{"input": "package augeas\n\n\n\nimport \"C\"\nimport (\n\t\"fmt\"\n)\n\n\n\n\ntype ErrorCode int\n\n\nconst (\n\tCouldNotInitialize ErrorCode = -2\n\tNoMatch = -1\n\n\tNoError = 0\n\n\tENOMEM\n\n\tEINTERNAL\n\n\tEPATHX\n\n\tENOMATCH\n\n\tEMMATCH\n\n\tESYNTAX\n\n\tENOLENS\n\n\tEMXFM\n\n\tENOSPAN\n\n\tEMVDESC\n\n\tECMDRUN\n\n\tEBADARG\n)\n\n\ntype Error struct {\n\tCode ErrorCode\n\n\tMessage string\n\n\tMinorMessage string\n\n\tDetails string\n}\n\nfunc (err Error) Error() string {\n\treturn fmt.Sprintf(\"Message: %s - Minor message: %s - Details: %s\",\n\t\terr.Message, err.MinorMessage, err.Details)\n}\n\nfunc (a Augeas) error() error {\n\tcode := a.errorCode()\n\tif code == NoError {\n\t\treturn nil\n\t}\n\n\treturn Error{code, a.errorMessage(), a.errorMinorMessage(), a.errorDetails()}\n}\n\nfunc (a Augeas) errorCode() ErrorCode {\n\treturn ErrorCode(C.aug_error(a.handle))\n}\n\nfunc (a Augeas) errorMessage() string {\n\treturn C.GoString(C.aug_error_message(a.handle))\n}\n\nfunc (a Augeas) errorMinorMessage() string {\n\treturn C.GoString(C.aug_error_minor_message(a.handle))\n}\n\n\n\nfunc (a Augeas) errorDetails() string ", "output": "{\n\treturn C.GoString(C.aug_error_details(a.handle))\n}"} {"input": "package circleci\n\nimport (\n\t\"log\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestRecentBuilds(t *testing.T) ", "output": "{\n\tc := setup()\n\n\tbuilds := c.RecentBuilds(\"ryanlower\", \"go-circleci\")\n\tlog.Print(builds)\n\n\tlastBuild := builds[0]\n\tassert.Equal(t, lastBuild.Branch, \"master\")\n\tassert.Equal(t, lastBuild.Status, \"running\")\n}"} {"input": "package names\n\nimport \"knative.dev/pkg/kmeta\"\n\n\nfunc Deployment(rev kmeta.Accessor) string {\n\treturn kmeta.ChildName(rev.GetName(), \"-deployment\")\n}\n\n\nfunc ImageCache(rev kmeta.Accessor) string {\n\treturn kmeta.ChildName(rev.GetName(), \"-cache\")\n}\n\n\n\n\nfunc PA(rev kmeta.Accessor) string ", "output": "{\n\treturn rev.GetName()\n}"} {"input": "package dataflow\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"go-common/app/interface/main/app-interface/conf\"\n\t\"go-common/library/log\"\n\t\"go-common/library/log/infoc\"\n)\n\n\ntype Service struct {\n\tc *conf.Config\n\tinfoc *infoc.Infoc\n}\n\n\nfunc New(c *conf.Config) (s *Service) {\n\ts = &Service{\n\t\tc: c,\n\t\tinfoc: infoc.New(c.Infoc),\n\t}\n\treturn\n}\n\n\n\nfunc (s *Service) Report(c context.Context, eventID, eventType, buvid, fts, messageInfo string, now time.Time) (err error) ", "output": "{\n\tif err = s.infoc.Info(strconv.FormatInt(now.Unix(), 10), eventID, eventType, buvid, fts, messageInfo); err != nil {\n\t\tlog.Error(\"s.infoc2.Info(%v,%v,%v,%v,%v,%v) error(%v)\", strconv.FormatInt(now.Unix(), 10), eventID, eventType, buvid, fts, messageInfo, err)\n\t}\n\treturn\n}"} {"input": "package http\n\nimport (\n\t\"net/url\"\n\t\"os\"\n\t\"testing\"\n)\n\n\n\n\nvar cacheKeysTests = []struct {\n\tproxy string\n\tscheme string\n\taddr string\n\tkey string\n}{\n\t{\"\", \"http\", \"foo.com\", \"|http|foo.com\"},\n\t{\"\", \"https\", \"foo.com\", \"|https|foo.com\"},\n\t{\"http://foo.com\", \"http\", \"foo.com\", \"http://foo.com|http|\"},\n\t{\"http://foo.com\", \"https\", \"foo.com\", \"http://foo.com|https|foo.com\"},\n}\n\n\n\nfunc ResetProxyEnv() {\n\tfor _, v := range []string{\"HTTP_PROXY\", \"http_proxy\", \"NO_PROXY\", \"no_proxy\", \"REQUEST_METHOD\"} {\n\t\tos.Unsetenv(v)\n\t}\n\tResetCachedEnvironment()\n}\n\nfunc TestCacheKeys(t *testing.T) ", "output": "{\n\tfor _, tt := range cacheKeysTests {\n\t\tvar proxy *url.URL\n\t\tif tt.proxy != \"\" {\n\t\t\tu, err := url.Parse(tt.proxy)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tproxy = u\n\t\t}\n\t\tcm := connectMethod{proxyURL: proxy, targetScheme: tt.scheme, targetAddr: tt.addr}\n\t\tif got := cm.key().String(); got != tt.key {\n\t\t\tt.Fatalf(\"{%q, %q, %q} cache key = %q; want %q\", tt.proxy, tt.scheme, tt.addr, got, tt.key)\n\t\t}\n\t}\n}"} {"input": "package future\n\nimport (\n\t\"time\"\n)\n\n\nconst FuelRechargeRate = float32(1.0 / 3.0) \n\n\n\n\n\nfunc CannonX(initial float32, rate float32, elap time.Duration) (float32, float32) {\n\tx := initial + rate*float32(elap)/float32(time.Second)\n\tswitch {\n\tcase x < 0:\n\t\tx = -x\n\t\trate = -rate\n\tcase x > 1:\n\t\tx = 2 - x\n\t\trate = -rate\n\t}\n\treturn x, rate\n}\n\n\nfunc MissileY(initial float32, rate float32, elap time.Duration) float32 {\n\ty := initial + rate*float32(elap)/float32(time.Second)\n\tif y > 1 {\n\t\ty = 1\n\t}\n\treturn y\n}\n\nfunc Fuel(initial float32, elap time.Duration) float32 ", "output": "{\n\tfuel := initial + FuelRechargeRate*float32(elap)/float32(time.Second)\n\tif fuel > 10 {\n\t\tfuel = 10\n\t}\n\treturn fuel\n}"} {"input": "package main\n\nvar x int\n\n\n\nfunc f() ", "output": "{\nL1: \n\tfor {\n\t}\nL2: \n\tselect {\n\t}\nL3: \n\tswitch {\n\t}\nL4: \n\tif true {\n\t}\nL5: \n\tf()\nL6: \n\tf()\nL6: \n\tf()\n\tif x == 20 {\n\t\tgoto L6\n\t}\n\nL7:\n\tfor {\n\t\tbreak L7\n\t}\n\nL8:\n\tfor {\n\t\tif x == 21 {\n\t\t\tcontinue L8\n\t\t}\n\t}\n\nL9:\n\tswitch {\n\tcase true:\n\t\tbreak L9\n\tdefalt: \n\t}\n\nL10:\n\tselect {\n\tdefault:\n\t\tbreak L10\n\t}\n}"} {"input": "package wca\n\nimport (\n\t\"unsafe\"\n)\n\n\n\n\ntype IAudioClient2 struct {\n\tIAudioClient\n}\n\ntype IAudioClient2Vtbl struct {\n\tIAudioClientVtbl\n\tIsOffloadCapable uintptr\n\tSetClientProperties uintptr\n\tGetBufferSizeLimits uintptr\n}\n\n\n\nfunc (v *IAudioClient2) IsOffloadCapable(category uint32, isOffloadCapable *bool) (err error) {\n\terr = ac2IsOffloadCapable(v, category, isOffloadCapable)\n\treturn\n}\n\nfunc (v *IAudioClient2) SetClientProperties(properties *AudioClientProperties) (err error) {\n\terr = ac2SetClientProperties(v, properties)\n\treturn\n}\n\nfunc (v *IAudioClient2) GetBufferSizeLimits(wfx *WAVEFORMATEX, isEventDriven bool, minBufferDuration, maxBufferDuration *uint32) (err error) {\n\terr = ac2GetBufferSizeLimits(v, wfx, isEventDriven, minBufferDuration, maxBufferDuration)\n\treturn\n}\n\nfunc (v *IAudioClient2) VTable() *IAudioClient2Vtbl ", "output": "{\n\treturn (*IAudioClient2Vtbl)(unsafe.Pointer(v.RawVTable))\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\tx := 1.5\n\tsquare(&x)\n\tfmt.Println(x)\n}\n\nfunc square(x *float64) ", "output": "{\n\t*x = *x * *x\n}"} {"input": "package jsoniter\n\nimport (\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\"\n)\n\nfunc Test_encode_optional_int_pointer(t *testing.T) {\n\tshould := require.New(t)\n\tvar ptr *int\n\tstr, err := MarshalToString(ptr)\n\tshould.Nil(err)\n\tshould.Equal(\"null\", str)\n\tval := 100\n\tptr = &val\n\tstr, err = MarshalToString(ptr)\n\tshould.Nil(err)\n\tshould.Equal(\"100\", str)\n}\n\n\n\nfunc Test_encode_struct_with_optional_field(t *testing.T) {\n\tshould := require.New(t)\n\ttype TestObject struct {\n\t\tField1 *string\n\t\tField2 *string\n\t}\n\tobj := TestObject{}\n\tworld := \"world\"\n\tobj.Field2 = &world\n\tstr, err := MarshalToString(obj)\n\tshould.Nil(err)\n\tshould.Contains(str, `\"Field1\":null`)\n\tshould.Contains(str, `\"Field2\":\"world\"`)\n}\n\nfunc Test_decode_struct_with_optional_field(t *testing.T) ", "output": "{\n\tshould := require.New(t)\n\ttype TestObject struct {\n\t\tField1 *string\n\t\tField2 *string\n\t}\n\tobj := TestObject{}\n\tUnmarshalFromString(`{\"field1\": null, \"field2\": \"world\"}`, &obj)\n\tshould.Nil(obj.Field1)\n\tshould.Equal(\"world\", *obj.Field2)\n}"} {"input": "package apm\n\nimport (\n\t\"fmt\"\n)\n\n\ntype KeyTransaction struct {\n\tID int `json:\"id,omitempty\"`\n\tName string `json:\"name,omitempty\"`\n\tTransactionName string `json:\"transaction_name,omitempty\"`\n\tHealthStatus string `json:\"health_status,omitempty\"`\n\tLastReportedAt string `json:\"last_reported_at,omitempty\"`\n\tReporting bool `json:\"reporting\"`\n\tSummary ApplicationSummary `json:\"application_summary,omitempty\"`\n\tEndUserSummary ApplicationEndUserSummary `json:\"end_user_summary,omitempty\"`\n\tLinks KeyTransactionLinks `json:\"links,omitempty\"`\n}\n\n\ntype KeyTransactionLinks struct {\n\tApplication int `json:\"application,omitempty\"`\n}\n\n\n\ntype ListKeyTransactionsParams struct {\n\tName string `url:\"filter[name],omitempty\"`\n\tIDs []int `url:\"filter[ids],omitempty,comma\"`\n}\n\n\n\n\n\nfunc (a *APM) GetKeyTransaction(id int) (*KeyTransaction, error) {\n\tresponse := keyTransactionResponse{}\n\turl := fmt.Sprintf(\"/key_transactions/%d.json\", id)\n\n\t_, err := a.client.Get(a.config.Region().RestURL(url), nil, &response)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &response.KeyTransaction, nil\n}\n\ntype keyTransactionsResponse struct {\n\tKeyTransactions []*KeyTransaction `json:\"key_transactions,omitempty\"`\n}\n\ntype keyTransactionResponse struct {\n\tKeyTransaction KeyTransaction `json:\"key_transaction,omitempty\"`\n}\n\nfunc (a *APM) ListKeyTransactions(params *ListKeyTransactionsParams) ([]*KeyTransaction, error) ", "output": "{\n\tresults := []*KeyTransaction{}\n\tnextURL := a.config.Region().RestURL(\"key_transactions.json\")\n\n\tfor nextURL != \"\" {\n\t\tresponse := keyTransactionsResponse{}\n\t\tresp, err := a.client.Get(nextURL, ¶ms, &response)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tresults = append(results, response.KeyTransactions...)\n\n\t\tpaging := a.pager.Parse(resp)\n\t\tnextURL = paging.Next\n\t}\n\n\treturn results, nil\n}"} {"input": "package main\n\nimport . \"g2d\"\n\nvar screen = Point{480, 360}\nvar size = Point{20, 20}\n\ntype Ball struct {\n x, y int\n dx, dy int\n}\n\nfunc NewBall(pos Point) *Ball {\n return &Ball{pos.X, pos.Y, 5, 5}\n}\n\nfunc (b *Ball) Move() {\n if !(0 <= b.x+b.dx && b.x+b.dx <= screen.X-size.X) {\n b.dx = -b.dx\n }\n if !(0 <= b.y+b.dy && b.y+b.dy <= screen.Y-size.Y) {\n b.dy = -b.dy\n }\n b.x += b.dx\n b.y += b.dy\n}\n\nfunc (b *Ball) Position() Point {\n return Point{b.x, b.y}\n}\n\n\nvar b1 = NewBall(Point{40, 80})\nvar b2 = NewBall(Point{80, 40})\n\n\n\nfunc tick() {\n ClearCanvas() \n b1.Move()\n b2.Move()\n DrawImage(\"ball.png\", b1.Position()) \n DrawImage(\"ball.png\", b2.Position()) \n}\n\nfunc main() {\n \n InitCanvas(screen)\n MainLoop(tick)\n}\n\nfunc mainConsole() ", "output": "{\n for i := 0; i < 25; i++ {\n Println(\"Ball 1 @\", b1.Position())\n Println(\"Ball 2 @\", b2.Position())\n b1.Move()\n b2.Move()\n }\n}"} {"input": "package middleware\n\nimport (\n\t\"github.com/drone/drone/shared/model\"\n\t\"github.com/zenazn/goji/web\"\n)\n\n\n\nfunc UserToC(c *web.C, user *model.User) {\n\tc.Env[\"user\"] = user\n}\n\n\n\nfunc RepoToC(c *web.C, repo *model.Repo) {\n\tc.Env[\"repo\"] = repo\n}\n\n\n\nfunc RoleToC(c *web.C, role *model.Perm) {\n\tc.Env[\"role\"] = role\n}\n\n\n\n\nfunc ToUser(c *web.C) *model.User {\n\tvar v = c.Env[\"user\"]\n\tif v == nil {\n\t\treturn nil\n\t}\n\tu, ok := v.(*model.User)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn u\n}\n\n\n\n\n\n\n\n\n\nfunc ToRole(c *web.C) *model.Perm {\n\tvar v = c.Env[\"role\"]\n\tif v == nil {\n\t\treturn nil\n\t}\n\tp, ok := v.(*model.Perm)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn p\n}\n\nfunc ToRepo(c *web.C) *model.Repo ", "output": "{\n\tvar v = c.Env[\"repo\"]\n\tif v == nil {\n\t\treturn nil\n\t}\n\tr, ok := v.(*model.Repo)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn r\n}"} {"input": "package elastic\n\n\n\n\ntype LimitFilter struct {\n Filter\n limit int\n}\n\n\n\nfunc (f LimitFilter) Source() interface{} {\n \n \n \n \n \n source := make(map[string]interface{})\n params := make(map[string]interface{})\n source[\"limit\"] = params\n params[\"value\"] = f.limit\n return source\n}\n\nfunc NewLimitFilter(limit int) LimitFilter ", "output": "{\n f := LimitFilter{limit: limit}\n return f\n}"} {"input": "package gospec\n\nimport (\n\t\"fmt\"\n\tfilepath \"path\"\n\t\"runtime\"\n)\n\ntype Location struct {\n\tname string\n\tfile string\n\tline int\n}\n\nfunc currentLocation() *Location {\n\treturn newLocation(1)\n}\n\nfunc callerLocation() *Location {\n\treturn newLocation(2)\n}\n\nfunc newLocation(n int) *Location {\n\tif pc, _, _, ok := runtime.Caller(n + 1); ok {\n\t\treturn locationForPC(pc)\n\t}\n\treturn nil\n}\n\nfunc locationForPC(pc uintptr) *Location {\n\tpc = pcOfWhereCallWasMade(pc)\n\tf := runtime.FuncForPC(pc)\n\tname := f.Name()\n\tfile, line := f.FileLine(pc)\n\treturn &Location{name, file, line}\n}\n\n\n\n\n\n\n\n\nfunc pcOfWhereCallWasMade(pcOfWhereCallReturnsTo uintptr) uintptr {\n\treturn pcOfWhereCallReturnsTo - 1\n}\n\nfunc (this *Location) Name() string { return this.name }\nfunc (this *Location) File() string { return this.file }\nfunc (this *Location) FileName() string { return filename(this.file) }\nfunc (this *Location) Line() int { return this.line }\n\nfunc filename(path string) string {\n\t_, file := filepath.Split(path)\n\treturn file\n}\n\n\n\nfunc (this *Location) String() string {\n\treturn fmt.Sprintf(\"%v:%v\", this.FileName(), this.Line())\n}\n\nfunc (this *Location) equals(that *Location) bool ", "output": "{\n\treturn this.name == that.name &&\n\t\tthis.file == that.file &&\n\t\tthis.line == that.line\n}"} {"input": "package sliceset\n\nimport (\n\t\"sort\"\n\n\t\"github.com/xtgo/set\"\n)\n\ntype Set []int\n\nfunc (s Set) Len() int { return len(s) }\nfunc (s Set) Less(i, j int) bool { return s[i] < s[j] }\nfunc (s Set) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s Set) Copy() Set { return append(Set(nil), s...) }\n\nfunc (s Set) Union(t Set) Set { return s.Do(set.Union, t) }\nfunc (s Set) Inter(t Set) Set { return s.Do(set.Inter, t) }\nfunc (s Set) Diff(t Set) Set { return s.Do(set.Diff, t) }\nfunc (s Set) SymDiff(t Set) Set { return s.Do(set.SymDiff, t) }\nfunc (s Set) IsSub(t Set) bool { return s.DoBool(set.IsSub, t) }\nfunc (s Set) IsSuper(t Set) bool { return s.DoBool(set.IsSuper, t) }\n\nfunc (s Set) IsEqual(t Set) bool { return s.DoBool(set.IsEqual, t) }\n\nfunc (s Set) Uniq() Set {\n\tn := set.Uniq(s)\n\treturn s[:n]\n}\n\nfunc (s Set) Do(op set.Op, t Set) Set {\n\tdata := append(s, t...)\n\tn := op(data, len(s))\n\treturn data[:n]\n}\n\ntype BoolOp func(sort.Interface, int) bool\n\nfunc (s Set) DoBool(op BoolOp, t Set) bool {\n\tdata := append(s, t...)\n\treturn op(data, len(s))\n}\n\nfunc (s Set) IsInter(t Set) bool ", "output": "{ return s.DoBool(set.IsInter, t) }"} {"input": "package containers\n\nimport (\n\t\"github.com/nanobox-io/golang-docker-client\"\n\n\t\"github.com/nanobox-io/nanobox/util/dhcp\"\n)\n\n\nfunc BridgeConfig() docker.ContainerConfig {\n\treturn docker.ContainerConfig{\n\t\tName: BridgeName(),\n\t\tImage: \"nanobox/bridge\",\n\t\tNetwork: \"virt\",\n\t\tIP: reserveIP(),\n\t\tRestartPolicy: \"always\",\n\t\tPorts: []string{\"1194:1194/udp\"},\n\t}\n}\n\n\n\n\n\nfunc reserveIP() string {\n\tip, _ := dhcp.ReserveLocal()\n\treturn ip.String()\n}\n\nfunc BridgeName() string ", "output": "{\n\treturn \"nanobox_bridge\"\n}"} {"input": "package redis\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\n\t\"github.com/iris-framework/iris/adaptors/sessions/sessiondb/redis/service\"\n)\n\n\ntype Database struct {\n\tredis *service.Service\n}\n\n\nfunc New(cfg ...service.Config) *Database {\n\treturn &Database{redis: service.New(cfg...)}\n}\n\n\nfunc (d *Database) Config() *service.Config {\n\treturn d.redis.Config\n}\n\n\nfunc (d *Database) Load(sid string) map[string]interface{} {\n\tvalues := make(map[string]interface{})\n\n\tif !d.redis.Connected { \n\t\td.redis.Connect()\n\t\t_, err := d.redis.PingPong()\n\t\tif err != nil {\n\t\t\tif err != nil {\n\t\t\t}\n\t\t}\n\t}\n\tval, err := d.redis.GetBytes(sid)\n\tif err == nil {\n\t\tDeserializeBytes(val, &values)\n\t}\n\n\treturn values\n\n}\n\n\nfunc serialize(values map[string]interface{}) []byte {\n\tval, err := SerializeBytes(values)\n\tif err != nil {\n\t\tprintln(\"On redisstore.serialize: \" + err.Error())\n\t}\n\n\treturn val\n}\n\n\n\n\n\nfunc SerializeBytes(m interface{}) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tenc := gob.NewEncoder(buf)\n\terr := enc.Encode(m)\n\tif err == nil {\n\t\treturn buf.Bytes(), nil\n\t}\n\treturn nil, err\n}\n\n\nfunc DeserializeBytes(b []byte, m interface{}) error {\n\tdec := gob.NewDecoder(bytes.NewBuffer(b))\n\treturn dec.Decode(m) \n}\n\nfunc (d *Database) Update(sid string, newValues map[string]interface{}) ", "output": "{\n\tif len(newValues) == 0 {\n\t\tgo d.redis.Delete(sid)\n\t} else {\n\t\tgo d.redis.Set(sid, serialize(newValues)) \n\t}\n\n}"} {"input": "package jms\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype UpdateFleetAgentConfigurationRequest struct {\n\n\tFleetId *string `mandatory:\"true\" contributesTo:\"path\" name:\"fleetId\"`\n\n\tUpdateFleetAgentConfigurationDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateFleetAgentConfigurationRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request UpdateFleetAgentConfigurationRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request UpdateFleetAgentConfigurationRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request UpdateFleetAgentConfigurationRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateFleetAgentConfigurationResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response UpdateFleetAgentConfigurationResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response UpdateFleetAgentConfigurationResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package main\n\nimport \"fmt\"\n\nvar c chan int\n\n\n\nfunc main() {\n\tc := make(chan int)\n\tquit := make(chan bool)\n\tgo count(c, quit)\n\tfor i := 0; i < 10; i++ {\n\t\tc <- i\n\n\t}\n\tquit <- false \n}\n\nfunc count(c chan int, quit chan bool) ", "output": "{\n\tfor {\n\t\tselect {\n\t\tcase i := <-c:\n\t\t\tfmt.Println(i)\n\t\tcase <-quit:\n\t\t\tbreak\n\t\t}\n\t}\n}"} {"input": "package geom\n\nimport \"math\"\n\n\ntype Vertex struct {\n\tX, Y float64\n}\n\n\ntype Vertices []Vertex\n\n\nfunc (l Vertices) Convert() (data []float32) {\n\n\tdata = make([]float32, len(l)*2)\n\tfor i, v := range l {\n\t\tindex := i * 2\n\t\tdata[index] = float32(v.X)\n\t\tdata[index+1] = float32(v.Y)\n\t}\n\treturn\n}\n\n\nfunc (c Vertex) SideOfLine(a Vertex, b Vertex) int {\n\n\tcross := float64((b.X-a.X)*(c.Y-a.Y) - (b.Y-a.Y)*(c.X-a.X))\n\n\tif cross == 0 {\n\t\treturn 0\n\t}\n\tif math.Signbit(cross) {\n\t\treturn 1\n\t}\n\treturn -1\n\n}\n\n\ntype Lexographically []Vertex\n\nfunc (a Lexographically) Len() int { return len(a) }\n\nfunc (a Lexographically) Less(i, j int) bool {\n\tif a[i].X == a[j].X {\n\t\treturn a[i].Y < a[j].Y\n\t}\n\treturn a[i].X < a[j].X\n}\n\nfunc (a Lexographically) Swap(i, j int) ", "output": "{ a[i], a[j] = a[j], a[i] }"} {"input": "package tango\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\nfunc TestDir1(t *testing.T) {\n\tbuff := bytes.NewBufferString(\"\")\n\trecorder := httptest.NewRecorder()\n\trecorder.Body = buff\n\n\ttg := New()\n\ttg.Get(\"/:name\", Dir(\"./public\"))\n\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:8000/test.html\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\ttg.ServeHTTP(recorder, req)\n\texpect(t, recorder.Code, http.StatusOK)\n\trefute(t, len(buff.String()), 0)\n\texpect(t, buff.String(), \"hello tango\")\n}\n\nfunc TestDir2(t *testing.T) {\n\tbuff := bytes.NewBufferString(\"\")\n\trecorder := httptest.NewRecorder()\n\trecorder.Body = buff\n\n\ttg := New()\n\ttg.Get(\"/\", Dir(\"./public\"))\n\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:8000/\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\ttg.ServeHTTP(recorder, req)\n\texpect(t, recorder.Code, http.StatusNotFound)\n\trefute(t, len(buff.String()), 0)\n\texpect(t, buff.String(), http.StatusText(http.StatusNotFound))\n}\n\n\n\nfunc TestFile1(t *testing.T) ", "output": "{\n\tbuff := bytes.NewBufferString(\"\")\n\trecorder := httptest.NewRecorder()\n\trecorder.Body = buff\n\n\ttg := New()\n\ttg.Get(\"/test.html\", File(\"./public/test.html\"))\n\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:8000/test.html\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\ttg.ServeHTTP(recorder, req)\n\texpect(t, recorder.Code, http.StatusOK)\n\trefute(t, len(buff.String()), 0)\n\texpect(t, buff.String(), \"hello tango\")\n}"} {"input": "package addrs\n\nimport \"fmt\"\n\n\n\n\n\n\n\n\n\n\n\ntype ResourceInstancePhase struct {\n\treferenceable\n\tResourceInstance ResourceInstance\n\tPhase ResourceInstancePhaseType\n}\n\nvar _ Referenceable = ResourceInstancePhase{}\n\n\n\n\nfunc (r ResourceInstance) Phase(rpt ResourceInstancePhaseType) ResourceInstancePhase {\n\treturn ResourceInstancePhase{\n\t\tResourceInstance: r,\n\t\tPhase: rpt,\n\t}\n}\n\n\n\nfunc (rp ResourceInstancePhase) ContainingResource() ResourcePhase {\n\treturn rp.ResourceInstance.Resource.Phase(rp.Phase)\n}\n\nfunc (rp ResourceInstancePhase) String() string {\n\treturn fmt.Sprintf(\"%s#%s\", rp.ResourceInstance, rp.Phase)\n}\n\n\ntype ResourceInstancePhaseType string\n\nconst (\n\tResourceInstancePhaseDestroy ResourceInstancePhaseType = \"destroy\"\n\n\tResourceInstancePhaseDestroyCBD ResourceInstancePhaseType = \"destroy-cbd\"\n)\n\nfunc (rpt ResourceInstancePhaseType) String() string {\n\treturn string(rpt)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype ResourcePhase struct {\n\treferenceable\n\tResource Resource\n\tPhase ResourceInstancePhaseType\n}\n\nvar _ Referenceable = ResourcePhase{}\n\n\n\n\nfunc (r Resource) Phase(rpt ResourceInstancePhaseType) ResourcePhase {\n\treturn ResourcePhase{\n\t\tResource: r,\n\t\tPhase: rpt,\n\t}\n}\n\n\n\nfunc (rp ResourcePhase) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%s#%s\", rp.Resource, rp.Phase)\n}"} {"input": "package cover\n\nimport (\n\t\"flag\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc ParseAndStripTestFlags() {\n\tflag.Parse()\n\n\tvar runtimeArgs []string\n\tfor _, arg := range os.Args {\n\t\tif strings.HasPrefix(arg, \"-test.\") ||\n\t\t\tstrings.HasPrefix(arg, \"-httptest.\") {\n\t\t\tcontinue\n\t\t}\n\t\truntimeArgs = append(runtimeArgs, arg)\n\t}\n\tos.Args = runtimeArgs\n}\n\ntype dummyTestDeps func(pat, str string) (bool, error)\n\nfunc (d dummyTestDeps) MatchString(pat, str string) (bool, error) { return false, nil }\nfunc (d dummyTestDeps) StartCPUProfile(io.Writer) error { return nil }\nfunc (d dummyTestDeps) StopCPUProfile() {}\nfunc (f dummyTestDeps) StartTestLog(w io.Writer) {}\nfunc (f dummyTestDeps) StopTestLog() error { return nil }\n\nfunc (d dummyTestDeps) WriteProfileTo(string, io.Writer, int) error { return nil }\nfunc (f dummyTestDeps) ImportPath() string { return \"\" }\n\n\n\n\n\nfunc FlushProfiles() {\n\toldstdout := os.Stdout\n\toldstderr := os.Stderr\n\tos.Stdout, _ = os.Open(os.DevNull)\n\tos.Stderr, _ = os.Open(os.DevNull)\n\n\ttests := []testing.InternalTest{}\n\tbenchmarks := []testing.InternalBenchmark{}\n\texamples := []testing.InternalExample{}\n\tvar f dummyTestDeps\n\tdummyM := testing.MainStart(f, tests, benchmarks, examples)\n\tdummyM.Run()\n\n\tos.Stdout = oldstdout\n\tos.Stderr = oldstderr\n}\n\nfunc (d dummyTestDeps) WriteHeapProfile(io.Writer) error ", "output": "{ return nil }"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\ntype SystemSettings struct {\n\tuserStreamAcl *StreamAcl\n\tsystemStreamAcl *StreamAcl\n}\n\nfunc NewSystemSettings(\n\tuserStreamAcl *StreamAcl,\n\tsystemStreamAcl *StreamAcl,\n) *SystemSettings {\n\treturn &SystemSettings{userStreamAcl, systemStreamAcl}\n}\n\nfunc (s *SystemSettings) UserStreamAcl() *StreamAcl { return s.userStreamAcl }\n\nfunc (s *SystemSettings) SystemStreamAcl() *StreamAcl { return s.systemStreamAcl }\n\n\n\ntype systemSettingsJson struct {\n\tUserStreamAcl *StreamAcl `json:\"$userStreamAcl,omitempty\"`\n\tSystemStreamAcl *StreamAcl `json:\"$systemStreamAcl,omitempty\"`\n}\n\nfunc (s *SystemSettings) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(systemSettingsJson{\n\t\tUserStreamAcl: s.userStreamAcl,\n\t\tSystemStreamAcl: s.systemStreamAcl,\n\t})\n}\n\nfunc (s *SystemSettings) UnmarshalJSON(data []byte) error {\n\tss := systemSettingsJson{}\n\tif err := json.Unmarshal(data, &ss); err != nil {\n\t\treturn err\n\t}\n\ts.userStreamAcl = ss.UserStreamAcl\n\ts.systemStreamAcl = ss.SystemStreamAcl\n\treturn nil\n}\n\nfunc SystemSettingsFromJsonBytes(data []byte) (*SystemSettings, error) {\n\tsystemSettings := &SystemSettings{}\n\treturn systemSettings, json.Unmarshal(data, systemSettings)\n}\n\nfunc (s *SystemSettings) String() string ", "output": "{\n\treturn fmt.Sprintf(\"&{userStreamAcl:%+v systemStreamAcl:%+v}\", s.userStreamAcl, s.systemStreamAcl)\n}"} {"input": "package service\n\nimport (\n\tlog \"github.com/golang/glog\"\n\t\"k8s.io/kubernetes/contrib/mesos/pkg/podutil\"\n\t\"k8s.io/kubernetes/contrib/mesos/pkg/scheduler/resources\"\n\t\"k8s.io/kubernetes/pkg/api\"\n)\n\n\n\n\nfunc StaticPodValidator(\n\tdefaultContainerCPULimit resources.CPUShares,\n\tdefaultContainerMemLimit resources.MegaBytes,\n\taccumCPU, accumMem *float64,\n) podutil.FilterFunc ", "output": "{\n\treturn podutil.FilterFunc(func(pod *api.Pod) (bool, error) {\n\t\t_, cpu, _, err := resources.LimitPodCPU(pod, defaultContainerCPULimit)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\t_, mem, _, err := resources.LimitPodMem(pod, defaultContainerMemLimit)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tlog.V(2).Infof(\"reserving %.2f cpu shares and %.2f MB of memory to static pod %s/%s\", cpu, mem, pod.Namespace, pod.Name)\n\n\t\t*accumCPU += float64(cpu)\n\t\t*accumMem += float64(mem)\n\t\treturn true, nil\n\t})\n}"} {"input": "package store\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"text/tabwriter\"\n\t\"time\"\n)\n\ntype Metadata map[string]string\n\ntype Entry struct {\n\tName string `json:\"name\"`\n\tPassword []byte `json:\"password\"`\n\tCtime time.Time `json:\"ctime\"` \n\tMtime time.Time `json:\"mtime\"` \n\tMetadata Metadata `json:\"metadata\"` \n}\n\nfunc NewEntry() *Entry {\n\treturn &Entry{\n\t\tMetadata: make(Metadata),\n\t\tCtime: getCurrentTime(),\n\t\tMtime: getCurrentTime(),\n\t}\n}\n\nfunc (e *Entry) Age() time.Duration {\n\treturn time.Since(e.Mtime)\n}\n\nfunc (e *Entry) Touch() {\n\te.Mtime = getCurrentTime()\n}\n\nfunc (e Entry) String() string {\n\tb := new(bytes.Buffer)\n\tw := tabwriter.NewWriter(b, 0, 0, 0, ' ', 0)\n\n\tvalof := reflect.ValueOf(e)\n\tfor i := 0; i < valof.NumField(); i++ {\n\t\tswitch val := valof.Field(i).Interface().(type) {\n\t\tdefault:\n\t\t\ttag := valof.Type().Field(i).Tag.Get(\"json\")\n\t\t\tfmt.Fprintf(w, \"%s\\t : %s\\n\", tag, val)\n\t\tcase Metadata:\n\t\t\tfor k, v := range val {\n\t\t\t\tfmt.Fprintf(w, \"%s\\t : %s\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\n\tw.Flush()\n\treturn b.String()\n}\n\n\n\nfunc getCurrentTime() time.Time {\n\treturn time.Now().Truncate(time.Second)\n}\n\nfunc (m Metadata) String() string ", "output": "{\n\tvar b bytes.Buffer\n\tfor k, v := range m {\n\t\tfmt.Fprintf(&b, \"%s:%s\", k, v)\n\t}\n\treturn b.String()\n}"} {"input": "package leet_25\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\ntype dequeue struct {\n\tbuff []*ListNode\n}\n\nfunc (q *dequeue) lpop() *ListNode {\n\tif 0 == len(q.buff) {\n\t\treturn nil\n\t}\n\tp := q.buff[0]\n\tq.buff = q.buff[1:]\n\treturn p\n}\n\nfunc (q *dequeue) rpop() *ListNode {\n\tif 0 == len(q.buff) {\n\t\treturn nil\n\t}\n\tlast := len(q.buff) - 1\n\tp := q.buff[last]\n\tq.buff = q.buff[:last]\n\treturn p\n}\n\nfunc (q *dequeue) rpush(p *ListNode) {\n\tq.buff = append(q.buff, p)\n}\n\n\n\nvar buff []*ListNode\n\nfunc reverseKGroup(head *ListNode, k int) *ListNode {\n\tif head == nil {\n\t\treturn nil\n\t}\n\tif k <= 1 {\n\t\treturn head\n\t}\n\tbuff = make([]*ListNode, 0, k)\n\tqueue := &dequeue{buff: buff}\n\tcount := 0\n\tcur := head\n\tfor cur != nil {\n\t\tcount++\n\t\tqueue.rpush(cur)\n\t\tif count == k {\n\t\t\tcount = 0\n\t\t\tfor {\n\t\t\t\tl := queue.lpop()\n\t\t\t\tr := queue.rpop()\n\t\t\t\tif l == nil || r == nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tl.Val, r.Val = r.Val, l.Val\n\t\t\t}\n\t\t\tqueue.clear()\n\t\t}\n\t\tcur = cur.Next\n\t}\n\treturn head\n}\n\nfunc (q *dequeue) clear() ", "output": "{\n\tq.buff = buff[:0]\n}"} {"input": "package history\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/avatar29A/microchat/history/model\"\n\t\"github.com/avatar29A/microchat/server/protocols\"\n\t\"github.com/avatar29A/microchat/utils\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n)\n\nimport \"github.com/satori/go.uuid\"\n\n\ntype MessagesContext struct {\n\tctx *DBContext\n}\n\n\nfunc NewMessagesContext(context *DBContext) *MessagesContext {\n\tc := &MessagesContext{context}\n\n\treturn c\n}\n\n\nfunc (c *MessagesContext) GetLastNMessages(n int) []*protocols.UserSay {\n\tquery := fmt.Sprintf(\"ORDER BY created_at DESC LIMIT %s\", c.ctx.DB.Placeholder(0))\n\n\trows, err := c.ctx.DB.SelectAllFrom(model.MessageTable, query, n)\n\tmessages := make([]*protocols.UserSay, 0, len(rows))\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn messages\n\t}\n\n\tfor _, row := range rows {\n\t\tmessage := row.(*model.Message)\n\t\tmessages = append(messages, &protocols.UserSay{\n\t\t\tUsername: message.UserName,\n\t\t\tMessage: message.Message,\n\t\t\tCreatedAt: utils.MakeTimeStampFromTime(message.CreatedAt),\n\t\t})\n\t}\n\n\treturn messages\n}\n\n\n\n\nfunc (c *MessagesContext) getDefaultChannel() *model.Channel {\n\tentity, err := c.ctx.DB.FindOneFrom(model.ChannelTable, \"name\", \"default\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn entity.(*model.Channel)\n}\n\nfunc (c *MessagesContext) SaveMessage(message *protocols.UserSay) error ", "output": "{\n\tchannel := c.getDefaultChannel()\n\n\tentity := &model.Message{\n\t\tID: string(uuid.NewV4().Bytes()),\n\t\tUserName: message.Username,\n\t\tChannelID: channel.ID,\n\t\tMessage: message.Message,\n\t\tCreatedAt: utils.MakeTimeFromTimestamp(message.CreatedAt),\n\t}\n\n\treturn c.ctx.DB.Save(entity)\n}"} {"input": "package migrator\n\nimport (\n\t\"github.com/cgrates/cgrates/engine\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc (m *Migrator) migrateCurrentTPactionplans() (err error) {\n\ttpids, err := m.storDBIn.StorDB().GetTpIds(utils.TBLTPActionPlans)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, tpid := range tpids {\n\t\tids, err := m.storDBIn.StorDB().GetTpTableIds(tpid, utils.TBLTPActionPlans,\n\t\t\tutils.TPDistinctIds{\"tag\"}, map[string]string{}, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, id := range ids {\n\t\t\tactPln, err := m.storDBIn.StorDB().GetTPActionPlans(tpid, id)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif actPln != nil {\n\t\t\t\tif m.dryRun != true {\n\t\t\t\t\tif err := m.storDBOut.StorDB().SetTPActionPlans(actPln); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tfor _, act := range actPln {\n\t\t\t\t\t\tif err := m.storDBIn.StorDB().RemTpData(utils.TBLTPActionPlans,\n\t\t\t\t\t\t\tact.TPid, map[string]string{\"tag\": act.ID}); err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tm.stats[utils.TpActionPlans]++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\n\n\nfunc (m *Migrator) migrateTPactionplans() (err error) ", "output": "{\n\tvar vrs engine.Versions\n\tcurrent := engine.CurrentStorDBVersions()\n\tif vrs, err = m.getVersions(utils.TpActionPlans); err != nil {\n\t\treturn\n\t}\n\tswitch vrs[utils.TpActionPlans] {\n\tcase current[utils.TpActionPlans]:\n\t\tif m.sameStorDB {\n\t\t\tbreak\n\t\t}\n\t\tif err := m.migrateCurrentTPactionplans(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn m.ensureIndexesStorDB(utils.TBLTPActionPlans)\n}"} {"input": "package sa\n\nimport (\n\t\"fmt\"\n\n\t\"gopkg.in/go-gorp/gorp.v2\"\n)\n\n\n\ntype RollbackError struct {\n\tErr error\n\tRollbackErr error\n}\n\n\n\n\n\n\n\nfunc Rollback(tx *gorp.Transaction, err error) error {\n\tif txErr := tx.Rollback(); txErr != nil {\n\t\treturn &RollbackError{\n\t\t\tErr: err,\n\t\t\tRollbackErr: txErr,\n\t\t}\n\t}\n\treturn err\n}\n\nfunc (re *RollbackError) Error() string ", "output": "{\n\tif re.RollbackErr == nil {\n\t\treturn re.Err.Error()\n\t}\n\treturn fmt.Sprintf(\"%s (also, while rolling back: %s)\", re.Err, re.RollbackErr)\n}"} {"input": "package dao\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc TestDaoassetRelationKey(t *testing.T) {\n\tconvey.Convey(\"assetRelationKey\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tmid = int64(0)\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\tp1 := assetRelationKey(mid)\n\t\t\tctx.Convey(\"Then p1 should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(p1, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}\n\n\n\nfunc TestDaoDelCacheAssetRelationState(t *testing.T) {\n\tconvey.Convey(\"DelCacheAssetRelationState\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t\toid = int64(0)\n\t\t\totype = \"\"\n\t\t\tmid = int64(0)\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\terr := d.DelCacheAssetRelationState(c, oid, otype, mid)\n\t\t\tctx.Convey(\"Then err should be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestDaoassetRelationField(t *testing.T) ", "output": "{\n\tconvey.Convey(\"assetRelationField\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\toid = int64(0)\n\t\t\totype = \"\"\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\tp1 := assetRelationField(oid, otype)\n\t\t\tctx.Convey(\"Then p1 should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(p1, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package sqltrace\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\nfunc boolToInt64(f bool) int64 {\n\tif f {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\ntype sqlTrace struct {\n\ton int64 \n\n\t*log.Logger\n}\n\nfunc newSQLTrace() *sqlTrace {\n\treturn &sqlTrace{\n\t\tLogger: log.New(os.Stdout, \"hdb \", log.Ldate|log.Ltime|log.Lshortfile),\n\t}\n}\n\nfunc (t *sqlTrace) SetOn(on bool) { atomic.StoreInt64(&t.on, boolToInt64(on)) }\n\ntype flagValue struct {\n\tt *sqlTrace\n}\n\nfunc (v flagValue) IsBoolFlag() bool { return true }\n\nfunc (v flagValue) String() string {\n\tif v.t == nil {\n\t\treturn \"\"\n\t}\n\treturn strconv.FormatBool(v.t.On())\n}\n\nfunc (v flagValue) Set(s string) error {\n\tf, err := strconv.ParseBool(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.t.SetOn(f)\n\treturn nil\n}\n\nvar tracer = newSQLTrace()\n\nfunc init() {\n\tflag.Var(&flagValue{t: tracer}, \"hdb.sqlTrace\", \"enabling hdb sql trace\")\n}\n\n\nfunc On() bool { return tracer.On() }\n\n\nfunc SetOn(on bool) { tracer.SetOn(on) }\n\n\nfunc Trace(v ...interface{}) { tracer.Print(v...) }\n\n\nfunc Tracef(format string, v ...interface{}) { tracer.Printf(format, v...) }\n\n\nfunc Traceln(v ...interface{}) { tracer.Println(v...) }\n\nfunc (t *sqlTrace) On() bool ", "output": "{ return atomic.LoadInt64(&t.on) != 0 }"} {"input": "package example1\n\nimport (\n\t\"fmt\"\n)\n\ntype Runner interface {\n\tRun(string) (string, error)\n}\n\ntype Gopher struct {\n\tname string\n\tage int\n}\n\n\n\nfunc (g Gopher) Run(desc string) (string, error) ", "output": "{\n\treturn fmt.Sprintf(\"I am %s and I run for %s\", g.name, desc), nil\n}"} {"input": "package league\n\ntype Division struct {\n\tname string\n\tteams map[string]*Team\n\tconfrence *Conference\n\tleague *League\n}\n\n\n\nfunc (division *Division) GetName() string {\n\treturn division.name\n}\n\nfunc (division *Division) GetConference() *Conference {\n\treturn division.confrence\n}\n\nfunc (division *Division) getLeague() *League {\n\treturn division.league\n}\n\nfunc (division *Division) GetTeams() map[string]*Team ", "output": "{\n\treturn division.teams\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\n\t\"github.com/rjeczalik/which\"\n)\n\nfunc die(v interface{}) {\n\tfmt.Fprintln(os.Stderr, v)\n\tos.Exit(1)\n}\n\nconst usage = `NAME:\n\tgowhich - shows the import path of Go executables\n\nUSAGE:\n\tgowhich name|path\n\nEXAMPLES:\n\tgowhich godoc\n\tgowhich ~/bin/godoc`\n\n\n\nfunc main() {\n\tif len(os.Args) != 2 {\n\t\tdie(usage)\n\t}\n\tif ishelp(os.Args[1]) {\n\t\tfmt.Println(usage)\n\t\treturn\n\t}\n\tpath, err := exec.LookPath(os.Args[1])\n\tif err != nil {\n\t\tdie(err)\n\t}\n\tpkg, err := which.Import(path)\n\tif err != nil {\n\t\tdie(err)\n\t}\n\tfmt.Println(pkg)\n}\n\nfunc ishelp(s string) bool ", "output": "{\n\treturn s == \"-h\" || s == \"-help\" || s == \"help\" || s == \"--help\" || s == \"/?\"\n}"} {"input": "package cachestore\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\ntype CacheStore struct {\n\tstores map[string]*KVStore\n\tmutex sync.RWMutex\n}\n\n\n\nfunc (c *CacheStore) GetStore(svcName string) *KVStore {\n\tc.mutex.RLock()\n\tkvstore := c.stores[svcName]\n\tc.mutex.RUnlock()\n\n\treturn kvstore\n}\n\n\n\nfunc (c *CacheStore) CreateStore(svcName string) *KVStore {\n\tkvstore := NewKVStore()\n\tc.mutex.Lock()\n\tc.stores[svcName] = kvstore\n\tc.mutex.Unlock()\n\n\treturn kvstore\n}\n\n\nfunc (c *CacheStore) DeleteStore(svcName string) {\n\tc.mutex.Lock()\n\tdelete(c.stores, svcName)\n\tc.mutex.Unlock()\n}\n\n\n\n\n\n\nfunc (c *CacheStore) GetCache(svcName string, key string) interface{} {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore == nil {\n\t\treturn nil\n\t}\n\treturn svcStore.Get(key)\n}\n\n\nfunc (c *CacheStore) DeleteCache(svcName string, key string) {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore != nil {\n\t\tsvcStore.Delete(key)\n\t}\n}\n\n\nfunc (c *CacheStore) MarshalJSON() ([]byte, error) {\n\tc.mutex.RLock()\n\tbytes, err := json.Marshal(&c.stores)\n\tc.mutex.RUnlock()\n\treturn bytes, err\n}\n\n\nfunc NewCacheStore() *CacheStore {\n\treturn &CacheStore{map[string]*KVStore{}, sync.RWMutex{}}\n}\n\nfunc (c *CacheStore) SetCache(svcName string, key string, value interface{}) ", "output": "{\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore == nil {\n\t\tsvcStore = c.CreateStore(svcName)\n\t}\n\n\tsvcStore.Set(key, value)\n}"} {"input": "package agent\n\nimport (\n\t\"github.com/hashicorp/consul/consul/structs\"\n\t\"net/http\"\n\t\"sort\"\n)\n\n\n\nfunc coordinateDisabled(resp http.ResponseWriter, req *http.Request) (interface{}, error) {\n\tresp.WriteHeader(401)\n\tresp.Write([]byte(\"Coordinate support disabled\"))\n\treturn nil, nil\n}\n\n\n\ntype sorter struct {\n\tcoordinates structs.Coordinates\n}\n\n\nfunc (s *sorter) Len() int {\n\treturn len(s.coordinates)\n}\n\n\nfunc (s *sorter) Swap(i, j int) {\n\ts.coordinates[i], s.coordinates[j] = s.coordinates[j], s.coordinates[i]\n}\n\n\nfunc (s *sorter) Less(i, j int) bool {\n\treturn s.coordinates[i].Node < s.coordinates[j].Node\n}\n\n\n\nfunc (s *HTTPServer) CoordinateDatacenters(resp http.ResponseWriter, req *http.Request) (interface{}, error) {\n\tvar out []structs.DatacenterMap\n\tif err := s.agent.RPC(\"Coordinate.ListDatacenters\", struct{}{}, &out); err != nil {\n\t\tfor i := range out {\n\t\t\tsort.Sort(&sorter{out[i].Coordinates})\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tfor i, _ := range out {\n\t\tif out[i].Coordinates == nil {\n\t\t\tout[i].Coordinates = make(structs.Coordinates, 0)\n\t\t}\n\t}\n\tif out == nil {\n\t\tout = make([]structs.DatacenterMap, 0)\n\t}\n\treturn out, nil\n}\n\n\n\n\n\nfunc (s *HTTPServer) CoordinateNodes(resp http.ResponseWriter, req *http.Request) (interface{}, error) ", "output": "{\n\targs := structs.DCSpecificRequest{}\n\tif done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {\n\t\treturn nil, nil\n\t}\n\n\tvar out structs.IndexedCoordinates\n\tdefer setMeta(resp, &out.QueryMeta)\n\tif err := s.agent.RPC(\"Coordinate.ListNodes\", &args, &out); err != nil {\n\t\tsort.Sort(&sorter{out.Coordinates})\n\t\treturn nil, err\n\t}\n\n\tif out.Coordinates == nil {\n\t\tout.Coordinates = make(structs.Coordinates, 0)\n\t}\n\treturn out.Coordinates, nil\n}"} {"input": "package channelling\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"log\"\n\n\t\"github.com/strukturag/spreed-webrtc/go/buffercache\"\n)\n\ntype IncomingDecoder interface {\n\tDecodeIncoming(buffercache.Buffer) (*DataIncoming, error)\n}\n\ntype OutgoingEncoder interface {\n\tEncodeOutgoing(*DataOutgoing) (buffercache.Buffer, error)\n}\n\ntype Codec interface {\n\tNewBuffer() buffercache.Buffer\n\tIncomingDecoder\n\tOutgoingEncoder\n}\n\ntype incomingCodec struct {\n\tbuffers buffercache.BufferCache\n\tincomingLimit int\n}\n\nfunc NewCodec(incomingLimit int) Codec {\n\treturn &incomingCodec{buffercache.NewBufferCache(1024, bytes.MinRead), incomingLimit}\n}\n\n\n\nfunc (codec incomingCodec) DecodeIncoming(b buffercache.Buffer) (*DataIncoming, error) {\n\tlength := b.GetBuffer().Len()\n\tif length > codec.incomingLimit {\n\t\treturn nil, errors.New(\"Incoming message size limit exceeded\")\n\t}\n\tincoming := &DataIncoming{}\n\treturn incoming, json.Unmarshal(b.Bytes(), incoming)\n}\n\nfunc (codec incomingCodec) EncodeOutgoing(outgoing *DataOutgoing) (buffercache.Buffer, error) {\n\tb := codec.NewBuffer()\n\tif err := json.NewEncoder(b).Encode(outgoing); err != nil {\n\t\tlog.Println(\"Error while encoding JSON\", err)\n\t\tb.Decref()\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}\n\nfunc (codec incomingCodec) NewBuffer() buffercache.Buffer ", "output": "{\n\treturn codec.buffers.New()\n}"} {"input": "package v1alpha1\n\nimport (\n\truntime \"k8s.io/apimachinery/pkg/runtime\"\n)\n\nvar _ runtime.NestedObjectDecoder = &AdmissionConfiguration{}\n\n\n\n\n\nvar _ runtime.NestedObjectEncoder = &AdmissionConfiguration{}\n\n\n\nfunc (c *AdmissionConfiguration) EncodeNestedObjects(e runtime.Encoder) error {\n\tfor k, v := range c.Plugins {\n\t\tif err := encodeNestedRawExtension(e, &v.Configuration); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.Plugins[k] = v\n\t}\n\treturn nil\n}\n\nfunc decodeNestedRawExtensionOrUnknown(d runtime.Decoder, ext *runtime.RawExtension) {\n\tif ext.Raw == nil || ext.Object != nil {\n\t\treturn\n\t}\n\tobj, gvk, err := d.Decode(ext.Raw, nil, nil)\n\tif err != nil {\n\t\tunk := &runtime.Unknown{Raw: ext.Raw}\n\t\tif runtime.IsNotRegisteredError(err) {\n\t\t\tif _, gvk, err := d.Decode(ext.Raw, nil, unk); err == nil {\n\t\t\t\tunk.APIVersion = gvk.GroupVersion().String()\n\t\t\t\tunk.Kind = gvk.Kind\n\t\t\t\text.Object = unk\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif gvk != nil {\n\t\t\tunk.APIVersion = gvk.GroupVersion().String()\n\t\t\tunk.Kind = gvk.Kind\n\t\t}\n\t\tobj = unk\n\t}\n\text.Object = obj\n}\n\nfunc encodeNestedRawExtension(e runtime.Encoder, ext *runtime.RawExtension) error {\n\tif ext.Raw != nil || ext.Object == nil {\n\t\treturn nil\n\t}\n\tdata, err := runtime.Encode(e, ext.Object)\n\tif err != nil {\n\t\treturn err\n\t}\n\text.Raw = data\n\treturn nil\n}\n\nfunc (c *AdmissionConfiguration) DecodeNestedObjects(d runtime.Decoder) error ", "output": "{\n\tfor k, v := range c.Plugins {\n\t\tdecodeNestedRawExtensionOrUnknown(d, &v.Configuration)\n\t\tc.Plugins[k] = v\n\t}\n\treturn nil\n}"} {"input": "package analyzer\n\nimport (\n . \"github.com/levythu/gurgling\"\n \"time\"\n \"fmt\"\n \"strconv\"\n)\n\n\n\ntype SimpleAnalyzer struct {\n \n}\n\nfunc ASimpleAnalyzer() Sandwich {\n return &SimpleAnalyzer{}\n}\n\nconst token_returncode=\"SimpleAnalyzer-Status-Code\"\nconst token_starttime=\"SimpleAnalyzer-Start-Time\"\n\n\n\nfunc (this *SimpleAnalyzer)Handler(req Request, res Response) (bool, Request, Response) {\n var newRes=&logResponse {\n o: res,\n OnHeadSent: logCode,\n }\n newRes.F()[token_starttime]=time.Now().UnixNano()\n return true, req, newRes\n}\nfunc (this *SimpleAnalyzer)Final(req Request, res Response) {\n var timeStart, ok=res.F()[token_starttime].(int64)\n var timeElpase string\n if ok {\n var t=time.Now().UnixNano()\n timeElpase=strconv.FormatInt((t-timeStart)/1000000, 10)+\"ms\"\n } else {\n timeElpase=\"xxxx\"\n }\n\n var statusCode, ok2=res.F()[token_returncode].(int)\n var codeStr string\n if ok2 {\n codeStr=strconv.Itoa(statusCode)\n } else {\n codeStr=\"---\"\n }\n\n var url=req.R().URL\n fmt.Print(\"- \"+timeElpase+\"\\t\\t\"+codeStr+\"\\t\"+req.Method()+\"\\t\"+url.Path)\n if url.RawQuery!=\"\" {\n fmt.Println(\"?\"+url.RawQuery)\n } else {\n fmt.Println(\"\")\n }\n}\n\nfunc logCode(res Response, c int) ", "output": "{\n res.F()[token_returncode]=c\n}"} {"input": "package protobuf\n\nimport \"github.com/m3db/m3x/pool\"\n\nconst (\n\tdefaultInitBufferSize = 2880\n\n\tdefaultMaxUnaggregatedMessageSize = 50 * 1024 * 1024\n)\n\n\ntype UnaggregatedOptions interface {\n\tSetBytesPool(value pool.BytesPool) UnaggregatedOptions\n\n\tBytesPool() pool.BytesPool\n\n\tSetInitBufferSize(value int) UnaggregatedOptions\n\n\tInitBufferSize() int\n\n\tSetMaxMessageSize(value int) UnaggregatedOptions\n\n\tMaxMessageSize() int\n}\n\ntype unaggregatedOptions struct {\n\tbytesPool pool.BytesPool\n\tinitBufferSize int\n\tmaxMessageSize int\n}\n\n\n\n\nfunc (o *unaggregatedOptions) SetBytesPool(value pool.BytesPool) UnaggregatedOptions {\n\topts := *o\n\topts.bytesPool = value\n\treturn &opts\n}\n\nfunc (o *unaggregatedOptions) BytesPool() pool.BytesPool {\n\treturn o.bytesPool\n}\n\nfunc (o *unaggregatedOptions) SetInitBufferSize(value int) UnaggregatedOptions {\n\topts := *o\n\topts.initBufferSize = value\n\treturn &opts\n}\n\nfunc (o *unaggregatedOptions) InitBufferSize() int {\n\treturn o.initBufferSize\n}\n\nfunc (o *unaggregatedOptions) SetMaxMessageSize(value int) UnaggregatedOptions {\n\topts := *o\n\topts.maxMessageSize = value\n\treturn &opts\n}\n\nfunc (o *unaggregatedOptions) MaxMessageSize() int {\n\treturn o.maxMessageSize\n}\n\nfunc NewUnaggregatedOptions() UnaggregatedOptions ", "output": "{\n\tp := pool.NewBytesPool(nil, nil)\n\tp.Init()\n\treturn &unaggregatedOptions{\n\t\tbytesPool: p,\n\t\tinitBufferSize: defaultInitBufferSize,\n\t\tmaxMessageSize: defaultMaxUnaggregatedMessageSize,\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"aptweb\"\n)\n\n\n\nfunc NewServer(aptWebConfig *aptweb.Config, config *Config) *http.Server ", "output": "{\n\th := NewHandler(aptWebConfig, config)\n\ts := &http.Server{\n\t\tAddr: config.Address,\n\t\tHandler: h,\n\t\tReadTimeout: 10 * time.Second,\n\t\tWriteTimeout: 10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\n\treturn s\n}"} {"input": "package dom\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\ntype Node interface {\n\tString() string\n\tParent() Node\n\tSetParent(node Node)\n\tChildren() []Node\n\tAddChild(child Node)\n\tClone() Node\n}\n\n\ntype Element struct {\n\ttext string\n\tparent Node\n\tchildren []Node\n}\n\n\nfunc NewElement(text string) *Element {\n\treturn &Element{\n\t\ttext: text,\n\t\tparent: nil,\n\t\tchildren: make([]Node, 0),\n\t}\n}\n\n\nfunc (e *Element) Parent() Node {\n\treturn e.parent\n}\n\n\nfunc (e *Element) SetParent(node Node) {\n\te.parent = node\n}\n\n\n\n\n\nfunc (e *Element) AddChild(child Node) {\n\tcopy := child.Clone()\n\tcopy.SetParent(e)\n\te.children = append(e.children, copy)\n}\n\n\n\nfunc (e *Element) Clone() Node {\n\tcopy := &Element{\n\t\ttext: e.text,\n\t\tparent: nil,\n\t\tchildren: make([]Node, 0),\n\t}\n\tfor _, child := range e.children {\n\t\tcopy.AddChild(child)\n\t}\n\treturn copy\n}\n\n\nfunc (e *Element) String() string {\n\tbuffer := bytes.NewBufferString(e.text)\n\n\tfor _, c := range e.Children() {\n\t\ttext := c.String()\n\t\tfmt.Fprintf(buffer, \"\\n %s\", text)\n\t}\n\n\treturn buffer.String()\n}\n\nfunc (e *Element) Children() []Node ", "output": "{\n\treturn e.children\n}"} {"input": "package app\n\nimport (\n\t\"github.com/mattermost/platform/model\"\n\t\"github.com/mattermost/platform/utils\"\n)\n\ntype AutoChannelCreator struct {\n\tclient *model.Client\n\tteam *model.Team\n\tFuzzy bool\n\tDisplayNameLen utils.Range\n\tDisplayNameCharset string\n\tNameLen utils.Range\n\tNameCharset string\n\tChannelType string\n}\n\n\n\nfunc (cfg *AutoChannelCreator) createRandomChannel() (*model.Channel, bool) {\n\tvar displayName string\n\tif cfg.Fuzzy {\n\t\tdisplayName = utils.FuzzName()\n\t} else {\n\t\tdisplayName = utils.RandomName(cfg.NameLen, cfg.NameCharset)\n\t}\n\tname := utils.RandomName(cfg.NameLen, cfg.NameCharset)\n\n\tchannel := &model.Channel{\n\t\tTeamId: cfg.team.Id,\n\t\tDisplayName: displayName,\n\t\tName: name,\n\t\tType: cfg.ChannelType}\n\n\tprintln(cfg.client.GetTeamRoute())\n\tresult, err := cfg.client.CreateChannel(channel)\n\tif err != nil {\n\t\terr.Translate(utils.T)\n\t\tprintln(err.Error())\n\t\tprintln(err.DetailedError)\n\t\treturn nil, false\n\t}\n\treturn result.Data.(*model.Channel), true\n}\n\nfunc (cfg *AutoChannelCreator) CreateTestChannels(num utils.Range) ([]*model.Channel, bool) {\n\tnumChannels := utils.RandIntFromRange(num)\n\tchannels := make([]*model.Channel, numChannels)\n\n\tfor i := 0; i < numChannels; i++ {\n\t\tvar err bool\n\t\tchannels[i], err = cfg.createRandomChannel()\n\t\tif err != true {\n\t\t\treturn channels, false\n\t\t}\n\t}\n\n\treturn channels, true\n}\n\nfunc NewAutoChannelCreator(client *model.Client, team *model.Team) *AutoChannelCreator ", "output": "{\n\treturn &AutoChannelCreator{\n\t\tclient: client,\n\t\tteam: team,\n\t\tFuzzy: false,\n\t\tDisplayNameLen: CHANNEL_DISPLAY_NAME_LEN,\n\t\tDisplayNameCharset: utils.ALPHANUMERIC,\n\t\tNameLen: CHANNEL_NAME_LEN,\n\t\tNameCharset: utils.LOWERCASE,\n\t\tChannelType: CHANNEL_TYPE,\n\t}\n}"} {"input": "package rtda\n\nimport (\n\t\"github.com/zxh0/jvm.go/rtda/heap\"\n)\n\ntype FrameCache struct {\n\tthread *Thread\n\tcachedFrames []*Frame\n\tframeCount uint\n\tmaxFrame uint\n}\n\nfunc newFrameCache(thread *Thread, maxFrame uint) *FrameCache {\n\treturn &FrameCache{\n\t\tthread: thread,\n\t\tmaxFrame: maxFrame,\n\t\tcachedFrames: make([]*Frame, maxFrame),\n\t}\n}\n\nfunc (cache *FrameCache) borrowFrame(method *heap.Method) *Frame {\n\tif cache.frameCount > 0 {\n\t\tfor i, frame := range cache.cachedFrames {\n\t\t\tif frame != nil &&\n\t\t\t\tframe.maxLocals >= method.MaxLocals &&\n\t\t\t\tframe.maxStack >= method.MaxStack {\n\n\t\t\t\tcache.frameCount--\n\t\t\t\tcache.cachedFrames[i] = nil\n\t\t\t\tframe.reset(method)\n\t\t\t\treturn frame\n\t\t\t}\n\t\t}\n\t}\n\treturn newFrame(cache.thread, method)\n}\n\n\n\nfunc (cache *FrameCache) returnFrame(frame *Frame) ", "output": "{\n\tif cache.frameCount < cache.maxFrame {\n\t\tfor i, cachedFrame := range cache.cachedFrames {\n\t\t\tif cachedFrame == nil {\n\t\t\t\tcache.cachedFrames[i] = frame\n\t\t\t\tcache.frameCount++\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor _, cachedFrame := range cache.cachedFrames {\n\t\t\tif frame.maxLocals > cachedFrame.maxLocals {\n\t\t\t\tcachedFrame.maxLocals = frame.maxLocals\n\t\t\t\tcachedFrame.LocalVars = frame.LocalVars\n\t\t\t\tframe.maxLocals = 0\n\t\t\t}\n\t\t\tif frame.maxStack > cachedFrame.maxStack {\n\t\t\t\tcachedFrame.maxStack = frame.maxStack\n\t\t\t\tcachedFrame.OperandStack = frame.OperandStack\n\t\t\t\tframe.maxStack = 0\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package commands\n\nimport (\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"github.com/jamesread/ovress/pkg/indexer\"\n\n\t\"github.com/spf13/cobra\"\n)\n\n\n\nfunc runIndexCmd(cmd *cobra.Command, args []string) {\n\tfor _, path := range args {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"path\": path,\n\t\t}).Infof(\"Indexing starting\")\n\n\t\troot := indexer.ScanRoot(path)\n\t\tindexer.SaveIndex(root)\n\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"path\": path,\n\t\t}).Infof(\"Indexing complete\")\n\t}\n}\n\nfunc init() {\n\trootCmd.AddCommand(newIndexCmd())\n}\n\nfunc newIndexCmd() *cobra.Command ", "output": "{\n\tvar indexCmd = &cobra.Command{\n\t\tUse: \"index\",\n\t\tShort: \"Indexes a file path\",\n\t\tRun: runIndexCmd,\n\t\tArgs: cobra.MinimumNArgs(1),\n\t}\n\n\treturn indexCmd\n}"} {"input": "package unibyte\n\nimport \"unicode\"\n\n\nfunc IsLower(b byte) bool {\n\treturn b >= 'a' && b <= 'z'\n}\n\n\nfunc IsUpper(b byte) bool {\n\treturn b >= 'A' && b <= 'Z'\n}\n\n\nfunc IsLetter(b byte) bool {\n\treturn IsLower(b) || IsUpper(b)\n}\n\n\nfunc IsSpaceQuote(b byte) bool {\n\treturn IsSpace(b) || b == '\"' || b == '\\''\n}\n\n\n\n\n\nfunc ToLower(b byte) byte {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn b\n}\n\n\nfunc ToUpper(b byte) byte {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn b\n}\n\n\nfunc ToLowerString(b byte) string {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn string(b)\n}\n\n\nfunc ToUpperString(b byte) string {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn string(b)\n}\n\nfunc IsSpace(b byte) bool ", "output": "{\n\treturn unicode.IsSpace(rune(b))\n}"} {"input": "package aprs\n\nimport (\n\t\"fmt\"\n)\n\n\ntype PacketType byte\n\nvar packetTypeNames = map[byte]string{\n\t0x1c: \"Current Mic-E Data (Rev 0 beta)\",\n\t0x1d: \"Old Mic-E Data (Rev 0 beta)\",\n\t'!': \"Position without timestamp (no APRS messaging), or Ultimeter 2000 WX Station\",\n\t'#': \"Peet Bros U-II Weather Station\",\n\t'$': \"Raw GPS data or Ultimeter 2000\",\n\t'%': \"Agrelo DFJr / MicroFinder\",\n\t'\"': \"Old Mic-E Data (but Current data for TM-D700)\",\n\t')': \"Item\",\n\t'*': \"Peet Bros U-II Weather Station\",\n\t',': \"Invalid data or test data\",\n\t'/': \"Position with timestamp (no APRS messaging)\",\n\t':': \"Message\",\n\t';': \"Object\",\n\t'<': \"Station Capabilities\",\n\t'=': \"Position without timestamp (with APRS messaging)\",\n\t'>': \"Status\",\n\t'?': \"Query\",\n\t'@': \"Position with timestamp (with APRS messaging)\",\n\t'T': \"Telemetry data\",\n\t'[': \"Maidenhead grid locator beacon (obsolete)\",\n\t'_': \"Weather Report (without position)\",\n\t'`': \"Current Mic-E Data (not used in TM-D700)\",\n\t'{': \"User-Defined APRS packet format\",\n\t'}': \"Third-party traffic\",\n}\n\n\n\n\n\nfunc (p PacketType) IsThirdParty() bool {\n\treturn p == '}'\n}\n\nfunc (p PacketType) String() string {\n\tif t, ok := packetTypeNames[byte(p)]; ok {\n\t\treturn t\n\t}\n\treturn fmt.Sprintf(\"Unknown %x\", byte(p))\n}\n\nfunc (p PacketType) IsMessage() bool ", "output": "{\n\treturn p == ':'\n}"} {"input": "package atomic\n\nimport (\n\t\"encoding/json\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\n\ntype Uint32 struct {\n\t_ nocmp \n\n\tv uint32\n}\n\n\nfunc NewUint32(val uint32) *Uint32 {\n\treturn &Uint32{v: val}\n}\n\n\nfunc (i *Uint32) Load() uint32 {\n\treturn atomic.LoadUint32(&i.v)\n}\n\n\nfunc (i *Uint32) Add(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, delta)\n}\n\n\nfunc (i *Uint32) Sub(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, ^(delta - 1))\n}\n\n\nfunc (i *Uint32) Inc() uint32 {\n\treturn i.Add(1)\n}\n\n\nfunc (i *Uint32) Dec() uint32 {\n\treturn i.Sub(1)\n}\n\n\nfunc (i *Uint32) CAS(old, new uint32) (swapped bool) {\n\treturn atomic.CompareAndSwapUint32(&i.v, old, new)\n}\n\n\nfunc (i *Uint32) Store(val uint32) {\n\tatomic.StoreUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) Swap(val uint32) (old uint32) {\n\treturn atomic.SwapUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(i.Load())\n}\n\n\nfunc (i *Uint32) UnmarshalJSON(b []byte) error {\n\tvar v uint32\n\tif err := json.Unmarshal(b, &v); err != nil {\n\t\treturn err\n\t}\n\ti.Store(v)\n\treturn nil\n}\n\n\n\n\nfunc (i *Uint32) String() string ", "output": "{\n\tv := i.Load()\n\treturn strconv.FormatUint(uint64(v), 10)\n}"} {"input": "package payload\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hyperledger/burrow/acm/acmstate\"\n\t\"github.com/hyperledger/burrow/crypto\"\n)\n\nfunc NewBondTx(address crypto.Address, amount uint64) *BondTx {\n\treturn &BondTx{\n\t\tInput: &TxInput{\n\t\t\tAddress: address,\n\t\t\tAmount: amount,\n\t\t},\n\t}\n}\n\nfunc (tx *BondTx) Type() Type {\n\treturn TypeBond\n}\n\nfunc (tx *BondTx) GetInputs() []*TxInput {\n\treturn []*TxInput{tx.Input}\n}\n\n\n\nfunc (tx *BondTx) AddInput(st acmstate.AccountGetter, pubkey *crypto.PublicKey, amt uint64) error {\n\taddr := pubkey.GetAddress()\n\tacc, err := st.GetAccount(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif acc == nil {\n\t\treturn fmt.Errorf(\"invalid address %s from pubkey %s\", addr, pubkey)\n\t}\n\treturn tx.AddInputWithSequence(pubkey, amt, acc.Sequence+uint64(1))\n}\n\nfunc (tx *BondTx) AddInputWithSequence(pubkey *crypto.PublicKey, amt uint64, sequence uint64) error {\n\ttx.Input = &TxInput{\n\t\tAddress: pubkey.GetAddress(),\n\t\tAmount: amt,\n\t\tSequence: sequence,\n\t}\n\treturn nil\n}\n\nfunc (tx *BondTx) Any() *Any {\n\treturn &Any{\n\t\tBondTx: tx,\n\t}\n}\n\nfunc (tx *BondTx) String() string ", "output": "{\n\treturn fmt.Sprintf(\"BondTx{%v}\", tx.Input)\n}"} {"input": "package vkutil\n\nimport (\n\t\"strconv\"\n\t\"time\"\n)\n\n\ntype EpochTime time.Time\n\n\nfunc (t EpochTime) MarshalJSON() ([]byte, error) {\n\treturn []byte(strconv.FormatInt(time.Time(t).Unix(), 10)), nil\n}\n\n\n\n\nfunc (t EpochTime) ToTime() time.Time {\n\treturn time.Time(t)\n}\n\nfunc (t *EpochTime) UnmarshalJSON(s []byte) error ", "output": "{\n\tvar err error\n\tvar q int64\n\tif q, err = strconv.ParseInt(string(s), 10, 64); err != nil {\n\t\treturn err\n\t}\n\t*(*time.Time)(t) = time.Unix(q, 0)\n\treturn err\n}"} {"input": "package password\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"time\"\n\n\tjwt \"github.com/dgrijalva/jwt-go\"\n)\n\nvar signingKey = genRandBytes()\n\n\nfunc GenToken(id string) (string, error) {\n\tjwt := jwt.New(jwt.SigningMethodHS256)\n\texpTime := time.Now().Add(time.Hour * 72).Unix()\n\n\tjwt.Claims[\"sub\"] = id\n\tjwt.Claims[\"exp\"] = expTime\n\tjwt.Claims[\"iat\"] = time.Now().Unix()\n\n\ttokStr, err := jwt.SignedString(signingKey)\n\tif err != nil {\n\t\treturn \"\", err \n\t}\n\n\treturn tokStr, nil\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc genRandBytes() []byte {\n\tb := make([]byte, 24)\n\t_, err := rand.Read(b)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []byte(base64.URLEncoding.EncodeToString(b))\n}\n\nfunc SetSigningKey(key []byte) ", "output": "{\n\tsigningKey = key\n}"} {"input": "package aws\n\nimport (\n\t\"log\"\n\n\t\"fmt\"\n\n\t\"github.com/hashicorp/terraform/helper/schema\"\n)\n\nfunc resourceAwsVpcPeeringConnectionAccepter() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsVPCPeeringAccepterCreate,\n\t\tRead: resourceAwsVPCPeeringRead,\n\t\tUpdate: resourceAwsVPCPeeringUpdate,\n\t\tDelete: resourceAwsVPCPeeringAccepterDelete,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"vpc_peering_connection_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tComputed: false,\n\t\t\t},\n\t\t\t\"auto_accept\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"accept_status\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"vpc_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"peer_vpc_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"peer_owner_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"peer_region\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"accepter\": vpcPeeringConnectionOptionsSchema(),\n\t\t\t\"requester\": vpcPeeringConnectionOptionsSchema(),\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\n\n\nfunc resourceAwsVPCPeeringAccepterDelete(d *schema.ResourceData, meta interface{}) error {\n\tlog.Printf(\"[WARN] Will not delete VPC peering connection. Terraform will remove this resource from the state file, however resources may remain.\")\n\td.SetId(\"\")\n\treturn nil\n}\n\nfunc resourceAwsVPCPeeringAccepterCreate(d *schema.ResourceData, meta interface{}) error ", "output": "{\n\tid := d.Get(\"vpc_peering_connection_id\").(string)\n\td.SetId(id)\n\n\tif err := resourceAwsVPCPeeringRead(d, meta); err != nil {\n\t\treturn err\n\t}\n\tif d.Id() == \"\" {\n\t\treturn fmt.Errorf(\"VPC Peering Connection %q not found\", id)\n\t}\n\n\treturn resourceAwsVPCPeeringUpdate(d, meta)\n}"} {"input": "package wire\n\nimport (\n\t\"time\"\n)\n\n\ntype periodicTask struct {\n\tperiod time.Duration\n\ttask func()\n\tticker *time.Ticker\n\tstop chan struct{}\n}\n\nfunc newPeriodicTask(period time.Duration, task func()) *periodicTask {\n\treturn &periodicTask{\n\t\tperiod: period,\n\t\ttask: task,\n\t}\n}\n\n\n\nfunc (pt *periodicTask) Start() {\n\tif pt.ticker != nil || pt.period <= 0 {\n\t\treturn\n\t}\n\n\tpt.ticker = time.NewTicker(pt.period)\n\tpt.stop = make(chan struct{})\n\tgo pt.poll(pt.ticker, pt.stop)\n}\n\n\nfunc (pt *periodicTask) Stop() {\n\tif pt.ticker == nil {\n\t\treturn\n\t}\n\n\tpt.ticker.Stop()\n\tclose(pt.stop)\n\n\tpt.ticker = nil\n\tpt.stop = nil\n}\n\n\n\nfunc (pt *periodicTask) poll(ticker *time.Ticker, stop chan struct{}) ", "output": "{\n\tfor {\n\t\tselect {\n\t\tcase <-stop:\n\t\t\treturn \n\t\tdefault:\n\t\t}\n\n\t\tselect {\n\t\tcase <-stop:\n\t\t\treturn \n\t\tcase <-ticker.C:\n\t\t\tpt.task()\n\t\t}\n\t}\n}"} {"input": "package embed\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/url\"\n\t\"os\"\n\t\"testing\"\n\n\t\"go.etcd.io/etcd/server/v3/auth\"\n)\n\n\nfunc TestStartEtcdWrongToken(t *testing.T) {\n\ttdir, err := ioutil.TempDir(os.TempDir(), \"token-test\")\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tdir)\n\n\tcfg := NewConfig()\n\n\turls := newEmbedURLs(2)\n\tcurls := []url.URL{urls[0]}\n\tpurls := []url.URL{urls[1]}\n\tcfg.LCUrls, cfg.ACUrls = curls, curls\n\tcfg.LPUrls, cfg.APUrls = purls, purls\n\tcfg.InitialCluster = \"\"\n\tfor i := range purls {\n\t\tcfg.InitialCluster += \",default=\" + purls[i].String()\n\t}\n\tcfg.InitialCluster = cfg.InitialCluster[1:]\n\tcfg.Dir = tdir\n\tcfg.AuthToken = \"wrong-token\"\n\n\tif _, err = StartEtcd(cfg); err != auth.ErrInvalidAuthOpts {\n\t\tt.Fatalf(\"expected %v, got %v\", auth.ErrInvalidAuthOpts, err)\n\t}\n}\n\n\n\nfunc newEmbedURLs(n int) (urls []url.URL) ", "output": "{\n\tscheme := \"unix\"\n\tfor i := 0; i < n; i++ {\n\t\tu, _ := url.Parse(fmt.Sprintf(\"%s:localhost:%d%06d\", scheme, os.Getpid(), i))\n\t\turls = append(urls, *u)\n\t}\n\treturn urls\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc splitQuoted(s string) (r []string, err error) {\n\tvar args []string\n\targ := make([]rune, len(s))\n\tescaped := false\n\tquoted := false\n\tquote := '\\x00'\n\ti := 0\n\tfor _, rune := range s {\n\t\tswitch {\n\t\tcase escaped:\n\t\t\tescaped = false\n\t\tcase rune == '\\\\':\n\t\t\tescaped = true\n\t\t\tcontinue\n\t\tcase quote != '\\x00':\n\t\t\tif rune == quote {\n\t\t\t\tquote = '\\x00'\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase rune == '\"' || rune == '\\'':\n\t\t\tquoted = true\n\t\t\tquote = rune\n\t\t\tcontinue\n\t\tcase unicode.IsSpace(rune):\n\t\t\tif quoted || i > 0 {\n\t\t\t\tquoted = false\n\t\t\t\targs = append(args, string(arg[:i]))\n\t\t\t\ti = 0\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\targ[i] = rune\n\t\ti++\n\t}\n\tif quoted || i > 0 {\n\t\targs = append(args, string(arg[:i]))\n\t}\n\tif quote != 0 {\n\t\terr = errors.New(\"unclosed quote\")\n\t} else if escaped {\n\t\terr = errors.New(\"unfinished escaping\")\n\t}\n\treturn args, err\n}\n\nfunc stringsCut(s, sep string) (before, after string, found bool) ", "output": "{\n\tif i := strings.Index(s, sep); i >= 0 {\n\t\treturn s[:i], s[i+len(sep):], true\n\t}\n\treturn s, \"\", false\n}"} {"input": "package control\n\nimport (\n\tyaml \"github.com/cloudfoundry-incubator/candiedyaml\"\n\t\"github.com/dansteen/controlled-compose/types\"\n\t\"github.com/docker/libcompose/config\"\n\t\"github.com/docker/libcompose/utils\"\n\t\"github.com/imdario/mergo.git\"\n\t\"io/ioutil\"\n\t\"path/filepath\"\n)\n\n\n\n\nfunc processRequires(file string, configFiles []string) ([]string, error) {\n\tcontent, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar requires types.Requires\n\terr = yaml.Unmarshal(content, &requires)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnewFiles := append(configFiles, file)\n\n\tfor _, require := range requires.Require {\n\t\trequire = filepath.Join(filepath.Dir(file), require)\n\n\t\tif !utils.Contains(configFiles, require) {\n\t\t\tnewFiles, err = processRequires(require, newFiles)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\treturn newFiles, nil\n}\n\n\n\n\nfunc consumeConfigs(files []string) ([]byte, error) ", "output": "{\n\n\tvar configContent config.Config\n\tvar mergedConfig config.Config\n\tfor _, file := range files {\n\t\tcontent, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = yaml.Unmarshal(content, &configContent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = mergo.Merge(&mergedConfig, configContent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tyamlConfig, err := yaml.Marshal(mergedConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn []byte(yamlConfig), nil\n}"} {"input": "package container\n\ntype (\n\tLifo struct {\n\t\tFifo\n\t}\n)\n\n\n\nfunc (li *Lifo) Less(i, j int) bool ", "output": "{\n\treturn li.data[i].index > li.data[j].index\n}"} {"input": "package algorithms\n\nimport \"log\"\n\n\nfunc canCompleteCircuit(gas []int, cost []int) int {\n\tfor i := 0; i < len(gas); i++ {\n\t\tgas[i] = gas[i] - cost[i]\n\t}\n\tlog.Println(\"A:\", gas)\n\n\tindex := 0\n\tfor i := 1; i < len(gas); i++ {\n\t\tgas[i] += gas[i-1]\n\t\tif gas[i] < gas[index] {\n\t\t\tindex = i\n\t\t}\n\t}\n\tlog.Println(\"B:\", gas)\n\tif gas[len(gas)-1] < 0 {\n\t\treturn -1\n\t}\n\treturn (index + 1) % len(gas)\n}\nfunc canCompleteCircuit(gas []int, cost []int) int {\n\tfor i := 0; i < len(gas); i++ {\n\t\tgas[i] = gas[i] - cost[i]\n\t}\n\tlog.Println(\"A:\", gas)\n\n\tindex := 0\n\tfor i := 1; i < len(gas); i++ {\n\t\tgas[i] += gas[i-1]\n\t\tif gas[i] < gas[index] {\n\t\t\tindex = i\n\t\t}\n\t}\n\tlog.Println(\"B:\", gas)\n\tif gas[len(gas)-1] < 0 {\n\t\treturn -1\n\t}\n\treturn (index + 1) % len(gas)\n}\n\nfunc canCompleteCircuit(gas []int, cost []int) int ", "output": "{\n\tindex := 0\n\tfor i := 0; i < len(gas); i++ {\n\t\tgas[i] = gas[i] - cost[i]\n\t\tif i > 0 {\n\t\t\tgas[i] += gas[i-1]\n\t\t\tif gas[i] < gas[index] {\n\t\t\t\tindex = i\n\t\t\t}\n\t\t}\n\t}\n\tif gas[len(gas)-1] < 0 {\n\t\treturn -1\n\t}\n\treturn (index + 1) % len(gas)\n}"} {"input": "package zk\n\nimport \"github.com/go-kit/kit/log\"\n\n\ntype Registrar struct {\n\tclient Client\n\tservice Service\n\tlogger log.Logger\n}\n\n\n\ntype Service struct {\n\tPath string \n\tName string \n\tData []byte \n\tnode string \n}\n\n\n\n\n\n\nfunc (r *Registrar) Register() {\n\tif err := r.client.Register(&r.service); err != nil {\n\t\tr.logger.Log(\"err\", err)\n\t} else {\n\t\tr.logger.Log(\"action\", \"register\")\n\t}\n}\n\n\nfunc (r *Registrar) Deregister() {\n\tif err := r.client.Deregister(&r.service); err != nil {\n\t\tr.logger.Log(\"err\", err)\n\t} else {\n\t\tr.logger.Log(\"action\", \"deregister\")\n\t}\n}\n\nfunc NewRegistrar(client Client, service Service, logger log.Logger) *Registrar ", "output": "{\n\treturn &Registrar{\n\t\tclient: client,\n\t\tservice: service,\n\t\tlogger: log.With(logger,\n\t\t\t\"service\", service.Name,\n\t\t\t\"path\", service.Path,\n\t\t\t\"data\", string(service.Data),\n\t\t),\n\t}\n}"} {"input": "package kv_test\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/influxdata/influxdb\"\n\t\"github.com/influxdata/influxdb/kv\"\n\tinfluxdbtesting \"github.com/influxdata/influxdb/testing\"\n)\n\nfunc TestBoltOrganizationService(t *testing.T) {\n\tinfluxdbtesting.OrganizationService(initBoltOrganizationService, t)\n}\n\nfunc TestInmemOrganizationService(t *testing.T) {\n\tinfluxdbtesting.OrganizationService(initInmemOrganizationService, t)\n}\n\nfunc initBoltOrganizationService(f influxdbtesting.OrganizationFields, t *testing.T) (influxdb.OrganizationService, string, func()) {\n\ts, closeBolt, err := NewTestBoltStore()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create new kv store: %v\", err)\n\t}\n\n\tsvc, op, closeSvc := initOrganizationService(s, f, t)\n\treturn svc, op, func() {\n\t\tcloseSvc()\n\t\tcloseBolt()\n\t}\n}\n\nfunc initInmemOrganizationService(f influxdbtesting.OrganizationFields, t *testing.T) (influxdb.OrganizationService, string, func()) {\n\ts, closeBolt, err := NewTestInmemStore()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create new kv store: %v\", err)\n\t}\n\n\tsvc, op, closeSvc := initOrganizationService(s, f, t)\n\treturn svc, op, func() {\n\t\tcloseSvc()\n\t\tcloseBolt()\n\t}\n}\n\n\n\nfunc initOrganizationService(s kv.Store, f influxdbtesting.OrganizationFields, t *testing.T) (influxdb.OrganizationService, string, func()) ", "output": "{\n\tsvc := kv.NewService(s)\n\tsvc.OrgBucketIDs = f.OrgBucketIDs\n\tsvc.IDGenerator = f.IDGenerator\n\tsvc.TimeGenerator = f.TimeGenerator\n\tif f.TimeGenerator == nil {\n\t\tsvc.TimeGenerator = influxdb.RealTimeGenerator{}\n\t}\n\n\tctx := context.Background()\n\tif err := svc.Initialize(ctx); err != nil {\n\t\tt.Fatalf(\"error initializing organization service: %v\", err)\n\t}\n\n\tfor _, u := range f.Organizations {\n\t\tif err := svc.PutOrganization(ctx, u); err != nil {\n\t\t\tt.Fatalf(\"failed to populate organizations\")\n\t\t}\n\t}\n\n\treturn svc, kv.OpPrefix, func() {\n\t\tfor _, u := range f.Organizations {\n\t\t\tif err := svc.DeleteOrganization(ctx, u.ID); err != nil {\n\t\t\t\tt.Logf(\"failed to remove organizations: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package service\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetServiceIDOKCode int = 200\n\n\ntype GetServiceIDOK struct {\n\n\tPayload *models.Service `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetServiceIDOK() *GetServiceIDOK {\n\n\treturn &GetServiceIDOK{}\n}\n\n\nfunc (o *GetServiceIDOK) WithPayload(payload *models.Service) *GetServiceIDOK {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *GetServiceIDOK) SetPayload(payload *models.Service) {\n\to.Payload = payload\n}\n\n\nfunc (o *GetServiceIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\n\nconst GetServiceIDNotFoundCode int = 404\n\n\ntype GetServiceIDNotFound struct {\n}\n\n\n\n\n\nfunc (o *GetServiceIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc NewGetServiceIDNotFound() *GetServiceIDNotFound ", "output": "{\n\n\treturn &GetServiceIDNotFound{}\n}"} {"input": "package alicloud\n\ntype PrimaryKeyTypeString string\n\nconst (\n\tIntegerType = PrimaryKeyTypeString(\"Integer\")\n\tStringType = PrimaryKeyTypeString(\"String\")\n\tBinaryType = PrimaryKeyTypeString(\"Binary\")\n)\n\ntype InstanceAccessedByType string\n\nconst (\n\tAnyNetwork = InstanceAccessedByType(\"Any\")\n\tVpcOnly = InstanceAccessedByType(\"Vpc\")\n\tVpcOrConsole = InstanceAccessedByType(\"ConsoleOrVpc\")\n)\n\ntype OtsInstanceType string\n\nconst (\n\tOtsCapacity = OtsInstanceType(\"Capacity\")\n\tOtsHighPerformance = OtsInstanceType(\"HighPerformance\")\n)\n\nfunc convertInstanceAccessedBy(accessed InstanceAccessedByType) string {\n\tswitch accessed {\n\tcase VpcOnly:\n\t\treturn \"VPC\"\n\tcase VpcOrConsole:\n\t\treturn \"VPC_CONSOLE\"\n\tdefault:\n\t\treturn \"NORMAL\"\n\t}\n}\n\nfunc convertInstanceAccessedByRevert(network string) InstanceAccessedByType {\n\tswitch network {\n\tcase \"VPC\":\n\t\treturn VpcOnly\n\tcase \"VPC_CONSOLE\":\n\t\treturn VpcOrConsole\n\tdefault:\n\t\treturn AnyNetwork\n\t}\n}\n\nfunc convertInstanceType(instanceType OtsInstanceType) string {\n\tswitch instanceType {\n\tcase OtsHighPerformance:\n\t\treturn \"SSD\"\n\tdefault:\n\t\treturn \"HYBRID\"\n\t}\n}\n\n\n\n\nfunc convertOtsInstanceStatus(status Status) int {\n\tswitch status {\n\tcase Running:\n\t\treturn 1\n\tcase DisabledStatus:\n\t\treturn 2\n\tcase Deleting:\n\t\treturn 3\n\tdefault:\n\t\treturn -1\n\t}\n}\n\nfunc convertInstanceTypeRevert(instanceType string) OtsInstanceType ", "output": "{\n\tswitch instanceType {\n\tcase \"SSD\":\n\t\treturn OtsHighPerformance\n\tdefault:\n\t\treturn OtsCapacity\n\t}\n}"} {"input": "package assert\n\n\n\nfunc isPrime(value int) bool ", "output": "{\n\tif value <= 3 {\n\t\treturn value >= 2\n\t}\n\tif value%2 == 0 || value%3 == 0 {\n\t\treturn false\n\t}\n\tuns := uint(value)\n\tfor i := uint(5); i*i <= uns; i += 6 {\n\t\tif uns%i == 0 || uns%(i+2) == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package state\n\nimport (\n\t\"net/url\"\n\n\t\"gopkg.in/juju/charm.v3\"\n)\n\n\ntype charmDoc struct {\n\tURL *charm.URL `bson:\"_id\"`\n\tMeta *charm.Meta\n\tConfig *charm.Config\n\tActions *charm.Actions\n\tBundleURL *url.URL\n\tBundleSha256 string\n\tPendingUpload bool\n\tPlaceholder bool\n}\n\n\ntype Charm struct {\n\tst *State\n\tdoc charmDoc\n}\n\nfunc newCharm(st *State, cdoc *charmDoc) (*Charm, error) {\n\treturn &Charm{st: st, doc: *cdoc}, nil\n}\n\nfunc (c *Charm) String() string {\n\treturn c.doc.URL.String()\n}\n\n\nfunc (c *Charm) URL() *charm.URL {\n\tclone := *c.doc.URL\n\treturn &clone\n}\n\n\n\nfunc (c *Charm) Revision() int {\n\treturn c.doc.URL.Revision\n}\n\n\nfunc (c *Charm) Meta() *charm.Meta {\n\treturn c.doc.Meta\n}\n\n\n\n\n\nfunc (c *Charm) Actions() *charm.Actions {\n\treturn c.doc.Actions\n}\n\n\n\nfunc (c *Charm) BundleURL() *url.URL {\n\treturn c.doc.BundleURL\n}\n\n\nfunc (c *Charm) BundleSha256() string {\n\treturn c.doc.BundleSha256\n}\n\n\n\nfunc (c *Charm) IsUploaded() bool {\n\treturn !c.doc.PendingUpload\n}\n\n\n\nfunc (c *Charm) IsPlaceholder() bool {\n\treturn c.doc.Placeholder\n}\n\nfunc (c *Charm) Config() *charm.Config ", "output": "{\n\treturn c.doc.Config\n}"} {"input": "package emperror\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n\n\n\nfunc Recover(r interface{}) (err error) ", "output": "{\n\tif r != nil {\n\t\tswitch x := r.(type) {\n\t\tcase string:\n\t\t\terr = errors.New(x)\n\t\tcase error:\n\t\t\terr = x\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"unknown panic, received: %v\", r)\n\t\t}\n\n\t\tif _, ok := StackTrace(err); !ok {\n\t\t\terr = &wrappedError{\n\t\t\t\terr: err,\n\t\t\t\tstack: callers()[2:], \n\t\t\t}\n\t\t}\n\t}\n\n\treturn err\n}"} {"input": "package systemd\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/google/cadvisor/container\"\n\t\"github.com/google/cadvisor/fs\"\n\tinfo \"github.com/google/cadvisor/info/v1\"\n\t\"github.com/google/cadvisor/watcher\"\n\n\t\"k8s.io/klog/v2\"\n)\n\ntype systemdFactory struct{}\n\nfunc (f *systemdFactory) String() string {\n\treturn \"systemd\"\n}\n\nfunc (f *systemdFactory) NewContainerHandler(name string, inHostNamespace bool) (container.ContainerHandler, error) {\n\treturn nil, fmt.Errorf(\"Not yet supported\")\n}\n\n\n\nfunc (f *systemdFactory) DebugInfo() map[string][]string {\n\treturn map[string][]string{}\n}\n\n\nfunc Register(machineInfoFactory info.MachineInfoFactory, fsInfo fs.FsInfo, includedMetrics container.MetricSet) error {\n\tklog.V(1).Infof(\"Registering systemd factory\")\n\tfactory := &systemdFactory{}\n\tcontainer.RegisterContainerHandlerFactory(factory, []watcher.ContainerWatchSource{watcher.Raw})\n\treturn nil\n}\n\nfunc (f *systemdFactory) CanHandleAndAccept(name string) (bool, bool, error) ", "output": "{\n\tif strings.HasSuffix(name, \".mount\") {\n\t\treturn true, false, nil\n\t}\n\tklog.V(5).Infof(\"%s not handled by systemd handler\", name)\n\treturn false, false, nil\n}"} {"input": "package errors\n\nfunc NewEmptyResourceError() *EmptyResourceError {\n\treturn &EmptyResourceError{}\n}\n\ntype EmptyResourceError struct{}\n\n\n\nfunc (e *EmptyResourceError) Error() string ", "output": "{\n\treturn \"EmptyResourceError\"\n}"} {"input": "package wifi\n\nvar _ = WiFi(&StubWorker{})\n\ntype StubWorker struct {\n\tOptions []Option\n\tID string\n}\n\nfunc (w *StubWorker) Scan() ([]Option, error) {\n\treturn w.Options, nil\n}\n\n\n\nfunc (*StubWorker) Connect(a ...string) error {\n\treturn nil\n}\n\nfunc NewStubWorker(id string, options ...Option) (WiFi, error) {\n\treturn &StubWorker{ID: id, Options: options}, nil\n}\n\nfunc (w *StubWorker) GetID() (string, error) ", "output": "{\n\treturn w.ID, nil\n}"} {"input": "package caaa\n\nimport (\n\t\"encoding/xml\"\n\n\t\"github.com/fgrid/iso20022\"\n)\n\ntype Document00900101 struct {\n\tXMLName xml.Name `xml:\"urn:iso:std:iso:20022:tech:xsd:caaa.009.001.01 Document\"`\n\tMessage *AcceptorReconciliationRequestV01 `xml:\"AccptrRcncltnReq\"`\n}\n\nfunc (d *Document00900101) AddMessage() *AcceptorReconciliationRequestV01 {\n\td.Message = new(AcceptorReconciliationRequestV01)\n\treturn d.Message\n}\n\n\n\n\n\n\ntype AcceptorReconciliationRequestV01 struct {\n\n\tHeader *iso20022.Header1 `xml:\"Hdr\"`\n\n\tReconciliationRequest *iso20022.AcceptorReconciliationRequest1 `xml:\"RcncltnReq\"`\n\n\tSecurityTrailer *iso20022.ContentInformationType3 `xml:\"SctyTrlr\"`\n}\n\n\n\nfunc (a *AcceptorReconciliationRequestV01) AddReconciliationRequest() *iso20022.AcceptorReconciliationRequest1 {\n\ta.ReconciliationRequest = new(iso20022.AcceptorReconciliationRequest1)\n\treturn a.ReconciliationRequest\n}\n\nfunc (a *AcceptorReconciliationRequestV01) AddSecurityTrailer() *iso20022.ContentInformationType3 {\n\ta.SecurityTrailer = new(iso20022.ContentInformationType3)\n\treturn a.SecurityTrailer\n}\n\nfunc (a *AcceptorReconciliationRequestV01) AddHeader() *iso20022.Header1 ", "output": "{\n\ta.Header = new(iso20022.Header1)\n\treturn a.Header\n}"} {"input": "package main\n\nimport (\n\t\"syscall\"\n)\n\n\n\nfunc setRlimit() error ", "output": "{\n\trlimit := int64(100000)\n\tif rlimit > 0 {\n\t\tvar limit syscall.Rlimit\n\t\tif err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif limit.Cur < rlimit {\n\t\t\tlimit.Cur = rlimit\n\t\t\tif err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package credentials\n\nimport (\n\t\"strings\"\n\n\t\"github.com/docker/docker/cliconfig/configfile\"\n\t\"github.com/docker/engine-api/types\"\n)\n\n\n\ntype fileStore struct {\n\tfile *configfile.ConfigFile\n}\n\n\nfunc NewFileStore(file *configfile.ConfigFile) Store {\n\treturn &fileStore{\n\t\tfile: file,\n\t}\n}\n\n\nfunc (c *fileStore) Erase(serverAddress string) error {\n\tdelete(c.file.AuthConfigs, serverAddress)\n\treturn c.file.Save()\n}\n\n\nfunc (c *fileStore) Get(serverAddress string) (types.AuthConfig, error) {\n\tauthConfig, ok := c.file.AuthConfigs[serverAddress]\n\tif !ok {\n\t\tfor registry, ac := range c.file.AuthConfigs {\n\t\t\tif serverAddress == convertToHostname(registry) {\n\t\t\t\treturn ac, nil\n\t\t\t}\n\t\t}\n\n\t\tauthConfig = types.AuthConfig{}\n\t}\n\treturn authConfig, nil\n}\n\nfunc (c *fileStore) GetAll() (map[string]types.AuthConfig, error) {\n\treturn c.file.AuthConfigs, nil\n}\n\n\n\n\nfunc convertToHostname(url string) string {\n\tstripped := url\n\tif strings.HasPrefix(url, \"http://\") {\n\t\tstripped = strings.Replace(url, \"http://\", \"\", 1)\n\t} else if strings.HasPrefix(url, \"https://\") {\n\t\tstripped = strings.Replace(url, \"https://\", \"\", 1)\n\t}\n\n\tnameParts := strings.SplitN(stripped, \"/\", 2)\n\n\treturn nameParts[0]\n}\n\nfunc (c *fileStore) Store(authConfig types.AuthConfig) error ", "output": "{\n\tc.file.AuthConfigs[authConfig.ServerAddress] = authConfig\n\treturn c.file.Save()\n}"} {"input": "package aggregator\n\nimport (\n\t\"github.com/CapillarySoftware/gostat/stat\"\n\t\"math\"\n)\n\n\n\nfunc Aggregate(stats []*stat.Stat) (aggregate StatsAggregate) {\n\tif stats == nil || len(stats) == 0 {\n\t\treturn StatsAggregate{}\n\t}\n\n\taggregate = StatsAggregate{Min : stats[0].Value, Max : stats[0].Value, Count : len(stats)}\n\tsum := 0.0\n\tfor i := range stats {\n\t\tv := stats[i].Value\n\n\t\tsum += v\n\n\t\tif v < aggregate.Min {\n\t\t\taggregate.Min = v\n\t\t}\n\n\t\tif v > aggregate.Max {\n\t\t\taggregate.Max = v\n\t\t}\n\t}\n\taggregate.Average = sum / float64(len(stats))\n\n\treturn\n}\n\n\n\n\n\n\n\nfunc AppendStatsAggregate(a, b StatsAggregate) (aggregate StatsAggregate) ", "output": "{\n\tif (a.Count == 0) {\n\t\treturn b\n\t}\n\n\tif (b.Count == 0) {\n\t\treturn a\n\t}\n\n\taggregate.Average = ( (a.Average * float64(a.Count)) + (b.Average * float64(b.Count)) ) / float64(a.Count + b.Count)\n\taggregate.Min = math.Min(a.Min, b.Min)\n\taggregate.Max = math.Max(a.Max, b.Max)\n\taggregate.Count = a.Count + b.Count\n\treturn\n}"} {"input": "package contextutil_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/arjantop/cuirass/util/contextutil\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\nfunc TestDoWithCancelErrorReturned(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\terr := contextutil.DoWithCancel(ctx, func() {}, func() error {\n\t\treturn errors.New(\"foo\")\n\t})\n\tassert.Equal(t, errors.New(\"foo\"), err)\n}\n\nfunc TestDoWithCancelTimeout(t *testing.T) {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond)\n\tdefer cancel()\n\tvar called bool\n\terr := contextutil.DoWithCancel(ctx, func() { called = true }, func() error {\n\t\ttime.Sleep(2 * time.Nanosecond)\n\t\treturn nil\n\t})\n\tassert.Equal(t, context.DeadlineExceeded, err)\n}\n\nfunc TestDoErrorReturned(t *testing.T) ", "output": "{\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\terr := contextutil.Do(ctx, func() error {\n\t\treturn errors.New(\"foo\")\n\t})\n\tassert.Equal(t, errors.New(\"foo\"), err)\n}"} {"input": "package bits_test\n\nimport (\n\t\"github.com/twmb/bits\"\n\t\"testing\"\n)\n\nfunc TestSet(t *testing.T) {\n\tfor i := 0; i < 256; i++ {\n\t\tif int(bits.SetU32(uint32(i))) != bits.Hamming(i, 0) {\n\t\t\tt.Errorf(\"Error in set: wanted %v for %v, got %v\",\n\t\t\t\tbits.Hamming(i, 0), i, bits.SetU32(uint32(i)))\n\t\t}\n\t}\n}\n\n\nfunc BenchmarkSetKernighan(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetKernighan(uint(i))\n\t}\n}\nfunc BenchmarkSetU32(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetU32(uint32(i))\n\t}\n}\nfunc BenchmarkSetU64(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetU64(uint64(i))\n\t}\n}\n\nfunc BenchmarkSetTable(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetTable(i)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\n\t\"github.com/opensourceorg/api/license\"\n)\n\ntype Blobs struct {\n\tLicenses license.Licenses\n\tLicenseIdMap map[string]license.License\n\tLicenseTagMap map[string][]license.License\n}\n\nfunc loadBlob(path string, blob *Blobs) error {\n\tlicenses, err := license.LoadLicensesFiles(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlicenseIdMap := licenses.GetIdMap()\n\tlicenseTagMap := licenses.GetTagMap()\n\n\tblob.Licenses = licenses\n\tblob.LicenseIdMap = licenseIdMap\n\tblob.LicenseTagMap = licenseTagMap\n\n\treturn nil\n}\n\n\n\nfunc Reloader(file string, target *Blobs) ", "output": "{\n\tif err := loadBlob(file, target); err != nil {\n\t\tpanic(err)\n\t}\n\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGHUP)\n\tfor _ = range c {\n\t\tif err := loadBlob(file, target); err != nil {\n\t\t\tlog.Printf(\"Error! Can not reload the JSON! - %s\", err)\n\t\t\tcontinue\n\t\t}\n\t}\n}"} {"input": "package iso20022\n\n\ntype ATMTransactionAmounts6 struct {\n\n\tCurrency *ActiveCurrencyCode `xml:\"Ccy,omitempty\"`\n\n\tMaximumPossibleAmount *ImpliedCurrencyAndAmount `xml:\"MaxPssblAmt,omitempty\"`\n\n\tMinimumPossibleAmount *ImpliedCurrencyAndAmount `xml:\"MinPssblAmt,omitempty\"`\n\n\tAdditionalAmount []*ATMTransactionAmounts7 `xml:\"AddtlAmt,omitempty\"`\n}\n\n\n\nfunc (a *ATMTransactionAmounts6) SetMaximumPossibleAmount(value, currency string) {\n\ta.MaximumPossibleAmount = NewImpliedCurrencyAndAmount(value, currency)\n}\n\nfunc (a *ATMTransactionAmounts6) SetMinimumPossibleAmount(value, currency string) {\n\ta.MinimumPossibleAmount = NewImpliedCurrencyAndAmount(value, currency)\n}\n\nfunc (a *ATMTransactionAmounts6) AddAdditionalAmount() *ATMTransactionAmounts7 {\n\tnewValue := new(ATMTransactionAmounts7)\n\ta.AdditionalAmount = append(a.AdditionalAmount, newValue)\n\treturn newValue\n}\n\nfunc (a *ATMTransactionAmounts6) SetCurrency(value string) ", "output": "{\n\ta.Currency = (*ActiveCurrencyCode)(&value)\n}"} {"input": "package systray\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\nfunc nativeLoop() {\n\tC.nativeLoop()\n}\n\nfunc quit() {\n\tC.quit()\n}\n\n\n\n\nfunc SetIcon(iconBytes []byte) {\n\tcstr := (*C.char)(unsafe.Pointer(&iconBytes[0]))\n\tC.setIcon(cstr, (C.int)(len(iconBytes)))\n}\n\n\nfunc SetTitle(title string) {\n\tC.setTitle(C.CString(title))\n}\n\n\n\nfunc SetTooltip(tooltip string) {\n\tC.setTooltip(C.CString(tooltip))\n}\n\n\n\n\nfunc systray_ready() {\n\tsystrayReady()\n}\n\n\nfunc systray_menu_item_selected(cId C.int) {\n\tsystrayMenuItemSelected(int32(cId))\n}\n\nfunc addOrUpdateMenuItem(item *MenuItem) ", "output": "{\n\tvar disabled C.short = 0\n\tif item.disabled {\n\t\tdisabled = 1\n\t}\n\tvar checked C.short = 0\n\tif item.checked {\n\t\tchecked = 1\n\t}\n\tC.add_or_update_menu_item(\n\n\t\tC.int(item.id),\n\t\tC.CString(item.title),\n\t\tC.CString(item.tooltip),\n\t\tdisabled,\n\t\tchecked,\n\t)\n}"} {"input": "package displayers\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/digitalocean/doctl/do\"\n)\n\ntype Size struct {\n\tSizes do.Sizes\n}\n\nvar _ Displayable = &Size{}\n\nfunc (si *Size) JSON(out io.Writer) error {\n\treturn writeJSON(si.Sizes, out)\n}\n\n\n\nfunc (si *Size) ColMap() map[string]string {\n\treturn map[string]string{\n\t\t\"Slug\": \"Slug\", \"Memory\": \"Memory\", \"VCPUs\": \"VCPUs\",\n\t\t\"Disk\": \"Disk\", \"PriceMonthly\": \"Price Monthly\",\n\t\t\"PriceHourly\": \"Price Hourly\",\n\t}\n}\n\nfunc (si *Size) KV() []map[string]interface{} {\n\tout := []map[string]interface{}{}\n\n\tfor _, s := range si.Sizes {\n\t\to := map[string]interface{}{\n\t\t\t\"Slug\": s.Slug, \"Memory\": s.Memory, \"VCPUs\": s.Vcpus,\n\t\t\t\"Disk\": s.Disk, \"PriceMonthly\": fmt.Sprintf(\"%0.2f\", s.PriceMonthly),\n\t\t\t\"PriceHourly\": s.PriceHourly,\n\t\t}\n\n\t\tout = append(out, o)\n\t}\n\n\treturn out\n}\n\nfunc (si *Size) Cols() []string ", "output": "{\n\treturn []string{\n\t\t\"Slug\", \"Memory\", \"VCPUs\", \"Disk\", \"PriceMonthly\", \"PriceHourly\",\n\t}\n}"} {"input": "package build\n\nimport \"github.com/docker/docker/api/server/router\"\n\n\ntype buildRouter struct {\n\tbackend Backend\n\troutes []router.Route\n}\n\n\nfunc NewRouter(b Backend) router.Router {\n\tr := &buildRouter{\n\t\tbackend: b,\n\t}\n\tr.initRoutes()\n\treturn r\n}\n\n\n\n\nfunc (r *buildRouter) initRoutes() {\n\tr.routes = []router.Route{\n\t\trouter.NewPostRoute(\"/build\", r.postBuild),\n\t}\n}\n\nfunc (r *buildRouter) Routes() []router.Route ", "output": "{\n\treturn r.routes\n}"} {"input": "package migrations\n\nimport (\n\t\"database/sql\"\n\n\t\"github.com/pressly/goose\"\n)\n\nfunc init() {\n\tgoose.AddMigration(up00002, down00002)\n}\n\n\n\nfunc down00002(tx *sql.Tx) error {\n\t_, err := tx.Exec(`DROP TABLE users`)\n\treturn err\n}\n\nfunc up00002(tx *sql.Tx) error ", "output": "{\n\t_, err := tx.Exec(`CREATE TABLE IF NOT EXISTS users (email text)`)\n\treturn err\n}"} {"input": "package internal\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\ntype ContextKey string\n\nconst userAgent = \"gcloud-golang/0.1\"\n\n\n\n\ntype Transport struct {\n\tBase http.RoundTripper\n}\n\n\n\nfunc (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq = cloneRequest(req)\n\tua := req.Header.Get(\"User-Agent\")\n\tif ua == \"\" {\n\t\tua = userAgent\n\t} else {\n\t\tua = fmt.Sprintf(\"%s;%s\", ua, userAgent)\n\t}\n\treq.Header.Set(\"User-Agent\", ua)\n\treturn t.Base.RoundTrip(req)\n}\n\n\n\nfunc cloneRequest(r *http.Request) *http.Request {\n\tr2 := new(http.Request)\n\t*r2 = *r\n\tr2.Header = make(http.Header)\n\tfor k, s := range r.Header {\n\t\tr2.Header[k] = s\n\t}\n\treturn r2\n}\n\n\nfunc ProjID(ctx context.Context) string {\n\treturn ctx.Value(ContextKey(\"base\")).(map[string]interface{})[\"project_id\"].(string)\n}\n\n\n\n\n\nfunc HttpClient(ctx context.Context) *http.Client {\n\treturn ctx.Value(ContextKey(\"base\")).(map[string]interface{})[\"http_client\"].(*http.Client)\n}\n\nfunc Namespace(ctx context.Context) string ", "output": "{\n\tv := ctx.Value(ContextKey(\"namespace\"))\n\tif v == nil {\n\t\treturn \"\"\n\t} else {\n\t\treturn v.(string)\n\t}\n}"} {"input": "package app\n\nimport (\n\t\"net/url\"\n)\n\ntype Service interface {\n\tProxyPath() string\n\tURL() string\n\tBasicAuth() (username, password string, ok bool)\n\tAddSecret(parameters url.Values)\n}\n\ntype basicAuthService struct {\n\tproxyPath, url, clientId, clientSecret string\n}\n\nfunc (s basicAuthService) ProxyPath() string {\n\treturn s.proxyPath\n}\n\n\n\nfunc (s basicAuthService) BasicAuth() (string, string, bool) {\n\treturn s.clientId, s.clientSecret, true\n}\n\nfunc (s basicAuthService) AddSecret(parameters url.Values) {\n}\n\ntype addParameterService struct {\n\tproxyPath, url, parameterName, clientSecret string\n}\n\nfunc (s addParameterService) ProxyPath() string {\n\treturn s.proxyPath\n}\n\nfunc (s addParameterService) URL() string {\n\treturn s.url\n}\n\nfunc (s addParameterService) BasicAuth() (string, string, bool) {\n\treturn \"\", \"\", false\n}\n\nfunc (s addParameterService) AddSecret(parameters url.Values) {\n\tparameters.Add(s.parameterName, s.clientSecret)\n}\n\nfunc BasicAuthService(proxyPath, url, clientId, clientSecret string) Service {\n\treturn basicAuthService{proxyPath, url, clientId, clientSecret}\n}\n\nfunc AddParameterService(proxyPath, url, parameterName, clientSecret string) Service {\n\treturn addParameterService{proxyPath, url, parameterName, clientSecret}\n}\n\nfunc (s basicAuthService) URL() string ", "output": "{\n\treturn s.url\n}"} {"input": "package iso20022\n\n\ntype PlainCardData4 struct {\n\n\tPAN *Min8Max28NumericText `xml:\"PAN\"`\n\n\tCardSequenceNumber *Min2Max3NumericText `xml:\"CardSeqNb,omitempty\"`\n\n\tEffectiveDate *Max10Text `xml:\"FctvDt,omitempty\"`\n\n\tExpiryDate *Max10Text `xml:\"XpryDt\"`\n\n\tServiceCode *Exact3NumericText `xml:\"SvcCd,omitempty\"`\n\n\tTrackData []*TrackData1 `xml:\"TrckData,omitempty\"`\n\n\tCardSecurityCode *CardSecurityInformation1 `xml:\"CardSctyCd,omitempty\"`\n}\n\nfunc (p *PlainCardData4) SetPAN(value string) {\n\tp.PAN = (*Min8Max28NumericText)(&value)\n}\n\n\n\nfunc (p *PlainCardData4) SetEffectiveDate(value string) {\n\tp.EffectiveDate = (*Max10Text)(&value)\n}\n\nfunc (p *PlainCardData4) SetExpiryDate(value string) {\n\tp.ExpiryDate = (*Max10Text)(&value)\n}\n\nfunc (p *PlainCardData4) SetServiceCode(value string) {\n\tp.ServiceCode = (*Exact3NumericText)(&value)\n}\n\nfunc (p *PlainCardData4) AddTrackData() *TrackData1 {\n\tnewValue := new(TrackData1)\n\tp.TrackData = append(p.TrackData, newValue)\n\treturn newValue\n}\n\nfunc (p *PlainCardData4) AddCardSecurityCode() *CardSecurityInformation1 {\n\tp.CardSecurityCode = new(CardSecurityInformation1)\n\treturn p.CardSecurityCode\n}\n\nfunc (p *PlainCardData4) SetCardSequenceNumber(value string) ", "output": "{\n\tp.CardSequenceNumber = (*Min2Max3NumericText)(&value)\n}"} {"input": "package geth\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n\ntype Strings struct{ strs []string }\n\n\nfunc (s *Strings) Size() int {\n\treturn len(s.strs)\n}\n\n\nfunc (s *Strings) Get(index int) (str string, _ error) {\n\tif index < 0 || index >= len(s.strs) {\n\t\treturn \"\", errors.New(\"index out of bounds\")\n\t}\n\treturn s.strs[index], nil\n}\n\n\nfunc (s *Strings) Set(index int, str string) error {\n\tif index < 0 || index >= len(s.strs) {\n\t\treturn errors.New(\"index out of bounds\")\n\t}\n\ts.strs[index] = str\n\treturn nil\n}\n\n\n\n\nfunc (s *Strings) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%v\", s.strs)\n}"} {"input": "package ergo_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/gima/ergo/v1\"\n\t\"github.com/gima/ergo/v1/pp\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\n\n\n\n\nfunc TestComposer_AddLinked(t *testing.T) {\n\tolde := fmt.Errorf(\"\")\n\toldE := ergo.New(\"\").Err()\n\tE := ergo.New(\"\").AddLinked(olde, oldE).Err()\n\trequire.Equal(t, 2, E.Linked().Len())\n\trequire.Equal(t, olde, E.Linked().Get(0))\n\trequire.Equal(t, oldE, E.Linked().Get(1))\n}\n\n\n\nfunc TestComposer_SetCause(t *testing.T) {\n\toldE := ergo.New(\"\").Err()\n\tE := ergo.New(\"\").SetCause(oldE).Err()\n\trequire.Equal(t, oldE, E.Cause())\n\n\tolde := fmt.Errorf(\"\")\n\tE = ergo.New(\"\").SetCause(olde).Err()\n\trequire.Equal(t, olde, E.Cause())\n}\n\n\n\nfunc TestComposer_SetPub(t *testing.T) {\n\tE := ergo.New(\"\").SetPub(\"Public Message\").Err()\n\trequire.Equal(t, \"Public Message\", E.PublicError())\n}\n\n\n\nfunc TestComposer_SkipStackRetainsOne(t *testing.T) {\n\tE := ergo.New(\"\").\n\t\tSkipStack(-1).\n\t\tSkipStack(1000).\n\t\tSkipStack(1).\n\t\tSkipStack(0).\n\t\tSkipStack(-1).\n\t\tErr()\n\n\trequire.Equal(t, 1, E.StackTrace().Len())\n}\n\nfunc TestComposer_AddContext(t *testing.T) ", "output": "{\n\tE := ergo.New(\"\").Err()\n\trequire.Equal(t, 0, E.Context().Len())\n\n\tE = ergo.New(\"\").AddContext(\"K1\", \"V1\").Err()\n\trequire.Equal(t, 1, E.Context().Len())\n\tk, v := E.Context().Get(0)\n\trequire.Equal(t, \"K1V1\", k+v)\n\n\tE = ergo.New(\"\").AddContextFrom(pp.Map{\"K1\": \"V1\"}).Err()\n\trequire.Equal(t, 1, E.Context().Len())\n\tk, v = E.Context().Get(0)\n\trequire.Equal(t, \"K1V1\", k+v)\n}"} {"input": "package log15\n\nimport (\n\t\"sync/atomic\"\n\t\"unsafe\"\n)\n\n\n\ntype swapHandler struct {\n\thandler unsafe.Pointer\n}\n\nfunc (h *swapHandler) Log(r *Record) error {\n\treturn (*(*Handler)(atomic.LoadPointer(&h.handler))).Log(r)\n}\n\n\n\nfunc (h *swapHandler) Swap(newHandler Handler) ", "output": "{\n\tatomic.StorePointer(&h.handler, unsafe.Pointer(&newHandler))\n}"} {"input": "package types\n\nimport (\n\t\"math\"\n)\n\n\n\n\n\nfunc RoundFloat(val float64) float64 {\n\tv, frac := math.Modf(val)\n\tif val >= 0.0 {\n\t\tif frac > 0.5 || (frac == 0.5 && uint64(v)%2 != 0) {\n\t\t\tv += 1.0\n\t\t}\n\t} else {\n\t\tif frac < -0.5 || (frac == -0.5 && uint64(v)%2 != 0) {\n\t\t\tv -= 1.0\n\t\t}\n\t}\n\n\treturn v\n}\n\nfunc getMaxFloat(flen int, decimal int) float64 {\n\tintPartLen := flen - decimal\n\tf := math.Pow10(intPartLen)\n\tf -= math.Pow10(-decimal)\n\treturn f\n}\n\n\n\n\n\nfunc TruncateFloat(f float64, flen int, decimal int) (float64, error) {\n\tif math.IsNaN(f) {\n\t\treturn 0, nil\n\t}\n\n\tmaxF := getMaxFloat(flen, decimal)\n\n\tif !math.IsInf(f, 0) {\n\t\tf = truncateFloat(f, decimal)\n\t}\n\n\tif f > maxF {\n\t\tf = maxF\n\t} else if f < -maxF {\n\t\tf = -maxF\n\t}\n\n\treturn f, nil\n}\n\nfunc truncateFloat(f float64, decimal int) float64 ", "output": "{\n\tpow := math.Pow10(decimal)\n\tt := (f - math.Floor(f)) * pow\n\n\tround := RoundFloat(t)\n\n\tf = math.Floor(f) + round/pow\n\treturn f\n}"} {"input": "package hook\n\nimport (\n\t\"fmt\"\n\n\t\"gopkg.in/juju/charm.v6-unstable/hooks\"\n\t\"gopkg.in/juju/names.v2\"\n)\n\n\nconst (\n\tLeaderElected hooks.Kind = \"leader-elected\"\n\tLeaderDeposed hooks.Kind = \"leader-deposed\"\n\tLeaderSettingsChanged hooks.Kind = \"leader-settings-changed\"\n)\n\n\n\ntype Info struct {\n\tKind hooks.Kind `yaml:\"kind\"`\n\n\tRelationId int `yaml:\"relation-id,omitempty\"`\n\n\tRemoteUnit string `yaml:\"remote-unit,omitempty\"`\n\n\tChangeVersion int64 `yaml:\"change-version,omitempty\"`\n\n\tStorageId string `yaml:\"storage-id,omitempty\"`\n}\n\n\n\n\n\n\ntype Committer interface {\n\tCommitHook(Info) error\n}\n\n\n\ntype Validator interface {\n\tValidateHook(Info) error\n}\n\nfunc (hi Info) Validate() error ", "output": "{\n\tswitch hi.Kind {\n\tcase hooks.RelationJoined, hooks.RelationChanged, hooks.RelationDeparted:\n\t\tif hi.RemoteUnit == \"\" {\n\t\t\treturn fmt.Errorf(\"%q hook requires a remote unit\", hi.Kind)\n\t\t}\n\t\tfallthrough\n\tcase hooks.Install, hooks.Start, hooks.ConfigChanged, hooks.UpgradeCharm, hooks.Stop, hooks.RelationBroken,\n\t\thooks.CollectMetrics, hooks.MeterStatusChanged, hooks.UpdateStatus:\n\t\treturn nil\n\tcase hooks.Action:\n\t\treturn fmt.Errorf(\"hooks.Kind Action is deprecated\")\n\tcase hooks.StorageAttached, hooks.StorageDetaching:\n\t\tif !names.IsValidStorage(hi.StorageId) {\n\t\t\treturn fmt.Errorf(\"invalid storage ID %q\", hi.StorageId)\n\t\t}\n\t\treturn nil\n\tcase LeaderElected, LeaderDeposed, LeaderSettingsChanged:\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown hook kind %q\", hi.Kind)\n}"} {"input": "package core\n\nimport (\n\t\"github.com/google/blueprint\"\n)\n\ntype generateBinary struct {\n\tgenerateLibrary\n}\n\n\nvar _ generateLibraryInterface = (*generateBinary)(nil)\nvar _ singleOutputModule = (*generateBinary)(nil)\nvar _ splittable = (*generateBinary)(nil)\nvar _ blueprint.Module = (*generateBinary)(nil)\n\nfunc (m *generateBinary) generateInouts(ctx blueprint.ModuleContext, g generatorBackend) []inout {\n\treturn generateLibraryInouts(m, ctx, g, m.Properties.Headers)\n}\n\n\n\n\n\n\n\nfunc (m *generateBinary) outputFileName() string {\n\treturn m.altName() + m.libExtension()\n}\n\n\n\nfunc (m *generateBinary) GenerateBuildActions(ctx blueprint.ModuleContext) {\n\tif isEnabled(m) {\n\t\tg := getBackend(ctx)\n\t\tg.genBinaryActions(m, ctx)\n\t}\n}\n\n\n\nfunc genBinaryFactory(config *bobConfig) (blueprint.Module, []interface{}) {\n\tmodule := &generateBinary{}\n\tmodule.generateCommon.init(&config.Properties, GenerateProps{})\n\n\treturn module, []interface{}{\n\t\t&module.SimpleName.Properties,\n\t\t&module.generateCommon.Properties,\n\t\t&module.Properties,\n\t}\n}\n\nfunc (m *generateBinary) libExtension() string ", "output": "{\n\treturn \"\"\n}"} {"input": "package version\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\nvar (\n\tGitCommit string\n\n\tVersion = \"0.13.0\"\n\n\tVersionPrerelease = \"dev\"\n\n\tVersionMetadata = \"\"\n)\n\n\ntype VersionInfo struct {\n\tRevision string\n\tVersion string\n\tVersionPrerelease string\n\tVersionMetadata string\n}\n\n\n\n\n\nfunc (c *VersionInfo) VersionNumber(rev bool) string {\n\tvar versionString bytes.Buffer\n\n\tfmt.Fprintf(&versionString, \"v%s\", c.Version)\n\n\tif c.VersionPrerelease != \"\" {\n\t\tfmt.Fprintf(&versionString, \"-%s\", c.VersionPrerelease)\n\t}\n\n\tif c.VersionMetadata != \"\" {\n\t\tfmt.Fprintf(&versionString, \"+%s\", c.VersionMetadata)\n\t}\n\n\tif rev && c.Revision != \"\" {\n\t\tfmt.Fprintf(&versionString, \" (%s)\", c.Revision)\n\t}\n\n\treturn versionString.String()\n}\n\nfunc GetVersion() *VersionInfo ", "output": "{\n\tver := Version\n\trel := VersionPrerelease\n\tmd := VersionMetadata\n\n\treturn &VersionInfo{\n\t\tRevision: GitCommit,\n\t\tVersion: ver,\n\t\tVersionPrerelease: rel,\n\t\tVersionMetadata: md,\n\t}\n}"} {"input": "package iso20022\n\n\ntype PaymentTransaction17 struct {\n\n\tSettlementAmount *ActiveCurrencyAndAmount `xml:\"SttlmAmt,omitempty\"`\n\n\tSettlementDate *ISODate `xml:\"SttlmDt,omitempty\"`\n\n\tPaymentInstrument *PaymentInstrument9Choice `xml:\"PmtInstrm,omitempty\"`\n}\n\n\n\nfunc (p *PaymentTransaction17) SetSettlementDate(value string) {\n\tp.SettlementDate = (*ISODate)(&value)\n}\n\nfunc (p *PaymentTransaction17) AddPaymentInstrument() *PaymentInstrument9Choice {\n\tp.PaymentInstrument = new(PaymentInstrument9Choice)\n\treturn p.PaymentInstrument\n}\n\nfunc (p *PaymentTransaction17) SetSettlementAmount(value, currency string) ", "output": "{\n\tp.SettlementAmount = NewActiveCurrencyAndAmount(value, currency)\n}"} {"input": "package runconfig\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\nfunc validateNetMode(vals *validateNM) error {\n\n\tif (vals.netMode.IsHost() || vals.netMode.IsContainer()) && *vals.flHostname != \"\" {\n\t\treturn ErrConflictNetworkHostname\n\t}\n\n\tif vals.netMode.IsHost() && vals.flLinks.Len() > 0 {\n\t\treturn ErrConflictHostNetworkAndLinks\n\t}\n\n\tif vals.netMode.IsContainer() && vals.flLinks.Len() > 0 {\n\t\treturn ErrConflictContainerNetworkAndLinks\n\t}\n\n\tif (vals.netMode.IsHost() || vals.netMode.IsContainer()) && vals.flDNS.Len() > 0 {\n\t\treturn ErrConflictNetworkAndDNS\n\t}\n\n\tif (vals.netMode.IsContainer() || vals.netMode.IsHost()) && vals.flExtraHosts.Len() > 0 {\n\t\treturn ErrConflictNetworkHosts\n\t}\n\n\tif (vals.netMode.IsContainer() || vals.netMode.IsHost()) && *vals.flMacAddress != \"\" {\n\t\treturn ErrConflictContainerNetworkAndMac\n\t}\n\n\tif vals.netMode.IsContainer() && (vals.flPublish.Len() > 0 || *vals.flPublishAll == true) {\n\t\treturn ErrConflictNetworkPublishPorts\n\t}\n\n\tif vals.netMode.IsContainer() && vals.flExpose.Len() > 0 {\n\t\treturn ErrConflictNetworkExposePorts\n\t}\n\treturn nil\n}\n\nfunc parseNetMode(netMode string) (NetworkMode, error) ", "output": "{\n\tparts := strings.Split(netMode, \":\")\n\tswitch mode := parts[0]; mode {\n\tcase \"default\", \"bridge\", \"none\", \"host\":\n\tcase \"container\":\n\t\tif len(parts) < 2 || parts[1] == \"\" {\n\t\t\treturn \"\", fmt.Errorf(\"invalid container format container:\")\n\t\t}\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"invalid --net: %s\", netMode)\n\t}\n\treturn NetworkMode(netMode), nil\n}"} {"input": "package cronjob\n\nimport (\n\tcontext \"context\"\n\n\tv1beta1 \"k8s.io/client-go/informers/batch/v1beta1\"\n\tfactory \"knative.dev/pkg/client/injection/kube/informers/factory\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Default.RegisterInformer(withInformer)\n}\n\n\ntype Key struct{}\n\n\n\n\nfunc Get(ctx context.Context) v1beta1.CronJobInformer {\n\tuntyped := ctx.Value(Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch k8s.io/client-go/informers/batch/v1beta1.CronJobInformer from context.\")\n\t}\n\treturn untyped.(v1beta1.CronJobInformer)\n}\n\nfunc withInformer(ctx context.Context) (context.Context, controller.Informer) ", "output": "{\n\tf := factory.Get(ctx)\n\tinf := f.Batch().V1beta1().CronJobs()\n\treturn context.WithValue(ctx, Key{}, inf), inf.Informer()\n}"} {"input": "package associations_test\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/gobuffalo/pop/associations\"\n\t\"github.com/gobuffalo/pop/nulls\"\n\t\"github.com/stretchr/testify/require\"\n)\n\ntype FooHasMany struct {\n\tID int `db:\"id\"`\n\tBarHasManies *barHasManies `has_many:\"bar_has_manies\"`\n}\n\ntype barHasMany struct {\n\tTitle string `db:\"title\"`\n\tFooHasManyID nulls.Int `db:\"foo_has_many_id\"`\n}\n\ntype barHasManies []barHasMany\n\n\n\nfunc Test_Has_Many_SetValue(t *testing.T) {\n\ta := require.New(t)\n\tfoo := FooHasMany{ID: 1, BarHasManies: &barHasManies{{Title: \"bar\"}}}\n\n\tas, _ := associations.ForStruct(&foo)\n\ta.Equal(len(as), 1)\n\n\tca, ok := as[0].(associations.AssociationAfterCreatable)\n\ta.True(ok)\n\n\tca.AfterSetup()\n\ta.Equal(foo.ID, (*foo.BarHasManies)[0].FooHasManyID.Interface().(int))\n}\n\nfunc Test_Has_Many_Association(t *testing.T) ", "output": "{\n\ta := require.New(t)\n\n\tid := 1\n\tfoo := FooHasMany{ID: 1}\n\n\tas, err := associations.ForStruct(&foo)\n\n\ta.NoError(err)\n\ta.Equal(len(as), 1)\n\ta.Equal(reflect.Slice, as[0].Kind())\n\n\twhere, args := as[0].Constraint()\n\ta.Equal(\"foo_has_many_id = ?\", where)\n\ta.Equal(id, args[0].(int))\n}"} {"input": "package auth\n\nimport (\n\t\"context\"\n)\n\ntype tokenNop struct{}\n\nfunc (t *tokenNop) enable() {}\nfunc (t *tokenNop) disable() {}\nfunc (t *tokenNop) invalidateUser(string) {}\nfunc (t *tokenNop) genTokenPrefix() (string, error) { return \"\", nil }\n\nfunc (t *tokenNop) assign(ctx context.Context, username string, revision uint64) (string, error) {\n\treturn \"\", ErrAuthFailed\n}\nfunc newTokenProviderNop() (*tokenNop, error) {\n\treturn &tokenNop{}, nil\n}\n\nfunc (t *tokenNop) info(ctx context.Context, token string, rev uint64) (*AuthInfo, bool) ", "output": "{\n\treturn nil, false\n}"} {"input": "package validate\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nvar (\n\tlogMutex = &sync.Mutex{}\n)\n\n\n\nfunc TestDebug(t *testing.T) ", "output": "{\n\tif !enableLongTests {\n\t\tskipNotify(t)\n\t\tt.SkipNow()\n\t}\n\ttmpFile, _ := ioutil.TempFile(\"\", \"debug-test\")\n\ttmpName := tmpFile.Name()\n\tdefer func() {\n\t\tDebug = false\n\t\tlogMutex.Unlock()\n\t\tos.Remove(tmpName)\n\t}()\n\n\tlogMutex.Lock()\n\tDebug = true\n\tdebugOptions()\n\tdefer func() {\n\t\tvalidateLogger.SetOutput(os.Stdout)\n\t}()\n\n\tvalidateLogger.SetOutput(tmpFile)\n\n\tdebugLog(\"A debug\")\n\tDebug = false\n\ttmpFile.Close()\n\n\tflushed, _ := os.Open(tmpName)\n\tbuf := make([]byte, 500)\n\tflushed.Read(buf)\n\tvalidateLogger.SetOutput(os.Stdout)\n\tassert.Contains(t, string(buf), \"A debug\")\n}"} {"input": "package spatial\n\nimport \"fmt\"\n\nfunc (p Polygon) string() string {\n\ts := \"(\"\n\tfor _, line := range p {\n\t\ts += fmt.Sprintf(\"%v, \", line)\n\t}\n\treturn s[:len(s)-2] + \")\"\n}\n\n\n\nfunc (l Line) string() string ", "output": "{\n\ts := \"\"\n\tfor _, point := range l {\n\t\ts += fmt.Sprintf(\"%v, \", point)\n\t}\n\treturn s[:len(s)-2]\n}"} {"input": "package application\n\nimport (\n\t\"encoding/base64\"\n\t\"github.com/gorilla/securecookie\"\n\t\"net/http\"\n\t\"testing\"\n)\n\n\nconst cookieName = \"recaptcha\"\nconst testHashKey = \"RovMQmutMbSogUuGQFZYLb37jwgwFNuMR7wrEz9EILQ9W039UHCFlCfkpX1EbecktHA563XX+7clPRinBPeaeQ==\"\nconst testBlockKey = \"+sSXCAbwswiYNqHx4zCuJJTD3hmRQp4f4uJKy+aFL70=\"\n\nfunc generateGorillaSecureCookie() *securecookie.SecureCookie {\n\thashKey, _ := base64.StdEncoding.DecodeString(testHashKey)\n\tblockKey, _ := base64.StdEncoding.DecodeString(testBlockKey)\n\treturn securecookie.New(hashKey, blockKey)\n}\n\nfunc TestNewSecureRecaptchaCookie(t *testing.T) {\n\tsecureRecaptchaCookie1 := NewSecureRecaptchaCookie(cookieName, nil, generateGorillaSecureCookie())\n\tif secureRecaptchaCookie1.Name != cookieName || len(secureRecaptchaCookie1.Value) != 0 {\n\t\tt.Error(\"The new secure cookie based on an empty cookie should have no value\")\n\t}\n\n\tvalidCookie := &http.Cookie{Value: \"Some Value\"}\n\tsecureRecaptchaCookie2 := NewSecureRecaptchaCookie(cookieName, validCookie, generateGorillaSecureCookie())\n\tif secureRecaptchaCookie2.Name != cookieName || len(secureRecaptchaCookie2.Value) == 0 {\n\t\tt.Error(\"The new secure cookie based on a valid cookie should have a value\")\n\t}\n}\n\n\n\nfunc TestSecureRecaptchaCookie_Encode(t *testing.T) ", "output": "{\n\tvalidCookie := &http.Cookie{Value: \"Some Value\"}\n\n\tsecureRecaptchaCookie := NewSecureRecaptchaCookie(cookieName, validCookie, generateGorillaSecureCookie())\n\tsecureRecaptchaCookie.Value = secureRecaptchaCookie.Encode(validCookie.Value)\n\n\tif secureRecaptchaCookie.IsValid(validCookie.Value) != true {\n\t\tt.Error(\"The cookie value should have been encoded and decoded correctly\")\n\t}\n}"} {"input": "package glw\n\nimport \"golang.org/x/mobile/gl\"\n\ntype A2fv gl.Attrib\n\nfunc (a A2fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A2fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A2fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 2, gl.FLOAT, false, 0, 0)\n}\n\ntype A3fv gl.Attrib\n\nfunc (a A3fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A3fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A3fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 3, gl.FLOAT, false, 0, 0)\n}\n\ntype A4fv gl.Attrib\n\nfunc (a A4fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A4fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\n\n\nfunc (a A4fv) Pointer() ", "output": "{\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 4, gl.FLOAT, false, 0, 0)\n}"} {"input": "package cli\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/alexyer/ghost/client\"\n)\n\n\n\n\n\n\nfunc ObtainUnixSocketClient(socket string) (*client.GhostClient, error) {\n\treturn connect(socket, \"unix\")\n}\n\nfunc connect(addr, network string) (*client.GhostClient, error) {\n\tc := client.New(&client.Options{\n\t\tAddr: addr,\n\t\tNetwork: network,\n\t})\n\n\tif _, err := c.Ping(); err != nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"cli-ghost: cannot obtain connection to %s\", addr))\n\t}\n\n\tlog.Printf(\"Connection to %s is successfull.\", addr)\n\treturn c, nil\n}\n\nfunc ObtainClient(host string, port int) (*client.GhostClient, error) ", "output": "{\n\taddr := fmt.Sprintf(\"%s:%d\", host, port)\n\treturn connect(addr, \"tcp\")\n}"} {"input": "package command\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/bitrise-io/go-utils/pathutil\"\n)\n\n\nfunc CopyFile(src, dst string) error {\n\tisDir, err := pathutil.IsDirExists(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isDir {\n\t\treturn errors.New(\"Source is a directory: \" + src)\n\t}\n\targs := []string{src, dst}\n\treturn RunCommand(\"rsync\", args...)\n}\n\n\n\n\n\nfunc RemoveDir(dirPth string) error {\n\tif exist, err := pathutil.IsPathExists(dirPth); err != nil {\n\t\treturn err\n\t} else if exist {\n\t\tif err := os.RemoveAll(dirPth); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc RemoveFile(pth string) error {\n\tif exist, err := pathutil.IsPathExists(pth); err != nil {\n\t\treturn err\n\t} else if exist {\n\t\tif err := os.Remove(pth); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc CopyDir(src, dst string, isOnlyContent bool) error ", "output": "{\n\tif isOnlyContent && !strings.HasSuffix(src, \"/\") {\n\t\tsrc = src + \"/\"\n\t}\n\targs := []string{\"-ar\", src, dst}\n\treturn RunCommand(\"rsync\", args...)\n}"} {"input": "package watch\n\n\n\ntype FilterFunc func(in Event) (out Event, keep bool)\n\n\n\n\n\n\n\n\n\n\nfunc Filter(w Interface, f FilterFunc) Interface {\n\tfw := &filteredWatch{\n\t\tincoming: w,\n\t\tresult: make(chan Event),\n\t\tf: f,\n\t}\n\tgo fw.loop()\n\treturn fw\n}\n\ntype filteredWatch struct {\n\tincoming Interface\n\tresult chan Event\n\tf FilterFunc\n}\n\n\n\n\n\nfunc (fw *filteredWatch) Stop() {\n\tfw.incoming.Stop()\n}\n\n\nfunc (fw *filteredWatch) loop() {\n\tdefer close(fw.result)\n\tfor {\n\t\tevent, ok := <-fw.incoming.ResultChan()\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tfiltered, keep := fw.f(event)\n\t\tif keep {\n\t\t\tfw.result <- filtered\n\t\t}\n\t}\n}\n\nfunc (fw *filteredWatch) ResultChan() <-chan Event ", "output": "{\n\treturn fw.result\n}"} {"input": "package controller\n\nimport (\n\t\"fmt\"\n)\n\ntype AdminParams struct {\n\tName *string\n\tInviteId *string\n\tInviteKey *string\n\tConfirmDelete *string\n}\n\nfunc NewAdminParams() *AdminParams {\n\treturn new(AdminParams)\n}\n\nfunc (params *AdminParams) ValidateName(required bool) error {\n\tif required && *params.Name == \"\" {\n\t\treturn fmt.Errorf(\"name cannot be empty\")\n\t}\n\treturn nil\n}\n\nfunc (params *AdminParams) ValidateInviteId(required bool) error { return nil }\n\n\nfunc (params *AdminParams) ValidateInviteKey(required bool) error ", "output": "{ return nil }"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"os\"\n\n\t\"gopkg.in/gin-gonic/gin.v1\"\n)\n\nvar router *gin.Engine\n\nfunc main() {\n\tif os.Getenv(\"GIN_ENV\") == \"production\" {\n\t\tgin.SetMode(gin.ReleaseMode)\n\t} else {\n\t\tgin.SetMode(gin.DebugMode)\n\t}\n\n\trouter = gin.Default()\n\n\trouter.LoadHTMLGlob(\"templates/*\")\n\n\tinitializeRoutes()\n\n\trouter.Run()\n}\n\n\n\nfunc render(c *gin.Context, templateName string, data gin.H) ", "output": "{\n\tc.HTML(http.StatusOK, templateName, data)\n}"} {"input": "package bc\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n)\n\ntype Bc interface {\n\tExec(string) error\n\tQuit()\n}\n\ntype bc struct {\n\tcmd *exec.Cmd\n\tstdin io.WriteCloser\n\tstdout io.ReadCloser\n}\n\nfunc Start() Bc {\n\tcmd := exec.Command(\"bc\")\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcmd.Stderr = os.Stderr\n\tcmd.Start()\n\treturn &bc{cmd, stdin, stdout}\n}\n\n\nvar inputSuffix = []byte(\"\\n\\\"\\x04\\\"\\n\")\n\n\n\nfunc readByte(r io.Reader) (byte, error) {\n\tvar buf [1]byte\n\t_, err := r.Read(buf[:])\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn buf[0], nil\n}\n\nfunc (bc *bc) Quit() {\n\tbc.stdin.Close()\n\tbc.cmd.Wait()\n\tbc.stdout.Close()\n}\n\nfunc (bc *bc) Exec(code string) error ", "output": "{\n\tbc.stdin.Write([]byte(code))\n\tbc.stdin.Write(inputSuffix)\n\tfor {\n\t\tb, err := readByte(bc.stdout)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif b == 0x04 {\n\t\t\tbreak\n\t\t}\n\t\tos.Stdout.Write([]byte{b})\n\t}\n\treturn nil\n}"} {"input": "package wxdata\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\nfunc DownloadGfs(targetFolder string) {\n\n\tfor _,t:= range GetGfsCandidateAnatimes(){\n\t\tdownloadGfs(targetFolder, t)\n\t}\n\n}\n\n\n\nfunc downloadGfs(targetFolder string, date time.Time) ", "output": "{\n\n\titems := GetGfsDownloadItems(date)\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(items))\n\n\tfor _,item := range items {\n\n\t\tgo (func(item DownloadItem){\n\t\t\tdefer wg.Done()\n\t\t\tDownload(item, targetFolder)\n\t\t})(item)\n\n\t\tfmt.Println(item.Url)\n\t}\n\n\twg.Wait()\n}"} {"input": "package tc\n\n\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype CRStates struct {\n\tCaches map[CacheName]IsAvailable `json:\"caches\"`\n\tDeliveryService map[DeliveryServiceName]CRStatesDeliveryService `json:\"deliveryServices\"`\n}\n\n\ntype CRStatesDeliveryService struct {\n\tDisabledLocations []CacheGroupName `json:\"disabledLocations\"`\n\tIsAvailable bool `json:\"isAvailable\"`\n}\n\n\ntype IsAvailable struct {\n\tIsAvailable bool `json:\"isAvailable\"`\n}\n\n\nfunc NewCRStates() CRStates {\n\treturn CRStates{\n\t\tCaches: map[CacheName]IsAvailable{},\n\t\tDeliveryService: map[DeliveryServiceName]CRStatesDeliveryService{},\n\t}\n}\n\n\nfunc (a CRStates) Copy() CRStates {\n\tb := NewCRStates()\n\tfor k, v := range a.Caches {\n\t\tb.Caches[k] = v\n\t}\n\tfor k, v := range a.DeliveryService {\n\t\tb.DeliveryService[k] = v\n\t}\n\treturn b\n}\n\n\nfunc (a CRStates) CopyDeliveryServices() map[DeliveryServiceName]CRStatesDeliveryService {\n\tb := map[DeliveryServiceName]CRStatesDeliveryService{}\n\tfor k, v := range a.DeliveryService {\n\t\tb[k] = v\n\t}\n\treturn b\n}\n\n\n\n\n\nfunc CRStatesMarshall(states CRStates) ([]byte, error) {\n\treturn json.Marshal(states)\n}\n\n\nfunc CRStatesUnMarshall(body []byte) (CRStates, error) {\n\tvar crStates CRStates\n\terr := json.Unmarshal(body, &crStates)\n\treturn crStates, err\n}\n\nfunc (a CRStates) CopyCaches() map[CacheName]IsAvailable ", "output": "{\n\tb := map[CacheName]IsAvailable{}\n\tfor k, v := range a.Caches {\n\t\tb[k] = v\n\t}\n\treturn b\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\n\nfunc simpleEvalInt(a, b int, op string) int {\n\tswitch op {\n\tcase \"+\":\n\t\treturn a + b\n\tcase \"-\":\n\t\treturn a - b\n\tcase \"/\":\n\t\treturn a / b\n\tcase \"*\":\n\t\treturn a * b\n\tcase \"^\":\n\t\treturn power(a, b)\n\tdefault:\n\t\treturn 0\n\t}\n}\n\n\n\n\n\n\nfunc power(a, b int) int {\n\tans := 1\n\tfor i := 0; i < b; i++ {\n\t\tans = a * ans\n\t}\n\treturn ans\n}\n\nfunc evalPostfixInt(postfix []string) (int, error) ", "output": "{\n\tvar stack []int\n\tfor _, val := range postfix {\n\t\tif isOp(val) {\n\t\t\ta := stack[len(stack)-2]\n\t\t\tb := stack[len(stack)-1]\n\t\t\tretVal := simpleEvalInt(a, b, val)\n\t\t\tstack = append(stack[0:len(stack)-2], retVal)\n\t\t} else {\n\t\t\tnum, err := strconv.Atoi(val)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, nil\n\t\t\t}\n\t\t\tstack = append(stack, num)\n\t\t}\n\t}\n\tif len(stack) != 1 {\n\t\terr := fmt.Errorf(\"error calculating postfix\")\n\t\treturn 0, err\n\t}\n\treturn stack[0], nil\n}"} {"input": "package dns\n\nimport (\n\t\"github.com/cilium/cilium/pkg/hubble/metrics/api\"\n)\n\ntype dnsPlugin struct{}\n\nfunc (p *dnsPlugin) NewHandler() api.Handler {\n\treturn &dnsHandler{}\n}\n\nfunc (p *dnsPlugin) HelpText() string {\n\treturn `dns - DNS related metrics\nReports metrics related to DNS queries and responses\n\nMetrics:\n hubble_dns_queries_total Number of observed TCP queries\n hubble_dns_responses_total Number of observed TCP responses\n\nOptions:\n query - Include query name as label\n ignoreAAAA - Do not include AAAA query & responses in metrics` +\n\t\tapi.ContextOptionsHelp\n}\n\n\n\nfunc init() ", "output": "{\n\tapi.DefaultRegistry().Register(\"dns\", &dnsPlugin{})\n}"} {"input": "package srpc\n\nimport (\n\t\"crypto/tls\"\n\n\t\"github.com/Symantec/Dominator/lib/connpool\"\n)\n\nfunc newClientResource(network, address string) *ClientResource {\n\tclientResource := &ClientResource{\n\t\tnetwork: network,\n\t\taddress: address,\n\t}\n\tclientResource.privateClientResource.clientResource = clientResource\n\trp := connpool.GetResourcePool()\n\tclientResource.resource = rp.Create(&clientResource.privateClientResource)\n\treturn clientResource\n}\n\nfunc (cr *ClientResource) getHTTP(tlsConfig *tls.Config,\n\tcancelChannel <-chan struct{}, dialer connpool.Dialer) (*Client, error) {\n\tcr.privateClientResource.tlsConfig = tlsConfig\n\tcr.privateClientResource.dialer = dialer\n\tif err := cr.resource.Get(cancelChannel); err != nil {\n\t\treturn nil, err\n\t}\n\tcr.inUse = true\n\tclientMetricsMutex.Lock()\n\tnumInUseClientConnections++\n\tclientMetricsMutex.Unlock()\n\treturn cr.client, nil\n}\n\n\n\nfunc (pcr *privateClientResource) Allocate() error {\n\tcr := pcr.clientResource\n\tclient, err := dialHTTP(cr.network, cr.address, pcr.tlsConfig, pcr.dialer)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcr.client = client\n\tclient.resource = cr\n\treturn nil\n}\n\nfunc (pcr *privateClientResource) Release() error {\n\tcr := pcr.clientResource\n\terr := cr.client.conn.Close()\n\tcr.client = nil\n\treturn err\n}\n\nfunc (client *Client) put() ", "output": "{\n\tclient.resource.resource.Put()\n\tif client.resource.inUse {\n\t\tclientMetricsMutex.Lock()\n\t\tnumInUseClientConnections--\n\t\tclientMetricsMutex.Unlock()\n\t\tclient.resource.inUse = false\n\t}\n}"} {"input": "package scripts\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\n\t\"github.com/lfkeitel/inca-tool/devices\"\n)\n\n\n\nfunc getHostVariables(host *devices.Device) map[string]string {\n\targList := make(map[string]string)\n\targList[\"protocol\"] = host.GetSetting(\"protocol\")\n\tif argList[\"protocol\"] == \"\" {\n\t\targList[\"protocol\"] = \"ssh\"\n\t}\n\n\targList[\"hostname\"] = host.GetSetting(\"address\")\n\tif argList[\"hostname\"] == \"\" {\n\t\targList[\"hostname\"] = host.Name\n\t}\n\n\targList[\"remote_user\"] = host.GetSetting(\"remote_user\")\n\tif argList[\"remote_user\"] == \"\" {\n\t\targList[\"remote_user\"] = \"root\"\n\t}\n\n\targList[\"remote_password\"] = host.GetSetting(\"remote_password\")\n\n\targList[\"cisco_enable\"] = host.GetSetting(\"cisco_enable\")\n\tif argList[\"cisco_enable\"] == \"\" {\n\t\targList[\"cisco_enable\"] = host.GetSetting(\"remote_password\")\n\t}\n\n\treturn argList\n}\n\nfunc insertVariables(filename string, vars map[string]string) error ", "output": "{\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor n, v := range vars {\n\t\tif n[0] == '_' {\n\t\t\tn = n[1:]\n\t\t}\n\t\tfile = bytes.Replace(file, []byte(\"{{\"+n+\"}}\"), []byte(v), -1)\n\t}\n\n\tif err := ioutil.WriteFile(filename, file, 0744); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package wait\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\n\n\n\nfunc Predicate(pred func() bool, timeout time.Duration) error {\n\tconst pollInterval = 20 * time.Millisecond\n\n\texitTimer := time.After(timeout)\n\tfor {\n\t\t<-time.After(pollInterval)\n\n\t\tselect {\n\t\tcase <-exitTimer:\n\t\t\treturn fmt.Errorf(\"predicate not satisfied after time out\")\n\t\tdefault:\n\t\t}\n\n\t\tif pred() {\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Invariant(statement func() bool, timeout time.Duration) error {\n\tconst pollInterval = 20 * time.Millisecond\n\n\texitTimer := time.After(timeout)\n\tfor {\n\t\t<-time.After(pollInterval)\n\n\t\tif !statement() {\n\t\t\treturn fmt.Errorf(\"invariant broken before time out\")\n\t\t}\n\n\t\tselect {\n\t\tcase <-exitTimer:\n\t\t\treturn nil\n\t\tdefault:\n\t\t}\n\t}\n}\n\n\n\n\nfunc InvariantNoError(f func() error, timeout time.Duration) error {\n\tvar predErr error\n\tpred := func() bool {\n\t\tif err := f(); err != nil {\n\t\t\tpredErr = err\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\n\tif err := Invariant(pred, timeout); err != nil {\n\t\treturn predErr\n\t}\n\n\treturn nil\n}\n\nfunc NoError(f func() error, timeout time.Duration) error ", "output": "{\n\tvar predErr error\n\tpred := func() bool {\n\t\tif err := f(); err != nil {\n\t\t\tpredErr = err\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\n\tif err := Predicate(pred, timeout); err != nil {\n\t\treturn predErr\n\t}\n\n\treturn nil\n}"} {"input": "package minicon\n\nimport \"container/ring\"\n\n\n\n\ntype History struct {\n\tr *ring.Ring\n}\n\n\n\n\ntype HistoryMarker *ring.Ring\n\n\n\n\nfunc NewHistory(capacity int) *History {\n\treturn &History{ring.New(capacity)}\n}\n\n\n\n\n\n\nfunc (hs *History) Add(s string, mark HistoryMarker) HistoryMarker {\n\ths.Restore(mark)\n\tif s != \"\" && hs.r.Value != s {\n\t\ths.r.Value = s\n\t\ths.r = hs.r.Next()\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (hs *History) Back() (string, bool) {\n\treturn hs._update(hs.r.Prev())\n}\n\n\n\n\n\nfunc (hs *History) Forward() (string, bool) {\n\treturn hs._update(hs.r.Next())\n}\n\n\n\n\n\n\n\n\n\nfunc (hs *History) Restore(mark HistoryMarker) {\n\tif mark != nil {\n\t\ths.r = mark\n\t}\n}\n\n\n\n\nfunc (hs *History) _update(r *ring.Ring) (ret string, okay bool) {\n\tif s, ok := r.Value.(string); ok && s != \"\" {\n\t\ths.r = r\n\t\tret, okay = s, ok\n\t}\n\treturn ret, okay\n}\n\nfunc (hs *History) Mark() HistoryMarker ", "output": "{\n\treturn hs.r\n}"} {"input": "package lmath\n\n\n\nfunc selfDividingNumbers(left int, right int) []int ", "output": "{\n\tres := []int{}\n\tfor i := left; i <= right; i++ {\n\t\tj := i\n\t\tfor ; j > 0; j /= 10 {\n\t\t\tif j%10 == 0 || i%(j%10) != 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif j == 0 {\n\t\t\tres = append(res, i)\n\t\t}\n\t}\n\treturn res\n}"} {"input": "package atomic\n\nimport (\n\t\"encoding/json\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\n\ntype Uint32 struct {\n\t_ nocmp \n\n\tv uint32\n}\n\n\nfunc NewUint32(val uint32) *Uint32 {\n\treturn &Uint32{v: val}\n}\n\n\nfunc (i *Uint32) Load() uint32 {\n\treturn atomic.LoadUint32(&i.v)\n}\n\n\n\n\n\nfunc (i *Uint32) Sub(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, ^(delta - 1))\n}\n\n\nfunc (i *Uint32) Inc() uint32 {\n\treturn i.Add(1)\n}\n\n\nfunc (i *Uint32) Dec() uint32 {\n\treturn i.Sub(1)\n}\n\n\nfunc (i *Uint32) CAS(old, new uint32) (swapped bool) {\n\treturn atomic.CompareAndSwapUint32(&i.v, old, new)\n}\n\n\nfunc (i *Uint32) Store(val uint32) {\n\tatomic.StoreUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) Swap(val uint32) (old uint32) {\n\treturn atomic.SwapUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(i.Load())\n}\n\n\nfunc (i *Uint32) UnmarshalJSON(b []byte) error {\n\tvar v uint32\n\tif err := json.Unmarshal(b, &v); err != nil {\n\t\treturn err\n\t}\n\ti.Store(v)\n\treturn nil\n}\n\n\nfunc (i *Uint32) String() string {\n\tv := i.Load()\n\treturn strconv.FormatUint(uint64(v), 10)\n}\n\nfunc (i *Uint32) Add(delta uint32) uint32 ", "output": "{\n\treturn atomic.AddUint32(&i.v, delta)\n}"} {"input": "package v1alpha1\n\nimport (\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\tcorev1 \"k8s.io/api/core/v1\"\n)\n\nfunc TestBuildTemplateSpec(t *testing.T) {\n\tc := BuildTemplate{\n\t\tSpec: BuildTemplateSpec{\n\t\t\tSteps: []corev1.Container{{\n\t\t\t\tName: \"build-spec\",\n\t\t\t}},\n\t\t},\n\t}\n\n\texpectedBuildSpec := BuildTemplateSpec{Steps: []corev1.Container{{Name: \"build-spec\"}}}\n\n\tif a := cmp.Diff(c.TemplateSpec(), expectedBuildSpec); a != \"\" {\n\t\tt.Errorf(\"templateSpec mismatch; expected: %v got: %v\", expectedBuildSpec, a)\n\t}\n}\n\n\n\nfunc TestBuildTemplateGroupVersionKind(t *testing.T) ", "output": "{\n\tc := BuildTemplate{}\n\n\texpectedKind := \"BuildTemplate\"\n\tif c.GetGroupVersionKind().Kind != expectedKind {\n\t\tt.Errorf(\"GetGroupVersionKind mismatch; expected: %v got: %v\", expectedKind, c.GetGroupVersionKind().Kind)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"runtime\"\n)\n\n\n\nfunc main() {\n}\n\nfunc init() ", "output": "{\n\tc := make(chan int, 1)\n\tdefer func() {\n\t\tc <- 0\n\t}()\n\tgo func() {\n\t\tos.Exit(<-c)\n\t}()\n\truntime.Goexit()\n}"} {"input": "package mock\n\nimport (\n\t\"github.com/eventials/goevents/messaging\"\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype Connection struct {\n\tmock.Mock\n}\n\nfunc NewMockConnection() messaging.Connection {\n\treturn &Connection{}\n}\n\nfunc (c *Connection) Consumer(autoAck bool, exchange, queue string) (messaging.Consumer, error) {\n\targs := c.Called(autoAck, exchange, queue)\n\treturn args.Get(0).(messaging.Consumer), args.Error(1)\n}\n\nfunc (c *Connection) Producer(exchange string) (messaging.Producer, error) {\n\targs := c.Called(exchange)\n\treturn args.Get(0).(messaging.Producer), args.Error(1)\n}\n\nfunc (c *Connection) Close() {\n\tc.Called()\n}\n\nfunc (c *Connection) NotifyConnectionClose() <-chan error {\n\targs := c.Called()\n\treturn args.Get(0).(chan error)\n}\n\nfunc (c *Connection) NotifyReestablish() <-chan bool {\n\targs := c.Called()\n\treturn args.Get(0).(chan bool)\n}\n\nfunc (c *Connection) WaitUntilConnectionCloses() {\n\tc.Called()\n}\n\nfunc (c *Connection) WaitUntilConnectionReestablished() {\n\tc.Called()\n}\n\n\n\nfunc (c *Connection) IsConnected() bool ", "output": "{\n\targs := c.Called()\n\treturn args.Get(0).(bool)\n}"} {"input": "package miniredis\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\nfunc assert(tb testing.TB, condition bool, msg string, v ...interface{}) {\n\ttb.Helper()\n\n\tif !condition {\n\t\ttb.Errorf(msg, v...)\n\t}\n}\n\n\nfunc ok(tb testing.TB, err error) {\n\ttb.Helper()\n\n\tif err != nil {\n\t\ttb.Errorf(\"unexpected error: %s\", err.Error())\n\t}\n}\n\n\nfunc equals(tb testing.TB, exp, act interface{}) {\n\ttb.Helper()\n\n\tif !reflect.DeepEqual(exp, act) {\n\t\ttb.Errorf(\"expected: %#v got: %#v\", exp, act)\n\t}\n}\n\n\n\n\nfunc mustFail(tb testing.TB, err error, want string) ", "output": "{\n\ttb.Helper()\n\n\tif err == nil {\n\t\ttb.Errorf(\"expected an error, but got a nil\")\n\t}\n\n\tif have := err.Error(); have != want {\n\t\ttb.Errorf(\"have %q, want %q\", have, want)\n\t}\n}"} {"input": "package handlers\n\nimport (\n\t\"net/http\"\n\t\"appengine/user\"\n\t\"appengine\"\n\t\"appengine/datastore\"\n\t\"text/template\"\n\t\"time\"\n\n\t\"model\"\n\t\"model/booth\"\n\t\"util\"\n)\n\n\n\n\n\nfunc handleGetAllBooths(w http.ResponseWriter, r *http.Request) {\n\tc := appengine.NewContext(r)\n\n\tutil.RedirectIfNotLoggedIn(w, r)\n\n\tq := datastore.NewQuery(\"Booth\").Ancestor(booth.Key(c)).Order(\"-Date\").Limit(10)\n\tbooths := make([]model.Booth, 10)\n\n\tif _, err := q.GetAll(c, &booths); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tboothsTemplate, _ := template.ParseFiles(\"./templates/booths/index.html\")\n\n\tif err := boothsTemplate.Execute(w, booths); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\n\nfunc handleCreateBooth(w http.ResponseWriter, r *http.Request) {\n\tc := appengine.NewContext(r)\n\tu := user.Current(c)\n\n\tutil.RedirectIfNotLoggedIn(w, r)\n\n\tb := model.Booth{\n\t\tAuthor: u.String(),\n\t\tDate: time.Now(),\n\t\tName: r.FormValue(\"name\"),\n\t}\n\n\tkey := datastore.NewIncompleteKey(c, \"Booth\", booth.Key(c))\n\t_, err := datastore.Put(c, key, &b)\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thttp.Redirect(w, r, \"/\", http.StatusCreated)\n}\n\nfunc HandleBooths(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tswitch r.Method {\n\tcase \"GET\":\n\t\thandleGetAllBooths(w, r)\n\t\tbreak;\n\tcase \"POST\":\n\t\thandleCreateBooth(w, r)\n\t\tbreak;\n\tdefault:\n\t\thttp.Error(w, \"\", http.StatusMethodNotAllowed)\n\t}\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\n\n\ntype TaskIDRange struct {\n\n\tEnd *int32 `json:\"end\"`\n\n\tStart *int32 `json:\"start\"`\n}\n\n\n\n\nfunc (m *TaskIDRange) validateEnd(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"end\", \"body\", m.End); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *TaskIDRange) validateStart(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"start\", \"body\", m.Start); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *TaskIDRange) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateEnd(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStart(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package google\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/acctest\"\n\t\"github.com/hashicorp/terraform/helper/resource\"\n)\n\n\nfunc TestAccGoogleSqlDatabaseInstance_importBasic(t *testing.T) {\n\tt.Parallel()\n\n\tresourceName := \"google_sql_database_instance.instance\"\n\tdatabaseID := acctest.RandInt()\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testAccGoogleSqlDatabaseInstanceDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: fmt.Sprintf(\n\t\t\t\t\ttestGoogleSqlDatabaseInstance_basic, databaseID),\n\t\t\t},\n\n\t\t\tresource.TestStep{\n\t\t\t\tResourceName: resourceName,\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\n\n\n\nfunc TestAccGoogleSqlDatabaseInstance_importBasic3(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\tresourceName := \"google_sql_database_instance.instance\"\n\tdatabaseID := acctest.RandInt()\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testAccGoogleSqlDatabaseInstanceDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: fmt.Sprintf(\n\t\t\t\t\ttestGoogleSqlDatabaseInstance_basic3, databaseID),\n\t\t\t},\n\n\t\t\tresource.TestStep{\n\t\t\t\tResourceName: resourceName,\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}"} {"input": "package plugin\n\n\ntype Kind uint8\n\nconst (\n\tAudit Kind = 1 + iota\n\tAuthentication\n\tSchema\n\tDaemon\n)\n\n\n\n\ntype State uint8\n\nconst (\n\tUninitialized State = iota\n\tReady\n\tDying\n\tDisable\n)\n\nfunc (s State) String() (str string) {\n\tswitch s {\n\tcase Uninitialized:\n\t\tstr = \"Uninitialized\"\n\tcase Ready:\n\t\tstr = \"Ready\"\n\tcase Dying:\n\t\tstr = \"Dying\"\n\tcase Disable:\n\t\tstr = \"Disable\"\n\t}\n\treturn\n}\n\nfunc (k Kind) String() (str string) ", "output": "{\n\tswitch k {\n\tcase Audit:\n\t\tstr = \"Audit\"\n\tcase Authentication:\n\t\tstr = \"Authentication\"\n\tcase Schema:\n\t\tstr = \"Schema\"\n\tcase Daemon:\n\t\tstr = \"Daemon\"\n\t}\n\treturn\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\n\tv1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/client-go/tools/cache\"\n\t\"k8s.io/component-helpers/storage/ephemeral\"\n)\n\nconst (\n\tPodPVCIndex = \"pod-pvc-index\"\n)\n\n\n\n\nfunc PodPVCIndexFunc() func(obj interface{}) ([]string, error) {\n\treturn func(obj interface{}) ([]string, error) {\n\t\tpod, ok := obj.(*v1.Pod)\n\t\tif !ok {\n\t\t\treturn []string{}, nil\n\t\t}\n\t\tkeys := []string{}\n\t\tfor _, podVolume := range pod.Spec.Volumes {\n\t\t\tclaimName := \"\"\n\t\t\tif pvcSource := podVolume.VolumeSource.PersistentVolumeClaim; pvcSource != nil {\n\t\t\t\tclaimName = pvcSource.ClaimName\n\t\t\t} else if podVolume.VolumeSource.Ephemeral != nil {\n\t\t\t\tclaimName = ephemeral.VolumeClaimName(pod, &podVolume)\n\t\t\t}\n\t\t\tif claimName != \"\" {\n\t\t\t\tkeys = append(keys, fmt.Sprintf(\"%s/%s\", pod.Namespace, claimName))\n\t\t\t}\n\t\t}\n\t\treturn keys, nil\n\t}\n}\n\n\n\n\n\nfunc AddIndexerIfNotPresent(indexer cache.Indexer, indexName string, indexFunc cache.IndexFunc) error {\n\tindexers := indexer.GetIndexers()\n\tif _, ok := indexers[indexName]; ok {\n\t\treturn nil\n\t}\n\treturn indexer.AddIndexers(cache.Indexers{indexName: indexFunc})\n}\n\nfunc AddPodPVCIndexerIfNotPresent(indexer cache.Indexer) error ", "output": "{\n\treturn AddIndexerIfNotPresent(indexer, PodPVCIndex, PodPVCIndexFunc())\n}"} {"input": "package aws\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/resource\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\nfunc TestAccAWSInspectorResourceGroup_basic(t *testing.T) {\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSInspectorResourceGroup,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSInspectorResourceGroupExists(\"aws_inspector_resource_group.foo\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tConfig: testAccCheckAWSInspectorResourceGroupModified,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSInspectorResourceGroupExists(\"aws_inspector_resource_group.foo\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\n\n\nvar testAccAWSInspectorResourceGroup = `\nresource \"aws_inspector_resource_group\" \"foo\" {\n\ttags = {\n\t Name = \"foo\"\n }\n}`\n\nvar testAccCheckAWSInspectorResourceGroupModified = `\nresource \"aws_inspector_resource_group\" \"foo\" {\n\ttags = {\n\t Name = \"bar\"\n }\n}`\n\nfunc testAccCheckAWSInspectorResourceGroupExists(name string) resource.TestCheckFunc ", "output": "{\n\treturn func(s *terraform.State) error {\n\t\t_, ok := s.RootModule().Resources[name]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", name)\n\t\t}\n\n\t\treturn nil\n\t}\n}"} {"input": "package browser\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"runtime\"\n)\n\n\n\n\n\nfunc Open(url string) bool {\n\tfor _, args := range Commands() {\n\t\tcmd := exec.Command(args[0], append(args[1:], url)...) \n\t\tif cmd.Start() == nil {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc Commands() [][]string ", "output": "{\n\tvar cmds [][]string\n\tif exe := os.Getenv(\"BROWSER\"); exe != \"\" {\n\t\tcmds = append(cmds, []string{exe})\n\t}\n\tswitch runtime.GOOS {\n\tcase \"darwin\":\n\t\tcmds = append(cmds, []string{\"/usr/bin/open\"})\n\tcase \"windows\":\n\t\tcmds = append(cmds, []string{\"cmd\", \"/c\", \"start\"})\n\tdefault:\n\t\tcmds = append(cmds, []string{\"xdg-open\"})\n\t}\n\tcmds = append(cmds,\n\t\t[]string{\"chrome\"},\n\t\t[]string{\"google-chrome\"},\n\t\t[]string{\"chromium\"},\n\t\t[]string{\"firefox\"},\n\t)\n\treturn cmds\n}"} {"input": "package nogo\n\n\ntype Permission int\n\n\ntype Principal interface {\n\tGetId() string\n\tGetSid() string\n\tGetRoleNames() []string\n}\n\n\ntype Role interface {\n\tGetName() string\n\tIsAdmin() bool\n\tHasPermission(permission Permission) (bool, error)\n}\n\n\nfunc NewRole(name string, mask Permission) Role {\n\treturn &defaultRole{RoleName: name, PermissionMask: mask, Admin: false}\n}\n\n\nfunc NewAdminRole(name string, mask Permission) Role {\n\treturn &defaultRole{RoleName: name, PermissionMask: mask, Admin: true}\n}\n\ntype defaultRole struct {\n\tRoleName string `db:\"role_name\"`\n\tPermissionMask Permission `db:\"permission_mask\"`\n\tAdmin bool `db:\"is_admin\"`\n}\n\nfunc (this *defaultRole) GetName() string {\n\treturn this.RoleName\n}\n\n\n\nfunc (this *defaultRole) HasPermission(permission Permission) (bool, error) {\n\tval := (this.PermissionMask&permission != 0)\n\treturn val, nil\n}\n\nfunc (this *defaultRole) IsAdmin() bool ", "output": "{\n\treturn this.Admin\n}"} {"input": "package coverage\n\nimport \"testing\"\n\n\n\nfunc TestCoverage(t *testing.T) ", "output": "{\n\tlive()\n}"} {"input": "package windows\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n\n\n\n\nfunc downloadFile(url string) (string, error) ", "output": "{\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to download from %q: %w\", url, err)\n\t}\n\tdefer response.Body.Close()\n\n\ttempFile, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to create temp file: %w\", err)\n\t}\n\tdefer tempFile.Close()\n\n\t_, err = io.Copy(tempFile, response.Body)\n\treturn tempFile.Name(), err\n}"} {"input": "package buckets\n\nimport (\n\t\"github.com/campadrenalin/scrap\"\n\t\"testing\"\n)\n\nfunc TestAnyBucket_Empty(t *testing.T) {\n\tb := AnyBucket{}\n\tif b.Check(\"foo\") {\n\t\tt.Fatal(\"Should always return false when there are no children\")\n\t}\n}\n\nfunc TestAnyBucket_OneItem(t *testing.T) {\n\tb := AnyBucket{\n\t\tChildren: []scrap.Bucket{\n\t\t\tscrap.NewCountBucket(1),\n\t\t},\n\t}\n\ttests := bt_slice{\n\t\tbt{\"foo\", true, \"First should succeed\"},\n\t\tbt{\"foo\", false, \"Second should fail\"},\n\t}\n\ttests.Run(t, b)\n}\n\n\n\nfunc TestAnyBucket_MultipleItems(t *testing.T) ", "output": "{\n\tb := AnyBucket{\n\t\tChildren: []scrap.Bucket{\n\t\t\tscrap.NewCountBucket(1),\n\t\t\tscrap.NewCountBucket(2),\n\t\t},\n\t}\n\ttests := bt_slice{\n\t\tbt{\"foo\", true, \"First bucket says yes\"},\n\t\tbt{\"foo\", true, \"First bucket exhausted, second says yes\"},\n\t\tbt{\"foo\", true, \"Second bucket says yes for the final time\"},\n\t\tbt{\"foo\", false, \"Second bucket exhausted\"},\n\t}\n\ttests.Run(t, b)\n\n\tb.Children[0].(*scrap.CountBucket).SetMaxHits(3)\n\ttests = bt_slice{\n\t\tbt{\"foo\", true, \"First bucket says yes\"},\n\t\tbt{\"foo\", true, \"First bucket says yes for the final time\"},\n\t\tbt{\"foo\", false, \"Both buckets exhausted\"},\n\t}\n\ttests.Run(t, b)\n}"} {"input": "package git\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/Originate/git-town/src/command\"\n\t\"github.com/Originate/git-town/src/util\"\n)\n\n\n\n\n\n\n\nfunc EnsureDoesNotHaveOpenChanges(message string) {\n\tutil.Ensure(!HasOpenChanges(), \"You have uncommitted changes. \"+message)\n}\n\n\nvar rootDirectory string\n\n\n\nfunc GetRootDirectory() string {\n\tif rootDirectory == \"\" {\n\t\trootDirectory = command.MustRun(\"git\", \"rev-parse\", \"--show-toplevel\").OutputSanitized()\n\t}\n\treturn rootDirectory\n}\n\n\nfunc HasConflicts() bool {\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"Unmerged paths\")\n}\n\n\nfunc HasOpenChanges() bool {\n\treturn command.MustRun(\"git\", \"status\", \"--porcelain\").OutputSanitized() != \"\"\n}\n\n\n\nfunc HasShippableChanges(branchName string) bool {\n\treturn command.MustRun(\"git\", \"diff\", Config().GetMainBranch()+\"..\"+branchName).OutputSanitized() != \"\"\n}\n\n\n\nfunc IsMergeInProgress() bool {\n\t_, err := os.Stat(fmt.Sprintf(\"%s/.git/MERGE_HEAD\", GetRootDirectory()))\n\treturn err == nil\n}\n\n\n\nfunc IsRebaseInProgress() bool {\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"rebase in progress\")\n}\n\nfunc EnsureDoesNotHaveConflicts() ", "output": "{\n\tutil.Ensure(!HasConflicts(), \"You must resolve the conflicts before continuing\")\n}"} {"input": "package checker\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"net/http\"\n)\n\ntype tokenChecker struct {\n}\n\nfunc (checker *tokenChecker) Support(eventMap map[string]string) bool {\n\treturn true\n}\n\n\n\nfunc (checker *tokenChecker) Check(eventMap map[string]string, expectedToken string, reqHeader http.Header, reqBody []byte) (bool, error) ", "output": "{\n\tpassCheck := false\n\n\tswitch eventMap[\"sourceType\"] {\n\tcase \"customize\":\n\t\tif expectedToken == eventMap[\"token\"] {\n\t\t\tpassCheck = true\n\t\t}\n\tcase \"gitlab\":\n\t\tif expectedToken == eventMap[\"token\"] {\n\t\t\tpassCheck = true\n\t\t}\n\tcase \"github\":\n\t\tmac := hmac.New(sha1.New, []byte(expectedToken))\n\t\tmac.Write(reqBody)\n\t\texpectedMAC := mac.Sum(nil)\n\t\texpectedSig := \"sha1=\" + hex.EncodeToString(expectedMAC)\n\n\t\tif expectedSig == eventMap[\"token\"] {\n\t\t\tpassCheck = true\n\t\t}\n\t}\n\n\tif passCheck {\n\t\treturn passCheck, nil\n\t}\n\n\treturn passCheck, errors.New(\"token checker failed\")\n}"} {"input": "package main\n\nimport (\n\t\"encoding/hex\"\n\t\"errors\"\n)\n\n\n\n\n\ntype User struct {\n\tId uint32\n\tName string\n\tPassword string\n\tCertHash string\n\tEmail string\n\tTextureBlob string\n\tCommentBlob string\n\tLastChannelId int\n\tLastActive uint64\n}\n\n\nfunc NewUser(id uint32, name string) (user *User, err error) {\n\tif id < 0 {\n\t\treturn nil, errors.New(\"Invalid user id\")\n\t}\n\tif len(name) == 0 {\n\t\treturn nil, errors.New(\"Invalid username\")\n\t}\n\n\treturn &User{\n\t\tId: id,\n\t\tName: name,\n\t}, nil\n}\n\n\nfunc (user *User) HasComment() bool {\n\treturn len(user.CommentBlob) > 0\n}\n\n\n\nfunc (user *User) CommentBlobHashBytes() (buf []byte) {\n\tbuf, err := hex.DecodeString(user.CommentBlob)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn buf\n}\n\n\nfunc (user *User) HasTexture() bool {\n\treturn len(user.TextureBlob) > 0\n}\n\n\n\n\n\nfunc (user *User) TextureBlobHashBytes() (buf []byte) ", "output": "{\n\tbuf, err := hex.DecodeString(user.TextureBlob)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn buf\n}"} {"input": "package plus\n\nfunc keySearch(keys keys, key Key) int {\n\tlow, high := 0, len(keys)-1\n\tvar mid int\n\tfor low <= high {\n\t\tmid = (high + low) / 2\n\t\tswitch keys[mid].Compare(key) {\n\t\tcase 1:\n\t\t\tlow = mid + 1\n\t\tcase -1:\n\t\t\thigh = mid - 1\n\t\tcase 0:\n\t\t\treturn mid\n\t\t}\n\t}\n\treturn low\n}\n\ntype btree struct {\n\troot node\n\tnodeSize, number uint64\n}\n\n\n\n\n\n\nfunc (tree *btree) Insert(keys ...Key) {\n\tfor _, key := range keys {\n\t\ttree.insert(key)\n\t}\n}\n\n\n\nfunc (tree *btree) Iter(key Key) Iterator {\n\tif tree.root == nil {\n\t\treturn nilIterator()\n\t}\n\n\treturn tree.root.find(key)\n}\n\nfunc (tree *btree) get(key Key) Key {\n\titer := tree.root.find(key)\n\tif !iter.Next() {\n\t\treturn nil\n\t}\n\n\tif iter.Value().Compare(key) == 0 {\n\t\treturn iter.Value()\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc (tree *btree) Get(keys ...Key) Keys {\n\tresults := make(Keys, 0, len(keys))\n\tfor _, k := range keys {\n\t\tresults = append(results, tree.get(k))\n\t}\n\n\treturn results\n}\n\n\nfunc (tree *btree) Len() uint64 {\n\treturn tree.number\n}\n\nfunc newBTree(nodeSize uint64) *btree {\n\treturn &btree{\n\t\tnodeSize: nodeSize,\n\t\troot: newLeafNode(nodeSize),\n\t}\n}\n\nfunc (tree *btree) insert(key Key) ", "output": "{\n\tif tree.root == nil {\n\t\tn := newLeafNode(tree.nodeSize)\n\t\tn.insert(tree, key)\n\t\ttree.number = 1\n\t\treturn\n\t}\n\n\tresult := tree.root.insert(tree, key)\n\tif result {\n\t\ttree.number++\n\t}\n\n\tif tree.root.needsSplit(tree.nodeSize) {\n\t\ttree.root = split(tree, nil, tree.root)\n\t}\n}"} {"input": "package slice\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/speedland/go/x/xtesting/assert\"\n)\n\nfunc ExampleSplitByLength() {\n\tvar a = []int{0, 1, 2, 3, 4}\n\tvar b = SplitByLength(a, 2).([][]int)\n\tfmt.Println(b)\n}\n\n\n\nfunc Test_ToInterface(t *testing.T) {\n\ta := assert.New(t)\n\ttype T struct {\n\t\ti int\n\t}\n\n\tintSlice := []int{1, 2, 3}\n\tia := ToInterface(intSlice)\n\ta.EqInt(2, ia[1].(int))\n\n\ttSlice := []T{T{1}, T{2}, T{3}}\n\tia = ToInterface(tSlice)\n\ta.EqInt(2, ia[1].(T).i)\n\n\tptrTSlice := []*T{&T{1}, &T{2}, &T{3}}\n\tia = ToInterface(ptrTSlice)\n\ta.EqInt(2, ia[1].(*T).i)\n}\n\nfunc Test_ToAddr(t *testing.T) {\n\ta := assert.New(t)\n\ttype Foo struct {\n\t\tfield string\n\t}\n\tlist := ToAddr([]Foo{Foo{\n\t\tfield: \"foo\",\n\t}}).([]*Foo)\n\ta.EqStr(\"foo\", list[0].field)\n}\n\nfunc Test_ToElem(t *testing.T) {\n\ta := assert.New(t)\n\ttype Foo struct {\n\t\tfield string\n\t}\n\tlist := ToElem([]*Foo{&Foo{\n\t\tfield: \"foo\",\n\t}}).([]Foo)\n\ta.EqStr(\"foo\", list[0].field)\n}\n\nfunc Test_SplitByLength(t *testing.T) ", "output": "{\n\ta := assert.New(t)\n\tvar a1 = []int{1, 2, 3, 4, 5}\n\tvar a2 = SplitByLength(a1, 3).([][]int)\n\ta.EqInt(1, a2[0][0])\n\ta.EqInt(2, a2[0][1])\n\ta.EqInt(3, a2[0][2])\n\ta.EqInt(2, len(a2[1]))\n\ta.EqInt(4, a2[1][0])\n\ta.EqInt(5, a2[1][1])\n}"} {"input": "package local\n\nimport (\n\t\"time\"\n\n\t\"github.com/prometheus/prometheus/util/testutil\"\n)\n\ntype testStorageCloser struct {\n\tstorage Storage\n\tdirectory testutil.Closer\n}\n\n\n\n\n\n\nfunc NewTestStorage(t testutil.T, encoding chunkEncoding) (*memorySeriesStorage, testutil.Closer) {\n\tDefaultChunkEncoding = encoding\n\tdirectory := testutil.NewTemporaryDirectory(\"test_storage\", t)\n\to := &MemorySeriesStorageOptions{\n\t\tMemoryChunks: 1000000,\n\t\tMaxChunksToPersist: 1000000,\n\t\tPersistenceRetentionPeriod: 24 * time.Hour * 365 * 100, \n\t\tPersistenceStoragePath: directory.Path(),\n\t\tCheckpointInterval: time.Hour,\n\t\tSyncStrategy: Adaptive,\n\t}\n\tstorage := NewMemorySeriesStorage(o)\n\tif err := storage.Start(); err != nil {\n\t\tdirectory.Close()\n\t\tt.Fatalf(\"Error creating storage: %s\", err)\n\t}\n\n\tcloser := &testStorageCloser{\n\t\tstorage: storage,\n\t\tdirectory: directory,\n\t}\n\n\treturn storage.(*memorySeriesStorage), closer\n}\n\nfunc (t *testStorageCloser) Close() ", "output": "{\n\tt.storage.Stop()\n\tt.directory.Close()\n}"} {"input": "package tlv\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\ntype ByteTLV struct {\n\tT uint64\n\tV []byte\n}\n\n\n\nfunc (t ByteTLV) Type() uint64 {\n\treturn t.T\n}\n\nfunc (t ByteTLV) WriteTo(w io.Writer) (n int64, err error) {\n\tn, err = WriteNumber(w, t.T)\n\tif err != nil {\n\t\treturn\n\t}\n\n\twritten, err := WriteNumber(w, uint64(len(t.V)))\n\tn += written\n\tif err != nil {\n\t\treturn\n\t}\n\n\twritten2, err := w.Write(t.V)\n\tn += int64(written2)\n\treturn\n}\n\nfunc (t ByteTLV) MarshalBinary() ([]byte, error) {\n\tbuf := &bytes.Buffer{}\n\t_, err := t.WriteTo(buf)\n\treturn buf.Bytes(), err\n}\n\nfunc readByteTLV(r io.Reader) (ByteTLV, error) ", "output": "{\n\tt, _, err := ReadNumber(r)\n\tif err != nil {\n\t\treturn ByteTLV{}, err\n\t}\n\n\tlength, _, err := ReadNumber(r)\n\tif err != nil {\n\t\treturn ByteTLV{}, err\n\t}\n\n\tvalue := make([]byte, length)\n\tn, err := r.Read(value)\n\tif err != nil {\n\t\treturn ByteTLV{}, err\n\t}\n\n\tif uint64(n) < length {\n\t\treturn ByteTLV{}, io.ErrUnexpectedEOF\n\t}\n\n\treturn ByteTLV{T: t, V: value[0:n]}, nil\n}"} {"input": "package tagquery\n\nimport (\n\t\"io\"\n\n\t\"github.com/grafana/metrictank/schema\"\n)\n\ntype expressionMatchNone struct {\n\texpressionCommon\n\toriginalOperator ExpressionOperator\n}\n\nfunc (e *expressionMatchNone) Equals(other Expression) bool {\n\treturn e.key == other.GetKey() && e.GetOperator() == other.GetOperator() && e.value == other.GetValue()\n}\n\nfunc (e *expressionMatchNone) GetDefaultDecision() FilterDecision {\n\treturn Fail\n}\n\n\n\nfunc (e *expressionMatchNone) GetValue() string {\n\treturn e.value\n}\n\nfunc (e *expressionMatchNone) GetOperator() ExpressionOperator {\n\treturn MATCH_NONE\n}\n\nfunc (e *expressionMatchNone) GetOperatorCost() uint32 {\n\treturn 0\n}\n\nfunc (e *expressionMatchNone) RequiresNonEmptyValue() bool {\n\treturn true\n}\n\nfunc (e *expressionMatchNone) Matches(value string) bool {\n\treturn false\n}\n\nfunc (e *expressionMatchNone) GetMetricDefinitionFilter(_ IdTagLookup) MetricDefinitionFilter {\n\treturn func(_ schema.MKey, _ string, _ []string) FilterDecision { return Fail }\n}\n\nfunc (e *expressionMatchNone) StringIntoWriter(writer io.Writer) {\n\twriter.Write([]byte(e.key))\n\te.originalOperator.StringIntoWriter(writer)\n\twriter.Write([]byte(e.value))\n}\n\nfunc (e *expressionMatchNone) GetKey() string ", "output": "{\n\treturn e.key\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"os/exec\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n\n\n\nfunc addRouteWithArg(name string, cmd string, router *gin.RouterGroup) {\n\tlog.Printf(\"Configuring route %v with command %s and argument\\n\", name, cmd)\n\tpath := name + \"/:arg\"\n\trouter.GET(path, func(c *gin.Context) {\n\t\targ := c.Params.ByName(\"arg\")\n\t\tif cmdOut, err := exec.Command(cmd, arg).Output(); err == nil {\n\t\t\tc.JSON(http.StatusOK, gin.H{\"status\": \"ok\", \"cmd\": string(cmd), \"argument\": string(arg), \"stdout\": string(cmdOut)})\n\t\t}\n\t})\n}\n\nfunc addRouteWithoutArg(name string, cmd string, router *gin.RouterGroup) {\n\tlog.Printf(\"Configuring route %s with command: %s\\n\", name, cmd)\n\trouter.GET(name, func(c *gin.Context) {\n\t\tif cmdOut, err := exec.Command(cmd).Output(); err == nil {\n\t\t\tc.JSON(http.StatusOK, gin.H{\"status\": \"ok\", \"cmd\": string(cmd), \"stdout\": string(cmdOut)})\n\t\t}\n\t})\n}\n\nfunc getPing(c *gin.Context) ", "output": "{\n\tc.String(200, \"pong\")\n}"} {"input": "package controller\n\nimport (\n\t\"github.com/tmacychen/UFG/framework\"\n\t\"github.com/tmacychen/UFG/framework/outer\"\n)\n\ntype AttachableOuter interface {\n\touter.Relayouter\n}\n\ntype Attachable struct {\n\touter AttachableOuter\n\tonAttach framework.Event\n\tonDetach framework.Event\n\tattached bool\n}\n\nfunc (a *Attachable) Init(outer AttachableOuter) {\n\ta.outer = outer\n}\n\nfunc (a *Attachable) Attached() bool {\n\treturn a.attached\n}\n\n\n\nfunc (a *Attachable) Detach() {\n\tif !a.attached {\n\t\tpanic(\"Control already detached\")\n\t}\n\ta.attached = false\n\tif a.onDetach != nil {\n\t\ta.onDetach.Fire()\n\t}\n}\n\nfunc (a *Attachable) OnAttach(f func()) framework.EventSubscription {\n\tif a.onAttach == nil {\n\t\ta.onAttach = CreateEvent(func() {})\n\t}\n\treturn a.onAttach.Listen(f)\n}\n\nfunc (a *Attachable) OnDetach(f func()) framework.EventSubscription {\n\tif a.onDetach == nil {\n\t\ta.onDetach = CreateEvent(func() {})\n\t}\n\treturn a.onDetach.Listen(f)\n}\n\nfunc (a *Attachable) Attach() ", "output": "{\n\tif a.attached {\n\t\tpanic(\"Control already attached\")\n\t}\n\ta.attached = true\n\tif a.onAttach != nil {\n\t\ta.onAttach.Fire()\n\t}\n}"} {"input": "package errors\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/GoogleContainerTools/skaffold/proto/v1\"\n)\n\ntype Error interface {\n\tError() string\n\tStatusCode() proto.StatusCode\n\tSuggestions() []*proto.Suggestion\n\tUnwrap() error\n}\n\ntype ErrDef struct {\n\terr error\n\tae *proto.ActionableErr\n}\n\nvar _ error = (*ErrDef)(nil)\n\n\n\nfunc (e *ErrDef) Unwrap() error {\n\treturn e.err\n}\n\nfunc (e *ErrDef) StatusCode() proto.StatusCode {\n\treturn e.ae.ErrCode\n}\n\nfunc (e *ErrDef) Suggestions() []*proto.Suggestion {\n\treturn e.ae.Suggestions\n}\n\n\nfunc NewError(err error, ae *proto.ActionableErr) *ErrDef {\n\treturn &ErrDef{\n\t\terr: err,\n\t\tae: ae,\n\t}\n}\n\n\nfunc NewErrorWithStatusCode(ae *proto.ActionableErr) *ErrDef {\n\treturn &ErrDef{\n\t\tae: ae,\n\t}\n}\n\nfunc IsSkaffoldErr(err error) bool {\n\tif _, ok := err.(Error); ok {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (e *ErrDef) Error() string ", "output": "{\n\tif s := concatSuggestions(e.Suggestions()); s != \"\" {\n\t\treturn fmt.Sprintf(\"%s. %s\", e.ae.Message, concatSuggestions(e.Suggestions()))\n\t}\n\treturn e.ae.Message\n}"} {"input": "package chatwork\n\nimport (\n\t\"encoding/json\"\n\t\"net/url\"\n\t\"strings\"\n)\n\ntype MessageResult struct {\n\tMessageId int `json:\"message_id\"`\n}\n\nvar format string = \"/rooms/{roomId}/messages\"\n\n\n\nfunc escapeMessage(message string) string {\n\treplacer := strings.NewReplacer(\"&\", \"&\", \"<\", \"<\", \">\", \">\")\n\treturn replacer.Replace(message)\n}\n\nfunc (api *Client) PostMessage(roomId, text string) int ", "output": "{\n\ttext = escapeMessage(text)\n\tapiUrl := CHATWORK_API + strings.Replace(format, \"{roomId}\", roomId, 1)\n\n\tvalues := url.Values{}\n\tvalues.Add(\"body\", text)\n\n\tcontents := api.Request(\"POST\", apiUrl, values.Encode())\n\tvar result MessageResult\n\tjson.Unmarshal(contents, &result)\n\treturn result.MessageId\n}"} {"input": "package underscore\n\nfunc Select(source, predicate interface{}) interface{} {\n\treturn filter(source, predicate, true)\n}\n\n\n\n\nfunc (this *Query) Select(predicate interface{}) Queryer {\n\tthis.source = Select(this.source, predicate)\n\treturn this\n}\n\nfunc (this *Query) SelectBy(properties map[string]interface{}) Queryer {\n\tthis.source = SelectBy(this.source, properties)\n\treturn this\n}\n\nfunc SelectBy(source interface{}, properties map[string]interface{}) interface{} ", "output": "{\n\treturn Select(source, func (value, _ interface{}) bool {\n\t\treturn IsMatch(value, properties)\n\t})\n}"} {"input": "package camelcase\n\nimport (\n\t\"bytes\"\n\t\"unicode/utf8\"\n\n\t\"github.com/blevesearch/bleve/analysis\"\n\t\"github.com/blevesearch/bleve/registry\"\n)\n\nconst Name = \"camelCase\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype CamelCaseFilter struct{}\n\nfunc NewCamelCaseFilter() *CamelCaseFilter {\n\treturn &CamelCaseFilter{}\n}\n\n\n\nfunc CamelCaseFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) {\n\treturn NewCamelCaseFilter(), nil\n}\n\nfunc init() {\n\tregistry.RegisterTokenFilter(Name, CamelCaseFilterConstructor)\n}\n\nfunc (f *CamelCaseFilter) Filter(input analysis.TokenStream) analysis.TokenStream ", "output": "{\n\trv := make(analysis.TokenStream, 0, len(input))\n\n\tnextPosition := 1\n\tfor _, token := range input {\n\t\truneCount := utf8.RuneCount(token.Term)\n\t\trunes := bytes.Runes(token.Term)\n\n\t\tp := NewParser(runeCount, nextPosition, token.Start)\n\t\tfor i := 0; i < runeCount; i++ {\n\t\t\tif i+1 >= runeCount {\n\t\t\t\tp.Push(runes[i], nil)\n\t\t\t} else {\n\t\t\t\tp.Push(runes[i], &runes[i+1])\n\t\t\t}\n\t\t}\n\t\trv = append(rv, p.FlushTokens()...)\n\t\tnextPosition = p.NextPosition()\n\t}\n\treturn rv\n}"} {"input": "package enforcer\n\nimport (\n\t\"bufio\"\n\t\"encoding/binary\"\n)\n\ntype hashWriter struct {\n\t*bufio.Writer\n}\n\n\n\nfunc (w hashWriter) WriteString(s string) {\n\tw.WriteInt(len(s))\n\tw.Writer.WriteString(s)\n}\n\nfunc (w hashWriter) WriteInt(v int) ", "output": "{\n\tvar buf [8]byte\n\tbinary.LittleEndian.PutUint64(buf[:], uint64(v))\n\tw.Write(buf[:])\n}"} {"input": "package iso20022\n\n\ntype SecuritiesCertificate5 struct {\n\n\tNumber *RestrictedFINXMax30Text `xml:\"Nb\"`\n\n\tIssuer *Max4AlphaNumericText `xml:\"Issr,omitempty\"`\n\n\tSchemeName *Max4AlphaNumericText `xml:\"SchmeNm,omitempty\"`\n}\n\nfunc (s *SecuritiesCertificate5) SetNumber(value string) {\n\ts.Number = (*RestrictedFINXMax30Text)(&value)\n}\n\nfunc (s *SecuritiesCertificate5) SetIssuer(value string) {\n\ts.Issuer = (*Max4AlphaNumericText)(&value)\n}\n\n\n\nfunc (s *SecuritiesCertificate5) SetSchemeName(value string) ", "output": "{\n\ts.SchemeName = (*Max4AlphaNumericText)(&value)\n}"} {"input": "package logrus_papertrail\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/botemout/consul-alerts/Godeps/_workspace/src/github.com/Sirupsen/logrus\"\n)\n\nconst (\n\tformat = \"Jan 2 15:04:05\"\n)\n\n\ntype PapertrailHook struct {\n\tHost string\n\tPort int\n\tAppName string\n\tUDPConn net.Conn\n}\n\n\nfunc NewPapertrailHook(host string, port int, appName string) (*PapertrailHook, error) {\n\tconn, err := net.Dial(\"udp\", fmt.Sprintf(\"%s:%d\", host, port))\n\treturn &PapertrailHook{host, port, appName, conn}, err\n}\n\n\n\n\n\nfunc (hook *PapertrailHook) Levels() []logrus.Level {\n\treturn []logrus.Level{\n\t\tlogrus.PanicLevel,\n\t\tlogrus.FatalLevel,\n\t\tlogrus.ErrorLevel,\n\t\tlogrus.WarnLevel,\n\t\tlogrus.InfoLevel,\n\t\tlogrus.DebugLevel,\n\t}\n}\n\nfunc (hook *PapertrailHook) Fire(entry *logrus.Entry) error ", "output": "{\n\tdate := time.Now().Format(format)\n\tmsg, _ := entry.String()\n\tpayload := fmt.Sprintf(\"<22> %s %s: %s\", date, hook.AppName, msg)\n\n\tbytesWritten, err := hook.UDPConn.Write([]byte(payload))\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to send log line to Papertrail via UDP. Wrote %d bytes before error: %v\", bytesWritten, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package trie\n\nimport \"fmt\"\n\ntype FullNode struct {\n\ttrie *Trie\n\tnodes [17]Node\n}\n\nfunc NewFullNode(t *Trie) *FullNode {\n\treturn &FullNode{trie: t}\n}\n\nfunc (self *FullNode) Dirty() bool { return true }\nfunc (self *FullNode) Value() Node {\n\tself.nodes[16] = self.trie.trans(self.nodes[16])\n\treturn self.nodes[16]\n}\nfunc (self *FullNode) Branches() []Node {\n\treturn self.nodes[:16]\n}\n\n\n\n\nfunc (self *FullNode) Len() (amount int) {\n\tfor _, node := range self.nodes {\n\t\tif node != nil {\n\t\t\tamount++\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (self *FullNode) Hash() interface{} {\n\treturn self.trie.store(self)\n}\n\nfunc (self *FullNode) RlpData() interface{} {\n\tt := make([]interface{}, 17)\n\tfor i, node := range self.nodes {\n\t\tif node != nil {\n\t\t\tt[i] = node.Hash()\n\t\t} else {\n\t\t\tt[i] = \"\"\n\t\t}\n\t}\n\n\treturn t\n}\n\nfunc (self *FullNode) set(k byte, value Node) {\n\tif _, ok := value.(*ValueNode); ok && k != 16 {\n\t\tfmt.Println(value, k)\n\t}\n\n\tself.nodes[int(k)] = value\n}\n\nfunc (self *FullNode) branch(i byte) Node {\n\tif self.nodes[int(i)] != nil {\n\t\tself.nodes[int(i)] = self.trie.trans(self.nodes[int(i)])\n\n\t\treturn self.nodes[int(i)]\n\t}\n\treturn nil\n}\n\nfunc (self *FullNode) Copy(t *Trie) Node ", "output": "{\n\tnnode := NewFullNode(t)\n\tfor i, node := range self.nodes {\n\t\tif node != nil {\n\t\t\tnnode.nodes[i] = node.Copy(t)\n\t\t}\n\t}\n\n\treturn nnode\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/user\"\n)\n\nfunc main() {\n\tstartServer()\n}\n\n\n\nfunc certsExists(certFile string, keyFile string) bool {\n\tfor _, file := range []string{certFile, keyFile} {\n\t\t_, err := os.Stat(file)\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc findPort(ssl bool) string {\n\tport := os.Getenv(\"PORT\")\n\tif len(port) == 0 {\n\t\tuser := !isRoot()\n\t\tif ssl {\n\t\t\tif user {\n\t\t\t\tport = \"4443\"\n\t\t\t} else {\n\t\t\t\tport = \"443\"\n\t\t\t}\n\t\t} else {\n\t\t\tif user {\n\t\t\t\tport = \"8080\"\n\t\t\t} else {\n\t\t\t\tport = \"80\"\n\t\t\t}\n\t\t}\n\t}\n\n\treturn port\n}\n\nfunc startServer() {\n\tcertFile := \"certs/server.pem\"\n\tkeyFile := \"certs/server.key\"\n\tssl := certsExists(certFile, keyFile)\n\tport := findPort(ssl)\n\trouter := NewRouter()\n\n\tlog.Printf(\"start listening on port %s\", port)\n\n\tvar err error\n\tif ssl {\n\t\terr = http.ListenAndServeTLS(\":\"+port, certFile, keyFile, router)\n\t} else {\n\t\terr = http.ListenAndServe(\":\"+port, router)\n\t}\n\n\tlog.Fatal(err)\n}\n\nfunc isRoot() bool ", "output": "{\n\tusr, _ := user.Current()\n\treturn usr.Uid == \"0\"\n}"} {"input": "package private\n\nimport \"testing\"\n\n\n\nfunc TestGetFreePort(t *testing.T) ", "output": "{\n\tp, _ := GetFreePort()\n\tif p <= 0 {\n\t\tt.Fatal(\"expecting > 0 port, got:\", p)\n\t}\n}"} {"input": "package simple\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestEqualShouldFail(t *testing.T) ", "output": "{\n\ta := 1\n\tb := 1\n\tshouldNotBe := false\n\tif real := equal(a, b); real == shouldNotBe {\n\t\tt.Errorf(\"equal(%d, %d) should not be %v, but is:%v\\n\", a, b, shouldNotBe, real)\n\t}\n}"} {"input": "package apigateway\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\n\ntype RenameQueryParameterPolicyItem struct {\n\n\tFrom *string `mandatory:\"true\" json:\"from\"`\n\n\tTo *string `mandatory:\"true\" json:\"to\"`\n}\n\n\n\nfunc (m RenameQueryParameterPolicyItem) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package cpf\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\nfunc Valid(digits string) (bool, error) {\n\treturn valid(digits)\n}\n\nfunc sanitize(data string) string {\n\tdata = strings.Replace(data, \".\", \"\", -1)\n\tdata = strings.Replace(data, \"-\", \"\", -1)\n\treturn data\n}\n\n\n\nconst blacklist = `00000000000\n11111111111\n22222222222\n33333333333\n44444444444\n55555555555\n66666666666\n77777777777\n88888888888\n99999999999\n12345678909`\n\nfunc stringToIntSlice(data string) (res []int) {\n\tfor _, d := range data {\n\t\tx, err := strconv.Atoi(string(d))\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, x)\n\t}\n\treturn\n}\n\nfunc verify(data []int, n int) int {\n\tvar total int\n\n\tfor i := 0; i < n; i++ {\n\t\ttotal += data[i] * (n + 1 - i)\n\t}\n\n\ttotal = total % 11\n\tif total < 2 {\n\t\treturn 0\n\t}\n\treturn 11 - total\n}\n\nfunc check(data string) bool {\n\treturn checkEach(data, 9) && checkEach(data, 10)\n}\n\nfunc checkEach(data string, n int) bool {\n\tfinal := verify(stringToIntSlice(data), n)\n\n\tx, err := strconv.Atoi(string(data[n]))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn final == x\n}\n\nfunc valid(data string) (bool, error) ", "output": "{\n\tdata = sanitize(data)\n\n\tif len(data) != 11 {\n\t\treturn false, errors.New(\"Invalid length\")\n\t}\n\n\tif strings.Contains(blacklist, data) || !check(data) {\n\t\treturn false, errors.New(\"Invalid value\")\n\t}\n\n\treturn true, nil\n}"} {"input": "package api\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/mundipagg/boleto-api/models\"\n)\n\n\nfunc validateRegisterV1(c *gin.Context) {\n\trules := getBoletoFromContext(c).Title.Rules\n\tbn := getBankFromContext(c).GetBankNumber()\n\n\tif rules != nil {\n\t\tc.AbortWithStatusJSON(400, models.NewSingleErrorCollection(\"MP400\", \"title.rules not available in this version\"))\n\t\treturn\n\t}\n\n\tif bn == models.Stone {\n\t\tc.AbortWithStatusJSON(400, models.NewSingleErrorCollection(\"MP400\", \"bank Stone not available in this version\"))\n\t\treturn\n\t}\n}\n\n\n\n\nfunc validateRegisterV2(c *gin.Context) ", "output": "{\n\tr := getBoletoFromContext(c).Title.Rules\n\tbn := getBankFromContext(c).GetBankNumber()\n\n\tif r != nil && bn != models.Caixa {\n\t\tc.AbortWithStatusJSON(400, models.NewSingleErrorCollection(\"MP400\", \"title.rules not available for this bank\"))\n\t\treturn\n\t}\n}"} {"input": "package commands\n\nimport (\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"github.com/jamesread/ovress/pkg/indexer\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nfunc newIndexCmd() *cobra.Command {\n\tvar indexCmd = &cobra.Command{\n\t\tUse: \"index\",\n\t\tShort: \"Indexes a file path\",\n\t\tRun: runIndexCmd,\n\t\tArgs: cobra.MinimumNArgs(1),\n\t}\n\n\treturn indexCmd\n}\n\nfunc runIndexCmd(cmd *cobra.Command, args []string) {\n\tfor _, path := range args {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"path\": path,\n\t\t}).Infof(\"Indexing starting\")\n\n\t\troot := indexer.ScanRoot(path)\n\t\tindexer.SaveIndex(root)\n\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"path\": path,\n\t\t}).Infof(\"Indexing complete\")\n\t}\n}\n\n\n\nfunc init() ", "output": "{\n\trootCmd.AddCommand(newIndexCmd())\n}"} {"input": "package iptables\n\nimport (\n\t\"github.com/google/netstack/tcpip/buffer\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Hook uint\n\n\nconst (\n\tPrerouting Hook = iota\n\n\tInput\n\n\tForward\n\n\tOutput\n\n\tPostrouting\n\n\tNumHooks\n)\n\n\n\ntype Verdict int\n\nconst (\n\tAccept Verdict = iota\n\n\tDrop\n\n\tStolen\n\n\tQueue\n\n\tRepeat\n\n\tNone\n\n\tJump\n\n\tContinue\n\n\tReturn\n)\n\n\ntype IPTables struct {\n\tTables map[string]Table\n\n\tPriorities map[Hook][]string\n}\n\n\n\n\n\ntype Table struct {\n\tBuiltinChains map[Hook]Chain\n\n\tDefaultTargets map[Hook]Target\n\n\tUserChains map[string]Chain\n\n\tChains map[string]*Chain\n\n\tmetadata interface{}\n}\n\n\nfunc (table *Table) ValidHooks() uint32 {\n\thooks := uint32(0)\n\tfor hook, _ := range table.BuiltinChains {\n\t\thooks |= 1 << hook\n\t}\n\treturn hooks\n}\n\n\n\n\n\nfunc (table *Table) SetMetadata(metadata interface{}) {\n\ttable.metadata = metadata\n}\n\n\n\n\n\n\n\n\ntype Chain struct {\n\tName string\n\n\tRules []Rule\n}\n\n\n\n\n\ntype Rule struct {\n\tMatchers []Matcher\n\n\tTarget Target\n}\n\n\ntype Matcher interface {\n\tMatch(hook Hook, packet buffer.VectorisedView, interfaceName string) (matches bool, hotdrop bool)\n}\n\n\ntype Target interface {\n\tAction(packet buffer.VectorisedView) (Verdict, string)\n}\n\nfunc (table *Table) Metadata() interface{} ", "output": "{\n\treturn table.metadata\n}"} {"input": "package memory\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"github.com/google/trillian/monitoring\"\n\t\"github.com/google/trillian/storage\"\n)\n\nfunc init() {\n\tif err := storage.RegisterProvider(\"memory\", newMemoryStorageProvider); err != nil {\n\t\tglog.Fatalf(\"Failed to register storage provider memory: %v\", err)\n\t}\n}\n\ntype memProvider struct {\n\tmf monitoring.MetricFactory\n\tts *TreeStorage\n}\n\n\n\nfunc (s *memProvider) LogStorage() storage.LogStorage {\n\treturn NewLogStorage(s.ts, s.mf)\n}\n\nfunc (s *memProvider) MapStorage() storage.MapStorage {\n\treturn nil\n}\n\nfunc (s *memProvider) AdminStorage() storage.AdminStorage {\n\treturn NewAdminStorage(s.ts)\n}\n\nfunc (s *memProvider) Close() error {\n\treturn nil\n}\n\nfunc newMemoryStorageProvider(mf monitoring.MetricFactory) (storage.Provider, error) ", "output": "{\n\treturn &memProvider{\n\t\tmf: mf,\n\t\tts: NewTreeStorage(),\n\t}, nil\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\n\n\nfunc PodContainerKey(namespace, podName, containerName string) string {\n\treturn fmt.Sprintf(\"namespace:%s/pod:%s/container:%s\", namespace, podName, containerName)\n}\n\nfunc PodKey(namespace, podName string) string {\n\treturn fmt.Sprintf(\"namespace:%s/pod:%s\", namespace, podName)\n}\n\n\n\nfunc NodeKey(node string) string {\n\treturn fmt.Sprintf(\"node:%s\", node)\n}\n\nfunc NodeContainerKey(node, container string) string {\n\treturn fmt.Sprintf(\"node:%s/container:%s\", node, container)\n}\n\nfunc ClusterKey() string {\n\treturn \"cluster\"\n}\n\nfunc NamespaceKey(namespace string) string ", "output": "{\n\treturn fmt.Sprintf(\"namespace:%s\", namespace)\n}"} {"input": "package fake\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\n\t. \"github.com/onsi/gomega\"\n\t\"github.com/onsi/gomega/ghttp\"\n)\n\ntype CFAPI struct {\n\tserver *ghttp.Server\n}\n\ntype CFAPIConfig struct {\n\tRoutes map[string]Response\n}\n\ntype Response struct {\n\tCode int\n\tBody interface{}\n}\n\nfunc NewCFAPI() *CFAPI {\n\tserver := ghttp.NewServer()\n\treturn &CFAPI{\n\t\tserver: server,\n\t}\n}\n\nfunc (a *CFAPI) SetConfiguration(config CFAPIConfig) {\n\ta.server.Reset()\n\n\tfor request, response := range config.Routes {\n\t\tmethod, path := parseRequest(request)\n\t\tresponseBytes, err := json.Marshal(response.Body)\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\ta.server.RouteToHandler(method, path, ghttp.RespondWith(response.Code, responseBytes))\n\t}\n}\n\nfunc (a *CFAPI) Close() {\n\ta.server.Close()\n}\n\nfunc (a *CFAPI) URL() string {\n\treturn a.server.URL()\n}\n\n\n\nfunc parseRequest(request string) (string, string) {\n\tfields := strings.Split(request, \" \")\n\tExpect(fields).To(HaveLen(2))\n\treturn fields[0], fields[1]\n}\n\nfunc (a *CFAPI) ReceivedRequests() map[string][]*http.Request ", "output": "{\n\tresult := map[string][]*http.Request{}\n\n\tfor _, req := range a.server.ReceivedRequests() {\n\t\tkey := fmt.Sprintf(\"%s %s\", req.Method, req.URL.Path)\n\t\tresult[key] = append(result[key], req)\n\t}\n\n\treturn result\n}"} {"input": "package next_permutation\n\nfunc nextPermutation(nums []int) {\n\tn := len(nums)\n\tif n < 2 {\n\t\treturn\n\t}\n\tindex := n - 1\n\tfor ; index > 0; index-- {\n\t\tif nums[index-1] < nums[index] {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif index == 0 {\n\t\treverseSort(nums, 0, n-1)\n\t\treturn\n\t}\n\n\tval := nums[index-1]\n\tj := n - 1\n\tfor ; j >= index && nums[j] <= val; j-- {\n\t}\n\tnums[j], nums[index-1] = val, nums[j]\n\n\treverseSort(nums, index, n-1)\n}\n\n\n\n\nfunc reverseSort(nums []int, start, end int) ", "output": "{\n\tif start > end {\n\t\treturn\n\t}\n\tfor i := start; i <= (end+start)/2; i++ {\n\t\tnums[i], nums[start+end-i] = nums[start+end-i], nums[i]\n\t}\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/networking/v1\"\n\t\"k8s.io/client-go/deprecated/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype NetworkingV1Interface interface {\n\tRESTClient() rest.Interface\n\tNetworkPoliciesGetter\n}\n\n\ntype NetworkingV1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *NetworkingV1Client) NetworkPolicies(namespace string) NetworkPolicyInterface {\n\treturn newNetworkPolicies(c, namespace)\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *NetworkingV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *NetworkingV1Client {\n\treturn &NetworkingV1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *NetworkingV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfig(c *rest.Config) (*NetworkingV1Client, error) ", "output": "{\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &NetworkingV1Client{client}, nil\n}"} {"input": "package runtime\n\nimport (\n\t\"strings\"\n\n\t\"github.com/Shopify/go-lua\"\n\t\"github.com/fsouza/go-dockerclient\"\n\t\"github.com/involucro/involucro/auth\"\n\t\"github.com/involucro/involucro/ilog\"\n)\n\ntype pushStepBuilderState struct {\n\tpushStep\n\tupper fm\n\tregisterStep func(Step)\n}\n\ntype pushStep struct {\n\tdocker.PushImageOptions\n}\n\nfunc newPushSubBuilder(upper fm, register func(Step)) lua.Function {\n\tpsbs := pushStepBuilderState{\n\t\tupper: upper,\n\t\tregisterStep: register,\n\t}\n\treturn psbs.push\n}\n\nfunc (psbs pushStepBuilderState) push(l *lua.State) int {\n\topts := &psbs.PushImageOptions\n\topts.Name = lua.CheckString(l, 1)\n\tif l.Top() >= 2 {\n\t\topts.Tag = lua.CheckString(l, 2)\n\t} else {\n\t\topts.Name, _, opts.Tag = repoNameAndTagFrom(opts.Name)\n\t}\n\tpsbs.registerStep(psbs.pushStep)\n\n\treturn tableWith(l, psbs.upper)\n}\n\nfunc (s pushStep) Take(i *Runtime) error {\n\tac, foundAuthentication, err := auth.ForServer(serverOfRepo(s.PushImageOptions.Name))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := i.client.PushImage(s.PushImageOptions, ac); err != nil {\n\t\tif !foundAuthentication {\n\t\t\tilog.Warn.Logf(\"Pull may have failed due to missing authentication information in ~/.involucro\")\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (s pushStep) ShowStartInfo() {\n\tlogTask.Logf(\"Push image [%s:%s]\", s.Name, s.Tag)\n}\n\n\n\nfunc serverOfRepo(name string) string ", "output": "{\n\tparts := strings.Split(name, \"/\")\n\tif len(parts) < 3 {\n\t\treturn \"\"\n\t}\n\treturn strings.Join(parts[:len(parts)-2], \"/\")\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/jackmanlabs/rpc/v2\"\n\t\"github.com/jackmanlabs/rpc/v2/json2\"\n)\n\ntype Counter struct {\n\tCount int\n}\n\ntype IncrReq struct {\n\tDelta int\n}\n\n\nfunc (c *Counter) Incr(r *http.Request, req *IncrReq, res *json2.EmptyResponse) error {\n\tlog.Printf(\"<- Incr %+v\", *req)\n\tc.Count += req.Delta\n\treturn nil\n}\n\ntype GetReq struct {\n}\n\n\n\nfunc main() {\n\taddress := flag.String(\"address\", \":65534\", \"\")\n\ts := rpc.NewServer()\n\ts.RegisterCodec(json2.NewCustomCodec(&rpc.CompressionSelector{}), \"application/json\")\n\ts.RegisterService(new(Counter), \"\")\n\thttp.Handle(\"/\", http.StripPrefix(\"/\", http.FileServer(http.Dir(\"./\"))))\n\thttp.Handle(\"/jsonrpc/\", s)\n\tlog.Fatal(http.ListenAndServe(*address, nil))\n}\n\nfunc (c *Counter) Get(r *http.Request, req *GetReq, res *Counter) error ", "output": "{\n\tlog.Printf(\"<- Get %+v\", *req)\n\t*res = *c\n\tlog.Printf(\"-> %v\", *res)\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/docker/docker/api/types/filters\"\n)\n\n\n\n\n\n\nfunc imagesCmd(ctx *cli.Context) {\n\tclient := getDockerClient()\n\n\tif ctx.GlobalBool(\"force\") {\n\t\tcd := getCacheFile()\n\t\tcd.reset()\n\t}\n\n\tif imgs, err := client.ImageList(context.Background(), types.ImageListOptions{}); err != nil {\n\t\tlogAndFatalf(\"Cannot proceed safely: %v.\", err)\n\t} else {\n\t\tprintImages(imgs)\n\t\texitWithCode(0)\n\t}\n}\n\n\n\nfunc checkImageExists(repo, tag string) (bool, error) {\n\tclient := getDockerClient()\n\n\timages, err := client.ImageList(context.Background(), types.ImageListOptions{\n\t\tAll: false,\n\t\tFilters: filters.NewArgs(filters.Arg(\"reference\", repo)),\n\t})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(images) == 0 {\n\t\treturn false, nil\n\t}\n\n\tref := fmt.Sprintf(\"%s:%s\", repo, tag)\n\tfor _, image := range images {\n\t\tfor _, t := range image.RepoTags {\n\t\t\tif ref == t {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn false, nil\n}\n\nfunc printImages(images []types.ImageSummary) ", "output": "{\n\tsuseImages := make([]types.ImageSummary, 0, len(images))\n\tcache := getCacheFile()\n\tcounter := 0\n\n\tfor _, img := range images {\n\t\tselect {\n\t\tcase <-killChannel:\n\t\t\treturn\n\t\tdefault:\n\t\t\tfmt.Printf(\"Inspecting image %d/%d\\r\", (counter + 1), len(images))\n\t\t\tif cache.isSUSE(img.ID) {\n\t\t\t\tsuseImages = append(suseImages, img)\n\t\t\t}\n\t\t}\n\t\tcounter++\n\t}\n\tformatAndPrint(suseImages)\n\tcache.flush()\n}"} {"input": "package sample\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n)\n\ntype sampleState struct {\n\trate uint64\n\tseed int64\n\tsampleCount uint64\n\ttrueCount uint64\n\trnd *rand.Rand\n}\n\n\ntype Sampler interface {\n\tSample() bool\n\tSampleFrom(probe uint64) bool\n\tState\n}\n\n\ntype State interface {\n\tReset()\n\tString() string\n\tRate() uint64\n\tCalls() uint64\n\tCount() uint64\n}\n\n\n\nfunc (state *sampleState) Calls() uint64 {\n\tif state != nil {\n\t\treturn state.sampleCount\n\t}\n\treturn 0\n}\n\nfunc (state *sampleState) Count() uint64 {\n\tif state != nil {\n\t\treturn state.trueCount\n\t}\n\treturn 0\n}\n\nfunc (state *sampleState) Reset() {\n\tstate.rnd.Seed(state.seed)\n\tstate.sampleCount = 0\n\tstate.trueCount = 0\n}\n\nfunc (state *sampleState) String() string {\n\ttype X *sampleState\n\tx := X(state)\n\treturn fmt.Sprintf(\"%+v\", x)\n}\n\n\nfunc Deviation(state State) (deviation float64) {\n\tif state != nil && state.Count() > 0 {\n\t\tdeviation = 1.0 - 1.0/float64(state.Rate())*(float64(state.Calls())/float64(state.Count()))\n\t} else {\n\t\tdeviation = 1.0\n\t}\n\n\treturn\n}\n\n\nfunc Stats(state State) string {\n\tif state != nil {\n\t\treturn fmt.Sprintf(\"Rate: %d, SampleCount: %d, TrueCount: %d, Deviation: %.4f%%\", state.Rate(), state.Calls(), state.Count(), Deviation(state)*100.0)\n\t}\n\treturn \"No state provided\"\n}\n\nfunc (state *sampleState) Rate() uint64 ", "output": "{\n\tif state != nil {\n\t\treturn state.rate\n\t}\n\treturn 0\n}"} {"input": "package gce\n\nimport (\n\t\"context\"\n\t\"github.com/supergiant/control/pkg/clouds/gcesdk\"\n\t\"io\"\n\n\t\"github.com/pkg/errors\"\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/supergiant/control/pkg/workflows/steps\"\n\t\"google.golang.org/api/compute/v1\"\n)\n\nconst DeleteTargetPoolStepName = \"gce_delete_target_pool\"\n\ntype DeleteTargetPoolStep struct {\n\tgetComputeSvc func(context.Context, steps.GCEConfig) (*computeService, error)\n}\n\n\n\nfunc (s *DeleteTargetPoolStep) Run(ctx context.Context, output io.Writer,\n\tconfig *steps.Config) error {\n\n\tlogrus.Debugf(\"Step %s\", DeleteTargetPoolStepName)\n\n\tsvc, err := s.getComputeSvc(ctx, config.GCEConfig)\n\n\tif err != nil {\n\t\tlogrus.Errorf(\"Error getting service %v\", err)\n\t\treturn errors.Wrapf(err, \"%s getting service caused\", DeleteTargetPoolStepName)\n\t}\n\n\t_, err = svc.deleteTargetPool(ctx, config.GCEConfig, config.GCEConfig.TargetPoolName)\n\n\tif err != nil {\n\t\tlogrus.Errorf(\"Error deleting target pool %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (s *DeleteTargetPoolStep) Name() string {\n\treturn DeleteTargetPoolStepName\n}\n\nfunc (s *DeleteTargetPoolStep) Depends() []string {\n\treturn nil\n}\n\nfunc (s *DeleteTargetPoolStep) Description() string {\n\treturn \"Delete target pool master nodes\"\n}\n\nfunc (s *DeleteTargetPoolStep) Rollback(context.Context, io.Writer, *steps.Config) error {\n\treturn nil\n}\n\nfunc NewDeleteTargetPoolStep() *DeleteTargetPoolStep ", "output": "{\n\treturn &DeleteTargetPoolStep{\n\t\tgetComputeSvc: func(ctx context.Context, config steps.GCEConfig) (*computeService, error) {\n\t\t\tclient, err := gcesdk.GetClient(ctx, config)\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\treturn &computeService{\n\t\t\t\tdeleteTargetPool: func(ctx context.Context, config steps.GCEConfig, targetPoolName string) (*compute.Operation, error) {\n\t\t\t\t\treturn client.TargetPools.Delete(config.ServiceAccount.ProjectID, config.Region, targetPoolName).Do()\n\t\t\t\t},\n\t\t\t}, nil\n\t\t},\n\t}\n}"} {"input": "package local\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/grafana/loki/pkg/storage/chunk\"\n)\n\ntype TableClient struct {\n\tdirectory string\n}\n\n\nfunc NewTableClient(directory string) (chunk.TableClient, error) {\n\treturn &TableClient{directory: directory}, nil\n}\n\nfunc (c *TableClient) ListTables(ctx context.Context) ([]string, error) {\n\tboltDbFiles := []string{}\n\terr := filepath.Walk(c.directory, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\tboltDbFiles = append(boltDbFiles, info.Name())\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn boltDbFiles, nil\n}\n\nfunc (c *TableClient) CreateTable(ctx context.Context, desc chunk.TableDesc) error {\n\tfile, err := os.OpenFile(filepath.Join(c.directory, desc.Name), os.O_CREATE|os.O_RDONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn file.Close()\n}\n\nfunc (c *TableClient) DeleteTable(ctx context.Context, name string) error {\n\treturn os.Remove(filepath.Join(c.directory, name))\n}\n\nfunc (c *TableClient) DescribeTable(ctx context.Context, name string) (desc chunk.TableDesc, isActive bool, err error) {\n\treturn chunk.TableDesc{\n\t\tName: name,\n\t}, true, nil\n}\n\n\n\nfunc (*TableClient) Stop() {}\n\nfunc (c *TableClient) UpdateTable(ctx context.Context, current, expected chunk.TableDesc) error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\n\n\nfunc Build(srcPath, targetPath string) (files Files, err error) ", "output": "{\n\tfiles, err = ReadFiles(srcPath)\n\tif err != nil {\n\t\tlogger.Error(\"Read\", \"err\", err)\n\t\treturn\n\t}\n\n\terr = TransformFiles(files)\n\tif err != nil {\n\t\tlogger.Error(\"Transform\", \"err\", err)\n\t\treturn\n\t}\n\n\terr = WriteFiles(files, targetPath)\n\tif err != nil {\n\t\tlogger.Error(\"Write\", \"err\", err)\n\t\treturn\n\t}\n\n\treturn\n}"} {"input": "package ftp\n\nimport \"io\"\n\ntype debugWrapper struct {\n\tconn io.ReadWriteCloser\n\tio.Reader\n\tio.Writer\n}\n\nfunc newDebugWrapper(conn io.ReadWriteCloser, w io.Writer) io.ReadWriteCloser {\n\treturn &debugWrapper{\n\t\tReader: io.TeeReader(conn, w),\n\t\tWriter: io.MultiWriter(w, conn),\n\t\tconn: conn,\n\t}\n}\n\nfunc (w *debugWrapper) Close() error {\n\treturn w.conn.Close()\n}\n\ntype streamDebugWrapper struct {\n\tio.Reader\n\tcloser io.ReadCloser\n}\n\nfunc newStreamDebugWrapper(rd io.ReadCloser, w io.Writer) io.ReadCloser {\n\treturn &streamDebugWrapper{\n\t\tReader: io.TeeReader(rd, w),\n\t\tcloser: rd,\n\t}\n}\n\n\n\nfunc (w *streamDebugWrapper) Close() error ", "output": "{\n\treturn w.closer.Close()\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype TerminateDbSystemRequest struct {\n\n\tDbSystemId *string `mandatory:\"true\" contributesTo:\"path\" name:\"dbSystemId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request TerminateDbSystemRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request TerminateDbSystemRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\n\n\n\ntype TerminateDbSystemResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response TerminateDbSystemResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response TerminateDbSystemResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request TerminateDbSystemRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package graph\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gonum/graph\"\n\t\"github.com/gonum/graph/concrete\"\n\t\"github.com/gonum/graph/encoding/dot\"\n)\n\ntype Node struct {\n\tId int\n\tUniqueName string\n\tLabelName string\n\tColor string\n}\n\nfunc (n Node) ID() int {\n\treturn n.Id\n}\n\n\nfunc (n Node) DOTAttributes() []dot.Attribute {\n\tcolor := n.Color\n\tif len(color) == 0 {\n\t\tcolor = \"black\"\n\t}\n\n\treturn []dot.Attribute{\n\t\t{Key: \"label\", Value: fmt.Sprintf(\"%q\", n.LabelName)},\n\t\t{Key: \"color\", Value: color},\n\t}\n}\n\nfunc NewMutableDirectedGraph(g *concrete.DirectedGraph) *MutableDirectedGraph {\n\treturn &MutableDirectedGraph{\n\t\tDirectedGraph: concrete.NewDirectedGraph(),\n\t\tnodesByName: make(map[string]graph.Node),\n\t}\n}\n\ntype MutableDirectedGraph struct {\n\t*concrete.DirectedGraph\n\n\tnodesByName map[string]graph.Node\n}\n\n\n\nfunc (g *MutableDirectedGraph) NodeByName(name string) (graph.Node, bool) {\n\tn, exists := g.nodesByName[name]\n\treturn n, exists && g.DirectedGraph.Has(n)\n}\n\nfunc (g *MutableDirectedGraph) AddNode(n *Node) error ", "output": "{\n\tif _, exists := g.nodesByName[n.UniqueName]; exists {\n\t\treturn fmt.Errorf(\"node .UniqueName collision: %s\", n.UniqueName)\n\t}\n\n\tg.nodesByName[n.UniqueName] = n\n\tg.DirectedGraph.AddNode(n)\n\treturn nil\n}"} {"input": "package tcp\n\nimport (\n\t\"net\"\n\t\"strconv\"\n\n\t\"github.com/reinit/coward/roles/common/network\"\n)\n\n\ntype listener struct {\n\thost net.IP\n\tport uint16\n\tconnectionWrapper network.ConnectionWrapper\n}\n\n\ntype acceptor struct {\n\tlistener *net.TCPListener\n\tconnectionWrapper network.ConnectionWrapper\n\tclosed chan struct{}\n}\n\n\nfunc New(\n\thost net.IP,\n\tport uint16,\n\tconnectionWrapper network.ConnectionWrapper,\n) network.Listener {\n\treturn listener{\n\t\thost: host,\n\t\tport: port,\n\t\tconnectionWrapper: connectionWrapper,\n\t}\n}\n\n\nfunc (t listener) Listen() (network.Acceptor, error) {\n\tlistener, listenErr := net.ListenTCP(\"tcp\", &net.TCPAddr{\n\t\tIP: t.host,\n\t\tPort: int(t.port), \n\t\tZone: \"\",\n\t})\n\n\tif listenErr != nil {\n\t\treturn nil, listenErr\n\t}\n\n\treturn acceptor{\n\t\tlistener: listener,\n\t\tconnectionWrapper: t.connectionWrapper,\n\t\tclosed: make(chan struct{}),\n\t}, nil\n}\n\n\nfunc (t listener) String() string {\n\treturn net.JoinHostPort(\n\t\tt.host.String(), strconv.FormatUint(uint64(t.port), 10))\n}\n\n\nfunc (a acceptor) Addr() net.Addr {\n\treturn a.listener.Addr()\n}\n\n\n\n\n\nfunc (a acceptor) Closed() chan struct{} {\n\treturn a.closed\n}\n\n\nfunc (a acceptor) Close() error {\n\tclose(a.closed)\n\n\treturn a.listener.Close()\n}\n\nfunc (a acceptor) Accept() (network.Connection, error) ", "output": "{\n\taccepted, acceptErr := a.listener.AcceptTCP()\n\n\tif acceptErr != nil {\n\t\treturn nil, acceptErr\n\t}\n\n\toptErr := accepted.SetLinger(0)\n\n\tif optErr != nil {\n\t\treturn nil, optErr\n\t}\n\n\toptErr = accepted.SetNoDelay(false)\n\n\tif optErr != nil {\n\t\treturn nil, optErr\n\t}\n\n\treturn a.connectionWrapper(accepted), nil\n}"} {"input": "package clipboard\n\nimport (\n\tps \"github.com/mitchellh/go-ps\"\n)\n\n\n\n\n\n\nfunc killPrecedessors() error ", "output": "{\n\tprocs, err := ps.Processes()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, proc := range procs {\n\t\twalkFn(proc.Pid(), killProc)\n\t}\n\treturn nil\n}"} {"input": "package collector\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com/go-kit/kit/log\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/procfs\"\n)\n\ntype softnetCollector struct {\n\tfs procfs.FS\n\tprocessed *prometheus.Desc\n\tdropped *prometheus.Desc\n\ttimeSqueezed *prometheus.Desc\n\tlogger log.Logger\n}\n\nconst (\n\tsoftnetSubsystem = \"softnet\"\n)\n\nfunc init() {\n\tregisterCollector(\"softnet\", defaultEnabled, NewSoftnetCollector)\n}\n\n\nfunc NewSoftnetCollector(logger log.Logger) (Collector, error) {\n\tfs, err := procfs.NewFS(*procPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open procfs: %w\", err)\n\t}\n\n\treturn &softnetCollector{\n\t\tfs: fs,\n\t\tprocessed: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, softnetSubsystem, \"processed_total\"),\n\t\t\t\"Number of processed packets\",\n\t\t\t[]string{\"cpu\"}, nil,\n\t\t),\n\t\tdropped: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, softnetSubsystem, \"dropped_total\"),\n\t\t\t\"Number of dropped packets\",\n\t\t\t[]string{\"cpu\"}, nil,\n\t\t),\n\t\ttimeSqueezed: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, softnetSubsystem, \"times_squeezed_total\"),\n\t\t\t\"Number of times processing packets ran out of quota\",\n\t\t\t[]string{\"cpu\"}, nil,\n\t\t),\n\t\tlogger: logger,\n\t}, nil\n}\n\n\n\n\nfunc (c *softnetCollector) Update(ch chan<- prometheus.Metric) error ", "output": "{\n\tstats, err := c.fs.NetSoftnetStat()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not get softnet statistics: %s\", err)\n\t}\n\n\tfor cpuNumber, cpuStats := range stats {\n\t\tcpu := strconv.Itoa(cpuNumber)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.processed,\n\t\t\tprometheus.CounterValue,\n\t\t\tfloat64(cpuStats.Processed),\n\t\t\tcpu,\n\t\t)\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.dropped,\n\t\t\tprometheus.CounterValue,\n\t\t\tfloat64(cpuStats.Dropped),\n\t\t\tcpu,\n\t\t)\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.timeSqueezed,\n\t\t\tprometheus.CounterValue,\n\t\t\tfloat64(cpuStats.TimeSqueezed),\n\t\t\tcpu,\n\t\t)\n\t}\n\n\treturn nil\n}"} {"input": "package aes\n\nimport (\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\n\t\"github.com/golang/glog\"\n)\n\ntype aesInfo struct {\n\tkeyLen int\n\tivLen int\n}\n\nvar info = map[string]aesInfo{\n\t\"aes-128-cfb\": aesInfo{keyLen: 16, ivLen: 16},\n\t\"aes-192-cfb\": aesInfo{keyLen: 24, ivLen: 16},\n\t\"aes-256-cfb\": aesInfo{keyLen: 32, ivLen: 16},\n}\n\n\ntype AES struct {\n\tName string\n}\n\n\nfunc NewAES(aesType string) (*AES, error) {\n\talg := &AES{\n\t\tName: aesType,\n\t}\n\treturn alg, nil\n}\n\n\nfunc (a *AES) NewStream(key, iv []byte, encrypt bool) (cipher.Stream, error) {\n\tglog.V(5).Infoln(\"New Aes Stream\")\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif encrypt {\n\t\treturn cipher.NewCFBEncrypter(block, iv), nil\n\t}\n\treturn cipher.NewCFBDecrypter(block, iv), nil\n}\n\n\n\n\nfunc (a *AES) GetKeyLen() int {\n\tv, ok := info[a.Name]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\treturn v.keyLen\n}\n\nfunc (a *AES) GetIVLen() int ", "output": "{\n\tv, ok := info[a.Name]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\treturn v.ivLen\n}"} {"input": "package utils\n\nimport (\n\t\"github.com/labstack/gommon/log\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nfunc UpdateFile(file, val string) error {\n\tdir := filepath.Dir(file)\n\tlog.Info(\"creating dir %s\", dir)\n\tdir, err := CreateDirIfReqd(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tioutil.WriteFile(filepath.Join(dir, filepath.Base(file)), []byte(val), 0777)\n\treturn nil\n}\n\n\n\nfunc CreateDirIfReqd(dir string) (string, error) ", "output": "{\n\tdirAbsPath, err := filepath.Abs(dir)\n\tif err != nil {\n\t\treturn dirAbsPath, err\n\t}\n\tif _, err := os.Stat(dirAbsPath); err == nil {\n\t\treturn dirAbsPath, nil\n\t}\n\terr = os.MkdirAll(dirAbsPath, 0777)\n\treturn dirAbsPath, err\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc main() {\n\tfmt.Println(Reverse(-27))\n\tfmt.Println(Reverse(314))\n}\n\n\n\nfunc Reverse(d int) (r int) ", "output": "{\n\tfactors := make([]int, 0, 0)\n\tisNeg := false\n\tif d < 0 {\n\t\tisNeg = true\n\t\td *= -1\n\t}\n\tfor {\n\t\tif d == 0 {\n\t\t\tbreak\n\t\t} else {\n\t\t\tfactors = append(factors, d%10)\n\t\t\td = d / 10\n\t\t}\n\t}\n\n\tfor i, v := range factors {\n\t\tr += v * int(math.Pow10(len(factors)-1-i))\n\t}\n\tif isNeg {\n\t\tr *= -1\n\t}\n\treturn r\n}"} {"input": "package test_helpers\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\tdatatypes \"github.com/maximilien/softlayer-go/data_types\"\n)\n\ntype MockProductPackageService struct{}\n\nfunc (mock *MockProductPackageService) GetName() string {\n\treturn \"Mock_Product_Package_Service\"\n}\n\nfunc (mock *MockProductPackageService) GetItemsByType(packageType string) ([]datatypes.SoftLayer_Product_Item, error) {\n\tresponse, _ := ReadJsonTestFixtures(\"services\", \"SoftLayer_Product_Package_getItemsByType_virtual_server.json\")\n\n\tproductItems := []datatypes.SoftLayer_Product_Item{}\n\tjson.Unmarshal(response, &productItems)\n\n\treturn productItems, nil\n}\n\nfunc (mock *MockProductPackageService) GetItemPrices(packageId int) ([]datatypes.SoftLayer_Product_Item_Price, error) {\n\treturn []datatypes.SoftLayer_Product_Item_Price{}, errors.New(\"Not supported\")\n}\n\n\n\nfunc (mock *MockProductPackageService) GetItems(packageId int) ([]datatypes.SoftLayer_Product_Item, error) {\n\treturn []datatypes.SoftLayer_Product_Item{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetPackagesByType(packageType string) ([]datatypes.Softlayer_Product_Package, error) {\n\treturn []datatypes.Softlayer_Product_Package{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetOnePackageByType(packageType string) (datatypes.Softlayer_Product_Package, error) {\n\treturn datatypes.Softlayer_Product_Package{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetItemPricesBySize(packageId int, size int) ([]datatypes.SoftLayer_Product_Item_Price, error) ", "output": "{\n\treturn []datatypes.SoftLayer_Product_Item_Price{}, errors.New(\"Not supported\")\n}"} {"input": "package train\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"path\"\n\t\"strings\"\n)\n\nvar assetServer *http.Handler\nvar publicAssetServer *http.Handler\n\nfunc servePublicAssets(w http.ResponseWriter, r *http.Request) {\n\t(*publicAssetServer).ServeHTTP(w, r)\n}\n\nvar contentTypes = map[string]string{\n\t\".js\": \"application/javascript\",\n\t\".css\": \"text/css\",\n}\n\nfunc serveAssets(w http.ResponseWriter, r *http.Request) {\n\turl := r.URL.Path\n\text := path.Ext(url)\n\n\tswitch ext {\n\tcase \".js\", \".css\":\n\t\tcontent, err := ReadAsset(url)\n\t\tif err != nil {\n\t\t\tif strings.Contains(err.Error(), \"Could not compile\") {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t} else {\n\t\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\t}\n\n\t\t\tio.Copy(w, strings.NewReader(err.Error()))\n\t\t\tlog.Printf(\"Failed to deliver asset\\nGET %s\\n-----------------------\\n%s\\n\", url, err.Error())\n\t\t} else {\n\t\t\tw.Header().Set(\"Content-Type\", contentTypes[ext])\n\t\t\tio.Copy(w, strings.NewReader(content))\n\t\t}\n\tdefault:\n\t\t(*assetServer).ServeHTTP(w, r)\n\t}\n}\n\n\n\nfunc setupFileServer() ", "output": "{\n\tif assetServer == nil {\n\t\tserver := http.FileServer(http.Dir(Config.AssetsPath + \"/..\"))\n\t\tassetServer = &server\n\t}\n\tif publicAssetServer == nil {\n\t\tserver := http.FileServer(http.Dir(\"public\"))\n\t\tpublicAssetServer = &server\n\t}\n}"} {"input": "package p10\n\nimport (\n\t\"fmt\"\n\n\tc \"s13g.com/euler/common\"\n)\n\n\n\nfunc Solve(input string) (string, string) {\n\treturn c.ToString(solveA(c.ParseIntArray(c.SplitByCommaTrim(input)))), solveB(input)\n}\n\nfunc solveA(lengths []int) int {\n\tnumbers := ProcessLengths(lengths, 1)\n\treturn numbers[0] * numbers[1]\n}\n\nfunc solveB(input string) string {\n\tlengths := make([]int, len(input))\n\tfor i, c := range input {\n\t\tlengths[i] = int(c)\n\t}\n\tlengths = append(lengths, 17, 31, 73, 47, 23)\n\tnumbers := ProcessLengths(lengths, 64)\n\n\tdenseHash := make([]int, 16)\n\tfor block := 0; block < 16; block++ {\n\t\tfor start, i := block*16, 0; i < 16; i++ {\n\t\t\tdenseHash[block] ^= numbers[start+i]\n\t\t}\n\t}\n\treturn c.MapIStr(denseHash, func(b int) string { return fmt.Sprintf(\"%02x\", b) })\n}\n\n\nfunc KnotHash(input string) string {\n\treturn solveB(input)\n}\n\n\n\nfunc ProcessLengths(lengths []int, numRounds int) []int ", "output": "{\n\treverseCircular := func(list []int, start int, length int) {\n\t\tfor l, r := start, start+length-1; l < r; l, r = l+1, r-1 {\n\t\t\tll, rr := l%len(list), r%len(list)\n\t\t\tlist[ll], list[rr] = list[rr], list[ll]\n\t\t}\n\t}\n\n\tnumbers := make([]int, 256)\n\tfor i := range numbers {\n\t\tnumbers[i] = i\n\t}\n\n\tcurrPos, skipSize := 0, 0\n\tfor round := 0; round < numRounds; round++ {\n\t\tfor _, length := range lengths {\n\t\t\treverseCircular(numbers, currPos, length)\n\t\t\tcurrPos += length + skipSize\n\t\t\tskipSize++\n\t\t}\n\t}\n\treturn numbers\n}"} {"input": "package operations\n\nimport (\n\t\"github.com/asuleymanov/golos-go/encoding/transaction\"\n)\n\n\ntype BreakFreeReferralOperation struct {\n\tReferral string `json:\"referral\"`\n\tExtensions []interface{} `json:\"extensions\"`\n}\n\n\nfunc (op *BreakFreeReferralOperation) Type() OpType {\n\treturn TypeBreakFreeReferral\n}\n\n\nfunc (op *BreakFreeReferralOperation) Data() interface{} {\n\treturn op\n}\n\n\n\n\nfunc (op *BreakFreeReferralOperation) MarshalTransaction(encoder *transaction.Encoder) error ", "output": "{\n\tenc := transaction.NewRollingEncoder(encoder)\n\tenc.EncodeUVarint(uint64(TypeBreakFreeReferral.Code()))\n\tenc.Encode(op.Referral)\n\tenc.Encode(byte(0))\n\treturn enc.Err()\n}"} {"input": "package misc\n\nimport (\n\t\"net/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\ntype Writer interface {\n\thttp.ResponseWriter\n\thttp.Hijacker\n}\n\n\n\nfunc ElapsedTime(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tnw := elapsedTimeResponseWriter{\n\t\tWriter: w.(Writer),\n\t\tTimestamp: time.Now().UnixNano(),\n\t\twritten: false,\n\t}\n\tnext(&nw, r)\n\n}\n\ntype elapsedTimeResponseWriter struct {\n\tWriter\n\tTimestamp int64\n\twritten bool\n}\n\nfunc (e *elapsedTimeResponseWriter) WriteHeader(status int) {\n\tif e.written == false {\n\t\te.written = true\n\t\te.Writer.Header().Set(\"Elapsed-Time\", strconv.FormatInt(time.Now().UnixNano()-e.Timestamp, 10)+\" ns\")\n\t}\n\te.Writer.WriteHeader(status)\n}\n\n\nfunc (e *elapsedTimeResponseWriter) Write(data []byte) (int, error) ", "output": "{\n\tif e.written == false {\n\t\te.WriteHeader(http.StatusOK)\n\t}\n\treturn e.Writer.Write(data)\n}"} {"input": "package events\n\nimport (\n\t\"fmt\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/klog\"\n)\n\ntype LoggingEventRecorder struct {\n\tcomponent string\n}\n\n\nfunc NewLoggingEventRecorder(component string) Recorder {\n\treturn &LoggingEventRecorder{component: component}\n}\n\nfunc (r *LoggingEventRecorder) ComponentName() string {\n\treturn r.component\n}\n\nfunc (r *LoggingEventRecorder) ForComponent(component string) Recorder {\n\tnewRecorder := *r\n\tnewRecorder.component = component\n\treturn &newRecorder\n}\n\nfunc (r *LoggingEventRecorder) WithComponentSuffix(suffix string) Recorder {\n\treturn r.ForComponent(fmt.Sprintf(\"%s-%s\", r.ComponentName(), suffix))\n}\n\nfunc (r *LoggingEventRecorder) Event(reason, message string) {\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeNormal, reason, message)\n\tklog.Info(event.String())\n}\n\n\n\nfunc (r *LoggingEventRecorder) Warning(reason, message string) {\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeWarning, reason, message)\n\tklog.Warning(event.String())\n}\n\nfunc (r *LoggingEventRecorder) Warningf(reason, messageFmt string, args ...interface{}) {\n\tr.Warning(reason, fmt.Sprintf(messageFmt, args...))\n}\n\nfunc (r *LoggingEventRecorder) Eventf(reason, messageFmt string, args ...interface{}) ", "output": "{\n\tr.Event(reason, fmt.Sprintf(messageFmt, args...))\n}"} {"input": "package custom_commands\n\nimport (\n\t\"github.com/jmoiron/sqlx\"\n\t\"github.com/sgt-kabukiman/kabukibot/bot\"\n)\n\ntype pluginStruct struct {\n\tdb *sqlx.DB\n}\n\nfunc NewPlugin() *pluginStruct {\n\treturn &pluginStruct{}\n}\n\nfunc (self *pluginStruct) Name() string {\n\treturn \"custom_commands\"\n}\n\nfunc (self *pluginStruct) Setup(bot *bot.Kabukibot) {\n\tself.db = bot.Database()\n}\n\n\n\nfunc (self *pluginStruct) CreateWorker(channel bot.Channel) bot.PluginWorker ", "output": "{\n\treturn &worker{\n\t\tchannel: channel,\n\t\tacl: channel.ACL(),\n\t\tdb: self.db,\n\t}\n}"} {"input": "package thread\n\nimport \"time\"\n\ntype ThreadStatistic struct {\n\tThreadId int `json:\"thread_id\"`\n\tProcessedLines int `json:\"processed_lines\"`\n\tStartTime time.Time `json:\"start_time\"`\n\tEndTime time.Time `json:\"end_time\"`\n\tDeltaTime time.Duration `json:\"delta_time\"`\n}\n\nfunc NewThreadStadistic(threadId int) *ThreadStatistic {\n\tvar ts ThreadStatistic\n\n\tts.ThreadId = threadId\n\tts.ProcessedLines = 0\n\tts.StartTime = time.Now()\n\n\treturn &ts\n}\n\n\n\nfunc (ts *ThreadStatistic) SetEndTime() {\n\tts.EndTime = time.Now()\n\tts.DeltaTime = ts.EndTime.Sub(ts.StartTime) / time.Millisecond\n}\n\nfunc (ts *ThreadStatistic) IncreaseProcessedLines() ", "output": "{\n\tts.ProcessedLines += 1\n}"} {"input": "package osc\n\nimport (\n\t\"net\"\n\t\"testing\"\n)\n\n\n\nfunc TestValidateAddress(t *testing.T) {\n\tif err := ValidateAddress(\"/foo\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := ValidateAddress(\"/foo@^#&*$^*%)()#($*@\"); err == nil {\n\t\tt.Fatal(\"expected error, got nil\")\n\t}\n}\n\nfunc TestUDPConn(t *testing.T) ", "output": "{\n\tladdr, err := net.ResolveUDPAddr(\"udp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tlc, err := ListenUDP(\"udp\", laddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar c Conn = lc\n\t_ = c\n}"} {"input": "package main\n\nimport (\n \"log\"\n \"net/http\"\n)\n\n\n\n\n\nfunc main() {\n http.HandleFunc(\"/\", droneServer)\n err := http.ListenAndServe(\":8080\", nil)\n if err != nil {\n log.Fatal(\"ListenAndServe: \", err)\n }\n}\n\nfunc droneServer(w http.ResponseWriter, req *http.Request) ", "output": "{\n w.Write([]byte(\"Built by Drone in Kubernetes!\"))\n}"} {"input": "package vflag\n\nimport \"strings\"\nimport \"net/url\"\n\n\ntype URL struct {\n\tRaw string\n\tSolt *url.URL\n\tSchemes *[]string\n\tRequirePort bool\n}\n\nfunc (val URL) String() string {\n\treturn val.Raw\n}\n\n\n\nfunc (val URL) Set(urlArg string) error ", "output": "{\n\tvar err error = nil\n\tvar u *url.URL = nil\n\tvar isValid bool = false\n\n\tif u, err = url.Parse(urlArg); err != nil {\n\t\treturn err\n\t}\n\tif strings.Index(u.Host, \":\") == -1 && val.RequirePort {\n\t\treturn ErrUrlNoPort\n\t}\n\tif val.Schemes != nil {\n\t\tfor _, s := range *val.Schemes {\n\t\t\tif s == u.Scheme {\n\t\t\t\tisValid = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !isValid {\n\t\t\treturn ErrInvalidUrlScheme\n\t\t}\n\t}\n\t*val.Solt = *u\n\n\treturn nil\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tc := incrementor()\n\tcSum := puller(c)\n\tfor n := range cSum {\n\t\tfmt.Println(n)\n\t}\n}\n\n\n\nfunc puller(c chan int) chan int {\n\tout := make(chan int)\n\tgo func() {\n\t\tvar sum int\n\t\tfor n := range c {\n\t\t\tsum += n\n\t\t}\n\t\tout <- sum\n\t\tclose(out)\n\t}()\n\treturn out\n}\n\nfunc incrementor() chan int ", "output": "{\n\tout := make(chan int)\n\tgo func() {\n\t\tfor i := 0; i < 10; i++ {\n\t\t\tout <- i\n\t\t}\n\t\tclose(out)\n\t}()\n\treturn out\n}"} {"input": "package keys\n\nimport \"context\"\n\n\ntype keySetType int\n\n\nconst keySet = keySetType(0)\n\n\n\n\n\nfunc WithValue(ctx context.Context, key interface{}, value interface{}) context.Context {\n\told, _ := ctx.Value(keySet).(*Link)\n\tctx = context.WithValue(ctx, key, value)\n\treturn context.WithValue(ctx, keySet, &Link{Value: key, Next: old})\n}\n\n\n\nfunc Clone(ctx context.Context, from context.Context) context.Context {\n\tfor _, key := range Get(from) {\n\t\tctx = WithValue(ctx, key, from.Value(key))\n\t}\n\treturn ctx\n}\n\nfunc Get(ctx context.Context) []interface{} ", "output": "{\n\tseen := map[interface{}]bool{}\n\tresult := make([]interface{}, 0, 10)\n\tfor link, _ := ctx.Value(keySet).(*Link); link != nil; link = link.Next {\n\t\tif !seen[link.Value] {\n\t\t\tseen[link.Value] = true\n\t\t\tresult = append(result, link.Value)\n\t\t}\n\t}\n\treturn result\n}"} {"input": "package memdb\n\n\n\ntype Changes []Change\n\n\ntype Change struct {\n\tTable string\n\tBefore interface{}\n\tAfter interface{}\n\n\tprimaryKey []byte\n}\n\n\n\n\n\n\nfunc (m *Change) Updated() bool {\n\treturn m.Before != nil && m.After != nil\n}\n\n\n\nfunc (m *Change) Deleted() bool {\n\treturn m.Before != nil && m.After == nil\n}\n\nfunc (m *Change) Created() bool ", "output": "{\n\treturn m.Before == nil && m.After != nil\n}"} {"input": "package collector\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"unsafe\"\n\n\t\"github.com/go-kit/log\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\n\nimport \"C\"\n\nconst maxCPUTimesLen = C.MAXCPU * C.CPUSTATES\n\ntype statCollector struct {\n\tcpu *prometheus.Desc\n\tlogger log.Logger\n}\n\nfunc init() {\n\tregisterCollector(\"cpu\", defaultEnabled, NewStatCollector)\n}\n\n\nfunc NewStatCollector(logger log.Logger) (Collector, error) {\n\treturn &statCollector{\n\t\tcpu: nodeCPUSecondsDesc,\n\t\tlogger: logger,\n\t}, nil\n}\n\nfunc getDragonFlyCPUTimes() ([]float64, error) {\n\n\tvar (\n\t\tcpuTimesC *C.uint64_t\n\t\tcpuTimesLength C.size_t\n\t)\n\n\tif C.getCPUTimes(&cpuTimesC, &cpuTimesLength) == -1 {\n\t\treturn nil, errors.New(\"could not retrieve CPU times\")\n\t}\n\tdefer C.free(unsafe.Pointer(cpuTimesC))\n\n\tcput := (*[maxCPUTimesLen]C.uint64_t)(unsafe.Pointer(cpuTimesC))[:cpuTimesLength:cpuTimesLength]\n\n\tcpuTimes := make([]float64, cpuTimesLength)\n\tfor i, value := range cput {\n\t\tcpuTimes[i] = float64(value) / float64(1000000)\n\t}\n\treturn cpuTimes, nil\n}\n\n\n\n\nfunc (c *statCollector) Update(ch chan<- prometheus.Metric) error ", "output": "{\n\tvar fieldsCount = 5\n\tcpuTimes, err := getDragonFlyCPUTimes()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcpuFields := []string{\"user\", \"nice\", \"sys\", \"interrupt\", \"idle\"}\n\tfor i, value := range cpuTimes {\n\t\tcpux := strconv.Itoa(i / fieldsCount)\n\t\tch <- prometheus.MustNewConstMetric(c.cpu, prometheus.CounterValue, value, cpux, cpuFields[i%fieldsCount])\n\t}\n\n\treturn nil\n}"} {"input": "package models\n\nimport (\n\t\"database/sql\"\n\t\"github.com/BrandonRomano/serf\"\n\tdb \"github.com/carrot/burrow/db/postgres\"\n\t\"time\"\n)\n\ntype Topic struct {\n\tserf.Worker `json:\"-\"`\n\tId int64 `json:\"id\"`\n\tName string `json:\"name\"`\n\tCreatedAt time.Time `json:\"created_at\"`\n\tUpdatedAt time.Time `json:\"updated_at\"`\n}\n\nfunc NewTopic() *Topic {\n\ttopic := new(Topic)\n\treturn topic.Prep()\n}\n\nfunc (t *Topic) Prep() *Topic {\n\tt.Worker = &serf.PqWorker{\n\t\tDatabase: db.Get(),\n\t\tConfig: serf.Configuration{\n\t\t\tTableName: \"topics\",\n\t\t\tFields: []serf.Field{\n\t\t\t\tserf.Field{Pointer: &t.Id, Name: \"id\", UniqueIdentifier: true,\n\t\t\t\t\tIsSet: func(pointer interface{}) bool {\n\t\t\t\t\t\tpointerInt := *pointer.(*int64)\n\t\t\t\t\t\treturn pointerInt != 0\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tserf.Field{Pointer: &t.Name, Name: \"name\", Insertable: true, Updatable: true},\n\t\t\t\tserf.Field{Pointer: &t.CreatedAt, Name: \"created_at\"},\n\t\t\t\tserf.Field{Pointer: &t.UpdatedAt, Name: \"updated_at\"},\n\t\t\t},\n\t\t},\n\t}\n\treturn t\n}\n\n\n\nfunc (t *Topic) consumeNextRow(rows *sql.Rows) error {\n\treturn rows.Scan(\n\t\t&t.Id,\n\t\t&t.Name,\n\t\t&t.CreatedAt,\n\t\t&t.UpdatedAt,\n\t)\n}\n\nfunc AllTopics(limit int64, offset int64) ([]Topic, error) ", "output": "{\n\tdatabase := db.Get()\n\trows, err := database.Query(\"SELECT * FROM topics ORDER BY created_at LIMIT $1 OFFSET $2\", limit, offset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tvar topics []Topic = []Topic{}\n\tfor rows.Next() {\n\t\tt := new(Topic)\n\t\terr = t.consumeNextRow(rows)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttopics = append(topics, *t)\n\t}\n\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn topics, nil\n}"} {"input": "package chapter3_cf\n\n\ntype SourceFileAttribute struct {\n\tcp ConstantPool\n\tsourceFileIndex uint16\n}\n\n\n\nfunc (self *SourceFileAttribute) FileName() string {\n\treturn self.cp.getUtf8(self.sourceFileIndex)\n}\n\nfunc (self *SourceFileAttribute) readInfo(reader *ClassReader) ", "output": "{\n\tself.sourceFileIndex = reader.readUint16()\n}"} {"input": "package server\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/Arvinderpal/go-storage-server/challenge/common/backend\"\n\t\"github.com/Arvinderpal/go-storage-server/challenge/common/types\"\n\n\t\"github.com/gorilla/mux\"\n)\n\n\ntype Router struct {\n\t*mux.Router\n\troutes routes\n\tdaemon backend.DaemonBackend\n}\n\n\nfunc NewRouter(daemon backend.DaemonBackend) Router {\n\tmRouter := mux.NewRouter().StrictSlash(true)\n\tr := Router{mRouter, routes{}, daemon}\n\tr.initBackendRoutes()\n\tfor _, route := range r.routes {\n\t\thandler := Logger(route.HandlerFunc, route.Name)\n\n\t\tr.Methods(route.Method).\n\t\t\tPath(route.Pattern).\n\t\t\tName(route.Name).\n\t\t\tHandler(handler)\n\t}\n\treturn r\n}\n\n\n\nfunc processServerError(w http.ResponseWriter, r *http.Request, err error) ", "output": "{\n\tw.WriteHeader(http.StatusInternalServerError)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tsErr := types.ServerError{\n\t\tCode: http.StatusInternalServerError,\n\t\tText: fmt.Sprintf(\"an unexpected internal error has occurred: \\\"%s\\\"\", err),\n\t}\n\tlogger.Debugf(\"Processing error %s\\n\", sErr)\n\tlogger.Errorf(\"Error while processing request '%+v': \\\"%s\\\"\", r, err)\n\tif err := json.NewEncoder(w).Encode(sErr); err != nil {\n\t\tlogger.Errorf(\"Error while encoding %T '%+v': \\\"%s\\\"\", sErr, sErr, err)\n\t\tfmt.Fprintf(w, \"Fatal error while processing request '%+v': \\\"%s\\\"\", r, err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n)\n\ntype Player struct {\n\tlog *os.File\n\tlogTime time.Time\n\tdecoder *json.Decoder\n\tdir string\n\toffset time.Duration\n}\n\nfunc NewPlayer(dir string) *Player {\n\tvar p Player\n\tp.dir = dir\n\treturn &p\n}\n\nfunc (p *Player) Reset() error {\n\tn := p.Then()\n\tp.logTime = logTime(n)\n\tfilename := logFileName(n)\n\tif p.log != nil {\n\t\tp.log.Close()\n\t}\n\tlog.Printf(\"Playing file %s\\n\", filename)\n\tvar err error\n\tp.log, err = os.Open(filepath.Join(p.dir, filename))\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.decoder = json.NewDecoder(p.log)\n\treturn nil\n}\n\n\n\n\nfunc (p *Player) Then() time.Time {\n\treturn time.Now().Add(-p.offset)\n}\n\nfunc (p *Player) Close() error {\n\tp.decoder = nil\n\treturn p.log.Close()\n}\n\nfunc (p *Player) Playback(t time.Time) error ", "output": "{\n\tlog.Printf(\"Playing back starting at %s\\n\", t)\n\tp.offset = time.Now().Sub(t)\n\terr := p.Reset()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor {\n\t\tvar m Msg\n\t\terr := p.decoder.Decode(&m)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\td := m.Timestamp.Time.Sub(p.Then())\n\t\tdebugf(\"difference is %f seconds\", d.Seconds())\n\t\tif d > 0 {\n\t\t\ttime.Sleep(d)\n\t\t}\n\t\tm.Print()\n\t}\n}"} {"input": "package requestutil\n\nimport (\n\t\"bytes\"\n\t\"crypto/tls\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/hashicorp/vault/helper/compressutil\"\n\t\"github.com/hashicorp/vault/helper/jsonutil\"\n)\n\ntype bufCloser struct {\n\t*bytes.Buffer\n}\n\nfunc (b bufCloser) Close() error {\n\tb.Reset()\n\treturn nil\n}\n\ntype ForwardedRequest struct {\n\tMethod string `json:\"method\"`\n\n\tURL *url.URL `json:\"url\"`\n\n\tHeader http.Header `json:\"header\"`\n\n\tBody []byte `json:\"body\"`\n\n\tHost string `json:\"host\"`\n\n\tRemoteAddr string `json:\"remote_addr\"`\n\n\tConnectionState *tls.ConnectionState `json:\"connection_state\"`\n}\n\n\n\nfunc GenerateForwardedRequest(req *http.Request, addr string) (*http.Request, error) {\n\tfq := ForwardedRequest{\n\t\tMethod: req.Method,\n\t\tURL: req.URL,\n\t\tHeader: req.Header,\n\t\tHost: req.Host,\n\t\tRemoteAddr: req.RemoteAddr,\n\t\tConnectionState: req.TLS,\n\t}\n\n\tbuf := bytes.NewBuffer(nil)\n\t_, err := buf.ReadFrom(req.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfq.Body = buf.Bytes()\n\n\tnewBody, err := jsonutil.EncodeJSONAndCompress(&fq, &compressutil.CompressionConfig{\n\t\tType: compressutil.CompressionTypeLzw,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret, err := http.NewRequest(\"POST\", addr, bytes.NewBuffer(newBody))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ret, nil\n}\n\n\n\n\n\n\nfunc ParseForwardedRequest(req *http.Request) (*http.Request, error) ", "output": "{\n\tbuf := bufCloser{\n\t\tBuffer: bytes.NewBuffer(nil),\n\t}\n\t_, err := buf.ReadFrom(req.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar fq ForwardedRequest\n\terr = jsonutil.DecodeJSON(buf.Bytes(), &fq)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuf.Reset()\n\t_, err = buf.Write(fq.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := &http.Request{\n\t\tMethod: fq.Method,\n\t\tURL: fq.URL,\n\t\tHeader: fq.Header,\n\t\tBody: buf,\n\t\tHost: fq.Host,\n\t\tRemoteAddr: fq.RemoteAddr,\n\t\tTLS: fq.ConnectionState,\n\t}\n\n\treturn ret, nil\n}"} {"input": "package cronsun\n\nimport (\n\t\"encoding/hex\"\n\n\t\"github.com/rogpeppe/fastuuid\"\n)\n\nvar generator *fastuuid.Generator\n\n\n\nfunc NextID() string {\n\tid := generator.Next()\n\treturn hex.EncodeToString(id[:])\n}\n\nfunc initID() (err error) ", "output": "{\n\tgenerator, err = fastuuid.NewGenerator()\n\treturn\n}"} {"input": "package reveldi\n\n\ntype Container struct {\n\tservices map[string]Service\n}\n\ntype Service interface{}\n\nfunc (c *Container) Register(name string, serviceStruct Service) {\n\tif len(c.services) == 0 {\n\t\tc.services = make(map[string]Service)\n\t}\n\tc.services[name] = serviceStruct\n}\n\n\n\nfunc (c *Container) Get(name string) Service ", "output": "{\n\treturn c.services[name]\n}"} {"input": "package classReader\n\nimport \"math\"\n\ntype ConstantIntegerInfo struct {\n\tval int32\n}\n\nfunc (self *ConstantIntegerInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint32()\n\tself.val = int32(bytes)\n}\n\nfunc (self *ConstantIntegerInfo) Value() int32 {\n\treturn self.val\n}\n\ntype ConstantFloatInfo struct {\n\tval float32\n}\n\nfunc (self *ConstantFloatInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint32()\n\tself.val = math.Float32frombits(bytes)\n}\n\nfunc (self *ConstantFloatInfo) Value() float32 {\n\treturn self.val\n}\n\ntype ConstantLongInfo struct {\n\tval int64\n}\n\nfunc (self *ConstantLongInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint64()\n\tself.val = int64(bytes)\n}\n\nfunc (self *ConstantLongInfo) Value() int64 {\n\treturn self.val\n}\n\ntype ConstantDoubleInfo struct {\n\tval float64\n}\n\n\n\nfunc (self *ConstantDoubleInfo) Value() float64 {\n\treturn self.val\n}\n\nfunc (self *ConstantDoubleInfo) readInfo(reader *ClassReader) ", "output": "{\n\tbytes := reader.readUint64()\n\tself.val = math.Float64frombits(bytes)\n}"} {"input": "package client\n\nimport (\n\tauthorizationapi \"github.com/openshift/origin/pkg/authorization/api\"\n)\n\n\ntype SubjectAccessReviewsNamespacer interface {\n\tSubjectAccessReviews(namespace string) SubjectAccessReviewInterface\n}\n\n\ntype ClusterSubjectAccessReviews interface {\n\tClusterSubjectAccessReviews() SubjectAccessReviewInterface\n}\n\n\ntype SubjectAccessReviewInterface interface {\n\tCreate(policy *authorizationapi.SubjectAccessReview) (*authorizationapi.SubjectAccessReviewResponse, error)\n}\n\n\ntype subjectAccessReviews struct {\n\tr *Client\n\tns string\n}\n\n\nfunc newSubjectAccessReviews(c *Client, namespace string) *subjectAccessReviews {\n\treturn &subjectAccessReviews{\n\t\tr: c,\n\t\tns: namespace,\n\t}\n}\n\n\nfunc (c *subjectAccessReviews) Create(policy *authorizationapi.SubjectAccessReview) (result *authorizationapi.SubjectAccessReviewResponse, err error) {\n\tresult = &authorizationapi.SubjectAccessReviewResponse{}\n\terr = c.r.Post().Namespace(c.ns).Resource(\"subjectAccessReviews\").Body(policy).Do().Into(result)\n\treturn\n}\n\n\ntype clusterSubjectAccessReviews struct {\n\tr *Client\n}\n\n\nfunc newClusterSubjectAccessReviews(c *Client) *clusterSubjectAccessReviews {\n\treturn &clusterSubjectAccessReviews{\n\t\tr: c,\n\t}\n}\n\n\n\n\nfunc (c *clusterSubjectAccessReviews) Create(policy *authorizationapi.SubjectAccessReview) (result *authorizationapi.SubjectAccessReviewResponse, err error) ", "output": "{\n\tresult = &authorizationapi.SubjectAccessReviewResponse{}\n\terr = c.r.Post().Resource(\"subjectAccessReviews\").Body(policy).Do().Into(result)\n\treturn\n}"} {"input": "package logging\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"strings\"\n)\n\ntype transport struct {\n\tname string\n\ttransport http.RoundTripper\n}\n\nfunc (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {\n\tif IsDebugOrHigher() {\n\t\treqData, err := httputil.DumpRequestOut(req, true)\n\t\tif err == nil {\n\t\t\tlog.Printf(\"[DEBUG] \"+logReqMsg, t.name, prettyPrintJsonLines(reqData))\n\t\t} else {\n\t\t\tlog.Printf(\"[ERROR] %s API Request error: %#v\", t.name, err)\n\t\t}\n\t}\n\n\tresp, err := t.transport.RoundTrip(req)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\tif IsDebugOrHigher() {\n\t\trespData, err := httputil.DumpResponse(resp, true)\n\t\tif err == nil {\n\t\t\tlog.Printf(\"[DEBUG] \"+logRespMsg, t.name, prettyPrintJsonLines(respData))\n\t\t} else {\n\t\t\tlog.Printf(\"[ERROR] %s API Response error: %#v\", t.name, err)\n\t\t}\n\t}\n\n\treturn resp, nil\n}\n\nfunc NewTransport(name string, t http.RoundTripper) *transport {\n\treturn &transport{name, t}\n}\n\n\n\n\n\nconst logReqMsg = `%s API Request Details:\n---[ REQUEST ]---------------------------------------\n%s\n-----------------------------------------------------`\n\nconst logRespMsg = `%s API Response Details:\n---[ RESPONSE ]--------------------------------------\n%s\n-----------------------------------------------------`\n\nfunc prettyPrintJsonLines(b []byte) string ", "output": "{\n\tparts := strings.Split(string(b), \"\\n\")\n\tfor i, p := range parts {\n\t\tif b := []byte(p); json.Valid(b) {\n\t\t\tvar out bytes.Buffer\n\t\t\tjson.Indent(&out, b, \"\", \" \")\n\t\t\tparts[i] = out.String()\n\t\t}\n\t}\n\treturn strings.Join(parts, \"\\n\")\n}"} {"input": "package common\n\n\n\n\nimport (\n\t\"strconv\"\n)\n\n\nfunc Atof32(s string) float64 {\n\tf, err := strconv.ParseFloat(s, 32)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn float64(f)\n}\n\n\nfunc Atoi(s string) int {\n\ti, err := strconv.Atoi(s)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn i\n}\n\n\nfunc Atob(str string) bool {\n\tb, err := strconv.ParseBool(str)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn b\n}\n\n\nfunc Atoi64(str string) int64 {\n\ti, err := strconv.ParseInt(str, 10, 64)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn i\n}\n\n\n\n\nfunc Atof64(str string) float64 ", "output": "{\n\ti, err := strconv.ParseFloat(str, 64)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn i\n}"} {"input": "package s0081\n\nimport (\n\t\"github.com/peterstace/project-euler/graph\"\n)\n\ntype matrix [][]int \n\n\n\nfunc parameterised(m matrix) interface{} {\n\tg, start, end := matrixToGraph(m)\n\treturn g.ShortestPath(start)[end]\n}\n\nfunc matrixToGraph(m matrix) (g graph.WeightedDigraph, start int, end int) {\n\tg = graph.NewOrderZeroWeightedDigraph()\n\tn := len(m)\n\tnode := func(i, j int) int {\n\t\treturn i*n + j\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tfor j := 0; j < n; j++ {\n\t\t\tif i > 0 {\n\t\t\t\tg.AddEdge(node(i-1, j), node(i, j), float64(m[i][j]))\n\t\t\t}\n\t\t\tif j > 0 {\n\t\t\t\tg.AddEdge(node(i, j-1), node(i, j), float64(m[i][j]))\n\t\t\t}\n\t\t}\n\t}\n\tg.AddEdge(-1, node(0, 0), float64(m[0][0]))\n\treturn g, -1, node(n-1, n-1)\n}\n\nfunc Answer() interface{} ", "output": "{\n\treturn parameterised(data)\n}"} {"input": "package run_model\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype APIPipelineRuntime struct {\n\n\tPipelineManifest string `json:\"pipeline_manifest,omitempty\"`\n\n\tWorkflowManifest string `json:\"workflow_manifest,omitempty\"`\n}\n\n\n\n\n\nfunc (m *APIPipelineRuntime) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *APIPipelineRuntime) UnmarshalBinary(b []byte) error {\n\tvar res APIPipelineRuntime\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *APIPipelineRuntime) Validate(formats strfmt.Registry) error ", "output": "{\n\treturn nil\n}"} {"input": "package btcec\n\nimport (\n\tsecp \"github.com/decred/dcrd/dcrec/secp256k1/v4\"\n)\n\n\n\ntype JacobianPoint = secp.JacobianPoint\n\n\n\nfunc MakeJacobianPoint(x, y, z *FieldVal) JacobianPoint {\n\treturn secp.MakeJacobianPoint(x, y, z)\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc DecompressY(x *FieldVal, odd bool, resultY *FieldVal) bool {\n\treturn secp.DecompressY(x, odd, resultY)\n}\n\n\n\n\n\n\nfunc DoubleNonConst(p, result *JacobianPoint) {\n\tsecp.DoubleNonConst(p, result)\n}\n\n\n\n\n\n\nfunc ScalarBaseMultNonConst(k *ModNScalar, result *JacobianPoint) {\n\tsecp.ScalarBaseMultNonConst(k, result)\n}\n\n\n\n\n\n\n\nfunc ScalarMultNonConst(k *ModNScalar, point, result *JacobianPoint) {\n\tsecp.ScalarMultNonConst(k, point, result)\n}\n\nfunc AddNonConst(p1, p2, result *JacobianPoint) ", "output": "{\n\tsecp.AddNonConst(p1, p2, result)\n}"} {"input": "package internalversion\n\nimport (\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n\tadmissionregistration \"k8s.io/kubernetes/pkg/apis/admissionregistration\"\n)\n\n\ntype ValidatingWebhookConfigurationLister interface {\n\tList(selector labels.Selector) (ret []*admissionregistration.ValidatingWebhookConfiguration, err error)\n\tGet(name string) (*admissionregistration.ValidatingWebhookConfiguration, error)\n\tValidatingWebhookConfigurationListerExpansion\n}\n\n\ntype validatingWebhookConfigurationLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewValidatingWebhookConfigurationLister(indexer cache.Indexer) ValidatingWebhookConfigurationLister {\n\treturn &validatingWebhookConfigurationLister{indexer: indexer}\n}\n\n\n\n\n\nfunc (s *validatingWebhookConfigurationLister) Get(name string) (*admissionregistration.ValidatingWebhookConfiguration, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(admissionregistration.Resource(\"validatingwebhookconfiguration\"), name)\n\t}\n\treturn obj.(*admissionregistration.ValidatingWebhookConfiguration), nil\n}\n\nfunc (s *validatingWebhookConfigurationLister) List(selector labels.Selector) (ret []*admissionregistration.ValidatingWebhookConfiguration, err error) ", "output": "{\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*admissionregistration.ValidatingWebhookConfiguration))\n\t})\n\treturn ret, err\n}"} {"input": "package machinelearningservices\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) BaseClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient ", "output": "{\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/apier/v1\"\n\t\"github.com/cgrates/cgrates/engine\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdGetDataCost{\n\t\tname: \"datacost\",\n\t\trpcMethod: \"ApierV1.GetDataCost\",\n\t\tclientArgs: []string{\"Direction\", \"Category\", \"Tenant\", \"Account\", \"Subject\", \"StartTime\", \"Usage\"},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetDataCost struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrGetDataCost\n\tclientArgs []string\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetDataCost) Name() string {\n\treturn self.name\n}\n\n\n\nfunc (self *CmdGetDataCost) RpcParams() interface{} {\n\tif self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrGetDataCost{Direction: utils.OUT}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetDataCost) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetDataCost) RpcResult() interface{} {\n\treturn &engine.DataCost{}\n}\n\nfunc (self *CmdGetDataCost) ClientArgs() []string {\n\treturn self.clientArgs\n}\n\nfunc (self *CmdGetDataCost) RpcMethod() string ", "output": "{\n\treturn self.rpcMethod\n}"} {"input": "package app\n\nimport (\n\t. \"strconv\"\n\t\"time\"\n)\n\ntype User struct {\n\tId int64\n\tNom string\n\tPrenom string\n\tEmail string\n\tPassword string\n\tCreatedAt time.Time\n\tUpdatedAt time.Time\n}\n\n\nfunc (u User) Save() {\n\tdb.Save(&u)\n}\n\n\nfunc (u User) Update() {\n\tdb.First(&u, &u.Id).Update(&u)\n}\n\n\n\n\n\n\nfunc (u User) GetById() User {\n\tdb.Where(\"id = ?\", Itoa(int(u.Id))).Find(&u)\n\treturn u\n}\n\n\nfunc (u User) GetList() []User {\n\tvar users []User\n\tdb.Find(&users)\n\treturn users\n}\n\nfunc (u User) Delete() ", "output": "{\n\tdb.Delete(&u)\n}"} {"input": "package internal\n\nimport (\n\t. \"github.com/signal18/replication-manager/goofys/api/common\"\n\t. \"gopkg.in/check.v1\"\n\n\t\"github.com/jacobsa/fuse\"\n)\n\ntype AwsTest struct {\n\ts3 *S3Backend\n}\n\nvar _ = Suite(&AwsTest{})\n\nfunc (s *AwsTest) SetUpSuite(t *C) {\n\tvar err error\n\ts.s3, err = NewS3(\"\", &FlagStorage{}, &S3Config{\n\t\tRegion: \"us-east-1\",\n\t})\n\tt.Assert(err, IsNil)\n}\n\n\n\nfunc (s *AwsTest) TestBucket404(t *C) {\n\ts.s3.bucket = RandStringBytesMaskImprSrc(64)\n\n\terr, isAws := s.s3.detectBucketLocationByHEAD()\n\tt.Assert(err, Equals, fuse.ENOENT)\n\tt.Assert(isAws, Equals, true)\n}\n\nfunc (s *AwsTest) TestRegionDetection(t *C) ", "output": "{\n\ts.s3.bucket = \"goofys-eu-west-1.signal18/replication-manager.xyz\"\n\n\terr, isAws := s.s3.detectBucketLocationByHEAD()\n\tt.Assert(err, IsNil)\n\tt.Assert(*s.s3.awsConfig.Region, Equals, \"eu-west-1\")\n\tt.Assert(isAws, Equals, true)\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/clients/generated/client/clientset/versioned/typed/cloudscheduler/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeCloudschedulerV1beta1 struct {\n\t*testing.Fake\n}\n\n\n\n\n\nfunc (c *FakeCloudschedulerV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeCloudschedulerV1beta1) CloudSchedulerJobs(namespace string) v1beta1.CloudSchedulerJobInterface ", "output": "{\n\treturn &FakeCloudSchedulerJobs{c, namespace}\n}"} {"input": "package s2\n\n\nvar (\n\t_ Shape = (*PointVector)(nil)\n)\n\n\n\n\n\n\n\n\ntype PointVector []Point\n\nfunc (p *PointVector) NumEdges() int { return len(*p) }\nfunc (p *PointVector) Edge(i int) Edge { return Edge{(*p)[i], (*p)[i]} }\nfunc (p *PointVector) ReferencePoint() ReferencePoint { return OriginReferencePoint(false) }\nfunc (p *PointVector) NumChains() int { return len(*p) }\nfunc (p *PointVector) Chain(i int) Chain { return Chain{i, 1} }\nfunc (p *PointVector) ChainEdge(i, j int) Edge { return Edge{(*p)[i], (*p)[j]} }\n\nfunc (p *PointVector) Dimension() int { return 0 }\nfunc (p *PointVector) IsEmpty() bool { return defaultShapeIsEmpty(p) }\nfunc (p *PointVector) IsFull() bool { return defaultShapeIsFull(p) }\nfunc (p *PointVector) typeTag() typeTag { return typeTagPointVector }\nfunc (p *PointVector) privateInterface() {}\n\nfunc (p *PointVector) ChainPosition(e int) ChainPosition ", "output": "{ return ChainPosition{e, 0} }"} {"input": "package serialconsole\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/serialconsole/mgmt/2018-05-01/serialconsole\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype BaseClient = original.BaseClient\ntype ConsoleClient = original.ConsoleClient\ntype DeploymentValidateResult = original.DeploymentValidateResult\ntype GetDisabledResult = original.GetDisabledResult\ntype GetResult = original.GetResult\ntype ListClient = original.ListClient\ntype ListConsoleClient = original.ListConsoleClient\ntype Operations = original.Operations\ntype SetDisabledResult = original.SetDisabledResult\n\nfunc New(subscriptionID string) BaseClient {\n\treturn original.New(subscriptionID)\n}\nfunc NewConsoleClient(subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClient(subscriptionID)\n}\nfunc NewConsoleClientWithBaseURI(baseURI string, subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewListClient(subscriptionID string) ListClient {\n\treturn original.NewListClient(subscriptionID)\n}\nfunc NewListClientWithBaseURI(baseURI string, subscriptionID string) ListClient {\n\treturn original.NewListClientWithBaseURI(baseURI, subscriptionID)\n}\n\nfunc NewListConsoleClientWithBaseURI(baseURI string, subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\n\nfunc NewListConsoleClient(subscriptionID string) ListConsoleClient ", "output": "{\n\treturn original.NewListConsoleClient(subscriptionID)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSIoTAnalyticsPipeline_DeviceShadowEnrich struct {\n\n\tAttribute string `json:\"Attribute,omitempty\"`\n\n\tName string `json:\"Name,omitempty\"`\n\n\tNext string `json:\"Next,omitempty\"`\n\n\tRoleArn string `json:\"RoleArn,omitempty\"`\n\n\tThingName string `json:\"ThingName,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) AWSCloudFormationType() string {\n\treturn \"AWS::IoTAnalytics::Pipeline.DeviceShadowEnrich\"\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\n\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) Metadata() map[string]interface{} ", "output": "{\n\treturn r._metadata\n}"} {"input": "package gaerecords\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestSetIDAndGetID(t *testing.T) ", "output": "{\n\n\tpeople := CreateTestModel()\n\tperson := people.New()\n\n\tassertEqual(t, NoIDValue, person.ID())\n\tassertEqual(t, person, person.setID(123))\n\tassertEqual(t, int64(123), person.ID())\n\n}"} {"input": "package test\n\nimport (\n\t\"io/ioutil\"\n)\n\n\n\nfunc Fixture(path string) string ", "output": "{\n\tcontents, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn string(contents)\n}"} {"input": "package ai\n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\ntype Loader func(context.Context) (map[int64]int64, error)\n\ntype AI struct {\n\twhites map[int64]int64\n\tsync.RWMutex\n}\n\nfunc New() (a *AI) {\n\treturn &AI{\n\t\twhites: make(map[int64]int64),\n\t}\n}\n\nfunc (a *AI) White(mid int64) (num int64, ok bool) {\n\ta.RLock()\n\tdefer a.RUnlock()\n\tnum, ok = a.whites[mid]\n\treturn\n}\n\n\n\nfunc (a *AI) LoadWhite(c context.Context, loader Loader) (err error) ", "output": "{\n\tvar (\n\t\twhites map[int64]int64\n\t)\n\tif whites, err = loader(c); err != nil {\n\t\treturn\n\t}\n\ta.Lock()\n\ta.whites = whites\n\ta.Unlock()\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"github.com/nprog/SkyEye/common\"\n\t\"github.com/nprog/SkyEye/libnet\"\n\t\"github.com/nprog/SkyEye/log\"\n\t\"encoding/json\"\n\t\"sync\"\n\t\"time\"\n)\n\n\nfunc Test() {\n\trti := common.NewMachineInfo()\n\trti.GetInfo()\n\n\ttemp, err := json.Marshal(rti)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn\n\t}\n\n\tlog.Info(string(temp))\n}\n\n\ntype OnlineCfg struct {\n\tRealtimeInfo []string\n\tRealtimeInfoCycle int64 \n}\n\n\ntype Collection struct {\n\tonlineCfg *OnlineCfg\n\tsession *libnet.Session\n\tchangeCfg bool\n\tchangeCfgMutex sync.Mutex\n}\n\n\n\n\n\nfunc (c *Collection) sendMachineInfo() {\n\tlog.V(1).Info(\"sendMachineInfo\")\n}\n\n\nfunc (c *Collection) sendRealtimeInfoLoop() {\n\tlog.Info(\"sendRealtimeInfoLoop\")\n\ttimer := time.NewTicker(5 * time.Second)\n\tttl := time.After(10 * time.Second)\nbkloop:\n\tfor {\n\t\tselect {\n\t\tcase <-timer.C:\n\n\t\t\tif c.changeCfg {\n\t\t\t\tc.changeCfg = false\n\t\t\t\tbreak bkloop\n\t\t\t}\n\t\tcase <-ttl:\n\t\t\tbreak\n\t\t}\n\t}\n\tlog.Info(\"re config RealtimeInfoLoop.\")\n\tc.sendRealtimeInfoLoop()\n}\n\n\nfunc (c *Collection) sendFastRealtimeInfoLoop() {\n\n}\n\nfunc NewCollection() *Collection ", "output": "{\n\treturn &Collection{}\n}"} {"input": "package action\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"fmt\"\n)\n\ntype Http struct {\n\tconfig *ActionConfig\n}\n\n\n\nfunc (h *Http) genResult(resp *http.Response) (*Result, error) {\n\tdata := make(map[string]interface{})\n\tdata[\"status-code\"] = resp.StatusCode\n\tdata[\"headers\"] = resp.Header\n\n\th.config.Log.Infof(\"%s %s -> %d\", resp.Request.Method, resp.Request.URL.String(), resp.StatusCode)\n\n\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata[\"raw-body\"] = bodyBytes\n\tdata[\"body\"] = string(bodyBytes)\n\n\treturn &Result{\n\t\tData: data,\n\t}, nil\n}\n\nfunc NewHttp(config *ActionConfig) *Http {\n\treturn &Http{\n\t\tconfig: config,\n\t}\n}\n\nfunc (h *Http) Run() (*Result, error) ", "output": "{\n\turl := h.config.Params.GetString(\"url\")\n\tif url == \"\" {\n\t\treturn nil, fmt.Errorf(\"url parameter required\")\n\t}\n\n\tmethod := h.config.Params.GetString(\"method\")\n\tif method == \"\" {\n\t\tmethod = \"GET\"\n\t} else {\n\t\tmethod = strings.ToUpper(method)\n\t}\n\n\tclient := &http.Client{}\n\n\th.config.Log.Debugf(\"%s %s\", method, url)\n\n\treq, err := http.NewRequest(method, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult, err := h.genResult(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}"} {"input": "package v1\n\n\n\ntype ConfigMapProjectionApplyConfiguration struct {\n\tLocalObjectReferenceApplyConfiguration `json:\",inline\"`\n\tItems []KeyToPathApplyConfiguration `json:\"items,omitempty\"`\n\tOptional *bool `json:\"optional,omitempty\"`\n}\n\n\n\nfunc ConfigMapProjection() *ConfigMapProjectionApplyConfiguration {\n\treturn &ConfigMapProjectionApplyConfiguration{}\n}\n\n\n\n\nfunc (b *ConfigMapProjectionApplyConfiguration) WithName(value string) *ConfigMapProjectionApplyConfiguration {\n\tb.Name = &value\n\treturn b\n}\n\n\n\n\n\n\n\n\n\nfunc (b *ConfigMapProjectionApplyConfiguration) WithOptional(value bool) *ConfigMapProjectionApplyConfiguration {\n\tb.Optional = &value\n\treturn b\n}\n\nfunc (b *ConfigMapProjectionApplyConfiguration) WithItems(values ...*KeyToPathApplyConfiguration) *ConfigMapProjectionApplyConfiguration ", "output": "{\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithItems\")\n\t\t}\n\t\tb.Items = append(b.Items, *values[i])\n\t}\n\treturn b\n}"} {"input": "package credentials\n\nimport (\n\t\"strings\"\n\n\t\"github.com/docker/docker/cliconfig/configfile\"\n\t\"github.com/docker/engine-api/types\"\n)\n\n\n\ntype fileStore struct {\n\tfile *configfile.ConfigFile\n}\n\n\nfunc NewFileStore(file *configfile.ConfigFile) Store {\n\treturn &fileStore{\n\t\tfile: file,\n\t}\n}\n\n\nfunc (c *fileStore) Erase(serverAddress string) error {\n\tdelete(c.file.AuthConfigs, serverAddress)\n\treturn c.file.Save()\n}\n\n\nfunc (c *fileStore) Get(serverAddress string) (types.AuthConfig, error) {\n\tauthConfig, ok := c.file.AuthConfigs[serverAddress]\n\tif !ok {\n\t\tfor registry, ac := range c.file.AuthConfigs {\n\t\t\tif serverAddress == convertToHostname(registry) {\n\t\t\t\treturn ac, nil\n\t\t\t}\n\t\t}\n\n\t\tauthConfig = types.AuthConfig{}\n\t}\n\treturn authConfig, nil\n}\n\nfunc (c *fileStore) GetAll() (map[string]types.AuthConfig, error) {\n\treturn c.file.AuthConfigs, nil\n}\n\n\nfunc (c *fileStore) Store(authConfig types.AuthConfig) error {\n\tc.file.AuthConfigs[authConfig.ServerAddress] = authConfig\n\treturn c.file.Save()\n}\n\n\n\nfunc convertToHostname(url string) string ", "output": "{\n\tstripped := url\n\tif strings.HasPrefix(url, \"http://\") {\n\t\tstripped = strings.Replace(url, \"http://\", \"\", 1)\n\t} else if strings.HasPrefix(url, \"https://\") {\n\t\tstripped = strings.Replace(url, \"https://\", \"\", 1)\n\t}\n\n\tnameParts := strings.SplitN(stripped, \"/\", 2)\n\n\treturn nameParts[0]\n}"} {"input": "package spnego\n\nimport (\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/apcera/gssapi\"\n)\n\n\n\n\n\n\n\nfunc CheckSPNEGONegotiate(lib *gssapi.Lib, h http.Header, name string) (present bool, token *gssapi.Buffer) {\n\tvar err error\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlib.Debug(fmt.Sprintf(\"CheckSPNEGONegotiate: %v\", err))\n\t\t}\n\t}()\n\n\tv := h.Get(name)\n\tif len(v) == 0 || !strings.HasPrefix(v, \"Negotiate\") {\n\t\treturn false, nil\n\t}\n\n\tpresent = true\n\ttbytes, err := base64.StdEncoding.DecodeString(strings.TrimSpace(v[len(\"Negotiate\"):]))\n\tif err != nil {\n\t\treturn false, nil\n\t}\n\n\tif len(tbytes) > 0 {\n\t\ttoken, err = lib.MakeBufferBytes(tbytes)\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\treturn present, token\n}\n\nfunc AddSPNEGONegotiate(h http.Header, name string, token *gssapi.Buffer) ", "output": "{\n\tif name == \"\" {\n\t\treturn\n\t}\n\n\tv := \"Negotiate\"\n\tif token.Length() != 0 {\n\t\tdata := token.Bytes()\n\t\tv = v + \" \" + base64.StdEncoding.EncodeToString(data)\n\t}\n\th.Set(name, v)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSBatchJobDefinition_NodeRangeProperty struct {\n\n\tContainer *AWSBatchJobDefinition_ContainerProperties `json:\"Container,omitempty\"`\n\n\tTargetNodes string `json:\"TargetNodes,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) AWSCloudFormationType() string {\n\treturn \"AWS::Batch::JobDefinition.NodeRangeProperty\"\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\n\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetMetadata(metadata map[string]interface{}) ", "output": "{\n\tr._metadata = metadata\n}"} {"input": "package versioned\n\nimport (\n\t\"fmt\"\n\n\tsecurityv1 \"github.com/openshift/client-go/security/clientset/versioned/typed/security/v1\"\n\tdiscovery \"k8s.io/client-go/discovery\"\n\trest \"k8s.io/client-go/rest\"\n\tflowcontrol \"k8s.io/client-go/util/flowcontrol\"\n)\n\ntype Interface interface {\n\tDiscovery() discovery.DiscoveryInterface\n\tSecurityV1() securityv1.SecurityV1Interface\n}\n\n\n\ntype Clientset struct {\n\t*discovery.DiscoveryClient\n\tsecurityV1 *securityv1.SecurityV1Client\n}\n\n\nfunc (c *Clientset) SecurityV1() securityv1.SecurityV1Interface {\n\treturn c.securityV1\n}\n\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.DiscoveryClient\n}\n\n\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *Clientset {\n\tvar cs Clientset\n\tcs.securityV1 = securityv1.NewForConfigOrDie(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)\n\treturn &cs\n}\n\n\nfunc New(c rest.Interface) *Clientset {\n\tvar cs Clientset\n\tcs.securityV1 = securityv1.New(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClient(c)\n\treturn &cs\n}\n\nfunc NewForConfig(c *rest.Config) (*Clientset, error) ", "output": "{\n\tconfigShallowCopy := *c\n\tif configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {\n\t\tif configShallowCopy.Burst <= 0 {\n\t\t\treturn nil, fmt.Errorf(\"Burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0\")\n\t\t}\n\t\tconfigShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)\n\t}\n\tvar cs Clientset\n\tvar err error\n\tcs.securityV1, err = securityv1.NewForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &cs, nil\n}"} {"input": "package validation\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/client-go/kubernetes/fake\"\n)\n\n\n\n\n\n\n\n\n\nfunc TestWaitForNodeToBeReady(t *testing.T) {\n\tconditions := []v1.NodeCondition{{Type: \"Ready\", Status: \"True\"}}\n\tnodeName := \"node-foo\"\n\tnodeAA := setupNodeAA(t, conditions, nodeName)\n\n\ttest, err := nodeAA.WaitForNodeToBeReady(nodeName)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif test != true {\n\t\tt.Fatalf(\"unexpected error WaitForNodeToBeReady Failed: %v\", test)\n\t}\n}\n\n\n\n\n\n\n\nfunc setupNodeAA(t *testing.T, conditions []v1.NodeCondition, nodeName string) *NodeAPIAdapter {\n\tnode := &v1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{Name: nodeName},\n\t\tSpec: v1.NodeSpec{Unschedulable: false},\n\t\tStatus: v1.NodeStatus{Conditions: conditions},\n\t}\n\n\tc := fake.NewSimpleClientset(node)\n\tnodeAA, err := NewNodeAPIAdapter(c, time.Duration(10)*time.Millisecond)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error building NodeAPIAdapter: %v\", err)\n\t}\n\treturn nodeAA\n}\n\nfunc TestWaitForNodeToBeNotReady(t *testing.T) ", "output": "{\n\tconditions := []v1.NodeCondition{{Type: \"Ready\", Status: \"False\"}}\n\tnodeName := \"node-foo\"\n\tnodeAA := setupNodeAA(t, conditions, nodeName)\n\n\ttest, err := nodeAA.WaitForNodeToBeNotReady(nodeName)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif test != true {\n\t\tt.Fatalf(\"unexpected error WaitForNodeToBeNotReady Failed: %v\", test)\n\t}\n}"} {"input": "package api\n\ntype FormatsResponse struct {\n\tFormats []string `json:\"formats\"`\n}\n\nfunc (a *API) getFormats(ctx *context) {\n\tctx.Success(FormatsResponse{Formats: a.c.formats.Keys()})\n}\n\ntype LeechTypesResponse struct {\n\tLeechTypes []string `json:\"leech_types\"`\n}\n\n\n\ntype MediaResponse struct {\n\tMedia []string `json:\"media\"`\n}\n\nfunc (a *API) getMedia(ctx *context) {\n\tctx.Success(MediaResponse{Media: a.c.media.Keys()})\n}\n\ntype ReleaseGroupTypesResponse struct {\n\tReleaseGroupTypes []string `json:\"release_group_types\"`\n}\n\nfunc (a *API) getReleaseGroupTypes(ctx *context) {\n\tctx.Success(ReleaseGroupTypesResponse{ReleaseGroupTypes: a.c.releaseGroupTypes.Keys()})\n}\n\ntype ReleasePropertiesResponse struct {\n\tReleaseProperties []string `json:\"release_properties\"`\n}\n\nfunc (a *API) getReleaseProperties(ctx *context) {\n\tctx.Success(ReleasePropertiesResponse{ReleaseProperties: a.c.releaseProperties.Keys()})\n}\n\ntype ReleaseRolesResponse struct {\n\tReleaseRoles []string `json:\"release_roles\"`\n}\n\nfunc (a *API) getReleaseRoles(ctx *context) {\n\tctx.Success(ReleaseRolesResponse{ReleaseRoles: a.c.releaseRoles.Keys()})\n}\n\ntype PrivilegesResponse struct {\n\tPrivileges []string `json:\"privileges\"`\n}\n\nfunc (a *API) getPrivileges(ctx *context) {\n\tctx.Success(PrivilegesResponse{Privileges: a.c.privileges.Keys()})\n}\n\nfunc (a *API) getLeechTypes(ctx *context) ", "output": "{\n\tctx.Success(LeechTypesResponse{LeechTypes: a.c.leechTypes.Keys()})\n}"} {"input": "package platform\n\nvar IsPartnerBuild = true\n\n\n\nfunc GuessMimeTypeByBuffer(buf []byte) (mimeType string, err error) {\n\treturn \"mime type disabled\", nil\n}\n\nfunc GuessMimeType(absPath string) (mimeType string, err error) ", "output": "{\n\treturn \"mime type disabled\", nil\n}"} {"input": "package core\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\ntype UpdateComputeImageCapabilitySchemaDetails struct {\n\n\tDisplayName *string `mandatory:\"false\" json:\"displayName\"`\n\n\tFreeformTags map[string]string `mandatory:\"false\" json:\"freeformTags\"`\n\n\tSchemaData map[string]ImageCapabilitySchemaDescriptor `mandatory:\"false\" json:\"schemaData\"`\n\n\tDefinedTags map[string]map[string]interface{} `mandatory:\"false\" json:\"definedTags\"`\n}\n\n\n\n\nfunc (m *UpdateComputeImageCapabilitySchemaDetails) UnmarshalJSON(data []byte) (e error) {\n\tmodel := struct {\n\t\tDisplayName *string `json:\"displayName\"`\n\t\tFreeformTags map[string]string `json:\"freeformTags\"`\n\t\tSchemaData map[string]imagecapabilityschemadescriptor `json:\"schemaData\"`\n\t\tDefinedTags map[string]map[string]interface{} `json:\"definedTags\"`\n\t}{}\n\n\te = json.Unmarshal(data, &model)\n\tif e != nil {\n\t\treturn\n\t}\n\tvar nn interface{}\n\tm.DisplayName = model.DisplayName\n\n\tm.FreeformTags = model.FreeformTags\n\n\tm.SchemaData = make(map[string]ImageCapabilitySchemaDescriptor)\n\tfor k, v := range model.SchemaData {\n\t\tnn, e = v.UnmarshalPolymorphicJSON(v.JsonData)\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\t\tif nn != nil {\n\t\t\tm.SchemaData[k] = nn.(ImageCapabilitySchemaDescriptor)\n\t\t} else {\n\t\t\tm.SchemaData[k] = nil\n\t\t}\n\t}\n\n\tm.DefinedTags = model.DefinedTags\n\n\treturn\n}\n\nfunc (m UpdateComputeImageCapabilitySchemaDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package clipboard\n\nimport (\n\t\"time\"\n)\n\ntype Duration struct {\n\ttime.Duration\n}\n\n\n\nfunc (d Duration) MarshalText() ([]byte, error) {\n\treturn []byte(d.String()), nil\n}\n\nfunc (d *Duration) UnmarshalText(text []byte) error ", "output": "{\n\tvar err error\n\td.Duration, err = time.ParseDuration(string(text))\n\treturn err\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype talker interface {\n\ttalk() string\n}\n\nfunc shout(t talker) {\n\tlouder := strings.ToUpper(t.talk())\n\tfmt.Println(louder)\n}\n\ntype laser int\n\n\n\ntype rover string\n\nfunc (r rover) talk() string {\n\treturn string(r)\n}\n\nfunc main() {\n\tr := rover(\"whir whir\")\n\tshout(r)\n}\n\nfunc (l laser) talk() string ", "output": "{\n\treturn strings.Repeat(\"toot \", int(l))\n}"} {"input": "package caller\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"testing\"\n)\n\nfunc TestCallResolver(t *testing.T) {\n\tcr := NewCallResolver(0, regexp.MustCompile(`resolver_test\\.go.*$`))\n\tfor i := 0; i < 2; i++ {\n\t\tif l := len(cr.cache); l != i {\n\t\t\tt.Fatalf(\"cache has %d entries, expected %d\", l, i)\n\t\t}\n\t\tfile, _, fun := func() (string, int, string) {\n\t\t\treturn cr.Lookup(1)\n\t\t}()\n\t\tif file != \"resolver_test.go\" {\n\t\t\tt.Fatalf(\"wrong file '%s'\", file)\n\t\t}\n\t\tif fun != \"TestCallResolver\" {\n\t\t\tt.Fatalf(\"unexpected caller reported: %s\", fun)\n\t\t}\n\t}\n}\n\n\n\nfunc BenchmarkFormatedCaller(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tfile, line, _ := Lookup(1)\n\t\ts := fmt.Sprintf(\"%s:%d\", file, line)\n\t\tif testing.Verbose() {\n\t\t\tb.Log(s)\n\t\t}\n\t}\n}\n\nfunc BenchmarkSimpleCaller(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tfile, line, _ := Lookup(1)\n\t\tif testing.Verbose() {\n\t\t\ts := fmt.Sprintf(\"%s:%d\", file, line)\n\t\t\tb.Log(s)\n\t\t}\n\t}\n}\n\nfunc TestDefaultCallResolver(t *testing.T) ", "output": "{\n\tdefer func() { defaultCallResolver.cache = map[uintptr]*cachedLookup{} }()\n\n\tfor i := 0; i < 2; i++ {\n\t\tif l := len(defaultCallResolver.cache); l != i {\n\t\t\tt.Fatalf(\"cache has %d entries, expected %d\", l, i)\n\t\t}\n\t\tfile, _, fun := Lookup(0)\n\t\tif fun != \"TestDefaultCallResolver\" {\n\t\t\tt.Fatalf(\"unexpected caller reported: %s\", fun)\n\t\t}\n\n\t\tif file != filepath.Join(\"util\", \"caller\", \"resolver_test.go\") {\n\t\t\tt.Fatalf(\"wrong file '%s'\", file)\n\t\t}\n\t}\n}"} {"input": "package resistor\n\n\n\n\n\n\n\nfunc Rpara(resists ...float64) (Rtotal float64) {\n\tfor _, r := range resists {\n\t\tRtotal = Rtotal + recip(r)\n\t}\n\treturn\n}\n\nfunc Rser(resists ...float64) (Rtotal float64) ", "output": "{\n\tfor _, r := range resists {\n\t\tRtotal = Rtotal + r\n\t}\n\treturn\n}"} {"input": "package routers\n\nimport (\n\t\"code.google.com/p/go.crypto/bcrypt\"\n\t\"github.com/codegangsta/martini-contrib/render\"\n\t\"github.com/martini-contrib/sessions\"\n\t\"labix.org/v2/mgo\"\n\t\"labix.org/v2/mgo/bson\"\n\t\"net/http\"\n)\n\n\n\nfunc AdminUpdatePassword(req *http.Request, r render.Render, db *mgo.Database) {\n\tpass := req.FormValue(\"password\")\n\tverify := req.FormValue(\"verify\")\n\n\tif pass == verify {\n\n\t\thashedPass, _ := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost)\n\t\tinfo, err := db.C(\"id\").Upsert(bson.M{\"email\": \"admin@vim-tips.com\"}, bson.M{\"$set\": bson.M{\"password\": hashedPass, \"email\": \"admin@vim-tips.com\"}})\n\n\t\tif err == nil {\n\t\t\tif info.Updated >= 0 {\n\t\t\t\tr.HTML(200, \"admin/password\", map[string]interface{}{\n\t\t\t\t\t\"IsPost\": true,\n\t\t\t\t\t\"IsPassword\": true,\n\t\t\t\t\t\"IsSuccess\": true}, render.HTMLOptions{Layout: \"admin/layout\"})\n\t\t\t}\n\t\t}\n\t} else {\n\t\tr.HTML(200, \"admin/password\", map[string]interface{}{\n\t\t\t\"IsPost\": true,\n\t\t\t\"IsPassword\": true,\n\t\t\t\"IsSuccess\": false}, render.HTMLOptions{Layout: \"admin/layout\"})\n\t}\n}\n\nfunc AdminPassword(r render.Render, s sessions.Session) ", "output": "{\n\tr.HTML(200, \"admin/password\", map[string]interface{}{\n\t\t\"IsPassword\": true}, render.HTMLOptions{Layout: \"admin/layout\"})\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"go.pedge.io/dockerplugin\"\n\t\"go.pedge.io/dockervolume\"\n)\n\nfunc main() {\n\tif err := do(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n\tos.Exit(0)\n}\n\n\n\nfunc do() error ", "output": "{\n\treturn dockervolume.NewTCPServer(\n\t\tnewVolumeDriver(\"/tmp/dockervolume-example-mount\"),\n\t\t\"dockervolume-example\",\n\t\t\":6789\",\n\t\tdockerplugin.ServerOptions{},\n\t).Serve()\n}"} {"input": "package sysstats\n\nimport (\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\n\n\n\ntype LoadAvg map[string]float64\n\n\n\n\nfunc getLoadAvg() (loadAvg LoadAvg, err error) ", "output": "{\n\tout, err := exec.Command(`sysctl`, `-n`, `vm.loadavg`).Output()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tloadAvg = LoadAvg{}\n\tfields := strings.Fields(string(out))\n\tfor i := 1; i < 4; i++ {\n\t\tload, err := strconv.ParseFloat(fields[i], 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch i {\n\t\tcase 1:\n\t\t\tloadAvg[`avg1`] = load\n\t\tcase 2:\n\t\t\tloadAvg[`avg5`] = load\n\t\tcase 3:\n\t\t\tloadAvg[`avg15`] = load\n\t\t}\n\t}\n\n\treturn loadAvg, nil\n}"} {"input": "package kusto\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) BaseClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient ", "output": "{\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package helpers\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"runtime\"\n)\n\n\n\nfunc BytesToUint16(field [2]byte) uint16 {\n\treturn uint16(field[0])<<8 | uint16(field[1])\n}\n\n\n\nfunc Uint16ToBytes(value uint16) [2]byte {\n\tbyte0 := byte(value >> 8)\n\tbyte1 := byte(0x00ff & value) \n\treturn [2]byte{byte0, byte1}\n}\n\n\n\n\n\n\n\n\n\nfunc GetBytes(b *bytes.Buffer, n int) []byte {\n\tslice := make([]byte, n)\n\tnread, err := b.Read(slice)\n\tif err != nil || nread != n {\n\t\tpanic(errors.New(\"Unexpected end of data.\"))\n\t}\n\treturn slice\n}\n\n\n\n\n\n\n\n\n\nfunc HandleErrorPanic(err *error, functionName string) {\n\tif r := recover(); r != nil {\n\t\tif _, ok := r.(runtime.Error); ok {\n\t\t\tpanic(r)\n\t\t}\n\t\tperr := r.(error)\n\t\t*err = errors.New(functionName + \": \" + perr.Error())\n\t}\n}\n\nfunc GetByte(b *bytes.Buffer) byte ", "output": "{\n\tbyte, err := b.ReadByte()\n\tif err != nil {\n\t\tpanic(errors.New(\"Unexpected end of data\"))\n\t}\n\treturn byte\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Player struct {\n\tID string\n\tName string\n\tHealth int\n\tHunger int\n\tCriticalHunger bool\n\tNextAction int\n\tDead bool\n}\n\n\nfunc NewPlayer(ID, name string) *Player {\n\treturn &Player{ID, name, 100, 0, false, 0, false}\n}\n\nfunc (p *Player) String() string {\n\treturn fmt.Sprintf(\"[%-12s](HP: %3d)\", p.Name, p.Health, p.Hunger)\n}\n\n\n\n\n\nfunc (p *Player) AddHunger(amount int) int {\n\tp.Hunger += amount\n\tif p.Hunger >= 100 {\n\t\tp.Hunger = 100\n\t\tif p.CriticalHunger {\n\t\t\treturn 2\n\t\t}\n\t\tp.CriticalHunger = true\n\t\treturn 1\n\t}\n\tif p.Hunger <= 0 {\n\t\tp.Hunger = 0\n\t}\n\treturn 0\n}\n\nfunc (p *Player) AddHealth(amount int) bool ", "output": "{\n\tp.Health += amount\n\tif p.Health > 100 {\n\t\tp.Health = 100\n\t}\n\tif p.Health <= 0 {\n\t\tp.Health = 0\n\t\tp.Dead = true\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package reports\n\nimport (\n\t\"time\"\n\n\t\"github.com/rafaeljusto/druns/core/db\"\n)\n\ntype Service struct {\n\tsqler db.SQLer\n}\n\n\n\nfunc (s Service) IncomingPerGroup(month time.Time, classValue float64) ([]Incoming, error) {\n\tdao := newDAO(s.sqler)\n\treturn dao.incomingPerGroup(month, classValue)\n}\n\nfunc NewService(sqler db.SQLer) Service ", "output": "{\n\treturn Service{sqler}\n}"} {"input": "package udt\n\n\n\nimport (\n\t\"io\"\n)\n\ntype ack2Packet struct {\n\th header\n\tackSeqNo uint32 \n}\n\n\n\nfunc (p *ack2Packet) sendTime() (ts uint32) {\n\treturn p.h.ts\n}\n\nfunc (p *ack2Packet) writeTo(w io.Writer) (err error) {\n\tif err := p.h.writeTo(w, ack2, p.ackSeqNo); err != nil {\n\t\treturn err\n\t}\n\treturn\n}\n\nfunc (p *ack2Packet) readFrom(r io.Reader) (err error) {\n\tp.ackSeqNo, err = p.h.readFrom(r)\n\treturn\n}\n\nfunc (p *ack2Packet) socketId() (sockId uint32) ", "output": "{\n\treturn p.h.dstSockId\n}"} {"input": "package types\n\nimport (\n\t\"net\"\n)\n\n\ntype IPv4 [4]byte\n\n\n\nfunc (v4 IPv4) String() string {\n\treturn v4.IP().String()\n}\n\n\nfunc (v4 *IPv4) DeepCopyInto(out *IPv4) {\n\tcopy(out[:], v4[:])\n\treturn\n}\n\nfunc (v4 IPv4) IP() net.IP ", "output": "{\n\treturn v4[:]\n}"} {"input": "package event\n\nimport (\n\t\"fmt\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\n\ntype Increment struct {\n\tName string\n\tValue int64\n}\n\nfunc (e *Increment) StatClass() string {\n\treturn \"counter\"\n}\n\n\nfunc (e *Increment) Update(e2 Event) error {\n\tif e.Type() != e2.Type() {\n\t\treturn fmt.Errorf(\"statsd event type conflict: %s vs %s \", e.String(), e2.String())\n\t}\n\tatomic.AddInt64(&e.Value, e2.Payload().(int64))\n\treturn nil\n}\n\n\nfunc (e *Increment) Reset() {\n\te.Value = 0\n}\n\n\nfunc (e Increment) Payload() interface{} {\n\treturn e.Value\n}\n\n\nfunc (e Increment) Stats(tick time.Duration) []string {\n\treturn []string{fmt.Sprintf(\"%s:%d|c\", e.Name, e.Value)}\n}\n\n\n\n\n\nfunc (e *Increment) SetKey(key string) {\n\te.Name = key\n}\n\n\nfunc (e Increment) Type() int {\n\treturn EventIncr\n}\n\n\nfunc (e Increment) TypeString() string {\n\treturn \"Increment\"\n}\n\n\nfunc (e Increment) String() string {\n\treturn fmt.Sprintf(\"{Type: %s, Key: %s, Value: %d}\", e.TypeString(), e.Name, e.Value)\n}\n\nfunc (e Increment) Key() string ", "output": "{\n\treturn e.Name\n}"} {"input": "package atc\n\nimport (\n\t\"errors\"\n\n\tmultierror \"github.com/hashicorp/go-multierror\"\n)\n\ntype AuthFlags struct {\n\tNoAuth bool `long:\"no-really-i-dont-want-any-auth\" description:\"Ignore warnings about not configuring auth\"`\n\n\tBasicAuth BasicAuthFlag `group:\"Basic Authentication\" namespace:\"basic-auth\"`\n}\n\ntype BasicAuthFlag struct {\n\tUsername string `long:\"username\" description:\"Username to use for basic auth.\"`\n\tPassword string `long:\"password\" description:\"Password to use for basic auth.\"`\n}\n\nfunc (auth *BasicAuthFlag) IsConfigured() bool {\n\treturn auth.Username != \"\" || auth.Password != \"\"\n}\n\n\n\nfunc (auth *BasicAuthFlag) Validate() error ", "output": "{\n\tvar errs *multierror.Error\n\tif auth.Username == \"\" {\n\t\terrs = multierror.Append(\n\t\t\terrs,\n\t\t\terrors.New(\"must specify --basic-auth-username to use basic auth.\"),\n\t\t)\n\t}\n\tif auth.Password == \"\" {\n\t\terrs = multierror.Append(\n\t\t\terrs,\n\t\t\terrors.New(\"must specify --basic-auth-password to use basic auth.\"),\n\t\t)\n\t}\n\treturn errs.ErrorOrNil()\n}"} {"input": "package cmd\n\n\ntype readDirOpts struct {\n\tcount int\n\tfollowDirSymlink bool\n}\n\n\nfunc readDir(dirPath string) (entries []string, err error) {\n\treturn readDirWithOpts(dirPath, readDirOpts{count: -1})\n}\n\n\n\n\nfunc readDirN(dirPath string, count int) (entries []string, err error) ", "output": "{\n\treturn readDirWithOpts(dirPath, readDirOpts{count: count})\n}"} {"input": "package v1\n\nimport (\n\tcommon \"github.com/kubeflow/common/pkg/apis/common/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\n\n\nfunc Int32(v int32) *int32 {\n\treturn &v\n}\n\nfunc addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}\n\n\nfunc setDefaultsTypeLauncher(spec *common.ReplicaSpec) {\n\tif spec != nil && spec.RestartPolicy == \"\" {\n\t\tspec.RestartPolicy = DefaultRestartPolicy\n\t}\n}\n\n\n\n\nfunc SetDefaults_MPIJob(mpiJob *MPIJob) {\n\tif mpiJob.Spec.CleanPodPolicy == nil {\n\t\tnone := common.CleanPodPolicyNone\n\t\tmpiJob.Spec.CleanPodPolicy = &none\n\t}\n\n\tsetDefaultsTypeLauncher(mpiJob.Spec.MPIReplicaSpecs[MPIReplicaTypeLauncher])\n\n\tsetDefaultsTypeWorker(mpiJob.Spec.MPIReplicaSpecs[MPIReplicaTypeWorker])\n}\n\nfunc setDefaultsTypeWorker(spec *common.ReplicaSpec) ", "output": "{\n\tif spec != nil && spec.RestartPolicy == \"\" {\n\t\tspec.RestartPolicy = DefaultRestartPolicy\n\t}\n}"} {"input": "package problems\n\nimport \"fmt\"\n\nfunc partitionDfs(data []byte, i int, buf *[]string, out *[][]string) {\n\tif i == len(data) {\n\t\tm := make([]string, len(*buf))\n\t\tcopy(m, *buf)\n\t\t*out = append(*out, m)\n\t\treturn\n\t}\n\n\tvar isPalindrome func (data []byte, s int, e int) bool\n\tisPalindrome = func (data []byte, s int, e int) bool {\n\t\ti, j := s, e\n\t\tfor i < j {\n\t\t\tif data[i] != data[j] {\n\t\t\t\treturn false\n\t\t\t} else {\n\t\t\t\ti++\n\t\t\t\tj--\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n\n\tfor k := i; k < len(data); k++ {\n\t\tif isPalindrome(data, i, k) {\n\t\t\t*buf = append(*buf, string(data[i:k + 1]))\n\t\t\tpartitionDfs(data, k + 1, buf, out)\n\t\t\t*buf = (*buf)[:len(*buf) - 1]\n\t\t}\n\t}\n}\n\nfunc partition(s string) [][]string {\n\tvar buf []string\n\tvar out [][]string\n\n\tpartitionDfs([]byte(s), 0, &buf, &out)\n\n\treturn out\n}\n\n\n\nfunc Partition() ", "output": "{\n\tfmt.Printf(\"<131> \")\n\tfmt.Println(partition(\"aabc\"))\n}"} {"input": "package queue\n\nimport \"context\"\n\n\ntype Client struct {\n\tContent []byte\n\terr error\n}\n\n\nfunc (c *Client) Push(ctx context.Context, content []byte) error {\n\tif c.err != nil {\n\t\treturn c.err\n\t}\n\tc.Content = content\n\treturn nil\n}\n\n\nfunc NewClient(options ...func(*Client)) *Client {\n\tc := &Client{}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\treturn c\n}\n\n\n\n\nfunc ClientError(err error) func(*Client) ", "output": "{\n\treturn func(c *Client) {\n\t\tc.err = err\n\t}\n}"} {"input": "package goku\n\nimport (\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype TestReader struct{}\n\nfunc (self TestReader) Read() ([]Message, error) {\n\ttime.Sleep(10 * time.Millisecond)\n\treturn []Message{\"Hello\"}, nil\n}\n\ntype TestWriter struct {\n\tmsgs []Message\n}\n\n\n\nfunc TestNewQueueSetupReader(t *testing.T) {\n\tt.Parallel()\n\n\tq := NewQueue(&TestReader{}, nil)\n\n\tselect {\n\tcase <-q.Sender():\n\t\tbreak\n\tcase <-time.After(100 * time.Millisecond):\n\t\tt.Fatal(\"Timeout expired\")\n\t}\n}\n\nfunc TestNewQueueSetsupWriter(t *testing.T) {\n\tt.Parallel()\n\n\twriter := &TestWriter{}\n\tq := NewQueue(nil, writer)\n\n\tq.Receiver() <- \"Hello\"\n\tq.Receiver() <- \"World\"\n\n\truntime.Gosched()\n\n\tif count := len(writer.msgs); count != 2 {\n\t\tt.Errorf(\"messages written == %d, want 2\", count)\n\t}\n}\n\nfunc (self *TestWriter) Write(msgs []Message) error ", "output": "{\n\tfor _, msg := range msgs {\n\t\tself.msgs = append(self.msgs, msg)\n\t}\n\treturn nil\n}"} {"input": "package externalversions\n\nimport (\n\t\"fmt\"\n\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tcache \"k8s.io/client-go/tools/cache\"\n\tv1beta1 \"k8s.io/kube-aggregator/pkg/apis/apiregistration/v1beta1\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\n\n\n\nfunc (f *genericInformer) Lister() cache.GenericLister {\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {\n\tswitch resource {\n\tcase v1beta1.SchemeGroupVersion.WithResource(\"apiservices\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Apiregistration().V1beta1().APIServices().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer ", "output": "{\n\treturn f.informer\n}"} {"input": "package parse\n\n\nimport (\n\t\"strings\"\n)\n\nfunc indent(s string, character string, size int) string {\n\tindent := strings.Repeat(character, size)\n\tlines := strings.Split(s, newLine)\n\tfor k, v := range lines {\n\t\tif len(v) > 0 {\n\t\t\tlines[k] = indent + v\n\t\t}\n\t}\n\treturn strings.Join(lines, newLine)\n}\n\n\n\nfunc EqualSlicesFoldPrefix(a, prefix []string) bool {\n\tl, lprefix := len(a), len(prefix)\n\tswitch {\n\tcase lprefix == 0:\n\t\treturn true\n\tcase l < lprefix:\n\t\treturn false\n\tcase l > lprefix:\n\t\treturn EqualSlicesFold(a[:lprefix], prefix)\n\tdefault:\n\t\treturn EqualSlicesFold(a, prefix)\n\t}\n}\n\n\n\nfunc EqualSlicesFoldSuffix(a, suffix []string) bool {\n\tl, lsuffix := len(a), len(suffix)\n\tswitch {\n\tcase lsuffix == 0:\n\t\treturn true\n\tcase l < lsuffix:\n\t\treturn false\n\tcase l > lsuffix:\n\t\treturn EqualSlicesFold(a[l-lsuffix:], suffix)\n\tdefault:\n\t\treturn EqualSlicesFold(a, suffix)\n\t}\n}\n\n\n\nfunc EqualSlicesFold(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor k := range a {\n\t\tif !strings.EqualFold(a[k], b[k]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc EqualSlicesFoldSome(a []string, b ...[]string) bool ", "output": "{\n\tif len(a) == 0 && len(b) == 0 {\n\t\treturn true\n\t}\n\n\tfor k := range b {\n\t\tif EqualSlicesFold(a, b[k]) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\n\n\nfunc main() {\n\tin, _ := os.Open(\"11455.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"11455.out\")\n\tdefer out.Close()\n\n\tvar kase int\n\tsides := make([]int, 4)\n\tfor fmt.Fscanf(in, \"%d\", &kase); kase > 0; kase-- {\n\t\tfmt.Fscanf(in, \"%d%d%d%d\", &sides[0], &sides[1], &sides[2], &sides[3])\n\t\tfmt.Fprintln(out, solve(sides))\n\t}\n}\n\nfunc solve(sides []int) string ", "output": "{\n\tsort.Ints(sides)\n\tif sides[0] == sides[1] && sides[2] == sides[3] {\n\t\tif sides[1] == sides[2] {\n\t\t\treturn \"square\"\n\t\t}\n\t\treturn \"rectangle\"\n\t}\n\tif sides[3] > sides[0]+sides[1]+sides[2] {\n\t\treturn \"banana\"\n\t}\n\treturn \"quadrangle\"\n}"} {"input": "package route\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar ()\n\n\ntype Route struct {\n\tPath string\n\tSystem int\n\tS0 NullRoute\n\tS1 StringRoute\n\tS2 ControllerRoute\n\tS3 FilesystemRoute\n\tS4 FunctionRoute\n}\n\n\nfunc NewRoute(path string, system int) Route {\n\treturn Route{path, system, NullRoute{}, StringRoute{}, ControllerRoute{}, FilesystemRoute{}, FunctionRoute{}}\n}\n\n\nfunc (r *Route) Read(w http.ResponseWriter, req *http.Request) {\n\tresult := \"\"\n\tswitch r.System {\n\tcase 0:\n\t\tresult = \"\"\n\tcase 1:\n\t\tresult = r.S1.String\n\tcase 2:\n\tcase 3:\n\t\tresult = r.S3.FileContent\n\tcase 4:\n\t\tresult = r.S4.Function()\n\t}\n\tio.Copy(w, strings.NewReader(result))\n}\n\n\n\n\nfunc ValidStringRoute(str string) bool ", "output": "{\n\trouteStringRegexp := `^\\/([a-zA-Z0-9](\\/)*)*\\s(null|str .*|fs .*)$`\n\tr, _ := regexp.Compile(routeStringRegexp)\n\tif r.MatchString(str) {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package project\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestTrimSpaceAndNonPrintable_space(t *testing.T) {\n\tt.Parallel()\n\n\textraChars := \" state \\r\\t\"\n\twant := \"state\"\n\tgot := TrimSpaceAndNonPrintable(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}\n\nfunc TestTrimSpace_unicode(t *testing.T) {\n\tt.Parallel()\n\n\textraChars := \"state\\uFEFF\"\n\twant := \"state\"\n\tgot := TrimSpace(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}\n\nfunc TestTrimSpace_space(t *testing.T) {\n\tt.Parallel()\n\n\textraChars := \" state \\r\\t\"\n\twant := \"state\"\n\tgot := TrimSpace(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}\n\nfunc TestTrimSpaceAndNonPrintable_unicode(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\textraChars := \"state\\uFEFF\"\n\twant := \"state\"\n\tgot := TrimSpaceAndNonPrintable(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/signal\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n)\n\ntype threadSafePrintliner struct {\n\tl sync.Mutex\n\tw io.Writer\n}\n\nfunc newThreadSafePrintliner(w io.Writer) *threadSafePrintliner {\n\treturn &threadSafePrintliner{w: w}\n}\n\nfunc (p *threadSafePrintliner) println(s string) {\n\tp.l.Lock()\n\tfmt.Fprintln(p.w, s)\n\tp.l.Unlock()\n}\n\nfunc readQuery(r io.Reader) string {\n\ts, _ := ioutil.ReadAll(r) \n\treturn strings.TrimSpace(strings.Replace(string(s), \"\\n\", \" \", -1))\n}\n\n\n\nfunc awaitSignal(cancel context.CancelFunc) {\n\tsignals := make(chan os.Signal)\n\tsignal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)\n\t<-signals\n\tcancel()\n}\n\nfunc trimEmpty(s []string) []string ", "output": "{\n\tvar r = make([]string, 0)\n\tfor _, str := range s {\n\t\tif str != \"\" {\n\t\t\tr = append(r, str)\n\t\t}\n\t}\n\treturn r\n}"} {"input": "package http\n\nimport (\n\t\"go-common/app/admin/main/tv/model\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\nfunc mangoList(c *bm.Context) {\n\tc.JSON(tvSrv.MangoList(c))\n}\n\nfunc mangoAdd(c *bm.Context) {\n\tparam := new(struct {\n\t\tIDs []int64 `form:\"rids,split\" validate:\"required,min=1,dive,gt=0\"`\n\t\tRType int `form:\"rtype\" validate:\"required,min=1,max=2\"` \n\t})\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(tvSrv.MangoAdd(c, param.RType, param.IDs))\n}\n\nfunc mangoEdit(c *bm.Context) {\n\tparam := new(model.ReqMangoEdit)\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(nil, tvSrv.MangoEdit(c, param))\n}\n\n\n\nfunc mangoPub(c *bm.Context) {\n\tparam := new(struct {\n\t\tIDs []int64 `form:\"ids,split\" validate:\"required,min=1,dive,gt=0\"`\n\t})\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(nil, tvSrv.MangoPub(c, param.IDs))\n}\n\nfunc mangoDel(c *bm.Context) ", "output": "{\n\tparam := new(struct {\n\t\tID int64 `form:\"id\" validate:\"required,min=1,gt=0\"`\n\t})\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(nil, tvSrv.MangoDel(c, param.ID))\n}"} {"input": "package containerregistry\n\nimport (\n\t\"context\"\n\n\t\"github.com/sacloud/libsacloud/v2/helper/service\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n)\n\n\n\nfunc (s *Service) DeleteWithContext(ctx context.Context, req *DeleteRequest) error {\n\tif err := req.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tclient := sacloud.NewContainerRegistryOp(s.caller)\n\tif err := client.Delete(ctx, req.ID); err != nil {\n\t\treturn service.HandleNotFoundError(err, !req.FailIfNotFound)\n\t}\n\treturn nil\n}\n\nfunc (s *Service) Delete(req *DeleteRequest) error ", "output": "{\n\treturn s.DeleteWithContext(context.Background(), req)\n}"} {"input": "package global\n\nimport (\n\t\"fmt\"\n)\n\n\n\nconst (\n\tversionMajor = 0\n\tversionMinor = 0\n\tversionPatch = 8\n)\n\nfunc Version() string ", "output": "{\n\treturn fmt.Sprintf(\"tgen v%d.%d.%d\", versionMajor, versionMinor, versionPatch)\n}"} {"input": "package gofixedfield\n\nimport (\n\t\"io/ioutil\"\n\t\"strings\"\n)\n\nconst (\n\tEOLUnix = \"\\n\"\n\tEOLMac = \"\\r\"\n\tEOLDOS = \"\\r\\n\"\n)\n\n\n\nvar DecimalComma bool\n\n\n\n\n\nfunc RecordsFromFile(filename string, eolstyle string) ([]string, error) ", "output": "{\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn strings.Split(string(data), eolstyle), nil\n}"} {"input": "package heckle\n\nimport (\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com/ianremmler/bort\"\n)\n\nvar (\n\tretorts = retortMap{}\n)\n\ntype retortMap map[string]string\n\n\n\nfunc setup() error {\n\tif err := bort.GetConfig(&struct{ Retorts retortMap }{retorts}); err != nil {\n\t\treturn err\n\t}\n\tfor watch, retort := range retorts {\n\t\tif _, err := bort.RegisterMatcher(bort.PrivMsg, watch, responder(retort)); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc init() {\n\tbort.RegisterSetup(setup)\n}\n\nfunc responder(retort string) bort.HandleFunc ", "output": "{\n\treturn func(in, out *bort.Message) error {\n\t\tout.Type = bort.PrivMsg\n\t\tout.Text = strings.Replace(retort, \"%m\", in.Match, -1)\n\t\treturn nil\n\t}\n}"} {"input": "package opt\n\nimport (\n\t\"encoding/json\"\n\t\"reflect\"\n)\n\n\n\ntype DisableTypoToleranceOnAttributesOption struct {\n\tvalue []string\n}\n\n\nfunc DisableTypoToleranceOnAttributes(v ...string) *DisableTypoToleranceOnAttributesOption {\n\treturn &DisableTypoToleranceOnAttributesOption{v}\n}\n\n\nfunc (o *DisableTypoToleranceOnAttributesOption) Get() []string {\n\tif o == nil {\n\t\treturn []string{}\n\t}\n\treturn o.value\n}\n\n\n\nfunc (o DisableTypoToleranceOnAttributesOption) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(o.value)\n}\n\n\n\n\n\n\n\n\nfunc (o *DisableTypoToleranceOnAttributesOption) Equal(o2 *DisableTypoToleranceOnAttributesOption) bool {\n\tif o == nil {\n\t\treturn o2 == nil || reflect.DeepEqual(o2.value, []string{})\n\t}\n\tif o2 == nil {\n\t\treturn o == nil || reflect.DeepEqual(o.value, []string{})\n\t}\n\treturn reflect.DeepEqual(o.value, o2.value)\n}\n\n\n\n\nfunc DisableTypoToleranceOnAttributesEqual(o1, o2 *DisableTypoToleranceOnAttributesOption) bool {\n\treturn o1.Equal(o2)\n}\n\nfunc (o *DisableTypoToleranceOnAttributesOption) UnmarshalJSON(data []byte) error ", "output": "{\n\tif string(data) == \"null\" {\n\t\to.value = []string{}\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(data, &o.value)\n}"} {"input": "package internal\n\nimport \"v2ray.com/core/common/errors\"\n\n\n\nfunc newError(values ...interface{}) *errors.Error ", "output": "{\n\treturn errors.New(values...).Path(\"Transport\", \"Internet\", \"Internal\")\n}"} {"input": "package contract\n\nimport (\n\t\"github.com/ethereum/go-ethereum/common\"\n\t\"github.com/ethereum/go-ethereum/crypto\"\n)\n\n\nfunc sha3(in ...[]byte) []byte {\n\tout := make([]byte, len(in)*32)\n\tfor i, input := range in {\n\t\tcopy(out[i*32:i*32+32], common.LeftPadBytes(input, 32))\n\t}\n\treturn crypto.Sha3(out)\n}\n\n\n\n\n\nfunc makeChannelName(from, to common.Address) []byte ", "output": "{\n\treturn sha3(from[:], to[:])\n}"} {"input": "package fritz\n\nimport (\n\t\"unicode/utf16\"\n\t\"unicode/utf8\"\n)\n\nfunc utf8To16LE(p []byte) []byte {\n\tbs := make([]byte, 0, 2*len(p))\n\tpos := 0\n\tfor pos < len(p) {\n\t\tbytes, size := consumeNextRune(p[pos:])\n\t\tpos += size\n\t\tbs = append(bs, bytes...)\n\t}\n\treturn bs\n}\n\n\n\nfunc consumeNextRune(p []byte) ([]byte, int) ", "output": "{\n\tr, size := utf8.DecodeRune(p)\n\tif r <= 0xffff {\n\t\treturn []byte{uint8(r), uint8(r >> 8)}, size\n\t}\n\tr1, r2 := utf16.EncodeRune(r)\n\treturn []byte{uint8(r1), uint8(r1 >> 8), uint8(r2), uint8(r2 >> 8)}, size\n}"} {"input": "package main\n\nimport . \"g2d\"\n\nvar arena = NewArena(Point{480, 360})\nvar a1 = NewAlien(arena, Point{40, 40})\nvar a2 = NewAlien(arena, Point{80, 80})\n\ntype Alien struct {\n arena *Arena\n x, y, w, h int\n xmin, xmax int\n dx, dy int\n}\n\nfunc NewAlien(arena *Arena, pos Point) *Alien {\n a := &Alien{arena, pos.X, pos.Y, 20, 20, pos.X, pos.X+150, 5, 5}\n arena.Add(a)\n return a\n}\n\nfunc (a *Alien) Move() {\n if a.xmin <= a.x+a.dx && a.x+a.dx <= a.xmax {\n a.x += a.dx\n } else {\n a.dx = -a.dx\n a.y += a.dy\n }\n}\n\nfunc (a *Alien) Position() Point {\n return Point{a.x, a.y}\n}\n\n\n\nfunc (a *Alien) Symbol() Point {\n return Point{0, 0}\n}\n\nfunc (a *Alien) Collide(other Actor) {\n}\n\nfunc tick() {\n ClearCanvas()\n arena.MoveAll()\n for _, actor := range arena.Actors() {\n FillRect(actor.Position(), actor.Size())\n }\n}\n\nfunc main() {\n InitCanvas(arena.Size())\n MainLoop(tick)\n}\n\nfunc (a *Alien) Size() Point ", "output": "{\n return Point{a.w, a.h}\n}"} {"input": "package internal\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\ntype ContextKey string\n\nconst userAgent = \"gcloud-golang/0.1\"\n\n\n\n\ntype Transport struct {\n\tBase http.RoundTripper\n}\n\n\n\nfunc (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq = cloneRequest(req)\n\tua := req.Header.Get(\"User-Agent\")\n\tif ua == \"\" {\n\t\tua = userAgent\n\t} else {\n\t\tua = fmt.Sprintf(\"%s;%s\", ua, userAgent)\n\t}\n\treq.Header.Set(\"User-Agent\", ua)\n\treturn t.Base.RoundTrip(req)\n}\n\n\n\n\n\n\nfunc ProjID(ctx context.Context) string {\n\treturn ctx.Value(ContextKey(\"base\")).(map[string]interface{})[\"project_id\"].(string)\n}\n\n\n\nfunc Namespace(ctx context.Context) string {\n\tv := ctx.Value(ContextKey(\"namespace\"))\n\tif v == nil {\n\t\treturn \"\"\n\t} else {\n\t\treturn v.(string)\n\t}\n}\n\nfunc HttpClient(ctx context.Context) *http.Client {\n\treturn ctx.Value(ContextKey(\"base\")).(map[string]interface{})[\"http_client\"].(*http.Client)\n}\n\nfunc cloneRequest(r *http.Request) *http.Request ", "output": "{\n\tr2 := new(http.Request)\n\t*r2 = *r\n\tr2.Header = make(http.Header)\n\tfor k, s := range r.Header {\n\t\tr2.Header[k] = s\n\t}\n\treturn r2\n}"} {"input": "package logging_test\n\nimport (\n\t\"cloud.google.com/go/logging/apiv2\"\n\t\"golang.org/x/net/context\"\n\tloggingpb \"google.golang.org/genproto/googleapis/logging/v2\"\n)\n\nfunc ExampleNewConfigClient() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\n\n\nfunc ExampleConfigClient_GetSink() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.GetSinkRequest{\n\t}\n\tresp, err := c.GetSink(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleConfigClient_CreateSink() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.CreateSinkRequest{\n\t}\n\tresp, err := c.CreateSink(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleConfigClient_UpdateSink() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.UpdateSinkRequest{\n\t}\n\tresp, err := c.UpdateSink(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleConfigClient_DeleteSink() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.DeleteSinkRequest{\n\t}\n\terr = c.DeleteSink(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleConfigClient_ListSinks() ", "output": "{\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.ListSinksRequest{\n\t}\n\tit := c.ListSinks(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t_ = resp\n\t}\n}"} {"input": "package middleware\n\nimport (\n\t\"time\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"gopkg.in/macaron.v1\"\n\n\t\"github.com/containerops/configure\"\n)\n\n\n\nfunc logger() macaron.Handler ", "output": "{\n\treturn func(ctx *macaron.Context) {\n\t\tif configure.GetString(\"runmode\") == \"dev\" {\n\t\t\tlog.Info(\"------------------------------------------------------------------------------\")\n\t\t\tlog.Info(time.Now().String())\n\t\t}\n\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"Method\": ctx.Req.Method,\n\t\t\t\"URL\": ctx.Req.RequestURI,\n\t\t}).Info(ctx.Req.Header)\n\n\t}\n}"} {"input": "package authorization\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tAPIVersion = \"2015-01-01\"\n\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype ManagementClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {\n\treturn ManagementClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) ManagementClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package http_handlers\n\nimport (\n\t\"fmt\"\n\t\"github.com/go-martini/martini\"\n\t\"net/http\"\n)\n\nfunc GetCaches() func(\n\tmartini.Context,\n\tmartini.Params,\n\thttp.ResponseWriter,\n\t*http.Request,\n) {\n\treturn HttpHandler(\n\t\t[]string{\n\t\t\tAUTH_REQUIRED,\n\t\t},\n\t\tfunc(h *Http) {\n\t\t\th.SetResponse(\n\t\t\t\th.session.Caches,\n\t\t\t)\n\t\t},\n\t)\n}\n\n\n\nfunc RegisterCache() func(\n\tmartini.Context,\n\tmartini.Params,\n\thttp.ResponseWriter,\n\t*http.Request,\n) {\n\treturn HttpHandler(\n\t\t[]string{\n\t\t\tAUTH_REQUIRED,\n\t\t},\n\t\tfunc(h *Http) {\n\t\t\th.SetResponseCreatedObject(\n\t\t\t\th.session.CreateCache(),\n\t\t\t)\n\t\t},\n\t)\n}\n\nfunc GetCache() func(\n\tmartini.Context,\n\tmartini.Params,\n\thttp.ResponseWriter,\n\t*http.Request,\n) ", "output": "{\n\treturn HttpHandler(\n\t\t[]string{\n\t\t\tAUTH_REQUIRED,\n\t\t\tCACHE_REQUIRED,\n\t\t},\n\t\tfunc(h *Http) {\n\t\t\tif c := h.session.GetCache(\n\t\t\t\th.vars[\"cache_id\"],\n\t\t\t); c != nil {\n\t\t\t\th.SetResponse(\n\t\t\t\t\tc,\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\th.AddError(\n\t\t\t\t\tfmt.Errorf(\n\t\t\t\t\t\t`Cache not found`,\n\t\t\t\t\t),\n\t\t\t\t\t404,\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\t)\n}"} {"input": "package pointer\n\nimport \"time\"\n\nfunc DefaultBool(value *bool, defaultValue bool) *bool {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultDuration(value *time.Duration, defaultValue time.Duration) *time.Duration {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultFloat64(value *float64, defaultValue float64) *float64 {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultInt(value *int, defaultValue int) *int {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultString(value *string, defaultValue string) *string {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultStringArray(value *[]string, defaultValue []string) *[]string {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\n\n\nfunc DefaultTime(value *time.Time, defaultValue time.Time) *time.Time ", "output": "{\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}"} {"input": "package ratelimiter\n\nimport \"time\"\n\nvar domainLimitMap = make(map[string]*Limiter)\n\n\ntype Limiter struct {\n\tnextChan chan bool\n\tapiLimit time.Duration\n}\n\n\nfunc New(domain string, apiLimit time.Duration) *Limiter {\n\tif _, ok := domainLimitMap[domain]; !ok {\n\t\tdomainLimitMap[domain] = &Limiter{\n\t\t\tnextChan: make(chan bool),\n\t\t\tapiLimit: apiLimit,\n\t\t}\n\t\tdomainLimitMap[domain].next()\n\t}\n\treturn domainLimitMap[domain]\n}\n\n\n\n\nfunc (limiter *Limiter) Wait() {\n\t<-limiter.nextChan\n\tlimiter.next()\n}\n\nfunc (limiter *Limiter) next() ", "output": "{\n\tgo func(l *Limiter) {\n\t\tticker := time.NewTimer(l.apiLimit)\n\t\t<-ticker.C\n\t\tticker.Stop()\n\t\tl.nextChan <- true\n\t}(limiter)\n}"} {"input": "package cfsb\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/wayneeseguin/rdpg-agent/log\"\n\t\"github.com/wayneeseguin/rdpg-agent/rdpg\"\n)\n\ntype PlanDetails struct {\n\tCost string `json:\"cost\"`\n\tBullets []map[string]string `json:\"bullets\"`\n\tDisplayName string `json:\"displayname\"`\n}\n\ntype Plan struct {\n\tId string `db:\"id\"`\n\tPlanId string `db:\"plan_id\" json:\"id\"`\n\tName string `db:\"name\" json:\"name\"`\n\tDescription string `db:\"description\" json:\"description\"`\n\tMetadata PlanDetails `json:\"metadata\"`\n\tMgmtDbUri string `json:\"\"`\n}\n\n\n\nfunc FindPlan(planId string) (plan *Plan, err error) ", "output": "{\n\tr := rdpg.New()\n\tr.OpenDB(\"rdpg\")\n\tplan = &Plan{}\n\tsq := `SELECT id,name,description FROM cfsb.plans WHERE id=$1 LIMIT 1;`\n\terr = r.DB.Get(&plan, sq, planId)\n\tif err != nil {\n\t\tlog.Error(fmt.Sprintf(\"cfsb.FindPlan(%s) %s\", planId, err))\n\t}\n\tr.DB.Close()\n\treturn plan, err\n}"} {"input": "package models\n\nimport (\n\t\"testing\"\n\n\t\"github.com/golib/assert\"\n\tuuid \"github.com/satori/go.uuid\"\n)\n\nfunc Test_NewUserModel(t *testing.T) {\n\tassertion := assert.New(t)\n\n\tvar (\n\t\tusername = uuid.NewV4().String()\n\t\temail = \"tes1@test.com\"\n\t\tpassword = uuid.NewV4().String()\n\t\tdesc = uuid.NewV4().String()\n\t)\n\n\tuser := User.NewUserModel(username, email, password, desc)\n\tassertion.Equal(username, user.Username)\n\tassertion.Equal(email, user.Email)\n\tassertion.Equal(password, user.Password)\n\tassertion.Equal(UserStatusInactive, user.Status)\n\tassertion.Equal(desc, user.Description)\n}\n\nfunc Test_User_FindByEmail(t *testing.T) {\n\tassertion := assert.New(t)\n\n\tvar (\n\t\tusername = uuid.NewV4().String()\n\t\temail = \"test2@test.com\"\n\t\tpassword = uuid.NewV4().String()\n\t\tdesc = uuid.NewV4().String()\n\t)\n\n\tuser := User.NewUserModel(username, email, password, desc)\n\terr := user.Save()\n\tassertion.Nil(err)\n\n\tuser.Save()\n\tassertion.Nil(err)\n\n\tuserNew, err := User.FindByEmail(email)\n\tassertion.Nil(err)\n\tassertion.Equal(user.Id, userNew.Id)\n\n}\n\n\n\nfunc Test_User_FindByUsername(t *testing.T) ", "output": "{\n\tassertion := assert.New(t)\n\n\tvar (\n\t\tusername = uuid.NewV4().String()\n\t\temail = \"test3@test.com\"\n\t\tpassword = uuid.NewV4().String()\n\t\tdesc = uuid.NewV4().String()\n\t)\n\n\tuser := User.NewUserModel(username, email, password, desc)\n\terr := user.Save()\n\tassertion.Nil(err)\n\n\tuserNew, err := User.FindByUsername(username)\n\tassertion.Nil(err)\n\tassertion.Equal(user.Id, userNew.Id)\n\n}"} {"input": "package openstacktasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realFloatingIP FloatingIP\n\n\nfunc (o *FloatingIP) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realFloatingIP\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = FloatingIP(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &FloatingIP{}\n\n\n\n\n\nfunc (o *FloatingIP) SetLifecycle(lifecycle fi.Lifecycle) {\n\to.Lifecycle = &lifecycle\n}\n\nvar _ fi.HasName = &FloatingIP{}\n\n\nfunc (o *FloatingIP) GetName() *string {\n\treturn o.Name\n}\n\n\nfunc (o *FloatingIP) SetName(name string) {\n\to.Name = &name\n}\n\n\nfunc (o *FloatingIP) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *FloatingIP) GetLifecycle() *fi.Lifecycle ", "output": "{\n\treturn o.Lifecycle\n}"} {"input": "package timeseriesinsights\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) BaseClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient ", "output": "{\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package qr\n\nimport (\n\t\"github.com/m3o/m3o-go/client\"\n)\n\n\n\ntype QrService struct {\n\tclient *client.Client\n}\n\n\nfunc (t *QrService) Generate(request *GenerateRequest) (*GenerateResponse, error) {\n\trsp := &GenerateResponse{}\n\treturn rsp, t.client.Call(\"qr\", \"Generate\", request, rsp)\n}\n\ntype GenerateRequest struct {\n\tSize int64 `json:\"size,string\"`\n\tText string `json:\"text\"`\n}\n\ntype GenerateResponse struct {\n\tQr string `json:\"qr\"`\n}\n\nfunc NewQrService(token string) *QrService ", "output": "{\n\treturn &QrService{\n\t\tclient: client.NewClient(&client.Options{\n\t\t\tToken: token,\n\t\t}),\n\t}\n}"} {"input": "package logutils\n\nimport (\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype MockLog struct {\n\tmock.Mock\n}\n\nfunc NewMockLog() *MockLog {\n\treturn &MockLog{}\n}\n\nfunc (m *MockLog) Fatalf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Panicf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Errorf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\n\n\nfunc (m *MockLog) Infof(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Child(name string) Log {\n\tm.Called(name)\n\treturn m\n}\n\nfunc (m *MockLog) SetLevel(level LogLevel) {\n\tm.Called(level)\n}\n\nfunc (m *MockLog) Warnf(format string, args ...interface{}) ", "output": "{\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}"} {"input": "package libra\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype validator struct {\n\tname string\n\tprogram\n\tstdin io.Reader\n}\n\nfunc (v validator) Name() string {\n\treturn v.name\n}\n\nfunc (v validator) Run() Status {\n\tstdout := new(bytes.Buffer)\n\tstderr := new(bytes.Buffer)\n\tv.program.cmd.Stdin = v.stdin\n\tv.program.cmd.Stdout = stdout\n\tv.program.cmd.Stderr = stderr\n\tres := v.program.Run()\n\tif res.Code != OK {\n\t\treturn Status{\n\t\t\tCode: RE,\n\t\t\tMsg: fmt.Sprintf(\"%v\", stderr.String()),\n\t\t}\n\t}\n\treturn res\n}\n\ntype valJob struct {\n\tabstractJob\n\tinputs []Input\n}\n\n\ntype Input interface {\n\tName() string\n\tReader() io.Reader\n}\n\n\n\n\nfunc ValJob(src Src, inputs []Input) Job {\n\tret := valJob{}\n\tret.src = src\n\tret.inputs = inputs\n\treturn ret\n}\n\nfunc (job valJob) Subtasks() []Task ", "output": "{\n\tret := make([]Task, len(job.inputs))\n\tfor i, v := range job.inputs {\n\t\tprog, _ := newProgram(job.src.Exec)\n\t\tret[i] = validator{name: v.Name(), program: prog, stdin: v.Reader()}\n\t}\n\treturn ret\n}"} {"input": "package example\n\nimport (\n\t\"testing\"\n\t\"github.com/remogatto/prettytest\"\n\t\"launchpad.net/gocheck\"\n)\n\n\n\ntype testSuite struct {\n\tprettytest.Suite\n}\n\n\n\n\n\n\n\n\nfunc (t *testSuite) TestTrueIsTrue() {\n\tt.True(true)\n}\n\nfunc (t *testSuite) TestEquality() {\n\tt.Equal(\"awesome\", \"awesome\")\n}\n\nfunc (t *testSuite) TestNot() {\n\tt.Not(t.Path(\"foo\"))\n}\n\nfunc (t *testSuite) TestGoCheck() {\n\tt.Check(\"foo\", gocheck.Equals, \"foo\")\n}\n\n\n\nfunc (t *testSuite) TestMustFail() {\n\tt.Error(\"This test must fail.\")\n\tt.MustFail()\n}\n\nfunc (t *testSuite) TestInequality() {\n\tt.Equal(\"awesome\", \"ugly\")\n\tt.MustFail()\n}\n\nfunc TestRunner(t *testing.T) ", "output": "{\n\tprettytest.Run(\n\t\tt,\n\t\tnew(testSuite),\n\t)\n}"} {"input": "package config\n\nimport (\n\t\"encoding/xml\"\n)\n\ntype defXMLReader struct {\n\topts ReaderOptions\n}\n\n\nfunc NewXMLReader(opts ...ReaderOptionFunc) Reader {\n\tr := &defXMLReader{}\n\tfor _, o := range opts {\n\t\to(&r.opts)\n\t}\n\treturn r\n}\n\nfunc (p *defXMLReader) Read(model interface{}) error {\n\tdata, err := ReadXMLFile(p.opts.filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ParseXMLConfig(data, model)\n}\n\n\n\nfunc (*defXMLReader) ParseData(data []byte, model interface{}) error {\n\treturn ParseXMLConfig(data, model)\n}\n\n\nfunc ReadXMLFile(name string) ([]byte, error) {\n\tdata, _, err := filesRepo.Read(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}\n\n\nfunc ParseXMLConfig(data []byte, model interface{}) error {\n\treturn xml.Unmarshal(data, model)\n}\n\nfunc (*defXMLReader) Dump(v interface{}) ([]byte, error) ", "output": "{\n\treturn xml.Marshal(v)\n}"} {"input": "package worker\n\nimport (\n\t\"github.com/stitchfix/flotilla-os/config\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestGetPollInterval(t *testing.T) ", "output": "{\n\tconf, _ := config.NewConfig(nil)\n\n\texpected := time.Duration(500) * time.Millisecond\n\tos.Setenv(\"WORKER_RETRY_INTERVAL\", \"500ms\")\n\n\tinterval, err := GetPollInterval(\"retry\", conf)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tif interval != expected {\n\t\tt.Errorf(\"Expected interval: [%v] but was [%v]\", expected, interval)\n\t}\n}"} {"input": "package tmdb\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Changes struct {\n\tResults []struct {\n\t\tID int\n\t\tAdult bool\n\t}\n}\n\nvar changeOptions = map[string]struct{}{\n\t\"page\": {},\n\t\"start_date\": {},\n\t\"end_date\": {}}\n\n\n\nfunc (tmdb *TMDb) GetChangesMovie(options map[string]string) (*Changes, error) {\n\tvar movieChanges Changes\n\toptionsString := getOptionsString(options, changeOptions)\n\turi := fmt.Sprintf(\"%s/movie/changes?api_key=%s%s\", baseURL, tmdb.apiKey, optionsString)\n\tresult, err := getTmdb(uri, &movieChanges)\n\treturn result.(*Changes), err\n}\n\n\n\n\n\n\n\nfunc (tmdb *TMDb) GetChangesTv(options map[string]string) (*Changes, error) {\n\tvar tvChanges Changes\n\toptionsString := getOptionsString(options, changeOptions)\n\turi := fmt.Sprintf(\"%s/tv/changes?api_key=%s%s\", baseURL, tmdb.apiKey, optionsString)\n\tresult, err := getTmdb(uri, &tvChanges)\n\treturn result.(*Changes), err\n}\n\nfunc (tmdb *TMDb) GetChangesPerson(options map[string]string) (*Changes, error) ", "output": "{\n\tvar personChanges Changes\n\toptionsString := getOptionsString(options, changeOptions)\n\turi := fmt.Sprintf(\"%s/person/changes?api_key=%s%s\", baseURL, tmdb.apiKey, optionsString)\n\tresult, err := getTmdb(uri, &personChanges)\n\treturn result.(*Changes), err\n}"} {"input": "package fgae\n\nimport(\n\t\"golang.org/x/net/context\"\n\t\"github.com/skypies/util/gcp/ds\"\n\tfdb \"github.com/skypies/flightdb\"\n)\n\n\ntype FlightIterator ds.Iterator\n\nfunc NewFlightIterator(ctx context.Context, p ds.DatastoreProvider, fq *FQuery) *FlightIterator {\n\tit := ds.NewIterator(ctx, p, (*ds.Query)(fq), fdb.IndexedFlightBlob{})\n\treturn (*FlightIterator)(it)\n}\n\n\n\nfunc (fi *FlightIterator)Err() error {\n\tit := (*ds.Iterator)(fi)\n\treturn it.Err()\n}\n\nfunc (fi *FlightIterator)Flight() *fdb.Flight {\n\tblob := fdb.IndexedFlightBlob{}\n\n\tit := (*ds.Iterator)(fi)\n\tkeyer := it.Val(&blob)\n\n\tf, err := blob.ToFlight(keyer.Encode())\n\tif err != nil {\n\t\tit.SetErr(err)\n\t\treturn nil\n\t}\n\n\treturn f\n}\n\nfunc (fi *FlightIterator)Iterate(ctx context.Context) bool ", "output": "{\n\tit := (*ds.Iterator)(fi)\n\treturn it.Iterate(ctx)\n}"} {"input": "package check\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestCompare(t *testing.T) {\n\tassert := assert.New(t)\n\n\tset1 := make(stringSet)\n\tset1.add(\"bar\")\n\tset1.add(\"foo\")\n\n\tset2 := make(stringSet)\n\tset2.add(\"foo\")\n\tset2.add(\"bar\")\n\n\tset3 := make(stringSet)\n\tset3.add(\"foo\")\n\tset3.add(\"baz\")\n\n\tassert.Equal(set1, set2)\n\tassert.Equal(set2, set1)\n\tassert.NotEqual(set1, set3)\n}\n\n\n\nfunc TestString(t *testing.T) ", "output": "{\n\tassert := assert.New(t)\n\n\tset := make(stringSet)\n\tset.add(\"bar\")\n\tset.add(\"xx\")\n\tset.add(\"foo\")\n\n\tassert.Equal(\"bar, foo, xx\", set.String())\n}"} {"input": "package gocleanup\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\nvar cleanupFuncs []func()\nvar capturingSignals bool\n\n\n\n\n\nfunc Register(f func()) {\n\tcleanupFuncs = append(cleanupFuncs, f)\n\tif !capturingSignals {\n\t\tcapturingSignals = true\n\t\tgo func() {\n\t\t\tc := make(chan os.Signal, 1)\n\t\t\tsignal.Notify(c, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM)\n\n\t\t\t<-c\n\t\t\tExit(1)\n\t\t}()\n\t}\n}\n\n\n\n\n\n\nfunc Exit(status int) {\n\tCleanup()\n\tos.Exit(status)\n}\n\nfunc Cleanup() ", "output": "{\n\tfor _, f := range cleanupFuncs {\n\t\tf()\n\t}\n\tcleanupFuncs = []func(){}\n}"} {"input": "package goque\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"encoding/gob\"\n)\n\n\ntype Item struct {\n\tID uint64\n\tKey []byte\n\tValue []byte\n}\n\n\nfunc (i *Item) ToString() string {\n\treturn string(i.Value)\n}\n\n\n\n\n\n\n\n\n\n\ntype PriorityItem struct {\n\tID uint64\n\tPriority uint8\n\tKey []byte\n\tValue []byte\n}\n\n\nfunc (pi *PriorityItem) ToString() string {\n\treturn string(pi.Value)\n}\n\n\n\n\n\n\n\nfunc (pi *PriorityItem) ToObject(value interface{}) error {\n\tbuffer := bytes.NewBuffer(pi.Value)\n\tdec := gob.NewDecoder(buffer)\n\treturn dec.Decode(value)\n}\n\n\nfunc idToKey(id uint64) []byte {\n\tkey := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(key, id)\n\treturn key\n}\n\n\nfunc keyToID(key []byte) uint64 {\n\treturn binary.BigEndian.Uint64(key)\n}\n\nfunc (i *Item) ToObject(value interface{}) error ", "output": "{\n\tbuffer := bytes.NewBuffer(i.Value)\n\tdec := gob.NewDecoder(buffer)\n\treturn dec.Decode(value)\n}"} {"input": "package token_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hyperledger/fabric/core/handlers/validation/token\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestValidation_Validate(t *testing.T) {\n\tfactory := &token.ValidationFactory{}\n\tplugin := factory.New()\n\n\terr := plugin.Init()\n\tassert.NoError(t, err)\n\n\terr = plugin.Validate(nil, \"\", 0, 0, nil)\n\tassert.NoError(t, err)\n}\n\nfunc TestValidationFactory_New(t *testing.T) ", "output": "{\n\tfactory := &token.ValidationFactory{}\n\tplugin := factory.New()\n\tassert.NotNil(t, plugin)\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"golang.org/x/net/context\"\n\n\tCli \"github.com/docker/docker/cli\"\n\tflag \"github.com/docker/docker/pkg/mflag\"\n)\n\n\n\n\n\n\n\n\nfunc (cli *DockerCli) CmdWait(args ...string) error ", "output": "{\n\tcmd := Cli.Subcmd(\"wait\", []string{\"CONTAINER [CONTAINER...]\"}, Cli.DockerCommands[\"wait\"].Description, true)\n\tcmd.Require(flag.Min, 1)\n\n\tcmd.ParseFlags(args, true)\n\n\tvar errs []string\n\tfor _, name := range cmd.Args() {\n\t\tstatus, err := cli.client.ContainerWait(context.Background(), name)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err.Error())\n\t\t} else {\n\t\t\tfmt.Fprintf(cli.out, \"%d\\n\", status)\n\t\t}\n\t}\n\tif len(errs) > 0 {\n\t\treturn fmt.Errorf(\"%s\", strings.Join(errs, \"\\n\"))\n\t}\n\treturn nil\n}"} {"input": "package window_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/kurin/blazer/x/window\"\n)\n\ntype Accumulator struct {\n\tw *window.Window\n}\n\nfunc (a Accumulator) Add(s string) {\n\ta.w.Insert([]string{s})\n}\n\nfunc (a Accumulator) All() []string {\n\tv := a.w.Reduce()\n\treturn v.([]string)\n}\n\nfunc NewAccum(size time.Duration) Accumulator {\n\tr := func(i, j interface{}) interface{} {\n\t\ta, ok := i.([]string)\n\t\tif !ok {\n\t\t\ta = nil\n\t\t}\n\t\tb, ok := j.([]string)\n\t\tif !ok {\n\t\t\tb = nil\n\t\t}\n\t\tfor _, s := range b {\n\t\t\ta = append(a, s)\n\t\t}\n\t\treturn a\n\t}\n\treturn Accumulator{w: window.New(size, time.Second, r)}\n}\n\n\n\nfunc Example_accumulator() ", "output": "{\n\ta := NewAccum(time.Minute)\n\ta.Add(\"this\")\n\ta.Add(\"is\")\n\ta.Add(\"that\")\n\tfmt.Printf(\"total: %v\\n\", a.All())\n}"} {"input": "package utils\n\nimport (\n\t\"golang.org/x/crypto/ssh\"\n)\n\ntype SshClient interface {\n\tClose() error\n\tExecCommand(command string) (string, error)\n}\n\ntype awsSshClient struct {\n\tclient *ssh.Client\n}\n\nfunc GetSshClient(username string, privateKey []byte, ip string) (*awsSshClient, error) {\n\tsigner, err := ssh.ParsePrivateKey(privateKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: username,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t}\n\tclient, err := ssh.Dial(\"tcp\", ip+\":22\", config)\n\n\treturn &awsSshClient{client: client}, err\n}\n\nfunc (sshClient *awsSshClient) Close() error {\n\treturn sshClient.client.Close()\n}\n\n\n\nfunc (sshClient *awsSshClient) ExecCommand(command string) (string, error) ", "output": "{\n\tsession, err := sshClient.client.NewSession()\n\tif err != nil {\n\t}\n\tdefer session.Close()\n\n\toutput, err := session.Output(command)\n\n\treturn string(output), err\n}"} {"input": "package result\n\ntype Classic struct {\n\tid int\n\tfitness float64\n\terr error\n\tstop bool\n}\n\n\n\n\nfunc (r Classic) ID() int { return r.id }\n\n\nfunc (r Classic) Fitness() float64 { return r.fitness }\n\n\nfunc (r Classic) Err() error { return r.err }\n\n\nfunc (r Classic) Stop() bool { return r.stop }\n\nfunc New(id int, fitness float64, err error, stop bool) Classic ", "output": "{\n\treturn Classic{id, fitness, err, stop}\n}"} {"input": "package endpoints\n\nimport (\n\t\"github.com/lxc/lxd/lxd/util\"\n\t\"github.com/lxc/lxd/shared\"\n)\n\n\n\n\nfunc (e *Endpoints) Up(config *Config) error {\n\treturn e.up(config)\n}\n\n\nfunc (e *Endpoints) DevLxdSocketPath() string {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tlistener := e.listeners[devlxd]\n\treturn listener.Addr().String()\n}\n\nfunc (e *Endpoints) LocalSocketPath() string {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tlistener := e.listeners[local]\n\treturn listener.Addr().String()\n}\n\n\n\n\nfunc (e *Endpoints) NetworkAddressAndCert() (string, *shared.CertInfo) {\n\treturn e.NetworkAddress(), e.cert\n}\n\n\n\n\nfunc (e *Endpoints) SystemdListenFDsStart(start int) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\te.systemdListenFDsStart = start\n}\n\nfunc Unstarted() *Endpoints ", "output": "{\n\treturn &Endpoints{\n\t\tsystemdListenFDsStart: util.SystemdListenFDsStart,\n\t}\n}"} {"input": "package rule\n\nimport (\n\t\"go/ast\"\n\n\t\"github.com/mgechev/revive/lint\"\n)\n\n\ntype NestedStructs struct{}\n\n\n\n\n\nfunc (r *NestedStructs) Name() string {\n\treturn \"nested-structs\"\n}\n\ntype lintNestedStructs struct {\n\tfileAST *ast.File\n\tonFailure func(lint.Failure)\n}\n\nfunc (l *lintNestedStructs) Visit(n ast.Node) ast.Visitor {\n\tswitch v := n.(type) {\n\tcase *ast.FuncDecl:\n\t\tif v.Body != nil {\n\t\t\tast.Walk(l, v.Body)\n\t\t}\n\t\treturn nil\n\tcase *ast.Field:\n\t\tif _, ok := v.Type.(*ast.StructType); ok {\n\t\t\tl.onFailure(lint.Failure{\n\t\t\t\tFailure: \"no nested structs are allowed\",\n\t\t\t\tCategory: \"style\",\n\t\t\t\tNode: v,\n\t\t\t\tConfidence: 1,\n\t\t\t})\n\t\t\tbreak\n\t\t}\n\t}\n\treturn l\n}\n\nfunc (r *NestedStructs) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure ", "output": "{\n\tvar failures []lint.Failure\n\n\tif len(arguments) > 0 {\n\t\tpanic(r.Name() + \" doesn't take any arguments\")\n\t}\n\n\twalker := &lintNestedStructs{\n\t\tfileAST: file.AST,\n\t\tonFailure: func(failure lint.Failure) {\n\t\t\tfailures = append(failures, failure)\n\t\t},\n\t}\n\n\tast.Walk(walker, file.AST)\n\n\treturn failures\n}"} {"input": "package clock\n\nimport \"time\"\n\n\nvar Work Clock\n\nfunc init() {\n\tWork = New()\n}\n\n\nfunc Now() time.Time {\n\treturn Work.Now()\n}\n\nfunc Since(t time.Time) time.Duration {\n\treturn Work.Now().Sub(t)\n}\n\n\n\n\n\n\n\nfunc After(d time.Duration) <-chan time.Time {\n\treturn Work.After(d)\n}\n\n\n\nfunc Tick(d time.Duration) <-chan time.Time {\n\treturn Work.Tick(d)\n}\n\n\n\n\n\nfunc Ticker(d time.Duration) *time.Ticker {\n\treturn Work.Ticker(d)\n}\n\n\ntype Clock interface {\n\n\tNow() time.Time\n\n\tSleep(d time.Duration)\n\n\tAfter(d time.Duration) <-chan time.Time\n\n\tTick(d time.Duration) <-chan time.Time\n\n\tTicker(d time.Duration) *time.Ticker\n\n}\n\n\ntype Mock interface {\n\tClock\n\n\n\tSet(t time.Time) Mock\n\n\tAdd(d time.Duration) Mock\n\n\tFreeze() Mock\n\n\tIsFrozen() bool\n\n\tUnfreeze() Mock\n\n\tClose()\n}\n\nfunc Sleep(d time.Duration) ", "output": "{\n\tWork.Sleep(d)\n}"} {"input": "package main\n\nimport \"fmt\"\n\nconst (\n\ta = iota\n\tb\n\tc\n\td\n\te\n)\n\nvar x = []int{1, 2, 3}\n\nfunc f(x int, len *byte) {\n\t*len = byte(x)\n}\n\n\n\nfunc whatis1(x interface{}) string {\n\txx := x\n\tswitch xx.(type) {\n\tdefault:\n\t\treturn fmt.Sprint(\"default \", xx)\n\tcase int, int8, int16, int32:\n\t\treturn fmt.Sprint(\"signed \", xx)\n\tcase int64:\n\t\treturn fmt.Sprint(\"signed64 \", xx.(int64))\n\tcase uint, uint8, uint16, uint32:\n\t\treturn fmt.Sprint(\"unsigned \", xx)\n\tcase uint64:\n\t\treturn fmt.Sprint(\"unsigned64 \", xx.(uint64))\n\tcase nil:\n\t\treturn fmt.Sprint(\"nil \", xx)\n\t}\n\tpanic(\"not reached\")\n}\n\nfunc check(x interface{}, s string) {\n\tw := whatis(x)\n\tif w != s {\n\t\tfmt.Println(\"whatis\", x, \"=>\", w, \"!=\", s)\n\t\tpanic(\"fail\")\n\t}\n\n\tw = whatis1(x)\n\tif w != s {\n\t\tfmt.Println(\"whatis1\", x, \"=>\", w, \"!=\", s)\n\t\tpanic(\"fail\")\n\t}\n}\n\nfunc main() {\n\tcheck(1, \"signed 1\")\n\tcheck(uint(1), \"unsigned 1\")\n\tcheck(int64(1), \"signed64 1\")\n\tcheck(uint64(1), \"unsigned64 1\")\n\tcheck(1.5, \"default 1.5\")\n\tcheck(nil, \"nil \")\n}\n\nfunc whatis(x interface{}) string ", "output": "{\n\tswitch xx := x.(type) {\n\tdefault:\n\t\treturn fmt.Sprint(\"default \", xx)\n\tcase int, int8, int16, int32:\n\t\treturn fmt.Sprint(\"signed \", xx)\n\tcase int64:\n\t\treturn fmt.Sprint(\"signed64 \", int64(xx))\n\tcase uint, uint8, uint16, uint32:\n\t\treturn fmt.Sprint(\"unsigned \", xx)\n\tcase uint64:\n\t\treturn fmt.Sprint(\"unsigned64 \", uint64(xx))\n\tcase nil:\n\t\treturn fmt.Sprint(\"nil \", xx)\n\t}\n\tpanic(\"not reached\")\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"github.com/go-swagger/go-swagger/errors\"\n\t\"github.com/go-swagger/go-swagger/strfmt\"\n\t\"github.com/go-swagger/go-swagger/swag\"\n)\n\n\ntype NotificationPageableResult struct {\n\n\tContent []*Notification `json:\"content,omitempty\"`\n\n\tFirst bool `json:\"first,omitempty\"`\n\n\tLast bool `json:\"last,omitempty\"`\n\n\tNumber int32 `json:\"number,omitempty\"`\n\n\tNumberOfElements int32 `json:\"numberOfElements,omitempty\"`\n\n\tServerTime int64 `json:\"serverTime,omitempty\"`\n\n\tSize int32 `json:\"size,omitempty\"`\n\n\tTotalElements int32 `json:\"totalElements,omitempty\"`\n\n\tTotalPages int32 `json:\"totalPages,omitempty\"`\n}\n\n\nfunc (m *NotificationPageableResult) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateContent(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\nfunc (m *NotificationPageableResult) validateContent(formats strfmt.Registry) error ", "output": "{\n\n\tif swag.IsZero(m.Content) { \n\t\treturn nil\n\t}\n\n\tfor i := 0; i < len(m.Content); i++ {\n\n\t\tif m.Content[i] != nil {\n\n\t\t\tif err := m.Content[i].Validate(formats); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}"} {"input": "package fileinterface\n\nimport (\n \"testing\"\n \"errors\"\n )\n\n\n\nfunc TestDelete(t *testing.T) {\n\terr := Delete(\"dummyfile\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestOpen(t *testing.T) {\n\tif f, err := Open(\"sample.database\"); err != nil {\n\t\tt.Error(err)\n\t} else if err = Close(f); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestRead(t *testing.T) {\n\tvar block *Block\n\tif f, err := Open(\"sample.database\"); err != nil {\n\t\tt.Error(err)\n\t} else if block, err = Read(f, 5); err != nil {\n\t\tt.Error(err)\n\t} else if err = Close(f); err != nil {\n\t\tt.Error(err)\n\t}\n\tfor i:=0; i Version {\n\t\terr = errors.Reason(\"bad version: %(ver)d > %(ours)d\").\n\t\t\tD(\"ver\", version).D(\"ours\", Version).Err()\n\t\treturn\n\t}\n\n\treturn\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateNatGatewayRequest struct {\n\n\tCreateNatGatewayDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateNatGatewayRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateNatGatewayRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CreateNatGatewayRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CreateNatGatewayRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateNatGatewayResponse struct {\n\n\tRawResponse *http.Response\n\n\tNatGateway `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response CreateNatGatewayResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response CreateNatGatewayResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package util\n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"testing\"\n)\n\nfunc TestHeartbeatUtil(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tt.Fatalf(\"TestHeartbeatUtil failed\")\n\t\t}\n\t}()\n\tHeartbeatUtil(context.Background(), \"\", \"\", \"\")\n}\n\n\n\nfunc TestKeepAliveLease(t *testing.T) ", "output": "{\n\t_, err := KeepAliveLease(context.Background(), \"\", \"\", \"\", -1)\n\tif err == nil {\n\t\tt.Fatalf(\"KeepAliveLease -1 failed\")\n\t}\n\n\t_, err = KeepAliveLease(context.Background(), \"\", \"\", \"\", 0)\n\tif err != nil {\n\t\tt.Fatalf(\"KeepAliveLease failed\")\n\t}\n}"} {"input": "package messages\n\nimport (\n\t\"bytes\"\n\t\"message-delivery-system/src/utils\"\n)\n\n\ntype ListResponse struct {\n\tList []uint64\n\tReceiver uint64\n}\n\n\nfunc NewListResponse(data []byte) ListResponse {\n\tbuf := bytes.NewReader(data)\n\tlist, _ := utils.ByteArrayToUint64List(buf, data)\n\treturn ListResponse{List:list}\n}\n\n\n\n\n\nfunc (l ListResponse) GetData() []byte {\n\tbuf := new(bytes.Buffer)\n\tdata, _ := utils.Uint64ListToByteArray(buf, l.List)\n\treturn data\n}\n\n\nfunc (l ListResponse) GetReceiverIds() []uint64 {\n\tvar receivers []uint64\n\treturn append(receivers, l.Receiver)\n}\n\nfunc (l ListResponse) GetMessageType() MessageType ", "output": "{\n\treturn ListResponseMessage\n}"} {"input": "package migrations_test\n\nimport (\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\n\n\nfunc assertCorrectFileContents(t *testing.T, filePath string, expectedFileContents string) {\n\tfileContents, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif string(fileContents) != expectedFileContents {\n\t\tt.Fatal(\"Incorrect file content:\", filePath)\n\t}\n}\n\nfunc assertCorrectRepoVer(t *testing.T, verPath, expectedRepoVer string) ", "output": "{\n\trepoVer, err := ioutil.ReadFile(verPath)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif string(repoVer) != expectedRepoVer {\n\t\tt.Fatal(\"Failed to write new repo version\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/gorilla/websocket\"\n)\n\nvar upgrader = websocket.Upgrader{} \nfunc Echo(w http.ResponseWriter, r *http.Request) {\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Print(\"upgrade:\", err)\n\t\treturn\n\t}\n\tfmt.Println(\"start websocket!\")\n\tsession := NewSession(ws)\n\tdefer func() {\n\t\tDelSession(session)\n\t\tfmt.Println(\"close websocket!\")\n\t}()\n\tgo session.Send()\n\tsession.handler()\n}\n\n\n\nfunc main() {\n\thttp.HandleFunc(\"/\", index)\n\thttp.HandleFunc(\"/echo\", Echo)\n\tgo NotifyClient()\n\tif err := http.ListenAndServe(\":1234\", nil); err != nil {\n\t\tlog.Fatal(\"ListenAndServe:\", err)\n\t}\n}\n\nfunc index(w http.ResponseWriter, res *http.Request) ", "output": "{\n\tt, _ := template.ParseFiles(\"index.html\")\n\tt.Execute(w, nil)\n}"} {"input": "package http\n\nimport (\n\t\"net\"\n\t\"time\"\n)\n\n\ntype TimeoutConn struct {\n\tQuirkConn\n\treadTimeout time.Duration\n\twriteTimeout time.Duration\n}\n\nfunc (c *TimeoutConn) setReadTimeout() {\n\tif c.readTimeout != 0 && c.canSetReadDeadline() {\n\t\tc.SetReadDeadline(time.Now().UTC().Add(c.readTimeout))\n\t}\n}\n\n\n\n\nfunc (c *TimeoutConn) Read(b []byte) (n int, err error) {\n\tc.setReadTimeout()\n\treturn c.Conn.Read(b)\n}\n\n\nfunc (c *TimeoutConn) Write(b []byte) (n int, err error) {\n\tc.setWriteTimeout()\n\treturn c.Conn.Write(b)\n}\n\n\nfunc NewTimeoutConn(c net.Conn, readTimeout, writeTimeout time.Duration) *TimeoutConn {\n\treturn &TimeoutConn{\n\t\tQuirkConn: QuirkConn{Conn: c},\n\t\treadTimeout: readTimeout,\n\t\twriteTimeout: writeTimeout,\n\t}\n}\n\nfunc (c *TimeoutConn) setWriteTimeout() ", "output": "{\n\tif c.writeTimeout != 0 {\n\t\tc.SetWriteDeadline(time.Now().UTC().Add(c.writeTimeout))\n\t}\n}"} {"input": "package chipmunk\n\nimport (\n\t\"github.com/Dethrail/chipmunk/transform\"\n\t\"github.com/Dethrail/chipmunk/vect\"\n\t\"math\"\n)\n\nconst (\n\tRadianConst = math.Pi / 180\n\tDegreeConst = 180 / math.Pi\n)\n\ntype Group int\ntype Layer int\n\ntype Shape struct {\n\tDefaultHash\n\tShapeClass\n\n\tBody *Body\n\n\tBB AABB\n\n\tIsSensor bool\n\n\te vect.Float\n\tu vect.Float\n\tSurface_v vect.Vect\n\n\tUserData interface{}\n\n\tGroup Group\n\tLayer Layer\n\n\tspace *Space\n\n\tvelocityIndexed bool\n}\n\nfunc newShape() *Shape {\n\treturn &Shape{velocityIndexed: true, e: 0.5, u: 0.5, Layer: -1}\n\n}\n\n\n\nfunc (shape *Shape) SetFriction(friction vect.Float) {\n\tshape.u = friction\n}\n\nfunc (shape *Shape) SetElasticity(e vect.Float) {\n\tshape.e = e\n}\n\nfunc (shape *Shape) Shape() *Shape {\n\treturn shape\n}\n\nfunc (shape *Shape) AABB() AABB {\n\treturn shape.BB\n}\n\nfunc (shape *Shape) Clone() *Shape {\n\tclone := *shape\n\tcc := &clone\n\tcc.space = nil\n\tcc.DefaultHash.Reset()\n\tcc.Body = nil\n\tcc.ShapeClass = cc.ShapeClass.Clone(cc)\n\treturn cc\n}\n\nfunc (shape *Shape) Update() {\n\tshape.BB = shape.ShapeClass.update(transform.NewTransform(shape.Body.p, shape.Body.a))\n}\n\nfunc (shape *Shape) Velocity() (vect.Vect, bool) ", "output": "{\n\treturn shape.Body.v, shape.velocityIndexed\n}"} {"input": "package glib\n\n\n\n\n\nimport \"C\"\nimport \"unsafe\"\n\n\n\ntype IActionMap interface {\n\tNative() uintptr\n\n\tLookupAction(actionName string) *Action\n\tAddAction(action IAction)\n\tRemoveAction(actionName string)\n}\n\n\ntype ActionMap struct {\n\t*Object\n}\n\n\n\n\n\nfunc (v *ActionMap) native() *C.GActionMap {\n\tif v == nil || v.GObject == nil {\n\t\treturn nil\n\t}\n\treturn C.toGActionMap(unsafe.Pointer(v.GObject))\n}\n\nfunc (v *ActionMap) Native() uintptr {\n\treturn uintptr(unsafe.Pointer(v.native()))\n}\n\nfunc marshalActionMap(p uintptr) (interface{}, error) {\n\tc := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))\n\treturn wrapActionMap(wrapObject(unsafe.Pointer(c))), nil\n}\n\n\n\n\nfunc (v *ActionMap) LookupAction(actionName string) *Action {\n\tc := C.g_action_map_lookup_action(v.native(), (*C.gchar)(C.CString(actionName)))\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn wrapAction(wrapObject(unsafe.Pointer(c)))\n}\n\n\nfunc (v *ActionMap) AddAction(action IAction) {\n\tC.g_action_map_add_action(v.native(), action.toGAction())\n}\n\n\nfunc (v *ActionMap) RemoveAction(actionName string) {\n\tC.g_action_map_remove_action(v.native(), (*C.gchar)(C.CString(actionName)))\n}\n\nfunc wrapActionMap(obj *Object) *ActionMap ", "output": "{\n\treturn &ActionMap{obj}\n}"} {"input": "package core \n\nimport (\n\t\"sync\"\n\n\t\"barista.run/bar\"\n\tl \"barista.run/logging\"\n\t\"barista.run/sink\"\n)\n\n\n\ntype ModuleSet struct {\n\tmodules []*Module\n\tupdateCh chan int\n\toutputs []bar.Segments\n\toutputsMu sync.RWMutex\n}\n\n\nfunc NewModuleSet(modules []bar.Module) *ModuleSet {\n\tset := &ModuleSet{\n\t\tmodules: make([]*Module, len(modules)),\n\t\toutputs: make([]bar.Segments, len(modules)),\n\t\tupdateCh: make(chan int),\n\t}\n\tfor i, m := range modules {\n\t\tl.Fine(\"%s added as %s[%d]\", l.ID(m), l.ID(set), i)\n\t\tset.modules[i] = NewModule(m)\n\t}\n\treturn set\n}\n\n\n\nfunc (m *ModuleSet) Stream() <-chan int {\n\tfor i, mod := range m.modules {\n\t\tgo mod.Stream(m.sinkFn(i))\n\t}\n\treturn m.updateCh\n}\n\nfunc (m *ModuleSet) sinkFn(idx int) bar.Sink {\n\treturn sink.Func(func(out bar.Segments) {\n\t\tl.Fine(\"%s new output from %s\",\n\t\t\tl.ID(m), l.ID(m.modules[idx].original))\n\t\tm.outputsMu.Lock()\n\t\tm.outputs[idx] = out\n\t\tm.outputsMu.Unlock()\n\t\tm.updateCh <- idx\n\t})\n}\n\n\nfunc (m *ModuleSet) Len() int {\n\treturn len(m.modules)\n}\n\n\n\nfunc (m *ModuleSet) LastOutput(idx int) bar.Segments {\n\tm.outputsMu.RLock()\n\tdefer m.outputsMu.RUnlock()\n\treturn m.outputs[idx]\n}\n\n\n\n\n\n\nfunc (m *ModuleSet) LastOutputs() []bar.Segments ", "output": "{\n\tm.outputsMu.RLock()\n\tdefer m.outputsMu.RUnlock()\n\tcp := make([]bar.Segments, len(m.outputs))\n\tcopy(cp, m.outputs)\n\treturn cp\n}"} {"input": "package main\n\ntype Move struct {\n\tSrc Point\n\tDest Point\n}\n\nvar EmptyMove = Move{Point{0, 0}, Point{0, 0}}\n\nfunc NewMove(src Point, dest Point) Move {\n\ts, d := src, dest\n\tif s.X > d.X {\n\t\ts.X, d.X = d.X, s.X\n\t}\n\tif s.Y > d.Y {\n\t\ts.Y, d.Y = d.Y, s.Y\n\t}\n\n\treturn Move{src, dest}\n}\n\n\n\nfunc (m Move) Valid(table Table) bool {\n\tfor x := m.Src.X; x <= m.Dest.X; x++ {\n\t\tfor y := m.Src.Y; y <= m.Dest.Y; y++ {\n\t\t\tcell := table[y][x]\n\t\t\tswitch cell {\n\t\t\tcase HOLLOW, LAND:\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (m Move) Apply(t Table) {\n\tdist := m.Src.DistanceTo(m.Dest) + 1\n\tdist /= 2\n\n\tif m.Src.X == m.Dest.X {\n\t\tfor i := 0; i < dist; i++ {\n\t\t\tt.SwapY(m.Src.X, m.Src.Y+i, m.Dest.Y-i)\n\t\t}\n\n\t} else if m.Src.Y == m.Dest.Y {\n\t\tfor i := 0; i < dist; i++ {\n\t\t\tt.SwapX(m.Src.Y, m.Src.X+i, m.Dest.X-i)\n\t\t}\n\n\t} else {\n\t\tpanic(\"Diagonal move is not supported!\")\n\t}\n\n\n\n\tfor t.Resolve() > 0 {\n\t}\n}\n\nfunc (m Move) String() string ", "output": "{\n\treturn m.Src.String() + \">\" + m.Dest.String()\n}"} {"input": "package cemi\n\n\ntype Priority uint8\n\nconst (\n\tPrioSystem Priority = 0\n\n\tPrioNormal Priority = 1\n\n\tPrioUrgent Priority = 2\n\n\tPrioLow Priority = 3\n)\n\n\ntype ControlField1 uint8\n\nconst (\n\tControl1StdFrame ControlField1 = 1 << 7\n\n\tControl1NoRepeat ControlField1 = 1 << 5\n\n\tControl1NoSysBroadcast ControlField1 = 1 << 4\n\n\tControl1WantAck ControlField1 = 1 << 1\n\n\tControl1HasError ControlField1 = 1\n)\n\n\n\n\n\ntype ControlField2 uint8\n\n\nfunc (ctrl2 ControlField2) IsGroupAddr() bool {\n\treturn ctrl2&Control2GroupAddr == Control2GroupAddr\n}\n\n\nfunc (ctrl2 ControlField2) Hops() uint8 {\n\treturn uint8(ctrl2>>7) & 7\n}\n\nconst (\n\tControl2GroupAddr ControlField2 = 1 << 7\n\n\tControl2LTEFrame ControlField2 = 1 << 2\n)\n\n\nfunc Control2Hops(hops uint8) ControlField2 {\n\tif hops > 7 {\n\t\thops = 7\n\t}\n\n\treturn ControlField2(hops&7) << 4\n}\n\nfunc Control1Prio(prio Priority) ControlField1 ", "output": "{\n\treturn ControlField1(prio&3) << 2\n}"} {"input": "package vm\n\nimport (\n\t\"math/big\"\n\n\t\"github.com/burnoutcoin/go-burnout/common\"\n)\n\n\n\n\ntype destinations map[common.Hash][]byte\n\n\nfunc (d destinations) has(codehash common.Hash, code []byte, dest *big.Int) bool {\n\tudest := dest.Uint64()\n\tif dest.BitLen() >= 63 || udest >= uint64(len(code)) {\n\t\treturn false\n\t}\n\n\tm, analysed := d[codehash]\n\tif !analysed {\n\t\tm = jumpdests(code)\n\t\td[codehash] = m\n\t}\n\treturn (m[udest/8] & (1 << (udest % 8))) != 0\n}\n\n\n\n\n\nfunc jumpdests(code []byte) []byte ", "output": "{\n\tm := make([]byte, len(code)/8+1)\n\tfor pc := uint64(0); pc < uint64(len(code)); pc++ {\n\t\top := OpCode(code[pc])\n\t\tif op == JUMPDEST {\n\t\t\tm[pc/8] |= 1 << (pc % 8)\n\t\t} else if op >= PUSH1 && op <= PUSH32 {\n\t\t\ta := uint64(op) - uint64(PUSH1) + 1\n\t\t\tpc += a\n\t\t}\n\t}\n\treturn m\n}"} {"input": "package security\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/goharbor/harbor/src/common/security\"\n\t\"github.com/goharbor/harbor/src/lib\"\n\t\"github.com/goharbor/harbor/src/lib/config\"\n\t\"github.com/goharbor/harbor/src/lib/log\"\n\t\"github.com/goharbor/harbor/src/server/middleware\"\n)\n\nvar (\n\tgenerators = []generator{\n\t\t&secret{},\n\t\t&oidcCli{},\n\t\t&v2Token{},\n\t\t&idToken{},\n\t\t&authProxy{},\n\t\t&robot{},\n\t\t&basicAuth{},\n\t\t&session{},\n\t\t&proxyCacheSecret{},\n\t}\n)\n\n\ntype generator interface {\n\tGenerate(req *http.Request) security.Context\n}\n\n\n\n\n\n\nfunc UnauthorizedMiddleware(skippers ...middleware.Skipper) func(http.Handler) http.Handler {\n\treturn middleware.New(func(w http.ResponseWriter, r *http.Request, next http.Handler) {\n\t\tif _, ok := security.FromContext(r.Context()); !ok {\n\t\t\tu := &unauthorized{}\n\t\t\tr = r.WithContext(security.NewContext(r.Context(), u.Generate(r)))\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t}, skippers...)\n}\n\nfunc Middleware(skippers ...middleware.Skipper) func(http.Handler) http.Handler ", "output": "{\n\treturn middleware.New(func(w http.ResponseWriter, r *http.Request, next http.Handler) {\n\t\tlog := log.G(r.Context())\n\t\tmode, err := config.AuthMode(r.Context())\n\t\tif err == nil {\n\t\t\tr = r.WithContext(lib.WithAuthMode(r.Context(), mode))\n\t\t} else {\n\t\t\tlog.Warningf(\"failed to get auth mode: %v\", err)\n\t\t}\n\t\tfor _, generator := range generators {\n\t\t\tif ctx := generator.Generate(r); ctx != nil {\n\t\t\t\tr = r.WithContext(security.NewContext(r.Context(), ctx))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t}, skippers...)\n}"} {"input": "package provider\n\nimport (\n\t\"strings\"\n)\n\n\ntype DomainFilter struct {\n\tfilters []string\n\texclude []string\n}\n\n\n\n\n\nfunc NewDomainFilterWithExclusions(domainFilters []string, excludeDomains []string) DomainFilter {\n\treturn DomainFilter{prepareFilters(domainFilters), prepareFilters(excludeDomains)}\n}\n\n\nfunc NewDomainFilter(domainFilters []string) DomainFilter {\n\treturn DomainFilter{prepareFilters(domainFilters), []string{}}\n}\n\n\nfunc (df DomainFilter) Match(domain string) bool {\n\treturn matchFilter(df.filters, domain, true) && !matchFilter(df.exclude, domain, false)\n}\n\n\n\n\nfunc matchFilter(filters []string, domain string, emptyval bool) bool {\n\tif len(filters) == 0 {\n\t\treturn emptyval\n\t}\n\n\tfor _, filter := range filters {\n\t\tstrippedDomain := strings.ToLower(strings.TrimSuffix(domain, \".\"))\n\n\t\tif filter == \"\" {\n\t\t\treturn emptyval\n\t\t} else if strings.HasPrefix(filter, \".\") && strings.HasSuffix(strippedDomain, filter) {\n\t\t\treturn true\n\t\t} else if strings.Count(strippedDomain, \".\") == strings.Count(filter, \".\") {\n\t\t\tif strippedDomain == filter {\n\t\t\t\treturn true\n\t\t\t}\n\t\t} else if strings.HasSuffix(strippedDomain, \".\"+filter) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (df DomainFilter) IsConfigured() bool {\n\tif len(df.filters) == 1 {\n\t\treturn df.filters[0] != \"\"\n\t}\n\treturn len(df.filters) > 0\n}\n\nfunc prepareFilters(filters []string) []string ", "output": "{\n\tfs := make([]string, len(filters))\n\tfor i, domain := range filters {\n\t\tfs[i] = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), \".\"))\n\t}\n\treturn fs\n}"} {"input": "package soap\n\nimport (\n\t\"github.com/vmware/govmomi/vim25/types\"\n\t\"github.com/vmware/govmomi/vim25/xml\"\n)\n\ntype Envelope struct {\n\tXMLName xml.Name `xml:\"http://schemas.xmlsoap.org/soap/envelope/ Envelope\"`\n\tHeader *Header `xml:\",omitempty\"`\n\tBody interface{}\n}\n\ntype Header struct {\n\tXMLName xml.Name `xml:\"http://schemas.xmlsoap.org/soap/envelope/ Header\"`\n}\n\ntype Fault struct {\n\tXMLName xml.Name `xml:\"http://schemas.xmlsoap.org/soap/envelope/ Fault\"`\n\tCode string `xml:\"faultcode\"`\n\tString string `xml:\"faultstring\"`\n\tDetail struct {\n\t\tFault types.AnyType `xml:\",any\"`\n\t} `xml:\"detail\"`\n}\n\n\n\nfunc (f *Fault) VimFault() types.AnyType ", "output": "{\n\treturn f.Detail.Fault\n}"} {"input": "package loads\n\nimport \"jvmgo/ch09/instructions/base\"\nimport \"jvmgo/ch09/rtda\"\n\n\ntype ILOAD struct{ base.Index8Instruction }\n\n\n\ntype ILOAD_0 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_0) Execute(frame *rtda.Frame) {\n\t_iload(frame, 0)\n}\n\ntype ILOAD_1 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_1) Execute(frame *rtda.Frame) {\n\t_iload(frame, 1)\n}\n\ntype ILOAD_2 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_2) Execute(frame *rtda.Frame) {\n\t_iload(frame, 2)\n}\n\ntype ILOAD_3 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_3) Execute(frame *rtda.Frame) {\n\t_iload(frame, 3)\n}\n\nfunc _iload(frame *rtda.Frame, index uint) {\n\tval := frame.LocalVars().GetInt(index)\n\tframe.OperandStack().PushInt(val)\n}\n\nfunc (self *ILOAD) Execute(frame *rtda.Frame) ", "output": "{\n\t_iload(frame, self.Index)\n}"} {"input": "package rbac\n\nimport (\n\tv3 \"github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3\"\n\ttypesrbacv1 \"github.com/rancher/rancher/pkg/generated/norman/rbac.authorization.k8s.io/v1\"\n\trbacv1 \"k8s.io/api/rbac/v1\"\n\tapierrors \"k8s.io/apimachinery/pkg/api/errors\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\ntype crHandler struct {\n\tclusterRoles typesrbacv1.ClusterRoleInterface\n\troleTemplateLister v3.RoleTemplateLister\n}\n\nfunc newClusterRoleHandler(r *manager) *crHandler {\n\treturn &crHandler{\n\t\tclusterRoles: r.clusterRoles,\n\t\troleTemplateLister: r.rtLister,\n\t}\n}\n\n\n\n\n\nfunc (c *crHandler) sync(key string, obj *rbacv1.ClusterRole) (runtime.Object, error) ", "output": "{\n\tif key == \"\" || obj == nil {\n\t\treturn nil, nil\n\t}\n\n\tif owner, ok := obj.Annotations[clusterRoleOwner]; ok {\n\t\t_, err := c.roleTemplateLister.Get(\"\", owner)\n\t\tif err != nil {\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\treturn obj, c.clusterRoles.Delete(obj.Name, &metav1.DeleteOptions{})\n\t\t\t}\n\t\t\treturn obj, err\n\t\t}\n\t}\n\n\treturn obj, nil\n}"} {"input": "package token\n\nimport (\n\t\"strings\"\n\n\t\"github.com/carlcui/expressive/locator\"\n)\n\n\ntype Token struct {\n\tTokenType Type\n\tRaw string\n\tLocator locator.Locator\n}\n\nfunc (tok *Token) String() string {\n\treturn tok.TokenType.String() + \": \" + tok.Raw\n}\n\nfunc (tok *Token) GetLocation() string {\n\tif tok.Locator == nil {\n\t\treturn \"unknown location\"\n\t}\n\n\treturn tok.Locator.Locate()\n}\n\n\nfunc IllegalToken(raw string, locator locator.Locator) *Token {\n\treturn &Token{TokenType: ILLEGAL, Raw: raw, Locator: locator}\n}\n\n\nfunc EOFToken(locator locator.Locator) *Token {\n\treturn &Token{TokenType: EOF, Raw: \"\", Locator: locator}\n}\n\n\n\n\n\nfunc MatchOperator(reading string) *Token {\n\tif tokenType, isOperator := operators[reading]; isOperator {\n\t\treturn &Token{TokenType: tokenType, Raw: reading}\n\t}\n\n\treturn nil\n}\n\nfunc HasOperatorPrefix(reading string) bool {\n\tfor i := operatorStart + 1; i < operatorEnd; i++ {\n\t\tif strings.HasPrefix(tokens[i], reading) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc MatchKeyword(reading string) *Token ", "output": "{\n\tif tokenType, isKeyword := keywords[reading]; isKeyword {\n\t\treturn &Token{TokenType: tokenType, Raw: reading}\n\t}\n\n\treturn nil\n}"} {"input": "package glacier\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/rdwilliamson/aws\"\n)\n\n\ntype Connection struct {\n\tClient *http.Client\n\n\tSignature *aws.Signature\n}\n\nfunc (c *Connection) client() *http.Client {\n\tif c.Client == nil {\n\t\treturn http.DefaultClient\n\t}\n\treturn c.Client\n}\n\n\nfunc (c *Connection) vault(vault string) string {\n\treturn \"https://\" + c.Signature.Region.Glacier + \"/-/vaults/\" + vault\n}\n\n\n\n\n\n\nfunc NewConnection(secret, access string, r *aws.Region) *Connection {\n\treturn &Connection{\n\t\tSignature: aws.NewSignature(secret, access, r, \"glacier\"),\n\t}\n}\n\n\n\n\nfunc toHex(x []byte) string {\n\treturn fmt.Sprintf(\"%x\", x)\n}\n\n\n\ntype parameters url.Values\n\n\n\nfunc (p parameters) add(key, value string) {\n\turl.Values(p).Add(key, value)\n}\n\n\n\nfunc (p parameters) encode() string {\n\tif encoded := url.Values(p).Encode(); encoded != \"\" {\n\t\treturn \"?\" + encoded\n\t}\n\treturn \"\"\n}\n\nfunc (c *Connection) policy(policy string) string ", "output": "{\n\treturn \"https://\" + c.Signature.Region.Glacier + \"/-/policies/\" + policy\n}"} {"input": "package mysql\n\nimport (\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"github.com/jmoiron/sqlx\"\n\t\"github.com/stellar/federation/db\"\n)\n\ntype MysqlDriver struct {\n\tdatabase *sqlx.DB\n}\n\n\n\nfunc (d *MysqlDriver) GetByStellarAddress(name, query string) (*db.FederationRecord, error) {\n\tvar record db.FederationRecord\n\terr := d.database.Get(&record, query, name)\n\tif err != nil {\n\t\tif err.Error() == \"sql: no rows in result set\" {\n\t\t\treturn nil, nil\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &record, nil\n}\n\nfunc (d *MysqlDriver) GetByAccountId(accountId, query string) (*db.ReverseFederationRecord, error) {\n\tvar record db.ReverseFederationRecord\n\terr := d.database.Get(&record, query, accountId)\n\tif err != nil {\n\t\tif err.Error() == \"sql: no rows in result set\" {\n\t\t\treturn nil, nil\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &record, nil\n}\n\nfunc (d *MysqlDriver) Init(url string) (err error) ", "output": "{\n\td.database, err = sqlx.Connect(\"mysql\", url)\n\treturn\n}"} {"input": "package test\n\nimport (\n\t\"github.com/tidepool-org/platform/data/types/bolus/combination\"\n\tdataTypesBolusTest \"github.com/tidepool-org/platform/data/types/bolus/test\"\n\t\"github.com/tidepool-org/platform/pointer\"\n\t\"github.com/tidepool-org/platform/test\"\n)\n\nfunc NewCombination() *combination.Combination {\n\tdatum := combination.New()\n\tdatum.Bolus = *dataTypesBolusTest.NewBolus()\n\tdatum.SubType = \"dual/square\"\n\tdatum.Duration = pointer.FromInt(test.RandomIntFromRange(combination.DurationMinimum, combination.DurationMaximum))\n\tdatum.Extended = pointer.FromFloat64(test.RandomFloat64FromRange(combination.ExtendedMinimum, combination.ExtendedMaximum))\n\tdatum.DurationExpected = pointer.FromInt(test.RandomIntFromRange(*datum.Duration, combination.DurationMaximum))\n\tdatum.ExtendedExpected = pointer.FromFloat64(test.RandomFloat64FromRange(*datum.Extended, combination.ExtendedMaximum))\n\tdatum.Normal = pointer.FromFloat64(test.RandomFloat64FromRange(combination.NormalMinimum, combination.NormalMaximum))\n\tdatum.NormalExpected = nil\n\treturn datum\n}\n\n\n\nfunc CloneCombination(datum *combination.Combination) *combination.Combination ", "output": "{\n\tif datum == nil {\n\t\treturn nil\n\t}\n\tclone := combination.New()\n\tclone.Duration = pointer.CloneInt(datum.Duration)\n\tclone.DurationExpected = pointer.CloneInt(datum.DurationExpected)\n\tclone.Extended = pointer.CloneFloat64(datum.Extended)\n\tclone.ExtendedExpected = pointer.CloneFloat64(datum.ExtendedExpected)\n\tclone.Bolus = *dataTypesBolusTest.CloneBolus(&datum.Bolus)\n\tclone.Normal = pointer.CloneFloat64(datum.Normal)\n\tclone.NormalExpected = pointer.CloneFloat64(datum.NormalExpected)\n\treturn clone\n}"} {"input": "package proxy\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n)\n\ntype Response interface {\n\tStatus() int\n\tHeader() http.Header\n\tBody() []byte\n}\n\ntype WriterRecorder struct {\n\thttp.ResponseWriter\n\tstatus int\n\tbody bytes.Buffer\n}\n\nfunc (w *WriterRecorder) WriteHeader(status int) {\n\tw.ResponseWriter.WriteHeader(status)\n\tw.status = status\n}\n\nfunc (w *WriterRecorder) Write(body []byte) (n int, err error) {\n\tif n, err := w.body.Write(body); err != nil {\n\t\treturn n, err\n\t}\n\n\treturn w.ResponseWriter.Write(body)\n}\n\n\n\nfunc (w *WriterRecorder) Status() int {\n\tif w.status == 0 {\n\t\treturn 200\n\t}\n\treturn w.status\n}\n\nfunc (w *WriterRecorder) Body() []byte ", "output": "{\n\treturn w.body.Bytes()\n}"} {"input": "package unifi\n\nimport (\n\t\"strconv\"\n)\n\ntype fuzzyFloat float64\n\n\n\nfunc (f *fuzzyFloat) UnmarshalJSON(b []byte) error ", "output": "{\n\ts := string(b)\n\tif len(s) == 0 {\n\t\treturn nil\n\t}\n\tif s[0] == '\"' && s[len(s)-1] == '\"' {\n\t\ts = s[1 : len(s)-1]\n\t}\n\tif s == \"\" || s == \"null\" {\n\t\treturn nil\n\t}\n\tv, err := strconv.ParseFloat(s, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*f = fuzzyFloat(v)\n\treturn nil\n}"} {"input": "package comment\n\nimport (\n\t\"time\"\n\n\t\"github.com/google/go-github/github\"\n)\n\n\ntype Matcher interface {\n\tMatch(comment *github.IssueComment) bool\n}\n\n\ntype CreatedAfter time.Time\n\n\nfunc (c CreatedAfter) Match(comment *github.IssueComment) bool {\n\tif comment == nil || comment.CreatedAt == nil {\n\t\treturn false\n\t}\n\treturn comment.CreatedAt.After(time.Time(c))\n}\n\n\ntype CreatedBefore time.Time\n\n\n\n\nfunc (c CreatedBefore) Match(comment *github.IssueComment) bool ", "output": "{\n\tif comment == nil || comment.CreatedAt == nil {\n\t\treturn false\n\t}\n\treturn comment.CreatedAt.Before(time.Time(c))\n}"} {"input": "package macaron\n\nimport (\n\t\"net/http\"\n\t\"reflect\"\n\n\t\"gitea.com/macaron/inject\"\n)\n\n\n\n\n\ntype ReturnHandler func(*Context, []reflect.Value)\n\nfunc canDeref(val reflect.Value) bool {\n\treturn val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr\n}\n\n\n\nfunc isByteSlice(val reflect.Value) bool {\n\treturn val.Kind() == reflect.Slice && val.Type().Elem().Kind() == reflect.Uint8\n}\n\nfunc defaultReturnHandler() ReturnHandler {\n\treturn func(ctx *Context, vals []reflect.Value) {\n\t\trv := ctx.GetVal(inject.InterfaceOf((*http.ResponseWriter)(nil)))\n\t\tresp := rv.Interface().(http.ResponseWriter)\n\t\tvar respVal reflect.Value\n\t\tif len(vals) > 1 && vals[0].Kind() == reflect.Int {\n\t\t\tresp.WriteHeader(int(vals[0].Int()))\n\t\t\trespVal = vals[1]\n\t\t} else if len(vals) > 0 {\n\t\t\trespVal = vals[0]\n\n\t\t\tif isError(respVal) {\n\t\t\t\terr := respVal.Interface().(error)\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx.internalServerError(ctx, err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t} else if canDeref(respVal) {\n\t\t\t\tif respVal.IsNil() {\n\t\t\t\t\treturn \n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif canDeref(respVal) {\n\t\t\trespVal = respVal.Elem()\n\t\t}\n\t\tif isByteSlice(respVal) {\n\t\t\t_, _ = resp.Write(respVal.Bytes())\n\t\t} else {\n\t\t\t_, _ = resp.Write([]byte(respVal.String()))\n\t\t}\n\t}\n}\n\nfunc isError(val reflect.Value) bool ", "output": "{\n\t_, ok := val.Interface().(error)\n\treturn ok\n}"} {"input": "package graphql\n\n\n\n\nimport (\n\t\"net/http\"\n\n\tmiddleware \"github.com/go-openapi/runtime/middleware\"\n\n\tmodels \"github.com/semi-technologies/weaviate/entities/models\"\n)\n\n\ntype GraphqlBatchHandlerFunc func(GraphqlBatchParams, *models.Principal) middleware.Responder\n\n\nfunc (fn GraphqlBatchHandlerFunc) Handle(params GraphqlBatchParams, principal *models.Principal) middleware.Responder {\n\treturn fn(params, principal)\n}\n\n\ntype GraphqlBatchHandler interface {\n\tHandle(GraphqlBatchParams, *models.Principal) middleware.Responder\n}\n\n\nfunc NewGraphqlBatch(ctx *middleware.Context, handler GraphqlBatchHandler) *GraphqlBatch {\n\treturn &GraphqlBatch{Context: ctx, Handler: handler}\n}\n\n\ntype GraphqlBatch struct {\n\tContext *middleware.Context\n\tHandler GraphqlBatchHandler\n}\n\n\n\nfunc (o *GraphqlBatch) ServeHTTP(rw http.ResponseWriter, r *http.Request) ", "output": "{\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\tr = rCtx\n\t}\n\tvar Params = NewGraphqlBatchParams()\n\n\tuprinc, aCtx, err := o.Context.Authorize(r, route)\n\tif err != nil {\n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\tif aCtx != nil {\n\t\tr = aCtx\n\t}\n\tvar principal *models.Principal\n\tif uprinc != nil {\n\t\tprincipal = uprinc.(*models.Principal) \n\t}\n\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params, principal) \n\n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}"} {"input": "package sflib\n\n\n\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\ntype APIStatusResponse struct {\n\tOK bool `json:\"ok\"`\n\tError string `json:\"error\"`\n}\n\n\nfunc (asr *APIStatusResponse) CheckAPIStatus() error {\n\tif (asr.OK != true) || (asr.Error != \"\") {\n\t\treturn APIFailureError{asr.Error}\n\t}\n\treturn nil\n}\n\n\ntype APIFailureError struct {\n\ts string\n}\n\n\n\n\ntype Stock struct {\n\tVenue string `json:\"venue\"`\n\tSymbol string `json:\"symbol\"`\n}\n\n\n\ntype Bid struct {\n\tPrice int `json:\"price\"`\n\tQuantity int `json:\"qty\"`\n\tIsBuy bool `json:\"isBuy\"`\n}\n\nfunc (afe APIFailureError) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"api returned error: %s\", afe.s)\n}"} {"input": "package opt\n\nimport (\n\t\"encoding/json\"\n\t\"reflect\"\n)\n\n\n\ntype DisableTypoToleranceOnAttributesOption struct {\n\tvalue []string\n}\n\n\nfunc DisableTypoToleranceOnAttributes(v ...string) *DisableTypoToleranceOnAttributesOption {\n\treturn &DisableTypoToleranceOnAttributesOption{v}\n}\n\n\n\n\n\n\nfunc (o DisableTypoToleranceOnAttributesOption) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(o.value)\n}\n\n\n\nfunc (o *DisableTypoToleranceOnAttributesOption) UnmarshalJSON(data []byte) error {\n\tif string(data) == \"null\" {\n\t\to.value = []string{}\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(data, &o.value)\n}\n\n\n\n\nfunc (o *DisableTypoToleranceOnAttributesOption) Equal(o2 *DisableTypoToleranceOnAttributesOption) bool {\n\tif o == nil {\n\t\treturn o2 == nil || reflect.DeepEqual(o2.value, []string{})\n\t}\n\tif o2 == nil {\n\t\treturn o == nil || reflect.DeepEqual(o.value, []string{})\n\t}\n\treturn reflect.DeepEqual(o.value, o2.value)\n}\n\n\n\n\nfunc DisableTypoToleranceOnAttributesEqual(o1, o2 *DisableTypoToleranceOnAttributesOption) bool {\n\treturn o1.Equal(o2)\n}\n\nfunc (o *DisableTypoToleranceOnAttributesOption) Get() []string ", "output": "{\n\tif o == nil {\n\t\treturn []string{}\n\t}\n\treturn o.value\n}"} {"input": "package upgrader\n\nimport (\n\t\"github.com/juju/juju/agent/tools\"\n\t\"github.com/juju/juju/version\"\n)\n\n\n\ntype UpgradeReadyError struct {\n\tAgentName string\n\tOldTools version.Binary\n\tNewTools version.Binary\n\tDataDir string\n}\n\n\n\n\n\n\nfunc (e *UpgradeReadyError) ChangeAgentTools() error {\n\tagentTools, err := tools.ChangeAgentTools(e.DataDir, e.AgentName, e.NewTools)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.Infof(\"upgraded from %v to %v (%q)\", e.OldTools, agentTools.Version, agentTools.URL)\n\treturn nil\n}\n\nfunc (e *UpgradeReadyError) Error() string ", "output": "{\n\treturn \"must restart: an agent upgrade is available\"\n}"} {"input": "package sendgrid\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"errors\"\n\t\"github.com/hashicorp/terraform/helper/schema\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\nfunc Provider() terraform.ResourceProvider {\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"api_key\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"SENDGRID_API_KEY\", nil),\n\t\t\t},\n\t\t},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"sendgrid_template\": resourceSendgridTemplate(),\n\t\t\t\"sendgrid_template_version\": resourceSendgridTemplateVersion(),\n\t\t},\n\n\t\tConfigureFunc: providerConfigure,\n\t}\n}\n\n\n\nfunc providerConfigure(d *schema.ResourceData) (interface{}, error) ", "output": "{\n\n\tconfig := Config{\n\t\tAPIKey: d.Get(\"api_key\").(string),\n\t}\n\n\tlog.Println(\"[INFO] Initializing Sendgrid client\")\n\tclient := config.Client()\n\tfmt.Println(\"Validate template\")\n\tok, err := client.Validate()\n\n\tif err != nil {\n\t\treturn client, err\n\t}\n\n\tif ok == false {\n\t\treturn client, errors.New(`No valid credential sources found for Sendgrid Provider. Please see https://terraform.io/docs/providers/sendgrid/index.html for more information on providing credentials for the Sendgrid Provider`)\n\t}\n\n\treturn client, nil\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\n\t\"gopkg.in/pivo.v2/ws\"\n)\n\nconst websocketChatUri = `/`\n\ntype websocket struct {\n\tconn *ws.Conn\n}\n\nfunc (ws *websocket) OnClose(why error) error {\n\tchat.hub.Leave(ws.conn)\n\treturn nil\n}\n\n\n\nfunc (ws *websocket) OnTextRead(text string) error {\n\tchat.pub <- ws.conn.TextMessage(formatMessage(ws.conn, text))\n\treturn nil\n}\n\nfunc (chat *Hub) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tconn := ws.DefaultConn()\n\tif err := conn.Upgrade(w, r, nil); err != nil {\n\t\tlog.Printf(\"websocket: %s: failed to upgrade: %s\",\n\t\t\tr.RemoteAddr, err)\n\t\treturn\n\t}\n\tgo conn.Sender()\n\tgo conn.Receiver(&websocket{conn})\n\tchat.sub <- conn\n}\n\nfunc init() {\n\thttp.Handle(websocketChatUri, chat)\n}\n\nfunc (ws *websocket) OnBinaryRead(data []byte) error ", "output": "{\n\treturn ErrProtocolViolation\n}"} {"input": "package buckettree\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TarantulaTechnology/fabric/core/ledger/testutil\"\n)\n\n\n\nfunc TestDataKeyGetBucketKey(t *testing.T) {\n\tconf = newConfig(26, 3, fnvHash)\n\tnewDataKey(\"chaincodeID1\", \"key1\").getBucketKey()\n\tnewDataKey(\"chaincodeID1\", \"key2\").getBucketKey()\n\tnewDataKey(\"chaincodeID2\", \"key1\").getBucketKey()\n\tnewDataKey(\"chaincodeID2\", \"key2\").getBucketKey()\n}\n\nfunc TestDataKey(t *testing.T) ", "output": "{\n\tconf = newConfig(26, 3, fnvHash)\n\tdataKey := newDataKey(\"chaincodeID\", \"key\")\n\tencodedBytes := dataKey.getEncodedBytes()\n\tdataKeyFromEncodedBytes := newDataKeyFromEncodedBytes(encodedBytes)\n\ttestutil.AssertEquals(t, dataKey, dataKeyFromEncodedBytes)\n}"} {"input": "package cli\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n)\n\n\nfunc CheckError(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n\n\nfunc CheckFatalError(err error) {\n\tif err != nil {\n\t\tCheckError(fmt.Errorf(\"Fatal error: %v\", err))\n\t}\n}\n\n\nfunc FileExists(path string) bool {\n\t_, err := os.Stat(path)\n\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\n\treturn false\n}\n\n\nfunc WritePid(pidfile string) {\n\tdirname := path.Dir(pidfile)\n\tif !FileExists(dirname) {\n\t\tCheckFatalError(fmt.Errorf(\"Directory \\\"%s\\\" doesn't exist\", dirname))\n\t}\n\n\tif FileExists(pidfile) {\n\t\tCheckFatalError(fmt.Errorf(\"File \\\"%s\\\" already exist\", pidfile))\n\t}\n\n\tpid := os.Getpid()\n\terr := ioutil.WriteFile(pidfile, []byte(strconv.Itoa(pid)), os.FileMode(0644))\n\tCheckFatalError(err)\n}\n\n\n\n\nfunc StopExecution(code int, pidfile string) ", "output": "{\n\tos.Remove(pidfile)\n\tos.Exit(code)\n}"} {"input": "package service\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\tupgrpc \"go-common/app/service/main/up/api/v1\"\n\t\"go-common/app/service/main/up/model/data\"\n\txtime \"go-common/library/time\"\n)\n\n\n\n\nfunc (s *Service) UpBaseStats(c context.Context, req *upgrpc.UpStatReq) (res *upgrpc.UpBaseStatReply, err error) ", "output": "{\n\tres = new(upgrpc.UpBaseStatReply)\n\tif req.Date.Time().IsZero() {\n\t\treq.Date = xtime.Time(time.Now().Add(-12*time.Hour).AddDate(0, 0, -1).Unix())\n\t}\n\tvar stat *data.UpBaseStat\n\tif stat, err = s.Data.BaseUpStat(c, req.Mid, req.Date.Time().Format(\"20060102\")); err != nil {\n\t\treturn\n\t}\n\tstat.CopyToReply(res)\n\treturn\n}"} {"input": "package diffsquares\n\n\nfunc SquareOfSums(n int) int {\n\ts := int(n)\n\ts *= s + 1\n\ts /= 2\n\treturn s * s\n}\n\n\n\n\n\nfunc Difference(n int) int {\n\treturn SquareOfSums(n) - SumOfSquares(n)\n}\n\nfunc SumOfSquares(n int) int ", "output": "{\n\ts := int(n)\n\ts = 2*s*s*s + 3*s*s + s\n\ts /= 6\n\treturn s\n\n}"} {"input": "package module\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n)\n\n\n\n\nfunc inode(path string) (uint64, error) ", "output": "{\n\tstat, err := os.Stat(path)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif st, ok := stat.Sys().(*syscall.Stat_t); ok {\n\t\treturn st.Ino, nil\n\t}\n\treturn 0, fmt.Errorf(\"could not determine file inode\")\n}"} {"input": "package gutil\n\n\nimport (\n\t\"bufio\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc NewReadForString(str string) *bufio.Reader {\n\treturn bufio.NewReader(strings.NewReader(str))\n}\n\n\n\n\n\nfunc ReadPath(path string) []string {\n\tif file, err := os.Open(path); CheckSucceed(err) {\n\t\tvar strs []string\n\t\tbuff := bufio.NewReader(file)\n\t\tfor {\n\t\t\tif str, ok := ReadLine(buff); ok {\n\t\t\t\tstrs = append(strs, str)\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\treturn strs\n\t}\n\treturn nil\n}\n\nfunc ReadLine(red *bufio.Reader) (string, bool) ", "output": "{\n\tline, _, err := red.ReadLine()\n\tif err != nil {\n\t\treturn \"\", false\n\t}\n\treturn string(line), true\n}"} {"input": "package container\n\nvar _ LogEntry = (*logEntry)(nil)\n\nfunc NewLogEntry(container, line string) logEntry {\n\treturn logEntry{\n\t\tcontainer: container,\n\t\tline: line,\n\t}\n}\n\ntype logEntry struct {\n\tline string\n\tcontainer string\n}\n\nfunc (l logEntry) Line() string {\n\treturn l.line\n}\n\n\n\nfunc (l logEntry) Container() string ", "output": "{\n\treturn l.container\n}"} {"input": "package ethutil\n\nimport \"fmt\"\n\ntype StorageSize float64\n\n\n\nfunc (self StorageSize) String() string ", "output": "{\n\tif self > 1000000 {\n\t\treturn fmt.Sprintf(\"%.2f mB\", self/1000000)\n\t} else if self > 1000 {\n\t\treturn fmt.Sprintf(\"%.2f kB\", self/1000)\n\t} else {\n\t\treturn fmt.Sprintf(\"%.2f B\", self)\n\t}\n}"} {"input": "package github\n\nimport (\n . \"github.com/ErintLabs/trellohub/genapi\"\n \"log\"\n)\n\ntype Label struct {\n Name string `json:\"name\"`\n}\n\ntype GitUser struct {\n Name string `json:\"login\"`\n}\n\nfunc (issue *Issue) SetLabels(lbls []Label) {\n lst := make([]string, len(lbls))\n for i, v := range lbls {\n lst[i] = v.Name\n }\n issue.Labels.SetNameable(lst)\n}\n\nfunc (issue *Issue) SetMembers(mbmrs []GitUser) {\n lst := make([]string, len(mbmrs))\n for i, v := range mbmrs {\n lst[i] = v.Name\n }\n issue.Members.SetNameable(lst)\n}\n\n\n\n\nfunc (issue *Issue) AddLabel(label string) {\n log.Printf(\"Adding label %s to %s\", label, issue.String())\n lbls := [...]string { label }\n GenPOSTJSON(issue.github, issue.ApiURL() + \"/labels\", nil, &lbls)\n}\n\n\nfunc (issue *Issue) DelLabel(label string) {\n log.Printf(\"Removing label %s from %s\", label, issue.String())\n GenDEL(issue.github, issue.ApiURL() + \"/labels/\" + label) \n}\n\n\ntype userAssignRequest struct {\n Assigs []string `json:\"assignees\"`\n}\n\n\n\n\nfunc (issue *Issue) DelUser(user string) {\n log.Printf(\"Removing user %s from %s\", user, issue.String())\n payload := userAssignRequest{ []string{ user } }\n GenDELJSON(issue.github, issue.ApiURL() + \"/assignees\", &payload)\n}\n\nfunc (issue *Issue) AddUser(user string) ", "output": "{\n log.Printf(\"Adding user %s to %s\", user, issue.String())\n payload := userAssignRequest{ []string{ user } }\n GenPOSTJSON(issue.github, issue.ApiURL() + \"/assignees\", nil, &payload)\n}"} {"input": "package db\n\nimport (\n\t\"database/sql\"\n\t_ \"github.com/go-sql-driver/mysql\" \n)\n\n\n\ntype DB struct {\n\tDriverName string\n\tDriverSourceName string\n\tDataBase *sql.DB\n}\n\n\nfunc (this *DB) Open() (err error) {\n\tthis.DataBase, err = sql.Open(this.DriverName, this.DriverSourceName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\nfunc (this *DB) Close() {\n\tthis.DataBase.Close()\n}\n\n\n\nfunc (this *DB) InsertData(sql string, args ...interface{}) error {\n\tstmt, err := this.DataBase.Prepare(sql)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\t_, err = stmt.Exec(args...)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc (this *DB) QueryData(sql string, args ...interface{}) *sql.Row {\n\treturn this.DataBase.QueryRow(sql, args...)\n\n}\n\nfunc NewDB(drivername, driversourcename string) *DB ", "output": "{\n\treturn &DB{\n\t\tDriverName: drivername,\n\t\tDriverSourceName: driversourcename,\n\t}\n}"} {"input": "package protocol\n\nvar (\n\tVersion13HelloMagic uint32 = 0x9F79BC40\n)\n\ntype Version13HelloMessage struct {\n\tDeviceName string \n\tClientName string \n\tClientVersion string \n}\n\nfunc (m Version13HelloMessage) Magic() uint32 {\n\treturn Version13HelloMagic\n}\n\n\n\nfunc (m Version13HelloMessage) Marshal() ([]byte, error) ", "output": "{\n\treturn m.MarshalXDR()\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\n\n\n\ntype MsgPong struct {\n\tNonce uint64\n}\n\n\n\n\n\n\n\nfunc (msg *MsgPong) BtcEncode(w io.Writer, pver uint32) error {\n\tif pver <= BIP0031Version {\n\t\tstr := fmt.Sprintf(\"pong message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgPong.BtcEncode\", str)\n\t}\n\n\treturn writeElement(w, msg.Nonce)\n}\n\n\n\nfunc (msg *MsgPong) Command() string {\n\treturn CmdPong\n}\n\n\n\nfunc (msg *MsgPong) MaxPayloadLength(pver uint32) uint32 {\n\tplen := uint32(0)\n\tif pver > BIP0031Version {\n\t\tplen += 8\n\t}\n\n\treturn plen\n}\n\n\n\nfunc NewMsgPong(nonce uint64) *MsgPong {\n\treturn &MsgPong{\n\t\tNonce: nonce,\n\t}\n}\n\nfunc (msg *MsgPong) BtcDecode(r io.Reader, pver uint32) error ", "output": "{\n\tif pver <= BIP0031Version {\n\t\tstr := fmt.Sprintf(\"pong message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgPong.BtcDecode\", str)\n\t}\n\n\treturn readElement(r, &msg.Nonce)\n}"} {"input": "package model\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestConsumerMessage(t *testing.T) ", "output": "{\n\tt.SkipNow()\n}"} {"input": "package events\n\nimport (\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/gravitational/teleport/lib/session\"\n)\n\n\n\ntype DiscardAuditLog struct {\n}\n\nfunc (d *DiscardAuditLog) Close() error {\n\treturn nil\n}\n\nfunc (d *DiscardAuditLog) EmitAuditEvent(eventType string, fields EventFields) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionChunk(namespace string, sid session.ID, reader io.Reader) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionSlice(SessionSlice) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\nfunc (d *DiscardAuditLog) GetSessionEvents(namespace string, sid session.ID, after int) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchEvents(fromUTC, toUTC time.Time, query string) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchSessionEvents(fromUTC time.Time, toUTC time.Time) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\n\n\n\n\ntype discardSessionLogger struct {\n}\n\nfunc (d *discardSessionLogger) LogEvent(fields EventFields) {\n\treturn\n}\n\n\n\nfunc (d *discardSessionLogger) Finalize() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) WriteChunk(chunk *SessionChunk) (written int, err error) {\n\treturn 0, nil\n}\n\nfunc (d *discardSessionLogger) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package limiter\n\ntype SimpleLimiter chan struct{}\n\nfunc (l SimpleLimiter) Enter() { l <- struct{}{} }\n\n\nfunc NewSimpleLimiter(l int) SimpleLimiter {\n\treturn make(chan struct{}, l)\n}\n\nfunc (l SimpleLimiter) Leave() ", "output": "{ <-l }"} {"input": "package dosingdecision\n\nimport (\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tRecommendedBasalDurationMaximum = 86400000\n\tRecommendedBasalDurationMinimum = 0\n\tRecommendedBasalRateMaximum = 100\n\tRecommendedBasalRateMinimum = 0\n)\n\ntype RecommendedBasal struct {\n\tRate *float64 `json:\"rate,omitempty\" bson:\"rate,omitempty\"`\n\tDuration *int `json:\"duration,omitempty\" bson:\"duration,omitempty\"`\n}\n\nfunc ParseRecommendedBasal(parser structure.ObjectParser) *RecommendedBasal {\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewRecommendedBasal()\n\tparser.Parse(datum)\n\treturn datum\n}\n\nfunc NewRecommendedBasal() *RecommendedBasal {\n\treturn &RecommendedBasal{}\n}\n\n\n\nfunc (r *RecommendedBasal) Validate(validator structure.Validator) {\n\tvalidator.Float64(\"rate\", r.Rate).Exists().InRange(RecommendedBasalRateMinimum, RecommendedBasalRateMaximum)\n\tvalidator.Int(\"duration\", r.Duration).InRange(RecommendedBasalDurationMinimum, RecommendedBasalDurationMaximum)\n}\n\nfunc (r *RecommendedBasal) Parse(parser structure.ObjectParser) ", "output": "{\n\tr.Rate = parser.Float64(\"rate\")\n\tr.Duration = parser.Int(\"duration\")\n}"} {"input": "package render\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n)\n\n\n\n\n\n\nfunc Error(c *gin.Context, msg string) ", "output": "{\n\tString(c, msg, 400)\n}"} {"input": "package couchdb\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\tkivik \"github.com/go-kivik/kivik/v3\"\n)\n\n\nfunc encodeKey(i interface{}) (string, error) {\n\tif raw, ok := i.(json.RawMessage); ok {\n\t\treturn string(raw), nil\n\t}\n\traw, err := json.Marshal(i)\n\tif err != nil {\n\t\terr = &kivik.Error{HTTPStatus: http.StatusBadRequest, Err: err}\n\t}\n\treturn string(raw), err\n}\n\nvar jsonKeys = []string{\"endkey\", \"end_key\", \"key\", \"startkey\", \"start_key\", \"keys\", \"doc_ids\"}\n\n\n\nfunc encodeKeys(opts map[string]interface{}) error ", "output": "{\n\tfor _, key := range jsonKeys {\n\t\tif v, ok := opts[key]; ok {\n\t\t\tnew, err := encodeKey(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\topts[key] = new\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package model\n\n\ntype Weight struct {\n\ttime int\n\trequirements map[*Reward]int\n}\n\n\nfunc (weight *Weight) Time() int {\n\treturn weight.time\n}\n\n\nfunc (weight *Weight) Requirements() map[*Reward]int {\n\treturn weight.requirements\n}\n\n\nfunc (weight *Weight) AddRequirement(reward *Reward, quantity int) {\n\tweight.requirements[reward] = quantity\n}\n\n\nfunc CreateWeight(time int) *Weight {\n\tweight := new(Weight)\n\tweight.time = time\n\tweight.requirements = make(map[*Reward]int)\n\treturn weight\n}\n\n\ntype ByTime []*Weight\n\n\nfunc (a ByTime) Len() int {\n\treturn len(a)\n}\n\n\nfunc (a ByTime) Swap(i, j int) {\n\ta[i], a[j] = a[j], a[i]\n}\n\n\n\n\nfunc (a ByTime) Less(i, j int) bool ", "output": "{\n\treturn a[i].Time() < a[j].Time()\n}"} {"input": "package tests\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n)\n\nfunc TestTransactions(t *testing.T) {\n\terr := RunTransactionTests(filepath.Join(transactionTestDir, \"ttTransactionTest.json\"), TransSkipTests)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestWrongRLPTransactions(t *testing.T) {\n\terr := RunTransactionTests(filepath.Join(transactionTestDir, \"ttWrongRLPTransaction.json\"), TransSkipTests)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\n\nfunc Test10MBtx(t *testing.T) ", "output": "{\n\terr := RunTransactionTests(filepath.Join(transactionTestDir, \"tt10mbDataField.json\"), TransSkipTests)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package entrapped\n\nimport (\n\t\"github.com/SKatiyar/entrapped/Godeps/_workspace/src/github.com/julienschmidt/httprouter\"\n\t\"net/http\"\n)\n\nconst (\n\tsize int = 7\n\tnumBombs int = 10\n\tlifes int = 5\n\tnumBonusLifes int = 2\n)\n\n\n\nfunc addPlayer(rw http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tid := params.ByName(\"id\")\n\n\tws, wsErr := upgrader.Upgrade(rw, req, nil)\n\tif wsErr != nil {\n\t\tlogger.Println(wsErr)\n\t\treturn\n\t}\n\n\ttrap := makeTrap(size, numBombs, numBonusLifes, lifes)\n\n\tch.add(&trooper{id, trap, ws, make(chan []byte, 512)})\n}\n\nfunc home(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\trw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\thttp.ServeFile(rw, req, \"client/dist/index.html\")\n}\n\nfunc Start(addr string) ", "output": "{\n\tif len(addr) == 0 {\n\t\taddr = \":7000\"\n\t}\n\n\tgo ch.run()\n\n\trouter := httprouter.New()\n\n\trouter.GET(\"/\", home)\n\trouter.ServeFiles(\"/statics/*filepath\", http.Dir(\"client/dist/statics\"))\n\n\trouter.GET(\"/players/:id\", addPlayer)\n\n\tlistenErr := http.ListenAndServe(addr, router)\n\tif listenErr != nil {\n\t\tlogger.Println(listenErr)\n\t\treturn\n\t}\n}"} {"input": "package travel\n\nimport (\n\t\"os\"\n\n\t\"github.com/akerl/speculate/v2/creds\"\n)\n\nfunc clearEnvironment() error {\n\tfor varName := range creds.Translations[\"envvar\"] {\n\t\tlogger.InfoMsgf(\"Unsetting env var: %s\", varName)\n\t\terr := os.Unsetenv(varName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc stringInSlice(list []string, key string) bool {\n\tfor _, item := range list {\n\t\tif item == key {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\ntype attrFunc func(Path) string\n\nfunc uniquePathAttributes(paths []Path, af attrFunc) []string {\n\ttmpMap := map[string]bool{}\n\tfor _, item := range paths {\n\t\tattr := af(item)\n\t\ttmpMap[attr] = true\n\t}\n\ttmpList := []string{}\n\tfor item := range tmpMap {\n\t\ttmpList = append(tmpList, item)\n\t}\n\treturn tmpList\n}\n\nfunc filterPathsByAttribute(paths []Path, match string, af attrFunc) []Path {\n\tfilteredPaths := []Path{}\n\tfor _, item := range paths {\n\t\tif af(item) == match {\n\t\t\tfilteredPaths = append(filteredPaths, item)\n\t\t}\n\t}\n\treturn filteredPaths\n}\n\nfunc sliceUnion(a []string, b []string) []string ", "output": "{\n\tvar res []string\n\tfor _, item := range a {\n\t\tif stringInSlice(b, item) {\n\t\t\tres = append(res, item)\n\t\t}\n\t}\n\treturn res\n}"} {"input": "package testing\n\nimport (\n\t\"github.com/markdaws/gohome/pkg/cmd\"\n\t\"github.com/markdaws/gohome/pkg/gohome\"\n)\n\ntype extension struct {\n\tgohome.NullExtension\n}\n\n\n\nfunc (e *extension) BuilderForDevice(sys *gohome.System, d *gohome.Device) cmd.Builder {\n\tswitch d.ModelNumber {\n\tcase \"testing.hardware\":\n\t\treturn &cmdBuilder{ModelNumber: d.ModelNumber, Device: d}\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (e *extension) NetworkForDevice(sys *gohome.System, d *gohome.Device) gohome.Network {\n\treturn nil\n}\n\nfunc (e *extension) EventsForDevice(sys *gohome.System, d *gohome.Device) *gohome.ExtEvents {\n\tswitch d.ModelNumber {\n\tcase \"testing.hardware\":\n\t\tevts := &gohome.ExtEvents{}\n\t\tevts.Producer = &producer{\n\t\t\tDevice: d,\n\t\t\tSystem: sys,\n\t\t}\n\t\tevts.Consumer = &consumer{\n\t\t\tDevice: d,\n\t\t\tSystem: sys,\n\t\t}\n\t\treturn evts\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (e *extension) Discovery(sys *gohome.System) gohome.Discovery {\n\treturn &discovery{}\n}\n\nfunc NewExtension() *extension {\n\treturn &extension{}\n}\n\nfunc (e *extension) Name() string ", "output": "{\n\treturn \"testing\"\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n)\n\ntype BuiltInClass struct {\n\tname Instance\n\tsupers []Class\n\tslots []Instance\n}\n\nfunc NewBuiltInClass(name string, super Class, slots ...string) Class {\n\tslotNames := []Instance{}\n\tfor _, slot := range slots {\n\t\tslotNames = append(slotNames, NewSymbol(slot))\n\t}\n\treturn BuiltInClass{NewSymbol(name), []Class{super}, slotNames}\n}\n\nfunc (p BuiltInClass) Supers() []Class {\n\treturn p.supers\n}\n\nfunc (p BuiltInClass) Slots() []Instance {\n\treturn p.slots\n}\n\nfunc (p BuiltInClass) Initform(arg Instance) (v Instance, ok bool) {\n\treturn nil, false\n}\n\nfunc (p BuiltInClass) Initarg(arg Instance) (v Instance, ok bool) {\n\treturn arg, true\n}\n\nfunc (BuiltInClass) Class() Class {\n\treturn BuiltInClassClass\n}\n\n\n\nfunc (p BuiltInClass) String() string ", "output": "{\n\treturn fmt.Sprint(p.name)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/robfig/cron\"\n)\n\ntype Sync struct{}\n\nfunc (s *Sync) Help() string {\n\treturn \"glr sync Help\"\n}\n\n\n\nfunc (s *Sync) Synopsis() string {\n\treturn \"Synchronize local git repository with remote at once\"\n}\n\n\ntype status struct {\n\tc *cron.Cron\n\trepositories []string\n\tschedules []string\n}\n\nvar sharedStatus *status = newStatus()\n\nfunc newStatus() *status {\n\treturn &status{\n\t\tc: cron.New(),\n\t}\n}\n\n\nfunc GetStatus() *status {\n\treturn sharedStatus\n}\n\ntype StatusStart struct{}\n\nfunc (s *StatusStart) Help() string {\n\treturn \"glr status start Help\"\n}\n\nfunc (s *StatusStart) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.AddFunc(\"@hourly\", func() {\n\t\tSyncRepository()\n\t})\n\tfmt.Println(\"set job schedule\")\n\tstatus.c.Start()\n\n\treturn 0\n}\n\nfunc (s *StatusStart) Synopsis() string {\n\treturn \"Synchronize local git repository with remote\"\n}\n\ntype StatusStop struct{}\n\nfunc (s *StatusStop) Help() string {\n\treturn \"glr status stop Help\"\n}\n\nfunc (s *StatusStop) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.Stop()\n\tfmt.Println(\"stop job scheduler\")\n\n\treturn 0\n}\n\nfunc (s *StatusStop) Synopsis() string {\n\treturn \"Stop cron scheduler\"\n}\n\nfunc (s *Sync) Run(args []string) int ", "output": "{\n\t_, err := SyncRepository()\n\n\tif err != nil {\n\t\treturn 1\n\t}\n\n\treturn 0\n}"} {"input": "package storageos\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/storageos/go-api/types\"\n)\n\nvar (\n\tHealthAPIPrefix = \"health\"\n)\n\n\nfunc (c *Client) CPHealth(ctx context.Context, hostname string) (*types.CPHealthStatus, error) {\n\n\turl := fmt.Sprintf(\"http://%s:%s/v1/%s\", hostname, DefaultPort, HealthAPIPrefix)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"User-Agent\", userAgent)\n\tif c.username != \"\" && c.secret != \"\" {\n\t\treq.SetBasicAuth(c.username, c.secret)\n\t}\n\n\tresp, err := c.HTTPClient.Do(req.WithContext(ctx))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar status *types.CPHealthStatus\n\tif err := json.NewDecoder(resp.Body).Decode(&status); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn status, nil\n}\n\n\n\n\nfunc (c *Client) DPHealth(ctx context.Context, hostname string) (*types.DPHealthStatus, error) ", "output": "{\n\n\turl := fmt.Sprintf(\"http://%s:%s/v1/%s\", hostname, DataplaneHealthPort, HealthAPIPrefix)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"User-Agent\", userAgent)\n\tif c.username != \"\" && c.secret != \"\" {\n\t\treq.SetBasicAuth(c.username, c.secret)\n\t}\n\n\tresp, err := c.HTTPClient.Do(req.WithContext(ctx))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar status *types.DPHealthStatus\n\tif err := json.NewDecoder(resp.Body).Decode(&status); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn status, nil\n}"} {"input": "package api\n\nimport (\n\t\"io\"\n\n\t\"github.com/dghubble/sling\"\n)\n\n\n\nconst SdkDebugKey = \"SdkDebug\"\n\n\ntype Client struct {\n\tsling.Doer\n\t*sling.Sling\n}\n\ntype ApiKeyClientOption func(*ApiKeyClientOptions)\ntype ApiKeyClientOptions struct {\n\tInsecureSkipVerify bool\n\n\tInsecureUsePlaintext bool\n\n\tEnableRoot bool\n\n\tProduct string\n\n\tDebugWriter io.Writer\n}\n\nvar DefaultApiKeyClientOptions = ApiKeyClientOptions{\n\tInsecureSkipVerify: false,\n\tInsecureUsePlaintext: false,\n\tEnableRoot: false,\n}\n\n\n\nvar InsecureNoSSLVerification ApiKeyClientOption\n\n\n\nvar InsecureUsePlaintext ApiKeyClientOption\n\n\nvar EnableRoot ApiKeyClientOption\n\n\nfunc UserAgent(product string) ApiKeyClientOption {\n\treturn func(o *ApiKeyClientOptions) {\n\t\to.Product = product\n\t}\n}\n\n\n\n\n\nfunc init() {\n\tInsecureNoSSLVerification = func(o *ApiKeyClientOptions) {\n\t\to.InsecureSkipVerify = true\n\t}\n\n\tInsecureUsePlaintext = func(o *ApiKeyClientOptions) {\n\t\to.InsecureUsePlaintext = true\n\t}\n\n\tEnableRoot = func(o *ApiKeyClientOptions) {\n\t\to.EnableRoot = true\n\t}\n}\n\nfunc DebugLogRequests(w io.Writer) ApiKeyClientOption ", "output": "{\n\treturn func(o *ApiKeyClientOptions) {\n\t\to.DebugWriter = w\n\t}\n}"} {"input": "package memcachep\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n)\n\ntype Stats map[string]fmt.Stringer\n\n\ntype FuncStat struct {\n\tCallable func() string\n}\n\nfunc (f *FuncStat) String() string {\n\treturn f.Callable()\n}\n\n\ntype StaticStat struct {\n\tValue string\n}\n\nfunc (s *StaticStat) String() string {\n\treturn s.Value\n}\n\n\ntype CounterStat struct {\n\tCount int\n\tcalculations chan int\n}\n\nfunc (c *CounterStat) Increment(num int) {\n\tc.calculations <- num\n}\n\nfunc (c *CounterStat) SetCount(num int) {\n\tc.Count = num\n}\n\nfunc (c *CounterStat) Decrement(num int) {\n\tc.calculations <- -num\n}\n\nfunc (c *CounterStat) String() string {\n\treturn strconv.Itoa(c.Count)\n}\n\nfunc (c *CounterStat) work() {\n\tfor num := range c.calculations {\n\t\tc.Count = c.Count + num\n\t}\n}\n\nfunc NewCounterStat() *CounterStat {\n\tc := &CounterStat{}\n\tc.calculations = make(chan int, 100)\n\tgo c.work()\n\treturn c\n}\n\n\n\nfunc NewStats() Stats ", "output": "{\n\ts := make(Stats)\n\ts[\"pid\"] = &StaticStat{strconv.Itoa(os.Getpid())}\n\ts[\"version\"] = &StaticStat{VERSION}\n\ts[\"golang\"] = &StaticStat{runtime.Version()}\n\ts[\"goroutines\"] = &FuncStat{func() string { return strconv.Itoa(runtime.NumGoroutine()) }}\n\ts[\"cpu_num\"] = &StaticStat{strconv.Itoa(runtime.NumCPU())}\n\ts[\"total_connections\"] = NewCounterStat()\n\ts[\"curr_connections\"] = NewCounterStat()\n\ts[\"cmd_get\"] = NewCounterStat()\n\treturn s\n}"} {"input": "package http\n\nimport (\n\t\"context\"\n\t\"github.com/go-kit/kit/endpoint\"\n\t\"github.com/kryptn/modulario/proto\"\n)\n\nfunc MakeLoginEndpoint(svc HttpService) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\treq := request.(proto.LoginRequest)\n\t\tresp, err := svc.Login(ctx, req)\n\t\treturn resp, err\n\t}\n}\n\nfunc MakeVisitPostEndpoint(svc HttpService) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\treq := request.(proto.VisitPostRequest)\n\t\treturn svc.VisitPost(ctx, req)\n\t}\n}\n\n\n\nfunc MakeCreatePostEndpoint(svc HttpService) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\treq := request.(proto.CreatePostRequest)\n\t\treturn svc.CreatePost(ctx, req)\n\t}\n}\n\nfunc MakeViewPostEndpoint(svc HttpService) endpoint.Endpoint ", "output": "{\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\treq := request.(proto.ViewPostRequest)\n\t\treturn svc.ViewPost(ctx, req)\n\t}\n}"} {"input": "package intsort\n\ntype Uints []uint\n\nfunc (s Uints) Len() int {\n\treturn len(s)\n}\n\nfunc (s Uints) Less(i int, j int) bool {\n\treturn s[i] < s[j]\n}\n\n\n\nfunc (s Uints) Swap(i int, j int) ", "output": "{\n\ts[i], s[j] = s[j], s[i]\n}"} {"input": "package bunyan\n\nimport \"fmt\"\n\n\ntype Logger struct {\n\tsink Sink\n\trecord Record\n}\n\n\nfunc NewLogger(target Sink) *Logger {\n\treturn &Logger{target, NewRecord()}\n}\n\n\n\nfunc (l *Logger) Write(record Record) error {\n\trecord.TemplateMerge(l.record)\n\treturn l.sink.Write(record)\n}\n\n\n\nfunc (l *Logger) Include(info Info) Log {\n\treturn NewLogger(InfoSink(l, info))\n}\n\n\n\nfunc (l *Logger) Record(key string, value interface{}) Log {\n\tbuilder := NewLogger(l)\n\tbuilder.record[key] = value\n\treturn builder\n}\n\n\n\nfunc (l *Logger) Recordf(key, value string, args ...interface{}) Log {\n\treturn l.Record(key, fmt.Sprintf(value, args...))\n}\n\n\n\nfunc (l *Logger) Child() Log {\n\treturn NewLogger(l)\n}\n\nfunc (l *Logger) Tracef(msg string, args ...interface{}) { l.send(TRACE, msg, args...) }\nfunc (l *Logger) Debugf(msg string, args ...interface{}) { l.send(DEBUG, msg, args...) }\nfunc (l *Logger) Infof(msg string, args ...interface{}) { l.send(INFO, msg, args...) }\nfunc (l *Logger) Warnf(msg string, args ...interface{}) { l.send(WARN, msg, args...) }\nfunc (l *Logger) Errorf(msg string, args ...interface{}) { l.send(ERROR, msg, args...) }\n\n\nfunc (l *Logger) send(level Level, msg string, args ...interface{}) {\n\trecord := NewRecord()\n\trecord.SetMessagef(level, msg, args...)\n\te := l.Write(record)\n\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc (l *Logger) Fatalf(msg string, args ...interface{}) ", "output": "{ l.send(FATAL, msg, args...) }"} {"input": "package armcosmos_test\n\nimport (\n\t\"context\"\n\t\"log\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azcore/to\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cosmos/armcosmos\"\n)\n\n\n\n\n\nfunc ExampleCollectionPartitionClient_ListUsages() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armcosmos.NewCollectionPartitionClient(\"\", cred, nil)\n\tres, err := client.ListUsages(ctx,\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t&armcosmos.CollectionPartitionClientListUsagesOptions{Filter: to.StringPtr(\"\")})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Response result: %#v\\n\", res.CollectionPartitionClientListUsagesResult)\n}\n\nfunc ExampleCollectionPartitionClient_ListMetrics() ", "output": "{\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armcosmos.NewCollectionPartitionClient(\"\", cred, nil)\n\tres, err := client.ListMetrics(ctx,\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Response result: %#v\\n\", res.CollectionPartitionClientListMetricsResult)\n}"} {"input": "package keyseq\n\nimport (\n\t\"testing\"\n)\n\nfunc checkTrieNode(t *testing.T, n Node, k Key, value int) {\n\tif n == nil {\n\t\tt.Fatal(\"TrieNode is null\")\n\t}\n\tif l := n.Label(); l != k {\n\t\tt.Errorf(\"TrieNode.Label() expected:'%c' actual:'%c'\", k, l)\n\t}\n\tif v := n.Value().(int); v != value {\n\t\tt.Errorf(\"TrieNode.Value() expected:%d actual:%d\", value, v)\n\t}\n}\n\n\n\nfunc TestNotFound(t *testing.T) {\n\ttrie := NewTrie()\n\tif trie.Get(Key{999, 999, 'a'}) != nil {\n\t\tt.Errorf(\"found 'not_exist' in empty trie\")\n\t}\n}\n\nfunc TestTrie(t *testing.T) ", "output": "{\n\ttrie := NewTrie()\n\tfor i := 1; i <= 5; i++ {\n\t\ttrie.Put(KeyList{Key{0, 0, rune(i)}}, 111*i)\n\t}\n\n\tnodes := Children(trie.Root())\n\tfor i := 0; i < 5; i++ {\n\t\tcheckTrieNode(t, nodes[i], Key{0, 0, rune(i + 1)}, 111*(i+1))\n\t}\n\n\tif s := trie.Size(); s != 5 {\n\t\tt.Errorf(\"trie.Size() returns not 5: %d\", s)\n\t}\n}"} {"input": "package stopwatch\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestSyncStopwatch_Mark(t *testing.T) ", "output": "{\n\ts := NewSync()\n\ts.Start()\n\ttime.Sleep(time.Millisecond * 100)\n\ts.Mark(\"sleep1\")\n\ttime.Sleep(time.Millisecond * 100)\n\ts.Mark(\"sleep2\")\n\ts.Stop()\n\tprintln(s.Report())\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype CreateBootVolumeRequest struct {\n\n\tCreateBootVolumeDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateBootVolumeRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateBootVolumeRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\n\n\n\ntype CreateBootVolumeResponse struct {\n\n\tRawResponse *http.Response\n\n\tBootVolume `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateBootVolumeResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateBootVolumeResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateBootVolumeRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package realtime\n\nimport (\n\t\"io\"\n)\n\n\n\ntype Reader interface {\n\tio.Reader\n\trealtime()\n}\n\n\n\n\nfunc NewReader(input io.Reader, rthandler func(Message)) Reader {\n\tif rthandler == nil {\n\t\treturn &discardReader{input}\n\t}\n\treturn &reader{input, rthandler}\n}\n\n\n\n\n\n\n\ntype reader struct {\n\tinput io.Reader\n\thandler func(Message)\n}\n\nfunc (r *reader) realtime() {}\n\n\ntype discardReader struct {\n\tinput io.Reader\n}\n\nfunc (r *discardReader) realtime() {}\n\nfunc (r *discardReader) Read(target []byte) (n int, err error) {\n\tvar bf []byte\n\n\tfor {\n\t\tif n == len(target) {\n\t\t\treturn\n\n\t\t}\n\t\tbf = make([]byte, 1)\n\n\t\t_, err = r.input.Read(bf)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif bf[0] < 0xF8 {\n\t\t\ttarget[n] = bf[0]\n\t\t\tn++\n\t\t\tcontinue\n\t\t}\n\n\n\t}\n\n}\n\nfunc dispatch(b byte) Message {\n\tm := msg(b)\n\tif _, has := msg2String[m]; !has {\n\t\treturn nil\n\t}\n\treturn m\n}\n\nfunc (r *reader) Read(target []byte) (n int, err error) ", "output": "{\n\tvar bf = make([]byte, 1)\n\n\tfor {\n\t\tif n == len(target) {\n\t\t\treturn\n\n\t\t}\n\n\t\t_, err = r.input.Read(bf)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif bf[0] < 0xF8 {\n\t\t\ttarget[n] = bf[0]\n\t\t\tn++\n\t\t\tcontinue\n\t\t}\n\n\t\tif m := dispatch(bf[0]); m != nil {\n\t\t\tr.handler(m)\n\t\t}\n\t}\n}"} {"input": "package sml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/sml\"\n)\n\n\n\nfunc TestCT_TextFieldMarshalUnmarshal(t *testing.T) {\n\tv := sml.NewCT_TextField()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := sml.NewCT_TextField()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestCT_TextFieldConstructor(t *testing.T) ", "output": "{\n\tv := sml.NewCT_TextField()\n\tif v == nil {\n\t\tt.Errorf(\"sml.NewCT_TextField must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed sml.CT_TextField should validate: %s\", err)\n\t}\n}"} {"input": "package common\n\nimport (\n\t\"encoding/json\"\n\t\"my/util\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"sso/user\"\n)\n\n\nfunc Myinfo(res http.ResponseWriter, req *http.Request) {\n\n\tcallback := req.FormValue(\"cb\")\n\tvar sweet map[string]interface{} = make(map[string]interface{})\n\tsweet[\"state\"] = 0\n\treg := regexp.MustCompile(`\"|'|<|\\s`)\n\tcallback = reg.ReplaceAllString(callback, \"\")\n\tif len(callback) > 10 {\n\t\tall_info, _ := json.Marshal(sweet)\n\t\tutil.WriteJSONP(res, callback+\"(\"+string(all_info)+\")\")\n\t\treturn\n\t}\n\tstat, userA := validateUserInfo(req)\n\n\tif stat == false {\n\t\tsweet[\"state\"] = 1\n\t\tall_info, _ := json.Marshal(sweet)\n\t\tutil.WriteJSONP(res, callback+\"(\"+string(all_info)+\")\")\n\t\treturn\n\t}\n\tsweet[\"u\"] = *userA\n\tsweet[\"state\"] = 2\n\tall_info, _ := json.Marshal(sweet)\n\tif callback == \"null\" {\n\t\tutil.WriteJSONP(res, string(all_info))\n\t\treturn\n\t}\n\n\tutil.WriteJSONP(res, callback+\"(\"+string(all_info)+\")\")\n\treturn\n}\n\n\n\n\nfunc validateUserInfo(req *http.Request) (bool, *user.User) ", "output": "{\n\tcookie := req.URL.Query().Get(\"token\")\n\n\tif cookie == \"\" {\n\t\treturn false, nil\n\t}\n\tuserA := byToken(cookie)\n\tif userA == nil {\n\t\treturn false, nil\n\t}\n\tif userA.Id == 0 {\n\t\treturn false, nil\n\t}\n\n\treturn true, userA\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetAutonomousPatchRequest struct {\n\n\tAutonomousPatchId *string `mandatory:\"true\" contributesTo:\"path\" name:\"autonomousPatchId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetAutonomousPatchRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request GetAutonomousPatchRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request GetAutonomousPatchRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetAutonomousPatchRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetAutonomousPatchResponse struct {\n\n\tRawResponse *http.Response\n\n\tAutonomousPatch `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetAutonomousPatchResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response GetAutonomousPatchResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package augeas\n\n\n\nimport \"C\"\nimport (\n\t\"fmt\"\n)\n\n\n\n\ntype ErrorCode int\n\n\nconst (\n\tCouldNotInitialize ErrorCode = -2\n\tNoMatch = -1\n\n\tNoError = 0\n\n\tENOMEM\n\n\tEINTERNAL\n\n\tEPATHX\n\n\tENOMATCH\n\n\tEMMATCH\n\n\tESYNTAX\n\n\tENOLENS\n\n\tEMXFM\n\n\tENOSPAN\n\n\tEMVDESC\n\n\tECMDRUN\n\n\tEBADARG\n)\n\n\ntype Error struct {\n\tCode ErrorCode\n\n\tMessage string\n\n\tMinorMessage string\n\n\tDetails string\n}\n\nfunc (err Error) Error() string {\n\treturn fmt.Sprintf(\"Message: %s - Minor message: %s - Details: %s\",\n\t\terr.Message, err.MinorMessage, err.Details)\n}\n\nfunc (a Augeas) error() error {\n\tcode := a.errorCode()\n\tif code == NoError {\n\t\treturn nil\n\t}\n\n\treturn Error{code, a.errorMessage(), a.errorMinorMessage(), a.errorDetails()}\n}\n\nfunc (a Augeas) errorCode() ErrorCode {\n\treturn ErrorCode(C.aug_error(a.handle))\n}\n\nfunc (a Augeas) errorMessage() string {\n\treturn C.GoString(C.aug_error_message(a.handle))\n}\n\n\n\nfunc (a Augeas) errorDetails() string {\n\treturn C.GoString(C.aug_error_details(a.handle))\n}\n\nfunc (a Augeas) errorMinorMessage() string ", "output": "{\n\treturn C.GoString(C.aug_error_minor_message(a.handle))\n}"} {"input": "package zipkin\n\nimport (\n\t\"github.com/jaegertracing/jaeger/thrift-gen/zipkincore\"\n)\n\n\nfunc IsServerCore(anno string) bool {\n\treturn anno == zipkincore.SERVER_SEND || anno == zipkincore.SERVER_RECV\n}\n\n\nfunc IsClientCore(anno string) bool {\n\treturn anno == zipkincore.CLIENT_SEND || anno == zipkincore.CLIENT_RECV\n}\n\n\nfunc IsCore(anno string) bool {\n\treturn IsServerCore(anno) || IsClientCore(anno)\n}\n\n\n\n\nfunc FindServiceName(span *zipkincore.Span) string ", "output": "{\n\tfor _, anno := range span.Annotations {\n\t\tendpoint := anno.GetHost()\n\t\tif endpoint == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif IsCore(anno.Value) && endpoint.GetServiceName() != \"\" {\n\t\t\treturn endpoint.GetServiceName()\n\t\t}\n\t}\n\treturn \"\"\n}"} {"input": "package local \n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/tiborvass/docker/errdefs\"\n\t\"github.com/pkg/errors\"\n)\n\ntype optsConfig struct{}\n\n\n\nfunc (r *Root) scopedPath(realPath string) bool {\n\tif strings.HasPrefix(realPath, filepath.Join(r.scope, volumesPathName)) && realPath != filepath.Join(r.scope, volumesPathName) {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc (v *localVolume) needsMount() bool {\n\treturn false\n}\n\nfunc (v *localVolume) mount() error {\n\treturn nil\n}\n\nfunc (v *localVolume) postMount() error {\n\treturn nil\n}\n\nfunc (v *localVolume) CreatedAt() (time.Time, error) {\n\tfileInfo, err := os.Stat(v.path)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\tft := fileInfo.Sys().(*syscall.Win32FileAttributeData).CreationTime\n\treturn time.Unix(0, ft.Nanoseconds()), nil\n}\n\nfunc setOpts(v *localVolume, opts map[string]string) error ", "output": "{\n\tif len(opts) > 0 {\n\t\treturn errdefs.InvalidParameter(errors.New(\"options are not supported on this platform\"))\n\t}\n\treturn nil\n}"} {"input": "package echo\n\ntype (\n\tGroup struct {\n\t\techo Echo\n\t}\n)\n\nfunc (g *Group) Use(m ...Middleware) {\n\tfor _, h := range m {\n\t\tg.echo.middleware = append(g.echo.middleware, wrapMiddleware(h))\n\t}\n}\n\nfunc (g *Group) Connect(path string, h Handler) {\n\tg.echo.Connect(path, h)\n}\n\nfunc (g *Group) Delete(path string, h Handler) {\n\tg.echo.Delete(path, h)\n}\n\nfunc (g *Group) Get(path string, h Handler) {\n\tg.echo.Get(path, h)\n}\n\nfunc (g *Group) Head(path string, h Handler) {\n\tg.echo.Head(path, h)\n}\n\nfunc (g *Group) Options(path string, h Handler) {\n\tg.echo.Options(path, h)\n}\n\nfunc (g *Group) Patch(path string, h Handler) {\n\tg.echo.Patch(path, h)\n}\n\nfunc (g *Group) Post(path string, h Handler) {\n\tg.echo.Post(path, h)\n}\n\nfunc (g *Group) Put(path string, h Handler) {\n\tg.echo.Put(path, h)\n}\n\nfunc (g *Group) Trace(path string, h Handler) {\n\tg.echo.Trace(path, h)\n}\n\n\n\nfunc (g *Group) Static(path, root string) {\n\tg.echo.Static(path, root)\n}\n\nfunc (g *Group) ServeDir(path, root string) {\n\tg.echo.ServeDir(path, root)\n}\n\nfunc (g *Group) ServeFile(path, file string) {\n\tg.echo.ServeFile(path, file)\n}\n\nfunc (g *Group) Group(prefix string, m ...Middleware) *Group {\n\treturn g.echo.Group(prefix, m...)\n}\n\nfunc (g *Group) WebSocket(path string, h HandlerFunc) ", "output": "{\n\tg.echo.WebSocket(path, h)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype geometry interface {\n\tarea() float64\n\tperim() float64\n}\n\ntype square struct {\n\twidth, heigth float64\n}\n\ntype circle struct {\n\tradius float64\n}\n\n\n\nfunc (s square) perim() float64 {\n\treturn 2*s.width + 2*s.heigth\n}\n\nfunc (c circle) area() float64 {\n\treturn math.Pi * c.radius * c.radius\n}\n\nfunc (c circle) perim() float64 {\n\treturn 2 * math.Pi * c.radius\n}\n\nfunc measure(g geometry) {\n\tfmt.Println(g)\n\tfmt.Println(g.area())\n\tfmt.Println(g.perim())\n}\n\nfunc main() {\n\ts := square{width: 3, heigth: 4}\n\tc := circle{radius: 5}\n\n\tmeasure(s)\n\tmeasure(c)\n}\n\nfunc (s square) area() float64 ", "output": "{\n\treturn s.width * s.heigth\n}"} {"input": "package rest\n\nimport (\n\t\"fmt\"\n)\n\ntype imagecache struct {\n\tca cache\n}\n\ntype pic struct {\n\tpng []byte\n\tpkthsh hashcode\n}\n\n\n\nfunc makeImageCache() imagecache {\n\tic := imagecache{}\n\tic.ca = makeCache(pic{})\n\treturn ic\n}\n\nfunc (ic imagecache) put(hsh hashcode, png []byte) {\n\tsz := 0\n\tif __DEBUG {\n\t\tsz = len(png)\n\t}\n\tdebugf(\"Storing image for %v (length %v)\", hsh, sz)\n\tp := pic{}\n\tp.png = png\n\tp.pkthsh = hsh\n\tic.ca.put(p)\n}\n\nfunc (ic imagecache) get(hsh hashcode) ([]byte, bool) {\n\tdebugf(\"Fetching image for %v\", hsh)\n\tany, present := ic.ca.get(hsh)\n\tif !present {\n\t\treturn nil, false\n\t}\n\tp, ok := any.(pic)\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"Expected type pic received: %v\", any))\n\t}\n\treturn p.png, true\n}\n\nfunc (p pic) hash() hashcode ", "output": "{\n\treturn p.pkthsh\n}"} {"input": "package utils\n\nimport \"bytes\"\n\n\n\ntype CompositeError []error\n\n\n\n\n\nfunc (c *CompositeError) AppendError(err error) {\n\tif err != nil {\n\t\t*c = append(*c, err)\n\t}\n}\n\n\nfunc (c *CompositeError) Empty() bool {\n\treturn c == nil || len(*c) == 0\n}\n\n\n\nfunc NewCompositeError(errors ...error) error {\n\tres := &CompositeError{}\n\tfor _, err := range errors {\n\t\tres.AppendError(err)\n\t}\n\tif res.Empty() {\n\t\treturn nil\n\t}\n\treturn res\n}\n\nfunc (c *CompositeError) Error() string ", "output": "{\n\tvar b bytes.Buffer\n\tfor ind, err := range *c {\n\t\t_, _ = b.WriteString(err.Error())\n\t\tif ind == len(*c)-1 {\n\t\t\tbreak\n\t\t}\n\t\t_, _ = b.WriteRune('\\n')\n\t}\n\n\treturn b.String()\n}"} {"input": "package utils\n\nimport (\n\t\"html/template\"\n\t\"testing\"\n)\n\n\n\nfunc TestCompressedContent(t *testing.T) ", "output": "{\n\thtmlContent1 := template.HTML(`\n\n\t\n\n\t\t

Test

\n\n\n\n\t\t

CompressedContent

\n\n\t\n\n\n`)\n\thtmlContent2 := htmlContent1\n\tCompressedContent(&htmlContent2)\n\tt.Log(len(htmlContent1) > len(htmlContent2))\n}"} {"input": "package common\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\ntype NodeMetastate struct {\n\n\tLedgerHeight uint64\n}\n\n\n\n\n\nfunc (n *NodeMetastate) Bytes() ([]byte, error) {\n\tbuffer := new(bytes.Buffer)\n\terr := binary.Write(buffer, binary.BigEndian, *n)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn buffer.Bytes(), nil\n}\n\n\nfunc (n *NodeMetastate) Height() uint64 {\n\treturn n.LedgerHeight\n}\n\n\nfunc (n *NodeMetastate) Update(height uint64) {\n\tn.LedgerHeight = height\n}\n\n\nfunc FromBytes(buf []byte) (*NodeMetastate, error) {\n\tstate := NodeMetastate{}\n\treader := bytes.NewReader(buf)\n\terr := binary.Read(reader, binary.BigEndian, &state)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn &state, nil\n}\n\nfunc NewNodeMetastate(height uint64) *NodeMetastate ", "output": "{\n\treturn &NodeMetastate{height}\n}"} {"input": "package model\n\nimport (\n\t\"testing\"\n)\n\nfunc TestGetUsers(t *testing.T) {\n\tusers := GetUsers()\n\tif len(users) != 50 {\n\t\tt.Errorf(\"Should have returned a list of 50 users\")\n\t}\n}\n\n\n\nfunc TestGetUsersById(t *testing.T) ", "output": "{\n\tuser, err := GetUserByID(3)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif user.FirstName != \"Jonathan\" {\n\t\tt.Errorf(\"should have returned the first name of %s\", user.FirstName)\n\t}\n}"} {"input": "package hugot\n\nimport \"context\"\n\n\n\n\ntype BackgroundHandler interface {\n\tDescriber\n\tStartBackground(ctx context.Context, w ResponseWriter)\n}\n\ntype baseBackgroundHandler struct {\n\tname string\n\tdesc string\n\tbhf BackgroundFunc\n}\n\n\ntype BackgroundFunc func(ctx context.Context, w ResponseWriter)\n\n\n\n\n\nfunc (bbh *baseBackgroundHandler) Describe() (string, string) {\n\treturn bbh.name, bbh.desc\n}\n\nfunc (bbh *baseBackgroundHandler) StartBackground(ctx context.Context, w ResponseWriter) {\n\tbbh.bhf(ctx, w)\n}\n\nfunc NewBackgroundHandler(name, desc string, f BackgroundFunc) BackgroundHandler ", "output": "{\n\treturn &baseBackgroundHandler{\n\t\tname: name,\n\t\tdesc: desc,\n\t\tbhf: f,\n\t}\n}"} {"input": "package dialects\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\ntype Filter interface {\n\tDo(sql string) string\n}\n\n\ntype SeqFilter struct {\n\tPrefix string\n\tStart int\n}\n\n\n\nfunc (s *SeqFilter) Do(sql string) string {\n\treturn convertQuestionMark(sql, s.Prefix, s.Start)\n}\n\nfunc convertQuestionMark(sql, prefix string, start int) string ", "output": "{\n\tvar buf strings.Builder\n\tvar beginSingleQuote bool\n\tvar index = start\n\tfor _, c := range sql {\n\t\tif !beginSingleQuote && c == '?' {\n\t\t\tbuf.WriteString(fmt.Sprintf(\"%s%v\", prefix, index))\n\t\t\tindex++\n\t\t} else {\n\t\t\tif c == '\\'' {\n\t\t\t\tbeginSingleQuote = !beginSingleQuote\n\t\t\t}\n\t\t\tbuf.WriteRune(c)\n\t\t}\n\t}\n\treturn buf.String()\n}"} {"input": "package derive\n\nimport (\n\t\"go/types\"\n\t\"strings\"\n)\n\n\ntype Named struct {\n\tFields []*Field\n\tReflect bool\n}\n\n\ntype Field struct {\n\tname string\n\texternal bool\n\tType types.Type\n\ttypeStr func() string\n}\n\n\nfunc (f *Field) Name(recv string, unsafePkg Import) string {\n\tif !f.Private() || !f.external {\n\t\treturn recv + \".\" + f.name\n\t}\n\treturn `*(*` + f.typeStr() + `)(` + unsafePkg() + `.Pointer(` + recv + `.FieldByName(\"` + f.name + `\").UnsafeAddr()))`\n}\n\n\nfunc (f *Field) DebugName() string {\n\treturn f.name\n}\n\n\nfunc (f *Field) Private() bool {\n\treturn strings.ToLower(f.name[0:1]) == f.name[0:1]\n}\n\n\n\n\nfunc GetStructFields(s *types.Struct) []*types.Var {\n\tfields := make([]*types.Var, s.NumFields())\n\tfor i := 0; i < s.NumFields(); i++ {\n\t\tfields[i] = s.Field(i)\n\t}\n\treturn fields\n}\n\nfunc Fields(typesMap TypesMap, typ *types.Struct, external bool) *Named ", "output": "{\n\tnumFields := typ.NumFields()\n\tn := &Named{\n\t\tFields: make([]*Field, numFields),\n\t}\n\tfor i := 0; i < numFields; i++ {\n\t\tfield := typ.Field(i)\n\t\tfieldType := field.Type()\n\t\tfieldName := field.Name()\n\t\tn.Fields[i] = &Field{\n\t\t\tname: fieldName,\n\t\t\texternal: external,\n\t\t\tType: fieldType,\n\t\t\ttypeStr: func() string {\n\t\t\t\treturn typesMap.TypeString(fieldType)\n\t\t\t},\n\t\t}\n\t\tif n.Fields[i].Private() {\n\t\t\tif external {\n\t\t\t\tn.Reflect = true\n\t\t\t}\n\t\t}\n\t}\n\treturn n\n}"} {"input": "package model\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc TestSubmitBenckmark(t *testing.T) {\n\ttestData1 := testData0\n\ttestData1.Bm = Bm{\n\t\tSwitch: true,\n\t\tN: 10,\n\t\tC: 1,\n\t}\n\n\tresp, err := SubmitModel.Submit(testData1)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tt.Log(resp.Bm)\n\tif resp.Bm == \"\" {\n\t\tt.Fatal(\"no benchmark data?\")\n\t}\n}\n\nfunc TestSubmitTest(t *testing.T) ", "output": "{\n\ttestResp := Response{\n\t\tReqUrl: testSrv.URL + \"?k1=v1&k2=v2\",\n\t\tStatus: \"200 OK\",\n\t\tTest: \"k1=v1&k2=v2 k3=v3&k4=v4\",\n\t\tReqBody: \"k3=v3&k4=v4\",\n\t}\n\n\tresp, err := SubmitModel.Submit(testData0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tt.Logf(\"%#v\", resp)\n\tif !reflect.DeepEqual(testResp, resp) {\n\t\tt.Fatal(\"response not equal!\")\n\t}\n}"} {"input": "package speak\n\nimport (\n\t\"errors\"\n\t\"os/exec\"\n)\n\nvar Voices = []string{\"Agnes\", \"Kathy\", \"Princess\",\n\t\"Vicki\", \"Victoria\", \"Bruce\",\n\t\"Fred\", \"Junior\", \"Ralph\",\n\t\"Albert\", \"Bahh\", \"Bells\",\n\t\"Boing\", \"Bubbles\", \"Cellos\",\n\t\"Deranged\", \"Hysterical\", \"Trinoids\",\n\t\"Whisper\", \"Zarvox\"}\n\n\n\n\nfunc GetVoice(req string) string {\n\tfor _, v := range Voices {\n\t\tif req == v {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn \"Alex\"\n}\n\nfunc Speak(str, voice string) error ", "output": "{\n\tif str == \"\" {\n\t\treturn errors.New(\"Problem executing: No message provided.\")\n\t}\n\tcmd := exec.Command(\"say\", \"-v\", GetVoice(voice), str)\n\treturn cmd.Run()\n}"} {"input": "package outlet\n\nimport (\n\t\"fmt\"\n\t\"l2met/bucket\"\n\t\"l2met/store\"\n\t\"time\"\n)\n\ntype BucketReader struct {\n\tStore store.Store\n\tInterval time.Duration\n\tPartition string\n\tTtl uint64\n\tNumOutlets int\n\tNumScanners int\n\tInbox chan *bucket.Bucket\n\tOutbox chan *bucket.Bucket\n}\n\nfunc NewBucketReader(sz, c int, i time.Duration, st store.Store) *BucketReader {\n\trdr := new(BucketReader)\n\trdr.Partition = \"bucket-reader\"\n\trdr.Inbox = make(chan *bucket.Bucket, sz)\n\trdr.NumScanners = c\n\trdr.NumOutlets = c\n\trdr.Interval = i\n\trdr.Store = st\n\treturn rdr\n}\n\n\n\nfunc (r *BucketReader) scan() {\n\tfor t := range time.Tick(r.Interval) {\n\t\tbuckets, err := r.Store.Scan(t)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"at=bucket.scan error=%s\\n\", err)\n\t\t\tcontinue\n\t\t}\n\t\tfor bucket := range buckets {\n\t\t\tr.Inbox <- bucket\n\t\t}\n\t}\n}\n\nfunc (r *BucketReader) outlet() {\n\tfor b := range r.Inbox {\n\t\tr.Store.Get(b)\n\t\tr.Outbox <- b\n\t}\n}\n\nfunc (r *BucketReader) Start(out chan *bucket.Bucket) ", "output": "{\n\tr.Outbox = out\n\tgo r.scan()\n\tfor i := 0; i < r.NumOutlets; i++ {\n\t\tgo r.outlet()\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/conformal/winsvc/eventlog\"\n\t\"github.com/conformal/winsvc/mgr\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\n\nfunc installService(name, desc string) error {\n\texepath, err := exePath()\n\tif err != nil {\n\t\treturn err\n\t}\n\tm, err := mgr.Connect()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer m.Disconnect()\n\ts, err := m.OpenService(name)\n\tif err == nil {\n\t\ts.Close()\n\t\treturn fmt.Errorf(\"service %s already exists\", name)\n\t}\n\ts, err = m.CreateService(name, exepath, mgr.Config{DisplayName: desc})\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer s.Close()\n\terr = eventlog.InstallAsEventCreate(name, eventlog.Error|eventlog.Warning|eventlog.Info)\n\tif err != nil {\n\t\ts.Delete()\n\t\treturn fmt.Errorf(\"SetupEventLogSource() failed: %s\", err)\n\t}\n\treturn nil\n}\n\nfunc removeService(name string) error {\n\tm, err := mgr.Connect()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer m.Disconnect()\n\ts, err := m.OpenService(name)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"service %s is not installed\", name)\n\t}\n\tdefer s.Close()\n\terr = s.Delete()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = eventlog.Remove(name)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"RemoveEventLogSource() failed: %s\", err)\n\t}\n\treturn nil\n}\n\nfunc exePath() (string, error) ", "output": "{\n\tprog := os.Args[0]\n\tp, err := filepath.Abs(prog)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfi, err := os.Stat(p)\n\tif err == nil {\n\t\tif !fi.Mode().IsDir() {\n\t\t\treturn p, nil\n\t\t}\n\t\terr = fmt.Errorf(\"%s is directory\", p)\n\t}\n\tif filepath.Ext(p) == \"\" {\n\t\tp += \".exe\"\n\t\tfi, err := os.Stat(p)\n\t\tif err == nil {\n\t\t\tif !fi.Mode().IsDir() {\n\t\t\t\treturn p, nil\n\t\t\t}\n\t\t\terr = fmt.Errorf(\"%s is directory\", p)\n\t\t}\n\t}\n\treturn \"\", err\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/flynn/flynn/Godeps/_workspace/src/github.com/julienschmidt/httprouter\"\n\t\"github.com/flynn/flynn/Godeps/_workspace/src/gopkg.in/inconshreveable/log15.v2\"\n\t\"github.com/flynn/flynn/appliance/postgresql/client\"\n\t\"github.com/flynn/flynn/appliance/postgresql/state\"\n\t\"github.com/flynn/flynn/discoverd/client\"\n\t\"github.com/flynn/flynn/pkg/httphelper\"\n)\n\nfunc ServeHTTP(pg *Postgres, peer *state.Peer, hb discoverd.Heartbeater, log log15.Logger) error {\n\tapi := &HTTP{\n\t\tpg: pg,\n\t\tpeer: peer,\n\t\thb: hb,\n\t\tlog: log,\n\t}\n\tr := httprouter.New()\n\tr.GET(\"/status\", api.GetStatus)\n\tr.POST(\"/stop\", api.Stop)\n\treturn http.ListenAndServe(\":5433\", r)\n}\n\ntype HTTP struct {\n\tpg *Postgres\n\tpeer *state.Peer\n\thb discoverd.Heartbeater\n\tlog log15.Logger\n}\n\n\n\nfunc (h *HTTP) Stop(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tif err := h.hb.Close(); err != nil {\n\t\thttphelper.Error(w, err)\n\t\treturn\n\t}\n\tif err := h.peer.Stop(); err != nil {\n\t\thttphelper.Error(w, err)\n\t\treturn\n\t}\n\tw.WriteHeader(200)\n}\n\nfunc (h *HTTP) GetStatus(w http.ResponseWriter, req *http.Request, _ httprouter.Params) ", "output": "{\n\tres := &pgmanager.Status{\n\t\tPeer: h.peer.Info(),\n\t}\n\tvar err error\n\tres.Postgres, err = h.pg.Info()\n\tif err != nil {\n\t\th.log.Error(\"error getting postgres info\", \"err\", err)\n\t}\n\thttphelper.JSON(w, 200, res)\n}"} {"input": "package sftp\n\n\n\n\nimport \"os\"\n\n\n\ntype FileOpenFlags struct {\n\tRead, Write, Append, Creat, Trunc, Excl bool\n}\n\nfunc newFileOpenFlags(flags uint32) FileOpenFlags {\n\treturn FileOpenFlags{\n\t\tRead: flags&ssh_FXF_READ != 0,\n\t\tWrite: flags&ssh_FXF_WRITE != 0,\n\t\tAppend: flags&ssh_FXF_APPEND != 0,\n\t\tCreat: flags&ssh_FXF_CREAT != 0,\n\t\tTrunc: flags&ssh_FXF_TRUNC != 0,\n\t\tExcl: flags&ssh_FXF_EXCL != 0,\n\t}\n}\n\n\n\nfunc (r *Request) Pflags() FileOpenFlags {\n\treturn newFileOpenFlags(r.Flags)\n}\n\n\n\n\ntype FileAttrFlags struct {\n\tSize, UidGid, Permissions, Acmodtime bool\n}\n\n\n\n\n\nfunc (r *Request) AttrFlags() FileAttrFlags {\n\treturn newFileAttrFlags(r.Flags)\n}\n\n\nfunc (a FileStat) FileMode() os.FileMode {\n\treturn os.FileMode(a.Mode)\n}\n\n\n\nfunc (r *Request) Attributes() *FileStat {\n\tfs, _ := getFileStat(r.Flags, r.Attrs)\n\treturn fs\n}\n\nfunc newFileAttrFlags(flags uint32) FileAttrFlags ", "output": "{\n\treturn FileAttrFlags{\n\t\tSize: (flags & ssh_FILEXFER_ATTR_SIZE) != 0,\n\t\tUidGid: (flags & ssh_FILEXFER_ATTR_UIDGID) != 0,\n\t\tPermissions: (flags & ssh_FILEXFER_ATTR_PERMISSIONS) != 0,\n\t\tAcmodtime: (flags & ssh_FILEXFER_ATTR_ACMODTIME) != 0,\n\t}\n}"} {"input": "package live_data\n\nimport (\n\t\"context\"\n\n\t\"go-common/app/interface/live/app-interface/conf\"\n)\n\n\ntype Dao struct {\n\tc *conf.Config\n}\n\n\n\n\n\nfunc (d *Dao) Close() {\n\treturn\n}\n\n\nfunc (d *Dao) Ping(c context.Context) error {\n\treturn nil\n}\n\nfunc New(c *conf.Config) (dao *Dao) ", "output": "{\n\tdao = &Dao{\n\t\tc: c,\n\t}\n\treturn\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realInternetGateway InternetGateway\n\n\n\n\nvar _ fi.HasLifecycle = &InternetGateway{}\n\n\nfunc (o *InternetGateway) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\n\nfunc (o *InternetGateway) SetLifecycle(lifecycle fi.Lifecycle) {\n\to.Lifecycle = &lifecycle\n}\n\nvar _ fi.HasName = &InternetGateway{}\n\n\nfunc (o *InternetGateway) GetName() *string {\n\treturn o.Name\n}\n\n\nfunc (o *InternetGateway) SetName(name string) {\n\to.Name = &name\n}\n\n\nfunc (o *InternetGateway) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *InternetGateway) UnmarshalJSON(data []byte) error ", "output": "{\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realInternetGateway\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = InternetGateway(r)\n\treturn nil\n}"} {"input": "package example\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc foo() int {\n\tn := 1\n\n\tfor i := 0; i < 3; i++ {\n\t\tif i == 0 {\n\t\t\tn++\n\t\t} else if i == 1 {\n\t\t\tn += 2\n\t\t} else {\n\t\t\tn += 3\n\t\t}\n\n\t\tn++\n\t}\n\n\tif n < 0 {\n\t\tn = 0\n\t}\n\n\tn++\n\n\tn += bar()\n\n\tbar()\n\n\tswitch {\n\tcase n < 20:\n\t\tn++\n\tcase n > 20:\n\t\tn--\n\tdefault:\n\t\tn = 0\n\t\tfmt.Println(n)\n\t\tfunc() {}()\n\t}\n\n\tvar x = 0\n\tx++\n\n\treturn n\n}\n\nfunc bar() int {\n\treturn 4\n}\n\n\n\nfunc statementRemoveStringArrayMap() map[string][]string {\n\thash := \"ok\"\n\tvar hdr = make(map[string][]string)\n\n\thdr[\"Hash\"] = []string{hash}\n\n\treturn hdr\n}\n\nfunc statementRemoveStructInitialization() (a http.Header, b error) ", "output": "{\n\tvar err error\n\n\ta, b = http.Header{}, err\n\n\treturn\n}"} {"input": "package instructions\n\nimport \"github.com/zxh0/jvm.go/jvmgo/jvm/rtda\"\n\n\ntype iand struct{ NoOperandsInstruction }\n\n\n\n\ntype land struct{ NoOperandsInstruction }\n\nfunc (self *land) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tv2 := stack.PopLong()\n\tv1 := stack.PopLong()\n\tresult := v1 & v2\n\tstack.PushLong(result)\n}\n\nfunc (self *iand) Execute(frame *rtda.Frame) ", "output": "{\n\tstack := frame.OperandStack()\n\tv2 := stack.PopInt()\n\tv1 := stack.PopInt()\n\tresult := v1 & v2\n\tstack.PushInt(result)\n}"} {"input": "package commands\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/layeh/gumble/gumble\"\n\t\"github.com/matthieugrieger/mumbledj/interfaces\"\n\t\"github.com/spf13/viper\"\n)\n\n\n\ntype SkipPlaylistCommand struct{}\n\n\nfunc (c *SkipPlaylistCommand) Aliases() []string {\n\treturn viper.GetStringSlice(\"commands.skipplaylist.aliases\")\n}\n\n\n\n\n\n\nfunc (c *SkipPlaylistCommand) IsAdminCommand() bool {\n\treturn viper.GetBool(\"commands.skipplaylist.is_admin\")\n}\n\n\n\n\n\n\n\n\n\n\nfunc (c *SkipPlaylistCommand) Execute(user *gumble.User, args ...string) (string, bool, error) {\n\tvar (\n\t\tcurrentTrack interfaces.Track\n\t\terr error\n\t)\n\n\tif currentTrack, err = DJ.Queue.CurrentTrack(); err != nil {\n\t\treturn \"\", true, errors.New(viper.GetString(\"commands.common_messages.no_tracks_error\"))\n\t}\n\n\tif playlist := currentTrack.GetPlaylist(); playlist == nil {\n\t\treturn \"\", true, errors.New(viper.GetString(\"commands.skipplaylist.messages.no_playlist_error\"))\n\t}\n\tif currentTrack.GetPlaylist().GetSubmitter() == user.Name {\n\t\tDJ.Queue.SkipPlaylist()\n\t\treturn fmt.Sprintf(viper.GetString(\"commands.skipplaylist.messages.submitter_voted\"), user.Name), false, nil\n\t}\n\tif err := DJ.Skips.AddPlaylistSkip(user); err != nil {\n\t\treturn \"\", true, errors.New(viper.GetString(\"commands.skipplaylist.messages.already_voted_error\"))\n\t}\n\n\treturn fmt.Sprintf(viper.GetString(\"commands.skipplaylist.messages.voted\"), user.Name), false, nil\n}\n\nfunc (c *SkipPlaylistCommand) Description() string ", "output": "{\n\treturn viper.GetString(\"commands.skipplaylist.description\")\n}"} {"input": "package stick\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"go.mongodb.org/mongo-driver/bson\"\n)\n\n\ntype Coding string\n\n\nconst (\n\tJSON Coding = \"json\"\n\tBSON Coding = \"bson\"\n)\n\n\nfunc (c Coding) Marshal(in interface{}) ([]byte, error) {\n\tswitch c {\n\tcase JSON:\n\t\treturn json.Marshal(in)\n\tcase BSON:\n\t\treturn bson.Marshal(in)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"coal: unknown coding %q\", c))\n\t}\n}\n\n\n\n\n\nfunc (c Coding) Transfer(in, out interface{}) error {\n\tbytes, err := c.Marshal(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.Unmarshal(bytes, out)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc GetJSONKey(field *reflect.StructField) string {\n\ttag := field.Tag.Get(\"json\")\n\n\tif tag == \"-\" {\n\t\treturn \"\"\n\t}\n\n\tvalues := strings.Split(tag, \",\")\n\n\tif len(values) > 0 && len(values[0]) > 0 {\n\t\treturn values[0]\n\t}\n\n\treturn field.Name\n}\n\n\nfunc GetBSONKey(field *reflect.StructField) string {\n\ttag := field.Tag.Get(\"bson\")\n\n\tif tag == \"-\" {\n\t\treturn \"\"\n\t}\n\n\tvalues := strings.Split(tag, \",\")\n\n\tif len(values) > 0 && len(values[0]) > 0 {\n\t\treturn values[0]\n\t}\n\n\treturn strings.ToLower(field.Name)\n}\n\nfunc (c Coding) Unmarshal(in []byte, out interface{}) error ", "output": "{\n\tswitch c {\n\tcase JSON:\n\t\treturn json.Unmarshal(in, out)\n\tcase BSON:\n\t\treturn bson.Unmarshal(in, out)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"coal: unknown coding %q\", c))\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/xtracdev/xavi/env\"\n\t\"github.com/xtracdev/xavi/plugin\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestPluginRegistration(t *testing.T) {\n\tregisterPlugins()\n\tassert.True(t, plugin.RegistryContains(\"Logging\"))\n}\n\nfunc TestXapHook(t *testing.T) {\n\tos.Setenv(env.LoggingOpts, \"\")\n\terr := addXapHook()\n\tassert.Nil(t, err)\n\n\tos.Setenv(env.LoggingOpts, env.Tcplog)\n\terr = addXapHook()\n\tassert.NotNil(t, err)\n\n\tos.Setenv(env.TcplogAddress, \"parse this ### yes?\")\n\terr = addXapHook()\n\tassert.NotNil(t, err)\n\n\tos.Setenv(env.TcplogAddress, \"0.0.0.0:80\")\n\terr = addXapHook()\n\tassert.NotNil(t, err)\n}\n\n\n\nfunc TestGrabCommandLineArgs(t *testing.T) ", "output": "{\n\tgrabCommandLineArgs()\n}"} {"input": "package cron\n\nimport (\n\t\"fmt\"\n\t\"github.com/Cepave/agent/g\"\n\t\"github.com/Cepave/common/model\"\n\t\"log\"\n\t\"time\"\n)\n\n\n\nfunc reportAgentStatus(interval time.Duration) {\n\tfor {\n\t\thostname, err := g.Hostname()\n\t\tif err != nil {\n\t\t\thostname = fmt.Sprintf(\"error:%s\", err.Error())\n\t\t}\n\n\t\treq := model.AgentReportRequest{\n\t\t\tHostname: hostname,\n\t\t\tIP: g.IP(),\n\t\t\tAgentVersion: g.VERSION,\n\t\t\tPluginVersion: g.GetCurrPluginVersion(),\n\t\t}\n\n\t\tvar resp model.SimpleRpcResponse\n\t\terr = g.HbsClient.Call(\"Agent.ReportStatus\", req, &resp)\n\t\tif err != nil || resp.Code != 0 {\n\t\t\tlog.Println(\"call Agent.ReportStatus fail:\", err, \"Request:\", req, \"Response:\", resp)\n\t\t}\n\n\t\ttime.Sleep(interval)\n\t}\n}\n\nfunc ReportAgentStatus() ", "output": "{\n\tif g.Config().Heartbeat.Enabled && g.Config().Heartbeat.Addr != \"\" {\n\t\tgo reportAgentStatus(time.Duration(g.Config().Heartbeat.Interval) * time.Second)\n\t}\n}"} {"input": "package elements_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/purl.org/dc/elements\"\n)\n\n\n\nfunc TestSimpleLiteralMarshalUnmarshal(t *testing.T) {\n\tv := elements.NewSimpleLiteral()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := elements.NewSimpleLiteral()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestSimpleLiteralConstructor(t *testing.T) ", "output": "{\n\tv := elements.NewSimpleLiteral()\n\tif v == nil {\n\t\tt.Errorf(\"elements.NewSimpleLiteral must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed elements.SimpleLiteral should validate: %s\", err)\n\t}\n}"} {"input": "package network\n\nimport (\n\t\"github.com/docker/docker/api/server/httputils\"\n\t\"github.com/docker/docker/api/server/router\"\n)\n\n\ntype networkRouter struct {\n\troutes []router.Route\n}\n\n\n\n\ntype networkRoute struct {\n\tpath string\n\thandler httputils.APIFunc\n}\n\n\nfunc (l networkRoute) Handler() httputils.APIFunc {\n\treturn l.handler\n}\n\nfunc (n networkRouter) Routes() []router.Route ", "output": "{\n\treturn n.routes\n}"} {"input": "package main\n\nimport (\n\t\"github.com/pebbe/zmq4/examples/mdapi\"\n\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n)\n\n\n\n\n\n\n\n\nfunc main() {\n\tvar verbose bool\n\tif len(os.Args) > 1 && os.Args[1] == \"-v\" {\n\t\tverbose = true\n\t}\n\tsession, _ := mdapi.NewMdcli(\"tcp:localhost:5555\", verbose)\n\n\treply, err := ServiceCall(session, \"titanic.request\", \"echo\", \"Hello world\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tvar uuid string\n\tif err == nil {\n\t\tuuid = reply[0]\n\t\tfmt.Println(\"I: request UUID\", uuid)\n\t}\n\n\ttime.Sleep(100 * time.Millisecond)\n\n\tfor {\n\t\treply, err := ServiceCall(session, \"titanic.reply\", uuid)\n\t\tif err == nil {\n\t\t\tfmt.Println(\"Reply:\", reply[0])\n\n\t\t\tServiceCall(session, \"titanic.close\", uuid)\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Println(\"I: no reply yet, trying again...\")\n\t\t\ttime.Sleep(5 * time.Second) \n\t\t}\n\t}\n}\n\nfunc ServiceCall(session *mdapi.Mdcli, service string, request ...string) (reply []string, err error) ", "output": "{\n\treply = []string{}\n\tmsg, err := session.Send(service, request...)\n\tif err == nil {\n\t\tswitch status := msg[0]; status {\n\t\tcase \"200\":\n\t\t\treply = msg[1:]\n\t\t\treturn\n\t\tcase \"400\":\n\t\t\tfmt.Println(\"E: client fatal error, aborting\")\n\t\t\tos.Exit(1)\n\t\tcase \"500\":\n\t\t\tfmt.Println(\"E: server fatal error, aborting\")\n\t\t\tos.Exit(1)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"E: \" + err.Error())\n\t\tos.Exit(0)\n\t}\n\n\terr = errors.New(\"Didn't succeed\")\n\treturn \n}"} {"input": "package kms\n\nimport (\n\t\"os\"\n\n\t\"github.com/denverdino/aliyungo/common\"\n)\n\nconst (\n\tKMSDefaultEndpoint = \"https://kms.cn-hangzhou.aliyuncs.com\"\n\tKMSAPIVersion = \"2016-01-20\"\n\tKMSServiceCode = \"kms\"\n)\n\ntype Client struct {\n\tcommon.Client\n}\n\n\nfunc NewClient(accessKeyId, accessKeySecret string) *Client {\n\tendpoint := os.Getenv(\"KMS_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = KMSDefaultEndpoint\n\t}\n\treturn NewClientWithEndpoint(endpoint, accessKeyId, accessKeySecret)\n}\n\nfunc NewClientWithRegion(accessKeyId string, accessKeySecret string, regionID common.Region) *Client {\n\tendpoint := os.Getenv(\"KMS_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = KMSDefaultEndpoint\n\t}\n\tclient := &Client{}\n\tclient.NewInit(endpoint, KMSAPIVersion, accessKeyId, accessKeySecret, KMSServiceCode, regionID)\n\treturn client\n}\n\nfunc NewClientWithEndpoint(endpoint string, accessKeyId string, accessKeySecret string) *Client {\n\tclient := &Client{}\n\tclient.Init(endpoint, KMSAPIVersion, accessKeyId, accessKeySecret)\n\treturn client\n}\n\n\n\nfunc NewKMSClientWithEndpointAndSecurityToken(endpoint string, accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client {\n\tclient := &Client{}\n\tclient.WithEndpoint(endpoint).\n\t\tWithVersion(KMSAPIVersion).\n\t\tWithAccessKeyId(accessKeyId).\n\t\tWithAccessKeySecret(accessKeySecret).\n\t\tWithSecurityToken(securityToken).\n\t\tWithServiceCode(KMSServiceCode).\n\t\tWithRegionID(regionID).\n\t\tInitClient()\n\treturn client\n}\n\nfunc NewECSClientWithSecurityToken(accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client ", "output": "{\n\tendpoint := os.Getenv(\"KMS_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = KMSDefaultEndpoint\n\t}\n\n\treturn NewKMSClientWithEndpointAndSecurityToken(endpoint, accessKeyId, accessKeySecret, securityToken, regionID)\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/bitly/go-nsq\"\n)\n\n\n\ntype BackendQueue interface {\n\tPut([]byte) error\n\tReadChan() chan []byte \n\tClose() error\n\tDelete() error\n\tDepth() int64\n\tEmpty() error\n}\n\ntype DummyBackendQueue struct {\n\treadChan chan []byte\n}\n\n\n\nfunc (d *DummyBackendQueue) Put([]byte) error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) ReadChan() chan []byte {\n\treturn d.readChan\n}\n\nfunc (d *DummyBackendQueue) Close() error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Delete() error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Depth() int64 {\n\treturn int64(0)\n}\n\nfunc (d *DummyBackendQueue) Empty() error {\n\treturn nil\n}\n\nfunc WriteMessageToBackend(buf *bytes.Buffer, msg *nsq.Message, bq BackendQueue) error {\n\tbuf.Reset()\n\terr := msg.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = bq.Put(buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc NewDummyBackendQueue() BackendQueue ", "output": "{\n\treturn &DummyBackendQueue{readChan: make(chan []byte)}\n}"} {"input": "package storage\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tgenericapirequest \"k8s.io/apiserver/pkg/request\"\n\t\"k8s.io/kubernetes/pkg/apis/batch\"\n\t\"k8s.io/kubernetes/pkg/genericapiserver/api/rest\"\n\t\"k8s.io/kubernetes/pkg/registry/batch/job\"\n\t\"k8s.io/kubernetes/pkg/registry/generic\"\n\tgenericregistry \"k8s.io/kubernetes/pkg/registry/generic/registry\"\n)\n\n\ntype JobStorage struct {\n\tJob *REST\n\tStatus *StatusREST\n}\n\nfunc NewStorage(optsGetter generic.RESTOptionsGetter) JobStorage {\n\tjobRest, jobStatusRest := NewREST(optsGetter)\n\n\treturn JobStorage{\n\t\tJob: jobRest,\n\t\tStatus: jobStatusRest,\n\t}\n}\n\n\ntype REST struct {\n\t*genericregistry.Store\n}\n\n\n\n\n\ntype StatusREST struct {\n\tstore *genericregistry.Store\n}\n\nfunc (r *StatusREST) New() runtime.Object {\n\treturn &batch.Job{}\n}\n\n\nfunc (r *StatusREST) Get(ctx genericapirequest.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}\n\n\nfunc (r *StatusREST) Update(ctx genericapirequest.Context, name string, objInfo rest.UpdatedObjectInfo) (runtime.Object, bool, error) {\n\treturn r.store.Update(ctx, name, objInfo)\n}\n\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST) ", "output": "{\n\tstore := &genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return &batch.Job{} },\n\t\tNewListFunc: func() runtime.Object { return &batch.JobList{} },\n\t\tObjectNameFunc: func(obj runtime.Object) (string, error) {\n\t\t\treturn obj.(*batch.Job).Name, nil\n\t\t},\n\t\tPredicateFunc: job.MatchJob,\n\t\tQualifiedResource: batch.Resource(\"jobs\"),\n\n\t\tCreateStrategy: job.Strategy,\n\t\tUpdateStrategy: job.Strategy,\n\t\tDeleteStrategy: job.Strategy,\n\t}\n\toptions := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: job.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\tpanic(err) \n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = job.StatusStrategy\n\n\treturn &REST{store}, &StatusREST{store: &statusStore}\n}"} {"input": "package client\n\nimport (\n\t\"math\"\n\t\"math/rand\"\n\t\"time\"\n\n\t\"github.com/paybyphone/kintail/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype DefaultRetryer struct {\n\tNumMaxRetries int\n}\n\n\n\n\n\n\nfunc (d DefaultRetryer) RetryRules(r *request.Request) time.Duration {\n\tdelay := int(math.Pow(2, float64(r.RetryCount))) * (rand.Intn(30) + 30)\n\treturn time.Duration(delay) * time.Millisecond\n}\n\n\nfunc (d DefaultRetryer) ShouldRetry(r *request.Request) bool {\n\tif r.HTTPResponse.StatusCode >= 500 {\n\t\treturn true\n\t}\n\treturn r.IsErrorRetryable()\n}\n\nfunc (d DefaultRetryer) MaxRetries() int ", "output": "{\n\treturn d.NumMaxRetries\n}"} {"input": "package vault\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\ntype AuthType interface {\n\tDescribe() string\n\tGetType() string\n\tgetAuthConfig() map[string]interface{}\n\tgetAuthMountConfig() map[string]interface{}\n\tConfigure(c *VCClient) error\n\tTuneMount(c *VCClient, path string) error\n\tWriteUsers(c *VCClient) error\n\tWriteGroups(c *VCClient) error\n}\n\n\nfunc (c *VCClient) AuthExist(name string) bool {\n\tauth, err := c.Sys().ListAuth()\n\tif err != nil {\n\t\treturn false\n\t}\n\tfor a := range auth {\n\t\tif strings.TrimSuffix(a, \"/\") == name {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\nfunc Path(a AuthType) string {\n\treturn fmt.Sprintf(\"auth/%s\", a.GetType())\n}\n\n\n\n\n\nfunc (c *VCClient) AuthConfigure(a AuthType) error {\n\tif err := a.WriteUsers(c); err != nil {\n\t\treturn err\n\t}\n\tif err := a.WriteGroups(c); err != nil {\n\t\treturn err\n\t}\n\tif err := a.TuneMount(c, Path(a)); err != nil {\n\t\treturn err\n\t}\n\n\tif err := a.Configure(c); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc EnableAndConfigure(a AuthType, c *VCClient) error {\n\tif !c.AuthExist(a.GetType()) {\n\t\tif err := c.AuthEnable(a); err != nil {\n\t\t\treturn fmt.Errorf(\"Error enabling auth mount: %v\", err)\n\t\t}\n\t}\n\tif err := c.AuthConfigure(a); err != nil {\n\t\treturn fmt.Errorf(\"Error configuring auth mount: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (c *VCClient) AuthEnable(a AuthType) error ", "output": "{\n\tif err := c.Sys().EnableAuth(a.GetType(), a.GetType(), a.Describe()); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package nodes\n\nimport \"bufio\"\n\ntype Representation struct {\n\tContent string `bson:\"c\"`\n}\n\n\n\n\nfunc (r *Representation) Render(w *bufio.Writer) error ", "output": "{\n\tw.WriteString(r.Content)\n\treturn nil\n}"} {"input": "package cluster_health\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\tmbtest \"github.com/elastic/beats/metricbeat/mb/testing\"\n)\n\nfunc TestData(t *testing.T) {\n\tf := mbtest.NewEventFetcher(t, getConfig())\n\terr := mbtest.WriteEvent(f, t)\n\tif err != nil {\n\t\tt.Fatal(\"write\", err)\n\t}\n}\n\n\n\nconst (\n\tcephDefaultHost = \"127.0.0.1\"\n\tcephDefaultPort = \"5000\"\n)\n\nfunc getTestCephHost() string {\n\treturn fmt.Sprintf(\"%v:%v\",\n\t\tgetenv(\"CEPH_HOST\", cephDefaultHost),\n\t\tgetenv(\"CEPH_PORT\", cephDefaultPort),\n\t)\n}\n\nfunc getenv(name, defaultValue string) string {\n\treturn strDefault(os.Getenv(name), defaultValue)\n}\n\nfunc strDefault(a, defaults string) string {\n\tif len(a) == 0 {\n\t\treturn defaults\n\t}\n\treturn a\n}\n\nfunc getConfig() map[string]interface{} ", "output": "{\n\treturn map[string]interface{}{\n\t\t\"module\": \"ceph\",\n\t\t\"metricsets\": []string{\"cluster_health\"},\n\t\t\"hosts\": getTestCephHost(),\n\t}\n}"} {"input": "package operations\n\n\n\nimport (\n\t\"github.com/denkhaus/bitshares/types\"\n\t\"github.com/denkhaus/bitshares/util\"\n\t\"github.com/juju/errors\"\n)\n\nfunc init() {\n\ttypes.OperationMap[types.OperationTypeTransferFromBlind] = func() types.Operation {\n\t\top := &TransferFromBlindOperation{}\n\t\treturn op\n\t}\n}\n\ntype TransferFromBlindOperation struct {\n\ttypes.OperationFee\n\tAmount types.AssetAmount `json:\"amount\"`\n\tTo types.AccountID `json:\"to\"`\n\tBlindFactor types.FixedBuffer `json:\"blinding_factor\"`\n\tBlindInputs types.BlindInputs `json:\"inputs\"`\n}\n\n\n\nfunc (p TransferFromBlindOperation) Marshal(enc *util.TypeEncoder) error {\n\tif err := enc.Encode(int8(p.Type())); err != nil {\n\t\treturn errors.Annotate(err, \"encode OperationType\")\n\t}\n\tif err := enc.Encode(p.Fee); err != nil {\n\t\treturn errors.Annotate(err, \"encode Fee\")\n\t}\n\tif err := enc.Encode(p.Amount); err != nil {\n\t\treturn errors.Annotate(err, \"encode Amount\")\n\t}\n\tif err := enc.Encode(p.To); err != nil {\n\t\treturn errors.Annotate(err, \"encode To\")\n\t}\n\tif err := enc.Encode(p.BlindFactor); err != nil {\n\t\treturn errors.Annotate(err, \"encode BlindFactor\")\n\t}\n\tif err := enc.Encode(p.BlindInputs); err != nil {\n\t\treturn errors.Annotate(err, \"encode BlindInputs\")\n\t}\n\n\treturn nil\n}\n\nfunc (p TransferFromBlindOperation) Type() types.OperationType ", "output": "{\n\treturn types.OperationTypeTransferFromBlind\n}"} {"input": "package github\n\nimport (\n\t\"strconv\"\n\t\"time\"\n)\n\n\n\n\n\ntype Timestamp struct {\n\ttime.Time\n}\n\n\n\n\n\nfunc (t *Timestamp) UnmarshalJSON(data []byte) (err error) {\n\tstr := string(data)\n\ti, err := strconv.ParseInt(str, 10, 64)\n\tif err == nil {\n\t\tt.Time = time.Unix(i, 0)\n\t} else {\n\t\tt.Time, err = time.Parse(`\"`+time.RFC3339+`\"`, str)\n\t}\n\treturn\n}\n\n\nfunc (t Timestamp) Equal(u Timestamp) bool {\n\treturn t.Time.Equal(u.Time)\n}\n\nfunc (t Timestamp) String() string ", "output": "{\n\treturn t.Time.String()\n}"} {"input": "package v1\n\nimport (\n\tv1 \"github.com/openshift/api/config/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype IdentityProviderLister interface {\n\tList(selector labels.Selector) (ret []*v1.IdentityProvider, err error)\n\tGet(name string) (*v1.IdentityProvider, error)\n\tIdentityProviderListerExpansion\n}\n\n\ntype identityProviderLister struct {\n\tindexer cache.Indexer\n}\n\n\n\n\n\nfunc (s *identityProviderLister) List(selector labels.Selector) (ret []*v1.IdentityProvider, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.IdentityProvider))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *identityProviderLister) Get(name string) (*v1.IdentityProvider, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"identityprovider\"), name)\n\t}\n\treturn obj.(*v1.IdentityProvider), nil\n}\n\nfunc NewIdentityProviderLister(indexer cache.Indexer) IdentityProviderLister ", "output": "{\n\treturn &identityProviderLister{indexer: indexer}\n}"} {"input": "package cgo\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestRead(t *testing.T) {\n\ttestRead(t)\n}\n\nfunc TestWrite(t *testing.T) ", "output": "{\n\ttestWrite(t)\n}"} {"input": "package v1beta3\n\nimport (\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/api\"\n)\n\n\n\nfunc init() ", "output": "{\n\tapi.Scheme.AddKnownTypes(\"v1beta3\",\n\t\t&User{},\n\t\t&UserList{},\n\t\t&Identity{},\n\t\t&IdentityList{},\n\t\t&UserIdentityMapping{},\n\t)\n}"} {"input": "package log\n\ntype logLevel struct {\n\tLevel int\n\tPrefix string\n\tColorFunc func(...interface{}) string\n}\n\ntype logLevels []*logLevel\n\n\n\nfunc (l *logLevels) getLevel(Level int) *logLevel {\n\tfor _, item := range *l {\n\t\tif item.Level == Level {\n\t\t\treturn item\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (l *logLevels) getFunc(Level int) func(...interface{}) string ", "output": "{\n\tlevel := l.getLevel(Level)\n\tif level != nil {\n\t\treturn level.ColorFunc\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n\n\t\"github.com/n0rad/go-erlog/errs\"\n)\n\ntype envMap struct {\n\tmapping map[string]string\n}\n\nfunc (e *envMap) Set(s string) error {\n\tif e.mapping == nil {\n\t\te.mapping = make(map[string]string)\n\t}\n\tpair := strings.SplitN(s, \"=\", 2)\n\tif len(pair) != 2 {\n\t\treturn errs.With(\"environment variable must be specified as name=value\")\n\t}\n\te.mapping[pair[0]] = pair[1]\n\treturn nil\n}\n\n\n\nfunc (e *envMap) Strings() []string {\n\tvar env []string\n\tfor n, v := range e.mapping {\n\t\tenv = append(env, n+\"=\"+v)\n\t}\n\treturn env\n}\n\nfunc (e *envMap) Type() string {\n\treturn \"envMap\"\n}\n\nfunc (e *envMap) String() string ", "output": "{\n\treturn strings.Join(e.Strings(), \"\\n\")\n}"} {"input": "package types\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v1\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc newLocalDevicesObj() *LocalDevices {\n\treturn &LocalDevices{\n\t\tDriver: \"vfs\",\n\t\tDeviceMap: map[string]string{\n\t\t\t\"vfs-000\": \"/dev/xvda\",\n\t\t\t\"vfs-001\": \"/dev/xvdb\",\n\t\t\t\"vfs-002\": \"/dev/xvdc\",\n\t\t},\n\t}\n}\n\nvar expectedLD1String = \"vfs=vfs-000::/dev/xvda,vfs-001::/dev/xvdb,vfs-002::/dev/xvdc\"\n\n\n\nfunc TestLocalDevicesUnmarshalText(t *testing.T) {\n\n\tld1 := &LocalDevices{}\n\terr := ld1.UnmarshalText([]byte(\"scaleio=\"))\n\tassert.NoError(t, err)\n}\n\nfunc TestLocalDevicesMarshalJSON(t *testing.T) {\n\n\tld1 := newLocalDevicesObj()\n\n\tbuf, err := ld1.MarshalJSON()\n\tassert.NoError(t, err)\n\tt.Logf(\"localDevices=%s\", string(buf))\n\n\tld2 := &LocalDevices{}\n\tassert.NoError(t, ld2.UnmarshalJSON(buf))\n\n\tassert.EqualValues(t, ld1, ld2)\n}\n\nfunc TestLocalDevicesMarshalToYAML(t *testing.T) {\n\tout, err := yaml.Marshal(newLocalDevicesObj())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfmt.Println(string(out))\n}\n\nfunc TestLocalDevicesMarshalText(t *testing.T) ", "output": "{\n\n\tld1 := newLocalDevicesObj()\n\tassert.Equal(t, expectedLD1String, ld1.String())\n\tt.Logf(\"localDevices=%s\", ld1)\n\n\tld2 := &LocalDevices{}\n\tassert.NoError(t, ld2.UnmarshalText([]byte(ld1.String())))\n\tassert.EqualValues(t, ld1, ld2)\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"strings\"\n)\n\n\nfunc Report(extra ...interface{}) {\n\tfmt.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\")\n\tfmt.Fprintln(os.Stderr, extra...)\n\n\t_, file, line, _ := runtime.Caller(1)\n\tfmt.Fprintf(os.Stderr, \"%v:%v\\n\", file, line)\n\n\tdebug.PrintStack()\n\n\tfmt.Fprintln(os.Stderr, \"#### BUG! PLEASE REPORT ####\")\n}\n\n\n\n\nfunc PrintDepricationWarning(str string) ", "output": "{\n\tline := strings.Repeat(\"#\", len(str)+4)\n\temptyLine := strings.Repeat(\" \", len(str))\n\tfmt.Printf(`\n%s\n# %s #\n# %s #\n# %s #\n%s\n\n`, line, emptyLine, str, emptyLine, line)\n}"} {"input": "package job\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/gapid/core/data/search\"\n\t\"github.com/google/gapid/core/event\"\n\t\"github.com/google/gapid/core/net/grpcutil\"\n\t\"github.com/google/gapid/core/os/device\"\n\t\"google.golang.org/grpc\"\n)\n\ntype remote struct {\n\tclient ServiceClient\n}\n\n\nfunc NewRemote(ctx context.Context, conn *grpc.ClientConn) Manager {\n\treturn &remote{client: NewServiceClient(conn)}\n}\n\n\n\nfunc (m *remote) SearchDevices(ctx context.Context, query *search.Query, handler DeviceHandler) error {\n\tstream, err := m.client.SearchDevices(ctx, query)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn event.Feed(ctx, event.AsHandler(ctx, handler), grpcutil.ToProducer(stream))\n}\n\n\n\n\n\n\n\nfunc (m *remote) GetWorker(ctx context.Context, host *device.Instance, target *device.Instance, op Operation) (*Worker, error) {\n\trequest := &GetWorkerRequest{Host: host, Target: target, Operation: op}\n\tresponse, err := m.client.GetWorker(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn response.Worker, nil\n}\n\nfunc (m *remote) SearchWorkers(ctx context.Context, query *search.Query, handler WorkerHandler) error ", "output": "{\n\tstream, err := m.client.SearchWorkers(ctx, query)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn event.Feed(ctx, event.AsHandler(ctx, handler), grpcutil.ToProducer(stream))\n}"} {"input": "package bunyan\n\nimport \"os\"\n\n\n\ntype Sink interface {\n\tWrite(record Record) error\n}\n\ntype funcSink struct {\n\twrite func(record Record) error\n}\n\nfunc (sink *funcSink) Write(record Record) error {\n\treturn sink.write(record)\n}\n\n\n\nfunc SinkFunc(write func(record Record) error) Sink {\n\treturn &funcSink{write}\n}\n\n\n\n\n\nfunc InfoSink(target Sink, info Info) Sink {\n\treturn SinkFunc(func(record Record) error {\n\t\trecord.SetIfNot(info.Key(), info.Value())\n\t\treturn target.Write(record)\n\t})\n}\n\n\nfunc StdoutSink() Sink {\n\treturn NewJsonSink(os.Stdout)\n}\n\n\nfunc FileSink(path string) Sink {\n\tconst flags = os.O_CREATE | os.O_APPEND | os.O_WRONLY\n\tfile, e := os.OpenFile(path, flags, 0666)\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\n\treturn NewJsonSink(file)\n}\n\nfunc NilSink() Sink ", "output": "{\n\treturn SinkFunc(func(record Record) error {\n\t\treturn nil \n\t})\n}"} {"input": "package model\n\nimport (\n\t\"fmt\"\n\tnative_time \"time\"\n)\n\n\n\n\n\n\n\n\ntype Timestamp int64\n\nconst (\n\tMinimumTick = native_time.Second\n\tsecond = int64(native_time.Second / MinimumTick)\n)\n\n\nfunc (t Timestamp) Equal(o Timestamp) bool {\n\treturn t == o\n}\n\n\nfunc (t Timestamp) Before(o Timestamp) bool {\n\treturn t < o\n}\n\n\nfunc (t Timestamp) After(o Timestamp) bool {\n\treturn t > o\n}\n\n\nfunc (t Timestamp) Add(d native_time.Duration) Timestamp {\n\treturn t + Timestamp(d/MinimumTick)\n}\n\n\nfunc (t Timestamp) Sub(o Timestamp) native_time.Duration {\n\treturn native_time.Duration(t-o) * MinimumTick\n}\n\n\nfunc (t Timestamp) Time() native_time.Time {\n\treturn native_time.Unix(int64(t)/second, (int64(t) % second))\n}\n\n\n\nfunc (t Timestamp) Unix() int64 {\n\treturn int64(t) / second\n}\n\n\nfunc (t Timestamp) String() string {\n\treturn fmt.Sprint(int64(t))\n}\n\n\nfunc Now() Timestamp {\n\treturn TimestampFromTime(native_time.Now())\n}\n\n\nfunc TimestampFromTime(t native_time.Time) Timestamp {\n\treturn TimestampFromUnix(t.Unix())\n}\n\n\n\n\nfunc TimestampFromUnix(t int64) Timestamp ", "output": "{\n\treturn Timestamp(t * second)\n}"} {"input": "package databasemigration\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype WorkRequestErrorCollection struct {\n\n\tItems []WorkRequestError `mandatory:\"true\" json:\"items\"`\n}\n\n\n\nfunc (m WorkRequestErrorCollection) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package s2\n\n\nvar (\n\t_ Shape = (*PointVector)(nil)\n)\n\n\n\n\n\n\n\n\ntype PointVector []Point\n\nfunc (p *PointVector) NumEdges() int { return len(*p) }\nfunc (p *PointVector) Edge(i int) Edge { return Edge{(*p)[i], (*p)[i]} }\nfunc (p *PointVector) ReferencePoint() ReferencePoint { return OriginReferencePoint(false) }\nfunc (p *PointVector) NumChains() int { return len(*p) }\nfunc (p *PointVector) Chain(i int) Chain { return Chain{i, 1} }\nfunc (p *PointVector) ChainEdge(i, j int) Edge { return Edge{(*p)[i], (*p)[j]} }\nfunc (p *PointVector) ChainPosition(e int) ChainPosition { return ChainPosition{e, 0} }\nfunc (p *PointVector) Dimension() int { return 0 }\nfunc (p *PointVector) IsEmpty() bool { return defaultShapeIsEmpty(p) }\nfunc (p *PointVector) IsFull() bool { return defaultShapeIsFull(p) }\n\nfunc (p *PointVector) privateInterface() {}\n\nfunc (p *PointVector) typeTag() typeTag ", "output": "{ return typeTagPointVector }"} {"input": "package wire\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader ", "output": "{\n\tb := make([]byte, max)\n\tif buf != nil {\n\t\tcopy(b, buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}"} {"input": "package coap\n\nimport (\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"io\"\n)\n\n\n\ntype TcpMessage struct {\n\tMessage\n}\n\n\n\nfunc (m *TcpMessage) UnmarshalBinary(data []byte) error {\n\tif len(data) < 4 {\n\t\treturn errors.New(\"short packet\")\n\t}\n\n\treturn m.Message.UnmarshalBinary(data)\n}\n\n\nfunc Decode(r io.Reader) (*TcpMessage, error) {\n\tvar ln uint16\n\terr := binary.Read(r, binary.BigEndian, &ln)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpacket := make([]byte, ln)\n\t_, err = io.ReadFull(r, packet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm := TcpMessage{}\n\n\terr = m.UnmarshalBinary(packet)\n\treturn &m, err\n}\n\nfunc (m *TcpMessage) MarshalBinary() ([]byte, error) ", "output": "{\n\tbin, err := m.Message.MarshalBinary()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\n\tl := []byte{0, 0}\n\tbinary.BigEndian.PutUint16(l, uint16(len(bin)))\n\n\treturn append(l, bin...), nil\n}"} {"input": "package constraint\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hashicorp/go-multierror\"\n)\n\n\ntype ExactlyOne struct {\n\tConstraints []Check\n}\n\nvar _ Range = &ExactlyOne{}\n\n\n\n\nfunc (e *ExactlyOne) ValidateItems(arr []interface{}, p Params) error ", "output": "{\n\tvar matches int\n\tvar err error\nmainloop:\n\tfor _, a := range arr {\n\t\tfor _, c := range e.Constraints {\n\t\t\ter := c.ValidateItem(a, p)\n\t\t\tif er != nil {\n\t\t\t\terr = multierror.Append(err, er)\n\t\t\t\tcontinue mainloop\n\t\t\t}\n\t\t}\n\t\tmatches++\n\t}\n\n\tswitch matches {\n\tcase 0:\n\t\terr = multierror.Append(err, fmt.Errorf(\"no item matched constraints: %v\", arr))\n\t\treturn multierror.Flatten(err)\n\tcase 1:\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"multiple items(%d) matched constraints: %v\", matches, arr)\n\t}\n}"} {"input": "package colorable\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\n\n\n\n\nfunc NewColorableStdout() io.Writer {\n\treturn os.Stdout\n}\n\n\nfunc NewColorableStderr() io.Writer {\n\treturn os.Stderr\n}\n\nfunc NewColorable(file *os.File) io.Writer ", "output": "{\n\tif file == nil {\n\t\tpanic(\"nil passed instead of *os.File to NewColorable()\")\n\t}\n\n\treturn file\n}"} {"input": "package s3storage\n\nimport (\n\t\"testing\"\n\n\t\"github.com/AdRoll/goamz/aws\"\n\t\"github.com/AdRoll/goamz/s3\"\n\t\"github.com/AdRoll/goamz/s3/s3test\"\n\t\"github.com/facebookgo/ensure\"\n)\n\n\ntype MockS3 struct {\n\tauth aws.Auth\n\tregion aws.Region\n\tsrv *s3test.Server\n\tconfig *s3test.Config\n}\n\n\nfunc (s *MockS3) Start(t *testing.T) {\n\tsrv, err := s3test.NewServer(s.config)\n\tensure.Nil(t, err)\n\tensure.NotNil(t, srv)\n\n\ts.srv = srv\n\ts.region = aws.Region{\n\t\tName: \"faux-region-1\",\n\t\tS3Endpoint: srv.URL(),\n\t\tS3LocationConstraint: true, \n\t}\n}\n\n\nfunc (s *MockS3) Stop() {\n\ts.srv.Quit()\n}\n\n\nfunc NewMockS3(t *testing.T) *MockS3 {\n\tm := MockS3{}\n\tm.Start(t)\n\treturn &m\n}\n\n\n\n\nfunc NewStorageWithMockS3(s *MockS3) (*S3Storage, error) ", "output": "{\n\treturn NewS3Storage(s.region, s.auth, \"testbucket\", \"test\", s3.Private)\n}"} {"input": "package rorm\n\ntype rorm struct {\n\tredisQuerier *RedisQuerier\n}\n\nfunc NewROrm() ROrmer {\n\treturn new(rorm).Using(\"default\")\n}\n\nfunc (r *rorm) QueryHash(key string) HashQuerySeter {\n\treturn &hashQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QueryKeys(key string) KeysQuerySeter {\n\treturn &keysQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QueryString(key string) StringQuerySeter {\n\treturn &stringQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QueryZSet(key string) ZSetQuerySeter {\n\treturn &zsetQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QuerySet(key string) SetQuerySeter {\n\treturn &setQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r rorm) Using(alias string) ROrmer {\n\tclient, ok := redisRegistry[alias]\n\tif !ok {\n\t\tpanic(\"using reids '\" + alias + \"' not exist.\")\n\t}\n\tr.redisQuerier = &RedisQuerier{\n\t\tClient: client,\n\t}\n\treturn &r\n}\n\n\n\nfunc (r *rorm) Querier() Querier ", "output": "{\n\treturn r.redisQuerier\n}"} {"input": "package main\n\nimport (\"log\"; \"net\")\n\nfunc main() {\n ln, err := net.Listen(\"tcp\", \":6000\")\n if err != nil {\n log.Fatal(err)\n }\n for {\n conn, err := ln.Accept()\n if err != nil {\n log.Println(err)\n continue\n }\n go handleConnection(conn)\n }\n}\n\n\n\nfunc handleConnection(c net.Conn) ", "output": "{\n buf := make([]byte, 4096)\n\n for {\n n, err := c.Read(buf)\n if err != nil || n == 0 {\n c.Close()\n break\n }\n n, err = c.Write(buf[0:n])\n if err != nil {\n c.Close()\n break\n }\n }\n log.Printf(\"Connection from %v closed.\", c.RemoteAddr())\n}"} {"input": "package cacheval\n\nimport (\n\t\"math/rand\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestInt32Stress(t *testing.T) {\n\tconst valid = 10 * time.Millisecond\n\tconst delay = 1 * time.Millisecond\n\tconst concurrency = 50\n\tconst N = 500\n\n\tcv := Int32{}\n\tcv.Init(valid)\n\n\twg := sync.WaitGroup{}\n\twg.Add(concurrency)\n\tpassive := func() {\n\t\tmax := int32(0)\n\t\tfor j := 1; j <= N; j++ {\n\t\t\tv, ok := cv.GetFresh()\n\t\t\tif v > max {\n\t\t\t\tmax = v\n\t\t\t} else if ok && v < max {\n\t\t\t\tt.Error(\"unexpected decrease\")\n\t\t\t}\n\t\t\ttime.Sleep(delay)\n\t\t}\n\t\twg.Done()\n\t}\n\tfor i := 1; i <= concurrency; i++ {\n\t\tgo passive()\n\t}\n\tfor j := 1; j <= N; j++ {\n\t\tprev := cv.Get()\n\t\tcv.GetOrUpdate(func() { cv.Set(prev + 1) })\n\t\ttime.Sleep(delay)\n\t}\n\twg.Wait()\n}\n\nfunc TestInt32Valid(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\trand := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tconst valid = 100 * time.Millisecond\n\n\tcv := Int32{}\n\tcv.Init(valid)\n\n\tassert.Equal(t, int32(0), cv.Get())\n\tv, ok := cv.GetFresh()\n\tassert.Equal(t, int32(0), v)\n\tassert.Equal(t, false, ok)\n\n\texpect := int32(rand.Uint32())\n\tcv.Set(expect)\n\tv, ok = cv.GetFresh()\n\tassert.Equal(t, expect, v)\n\tassert.Equal(t, true, ok)\n\n\ttime.Sleep(valid)\n\tv = cv.GetOrUpdate(func() { cv.Set(expect + 1) })\n\tassert.Equal(t, expect+1, v)\n\tassert.Equal(t, expect+1, cv.Get())\n}"} {"input": "package toJson\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc WriteToJson(w http.ResponseWriter, obj interface{}) error {\n\treturn WriteToJsonWithCode(w, obj, http.StatusOK)\n}\n\nfunc WriteToJsonWithCode(w http.ResponseWriter, obj interface{}, code int) error {\n\to, err := ToJson(obj)\n\tif err != nil {\n\t\twriteError(err)\n\t\treturn err\n\t}\n\n\twrapped := map[string]interface{}{\"result\": o}\n\n\treturn WriteJson(w, &wrapped, code)\n}\n\n\n\nfunc WriteToJsonNotWrappedWithCode(w http.ResponseWriter, obj interface{}, code int) error {\n\to, err := ToJson(obj)\n\tif err != nil {\n\t\twriteError(err)\n\t\treturn err\n\t}\n\n\treturn WriteJson(w, &o, code)\n}\n\nfunc WriteJson(w http.ResponseWriter, obj interface{}, code int) error {\n\tmarshalled, err := json.MarshalIndent(obj, \"\", \" \")\n\tif err != nil {\n\t\twriteError(err)\n\t\treturn err\n\t}\n\n\tdata := []byte(fmt.Sprintf(\"%s\\n\", marshalled))\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.Header().Set(\"Content-Length\", fmt.Sprint(len(data)))\n\tw.WriteHeader(code)\n\tw.Write(data)\n\n\treturn nil\n}\n\nfunc WriteToJsonNotWrapped(w http.ResponseWriter, obj interface{}) error ", "output": "{\n\treturn WriteToJsonNotWrappedWithCode(w, obj, http.StatusOK)\n}"} {"input": "package client\n\nimport (\n\tatlantis \"atlantis/common\"\n\t. \"atlantis/manager/constant\"\n)\n\ntype ManagerRPCClient struct {\n\tatlantis.RPCClient\n\tUser string\n\tSecrets map[string]string\n}\n\ntype AuthedArg interface {\n\tSetCredentials(string, string)\n}\n\nfunc (r *ManagerRPCClient) CallAuthed(name string, arg AuthedArg, reply interface{}) error {\n\treturn r.CallAuthedMulti(name, arg, 0, reply)\n}\n\nfunc (r *ManagerRPCClient) CallAuthedMulti(name string, arg AuthedArg, region int, reply interface{}) error {\n\targ.SetCredentials(r.User, r.Secrets[r.Opts[region].RPCHostAndPort()])\n\n\treturn r.RPCClient.CallMulti(name, arg, region, reply)\n}\n\nfunc NewManagerRPCClient(hostAndPort string) *atlantis.RPCClient {\n\treturn atlantis.NewRPCClient(hostAndPort, \"ManagerRPC\", ManagerRPCVersion, true)\n}\n\n\n\nfunc NewManagerRPCClientWithConfig(cfg []atlantis.RPCServerOpts) *atlantis.RPCClient ", "output": "{\n\treturn atlantis.NewMultiRPCClientWithConfig(cfg, \"ManagerRPC\", ManagerRPCVersion, true)\n}"} {"input": "package retry\n\nimport (\n\t\"context\"\n\n\t\"k8s.io/apimachinery/pkg/util/wait\"\n)\n\n\n\n\n\n\ntype ConditionWithContextFunc func(ctx context.Context) (done bool, err error)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ExponentialBackoffWithContext(ctx context.Context, backoff wait.Backoff, condition ConditionWithContextFunc) error ", "output": "{\n\treturn wait.ExponentialBackoff(backoff, func() (bool, error) {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn false, wait.ErrWaitTimeout\n\t\tdefault:\n\t\t\treturn condition(ctx)\n\t\t}\n\t})\n}"} {"input": "package core\n\nimport (\n\t\"os\";\n\t\"container/list\";\n\t\"net\";\n\t\"log\";\n\t\"irc\";\n\t\"runloop\";\n)\n\ntype Network struct {\n\tname\t\tstring;\n\tserver\t\t*server;\n\tclients\t\t*list.List;\n\tlisten\t\t*listenConn;\n}\n\nfunc newNetwork(name string, serverConn net.Conn, listen net.Listener) *Network {\n\tvar network *Network;\n\n\taccept := func(conn net.Conn) {\n\t\trunloop.CallLater(func() {\n\t\t\tnetwork.addClient(conn)\n\t\t})\n\t};\n\n\terror := func(err os.Error) {\n\t};\n\n\tl := newListenConn(listen, accept, error);\n\tnetwork = &Network{name: name, clients: list.New(), listen: l};\n\tnetwork.server = newServer(serverConn, network);\n\treturn network;\n}\n\nfunc (network *Network) addClient(conn net.Conn) {\n\tclient := newClient(conn, network);\n\tnetwork.clients.PushBack(client);\n\tlog.Stderrf(\"client connected from %s\\n\", conn.RemoteAddr());\n}\n\n\n\nfunc (network *Network) SendToServer(msg *irc.Message) {\n\tif network.server != nil {\n\t\tnetwork.server.Send(msg)\n\t}\n}\n\n\n\n\n\nfunc (network *Network) SendNoticeToClient(conn Conn, line string) {\n\tnick := \"bouncin\"; \n\tconn.Send(&irc.Message{Command: \"NOTICE\", Params: []string{nick, line}});\n}\n\nvar networks = make(map[string] *Network);\n\nfunc AddNetwork(name string, server net.Conn, listen net.Listener) *Network {\n\tnetwork := newNetwork(name, server, listen);\n\tnetworks[name] = network;\n\treturn network;\n}\n\nfunc (network *Network) SendToClients(msg *irc.Message) ", "output": "{\n\tfor c := range network.clients.Iter() {\n\t\tc.(*client).Send(msg)\n\t}\n}"} {"input": "package misc\n\nimport \"errors\"\n\nfunc Mkfifo(path string, mode uint32) (err error) {\n\treturn errors.New(\"not supported\")\n}\n\n\n\n\nfunc Mksocket(path string) (err error) ", "output": "{\n\treturn errors.New(\"not supported\")\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-chi/chi\"\n)\n\ntype todosResource struct{}\n\n\nfunc (rs todosResource) Routes() chi.Router {\n\tr := chi.NewRouter()\n\n\tr.Get(\"/\", rs.List) \n\tr.Post(\"/\", rs.Create) \n\tr.Put(\"/\", rs.Delete)\n\n\tr.Route(\"/{id}\", func(r chi.Router) {\n\t\tr.Get(\"/\", rs.Get) \n\t\tr.Put(\"/\", rs.Update) \n\t\tr.Delete(\"/\", rs.Delete) \n\t\tr.Get(\"/sync\", rs.Sync)\n\t})\n\n\treturn r\n}\n\nfunc (rs todosResource) List(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todos list of stuff..\"))\n}\n\nfunc (rs todosResource) Create(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todos create\"))\n}\n\nfunc (rs todosResource) Get(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo get\"))\n}\n\nfunc (rs todosResource) Update(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo update\"))\n}\n\nfunc (rs todosResource) Delete(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo delete\"))\n}\n\n\n\nfunc (rs todosResource) Sync(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tw.Write([]byte(\"todo sync\"))\n}"} {"input": "package actor\n\n\n\ntype restartingStrategy struct{}\n\nfunc (strategy *restartingStrategy) HandleFailure(actorSystem *ActorSystem, supervisor Supervisor, child *PID, rs *RestartStatistics, reason interface{}, message interface{}) {\n\tlogFailure(actorSystem, child, reason, RestartDirective)\n\tsupervisor.RestartChildren(child)\n}\n\nfunc NewRestartingStrategy() SupervisorStrategy ", "output": "{\n\treturn &restartingStrategy{}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t_ \"github.com/go-training/training/example16-init-func/bar\"\n\t_ \"github.com/go-training/training/example16-init-func/foo\"\n)\n\nvar global = convert()\n\nfunc convert() int {\n\treturn 100\n}\n\n\n\nfunc main() {\n\tfmt.Println(\"global is\", global)\n}\n\nfunc init() ", "output": "{\n\tglobal = 0\n}"} {"input": "package main\n\nimport \"github.com/containerd/containerd/cmd/ctr/commands/shim\"\n\n\n\nfunc init() ", "output": "{\n\textraCmds = append(extraCmds, shim.Command)\n}"} {"input": "package filehash\n\nimport (\n\t\"crypto/sha1\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/cloudfoundry/gofileutils/fileutils\"\n)\n\ntype Hash []byte\n\nfunc Zero() Hash {\n\treturn Hash(make([]byte, sha1.Size))\n}\n\n\nfunc New(filePath string) Hash {\n\tfileInfo, err := os.Lstat(filePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif fileInfo.IsDir() {\n\t\tpanic(\"cannot compute hash of directory\")\n\t} else {\n\t\thash := sha1.New()\n\t\terr = fileutils.CopyPathToWriter(filePath, hash)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn Hash(hash.Sum(nil))\n\t}\n}\n\nfunc (k Hash) String() string {\n\treturn fmt.Sprintf(\"%x\", string(k))\n}\n\nfunc StringToHash(s string) Hash {\n\tvar sh string\n\tif _, err := fmt.Sscanf(s, \"%x\", &sh); err != nil {\n\t\tpanic(err)\n\t}\n\treturn Hash(sh)\n}\n\nfunc (h1 Hash) Combine(h2 Hash) {\n\tif len(h1) != len(h2) {\n\t\tpanic(\"Invalid hash length\")\n\t}\n\tfor i, b := range h1 {\n\t\th1[i] = b ^ h2[i]\n\t}\n}\n\n\n\nfunc (h1 Hash) Remove(h2 Hash) ", "output": "{\n\th1.Combine(h2)\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvalidate(\"aaaaa\", \"aaaaa\", true)\n\tvalidate(\"aaaab\", \"aaaab\", true)\n\tvalidate(\"aaaabc\", \"aaaab\", false)\n\tvalidate(\"aaaa\", \"a*\", true)\n\tvalidate(\"aaaabbb\", \"a*bbb\", true)\n}\n\nfunc validate(s string, p string, want bool) {\n\tfmt.Printf(\"s: %s, p: %s, want: %t, got: %t\\n\", s, p, want, IsMatch(s, p))\n}\n\n\n\nfunc IsMatch(s string, p string) bool ", "output": "{\n\tif len(p) == 0 {\n\t\treturn len(s) == 0\n\t}\n\tfirst := len(s) != 0 && (s[0] == p[0] || p[0] == '.')\n\tif len(p) > 1 && p[1] == '*' {\n\t\treturn (first && IsMatch(s[1:], p)) || (IsMatch(s, p[2:]))\n\t}\n\treturn first && IsMatch(s[1:], p[1:])\n}"} {"input": "package conn\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\ntype ConnectRequest struct {\n\tid uint64\n\tAddress net.Addr\n\tPermanent bool\n\tConn net.Conn\n\tstate ConnectState\n\tlock sync.RWMutex\n\tretryCount uint32\n}\n\nfunc (connectRequest *ConnectRequest) updateState(state ConnectState) {\n\tconnectRequest.lock.Lock()\n\tdefer connectRequest.lock.Unlock()\n\tconnectRequest.state = state\n}\n\n\nfunc (connectRequest *ConnectRequest) State() ConnectState {\n\tconnectRequest.lock.RLock()\n\tdefer connectRequest.lock.RUnlock()\n\treturn connectRequest.state\n}\nfunc (connectRequest *ConnectRequest) String() string {\n\tif connectRequest.Address.String() == \"\" {\n\t\treturn fmt.Sprintf(\"reqid %d\", atomic.LoadUint64(&connectRequest.id))\n\t}\n\treturn fmt.Sprintf(\"%s (reqid %d)\", connectRequest.Address, atomic.LoadUint64(&connectRequest.id))\n}\n\nfunc (connectRequest *ConnectRequest) ID() uint64 ", "output": "{\n\treturn atomic.LoadUint64(&connectRequest.id)\n}"} {"input": "package image\n\nimport (\n\t\"github.com/dnephin/dobi/tasks/context\"\n)\n\n\n\n\nfunc RunRemove(ctx *context.ExecuteContext, t *Task, _ bool) (bool, error) ", "output": "{\n\tremoveTag := func(tag string) error {\n\t\tif err := ctx.Client.RemoveImage(tag); err != nil {\n\t\t\tt.logger().Warnf(\"failed to remove %q: %s\", tag, err)\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := t.ForEachTag(ctx, removeTag); err != nil {\n\t\treturn false, err\n\t}\n\n\tif err := updateImageRecord(recordPath(ctx, t.config), imageModifiedRecord{}); err != nil {\n\t\tt.logger().Warnf(\"Failed to clear image record: %s\", err)\n\t}\n\n\tt.logger().Info(\"Removed\")\n\treturn true, nil\n}"} {"input": "package ivona_test\n\nimport (\n\t\"log\"\n\n\tivona \"github.com/jpadilla/ivona-go\"\n)\n\nfunc ExampleIvona_CreateSpeech() {\n\tclient := ivona.New(\"IVONA_ACCESS_KEY\", \"IVONA_SECRET_KEY\")\n\toptions := ivona.NewSpeechOptions(\"Hello World\")\n\tr, err := client.CreateSpeech(options)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Printf(\"%v\\n\", len(r.Audio))\n\tlog.Printf(\"%v\\n\", r.ContentType)\n\tlog.Printf(\"%v\\n\", r.RequestID)\n}\n\n\n\nfunc ExampleIvona_ListVoices() ", "output": "{\n\tclient := ivona.New(\"IVONA_ACCESS_KEY\", \"IVONA_SECRET_KEY\")\n\n\tr, err := client.ListVoices(ivona.Voice{})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Printf(\"%v\\n\", len(r.Voices))\n}"} {"input": "package wire\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\n\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc (w *fixedWriter) Bytes() []byte ", "output": "{\n\treturn w.b\n}"} {"input": "package cloudguard\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype UpdateManagedListRequest struct {\n\n\tManagedListId *string `mandatory:\"true\" contributesTo:\"path\" name:\"managedListId\"`\n\n\tUpdateManagedListDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateManagedListRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request UpdateManagedListRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request UpdateManagedListRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateManagedListResponse struct {\n\n\tRawResponse *http.Response\n\n\tManagedList `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateManagedListResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateManagedListResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateManagedListRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n\t_ \"ServiceTree/docs\"\n\t_ \"ServiceTree/routers\"\n\n\t\"github.com/astaxie/beego\"\n\t\"github.com/astaxie/beego/orm\"\n\t_ \"github.com/go-sql-driver/mysql\"\n)\n\n\n\nfunc main() {\n\tif beego.RunMode == \"dev\" {\n\t\tbeego.DirectoryIndex = true\n\t\tbeego.StaticDir[\"/swagger\"] = \"swagger\"\n\t}\n\tbeego.Run()\n}\n\nfunc init() ", "output": "{\n \n db_type := beego.AppConfig.String(\"database::db_type\")\n db_user := beego.AppConfig.String(\"database::username\")\n db_password := beego.AppConfig.String(\"database::password\")\n db_host := beego.AppConfig.String(\"database::host\")\n db_port := beego.AppConfig.String(\"database::port\")\n db_name := beego.AppConfig.String(\"database::dbname\")\n\n connect_str := fmt.Sprintf(\"%s:%s@tcp(%s:%s)/%s\",db_user, db_password, db_host, db_port, db_name)\n beego.SetLogger(\"file\", `{\"filename\":\"./logs/tree.log\"}`)\n\torm.RegisterDataBase(\"default\", db_type, connect_str)\n}"} {"input": "package os\n\nconst (\n\tPathSeparator = '/' \n\tPathListSeparator = ':' \n)\n\n\n\n\nfunc IsPathSeparator(c uint8) bool ", "output": "{\n\treturn PathSeparator == c\n}"} {"input": "package floatingips\n\nimport \"github.com/gophercloud/gophercloud\"\n\nconst resourcePath = \"floatingips\"\n\nfunc rootURL(c *gophercloud.ServiceClient) string {\n\treturn c.ServiceURL(resourcePath)\n}\n\n\n\nfunc resourceURL(c *gophercloud.ServiceClient, id string) string ", "output": "{\n\treturn c.ServiceURL(resourcePath, id)\n}"} {"input": "package pes\n\nimport \"io\"\nimport \"bytes\"\nimport \"github.com/32bitkid/bitreader\"\n\n\n\n\ntype payloadReader struct {\n\tbr bitreader.BitReader\n\tcurrentPacket *Packet\n\tremainder bytes.Buffer\n}\n\nfunc (r *payloadReader) Read(p []byte) (n int, err error) {\n\tfor len(p) > 0 {\n\t\tcn, err := r.remainder.Read(p)\n\t\tn += cn\n\t\tp = p[cn:]\n\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn n, err\n\t\t}\n\t}\n\n\tvar remainder []byte\n\n\tfor len(p) > 0 {\n\t\terr := r.currentPacket.Next(r.br)\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\n\t\tcn := copy(p, r.currentPacket.Payload)\n\t\tn += cn\n\t\tp = p[cn:]\n\t\tremainder = r.currentPacket.Payload[cn:]\n\t}\n\n\t_, err = r.remainder.Write(remainder)\n\n\treturn\n}\n\nfunc NewPayloadReader(source io.Reader) io.Reader ", "output": "{\n\treturn &payloadReader{\n\t\tbr: bitreader.NewReader(source),\n\t\tcurrentPacket: new(Packet),\n\t}\n}"} {"input": "package Plugin\n\nimport \"github.com/MPjct/GoMP/MySQLProtocol\"\n\ntype Plugin_interface interface {\n\tinit(context MySQLProtocol.Context)\n\tread_handshake(context MySQLProtocol.Context)\n\tsend_handshake(context MySQLProtocol.Context)\n\tread_auth(context MySQLProtocol.Context)\n\tsend_auth(context MySQLProtocol.Context)\n\tread_auth_result(context MySQLProtocol.Context)\n\tsend_auth_result(context MySQLProtocol.Context)\n\tread_query(context MySQLProtocol.Context)\n\tsend_query(context MySQLProtocol.Context)\n\tread_query_result(context MySQLProtocol.Context)\n\tsend_query_result(context MySQLProtocol.Context)\n\tcleanup(context MySQLProtocol.Context)\n}\n\ntype Plugin struct {\n}\n\nfunc (plugin *Plugin) init(context MySQLProtocol.Context) {\n\treturn\n}\n\n\n\nfunc (plugin *Plugin) send_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) cleanup(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_handshake(context MySQLProtocol.Context) ", "output": "{\n\treturn\n}"} {"input": "package builders\n\nimport (\n\t\"time\"\n\n\t\"github.com/docker/docker/api/types\"\n)\n\n\n\nfunc Container(name string, builders ...func(container *types.Container)) *types.Container {\n\tcontainer := &types.Container{\n\t\tID: \"container_id\",\n\t\tNames: []string{\"/\" + name},\n\t\tCommand: \"top\",\n\t\tImage: \"busybox:latest\",\n\t\tStatus: \"Up 1 second\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tfor _, builder := range builders {\n\t\tbuilder(container)\n\t}\n\n\treturn container\n}\n\n\nfunc WithLabel(key, value string) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tif c.Labels == nil {\n\t\t\tc.Labels = map[string]string{}\n\t\t}\n\t\tc.Labels[key] = value\n\t}\n}\n\n\nfunc WithName(name string) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tc.Names = append(c.Names, \"/\"+name)\n\t}\n}\n\n\nfunc WithPort(privateport, publicport uint16, builders ...func(*types.Port)) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tif c.Ports == nil {\n\t\t\tc.Ports = []types.Port{}\n\t\t}\n\t\tport := &types.Port{\n\t\t\tPrivatePort: privateport,\n\t\t\tPublicPort: publicport,\n\t\t}\n\t\tfor _, builder := range builders {\n\t\t\tbuilder(port)\n\t\t}\n\t\tc.Ports = append(c.Ports, *port)\n\t}\n}\n\n\nfunc IP(ip string) func(*types.Port) {\n\treturn func(p *types.Port) {\n\t\tp.IP = ip\n\t}\n}\n\n\nfunc TCP(p *types.Port) {\n\tp.Type = \"tcp\"\n}\n\n\n\n\nfunc UDP(p *types.Port) ", "output": "{\n\tp.Type = \"udp\"\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/bfontaine/go-tchoutchou/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n)\n\ntype SucceedMatcher struct {\n}\n\n\n\nfunc (matcher *SucceedMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn fmt.Sprintf(\"Expected success, but got an error:\\n%s\", format.Object(actual, 1))\n}\n\nfunc (matcher *SucceedMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn \"Expected failure, but got no error.\"\n}\n\nfunc (matcher *SucceedMatcher) Match(actual interface{}) (success bool, err error) ", "output": "{\n\tif actual == nil {\n\t\treturn true, nil\n\t}\n\n\tif isError(actual) {\n\t\treturn false, nil\n\t}\n\n\treturn false, fmt.Errorf(\"Expected an error-type. Got:\\n%s\", format.Object(actual, 1))\n}"} {"input": "package uguis\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n)\n\nconst serviceNameSimplePlayer = \"simplePlayer\"\n\n\ntype simplePlayer struct {\n\tcommand string\n\treqC chan PlayerRequest\n\tresC chan PlayerResponse\n\tclosedReqC chan struct{}\n\tapp *Application\n\tlgr Logger\n}\n\n\nfunc (p *simplePlayer) Play(req PlayerRequest) {\n\tp.reqC <- req\n}\n\n\nfunc (p *simplePlayer) Close() error {\n\tclose(p.reqC)\n\n\t<-p.closedReqC\n\n\treturn nil\n}\n\n\nfunc (p *simplePlayer) ResC() <-chan PlayerResponse {\n\treturn p.resC\n}\n\n\n\n\nfunc (p *simplePlayer) logError(err error) {\n\tp.lgr.Print(NewLog(\n\t\tLogLevelERROR,\n\t\tp.app.Hostname,\n\t\tserviceNameSimplePlayer,\n\t\terr.Error(),\n\t))\n}\n\n\nfunc NewSimplePlayer(\n\tcommand string,\n\tapp *Application,\n\tlgr Logger,\n\topts *SimplePlayerOptions,\n) Player {\n\tif opts == nil {\n\t\topts = &SimplePlayerOptions{}\n\t}\n\topts.setDefaults()\n\n\tp := &simplePlayer{\n\t\tcommand: command,\n\t\treqC: make(chan PlayerRequest, opts.ReqCBfSize),\n\t\tresC: make(chan PlayerResponse, opts.ResCBfSize),\n\t\tclosedReqC: make(chan struct{}),\n\t\tapp: app,\n\t\tlgr: lgr,\n\t}\n\n\tgo p.play()\n\n\treturn p\n}\n\nfunc (p *simplePlayer) play() ", "output": "{\n\tfor req := range p.reqC {\n\t\tp.lgr.Print(NewLog(\n\t\t\tLogLevelINFO,\n\t\t\tp.app.Hostname,\n\t\t\tserviceNameSimplePlayer,\n\t\t\tfmt.Sprintf(\"%s by %s(@%s)\", req.tweet.Text, req.tweet.User.Name, req.tweet.User.ScreenName),\n\t\t))\n\n\t\tpath := req.path\n\n\t\tif err := exec.Command(p.command, path).Run(); err != nil {\n\t\t\tp.logError(err)\n\t\t\tcontinue\n\t\t}\n\t\tp.resC <- NewPlayerResponse(req.tweet, path)\n\t}\n\n\tp.closedReqC <- struct{}{}\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"github.com/docker/distribution/registry/api/errcode\"\n\t\"github.com/docker/distribution/registry/api/v2\"\n)\n\n\n\ntype UnexpectedHTTPStatusError struct {\n\tStatus string\n}\n\nfunc (e *UnexpectedHTTPStatusError) Error() string {\n\treturn fmt.Sprintf(\"Received unexpected HTTP status: %s\", e.Status)\n}\n\n\n\ntype UnexpectedHTTPResponseError struct {\n\tParseErr error\n\tResponse []byte\n}\n\n\n\nfunc parseHTTPErrorResponse(r io.Reader) error {\n\tvar errors errcode.Errors\n\tbody, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(body, &errors); err != nil {\n\t\treturn &UnexpectedHTTPResponseError{\n\t\t\tParseErr: err,\n\t\t\tResponse: body,\n\t\t}\n\t}\n\treturn errors\n}\n\nfunc handleErrorResponse(resp *http.Response) error {\n\tif resp.StatusCode == 401 {\n\t\terr := parseHTTPErrorResponse(resp.Body)\n\t\tif uErr, ok := err.(*UnexpectedHTTPResponseError); ok {\n\t\t\treturn v2.ErrorCodeUnauthorized.WithDetail(uErr.Response)\n\t\t}\n\t\treturn err\n\t}\n\tif resp.StatusCode >= 400 && resp.StatusCode < 500 {\n\t\treturn parseHTTPErrorResponse(resp.Body)\n\t}\n\treturn &UnexpectedHTTPStatusError{Status: resp.Status}\n}\n\nfunc (e *UnexpectedHTTPResponseError) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"Error parsing HTTP response: %s: %q\", e.ParseErr.Error(), string(e.Response))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/unrolled/render\"\n)\n\n\nvar Render *render.Render\n\n\nfunc init() {\n\tRender = render.New(render.Options{\n\t\tIndentJSON: true,\n\t})\n}\n\nfunc index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Welcome to the home page!\")\n}\n\nfunc apiHandler(w http.ResponseWriter, r *http.Request) {\n\tRender.JSON(w, http.StatusOK, \"Welcome to the api hander page!\")\n}\n\n\n\nfunc apiKeyDetailsHandler(w http.ResponseWriter, r *http.Request) {\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the api Key Details hander page! %s\", id)\n}\n\nfunc webKeyHandler(w http.ResponseWriter, r *http.Request) {\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the web Key hander page! %s\", id)\n}\n\nfunc notFound(w http.ResponseWriter, r *http.Request) {\n\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n}\n\nfunc apiKeyHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the api Key hander page! %s\", id)\n}"} {"input": "package fake\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\n\t. \"github.com/onsi/gomega\"\n\t\"github.com/onsi/gomega/ghttp\"\n)\n\ntype CFAPI struct {\n\tserver *ghttp.Server\n}\n\ntype CFAPIConfig struct {\n\tRoutes map[string]Response\n}\n\ntype Response struct {\n\tCode int\n\tBody interface{}\n}\n\nfunc NewCFAPI() *CFAPI {\n\tserver := ghttp.NewServer()\n\treturn &CFAPI{\n\t\tserver: server,\n\t}\n}\n\nfunc (a *CFAPI) SetConfiguration(config CFAPIConfig) {\n\ta.server.Reset()\n\n\tfor request, response := range config.Routes {\n\t\tmethod, path := parseRequest(request)\n\t\tresponseBytes, err := json.Marshal(response.Body)\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\ta.server.RouteToHandler(method, path, ghttp.RespondWith(response.Code, responseBytes))\n\t}\n}\n\n\n\nfunc (a *CFAPI) URL() string {\n\treturn a.server.URL()\n}\n\nfunc (a *CFAPI) ReceivedRequests() map[string][]*http.Request {\n\tresult := map[string][]*http.Request{}\n\n\tfor _, req := range a.server.ReceivedRequests() {\n\t\tkey := fmt.Sprintf(\"%s %s\", req.Method, req.URL.Path)\n\t\tresult[key] = append(result[key], req)\n\t}\n\n\treturn result\n}\n\nfunc parseRequest(request string) (string, string) {\n\tfields := strings.Split(request, \" \")\n\tExpect(fields).To(HaveLen(2))\n\treturn fields[0], fields[1]\n}\n\nfunc (a *CFAPI) Close() ", "output": "{\n\ta.server.Close()\n}"} {"input": "package document\n\ntype IndexingOptions int\n\nconst (\n\tIndexField IndexingOptions = 1 << iota\n\tStoreField\n\tIncludeTermVectors\n)\n\nfunc (o IndexingOptions) IsIndexed() bool {\n\treturn o&IndexField != 0\n}\n\n\n\nfunc (o IndexingOptions) IncludeTermVectors() bool {\n\treturn o&IncludeTermVectors != 0\n}\n\nfunc (o IndexingOptions) String() string {\n\trv := \"\"\n\tif o.IsIndexed() {\n\t\trv += \"INDEXED\"\n\t}\n\tif o.IsStored() {\n\t\tif rv != \"\" {\n\t\t\trv += \", \"\n\t\t}\n\t\trv += \"STORE\"\n\t}\n\tif o.IncludeTermVectors() {\n\t\tif rv != \"\" {\n\t\t\trv += \", \"\n\t\t}\n\t\trv += \"TV\"\n\t}\n\treturn rv\n}\n\nfunc (o IndexingOptions) IsStored() bool ", "output": "{\n\treturn o&StoreField != 0\n}"} {"input": "package log\n\nimport (\n\t\"testing\"\n)\n\ntype testLogger struct {\n\tkeyvals []interface{}\n}\n\n\n\ntype testSink struct {\n\tkeyvals []interface{}\n}\n\nfunc (ts *testSink) Receive(keyvals ...interface{}) error {\n\tts.keyvals = keyvals\n\treturn nil\n}\n\nfunc TestLogger_Log(t *testing.T) {\n\ttl := &testLogger{}\n\tl := NewLogger(tl, nil)\n\n\tl.Log(\"message\", \"value\")\n\tif len(tl.keyvals) != 2 {\n\t\tt.Errorf(\"Expected log message with 2 values, got %v\", len(tl.keyvals))\n\t}\n\n\tm1 := tl.keyvals[0]\n\tm2 := tl.keyvals[1]\n\tif m1.(string) != \"message\" || m2.(string) != \"value\" {\n\t\tt.Errorf(\"Expected [message, value] but got %s\", tl.keyvals)\n\t}\n}\n\nfunc TestLogger_Event(t *testing.T) {\n\tts := &testSink{}\n\ttl := &testLogger{}\n\tl := NewLogger(tl, []EventSink{ts})\n\n\tl.Event(\"important_event\", \"act_on_me\")\n\tif len(ts.keyvals) != 2 {\n\t\tt.Errorf(\"Expected to recieve event with 2 values, got %v\", len(ts.keyvals))\n\t}\n\n\tm1 := ts.keyvals[0]\n\tm2 := ts.keyvals[1]\n\tif m1.(string) != \"important_event\" || m2.(string) != \"act_on_me\" {\n\t\tt.Errorf(\"Expected [important_event, act_on_me] but got %s\", ts.keyvals)\n\t}\n}\n\nfunc (tl *testLogger) Log(keyvals ...interface{}) error ", "output": "{\n\ttl.keyvals = keyvals\n\treturn nil\n}"} {"input": "package tasks\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime/middleware\"\n\t\"github.com/go-openapi/swag\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\n\n\n\n\n\n\ntype DeleteTaskParams struct {\n\n\tHTTPRequest *http.Request\n\n\tID int64\n}\n\n\n\nfunc (o *DeleteTaskParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {\n\tvar res []error\n\to.HTTPRequest = r\n\n\trID, rhkID, _ := route.Params.GetOK(\"id\")\n\tif err := o.bindID(rID, rhkID, route.Formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (o *DeleteTaskParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error {\n\tvar raw string\n\tif len(rawData) > 0 {\n\t\traw = rawData[len(rawData)-1]\n\t}\n\n\tvalue, err := swag.ConvertInt64(raw)\n\tif err != nil {\n\t\treturn errors.InvalidType(\"id\", \"path\", \"int64\", raw)\n\t}\n\to.ID = value\n\n\treturn nil\n}\n\nfunc NewDeleteTaskParams() DeleteTaskParams ", "output": "{\n\tvar ()\n\treturn DeleteTaskParams{}\n}"} {"input": "package pdf417\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\n\t\"github.com/boombuler/barcode\"\n\t\"github.com/boombuler/barcode/utils\"\n)\n\ntype pdfBarcode struct {\n\tdata string\n\twidth int\n\tcode *utils.BitList\n}\n\nfunc (c *pdfBarcode) Metadata() barcode.Metadata {\n\treturn barcode.Metadata{barcode.TypePDF, 2}\n}\n\nfunc (c *pdfBarcode) Content() string {\n\treturn c.data\n}\n\nfunc (c *pdfBarcode) ColorModel() color.Model {\n\treturn color.Gray16Model\n}\n\nfunc (c *pdfBarcode) Bounds() image.Rectangle {\n\theight := c.code.Len() / c.width\n\n\treturn image.Rect(0, 0, c.width, height*moduleHeight)\n}\n\n\n\nfunc (c *pdfBarcode) At(x, y int) color.Color ", "output": "{\n\tif c.code.GetBit((y/moduleHeight)*c.width + x) {\n\t\treturn color.Black\n\t}\n\treturn color.White\n}"} {"input": "package model\n\nimport \"testing\"\n\n\n\nfunc TestLocaleSyncKeys(t *testing.T) ", "output": "{\n\tl := Locale{}\n\n\tl.SyncKeys([]string{\"testkey1\", \"testkey2\"})\n\tif _, ok := l.Pairs[\"testkey1\"]; !ok {\n\t\tt.Fatal(\"expected 'testkey1' to be present\")\n\t}\n\tif _, ok := l.Pairs[\"testkey2\"]; !ok {\n\t\tt.Fatal(\"expected 'testkey2' to be present\")\n\t}\n\n\tl.SyncKeys([]string{\"testkey1\"})\n\tif _, ok := l.Pairs[\"testkey2\"]; ok {\n\t\tt.Fatal(\"expected 'testkey2' to not be present\")\n\t}\n}"} {"input": "package object\n\ntype Error string\n\nfunc (e Error) First() Value {\n\treturn e\n}\n\nfunc (e Error) Rest() Value {\n\treturn e\n}\n\n\n\nfunc (e Error) String() string {\n\treturn string(\"\")\n}\n\nfunc (e Error) Type() Type ", "output": "{\n\treturn ERROR\n}"} {"input": "package readline\n\nimport \"io\"\n\ntype Instance struct {\n\tt *Terminal\n\to *Operation\n}\n\ntype Config struct {\n\tPrompt string\n\tHistoryFile string\n}\n\nfunc NewEx(cfg *Config) (*Instance, error) {\n\tt, err := NewTerminal(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trl := t.Readline()\n\treturn &Instance{\n\t\tt: t,\n\t\to: rl,\n\t}, nil\n}\n\nfunc New(prompt string) (*Instance, error) {\n\treturn NewEx(&Config{Prompt: prompt})\n}\n\nfunc (i *Instance) Stdout() io.Writer {\n\treturn i.o.Stdout()\n}\n\n\n\nfunc (i *Instance) Readline() (string, error) {\n\treturn i.o.String()\n}\n\nfunc (i *Instance) ReadSlice() ([]byte, error) {\n\treturn i.o.Slice()\n}\n\nfunc (i *Instance) Close() error {\n\tif err := i.t.Close(); err != nil {\n\t\treturn err\n\t}\n\ti.o.Close()\n\treturn nil\n}\n\nfunc (i *Instance) Stderr() io.Writer ", "output": "{\n\treturn i.o.Stderr()\n}"} {"input": "package metrics\n\nimport (\n\t\"github.com/cloudfoundry/dropsonde/metric_sender\"\n)\n\nvar metricSender metric_sender.MetricSender\nvar metricBatcher MetricBatcher\n\ntype MetricBatcher interface {\n\tBatchIncrementCounter(name string)\n\tBatchAddCounter(name string, delta uint64)\n\tClose()\n}\n\n\nfunc Initialize(ms metric_sender.MetricSender, mb MetricBatcher) {\n\tif metricBatcher != nil {\n\t\tmetricBatcher.Close()\n\t}\n\tmetricSender = ms\n\tmetricBatcher = mb\n}\n\n\nfunc Close() {\n\tmetricBatcher.Close()\n}\n\n\n\nfunc SendValue(name string, value float64, unit string) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.SendValue(name, value, unit)\n}\n\n\n\n\nfunc IncrementCounter(name string) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.IncrementCounter(name)\n}\n\n\n\n\nfunc BatchIncrementCounter(name string) {\n\tif metricBatcher == nil {\n\t\treturn\n\t}\n\tmetricBatcher.BatchIncrementCounter(name)\n}\n\n\n\n\nfunc AddToCounter(name string, delta uint64) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.AddToCounter(name, delta)\n}\n\n\n\n\n\n\n\n\n\n\nfunc SendContainerMetric(applicationId string, instanceIndex int32, cpuPercentage float64, memoryBytes uint64, diskBytes uint64) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\n\treturn metricSender.SendContainerMetric(applicationId, instanceIndex, cpuPercentage, memoryBytes, diskBytes)\n}\n\nfunc BatchAddCounter(name string, delta uint64) ", "output": "{\n\tif metricBatcher == nil {\n\t\treturn\n\t}\n\tmetricBatcher.BatchAddCounter(name, delta)\n}"} {"input": "package vox\n\ntype Block uint8\n\nconst (\n\tBlockNil = 0x00\n\tblockActiveMask = 0x80 \n\tblockTypeMask = 0x7F \n)\n\nfunc (b Block) Active() bool {\n\treturn (blockActiveMask & b) == blockActiveMask\n}\n\nfunc (b Block) Activate(active bool) Block {\n\tif active {\n\t\treturn b | blockActiveMask\n\t}\n\treturn b & blockTypeMask\n}\n\nfunc (b Block) TypeID() uint8 {\n\treturn uint8(b & blockTypeMask)\n}\n\nfunc (b Block) ChangeType(t *BlockType) Block {\n\treturn Block((uint8(b) & blockActiveMask) | t.ID)\n}\n\ntype BlockType struct {\n\tID uint8\n\tTop *TextureRegion\n\tBottom *TextureRegion\n\tSide *TextureRegion\n}\n\ntype BlockBank struct {\n\tTypes []*BlockType\n\ttypeMap map[uint8]*BlockType\n}\n\n\n\nfunc (b *BlockBank) AddType(blockType *BlockType) {\n\tb.typeMap[blockType.ID] = blockType\n\tb.Types = append(b.Types, blockType)\n}\n\nfunc (b *BlockBank) TypeOf(block Block) *BlockType {\n\treturn b.typeMap[block.TypeID()]\n}\n\nfunc NewBlockBank() *BlockBank ", "output": "{\n\treturn &BlockBank{\n\t\ttypeMap: make(map[uint8]*BlockType),\n\t}\n}"} {"input": "package bauth_test\n\nimport (\n\t\"github.com/insionng/macross\"\n\t\"github.com/insionng/macross/bauth\"\n\t\"testing\"\n)\n\n\n\nfunc TestBasicAuth(t *testing.T) ", "output": "{\n\tm := macross.New()\n\tm.Use(bauth.BasicAuth(func(username, password string) bool {\n\t\tif username == \"inson\" && password == \"secret\" {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}))\n\n\tgo m.Run(\":9999\")\n}"} {"input": "package ast\n\nimport (\n\t\"fmt\"\n\t\"github.com/rhysd/gocaml/token\"\n\t\"github.com/rhysd/locerr\"\n)\n\n\ntype printPath struct {\n\ttotal int\n}\n\n\nfunc (v *printPath) VisitTopdown(e Expr) Visitor {\n\tfmt.Printf(\"\\n -> %s (topdown)\", e.Name())\n\treturn v\n}\n\n\n\n\nfunc Example() {\n\tsrc := locerr.NewDummySource(\"\")\n\n\trootOfAST := &Let{\n\t\tLetToken: &token.Token{File: src},\n\t\tSymbol: NewSymbol(\"test\"),\n\t\tBound: &Int{\n\t\t\tToken: &token.Token{File: src},\n\t\t\tValue: 42,\n\t\t},\n\t\tBody: &Add{\n\t\t\tLeft: &VarRef{\n\t\t\t\tToken: &token.Token{File: src},\n\t\t\t\tSymbol: NewSymbol(\"test\"),\n\t\t\t},\n\t\t\tRight: &Float{\n\t\t\t\tToken: &token.Token{File: src},\n\t\t\t\tValue: 3.14,\n\t\t\t},\n\t\t},\n\t}\n\n\tast := &AST{Root: rootOfAST}\n\n\tv := &printPath{0}\n\tfmt.Println(\"ROOT\")\n\n\tVisit(v, ast.Root)\n\n\tPrintln(ast)\n}\n\nfunc (v *printPath) VisitBottomup(e Expr) ", "output": "{\n\tfmt.Printf(\"\\n -> %s (bottomup)\", e.Name())\n}"} {"input": "package jail\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n)\n\ntype logReader struct {\n\tfilename string\n\tfile *os.File\n\treader *bufio.Reader\n\tlines chan string\n\terrors chan error\n}\n\nfunc newLogReader(filename string) *logReader {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil\n\t}\n\n\tr := bufio.NewReader(f)\n\n\treturn &logReader{\n\t\tfilename: filename,\n\t\tfile: f,\n\t\treader: r,\n\t\tlines: make(chan string),\n\t\terrors: make(chan error),\n\t}\n}\n\n\nfunc (l *logReader) reset() {\n\tf, err := os.Open(l.filename)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tr := bufio.NewReader(f)\n\tl.reader.Reset(r)\n}\n\nfunc (l *logReader) readLine() ", "output": "{\n\tline, err := l.reader.ReadString('\\n')\n\tif err != nil {\n\t\tgo func() {\n\t\t\tl.errors <- err\n\t\t}()\n\t}\n\n\tif line != \"\" {\n\t\tgo func() {\n\t\t\tl.lines <- line\n\t\t}()\n\t}\n}"} {"input": "package issues\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"code.gitea.io/gitea/models/unittest\"\n)\n\n\n\nfunc TestMain(m *testing.M) ", "output": "{\n\tunittest.MainTest(m, filepath.Join(\"..\", \"..\"), \"\")\n}"} {"input": "package btcd\n\nimport (\n\t\"os\"\n\t\"os/user\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\n\n\n\n\nfunc appDataDir(goos, appName string, roaming bool) string {\n\tif appName == \"\" || appName == \".\" {\n\t\treturn \".\"\n\t}\n\n\tif strings.HasPrefix(appName, \".\") {\n\t\tappName = appName[1:]\n\t}\n\tappNameUpper := string(unicode.ToUpper(rune(appName[0]))) + appName[1:]\n\tappNameLower := string(unicode.ToLower(rune(appName[0]))) + appName[1:]\n\n\tvar homeDir string\n\tusr, err := user.Current()\n\tif err == nil {\n\t\thomeDir = usr.HomeDir\n\t}\n\n\tif err != nil || homeDir == \"\" {\n\t\thomeDir = os.Getenv(\"HOME\")\n\t}\n\n\tswitch goos {\n\tcase \"windows\":\n\t\tappData := os.Getenv(\"LOCALAPPDATA\")\n\t\tif roaming || appData == \"\" {\n\t\t\tappData = os.Getenv(\"APPDATA\")\n\t\t}\n\n\t\tif appData != \"\" {\n\t\t\treturn filepath.Join(appData, appNameUpper)\n\t\t}\n\n\tcase \"darwin\":\n\t\tif homeDir != \"\" {\n\t\t\treturn filepath.Join(homeDir, \"Library\",\n\t\t\t\t\"Application Support\", appNameUpper)\n\t\t}\n\n\tcase \"plan9\":\n\t\tif homeDir != \"\" {\n\t\t\treturn filepath.Join(homeDir, appNameLower)\n\t\t}\n\n\tdefault:\n\t\tif homeDir != \"\" {\n\t\t\treturn filepath.Join(homeDir, \".\"+appNameLower)\n\t\t}\n\t}\n\n\treturn \".\"\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc AppDataDir(appName string, roaming bool) string ", "output": "{\n\treturn appDataDir(runtime.GOOS, appName, roaming)\n}"} {"input": "package helper\n\nimport (\n\t\"bufio\"\n\t\"net\"\n)\n\ntype BufConn struct {\n\tnet.Conn\n\tBR *bufio.Reader\n}\n\nfunc (c *BufConn) Peek(n int) ([]byte, error) {\n\treturn c.BR.Peek(n)\n}\n\nfunc (c *BufConn) Read(b []byte) (n int, err error) {\n\treturn c.BR.Read(b)\n}\n\nfunc (c *BufConn) Write(b []byte) (n int, err error) {\n\treturn c.Conn.Write(b)\n}\n\n\n\nfunc NewBufConn(c net.Conn, r *bufio.Reader) *BufConn {\n\tconn := &BufConn{Conn: c}\n\tconn.BR = r\n\tif nil == r {\n\t\tconn.BR = bufio.NewReader(c)\n\t}\n\treturn conn\n}\n\nfunc (c *BufConn) Reset(conn net.Conn) ", "output": "{\n\tc.Conn = conn\n}"} {"input": "package main\n\nfunc f(int) {}\n\n\n\nfunc h(int, int) {}\n\nfunc main() {\n\tf(g()) \n\tf(true) \n\th(true, true) \n}\n\nfunc g() bool ", "output": "{ return true }"} {"input": "package glib\n\n\n\n\n\nimport \"C\"\nimport \"unsafe\"\n\n\n\ntype IActionMap interface {\n\tNative() uintptr\n\n\tLookupAction(actionName string) *Action\n\tAddAction(action IAction)\n\tRemoveAction(actionName string)\n}\n\n\ntype ActionMap struct {\n\t*Object\n}\n\n\n\n\n\n\n\nfunc (v *ActionMap) Native() uintptr {\n\treturn uintptr(unsafe.Pointer(v.native()))\n}\n\nfunc marshalActionMap(p uintptr) (interface{}, error) {\n\tc := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))\n\treturn wrapActionMap(wrapObject(unsafe.Pointer(c))), nil\n}\n\nfunc wrapActionMap(obj *Object) *ActionMap {\n\treturn &ActionMap{obj}\n}\n\n\nfunc (v *ActionMap) LookupAction(actionName string) *Action {\n\tc := C.g_action_map_lookup_action(v.native(), (*C.gchar)(C.CString(actionName)))\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn wrapAction(wrapObject(unsafe.Pointer(c)))\n}\n\n\nfunc (v *ActionMap) AddAction(action IAction) {\n\tC.g_action_map_add_action(v.native(), action.toGAction())\n}\n\n\nfunc (v *ActionMap) RemoveAction(actionName string) {\n\tC.g_action_map_remove_action(v.native(), (*C.gchar)(C.CString(actionName)))\n}\n\nfunc (v *ActionMap) native() *C.GActionMap ", "output": "{\n\tif v == nil || v.GObject == nil {\n\t\treturn nil\n\t}\n\treturn C.toGActionMap(unsafe.Pointer(v.GObject))\n}"} {"input": "package lib\n\nimport \"sync\"\n\n\n\ntype ConcurrentPrinterMap struct {\n\tbyCUPSName map[string]Printer\n\tbyGCPID map[string]Printer\n\tmutex sync.RWMutex\n}\n\n\nfunc NewConcurrentPrinterMap(printers []Printer) *ConcurrentPrinterMap {\n\tcpm := ConcurrentPrinterMap{}\n\tcpm.Refresh(printers)\n\treturn &cpm\n}\n\n\n\n\n\n\n\nfunc (cpm *ConcurrentPrinterMap) GetByCUPSName(name string) (Printer, bool) {\n\tcpm.mutex.RLock()\n\tdefer cpm.mutex.RUnlock()\n\n\tif p, exists := cpm.byCUPSName[name]; exists {\n\t\treturn p, true\n\t}\n\treturn Printer{}, false\n}\n\n\n\n\nfunc (cpm *ConcurrentPrinterMap) GetByGCPID(gcpID string) (Printer, bool) {\n\tcpm.mutex.RLock()\n\tdefer cpm.mutex.RUnlock()\n\n\tif p, exists := cpm.byGCPID[gcpID]; exists {\n\t\treturn p, true\n\t}\n\treturn Printer{}, false\n}\n\n\nfunc (cpm *ConcurrentPrinterMap) GetAll() []Printer {\n\tcpm.mutex.RLock()\n\tdefer cpm.mutex.RUnlock()\n\n\tprinters := make([]Printer, len(cpm.byCUPSName))\n\ti := 0\n\tfor _, printer := range cpm.byCUPSName {\n\t\tprinters[i] = printer\n\t\ti++\n\t}\n\n\treturn printers\n}\n\nfunc (cpm *ConcurrentPrinterMap) Refresh(newPrinters []Printer) ", "output": "{\n\tc := make(map[string]Printer, len(newPrinters))\n\tfor _, printer := range newPrinters {\n\t\tc[printer.Name] = printer\n\t}\n\n\tg := make(map[string]Printer, len(newPrinters))\n\tfor _, printer := range newPrinters {\n\t\tif len(printer.GCPID) > 0 {\n\t\t\tg[printer.GCPID] = printer\n\t\t}\n\t}\n\n\tcpm.mutex.Lock()\n\tdefer cpm.mutex.Unlock()\n\n\tcpm.byCUPSName = c\n\tcpm.byGCPID = g\n}"} {"input": "package astar\n\nimport (\n\t\"os\"\n\t\"image\"\n)\n\nimport _ \"image/png\"\n\n\n\nfunc parseImage(img image.Image) MapData {\n\tmax := uint32(65536-1) \n\n\tbounds := img.Bounds()\n\tmap_data := NewMapData(bounds.Max.X, bounds.Max.Y)\n\tfor y := bounds.Min.Y; y < bounds.Max.Y; y++ {\n\t\tfor x := bounds.Min.X; x < bounds.Max.X; x++ {\n\t\t\tr, g, b, a := img.At(x, y).RGBA()\n\n\t\t\tif(r == max && g == max && b == max && a == max) {\n\t\t\t\tmap_data[x][bounds.Max.Y-1-y] = LAND\n\t\t\t} else {\n\t\t\t\tmap_data[x][bounds.Max.Y-1-y] = WALL\n\t\t\t}\n\t\t}\n\t}\n\treturn map_data\n}\n\nfunc GetMapFromImage(filename string) MapData {\n\timg := openImage(filename)\n\tif(img == nil) {\n\t\treturn nil\n\t}\n\treturn parseImage(img)\n}\n\nfunc openImage(filename string) (image.Image) ", "output": "{\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer f.Close()\n\timg, _, _ := image.Decode(f)\n\treturn img\n}"} {"input": "package centos\n\nimport (\n\t\"github.com/megamsys/libmegdc/templates\"\n\n\t\"github.com/megamsys/urknall\"\n\n)\n\nvar centoshostinfo *CentosHostInfo\n\nfunc init() {\n\tcentoshostinfo = &CentosHostInfo{}\n\ttemplates.Register(\"CentosHostInfo\", centoshostinfo)\n}\n\ntype CentosHostInfo struct{}\n\n\n\nfunc (tpl *CentosHostInfo) Options(t *templates.Template) {\n}\n\nfunc (tpl *CentosHostInfo) Run(target urknall.Target,inputs map[string]string) error {\n\treturn urknall.Run(target, &CentosHostInfo{},inputs)\n}\n\ntype CentosHostInfoTemplate struct{}\n\nfunc (m *CentosHostInfoTemplate) Render(pkg urknall.Package) {\n\tpkg.AddCommands(\"disk\",\n\t\tShell(\"df -h\"),\n\t)\n\tpkg.AddCommands(\"memory\",\n\t\tShell(\"free -m\"),\n\t)\n\tpkg.AddCommands(\"blockdevices\",\n\t\tShell(\"lsblk\"),\n\t)\n\tpkg.AddCommands(\"cpu\",\n\t\tShell(\"lscpu\"),\n\t)\n\tpkg.AddCommands(\"hostname\",\n\t\tShell(\"hostname\"),\n\t)\n\tpkg.AddCommands(\"dnsserver\",\n\t\tShell(\"cat /etc/resolv.conf\"),\n\t)\n\tpkg.AddCommands(\"ipaddress\",\n\t\tShell(\"yum install -y net-tools\"),\n\t\tShell(\"ifconfig\"),\n\t)\n\tpkg.AddCommands(\"bridge\",\n \t\t Shell(\"if /sbin/brctl ; then brctl show; else echo 'no bridge is available'; fi\"),\n \t )\n}\n\nfunc (tpl *CentosHostInfo) Render(p urknall.Package) ", "output": "{\n\tp.AddTemplate(\"hostinfo\", &CentosHostInfoTemplate{})\n}"} {"input": "package TeleGogo\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n)\n\n\n\nfunc responseToTgError(response *http.Response) TelegramError {\n\tdefer response.Body.Close()\n\ttgErr := telegramError{}\n\tjson.NewDecoder(response.Body).Decode(&tgErr)\n\treturn tgErr\n}\n\nfunc errToTelegramErr(err error) TelegramError {\n\treturn telegramError{OK: false, ErrorCode: 0, Description: err.Error()}\n}\n\ntype telegramError struct {\n\tOK bool `json:\"ok\"`\n\tErrorCode int `json:\"error_code\"`\n\tDescription string `json:\"description\"`\n}\n\nfunc (t telegramError) IsOK() bool {\n\treturn t.OK\n}\n\nfunc (t telegramError) ErrCode() int {\n\treturn t.ErrorCode\n}\n\nfunc (t telegramError) Error() string {\n\treturn t.Description\n}\n\n\ntype TelegramError interface {\n\tIsOK() bool\n\tErrCode() int\n\tError() string\n}\n\nfunc responseToError(response *http.Response) error ", "output": "{\n\treturn responseToTgError(response)\n}"} {"input": "package lock\n\nimport (\n\t\"os\"\n)\n\ntype LockedFile interface {\n\tFile() *os.File\n\tExclusive() bool\n\tClose() error\n}\n\ntype DefaultLockedFile struct {\n\tf *os.File\n\texclusive bool\n}\n\nfunc OpenExclusive(path string, flag int, perm os.FileMode) (LockedFile, error) {\n\treturn open(path, flag, perm, true)\n}\n\nfunc OpenShared(path string, flag int, perm os.FileMode) (LockedFile, error) {\n\treturn open(path, flag, perm, false)\n}\n\nfunc (e *DefaultLockedFile) File() *os.File {\n\treturn e.f\n}\n\n\n\nfunc (e *DefaultLockedFile) Close() error {\n\terr := e.unlock()\n\terr2 := e.f.Close()\n\tif err2 != nil && err == nil {\n\t\terr = err2\n\t}\n\treturn err\n}\n\nfunc (e *DefaultLockedFile) Exclusive() bool ", "output": "{\n\treturn e.exclusive\n}"} {"input": "package treemap\n\nimport \"github.com/emirpasic/gods/containers\"\n\n\n\n\nfunc (m *Map) ToJSON() ([]byte, error) {\n\treturn m.tree.ToJSON()\n}\n\n\nfunc (m *Map) FromJSON(data []byte) error {\n\treturn m.tree.FromJSON(data)\n}\n\nfunc assertSerializationImplementation() ", "output": "{\n\tvar _ containers.JSONSerializer = (*Map)(nil)\n\tvar _ containers.JSONDeserializer = (*Map)(nil)\n}"} {"input": "package main\n\nimport \"./buildings\"\n\n\nvar board [2][2][][]buildings.Building \nfunc bget(x, y int) buildings.Building {\n\txIndex, yIndex := 0, 0 \n\tif x < 0 {\n\t\txIndex = 1\n\t\tx = -x\n\t}\n\tif y < 0 {\n\t\tyIndex = 1\n\t\ty = -y\n\t}\n\treturn board[xIndex][yIndex][x][y]\n}\nfunc bset(x, y int, b buildings.Building) {\n\txIndex, yIndex := 0, 0\n\tif x < 0 {\n\t\txIndex = 1\n\t\tx = -x\n\t}\n\tif y < 0 {\n\t\tyIndex = 1\n\t\ty = -y\n\t}\n\tboard[xIndex][yIndex][x][y] = b\n}\nfunc badd(x, y int, b buildings.Building) { \n\txIndex, yIndex := 0, 0\n\tif x < 0 {\n\t\txIndex = 1\n\t\tx = -x\n\t}\n\tif y < 0 {\n\t\tyIndex = 1\n\t\ty = -y\n\t}\n\tif cap(board[xIndex][yIndex]) < x {\n\t\tslice2 := make([][]buildings.Building, len(board[xIndex][yIndex]), x+4) \n\t\tcopy(slice2, board[xIndex][yIndex])\n\t\tboard[xIndex][yIndex] = slice2\n\t}\n\tif cap(board[xIndex][yIndex][x]) < y {\n\t\tslice2 := make([]buildings.Building, len(board[xIndex][yIndex][x]), x+4) \n\t\tcopy(slice2, board[xIndex][yIndex][x])\n\t\tboard[xIndex][yIndex][x] = slice2\n\t}\n\tboard[xIndex][yIndex][x][y] = b\n}\n\n\nfunc bForEach(f func(buildings.Building, int, int)) ", "output": "{\n\tfor xIndex := 0; xIndex <= 1; xIndex++ {\n\t\tfor yIndex := 0; yIndex <= 1; yIndex++ {\n\t\t\tfor x := xIndex; x < len(board[xIndex][yIndex]); x++ {\n\t\t\t\tfor y := yIndex; y < len(board[xIndex][yIndex][x]); y++ {\n\t\t\t\t\tf(board[xIndex][yIndex][x][y], x, y)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package auth\n\nimport (\n\t\"encoding/base64\"\n\t\"github.com/outbrain/orchestrator/Godeps/_workspace/src/github.com/go-martini/martini\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n\ntype User string\n\n\nvar BasicRealm = \"Authorization Required\"\n\n\n\nfunc Basic(username string, password string) martini.Handler {\n\tvar siteAuth = base64.StdEncoding.EncodeToString([]byte(username + \":\" + password))\n\treturn func(res http.ResponseWriter, req *http.Request, c martini.Context) {\n\t\tauth := req.Header.Get(\"Authorization\")\n\t\tif !SecureCompare(auth, \"Basic \"+siteAuth) {\n\t\t\tunauthorized(res)\n\t\t\treturn\n\t\t}\n\t\tc.Map(User(username))\n\t}\n}\n\n\n\nfunc BasicFunc(authfn func(string, string) bool) martini.Handler {\n\treturn func(res http.ResponseWriter, req *http.Request, c martini.Context) {\n\t\tauth := req.Header.Get(\"Authorization\")\n\t\tif len(auth) < 6 || auth[:6] != \"Basic \" {\n\t\t\tunauthorized(res)\n\t\t\treturn\n\t\t}\n\t\tb, err := base64.StdEncoding.DecodeString(auth[6:])\n\t\tif err != nil {\n\t\t\tunauthorized(res)\n\t\t\treturn\n\t\t}\n\t\ttokens := strings.SplitN(string(b), \":\", 2)\n\t\tif len(tokens) != 2 || !authfn(tokens[0], tokens[1]) {\n\t\t\tunauthorized(res)\n\t\t\treturn\n\t\t}\n\t\tc.Map(User(tokens[0]))\n\t}\n}\n\n\n\nfunc unauthorized(res http.ResponseWriter) ", "output": "{\n\tres.Header().Set(\"WWW-Authenticate\", \"Basic realm=\\\"\"+BasicRealm+\"\\\"\")\n\thttp.Error(res, \"Not Authorized\", http.StatusUnauthorized)\n}"} {"input": "package dom\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\ntype Node interface {\n\tString() string\n\tParent() Node\n\tSetParent(node Node)\n\tChildren() []Node\n\tAddChild(child Node)\n\tClone() Node\n}\n\n\ntype Element struct {\n\ttext string\n\tparent Node\n\tchildren []Node\n}\n\n\nfunc NewElement(text string) *Element {\n\treturn &Element{\n\t\ttext: text,\n\t\tparent: nil,\n\t\tchildren: make([]Node, 0),\n\t}\n}\n\n\nfunc (e *Element) Parent() Node {\n\treturn e.parent\n}\n\n\nfunc (e *Element) SetParent(node Node) {\n\te.parent = node\n}\n\n\nfunc (e *Element) Children() []Node {\n\treturn e.children\n}\n\n\nfunc (e *Element) AddChild(child Node) {\n\tcopy := child.Clone()\n\tcopy.SetParent(e)\n\te.children = append(e.children, copy)\n}\n\n\n\n\n\n\nfunc (e *Element) String() string {\n\tbuffer := bytes.NewBufferString(e.text)\n\n\tfor _, c := range e.Children() {\n\t\ttext := c.String()\n\t\tfmt.Fprintf(buffer, \"\\n %s\", text)\n\t}\n\n\treturn buffer.String()\n}\n\nfunc (e *Element) Clone() Node ", "output": "{\n\tcopy := &Element{\n\t\ttext: e.text,\n\t\tparent: nil,\n\t\tchildren: make([]Node, 0),\n\t}\n\tfor _, child := range e.children {\n\t\tcopy.AddChild(child)\n\t}\n\treturn copy\n}"} {"input": "package getter\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/goharbor/harbor/src/lib/orm\"\n\t\"github.com/goharbor/harbor/src/pkg/joblog\"\n\n\t\"github.com/goharbor/harbor/src/jobservice/errs\"\n)\n\n\ntype DBGetter struct {\n}\n\n\nfunc NewDBGetter() *DBGetter {\n\treturn &DBGetter{}\n}\n\n\n\n\nfunc (dbg *DBGetter) Retrieve(logID string) ([]byte, error) ", "output": "{\n\tif len(logID) == 0 {\n\t\treturn nil, errors.New(\"empty log identify\")\n\t}\n\n\tjobLog, err := joblog.Mgr.Get(orm.Context(), logID)\n\tif err != nil {\n\t\treturn nil, errs.NoObjectFoundError(fmt.Sprintf(\"log entity: %s\", logID))\n\t}\n\n\treturn []byte(jobLog.Content), nil\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestAvgScore(t *testing.T) ", "output": "{\n\tscores := []int{30, 60, 80, 100}\n\texp := 67\n\tact := avgScore(scores)\n\tif exp != act {\n\t\tt.Error(\"Expected\", exp, \"got\", act)\n\t}\n\n}"} {"input": "package drive\n\nimport (\n\t\"camlistore.org/pkg/blob\"\n)\n\n\n\nfunc (sto *driveStorage) StatBlobs(dest chan<- blob.SizedRef, blobs []blob.Ref) error ", "output": "{\n\tfor _, br := range blobs {\n\t\tsize, err := sto.service.Stat(br.String())\n\t\tif err == nil {\n\t\t\tdest <- blob.SizedRef{Ref: br, Size: size}\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package obj\n\nimport \"fmt\"\n\nconst _SymKind_name = \"SxxxSTEXTSELFRXSECTSTYPESSTRINGSGOSTRINGSGOFUNCSGCBITSSRODATASFUNCTABSELFROSECTSMACHOPLTSTYPERELROSSTRINGRELROSGOSTRINGRELROSGOFUNCRELROSGCBITSRELROSRODATARELROSFUNCTABRELROSTYPELINKSITABLINKSSYMTABSPCLNTABSELFSECTSMACHOSMACHOGOTSWINDOWSSELFGOTSNOPTRDATASINITARRSDATASBSSSNOPTRBSSSTLSBSSSXREFSMACHOSYMSTRSMACHOSYMTABSMACHOINDIRECTPLTSMACHOINDIRECTGOTSFILESFILEPATHSCONSTSDYNIMPORTSHOSTOBJSDWARFSECTSDWARFINFO\"\n\nvar _SymKind_index = [...]uint16{0, 4, 9, 19, 24, 31, 40, 47, 54, 61, 69, 79, 88, 98, 110, 124, 136, 148, 160, 173, 182, 191, 198, 206, 214, 220, 229, 237, 244, 254, 262, 267, 271, 280, 287, 292, 304, 316, 333, 350, 355, 364, 370, 380, 388, 398, 408}\n\n\n\nfunc (i SymKind) String() string ", "output": "{\n\tif i < 0 || i >= SymKind(len(_SymKind_index)-1) {\n\t\treturn fmt.Sprintf(\"SymKind(%d)\", i)\n\t}\n\treturn _SymKind_name[_SymKind_index[i]:_SymKind_index[i+1]]\n}"} {"input": "package validating\n\nimport (\n\t\"io\"\n\n\t\"k8s.io/apiserver/pkg/admission\"\n\t\"k8s.io/apiserver/pkg/admission/configuration\"\n\t\"k8s.io/apiserver/pkg/admission/plugin/webhook/generic\"\n)\n\nconst (\n\tPluginName = \"ValidatingAdmissionWebhook\"\n)\n\n\n\n\n\ntype Plugin struct {\n\t*generic.Webhook\n}\n\nvar _ admission.ValidationInterface = &Plugin{}\n\n\nfunc NewValidatingAdmissionWebhook(configFile io.Reader) (*Plugin, error) {\n\thandler := admission.NewHandler(admission.Connect, admission.Create, admission.Delete, admission.Update)\n\twebhook, err := generic.NewWebhook(handler, configFile, configuration.NewValidatingWebhookConfigurationManager, newValidatingDispatcher)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Plugin{webhook}, nil\n}\n\n\nfunc (a *Plugin) Validate(attr admission.Attributes) error {\n\treturn a.Webhook.Dispatch(attr)\n}\n\nfunc Register(plugins *admission.Plugins) ", "output": "{\n\tplugins.Register(PluginName, func(configFile io.Reader) (admission.Interface, error) {\n\t\tplugin, err := NewValidatingAdmissionWebhook(configFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn plugin, nil\n\t})\n}"} {"input": "package servo_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n\t\"github.com/fgrosse/servo\"\n\t\"fmt\"\n)\n\nfunc TestServo(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Servo Test Suite\")\n}\n\ntype TestBundle struct {}\n\nfunc (b *TestBundle) Boot(kernel *servo.Kernel) {\n\tkernel.RegisterType(\"test_bundle.my_type\", NewService)\n}\n\ntype SomeService struct {}\n\n\n\nfunc NewService() *SomeService {\n\treturn &SomeService{}\n}\n\nfunc NewServiceWithParam(param interface{}) *SomeService {\n\tpanic(param)\n\treturn &SomeService{}\n}\n\n\ntype ServerMock struct {\n\tRunHasBeenCalled bool\n\tReturnError bool\n\n\tParameter1, Parameter2 string\n}\n\nfunc NewServerMockWithParams(param1, param2 string) *ServerMock {\n\tExpect(param1).To(Equal(\"foo\"), `NewServerMockWithParams should always be called with the values \"foo\" and \"bar\"`)\n\tExpect(param2).To(Equal(\"bar\"), `NewServerMockWithParams should always be called with the values \"foo\" and \"bar\"`)\n\n\treturn &ServerMock{\n\t\tParameter1: param1,\n\t\tParameter2: param2,\n\t}\n}\n\nfunc (s *ServerMock) Run() error {\n\ts.RunHasBeenCalled = true\n\tif s.ReturnError {\n\t\treturn fmt.Errorf(\"ServerMock was told to return an error!\")\n\t}\n\n\treturn nil\n}\n\nfunc NewRecursiveService(*SomeService) *SomeService ", "output": "{\n\treturn &SomeService{}\n}"} {"input": "package chart\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/golang/protobuf/jsonpb\"\n)\n\n\nfunc (msg *Config) MarshalJSON() ([]byte, error) {\n\tvar buf bytes.Buffer\n\terr := (&jsonpb.Marshaler{\n\t\tEnumsAsInts: false,\n\t\tEmitDefaults: false,\n\t\tOrigName: false,\n\t}).Marshal(&buf, msg)\n\treturn buf.Bytes(), err\n}\n\n\n\n\n\nfunc (msg *Value) MarshalJSON() ([]byte, error) {\n\tvar buf bytes.Buffer\n\terr := (&jsonpb.Marshaler{\n\t\tEnumsAsInts: false,\n\t\tEmitDefaults: false,\n\t\tOrigName: false,\n\t}).Marshal(&buf, msg)\n\treturn buf.Bytes(), err\n}\n\n\nfunc (msg *Value) UnmarshalJSON(b []byte) error {\n\treturn (&jsonpb.Unmarshaler{\n\t\tAllowUnknownFields: false,\n\t}).Unmarshal(bytes.NewReader(b), msg)\n}\n\nfunc (msg *Config) UnmarshalJSON(b []byte) error ", "output": "{\n\treturn (&jsonpb.Unmarshaler{\n\t\tAllowUnknownFields: false,\n\t}).Unmarshal(bytes.NewReader(b), msg)\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/SaferLuo/EtherIOT/node\"\n\t\"github.com/SaferLuo/EtherIOT/rpc\"\n\t\"gopkg.in/urfave/cli.v1\"\n)\n\n\n\nfunc NewRemoteRPCClient(ctx *cli.Context) (rpc.Client, error) {\n\tif ctx.Args().Present() {\n\t\tendpoint := ctx.Args().First()\n\t\treturn NewRemoteRPCClientFromString(endpoint)\n\t}\n\treturn rpc.NewIPCClient(node.DefaultIPCEndpoint())\n}\n\n\n\n\n\nfunc NewRemoteRPCClientFromString(endpoint string) (rpc.Client, error) ", "output": "{\n\tif strings.HasPrefix(endpoint, \"ipc:\") {\n\t\treturn rpc.NewIPCClient(endpoint[4:])\n\t}\n\tif strings.HasPrefix(endpoint, \"rpc:\") {\n\t\treturn rpc.NewHTTPClient(endpoint[4:])\n\t}\n\tif strings.HasPrefix(endpoint, \"http:\") {\n\t\treturn rpc.NewHTTPClient(endpoint)\n\t}\n\tif strings.HasPrefix(endpoint, \"ws:\") {\n\t\treturn rpc.NewWSClient(endpoint)\n\t}\n\treturn nil, fmt.Errorf(\"invalid endpoint\")\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\trmbNum := make(map[int]int)\n\tonly89 := []int{}\n\trmbNum[89] = 89\n\trmbNum[1] = 1\n\tfor i := 1; i < 10000000; i++ {\n\t\tyes := false\n\t\trmbSeq := []int{}\n\t\tfor num := i; ; num = findNext(num) {\n\t\t\trmbSeq = append(rmbSeq, num)\n\t\t\tif val, ok := rmbNum[num]; ok {\n\t\t\t\tif val == 89 {\n\t\t\t\t\tfor _, r := range rmbSeq {\n\t\t\t\t\t\trmbNum[r] = 89\n\t\t\t\t\t}\n\t\t\t\t\tyes = true\n\t\t\t\t\tbreak\n\t\t\t\t} else if val == 1 {\n\t\t\t\t\tfor _, r := range rmbSeq {\n\t\t\t\t\t\trmbNum[r] = 1\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif yes {\n\t\t\tonly89 = append(only89, i)\n\t\t}\n\t}\n\tfmt.Println(len(only89))\n}\n\nfunc findNext(num int) int ", "output": "{\n\tvar newNum int\n\tfor num > 0 {\n\t\tdigit := num % 10\n\t\tnewNum += digit * digit\n\t\tnum /= 10\n\t}\n\treturn newNum\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/lxc/lxd/client\"\n)\n\n\n\nfunc cmdShutdown(args *Args) error ", "output": "{\n\tc, err := lxd.ConnectLXDUnix(\"\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, _, err = c.RawQuery(\"PUT\", \"/internal/shutdown\", nil, \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tchMonitor := make(chan bool, 1)\n\tgo func() {\n\t\tmonitor, err := c.GetEvents()\n\t\tif err != nil {\n\t\t\tclose(chMonitor)\n\t\t\treturn\n\t\t}\n\n\t\tmonitor.Wait()\n\t\tclose(chMonitor)\n\t}()\n\n\tif args.Timeout > 0 {\n\t\tselect {\n\t\tcase <-chMonitor:\n\t\t\tbreak\n\t\tcase <-time.After(time.Second * time.Duration(args.Timeout)):\n\t\t\treturn fmt.Errorf(\"LXD still running after %ds timeout.\", args.Timeout)\n\t\t}\n\t} else {\n\t\t<-chMonitor\n\t}\n\n\treturn nil\n}"} {"input": "package lemon\n\nimport (\n\t\"errors\"\n\t\"testing\"\n)\n\nfunc TestOption(t *testing.T) {\n\ttests := map[string]TestHandler{\n\t\t\"WithError\": OptionWithError,\n\t}\n\n\tfor name, handler := range tests {\n\t\tt.Run(name, Setup(handler))\n\t}\n}\n\ntype errOption struct {\n\terr error\n}\n\n\n\nfunc OptionWithError(runtime *TestRuntime) {\n\n\texpected := errors.New(\"cannot update engine with foobar\")\n\toption := errOption{\n\t\terr: expected,\n\t}\n\n\tengine, err := New(runtime.Context(), option)\n\n\tif err == nil {\n\t\truntime.Error(\"An error was expected\")\n\t}\n\n\tif err != expected {\n\t\truntime.Error(\"Unexpected error: %s\", err)\n\t}\n\n\tif engine != nil {\n\t\truntime.Error(\"Engine should be undefined\")\n\t}\n\n\truntime.Log(\"We received expected error: %s.\", err)\n\n}\n\nfunc (o errOption) apply(e *Engine) error ", "output": "{\n\treturn o.err\n}"} {"input": "package mailru\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/markbates/goth\"\n)\n\n\ntype Session struct {\n\tAuthURL string\n\tAccessToken string\n\tRefreshToken string\n\tExpiresAt time.Time\n}\n\n\nfunc (s *Session) GetAuthURL() (string, error) {\n\tif s.AuthURL == \"\" {\n\t\treturn \"\", errors.New(goth.NoAuthUrlErrorMessage)\n\t}\n\n\treturn s.AuthURL, nil\n}\n\n\nfunc (s *Session) Marshal() string {\n\tb, _ := json.Marshal(s)\n\treturn string(b)\n}\n\n\nfunc (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {\n\tp := provider.(*Provider)\n\ttoken, err := p.oauthConfig.Exchange(goth.ContextForClient(p.Client()), params.Get(\"code\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !token.Valid() {\n\t\treturn \"\", errors.New(\"invalid token received from provider\")\n\t}\n\n\ts.AccessToken = token.AccessToken\n\ts.RefreshToken = token.RefreshToken\n\ts.ExpiresAt = token.Expiry\n\n\treturn s.AccessToken, err\n}\n\n\n\n\nfunc (p *Provider) UnmarshalSession(data string) (goth.Session, error) ", "output": "{\n\tsess := new(Session)\n\terr := json.NewDecoder(strings.NewReader(data)).Decode(&sess)\n\treturn sess, err\n}"} {"input": "package flag\n\nimport (\n\t\"flag\"\n\t\"github.com/mono83/cfg\"\n\t\"github.com/mono83/cfg/reflect\"\n\t\"os\"\n\t\"sync\"\n)\n\ntype flagSource struct {\n\tset *flag.FlagSet\n\targs []string\n\tm sync.Mutex\n\n\tvalues map[string]interface{}\n}\n\n\nfunc NewFlagSource() cfg.Configurer {\n\treturn NewCustomFlagSource(flag.CommandLine, os.Args[1:])\n}\n\n\n\nfunc NewCustomFlagSource(source *flag.FlagSet, args []string) cfg.Configurer {\n\treturn &flagSource{set: source, args: args}\n}\n\nfunc (f *flagSource) Validate() error {\n\treturn f.load()\n}\n\nfunc (f *flagSource) load() error {\n\tf.m.Lock()\n\tdefer f.m.Unlock()\n\n\tif !f.set.Parsed() {\n\t\terr := f.set.Parse(f.args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tf.values = map[string]interface{}{}\n\n\tf.set.Visit(func(fl *flag.Flag) {\n\t\tv, ok := fl.Value.(flag.Getter)\n\t\tif ok {\n\t\t\tf.values[fl.Name] = v.Get()\n\t\t}\n\t})\n\n\treturn nil\n}\n\nfunc (f *flagSource) Has(key string) bool {\n\tif f.values == nil {\n\t\terr := f.load()\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t_, ok := f.values[key]\n\treturn ok\n}\n\n\n\nfunc (f *flagSource) KeyFunc(key string) func(interface{}) error {\n\treturn cfg.ExtractUnmarshalFunc(f, key)\n}\n\nfunc (f *flagSource) UnmarshalKey(key string, target interface{}) error ", "output": "{\n\tif f.values == nil {\n\t\terr := f.load()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tv, ok := f.values[key]\n\tif !ok {\n\t\treturn cfg.ErrKeyMissing{Key: key}\n\t}\n\n\treturn reflect.CopyHelper(key, v, target)\n}"} {"input": "package main\n\n\n\nfunc isValidUsername(s string) bool ", "output": "{\n\treturn false\n}"} {"input": "package schedulercache\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/labels\"\n\t\"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache\"\n)\n\n\ntype FakeCache struct {\n\tAssumeFunc func(*api.Pod)\n}\n\nfunc (f *FakeCache) AssumePod(pod *api.Pod) error {\n\tf.AssumeFunc(pod)\n\treturn nil\n}\n\nfunc (f *FakeCache) AddPod(pod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) UpdatePod(oldPod, newPod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) RemovePod(pod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) AddNode(node *api.Node) error { return nil }\n\nfunc (f *FakeCache) UpdateNode(oldNode, newNode *api.Node) error { return nil }\n\n\n\nfunc (f *FakeCache) UpdateNodeNameToInfoMap(infoMap map[string]*schedulercache.NodeInfo) error {\n\treturn nil\n}\n\nfunc (f *FakeCache) List(s labels.Selector) ([]*api.Pod, error) { return nil, nil }\n\nfunc (f *FakeCache) RemoveNode(node *api.Node) error ", "output": "{ return nil }"} {"input": "package gq\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nvar count int\n\ntype WorkerTest struct {\n\tDelay time.Duration\n}\n\n\n\nfunc (w WorkerTest) Data() string {\n\treturn \"\"\n}\n\nfunc (w WorkerTest) DelayTime() time.Duration {\n\treturn w.Delay\n}\n\nfunc (w WorkerTest) Preprocess() string {\n\treturn \"\"\n}\n\nfunc (w WorkerTest) Postprocess() string {\n\treturn \"\"\n}\n\nfunc nullLogger(...interface{}) {}\n\nfunc init() {\n\tLogger(nullLogger)\n\tStartDispatcher(10)\n\tfor i := 0; i < 10; i++ {\n\t\twork := WorkerTest{Delay: 0 * time.Second}\n\t\tWorkQueue <- work\n\t}\n\ttime.Sleep(1 * time.Second)\n}\n\nfunc TestIncrement(t *testing.T) {\n\tif count != 10 {\n\t\tt.Errorf(\"expected count to be 10, got %d\\n\", count)\n\t}\n}\n\nfunc (w WorkerTest) Work() ", "output": "{\n\tcount++\n}"} {"input": "package client\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"golang.org/x/net/context\"\n)\n\nfunc TestVolumeRemoveError(t *testing.T) {\n\tclient := &Client{\n\t\ttransport: newMockClient(nil, errorMock(http.StatusInternalServerError, \"Server error\")),\n\t}\n\n\terr := client.VolumeRemove(context.Background(), \"volume_id\")\n\tif err == nil || err.Error() != \"Error response from daemon: Server error\" {\n\t\tt.Fatalf(\"expected a Server Error, got %v\", err)\n\t}\n}\n\n\n\nfunc TestVolumeRemove(t *testing.T) ", "output": "{\n\texpectedURL := \"/volumes/volume_id\"\n\n\tclient := &Client{\n\t\ttransport: newMockClient(nil, func(req *http.Request) (*http.Response, error) {\n\t\t\tif !strings.HasPrefix(req.URL.Path, expectedURL) {\n\t\t\t\treturn nil, fmt.Errorf(\"Expected URL '%s', got '%s'\", expectedURL, req.URL)\n\t\t\t}\n\t\t\tif req.Method != \"DELETE\" {\n\t\t\t\treturn nil, fmt.Errorf(\"expected DELETE method, got %s\", req.Method)\n\t\t\t}\n\t\t\treturn &http.Response{\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tBody: ioutil.NopCloser(bytes.NewReader([]byte(\"body\"))),\n\t\t\t}, nil\n\t\t}),\n\t}\n\n\terr := client.VolumeRemove(context.Background(), \"volume_id\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package downloader\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/WhaleCoinOrg/WhaleCoin/core/types\"\n)\n\n\ntype peerDropFn func(id string)\n\n\ntype dataPack interface {\n\tPeerId() string\n\tItems() int\n\tStats() string\n}\n\n\ntype headerPack struct {\n\tpeerId string\n\theaders []*types.Header\n}\n\nfunc (p *headerPack) PeerId() string { return p.peerId }\nfunc (p *headerPack) Items() int { return len(p.headers) }\nfunc (p *headerPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.headers)) }\n\n\ntype bodyPack struct {\n\tpeerId string\n\ttransactions [][]*types.Transaction\n\tuncles [][]*types.Header\n}\n\n\nfunc (p *bodyPack) Items() int {\n\tif len(p.transactions) <= len(p.uncles) {\n\t\treturn len(p.transactions)\n\t}\n\treturn len(p.uncles)\n}\nfunc (p *bodyPack) Stats() string { return fmt.Sprintf(\"%d:%d\", len(p.transactions), len(p.uncles)) }\n\n\ntype receiptPack struct {\n\tpeerId string\n\treceipts [][]*types.Receipt\n}\n\nfunc (p *receiptPack) PeerId() string { return p.peerId }\nfunc (p *receiptPack) Items() int { return len(p.receipts) }\nfunc (p *receiptPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.receipts)) }\n\n\ntype statePack struct {\n\tpeerId string\n\tstates [][]byte\n}\n\nfunc (p *statePack) PeerId() string { return p.peerId }\nfunc (p *statePack) Items() int { return len(p.states) }\nfunc (p *statePack) Stats() string { return fmt.Sprintf(\"%d\", len(p.states)) }\n\nfunc (p *bodyPack) PeerId() string ", "output": "{ return p.peerId }"} {"input": "package action\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"errors\"\n\n\tboshagentblobstore \"github.com/cloudfoundry/bosh-agent/agent/blobstore\"\n\tboshcrypto \"github.com/cloudfoundry/bosh-utils/crypto\"\n\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n)\n\ntype UploadBlobSpec struct {\n\tBlobID string `json:\"blob_id\"`\n\tChecksum boshcrypto.MultipleDigest `json:\"checksum\"`\n\tPayload string `json:\"payload\"`\n}\n\ntype UploadBlobAction struct {\n\tblobManager boshagentblobstore.BlobManagerInterface\n}\n\nfunc NewUploadBlobAction(blobManager boshagentblobstore.BlobManagerInterface) UploadBlobAction {\n\treturn UploadBlobAction{blobManager: blobManager}\n}\n\nfunc (a UploadBlobAction) IsAsynchronous(_ ProtocolVersion) bool {\n\treturn true\n}\n\nfunc (a UploadBlobAction) IsPersistent() bool {\n\treturn false\n}\n\nfunc (a UploadBlobAction) IsLoggable() bool {\n\treturn false\n}\n\n\n\nfunc (a UploadBlobAction) validatePayload(payload []byte, payloadDigest boshcrypto.Digest) error {\n\terr := payloadDigest.Verify(bytes.NewReader(payload))\n\tif err != nil {\n\t\treturn bosherr.WrapErrorf(err, \"Payload corrupted. Checksum mismatch. Expected '%s'\", payloadDigest.String())\n\t}\n\n\treturn nil\n}\n\nfunc (a UploadBlobAction) Resume() (interface{}, error) {\n\treturn nil, errors.New(\"not supported\")\n}\n\nfunc (a UploadBlobAction) Cancel() error {\n\treturn errors.New(\"not supported\")\n}\n\nfunc (a UploadBlobAction) Run(content UploadBlobSpec) (string, error) ", "output": "{\n\n\tdecodedPayload, err := base64.StdEncoding.DecodeString(content.Payload)\n\tif err != nil {\n\t\treturn content.BlobID, err\n\t}\n\n\tif err = a.validatePayload(decodedPayload, content.Checksum); err != nil {\n\t\treturn content.BlobID, err\n\t}\n\n\treader := bytes.NewReader(decodedPayload)\n\n\terr = a.blobManager.Write(content.BlobID, reader)\n\n\treturn content.BlobID, err\n}"} {"input": "package gitlab\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/nlamirault/guzuta/utils\"\n)\n\nvar (\n\tnamespace = \"nicolas-lamirault\"\n\tname = \"scame\"\n\tdescription = \"An Emacs configuration\"\n)\n\nfunc getGitlabClient() *Client {\n\treturn NewClient(utils.Getenv(\"GUZUTA_GITLAB_TOKEN\"))\n}\n\nfunc TestRetrieveGitLabProjects(t *testing.T) {\n\tclient := getGitlabClient()\n\tprojects, _ := client.GetProjects()\n\tfor _, project := range *projects {\n\t\tpath := fmt.Sprintf(\"%s/%s\", namespace, project.Path)\n\t\tif !strings.HasPrefix(project.PathWithNamespace, path) {\n\t\t\tt.Fatalf(\"Invalid project name : %s %s\",\n\t\t\t\tproject.PathWithNamespace, path)\n\t\t}\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc TestRetrieveGitlabUnknownProject(t *testing.T) ", "output": "{\n\tclient := getGitlabClient()\n\t_, err := client.GetProject(namespace, \"aaaaaaaaaa\")\n\tif err == nil {\n\t\tt.Fatalf(\"No error with unknown username\")\n\t}\n}"} {"input": "package buffactory\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestStats(t *testing.T) {\n\tstats := make(Stats, 0, 3)\n\tstats.InsertData(1)\n\tstats.InsertData(2)\n\tstats.InsertData(3)\n\tif stats.Min() != 1 {\n\t\tt.Fatal(\"Min failed\", stats.Min())\n\t}\n\tif stats.Max() != 3 {\n\t\tt.Fatal(\"Max failed\", stats.Max())\n\t}\n\tif stats.Average() != 2.0 {\n\t\tt.Fatal(\"Average failed\", stats.Average())\n\t}\n\tif stats.StdDev() != 1.0 {\n\t\tt.Fatal(\"StdDev failed\", stats.StdDev())\n\t}\n}\n\nfunc TestInsertData(t *testing.T) ", "output": "{\n\tstats := make(Stats, 0, 3)\n\tstats.InsertData(0)\n\tstats.InsertData(1)\n\tstats.InsertData(2)\n\tstats.InsertData(3)\n\tfor i, s := range stats {\n\t\tif int64(i) != s {\n\t\t\tt.Fatal(\"numbers don't match\", i , s, []int64(stats))\n\t\t}\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"os/signal\"\n\n\t\"k8s.io/klog/v2\"\n)\n\nvar onlyOneSignalHandler = make(chan struct{})\nvar shutdownHandler chan os.Signal\n\n\n\n\n\n\n\n\n\n\nfunc SetupSignalHandlerIgnoringFurtherSignals() <-chan struct{} {\n\treturn SetupSignalContextNotExiting().Done()\n}\n\n\n\n\nfunc SetupSignalContext() context.Context {\n\treturn setupSignalContext(true)\n}\n\n\n\nfunc SetupSignalContextNotExiting() context.Context {\n\treturn setupSignalContext(false)\n}\n\nfunc setupSignalContext(exitOnSecondSignal bool) context.Context {\n\tclose(onlyOneSignalHandler) \n\n\tshutdownHandler = make(chan os.Signal, 2)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tsignal.Notify(shutdownHandler, shutdownSignals...)\n\tgo func() {\n\t\t<-shutdownHandler\n\t\tcancel()\n\t\tif exitOnSecondSignal {\n\t\t\t<-shutdownHandler\n\t\t\tos.Exit(1)\n\t\t} else {\n\t\t\tfor {\n\t\t\t\t<-shutdownHandler\n\t\t\t\tklog.Infof(\"Termination signal has been received already. Ignoring signal.\")\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn ctx\n}\n\n\n\nfunc RequestShutdown() bool {\n\tif shutdownHandler != nil {\n\t\tselect {\n\t\tcase shutdownHandler <- shutdownSignals[0]:\n\t\t\treturn true\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc SetupSignalHandler() <-chan struct{} ", "output": "{\n\treturn SetupSignalContext().Done()\n}"} {"input": "package ldb\n\nimport (\n\t\"bytes\"\n\n\t\"testing\"\n\n\t\"github.com/decred/dcrd/database\"\n\t\"github.com/decred/dcrutil\"\n\n\t\"github.com/btcsuite/golangcrypto/ripemd160\"\n)\n\nfunc TestAddrIndexKeySerialization(t *testing.T) {\n\tvar hash160Bytes [ripemd160.Size]byte\n\tvar packedIndex [35]byte\n\n\tfakeHash160 := dcrutil.Hash160([]byte(\"testing\"))\n\tcopy(fakeHash160, hash160Bytes[:])\n\n\tfakeIndex := database.TxAddrIndex{\n\t\tHash160: hash160Bytes,\n\t\tHeight: 1,\n\t\tTxOffset: 5,\n\t\tTxLen: 360,\n\t}\n\n\tserializedKey := addrIndexToKey(&fakeIndex)\n\tcopy(packedIndex[:], serializedKey[0:35])\n\tunpackedIndex := unpackTxIndex(packedIndex)\n\n\tif unpackedIndex.Height != fakeIndex.Height {\n\t\tt.Errorf(\"Incorrect block height. Unpack addr index key\"+\n\t\t\t\"serialization failed. Expected %d, received %d\",\n\t\t\t1, unpackedIndex.Height)\n\t}\n\n\tif unpackedIndex.TxOffset != fakeIndex.TxOffset {\n\t\tt.Errorf(\"Incorrect tx offset. Unpack addr index key\"+\n\t\t\t\"serialization failed. Expected %d, received %d\",\n\t\t\t5, unpackedIndex.TxOffset)\n\t}\n\n\tif unpackedIndex.TxLen != fakeIndex.TxLen {\n\t\tt.Errorf(\"Incorrect tx len. Unpack addr index key\"+\n\t\t\t\"serialization failed. Expected %d, received %d\",\n\t\t\t360, unpackedIndex.TxLen)\n\t}\n}\n\n\n\nfunc TestBytesPrefix(t *testing.T) ", "output": "{\n\ttestKey := []byte(\"a\")\n\n\tprefixRange := bytesPrefix(testKey)\n\tif !bytes.Equal(prefixRange.Start, []byte(\"a\")) {\n\t\tt.Errorf(\"Wrong prefix start, got %d, expected %d\", prefixRange.Start,\n\t\t\t[]byte(\"a\"))\n\t}\n\n\tif !bytes.Equal(prefixRange.Limit, []byte(\"b\")) {\n\t\tt.Errorf(\"Wrong prefix end, got %d, expected %d\", prefixRange.Limit,\n\t\t\t[]byte(\"b\"))\n\t}\n}"} {"input": "package proxy\n\nimport (\n\t\"github.com/fatedier/frp/models/config\"\n)\n\ntype StcpProxy struct {\n\t*BaseProxy\n\tcfg *config.StcpProxyConf\n}\n\nfunc (pxy *StcpProxy) Run() (remoteAddr string, err error) {\n\tlistener, errRet := pxy.rc.VisitorManager.Listen(pxy.GetName(), pxy.cfg.Sk)\n\tif errRet != nil {\n\t\terr = errRet\n\t\treturn\n\t}\n\tlistener.AddLogPrefix(pxy.name)\n\tpxy.listeners = append(pxy.listeners, listener)\n\tpxy.Info(\"stcp proxy custom listen success\")\n\n\tpxy.startListenHandler(pxy, HandleUserTcpConnection)\n\treturn\n}\n\n\n\nfunc (pxy *StcpProxy) Close() {\n\tpxy.BaseProxy.Close()\n\tpxy.rc.VisitorManager.CloseListener(pxy.GetName())\n}\n\nfunc (pxy *StcpProxy) GetConf() config.ProxyConf ", "output": "{\n\treturn pxy.cfg\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"bufio\"\n\t\"fmt\"\n)\n\ntype Store struct {\n\n}\n\nfunc NewStore() *Store {\n\treturn &Store{}\n}\n\n\n\nfunc (s Store)WriteStore(store map[string]string, file string) error {\n\tf, err := os.Create(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\treturn s.WriteTo(store, f)\n}\n\nfunc (s Store)WriteTo(store map[string]string, w io.Writer) error {\n\tfor k, v := range store {\n\t\tif _, err := fmt.Fprintf(w, \"%v=%v\\n\", k, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s Store)ReadStore(file string) (map[string]string, error) ", "output": "{\n\tstore := make(map[string]string)\n\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn store, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\thandleCommand(store, scanner.Text())\n\t}\n\n\treturn store, scanner.Err()\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"time\"\n)\n\nvar ACTION_POTENTIAL_THRESHOLD int = 30\nvar DELAY_BETWEEN_FIRINGS time.Duration = 10\nvar SIGNAL_BUFFER_SIZE = 2048\n\ntype Neuron struct {\n\ttag string\n\tdendrite chan int \n\tsynapses []Synapse \n\tpotential int\n}\n\nfunc (n *Neuron) Fire() {\n\tlog.Println(n.tag, \"Fired\")\n\tn.potential = 0\n\tfor _, synapse := range n.synapses {\n\t\tselect {\n\t\tcase synapse.channel <- synapse.weight:\n\t\tdefault:\n\t\t\tlog.Println(\"Signal from\", n.tag, \"dropped\")\n\t\t}\n\t\ttime.Sleep(DELAY_BETWEEN_FIRINGS * time.Millisecond)\n\t}\n}\n\nfunc (n *Neuron) HasReachedThreshold() bool {\n\treturn n.potential > ACTION_POTENTIAL_THRESHOLD\n}\n\n\n\nfunc (n *Neuron) AddSynapse(destination *Neuron, weight int) {\n\tn.synapses = append(n.synapses, Synapse{destination.dendrite, weight})\n}\n\nfunc NewNeuron(tag string) Neuron {\n\treturn Neuron{tag, make(chan int, SIGNAL_BUFFER_SIZE), []Synapse{}, 0}\n}\n\nfunc (n *Neuron) Listen() ", "output": "{\n\tfor actionPotential := range n.dendrite {\n\t\tn.potential += actionPotential\n\t\tif n.HasReachedThreshold() {\n\t\t\tn.Fire()\n\t\t}\n\t}\n}"} {"input": "package controllers\n\nimport (\n\t\"fmt\"\n\t\"github.com/codeskyblue/go-sh\"\n\t\"github.com/revel/revel\"\n\t\"strings\"\n)\n\ntype Search struct {\n\t*revel.Controller\n}\n\n\n\nfunc (c Search) Search(q string, count int) revel.Result ", "output": "{\n\tfmt.Printf(\"query string is %s\\n\", q)\n\tfmt.Printf(\"count is %d\\n\", count)\n\tif count == 0 {\n\t\tcount = 10\n\t}\n\tcommand := fmt.Sprintf(\"ag --silent -i -m %d \\\"%s\\\" \\\"/Users/Join/Elements\\\"\", count, strings.Trim(q, \" \"))\n\tshell_out, err := sh.Command(\"bash\", \"-c\", command).Output()\n\tvar pretty_results []string\n\tif err != nil {\n\t\treturn c.Render(pretty_results)\n\t}\n\tr := strings.NewReplacer(q, fmt.Sprintf(\"%s\", q))\n\tresults := r.Replace(string(shell_out[:]))\n\tpretty_results = strings.Split(results, \"\\n\")\n\treturn c.Render(pretty_results)\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n)\n\n\ntype ByoipRangeCollection struct {\n\n\tItems []ByoipRangeSummary `mandatory:\"true\" json:\"items\"`\n}\n\n\n\nfunc (m ByoipRangeCollection) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package system\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nconst (\n\texecErrorMsgFmt = \"Running command: '%s', stdout: '%s', stderr: '%s'\"\n\texecShortErrorMaxLines = 100\n)\n\ntype ExecError struct {\n\tCommand string\n\tStdOut string\n\tStdErr string\n}\n\nfunc NewExecError(cmd, stdout, stderr string) ExecError {\n\treturn ExecError{\n\t\tCommand: cmd,\n\t\tStdOut: stdout,\n\t\tStdErr: stderr,\n\t}\n}\n\nfunc (e ExecError) Error() string {\n\treturn fmt.Sprintf(execErrorMsgFmt, e.Command, e.StdOut, e.StdErr)\n}\n\n\nfunc (e ExecError) ShortError() string {\n\toutStr := e.truncateStr(e.StdOut, execShortErrorMaxLines)\n\terrStr := e.truncateStr(e.StdErr, execShortErrorMaxLines)\n\treturn fmt.Sprintf(execErrorMsgFmt, e.Command, outStr, errStr)\n}\n\n\n\nfunc (e ExecError) truncateStr(in string, maxLines int) string ", "output": "{\n\toutLines := strings.Split(in, \"\\n\")\n\tif i := len(outLines); i > maxLines {\n\t\toutLines = outLines[i-maxLines:]\n\t}\n\n\treturn strings.Join(outLines, \"\\n\")\n}"} {"input": "package olog\n\nimport (\n\t\"fmt\"\n)\n\n\ntype DirectLogger struct {\n\twriters map[string]Writer\n}\n\n\nfunc NewDirectLogger() *DirectLogger {\n\treturn &DirectLogger{\n\t\twriters: make(map[string]Writer),\n\t}\n}\n\n\nfunc (dl *DirectLogger) Log(level Level,\n\tmodule string,\n\tfmtstr string,\n\targs ...interface{}) {\n\tif level == PrintLevel {\n\t\treturn\n\t}\n\tfmtstr = ToString(level) + \" [\" + module + \"] \" + fmtstr\n\tmsg := fmt.Sprintf(fmtstr, args...)\n\tfor _, writer := range dl.writers {\n\t\tif writer.IsEnabled() {\n\t\t\twriter.Write(msg)\n\t\t}\n\t}\n}\n\n\nfunc (dl *DirectLogger) RegisterWriter(writer Writer) {\n\tif writer != nil {\n\t\tdl.writers[writer.UniqueID()] = writer\n\t}\n}\n\n\n\n\n\nfunc (dl *DirectLogger) GetWriter(uniqueID string) (writer Writer) {\n\treturn dl.writers[uniqueID]\n}\n\nfunc (dl *DirectLogger) RemoveWriter(uniqueID string) ", "output": "{\n\tdelete(dl.writers, uniqueID)\n}"} {"input": "package render\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gogo/protobuf/proto\"\n\t\"github.com/pkg/errors\"\n)\n\nvar pbContentType = []string{\"application/x-protobuf\"}\n\n\nfunc (r PB) Render(w http.ResponseWriter) error {\n\tif r.TTL <= 0 {\n\t\tr.TTL = 1\n\t}\n\treturn writePB(w, r)\n}\n\n\n\n\nfunc writePB(w http.ResponseWriter, obj PB) (err error) {\n\tvar pbBytes []byte\n\twriteContentType(w, pbContentType)\n\n\tif pbBytes, err = proto.Marshal(&obj); err != nil {\n\t\terr = errors.WithStack(err)\n\t\treturn\n\t}\n\n\tif _, err = w.Write(pbBytes); err != nil {\n\t\terr = errors.WithStack(err)\n\t}\n\treturn\n}\n\nfunc (r PB) WriteContentType(w http.ResponseWriter) ", "output": "{\n\twriteContentType(w, pbContentType)\n}"} {"input": "package dbr\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\nfunc BenchmarkDeleteSql(b *testing.B) {\n\ts := createFakeSession()\n\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\ts.DeleteFrom(\"alpha\").Where(\"a\", \"b\").Limit(1).OrderDir(\"id\", true).ToSql()\n\t}\n}\n\nfunc TestDeleteAllToSql(t *testing.T) {\n\ts := createFakeSession()\n\n\tsql, _ := s.DeleteFrom(\"a\").ToSql()\n\n\tassert.Equal(t, sql, \"DELETE FROM a\")\n}\n\nfunc TestDeleteSingleToSql(t *testing.T) {\n\ts := createFakeSession()\n\n\tsql, args := s.DeleteFrom(\"a\").Where(\"id = ?\", 1).ToSql()\n\n\tassert.Equal(t, sql, \"DELETE FROM a WHERE (id = ?)\")\n\tassert.Equal(t, args, []interface{}{1})\n}\n\nfunc TestDeleteTenStaringFromTwentyToSql(t *testing.T) {\n\ts := createFakeSession()\n\n\tsql, _ := s.DeleteFrom(\"a\").Limit(10).Offset(20).OrderBy(\"id\").ToSql()\n\n\tassert.Equal(t, sql, \"DELETE FROM a ORDER BY id LIMIT 10 OFFSET 20\")\n}\n\n\n\nfunc TestDeleteReal(t *testing.T) ", "output": "{\n\ts := createRealSessionWithFixtures()\n\n\tres, err := s.InsertInto(\"dbr_people\").Columns(\"name\", \"email\").Values(\"Barack\", \"barack@whitehouse.gov\").Exec()\n\tassert.NoError(t, err)\n\n\tid, err := res.LastInsertId()\n\tassert.NoError(t, err)\n\n\tres, err = s.DeleteFrom(\"dbr_people\").Where(\"id = ?\", id).Exec()\n\tassert.NoError(t, err)\n\n\trowsAff, err := res.RowsAffected()\n\tassert.NoError(t, err)\n\tassert.Equal(t, rowsAff, 1)\n\n\tvar count int64\n\terr = s.Select(\"count(*)\").From(\"dbr_people\").Where(\"id = ?\", id).LoadValue(&count)\n\tassert.NoError(t, err)\n\tassert.Equal(t, count, 0)\n}"} {"input": "package roles\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestIsTopLevelRole(t *testing.T) {\n\tassert.True(t, IsTopLevelRole(\"root\"))\n\tassert.True(t, IsTopLevelRole(\"targets\"))\n\tassert.True(t, IsTopLevelRole(\"timestamp\"))\n\tassert.True(t, IsTopLevelRole(\"snapshot\"))\n\tassert.False(t, IsTopLevelRole(\"bins\"))\n}\n\nfunc TestIsDelegatedTargetsRole(t *testing.T) {\n\tassert.False(t, IsDelegatedTargetsRole(\"root\"))\n\tassert.False(t, IsDelegatedTargetsRole(\"targets\"))\n\tassert.False(t, IsDelegatedTargetsRole(\"timestamp\"))\n\tassert.False(t, IsDelegatedTargetsRole(\"snapshot\"))\n\tassert.True(t, IsDelegatedTargetsRole(\"deleg\"))\n}\n\nfunc TestIsTopLevelManifest(t *testing.T) {\n\tassert.True(t, IsTopLevelManifest(\"root.json\"))\n\tassert.True(t, IsTopLevelManifest(\"targets.json\"))\n\tassert.True(t, IsTopLevelManifest(\"timestamp.json\"))\n\tassert.True(t, IsTopLevelManifest(\"snapshot.json\"))\n\tassert.False(t, IsTopLevelManifest(\"bins.json\"))\n}\n\n\n\nfunc TestIsVersionedManifest(t *testing.T) {\n\tassert.False(t, IsVersionedManifest(\"a.b\"))\n\tassert.False(t, IsVersionedManifest(\"a.b.c\"))\n\tassert.False(t, IsVersionedManifest(\"a.b.json\"))\n\tassert.False(t, IsVersionedManifest(\"1.a\"))\n\tassert.True(t, IsVersionedManifest(\"1.a.json\"))\n\tassert.True(t, IsVersionedManifest(\"2.a.json\"))\n}\n\nfunc TestIsDelegatedTargetsManifest(t *testing.T) ", "output": "{\n\tassert.False(t, IsDelegatedTargetsManifest(\"root.json\"))\n\tassert.False(t, IsDelegatedTargetsManifest(\"targets.json\"))\n\tassert.False(t, IsDelegatedTargetsManifest(\"timestamp.json\"))\n\tassert.False(t, IsDelegatedTargetsManifest(\"snapshot.json\"))\n\tassert.True(t, IsDelegatedTargetsManifest(\"bins.json\"))\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n\n\tctypes \"github.com/tendermint/tendermint/rpc/core/types\"\n\t\"github.com/tendermint/tendermint/types\"\n\t. \"github.com/tendermint/tmlibs/common\"\n)\n\n\n\n\nfunc BlockchainInfo(minHeight, maxHeight int) (*ctypes.ResultBlockchainInfo, error) {\n\tif maxHeight == 0 {\n\t\tmaxHeight = blockStore.Height()\n\t} else {\n\t\tmaxHeight = MinInt(blockStore.Height(), maxHeight)\n\t}\n\tif minHeight == 0 {\n\t\tminHeight = MaxInt(1, maxHeight-20)\n\t} else {\n\t\tminHeight = MaxInt(minHeight, maxHeight-20)\n\t}\n\n\tlogger.Debug(\"BlockchainInfoHandler\", \"maxHeight\", maxHeight, \"minHeight\", minHeight)\n\n\tblockMetas := []*types.BlockMeta{}\n\tfor height := maxHeight; height >= minHeight; height-- {\n\t\tblockMeta := blockStore.LoadBlockMeta(height)\n\t\tblockMetas = append(blockMetas, blockMeta)\n\t}\n\n\treturn &ctypes.ResultBlockchainInfo{blockStore.Height(), blockMetas}, nil\n}\n\n\n\nfunc Block(height int) (*ctypes.ResultBlock, error) {\n\tif height == 0 {\n\t\treturn nil, fmt.Errorf(\"Height must be greater than 0\")\n\t}\n\tif height > blockStore.Height() {\n\t\treturn nil, fmt.Errorf(\"Height must be less than the current blockchain height\")\n\t}\n\n\tblockMeta := blockStore.LoadBlockMeta(height)\n\tblock := blockStore.LoadBlock(height)\n\treturn &ctypes.ResultBlock{blockMeta, block}, nil\n}\n\n\n\n\n\nfunc Commit(height int) (*ctypes.ResultCommit, error) ", "output": "{\n\tif height == 0 {\n\t\treturn nil, fmt.Errorf(\"Height must be greater than 0\")\n\t}\n\tstoreHeight := blockStore.Height()\n\tif height > storeHeight {\n\t\treturn nil, fmt.Errorf(\"Height must be less than or equal to the current blockchain height\")\n\t}\n\n\theader := blockStore.LoadBlockMeta(height).Header\n\n\tif height == storeHeight {\n\t\tcommit := blockStore.LoadSeenCommit(height)\n\t\treturn &ctypes.ResultCommit{header, commit, false}, nil\n\t}\n\n\tcommit := blockStore.LoadBlockCommit(height)\n\treturn &ctypes.ResultCommit{header, commit, true}, nil\n}"} {"input": "package loop\n\n\n\n\n\nimport (\n\t\"github.com/tideland/golib/errors\"\n)\n\n\n\n\n\n\nconst (\n\tErrLoopPanicked = iota + 1\n\tErrHandlingFailed\n\tErrRestartNonStopped\n\tErrKilledBySentinel\n)\n\nvar errorMessages = errors.Messages{\n\tErrLoopPanicked: \"loop panicked: %v\",\n\tErrHandlingFailed: \"error handling for %q failed\",\n\tErrRestartNonStopped: \"cannot restart unstopped %q\",\n\tErrKilledBySentinel: \"%q killed by sentinel\",\n}\n\n\n\n\n\n\n\n\n\n\nfunc IsKilledBySentinelError(err error) bool ", "output": "{\n\treturn errors.IsError(err, ErrKilledBySentinel)\n}"} {"input": "package main\n\n\n\n\nimport \"C\"\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime/pprof\"\n\t\"time\"\n\t\"unsafe\"\n)\n\nfunc init() {\n\tregister(\"CgoPprofThread\", CgoPprofThread)\n\tregister(\"CgoPprofThreadNoTraceback\", CgoPprofThreadNoTraceback)\n}\n\n\n\nfunc CgoPprofThreadNoTraceback() {\n\tpprofThread()\n}\n\nfunc pprofThread() {\n\tf, err := os.CreateTemp(\"\", \"prof\")\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(2)\n\t}\n\n\tif err := pprof.StartCPUProfile(f); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(2)\n\t}\n\n\tC.runCPUHogThread()\n\n\tt0 := time.Now()\n\tfor C.getCPUHogThreadCount() < 2 && time.Since(t0) < time.Second {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\n\tpprof.StopCPUProfile()\n\n\tname := f.Name()\n\tif err := f.Close(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Println(name)\n}\n\nfunc CgoPprofThread() ", "output": "{\n\truntime.SetCgoTraceback(0, unsafe.Pointer(C.pprofCgoThreadTraceback), nil, nil)\n\tpprofThread()\n}"} {"input": "package conditions_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestConditions(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Conditions Suite\")\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSOpsWorksStack_ElasticIp struct {\n\n\tIp string `json:\"Ip,omitempty\"`\n\n\tName string `json:\"Name,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) AWSCloudFormationType() string {\n\treturn \"AWS::OpsWorks::Stack.ElasticIp\"\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\n\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSOpsWorksStack_ElasticIp) SetMetadata(metadata map[string]interface{}) ", "output": "{\n\tr._metadata = metadata\n}"} {"input": "package watcher\n\n\n\nfunc (w *Watcher) webhookPolling() ", "output": "{\n\tdefer w.syncWg.Done()\n\n\tif w.once {\n\t\treturn\n\t}\n\n\terrCh := make(chan error, 1)\n\tgo w.ListenAndServe(errCh)\n\n\tfor {\n\t\tselect {\n\t\tcase err := <-errCh:\n\t\t\tw.ErrCh <- err\n\t\tcase <-w.rcvDoneCh:\n\t\t\treturn\n\t\t}\n\t}\n}"} {"input": "package cli\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n)\n\n\nfunc CheckError(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n\n\n\n\n\nfunc FileExists(path string) bool {\n\t_, err := os.Stat(path)\n\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\n\treturn false\n}\n\n\nfunc WritePid(pidfile string) {\n\tdirname := path.Dir(pidfile)\n\tif !FileExists(dirname) {\n\t\tCheckFatalError(fmt.Errorf(\"Directory \\\"%s\\\" doesn't exist\", dirname))\n\t}\n\n\tif FileExists(pidfile) {\n\t\tCheckFatalError(fmt.Errorf(\"File \\\"%s\\\" already exist\", pidfile))\n\t}\n\n\tpid := os.Getpid()\n\terr := ioutil.WriteFile(pidfile, []byte(strconv.Itoa(pid)), os.FileMode(0644))\n\tCheckFatalError(err)\n}\n\n\nfunc StopExecution(code int, pidfile string) {\n\tos.Remove(pidfile)\n\tos.Exit(code)\n}\n\nfunc CheckFatalError(err error) ", "output": "{\n\tif err != nil {\n\t\tCheckError(fmt.Errorf(\"Fatal error: %v\", err))\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc produce(s string) string {\n\tif s == \"2\" {\n\t\treturn s\n\t}\n\treturn s[1:]\n}\n\nfunc associate(s string) string {\n\tif s == \"\" {\n\t\treturn s\n\t}\n\treturn s + \"2\" + s\n}\n\n\n\nfunc main() {\n\tin, _ := os.Open(\"743.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"743.out\")\n\tdefer out.Close()\n\n\tvar n int64\n\tfor {\n\t\tif fmt.Fscanf(in, \"%d\", &n); n == 0 {\n\t\t\tbreak\n\t\t}\n\t\tif s := solve(fmt.Sprint(n)); s != \"\" {\n\t\t\tfmt.Fprintln(out, s)\n\t\t} else {\n\t\t\tfmt.Fprintln(out, \"NOT ACCEPTABLE\")\n\t\t}\n\t}\n}\n\nfunc solve(s string) string ", "output": "{\n\tswitch {\n\tcase strings.Contains(s, \"0\"):\n\t\treturn \"\"\n\tcase s[0] == '3':\n\t\treturn associate(solve(s[1:]))\n\tcase len(s) > 1 && s[0] == '2':\n\t\treturn produce(s)\n\tdefault:\n\t\treturn \"\"\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\nvar cliParamsTcs = []struct {\n\tparams []string\n\tresultIsError bool\n}{\n\t{[]string{\"FOO=BAR\", \"BAZ=BLAH\"}, false},\n\t{[]string{\"FOO=BAR\", \"BAZ\"}, true},\n}\n\n\n\nvar cliExistsTcs = []struct {\n\tcmd string\n\tresultIsError bool\n}{\n\t{\"ls\", false},\n\t{\"no-way-this-exists\", true},\n}\n\nfunc TestValidateCliExists(t *testing.T) {\n\tfor _, tc := range cliExistsTcs {\n\t\terr := validateCliExists(tc.cmd)\n\t\tif (err != nil) != tc.resultIsError {\n\t\t\tt.Fatalf(\"Expected '%v' got '%v' for '%v'\", tc.resultIsError, err, tc.cmd)\n\t\t}\n\t}\n}\n\nvar templateExistsTcs = []struct {\n\tfile string\n\tcreateTmpFile bool\n\tresultIsError bool\n}{\n\t{\"\", true, false},\n\t{\"/no-way-this-exists\", false, true},\n}\n\nfunc TestValidateTemplateExists(t *testing.T) {\n\tfor _, tc := range templateExistsTcs {\n\t\tif tc.createTmpFile {\n\t\t\tf, err := ioutil.TempFile(\"\", \"cfn-clone-test\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Unable to create temp file for testing ValidateTemplateExists\")\n\t\t\t}\n\n\t\t\tdefer f.Close()\n\t\t\ttc.file = f.Name()\n\t\t}\n\n\t\terr := validateTemplateExists(tc.file)\n\t\tif (err != nil) != tc.resultIsError {\n\t\t\tt.Fatalf(\"Expected '%v' got '%v' for '%v'\", tc.resultIsError, err, tc.file)\n\t\t}\n\t}\n}\n\nfunc TestValidateCliParameters(t *testing.T) ", "output": "{\n\tfor _, tc := range cliParamsTcs {\n\t\terr := validateCliParameters(tc.params)\n\t\tif (err != nil) != tc.resultIsError {\n\t\t\tt.Fatalf(\"Expected '%v' got '%v' for '%v'\", tc.resultIsError, err, tc.params)\n\t\t}\n\t}\n}"} {"input": "package lib\n\nimport \"sync\"\n\n\n\ntype ConcurrentPrinterMap struct {\n\tbyCUPSName map[string]Printer\n\tbyGCPID map[string]Printer\n\tmutex sync.RWMutex\n}\n\n\nfunc NewConcurrentPrinterMap(printers []Printer) *ConcurrentPrinterMap {\n\tcpm := ConcurrentPrinterMap{}\n\tcpm.Refresh(printers)\n\treturn &cpm\n}\n\n\nfunc (cpm *ConcurrentPrinterMap) Refresh(newPrinters []Printer) {\n\tc := make(map[string]Printer, len(newPrinters))\n\tfor _, printer := range newPrinters {\n\t\tc[printer.Name] = printer\n\t}\n\n\tg := make(map[string]Printer, len(newPrinters))\n\tfor _, printer := range newPrinters {\n\t\tif len(printer.GCPID) > 0 {\n\t\t\tg[printer.GCPID] = printer\n\t\t}\n\t}\n\n\tcpm.mutex.Lock()\n\tdefer cpm.mutex.Unlock()\n\n\tcpm.byCUPSName = c\n\tcpm.byGCPID = g\n}\n\n\n\n\n\n\n\n\n\nfunc (cpm *ConcurrentPrinterMap) GetByGCPID(gcpID string) (Printer, bool) {\n\tcpm.mutex.RLock()\n\tdefer cpm.mutex.RUnlock()\n\n\tif p, exists := cpm.byGCPID[gcpID]; exists {\n\t\treturn p, true\n\t}\n\treturn Printer{}, false\n}\n\n\nfunc (cpm *ConcurrentPrinterMap) GetAll() []Printer {\n\tcpm.mutex.RLock()\n\tdefer cpm.mutex.RUnlock()\n\n\tprinters := make([]Printer, len(cpm.byCUPSName))\n\ti := 0\n\tfor _, printer := range cpm.byCUPSName {\n\t\tprinters[i] = printer\n\t\ti++\n\t}\n\n\treturn printers\n}\n\nfunc (cpm *ConcurrentPrinterMap) GetByCUPSName(name string) (Printer, bool) ", "output": "{\n\tcpm.mutex.RLock()\n\tdefer cpm.mutex.RUnlock()\n\n\tif p, exists := cpm.byCUPSName[name]; exists {\n\t\treturn p, true\n\t}\n\treturn Printer{}, false\n}"} {"input": "package crypto\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"io\"\n\t\"time\"\n)\n\n\n\n\nfunc GenerateRandomBytes(n int) []byte {\n\tb := make([]byte, n)\n\tif _, err := io.ReadFull(rand.Reader, b); err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}\n\n\nfunc Timestamp() int64 {\n\treturn time.Now().UTC().Unix()\n}\n\n\n\n\n\nfunc Base64Decode(value []byte) ([]byte, error) {\n\tdec := make([]byte, base64.RawURLEncoding.DecodedLen(len(value)))\n\tb, err := base64.RawURLEncoding.Decode(dec, value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dec[:b], nil\n}\n\nfunc Base64Encode(value []byte) []byte ", "output": "{\n\tenc := make([]byte, base64.RawURLEncoding.EncodedLen(len(value)))\n\tbase64.RawURLEncoding.Encode(enc, value)\n\treturn enc\n}"} {"input": "package hdinsight\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tEndpoint string\n\tUserName string\n}\n\n\n\n\n\nfunc NewWithoutDefaults(endpoint string, userName string) BaseClient {\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tEndpoint: endpoint,\n\t\tUserName: userName,\n\t}\n}\n\nfunc New(endpoint string, userName string) BaseClient ", "output": "{\n\treturn NewWithoutDefaults(endpoint, userName)\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\n\tv3 \"github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3\"\n\t\"github.com/rancher/rancher/pkg/ref\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc GetRuleID(groupID string, ruleName string) string {\n\treturn fmt.Sprintf(\"%s_%s\", groupID, ruleName)\n}\n\nfunc GetGroupID(namespace, name string) string {\n\treturn fmt.Sprintf(\"%s:%s\", namespace, name)\n}\n\nfunc GetAlertManagerSecretName(appName string) string {\n\treturn fmt.Sprintf(\"alertmanager-%s\", appName)\n}\n\nfunc GetAlertManagerDaemonsetName(appName string) string {\n\treturn fmt.Sprintf(\"alertmanager-%s\", appName)\n}\n\nfunc formatProjectDisplayName(projectDisplayName, projectID string) string {\n\treturn fmt.Sprintf(\"%s (ID: %s)\", projectDisplayName, projectID)\n}\n\nfunc formatClusterDisplayName(clusterDisplayName, clusterID string) string {\n\treturn fmt.Sprintf(\"%s (ID: %s)\", clusterDisplayName, clusterID)\n}\n\n\n\nfunc GetProjectDisplayName(projectID string, projectLister v3.ProjectLister) string {\n\tclusterName, projectName := ref.Parse(projectID)\n\tproject, err := projectLister.Get(clusterName, projectName)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to get project %s: %v\", projectID, err)\n\t\treturn projectID\n\t}\n\n\treturn formatProjectDisplayName(project.Spec.DisplayName, projectID)\n}\n\nfunc GetClusterDisplayName(clusterName string, clusterLister v3.ClusterLister) string ", "output": "{\n\tcluster, err := clusterLister.Get(\"\", clusterName)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to get cluster for %s: %v\", clusterName, err)\n\t\treturn clusterName\n\t}\n\n\treturn formatClusterDisplayName(cluster.Spec.DisplayName, clusterName)\n}"} {"input": "package sha512\n\nimport \"crypto/sha512\"\n\nconst (\n\tSize = 64\n\n\tSize224 = 28\n\n\tSize256 = 32\n\n\tSize384 = 48\n\n\tBlockSize = 128\n)\n\n\nfunc Sum512(data []byte) []byte {\n\ta := sha512.Sum512(data)\n\treturn a[:]\n}\n\n\n\n\n\nfunc Sum512_224(data []byte) (sum224 []byte) {\n\ta := sha512.Sum512_224(data)\n\treturn a[:]\n}\n\n\nfunc Sum512_256(data []byte) (sum256 []byte) {\n\ta := sha512.Sum512_256(data)\n\treturn a[:]\n}\n\nfunc Sum384(data []byte) (sum384 []byte) ", "output": "{\n\ta := sha512.Sum384(data)\n\treturn a[:]\n}"} {"input": "package customer\n\nimport (\n\t\"testing\"\n\n\tassert \"github.com/stretchr/testify/require\"\n\tstripe \"github.com/stripe/stripe-go\"\n\t_ \"github.com/stripe/stripe-go/testing\"\n)\n\nfunc TestCustomerDel(t *testing.T) {\n\tcustomer, err := Del(\"cus_123\", nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerGet(t *testing.T) {\n\tcustomer, err := Get(\"cus_123\", nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerList(t *testing.T) {\n\ti := List(&stripe.CustomerListParams{})\n\n\tassert.True(t, i.Next())\n\tassert.Nil(t, i.Err())\n\tassert.NotNil(t, i.Customer())\n}\n\n\n\nfunc TestCustomerNew_NilParams(t *testing.T) {\n\tcustomer, err := New(nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerUpdate(t *testing.T) {\n\tcustomer, err := Update(\"cus_123\", &stripe.CustomerParams{\n\t\tEmail: stripe.String(\"foo@example.com\"),\n\t})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerNew(t *testing.T) ", "output": "{\n\tcustomer, err := New(&stripe.CustomerParams{\n\t\tEmail: stripe.String(\"foo@example.com\"),\n\t\tShipping: &stripe.CustomerShippingDetailsParams{\n\t\t\tAddress: &stripe.AddressParams{\n\t\t\t\tLine1: stripe.String(\"line1\"),\n\t\t\t\tCity: stripe.String(\"city\"),\n\t\t\t},\n\t\t\tName: stripe.String(\"name\"),\n\t\t},\n\t})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\ntype Response struct {\n\tStatus string `json:\"status\"`\n\tErrorText string `json:\"errorText,omitempty\"`\n\tAddress string `json:\"address,omitempty\"`\n\tStatusCode int `json:\"statusCode,omitempty\"`\n\tVersion string `json:\"version,omitempty\"`\n}\n\ntype Responses struct {\n\tResponses []Response `json:\"responses\"`\n}\n\nfunc (r *Response) Fill(outStr string, err error) {\n\tif err != nil {\n\t\tr.Status = \"ERR\"\n\t\tr.ErrorText = strings.TrimSpace(outStr + \" \" + err.Error())\n\t} else {\n\t\tr.Status = \"OK\"\n\t}\n}\n\nfunc (r Responses) String() string {\n\tj, _ := json.Marshal(r)\n\treturn fmt.Sprintf(\"Responses: %s\", string(j))\n}\n\nfunc (r Response) String() string {\n\tj, _ := json.Marshal(r)\n\treturn fmt.Sprintf(\"Response: %s\", string(j))\n}\n\n\n\nfunc (r Response) WriteBadRequestHttp(w http.ResponseWriter) (resp Response) {\n\tw.WriteHeader(http.StatusBadRequest)\n\tr.StatusCode = http.StatusBadRequest\n\treturn EncodeJson(r, w)\n}\n\nfunc (r Response) WriteInternalServerErrorHttp(w http.ResponseWriter) (resp Response) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tr.StatusCode = http.StatusInternalServerError\n\treturn EncodeJson(r, w)\n}\n\nfunc EncodeJson(r Response, w http.ResponseWriter) (resp Response) {\n\terr := json.NewEncoder(w).Encode(r)\n\tif err != nil {\n\t\tlog.Printf(\"[writehttp] failed to create json from model: %s\", err.Error())\n\t}\n\treturn r\n}\n\nfunc (r Response) WriteHttp(w http.ResponseWriter) (resp Response) ", "output": "{\n\tif r.StatusCode == 0 {\n\t\tr.StatusCode = 200\n\t}\n\tw.WriteHeader(r.StatusCode)\n\treturn EncodeJson(r, w)\n}"} {"input": "package component\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/config\"\n\t\"go.opentelemetry.io/collector/consumer\"\n)\n\nfunc TestNewProcessorFactory(t *testing.T) {\n\tconst typeStr = \"test\"\n\tdefaultCfg := config.NewProcessorSettings(config.NewComponentID(typeStr))\n\tfactory := NewProcessorFactory(\n\t\ttypeStr,\n\t\tfunc() config.Processor { return &defaultCfg })\n\tassert.EqualValues(t, typeStr, factory.Type())\n\tassert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())\n\t_, err := factory.CreateTracesProcessor(context.Background(), ProcessorCreateSettings{}, &defaultCfg, nil)\n\tassert.Error(t, err)\n\t_, err = factory.CreateMetricsProcessor(context.Background(), ProcessorCreateSettings{}, &defaultCfg, nil)\n\tassert.Error(t, err)\n\t_, err = factory.CreateLogsProcessor(context.Background(), ProcessorCreateSettings{}, &defaultCfg, nil)\n\tassert.Error(t, err)\n}\n\n\n\nfunc createTracesProcessor(context.Context, ProcessorCreateSettings, config.Processor, consumer.Traces) (TracesProcessor, error) {\n\treturn nil, nil\n}\n\nfunc createMetricsProcessor(context.Context, ProcessorCreateSettings, config.Processor, consumer.Metrics) (MetricsProcessor, error) {\n\treturn nil, nil\n}\n\nfunc createLogsProcessor(context.Context, ProcessorCreateSettings, config.Processor, consumer.Logs) (LogsProcessor, error) {\n\treturn nil, nil\n}\n\nfunc TestNewProcessorFactory_WithOptions(t *testing.T) ", "output": "{\n\tconst typeStr = \"test\"\n\tdefaultCfg := config.NewProcessorSettings(config.NewComponentID(typeStr))\n\tfactory := NewProcessorFactory(\n\t\ttypeStr,\n\t\tfunc() config.Processor { return &defaultCfg },\n\t\tWithTracesProcessor(createTracesProcessor),\n\t\tWithMetricsProcessor(createMetricsProcessor),\n\t\tWithLogsProcessor(createLogsProcessor))\n\tassert.EqualValues(t, typeStr, factory.Type())\n\tassert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())\n\n\t_, err := factory.CreateTracesProcessor(context.Background(), ProcessorCreateSettings{}, &defaultCfg, nil)\n\tassert.NoError(t, err)\n\n\t_, err = factory.CreateMetricsProcessor(context.Background(), ProcessorCreateSettings{}, &defaultCfg, nil)\n\tassert.NoError(t, err)\n\n\t_, err = factory.CreateLogsProcessor(context.Background(), ProcessorCreateSettings{}, &defaultCfg, nil)\n\tassert.NoError(t, err)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc produce(s string) string {\n\tif s == \"2\" {\n\t\treturn s\n\t}\n\treturn s[1:]\n}\n\n\n\nfunc solve(s string) string {\n\tswitch {\n\tcase strings.Contains(s, \"0\"):\n\t\treturn \"\"\n\tcase s[0] == '3':\n\t\treturn associate(solve(s[1:]))\n\tcase len(s) > 1 && s[0] == '2':\n\t\treturn produce(s)\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\nfunc main() {\n\tin, _ := os.Open(\"743.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"743.out\")\n\tdefer out.Close()\n\n\tvar n int64\n\tfor {\n\t\tif fmt.Fscanf(in, \"%d\", &n); n == 0 {\n\t\t\tbreak\n\t\t}\n\t\tif s := solve(fmt.Sprint(n)); s != \"\" {\n\t\t\tfmt.Fprintln(out, s)\n\t\t} else {\n\t\t\tfmt.Fprintln(out, \"NOT ACCEPTABLE\")\n\t\t}\n\t}\n}\n\nfunc associate(s string) string ", "output": "{\n\tif s == \"\" {\n\t\treturn s\n\t}\n\treturn s + \"2\" + s\n}"} {"input": "package policy\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/\" + version.Number + \" policy/2019-01-01\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package fs\n\nimport (\n\t. \"launchpad.net/gocheck\"\n\t\"os\"\n)\n\ntype CommonTestSuite struct{}\n\nvar _ = Suite(&CommonTestSuite{})\n\nfunc (s *CommonTestSuite) TestMkDir_NonRecursive(c *C) {\n\ttmpDir := c.MkDir() + \"/foo\"\n\n\terr := MkDir(tmpDir, false, 0755)\n\tc.Assert(err, IsNil)\n\n\tf, err := os.Stat(tmpDir)\n\tc.Assert(err, IsNil)\n\tc.Assert(f.IsDir(), Equals, true)\n}\n\nfunc (s *CommonTestSuite) TestMkDir_Recursive(c *C) {\n\ttmpDir := c.MkDir() + \"/foo/bar/baz\"\n\n\terr := MkDir(tmpDir, true, 0755)\n\tc.Assert(err, IsNil)\n\n\tf, err := os.Stat(tmpDir)\n\tc.Assert(err, IsNil)\n\tc.Assert(f.IsDir(), Equals, true)\n}\n\nfunc (s *CommonTestSuite) TestRmDir_NonRecursive(c *C) {\n\ttmpDir := c.MkDir() + \"/foo\"\n\n\terr := MkDir(tmpDir, false, 0755)\n\tc.Assert(err, IsNil)\n\n\tf, err := os.Stat(tmpDir)\n\tc.Assert(err, IsNil)\n\tc.Assert(f.IsDir(), Equals, true)\n\n\terr = RmDir(tmpDir, false)\n\tc.Assert(err, IsNil)\n\n\tf, err = os.Stat(tmpDir)\n\tc.Assert(os.IsNotExist(err), Equals, true)\n\tc.Assert(f, IsNil)\n}\n\n\n\nfunc (s *CommonTestSuite) TestRmDir_Recursive(c *C) ", "output": "{\n\tsuffix := \"/foo/bar/baz\"\n\ttmpDir := c.MkDir()\n\n\terr := MkDir(tmpDir+suffix, true, 0755)\n\tc.Assert(err, IsNil)\n\n\tf, err := os.Stat(tmpDir)\n\tc.Assert(err, IsNil)\n\tc.Assert(f.IsDir(), Equals, true)\n\n\terr = RmDir(tmpDir, true)\n\tc.Assert(err, IsNil)\n\n\tf, err = os.Stat(tmpDir + suffix)\n\tc.Assert(os.IsNotExist(err), Equals, true)\n\tc.Assert(f, IsNil)\n}"} {"input": "package authmethod\n\nimport (\n\t\"sync\"\n\n\t\"github.com/hashicorp/consul/agent/structs\"\n)\n\ntype syncCache struct {\n\tlock sync.RWMutex\n\tcache authMethodCache\n}\n\n\n\nfunc (c *syncCache) GetValidator(method *structs.ACLAuthMethod) (uint64, Validator, bool) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\treturn c.cache.GetValidator(method)\n}\n\nfunc (c *syncCache) PutValidatorIfNewer(method *structs.ACLAuthMethod, validator Validator, idx uint64) Validator {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\treturn c.cache.PutValidatorIfNewer(method, validator, idx)\n}\n\nfunc (c *syncCache) Purge() {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tc.cache.Purge()\n}\n\nfunc NewCache() Cache ", "output": "{\n\tc := &syncCache{}\n\tc.cache.init()\n\treturn c\n}"} {"input": "package gorocksdb\n\nimport (\n\t\"testing\"\n\n\t\"github.com/facebookgo/ensure\"\n)\n\nfunc TestSliceTransform(t *testing.T) {\n\tdb := newTestDB(t, \"TestSliceTransform\", func(opts *Options) {\n\t\topts.SetPrefixExtractor(&testSliceTransform{})\n\t})\n\tdefer db.Close()\n\n\two := NewDefaultWriteOptions()\n\tensure.Nil(t, db.Put(wo, []byte(\"foo1\"), []byte(\"foo\")))\n\tensure.Nil(t, db.Put(wo, []byte(\"foo2\"), []byte(\"foo\")))\n\tensure.Nil(t, db.Put(wo, []byte(\"bar1\"), []byte(\"bar\")))\n\n\titer := db.NewIterator(NewDefaultReadOptions())\n\tdefer iter.Close()\n\tprefix := []byte(\"foo\")\n\tnumFound := 0\n\tfor iter.Seek(prefix); iter.ValidForPrefix(prefix); iter.Next() {\n\t\tnumFound++\n\t}\n\tensure.Nil(t, iter.Err())\n\tensure.DeepEqual(t, numFound, 2)\n}\n\n\n\nfunc TestNewNoopPrefixTransform(t *testing.T) {\n\tdb := newTestDB(t, \"TestNewNoopPrefixTransform\", func(opts *Options) {\n\t\topts.SetPrefixExtractor(NewNoopPrefixTransform())\n\t})\n\tdefer db.Close()\n}\n\ntype testSliceTransform struct {\n\tinitiated bool\n}\n\nfunc (st *testSliceTransform) Name() string { return \"gorocksdb.test\" }\nfunc (st *testSliceTransform) Transform(src []byte) []byte { return src[0:3] }\nfunc (st *testSliceTransform) InDomain(src []byte) bool { return len(src) >= 3 }\nfunc (st *testSliceTransform) InRange(src []byte) bool { return len(src) == 3 }\n\nfunc TestFixedPrefixTransformOpen(t *testing.T) ", "output": "{\n\tdb := newTestDB(t, \"TestFixedPrefixTransformOpen\", func(opts *Options) {\n\t\topts.SetPrefixExtractor(NewFixedPrefixTransform(3))\n\t})\n\tdefer db.Close()\n}"} {"input": "package shell\n\nimport (\n\t\"context\"\n\n\t\"github.com/hashicorp/hcl/v2/hcldec\"\n\tsl \"github.com/hashicorp/packer/common/shell-local\"\n\t\"github.com/hashicorp/packer/packer\"\n)\n\ntype Provisioner struct {\n\tconfig sl.Config\n}\n\nfunc (p *Provisioner) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }\n\n\n\nfunc (p *Provisioner) Provision(ctx context.Context, ui packer.Ui, _ packer.Communicator, generatedData map[string]interface{}) error {\n\t_, retErr := sl.Run(ctx, ui, &p.config, generatedData)\n\n\treturn retErr\n}\n\nfunc (p *Provisioner) Prepare(raws ...interface{}) error ", "output": "{\n\terr := sl.Decode(&p.config, raws...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = sl.Validate(&p.config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package acpi\n\nimport (\n\t\"testing\"\n\n\t\"github.com/u-root/u-root/pkg/testutil\"\n)\n\n\n\n\nfunc TestRSDP(t *testing.T) ", "output": "{\n\ttestutil.SkipIfNotRoot(t)\n\n\t_, err := GetRSDP()\n\tif err != nil {\n\t\tt.Fatalf(\"GetRSDP: got %v, want nil\", err)\n\t}\n}"} {"input": "package jsondns\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/miekg/dns\"\n)\n\ntype dnsError struct {\n\tStatus uint32 `json:\"Status\"`\n\tComment string `json:\"Comment,omitempty\"`\n}\n\n\n\nfunc FormatError(w http.ResponseWriter, comment string, errcode int) ", "output": "{\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\terrJSON := dnsError{\n\t\tStatus: dns.RcodeServerFailure,\n\t\tComment: comment,\n\t}\n\terrStr, err := json.Marshal(errJSON)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tw.WriteHeader(errcode)\n\tw.Write(errStr)\n}"} {"input": "package lib\n\nimport (\n\t\"log\"\n\t\"strings\"\n)\n\ntype (\n\tQuestion struct {\n\t\tRelatesTo struct {\n\t\t\tAnswers []string `json:\"answers\"`\n\t\t\tSave bool `json:\"save\"`\n\t\t\tSaveTag string `json:\"saveTag\"`\n\t\t} `json:\"relatesTo\"`\n\t\tContext []string `json:\"context\"`\n\t\tQuestionText string `json:\"question\"`\n\t\tPossibleAnswers []string `json:\"answers\"`\n\t}\n\n\tQuestions []*Question\n)\n\nfunc (this Questions) First() *Question {\n\tif len(this) > 0 {\n\t\treturn this[0]\n\t}\n\treturn nil\n}\n\n\n\nfunc (this Questions) nextFrom(prevAnswers ...string) (*Question, bool) {\n\tfor i := range prevAnswers {\n\t\tif nxt, sv := this.next(prevAnswers[i]); nxt != nil {\n\t\t\tlog.Println(\"got it from sticker ...\")\n\t\t\treturn nxt, sv\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc (this *Question) makeKeyboard() Keyboard {\n\tkeyboard := Keyboard{}\n\tfor i := range this.PossibleAnswers {\n\t\tkeyboard = append(keyboard, []string{this.PossibleAnswers[i]})\n\t}\n\treturn keyboard\n}\n\nfunc (this Questions) next(prevAnswer string) (*Question, bool) ", "output": "{\n\tfor i := range this {\n\t\tfor a := range this[i].RelatesTo.Answers {\n\t\t\tif strings.EqualFold(this[i].RelatesTo.Answers[a], prevAnswer) {\n\t\t\t\treturn this[i], this[i].RelatesTo.Save\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, false\n}"} {"input": "package cmd\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestEnvDiff(t *testing.T) {\n\tdiff := &EnvDiff{map[string]string{\"FOO\": \"bar\"}, map[string]string{\"BAR\": \"baz\"}}\n\n\tout := diff.Serialize()\n\n\tdiff2, err := LoadEnvDiff(out)\n\tif err != nil {\n\t\tt.Error(\"parse error\", err)\n\t}\n\n\tif len(diff2.Prev) != 1 {\n\t\tt.Error(\"len(diff2.prev) != 1\", len(diff2.Prev))\n\t}\n\n\tif len(diff2.Next) != 1 {\n\t\tt.Error(\"len(diff2.next) != 0\", len(diff2.Next))\n\t}\n}\n\n\n\nfunc TestEnvDiffEmptyValue(t *testing.T) {\n\tbefore := Env{}\n\tafter := Env{\"FOO\": \"\"}\n\n\tdiff := BuildEnvDiff(before, after)\n\n\tif !reflect.DeepEqual(diff.Next, map[string]string(after)) {\n\t\tt.Errorf(\"diff.Next != after (%#+v != %#+v)\", diff.Next, after)\n\t}\n}\n\n\n\nfunc TestIgnoredEnv(t *testing.T) ", "output": "{\n\tif !IgnoredEnv(DIRENV_BASH) {\n\t\tt.Fail()\n\t}\n\tif IgnoredEnv(DIRENV_DIFF) {\n\t\tt.Fail()\n\t}\n\tif !IgnoredEnv(\"_\") {\n\t\tt.Fail()\n\t}\n\tif !IgnoredEnv(\"__fish_foo\") {\n\t\tt.Fail()\n\t}\n\tif !IgnoredEnv(\"__fishx\") {\n\t\tt.Fail()\n\t}\n}"} {"input": "package rpc\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/rpc\"\n\t\"net/rpc/jsonrpc\"\n\n\t\"github.com/eduardonunesp/sslb/lb\"\n)\n\ntype ServerStatus struct {\n\tServer *lb.Server\n}\n\ntype StatusResponse struct {\n\tIdleWPool int\n}\n\n\n\nfunc StartServer(s *lb.Server) {\n\tgo func() {\n\t\tserverStatus := &ServerStatus{s}\n\n\t\tserver := rpc.NewServer()\n\t\tserver.Register(serverStatus)\n\n\t\taddress := fmt.Sprintf(\"%s:%d\",\n\t\t\ts.Configuration.GeneralConfig.RPCHost,\n\t\t\ts.Configuration.GeneralConfig.RPCPort,\n\t\t)\n\n\t\tserver.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)\n\t\tlistener, e := net.Listen(\"tcp\", address)\n\t\tif e != nil {\n\t\t\tlog.Fatal(\"listen error:\", e)\n\t\t}\n\n\t\tfor {\n\t\t\tif conn, err := listener.Accept(); err != nil {\n\t\t\t\tlog.Fatal(\"accept error: \" + err.Error())\n\t\t\t} else {\n\t\t\t\tgo server.ServeCodec(jsonrpc.NewServerCodec(conn))\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (s *ServerStatus) GetIdle(args interface{}, reply *StatusResponse) error ", "output": "{\n\tstatusRes := StatusResponse{\n\t\ts.Server.CountIdle(),\n\t}\n\n\t*reply = statusRes\n\treturn nil\n}"} {"input": "package ray\n\nimport (\n\t\"github.com/v2ray/v2ray-core/common/alloc\"\n)\n\nconst (\n\tbufferSize = 16\n)\n\n\nfunc NewRay() Ray {\n\treturn &directRay{\n\t\tInput: make(chan *alloc.Buffer, bufferSize),\n\t\tOutput: make(chan *alloc.Buffer, bufferSize),\n\t}\n}\n\ntype directRay struct {\n\tInput chan *alloc.Buffer\n\tOutput chan *alloc.Buffer\n}\n\nfunc (this *directRay) OutboundInput() <-chan *alloc.Buffer {\n\treturn this.Input\n}\n\nfunc (this *directRay) OutboundOutput() chan<- *alloc.Buffer {\n\treturn this.Output\n}\n\n\n\nfunc (this *directRay) InboundOutput() <-chan *alloc.Buffer {\n\treturn this.Output\n}\n\nfunc (this *directRay) InboundInput() chan<- *alloc.Buffer ", "output": "{\n\treturn this.Input\n}"} {"input": "package fake\n\nimport (\n\tcontext \"context\"\n\n\truntime \"k8s.io/apimachinery/pkg/runtime\"\n\trest \"k8s.io/client-go/rest\"\n\tfake \"knative.dev/eventing-prometheus/pkg/client/clientset/versioned/fake\"\n\tclient \"knative.dev/eventing-prometheus/pkg/client/injection/client\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Fake.RegisterClient(withClient)\n\tinjection.Fake.RegisterClientFetcher(func(ctx context.Context) interface{} {\n\t\treturn Get(ctx)\n\t})\n}\n\nfunc withClient(ctx context.Context, cfg *rest.Config) context.Context {\n\tctx, _ = With(ctx)\n\treturn ctx\n}\n\nfunc With(ctx context.Context, objects ...runtime.Object) (context.Context, *fake.Clientset) {\n\tcs := fake.NewSimpleClientset(objects...)\n\treturn context.WithValue(ctx, client.Key{}, cs), cs\n}\n\n\n\n\nfunc Get(ctx context.Context) *fake.Clientset ", "output": "{\n\tuntyped := ctx.Value(client.Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch knative.dev/eventing-prometheus/pkg/client/clientset/versioned/fake.Clientset from context.\")\n\t}\n\treturn untyped.(*fake.Clientset)\n}"} {"input": "package log\n\nimport \"gopkg.in/inconshreveable/log15.v2\"\n\nvar (\n\tLogger log15.Logger\n)\n\nfunc init() {\n\tLogger = log15.New()\n\tLogger.SetHandler(log15.DiscardHandler())\n}\n\n\n\nfunc Interactive() {\n\tLogger.SetHandler(log15.MultiHandler(\n\t\tlog15.LvlFilterHandler(\n\t\t\tlog15.LvlError,\n\t\t\tlog15.StderrHandler)))\n}\n\n\nfunc Debug(msg string, ctx ...interface{}) { Logger.Debug(msg, ctx...) }\n\nfunc Warn(msg string, ctx ...interface{}) { Logger.Warn(msg, ctx...) }\nfunc Error(msg string, ctx ...interface{}) { Logger.Error(msg, ctx...) }\nfunc Crit(msg string, ctx ...interface{}) { Logger.Crit(msg, ctx...) }\n\nfunc Info(msg string, ctx ...interface{}) ", "output": "{ Logger.Info(msg, ctx...) }"} {"input": "package http\n\nimport (\n\t\"github.com/wcong/ants-go/ants/util\"\n\t\"log\"\n\tHttp \"net/http\"\n\t\"strconv\"\n\t\"sync\"\n)\n\ntype HttpServer struct {\n\tHttp.Server\n}\n\nfunc NewHttpServer(setting *util.Settings, handler Http.Handler) *HttpServer {\n\tport := strconv.Itoa(setting.HttpPort)\n\thttpServer := &HttpServer{\n\t\tHttp.Server{\n\t\t\tAddr: \":\" + port,\n\t\t\tHandler: handler,\n\t\t},\n\t}\n\treturn httpServer\n}\n\n\n\nfunc (this *HttpServer) server(wg sync.WaitGroup) {\n\tlog.Println(\"start to server http\" + this.Addr)\n\terr := this.ListenAndServe()\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tlog.Println(\"http server down\")\n\twg.Done()\n}\n\nfunc (this *HttpServer) Start(wg sync.WaitGroup) ", "output": "{\n\tgo this.server(wg)\n}"} {"input": "package gmcache\n\nimport (\n\t\"fmt\"\n\t\"github.com/codinl/go-logger\"\n\t\"github.com/liyue201/gmcache/gmcache/config\"\n\t\"github.com/liyue201/gmcache/utils\"\n\t\"os\"\n)\n\n\n\nfunc InitLog() error ", "output": "{\n\tif !utils.PathExist(config.AppConfig.Log.Dir) {\n\t\tos.MkdirAll(config.AppConfig.Log.Dir, os.ModePerm)\n\t}\n\n\terr := logger.Init(config.AppConfig.Log.Dir, config.AppConfig.Log.File, config.AppConfig.Log.Level)\n\tif err != nil {\n\t\tfmt.Println(\"logger init error err=\", err)\n\t\treturn err\n\t}\n\n\tlogger.SetConsole(true)\n\n\tfmt.Println(\"logger init success\")\n\treturn nil\n}"} {"input": "package fake\n\nimport (\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n\n\taction \"github.com/vmware-tanzu/octant/pkg/action\"\n)\n\n\ntype MockActionRegistrar struct {\n\tctrl *gomock.Controller\n\trecorder *MockActionRegistrarMockRecorder\n}\n\n\ntype MockActionRegistrarMockRecorder struct {\n\tmock *MockActionRegistrar\n}\n\n\nfunc NewMockActionRegistrar(ctrl *gomock.Controller) *MockActionRegistrar {\n\tmock := &MockActionRegistrar{ctrl: ctrl}\n\tmock.recorder = &MockActionRegistrarMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockActionRegistrar) EXPECT() *MockActionRegistrarMockRecorder {\n\treturn m.recorder\n}\n\n\n\n\n\nfunc (mr *MockActionRegistrarMockRecorder) Register(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Register\", reflect.TypeOf((*MockActionRegistrar)(nil).Register), arg0, arg1, arg2)\n}\n\n\nfunc (m *MockActionRegistrar) Unregister(arg0, arg1 string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Unregister\", arg0, arg1)\n}\n\n\nfunc (mr *MockActionRegistrarMockRecorder) Unregister(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Unregister\", reflect.TypeOf((*MockActionRegistrar)(nil).Unregister), arg0, arg1)\n}\n\nfunc (m *MockActionRegistrar) Register(arg0, arg1 string, arg2 action.DispatcherFunc) error ", "output": "{\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Register\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}"} {"input": "package null\n\nimport (\n\t\"github.com/lmorg/murex/lang/stdio\"\n\t\"github.com/lmorg/murex/lang/types\"\n)\n\n\n\nfunc init() ", "output": "{\n\tstdio.RegisterWriteArray(types.Null, newArrayWriter)\n}"} {"input": "package elastic\n\n\n\n\n\n\n\n\n\ntype MissingAggregation struct {\n\tfield string\n\tsubAggregations map[string]Aggregation\n\tmeta map[string]interface{}\n}\n\nfunc NewMissingAggregation() *MissingAggregation {\n\treturn &MissingAggregation{\n\t\tsubAggregations: make(map[string]Aggregation),\n\t}\n}\n\nfunc (a *MissingAggregation) Field(field string) *MissingAggregation {\n\ta.field = field\n\treturn a\n}\n\nfunc (a *MissingAggregation) SubAggregation(name string, subAggregation Aggregation) *MissingAggregation {\n\ta.subAggregations[name] = subAggregation\n\treturn a\n}\n\n\nfunc (a *MissingAggregation) Meta(metaData map[string]interface{}) *MissingAggregation {\n\ta.meta = metaData\n\treturn a\n}\n\n\n\nfunc (a *MissingAggregation) Source() (interface{}, error) ", "output": "{\n\n\tsource := make(map[string]interface{})\n\topts := make(map[string]interface{})\n\tsource[\"missing\"] = opts\n\n\tif a.field != \"\" {\n\t\topts[\"field\"] = a.field\n\t}\n\n\tif len(a.subAggregations) > 0 {\n\t\taggsMap := make(map[string]interface{})\n\t\tsource[\"aggregations\"] = aggsMap\n\t\tfor name, aggregate := range a.subAggregations {\n\t\t\tsrc, err := aggregate.Source()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\taggsMap[name] = src\n\t\t}\n\t}\n\n\tif len(a.meta) > 0 {\n\t\tsource[\"meta\"] = a.meta\n\t}\n\n\treturn source, nil\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/VojtechVitek/ratelimit\"\n)\n\n\nfunc main() {\n\tmiddleware := ratelimit.Throttle(1)\n\n\thttp.ListenAndServe(\":3333\", middleware(http.HandlerFunc(Work)))\n}\n\n\n\nfunc Work(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tw.Write([]byte(\"working hard...\\n\\n\"))\n\tif f, ok := w.(http.Flusher); ok {\n\t\tf.Flush()\n\t}\n\ttime.Sleep(10 * time.Second)\n\tw.Write([]byte(\"done\"))\n}"} {"input": "package message\n\nimport (\n\t\"bytes\"\n\t\"math/rand\"\n\t\"time\"\n\n\t\"encoding/json\"\n)\n\n\n\n\nconst MaxVectors = 32\nconst PacketSize = 512\n\ntype Packet []byte\n\ntype Vector struct {\n\tX int\n\tY int\n}\n\ntype Message struct {\n\tName int\n\tVectors []*Vector\n\tValue string\n}\n\nvar delim = byte(0)\n\n\n\n\n\nfunc MessageToPacket(m *Message) Packet {\n\n\tbuf := new(bytes.Buffer)\n\tenc := json.NewEncoder(buf)\n\tenc.Encode(m)\n\n\tif buf.Len() > PacketSize {\n\t\tprintln(\"len m v's \", len(m.Vectors))\n\t}\n\n\tbuf.WriteByte(delim)\n\tpacket := make([]byte, PacketSize)\n\tbuf.Read(packet)\n\n\treturn packet\n}\n\nfunc PacketToMessage(p []byte) *Message {\n\tvar in bytes.Buffer\n\tin.Write(p)\n\n\tb, e := in.ReadBytes(delim)\n\tif e != nil {\n\t\tprintln(e)\n\t}\n\tvar m Message\n\tjson.Unmarshal(b[:len(b)-1], &m)\n\n\treturn &m\n}\n\nfunc randVectors(num int) []*Vector {\n\n\tresults := make([]*Vector, num)\n\tfor i := range results {\n\t\txdir := random(1, 6)\n\t\tydir := random(1, 10)\n\n\t\tv := &Vector{xdir, ydir}\n\n\t\tresults[i] = v\n\t}\n\n\treturn results\n}\n\nfunc random(min, max int) int {\n\trand.Seed(time.Now().Unix())\n\treturn rand.Intn(max-min) + min\n}\n\nfunc VectorsToMessages(vectors []*Vector, name int) []*Message ", "output": "{\n\n\tif len(vectors) <= MaxVectors {\n\n\t\tresults := make([]*Message, 0)\n\t\tresults = append(results, &Message{Name: name, Vectors: vectors})\n\t\treturn results\n\t}\n\n\tnumMessages := len(vectors) / MaxVectors\n\tresults := make([]*Message, numMessages)\n\n\tj := 0\n\tfor i := range results {\n\t\tm := &Message{Vectors: make([]*Vector, 0)}\n\t\tfor len(m.Vectors) < MaxVectors && j < len(vectors)-1 {\n\t\t\tm.Vectors = append(m.Vectors, vectors[j])\n\t\t\tj++\n\t\t}\n\t\tresults[i] = m\n\t}\n\n\treturn results\n}"} {"input": "package utils\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n\n\t\"github.com/astaxie/beego\"\n)\n\nvar testRandNum int\nvar testRandString string\n\n\nfunc SetTestRandNum(n int) {\n\tif !IsTest() {\n\t\treturn\n\t}\n\n\ttestRandNum = n\n}\n\n\nfunc GetRandNum(n int) int {\n\tif IsTest() {\n\t\treturn testRandNum\n\t}\n\n\trand.Seed(time.Now().UnixNano())\n\n\treturn rand.Intn(n)\n}\n\n\n\n\n\nfunc GetRandString(n int) string {\n\tif IsTest() {\n\t\treturn testRandString\n\t}\n\n\trs2Letters := beego.AppConfig.String(\"randKey\")\n\n\tb := make([]byte, n)\n\tfor i := range b {\n\t\tb[i] = rs2Letters[rand.Intn(len(rs2Letters))]\n\t}\n\n\treturn string(b)\n}\n\nfunc SetTestRandString(s string) ", "output": "{\n\tif !IsTest() {\n\t\treturn\n\t}\n\n\ttestRandString = s\n}"} {"input": "package persona\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\ntype personaResponse struct {\n\tStatus string `json:\"status\"`\n\tEmail string `json:\"email\"`\n}\n\n\n\nfunc assert(audience, assertion string) (string, error) ", "output": "{\n\tparams := url.Values{}\n\tparams.Add(\"assertion\", assertion)\n\tparams.Add(\"audience\", audience)\n\n\tresp, err := http.PostForm(\"https://verifier.login.persona.org/verify\", params)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tvar f personaResponse\n\terr = json.Unmarshal(body, &f)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif f.Status != \"okay\" {\n\t\treturn \"\", errors.New(\"Status not okay\")\n\t}\n\n\treturn f.Email, nil\n}"} {"input": "package playground \n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst baseURL = \"https://play.golang.org\"\n\nfunc init() {\n\thttp.HandleFunc(\"/compile\", bounce)\n\thttp.HandleFunc(\"/share\", bounce)\n}\n\nfunc bounce(w http.ResponseWriter, r *http.Request) {\n\tb := new(bytes.Buffer)\n\tif err := passThru(b, r); err != nil {\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treport(r, err)\n\t\treturn\n\t}\n\tio.Copy(w, b)\n}\n\n\n\nvar onAppengine = false \n\nfunc allowShare(r *http.Request) bool {\n\tif !onAppengine {\n\t\treturn true\n\t}\n\tswitch r.Header.Get(\"X-AppEngine-Country\") {\n\tcase \"\", \"ZZ\", \"CN\":\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc passThru(w io.Writer, req *http.Request) error ", "output": "{\n\tif req.URL.Path == \"/share\" && !allowShare(req) {\n\t\treturn errors.New(\"Forbidden\")\n\t}\n\tdefer req.Body.Close()\n\turl := baseURL + req.URL.Path\n\tctx, cancel := context.WithTimeout(contextFunc(req), 60*time.Second)\n\tdefer cancel()\n\tr, err := post(ctx, url, req.Header.Get(\"Content-type\"), req.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"making POST request: %v\", err)\n\t}\n\tdefer r.Body.Close()\n\tif _, err := io.Copy(w, r.Body); err != nil {\n\t\treturn fmt.Errorf(\"copying response Body: %v\", err)\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport \"errors\"\n\n\n\ntype Item struct {\n\tId int\n\tPath string\n}\n\ntype Status struct {\n\tStatus string\n\tList []Item\n\tId int\n}\n\nconst (\n\tStateStopped = iota\n\tStatePlaying\n)\n\n\n\nvar items []Item\nvar nextId int\nvar currentTrack int\nvar currentState int\n\n\n\nfunc addItem(path string) (id int) {\n\tid = nextId\n\titems = append(items, Item{Id: nextId, Path: path})\n\tnextId = nextId + 1\n\treturn\n}\n\nfunc itemIndex(id int) (i int, err error) {\n\tfor i = 0; i < len(items); i++ {\n\t\tif items[i].Id == id {\n\t\t\treturn\n\t\t}\n\t}\n\terr = errors.New(\"no item with that id found\")\n\treturn\n}\n\nfunc removeItem(id int) (err error) {\n\ti, err := itemIndex(id)\n\tif err != nil {\n\t\treturn\n\t}\n\titems = append(items[:i], items[i+1:]...)\n\treturn\n}\n\n\n\nfunc initialize() ", "output": "{\n\titems = []Item{}\n\tnextId = 1\n\tcurrentTrack = 0\n\tcurrentState = StateStopped\n}"} {"input": "package serialconsole\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/serialconsole/mgmt/2018-05-01/serialconsole\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype BaseClient = original.BaseClient\ntype ConsoleClient = original.ConsoleClient\ntype DeploymentValidateResult = original.DeploymentValidateResult\ntype GetDisabledResult = original.GetDisabledResult\ntype GetResult = original.GetResult\ntype ListClient = original.ListClient\ntype ListConsoleClient = original.ListConsoleClient\ntype Operations = original.Operations\ntype SetDisabledResult = original.SetDisabledResult\n\nfunc New(subscriptionID string) BaseClient {\n\treturn original.New(subscriptionID)\n}\nfunc NewConsoleClient(subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClient(subscriptionID)\n}\nfunc NewConsoleClientWithBaseURI(baseURI string, subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewListClient(subscriptionID string) ListClient {\n\treturn original.NewListClient(subscriptionID)\n}\nfunc NewListClientWithBaseURI(baseURI string, subscriptionID string) ListClient {\n\treturn original.NewListClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewListConsoleClient(subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClient(subscriptionID)\n}\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\n\nfunc NewListConsoleClientWithBaseURI(baseURI string, subscriptionID string) ListConsoleClient ", "output": "{\n\treturn original.NewListConsoleClientWithBaseURI(baseURI, subscriptionID)\n}"} {"input": "package blobstore\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync\"\n)\n\ntype localStore struct {\n\tsync.Mutex\n\troot string\n}\n\n\nfunc NewLocalStore(root string) (Store, error) {\n\treturn newLocalStore(root)\n}\n\nfunc (ls *localStore) blobDirname(digest string) string {\n\treturn filepath.Join(ls.root, \"blobs\", digest)\n}\n\nfunc (ls *localStore) blobFilename(digest string) string {\n\treturn filepath.Join(ls.blobDirname(digest), \"blob\")\n}\n\nfunc (ls *localStore) blobInfoFilename(digest string) string {\n\treturn filepath.Join(ls.blobDirname(digest), \"info.json\")\n}\n\n\n\n\n\nfunc newLocalStore(root string) (*localStore, error) ", "output": "{\n\tls := &localStore{root: root}\n\n\tblobsDirname := ls.blobDirname(\"\")\n\tif err := os.MkdirAll(blobsDirname, os.FileMode(0755)); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create local blob store directory %q: %s\", blobsDirname, err)\n\t}\n\n\treturn ls, nil\n}"} {"input": "package client\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/akutz/gotil\"\n)\n\nfunc (c *client) logRequest(req *http.Request) {\n\n\tif !c.logRequests {\n\t\treturn\n\t}\n\n\tw := log.StandardLogger().Writer()\n\n\tfmt.Fprintln(w, \"\")\n\tfmt.Fprint(w, \" -------------------------- \")\n\tfmt.Fprint(w, \"HTTP REQUEST (CLIENT)\")\n\tfmt.Fprintln(w, \" -------------------------\")\n\n\tbuf, err := httputil.DumpRequest(req, true)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgotil.WriteIndented(w, buf)\n\tfmt.Fprintln(w)\n}\n\n\n\nfunc (c *client) logResponse(res *http.Response) ", "output": "{\n\n\tif !c.logResponses {\n\t\treturn\n\t}\n\n\tw := log.StandardLogger().Writer()\n\n\tfmt.Fprintln(w)\n\tfmt.Fprint(w, \" -------------------------- \")\n\tfmt.Fprint(w, \"HTTP RESPONSE (CLIENT)\")\n\tfmt.Fprintln(w, \" -------------------------\")\n\n\tbuf, err := httputil.DumpResponse(\n\t\tres,\n\t\tres.Header.Get(\"Content-Type\") != \"application/octet-stream\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbw := &bytes.Buffer{}\n\tgotil.WriteIndented(bw, buf)\n\n\tscanner := bufio.NewScanner(bw)\n\tfor {\n\t\tif !scanner.Scan() {\n\t\t\tbreak\n\t\t}\n\t\tfmt.Fprintln(w, scanner.Text())\n\t}\n}"} {"input": "package kubectl\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n)\n\n\n\n\ntype FilterFunc func(runtime.Object, PrintOptions) bool\n\n\ntype Filters []FilterFunc\n\nfunc NewResourceFilter() Filters {\n\treturn []FilterFunc{\n\t\tfilterPods,\n\t}\n}\n\n\n\nfunc filterPods(obj runtime.Object, options PrintOptions) bool {\n\tswitch p := obj.(type) {\n\tcase *v1.Pod:\n\t\treason := string(p.Status.Phase)\n\t\tif p.Status.Reason != \"\" {\n\t\t\treason = p.Status.Reason\n\t\t}\n\t\treturn !options.ShowAll && (reason == string(v1.PodSucceeded) || reason == string(v1.PodFailed))\n\tcase *api.Pod:\n\t\treason := string(p.Status.Phase)\n\t\tif p.Status.Reason != \"\" {\n\t\t\treason = p.Status.Reason\n\t\t}\n\t\treturn !options.ShowAll && (reason == string(api.PodSucceeded) || reason == string(api.PodFailed))\n\t}\n\treturn false\n}\n\n\nfunc (f Filters) Filter(obj runtime.Object, opts *PrintOptions) (bool, error) {\n\tobj, _ = DecodeUnknownObject(obj)\n\n\tfor _, filter := range f {\n\t\tif ok := filter(obj, *opts); ok {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}\n\n\n\n\nfunc DecodeUnknownObject(obj runtime.Object) (runtime.Object, error) ", "output": "{\n\tvar err error\n\n\tswitch obj.(type) {\n\tcase runtime.Unstructured, *runtime.Unknown:\n\t\tif objBytes, err := runtime.Encode(api.Codecs.LegacyCodec(), obj); err == nil {\n\t\t\tif decodedObj, err := runtime.Decode(api.Codecs.UniversalDecoder(), objBytes); err == nil {\n\t\t\t\tobj = decodedObj\n\t\t\t}\n\t\t}\n\t}\n\n\treturn obj, err\n}"} {"input": "package format\n\nimport (\n\t\"github.com/kitwalker12/fotomat/vips\"\n)\n\n\ntype Metadata struct {\n\tWidth int\n\tHeight int\n\tFormat Format\n\tOrientation Orientation\n\tHasAlpha bool\n}\n\n\n\n\n\nfunc (format Format) MetadataBytes(blob []byte) (Metadata, error) {\n\timage, err := format.LoadBytes(blob)\n\tif err != nil {\n\t\treturn Metadata{}, ErrUnknownFormat\n\t}\n\n\tdefer image.Close()\n\n\treturn metadataImageFormat(image, format), nil\n}\n\n\nfunc (format Format) MetadataFile(filename string) (Metadata, error) {\n\timage, err := format.LoadFile(filename)\n\tif err != nil {\n\t\treturn Metadata{}, err\n\t}\n\n\tdefer image.Close()\n\n\treturn metadataImageFormat(image, format), nil\n}\n\nfunc metadataImageFormat(image *vips.Image, format Format) Metadata {\n\tm := MetadataImage(image)\n\tm.Format = format\n\treturn m\n}\n\n\nfunc MetadataImage(image *vips.Image) Metadata {\n\to := DetectOrientation(image)\n\tw, h := o.Dimensions(image.Xsize(), image.Ysize())\n\tif w <= 0 || h <= 0 {\n\t\tpanic(\"Invalid image dimensions.\")\n\t}\n\treturn Metadata{Width: w, Height: h, Orientation: o, HasAlpha: image.HasAlpha()}\n}\n\nfunc MetadataBytes(blob []byte) (Metadata, error) ", "output": "{\n\tformat := DetectFormat(blob)\n\tif format == Unknown {\n\t\treturn Metadata{}, ErrUnknownFormat\n\t}\n\n\treturn format.MetadataBytes(blob)\n}"} {"input": "package errorreporting \n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\n\n\n\nfunc DefaultAuthScopes() []string {\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t}\n}\n\nfunc insertXGoog(ctx context.Context, val []string) context.Context ", "output": "{\n\tmd, _ := metadata.FromOutgoingContext(ctx)\n\tmd = md.Copy()\n\tmd[\"x-goog-api-client\"] = val\n\treturn metadata.NewOutgoingContext(ctx, md)\n}"} {"input": "package comm\n\nimport (\n\t\"context\"\n\n\t\"github.com/hyperledger/fabric/common/semaphore\"\n\t\"google.golang.org/grpc\"\n)\n\ntype Semaphore interface {\n\tAcquire(ctx context.Context) error\n\tRelease()\n}\n\ntype Throttle struct {\n\tnewSemaphore NewSemaphoreFunc\n\tsemaphore Semaphore\n}\n\ntype ThrottleOption func(t *Throttle)\ntype NewSemaphoreFunc func(size int) Semaphore\n\nfunc WithNewSemaphore(newSemaphore NewSemaphoreFunc) ThrottleOption {\n\treturn func(t *Throttle) {\n\t\tt.newSemaphore = newSemaphore\n\t}\n}\n\n\n\nfunc (t *Throttle) UnaryServerIntercptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {\n\tif err := t.semaphore.Acquire(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer t.semaphore.Release()\n\n\treturn handler(ctx, req)\n}\n\nfunc (t *Throttle) StreamServerInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {\n\tctx := ss.Context()\n\tif err := t.semaphore.Acquire(ctx); err != nil {\n\t\treturn err\n\t}\n\tdefer t.semaphore.Release()\n\n\treturn handler(srv, ss)\n}\n\nfunc NewThrottle(maxConcurrency int, options ...ThrottleOption) *Throttle ", "output": "{\n\tt := &Throttle{\n\t\tnewSemaphore: func(count int) Semaphore { return semaphore.New(count) },\n\t}\n\n\tfor _, optionFunc := range options {\n\t\toptionFunc(t)\n\t}\n\n\tt.semaphore = t.newSemaphore(maxConcurrency)\n\treturn t\n}"} {"input": "package thrift\n\nimport \"io\"\n\ntype RichTransport struct {\n\tTTransport\n}\n\n\n\n\nfunc (r *RichTransport) ReadByte() (c byte, err error) {\n\treturn readByte(r.TTransport)\n}\n\nfunc (r *RichTransport) WriteByte(c byte) error {\n\treturn writeByte(r.TTransport, c)\n}\n\nfunc (r *RichTransport) WriteString(s string) (n int, err error) {\n\treturn r.Write([]byte(s))\n}\n\nfunc (r *RichTransport) RemainingBytes() (num_bytes uint64) {\n\treturn r.TTransport.RemainingBytes()\n}\n\nfunc readByte(r io.Reader) (c byte, err error) {\n\tv := [1]byte{0}\n\tn, err := r.Read(v[0:1])\n\tif n > 0 && (err == nil || err == io.EOF) {\n\t\treturn v[0], nil\n\t}\n\tif n > 0 && err != nil {\n\t\treturn v[0], err\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn v[0], nil\n}\n\nfunc writeByte(w io.Writer, c byte) error {\n\tv := [1]byte{c}\n\t_, err := w.Write(v[0:1])\n\treturn err\n}\n\nfunc NewTRichTransport(trans TTransport) *RichTransport ", "output": "{\n\treturn &RichTransport{trans}\n}"} {"input": "package model\n\ntype RepoSecret struct {\n\tID int64 `json:\"id\" meddler:\"secret_id,pk\"`\n\n\tRepoID int64 `json:\"-\" meddler:\"secret_repo_id\"`\n\n\tName string `json:\"name\" meddler:\"secret_name\"`\n\n\tValue string `json:\"value\" meddler:\"secret_value\"`\n\n\tImages []string `json:\"image,omitempty\" meddler:\"secret_images,json\"`\n\n\tEvents []string `json:\"event,omitempty\" meddler:\"secret_events,json\"`\n\n\tSkipVerify bool `json:\"skip_verify\" meddler:\"secret_skip_verify\"`\n\n\tConceal bool `json:\"conceal\" meddler:\"secret_conceal\"`\n}\n\n\nfunc (s *RepoSecret) Secret() *Secret {\n\treturn &Secret{\n\t\tName: s.Name,\n\t\tValue: s.Value,\n\t\tImages: s.Images,\n\t\tEvents: s.Events,\n\t\tSkipVerify: s.SkipVerify,\n\t\tConceal: s.Conceal,\n\t}\n}\n\n\nfunc (s *RepoSecret) Clone() *RepoSecret {\n\treturn &RepoSecret{\n\t\tID: s.ID,\n\t\tName: s.Name,\n\t\tImages: s.Images,\n\t\tEvents: s.Events,\n\t\tSkipVerify: s.SkipVerify,\n\t\tConceal: s.Conceal,\n\t}\n}\n\n\n\n\nfunc (s *RepoSecret) Validate() error ", "output": "{\n\treturn nil\n}"} {"input": "package client\n\nimport (\n\t\"encoding/xml\"\n)\n\ntype Frame struct {\n\tID string `xml:\"id,attr\"`\n\tFrameType int\n\tOpMode int\n\tName string\n\tContact string\n\tOSVersion string\n\tVersion string\n\tIsConnected int\n\tSyncedSetting int\n\n}\n\n\ntype FrameCollection map[string]Frame\n\nfunc (col *FrameCollection) UnmarshalXML(d *xml.Decoder, e xml.StartElement) error {\n\treturn unmarshalXMLCol(col, d, e)\n}\n\n\n\nfunc (col FrameCollection) MarshalJSON() ([]byte, error) ", "output": "{\n\treturn marshalJSONMap(col)\n}"} {"input": "package lzma\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"unicode\"\n)\n\n\n\ntype operation interface {\n\tLen() int\n}\n\n\ntype match struct {\n\tdistance int64\n\tn int\n}\n\n\n\nfunc (m match) verify() error {\n\tif !(minDistance <= m.distance && m.distance <= maxDistance) {\n\t\treturn errors.New(\"distance out of range\")\n\t}\n\tif !(1 <= m.n && m.n <= maxMatchLen) {\n\t\treturn errors.New(\"length out of range\")\n\t}\n\treturn nil\n}\n\n\n\nfunc (m match) l() uint32 {\n\treturn uint32(m.n - minMatchLen)\n}\n\n\n\nfunc (m match) dist() uint32 {\n\treturn uint32(m.distance - minDistance)\n}\n\n\n\n\n\nfunc (m match) String() string {\n\treturn fmt.Sprintf(\"M{%d,%d}\", m.distance, m.n)\n}\n\n\ntype lit struct {\n\tb byte\n}\n\n\nfunc (l lit) Len() int {\n\treturn 1\n}\n\n\nfunc (l lit) String() string {\n\tvar c byte\n\tif unicode.IsPrint(rune(l.b)) {\n\t\tc = l.b\n\t} else {\n\t\tc = '.'\n\t}\n\treturn fmt.Sprintf(\"L{%c/%02x}\", c, l.b)\n}\n\nfunc (m match) Len() int ", "output": "{\n\treturn m.n\n}"} {"input": "package main\n\n\n\nimport (\n\t\"github.com/faceless-saint/go-socketcmd\"\n\n\t\"os\"\n\t\"strings\"\n)\n\nconst EnvSocketPath = \"SOCKET_PATH\"\n\nvar ExampleSocketPath = \"example.sock\"\n\n\n\nfunc main() {\n\tclient := socketcmd.NewClient(\"unix\", ExampleSocketPath, nil)\n\n\tif resp, err := client.Send(os.Args[1:]...); err != nil {\n\t\tpanic(err)\n\t} else {\n\t\tfmt.Println(strings.Join(resp, \"\\n\"))\n\t}\n}\n\nfunc init() ", "output": "{\n\tenvPath := os.Getenv(EnvSocketPath)\n\tif envPath != \"\" {\n\t\tExampleSocketPath = envPath\n\t}\n}"} {"input": "package codec\n\nimport \"time\"\n\n\n\nfunc fmtTime(t time.Time, fmt string, b []byte) []byte ", "output": "{\n\ts := t.Format(fmt)\n\tb = b[:len(s)]\n\tcopy(b, s)\n\treturn b\n}"} {"input": "package daemon\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/docker/docker/container\"\n)\n\n\n\n\n\n\nfunc fixPermissions(source, destination string, uid, gid int, destExisted bool) error {\n\tdestStat, err := os.Stat(destination)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdoChownDestination := !destExisted || !destStat.IsDir()\n\n\treturn filepath.Walk(source, func(fullpath string, info os.FileInfo, err error) error {\n\t\tif !doChownDestination && (source == fullpath) {\n\t\t\treturn nil\n\t\t}\n\n\t\tcleaned, err := filepath.Rel(source, fullpath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfullpath = filepath.Join(destination, cleaned)\n\t\treturn os.Lchown(fullpath, uid, gid)\n\t})\n}\n\nfunc checkIfPathIsInAVolume(container *container.Container, absPath string) (bool, error) ", "output": "{\n\tvar toVolume bool\n\tfor _, mnt := range container.MountPoints {\n\t\tif toVolume = mnt.HasResource(absPath); toVolume {\n\t\t\tif mnt.RW {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn false, ErrVolumeReadonly\n\t\t}\n\t}\n\treturn toVolume, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/karrick/godirwalk\"\n\t\"github.com/pkg/errors\"\n)\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Fprintf(os.Stderr, \"usage: %s dir1 [dir2 [dir3...]]\\n\", filepath.Base(os.Args[0]))\n\t\tos.Exit(2)\n\t}\n\n\tscratchBuffer := make([]byte, 64*1024) \n\tvar count, total int\n\tvar err error\n\n\tfor _, arg := range os.Args[1:] {\n\t\tcount, err = pruneEmptyDirectories(arg, scratchBuffer)\n\t\ttotal += count\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfmt.Fprintf(os.Stderr, \"Removed %d empty directories\\n\", total)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"ERROR: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\n\n\nfunc pruneEmptyDirectories(osDirname string, scratchBuffer []byte) (int, error) ", "output": "{\n\tvar count int\n\n\terr := godirwalk.Walk(osDirname, &godirwalk.Options{\n\t\tUnsorted: true,\n\t\tScratchBuffer: scratchBuffer,\n\t\tCallback: func(_ string, _ *godirwalk.Dirent) error {\n\t\t\treturn nil\n\t\t},\n\t\tPostChildrenCallback: func(osPathname string, _ *godirwalk.Dirent) error {\n\t\t\tdeChildren, err := godirwalk.ReadDirents(osPathname, scratchBuffer)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"cannot ReadDirents\")\n\t\t\t}\n\t\t\tif len(deChildren) > 0 {\n\t\t\t\treturn nil \n\t\t\t}\n\t\t\tif osPathname == osDirname {\n\t\t\t\treturn nil \n\t\t\t}\n\t\t\terr = os.Remove(osPathname)\n\t\t\tif err == nil {\n\t\t\t\tcount++\n\t\t\t}\n\t\t\treturn err\n\t\t},\n\t})\n\n\treturn count, err\n}"} {"input": "package phaul\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype images struct {\n\tcursor int\n\tdir string\n}\n\n\n\nfunc (i *images) getPath(idx int) string {\n\treturn fmt.Sprintf(i.dir+\"/%d\", idx)\n}\n\nfunc (i *images) openNextDir() (*os.File, error) {\n\tipath := i.getPath(i.cursor)\n\terr := os.Mkdir(ipath, 0700)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ti.cursor++\n\treturn os.Open(ipath)\n}\n\nfunc (i *images) lastImagesDir() string {\n\tvar ret string\n\tif i.cursor == 0 {\n\t\tret = \"\"\n\t} else {\n\t\tret, _ = filepath.Abs(i.getPath(i.cursor - 1))\n\t}\n\treturn ret\n}\n\nfunc preparePhaulImages(wdir string) (*images, error) ", "output": "{\n\treturn &images{dir: wdir}, nil\n}"} {"input": "package v1\n\n\n\ntype ConfigMapProjectionApplyConfiguration struct {\n\tLocalObjectReferenceApplyConfiguration `json:\",inline\"`\n\tItems []KeyToPathApplyConfiguration `json:\"items,omitempty\"`\n\tOptional *bool `json:\"optional,omitempty\"`\n}\n\n\n\nfunc ConfigMapProjection() *ConfigMapProjectionApplyConfiguration {\n\treturn &ConfigMapProjectionApplyConfiguration{}\n}\n\n\n\n\nfunc (b *ConfigMapProjectionApplyConfiguration) WithName(value string) *ConfigMapProjectionApplyConfiguration {\n\tb.Name = &value\n\treturn b\n}\n\n\n\n\nfunc (b *ConfigMapProjectionApplyConfiguration) WithItems(values ...*KeyToPathApplyConfiguration) *ConfigMapProjectionApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithItems\")\n\t\t}\n\t\tb.Items = append(b.Items, *values[i])\n\t}\n\treturn b\n}\n\n\n\n\n\n\nfunc (b *ConfigMapProjectionApplyConfiguration) WithOptional(value bool) *ConfigMapProjectionApplyConfiguration ", "output": "{\n\tb.Optional = &value\n\treturn b\n}"} {"input": "package two\n\nimport (\n\t\"math\"\n\t\"strings\"\n)\n\ntype Key struct {\n\tcode string\n\tU bool\n\tR bool\n\tD bool\n\tL bool\n}\n\nfunc KeypadCode(lines []string, keypad map[int]Key, currentKeypadIndex int) string {\n\tcode := make([]string, len(lines))\n\n\trowsQty := int(math.Sqrt(float64(len(keypad))))\n\n\tcurrentKey := keypad[currentKeypadIndex]\n\n\tfor i, line := range lines {\n\t\tlineDirections := strings.Split(line, \"\")\n\t\tfor _, direction := range lineDirections {\n\t\t\tif direction == \"U\" && currentKey.U == true {\n\t\t\t\tcurrentKeypadIndex = currentKeypadIndex - rowsQty\n\t\t\t}\n\t\t\tif direction == \"R\" && currentKey.R == true {\n\t\t\t\tcurrentKeypadIndex = currentKeypadIndex + 1\n\t\t\t}\n\t\t\tif direction == \"D\" && currentKey.D == true {\n\t\t\t\tcurrentKeypadIndex = currentKeypadIndex + rowsQty\n\t\t\t}\n\t\t\tif direction == \"L\" && currentKey.L == true {\n\t\t\t\tcurrentKeypadIndex = currentKeypadIndex - 1\n\t\t\t}\n\t\t\tcurrentKey = keypad[currentKeypadIndex]\n\t\t}\n\t\tcode[i] = currentKey.code\n\t}\n\treturn strings.Join(code, \"\")\n}\n\n\n\nfunc DayTwoPartOne(directions string) string ", "output": "{\n\tlines := strings.Split(directions, \"\\n\")\n\tkeypad := make(map[int]Key)\n\n\tkeypad[0] = Key{\"1\", false, true, true, false}\n\tkeypad[1] = Key{\"2\", false, true, true, true}\n\tkeypad[2] = Key{\"3\", false, false, true, true}\n\n\tkeypad[3] = Key{\"4\", true, true, true, false}\n\tkeypad[4] = Key{\"5\", true, true, true, true}\n\tkeypad[5] = Key{\"6\", true, false, true, true}\n\n\tkeypad[6] = Key{\"7\", true, true, false, false}\n\tkeypad[7] = Key{\"8\", true, true, false, true}\n\tkeypad[8] = Key{\"9\", true, false, false, true}\n\n\treturn KeypadCode(lines, keypad, 4)\n}"} {"input": "package path\n\nimport (\n\t\"encoding/binary\"\n\t\"time\"\n\n\t\"github.com/scionproto/scion/go/lib/serrors\"\n)\n\nconst (\n\tHopLen = 12\n\tMacLen = 6\n)\n\n\nconst MaxTTL = 24 * 60 * 60 \n\nconst expTimeUnit = MaxTTL / 256 \n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype HopField struct {\n\tIngressRouterAlert bool\n\tEgressRouterAlert bool\n\tExpTime uint8\n\tConsIngress uint16\n\tConsEgress uint16\n\tMac [MacLen]byte\n}\n\n\n\n\n\n\n\nfunc (h *HopField) SerializeTo(b []byte) error {\n\tif len(b) < HopLen {\n\t\treturn serrors.New(\"buffer for HopField too short\", \"expected\", MacLen, \"actual\", len(b))\n\t}\n\tb[0] = 0\n\tif h.EgressRouterAlert {\n\t\tb[0] |= 0x1\n\t}\n\tif h.IngressRouterAlert {\n\t\tb[0] |= 0x2\n\t}\n\tb[1] = h.ExpTime\n\tbinary.BigEndian.PutUint16(b[2:4], h.ConsIngress)\n\tbinary.BigEndian.PutUint16(b[4:6], h.ConsEgress)\n\tcopy(b[6:6+MacLen], h.Mac[:])\n\n\treturn nil\n}\n\n\n\nfunc ExpTimeToDuration(expTime uint8) time.Duration {\n\treturn (time.Duration(expTime) + 1) * time.Duration(expTimeUnit) * time.Second\n}\n\nfunc (h *HopField) DecodeFromBytes(raw []byte) error ", "output": "{\n\tif len(raw) < HopLen {\n\t\treturn serrors.New(\"HopField raw too short\", \"expected\", HopLen, \"actual\", len(raw))\n\t}\n\th.EgressRouterAlert = raw[0]&0x1 == 0x1\n\th.IngressRouterAlert = raw[0]&0x2 == 0x2\n\th.ExpTime = raw[1]\n\th.ConsIngress = binary.BigEndian.Uint16(raw[2:4])\n\th.ConsEgress = binary.BigEndian.Uint16(raw[4:6])\n\tcopy(h.Mac[:], raw[6:6+MacLen])\n\treturn nil\n}"} {"input": "package suite_init\n\ntype SuiteData struct {\n\t*StubsData\n\t*SynchronizedSuiteCallbacksData\n\t*WerfBinaryData\n\t*ProjectNameData\n\t*K8sDockerRegistryData\n\t*TmpDirData\n\t*ContainerRegistryPerImplementationData\n}\n\nfunc (data *SuiteData) SetupStubs(setupData *StubsData) bool {\n\tdata.StubsData = setupData\n\treturn true\n}\n\n\n\nfunc (data *SuiteData) SetupWerfBinary(setupData *WerfBinaryData) bool {\n\tdata.WerfBinaryData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupProjectName(setupData *ProjectNameData) bool {\n\tdata.ProjectNameData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupK8sDockerRegistry(setupData *K8sDockerRegistryData) bool {\n\tdata.K8sDockerRegistryData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupTmp(setupData *TmpDirData) bool {\n\tdata.TmpDirData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupContainerRegistryPerImplementation(setupData *ContainerRegistryPerImplementationData) bool {\n\tdata.ContainerRegistryPerImplementationData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupSynchronizedSuiteCallbacks(setupData *SynchronizedSuiteCallbacksData) bool ", "output": "{\n\tdata.SynchronizedSuiteCallbacksData = setupData\n\treturn true\n}"} {"input": "package queue\n\nimport \"testing\"\n\n\n\nfunc TestQueueS(t *testing.T) {\n\tq := NewSQ()\n\n\tif !q.IsEmpty() ||\n\t\tq.size != 0 ||\n\t\tq.Size() != 0 {\n\t\tt.Error()\n\t}\n\n\tq.EnQueue(0)\n\tq.EnQueue(1)\n\tq.EnQueue(2)\n\n\tif q.Size() != 3 {\n\t\tt.Error()\n\t}\n\n\te0 := q.DeQueue()\n\n\tif e0 != 0 || q.Size() != 2 {\n\t\tt.Error()\n\t}\n\n\te1 := q.DeQueue()\n\n\tif e1 != 1 {\n\t\tt.Error()\n\t}\n\n\te2 := q.DeQueue()\n\n\tif e2 != 2 || q.Size() != 0 {\n\t\tt.Error()\n\t}\n\n\tee := q.DeQueue()\n\n\tif ee != nil || q.Size() != 0 {\n\t\tt.Error()\n\t}\n}\n\nfunc TestQueue(t *testing.T) ", "output": "{\n\tq := New()\n\n\tif !q.IsEmpty() ||\n\t\tq.size != 0 ||\n\t\tq.Size() != 0 {\n\t\tt.Error()\n\t}\n\n\tq.EnQueue(0)\n\tq.EnQueue(1)\n\tq.EnQueue(2)\n\n\tif q.Size() != 3 {\n\t\tt.Error()\n\t}\n\n\te0 := q.DeQueue()\n\n\tif e0 != 0 || q.Size() != 2 {\n\t\tt.Error()\n\t}\n\n\te1 := q.DeQueue()\n\n\tif e1 != 1 {\n\t\tt.Error()\n\t}\n\n\te2 := q.DeQueue()\n\n\tif e2 != 2 || q.Size() != 0 {\n\t\tt.Error()\n\t}\n\n\tee := q.DeQueue()\n\n\tif ee != nil || q.Size() != 0 {\n\t\tt.Error()\n\t}\n}"} {"input": "package logger\n\nimport (\n\t\"log\"\n\t\"log/syslog\"\n)\n\nconst (\n\tLOG_PRIORITY = syslog.LOG_DAEMON | syslog.LOG_INFO\n\tLOG_FLAGS = log.Lshortfile\n)\n\nvar (\n\tLogger *log.Logger\n)\n\n\n\nfunc init() ", "output": "{\n\tvar err error\n\tlog.SetFlags(LOG_FLAGS)\n\tLogger, err = syslog.NewLogger(LOG_PRIORITY, LOG_FLAGS)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}"} {"input": "package db\n\nimport (\n\t\"hg/messages\"\n\t\"fmt\"\n\t\"gopkg.in/mgo.v2\"\n)\n\nconst (\n\tmongoURL = \"127.0.0.1:27017\"\n)\n\n\n\nfunc RecordHistory(historyEntry messages.HistoryMessage){\n\tfmt.Println(\"Start to record history object\")\n\tpersist(\"Insert\",historyEntry)\n}\n\nfunc persist(operation string,historyEntry messages.HistoryMessage) ", "output": "{\n\tfmt.Println(\"Do db operation\")\n\tsession, err := mgo.Dial(mongoURL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer session.Close()\n\n\thistoryCollection := session.DB(\"historys\").C(\"history\")\n\n\tswitch operation {\n\tcase \"Insert\":\n\t\terr = historyCollection.Insert(historyEntry)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Can't insert document: %v\\n\", err)\n\t\t\tpanic(err)\n\t\t}\n\tcase \"Update\":\n\t\tfmt.Println(\"Update method is not supported yet!\")\n\tcase \"Delete\":\n\t\tfmt.Println(\"Delete method is not supported yet!\")\n\tcase \"Put\":\n\t\tfmt.Println(\"Put method is not supported yet!\")\n\t}\n}"} {"input": "package scaleway\n\nimport (\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/scaleway/scaleway-cli/pkg/api\"\n)\n\n\nfunc Bool(val bool) *bool {\n\treturn &val\n}\n\n\n\n\n\n\n\nfunc deleteServerSafe(s *api.ScalewayAPI, serverID string) error {\n\tserver, err := s.GetServer(serverID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif server.State != \"stopped\" {\n\t\tif err := s.PostServerAction(serverID, \"poweroff\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := waitForServerState(s, serverID, \"stopped\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := s.DeleteServer(serverID); err != nil {\n\t\treturn err\n\t}\n\tif rootVolume, ok := server.Volumes[\"0\"]; ok {\n\t\tif err := s.DeleteVolume(rootVolume.Identifier); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc waitForServerState(s *api.ScalewayAPI, serverID string, targetState string) error {\n\tvar server *api.ScalewayServer\n\tvar err error\n\n\tvar currentState string\n\n\tfor {\n\t\tserver, err = s.GetServer(serverID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif currentState != server.State {\n\t\t\tlog.Printf(\"[DEBUG] Server changed state to %q\\n\", server.State)\n\t\t\tcurrentState = server.State\n\t\t}\n\t\tif server.State == targetState {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\treturn nil\n}\n\nfunc String(val string) *string ", "output": "{\n\treturn &val\n}"} {"input": "package l4\n\ntype TCP struct{}\n\n\n\nfunc (t *TCP) String() string ", "output": "{\n\treturn \"\"\n}"} {"input": "package entity\n\nimport (\n\t\"context\"\n\n\t\"github.com/utahta/momoclo-channel/dao\"\n)\n\ntype (\n\tReminderRepository interface {\n\t\tFindAll(context.Context) ([]*Reminder, error)\n\t\tSave(context.Context, *Reminder) error\n\t}\n\n\treminderRepository struct {\n\t\tdao.PersistenceHandler\n\t}\n)\n\n\n\n\n\nfunc (repo *reminderRepository) FindAll(ctx context.Context) ([]*Reminder, error) {\n\tkind := repo.Kind(ctx, &Reminder{})\n\tq := repo.NewQuery(kind).Filter(\"Enabled =\", true)\n\n\tvar dst []*Reminder\n\treturn dst, repo.GetAll(ctx, q, &dst)\n}\n\n\nfunc (repo *reminderRepository) Save(ctx context.Context, item *Reminder) error {\n\treturn repo.Put(ctx, item)\n}\n\nfunc NewReminderRepository(h dao.PersistenceHandler) ReminderRepository ", "output": "{\n\treturn &reminderRepository{h}\n}"} {"input": "package clients\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n\n\t\"github.com/VolantMQ/volantmq/subscriber\"\n)\n\nvar subCount int32 = 0\n\n\n\ntype container struct {\n\tlock sync.Mutex\n\trmLock sync.RWMutex\n\tses *session\n\texpiry atomic.Value\n\tsub *subscriber.Type\n\tremovable bool\n\tremoved bool\n}\n\nfunc (s *container) setRemovable(rm bool) {\n\ts.rmLock.Lock()\n\ts.removable = rm\n\ts.rmLock.Unlock()\n}\n\nfunc (s *container) acquire() {\n\ts.lock.Lock()\n}\n\nfunc (s *container) release() {\n\ts.lock.Unlock()\n}\n\nfunc (s *container) session() *session {\n\tdefer s.rmLock.Unlock()\n\ts.rmLock.Lock()\n\treturn s.ses\n}\n\nfunc (s *container) swap(from *container) *container {\n\ts.ses = from.ses\n\n\ts.ses.idLock = &s.lock\n\n\treturn s\n}\n\n\n\nfunc (s *container) subscriber(cleanStart bool, c subscriber.Config) *subscriber.Type ", "output": "{\n\tif cleanStart && s.sub != nil {\n\t\ts.sub.Offline(true)\n\t\ts.sub = nil\n\t}\n\n\tif s.sub == nil {\n\t\ts.sub = subscriber.New(c)\n\t}\n\n\treturn s.sub\n}"} {"input": "package goji\n\nimport \"net/http\"\n\n\n\ntype router []route\n\ntype route struct {\n\tPattern\n\thttp.Handler\n}\n\n\n\nfunc (rt *router) route(r *http.Request) *http.Request {\n\tfor _, route := range *rt {\n\t\tif r2 := route.Match(r); r2 != nil {\n\t\t\treturn r2.WithContext(&match{\n\t\t\t\tContext: r2.Context(),\n\t\t\t\tp: route.Pattern,\n\t\t\t\th: route.Handler,\n\t\t\t})\n\t\t}\n\t}\n\treturn r.WithContext(&match{Context: r.Context()})\n}\n\nfunc (rt *router) add(p Pattern, h http.Handler) ", "output": "{\n\t*rt = append(*rt, route{p, h})\n}"} {"input": "package pango_mock\n\nimport \"github.com/coyim/gotk3adapter/pangoi\"\n\n\n\nfunc init() ", "output": "{\n\tpangoi.AssertPango(&Mock{})\n\tpangoi.AssertFontDescription(&MockFontDescription{})\n}"} {"input": "package backend\n\nimport (\n\t\"path/filepath\"\n\n\t\"github.com/webx-top/echo/handler/captcha\"\n\t\"github.com/webx-top/echo/middleware/render\"\n\n\t\"github.com/admpub/nging/v4/application/handler\"\n\t\"github.com/admpub/nging/v4/application/library/common\"\n\t\"github.com/admpub/nging/v4/application/library/config\"\n\t\"github.com/admpub/nging/v4/application/middleware\"\n)\n\nfunc Initialize() {\n\thandler.Use(BackendURLFuncMW(), middleware.FuncMap(), middleware.BackendFuncMap(), render.Auto())\n\thandler.Use(middleware.Middlewares...)\n\taddRouter()\n\tDefaultConfigWatcher(true)\n}\n\nvar onConfigChange = []func(file string) error{}\n\nfunc OnConfigChange(fn func(file string) error) {\n\tonConfigChange = append(onConfigChange, fn)\n}\n\nfunc FireConfigChange(file string) error {\n\tfor _, fn := range onConfigChange {\n\t\tif err := fn(file); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn common.ErrIgnoreConfigChange\n}\n\n\n\nfunc addRouter() {\n\topt := captcha.Options{EnableImage: true}\n\topt.Wrapper(handler.IRegister().Echo())\n\thandler.UseToGroup(`*`, middleware.AuthCheck) \n\thandler.Apply()\n}\n\nfunc DefaultConfigWatcher(mustOk bool) ", "output": "{\n\tif config.DefaultCLIConfig.Type != `manager` {\n\t\treturn\n\t}\n\tconf := filepath.Base(config.DefaultCLIConfig.Conf)\n\tconfig.WatchConfig(func(file string) error {\n\t\tname := filepath.Base(file)\n\t\tswitch name {\n\t\tcase conf:\n\t\t\terr := config.ParseConfig()\n\t\t\tif err != nil {\n\t\t\t\tif mustOk && config.IsInstalled() {\n\t\t\t\t\tconfig.MustOK(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn err\n\t\tdefault:\n\t\t\tif !config.IsInstalled() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfilePath := filepath.ToSlash(file)\n\t\t\treturn FireConfigChange(filePath)\n\t\t}\n\t})\n}"} {"input": "package reaperlog\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/rifflock/lfshook\"\n\t\"go.mozilla.org/mozlogrus\"\n)\n\nvar config LogConfig\n\ntype LogConfig struct {\n\tExtras bool\n}\n\nfunc EnableExtras() {\n\tconfig.Extras = true\n}\n\nfunc EnableMozlog() {\n\tmozlogrus.Enable(\"Reaper\")\n}\n\nfunc Extras() bool {\n\treturn config.Extras\n}\n\nfunc SetConfig(c *LogConfig) {\n\tconfig = *c\n}\n\nfunc AddLogFile(filename string) {\n\tlog.AddHook(lfshook.NewHook(lfshook.PathMap{\n\t\tlog.DebugLevel: filename,\n\t\tlog.InfoLevel: filename,\n\t\tlog.WarnLevel: filename,\n\t\tlog.ErrorLevel: filename,\n\t\tlog.FatalLevel: filename,\n\t\tlog.PanicLevel: filename,\n\t}))\n}\n\nfunc Debug(format string, args ...interface{}) {\n\tlog.Debugf(format, args...)\n}\n\nfunc Info(format string, args ...interface{}) {\n\tlog.Infof(format, args...)\n}\n\nfunc Warning(format string, args ...interface{}) {\n\tlog.Warningf(format, args...)\n}\n\n\n\nfunc Panic(format string, args ...interface{}) {\n\tlog.Panicf(format, args...)\n}\n\nfunc Error(format string, args ...interface{}) {\n\tlog.Errorf(format, args...)\n}\n\nfunc Fatal(format string, args ...interface{}) ", "output": "{\n\tlog.Fatalf(format, args...)\n}"} {"input": "package geo\n\nimport (\n\t\"image/jpeg\"\n\t\"image/png\"\n\t\"io\"\n\n\t\"github.com/mmcloughlin/globe\"\n)\n\ntype Sphere struct {\n\t*globe.Globe\n}\n\n\n\nfunc (s *Sphere) EncodePNG(size int, writer io.Writer) error {\n\timage := s.Image(size)\n\treturn png.Encode(writer, image)\n}\n\nfunc (s *Sphere) EncodeJPEG(size int, quality int, writer io.Writer) error {\n\timage := s.Image(size)\n\treturn jpeg.Encode(writer, image, &jpeg.Options{Quality: quality})\n}\n\nfunc NewSphere() *Sphere ", "output": "{\n\ts := &Sphere{globe.New()}\n\treturn s\n}"} {"input": "package cluster\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\n\t\"github.com/docker/docker/api/types\"\n\tv3 \"github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3\"\n\t\"github.com/rancher/rancher/pkg/settings\"\n\trketypes \"github.com/rancher/rke/types\"\n)\n\n\n\nfunc GetPrivateRepo(cluster *v3.Cluster) *rketypes.PrivateRegistry {\n\tif cluster != nil && cluster.Spec.RancherKubernetesEngineConfig != nil && len(cluster.Spec.RancherKubernetesEngineConfig.PrivateRegistries) > 0 {\n\t\tconfig := cluster.Spec.RancherKubernetesEngineConfig\n\t\treturn &config.PrivateRegistries[0]\n\t}\n\tif settings.SystemDefaultRegistry.Get() != \"\" {\n\t\treturn &rketypes.PrivateRegistry{\n\t\t\tURL: settings.SystemDefaultRegistry.Get(),\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenerateClusterPrivateRegistryDockerConfig(cluster *v3.Cluster) (string, error) {\n\tif cluster == nil {\n\t\treturn \"\", nil\n\t}\n\treturn GeneratePrivateRegistryDockerConfig(GetPrivateRepo(cluster))\n}\n\n\nfunc GeneratePrivateRegistryDockerConfig(privateRegistry *rketypes.PrivateRegistry) (string, error) {\n\tif privateRegistry == nil || privateRegistry.User == \"\" || privateRegistry.Password == \"\" {\n\t\treturn \"\", nil\n\t}\n\tauthConfig := types.AuthConfig{\n\t\tUsername: privateRegistry.User,\n\t\tPassword: privateRegistry.Password,\n\t}\n\tencodedJSON, err := json.Marshal(authConfig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.URLEncoding.EncodeToString(encodedJSON), nil\n}\n\nfunc GetPrivateRepoURL(cluster *v3.Cluster) string ", "output": "{\n\tregistry := GetPrivateRepo(cluster)\n\tif registry == nil {\n\t\treturn \"\"\n\t}\n\treturn registry.URL\n}"} {"input": "package stringutil\n\nimport (\n\t\"strings\"\n\t\"unicode\"\n)\n\n\n\n\n\n\nfunc Rstrip(s string) string ", "output": "{\n\treturn strings.TrimRightFunc(s, unicode.IsSpace)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\n\nfunc simpleEvalInt(a, b int, op string) int {\n\tswitch op {\n\tcase \"+\":\n\t\treturn a + b\n\tcase \"-\":\n\t\treturn a - b\n\tcase \"/\":\n\t\treturn a / b\n\tcase \"*\":\n\t\treturn a * b\n\tcase \"^\":\n\t\treturn power(a, b)\n\tdefault:\n\t\treturn 0\n\t}\n}\n\n\n\nfunc evalPostfixInt(postfix []string) (int, error) {\n\tvar stack []int\n\tfor _, val := range postfix {\n\t\tif isOp(val) {\n\t\t\ta := stack[len(stack)-2]\n\t\t\tb := stack[len(stack)-1]\n\t\t\tretVal := simpleEvalInt(a, b, val)\n\t\t\tstack = append(stack[0:len(stack)-2], retVal)\n\t\t} else {\n\t\t\tnum, err := strconv.Atoi(val)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, nil\n\t\t\t}\n\t\t\tstack = append(stack, num)\n\t\t}\n\t}\n\tif len(stack) != 1 {\n\t\terr := fmt.Errorf(\"error calculating postfix\")\n\t\treturn 0, err\n\t}\n\treturn stack[0], nil\n}\n\n\n\n\nfunc power(a, b int) int ", "output": "{\n\tans := 1\n\tfor i := 0; i < b; i++ {\n\t\tans = a * ans\n\t}\n\treturn ans\n}"} {"input": "package main\n\nimport . \"g2d\"\n\nvar screen = Point{480, 360}\nvar size = Point{20, 20}\n\ntype Ball struct {\n x, y int\n dx, dy int\n}\n\nfunc NewBall(pos Point) *Ball {\n return &Ball{pos.X, pos.Y, 5, 5}\n}\n\n\n\nfunc (b *Ball) Position() Point {\n return Point{b.x, b.y}\n}\n\n\nvar b1 = NewBall(Point{40, 80})\nvar b2 = NewBall(Point{80, 40})\n\nfunc mainConsole() {\n for i := 0; i < 25; i++ {\n Println(\"Ball 1 @\", b1.Position())\n Println(\"Ball 2 @\", b2.Position())\n b1.Move()\n b2.Move()\n }\n}\n\nfunc tick() {\n ClearCanvas() \n b1.Move()\n b2.Move()\n DrawImage(\"ball.png\", b1.Position()) \n DrawImage(\"ball.png\", b2.Position()) \n}\n\nfunc main() {\n \n InitCanvas(screen)\n MainLoop(tick)\n}\n\nfunc (b *Ball) Move() ", "output": "{\n if !(0 <= b.x+b.dx && b.x+b.dx <= screen.X-size.X) {\n b.dx = -b.dx\n }\n if !(0 <= b.y+b.dy && b.y+b.dy <= screen.Y-size.Y) {\n b.dy = -b.dy\n }\n b.x += b.dx\n b.y += b.dy\n}"} {"input": "package acquire\n\nimport \"math/rand\"\n\nfunc countTiles(c *PieceCollection) [BoardHeight][BoardWidth]int {\n\tvar tileCount [BoardHeight][BoardWidth]int\n\n\tfor _, p := range c.Pieces {\n\t\ttileCount[p.Row][p.Col]++\n\t}\n\n\treturn tileCount\n}\n\nfunc _genTestGame() (*Game, *PlayerRandom) {\n\tr := rand.New(rand.NewSource(0))\n\tp1 := NewPlayerRandom(r)\n\treturn NewGame(r, []Player{p1}), p1\n}\n\n\n\nfunc genGameParams() (r *rand.Rand, players []Player) ", "output": "{\n\tr = rand.New(rand.NewSource(0))\n\tplayers = []Player{NewPlayerRandom(r)}\n\treturn\n}"} {"input": "package addrmgr\n\nimport (\n\t\"time\"\n\n\t\"github.com/abcsuite/abcd/wire\"\n)\n\nfunc TstKnownAddressIsBad(ka *KnownAddress) bool {\n\treturn ka.isBad()\n}\n\n\n\nfunc TstNewKnownAddress(na *wire.NetAddress, attempts int,\n\tlastattempt, lastsuccess time.Time, tried bool, refs int) *KnownAddress {\n\treturn &KnownAddress{na: na, attempts: attempts, lastattempt: lastattempt,\n\t\tlastsuccess: lastsuccess, tried: tried, refs: refs}\n}\n\nfunc TstKnownAddressChance(ka *KnownAddress) float64 ", "output": "{\n\treturn ka.chance()\n}"} {"input": "package unibyte\n\nimport \"unicode\"\n\n\nfunc IsLower(b byte) bool {\n\treturn b >= 'a' && b <= 'z'\n}\n\n\n\n\n\nfunc IsLetter(b byte) bool {\n\treturn IsLower(b) || IsUpper(b)\n}\n\n\nfunc IsSpaceQuote(b byte) bool {\n\treturn IsSpace(b) || b == '\"' || b == '\\''\n}\n\n\nfunc IsSpace(b byte) bool {\n\treturn unicode.IsSpace(rune(b))\n}\n\n\nfunc ToLower(b byte) byte {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn b\n}\n\n\nfunc ToUpper(b byte) byte {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn b\n}\n\n\nfunc ToLowerString(b byte) string {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn string(b)\n}\n\n\nfunc ToUpperString(b byte) string {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn string(b)\n}\n\nfunc IsUpper(b byte) bool ", "output": "{\n\treturn b >= 'A' && b <= 'Z'\n}"} {"input": "package wire_test\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader ", "output": "{\n\tb := make([]byte, max, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}"} {"input": "package collector\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/google/cadvisor/info/v1\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype fakeCollector struct {\n\tnextCollectionTime time.Time\n\terr error\n\tcollectedFrom int\n}\n\n\n\nfunc (fc *fakeCollector) Name() string {\n\treturn \"fake-collector\"\n}\n\nfunc (fc *fakeCollector) GetSpec() []v1.MetricSpec {\n\treturn []v1.MetricSpec{}\n}\n\nfunc TestCollect(t *testing.T) {\n\tcm := &GenericCollectorManager{}\n\n\tfirstTime := time.Now().Add(-time.Hour)\n\tsecondTime := time.Now().Add(time.Hour)\n\tf1 := &fakeCollector{\n\t\tnextCollectionTime: firstTime,\n\t}\n\tf2 := &fakeCollector{\n\t\tnextCollectionTime: secondTime,\n\t}\n\n\tassert := assert.New(t)\n\tassert.NoError(cm.RegisterCollector(f1))\n\tassert.NoError(cm.RegisterCollector(f2))\n\n\tnextTime, _, err := cm.Collect()\n\tassert.Equal(firstTime, nextTime)\n\tassert.NoError(err)\n\tassert.Equal(1, f1.collectedFrom)\n\tassert.Equal(1, f2.collectedFrom)\n\n\tf1.nextCollectionTime = time.Now().Add(2 * time.Hour)\n\n\tnextTime, _, err = cm.Collect()\n\tassert.Equal(secondTime, nextTime)\n\tassert.NoError(err)\n\tassert.Equal(2, f1.collectedFrom)\n\tassert.Equal(1, f2.collectedFrom)\n}\n\nfunc (fc *fakeCollector) Collect(metric map[string]v1.MetricVal) (time.Time, map[string]v1.MetricVal, error) ", "output": "{\n\tfc.collectedFrom++\n\treturn fc.nextCollectionTime, metric, fc.err\n}"} {"input": "package auth\n\nimport (\n\t\"sync\"\n\n\t\"github.com/google/martian/session\"\n)\n\nconst key = \"auth.Context\"\n\n\ntype Context struct {\n\tmu sync.RWMutex\n\tid string\n\terr error\n}\n\n\nfunc FromContext(ctx *session.Context) *Context {\n\tif v, ok := ctx.GetSession().Get(key); ok {\n\t\treturn v.(*Context)\n\t}\n\n\tactx := &Context{}\n\tctx.GetSession().Set(key, actx)\n\n\treturn actx\n}\n\n\n\n\n\nfunc (ctx *Context) SetID(id string) {\n\tctx.mu.Lock()\n\tctx.mu.Unlock()\n\n\tctx.err = nil\n\n\tif id == \"\" {\n\t\treturn\n\t}\n\n\tctx.id = id\n}\n\n\nfunc (ctx *Context) SetError(err error) {\n\tctx.mu.Lock()\n\tdefer ctx.mu.Unlock()\n\n\tctx.id = \"\"\n\tctx.err = err\n}\n\n\nfunc (ctx *Context) Error() error {\n\tctx.mu.RLock()\n\tdefer ctx.mu.RUnlock()\n\n\treturn ctx.err\n}\n\nfunc (ctx *Context) ID() string ", "output": "{\n\tctx.mu.RLock()\n\tctx.mu.RUnlock()\n\n\treturn ctx.id\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n)\n\nfunc main() {\n \n methods()\n interfaces()\n typeAssertions()\n}\n\n\n\n\nfunc interfaces() {\n fmt.Println(\"Interfaces\")\n fmt.Println(\"==========\")\n\n person := Person{\n Phrase: \"Hello\",\n Thought: \"Cogito ergo sum\",\n }\n \n \n dog := Dog{}\n\n var sentient Sentient\n \n sentient = person\n fmt.Printf(\"sentient says '%s' and thinks '%s'\\n\", sentient.Speak(), sentient.Reason())\n \n \n\n var speaker Speaker\n \n speaker = sentient\n fmt.Printf(\"sentient speaker says '%s'\\n\", speaker.Speak())\n speaker = dog\n fmt.Printf(\"non-sentient speaker says '%s'\\n\", speaker.Speak())\n speaker.Speak()\n\n fmt.Println()\n}\n\nfunc typeAssertions() {\n fmt.Println(\"Type assertions\")\n fmt.Println(\"===============\")\n\n var i interface{} = \"All types match the empty interface\"\n\n \n f, ok := i.(float64)\n fmt.Printf(\"Type assertion results for float64 -> f = %f, ok = %t\\n\", f, ok)\n s, ok := i.(string)\n fmt.Printf(\"Type assertion results for string -> s = %s, ok = %t\\n\", s, ok)\n \n \n\n \n switch i.(type) {\n case int:\n fmt.Println(\"It's an int\")\n case string:\n fmt.Println(\"It's a string\")\n default:\n fmt.Println(\"Hell if I know\")\n }\n fmt.Println()\n}\n\nfunc methods() ", "output": "{\n fmt.Println(\"Methods\")\n fmt.Println(\"=======\")\n\n swedishChef := Person{\n Phrase: \"Bork bork bork!\",\n }\n\n fmt.Printf(\"swedishChef says '%s'\\n\", swedishChef.Speak())\n\n myFloat := MyFloat(16.0)\n myFloat.Square()\n\n fmt.Printf(\"myFloat -> value = %f, squared = %f\\n\", myFloat, myFloat.Square())\n\n fmt.Println()\n}"} {"input": "package influxdb\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/url\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/fractalplatform/fractal/metrics\"\n\tclient \"github.com/influxdata/influxdb1-client\"\n)\n\nconst (\n\tdburl = \"http://localhost:8086\"\n\ttestdb = \"testmetrics\"\n\tusername = \"\"\n\tpassword = \"\"\n\tnamespace = \"test/\"\n\tprefix = \"test\"\n\ttable = namespace + prefix + \".timer\"\n)\n\n\n\nfunc TestQuery(t *testing.T) {\n\thost, err := url.Parse(dburl)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcon, err := client.NewClient(client.Config{URL: *host})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tq := client.Query{\n\t\tCommand: fmt.Sprintf(`select * from \"%s\"`, table),\n\t\tDatabase: testdb,\n\t}\n\tif response, err := con.Query(q); err == nil && response.Error() == nil {\n\t\tlog.Println(response.Results)\n\t}\n}\n\nfunc TestWrite(t *testing.T) ", "output": "{\n\tgo InfluxDBWithTags(metrics.DefaultRegistry, 1*time.Second, dburl, testdb, \"\", \"\", namespace, make(map[string]string))\n\ttm := metrics.NewRegisteredTimer(prefix, nil)\n\tfor i := 0; i < 5; i++ {\n\t\ttm.Update(100 * time.Second)\n\t}\n\ttime.Sleep(time.Duration(10) * time.Second)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\trice \"github.com/GeertJohan/go.rice\"\n\n\t\"git.timschuster.info/rls.moe/catgi/logger\"\n)\n\ntype handlerServeResources struct {\n\trice *rice.Box\n}\n\nfunc newHandlerServeResources() http.Handler {\n\treturn &handlerServeResources{\n\t\trice: (&rice.Config{\n\t\t\tLocateOrder: []rice.LocateMethod{\n\t\t\t\trice.LocateWorkingDirectory,\n\t\t\t\trice.LocateFS,\n\t\t\t\trice.LocateEmbedded,\n\t\t\t},\n\t\t}).MustFindBox(\"./resources\"),\n\t}\n}\n\n\nfunc (h *handlerServeResources) ServeHTTP(rw http.ResponseWriter, r *http.Request) ", "output": "{\n\tlog := logger.LogFromCtx(\"serverIndex\", r.Context())\n\tlog.Info(\"Loading file from disk: \", r.RequestURI)\n\tdat, err := h.rice.Bytes(r.URL.String())\n\tif err != nil {\n\t\tlog.Error(\"Could not load file from disk: \", err)\n\t\trw.WriteHeader(404)\n\t\tfmt.Fprint(rw, \"index.html not found\")\n\t\treturn\n\t}\n\trw.WriteHeader(200)\n\trw.Header().Add(\"Content-Type\", \"application/html\")\n\trw.Write(dat)\n}"} {"input": "package logutils\n\nimport (\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype MockLog struct {\n\tmock.Mock\n}\n\nfunc NewMockLog() *MockLog {\n\treturn &MockLog{}\n}\n\nfunc (m *MockLog) Fatalf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Panicf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Errorf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Warnf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Infof(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Child(name string) Log {\n\tm.Called(name)\n\treturn m\n}\n\n\n\nfunc (m *MockLog) SetLevel(level LogLevel) ", "output": "{\n\tm.Called(level)\n}"} {"input": "package lock\n\nimport (\n\t\"testing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\ntype LockSuite struct{}\n\nvar _ = Suite(&LockSuite{})\n\n\n\nfunc (s *LockSuite) TestDebugLock(c *C) {\n\tvar lock1 RWMutexDebug\n\tlock1.Lock()\n\tlock1.Unlock()\n\n\tlock1.RLock()\n\tlock1.RLock()\n\tlock1.RUnlock()\n\tlock1.RUnlock()\n\n\tvar lock2 MutexDebug\n\tlock2.Lock()\n\tlock2.Unlock()\n}\n\nfunc (s *LockSuite) TestLock(c *C) ", "output": "{\n\tvar lock1 RWMutex\n\tlock1.Lock()\n\tlock1.Unlock()\n\n\tlock1.RLock()\n\tlock1.RLock()\n\tlock1.RUnlock()\n\tlock1.RUnlock()\n\n\tvar lock2 Mutex\n\tlock2.Lock()\n\tlock2.Unlock()\n}"} {"input": "package models\n\nimport \"testing\"\n\nfunc TestGetEntityName(t *testing.T) {\n\t_, err := GetEntityName(2)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}\nfunc TestGetTypeName(t *testing.T) {\n\t_, err := GetTypeName(2)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}\n\n\n\nfunc TestGetCelestialName(t *testing.T) {\n\t_, err := GetCelestialName(30000001)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}\n\nfunc TestGetSystemName(t *testing.T) ", "output": "{\n\t_, err := GetSystemName(30000001)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}"} {"input": "package codegen\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"goa.design/goa/v3/codegen/service\"\n\t\"goa.design/goa/v3/expr\"\n)\n\n\n\n\n\n\n\nfunc makeGolden(t *testing.T, p string) *os.File {\n\tt.Helper()\n\tif os.Getenv(\"GOLDEN\") == \"\" {\n\t\treturn nil\n\t}\n\tf, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY, 0600)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn f\n}\n\nfunc RunHTTPDSL(t *testing.T, dsl func()) *expr.RootExpr ", "output": "{\n\tservice.Services = make(service.ServicesData)\n\tHTTPServices = make(ServicesData)\n\treturn expr.RunDSL(t, dsl)\n}"} {"input": "package rorm\n\ntype rorm struct {\n\tredisQuerier *RedisQuerier\n}\n\nfunc NewROrm() ROrmer {\n\treturn new(rorm).Using(\"default\")\n}\n\nfunc (r *rorm) QueryHash(key string) HashQuerySeter {\n\treturn &hashQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QueryKeys(key string) KeysQuerySeter {\n\treturn &keysQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QueryString(key string) StringQuerySeter {\n\treturn &stringQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QueryZSet(key string) ZSetQuerySeter {\n\treturn &zsetQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\n\n\nfunc (r rorm) Using(alias string) ROrmer {\n\tclient, ok := redisRegistry[alias]\n\tif !ok {\n\t\tpanic(\"using reids '\" + alias + \"' not exist.\")\n\t}\n\tr.redisQuerier = &RedisQuerier{\n\t\tClient: client,\n\t}\n\treturn &r\n}\n\nfunc (r *rorm) Querier() Querier {\n\treturn r.redisQuerier\n}\n\nfunc (r *rorm) QuerySet(key string) SetQuerySeter ", "output": "{\n\treturn &setQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}"} {"input": "package data_table\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/julienschmidt/httprouter\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\n\nfunc TreePostFormValues(values url.Values) map[string]interface{} {\n\tres := make(map[string]interface{})\n\tvar currValue map[string]interface{}\n\tfor rawKey, value := range values {\n\t\tif vs := value; len(vs) > 0 {\n\t\t\tcurrValue = res\n\t\t\tkeyPath := ParseKey(rawKey)\n\t\t\tlastIndex := len(keyPath) - 1\n\t\t\tfor index, key := range keyPath {\n\t\t\t\tif index == lastIndex {\n\t\t\t\t\tcurrValue[key] = vs[0]\n\t\t\t\t} else {\n\t\t\t\t\tif _, ok := currValue[key]; !ok {\n\t\t\t\t\t\tcurrValue[key] = make(map[string]interface{})\n\t\t\t\t\t}\n\t\t\t\t\tcurrValue = currValue[key].(map[string]interface{})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\treturn res\n}\n\nfunc ParseKey(key string) []string {\n\tres := make([]string, 0)\n\tvar currKey bytes.Buffer\n\n\tfor _, char := range key {\n\t\tif char == '[' || char == ']' {\n\t\t\tif currKey.Len() > 0 {\n\t\t\t\tres = append(res, currKey.String())\n\t\t\t\tcurrKey.Reset()\n\t\t\t}\n\t\t} else {\n\t\t\tcurrKey.WriteRune(char)\n\t\t}\n\t}\n\n\tif currKey.Len() > 0 {\n\t\tres = append(res, currKey.String())\n\t}\n\n\treturn res\n}\n\nfunc DataStoreHandler(tableStore TableStore) func(http.ResponseWriter, *http.Request, httprouter.Params) ", "output": "{\n\treturn func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\t\trequest := newSearchRequest(r, ps)\n\t\tresult := tableStore.QueryData(request)\n\t\tjsonBytes, _ := json.Marshal(result)\n\t\tfmt.Fprint(w, string(jsonBytes))\n\t}\n}"} {"input": "package sharpen\n\nimport (\n\t\"hawx.me/code/img/blur\"\n\t\"hawx.me/code/img/utils\"\n\n\t\"image\"\n\t\"image/color\"\n\t\"math\"\n)\n\n\n\n\n\n\n\n\n\nfunc UnsharpMask(in image.Image, radius int, sigma, amount, threshold float64) image.Image {\n\tblurred := blur.Gaussian(in, radius, sigma, blur.IGNORE)\n\tbounds := in.Bounds()\n\tout := image.NewRGBA(bounds)\n\n\tdiff := func(a, b float64) float64 {\n\t\tif a > b {\n\t\t\treturn a - b\n\t\t}\n\t\treturn b - a\n\t}\n\n\tfor y := bounds.Min.Y; y < bounds.Max.Y; y++ {\n\t\tfor x := bounds.Min.X; x < bounds.Max.X; x++ {\n\t\t\tar, ag, ab, aa := utils.RatioRGBA(in.At(x, y))\n\t\t\tbr, bg, bb, _ := utils.RatioRGBA(blurred.At(x, y))\n\n\t\t\tif diff(ar, br) >= threshold {\n\t\t\t\tar = amount*(ar-br) + ar\n\t\t\t}\n\n\t\t\tif diff(ag, bg) >= threshold {\n\t\t\t\tag = amount*(ag-bg) + ag\n\t\t\t}\n\n\t\t\tif diff(ab, bb) >= threshold {\n\t\t\t\tab = amount*(ab-bb) + ab\n\t\t\t}\n\n\t\t\tout.Set(x, y, color.NRGBA{\n\t\t\t\tuint8(utils.Truncatef(ar * 255)),\n\t\t\t\tuint8(utils.Truncatef(ag * 255)),\n\t\t\t\tuint8(utils.Truncatef(ab * 255)),\n\t\t\t\tuint8(aa * 255),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn out\n}\n\nfunc Sharpen(in image.Image, radius int, sigma float64) image.Image ", "output": "{\n\n\tnormalize := 0.0\n\tf := func(u, v int) float64 {\n\t\tusq := float64(u * u)\n\t\tvsq := float64(v * v)\n\t\tval := -math.Exp(-(usq+vsq)/(2.0*sigma*sigma)) / (2.0 * math.Pi * sigma * sigma)\n\t\tnormalize += val\n\t\treturn val\n\t}\n\n\tk := blur.NewKernel(radius*2+1, radius*2+1, f)\n\tk[radius+1][radius+1] = -2.0 * normalize\n\n\treturn blur.Convolve(in, k, blur.CLAMP)\n}"} {"input": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"time\"\n)\n\ntype TLSConnection struct {\n\thost string\n\tcertPool *x509.CertPool\n\tconn *tls.Conn\n}\n\n\n\nfunc (c *TLSConnection) Connect() (err error) {\n\tc.conn, err = tls.Dial(\"tcp\", c.host, &tls.Config{\n\t\tRootCAs: c.certPool,\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\tc.conn.SetWriteDeadline(time.Time{})\n\treturn\n}\n\nfunc (c *TLSConnection) WriteString(s string) (n int, err error) {\n\treturn io.WriteString(c.conn, s)\n}\n\nfunc (c *TLSConnection) Write(p []byte) (n int, err error) {\n\treturn c.conn.Write(p)\n}\n\nfunc (c *TLSConnection) Close() error {\n\treturn c.conn.Close()\n}\n\nfunc (c *TLSConnection) getCerts() {\n\tc.certPool = x509.NewCertPool()\n\tcert, err := ioutil.ReadFile(certsPemFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif !c.certPool.AppendCertsFromPEM(cert) {\n\t\tlog.Fatal(\"Failed parsing root certificate\")\n\t}\n}\n\nfunc NewTLSConnection(host string) (*TLSConnection, error) ", "output": "{\n\tc := &TLSConnection{}\n\tc.host = host\n\tc.getCerts()\n\terr := c.Connect()\n\treturn c, err\n}"} {"input": "package pml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/pml\"\n)\n\nfunc TestEG_TopLevelSlideConstructor(t *testing.T) {\n\tv := pml.NewEG_TopLevelSlide()\n\tif v == nil {\n\t\tt.Errorf(\"pml.NewEG_TopLevelSlide must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed pml.EG_TopLevelSlide should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestEG_TopLevelSlideMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := pml.NewEG_TopLevelSlide()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := pml.NewEG_TopLevelSlide()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package testing\n\nimport (\n\t\"github.com/markdaws/gohome/pkg/cmd\"\n\t\"github.com/markdaws/gohome/pkg/gohome\"\n)\n\ntype extension struct {\n\tgohome.NullExtension\n}\n\nfunc (e *extension) Name() string {\n\treturn \"testing\"\n}\n\n\n\nfunc (e *extension) NetworkForDevice(sys *gohome.System, d *gohome.Device) gohome.Network {\n\treturn nil\n}\n\nfunc (e *extension) EventsForDevice(sys *gohome.System, d *gohome.Device) *gohome.ExtEvents {\n\tswitch d.ModelNumber {\n\tcase \"testing.hardware\":\n\t\tevts := &gohome.ExtEvents{}\n\t\tevts.Producer = &producer{\n\t\t\tDevice: d,\n\t\t\tSystem: sys,\n\t\t}\n\t\tevts.Consumer = &consumer{\n\t\t\tDevice: d,\n\t\t\tSystem: sys,\n\t\t}\n\t\treturn evts\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (e *extension) Discovery(sys *gohome.System) gohome.Discovery {\n\treturn &discovery{}\n}\n\nfunc NewExtension() *extension {\n\treturn &extension{}\n}\n\nfunc (e *extension) BuilderForDevice(sys *gohome.System, d *gohome.Device) cmd.Builder ", "output": "{\n\tswitch d.ModelNumber {\n\tcase \"testing.hardware\":\n\t\treturn &cmdBuilder{ModelNumber: d.ModelNumber, Device: d}\n\tdefault:\n\t\treturn nil\n\t}\n}"} {"input": "package hawkular\n\nimport (\n\t\"net/url\"\n\t\"sync\"\n\n\t\"github.com/adfin/statster/metrics/core\"\n\thawkular \"github.com/hawkular/hawkular-client-go/metrics\"\n)\n\ntype Filter func(ms *core.MetricSet, metricName string) bool\ntype FilterType int\n\nconst (\n\tLabel FilterType = iota\n\tName\n\tUnknown\n)\n\n\n\ntype hawkularSink struct {\n\tclient *hawkular.Client\n\tmodels map[string]*hawkular.MetricDefinition \n\tregLock sync.RWMutex\n\treg map[string]*hawkular.MetricDefinition \n\n\turi *url.URL\n\n\tlabelTenant string\n\tlabelNodeId string\n\tlabelTagPrefix string\n\tmodifiers []hawkular.Modifier\n\tfilters []Filter\n\n\tdisablePreCaching bool\n\tbatchSize int\n}\n\nfunc heapsterTypeToHawkularType(t core.MetricType) hawkular.MetricType {\n\tswitch t {\n\tcase core.MetricCumulative:\n\t\treturn hawkular.Counter\n\tcase core.MetricGauge:\n\t\treturn hawkular.Gauge\n\tdefault:\n\t\treturn hawkular.Gauge\n\t}\n}\n\nfunc (f FilterType) From(s string) FilterType ", "output": "{\n\tswitch s {\n\tcase \"label\":\n\t\treturn Label\n\tcase \"name\":\n\t\treturn Name\n\tdefault:\n\t\treturn Unknown\n\t}\n}"} {"input": "package distsql\n\nimport (\n\t\"errors\"\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n\n\t. \"github.com/pingcap/check\"\n\t\"github.com/pingcap/tidb/model\"\n\t\"github.com/pingcap/tidb/mysql\"\n\t\"github.com/pingcap/tidb/util/testleak\"\n\t\"github.com/pingcap/tidb/util/types\"\n\t\"github.com/pingcap/tipb/go-tipb\"\n\tgoctx \"golang.org/x/net/context\"\n)\n\nfunc TestT(t *testing.T) {\n\tCustomVerboseFlag = true\n\tTestingT(t)\n}\n\nvar _ = Suite(&testTableCodecSuite{})\n\ntype testTableCodecSuite struct{}\n\n\nfunc (s *testTableCodecSuite) TestColumnToProto(c *C) {\n\tdefer testleak.AfterTest(c)()\n\ttp := types.NewFieldType(mysql.TypeLong)\n\ttp.Flag = 10\n\tcol := &model.ColumnInfo{\n\t\tFieldType: *tp,\n\t}\n\tpc := columnToProto(col)\n\tc.Assert(pc.GetFlag(), Equals, int32(10))\n}\n\n\n\n\ntype mockResponse struct {\n\tcount int\n}\n\nfunc (resp *mockResponse) Next() ([]byte, error) {\n\tresp.count++\n\tif resp.count == 100 {\n\t\treturn nil, errors.New(\"error happend\")\n\t}\n\treturn mockSubresult(), nil\n}\n\nfunc (resp *mockResponse) Close() error {\n\treturn nil\n}\n\nfunc mockSubresult() []byte {\n\tresp := new(tipb.SelectResponse)\n\tb, err := resp.Marshal()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}\n\nfunc (s *testTableCodecSuite) TestGoroutineLeak(c *C) ", "output": "{\n\tvar sr SelectResult\n\tcountBefore := runtime.NumGoroutine()\n\n\tsr = &selectResult{\n\t\tresp: &mockResponse{},\n\t\tresults: make(chan resultWithErr, 5),\n\t\tclosed: make(chan struct{}),\n\t}\n\tgo sr.Fetch(goctx.TODO())\n\tfor {\n\t\t_, err := sr.Next()\n\t\tif err != nil {\n\t\t\tsr.Close()\n\t\t\tbreak\n\t\t}\n\t}\n\n\ttick := 10 * time.Millisecond\n\ttotalSleep := time.Duration(0)\n\tfor totalSleep < 3*time.Second {\n\t\ttime.Sleep(tick)\n\t\ttotalSleep += tick\n\t\tcountAfter := runtime.NumGoroutine()\n\n\t\tif countAfter-countBefore < 5 {\n\t\t\treturn\n\t\t}\n\t}\n\n\tc.Error(\"distsql goroutine leak!\")\n}"} {"input": "package http\n\nimport (\n\t\"strconv\"\n\n\t\"go-common/app/service/main/archive/api\"\n\t\"go-common/library/ecode\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\nfunc pageList(c *bm.Context) {\n\tvar (\n\t\taid int64\n\t\terr error\n\t\tpages []*api.Page\n\t)\n\taidStr := c.Request.Form.Get(\"aid\")\n\tif aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil || aid <= 0 {\n\t\tc.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\tif pages, err = playSvr.PageList(c, aid); err != nil {\n\t\tc.JSON(nil, err)\n\t\treturn\n\t}\n\tif len(pages) == 0 {\n\t\tc.JSON(nil, ecode.NothingFound)\n\t\treturn\n\t}\n\tc.JSON(pages, nil)\n}\n\n\n\nfunc playURLToken(c *bm.Context) {\n\tvar (\n\t\taid, cid, mid int64\n\t\terr error\n\t)\n\tparams := c.Request.Form\n\taidStr := params.Get(\"aid\")\n\tif aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil {\n\t\tc.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\tcid, _ = strconv.ParseInt(params.Get(\"cid\"), 10, 64)\n\tmidStr, _ := c.Get(\"mid\")\n\tmid = midStr.(int64)\n\tc.JSON(playSvr.PlayURLToken(c, mid, aid, cid))\n}\n\nfunc videoShot(c *bm.Context) ", "output": "{\n\tv := new(struct {\n\t\tAid int64 `form:\"aid\" validate:\"min=1\"`\n\t\tCid int64 `form:\"cid\"`\n\t\tIndex bool `form:\"index\"`\n\t})\n\tif err := c.Bind(v); err != nil {\n\t\treturn\n\t}\n\tc.JSON(playSvr.VideoShot(c, v.Aid, v.Cid, v.Index))\n}"} {"input": "package internal\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"gopkg.in/reform.v1\"\n)\n\n\ntype Logger struct {\n\tprintf reform.Printf\n\tdebug bool\n}\n\n\nfunc NewLogger(prefix string, debug bool) *Logger {\n\tvar flags int\n\tif debug {\n\t\tflags = log.Ldate | log.Lmicroseconds | log.Lshortfile\n\t}\n\n\tl := log.New(os.Stderr, prefix, flags)\n\treturn &Logger{\n\t\tprintf: func(format string, args ...interface{}) {\n\t\t\tl.Output(3, fmt.Sprintf(format, args...))\n\t\t},\n\t\tdebug: debug,\n\t}\n}\n\n\nfunc (l *Logger) Debugf(format string, args ...interface{}) {\n\tif l.debug {\n\t\tl.printf(format, args...)\n\t}\n}\n\n\n\nfunc (l *Logger) Printf(format string, args ...interface{}) {\n\tl.printf(format, args...)\n}\n\n\n\n\nfunc (l *Logger) Fatalf(format string, args ...interface{}) ", "output": "{\n\tl.printf(format, args...)\n\tif l.debug {\n\t\tpanic(fmt.Sprintf(format, args...))\n\t}\n\tos.Exit(1)\n}"} {"input": "package timekeeper\n\nimport \"time\"\n\n\n\n\n\ntype TimeKeeper interface {\n\tAfter(d time.Duration) <-chan time.Time\n\tSleep(d time.Duration)\n\tNow() time.Time\n}\n\n\ntype realTime struct{}\n\nvar rt realTime\n\n\nfunc (t *realTime) After(d time.Duration) <-chan time.Time {\n\treturn time.After(d)\n}\n\n\nfunc (t *realTime) Sleep(d time.Duration) {\n\ttime.Sleep(d)\n}\n\n\nfunc RealTime() TimeKeeper {\n\treturn &rt\n}\n\n\n\n\nfunc (t *realTime) Now() time.Time ", "output": "{\n\treturn time.Now()\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/protobuf/encoding/prototext\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t_ \"google.golang.org/genproto/googleapis/rpc/errdetails\" \n)\n\n\ntype StatusError struct {\n\tst *status.Status\n\tdetails string\n}\n\n\n\n\nfunc (e *StatusError) Error() string {\n\tmsg := fmt.Sprintf(\"rpc error: code = %s desc = %s\", e.st.Code(), e.st.Message())\n\tif e.details != \"\" {\n\t\tmsg += \" details = \" + e.details\n\t}\n\treturn msg\n}\n\n\nfunc (e *StatusError) GRPCStatus() *status.Status {\n\treturn e.st\n}\n\n\n\nfunc (e *StatusError) Is(target error) bool {\n\tif tse, ok := target.(*StatusError); ok {\n\t\treturn proto.Equal(e.st.Proto(), tse.st.Proto())\n\t}\n\tif tst, ok := status.FromError(target); ok {\n\t\treturn proto.Equal(e.st.Proto(), tst.Proto())\n\t}\n\treturn false\n}\n\nfunc StatusDetailedError(st *status.Status) *StatusError ", "output": "{\n\tvar details []string\n\tfor _, d := range st.Details() {\n\t\ts := fmt.Sprintf(\"%+v\", d)\n\t\tif pb, ok := d.(proto.Message); ok {\n\t\t\ts = prototext.Format(pb)\n\t\t}\n\t\tdetails = append(details, s)\n\t}\n\treturn &StatusError{st, strings.Join(details, \"; \")}\n}"} {"input": "package cache\n\nimport (\n\t\"context\"\n\t\"io\"\n\n\t\"github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph\"\n\t\"github.com/GoogleContainerTools/skaffold/pkg/skaffold/platform\"\n\tlatestV1 \"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1\"\n\t\"github.com/GoogleContainerTools/skaffold/pkg/skaffold/tag\"\n)\n\ntype BuildAndTestFn func(context.Context, io.Writer, tag.ImageTags, []*latestV1.Artifact, platform.Resolver) ([]graph.Artifact, error)\n\ntype Cache interface {\n\tBuild(context.Context, io.Writer, tag.ImageTags, []*latestV1.Artifact, platform.Resolver, BuildAndTestFn) ([]graph.Artifact, error)\n}\n\ntype noCache struct{}\n\n\n\nfunc (n *noCache) Build(ctx context.Context, out io.Writer, tags tag.ImageTags, artifacts []*latestV1.Artifact, platforms platform.Resolver, buildAndTest BuildAndTestFn) ([]graph.Artifact, error) ", "output": "{\n\treturn buildAndTest(ctx, out, tags, artifacts, platforms)\n}"} {"input": "package http\n\nimport (\n\t\"net/http\"\n\t\"reflect\"\n)\n\n\ntype JSONErrorBuilder interface {\n\tBuild() JSONError\n\n\tCustomError(code int, errorType, msg string) JSONErrorBuilder\n\n\tFromError(e error) JSONErrorBuilder\n\n\tMessage(string) JSONErrorBuilder\n\n\tStatus(int) JSONErrorBuilder\n\n\tURL(string) JSONErrorBuilder\n}\n\ntype jsonErrorBuilder struct {\n\tinstance JSONError\n}\n\n\n\nfunc NewJSONError() JSONErrorBuilder {\n\treturn &jsonErrorBuilder{JSONError{\n\t\tStatus: http.StatusInternalServerError,\n\t}}\n}\n\nfunc (b *jsonErrorBuilder) Build() JSONError {\n\treturn b.instance\n}\n\nfunc (b *jsonErrorBuilder) CustomError(\n\tcode int,\n\terrorType,\n\tmsg string,\n) JSONErrorBuilder {\n\tb.instance.Code = code\n\tb.instance.Type = errorType\n\tb.instance.Message = msg\n\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) FromError(e error) JSONErrorBuilder {\n\terrType := reflect.TypeOf(e)\n\tvar typeName string\n\tif errType.Kind() == reflect.Ptr {\n\t\ttypeName = errType.Elem().Name()\n\t} else {\n\t\ttypeName = errType.Name()\n\t}\n\n\tb.instance.Type = typeName\n\tb.instance.Message = e.Error()\n\treturn b\n}\n\n\n\nfunc (b *jsonErrorBuilder) Status(status int) JSONErrorBuilder {\n\tb.instance.Status = status\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) URL(url string) JSONErrorBuilder {\n\tb.instance.MoreInfo = url\n\treturn b\n}\n\nvar _ JSONErrorBuilder = (*jsonErrorBuilder)(nil)\n\nfunc (b *jsonErrorBuilder) Message(msg string) JSONErrorBuilder ", "output": "{\n\tb.instance.Message = msg\n\treturn b\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\n\n\ntype RdmaProtocol string\n\nconst (\n\n\tRdmaProtocolRoce RdmaProtocol = \"roce\"\n)\n\n\nvar rdmaProtocolEnum []interface{}\n\nfunc init() {\n\tvar res []RdmaProtocol\n\tif err := json.Unmarshal([]byte(`[\"roce\"]`), &res); err != nil {\n\t\tpanic(err)\n\t}\n\tfor _, v := range res {\n\t\trdmaProtocolEnum = append(rdmaProtocolEnum, v)\n\t}\n}\n\nfunc (m RdmaProtocol) validateRdmaProtocolEnum(path, location string, value RdmaProtocol) error {\n\tif err := validate.EnumCase(path, location, value, rdmaProtocolEnum, true); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\nfunc (m RdmaProtocol) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateRdmaProtocolEnum(\"\", \"body\", m); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\n\nfunc (m RdmaProtocol) ContextValidate(ctx context.Context, formats strfmt.Registry) error ", "output": "{\n\treturn nil\n}"} {"input": "package db\n\nimport (\n \"time\"\n\n \"github.com/jinzhu/gorm\"\n _\"github.com/mattn/go-sqlite3\"\n\n)\n\nvar (\n DB gorm.DB\n)\n\ntype User struct {\n Id\tint `json:\"id\"`\n Username string `json:\"username\"; unique`\n Password string `json:\"password\"`\n Created time.Time `json:\"created_at\"`\n}\n\ntype Device struct {\n Id\tint `json:\"id\"`\n Wifimode string `json:\"wifimode\"`\n Wifissid string `json:\"wifissid\"`\n Wifipwd string `json:\"wifipwd\"`\n Wifiip string `json:\"wifiip\"`\n Wifinetmask string `json:\"wifinetmask\"`\n Wifigateway\tstring\t`json:\"gateway\"`\n Device string `json:\"device\"`\n Land\t string `json:\"land\"`\n Serial string `json:\"serial\"`\n Mac string `json:\"mac\"`\n Ip string `json:\"ip\"`\n Landhq string `json:\"landhq\"`\n Swstate string `json:\"swstate\"`\n Created time.Time\t`json:\"created_at\"`\n}\n\n\n\nfunc Init(dbname *string) error ", "output": "{\n var err error\n\n\n\n\n DB, err = gorm.Open(\"sqlite3\", *dbname)\n if err != nil {\n return err\n }\n\n DB.AutoMigrate(&User{}, &Device{})\n\n return nil\n}"} {"input": "package com\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc TestIsFile(t *testing.T) {\n\tif !IsFile(\"file.go\") {\n\t\tt.Errorf(\"IsExist:\\n Expect => %v\\n Got => %v\\n\", true, false)\n\t}\n\n\tif IsFile(\"testdata\") {\n\t\tt.Errorf(\"IsExist:\\n Expect => %v\\n Got => %v\\n\", false, true)\n\t}\n\n\tif IsFile(\"files.go\") {\n\t\tt.Errorf(\"IsExist:\\n Expect => %v\\n Got => %v\\n\", false, true)\n\t}\n}\n\nfunc TestIsExist(t *testing.T) {\n\tConvey(\"Check if file or directory exists\", t, func() {\n\t\tConvey(\"Pass a file name that exists\", func() {\n\t\t\tSo(IsExist(\"file.go\"), ShouldEqual, true)\n\t\t})\n\t\tConvey(\"Pass a directory name that exists\", func() {\n\t\t\tSo(IsExist(\"testdata\"), ShouldEqual, true)\n\t\t})\n\t\tConvey(\"Pass a directory name that does not exist\", func() {\n\t\t\tSo(IsExist(\".hg\"), ShouldEqual, false)\n\t\t})\n\t})\n}\n\n\n\n\nfunc BenchmarkIsExist(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tIsExist(\"file.go\")\n\t}\n}\n\nfunc BenchmarkIsFile(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tIsFile(\"file.go\")\n\t}\n}"} {"input": "package gtk\n\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\n\nfunc (v *Menu) PopupAtMouseCursor(parentMenuShell IMenu, parentMenuItem IMenuItem, button int, activateTime uint32) {\n\twshell := nullableWidget(parentMenuShell)\n\twitem := nullableWidget(parentMenuItem)\n\n\tC.gtk_menu_popup(v.native(),\n\t\twshell,\n\t\twitem,\n\t\tnil,\n\t\tnil,\n\t\tC.guint(button),\n\t\tC.guint32(activateTime))\n}\n\nfunc (v *SizeGroup) GetIgnoreHidden() bool {\n\tc := C.gtk_size_group_get_ignore_hidden(v.native())\n\treturn gobool(c)\n}\n\n\nfunc (v *Window) SetWMClass(name, class string) {\n\tcName := C.CString(name)\n\tdefer C.free(unsafe.Pointer(cName))\n\tcClass := C.CString(class)\n\tdefer C.free(unsafe.Pointer(cClass))\n\tC.gtk_window_set_wmclass(v.native(), (*C.gchar)(cName), (*C.gchar)(cClass))\n}\n\nfunc (v *SizeGroup) SetIgnoreHidden(ignoreHidden bool) {\n\tC.gtk_size_group_set_ignore_hidden(v.native(), gbool(ignoreHidden))\n}\n\n\n\n\n\nfunc (v *FontButton) SetFontName(fontname string) bool {\n\tcstr := C.CString(fontname)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_font_button_set_font_name(v.native(), (*C.gchar)(cstr))\n\treturn gobool(c)\n}\n\nfunc (v *FontButton) GetFontName() string ", "output": "{\n\tc := C.gtk_font_button_get_font_name(v.native())\n\treturn goString(c)\n}"} {"input": "package leafnodes_test\n\nimport (\n\t. \"github.com/sinbad/git-lfs-ssh-serve/Godeps/_workspace/src/github.com/onsi/ginkgo\"\n\t. \"github.com/sinbad/git-lfs-ssh-serve/Godeps/_workspace/src/github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestLeafNode(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"LeafNode Suite\")\n}"} {"input": "package timeutil\n\nimport (\n\t\"time\"\n)\n\n\nfunc SetTimeout(t time.Duration, callback func()) {\n\tgo func() {\n\t\ttime.Sleep(t)\n\t\tcallback()\n\t}()\n}\n\n\n\nfunc SetInterval(t time.Duration, callback func() bool) {\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(t)\n\t\t\tif !callback() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\nfunc Nanosecond() int64 {\n\treturn time.Now().UnixNano()\n}\n\n\nfunc Microsecond() int64 {\n\treturn time.Now().UnixNano() / 1e3\n}\n\n\nfunc Millisecond() int64 {\n\treturn time.Now().UnixNano() / 1e6\n}\n\n\nfunc Second() int64 {\n\treturn time.Now().UnixNano() / 1e9\n}\n\n\nfunc Date() string {\n\treturn time.Now().Format(\"2006-01-02\")\n}\n\n\n\n\n\n\nfunc Format(format string, timestamps ...int64) string {\n\ttimestamp := Second()\n\tif len(timestamps) > 0 {\n\t\ttimestamp = timestamps[0]\n\t}\n\treturn time.Unix(timestamp, 0).Format(format)\n}\n\n\nfunc StrToTime(format string, timestr string) (int64, error) {\n\tt, err := time.Parse(format, timestr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn t.Unix(), nil\n}\n\nfunc Datetime() string ", "output": "{\n\treturn time.Now().Format(\"2006-01-02 15:04:05\")\n}"} {"input": "package iso20022\n\n\ntype PartyIdentificationAndAccount77 struct {\n\n\tIdentification *PartyIdentification32Choice `xml:\"Id\"`\n\n\tAlternateIdentification *AlternatePartyIdentification5 `xml:\"AltrnId,omitempty\"`\n\n\tSafekeepingAccount *Max35Text `xml:\"SfkpgAcct,omitempty\"`\n\n\tProcessingIdentification *Max35Text `xml:\"PrcgId,omitempty\"`\n\n\tAdditionalInformation *PartyTextInformation1 `xml:\"AddtlInf,omitempty\"`\n}\n\nfunc (p *PartyIdentificationAndAccount77) AddIdentification() *PartyIdentification32Choice {\n\tp.Identification = new(PartyIdentification32Choice)\n\treturn p.Identification\n}\n\nfunc (p *PartyIdentificationAndAccount77) AddAlternateIdentification() *AlternatePartyIdentification5 {\n\tp.AlternateIdentification = new(AlternatePartyIdentification5)\n\treturn p.AlternateIdentification\n}\n\nfunc (p *PartyIdentificationAndAccount77) SetSafekeepingAccount(value string) {\n\tp.SafekeepingAccount = (*Max35Text)(&value)\n}\n\nfunc (p *PartyIdentificationAndAccount77) SetProcessingIdentification(value string) {\n\tp.ProcessingIdentification = (*Max35Text)(&value)\n}\n\n\n\nfunc (p *PartyIdentificationAndAccount77) AddAdditionalInformation() *PartyTextInformation1 ", "output": "{\n\tp.AdditionalInformation = new(PartyTextInformation1)\n\treturn p.AdditionalInformation\n}"} {"input": "package armrecoveryservicesbackup_test\n\nimport (\n\t\"context\"\n\t\"log\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/recoveryservices/armrecoveryservicesbackup\"\n)\n\n\n\n\n\nfunc ExampleBackupEnginesClient_Get() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armrecoveryservicesbackup.NewBackupEnginesClient(\"\", cred, nil)\n\tres, err := client.Get(ctx,\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t&armrecoveryservicesbackup.BackupEnginesClientGetOptions{Filter: nil,\n\t\t\tSkipToken: nil,\n\t\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Response result: %#v\\n\", res.BackupEnginesClientGetResult)\n}\n\nfunc ExampleBackupEnginesClient_List() ", "output": "{\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armrecoveryservicesbackup.NewBackupEnginesClient(\"\", cred, nil)\n\tpager := client.List(\"\",\n\t\t\"\",\n\t\t&armrecoveryservicesbackup.BackupEnginesClientListOptions{Filter: nil,\n\t\t\tSkipToken: nil,\n\t\t})\n\tfor {\n\t\tnextResult := pager.NextPage(ctx)\n\t\tif err := pager.Err(); err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tif !nextResult {\n\t\t\tbreak\n\t\t}\n\t\tfor _, v := range pager.PageResponse().Value {\n\t\t\tlog.Printf(\"Pager result: %#v\\n\", v)\n\t\t}\n\t}\n}"} {"input": "package replicationcontroller\n\nimport (\n\t\"github.com/kubernetes/dashboard/src/app/backend/resource/common\"\n\t\"github.com/kubernetes/dashboard/src/app/backend/resource/dataselect\"\n\t\"github.com/kubernetes/dashboard/src/app/backend/resource/service\"\n\tmetaV1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\tclient \"k8s.io/client-go/kubernetes\"\n)\n\n\n\n\n\nfunc GetReplicationControllerServices(client client.Interface, dsQuery *dataselect.DataSelectQuery,\n\tnamespace, rcName string) (*service.ServiceList, error) ", "output": "{\n\n\treplicationController, err := client.CoreV1().ReplicationControllers(namespace).Get(rcName, metaV1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tchannels := &common.ResourceChannels{\n\t\tServiceList: common.GetServiceListChannel(client, common.NewSameNamespaceQuery(namespace),\n\t\t\t1),\n\t}\n\n\tservices := <-channels.ServiceList.List\n\tif err := <-channels.ServiceList.Error; err != nil {\n\t\treturn nil, err\n\t}\n\n\tmatchingServices := common.FilterNamespacedServicesBySelector(services.Items, namespace,\n\t\treplicationController.Spec.Selector)\n\treturn service.CreateServiceList(matchingServices, dsQuery), nil\n}"} {"input": "package nodos\n\nimport (\n\t\"unsafe\"\n)\n\n\n\nfunc progressPrintCallBack(totalL, totalH, transferL, transferH, c1, c2, d1, d2, e, f, g, h, this uintptr) uintptr ", "output": "{\n\tprogressPrint(uint64(totalL)|(uint64(totalH)<<32),\n\t\tuint64(transferL)|(uint64(transferH)<<32),\n\t\t(*progressCopy)(unsafe.Pointer(this)))\n\treturn 0\n}"} {"input": "package engine\n\nimport (\n\t\"time\"\n\n\t\"github.com/aws/amazon-ecs-agent/agent/api\"\n)\n\n\n\ntype impossibleTransitionError struct {\n\tstate api.ContainerStatus\n}\n\nfunc (err *impossibleTransitionError) Error() string {\n\treturn \"Cannot transition to \" + err.state.String()\n}\nfunc (err *impossibleTransitionError) ErrorName() string { return \"ImpossibleStateTransitionError\" }\n\ntype DockerTimeoutError struct {\n\tduration time.Duration\n\ttransition string\n}\n\nfunc (err *DockerTimeoutError) Error() string {\n\treturn \"Could not transition to \" + err.transition + \"; timed out after waiting \" + err.duration.String()\n}\nfunc (err *DockerTimeoutError) ErrorName() string { return \"DockerTimeoutError\" }\n\ntype ContainerVanishedError struct{}\n\nfunc (err ContainerVanishedError) Error() string { return \"No container matching saved ID found\" }\nfunc (err ContainerVanishedError) ErrorName() string { return \"ContainerVanishedError\" }\n\ntype CannotXContainerError struct {\n\ttransition string\n\tmsg string\n}\n\nfunc (err CannotXContainerError) Error() string { return err.msg }\nfunc (err CannotXContainerError) ErrorName() string {\n\treturn \"Cannot\" + err.transition + \"ContainerError\"\n}\n\ntype OutOfMemoryError struct{}\n\nfunc (err OutOfMemoryError) Error() string { return \"Container killed due to memory usage\" }\n\n\n\ntype DockerStateError struct {\n\tdockerError string\n\tname string\n}\n\nfunc NewDockerStateError(err string) DockerStateError {\n\treturn DockerStateError{\n\t\tdockerError: err,\n\t\tname: \"DockerStateError\",\n\t}\n}\n\nfunc (err DockerStateError) Error() string {\n\treturn err.dockerError\n}\nfunc (err DockerStateError) ErrorName() string {\n\treturn err.name\n}\n\nfunc (err OutOfMemoryError) ErrorName() string ", "output": "{ return \"OutOfMemoryError\" }"} {"input": "package vision \n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}\n\n\n\n\nfunc DefaultAuthScopes() []string ", "output": "{\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t\t\"https:www.googleapis.com/auth/cloud-vision\",\n\t}\n}"} {"input": "package msd\n\nimport (\n\t\"encoding/base64\"\n\t\"github.com/bluefw/blued/discoverd/api\"\n\t\"github.com/gin-gonic/gin\"\n\t\"log\"\n\t\"net/http\"\n)\n\ntype ServiceResource struct {\n\trepo *DiscoverdRepo\n\tlogger *log.Logger\n}\n\n\n\nfunc (sr *ServiceResource) RegMicroApp(c *gin.Context) {\n\tvar as api.MicroApp\n\tif err := c.Bind(&as); err != nil {\n\t\tc.JSON(http.StatusBadRequest, api.NewError(\"problem decoding body\"))\n\t\treturn\n\t}\n\n\tsr.repo.Register(&as)\n\tc.JSON(http.StatusCreated, nil)\n}\n\nfunc (sr *ServiceResource) GetRouterTable(c *gin.Context) {\n\taddr, err := base64.StdEncoding.DecodeString(c.Params.ByName(\"addr\"))\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, api.NewError(\"error decoding addr\"))\n\t\treturn\n\t}\n\trt := sr.repo.GetRouterTable(string(addr))\n\tc.JSON(http.StatusOK, rt)\n}\n\nfunc (sr *ServiceResource) Refresh(c *gin.Context) {\n\taddr, err := base64.StdEncoding.DecodeString(c.Params.ByName(\"addr\"))\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, api.NewError(\"error decoding addr\"))\n\t\treturn\n\t}\n\tappStatus := sr.repo.Refresh(string(addr))\n\tc.JSON(http.StatusAccepted, appStatus)\n}\n\nfunc NewServiceResource(dr *DiscoverdRepo, l *log.Logger) *ServiceResource ", "output": "{\n\treturn &ServiceResource{\n\t\trepo: dr,\n\t\tlogger: l,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"text/template\"\n)\n\n\n\n\n\nfunc copyFile(dst, src string) (int64, error) {\n\tsf, err := os.Open(src)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer sf.Close()\n\n\tdf, err := os.Create(dst)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer df.Close()\n\n\treturn io.Copy(df, sf)\n}\n\nfunc writeTemplateToFile(path string, t *template.Template, data interface{}) (string, error) ", "output": "{\n\tf, e := os.Create(path)\n\tif e != nil {\n\t\treturn \"\", e\n\t}\n\tdefer f.Close()\n\n\te = t.Execute(f, data)\n\tif e != nil {\n\t\treturn \"\", e\n\t}\n\n\treturn f.Name(), nil\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/NebulousLabs/Sia/build\"\n\t\"github.com/NebulousLabs/Sia/types\"\n)\n\n\n\ntype ConsensusGET struct {\n\tHeight types.BlockHeight `json:\"height\"`\n\tCurrentBlock types.BlockID `json:\"currentblock\"`\n\tTarget types.Target `json:\"target\"`\n}\n\n\n\n\n\nfunc (srv *Server) consensusHandler(w http.ResponseWriter, req *http.Request) {\n\tif req.Method == \"\" || req.Method == \"GET\" {\n\t\tsrv.consensusHandlerGET(w, req)\n\t\treturn\n\t}\n\twriteError(w, \"unrecognized method when calling /consensus\", http.StatusBadRequest)\n}\n\nfunc (srv *Server) consensusHandlerGET(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tid := srv.mu.RLock()\n\tdefer srv.mu.RUnlock(id)\n\n\tcurblockID := srv.currentBlock.ID()\n\tcurrentTarget, exists := srv.cs.ChildTarget(curblockID)\n\tif build.DEBUG {\n\t\tif !exists {\n\t\t\tfmt.Printf(\"Could not find block %s\\n\", curblockID)\n\t\t\tpanic(\"server has nonexistent current block\")\n\t\t}\n\t}\n\n\twriteJSON(w, ConsensusGET{\n\t\tHeight: types.BlockHeight(srv.blockchainHeight),\n\t\tCurrentBlock: srv.currentBlock.ID(),\n\t\tTarget: currentTarget,\n\t})\n}"} {"input": "package triton\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/hashicorp/errwrap\"\n)\n\ntype ConfigClient struct {\n\t*Client\n}\n\n\n\nfunc (c *Client) Config() *ConfigClient {\n\treturn &ConfigClient{c}\n}\n\n\ntype Config struct {\n\tDefaultNetwork string `json:\"default_network\"`\n}\n\ntype GetConfigInput struct{}\n\n\nfunc (client *ConfigClient) GetConfig(ctx context.Context, input *GetConfigInput) (*Config, error) {\n\tpath := fmt.Sprintf(\"/%s/config\", client.accountName)\n\trespReader, err := client.executeRequest(ctx, http.MethodGet, path, nil)\n\tif respReader != nil {\n\t\tdefer respReader.Close()\n\t}\n\tif err != nil {\n\t\treturn nil, errwrap.Wrapf(\"Error executing GetConfig request: {{err}}\", err)\n\t}\n\n\tvar result *Config\n\tdecoder := json.NewDecoder(respReader)\n\tif err = decoder.Decode(&result); err != nil {\n\t\treturn nil, errwrap.Wrapf(\"Error decoding GetConfig response: {{err}}\", err)\n\t}\n\n\treturn result, nil\n}\n\ntype UpdateConfigInput struct {\n\tDefaultNetwork string `json:\"default_network\"`\n}\n\n\n\n\nfunc (client *ConfigClient) UpdateConfig(ctx context.Context, input *UpdateConfigInput) (*Config, error) ", "output": "{\n\tpath := fmt.Sprintf(\"/%s/config\", client.accountName)\n\trespReader, err := client.executeRequest(ctx, http.MethodPut, path, input)\n\tif respReader != nil {\n\t\tdefer respReader.Close()\n\t}\n\tif err != nil {\n\t\treturn nil, errwrap.Wrapf(\"Error executing UpdateConfig request: {{err}}\", err)\n\t}\n\n\tvar result *Config\n\tdecoder := json.NewDecoder(respReader)\n\tif err = decoder.Decode(&result); err != nil {\n\t\treturn nil, errwrap.Wrapf(\"Error decoding UpdateConfig response: {{err}}\", err)\n\t}\n\n\treturn result, nil\n}"} {"input": "package xy\n\ntype Group []Geometric\n\n\nfunc (g *Group) Add(shape Geometric) {\n\t*g = append(*g, shape)\n}\n\nfunc (g Group) Accept(visitor Visitor) ", "output": "{\n\tvisitor.VisitGroup(g)\n}"} {"input": "package server\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/localhots/shezmu/stats\"\n)\n\ntype Server struct {\n\tport int\n\tss *stats.Server\n\tmux *http.ServeMux\n}\n\n\n\nfunc (s *Server) Start() {\n\taddr := fmt.Sprintf(\":%d\", s.port)\n\ts.mux.HandleFunc(\"/stats.json\", s.ss.History)\n\tgo http.ListenAndServe(addr, s.mux)\n}\n\nfunc New(port int, ss *stats.Server) *Server ", "output": "{\n\treturn &Server{\n\t\tport: port,\n\t\tss: ss,\n\t\tmux: http.NewServeMux(),\n\t}\n}"} {"input": "package goapp\n\n\nimport(\n \"github.com/xaevman/goat/mod/log\"\n)\n\n\nimport(\n \"testing\"\n \"time\"\n)\n\n\n\n\n\n\n\nfunc waitForShutdown() {\n <-time.After(10 * time.Second)\n Stop()\n}\n\nfunc TestDefaultApp(t *testing.T) ", "output": "{\n log.DebugLogs = true\n\n SetHeartbeat(1 * 1000) \n go waitForShutdown()\n\n stopChan := Start(\"DefaultApp\")\n <-stopChan\n}"} {"input": "package kasper\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestTopicProcessorConfig_kafkaConsumerGroup(t *testing.T) {\n\tc := &Config{\n\t\tTopicProcessorName: \"hari-seldon\",\n\t}\n\tassert.Equal(t, \"kasper-topic-processor-hari-seldon\", c.kafkaConsumerGroup())\n}\n\n\n\nfunc TestTopicProcessorConfig_producerClientID(t *testing.T) ", "output": "{\n\tc := &Config{\n\t\tTopicProcessorName: \"ford-prefect\",\n\t}\n\tassert.Equal(t, \"kasper-topic-processor-ford-prefect\", c.producerClientID())\n}"} {"input": "package util\n\nimport \"fmt\"\n\n\n\n\n\n\n\nfunc PanicOnError(err error, message string) {\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"%s: %s\", message, err.Error()))\n\t}\n}\n\nfunc PanicIfNil(check interface{}, message string) ", "output": "{\n\tif check == nil {\n\t\tpanic(message)\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/protobuf/encoding/prototext\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t_ \"google.golang.org/genproto/googleapis/rpc/errdetails\" \n)\n\n\ntype StatusError struct {\n\tst *status.Status\n\tdetails string\n}\n\n\nfunc StatusDetailedError(st *status.Status) *StatusError {\n\tvar details []string\n\tfor _, d := range st.Details() {\n\t\ts := fmt.Sprintf(\"%+v\", d)\n\t\tif pb, ok := d.(proto.Message); ok {\n\t\t\ts = prototext.Format(pb)\n\t\t}\n\t\tdetails = append(details, s)\n\t}\n\treturn &StatusError{st, strings.Join(details, \"; \")}\n}\n\n\n\n\nfunc (e *StatusError) GRPCStatus() *status.Status {\n\treturn e.st\n}\n\n\n\nfunc (e *StatusError) Is(target error) bool {\n\tif tse, ok := target.(*StatusError); ok {\n\t\treturn proto.Equal(e.st.Proto(), tse.st.Proto())\n\t}\n\tif tst, ok := status.FromError(target); ok {\n\t\treturn proto.Equal(e.st.Proto(), tst.Proto())\n\t}\n\treturn false\n}\n\nfunc (e *StatusError) Error() string ", "output": "{\n\tmsg := fmt.Sprintf(\"rpc error: code = %s desc = %s\", e.st.Code(), e.st.Message())\n\tif e.details != \"\" {\n\t\tmsg += \" details = \" + e.details\n\t}\n\treturn msg\n}"} {"input": "package lints\n\n\n\n\n\nimport (\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/util\"\n)\n\ntype caKeyCertSignNotSet struct{}\n\nfunc (l *caKeyCertSignNotSet) Initialize() error {\n\treturn nil\n}\n\n\n\nfunc (l *caKeyCertSignNotSet) Execute(c *x509.Certificate) *LintResult {\n\tif c.KeyUsage&x509.KeyUsageCertSign != 0 {\n\t\treturn &LintResult{Status: Pass}\n\t} else {\n\t\treturn &LintResult{Status: Error}\n\t}\n}\n\nfunc init() {\n\tRegisterLint(&Lint{\n\t\tName: \"e_ca_key_cert_sign_not_set\",\n\t\tDescription: \"Root CA Certificate: Bit positions for keyCertSign and cRLSign MUST be set.\",\n\t\tCitation: \"BRs: 7.1.2.1\",\n\t\tSource: CABFBaselineRequirements,\n\t\tEffectiveDate: util.CABEffectiveDate,\n\t\tLint: &caKeyCertSignNotSet{},\n\t})\n}\n\nfunc (l *caKeyCertSignNotSet) CheckApplies(c *x509.Certificate) bool ", "output": "{\n\treturn c.IsCA && util.IsExtInCert(c, util.KeyUsageOID)\n}"} {"input": "package transporttest\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\n\ntype ContextMatcher struct {\n\tt *testing.T\n\tttl time.Duration\n\n\tTTLDelta time.Duration\n}\n\n\ntype ContextMatcherOption interface {\n\trun(*ContextMatcher)\n}\n\n\n\ntype ContextTTL time.Duration\n\nfunc (ttl ContextTTL) run(c *ContextMatcher) {\n\tc.ttl = time.Duration(ttl)\n}\n\n\n\nfunc NewContextMatcher(t *testing.T, options ...ContextMatcherOption) *ContextMatcher {\n\tmatcher := &ContextMatcher{t: t, TTLDelta: DefaultTTLDelta}\n\tfor _, opt := range options {\n\t\topt.run(matcher)\n\t}\n\treturn matcher\n}\n\n\n\n\nfunc (c *ContextMatcher) Matches(got interface{}) bool {\n\tctx, ok := got.(context.Context)\n\tif !ok {\n\t\tc.t.Logf(\"expected a Context but got a %T: %v\", got, got)\n\t\treturn false\n\t}\n\n\tif c.ttl != 0 {\n\t\td, ok := ctx.Deadline()\n\t\tif !ok {\n\t\t\tc.t.Logf(\n\t\t\t\t\"expected Context to have a TTL of %v but it has no deadline\", c.ttl)\n\t\t\treturn false\n\t\t}\n\n\t\tttl := time.Until(d)\n\t\tmaxTTL := c.ttl + c.TTLDelta\n\t\tminTTL := c.ttl - c.TTLDelta\n\t\tif ttl > maxTTL || ttl < minTTL {\n\t\t\tc.t.Logf(\"TTL out of expected bounds: %v < %v < %v\", minTTL, ttl, maxTTL)\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n\n\nfunc (c *ContextMatcher) String() string ", "output": "{\n\treturn fmt.Sprintf(\"ContextMatcher(TTL:%v±%v)\", c.ttl, c.TTLDelta)\n}"} {"input": "package identitymapper\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/klog\"\n\n\t\"k8s.io/apiserver/pkg/authentication/authenticator\"\n\n\t\"github.com/openshift/origin/pkg/oauthserver/api\"\n)\n\n\n\n\n\nfunc logf(format string, args ...interface{}) {\n\tif klog.V(4) {\n\t\tklog.InfoDepth(2, fmt.Sprintf(\"identitymapper: \"+format, args...))\n\t}\n}\n\nfunc ResponseFor(mapper api.UserIdentityMapper, identity api.UserIdentityInfo) (*authenticator.Response, bool, error) ", "output": "{\n\tuser, err := mapper.UserFor(identity)\n\tif err != nil {\n\t\tlogf(\"error creating or updating mapping for: %#v due to %v\", identity, err)\n\t\treturn nil, false, err\n\t}\n\tlogf(\"got userIdentityMapping: %#v\", user)\n\n\treturn &authenticator.Response{User: user}, true, nil\n}"} {"input": "package collector\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/log\"\n)\n\n\nimport \"C\"\n\ntype loadavgCollector struct {\n\tmetric prometheus.Gauge\n}\n\nfunc init() {\n\tFactories[\"loadavg\"] = NewLoadavgCollector\n}\n\n\n\n\n\nfunc (c *loadavgCollector) Update(ch chan<- prometheus.Metric) (err error) {\n\tload, err := getLoad1()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Couldn't get load: %s\", err)\n\t}\n\tlog.Debugf(\"Set node_load: %f\", load)\n\tc.metric.Set(load)\n\tc.metric.Collect(ch)\n\treturn err\n}\n\nfunc getLoad1() (float64, error) {\n\tvar loadavg [1]C.double\n\tsamples := C.getloadavg(&loadavg[0], 1)\n\tif samples > 0 {\n\t\treturn float64(loadavg[0]), nil\n\t} else {\n\t\treturn 0, errors.New(\"failed to get load average\")\n\t}\n\n}\n\nfunc NewLoadavgCollector() (Collector, error) ", "output": "{\n\treturn &loadavgCollector{\n\t\tmetric: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tNamespace: Namespace,\n\t\t\tName: \"load1\",\n\t\t\tHelp: \"1m load average.\",\n\t\t}),\n\t}, nil\n}"} {"input": "package library\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/vapi/library\"\n\t\"github.com/vmware/govmomi/vapi/rest\"\n)\n\ntype rm struct {\n\t*flags.ClientFlag\n\tforce bool\n}\n\n\n\nfunc (cmd *rm) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.ClientFlag, ctx = flags.NewClientFlag(ctx)\n\tcmd.ClientFlag.Register(ctx, f)\n}\n\nfunc (cmd *rm) Usage() string {\n\treturn \"NAME\"\n}\n\nfunc (cmd *rm) Description() string {\n\treturn `Delete library or item NAME.\n\nExamples:\n govc library.rm /library_name\n govc library.rm library_id # Use library id if multiple libraries have the same name\n govc library.rm /library_name/item_name`\n}\n\nfunc (cmd *rm) Run(ctx context.Context, f *flag.FlagSet) error {\n\treturn cmd.WithRestClient(ctx, func(c *rest.Client) error {\n\t\tm := library.NewManager(c)\n\t\tres, err := flags.ContentLibraryResult(ctx, c, \"\", f.Arg(0))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch t := res.GetResult().(type) {\n\t\tcase library.Library:\n\t\t\treturn m.DeleteLibrary(ctx, &t)\n\t\tcase library.Item:\n\t\t\treturn m.DeleteLibraryItem(ctx, &t)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"%q is a %T\", f.Arg(0), t)\n\t\t}\n\t})\n}\n\nfunc init() ", "output": "{\n\tcli.Register(\"library.rm\", &rm{})\n}"} {"input": "package topovalidator\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"vitess.io/vitess/go/vt/topo\"\n\n\ttopodatapb \"vitess.io/vitess/go/vt/proto/topodata\"\n)\n\n\n\n\n\n\n\n\n\n\ntype KeyspaceValidator struct{}\n\n\nfunc (kv *KeyspaceValidator) Audit(ctx context.Context, ts *topo.Server, w *Workflow) error {\n\tkeyspaces, err := ts.GetKeyspaces(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, keyspace := range keyspaces {\n\t\t_, err := ts.GetKeyspace(ctx, keyspace)\n\t\tif err != nil {\n\t\t\tw.AddFixer(keyspace, fmt.Sprintf(\"Error: %v\", err), &KeyspaceFixer{\n\t\t\t\tts: ts,\n\t\t\t\tkeyspace: keyspace,\n\t\t\t}, []string{\"Create\", \"Delete\"})\n\t\t}\n\t}\n\treturn nil\n}\n\n\ntype KeyspaceFixer struct {\n\tts *topo.Server\n\tkeyspace string\n}\n\n\nfunc (kf *KeyspaceFixer) Action(ctx context.Context, name string) error {\n\tif name == \"Create\" {\n\t\treturn kf.ts.CreateKeyspace(ctx, kf.keyspace, &topodatapb.Keyspace{})\n\t}\n\tif name == \"Delete\" {\n\t\treturn kf.ts.DeleteKeyspace(ctx, kf.keyspace)\n\t}\n\treturn fmt.Errorf(\"unknown KeyspaceFixer action: %v\", name)\n}\n\nfunc RegisterKeyspaceValidator() ", "output": "{\n\tRegisterValidator(\"Keyspace Validator\", &KeyspaceValidator{})\n}"} {"input": "package graphdriver\n\n\nimport \"C\"\nimport (\n\t\"path/filepath\"\n\t\"unsafe\"\n\n\t\"github.com/docker/docker/pkg/mount\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tFsMagicZfs = FsMagic(0x2fc12fc1)\n)\n\nvar (\n\tpriority = []string{\n\t\t\"zfs\",\n\t}\n\n\tFsNames = map[FsMagic]string{\n\t\tFsMagicZfs: \"zfs\",\n\t}\n)\n\n\nfunc GetFSMagic(rootpath string) (FsMagic, error) {\n\treturn 0, nil\n}\n\ntype fsChecker struct {\n\tt FsMagic\n}\n\nfunc (c *fsChecker) IsMounted(path string) bool {\n\tm, _ := Mounted(c.t, path)\n\treturn m\n}\n\n\nfunc NewFsChecker(t FsMagic) Checker {\n\treturn &fsChecker{\n\t\tt: t,\n\t}\n}\n\n\n\n\nfunc NewDefaultChecker() Checker {\n\treturn &defaultChecker{}\n}\n\ntype defaultChecker struct {\n}\n\nfunc (c *defaultChecker) IsMounted(path string) bool {\n\tm, _ := mount.Mounted(path)\n\treturn m\n}\n\n\n\n\n\nfunc Mounted(fsType FsMagic, mountPath string) (bool, error) ", "output": "{\n\n\tcs := C.CString(filepath.Dir(mountPath))\n\tdefer C.free(unsafe.Pointer(cs))\n\tbuf := C.getstatfs(cs)\n\tdefer C.free(unsafe.Pointer(buf))\n\n\tif (buf.f_basetype[0] != 122) || (buf.f_basetype[1] != 102) || (buf.f_basetype[2] != 115) ||\n\t\t(buf.f_basetype[3] != 0) {\n\t\tlogrus.Debugf(\"[zfs] no zfs dataset found for rootdir '%s'\", mountPath)\n\t\treturn false, ErrPrerequisites\n\t}\n\n\treturn true, nil\n}"} {"input": "package blobstoredbstatesnapshotio\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/nyaxt/otaru/metadata\"\n)\n\nfunc generateBlobpath() string {\n\treturn fmt.Sprintf(\"%s_SimpleSSLocator\", metadata.INodeDBSnapshotBlobpathPrefix)\n}\n\nvar simplesslocatorTxID int64\n\ntype SimpleSSLocator struct{}\n\nfunc (SimpleSSLocator) Locate(history int) (string, int64, error) {\n\treturn generateBlobpath(), simplesslocatorTxID, nil\n}\n\nfunc (SimpleSSLocator) GenerateBlobpath() string {\n\treturn generateBlobpath()\n}\n\nfunc (SimpleSSLocator) Put(blobpath string, txid int64) error {\n\tsimplesslocatorTxID = txid\n\treturn nil\n}\n\n\n\nfunc (SimpleSSLocator) DeleteOld(ctx context.Context, threshold int, dryRun bool) ([]string, error) ", "output": "{\n\treturn []string{}, nil\n}"} {"input": "package header\n\nimport \"github.com/google/netstack/tcpip\"\n\n\n\n\n\ntype NDPNeighborSolicit []byte\n\nconst (\n\tNDPNSMinimumSize = 20\n\n\tndpNSTargetAddessOffset = 4\n\n\tndpNSOptionsOffset = ndpNSTargetAddessOffset + IPv6AddressSize\n)\n\n\n\n\n\nfunc (b NDPNeighborSolicit) SetTargetAddress(addr tcpip.Address) {\n\tcopy(b[ndpNSTargetAddessOffset:][:IPv6AddressSize], addr)\n}\n\n\nfunc (b NDPNeighborSolicit) Options() NDPOptions {\n\treturn NDPOptions(b[ndpNSOptionsOffset:])\n}\n\nfunc (b NDPNeighborSolicit) TargetAddress() tcpip.Address ", "output": "{\n\treturn tcpip.Address(b[ndpNSTargetAddessOffset:][:IPv6AddressSize])\n}"} {"input": "package format\n\nimport (\n\t\"github.com/trivago/gollum/core\"\n\t\"os\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Hostname struct {\n\tcore.SimpleFormatter `gollumdoc:\"embed_type\"`\n\tseparator []byte `config:\"Separator\" default:\":\"`\n}\n\nfunc init() {\n\tcore.TypeRegistry.Register(Hostname{})\n}\n\n\nfunc (format *Hostname) Configure(conf core.PluginConfigReader) {\n}\n\n\nfunc (format *Hostname) ApplyFormatter(msg *core.Message) error {\n\tcontent := format.getFinalContent(format.GetAppliedContent(msg))\n\tformat.SetAppliedContent(msg, content)\n\n\treturn nil\n}\n\n\n\nfunc (format *Hostname) getFinalContent(content []byte) []byte ", "output": "{\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\tformat.Logger.Error(err)\n\t\thostname = \"unknown host\"\n\t}\n\n\tdataSize := len(hostname) + len(format.separator) + len(content)\n\tpayload := core.MessageDataPool.Get(dataSize)\n\n\toffset := copy(payload, []byte(hostname))\n\toffset += copy(payload[offset:], format.separator)\n\tcopy(payload[offset:], content)\n\n\treturn payload\n}"} {"input": "package lifegame\n\ntype Universe struct {\n\taliveCells []Cell\n}\n\ntype Cell struct{}\n\nfunc NewUniverse() *Universe {\n\treturn &Universe{}\n}\n\nfunc (u *Universe) HasAliveCell() bool {\n\treturn len(u.AliveCells()) != 0\n}\n\nfunc (u *Universe) AliveCells() []Cell {\n\treturn u.aliveCells\n}\n\nfunc (u *Universe) NextGeneration() {\n\tu.aliveCells = []Cell{}\n}\n\nfunc (u *Universe) BornCellAtLocation(x, y int) {\n\tu.aliveCells = append(u.aliveCells, Cell{})\n}\n\n\n\nfunc (c *Cell) Location() (int, int) ", "output": "{\n\treturn 0, 0\n}"} {"input": "package backend\n\nimport (\n\t\"sync\"\n\n\t\"github.com/docker/infrakit/pkg/run/scope\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/pflag\"\n)\n\n\ntype ExecFunc func(script string, cmd *cobra.Command, args []string) error\n\n\ntype FlagsFunc func(*pflag.FlagSet)\n\n\ntype TemplateFunc func(scope scope.Scope, trial bool, opt ...interface{}) (ExecFunc, error)\n\nvar (\n\tbackends = map[string]TemplateFunc{}\n\tflags = map[string]FlagsFunc{}\n\tlock = sync.Mutex{}\n)\n\n\n\n\n\n\n\nfunc Visit(visitor func(funcName string, backend TemplateFunc)) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tfor funcName, backend := range backends {\n\t\tvisitor(funcName, backend)\n\t}\n}\n\n\nfunc VisitFlags(visitor func(string, FlagsFunc)) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tfor funcName, f := range flags {\n\t\tvisitor(funcName, f)\n\t}\n}\n\nfunc Register(funcName string, backend TemplateFunc, buildFlags FlagsFunc) ", "output": "{\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tbackends[funcName] = backend\n\tflags[funcName] = buildFlags\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/fnproject/fn/api\"\n\t\"github.com/gin-gonic/gin\"\n)\n\n\n\nfunc (s *Server) handleAppGet(c *gin.Context) ", "output": "{\n\tctx := c.Request.Context()\n\n\tappId := c.Param(api.AppID)\n\tapp, err := s.datastore.GetAppByID(ctx, appId)\n\tif err != nil {\n\t\thandleErrorResponse(c, err)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, app)\n}"} {"input": "package restic\n\nimport \"syscall\"\n\nfunc (node Node) restoreSymlinkTimestamps(path string, utimes [2]syscall.Timespec) error {\n\treturn nil\n}\n\nfunc (node Node) device() int {\n\treturn int(node.Device)\n}\n\nfunc (s statUnix) atim() syscall.Timespec { return s.Atimespec }\nfunc (s statUnix) mtim() syscall.Timespec { return s.Mtimespec }\nfunc (s statUnix) ctim() syscall.Timespec { return s.Ctimespec }\n\n\nfunc Getxattr(path, name string) ([]byte, error) {\n\treturn nil, nil\n}\n\n\n\n\n\n\nfunc Setxattr(path, name string, data []byte) error {\n\treturn nil\n}\n\nfunc Listxattr(path string) ([]string, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package post\n\nimport \"github.com/barnex/bruteray/imagef\"\n\ntype Params struct {\n\tGaussian BloomParams\n\tAiry BloomParams\n\tStar BloomParams\n}\n\ntype BloomParams struct {\n\tRadius float64\n\tAmplitude float64\n\tThreshold float64\n}\n\nfunc (p *Params) ApplyTo(img imagef.Image, pixelSize float64) imagef.Image {\n\tif b := p.Gaussian; b.Radius != 0 {\n\t\timg = ApplyGaussianBloom(img, pixelSize, b.Radius, b.Amplitude, b.Threshold)\n\t}\n\tif b := p.Airy; b.Radius != 0 {\n\t\timg = ApplyAiryBloom(img, pixelSize, b.Radius, b.Amplitude, b.Threshold)\n\t}\n\tif b := p.Star; b.Radius != 0 {\n\t\timg = ApplyStarBloom(img, pixelSize, b.Radius, b.Amplitude, b.Threshold)\n\t}\n\treturn img\n}\n\nfunc ApplyGaussianBloom(img imagef.Image, pixelSize, radius, amplitude, threshold float64) imagef.Image {\n\twidthPix := radius / pixelSize\n\tnumPix := int(5*widthPix) + 1\n\tK := Gaussian(numPix, widthPix)\n\timg2 := img.Copy()\n\tAddConvolution(img2, img, K, amplitude, threshold)\n\treturn img2\n}\n\nfunc ApplyAiryBloom(img imagef.Image, pixelSize, radius, amplitude, threshold float64) imagef.Image {\n\twidthPix := radius / pixelSize\n\tnumPix := int(8*widthPix) + 1\n\tK := Airy(numPix, widthPix)\n\timg2 := img.Copy()\n\tAddConvolution(img2, img, K, amplitude, threshold)\n\treturn img2\n}\n\n\n\nfunc ApplyStarBloom(img imagef.Image, pixelSize, radius, amplitude, threshold float64) imagef.Image ", "output": "{\n\twidthPix := radius / pixelSize\n\tnumPix := int(widthPix)\n\tK := starKernel(numPix)\n\timg2 := img.Copy()\n\tAddConvolution(img2, img, K, amplitude, threshold)\n\treturn img2\n}"} {"input": "package byteorder\n\nimport (\n\t\"encoding/binary\"\n\t\"net\"\n\t\"testing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\ntype ByteorderSuite struct{}\n\nvar _ = Suite(&ByteorderSuite{})\n\nfunc (b *ByteorderSuite) TestNativeIsInitialized(c *C) {\n\tc.Assert(Native, NotNil)\n}\n\nfunc (b *ByteorderSuite) TestHostToNetwork(c *C) {\n\tswitch Native {\n\tcase binary.LittleEndian:\n\t\tc.Assert(HostToNetwork16(0xAABB), Equals, uint16(0xBBAA))\n\t\tc.Assert(HostToNetwork32(0xAABBCCDD), Equals, uint32(0xDDCCBBAA))\n\tcase binary.BigEndian:\n\t\tc.Assert(HostToNetwork16(0xAABB), Equals, uint16(0xAABB))\n\t\tc.Assert(HostToNetwork32(0xAABBCCDD), Equals, uint32(0xAABBCCDD))\n\t}\n}\n\n\n\nfunc (b *ByteorderSuite) TestNetIPv4ToHost32(c *C) ", "output": "{\n\tswitch Native {\n\tcase binary.LittleEndian:\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.129.91\")), Equals, uint32(0x5b810b0a))\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.138.214\")), Equals, uint32(0xd68a0b0a))\n\tcase binary.BigEndian:\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.129.91\")), Equals, uint32(0x0a0b815b))\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.138.214\")), Equals, uint32(0x0a0b8ad6))\n\t}\n}"} {"input": "package vm\n\nimport (\n\t\"github.com/expanse-org/go-expanse/common\"\n\t\"github.com/expanse-org/go-expanse/common/math\"\n\t\"github.com/holiman/uint256\"\n)\n\n\n\n\n\n\n\n\nfunc calcMemSize64WithUint(off *uint256.Int, length64 uint64) (uint64, bool) {\n\tif length64 == 0 {\n\t\treturn 0, false\n\t}\n\toffset64, overflow := off.Uint64WithOverflow()\n\tif overflow {\n\t\treturn 0, true\n\t}\n\tval := offset64 + length64\n\treturn val, val < offset64\n}\n\n\n\nfunc getData(data []byte, start uint64, size uint64) []byte {\n\tlength := uint64(len(data))\n\tif start > length {\n\t\tstart = length\n\t}\n\tend := start + size\n\tif end > length {\n\t\tend = length\n\t}\n\treturn common.RightPadBytes(data[start:end], int(size))\n}\n\n\nfunc toWordSize(size uint64) uint64 {\n\tif size > math.MaxUint64-31 {\n\t\treturn math.MaxUint64/32 + 1\n\t}\n\n\treturn (size + 31) / 32\n}\n\nfunc allZero(b []byte) bool {\n\tfor _, byte := range b {\n\t\tif byte != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc calcMemSize64(off, l *uint256.Int) (uint64, bool) ", "output": "{\n\tif !l.IsUint64() {\n\t\treturn 0, true\n\t}\n\treturn calcMemSize64WithUint(off, l.Uint64())\n}"} {"input": "package metrics_test\n\nimport (\n\t\"github.com/stripe/veneur/v14/ssf\"\n\t\"github.com/stripe/veneur/v14/trace\"\n\t\"github.com/stripe/veneur/v14/trace/metrics\"\n)\n\n\n\nfunc ExampleReportAsync() ", "output": "{\n\tsamples := []*ssf.SSFSample{}\n\n\tsamples = append(samples, ssf.Count(\"a.counter\", 2, nil))\n\tsamples = append(samples, ssf.Gauge(\"a.gauge\", 420, nil))\n\n\tdone := make(chan error)\n\tmetrics.ReportAsync(trace.DefaultClient, samples, done)\n\t<-done\n}"} {"input": "package cluster\n\nimport (\n\t\"common\"\n\t\"testing\"\n\t. \"launchpad.net/gocheck\"\n)\n\ntype UserSuite struct{}\n\nvar _ = Suite(&UserSuite{})\n\nvar root common.User\n\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\n\n\nfunc (self *UserSuite) TestProperties(c *C) {\n\tu := ClusterAdmin{CommonUser{Name: \"root\"}}\n\tc.Assert(u.IsClusterAdmin(), Equals, true)\n\tc.Assert(u.GetName(), Equals, \"root\")\n\thash, err := HashPassword(\"foobar\")\n\tc.Assert(err, IsNil)\n\tc.Assert(u.ChangePassword(string(hash)), IsNil)\n\tc.Assert(u.isValidPwd(\"foobar\"), Equals, true)\n\tc.Assert(u.isValidPwd(\"password\"), Equals, false)\n\n\tdbUser := DbUser{CommonUser{Name: \"db_user\"}, \"db\", nil, nil, true}\n\tc.Assert(dbUser.IsClusterAdmin(), Equals, false)\n\tc.Assert(dbUser.IsDbAdmin(\"db\"), Equals, true)\n\tc.Assert(dbUser.GetName(), Equals, \"db_user\")\n\thash, err = HashPassword(\"password\")\n\tc.Assert(err, IsNil)\n\tc.Assert(dbUser.ChangePassword(string(hash)), IsNil)\n\tc.Assert(dbUser.isValidPwd(\"password\"), Equals, true)\n\tc.Assert(dbUser.isValidPwd(\"password1\"), Equals, false)\n}\n\nfunc (self *UserSuite) SetUpSuite(c *C) ", "output": "{\n\tuser := &ClusterAdmin{CommonUser{\"root\", \"\", false, \"root\"}}\n\tc.Assert(user.ChangePassword(\"password\"), IsNil)\n\troot = user\n}"} {"input": "package common\n\nimport (\n\t\"strconv\"\n\t\"time\"\n)\n\ntype ConversionResult struct {\n\tDateAsString string\n\tDateAsInt int\n\tDate time.Time\n}\n\nfunc ConvertIntToDisplay(dateAsInt int) string {\n\tdayAsString := strconv.Itoa(dateAsInt)\n\n\treturn dayAsString\n}\n\nfunc ConvertStringToDates(dateAsString string) (ConversionResult, error) {\n\tresult := ConversionResult{}\n\tresult.DateAsString = dateAsString\n\n\tdateAsInt, err := strconv.Atoi(dateAsString)\n\tif err != nil {\n\t\treturn result, nil\n\t}\n\tresult.DateAsInt = dateAsInt\n\n\tdate, err := time.Parse(\"20060102\", dateAsString)\n\tif err != nil {\n\t\treturn result, nil\n\t}\n\tresult.Date = date\n\n\treturn result, nil\n}\n\n\n\nfunc (d *ConversionResult) Yesterday() (ConversionResult, error) {\n\treturn ConvertStringToDates(d.Date.AddDate(0, 0, -1).Format(\"20060102\"))\n}\n\nfunc (d *ConversionResult) Tomorrow() (ConversionResult, error) ", "output": "{\n\treturn ConvertStringToDates(d.Date.AddDate(0, 0, 1).Format(\"20060102\"))\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CopyVolumeGroupBackupRequest struct {\n\n\tVolumeGroupBackupId *string `mandatory:\"true\" contributesTo:\"path\" name:\"volumeGroupBackupId\"`\n\n\tCopyVolumeGroupBackupDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request CopyVolumeGroupBackupRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CopyVolumeGroupBackupRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CopyVolumeGroupBackupRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CopyVolumeGroupBackupResponse struct {\n\n\tRawResponse *http.Response\n\n\tVolumeGroupBackup `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CopyVolumeGroupBackupResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CopyVolumeGroupBackupResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CopyVolumeGroupBackupRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package handler\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/cosiner/zerver\"\n)\n\ntype MethodHandler interface {\n\tGet(zerver.Request, zerver.Response)\n\tPost(zerver.Request, zerver.Response)\n\tDelete(zerver.Request, zerver.Response)\n\tPut(zerver.Request, zerver.Response)\n\tPatch(zerver.Request, zerver.Response)\n}\n\ntype methodHandler struct {\n\tzerver.Component\n\tMethodHandler\n}\n\nfunc WrapMethodHandler(m MethodHandler) zerver.Handler {\n\treturn &methodHandler{\n\t\tComponent: zerver.NopComponent{},\n\t\tMethodHandler: m,\n\t}\n}\n\nfunc (s methodHandler) Handler(method string) zerver.HandleFunc {\n\tswitch method {\n\tcase zerver.METHOD_GET:\n\t\treturn s.Get\n\tcase zerver.METHOD_POST:\n\t\treturn s.Post\n\tcase zerver.METHOD_DELETE:\n\t\treturn s.Delete\n\tcase zerver.METHOD_PUT:\n\t\treturn s.Put\n\tcase zerver.METHOD_PATCH:\n\t\treturn s.Patch\n\t}\n\n\treturn nil\n}\n\ntype NopMethodHandler struct{}\n\nfunc (NopMethodHandler) Get(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Post(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Delete(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\n\n\nfunc (NopMethodHandler) Patch(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Put(_ zerver.Request, resp zerver.Response) ", "output": "{\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/bitly/go-nsq\"\n)\n\n\n\ntype BackendQueue interface {\n\tPut([]byte) error\n\tReadChan() chan []byte \n\tClose() error\n\tDelete() error\n\tDepth() int64\n\tEmpty() error\n}\n\ntype DummyBackendQueue struct {\n\treadChan chan []byte\n}\n\nfunc NewDummyBackendQueue() BackendQueue {\n\treturn &DummyBackendQueue{readChan: make(chan []byte)}\n}\n\nfunc (d *DummyBackendQueue) Put([]byte) error {\n\treturn nil\n}\n\n\n\nfunc (d *DummyBackendQueue) Close() error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Delete() error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Depth() int64 {\n\treturn int64(0)\n}\n\nfunc (d *DummyBackendQueue) Empty() error {\n\treturn nil\n}\n\nfunc WriteMessageToBackend(buf *bytes.Buffer, msg *nsq.Message, bq BackendQueue) error {\n\tbuf.Reset()\n\terr := msg.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = bq.Put(buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) ReadChan() chan []byte ", "output": "{\n\treturn d.readChan\n}"} {"input": "package land\n\nimport (\n\t\"context\"\n\t\"os\"\n\n\t\"code.cloudfoundry.org/lager\"\n\t\"code.cloudfoundry.org/lager/lagerctx\"\n\t\"github.com/concourse/concourse/atc\"\n\t\"github.com/concourse/concourse/worker\"\n)\n\ntype LandWorkerCommand struct {\n\tTSA worker.TSAConfig `group:\"TSA Configuration\" namespace:\"tsa\" required:\"true\"`\n\n\tWorkerName string `long:\"name\" required:\"true\" description:\"The name of the worker you wish to land.\"`\n}\n\n\n\nfunc (cmd *LandWorkerCommand) Execute(args []string) error ", "output": "{\n\tlogger := lager.NewLogger(\"land-worker\")\n\tlogger.RegisterSink(lager.NewPrettySink(os.Stdout, lager.DEBUG))\n\n\tclient := cmd.TSA.Client(atc.Worker{\n\t\tName: cmd.WorkerName,\n\t})\n\n\treturn client.Land(lagerctx.NewContext(context.Background(), logger))\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gossamer-irc/lib\"\n\t\"strings\"\n)\n\ntype PendingClient struct {\n\tIrcd *Ircd\n\tConn *IrcConnection\n\tSubnet *lib.Subnet\n\tNick string\n\tIdent string\n\tGecos string\n\tHost string\n}\n\nfunc NewPendingClient(ircd *Ircd, conn *IrcConnection, subnet *lib.Subnet, host string) *PendingClient {\n\treturn &PendingClient{\n\t\tIrcd: ircd,\n\t\tSubnet: subnet,\n\t\tConn: conn,\n\t\tHost: host,\n\t}\n}\n\nfunc (pc *PendingClient) Handle(raw IrcClientMessage) {\n\tswitch msg := raw.(type) {\n\tcase *InvalidIrcClientMessage:\n\t\tbreak\n\tcase *NickIrcClientMessage:\n\t\tlnick := strings.ToLower(msg.Nick)\n\t\t_, found := pc.Subnet.Client[lnick]\n\t\tif found {\n\t\t\tpc.Conn.Send(&IrcNickInUse{msg.Nick})\n\t\t\treturn\n\t\t}\n\t\tpc.Nick = msg.Nick\n\t\tpc.CheckReady()\n\t\tbreak\n\tcase *UserIrcClientMessage:\n\t\tpc.Ident = msg.Ident\n\t\tpc.Gecos = msg.Gecos\n\t\tpc.CheckReady()\n\t\tbreak\n\t}\n}\n\n\n\nfunc (pc *PendingClient) CheckReady() ", "output": "{\n\tif pc.Nick == \"\" || pc.Ident == \"\" || pc.Gecos == \"\" {\n\t\treturn\n\t}\n\tlnick := strings.ToLower(pc.Nick)\n\t_, found := pc.Subnet.Client[lnick]\n\tif found {\n\t\tpc.Conn.Send(&IrcNickInUse{pc.Nick})\n\t\tpc.Nick = \"\"\n\t\treturn\n\t}\n\tpc.Ircd.AcceptPendingClient(pc)\n}"} {"input": "package like\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go-common/app/interface/main/activity/model/like\"\n\t\"go-common/library/cache/memcache\"\n\t\"go-common/library/log\"\n)\n\nconst (\n\t_prefixInfo = \"m_\"\n)\n\n\n\n\nfunc (dao *Dao) SetInfoCache(c context.Context, v *like.Subject, sid int64) (err error) {\n\tif v == nil {\n\t\tv = &like.Subject{}\n\t}\n\tvar (\n\t\tconn = dao.mc.Get(c)\n\t\tmckey = keyInfo(sid)\n\t)\n\tdefer conn.Close()\n\tif err = conn.Set(&memcache.Item{Key: mckey, Object: v, Flags: memcache.FlagGOB, Expiration: dao.mcLikeExpire}); err != nil {\n\t\tlog.Error(\"conn.Set error(%v)\", err)\n\t\treturn\n\t}\n\treturn\n}\n\n\nfunc (dao *Dao) InfoCache(c context.Context, sid int64) (v *like.Subject, err error) {\n\tvar (\n\t\tmckey = keyInfo(sid)\n\t\tconn = dao.mc.Get(c)\n\t\titem *memcache.Item\n\t)\n\tdefer conn.Close()\n\tif item, err = conn.Get(mckey); err != nil {\n\t\tif err == memcache.ErrNotFound {\n\t\t\terr = nil\n\t\t\tv = nil\n\t\t} else {\n\t\t\tlog.Error(\"conn.Get error(%v)\", err)\n\t\t}\n\t\treturn\n\t}\n\tif err = conn.Scan(item, &v); err != nil {\n\t\tlog.Error(\"item.Scan error(%v)\", err)\n\t\treturn\n\t}\n\treturn\n}\n\nfunc keyInfo(sid int64) string ", "output": "{\n\treturn fmt.Sprintf(\"%s%d\", _prefixInfo, sid)\n}"} {"input": "package character\n\ntype Histogram struct {\n\tcounts [256]uint16\n}\n\nfunc StringHistogram(text string) *Histogram {\n\thistogram := &Histogram{}\n\tfor i := 0; i < len(text); i++ {\n\t\thistogram.Add(Char(text[i]))\n\t}\n\treturn histogram\n}\n\nfunc (h *Histogram) Add(char Char) {\n\th.counts[char]++\n}\n\n\n\nfunc (h *Histogram) Count(char Char) int ", "output": "{\n\treturn int(h.counts[char])\n}"} {"input": "package dhcpv6\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/u-root/uio/uio\"\n)\n\n\n\n\ntype optRelayPort struct {\n\tDownstreamSourcePort uint16\n}\n\nfunc (op *optRelayPort) Code() OptionCode {\n\treturn OptionRelayPort\n}\n\nfunc (op *optRelayPort) ToBytes() []byte {\n\tbuf := uio.NewBigEndianBuffer(nil)\n\tbuf.Write16(op.DownstreamSourcePort)\n\treturn buf.Data()\n}\n\nfunc (op *optRelayPort) String() string {\n\treturn fmt.Sprintf(\"RelayPort: %d\", op.DownstreamSourcePort)\n}\n\n\n\nfunc parseOptRelayPort(data []byte) (*optRelayPort, error) {\n\tvar opt optRelayPort\n\tbuf := uio.NewBigEndianBuffer(data)\n\topt.DownstreamSourcePort = buf.Read16()\n\treturn &opt, buf.FinError()\n}\n\nfunc OptRelayPort(port uint16) Option ", "output": "{\n\treturn &optRelayPort{DownstreamSourcePort: port}\n}"} {"input": "package lib\n\n\n\nfunc cacheHintTagList(repository string) string {\n\treturn \"pull:\" + repository\n}\n\nfunc cacheHintTagDetails(repository string) string {\n\treturn \"pull:\" + repository\n}\n\nfunc cacheHintRegistryList() string ", "output": "{\n\treturn \"catalog:\"\n}"} {"input": "package vpki\n\nimport (\n\t\"crypto/tls\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype certCache struct {\n\tm map[string]*tls.Certificate\n\tmut *sync.RWMutex\n\tcrt Certifier\n\tttl time.Duration\n}\n\nfunc newCertCache(crt Certifier) *certCache {\n\treturn &certCache{\n\t\tm: map[string]*tls.Certificate{},\n\t\tmut: &sync.RWMutex{},\n\t\tcrt: crt,\n\t\tttl: DefaultTTL,\n\t}\n}\n\nfunc (cc *certCache) add(name string) (*tls.Certificate, error) {\n\tcrt, err := cc.crt.Cert(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcc.mut.Lock()\n\tcc.m[name] = crt\n\tcc.mut.Unlock()\n\treturn crt, nil\n}\n\n\n\nfunc (cc *certCache) get(name string) (*tls.Certificate, error) ", "output": "{\n\tlkr := cc.mut.RLocker()\n\tlkr.Lock()\n\n\tif c, ok := cc.m[name]; ok {\n\t\tn := time.Now()\n\t\tif n.After(c.Leaf.NotBefore) && n.Before(c.Leaf.NotAfter) {\n\t\t\tlkr.Unlock()\n\t\t\treturn c, nil\n\t\t}\n\t}\n\tlkr.Unlock()\n\n\treturn cc.add(name)\n}"} {"input": "package fake_cmdpreparer\n\nimport (\n\t\"os/exec\"\n\t\"sync\"\n\n\t\"code.cloudfoundry.org/garden\"\n\t\"code.cloudfoundry.org/garden-linux/container_daemon\"\n)\n\ntype FakeCmdPreparer struct {\n\tPrepareCmdStub func(garden.ProcessSpec) (*exec.Cmd, error)\n\tprepareCmdMutex sync.RWMutex\n\tprepareCmdArgsForCall []struct {\n\t\targ1 garden.ProcessSpec\n\t}\n\tprepareCmdReturns struct {\n\t\tresult1 *exec.Cmd\n\t\tresult2 error\n\t}\n}\n\nfunc (fake *FakeCmdPreparer) PrepareCmd(arg1 garden.ProcessSpec) (*exec.Cmd, error) {\n\tfake.prepareCmdMutex.Lock()\n\tfake.prepareCmdArgsForCall = append(fake.prepareCmdArgsForCall, struct {\n\t\targ1 garden.ProcessSpec\n\t}{arg1})\n\tfake.prepareCmdMutex.Unlock()\n\tif fake.PrepareCmdStub != nil {\n\t\treturn fake.PrepareCmdStub(arg1)\n\t} else {\n\t\treturn fake.prepareCmdReturns.result1, fake.prepareCmdReturns.result2\n\t}\n}\n\nfunc (fake *FakeCmdPreparer) PrepareCmdCallCount() int {\n\tfake.prepareCmdMutex.RLock()\n\tdefer fake.prepareCmdMutex.RUnlock()\n\treturn len(fake.prepareCmdArgsForCall)\n}\n\n\n\nfunc (fake *FakeCmdPreparer) PrepareCmdReturns(result1 *exec.Cmd, result2 error) {\n\tfake.PrepareCmdStub = nil\n\tfake.prepareCmdReturns = struct {\n\t\tresult1 *exec.Cmd\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nvar _ container_daemon.CmdPreparer = new(FakeCmdPreparer)\n\nfunc (fake *FakeCmdPreparer) PrepareCmdArgsForCall(i int) garden.ProcessSpec ", "output": "{\n\tfake.prepareCmdMutex.RLock()\n\tdefer fake.prepareCmdMutex.RUnlock()\n\treturn fake.prepareCmdArgsForCall[i].arg1\n}"} {"input": "package aviasales\n\ntype Alliance struct {\n\tName string `json:\"name\" bson:\"name\"`\n\tAirlines []string `json:\"alias\" bson:\"alias\"`\n}\n\n\n\n\n\n\n\n\n\n\nfunc (a *AviasalesApi) DataAirlinesAlliances() (airlinesAlliances []Alliance, err error) ", "output": "{\n\terr = a.getJson(\"data/airlines_alliances.json\", map[string]string{}, &airlinesAlliances)\n\treturn\n}"} {"input": "package v1\n\nimport (\n\t\"github.com/ertgl/croncache\"\n)\n\n\n\nfunc init() ", "output": "{\n\terr := croncache.TaskManagerRepository().Register(MODULE_NAME, Generator)\n\tif err != nil {\n\t\tcroncache.HandleFatalError(err)\n\t}\n}"} {"input": "package cgotest\n\n\nimport \"C\"\n\nimport \"testing\"\nimport \"time\"\n\n\n\nfunc test6997(t *testing.T) ", "output": "{\n\tr := C.StartThread()\n\tif r != 0 {\n\t\tt.Error(\"pthread_create failed\")\n\t}\n\tc := make(chan C.int)\n\tgo func() {\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\tc <- C.CancelThread()\n\t}()\n\n\tselect {\n\tcase r = <-c:\n\t\tif r == 0 {\n\t\t\tt.Error(\"pthread finished but wasn't cancelled??\")\n\t\t}\n\tcase <-time.After(30 * time.Second):\n\t\tt.Error(\"hung in pthread_cancel/pthread_join\")\n\t}\n}"} {"input": "package watch\n\n\n\ntype FilterFunc func(in Event) (out Event, keep bool)\n\n\n\n\n\n\n\n\n\n\n\n\ntype filteredWatch struct {\n\tincoming Interface\n\tresult chan Event\n\tf FilterFunc\n}\n\n\nfunc (fw *filteredWatch) ResultChan() <-chan Event {\n\treturn fw.result\n}\n\n\nfunc (fw *filteredWatch) Stop() {\n\tfw.incoming.Stop()\n}\n\n\nfunc (fw *filteredWatch) loop() {\n\tdefer close(fw.result)\n\tfor {\n\t\tevent, ok := <-fw.incoming.ResultChan()\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tfiltered, keep := fw.f(event)\n\t\tif keep {\n\t\t\tfw.result <- filtered\n\t\t}\n\t}\n}\n\nfunc Filter(w Interface, f FilterFunc) Interface ", "output": "{\n\tfw := &filteredWatch{\n\t\tincoming: w,\n\t\tresult: make(chan Event),\n\t\tf: f,\n\t}\n\tgo fw.loop()\n\treturn fw\n}"} {"input": "package sql\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cockroachdb/cockroach/sql/parser\"\n)\n\n\nfunc (p *planner) Values(n parser.Values) (planNode, error) {\n\tv := &valuesNode{\n\t\trows: make([]parser.DTuple, 0, len(n)),\n\t}\n\tfor _, tuple := range n {\n\t\tdata, err := parser.EvalExpr(tuple, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvals, ok := data.(parser.DTuple)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"expected a tuple, but found %T\", data)\n\t\t}\n\t\tv.rows = append(v.rows, vals)\n\t}\n\treturn v, nil\n}\n\ntype valuesNode struct {\n\tcolumns []string\n\trows []parser.DTuple\n\tnextRow int \n}\n\nfunc (n *valuesNode) Columns() []string {\n\treturn n.columns\n}\n\nfunc (n *valuesNode) Values() parser.DTuple {\n\treturn n.rows[n.nextRow-1]\n}\n\n\n\nfunc (*valuesNode) Err() error {\n\treturn nil\n}\n\nfunc (n *valuesNode) Next() bool ", "output": "{\n\tif n.nextRow >= len(n.rows) {\n\t\treturn false\n\t}\n\tn.nextRow++\n\treturn true\n}"} {"input": "package v1\n\nimport (\n\tdataService \"github.com/tidepool-org/platform/data/service\"\n\t\"github.com/tidepool-org/platform/request\"\n\t\"github.com/tidepool-org/platform/service\"\n)\n\n\n\nfunc Authenticate(handler dataService.HandlerFunc) dataService.HandlerFunc ", "output": "{\n\treturn func(context dataService.Context) {\n\t\tif details := request.DetailsFromContext(context.Request().Context()); details == nil {\n\t\t\tcontext.RespondWithError(service.ErrorUnauthenticated())\n\t\t\treturn\n\t\t}\n\n\t\thandler(context)\n\t}\n}"} {"input": "package testing\n\nimport \"k8s.io/kubernetes/pkg/util/iptables\"\n\n\ntype fake struct{}\n\nfunc NewFake() *fake {\n\treturn &fake{}\n}\n\nfunc (*fake) EnsureChain(table iptables.Table, chain iptables.Chain) (bool, error) {\n\treturn true, nil\n}\n\nfunc (*fake) FlushChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) DeleteChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) EnsureRule(position iptables.RulePosition, table iptables.Table, chain iptables.Chain, args ...string) (bool, error) {\n\treturn true, nil\n}\n\nfunc (*fake) DeleteRule(table iptables.Table, chain iptables.Chain, args ...string) error {\n\treturn nil\n}\n\nfunc (*fake) IsIpv6() bool {\n\treturn false\n}\n\n\n\nfunc (*fake) SaveAll() ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\nfunc (*fake) Restore(table iptables.Table, data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\n\nfunc (*fake) RestoreAll(data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\nfunc (*fake) AddReloadFunc(reloadFunc func()) {}\n\nfunc (*fake) Destroy() {}\n\nvar _ = iptables.Interface(&fake{})\n\nfunc (*fake) Save(table iptables.Table) ([]byte, error) ", "output": "{\n\treturn make([]byte, 0), nil\n}"} {"input": "package process\n\nimport (\n\t\"net\"\n\t\"strconv\"\n)\n\nconst (\n\tMIN_PORT = 50000\n\tMAX_PORT = 60000\n\tINVALID_PORT = -1\n)\n\n\nfunc GetAvailablePort() (int, bool) {\n\tfor port := MIN_PORT; port <= MAX_PORT; port++ {\n\t\tif !isPortUsed(port) {\n\t\t\treturn port, true\n\t\t}\n\t}\n\n\treturn INVALID_PORT, false\n}\n\n\n\n\nfunc isPortUsed(port int) bool ", "output": "{\n\tconn, err := net.Dial(\"tcp\", net.JoinHostPort(\"localhost\", strconv.Itoa(port)))\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tdefer conn.Close()\n\n\treturn true\n}"} {"input": "package lrucache\n\n\n\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestListMap_PushBack(t *testing.T) {\n\tm := NewListMap()\n\n\tt1 := time.Now().Nanosecond()\n\tt2 := time.Now().Nanosecond()\n\tm.PushBack(1, t1)\n\tm.PushFront(2, t2)\n\n\tv, _ := m.Get(1)\n\tassert.Equal(t, t1, v)\n\n\tv1, _ := m.Back()\n\tv2, _ := m.Front()\n\tassert.Equal(t, t1, v1)\n\tassert.Equal(t, t2, v2)\n\tassert.Equal(t, 2, m.Len())\n}\n\nfunc TestListMap_PopFront(t *testing.T) {\n\tm := NewListMap()\n\n\tt1 := time.Now().Nanosecond()\n\tt2 := time.Now().Nanosecond()\n\tm.PushBack(1, t1)\n\tm.PushFront(2, t2)\n\n\tv, _ := m.PopFront()\n\tassert.Equal(t, t2, v)\n\n\tv, _ = m.Front()\n\tassert.Equal(t, t1, v)\n\tassert.Equal(t, 1, m.Len())\n\n\tm.PopFront()\n\tm.PopFront()\n\tassert.Equal(t, 0, m.Len())\n}\n\n\n\nfunc TestListMap_MoveToFront(t *testing.T) ", "output": "{\n\tm := NewListMap()\n\n\tt1 := time.Now().Nanosecond()\n\tt2 := time.Now().Nanosecond()\n\tm.PushBack(1, t1)\n\tm.PushFront(2, t2)\n\n\tm.MoveToFront(1)\n\n\tv1, _ := m.Back()\n\tv2, _ := m.Front()\n\tassert.Equal(t, t2, v1)\n\tassert.Equal(t, t1, v2)\n}"} {"input": "package storage\n\nimport (\n\t\"fmt\"\n\t\"github.com/apigee-labs/transicator/common\"\n\t\"strings\"\n)\n\n\nconst (\n\tEntryComparatorName = \"transicator-entries-v1\"\n\tSequenceComparatorName = \"transicator-sequence-v1\"\n)\n\nvar entryComparator = new(entryCmp)\nvar sequenceComparator = new(sequenceCmp)\n\ntype entryCmp struct {\n}\n\n\n\n\n\nfunc (c entryCmp) Name() string {\n\treturn EntryComparatorName\n}\n\ntype sequenceCmp struct {\n}\n\nfunc (s sequenceCmp) Compare(a, b []byte) int {\n\ts1, err := common.ParseSequenceBytes(a)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error parsing sequence: %s\", err))\n\t}\n\ts2, err := common.ParseSequenceBytes(b)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error parsing sequence: %s\", err))\n\t}\n\n\treturn s1.Compare(s2)\n}\n\nfunc (s sequenceCmp) Name() string {\n\treturn SequenceComparatorName\n}\n\nfunc (c entryCmp) Compare(a, b []byte) int ", "output": "{\n\taScope, aLsn, aIndex, err := keyToLsnAndOffset(a)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error parsing database key: %s\", err))\n\t}\n\tbScope, bLsn, bIndex, err := keyToLsnAndOffset(b)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error parsing database key: %s\", err))\n\t}\n\n\tscopeCmp := strings.Compare(aScope, bScope)\n\tif scopeCmp == 0 {\n\t\tif aLsn < bLsn {\n\t\t\treturn -1\n\t\t} else if aLsn > bLsn {\n\t\t\treturn 1\n\t\t}\n\n\t\tif aIndex < bIndex {\n\t\t\treturn -1\n\t\t} else if aIndex > bIndex {\n\t\t\treturn 1\n\t\t}\n\t\treturn 0\n\t}\n\treturn scopeCmp\n}"} {"input": "package merkledag\n\nimport (\n\t\"context\"\n\n\tcid \"gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid\"\n\tipld \"gx/ipfs/QmR7TcHkR9nxkUorfi8XMTAMLUK7GiP64TWWBzY3aacc1o/go-ipld-format\"\n)\n\n\ntype ErrorService struct {\n\tErr error\n}\n\nvar _ ipld.DAGService = (*ErrorService)(nil)\n\n\nfunc (cs *ErrorService) Add(ctx context.Context, nd ipld.Node) error {\n\treturn cs.Err\n}\n\n\nfunc (cs *ErrorService) AddMany(ctx context.Context, nds []ipld.Node) error {\n\treturn cs.Err\n}\n\n\nfunc (cs *ErrorService) Get(ctx context.Context, c cid.Cid) (ipld.Node, error) {\n\treturn nil, cs.Err\n}\n\n\n\n\n\nfunc (cs *ErrorService) Remove(ctx context.Context, c cid.Cid) error {\n\treturn cs.Err\n}\n\n\nfunc (cs *ErrorService) RemoveMany(ctx context.Context, cids []cid.Cid) error {\n\treturn cs.Err\n}\n\nfunc (cs *ErrorService) GetMany(ctx context.Context, cids []cid.Cid) <-chan *ipld.NodeOption ", "output": "{\n\tch := make(chan *ipld.NodeOption)\n\tclose(ch)\n\treturn ch\n}"} {"input": "package models\n\nimport (\n\t\"database/sql\"\n\t\"github.com/BrandonRomano/serf\"\n\tdb \"github.com/carrot/burrow/db/postgres\"\n\t\"time\"\n)\n\ntype Topic struct {\n\tserf.Worker `json:\"-\"`\n\tId int64 `json:\"id\"`\n\tName string `json:\"name\"`\n\tCreatedAt time.Time `json:\"created_at\"`\n\tUpdatedAt time.Time `json:\"updated_at\"`\n}\n\nfunc NewTopic() *Topic {\n\ttopic := new(Topic)\n\treturn topic.Prep()\n}\n\n\n\nfunc AllTopics(limit int64, offset int64) ([]Topic, error) {\n\tdatabase := db.Get()\n\trows, err := database.Query(\"SELECT * FROM topics ORDER BY created_at LIMIT $1 OFFSET $2\", limit, offset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tvar topics []Topic = []Topic{}\n\tfor rows.Next() {\n\t\tt := new(Topic)\n\t\terr = t.consumeNextRow(rows)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttopics = append(topics, *t)\n\t}\n\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn topics, nil\n}\n\nfunc (t *Topic) consumeNextRow(rows *sql.Rows) error {\n\treturn rows.Scan(\n\t\t&t.Id,\n\t\t&t.Name,\n\t\t&t.CreatedAt,\n\t\t&t.UpdatedAt,\n\t)\n}\n\nfunc (t *Topic) Prep() *Topic ", "output": "{\n\tt.Worker = &serf.PqWorker{\n\t\tDatabase: db.Get(),\n\t\tConfig: serf.Configuration{\n\t\t\tTableName: \"topics\",\n\t\t\tFields: []serf.Field{\n\t\t\t\tserf.Field{Pointer: &t.Id, Name: \"id\", UniqueIdentifier: true,\n\t\t\t\t\tIsSet: func(pointer interface{}) bool {\n\t\t\t\t\t\tpointerInt := *pointer.(*int64)\n\t\t\t\t\t\treturn pointerInt != 0\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tserf.Field{Pointer: &t.Name, Name: \"name\", Insertable: true, Updatable: true},\n\t\t\t\tserf.Field{Pointer: &t.CreatedAt, Name: \"created_at\"},\n\t\t\t\tserf.Field{Pointer: &t.UpdatedAt, Name: \"updated_at\"},\n\t\t\t},\n\t\t},\n\t}\n\treturn t\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\ntype CommonTests struct {\n\tout *bytes.Buffer\n\td *Dispatcher\n}\n\nvar _ = Suite(&CommonTests{})\n\nfunc (t *CommonTests) SetUpTest(c *C) {\n\tt.out = new(bytes.Buffer)\n\tt.d = &Dispatcher{stderr: t.out}\n}\n\n\n\nfunc removeFilesInDir(dir string) error ", "output": "{\n\tfiles, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, file := range files {\n\t\tpath := filepath.Join(dir, file.Name())\n\t\terr = os.Remove(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc main() {\n\tsc := bufio.NewScanner(os.Stdin)\n\tsc.Split(bufio.ScanWords)\n\tn := nextInt(sc)\n\ta := nextInt(sc)\n\tb := nextInt(sc)\n\n\tanswer := 0\n\tfor i := 1; i <= n; i++ {\n\t\tsum := 0\n\t\tfor _, s := range fmt.Sprintf(\"%d\", i) {\n\t\t\tx, _ := strconv.Atoi(string(s))\n\t\t\tsum = sum + x\n\t\t}\n\t\tif a <= sum && sum <= b {\n\t\t\tanswer = answer + i\n\t\t}\n\t}\n\n\tfmt.Println(answer)\n}\n\n\n\nfunc nextString(sc *bufio.Scanner) string {\n\tsc.Scan()\n\treturn sc.Text()\n}\n\nfunc nextNumber(sc *bufio.Scanner) float64 {\n\tsc.Scan()\n\tf, err := strconv.ParseFloat(sc.Text(), 32)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}\n\nfunc nextInt(sc *bufio.Scanner) int {\n\tsc.Scan()\n\tn, err := strconv.Atoi(sc.Text())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn n\n}\n\nfunc printArray(xs []int) {\n\tfmt.Println(strings.Trim(fmt.Sprint(xs), \"[]\"))\n}\n\n\n\nfunc debugPrintf(format string, a ...interface{}) ", "output": "{\n\tfmt.Fprintf(os.Stderr, format, a...)\n}"} {"input": "package models\n\nimport (\n\t\"sync\"\n\n\t\"github.com/eaciit/orm\"\n)\n\ntype FuelTransport struct {\n\tsync.RWMutex\n\torm.ModelBase `bson:\"-\" json:\"-\"`\n\tPlant string `bson:\"Plant\" json:\"Plant\"`\n\tYear int `bson:\"Year\" json:\"Year\"`\n\tTransportCost float64 `bson:\"TransportCost\" json:\"TransportCost\"`\n}\n\n\n\nfunc (m *FuelTransport) TableName() string ", "output": "{\n\treturn \"FuelTransport\"\n}"} {"input": "package models\n\nimport (\n\t\"crawshaw.io/sqlite\"\n\t\"xorm.io/builder\"\n\titchio \"github.com/itchio/go-itchio\"\n\t\"github.com/itchio/hades\"\n)\n\n\ntype ProfileGame struct {\n\tGameID int64 `json:\"gameId\" hades:\"primary_key\"`\n\tGame *itchio.Game `json:\"game,omitempty\"`\n\n\tProfileID int64 `json:\"profileId\" hades:\"primary_key\"`\n\tProfile *Profile `json:\"profile,omitempty\"`\n\n\tPosition int64 `json:\"position\"`\n\n\n\tViewsCount int64 `json:\"viewsCount\"`\n\tDownloadsCount int64 `json:\"downloadsCount\"`\n\tPurchasesCount int64 `json:\"purchasesCount\"`\n\n\tPublished bool `json:\"published\"`\n}\n\n\n\nfunc ProfileGamesByGameID(conn *sqlite.Conn, gameID int64) []*ProfileGame ", "output": "{\n\tvar pgs []*ProfileGame\n\tMustSelect(conn, &pgs, builder.Eq{\"game_id\": gameID}, hades.Search{})\n\treturn pgs\n}"} {"input": "package kernel \n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\n\nfunc GetKernelVersion() (*VersionInfo, error) {\n\tosName, err := getSPSoftwareDataType()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trelease, err := getRelease(osName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseRelease(release)\n}\n\n\n\n\nfunc getSPSoftwareDataType() (string, error) {\n\tcmd := exec.Command(\"system_profiler\", \"SPSoftwareDataType\")\n\tosName, err := cmd.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(osName), nil\n}\n\nfunc getRelease(osName string) (string, error) ", "output": "{\n\tvar release string\n\tdata := strings.Split(osName, \"\\n\")\n\tfor _, line := range data {\n\t\tif !strings.Contains(line, \"Kernel Version\") {\n\t\t\tcontinue\n\t\t}\n\t\tcontent := strings.SplitN(line, \":\", 2)\n\t\tif len(content) != 2 {\n\t\t\treturn \"\", fmt.Errorf(\"Kernel Version is invalid\")\n\t\t}\n\n\t\tprettyNames := strings.SplitN(strings.TrimSpace(content[1]), \" \", 2)\n\n\t\tif len(prettyNames) != 2 {\n\t\t\treturn \"\", fmt.Errorf(\"Kernel Version needs to be 'Darwin x.x.x' \")\n\t\t}\n\t\trelease = prettyNames[1]\n\t}\n\n\treturn release, nil\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/user\"\n\t\"strconv\"\n)\n\n\n\nfunc mkdir(paths []string) error {\n\tfor _, path := range paths {\n\t\terr := os.MkdirAll(path, os.ModePerm)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Make directory failed: %s\\n\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc chown(paths []string, userName string, groupName string) error {\n\tuserId, err := GetUserId(userName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgroupId, err := getGroupId(groupName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, path := range paths {\n\t\terr := os.Chown(path, userId, groupId)\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Chown failed: %s\\n\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc GetUserId(userName string) (int, error) {\n\tu, err := user.Lookup(userName)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to obtain UID: %s\\n\", err)\n\t\treturn -1, err\n\t}\n\n\tuserId, _ := strconv.Atoi(u.Uid)\n\n\treturn userId, nil\n}\n\nfunc getGroupId(groupName string) (int, error) {\n\tg, err := user.LookupGroup(groupName)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to obtain GID: %s\\n\", err)\n\t\treturn -1, err\n\t}\n\n\tgroupId, _ := strconv.Atoi(g.Gid)\n\n\treturn groupId, nil\n}\n\nfunc CreateVcapDirs(paths []string, userName string, groupName string) error ", "output": "{\n\terr := mkdir(paths)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = chown(paths, userName, groupName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\ntype SendPhotoLinkBody struct {\n\n\tCaption string `json:\"caption,omitempty\"`\n\n\tChatID interface{} `json:\"chat_id\"`\n\n\tDisableNotification bool `json:\"disable_notification,omitempty\"`\n\n\tPhoto *string `json:\"photo\"`\n\n\tReplyMarkup interface{} `json:\"reply_markup,omitempty\"`\n\n\tReplyToMessageID int64 `json:\"reply_to_message_id,omitempty\"`\n}\n\n\nfunc (m *SendPhotoLinkBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateChatID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePhoto(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (m *SendPhotoLinkBody) validateChatID(formats strfmt.Registry) error {\n\n\treturn nil\n}\n\nfunc (m *SendPhotoLinkBody) validatePhoto(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"photo\", \"body\", m.Photo); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc (m *SendPhotoLinkBody) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\n\n\nfunc (m *SendPhotoLinkBody) UnmarshalBinary(b []byte) error ", "output": "{\n\tvar res SendPhotoLinkBody\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"reflect\"\n)\n\ntype User struct{\n Id int\n Name string\n Age int\n}\n\nfunc (u User) Hello(){\n fmt.Println(\"Hello World.\")\n}\n\nfunc main(){\n var u User\n u = User{1, \"ok\", 12}\n info(u)\n}\n\n\n\nfunc info(o interface{})", "output": "{\n t := reflect.TypeOf(o)\n fmt.Println(\"Type:\", t.Name())\n\n v := reflect.ValueOf(o)\n fmt.Println(\"Fields:\")\n\n for i:= 0; i < t.NumField(); i++{\n f := t.Field(i)\n val := v.Field(i).Interface()\n fmt.Printf(\"%6s: %v = %v\\n\", f.Name, f.Type, val)\n }\n \n for i:= 0; i < t.NumMethod(); i++{\n m := t.Method(i)\n fmt.Printf(\"%6s: %v\\n\", m.Name)\n }\n}"} {"input": "package utils\n\nimport (\n\t\"runtime\"\n\t\"strings\"\n)\n\n\n\nfunc GetTraceback() string ", "output": "{\n\ttb := make([]byte, 4096)\n\tstb := string(tb[:runtime.Stack(tb, false)])\n\tlines := strings.Split(stb, \"\\n\")\n\tfor i := range lines {\n\t\tif strings.Contains(lines[i], \"ServeHTTP\") {\n\t\t\treturn strings.Join(lines[4:i], \"\\n\")\n\t\t}\n\t}\n\treturn stb\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/devfeel/dotweb\"\n\t\"github.com/devfeel/dotweb/cache\"\n\t\"github.com/devfeel/dotweb/framework/file\"\n\t\"strconv\"\n)\n\nfunc main() {\n\tapp := dotweb.New()\n\n\tapp.SetLogPath(file.GetCurrentDirectory())\n\n\n\tInitRoute(app.HttpServer)\n\n\n\tapp.SetCache(cache.NewRuntimeCache())\n\n\terr := app.Cache().Set(\"g\", \"gv\", 20)\n\tif err != nil {\n\t\tfmt.Println(\"Cache Set \", err)\n\t}\n\n\tport := 8080\n\tfmt.Println(\"dotweb.StartServer => \" + strconv.Itoa(port))\n\terr = app.StartServer(port)\n\tfmt.Println(\"dotweb.StartServer error => \", err)\n}\n\ntype UserInfo struct {\n\tUserName string\n\tSex int\n}\n\nfunc One(ctx dotweb.Context) error {\n\tg, err := ctx.Cache().GetString(\"g\")\n\tif err != nil {\n\t\tg = err.Error()\n\t}\n\t_, err = ctx.Cache().Incr(\"count\")\n\treturn ctx.WriteString(\"One [\" + g + \"] \" + fmt.Sprint(err))\n}\n\n\n\nfunc InitRoute(server *dotweb.HttpServer) {\n\tserver.Router().GET(\"/1\", One)\n\tserver.Router().GET(\"/2\", Two)\n}\n\nfunc Two(ctx dotweb.Context) error ", "output": "{\n\tg, err := ctx.Cache().GetString(\"g\")\n\tif err != nil {\n\t\tg = err.Error()\n\t}\n\t_, err = ctx.Cache().Incr(\"count\")\n\tc, _ := ctx.Cache().GetString(\"count\")\n\treturn ctx.WriteString(\"Two [\" + g + \"] [\" + c + \"] \" + fmt.Sprint(err))\n}"} {"input": "package wire_test\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader ", "output": "{\n\tb := make([]byte, max, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/runtime/serializer/json\"\n\tauditinstall \"k8s.io/apiserver/pkg/apis/audit/install\"\n\tauditv1 \"k8s.io/apiserver/pkg/apis/audit/v1\"\n\t\"k8s.io/apiserver/pkg/audit\"\n)\n\nvar (\n\tencoder runtime.Encoder\n\tdecoder runtime.Decoder\n)\n\nfunc main() {\n\tscheme := runtime.NewScheme()\n\tauditinstall.Install(scheme)\n\tserializer := json.NewSerializer(json.DefaultMetaFactory, scheme, scheme, false)\n\tencoder = audit.Codecs.EncoderForVersion(serializer, auditv1.SchemeGroupVersion)\n\tdecoder = audit.Codecs.UniversalDecoder(auditv1.SchemeGroupVersion)\n\n\thttp.HandleFunc(\"/\", handler)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\n\n\nfunc handler(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tbody, err := ioutil.ReadAll(req.Body)\n\tif err != nil {\n\t\tlog.Printf(\"could not read request body: %v\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tel := &auditv1.EventList{}\n\n\tif err := runtime.DecodeInto(decoder, body, el); err != nil {\n\t\tlog.Printf(\"failed decoding buf: %b, apiVersion: %s\", body, auditv1.SchemeGroupVersion)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer req.Body.Close()\n\n\tfor _, event := range el.Items {\n\t\terr := encoder.Encode(&event, os.Stdout)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"could not encode audit event: %v\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\tw.WriteHeader(http.StatusOK)\n}"} {"input": "package database\n\nimport \"database/sql\"\n\nvar db *sql.DB\n\n\nfunc OpenDB() {\n\topenSQLite()\n}\n\n\n\n\n\nfunc Query(s string, args ...interface{}) (*sql.Rows, error) {\n\trows, err := db.Query(s, args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rows, nil\n}\n\n\nfunc Exec(s string, args ...interface{}) (sql.Result, error) {\n\tres, err := db.Exec(s, args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}\n\nfunc openSQLite() ", "output": "{\n\tvar err error\n\tdb, err = sql.Open(\"sqlite3\", \"adnalerts.db?loc.auto\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"time\"\n)\n\n\n\nfunc read2(path string) string {\n\tfi, err := os.Open(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer fi.Close()\n\tr := bufio.NewReader(fi)\n\n\tchunks := make([]byte, 1024, 1024)\n\n\tbuf := make([]byte, 1024)\n\tfor {\n\t\tn, err := r.Read(buf)\n\t\tif err != nil && err != io.EOF {\n\t\t\tpanic(err)\n\t\t}\n\t\tif 0 == n {\n\t\t\tbreak\n\t\t}\n\t\tchunks = append(chunks, buf[:n]...)\n\t}\n\treturn string(chunks)\n}\n\nfunc read3(path string) string {\n\tfi, err := os.Open(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer fi.Close()\n\tfd, err := ioutil.ReadAll(fi)\n\treturn string(fd)\n}\n\nfunc main() {\n\tflag.Parse()\n\tfile := flag.Arg(0)\n\n\tf, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tfmt.Printf(\"%s\\n\", err)\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(string(f))\n\tstart := time.Now()\n\tread3(file)\n\tt1 := time.Now()\n\tfmt.Printf(\"Cost time %v\\n\", t1.Sub(start))\n\n\tread1(file)\n\tt2 := time.Now()\n\tfmt.Printf(\"Cost time %v\\n\", t2.Sub(t1))\n\n\tread2(file)\n\tt3 := time.Now()\n\tfmt.Printf(\"Cost time %v\\n\", t3.Sub(t2))\n}\n\nfunc read1(path string) string ", "output": "{\n\tfi, err := os.Open(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer fi.Close()\n\n\tchunks := make([]byte, 1024, 1024)\n\tbuf := make([]byte, 1024)\n\tfor {\n\t\tn, err := fi.Read(buf)\n\t\tif err != nil && err != io.EOF {\n\t\t\tpanic(err)\n\t\t}\n\t\tif 0 == n {\n\t\t\tbreak\n\t\t}\n\t\tchunks = append(chunks, buf[:n]...)\n\t}\n\treturn string(chunks)\n}"} {"input": "package segment\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/checkr/flagr/swagger_gen/models\"\n)\n\n\nconst DeleteSegmentOKCode int = 200\n\n\ntype DeleteSegmentOK struct {\n}\n\n\nfunc NewDeleteSegmentOK() *DeleteSegmentOK {\n\n\treturn &DeleteSegmentOK{}\n}\n\n\nfunc (o *DeleteSegmentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(200)\n}\n\n\ntype DeleteSegmentDefault struct {\n\t_statusCode int\n\n\tPayload *models.Error `json:\"body,omitempty\"`\n}\n\n\nfunc NewDeleteSegmentDefault(code int) *DeleteSegmentDefault {\n\tif code <= 0 {\n\t\tcode = 500\n\t}\n\n\treturn &DeleteSegmentDefault{\n\t\t_statusCode: code,\n\t}\n}\n\n\nfunc (o *DeleteSegmentDefault) WithStatusCode(code int) *DeleteSegmentDefault {\n\to._statusCode = code\n\treturn o\n}\n\n\nfunc (o *DeleteSegmentDefault) SetStatusCode(code int) {\n\to._statusCode = code\n}\n\n\n\n\n\nfunc (o *DeleteSegmentDefault) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}\n\n\nfunc (o *DeleteSegmentDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(o._statusCode)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\nfunc (o *DeleteSegmentDefault) WithPayload(payload *models.Error) *DeleteSegmentDefault ", "output": "{\n\to.Payload = payload\n\treturn o\n}"} {"input": "package dns\n\nimport (\n\t\"strings\"\n)\n\nconst etcHostsFile = \"C:/Windows/System32/drivers/etc/hosts\"\n\n\n\nfunc getDNSServerList() []string {\n\toutput := runCommand(\"powershell\", \"-Command\", \"(Get-DnsClientServerAddress).ServerAddresses\")\n\tif len(output) > 0 {\n\t\treturn strings.Split(output, \"\\r\\n\")\n\t}\n\n\tpanic(\"Could not find DNS Server list!\")\n}\n\nfunc getDNSSuffixList() []string ", "output": "{\n\toutput := runCommand(\"powershell\", \"-Command\", \"(Get-DnsClient)[0].SuffixSearchList\")\n\tif len(output) > 0 {\n\t\treturn strings.Split(output, \"\\r\\n\")\n\t}\n\n\tpanic(\"Could not find DNS search list!\")\n}"} {"input": "package iiif\n\nimport (\n\t\"strconv\"\n)\n\n\n\n\ntype Rotation struct {\n\tMirror bool\n\tDegrees float64\n}\n\n\n\n\nfunc StringToRotation(p string) Rotation {\n\tr := Rotation{}\n\tif p[0:1] == \"!\" {\n\t\tr.Mirror = true\n\t\tp = p[1:]\n\t}\n\n\tr.Degrees, _ = strconv.ParseFloat(p, 64)\n\n\tif r.Degrees == 360 {\n\t\tr.Degrees = 0\n\t}\n\n\treturn r\n}\n\n\n\n\n\nfunc (r Rotation) Valid() bool ", "output": "{\n\treturn r.Degrees >= 0 && r.Degrees < 360\n}"} {"input": "package math\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Ceil(x float64) float64 { return -Floor(-x) }\n\n\n\n\n\n\n\nfunc Trunc(x float64) float64 {\n\tif x == 0 || x != x || x > MaxFloat64 || x < -MaxFloat64 { \n\t\treturn x\n\t}\n\td, _ := Modf(x)\n\treturn d\n}\n\nfunc Floor(x float64) float64 ", "output": "{\n\tif x == 0 || x != x || x > MaxFloat64 || x < -MaxFloat64 { \n\t\treturn x\n\t}\n\tif x < 0 {\n\t\td, fract := Modf(-x)\n\t\tif fract != 0.0 {\n\t\t\td = d + 1\n\t\t}\n\t\treturn -d\n\t}\n\td, _ := Modf(x)\n\treturn d\n}"} {"input": "package ast\n\nimport (\n\t\"fmt\"\n\t\"github.com/rhysd/gocaml/token\"\n\t\"github.com/rhysd/locerr\"\n)\n\n\ntype printPath struct {\n\ttotal int\n}\n\n\nfunc (v *printPath) VisitTopdown(e Expr) Visitor {\n\tfmt.Printf(\"\\n -> %s (topdown)\", e.Name())\n\treturn v\n}\n\n\nfunc (v *printPath) VisitBottomup(e Expr) {\n\tfmt.Printf(\"\\n -> %s (bottomup)\", e.Name())\n}\n\n\n\nfunc Example() ", "output": "{\n\tsrc := locerr.NewDummySource(\"\")\n\n\trootOfAST := &Let{\n\t\tLetToken: &token.Token{File: src},\n\t\tSymbol: NewSymbol(\"test\"),\n\t\tBound: &Int{\n\t\t\tToken: &token.Token{File: src},\n\t\t\tValue: 42,\n\t\t},\n\t\tBody: &Add{\n\t\t\tLeft: &VarRef{\n\t\t\t\tToken: &token.Token{File: src},\n\t\t\t\tSymbol: NewSymbol(\"test\"),\n\t\t\t},\n\t\t\tRight: &Float{\n\t\t\t\tToken: &token.Token{File: src},\n\t\t\t\tValue: 3.14,\n\t\t\t},\n\t\t},\n\t}\n\n\tast := &AST{Root: rootOfAST}\n\n\tv := &printPath{0}\n\tfmt.Println(\"ROOT\")\n\n\tVisit(v, ast.Root)\n\n\tPrintln(ast)\n}"} {"input": "package fs\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nconst (\n\tWindowsTempPrefix = \"~syncthing~\"\n\tUnixTempPrefix = \".syncthing.\"\n)\n\nvar TempPrefix string\n\n\n\n\nconst maxFilenameLength = 160 - len(UnixTempPrefix) - len(\".tmp\")\n\n\n\n\n\n\nfunc IsTemporary(name string) bool {\n\tname = filepath.Base(name)\n\tif strings.HasPrefix(name, WindowsTempPrefix) ||\n\t\tstrings.HasPrefix(name, UnixTempPrefix) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc TempName(name string) string {\n\ttdir := filepath.Dir(name)\n\ttbase := filepath.Base(name)\n\tif len(tbase) > maxFilenameLength {\n\t\thash := md5.New()\n\t\thash.Write([]byte(name))\n\t\ttbase = fmt.Sprintf(\"%x\", hash.Sum(nil))\n\t}\n\ttname := fmt.Sprintf(\"%s%s.tmp\", TempPrefix, tbase)\n\treturn filepath.Join(tdir, tname)\n}\n\nfunc init() ", "output": "{\n\tif runtime.GOOS == \"windows\" {\n\t\tTempPrefix = WindowsTempPrefix\n\t} else {\n\t\tTempPrefix = UnixTempPrefix\n\t}\n}"} {"input": "package writer\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"hash/crc32\"\n\n\t\"github.com/rameshvarun/ups/common\"\n)\n\n\n\n\n\n\nfunc WriteVariableLengthInteger(value uint64) []byte {\n\tvar data []byte\n\tx := value & 0x7f\n\tvalue >>= 7\n\n\tfor value != 0 {\n\t\tdata = append(data, byte(x))\n\t\tvalue--\n\t\tx = value & 0x7f\n\t\tvalue >>= 7\n\t}\n\tdata = append(data, byte(0x80|x))\n\treturn data\n}\n\nfunc WriteUPS(data *common.PatchData) []byte ", "output": "{\n\tvar buffer bytes.Buffer\n\n\tbuffer.Write(common.Signature)\n\n\tbuffer.Write(WriteVariableLengthInteger(data.InputFileSize))\n\tbuffer.Write(WriteVariableLengthInteger(data.OutputFileSize))\n\n\tfor _, block := range data.PatchBlocks {\n\t\tbuffer.Write(WriteVariableLengthInteger(block.RelativeOffset))\n\t\tbuffer.Write(block.Data)\n\t\tbuffer.WriteByte(0)\n\t}\n\n\tbinary.Write(&buffer, binary.LittleEndian, data.InputChecksum)\n\tbinary.Write(&buffer, binary.LittleEndian, data.OutputChecksum)\n\n\tchecksum := crc32.ChecksumIEEE(buffer.Bytes())\n\tbinary.Write(&buffer, binary.LittleEndian, checksum)\n\n\treturn buffer.Bytes()\n}"} {"input": "package glw\n\nimport \"golang.org/x/mobile/gl\"\n\ntype A2fv gl.Attrib\n\n\nfunc (a A2fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A2fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 2, gl.FLOAT, false, 0, 0)\n}\n\ntype A3fv gl.Attrib\n\nfunc (a A3fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A3fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A3fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 3, gl.FLOAT, false, 0, 0)\n}\n\ntype A4fv gl.Attrib\n\nfunc (a A4fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A4fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A4fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 4, gl.FLOAT, false, 0, 0)\n}\n\nfunc (a A2fv) Enable() ", "output": "{ ctx.EnableVertexAttribArray(gl.Attrib(a)) }"} {"input": "package dummy\n\nimport (\n\t\"log\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/svenwiltink/go-musicbot/pkg/music\"\n)\n\ntype SongPlayer struct {\n\tlock sync.Mutex\n}\n\nfunc (player *SongPlayer) CanPlay(song music.Song) bool {\n\treturn true\n}\n\nfunc (player *SongPlayer) Wait() {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\ttime.Sleep(time.Second * 10)\n}\n\n\n\nfunc (player *SongPlayer) Play() error {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\tlog.Printf(\"resuming playback\")\n\treturn nil\n}\n\nfunc (player *SongPlayer) Pause() error {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\tlog.Printf(\"pausing playback\")\n\treturn nil\n}\n\nfunc NewSongPlayer() *SongPlayer {\n\treturn &SongPlayer{}\n}\n\nfunc (player *SongPlayer) PlaySong(song music.Song) error ", "output": "{\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\tlog.Printf(\"starting playback of %s\", song.Name)\n\treturn nil\n}"} {"input": "package role\n\nimport (\n\t\"github.com/watermint/toolbox/domain/dropbox/api/dbx_auth\"\n\t\"github.com/watermint/toolbox/domain/dropbox/api/dbx_conn\"\n\t\"github.com/watermint/toolbox/domain/dropbox/model/mo_user\"\n\t\"github.com/watermint/toolbox/domain/dropbox/service/sv_adminrole\"\n\t\"github.com/watermint/toolbox/domain/dropbox/service/sv_member\"\n\t\"github.com/watermint/toolbox/infra/control/app_control\"\n\t\"github.com/watermint/toolbox/infra/recipe/rc_exec\"\n\t\"github.com/watermint/toolbox/infra/recipe/rc_recipe\"\n)\n\ntype Clear struct {\n\tPeer dbx_conn.ConnScopedTeam\n\tEmail string\n}\n\nfunc (z *Clear) Preset() {\n\tz.Peer.SetScopes(\n\t\tdbx_auth.ScopeMembersRead,\n\t\tdbx_auth.ScopeMembersWrite,\n\t)\n}\n\n\n\nfunc (z *Clear) Test(c app_control.Control) error {\n\treturn rc_exec.ExecMock(c, &Clear{}, func(r rc_recipe.Recipe) {\n\t\tm := r.(*Clear)\n\t\tm.Email = \"jo@example.com\"\n\t})\n}\n\nfunc (z *Clear) Exec(c app_control.Control) error ", "output": "{\n\tmember, err := sv_member.New(z.Peer.Context()).ResolveByEmail(z.Email)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = sv_adminrole.New(z.Peer.Context()).UpdateRole(mo_user.NewUserSelectorByTeamMemberId(member.TeamMemberId), []string{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package testhelpers\n\nimport \"github.com/go-kit/kit/metrics\"\n\n\ntype CollectingCounter struct {\n\tCounterValue float64\n\tLastLabelValues []string\n}\n\n\nfunc (c *CollectingCounter) With(labelValues ...string) metrics.Counter {\n\tc.LastLabelValues = labelValues\n\treturn c\n}\n\n\nfunc (c *CollectingCounter) Add(delta float64) {\n\tc.CounterValue += delta\n}\n\n\ntype CollectingGauge struct {\n\tGaugeValue float64\n\tLastLabelValues []string\n}\n\n\nfunc (g *CollectingGauge) With(labelValues ...string) metrics.Gauge {\n\tg.LastLabelValues = labelValues\n\treturn g\n}\n\n\nfunc (g *CollectingGauge) Set(value float64) {\n\tg.GaugeValue = value\n}\n\n\nfunc (g *CollectingGauge) Add(delta float64) {\n\tg.GaugeValue = delta\n}\n\n\ntype CollectingHealthCheckMetrics struct {\n\tGauge *CollectingGauge\n}\n\n\n\n\n\nfunc NewCollectingHealthCheckMetrics() *CollectingHealthCheckMetrics {\n\treturn &CollectingHealthCheckMetrics{&CollectingGauge{}}\n}\n\nfunc (m *CollectingHealthCheckMetrics) BackendServerUpGauge() metrics.Gauge ", "output": "{\n\treturn m.Gauge\n}"} {"input": "package xenserver\n\nimport (\n\t\"time\"\n\n\t\"github.com/hashicorp/terraform/helper/schema\"\n)\n\nfunc dataSourceXenServerPifs() *schema.Resource {\n\treturn &schema.Resource{\n\t\tRead: dataSourceXenServerPifsRead,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"uuids\": &schema.Schema{\n\t\t\t\tType: schema.TypeList,\n\t\t\t\tComputed: true,\n\t\t\t\tElem: &schema.Schema{Type: schema.TypeString},\n\t\t\t},\n\t\t},\n\t}\n}\n\n\n\nfunc dataSourceXenServerPifsRead(d *schema.ResourceData, meta interface{}) error ", "output": "{\n\tc := meta.(*Connection)\n\n\tpifUUIDs := make([]string, 0)\n\n\tif pifs, err := c.client.PIF.GetAllRecords(c.session); err == nil {\n\t\tfor _, pif := range pifs {\n\t\t\tpifUUIDs = append(pifUUIDs, pif.UUID)\n\t\t}\n\t}\n\n\td.SetId(time.Now().UTC().String())\n\td.Set(\"uuids\", pifUUIDs)\n\n\treturn nil\n}"} {"input": "package mediaservices\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tAPIVersion = \"2015-10-01\"\n\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype ManagementClient struct {\n\tautorest.Client\n\tBaseURI string\n\tAPIVersion string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) ManagementClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient ", "output": "{\n\treturn ManagementClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tAPIVersion: APIVersion,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package proxy\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/fsouza/go-dockerclient\"\n\t. \"github.com/weaveworks/weave/common\"\n)\n\ntype createExecInterceptor struct {\n\tclient *docker.Client\n\twithIPAM bool\n}\n\nfunc (i *createExecInterceptor) InterceptRequest(r *http.Request) error {\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.Body.Close()\n\n\toptions := docker.CreateExecOptions{}\n\tif err := json.Unmarshal(body, &options); err != nil {\n\t\treturn err\n\t}\n\n\tcontainer, err := inspectContainerInPath(i.client, r.URL.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif cidrs, ok := weaveCIDRsFromConfig(container.Config); ok || i.withIPAM {\n\t\tInfo.Printf(\"Exec in container %s with WEAVE_CIDR \\\"%s\\\"\", container.ID, strings.Join(cidrs, \" \"))\n\t\tcmd := append(weaveWaitEntrypoint, \"-s\")\n\t\toptions.Cmd = append(cmd, options.Cmd...)\n\t}\n\n\tif err := marshalRequestBody(r, options); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (i *createExecInterceptor) InterceptResponse(r *http.Response) error ", "output": "{\n\treturn nil\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/api/extensions/v1beta1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype PodSecurityPolicyLister interface {\n\tList(selector labels.Selector) (ret []*v1beta1.PodSecurityPolicy, err error)\n\tGet(name string) (*v1beta1.PodSecurityPolicy, error)\n\tPodSecurityPolicyListerExpansion\n}\n\n\ntype podSecurityPolicyLister struct {\n\tindexer cache.Indexer\n}\n\n\n\n\n\nfunc (s *podSecurityPolicyLister) List(selector labels.Selector) (ret []*v1beta1.PodSecurityPolicy, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.PodSecurityPolicy))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *podSecurityPolicyLister) Get(name string) (*v1beta1.PodSecurityPolicy, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"podsecuritypolicy\"), name)\n\t}\n\treturn obj.(*v1beta1.PodSecurityPolicy), nil\n}\n\nfunc NewPodSecurityPolicyLister(indexer cache.Indexer) PodSecurityPolicyLister ", "output": "{\n\treturn &podSecurityPolicyLister{indexer: indexer}\n}"} {"input": "package ovnmodel\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/skydive-project/skydive/graffiti/getter\"\n\t\"github.com/skydive-project/skydive/graffiti/graph\"\n)\n\n\n\n\ntype LoadBalancerHealthCheck struct {\n\tUUID string `ovsdb:\"_uuid\" json:\",omitempty\" `\n\tExternalIDs map[string]string `ovsdb:\"external_ids\" json:\",omitempty\" `\n\tOptions map[string]string `ovsdb:\"options\" json:\",omitempty\" `\n\tVip string `ovsdb:\"vip\" json:\",omitempty\" `\n\n\tExternalIDsMeta graph.Metadata `json:\",omitempty\" field:\"Metadata\"`\n\tOptionsMeta graph.Metadata `json:\",omitempty\" field:\"Metadata\"`\n}\n\nfunc (t *LoadBalancerHealthCheck) Metadata() graph.Metadata {\n\tt.ExternalIDsMeta = graph.NormalizeValue(t.ExternalIDs).(map[string]interface{})\n\tt.OptionsMeta = graph.NormalizeValue(t.Options).(map[string]interface{})\n\n\treturn graph.Metadata{\n\t\t\"Type\": \"LoadBalancerHealthCheck\",\n\t\t\"Manager\": \"ovn\",\n\t\t\"UUID\": t.GetUUID(),\n\t\t\"Name\": t.GetName(),\n\t\t\"OVN\": t,\n\t}\n}\n\n\n\nfunc (t *LoadBalancerHealthCheck) GetName() string {\n\tif name := t.UUID; name != \"\" {\n\t\treturn name\n\t}\n\treturn t.GetUUID()\n}\n\n\nfunc LoadBalancerHealthCheckDecoder(raw json.RawMessage) (getter.Getter, error) {\n\tvar t LoadBalancerHealthCheck\n\tif err := json.Unmarshal(raw, &t); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to unmarshal LoadBalancerHealthCheck metadata %s: %s\", string(raw), err)\n\t}\n\treturn &t, nil\n}\n\nfunc (t *LoadBalancerHealthCheck) GetUUID() string ", "output": "{\n\treturn t.UUID\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/golang/protobuf/proto\"\n\t\"github.com/lightstep/lightstep-tracer-cpp/lightstep-tracer-common\"\n\t\"io\"\n)\n\nfunc computeFieldTypeNumber(field uint64, wireType uint64) uint64 {\n\treturn (field << 3) | wireType\n}\n\n\n\nfunc readReporter(reader *bufio.Reader) (*collectorpb.Reporter, error) {\n\treporter := &collectorpb.Reporter{}\n\treturn reporter, readEmbeddedMessage(reader, 1, reporter)\n}\n\nfunc readAuth(reader *bufio.Reader) (*collectorpb.Auth, error) {\n\tauth := &collectorpb.Auth{}\n\treturn auth, readEmbeddedMessage(reader, 2, auth)\n}\n\nfunc readInternalMetrics(reader *bufio.Reader) (*collectorpb.InternalMetrics, error) {\n\tinternalMetrics := &collectorpb.InternalMetrics{}\n\treturn internalMetrics, readEmbeddedMessage(reader, 6, internalMetrics)\n}\n\nfunc ReadStreamHeader(reader *bufio.Reader) (*collectorpb.ReportRequest, error) {\n\treporter, err := readReporter(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauth, err := readAuth(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinternalMetrics, err := readInternalMetrics(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := &collectorpb.ReportRequest{\n\t\tReporter: reporter,\n\t\tAuth: auth,\n\t\tInternalMetrics: internalMetrics,\n\t}\n\treturn result, nil\n}\n\nfunc ReadSpan(reader *bufio.Reader) (*collectorpb.Span, error) {\n\tspan := &collectorpb.Span{}\n\treturn span, readEmbeddedMessage(reader, 3, span)\n}\n\nfunc readEmbeddedMessage(reader *bufio.Reader, field uint64, message proto.Message) error ", "output": "{\n\tfieldType, err := binary.ReadUvarint(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif expectedFieldType := computeFieldTypeNumber(field, proto.WireBytes); fieldType != expectedFieldType {\n\t\treturn errors.New(fmt.Sprintf(\"Unexpected fieldType %d number for Reporter: expected %d\", fieldType,\n\t\t\texpectedFieldType))\n\t}\n\tlength, err := binary.ReadUvarint(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuffer := make([]byte, length)\n\t_, err = io.ReadFull(reader, buffer)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn proto.Unmarshal(buffer, message)\n}"} {"input": "package glw\n\nimport \"golang.org/x/mobile/gl\"\n\ntype A2fv gl.Attrib\n\nfunc (a A2fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A2fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A2fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 2, gl.FLOAT, false, 0, 0)\n}\n\ntype A3fv gl.Attrib\n\nfunc (a A3fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A3fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\n\n\ntype A4fv gl.Attrib\n\nfunc (a A4fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A4fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A4fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 4, gl.FLOAT, false, 0, 0)\n}\n\nfunc (a A3fv) Pointer() ", "output": "{\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 3, gl.FLOAT, false, 0, 0)\n}"} {"input": "package main\n\nimport (\n\t\"reflect\"\n)\n\ntype Person struct {\n\tname string \"namestr\"\n\tage int\n}\n\nfunc ShowTag(i interface{}) {\n\tswitch t := reflect.TypeOf(i); t.Kind() {\n\tcase reflect.Ptr:\n\t\ttag := t.Elem().Field(0).Tag\n\t\tprintln(tag)\n\t}\n}\n\n\n\nfunc main() {\n\tp := new(Person)\n\tp.name = \"test\"\n\tp.age = 18\n\tShowTag(p)\n\tshow(p)\n}\n\nfunc show(i interface{}) ", "output": "{\n\tswitch i.(type) {\n\tcase *Person:\n\t\tt := reflect.TypeOf(i)\n\t\tv := reflect.ValueOf(i)\n\t\ttag := t.Elem().Field(0).Tag\n\t\tname := v.Elem().Field(0).String()\n\t\tage := v.Elem().Field(1).Int()\n\t\tprintln(tag)\n\t\tprintln(name)\n\t\tprintln(age)\n\t}\n}"} {"input": "package tequilapi\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n\ntype APIServer interface {\n\tWait() error\n\tStartServing() error\n\tStop()\n\tAddress() (string, error)\n}\n\ntype apiServer struct {\n\terrorChannel chan error\n\thandler http.Handler\n\tlistenAddress string\n\tlistener net.Listener\n}\n\n\nfunc NewServer(address string, port int, handler http.Handler, corsPolicy CorsPolicy) APIServer {\n\tserver := apiServer{\n\t\tmake(chan error, 1),\n\t\tDisableCaching(ApplyCors(handler, corsPolicy)),\n\t\tfmt.Sprintf(\"%s:%d\", address, port),\n\t\tnil}\n\treturn &server\n}\n\n\nfunc (server *apiServer) Stop() {\n\tif server.listener == nil {\n\t\treturn\n\t}\n\tserver.listener.Close()\n}\n\n\nfunc (server *apiServer) Wait() error {\n\treturn <-server.errorChannel\n}\n\n\nfunc (server *apiServer) Address() (string, error) {\n\tif server.listener == nil {\n\t\treturn \"\", errors.New(\"not bound\")\n\t}\n\treturn extractBoundAddress(server.listener)\n}\n\n\n\nfunc (server *apiServer) StartServing() error {\n\tvar err error\n\tserver.listener, err = net.Listen(\"tcp\", server.listenAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo server.serve(server.handler)\n\treturn nil\n}\n\nfunc (server *apiServer) serve(handler http.Handler) {\n\tserver.errorChannel <- http.Serve(server.listener, handler)\n}\n\n\n\nfunc extractBoundAddress(listener net.Listener) (string, error) ", "output": "{\n\taddr := listener.Addr()\n\tparts := strings.Split(addr.String(), \":\")\n\tif len(parts) < 2 {\n\t\treturn \"\", errors.New(\"Unable to locate address: \" + addr.String())\n\t}\n\treturn addr.String(), nil\n}"} {"input": "package runners\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\t\"text/template\"\n\n\t\"github.com/davecgh/go-spew/spew\"\n\t\"github.com/kylelemons/godebug/pretty\"\n\tyaml \"gopkg.in/yaml.v2\"\n)\n\nfunc getFuncs() template.FuncMap {\n\treturn template.FuncMap{\n\t\t\"pretty\": func(i interface{}) string {\n\t\t\treturn pretty.Sprint(i)\n\t\t},\n\t\t\"json\": func(i interface{}) string {\n\t\t\tjson, _ := json.MarshalIndent(i, \"\", \"\\t\")\n\t\t\treturn string(json)\n\t\t},\n\t\t\"yaml\": func(i interface{}) string {\n\t\t\tyaml, _ := yaml.Marshal(i)\n\t\t\treturn string(yaml)\n\t\t},\n\t\t\"spew\": func(i interface{}) string {\n\t\t\treturn spew.Sprint(i)\n\t\t},\n\t\t\"describe\": func(i interface{}) string {\n\t\t\treturn describeStruct(i, 0)\n\t\t},\n\t}\n}\n\n\n\nfunc describeStruct(t interface{}, depth int) string ", "output": "{\n\tprefix := strings.Repeat(\" \", depth)\n\tvar out string\n\ts := reflect.Indirect(reflect.ValueOf(t))\n\ttypeOfT := s.Type()\n\n\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\n\t\tout = fmt.Sprintf(\"%s%s%s %s\\n\", out, prefix, typeOfT.Field(i).Name, typeOfT.Field(i).Type)\n\t\tswitch f.Type().Kind() {\n\t\tcase reflect.Struct, reflect.Ptr:\n\t\t\tout = fmt.Sprintf(\"%s%s{\\n\", out, prefix)\n\t\t\tout = fmt.Sprintf(\"%s%s\", out, describeStruct(f.Interface(), depth+1))\n\t\t\tout = fmt.Sprintf(\"%s%s}\\n\", out, prefix)\n\t\t}\n\t}\n\treturn out\n}"} {"input": "package sign\n\nimport (\n\t\"dfss\"\n\tcAPI \"dfss/dfssc/api\"\n\tpAPI \"dfss/dfssp/api\"\n\t\"dfss/dfsst/entities\"\n\t\"dfss/net\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\ntype clientServer struct {\n\tincomingPromises chan interface{}\n\tincomingSignatures chan interface{}\n}\n\nfunc getServerErrorCode(c chan interface{}, in interface{}) *pAPI.ErrorCode {\n\tif c != nil {\n\t\tc <- in\n\t\treturn &pAPI.ErrorCode{Code: pAPI.ErrorCode_SUCCESS}\n\t}\n\treturn &pAPI.ErrorCode{Code: pAPI.ErrorCode_INTERR} \n}\n\n\n\n\nfunc (s *clientServer) TreatPromise(ctx context.Context, in *cAPI.Promise) (*pAPI.ErrorCode, error) {\n\tvalid, _, _, _ := entities.IsRequestValid(ctx, []*cAPI.Promise{in})\n\tif !valid {\n\t\treturn &pAPI.ErrorCode{Code: pAPI.ErrorCode_SUCCESS}, nil\n\t}\n\treturn getServerErrorCode(s.incomingPromises, in), nil\n}\n\n\n\n\nfunc (s *clientServer) TreatSignature(ctx context.Context, in *cAPI.Signature) (*pAPI.ErrorCode, error) {\n\treturn getServerErrorCode(s.incomingSignatures, in), nil\n}\n\n\n\n\n\n\n\nfunc (m *SignatureManager) GetServer() *grpc.Server {\n\tserver := net.NewServer(m.auth.Cert, m.auth.Key, m.auth.CA)\n\tm.cServerIface = clientServer{}\n\tcAPI.RegisterClientServer(server, &m.cServerIface)\n\treturn server\n}\n\nfunc (s *clientServer) Discover(ctx context.Context, in *cAPI.Hello) (*cAPI.Hello, error) ", "output": "{\n\treturn &cAPI.Hello{Version: dfss.Version}, nil\n}"} {"input": "package resolver\n\nvar (\n\tm = make(map[string]Builder)\n\tdefaultScheme = \"passthrough\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Get(scheme string) Builder {\n\tif b, ok := m[scheme]; ok {\n\t\treturn b\n\t}\n\tif b, ok := m[defaultScheme]; ok {\n\t\treturn b\n\t}\n\treturn nil\n}\n\n\n\nfunc SetDefaultScheme(scheme string) {\n\tdefaultScheme = scheme\n}\n\n\ntype AddressType uint8\n\nconst (\n\tBackend AddressType = iota\n\tGRPCLB\n)\n\n\n\ntype Address struct {\n\tAddr string\n\tType AddressType\n\tServerName string\n\tMetadata interface{}\n}\n\n\n\ntype BuildOption struct {\n}\n\n\n\ntype ClientConn interface {\n\tNewAddress(addresses []Address)\n\tNewServiceConfig(serviceConfig string)\n}\n\n\n\ntype Target struct {\n\tScheme string\n\tAuthority string\n\tEndpoint string\n}\n\n\ntype Builder interface {\n\tBuild(target Target, cc ClientConn, opts BuildOption) (Resolver, error)\n\tScheme() string\n}\n\n\ntype ResolveNowOption struct{}\n\n\n\ntype Resolver interface {\n\tResolveNow(ResolveNowOption)\n\tClose()\n}\n\n\n\n\nfunc UnregisterForTesting(scheme string) {\n\tdelete(m, scheme)\n}\n\nfunc Register(b Builder) ", "output": "{\n\tm[b.Scheme()] = b\n}"} {"input": "package bst\n\nimport (\n\t\"math\"\n\n\t\"github.com/catorpilor/leetcode/utils\"\n)\n\n\n\nfunc helper(node *utils.TreeNode, min, max int) bool {\n\tif node == nil {\n\t\treturn true\n\t}\n\tif node.Val <= min || node.Val >= max {\n\t\treturn false\n\t}\n\treturn helper(node.Left, min, node.Val) && helper(node.Right, node.Val, max)\n}\n\nfunc IsValidBST(root *utils.TreeNode) bool ", "output": "{\n\treturn helper(root, math.MinInt64, math.MaxInt64)\n\n}"} {"input": "package master\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\n\tauth \"github.com/abbot/go-http-auth\"\n\t\"github.com/h2oai/steam/master/az\"\n)\n\ntype DefaultAz struct {\n\tdirectory az.Directory\n}\n\nfunc NewDefaultAz(directory az.Directory) *DefaultAz {\n\treturn &DefaultAz{directory}\n}\n\nfunc (a *DefaultAz) Authenticate(username string) string {\n\tpz, err := a.directory.Lookup(username)\n\tif err != nil {\n\t\tlog.Printf(\"User %s read failed: %s\\n\", username, err)\n\t\treturn \"\"\n\t}\n\n\tif pz == nil {\n\t\tlog.Printf(\"User %s does not exist\\n\", username)\n\t\treturn \"\"\n\t}\n\treturn pz.Password()\n}\n\nfunc (a *DefaultAz) Identify(r *http.Request) (az.Principal, error) {\n\tusername := r.Header.Get(auth.AuthUsernameHeader)\n\tpz, err := a.directory.Lookup(username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif pz == nil {\n\t\treturn nil, fmt.Errorf(\"User %s does not exist\\n\", username)\n\t}\n\n\treturn pz, nil\n}\n\nfunc serveNoop(w http.ResponseWriter, r *http.Request) {}\n\n\nfunc authNoop(user, realm string) string ", "output": "{ return \"\" }"} {"input": "package Utils\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestGzip(t *testing.T) {\n\tmergeBuf := MergeBinary([]byte(\"i am first words\"), []byte(\"i am second words\"))\n\n\tgzip, err := FastGZipMsg(mergeBuf, true)\n\tif err != nil {\n\t\tt.Fail()\n\t\treturn\n\t}\n\n\tunzip, err := FastUnGZipMsg(gzip, true)\n\tif err != nil {\n\t\tt.Fail()\n\t\treturn\n\t}\n\n\tsplitBuf := SplitBinary(unzip)\n\n\tfor _, v := range splitBuf {\n\t\tfmt.Println(string(v))\n\t}\n}\n\nfunc TestBinary(t *testing.T) ", "output": "{\n\tmergeBuf := MergeBinary([]byte(\"i am first words\"), []byte(\"i am second words\"))\n\n\tsplitBuf := SplitBinary(mergeBuf)\n\n\tfor _, v := range splitBuf {\n\t\tfmt.Println(string(v))\n\t}\n}"} {"input": "package font\n\nimport (\n\t\"bytes\"\n)\n\nvar alias = map[rune]string{\n\t0x2764: \"\\u2665\", \n\t0x0001f499: \"\\u2665\", \n\t0x0001f49a: \"\\u2665\", \n\t0x0001f49b: \"\\u2665\", \n\t0x0001f49c: \"\\u2665\", \n\t0x0001f49d: \"\\u2665\", \n\t0x0001F601: \":|\", \n\t0x0001F602: \":)\", \n\t0x0001F603: \":D\", \n}\n\ntype Font struct {\n\twidth int\n\theight int\n\tbitmap map[rune][]byte\n}\n\nfunc ExpandAlias(text string) string {\n\tvar f func(b *bytes.Buffer, s string)\n\tf = func(b *bytes.Buffer, s string) {\n\t\tfor _, c := range s {\n\t\t\tm, ok := alias[c]\n\t\t\tif ok {\n\t\t\t\tf(b, m)\n\t\t\t} else {\n\t\t\t\tb.WriteRune(c)\n\t\t\t}\n\t\t}\n\t}\n\tb := new(bytes.Buffer)\n\tf(b, text)\n\treturn b.String()\n}\n\nfunc (f *Font) Height() int {\n\treturn f.height\n}\n\n\n\nfunc (f *Font) Bitmap(c rune) []byte {\n\treturn f.bitmap[c]\n}\n\nfunc (f *Font) Width() int ", "output": "{\n\treturn f.width\n}"} {"input": "package v1alpha1_test\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"k8s.io/api/scheduling/v1alpha1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\n\tapiv1 \"k8s.io/api/core/v1\"\n\tutilfeature \"k8s.io/apiserver/pkg/util/feature\"\n\tfeaturegatetesting \"k8s.io/component-base/featuregate/testing\"\n\t_ \"k8s.io/kubernetes/pkg/api/testapi\"\n\t\"k8s.io/kubernetes/pkg/features\"\n)\n\nfunc roundTrip(t *testing.T, obj runtime.Object) runtime.Object {\n\tcodec := legacyscheme.Codecs.LegacyCodec(v1alpha1.SchemeGroupVersion)\n\tdata, err := runtime.Encode(codec, obj)\n\tif err != nil {\n\t\tt.Errorf(\"%v\\n %#v\", err, obj)\n\t\treturn nil\n\t}\n\tobj2, err := runtime.Decode(codec, data)\n\tif err != nil {\n\t\tt.Errorf(\"%v\\nData: %s\\nSource: %#v\", err, string(data), obj)\n\t\treturn nil\n\t}\n\tobj3 := reflect.New(reflect.TypeOf(obj).Elem()).Interface().(runtime.Object)\n\terr = legacyscheme.Scheme.Convert(obj2, obj3, nil)\n\tif err != nil {\n\t\tt.Errorf(\"%v\\nSource: %#v\", err, obj2)\n\t\treturn nil\n\t}\n\treturn obj3\n}\n\n\n\nfunc TestSetDefaultPreempting(t *testing.T) ", "output": "{\n\tpriorityClass := &v1alpha1.PriorityClass{}\n\n\tdefer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.NonPreemptingPriority, true)()\n\n\toutput := roundTrip(t, runtime.Object(priorityClass)).(*v1alpha1.PriorityClass)\n\tif output.PreemptionPolicy == nil || *output.PreemptionPolicy != apiv1.PreemptLowerPriority {\n\t\tt.Errorf(\"Expected PriorityClass.Preempting value: %+v\\ngot: %+v\\n\", apiv1.PreemptLowerPriority, output.PreemptionPolicy)\n\t}\n}"} {"input": "package sdk\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\n\n\n\nvar NowTime func() time.Time\n\n\n\nvar Sleep func(time.Duration)\n\n\n\n\n\n\nvar SleepWithContext func(context.Context, time.Duration) error\n\n\n\n\nfunc sleepWithContext(ctx context.Context, dur time.Duration) error {\n\tt := time.NewTimer(dur)\n\tdefer t.Stop()\n\n\tselect {\n\tcase <-t.C:\n\t\tbreak\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n\n\treturn nil\n}\n\n\nfunc noOpSleepWithContext(context.Context, time.Duration) error {\n\treturn nil\n}\n\nfunc noOpSleep(time.Duration) {}\n\n\n\nfunc TestingUseNopSleep() func() {\n\tSleepWithContext = noOpSleepWithContext\n\tSleep = noOpSleep\n\n\treturn func() {\n\t\tSleepWithContext = sleepWithContext\n\t\tSleep = time.Sleep\n\t}\n}\n\n\n\nfunc TestingUseReferenceTime(referenceTime time.Time) func() {\n\tNowTime = func() time.Time {\n\t\treturn referenceTime\n\t}\n\treturn func() {\n\t\tNowTime = time.Now\n\t}\n}\n\nfunc init() ", "output": "{\n\tNowTime = time.Now\n\tSleep = time.Sleep\n\tSleepWithContext = sleepWithContext\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc bats(l, d, n int, s []string) (c int) {\n\tvar t int\n\ttx := 6 - d\n\tfor i := 6; i <= l-6; i += d {\n\t\tif i > tx-d {\n\t\t\ti = tx\n\t\t\tif t == n {\n\t\t\t\ttx = l - 6 + d\n\t\t\t} else {\n\t\t\t\tfmt.Sscanf(s[t], \"%d\", &tx)\n\t\t\t\tt++\n\t\t\t}\n\t\t} else {\n\t\t\tc++\n\t\t}\n\t}\n\treturn c\n}\n\nfunc TestBats(t *testing.T) ", "output": "{\n\tif r := bats(22, 2, 2, []string{\"9\", \"11\"}); r != 3 {\n\t\tt.Errorf(\"failed: bats 22 2 2 9 11 is 3, got %d\",\n\t\t\tr)\n\t}\n\tif r := bats(835, 125, 1, []string{\"113\"}); r != 5 {\n\t\tt.Errorf(\"failed: bats 835 125 1 113 is 5, got %d\",\n\t\t\tr)\n\t}\n\tif r := bats(47, 5, 0, []string{}); r != 8 {\n\t\tt.Errorf(\"failed: bats 475 5 0 is 8, got %d\",\n\t\t\tr)\n\t}\n}"} {"input": "package resource\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n)\n\n\ntype Item struct {\n\tID interface{}\n\tETag string\n\tUpdated time.Time\n\tPayload map[string]interface{}\n}\n\n\ntype ItemList struct {\n\tTotal int\n\tPage int\n\tItems []*Item\n}\n\n\nfunc NewItem(payload map[string]interface{}) (*Item, error) {\n\tid, found := payload[\"id\"]\n\tif !found {\n\t\treturn nil, errors.New(\"Missing ID field\")\n\t}\n\tetag, err := genEtag(payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\titem := &Item{\n\t\tID: id,\n\t\tETag: etag,\n\t\tUpdated: time.Now(),\n\t\tPayload: payload,\n\t}\n\treturn item, nil\n}\n\n\n\n\n\n\n\n\n\nfunc getField(payload map[string]interface{}, name string) interface{} {\n\tpath := strings.SplitN(name, \".\", 2)\n\tif value, found := payload[path[0]]; found {\n\t\tif len(path) == 2 {\n\t\t\tif subPayload, ok := value.(map[string]interface{}); ok {\n\t\t\t\treturn getField(subPayload, path[1])\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\treturn value\n\t}\n\treturn nil\n}\n\nfunc (i Item) GetField(name string) interface{} ", "output": "{\n\treturn getField(i.Payload, name)\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n\n\tctypes \"github.com/tendermint/tendermint/rpc/core/types\"\n\t\"github.com/tendermint/tendermint/types\"\n\t. \"github.com/tendermint/tmlibs/common\"\n)\n\n\n\n\nfunc BlockchainInfo(minHeight, maxHeight int) (*ctypes.ResultBlockchainInfo, error) {\n\tif maxHeight == 0 {\n\t\tmaxHeight = blockStore.Height()\n\t} else {\n\t\tmaxHeight = MinInt(blockStore.Height(), maxHeight)\n\t}\n\tif minHeight == 0 {\n\t\tminHeight = MaxInt(1, maxHeight-20)\n\t} else {\n\t\tminHeight = MaxInt(minHeight, maxHeight-20)\n\t}\n\n\tlogger.Debug(\"BlockchainInfoHandler\", \"maxHeight\", maxHeight, \"minHeight\", minHeight)\n\n\tblockMetas := []*types.BlockMeta{}\n\tfor height := maxHeight; height >= minHeight; height-- {\n\t\tblockMeta := blockStore.LoadBlockMeta(height)\n\t\tblockMetas = append(blockMetas, blockMeta)\n\t}\n\n\treturn &ctypes.ResultBlockchainInfo{blockStore.Height(), blockMetas}, nil\n}\n\n\n\n\n\n\n\nfunc Commit(height int) (*ctypes.ResultCommit, error) {\n\tif height == 0 {\n\t\treturn nil, fmt.Errorf(\"Height must be greater than 0\")\n\t}\n\tstoreHeight := blockStore.Height()\n\tif height > storeHeight {\n\t\treturn nil, fmt.Errorf(\"Height must be less than or equal to the current blockchain height\")\n\t}\n\n\theader := blockStore.LoadBlockMeta(height).Header\n\n\tif height == storeHeight {\n\t\tcommit := blockStore.LoadSeenCommit(height)\n\t\treturn &ctypes.ResultCommit{header, commit, false}, nil\n\t}\n\n\tcommit := blockStore.LoadBlockCommit(height)\n\treturn &ctypes.ResultCommit{header, commit, true}, nil\n}\n\nfunc Block(height int) (*ctypes.ResultBlock, error) ", "output": "{\n\tif height == 0 {\n\t\treturn nil, fmt.Errorf(\"Height must be greater than 0\")\n\t}\n\tif height > blockStore.Height() {\n\t\treturn nil, fmt.Errorf(\"Height must be less than the current blockchain height\")\n\t}\n\n\tblockMeta := blockStore.LoadBlockMeta(height)\n\tblock := blockStore.LoadBlock(height)\n\treturn &ctypes.ResultBlock{blockMeta, block}, nil\n}"} {"input": "package account\n\ntype Response struct {\n\tCode int `json:\"code\"`\n\tMessage string `json:\"message\"`\n}\n\ntype DescribeProjectArgs struct{}\n\ntype DescribeProjectResponse struct {\n\tResponse\n\tData []Project `json:\"data\"`\n}\n\ntype Project struct {\n\tProjectName string `json:\"projectName\"`\n\tProjectId int `json:\"projectId\"`\n\tCreateTime string `json:\"createTime\"`\n\tCreatorUin int `json:\"creatorUin\"`\n\tProjectInfo string `json:\"projectInfo\"`\n}\n\n\n\nfunc (client *Client) DescribeProject(args *DescribeProjectArgs) (*DescribeProjectResponse, error) ", "output": "{\n\tresponse := &DescribeProjectResponse{}\n\terr := client.Invoke(\"DescribeProject\", args, response)\n\tif err != nil {\n\t\treturn &DescribeProjectResponse{}, err\n\t}\n\treturn response, nil\n}"} {"input": "package v1\n\n\n\ntype EnvVarSourceApplyConfiguration struct {\n\tFieldRef *ObjectFieldSelectorApplyConfiguration `json:\"fieldRef,omitempty\"`\n\tResourceFieldRef *ResourceFieldSelectorApplyConfiguration `json:\"resourceFieldRef,omitempty\"`\n\tConfigMapKeyRef *ConfigMapKeySelectorApplyConfiguration `json:\"configMapKeyRef,omitempty\"`\n\tSecretKeyRef *SecretKeySelectorApplyConfiguration `json:\"secretKeyRef,omitempty\"`\n}\n\n\n\nfunc EnvVarSource() *EnvVarSourceApplyConfiguration {\n\treturn &EnvVarSourceApplyConfiguration{}\n}\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithFieldRef(value *ObjectFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.FieldRef = value\n\treturn b\n}\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithResourceFieldRef(value *ResourceFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.ResourceFieldRef = value\n\treturn b\n}\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithConfigMapKeyRef(value *ConfigMapKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.ConfigMapKeyRef = value\n\treturn b\n}\n\n\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithSecretKeyRef(value *SecretKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration ", "output": "{\n\tb.SecretKeyRef = value\n\treturn b\n}"} {"input": "package gbcrypto\n\nimport \"testing\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc TestDecrypt(t *testing.T) ", "output": "{\n\tsecretKey := \"SecretKey\"\n\tmessage := \"Pz3cJ61A4Dw4vTFcqWN6t39pyWyOGCQe9F0=\"\n\texpected := \"encrypt me\"\n\n\tcryptography := Cryptography{}\n\tdecrypted := cryptography.Decrypt(secretKey, message)\n\n\tif decrypted != expected {\n\t\tt.Errorf(\"Expected %v, got %v\", expected, decrypted)\n\t}\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\n\n\ntype ContainerStateRunningApplyConfiguration struct {\n\tStartedAt *v1.Time `json:\"startedAt,omitempty\"`\n}\n\n\n\nfunc ContainerStateRunning() *ContainerStateRunningApplyConfiguration {\n\treturn &ContainerStateRunningApplyConfiguration{}\n}\n\n\n\n\n\n\nfunc (b *ContainerStateRunningApplyConfiguration) WithStartedAt(value v1.Time) *ContainerStateRunningApplyConfiguration ", "output": "{\n\tb.StartedAt = &value\n\treturn b\n}"} {"input": "package smtp\n\nimport (\n\t\"errors\"\n\t\"testing\"\n)\n\ntype EmailRecorder struct {\n\tfrom string\n\tto []string\n\tmsg []byte\n}\n\ntype SMTPMock struct {\n\tr *EmailRecorder\n\terr error\n}\n\nfunc (s *SMTPMock) SendMail(from string, to []string, msg []byte) error {\n\ts.r = &EmailRecorder{from, to, msg}\n\treturn s.err\n}\n\nfunc TestMailService(t *testing.T) {\n\tmailService := MailService{}\n\n\tvar i interface{} = &mailService\n\t_, ok := i.(IMailService)\n\n\tif !ok {\n\t\tt.Fatalf(\"MailService must implement IMailService\")\n\t}\n}\n\nfunc TestSendNormal(t *testing.T) {\n\tbody := \"From: john@doe.com\\r\\n\" +\n\t\t\"To: jane@doe.com\\r\\n\" +\n\t\t\"Subject: test\\r\\n\" +\n\t\t\"\\r\\n\" +\n\t\t\"message\\r\\n\"\n\ts := SMTPMock{err: nil}\n\tmailService := NewMailService(&s)\n\n\terr := mailService.Send(\"message\", \"test\", \"john@doe.com\", \"jane@doe.com\")\n\tif err != nil {\n\t\tt.Fatalf(\"Mustn't return an error\")\n\t}\n\tif string(s.r.msg) != body {\n\t\tt.Errorf(\"wrong message body.\\n\\nexpected: %s\\n got: %s\", body, s.r.msg)\n\t}\n}\n\n\n\nfunc TestSendError(t *testing.T) ", "output": "{\n\terr := errors.New(\"Error\")\n\ts := SMTPMock{err: err}\n\tmailService := NewMailService(&s)\n\n\terr = mailService.Send(\"message\", \"test\", \"john@doe.com\", \"jane@doe.com\")\n\tif err == nil {\n\t\tt.Fatalf(\"Must return an error\")\n\t}\n}"} {"input": "package data\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestNote(t *testing.T) {\n\tacc := AccountNew(\"mail@example.com\")\n\tuser, err := acc.Store()\n\n\tassert.Nil(t, err)\n\n\tnote := NoteNew(user.ID, \"example content\")\n\n\tassert.False(t, note.IsStored())\n\tassert.Equal(t, \"example content\", note.Text)\n\tassert.Equal(t, user.ID, note.Account)\n\n\tnote, err = note.Store()\n\n\tif assert.Nil(t, err) {\n\t\tassert.True(t, note.IsStored())\n\t}\n\n\tuser.Remove()\n}\n\n\n\nfunc TestNoteList(t *testing.T) {\n\tacc := AccountNew(\"mail@example.com\")\n\tuser, err := acc.Store()\n\n\tassert.Nil(t, err)\n\n\tnote := NoteNew(user.ID, \"This is a note!\")\n\tnote, err = note.Store()\n\n\tassert.Nil(t, err)\n\n\tnote2 := NoteNew(user.ID, \"This is a second note!\")\n\tnote2, err = note2.Store()\n\n\tassert.Nil(t, err)\n\n\tlist, err := NoteListByAccount(user.ID)\n\n\tassert.Nil(t, err)\n\tassert.Equal(t, 2, len(list))\n\n\tuser.Remove()\n}\n\nfunc TestNoteLimit(t *testing.T) ", "output": "{\n\tacc := AccountNew(\"mail@example.com\")\n\tuser, err := acc.Store()\n\n\tassert.Nil(t, err)\n\n\tnote := NoteNew(user.ID, \"This is a note! This is a note! This is a note! This is a note! This is a note! This is a note! This is a note!\")\n\n\tassert.False(t, note.IsStored())\n\tassert.Equal(t, user.ID, note.Account)\n\n\tnote, err = note.Store()\n\n\tassert.NotNil(t, err)\n\n\tuser.Remove()\n}"} {"input": "package portmapper\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/golang/glog\"\n)\n\ntype PortMap struct {\n\tcontainerIP string\n\tcontainerPort int\n}\n\nfunc newPortMap(containerip string, containerport int) *PortMap {\n\treturn &PortMap{\n\t\tcontainerIP: containerip,\n\t\tcontainerPort: containerport,\n\t}\n}\n\ntype PortSet map[int]*PortMap\n\ntype PortMapper struct {\n\ttcpMap PortSet\n\tudpMap PortSet\n\tmutex sync.Mutex\n}\n\nfunc New() *PortMapper {\n\treturn &PortMapper{PortSet{}, PortSet{}, sync.Mutex{}}\n}\n\n\n\nfunc (p *PortMapper) ReleaseMap(protocol string, hostPort int) error {\n\tp.mutex.Lock()\n\tdefer p.mutex.Unlock()\n\n\tvar pset PortSet\n\n\tif strings.EqualFold(protocol, \"udp\") {\n\t\tpset = p.udpMap\n\t} else {\n\t\tpset = p.tcpMap\n\t}\n\n\t_, ok := pset[hostPort]\n\tif !ok {\n\t\tglog.Errorf(\"Host port %d has not been used\", hostPort)\n\t}\n\n\tdelete(pset, hostPort)\n\treturn nil\n}\n\nfunc (p *PortMapper) AllocateMap(protocol string, hostPort int,\n\tcontainerIP string, ContainerPort int) error ", "output": "{\n\tp.mutex.Lock()\n\tdefer p.mutex.Unlock()\n\n\tvar pset PortSet\n\n\tif strings.EqualFold(protocol, \"udp\") {\n\t\tpset = p.udpMap\n\t} else {\n\t\tpset = p.tcpMap\n\t}\n\n\te, ok := pset[hostPort]\n\tif ok {\n\t\treturn fmt.Errorf(\"Host port %d had already been used, %s %d\",\n\t\t\thostPort, e.containerIP, e.containerPort)\n\t}\n\n\tallocated := newPortMap(containerIP, ContainerPort)\n\tpset[hostPort] = allocated\n\n\treturn nil\n}"} {"input": "package rest\n\nimport \"net/http\"\n\ntype StaticResource struct {\n\tResourceBase\n\tresult *Result\n\tself Link\n}\n\nfunc NewStaticResource(result *Result, self Link) Resource {\n\treturn &StaticResource{\n\t\tresult: result,\n\t\tself: self,\n\t}\n}\n\nfunc StaticContent(content []byte, contentType string, selfHref string) Resource {\n\treturn NewStaticResource(\n\t\tOk().AddHeader(\"Content-Type\", contentType).WithBody(content),\n\t\tSimpleLink(selfHref),\n\t)\n}\n\n\n\nfunc (r StaticResource) Self() Link {\n\treturn r.self\n}\n\nfunc (r StaticResource) Get(request *http.Request) (interface{}, error) ", "output": "{\n\treturn r.result, nil\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n\t\"os\"\n)\n\n\n\nfunc encodeJSON(w io.Writer, v interface{}) {\n\tenc := json.NewEncoder(w)\n\n\tenc.SetIndent(\"\", \" \")\n\n\tenc.Encode(v)\n}\n\nfunc dump(v interface{}) ", "output": "{\n\tencodeJSON(os.Stdout, v)\n}"} {"input": "package main\n\nimport (\n\t\"time\"\n\n\t\"github.com/PalmStoneGames/polymer\"\n)\n\nfunc init() {\n\tpolymer.Register(\"tick-timer\", &Timer{})\n}\n\ntype Timer struct {\n\t*polymer.Proto\n\n\tTime time.Time `polymer:\"bind\"`\n}\n\nfunc (t *Timer) Created() {\n\tgo func() {\n\t\tfor {\n\t\t\tt.Time = time.Now()\n\n\t\t\tt.Notify(\"time\")\n\n\t\t\ttime.Sleep(time.Millisecond * 100)\n\t\t}\n\t}()\n}\n\n\n\nfunc main() {}\n\nfunc (t *Timer) ComputeTime() string ", "output": "{\n\treturn t.Time.String()\n}"} {"input": "package dialects\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\ntype Filter interface {\n\tDo(sql string) string\n}\n\n\ntype SeqFilter struct {\n\tPrefix string\n\tStart int\n}\n\nfunc convertQuestionMark(sql, prefix string, start int) string {\n\tvar buf strings.Builder\n\tvar beginSingleQuote bool\n\tvar index = start\n\tfor _, c := range sql {\n\t\tif !beginSingleQuote && c == '?' {\n\t\t\tbuf.WriteString(fmt.Sprintf(\"%s%v\", prefix, index))\n\t\t\tindex++\n\t\t} else {\n\t\t\tif c == '\\'' {\n\t\t\t\tbeginSingleQuote = !beginSingleQuote\n\t\t\t}\n\t\t\tbuf.WriteRune(c)\n\t\t}\n\t}\n\treturn buf.String()\n}\n\n\n\nfunc (s *SeqFilter) Do(sql string) string ", "output": "{\n\treturn convertQuestionMark(sql, s.Prefix, s.Start)\n}"} {"input": "package v1\n\nimport context \"context\"\n\nimport proto \"github.com/golang/protobuf/proto\"\nimport \"go-common/library/net/rpc/liverpc\"\n\nvar _ proto.Message \n\n\n\n\n\n\ntype CaptchaRPCClient interface {\n\tCreate(ctx context.Context, req *CaptchaCreateReq, opts ...liverpc.CallOption) (resp *CaptchaCreateResp, err error)\n}\n\n\n\n\n\ntype captchaRPCClient struct {\n\tclient *liverpc.Client\n}\n\n\n\n\nfunc (c *captchaRPCClient) Create(ctx context.Context, in *CaptchaCreateReq, opts ...liverpc.CallOption) (*CaptchaCreateResp, error) {\n\tout := new(CaptchaCreateResp)\n\terr := doRPCRequest(ctx, c.client, 1, \"Captcha.create\", in, out, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}\n\n\n\n\n\nfunc doRPCRequest(ctx context.Context, client *liverpc.Client, version int, method string, in, out proto.Message, opts []liverpc.CallOption) (err error) {\n\terr = client.Call(ctx, version, method, in, out, opts...)\n\treturn\n}\n\nfunc NewCaptchaRPCClient(client *liverpc.Client) CaptchaRPCClient ", "output": "{\n\treturn &captchaRPCClient{\n\t\tclient: client,\n\t}\n}"} {"input": "package assets\n\nimport (\n \"fmt\"\n\n \"github.com/iceburg-instance/database\"\n \"github.com/iceburg-instance/database/models/terrain\"\n)\n\ntype HeightData struct {\n HeightVals []terrain.HeightTuple\n}\n\n\n\n\n\nfunc GetHeight() (*HeightData, error) ", "output": "{\n\n \n \n qString := terrain.GetAllString()\n rows, err := database.Query(qString)\n if err != nil {\n fmt.Println(err)\n return nil, err\n }\n defer rows.Close()\n\n var heightSlice []terrain.HeightTuple\n var heightTuple terrain.HeightTuple\n\n for rows.Next() {\n heightTuple = terrain.HeightTuple{}\n if err := rows.Scan(&heightTuple.Id, &heightTuple.Height); err != nil {\n fmt.Println(err)\n return nil, err\n }\n heightSlice = append(heightSlice, heightTuple)\n }\n\n \n return &HeightData{HeightVals: heightSlice}, nil\n}"} {"input": "package blocker\n\nimport \"sort\"\n\ntype sources []string\n\nfunc (s *sources) Add(source string) {\n\tn := sort.SearchStrings(*s, source)\n\n\tif n < len(*s) && (*s)[n] == source {\n\t\treturn\n\t}\n\n\t*s = append(*s, \"\")\n\tcopy((*s)[n+1:], (*s)[n:])\n\t(*s)[n] = source\n}\n\nfunc (s *sources) Remove(source string) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tn := sort.SearchStrings(*s, source)\n\n\tif n < len(*s) && (*s)[n] == source {\n\t\t*s = append((*s)[:n], (*s)[n+1:]...)\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\n\nfunc (s *sources) Len() int {\n\treturn len(*s)\n}\n\nfunc newSources(s ...string) *sources {\n\tret := sources(s)\n\treturn &ret\n}\n\nfunc (s *sources) Has(source string) bool ", "output": "{\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tn := sort.SearchStrings(*s, source)\n\n\tif n < len(*s) && (*s)[n] == source {\n\t\treturn true\n\t}\n\n\treturn false\n}"} {"input": "package adal\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n)\n\nconst (\n\tactiveDirectoryAPIVersion = \"1.0\"\n)\n\n\n\ntype OAuthConfig struct {\n\tAuthorityEndpoint url.URL\n\tAuthorizeEndpoint url.URL\n\tTokenEndpoint url.URL\n\tDeviceCodeEndpoint url.URL\n}\n\n\nfunc (oac OAuthConfig) IsZero() bool {\n\treturn oac == OAuthConfig{}\n}\n\n\n\n\nfunc NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) {\n\tif err := validateStringParam(activeDirectoryEndpoint, \"activeDirectoryEndpoint\"); err != nil {\n\t\treturn nil, err\n\t}\n\tconst activeDirectoryEndpointTemplate = \"%s/oauth2/%s?api-version=%s\"\n\tu, err := url.Parse(activeDirectoryEndpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauthorityURL, err := u.Parse(tenantID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauthorizeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, \"authorize\", activeDirectoryAPIVersion))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttokenURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, \"token\", activeDirectoryAPIVersion))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdeviceCodeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, \"devicecode\", activeDirectoryAPIVersion))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &OAuthConfig{\n\t\tAuthorityEndpoint: *authorityURL,\n\t\tAuthorizeEndpoint: *authorizeURL,\n\t\tTokenEndpoint: *tokenURL,\n\t\tDeviceCodeEndpoint: *deviceCodeURL,\n\t}, nil\n}\n\nfunc validateStringParam(param, name string) error ", "output": "{\n\tif len(param) == 0 {\n\t\treturn fmt.Errorf(\"parameter '\" + name + \"' cannot be empty\")\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc createServer() error {\n\tc, err := getClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsb := c.NewServerBuilder()\n\tsb.Addr(\"127.0.0.1:8080\").HTTPBackend().MaxQPS(100)\n\n\tsb.CheckHTTPCode(\"/check/path\", time.Second*10, time.Second*30)\n\n\tsb.CircuitBreakerCheckPeriod(time.Second)\n\tsb.CircuitBreakerCloseToHalfTimeout(time.Second * 60)\n\tsb.CircuitBreakerHalfTrafficRate(10)\n\tsb.CircuitBreakerHalfToCloseCondition(2)\n\tsb.CircuitBreakerHalfToOpenCondition(90)\n\n\tid, err := sb.Commit()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"server id is: %d\", id)\n\n\tc.AddBind(1, id)\n\n\tc.RemoveBind(1, id)\n\n\tc.AddBind(2, id)\n\treturn nil\n}\n\nfunc updateServer(id uint64) error {\n\tc, err := getClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsvr, err := c.GetServer(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsb := c.NewServerBuilder()\n\tsb.Use(*svr)\n\n\tsb.MaxQPS(1000)\n\tsb.NoCircuitBreaker() \n\tsb.NoHeathCheck() \n\n\t_, err = sb.Commit()\n\treturn err\n}\n\n\n\nfunc deleteServer(id uint64) error ", "output": "{\n\tc, err := getClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.RemoveServer(id)\n}"} {"input": "package miniredis\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\nfunc assert(tb testing.TB, condition bool, msg string, v ...interface{}) {\n\ttb.Helper()\n\n\tif !condition {\n\t\ttb.Errorf(msg, v...)\n\t}\n}\n\n\n\n\n\nfunc equals(tb testing.TB, exp, act interface{}) {\n\ttb.Helper()\n\n\tif !reflect.DeepEqual(exp, act) {\n\t\ttb.Errorf(\"expected: %#v got: %#v\", exp, act)\n\t}\n}\n\n\nfunc mustFail(tb testing.TB, err error, want string) {\n\ttb.Helper()\n\n\tif err == nil {\n\t\ttb.Errorf(\"expected an error, but got a nil\")\n\t}\n\n\tif have := err.Error(); have != want {\n\t\ttb.Errorf(\"have %q, want %q\", have, want)\n\t}\n}\n\nfunc ok(tb testing.TB, err error) ", "output": "{\n\ttb.Helper()\n\n\tif err != nil {\n\t\ttb.Errorf(\"unexpected error: %s\", err.Error())\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n)\n\ntype Monitor interface {\n\tGetVariables() []string\n\tGetValues([]string) map[string]interface{}\n}\n\nvar monitorDrivers = make(map[string]func(*json.RawMessage) Monitor)\n\nfunc AddMonitorDriver(monitor string, constructor func(*json.RawMessage) Monitor) {\n\tmonitorDrivers[monitor] = constructor\n}\n\ntype MonitorTrack struct {\n\tVariables map[string]*MonitorTrackVariable\n\tInterval int\n\ttimer *time.Timer\n}\n\nfunc newMonitorTrack() *MonitorTrack {\n\treturn &MonitorTrack{\n\t\tVariables: make(map[string]*MonitorTrackVariable),\n\t}\n}\n\ntype MonitorTrackVariable struct {\n\tHistory int\n\tData []interface{}\n}\n\n\n\nfunc (mt *MonitorTrack) Start(monitor Monitor) {\n\tgo func() {\n\t\tmt.timer = time.NewTimer(time.Duration(1) * time.Second)\n\t\tfor _ = range mt.timer.C {\n\t\t\tif mt.Interval > 0 {\n\t\t\t\tmt.timer.Reset(time.Second * time.Duration(mt.Interval))\n\t\t\t}\n\t\t\tvariables := []string{}\n\t\t\tfor variable := range mt.Variables {\n\t\t\t\tvariables = append(variables, variable)\n\t\t\t}\n\t\t\tvalues := monitor.GetValues(variables)\n\t\t\tfor variable, vt := range mt.Variables {\n\t\t\t\tvt.Data = append(vt.Data, values[variable])\n\t\t\t\tif len(vt.Data) > vt.History {\n\t\t\t\t\tvt.Data = vt.Data[len(vt.Data)-vt.History:]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (mt *MonitorTrack) SetTrack(variable string, history int) ", "output": "{\n\ttrack, ok := mt.Variables[variable]\n\tif !ok && history > 0 {\n\t\ttrack = &MonitorTrackVariable{}\n\t\tmt.Variables[variable] = track\n\t}\n\tif history == 0 && ok {\n\t\tdelete(mt.Variables, variable)\n\t\treturn\n\t}\n\ttrack.History = history\n}"} {"input": "package cmd\n\nimport (\n\t\"errors\"\n\t\"os\"\n\n\t\"github.com/codegangsta/cli\"\n\n\t\"github.com/DevMine/srctool/config\"\n\t\"github.com/DevMine/srctool/log\"\n)\n\n\nfunc Delete(c *cli.Context) {\n\tif !c.Args().Present() {\n\t\tdeleteAll(c.Bool(\"dry\"))\n\t} else {\n\t\tif err := deleteParser(genParserName(c.Args().First()), c.Bool(\"dry\"), true); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}\n\n\n\nfunc deleteParser(parserName string, dryMode bool, verbose bool) error {\n\tparserPath := config.ParserPath(parserName)\n\n\tif _, err := os.Stat(parserPath); os.IsNotExist(err) {\n\t\tlog.Debug(err)\n\t\treturn errors.New(parserName + \" is not installed\")\n\t}\n\n\tif dryMode {\n\t\tlog.Info(\"parser path:\", parserPath)\n\t\treturn nil\n\t}\n\n\tlog.Debug(\"removing \", parserPath)\n\tif err := os.RemoveAll(parserPath); err != nil {\n\t\tlog.Debug(err)\n\t\treturn errors.New(\"failed to remove \" + parserName)\n\t}\n\n\tif verbose {\n\t\tlog.Success(parserName, \" successfully removed\")\n\t}\n\treturn nil\n}\n\nfunc deleteAll(dryMode bool) ", "output": "{\n\tparsers := getInstalledParsers()\n\tfor _, parser := range parsers {\n\t\tif err := deleteParser(genParserName(parser), dryMode, true); err != nil {\n\t\t\tlog.Fail(err)\n\t\t}\n\t}\n}"} {"input": "package router\n\nimport (\n\t\"net/http\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/ewhal/nyaa/db\"\n\t\"github.com/ewhal/nyaa/model\"\n\t\"github.com/ewhal/nyaa/service/captcha\"\n\t\"github.com/ewhal/nyaa/service/torrent\"\n\t\"github.com/ewhal/nyaa/util\"\n\t\"github.com/ewhal/nyaa/util/languages\"\n\t\"github.com/ewhal/nyaa/util/log\"\n\t\"github.com/gorilla/mux\"\n)\n\n\n\nfunc PostCommentHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tid := vars[\"id\"]\n\n\tuserCaptcha := captcha.Extract(r)\n\tif !captcha.Authenticate(userCaptcha) {\n\t\thttp.Error(w, \"bad captcha\", 403)\n\t}\n\tcurrentUser := GetUser(r)\n\tcontent := p.Sanitize(r.FormValue(\"comment\"))\n\n\tidNum_, err := strconv.Atoi(id)\n\tvar idNum uint = uint(idNum_)\n\tvar userId uint = 0\n\tif currentUser.Id > 0 {\n\t\tuserId = currentUser.Id\n\t}\n\tcomment := model.Comment{TorrentId: idNum, UserId: userId, Content: content, CreatedAt: time.Now()}\n\terr = db.ORM.Create(&comment).Error\n\tif err != nil {\n\t\tutil.SendError(w, err, 500)\n\t\treturn\n\t}\n\n\turl, err := Router.Get(\"view_torrent\").URL(\"id\", id)\n\tif err == nil {\n\t\thttp.Redirect(w, r, url.String(), 302)\n\t} else {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\nfunc ViewHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tvars := mux.Vars(r)\n\tid := vars[\"id\"]\n\n\ttorrent, err := torrentService.GetTorrentById(id)\n\tif err != nil {\n\t\tNotFoundHandler(w, r)\n\t\treturn\n\t}\n\tb := torrent.ToJson()\n\thtv := ViewTemplateVariables{b, captcha.Captcha{CaptchaID: captcha.GetID()}, NewSearchForm(), Navigation{}, GetUser(r), r.URL, mux.CurrentRoute(r)}\n\n\tlanguages.SetTranslationFromRequest(viewTemplate, r, \"en-us\")\n\terr = viewTemplate.ExecuteTemplate(w, \"index.html\", htv)\n\tif err != nil {\n\t\tlog.Errorf(\"ViewHandler(): %s\", err)\n\t}\n}"} {"input": "package model\n\nimport (\n\t\"go-common/app/service/main/archive/model/archive\"\n)\n\n\ntype ArcToView struct {\n\t*archive.Archive3\n\tPage *archive.Page3 `json:\"page,omitempty\"`\n\tCount int `json:\"count\"`\n\tCid int64 `json:\"cid\"`\n\tProgress int64 `json:\"progress\"`\n\tAddTime int64 `json:\"add_at\"`\n}\n\n\ntype WebArcToView struct {\n\t*archive.View3\n\tBangumiInfo *Bangumi `json:\"bangumi,omitempty\"`\n\tCid int64 `json:\"cid\"`\n\tProgress int64 `json:\"progress\"`\n\tAddTime int64 `json:\"add_at\"`\n}\n\n\ntype ToView struct {\n\tAid int64 `json:\"aid,omitempty\"`\n\tUnix int64 `json:\"now,omitempty\"`\n}\n\n\ntype ToViews []*ToView\n\nfunc (h ToViews) Len() int { return len(h) }\nfunc (h ToViews) Less(i, j int) bool { return h[i].Unix > h[j].Unix }\n\n\nfunc (h ToViews) Swap(i, j int) ", "output": "{ h[i], h[j] = h[j], h[i] }"} {"input": "package helpers\n\nimport (\n\t\"fmt\"\n\t\"gopkg.in/ini.v1\"\n\t\"runtime\"\n)\n\ntype Distro struct {\n\tFamily string \n\tInitSystem string \n\tVersion string \n}\n\n\n\n\n\nfunc (d *Distro) SetInitSystem() error {\n\n\tswitch d.Family {\n\tcase \"debian\":\n\t\td.InitSystem = \"systemd\" \n\tcase \"centos\":\n\t\td.InitSystem = \"sysv\"\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown Init system for distribution: %s\", d.Family)\n\t}\n\treturn nil\n}\n\n\n\nfunc GetDistro() (*Distro, error) {\n\td := Distro{}\n\tif runtime.GOOS == \"linux\" {\n\t\ti, err := ini.Load([]byte(\"\"), \"/etc/os-release\")\n\t\tsection, err := i.Section(\"\").GetKey(\"ID_LIKE\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = d.SetFamily(section.String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = d.SetInitSystem()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &d, nil\n}\n\nfunc (d *Distro) SetFamily(family string) error ", "output": "{\n\n\tswitch family {\n\tcase \"debian\":\n\t\td.Family = family\n\tcase \"centos\":\n\t\td.Family = family\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown Linux distribution: %s\", family)\n\t}\n\treturn nil\n}"} {"input": "package helper\n\nimport (\n\t\"bufio\"\n\t\"net\"\n)\n\ntype BufConn struct {\n\tnet.Conn\n\tBR *bufio.Reader\n}\n\nfunc (c *BufConn) Peek(n int) ([]byte, error) {\n\treturn c.BR.Peek(n)\n}\n\nfunc (c *BufConn) Read(b []byte) (n int, err error) {\n\treturn c.BR.Read(b)\n}\n\n\n\nfunc (c *BufConn) Reset(conn net.Conn) {\n\tc.Conn = conn\n}\n\nfunc NewBufConn(c net.Conn, r *bufio.Reader) *BufConn {\n\tconn := &BufConn{Conn: c}\n\tconn.BR = r\n\tif nil == r {\n\t\tconn.BR = bufio.NewReader(c)\n\t}\n\treturn conn\n}\n\nfunc (c *BufConn) Write(b []byte) (n int, err error) ", "output": "{\n\treturn c.Conn.Write(b)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\n\t\"gopkg.in/yaml.v1\"\n)\n\nconst (\n\tCONFIG_SUBDIR = \"mcmd\"\n\tDEFAULT_KNOWN_HOSTS_FILE = \"$HOME/.ssh/known_hosts\"\n)\n\ntype HostConfig struct {\n\tUser string\n\tPrivatekey string\n\tHosts []string\n}\n\nfunc loadConfig() HostConfig {\n\trawYaml := readHostfile()\n\tvar result HostConfig\n\terr := yaml.Unmarshal(rawYaml, &result)\n\tif err != nil {\n\t\terrLogger.Fatalln(\"Error parsing hostfile:\", err)\n\t}\n\treturn result\n}\n\n\n\nfunc getConfigLocationCandidates(configFileParam string) []string {\n\tconfigRoot, err := os.UserConfigDir()\n\tif err != nil {\n\t\terrLogger.Fatalf(\"no user config dir found\")\n\t}\n\tconfigDir := path.Join(configRoot, CONFIG_SUBDIR)\n\treturn []string{configFileParam,\n\t\tpath.Join(configDir, configFileParam+\".yml\"),\n\t\tpath.Join(configDir, configFileParam+\".yaml\")}\n}\n\nfunc exists(filename string) bool {\n\t_, err := os.Stat(filename)\n\treturn !os.IsNotExist(err)\n}\n\nfunc getContents(filename string) []byte {\n\tfileContents, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\terrLogger.Fatalln(err)\n\t}\n\treturn fileContents\n}\n\nfunc readHostfile() []byte ", "output": "{\n\tconfigFileParam := flag.Arg(0)\n\tfor _, file := range getConfigLocationCandidates(configFileParam) {\n\t\tif exists(file) {\n\t\t\treturn getContents(file)\n\t\t}\n\t}\n\terrLogger.Fatalf(\"hostfile %s not found\", configFileParam)\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/bitly/go-nsq\"\n\t\"log\"\n\t\"time\"\n)\n\nvar (\n\tPublisher *MsgPublisher\n)\n\ntype MsgPublisher struct {\n\tusr User\n\twriter *nsq.Writer\n}\n\nfunc init() {\n\tPublisher = &MsgPublisher{\n\t\twriter: nsq.NewWriter(\"106.186.31.48:4150\"),\n\t}\n}\n\nfunc (publisher *MsgPublisher) SetLoginUsr(_usr User) error {\n\tif Publisher == nil {\n\t\tPublisher = &MsgPublisher{\n\t\t\twriter: nsq.NewWriter(\"106.186.31.48:4150\"),\n\t\t}\n\t}\n\tPublisher.usr = _usr\n\tPublisher.usr.Pwd = \"xxxx\"\n\treturn nil\n}\n\n\n\nfunc (mp *MsgPublisher) WriteAsync(topic, msg string, responseChan chan *nsq.WriterTransaction) error {\n\tm := Message{\n\t\tTopic: topic,\n\t\tType: MSG_TYPE_CHAT,\n\t\tBody: MessageBody{\n\t\t\tFrom: mp.usr,\n\t\t\tMsg: msg,\n\t\t},\n\t}\n\tmsgBytes, _ := json.Marshal(m)\n\tlog.Println(\"PublishAsync.msg = \", string(msgBytes))\n\treturn mp.writer.PublishAsync(topic, msgBytes, responseChan, \"\")\n}\n\nfunc (mp *MsgPublisher) Stop() {\n\tmp.writer.Stop()\n}\n\nfunc (mp *MsgPublisher) Write(topic, msg string) (int32, []byte, error) ", "output": "{\n\tm := Message{\n\t\tTopic: topic,\n\t\tType: MSG_TYPE_CHAT,\n\t\tTime: time.Now().Format(\"2006-01-02 15:04:05\"),\n\t\tBody: MessageBody{\n\t\t\tFrom: mp.usr,\n\t\t\tMsg: msg,\n\t\t},\n\t}\n\tmsgBytes, _ := json.Marshal(m)\n\tlog.Println(\"Publish.msg = \", string(msgBytes))\n\treturn mp.writer.Publish(topic, msgBytes)\n}"} {"input": "package storage\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/rynorris/website/server/site\"\n\t\"github.com/rynorris/website/server/storage\"\n)\n\nconst dummyKey = \"site-configuration\"\n\ntype Service struct {\n\tstorage storage.Service\n}\n\nfunc NewService(storage storage.Service) *Service {\n\treturn &Service{\n\t\tstorage: storage,\n\t}\n}\n\n\n\nfunc (s *Service) Put(site site.Site) error {\n\tblob, err := json.Marshal(site)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.storage.Put(dummyKey, blob)\n}\n\nfunc (s *Service) Get() (site.Site, error) ", "output": "{\n\tsite := site.Site{}\n\n\tblob, err := s.storage.Get(dummyKey)\n\tif err != nil {\n\t\treturn site, err\n\t}\n\n\terr = json.Unmarshal(blob, &site)\n\n\treturn site, err\n}"} {"input": "package logger\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"gopkg.in/clever/kayvee-go.v2\"\n)\n\n\ntype M map[string]interface{}\n\n\nfunc Info(title string, data M) {\n\tlogWithLevel(title, kayvee.Info, data)\n}\n\n\nfunc Trace(title string, data M) {\n\tlogWithLevel(title, kayvee.Trace, data)\n}\n\n\n\n\n\nfunc Critical(title string, data M) {\n\tlogWithLevel(title, kayvee.Critical, data)\n}\n\n\nfunc Error(title string, err error) {\n\tlogWithLevel(title, kayvee.Error, M{\"error\": fmt.Sprint(err)})\n}\n\n\nfunc ErrorDetailed(title string, err error, extras M) {\n\textras[\"error\"] = fmt.Sprint(err)\n\tlogWithLevel(title, kayvee.Error, extras)\n}\n\nfunc logWithLevel(title string, level kayvee.LogLevel, data M) {\n\tformatted := kayvee.FormatLog(\"moredis\", level, title, data)\n\tlog.Println(formatted)\n}\n\nfunc Warning(title string, data M) ", "output": "{\n\tlogWithLevel(title, kayvee.Warning, data)\n}"} {"input": "package metrics\n\nimport (\n\t\"sync\"\n\n\tprom \"github.com/prometheus/client_golang/prometheus\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tsandboxGuageName = \"bundlelib_sandbox\"\n)\n\nvar (\n\tonce sync.Once\n\tcollector *Collector\n)\n\n\ntype Collector struct {\n\tSandbox prom.Gauge\n}\n\n\n\n\nfunc recoverMetricPanic() {\n\tif r := recover(); r != nil {\n\t\tlog.Errorf(\"Recovering from metric function - %v\", r)\n\t}\n}\n\n\n\nfunc RegisterCollector() {\n\tonce.Do(func() {\n\t\tcollector = &Collector{\n\t\t\tSandbox: prom.NewGauge(prom.GaugeOpts{\n\t\t\t\tName: sandboxGuageName,\n\t\t\t\tHelp: \"Guage of all sandbox namespaces that are active.\",\n\t\t\t}),\n\t\t}\n\n\t\terr := prom.Register(collector)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"unable to register collector with prometheus: %v\", err)\n\t\t}\n\t})\n}\n\n\n\n\n\nfunc SandboxDeleted() {\n\tdefer recoverMetricPanic()\n\tcollector.Sandbox.Dec()\n}\n\n\nfunc (c Collector) Describe(ch chan<- *prom.Desc) {\n\tc.Sandbox.Describe(ch)\n}\n\n\nfunc (c Collector) Collect(ch chan<- prom.Metric) {\n\tc.Sandbox.Collect(ch)\n}\n\nfunc SandboxCreated() ", "output": "{\n\tdefer recoverMetricPanic()\n\tcollector.Sandbox.Inc()\n}"} {"input": "package openstack\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gophercloud/gophercloud\"\n\ttokens2 \"github.com/gophercloud/gophercloud/openstack/identity/v2/tokens\"\n\ttokens3 \"github.com/gophercloud/gophercloud/openstack/identity/v3/tokens\"\n)\n\n\n\ntype ErrEndpointNotFound struct{ gophercloud.BaseError }\n\nfunc (e ErrEndpointNotFound) Error() string {\n\treturn \"No suitable endpoint could be found in the service catalog.\"\n}\n\n\n\ntype ErrInvalidAvailabilityProvided struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrInvalidAvailabilityProvided) Error() string {\n\treturn fmt.Sprintf(\"Unexpected availability in endpoint query: %s\", e.Value)\n}\n\n\n\ntype ErrMultipleMatchingEndpointsV2 struct {\n\tgophercloud.BaseError\n\tEndpoints []tokens2.Endpoint\n}\n\n\n\n\n\ntype ErrMultipleMatchingEndpointsV3 struct {\n\tgophercloud.BaseError\n\tEndpoints []tokens3.Endpoint\n}\n\nfunc (e ErrMultipleMatchingEndpointsV3) Error() string {\n\treturn fmt.Sprintf(\"Discovered %d matching endpoints: %#v\", len(e.Endpoints), e.Endpoints)\n}\n\n\n\ntype ErrNoAuthURL struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoAuthURL) Error() string {\n\treturn \"Environment variable OS_AUTH_URL needs to be set.\"\n}\n\n\n\ntype ErrNoUsername struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoUsername) Error() string {\n\treturn \"Environment variable OS_USERNAME needs to be set.\"\n}\n\n\n\ntype ErrNoPassword struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoPassword) Error() string {\n\treturn \"Environment variable OS_PASSWORD needs to be set.\"\n}\n\nfunc (e ErrMultipleMatchingEndpointsV2) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"Discovered %d matching endpoints: %#v\", len(e.Endpoints), e.Endpoints)\n}"} {"input": "package sandglass\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hashicorp/serf/serf\"\n\t\"github.com/sandglass/sandglass-grpc/go/sgproto\"\n\t\"google.golang.org/grpc\"\n)\n\ntype Node struct {\n\tID string\n\tName string\n\tIP string\n\tGRPCAddr string\n\tRAFTAddr string\n\tHTTPAddr string\n\tStatus serf.MemberStatus\n\tconn *grpc.ClientConn\n\tsgproto.BrokerServiceClient\n\tsgproto.InternalServiceClient\n}\n\nfunc (n *Node) Dial() (err error) {\n\tn.conn, err = grpc.Dial(n.GRPCAddr, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn err\n\t}\n\tn.BrokerServiceClient = sgproto.NewBrokerServiceClient(n.conn)\n\tn.InternalServiceClient = sgproto.NewInternalServiceClient(n.conn)\n\n\treturn nil\n}\n\nfunc (n *Node) Close() error {\n\tif n.conn == nil {\n\t\treturn nil\n\t}\n\tif err := n.conn.Close(); err != nil {\n\t\treturn err\n\t}\n\tn.conn = nil\n\treturn nil\n}\n\nfunc (n *Node) String() string {\n\treturn fmt.Sprintf(\"%s(%s)\", n.Name, n.GRPCAddr)\n}\n\n\n\nfunc (n *Node) IsAlive() bool ", "output": "{\n\treturn n.conn != nil\n}"} {"input": "package gorm\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"github.com/jinzhu/gorm\"\n)\n\n\ntype GR struct {\n\tDB *gorm.DB\n\tServerInfo \n}\n\n\n\ntype ServerInfo struct {\n\thost string\n\tport uint16\n\tdbname string\n\tuser string\n\tpass string\n}\n\nvar dbInfo GR\n\n\nfunc New(host, dbname, user, pass string, port uint16) error {\n\n\tvar err error\n\tif dbInfo.DB == nil {\n\t\tdbInfo.host = host\n\t\tdbInfo.port = port\n\t\tdbInfo.dbname = dbname\n\t\tdbInfo.user = user\n\t\tdbInfo.pass = pass\n\n\t\tdbInfo.DB, err = dbInfo.Connection()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc GetDB() *GR {\n\tif dbInfo.DB == nil {\n\t\tpanic(errors.New(\"DB instance is nil\"))\n\t}\n\treturn &dbInfo\n}\n\n\n\n\n\nfunc (gr *GR) Connection() (*gorm.DB, error) {\n\treturn gorm.Open(\"mysql\", gr.getDsn())\n}\n\n\nfunc (gr *GR) Close() {\n\tgr.DB.Close()\n}\n\nfunc (gr *GR) getDsn() string ", "output": "{\n\tparam := \"?charset=utf8&parseTime=True&loc=Local\"\n\treturn fmt.Sprintf(\"%s:%s@tcp(%s:%d)/%s%s\",\n\t\tgr.user, gr.pass, gr.host, gr.port, gr.dbname, param)\n}"} {"input": "package cluster_health\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\tmbtest \"github.com/elastic/beats/metricbeat/mb/testing\"\n)\n\nfunc TestData(t *testing.T) {\n\tf := mbtest.NewEventFetcher(t, getConfig())\n\terr := mbtest.WriteEvent(f, t)\n\tif err != nil {\n\t\tt.Fatal(\"write\", err)\n\t}\n}\n\nfunc getConfig() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"module\": \"ceph\",\n\t\t\"metricsets\": []string{\"cluster_health\"},\n\t\t\"hosts\": getTestCephHost(),\n\t}\n}\n\nconst (\n\tcephDefaultHost = \"127.0.0.1\"\n\tcephDefaultPort = \"5000\"\n)\n\nfunc getTestCephHost() string {\n\treturn fmt.Sprintf(\"%v:%v\",\n\t\tgetenv(\"CEPH_HOST\", cephDefaultHost),\n\t\tgetenv(\"CEPH_PORT\", cephDefaultPort),\n\t)\n}\n\nfunc getenv(name, defaultValue string) string {\n\treturn strDefault(os.Getenv(name), defaultValue)\n}\n\n\n\nfunc strDefault(a, defaults string) string ", "output": "{\n\tif len(a) == 0 {\n\t\treturn defaults\n\t}\n\treturn a\n}"} {"input": "package config\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\n\t\"github.com/hauke96/sigolo\"\n)\n\n\n\n\n\n\ntype ConfigLoader struct {\n\ttopicConfig *TopicConfig\n\tserverConfig *ServerConfig\n}\n\n\n\nfunc (cl *ConfigLoader) loadTopics(filename string) {\n\tdata, err := ioutil.ReadFile(filename)\n\n\tif err != nil {\n\t\tsigolo.Error(\"Error reading \" + filename)\n\t\tsigolo.Error(\"\\n\\nAhhh, *urg*, I'm sorry but there was a really bad error inside of me. Above the stack trace is a message marked with [FATAL], you'll find some information there.\\nIf not, feel free to contact my maker via:\\n\\n goms@hauke-stieler.de\\n\\nI hope my death .. . eh ... crash is only an exception and will be fixed soon ... my power ... leaves me ... good bye ... x.x\")\n\t\tsigolo.Error(err.Error())\n\t}\n\n\tcl.topicConfig = &TopicConfig{}\n\tjson.Unmarshal(data, cl.topicConfig)\n}\n\n\n\n\n\n\nfunc (cl *ConfigLoader) GetConfig() Config {\n\treturn Config{\n\t\tTopicConfig: *cl.topicConfig,\n\t\tServerConfig: *cl.serverConfig,\n\t}\n}\n\nfunc (cl *ConfigLoader) LoadConfig(filename string) ", "output": "{\n\tdata, err := ioutil.ReadFile(filename)\n\n\tif err != nil {\n\t\tsigolo.Error(\"Error reading \" + filename)\n\t\tsigolo.Error(\"\\n\\nAhhh, *urg*, I'm sorry but there was a really bad error inside of me. Above the stack trace is a message marked with [FATAL], you'll find some information there.\\nIf not, feel free to contact my maker via:\\n\\n goms@hauke-stieler.de\\n\\nI hope my death .. . eh ... crash is only an exception and will be fixed soon ... my power ... leaves me ... good bye ... x.x\")\n\t\tsigolo.Fatal(err.Error())\n\t}\n\n\tcl.serverConfig = &ServerConfig{}\n\tjson.Unmarshal(data, cl.serverConfig)\n\n\tcl.loadTopics(cl.serverConfig.TopicLocation)\n}"} {"input": "package rancher\n\nimport (\n\t\"github.com/Sirupsen/logrus\"\n\n\t\"github.com/docker/libcompose/logger\"\n\t\"github.com/docker/libcompose/lookup\"\n\t\"github.com/docker/libcompose/project\"\n)\n\n\n\nfunc NewProject(context *Context) (*project.Project, error) ", "output": "{\n\tcontext.ConfigLookup = &lookup.FileConfigLookup{}\n\tcontext.EnvironmentLookup = &lookup.OsEnvLookup{}\n\tcontext.LoggerFactory = logger.NewColorLoggerFactory()\n\tcontext.ServiceFactory = &RancherServiceFactory{\n\t\tContext: context,\n\t}\n\n\tp := project.NewProject(&context.Context)\n\n\terr := p.Parse()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = context.open(); err != nil {\n\t\tlogrus.Errorf(\"Failed to open project %s: %v\", p.Name, err)\n\t\treturn nil, err\n\t}\n\n\tcontext.SidekickInfo = NewSidekickInfo(p)\n\n\treturn p, err\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/coreos/etcd/client\"\n)\n\nconst (\n\tExitSuccess = iota\n\tExitError\n\tExitBadConnection\n\tExitInvalidInput \n\tExitBadFeature \n\tExitInterrupted\n\tExitIO\n\tExitBadArgs = 128\n)\n\n\n\nfunc ExitWithError(code int, err error) ", "output": "{\n\tfmt.Fprintln(os.Stderr, \"Error:\", err)\n\tif cerr, ok := err.(*client.ClusterError); ok {\n\t\tfmt.Fprintln(os.Stderr, cerr.Detail())\n\t}\n\tos.Exit(code)\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/fatih/color\"\n\tout \"github.com/plouc/go-gitlab-client/cli/output\"\n\t\"github.com/plouc/go-gitlab-client/gitlab\"\n\t\"github.com/spf13/cobra\"\n)\n\n\n\nfunc fetchSshKeys() {\n\tcolor.Yellow(\"Fetching current user ssh keys…\")\n\n\to := &gitlab.PaginationOptions{}\n\to.Page = page\n\to.PerPage = perPage\n\n\tloader.Start()\n\tcollection, meta, err := client.CurrentUserSshKeys(o)\n\tloader.Stop()\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\n\tif len(collection.Items) == 0 {\n\t\tcolor.Red(\"No ssh key found\")\n\t} else {\n\t\tout.SshKeys(output, outputFormat, collection)\n\t}\n\n\tprintMeta(meta, true)\n\n\thandlePaginatedResult(meta, fetchSshKeys)\n}\n\nvar listSshKeysCmd = &cobra.Command{\n\tUse: \"ssh-keys\",\n\tAliases: []string{\"sk\"},\n\tShort: \"List current user ssh keys\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tfetchSshKeys()\n\t},\n}\n\nfunc init() ", "output": "{\n\tlistCmd.AddCommand(listSshKeysCmd)\n}"} {"input": "package tests\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"github.com/google/go-github/github\"\n\t\"golang.org/x/oauth2\"\n)\n\nvar (\n\tclient *github.Client\n\n\tauth bool\n)\n\nfunc init() {\n\ttoken := os.Getenv(\"GITHUB_AUTH_TOKEN\")\n\tif token == \"\" {\n\t\tprint(\"!!! No OAuth token. Some tests won't run. !!!\\n\\n\")\n\t\tclient = github.NewClient(nil)\n\t} else {\n\t\ttc := oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(\n\t\t\t&oauth2.Token{AccessToken: token},\n\t\t))\n\t\tclient = github.NewClient(tc)\n\t\tauth = true\n\t}\n\n\tvars := []string{envKeyGitHubUsername, envKeyGitHubPassword, envKeyClientID, envKeyClientSecret}\n\n\tfor _, v := range vars {\n\t\tvalue := os.Getenv(v)\n\t\tif value == \"\" {\n\t\t\tprint(\"!!! \" + fmt.Sprintf(msgEnvMissing, v) + \" !!!\\n\\n\")\n\t\t}\n\t}\n\n}\n\nfunc checkAuth(name string) bool {\n\tif !auth {\n\t\tfmt.Printf(\"No auth - skipping portions of %v\\n\", name)\n\t}\n\treturn auth\n}\n\n\n\nfunc createRandomTestRepository(owner string, autoinit bool) (*github.Repository, error) ", "output": "{\n\tvar repoName string\n\tfor {\n\t\trepoName = fmt.Sprintf(\"test-%d\", rand.Int())\n\t\t_, resp, err := client.Repositories.Get(owner, repoName)\n\t\tif err != nil {\n\t\t\tif resp.StatusCode == http.StatusNotFound {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\trepo, _, err := client.Repositories.Create(\"\", &github.Repository{Name: github.String(repoName), AutoInit: github.Bool(autoinit)})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn repo, nil\n}"} {"input": "package assets\n\nimport (\n\t\"fmt\"\n)\n\nconst (\n\tanalyticsScript = ``\n)\n\n\n\nfunc init() {\n\tRegister(\"analytics\", googleAnalytics)\n}\n\nfunc googleAnalytics(m *Manager, names []string, options Options) ([]*Asset, error) ", "output": "{\n\tif len(names) != 1 && len(names) != 2 {\n\t\treturn nil, fmt.Errorf(\"analytics requires either 1 or 2 arguments (either \\\"UA-XXXXXX-YY, mysite.com\\\" or just \\\"UA-XXXXXX-YY\\\" - without quotes in both cases\")\n\t}\n\tkey := names[0]\n\tif key == \"\" {\n\t\treturn nil, nil\n\t}\n\tvar arg string\n\tif len(names) == 2 {\n\t\targ = fmt.Sprintf(\"'%s', '%s'\", key, names[1])\n\t} else {\n\t\targ = fmt.Sprintf(\"'%s'\", key)\n\t}\n\treturn []*Asset{\n\t\t&Asset{\n\t\t\tName: \"google-analytics.js\",\n\t\t\tPosition: Bottom,\n\t\t\tHTML: fmt.Sprintf(analyticsScript, arg),\n\t\t},\n\t}, nil\n}"} {"input": "package conway\n\nimport (\n\t\"fmt\"\n)\n\nfunc Example_singleCell() {\n\tvar p = Population{cells: map[Cell]int{\n\t\tCell{0, 0}: 0,\n\t},\n\t\tpopNumber: 0,\n\t}\n\tp.Next()\n\tfmt.Println(p)\n}\n\nfunc Example_twoCells() {\n\tvar p = Population{cells: map[Cell]int{\n\t\tCell{0, 0}: 0,\n\t\tCell{0, 1}: 0,\n\t},\n\t\tpopNumber: 0,\n\t}\n\tp.Next()\n\tfmt.Println(p)\n}\n\n\n\nfunc Example_blinker() ", "output": "{\n\tvar p = Population{cells: map[Cell]int{\n\t\tCell{0, 0}: 0,\n\t\tCell{0, 1}: 0,\n\t\tCell{0, -1}: 0,\n\t},\n\t\tpopNumber: 0,\n\t}\n\tp.SaveToFile(\"blinker0.log\")\n\tp.Next()\n\tp.SaveToFile(\"blinker1.log\")\n\tfmt.Println(len(p.cells))\n}"} {"input": "package handle\n\nimport (\n \n \"net/http\"\n)\n\n\ntype HTTPErrorPipeline struct {\n Code int\n Message string\n Global GlobalPipeline\n}\n\n\n\n\n\nfunc ReturnError(w http.ResponseWriter, code int) int {\n w.WriteHeader(code)\n tpl, _ := OpenTemplate(ERROR_TPL)\n tpl.Execute(w, NewError(code, http.StatusText(code)))\n return code\n}\n\nfunc NewError(code int, message string) HTTPErrorPipeline ", "output": "{\n return HTTPErrorPipeline{\n Code: code,\n Message: message,\n Global: DefaultGlobalPipeline,\n }\n}"} {"input": "package rest\n\n\ntype Method int\n\nconst (\n\tGET Method = 1 + iota\n\tPOST\n\tPUT\n\tDELETE\n)\n\nvar method = [...]string{\n\t\"GET\",\n\t\"POST\",\n\t\"PUT\",\n\t\"DELETE\",\n}\n\n\n\nfunc (m Method) String() string ", "output": "{ return method[m-1] }"} {"input": "package commons\n\nimport \"net/http\"\n\n\n\nfunc HttpUnauthorized(w http.ResponseWriter) {\n\tHttpError(w, http.StatusUnauthorized)\n}\n\nfunc HttpBadRequest(w http.ResponseWriter) {\n\tHttpError(w, http.StatusBadRequest)\n}\n\nfunc HttpError(w http.ResponseWriter, code int) {\n\thttp.Error(w, http.StatusText(code), code)\n}\n\nfunc HttpCheckError(err error, status int, w http.ResponseWriter) {\n\tif err != nil {\n\t\tHttpError(w, status)\n\t}\n}\n\nfunc HttpNoContent(w http.ResponseWriter) ", "output": "{\n\tHttpError(w, http.StatusNoContent)\n}"} {"input": "package etcd2\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/coreos/etcd/client\"\n\t\"golang.org/x/net/context\"\n)\n\n\ntype Etcd2Connect struct {\n\tetcd2 client.Client\n}\n\n\nfunc NewEtcd2Connect(etcd2EndPoint string) (*Etcd2Connect, error) {\n\tc, err := client.New(client.Config{\n\t\tEndpoints: []string{fmt.Sprintf(\"http://%s\", etcd2EndPoint)},\n\t\tTransport: client.DefaultTransport,\n\t\tHeaderTimeoutPerRequest: time.Second,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Etcd2Connect{etcd2: c}, nil\n}\n\n\nfunc (e *Etcd2Connect) Set(data map[string]string) error {\n\tkapi := client.NewKeysAPI(e.etcd2)\n\tfor k, v := range data {\n\t\tif _, err := kapi.Set(context.Background(), k, v, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (e *Etcd2Connect) Get(data map[string]string) (map[string]string, error) {\n\tkapi := client.NewKeysAPI(e.etcd2)\n\tresult := make(map[string]string)\n\tfor k := range data {\n\t\tresp, err := kapi.Get(context.Background(), k, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult[k] = resp.Node.Value\n\t}\n\treturn result, nil\n}\n\nfunc (e *Etcd2Connect) Make(data map[string]string) error ", "output": "{\n\tkapi := client.NewKeysAPI(e.etcd2)\n\topts := &client.SetOptions{PrevExist: client.PrevNoExist}\n\tfor k, v := range data {\n\t\tif _, err := kapi.Set(context.Background(), k, v, opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/APTrust/bagman/bagman\"\n\t\"github.com/APTrust/bagman/workers\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\n\nfunc main() {\n\tjsonFile := flag.String(\"file\", \"\", \"JSON file to load\")\n\tprocUtil := workers.CreateProcUtil(\"aptrust\")\n\tprocUtil.MessageLog.Info(\"apt_retry started\")\n\tbagRecorder := workers.NewBagRecorder(procUtil)\n\n\tif jsonFile == nil {\n\t\tfmt.Println(\"apt_retry tries to re-send metadata to Fluctus\")\n\t\tfmt.Println(\"Usage: apt_retry -file=path/to/file.json -config=some_config\")\n\t\tos.Exit(0)\n\t}\n\tfmt.Println(*jsonFile)\n\tresult := loadJsonFile(*jsonFile)\n\tresult.ErrorMessage = \"\"\n\tbagRecorder.RunWithoutNsq(result)\n}\n\n\n\nfunc loadJsonFile(jsonFile string) (*bagman.ProcessResult) ", "output": "{\n\tbytes, err := ioutil.ReadFile(jsonFile)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Cannot read file '%s': %v\\n\", jsonFile, err)\n\t\tos.Exit(1)\n\t}\n\tvar result bagman.ProcessResult\n\terr = json.Unmarshal(bytes, &result)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Cannot convert JSON to object: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\treturn &result\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/spf13/viper\"\n)\n\ntype writeStdout struct {\n}\n\n\nfunc (s *writeStdout) Write(dirname, filename, content, contentType, contentEncoding string,\n\tmetadata map[string]*string) error {\n\tfmt.Printf(\"--- %s/%s ---\\n\", dirname, filename)\n\tfmt.Printf(\"%s\\n\", content)\n\treturn nil\n}\n\n\n\n\nfunc NewWriteStdout(cfg *viper.Viper) (interface{}, error) ", "output": "{\n\treturn &writeStdout{}, nil\n}"} {"input": "package even\n\n\n\nfunc Even(i int) bool ", "output": "{ \n\treturn i%2 == 0\n}"} {"input": "package fabric\n\n\nfunc contains(s []DGNode, i DGNode) bool {\n\tfor _, v := range s {\n\t\tif i.ID() == v.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\nfunc ContainsNode(l NodeList, n Node) bool {\n\tfor _, v := range l {\n\t\tif v.ID() == n.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc ContainsEdge(l EdgeList, e Edge) bool {\n\tfor _, v := range l {\n\t\tif v.ID() == e.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc containsVirtual(s []Virtual, i Virtual) bool ", "output": "{\n\tfor _, v := range s {\n\t\tif i.ID() == v.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n\t\"time\"\n\n\tgetter \"github.com/hashicorp/go-getter\"\n\t\"github.com/hashicorp/nomad/helper/discover\"\n)\n\n\nfunc fetchBinary(bin string) (string, error) {\n\tnomadBinaryDir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create temp dir: %v\", err)\n\t}\n\n\tif bin == \"\" {\n\t\tbin, err = discover.NomadExecutable()\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to discover nomad binary: %v\", err)\n\t\t}\n\t}\n\n\tdest := path.Join(nomadBinaryDir, \"nomad\")\n\tif runtime.GOOS == \"windows\" {\n\t\tdest = dest + \".exe\"\n\t}\n\n\tif err = getter.GetFile(dest, bin); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get nomad binary: %v\", err)\n\t}\n\n\treturn nomadBinaryDir, nil\n}\n\n\n\nfunc procWaitTimeout(p *os.Process, d time.Duration) error ", "output": "{\n\tstop := make(chan struct{})\n\n\tgo func() {\n\t\tp.Wait()\n\t\tstop <- struct{}{}\n\t}()\n\n\tselect {\n\tcase <-stop:\n\t\treturn nil\n\tcase <-time.NewTimer(d).C:\n\t\treturn fmt.Errorf(\"timeout waiting for process %d to exit\", p.Pid)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\ntype ListOfInt []int\n\ntype IntMonad struct {\n\tNeutralElement int\n\tAssocFunc func(int, int) int\n}\n\n\n\n\n\nfunc main() {\n\tvar list = ListOfInt{-2, -1, 2, 2, 3}\n\n\tmonad := IntMonad{0, func(x, y int) int { return x + y }}\n\n\tfmt.Printf(\"List %v: Fold(monad) yields %v\\n\", list, list.Fold(monad))\n}\n\nfunc (list ListOfInt) Fold(monad IntMonad) int ", "output": "{\n\tout := monad.NeutralElement\n\tfor _, i := range list {\n\t\tout = monad.AssocFunc(out, i)\n\t}\n\treturn out\n}"} {"input": "package datasource\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/golang/glog\"\n\tcadvisorClient \"github.com/google/cadvisor/client\"\n\tcadvisor \"github.com/google/cadvisor/info/v1\"\n\t\"k8s.io/heapster/sources/api\"\n)\n\ntype cadvisorSource struct{}\n\n\n\nfunc (self *cadvisorSource) getAllContainers(client *cadvisorClient.Client, start, end time.Time) (subcontainers []*api.Container, root *api.Container, err error) {\n\tallContainers, err := client.SubcontainersInfo(\"/\",\n\t\t&cadvisor.ContainerInfoRequest{Start: start, End: end})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfor _, containerInfo := range allContainers {\n\t\tcontainer := self.parseStat(&containerInfo)\n\t\tif containerInfo.Name == \"/\" {\n\t\t\troot = container\n\t\t} else {\n\t\t\tsubcontainers = append(subcontainers, container)\n\t\t}\n\t}\n\n\treturn subcontainers, root, nil\n}\n\nfunc (self *cadvisorSource) GetAllContainers(host Host, start, end time.Time) (subcontainers []*api.Container, root *api.Container, err error) {\n\turl := fmt.Sprintf(\"http:%s:%d/\", host.IP, host.Port)\n\tclient, err := cadvisorClient.NewClient(url)\n\tif err != nil {\n\t\treturn\n\t}\n\tsubcontainers, root, err = self.getAllContainers(client, start, end)\n\tif err != nil {\n\t\tglog.Errorf(\"failed to get stats from cadvisor %q - %v\\n\", url, err)\n\t}\n\treturn\n}\n\nfunc (self *cadvisorSource) parseStat(containerInfo *cadvisor.ContainerInfo) *api.Container ", "output": "{\n\tcontainer := &api.Container{\n\t\tName: containerInfo.Name,\n\t\tSpec: containerInfo.Spec,\n\t\tStats: sampleContainerStats(containerInfo.Stats),\n\t}\n\tif len(containerInfo.Aliases) > 0 {\n\t\tcontainer.Name = containerInfo.Aliases[0]\n\t}\n\n\treturn container\n}"} {"input": "package indexdb\n\nimport (\n\t\"fmt\"\n\t\"github.com/eleme/banshee/models\"\n\t\"github.com/eleme/banshee/util\"\n)\n\n\nfunc encode(idx *models.Index) []byte {\n\tscore := util.ToFixed(idx.Score, 5)\n\taverage := util.ToFixed(idx.Average, 5)\n\ts := fmt.Sprintf(\"%d:%s:%s\", idx.Stamp, score, average)\n\treturn []byte(s)\n}\n\n\n\n\nfunc decode(value []byte, idx *models.Index) error ", "output": "{\n\tn, err := fmt.Sscanf(string(value), \"%d:%f:%f\", &idx.Stamp, &idx.Score, &idx.Average)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n != 3 {\n\t\treturn ErrCorrupted\n\t}\n\treturn nil\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"testing\"\n\n\t\"github.com/gorilla/websocket\"\n)\n\n\n\n\n\nfunc TestWsHandler(t *testing.T) {\n\texpectedResponse := []byte(\"acknowledged\")\n\n\tserver := httptest.NewServer(serverEngine())\n\tdefer server.Close()\n\n\tURL, err := url.Parse(server.URL + \"/ws\")\n\tif err != nil {\n\t\tt.Errorf(\"could not parse server URL: %s\", err)\n\t}\n\n\tURL.Scheme = \"ws\"\n\n\tconn, _, err := websocket.DefaultDialer.Dial(URL.String(), nil)\n\tif err != nil {\n\t\tt.Errorf(\"expected to create websocket connection with success instead: %s\", err)\n\t}\n\n\tif err := conn.WriteMessage(websocket.TextMessage, []byte(\"test\")); err != nil {\n\t\tt.Errorf(\"could not write message: %s\", err)\n\t}\n\n\t_, observed, err := conn.ReadMessage()\n\tif err != nil {\n\t\tt.Errorf(\"cannot read message: %v\", err)\n\t}\n\n\tif string(observed) != string(expectedResponse) {\n\t\tt.Errorf(\"expected server response: %s, observed: %s\",\n\t\t\tstring(expectedResponse), string(observed))\n\t}\n}\n\nfunc TestIndexHandler(t *testing.T) ", "output": "{\n\tserver := httptest.NewServer(serverEngine())\n\tdefer server.Close()\n\n\tresp, err := http.Get(server.URL)\n\tif err != nil {\n\t\tt.Errorf(\"could not make get request to server\")\n\t}\n\n\texpectedStatus := 200\n\tif resp.StatusCode != expectedStatus {\n\t\tt.Errorf(\"expected status code: %d, observed: %d\",\n\t\t\tresp.StatusCode, expectedStatus)\n\t}\n}"} {"input": "package service\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"go-common/app/service/main/assist/conf\"\n\t\"go-common/app/service/main/assist/dao/account\"\n\t\"go-common/app/service/main/assist/dao/assist\"\n\t\"go-common/app/service/main/assist/dao/message\"\n\t\"go-common/library/log\"\n\t\"go-common/library/queue/databus\"\n)\n\n\ntype Service struct {\n\tc *conf.Config\n\tass *assist.Dao\n\tacc *account.Dao\n\tmsg *message.Dao\n\trelationSub *databus.Databus\n\tcacheChan chan func()\n\twg sync.WaitGroup\n}\n\n\n\n\n\nfunc (s *Service) Ping(c context.Context) (err error) {\n\tif err = s.ass.Ping(c); err != nil {\n\t\tlog.Error(\"s.ass.Dao.Ping err(%v)\", err)\n\t}\n\treturn\n}\n\n\nfunc (s *Service) asyncCache(f func()) {\n\tselect {\n\tcase s.cacheChan <- f:\n\tdefault:\n\t\tlog.Warn(\"assist cacheproc chan full\")\n\t}\n}\n\n\nfunc (s *Service) cacheproc() {\n\tfor {\n\t\tf := <-s.cacheChan\n\t\tf()\n\t}\n}\n\n\nfunc (s *Service) Close() {\n\ts.relationSub.Close()\n\ts.wg.Wait()\n}\n\nfunc New(c *conf.Config) *Service ", "output": "{\n\ts := &Service{\n\t\tc: c,\n\t\tass: assist.New(c),\n\t\tacc: account.New(c),\n\t\tmsg: message.New(c),\n\t\tcacheChan: make(chan func(), 1024),\n\t\trelationSub: databus.New(c.RelationSub),\n\t}\n\ts.wg.Add(1)\n\tgo s.relationConsumer()\n\ts.wg.Add(1)\n\tgo s.cacheproc()\n\treturn s\n}"} {"input": "package instructions\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/bongo227/goory/types\"\n\n\t\"github.com/bongo227/goory/value\"\n)\n\n\ntype CondBr struct {\n\tblock value.Value\n\tname string\n\tcondition value.Value\n\ttrueBlock value.Value\n\tfalseBlock value.Value\n}\n\nfunc NewCondBr(block value.Value, name string, condition value.Value, trueBlock value.Value, falseBlock value.Value) *CondBr {\n\tif !condition.Type().Equal(types.NewBoolType()) {\n\t\tpanic(\"condition is not a bool type\")\n\t}\n\n\tif !trueBlock.Type().Equal(types.NewBlockType()) {\n\t\tpanic(\"trueBlock is not a block type\")\n\t}\n\n\tif !falseBlock.Type().Equal(types.NewBlockType()) {\n\t\tpanic(\"falseBlock is not a block type\")\n\t}\n\n\treturn &CondBr{block, name, condition, trueBlock, falseBlock}\n}\n\nfunc (i *CondBr) Block() value.Value {\n\treturn i.block\n}\n\nfunc (i *CondBr) IsTerminator() bool {\n\treturn true\n}\n\n\n\nfunc (i *CondBr) Ident() string {\n\treturn \"%\" + i.name\n}\n\nfunc (i *CondBr) Llvm() string {\n\treturn fmt.Sprintf(\"br i1 %s, label %%%s, label %%%s\",\n\t\ti.condition.Ident(),\n\t\ti.trueBlock.Ident(),\n\t\ti.falseBlock.Ident())\n}\n\nfunc (i *CondBr) Type() types.Type ", "output": "{\n\treturn types.VOID\n}"} {"input": "package bsu\n\nimport (\n\t\"crypto/tls\"\n\t\"net/http\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/packer/builder/osc/common\"\n\tbuilderT \"github.com/hashicorp/packer/helper/builder/testing\"\n\t\"github.com/outscale/osc-go/oapi\"\n)\n\nfunc TestBuilderAcc_basic(t *testing.T) {\n\tbuilderT.Test(t, builderT.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tBuilder: &Builder{},\n\t\tTemplate: testBuilderAccBasic,\n\t\tSkipArtifactTeardown: true,\n\t})\n}\n\nfunc testAccPreCheck(t *testing.T) {\n}\n\n\n\nconst testBuilderAccBasic = `\n{\n\t\"builders\": [{\n\t\t\"type\": \"test\",\n\t\t\"region\": \"eu-west-2\",\n\t\t\"vm_type\": \"t2.micro\",\n\t\t\"source_omi\": \"ami-65efcc11\",\n\t\t\"ssh_username\": \"outscale\",\n\t\t\"omi_name\": \"packer-test {{timestamp}}\"\n\t}]\n}\n`\n\nfunc testOAPIConn() (*oapi.Client, error) ", "output": "{\n\taccess := &common.AccessConfig{RawRegion: \"us-east-1\"}\n\tclientConfig, err := access.Config()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tskipClient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t}\n\n\treturn oapi.NewClient(clientConfig, skipClient), nil\n}"} {"input": "package app\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\ntype collect struct{\n\turl string\n\tcontroller func(w http.ResponseWriter, r *http.Request) bool\n}\n\nfunc render(w http.ResponseWriter, r *http.Request){\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\troutes := Routes()\n\turl := r.URL.Path\n\tfor _, element := range routes{\n\t\tif url == element.url {\n\t\t\telement.controller(w, r)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Fprintf(w, \"

Error 404

\")\n}\n\nfunc api(w http.ResponseWriter, r *http.Request){\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\troutes := Routes()\n\turl := r.URL.Path\n\tfor _, element := range routes{\n\t\tif url == element.url {\n\t\t\telement.controller(w, r)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Fprintf(w, \"{\\\"error\\\":true}\")\n}\n\n\n\nfunc Server(port int, host string)", "output": "{\n\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc( \"/\" , func(w http.ResponseWriter, r *http.Request){\n\t\trender(w, r)\n\t})\n\tmux.HandleFunc( \"/api/\" , func(w http.ResponseWriter, r *http.Request){\n\t\tapi(w, r)\n\t})\n\n\tprintln( fmt.Sprintf(\"Starting exodo server on port %d\", port))\n http.ListenAndServe(fmt.Sprintf(\"%s:%d\",host, port), mux)\n}"} {"input": "package engine\n\nimport (\n\t\"time\"\n\n\t\"github.com/aws/amazon-ecs-agent/agent/api\"\n)\n\n\n\ntype impossibleTransitionError struct {\n\tstate api.ContainerStatus\n}\n\nfunc (err *impossibleTransitionError) Error() string {\n\treturn \"Cannot transition to \" + err.state.String()\n}\nfunc (err *impossibleTransitionError) ErrorName() string { return \"ImpossibleStateTransitionError\" }\n\ntype DockerTimeoutError struct {\n\tduration time.Duration\n\ttransition string\n}\n\nfunc (err *DockerTimeoutError) Error() string {\n\treturn \"Could not transition to \" + err.transition + \"; timed out after waiting \" + err.duration.String()\n}\nfunc (err *DockerTimeoutError) ErrorName() string { return \"DockerTimeoutError\" }\n\ntype ContainerVanishedError struct{}\n\nfunc (err ContainerVanishedError) Error() string { return \"No container matching saved ID found\" }\nfunc (err ContainerVanishedError) ErrorName() string { return \"ContainerVanishedError\" }\n\ntype CannotXContainerError struct {\n\ttransition string\n\tmsg string\n}\n\nfunc (err CannotXContainerError) Error() string { return err.msg }\n\n\ntype OutOfMemoryError struct{}\n\nfunc (err OutOfMemoryError) Error() string { return \"Container killed due to memory usage\" }\nfunc (err OutOfMemoryError) ErrorName() string { return \"OutOfMemoryError\" }\n\n\ntype DockerStateError struct {\n\tdockerError string\n\tname string\n}\n\nfunc NewDockerStateError(err string) DockerStateError {\n\treturn DockerStateError{\n\t\tdockerError: err,\n\t\tname: \"DockerStateError\",\n\t}\n}\n\nfunc (err DockerStateError) Error() string {\n\treturn err.dockerError\n}\nfunc (err DockerStateError) ErrorName() string {\n\treturn err.name\n}\n\nfunc (err CannotXContainerError) ErrorName() string ", "output": "{\n\treturn \"Cannot\" + err.transition + \"ContainerError\"\n}"} {"input": "package timeutil\n\nimport (\n\t\"time\"\n)\n\n\nfunc SetTimeout(t time.Duration, callback func()) {\n\tgo func() {\n\t\ttime.Sleep(t)\n\t\tcallback()\n\t}()\n}\n\n\n\nfunc SetInterval(t time.Duration, callback func() bool) {\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(t)\n\t\t\tif !callback() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\nfunc Nanosecond() int64 {\n\treturn time.Now().UnixNano()\n}\n\n\nfunc Microsecond() int64 {\n\treturn time.Now().UnixNano() / 1e3\n}\n\n\nfunc Millisecond() int64 {\n\treturn time.Now().UnixNano() / 1e6\n}\n\n\n\n\n\nfunc Date() string {\n\treturn time.Now().Format(\"2006-01-02\")\n}\n\n\nfunc Datetime() string {\n\treturn time.Now().Format(\"2006-01-02 15:04:05\")\n}\n\n\n\nfunc Format(format string, timestamps ...int64) string {\n\ttimestamp := Second()\n\tif len(timestamps) > 0 {\n\t\ttimestamp = timestamps[0]\n\t}\n\treturn time.Unix(timestamp, 0).Format(format)\n}\n\n\nfunc StrToTime(format string, timestr string) (int64, error) {\n\tt, err := time.Parse(format, timestr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn t.Unix(), nil\n}\n\nfunc Second() int64 ", "output": "{\n\treturn time.Now().UnixNano() / 1e9\n}"} {"input": "package iso\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/hashicorp/packer-plugin-sdk/multistep\"\n\tpackersdk \"github.com/hashicorp/packer-plugin-sdk/packer\"\n\tparallelscommon \"github.com/hashicorp/packer/builder/parallels/common\"\n)\n\n\n\n\n\n\n\n\n\n\n\ntype stepAttachISO struct{}\n\n\n\nfunc (s *stepAttachISO) Cleanup(state multistep.StateBag) {\n\tif _, ok := state.GetOk(\"attachedIso\"); !ok {\n\t\treturn\n\t}\n\n\tdriver := state.Get(\"driver\").(parallelscommon.Driver)\n\tui := state.Get(\"ui\").(packersdk.Ui)\n\tvmName := state.Get(\"vmName\").(string)\n\n\tlog.Println(\"Detaching ISO from the default CD/DVD ROM device...\")\n\tcommand := []string{\n\t\t\"set\", vmName,\n\t\t\"--device-set\", \"cdrom0\",\n\t\t\"--image\", \"\", \"--disconnect\", \"--enable\",\n\t}\n\n\tif err := driver.Prlctl(command...); err != nil {\n\t\tui.Error(fmt.Sprintf(\"Error detaching ISO: %s\", err))\n\t}\n}\n\nfunc (s *stepAttachISO) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction ", "output": "{\n\tdriver := state.Get(\"driver\").(parallelscommon.Driver)\n\tisoPath := state.Get(\"iso_path\").(string)\n\tui := state.Get(\"ui\").(packersdk.Ui)\n\tvmName := state.Get(\"vmName\").(string)\n\n\tui.Say(\"Attaching ISO to the default CD/DVD ROM device...\")\n\tcommand := []string{\n\t\t\"set\", vmName,\n\t\t\"--device-set\", \"cdrom0\",\n\t\t\"--image\", isoPath,\n\t\t\"--enable\", \"--connect\",\n\t}\n\tif err := driver.Prlctl(command...); err != nil {\n\t\terr := fmt.Errorf(\"Error attaching ISO: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\tstate.Put(\"attachedIso\", true)\n\n\treturn multistep.ActionContinue\n}"} {"input": "package tempconv\n\nimport \"testing\"\n\n\n\nfunc TestFToC(t *testing.T) {\n\tvar f Fahrenheit = 95\n\tc := FToC(f)\n\tif c != Celsius(35) {\n\t\tt.Errorf(`FToC(%g) == %g failed`, f, c)\n\t}\n}\n\nfunc TestCToK(t *testing.T) {\n\tvar c Celsius = 37\n\tk := CToK(c)\n\tif k != Kelvin(310.15) {\n\t\tt.Errorf(`CToK(%g) == %g failed`, c, k)\n\t}\n}\n\nfunc TestKToC(t *testing.T) {\n\tvar k Kelvin = 1000\n\tc := KToC(k)\n\tif c != Celsius(726.85) {\n\t\tt.Errorf(`KToC(%g) == %g failed`, k, c)\n\t}\n}\n\nfunc TestCToF(t *testing.T) ", "output": "{\n\tvar c Celsius = 37\n\tf := CToF(c)\n\tif f != Fahrenheit(98.6) {\n\t\tt.Errorf(`CToF(%g) == %g failed`, c, f)\n\t}\n}"} {"input": "package fasthttpradix\n\n\nimport (\n\t\"github.com/valyala/fasthttp\"\n\trr \"github.com/byte-mug/golibs/radixroute\"\n\t\"strings\"\n)\n\n\nfunc NormPath(str string) string {\n\treturn \"/\"+strings.Trim(str,\"/\")+\"/\"\n}\n\nfunc InvalidPath(ctx *fasthttp.RequestCtx) {\n\tctx.SetBody([]byte(\"404 Not Found\\n\"))\n\tctx.SetStatusCode(fasthttp.StatusNotFound)\n}\n\ntype handling struct{\n\thandle fasthttp.RequestHandler\n}\ntype Router struct{\n\troutes map[string]*rr.Tree\n}\nfunc (r *Router) getOrCreate(m string) *rr.Tree {\n\tt := r.routes[m]\n\tif t!=nil { return t }\n\tif r.routes==nil { r.routes = make(map[string]*rr.Tree) }\n\tr.routes[m] = rr.New()\n\treturn r.routes[m]\n}\nfunc (r *Router) Handle(method string,path string,handler fasthttp.RequestHandler) {\n\tif handler==nil { panic(\"handler must not be nil\") }\n\th := &handling{handler}\n\tcpath := []byte(NormPath(path))\n\tbpath := cpath[:len(cpath)-1]\n\tif method==\"\" {\n\t\tmethod = \"DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT\"\n\t}\n\tfor _,m := range strings.Split(method,\",\") {\n\t\trrt := r.getOrCreate(m)\n\t\trrt.InsertRoute(bpath,h)\n\t\trrt.InsertRoute(cpath,h)\n\t}\n}\n\n\nfunc (r *Router) RequestHandler(ctx *fasthttp.RequestCtx) ", "output": "{\n\tt := r.routes[string(ctx.Method())]\n\tif t==nil {\n\t\tInvalidPath(ctx)\n\t\treturn\n\t}\n\ti,_ := t.Get(ctx.Path(),ctx.SetUserValue)\n\th,ok := i.(*handling)\n\tif !ok {\n\t\tInvalidPath(ctx)\n\t\treturn\n\t}\n\th.handle(ctx)\n}"} {"input": "package validator\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/pivotal-cf/pivnet-resource/concourse\"\n)\n\ntype CheckValidator struct {\n\tinput concourse.CheckRequest\n}\n\nfunc NewCheckValidator(input concourse.CheckRequest) *CheckValidator {\n\treturn &CheckValidator{\n\t\tinput: input,\n\t}\n}\n\n\n\nfunc (v CheckValidator) Validate() error ", "output": "{\n\tif v.input.Source.APIToken == \"\" {\n\t\treturn fmt.Errorf(\"%s must be provided\", \"api_token\")\n\t}\n\n\tif v.input.Source.ProductSlug == \"\" {\n\t\treturn fmt.Errorf(\"%s must be provided\", \"product_slug\")\n\t}\n\treturn nil\n}"} {"input": "package multiwriter\n\nimport (\n\t\"io\"\n)\n\n\ntype multiWriter []io.Writer\n\n\nfunc New(w ...io.Writer) io.Writer {\n\treturn multiWriter(w)\n}\n\n\n\n\nfunc send(w io.Writer, p []byte, done chan<- result) {\n\tvar res result\n\tres.n, res.err = w.Write(p)\n\tif res.n < len(p) && res.err == nil {\n\t\tres.err = io.ErrShortWrite\n\t}\n\tdone <- res\n}\n\ntype result struct {\n\tn int\n\terr error\n}\n\nfunc (mw multiWriter) Write(p []byte) (int, error) ", "output": "{\n\tdone := make(chan result, len(mw))\n\tfor _, w := range mw {\n\t\tgo send(w, p, done)\n\t}\n\tendResult := result{n: len(p)}\n\tfor _ = range mw {\n\t\tres := <-done\n\t\tif res.err != nil && (endResult.err == nil || res.n < endResult.n) {\n\t\t\tendResult = res\n\t\t}\n\t}\n\treturn endResult.n, endResult.err\n}"} {"input": "package cli\n\nimport (\n\t\"fmt\"\n\t\"github.com/dailymuse/git-fit/config\"\n\t\"github.com/dailymuse/git-fit/transport\"\n\t\"github.com/dailymuse/git-fit/util\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\n\n\nfunc Gc(schema *config.Config, trans transport.Transport, args []string) ", "output": "{\n\tsavedFiles := make(map[string]bool, len(schema.Files)*2)\n\n\tfor _, hash := range schema.Files {\n\t\tsavedFiles[hash] = true\n\t}\n\n\tallFiles, err := ioutil.ReadDir(\".git/fit\")\n\n\tif err != nil {\n\t\tutil.Fatal(\"Could not read .git/fit: %s\\n\", err.Error())\n\t}\n\n\tfor _, file := range allFiles {\n\t\t_, ok := savedFiles[file.Name()]\n\n\t\tif !ok {\n\t\t\tpath := fmt.Sprintf(\".git/fit/%s\", file.Name())\n\t\t\terr = os.Remove(path)\n\n\t\t\tif err != nil {\n\t\t\t\tutil.Error(\"Could not delete cached file %s: %s\\n\", path, err.Error())\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package session\n\nimport (\n\t\"github.com/gorilla/mux\"\n\t\"github.com/rebel-l/sessionservice/src/authentication\"\n\t\"github.com/rebel-l/sessionservice/src/configuration\"\n\t\"github.com/rebel-l/sessionservice/src/storage\"\n\tlog \"github.com/sirupsen/logrus\"\n\t\"net/http\"\n)\n\n\ntype Session struct {\n\tStorage storage.Handler\n\tAuthentication *authentication.Authentication\n\tConfig *configuration.Service\n}\n\nfunc NewSession(\n\tstorage storage.Handler,\n\tauthentication *authentication.Authentication,\n\tconfig *configuration.Service) *Session {\n\ts := new(Session)\n\ts.Storage = storage\n\ts.Authentication = authentication\n\ts.Config = config\n\treturn s\n}\n\n\n\n\nfunc (s *Session) handlerFactory(method string) http.Handler {\n\tvar handler func(http.ResponseWriter, *http.Request)\n\tswitch method {\n\t\tcase http.MethodPut:\n\t\t\tput := NewPut(s)\n\t\t\thandler = put.Handler\n\t\tdefault:\n\t\t\tlog.Panicf(\"Method %s is not implemented\", method)\n\t\t\treturn nil\n\t}\n\n\treturn s.Authentication.Middleware(http.HandlerFunc(handler))\n}\n\nfunc (s *Session) Init(router *mux.Router) ", "output": "{\n\tlog.Debug(\"Session endpoint: Init ...\")\n\n\trouter.Handle(\"/session/\", s.handlerFactory(http.MethodPut)).Methods(http.MethodPut)\n\n\tlog.Debug(\"Session endpoint: initialized!\")\n}"} {"input": "package eventbreakpoints\n\n\n\nimport (\n\t\"context\"\n\n\t\"github.com/chromedp/cdproto/cdp\"\n)\n\n\n\ntype SetInstrumentationBreakpointParams struct {\n\tEventName string `json:\"eventName\"` \n}\n\n\n\n\n\n\n\nfunc SetInstrumentationBreakpoint(eventName string) *SetInstrumentationBreakpointParams {\n\treturn &SetInstrumentationBreakpointParams{\n\t\tEventName: eventName,\n\t}\n}\n\n\nfunc (p *SetInstrumentationBreakpointParams) Do(ctx context.Context) (err error) {\n\treturn cdp.Execute(ctx, CommandSetInstrumentationBreakpoint, p, nil)\n}\n\n\n\ntype RemoveInstrumentationBreakpointParams struct {\n\tEventName string `json:\"eventName\"` \n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *RemoveInstrumentationBreakpointParams) Do(ctx context.Context) (err error) {\n\treturn cdp.Execute(ctx, CommandRemoveInstrumentationBreakpoint, p, nil)\n}\n\n\nconst (\n\tCommandSetInstrumentationBreakpoint = \"EventBreakpoints.setInstrumentationBreakpoint\"\n\tCommandRemoveInstrumentationBreakpoint = \"EventBreakpoints.removeInstrumentationBreakpoint\"\n)\n\nfunc RemoveInstrumentationBreakpoint(eventName string) *RemoveInstrumentationBreakpointParams ", "output": "{\n\treturn &RemoveInstrumentationBreakpointParams{\n\t\tEventName: eventName,\n\t}\n}"} {"input": "package menu\n\nimport \"fmt\"\n\ntype MenuFunc func()\n\n\ntype MenuEntry struct {\n\tMenuText string\n\tMenuSelector int\n\tMenuFunction MenuFunc\n\tStopRunning bool\n}\n\n\n\n\n\nfunc (entry MenuEntry) IsSelected(selector int) bool {\n\treturn entry.MenuSelector == selector\n}\n\nfunc (entry MenuEntry) PrintEntry() ", "output": "{\n\tfmt.Printf(\"%d - %v\\n\", entry.MenuSelector, entry.MenuText)\n}"} {"input": "package language \n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}\n\n\n\n\nfunc DefaultAuthScopes() []string ", "output": "{\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t}\n}"} {"input": "package db\n\nimport (\n\t\"github.com/globalsign/mgo\"\n\t\"github.com/tsuru/config\"\n\t\"github.com/tsuru/tsuru/db/storage\"\n)\n\nconst (\n\tDefaultDatabaseURL = \"127.0.0.1:27017\"\n\tDefaultDatabaseName = \"gandalf\"\n)\n\ntype Storage struct {\n\t*storage.Storage\n}\n\n\n\n\n\nfunc conn() (*storage.Storage, error) {\n\turl, dbname := DbConfig()\n\treturn storage.Open(url, dbname)\n}\n\n\n\nfunc DbConfig() (string, string) {\n\turl, _ := config.GetString(\"database:url\")\n\tif url == \"\" {\n\t\turl = DefaultDatabaseURL\n\t}\n\tdbname, _ := config.GetString(\"database:name\")\n\tif dbname == \"\" {\n\t\tdbname = DefaultDatabaseName\n\t}\n\treturn url, dbname\n}\n\n\nfunc (s *Storage) Repository() *storage.Collection {\n\treturn s.Collection(\"repository\")\n}\n\n\nfunc (s *Storage) User() *storage.Collection {\n\treturn s.Collection(\"user\")\n}\n\nfunc (s *Storage) Key() *storage.Collection {\n\tbodyIndex := mgo.Index{Key: []string{\"body\"}, Unique: true}\n\tnameIndex := mgo.Index{Key: []string{\"username\", \"name\"}, Unique: true}\n\tc := s.Collection(\"key\")\n\tc.EnsureIndex(bodyIndex)\n\tc.EnsureIndex(nameIndex)\n\treturn c\n}\n\nfunc Conn() (*Storage, error) ", "output": "{\n\tvar (\n\t\tstrg Storage\n\t\terr error\n\t)\n\tstrg.Storage, err = conn()\n\treturn &strg, err\n}"} {"input": "package watt\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n\n\t\"github.com/datawire/ambassador/pkg/consulwatch\"\n\n\t\"github.com/datawire/ambassador/pkg/k8s\"\n)\n\ntype ConsulSnapshot struct {\n\tEndpoints map[string]consulwatch.Endpoints `json:\",omitempty\"`\n}\n\n\n\ntype Error struct {\n\tSource string\n\tMessage string\n\tTimestamp int64\n}\n\nfunc NewError(source, message string) Error {\n\treturn Error{Source: source, Message: message, Timestamp: time.Now().Unix()}\n}\n\ntype Snapshot struct {\n\tConsul ConsulSnapshot `json:\",omitempty\"`\n\tKubernetes map[string][]k8s.Resource `json:\",omitempty\"`\n\tErrors map[string][]Error `json:\",omitempty\"`\n}\n\nfunc (s *ConsulSnapshot) DeepCopy() (*ConsulSnapshot, error) ", "output": "{\n\tjsonBytes, err := json.Marshal(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := &ConsulSnapshot{}\n\terr = json.Unmarshal(jsonBytes, res)\n\n\treturn res, err\n}"} {"input": "package engine\n\nimport (\n\t\"time\"\n\n\t\"github.com/aws/amazon-ecs-agent/agent/api\"\n)\n\n\n\ntype impossibleTransitionError struct {\n\tstate api.ContainerStatus\n}\n\nfunc (err *impossibleTransitionError) Error() string {\n\treturn \"Cannot transition to \" + err.state.String()\n}\nfunc (err *impossibleTransitionError) ErrorName() string { return \"ImpossibleStateTransitionError\" }\n\ntype DockerTimeoutError struct {\n\tduration time.Duration\n\ttransition string\n}\n\nfunc (err *DockerTimeoutError) Error() string {\n\treturn \"Could not transition to \" + err.transition + \"; timed out after waiting \" + err.duration.String()\n}\nfunc (err *DockerTimeoutError) ErrorName() string { return \"DockerTimeoutError\" }\n\ntype ContainerVanishedError struct{}\n\nfunc (err ContainerVanishedError) Error() string { return \"No container matching saved ID found\" }\nfunc (err ContainerVanishedError) ErrorName() string { return \"ContainerVanishedError\" }\n\ntype CannotXContainerError struct {\n\ttransition string\n\tmsg string\n}\n\nfunc (err CannotXContainerError) Error() string { return err.msg }\nfunc (err CannotXContainerError) ErrorName() string {\n\treturn \"Cannot\" + err.transition + \"ContainerError\"\n}\n\ntype OutOfMemoryError struct{}\n\nfunc (err OutOfMemoryError) Error() string { return \"Container killed due to memory usage\" }\nfunc (err OutOfMemoryError) ErrorName() string { return \"OutOfMemoryError\" }\n\n\ntype DockerStateError struct {\n\tdockerError string\n\tname string\n}\n\nfunc NewDockerStateError(err string) DockerStateError {\n\treturn DockerStateError{\n\t\tdockerError: err,\n\t\tname: \"DockerStateError\",\n\t}\n}\n\nfunc (err DockerStateError) Error() string {\n\treturn err.dockerError\n}\n\n\nfunc (err DockerStateError) ErrorName() string ", "output": "{\n\treturn err.name\n}"} {"input": "package do\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\n\n\n\n\n\nfunc WaitForErrorChannels(ctx Context, channels ...<-chan error) (err error) {\n\tcases := make([]reflect.SelectCase, len(channels)+1)\n\tctxDoneCaseIndex := len(channels)\n\tfor i, ch := range channels {\n\t\tcases[i] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ch)}\n\t}\n\tif ctx != nil {\n\t\tcases[ctxDoneCaseIndex] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ctx.Done())}\n\t}\n\n\tremaining := len(channels)\n\tfor remaining > 0 {\n\t\ti, value, ok := reflect.Select(cases)\n\n\t\tif i == ctxDoneCaseIndex {\n\t\t\treturn ctx.Err()\n\n\t\t} else if !value.IsNil() {\n\t\t\treturn value.Interface().(error)\n\n\t\t} else if !ok {\n\t\t\treturn fmt.Errorf(\"WaitForErrorChannels attempted read from closed channel #%d\", i)\n\t\t}\n\n\t\tcases[i].Chan = reflect.ValueOf(nil)\n\t\tremaining--\n\t}\n\treturn nil\n}\n\n\n\nfunc CheckChan(channel chan interface{}) (didRead bool, item interface{}) {\n\treturn nonBlockingChannelRead(channel)\n}\n\n\n\n\n\n\n\nfunc CheckStructChan(channel chan struct{}) (didRead bool) {\n\tdidRead, _ = nonBlockingChannelRead(channel)\n\treturn didRead\n}\n\nfunc nonBlockingChannelRead(channel interface{}) (didRead bool, item interface{}) {\n\trCase := reflect.SelectCase{\n\t\tChan: reflect.ValueOf(channel),\n\t\tDir: reflect.SelectRecv,\n\t}\n\t_, value, didRead := reflect.Select([]reflect.SelectCase{rCase})\n\treturn didRead, value.Interface()\n}\n\nfunc CheckErrChan(errChan chan error) (didRead bool, err error) ", "output": "{\n\tdidRead, val := nonBlockingChannelRead(errChan)\n\treturn didRead, val.(error)\n}"} {"input": "package model\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/utils\"\n\n\t\"strings\"\n)\n\n\ntype RegisterServerAutoRecoveryResponse struct {\n\tHttpStatusCode int `json:\"-\"`\n}\n\n\n\nfunc (o RegisterServerAutoRecoveryResponse) String() string ", "output": "{\n\tdata, err := utils.Marshal(o)\n\tif err != nil {\n\t\treturn \"RegisterServerAutoRecoveryResponse struct{}\"\n\t}\n\n\treturn strings.Join([]string{\"RegisterServerAutoRecoveryResponse\", string(data)}, \" \")\n}"} {"input": "package model\n\ntype Interface interface {\n\tVisitString(name string, resume func())\n\tVisitInt(name string, resume func())\n\tVisitFloat(name string, resume func())\n\tVisitBool(name string, resume func())\n\tVisitPtr(name string, resume func())\n\tVisitBytes(name string, resume func())\n\tVisitSlice(name string, resume func())\n\tVisitStruct(name string, fields []Field, resume func())\n\tVisitStructField(field Field, resume func())\n\tVisitMap(name string, resume func())\n\tVisitCustom(name string, resume func())\n\tVisitReference(name string, resume func())\n}\n\ntype Visitor struct{}\n\nfunc (self *Visitor) VisitString(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitInt(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitFloat(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBool(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitPtr(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBytes(name string, resume func()) {\n\tresume()\n}\n\n\n\nfunc (self *Visitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStructField(field Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitMap(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitCustom(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitReference(name string, resume func()) {\n\tresume()\n}\n\ntype EmbeddedStructVisitor struct {\n\tInterface\n}\n\nfunc (self *EmbeddedStructVisitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitSlice(name string, resume func()) ", "output": "{\n\tresume()\n}"} {"input": "package mock\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/cilium/cilium/pkg/lock\"\n)\n\n\ntype MockMetrics struct {\n\tmutex lock.RWMutex\n\tapiCall map[string]float64\n\trateLimit map[string]time.Duration\n}\n\n\nfunc NewMockMetrics() *MockMetrics {\n\treturn &MockMetrics{\n\t\tapiCall: map[string]float64{},\n\t\trateLimit: map[string]time.Duration{},\n\t}\n}\n\n\n\nfunc (m *MockMetrics) APICall(operation, status string) float64 {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\treturn m.apiCall[fmt.Sprintf(\"operation=%s, status=%s\", operation, status)]\n}\n\n\n\n\n\n\n\n\n\nfunc (m *MockMetrics) RateLimit(operation string) time.Duration {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\treturn m.rateLimit[operation]\n}\n\n\n\n\nfunc (m *MockMetrics) ObserveRateLimit(operation string, delay time.Duration) {\n\tm.mutex.Lock()\n\tm.rateLimit[operation] += delay\n\tm.mutex.Unlock()\n}\n\nfunc (m *MockMetrics) ObserveAPICall(operation, status string, duration float64) ", "output": "{\n\tm.mutex.Lock()\n\tm.apiCall[fmt.Sprintf(\"operation=%s, status=%s\", operation, status)] += duration\n\tm.mutex.Unlock()\n}"} {"input": "package main\n\nimport (\n\tfmtlog \"log\"\n\t\"time\"\n\n\t\"github.com/BurntSushi/toml\"\n\t\"github.com/emilevauge/traefik/provider\"\n\t\"github.com/emilevauge/traefik/types\"\n)\n\n\n\ntype GlobalConfiguration struct {\n\tPort string\n\tGraceTimeOut int64\n\tAccessLogsFile string\n\tTraefikLogsFile string\n\tCertificates []Certificate\n\tLogLevel string\n\tProvidersThrottleDuration time.Duration\n\tDocker *provider.Docker\n\tFile *provider.File\n\tWeb *WebProvider\n\tMarathon *provider.Marathon\n\tConsul *provider.Consul\n\tEtcd *provider.Etcd\n\tZookeeper *provider.Zookepper\n\tBoltdb *provider.BoltDb\n}\n\n\ntype Certificate struct {\n\tCertFile string\n\tKeyFile string\n}\n\n\n\n\n\nfunc LoadFileConfig(file string) *GlobalConfiguration {\n\tconfiguration := NewGlobalConfiguration()\n\tif _, err := toml.DecodeFile(file, configuration); err != nil {\n\t\tfmtlog.Fatalf(\"Error reading file: %s\", err)\n\t}\n\treturn configuration\n}\n\ntype configs map[string]*types.Configuration\n\nfunc NewGlobalConfiguration() *GlobalConfiguration ", "output": "{\n\tglobalConfiguration := new(GlobalConfiguration)\n\tglobalConfiguration.Port = \":80\"\n\tglobalConfiguration.GraceTimeOut = 10\n\tglobalConfiguration.LogLevel = \"ERROR\"\n\tglobalConfiguration.ProvidersThrottleDuration = time.Duration(2 * time.Second)\n\n\treturn globalConfiguration\n}"} {"input": "package runners\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\t\"text/template\"\n\n\t\"github.com/davecgh/go-spew/spew\"\n\t\"github.com/kylelemons/godebug/pretty\"\n\tyaml \"gopkg.in/yaml.v2\"\n)\n\n\n\nfunc describeStruct(t interface{}, depth int) string {\n\tprefix := strings.Repeat(\" \", depth)\n\tvar out string\n\ts := reflect.Indirect(reflect.ValueOf(t))\n\ttypeOfT := s.Type()\n\n\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\n\t\tout = fmt.Sprintf(\"%s%s%s %s\\n\", out, prefix, typeOfT.Field(i).Name, typeOfT.Field(i).Type)\n\t\tswitch f.Type().Kind() {\n\t\tcase reflect.Struct, reflect.Ptr:\n\t\t\tout = fmt.Sprintf(\"%s%s{\\n\", out, prefix)\n\t\t\tout = fmt.Sprintf(\"%s%s\", out, describeStruct(f.Interface(), depth+1))\n\t\t\tout = fmt.Sprintf(\"%s%s}\\n\", out, prefix)\n\t\t}\n\t}\n\treturn out\n}\n\nfunc getFuncs() template.FuncMap ", "output": "{\n\treturn template.FuncMap{\n\t\t\"pretty\": func(i interface{}) string {\n\t\t\treturn pretty.Sprint(i)\n\t\t},\n\t\t\"json\": func(i interface{}) string {\n\t\t\tjson, _ := json.MarshalIndent(i, \"\", \"\\t\")\n\t\t\treturn string(json)\n\t\t},\n\t\t\"yaml\": func(i interface{}) string {\n\t\t\tyaml, _ := yaml.Marshal(i)\n\t\t\treturn string(yaml)\n\t\t},\n\t\t\"spew\": func(i interface{}) string {\n\t\t\treturn spew.Sprint(i)\n\t\t},\n\t\t\"describe\": func(i interface{}) string {\n\t\t\treturn describeStruct(i, 0)\n\t\t},\n\t}\n}"} {"input": "package vm\n\nimport (\n\t\"github.com/rancher/wrangler/pkg/generic\"\n\t\"k8s.io/client-go/rest\"\n)\n\ntype Factory struct {\n\t*generic.Factory\n}\n\nfunc NewFactoryFromConfigOrDie(config *rest.Config) *Factory {\n\tf, err := NewFactoryFromConfig(config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}\n\nfunc NewFactoryFromConfig(config *rest.Config) (*Factory, error) {\n\treturn NewFactoryFromConfigWithOptions(config, nil)\n}\n\nfunc NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (*Factory, error) {\n\treturn NewFactoryFromConfigWithOptions(config, &FactoryOptions{\n\t\tNamespace: namespace,\n\t})\n}\n\ntype FactoryOptions = generic.FactoryOptions\n\n\n\nfunc (c *Factory) Vm() Interface {\n\treturn New(c.ControllerFactory())\n}\n\nfunc NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) ", "output": "{\n\tf, err := generic.NewFactoryFromConfigWithOptions(config, opts)\n\treturn &Factory{\n\t\tFactory: f,\n\t}, err\n}"} {"input": "package locus\n\nimport (\n\t\"github.com/gocircuit/circuit/use/circuit\"\n)\n\n\n\ntype XLocus struct {\n\tl *Locus\n}\n\nfunc (x XLocus) GetPeers() []*Peer {\n\treturn x.l.GetPeers()\n}\n\nfunc (x XLocus) Self() interface{} {\n\treturn x.l.Self()\n}\n\n\ntype YLocus struct {\n\tX circuit.PermX\n}\n\nfunc (y YLocus) GetPeers() map[string]*Peer {\n\tr := make(map[string]*Peer)\n\tfor _, p := range y.X.Call(\"GetPeers\")[0].([]*Peer) {\n\t\tr[p.Key()] = p\n\t}\n\treturn r\n}\n\nfunc (y YLocus) Self() *Peer {\n\treturn y.X.Call(\"Self\")[0].(*Peer)\n}\n\nfunc init() ", "output": "{\n\tcircuit.RegisterValue(XLocus{})\n}"} {"input": "package rfc\n\n\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/util\"\n)\n\ntype extDuplicateExtension struct{}\n\n\n\nfunc init() {\n\tlint.RegisterLint(&lint.Lint{\n\t\tName: \"e_ext_duplicate_extension\",\n\t\tDescription: \"A certificate MUST NOT include more than one instance of a particular extension\",\n\t\tCitation: \"RFC 5280: 4.2\",\n\t\tSource: lint.RFC5280,\n\t\tEffectiveDate: util.RFC2459Date,\n\t\tLint: &extDuplicateExtension{},\n\t})\n}\n\nfunc (l *extDuplicateExtension) Initialize() error {\n\treturn nil\n}\n\nfunc (l *extDuplicateExtension) CheckApplies(cert *x509.Certificate) bool {\n\treturn cert.Version == 3\n}\n\n\n\nfunc (l *extDuplicateExtension) Execute(cert *x509.Certificate) *lint.LintResult ", "output": "{\n\textensionOIDs := make(map[string]bool)\n\tduplicateOIDs := make(map[string]bool)\n\n\tfor _, ext := range cert.Extensions {\n\t\toid := ext.Id.String()\n\n\t\tif alreadySeen := extensionOIDs[oid]; alreadySeen {\n\t\t\tduplicateOIDs[oid] = true\n\t\t} else {\n\t\t\textensionOIDs[oid] = true\n\t\t}\n\t}\n\n\tif len(duplicateOIDs) == 0 {\n\t\treturn &lint.LintResult{Status: lint.Pass}\n\t}\n\n\tvar duplicateOIDsList []string\n\tfor oid := range duplicateOIDs {\n\t\tduplicateOIDsList = append(duplicateOIDsList, oid)\n\t}\n\n\treturn &lint.LintResult{\n\t\tStatus: lint.Error,\n\t\tDetails: fmt.Sprintf(\n\t\t\t\"The following extensions are duplicated: %s\",\n\t\t\tstrings.Join(duplicateOIDsList, \", \")),\n\t}\n}"} {"input": "package rest\n\nimport (\n\t\"time\"\n\n\teventsapiv1beta1 \"k8s.io/api/events/v1beta1\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\t\"k8s.io/apiserver/pkg/registry/rest\"\n\tgenericapiserver \"k8s.io/apiserver/pkg/server\"\n\tserverstorage \"k8s.io/apiserver/pkg/server/storage\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\t\"k8s.io/kubernetes/pkg/apis/events\"\n\teventstore \"k8s.io/kubernetes/pkg/registry/core/event/storage\"\n)\n\ntype RESTStorageProvider struct {\n\tTTL time.Duration\n}\n\nfunc (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(events.GroupName, legacyscheme.Registry, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\n\tif apiResourceConfigSource.VersionEnabled(eventsapiv1beta1.SchemeGroupVersion) {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[eventsapiv1beta1.SchemeGroupVersion.Version] = p.v1beta1Storage(apiResourceConfigSource, restOptionsGetter)\n\t\tapiGroupInfo.GroupMeta.GroupVersion = eventsapiv1beta1.SchemeGroupVersion\n\t}\n\n\treturn apiGroupInfo, true\n}\n\n\n\nfunc (p RESTStorageProvider) GroupName() string {\n\treturn events.GroupName\n}\n\nfunc (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage ", "output": "{\n\tstorage := map[string]rest.Storage{}\n\teventsStorage := eventstore.NewREST(restOptionsGetter, uint64(p.TTL.Seconds()))\n\tstorage[\"events\"] = eventsStorage\n\n\treturn storage\n}"} {"input": "package atomic\n\nimport (\n\t\"encoding/json\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\n\ntype Uint32 struct {\n\t_ nocmp \n\n\tv uint32\n}\n\n\nfunc NewUint32(val uint32) *Uint32 {\n\treturn &Uint32{v: val}\n}\n\n\nfunc (i *Uint32) Load() uint32 {\n\treturn atomic.LoadUint32(&i.v)\n}\n\n\nfunc (i *Uint32) Add(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, delta)\n}\n\n\nfunc (i *Uint32) Sub(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, ^(delta - 1))\n}\n\n\nfunc (i *Uint32) Inc() uint32 {\n\treturn i.Add(1)\n}\n\n\nfunc (i *Uint32) Dec() uint32 {\n\treturn i.Sub(1)\n}\n\n\nfunc (i *Uint32) CAS(old, new uint32) (swapped bool) {\n\treturn atomic.CompareAndSwapUint32(&i.v, old, new)\n}\n\n\n\n\n\nfunc (i *Uint32) Swap(val uint32) (old uint32) {\n\treturn atomic.SwapUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(i.Load())\n}\n\n\nfunc (i *Uint32) UnmarshalJSON(b []byte) error {\n\tvar v uint32\n\tif err := json.Unmarshal(b, &v); err != nil {\n\t\treturn err\n\t}\n\ti.Store(v)\n\treturn nil\n}\n\n\nfunc (i *Uint32) String() string {\n\tv := i.Load()\n\treturn strconv.FormatUint(uint64(v), 10)\n}\n\nfunc (i *Uint32) Store(val uint32) ", "output": "{\n\tatomic.StoreUint32(&i.v, val)\n}"} {"input": "package test_utils\n\nimport (\n\t\"fmt\"\n\t\"simplejsondb/dbio\"\n)\n\n\n\ntype InMemoryDataFile struct {\n\tBlocks [][]byte\n\tCloseFunc func() error\n\tReadBlockFunc func(uint16, []byte) error\n\tWriteBlockFunc func(uint16, []byte) error\n}\n\nfunc NewFakeDataFile(blocksCount int) *InMemoryDataFile {\n\tblocks := [][]byte{}\n\tfor i := 0; i < blocksCount; i++ {\n\t\tblocks = append(blocks, make([]byte, dbio.DATABLOCK_SIZE))\n\t}\n\treturn NewFakeDataFileWithBlocks(blocks)\n}\n\nfunc NewFakeDataFileWithBlocks(blocks [][]byte) *InMemoryDataFile {\n\treturn &InMemoryDataFile{\n\t\tBlocks: blocks,\n\t\tCloseFunc: func() error {\n\t\t\treturn nil \n\t\t},\n\t\tWriteBlockFunc: func(id uint16, data []byte) error {\n\t\t\tblock := blocks[id]\n\t\t\tfor i := range block {\n\t\t\t\tblock[i] = data[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tReadBlockFunc: func(id uint16, data []byte) error {\n\t\t\tif id < 0 || id >= uint16(len(blocks)) {\n\t\t\t\treturn fmt.Errorf(\"Invalid datablock requested: %d\", id)\n\t\t\t}\n\t\t\tblock := blocks[id]\n\t\t\tfor i := 0; i < len(block); i++ {\n\t\t\t\tdata[i] = block[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\nfunc (df *InMemoryDataFile) Close() error {\n\treturn df.CloseFunc()\n}\nfunc (df *InMemoryDataFile) ReadBlock(id uint16, data []byte) error {\n\treturn df.ReadBlockFunc(id, data)\n}\n\n\nfunc (df *InMemoryDataFile) WriteBlock(id uint16, data []byte) error ", "output": "{\n\treturn df.WriteBlockFunc(id, data)\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestLogParser(t *testing.T) ", "output": "{\n\tfields := []string{\"\", \"\", \"size\", \"\", \"\", \"duration\", \"method\", \"url\", \"\", \"\", \"mime_type\", \"agent\"}\n\tp := NewLogParser(strings.NewReader(ssvLog), NewSSVLexer(fields))\n\n\tch, err := p.Get()\n\tif err != nil {\n\t\tt.Fatalf(\"%v\\n\", err)\n\t}\n\n\tfor r := range ch {\n\t\tif r.Err() != nil {\n\t\t\tt.Errorf(\"%v\", r.Err())\n\t\t}\n\t}\n}"} {"input": "package server\n\nvar skipSystemMastersAuthorizer = false\n\n\n\n\nfunc SkipSystemMastersAuthorizer() ", "output": "{\n\tskipSystemMastersAuthorizer = true\n}"} {"input": "package server\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/cockroachdb/cockroach/gossip/resolver\"\n\t\"github.com/cockroachdb/cockroach/util/leaktest\"\n)\n\nfunc TestParseNodeAttributes(t *testing.T) {\n\tdefer leaktest.AfterTest(t)\n\tctx := NewContext()\n\tctx.Attrs = \"attr1=val1::attr2=val2\"\n\tctx.Stores = \"mem=1\"\n\tctx.GossipBootstrap = \"self=\"\n\tif err := ctx.Init(\"start\"); err != nil {\n\t\tt.Fatalf(\"Failed to initialize the context: %v\", err)\n\t}\n\texpected := []string{\"attr1=val1\", \"attr2=val2\"}\n\tif !reflect.DeepEqual(ctx.NodeAttributes.GetAttrs(), expected) {\n\t\tt.Fatalf(\"Unexpected attributes: %v\", ctx.NodeAttributes.GetAttrs())\n\t}\n}\n\n\n\n\n\nfunc TestParseGossipBootstrapAddrs(t *testing.T) ", "output": "{\n\tdefer leaktest.AfterTest(t)\n\tctx := NewContext()\n\tctx.GossipBootstrap = \"localhost:12345,,localhost:23456\"\n\tctx.Stores = \"mem=1\"\n\tif err := ctx.Init(\"start\"); err != nil {\n\t\tt.Fatalf(\"Failed to initialize the context: %v\", err)\n\t}\n\tr1, err := resolver.NewResolver(&ctx.Context, \"tcp=localhost:12345\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tr2, err := resolver.NewResolver(&ctx.Context, \"tcp=localhost:23456\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\texpected := []resolver.Resolver{r1, r2}\n\tif !reflect.DeepEqual(ctx.GossipBootstrapResolvers, expected) {\n\t\tt.Fatalf(\"Unexpected bootstrap addresses: %v, expected: %v\", ctx.GossipBootstrapResolvers, expected)\n\t}\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aptly-dev/aptly/deb\"\n\t\"github.com/smira/commander\"\n)\n\nfunc aptlySnapshotRename(cmd *commander.Command, args []string) error {\n\tvar (\n\t\terr error\n\t\tsnapshot *deb.Snapshot\n\t)\n\n\tif len(args) != 2 {\n\t\tcmd.Usage()\n\t\treturn commander.ErrCommandError\n\t}\n\n\toldName, newName := args[0], args[1]\n\n\tsnapshot, err = context.CollectionFactory().SnapshotCollection().ByName(oldName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to rename: %s\", err)\n\t}\n\n\t_, err = context.CollectionFactory().SnapshotCollection().ByName(newName)\n\tif err == nil {\n\t\treturn fmt.Errorf(\"unable to rename: snapshot %s already exists\", newName)\n\t}\n\n\tsnapshot.Name = newName\n\terr = context.CollectionFactory().SnapshotCollection().Update(snapshot)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to rename: %s\", err)\n\t}\n\n\tfmt.Printf(\"\\nSnapshot %s -> %s has been successfully renamed.\\n\", oldName, newName)\n\n\treturn err\n}\n\n\n\nfunc makeCmdSnapshotRename() *commander.Command ", "output": "{\n\tcmd := &commander.Command{\n\t\tRun: aptlySnapshotRename,\n\t\tUsageLine: \"rename \",\n\t\tShort: \"renames snapshot\",\n\t\tLong: `\nCommand changes name of the snapshot. Snapshot name should be unique.\n\nExample:\n\n $ aptly snapshot rename wheezy-min wheezy-main\n`,\n\t}\n\n\treturn cmd\n\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\ntype CommonTests struct {\n\tout *bytes.Buffer\n\td *Dispatcher\n}\n\nvar _ = Suite(&CommonTests{})\n\n\n\nfunc removeFilesInDir(dir string) error {\n\tfiles, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, file := range files {\n\t\tpath := filepath.Join(dir, file.Name())\n\t\terr = os.Remove(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (t *CommonTests) SetUpTest(c *C) ", "output": "{\n\tt.out = new(bytes.Buffer)\n\tt.d = &Dispatcher{stderr: t.out}\n}"} {"input": "import \"sort\"\n\ntype Schedule struct {\n intervals []Interval\n}\n\nfunc (s *Schedule) Len() int {\n return len(s.intervals)\n}\n\n\n\nfunc (s *Schedule) Swap(i, j int) {\n s.intervals[i], s.intervals[j] = s.intervals[j], s.intervals[i]\n}\n\nfunc (s *Schedule) Check() bool {\n for i:=0; i s.intervals[i+1].Start {\n return false\n }\n }\n return true\n}\n\nfunc canAttendMeetings(intervals []Interval) bool {\n if len(intervals) <= 1 {\n return true\n }\n s := Schedule{intervals}\n sort.Sort(&s)\n return s.Check()\n}\n\nfunc (s *Schedule) Less(i, j int) bool ", "output": "{\n if s.intervals[i].Start < s.intervals[j].Start {\n return true\n }\n return false\n}"} {"input": "package sample\n\n\nimport (\n\t\"time\"\n\t\"encoding/json\"\n)\n\ntype Datum struct {\n\tStatus string `json:\"status\"`\n\tTimestamp time.Time `json:\"timestamp\"`\n}\n\ntype Sample struct {\n\tKey string `json:\"key\"`\n\tTyp string `json:\"type\"`\n\tData Datum `json:\"data\"`\n}\n\nfunc Init() Sample {\n\tsample := Sample{\"sample\",\"testing\", Datum{\"ok\", time.Now()}}\n\treturn sample\n}\n\n\n\nfunc ConvertStatus(value int) string{\n\tswitch value {\n\tcase 1:\n\t\treturn \"ok\"\n\tdefault:\n\t\treturn \"error\"\n\n\t}\n}\n\nfunc (m *Sample) Json() string ", "output": "{\n\tresult, _ := json.Marshal(m)\n\treturn string(result)\n}"} {"input": "package timeutil\n\nimport (\n\t\"time\"\n)\n\n\nfunc SetTimeout(t time.Duration, callback func()) {\n\tgo func() {\n\t\ttime.Sleep(t)\n\t\tcallback()\n\t}()\n}\n\n\n\nfunc SetInterval(t time.Duration, callback func() bool) {\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(t)\n\t\t\tif !callback() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\nfunc Nanosecond() int64 {\n\treturn time.Now().UnixNano()\n}\n\n\nfunc Microsecond() int64 {\n\treturn time.Now().UnixNano() / 1e3\n}\n\n\nfunc Millisecond() int64 {\n\treturn time.Now().UnixNano() / 1e6\n}\n\n\nfunc Second() int64 {\n\treturn time.Now().UnixNano() / 1e9\n}\n\n\nfunc Date() string {\n\treturn time.Now().Format(\"2006-01-02\")\n}\n\n\nfunc Datetime() string {\n\treturn time.Now().Format(\"2006-01-02 15:04:05\")\n}\n\n\n\n\n\n\nfunc StrToTime(format string, timestr string) (int64, error) {\n\tt, err := time.Parse(format, timestr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn t.Unix(), nil\n}\n\nfunc Format(format string, timestamps ...int64) string ", "output": "{\n\ttimestamp := Second()\n\tif len(timestamps) > 0 {\n\t\ttimestamp = timestamps[0]\n\t}\n\treturn time.Unix(timestamp, 0).Format(format)\n}"} {"input": "package dbr\n\nimport \"bytes\"\n\n\ntype Buffer interface {\n\tWriteString(s string) (n int, err error)\n\tString() string\n\n\tWriteValue(v ...interface{}) (err error)\n\tValue() []interface{}\n}\n\n\n\n\ntype buffer struct {\n\tbytes.Buffer\n\tv []interface{}\n}\n\nfunc (b *buffer) WriteValue(v ...interface{}) error {\n\tb.v = append(b.v, v...)\n\treturn nil\n}\n\nfunc (b *buffer) Value() []interface{} {\n\treturn b.v\n}\n\nfunc NewBuffer() Buffer ", "output": "{\n\treturn &buffer{}\n}"} {"input": "package system\n\nimport (\n\t\"context\"\n\n\t\"github.com/docker/cli/cli\"\n\t\"github.com/docker/cli/cli/command\"\n\t\"github.com/docker/cli/cli/command/formatter\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype diskUsageOptions struct {\n\tverbose bool\n\tformat string\n}\n\n\nfunc newDiskUsageCommand(dockerCli command.Cli) *cobra.Command {\n\tvar opts diskUsageOptions\n\n\tcmd := &cobra.Command{\n\t\tUse: \"df [OPTIONS]\",\n\t\tShort: \"Show docker disk usage\",\n\t\tArgs: cli.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn runDiskUsage(dockerCli, opts)\n\t\t},\n\t\tAnnotations: map[string]string{\"version\": \"1.25\"},\n\t}\n\n\tflags := cmd.Flags()\n\n\tflags.BoolVarP(&opts.verbose, \"verbose\", \"v\", false, \"Show detailed information on space usage\")\n\tflags.StringVar(&opts.format, \"format\", \"\", \"Pretty-print images using a Go template\")\n\n\treturn cmd\n}\n\n\n\nfunc runDiskUsage(dockerCli command.Cli, opts diskUsageOptions) error ", "output": "{\n\tdu, err := dockerCli.Client().DiskUsage(context.Background())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tformat := opts.format\n\tif len(format) == 0 {\n\t\tformat = formatter.TableFormatKey\n\t}\n\n\tvar bsz int64\n\tfor _, bc := range du.BuildCache {\n\t\tif !bc.Shared {\n\t\t\tbsz += bc.Size\n\t\t}\n\t}\n\n\tduCtx := formatter.DiskUsageContext{\n\t\tContext: formatter.Context{\n\t\t\tOutput: dockerCli.Out(),\n\t\t\tFormat: formatter.NewDiskUsageFormat(format, opts.verbose),\n\t\t},\n\t\tLayersSize: du.LayersSize,\n\t\tBuilderSize: bsz,\n\t\tBuildCache: du.BuildCache,\n\t\tImages: du.Images,\n\t\tContainers: du.Containers,\n\t\tVolumes: du.Volumes,\n\t\tVerbose: opts.verbose,\n\t}\n\n\treturn duCtx.Write()\n}"} {"input": "package factor\n\nimport (\n\t\"github.com/jesand/stats\"\n\t\"github.com/jesand/stats/dist\"\n\t\"github.com/jesand/stats/variable\"\n)\n\n\n\n\ntype Factor interface {\n\n\tAdjacent() []variable.RandomVariable\n\n\tScore() float64\n}\n\n\n\n\nfunc NewDistFactor(vars []variable.RandomVariable, distr dist.Dist) *DistFactor {\n\treturn &DistFactor{\n\t\tVars: vars,\n\t\tDist: distr,\n\t}\n}\n\n\ntype DistFactor struct {\n\tVars []variable.RandomVariable\n\tDist dist.Dist\n}\n\n\n\n\n\nfunc (factor DistFactor) Score() float64 {\n\tvar (\n\t\tnumVars = factor.Dist.NumVars()\n\t\tnumParams = factor.Dist.NumParams()\n\t)\n\tif len(factor.Vars) != numVars+numParams {\n\t\tpanic(stats.ErrfFactorVarNum(numVars, numParams, len(factor.Vars)))\n\t}\n\tvar (\n\t\tvars = make([]float64, numVars)\n\t\tparams = make([]float64, numParams)\n\t)\n\tfor i, rv := range factor.Vars {\n\t\tif i < len(vars) {\n\t\t\tvars[i] = rv.Val()\n\t\t} else {\n\t\t\tparams[i-len(vars)] = rv.Val()\n\t\t}\n\t}\n\treturn factor.Dist.Score(vars, params)\n}\n\n\nfunc NewConstFactor(vars []variable.RandomVariable, value float64) *ConstFactor {\n\treturn &ConstFactor{\n\t\tVars: vars,\n\t\tValue: value,\n\t}\n}\n\n\ntype ConstFactor struct {\n\tVars []variable.RandomVariable\n\tValue float64\n}\n\n\nfunc (factor ConstFactor) Adjacent() []variable.RandomVariable {\n\treturn factor.Vars\n}\n\n\nfunc (factor ConstFactor) Score() float64 {\n\treturn factor.Value\n}\n\nfunc (factor DistFactor) Adjacent() []variable.RandomVariable ", "output": "{\n\treturn factor.Vars\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/bitly/go-nsq\"\n)\n\n\n\ntype BackendQueue interface {\n\tPut([]byte) error\n\tReadChan() chan []byte \n\tClose() error\n\tDelete() error\n\tDepth() int64\n\tEmpty() error\n}\n\ntype DummyBackendQueue struct {\n\treadChan chan []byte\n}\n\nfunc NewDummyBackendQueue() BackendQueue {\n\treturn &DummyBackendQueue{readChan: make(chan []byte)}\n}\n\nfunc (d *DummyBackendQueue) Put([]byte) error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) ReadChan() chan []byte {\n\treturn d.readChan\n}\n\n\n\nfunc (d *DummyBackendQueue) Delete() error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Depth() int64 {\n\treturn int64(0)\n}\n\nfunc (d *DummyBackendQueue) Empty() error {\n\treturn nil\n}\n\nfunc WriteMessageToBackend(buf *bytes.Buffer, msg *nsq.Message, bq BackendQueue) error {\n\tbuf.Reset()\n\terr := msg.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = bq.Put(buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package context\n\nimport (\n\t\"github.com/julienschmidt/httprouter\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"golang.org/x/net/context\"\n\t\"testing\"\n)\n\n\n\nfunc TestGetterAndSetter(t *testing.T) ", "output": "{\n\tparams := httprouter.Params{{\"foo\", \"bar\"}}\n\tctx := NewContextFromRouterParams(context.Background(), params)\n\tassert.NotNil(t, ctx)\n\tres, err := FetchRouterParamsFromContext(ctx, \"foo\")\n\tassert.Nil(t, err)\n\tassert.Equal(t, map[string]string{\"foo\": \"bar\"}, res)\n\n\t_, err = FetchRouterParamsFromContext(context.Background(), \"foo\")\n\tassert.NotNil(t, err)\n}"} {"input": "package utils\n\nimport (\n\t\"code.google.com/p/goauth2/oauth\"\n\t\"github.com/google/go-github/github\"\n\t\"github.com/pinterb/hsc/config\"\n)\n\n\ntype Utils struct {\n\tclient *github.Client\n\tconfig *config.Config\n\n\tUsers *UserUtils\n}\n\n\ntype Response struct {\n\t*github.Response\n}\n\n\nfunc NewUtils(config *config.Config) *Utils {\n\n\tclient := github.NewClient(nil)\n\tif config != nil {\n\t\tt := &oauth.Transport{\n\t\t\tToken: &oauth.Token{AccessToken: config.Token},\n\t\t}\n\n\t\tclient = github.NewClient(t.Client())\n\t}\n\n\tu := &Utils{config: config, client: client}\n\tu.Users = &UserUtils{Utils: u}\n\n\treturn u\n}\n\n\n\n\nfunc NewResponse(r *github.Response) *Response ", "output": "{\n\tresp := &Response{Response: r}\n\treturn resp\n}"} {"input": "package action\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"fmt\"\n)\n\ntype Http struct {\n\tconfig *ActionConfig\n}\n\nfunc (h *Http) Run() (*Result, error) {\n\turl := h.config.Params.GetString(\"url\")\n\tif url == \"\" {\n\t\treturn nil, fmt.Errorf(\"url parameter required\")\n\t}\n\n\tmethod := h.config.Params.GetString(\"method\")\n\tif method == \"\" {\n\t\tmethod = \"GET\"\n\t} else {\n\t\tmethod = strings.ToUpper(method)\n\t}\n\n\tclient := &http.Client{}\n\n\th.config.Log.Debugf(\"%s %s\", method, url)\n\n\treq, err := http.NewRequest(method, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult, err := h.genResult(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\n\n\nfunc NewHttp(config *ActionConfig) *Http {\n\treturn &Http{\n\t\tconfig: config,\n\t}\n}\n\nfunc (h *Http) genResult(resp *http.Response) (*Result, error) ", "output": "{\n\tdata := make(map[string]interface{})\n\tdata[\"status-code\"] = resp.StatusCode\n\tdata[\"headers\"] = resp.Header\n\n\th.config.Log.Infof(\"%s %s -> %d\", resp.Request.Method, resp.Request.URL.String(), resp.StatusCode)\n\n\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata[\"raw-body\"] = bodyBytes\n\tdata[\"body\"] = string(bodyBytes)\n\n\treturn &Result{\n\t\tData: data,\n\t}, nil\n}"} {"input": "package eventlistener\n\nimport (\n\t\"testing\"\n\t\"github.com/docker/docker/api/types\"\n\t\"golang.org/x/net/context\"\n\t\"fmt\"\n\t\"time\"\n\t\"github.com/docker/docker/api/types/events\"\n)\n\n\nfunc TestEventListener(t *testing.T) {\n\n\tconst labelToMonitor = \"tugbot-test\"\n\ttsk := make(chan string, 10)\n\n\tRegister(dockerClientMock{}, labelToMonitor, tsk)\n\tselect {\n\tcase res := <-tsk:\n\t\tfmt.Println(\"we recieved the die container id via the tasks chan: \", res)\n\tcase <-time.After(time.Second * 5):\n\t\tt.Error(\"we did not recieved the die container id on the tasks chan after 5 sec!\")\n\t}\n}\n\ntype dockerClientMock struct {}\n\nfunc (d dockerClientMock) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) {\n\teventsChan := make(chan events.Message, 10)\n\terrChan := make(chan error, 10)\n\tevent := events.Message{ Type: \"container\", Action: \"die\", }\n\teventsChan <- event\n\treturn eventsChan, errChan\n}\n\nfunc (d dockerClientMock) RegistryLogin(ctx context.Context, auth types.AuthConfig) (types.AuthResponse, error) {\n\tpanic(\"This function not suppose to be called\")\n}\n\nfunc (d dockerClientMock) DiskUsage(ctx context.Context) (types.DiskUsage, error) {\n\tpanic(\"This function not suppose to be called\")\n}\n\nfunc (d dockerClientMock) Ping(ctx context.Context) (bool, error) {\n\tpanic(\"This function not suppose to be called\")\n}\n\nfunc (d dockerClientMock) Info(ctx context.Context) (types.Info, error) ", "output": "{\n\tpanic(\"This function not suppose to be called\")\n}"} {"input": "package command\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"google.golang.org/grpc\"\n\n\t\"github.com/itslab-kyushu/simple-kvs/kvs\"\n\t\"github.com/itslab-kyushu/sss/cfg\"\n\t\"github.com/urfave/cli\"\n)\n\ntype getOpt struct {\n\tConfig *cfg.Config\n\tName string\n\tOutputFile string\n\tLog io.Writer\n}\n\n\nfunc CmdGet(c *cli.Context) (err error) {\n\n\tif c.NArg() != 1 {\n\t\treturn cli.ShowSubcommandHelp(c)\n\t}\n\n\tconf, err := cfg.ReadConfig(c.String(\"config\"))\n\tif err != nil {\n\t\treturn\n\t}\n\n\toutput := c.String(\"output\")\n\tif output == \"\" {\n\t\toutput = c.Args().First()\n\t}\n\n\tvar log io.Writer\n\tif c.GlobalBool(\"quiet\") {\n\t\tlog = ioutil.Discard\n\t} else {\n\t\tlog = os.Stderr\n\t}\n\n\treturn cmdGet(&getOpt{\n\t\tConfig: conf,\n\t\tName: c.Args().First(),\n\t\tOutputFile: output,\n\t\tLog: log,\n\t})\n\n}\n\n\n\nfunc cmdGet(opt *getOpt) (err error) ", "output": "{\n\n\tif opt.Config.NServers() == 0 {\n\t\treturn fmt.Errorf(\"No server information is given.\")\n\t}\n\n\tfmt.Fprintln(opt.Log, \"Downloading a file\")\n\tserver := opt.Config.Servers[0]\n\n\tconn, err := grpc.Dial(\n\t\tfmt.Sprintf(\"%s:%d\", server.Address, server.Port),\n\t\tgrpc.WithInsecure(),\n\t\tgrpc.WithCompressor(grpc.NewGZIPCompressor()),\n\t\tgrpc.WithDecompressor(grpc.NewGZIPDecompressor()),\n\t)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tclient := kvs.NewKvsClient(conn)\n\tvalue, err := client.Get(context.Background(), &kvs.Key{\n\t\tName: opt.Name,\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ioutil.WriteFile(opt.OutputFile, value.Value, 0644)\n\n}"} {"input": "package douban\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n\n\t\"github.com/q191201771/chef_go/http\"\n)\n\ntype Book struct {\n\tpubdate time.Time\n\tAuthors []string `json:\"author\"`\n\tTitle string `json:\"title\"`\n\tPubDate string `json:\"pubdate\"`\n\tISBN10 string `json:\"isbn10\"`\n\tSummary string `json:\"summary\"`\n}\n\ntype Resp struct {\n\tCount int `json:\"count\"`\n\tStart int `json:\"start\"`\n\tTotal int `json:\"total\"`\n\tBooks []Book `json:\"books\"`\n}\n\nconst PATH = \"https://api.douban.com/v2/book/search\"\n\n\n\nfunc Fetch(bookname string) Book ", "output": "{\n\tvar resp Resp\n\n\tqueries := map[string]string{\n\t\t\"q\": bookname,\n\t}\n\tres, _, _ := http.Get(PATH, queries, nil, nil)\n\n\terr := json.Unmarshal([]byte(res), &resp)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn resp.Books[0]\n}"} {"input": "package match\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\nfunc Match(t *testing.T, value interface{}) *Matcher {\n\treturn &Matcher{\n\t\tt: t,\n\t\tvalue: value,\n\t}\n}\n\n\nfunc IsNil(t *testing.T, value interface{}) *Matcher {\n\treturn Match(t, value).IsNil()\n}\n\n\nfunc IsNotNil(t *testing.T, value interface{}) *Matcher {\n\treturn Match(t, value).IsNotNil()\n}\n\n\nfunc Equals(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).Equals(other)\n}\n\n\nfunc NotEquals(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).NotEquals(other)\n}\n\n\nfunc LessThan(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).LessThan(other)\n}\n\n\nfunc GreaterThan(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).GreaterThan(other)\n}\n\n\nfunc Contains(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).Contains(other)\n}\n\n\n\n\n\nfunc KindOf(t *testing.T, value interface{}, kind reflect.Kind) *Matcher {\n\treturn Match(t, value).KindOf(kind)\n}\n\nfunc Matches(t *testing.T, value interface{}, pattern string) *Matcher ", "output": "{\n\treturn Match(t, value).Matches(pattern)\n}"} {"input": "package example\n\nimport (\n\t\"net/http\"\n\n\t\"gopkg.in/gin-gonic/gin.v1\"\n)\n\n\n\n\nfunc GinEngine() *gin.Engine {\n\tgin.SetMode(gin.TestMode)\n\tr := gin.New()\n\n\tr.GET(\"/\", ginHelloHandler)\n\n\treturn r\n}\n\nfunc ginHelloHandler(c *gin.Context) ", "output": "{\n\tc.String(http.StatusOK, \"Hello World\")\n}"} {"input": "package string\n\nimport (\n\tdss \"github.com/emirpasic/gods/stacks/arraystack\"\n)\n\n\nfunc Reverse(s string) string {\n\tr := []rune(s) \n\tfor i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n\t\tr[i], r[j] = r[j], r[i]\n\t}\n\treturn string(r)\n}\n\n\n\n\n\n\n\n\n\n\nfunc ReverseNest1(s string) string {\n\tr := []rune(s)\n\tswitchHeadTail(r)\n\treturn string(r)\n}\n\nfunc switchHeadTail(r []rune) {\n\tif len(r) <= 1 {\n\t\treturn\n\t}\n\tbottom, top := 0, len(r)-1\n\tr[bottom], r[top] = r[top], r[bottom]\n\tswitchHeadTail(r[bottom+1 : top])\n}\n\n\nfunc ReverseInStack(s string) string {\n\tr := []rune(s)\n\tstack := dss.New()\n\tfor i := 0; i < len(r); i++ {\n\t\tstack.Push(r[i])\n\t}\n\trs := make([]rune, len(r))\n\tfor i := 0; i < len(r); i++ {\n\t\tv, _ := stack.Pop()\n\t\tif v != nil {\n\t\t\trs[i] = v.(rune)\n\t\t}\n\t}\n\treturn string(rs)\n}\n\nfunc ReverseNest(s string) string ", "output": "{\n\tr := []rune(s)\n\tif len(r) == 1 || len(r) == 0 {\n\t\treturn s\n\t}\n\tsub := ReverseNest(string(r[1:]))\n\treturn sub + string(r[0:1])\n}"} {"input": "package tequilapi\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n\ntype APIServer interface {\n\tWait() error\n\tStartServing() error\n\tStop()\n\tAddress() (string, error)\n}\n\ntype apiServer struct {\n\terrorChannel chan error\n\thandler http.Handler\n\tlistenAddress string\n\tlistener net.Listener\n}\n\n\nfunc NewServer(address string, port int, handler http.Handler, corsPolicy CorsPolicy) APIServer {\n\tserver := apiServer{\n\t\tmake(chan error, 1),\n\t\tDisableCaching(ApplyCors(handler, corsPolicy)),\n\t\tfmt.Sprintf(\"%s:%d\", address, port),\n\t\tnil}\n\treturn &server\n}\n\n\nfunc (server *apiServer) Stop() {\n\tif server.listener == nil {\n\t\treturn\n\t}\n\tserver.listener.Close()\n}\n\n\nfunc (server *apiServer) Wait() error {\n\treturn <-server.errorChannel\n}\n\n\n\n\n\n\nfunc (server *apiServer) StartServing() error {\n\tvar err error\n\tserver.listener, err = net.Listen(\"tcp\", server.listenAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo server.serve(server.handler)\n\treturn nil\n}\n\nfunc (server *apiServer) serve(handler http.Handler) {\n\tserver.errorChannel <- http.Serve(server.listener, handler)\n}\n\nfunc extractBoundAddress(listener net.Listener) (string, error) {\n\taddr := listener.Addr()\n\tparts := strings.Split(addr.String(), \":\")\n\tif len(parts) < 2 {\n\t\treturn \"\", errors.New(\"Unable to locate address: \" + addr.String())\n\t}\n\treturn addr.String(), nil\n}\n\nfunc (server *apiServer) Address() (string, error) ", "output": "{\n\tif server.listener == nil {\n\t\treturn \"\", errors.New(\"not bound\")\n\t}\n\treturn extractBoundAddress(server.listener)\n}"} {"input": "package tmdb\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Changes struct {\n\tResults []struct {\n\t\tID int\n\t\tAdult bool\n\t}\n}\n\nvar changeOptions = map[string]struct{}{\n\t\"page\": {},\n\t\"start_date\": {},\n\t\"end_date\": {}}\n\n\n\nfunc (tmdb *TMDb) GetChangesMovie(options map[string]string) (*Changes, error) {\n\tvar movieChanges Changes\n\toptionsString := getOptionsString(options, changeOptions)\n\turi := fmt.Sprintf(\"%s/movie/changes?api_key=%s%s\", baseURL, tmdb.apiKey, optionsString)\n\tresult, err := getTmdb(uri, &movieChanges)\n\treturn result.(*Changes), err\n}\n\n\n\nfunc (tmdb *TMDb) GetChangesPerson(options map[string]string) (*Changes, error) {\n\tvar personChanges Changes\n\toptionsString := getOptionsString(options, changeOptions)\n\turi := fmt.Sprintf(\"%s/person/changes?api_key=%s%s\", baseURL, tmdb.apiKey, optionsString)\n\tresult, err := getTmdb(uri, &personChanges)\n\treturn result.(*Changes), err\n}\n\n\n\n\n\nfunc (tmdb *TMDb) GetChangesTv(options map[string]string) (*Changes, error) ", "output": "{\n\tvar tvChanges Changes\n\toptionsString := getOptionsString(options, changeOptions)\n\turi := fmt.Sprintf(\"%s/tv/changes?api_key=%s%s\", baseURL, tmdb.apiKey, optionsString)\n\tresult, err := getTmdb(uri, &tvChanges)\n\treturn result.(*Changes), err\n}"} {"input": "package service\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc TestService_OnlineList(t *testing.T) {\n\tConvey(\"online list\", t, WithService(func(s *Service) {\n\t\tdata, err := s.OnlineList(context.Background())\n\t\tSo(err, ShouldBeNil)\n\t\tPrintf(\"%v\", data)\n\t}))\n}\n\n\n\nfunc TestService_OnlineArchiveCount(t *testing.T) ", "output": "{\n\tConvey(\"test online OnlineArchiveCount\", t, WithService(func(s *Service) {\n\t\tres := s.OnlineArchiveCount(context.Background())\n\t\tSo(res, ShouldNotBeNil)\n\t}))\n}"} {"input": "package gc\n\nimport \"strconv\"\n\nfunc _() {\n\tvar x [1]struct{}\n\t_ = x[Pxxx-0]\n\t_ = x[PEXTERN-1]\n\t_ = x[PAUTO-2]\n\t_ = x[PAUTOHEAP-3]\n\t_ = x[PPARAM-4]\n\t_ = x[PPARAMOUT-5]\n\t_ = x[PFUNC-6]\n}\n\nconst _Class_name = \"PxxxPEXTERNPAUTOPAUTOHEAPPPARAMPPARAMOUTPFUNC\"\n\nvar _Class_index = [...]uint8{0, 4, 11, 16, 25, 31, 40, 45}\n\n\n\nfunc (i Class) String() string ", "output": "{\n\tif i >= Class(len(_Class_index)-1) {\n\t\treturn \"Class(\" + strconv.FormatInt(int64(i), 10) + \")\"\n\t}\n\treturn _Class_name[_Class_index[i]:_Class_index[i+1]]\n}"} {"input": "package main\n\ntype OffState struct {\n\tstatusLed Output\n}\n\nfunc NewOffState(statusLed Output) State {\n\ts := OffState{statusLed: statusLed}\n\treturn &s\n}\n\n\n\nfunc (s *OffState) Event(m StateMachine, pin uint, value uint) {\n\tif pin == GPIO_SWITCH_PIN && value == GPIO_SWITCH_ON {\n\t\tm.Transit(STATE_WAITING)\n\t}\n}\n\nfunc (s *OffState) Leave(m StateMachine) {}\n\nfunc (s *OffState) String() string {\n\treturn \"Off\"\n}\n\nfunc (s *OffState) Enter(m StateMachine) ", "output": "{\n\ts.statusLed.Low()\n}"} {"input": "package cache\n\nimport (\n\t\"time\"\n\n\tutilcache \"k8s.io/apimachinery/pkg/util/cache\"\n\t\"k8s.io/apimachinery/pkg/util/clock\"\n)\n\ntype simpleCache struct {\n\tcache *utilcache.Expiring\n}\n\nfunc newSimpleCache(clock clock.Clock) cache {\n\treturn &simpleCache{cache: utilcache.NewExpiringWithClock(clock)}\n}\n\n\n\nfunc (c *simpleCache) set(key string, value *cacheRecord, ttl time.Duration) {\n\tc.cache.Set(key, value, ttl)\n}\n\nfunc (c *simpleCache) remove(key string) {\n\tc.cache.Delete(key)\n}\n\nfunc (c *simpleCache) get(key string) (*cacheRecord, bool) ", "output": "{\n\trecord, ok := c.cache.Get(key)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\tvalue, ok := record.(*cacheRecord)\n\treturn value, ok\n}"} {"input": "package protocol\n\nimport \"sync\"\n\nvar msgPool = sync.Pool{\n\tNew: func() interface{} {\n\t\theader := Header([12]byte{})\n\t\theader[0] = magicNumber\n\n\t\treturn &Message{\n\t\t\tHeader: &header,\n\t\t}\n\t},\n}\n\n\n\n\n\nfunc FreeMsg(msg *Message) {\n\tif msg != nil {\n\t\tmsg.Reset()\n\t\tmsgPool.Put(msg)\n\t}\n}\n\nvar poolUint32Data = sync.Pool{\n\tNew: func() interface{} {\n\t\tdata := make([]byte, 4)\n\t\treturn &data\n\t},\n}\n\nfunc GetPooledMsg() *Message ", "output": "{\n\treturn msgPool.Get().(*Message)\n}"} {"input": "package main_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/boltdb/bolt\"\n\t. \"github.com/boltdb/bolt/cmd/bolt\"\n)\n\n\n\n\n\nfunc TestBucketsDBNotFound(t *testing.T) {\n\tSetTestMode(true)\n\toutput := run(\"buckets\", \"no/such/db\")\n\tequals(t, \"stat no/such/db: no such file or directory\", output)\n}\n\nfunc TestBuckets(t *testing.T) ", "output": "{\n\tSetTestMode(true)\n\topen(func(db *bolt.DB, path string) {\n\t\tdb.Update(func(tx *bolt.Tx) error {\n\t\t\ttx.CreateBucket([]byte(\"woojits\"))\n\t\t\ttx.CreateBucket([]byte(\"widgets\"))\n\t\t\ttx.CreateBucket([]byte(\"whatchits\"))\n\t\t\treturn nil\n\t\t})\n\t\tdb.Close()\n\t\toutput := run(\"buckets\", path)\n\t\tequals(t, \"whatchits\\nwidgets\\nwoojits\", output)\n\t})\n}"} {"input": "package model\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/utils\"\n\n\t\"errors\"\n\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/converter\"\n\n\t\"strings\"\n)\n\n\ntype PrePaidServerSchedulerHints struct {\n\n\tGroup *string `json:\"group,omitempty\"`\n\n\tTenancy *PrePaidServerSchedulerHintsTenancy `json:\"tenancy,omitempty\"`\n\n\tDedicatedHostId *string `json:\"dedicated_host_id,omitempty\"`\n}\n\nfunc (o PrePaidServerSchedulerHints) String() string {\n\tdata, err := utils.Marshal(o)\n\tif err != nil {\n\t\treturn \"PrePaidServerSchedulerHints struct{}\"\n\t}\n\n\treturn strings.Join([]string{\"PrePaidServerSchedulerHints\", string(data)}, \" \")\n}\n\ntype PrePaidServerSchedulerHintsTenancy struct {\n\tvalue string\n}\n\ntype PrePaidServerSchedulerHintsTenancyEnum struct {\n\tSHARED PrePaidServerSchedulerHintsTenancy\n\tDEDICATED PrePaidServerSchedulerHintsTenancy\n}\n\n\n\nfunc (c PrePaidServerSchedulerHintsTenancy) MarshalJSON() ([]byte, error) {\n\treturn utils.Marshal(c.value)\n}\n\nfunc (c *PrePaidServerSchedulerHintsTenancy) UnmarshalJSON(b []byte) error {\n\tmyConverter := converter.StringConverterFactory(\"string\")\n\tif myConverter != nil {\n\t\tval, err := myConverter.CovertStringToInterface(strings.Trim(string(b[:]), \"\\\"\"))\n\t\tif err == nil {\n\t\t\tc.value = val.(string)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t} else {\n\t\treturn errors.New(\"convert enum data to string error\")\n\t}\n}\n\nfunc GetPrePaidServerSchedulerHintsTenancyEnum() PrePaidServerSchedulerHintsTenancyEnum ", "output": "{\n\treturn PrePaidServerSchedulerHintsTenancyEnum{\n\t\tSHARED: PrePaidServerSchedulerHintsTenancy{\n\t\t\tvalue: \"shared\",\n\t\t},\n\t\tDEDICATED: PrePaidServerSchedulerHintsTenancy{\n\t\t\tvalue: \"dedicated\",\n\t\t},\n\t}\n}"} {"input": "package proxy\n\nimport (\n\t\"store\"\n\t\"utils\"\n)\n\nconst (\n\tEFFICIENT_POOL_KEY = \"EfficientPoolKey\"\n)\n\nvar (\n\tefficientPool = InitEfficientPool()\n)\n\ntype EfficientPool struct {\n\tBasePool\n\tStorage store.SetStringStorer\n}\n\nfunc InitEfficientPool() *EfficientPool {\n\treturn &EfficientPool{BasePool: *InitBasePool(), Storage: store.RedisSet{}}\n}\n\n\n\nfunc (pool *EfficientPool) Remove(proxy string) {\n\tpool.Storage.Remove(EFFICIENT_POOL_KEY, proxy)\n}\n\nfunc Rand() (ok bool, proxy string) {\n\treturn efficientPool.Storage.Rand(EFFICIENT_POOL_KEY)\n}\n\nfunc Feedback(proxy string, ok bool, time int) {\n\tstablePool.Add(proxy, utils.EscapeToTime(ok, time))\n\n\tif !ok {\n\t\tefficientPool.Remove(proxy)\n\t}\n}\n\nfunc (pool *EfficientPool) Add(proxy string) ", "output": "{\n\tpool.Storage.Add(EFFICIENT_POOL_KEY, proxy)\n}"} {"input": "package models\n\nimport \"encoding/binary\"\n\n\n\ntype Page struct {\n\tPrev bool\n\tPrevVal int\n\n\tNext bool\n\tNextVal int\n\n\tNextURL string\n\n\tpages int\n\tPages []string\n\tTotal int\n\tCount int\n\tSkip int\n}\n\n\nfunc itob(v int) []byte {\n\tb := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(b, uint64(v))\n\treturn b\n}\n\n\n\n\n\nfunc SearchPagination(count int, page int, perPage int) Page ", "output": "{\n\tvar pg Page\n\tvar total int\n\n\tif count%perPage != 0 {\n\t\ttotal = count/perPage + 1\n\t} else {\n\t\ttotal = count / perPage\n\t}\n\n\tif total < page {\n\t\tpage = total\n\t}\n\n\tif page == 1 {\n\t\tpg.Prev = false\n\t\tpg.Next = true\n\t}\n\n\tif page != 1 {\n\t\tpg.Prev = true\n\t}\n\n\tif total > page {\n\t\tpg.Next = true\n\t}\n\n\tif total == page {\n\t\tpg.Next = false\n\t}\n\n\tvar pgs = make([]string, total)\n\n\tskip := perPage * (page - 1)\n\n\tpg.Total = total\n\tpg.Skip = skip\n\tpg.Count = count\n\tpg.NextVal = page + 1\n\tpg.PrevVal = page - 1\n\tpg.Pages = pgs\n\n\treturn pg\n}"} {"input": "package go_koans\n\nfunc isPrimeNumber(possiblePrime int) bool {\n\tfor underPrime := 2; underPrime < possiblePrime; underPrime++ {\n\t\tif possiblePrime%underPrime == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\nfunc aboutConcurrency() {\n\tch := make(chan int)\n\n\tassert(__delete_me__) \n\n\tassert(<-ch == 2)\n\tassert(<-ch == 3)\n\tassert(<-ch == 5)\n\tassert(<-ch == 7)\n\tassert(<-ch == 11)\n}\n\nfunc findPrimeNumbers(channel chan int) ", "output": "{\n\tfor i := 2; ; i++ {\n\n\t\tassert(i < 100) \n\t}\n}"} {"input": "package v1beta1\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/knative-gcp/pkg/apis/duck\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\t\"github.com/google/go-cmp/cmp/cmpopts\"\n\n\t\"knative.dev/pkg/apis\"\n)\n\nfunc (t *Topic) Validate(ctx context.Context) *apis.FieldError {\n\terr := t.Spec.Validate(ctx).ViaField(\"spec\")\n\n\tif apis.IsInUpdate(ctx) {\n\t\toriginal := apis.GetBaseline(ctx).(*Topic)\n\t\terr = err.Also(t.CheckImmutableFields(ctx, original))\n\t}\n\treturn err\n}\n\n\n\nfunc (current *Topic) CheckImmutableFields(ctx context.Context, original *Topic) *apis.FieldError {\n\tif original == nil {\n\t\treturn nil\n\t}\n\n\tvar errs *apis.FieldError\n\tif diff := cmp.Diff(original.Spec, current.Spec,\n\t\tcmpopts.IgnoreFields(TopicSpec{})); diff != \"\" {\n\t\terrs = errs.Also(&apis.FieldError{\n\t\t\tMessage: \"Immutable fields changed (-old +new)\",\n\t\t\tPaths: []string{\"spec\"},\n\t\t\tDetails: diff,\n\t\t})\n\t}\n\terrs = duck.CheckImmutableAutoscalingClassAnnotations(¤t.ObjectMeta, &original.ObjectMeta, errs)\n\n\treturn duck.CheckImmutableClusterNameAnnotation(¤t.ObjectMeta, &original.ObjectMeta, errs)\n}\n\nfunc (ts *TopicSpec) Validate(ctx context.Context) *apis.FieldError ", "output": "{\n\tvar errs *apis.FieldError\n\n\tif ts.Topic == \"\" {\n\t\terrs = errs.Also(\n\t\t\tapis.ErrMissingField(\"topic\"),\n\t\t)\n\t}\n\n\tswitch ts.PropagationPolicy {\n\tcase TopicPolicyCreateDelete, TopicPolicyCreateNoDelete, TopicPolicyNoCreateNoDelete:\n\n\tdefault:\n\t\terrs = errs.Also(\n\t\t\tapis.ErrInvalidValue(ts.PropagationPolicy, \"propagationPolicy\"),\n\t\t)\n\t}\n\n\treturn errs\n}"} {"input": "package manual\n\nimport (\n\t\"os/exec\"\n)\n\ntype sshOption []string\n\nvar allocateTTY sshOption = []string{\"-t\"}\n\n\n\nvar commonSSHOptions = []string{\"-o\", \"StrictHostKeyChecking no\"}\n\n\n\nfunc sshCommand(host string, command string, options ...sshOption) *exec.Cmd ", "output": "{\n\targs := append([]string{}, commonSSHOptions...)\n\tfor _, option := range options {\n\t\targs = append(args, option...)\n\t}\n\targs = append(args, host, \"--\", command)\n\treturn exec.Command(\"ssh\", args...)\n}"} {"input": "package oci\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/phoenix-io/phoenix-mon/plugins\"\n\tps \"github.com/shirou/gopsutil/process\"\n\t\"io/ioutil\"\n)\n\ntype OCI struct {\n\tprocess []plugin.Process\n\tcount\tint\n}\n\ntype PState struct {\n\tID string `json:\"id\"`\n\tPid int `json:\"init_process_pid\"`\n}\n\nfunc init() {\n\tplugin.Register(\"oci\", &plugin.RegisteredPlugin{New: NewPlugin})\n}\n\n\n\nfunc (p *OCI) GetProcessList() ([]plugin.Process, error) {\n\n\tvar state PState\n\tcontainers, _ := ioutil.ReadDir(\"/run/oci/\")\n\tfor _, c := range containers {\n\t\tdata, err := ioutil.ReadFile(\"/run/oci/\" + c.Name() + \"/state.json\")\n\t\tif err != nil {\n\t\t\treturn p.process, fmt.Errorf(\"Error in reading file\")\n\t\t}\n\n\t\tjson.Unmarshal(data, &state)\n\t\tname := fmt.Sprintf(\"%s %d\",state.ID,p.count)\n\t\tp.count++\n\t\tp.process = append(p.process, plugin.Process{Pid: state.Pid, Name: name})\n\t}\n\n\treturn p.process, nil\n}\n\nfunc (p *OCI) GetProcessStat(process plugin.Process) (plugin.Process, error) {\n\tres, err := ps.NewProcess(int32(process.Pid))\n\tif err != nil {\n\t\tfmt.Println(\"Unable to Create Process Object\")\n\t}\n\tmemInfo, err := res.MemoryInfo()\n\tif err != nil {\n\t\treturn process, fmt.Errorf(\"geting ppid error %v\", err)\n\n\t}\n\tprocess.Memory = memInfo.RSS\n\treturn process, nil\n}\n\nfunc NewPlugin(pluginName string) (plugin.Plugin, error) ", "output": "{\n\treturn &OCI{}, nil\n}"} {"input": "package sparta\n\nimport (\n\t\"context\"\n\n\t\"github.com/aws/aws-lambda-go/lambdacontext\"\n)\n\nfunc cloudWatchLogsProcessor(ctx context.Context,\n\tprops map[string]interface{}) error {\n\tlambdaCtx, _ := lambdacontext.FromContext(ctx)\n\tLogger().Info().\n\t\tStr(\"RequestID\", lambdaCtx.AwsRequestID).\n\t\tMsg(\"CloudWatch log event\")\n\tLogger().Info().Msg(\"CloudWatch Log event received\")\n\treturn nil\n}\n\n\n\nfunc ExampleCloudWatchLogsPermission() ", "output": "{\n\tvar lambdaFunctions []*LambdaAWSInfo\n\n\tcloudWatchLogsLambda, _ := NewAWSLambda(LambdaName(cloudWatchLogsProcessor),\n\t\tcloudWatchLogsProcessor,\n\t\tIAMRoleDefinition{})\n\n\tcloudWatchLogsPermission := CloudWatchLogsPermission{}\n\tcloudWatchLogsPermission.Filters = make(map[string]CloudWatchLogsSubscriptionFilter, 1)\n\tcloudWatchLogsPermission.Filters[\"MyFilter\"] = CloudWatchLogsSubscriptionFilter{\n\t\tLogGroupName: \"/aws/lambda/*\",\n\t}\n\tcloudWatchLogsLambda.Permissions = append(cloudWatchLogsLambda.Permissions, cloudWatchLogsPermission)\n\n\tlambdaFunctions = append(lambdaFunctions, cloudWatchLogsLambda)\n\tmainErr := Main(\"CloudWatchLogs\", \"Registers for CloudWatch Logs\", lambdaFunctions, nil, nil)\n\tif mainErr != nil {\n\t\tpanic(\"Failed to invoke sparta.Main: %s\" + mainErr.Error())\n\t}\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1alpha1 \"k8s.io/kops/pkg/client/clientset_generated/clientset/typed/kops/v1alpha1\"\n)\n\ntype FakeKopsV1alpha1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeKopsV1alpha1) Clusters(namespace string) v1alpha1.ClusterInterface {\n\treturn &FakeClusters{c, namespace}\n}\n\nfunc (c *FakeKopsV1alpha1) InstanceGroups(namespace string) v1alpha1.InstanceGroupInterface {\n\treturn &FakeInstanceGroups{c, namespace}\n}\n\nfunc (c *FakeKopsV1alpha1) SSHCredentials(namespace string) v1alpha1.SSHCredentialInterface {\n\treturn &FakeSSHCredentials{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeKopsV1alpha1) RESTClient() rest.Interface ", "output": "{\n\tvar ret *rest.RESTClient\n\treturn ret\n}"} {"input": "package logger\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/influxdata/wlog\"\n)\n\n\nfunc newTelegrafWriter(w io.Writer) io.Writer {\n\treturn &telegrafLog{\n\t\twriter: wlog.NewWriter(w),\n\t}\n}\n\ntype telegrafLog struct {\n\twriter io.Writer\n}\n\n\n\n\n\n\n\n\n\nfunc SetupLogging(debug, quiet bool, logfile string) {\n\tif debug {\n\t\twlog.SetLevel(wlog.DEBUG)\n\t}\n\tif quiet {\n\t\twlog.SetLevel(wlog.ERROR)\n\t}\n\n\tvar oFile *os.File\n\tif logfile != \"\" {\n\t\tif _, err := os.Stat(logfile); os.IsNotExist(err) {\n\t\t\tif oFile, err = os.Create(logfile); err != nil {\n\t\t\t\tlog.Printf(\"E! Unable to create %s (%s), using stdout\", logfile, err)\n\t\t\t\toFile = os.Stdout\n\t\t\t}\n\t\t} else {\n\t\t\tif oFile, err = os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, os.ModeAppend); err != nil {\n\t\t\t\tlog.Printf(\"E! Unable to append to %s (%s), using stdout\", logfile, err)\n\t\t\t\toFile = os.Stdout\n\t\t\t}\n\t\t}\n\t} else {\n\t\toFile = os.Stdout\n\t}\n\n\tlog.SetOutput(newTelegrafWriter(oFile))\n}\n\nfunc (t *telegrafLog) Write(p []byte) (n int, err error) ", "output": "{\n\treturn t.writer.Write(p)\n}"} {"input": "package cpdf\n\nimport (\n\t\"io/ioutil\"\n)\n\n\ntype bookmarkable interface {\n\tCombinedBookmarkList() string\n\tLocalPath() string\n\tDir() string\n}\n\nfunc (c *Cpdf) addBookmarksArgs(job bookmarkable) {\n\tc.addArgs(\"-add-bookmarks\", infoPath(job))\n}\n\n\n\nfunc infoPath(job bookmarkable) string {\n\treturn job.Dir() + \"bookmarks.info\"\n}\n\nfunc writeBookmarkInfoFile(job bookmarkable) error ", "output": "{\n\treturn ioutil.WriteFile(infoPath(job), []byte(job.CombinedBookmarkList()), 0644)\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/mgoltzsche/ctnr/bundle/builder\"\n\t\"github.com/mgoltzsche/ctnr/model/oci\"\n\t\"github.com/mgoltzsche/ctnr/run\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar (\n\texecCmd = &cobra.Command{\n\t\tUse: \"exec [flags] CONTAINERID COMMAND\",\n\t\tShort: \"Executes a process in a container\",\n\t\tLong: `Executes a process in a container.`,\n\t\tRun: wrapRun(runExec),\n\t}\n\n\n)\n\n\n\nfunc runExec(cmd *cobra.Command, args []string) (err error) {\n\tif len(args) < 1 {\n\t\treturn usageError(\"No CONTAINERID argument specified\")\n\t}\n\tif len(args) < 2 {\n\t\treturn usageError(\"No COMMAND argument specified\")\n\t}\n\tif err := flagsBundle.SetBundleArgs(args); err != nil {\n\t\treturn err\n\t}\n\tservice, err := flagsBundle.Read()\n\tif err != nil {\n\t\treturn\n\t}\n\tspec := builder.NewSpecBuilder()\n\tif err = oci.ToSpecProcess(&service.Process, flagPRootPath, &spec); err != nil {\n\t\treturn\n\t}\n\tmanager, err := newContainerManager()\n\tif err != nil {\n\t\treturn\n\t}\n\tcontainer, err := manager.Get(args[0])\n\tif err != nil {\n\t\treturn\n\t}\n\tsp, err := spec.Spec(container.Rootfs())\n\tif err != nil {\n\t\treturn\n\t}\n\tproc, err := container.Exec(sp.Process, run.NewStdContainerIO())\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif e := proc.Close(); e != nil && err == nil {\n\t\t\terr = e\n\t\t}\n\t}()\n\treturn proc.Wait()\n}\n\nfunc init() ", "output": "{\n\tflagsBundle.InitProcessFlags(execCmd.Flags())\n\tflagsBundle.InitRunFlags(execCmd.Flags())\n}"} {"input": "package esbuilder\n\nimport \"github.com/serulian/compiler/sourcemap\"\n\n\ntype StatementBuilder interface {\n\tWithMapping(mapping sourcemap.SourceMapping) SourceBuilder\n\n\tmapping() (sourcemap.SourceMapping, bool)\n\n\temitSource(sb *sourceBuilder)\n}\n\n\ntype statementNode interface {\n\temit(sb *sourceBuilder)\n}\n\n\ntype statementBuilder struct {\n\tstatement statementNode\n\n\tsourceMapping *sourcemap.SourceMapping\n}\n\nfunc (builder statementBuilder) mapping() (sourcemap.SourceMapping, bool) {\n\tif builder.sourceMapping == nil {\n\t\treturn sourcemap.SourceMapping{}, false\n\t}\n\n\treturn *builder.sourceMapping, true\n}\n\n\n\n\nfunc (builder statementBuilder) WithMapping(mapping sourcemap.SourceMapping) SourceBuilder {\n\tbuilder.sourceMapping = &mapping\n\treturn builder\n}\n\nfunc (builder statementBuilder) emitSource(sb *sourceBuilder) ", "output": "{\n\tbuilder.statement.emit(sb)\n}"} {"input": "package datastore\n\nimport \"strconv\"\n\nfunc _() {\n\tvar x [1]struct{}\n\t_ = x[PTNull-0]\n\t_ = x[PTInt-1]\n\t_ = x[PTTime-2]\n\t_ = x[PTBool-3]\n\t_ = x[PTBytes-4]\n\t_ = x[PTString-5]\n\t_ = x[PTFloat-6]\n\t_ = x[PTGeoPoint-7]\n\t_ = x[PTKey-8]\n\t_ = x[PTBlobKey-9]\n\t_ = x[PTPropertyMap-10]\n\t_ = x[PTUnknown-11]\n}\n\nconst _PropertyType_name = \"PTNullPTIntPTTimePTBoolPTBytesPTStringPTFloatPTGeoPointPTKeyPTBlobKeyPTPropertyMapPTUnknown\"\n\nvar _PropertyType_index = [...]uint8{0, 6, 11, 17, 23, 30, 38, 45, 55, 60, 69, 82, 91}\n\n\n\nfunc (i PropertyType) String() string ", "output": "{\n\tif i >= PropertyType(len(_PropertyType_index)-1) {\n\t\treturn \"PropertyType(\" + strconv.FormatInt(int64(i), 10) + \")\"\n\t}\n\treturn _PropertyType_name[_PropertyType_index[i]:_PropertyType_index[i+1]]\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\nfunc setTimespec(sec, nsec int64) Timespec {\n\treturn Timespec{Sec: sec, Nsec: nsec}\n}\n\n\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint64(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint64(length)\n}\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\nfunc setTimeval(sec, usec int64) Timeval ", "output": "{\n\treturn Timeval{Sec: sec, Usec: usec}\n}"} {"input": "package gtimer\n\n\nfunc (h *priorityQueueHeap) Len() int {\n\treturn len(h.array)\n}\n\n\n\nfunc (h *priorityQueueHeap) Less(i, j int) bool {\n\treturn h.array[i].priority < h.array[j].priority\n}\n\n\n\n\n\nfunc (h *priorityQueueHeap) Push(x interface{}) {\n\th.array = append(h.array, x.(priorityQueueItem))\n}\n\n\nfunc (h *priorityQueueHeap) Pop() interface{} {\n\tlength := len(h.array)\n\tif length == 0 {\n\t\treturn nil\n\t}\n\titem := h.array[length-1]\n\th.array = h.array[0 : length-1]\n\treturn item\n}\n\nfunc (h *priorityQueueHeap) Swap(i, j int) ", "output": "{\n\tif len(h.array) == 0 {\n\t\treturn\n\t}\n\th.array[i], h.array[j] = h.array[j], h.array[i]\n}"} {"input": "package plan\n\nimport (\n\t\"github.com/pingcap/tidb/expression\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\nfunc projectionCanBeEliminated(p *Projection) bool {\n\tchild := p.children[0].(PhysicalPlan)\n\tif p.Schema().Len() != child.Schema().Len() {\n\t\treturn false\n\t}\n\tfor i, expr := range p.Exprs {\n\t\tcol, ok := expr.(*expression.Column)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\tif col.FromID != child.Schema().Columns[i].FromID || col.Position != child.Schema().Columns[i].Position {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc EliminateProjection(p PhysicalPlan) PhysicalPlan ", "output": "{\n\tswitch plan := p.(type) {\n\tcase *Projection:\n\t\tif !projectionCanBeEliminated(plan) {\n\t\t\tbreak\n\t\t}\n\t\tchild := plan.children[0].(PhysicalPlan)\n\t\tchild.SetSchema(plan.Schema())\n\t\tRemovePlan(p)\n\t\tp = EliminateProjection(child)\n\t}\n\tchildren := make([]Plan, 0, len(p.Children()))\n\tfor _, child := range p.Children() {\n\t\tchildren = append(children, EliminateProjection(child.(PhysicalPlan)))\n\t}\n\tp.SetChildren(children...)\n\treturn p\n}"} {"input": "package characteristic\n\nimport (\n\t\"github.com/brutella/hc/model\"\n)\n\ntype HeatingCoolingMode struct {\n\t*ByteCharacteristic\n}\n\nfunc NewHeatingCoolingMode(current model.HeatCoolModeType, charType CharType, permissions []string) *HeatingCoolingMode {\n\tc := HeatingCoolingMode{NewByteCharacteristic(byte(current), permissions)}\n\tc.Type = charType\n\n\treturn &c\n}\n\nfunc NewCurrentHeatingCoolingMode(current model.HeatCoolModeType) *HeatingCoolingMode {\n\treturn NewHeatingCoolingMode(current, CharTypeHeatingCoolingModeCurrent, PermsRead())\n}\n\nfunc NewTargetHeatingCoolingMode(current model.HeatCoolModeType) *HeatingCoolingMode {\n\treturn NewHeatingCoolingMode(current, CharTypeHeatingCoolingModeTarget, PermsAll())\n}\n\nfunc (c *HeatingCoolingMode) SetHeatingCoolingMode(mode model.HeatCoolModeType) {\n\tc.SetByte(byte(mode))\n}\n\n\n\nfunc (c *HeatingCoolingMode) HeatingCoolingMode() model.HeatCoolModeType ", "output": "{\n\treturn model.HeatCoolModeType(c.Byte())\n}"} {"input": "package fake\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\n\t. \"github.com/onsi/gomega\"\n\t\"github.com/onsi/gomega/ghttp\"\n)\n\ntype CFAPI struct {\n\tserver *ghttp.Server\n}\n\ntype CFAPIConfig struct {\n\tRoutes map[string]Response\n}\n\ntype Response struct {\n\tCode int\n\tBody interface{}\n}\n\nfunc NewCFAPI() *CFAPI {\n\tserver := ghttp.NewServer()\n\treturn &CFAPI{\n\t\tserver: server,\n\t}\n}\n\nfunc (a *CFAPI) SetConfiguration(config CFAPIConfig) {\n\ta.server.Reset()\n\n\tfor request, response := range config.Routes {\n\t\tmethod, path := parseRequest(request)\n\t\tresponseBytes, err := json.Marshal(response.Body)\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\ta.server.RouteToHandler(method, path, ghttp.RespondWith(response.Code, responseBytes))\n\t}\n}\n\nfunc (a *CFAPI) Close() {\n\ta.server.Close()\n}\n\nfunc (a *CFAPI) URL() string {\n\treturn a.server.URL()\n}\n\nfunc (a *CFAPI) ReceivedRequests() map[string][]*http.Request {\n\tresult := map[string][]*http.Request{}\n\n\tfor _, req := range a.server.ReceivedRequests() {\n\t\tkey := fmt.Sprintf(\"%s %s\", req.Method, req.URL.Path)\n\t\tresult[key] = append(result[key], req)\n\t}\n\n\treturn result\n}\n\n\n\nfunc parseRequest(request string) (string, string) ", "output": "{\n\tfields := strings.Split(request, \" \")\n\tExpect(fields).To(HaveLen(2))\n\treturn fields[0], fields[1]\n}"} {"input": "package astar\n\nimport (\n\t\"os\"\n\t\"image\"\n)\n\nimport _ \"image/png\"\n\nfunc openImage(filename string) (image.Image) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer f.Close()\n\timg, _, _ := image.Decode(f)\n\treturn img\n}\n\n\n\nfunc GetMapFromImage(filename string) MapData {\n\timg := openImage(filename)\n\tif(img == nil) {\n\t\treturn nil\n\t}\n\treturn parseImage(img)\n}\n\nfunc parseImage(img image.Image) MapData ", "output": "{\n\tmax := uint32(65536-1) \n\n\tbounds := img.Bounds()\n\tmap_data := NewMapData(bounds.Max.X, bounds.Max.Y)\n\tfor y := bounds.Min.Y; y < bounds.Max.Y; y++ {\n\t\tfor x := bounds.Min.X; x < bounds.Max.X; x++ {\n\t\t\tr, g, b, a := img.At(x, y).RGBA()\n\n\t\t\tif(r == max && g == max && b == max && a == max) {\n\t\t\t\tmap_data[x][bounds.Max.Y-1-y] = LAND\n\t\t\t} else {\n\t\t\t\tmap_data[x][bounds.Max.Y-1-y] = WALL\n\t\t\t}\n\t\t}\n\t}\n\treturn map_data\n}"} {"input": "package runconfig\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"strings\"\n\n\t\"github.com/hyperhq/hypercli/pkg/broadcaster\"\n\t\"github.com/hyperhq/hypercli/pkg/ioutils\"\n)\n\n\n\n\n\n\n\n\n\n\ntype StreamConfig struct {\n\tstdout *broadcaster.Unbuffered\n\tstderr *broadcaster.Unbuffered\n\tstdin io.ReadCloser\n\tstdinPipe io.WriteCloser\n}\n\n\n\nfunc NewStreamConfig() *StreamConfig {\n\treturn &StreamConfig{\n\t\tstderr: new(broadcaster.Unbuffered),\n\t\tstdout: new(broadcaster.Unbuffered),\n\t}\n}\n\n\nfunc (streamConfig *StreamConfig) Stdout() *broadcaster.Unbuffered {\n\treturn streamConfig.stdout\n}\n\n\nfunc (streamConfig *StreamConfig) Stderr() *broadcaster.Unbuffered {\n\treturn streamConfig.stderr\n}\n\n\nfunc (streamConfig *StreamConfig) Stdin() io.ReadCloser {\n\treturn streamConfig.stdin\n}\n\n\nfunc (streamConfig *StreamConfig) StdinPipe() io.WriteCloser {\n\treturn streamConfig.stdinPipe\n}\n\n\n\nfunc (streamConfig *StreamConfig) StdoutPipe() io.ReadCloser {\n\tbytesPipe := ioutils.NewBytesPipe(nil)\n\tstreamConfig.stdout.Add(bytesPipe)\n\treturn bytesPipe\n}\n\n\n\nfunc (streamConfig *StreamConfig) StderrPipe() io.ReadCloser {\n\tbytesPipe := ioutils.NewBytesPipe(nil)\n\tstreamConfig.stderr.Add(bytesPipe)\n\treturn bytesPipe\n}\n\n\nfunc (streamConfig *StreamConfig) NewInputPipes() {\n\tstreamConfig.stdin, streamConfig.stdinPipe = io.Pipe()\n}\n\n\nfunc (streamConfig *StreamConfig) NewNopInputPipe() {\n\tstreamConfig.stdinPipe = ioutils.NopWriteCloser(ioutil.Discard)\n}\n\n\n\n\nfunc (streamConfig *StreamConfig) CloseStreams() error ", "output": "{\n\tvar errors []string\n\n\tif streamConfig.stdin != nil {\n\t\tif err := streamConfig.stdin.Close(); err != nil {\n\t\t\terrors = append(errors, fmt.Sprintf(\"error close stdin: %s\", err))\n\t\t}\n\t}\n\n\tif err := streamConfig.stdout.Clean(); err != nil {\n\t\terrors = append(errors, fmt.Sprintf(\"error close stdout: %s\", err))\n\t}\n\n\tif err := streamConfig.stderr.Clean(); err != nil {\n\t\terrors = append(errors, fmt.Sprintf(\"error close stderr: %s\", err))\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn fmt.Errorf(strings.Join(errors, \"\\n\"))\n\t}\n\n\treturn nil\n}"} {"input": "package swt\n\nimport \"github.com/timob/javabind\"\n\ntype EventsTraverseEventInterface interface {\n\tEventsKeyEventInterface\n}\n\ntype EventsTraverseEvent struct {\n\tEventsKeyEvent\n}\n\n\n\n\n\nfunc (jbobject *EventsTraverseEvent) ToString() string {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"toString\", \"java/lang/String\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tretconv := javabind.NewJavaToGoString()\n\tdst := new(string)\n\tretconv.Dest(dst)\n\tif err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {\n\t\tpanic(err)\n\t}\n\tretconv.CleanUp()\n\treturn *dst\n}\n\nfunc (jbobject *EventsTraverseEvent) Detail() int {\n\tjret, err := jbobject.GetField(javabind.GetEnv(), \"detail\", javabind.Int)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn jret.(int)\n}\n\nfunc (jbobject *EventsTraverseEvent) SetFieldDetail(val int) {\n\terr := jbobject.SetField(javabind.GetEnv(), \"detail\", val)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n}\n\nfunc NewEventsTraverseEvent(a WidgetsEventInterface) (*EventsTraverseEvent) ", "output": "{\n\tconv_a := javabind.NewGoToJavaCallable()\n\tif err := conv_a.Convert(a); err != nil {\n\t\tpanic(err)\n\t}\n\n\tobj, err := javabind.GetEnv().NewObject(\"org/eclipse/swt/events/TraverseEvent\", conv_a.Value().Cast(\"org/eclipse/swt/widgets/Event\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tconv_a.CleanUp()\n\tx := &EventsTraverseEvent{}\n\tx.Callable = &javabind.Callable{obj}\n\treturn x\n}"} {"input": "package check\n\n\ntype GoFmt struct {\n\tDir string\n\tFilenames []string\n}\n\n\n\n\n\nfunc (g GoFmt) Weight() float64 {\n\treturn .35\n}\n\n\nfunc (g GoFmt) Percentage() (float64, []FileSummary, error) {\n\treturn GoTool(g.Dir, g.Filenames, []string{\"gofmt\", \"-s\", \"-l\"})\n}\n\n\nfunc (g GoFmt) Description() string {\n\treturn `Gofmt formats Go programs. We run gofmt -s on your code, where -s is for the \"simplify\" command`\n}\n\nfunc (g GoFmt) Name() string ", "output": "{\n\treturn \"gofmt\"\n}"} {"input": "package models\n\nimport \"fmt\"\n\n\nvar RoomPool = make([] *Room, 0)\n\nfunc AddRoom(r *Room) {\n\tRoomPool = append(RoomPool, r)\n}\n\n\n\n\n\nfunc FindRoom(d string) (int, *Room) {\n\tfor i, v := range RoomPool {\n\t\tif v.Name == d {\n\t\t\treturn i, v\n\t\t}\n\t}\n\treturn -1, &Room{}\n}\n\n\nfunc RemoveRoom(r *Room) {\n\n\tindex, _ := FindRoom(r.Name)\n\n\tif index != -1 {\n\t\tRoomPool = append(RoomPool[:index], RoomPool[index + 1:]...)\n\t}\n}\n\n\n\n\nfunc RemoveClient(c *Client) {\n\tfor _, room := range RoomPool{\n\t\tif room.Name == c.Room {\n\t\t\tif room.HasClient(c) {\n\t\t\t\troom.DeleteClient(c)\n\t\t\t\tif room.ClientCount() == 0 {\n\t\t\t\t\tRemoveRoom(room)\n\t\t\t\t\tPoolBroadcast(NewMessage(map[string]string{\n\t\t\t\t\t\t\"connectedClients\": fmt.Sprintf(\"%v\", GetAllClients()),\n\t\t\t\t\t\t\"numberOfRooms\": fmt.Sprintf(\"%v\", GetNumberOfRooms()),\n\t\t\t\t\t}))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n\n\n\nfunc PoolBroadcast(m Message) {\n\tfor _, room := range RoomPool {\n\t\troom.RoomBroadcast(m)\n\t}\n}\n\n\nfunc GetAllClients() int {\n\n\tclientSum := 0\n\tfor _, room := range RoomPool {\n\t\tclientSum += len(room.ClientPool)\n\t}\n\treturn clientSum\n}\n\n\nfunc GetNumberOfRooms() int{\n\treturn len(RoomPool)\n}\n\nfunc ListRooms() (int, []string) ", "output": "{\n\tpool := make([]string, 0)\n\tfor _, obj := range RoomPool {\n\t\tpool = append(pool, obj.Name)\n\t}\n\treturn len(RoomPool), pool\n}"} {"input": "package lwmq\n\nimport (\n\t\"fmt\"\n)\n\n\ntype MessageStore interface {\n\n\tMessages(*Queue) ([]*Message, error)\n\n\tAddMessage(*Message) error\n\n\tPopMessages(*Queue) ([]*Message, error)\n}\n\n\ntype MemoryMessageStore struct {\n\tmessages map[*Queue][]*Message\n}\n\nfunc NewMemoryMessageStore() *MemoryMessageStore {\n\ts := &MemoryMessageStore{\n\t\tmessages: make(map[*Queue][]*Message),\n\t}\n\treturn s\n}\n\n\n\n\nfunc (self *MemoryMessageStore) AddMessage(msg *Message) error {\n\tif msg.Queue == nil {\n\t\terr := fmt.Errorf(\"Can not store message without a queue\")\n\t\treturn err\n\t}\n\n\tmsg.Offline = true\n\n\tself.messages[msg.Queue] = append(self.messages[msg.Queue], msg)\n\n\treturn nil\n}\n\n\nfunc (self *MemoryMessageStore) Messages(q *Queue) ([]*Message, error) {\n\tmessages, ok := self.messages[q]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Unknown queue: %s\", q.Id)\n\t}\n\n\treturn messages, nil\n}\n\n\n\n\nfunc (self *MemoryMessageStore) PopMessages(q *Queue) ([]*Message, error) ", "output": "{\n\tmessages, err := self.Messages(q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tself.messages[q] = []*Message{}\n\n\treturn messages, nil\n}"} {"input": "package global\n\nimport (\n\t\"database/sql\"\n\t\"encoding/json\"\n\t\"html/template\"\n\t\"io/ioutil\"\n\t\"log\"\n)\n\n\nvar Templates *template.Template\n\n\nvar DB *sql.DB\n\n\nvar Config Configuration\n\n\ntype Configuration struct {\n\tPort string\n\tDbUser string\n\tDbPassword string\n\tDbName string\n\tJWTtokenPassword string\n}\n\n\n\n\n\n\n\nfunc ParseTemplates() {\n\tparsedTemplates, err := template.ParseGlob(\"templates/*.html\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttmpl := template.Must(parsedTemplates, err)\n\tTemplates = tmpl \n}\n\nfunc ReadConfig() Configuration ", "output": "{\n\tdata, err := ioutil.ReadFile(\"config.json\")\n\tif err != nil {\n\t\tlog.Fatal(\"Please add config.json file:\", err)\n\t}\n\tconfig := Configuration{}\n\tif err := json.Unmarshal(data, &config); err != nil {\n\t\tlog.Fatal(\"Please format configuration file correctly:\", err)\n\t}\n\n\tParseTemplates()\n\n\tConfig = config \n\treturn config\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\ntype UpdatePublicIpDetails struct {\n\n\tDefinedTags map[string]map[string]interface{} `mandatory:\"false\" json:\"definedTags\"`\n\n\tDisplayName *string `mandatory:\"false\" json:\"displayName\"`\n\n\tFreeformTags map[string]string `mandatory:\"false\" json:\"freeformTags\"`\n\n\tPrivateIpId *string `mandatory:\"false\" json:\"privateIpId\"`\n}\n\n\n\nfunc (m UpdatePublicIpDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package decorators\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t\"github.com/antham/chyle/chyle/convh\"\n)\n\ntype shellConfig map[string]struct {\n\tCOMMAND string\n\tORIGKEY string\n\tDESTKEY string\n}\n\n\n\ntype shell struct {\n\tCOMMAND string\n\tORIGKEY string\n\tDESTKEY string\n}\n\n\n\nfunc (s shell) execute(value string) (string, error) {\n\tvar result []byte\n\tvar err error\n\n\tcommand := fmt.Sprintf(`echo \"%s\"|%s`, strings.Replace(value, `\"`, `\\\"`, -1), s.COMMAND)\n\n\tif result, err = exec.Command(\"sh\", \"-c\", command).Output(); err != nil {\n\t\treturn \"\", fmt.Errorf(\"%s : command failed\", command)\n\t}\n\n\treturn string(result[:len(result)-1]), nil\n}\n\nfunc newShell(configs shellConfig) []Decorater {\n\tresults := []Decorater{}\n\n\tfor _, config := range configs {\n\t\tresults = append(results, shell(config))\n\t}\n\n\treturn results\n}\n\nfunc (s shell) Decorate(commitMap *map[string]interface{}) (*map[string]interface{}, error) ", "output": "{\n\tvar tmp interface{}\n\tvar value string\n\tvar ok bool\n\tvar err error\n\n\tif tmp, ok = (*commitMap)[s.ORIGKEY]; !ok {\n\t\treturn commitMap, nil\n\t}\n\n\tif value, err = convh.ConvertToString(tmp); err != nil {\n\t\treturn commitMap, nil\n\t}\n\n\tif (*commitMap)[s.DESTKEY], err = s.execute(value); err != nil {\n\t\treturn commitMap, err\n\t}\n\n\treturn commitMap, nil\n}"} {"input": "package common\n\nimport \"math/big\"\n\ntype _N_ [_S_]byte\n\nfunc BytesTo_N_(b []byte) _N_ {\n\tvar h _N_\n\th.SetBytes(b)\n\treturn h\n}\nfunc StringTo_N_(s string) _N_ { return BytesTo_N_([]byte(s)) }\nfunc BigTo_N_(b *big.Int) _N_ { return BytesTo_N_(b.Bytes()) }\nfunc HexTo_N_(s string) _N_ { return BytesTo_N_(FromHex(s)) }\n\n\n\n\n\nfunc (h _N_) Bytes() []byte { return h[:] }\nfunc (h _N_) Big() *big.Int { return Bytes2Big(h[:]) }\nfunc (h _N_) Hex() string { return \"0x\" + Bytes2Hex(h[:]) }\n\n\nfunc (h *_N_) SetBytes(b []byte) {\n\tif len(b) > len(h) {\n\t\tb = b[len(b)-_S_:]\n\t}\n\n\tfor i := len(b) - 1; i >= 0; i-- {\n\t\th[_S_-len(b)+i] = b[i]\n\t}\n}\n\n\nfunc (h *_N_) SetString(s string) { h.SetBytes([]byte(s)) }\n\n\nfunc (h *_N_) Set(other _N_) {\n\tfor i, v := range other {\n\t\th[i] = v\n\t}\n}\n\nfunc (h _N_) Str() string ", "output": "{ return string(h[:]) }"} {"input": "package permute\n\nimport \"testing\"\n\nfunc BenchmarkPermGenLex(b *testing.B) {\n\tp := New(20)\n\tfor i := 0; i < b.N; i++ {\n\t\tLexNext(p)\n\t}\n}\n\n\n\nfunc BenchmarkPermGenHeap(b *testing.B) {\n\th := NewHeap(20)\n\tvar sw [2]int\n\tfor i := 0; i < b.N; i++ {\n\t\th.Next(&sw)\n\t}\n}\nfunc BenchmarkPermGenEven(b *testing.B) {\n\th := NewPlainChangeFastGen(20)\n\tvar sw [2]int\n\tfor i := 0; i < b.N; i++ {\n\t\th.Next(&sw)\n\t}\n}\n\nfunc BenchmarkPermGenSJT(b *testing.B) ", "output": "{\n\th := NewPlainChangeGen(20)\n\tvar sw [2]int\n\tfor i := 0; i < b.N; i++ {\n\t\th.Next(&sw)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"github.com/jonasi/baller\"\n\t\"os\"\n)\n\n\n\nfunc init() {\n\tmethods[\"boxscore_advanced_v2\"] = cmd_boxscore_advanced_v2\n}\n\nfunc cmd_boxscore_advanced_v2(cl *baller.Client) (interface{}, error) ", "output": "{\n\tvar (\n\t\tfs = flag.NewFlagSet(\"boxscore_advanced_v2\", flag.ExitOnError)\n\t\tverbose = fs.Bool(\"verbose\", false, \"\")\n\t\toptions baller.BoxscoreAdvancedV2Options\n\t)\n\n\tfs.StringVar(&options.GameID, \"GameID\", \"\", \"\")\n\tfs.IntVar(&options.StartPeriod, \"StartPeriod\", 0, \"\")\n\tfs.IntVar(&options.EndPeriod, \"EndPeriod\", 0, \"\")\n\tfs.IntVar(&options.StartRange, \"StartRange\", 0, \"\")\n\tfs.IntVar(&options.EndRange, \"EndRange\", 0, \"\")\n\tfs.IntVar(&options.RangeType, \"RangeType\", 0, \"\")\n\n\tfs.Parse(os.Args[2:])\n\n\tif *verbose {\n\t\tcl.Logger = os.Stderr\n\t}\n\n\treturn cl.BoxscoreAdvancedV2(&options)\n}"} {"input": "package seqnum\n\n\ntype Value uint32\n\n\ntype Size uint32\n\n\nfunc (v Value) LessThan(w Value) bool {\n\treturn int32(v-w) < 0\n}\n\n\nfunc (v Value) LessThanEq(w Value) bool {\n\tif v == w {\n\t\treturn true\n\t}\n\treturn v.LessThan(w)\n}\n\n\nfunc (v Value) InRange(a, b Value) bool {\n\treturn v-a < b-a\n}\n\n\n\nfunc (v Value) InWindow(first Value, size Size) bool {\n\treturn v.InRange(first, first.Add(size))\n}\n\n\nfunc Overlap(a Value, b Size, x Value, y Size) bool {\n\treturn a.LessThan(x.Add(y)) && x.LessThan(a.Add(b))\n}\n\n\nfunc (v Value) Add(s Size) Value {\n\treturn v + Value(s)\n}\n\n\nfunc (v Value) Size(w Value) Size {\n\treturn Size(w - v)\n}\n\n\n\n\nfunc (v *Value) UpdateForward(s Size) ", "output": "{\n\t*v += Value(s)\n}"} {"input": "package auth\n\nimport (\n\tauthorizationapi \"github.com/projectatomic/atomic-enterprise/pkg/authorization/api\"\n\t\"github.com/projectatomic/atomic-enterprise/pkg/client\"\n)\n\n\ntype Review interface {\n\tUsers() []string\n\tGroups() []string\n}\n\ntype review struct {\n\tresponse *authorizationapi.ResourceAccessReviewResponse\n}\n\n\nfunc (r *review) Users() []string {\n\treturn r.response.Users.List()\n}\n\n\nfunc (r *review) Groups() []string {\n\treturn r.response.Groups.List()\n}\n\n\ntype Reviewer interface {\n\tReview(name string) (Review, error)\n}\n\n\ntype reviewer struct {\n\tresourceAccessReviewsNamespacer client.ResourceAccessReviewsNamespacer\n}\n\n\n\n\n\nfunc (r *reviewer) Review(name string) (Review, error) {\n\tresourceAccessReview := &authorizationapi.ResourceAccessReview{\n\t\tVerb: \"get\",\n\t\tResource: \"namespaces\",\n\t\tResourceName: name,\n\t}\n\n\tresponse, err := r.resourceAccessReviewsNamespacer.ResourceAccessReviews(name).Create(resourceAccessReview)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treview := &review{\n\t\tresponse: response,\n\t}\n\treturn review, nil\n}\n\nfunc NewReviewer(resourceAccessReviewsNamespacer client.ResourceAccessReviewsNamespacer) Reviewer ", "output": "{\n\treturn &reviewer{\n\t\tresourceAccessReviewsNamespacer: resourceAccessReviewsNamespacer,\n\t}\n}"} {"input": "package httpmux\n\nimport \"net/http\"\n\n\ntype ConfigOption interface {\n\tSet(c *Config)\n}\n\n\ntype ConfigOptionFunc func(c *Config)\n\n\nfunc (f ConfigOptionFunc) Set(c *Config) { f(c) }\n\n\nfunc WithPrefix(prefix string) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Prefix = prefix })\n}\n\n\nfunc WithMiddleware(mw ...Middleware) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Middleware = mw })\n}\n\n\nfunc WithMiddlewareFunc(mw ...MiddlewareFunc) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.UseFunc(mw...) })\n}\n\n\n\n\n\nfunc WithRedirectFixedPath(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectFixedPath = v })\n}\n\n\nfunc WithHandleMethodNotAllowed(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.HandleMethodNotAllowed = v })\n}\n\n\nfunc WithNotFound(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.NotFound = f })\n}\n\n\nfunc WithMethodNotAllowed(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.MethodNotAllowed = f })\n}\n\n\nfunc WithPanicHandler(f func(http.ResponseWriter, *http.Request, interface{})) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.PanicHandler = f })\n}\n\nfunc WithRedirectTrailingSlash(v bool) ConfigOption ", "output": "{\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectTrailingSlash = v })\n}"} {"input": "package shutdown\n\nimport (\n\t\"log\"\n\t\"os/exec\"\n\t\"strconv\"\n)\n\nfunc abort() {\n\trun(\"/a\")\n}\n\n\n\n\nfunc run(args ...string) {\n\tcmd := exec.Command(\"shutdown\", args...)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Println(\"error: \" + err.Error())\n\t}\n}\n\nfunc start(sec int) ", "output": "{\n\trun(\"/s\", \"/t\", strconv.Itoa(sec))\n}"} {"input": "package refmt\n\nimport (\n\t\"github.com/polydawn/refmt/obj\"\n\t\"github.com/polydawn/refmt/obj/atlas\"\n\t\"github.com/polydawn/refmt/shared\"\n)\n\nfunc Clone(src, dst interface{}) error {\n\treturn CloneAtlased(src, dst, atlas.MustBuild())\n}\nfunc MustClone(src, dst interface{}) {\n\tif err := Clone(src, dst); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc CloneAtlased(src, dst interface{}, atl atlas.Atlas) error {\n\treturn NewCloner(atl).Clone(src, dst)\n}\nfunc MustCloneAtlased(src, dst interface{}, atl atlas.Atlas) {\n\tif err := CloneAtlased(src, dst, atl); err != nil {\n\t\tpanic(err)\n\t}\n}\n\ntype Cloner interface {\n\tClone(src, dst interface{}) error\n}\n\n\n\ntype cloner struct {\n\tmarshaller *obj.Marshaller\n\tunmarshaller *obj.Unmarshaller\n\tpump shared.TokenPump\n}\n\nfunc (c cloner) Clone(src, dst interface{}) error {\n\tc.marshaller.Bind(src)\n\tc.unmarshaller.Bind(dst)\n\treturn c.pump.Run()\n}\n\nfunc NewCloner(atl atlas.Atlas) Cloner ", "output": "{\n\tx := &cloner{\n\t\tmarshaller: obj.NewMarshaller(atl),\n\t\tunmarshaller: obj.NewUnmarshaller(atl),\n\t}\n\tx.pump = shared.TokenPump{x.marshaller, x.unmarshaller}\n\treturn x\n}"} {"input": "package eventstreamapi\n\nimport (\n\t\"github.com/aws/aws-sdk-go/private/protocol\"\n\t\"github.com/aws/aws-sdk-go/private/protocol/eventstream\"\n)\n\n\n\ntype Marshaler interface {\n\tMarshalEvent(protocol.PayloadMarshaler) (eventstream.Message, error)\n}\n\n\n\ntype Encoder interface {\n\tEncode(eventstream.Message) error\n}\n\n\n\ntype EventWriter struct {\n\tencoder Encoder\n\tpayloadMarshaler protocol.PayloadMarshaler\n\teventTypeFor func(Marshaler) (string, error)\n}\n\n\n\nfunc NewEventWriter(encoder Encoder, pm protocol.PayloadMarshaler, eventTypeFor func(Marshaler) (string, error),\n) *EventWriter {\n\treturn &EventWriter{\n\t\tencoder: encoder,\n\t\tpayloadMarshaler: pm,\n\t\teventTypeFor: eventTypeFor,\n\t}\n}\n\n\n\n\n\nfunc (w *EventWriter) marshal(event Marshaler) (eventstream.Message, error) {\n\teventType, err := w.eventTypeFor(event)\n\tif err != nil {\n\t\treturn eventstream.Message{}, err\n\t}\n\n\tmsg, err := event.MarshalEvent(w.payloadMarshaler)\n\tif err != nil {\n\t\treturn eventstream.Message{}, err\n\t}\n\n\tmsg.Headers.Set(EventTypeHeader, eventstream.StringValue(eventType))\n\treturn msg, nil\n}\n\nfunc (w *EventWriter) WriteEvent(event Marshaler) error ", "output": "{\n\tmsg, err := w.marshal(event)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn w.encoder.Encode(msg)\n}"} {"input": "package spotify\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/laicosly/goth\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc provider() *Provider {\n\treturn New(os.Getenv(\"SPOTIFY_KEY\"), os.Getenv(\"SPOTIFY_SECRET\"), \"/foo\", \"user\")\n}\n\nfunc Test_New(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\tp := provider()\n\n\ta.Equal(p.ClientKey, os.Getenv(\"SPOTIFY_KEY\"))\n\ta.Equal(p.Secret, os.Getenv(\"SPOTIFY_SECRET\"))\n\ta.Equal(p.CallbackURL, \"/foo\")\n}\n\nfunc Test_ImplementsProvider(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\ta.Implements((*goth.Provider)(nil), provider())\n}\n\n\n\nfunc Test_SessionFromJSON(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\n\tp := provider()\n\tsession, err := p.UnmarshalSession(`{\"AuthURL\":\"http://accounts.spotify.com/authorize\",\"AccessToken\":\"1234567890\"}`)\n\ta.NoError(err)\n\n\ts := session.(*Session)\n\ta.Equal(s.AuthURL, \"http://accounts.spotify.com/authorize\")\n\ta.Equal(s.AccessToken, \"1234567890\")\n}\n\nfunc Test_BeginAuth(t *testing.T) ", "output": "{\n\tt.Parallel()\n\ta := assert.New(t)\n\n\tp := provider()\n\tsession, err := p.BeginAuth(\"test_state\")\n\ts := session.(*Session)\n\ta.NoError(err)\n\ta.Contains(s.AuthURL, \"accounts.spotify.com/authorize\")\n}"} {"input": "package gapbuf\n\nimport \"github.com/millere/jk/line\"\n\ntype GapBuf struct {\n\tbuffer []*line.Line \n\tgapStart int \n\tgapEnd int \n\treadPoint int\n}\n\nfunc New(size int) *GapBuf {\n\ta := GapBuf{\n\t\tbuffer: make([]*line.Line, size),\n\t\tgapStart: 0,\n\t\tgapEnd: size,\n\t}\n\treturn &a\n}\n\n\nfunc (a *GapBuf) Len() int {\n\treturn len(a.buffer) + a.gapStart - a.gapEnd\n}\n\n\n\n\n\nfunc (a *GapBuf) Insert(r rune, i int) {\n}\n\nfunc (a *GapBuf) moveGap(to int) {\n}\n\nfunc (a *GapBuf) At(i int) *line.Line ", "output": "{\n\tif i >= a.gapStart {\n\t\treturn a.buffer[i+a.gapEnd-a.gapStart]\n\t} else {\n\t\treturn a.buffer[i]\n\t}\n}"} {"input": "package stdlib\n\nimport (\n\t\"container/heap\"\n\t\"reflect\"\n)\n\nfunc init() {\n\tSymbols[\"container/heap\"] = map[string]reflect.Value{\n\t\t\"Fix\": reflect.ValueOf(heap.Fix),\n\t\t\"Init\": reflect.ValueOf(heap.Init),\n\t\t\"Pop\": reflect.ValueOf(heap.Pop),\n\t\t\"Push\": reflect.ValueOf(heap.Push),\n\t\t\"Remove\": reflect.ValueOf(heap.Remove),\n\n\t\t\"Interface\": reflect.ValueOf((*heap.Interface)(nil)),\n\n\t\t\"_Interface\": reflect.ValueOf((*_container_heap_Interface)(nil)),\n\t}\n}\n\n\ntype _container_heap_Interface struct {\n\tWLen func() int\n\tWLess func(i int, j int) bool\n\tWPop func() interface{}\n\tWPush func(x interface{})\n\tWSwap func(i int, j int)\n}\n\nfunc (W _container_heap_Interface) Len() int { return W.WLen() }\nfunc (W _container_heap_Interface) Less(i int, j int) bool { return W.WLess(i, j) }\nfunc (W _container_heap_Interface) Pop() interface{} { return W.WPop() }\nfunc (W _container_heap_Interface) Push(x interface{}) { W.WPush(x) }\n\n\nfunc (W _container_heap_Interface) Swap(i int, j int) ", "output": "{ W.WSwap(i, j) }"} {"input": "package packages\n\nimport (\n\t\"fmt\"\n\t\"github.com/alexandrecarlton/gogurt\"\n)\n\ntype PkgConfig struct{}\n\n\n\nfunc (pkgconfig PkgConfig) URL(version string) string {\n\treturn fmt.Sprintf(\"https://pkgconfig.freedesktop.org/releases/pkg-config-%s.tar.gz\", version)\n}\n\nfunc (pkgconfig PkgConfig) Build(config gogurt.Config) error {\n\tconfigure := gogurt.ConfigureCmd{\n\t\tPrefix: config.InstallDir(pkgconfig),\n\t\tArgs: []string{\n\t\t\t\"--disable-shared\",\n\t\t\t\"--enable-static\",\n\t\t\t\"--with-internal-glib\",\n\t\t},\n\t}.Cmd()\n\tif err := configure.Run(); err != nil {\n\t\treturn err\n\t}\n\tmake := gogurt.MakeCmd{\n\t\tJobs: config.NumCores,\n\t}.Cmd()\n\treturn make.Run()\n}\n\nfunc (pkgconfig PkgConfig) Install(config gogurt.Config) error {\n\tmakeInstall := gogurt.MakeCmd{\n\t\tArgs: []string{\n\t\t\t\"install\",\n\t\t},\n\t}.Cmd()\n\treturn makeInstall.Run()\n}\n\nfunc (pkgconfig PkgConfig) Dependencies() []gogurt.Package {\n\treturn []gogurt.Package{}\n}\n\nfunc (pkgconfig PkgConfig) Name() string ", "output": "{\n\treturn \"pkg-config\"\n}"} {"input": "package blanket_emulator\n\nimport (\n\t\"testing\"\n\t\"github.com/ranmrdrakono/indika/loader/elf\"\n)\n\n\n\nfunc TestRun(t *testing.T) ", "output": "{\n\telf.Run(\"../samples/binutils/bin_O1/gdb\")\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/gorilla/websocket\"\n)\n\ntype Client struct {\n\thub *Hub\n\tws *websocket.Conn\n\totherSide *Client\n\tchannelID uuid.UUID\n\tremoteType string\n\tparams map[string][]string\n\twmu sync.Mutex\n\trmu sync.Mutex\n}\n\nfunc (c *Client) WriteMessage(msgType int, message []byte) (err error) {\n\tc.wmu.Lock()\n\terr = c.ws.WriteMessage(msgType, message)\n\tc.wmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) NextWriter(msgType int) (w io.WriteCloser, err error) {\n\tc.wmu.Lock()\n\tw, err = c.ws.NextWriter(msgType)\n\tc.wmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) ReadMessage() (msgType int, message []byte, err error) {\n\tc.rmu.Lock()\n\tmsgType, message, err = c.ws.ReadMessage()\n\tc.rmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) NextReader() (msgType int, r io.Reader, err error) {\n\tc.rmu.Lock()\n\tmsgType, r, err = c.ws.NextReader()\n\tc.rmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) SetWriteDeadline(t time.Time) (err error) {\n\tc.wmu.Lock()\n\terr = c.ws.SetWriteDeadline(t)\n\tc.wmu.Unlock()\n\treturn\n}\n\n\n\nfunc (c *Client) SetReadDeadline(t time.Time) (err error) ", "output": "{\n\tc.rmu.Lock()\n\terr = c.ws.SetReadDeadline(t)\n\tc.rmu.Unlock()\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"time\"\n)\n\nvar ACTION_POTENTIAL_THRESHOLD int = 30\nvar DELAY_BETWEEN_FIRINGS time.Duration = 10\nvar SIGNAL_BUFFER_SIZE = 2048\n\ntype Neuron struct {\n\ttag string\n\tdendrite chan int \n\tsynapses []Synapse \n\tpotential int\n}\n\nfunc (n *Neuron) Fire() {\n\tlog.Println(n.tag, \"Fired\")\n\tn.potential = 0\n\tfor _, synapse := range n.synapses {\n\t\tselect {\n\t\tcase synapse.channel <- synapse.weight:\n\t\tdefault:\n\t\t\tlog.Println(\"Signal from\", n.tag, \"dropped\")\n\t\t}\n\t\ttime.Sleep(DELAY_BETWEEN_FIRINGS * time.Millisecond)\n\t}\n}\n\nfunc (n *Neuron) HasReachedThreshold() bool {\n\treturn n.potential > ACTION_POTENTIAL_THRESHOLD\n}\n\nfunc (n *Neuron) Listen() {\n\tfor actionPotential := range n.dendrite {\n\t\tn.potential += actionPotential\n\t\tif n.HasReachedThreshold() {\n\t\t\tn.Fire()\n\t\t}\n\t}\n}\n\nfunc (n *Neuron) AddSynapse(destination *Neuron, weight int) {\n\tn.synapses = append(n.synapses, Synapse{destination.dendrite, weight})\n}\n\n\n\nfunc NewNeuron(tag string) Neuron ", "output": "{\n\treturn Neuron{tag, make(chan int, SIGNAL_BUFFER_SIZE), []Synapse{}, 0}\n}"} {"input": "package graph\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gonum/graph\"\n\n\tkapi \"github.com/GoogleCloudPlatform/kubernetes/pkg/api\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime\"\n)\n\nvar (\n\tUnknownNodeKind = \"UnknownNode\"\n)\n\nvar (\n\tUnknownEdgeKind = \"UnknownEdge\"\n\tReferencedByEdgeKind = \"ReferencedBy\"\n\tContainsEdgeKind = \"Contains\"\n)\n\nfunc GetUniqueRuntimeObjectNodeName(nodeKind string, obj runtime.Object) UniqueName {\n\tmeta, err := kapi.ObjectMetaFor(obj)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn UniqueName(fmt.Sprintf(\"%s|%s/%s\", nodeKind, meta.Namespace, meta.Name))\n}\n\n\n\n\n\n\n\nfunc GetContainingNode(g Graph, containedNode graph.Node) graph.Node {\n\tfor _, node := range g.To(containedNode) {\n\t\tedge := g.Edge(node, containedNode)\n\n\t\tif g.EdgeKinds(edge).Has(ContainsEdgeKind) {\n\t\t\treturn node\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc GetTopLevelContainerNode(g Graph, containedNode graph.Node) graph.Node ", "output": "{\n\tvisited := map[int]bool{}\n\tprevContainingNode := containedNode\n\n\tfor {\n\t\tvisited[prevContainingNode.ID()] = true\n\t\tcurrContainingNode := GetContainingNode(g, prevContainingNode)\n\n\t\tif currContainingNode == nil {\n\t\t\treturn prevContainingNode\n\t\t}\n\t\tif _, alreadyVisited := visited[currContainingNode.ID()]; alreadyVisited {\n\t\t\tpanic(fmt.Sprintf(\"contains cycle in %v\", visited))\n\t\t}\n\n\t\tprevContainingNode = currContainingNode\n\t}\n\n\tpanic(fmt.Sprintf(\"math failed %v\", visited))\n\treturn nil\n}"} {"input": "package serialconsole\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/serialconsole/mgmt/2018-05-01/serialconsole\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype BaseClient = original.BaseClient\ntype ConsoleClient = original.ConsoleClient\ntype DeploymentValidateResult = original.DeploymentValidateResult\ntype GetDisabledResult = original.GetDisabledResult\ntype GetResult = original.GetResult\ntype ListClient = original.ListClient\ntype ListConsoleClient = original.ListConsoleClient\ntype Operations = original.Operations\ntype SetDisabledResult = original.SetDisabledResult\n\n\nfunc NewConsoleClient(subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClient(subscriptionID)\n}\nfunc NewConsoleClientWithBaseURI(baseURI string, subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewListClient(subscriptionID string) ListClient {\n\treturn original.NewListClient(subscriptionID)\n}\nfunc NewListClientWithBaseURI(baseURI string, subscriptionID string) ListClient {\n\treturn original.NewListClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewListConsoleClient(subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClient(subscriptionID)\n}\nfunc NewListConsoleClientWithBaseURI(baseURI string, subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\n\nfunc New(subscriptionID string) BaseClient ", "output": "{\n\treturn original.New(subscriptionID)\n}"} {"input": "package permissions\n\nimport (\n\t\"path/filepath\"\n\t\"util\"\n)\n\n\nvar globalPermissions *PermissionsLoader\n\n\n\n\n\nfunc SetPath(permissions string) error {\n\tif permissions != \"default\" {\n\t\tpl, err := NewPermissionsLoader(permissions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = pl\n\t\tif !pl.Get().Watch {\n\t\t\tglobalPermissions.Close() \n\t\t}\n\n\t} else {\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = nil\n\t}\n\treturn nil\n}\n\n\ntype PermissionsLoader struct {\n\tPermissions *Permissions \n\tWatcher *util.FileWatcher \n}\n\n\nfunc (pl *PermissionsLoader) Get() *Permissions {\n\tif pl == nil {\n\t\treturn &Default\n\t}\n\n\tpl.Watcher.RLock()\n\tdefer pl.Watcher.RUnlock()\n\treturn pl.Permissions\n}\n\n\n\nfunc NewPermissionsLoader(filename string) (*PermissionsLoader, error) {\n\tfilename, err := filepath.Abs(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp, err := Load(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpl := &PermissionsLoader{\n\t\tPermissions: p,\n\t}\n\tpl.Watcher, err = util.NewFileWatcher(filename, pl)\n\treturn pl, err\n}\n\n\nfunc (pl *PermissionsLoader) Reload() error {\n\tp, err := Load(pl.Watcher.FileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpl.Watcher.Lock()\n\tpl.Permissions = p\n\tpl.Watcher.Unlock()\n\n\tif !p.Watch {\n\t\tpl.Close() \n\t}\n\n\treturn nil\n}\n\n\nfunc (pl *PermissionsLoader) Close() {\n\tpl.Watcher.Close()\n}\n\nfunc Get() *Permissions ", "output": "{\n\tif globalPermissions == nil {\n\t\treturn &Default\n\t}\n\treturn globalPermissions.Get()\n}"} {"input": "package leetcode\n\n\n\n\n\n\nfunc pow(x float64, n int) float64 {\n\tif n == 1 {\n\t\treturn x\n\t}\n\tres := pow(x*x, n/2)\n\tif n%2 == 1 {\n\t\tres *= x\n\t}\n\treturn res\n}\n\nfunc myPow(x float64, n int) float64 ", "output": "{\n\tif n == 0 {\n\t\treturn 1\n\t}\n\tflag := false\n\tif n > 0 {\n\t\tflag = true\n\t} else {\n\t\tn = -n\n\t}\n\tres := pow(x, n)\n\tif !flag {\n\t\tres = 1 / res\n\t}\n\treturn res\n}"} {"input": "package websocket\n\ntype data struct {\n\tIndex int\n\tBody []byte\n\tError error\n}\n\n\n\nfunc parseHeader(header []byte) (index int, ok bool) {\n\tindex = int(header[0])<<24 | int(header[1])<<16 | int(header[2])<<8 | int(header[3])\n\tif ok = (header[0]&0x80 == 0); !ok {\n\t\tindex &= 0x7fffffff\n\t}\n\treturn\n}\n\nfunc makeHeader(index int) (header [4]byte) ", "output": "{\n\theader[0] = byte(index >> 24 & 0xff)\n\theader[1] = byte(index >> 16 & 0xff)\n\theader[2] = byte(index >> 8 & 0xff)\n\theader[3] = byte(index & 0xff)\n\treturn\n}"} {"input": "package terminal\n\nimport \"fmt\"\n\nvar ColorError int = 167\nvar ColorWarn int = 93\nvar ColorSuccess int = 82\nvar ColorNeutral int = 50\nvar BackgroundColorBlack = \"\\033[30;49m\"\nvar BackgroundColorWhite = \"\\033[30;47m\"\nvar ResetCode string = \"\\033[0m\"\n\n\n\n\n\n\n\nfunc Colorize(color int, msg string) string {\n\tif !stdoutIsTTY {\n\t\treturn msg\n\t}\n\treturn fmt.Sprintf(\"\\033[0;1m\\033[38;5;%dm%s%s\", color, msg, ResetCode)\n}\n\n\n\n\nfunc BoldText(msg string) string ", "output": "{\n\tif !stdoutIsTTY {\n\t\treturn msg\n\t}\n\treturn fmt.Sprintf(\"\\033[1m%s\\033[0m\", msg)\n}"} {"input": "package testing\n\nimport \"k8s.io/kubernetes/pkg/util/iptables\"\n\n\ntype fake struct{}\n\nfunc NewFake() *fake {\n\treturn &fake{}\n}\n\nfunc (*fake) EnsureChain(table iptables.Table, chain iptables.Chain) (bool, error) {\n\treturn true, nil\n}\n\n\n\nfunc (*fake) DeleteChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) EnsureRule(position iptables.RulePosition, table iptables.Table, chain iptables.Chain, args ...string) (bool, error) {\n\treturn true, nil\n}\n\nfunc (*fake) DeleteRule(table iptables.Table, chain iptables.Chain, args ...string) error {\n\treturn nil\n}\n\nfunc (*fake) IsIpv6() bool {\n\treturn false\n}\n\nfunc (*fake) Save(table iptables.Table) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\nfunc (*fake) SaveAll() ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\nfunc (*fake) Restore(table iptables.Table, data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\n\nfunc (*fake) RestoreAll(data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\nfunc (*fake) AddReloadFunc(reloadFunc func()) {}\n\nfunc (*fake) Destroy() {}\n\nvar _ = iptables.Interface(&fake{})\n\nfunc (*fake) FlushChain(table iptables.Table, chain iptables.Chain) error ", "output": "{\n\treturn nil\n}"} {"input": "package lua\n\ntype Metatable struct {\n IndexFunc Function\n NewindexFunc Function\n TostringFunc Function \n GCFunc Function\n}\n\nfunc (this *Metatable) Index() Function {\n return this.IndexFunc\n}\n\nfunc (this *Metatable) Newindex() Function {\n return this.NewindexFunc\n}\n\n\n\nfunc (this *Metatable) GC() Function {\n return this.GCFunc\n}\n\nfunc (this *Metatable) Tostring() Function ", "output": "{\n return this.TostringFunc\n}"} {"input": "package external\n\nimport (\n\t\"github.com/Aptomi/aptomi/pkg/external/secrets\"\n\t\"github.com/Aptomi/aptomi/pkg/external/users\"\n)\n\n\ntype Data struct {\n\tUserLoader users.UserLoader\n\tSecretLoader secrets.SecretLoader\n}\n\n\n\n\nfunc NewData(userLoader users.UserLoader, secretLoader secrets.SecretLoader) *Data ", "output": "{\n\treturn &Data{\n\t\tUserLoader: userLoader,\n\t\tSecretLoader: secretLoader,\n\t}\n}"} {"input": "package category\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/vapi/tags\"\n)\n\ntype ls struct {\n\t*flags.ClientFlag\n\t*flags.OutputFlag\n}\n\nfunc init() {\n\tcli.Register(\"tags.category.ls\", &ls{})\n}\n\nfunc (cmd *ls) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.ClientFlag, ctx = flags.NewClientFlag(ctx)\n\tcmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)\n\tcmd.ClientFlag.Register(ctx, f)\n\tcmd.OutputFlag.Register(ctx, f)\n}\n\nfunc (cmd *ls) Process(ctx context.Context) error {\n\tif err := cmd.ClientFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn cmd.OutputFlag.Process(ctx)\n}\n\n\n\ntype lsResult []tags.Category\n\nfunc (r lsResult) Write(w io.Writer) error {\n\tfor _, c := range r {\n\t\tfmt.Fprintln(w, c.Name)\n\t}\n\treturn nil\n}\n\nfunc (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {\n\tc, err := cmd.RestClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tl, err := tags.NewManager(c).GetCategories(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn cmd.WriteResult(lsResult(l))\n}\n\nfunc (cmd *ls) Description() string ", "output": "{\n\treturn `List all categories.\n\nExamples:\n govc tags.category.ls\n govc tags.category.ls -json | jq .`\n}"} {"input": "package zk2topo\n\nimport (\n\t\"path\"\n\t\"sort\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\nfunc (zs *Server) ListDir(ctx context.Context, cell, dirPath string) ([]string, error) ", "output": "{\n\tconn, root, err := zs.connForCell(ctx, cell)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tzkPath := path.Join(root, dirPath)\n\n\tchildren, _, err := conn.Children(ctx, zkPath)\n\tif err != nil {\n\t\treturn nil, convertError(err)\n\t}\n\tsort.Strings(children)\n\treturn children, nil\n}"} {"input": "package export\n\nimport (\n\t\"bytes\"\n\t\"database/sql\"\n\t\"strings\"\n\n\t\"github.com/pingcap/errors\"\n\n\ttcontext \"github.com/pingcap/tidb/dumpling/context\"\n)\n\n\n\ntype TableDataIR interface {\n\tStart(*tcontext.Context, *sql.Conn) error\n\tRows() SQLRowIter\n\tClose() error\n\tRawRows() *sql.Rows\n}\n\n\ntype TableMeta interface {\n\tDatabaseName() string\n\tTableName() string\n\tColumnCount() uint\n\tColumnTypes() []string\n\tColumnNames() []string\n\tSelectedField() string\n\tSelectedLen() int\n\tSpecialComments() StringIter\n\tShowCreateTable() string\n\tShowCreateView() string\n\tAvgRowLength() uint64\n\tHasImplicitRowID() bool\n}\n\n\ntype SQLRowIter interface {\n\tDecode(RowReceiver) error\n\tNext()\n\tError() error\n\tHasNext() bool\n\tClose() error\n}\n\n\ntype RowReceiverStringer interface {\n\tRowReceiver\n\tStringer\n}\n\n\ntype Stringer interface {\n\tWriteToBuffer(*bytes.Buffer, bool)\n\tWriteToBufferInCsv(*bytes.Buffer, bool, *csvOption)\n}\n\n\ntype RowReceiver interface {\n\tBindAddress([]interface{})\n}\n\nfunc decodeFromRows(rows *sql.Rows, args []interface{}, row RowReceiver) error {\n\trow.BindAddress(args)\n\tif err := rows.Scan(args...); err != nil {\n\t\trows.Close()\n\t\treturn errors.Trace(err)\n\t}\n\treturn nil\n}\n\n\ntype StringIter interface {\n\tNext() string\n\tHasNext() bool\n}\n\n\ntype MetaIR interface {\n\tSpecialComments() StringIter\n\tTargetName() string\n\tMetaSQL() string\n}\n\n\n\nfunc setTableMetaFromRows(rows *sql.Rows) (TableMeta, error) ", "output": "{\n\ttps, err := rows.ColumnTypes()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tnms, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tfor i := range nms {\n\t\tnms[i] = wrapBackTicks(nms[i])\n\t}\n\treturn &tableMeta{\n\t\tcolTypes: tps,\n\t\tselectedField: strings.Join(nms, \",\"),\n\t\tselectedLen: len(nms),\n\t\tspecCmts: []string{\"/*!40101 SET NAMES binary*/;\"},\n\t}, nil\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\n\tv3 \"github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3\"\n\t\"github.com/rancher/rancher/pkg/ref\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc GetRuleID(groupID string, ruleName string) string {\n\treturn fmt.Sprintf(\"%s_%s\", groupID, ruleName)\n}\n\nfunc GetGroupID(namespace, name string) string {\n\treturn fmt.Sprintf(\"%s:%s\", namespace, name)\n}\n\nfunc GetAlertManagerSecretName(appName string) string {\n\treturn fmt.Sprintf(\"alertmanager-%s\", appName)\n}\n\nfunc GetAlertManagerDaemonsetName(appName string) string {\n\treturn fmt.Sprintf(\"alertmanager-%s\", appName)\n}\n\nfunc formatProjectDisplayName(projectDisplayName, projectID string) string {\n\treturn fmt.Sprintf(\"%s (ID: %s)\", projectDisplayName, projectID)\n}\n\n\n\nfunc GetClusterDisplayName(clusterName string, clusterLister v3.ClusterLister) string {\n\tcluster, err := clusterLister.Get(\"\", clusterName)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to get cluster for %s: %v\", clusterName, err)\n\t\treturn clusterName\n\t}\n\n\treturn formatClusterDisplayName(cluster.Spec.DisplayName, clusterName)\n}\n\nfunc GetProjectDisplayName(projectID string, projectLister v3.ProjectLister) string {\n\tclusterName, projectName := ref.Parse(projectID)\n\tproject, err := projectLister.Get(clusterName, projectName)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to get project %s: %v\", projectID, err)\n\t\treturn projectID\n\t}\n\n\treturn formatProjectDisplayName(project.Spec.DisplayName, projectID)\n}\n\nfunc formatClusterDisplayName(clusterDisplayName, clusterID string) string ", "output": "{\n\treturn fmt.Sprintf(\"%s (ID: %s)\", clusterDisplayName, clusterID)\n}"} {"input": "package iso20022\n\n\ntype RemittanceInformation8 struct {\n\n\tRemittanceIdentification *Max35Text `xml:\"RmtId,omitempty\"`\n\n\tUnstructured []*Max140Text `xml:\"Ustrd,omitempty\"`\n\n\tStructured []*StructuredRemittanceInformation10 `xml:\"Strd,omitempty\"`\n\n\tOriginalPaymentInformation *OriginalPaymentInformation6 `xml:\"OrgnlPmtInf\"`\n}\n\nfunc (r *RemittanceInformation8) SetRemittanceIdentification(value string) {\n\tr.RemittanceIdentification = (*Max35Text)(&value)\n}\n\nfunc (r *RemittanceInformation8) AddUnstructured(value string) {\n\tr.Unstructured = append(r.Unstructured, (*Max140Text)(&value))\n}\n\nfunc (r *RemittanceInformation8) AddStructured() *StructuredRemittanceInformation10 {\n\tnewValue := new(StructuredRemittanceInformation10)\n\tr.Structured = append(r.Structured, newValue)\n\treturn newValue\n}\n\n\n\nfunc (r *RemittanceInformation8) AddOriginalPaymentInformation() *OriginalPaymentInformation6 ", "output": "{\n\tr.OriginalPaymentInformation = new(OriginalPaymentInformation6)\n\treturn r.OriginalPaymentInformation\n}"} {"input": "package client_test\n\nimport (\n\t\"github.com/jdextraze/go-gesclient/client\"\n\t\"testing\"\n)\n\nfunc TestWrongExpectedVersion_Error(t *testing.T) {\n\tif client.WrongExpectedVersion.Error() != \"Wrong expected version\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestStreamDeleted_Error(t *testing.T) {\n\tif client.StreamDeleted.Error() != \"Stream deleted\" {\n\t\tt.FailNow()\n\t}\n}\n\n\n\nfunc TestAccessDenied_Error(t *testing.T) {\n\tif client.AccessDenied.Error() != \"Access denied\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestAuthenticationError_Error(t *testing.T) {\n\tif client.AuthenticationError.Error() != \"Authentication error\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestBadRequest_Error(t *testing.T) {\n\tif client.BadRequest.Error() != \"Bad request\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestServerError_Error(t *testing.T) {\n\terr := client.NewServerError(\"\")\n\tif err.Error() != \"Unexpected error on server: \" {\n\t\tt.FailNow()\n\t}\n\n\terr = client.NewServerError(\"test\")\n\tif err.Error() != \"Unexpected error on server: test\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestNotModified_Error(t *testing.T) {\n\terr := client.NewNotModified(\"test\")\n\tif err.Error() != \"Stream not modified: test\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestInvalidTransaction_Error(t *testing.T) ", "output": "{\n\tif client.InvalidTransaction.Error() != \"Invalid transaction\" {\n\t\tt.FailNow()\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n)\n\ntype Player struct {\n\tlog *os.File\n\tlogTime time.Time\n\tdecoder *json.Decoder\n\tdir string\n\toffset time.Duration\n}\n\n\n\nfunc (p *Player) Reset() error {\n\tn := p.Then()\n\tp.logTime = logTime(n)\n\tfilename := logFileName(n)\n\tif p.log != nil {\n\t\tp.log.Close()\n\t}\n\tlog.Printf(\"Playing file %s\\n\", filename)\n\tvar err error\n\tp.log, err = os.Open(filepath.Join(p.dir, filename))\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.decoder = json.NewDecoder(p.log)\n\treturn nil\n}\n\n\nfunc (p *Player) Playback(t time.Time) error {\n\tlog.Printf(\"Playing back starting at %s\\n\", t)\n\tp.offset = time.Now().Sub(t)\n\terr := p.Reset()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor {\n\t\tvar m Msg\n\t\terr := p.decoder.Decode(&m)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\td := m.Timestamp.Time.Sub(p.Then())\n\t\tdebugf(\"difference is %f seconds\", d.Seconds())\n\t\tif d > 0 {\n\t\t\ttime.Sleep(d)\n\t\t}\n\t\tm.Print()\n\t}\n}\n\nfunc (p *Player) Then() time.Time {\n\treturn time.Now().Add(-p.offset)\n}\n\nfunc (p *Player) Close() error {\n\tp.decoder = nil\n\treturn p.log.Close()\n}\n\nfunc NewPlayer(dir string) *Player ", "output": "{\n\tvar p Player\n\tp.dir = dir\n\treturn &p\n}"} {"input": "package bigcache\n\n\n\nfunc convertMBToBytes(value int) int {\n\treturn value * 1024 * 1024\n}\n\nfunc isPowerOfTwo(number int) bool {\n\treturn (number & (number - 1)) == 0\n}\n\nfunc max(a, b int) int ", "output": "{\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}"} {"input": "package nodes\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\ntype Name struct {\n\tTaxID string `json:\"TaxID\"`\n\tNames []NameItem `json:\"Names\"`\n}\n\n\ntype NameItem struct {\n\tName string `json:\"Name\"`\n\tUniqueName string `json:\"UniqueName\"`\n\tNameClass string `json:\"NameClass\"`\n}\n\n\nfunc (name Name) ToJSON() (string, error) {\n\ts, err := json.Marshal(name)\n\treturn string(s), err\n}\n\n\n\n\n\nfunc NameFromArgs(items []string) Name {\n\tif len(items) != 4 {\n\t\treturn Name{}\n\t}\n\n\treturn Name{\n\t\tTaxID: items[0],\n\t\tNames: []NameItem{\n\t\t\tNameItem{\n\t\t\t\tName: items[1],\n\t\t\t\tUniqueName: items[2],\n\t\t\t\tNameClass: items[3],\n\t\t\t}},\n\t}\n}\n\n\nfunc MergeNames(names ...Name) Name {\n\tif len(names) < 2 {\n\t\treturn names[0]\n\t}\n\tname := names[0]\n\tfor _, another := range names[1:] {\n\t\tif another.TaxID != name.TaxID {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, anotherNameItem := range another.Names {\n\t\t\tname.Names = append(name.Names, anotherNameItem)\n\t\t}\n\t}\n\treturn name\n}\n\n\nvar Names map[string]Name\n\nvar mutex1 = &sync.Mutex{}\n\n\nfunc SetNames(names map[string]Name) {\n\tmutex1.Lock()\n\tNames = names\n\tmutex1.Unlock()\n}\n\nfunc NameFromJSON(s string) (Name, error) ", "output": "{\n\tvar name Name\n\terr := json.Unmarshal([]byte(s), &name)\n\treturn name, err\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\nfunc WordCount(s string) map[string]int {\n\tresult := make(map[string]int)\n\tfor _, v := range strings.Fields(s) {\n\t\t_, ok := result[v]\n\t\tif ok == false {\n\t\t\tresult[v] = 0\n\t\t}\n\t\tresult[v]++\n\t}\n\treturn result\n}\n\nfunc map_operations() ", "output": "{\n\tm := make(map[string]int)\n\tm[\"Answer\"] = 42\n\tfmt.Println(\"The value:\", m[\"Answer\"])\n\tm[\"Answer\"] = 48\n\tfmt.Println(\"The value:\", m[\"Answer\"])\n\tdelete(m, \"Answer\")\n\tfmt.Println(\"The value:\", m[\"Answer\"])\n\tv, ok := m[\"Answer\"]\n\tfmt.Println(\"The value:\", v, \"Present?\", ok)\n}"} {"input": "package methods\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/barnettzqg/journey/configuration\"\n\t\"github.com/barnettzqg/journey/database\"\n\t\"github.com/barnettzqg/journey/slug\"\n\t\"github.com/barnettzqg/journey/structure\"\n)\n\n\nvar Blog *structure.Blog\n\nvar assetPath = []byte(\"/assets/\")\n\n\n\nfunc UpdateActiveTheme(activeTheme string, userId int64) error {\n\terr := database.UpdateActiveTheme(activeTheme, time.Now(), userId)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = GenerateBlog()\n\tif err != nil {\n\t\tlog.Panic(\"Error: couldn't generate blog data:\", err)\n\t}\n\treturn nil\n}\n\nfunc GenerateBlog() error {\n\tif Blog != nil {\n\t\tBlog.Lock()\n\t\tdefer Blog.Unlock()\n\t}\n\tblog, err := database.RetrieveBlog()\n\tif err != nil {\n\t\treturn err\n\t}\n\tblog.Url = []byte(configuration.Config.Url)\n\tblog.AssetPath = assetPath\n\tfor index, _ := range blog.NavigationItems {\n\t\tblog.NavigationItems[index].Slug = slug.Generate(blog.NavigationItems[index].Label, \"navigation\")\n\t}\n\tBlog = blog\n\treturn nil\n}\n\nfunc UpdateBlog(b *structure.Blog, userId int64) error ", "output": "{\n\tnavigation, err := json.Marshal(b.NavigationItems)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = database.UpdateSettings(b.Title, b.Description, b.Logo, b.Cover, b.PostsPerPage, b.ActiveTheme, navigation, time.Now(), userId)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = GenerateBlog()\n\tif err != nil {\n\t\tlog.Panic(\"Error: couldn't generate blog data:\", err)\n\t}\n\treturn nil\n}"} {"input": "package contentutil\n\nimport (\n\t\"context\"\n\n\t\"github.com/containerd/containerd/content\"\n\t\"github.com/containerd/containerd/errdefs\"\n\t\"github.com/containerd/containerd/remotes\"\n\t\"github.com/pkg/errors\"\n)\n\n\n\ntype pushingIngester struct {\n\tp remotes.Pusher\n}\n\n\nfunc (i *pushingIngester) Writer(ctx context.Context, opts ...content.WriterOpt) (content.Writer, error) {\n\tvar wOpts content.WriterOpts\n\tfor _, opt := range opts {\n\t\tif err := opt(&wOpts); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif wOpts.Ref == \"\" {\n\t\treturn nil, errors.Wrap(errdefs.ErrInvalidArgument, \"ref must not be empty\")\n\t}\n\tcontentWriter, err := i.p.Push(ctx, wOpts.Desc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &writer{\n\t\tWriter: contentWriter,\n\t\tcontentWriterRef: wOpts.Ref,\n\t}, nil\n}\n\ntype writer struct {\n\tcontent.Writer \n\tcontentWriterRef string \n}\n\nfunc (w *writer) Status() (content.Status, error) {\n\tst, err := w.Writer.Status()\n\tif err != nil {\n\t\treturn st, err\n\t}\n\tif w.contentWriterRef != \"\" {\n\t\tst.Ref = w.contentWriterRef\n\t}\n\treturn st, nil\n}\n\nfunc FromPusher(p remotes.Pusher) content.Ingester ", "output": "{\n\treturn &pushingIngester{\n\t\tp: p,\n\t}\n}"} {"input": "package async\n\nimport (\n\t\"reflect\"\n)\n\n\n\n\n\nfunc FilterParallel(data interface{}, routine Routine, callbacks ...Done) {\n\tvar routines []Routine\n\n\td := reflect.ValueOf(data)\n\n\tfor i := 0; i < d.Len(); i++ {\n\t\tv := d.Index(i).Interface()\n\t\troutines = append(routines, func(id int) Routine {\n\t\t\treturn func(done Done, args ...interface{}) {\n\t\t\t\tdone = func(original Done) Done {\n\t\t\t\t\treturn func(err error, args ...interface{}) {\n\t\t\t\t\t\tif args[0] != false {\n\t\t\t\t\t\t\toriginal(err, v)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\toriginal(err)\n\t\t\t\t\t}\n\t\t\t\t}(done)\n\n\t\t\t\troutine(done, v, id)\n\t\t\t}\n\t\t}(i))\n\t}\n\n\tParallel(routines, callbacks...)\n}\n\nfunc Filter(data interface{}, routine Routine, callbacks ...Done) ", "output": "{\n\tvar (\n\t\troutines []Routine\n\t\tresults []interface{}\n\t)\n\n\td := reflect.ValueOf(data)\n\n\tfor i := 0; i < d.Len(); i++ {\n\t\tv := d.Index(i).Interface()\n\t\troutines = append(routines, func(id int) Routine {\n\t\t\treturn func(done Done, args ...interface{}) {\n\t\t\t\tdone = func(original Done) Done {\n\t\t\t\t\treturn func(err error, args ...interface{}) {\n\t\t\t\t\t\tif args[0] != false {\n\t\t\t\t\t\t\tresults = append(results, v)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif id == (d.Len() - 1) {\n\t\t\t\t\t\t\toriginal(err, results...)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\toriginal(err, args...)\n\t\t\t\t\t}\n\t\t\t\t}(done)\n\n\t\t\t\troutine(done, v, id)\n\t\t\t}\n\t\t}(i))\n\t}\n\n\tWaterfall(routines, callbacks...)\n}"} {"input": "package command\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/hashicorp/serf/serf\"\n\t\"github.com/mitchellh/cli\"\n)\n\n\ntype VersionCommand struct {\n\tRevision string\n\tVersion string\n\tVersionPrerelease string\n\tUi cli.Ui\n}\n\n\n\nfunc (c *VersionCommand) Run(_ []string) int {\n\tvar versionString bytes.Buffer\n\tfmt.Fprintf(&versionString, \"Serf v%s\", c.Version)\n\tif c.VersionPrerelease != \"\" {\n\t\tfmt.Fprintf(&versionString, \".%s\", c.VersionPrerelease)\n\n\t\tif c.Revision != \"\" {\n\t\t\tfmt.Fprintf(&versionString, \" (%s)\", c.Revision)\n\t\t}\n\t}\n\n\tc.Ui.Output(versionString.String())\n\tc.Ui.Output(fmt.Sprintf(\"Agent Protocol: %d (Understands back to: %d)\",\n\t\tserf.ProtocolVersionMax, serf.ProtocolVersionMin))\n\treturn 0\n}\n\nfunc (c *VersionCommand) Synopsis() string {\n\treturn \"Prints the Serf version\"\n}\n\nfunc (c *VersionCommand) Help() string ", "output": "{\n\treturn \"\"\n}"} {"input": "package bunyan\n\nimport \"os\"\n\n\n\ntype Sink interface {\n\tWrite(record Record) error\n}\n\ntype funcSink struct {\n\twrite func(record Record) error\n}\n\nfunc (sink *funcSink) Write(record Record) error {\n\treturn sink.write(record)\n}\n\n\n\n\n\n\n\nfunc NilSink() Sink {\n\treturn SinkFunc(func(record Record) error {\n\t\treturn nil \n\t})\n}\n\nfunc InfoSink(target Sink, info Info) Sink {\n\treturn SinkFunc(func(record Record) error {\n\t\trecord.SetIfNot(info.Key(), info.Value())\n\t\treturn target.Write(record)\n\t})\n}\n\n\nfunc StdoutSink() Sink {\n\treturn NewJsonSink(os.Stdout)\n}\n\n\nfunc FileSink(path string) Sink {\n\tconst flags = os.O_CREATE | os.O_APPEND | os.O_WRONLY\n\tfile, e := os.OpenFile(path, flags, 0666)\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\n\treturn NewJsonSink(file)\n}\n\nfunc SinkFunc(write func(record Record) error) Sink ", "output": "{\n\treturn &funcSink{write}\n}"} {"input": "package models\n\nimport \"time\"\n\n\ntype KeyType struct {\n\tID int\n\tKey string\n\tCreated time.Time\n\tExpires bool\n}\n\n\ntype Keys []KeyType\n\nfunc (f Keys) Len() int {\n\treturn len(f)\n}\n\n\n\nfunc (f Keys) Swap(i, j int) {\n\tf[i], f[j] = f[j], f[i]\n}\n\nfunc (f Keys) Less(i, j int) bool ", "output": "{\n\treturn f[i].ID < f[j].ID\n}"} {"input": "package container\n\nimport (\n\t\"github.com/e154/smart-home/models\"\n\t\"github.com/e154/smart-home/system/backup\"\n)\n\n\n\n\nfunc NewBackupConfig(cfg *models.AppConfig) *backup.BackupConfig ", "output": "{\n\treturn &backup.BackupConfig{\n\t\tPath: cfg.SnapshotDir,\n\t\tPgUser: cfg.PgUser,\n\t\tPgPass: cfg.PgPass,\n\t\tPgHost: cfg.PgHost,\n\t\tPgName: cfg.PgName,\n\t\tPgPort: cfg.PgPort,\n\t}\n}"} {"input": "package master\n\nimport ()\n\n\n\ntype frame struct {\n\tjob *job\n\tslaveName string\n\tframe int\n\tdata []byte\n\tprogress byte\n\tcompleted bool\n}\n\n\n\nfunc NewFrame(job *job, fr int) *frame {\n\treturn &frame{\n\t\tjob: job,\n\t\tslaveName: \"\",\n\t\tframe: fr,\n\t\tdata: nil,\n\t\tprogress: 0,\n\t\tcompleted: false,\n\t}\n}\n\n\n\nfunc (f *frame) Job() *job {\n\treturn f.job\n}\n\nfunc (f *frame) SlaveName() string {\n\treturn f.slaveName\n}\n\nfunc (f *frame) Frame() int {\n\treturn f.frame\n}\n\nfunc (f *frame) AlignedFrame() int {\n\treturn f.frame + f.Job().Start()\n}\n\nfunc (f *frame) Data() []byte {\n\treturn f.data\n}\n\nfunc (f *frame) Progress() byte {\n\treturn f.progress\n}\n\nfunc (f *frame) Completed() bool {\n\treturn f.completed\n}\n\nfunc (f *frame) File() []byte {\n\treturn f.Job().File()\n}\n\n\n\nfunc (f *frame) SetSlaveName(slaveName string) {\n\tf.slaveName = slaveName\n}\n\nfunc (f *frame) SetData(data []byte) {\n\tf.data = data\n}\n\nfunc (f *frame) SetProgress(progress byte) {\n\tf.progress = progress\n}\n\n\n\n\n\nfunc (f *frame) Reset() {\n\tf.SetSlaveName(\"\")\n\tf.SetData(nil)\n\tf.SetProgress(0)\n\tf.SetCompleted(false)\n}\n\nfunc (f *frame) SetCompleted(completed bool) ", "output": "{\n\tf.completed = completed\n\tif completed {\n\t\tf.SetProgress(100)\n\t}\n}"} {"input": "package dfa\n\nimport (\n\t\"fmt\"\n\t\"unicode\"\n)\n\n\n\nfunc eachRangeInCharClass(name string, visit func(lo, hi rune)) error {\n\ttable := unicode.Categories[name]\n\tif table == nil {\n\t\ttable = unicode.Scripts[name]\n\t\tif table == nil {\n\t\t\treturn fmt.Errorf(\"character class %s not exists\", name)\n\t\t}\n\t}\n\n\tfor _, xr := range table.R16 {\n\t\teachRangeWithStride(rune(xr.Lo), rune(xr.Hi), rune(xr.Stride), visit)\n\t}\n\tfor _, xr := range table.R32 {\n\t\teachRangeWithStride(rune(xr.Lo), rune(xr.Hi), rune(xr.Stride), visit)\n\t}\n\treturn nil\n}\nfunc eachRangeWithStride(lo, hi, stride rune, visit func(lo, hi rune)) {\n\tif stride == 1 {\n\t\tvisit(lo, hi)\n\t} else {\n\t\tfor c := lo; c <= hi; c += stride {\n\t\t\tvisit(c, c)\n\t\t}\n\t}\n}\n\nfunc charClass(name string) (m *M, err error) ", "output": "{\n\tms := []*M{}\n\terr = eachRangeInCharClass(name, func(lo, hi rune) {\n\t\tms = append(ms, Between(lo, hi))\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm, err = orMany(ms)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn m.minimize()\n}"} {"input": "package mcore\n\nimport (\n\t\"log\"\n)\n\ntype StringKeyValueMap map[string]string\n\nfunc NewStringKeyValueMap() StringKeyValueMap {\n\treturn make(map[string]string)\n}\n\n\nfunc (c StringKeyValueMap) Put(key, value string) {\n\tc[key] = value\n}\n\nfunc (c StringKeyValueMap) IsContain(key string) bool {\n\t_, ok := c[key]\n\treturn ok\n}\n\nfunc (c StringKeyValueMap) GetString(key string) string {\n\treturn c.GetStringWithDefault(key, \"\")\n}\n\nfunc (c StringKeyValueMap) GetStringWithDefault(key, defaultValue string) string {\n\tif c.IsContain(key) {\n\t\treturn c[key]\n\t}\n\tlog.Printf(\"Error: not contains key: %s\", key)\n\treturn defaultValue\n}\n\nfunc (c StringKeyValueMap) GetInt(key string) int {\n\treturn String(c.GetString(key)).ToIntNoError()\n}\n\n\n\nfunc (c StringKeyValueMap) GetBool(key string) bool ", "output": "{\n\treturn String(c.GetString(key)).ToBool()\n}"} {"input": "package format\n\nimport (\n\t\"reflect\"\n\t\"strconv\"\n)\n\n\nfunc Any(value interface{}) string {\n\treturn formatAtom(reflect.ValueOf(value))\n}\n\n\n\n\nfunc formatAtom(v reflect.Value) string ", "output": "{\n\tswitch v.Kind() {\n\tcase reflect.Invalid:\n\t\treturn \"invalid\"\n\tcase reflect.Int, reflect.Int8, reflect.Int16,\n\t\treflect.Int32, reflect.Int64:\n\t\treturn strconv.FormatInt(v.Int(), 10)\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16,\n\t\treflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\treturn strconv.FormatUint(v.Uint(), 10)\n\tcase reflect.Bool:\n\t\treturn strconv.FormatBool(v.Bool())\n\tcase reflect.String:\n\t\treturn strconv.Quote(v.String())\n\tcase reflect.Chan, reflect.Func, reflect.Ptr, reflect.Slice, reflect.Map:\n\t\treturn v.Type().String() + \" 0x\" +\n\t\t\tstrconv.FormatUint(uint64(v.Pointer()), 16)\n\tdefault: \n\t\treturn v.Type().String() + \" value\"\n\t}\n}"} {"input": "package bigquery\n\nimport (\n\t\"fmt\"\n\t\"github.com/viant/endly\"\n\t\"github.com/viant/endly/system/cloud/gcp\"\n\t\"google.golang.org/api/bigquery/v2\"\n)\n\nvar clientKey = (*CtxClient)(nil)\n\n\ntype CtxClient struct {\n\t*gcp.AbstractClient\n\tservice *bigquery.Service\n}\n\nfunc (s *CtxClient) SetService(service interface{}) error {\n\tvar ok bool\n\ts.service, ok = service.(*bigquery.Service)\n\tif !ok {\n\t\treturn fmt.Errorf(\"unable to set service: %T\", service)\n\t}\n\treturn nil\n}\n\nfunc (s *CtxClient) Service() interface{} {\n\treturn s.service\n}\n\nfunc InitRequest(context *endly.Context, rawRequest map[string]interface{}) error {\n\tconfig, err := gcp.InitCredentials(context, rawRequest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient, err := getClient(context)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgcp.UpdateActionRequest(rawRequest, config, client)\n\treturn nil\n}\n\nfunc getClient(context *endly.Context) (gcp.CtxClient, error) {\n\treturn GetClient(context)\n}\n\n\n\nfunc GetClient(context *endly.Context) (*CtxClient, error) ", "output": "{\n\tclient := &CtxClient{\n\t\tAbstractClient: &gcp.AbstractClient{},\n\t}\n\terr := gcp.GetClient(context, bigquery.New, clientKey, &client, bigquery.CloudPlatformScope, bigquery.BigqueryScope, bigquery.BigqueryInsertdataScope)\n\treturn client, err\n}"} {"input": "package iotcentral\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" iotcentral/2021-06-01\"\n}"} {"input": "package resources\n\nimport (\n\t\"sort\"\n\n\t\"encoding/json\"\n\n\t\"github.com/mitchellh/mapstructure\"\n)\n\n\ntype AWSServerlessApplication_Location struct {\n\tString *string\n\n\tApplicationLocation *AWSServerlessApplication_ApplicationLocation\n}\n\nfunc (r AWSServerlessApplication_Location) value() interface{} {\n\n\tif r.String != nil {\n\t\treturn r.String\n\t}\n\n\tret := []interface{}{}\n\n\tif r.ApplicationLocation != nil {\n\t\tret = append(ret, *r.ApplicationLocation)\n\t}\n\n\tsort.Sort(byJSONLength(ret))\n\tif len(ret) > 0 {\n\t\treturn ret[0]\n\t}\n\n\treturn nil\n\n}\n\n\n\n\nfunc (r *AWSServerlessApplication_Location) UnmarshalJSON(b []byte) error {\n\n\tvar typecheck interface{}\n\tif err := json.Unmarshal(b, &typecheck); err != nil {\n\t\treturn err\n\t}\n\n\tswitch val := typecheck.(type) {\n\n\tcase string:\n\t\tr.String = &val\n\n\tcase map[string]interface{}:\n\n\t\tmapstructure.Decode(val, &r.ApplicationLocation)\n\n\tcase []interface{}:\n\n\t}\n\n\treturn nil\n}\n\nfunc (r AWSServerlessApplication_Location) MarshalJSON() ([]byte, error) ", "output": "{\n\treturn json.Marshal(r.value())\n}"} {"input": "package repository\n\nimport (\n\t\"strings\"\n\n\t\"code.gitea.io/gitea/models\"\n\t\"code.gitea.io/gitea/modules/cache\"\n\t\"code.gitea.io/gitea/modules/git\"\n\t\"code.gitea.io/gitea/modules/setting\"\n)\n\n\n\n\nfunc CacheRef(repo *models.Repository, gitRepo *git.Repository, fullRefName string) error {\n\tif !setting.CacheService.LastCommit.Enabled {\n\t\treturn nil\n\t}\n\n\tcommit, err := gitRepo.GetCommit(fullRefName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcommitsCount, err := cache.GetInt64(repo.GetCommitsCountCacheKey(getRefName(fullRefName), true), commit.CommitsCount)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif commitsCount < setting.CacheService.LastCommit.CommitsCount {\n\t\treturn nil\n\t}\n\n\tcommitCache := git.NewLastCommitCache(repo.FullName(), gitRepo, setting.LastCommitCacheTTLSeconds, cache.GetCache())\n\n\treturn commitCache.CacheCommit(commit)\n}\n\nfunc getRefName(fullRefName string) string ", "output": "{\n\tif strings.HasPrefix(fullRefName, git.TagPrefix) {\n\t\treturn fullRefName[len(git.TagPrefix):]\n\t} else if strings.HasPrefix(fullRefName, git.BranchPrefix) {\n\t\treturn fullRefName[len(git.BranchPrefix):]\n\t}\n\treturn \"\"\n}"} {"input": "package sortedmap\n\nimport (\n\t\"testing\"\n\n\t\"github.com/umpc/go-sortedmap/asc\"\n)\n\nfunc insertRecord(b *testing.B) {\n\trecords := randRecords(1)\n\tsm := New(0, asc.Time)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsm.Insert(records[0].Key, records[0].Val)\n\n\t\tb.StopTimer()\n\t\trecords = randRecords(1)\n\t\tsm = New(0, asc.Time)\n\t\tb.StartTimer()\n\t}\n}\n\nfunc batchInsertRecords(b *testing.B, n int) {\n\trecords := randRecords(n)\n\tsm := New(0, asc.Time)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsm.BatchInsert(records)\n\n\t\tb.StopTimer()\n\t\trecords = randRecords(n)\n\t\tsm = New(0, asc.Time)\n\t\tb.StartTimer()\n\t}\n}\n\nfunc BenchmarkInsert1Record(b *testing.B) {\n\tinsertRecord(b)\n}\n\nfunc BenchmarkBatchInsert10Records(b *testing.B) {\n\tbatchInsertRecords(b, 10)\n}\n\n\n\nfunc BenchmarkBatchInsert1000Records(b *testing.B) {\n\tbatchInsertRecords(b, 1000)\n}\n\nfunc BenchmarkBatchInsert10000Records(b *testing.B) {\n\tbatchInsertRecords(b, 10000)\n}\n\nfunc BenchmarkBatchInsert100Records(b *testing.B) ", "output": "{\n\tbatchInsertRecords(b, 100)\n}"} {"input": "package block\n\n\ntype NoopLeaseManager struct{}\n\n\n\nfunc (n *NoopLeaseManager) UnregisterLeaser(leaser Leaser) error {\n\treturn nil\n}\n\nfunc (n *NoopLeaseManager) OpenLease(\n\tleaser Leaser,\n\tdescriptor LeaseDescriptor,\n\tstate LeaseState,\n) error {\n\treturn nil\n}\n\nfunc (n *NoopLeaseManager) OpenLatestLease(\n\tleaser Leaser,\n\tdescriptor LeaseDescriptor,\n) (LeaseState, error) {\n\treturn LeaseState{}, nil\n}\n\nfunc (n *NoopLeaseManager) UpdateOpenLeases(\n\tdescriptor LeaseDescriptor,\n\tstate LeaseState,\n) (UpdateLeasesResult, error) {\n\treturn UpdateLeasesResult{}, nil\n}\n\nfunc (n *NoopLeaseManager) SetLeaseVerifier(leaseVerifier LeaseVerifier) error {\n\treturn nil\n}\n\nfunc (n *NoopLeaseManager) RegisterLeaser(leaser Leaser) error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/codegangsta/martini-contrib/render\"\n\t\"github.com/luan/godo/godo\"\n\t\"net/http\"\n)\n\ntype ProjectsController struct{}\n\nfunc (c *ProjectsController) List(r render.Render) {\n\tprojects, _ := godo.NewProjectManager().FindAllWithTasks()\n\n\tr.HTML(200, \"projects\", projects)\n}\n\n\n\nfunc (c *ProjectsController) Create(req *http.Request, r render.Render) ", "output": "{\n\n\tp := godo.NewProject(req.FormValue(\"name\"))\n\tgodo.NewProjectManager().Add(&p)\n\n\tr.Redirect(\"/projects\", 301)\n}"} {"input": "package parsex\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype ParsexError struct {\n\tPos int\n\tMessage string\n}\n\nfunc (err ParsexError) Error() string {\n\treturn fmt.Sprintf(\"pos %d :\\n%s\",\n\t\terr.Pos, err.Message)\n}\n\ntype ParsexState interface {\n\tNext(pred func(int, interface{}) (interface{}, error)) (x interface{}, err error)\n\tPos() int\n\tSeekTo(int)\n\tTrap(message string, args ...interface{}) error\n}\n\ntype StateInMemory struct {\n\tbuffer []interface{}\n\tpos int\n}\n\n\n\nfunc (this *StateInMemory) Next(pred func(int, interface{}) (interface{}, error)) (x interface{}, err error) {\n\tbuffer := (*this).buffer\n\tif (*this).pos < len(buffer) {\n\t\tx := buffer[(*this).pos]\n\t\toutput, err := pred((*this).pos, x)\n\t\tif err == nil {\n\t\t\t(*this).pos++\n\t\t\treturn output, nil\n\t\t} else {\n\t\t\treturn x, err\n\t\t}\n\t} else {\n\t\treturn nil, io.EOF\n\t}\n}\n\nfunc (this *StateInMemory) Pos() int {\n\treturn (*this).pos\n}\n\nfunc (this *StateInMemory) SeekTo(pos int) {\n\tend := len((*this).buffer)\n\tif pos < 0 || pos > end {\n\t\tmessage := fmt.Sprintf(\"%d out range [0, %d]\", pos, end)\n\t\tpanic(errors.New(message))\n\t}\n\t(*this).pos = pos\n}\n\nfunc (this *StateInMemory) Trap(message string, args ...interface{}) error {\n\treturn ParsexError{(*this).pos,\n\t\tfmt.Sprintf(message, args...)}\n}\n\nfunc NewStateInMemory(buffer []interface{}) *StateInMemory ", "output": "{\n\treturn &StateInMemory{buffer, 0}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/ian-kent/go-log/log\"\n\t\"github.com/ian-kent/gotcha/http\"\n\t\"strconv\"\n)\n\n\n\nfunc pkgindex(session *http.Session) {\n\tif _, ok := session.Stash[\"repo\"]; !ok {\n\t\tsession.RenderNotFound()\n\t\treturn\n\t}\n\n\trepo := session.Stash[\"repo\"].(string)\n\n\tfor fname, _ := range indexes {\n\t\tif _, ok := indexes[fname][repo]; !ok && repo != \"SmartPAN\" {\n\t\t\tsession.RenderNotFound()\n\t\t\treturn\n\t\t}\n\t}\n\n\tif g, ok := session.Stash[\"gz\"]; ok {\n\t\tif len(g.(string)) > 0 {\n\t\t\tsession.Response.Headers.Set(\"Content-Type\", \"application/gzip\")\n\t\t\tsession.Response.Send()\n\t\t\tsession.Response.Gzip()\n\t\t\tsession.Response.Headers.Remove(\"Content-Encoding\")\n\t\t\tlog.Debug(\"Using gzip\")\n\t\t}\n\t}\n\n\tsession.Response.WriteText(\"File: 02packages.details.txt\\n\")\n\tsession.Response.WriteText(\"Description: Package names found in directory \" + repo + \"/authors/id\\n\")\n\tsession.Response.WriteText(\"Columns: package name, version, path\\n\")\n\tsession.Response.WriteText(\"Written-By: SmartPAN (from GoPAN)\\n\")\n\tsession.Response.WriteText(\"Line-Count: \" + strconv.Itoa(summary.Packages) + \"\\n\") \n\tsession.Response.WriteText(\"\\n\")\n\n\tif repo == \"SmartPAN\" {\n\t\tfor _, pkg := range packages {\n\t\t\twritepkgindex(session, pkg)\n\t\t}\n\t} else {\n\t\tfor _, pkg := range idxpackages[repo] {\n\t\t\twritepkgindex(session, pkg)\n\t\t}\n\t}\n}\n\nfunc writepkgindex(session *http.Session, pkgspace *PkgSpace) ", "output": "{\n\tif len(pkgspace.Packages) > 0 {\n\t\tlatest := pkgspace.Packages[0]\n\t\tif len(latest.Version) == 0 {\n\t\t\tlatest.Version = \"undef\"\n\t\t}\n\t\tsession.Response.WriteText(fmt.Sprintf(\"%-40s %-10s %s\\n\", pkgspace.FullName(), latest.Version, latest.Package.AuthorURL()))\n\t}\n\n\tif len(pkgspace.Children) > 0 {\n\t\tfor _, ps := range pkgspace.Children {\n\t\t\twritepkgindex(session, ps)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/mrcsparker/ifin/service\"\n)\n\n\n\nfunc main() {\n\tfmt.Println(welcome())\n\n\tcontroller := service.Flow{}\n\tfmt.Println(controller.GetAboutInfo())\n\n}\n\nfunc welcome() string ", "output": "{\n\treturn \"[ifin]\"\n}"} {"input": "package eventbreakpoints\n\n\n\nimport (\n\t\"context\"\n\n\t\"github.com/chromedp/cdproto/cdp\"\n)\n\n\n\ntype SetInstrumentationBreakpointParams struct {\n\tEventName string `json:\"eventName\"` \n}\n\n\n\n\n\n\n\n\n\n\nfunc (p *SetInstrumentationBreakpointParams) Do(ctx context.Context) (err error) {\n\treturn cdp.Execute(ctx, CommandSetInstrumentationBreakpoint, p, nil)\n}\n\n\n\ntype RemoveInstrumentationBreakpointParams struct {\n\tEventName string `json:\"eventName\"` \n}\n\n\n\n\n\n\n\n\nfunc RemoveInstrumentationBreakpoint(eventName string) *RemoveInstrumentationBreakpointParams {\n\treturn &RemoveInstrumentationBreakpointParams{\n\t\tEventName: eventName,\n\t}\n}\n\n\nfunc (p *RemoveInstrumentationBreakpointParams) Do(ctx context.Context) (err error) {\n\treturn cdp.Execute(ctx, CommandRemoveInstrumentationBreakpoint, p, nil)\n}\n\n\nconst (\n\tCommandSetInstrumentationBreakpoint = \"EventBreakpoints.setInstrumentationBreakpoint\"\n\tCommandRemoveInstrumentationBreakpoint = \"EventBreakpoints.removeInstrumentationBreakpoint\"\n)\n\nfunc SetInstrumentationBreakpoint(eventName string) *SetInstrumentationBreakpointParams ", "output": "{\n\treturn &SetInstrumentationBreakpointParams{\n\t\tEventName: eventName,\n\t}\n}"} {"input": "package pointer\n\nimport \"time\"\n\nfunc DefaultBool(value *bool, defaultValue bool) *bool {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultDuration(value *time.Duration, defaultValue time.Duration) *time.Duration {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultFloat64(value *float64, defaultValue float64) *float64 {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\n\n\nfunc DefaultString(value *string, defaultValue string) *string {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultStringArray(value *[]string, defaultValue []string) *[]string {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultTime(value *time.Time, defaultValue time.Time) *time.Time {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultInt(value *int, defaultValue int) *int ", "output": "{\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}"} {"input": "package lease\n\n\n\ntype block struct {\n\tleaseName string\n\tunblock chan struct{}\n\tabort <-chan struct{}\n}\n\n\n\nfunc (b block) invoke(ch chan<- block) error {\n\tfor {\n\t\tselect {\n\t\tcase <-b.abort:\n\t\t\treturn errStopped\n\t\tcase ch <- b:\n\t\t\tch = nil\n\t\tcase <-b.unblock:\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\n\n\ntype blocks map[string][]chan struct{}\n\n\nfunc (b blocks) add(block block) {\n\tb[block.leaseName] = append(b[block.leaseName], block.unblock)\n}\n\n\n\n\n\nfunc (b blocks) unblock(leaseName string) ", "output": "{\n\tunblocks := b[leaseName]\n\tdelete(b, leaseName)\n\tfor _, unblock := range unblocks {\n\t\tclose(unblock)\n\t}\n}"} {"input": "package grace\n\nimport \"net/http\"\n\ntype ServeMux struct {\n\thttp.ServeMux\n}\n\n\n\n\n\nfunc NewServeMux() *ServeMux { return &ServeMux{*http.NewServeMux()} }\n\n\nvar DefaultServeMux = NewServeMux()\n\nfunc (sm *ServeMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) ", "output": "{\n\tsm.Handle(pattern, HandlerFunc(handler))\n}"} {"input": "package remotestate\n\nimport (\n\t\"context\"\n\n\t\"github.com/r3labs/terraform/backend\"\n\t\"github.com/r3labs/terraform/helper/schema\"\n\t\"github.com/r3labs/terraform/state\"\n\t\"github.com/r3labs/terraform/state/remote\"\n\t\"github.com/r3labs/terraform/terraform\"\n)\n\n\n\n\n\n\ntype Backend struct {\n\t*schema.Backend\n\n\tConfigureFunc func(ctx context.Context) (remote.Client, error)\n\n\tclient remote.Client\n}\n\nfunc (b *Backend) Configure(rc *terraform.ResourceConfig) error {\n\tb.Backend.ConfigureFunc = func(ctx context.Context) error {\n\t\tc, err := b.ConfigureFunc(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tb.client = c\n\t\treturn nil\n\t}\n\n\treturn b.Backend.Configure(rc)\n}\n\nfunc (b *Backend) States() ([]string, error) {\n\treturn nil, backend.ErrNamedStatesNotSupported\n}\n\nfunc (b *Backend) DeleteState(name string) error {\n\treturn backend.ErrNamedStatesNotSupported\n}\n\n\n\nfunc (b *Backend) State(name string) (state.State, error) ", "output": "{\n\tif b.client == nil {\n\t\tpanic(\"nil remote client\")\n\t}\n\n\tif name != backend.DefaultStateName {\n\t\treturn nil, backend.ErrNamedStatesNotSupported\n\t}\n\n\ts := &remote.State{Client: b.client}\n\treturn s, nil\n}"} {"input": "package rotaryLogger\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\nvar Logger *log.Logger\n\nvar file os.File\n\n\n\n\n\n\n\n\n\nfunc StartLogger(logLocation string) {\n\tfile, err := os.OpenFile(logLocation+\"0.log\", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to open Logger file\", err)\n\t}\n\n\tmulti := io.MultiWriter(file, os.Stdout)\n\n\tLogger = log.New(multi,\n\t\t\"\", \n\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n}\n\n\n\nfunc logRotator(logAmount int, logLocation string) {\n\tif _, err := os.Stat(logLocation + strconv.Itoa(logAmount) + \".log\"); os.IsNotExist(err) {\n\t\tos.Remove(logLocation + strconv.Itoa(logAmount) + \".log\")\n\t}\n\n\tfor i := 2; i != -1; i-- {\n\t\tfmt.Println(logLocation + strconv.Itoa(i) + \".log\")\n\t\tif _, err := os.Stat(logLocation + strconv.Itoa(i) + \".log\"); err == nil {\n\t\t\tos.Rename(logLocation+strconv.Itoa(i)+\".log\", logLocation+strconv.Itoa(i+1)+\".log\")\n\t\t}\n\t}\n}\n\nfunc StartLoggerWRotation(logAmount int, logLocation string, rotationPeriod time.Duration) ", "output": "{\n\tlogRotator(logAmount, logLocation)\n\n\tStartLogger(logLocation)\n\n\tticker := time.NewTicker(rotationPeriod)\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tLogger.Println(\"Rotating Logs\")\n\n\t\t\tLogger = log.New(os.Stdout,\n\t\t\t\t\"\", \n\t\t\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n\n\t\t\tlogRotator(logAmount, logLocation)\n\n\t\t\tStartLogger(logLocation)\n\n\t\t}\n\t}()\n}"} {"input": "package s0132\n\nimport (\n\t\"github.com/peterstace/project-euler/number\"\n)\n\nfunc Answer() interface{} {\n\treturn SumPrimeFactors(40, 10e9)\n}\n\n\n\n\nfunc repunit(k, m int) int {\n\tif k == 1 {\n\t\treturn 1\n\t}\n\tif k%2 == 0 {\n\t\thalf := repunit(k/2, m)\n\t\treturn (tenPow(k/2, m)*half + half) % m\n\t} else {\n\t\treturn (10*repunit(k-1, m) + 1) % m\n\t}\n}\n\n\nfunc tenPow(k, m int) int {\n\tif k == 0 {\n\t\treturn 1\n\t}\n\tif k%2 == 0 {\n\t\thalf := tenPow(k/2, m)\n\t\treturn (half * half) % m\n\t} else {\n\t\treturn (10 * tenPow(k-1, m)) % m\n\t}\n}\n\nfunc SumPrimeFactors(numFactors int, k int) int ", "output": "{\n\tvar factorsFound int\n\tvar sum int\n\tnthPrime := number.MakeSieveBackedNthPrime()\n\tfor i := 0; factorsFound < numFactors; i++ {\n\t\tp := nthPrime(i)\n\t\tif repunit(k, p) == 0 {\n\t\t\tfactorsFound++\n\t\t\tsum += p\n\t\t}\n\t}\n\treturn sum\n}"} {"input": "package api\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/google/gapid/core/data/id\"\n\t\"github.com/google/gapid/core/image\"\n\t\"github.com/google/gapid/gapil/constset\"\n)\n\n\ntype API interface {\n\tName() string\n\n\tIndex() uint8\n\n\tID() ID\n\n\tConstantSets() *constset.Pack\n\n\tGetFramebufferAttachmentInfo(\n\t\tctx context.Context,\n\t\tafter []uint64,\n\t\tstate *GlobalState,\n\t\tthread uint64,\n\t\tattachment FramebufferAttachment) (width, height, index uint32, format *image.Format, err error)\n\n\tContext(state *GlobalState, thread uint64) Context\n\n\tCreateCmd(name string) Cmd\n}\n\n\ntype ID id.ID\n\n\nfunc (i ID) IsValid() bool { return id.ID(i).IsValid() }\nfunc (i ID) String() string { return id.ID(i).String() }\n\n\ntype APIObject interface {\n\tAPI() API\n}\n\nvar apis = map[ID]API{}\nvar indices = map[uint8]bool{}\n\n\n\nfunc Register(api API) {\n\tid := api.ID()\n\tif _, present := apis[id]; present {\n\t\tpanic(fmt.Errorf(\"API %s registered more than once\", id))\n\t}\n\tapis[id] = api\n\n\tindex := api.Index()\n\tif _, present := indices[index]; present {\n\t\tpanic(fmt.Errorf(\"API %s used an occupied index %d\", id, index))\n\t}\n\tindices[index] = true\n}\n\n\n\n\n\nfunc Find(id ID) API ", "output": "{\n\treturn apis[id]\n}"} {"input": "package vcl\n\n\n\n\nimport (\n\t. \"github.com/ying32/govcl/vcl/api\"\n\t. \"github.com/ying32/govcl/vcl/types\"\n)\n\ntype (\n\tNSObject uintptr\n\n\tNSWindow uintptr\n\n\tNSURL uintptr\n)\n\n\n\n\nfunc (f *TForm) PlatformWindow() NSWindow {\n\tr, _, _ := NSWindow_FromForm.Call(f.instance)\n\treturn NSWindow(r)\n}\n\nfunc (n NSWindow) TitleVisibility() NSWindowTitleVisibility {\n\tr, _, _ := NSWindow_titleVisibility.Call(uintptr(n))\n\treturn NSWindowTitleVisibility(r)\n}\n\nfunc (n NSWindow) SetTitleVisibility(flag NSWindowTitleVisibility) {\n\tNSWindow_setTitleVisibility.Call(uintptr(n), uintptr(flag))\n}\n\nfunc (n NSWindow) TitleBarAppearsTransparent() bool {\n\tr, _, _ := NSWindow_titlebarAppearsTransparent.Call(uintptr(n))\n\treturn DBoolToGoBool(r)\n}\n\nfunc (n NSWindow) SetTitleBarAppearsTransparent(flag bool) {\n\tNSWindow_setTitlebarAppearsTransparent.Call(uintptr(n), GoBoolToDBool(flag))\n}\n\nfunc (n NSWindow) SetRepresentedURL(url NSURL) {\n\tNSWindow_setRepresentedURL.Call(uintptr(n), uintptr(url))\n}\n\nfunc (n NSWindow) StyleMask() uint {\n\tr, _, _ := NSWindow_styleMask.Call(uintptr(n))\n\treturn uint(r)\n}\n\nfunc (n NSWindow) SetStyleMask(mask uint) {\n\tNSWindow_setStyleMask.Call(uintptr(n), uintptr(mask))\n}\n\nfunc HandleToPlatformHandle(h HWND) NSObject ", "output": "{\n\treturn NSObject(h)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc main() {\n\targs := []int{5, 2, 6, 1}\n\tfmt.Println(countSmaller(args))\n}\n\nfunc countSmaller(nums []int) []int ", "output": "{\n\tvar nums2 []int\n\n\tfor i, numb := range nums {\n\t\ttimeCount := 0\n\t\tfor ii := i; ii < len(nums); ii++ {\n\t\t\tif nums[ii] < numb {\n\t\t\t\ttimeCount = timeCount + 1\n\t\t\t}\n\t\t}\n\t\tnums2 = append(nums2, timeCount)\n\t}\n\n\treturn nums2\n\n}"} {"input": "package engine\n\n\ntype Novel struct {\n\tName string \n\tLastUpdateTime string \n\tAuthor string \n\tMenuURL string \n\tIconURL string \n\tNewestLastChapterName string \n\tDescription string \n\tMenus []*Menu \n\tChapters []*Chapter \n}\n\n\ntype Menu struct {\n\tName string \n\tURL string \n}\n\n\ntype Chapter struct {\n\tTitle string \n\tContent string \n}\n\nfunc (novel *Novel) AddMenu(menu *Menu) {\n\tnovel.Menus = append(novel.Menus, menu)\n}\n\nfunc (novel *Novel) AddChapter(chapter *Chapter) {\n\tnovel.Chapters = append(novel.Chapters, chapter)\n}\n\n\n\nfunc NewChapter(title, content string) *Chapter {\n\treturn &Chapter{title, content}\n}\n\nfunc NewMenu(name, url string) *Menu ", "output": "{\n\treturn &Menu{name, url}\n}"} {"input": "package block\n\n\ntype NoopLeaseManager struct{}\n\nfunc (n *NoopLeaseManager) RegisterLeaser(leaser Leaser) error {\n\treturn nil\n}\n\nfunc (n *NoopLeaseManager) UnregisterLeaser(leaser Leaser) error {\n\treturn nil\n}\n\n\n\nfunc (n *NoopLeaseManager) OpenLatestLease(\n\tleaser Leaser,\n\tdescriptor LeaseDescriptor,\n) (LeaseState, error) {\n\treturn LeaseState{}, nil\n}\n\nfunc (n *NoopLeaseManager) UpdateOpenLeases(\n\tdescriptor LeaseDescriptor,\n\tstate LeaseState,\n) (UpdateLeasesResult, error) {\n\treturn UpdateLeasesResult{}, nil\n}\n\nfunc (n *NoopLeaseManager) SetLeaseVerifier(leaseVerifier LeaseVerifier) error {\n\treturn nil\n}\n\nfunc (n *NoopLeaseManager) OpenLease(\n\tleaser Leaser,\n\tdescriptor LeaseDescriptor,\n\tstate LeaseState,\n) error ", "output": "{\n\treturn nil\n}"} {"input": "package config\n\nimport (\n\t\"encoding/json\"\n\t\"os\"\n)\n\n\n\n\ntype Config struct {\n\tBindAddress string `json:\"bindAddress\"`\n\tImageDirectory string `json:\"imageDirectory\"`\n\tDbProtocol string `json:\"dbProtocol\"`\n\tDbAddress string `json:\"dbAddress\"`\n\tDbName string `json:\"dbName\"`\n\tDbUser string `json:\"dbUser\"`\n\tDbPassword string `json:\"dbPassword\"`\n\tAuthToken string `json:\"authToken\"`\n}\n\n\n\n\n\nfunc LoadConfig(path string) (*Config, error) ", "output": "{\n\tfile, openErr := os.Open(path)\n\tif openErr != nil {\n\t\treturn nil, openErr\n\t}\n\tdefer file.Close()\n\tdecoder := json.NewDecoder(file)\n\tconfig := Config{}\n\tdecodeErr := decoder.Decode(&config)\n\treturn &config, decodeErr\n}"} {"input": "package render\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\ntype Redirect struct {\n\tCode int\n\tRequest *http.Request\n\tLocation string\n}\n\n\n\nfunc (r Redirect) Render(w http.ResponseWriter) error ", "output": "{\n\tif r.Code < 300 || r.Code > 308 {\n\t\tpanic(fmt.Sprintf(\"Cannot redirect with status code %d\", r.Code))\n\t}\n\thttp.Redirect(w, r.Request, r.Location, r.Code)\n\treturn nil\n}"} {"input": "package main\n\nimport (\n \"os\"\n \"fmt\"\n \"bufio\"\n \"encoding/hex\"\n)\n\n\nfunc check(e error) {\n\tif e != nil {\n\t\tfmt.Printf(\"Error: %s\\n\", e.Error())\n\t\tos.Exit(0)\n\t}\n}\n\n\nfunc get_hex_data(filename string) [][]byte {\n file, err := os.Open(filename)\n check(err)\n\n var data [][]byte\n scan := bufio.NewScanner(file)\n\n\tfor scan.Scan() {\n temp, err := hex.DecodeString(scan.Text())\n check(err)\n data = append(data, temp)\n }\n\n return data\n}\n\n\n\n\n\nfunc main() {\n fmt.Println(\"Cryptopals Set 1\")\n fmt.Println(\"================\")\n\n fmt.Println(\"Challenge 8\")\n fmt.Println(\"-----------\")\n\n block_size := 16\n crypts := get_hex_data(\"data/8.txt\")\n low := len(crypts[0]) / block_size\n msg := \"\"\n\n for _, crypt := range crypts {\n chunks := chunk(crypt, block_size)\n temp := make(map[string] int)\n\n for _, c := range chunks {\n temp[string(c)] = 0\n }\n\n \n \n if len(temp) < low {\n low = len(temp)\n msg = string(crypt)\n }\n }\n\n for _, c := range chunk([]byte(msg), 16) {\n fmt.Printf(\"%x\\n\", c)\n }\n}\n\nfunc chunk(data []byte, size int) [][]byte ", "output": "{\n var chunks [][]byte\n\n for i:=0; i 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (m *Ticket) validateEventID(formats strfmt.Registry) error {\n\n\tif err := validate.RequiredString(\"event_id\", \"body\", string(m.EventID)); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (m *Ticket) validateNum(formats strfmt.Registry) error ", "output": "{\n\n\tif err := validate.Required(\"num\", \"body\", int32(m.Num)); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package cgzip\n\n\nimport \"C\"\n\nimport (\n\t\"hash\"\n\t\"unsafe\"\n)\n\ntype adler32Hash struct {\n\tadler C.uLong\n}\n\n\n\nfunc NewAdler32() hash.Hash32 {\n\ta := &adler32Hash{}\n\ta.Reset()\n\treturn a\n}\n\n\nfunc (a *adler32Hash) Write(p []byte) (n int, err error) {\n\tif len(p) > 0 {\n\t\ta.adler = C.adler32(a.adler, (*C.Bytef)(unsafe.Pointer(&p[0])), (C.uInt)(len(p)))\n\t}\n\treturn len(p), nil\n}\n\n\n\n\nfunc (a *adler32Hash) Reset() {\n\ta.adler = C.adler32(0, (*C.Bytef)(unsafe.Pointer(nil)), 0)\n}\n\nfunc (a *adler32Hash) Size() int {\n\treturn 4\n}\n\nfunc (a *adler32Hash) BlockSize() int {\n\treturn 1\n}\n\n\nfunc (a *adler32Hash) Sum32() uint32 {\n\treturn uint32(a.adler)\n}\n\n\n\n\n\n\n\nfunc Adler32Combine(adler1, adler2 uint32, len2 int) uint32 {\n\treturn uint32(C.adler32_combine(C.uLong(adler1), C.uLong(adler2), C.z_off_t(len2)))\n}\n\nfunc (a *adler32Hash) Sum(b []byte) []byte ", "output": "{\n\ts := a.Sum32()\n\tb = append(b, byte(s>>24))\n\tb = append(b, byte(s>>16))\n\tb = append(b, byte(s>>8))\n\tb = append(b, byte(s))\n\treturn b\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype TerminateDbSystemRequest struct {\n\n\tDbSystemId *string `mandatory:\"true\" contributesTo:\"path\" name:\"dbSystemId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request TerminateDbSystemRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request TerminateDbSystemRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request TerminateDbSystemRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype TerminateDbSystemResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response TerminateDbSystemResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response TerminateDbSystemResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package routes\n\nimport (\n\t\"k8s.io/kubernetes/pkg/genericapiserver/server/mux\"\n\n\t\"github.com/emicklei/go-restful/swagger\"\n)\n\n\n\n\n\ntype Swagger struct {\n\tConfig *swagger.Config\n}\n\n\n\n\nfunc (s Swagger) Install(c *mux.APIContainer) ", "output": "{\n\ts.Config.WebServices = c.RegisteredWebServices()\n\tswagger.RegisterSwaggerService(*s.Config, c.Container)\n}"} {"input": "package store\n\nimport (\n\t\"github.com/docker/docker/pkg/plugins\"\n)\n\n\nfunc FindWithCapability(capability string) ([]CompatPlugin, error) {\n\tpl, err := plugins.GetAll(capability)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := make([]CompatPlugin, len(pl))\n\tfor i, p := range pl {\n\t\tresult[i] = p\n\t}\n\treturn result, nil\n}\n\n\n\n\nfunc LookupWithCapability(name, capability string, _ int) (CompatPlugin, error) ", "output": "{\n\treturn plugins.Get(name, capability)\n}"} {"input": "package notmain\n\nimport (\n\t\"testing\"\n\n\t\"github.com/letsencrypt/boulder/test\"\n)\n\nfunc TestLineValidAccepts(t *testing.T) {\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: kKG6cwA Caught SIGTERM\")\n\ttest.AssertNotError(t, err, \"errored on valid checksum\")\n}\n\nfunc TestLineValidRejects(t *testing.T) {\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: xxxxxxx Caught SIGTERM\")\n\ttest.AssertError(t, err, \"didn't error on invalid checksum\")\n}\n\n\n\nfunc TestLineValidNonOurobouros(t *testing.T) {\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: xxxxxxx Caught SIGTERM\")\n\ttest.AssertError(t, err, \"didn't error on invalid checksum\")\n\n\tselfOutput := \"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 log-validator[1337]: xxxxxxx \" + err.Error()\n\terr2 := lineValid(selfOutput)\n\ttest.AssertNotError(t, err2, \"expected no error when feeding lineValid's error output into itself\")\n}\n\nfunc TestLineValidRejectsNotAChecksum(t *testing.T) ", "output": "{\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: xxxx Caught SIGTERM\")\n\ttest.AssertError(t, err, \"didn't error on invalid checksum\")\n\ttest.AssertErrorIs(t, err, errInvalidChecksum)\n}"} {"input": "package figure\n\nimport (\n \"fmt\"\n \"log\"\n \"net/http\"\n \"strconv\"\n \"strings\"\n)\n\nconst signature = \"flf2\"\nconst reverseFlag = \"1\"\nvar charDelimiters = [3]string{\"@\", \"#\", \"$\"}\nvar hardblanksBlacklist = [2]byte{'a', '2'}\n\nfunc getFile(name string) (file http.File) {\n filePath := fmt.Sprintf(\"%s.flf\", name)\n file, err := AssetFS().Open(filePath)\n if err != nil {\n log.Fatalf(\"invalid font name:%s.\",err)\n }\n return file\n}\n\nfunc getHeight(metadata string) int {\n datum := strings.Fields(metadata)[1]\n height, _ := strconv.Atoi(datum)\n return height\n}\n\nfunc getBaseline(metadata string) int {\n datum := strings.Fields(metadata)[2]\n baseline, _ := strconv.Atoi(datum)\n return baseline\n}\n\n\n\nfunc getReverse(metadata string) bool {\n data := strings.Fields(metadata)\n return len(data) > 6 && data[6] == reverseFlag\n}\n\nfunc lastCharLine(text string, height int) bool {\n endOfLine, length := \" \", 2\n if height == 1 && len(text) > 0 {\n length = 1\n }\n if len(text) >= length {\n endOfLine = text[len(text)-length:]\n }\n return endOfLine == strings.Repeat(charDelimiters[0], length) ||\n endOfLine == strings.Repeat(charDelimiters[1], length) ||\n endOfLine == strings.Repeat(charDelimiters[2], length)\n}\n\nfunc getHardblank(metadata string) byte ", "output": "{\n datum := strings.Fields(metadata)[0]\n hardblank := datum[len(datum)-1]\n if hardblank == hardblanksBlacklist[0] || hardblank == hardblanksBlacklist[1] {\n return ' '\n } else {\n return hardblank\n }\n}"} {"input": "package lib2048\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Direction int\n\nconst layout = \"15:04:05.12\"\nconst (\n\tUp Direction = iota + 1\n\tLeft\n\tDown\n\tRight\n)\n\ntype Move struct {\n\tTime time.Time\n\tDirection Direction\n}\n\nfunc NewMove(dir Direction) *Move {\n\treturn &Move{time.Now(), dir}\n}\n\n\n\nfunc (m *Move) String() string ", "output": "{\n\tvar moveString string\n\tswitch m.Direction {\n\tcase Up:\n\t\tmoveString = \"Up\"\n\tcase Down:\n\t\tmoveString = \"Down\"\n\tcase Left:\n\t\tmoveString = \"Left\"\n\tcase Right:\n\t\tmoveString = \"Right\"\n\t}\n\n\treturn fmt.Sprintf(\"'%s': %s\", m.Time.Format(layout), moveString)\n}"} {"input": "package azure\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\n\tv1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/util/uuid\"\n\t\"k8s.io/kubernetes/test/e2e/framework\"\n\t\"k8s.io/legacy-cloud-providers/azure\"\n)\n\nfunc init() {\n\tframework.RegisterProvider(\"azure\", newProvider)\n}\n\n\n\n\ntype Provider struct {\n\tframework.NullProvider\n\n\tazureCloud *azure.Cloud\n}\n\n\nfunc (p *Provider) DeleteNode(node *v1.Node) error {\n\treturn errors.New(\"not implemented yet\")\n}\n\n\nfunc (p *Provider) CreatePD(zone string) (string, error) {\n\tpdName := fmt.Sprintf(\"%s-%s\", framework.TestContext.Prefix, string(uuid.NewUUID()))\n\t_, diskURI, _, err := p.azureCloud.CreateVolume(pdName, \"\" , \"\" , \"\" , 1 )\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn diskURI, nil\n}\n\n\nfunc (p *Provider) DeletePD(pdName string) error {\n\tif err := p.azureCloud.DeleteVolume(pdName); err != nil {\n\t\tframework.Logf(\"failed to delete Azure volume %q: %v\", pdName, err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\nfunc (p *Provider) EnableAndDisableInternalLB() (enable, disable func(svc *v1.Service)) {\n\tenable = func(svc *v1.Service) {\n\t\tsvc.ObjectMeta.Annotations = map[string]string{azure.ServiceAnnotationLoadBalancerInternal: \"true\"}\n\t}\n\tdisable = func(svc *v1.Service) {\n\t\tsvc.ObjectMeta.Annotations = map[string]string{azure.ServiceAnnotationLoadBalancerInternal: \"false\"}\n\t}\n\treturn\n}\n\nfunc newProvider() (framework.ProviderInterface, error) ", "output": "{\n\tif framework.TestContext.CloudConfig.ConfigFile == \"\" {\n\t\treturn nil, fmt.Errorf(\"config-file must be specified for Azure\")\n\t}\n\tconfig, err := os.Open(framework.TestContext.CloudConfig.ConfigFile)\n\tif err != nil {\n\t\tframework.Logf(\"Couldn't open cloud provider configuration %s: %#v\",\n\t\t\tframework.TestContext.CloudConfig.ConfigFile, err)\n\t}\n\tdefer config.Close()\n\tazureCloud, err := azure.NewCloud(config)\n\treturn &Provider{\n\t\tazureCloud: azureCloud.(*azure.Cloud),\n\t}, err\n}"} {"input": "package serviceaccess_test\n\nimport (\n\t\"github.com/cloudfoundry/cli/cf/i18n\"\n\t\"github.com/cloudfoundry/cli/cf/i18n/detection\"\n\t\"github.com/cloudfoundry/cli/testhelpers/configuration\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestServiceAccess(t *testing.T) ", "output": "{\n\tconfig := configuration.NewRepositoryWithDefaults()\n\ti18n.T = i18n.Init(config, &detection.JibberJabberDetector{})\n\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Service Access Suite\")\n}"} {"input": "package syscall\n\nfunc setTimespec(sec, nsec int64) Timespec {\n\treturn Timespec{Sec: sec, Nsec: nsec}\n}\n\nfunc setTimeval(sec, usec int64) Timeval {\n\treturn Timeval{Sec: sec, Usec: usec}\n}\n\n\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint64(length)\n}\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\n\nconst RTM_LOCK = 0x8\n\n\n\nconst SYS___SYSCTL = SYS_SYSCTL\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) ", "output": "{\n\tk.Ident = uint64(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}"} {"input": "package common\n\nimport (\n\t\"encoding/binary\"\n\t\"sort\"\n)\n\n\n\ntype Uint64Slice []uint64\n\nfunc (p Uint64Slice) Len() int { return len(p) }\nfunc (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] }\nfunc (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p Uint64Slice) Sort() { sort.Sort(p) }\n\n\n\nfunc (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) }\n\n\n\nfunc PutUint64LE(dest []byte, i uint64) {\n\tbinary.LittleEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64LE(src []byte) uint64 {\n\treturn binary.LittleEndian.Uint64(src)\n}\n\nfunc PutUint64BE(dest []byte, i uint64) {\n\tbinary.BigEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64BE(src []byte) uint64 {\n\treturn binary.BigEndian.Uint64(src)\n}\n\nfunc PutInt64LE(dest []byte, i int64) {\n\tbinary.LittleEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64LE(src []byte) int64 {\n\treturn int64(binary.LittleEndian.Uint64(src))\n}\n\nfunc PutInt64BE(dest []byte, i int64) {\n\tbinary.BigEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64BE(src []byte) int64 {\n\treturn int64(binary.BigEndian.Uint64(src))\n}\n\nfunc SearchUint64s(a []uint64, x uint64) int ", "output": "{\n\treturn sort.Search(len(a), func(i int) bool { return a[i] >= x })\n}"} {"input": "package nom\n\nimport (\n\t\"encoding/gob\"\n\t\"fmt\"\n)\n\n\nconst (\n\tPortFlood UID = \"Ports.PortBcast\"\n\tPortAll UID = \"Ports.PortAll\"\n)\n\n\ntype PacketIn struct {\n\tNode UID\n\tInPort UID\n\tBufferID PacketBufferID\n\tPacket Packet\n}\n\nfunc (in PacketIn) String() string {\n\treturn fmt.Sprintf(\"packet in on switch %s port %s\", in.Node, in.InPort)\n}\n\n\ntype PacketOut struct {\n\tNode UID\n\tInPort UID\n\tBufferID PacketBufferID\n\tPacket Packet\n\tActions []Action\n}\n\n\ntype Packet []byte\n\n\nfunc (p Packet) DstMAC() MACAddr {\n\treturn MACAddr{p[0], p[1], p[2], p[3], p[4], p[5]}\n}\n\n\n\n\n\n\n\ntype PacketBufferID uint32\n\nfunc init() {\n\tgob.Register(Packet{})\n\tgob.Register(PacketBufferID(0))\n\tgob.Register(PacketIn{})\n\tgob.Register(PacketOut{})\n}\n\nfunc (p Packet) SrcMAC() MACAddr ", "output": "{\n\treturn MACAddr{p[6], p[7], p[8], p[9], p[10], p[11]}\n}"} {"input": "package testlib\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\n\n\nfunc Mktmp(tb testing.TB) string ", "output": "{\n\ttb.Helper()\n\tfolder := tb.TempDir()\n\tcurrent, err := os.Getwd()\n\trequire.NoError(tb, err)\n\trequire.NoError(tb, os.Chdir(folder))\n\ttb.Cleanup(func() {\n\t\trequire.NoError(tb, os.Chdir(current))\n\t})\n\treturn folder\n}"} {"input": "package dml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/dml\"\n)\n\nfunc TestCT_TablePartStyleConstructor(t *testing.T) {\n\tv := dml.NewCT_TablePartStyle()\n\tif v == nil {\n\t\tt.Errorf(\"dml.NewCT_TablePartStyle must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed dml.CT_TablePartStyle should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestCT_TablePartStyleMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := dml.NewCT_TablePartStyle()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := dml.NewCT_TablePartStyle()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package migrations\n\nimport \"xorm.io/xorm\"\n\n\n\nfunc addEmailHashTable(x *xorm.Engine) error ", "output": "{\n\ttype EmailHash struct {\n\t\tHash string `xorm:\"pk varchar(32)\"`\n\t\tEmail string `xorm:\"UNIQUE NOT NULL\"`\n\t}\n\treturn x.Sync2(new(EmailHash))\n}"} {"input": "package xmlkey\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/xml\"\n\t\"math/big\"\n)\n\ntype (\n\tkeyXML struct {\n\t\tXMLName xml.Name `xml:\"RSAKeyValue\"`\n\t\tpublicKeyXML\n\t\tprivateKeyXML\n\t}\n\n\tpublicKeyXML struct {\n\t\tModulus, Exponent *bigInt\n\t}\n\tprivateKeyXML struct {\n\t\tP, Q, DP, DQ, D, InverseQ *bigInt\n\t}\n\n\tbigInt struct{ *big.Int }\n)\n\nfunc (k keyXML) HasPublicKey() bool {\n\treturn allNotEmpty(k.Exponent, k.Modulus)\n}\n\nfunc (k keyXML) HasPrivateKey() bool {\n\treturn allNotEmpty(k.D, k.DP, k.DQ, k.InverseQ, k.P, k.Q)\n}\n\n\n\nfunc (bi *bigInt) UnmarshalText(text []byte) error {\n\tbs := make([]byte, base64.StdEncoding.DecodedLen(len(text)))\n\tif _, err := base64.StdEncoding.Decode(bs, text); err != nil {\n\t\treturn err\n\t}\n\tif bi.Int == nil {\n\t\tbi.Int = new(big.Int)\n\t}\n\tbi.Int.SetBytes(bytes.TrimRight(bs, \"\\x00\"))\n\treturn nil\n}\n\nfunc (bi *bigInt) MarshalText() ([]byte, error) {\n\ttext := make([]byte, base64.StdEncoding.EncodedLen(len(bi.Bytes())))\n\tbase64.StdEncoding.Encode(text, bi.Bytes())\n\treturn text, nil\n}\n\nfunc (bi bigInt) BigInt() *big.Int {\n\treturn bi.Int\n}\n\nfunc (bi bigInt) Integer() int {\n\treturn int(bi.Int64())\n}\n\nfunc (bi bigInt) IsEmpty() bool {\n\treturn bi.Int == nil\n}\n\nfunc allNotEmpty(bis ...*bigInt) bool ", "output": "{\n\tfor _, bi := range bis {\n\t\tif bi == nil || bi.IsEmpty() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package blanket_emulator\n\nimport (\n\t\"fmt\"\n)\n\ntype Event interface {\n\tHash() uint64\n\tInspect() string\n}\n\ntype ReturnEvent uint64\ntype ReadEvent uint64\ntype WriteEvent struct {\n\tAddr uint64\n\tValue uint64\n}\ntype SyscallEvent uint64\ntype InvalidInstructionEvent uint64\n\nfunc (addr ReadEvent) Hash() uint64 {\n\treturn ReadEventHash(uint64(addr))\n}\n\n\n\nfunc (s SyscallEvent) Hash() uint64 {\n\treturn SysEventHash(uint64(s))\n}\n\nfunc (s ReturnEvent) Hash() uint64 {\n\treturn ReturnEventHash(uint64(s))\n}\n\nfunc (s InvalidInstructionEvent) Hash() uint64 {\n\treturn InvalidInstructionEventHash(uint64(s))\n}\n\nfunc (addr ReadEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Read([%x])\", addr)\n}\n\nfunc (addr ReturnEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Return([%x])\", addr)\n}\n\nfunc (s WriteEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Write([%x]=%x)\", s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Sys(%x)\", s)\n}\n\nfunc (s InvalidInstructionEvent) Inspect() string {\n\treturn fmt.Sprintf(\"InvalidOpcode([%x])\", s)\n}\n\nfunc (s WriteEvent) Hash() uint64 ", "output": "{\n\treturn WriteEventHash(s.Addr, s.Value)\n}"} {"input": "package cli\n\nimport \"github.com/scaleway/scaleway-cli/pkg/commands\"\n\nvar cmdRm = &Command{\n\tExec: runRm,\n\tUsageLine: \"rm [OPTIONS] SERVER [SERVER...]\",\n\tDescription: \"Remove one or more servers\",\n\tHelp: \"Remove one or more servers.\",\n\tExamples: `\n $ scw rm myserver\n $ scw rm -f myserver\n $ scw rm my-stopped-server my-second-stopped-server\n $ scw rm $(scw ps -q)\n $ scw rm $(scw ps | grep mysql | awk '{print $1}')\n`,\n}\n\nfunc init() {\n\tcmdRm.Flag.BoolVar(&rmHelp, []string{\"h\", \"-help\"}, false, \"Print usage\")\n\tcmdRm.Flag.BoolVar(&rmForce, []string{\"f\", \"-force\"}, false, \"Force the removal of a server\")\n}\n\n\nvar rmHelp bool \nvar rmForce bool \n\n\n\nfunc runRm(cmd *Command, rawArgs []string) error ", "output": "{\n\tif rmHelp {\n\t\treturn cmd.PrintUsage()\n\t}\n\tif len(rawArgs) < 1 {\n\t\treturn cmd.PrintShortUsage()\n\t}\n\n\targs := commands.RmArgs{\n\t\tServers: rawArgs,\n\t\tForce: rmForce,\n\t}\n\tctx := cmd.GetContext(rawArgs)\n\treturn commands.RunRm(ctx, args)\n}"} {"input": "package srcobj\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype DrawChar string\n\n\n\n\nfunc (dc DrawChar) Dump(w io.Writer) error ", "output": "{\n\t_, err := fmt.Fprintf(w, `\"%s\"`, string(dc))\n\treturn err\n}"} {"input": "package gen\n\nimport (\n\t\"regexp\"\n\t\"strings\"\n)\n\nfunc ReplaceSearchCallback(code []byte, modelName string) []byte {\n\trSearchCallback, _ := regexp.Compile(\"SearchCallback\")\n\tresult := rSearchCallback.ReplaceAll(code, []byte(\"SearchCallback\"+strings.Title(modelName)))\n\n\treturn result\n}\n\n\nfunc RemovePackage(code []byte) []byte {\n\trPackage, _ := regexp.Compile(\"package collection\")\n\tresult := rPackage.ReplaceAll(code, make([]byte, 0))\n\n\treturn result\n}\n\nfunc ReplaceGrizzlyId(code []byte, customType string) []byte {\n\tgICollections, _ := regexp.Compile(\"GrizzlyId\")\n\tresult := gICollections.ReplaceAll(code, []byte(strings.Title(customType)))\n\n\treturn result\n}\n\n\n\nfunc InjectImports(code []byte, imports []string) (result []byte) {\n\tresult = code[:]\n\n\tfor _, i := range imports {\n\t\tresult = append([]byte(\"\\nimport \\\"\"+i+\"\\\"\\n\"), code...)\n\t}\n\n\treturn result\n}\n\nfunc ReplaceImports(code []byte) []byte ", "output": "{\n\trICollections, _ := regexp.Compile(\"(import \\\"sort\\\")\")\n\tresult := rICollections.ReplaceAll(code, []byte(\"\"))\n\n\treturn result\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/jackytck/projecteuler/tools\"\n)\n\n\n\nfunc isSumOfTwoAbundant(n int, a []bool) bool {\n\tvar ret bool\n\tfor i := 1; i < n; i++ {\n\t\tif a[i] && a[n-i] {\n\t\t\tret = true\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ret\n}\n\nfunc solve() int {\n\tvar sum int\n\tab := make([]bool, 28124)\n\tfor i := 12; i <= 28123; i++ {\n\t\tab[i] = isAbundant(i)\n\t}\n\tfor i := 1; i <= 28123; i++ {\n\t\tif !isSumOfTwoAbundant(i, ab) {\n\t\t\tsum += i\n\t\t}\n\t}\n\treturn sum\n}\n\nfunc main() {\n\tfmt.Println(solve())\n}\n\nfunc isAbundant(n int) bool ", "output": "{\n\treturn tools.SumDivisors(n) > n\n}"} {"input": "package middleware\n\nimport (\n\t\"github.com/drone/drone/shared/model\"\n\t\"github.com/zenazn/goji/web\"\n)\n\n\n\nfunc UserToC(c *web.C, user *model.User) {\n\tc.Env[\"user\"] = user\n}\n\n\n\n\n\n\n\nfunc RoleToC(c *web.C, role *model.Perm) {\n\tc.Env[\"role\"] = role\n}\n\n\n\n\nfunc ToUser(c *web.C) *model.User {\n\tvar v = c.Env[\"user\"]\n\tif v == nil {\n\t\treturn nil\n\t}\n\tu, ok := v.(*model.User)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn u\n}\n\n\n\n\nfunc ToRepo(c *web.C) *model.Repo {\n\tvar v = c.Env[\"repo\"]\n\tif v == nil {\n\t\treturn nil\n\t}\n\tr, ok := v.(*model.Repo)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn r\n}\n\n\n\n\nfunc ToRole(c *web.C) *model.Perm {\n\tvar v = c.Env[\"role\"]\n\tif v == nil {\n\t\treturn nil\n\t}\n\tp, ok := v.(*model.Perm)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn p\n}\n\nfunc RepoToC(c *web.C, repo *model.Repo) ", "output": "{\n\tc.Env[\"repo\"] = repo\n}"} {"input": "package ast\n\nimport \"monkey/token\"\n\ntype StringLiteral struct {\n\tToken token.Token\n\tValue string\n}\n\nfunc (s *StringLiteral) expressionNode() {}\nfunc (s *StringLiteral) TokenLiteral() string { return s.Token.Literal }\nfunc (s *StringLiteral) String() string { return s.Token.Literal }\n\ntype InterpolatedString struct {\n\tToken token.Token\n\tValue string\n\tExprMap map[byte]Expression\n}\n\nfunc (is *InterpolatedString) expressionNode() {}\n\nfunc (is *InterpolatedString) String() string { return is.Token.Literal }\n\nfunc (is *InterpolatedString) TokenLiteral() string ", "output": "{ return is.Token.Literal }"} {"input": "package handlers\n\nimport (\n\t\"github.com/bbiskup/edify-web/defs\"\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n)\n\nvar indexTemplates *template.Template\n\nfunc init() {\n\tindexTemplates = template.Must(template.ParseFiles(\n\t\tdefs.TemplatePaths(\"layout.html\", \"navbar.html\", \"index.html\")...,\n\t))\n}\n\n\n\nfunc Index(w http.ResponseWriter, r *http.Request) ", "output": "{\n\terr := indexTemplates.ExecuteTemplate(w, \"layout\", nil)\n\tif err != nil {\n\t\tlog.Printf(\"Error executing template: %s\", err)\n\t}\n}"} {"input": "package tristate\n\ntype StateValue int\n\nconst (\n\tTRISTATE_SUCCESS StateValue = iota\n\tTRISTATE_FAILRUE\n\tTRISTATE_UNKNOWN\n)\n\ntype TriState struct {\n\tState StateValue\n\tErr error\n}\n\nfunc NewSuccess() *TriState {\n\treturn nil\n}\n\nfunc NewUnknown(err error) *TriState {\n\tif err == nil {\n\t\tpanic(\"error not set\")\n\t}\n\treturn &TriState{TRISTATE_UNKNOWN, err}\n}\n\nfunc NewFailure(err error) *TriState {\n\tif err == nil {\n\t\tpanic(\"error not set\")\n\t}\n\treturn &TriState{TRISTATE_FAILRUE, err}\n}\n\nfunc (state *TriState) Error() string {\n\treturn state.Err.Error()\n}\n\n\n\nfunc (state *TriState) IsFailure() bool {\n\treturn state != nil && state.State == TRISTATE_FAILRUE\n}\n\nfunc (state *TriState) IsUnknown() bool {\n\treturn state != nil && state.State == TRISTATE_UNKNOWN\n}\n\nfunc (state *TriState) IsSuccess() bool ", "output": "{\n\treturn state == nil || state.State == TRISTATE_SUCCESS\n}"} {"input": "package v1beta2\n\nimport (\n\tv1beta2 \"github.com/enmasseproject/enmasse/pkg/apis/admin/v1beta2\"\n\t\"github.com/enmasseproject/enmasse/pkg/client/clientset/versioned/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype AdminV1beta2Interface interface {\n\tRESTClient() rest.Interface\n\tAddressPlansGetter\n\tAddressSpacePlansGetter\n}\n\n\ntype AdminV1beta2Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *AdminV1beta2Client) AddressPlans(namespace string) AddressPlanInterface {\n\treturn newAddressPlans(c, namespace)\n}\n\nfunc (c *AdminV1beta2Client) AddressSpacePlans(namespace string) AddressSpacePlanInterface {\n\treturn newAddressSpacePlans(c, namespace)\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *AdminV1beta2Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *AdminV1beta2Client {\n\treturn &AdminV1beta2Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta2.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *AdminV1beta2Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfig(c *rest.Config) (*AdminV1beta2Client, error) ", "output": "{\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AdminV1beta2Client{client}, nil\n}"} {"input": "package http\n\nimport (\n\t\"go-common/app/admin/main/app/model/language\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\n\nfunc languages(c *bm.Context) {\n\tc.JSON(langSvc.Languages(c))\n}\n\n\n\n\n\nfunc addOrup(c *bm.Context) {\n\tvar (\n\t\terr error\n\t\tv = &language.Param{}\n\t)\n\tif err = c.Bind(v); err != nil {\n\t\treturn\n\t}\n\tif v.ID > 0 {\n\t\terr = langSvc.Update(c, v)\n\t} else {\n\t\terr = langSvc.Insert(c, v)\n\t}\n\tc.JSON(nil, err)\n}\n\nfunc langByID(c *bm.Context) ", "output": "{\n\tv := &language.Param{}\n\tif err := c.Bind(v); err != nil {\n\t\treturn\n\t}\n\tc.JSON(langSvc.LangByID(c, v.ID))\n}"} {"input": "package log\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestLogFile(t *testing.T) {\n\tfileLogWrite := NewFileWriter()\n\trequire.NotNil(t, fileLogWrite)\n\n\tt.Cleanup(func() {\n\t\terr := fileLogWrite.Close()\n\t\tassert.NoError(t, err)\n\t\terr = os.Remove(fileLogWrite.Filename)\n\t\tassert.NoError(t, err)\n\t})\n\n\tfileLogWrite.Filename = \"grafana_test.log\"\n\terr := fileLogWrite.Init()\n\trequire.NoError(t, err)\n\n\tassert.Zero(t, fileLogWrite.maxlinesCurlines)\n\n\tt.Run(\"adding lines\", func(t *testing.T) {\n\t\terr := fileLogWrite.WriteLine(\"test1\\n\")\n\t\trequire.NoError(t, err)\n\t\terr = fileLogWrite.WriteLine(\"test2\\n\")\n\t\trequire.NoError(t, err)\n\t\terr = fileLogWrite.WriteLine(\"test3\\n\")\n\t\trequire.NoError(t, err)\n\n\t\tassert.Equal(t, 3, fileLogWrite.maxlinesCurlines)\n\t})\n}\n\nfunc (w *FileLogWriter) WriteLine(line string) error ", "output": "{\n\t_, err := w.Write([]byte(line))\n\treturn err\n}"} {"input": "package udp\n\nimport (\n\t\"encoding/binary\"\n\t\"github.com/davyxu/cellnet/codec\"\n)\n\nconst (\n\tMTU = 1472 \n\tpacketLen = 2 \n\tMsgIDLen = 2 \n\n\tHeaderSize = MsgIDLen + MsgIDLen \n)\n\n\n\nfunc RecvPacket(pktData []byte) (msg interface{}, err error) ", "output": "{\n\n\tif len(pktData) < packetLen {\n\t\treturn nil, nil\n\t}\n\n\tdatasize := binary.LittleEndian.Uint16(pktData)\n\n\tif int(datasize) != len(pktData) || datasize > MTU {\n\t\treturn nil, nil\n\t}\n\n\tmsgid := binary.LittleEndian.Uint16(pktData[packetLen:])\n\n\tmsgData := pktData[HeaderSize:]\n\n\tmsg, _, err = codec.DecodeMessage(int(msgid), msgData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn\n}"} {"input": "package packer\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\n\nvar GitCommit string\n\n\nconst Version = \"0.5.3\"\n\n\n\n\nconst VersionPrerelease = \"dev\"\n\ntype versionCommand byte\n\nfunc (versionCommand) Help() string {\n\treturn `usage: packer version\n\nOutputs the version of Packer that is running. There are no additional\ncommand-line flags for this command.`\n}\n\nfunc (versionCommand) Run(env Environment, args []string) int {\n\tenv.Ui().Machine(\"version\", Version)\n\tenv.Ui().Machine(\"version-prelease\", VersionPrerelease)\n\tenv.Ui().Machine(\"version-commit\", GitCommit)\n\n\tenv.Ui().Say(VersionString())\n\treturn 0\n}\n\nfunc (versionCommand) Synopsis() string {\n\treturn \"print Packer version\"\n}\n\n\n\n\n\n\nfunc VersionString() string ", "output": "{\n\tvar versionString bytes.Buffer\n\tfmt.Fprintf(&versionString, \"Packer v%s\", Version)\n\tif VersionPrerelease != \"\" {\n\t\tfmt.Fprintf(&versionString, \".%s\", VersionPrerelease)\n\n\t\tif GitCommit != \"\" {\n\t\t\tfmt.Fprintf(&versionString, \" (%s)\", GitCommit)\n\t\t}\n\t}\n\n\treturn versionString.String()\n}"} {"input": "package learn\n\nimport (\n\t\"fmt\"\n)\n\ntype List struct {\n\tData interface{}\n\tNextnode *List\n}\n\nfunc myPrint(t interface{}) {\n\tfmt.Println(t)\n}\n\n\nfunc (l *List) ListLength() int {\n\tvar i int = 0\n\tn := l\n\tfor n.Nextnode != nil {\n\t\ti++\n\t\tn = n.Nextnode\n\t}\n\treturn i + 1\n}\n\n\nfunc (l *List) GetEle(i int) (ele interface{}) {\n\tif i < 0 || i > l.ListLength() {\n\t\treturn nil\n\t}\n\tcur := l\n\tj := 1\n\tfor cur.Nextnode != nil {\n\t\tif j == i {\n\t\t\treturn cur.Data\n\t\t}\n\t\tj++\n\t\tcur = cur.Nextnode\n\n\t}\n\tif cur != nil && j == i {\n\t\treturn cur.Data\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (l *List) ListDelete(i int) bool {\n\tp := l\n\tj := 1\n\tfor j < i && p != nil {\n\t\tj++\n\t\tp = p.Nextnode\n\t}\n\tif p == nil || j > i {\n\t\treturn false\n\t}\n\tp.Nextnode = p.Nextnode.Nextnode\n\treturn true\n}\n\n\nfunc (l *List) ListAll() (all string) {\n\tp := l\n\tfor p != nil {\n\t\tall += fmt.Sprintf(\"%v+\", p.Data)\n\t\tp = p.Nextnode\n\t}\n\treturn all\n}\n\nfunc (l *List) ListInsert(i int, ele interface{}) bool ", "output": "{\n\tvar s List \n\tif i < 0 || i > l.ListLength() {\n\t\treturn false\n\t}\n\ts.Data = ele\n\tp := l\n\tj := 1\n\tfor j < i && p != nil {\n\t\tj++\n\t\tp = p.Nextnode\n\t}\n\tif p != nil && j <= i {\n\t\ts.Nextnode = p.Nextnode\n\t\tp.Nextnode = &s\n\t} else {\n\t\treturn false\n\t}\n\n\treturn true\n}"} {"input": "package vhosts\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n\t\"sync\"\n)\n\ntype VirtualHosts struct {\n\tvhosts map[string]http.Handler\n\tmu sync.RWMutex\n}\n\nfunc NewVirtualHosts(vhosts map[string]http.Handler) *VirtualHosts {\n\tv := &VirtualHosts{}\n\tfor hosts, h := range vhosts {\n\t\tfor _, host := range strings.Split(hosts, \" \") {\n\t\t\tif host != \"\" {\n\t\t\t\tv.HandleHost(h, host)\n\t\t\t}\n\t\t}\n\t}\n\treturn v\n}\n\n\n\nfunc (v *VirtualHosts) HandleHost(handler http.Handler, hosts ...string) {\n\tv.mu.Lock()\n\tdefer v.mu.Unlock()\n\tif v.vhosts == nil {\n\t\tv.vhosts = make(map[string]http.Handler)\n\t}\n\tfor _, host := range hosts {\n\t\tfor _, h := range strings.Split(host, \" \") {\n\t\t\tif h = strings.TrimSpace(h); h != \"\" {\n\t\t\t\tv.vhosts[h] = handler\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (v *VirtualHosts) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tv.mu.RLock()\n\tdefer v.mu.RUnlock()\n\tif v.vhosts != nil {\n\t\tif handler, ok := v.vhosts[r.Host]; ok && handler != nil {\n\t\t\thandler.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t}\n\thttp.NotFound(w, r)\n}"} {"input": "package bytealg\n\nconst MaxBruteForce = 0\n\n\n\nfunc Index(a, b []byte) int {\n\tpanic(\"unimplemented\")\n}\n\n\n\n\n\n\n\n\n\nfunc Cutover(n int) int {\n\tpanic(\"unimplemented\")\n}\n\nfunc IndexString(s, substr string) int ", "output": "{\n\tn := len(substr)\n\tc0 := substr[0]\n\tc1 := substr[1]\n\ti := 0\n\tt := len(s) - n + 1\n\tfails := 0\n\tfor i < t {\n\t\tif s[i] != c0 {\n\t\t\to := IndexByteString(s[i:t], c0)\n\t\t\tif o < 0 {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\ti += o\n\t\t}\n\t\tif s[i+1] == c1 && s[i:i+n] == substr {\n\t\t\treturn i\n\t\t}\n\t\ti++\n\t\tfails++\n\t\tif fails >= 4+i>>4 && i < t {\n\t\t\tj := IndexRabinKarp(s[i:], substr)\n\t\t\tif j < 0 {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\treturn i + j\n\t\t}\n\t}\n\treturn -1\n}"} {"input": "package util\n\nimport (\n\t\"strings\"\n\n\t\"github.com/spf13/viper\"\n)\n\n\nconst EnvPrefix = \"GSD\" \n\n\n\n\n\nfunc InitViper(v *viper.Viper, subViperName string) {\n\tv.SetEnvKeyReplacer(strings.NewReplacer(\"-\", \"_\"))\n\tif subViperName != \"\" {\n\t\tv.SetEnvPrefix(EnvPrefix + \"_\" + strings.ToUpper(subViperName))\n\t} else {\n\t\tv.SetEnvPrefix(EnvPrefix)\n\t}\n\tv.SetTypeByDefaultValue(true)\n\tv.AutomaticEnv()\n}\n\nfunc GetSubViper(v *viper.Viper, key string) *viper.Viper ", "output": "{\n\tn := v.Sub(key)\n\tif n == nil {\n\t\tn = viper.New()\n\t}\n\tInitViper(n, key)\n\treturn n\n}"} {"input": "package blobstoredbstatesnapshotio\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/nyaxt/otaru/metadata\"\n)\n\nfunc generateBlobpath() string {\n\treturn fmt.Sprintf(\"%s_SimpleSSLocator\", metadata.INodeDBSnapshotBlobpathPrefix)\n}\n\nvar simplesslocatorTxID int64\n\ntype SimpleSSLocator struct{}\n\nfunc (SimpleSSLocator) Locate(history int) (string, int64, error) {\n\treturn generateBlobpath(), simplesslocatorTxID, nil\n}\n\n\n\nfunc (SimpleSSLocator) Put(blobpath string, txid int64) error {\n\tsimplesslocatorTxID = txid\n\treturn nil\n}\n\nfunc (SimpleSSLocator) DeleteOld(ctx context.Context, threshold int, dryRun bool) ([]string, error) {\n\treturn []string{}, nil\n}\n\nfunc (SimpleSSLocator) GenerateBlobpath() string ", "output": "{\n\treturn generateBlobpath()\n}"} {"input": "package cli\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/alexyer/ghost/client\"\n)\n\n\n\nfunc ObtainClient(host string, port int) (*client.GhostClient, error) {\n\taddr := fmt.Sprintf(\"%s:%d\", host, port)\n\treturn connect(addr, \"tcp\")\n}\n\n\n\n\nfunc connect(addr, network string) (*client.GhostClient, error) {\n\tc := client.New(&client.Options{\n\t\tAddr: addr,\n\t\tNetwork: network,\n\t})\n\n\tif _, err := c.Ping(); err != nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"cli-ghost: cannot obtain connection to %s\", addr))\n\t}\n\n\tlog.Printf(\"Connection to %s is successfull.\", addr)\n\treturn c, nil\n}\n\nfunc ObtainUnixSocketClient(socket string) (*client.GhostClient, error) ", "output": "{\n\treturn connect(socket, \"unix\")\n}"} {"input": "package test\n\nimport \"github.com/tidepool-org/platform/test\"\n\n\n\nfunc NewAccessToken() string {\n\treturn test.RandomStringFromRangeAndCharset(256, 256, test.CharsetAlphaNumeric)\n}\n\nfunc NewSessionToken() string {\n\treturn test.RandomStringFromRangeAndCharset(256, 256, test.CharsetAlphaNumeric)\n}\n\nfunc NewRestrictedToken() string {\n\treturn test.RandomStringFromRangeAndCharset(40, 40, test.CharsetAlphaNumeric)\n}\n\nfunc NewServiceSecret() string ", "output": "{\n\treturn test.RandomStringFromRangeAndCharset(128, 128, test.CharsetAlphaNumeric)\n}"} {"input": "package account\n\nimport (\n\t\"flag\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n)\n\ntype update struct {\n\t*AccountFlag\n}\n\nfunc init() {\n\tcli.Register(\"host.account.update\", &update{})\n}\n\n\n\nfunc (cmd *update) Process(ctx context.Context) error {\n\tif err := cmd.AccountFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (cmd *update) Run(ctx context.Context, f *flag.FlagSet) error {\n\tm, err := cmd.AccountFlag.HostAccountManager(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn m.Update(ctx, &cmd.HostAccountSpec)\n}\n\nfunc (cmd *update) Register(ctx context.Context, f *flag.FlagSet) ", "output": "{\n\tcmd.AccountFlag, ctx = newAccountFlag(ctx)\n\tcmd.AccountFlag.Register(ctx, f)\n}"} {"input": "package byteorder\n\nimport (\n\t\"encoding/binary\"\n\t\"net\"\n\t\"testing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\ntype ByteorderSuite struct{}\n\nvar _ = Suite(&ByteorderSuite{})\n\n\n\nfunc (b *ByteorderSuite) TestHostToNetwork(c *C) {\n\tswitch Native {\n\tcase binary.LittleEndian:\n\t\tc.Assert(HostToNetwork16(0xAABB), Equals, uint16(0xBBAA))\n\t\tc.Assert(HostToNetwork32(0xAABBCCDD), Equals, uint32(0xDDCCBBAA))\n\tcase binary.BigEndian:\n\t\tc.Assert(HostToNetwork16(0xAABB), Equals, uint16(0xAABB))\n\t\tc.Assert(HostToNetwork32(0xAABBCCDD), Equals, uint32(0xAABBCCDD))\n\t}\n}\n\nfunc (b *ByteorderSuite) TestNetIPv4ToHost32(c *C) {\n\tswitch Native {\n\tcase binary.LittleEndian:\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.129.91\")), Equals, uint32(0x5b810b0a))\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.138.214\")), Equals, uint32(0xd68a0b0a))\n\tcase binary.BigEndian:\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.129.91\")), Equals, uint32(0x0a0b815b))\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.138.214\")), Equals, uint32(0x0a0b8ad6))\n\t}\n}\n\nfunc (b *ByteorderSuite) TestNativeIsInitialized(c *C) ", "output": "{\n\tc.Assert(Native, NotNil)\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype UpdateDedicatedVmHostRequest struct {\n\n\tDedicatedVmHostId *string `mandatory:\"true\" contributesTo:\"path\" name:\"dedicatedVmHostId\"`\n\n\tUpdateDedicatedVmHostDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateDedicatedVmHostRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request UpdateDedicatedVmHostRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request UpdateDedicatedVmHostRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateDedicatedVmHostResponse struct {\n\n\tRawResponse *http.Response\n\n\tDedicatedVmHost `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response UpdateDedicatedVmHostResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response UpdateDedicatedVmHostResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package throttler\n\nimport (\n\t\"vitess.io/vitess/go/sync2\"\n)\n\n\n\ntype MaxRateModule struct {\n\tmaxRate sync2.AtomicInt64\n\trateUpdateChan chan<- struct{}\n}\n\n\n\nfunc NewMaxRateModule(maxRate int64) *MaxRateModule {\n\treturn &MaxRateModule{\n\t\tmaxRate: sync2.NewAtomicInt64(maxRate),\n\t}\n}\n\n\nfunc (m *MaxRateModule) Start(rateUpdateChan chan<- struct{}) {\n\tm.rateUpdateChan = rateUpdateChan\n}\n\n\nfunc (m *MaxRateModule) Stop() {}\n\n\n\n\n\n\nfunc (m *MaxRateModule) SetMaxRate(rate int64) {\n\tm.maxRate.Set(rate)\n\tm.rateUpdateChan <- struct{}{}\n}\n\nfunc (m *MaxRateModule) MaxRate() int64 ", "output": "{\n\treturn m.maxRate.Get()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/go-redis/redis\"\n\t\"github.com/jasonlvhit/gocron\"\n)\n\n\n\n\n\n\ntype locker struct {\n\tcache *redis.Client\n}\n\nfunc (s *locker) Lock(key string) (success bool, err error) {\n\tres, err := s.cache.SetNX(key, time.Now().String(), time.Second*15).Result()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn res, nil\n}\n\nfunc (s *locker) Unlock(key string) error {\n\treturn s.cache.Del(key).Err()\n}\n\n\n\nfunc main() {\n\tl := &locker{\n\t\tredis.NewClient(&redis.Options{\n\t\t\tAddr: \"localhost:6379\",\n\t\t}),\n\t}\n\n\tgocron.SetLocker(l)\n\n\targ := \"Some Name\"\n\targs := os.Args[1:]\n\tif len(args) > 0 {\n\t\targ = args[0]\n\t}\n\n\tgocron.Every(1).Second().Lock().Do(lockedTask, arg)\n\t<-gocron.Start()\n}\n\nfunc lockedTask(name string) ", "output": "{\n\tfmt.Printf(\"Hello, %s!\\n\", name)\n\n\tt := time.NewTicker(time.Millisecond * 100)\n\tc := make(chan struct{})\n\ttime.AfterFunc(time.Second*5, func() {\n\t\tclose(c)\n\t})\n\n\tfor {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tfmt.Print(\".\")\n\t\tcase <-c:\n\t\t\tfmt.Println()\n\t\t\treturn\n\t\t}\n\t}\n}"} {"input": "package identity\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListTaggingWorkRequestErrorsRequest struct {\n\n\tWorkRequestId *string `mandatory:\"true\" contributesTo:\"path\" name:\"workRequestId\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListTaggingWorkRequestErrorsRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListTaggingWorkRequestErrorsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ListTaggingWorkRequestErrorsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ListTaggingWorkRequestErrorsRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListTaggingWorkRequestErrorsResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []TaggingWorkRequestErrorSummary `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n\n\tRetryAfter *float32 `presentIn:\"header\" name:\"retry-after\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n}\n\n\n\n\nfunc (response ListTaggingWorkRequestErrorsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response ListTaggingWorkRequestErrorsResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package main\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n\nfunc ParseForCommands(line string) string {\n\tswitch line {\n\tcase \":g\":\n\t\tSelectGuild()\n\t\tline = \"\"\n\tcase \":c\":\n\t\tSelectChannel()\n\t\tline = \"\"\n\tdefault:\n\t}\n\n\tif strings.HasPrefix(line, \":m\") {\n\t\tAmountStr := strings.Split(line, \" \")\n\t\tif len(AmountStr) < 2 {\n\t\t\tMsg(ErrorMsg, \"[:m] No Arguments \\n\")\n\t\t\treturn \"\"\n\t\t}\n\n\t\tAmount, err := strconv.Atoi(AmountStr[1])\n\t\tif err != nil {\n\t\t\tMsg(ErrorMsg, \"[:m] Argument Error: %s \\n\", err)\n\t\t\treturn \"\"\n\t\t}\n\n\t\tMsg(InfoMsg, \"Printing last %d messages!\\n\", Amount)\n\t\tState.RetrieveMessages(Amount)\n\t\tPrintMessages(Amount)\n\t\tline = \"\"\n\t}\n\n\treturn line\n}\n\n\nfunc SelectGuild() {\n\tState.Enabled = false\n\tSelectGuildMenu()\n\tSelectChannelMenu()\n\tState.Enabled = true\n\tShowContent()\n}\n\n\n\n\nfunc SelectChannel() ", "output": "{\n\tState.Enabled = false\n\tSelectChannelMenu()\n\tState.Enabled = true\n\tShowContent()\n}"} {"input": "package backoff\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\n\ntype BackOffContext interface {\n\tBackOff\n\tContext() context.Context\n}\n\ntype backOffContext struct {\n\tBackOff\n\tctx context.Context\n}\n\n\n\n\nfunc WithContext(b BackOff, ctx context.Context) BackOffContext {\n\tif ctx == nil {\n\t\tpanic(\"nil context\")\n\t}\n\n\tif b, ok := b.(*backOffContext); ok {\n\t\treturn &backOffContext{\n\t\t\tBackOff: b.BackOff,\n\t\t\tctx: ctx,\n\t\t}\n\t}\n\n\treturn &backOffContext{\n\t\tBackOff: b,\n\t\tctx: ctx,\n\t}\n}\n\n\n\nfunc (b *backOffContext) Context() context.Context {\n\treturn b.ctx\n}\n\nfunc (b *backOffContext) NextBackOff() time.Duration {\n\tselect {\n\tcase <-b.ctx.Done():\n\t\treturn Stop\n\tdefault:\n\t}\n\tnext := b.BackOff.NextBackOff()\n\tif deadline, ok := b.ctx.Deadline(); ok && deadline.Sub(time.Now()) < next {\n\t\treturn Stop\n\t}\n\treturn next\n}\n\nfunc ensureContext(b BackOff) BackOffContext ", "output": "{\n\tif cb, ok := b.(BackOffContext); ok {\n\t\treturn cb\n\t}\n\treturn WithContext(b, context.Background())\n}"} {"input": "package state\n\nimport (\n\t\"net/url\"\n\n\t\"gopkg.in/juju/charm.v3\"\n)\n\n\ntype charmDoc struct {\n\tURL *charm.URL `bson:\"_id\"`\n\tMeta *charm.Meta\n\tConfig *charm.Config\n\tActions *charm.Actions\n\tBundleURL *url.URL\n\tBundleSha256 string\n\tPendingUpload bool\n\tPlaceholder bool\n}\n\n\ntype Charm struct {\n\tst *State\n\tdoc charmDoc\n}\n\nfunc newCharm(st *State, cdoc *charmDoc) (*Charm, error) {\n\treturn &Charm{st: st, doc: *cdoc}, nil\n}\n\nfunc (c *Charm) String() string {\n\treturn c.doc.URL.String()\n}\n\n\n\n\n\n\nfunc (c *Charm) Revision() int {\n\treturn c.doc.URL.Revision\n}\n\n\nfunc (c *Charm) Meta() *charm.Meta {\n\treturn c.doc.Meta\n}\n\n\nfunc (c *Charm) Config() *charm.Config {\n\treturn c.doc.Config\n}\n\n\nfunc (c *Charm) Actions() *charm.Actions {\n\treturn c.doc.Actions\n}\n\n\n\nfunc (c *Charm) BundleURL() *url.URL {\n\treturn c.doc.BundleURL\n}\n\n\nfunc (c *Charm) BundleSha256() string {\n\treturn c.doc.BundleSha256\n}\n\n\n\nfunc (c *Charm) IsUploaded() bool {\n\treturn !c.doc.PendingUpload\n}\n\n\n\nfunc (c *Charm) IsPlaceholder() bool {\n\treturn c.doc.Placeholder\n}\n\nfunc (c *Charm) URL() *charm.URL ", "output": "{\n\tclone := *c.doc.URL\n\treturn &clone\n}"} {"input": "package dax\n\n\ntype Grapher interface {\n\tGetParent() Grapher\n\tAddChild(child Grapher)\n\tGetChildren() []Grapher\n}\n\ntype nodeStack struct {\n\tnodes []Grapher\n}\n\nfunc (s *nodeStack) Init() {\n\ts.nodes = make([]Grapher, 0, 16)\n}\n\nfunc (s *nodeStack) Empty() bool {\n\treturn len(s.nodes) == 0\n}\n\nfunc (s *nodeStack) Push(n Grapher) {\n\ts.nodes = append(s.nodes, n)\n}\n\nfunc (s *nodeStack) Pop() Grapher {\n\ti := len(s.nodes) - 1\n\tn := s.nodes[i]\n\ts.nodes[i] = nil\n\ts.nodes = s.nodes[:i]\n\treturn n\n}\n\ntype SceneGraph struct {\n\tNode\n}\n\nfunc NewSceneGraph() *SceneGraph {\n\tsg := new(SceneGraph)\n\tsg.Init()\n\treturn sg\n}\n\nfunc (sg *SceneGraph) Init() {\n\tsg.Node.Init()\n}\n\nfunc (sg *SceneGraph) updateWorldTransform() {\n\tsg.Node.updateWorldTransform(false)\n}\n\n\n\n\nfunc (sg *SceneGraph) Traverse() <-chan Grapher {\n\tch := make(chan Grapher)\n\n\tgo func() {\n\t\tvar stack nodeStack\n\n\t\tstack.Init()\n\t\tstack.Push(sg)\n\n\t\tfor !stack.Empty() {\n\t\t\tn := stack.Pop()\n\t\t\tch <- n\n\t\t\tchildren := n.GetChildren()\n\t\t\tfor i := len(children) - 1; i >= 0; i-- {\n\t\t\t\tstack.Push(children[i])\n\t\t\t}\n\t\t}\n\t\tclose(ch)\n\t}()\n\n\treturn ch\n}\n\nfunc (sg *SceneGraph) Draw(fb Framebuffer) {\n\tfb.render().drawSceneGraph(fb, sg)\n}\n\nfunc (sg *SceneGraph) Update(time float64) ", "output": "{\n\tsg.updateWorldTransform()\n}"} {"input": "package internal\n\nimport G \"github.com/ionous/sashimi/game\"\n\n\ntype PendingChain struct {\n\tsrc *GameEventAdapter\n}\n\n\n\nfunc (c PendingChain) Then(cb G.Callback) {\n\tif c.src != nil {\n\t\tchain := ChainedCallback{c.src.data, cb}\n\t\tchain.Run(c.src.Game)\n\t}\n}\n\nfunc NewPendingChain(src *GameEventAdapter, _ Future) PendingChain ", "output": "{\n\treturn PendingChain{src}\n}"} {"input": "package query\n\n\n\nfunc shouldEscape(c byte) bool {\n\tif 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' {\n\t\treturn false\n\t}\n\n\tswitch c {\n\tcase '-', '_', '.', '~': \n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc Escape(s string) string ", "output": "{\n\thexCount := 0\n\tfor i := 0; i < len(s); i++ {\n\t\tc := s[i]\n\t\tif shouldEscape(c) {\n\t\t\thexCount++\n\t\t}\n\t}\n\n\tif hexCount == 0 {\n\t\treturn s\n\t}\n\n\tt := make([]byte, len(s)+2*hexCount)\n\tj := 0\n\tfor i := 0; i < len(s); i++ {\n\t\tswitch c := s[i]; {\n\t\tcase shouldEscape(c):\n\t\t\tt[j] = '%'\n\t\t\tt[j+1] = \"0123456789ABCDEF\"[c>>4]\n\t\t\tt[j+2] = \"0123456789ABCDEF\"[c&15]\n\t\t\tj += 3\n\t\tdefault:\n\t\t\tt[j] = s[i]\n\t\t\tj++\n\t\t}\n\t}\n\treturn string(t)\n}"} {"input": "package protobuf\n\nimport \"github.com/m3db/m3x/pool\"\n\nconst (\n\tdefaultInitBufferSize = 2880\n\n\tdefaultMaxUnaggregatedMessageSize = 50 * 1024 * 1024\n)\n\n\ntype UnaggregatedOptions interface {\n\tSetBytesPool(value pool.BytesPool) UnaggregatedOptions\n\n\tBytesPool() pool.BytesPool\n\n\tSetInitBufferSize(value int) UnaggregatedOptions\n\n\tInitBufferSize() int\n\n\tSetMaxMessageSize(value int) UnaggregatedOptions\n\n\tMaxMessageSize() int\n}\n\ntype unaggregatedOptions struct {\n\tbytesPool pool.BytesPool\n\tinitBufferSize int\n\tmaxMessageSize int\n}\n\n\nfunc NewUnaggregatedOptions() UnaggregatedOptions {\n\tp := pool.NewBytesPool(nil, nil)\n\tp.Init()\n\treturn &unaggregatedOptions{\n\t\tbytesPool: p,\n\t\tinitBufferSize: defaultInitBufferSize,\n\t\tmaxMessageSize: defaultMaxUnaggregatedMessageSize,\n\t}\n}\n\nfunc (o *unaggregatedOptions) SetBytesPool(value pool.BytesPool) UnaggregatedOptions {\n\topts := *o\n\topts.bytesPool = value\n\treturn &opts\n}\n\n\n\nfunc (o *unaggregatedOptions) SetInitBufferSize(value int) UnaggregatedOptions {\n\topts := *o\n\topts.initBufferSize = value\n\treturn &opts\n}\n\nfunc (o *unaggregatedOptions) InitBufferSize() int {\n\treturn o.initBufferSize\n}\n\nfunc (o *unaggregatedOptions) SetMaxMessageSize(value int) UnaggregatedOptions {\n\topts := *o\n\topts.maxMessageSize = value\n\treturn &opts\n}\n\nfunc (o *unaggregatedOptions) MaxMessageSize() int {\n\treturn o.maxMessageSize\n}\n\nfunc (o *unaggregatedOptions) BytesPool() pool.BytesPool ", "output": "{\n\treturn o.bytesPool\n}"} {"input": "package flags\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\n\n\ntype IniError struct {\n\tMessage string\n\n\tFile string\n\n\tLineNumber uint\n}\n\n\nfunc (x *IniError) Error() string {\n\treturn fmt.Sprintf(\"%s:%d: %s\",\n\t\tx.File,\n\t\tx.LineNumber,\n\t\tx.Message)\n}\n\n\ntype IniOptions uint\n\nconst (\n\tIniNone IniOptions = 0\n\n\tIniIncludeDefaults = 1 << iota\n\n\tIniCommentDefaults\n\n\tIniIncludeComments\n\n\tIniDefault = IniIncludeComments\n)\n\n\n\ntype IniParser struct {\n\tparser *Parser\n}\n\n\nfunc NewIniParser(p *Parser) *IniParser {\n\treturn &IniParser{\n\t\tparser: p,\n\t}\n}\n\n\n\n\n\nfunc IniParse(filename string, data interface{}) error {\n\tp := NewParser(data, Default)\n\treturn NewIniParser(p).ParseFile(filename)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (i *IniParser) Parse(reader io.Reader) error {\n\ti.parser.storeDefaults()\n\n\tini, err := readIni(reader, \"\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn i.parse(ini)\n}\n\n\n\n\nfunc (i *IniParser) WriteFile(filename string, options IniOptions) error {\n\tfile, err := os.Create(filename)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer file.Close()\n\ti.Write(file, options)\n\n\treturn nil\n}\n\n\n\n\n\n\nfunc (i *IniParser) Write(writer io.Writer, options IniOptions) {\n\twriteIni(i, writer, options)\n}\n\nfunc (i *IniParser) ParseFile(filename string) error ", "output": "{\n\ti.parser.storeDefaults()\n\n\tini, err := readIniFromFile(filename)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn i.parse(ini)\n}"} {"input": "package global\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/propagation\"\n)\n\n\n\n\ntype textMapPropagator struct {\n\tmtx sync.Mutex\n\tonce sync.Once\n\tdelegate propagation.TextMapPropagator\n\tnoop propagation.TextMapPropagator\n}\n\n\n\nvar _ propagation.TextMapPropagator = (*textMapPropagator)(nil)\n\nfunc newTextMapPropagator() *textMapPropagator {\n\treturn &textMapPropagator{\n\t\tnoop: propagation.NewCompositeTextMapPropagator(),\n\t}\n}\n\n\n\n\nfunc (p *textMapPropagator) SetDelegate(delegate propagation.TextMapPropagator) {\n\tif delegate == nil {\n\t\treturn\n\t}\n\n\tp.mtx.Lock()\n\tp.once.Do(func() { p.delegate = delegate })\n\tp.mtx.Unlock()\n}\n\n\n\n\nfunc (p *textMapPropagator) effectiveDelegate() propagation.TextMapPropagator {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tif p.delegate != nil {\n\t\treturn p.delegate\n\t}\n\treturn p.noop\n}\n\n\nfunc (p *textMapPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) {\n\tp.effectiveDelegate().Inject(ctx, carrier)\n}\n\n\n\n\n\nfunc (p *textMapPropagator) Fields() []string {\n\treturn p.effectiveDelegate().Fields()\n}\n\nfunc (p *textMapPropagator) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context ", "output": "{\n\treturn p.effectiveDelegate().Extract(ctx, carrier)\n}"} {"input": "package main\n\nimport (\n\t\"net\"\n\t\"strconv\"\n)\n\nimport (\n\t\"cfg\"\n\t. \"helper\"\n\t\"misc/packet\"\n\t. \"types\"\n)\n\ntype Buffer struct {\n\tctrl chan bool \n\tpending chan []byte \n\tmax int \n\tconn net.Conn \n\tsess *Session \n}\n\n\n\nfunc (buf *Buffer) Send(data []byte) (err error) {\n\tdefer func() {\n\t\tif x := recover(); x != nil {\n\t\t\tWARN(\"buffer.Send failed\", x)\n\t\t}\n\t}()\n\n\tif buf.sess.Flag&SESS_ENCRYPT != 0 { \n\t\tbuf.sess.Encoder.Codec(data)\n\t} else if buf.sess.Flag&SESS_KEYEXCG != 0 { \n\t\tbuf.sess.Flag &= ^SESS_KEYEXCG\n\t\tbuf.sess.Flag |= SESS_ENCRYPT\n\t}\n\tbuf.pending <- data\n\treturn nil\n}\n\n\n\n\n\nfunc (buf *Buffer) raw_send(data []byte) {\n\twriter := packet.Writer()\n\twriter.WriteU16(uint16(len(data)))\n\twriter.WriteRawBytes(data)\n\n\tn, err := buf.conn.Write(writer.Data())\n\tif err != nil {\n\t\tERR(\"Error send reply, bytes:\", n, \"reason:\", err)\n\t\treturn\n\t}\n}\n\n\nfunc NewBuffer(sess *Session, conn net.Conn, ctrl chan bool) *Buffer {\n\tconfig := cfg.Get()\n\tmax, err := strconv.Atoi(config[\"outqueue_size\"])\n\tif err != nil {\n\t\tmax = DEFAULT_OUTQUEUE_SIZE\n\t\tWARN(\"cannot parse outqueue_size from config\", err, \"using default:\", max)\n\t}\n\n\tbuf := Buffer{conn: conn}\n\tbuf.sess = sess\n\tbuf.pending = make(chan []byte, max)\n\tbuf.ctrl = ctrl\n\tbuf.max = max\n\treturn &buf\n}\n\nfunc (buf *Buffer) Start() ", "output": "{\n\tdefer func() {\n\t\tif x := recover(); x != nil {\n\t\t\tERR(\"caught panic in buffer goroutine\", x)\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase data := <-buf.pending:\n\t\t\tbuf.raw_send(data)\n\t\tcase <-buf.ctrl: \n\t\t\tclose(buf.pending)\n\t\t\tfor data := range buf.pending {\n\t\t\t\tbuf.raw_send(data)\n\t\t\t}\n\t\t\tbuf.conn.Close()\n\t\t\treturn\n\t\t}\n\t}\n}"} {"input": "package dexcom\n\nimport (\n\t\"math\"\n)\n\n\n\n\n\n\nfunc marshalInt16(n int16) []byte {\n\treturn marshalUint16(uint16(n))\n}\n\nfunc marshalUint32(n uint32) []byte {\n\treturn append(marshalUint16(uint16(n&0xFFFF)), marshalUint16(uint16(n>>16))...)\n}\n\nfunc marshalInt32(n int32) []byte {\n\treturn marshalUint32(uint32(n))\n}\n\nfunc unmarshalUint16(v []byte) uint16 {\n\treturn uint16(v[0]) | uint16(v[1])<<8\n}\n\n\nfunc unmarshalInt16(v []byte) int16 {\n\treturn int16(unmarshalUint16(v))\n}\n\nfunc unmarshalUint32(v []byte) uint32 {\n\treturn uint32(unmarshalUint16(v[0:2])) | uint32(unmarshalUint16(v[2:4]))<<16\n}\n\nfunc unmarshalInt32(v []byte) int32 {\n\treturn int32(unmarshalUint32(v))\n}\n\nfunc unmarshalUint64(v []byte) uint64 {\n\treturn uint64(unmarshalUint32(v[0:4])) | uint64(unmarshalUint32(v[4:8]))<<32\n}\n\nfunc unmarshalFloat64(v []byte) float64 {\n\treturn math.Float64frombits(unmarshalUint64(v))\n}\n\nfunc marshalUint16(n uint16) []byte ", "output": "{\n\treturn []byte{byte(n & 0xFF), byte(n >> 8)}\n}"} {"input": "package fenwick\n\nimport \"testing\"\n\n\n\nfunc TestNewFenwickTree(t *testing.T) ", "output": "{\n\tf := []int{2,4,5,5,6,6,6,7,7,8,9}\n\tfw := NewFenwickTree(10)\n\tfor i := 0; i < 11; i++ {\n\t\tfw.adjust(f[i],1)\n\t}\n\n\tif fw.rsq(1,1) != 0 {\n\t\tt.Errorf(\"expect 0\")\n\t}\n\tif fw.rsq(1,2) != 1 {\n\t\tt.Errorf(\"expect 1\")\n\t}\n\tif fw.rsq(1,10) != 11 {\n\t\tt.Errorf(\"expect 11\")\n\t}\n\tif fw.rsq(3,6) != 6 {\n\t\tt.Errorf(\"expect 6\")\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"github.com/scionproto/scion/go/lib/ctrl/seg\"\n\t\"github.com/scionproto/scion/go/lib/scrypto/signed\"\n\t\"github.com/scionproto/scion/go/lib/serrors\"\n)\n\n\n\nfunc ExtractLastHopVersion(ps *seg.PathSegment) (int64, error) ", "output": "{\n\tases := ps.ASEntries\n\tif len(ases) == 0 {\n\t\treturn 0, serrors.New(\"segment without AS Entries\")\n\t}\n\tsign := ases[len(ases)-1].Signed\n\thdr, err := signed.ExtractUnverifiedHeader(sign)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn hdr.Timestamp.UnixNano(), nil\n}"} {"input": "package strings\n\nimport (\n\t\"strings\"\n)\n\n\nfunc RemoveSpace(s string) (d string) {\n\tif IsBlank(s) {\n\t\treturn\n\t}\n\td = s\n\tsps := [...]string{\"\\t\", \"\\n\", \"\\v\", \"\\f\", \"\\r\", \" \"}\n\tfor _, sp := range sps {\n\t\td = strings.Replace(d, sp, \"\", -1)\n\t}\n\treturn\n}\n\n\nfunc RemoveBlank(s string) (d string) {\n\tif IsBlank(s) {\n\t\treturn\n\t}\n\td = strings.TrimSpace(s)\n\tsps := [...]string{\"\\t\", \"\\n\", \"\\v\", \"\\f\", \"\\r\", \" \"}\n\tfor _, sp := range sps {\n\t\td = strings.Replace(d, sp, \"\", -1)\n\t}\n\treturn\n}\n\n\n\n\n\n\n\nfunc RemoveEnd(s, remove string) string {\n\tif IsBlank(s) || IsBlank(remove) {\n\t\treturn s\n\t}\n\tif strings.HasSuffix(s, remove) {\n\t\treturn s[0 : len(s)-len(remove)]\n\t}\n\treturn s\n}\n\n\nfunc Remove(s, remove string) string {\n\tif IsBlank(s) || IsBlank(remove) {\n\t\treturn s\n\t}\n\treturn strings.Replace(s, remove, \"\", -1)\n}\n\nfunc RemoveStart(s, remove string) string ", "output": "{\n\tif IsBlank(s) || IsBlank(remove) {\n\t\treturn s\n\t}\n\tif strings.HasPrefix(s, remove) {\n\t\treturn s[len(remove):]\n\t}\n\treturn s\n}"} {"input": "package db_models\n\nimport \"time\"\nimport \"github.com/go-xorm/xorm\"\n\ntype UriFilteringTelemetryPreMitigation struct {\n\tId int64 `xorm:\"'id' pk autoincr\"`\n\tCustomerId int `xorm:\"'customer_id' not null\"`\n\tCuid string `xorm:\"'cuid' not null\"`\n\tCdid string `xorm:\"'cdid'\"`\n\tTmid int `xorm:\"'tmid' not null\"`\n\tTargetPrefix string `xorm:\"target_prefix\"`\n\tLowerPort int `xorm:\"lower_port\"`\n\tUpperPort int `xorm:\"upper_port\"`\n\tTargetProtocol int `xorm:\"target_protocol\"`\n\tTargetFqdn string `xorm:\"target_fqdn\"`\n\tAliasName string `xorm:\"alias_name\"`\n\tCreated time.Time `xorm:\"created\"`\n\tUpdated time.Time `xorm:\"updated\"`\n}\n\n\n\n\n\nfunc GetUriFilteringTelemetryPreMitigationByCuid(engine *xorm.Engine, customerId int, cuid string) ([]UriFilteringTelemetryPreMitigation, error) {\n\ttelePreMitigation := []UriFilteringTelemetryPreMitigation{}\n\terr := engine.Where(\"customer_id = ? AND cuid = ?\", customerId, cuid).Find(&telePreMitigation)\n\treturn telePreMitigation, err\n}\n\n\nfunc DeleteUriFilteringTelemetryPreMitigationByTmid(session *xorm.Session, tmid int) (err error) {\n\t_, err = session.Delete(&UriFilteringTelemetryPreMitigation{Tmid: tmid})\n\treturn\n}\n\nfunc GetUriFilteringTelemetryPreMitigationByTmid(engine *xorm.Engine, customerId int, cuid string, tmid int) ([]UriFilteringTelemetryPreMitigation, error) ", "output": "{\n\ttelePreMitigation := []UriFilteringTelemetryPreMitigation{}\n\terr := engine.Where(\"customer_id = ? AND cuid = ? AND tmid = ?\", customerId, cuid, tmid).Find(&telePreMitigation)\n\treturn telePreMitigation, err\n}"} {"input": "package upside_down\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/blevesearch/bleve/index\"\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\ntype UpsideDownCouchFieldDict struct {\n\tindexReader *IndexReader\n\titerator store.KVIterator\n\tendKey []byte\n\tfield uint16\n}\n\nfunc newUpsideDownCouchFieldDict(indexReader *IndexReader, field uint16, startTerm, endTerm []byte) (*UpsideDownCouchFieldDict, error) {\n\n\tstartKey := NewDictionaryRow(startTerm, field, 0).Key()\n\tif endTerm == nil {\n\t\tendTerm = []byte{ByteSeparator}\n\t}\n\tendKey := NewDictionaryRow(endTerm, field, 0).Key()\n\n\tit := indexReader.kvreader.Iterator(startKey)\n\n\treturn &UpsideDownCouchFieldDict{\n\t\tindexReader: indexReader,\n\t\titerator: it,\n\t\tfield: field,\n\t\tendKey: endKey,\n\t}, nil\n\n}\n\nfunc (r *UpsideDownCouchFieldDict) Next() (*index.DictEntry, error) {\n\tkey, val, valid := r.iterator.Current()\n\tif !valid {\n\t\treturn nil, nil\n\t}\n\n\tif bytes.Compare(key, r.endKey) > 0 {\n\t\treturn nil, nil\n\t}\n\n\tcurrRow, err := NewDictionaryRowKV(key, val)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unexpected error parsing dictionary row kv: %v\", err)\n\t}\n\trv := index.DictEntry{\n\t\tTerm: string(currRow.term),\n\t\tCount: currRow.count,\n\t}\n\tr.iterator.Next()\n\treturn &rv, nil\n\n}\n\nfunc (r *UpsideDownCouchFieldDict) Close() error {\n\treturn r.iterator.Close()\n}\n\n\n\nfunc incrementBytes(in []byte) []byte ", "output": "{\n\trv := make([]byte, len(in))\n\tcopy(rv, in)\n\tfor i := len(rv) - 1; i >= 0; i-- {\n\t\trv[i] = rv[i] + 1\n\t\tif rv[i] != 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn rv\n}"} {"input": "package tc\n\n\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype CRStates struct {\n\tCaches map[CacheName]IsAvailable `json:\"caches\"`\n\tDeliveryService map[DeliveryServiceName]CRStatesDeliveryService `json:\"deliveryServices\"`\n}\n\n\ntype CRStatesDeliveryService struct {\n\tDisabledLocations []CacheGroupName `json:\"disabledLocations\"`\n\tIsAvailable bool `json:\"isAvailable\"`\n}\n\n\ntype IsAvailable struct {\n\tIsAvailable bool `json:\"isAvailable\"`\n}\n\n\nfunc NewCRStates() CRStates {\n\treturn CRStates{\n\t\tCaches: map[CacheName]IsAvailable{},\n\t\tDeliveryService: map[DeliveryServiceName]CRStatesDeliveryService{},\n\t}\n}\n\n\n\n\n\nfunc (a CRStates) CopyDeliveryServices() map[DeliveryServiceName]CRStatesDeliveryService {\n\tb := map[DeliveryServiceName]CRStatesDeliveryService{}\n\tfor k, v := range a.DeliveryService {\n\t\tb[k] = v\n\t}\n\treturn b\n}\n\n\nfunc (a CRStates) CopyCaches() map[CacheName]IsAvailable {\n\tb := map[CacheName]IsAvailable{}\n\tfor k, v := range a.Caches {\n\t\tb[k] = v\n\t}\n\treturn b\n}\n\n\nfunc CRStatesMarshall(states CRStates) ([]byte, error) {\n\treturn json.Marshal(states)\n}\n\n\nfunc CRStatesUnMarshall(body []byte) (CRStates, error) {\n\tvar crStates CRStates\n\terr := json.Unmarshal(body, &crStates)\n\treturn crStates, err\n}\n\nfunc (a CRStates) Copy() CRStates ", "output": "{\n\tb := NewCRStates()\n\tfor k, v := range a.Caches {\n\t\tb.Caches[k] = v\n\t}\n\tfor k, v := range a.DeliveryService {\n\t\tb.DeliveryService[k] = v\n\t}\n\treturn b\n}"} {"input": "package outbarriers\n\nimport (\n\t\"log\"\n\t\"time\"\n)\n\ntype User struct {\n\tId int64\n\tEmail string\n\tPassword string \n}\ntype Session struct {\n\tId int64\n\tUserId int64\n\tToken string `sql:\"unique; not null\"`\n\tCreatedAt time.Time\n}\n\nfunc (ctx *Context) AuthUser(email, password string) *User {\n\n\tvar user User\n\tctx.DB.Where(\"email = ? and password = ?\", email, password).First(&user)\n\treturn &user\n}\n\nfunc (ctx *Context) CheckAdmin() {\n\n\tvar user User\n\tctx.DB.Where(User{Email: ADMIN_EMAIL, Password: ADMIN_PASSWORD}).FirstOrInit(&user)\n\tif ctx.DB.NewRecord(user) {\n\t\tlog.Printf(\"Admin user not exists, creating...\")\n\t\tctx.DB.Create(&user)\n\t}\n}\n\n\n\nfunc (ctx *Context) GetSessionByToken(token string) *Session {\n\n\tvar session Session\n\tctx.DB.Where(\"token = ?\", token).First(&session)\n\tif session.Id == 0 {\n\t\treturn nil\n\t}\n\treturn &session\n}\n\nfunc (ctx *Context) LoginUser(user *User) string ", "output": "{\n\n\ttoken := RandomString(64)\n\tsession := &Session{UserId: user.Id, Token: token, CreatedAt: time.Now()}\n\tctx.DB.Create(session)\n\treturn token\n}"} {"input": "package utils\n\nimport \"time\"\n\n\nfunc GetUnixEpochFrom(now time.Time) int64 {\n\treturn now.UnixNano()\n}\n\n\n\n\n\nfunc GetUnixEpoch() int64 ", "output": "{\n\treturn GetUnixEpochFrom(time.Now())\n}"} {"input": "package config\n\nimport (\n\tcb \"github.com/hyperledger/fabric/protos/common\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n\t\"github.com/hyperledger/fabric/protos/utils\"\n)\n\nfunc ordererConfigGroup(key string, value []byte) *cb.ConfigGroup {\n\tresult := cb.NewConfigGroup()\n\tresult.Groups[OrdererGroupKey] = cb.NewConfigGroup()\n\tresult.Groups[OrdererGroupKey].Values[key] = &cb.ConfigValue{\n\t\tValue: value,\n\t}\n\treturn result\n}\n\n\nfunc TemplateConsensusType(typeValue string) *cb.ConfigGroup {\n\treturn ordererConfigGroup(ConsensusTypeKey, utils.MarshalOrPanic(&ab.ConsensusType{Type: typeValue}))\n}\n\n\nfunc TemplateBatchSize(batchSize *ab.BatchSize) *cb.ConfigGroup {\n\treturn ordererConfigGroup(BatchSizeKey, utils.MarshalOrPanic(batchSize))\n}\n\n\nfunc TemplateBatchTimeout(batchTimeout string) *cb.ConfigGroup {\n\treturn ordererConfigGroup(BatchTimeoutKey, utils.MarshalOrPanic(&ab.BatchTimeout{Timeout: batchTimeout}))\n}\n\n\n\n\n\nfunc TemplateKafkaBrokers(brokers []string) *cb.ConfigGroup {\n\treturn ordererConfigGroup(KafkaBrokersKey, utils.MarshalOrPanic(&ab.KafkaBrokers{Brokers: brokers}))\n}\n\nfunc TemplateChannelRestrictions(maxChannels uint64) *cb.ConfigGroup ", "output": "{\n\treturn ordererConfigGroup(ChannelRestrictionsKey, utils.MarshalOrPanic(&ab.ChannelRestrictions{MaxCount: maxChannels}))\n}"} {"input": "package virtcontainers\n\ntype mockAddr struct {\n\tnetwork string\n\tipAddr string\n}\n\nfunc (m mockAddr) Network() string {\n\treturn m.network\n}\n\n\n\nfunc (m mockAddr) String() string ", "output": "{\n\treturn m.ipAddr\n}"} {"input": "package seccomp\n\nimport (\n\tseccomp_compiler \"github.com/snapcore/snapd/sandbox/seccomp\"\n)\n\n\n\n\n\n\n\nfunc MockKernelFeatures(f func() []string) (resture func()) {\n\told := kernelFeatures\n\tkernelFeatures = f\n\treturn func() {\n\t\tkernelFeatures = old\n\t}\n}\n\nfunc MockRequiresSocketcall(f func(string) bool) (restore func()) {\n\told := requiresSocketcall\n\trequiresSocketcall = f\n\treturn func() {\n\t\trequiresSocketcall = old\n\t}\n}\n\nfunc MockDpkgKernelArchitecture(f func() string) (restore func()) {\n\told := dpkgKernelArchitecture\n\tdpkgKernelArchitecture = f\n\treturn func() {\n\t\tdpkgKernelArchitecture = old\n\t}\n}\n\nfunc MockReleaseInfoId(s string) (restore func()) {\n\told := releaseInfoId\n\treleaseInfoId = s\n\treturn func() {\n\t\treleaseInfoId = old\n\t}\n}\n\nfunc MockReleaseInfoVersionId(s string) (restore func()) {\n\told := releaseInfoVersionId\n\treleaseInfoVersionId = s\n\treturn func() {\n\t\treleaseInfoVersionId = old\n\t}\n}\n\nfunc MockSeccompCompilerLookup(f func(string) (string, error)) (restore func()) {\n\told := seccompCompilerLookup\n\tseccompCompilerLookup = f\n\treturn func() {\n\t\tseccompCompilerLookup = old\n\t}\n}\n\nfunc (b *Backend) VersionInfo() seccomp_compiler.VersionInfo {\n\treturn b.versionInfo\n}\n\nvar (\n\tRequiresSocketcall = requiresSocketcall\n\n\tGlobalProfileLE = globalProfileLE\n\tGlobalProfileBE = globalProfileBE\n\tIsBigEndian = isBigEndian\n)\n\nfunc MockTemplate(fakeTemplate []byte) (restore func()) ", "output": "{\n\torig := defaultTemplate\n\torigBarePrivDropSyscalls := barePrivDropSyscalls\n\tdefaultTemplate = fakeTemplate\n\tbarePrivDropSyscalls = \"\"\n\treturn func() {\n\t\tdefaultTemplate = orig\n\t\tbarePrivDropSyscalls = origBarePrivDropSyscalls\n\t}\n}"} {"input": "package context\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\n\tjujuos \"github.com/juju/utils/os\"\n)\n\n\n\nfunc OSDependentEnvVars(paths Paths) []string {\n\tswitch jujuos.HostOS() {\n\tcase jujuos.Windows:\n\t\treturn windowsEnv(paths)\n\tcase jujuos.Ubuntu:\n\t\treturn ubuntuEnv(paths)\n\tcase jujuos.CentOS:\n\t\treturn centosEnv(paths)\n\t}\n\treturn nil\n}\n\nfunc appendPath(paths Paths) []string {\n\treturn []string{\n\t\t\"PATH=\" + paths.GetToolsDir() + \":\" + os.Getenv(\"PATH\"),\n\t}\n}\n\n\n\nfunc centosEnv(paths Paths) []string {\n\treturn appendPath(paths)\n}\n\n\n\n\n\nfunc windowsEnv(paths Paths) []string {\n\tcharmDir := paths.GetCharmDir()\n\tcharmModules := filepath.Join(charmDir, \"lib\", \"Modules\")\n\treturn []string{\n\t\t\"Path=\" + paths.GetToolsDir() + \";\" + os.Getenv(\"Path\"),\n\t\t\"PSModulePath=\" + os.Getenv(\"PSModulePath\") + \";\" + charmModules,\n\t}\n}\n\nfunc ubuntuEnv(paths Paths) []string ", "output": "{\n\tpath := appendPath(paths)\n\tenv := []string{\n\t\t\"APT_LISTCHANGES_FRONTEND=none\",\n\t\t\"DEBIAN_FRONTEND=noninteractive\",\n\t}\n\tenv = append(env, path...)\n\treturn env\n}"} {"input": "package i3ipc\n\nimport (\n\t\"encoding/json\"\n)\n\n\n\ntype I3Node struct {\n\tID int64\n\tName string\n\tType string\n\tBorder string\n\tCurrentBorderWidth int32 `json:\"current_border_width\"`\n\tLayout string\n\tOrientation string\n\tPercent float64\n\tRect Rect\n\tWindowRect Rect\n\tDecoRect Rect `json:\"deco_rect\"`\n\tGeometry Rect\n\tWindow int32\n\tUrgent bool\n\tFocused bool\n\tFloating_Nodes []I3Node\n\tNodes []I3Node\n\tParent *I3Node\n\n\tWindow_Properties struct {\n\t\tTitle string\n\t\tInstance string\n\t\tClass string\n\t}\n\tSticky bool\n\tFloating string\n\tLast_Split_Layout string\n\tFullscreen_Mode int32\n\tScratchpad_State string\n\tWorkspace_Layout string\n}\n\n\nfunc setParent(node, parent *I3Node) {\n\n\tnode.Parent = parent\n\n\tfor i := range node.Nodes {\n\t\tsetParent(&node.Nodes[i], node)\n\t}\n\tfor i := range node.Floating_Nodes {\n\t\tsetParent(&node.Floating_Nodes[i], node)\n\t}\n}\n\n\n\n\nfunc (socket *IPCSocket) GetTree() (root I3Node, err error) ", "output": "{\n\tjsonReply, err := socket.Raw(I3GetTree, \"\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer setParent(&root, nil)\n\n\terr = json.Unmarshal(jsonReply, &root)\n\tif err == nil {\n\t\treturn\n\t}\n\tif _, ok := err.(*json.UnmarshalTypeError); ok {\n\t\terr = nil\n\t}\n\treturn\n}"} {"input": "package turtle\n\nimport (\n\t\"strings\"\n)\n\ntype DataSet struct {\n\ttriplecount int\n\tnscount int\n\tNamespaces map[string]string\n\tTriples []Triple\n}\n\nfunc newDataSet() *DataSet {\n\treturn &DataSet{\n\t\ttriplecount: 0,\n\t\tnscount: 0,\n\t\tNamespaces: make(map[string]string),\n\t\tTriples: []Triple{},\n\t}\n}\n\nfunc (d *DataSet) AddTripleStrings(subject, predicate, object string) {\n\td.triplecount += 1\n\td.Triples = append(d.Triples, MakeTriple(subject, predicate, object))\n}\n\nfunc (d *DataSet) AddTripleURIs(subject, predicate, object URI) {\n\td.triplecount += 1\n\td.Triples = append(d.Triples, Triple{subject, predicate, object})\n}\n\nfunc (d *DataSet) addNamespace(prefix, namespace string) {\n\td.nscount += 1\n\tnamespace = strings.TrimRight(namespace, \"#\")\n\td.Namespaces[prefix] = namespace\n}\n\n\n\nfunc (d *DataSet) NumNamespaces() int {\n\treturn d.nscount\n}\n\nfunc (d *DataSet) NumTriples() int ", "output": "{\n\treturn d.triplecount\n}"} {"input": "package utilmocks\n\nimport (\n\tcontext \"context\"\n\tgomock \"github.com/golang/mock/gomock\"\n\texec \"os/exec\"\n\treflect \"reflect\"\n)\n\n\ntype MockCommandRunner struct {\n\tctrl *gomock.Controller\n\trecorder *MockCommandRunnerMockRecorder\n}\n\n\ntype MockCommandRunnerMockRecorder struct {\n\tmock *MockCommandRunner\n}\n\n\nfunc NewMockCommandRunner(ctrl *gomock.Controller) *MockCommandRunner {\n\tmock := &MockCommandRunner{ctrl: ctrl}\n\tmock.recorder = &MockCommandRunnerMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockCommandRunner) EXPECT() *MockCommandRunnerMockRecorder {\n\treturn m.recorder\n}\n\n\n\n\n\nfunc (mr *MockCommandRunnerMockRecorder) Run(ctx, command interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Run\", reflect.TypeOf((*MockCommandRunner)(nil).Run), ctx, command)\n}\n\nfunc (m *MockCommandRunner) Run(ctx context.Context, command *exec.Cmd) ([]byte, []byte, error) ", "output": "{\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Run\", ctx, command)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].([]byte)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}"} {"input": "package testclient\n\nimport (\n\tkapi \"k8s.io/kubernetes/pkg/api\"\n\tktestclient \"k8s.io/kubernetes/pkg/client/unversioned/testclient\"\n\n\t\"github.com/openshift/origin/pkg/client\"\n\timageapi \"github.com/openshift/origin/pkg/image/api\"\n)\n\n\n\n\ntype FakeImages struct {\n\tFake *Fake\n}\n\nvar _ client.ImageInterface = &FakeImages{}\n\nfunc (c *FakeImages) Get(name string) (*imageapi.Image, error) {\n\tobj, err := c.Fake.Invokes(ktestclient.NewRootGetAction(\"images\", name), &imageapi.Image{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*imageapi.Image), err\n}\n\nfunc (c *FakeImages) List(opts kapi.ListOptions) (*imageapi.ImageList, error) {\n\tobj, err := c.Fake.Invokes(ktestclient.NewRootListAction(\"images\", opts), &imageapi.ImageList{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*imageapi.ImageList), err\n}\n\nfunc (c *FakeImages) Create(inObj *imageapi.Image) (*imageapi.Image, error) {\n\tobj, err := c.Fake.Invokes(ktestclient.NewRootCreateAction(\"images\", inObj), inObj)\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*imageapi.Image), err\n}\n\n\n\nfunc (c *FakeImages) Delete(name string) error ", "output": "{\n\t_, err := c.Fake.Invokes(ktestclient.NewRootDeleteAction(\"images\", name), &imageapi.Image{})\n\treturn err\n}"} {"input": "package chipmunk\n\nimport (\n\t\"github.com/Dethrail/chipmunk/transform\"\n\t\"github.com/Dethrail/chipmunk/vect\"\n\t\"math\"\n)\n\nconst (\n\tRadianConst = math.Pi / 180\n\tDegreeConst = 180 / math.Pi\n)\n\ntype Group int\ntype Layer int\n\ntype Shape struct {\n\tDefaultHash\n\tShapeClass\n\n\tBody *Body\n\n\tBB AABB\n\n\tIsSensor bool\n\n\te vect.Float\n\tu vect.Float\n\tSurface_v vect.Vect\n\n\tUserData interface{}\n\n\tGroup Group\n\tLayer Layer\n\n\tspace *Space\n\n\tvelocityIndexed bool\n}\n\nfunc newShape() *Shape {\n\treturn &Shape{velocityIndexed: true, e: 0.5, u: 0.5, Layer: -1}\n\n}\n\nfunc (shape *Shape) Velocity() (vect.Vect, bool) {\n\treturn shape.Body.v, shape.velocityIndexed\n}\n\nfunc (shape *Shape) SetFriction(friction vect.Float) {\n\tshape.u = friction\n}\n\nfunc (shape *Shape) SetElasticity(e vect.Float) {\n\tshape.e = e\n}\n\nfunc (shape *Shape) Shape() *Shape {\n\treturn shape\n}\n\nfunc (shape *Shape) AABB() AABB {\n\treturn shape.BB\n}\n\nfunc (shape *Shape) Clone() *Shape {\n\tclone := *shape\n\tcc := &clone\n\tcc.space = nil\n\tcc.DefaultHash.Reset()\n\tcc.Body = nil\n\tcc.ShapeClass = cc.ShapeClass.Clone(cc)\n\treturn cc\n}\n\n\n\nfunc (shape *Shape) Update() ", "output": "{\n\tshape.BB = shape.ShapeClass.update(transform.NewTransform(shape.Body.p, shape.Body.a))\n}"} {"input": "package protocol\n\nimport (\n\t\"io\"\n\t\"sync/atomic\"\n)\n\ntype countingReader struct {\n\tio.Reader\n\ttot uint64\n}\n\nvar (\n\ttotalIncoming uint64\n\ttotalOutgoing uint64\n)\n\n\n\nfunc (c *countingReader) Tot() uint64 {\n\treturn atomic.LoadUint64(&c.tot)\n}\n\ntype countingWriter struct {\n\tio.Writer\n\ttot uint64\n}\n\nfunc (c *countingWriter) Write(bs []byte) (int, error) {\n\tn, err := c.Writer.Write(bs)\n\tatomic.AddUint64(&c.tot, uint64(n))\n\tatomic.AddUint64(&totalOutgoing, uint64(n))\n\treturn n, err\n}\n\nfunc (c *countingWriter) Tot() uint64 {\n\treturn atomic.LoadUint64(&c.tot)\n}\n\nfunc TotalInOut() (uint64, uint64) {\n\treturn atomic.LoadUint64(&totalIncoming), atomic.LoadUint64(&totalOutgoing)\n}\n\nfunc (c *countingReader) Read(bs []byte) (int, error) ", "output": "{\n\tn, err := c.Reader.Read(bs)\n\tatomic.AddUint64(&c.tot, uint64(n))\n\tatomic.AddUint64(&totalIncoming, uint64(n))\n\treturn n, err\n}"} {"input": "package datastore\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hellodudu/Ultimate/iface\"\n\t\"github.com/hellodudu/Ultimate/utils/global\"\n)\n\nvar ds iface.IDatastore\n\n\n\nfunc TestNewDatastore(t *testing.T) {\n\n\tvar err error\n\tds, err = NewDatastore()\n\tif err != nil {\n\t\tt.Error(\"NewDatastore error:\", err)\n\t}\n\n}\n\nfunc TestTableGlobal(t *testing.T) {\n\ttbl := ds.TableGlobal()\n\tif tbl == nil {\n\t\tt.Error(\"Init table global error\")\n\t}\n\n\tif tbl.Id != 110 {\n\t\tt.Error(\"Init table global ultimate_id error\")\n\t}\n}\n\nfunc init() ", "output": "{\n\tglobal.Debugging = false\n\tglobal.MysqlUser = \"root\"\n\tglobal.MysqlPwd = \"\"\n\tglobal.MysqlAddr = \"127.0.0.1\"\n\tglobal.MysqlPort = \"3306\"\n\tglobal.MysqlDB = \"db_ultimate\"\n\tglobal.UltimateID = 110\n}"} {"input": "package queue\n\n\n\n\ntype LazyQueue struct {\n\tqChan chan interface{}\n\tDequeueMethod DequeueMethod\n}\n\n\n\n\ntype DequeueMethod func(interface{})\n\n\n\n\nfunc NewLazyQueue(qsize int, dequeueMethod DequeueMethod, grcount int) *LazyQueue {\n\tqInstance := &LazyQueue{}\n\tqInstance.qChan = make(chan interface{}, qsize)\n\tqInstance.DequeueMethod = dequeueMethod\n\tif grcount <= 0 {\n\t\tgrcount = 1\n\t}\n\tfor i := 0; i < grcount; i++ {\n\t\tgo qInstance.startDequeue()\n\t}\n\n\treturn qInstance\n}\n\n\n\nfunc (lq *LazyQueue) Enqueue(qinfo interface{}) {\n\tlq.qChan <- qinfo\n}\n\n\n\nfunc (lq *LazyQueue) startDequeue() ", "output": "{\n\tfor {\n\t\tselect {\n\t\tcase bm := <-lq.qChan:\n\t\t\tlq.DequeueMethod(bm)\n\t\t}\n\t}\n}"} {"input": "package archive \n\nimport (\n\t\"syscall\"\n\t\"time\"\n)\n\n\n\nfunc timeToTimespec(time time.Time) (ts syscall.Timespec) ", "output": "{\n\tif time.IsZero() {\n\t\tts.Sec = 0\n\t\tts.Nsec = ((1 << 30) - 2)\n\t\treturn\n\t}\n\treturn syscall.NsecToTimespec(time.UnixNano())\n}"} {"input": "package engine\n\nimport (\n\t\"time\"\n\n\t\"github.com/aws/amazon-ecs-agent/agent/api\"\n)\n\n\n\ntype impossibleTransitionError struct {\n\tstate api.ContainerStatus\n}\n\nfunc (err *impossibleTransitionError) Error() string {\n\treturn \"Cannot transition to \" + err.state.String()\n}\nfunc (err *impossibleTransitionError) ErrorName() string { return \"ImpossibleStateTransitionError\" }\n\ntype DockerTimeoutError struct {\n\tduration time.Duration\n\ttransition string\n}\n\nfunc (err *DockerTimeoutError) Error() string {\n\treturn \"Could not transition to \" + err.transition + \"; timed out after waiting \" + err.duration.String()\n}\nfunc (err *DockerTimeoutError) ErrorName() string { return \"DockerTimeoutError\" }\n\ntype ContainerVanishedError struct{}\n\nfunc (err ContainerVanishedError) Error() string { return \"No container matching saved ID found\" }\nfunc (err ContainerVanishedError) ErrorName() string { return \"ContainerVanishedError\" }\n\ntype CannotXContainerError struct {\n\ttransition string\n\tmsg string\n}\n\nfunc (err CannotXContainerError) Error() string { return err.msg }\nfunc (err CannotXContainerError) ErrorName() string {\n\treturn \"Cannot\" + err.transition + \"ContainerError\"\n}\n\ntype OutOfMemoryError struct{}\n\n\nfunc (err OutOfMemoryError) ErrorName() string { return \"OutOfMemoryError\" }\n\n\ntype DockerStateError struct {\n\tdockerError string\n\tname string\n}\n\nfunc NewDockerStateError(err string) DockerStateError {\n\treturn DockerStateError{\n\t\tdockerError: err,\n\t\tname: \"DockerStateError\",\n\t}\n}\n\nfunc (err DockerStateError) Error() string {\n\treturn err.dockerError\n}\nfunc (err DockerStateError) ErrorName() string {\n\treturn err.name\n}\n\nfunc (err OutOfMemoryError) Error() string ", "output": "{ return \"Container killed due to memory usage\" }"} {"input": "package unitassigner\n\nimport (\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/worker/v2\"\n\t\"github.com/juju/worker/v2/dependency\"\n\n\t\"github.com/juju/juju/api/base\"\n\t\"github.com/juju/juju/api/unitassigner\"\n\t\"github.com/juju/juju/cmd/jujud/agent/engine\"\n)\n\n\ntype Logger interface {\n\tTracef(string, ...interface{})\n}\n\n\ntype ManifoldConfig struct {\n\tAPICallerName string\n\tLogger Logger\n}\n\n\n\n\n\nfunc (c *ManifoldConfig) start(apiCaller base.APICaller) (worker.Worker, error) {\n\tfacade := unitassigner.New(apiCaller)\n\tworker, err := New(facade, c.Logger)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treturn worker, nil\n}\n\nfunc Manifold(config ManifoldConfig) dependency.Manifold ", "output": "{\n\treturn engine.APIManifold(\n\t\tengine.APIManifoldConfig{\n\t\t\tAPICallerName: config.APICallerName,\n\t\t},\n\t\tconfig.start,\n\t)\n}"} {"input": "package blanket_emulator\n\nimport (\n\t\"fmt\"\n)\n\ntype Event interface {\n\tHash() uint64\n\tInspect() string\n}\n\ntype ReturnEvent uint64\ntype ReadEvent uint64\ntype WriteEvent struct {\n\tAddr uint64\n\tValue uint64\n}\ntype SyscallEvent uint64\ntype InvalidInstructionEvent uint64\n\nfunc (addr ReadEvent) Hash() uint64 {\n\treturn ReadEventHash(uint64(addr))\n}\n\nfunc (s WriteEvent) Hash() uint64 {\n\treturn WriteEventHash(s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Hash() uint64 {\n\treturn SysEventHash(uint64(s))\n}\n\nfunc (s ReturnEvent) Hash() uint64 {\n\treturn ReturnEventHash(uint64(s))\n}\n\nfunc (s InvalidInstructionEvent) Hash() uint64 {\n\treturn InvalidInstructionEventHash(uint64(s))\n}\n\nfunc (addr ReadEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Read([%x])\", addr)\n}\n\nfunc (addr ReturnEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Return([%x])\", addr)\n}\n\n\n\nfunc (s SyscallEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Sys(%x)\", s)\n}\n\nfunc (s InvalidInstructionEvent) Inspect() string {\n\treturn fmt.Sprintf(\"InvalidOpcode([%x])\", s)\n}\n\nfunc (s WriteEvent) Inspect() string ", "output": "{\n\treturn fmt.Sprintf(\"Write([%x]=%x)\", s.Addr, s.Value)\n}"} {"input": "package global\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/propagation\"\n)\n\n\n\n\ntype textMapPropagator struct {\n\tmtx sync.Mutex\n\tonce sync.Once\n\tdelegate propagation.TextMapPropagator\n\tnoop propagation.TextMapPropagator\n}\n\n\n\nvar _ propagation.TextMapPropagator = (*textMapPropagator)(nil)\n\nfunc newTextMapPropagator() *textMapPropagator {\n\treturn &textMapPropagator{\n\t\tnoop: propagation.NewCompositeTextMapPropagator(),\n\t}\n}\n\n\n\n\nfunc (p *textMapPropagator) SetDelegate(delegate propagation.TextMapPropagator) {\n\tif delegate == nil {\n\t\treturn\n\t}\n\n\tp.mtx.Lock()\n\tp.once.Do(func() { p.delegate = delegate })\n\tp.mtx.Unlock()\n}\n\n\n\n\nfunc (p *textMapPropagator) effectiveDelegate() propagation.TextMapPropagator {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tif p.delegate != nil {\n\t\treturn p.delegate\n\t}\n\treturn p.noop\n}\n\n\n\n\n\nfunc (p *textMapPropagator) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context {\n\treturn p.effectiveDelegate().Extract(ctx, carrier)\n}\n\n\nfunc (p *textMapPropagator) Fields() []string {\n\treturn p.effectiveDelegate().Fields()\n}\n\nfunc (p *textMapPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) ", "output": "{\n\tp.effectiveDelegate().Inject(ctx, carrier)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\n\t\"github.com/rjeczalik/which\"\n)\n\n\n\nconst usage = `NAME:\n\tgowhich - shows the import path of Go executables\n\nUSAGE:\n\tgowhich name|path\n\nEXAMPLES:\n\tgowhich godoc\n\tgowhich ~/bin/godoc`\n\nfunc ishelp(s string) bool {\n\treturn s == \"-h\" || s == \"-help\" || s == \"help\" || s == \"--help\" || s == \"/?\"\n}\n\nfunc main() {\n\tif len(os.Args) != 2 {\n\t\tdie(usage)\n\t}\n\tif ishelp(os.Args[1]) {\n\t\tfmt.Println(usage)\n\t\treturn\n\t}\n\tpath, err := exec.LookPath(os.Args[1])\n\tif err != nil {\n\t\tdie(err)\n\t}\n\tpkg, err := which.Import(path)\n\tif err != nil {\n\t\tdie(err)\n\t}\n\tfmt.Println(pkg)\n}\n\nfunc die(v interface{}) ", "output": "{\n\tfmt.Fprintln(os.Stderr, v)\n\tos.Exit(1)\n}"} {"input": "package influxdb\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"testing\"\n\t\"time\"\n\n\t\"go.k6.io/k6/stats\"\n)\n\nfunc benchmarkInfluxdb(b *testing.B, t time.Duration) {\n\ttestOutputCycle(b, func(rw http.ResponseWriter, r *http.Request) {\n\t\tfor {\n\t\t\ttime.Sleep(t)\n\t\t\tm, _ := io.CopyN(ioutil.Discard, r.Body, 1<<18) \n\t\t\tif m == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\trw.WriteHeader(204)\n\t}, func(tb testing.TB, c *Output) {\n\t\tb = tb.(*testing.B)\n\t\tb.ResetTimer()\n\n\t\tsamples := make(stats.Samples, 10)\n\t\tfor i := 0; i < len(samples); i++ {\n\t\t\tsamples[i] = stats.Sample{\n\t\t\t\tMetric: stats.New(\"testGauge\", stats.Gauge),\n\t\t\t\tTime: time.Now(),\n\t\t\t\tTags: stats.NewSampleTags(map[string]string{\n\t\t\t\t\t\"something\": \"else\",\n\t\t\t\t\t\"VU\": \"21\",\n\t\t\t\t\t\"else\": \"something\",\n\t\t\t\t}),\n\t\t\t\tValue: 2.0,\n\t\t\t}\n\t\t}\n\n\t\tb.ResetTimer()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tc.AddMetricSamples([]stats.SampleContainer{samples})\n\t\t\ttime.Sleep(time.Nanosecond * 20)\n\t\t}\n\t})\n}\n\nfunc BenchmarkInfluxdb1Second(b *testing.B) {\n\tbenchmarkInfluxdb(b, time.Second)\n}\n\n\n\nfunc BenchmarkInfluxdb100Milliseconds(b *testing.B) {\n\tbenchmarkInfluxdb(b, 100*time.Millisecond)\n}\n\nfunc BenchmarkInfluxdb2Second(b *testing.B) ", "output": "{\n\tbenchmarkInfluxdb(b, 2*time.Second)\n}"} {"input": "package daemon\n\nimport (\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/Cloakaac/cloak/models\"\n)\n\ntype RecordDaemon struct{}\n\n\n\nfunc (r *RecordDaemon) tick() ", "output": "{\n\ttotal := models.GetOnlineCount()\n\terr := models.AddOnlineRecord(total, time.Now().Unix())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"input": "package remotecache\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/bradfitz/gomemcache/memcache\"\n\t\"github.com/grafana/grafana/pkg/setting\"\n)\n\nconst memcachedCacheType = \"memcached\"\n\ntype memcachedStorage struct {\n\tc *memcache.Client\n}\n\nfunc newMemcachedStorage(opts *setting.RemoteCacheOptions) *memcachedStorage {\n\treturn &memcachedStorage{\n\t\tc: memcache.New(opts.ConnStr),\n\t}\n}\n\n\n\n\nfunc (s *memcachedStorage) Set(ctx context.Context, key string, val interface{}, expires time.Duration) error {\n\titem := &cachedItem{Val: val}\n\tbytes, err := encodeGob(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar expiresInSeconds int64\n\tif expires != 0 {\n\t\texpiresInSeconds = int64(expires) / int64(time.Second)\n\t}\n\n\tmemcachedItem := newItem(key, bytes, int32(expiresInSeconds))\n\treturn s.c.Set(memcachedItem)\n}\n\n\nfunc (s *memcachedStorage) Get(ctx context.Context, key string) (interface{}, error) {\n\tmemcachedItem, err := s.c.Get(key)\n\tif err != nil && err.Error() == \"memcache: cache miss\" {\n\t\treturn nil, ErrCacheItemNotFound\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titem := &cachedItem{}\n\n\terr = decodeGob(memcachedItem.Value, item)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn item.Val, nil\n}\n\n\nfunc (s *memcachedStorage) Delete(ctx context.Context, key string) error {\n\treturn s.c.Delete(key)\n}\n\nfunc newItem(sid string, data []byte, expire int32) *memcache.Item ", "output": "{\n\treturn &memcache.Item{\n\t\tKey: sid,\n\t\tValue: data,\n\t\tExpiration: expire,\n\t}\n}"} {"input": "package cmac\n\nimport (\n\t\"log\"\n\t\"unsafe\"\n)\n\n\n\n\nfunc xorBlock(\n\tdstPtr unsafe.Pointer,\n\taPtr unsafe.Pointer,\n\tbPtr unsafe.Pointer) ", "output": "{\n\tconst wordSize = unsafe.Sizeof(uintptr(0))\n\tif blockSize != 2*wordSize {\n\t\tlog.Panicf(\"%d %d\", blockSize, wordSize)\n\t}\n\n\ta := (*[2]uintptr)(aPtr)\n\tb := (*[2]uintptr)(bPtr)\n\tdst := (*[2]uintptr)(dstPtr)\n\n\tdst[0] = a[0] ^ b[0]\n\tdst[1] = a[1] ^ b[1]\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/bitly/go-nsq\"\n)\n\n\n\ntype BackendQueue interface {\n\tPut([]byte) error\n\tReadChan() chan []byte \n\tClose() error\n\tDelete() error\n\tDepth() int64\n\tEmpty() error\n}\n\ntype DummyBackendQueue struct {\n\treadChan chan []byte\n}\n\nfunc NewDummyBackendQueue() BackendQueue {\n\treturn &DummyBackendQueue{readChan: make(chan []byte)}\n}\n\nfunc (d *DummyBackendQueue) Put([]byte) error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) ReadChan() chan []byte {\n\treturn d.readChan\n}\n\nfunc (d *DummyBackendQueue) Close() error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Delete() error {\n\treturn nil\n}\n\n\n\nfunc (d *DummyBackendQueue) Empty() error {\n\treturn nil\n}\n\nfunc WriteMessageToBackend(buf *bytes.Buffer, msg *nsq.Message, bq BackendQueue) error {\n\tbuf.Reset()\n\terr := msg.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = bq.Put(buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Depth() int64 ", "output": "{\n\treturn int64(0)\n}"} {"input": "package iso20022\n\n\ntype AcquirerProtocolParameters5 struct {\n\n\tFinancialCapture *FinancialCapture1Code `xml:\"FinCaptr\"`\n\n\tBatchTransfer *ExchangeConfiguration4 `xml:\"BtchTrf,omitempty\"`\n\n\tCompletionExchange *ExchangeConfiguration5 `xml:\"CmpltnXchg,omitempty\"`\n\n\tCancellationExchange *CancellationProcess1Code `xml:\"CxlXchg,omitempty\"`\n}\n\nfunc (a *AcquirerProtocolParameters5) SetFinancialCapture(value string) {\n\ta.FinancialCapture = (*FinancialCapture1Code)(&value)\n}\n\nfunc (a *AcquirerProtocolParameters5) AddBatchTransfer() *ExchangeConfiguration4 {\n\ta.BatchTransfer = new(ExchangeConfiguration4)\n\treturn a.BatchTransfer\n}\n\n\n\nfunc (a *AcquirerProtocolParameters5) SetCancellationExchange(value string) {\n\ta.CancellationExchange = (*CancellationProcess1Code)(&value)\n}\n\nfunc (a *AcquirerProtocolParameters5) AddCompletionExchange() *ExchangeConfiguration5 ", "output": "{\n\ta.CompletionExchange = new(ExchangeConfiguration5)\n\treturn a.CompletionExchange\n}"} {"input": "package backingstore\n\nimport (\n\t\"github.com/gostor/gotgt/pkg/api\"\n\t\"github.com/gostor/gotgt/pkg/scsi\"\n)\n\nfunc init() {\n\tscsi.RegisterBackingStore(\"null\", newNull)\n}\n\ntype NullBackingStore struct {\n\tscsi.BaseBackingStore\n}\n\nfunc newNull() (api.BackingStore, error) {\n\treturn &NullBackingStore{\n\t\tBaseBackingStore: scsi.BaseBackingStore{\n\t\t\tName: \"null\",\n\t\t\tDataSize: 0,\n\t\t\tOflagsSupported: 0,\n\t\t},\n\t}, nil\n}\n\nfunc (bs *NullBackingStore) Open(dev *api.SCSILu, path string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Close(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Init(dev *api.SCSILu, Opts string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Exit(dev *api.SCSILu) error {\n\treturn nil\n}\n\n\n\nfunc (bs *NullBackingStore) Read(offset, tl int64) ([]byte, error) {\n\treturn nil, nil\n}\n\nfunc (bs *NullBackingStore) Write(wbuf []byte, offset int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataSync(offset, tl int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataAdvise(offset, length int64, advise uint32) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Unmap([]api.UnmapBlockDescriptor) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Size(dev *api.SCSILu) uint64 ", "output": "{\n\treturn 0\n}"} {"input": "package query\n\nimport (\n\t\"encoding/json\"\n\t\"reflect\"\n)\n\n\n\nfunc wrapper(name string, v interface{}) map[string]interface{} {\n\tquery := map[string]interface{}{\n\t\tname: v,\n\t}\n\treturn query\n}\n\nfunc convert(value reflect.Value) interface{} {\n\tswitch value.Kind() {\n\tcase reflect.Slice:\n\t\tvar res []interface{}\n\t\tfor i := 0; i < value.Len(); i++ {\n\t\t\tres = append(res, convert(value.Index(i)))\n\t\t}\n\t\treturn res\n\tcase reflect.Ptr:\n\t\tif !value.IsNil() {\n\t\t\treturn convert(value.Elem())\n\t\t}\n\tcase reflect.String:\n\t\treturn value.String()\n\tcase reflect.Float64:\n\t\treturn value.Float()\n\tcase reflect.Int:\n\t\treturn value.Int()\n\tcase reflect.Bool:\n\t\treturn value.Bool()\n\t}\n\treturn value.Interface()\n}\n\nfunc convertable(value reflect.Value) bool {\n\tswitch value.Kind() {\n\tcase reflect.Slice:\n\t\treturn value.Len() > 0\n\tcase reflect.Ptr:\n\t\treturn !value.IsNil()\n\t}\n\treturn true\n}\n\nfunc convertStruct(x interface{}) interface{} {\n\tquery := make(map[string]interface{})\n\n\tt := reflect.ValueOf(x).Type()\n\tv := reflect.ValueOf(x)\n\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tfield := t.Field(i)\n\t\tvalue := v.FieldByName(field.Name)\n\t\ttag := field.Tag.Get(\"json\")\n\t\tif tag == \"-\" {\n\t\t\tcontinue\n\t\t}\n\t\tif convertable(value) {\n\t\t\tquery[tag] = convert(value)\n\t\t}\n\t}\n\n\treturn query\n\n}\n\nfunc toJson(v interface{}) ([]byte, error) ", "output": "{\n\treturn json.Marshal(v)\n}"} {"input": "package armpeering_test\n\nimport (\n\t\"context\"\n\t\"log\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/peering/armpeering\"\n)\n\n\n\n\nfunc ExampleLegacyPeeringsClient_List() ", "output": "{\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armpeering.NewLegacyPeeringsClient(\"\", cred, nil)\n\tpager := client.List(\"\",\n\t\tarmpeering.LegacyPeeringsKind(\"Exchange\"),\n\t\t&armpeering.LegacyPeeringsClientListOptions{Asn: nil})\n\tfor {\n\t\tnextResult := pager.NextPage(ctx)\n\t\tif err := pager.Err(); err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tif !nextResult {\n\t\t\tbreak\n\t\t}\n\t\tfor _, v := range pager.PageResponse().Value {\n\t\t\tlog.Printf(\"Pager result: %#v\\n\", v)\n\t\t}\n\t}\n}"} {"input": "package jmespath\n\nimport \"strconv\"\n\n\n\ntype JMESPath struct {\n\tast ASTNode\n\tintr *treeInterpreter\n}\n\n\n\nfunc Compile(expression string) (*JMESPath, error) {\n\tparser := NewParser()\n\tast, err := parser.Parse(expression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tjmespath := &JMESPath{ast: ast, intr: newInterpreter()}\n\treturn jmespath, nil\n}\n\n\n\n\nfunc MustCompile(expression string) *JMESPath {\n\tjmespath, err := Compile(expression)\n\tif err != nil {\n\t\tpanic(`jmespath: Compile(` + strconv.Quote(expression) + `): ` + err.Error())\n\t}\n\treturn jmespath\n}\n\n\n\n\n\nfunc Search(expression string, data interface{}) (interface{}, error) {\n\tintr := newInterpreter()\n\tparser := NewParser()\n\tast, err := parser.Parse(expression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn intr.Execute(ast, data)\n}\n\nfunc (jp *JMESPath) Search(data interface{}) (interface{}, error) ", "output": "{\n\treturn jp.intr.Execute(jp.ast, data)\n}"} {"input": "package main\n\nimport (\n\t\"go/build\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/posener/complete\"\n)\n\n\n\nfunc predictPackages(a complete.Args) (prediction []string) {\n\tprediction = []string{a.Last}\n\tlastPrediction := \"\"\n\tfor len(prediction) == 1 && (lastPrediction == \"\" || lastPrediction != prediction[0]) {\n\t\tlastPrediction = prediction[0]\n\t\ta.Last = prediction[0]\n\t\tprediction = predictLocalAndSystem(a)\n\t}\n\treturn\n}\n\nfunc predictLocalAndSystem(a complete.Args) []string {\n\tlocalDirs := complete.PredictFilesSet(listPackages(a.Directory())).Predict(a)\n\ts := systemDirs(a.Last)\n\tsysDirs := complete.PredictSet(s...).Predict(a)\n\treturn append(localDirs, sysDirs...)\n}\n\n\n\nfunc listPackages(dir string) (directories []string) {\n\tfiles, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\tcomplete.Log(\"failed reading directory %s: %s\", dir, err)\n\t\treturn\n\t}\n\n\tpaths := make([]string, 0, len(files)+1)\n\tfor _, f := range files {\n\t\tif f.IsDir() {\n\t\t\tpaths = append(paths, filepath.Join(dir, f.Name()))\n\t\t}\n\t}\n\tpaths = append(paths, dir)\n\n\tfor _, p := range paths {\n\t\tpkg, err := build.ImportDir(p, 0)\n\t\tif err != nil {\n\t\t\tcomplete.Log(\"failed importing directory %s: %s\", p, err)\n\t\t\tcontinue\n\t\t}\n\t\tdirectories = append(directories, pkg.Dir)\n\t}\n\treturn\n}\n\n\n\nfunc systemDirs(dir string) (directories []string) ", "output": "{\n\tpaths := strings.Split(os.Getenv(\"GOPATH\"), \":\")\n\tfor i := range paths {\n\t\tpaths[i] = filepath.Join(paths[i], \"src\")\n\t}\n\n\tif !strings.HasSuffix(dir, \"/\") {\n\t\tdir = filepath.Dir(dir)\n\t}\n\n\tfor _, basePath := range paths {\n\t\tpath := filepath.Join(basePath, dir)\n\t\tfiles, err := ioutil.ReadDir(path)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tswitch dir {\n\t\tcase \"\", \".\", \"/\", \"./\":\n\t\tdefault:\n\t\t\tdirectories = append(directories, dir)\n\t\t}\n\t\tfor _, f := range files {\n\t\t\tif !f.IsDir() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdirectories = append(directories, filepath.Join(dir, f.Name())+\"/\")\n\t\t}\n\t}\n\treturn\n}"} {"input": "package serverrpc\n\nimport (\n\t\"github.com/hyperhq/hyperd/types\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\nfunc (s *ServerRPC) TTYResize(c context.Context, req *types.TTYResizeRequest) (*types.TTYResizeResponse, error) ", "output": "{\n\terr := s.daemon.TtyResize(req.ContainerID, req.ExecID, int(req.Height), int(req.Width))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &types.TTYResizeResponse{}, nil\n}"} {"input": "package tests\n\nimport (\n log \"github.com/janekolszak/revfluent\"\n \"github.com/revel/revel/testing\"\n)\n\ntype AppTest struct {\n testing.TestSuite\n}\n\nfunc (t *AppTest) TestError() {\n data := map[string]string{\"message\": \"Error\"}\n log.Error(data)\n}\n\nfunc (t *AppTest) TestDebug() {\n data := map[string]string{\"message\": \"Debug\"}\n log.Debug(data)\n}\n\n\n\nfunc (t *AppTest) TestLog() {\n data := map[string]string{\"message\": \"Log\"}\n log.Log(\"tag\", data)\n}\n\nfunc (t *AppTest) TestLogger() {\n data := map[string]string{\"message\": \"Logger\"}\n log.Logger.Post(\"tag\", data)\n}\n\nfunc (t *AppTest) TestInfo() ", "output": "{\n data := map[string]string{\"message\": \"Info\"}\n log.Info(data)\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc main() {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Scan()\n\ttestCases, _ := strconv.Atoi(scanner.Text())\n\tfor i := 0; i < testCases; i++ {\n\t\tfmt.Printf(\"Case #%v: %v\\n\", i+1, solve(parseTestCase(scanner)))\n\t}\n}\n\nfunc solve(us int, others []int) int {\n\tcnt := 0\n\tfmt.Println(us, others)\n\tprobs := make([]int, len(others))\n\tif us > others[0] {\n\t\tprobs[0] = us\n\t}\n\tfor i := 1; i < len(others); i++ {\n\t\tif probs[i-1]+others[i-1] > others[i] {\n\t\t\tprobs[i] = probs[i-1] + others[i-1]\n\t\t}\n\t}\n\tfor i := 0; i < len(probs); i++ {\n\t\tif probs[i] <= others[i] {\n\t\t\tcnt++\n\t\t}\n\t}\n\n\treturn cnt\n}\n\n\n\nfunc parseTestCase(scanner *bufio.Scanner) (int, []int) ", "output": "{\n\tscanner.Scan()\n\tpair := strings.Split(scanner.Text(), \" \")\n\n\tus, _ := strconv.Atoi(pair[0])\n\tscanner.Scan()\n\tothers := []int{}\n\tfor _, m := range strings.Split(scanner.Text(), \" \") {\n\t\tmote, _ := strconv.Atoi(m)\n\t\tothers = append(others, mote)\n\t}\n\tsort.Ints(others)\n\treturn us, others\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSGameLiftBuild_S3Location struct {\n\n\tBucket string `json:\"Bucket,omitempty\"`\n\n\tKey string `json:\"Key,omitempty\"`\n\n\tRoleArn string `json:\"RoleArn,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSGameLiftBuild_S3Location) AWSCloudFormationType() string {\n\treturn \"AWS::GameLift::Build.S3Location\"\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\n\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSGameLiftBuild_S3Location) SetMetadata(metadata map[string]interface{}) ", "output": "{\n\tr._metadata = metadata\n}"} {"input": "package kubernetes\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/api/apps/v1beta1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\n\t\"github.com/weaveworks/scope/report\"\n)\n\n\ntype StatefulSet interface {\n\tMeta\n\tSelector() (labels.Selector, error)\n\tGetNode(probeID string) report.Node\n}\n\ntype statefulSet struct {\n\t*v1beta1.StatefulSet\n\tMeta\n}\n\n\n\n\nfunc (s *statefulSet) Selector() (labels.Selector, error) {\n\tselector, err := metav1.LabelSelectorAsSelector(s.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn selector, nil\n}\n\nfunc (s *statefulSet) GetNode(probeID string) report.Node {\n\tdesiredReplicas := 1\n\tif s.Spec.Replicas != nil {\n\t\tdesiredReplicas = int(*s.Spec.Replicas)\n\t}\n\tlatests := map[string]string{\n\t\tNodeType: \"StatefulSet\",\n\t\tDesiredReplicas: fmt.Sprint(desiredReplicas),\n\t\tReplicas: fmt.Sprint(s.Status.Replicas),\n\t\treport.ControlProbeID: probeID,\n\t}\n\tif s.Status.ObservedGeneration != nil {\n\t\tlatests[ObservedGeneration] = fmt.Sprint(*s.Status.ObservedGeneration)\n\t}\n\treturn s.MetaNode(report.MakeStatefulSetNodeID(s.UID())).WithLatests(latests)\n}\n\nfunc NewStatefulSet(s *v1beta1.StatefulSet) StatefulSet ", "output": "{\n\treturn &statefulSet{\n\t\tStatefulSet: s,\n\t\tMeta: meta{s.ObjectMeta},\n\t}\n}"} {"input": "package examples\n\nimport (\n\t\"github.com/orfjackal/gospec/src/gospec\"\n\t\"testing\"\n)\n\n\n\n\n\n\n\n\n\nfunc TestAllSpecs(t *testing.T) ", "output": "{\n\tr := gospec.NewRunner()\n\n\tr.AddSpec(ExecutionModelSpec)\n\tr.AddSpec(ExpectationSyntaxSpec)\n\tr.AddSpec(FibSpec)\n\tr.AddSpec(StackSpec)\n\n\tgospec.MainGoTest(r, t)\n}"} {"input": "package esicache\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/corestoreio/errors\"\n)\n\n\n\n\ntype Cacher interface {\n\tSet(key string, value []byte, expiration time.Duration) error\n\tGet(key string) ([]byte, error)\n}\n\n\n\nfunc NewCacher(url string) (Cacher, error) {\n\n\treturn nil, nil\n}\n\n\ntype Caches []Cacher\n\n\nfunc (c Caches) Set(key string, value []byte, expiration time.Duration) error {\n\treturn nil\n}\n\n\nfunc (c Caches) Get(key string) ([]byte, error) {\n\treturn nil, nil\n}\n\n\nvar MainRegistry = ®istry{\n\tcaches: make(map[string]Caches),\n}\n\ntype registry struct {\n\tmu sync.RWMutex\n\tcaches map[string]Caches\n}\n\nfunc (r *registry) Get(ctx context.Context, scope, alias, key string) error {\n\treturn errors.New(\"TODO IMPLEMENT\")\n}\n\n\n\n\n\n\n\nfunc (r *registry) Len(scope string) int {\n\tr.mu.RLock()\n\tdefer r.mu.RUnlock()\n\treturn len(r.caches[scope])\n}\n\n\nfunc (r *registry) Clear() {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tr.caches = make(map[string]Caches)\n}\n\nfunc (r *registry) Register(scope, url string) error ", "output": "{\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tc, err := NewCacher(url)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"[esikv] NewCacher URL %q\", url)\n\t}\n\n\tif _, ok := r.caches[scope]; !ok {\n\t\tr.caches[scope] = make(Caches, 0, 2)\n\t}\n\tr.caches[scope] = append(r.caches[scope], c)\n\n\treturn nil\n}"} {"input": "package rng\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\n\ntype CauchyGenerator struct {\n\tuniform *UniformGenerator\n}\n\n\n\n\nfunc NewCauchyGenerator(seed int64) *CauchyGenerator {\n\turng := NewUniformGenerator(seed)\n\treturn &CauchyGenerator{urng}\n}\n\n\nfunc (crng CauchyGenerator) Cauchy(x0, gamma float64) float64 {\n\tif !(gamma > 0.0) {\n\t\tpanic(fmt.Sprintf(\"Invalid parameter gamma: %.2f\", gamma))\n\t}\n\treturn crng.cauchy(x0, gamma)\n}\n\n\nfunc (crng CauchyGenerator) StandardCauchy() float64 {\n\treturn crng.cauchy(0.0, 1.0)\n}\n\n\n\nfunc (crng CauchyGenerator) cauchy(x0, gamma float64) float64 ", "output": "{\n\treturn x0 + gamma*math.Tan(math.Pi*(crng.uniform.Float64()-0.5))\n}"} {"input": "package lapack\n\nimport (\n \n \"fmt\"\n \"github.com/hrautila/linalg\"\n \"github.com/hrautila/matrix\"\n)\n\n\nfunc Potrf(A matrix.Matrix, opts ...linalg.Option) error {\n switch A.(type) {\n case *matrix.FloatMatrix:\n return PotrfFloat(A.(*matrix.FloatMatrix), opts...)\n case *matrix.ComplexMatrix:\n return onError(\"Potrf: complex not implemented yet\")\n }\n return onError(\"Potrf unknown types\")\n}\n\nfunc PotrfFloat(A *matrix.FloatMatrix, opts ...linalg.Option) error {\n pars, err := linalg.GetParameters(opts...)\n if err != nil {\n return err\n }\n ind := linalg.GetIndexOpts(opts...)\n err = checkPotrf(ind, A)\n if ind.N == 0 {\n return nil\n }\n Aa := A.FloatArray()\n uplo := linalg.ParamString(pars.Uplo)\n info := dpotrf(uplo, ind.N, Aa[ind.OffsetA:], ind.LDa)\n if info != 0 {\n return onError(fmt.Sprintf(\"Potrf: lapack error %d\", info))\n }\n return nil\n}\n\n\n\nfunc checkPotrf(ind *linalg.IndexOpts, A matrix.Matrix) error ", "output": "{\n arows := ind.LDa\n if ind.N < 0 {\n ind.N = A.Rows()\n if ind.N != A.Cols() {\n return onError(\"Potrf: not square\")\n }\n }\n if ind.N == 0 {\n return nil\n }\n if ind.LDa == 0 {\n ind.LDa = max(1, A.LeadingIndex())\n arows = max(1, A.Rows())\n }\n if ind.LDa < max(1, ind.N) {\n return onError(\"Potrf: lda\")\n }\n if ind.OffsetA < 0 {\n return onError(\"Potrf: offsetA\")\n }\n if A.NumElements() < ind.OffsetA+(ind.N-1)*arows+ind.N {\n return onError(\"Potrf: sizeA\")\n }\n return nil\n}"} {"input": "package configmap\n\nimport (\n\t\"sync\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n)\n\n\ntype ManualWatcher struct {\n\tNamespace string\n\n\tsync.RWMutex\n\tobservers map[string][]Observer\n}\n\nvar _ Watcher = (*ManualWatcher)(nil)\n\n\n\n\n\nfunc (w *ManualWatcher) ForEach(f func(string, []Observer) error) error {\n\tfor k, v := range w.observers {\n\t\tif err := f(k, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (w *ManualWatcher) Start(<-chan struct{}) error {\n\treturn nil\n}\n\n\nfunc (w *ManualWatcher) OnChange(configMap *corev1.ConfigMap) {\n\tif configMap.Namespace != w.Namespace {\n\t\treturn\n\t}\n\tw.RLock()\n\tdefer w.RUnlock()\n\tfor _, o := range w.observers[configMap.Name] {\n\t\to(configMap)\n\t}\n}\n\nfunc (w *ManualWatcher) Watch(name string, o ...Observer) ", "output": "{\n\tw.Lock()\n\tdefer w.Unlock()\n\n\tif w.observers == nil {\n\t\tw.observers = make(map[string][]Observer, 1)\n\t}\n\tw.observers[name] = append(w.observers[name], o...)\n}"} {"input": "package gridq\n\ntype byColRow []*WriteResponse\n\nfunc (p byColRow) Len() int { return len(p) }\nfunc (p byColRow) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\n\n\ntype byRowTimestamp []*ReadResponse\n\nfunc (p byRowTimestamp) Len() int { return len(p) }\nfunc (p byRowTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byRowTimestamp) Less(i, j int) bool {\n\tif p[i].Row < p[j].Row {\n\t\treturn true\n\t} else if p[i].Row > p[j].Row {\n\t\treturn false\n\t} else {\n\t\treturn p[i].State.Timestamp > p[j].State.Timestamp\n\t}\n}\n\ntype byTimestamp []*ReadResponse\n\nfunc (p byTimestamp) Len() int { return len(p) }\nfunc (p byTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byTimestamp) Less(i, j int) bool { return p[i].State.Timestamp < p[j].State.Timestamp }\n\nfunc (p byColRow) Less(i, j int) bool ", "output": "{\n\tif p[i].Col < p[j].Col {\n\t\treturn true\n\t} else if p[i].Col > p[j].Col {\n\t\treturn false\n\t} else {\n\t\treturn p[i].Row < p[j].Row\n\t}\n}"} {"input": "package naivecheap\n\nimport \"github.com/ffloyd/evergrid-go/global/types\"\n\ntype byPriceAsc []types.WorkerInfo\n\nfunc (sw byPriceAsc) Len() int {\n\treturn len(sw)\n}\n\nfunc (sw byPriceAsc) Swap(i, j int) {\n\tsw[i], sw[j] = sw[j], sw[i]\n}\n\n\n\ntype byQueueAsc []types.WorkerInfo\n\nfunc (sw byQueueAsc) Len() int {\n\treturn len(sw)\n}\n\nfunc (sw byQueueAsc) Swap(i, j int) {\n\tsw[i], sw[j] = sw[j], sw[i]\n}\n\nfunc (sw byQueueAsc) Less(i, j int) bool {\n\treturn sw[i].QueueLength < sw[j].QueueLength \n}\n\nfunc (sw byPriceAsc) Less(i, j int) bool ", "output": "{\n\treturn sw[i].PricePerTick < sw[j].PricePerTick \n}"} {"input": "package gtk\n\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\n\nfunc (v *Menu) PopupAtMouseCursor(parentMenuShell IMenu, parentMenuItem IMenuItem, button int, activateTime uint32) {\n\twshell := nullableWidget(parentMenuShell)\n\twitem := nullableWidget(parentMenuItem)\n\n\tC.gtk_menu_popup(v.native(),\n\t\twshell,\n\t\twitem,\n\t\tnil,\n\t\tnil,\n\t\tC.guint(button),\n\t\tC.guint32(activateTime))\n}\n\nfunc (v *SizeGroup) GetIgnoreHidden() bool {\n\tc := C.gtk_size_group_get_ignore_hidden(v.native())\n\treturn gobool(c)\n}\n\n\nfunc (v *Window) SetWMClass(name, class string) {\n\tcName := C.CString(name)\n\tdefer C.free(unsafe.Pointer(cName))\n\tcClass := C.CString(class)\n\tdefer C.free(unsafe.Pointer(cClass))\n\tC.gtk_window_set_wmclass(v.native(), (*C.gchar)(cName), (*C.gchar)(cClass))\n}\n\n\n\n\nfunc (v *FontButton) GetFontName() string {\n\tc := C.gtk_font_button_get_font_name(v.native())\n\treturn goString(c)\n}\n\n\nfunc (v *FontButton) SetFontName(fontname string) bool {\n\tcstr := C.CString(fontname)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_font_button_set_font_name(v.native(), (*C.gchar)(cstr))\n\treturn gobool(c)\n}\n\nfunc (v *SizeGroup) SetIgnoreHidden(ignoreHidden bool) ", "output": "{\n\tC.gtk_size_group_set_ignore_hidden(v.native(), gbool(ignoreHidden))\n}"} {"input": "package models\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n)\n\n\n\nfunc Hash(s string) string ", "output": "{\n\thash := md5.New()\n\thash.Write([]byte(s))\n\treturn hex.EncodeToString(hash.Sum(nil))\n}"} {"input": "package credit_card_utils\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestDisplayNumber(t *testing.T) ", "output": "{\n\tmaskedNumber := MaskNumber(\"42224242422222\")\n\n\tassert.Equal(t, \"XXXX-XXXX-XXXX-2222\", maskedNumber)\n}"} {"input": "package stick\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"go.mongodb.org/mongo-driver/bson\"\n)\n\n\ntype Coding string\n\n\nconst (\n\tJSON Coding = \"json\"\n\tBSON Coding = \"bson\"\n)\n\n\n\n\n\nfunc (c Coding) Unmarshal(in []byte, out interface{}) error {\n\tswitch c {\n\tcase JSON:\n\t\treturn json.Unmarshal(in, out)\n\tcase BSON:\n\t\treturn bson.Unmarshal(in, out)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"coal: unknown coding %q\", c))\n\t}\n}\n\n\nfunc (c Coding) Transfer(in, out interface{}) error {\n\tbytes, err := c.Marshal(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.Unmarshal(bytes, out)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc GetJSONKey(field *reflect.StructField) string {\n\ttag := field.Tag.Get(\"json\")\n\n\tif tag == \"-\" {\n\t\treturn \"\"\n\t}\n\n\tvalues := strings.Split(tag, \",\")\n\n\tif len(values) > 0 && len(values[0]) > 0 {\n\t\treturn values[0]\n\t}\n\n\treturn field.Name\n}\n\n\nfunc GetBSONKey(field *reflect.StructField) string {\n\ttag := field.Tag.Get(\"bson\")\n\n\tif tag == \"-\" {\n\t\treturn \"\"\n\t}\n\n\tvalues := strings.Split(tag, \",\")\n\n\tif len(values) > 0 && len(values[0]) > 0 {\n\t\treturn values[0]\n\t}\n\n\treturn strings.ToLower(field.Name)\n}\n\nfunc (c Coding) Marshal(in interface{}) ([]byte, error) ", "output": "{\n\tswitch c {\n\tcase JSON:\n\t\treturn json.Marshal(in)\n\tcase BSON:\n\t\treturn bson.Marshal(in)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"coal: unknown coding %q\", c))\n\t}\n}"} {"input": "package migrations\n\nimport \"github.com/BurntSushi/migration\"\n\n\n\nfunc ReplaceStepLocationWithPlanID(tx migration.LimitedTx) error ", "output": "{\n\t_, err := tx.Exec(`\n ALTER TABLE containers DROP COLUMN step_location;\n\t`)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = tx.Exec(`\n ALTER TABLE containers ADD COLUMN plan_id text;\n\t`)\n\n\treturn err\n}"} {"input": "package c3\n\ntype whereIterable struct {\n\titems Iterable\n\twhere Predicate\n}\n\n\n\nfunc (i *whereIterable) Iterator() Iterator ", "output": "{\n\treturn &whereIterator{i.items.Iterator(), i.where}\n}"} {"input": "package internalversion\n\nimport (\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n\tcore \"k8s.io/kubernetes/pkg/apis/core\"\n)\n\n\ntype ComponentStatusLister interface {\n\tList(selector labels.Selector) (ret []*core.ComponentStatus, err error)\n\tGet(name string) (*core.ComponentStatus, error)\n\tComponentStatusListerExpansion\n}\n\n\ntype componentStatusLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewComponentStatusLister(indexer cache.Indexer) ComponentStatusLister {\n\treturn &componentStatusLister{indexer: indexer}\n}\n\n\n\n\n\nfunc (s *componentStatusLister) Get(name string) (*core.ComponentStatus, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(core.Resource(\"componentstatus\"), name)\n\t}\n\treturn obj.(*core.ComponentStatus), nil\n}\n\nfunc (s *componentStatusLister) List(selector labels.Selector) (ret []*core.ComponentStatus, err error) ", "output": "{\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*core.ComponentStatus))\n\t})\n\treturn ret, err\n}"} {"input": "package common\n\nimport \"strings\"\n\n\n\nfunc TransformToAuthProvider(authConfig map[string]interface{}) map[string]interface{} ", "output": "{\n\tresult := map[string]interface{}{}\n\tif m, ok := authConfig[\"metadata\"].(map[string]interface{}); ok {\n\t\tresult[\"id\"] = m[\"name\"]\n\t}\n\tif t, ok := authConfig[\"type\"].(string); ok && t != \"\" {\n\t\tresult[\"type\"] = strings.Replace(t, \"Config\", \"Provider\", -1)\n\t}\n\treturn result\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"google.golang.org/grpc\"\n\n\t\"github.com/go-svc/svc/examples/grpc-lb/pb\"\n\t\"github.com/go-svc/svc/sd/consul\"\n\t\"github.com/go-svc/svc/sd/lb\"\n\t\"github.com/hashicorp/consul/api\"\n)\n\n\ntype server struct {\n\tdb pb.TodoClient\n}\n\n\nfunc (s *server) Add(ctx context.Context, in *pb.Task) (*pb.Task, error) {\n\ts.db.Add(context.Background(), in)\n\treturn in, nil\n}\n\n\nfunc (s *server) List(ctx context.Context, in *pb.Void) (*pb.Tasks, error) {\n\ttasks, _ := s.db.List(context.Background(), in)\n\treturn tasks, nil\n}\n\n\n\n\nfunc main() {\n\tlis, err := net.Listen(\"tcp\", \":50051\")\n\tif err != nil {\n\t\tlog.Fatalf(\"無法監聽該埠口:%v\", err)\n\t}\n\n\ts := grpc.NewServer()\n\tpb.RegisterTodoServer(s, &server{\n\t\tdb: newDB(),\n\t})\n\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"無法提供服務:%v\", err)\n\t}\n}\n\nfunc newDB() pb.TodoClient ", "output": "{\n\tsd, _ := consul.NewClient(api.DefaultConfig())\n\tbalancer := lb.NewBalancer(lb.ConsulOption{\n\t\tName: \"Database\",\n\t\tMode: lb.RoundRobin,\n\t\tTag: \"\",\n\t\tClient: sd,\n\t})\n\n\tconn, err := grpc.Dial(\"localhost:50050\", grpc.WithInsecure(), grpc.WithBalancer(balancer))\n\tif err != nil {\n\t\tlog.Fatalf(\"連線失敗:%v\", err)\n\t}\n\n\treturn pb.NewTodoClient(conn)\n}"} {"input": "package vmware\n\n\n\nfunc (v VMWare) IsAvailable() bool {\n\treturn false\n}\n\nfunc NewDatasource(fileName string) *VMWare ", "output": "{\n\treturn &VMWare{}\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\n\nfunc Example_noTrailingNewline() {\n\tld := NewLineDelimiter(os.Stdout, \"|\")\n\tdefer ld.Flush()\n\tfmt.Fprint(ld, \" Hello \\n World \")\n}\n\nfunc Example_trailingNewline() ", "output": "{\n\tld := NewLineDelimiter(os.Stdout, \"|\")\n\tdefer ld.Flush()\n\tfmt.Fprint(ld, \" Hello \\n World \\n\")\n}"} {"input": "package goque\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"encoding/gob\"\n)\n\n\ntype Item struct {\n\tID uint64\n\tKey []byte\n\tValue []byte\n}\n\n\nfunc (i *Item) ToString() string {\n\treturn string(i.Value)\n}\n\n\n\n\n\n\n\nfunc (i *Item) ToObject(value interface{}) error {\n\tbuffer := bytes.NewBuffer(i.Value)\n\tdec := gob.NewDecoder(buffer)\n\treturn dec.Decode(value)\n}\n\n\ntype PriorityItem struct {\n\tID uint64\n\tPriority uint8\n\tKey []byte\n\tValue []byte\n}\n\n\nfunc (pi *PriorityItem) ToString() string {\n\treturn string(pi.Value)\n}\n\n\n\n\n\n\n\n\n\n\nfunc idToKey(id uint64) []byte {\n\tkey := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(key, id)\n\treturn key\n}\n\n\nfunc keyToID(key []byte) uint64 {\n\treturn binary.BigEndian.Uint64(key)\n}\n\nfunc (pi *PriorityItem) ToObject(value interface{}) error ", "output": "{\n\tbuffer := bytes.NewBuffer(pi.Value)\n\tdec := gob.NewDecoder(buffer)\n\treturn dec.Decode(value)\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n)\n\nconst (\n\tSYSTEM_DIAGNOSTIC_ID = \"DiagnosticId\"\n\tSYSTEM_RAN_UNIT_TESTS = \"RanUnitTests\"\n\tSYSTEM_LAST_SECURITY_TIME = \"LastSecurityTime\"\n)\n\ntype System struct {\n\tName string `json:\"name\"`\n\tValue string `json:\"value\"`\n}\n\n\n\nfunc SystemFromJson(data io.Reader) *System {\n\tdecoder := json.NewDecoder(data)\n\tvar o System\n\terr := decoder.Decode(&o)\n\tif err == nil {\n\t\treturn &o\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc (o *System) ToJson() string ", "output": "{\n\tb, err := json.Marshal(o)\n\tif err != nil {\n\t\treturn \"\"\n\t} else {\n\t\treturn string(b)\n\t}\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\ntype Response struct {\n\tStatus string `json:\"status\"`\n\tErrorText string `json:\"errorText,omitempty\"`\n\tAddress string `json:\"address,omitempty\"`\n\tStatusCode int `json:\"statusCode,omitempty\"`\n\tVersion string `json:\"version,omitempty\"`\n}\n\ntype Responses struct {\n\tResponses []Response `json:\"responses\"`\n}\n\nfunc (r *Response) Fill(outStr string, err error) {\n\tif err != nil {\n\t\tr.Status = \"ERR\"\n\t\tr.ErrorText = strings.TrimSpace(outStr + \" \" + err.Error())\n\t} else {\n\t\tr.Status = \"OK\"\n\t}\n}\n\n\n\nfunc (r Response) String() string {\n\tj, _ := json.Marshal(r)\n\treturn fmt.Sprintf(\"Response: %s\", string(j))\n}\n\nfunc (r Response) WriteHttp(w http.ResponseWriter) (resp Response) {\n\tif r.StatusCode == 0 {\n\t\tr.StatusCode = 200\n\t}\n\tw.WriteHeader(r.StatusCode)\n\treturn EncodeJson(r, w)\n}\n\nfunc (r Response) WriteBadRequestHttp(w http.ResponseWriter) (resp Response) {\n\tw.WriteHeader(http.StatusBadRequest)\n\tr.StatusCode = http.StatusBadRequest\n\treturn EncodeJson(r, w)\n}\n\nfunc (r Response) WriteInternalServerErrorHttp(w http.ResponseWriter) (resp Response) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tr.StatusCode = http.StatusInternalServerError\n\treturn EncodeJson(r, w)\n}\n\nfunc EncodeJson(r Response, w http.ResponseWriter) (resp Response) {\n\terr := json.NewEncoder(w).Encode(r)\n\tif err != nil {\n\t\tlog.Printf(\"[writehttp] failed to create json from model: %s\", err.Error())\n\t}\n\treturn r\n}\n\nfunc (r Responses) String() string ", "output": "{\n\tj, _ := json.Marshal(r)\n\treturn fmt.Sprintf(\"Responses: %s\", string(j))\n}"} {"input": "package logger\n\nimport (\n\t\"testing\"\n\n\t\"github.com/golib/assert\"\n)\n\nfunc Test_Level_String(t *testing.T) {\n\tassertion := assert.New(t)\n\n\tfor level, s := range levels {\n\t\tassertion.Equal(s, level.String())\n\t}\n\n\tassertion.Equal(\"UNKNOWN\", lmin.String())\n\tassertion.Equal(\"UNKNOWN\", lmax.String())\n}\n\n\n\nfunc Test_Level_ResolveLevelByName(t *testing.T) ", "output": "{\n\tassertion := assert.New(t)\n\n\tfor level, name := range levels {\n\t\tassertion.Equal(level, ResolveLevelByName(name))\n\t}\n\n\tassertion.Equal(lmin, ResolveLevelByName(\"UNKNOWN\"))\n}"} {"input": "package gitlab\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/nlamirault/guzuta/utils\"\n)\n\nvar (\n\tnamespace = \"nicolas-lamirault\"\n\tname = \"scame\"\n\tdescription = \"An Emacs configuration\"\n)\n\n\n\nfunc TestRetrieveGitLabProjects(t *testing.T) {\n\tclient := getGitlabClient()\n\tprojects, _ := client.GetProjects()\n\tfor _, project := range *projects {\n\t\tpath := fmt.Sprintf(\"%s/%s\", namespace, project.Path)\n\t\tif !strings.HasPrefix(project.PathWithNamespace, path) {\n\t\t\tt.Fatalf(\"Invalid project name : %s %s\",\n\t\t\t\tproject.PathWithNamespace, path)\n\t\t}\n\t}\n}\n\n\n\n\n\n\n\n\n\n\nfunc TestRetrieveGitlabUnknownProject(t *testing.T) {\n\tclient := getGitlabClient()\n\t_, err := client.GetProject(namespace, \"aaaaaaaaaa\")\n\tif err == nil {\n\t\tt.Fatalf(\"No error with unknown username\")\n\t}\n}\n\nfunc getGitlabClient() *Client ", "output": "{\n\treturn NewClient(utils.Getenv(\"GUZUTA_GITLAB_TOKEN\"))\n}"} {"input": "package event\n\nimport (\n\t\"fmt\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\n\ntype Increment struct {\n\tName string\n\tValue int64\n}\n\nfunc (e *Increment) StatClass() string {\n\treturn \"counter\"\n}\n\n\nfunc (e *Increment) Update(e2 Event) error {\n\tif e.Type() != e2.Type() {\n\t\treturn fmt.Errorf(\"statsd event type conflict: %s vs %s \", e.String(), e2.String())\n\t}\n\tatomic.AddInt64(&e.Value, e2.Payload().(int64))\n\treturn nil\n}\n\n\nfunc (e *Increment) Reset() {\n\te.Value = 0\n}\n\n\nfunc (e Increment) Payload() interface{} {\n\treturn e.Value\n}\n\n\n\n\n\nfunc (e Increment) Key() string {\n\treturn e.Name\n}\n\n\nfunc (e *Increment) SetKey(key string) {\n\te.Name = key\n}\n\n\nfunc (e Increment) Type() int {\n\treturn EventIncr\n}\n\n\nfunc (e Increment) TypeString() string {\n\treturn \"Increment\"\n}\n\n\nfunc (e Increment) String() string {\n\treturn fmt.Sprintf(\"{Type: %s, Key: %s, Value: %d}\", e.TypeString(), e.Name, e.Value)\n}\n\nfunc (e Increment) Stats(tick time.Duration) []string ", "output": "{\n\treturn []string{fmt.Sprintf(\"%s:%d|c\", e.Name, e.Value)}\n}"} {"input": "package paths\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype Path struct {\n\tHome string\n\tConfig string\n\tData string\n\tLogs string\n}\n\n\n\ntype FileType string\n\nconst (\n\tHome FileType = \"home\"\n\tConfig FileType = \"config\"\n\tData FileType = \"data\"\n\tLogs FileType = \"logs\"\n)\n\n\n\nvar Paths = New()\n\n\nfunc New() *Path {\n\treturn &Path{}\n}\n\n\n\n\nfunc (paths *Path) InitPaths(cfg *Path) error {\n\terr := paths.initPaths(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.MkdirAll(paths.Data, 0755)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create data path %s: %v\", paths.Data, err)\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc InitPaths(cfg *Path) error {\n\treturn Paths.InitPaths(cfg)\n}\n\n\n\nfunc (paths *Path) initPaths(cfg *Path) error {\n\t*paths = *cfg\n\n\tif paths.Config == \"\" {\n\t\tpaths.Config = paths.Home\n\t}\n\n\tif paths.Data == \"\" {\n\t\tpaths.Data = filepath.Join(paths.Home, \"data\")\n\t}\n\n\tif paths.Logs == \"\" {\n\t\tpaths.Logs = filepath.Join(paths.Home, \"logs\")\n\t}\n\n\treturn nil\n}\n\n\n\n\n\n\n\n\n\nfunc Resolve(fileType FileType, path string) string {\n\treturn Paths.Resolve(fileType, path)\n}\n\n\nfunc (paths *Path) String() string {\n\treturn fmt.Sprintf(\"Home path: [%s] Config path: [%s] Data path: [%s] Logs path: [%s]\",\n\t\tpaths.Home, paths.Config, paths.Data, paths.Logs)\n}\n\nfunc (paths *Path) Resolve(fileType FileType, path string) string ", "output": "{\n\tif filepath.IsAbs(path) {\n\t\treturn path\n\t}\n\n\tswitch fileType {\n\tcase Home:\n\t\treturn filepath.Join(paths.Home, path)\n\tcase Config:\n\t\treturn filepath.Join(paths.Config, path)\n\tcase Data:\n\t\treturn filepath.Join(paths.Data, path)\n\tcase Logs:\n\t\treturn filepath.Join(paths.Logs, path)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Unknown file type: %s\", fileType))\n\t}\n}"} {"input": "package e2e\n\nimport (\n\t\"testing\"\n\t\"flag\"\n\n\t\"github.com/kubernetes-incubator/service-catalog/test/e2e/framework\"\n)\n\nvar brokerImageFlag string\n\nfunc init() {\n\tflag.StringVar(&brokerImageFlag, \"broker-image\", \"quay.io/kubernetes-service-catalog/user-broker:latest\",\n\t\t\"The container image for the broker to test against\")\n\tframework.RegisterParseFlags()\n}\n\n\n\nfunc TestE2E(t *testing.T) ", "output": "{\n\tRunE2ETests(t)\n}"} {"input": "package main \n\nimport (\n\t\"testing\" \n)\n\nfunc Benchmark_numberOfWaysToMake2Pounds(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tnumberOfWaysToMake2Pounds()\n\t}\n}\n\n\n\nfunc Benchmark_numberOfWaysToMakeX2(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tnumberOfWaysToMakeX2(200)\n\t}\n}\n\nfunc Benchmark_numberOfWaysToMakeX1(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tnumberOfWaysToMakeX1(200)\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/pivotal-golang/lager\"\n\t\"github.com/tedsuo/rata\"\n\n\t\"github.com/concourse/turbine\"\n\t\"github.com/concourse/turbine/api/abort\"\n\t\"github.com/concourse/turbine/api/check\"\n\t\"github.com/concourse/turbine/api/deletebuild\"\n\t\"github.com/concourse/turbine/api/events\"\n\t\"github.com/concourse/turbine/api/execute\"\n\t\"github.com/concourse/turbine/api/hijack\"\n\t\"github.com/concourse/turbine/resource\"\n\t\"github.com/concourse/turbine/scheduler\"\n)\n\n\n\nfunc New(\n\tlogger lager.Logger,\n\tscheduler scheduler.Scheduler,\n\ttracker resource.Tracker,\n\tturbineEndpoint string,\n\tdrain <-chan struct{},\n) (http.Handler, error) ", "output": "{\n\tcheckHandler := check.NewHandler(logger, tracker, drain)\n\n\thandlers := map[string]http.Handler{\n\t\tturbine.ExecuteBuild: execute.NewHandler(logger, scheduler, turbineEndpoint),\n\t\tturbine.DeleteBuild: deletebuild.NewHandler(logger, scheduler),\n\t\tturbine.AbortBuild: abort.NewHandler(logger, scheduler),\n\t\tturbine.HijackBuild: hijack.NewHandler(logger, scheduler),\n\t\tturbine.GetBuildEvents: events.NewHandler(logger, scheduler),\n\t\tturbine.CheckInput: checkHandler,\n\t\tturbine.CheckInputStream: http.HandlerFunc(checkHandler.Stream),\n\t}\n\n\treturn rata.NewRouter(turbine.Routes, handlers)\n}"} {"input": "package metrics_test\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/gkarlik/quark-go\"\n\t\"github.com/gkarlik/quark-go/metrics/prometheus\"\n\t\"github.com/gkarlik/quark-go/middleware/metrics\"\n\ttr \"github.com/gkarlik/quark-go/service/trace/noop\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype TestService struct {\n\t*quark.ServiceBase\n}\n\ntype TestHttpHandler struct{}\n\nfunc (h *TestHttpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"OK\"))\n}\n\n\n\nfunc TestMetricsMiddlewareWithNext(t *testing.T) {\n\ta, _ := quark.GetHostAddress(1234)\n\n\tts := &TestService{\n\t\tServiceBase: quark.NewService(\n\t\t\tquark.Name(\"TestService\"),\n\t\t\tquark.Version(\"1.0\"),\n\t\t\tquark.Address(a),\n\t\t\tquark.Metrics(prometheus.NewMetricsExposer()),\n\t\t\tquark.Tracer(tr.NewTracer())),\n\t}\n\tdefer ts.Dispose()\n\n\tmm := metrics.NewRequestMetricsMiddleware(ts)\n\tr, _ := http.NewRequest(http.MethodGet, \"/test\", nil)\n\tw := httptest.NewRecorder()\n\tth := &TestHttpHandler{}\n\tmm.HandleWithNext(w, r, th.ServeHTTP)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n}\n\nfunc TestMetricsMiddleware(t *testing.T) ", "output": "{\n\ta, _ := quark.GetHostAddress(1234)\n\n\tts := &TestService{\n\t\tServiceBase: quark.NewService(\n\t\t\tquark.Name(\"TestService\"),\n\t\t\tquark.Version(\"1.0\"),\n\t\t\tquark.Address(a),\n\t\t\tquark.Metrics(prometheus.NewMetricsExposer()),\n\t\t\tquark.Tracer(tr.NewTracer())),\n\t}\n\tdefer ts.Dispose()\n\n\tmm := metrics.NewRequestMetricsMiddleware(ts)\n\tr, _ := http.NewRequest(http.MethodGet, \"/test\", nil)\n\tw := httptest.NewRecorder()\n\th := mm.Handle(&TestHttpHandler{})\n\th.ServeHTTP(w, r)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n}"} {"input": "package bigquery\n\nimport (\n\t\"fmt\"\n\t\"github.com/viant/endly\"\n\t\"github.com/viant/endly/system/cloud/gcp\"\n\t\"google.golang.org/api/bigquery/v2\"\n)\n\nvar clientKey = (*CtxClient)(nil)\n\n\ntype CtxClient struct {\n\t*gcp.AbstractClient\n\tservice *bigquery.Service\n}\n\nfunc (s *CtxClient) SetService(service interface{}) error {\n\tvar ok bool\n\ts.service, ok = service.(*bigquery.Service)\n\tif !ok {\n\t\treturn fmt.Errorf(\"unable to set service: %T\", service)\n\t}\n\treturn nil\n}\n\n\n\nfunc InitRequest(context *endly.Context, rawRequest map[string]interface{}) error {\n\tconfig, err := gcp.InitCredentials(context, rawRequest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient, err := getClient(context)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgcp.UpdateActionRequest(rawRequest, config, client)\n\treturn nil\n}\n\nfunc getClient(context *endly.Context) (gcp.CtxClient, error) {\n\treturn GetClient(context)\n}\n\nfunc GetClient(context *endly.Context) (*CtxClient, error) {\n\tclient := &CtxClient{\n\t\tAbstractClient: &gcp.AbstractClient{},\n\t}\n\terr := gcp.GetClient(context, bigquery.New, clientKey, &client, bigquery.CloudPlatformScope, bigquery.BigqueryScope, bigquery.BigqueryInsertdataScope)\n\treturn client, err\n}\n\nfunc (s *CtxClient) Service() interface{} ", "output": "{\n\treturn s.service\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/gorilla/websocket\"\n)\n\ntype Client struct {\n\thub *Hub\n\tws *websocket.Conn\n\totherSide *Client\n\tchannelID uuid.UUID\n\tremoteType string\n\tparams map[string][]string\n\twmu sync.Mutex\n\trmu sync.Mutex\n}\n\nfunc (c *Client) WriteMessage(msgType int, message []byte) (err error) {\n\tc.wmu.Lock()\n\terr = c.ws.WriteMessage(msgType, message)\n\tc.wmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) NextWriter(msgType int) (w io.WriteCloser, err error) {\n\tc.wmu.Lock()\n\tw, err = c.ws.NextWriter(msgType)\n\tc.wmu.Unlock()\n\treturn\n}\n\n\n\nfunc (c *Client) NextReader() (msgType int, r io.Reader, err error) {\n\tc.rmu.Lock()\n\tmsgType, r, err = c.ws.NextReader()\n\tc.rmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) SetWriteDeadline(t time.Time) (err error) {\n\tc.wmu.Lock()\n\terr = c.ws.SetWriteDeadline(t)\n\tc.wmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) SetReadDeadline(t time.Time) (err error) {\n\tc.rmu.Lock()\n\terr = c.ws.SetReadDeadline(t)\n\tc.rmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) ReadMessage() (msgType int, message []byte, err error) ", "output": "{\n\tc.rmu.Lock()\n\tmsgType, message, err = c.ws.ReadMessage()\n\tc.rmu.Unlock()\n\treturn\n}"} {"input": "package google\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/resource\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\n\n\nfunc testAccCheckGoogleComputeZonesMeta(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Can't find zones data source: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn errors.New(\"zones data source ID not set.\")\n\t\t}\n\n\t\tcount, ok := rs.Primary.Attributes[\"names.#\"]\n\t\tif !ok {\n\t\t\treturn errors.New(\"can't find 'names' attribute\")\n\t\t}\n\n\t\tnoOfNames, err := strconv.Atoi(count)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"failed to read number of zones\")\n\t\t}\n\t\tif noOfNames < 2 {\n\t\t\treturn fmt.Errorf(\"expected at least 2 zones, received %d, this is most likely a bug\",\n\t\t\t\tnoOfNames)\n\t\t}\n\n\t\tfor i := 0; i < noOfNames; i++ {\n\t\t\tidx := \"names.\" + strconv.Itoa(i)\n\t\t\tv, ok := rs.Primary.Attributes[idx]\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"zone list is corrupt (%q not found), this is definitely a bug\", idx)\n\t\t\t}\n\t\t\tif len(v) < 1 {\n\t\t\t\treturn fmt.Errorf(\"Empty zone name (%q), this is definitely a bug\", idx)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nvar testAccCheckGoogleComputeZonesConfig = `\ndata \"google_compute_zones\" \"available\" {}\n`\n\nfunc TestAccComputeZones_basic(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccCheckGoogleComputeZonesConfig,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckGoogleComputeZonesMeta(\"data.google_compute_zones.available\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}"} {"input": "package memberlist\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\ntype Packet struct {\n\tBuf []byte\n\n\tFrom net.Addr\n\n\tTimestamp time.Time\n}\n\n\n\n\ntype Transport interface {\n\tFinalAdvertiseAddr(ip string, port int) (net.IP, int, error)\n\n\tWriteTo(b []byte, addr string) (time.Time, error)\n\n\tPacketCh() <-chan *Packet\n\n\tDialTimeout(addr string, timeout time.Duration) (net.Conn, error)\n\n\tStreamCh() <-chan net.Conn\n\n\tShutdown() error\n}\n\ntype Address struct {\n\tAddr string\n\n\tName string\n}\n\nfunc (a *Address) String() string {\n\tif a.Name != \"\" {\n\t\treturn fmt.Sprintf(\"%s (%s)\", a.Name, a.Addr)\n\t}\n\treturn a.Addr\n}\n\n\n\n\n\n\ntype IngestionAwareTransport interface {\n\tIngestPacket(conn net.Conn, addr net.Addr, now time.Time, shouldClose bool) error\n\tIngestStream(conn net.Conn) error\n}\n\ntype NodeAwareTransport interface {\n\tTransport\n\tWriteToAddress(b []byte, addr Address) (time.Time, error)\n\tDialAddressTimeout(addr Address, timeout time.Duration) (net.Conn, error)\n}\n\ntype shimNodeAwareTransport struct {\n\tTransport\n}\n\nvar _ NodeAwareTransport = (*shimNodeAwareTransport)(nil)\n\n\n\nfunc (t *shimNodeAwareTransport) DialAddressTimeout(addr Address, timeout time.Duration) (net.Conn, error) {\n\treturn t.DialTimeout(addr.Addr, timeout)\n}\n\nfunc (t *shimNodeAwareTransport) WriteToAddress(b []byte, addr Address) (time.Time, error) ", "output": "{\n\treturn t.WriteTo(b, addr.Addr)\n}"} {"input": "package k8sclient\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\t\"hash/fnv\"\n\t\"math/rand\"\n\t\"sync\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/google/uuid\"\n)\n\nvar (\n\tseedOnce sync.Once\n\tuuidMutex sync.Mutex\n)\n\nfunc GenerateUUID(seed string) string {\n\tvar stringUUID string\n\tuuidMutex.Lock()\n\tuuid.SetRand(rand.New(rand.NewSource(int64(hash(seed)))))\n\tstringUUID = uuid.New().String()\n\tuuidMutex.Unlock()\n\treturn stringUUID\n}\n\n\n\n\nfunc hash(valueOne interface{}) uint64 {\n\tnewHash := fnv.New64()\n\tnewHash.Write(getBytes(valueOne))\n\treturn newHash.Sum64()\n}\n\nfunc HashCombine(valueOne, valueTwo interface{}) uint64 {\n\tnewHash := fnv.New64()\n\tvalueOneBytes := getBytes(valueOne)\n\tvalueTwoBytes := getBytes(valueTwo)\n\tnewHash.Write(append(valueOneBytes, valueTwoBytes...))\n\treturn newHash.Sum64()\n}\n\nfunc getBytes(value interface{}) []byte ", "output": "{\n\tvar byteBuffer bytes.Buffer\n\tgobEncoder := gob.NewEncoder(&byteBuffer)\n\tif err := gobEncoder.Encode(value); err != nil {\n\t\tglog.Fatalln(\"Failed to encode value\")\n\t\treturn nil\n\t}\n\treturn byteBuffer.Bytes()\n}"} {"input": "package mock_concurrent\n\nimport (\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n)\n\n\ntype MockMath struct {\n\tctrl *gomock.Controller\n\trecorder *MockMathMockRecorder\n}\n\n\ntype MockMathMockRecorder struct {\n\tmock *MockMath\n}\n\n\nfunc NewMockMath(ctrl *gomock.Controller) *MockMath {\n\tmock := &MockMath{ctrl: ctrl}\n\tmock.recorder = &MockMathMockRecorder{mock}\n\treturn mock\n}\n\n\n\n\n\nfunc (m *MockMath) Sum(arg0, arg1 int) int {\n\tret := m.ctrl.Call(m, \"Sum\", arg0, arg1)\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}\n\n\nfunc (mr *MockMathMockRecorder) Sum(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Sum\", reflect.TypeOf((*MockMath)(nil).Sum), arg0, arg1)\n}\n\nfunc (m *MockMath) EXPECT() *MockMathMockRecorder ", "output": "{\n\treturn m.recorder\n}"} {"input": "package types\n\nimport \"testing\"\n\nfunc TestGzipText(t *testing.T) {\n\tg := GzippedText(\"Hello, world\")\n\tv, err := g.Value()\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\terr = (&g).Scan(v)\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\tif string(g) != \"Hello, world\" {\n\t\tt.Errorf(\"Was expecting the string we sent in (Hello World), got %s\", string(g))\n\t}\n}\n\nfunc TestJSONText(t *testing.T) {\n\tj := JSONText(`{\"foo\": 1, \"bar\": 2}`)\n\tv, err := j.Value()\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\terr = (&j).Scan(v)\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\tm := map[string]interface{}{}\n\tj.Unmarshal(&m)\n\n\tif m[\"foo\"].(float64) != 1 || m[\"bar\"].(float64) != 2 {\n\t\tt.Errorf(\"Expected valid json but got some garbage instead? %#v\", m)\n\t}\n\n\tj = JSONText(`{\"foo\": 1, invalid, false}`)\n\tv, err = j.Value()\n\tif err == nil {\n\t\tt.Errorf(\"Was expecting invalid json to fail!\")\n\t}\n}\n\n\n\nfunc TestBitBool(t *testing.T) ", "output": "{\n\tvar b BitBool = true\n\n\tv, err := b.Value()\n\tif err != nil {\n\t\tt.Errorf(\"Cannot return error\")\n\t}\n\terr = (&b).Scan(v)\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\tif !b {\n\t\tt.Errorf(\"Was expecting the bool we sent in (true), got %b\", b)\n\t}\n\n\tb = false\n\n\tv, err = b.Value()\n\tif err != nil {\n\t\tt.Errorf(\"Cannot return error\")\n\t}\n\terr = (&b).Scan(v)\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\tif b {\n\t\tt.Errorf(\"Was expecting the bool we sent in (false), got %b\", b)\n\t}\n}"} {"input": "package tasks\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime/middleware\"\n\t\"github.com/go-openapi/swag\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewDeleteTaskParams() DeleteTaskParams {\n\tvar ()\n\treturn DeleteTaskParams{}\n}\n\n\n\n\n\ntype DeleteTaskParams struct {\n\n\tHTTPRequest *http.Request\n\n\tID int64\n}\n\n\n\n\n\nfunc (o *DeleteTaskParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error {\n\tvar raw string\n\tif len(rawData) > 0 {\n\t\traw = rawData[len(rawData)-1]\n\t}\n\n\tvalue, err := swag.ConvertInt64(raw)\n\tif err != nil {\n\t\treturn errors.InvalidType(\"id\", \"path\", \"int64\", raw)\n\t}\n\to.ID = value\n\n\treturn nil\n}\n\nfunc (o *DeleteTaskParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error ", "output": "{\n\tvar res []error\n\to.HTTPRequest = r\n\n\trID, rhkID, _ := route.Params.GetOK(\"id\")\n\tif err := o.bindID(rID, rhkID, route.Formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package permutation\n\n\nimport \"C\"\n\nimport (\n\t\"github.com/dtromb/gogsl\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\nfunc (p *GslPermutation) Len() int {\n\treturn int(C.get_permutation_size((*C.gsl_permutation)(unsafe.Pointer(p.Ptr()))))\n}\n\n\n\nfunc (p *GslPermutation) Slice_() interface{} ", "output": "{\n\tbaseType := gogsl.GOGSL_SIZE_T_TYPE\n\tsliceType := reflect.SliceOf(baseType)\n\tsize := p.Len()\n\thdr := &reflect.SliceHeader{Len: size, Cap: size, Data: uintptr(C.get_permutation_data((*C.gsl_permutation)(unsafe.Pointer(p.Ptr()))))}\n\treturn reflect.NewAt(sliceType, unsafe.Pointer(hdr)).Elem().Interface()\n}"} {"input": "package trace\n\nimport (\n\t\"github.com/golang/groupcache/lru\"\n)\n\n\n\ntype lruMap struct {\n\tcacheKeys map[lru.Key]bool\n\tcache *lru.Cache\n\tdroppedCount int\n}\n\nfunc newLruMap(size int) *lruMap {\n\tlm := &lruMap{\n\t\tcacheKeys: make(map[lru.Key]bool),\n\t\tcache: lru.New(size),\n\t\tdroppedCount: 0,\n\t}\n\tlm.cache.OnEvicted = func(key lru.Key, value interface{}) {\n\t\tdelete(lm.cacheKeys, key)\n\t\tlm.droppedCount++\n\t}\n\treturn lm\n}\n\nfunc (lm lruMap) len() int {\n\treturn lm.cache.Len()\n}\n\n\n\nfunc (lm *lruMap) add(key, value interface{}) {\n\tlm.cacheKeys[lru.Key(key)] = true\n\tlm.cache.Add(lru.Key(key), value)\n}\n\nfunc (lm *lruMap) get(key interface{}) (interface{}, bool) {\n\treturn lm.cache.Get(key)\n}\n\nfunc (lm lruMap) keys() []interface{} ", "output": "{\n\tkeys := []interface{}{}\n\tfor k := range lm.cacheKeys {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}"} {"input": "package matchers\n\nimport (\n\t\"github.com/nttlabs/cli/cf/errors\"\n\ttestcmd \"github.com/nttlabs/cli/testhelpers/commands\"\n\t\"github.com/onsi/gomega\"\n)\n\ntype havePassedRequirementsMatcher struct{}\n\n\n\nfunc (matcher havePassedRequirementsMatcher) Match(actual interface{}) (bool, error) {\n\tswitch actual.(type) {\n\tcase bool:\n\t\tasBool := actual.(bool)\n\t\treturn asBool == true, nil\n\tcase testcmd.RunCommandResult:\n\t\tresult := actual.(testcmd.RunCommandResult)\n\t\treturn result == testcmd.RunCommandResultSuccess, nil\n\tdefault:\n\t\treturn false, errors.NewWithFmt(\"Expected actual value to be a bool or enum, but it was a %T\", actual)\n\t}\n}\n\nfunc (matcher havePassedRequirementsMatcher) FailureMessage(_ interface{}) string {\n\treturn \"Expected command to pass requirements but it did not\"\n}\n\nfunc (matcher havePassedRequirementsMatcher) NegatedFailureMessage(_ interface{}) string {\n\treturn \"Expected command to have not passed requirements but it did\"\n}\n\nfunc HavePassedRequirements() gomega.OmegaMatcher ", "output": "{\n\treturn havePassedRequirementsMatcher{}\n}"} {"input": "package utils\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\tirc \"gopkg.in/irc.v3\"\n)\n\n\n\ntype TestClientServer struct {\n\tclient *bytes.Buffer\n\tserver *bytes.Buffer\n}\n\n\nfunc NewTestClientServer() *TestClientServer {\n\treturn &TestClientServer{\n\t\tclient: &bytes.Buffer{},\n\t\tserver: &bytes.Buffer{},\n\t}\n}\n\n\nfunc (cs *TestClientServer) Read(p []byte) (int, error) {\n\treturn cs.server.Read(p)\n}\n\n\n\n\n\n\nfunc (cs *TestClientServer) SendServerLines(lines []string) {\n\tw := irc.NewWriter(cs.server)\n\n\tfor _, line := range lines {\n\t\tw.WriteMessage(irc.MustParseMessage(line))\n\t}\n}\n\n\n\n\nfunc (cs *TestClientServer) CheckLines(t *testing.T, expected []string) bool {\n\tok := true\n\n\tlines := strings.Split(cs.client.String(), \"\\r\\n\")\n\n\tvar line, clientLine string\n\tfor len(expected) > 0 && len(lines) > 0 {\n\t\tline, expected = expected[0], expected[1:]\n\t\tclientLine, lines = lines[0], lines[1:]\n\n\t\tok = ok && assert.Equal(t, line, clientLine)\n\t}\n\n\tok = ok && assert.Equal(t, 0, len(expected), \"Not enough lines: %s\", strings.Join(expected, \", \"))\n\tok = ok && assert.Equal(t, 0, len(lines), \"Extra non-empty lines: %s\", strings.Join(lines, \", \"))\n\n\treturn ok\n}\n\n\nfunc (cs *TestClientServer) Reset() {\n\tcs.client.Reset()\n\tcs.server.Reset()\n}\n\nfunc (cs *TestClientServer) Write(p []byte) (int, error) ", "output": "{\n\treturn cs.client.Write(p)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\nvar (\n\tcmdAuth = &Command{\n\t\tName: \"auth\",\n\t\tRun: RunAuth,\n\t\tShort: \"auth LOGIN\",\n\t\tDescription: \"authenticate user\",\n\t\tEnabled: false,\n\t}\n)\n\n\n\n\nfunc RunAuth(args []string) error ", "output": "{\n\tfmt.Println(\"hello from auth command\")\n\treturn nil\n}"} {"input": "package api\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\n\n\n\n\nfunc Load(api, docs, paginators, waiters string) *API {\n\ta := API{}\n\ta.Attach(api)\n\ta.Attach(docs)\n\ta.Attach(paginators)\n\ta.Attach(waiters)\n\ta.Setup()\n\treturn &a\n}\n\n\n\n\n\n\n\nfunc (a *API) AttachString(str string) {\n\tjson.Unmarshal([]byte(str), a)\n\n\tif !a.initialized {\n\t\ta.Setup()\n\t}\n}\n\n\nfunc (a *API) Setup() {\n\ta.unrecognizedNames = map[string]string{}\n\ta.writeShapeNames()\n\ta.resolveReferences()\n\ta.fixStutterNames()\n\ta.renameExportable()\n\ta.renameToplevelShapes()\n\ta.updateTopLevelShapeReferences()\n\ta.createInputOutputShapes()\n\ta.customizationPasses()\n\n\tif !a.NoRemoveUnusedShapes {\n\t\ta.removeUnusedShapes()\n\t}\n\n\tif len(a.unrecognizedNames) > 0 {\n\t\tmsg := []string{\n\t\t\t\"Unrecognized inflections for the following export names:\",\n\t\t\t\"(Add these to inflections.csv with any inflections added after the ':')\",\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"%s\\n%s\\n\\n\", msg[0], msg[1])\n\t\tfor n, m := range a.unrecognizedNames {\n\t\t\tif n == m {\n\t\t\t\tm = \"\"\n\t\t\t}\n\t\t\tfmt.Fprintf(os.Stderr, \"%s:%s\\n\", n, m)\n\t\t}\n\t\tos.Stderr.WriteString(\"\\n\\n\")\n\t\tpanic(\"Found unrecognized exported names in API \" + a.PackageName())\n\t}\n\n\ta.initialized = true\n}\n\nfunc (a *API) Attach(filename string) ", "output": "{\n\ta.path = filepath.Dir(filename)\n\tf, err := os.Open(filename)\n\tdefer f.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjson.NewDecoder(f).Decode(a)\n}"} {"input": "package smartest\n\nimport (\n \"testing\"\n \"os\"\n)\n\n\n\nfunc TestCheckCleanTest(t *testing.T) ", "output": "{\n if _, err := os.Stat(\"1.log\"); err == nil { t.Error(\"dirty test\") }\n if _, err := os.Stat(\"2.log\"); err == nil { t.Error(\"dirty test\") }\n if _, err := os.Stat(\"hello\"); err == nil { t.Error(\"dirty test\") }\n if _, err := os.Stat(\"main.o\"); err == nil { t.Error(\"dirty test\") }\n if _, err := os.Stat(\"src/foo.o\"); err == nil { t.Error(\"dirty test\") }\n if _, err := os.Stat(\"src/bar.o\"); err == nil { t.Error(\"dirty test\") }\n if _, err := os.Stat(\"src/baz.o\"); err == nil { t.Error(\"dirty test\") }\n}"} {"input": "package redis\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) BaseClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient ", "output": "{\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package disk\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/vslm\"\n)\n\ntype register struct {\n\t*flags.DatastoreFlag\n}\n\n\n\nfunc (cmd *register) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)\n\tcmd.DatastoreFlag.Register(ctx, f)\n}\n\nfunc (cmd *register) Usage() string {\n\treturn \"PATH [NAME]\"\n}\n\nfunc (cmd *register) Description() string {\n\treturn `Register existing disk on DS.\n\nExamples:\n govc disk.register disks/disk1.vmdk my-disk`\n}\n\nfunc (cmd *register) Run(ctx context.Context, f *flag.FlagSet) error {\n\tds, err := cmd.Datastore()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm := vslm.NewObjectManager(ds.Client())\n\n\tpath := ds.NewURL(f.Arg(0)).String()\n\n\tobj, err := m.RegisterDisk(ctx, path, f.Arg(1))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(obj.Config.Id.Id)\n\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tcli.Register(\"disk.register\", ®ister{})\n}"} {"input": "package connectivity\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth\"\n\t\"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials\"\n\n\t\"github.com/denverdino/aliyungo/common\"\n)\n\n\ntype Config struct {\n\tAccessKey string\n\tSecretKey string\n\tRegion common.Region\n\tRegionId string\n\tSecurityToken string\n\tOtsInstanceName string\n\tLogEndpoint string\n\tAccountId string\n\tFcEndpoint string\n\tMNSEndpoint string\n}\n\nfunc (c *Config) loadAndValidate() error {\n\terr := c.validateRegion()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *Config) getAuthCredential(stsSupported bool) auth.Credential {\n\tif stsSupported {\n\t\treturn credentials.NewStsTokenCredential(c.AccessKey, c.SecretKey, c.SecurityToken)\n\t}\n\n\treturn credentials.NewAccessKeyCredential(c.AccessKey, c.SecretKey)\n}\n\nfunc (c *Config) validateRegion() error ", "output": "{\n\n\tfor _, valid := range common.ValidRegions {\n\t\tif c.Region == valid {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"Not a valid region: %s\", c.Region)\n}"} {"input": "package operations\n\n\n\nimport (\n\t\"github.com/denkhaus/bitshares/types\"\n\t\"github.com/denkhaus/bitshares/util\"\n\t\"github.com/juju/errors\"\n)\n\n\n\ntype TransferFromBlindOperation struct {\n\ttypes.OperationFee\n\tAmount types.AssetAmount `json:\"amount\"`\n\tTo types.AccountID `json:\"to\"`\n\tBlindFactor types.FixedBuffer `json:\"blinding_factor\"`\n\tBlindInputs types.BlindInputs `json:\"inputs\"`\n}\n\nfunc (p TransferFromBlindOperation) Type() types.OperationType {\n\treturn types.OperationTypeTransferFromBlind\n}\n\nfunc (p TransferFromBlindOperation) Marshal(enc *util.TypeEncoder) error {\n\tif err := enc.Encode(int8(p.Type())); err != nil {\n\t\treturn errors.Annotate(err, \"encode OperationType\")\n\t}\n\tif err := enc.Encode(p.Fee); err != nil {\n\t\treturn errors.Annotate(err, \"encode Fee\")\n\t}\n\tif err := enc.Encode(p.Amount); err != nil {\n\t\treturn errors.Annotate(err, \"encode Amount\")\n\t}\n\tif err := enc.Encode(p.To); err != nil {\n\t\treturn errors.Annotate(err, \"encode To\")\n\t}\n\tif err := enc.Encode(p.BlindFactor); err != nil {\n\t\treturn errors.Annotate(err, \"encode BlindFactor\")\n\t}\n\tif err := enc.Encode(p.BlindInputs); err != nil {\n\t\treturn errors.Annotate(err, \"encode BlindInputs\")\n\t}\n\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\ttypes.OperationMap[types.OperationTypeTransferFromBlind] = func() types.Operation {\n\t\top := &TransferFromBlindOperation{}\n\t\treturn op\n\t}\n}"} {"input": "package session\n\nimport (\n \"github.com/wpxiong/beargo/log\"\n \"sync\"\n)\n\n\n\n\ntype SessionProvider interface {\n InitProvider(SessionLifeTime int64)\n CreateSession(sessionId string) (Session, error)\n DeleteSession(sessionId string) error\n FindSessionById(sessionId string) bool\n LoadSessionById(sessionId string) (Session ,error)\n SerializeSession()\n DeserializeSession()\n ClearSession(sessionAccess *sync.Mutex)\n DeseriazeObject (valueId string,bytearray []byte, obj interface{},sess *Session) bool\n}\n\nfunc init() ", "output": "{\n log.InitLog()\n}"} {"input": "package transformers\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"sigs.k8s.io/kustomize/pkg/resmap\"\n\t\"sigs.k8s.io/kustomize/pkg/transformers/config\"\n)\n\n\ntype mapTransformer struct {\n\tm map[string]string\n\tfieldSpecs []config.FieldSpec\n}\n\nvar _ Transformer = &mapTransformer{}\n\n\nfunc NewLabelsMapTransformer(\n\tm map[string]string, fs []config.FieldSpec) (Transformer, error) {\n\treturn NewMapTransformer(fs, m)\n}\n\n\nfunc NewAnnotationsMapTransformer(\n\tm map[string]string, fs []config.FieldSpec) (Transformer, error) {\n\treturn NewMapTransformer(fs, m)\n}\n\n\nfunc NewMapTransformer(\n\tpc []config.FieldSpec, m map[string]string) (Transformer, error) {\n\tif m == nil {\n\t\treturn NewNoOpTransformer(), nil\n\t}\n\tif pc == nil {\n\t\treturn nil, errors.New(\"fieldSpecs is not expected to be nil\")\n\t}\n\treturn &mapTransformer{fieldSpecs: pc, m: m}, nil\n}\n\n\n\n\n\nfunc (o *mapTransformer) addMap(in interface{}) (interface{}, error) {\n\tm, ok := in.(map[string]interface{})\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%#v is expected to be %T\", in, m)\n\t}\n\tfor k, v := range o.m {\n\t\tm[k] = v\n\t}\n\treturn m, nil\n}\n\nfunc (o *mapTransformer) Transform(m resmap.ResMap) error ", "output": "{\n\tfor id := range m {\n\t\tobjMap := m[id].Map()\n\t\tfor _, path := range o.fieldSpecs {\n\t\t\tif !id.Gvk().IsSelected(&path.Gvk) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr := mutateField(objMap, path.PathSlice(), path.CreateIfNotPresent, o.addMap)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package godo\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestImageActions_ImageActionsServiceOpImplementsImageActionsService(t *testing.T) {\n\tif !Implements((*ImageActionsService)(nil), new(ImageActionsServiceOp)) {\n\t\tt.Error(\"ImageActionsServiceOp does not implement ImageActionsService\")\n\t}\n}\n\nfunc TestImageActions_Transfer(t *testing.T) {\n\tsetup()\n\tdefer teardown()\n\n\ttransferRequest := &ActionRequest{}\n\n\tmux.HandleFunc(\"/v2/images/12345/actions\", func(w http.ResponseWriter, r *http.Request) {\n\t\tv := new(ActionRequest)\n\t\tjson.NewDecoder(r.Body).Decode(v)\n\n\t\ttestMethod(t, r, \"POST\")\n\t\tif !reflect.DeepEqual(v, transferRequest) {\n\t\t\tt.Errorf(\"Request body = %+v, expected %+v\", v, transferRequest)\n\t\t}\n\n\t\tfmt.Fprintf(w, `{\"action\":{\"status\":\"in-progress\"}}`)\n\n\t})\n\n\ttransfer, _, err := client.ImageActions.Transfer(12345, transferRequest)\n\tif err != nil {\n\t\tt.Errorf(\"ImageActions.Transfer returned error: %v\", err)\n\t}\n\n\texpected := &Action{Status: \"in-progress\"}\n\tif !reflect.DeepEqual(transfer, expected) {\n\t\tt.Errorf(\"ImageActions.Transfer returned %+v, expected %+v\", transfer, expected)\n\t}\n}\n\n\n\nfunc TestImageActions_Get(t *testing.T) ", "output": "{\n\tsetup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"/v2/images/123/actions/456\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tfmt.Fprintf(w, `{\"action\":{\"status\":\"in-progress\"}}`)\n\t})\n\n\taction, _, err := client.ImageActions.Get(123, 456)\n\tif err != nil {\n\t\tt.Errorf(\"ImageActions.Get returned error: %v\", err)\n\t}\n\n\texpected := &Action{Status: \"in-progress\"}\n\tif !reflect.DeepEqual(action, expected) {\n\t\tt.Errorf(\"ImageActions.Get returned %+v, expected %+v\", action, expected)\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CopyVolumeGroupBackupRequest struct {\n\n\tVolumeGroupBackupId *string `mandatory:\"true\" contributesTo:\"path\" name:\"volumeGroupBackupId\"`\n\n\tCopyVolumeGroupBackupDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CopyVolumeGroupBackupRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CopyVolumeGroupBackupRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CopyVolumeGroupBackupRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CopyVolumeGroupBackupRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CopyVolumeGroupBackupResponse struct {\n\n\tRawResponse *http.Response\n\n\tVolumeGroupBackup `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response CopyVolumeGroupBackupResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response CopyVolumeGroupBackupResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package policy\n\nimport (\n\t\"testing\"\n)\n\nfunc TestEffectIsAllowed(t *testing.T) {\n\ttestCases := []struct {\n\t\teffect Effect\n\t\tcheck bool\n\t\texpectedResult bool\n\t}{\n\t\t{Allow, false, false},\n\t\t{Allow, true, true},\n\t\t{Deny, false, true},\n\t\t{Deny, true, false},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tresult := testCase.effect.IsAllowed(testCase.check)\n\n\t\tif result != testCase.expectedResult {\n\t\t\tt.Fatalf(\"case %v: expected: %v, got: %v\\n\", i+1, testCase.expectedResult, result)\n\t\t}\n\t}\n\n}\n\n\n\nfunc TestEffectIsValid(t *testing.T) ", "output": "{\n\ttestCases := []struct {\n\t\teffect Effect\n\t\texpectedResult bool\n\t}{\n\t\t{Allow, true},\n\t\t{Deny, true},\n\t\t{Effect(\"\"), false},\n\t\t{Effect(\"foo\"), false},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tresult := testCase.effect.IsValid()\n\n\t\tif result != testCase.expectedResult {\n\t\t\tt.Fatalf(\"case %v: expected: %v, got: %v\\n\", i+1, testCase.expectedResult, result)\n\t\t}\n\t}\n}"} {"input": "package dao\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc TestDaotypesURI(t *testing.T) {\n\tconvey.Convey(\"typesURI\", t, func(ctx convey.C) {\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\tp1 := testDao.typesURI()\n\t\t\tctx.Convey(\"Then p1 should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(p1, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}\n\n\n\nfunc TestDaoTypeMapping(t *testing.T) ", "output": "{\n\tconvey.Convey(\"TypeMapping\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\trmap, err := testDao.TypeMapping(c)\n\t\t\tctx.Convey(\"Then err should be nil.rmap should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t\tctx.So(rmap, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package runcmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t\"github.com/visualfc/gotools/pkg/command\"\n)\n\nvar Command = &command.Command{\n\tRun: runCmd,\n\tUsageLine: \"runcmd [-w work_path] [arguments...]\",\n\tShort: \"run program\",\n\tLong: `run program and arguments`,\n}\n\nvar execWorkPath string\nvar execWaitEnter bool\n\nfunc init() {\n\tCommand.Flag.StringVar(&execWorkPath, \"w\", \"\", \"work path\")\n\tCommand.Flag.BoolVar(&execWaitEnter, \"e\", true, \"wait enter and continue\")\n}\n\nfunc runCmd(cmd *command.Command, args []string) error {\n\tif len(args) == 0 {\n\t\tcmd.Usage()\n\t\treturn os.ErrInvalid\n\t}\n\tif execWorkPath == \"\" {\n\t\tvar err error\n\t\texecWorkPath, err = os.Getwd()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfileName := args[0]\n\n\tfilePath, err := exec.LookPath(fileName)\n\tif err != nil {\n\t\tfilePath, err = exec.LookPath(\"./\" + fileName)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Starting Process\", filePath, strings.Join(args[1:], \" \"), \"...\")\n\n\tcommand := exec.Command(filePath, args[1:]...)\n\tcommand.Dir = execWorkPath\n\tcommand.Stdin = os.Stdin\n\tcommand.Stdout = os.Stdout\n\tcommand.Stderr = os.Stderr\n\n\terr = command.Run()\n\n\tif err != nil {\n\t\tfmt.Println(\"\\nEnd Process\", err)\n\t} else {\n\t\tfmt.Println(\"\\nEnd Process\", \"exit status 0\")\n\t}\n\n\texitWaitEnter()\n\treturn nil\n}\n\n\n\nfunc exitWaitEnter() ", "output": "{\n\tif !execWaitEnter {\n\t\treturn\n\t}\n\tfmt.Println(\"\\nPress enter key to continue\")\n\tvar s = [256]byte{}\n\tos.Stdin.Read(s[:])\n}"} {"input": "package minicon\n\nimport \"container/ring\"\n\n\n\n\ntype History struct {\n\tr *ring.Ring\n}\n\n\n\n\ntype HistoryMarker *ring.Ring\n\n\n\n\nfunc NewHistory(capacity int) *History {\n\treturn &History{ring.New(capacity)}\n}\n\n\n\n\n\n\nfunc (hs *History) Add(s string, mark HistoryMarker) HistoryMarker {\n\ths.Restore(mark)\n\tif s != \"\" && hs.r.Value != s {\n\t\ths.r.Value = s\n\t\ths.r = hs.r.Next()\n\t}\n\treturn nil\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (hs *History) Forward() (string, bool) {\n\treturn hs._update(hs.r.Next())\n}\n\n\n\n\nfunc (hs *History) Mark() HistoryMarker {\n\treturn hs.r\n}\n\n\n\n\nfunc (hs *History) Restore(mark HistoryMarker) {\n\tif mark != nil {\n\t\ths.r = mark\n\t}\n}\n\n\n\n\nfunc (hs *History) _update(r *ring.Ring) (ret string, okay bool) {\n\tif s, ok := r.Value.(string); ok && s != \"\" {\n\t\ths.r = r\n\t\tret, okay = s, ok\n\t}\n\treturn ret, okay\n}\n\nfunc (hs *History) Back() (string, bool) ", "output": "{\n\treturn hs._update(hs.r.Prev())\n}"} {"input": "package logs\n\nconst (\n\tErrorLevel = iota\n\tWarnLevel\n\tInfoLevel\n\tDebugLevel\n)\n\ntype Level uint32\n\nfunc (l Level) EQ(lv Level) bool {\n\tif l == lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) LTE(lv Level) bool {\n\tif l <= lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) LT(lv Level) bool {\n\tif l < lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) GTE(lv Level) bool {\n\tif l >= lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) GT(lv Level) bool {\n\tif l > lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc (l Level) String() string {\n\tswitch l {\n\tcase DebugLevel:\n\t\treturn \"DEBU\"\n\tcase InfoLevel:\n\t\treturn \"INFO\"\n\tcase WarnLevel:\n\t\treturn \"WARN\"\n\tcase ErrorLevel:\n\t\treturn \"ERRO\"\n\t}\n\treturn \" \"\n}\n\nfunc (l Level) Color() int ", "output": "{\n\tvar levelColor int\n\tswitch l {\n\tcase DebugLevel:\n\t\tlevelColor = 32\n\tcase InfoLevel:\n\t\tlevelColor = 36\n\tcase WarnLevel:\n\t\tlevelColor = 33\n\tcase ErrorLevel:\n\t\tlevelColor = 31\n\tdefault:\n\t\tlevelColor = 0\n\t}\n\treturn levelColor\n}"} {"input": "package godo\n\nimport(\n\t\"github.com/jmoiron/modl\"\n\t\"database/sql\"\n\t_ \"github.com/mattn/go-sqlite3\"\n\t\"log\"\n)\n\nvar Dbmap *modl.DbMap\n\n\n\nfunc CheckErr(err error, msg string) {\n\tif err != nil {\n\t\tlog.Fatalln(msg, err)\n\t}\n}\n\nfunc ResetDatabase() {\n\tDbmap.TruncateTables()\n}\n\nfunc InitDb(dbname string) *modl.DbMap ", "output": "{\n\tdb, err := sql.Open(\"sqlite3\", \"/tmp/\"+dbname)\n\tCheckErr(err, \"sql.Open failed\")\n\n\tdbmap := modl.NewDbMap(db, modl.SqliteDialect{})\n\n\tdbmap.AddTableWithName(Task{}, \"tasks\").SetKeys(true, \"ID\")\n\tdbmap.AddTableWithName(Project{}, \"projects\").SetKeys(true, \"ID\")\n\tDbmap = dbmap\n\n\terr = dbmap.CreateTablesIfNotExists()\n\tCheckErr(err, \"Create tables failed\")\n\n\treturn dbmap\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/signal\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n)\n\ntype threadSafePrintliner struct {\n\tl sync.Mutex\n\tw io.Writer\n}\n\n\n\nfunc (p *threadSafePrintliner) println(s string) {\n\tp.l.Lock()\n\tfmt.Fprintln(p.w, s)\n\tp.l.Unlock()\n}\n\nfunc readQuery(r io.Reader) string {\n\ts, _ := ioutil.ReadAll(r) \n\treturn strings.TrimSpace(strings.Replace(string(s), \"\\n\", \" \", -1))\n}\n\nfunc trimEmpty(s []string) []string {\n\tvar r = make([]string, 0)\n\tfor _, str := range s {\n\t\tif str != \"\" {\n\t\t\tr = append(r, str)\n\t\t}\n\t}\n\treturn r\n}\n\nfunc awaitSignal(cancel context.CancelFunc) {\n\tsignals := make(chan os.Signal)\n\tsignal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)\n\t<-signals\n\tcancel()\n}\n\nfunc newThreadSafePrintliner(w io.Writer) *threadSafePrintliner ", "output": "{\n\treturn &threadSafePrintliner{w: w}\n}"} {"input": "package martini\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"runtime/debug\"\n)\n\nconst (\n\tpanicHtml = `\nPANIC: %s\n\n\n

PANIC

\n
%s
\n
%s
\n\n`\n)\n\n\n\n\n\nfunc Recovery() Handler ", "output": "{\n\treturn func(res http.ResponseWriter, c Context, log *log.Logger) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tres.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tlog.Printf(\"PANIC: %s\\n%s\", err, debug.Stack())\n\n\t\t\t\tif Env == Dev {\n\t\t\t\t\tres.Write([]byte(fmt.Sprintf(panicHtml, err, err, debug.Stack())))\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\tc.Next()\n\t}\n}"} {"input": "package leetcode\n\n\n\nfunc minMoves(nums []int) int ", "output": "{\n\tsum, min := 0, (1<<31 - 1)\n\tfor _, num := range nums {\n\t\tif min > num {\n\t\t\tmin = num\n\t\t}\n\t\tsum += num\n\t}\n\treturn sum - len(nums)*min\n}"} {"input": "package sidekick\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\ntype stringSlice []string\n\nfunc (ss stringSlice) String() string { return strings.Join(ss, \",\") }\nfunc (ss *stringSlice) Set(s string) error { *ss = append(*ss, s); return nil }\n\nvar (\n\tDebug bool\n\n\tskips stringSlice\n\tcases stringSlice\n)\n\nfunc init() {\n\tflag.Var(&skips, \"skip\", \"skip test case\")\n\tflag.Var(&cases, \"case\", \"run test case\")\n\tflag.BoolVar(&Debug, \"debug\", false, \"enter debug mode\")\n\n\tlog.SetFlags(log.Lshortfile | log.LstdFlags)\n}\n\n\n\n\n\n\nfunc SkipCase(c interface{}) bool ", "output": "{\n\tfor _, item := range skips {\n\t\tif item == fmt.Sprint(c) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tfor _, item := range cases {\n\t\tif item == fmt.Sprint(c) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif len(cases) > 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\n\n\ntype PatchDetails struct {\n\n\tAction PatchDetailsActionEnum `mandatory:\"false\" json:\"action,omitempty\"`\n\n\tPatchId *string `mandatory:\"false\" json:\"patchId\"`\n}\n\n\n\n\ntype PatchDetailsActionEnum string\n\n\nconst (\n\tPatchDetailsActionApply PatchDetailsActionEnum = \"APPLY\"\n\tPatchDetailsActionPrecheck PatchDetailsActionEnum = \"PRECHECK\"\n)\n\nvar mappingPatchDetailsAction = map[string]PatchDetailsActionEnum{\n\t\"APPLY\": PatchDetailsActionApply,\n\t\"PRECHECK\": PatchDetailsActionPrecheck,\n}\n\n\nfunc GetPatchDetailsActionEnumValues() []PatchDetailsActionEnum {\n\tvalues := make([]PatchDetailsActionEnum, 0)\n\tfor _, v := range mappingPatchDetailsAction {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}\n\nfunc (m PatchDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package swagger\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n)\n\nfunc (prop *ModelProperty) setDescription(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"description\"); tag != \"\" {\n\t\tprop.Description = tag\n\t}\n}\n\nfunc (prop *ModelProperty) setDefaultValue(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"default\"); tag != \"\" {\n\t\tprop.DefaultValue = Special(tag)\n\t}\n}\n\nfunc (prop *ModelProperty) setEnumValues(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"enum\"); tag != \"\" {\n\t\tprop.Enum = strings.Split(tag, \"|\")\n\t}\n}\n\nfunc (prop *ModelProperty) setMaximum(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"maximum\"); tag != \"\" {\n\t\tprop.Maximum = tag\n\t}\n}\n\nfunc (prop *ModelProperty) setMinimum(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"minimum\"); tag != \"\" {\n\t\tprop.Minimum = tag\n\t}\n}\n\n\n\nfunc (prop *ModelProperty) setPropertyMetadata(field reflect.StructField) {\n\tprop.setDescription(field)\n\tprop.setEnumValues(field)\n\tprop.setMinimum(field)\n\tprop.setMaximum(field)\n\tprop.setUniqueItems(field)\n\tprop.setDefaultValue(field)\n}\n\nfunc (prop *ModelProperty) setUniqueItems(field reflect.StructField) ", "output": "{\n\ttag := field.Tag.Get(\"unique\")\n\tswitch tag {\n\tcase \"true\":\n\t\tv := true\n\t\tprop.UniqueItems = &v\n\tcase \"false\":\n\t\tv := false\n\t\tprop.UniqueItems = &v\n\t}\n}"} {"input": "package logging\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype ServiceSummary struct {\n\n\tTenantId *string `mandatory:\"true\" json:\"tenantId\"`\n\n\tServicePrincipalName *string `mandatory:\"true\" json:\"servicePrincipalName\"`\n\n\tEndpoint *string `mandatory:\"true\" json:\"endpoint\"`\n\n\tName *string `mandatory:\"true\" json:\"name\"`\n\n\tResourceTypes []ResourceType `mandatory:\"true\" json:\"resourceTypes\"`\n\n\tNamespace *string `mandatory:\"false\" json:\"namespace\"`\n\n\tId *string `mandatory:\"false\" json:\"id\"`\n}\n\n\n\nfunc (m ServiceSummary) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package analyzer\n\nimport (\n . \"github.com/levythu/gurgling\"\n \"time\"\n \"fmt\"\n \"strconv\"\n)\n\n\n\ntype SimpleAnalyzer struct {\n \n}\n\nfunc ASimpleAnalyzer() Sandwich {\n return &SimpleAnalyzer{}\n}\n\nconst token_returncode=\"SimpleAnalyzer-Status-Code\"\nconst token_starttime=\"SimpleAnalyzer-Start-Time\"\n\nfunc logCode(res Response, c int) {\n res.F()[token_returncode]=c\n}\n\n\nfunc (this *SimpleAnalyzer)Final(req Request, res Response) {\n var timeStart, ok=res.F()[token_starttime].(int64)\n var timeElpase string\n if ok {\n var t=time.Now().UnixNano()\n timeElpase=strconv.FormatInt((t-timeStart)/1000000, 10)+\"ms\"\n } else {\n timeElpase=\"xxxx\"\n }\n\n var statusCode, ok2=res.F()[token_returncode].(int)\n var codeStr string\n if ok2 {\n codeStr=strconv.Itoa(statusCode)\n } else {\n codeStr=\"---\"\n }\n\n var url=req.R().URL\n fmt.Print(\"- \"+timeElpase+\"\\t\\t\"+codeStr+\"\\t\"+req.Method()+\"\\t\"+url.Path)\n if url.RawQuery!=\"\" {\n fmt.Println(\"?\"+url.RawQuery)\n } else {\n fmt.Println(\"\")\n }\n}\n\nfunc (this *SimpleAnalyzer)Handler(req Request, res Response) (bool, Request, Response) ", "output": "{\n var newRes=&logResponse {\n o: res,\n OnHeadSent: logCode,\n }\n newRes.F()[token_starttime]=time.Now().UnixNano()\n return true, req, newRes\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetAutonomousPatchRequest struct {\n\n\tAutonomousPatchId *string `mandatory:\"true\" contributesTo:\"path\" name:\"autonomousPatchId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetAutonomousPatchRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request GetAutonomousPatchRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetAutonomousPatchRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetAutonomousPatchResponse struct {\n\n\tRawResponse *http.Response\n\n\tAutonomousPatch `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetAutonomousPatchResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetAutonomousPatchResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetAutonomousPatchRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package comparisons\n\nimport \"jvmgo/ch05/instructions/base\"\nimport \"jvmgo/ch05/rtda\"\n\n\ntype IF_ACMPEQ struct{ base.BranchInstruction }\n\nfunc (self *IF_ACMPEQ) Execute(frame *rtda.Frame) {\n\tif _acmp(frame) {\n\t\tbase.Branch(frame, self.Offset)\n\t}\n}\n\ntype IF_ACMPNE struct{ base.BranchInstruction }\n\nfunc (self *IF_ACMPNE) Execute(frame *rtda.Frame) {\n\tif !_acmp(frame) {\n\t\tbase.Branch(frame, self.Offset)\n\t}\n}\n\n\n\nfunc _acmp(frame *rtda.Frame) bool ", "output": "{\n\tstack := frame.OperandStack()\n\tref2 := stack.PopRef()\n\tref1 := stack.PopRef()\n\treturn ref1 == ref2 \n}"} {"input": "package cli\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestRequiredParameterNotSetError_Error(t *testing.T) {\n\terr := &RequiredParameterNotSetError{\n\t\tName: \"name\",\n\t}\n\tif err.Error() != \"required parameter name not set\" {\n\t\tt.Fail()\n\t}\n\n\terr = &RequiredParameterNotSetError{\n\t\tFormatted: \"formatted\",\n\t}\n\tif err.Error() != \"required parameter formatted not set\" {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestExitStatusError_Error(t *testing.T) ", "output": "{\n\terr := &ExitStatusError{\n\t\tCode: 1,\n\t\tErr: fmt.Errorf(\"error\"),\n\t}\n\n\tif err.Error() != \"error\" {\n\t\tt.Fatal()\n\t}\n}"} {"input": "package longestvalidparentheses\n\n\n\nfunc longestValidParentheses(s string) int ", "output": "{\n\tl := 0\n\tif len(s) >= 1 {\n\t\ti, stack := 0, make([]int, len(s)+1)\n\t\tstack[0] = -1 \n\t\tfor si := 0; si < len(s); si++ {\n\t\t\tif s[si] == '(' { \n\t\t\t\ti++ \n\t\t\t\tstack[i] = si\n\t\t\t} else { \n\t\t\t\ti-- \n\t\t\t\tif i < 0 { \n\t\t\t\t\ti = 0 \n\t\t\t\t\tstack[i] = si\n\t\t\t\t} else if tmp := si - stack[i]; tmp > l {\n\t\t\t\t\tl = tmp \n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn l\n}"} {"input": "package util\n\nimport \"testing\"\n\n\n\nfunc TestCharsLength(t *testing.T) {\n\tchars := ToChars([]byte(\"\\tabc한글 \"))\n\tif chars.inBytes || chars.Length() != 8 || chars.TrimLength() != 5 {\n\t\tt.Error()\n\t}\n}\n\nfunc TestCharsToString(t *testing.T) {\n\ttext := \"\\tabc한글 \"\n\tchars := ToChars([]byte(text))\n\tif chars.ToString() != text {\n\t\tt.Error()\n\t}\n}\n\nfunc TestTrimLength(t *testing.T) {\n\tcheck := func(str string, exp uint16) {\n\t\tchars := ToChars([]byte(str))\n\t\ttrimmed := chars.TrimLength()\n\t\tif trimmed != exp {\n\t\t\tt.Errorf(\"Invalid TrimLength result for '%s': %d (expected %d)\",\n\t\t\t\tstr, trimmed, exp)\n\t\t}\n\t}\n\tcheck(\"hello\", 5)\n\tcheck(\"hello \", 5)\n\tcheck(\"hello \", 5)\n\tcheck(\" hello\", 5)\n\tcheck(\" hello\", 5)\n\tcheck(\" hello \", 5)\n\tcheck(\" hello \", 5)\n\tcheck(\"h o\", 5)\n\tcheck(\" h o \", 5)\n\tcheck(\" \", 0)\n}\n\nfunc TestToCharsAscii(t *testing.T) ", "output": "{\n\tchars := ToChars([]byte(\"foobar\"))\n\tif !chars.inBytes || chars.ToString() != \"foobar\" || !chars.inBytes {\n\t\tt.Error()\n\t}\n}"} {"input": "package testing\n\nimport (\n\t\"time\"\n\n\t\"github.com/zinic/protobus/bus\"\n\t\"github.com/zinic/protobus/concurrent\"\n)\n\nfunc NewInjector(event bus.Event, interval time.Duration) (injector bus.Source) {\n\treturn &InjectorSource {\n\t\tevent: event,\n\t\trunning: concurrent.NewReferenceLocker(false),\n\t\tinterval: interval,\n\t}\n}\n\ntype InjectorSource struct {\n\tevent bus.Event\n\trunning concurrent.ReferenceLocker\n\tinterval time.Duration\n}\n\nfunc (injector *InjectorSource) Start(outgoing chan<- bus.Event, actx bus.ActorContext) (err error) {\n\tinjector.running.Set(true)\n\n\tvar elapsedNanos int64 = 0\n\tfor injector.running.Get().(bool) {\n\t\tthen := time.Now()\n\n\t\tif elapsedNanos >= injector.interval.Nanoseconds() {\n\t\t\telapsedNanos = 0\n\t\t\toutgoing <- injector.event\n\t\t}\n\n\t\ttime.Sleep(1 * time.Millisecond)\n\t\telapsedNanos += time.Now().Sub(then).Nanoseconds()\n\t}\n\n\treturn\n}\n\n\n\nfunc (injector *InjectorSource) Stop() (err error) ", "output": "{\n\tinjector.running.Set(false)\n\treturn\n}"} {"input": "package lru\n\nimport (\n\t\"container/list\"\n\t\"sync\"\n)\n\n\ntype kv struct {\n\tkey interface{}\n\tvalue interface{}\n}\n\n\n\n\n\n\n\n\ntype KVCache struct {\n\tmtx sync.Mutex\n\tcache map[interface{}]*list.Element \n\tlist *list.List \n\tlimit uint\n}\n\n\n\n\n\nfunc (m *KVCache) Lookup(key interface{}) (interface{}, bool) {\n\tvar value interface{}\n\tm.mtx.Lock()\n\tnode, exists := m.cache[key]\n\tif exists {\n\t\tm.list.MoveToFront(node)\n\t\tpair := node.Value.(*kv)\n\t\tvalue = pair.value\n\t}\n\tm.mtx.Unlock()\n\n\treturn value, exists\n}\n\n\n\n\n\n\nfunc (m *KVCache) Contains(key interface{}) bool {\n\tm.mtx.Lock()\n\tnode, exists := m.cache[key]\n\tif exists {\n\t\tm.list.MoveToFront(node)\n\t}\n\tm.mtx.Unlock()\n\treturn exists\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (m *KVCache) Delete(key interface{}) {\n\tm.mtx.Lock()\n\tif node, exists := m.cache[key]; exists {\n\t\tm.list.Remove(node)\n\t\tdelete(m.cache, key)\n\t}\n\tm.mtx.Unlock()\n}\n\n\n\nfunc NewKVCache(limit uint) KVCache {\n\treturn KVCache{\n\t\tcache: make(map[interface{}]*list.Element),\n\t\tlist: list.New(),\n\t\tlimit: limit,\n\t}\n}\n\nfunc (m *KVCache) Add(key interface{}, value interface{}) ", "output": "{\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\n\tif m.limit == 0 {\n\t\treturn\n\t}\n\n\tif node, exists := m.cache[key]; exists {\n\t\tnode.Value.(*kv).value = value\n\t\tm.list.MoveToFront(node)\n\t\tm.cache[key] = node\n\t\treturn\n\t}\n\n\tif uint(len(m.cache))+1 > m.limit {\n\t\tnode := m.list.Back()\n\t\tlru := node.Value.(*kv)\n\n\t\tdelete(m.cache, lru.key)\n\n\t\tlru.key = key\n\t\tlru.value = value\n\t\tm.list.MoveToFront(node)\n\t\tm.cache[key] = node\n\t\treturn\n\t}\n\n\tnode := m.list.PushFront(&kv{key: key, value: value})\n\tm.cache[key] = node\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetVolumeKmsKeyRequest struct {\n\n\tVolumeId *string `mandatory:\"true\" contributesTo:\"path\" name:\"volumeId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetVolumeKmsKeyRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request GetVolumeKmsKeyRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request GetVolumeKmsKeyRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetVolumeKmsKeyRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetVolumeKmsKeyResponse struct {\n\n\tRawResponse *http.Response\n\n\tVolumeKmsKey `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response GetVolumeKmsKeyResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response GetVolumeKmsKeyResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/cloudfoundry/cli/cf/terminal\"\n\t\"github.com/onsi/gomega\"\n)\n\ntype SliceMatcher struct {\n\texpected [][]string\n\tfailedAtIndex int\n}\n\nfunc ContainSubstrings(substrings ...[]string) gomega.OmegaMatcher {\n\treturn &SliceMatcher{expected: substrings}\n}\n\nfunc (matcher *SliceMatcher) Match(actual interface{}) (success bool, err error) {\n\tactualStrings, ok := actual.([]string)\n\tif !ok {\n\t\treturn false, nil\n\t}\n\n\tallStringsMatched := make([]bool, len(matcher.expected))\n\n\tfor index, expectedArray := range matcher.expected {\n\t\tfor _, actualValue := range actualStrings {\n\n\t\t\tallStringsFound := true\n\n\t\t\tfor _, expectedValue := range expectedArray {\n\t\t\t\tallStringsFound = allStringsFound && strings.Contains(terminal.Decolorize(actualValue), expectedValue)\n\t\t\t}\n\n\t\t\tif allStringsFound {\n\t\t\t\tallStringsMatched[index] = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tfor index, value := range allStringsMatched {\n\t\tif !value {\n\t\t\tmatcher.failedAtIndex = index\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\treturn true, nil\n}\n\n\n\nfunc (matcher *SliceMatcher) NegatedFailureMessage(actual interface{}) string {\n\tactualStrings, ok := actual.([]string)\n\tif !ok {\n\t\treturn fmt.Sprintf(\"Expected actual to be a slice of strings, but it's actually a %T\", actual)\n\t}\n\treturn fmt.Sprintf(\"expected to not find \\\"%s\\\" in actual:\\n'%s'\\n\", matcher.expected[matcher.failedAtIndex], strings.Join(actualStrings, \"\\n\"))\n}\n\nfunc (matcher *SliceMatcher) FailureMessage(actual interface{}) string ", "output": "{\n\tactualStrings, ok := actual.([]string)\n\tif !ok {\n\t\treturn fmt.Sprintf(\"Expected actual to be a slice of strings, but it's actually a %T\", actual)\n\t}\n\n\treturn fmt.Sprintf(\"expected to find \\\"%s\\\" in actual:\\n'%s'\\n\", matcher.expected[matcher.failedAtIndex], strings.Join(actualStrings, \"\\n\"))\n}"} {"input": "package zebra\n\nimport \"fmt\"\n\nconst _AFI_name = \"AFI_IPAFI_IP6AFI_ETHERAFI_MAX\"\n\nvar _AFI_index = [...]uint8{0, 6, 13, 22, 29}\n\n\n\nfunc (i AFI) String() string ", "output": "{\n\ti -= 1\n\tif i >= AFI(len(_AFI_index)-1) {\n\t\treturn fmt.Sprintf(\"AFI(%d)\", i+1)\n\t}\n\treturn _AFI_name[_AFI_index[i]:_AFI_index[i+1]]\n}"} {"input": "package iso20022\n\n\ntype ApplicationParameters4 struct {\n\n\tApplicationIdentification *Max35Text `xml:\"ApplId\"`\n\n\tVersion *Max256Text `xml:\"Vrsn\"`\n\n\tParameters []*Max100KBinary `xml:\"Params,omitempty\"`\n\n\tEncryptedParameters *ContentInformationType10 `xml:\"NcrptdParams,omitempty\"`\n}\n\nfunc (a *ApplicationParameters4) SetApplicationIdentification(value string) {\n\ta.ApplicationIdentification = (*Max35Text)(&value)\n}\n\nfunc (a *ApplicationParameters4) SetVersion(value string) {\n\ta.Version = (*Max256Text)(&value)\n}\n\nfunc (a *ApplicationParameters4) AddParameters(value string) {\n\ta.Parameters = append(a.Parameters, (*Max100KBinary)(&value))\n}\n\n\n\nfunc (a *ApplicationParameters4) AddEncryptedParameters() *ContentInformationType10 ", "output": "{\n\ta.EncryptedParameters = new(ContentInformationType10)\n\treturn a.EncryptedParameters\n}"} {"input": "package goschema\n\ntype nullType struct {\n\tbaseType\n}\n\nfunc NewNullType(description string) NullType {\n\treturn &nullType{\n\t\tbaseType: baseType{\n\t\t\tdescription: description,\n\t\t},\n\t}\n}\n\nfunc (g *nullType) docString(field string, docPrefix string) string {\n\treturn docString(field, g.description, docPrefix, \"must be nothing (null)\")\n}\n\n\n\nfunc (g *nullType) asJSONSchema() map[string]interface{} ", "output": "{\n\tdata := map[string]interface{}{\n\t\t\"type\": \"null\",\n\t}\n\tif g.description != \"\" {\n\t\tdata[\"description\"] = g.description\n\t}\n\treturn data\n}"} {"input": "package suggest\n\nimport (\n\t\"github.com/google/btree\"\n\t\"sync\"\n)\n\n\ntype Suggester interface {\n\tSuggest(max int, q string) (result []string)\n}\n\n\ntype Adder interface {\n\tAdd(s string)\n}\n\n\n\ntype Engine struct {\n\tincomingCh chan string\n\tawaitCh chan bool\n\tlock sync.RWMutex\n\tsuggestions *btree.BTree\n}\n\n\nfunc NewEngine() *Engine {\n\treturn newEngine()\n}\n\n\n\n\n\n\nfunc (e *Engine) Add(s string) {\n\te.add(s)\n}\n\n\nfunc (e *Engine) Await() {\n\te.await()\n}\n\n\n\n\n\n\nfunc NewSuggester(suggestions ...string) Suggester {\n\treturn newSuggester(suggestions)\n}\n\nfunc (e *Engine) Suggest(max int, q string) (result []string) ", "output": "{\n\treturn e.suggest(max, q)\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\tclayControllers \"github.com/qb0C80aE/clay/controllers\"\n\t\"github.com/qb0C80aE/clay/extensions\"\n\t\"github.com/qb0C80aE/pottery/logics\"\n\t\"github.com/qb0C80aE/pottery/models\"\n)\n\ntype hostGroupController struct {\n\t*clayControllers.BaseController\n}\n\nfunc newHostGroupController() extensions.Controller {\n\tcontroller := &hostGroupController{\n\t\tBaseController: clayControllers.NewBaseController(\n\t\t\tmodels.SharedHostGroupModel(),\n\t\t\tlogics.UniqueHostGroupLogic(),\n\t\t),\n\t}\n\treturn controller\n}\n\nfunc (controller *hostGroupController) RouteMap() map[int]map[int]gin.HandlerFunc {\n\trouteMap := map[int]map[int]gin.HandlerFunc{\n\t\textensions.MethodGet: {\n\t\t\textensions.URLSingle: controller.GetSingle,\n\t\t\textensions.URLMulti: controller.GetMulti,\n\t\t},\n\t\textensions.MethodPost: {\n\t\t\textensions.URLMulti: controller.Create,\n\t\t},\n\t\textensions.MethodPut: {\n\t\t\textensions.URLSingle: controller.Update,\n\t\t},\n\t\textensions.MethodDelete: {\n\t\t\textensions.URLSingle: controller.Delete,\n\t\t},\n\t}\n\treturn routeMap\n}\n\nvar uniqueHostGroupController = newHostGroupController()\n\n\n\nfunc init() ", "output": "{\n\textensions.RegisterController(uniqueHostGroupController)\n}"} {"input": "package engine\n\nimport \"testing\"\n\nfunc TestBackendLobbyMuxAddLobby(t *testing.T) {\n\tmux := NewBackendLobbyMux()\n\tmux.AddLobby(\"/foo\", &backendLobby{})\n\tif _, ok := mux.m[\"/foo\"]; !ok {\n\t\tt.Errorf(\"Expected to add lobby\")\n\t}\n}\n\nfunc TestBackendLobbyMuxDeleteLobby(t *testing.T) {\n\tmux := NewBackendLobbyMux()\n\tl := &backendLobby{queue: make(chan interface{})}\n\tmux.AddLobby(\"/foo\", l)\n\tif ok := mux.DeleteLobby(\"/foo\"); !ok {\n\t\tt.Errorf(\"Expected to delete lobby\")\n\t}\n\tif l.IsAlive() {\n\t\tt.Errorf(\"Lobby should be killed when deleting from the mux\")\n\t}\n\tif _, ok := mux.m[\"/foo\"]; ok {\n\t\tt.Errorf(\"Expected to delete lobby\")\n\t}\n\tif ok := mux.DeleteLobby(\"/bar\"); ok {\n\t\tt.Errorf(\"Expected to not delete non existing lobby\")\n\t}\n}\n\n\n\nfunc TestBackendLobbyMuxMatch(t *testing.T) ", "output": "{\n\tmux := NewBackendLobbyMux()\n\tmux.AddLobby(\"/foo\", &backendLobby{})\n\tif lobby := mux.Match(\"/foo\"); lobby == nil {\n\t\tt.Errorf(\"Expected to match existing lobby\")\n\t}\n\tif lobby := mux.Match(\"/bar\"); lobby != nil {\n\t\tt.Errorf(\"Expected to not match non existing lobby\")\n\t}\n}"} {"input": "package helper\n\nimport (\n\t\"encoding/base64\"\n\t\"strings\"\n\t\"time\"\n\t\"github.com/insionng/yougam/libraries/flosch/pongo2.v3\"\n)\n\nfunc ConvertToBase64(in string) string {\n\treturn base64.StdEncoding.EncodeToString([]byte(in))\n}\n\nfunc ConvertToBase64ByPongo2(in *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(base64.StdEncoding.EncodeToString([]byte(in.String())))\n}\n\nfunc SplitByPongo2(in *pongo2.Value, splitor *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Split(in.String(), splitor.String()))\n}\n\nfunc MarkdownByPongo2(in *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Markdown(in.String()))\n}\n\nfunc CropwordByPongo2(in *pongo2.Value, start *pongo2.Value, length *pongo2.Value, symbol *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Substr(in.String(), start.Integer(), length.Integer(), symbol.String()))\n}\n\nfunc Cropword(in string, start int, length int, symbol string) string {\n\treturn Substr(in, start, length, symbol)\n}\n\nfunc File(s string) string {\n\tif len(s) > 0 {\n\t\tif strings.HasPrefix(s, \"http\") || strings.HasPrefix(s, \"/identicon\") {\n\t\t\treturn s\n\t\t} else {\n\t\t\treturn \"/file\" + s\n\t\t}\n\t}\n\treturn s\n}\n\n\n\nfunc Unix2TimeByPongo2(in *pongo2.Value, timeLayout *pongo2.Value) *pongo2.Value ", "output": "{\n\treturn pongo2.AsValue(time.Unix(int64(in.Integer()), 0).Format(timeLayout.String()))\n}"} {"input": "package example\n\nimport (\n\t\"testing\"\n\t\"github.com/remogatto/prettytest\"\n\t\"launchpad.net/gocheck\"\n)\n\n\n\ntype testSuite struct {\n\tprettytest.Suite\n}\n\nfunc TestRunner(t *testing.T) {\n\tprettytest.Run(\n\t\tt,\n\t\tnew(testSuite),\n\t)\n}\n\n\n\n\n\n\nfunc (t *testSuite) TestTrueIsTrue() {\n\tt.True(true)\n}\n\n\n\nfunc (t *testSuite) TestNot() {\n\tt.Not(t.Path(\"foo\"))\n}\n\nfunc (t *testSuite) TestGoCheck() {\n\tt.Check(\"foo\", gocheck.Equals, \"foo\")\n}\n\n\n\nfunc (t *testSuite) TestMustFail() {\n\tt.Error(\"This test must fail.\")\n\tt.MustFail()\n}\n\nfunc (t *testSuite) TestInequality() {\n\tt.Equal(\"awesome\", \"ugly\")\n\tt.MustFail()\n}\n\nfunc (t *testSuite) TestEquality() ", "output": "{\n\tt.Equal(\"awesome\", \"awesome\")\n}"} {"input": "package ast\n\nimport (\n \"fmt\"\n \"github.com/kedebug/LispEx/binder\"\n \"github.com/kedebug/LispEx/constants\"\n \"github.com/kedebug/LispEx/scope\"\n . \"github.com/kedebug/LispEx/value\"\n)\n\ntype Set struct {\n Pattern *Name\n Value Node\n}\n\n\n\nfunc (self *Set) Eval(env *scope.Scope) Value {\n val := self.Value.Eval(env)\n binder.Assign(env, self.Pattern.Identifier, val)\n return nil\n}\n\nfunc (self *Set) String() string {\n return fmt.Sprintf(\"(%s %s %s)\", constants.SET, self.Pattern, self.Value)\n}\n\nfunc NewSet(pattern *Name, val Node) *Set ", "output": "{\n return &Set{Pattern: pattern, Value: val}\n}"} {"input": "package router\n\nimport (\n\t\"sync/atomic\"\n\n\t\"github.com/AsynkronIT/protoactor-go/actor\"\n)\n\ntype roundRobinGroupRouter struct {\n\tGroupRouter\n}\n\ntype roundRobinPoolRouter struct {\n\tPoolRouter\n}\n\ntype roundRobinState struct {\n\tindex int32\n\troutees *actor.PIDSet\n\tvalues []actor.PID\n}\n\nfunc (state *roundRobinState) SetRoutees(routees *actor.PIDSet) {\n\tstate.routees = routees\n\tstate.values = routees.Values()\n}\n\nfunc (state *roundRobinState) GetRoutees() *actor.PIDSet {\n\treturn state.routees\n}\n\nfunc (state *roundRobinState) RouteMessage(message interface{}, sender *actor.PID) {\n\tpid := roundRobinRoutee(&state.index, state.values)\n\tpid.Request(message, sender)\n}\n\nfunc NewRoundRobinPool(size int) *actor.Props {\n\treturn actor.FromSpawnFunc(spawner(&roundRobinPoolRouter{PoolRouter{PoolSize: size}}))\n}\n\nfunc NewRoundRobinGroup(routees ...*actor.PID) *actor.Props {\n\treturn actor.FromSpawnFunc(spawner(&roundRobinGroupRouter{GroupRouter{Routees: actor.NewPIDSet(routees...)}}))\n}\n\n\n\nfunc (config *roundRobinGroupRouter) CreateRouterState() Interface {\n\treturn &roundRobinState{}\n}\n\nfunc roundRobinRoutee(index *int32, routees []actor.PID) actor.PID {\n\ti := int(atomic.AddInt32(index, 1))\n\tif i < 0 {\n\t\t*index = 0\n\t\ti = 0\n\t}\n\tmod := len(routees)\n\troutee := routees[i%mod]\n\treturn routee\n}\n\nfunc (config *roundRobinPoolRouter) CreateRouterState() Interface ", "output": "{\n\treturn &roundRobinState{}\n}"} {"input": "package daemon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/docker/docker/pkg/signal\"\n\t\"github.com/docker/docker/runconfig\"\n)\n\n\n\nfunc TestValidContainerNames(t *testing.T) {\n\tinvalidNames := []string{\"-rm\", \"&sdfsfd\", \"safd%sd\"}\n\tvalidNames := []string{\"word-word\", \"word_word\", \"1weoid\"}\n\n\tfor _, name := range invalidNames {\n\t\tif validContainerNamePattern.MatchString(name) {\n\t\t\tt.Fatalf(\"%q is not a valid container name and was returned as valid.\", name)\n\t\t}\n\t}\n\n\tfor _, name := range validNames {\n\t\tif !validContainerNamePattern.MatchString(name) {\n\t\t\tt.Fatalf(\"%q is a valid container name and was returned as invalid.\", name)\n\t\t}\n\t}\n}\n\nfunc TestContainerStopSignal(t *testing.T) {\n\tc := &Container{\n\t\tCommonContainer: CommonContainer{\n\t\t\tConfig: &runconfig.Config{},\n\t\t},\n\t}\n\n\tdef, err := signal.ParseSignal(signal.DefaultStopSignal)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ts := c.stopSignal()\n\tif s != int(def) {\n\t\tt.Fatalf(\"Expected %v, got %v\", def, s)\n\t}\n\n\tc = &Container{\n\t\tCommonContainer: CommonContainer{\n\t\t\tConfig: &runconfig.Config{StopSignal: \"SIGKILL\"},\n\t\t},\n\t}\n\ts = c.stopSignal()\n\tif s != 9 {\n\t\tt.Fatalf(\"Expected 9, got %v\", s)\n\t}\n}\n\nfunc TestGetFullName(t *testing.T) ", "output": "{\n\tname, err := GetFullContainerName(\"testing\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif name != \"/testing\" {\n\t\tt.Fatalf(\"Expected /testing got %s\", name)\n\t}\n\tif _, err := GetFullContainerName(\"\"); err == nil {\n\t\tt.Fatal(\"Error should not be nil\")\n\t}\n}"} {"input": "package service\n\nimport (\n\t\"fmt\"\n\t\"github.com/mrcsparker/ifin/api\"\n\t\"github.com/mrcsparker/ifin/model\"\n\t\"log\"\n)\n\ntype Counters struct {\n}\n\n\n\n\n\nfunc (self Counters) UpdateCounter(id string) model.CounterEntity {\n\ts := api.Setup()\n\tres := model.CounterEntity{}\n\turl := \"http://localhost:8080/nifi-api/counters/{id}\"\n\tresp, err := s.Put(url, nil, &res, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif resp.Status() != 200 {\n\t\tfmt.Println(res)\n\t}\n\n\treturn res\n}\n\nfunc (self Counters) GetCounters(nodewise bool, clusterNodeId string) model.CountersEntity ", "output": "{\n\ts := api.Setup()\n\tres := model.CountersEntity{}\n\turl := \"http://localhost:8080/nifi-api/counters\"\n\tresp, err := s.Get(url, nil, &res, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif resp.Status() != 200 {\n\t\tfmt.Println(res)\n\t}\n\n\treturn res\n}"} {"input": "package gogen\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\n\t\"text/template\"\n\n\t\"github.com/gobuffalo/genny\"\n\t\"github.com/pkg/errors\"\n)\n\nvar TemplateHelpers = map[string]interface{}{}\n\n\n\n\nfunc renderWithTemplate(f genny.File, data interface{}, helpers template.FuncMap) (genny.File, error) {\n\tif f == nil {\n\t\treturn f, errors.New(\"file was nil\")\n\t}\n\tpath := f.Name()\n\tt := template.New(path)\n\tif helpers != nil {\n\t\tt = t.Funcs(helpers)\n\t}\n\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn f, errors.WithStack(err)\n\t}\n\tt, err = t.Parse(string(b))\n\tif err != nil {\n\t\treturn f, errors.WithStack(err)\n\t}\n\n\tvar bb bytes.Buffer\n\tif err = t.Execute(&bb, data); err != nil {\n\t\terr = errors.WithStack(err)\n\t\treturn f, errors.WithStack(err)\n\t}\n\treturn genny.StripExt(genny.NewFile(path, &bb), \".tmpl\"), nil\n}\n\nfunc TemplateTransformer(data interface{}, helpers map[string]interface{}) genny.Transformer ", "output": "{\n\tif helpers == nil {\n\t\thelpers = TemplateHelpers\n\t}\n\tt := genny.NewTransformer(\".tmpl\", func(f genny.File) (genny.File, error) {\n\t\treturn renderWithTemplate(f, data, helpers)\n\t})\n\tt.StripExt = true\n\treturn t\n}"} {"input": "package crypto\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha512\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n)\n\n\n\n\n\nfunc HS512Base64(in, secret string) string {\n\tkey := []byte(secret)\n\th := hmac.New(sha512.New, key)\n\th.Write([]byte(in))\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil))\n}\n\n\nfunc HS512Hex(in, secret string) string {\n\tkey := []byte(secret)\n\th := hmac.New(sha512.New, key)\n\th.Write([]byte(in))\n\treturn hex.EncodeToString(h.Sum(nil))\n}\n\n\nfunc CompareHS512Hex(in, secret, hs512Hex string) bool {\n\tif HS512Hex(in, secret) == hs512Hex {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc HS512Byte(in, secret []byte) []byte ", "output": "{\n\th := hmac.New(sha512.New, secret)\n\th.Write(in)\n\treturn h.Sum(nil)\n}"} {"input": "package donna\n\nfunc (gen *MoveGen) generateCaptures() *MoveGen {\n\tcolor := gen.p.color\n\treturn gen.pawnCaptures(color).pieceCaptures(color)\n}\n\n\nfunc (gen *MoveGen) pawnCaptures(color int) *MoveGen {\n\tenemy := gen.p.outposts[color^1]\n\n\tfor pawns := gen.p.outposts[pawn(color)]; pawns.any(); pawns = pawns.pop() {\n\t\tsquare := pawns.first()\n\n\t\tif rank(color, square) != A7H7 {\n\t\t\tgen.movePawn(square, gen.p.targets(square) & enemy)\n\t\t} else {\n\t\t\tfor bm := gen.p.targets(square); bm.any(); bm = bm.pop() {\n\t\t\t\ttarget := bm.first()\n\t\t\t\tmQ, _, _, _ := NewPromotion(gen.p, square, target)\n\t\t\t\tgen.add(mQ)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn gen\n}\n\n\n\n\nfunc (gen *MoveGen) pieceCaptures(color int) *MoveGen ", "output": "{\n\tenemy := gen.p.outposts[color^1]\n\n\tfor bm := gen.p.outposts[color] ^ gen.p.outposts[pawn(color)] ^ gen.p.outposts[king(color)]; bm.any(); bm = bm.pop() {\n\t\tsquare := bm.first()\n\t\tgen.movePiece(square, gen.p.targets(square) & enemy)\n\t}\n\tif gen.p.outposts[king(color)].any() {\n\t\tsquare := gen.p.king[color]\n\t\tgen.moveKing(square, gen.p.targets(square) & enemy)\n\t}\n\n\treturn gen\n}"} {"input": "package types\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\t\"time\"\n)\n\n\n\ntype CommitObject struct {\n\tAuthor string\n\tMessage string\n\tTime time.Time\n\tTree Hash\n\tParents []Hash\n}\n\n\nfunc (commit *CommitObject) Serialize() []byte {\n\tbuffer := new(bytes.Buffer)\n\te := gob.NewEncoder(buffer)\n\terr := e.Encode(commit)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn buffer.Bytes()\n}\n\n\n\n\n\nfunc DeserializeCommitObject(input []byte) *CommitObject ", "output": "{\n\tbuffer := bytes.NewBuffer(input)\n\tdec := gob.NewDecoder(buffer)\n\n\tvar commit CommitObject\n\terr := dec.Decode(&commit)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &commit\n}"} {"input": "package client\n\nimport (\n\t\"context\"\n\t\"math\"\n\t\"time\"\n)\n\ntype BackoffFunc func(ctx context.Context, req Request, attempts int) (time.Duration, error)\n\n\n\n\nfunc exponentialBackoff(ctx context.Context, req Request, attempts int) (time.Duration, error) ", "output": "{\n\tif attempts == 0 {\n\t\treturn time.Duration(0), nil\n\t}\n\treturn time.Duration(math.Pow(10, float64(attempts))) * time.Millisecond, nil\n}"} {"input": "package head\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/arapov/pile/lib/flight\"\n\n\t\"github.com/blue-jay/core/router\"\n)\n\nvar (\n\turi = \"/roster\"\n)\n\n\nfunc Load() {\n\trouter.Get(uri+\"/head\", IndexHead)\n\trouter.Get(uri+\"/all\", IndexAll)\n}\n\n\nfunc IndexHead(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\tv := c.View.New(\"head/index\")\n\tv.Vars[\"name\"] = \"TC-UA-Steward\"\n\tv.Vars[\"suffix\"] = \"heads\"\n\tv.Render(w, r)\n}\n\n\n\n\nfunc IndexAll(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tc := flight.Context(w, r)\n\n\tv := c.View.New(\"head/index\")\n\tv.Vars[\"name\"] = \"Everyone in organization\"\n\tv.Vars[\"suffix\"] = \"all\"\n\tv.Render(w, r)\n}"} {"input": "package http\n\nimport (\n\t\"net\"\n\t\"time\"\n)\n\n\ntype TimeoutConn struct {\n\tQuirkConn\n\treadTimeout time.Duration\n\twriteTimeout time.Duration\n}\n\nfunc (c *TimeoutConn) setReadTimeout() {\n\tif c.readTimeout != 0 && c.canSetReadDeadline() {\n\t\tc.SetReadDeadline(time.Now().UTC().Add(c.readTimeout))\n\t}\n}\n\nfunc (c *TimeoutConn) setWriteTimeout() {\n\tif c.writeTimeout != 0 {\n\t\tc.SetWriteDeadline(time.Now().UTC().Add(c.writeTimeout))\n\t}\n}\n\n\n\n\n\nfunc (c *TimeoutConn) Write(b []byte) (n int, err error) {\n\tc.setWriteTimeout()\n\treturn c.Conn.Write(b)\n}\n\n\nfunc NewTimeoutConn(c net.Conn, readTimeout, writeTimeout time.Duration) *TimeoutConn {\n\treturn &TimeoutConn{\n\t\tQuirkConn: QuirkConn{Conn: c},\n\t\treadTimeout: readTimeout,\n\t\twriteTimeout: writeTimeout,\n\t}\n}\n\nfunc (c *TimeoutConn) Read(b []byte) (n int, err error) ", "output": "{\n\tc.setReadTimeout()\n\treturn c.Conn.Read(b)\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype RemoveNetworkSecurityGroupSecurityRulesRequest struct {\n\n\tNetworkSecurityGroupId *string `mandatory:\"true\" contributesTo:\"path\" name:\"networkSecurityGroupId\"`\n\n\tRemoveNetworkSecurityGroupSecurityRulesDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype RemoveNetworkSecurityGroupSecurityRulesResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response RemoveNetworkSecurityGroupSecurityRulesResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response RemoveNetworkSecurityGroupSecurityRulesResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package middleware\n\nimport (\n\t\"github.com/drone/drone/version\"\n\t\"github.com/gin-gonic/gin\"\n)\n\n\n\n\n\nfunc Version(c *gin.Context) ", "output": "{\n\tc.Header(\"X-DRONE-VERSION\", version.Version)\n}"} {"input": "package clipboard\n\nimport (\n\t\"time\"\n)\n\ntype Duration struct {\n\ttime.Duration\n}\n\nfunc (d *Duration) UnmarshalText(text []byte) error {\n\tvar err error\n\td.Duration, err = time.ParseDuration(string(text))\n\treturn err\n}\n\n\n\nfunc (d Duration) MarshalText() ([]byte, error) ", "output": "{\n\treturn []byte(d.String()), nil\n}"} {"input": "package gnr\n\nimport (\n\t\"math\"\n)\n\ntype FalloffFunc func(ir *InteractionResult) *InteractionResult\ntype FlatShader struct {\n\tObject\n\tFalloffFunc\n}\n\n\n\nfunc NewLinearFalloffFunc(lightDir *Vector3f) FalloffFunc {\n\treturn func(ir *InteractionResult) *InteractionResult {\n\t\tcosAngle := VectorProduct(lightDir, ir.Normal) / lightDir.Magnitude() / ir.Normal.Magnitude()\n\t\tangle := math.Acos(cosAngle)\n\t\tir.Color = VLerpCap(0, math.Pi, ColorBlack, ir.Color)(angle)\n\t\treturn ir\n\t}\n}\n\nfunc (fs *FlatShader) RayInteraction(r *Ray) []*InteractionResult ", "output": "{\n\tirs := fs.Object.RayInteraction(r)\n\tirs = InteractionResultSlice(irs).SelectInteractionResult(fs.FalloffFunc)\n\treturn irs\n}"} {"input": "package blockchain\n\nimport (\n\t\"github.com/cfromknecht/certcoin/crypto\"\n\tdb \"github.com/syndtr/goleveldb/leveldb\"\n\n\t\"log\"\n)\n\ntype SVP struct {\n\tHeaderDBPath string\n\tLastHeader BlockHeader\n}\n\n\n\nfunc (s *SVP) ValidHeader(header BlockHeader) bool {\n\tif header.SeqNum == 0 {\n\t\treturn header.PrevHash == crypto.SHA256Sum{} &&\n\t\t\theader.ValidPoW()\n\t}\n\n\treturn s.LastHeader.Hash() == header.PrevHash &&\n\t\theader.ValidPoW()\n}\n\nfunc (s *SVP) WriteHeader(header BlockHeader) error {\n\theaderDB, err := db.OpenFile(s.HeaderDBPath, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tpanic(\"Unable to open header database\")\n\t}\n\tdefer headerDB.Close()\n\n\theaderJson := header.Json()\n\thash := header.Hash()\n\n\terr = headerDB.Put(hash[:], headerJson, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\tlog.Println(\"Last header:\", header)\n\ts.LastHeader = header\n\n\treturn nil\n}\n\nfunc NewSVP() SVP ", "output": "{\n\tsvp := SVP{\n\t\tHeaderDBPath: \"db/header.db\",\n\t}\n\n\terr := svp.WriteHeader(GenesisBlock().Header)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tpanic(\"Unable to add genesis block header to database\")\n\t}\n\n\treturn svp\n}"} {"input": "package geoMath\n\nimport (\n \"github.com/helmutkemper/mgo/bson\"\n \"github.com/helmutkemper/db\"\n)\n\ntype RelationErrorStt struct {\n IdMongo bson.ObjectId `bson:\"_id,omitempty\"`\n IdParser bson.ObjectId `bson:\"IdParser,omitempty\"`\n \n Id int64\n IdSearched int64\n DbCollectionName string `bson:\"dbCollectionName\" json:\"-\"`\n *db.DbStt `bson:\"-\"` \n}\n\nfunc ( RelationErrorAStt *RelationErrorStt ) SetDbCollectionName( nameAStr string ){ RelationErrorAStt.DbCollectionName = nameAStr }\n\n\n\nfunc ( RelationErrorAStt *RelationErrorStt ) FindOne( queryAObj bson.M ) error {\n err := RelationErrorAStt.DbStt.TestConnection()\n if err != nil {\n return err\n }\n\n return RelationErrorAStt.DbStt.FindOne( RelationErrorAStt.DbCollectionName, &RelationErrorAStt, queryAObj )\n}\n\nfunc ( RelationErrorAStt *RelationErrorStt ) RemoveAll( queryAObj bson.M ) error {\n err := RelationErrorAStt.DbStt.TestConnection()\n if err != nil {\n return err\n }\n\n _, ret := RelationErrorAStt.DbStt.RemoveAll( RelationErrorAStt.DbCollectionName, queryAObj )\n return ret\n}\n\nfunc ( RelationErrorAStt *RelationErrorStt ) Insert() error ", "output": "{\n var err error\n\n err = RelationErrorAStt.DbStt.TestConnection()\n if err != nil{\n return err\n }\n\n RelationErrorAStt.IdMongo, err = RelationErrorAStt.DbStt.GetMongoId()\n if err != nil{\n return err\n }\n\n if RelationErrorAStt.DbStt.HasIndex( RelationErrorAStt.DbCollectionName, \"id\" ) != true {\n RelationErrorAStt.DbStt.IndexKeyMake ( RelationErrorAStt.DbCollectionName, \"id\" )\n }\n\n if RelationErrorAStt.DbStt.HasIndex( RelationErrorAStt.DbCollectionName, \"idSearched\" ) != true {\n RelationErrorAStt.DbStt.IndexKeyMake ( RelationErrorAStt.DbCollectionName, \"idSearched\" )\n }\n\n return RelationErrorAStt.DbStt.Insert( RelationErrorAStt.DbCollectionName, RelationErrorAStt )\n}"} {"input": "package models\n\n\n\n\nimport (\n\tciliumModels \"github.com/cilium/cilium/api/v1/models\"\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\n\ntype HealthResponse struct {\n\n\tCilium ciliumModels.StatusResponse `json:\"cilium,omitempty\"`\n\n\tSystemLoad *LoadResponse `json:\"system-load,omitempty\"`\n\n\tUptime string `json:\"uptime,omitempty\"`\n}\n\n\nfunc (m *HealthResponse) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateSystemLoad(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\n\nfunc (m *HealthResponse) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *HealthResponse) UnmarshalBinary(b []byte) error {\n\tvar res HealthResponse\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *HealthResponse) validateSystemLoad(formats strfmt.Registry) error ", "output": "{\n\n\tif swag.IsZero(m.SystemLoad) { \n\t\treturn nil\n\t}\n\n\tif m.SystemLoad != nil {\n\t\tif err := m.SystemLoad.Validate(formats); err != nil {\n\t\t\tif ve, ok := err.(*errors.Validation); ok {\n\t\t\t\treturn ve.ValidateName(\"system-load\")\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package kernel \n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\n\n\n\n\nfunc getRelease(osName string) (string, error) {\n\tvar release string\n\tdata := strings.Split(osName, \"\\n\")\n\tfor _, line := range data {\n\t\tif !strings.Contains(line, \"Kernel Version\") {\n\t\t\tcontinue\n\t\t}\n\t\tcontent := strings.SplitN(line, \":\", 2)\n\t\tif len(content) != 2 {\n\t\t\treturn \"\", fmt.Errorf(\"Kernel Version is invalid\")\n\t\t}\n\n\t\tprettyNames := strings.SplitN(strings.TrimSpace(content[1]), \" \", 2)\n\n\t\tif len(prettyNames) != 2 {\n\t\t\treturn \"\", fmt.Errorf(\"Kernel Version needs to be 'Darwin x.x.x' \")\n\t\t}\n\t\trelease = prettyNames[1]\n\t}\n\n\treturn release, nil\n}\n\nfunc getSPSoftwareDataType() (string, error) {\n\tcmd := exec.Command(\"system_profiler\", \"SPSoftwareDataType\")\n\tosName, err := cmd.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(osName), nil\n}\n\nfunc GetKernelVersion() (*VersionInfo, error) ", "output": "{\n\tosName, err := getSPSoftwareDataType()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trelease, err := getRelease(osName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseRelease(release)\n}"} {"input": "package block\n\nimport (\n\t\"github.com/juju/cmd/v3\"\n\t\"github.com/juju/juju/jujuclient\"\n\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/cmd/modelcmd\"\n)\n\n\n\n\n\n\n\nfunc NewEnableCommandForTest(store jujuclient.ClientStore, api unblockClientAPI, err error) cmd.Command {\n\tcmd := &enableCommand{\n\t\tapiFunc: func(_ newAPIRoot) (unblockClientAPI, error) {\n\t\t\treturn api, err\n\t\t},\n\t}\n\tcmd.SetClientStore(store)\n\treturn modelcmd.Wrap(cmd)\n}\n\ntype listMockAPI interface {\n\tblockListAPI\n\tListBlockedModels() ([]params.ModelBlockInfo, error)\n}\n\n\n\nfunc NewListCommandForTest(store jujuclient.ClientStore, api listMockAPI, err error) cmd.Command {\n\tcmd := &listCommand{\n\t\tapiFunc: func(_ newAPIRoot) (blockListAPI, error) {\n\t\t\treturn api, err\n\t\t},\n\t\tcontrollerAPIFunc: func(_ newControllerAPIRoot) (controllerListAPI, error) {\n\t\t\treturn api, err\n\t\t},\n\t}\n\tcmd.SetClientStore(store)\n\treturn modelcmd.Wrap(cmd)\n}\n\nfunc NewDisableCommandForTest(store jujuclient.ClientStore, api blockClientAPI, err error) cmd.Command ", "output": "{\n\tcmd := &disableCommand{\n\t\tapiFunc: func(_ newAPIRoot) (blockClientAPI, error) {\n\t\t\treturn api, err\n\t\t},\n\t}\n\tcmd.SetClientStore(store)\n\treturn modelcmd.Wrap(cmd)\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tconst freezingF, boilingF = 32.0, 212.0\n\tfmt.Printf(\"%g°F = %g°C\\n\", freezingF, fToC(freezingF)) \n\tfmt.Printf(\"%g°F = %g°C\\n\", boilingF, fToC(boilingF)) \n}\n\n\n\nfunc fToC(f float64) float64 ", "output": "{ \n\treturn (f - 32) * 5 / 9\n}"} {"input": "package box\n\nimport (\n\t\"golang.org/x/crypto/curve25519\"\n\t\"golang.org/x/crypto/nacl/secretbox\"\n\t\"golang.org/x/crypto/salsa20/salsa\"\n\t\"io\"\n)\n\n\nconst Overhead = secretbox.Overhead\n\n\n\nfunc GenerateKey(rand io.Reader) (publicKey, privateKey *[32]byte, err error) {\n\tpublicKey = new([32]byte)\n\tprivateKey = new([32]byte)\n\t_, err = io.ReadFull(rand, privateKey[:])\n\tif err != nil {\n\t\tpublicKey = nil\n\t\tprivateKey = nil\n\t\treturn\n\t}\n\n\tcurve25519.ScalarBaseMult(publicKey, privateKey)\n\treturn\n}\n\nvar zeros [16]byte\n\n\n\n\n\nfunc Precompute(sharedKey, peersPublicKey, privateKey *[32]byte) {\n\tcurve25519.ScalarMult(sharedKey, privateKey, peersPublicKey)\n\tsalsa.HSalsa20(sharedKey, &zeros, sharedKey, &salsa.Sigma)\n}\n\n\n\n\nfunc Seal(out, message []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) []byte {\n\tvar sharedKey [32]byte\n\tPrecompute(&sharedKey, peersPublicKey, privateKey)\n\treturn secretbox.Seal(out, message, nonce, &sharedKey)\n}\n\n\n\nfunc SealAfterPrecomputation(out, message []byte, nonce *[24]byte, sharedKey *[32]byte) []byte {\n\treturn secretbox.Seal(out, message, nonce, sharedKey)\n}\n\n\n\n\n\n\n\n\nfunc OpenAfterPrecomputation(out, box []byte, nonce *[24]byte, sharedKey *[32]byte) ([]byte, bool) {\n\treturn secretbox.Open(out, box, nonce, sharedKey)\n}\n\nfunc Open(out, box []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) ([]byte, bool) ", "output": "{\n\tvar sharedKey [32]byte\n\tPrecompute(&sharedKey, peersPublicKey, privateKey)\n\treturn secretbox.Open(out, box, nonce, &sharedKey)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/polariseye/polarserver/common\"\n\t\"github.com/polariseye/polarserver/common/errorCode\"\n\t\"github.com/polariseye/polarserver/moduleManage\"\n)\n\ntype testStruct struct {\n\tclassName string\n}\n\nvar TestBLL *testStruct\n\nfunc init() {\n\tTestBLL = NewTestStruct()\n\tmoduleManage.RegisterModule(func() (moduleManage.IModule, moduleManage.ModuleType) {\n\t\treturn NewTestStruct(), moduleManage.NormalModule\n\t})\n}\n\n\n\n\nfunc (this *testStruct) InitModule() []error {\n\tfmt.Println(\"初始化\")\n\n\treturn nil\n}\n\nfunc (this *testStruct) CheckModule() []error {\n\tfmt.Println(\"check\")\n\n\treturn nil\n}\n\nfunc (this *testStruct) ConvertModule() []error {\n\tfmt.Println(\"数据转换\")\n\n\treturn nil\n}\n\n\nfunc (this *testStruct) C_Hello(request *common.RequestModel, d int, name string) *common.ResultModel {\n\tresult := common.NewResultModel(errorCode.ClientDataError)\n\n\tresult.Value[\"Hello\"] = name + \"_\" + this.Name()\n\tresult.Value[\"Extra\"] = d\n\n\tresult.SetNormalError(errorCode.Success)\n\treturn result\n}\n\nfunc NewTestStruct() *testStruct {\n\treturn &testStruct{\n\t\tclassName: \"TestBLL\",\n\t}\n}\n\nfunc (this *testStruct) Name() string ", "output": "{\n\treturn this.className\n}"} {"input": "package crypto\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\n\t. \"github.com/tendermint/go-common\"\n\t\"golang.org/x/crypto/openpgp/armor\"\n)\n\nfunc EncodeArmor(blockType string, headers map[string]string, data []byte) string {\n\tbuf := new(bytes.Buffer)\n\tw, err := armor.Encode(buf, blockType, headers)\n\tif err != nil {\n\t\tPanicSanity(\"Error encoding ascii armor: \" + err.Error())\n\t}\n\t_, err = w.Write(data)\n\tif err != nil {\n\t\tPanicSanity(\"Error encoding ascii armor: \" + err.Error())\n\t}\n\terr = w.Close()\n\tif err != nil {\n\t\tPanicSanity(\"Error encoding ascii armor: \" + err.Error())\n\t}\n\treturn string(buf.Bytes())\n}\n\n\n\nfunc DecodeArmor(armorStr string) (blockType string, headers map[string]string, data []byte, err error) ", "output": "{\n\tbuf := bytes.NewBufferString(armorStr)\n\tblock, err := armor.Decode(buf)\n\tif err != nil {\n\t\treturn \"\", nil, nil, err\n\t}\n\tdata, err = ioutil.ReadAll(block.Body)\n\tif err != nil {\n\t\treturn \"\", nil, nil, err\n\t}\n\treturn block.Type, block.Header, data, nil\n}"} {"input": "package extra\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\nfunc SetNamingStrategy(translate func(string) string) {\n\tjsoniter.RegisterExtension(&namingStrategyExtension{jsoniter.DummyExtension{}, translate})\n}\n\ntype namingStrategyExtension struct {\n\tjsoniter.DummyExtension\n\ttranslate func(string) string\n}\n\n\n\n\nfunc LowerCaseWithUnderscores(name string) string {\n\tnewName := []rune{}\n\tfor i, c := range name {\n\t\tif i == 0 {\n\t\t\tnewName = append(newName, unicode.ToLower(c))\n\t\t} else {\n\t\t\tif unicode.IsUpper(c) {\n\t\t\t\tnewName = append(newName, '_')\n\t\t\t\tnewName = append(newName, unicode.ToLower(c))\n\t\t\t} else {\n\t\t\t\tnewName = append(newName, c)\n\t\t\t}\n\t\t}\n\t}\n\treturn string(newName)\n}\n\nfunc (extension *namingStrategyExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) ", "output": "{\n\tfor _, binding := range structDescriptor.Fields {\n\t\tif unicode.IsLower(rune(binding.Field.Name()[0])) || binding.Field.Name()[0] == '_'{\n\t\t\tcontinue\n\t\t}\n\t\ttag, hastag := binding.Field.Tag().Lookup(\"json\")\n\t\tif hastag {\n\t\t\ttagParts := strings.Split(tag, \",\")\n\t\t\tif tagParts[0] == \"-\" {\n\t\t\t\tcontinue \n\t\t\t}\n\t\t\tif tagParts[0] != \"\" {\n\t\t\t\tcontinue \n\t\t\t}\n\t\t}\n\t\tbinding.ToNames = []string{extension.translate(binding.Field.Name())}\n\t\tbinding.FromNames = []string{extension.translate(binding.Field.Name())}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", mainHandle)\n\tif err := http.ListenAndServe(\":8080\", nil); err != nil {\n\t\tlog.Fatal(\"Listen and serve:\", err)\n\t}\n}\n\n\ntype reply struct {\n\tLanguage string `json:\"language\"`\n\tOs string `json:\"software\"`\n\tIP string `json:\"ipaddress\"`\n}\n\n\nfunc mainHandle(w http.ResponseWriter, r *http.Request) {\n\theader := r.Header\n\th := fmt.Sprintf(\"%v\", header)\n\taddr := r.RemoteAddr\n\n\tos := parseOs(h)\n\tl := parseLang(h)\n\tip := parseIP(addr)\n\n\treply := reply{Language: l, Os: os, IP: ip}\n\n\tout, err := json.MarshalIndent(reply, \"\", \" \")\n\tif err != nil {\n\t\tfmt.Println(\"Cannot produce json\", err)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"%s\\n\", out)\n}\n\n\n\n\n\n\nfunc parseIP(addr string) string {\n\tip := strings.Split(addr, \":\")[0]\n\treturn ip\n}\n\n\n\n\n\nfunc parseOs(h string) string {\n\ttag := strings.Index(h, \"User-Agent\")\n\tstart := strings.Index(h[tag:], \"(\")\n\tstart += tag + 1 \n\n\tend := strings.Index(h[start:], \")\")\n\tend += start\n\n\treturn h[start:end]\n}\n\nfunc parseLang(h string) string ", "output": "{\n\ttag := strings.Index(h, \"Accept-Language:\")\n\tstart := strings.Index(h[tag:], \"[\")\n\tstart += tag + 1\n\n\tend := strings.Index(h[start:], \"]\")\n\tend += start\n\n\tl := h[start:end]\n\n\treturn strings.Split(l, \";\")[0]\n}"} {"input": "package sqlite\n\nimport (\n\t\"testing\"\n\n\t\"github.com/anmil/quicknote/test\"\n)\n\nvar tableNames = []string{\n\t\"books\",\n\t\"note_book_tag\",\n\t\"note_tag\",\n\t\"notes\",\n\t\"sqlite_sequence\",\n\t\"tags\",\n}\n\nfunc openDatabase(t *testing.T) *Database {\n\tdb, err := NewDatabase(\"file::memory:?cache=shared\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treturn db\n}\n\n\n\nfunc TestCreateDatabaseSQLite(t *testing.T) {\n\tdb := openDatabase(t)\n\tdefer closeDatabase(db, t)\n\n\tif tables, err := db.GetTableNames(); err != nil {\n\t\tt.Fatal(err)\n\t} else if !test.StringSliceEq(tables, tableNames) {\n\t\tt.Fatal(\"Database either has extra or is missing tables\")\n\t}\n}\n\nfunc closeDatabase(db *Database, t *testing.T) ", "output": "{\n\tif err := db.Close(); err != nil {\n\t\tt.Error(err)\n\t}\n}"} {"input": "package ig\n\nimport \"fmt\"\n\n\nfunc (ic *IntelliClimate) SetTempTarget(target float64) error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\n\n\n\nfunc (ic *IntelliClimate) SetRHTarget(target float64) error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\nfunc (ic *IntelliClimate) EnableCO2Dosing() error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\nfunc (ic *IntelliClimate) DisableCO2Dosing() error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\nfunc (ic *IntelliClimate) SetCO2Target(target float64) error ", "output": "{\n\treturn fmt.Errorf(\"not implemented\")\n}"} {"input": "package gospec\n\nimport (\n\t\"fmt\"\n\tfilepath \"path\"\n\t\"runtime\"\n)\n\ntype Location struct {\n\tname string\n\tfile string\n\tline int\n}\n\nfunc currentLocation() *Location {\n\treturn newLocation(1)\n}\n\nfunc callerLocation() *Location {\n\treturn newLocation(2)\n}\n\nfunc newLocation(n int) *Location {\n\tif pc, _, _, ok := runtime.Caller(n + 1); ok {\n\t\treturn locationForPC(pc)\n\t}\n\treturn nil\n}\n\nfunc locationForPC(pc uintptr) *Location {\n\tpc = pcOfWhereCallWasMade(pc)\n\tf := runtime.FuncForPC(pc)\n\tname := f.Name()\n\tfile, line := f.FileLine(pc)\n\treturn &Location{name, file, line}\n}\n\n\n\n\n\n\n\n\nfunc pcOfWhereCallWasMade(pcOfWhereCallReturnsTo uintptr) uintptr {\n\treturn pcOfWhereCallReturnsTo - 1\n}\n\n\nfunc (this *Location) File() string { return this.file }\nfunc (this *Location) FileName() string { return filename(this.file) }\nfunc (this *Location) Line() int { return this.line }\n\nfunc filename(path string) string {\n\t_, file := filepath.Split(path)\n\treturn file\n}\n\nfunc (this *Location) equals(that *Location) bool {\n\treturn this.name == that.name &&\n\t\tthis.file == that.file &&\n\t\tthis.line == that.line\n}\n\nfunc (this *Location) String() string {\n\treturn fmt.Sprintf(\"%v:%v\", this.FileName(), this.Line())\n}\n\nfunc (this *Location) Name() string ", "output": "{ return this.name }"} {"input": "package udp\n\nimport (\n\t\"reflect\"\n\t\"time\"\n\n\t\"shadowss/pkg/config\"\n\t\"shadowss/pkg/crypto\"\n\n\t\"github.com/golang/glog\"\n)\n\n\ntype UDPServer struct {\n\tConfig *config.ConnectionInfo\n\tudpProxy *Proxy\n}\n\n\nfunc NewUDPServer(cfg *config.ConnectionInfo) *UDPServer {\n\treturn &UDPServer{\n\t\tConfig: cfg,\n\t}\n}\n\n\nfunc (udpSrv *UDPServer) Stop() {\n\tglog.V(5).Infof(\"udp server close %v\\r\\n\", udpSrv.Config)\n\tudpSrv.udpProxy.Stop()\n}\n\n\nfunc (udpSrv *UDPServer) Traffic() (int64, int64) {\n\treturn udpSrv.udpProxy.Traffic()\n}\n\n\n\n\nfunc (udpSrv *UDPServer) Compare(client *config.ConnectionInfo) bool {\n\treturn reflect.DeepEqual(udpSrv.Config, client)\n}\n\nfunc (udpSrv *UDPServer) GetListenPort() int {\n\treturn udpSrv.Config.Port\n}\n\nfunc (udpSrv *UDPServer) GetConfig() config.ConnectionInfo {\n\treturn *udpSrv.Config\n}\n\nfunc (udpSrv *UDPServer) GetLastActiveTime() time.Time {\n\treturn time.Now()\n}\n\nfunc (udpSrv *UDPServer) Run() ", "output": "{\n\n\tpassword := udpSrv.Config.Password\n\tmethod := udpSrv.Config.EncryptMethod\n\tport := udpSrv.Config.Port\n\tauth := udpSrv.Config.EnableOTA\n\ttimeout := time.Duration(udpSrv.Config.Timeout) * time.Second\n\n\tcrypto, err := crypto.NewCrypto(method, password)\n\tif err != nil {\n\t\tglog.Errorf(\"Error generating cipher for udp port: %d %v\\n\", port, err)\n\t\treturn\n\t}\n\n\tproxy := NewProxy(port, crypto, auth, timeout)\n\tif proxy == nil {\n\t\tglog.Errorf(\"listening upd port: %v error:%v\\r\\n\", port, err)\n\t\treturn\n\t}\n\tudpSrv.udpProxy = proxy\n\n\tudpSrv.Config.Port = udpSrv.udpProxy.GetPort()\n\n\tgo proxy.RunProxy()\n}"} {"input": "package entities\n\nconst (\n\tActionMove = iota + 1\n\n\tActionAttack\n\n\tActionCastSpell\n\n\tActionGather\n\n\tActionLoot\n\n\tActionConsume\n)\n\n\n\n\n\n\n\n\n\n\n\ntype Action interface {\n\tSetTarget(Entity)\n\tSetSelf(Entity)\n\n\tGetTypeAction() uint8\n\tGetSelf() Entity\n\tGetTarget() Entity\n\n\tPlay() error\n}\n\n\ntype SimpleAction struct {\n\tself Entity\n\ttarget Entity\n\ttypeAction uint8\n}\n\n\nfunc (action *SimpleAction) GetTypeAction() uint8 {\n\treturn action.GetTypeAction()\n}\n\n\n\n\n\nfunc (action *SimpleAction) GetTarget() Entity {\n\treturn action.target\n}\n\n\nfunc (action *SimpleAction) SetSelf(self Entity) {\n\taction.self = self\n}\n\n\nfunc (action *SimpleAction) GetSelf() Entity {\n\treturn action.self\n}\n\n\nfunc (action *SimpleAction) Play() error {\n\treturn nil\n}\n\nfunc (action *SimpleAction) SetTarget(target Entity) ", "output": "{\n\taction.target = target\n}"} {"input": "package gooh\n\ntype MemoryContext struct {\n\tdata map[string]interface{}\n}\n\nfunc (c *MemoryContext) Get(k string) (interface{}, error) {\n\treturn c.data[k], nil\n}\n\n\n\nfunc (c *MemoryContext) Exists(k string) (bool, error) {\n\t_, ok := c.data[k]\n\treturn ok, nil\n}\n\nfunc (c *MemoryContext) Set(k string, d interface{}) error ", "output": "{\n\tif c.data == nil {\n\t\tc.data = make(map[string]interface{})\n\t}\n\tc.data[k] = d\n\treturn nil\n}"} {"input": "package iso20022\n\n\ntype CardPaymentTransaction42 struct {\n\n\tSaleReferenceIdentification *Max35Text `xml:\"SaleRefId,omitempty\"`\n\n\tTransactionIdentification *TransactionIdentifier1 `xml:\"TxId\"`\n\n\tRecipientTransactionIdentification *Max35Text `xml:\"RcptTxId,omitempty\"`\n\n\tReconciliationIdentification *Max35Text `xml:\"RcncltnId,omitempty\"`\n\n\tInterchangeData *Max140Text `xml:\"IntrchngData,omitempty\"`\n\n\tTransactionDetails *CardPaymentTransactionDetails22 `xml:\"TxDtls\"`\n}\n\n\n\nfunc (c *CardPaymentTransaction42) AddTransactionIdentification() *TransactionIdentifier1 {\n\tc.TransactionIdentification = new(TransactionIdentifier1)\n\treturn c.TransactionIdentification\n}\n\nfunc (c *CardPaymentTransaction42) SetRecipientTransactionIdentification(value string) {\n\tc.RecipientTransactionIdentification = (*Max35Text)(&value)\n}\n\nfunc (c *CardPaymentTransaction42) SetReconciliationIdentification(value string) {\n\tc.ReconciliationIdentification = (*Max35Text)(&value)\n}\n\nfunc (c *CardPaymentTransaction42) SetInterchangeData(value string) {\n\tc.InterchangeData = (*Max140Text)(&value)\n}\n\nfunc (c *CardPaymentTransaction42) AddTransactionDetails() *CardPaymentTransactionDetails22 {\n\tc.TransactionDetails = new(CardPaymentTransactionDetails22)\n\treturn c.TransactionDetails\n}\n\nfunc (c *CardPaymentTransaction42) SetSaleReferenceIdentification(value string) ", "output": "{\n\tc.SaleReferenceIdentification = (*Max35Text)(&value)\n}"} {"input": "package cleanhttp\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"runtime\"\n\t\"time\"\n)\n\n\n\nfunc DefaultTransport() *http.Transport {\n\ttransport := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t}\n\tSetTransportFinalizer(transport)\n\treturn transport\n}\n\n\n\nfunc DefaultClient() *http.Client {\n\treturn &http.Client{\n\t\tTransport: DefaultTransport(),\n\t}\n}\n\n\n\n\n\n\nfunc SetTransportFinalizer(transport *http.Transport) ", "output": "{\n\truntime.SetFinalizer(&transport, func(t **http.Transport) {\n\t\t(*t).CloseIdleConnections()\n\t})\n}"} {"input": "package calendar\n\nimport (\n\t\"time\"\n)\n\nvar (\n\tentries = make(map[int]Entry)\n\tindex int\n)\n\ntype Entry struct {\n\tID int\n\tTitle string\n\tStarts time.Time\n\tFinishes time.Time\n}\n\nfunc (e Entry) Duration() time.Duration {\n\treturn e.Finishes.Sub(e.Starts)\n}\n\nfunc Lookup(id int) (Entry, bool) {\n\te, isPresent := entries[id]\n\treturn e, isPresent\n}\n\nfunc Add(e Entry) Entry {\n\tindex++\n\te.ID = index\n\tUpdate(e)\n\treturn e\n}\n\n\n\nfunc Remove(id int) {\n\tdelete(entries, id)\n}\n\nfunc Count() int {\n\treturn len(entries)\n}\n\nfunc All() []Entry {\n\tall := []Entry{}\n\tfor _, e := range entries {\n\t\tall = append(all, e)\n\t}\n\treturn all\n}\n\nfunc Update(e Entry) ", "output": "{\n\tentries[e.ID] = e\n}"} {"input": "package conversion\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n)\n\n\n\n\n\n\nfunc (s *Scheme) Decode(data []byte) (interface{}, error) {\n\tversion, kind, err := s.DataVersionAndKind(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif version == \"\" && s.InternalVersion != \"\" {\n\t\treturn nil, fmt.Errorf(\"version not set in '%s'\", string(data))\n\t}\n\tif kind == \"\" {\n\t\treturn nil, fmt.Errorf(\"kind not set in '%s'\", string(data))\n\t}\n\tobj, err := s.NewObject(version, kind)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := json.Unmarshal(data, obj); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := s.SetVersionAndKind(\"\", \"\", obj); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif s.InternalVersion != version {\n\t\tobjOut, err := s.NewObject(s.InternalVersion, kind)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := s.converter.Convert(obj, objOut, 0, s.generateConvertMeta(version, s.InternalVersion)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tobj = objOut\n\t}\n\treturn obj, nil\n}\n\n\n\n\n\n\n\n\nfunc (s *Scheme) DecodeInto(data []byte, obj interface{}) error ", "output": "{\n\tif len(data) == 0 {\n\t\treturn errors.New(\"empty input\")\n\t}\n\tdataVersion, dataKind, err := s.DataVersionAndKind(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tobjVersion, objKind, err := s.ObjectVersionAndKind(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif dataKind == \"\" {\n\t\tdataKind = objKind\n\t}\n\tif dataVersion == \"\" {\n\t\tdataVersion = objVersion\n\t}\n\n\texternal, err := s.NewObject(dataVersion, dataKind)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := json.Unmarshal(data, external); err != nil {\n\t\treturn err\n\t}\n\tif err := s.converter.Convert(external, obj, 0, s.generateConvertMeta(dataVersion, objVersion)); err != nil {\n\t\treturn err\n\t}\n\n\treturn s.SetVersionAndKind(\"\", \"\", obj)\n}"} {"input": "package log\n\nimport (\n\t\"testing\"\n)\n\ntype testLogger struct {\n\tkeyvals []interface{}\n}\n\nfunc (tl *testLogger) Log(keyvals ...interface{}) error {\n\ttl.keyvals = keyvals\n\treturn nil\n}\n\ntype testSink struct {\n\tkeyvals []interface{}\n}\n\nfunc (ts *testSink) Receive(keyvals ...interface{}) error {\n\tts.keyvals = keyvals\n\treturn nil\n}\n\n\n\nfunc TestLogger_Event(t *testing.T) {\n\tts := &testSink{}\n\ttl := &testLogger{}\n\tl := NewLogger(tl, []EventSink{ts})\n\n\tl.Event(\"important_event\", \"act_on_me\")\n\tif len(ts.keyvals) != 2 {\n\t\tt.Errorf(\"Expected to recieve event with 2 values, got %v\", len(ts.keyvals))\n\t}\n\n\tm1 := ts.keyvals[0]\n\tm2 := ts.keyvals[1]\n\tif m1.(string) != \"important_event\" || m2.(string) != \"act_on_me\" {\n\t\tt.Errorf(\"Expected [important_event, act_on_me] but got %s\", ts.keyvals)\n\t}\n}\n\nfunc TestLogger_Log(t *testing.T) ", "output": "{\n\ttl := &testLogger{}\n\tl := NewLogger(tl, nil)\n\n\tl.Log(\"message\", \"value\")\n\tif len(tl.keyvals) != 2 {\n\t\tt.Errorf(\"Expected log message with 2 values, got %v\", len(tl.keyvals))\n\t}\n\n\tm1 := tl.keyvals[0]\n\tm2 := tl.keyvals[1]\n\tif m1.(string) != \"message\" || m2.(string) != \"value\" {\n\t\tt.Errorf(\"Expected [message, value] but got %s\", tl.keyvals)\n\t}\n}"} {"input": "package main\n\nimport \"reflect\"\n\n\n\n\n\n\nvar a, b int\n\nfunc chanreflect1() {\n\tch := make(chan *int, 0)\n\tcrv := reflect.ValueOf(ch)\n\tcrv.Send(reflect.ValueOf(&a))\n\tprint(crv.Interface()) \n\tprint(crv.Interface().(chan *int)) \n\tprint(<-ch) \n}\n\n\n\nfunc main() {\n\tchanreflect1()\n\tchanreflect2()\n}\n\nfunc chanreflect2() ", "output": "{\n\tch := make(chan *int, 0)\n\tch <- &b\n\tcrv := reflect.ValueOf(ch)\n\tr, _ := crv.Recv()\n\tprint(r.Interface()) \n\tprint(r.Interface().(*int)) \n}"} {"input": "package godo\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst billingHistoryBasePath = \"v2/customers/my/billing_history\"\n\n\n\n\ntype BillingHistoryService interface {\n\tList(context.Context, *ListOptions) (*BillingHistory, *Response, error)\n}\n\n\n\ntype BillingHistoryServiceOp struct {\n\tclient *Client\n}\n\nvar _ BillingHistoryService = &BillingHistoryServiceOp{}\n\n\ntype BillingHistory struct {\n\tBillingHistory []BillingHistoryEntry `json:\"billing_history\"`\n\tLinks *Links `json:\"links\"`\n\tMeta *Meta `json:\"meta\"`\n}\n\n\ntype BillingHistoryEntry struct {\n\tDescription string `json:\"description\"`\n\tAmount string `json:\"amount\"`\n\tInvoiceID *string `json:\"invoice_id\"`\n\tInvoiceUUID *string `json:\"invoice_uuid\"`\n\tDate time.Time `json:\"date\"`\n\tType string `json:\"type\"`\n}\n\n\n\n\nfunc (s *BillingHistoryServiceOp) List(ctx context.Context, opt *ListOptions) (*BillingHistory, *Response, error) {\n\tpath, err := addOptions(billingHistoryBasePath, opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := s.client.NewRequest(ctx, http.MethodGet, path, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\troot := new(BillingHistory)\n\tresp, err := s.client.Do(ctx, req, root)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\tif l := root.Links; l != nil {\n\t\tresp.Links = l\n\t}\n\tif m := root.Meta; m != nil {\n\t\tresp.Meta = m\n\t}\n\n\treturn root, resp, err\n}\n\nfunc (b BillingHistory) String() string ", "output": "{\n\treturn Stringify(b)\n}"} {"input": "package govaluate\n\ntype lexerStream struct {\n\tsource []rune\n\tposition int\n\tlength int\n}\n\nfunc newLexerStream(source string) *lexerStream {\n\n\tvar ret *lexerStream\n\tvar runes []rune\n\n\tfor _, character := range source {\n\t\trunes = append(runes, character)\n\t}\n\n\tret = new(lexerStream)\n\tret.source = runes\n\tret.length = len(runes)\n\treturn ret\n}\n\n\n\nfunc (l *lexerStream) rewind(amount int) {\n\tl.position -= amount\n}\n\nfunc (l lexerStream) canRead() bool {\n\treturn l.position < l.length\n}\n\nfunc (l *lexerStream) readCharacter() rune ", "output": "{\n\n\tvar character rune\n\n\tcharacter = l.source[l.position]\n\tl.position++\n\treturn character\n}"} {"input": "package townsita\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"os\"\n)\n\nconst defaultConfigFile = \"./config/townsita.json\"\n\ntype Config struct{}\n\nfunc NewConfig() *Config {\n\treturn &Config{}\n}\n\n\n\nfunc (c *Config) templatePath(templateName string) string {\n\treturn \"./templates/\" + templateName\n}\n\nfunc (c *Config) Load(args []string) error ", "output": "{\n\tfileName := defaultConfigFile\n\tif len(args) > 1 {\n\t\tfileName = args[1]\n\t}\n\tlog.Printf(\"Loading config from %s\", fileName)\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdecoder := json.NewDecoder(file)\n\tif err := decoder.Decode(c); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package iso20022\n\n\ntype PlainCardData4 struct {\n\n\tPAN *Min8Max28NumericText `xml:\"PAN\"`\n\n\tCardSequenceNumber *Min2Max3NumericText `xml:\"CardSeqNb,omitempty\"`\n\n\tEffectiveDate *Max10Text `xml:\"FctvDt,omitempty\"`\n\n\tExpiryDate *Max10Text `xml:\"XpryDt\"`\n\n\tServiceCode *Exact3NumericText `xml:\"SvcCd,omitempty\"`\n\n\tTrackData []*TrackData1 `xml:\"TrckData,omitempty\"`\n\n\tCardSecurityCode *CardSecurityInformation1 `xml:\"CardSctyCd,omitempty\"`\n}\n\nfunc (p *PlainCardData4) SetPAN(value string) {\n\tp.PAN = (*Min8Max28NumericText)(&value)\n}\n\nfunc (p *PlainCardData4) SetCardSequenceNumber(value string) {\n\tp.CardSequenceNumber = (*Min2Max3NumericText)(&value)\n}\n\nfunc (p *PlainCardData4) SetEffectiveDate(value string) {\n\tp.EffectiveDate = (*Max10Text)(&value)\n}\n\nfunc (p *PlainCardData4) SetExpiryDate(value string) {\n\tp.ExpiryDate = (*Max10Text)(&value)\n}\n\nfunc (p *PlainCardData4) SetServiceCode(value string) {\n\tp.ServiceCode = (*Exact3NumericText)(&value)\n}\n\nfunc (p *PlainCardData4) AddTrackData() *TrackData1 {\n\tnewValue := new(TrackData1)\n\tp.TrackData = append(p.TrackData, newValue)\n\treturn newValue\n}\n\n\n\nfunc (p *PlainCardData4) AddCardSecurityCode() *CardSecurityInformation1 ", "output": "{\n\tp.CardSecurityCode = new(CardSecurityInformation1)\n\treturn p.CardSecurityCode\n}"} {"input": "package main\nimport \"bufio\"\nimport \"crypto/tls\"\nimport \"fmt\"\nimport \"net\"\n \nfunc main() {\n\tDial(\":1025\", ConfigTLS(\"ccert\", \"ckey\"), func(c net.Conn) {\n\t\tif m, e := bufio.NewReader(c).ReadString('\\n'); e == nil {\n\t\t\tfmt.Printf(m)\n\t\t}\n\t})\n}\n\nfunc ConfigTLS(c, k string) (r *tls.Config) {\n\tif cert, e := tls.LoadX509KeyPair(c, k); e == nil {\n\t\tr = &tls.Config{\n\t\t\tCertificates: []tls.Certificate{ cert },\n\t\t\tInsecureSkipVerify: true,\n\t\t}\n\t}\n\treturn\n}\n\n\n\nfunc Dial(a string, conf *tls.Config, f func(net.Conn)) ", "output": "{\n\tif c, e := tls.Dial(\"tcp\", a, conf); e == nil {\n\t\tdefer c.Close()\n\t\tf(c)\n\t}\n}"} {"input": "package numericword\n\n\n\nimport (\n\t\"fmt\"\n)\n\nvar (\n\tbigkeys = []int64{\n\t\t1000000000000000000,\n\t\t1000000000000000,\n\t\t1000000000000,\n\t\t1000000000,\n\t\t1000000,\n\t\t1000,\n\t\t100}\n\n\tbignames = map[int64]string{\n\t\t1000000000000000000: \"quintillion\",\n\t\t1000000000000000: \"quadrillion\",\n\t\t1000000000000: \"trillion\",\n\t\t1000000000: \"billion\",\n\t\t1000000: \"million\",\n\t\t1000: \"thousand\",\n\t\t100: \"hundred\"}\n\n\ttens = []string{\n\t\t\"\",\n\t\t\"\",\n\t\t\"twenty\",\n\t\t\"thirty\",\n\t\t\"forty\",\n\t\t\"fifty\",\n\t\t\"sixty\",\n\t\t\"seventy\",\n\t\t\"eighty\",\n\t\t\"ninety\"}\n\n\tones = []string{\n\t\t\"zero\",\n\t\t\"one\",\n\t\t\"two\",\n\t\t\"three\",\n\t\t\"four\",\n\t\t\"five\",\n\t\t\"six\",\n\t\t\"seven\",\n\t\t\"eight\",\n\t\t\"nine\",\n\t\t\"ten\",\n\t\t\"eleven\",\n\t\t\"twelve\",\n\t\t\"thirteen\",\n\t\t\"fourteen\",\n\t\t\"fifteen\",\n\t\t\"sixteen\",\n\t\t\"seventeen\",\n\t\t\"eighteen\",\n\t\t\"nineteen\"}\n)\n\n\n\n\nfunc ToWords(i int64) string {\n\tif i < 0 {\n\t\treturn fmt.Sprintf(\"negative %s\", convert(-1*i))\n\t}\n\treturn convert(i)\n}\n\nfunc convert(i int64) string ", "output": "{\n\tif i < 20 {\n\t\treturn ones[i]\n\t} else if i < 100 && i%10 == 0 {\n\t\treturn tens[i/10]\n\t} else if i < 100 {\n\t\treturn fmt.Sprintf(\"%s %s\", tens[i/10], convert(i%10))\n\t}\n\n\tfor j := 0; j < len(bigkeys); j++ {\n\t\tplace := bigkeys[j]\n\t\tif i >= place {\n\t\t\tif i%place == 0 {\n\t\t\t\treturn fmt.Sprintf(\"%s %s\", convert(i/place), bignames[place])\n\t\t\t} else {\n\t\t\t\treturn fmt.Sprintf(\"%s %s %s\",\n\t\t\t\t\tconvert(i/place),\n\t\t\t\t\tbignames[place],\n\t\t\t\t\tconvert(i%place))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"oops\"\n}"} {"input": "package jsonutil\n\nimport (\n\t\"github.com/buger/jsonparser\"\n\t\"strconv\"\n)\n\nfunc GetString(data []byte, keys ...string) (string, error) {\n\treturn jsonparser.GetString(data, keys...)\n}\n\nfunc MustGetString(data []byte, keys ...string) string {\n\ts, err := GetString(data, keys...)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s\n}\n\nfunc GetFloat(data []byte, keys ...string) (float64, error) {\n\treturn jsonparser.GetFloat(data, keys...)\n}\n\nfunc MustGetFloat(data []byte, keys ...string) float64 {\n\tf, err := GetFloat(data, keys...)\n\tif err != nil {\n\t\treturn 0.0\n\t}\n\treturn f\n}\n\n\n\nfunc MustGetInt(data []byte, keys ...string) int64 {\n\ti, err := GetInt(data, keys...)\n\tif err != nil {\n\t\tif s := MustGetString(data, keys...); len(s) == 0 {\n\t\t\treturn 0\n\t\t} else if i, err = strconv.ParseInt(s, 10, 64); err != nil {\n\t\t\treturn 0\n\t\t}\n\t}\n\treturn i\n}\n\nfunc GetBoolean(data []byte, keys ...string) (bool, error) {\n\treturn jsonparser.GetBoolean(data, keys...)\n}\n\nfunc MustGetBoolean(data []byte, keys ...string) bool {\n\tb, err := GetBoolean(data, keys...)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn b\n}\n\nfunc GetInt(data []byte, keys ...string) (int64, error) ", "output": "{\n\treturn jsonparser.GetInt(data, keys...)\n}"} {"input": "package update\n\nimport (\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/emicklei/go-restful/log\"\n\t\"github.com/kubernetes-incubator/apiserver-builder/cmd/apiserver-boot/boot/init_repo\"\n)\n\nvar vendorCmd = &cobra.Command{\n\tUse: \"vendor\",\n\tShort: \"Update the vendor packages managed by apiserver-builder.\",\n\tLong: `Update the vendor packages managed by apiserver-builder.`,\n\tExample: `# Replace the vendor packages managed by apiserver-builder with versions for the current install.\napiserver-boot update vendor\n`,\n\tRun: RunUpdateVendor,\n}\n\n\n\nfunc RunUpdateVendor(cmd *cobra.Command, args []string) {\n\tinit_repo.Update = true\n\tlog.Printf(\"Replacing vendored libraries managed by apiserver-builder with the current version.\")\n\tinit_repo.CopyGlide()\n}\n\nfunc AddUpdateVendorCmd(cmd *cobra.Command) ", "output": "{\n\tcmd.AddCommand(vendorCmd)\n}"} {"input": "package testutils\n\n\ntype BlockingRW struct{ nilChan chan struct{} }\n\nfunc (rw *BlockingRW) Read(p []byte) (n int, err error) {\n\t<-rw.nilChan\n\treturn\n}\n\n\n\n\ntype NoopRW struct{}\n\nfunc (rw *NoopRW) Read(p []byte) (n int, err error) {\n\treturn len(p), nil\n}\n\nfunc (rw *NoopRW) Write(p []byte) (n int, err error) {\n\treturn len(p), nil\n}\n\nfunc (rw *BlockingRW) Write(p []byte) (n int, err error) ", "output": "{\n\t<-rw.nilChan\n\treturn\n}"} {"input": "package caaa\n\nimport (\n\t\"encoding/xml\"\n\n\t\"github.com/fgrid/iso20022\"\n)\n\ntype Document00900101 struct {\n\tXMLName xml.Name `xml:\"urn:iso:std:iso:20022:tech:xsd:caaa.009.001.01 Document\"`\n\tMessage *AcceptorReconciliationRequestV01 `xml:\"AccptrRcncltnReq\"`\n}\n\n\n\n\n\n\n\n\ntype AcceptorReconciliationRequestV01 struct {\n\n\tHeader *iso20022.Header1 `xml:\"Hdr\"`\n\n\tReconciliationRequest *iso20022.AcceptorReconciliationRequest1 `xml:\"RcncltnReq\"`\n\n\tSecurityTrailer *iso20022.ContentInformationType3 `xml:\"SctyTrlr\"`\n}\n\nfunc (a *AcceptorReconciliationRequestV01) AddHeader() *iso20022.Header1 {\n\ta.Header = new(iso20022.Header1)\n\treturn a.Header\n}\n\nfunc (a *AcceptorReconciliationRequestV01) AddReconciliationRequest() *iso20022.AcceptorReconciliationRequest1 {\n\ta.ReconciliationRequest = new(iso20022.AcceptorReconciliationRequest1)\n\treturn a.ReconciliationRequest\n}\n\nfunc (a *AcceptorReconciliationRequestV01) AddSecurityTrailer() *iso20022.ContentInformationType3 {\n\ta.SecurityTrailer = new(iso20022.ContentInformationType3)\n\treturn a.SecurityTrailer\n}\n\nfunc (d *Document00900101) AddMessage() *AcceptorReconciliationRequestV01 ", "output": "{\n\td.Message = new(AcceptorReconciliationRequestV01)\n\treturn d.Message\n}"} {"input": "package template\n\nimport (\n\t\"github.com/dpb587/metalink\"\n)\n\ntype templateFile metalink.File\n\n\n\nfunc (tf templateFile) SHA1() string {\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"sha-1\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\nfunc (tf templateFile) SHA256() string {\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"sha-256\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\nfunc (tf templateFile) SHA512() string {\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"sha-512\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\nfunc (tf templateFile) MD5() string ", "output": "{\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"md5\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestMatchWithTag(t *testing.T) {\n\tisMatch := matchesReference(\"gcr.io/pause:latest\", \"pause:latest\")\n\tif !isMatch {\n\t\tt.Error(\"expected match, got not match\")\n\t}\n\n\tisMatch = matchesReference(\"gcr.io/pause:latest\", \"kubernetes/pause:latest\")\n\tif isMatch {\n\t\tt.Error(\"expected not match, got match\")\n\t}\n}\n\nfunc TestNoMatchesReferenceWithTag(t *testing.T) {\n\tisMatch := matchesReference(\"gcr.io/pause:latest\", \"redis:latest\")\n\tif isMatch {\n\t\tt.Error(\"expected no match, got match\")\n\t}\n\n\tisMatch = matchesReference(\"gcr.io/pause:latest\", \"kubernetes/redis:latest\")\n\tif isMatch {\n\t\tt.Error(\"expected no match, got match\")\n\t}\n}\n\nfunc TestMatchesReferenceWithoutTag(t *testing.T) {\n\tisMatch := matchesReference(\"gcr.io/pause:latest\", \"pause\")\n\tif !isMatch {\n\t\tt.Error(\"expected match, got not match\")\n\t}\n\n\tisMatch = matchesReference(\"gcr.io/pause:latest\", \"kubernetes/pause\")\n\tif isMatch {\n\t\tt.Error(\"expected not match, got match\")\n\t}\n}\n\nfunc TestNoMatchesReferenceWithoutTag(t *testing.T) {\n\tisMatch := matchesReference(\"gcr.io/pause:latest\", \"redis\")\n\tif isMatch {\n\t\tt.Error(\"expected no match, got match\")\n\t}\n\n\tisMatch = matchesReference(\"gcr.io/pause:latest\", \"kubernetes/redis\")\n\tif isMatch {\n\t\tt.Error(\"expected no match, got match\")\n\t}\n}\n\nfunc TestSizeFormatting(t *testing.T) ", "output": "{\n\tsize := formattedSize(0)\n\tif size != \"0 B\" {\n\t\tt.Errorf(\"Error formatting size: expected '%s' got '%s'\", \"0 B\", size)\n\t}\n\n\tsize = formattedSize(1000)\n\tif size != \"1 KB\" {\n\t\tt.Errorf(\"Error formatting size: expected '%s' got '%s'\", \"1 KB\", size)\n\t}\n\n\tsize = formattedSize(1000 * 1000 * 1000 * 1000)\n\tif size != \"1 TB\" {\n\t\tt.Errorf(\"Error formatting size: expected '%s' got '%s'\", \"1 TB\", size)\n\t}\n}"} {"input": "package insights\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/\" + version.Number + \" insights/2015-05-01\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package task\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Event struct {\n\tTask *Task\n\tPayload interface{}\n}\n\nfunc (e *Event) String() string {\n\treturn fmt.Sprintf(\"%T{from %v: %v}\", e, e.Task, e.Payload)\n}\n\n\n\ntype Ended struct {\n\tError error\n}\n\n\n\n\ntype Output struct {\n\tChunk string\n}\n\nfunc (p *Output) String() string {\n\treturn fmt.Sprintf(\"%T{%v}\", p, p.Chunk)\n}\n\nfunc (p *Ended) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%T{%v}\", p, p.Error)\n}"} {"input": "package building\n\nimport \"fmt\"\n\ntype Single struct {\n\tprefix string\n\toption string\n}\n\nfunc (s Single) IsPresent() bool {\n\treturn s.option != \"\"\n}\n\nfunc (s Single) Build() string {\n\treturn fmt.Sprintf(\"%s %s\", s.prefix, s.option)\n}\n\n\n\nfunc NewSingleBuilder(prefix, value string) Single ", "output": "{\n\treturn Single{prefix, value}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"github.com/teddywing/new-house-on-the-block/purchase\"\n)\n\n\n\nfunc sendTokenToBuyer() error {\n\ttransaction_id, err := purchase.SendMoney(os.Getenv(\"SELLER_COINBASE_KEY\"),\n\t\tos.Getenv(\"SELLER_COINBASE_SECRET\"),\n\t\t\"mqy3kT6aFHymTcvmdwZLKq1Svo2m6sUtzH\",\n\t\t\"0.0001\")\n\tif err != nil {\n\t\treturn err\n\t} else {\n\t\tfmt.Println(transaction_id)\n\t\treturn nil\n\t}\n}\n\nfunc main() {\n\tfs := http.FileServer(http.Dir(\"static\"))\n\thttp.Handle(\"/\", fs)\n\n\thttp.HandleFunc(\"/buy/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tvar err error\n\n\t\terr = sendMoneyToSeller()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\terr = sendTokenToBuyer()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\thttp.Redirect(w, r, \"http://testsite.perfectburpee.com/new-house-on-the-block-page6/\", 302)\n\t})\n\n\tlog.Println(\"Listening on port 3000\")\n\thttp.ListenAndServe(\":3000\", nil)\n}\n\nfunc sendMoneyToSeller() error ", "output": "{\n\ttransaction_id, err := purchase.SendMoney(os.Getenv(\"COINBASE_KEY\"),\n\t\tos.Getenv(\"COINBASE_SECRET\"),\n\t\t\"n2Qd6da1jiFgij5SSncFKh7MoFN74GdUxv\",\n\t\t\"0.0001\")\n\tif err != nil {\n\t\treturn err\n\t} else {\n\t\tfmt.Println(transaction_id)\n\t\treturn nil\n\t}\n}"} {"input": "package model\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestGetUsersById(t *testing.T) {\n\tuser, err := GetUserByID(3)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif user.FirstName != \"Jonathan\" {\n\t\tt.Errorf(\"should have returned the first name of %s\", user.FirstName)\n\t}\n}\n\nfunc TestGetUsers(t *testing.T) ", "output": "{\n\tusers := GetUsers()\n\tif len(users) != 50 {\n\t\tt.Errorf(\"Should have returned a list of 50 users\")\n\t}\n}"} {"input": "package csi_test\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n\n\tgofigCore \"github.com/akutz/gofig\"\n\tgofig \"github.com/akutz/gofig/types\"\n)\n\nfunc init() {\n\tr := gofigCore.NewRegistration(\"MapTest\")\n\tr.Key(gofig.String,\n\t\t\"\", \"\", \"\",\n\t\t\"nfs.volumes\")\n\tgofigCore.Register(r)\n}\n\n\n\nfunc TestGofigMap(t *testing.T) ", "output": "{\n\tconfig := gofigCore.NewConfig(false, false, \"config\", \"yaml\")\n\tconfig.ReadConfig(strings.NewReader(`\nnfs:\n volumes:\n - name1=uri1\n - name2=uri2\n - name3=uri3\n`))\n\tasSlice := config.GetStringSlice(\"nfs.volumes\")\n\tfmt.Printf(\"GetStringSlice: len=%d, %v\\n\", len(asSlice), asSlice)\n\n\tos.Setenv(\"NFS_VOLUMES\", \"name4=uri4 name5=uri5\")\n\tasSlice = config.GetStringSlice(\"nfs.volumes\")\n\tfmt.Printf(\"GetStringSlice: len=%d, %v\\n\", len(asSlice), asSlice)\n}"} {"input": "package assert\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/alecthomas/colour\"\n\t\"github.com/alecthomas/repr\"\n\t\"github.com/sergi/go-diff/diffmatchpatch\"\n)\n\nfunc DiffValues(a, b interface{}) string {\n\tprinter := colour.String()\n\tdiff := diffmatchpatch.New()\n\tat := repr.String(a, repr.OmitEmpty())\n\tbt := repr.String(b, repr.OmitEmpty())\n\tdiffs := diff.DiffMain(at, bt, true)\n\tfor _, d := range diffs {\n\t\tswitch d.Type {\n\t\tcase diffmatchpatch.DiffEqual:\n\t\t\tif len(d.Text) <= 40 {\n\t\t\t\tprinter.Print(d.Text)\n\t\t\t} else {\n\t\t\t\tprinter.Printf(\"%s^B...^R%s\", d.Text[:15], d.Text[len(d.Text)-15:])\n\t\t\t}\n\t\tcase diffmatchpatch.DiffDelete:\n\t\t\tprinter.Printf(\"^9%s^R\", d.Text)\n\t\tcase diffmatchpatch.DiffInsert:\n\t\t\tprinter.Printf(\"^a%s^R\", d.Text)\n\t\t}\n\t}\n\treturn printer.String()\n}\n\n\n\nfunc DiffValuesDefault(a, b interface{}) string ", "output": "{\n\tdiff := diffmatchpatch.New()\n\tat := repr.String(a)\n\tbt := repr.String(b)\n\tdiffs := diff.DiffMain(at, bt, true)\n\tw := bytes.NewBuffer(nil)\n\tfor _, d := range diffs {\n\t\tswitch d.Type {\n\t\tcase diffmatchpatch.DiffEqual:\n\t\t\tif len(d.Text) <= 40 {\n\t\t\t\tw.WriteString(d.Text)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(w, \"%s...%s\", d.Text[:15], d.Text[len(d.Text)-15:])\n\t\t\t}\n\t\tcase diffmatchpatch.DiffDelete:\n\t\t\tfmt.Fprintf(w, \"-{{%s}}\", d.Text)\n\t\tcase diffmatchpatch.DiffInsert:\n\t\t\tfmt.Fprintf(w, \"+{{%s}}\", d.Text)\n\t\t}\n\t}\n\treturn w.String()\n}"} {"input": "package fractal\n\nimport (\n\t\"reflect\"\n\t\"github.com/nsf/termbox-go\"\n\t\"testing\"\n)\n\nfunc TestFrameProxyMan(t *testing.T) {\n\tmyManual := Manual{\n\t\tSummary: \"sup\",\n\t\tKeys: KeyMap{\n\t\t\ttermbox.Event{Ch: 'j'}: {\n\t\t\t\tID: \"wow\",\n\t\t\t\tDescription: \"now\",\n\t\t\t},\n\t\t},\n\t}\n\thandler := &TestHandler{Manual: myManual}\n\tif !reflect.DeepEqual(handler.Man(), NewFrameProxy(handler, 0, 0).Man()) {\n\t\tt.Errorf(\"did not proxy Man correctly\")\n\t}\n}\n\n\n\nfunc TestFrameProxyCursor(t *testing.T) ", "output": "{\n\thandler := &TestHandler{}\n\tproxy := NewFrameProxy(handler, 0, 0)\n\tproxy.Frame.bwidth, proxy.Frame.bheight = 2, 2\n\toffsetCursor := handler.GetCursor()\n\toffsetCursor.X++\n\toffsetCursor.Y++\n\n\tif offsetCursor != proxy.GetCursor() {\n\t\tt.Errorf(\"did not proxy GetCursor correctly\")\n\t}\n}"} {"input": "package oauth\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\n\n\n\nfunc (c oauthClient) AvatarURL(userID uint, size int, fallback bool) (string, error) {\n\turl := fmt.Sprintf(\n\t\t\"%s/avatar?user_id=%d\",\n\t\tc.apiURL,\n\t\tuserID,\n\t)\n\n\tif size > 0 {\n\t\tif !c.validSize(size) {\n\t\t\treturn \"\", fmt.Errorf(\"Invalid size: %d\", size)\n\t\t}\n\t\turl = fmt.Sprintf(\n\t\t\t\"%s&size=%d\",\n\t\t\turl,\n\t\t\tsize,\n\t\t)\n\t}\n\n\tif !fallback {\n\t\turl = fmt.Sprintf(\n\t\t\t\"%s&fallback=%t\",\n\t\t\turl,\n\t\t\tfallback,\n\t\t)\n\n\t}\n\n\treq, err := c.newGetRequest(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tc.logRequest(req)\n\n\tresp, err := http.DefaultTransport.RoundTrip(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif resp != nil {\n\t\tc.logResponse(resp)\n\t}\n\n\tif fallback {\n\t\tif resp.StatusCode != http.StatusFound {\n\t\t\treturn \"\", fmt.Errorf(\"Unexpected response code %d - expected %d\", resp.StatusCode, http.StatusFound)\n\t\t}\n\t} else {\n\t\tif resp.StatusCode == http.StatusNoContent {\n\t\t\treturn \"\", nil\n\t\t}\n\n\t\tif resp.StatusCode != http.StatusFound {\n\t\t\treturn \"\", fmt.Errorf(\"Unexpected response code %d - expected either %d or %d\", resp.StatusCode, http.StatusNoContent, http.StatusFound)\n\t\t}\n\t}\n\n\tlocation, err := resp.Location()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn location.String(), nil\n}\n\n\n\nfunc (c oauthClient) validSize(size int) bool ", "output": "{\n\tvalidSizes := []int{25, 28, 30, 32, 50, 54, 56, 60, 64, 108, 128, 135, 256, 270, 512}\n\n\tfor _, s := range validSizes {\n\t\tif s == size {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n)\n\n\ntype Address struct {\n\tStreet, City string\n}\n\ntype Person struct {\n\tFirstName, LastName string\n}\n\ntype T1 string\ntype T2 string\ntype T3 string\n\nvar logger *log.Logger\n\nfunc main() {\n\tmyAddress := Address{\n\t\tStreet: \"Trimveien 6\",\n\t\tCity: \"Oslo\",\n\t}\n\tlog.Println(myAddress)\n\n\tme := Person{\n\t\tFirstName: \"Christian\",\n\t\tLastName: \"Bergum Bergersen\",\n\t}\n\tlog.Println(me)\n\n\tvar foo T1\n\tfoo = \"foo\"\n\tlog.Println(foo)\n\n\tvar bar T3\n\tbar = \"bar\"\n\tlog.Println(bar)\n}\n\n\nfunc (address Address) String() string {\n\treturn fmt.Sprintf(\"%s\", address)\n}\n\n\n\n\n\nfunc (t1 T1) String() string {\n\treturn fmt.Sprint(t1)\n}\n\n\nfunc (t2 T2) String() string {\n\tlog.Print(\"Calling String() for : %v\", t2)\n\treturn fmt.Sprintln(t2)\n}\n\n\nfunc (bar T3) String() string {\n\tvar buf bytes.Buffer\n\tlogger = log.New(&buf, \"logger: \", log.Lshortfile)\n\tlogger.Printf(\"Calling String() for %+v\", bar)\n\treturn fmt.Sprintf(\"Bar\")\n}\n\nfunc (person Person) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%s %s\", person.FirstName, person.LastName)\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"html/template\"\n \"net/http\"\n \"strings\"\n \"log\"\n)\n\n\n\nfunc login(w http.ResponseWriter, r *http.Request) {\n fmt.Println(\"method:\", r.Method)\n\n if r.Method == \"GET\" {\n t, _ := template.ParseFiles(\"login.gtpl\")\n t.Execute(w, nil)\n } else {\n r.ParseForm()\n fmt.Println(\"username:\", r.Form[\"username\"])\n fmt.Println(\"password:\", r.Form[\"password\"])\n }\n}\n\nfunc main() {\n http.HandleFunc(\"/\", sayHelloName)\n http.HandleFunc(\"/login\", login)\n err := http.ListenAndServe(\":9090\", nil)\n if err != nil {\n log.Fatal(\"ListenAndServe:\", err)\n }\n}\n\nfunc sayHelloName(w http.ResponseWriter, r *http.Request) ", "output": "{\n r.ParseForm()\n fmt.Println(\"---------------------------\")\n fmt.Println(\"Form\", r.Form)\n fmt.Println(\"path\", r.URL.Path)\n fmt.Println(\"scheme\", r.URL.Scheme)\n for k, v := range r.Form {\n fmt.Println(k, \"=\", strings.Join(v, \"\"))\n }\n\n fmt.Fprintf(w, \"Hello!!\" + strings.Join(r.Form[\"name\"], \"\"))\n}"} {"input": "package cdsclient\n\nimport (\n\t\"context\"\n\n\t\"github.com/ovh/cds/sdk\"\n)\n\n\n\n\nfunc (c *client) VCSConfiguration() (map[string]sdk.VCSConfiguration, error) ", "output": "{\n\tvar vcsServers map[string]sdk.VCSConfiguration\n\tif _, err := c.GetJSON(context.Background(), \"/config/vcs\", &vcsServers); err != nil {\n\t\treturn nil, err\n\t}\n\treturn vcsServers, nil\n}"} {"input": "package cluster_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/influxdb/influxdb/cluster\"\n\t\"github.com/influxdb/influxdb/services/meta\"\n)\n\nfunc NewNodes() []meta.NodeInfo {\n\tvar nodes []meta.NodeInfo\n\tfor i := 1; i <= 2; i++ {\n\t\tnodes = append(nodes, meta.NodeInfo{\n\t\t\tID: uint64(i),\n\t\t\tHost: fmt.Sprintf(\"localhost:999%d\", i),\n\t\t})\n\t}\n\treturn nodes\n}\n\n\n\nfunc TestBalancerUp(t *testing.T) {\n\tnodes := NewNodes()\n\tb := cluster.NewNodeBalancer(nodes)\n\n\tfirst := b.Next()\n\tif first == nil {\n\t\tt.Errorf(\"expected datanode, got %v\", first)\n\t}\n\n\tsecond := b.Next()\n\tif second == nil {\n\t\tt.Errorf(\"expected datanode, got %v\", second)\n\t}\n\n\tif first.ID == second.ID {\n\t\tt.Errorf(\"expected first != second. got %v = %v\", first.ID, second.ID)\n\t}\n}\n\nfunc TestBalancerEmptyNodes(t *testing.T) ", "output": "{\n\tb := cluster.NewNodeBalancer([]meta.NodeInfo{})\n\tgot := b.Next()\n\tif got != nil {\n\t\tt.Errorf(\"expected nil, got %v\", got)\n\t}\n}"} {"input": "package clock\n\nimport \"time\"\n\n\nvar Work Clock\n\nfunc init() {\n\tWork = New()\n}\n\n\nfunc Now() time.Time {\n\treturn Work.Now()\n}\n\nfunc Since(t time.Time) time.Duration {\n\treturn Work.Now().Sub(t)\n}\n\n\n\nfunc Sleep(d time.Duration) {\n\tWork.Sleep(d)\n}\n\n\n\nfunc After(d time.Duration) <-chan time.Time {\n\treturn Work.After(d)\n}\n\n\n\n\n\n\n\n\n\nfunc Ticker(d time.Duration) *time.Ticker {\n\treturn Work.Ticker(d)\n}\n\n\ntype Clock interface {\n\n\tNow() time.Time\n\n\tSleep(d time.Duration)\n\n\tAfter(d time.Duration) <-chan time.Time\n\n\tTick(d time.Duration) <-chan time.Time\n\n\tTicker(d time.Duration) *time.Ticker\n\n}\n\n\ntype Mock interface {\n\tClock\n\n\n\tSet(t time.Time) Mock\n\n\tAdd(d time.Duration) Mock\n\n\tFreeze() Mock\n\n\tIsFrozen() bool\n\n\tUnfreeze() Mock\n\n\tClose()\n}\n\nfunc Tick(d time.Duration) <-chan time.Time ", "output": "{\n\treturn Work.Tick(d)\n}"} {"input": "package sw\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/sha256\"\n\t\"crypto/x509\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/hyperledger/fabric/bccsp\"\n)\n\n\n\n\n\n\ntype rsaPublicKey struct{ pubKey *rsa.PublicKey }\n\nfunc (k *rsaPublicKey) Symmetric() bool { return false }\nfunc (k *rsaPublicKey) Private() bool { return false }\nfunc (k *rsaPublicKey) PublicKey() (bccsp.Key, error) { return k, nil }\n\n\nfunc (k *rsaPublicKey) Bytes() (raw []byte, err error) {\n\tif k.pubKey == nil {\n\t\treturn nil, errors.New(\"Failed marshalling key. Key is nil.\")\n\t}\n\traw, err = x509.MarshalPKIXPublicKey(k.pubKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed marshalling key [%s]\", err)\n\t}\n\treturn\n}\n\n\n\n\nfunc (k *rsaPublicKey) SKI() []byte ", "output": "{\n\tif k.pubKey == nil {\n\t\treturn nil\n\t}\n\n\traw := x509.MarshalPKCS1PublicKey(k.pubKey)\n\thash := sha256.Sum256(raw)\n\treturn hash[:]\n}"} {"input": "package lib\n\nimport \"sync\"\n\n\n\ntype ConcurrentPrinterMap struct {\n\tbyCUPSName map[string]Printer\n\tbyGCPID map[string]Printer\n\tmutex sync.RWMutex\n}\n\n\nfunc NewConcurrentPrinterMap(printers []Printer) *ConcurrentPrinterMap {\n\tcpm := ConcurrentPrinterMap{}\n\tcpm.Refresh(printers)\n\treturn &cpm\n}\n\n\nfunc (cpm *ConcurrentPrinterMap) Refresh(newPrinters []Printer) {\n\tc := make(map[string]Printer, len(newPrinters))\n\tfor _, printer := range newPrinters {\n\t\tc[printer.Name] = printer\n\t}\n\n\tg := make(map[string]Printer, len(newPrinters))\n\tfor _, printer := range newPrinters {\n\t\tif len(printer.GCPID) > 0 {\n\t\t\tg[printer.GCPID] = printer\n\t\t}\n\t}\n\n\tcpm.mutex.Lock()\n\tdefer cpm.mutex.Unlock()\n\n\tcpm.byCUPSName = c\n\tcpm.byGCPID = g\n}\n\n\n\n\nfunc (cpm *ConcurrentPrinterMap) GetByCUPSName(name string) (Printer, bool) {\n\tcpm.mutex.RLock()\n\tdefer cpm.mutex.RUnlock()\n\n\tif p, exists := cpm.byCUPSName[name]; exists {\n\t\treturn p, true\n\t}\n\treturn Printer{}, false\n}\n\n\n\n\n\n\n\nfunc (cpm *ConcurrentPrinterMap) GetAll() []Printer {\n\tcpm.mutex.RLock()\n\tdefer cpm.mutex.RUnlock()\n\n\tprinters := make([]Printer, len(cpm.byCUPSName))\n\ti := 0\n\tfor _, printer := range cpm.byCUPSName {\n\t\tprinters[i] = printer\n\t\ti++\n\t}\n\n\treturn printers\n}\n\nfunc (cpm *ConcurrentPrinterMap) GetByGCPID(gcpID string) (Printer, bool) ", "output": "{\n\tcpm.mutex.RLock()\n\tdefer cpm.mutex.RUnlock()\n\n\tif p, exists := cpm.byGCPID[gcpID]; exists {\n\t\treturn p, true\n\t}\n\treturn Printer{}, false\n}"} {"input": "package logging\n\n\ntype DefaultFormatter struct {\n}\n\n\nfunc (f *DefaultFormatter) GetPrefix(lvl level) string {\n\treturn \"\"\n}\n\n\n\n\n\nfunc (f *DefaultFormatter) Format(lvl level, v ...interface{}) []interface{} {\n\treturn append([]interface{}{header()}, v...)\n}\n\nfunc (f *DefaultFormatter) GetSuffix(lvl level) string ", "output": "{\n\treturn \"\"\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSAmazonMQBroker_MaintenanceWindow struct {\n\n\tDayOfWeek string `json:\"DayOfWeek,omitempty\"`\n\n\tTimeOfDay string `json:\"TimeOfDay,omitempty\"`\n\n\tTimeZone string `json:\"TimeZone,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) AWSCloudFormationType() string {\n\treturn \"AWS::AmazonMQ::Broker.MaintenanceWindow\"\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\n\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetDependsOn(dependencies []string) ", "output": "{\n\tr._dependsOn = dependencies\n}"} {"input": "package etcd2\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/coreos/etcd/client\"\n\t\"golang.org/x/net/context\"\n)\n\n\ntype Etcd2Connect struct {\n\tetcd2 client.Client\n}\n\n\n\n\n\nfunc (e *Etcd2Connect) Set(data map[string]string) error {\n\tkapi := client.NewKeysAPI(e.etcd2)\n\tfor k, v := range data {\n\t\tif _, err := kapi.Set(context.Background(), k, v, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (e *Etcd2Connect) Make(data map[string]string) error {\n\tkapi := client.NewKeysAPI(e.etcd2)\n\topts := &client.SetOptions{PrevExist: client.PrevNoExist}\n\tfor k, v := range data {\n\t\tif _, err := kapi.Set(context.Background(), k, v, opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (e *Etcd2Connect) Get(data map[string]string) (map[string]string, error) {\n\tkapi := client.NewKeysAPI(e.etcd2)\n\tresult := make(map[string]string)\n\tfor k := range data {\n\t\tresp, err := kapi.Get(context.Background(), k, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult[k] = resp.Node.Value\n\t}\n\treturn result, nil\n}\n\nfunc NewEtcd2Connect(etcd2EndPoint string) (*Etcd2Connect, error) ", "output": "{\n\tc, err := client.New(client.Config{\n\t\tEndpoints: []string{fmt.Sprintf(\"http://%s\", etcd2EndPoint)},\n\t\tTransport: client.DefaultTransport,\n\t\tHeaderTimeoutPerRequest: time.Second,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Etcd2Connect{etcd2: c}, nil\n}"} {"input": "package utils\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/heketi/heketi/tests\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestStatusGroupSuccess(t *testing.T) {\n\n\ts := NewStatusGroup()\n\n\tmax := 100\n\ts.Add(max)\n\n\tfor i := 0; i < max; i++ {\n\t\tgo func(value int) {\n\t\t\tdefer s.Done()\n\t\t\ttime.Sleep(time.Millisecond * 1 * time.Duration(value))\n\t\t}(i)\n\t}\n\n\terr := s.Result()\n\ttests.Assert(t, err == nil)\n\n}\n\nfunc TestStatusGroupFailure(t *testing.T) {\n\ts := NewStatusGroup()\n\n\tfor i := 0; i < 100; i++ {\n\n\t\ts.Add(1)\n\t\tgo func(value int) {\n\t\t\tdefer s.Done()\n\t\t\ttime.Sleep(time.Millisecond * 1 * time.Duration(value))\n\t\t\tif value%10 == 0 {\n\t\t\t\ts.Err(errors.New(fmt.Sprintf(\"Err: %v\", value)))\n\t\t\t}\n\n\t\t}(i)\n\n\t}\n\n\terr := s.Result()\n\n\ttests.Assert(t, err != nil)\n\ttests.Assert(t, err.Error() == \"Err: 90\", err)\n\n}\n\nfunc TestNewStatusGroup(t *testing.T) ", "output": "{\n\ts := NewStatusGroup()\n\ttests.Assert(t, s != nil)\n\ttests.Assert(t, s.results != nil)\n\ttests.Assert(t, len(s.results) == 0)\n\ttests.Assert(t, s.err == nil)\n}"} {"input": "package util\n\nimport (\n\t\"os\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\n\nfunc FsTime(info os.FileInfo) []time.Time ", "output": "{\n\tret := make([]time.Time, 3, 3)\n\tattr := info.Sys().(*syscall.Win32FileAttributeData)\n\tret[0] = time.Unix(0, attr.CreationTime.Nanoseconds())\n\tret[1] = time.Unix(0, attr.LastWriteTime.Nanoseconds())\n\tret[2] = time.Unix(0, attr.LastAccessTime.Nanoseconds())\n\treturn ret\n}"} {"input": "package ansiwriter\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype Modifier func() string\n\n\n\nfunc Bold() string { return escapeANSI(1) }\nfunc Black() string { return escapeANSI(30) }\nfunc Red() string { return escapeANSI(31) }\nfunc Green() string { return escapeANSI(32) }\nfunc Yellow() string { return escapeANSI(33) }\nfunc Blue() string { return escapeANSI(34) }\nfunc Magenta() string { return escapeANSI(35) }\nfunc Cyan() string { return escapeANSI(36) }\nfunc White() string { return escapeANSI(37) }\n\ntype awr struct {\n\tio.Writer\n\tmodifiers []Modifier\n}\n\n\n\n\nfunc New(w io.Writer, mods ...Modifier) io.Writer {\n\treturn awr{w, mods}\n}\n\nfunc (a awr) Write(b []byte) (n int, err error) {\n\tfor _, mod := range a.modifiers {\n\t\ta.Writer.Write([]byte(mod()))\n\t}\n\tn, err = a.Writer.Write(b)\n\t_, _ = a.Writer.Write([]byte(\"\\033[0m\"))\n\treturn\n}\n\nfunc escapeANSI(code int) string ", "output": "{\n\treturn fmt.Sprintf(\"\\033[%dm\", code)\n}"} {"input": "package btcec\n\nimport (\n\tsecp \"github.com/decred/dcrd/dcrec/secp256k1/v4\"\n)\n\n\n\ntype JacobianPoint = secp.JacobianPoint\n\n\n\nfunc MakeJacobianPoint(x, y, z *FieldVal) JacobianPoint {\n\treturn secp.MakeJacobianPoint(x, y, z)\n}\n\n\n\nfunc AddNonConst(p1, p2, result *JacobianPoint) {\n\tsecp.AddNonConst(p1, p2, result)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc DoubleNonConst(p, result *JacobianPoint) {\n\tsecp.DoubleNonConst(p, result)\n}\n\n\n\n\n\n\nfunc ScalarBaseMultNonConst(k *ModNScalar, result *JacobianPoint) {\n\tsecp.ScalarBaseMultNonConst(k, result)\n}\n\n\n\n\n\n\n\nfunc ScalarMultNonConst(k *ModNScalar, point, result *JacobianPoint) {\n\tsecp.ScalarMultNonConst(k, point, result)\n}\n\nfunc DecompressY(x *FieldVal, odd bool, resultY *FieldVal) bool ", "output": "{\n\treturn secp.DecompressY(x, odd, resultY)\n}"} {"input": "package billing\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/billing/mgmt/2017-04-24-preview/billing\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype ManagementClient = original.ManagementClient\ntype InvoicesClient = original.InvoicesClient\ntype DownloadURL = original.DownloadURL\ntype ErrorDetails = original.ErrorDetails\ntype ErrorResponse = original.ErrorResponse\ntype Invoice = original.Invoice\ntype InvoiceProperties = original.InvoiceProperties\ntype InvoicesListResult = original.InvoicesListResult\ntype Operation = original.Operation\ntype OperationDisplay = original.OperationDisplay\ntype OperationListResult = original.OperationListResult\ntype Period = original.Period\ntype PeriodProperties = original.PeriodProperties\ntype PeriodsListResult = original.PeriodsListResult\ntype Resource = original.Resource\ntype OperationsClient = original.OperationsClient\ntype PeriodsClient = original.PeriodsClient\n\n\nfunc NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewPeriodsClient(subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClient(subscriptionID)\n}\nfunc NewPeriodsClientWithBaseURI(baseURI string, subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\nfunc New(subscriptionID string) ManagementClient {\n\treturn original.New(subscriptionID)\n}\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewInvoicesClient(subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClient(subscriptionID)\n}\nfunc NewInvoicesClientWithBaseURI(baseURI string, subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClientWithBaseURI(baseURI, subscriptionID)\n}\n\nfunc NewOperationsClient(subscriptionID string) OperationsClient ", "output": "{\n\treturn original.NewOperationsClient(subscriptionID)\n}"} {"input": "package dosingdecision\n\nimport (\n\t\"time\"\n\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tCarbohydratesOnBoardAmountMaximum = 1000\n\tCarbohydratesOnBoardAmountMinimum = 0\n)\n\ntype CarbohydratesOnBoard struct {\n\tTime *time.Time `json:\"time,omitempty\" bson:\"time,omitempty\"`\n\tAmount *float64 `json:\"amount,omitempty\" bson:\"amount,omitempty\"`\n}\n\nfunc ParseCarbohydratesOnBoard(parser structure.ObjectParser) *CarbohydratesOnBoard {\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewCarbohydratesOnBoard()\n\tparser.Parse(datum)\n\treturn datum\n}\n\nfunc NewCarbohydratesOnBoard() *CarbohydratesOnBoard {\n\treturn &CarbohydratesOnBoard{}\n}\n\n\n\nfunc (c *CarbohydratesOnBoard) Validate(validator structure.Validator) {\n\tvalidator.Float64(\"amount\", c.Amount).Exists().InRange(CarbohydratesOnBoardAmountMinimum, CarbohydratesOnBoardAmountMaximum)\n}\n\nfunc (c *CarbohydratesOnBoard) Parse(parser structure.ObjectParser) ", "output": "{\n\tc.Time = parser.Time(\"time\", time.RFC3339Nano)\n\tc.Amount = parser.Float64(\"amount\")\n}"} {"input": "package cache\n\nimport \"github.com/lomik/go-carbon/points\"\n\n\ntype Query struct {\n\tMetric string\n\tReplyChan chan *Reply\n}\n\n\nfunc NewQuery(metric string) *Query {\n\treturn &Query{\n\t\tMetric: metric,\n\t\tReplyChan: make(chan *Reply, 1),\n\t}\n}\n\n\ntype Reply struct {\n\tPoints *points.Points\n}\n\n\n\n\nfunc NewReply() *Reply ", "output": "{\n\treturn &Reply{}\n}"} {"input": "package routing\n\nimport \"net/http\"\n\n\nfunc Method(method string, handler http.Handler) Matcher {\n\treturn func(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\t\tif req.Method == method {\n\t\t\thandler.ServeHTTP(resp, req)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}\n\n\nfunc GET(handler http.Handler) Matcher {\n\treturn Method(\"GET\", handler)\n}\n\n\nfunc GETFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn GET(http.HandlerFunc(handler))\n}\n\n\n\n\n\nfunc POSTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn POST(http.HandlerFunc(handler))\n}\n\n\nfunc PUT(handler http.Handler) Matcher {\n\treturn Method(\"PUT\", handler)\n}\n\n\nfunc PUTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PUT(http.HandlerFunc(handler))\n}\n\n\nfunc PATCH(handler http.Handler) Matcher {\n\treturn Method(\"PATCH\", handler)\n}\n\n\nfunc PATCHFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PATCH(http.HandlerFunc(handler))\n}\n\n\nfunc DELETE(handler http.Handler) Matcher {\n\treturn Method(\"DELETE\", handler)\n}\n\n\nfunc DELETEFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn DELETE(http.HandlerFunc(handler))\n}\n\n\n\nfunc MethodNotAllowed(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\tresp.WriteHeader(405)\n\treturn true\n}\n\nfunc POST(handler http.Handler) Matcher ", "output": "{\n\treturn Method(\"POST\", handler)\n}"} {"input": "package agent\n\nimport (\n\t\"flag\"\n)\n\n\n\nfunc (this *Agent) BindFlags() ", "output": "{\n\tflag.BoolVar(&this.selfRegister, \"self_register\", true, \"Registers self with the registry.\")\n\tflag.IntVar(&this.ListenPort, \"port\", 25657, \"Listening port for agent\")\n\tflag.StringVar(&this.StatusPubsubTopic, \"status_topic\", \"\", \"Status pubsub topic\")\n\n\tflag.BoolVar(&this.EnableUI, \"enable_ui\", false, \"Enables UI\")\n\tflag.IntVar(&this.DockerUIPort, \"dockerui_port\", 25658, \"Listening port for dockerui\")\n\tflag.StringVar(&this.UiDocRoot, \"ui_docroot\", \"\", \"UI DocRoot\")\n}"} {"input": "package muta\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/leeola/muta/mutil\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype MockStreamer struct {\n\tFiles []string\n\n\tContents []string\n\n\tErrors []error\n}\n\n\n\nfunc (s *MockStreamer) Next(inFi FileInfo, inRc io.ReadCloser) (\n\tfi FileInfo, rc io.ReadCloser, err error) ", "output": "{\n\n\tfi = inFi\n\trc = inRc\n\tif fi != nil {\n\t\treturn\n\t}\n\n\tif len(s.Files) == 0 {\n\t\treturn\n\t}\n\n\tfile := s.Files[0]\n\ts.Files = s.Files[1:]\n\tfi = NewFileInfo(file)\n\n\tif len(s.Contents) > 0 {\n\t\trc = mutil.ByteCloser([]byte(s.Contents[0]))\n\t\ts.Contents = s.Contents[1:]\n\t} else {\n\t\trc = mutil.ByteCloser([]byte(fmt.Sprintf(\"%s content\", file)))\n\t}\n\n\tif len(s.Errors) > 0 {\n\t\terr = s.Errors[0]\n\t\ts.Errors = s.Errors[1:]\n\t}\n\n\treturn\n}"} {"input": "package collaboration\n\nimport \"sync\"\n\nfunc NewMemoryStorage() *memoryStorage {\n\treturn &memoryStorage{\n\t\tusers: make(map[string]*Option),\n\t}\n}\n\n\ntype memoryStorage struct {\n\tusers map[string]*Option\n\tsync.Mutex\n}\n\nfunc (m *memoryStorage) Get(username string) (*Option, error) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\toption, ok := m.users[username]\n\tif !ok {\n\t\treturn nil, ErrUserNotFound\n\t}\n\n\treturn option, nil\n}\n\nfunc (m *memoryStorage) GetAll() (map[string]*Option, error) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\treturn m.users, nil\n}\n\nfunc (m *memoryStorage) Set(username string, value *Option) error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tm.users[username] = value\n\treturn nil\n}\n\n\n\nfunc (m *memoryStorage) Close() error {\n\treturn nil\n}\n\nfunc (m *memoryStorage) Delete(username string) error ", "output": "{\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tdelete(m.users, username)\n\treturn nil\n}"} {"input": "package manager\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"sync\"\n\t\"time\"\n\n\tproto \"github.com/Cloud-Foundations/Dominator/proto/hypervisor\"\n)\n\ntype flusher interface {\n\tFlush() error\n}\n\nfunc (m *Manager) powerOff(stopVMs bool) error {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\tif stopVMs {\n\t\tm.shutdownVMs()\n\t}\n\tfor _, vm := range m.vms {\n\t\tif vm.State != proto.StateStopped {\n\t\t\treturn fmt.Errorf(\"%s is not shut down\", vm.Address.IpAddress)\n\t\t}\n\t}\n\tcmd := exec.Command(\"poweroff\")\n\tif output, err := cmd.CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"%s: %s\", err, string(output))\n\t}\n\treturn nil\n}\n\nfunc (m *Manager) shutdownVMs() {\n\tvar waitGroup sync.WaitGroup\n\tfor _, vm := range m.vms {\n\t\twaitGroup.Add(1)\n\t\tgo func(vm *vmInfoType) {\n\t\t\tdefer waitGroup.Done()\n\t\t\tvm.shutdown()\n\t\t}(vm)\n\t}\n\twaitGroup.Wait()\n\tm.Logger.Println(\"stopping cleanly after shutting down VMs\")\n\tif flusher, ok := m.Logger.(flusher); ok {\n\t\tflusher.Flush()\n\t}\n}\n\nfunc (m *Manager) shutdownVMsAndExit() {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\tm.shutdownVMs()\n\tos.Exit(0)\n}\n\n\n\nfunc (vm *vmInfoType) shutdown() ", "output": "{\n\tvm.mutex.RLock()\n\tswitch vm.State {\n\tcase proto.StateStarting, proto.StateRunning:\n\t\tstoppedNotifier := make(chan struct{}, 1)\n\t\tvm.stoppedNotifier = stoppedNotifier\n\t\tvm.commandChannel <- \"system_powerdown\"\n\t\tvm.mutex.RUnlock()\n\t\ttimer := time.NewTimer(time.Minute)\n\t\tselect {\n\t\tcase <-stoppedNotifier:\n\t\t\tif !timer.Stop() {\n\t\t\t\t<-timer.C\n\t\t\t}\n\t\t\tvm.logger.Println(\"shut down cleanly for system shutdown\")\n\t\tcase <-timer.C:\n\t\t\tvm.logger.Println(\"shutdown timed out: killing VM\")\n\t\t\tvm.commandChannel <- \"quit\"\n\t\t}\n\tdefault:\n\t\tvm.mutex.RUnlock()\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/hpcloud/tail\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\nfunc tailFile(ctx context.Context, cancel context.CancelFunc, fileName string, poll bool, dest *os.File) ", "output": "{\n\tdefer wg.Done()\n\n\t_file, err := os.Open(fileName)\n\tif err != nil {\n\t\tlog.Printf(\"Error opening '%s':%s\\n\", fileName, err)\n\t\tcancel()\n\t}\n\t_file.Close()\n\n\tt, err := tail.TailFile(fileName, tail.Config{\n\t\tFollow: true,\n\t\tReOpen: true,\n\t\tPoll: poll,\n\t\tLogger: tail.DiscardingLogger,\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"unable to tail %s: %s\\n\", fileName, err)\n\t\tcancel()\n\t}\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tt.Stop()\n\t\t\tt.Cleanup()\n\t\t\treturn\n\t\tcase line := <-t.Lines:\n\t\t\tif line != nil {\n\t\t\t\tfmt.Fprintln(dest, line.Text)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package memfs\n\nimport (\n\t\"io\"\n\t\"testing\"\n\n\t\"gopkg.in/src-d/go-billy.v4\"\n\t\"gopkg.in/src-d/go-billy.v4/test\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype MemorySuite struct {\n\ttest.FilesystemSuite\n\tpath string\n}\n\nvar _ = Suite(&MemorySuite{})\n\nfunc (s *MemorySuite) SetUpTest(c *C) {\n\ts.FilesystemSuite = test.NewFilesystemSuite(New())\n}\n\nfunc (s *MemorySuite) TestCapabilities(c *C) {\n\t_, ok := s.FS.(billy.Capable)\n\tc.Assert(ok, Equals, true)\n\n\tcaps := billy.Capabilities(s.FS)\n\tc.Assert(caps, Equals, billy.DefaultCapabilities&^billy.LockCapability)\n}\n\n\n\nfunc (s *MemorySuite) TestNegativeOffsets(c *C) ", "output": "{\n\tf, err := s.FS.Create(\"negative\")\n\tc.Assert(err, IsNil)\n\n\tbuf := make([]byte, 100)\n\t_, err = f.ReadAt(buf, -100)\n\tc.Assert(err, ErrorMatches, \"readat negative: negative offset\")\n\n\t_, err = f.Seek(-100, io.SeekCurrent)\n\tc.Assert(err, IsNil)\n\t_, err = f.Write(buf)\n\tc.Assert(err, ErrorMatches, \"writeat negative: negative offset\")\n}"} {"input": "package govppmux\n\nimport \"time\"\n\n\ntype Config struct {\n\tReconnectResync bool `json:\"resync-after-reconnect\"`\n\n\tReplyTimeout time.Duration `json:\"reply-timeout\"`\n\n\tConnectViaShm bool `json:\"connect-via-shm\"`\n\n\tShmPrefix string `json:\"shm-prefix\"`\n\n\tBinAPISocketPath string `json:\"binapi-socket-path\"`\n\n\tStatsSocketPath string `json:\"stats-socket-path\"`\n\n\tRetryRequestCount int `json:\"retry-request-count\"`\n\n\tRetryRequestTimeout time.Duration `json:\"retry-request-timeout\"`\n\n\tRetryConnectCount int `json:\"retry-connect-count\"`\n\n\tRetryConnectTimeout time.Duration `json:\"retry-connect-timeout\"`\n\n\tProxyEnabled bool `json:\"proxy-enabled\"`\n\n\tHealthCheckProbeInterval time.Duration `json:\"health-check-probe-interval\"`\n\tHealthCheckReplyTimeout time.Duration `json:\"health-check-reply-timeout\"`\n\tHealthCheckThreshold int `json:\"health-check-threshold\"`\n\n\tTraceEnabled bool `json:\"trace-enabled\"`\n}\n\nfunc DefaultConfig() *Config {\n\treturn &Config{\n\t\tReconnectResync: true,\n\t\tHealthCheckProbeInterval: time.Second,\n\t\tHealthCheckReplyTimeout: 250 * time.Millisecond,\n\t\tHealthCheckThreshold: 1,\n\t\tReplyTimeout: time.Second,\n\t\tRetryRequestTimeout: 500 * time.Millisecond,\n\t\tRetryConnectTimeout: time.Second,\n\t\tProxyEnabled: true,\n\t}\n}\n\n\n\nfunc (p *Plugin) loadConfig() (*Config, error) ", "output": "{\n\tcfg := DefaultConfig()\n\tfound, err := p.Cfg.LoadValue(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if found {\n\t\tp.Log.Debugf(\"config loaded from file %q\", p.Cfg.GetConfigName())\n\t} else {\n\t\tp.Log.Debugf(\"config file %q not found, using default config\", p.Cfg.GetConfigName())\n\t}\n\treturn cfg, nil\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetAutonomousPatchRequest struct {\n\n\tAutonomousPatchId *string `mandatory:\"true\" contributesTo:\"path\" name:\"autonomousPatchId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetAutonomousPatchRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request GetAutonomousPatchRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request GetAutonomousPatchRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype GetAutonomousPatchResponse struct {\n\n\tRawResponse *http.Response\n\n\tAutonomousPatch `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetAutonomousPatchResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetAutonomousPatchResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetAutonomousPatchRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package iso20022\n\n\ntype TaxReportHeader1 struct {\n\n\tMessageIdentification *MessageIdentification1 `xml:\"MsgId\"`\n\n\tNumberOfTaxReports *Number `xml:\"NbOfTaxRpts,omitempty\"`\n\n\tTaxAuthority []*TaxOrganisationIdentification1 `xml:\"TaxAuthrty,omitempty\"`\n}\n\nfunc (t *TaxReportHeader1) AddMessageIdentification() *MessageIdentification1 {\n\tt.MessageIdentification = new(MessageIdentification1)\n\treturn t.MessageIdentification\n}\n\nfunc (t *TaxReportHeader1) SetNumberOfTaxReports(value string) {\n\tt.NumberOfTaxReports = (*Number)(&value)\n}\n\n\n\nfunc (t *TaxReportHeader1) AddTaxAuthority() *TaxOrganisationIdentification1 ", "output": "{\n\tnewValue := new(TaxOrganisationIdentification1)\n\tt.TaxAuthority = append(t.TaxAuthority, newValue)\n\treturn newValue\n}"} {"input": "package sml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/sml\"\n)\n\nfunc TestCT_TextFieldConstructor(t *testing.T) {\n\tv := sml.NewCT_TextField()\n\tif v == nil {\n\t\tt.Errorf(\"sml.NewCT_TextField must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed sml.CT_TextField should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestCT_TextFieldMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := sml.NewCT_TextField()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := sml.NewCT_TextField()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package goboard\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TGetBoard(I, C, D, H, R, A int) []Board {\n\tgoboard := GoBoard{TargetBoardList: make([]BoardInterface, 0)}\n\ti, c, d, h, r, a := InvenBoard{}, ClienBoard{}, DcinsideBoard{}, HUnivBoard{}, RuliwebBoard{}, AlrinBoard{}\n\tgoboard.TargetBoardList = append(goboard.TargetBoardList, i)\n\tgoboard.TargetBoardList = append(goboard.TargetBoardList, c)\n\tgoboard.TargetBoardList = append(goboard.TargetBoardList, d)\n\tgoboard.TargetBoardList = append(goboard.TargetBoardList, h)\n\tgoboard.TargetBoardList = append(goboard.TargetBoardList, r)\n\tgoboard.TargetBoardList = append(goboard.TargetBoardList, a)\n\n\tlist := goboard.GetBoardList()\n\tlist = goboard.Filter(list, func(l []Board, t BoardInterface) []Board {\n\t\tswitch t.(type) {\n\t\tcase InvenBoard:\n\t\t\treturn t.Filter(I, -1, l)\n\t\tcase ClienBoard:\n\t\t\treturn t.Filter(C, -1, l)\n\t\tcase HUnivBoard:\n\t\t\treturn h.Filter(H, -1, l)\n\t\tcase RuliwebBoard:\n\t\t\treturn r.Filter(R, -1, l)\n\t\tcase DcinsideBoard:\n\t\t\treturn d.Filter(D, -1, l)\n\t\tcase AlrinBoard:\n\t\t\treturn a.Filter(A, -1, l)\n\t\t}\n\t\treturn nil\n\t})\n\tgoboard.LoadBoards(list)\n\tgoboard.Sort(list, DESC)\n\treturn list\n}\n\nfunc TestBoard(t *testing.T) ", "output": "{\n\tlist := TGetBoard(-1, -1, -1, -1, -1, -1)\n\tfor i, b := range list {\n\t\tt.Log(i, b.RegDate, b)\n\t}\n\n}"} {"input": "package layers\n\nimport (\n\t\"github.com/vtolstov/gopacket\"\n)\n\n\n\ntype BaseLayer struct {\n\tContents []byte\n\tPayload []byte\n}\n\n\nfunc (b *BaseLayer) LayerContents() []byte { return b.Contents }\n\n\nfunc (b *BaseLayer) LayerPayload() []byte { return b.Payload }\n\ntype layerDecodingLayer interface {\n\tgopacket.Layer\n\tDecodeFromBytes([]byte, gopacket.DecodeFeedback) error\n\tNextLayerType() gopacket.LayerType\n}\n\n\n\n\nvar lotsOfZeros [1024]byte\n\nfunc decodingLayerDecoder(d layerDecodingLayer, data []byte, p gopacket.PacketBuilder) error ", "output": "{\n\terr := d.DecodeFromBytes(data, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.AddLayer(d)\n\tnext := d.NextLayerType()\n\tif next == gopacket.LayerTypeZero {\n\t\treturn nil\n\t}\n\treturn p.NextDecoder(next)\n}"} {"input": "package main\n\nimport (\n\t\"code.google.com/p/go.tools/go/gccgoimporter\"\n\t\"code.google.com/p/go.tools/go/types\"\n)\n\nvar (\n\tinitmap = make(map[*types.Package]gccgoimporter.InitData)\n)\n\n\n\n\nfunc (p *printer) printGccgoExtra(pkg *types.Package) {\n\tif initdata, ok := initmap[pkg]; ok {\n\t\tp.printf(\"/*\\npriority %d\\n\", initdata.Priority)\n\n\t\tp.printDecl(\"init\", len(initdata.Inits), func() {\n\t\t\tfor _, init := range initdata.Inits {\n\t\t\t\tp.printf(\"%s %s %d\\n\", init.Name, init.InitFunc, init.Priority)\n\t\t\t}\n\t\t})\n\n\t\tp.print(\"*/\\n\")\n\t}\n}\n\nfunc init() ", "output": "{\n\tincpaths := []string{\"/\"}\n\n\tvar inst gccgoimporter.GccgoInstallation\n\tinst.InitFromDriver(\"gccgo\")\n\tregister(\"gccgo\", inst.GetImporter(incpaths, initmap))\n}"} {"input": "package main\n\nimport (\n\t. \"github.com/conclave/pcduino/core\"\n)\n\nfunc init() {\n\tInit()\n\tsetup()\n}\n\nfunc main() {\n\tfor {\n\t\tloop()\n\t}\n}\n\nvar touchPin byte = 1\nvar ledPin byte = 0\n\n\n\nfunc loop() {\n\tval := DigitalRead(touchPin)\n\tDigitalWrite(ledPin, val)\n}\n\nfunc setup() ", "output": "{\n\tprintln(\"Touch sensor test code!\")\n\tprintln(\"Using I/O_0=Drive LED, I/O_1=Sensor output.\")\n\tPinMode(touchPin, INPUT)\n\tPinMode(ledPin, OUTPUT)\n}"} {"input": "package log\n\n\nfunc (me *Logging) Prefix() string {\n\treturn me.prefix\n}\n\n\nfunc (me *Logging) SetPrefix(value string) {\n\tme.prefix = value\n\tif me.console != nil {\n\t\tme.console.SetPrefix(me.prefix)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPrefix(me.prefix)\n\t}\n}\n\n\n\n\n\nfunc (me *Logging) SetPriority(value int) {\n\tme.setPriority = true\n\tme.priority = value\n\tif me.console != nil {\n\t\tme.console.SetPriority(me.priority)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPriority(me.priority)\n\t}\n}\n\n\nfunc (me *Logging) Layouts() int {\n\treturn me.layouts\n}\n\n\nfunc (me *Logging) SetLayouts(value int) {\n\tme.setLayouts = true\n\tme.layouts = value\n\tif me.console != nil {\n\t\tme.console.SetLayouts(me.layouts)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetLayouts(me.layouts)\n\t}\n}\n\n\nfunc (me *Logging) Outputs() int {\n\treturn me.outputs\n}\n\n\nfunc (me *Logging) SetOutputs(value int) {\n\tme.setOutputs = true\n\tme.outputs = value\n}\n\nfunc (me *Logging) Priority() int ", "output": "{\n\treturn me.priority\n}"} {"input": "package signage\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"golang.org/x/net/html\"\n)\n\n\n\ntype Bill struct {\n\tDate time.Time\n\tTitle string\n\tURL string\n}\n\n\n\n\n\n\n\n\n\nfunc writeNode(w io.Writer, n *html.Node) {\n\tvar inner func(io.Writer, *html.Node, bool)\n\tinner = func(w io.Writer, n *html.Node, top bool) {\n\t\tif n == nil {\n\t\t\treturn\n\t\t}\n\n\t\tswitch n.Type {\n\t\tcase html.TextNode:\n\t\t\tio.WriteString(w, n.Data)\n\n\t\tcase html.ElementNode:\n\t\t\tio.WriteString(w, \"<\")\n\t\t\tio.WriteString(w, n.Data)\n\t\t\tif len(n.Attr) > 0 {\n\t\t\t\tfor _, attr := range n.Attr {\n\t\t\t\t\tio.WriteString(w, \" \")\n\t\t\t\t\tio.WriteString(w, attr.Key)\n\t\t\t\t\tio.WriteString(w, \"='\")\n\t\t\t\t\tio.WriteString(w, html.EscapeString(attr.Val))\n\t\t\t\t\tio.WriteString(w, \"'\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tif n.FirstChild == nil {\n\t\t\t\tio.WriteString(w, \" />\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tio.WriteString(w, \">\")\n\t\t\tinner(w, n.FirstChild, false)\n\t\t\tio.WriteString(w, \"\")\n\t\t}\n\n\t\tif !top {\n\t\t\tinner(w, n.NextSibling, false)\n\t\t}\n\t}\n\n\tinner(w, n, true)\n}\n\nfunc (b Bill) Summary(length int) (string, error) ", "output": "{\n\troot, err := getHTML(b.URL)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfirst := findNode(root, func(n *html.Node) bool {\n\t\treturn (n.Type == html.TextNode) && (strings.HasPrefix(n.Data, \"One Hundred\"))\n\t})\n\tif first == nil {\n\t\treturn \"\", nil\n\t}\n\n\tvar buf bytes.Buffer\n\tfor i, cur := 0, first.Parent.Parent; ((length < 0) || (i < length)) && (cur != nil); i, cur = i+1, cur.NextSibling {\n\t\twriteNode(&buf, cur)\n\t}\n\n\treturn buf.String(), nil\n}"} {"input": "package filter\n\nimport (\n\t\"context\"\n\n\t\"github.com/hyperledger/fabric-protos-go/peer\"\n\t\"github.com/hyperledger/fabric/core/handlers/auth\"\n)\n\n\nfunc NewFilter() auth.Filter {\n\treturn &filter{}\n}\n\ntype filter struct {\n\tnext peer.EndorserServer\n}\n\n\nfunc (f *filter) Init(next peer.EndorserServer) {\n\tf.next = next\n}\n\n\n\n\nfunc (f *filter) ProcessProposal(ctx context.Context, signedProp *peer.SignedProposal) (*peer.ProposalResponse, error) ", "output": "{\n\treturn f.next.ProcessProposal(ctx, signedProp)\n}"} {"input": "package x\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/pkg/errors\"\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/ory/x/logrusx\"\n)\n\ntype errStackTracer struct{}\n\n\n\nfunc (s *errStackTracer) Error() string {\n\treturn \"foo\"\n}\n\nfunc TestLogError(t *testing.T) {\n\tr, err := http.NewRequest(http.MethodGet, \"https://hydra/some/endpoint\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tbuf := bytes.NewBuffer([]byte{})\n\tl := logrusx.New(\"\", \"\", logrusx.ForceLevel(logrus.TraceLevel))\n\tl.Logger.Out = buf\n\tLogError(r, errors.New(\"asdf\"), l)\n\n\tt.Logf(\"%s\", string(buf.Bytes()))\n\n\tassert.True(t, strings.Contains(string(buf.Bytes()), \"trace\"))\n\n\tLogError(r, errors.Wrap(new(errStackTracer), \"\"), l)\n}\n\nfunc TestLogErrorDoesNotPanic(t *testing.T) {\n\tr, err := http.NewRequest(http.MethodGet, \"https://hydra/some/endpoint\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tLogError(r, errors.New(\"asdf\"), nil)\n}\n\nfunc (s *errStackTracer) StackTrace() errors.StackTrace ", "output": "{\n\treturn errors.StackTrace{}\n}"} {"input": "package files\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"mime\"\n\t\"mime/multipart\"\n\t\"net/url\"\n)\n\nconst (\n\tmultipartFormdataType = \"multipart/form-data\"\n\n\tapplicationDirectory = \"application/x-directory\"\n\tapplicationSymlink = \"application/symlink\"\n\tapplicationFile = \"application/octet-stream\"\n\n\tcontentTypeHeader = \"Content-Type\"\n)\n\n\n\ntype MultipartFile struct {\n\tFile\n\n\tPart *multipart.Part\n\tReader *multipart.Reader\n\tMediatype string\n}\n\n\n\nfunc (f *MultipartFile) IsDirectory() bool {\n\treturn f.Mediatype == multipartFormdataType || f.Mediatype == applicationDirectory\n}\n\nfunc (f *MultipartFile) NextFile() (File, error) {\n\tif !f.IsDirectory() {\n\t\treturn nil, ErrNotDirectory\n\t}\n\tif f.Reader != nil {\n\t\tpart, err := f.Reader.NextPart()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn NewFileFromPart(part)\n\t}\n\n\treturn nil, io.EOF\n}\n\nfunc (f *MultipartFile) FileName() string {\n\tif f == nil || f.Part == nil {\n\t\treturn \"\"\n\t}\n\n\tfilename, err := url.QueryUnescape(f.Part.FileName())\n\tif err != nil {\n\t\treturn f.Part.FileName()\n\t}\n\treturn filename\n}\n\nfunc (f *MultipartFile) FullPath() string {\n\treturn f.FileName()\n}\n\nfunc (f *MultipartFile) Read(p []byte) (int, error) {\n\tif f.IsDirectory() {\n\t\treturn 0, ErrNotReader\n\t}\n\treturn f.Part.Read(p)\n}\n\nfunc (f *MultipartFile) Close() error {\n\tif f.IsDirectory() {\n\t\treturn ErrNotReader\n\t}\n\treturn f.Part.Close()\n}\n\nfunc NewFileFromPart(part *multipart.Part) (File, error) ", "output": "{\n\tf := &MultipartFile{\n\t\tPart: part,\n\t}\n\n\tcontentType := part.Header.Get(contentTypeHeader)\n\tswitch contentType {\n\tcase applicationSymlink:\n\t\tout, err := ioutil.ReadAll(part)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &Symlink{\n\t\t\tTarget: string(out),\n\t\t\tname: f.FileName(),\n\t\t}, nil\n\tcase applicationFile:\n\t\treturn &ReaderFile{\n\t\t\treader: part,\n\t\t\tfilename: f.FileName(),\n\t\t\tabspath: part.Header.Get(\"abspath\"),\n\t\t\tfullpath: f.FullPath(),\n\t\t}, nil\n\t}\n\n\tvar err error\n\tf.Mediatype, _, err = mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f, nil\n}"} {"input": "package models\n\nimport (\n\t\"fmt\"\n\n\t\"google.golang.org/protobuf/reflect/protoreflect\"\n\t\"google.golang.org/protobuf/types/known/fieldmaskpb\"\n)\n\n\nfunc ValidateMask(message protoreflect.ProtoMessage, mask *fieldmaskpb.FieldMask) error {\n\tif mask == nil {\n\t\treturn nil\n\t}\n\n\tif len(mask.GetPaths()) == 1 && mask.Paths[0] == \"*\" {\n\t\treturn nil\n\t}\n\n\tunknowns := make([]string, 0)\n\tfor _, field := range mask.GetPaths() {\n\t\tif _, err := fieldmaskpb.New(message, field); err != nil {\n\t\t\tunknowns = append(unknowns, field)\n\t\t}\n\t}\n\n\tif len(unknowns) > 0 {\n\t\treturn fmt.Errorf(\"unrecognized fields %v\", unknowns)\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc ExpandMask(m protoreflect.ProtoMessage, mask *fieldmaskpb.FieldMask) *fieldmaskpb.FieldMask {\n\tif mask == nil || len(mask.GetPaths()) == 0 {\n\t\treturn populatedFields(m)\n\t} else if len(mask.GetPaths()) == 1 && mask.Paths[0] == \"*\" {\n\t\treturn allFields(m)\n\t}\n\n\tmask.Normalize()\n\treturn mask\n}\n\nfunc populatedFields(m protoreflect.ProtoMessage) *fieldmaskpb.FieldMask {\n\tmask, _ := fieldmaskpb.New(m)\n\n\tm.ProtoReflect().Range(func(field protoreflect.FieldDescriptor, _ protoreflect.Value) bool {\n\t\t_ = mask.Append(m, string(field.Name()))\n\t\treturn true \n\t})\n\n\treturn mask\n}\n\n\n\nfunc allFields(m protoreflect.ProtoMessage) *fieldmaskpb.FieldMask ", "output": "{\n\tmask, _ := fieldmaskpb.New(m)\n\n\tfields := m.ProtoReflect().Descriptor().Fields()\n\tfor i := 0; i < fields.Len(); i++ {\n\t\t_ = mask.Append(m, string(fields.Get(i).Name()))\n\t}\n\n\treturn mask\n}"} {"input": "package spotify\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/laicosly/goth\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc provider() *Provider {\n\treturn New(os.Getenv(\"SPOTIFY_KEY\"), os.Getenv(\"SPOTIFY_SECRET\"), \"/foo\", \"user\")\n}\n\nfunc Test_New(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\tp := provider()\n\n\ta.Equal(p.ClientKey, os.Getenv(\"SPOTIFY_KEY\"))\n\ta.Equal(p.Secret, os.Getenv(\"SPOTIFY_SECRET\"))\n\ta.Equal(p.CallbackURL, \"/foo\")\n}\n\n\n\nfunc Test_BeginAuth(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\n\tp := provider()\n\tsession, err := p.BeginAuth(\"test_state\")\n\ts := session.(*Session)\n\ta.NoError(err)\n\ta.Contains(s.AuthURL, \"accounts.spotify.com/authorize\")\n}\n\nfunc Test_SessionFromJSON(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\n\tp := provider()\n\tsession, err := p.UnmarshalSession(`{\"AuthURL\":\"http://accounts.spotify.com/authorize\",\"AccessToken\":\"1234567890\"}`)\n\ta.NoError(err)\n\n\ts := session.(*Session)\n\ta.Equal(s.AuthURL, \"http://accounts.spotify.com/authorize\")\n\ta.Equal(s.AccessToken, \"1234567890\")\n}\n\nfunc Test_ImplementsProvider(t *testing.T) ", "output": "{\n\tt.Parallel()\n\ta := assert.New(t)\n\ta.Implements((*goth.Provider)(nil), provider())\n}"} {"input": "package balanced_brackets\n\nimport \"testing\"\n\nfunc TestStackBalanced(t *testing.T) {\n\n\tgot := Balance(\"{[]}()\")\n\n\twant := true\n\n\tif got != want {\n\n\t\tt.Errorf(\"Should be %v but is %v\", want, got)\n\n\t}\n\n}\n\n\n\nfunc TestOpenStack(t *testing.T) {\n\n\tgot := Balance(\"(\")\n\n\twant := false\n\n\tif got != want {\n\n\t\tt.Errorf(\"Should be %v but is %v\", want, got)\n\n\t}\n}\n\nfunc TestStackUnbalanced(t *testing.T) ", "output": "{\n\n\tgot := Balance(\"{(])}\")\n\n\twant := false\n\n\tif got != want {\n\n\t\tt.Errorf(\"Should be %v but is %v\", want, got)\n\n\t}\n}"} {"input": "package goque\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"encoding/gob\"\n)\n\n\ntype Item struct {\n\tID uint64\n\tKey []byte\n\tValue []byte\n}\n\n\nfunc (i *Item) ToString() string {\n\treturn string(i.Value)\n}\n\n\n\n\n\n\n\nfunc (i *Item) ToObject(value interface{}) error {\n\tbuffer := bytes.NewBuffer(i.Value)\n\tdec := gob.NewDecoder(buffer)\n\treturn dec.Decode(value)\n}\n\n\ntype PriorityItem struct {\n\tID uint64\n\tPriority uint8\n\tKey []byte\n\tValue []byte\n}\n\n\n\n\n\n\n\n\n\n\nfunc (pi *PriorityItem) ToObject(value interface{}) error {\n\tbuffer := bytes.NewBuffer(pi.Value)\n\tdec := gob.NewDecoder(buffer)\n\treturn dec.Decode(value)\n}\n\n\nfunc idToKey(id uint64) []byte {\n\tkey := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(key, id)\n\treturn key\n}\n\n\nfunc keyToID(key []byte) uint64 {\n\treturn binary.BigEndian.Uint64(key)\n}\n\nfunc (pi *PriorityItem) ToString() string ", "output": "{\n\treturn string(pi.Value)\n}"} {"input": "package main\n\nimport \"testing\"\n\nfunc TestValidateURL(t *testing.T) {\n\tif !validateURL(\"https://github.com/chadev/Chadev_ircbot\") {\n\t\tt.Error(\"failed to validate proper URL: https://github.com/chadev/Chadev_ircbot\")\n\t}\n}\n\nfunc TestGetGitHubURL(t *testing.T) {\n\tURL, err := getGitHubURL(\"Chadev_ircbot\")\n\tif err != nil {\n\t\tt.Errorf(\"failed fetching GitHub repo URL: %s\\n\", err.Error())\n\t}\n\n\tt.Logf(\"returned URL: %s\\n\", URL)\n\tif !validateGitHubURL(URL) {\n\t\tt.Error(\"the URL came back as invalid\")\n\t}\n}\n\n\n\nfunc TestGetIssueIDURL(t *testing.T) {\n\tURL, err := getIssueURL(\"Chadev_ircbot\")\n\tif err != nil {\n\t\tt.Errorf(\"failed fetching GitHub Issue URL: %s\\n\", err.Error())\n\t}\n\n\tt.Logf(\"returned URL: %s\\n\", URL)\n\tif !validateGitHubURL(URL) {\n\t\tt.Error(\"the issue queue URL came back as invalid\")\n\t}\n\n\tURL, err = getIssueIDURL(URL, \"#1\")\n\tif err != nil {\n\t\tt.Errorf(\"failed fetching GitHub Issue URL: %s\\n\", err.Error())\n\t}\n\n\tt.Logf(\"returned URL: %s\\n\", URL)\n\tif !validateGitHubURL(URL) {\n\t\tt.Errorf(\"the issue URL came back as invalid\")\n\t}\n}\n\nfunc TestGetIssueURL(t *testing.T) ", "output": "{\n\tURL, err := getIssueURL(\"Chadev_ircbot\")\n\tif err != nil {\n\t\tt.Errorf(\"failed fetching GitHub Issue URL: %s\\n\", err.Error())\n\t}\n\n\tt.Logf(\"returned URL: %s\\n\", URL)\n\tif !validateGitHubURL(URL) {\n\t\tt.Error(\"the URL came back as invalid\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/user\"\n)\n\nfunc main() {\n\tstartServer()\n}\n\nfunc isRoot() bool {\n\tusr, _ := user.Current()\n\treturn usr.Uid == \"0\"\n}\n\nfunc certsExists(certFile string, keyFile string) bool {\n\tfor _, file := range []string{certFile, keyFile} {\n\t\t_, err := os.Stat(file)\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n\n\nfunc startServer() {\n\tcertFile := \"certs/server.pem\"\n\tkeyFile := \"certs/server.key\"\n\tssl := certsExists(certFile, keyFile)\n\tport := findPort(ssl)\n\trouter := NewRouter()\n\n\tlog.Printf(\"start listening on port %s\", port)\n\n\tvar err error\n\tif ssl {\n\t\terr = http.ListenAndServeTLS(\":\"+port, certFile, keyFile, router)\n\t} else {\n\t\terr = http.ListenAndServe(\":\"+port, router)\n\t}\n\n\tlog.Fatal(err)\n}\n\nfunc findPort(ssl bool) string ", "output": "{\n\tport := os.Getenv(\"PORT\")\n\tif len(port) == 0 {\n\t\tuser := !isRoot()\n\t\tif ssl {\n\t\t\tif user {\n\t\t\t\tport = \"4443\"\n\t\t\t} else {\n\t\t\t\tport = \"443\"\n\t\t\t}\n\t\t} else {\n\t\t\tif user {\n\t\t\t\tport = \"8080\"\n\t\t\t} else {\n\t\t\t\tport = \"80\"\n\t\t\t}\n\t\t}\n\t}\n\n\treturn port\n}"} {"input": "package wire\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\n\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) ", "output": "{\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}"} {"input": "package config\n\nimport (\n\t\"encoding/xml\"\n)\n\ntype defXMLReader struct {\n\topts ReaderOptions\n}\n\n\nfunc NewXMLReader(opts ...ReaderOptionFunc) Reader {\n\tr := &defXMLReader{}\n\tfor _, o := range opts {\n\t\to(&r.opts)\n\t}\n\treturn r\n}\n\nfunc (p *defXMLReader) Read(model interface{}) error {\n\tdata, err := ReadXMLFile(p.opts.filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ParseXMLConfig(data, model)\n}\n\nfunc (*defXMLReader) Dump(v interface{}) ([]byte, error) {\n\treturn xml.Marshal(v)\n}\n\n\n\n\nfunc ReadXMLFile(name string) ([]byte, error) {\n\tdata, _, err := filesRepo.Read(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}\n\n\nfunc ParseXMLConfig(data []byte, model interface{}) error {\n\treturn xml.Unmarshal(data, model)\n}\n\nfunc (*defXMLReader) ParseData(data []byte, model interface{}) error ", "output": "{\n\treturn ParseXMLConfig(data, model)\n}"} {"input": "package initializer\n\nimport (\n\t\"k8s.io/apiserver/pkg/admission\"\n\t\"k8s.io/apiserver/pkg/authorization/authorizer\"\n\t\"k8s.io/client-go/informers\"\n\t\"k8s.io/client-go/kubernetes\"\n\t\"k8s.io/component-base/featuregate\"\n)\n\ntype pluginInitializer struct {\n\texternalClient kubernetes.Interface\n\texternalInformers informers.SharedInformerFactory\n\tauthorizer authorizer.Authorizer\n\tfeatureGates featuregate.FeatureGate\n}\n\n\n\n\nfunc New(\n\textClientset kubernetes.Interface,\n\textInformers informers.SharedInformerFactory,\n\tauthz authorizer.Authorizer,\n\tfeatureGates featuregate.FeatureGate,\n) pluginInitializer {\n\treturn pluginInitializer{\n\t\texternalClient: extClientset,\n\t\texternalInformers: extInformers,\n\t\tauthorizer: authz,\n\t\tfeatureGates: featureGates,\n\t}\n}\n\n\n\n\n\nvar _ admission.PluginInitializer = pluginInitializer{}\n\nfunc (i pluginInitializer) Initialize(plugin admission.Interface) ", "output": "{\n\tif wants, ok := plugin.(WantsFeatures); ok {\n\t\twants.InspectFeatureGates(i.featureGates)\n\t}\n\n\tif wants, ok := plugin.(WantsExternalKubeClientSet); ok {\n\t\twants.SetExternalKubeClientSet(i.externalClient)\n\t}\n\n\tif wants, ok := plugin.(WantsExternalKubeInformerFactory); ok {\n\t\twants.SetExternalKubeInformerFactory(i.externalInformers)\n\t}\n\n\tif wants, ok := plugin.(WantsAuthorizer); ok {\n\t\twants.SetAuthorizer(i.authorizer)\n\t}\n}"} {"input": "package instana\n\nimport (\n\t\"time\"\n)\n\n\ntype EventData struct {\n\tTitle string `json:\"title\"`\n\tText string `json:\"text\"`\n\tDuration int `json:\"duration\"`\n\tSeverity int `json:\"severity\"`\n\tPlugin string `json:\"plugin,omitempty\"`\n\tID string `json:\"id,omitempty\"`\n\tHost string `json:\"host\"`\n}\n\ntype severity int\n\n\nconst (\n\tSeverityChange severity = -1\n\tSeverityWarning severity = 5\n\tSeverityCritical severity = 10\n)\n\n\nconst (\n\tServicePlugin = \"com.instana.forge.connection.http.logical.LogicalWebApp\"\n\tServiceHost = \"\"\n)\n\n\n\n\n\nfunc SendServiceEvent(service string, title string, text string, sev severity, duration time.Duration) {\n\tsendEvent(&EventData{\n\t\tTitle: title,\n\t\tText: text,\n\t\tSeverity: int(sev),\n\t\tPlugin: ServicePlugin,\n\t\tID: service,\n\t\tHost: ServiceHost,\n\t\tDuration: int(duration / time.Millisecond),\n\t})\n}\n\n\nfunc SendHostEvent(title string, text string, sev severity, duration time.Duration) {\n\tsendEvent(&EventData{\n\t\tTitle: title,\n\t\tText: text,\n\t\tDuration: int(duration / time.Millisecond),\n\t\tSeverity: int(sev),\n\t})\n}\n\nfunc sendEvent(event *EventData) {\n\tif sensor == nil {\n\t\tInitSensor(&Options{})\n\t}\n\tgo sensor.agent.request(sensor.agent.makeURL(agentEventURL), \"POST\", event)\n}\n\nfunc SendDefaultServiceEvent(title string, text string, sev severity, duration time.Duration) ", "output": "{\n\tif sensor == nil {\n\t\tSendServiceEvent(\"\", title, text, sev, duration)\n\t} else {\n\t\tSendServiceEvent(sensor.serviceName, title, text, sev, duration)\n\t}\n}"} {"input": "package bolt\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestPaperRepository(t *testing.T) {\n\tdriver, tearDown := setUp(t)\n\tdefer tearDown()\n\n\trepo := NewPaperRepository(driver)\n\n\tid, err := repo.Get(1, \"source 1\", \"ref 1\")\n\trequire.NoError(t, err, \"get non inserted u1 s1 r1\")\n\tassert.Equal(t, 0, id, \"get non inserted u1 s1 r1 - id\")\n\n\terr = repo.Save(1, 10, \"source 1\", \"ref 1\")\n\trequire.NoError(t, err, \"insert u1 p10 s1 r1\")\n\n\tid, err = repo.Get(1, \"source 1\", \"ref 1\")\n\trequire.NoError(t, err, \"get u1 s1 r1\")\n\tassert.Equal(t, 10, id, \"get u1 s1 r1 - id\")\n}\n\nfunc setUp(t *testing.T) (*Driver, func()) ", "output": "{\n\ttmpFile, err := ioutil.TempFile(\"\", \"\")\n\trequire.NoError(t, err, \"tmp file\")\n\n\tfilename := tmpFile.Name()\n\tdriver := &Driver{}\n\terr = driver.Open(filename)\n\trequire.NoError(t, err, \"open driver\")\n\n\treturn driver, func() {\n\t\tdriver.Close()\n\t\tos.Remove(filename)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/bitly/go-nsq\"\n\t\"log\"\n\t\"time\"\n)\n\nvar (\n\tPublisher *MsgPublisher\n)\n\ntype MsgPublisher struct {\n\tusr User\n\twriter *nsq.Writer\n}\n\nfunc init() {\n\tPublisher = &MsgPublisher{\n\t\twriter: nsq.NewWriter(\"106.186.31.48:4150\"),\n\t}\n}\n\nfunc (publisher *MsgPublisher) SetLoginUsr(_usr User) error {\n\tif Publisher == nil {\n\t\tPublisher = &MsgPublisher{\n\t\t\twriter: nsq.NewWriter(\"106.186.31.48:4150\"),\n\t\t}\n\t}\n\tPublisher.usr = _usr\n\tPublisher.usr.Pwd = \"xxxx\"\n\treturn nil\n}\n\nfunc (mp *MsgPublisher) Write(topic, msg string) (int32, []byte, error) {\n\tm := Message{\n\t\tTopic: topic,\n\t\tType: MSG_TYPE_CHAT,\n\t\tTime: time.Now().Format(\"2006-01-02 15:04:05\"),\n\t\tBody: MessageBody{\n\t\t\tFrom: mp.usr,\n\t\t\tMsg: msg,\n\t\t},\n\t}\n\tmsgBytes, _ := json.Marshal(m)\n\tlog.Println(\"Publish.msg = \", string(msgBytes))\n\treturn mp.writer.Publish(topic, msgBytes)\n}\n\n\n\nfunc (mp *MsgPublisher) Stop() {\n\tmp.writer.Stop()\n}\n\nfunc (mp *MsgPublisher) WriteAsync(topic, msg string, responseChan chan *nsq.WriterTransaction) error ", "output": "{\n\tm := Message{\n\t\tTopic: topic,\n\t\tType: MSG_TYPE_CHAT,\n\t\tBody: MessageBody{\n\t\t\tFrom: mp.usr,\n\t\t\tMsg: msg,\n\t\t},\n\t}\n\tmsgBytes, _ := json.Marshal(m)\n\tlog.Println(\"PublishAsync.msg = \", string(msgBytes))\n\treturn mp.writer.PublishAsync(topic, msgBytes, responseChan, \"\")\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"layeh.com/gumble/gumble\"\n\t\"time\"\n)\n\nvar connect = &Command{\n\tRun: Lastconnect,\n\tPublicResponse: false,\n\tUsageLine: \"connect [delete]\",\n\tShort: \"Shows last connect info pasted into mumble\",\n\tLong: `\nShows last connect info last pasted into mumbble, you can allso\nuse the \"delete\" arg to remove this from memory.\n\nnote: This will replace the connect string with your user ID!\n`,\n}\n\ntype SourceConnect struct {\n\thostname string\n\tpassword string\n\tUserID uint32\n}\n\n\n\nfunc (c SourceConnect) HTMLSteamConnect() string {\n\ttimeStamp := time.Now().UTC().Format(time.RFC850)\n\tbutton := fmt.Sprintf(\"
Here is the last connect posted:
[%s]
%s
CLICK TO CONNECT TO SERVER\",\n\t\ttimeStamp, c.ConnectString(), c.hostname, c.password)\n\tlog.Debug(button)\n\treturn button\n}\n\nfunc (c SourceConnect) ConnectString() string {\n\treturn fmt.Sprintf(\"connect %s; password %s\", c.hostname, c.password)\n}\n\nvar currentConnect = new(SourceConnect)\nvar currentConnectHTML = \"There is not yet a connect!\"\nvar currentConnectString = \"There is not yet a connect!\"\n\nfunc (c SourceConnect) GenConnectString() (string, string) {\n\treturn c.HTMLSteamConnect(), c.ConnectString()\n}\n\n\n\nfunc Lastconnect(cmd *Command, args []string, event *gumble.TextMessageEvent) string ", "output": "{\n\tsender := event.Sender\n\tif args[2] != \"\" {\n\t\tswitch args[2] {\n\t\tcase \"delete\":\n\t\t\tvar delMsg = fmt.Sprintf(\"The last connect was deleted by '%s' ID: %d at %s\",\n\t\t\t\tsender.Name, sender.UserID, time.Now().UTC().Format(time.RFC850))\n\n\t\t\tcurrentConnectHTML = delMsg\n\t\t\tcurrentConnectString = delMsg\n\t\t\tcurrentConnect = new(SourceConnect)\n\t\tcase \"raw\":\n\t\t\treturn currentConnectString\n\t\tdefault:\n\t\t\treturn CommandNotFound(args[0])\n\t\t}\n\t}\n\treturn currentConnectHTML\n}"} {"input": "package persist\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n)\n\n\ntype Database struct {\n\tuser string\n\tpassword string\n\tdatabase string\n\thost string\n}\n\n\nfunc NewDatabase(username string, password string, database string, host string) Database {\n\treturn Database{username, password, database, host}\n}\n\n\nfunc (db Database) TestConnection() error {\n\tcon, err := db.getConnection()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer con.Close()\n\n\terr = con.Ping()\n\treturn err\n}\n\n\n\n\nfunc (db Database) GetConnectionString() string {\n\treturn fmt.Sprintf(\"Data Source=%s;Database=%s;User ID=%s;Password=%s;Old Guids=true;\", db.host, db.database, db.user, db.password)\n}\n\nfunc (db Database) getConnection() (*sql.DB, error) ", "output": "{\n\tcon, err := sql.Open(\"mysql\", fmt.Sprintf(\"%v:%v@tcp(%v:3306)/%v?parseTime=true\", db.user, db.password, db.host, db.database))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn con, nil\n}"} {"input": "package ibmmq\n\n\n\n\nimport \"C\"\n\n\ntype MQCBD struct {\n\tCallbackType int32\n\tOptions int32\n\tCallbackArea interface{}\n\tCallbackFunction MQCB_FUNCTION\n\tCallbackName string\n\tMaxMsgLength int32\n}\n\n\nfunc NewMQCBD() *MQCBD {\n\tcbd := new(MQCBD)\n\tcbd.CallbackType = C.MQCBT_MESSAGE_CONSUMER\n\tcbd.Options = C.MQCBDO_NONE\n\tcbd.CallbackArea = nil\n\tcbd.CallbackFunction = nil\n\tcbd.CallbackName = \"\"\n\tcbd.MaxMsgLength = C.MQCBD_FULL_MSG_LENGTH\n\n\treturn cbd\n}\n\nfunc copyCBDtoC(mqcbd *C.MQCBD, gocbd *MQCBD) {\n\n\tsetMQIString((*C.char)(&mqcbd.StrucId[0]), \"CBD \", 4)\n\tmqcbd.Version = C.MQCBD_VERSION_1\n\n\tmqcbd.CallbackType = C.MQLONG(gocbd.CallbackType)\n\tmqcbd.Options = C.MQLONG(gocbd.Options) | C.MQCBDO_FAIL_IF_QUIESCING\n\tmqcbd.CallbackArea = (C.MQPTR)(C.NULL)\n\n\tsetMQIString((*C.char)(&mqcbd.CallbackName[0]), gocbd.CallbackName, 128) \n\n\tmqcbd.MaxMsgLength = C.MQLONG(gocbd.MaxMsgLength)\n\n\treturn\n}\n\n\n\nfunc copyCBDfromC(mqcbd *C.MQCBD, gocbd *MQCBD) ", "output": "{\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"../contrail\"\n\tlog \"../logging\"\n\t\"github.com/containernetworking/cni/pkg/skel\"\n\t\"github.com/containernetworking/cni/pkg/version\"\n)\n\n\n\n\n\nfunc CmdAdd(skelArgs *skel.CmdArgs) error {\n\tcni, err := contrailCni.Init(skelArgs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\"Came in Add for container %s\", skelArgs.ContainerID)\n\tcontainerUuid, containerName, err := getPodInfo(skelArgs)\n\tif err != nil {\n\t\tlog.Errorf(\"Error getting UUID/Name for Container\")\n\t\treturn err\n\t}\n\n\tcni.Update(containerName, containerUuid, \"\")\n\tcni.Log()\n\n\terr = cni.CmdAdd()\n\tif err != nil {\n\t\tlog.Errorf(\"Failed processing Add command.\")\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc CmdDel(skelArgs *skel.CmdArgs) error {\n\tcni, err := contrailCni.Init(skelArgs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\"Came in Del for container %s\", skelArgs.ContainerID)\n\tcontainerUuid, containerName, err := getPodInfo(skelArgs)\n\tif err != nil {\n\t\tlog.Errorf(\"Error getting UUID/Name for Container\")\n\t\treturn err\n\t}\n\n\tcni.Update(containerName, containerUuid, \"\")\n\tcni.Log()\n\n\terr = cni.CmdDel()\n\tif err != nil {\n\t\tlog.Errorf(\"Failed processing Add command.\")\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\tskel.PluginMain(CmdAdd, CmdDel,\n\t\tversion.PluginSupports(contrailCni.CniVersion))\n}\n\nfunc getPodInfo(skelArgs *skel.CmdArgs) (string, string, error) ", "output": "{\n\treturn skelArgs.ContainerID, skelArgs.ContainerID, nil\n}"} {"input": "package remote\n\nimport (\n\t\"github.com/AsynkronIT/protoactor-go/actor\"\n)\n\ntype process struct {\n\tpid *actor.PID\n\tremote *Remote\n}\n\nfunc newProcess(pid *actor.PID, r *Remote) actor.Process {\n\treturn &process{\n\t\tpid: pid,\n\t\tremote: r,\n\t}\n}\n\n\n\nfunc (ref *process) SendSystemMessage(pid *actor.PID, message interface{}) {\n\n\tswitch msg := message.(type) {\n\tcase *actor.Watch:\n\t\trw := &remoteWatch{\n\t\t\tWatcher: msg.Watcher,\n\t\t\tWatchee: pid,\n\t\t}\n\t\tref.remote.edpManager.remoteWatch(rw)\n\tcase *actor.Unwatch:\n\t\truw := &remoteUnwatch{\n\t\t\tWatcher: msg.Watcher,\n\t\t\tWatchee: pid,\n\t\t}\n\t\tref.remote.edpManager.remoteUnwatch(ruw)\n\tdefault:\n\t\tref.remote.SendMessage(pid, nil, message, nil, -1)\n\t}\n}\n\nfunc (ref *process) Stop(pid *actor.PID) {\n\tref.SendSystemMessage(pid, stopMessage)\n}\n\nfunc (ref *process) SendUserMessage(pid *actor.PID, message interface{}) ", "output": "{\n\theader, msg, sender := actor.UnwrapEnvelope(message)\n\tref.remote.SendMessage(pid, header, msg, sender, -1)\n}"} {"input": "package structs\n\nimport (\n\t\"strings\"\n)\n\ntype S struct{}\n\nfunc (S) Init() {}\n\n\nfunc FuncTest(item S) {}\n\nfunc (this S) MethodTest(item S1) {}\n\ntype S1 struct {\n\tprivate int\n}\n\ntype S2 struct {\n\tPublic int\n\tprivate int\n}\n\ntype Dim int\n\ntype S3 struct {\n\tX Dim\n\tY Dim\n}\n\nfunc (S) Upper(s string) string ", "output": "{\n\treturn strings.ToUpper(s)\n}"} {"input": "package termios\n\nimport (\n\t\"fmt\"\n\t\"syscall\"\n\t\"unsafe\"\n)\n\nfunc ptsname(fd uintptr) (string, error) {\n\tvar n uintptr\n\terr := ioctl(fd, syscall.TIOCGPTN, uintptr(unsafe.Pointer(&n)))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"/dev/pts/%d\", n), nil\n}\n\n\n\nfunc unlockpt(fd uintptr) error {\n\tvar n uintptr\n\treturn ioctl(fd, syscall.TIOCSPTLCK, uintptr(unsafe.Pointer(&n)))\n}\n\nfunc grantpt(fd uintptr) error ", "output": "{\n\tvar n uintptr\n\treturn ioctl(fd, syscall.TIOCGPTN, uintptr(unsafe.Pointer(&n)))\n}"} {"input": "package admission\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\n\t\"github.com/golang/glog\"\n\tclient \"k8s.io/kubernetes/pkg/client/unversioned\"\n)\n\n\n\n\n\ntype Factory func(client client.Interface, config io.Reader) (Interface, error)\n\n\nvar (\n\tpluginsMutex sync.Mutex\n\tplugins = make(map[string]Factory)\n)\n\n\nfunc GetPlugins() []string {\n\tpluginsMutex.Lock()\n\tdefer pluginsMutex.Unlock()\n\tkeys := []string{}\n\tfor k := range plugins {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}\n\n\n\nfunc RegisterPlugin(name string, plugin Factory) {\n\tpluginsMutex.Lock()\n\tdefer pluginsMutex.Unlock()\n\t_, found := plugins[name]\n\tif found {\n\t\tglog.Fatalf(\"Admission plugin %q was registered twice\", name)\n\t}\n\tglog.V(1).Infof(\"Registered admission plugin %q\", name)\n\tplugins[name] = plugin\n}\n\n\n\n\n\n\nfunc GetPlugin(name string, client client.Interface, config io.Reader) (Interface, error) {\n\tpluginsMutex.Lock()\n\tdefer pluginsMutex.Unlock()\n\tf, found := plugins[name]\n\tif !found {\n\t\treturn nil, nil\n\t}\n\treturn f(client, config)\n}\n\n\n\n\nfunc InitPlugin(name string, client client.Interface, configFilePath string) Interface ", "output": "{\n\tvar (\n\t\tconfig *os.File\n\t\terr error\n\t)\n\n\tif name == \"\" {\n\t\tglog.Info(\"No admission plugin specified.\")\n\t\treturn nil\n\t}\n\n\tif configFilePath != \"\" {\n\t\tconfig, err = os.Open(configFilePath)\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"Couldn't open admission plugin configuration %s: %#v\",\n\t\t\t\tconfigFilePath, err)\n\t\t}\n\n\t\tdefer config.Close()\n\t}\n\n\tplugin, err := GetPlugin(name, client, config)\n\tif err != nil {\n\t\tglog.Fatalf(\"Couldn't init admission plugin %q: %v\", name, err)\n\t}\n\tif plugin == nil {\n\t\tglog.Fatalf(\"Unknown admission plugin: %s\", name)\n\t}\n\n\treturn plugin\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"launchpad.net/gnuflag\"\n\n\t\"launchpad.net/juju-core/cmd\"\n\t\"launchpad.net/juju-core/environs\"\n)\n\n\ntype DestroyEnvironmentCommand struct {\n\tcmd.EnvCommandBase\n\tassumeYes bool\n}\n\nfunc (c *DestroyEnvironmentCommand) Info() *cmd.Info {\n\treturn &cmd.Info{\n\t\tName: \"destroy-environment\",\n\t\tPurpose: \"terminate all machines and other associated resources for an environment\",\n\t}\n}\n\nfunc (c *DestroyEnvironmentCommand) SetFlags(f *gnuflag.FlagSet) {\n\tc.EnvCommandBase.SetFlags(f)\n\tf.BoolVar(&c.assumeYes, \"y\", false, \"Do not ask for confirmation\")\n\tf.BoolVar(&c.assumeYes, \"yes\", false, \"\")\n}\n\n\n\nconst destroyEnvMsg = `\nWARNING: this command will destroy the %q environment (type: %s)\nThis includes all machines, services, data and other resources.\n\nContinue [y/N]? `\n\nfunc (c *DestroyEnvironmentCommand) Run(ctx *cmd.Context) error ", "output": "{\n\tenviron, err := environs.NewFromName(c.EnvName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !c.assumeYes {\n\t\tvar answer string\n\t\tfmt.Fprintf(ctx.Stdout, destroyEnvMsg[1:], environ.Name(), environ.Config().Type())\n\t\tfmt.Fscanln(ctx.Stdin, &answer) \n\t\tanswer = strings.ToLower(answer)\n\t\tif answer != \"y\" && answer != \"yes\" {\n\t\t\treturn errors.New(\"Environment destruction aborted\")\n\t\t}\n\t}\n\n\treturn environ.Destroy(nil)\n}"} {"input": "package command\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/mitchellh/cli\"\n)\n\nfunc TestNewCommand_implement(t *testing.T) {\n\tvar _ cli.Command = &NewCommand{}\n}\n\n\n\nfunc TestNewCommand_directoryExist(t *testing.T) {\n\tui := new(cli.MockUi)\n\tc := &NewCommand{\n\t\tMeta: Meta{\n\t\t\tUI: ui,\n\t\t},\n\t}\n\n\ttmpDir, err := ioutil.TempDir(\"\", \"new-command\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbackFunc, err := TmpChdir(tmpDir)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer backFunc()\n\n\tif err := os.Mkdir(\"todo\", 0777); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\targs := []string{\"todo\"}\n\tif code := c.Run(args); code != 1 {\n\t\tt.Fatalf(\"bad status code: %d\", code)\n\t}\n\n\toutput := ui.ErrorWriter.String()\n\texpect := \"Cannot create directory todo: file exists\"\n\tif !strings.Contains(output, expect) {\n\t\tt.Errorf(\"expect %q to contain %q\", output, expect)\n\t}\n}\n\nfunc TestNewCommand(t *testing.T) ", "output": "{\n\tui := new(cli.MockUi)\n\tc := &NewCommand{\n\t\tMeta: Meta{\n\t\t\tUI: ui,\n\t\t},\n\t}\n\n\ttmpDir, err := ioutil.TempDir(\"\", \"new-command\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbackFunc, err := TmpChdir(tmpDir)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer backFunc()\n\n\targs := []string{\"-F\", \"mitchellh_cli\", \"-owner\", \"deeeet\", \"todo\"}\n\tif code := c.Run(args); code != 0 {\n\t\tt.Fatalf(\"bad status code: %d\\n\\n%s\", code, ui.ErrorWriter.String())\n\t}\n\n}"} {"input": "package v1alpha1\n\nimport (\n\tcorev1 \"k8s.io/api/core/v1\"\n)\n\n\n\ntype ListBuilder struct {\n\tlist *PodList\n\tfilters predicateList\n}\n\n\nfunc NewListBuilder() *ListBuilder {\n\treturn &ListBuilder{list: &PodList{items: []*Pod{}}}\n}\n\n\nfunc ListBuilderForAPIList(pods *corev1.PodList) *ListBuilder {\n\tb := &ListBuilder{list: &PodList{}}\n\tif pods == nil {\n\t\treturn b\n\t}\n\tfor _, p := range pods.Items {\n\t\tp := p\n\t\tb.list.items = append(b.list.items, &Pod{object: &p})\n\t}\n\treturn b\n}\n\n\nfunc ListBuilderForObjectList(pods ...*Pod) *ListBuilder {\n\tb := &ListBuilder{list: &PodList{}}\n\tif pods == nil {\n\t\treturn b\n\t}\n\tfor _, p := range pods {\n\t\tp := p\n\t\tb.list.items = append(b.list.items, p)\n\t}\n\treturn b\n}\n\n\n\n\nfunc (b *ListBuilder) List() *PodList {\n\tif b.filters == nil || len(b.filters) == 0 {\n\t\treturn b.list\n\t}\n\tfiltered := &PodList{}\n\tfor _, pod := range b.list.items {\n\t\tif b.filters.all(pod) {\n\t\t\tfiltered.items = append(filtered.items, pod)\n\t\t}\n\t}\n\treturn filtered\n}\n\n\n\n\n\nfunc (b *ListBuilder) WithFilter(pred ...Predicate) *ListBuilder ", "output": "{\n\tb.filters = append(b.filters, pred...)\n\treturn b\n}"} {"input": "package debugtools\n\nimport (\n\t\"github.com/oakmound/oak/v3/render\"\n\t\"golang.org/x/sync/syncmap\"\n)\n\nvar (\n\tdebugMap syncmap.Map\n)\n\n\n\n\n\n\n\nfunc GetDebugRenderable(rName string) (render.Renderable, bool) {\n\tr, ok := debugMap.Load(rName)\n\tif r == nil {\n\t\treturn nil, false\n\t}\n\treturn r.(render.Renderable), ok\n}\n\n\n\nfunc EnumerateDebugRenderableKeys() []string {\n\tkeys := []string{}\n\tdebugMap.Range(func(k, v interface{}) bool {\n\t\tkey, ok := k.(string)\n\t\tif ok {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t\treturn true\n\t})\n\treturn keys\n}\n\nfunc SetDebugRenderable(rName string, r render.Renderable) ", "output": "{\n\tdebugMap.Store(rName, r)\n}"} {"input": "package evoli\n\nimport \"math/rand\"\n\ntype crosserMock struct {\n}\n\n\n\ntype evaluaterMock struct {\n}\n\nfunc (e evaluaterMock) Evaluate(individual Individual) (Fitness float64, err error) {\n\treturn individual.Fitness(), nil\n}\n\ntype mutaterMock struct {\n}\n\nfunc (m mutaterMock) Mutate(individual Individual, p float64) (Individual, error) {\n\treturn individual, nil\n}\n\ntype positionerMock struct {\n}\n\nfunc (p positionerMock) Position(indiv, pBest, gBest Individual, c1, c2 float64) (Individual, error) {\n\treturn NewIndividual((indiv.Fitness() + pBest.Fitness() + gBest.Fitness()) / 3), nil\n}\n\nfunc (c crosserMock) Cross(parent1, parent2 Individual) (child1, child2 Individual, err error) ", "output": "{\n\tw := 0.1 + 0.8*rand.Float64()\n\treturn NewIndividual(w*parent1.Fitness() + (1-w)*parent2.Fitness()),\n\t\tNewIndividual((1-w)*parent1.Fitness() + w*parent2.Fitness()),\n\t\tnil\n}"} {"input": "package v1\n\n\n\ntype EnvVarApplyConfiguration struct {\n\tName *string `json:\"name,omitempty\"`\n\tValue *string `json:\"value,omitempty\"`\n\tValueFrom *EnvVarSourceApplyConfiguration `json:\"valueFrom,omitempty\"`\n}\n\n\n\n\n\n\n\n\nfunc (b *EnvVarApplyConfiguration) WithName(value string) *EnvVarApplyConfiguration {\n\tb.Name = &value\n\treturn b\n}\n\n\n\n\nfunc (b *EnvVarApplyConfiguration) WithValue(value string) *EnvVarApplyConfiguration {\n\tb.Value = &value\n\treturn b\n}\n\n\n\n\nfunc (b *EnvVarApplyConfiguration) WithValueFrom(value *EnvVarSourceApplyConfiguration) *EnvVarApplyConfiguration {\n\tb.ValueFrom = value\n\treturn b\n}\n\nfunc EnvVar() *EnvVarApplyConfiguration ", "output": "{\n\treturn &EnvVarApplyConfiguration{}\n}"} {"input": "package docker\n\nimport (\n\t\"github.com/kelseyhightower/envconfig\"\n\t\"github.com/davidhiendl/telegraf-docker-sd/app/config\"\n\t\"github.com/sirupsen/logrus\"\n)\n\ntype DockerConfigSpec struct {\n\tAutoConfPrefix string `envconfig:\"AUTO_CONF_PREFIX\",default:\"docker_\"`\n\tTagsFromSwarm bool `envconfig:\"TAGS_FROM_SWARM\",default:\"true\"`\n\n\tTagLabelsWhitelistStr string `envconfig:\"TAG_LABELS_WHITELIST\"`\n\tTagLabelsBlacklistStr string `envconfig:\"TAG_LABELS_BLACKLIST\"`\n\n\tTagLabelsWhitelist []string `ignored:\"true\"`\n\tTagLabelsBlacklist []string `ignored:\"true\"`\n}\n\n\n\nfunc LoadConfig() *DockerConfigSpec ", "output": "{\n\tcfg := &DockerConfigSpec{}\n\terr := envconfig.Process(\"TSD_DOCKER\", cfg)\n\n\tif err != nil {\n\t\tlogrus.Fatalf(\"failed to parse config: %v\", err)\n\t}\n\n\tcfg.TagLabelsWhitelist = config.ConfigListToArray(cfg.TagLabelsWhitelistStr)\n\tcfg.TagLabelsBlacklist = config.ConfigListToArray(cfg.TagLabelsBlacklistStr)\n\n\tif len(cfg.TagLabelsWhitelist) > 0 && len(cfg.TagLabelsBlacklist) > 0 {\n\t\tlogrus.Fatalf(LOG_PREFIX+\" cannot have label whitelist and blacklist\", err)\n\t}\n\n\treturn cfg\n}"} {"input": "package drum\n\nimport \"fmt\"\n\n\n\ntype Pattern struct {\n\tversion Version\n\ttempo Tempo\n\ttracks Tracks\n}\n\nfunc (p Pattern) String() string {\n\treturn fmt.Sprintf(\"%s\\n%s\\n%s\", p.version.String(), p.tempo.String(), p.tracks.String())\n}\n\n\ntype Version string\n\n\n\n\ntype Tempo float64\n\nfunc (t Tempo) String() string {\n\treturn fmt.Sprintf(\"Tempo: %.3g\", t)\n}\n\n\ntype Tracks []Track\n\nfunc (t Tracks) String() string {\n\tpretty := \"\"\n\tfor _, track := range t {\n\t\tpretty = fmt.Sprintf(\"%s%s\\n\", pretty, track.String())\n\t}\n\treturn pretty\n}\n\n\ntype Track struct {\n\tID int\n\tName string\n\tSteps Steps\n}\n\nfunc (t Track) String() string {\n\treturn fmt.Sprintf(\"(%d) %s\\t%s\", t.ID, t.Name, t.Steps.String())\n}\n\n\ntype Steps struct {\n\tBars [4]Bar\n}\n\nfunc (s Steps) String() string {\n\tpretty := \"|\"\n\tfor _, bar := range s.Bars {\n\t\tpretty = pretty + bar.String() + \"|\"\n\t}\n\treturn pretty\n}\n\n\ntype Bar [4]Note\n\nfunc (bar Bar) String() string {\n\tpretty := \"\"\n\tfor _, note := range bar {\n\t\tpretty = pretty + note.String()\n\t}\n\treturn pretty\n}\n\n\ntype Note bool\n\nfunc (n Note) String() string {\n\tif n {\n\t\treturn \"x\"\n\t}\n\treturn \"-\"\n}\n\nfunc (v Version) String() string ", "output": "{\n\treturn fmt.Sprintf(\"Saved with HW Version: %s\", string(v))\n}"} {"input": "package containerengine\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListWorkRequestLogsRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tWorkRequestId *string `mandatory:\"true\" contributesTo:\"path\" name:\"workRequestId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListWorkRequestLogsRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListWorkRequestLogsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request ListWorkRequestLogsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ListWorkRequestLogsRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListWorkRequestLogsResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []WorkRequestLogEntry `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ListWorkRequestLogsResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response ListWorkRequestLogsResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package internal\n\nimport \"go.uber.org/zap\"\nimport gokitLog \"github.com/go-kit/kit/log\"\n\n\n\n\ntype zapToGokitLogAdapter struct {\n\tl *zap.SugaredLogger\n}\n\nfunc (w *zapToGokitLogAdapter) Log(keyvals ...interface{}) error {\n\tif len(keyvals)%2 == 0 {\n\t\tw.l.Infow(\"\", keyvals...)\n\t} else {\n\t\tw.l.Info(keyvals...)\n\t}\n\treturn nil\n}\n\nvar _ gokitLog.Logger = (*zapToGokitLogAdapter)(nil)\n\nfunc NewZapToGokitLogAdapter(logger *zap.Logger) gokitLog.Logger ", "output": "{\n\tlogger = logger.WithOptions(zap.AddCallerSkip(2))\n\treturn &zapToGokitLogAdapter{l: logger.Sugar()}\n}"} {"input": "package projecteuler\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nvar isPrimeTests = []struct {\n\tinput int\n\texpected bool\n}{\n\t{2, true},\n\t{4, false},\n\t{9, false},\n\t{13, true},\n}\n\n\n\nvar findLargestPrimeTests = []struct {\n\tinput int\n\texpected int\n}{\n\t{13195, 29},\n}\n\nfunc TestFindLargestPrime(t *testing.T) {\n\tfor _, td := range findLargestPrimeTests {\n\t\tactual := FindLargestPrime(td.input)\n\t\tif actual != td.expected {\n\t\t\tt.Errorf(\"FindLargestPrime(%d): expected %d, actual %d\", td.input, td.expected, actual)\n\t\t}\n\t}\n\tfmt.Printf(\"3: FindLargestPrime(600851475143) = %d\\n\", FindLargestPrime(600851475143))\n}\n\nfunc TestIsPrime(t *testing.T) ", "output": "{\n\tfor _, td := range isPrimeTests {\n\t\tactual := IsPrime(td.input)\n\t\tif actual != td.expected {\n\t\t\tt.Errorf(\"IsPrime(%d): exptected %t, actual %t\", td.input, td.expected, actual)\n\t\t}\n\t}\n}"} {"input": "package metrics\n\nimport (\n\t\"github.com/cloudfoundry/dropsonde/metric_sender\"\n)\n\nvar metricSender metric_sender.MetricSender\nvar metricBatcher MetricBatcher\n\ntype MetricBatcher interface {\n\tBatchIncrementCounter(name string)\n\tBatchAddCounter(name string, delta uint64)\n\tClose()\n}\n\n\nfunc Initialize(ms metric_sender.MetricSender, mb MetricBatcher) {\n\tif metricBatcher != nil {\n\t\tmetricBatcher.Close()\n\t}\n\tmetricSender = ms\n\tmetricBatcher = mb\n}\n\n\nfunc Close() {\n\tmetricBatcher.Close()\n}\n\n\n\nfunc SendValue(name string, value float64, unit string) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.SendValue(name, value, unit)\n}\n\n\n\n\nfunc IncrementCounter(name string) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.IncrementCounter(name)\n}\n\n\n\n\nfunc BatchIncrementCounter(name string) {\n\tif metricBatcher == nil {\n\t\treturn\n\t}\n\tmetricBatcher.BatchIncrementCounter(name)\n}\n\n\n\n\nfunc AddToCounter(name string, delta uint64) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.AddToCounter(name, delta)\n}\n\n\n\n\nfunc BatchAddCounter(name string, delta uint64) {\n\tif metricBatcher == nil {\n\t\treturn\n\t}\n\tmetricBatcher.BatchAddCounter(name, delta)\n}\n\n\n\n\n\n\n\nfunc SendContainerMetric(applicationId string, instanceIndex int32, cpuPercentage float64, memoryBytes uint64, diskBytes uint64) error ", "output": "{\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\n\treturn metricSender.SendContainerMetric(applicationId, instanceIndex, cpuPercentage, memoryBytes, diskBytes)\n}"} {"input": "package accounts\n\nimport (\n\t\"testing\"\n\n\tos \"github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts\"\n\tth \"github.com/rackspace/gophercloud/testhelper\"\n\tfake \"github.com/rackspace/gophercloud/testhelper/client\"\n)\n\n\n\nfunc TestGetAccounts(t *testing.T) {\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\n\tos.HandleGetAccountSuccessfully(t)\n\n\texpected := map[string]string{\"Foo\": \"bar\"}\n\tactual, err := Get(fake.ServiceClient()).ExtractMetadata()\n\tth.CheckNoErr(t, err)\n\tth.CheckDeepEquals(t, expected, actual)\n}\n\nfunc TestUpdateAccounts(t *testing.T) ", "output": "{\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\n\tos.HandleUpdateAccountSuccessfully(t)\n\n\toptions := &UpdateOpts{Metadata: map[string]string{\"gophercloud-test\": \"accounts\"}}\n\tres := Update(fake.ServiceClient(), options)\n\tth.CheckNoErr(t, res.Err)\n}"} {"input": "package syscall\n\nfunc setTimespec(sec, nsec int64) Timespec {\n\treturn Timespec{Sec: sec, Nsec: nsec}\n}\n\nfunc setTimeval(sec, usec int64) Timeval {\n\treturn Timeval{Sec: sec, Usec: usec}\n}\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint64(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint64(length)\n}\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\n\n\n\nconst RTM_LOCK = 0x8\n\n\n\nconst SYS___SYSCTL = SYS_SYSCTL\n\nfunc (cmsg *Cmsghdr) SetLen(length int) ", "output": "{\n\tcmsg.Len = uint32(length)\n}"} {"input": "package eureka\n\nimport (\n\t\"encoding/xml\"\n\t\"strings\"\n)\n\n\n\nfunc (c *Client) GetApplication(appId string) (*Application, error) {\n\tvalues := []string{\"apps\", appId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar application *Application = new(Application)\n\terr = xml.Unmarshal(response.Body, application)\n\treturn application, err\n}\n\nfunc (c *Client) GetInstance(appId, instanceId string) (*InstanceInfo, error) {\n\tvalues := []string{\"apps\", appId, instanceId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar instance *InstanceInfo = new(InstanceInfo)\n\terr = xml.Unmarshal(response.Body, instance)\n\treturn instance, err\n}\n\nfunc (c *Client) GetVIP(vipId string) (*Applications, error) {\n\tvalues := []string{\"vips\", vipId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar applications *Applications = new(Applications)\n\terr = xml.Unmarshal(response.Body, applications)\n\treturn applications, err\n}\n\nfunc (c *Client) GetSVIP(svipId string) (*Applications, error) {\n\tvalues := []string{\"svips\", svipId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar applications *Applications = new(Applications)\n\terr = xml.Unmarshal(response.Body, applications)\n\treturn applications, err\n}\n\nfunc (c *Client) GetApplications() (*Applications, error) ", "output": "{\n\tresponse, err := c.Get(\"apps\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar applications *Applications = new(Applications)\n\terr = xml.Unmarshal(response.Body, applications)\n\treturn applications, err\n}"} {"input": "package get\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\n\n\n\n\nfunc NewGetWorkflowsLibraryParamsWithTimeout(timeout time.Duration) *GetWorkflowsLibraryParams {\n\n\treturn &GetWorkflowsLibraryParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype GetWorkflowsLibraryParams struct {\n\ttimeout time.Duration\n}\n\n\nfunc (o *GetWorkflowsLibraryParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewGetWorkflowsLibraryParams() *GetWorkflowsLibraryParams ", "output": "{\n\n\treturn &GetWorkflowsLibraryParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}"} {"input": "package gocrawl\n\n\n\ntype popChannel chan []*URLContext\n\n\nfunc newPopChannel() popChannel {\n\treturn make(chan []*URLContext, 1)\n}\n\n\n\n\n\n\nfunc (pc popChannel) stack(cmd ...*URLContext) ", "output": "{\n\ttoStack := cmd\n\tfor {\n\t\tselect {\n\t\tcase pc <- toStack:\n\t\t\treturn\n\t\tcase old := <-pc:\n\t\t\ttoStack = append(old, toStack...)\n\t\t}\n\t}\n}"} {"input": "package httpapi\n\nimport (\n\t\"github.com/labstack/echo\"\n\t\"github.com/labstack/echo/engine/standard\"\n\t\"github.com/labstack/echo/middleware\"\n\t\"net/http\"\n)\n\nvar (\n\tReloadChan chan bool\n)\n\ntype HttpError struct {\n\tCode int `json:\"code\"`\n\tMessage string `json:\"message\"`\n}\n\n\n\nfunc NewHttpError(c echo.Context, code int, msg string) (err error) {\n\thttperr := &HttpError{Code: code, Message: msg}\n\treturn c.JSON(code, httperr)\n}\n\nfunc RunApiServer(addr string, reload chan bool) ", "output": "{\n\tReloadChan = reload\n\n\te := echo.New()\n\te.Pre(middleware.AddTrailingSlash())\n\n\te.GET(\"/\", func(c echo.Context) error {\n\t\treturn c.JSON(http.StatusOK, map[string]string{\"name\": \"Gydro Api Gateway\", \"version\": \"0.1.0\"})\n\t})\n\n\tApiController(e)\n\tConsumerController(e)\n\n\te.Run(standard.New(addr))\n}"} {"input": "\n\nfunc stress1(verbose bool) ", "output": "{\n\tfor i:=0; i<20; i++ {\n\t\tif verbose {\n\t\t\tputs(\"Setting scale to 1\\n\")\n\t\t}\n\t\tscale(1)\n\t\twait(10)\n\n\t\tif verbose {\n\t\t\tputs(\"Setting scale to 2\\n\")\n\t\t}\n\t\tscale(2)\n\t\twait(10)\n\t}\n}"} {"input": "package collector\n\nimport (\n\t\"fullerite/metric\"\n\t\"math/rand\"\n)\n\n\ntype Test struct {\n\tinterval int\n\tchannel chan metric.Metric\n}\n\n\nfunc NewTest() *Test {\n\tt := new(Test)\n\tt.channel = make(chan metric.Metric)\n\treturn t\n}\n\n\nfunc (t Test) Collect() {\n\tmetric := metric.New(\"TestMetric\")\n\tmetric.Value = rand.Float64()\n\tmetric.AddDimension(\"testing\", \"yes\")\n\tt.Channel() <- metric\n}\n\n\nfunc (t Test) Name() string {\n\treturn \"Test\"\n}\n\n\nfunc (t Test) Interval() int {\n\treturn t.interval\n}\n\n\n\n\n\n\nfunc (t Test) String() string {\n\treturn t.Name() + \"Collector\"\n}\n\n\nfunc (t *Test) SetInterval(interval int) {\n\tt.interval = interval\n}\n\nfunc (t Test) Channel() chan metric.Metric ", "output": "{\n\treturn t.channel\n}"} {"input": "package armmanagedservices\n\nconst (\n\tmoduleName = \"armmanagedservices\"\n\tmoduleVersion = \"v0.2.1\"\n)\n\n\ntype MultiFactorAuthProvider string\n\nconst (\n\tMultiFactorAuthProviderAzure MultiFactorAuthProvider = \"Azure\"\n\tMultiFactorAuthProviderNone MultiFactorAuthProvider = \"None\"\n)\n\n\nfunc PossibleMultiFactorAuthProviderValues() []MultiFactorAuthProvider {\n\treturn []MultiFactorAuthProvider{\n\t\tMultiFactorAuthProviderAzure,\n\t\tMultiFactorAuthProviderNone,\n\t}\n}\n\n\n\n\n\ntype ProvisioningState string\n\nconst (\n\tProvisioningStateAccepted ProvisioningState = \"Accepted\"\n\tProvisioningStateCanceled ProvisioningState = \"Canceled\"\n\tProvisioningStateCreated ProvisioningState = \"Created\"\n\tProvisioningStateCreating ProvisioningState = \"Creating\"\n\tProvisioningStateDeleted ProvisioningState = \"Deleted\"\n\tProvisioningStateDeleting ProvisioningState = \"Deleting\"\n\tProvisioningStateFailed ProvisioningState = \"Failed\"\n\tProvisioningStateNotSpecified ProvisioningState = \"NotSpecified\"\n\tProvisioningStateReady ProvisioningState = \"Ready\"\n\tProvisioningStateRunning ProvisioningState = \"Running\"\n\tProvisioningStateSucceeded ProvisioningState = \"Succeeded\"\n\tProvisioningStateUpdating ProvisioningState = \"Updating\"\n)\n\n\nfunc PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateAccepted,\n\t\tProvisioningStateCanceled,\n\t\tProvisioningStateCreated,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleted,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateNotSpecified,\n\t\tProvisioningStateReady,\n\t\tProvisioningStateRunning,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateUpdating,\n\t}\n}\n\n\nfunc (c ProvisioningState) ToPtr() *ProvisioningState {\n\treturn &c\n}\n\nfunc (c MultiFactorAuthProvider) ToPtr() *MultiFactorAuthProvider ", "output": "{\n\treturn &c\n}"} {"input": "package basictypes\n\nconst (\n\tAString = \"a string\"\n\tAnInt = 7\n\tAnInt2 = 1<<63 - 1\n\tAFloat = 0.2015\n\tARune = rune(32)\n\tABool = true\n)\n\nfunc Ints(x int8, y int16, z int32, t int64, u int) {}\n\nfunc Error() error { return nil }\n\n\n\nfunc ByteArrays(x []byte) []byte { return nil }\n\nfunc Bool(bool) bool { return true }\n\nfunc ErrorPair() (int, error) ", "output": "{ return 0, nil }"} {"input": "package logging\n\n\ntype DefaultFormatter struct {\n}\n\n\n\n\n\nfunc (f *DefaultFormatter) GetSuffix(lvl level) string {\n\treturn \"\"\n}\n\n\nfunc (f *DefaultFormatter) Format(lvl level, v ...interface{}) []interface{} {\n\treturn append([]interface{}{header()}, v...)\n}\n\nfunc (f *DefaultFormatter) GetPrefix(lvl level) string ", "output": "{\n\treturn \"\"\n}"} {"input": "package fake\n\nimport (\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n\n\taction \"github.com/vmware-tanzu/octant/pkg/action\"\n)\n\n\ntype MockActionRegistrar struct {\n\tctrl *gomock.Controller\n\trecorder *MockActionRegistrarMockRecorder\n}\n\n\ntype MockActionRegistrarMockRecorder struct {\n\tmock *MockActionRegistrar\n}\n\n\nfunc NewMockActionRegistrar(ctrl *gomock.Controller) *MockActionRegistrar {\n\tmock := &MockActionRegistrar{ctrl: ctrl}\n\tmock.recorder = &MockActionRegistrarMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockActionRegistrar) EXPECT() *MockActionRegistrarMockRecorder {\n\treturn m.recorder\n}\n\n\nfunc (m *MockActionRegistrar) Register(arg0, arg1 string, arg2 action.DispatcherFunc) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Register\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}\n\n\nfunc (mr *MockActionRegistrarMockRecorder) Register(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Register\", reflect.TypeOf((*MockActionRegistrar)(nil).Register), arg0, arg1, arg2)\n}\n\n\nfunc (m *MockActionRegistrar) Unregister(arg0, arg1 string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Unregister\", arg0, arg1)\n}\n\n\n\n\nfunc (mr *MockActionRegistrarMockRecorder) Unregister(arg0, arg1 interface{}) *gomock.Call ", "output": "{\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Unregister\", reflect.TypeOf((*MockActionRegistrar)(nil).Unregister), arg0, arg1)\n}"} {"input": "package main \n\nimport (\n\t\"testing\" \n)\n\n\n\nfunc Benchmark_numberOfWaysToMakeX1(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tnumberOfWaysToMakeX1(200)\n\t}\n}\n\nfunc Benchmark_numberOfWaysToMakeX2(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tnumberOfWaysToMakeX2(200)\n\t}\n}\n\nfunc Benchmark_numberOfWaysToMake2Pounds(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tnumberOfWaysToMake2Pounds()\n\t}\n}"} {"input": "package discovery\n\nimport (\n\t\"net/url\"\n\n\t\"github.com/pkg/errors\"\n\n\tclientcmdapi \"k8s.io/client-go/tools/clientcmd/api\"\n\t\"k8s.io/klog/v2\"\n\tkubeadmapi \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm\"\n\tkubeadmapiv1 \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta3\"\n\t\"k8s.io/kubernetes/cmd/kubeadm/app/discovery/file\"\n\t\"k8s.io/kubernetes/cmd/kubeadm/app/discovery/https\"\n\t\"k8s.io/kubernetes/cmd/kubeadm/app/discovery/token\"\n\tkubeconfigutil \"k8s.io/kubernetes/cmd/kubeadm/app/util/kubeconfig\"\n)\n\n\nconst TokenUser = \"tls-bootstrap-token-user\"\n\n\n\n\n\n\nfunc DiscoverValidatedKubeConfig(cfg *kubeadmapi.JoinConfiguration) (*clientcmdapi.Config, error) {\n\tswitch {\n\tcase cfg.Discovery.File != nil:\n\t\tkubeConfigPath := cfg.Discovery.File.KubeConfigPath\n\t\tif isHTTPSURL(kubeConfigPath) {\n\t\t\treturn https.RetrieveValidatedConfigInfo(kubeConfigPath, kubeadmapiv1.DefaultClusterName, cfg.Discovery.Timeout.Duration)\n\t\t}\n\t\treturn file.RetrieveValidatedConfigInfo(kubeConfigPath, kubeadmapiv1.DefaultClusterName, cfg.Discovery.Timeout.Duration)\n\tcase cfg.Discovery.BootstrapToken != nil:\n\t\treturn token.RetrieveValidatedConfigInfo(&cfg.Discovery)\n\tdefault:\n\t\treturn nil, errors.New(\"couldn't find a valid discovery configuration\")\n\t}\n}\n\n\nfunc isHTTPSURL(s string) bool {\n\tu, err := url.Parse(s)\n\treturn err == nil && u.Scheme == \"https\"\n}\n\nfunc For(cfg *kubeadmapi.JoinConfiguration) (*clientcmdapi.Config, error) ", "output": "{\n\tconfig, err := DiscoverValidatedKubeConfig(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"couldn't validate the identity of the API Server\")\n\t}\n\n\tif len(cfg.Discovery.TLSBootstrapToken) != 0 {\n\t\tklog.V(1).Info(\"[discovery] Using provided TLSBootstrapToken as authentication credentials for the join process\")\n\n\t\tclusterinfo := kubeconfigutil.GetClusterFromKubeConfig(config)\n\t\treturn kubeconfigutil.CreateWithToken(\n\t\t\tclusterinfo.Server,\n\t\t\tkubeadmapiv1.DefaultClusterName,\n\t\t\tTokenUser,\n\t\t\tclusterinfo.CertificateAuthorityData,\n\t\t\tcfg.Discovery.TLSBootstrapToken,\n\t\t), nil\n\t}\n\n\tif kubeconfigutil.HasAuthenticationCredentials(config) {\n\t\treturn config, nil\n\t}\n\n\treturn nil, errors.New(\"couldn't find authentication credentials for the TLS boostrap process. Please use Token discovery, a discovery file with embedded authentication credentials or a discovery file without authentication credentials but with the TLSBootstrapToken flag\")\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"os\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"github.com/go-xorm/xorm\"\n)\n\n\ntype Account struct {\n\tId int64\n\tName string `xorm:\"unique\"`\n\tBalance float64\n\tVersion int `xorm:\"version\"` \n}\n\n\nfunc (a *Account) BeforeInsert() {\n\tlog.Printf(\"before insert: %s\", a.Name)\n}\n\n\nfunc (a *Account) AfterInsert() {\n\tlog.Printf(\"after insert: %s\", a.Name)\n}\n\n\nvar x *xorm.Engine\n\n\n\n\nfunc newAccount(name string, balance float64) error {\n\t_, err := x.Insert(&Account{Name: name, Balance: balance})\n\treturn err\n}\n\n\nfunc getAccountCount() (int64, error) {\n\treturn x.Count(new(Account))\n}\n\n\nfunc getAccount(id int64) (*Account, error) {\n\ta := &Account{}\n\thas, err := x.ID(id).Get(a)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if !has {\n\t\treturn nil, errors.New(\"Account does not exist\")\n\t}\n\treturn a, nil\n}\n\nfunc init() ", "output": "{\n\tvar err error\n\tx, err = xorm.NewEngine(\"mysql\", \"root:password@tcp(10.10.0.122)/test?charset=utf8&parseTime=True&loc=Local\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to create engine: %v\\n\", err)\n\t}\n\n\tif err = x.Sync(new(Account)); err != nil {\n\t\tlog.Fatalf(\"Fail to sync database: %v\\n\", err)\n\t}\n\n\tf, err := os.Create(\"sql.log\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to create log file: %v\\n\", err)\n\t\treturn\n\t}\n\tx.SetLogger(xorm.NewSimpleLogger(f))\n\tx.ShowSQL()\n\n\tcacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)\n\tx.SetDefaultCacher(cacher)\n}"} {"input": "package route\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar ()\n\n\ntype Route struct {\n\tPath string\n\tSystem int\n\tS0 NullRoute\n\tS1 StringRoute\n\tS2 ControllerRoute\n\tS3 FilesystemRoute\n\tS4 FunctionRoute\n}\n\n\n\n\n\nfunc (r *Route) Read(w http.ResponseWriter, req *http.Request) {\n\tresult := \"\"\n\tswitch r.System {\n\tcase 0:\n\t\tresult = \"\"\n\tcase 1:\n\t\tresult = r.S1.String\n\tcase 2:\n\tcase 3:\n\t\tresult = r.S3.FileContent\n\tcase 4:\n\t\tresult = r.S4.Function()\n\t}\n\tio.Copy(w, strings.NewReader(result))\n}\n\n\nfunc ValidStringRoute(str string) bool {\n\trouteStringRegexp := `^\\/([a-zA-Z0-9](\\/)*)*\\s(null|str .*|fs .*)$`\n\tr, _ := regexp.Compile(routeStringRegexp)\n\tif r.MatchString(str) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc NewRoute(path string, system int) Route ", "output": "{\n\treturn Route{path, system, NullRoute{}, StringRoute{}, ControllerRoute{}, FilesystemRoute{}, FunctionRoute{}}\n}"} {"input": "package model\n\nimport (\n\t\"github.com/Konstantin8105/GoFea/input/element\"\n\t\"github.com/Konstantin8105/GoFea/input/material\"\n)\n\ntype materialLinearGroup struct {\n\tmaterial material.Linear\n\telementIndex element.Index\n}\n\n\ntype materialByElement []materialLinearGroup\n\nfunc (a materialByElement) Len() int { return len(a) }\nfunc (a materialByElement) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a materialByElement) Less(i, j int) bool { return a[i].elementIndex < a[j].elementIndex }\nfunc (a materialByElement) Equal(i, j int) bool { return a[i].elementIndex == a[j].elementIndex }\n\n\nfunc (a materialByElement) Name(i int) int ", "output": "{ return int(a[i].elementIndex) }"} {"input": "package longrunning_test\n\nimport (\n\t\"cloud.google.com/go/longrunning/autogen\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/api/iterator\"\n\tlongrunningpb \"google.golang.org/genproto/googleapis/longrunning\"\n)\n\nfunc ExampleNewOperationsClient() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\nfunc ExampleOperationsClient_GetOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.GetOperationRequest{\n\t}\n\tresp, err := c.GetOperation(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\n\n\nfunc ExampleOperationsClient_CancelOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.CancelOperationRequest{\n\t}\n\terr = c.CancelOperation(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleOperationsClient_DeleteOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.DeleteOperationRequest{\n\t}\n\terr = c.DeleteOperation(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleOperationsClient_ListOperations() ", "output": "{\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.ListOperationsRequest{\n\t}\n\tit := c.ListOperations(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}"} {"input": "package cases\n\nimport (\n\t\"io/ioutil\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc isIncludedTestCase(s string, includes, ignores []string) bool {\n\n\tfor _, ignore := range ignores {\n\t\trgx := rgxForMatcher(ignore)\n\n\t\tif rgx.MatchString(s) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tfor _, include := range includes {\n\t\trgx := rgxForMatcher(include)\n\n\t\tif !rgx.MatchString(s) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n\n}\n\nfunc rgxForMatcher(s string) *regexp.Regexp {\n\treturn regexp.MustCompile(\"(?i)\" + regexp.QuoteMeta(s))\n}\n\nfunc testFilesFor(t testing.TB, dirname string, includes, ignores []string) []string ", "output": "{\n\tfiles, err := ioutil.ReadDir(dirname)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ttestFiles := make([]string, 0)\n\n\tfor _, file := range files {\n\n\t\tif file.IsDir() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !strings.HasSuffix(file.Name(), \".json\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !isIncludedTestCase(file.Name(), includes, ignores) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !isTestCaseAllowed(file.Name()) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !file.IsDir() {\n\t\t\ttestFiles = append(testFiles, filepath.Join(dirname, file.Name()))\n\t\t}\n\n\t}\n\n\treturn testFiles\n}"} {"input": "package main\n\nimport (\n\t\"code.google.com/p/go.crypto/ssh/terminal\"\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc clearscr() {\n\tfmt.Printf(\"%c[2J%c[0;0H\", 27, 27)\n}\n\ntype uterm struct {\n\ts *terminal.State\n\tt *terminal.Terminal\n}\n\nfunc newTerm() Term {\n\tu := new(uterm)\n\tvar err error\n\tu.s, err = terminal.MakeRaw(0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tu.t = terminal.NewTerminal(os.Stdin, \"lixian >> \")\n\treturn u\n}\n\n\n\nfunc (u *uterm) ReadLine() (string, error) {\n\treturn u.t.ReadLine()\n}\n\nfunc (u *uterm) Restore() ", "output": "{\n\tterminal.Restore(0, u.s)\n}"} {"input": "package rpc\n\nimport (\n\t\"github.com/open-falcon/common/model\"\n\t\"github.com/open-falcon/judge/g\"\n\t\"github.com/open-falcon/judge/store\"\n\t\"time\"\n)\n\ntype Judge int\n\n\n\nfunc (this *Judge) Send(items []*model.JudgeItem, resp *model.SimpleRpcResponse) error {\n\tremain := g.Config().Remain\n\tnow := time.Now().Unix()\n\tfor _, item := range items {\n\t\tpk := item.PrimaryKey()\n\n\t\tstore.HistoryBigMap[pk[0:2]].PushFrontAndMaintain(pk, item, remain, now)\n\t}\n\treturn nil\n}\n\nfunc (this *Judge) Ping(req model.NullRpcRequest, resp *model.SimpleRpcResponse) error ", "output": "{\n\treturn nil\n}"} {"input": "package ks\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nfunc ReadBytesFromFile(filename string) ([]byte, error) {\n\tfin, err := os.Open(filename)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ioutil.ReadAll(fin)\n}\n\nfunc ReadLines(r io.Reader) []string {\n\n\tbr := bufio.NewReader(r)\n\tvar res []string\n\n\tfor {\n\t\ts, _, err := br.ReadLine()\n\n\t\tif err != nil {\n\t\t\treturn res\n\t\t}\n\n\t\tres = append(res, string(s))\n\n\t}\n\n}\n\nfunc ListFiles(folder string) []string {\n\n\tvar res []string\n\n\tfilepath.Walk(fmt.Sprintf(folder),\n\t\tfunc(path string, info os.FileInfo, err error) error {\n\n\t\t\tif info != nil && !info.IsDir() {\n\t\t\t\tres = append(res, info.Name())\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\treturn res\n}\n\n\n\nfunc FileExists(filename string) bool ", "output": "{\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\n\t\treturn false\n\t}\n\n\treturn true\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/tj/go-spin\"\n)\n\nfunc main() {\n\ts := spin.New()\n\n\tshow(s, \"Default\", spin.Default)\n\n\tshow(s, \"Box1\", spin.Box1)\n\tshow(s, \"Box2\", spin.Box2)\n\tshow(s, \"Box3\", spin.Box3)\n\tshow(s, \"Box4\", spin.Box4)\n\tshow(s, \"Box5\", spin.Box5)\n\tshow(s, \"Box6\", spin.Box6)\n\tshow(s, \"Box7\", spin.Box7)\n\n\tshow(s, \"Spin1\", spin.Spin1)\n\tshow(s, \"Spin2\", spin.Spin2)\n\tshow(s, \"Spin3\", spin.Spin3)\n\tshow(s, \"Spin4\", spin.Spin4)\n\tshow(s, \"Spin5\", spin.Spin5)\n\tshow(s, \"Spin6\", spin.Spin6)\n\tshow(s, \"Spin7\", spin.Spin7)\n\tshow(s, \"Spin8\", spin.Spin8)\n\tshow(s, \"Spin9\", spin.Spin9)\n}\n\n\n\nfunc show(s *spin.Spinner, name, frames string) ", "output": "{\n\ts.Set(frames)\n\tfmt.Printf(\"\\n\\n %s: %s\\n\\n\", name, frames)\n\tfor i := 0; i < 30; i++ {\n\t\tfmt.Printf(\"\\r \\033[36mcomputing\\033[m %s \", s.Next())\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}"} {"input": "package tagquery\n\nimport (\n\t\"io\"\n\n\t\"github.com/grafana/metrictank/schema\"\n)\n\ntype expressionMatchNone struct {\n\texpressionCommon\n\toriginalOperator ExpressionOperator\n}\n\nfunc (e *expressionMatchNone) Equals(other Expression) bool {\n\treturn e.key == other.GetKey() && e.GetOperator() == other.GetOperator() && e.value == other.GetValue()\n}\n\nfunc (e *expressionMatchNone) GetDefaultDecision() FilterDecision {\n\treturn Fail\n}\n\nfunc (e *expressionMatchNone) GetKey() string {\n\treturn e.key\n}\n\nfunc (e *expressionMatchNone) GetValue() string {\n\treturn e.value\n}\n\nfunc (e *expressionMatchNone) GetOperator() ExpressionOperator {\n\treturn MATCH_NONE\n}\n\nfunc (e *expressionMatchNone) GetOperatorCost() uint32 {\n\treturn 0\n}\n\nfunc (e *expressionMatchNone) RequiresNonEmptyValue() bool {\n\treturn true\n}\n\n\n\nfunc (e *expressionMatchNone) GetMetricDefinitionFilter(_ IdTagLookup) MetricDefinitionFilter {\n\treturn func(_ schema.MKey, _ string, _ []string) FilterDecision { return Fail }\n}\n\nfunc (e *expressionMatchNone) StringIntoWriter(writer io.Writer) {\n\twriter.Write([]byte(e.key))\n\te.originalOperator.StringIntoWriter(writer)\n\twriter.Write([]byte(e.value))\n}\n\nfunc (e *expressionMatchNone) Matches(value string) bool ", "output": "{\n\treturn false\n}"} {"input": "package migrations\n\nimport (\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"code.cloudfoundry.org/bbs/migration\"\n)\n\nvar migrationsRegistry = migration.Migrations{}\n\n\n\nfunc migrationString(m migration.Migration) string {\n\t_, filename, _, ok := runtime.Caller(1)\n\tif !ok {\n\t\treturn strconv.FormatInt(m.Version(), 10)\n\t}\n\treturn strings.Split(filepath.Base(filename), \".\")[0]\n}\n\nfunc AllMigrations() migration.Migrations {\n\tmigs := make(migration.Migrations, len(migrationsRegistry))\n\tfor i, mig := range migrationsRegistry {\n\t\trt := reflect.TypeOf(mig)\n\t\tif rt.Kind() == reflect.Ptr {\n\t\t\trt = rt.Elem()\n\t\t}\n\t\tmigs[i] = reflect.New(rt).Interface().(migration.Migration)\n\t}\n\treturn migs\n}\n\nfunc appendMigration(migrationTemplate migration.Migration) ", "output": "{\n\tmigrationsRegistry = append(migrationsRegistry, migrationTemplate)\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\nvar configFileOptions map[string]interface{}\n\nfunc LoadConfigFile(file string) error {\n\tconfigFileOptions = nil\n\tif _, err := os.Stat(file); err != nil {\n\t\treturn nil\n\t}\n\tif s, err := ioutil.ReadFile(file); err != nil {\n\t\treturn err\n\t} else if err := yaml.Unmarshal(s, &configFileOptions); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc getConfigFileValue(key string) interface{} {\n\tif v, ok := configFileOptions[key]; ok {\n\t\treturn v\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc IsKeyInConfig(key string) bool {\n\t_, ok := configFileOptions[key]\n\treturn ok\n}\n\nfunc getConfigFileValueWithDefault(key string, defaultValue interface{}) interface{} {\n\tif v := getConfigFileValue(key); v != nil {\n\t\treturn v\n\t} else {\n\t\treturn defaultValue\n\t}\n}\n\n\n\n\n\nfunc GetConfigFileString(key string) string {\n\tv, _ := getConfigFileValue(key).(string)\n\treturn v\n}\n\nfunc GetConfigFileStringWithDefault(key string, defaultValue interface{}) string {\n\tv, _ := getConfigFileValueWithDefault(key, defaultValue).(string)\n\treturn v\n}\n\nfunc GetConfigFileSlice(key string) []string ", "output": "{\n\tif v, ok := configFileOptions[key].([]interface{}); ok {\n\t\tretVal := []string{}\n\t\tfor _, e := range v {\n\t\t\tif strV, ok := e.(string); ok {\n\t\t\t\tretVal = append(retVal, strV)\n\t\t\t}\n\t\t}\n\t\treturn retVal\n\t} else {\n\t\treturn []string{}\n\t}\n}"} {"input": "package disjointset\n\nimport ()\n\ntype QuickUnion struct {\n\tdisjointset\n}\n\nfunc NewQuickUnion(N int) *QuickUnion {\n\tthis := &QuickUnion{}\n\tthis.UnionFind = this\n\tthis.Init(N)\n\treturn this\n}\n\nfunc (this *QuickUnion) Find(p int) int {\n\tfor p != this.id[p] {\n\t\tp = this.id[p]\n\t}\n\treturn p\n}\n\n\n\nfunc (this *QuickUnion) Union(p, q int) ", "output": "{\n\tpRoot := this.Find(p)\n\tqRoot := this.Find(q)\n\n\tif pRoot == qRoot {\n\t\treturn\n\t}\n\n\tthis.id[pRoot] = qRoot\n\n\tthis.count--\n}"} {"input": "package gamejam\n\ntype SceneID int\n\ntype Scene interface {\n\tAddComponent(c Component)\n\tLoad(r Resources) (err error)\n\tUnload(r Resources) (err error)\n\tRender()\n\tUpdate(mgr SceneManager)\n\tSetSceneID(id SceneID)\n\tSceneID() SceneID\n}\n\ntype BaseScene struct {\n\tcomponents map[ComponentID]Component\n\tid SceneID\n}\n\nfunc NewBaseScene() *BaseScene {\n\treturn &BaseScene{\n\t\tcomponents: map[ComponentID]Component{},\n\t}\n}\n\nfunc (s *BaseScene) AddComponent(c Component) {\n\tc.SetScene(s)\n\ts.components[c.GetID()] = c\n}\n\nfunc (s *BaseScene) Load(r Resources) (err error) {\n\treturn\n}\n\nfunc (s *BaseScene) Render() {\n}\n\nfunc (s *BaseScene) SetSceneID(id SceneID) {\n\ts.id = id\n}\n\nfunc (s *BaseScene) SceneID() SceneID {\n\treturn s.id\n}\n\n\n\nfunc (s *BaseScene) Update(mgr SceneManager) {\n}\n\nfunc (s *BaseScene) Unload(r Resources) (err error) ", "output": "{\n\tvar (\n\t\tid ComponentID\n\t\tc Component\n\t)\n\tfor id, c = range s.components {\n\t\ts.components[id] = nil\n\t\tc.Delete()\n\t}\n\treturn\n}"} {"input": "package da_griddata\n\nimport (\n\t\"github.com/watermint/toolbox/essentials/io/es_stdout\"\n\t\"github.com/watermint/toolbox/infra/control/app_control\"\n\t\"sync\"\n)\n\nfunc NewConsoleWriter(formatter GridDataFormatter, pw PlainGridDataWriter) GridDataWriter {\n\treturn &consoleWriter{\n\t\tformatter: formatter,\n\t\tpw: pw,\n\t}\n}\n\ntype consoleWriter struct {\n\tctl app_control.Control\n\tname string\n\tformatter GridDataFormatter\n\tpw PlainGridDataWriter\n\trow int\n\tmutex sync.Mutex\n}\n\n\n\nfunc (z *consoleWriter) Row(column []interface{}) {\n\tz.mutex.Lock()\n\tdefer z.mutex.Unlock()\n\tout := es_stdout.NewDefaultOut(z.ctl.Feature())\n\n\t_ = z.pw.WriteRow(z.ctl.Log(), out, z.formatter, z.row, column)\n\tz.row++\n}\n\nfunc (z *consoleWriter) Open(c app_control.Control) error {\n\tz.ctl = c\n\treturn nil\n}\n\nfunc (z *consoleWriter) Close() {\n}\n\nfunc (z *consoleWriter) Name() string ", "output": "{\n\treturn z.name\n}"} {"input": "package registrytest\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/api\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/fields\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/labels\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/watch\"\n)\n\n\ntype EndpointRegistry struct {\n\tEndpoints *api.EndpointsList\n\tUpdates []api.Endpoints\n\tErr error\n\n\tlock sync.Mutex\n}\n\nfunc (e *EndpointRegistry) ListEndpoints(ctx api.Context) (*api.EndpointsList, error) {\n\te.lock.Lock()\n\tdefer e.lock.Unlock()\n\n\treturn e.Endpoints, e.Err\n}\n\n\n\nfunc (e *EndpointRegistry) WatchEndpoints(ctx api.Context, labels labels.Selector, fields fields.Selector, resourceVersion string) (watch.Interface, error) {\n\treturn nil, fmt.Errorf(\"unimplemented!\")\n}\n\nfunc (e *EndpointRegistry) UpdateEndpoints(ctx api.Context, endpoints *api.Endpoints) error {\n\te.lock.Lock()\n\tdefer e.lock.Unlock()\n\n\te.Updates = append(e.Updates, *endpoints)\n\n\tif e.Err != nil {\n\t\treturn e.Err\n\t}\n\tif e.Endpoints == nil {\n\t\te.Endpoints = &api.EndpointsList{\n\t\t\tItems: []api.Endpoints{\n\t\t\t\t*endpoints,\n\t\t\t},\n\t\t}\n\t\treturn nil\n\t}\n\tfor ix := range e.Endpoints.Items {\n\t\tif e.Endpoints.Items[ix].Name == endpoints.Name {\n\t\t\te.Endpoints.Items[ix] = *endpoints\n\t\t}\n\t}\n\te.Endpoints.Items = append(e.Endpoints.Items, *endpoints)\n\treturn nil\n}\n\nfunc (e *EndpointRegistry) GetEndpoints(ctx api.Context, name string) (*api.Endpoints, error) ", "output": "{\n\te.lock.Lock()\n\tdefer e.lock.Unlock()\n\tif e.Err != nil {\n\t\treturn nil, e.Err\n\t}\n\tif e.Endpoints != nil {\n\t\tfor _, endpoint := range e.Endpoints.Items {\n\t\t\tif endpoint.Name == name {\n\t\t\t\treturn &endpoint, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, errors.NewNotFound(\"Endpoints\", name)\n}"} {"input": "package queue\n\nimport \"fmt\"\n\ntype Queue struct {\n\tElems []interface{}\n\tTop int\n\tBottom int\n\tMaxlen int\n\tFull bool\n}\n\n\nfunc New(maxLen int) *Queue {\n\tq := &Queue{\n\t\tElems: make([]interface{}, maxLen),\n\t\tTop: 0,\n\t\tBottom: 0,\n\t\tMaxlen: maxLen,\n\t}\n\n\tfmt.Printf(\"Queue: %d\\n\", q.Maxlen)\n\treturn q\n}\n\nfunc (q *Queue) EnQueue(e interface{}) {\n\n\tif q.Maxlen == q.Bottom - q.Top {\n\t\tq.Bottom = q.Top\n\t\tq.Full = true\n\t}\n\tq.Elems[q.Bottom] = e\n\tq.Bottom++\n\n}\n\nfunc (q *Queue) DeQueue() {\n\n\tif q.Bottom > q.Top {\n\t\tq.Top++\n\t}\n\n}\n\n\n\nfunc (q *Queue) Len() int ", "output": "{\n\treturn len(q.Elems)\n}"} {"input": "package arrow\n\nimport (\n\t\"sort\"\n\n\t\"github.com/catorpilor/leetcode/utils\"\n)\n\nfunc minArrows(points [][]int) int {\n\treturn useTwoPointers(points)\n}\n\n\nfunc useTwoPointers(points [][]int) int {\n\tn := len(points)\n\tif n <= 1 {\n\t\treturn n\n\t}\n\tsort.Slice(points, func(i, j int) bool {\n\t\tif points[i][0] == points[j][0] {\n\t\t\treturn points[i][1] < points[j][1]\n\t\t}\n\t\treturn points[i][0] < points[j][0]\n\t})\n\tleft, right := points[0][0], points[0][1]\n\tans := 1\n\tfor i := 1; i < n; i++ {\n\t\tif points[i][0] > right {\n\t\t\tright = points[i][1]\n\t\t\tans++\n\t\t} else {\n\t\t\tright = utils.Min(right, points[i][1])\n\t\t}\n\t\t_ = left\n\t\tleft = points[i][0]\n\t}\n\treturn ans\n}\n\n\n\n\nfunc useBoundary(points [][]int) int ", "output": "{\n\tn := len(points)\n\tif n <= 1 {\n\t\treturn n\n\t}\n\tsort.Slice(points, func(i, j int) bool {\n\t\treturn points[i][1] < points[j][1]\n\t})\n\tcurB := points[0]\n\tans := 1\n\tfor i := 1; i < n; i++ {\n\t\tif points[i][0] > curB[1] {\n\t\t\tans++\n\t\t\tcurB = points[i]\n\t\t}\n\t}\n\treturn ans\n}"} {"input": "package internal\n\nimport (\n\t\"encoding/json\"\n\t\"regexp\"\n)\n\ntype Pattern struct {\n\t*regexp.Regexp\n}\n\ntype CallBack func(g []string) error\n\nfunc (p Pattern) IfMatches(s string, callback CallBack) error {\n\tif g := p.FindStringSubmatch(s); g != nil {\n\t\treturn callback(g)\n\t}\n\treturn nil\n}\n\n\n\nfunc (p *Pattern) UnmarshalJSON(text []byte) error ", "output": "{\n\tvar pattern string\n\tif err := json.Unmarshal(text, &pattern); err != nil {\n\t\treturn err\n\t}\n\n\tq, err := regexp.Compile(pattern)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.Regexp = q\n\treturn nil\n}"} {"input": "package stats\n\nimport (\n\t\"time\"\n\n\t\"sync\"\n\n\t\"github.com/paulbellamy/ratecounter\"\n)\n\nvar lock = sync.RWMutex{}\n\ntype stat struct {\n\treadReq *ratecounter.RateCounter\n\twriteReq *ratecounter.RateCounter\n}\n\nfunc newStat() stat {\n\treturn stat{\n\t\treadReq: ratecounter.NewRateCounter(time.Hour),\n\t\twriteReq: ratecounter.NewRateCounter(time.Hour),\n\t}\n}\n\ntype namespaceStatMap map[string]stat\n\nvar golbalNamespaceStat namespaceStatMap\n\n\n\n\nfunc AddNamespace(label string) {\n\t_, ok := golbalNamespaceStat[label]\n\tif ok {\n\t\treturn\n\t}\n\n\tgolbalNamespaceStat[label] = newStat()\n\treturn\n}\n\n\nfunc IncrRead(label string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tstat, ok := golbalNamespaceStat[label]\n\tif !ok {\n\t\tAddNamespace(label)\n\t\tstat = golbalNamespaceStat[label]\n\t}\n\n\tstat.readReq.Incr(1)\n}\n\n\nfunc IncrWrite(label string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tstat, ok := golbalNamespaceStat[label]\n\tif !ok {\n\t\tAddNamespace(label)\n\t\tstat = golbalNamespaceStat[label]\n\t}\n\n\tstat.writeReq.Incr(1)\n}\n\n\nfunc Rate(label string) (read, write int64) {\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\tstat, ok := golbalNamespaceStat[label]\n\tif !ok {\n\t\tAddNamespace(label)\n\t\tstat = golbalNamespaceStat[label]\n\t}\n\n\treturn stat.readReq.Rate(), stat.writeReq.Rate()\n}\n\nfunc init() ", "output": "{\n\tgolbalNamespaceStat = namespaceStatMap{}\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n)\n\nfunc PK(endpoint, metric string, tags map[string]string) string {\n\tif tags == nil || len(tags) == 0 {\n\t\treturn fmt.Sprintf(\"%s/%s\", endpoint, metric)\n\t}\n\treturn fmt.Sprintf(\"%s/%s/%s\", endpoint, metric, SortedTags(tags))\n}\n\nfunc PK2(endpoint, counter string) string {\n\treturn fmt.Sprintf(\"%s/%s\", endpoint, counter)\n}\n\nfunc UUID(endpoint, metric string, tags map[string]string, dstype string, step int) string {\n\tif tags == nil || len(tags) == 0 {\n\t\treturn fmt.Sprintf(\"%s/%s/%s/%d\", endpoint, metric, dstype, step)\n\t}\n\treturn fmt.Sprintf(\"%s/%s/%s/%s/%d\", endpoint, metric, SortedTags(tags), dstype, step)\n}\n\n\n\nfunc ChecksumOfUUID(endpoint, metric string, tags map[string]string, dstype string, step int64) string {\n\treturn Md5(UUID(endpoint, metric, tags, dstype, int(step)))\n}\n\nfunc Checksum(endpoint string, metric string, tags map[string]string) string ", "output": "{\n\tpk := PK(endpoint, metric, tags)\n\treturn Md5(pk)\n}"} {"input": "package keymanager\n\nimport (\n\t\"launchpad.net/juju-core/state/api\"\n\t\"launchpad.net/juju-core/state/api/params\"\n\t\"launchpad.net/juju-core/utils/ssh\"\n)\n\n\ntype Client struct {\n\tst *api.State\n}\n\n\nfunc NewClient(st *api.State) *Client {\n\treturn &Client{st}\n}\n\n\nfunc (c *Client) Close() error {\n\treturn c.st.Close()\n}\n\n\n\n\n\nfunc (c *Client) AddKeys(user string, keys ...string) ([]params.ErrorResult, error) {\n\tp := params.ModifyUserSSHKeys{User: user, Keys: keys}\n\tresults := new(params.ErrorResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"AddKeys\", p, results)\n\treturn results.Results, err\n}\n\n\nfunc (c *Client) DeleteKeys(user string, keys ...string) ([]params.ErrorResult, error) {\n\tp := params.ModifyUserSSHKeys{User: user, Keys: keys}\n\tresults := new(params.ErrorResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"DeleteKeys\", p, results)\n\treturn results.Results, err\n}\n\n\nfunc (c *Client) ImportKeys(user string, keyIds ...string) ([]params.ErrorResult, error) {\n\tp := params.ModifyUserSSHKeys{User: user, Keys: keyIds}\n\tresults := new(params.ErrorResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"ImportKeys\", p, results)\n\treturn results.Results, err\n}\n\nfunc (c *Client) ListKeys(mode ssh.ListMode, users ...string) ([]params.StringsResult, error) ", "output": "{\n\tp := params.ListSSHKeys{Mode: mode}\n\tp.Entities.Entities = make([]params.Entity, len(users))\n\tfor i, userName := range users {\n\t\tp.Entities.Entities[i] = params.Entity{Tag: userName}\n\t}\n\tresults := new(params.StringsResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"ListKeys\", p, results)\n\treturn results.Results, err\n}"} {"input": "package app\n\nimport (\n\t\"flag\"\n\n\t\"github.com/spf13/viper\"\n)\n\nconst (\n\tindexPrefix = \"index-prefix\"\n\tarchive = \"archive\"\n\tusername = \"es.username\"\n\tpassword = \"es.password\"\n\tuseILM = \"es.use-ilm\"\n\tilmPolicyName = \"es.ilm-policy-name\"\n\ttimeout = \"timeout\"\n)\n\n\ntype Config struct {\n\tIndexPrefix string\n\tArchive bool\n\tUsername string\n\tPassword string\n\tTLSEnabled bool\n\tILMPolicyName string\n\tUseILM bool\n\tTimeout int\n}\n\n\nfunc AddFlags(flags *flag.FlagSet) {\n\tflags.String(indexPrefix, \"\", \"Index prefix\")\n\tflags.Bool(archive, false, \"Handle archive indices\")\n\tflags.String(username, \"\", \"The username required by storage\")\n\tflags.String(password, \"\", \"The password required by storage\")\n\tflags.Bool(useILM, false, \"Use ILM to manage jaeger indices\")\n\tflags.String(ilmPolicyName, \"jaeger-ilm-policy\", \"The name of the ILM policy to use if ILM is active\")\n\tflags.Int(timeout, 120, \"Number of seconds to wait for master node response\")\n}\n\n\n\n\nfunc (c *Config) InitFromViper(v *viper.Viper) ", "output": "{\n\tc.IndexPrefix = v.GetString(indexPrefix)\n\tif c.IndexPrefix != \"\" {\n\t\tc.IndexPrefix += \"-\"\n\t}\n\tc.Archive = v.GetBool(archive)\n\tc.Username = v.GetString(username)\n\tc.Password = v.GetString(password)\n\tc.ILMPolicyName = v.GetString(ilmPolicyName)\n\tc.UseILM = v.GetBool(useILM)\n\tc.Timeout = v.GetInt(timeout)\n}"} {"input": "package commands\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/layeh/gumble/gumble\"\n\t\"github.com/matthieugrieger/mumbledj/interfaces\"\n\t\"github.com/spf13/viper\"\n)\n\n\n\ntype SkipPlaylistCommand struct{}\n\n\n\n\n\nfunc (c *SkipPlaylistCommand) Description() string {\n\treturn viper.GetString(\"commands.skipplaylist.description\")\n}\n\n\n\nfunc (c *SkipPlaylistCommand) IsAdminCommand() bool {\n\treturn viper.GetBool(\"commands.skipplaylist.is_admin\")\n}\n\n\n\n\n\n\n\n\n\n\nfunc (c *SkipPlaylistCommand) Execute(user *gumble.User, args ...string) (string, bool, error) {\n\tvar (\n\t\tcurrentTrack interfaces.Track\n\t\terr error\n\t)\n\n\tif currentTrack, err = DJ.Queue.CurrentTrack(); err != nil {\n\t\treturn \"\", true, errors.New(viper.GetString(\"commands.common_messages.no_tracks_error\"))\n\t}\n\n\tif playlist := currentTrack.GetPlaylist(); playlist == nil {\n\t\treturn \"\", true, errors.New(viper.GetString(\"commands.skipplaylist.messages.no_playlist_error\"))\n\t}\n\tif currentTrack.GetPlaylist().GetSubmitter() == user.Name {\n\t\tDJ.Queue.SkipPlaylist()\n\t\treturn fmt.Sprintf(viper.GetString(\"commands.skipplaylist.messages.submitter_voted\"), user.Name), false, nil\n\t}\n\tif err := DJ.Skips.AddPlaylistSkip(user); err != nil {\n\t\treturn \"\", true, errors.New(viper.GetString(\"commands.skipplaylist.messages.already_voted_error\"))\n\t}\n\n\treturn fmt.Sprintf(viper.GetString(\"commands.skipplaylist.messages.voted\"), user.Name), false, nil\n}\n\nfunc (c *SkipPlaylistCommand) Aliases() []string ", "output": "{\n\treturn viper.GetStringSlice(\"commands.skipplaylist.aliases\")\n}"} {"input": "package credentials\n\nimport (\n\t\"strings\"\n\n\t\"github.com/docker/docker/cliconfig/configfile\"\n\t\"github.com/docker/engine-api/types\"\n)\n\n\n\ntype fileStore struct {\n\tfile *configfile.ConfigFile\n}\n\n\nfunc NewFileStore(file *configfile.ConfigFile) Store {\n\treturn &fileStore{\n\t\tfile: file,\n\t}\n}\n\n\nfunc (c *fileStore) Erase(serverAddress string) error {\n\tdelete(c.file.AuthConfigs, serverAddress)\n\treturn c.file.Save()\n}\n\n\n\n\nfunc (c *fileStore) GetAll() (map[string]types.AuthConfig, error) {\n\treturn c.file.AuthConfigs, nil\n}\n\n\nfunc (c *fileStore) Store(authConfig types.AuthConfig) error {\n\tc.file.AuthConfigs[authConfig.ServerAddress] = authConfig\n\treturn c.file.Save()\n}\n\nfunc convertToHostname(url string) string {\n\tstripped := url\n\tif strings.HasPrefix(url, \"http://\") {\n\t\tstripped = strings.Replace(url, \"http://\", \"\", 1)\n\t} else if strings.HasPrefix(url, \"https://\") {\n\t\tstripped = strings.Replace(url, \"https://\", \"\", 1)\n\t}\n\n\tnameParts := strings.SplitN(stripped, \"/\", 2)\n\n\treturn nameParts[0]\n}\n\nfunc (c *fileStore) Get(serverAddress string) (types.AuthConfig, error) ", "output": "{\n\tauthConfig, ok := c.file.AuthConfigs[serverAddress]\n\tif !ok {\n\t\tfor registry, ac := range c.file.AuthConfigs {\n\t\t\tif serverAddress == convertToHostname(registry) {\n\t\t\t\treturn ac, nil\n\t\t\t}\n\t\t}\n\n\t\tauthConfig = types.AuthConfig{}\n\t}\n\treturn authConfig, nil\n}"} {"input": "package windows\n\nimport (\n\t\"github.com/docker/libnetwork/driverapi\"\n\t\"github.com/docker/libnetwork/types\"\n)\n\nconst networkType = \"windows\"\n\n\n\ntype driver struct{}\n\n\nfunc Init(dc driverapi.DriverCallback) error {\n\tc := driverapi.Capability{\n\t\tScope: driverapi.LocalScope,\n\t}\n\treturn dc.RegisterDriver(networkType, &driver{}, c)\n}\n\nfunc (d *driver) Config(option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) DeleteNetwork(nid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) DeleteEndpoint(nid, eid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {\n\treturn make(map[string]interface{}, 0), nil\n}\n\n\nfunc (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {\n\treturn nil\n}\n\n\n\n\nfunc (d *driver) Type() string {\n\treturn networkType\n}\n\nfunc (d *driver) Leave(nid, eid types.UUID) error ", "output": "{\n\treturn nil\n}"} {"input": "package cf\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"time\"\n\n\tginkgoconfig \"github.com/onsi/ginkgo/config\"\n\n\t\"github.com/cloudfoundry-incubator/cf-test-helpers/runner\"\n)\n\nvar AsUser = func(userContext UserContext, timeout time.Duration, actions func()) {\n\toriginalCfHomeDir, currentCfHomeDir := InitiateUserContext(userContext, timeout)\n\tdefer func() {\n\t\tRestoreUserContext(userContext, timeout, originalCfHomeDir, currentCfHomeDir)\n\t}()\n\n\tTargetSpace(userContext, timeout)\n\n\tactions()\n}\n\n\n\nfunc TargetSpace(userContext UserContext, timeout time.Duration) {\n\tif userContext.Org != \"\" {\n\t\tif userContext.Space != \"\" {\n\t\t\trunner.NewCmdRunner(Cf(\"target\", \"-o\", userContext.Org, \"-s\", userContext.Space), timeout).Run()\n\t\t} else {\n\t\t\trunner.NewCmdRunner(Cf(\"target\", \"-o\", userContext.Org), timeout).Run()\n\t\t}\n\t}\n}\n\nfunc RestoreUserContext(_ UserContext, timeout time.Duration, originalCfHomeDir, currentCfHomeDir string) {\n\trunner.NewCmdRunner(Cf(\"logout\"), timeout).Run()\n\tos.Setenv(\"CF_HOME\", originalCfHomeDir)\n\tos.RemoveAll(currentCfHomeDir)\n}\n\nfunc InitiateUserContext(userContext UserContext, timeout time.Duration) (originalCfHomeDir, currentCfHomeDir string) ", "output": "{\n\toriginalCfHomeDir = os.Getenv(\"CF_HOME\")\n\tcurrentCfHomeDir, err := ioutil.TempDir(\"\", fmt.Sprintf(\"cf_home_%d\", ginkgoconfig.GinkgoConfig.ParallelNode))\n\n\tif err != nil {\n\t\tpanic(\"Error: could not create temporary home directory: \" + err.Error())\n\t}\n\n\tos.Setenv(\"CF_HOME\", currentCfHomeDir)\n\n\tcfSetApiArgs := []string{\"api\", userContext.ApiUrl}\n\tif userContext.SkipSSLValidation {\n\t\tcfSetApiArgs = append(cfSetApiArgs, \"--skip-ssl-validation\")\n\t}\n\n\trunner.NewCmdRunner(Cf(cfSetApiArgs...), timeout).Run()\n\n\trunner.NewCmdRunner(Cf(\"auth\", userContext.Username, userContext.Password), timeout).Run()\n\n\treturn\n}"} {"input": "package cpumanager\n\nimport (\n\t\"k8s.io/api/core/v1\"\n\t\"k8s.io/klog\"\n\t\"k8s.io/kubernetes/pkg/kubelet/cm/cpumanager/state\"\n\t\"k8s.io/kubernetes/pkg/kubelet/cm/topologymanager\"\n)\n\ntype nonePolicy struct{}\n\nvar _ Policy = &nonePolicy{}\n\n\nconst PolicyNone policyName = \"none\"\n\n\nfunc NewNonePolicy() Policy {\n\treturn &nonePolicy{}\n}\n\n\n\nfunc (p *nonePolicy) Start(s state.State) {\n\tklog.Info(\"[cpumanager] none policy: Start\")\n}\n\nfunc (p *nonePolicy) AddContainer(s state.State, pod *v1.Pod, container *v1.Container) error {\n\treturn nil\n}\n\nfunc (p *nonePolicy) RemoveContainer(s state.State, podUID string, containerName string) error {\n\treturn nil\n}\n\nfunc (p *nonePolicy) GetTopologyHints(s state.State, pod v1.Pod, container v1.Container) map[string][]topologymanager.TopologyHint {\n\treturn nil\n}\n\nfunc (p *nonePolicy) Name() string ", "output": "{\n\treturn string(PolicyNone)\n}"} {"input": "package config\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar (\n\tCurrent = Version{\n\t\tMajor: 0,\n\t\tMinor: 15,\n\t\tPatch: 1,\n\t}\n\n\tFirst = Version{\n\t\t0, 10, 4,\n\t}\n)\n\n\ntype Version struct {\n\tMajor int `json:\"major\"`\n\tMinor int `json:\"minor\"`\n\tPatch int `json:\"patch\"`\n}\n\n\n\n\n\nfunc (v Version) String() string {\n\treturn fmt.Sprintf(\"%d.%d.%d\", v.Major, v.Minor, v.Patch)\n}\n\n\nfunc (v Version) Greater(x Version) bool {\n\tif v.Major > x.Major {\n\t\treturn true\n\t}\n\n\tif v.Major == x.Major {\n\t\tif v.Minor > x.Minor {\n\t\t\treturn true\n\t\t}\n\n\t\tif v.Minor == x.Minor {\n\t\t\tif v.Patch > x.Patch {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\treturn false\n\t\t}\n\t\treturn false\n\t}\n\n\treturn false\n}\n\nfunc VersionFromString(s string) Version ", "output": "{\n\tvs := strings.Split(s, \".\")\n\n\tif len(vs) < 3 {\n\n\t\treturn First\n\t}\n\n\ttoInt := func(s string) int {\n\t\ti, err := strconv.Atoi(s)\n\t\tif err != nil {\n\t\t\treturn 0\n\t\t}\n\t\treturn i\n\t}\n\n\treturn Version{toInt(vs[0]), toInt(vs[1]), toInt(vs[2])}\n}"} {"input": "package main\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"os/exec\"\n\t\"text/template\"\n\n\t\"github.com/golang/glog\"\n\tk8sexec \"k8s.io/kubernetes/pkg/util/exec\"\n)\n\nconst (\n\tnsdTmpl = `\n`\n)\n\ntype record struct {\n\tname string\n\tip net.IP\n}\n\ntype nsd struct {\n\tns []record\n\ta []record\n}\n\n\n\nfunc (k *nsd) Start() {\n\tcmd := exec.Command(\"/usr/sbin/nsd\",\n\t\t\"-d\",\n\t\t\"-P\", \"/nsd.pid\")\n\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\tif err := cmd.Start(); err != nil {\n\t\tglog.Errorf(\"nsd error: %v\", err)\n\t}\n\n\tif err := cmd.Wait(); err != nil {\n\t\tglog.Fatalf(\"nsd error: %v\", err)\n\t}\n}\n\nfunc (k *nsd) Reload() error {\n\tglog.Info(\"reloading nsd server\")\n\t_, err := k8sexec.New().Command(\"killall\", \"-1\", \"nsd\").CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reloading nsd: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (k *nsd) WriteCfg(svcs []vip) error ", "output": "{\n\tw, err := os.Create(\"/etc/nsd/nsd.conf.\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer w.Close()\n\n\tt, err := template.New(\"nsd\").Parse(nsdTmpl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconf := make(map[string]interface{})\n\tconf[\"ns\"] = k.iface\n\tconf[\"a\"] = k.ip\n\n\tb, _ := json.Marshal(conf)\n\tglog.Infof(\"%v\", string(b))\n\n\treturn t.Execute(w, conf)\n}"} {"input": "package engine\n\nimport (\n\t\"time\"\n\n\t\"github.com/aws/amazon-ecs-agent/agent/api\"\n)\n\n\n\ntype impossibleTransitionError struct {\n\tstate api.ContainerStatus\n}\n\nfunc (err *impossibleTransitionError) Error() string {\n\treturn \"Cannot transition to \" + err.state.String()\n}\nfunc (err *impossibleTransitionError) ErrorName() string { return \"ImpossibleStateTransitionError\" }\n\ntype DockerTimeoutError struct {\n\tduration time.Duration\n\ttransition string\n}\n\nfunc (err *DockerTimeoutError) Error() string {\n\treturn \"Could not transition to \" + err.transition + \"; timed out after waiting \" + err.duration.String()\n}\nfunc (err *DockerTimeoutError) ErrorName() string { return \"DockerTimeoutError\" }\n\ntype ContainerVanishedError struct{}\n\nfunc (err ContainerVanishedError) Error() string { return \"No container matching saved ID found\" }\nfunc (err ContainerVanishedError) ErrorName() string { return \"ContainerVanishedError\" }\n\ntype CannotXContainerError struct {\n\ttransition string\n\tmsg string\n}\n\nfunc (err CannotXContainerError) Error() string { return err.msg }\nfunc (err CannotXContainerError) ErrorName() string {\n\treturn \"Cannot\" + err.transition + \"ContainerError\"\n}\n\ntype OutOfMemoryError struct{}\n\nfunc (err OutOfMemoryError) Error() string { return \"Container killed due to memory usage\" }\nfunc (err OutOfMemoryError) ErrorName() string { return \"OutOfMemoryError\" }\n\n\ntype DockerStateError struct {\n\tdockerError string\n\tname string\n}\n\n\n\nfunc (err DockerStateError) Error() string {\n\treturn err.dockerError\n}\nfunc (err DockerStateError) ErrorName() string {\n\treturn err.name\n}\n\nfunc NewDockerStateError(err string) DockerStateError ", "output": "{\n\treturn DockerStateError{\n\t\tdockerError: err,\n\t\tname: \"DockerStateError\",\n\t}\n}"} {"input": "package roles\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar TopLevelRoles = map[string]struct{}{\n\t\"root\": {},\n\t\"targets\": {},\n\t\"snapshot\": {},\n\t\"timestamp\": {},\n}\n\n\n\nfunc IsDelegatedTargetsRole(name string) bool {\n\treturn !IsTopLevelRole(name)\n}\n\nfunc IsTopLevelManifest(name string) bool {\n\treturn IsTopLevelRole(strings.TrimSuffix(name, \".json\"))\n}\n\nfunc IsDelegatedTargetsManifest(name string) bool {\n\treturn !IsTopLevelManifest(name)\n}\n\nfunc IsVersionedManifest(name string) bool {\n\tparts := strings.Split(name, \".\")\n\tif len(parts) < 3 {\n\t\treturn false\n\t}\n\n\t_, err := strconv.Atoi(parts[0])\n\treturn err == nil\n}\n\nfunc IsTopLevelRole(name string) bool ", "output": "{\n\t_, ok := TopLevelRoles[name]\n\treturn ok\n}"} {"input": "package iddispatcher\n\nimport \"fmt\"\n\ntype Dispatch struct {\n\tid chan int\n\tduringLoad chan int\n\tmaxValue int\n\tnowID int\n}\n\nconst idDefaultCount = 10\nconst idDefaultLoadCount = idDefaultCount\n\nconst idDefaultValue = 0\n\nfunc GetADispather(maxvalue int) Dispatcher {\n\tif maxvalue < 1 {\n\t\tpanic(fmt.Sprintf(\"error maxvalue: %v\", maxvalue))\n\t}\n\n\treturn &Dispatch{\n\t\tid: make(chan int, idDefaultCount),\n\t\tduringLoad: make(chan int, 1),\n\t\tmaxValue: maxvalue,\n\t\tnowID: idDefaultValue,\n\t}\n}\n\nfunc reloadIDs(dispatch *Dispatch) {\n\tif len(dispatch.id) > 0 {\n\t\treturn\n\t}\n\n\tdispatch.duringLoad <- 1\n\n\tif len(dispatch.id) > 0 {\n\t\t<-dispatch.duringLoad\n\t\treturn\n\t}\n\n\tfor i := 1; i <= idDefaultLoadCount; i++ {\n\t\tif dispatch.nowID > dispatch.maxValue {\n\t\t\tdispatch.nowID = idDefaultValue + 1\n\t\t} else {\n\t\t\tdispatch.nowID++\n\t\t}\n\n\t\tselect {\n\t\tcase dispatch.id <- dispatch.nowID:\n\t\tdefault:\n\t\t\t<-dispatch.duringLoad\n\t\t\treturn\n\t\t}\n\t}\n\t<-dispatch.duringLoad\n}\n\n\n\nfunc (patcher *Dispatch) GetID() int ", "output": "{\n\tif nil == patcher {\n\t\treturn -1\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase id := <-patcher.id:\n\t\t\treturn id\n\t\tdefault:\n\t\t\treloadIDs(patcher)\n\t\t}\n\t}\n}"} {"input": "package async\n\nimport (\n\t\"sync\"\n\t\"time\"\n)\n\ntype TTLCache interface {\n\tGet(key string) (value interface{}, expired bool, ok bool)\n\tSet(key string, value interface{})\n\tDelete(key string)\n}\n\n\n\n\ntype ttlCacheEntry struct {\n\tvalue interface{}\n\texpiry time.Time\n}\n\ntype ttlCache struct {\n\tmu sync.RWMutex\n\tcache map[string]*ttlCacheEntry\n\tttl time.Duration\n}\n\n\n\n\n\n\nfunc (t *ttlCache) Get(key string) (value interface{}, expired bool, ok bool) {\n\tt.mu.RLock()\n\tdefer t.mu.RUnlock()\n\tif _, iok := t.cache[key]; !iok {\n\t\treturn nil, false, false\n\t}\n\tentry := t.cache[key]\n\texpired = time.Now().After(entry.expiry)\n\treturn entry.value, expired, true\n}\n\n\nfunc (t *ttlCache) Set(key string, value interface{}) {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\tt.cache[key] = &ttlCacheEntry{\n\t\tvalue: value,\n\t\texpiry: time.Now().Add(t.ttl),\n\t}\n}\n\n\nfunc (t *ttlCache) Delete(key string) {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\tdelete(t.cache, key)\n}\n\nfunc NewTTLCache(ttl time.Duration) TTLCache ", "output": "{\n\treturn &ttlCache{\n\t\tttl: ttl,\n\t\tcache: make(map[string]*ttlCacheEntry),\n\t}\n}"} {"input": "package musicserver\n\nimport (\n\t\"net/http\"\n\t\"time\"\n)\n\nfunc adminHandler(w http.ResponseWriter, req *http.Request) {\n\tip := getIPFromRequest(req)\n\n\tif ad.ValidSession(ip) {\n\t\ttl.Render(w, \"admin\", newPlaylistInfo(ip))\n\t} else {\n\t\thttp.Redirect(w, req, url(\"/admin/login\"), http.StatusFound)\n\t}\n}\n\nfunc adminLoginHandler(w http.ResponseWriter, req *http.Request) {\n\tif req.Method != http.MethodPost {\n\t\ttl.Render(w, \"admin_login\", nil)\n\t\treturn\n\t}\n\n\tip := getIPFromRequest(req)\n\tpwd := req.PostFormValue(\"admin_pwd\")\n\tif ad.ValidPassword(pwd) {\n\t\tad.StartSession(ip)\n\t\thttp.Redirect(w, req, url(\"/admin\"), http.StatusSeeOther)\n\t\treturn\n\t} else {\n\t\ttl.Render(w, \"admin_bad_login\", nil)\n\t\treturn\n\t}\n}\n\nfunc adminLogoutHandler(w http.ResponseWriter, req *http.Request) {\n\tip := getIPFromRequest(req)\n\tad.EndSession(ip)\n\thttp.Redirect(w, req, url(\"/\"), http.StatusSeeOther)\n}\n\n\n\nfunc adminKillVideoHandler(w http.ResponseWriter, req *http.Request) {\n\tip := getIPFromRequest(req)\n\tif !ad.ValidSession(ip) {\n\t\thttp.Redirect(w, req, url(\"/admin/login\"), http.StatusFound)\n\t\treturn\n\t}\n\n\tvd.End()\n\ttime.Sleep(500 * time.Millisecond)\n\n\thttp.Redirect(w, req, url(\"/admin\"), http.StatusFound)\n}\n\nfunc adminRemoveHandler(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tip := getIPFromRequest(req)\n\tif req.Method == http.MethodPost && ad.ValidSession(ip) {\n\t\tremUUID := req.PostFormValue(\"video_id\")\n\t\tpl.RemoveVideo(remUUID)\n\t}\n\thttp.Redirect(w, req, url(\"/admin\"), http.StatusSeeOther)\n}"} {"input": "package lzma\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"unicode\"\n)\n\n\n\ntype operation interface {\n\tLen() int\n}\n\n\ntype match struct {\n\tdistance int64\n\tn int\n}\n\n\n\nfunc (m match) verify() error {\n\tif !(minDistance <= m.distance && m.distance <= maxDistance) {\n\t\treturn errors.New(\"distance out of range\")\n\t}\n\tif !(1 <= m.n && m.n <= maxMatchLen) {\n\t\treturn errors.New(\"length out of range\")\n\t}\n\treturn nil\n}\n\n\n\nfunc (m match) l() uint32 {\n\treturn uint32(m.n - minMatchLen)\n}\n\n\n\nfunc (m match) dist() uint32 {\n\treturn uint32(m.distance - minDistance)\n}\n\n\nfunc (m match) Len() int {\n\treturn m.n\n}\n\n\n\n\n\ntype lit struct {\n\tb byte\n}\n\n\nfunc (l lit) Len() int {\n\treturn 1\n}\n\n\nfunc (l lit) String() string {\n\tvar c byte\n\tif unicode.IsPrint(rune(l.b)) {\n\t\tc = l.b\n\t} else {\n\t\tc = '.'\n\t}\n\treturn fmt.Sprintf(\"L{%c/%02x}\", c, l.b)\n}\n\nfunc (m match) String() string ", "output": "{\n\treturn fmt.Sprintf(\"M{%d,%d}\", m.distance, m.n)\n}"} {"input": "package benchmarks\n\nimport (\n\t\"io/ioutil\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/go-kit/kit/log\"\n)\n\nfunc newKit() *log.Context {\n\treturn log.NewContext(log.NewJSONLogger(ioutil.Discard))\n}\n\nfunc BenchmarkGoKitAddingFields(b *testing.B) {\n\tlogger := newKit()\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tlogger.With(\n\t\t\t\t\"int\", 1,\n\t\t\t\t\"int64\", int64(1),\n\t\t\t\t\"float\", 3.0,\n\t\t\t\t\"string\", \"four!\",\n\t\t\t\t\"bool\", true,\n\t\t\t\t\"time\", time.Unix(0, 0),\n\t\t\t\t\"error\", errExample.Error(),\n\t\t\t\t\"duration\", time.Second,\n\t\t\t\t\"user-defined type\", _jane,\n\t\t\t\t\"another string\", \"done!\",\n\t\t\t).Log(\"Go fast.\")\n\t\t}\n\t})\n}\n\n\n\nfunc BenchmarkGoKitWithoutFields(b *testing.B) {\n\tlogger := newKit()\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tlogger.Log(\"Go fast.\")\n\t\t}\n\t})\n}\n\nfunc BenchmarkGoKitWithAccumulatedContext(b *testing.B) ", "output": "{\n\tlogger := newKit().With(\n\t\t\"int\", 1,\n\t\t\"int64\", int64(1),\n\t\t\"float\", 3.0,\n\t\t\"string\", \"four!\",\n\t\t\"bool\", true,\n\t\t\"time\", time.Unix(0, 0),\n\t\t\"error\", errExample.Error(),\n\t\t\"duration\", time.Second,\n\t\t\"user-defined type\", _jane,\n\t\t\"another string\", \"done!\",\n\t)\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tlogger.Log(\"Go really fast.\")\n\t\t}\n\t})\n}"} {"input": "package http\n\nimport (\n\t\"github.com/wcong/ants-go/ants/util\"\n\t\"log\"\n\tHttp \"net/http\"\n\t\"strconv\"\n\t\"sync\"\n)\n\ntype HttpServer struct {\n\tHttp.Server\n}\n\n\n\nfunc (this *HttpServer) Start(wg sync.WaitGroup) {\n\tgo this.server(wg)\n}\n\nfunc (this *HttpServer) server(wg sync.WaitGroup) {\n\tlog.Println(\"start to server http\" + this.Addr)\n\terr := this.ListenAndServe()\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tlog.Println(\"http server down\")\n\twg.Done()\n}\n\nfunc NewHttpServer(setting *util.Settings, handler Http.Handler) *HttpServer ", "output": "{\n\tport := strconv.Itoa(setting.HttpPort)\n\thttpServer := &HttpServer{\n\t\tHttp.Server{\n\t\t\tAddr: \":\" + port,\n\t\t\tHandler: handler,\n\t\t},\n\t}\n\treturn httpServer\n}"} {"input": "package server\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n\n\t\"github.com/kyokomi/expcache\"\n)\n\ntype ImageCache interface {\n\tGetRandomImageURL() string\n}\n\ntype imageCache struct {\n\tExpire expcache.ExpireOnMemoryCache\n\tcache []string\n\n\ttwAPI TwitterAPI\n\trd *rand.Rand\n\ttwitterID string\n\tcacheCnt int\n}\n\n\n\nfunc (c *imageCache) GetRandomImageURL() string {\n\tvar result string\n\tc.Expire.WithRefreshLock(time.Now(), func() {\n\t\tidx := c.rd.Int31n(int32(len(c.cache))) - 1\n\t\tresult = c.cache[idx]\n\t})\n\treturn result\n}\n\nfunc (c *imageCache) Refresh() error {\n\timages, err := c.twAPI.GetFavoritesImages(c.cacheCnt, c.twitterID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.cache = images\n\treturn nil\n}\n\nvar _ expcache.OnMemoryCache = (*imageCache)(nil)\nvar _ ImageCache = (*imageCache)(nil)\n\nfunc NewImageCache(twAPI TwitterAPI, twitterID string, cacheCnt int) ImageCache ", "output": "{\n\te := &imageCache{\n\t\tcache: []string{},\n\t\ttwAPI: twAPI,\n\t\trd: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t\ttwitterID: twitterID,\n\t\tcacheCnt: cacheCnt,\n\t}\n\te.Expire = expcache.NewExpireMemoryCache(e, 24*time.Hour)\n\treturn e\n}"} {"input": "package osenv\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n)\n\nconst (\n\tJujuEnv = \"JUJU_ENV\"\n\tJujuHome = \"JUJU_HOME\"\n\tJujuRepository = \"JUJU_REPOSITORY\"\n\tJujuLoggingConfig = \"JUJU_LOGGING_CONFIG\"\n\tJujuContainerType = \"JUJU_CONTAINER_TYPE\"\n)\n\n\n\n\n\nfunc jujuHomeLinux() string {\n\thome := Home()\n\tif home == \"\" {\n\t\treturn \"\"\n\t}\n\treturn filepath.Join(home, \".juju\")\n}\n\n\nfunc jujuHomeWin() string {\n\tappdata := os.Getenv(\"APPDATA\")\n\tif appdata == \"\" {\n\t\treturn \"\"\n\t}\n\treturn filepath.Join(appdata, \"Juju\")\n}\n\nfunc JujuHomeDir() string ", "output": "{\n\tjujuHome := os.Getenv(JujuHome)\n\tif jujuHome == \"\" {\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\tjujuHome = jujuHomeWin()\n\t\t} else {\n\t\t\tjujuHome = jujuHomeLinux()\n\t\t}\n\t}\n\treturn jujuHome\n}"} {"input": "package addrs\n\nimport \"fmt\"\n\n\n\n\n\n\n\n\n\n\n\ntype ResourceInstancePhase struct {\n\treferenceable\n\tResourceInstance ResourceInstance\n\tPhase ResourceInstancePhaseType\n}\n\nvar _ Referenceable = ResourceInstancePhase{}\n\n\n\n\nfunc (r ResourceInstance) Phase(rpt ResourceInstancePhaseType) ResourceInstancePhase {\n\treturn ResourceInstancePhase{\n\t\tResourceInstance: r,\n\t\tPhase: rpt,\n\t}\n}\n\n\n\nfunc (rp ResourceInstancePhase) ContainingResource() ResourcePhase {\n\treturn rp.ResourceInstance.Resource.Phase(rp.Phase)\n}\n\n\n\n\ntype ResourceInstancePhaseType string\n\nconst (\n\tResourceInstancePhaseDestroy ResourceInstancePhaseType = \"destroy\"\n\n\tResourceInstancePhaseDestroyCBD ResourceInstancePhaseType = \"destroy-cbd\"\n)\n\nfunc (rpt ResourceInstancePhaseType) String() string {\n\treturn string(rpt)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype ResourcePhase struct {\n\treferenceable\n\tResource Resource\n\tPhase ResourceInstancePhaseType\n}\n\nvar _ Referenceable = ResourcePhase{}\n\n\n\n\nfunc (r Resource) Phase(rpt ResourceInstancePhaseType) ResourcePhase {\n\treturn ResourcePhase{\n\t\tResource: r,\n\t\tPhase: rpt,\n\t}\n}\n\nfunc (rp ResourcePhase) String() string {\n\treturn fmt.Sprintf(\"%s#%s\", rp.Resource, rp.Phase)\n}\n\nfunc (rp ResourceInstancePhase) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%s#%s\", rp.ResourceInstance, rp.Phase)\n}"} {"input": "package goleveldb\n\nimport (\n\tstore \"github.com/blevesearch/upsidedown_store_api\"\n\t\"github.com/syndtr/goleveldb/leveldb\"\n)\n\ntype Batch struct {\n\tstore *Store\n\tmerge *store.EmulatedMerge\n\tbatch *leveldb.Batch\n}\n\nfunc (b *Batch) Set(key, val []byte) {\n\tb.batch.Put(key, val)\n}\n\nfunc (b *Batch) Delete(key []byte) {\n\tb.batch.Delete(key)\n}\n\nfunc (b *Batch) Merge(key, val []byte) {\n\tb.merge.Merge(key, val)\n}\n\nfunc (b *Batch) Reset() {\n\tb.batch.Reset()\n\tb.merge = store.NewEmulatedMerge(b.store.mo)\n}\n\n\n\nfunc (b *Batch) Close() error ", "output": "{\n\tb.batch.Reset()\n\tb.batch = nil\n\tb.merge = nil\n\treturn nil\n}"} {"input": "package fingerprint\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hashicorp/nomad/client/config\"\n\t\"github.com/hashicorp/nomad/helper/testlog\"\n\t\"github.com/hashicorp/nomad/nomad/structs\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestMemoryFingerprint_Override(t *testing.T) {\n\tf := NewMemoryFingerprint(testlog.HCLogger(t))\n\tnode := &structs.Node{\n\t\tAttributes: make(map[string]string),\n\t}\n\n\tmemoryMB := 15000\n\trequest := &FingerprintRequest{Config: &config.Config{MemoryMB: memoryMB}, Node: node}\n\tvar response FingerprintResponse\n\terr := f.Fingerprint(request, &response)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tassertNodeAttributeContains(t, response.Attributes, \"memory.totalbytes\")\n\trequire := require.New(t)\n\trequire.NotNil(response.Resources)\n\trequire.EqualValues(response.Resources.MemoryMB, memoryMB)\n\trequire.NotNil(response.NodeResources)\n\trequire.EqualValues(response.NodeResources.Memory.MemoryMB, memoryMB)\n}\n\nfunc TestMemoryFingerprint(t *testing.T) ", "output": "{\n\trequire := require.New(t)\n\n\tf := NewMemoryFingerprint(testlog.HCLogger(t))\n\tnode := &structs.Node{\n\t\tAttributes: make(map[string]string),\n\t}\n\n\trequest := &FingerprintRequest{Config: &config.Config{}, Node: node}\n\tvar response FingerprintResponse\n\terr := f.Fingerprint(request, &response)\n\trequire.NoError(err)\n\n\tassertNodeAttributeContains(t, response.Attributes, \"memory.totalbytes\")\n\trequire.NotNil(response.Resources, \"expected response Resources to not be nil\")\n\trequire.NotZero(response.Resources.MemoryMB, \"expected memory to be non-zero\")\n\trequire.NotNil(response.NodeResources, \"expected response NodeResources to not be nil\")\n\trequire.NotZero(response.NodeResources.Memory.MemoryMB, \"expected memory to be non-zero\")\n}"} {"input": "package keymanagement\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ImportKeyVersionRequest struct {\n\n\tKeyId *string `mandatory:\"true\" contributesTo:\"path\" name:\"keyId\"`\n\n\tImportKeyVersionDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ImportKeyVersionRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ImportKeyVersionRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ImportKeyVersionRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ImportKeyVersionRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ImportKeyVersionResponse struct {\n\n\tRawResponse *http.Response\n\n\tKeyVersion `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response ImportKeyVersionResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response ImportKeyVersionResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package yaml\n\nimport (\n\t\"github.com/pinpt/dialect/pkg\"\n\t\"github.com/pinpt/dialect/pkg/types\"\n)\n\ntype YAMLExaminer struct {\n}\n\nfunc (e *YAMLExaminer) Examine(language string, filename string, line *types.DialectLine) error {\n\tpkg.SingleSymbolProcessor(\"#\", line)\n\treturn nil\n}\n\n\n\nfunc init() {\n\ttypes.RegisterExaminer(\"YAML\", &YAMLExaminer{})\n}\n\nfunc (e *YAMLExaminer) NewExaminer() types.DialectExaminer ", "output": "{\n\tex := new(YAMLExaminer)\n\treturn ex\n}"} {"input": "package merkledag\n\nimport (\n\t\"context\"\n\n\tcid \"gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid\"\n\tipld \"gx/ipfs/QmR7TcHkR9nxkUorfi8XMTAMLUK7GiP64TWWBzY3aacc1o/go-ipld-format\"\n)\n\n\ntype ErrorService struct {\n\tErr error\n}\n\nvar _ ipld.DAGService = (*ErrorService)(nil)\n\n\nfunc (cs *ErrorService) Add(ctx context.Context, nd ipld.Node) error {\n\treturn cs.Err\n}\n\n\n\n\n\nfunc (cs *ErrorService) Get(ctx context.Context, c cid.Cid) (ipld.Node, error) {\n\treturn nil, cs.Err\n}\n\n\nfunc (cs *ErrorService) GetMany(ctx context.Context, cids []cid.Cid) <-chan *ipld.NodeOption {\n\tch := make(chan *ipld.NodeOption)\n\tclose(ch)\n\treturn ch\n}\n\n\nfunc (cs *ErrorService) Remove(ctx context.Context, c cid.Cid) error {\n\treturn cs.Err\n}\n\n\nfunc (cs *ErrorService) RemoveMany(ctx context.Context, cids []cid.Cid) error {\n\treturn cs.Err\n}\n\nfunc (cs *ErrorService) AddMany(ctx context.Context, nds []ipld.Node) error ", "output": "{\n\treturn cs.Err\n}"} {"input": "package v1\n\nimport (\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\trest \"k8s.io/client-go/rest\"\n\tv1 \"k8s.io/code-generator/_examples/crd/apis/example/v1\"\n\t\"k8s.io/code-generator/_examples/crd/clientset/versioned/scheme\"\n)\n\ntype ExampleV1Interface interface {\n\tRESTClient() rest.Interface\n\tTestTypesGetter\n}\n\n\ntype ExampleV1Client struct {\n\trestClient rest.Interface\n}\n\n\n\n\nfunc NewForConfig(c *rest.Config) (*ExampleV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ExampleV1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *ExampleV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *ExampleV1Client {\n\treturn &ExampleV1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *ExampleV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc (c *ExampleV1Client) TestTypes(namespace string) TestTypeInterface ", "output": "{\n\treturn newTestTypes(c, namespace)\n}"} {"input": "package database\n\nimport (\n\t\"github.com/sacloud/libsacloud/v2/helper/validate\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\ntype BootRequest struct {\n\tZone string `request:\"-\" validate:\"required\"`\n\tID types.ID `request:\"-\" validate:\"required\"`\n\n\tNoWait bool `request:\"-\"`\n}\n\n\n\nfunc (req *BootRequest) Validate() error ", "output": "{\n\treturn validate.Struct(req)\n}"} {"input": "package gospell\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\ntype Match struct {\n\tWord []rune\n\tDistance int\n\tWeight int\n}\n\ntype Matches []Match\n\n\n\nfunc (m Match) String() string {\n\treturn fmt.Sprintf(\"{%v %d %d}\", string(m.Word), m.Distance, m.Weight)\n}\n\nfunc (s Matches) Len() int { return len(s) }\nfunc (s Matches) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\n\nfunc (s Matches) Strings() []string {\n\tstrings := make([]string, len(s))\n\tsort.Sort(ByDistance{s})\n\tfor i, r := range s {\n\t\tstrings[i] = string(r.Word)\n\t}\n\n\treturn strings\n}\n\ntype ByDistance struct {\n\tMatches\n}\n\nfunc (s ByDistance) Less(i, j int) bool {\n\td1 := s.Matches[i].Distance\n\td2 := s.Matches[j].Distance\n\tif d1 == d2 {\n\t\treturn string(s.Matches[i].Word) < string(s.Matches[j].Word)\n\t}\n\treturn d1 < d2\n}\n\nfunc (m *Match) update(r rune, distance, weight int) Match {\n\tm2 := Match{}\n\tif r != 0 {\n\t\tm2.Word = []rune{r}\n\t\tm2.Word = append(m2.Word, m.Word...)\n\t} else {\n\t\tm2.Word = m.Word[:]\n\t}\n\tm2.Distance = m.Distance + distance\n\tm2.Weight = m.Weight + weight\n\treturn m2\n}\n\nfunc (m1 Match) Equal(m2 Match) bool ", "output": "{\n\treturn string(m1.Word) == string(m2.Word) &&\n\t\tm1.Distance == m2.Distance && m1.Weight == m2.Weight\n}"} {"input": "package storage\n\nimport (\n\t\"path/filepath\"\n\n\t\"github.com/juju/errors\"\n)\n\nconst (\n\tdiskByUUID = \"/dev/disk/by-uuid\"\n\tdiskByLabel = \"/dev/disk/by-label\"\n)\n\n\n\n\n\n\n\n\nfunc BlockDevicePath(device BlockDevice) (string, error) ", "output": "{\n\tif device.Label != \"\" {\n\t\treturn filepath.Join(diskByLabel, device.Label), nil\n\t}\n\tif device.UUID != \"\" {\n\t\treturn filepath.Join(diskByUUID, device.UUID), nil\n\t}\n\tif device.DeviceName != \"\" {\n\t\treturn filepath.Join(\"/dev\", device.DeviceName), nil\n\t}\n\treturn \"\", errors.Errorf(\"could not determine path for block device %q\", device.Name)\n}"} {"input": "package model\n\nimport (\n\t\"math\"\n\t\"strconv\"\n\n\tnative_time \"time\"\n)\n\n\n\ntype Timestamp int64\n\nconst (\n\tMinimumTick = native_time.Millisecond\n\tsecond = int64(native_time.Second / MinimumTick)\n\tnanosPerTick = int64(MinimumTick / native_time.Nanosecond)\n\n\tEarliest = Timestamp(math.MinInt64)\n\tLatest = Timestamp(math.MaxInt64)\n)\n\n\nfunc (t Timestamp) Equal(o Timestamp) bool {\n\treturn t == o\n}\n\n\nfunc (t Timestamp) Before(o Timestamp) bool {\n\treturn t < o\n}\n\n\nfunc (t Timestamp) After(o Timestamp) bool {\n\treturn t > o\n}\n\n\nfunc (t Timestamp) Add(d native_time.Duration) Timestamp {\n\treturn t + Timestamp(d/MinimumTick)\n}\n\n\nfunc (t Timestamp) Sub(o Timestamp) native_time.Duration {\n\treturn native_time.Duration(t-o) * MinimumTick\n}\n\n\n\n\n\n\nfunc (t Timestamp) Unix() int64 {\n\treturn int64(t) / second\n}\n\n\n\nfunc (t Timestamp) UnixNano() int64 {\n\treturn int64(t) * nanosPerTick\n}\n\n\nfunc (t Timestamp) String() string {\n\treturn strconv.FormatFloat(float64(t)/float64(second), 'f', -1, 64)\n}\n\n\nfunc (t Timestamp) MarshalJSON() ([]byte, error) {\n\treturn []byte(t.String()), nil\n}\n\n\nfunc Now() Timestamp {\n\treturn TimestampFromTime(native_time.Now())\n}\n\n\nfunc TimestampFromTime(t native_time.Time) Timestamp {\n\treturn TimestampFromUnixNano(t.UnixNano())\n}\n\n\n\nfunc TimestampFromUnix(t int64) Timestamp {\n\treturn Timestamp(t * second)\n}\n\n\n\nfunc TimestampFromUnixNano(t int64) Timestamp {\n\treturn Timestamp(t / nanosPerTick)\n}\n\nfunc (t Timestamp) Time() native_time.Time ", "output": "{\n\treturn native_time.Unix(int64(t)/second, (int64(t)%second)*nanosPerTick)\n}"} {"input": "package aws\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/resource\"\n)\n\n\n\nfunc TestAccAWSELB_importBasic(t *testing.T) ", "output": "{\n\tresourceName := \"aws_elb.bar\"\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSELBDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSELBConfig,\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tResourceName: resourceName,\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}"} {"input": "package sha512\n\nimport \"crypto/sha512\"\n\nconst (\n\tSize = 64\n\n\tSize224 = 28\n\n\tSize256 = 32\n\n\tSize384 = 48\n\n\tBlockSize = 128\n)\n\n\n\n\n\nfunc Sum384(data []byte) (sum384 []byte) {\n\ta := sha512.Sum384(data)\n\treturn a[:]\n}\n\n\nfunc Sum512_224(data []byte) (sum224 []byte) {\n\ta := sha512.Sum512_224(data)\n\treturn a[:]\n}\n\n\nfunc Sum512_256(data []byte) (sum256 []byte) {\n\ta := sha512.Sum512_256(data)\n\treturn a[:]\n}\n\nfunc Sum512(data []byte) []byte ", "output": "{\n\ta := sha512.Sum512(data)\n\treturn a[:]\n}"} {"input": "package migrations\n\nimport (\n\t\"context\"\n\n\t\"github.com/fnproject/fn/api/datastore/sql/migratex\"\n\t\"github.com/jmoiron/sqlx\"\n)\n\n\n\nfunc down6(ctx context.Context, tx *sqlx.Tx) error {\n\t_, err := tx.ExecContext(ctx, \"ALTER TABLE apps DROP COLUMN updated_at;\")\n\treturn err\n}\n\nfunc init() {\n\tMigrations = append(Migrations, &migratex.MigFields{\n\t\tVersionFunc: vfunc(6),\n\t\tUpFunc: up6,\n\t\tDownFunc: down6,\n\t})\n}\n\nfunc up6(ctx context.Context, tx *sqlx.Tx) error ", "output": "{\n\t_, err := tx.ExecContext(ctx, \"ALTER TABLE apps ADD updated_at VARCHAR(256);\")\n\treturn err\n}"} {"input": "package value\n\nimport (\n\t\"bytes\"\n)\n\n\n\n\n\nfunc Cons(x, y Value) *Cell {\n\treturn &Cell{Car: x, Cdr: y}\n}\n\n\ntype Cell struct {\n\tCar Value\n\tCdr Value\n}\n\n\nfunc (c *Cell) Walk(fn func(Value)) {\n\tcur := c\n\tfor {\n\t\tfn(cur.Car)\n\n\t\tif cur.Cdr == NIL {\n\t\t\treturn\n\t\t}\n\n\t\tnext, ok := cur.Cdr.(*Cell)\n\t\tif !ok {\n\t\t\tErrorf(\"cannot evaluate an improper list: %s\", c)\n\t\t}\n\t\tcur = next\n\t}\n}\n\n\n\nfunc (c *Cell) String() string {\n\tvar buf bytes.Buffer\n\n\tbuf.WriteByte('(')\n\tfor {\n\t\tbuf.WriteString(c.Car.String())\n\n\t\tif c.Cdr == NIL {\n\t\t\tbreak\n\t\t}\n\n\t\tcdr, ok := c.Cdr.(*Cell)\n\t\tif !ok {\n\t\t\tbuf.WriteString(\" . \")\n\t\t\tbuf.WriteString(c.Cdr.String())\n\t\t\tbreak\n\t\t}\n\t\tc = cdr \n\n\t\tbuf.WriteByte(' ')\n\t}\n\tbuf.WriteByte(')')\n\n\treturn buf.String()\n}\n\nfunc (c *Cell) Equal(cmp Value) Value ", "output": "{\n\tx, ok := cmp.(*Cell)\n\tif !ok {\n\t\treturn NIL\n\t}\n\n\tif c.Car.Equal(x.Car) != T {\n\t\treturn NIL\n\t}\n\tif c.Cdr.Equal(x.Cdr) != T {\n\t\treturn NIL\n\t}\n\treturn T\n}"} {"input": "package protocol\n\n\ntype LogoutRequestMessageData struct {\n}\n\n\ntype LogoutRequestMessage struct {\n\tBaseMessage\n\tData LogoutRequestMessageData `json:\"data\"`\n}\n\n\nfunc NewLogoutRequesMessage(session string) *LogoutRequestMessage {\n\tmessage := LogoutRequestMessage{}\n\tmessage.Type = LogoutRequestMessageType\n\tmessage.Session = session\n\treturn &message\n}\n\n\nfunc (m *LogoutRequestMessage) GetType() string {\n\treturn m.Type\n}\n\n\nfunc (m *LogoutRequestMessage) GetSession() string {\n\treturn m.Session\n}\n\n\n\n\n\nfunc (m *LogoutRequestMessage) SetSession(session string) {\n\tm.BaseMessage.Session = session\n}\n\nfunc (m *LogoutRequestMessage) GetData() interface{} ", "output": "{\n\treturn m.Data\n}"} {"input": "package temperature\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/pelletier/go-toml\"\n\t\"github.com/rumpelsepp/i3gostatus/lib/config\"\n\t\"github.com/rumpelsepp/i3gostatus/lib/model\"\n)\n\nconst (\n\tname = \"temperature\"\n\tmoduleName = \"i3gostatus.modules.\" + name\n\tdefaultPeriod = 5000\n\tdefaultFormat = \"%d°C\"\n\tdefaultUrgentTemp = 70\n\tdefaultUrgentColor = \"#FF0000\"\n)\n\ntype Config struct {\n\tmodel.BaseConfig\n\tUrgentTemp int\n\tUrgentColor string\n}\n\nfunc (c *Config) ParseConfig(configTree *toml.TomlTree) {\n\tc.BaseConfig.Parse(name, configTree)\n\tc.BaseConfig.Period = config.GetDurationMs(configTree, c.Name+\".period\", defaultPeriod)\n\tc.Format = config.GetString(configTree, name+\".format\", defaultFormat)\n\tc.UrgentTemp = config.GetInt(configTree, name+\".urgent_temp\", defaultUrgentTemp)\n\tc.UrgentColor = config.GetString(configTree, name+\".urgent_color\", defaultUrgentColor)\n}\n\n\n\nfunc (c *Config) Run(args *model.ModuleArgs) ", "output": "{\n\tvar (\n\t\toutputBlock *model.I3BarBlock\n\t\ttemperature int\n\t\tthermalFile = \"/sys/class/thermal/thermal_zone0/temp\"\n\t)\n\n\tfor range time.NewTicker(c.Period).C {\n\t\toutputBlock = model.NewBlock(moduleName, c.BaseConfig, args.Index)\n\t\tdata, err := ioutil.ReadFile(thermalFile)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tdataStr := strings.TrimSpace(string(data))\n\n\t\tif t, err := strconv.Atoi(dataStr); err == nil {\n\t\t\ttemperature = int(t / 1000)\n\t\t\tif temperature >= c.UrgentTemp {\n\t\t\t\toutputBlock.Urgent = true\n\t\t\t\toutputBlock.Color = c.UrgentColor\n\t\t\t}\n\t\t}\n\n\t\toutputBlock.FullText = fmt.Sprintf(c.Format, temperature)\n\t\targs.OutCh <- outputBlock\n\t}\n}"} {"input": "package precis\n\nimport (\n\t\"unicode\"\n\t\"unicode/utf8\"\n\n\t\"golang.org/x/text/transform\"\n)\n\ntype nickAdditionalMapping struct {\n\tnotStart bool\n\tprevSpace bool\n}\n\n\n\nfunc (t *nickAdditionalMapping) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {\n\tfor nSrc < len(src) {\n\t\tr, size := utf8.DecodeRune(src[nSrc:])\n\t\tif size == 0 { \n\t\t\tif !atEOF {\n\t\t\t\treturn nDst, nSrc, transform.ErrShortSrc\n\t\t\t}\n\t\t\tsize = 1\n\t\t}\n\t\tif unicode.Is(unicode.Zs, r) {\n\t\t\tt.prevSpace = true\n\t\t} else {\n\t\t\tif t.prevSpace && t.notStart {\n\t\t\t\tdst[nDst] = ' '\n\t\t\t\tnDst += 1\n\t\t\t}\n\t\t\tif size != copy(dst[nDst:], src[nSrc:nSrc+size]) {\n\t\t\t\tnDst += size\n\t\t\t\treturn nDst, nSrc, transform.ErrShortDst\n\t\t\t}\n\t\t\tnDst += size\n\t\t\tt.prevSpace = false\n\t\t\tt.notStart = true\n\t\t}\n\t\tnSrc += size\n\t}\n\treturn nDst, nSrc, nil\n}\n\nfunc (t *nickAdditionalMapping) Reset() ", "output": "{\n\tt.prevSpace = false\n\tt.notStart = false\n}"} {"input": "package consul\n\nimport (\n\t\"log\"\n\n\t\"github.com/armon/consul-api\"\n\t\"github.com/hashicorp/terraform/helper/config\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\ntype ResourceProvider struct {\n\tConfig Config\n\tclient *consulapi.Client\n}\n\nfunc (p *ResourceProvider) Validate(c *terraform.ResourceConfig) ([]string, []error) {\n\tv := &config.Validator{\n\t\tOptional: []string{\n\t\t\t\"datacenter\",\n\t\t\t\"address\",\n\t\t},\n\t}\n\treturn v.Validate(c)\n}\n\nfunc (p *ResourceProvider) ValidateResource(\n\tt string, c *terraform.ResourceConfig) ([]string, []error) {\n\treturn resourceMap.Validate(t, c)\n}\n\nfunc (p *ResourceProvider) Configure(c *terraform.ResourceConfig) error {\n\tif _, err := config.Decode(&p.Config, c.Config); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[INFO] Initializing Consul client\")\n\tvar err error\n\tp.client, err = p.Config.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (p *ResourceProvider) Apply(\n\ts *terraform.ResourceState,\n\td *terraform.ResourceDiff) (*terraform.ResourceState, error) {\n\treturn resourceMap.Apply(s, d, p)\n}\n\nfunc (p *ResourceProvider) Diff(\n\ts *terraform.ResourceState,\n\tc *terraform.ResourceConfig) (*terraform.ResourceDiff, error) {\n\treturn resourceMap.Diff(s, c, p)\n}\n\nfunc (p *ResourceProvider) Refresh(\n\ts *terraform.ResourceState) (*terraform.ResourceState, error) {\n\treturn resourceMap.Refresh(s, p)\n}\n\n\n\nfunc (p *ResourceProvider) Resources() []terraform.ResourceType ", "output": "{\n\treturn resourceMap.Resources()\n}"} {"input": "package v1alpha1\n\nimport (\n\tv1alpha1 \"k8s.io/api/scheduling/v1alpha1\"\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\t\"github.com/hyperhq/client-go/kubernetes/scheme\"\n\trest \"github.com/hyperhq/client-go/rest\"\n)\n\ntype SchedulingV1alpha1Interface interface {\n\tRESTClient() rest.Interface\n\tPriorityClassesGetter\n}\n\n\ntype SchedulingV1alpha1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *SchedulingV1alpha1Client) PriorityClasses() PriorityClassInterface {\n\treturn newPriorityClasses(c)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*SchedulingV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SchedulingV1alpha1Client{client}, nil\n}\n\n\n\n\n\n\nfunc New(c rest.Interface) *SchedulingV1alpha1Client {\n\treturn &SchedulingV1alpha1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *SchedulingV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfigOrDie(c *rest.Config) *SchedulingV1alpha1Client ", "output": "{\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}"} {"input": "package figure\n\nimport (\n \"fmt\"\n \"log\"\n \"net/http\"\n \"strconv\"\n \"strings\"\n)\n\nconst signature = \"flf2\"\nconst reverseFlag = \"1\"\nvar charDelimiters = [3]string{\"@\", \"#\", \"$\"}\nvar hardblanksBlacklist = [2]byte{'a', '2'}\n\nfunc getFile(name string) (file http.File) {\n filePath := fmt.Sprintf(\"%s.flf\", name)\n file, err := AssetFS().Open(filePath)\n if err != nil {\n log.Fatalf(\"invalid font name:%s.\",err)\n }\n return file\n}\n\nfunc getHeight(metadata string) int {\n datum := strings.Fields(metadata)[1]\n height, _ := strconv.Atoi(datum)\n return height\n}\n\nfunc getBaseline(metadata string) int {\n datum := strings.Fields(metadata)[2]\n baseline, _ := strconv.Atoi(datum)\n return baseline\n}\n\nfunc getHardblank(metadata string) byte {\n datum := strings.Fields(metadata)[0]\n hardblank := datum[len(datum)-1]\n if hardblank == hardblanksBlacklist[0] || hardblank == hardblanksBlacklist[1] {\n return ' '\n } else {\n return hardblank\n }\n}\n\n\n\nfunc lastCharLine(text string, height int) bool {\n endOfLine, length := \" \", 2\n if height == 1 && len(text) > 0 {\n length = 1\n }\n if len(text) >= length {\n endOfLine = text[len(text)-length:]\n }\n return endOfLine == strings.Repeat(charDelimiters[0], length) ||\n endOfLine == strings.Repeat(charDelimiters[1], length) ||\n endOfLine == strings.Repeat(charDelimiters[2], length)\n}\n\nfunc getReverse(metadata string) bool ", "output": "{\n data := strings.Fields(metadata)\n return len(data) > 6 && data[6] == reverseFlag\n}"} {"input": "package dao\n\nimport (\n\t\"context\"\n\n\t\"go-common/library/cache/redis\"\n\t\"go-common/library/log\"\n)\n\nconst (\n\t_taskJobKey = \"task_job\"\n)\n\n\nfunc (d *Dao) SetnxTaskJob(c context.Context, value string) (ok bool, err error) {\n\tvar (\n\t\tconn = d.dmRds.Get(c)\n\t)\n\tdefer conn.Close()\n\tif ok, err = redis.Bool(conn.Do(\"SETNX\", _taskJobKey, value)); err != nil {\n\t\tlog.Error(\"d.SetnxMask(value:%s),error(%v)\", value, err)\n\t\treturn\n\t}\n\treturn\n}\n\n\n\n\n\nfunc (d *Dao) GetSetTaskJob(c context.Context, value string) (old string, err error) {\n\tvar (\n\t\tconn = d.dmRds.Get(c)\n\t)\n\tdefer conn.Close()\n\tif old, err = redis.String(conn.Do(\"GETSET\", _taskJobKey, value)); err != nil {\n\t\tlog.Error(\"d.GetSetTaskJob(value:%s),error(%v)\", value, err)\n\t\treturn\n\t}\n\treturn\n}\n\n\nfunc (d *Dao) DelTaskJob(c context.Context) (err error) {\n\tvar (\n\t\tconn = d.dmRds.Get(c)\n\t)\n\tdefer conn.Close()\n\tif _, err = conn.Do(\"DEL\", _taskJobKey); err != nil {\n\t\tlog.Error(\"d.DelTaskJob,error(%v)\", err)\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (d *Dao) GetTaskJob(c context.Context) (value string, err error) ", "output": "{\n\tvar (\n\t\tconn = d.dmRds.Get(c)\n\t)\n\tdefer conn.Close()\n\tif value, err = redis.String(conn.Do(\"GET\", _taskJobKey)); err != nil {\n\t\tlog.Error(\"d.GetMaskJob,error(%v)\", err)\n\t\treturn\n\t}\n\treturn\n}"} {"input": "package daemon\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime/middleware\"\n)\n\n\ntype GetHealthzHandlerFunc func(GetHealthzParams) middleware.Responder\n\n\nfunc (fn GetHealthzHandlerFunc) Handle(params GetHealthzParams) middleware.Responder {\n\treturn fn(params)\n}\n\n\ntype GetHealthzHandler interface {\n\tHandle(GetHealthzParams) middleware.Responder\n}\n\n\nfunc NewGetHealthz(ctx *middleware.Context, handler GetHealthzHandler) *GetHealthz {\n\treturn &GetHealthz{Context: ctx, Handler: handler}\n}\n\n\ntype GetHealthz struct {\n\tContext *middleware.Context\n\tHandler GetHealthzHandler\n}\n\n\n\nfunc (o *GetHealthz) ServeHTTP(rw http.ResponseWriter, r *http.Request) ", "output": "{\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\tr = rCtx\n\t}\n\tvar Params = NewGetHealthzParams()\n\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params) \n\n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}"} {"input": "package collaboration\n\nimport \"sync\"\n\nfunc NewMemoryStorage() *memoryStorage {\n\treturn &memoryStorage{\n\t\tusers: make(map[string]*Option),\n\t}\n}\n\n\ntype memoryStorage struct {\n\tusers map[string]*Option\n\tsync.Mutex\n}\n\nfunc (m *memoryStorage) Get(username string) (*Option, error) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\toption, ok := m.users[username]\n\tif !ok {\n\t\treturn nil, ErrUserNotFound\n\t}\n\n\treturn option, nil\n}\n\nfunc (m *memoryStorage) GetAll() (map[string]*Option, error) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\treturn m.users, nil\n}\n\n\n\nfunc (m *memoryStorage) Delete(username string) error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tdelete(m.users, username)\n\treturn nil\n}\n\nfunc (m *memoryStorage) Close() error {\n\treturn nil\n}\n\nfunc (m *memoryStorage) Set(username string, value *Option) error ", "output": "{\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tm.users[username] = value\n\treturn nil\n}"} {"input": "package fake\n\nimport (\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n\n\taction \"github.com/vmware-tanzu/octant/pkg/action\"\n)\n\n\ntype MockActionRegistrar struct {\n\tctrl *gomock.Controller\n\trecorder *MockActionRegistrarMockRecorder\n}\n\n\ntype MockActionRegistrarMockRecorder struct {\n\tmock *MockActionRegistrar\n}\n\n\nfunc NewMockActionRegistrar(ctrl *gomock.Controller) *MockActionRegistrar {\n\tmock := &MockActionRegistrar{ctrl: ctrl}\n\tmock.recorder = &MockActionRegistrarMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockActionRegistrar) EXPECT() *MockActionRegistrarMockRecorder {\n\treturn m.recorder\n}\n\n\nfunc (m *MockActionRegistrar) Register(arg0, arg1 string, arg2 action.DispatcherFunc) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Register\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}\n\n\nfunc (mr *MockActionRegistrarMockRecorder) Register(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Register\", reflect.TypeOf((*MockActionRegistrar)(nil).Register), arg0, arg1, arg2)\n}\n\n\n\n\n\nfunc (mr *MockActionRegistrarMockRecorder) Unregister(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Unregister\", reflect.TypeOf((*MockActionRegistrar)(nil).Unregister), arg0, arg1)\n}\n\nfunc (m *MockActionRegistrar) Unregister(arg0, arg1 string) ", "output": "{\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Unregister\", arg0, arg1)\n}"} {"input": "package sw\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/sha256\"\n\t\"crypto/x509\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/hyperledger/fabric/bccsp\"\n)\n\n\n\n\n\n\ntype rsaPublicKey struct{ pubKey *rsa.PublicKey }\n\n\nfunc (k *rsaPublicKey) Private() bool { return false }\nfunc (k *rsaPublicKey) PublicKey() (bccsp.Key, error) { return k, nil }\n\n\nfunc (k *rsaPublicKey) Bytes() (raw []byte, err error) {\n\tif k.pubKey == nil {\n\t\treturn nil, errors.New(\"Failed marshalling key. Key is nil.\")\n\t}\n\traw, err = x509.MarshalPKIXPublicKey(k.pubKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed marshalling key [%s]\", err)\n\t}\n\treturn\n}\n\n\nfunc (k *rsaPublicKey) SKI() []byte {\n\tif k.pubKey == nil {\n\t\treturn nil\n\t}\n\n\traw := x509.MarshalPKCS1PublicKey(k.pubKey)\n\thash := sha256.Sum256(raw)\n\treturn hash[:]\n}\n\nfunc (k *rsaPublicKey) Symmetric() bool ", "output": "{ return false }"} {"input": "package main\n\nimport \"bufio\"\nimport \"log\"\nimport \"strings\"\n\n\n\nfunc ScanGit(options ParserOptions, otherArgs string) Commits ", "output": "{\n\tcommits := make(Commits, 0)\n\targs := strings.Split(otherArgs, \" \")\n\tlogArgs := append(options.GitArgs, args...)\n\tcmd := ExecGit(logArgs...)\n\n\tdata, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ts := bufio.NewScanner(data)\n\ts.Split(options.SplitFunc)\n\n\tif err := cmd.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor s.Scan() {\n\t\tcommits = append(commits, options.CommitParser(s.Text()))\n\t}\n\n\tif err := s.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcmd.Wait()\n\n\treturn commits\n}"} {"input": "package utils\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\n\n\n\n\nfunc AskForConfirmation(s string) bool {\n\treader := bufio.NewReader(os.Stdin)\n\n\tfor {\n\t\tfmt.Printf(\"%s [y/n]: \", s)\n\n\t\tresponse, err := reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\texitWithError(err)\n\t\t}\n\n\t\tresponse = strings.ToLower(strings.TrimSpace(response))\n\n\t\tif response == \"y\" || response == \"yes\" {\n\t\t\treturn true\n\t\t} else if response == \"n\" || response == \"no\" {\n\t\t\treturn false\n\t\t}\n\t}\n}\n\n\n\n\n\nfunc exitWithError(err error) ", "output": "{\n\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\tos.Exit(1)\n}"} {"input": "package structs\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nconst (\n\tDefaultUnpriviledgedUser = \"nobody\"\n\n\tCheckBufSize = 4 * 1024\n)\n\n\ntype WaitResult struct {\n\tExitCode int\n\tSignal int\n\tErr error\n}\n\nfunc NewWaitResult(code, signal int, err error) *WaitResult {\n\treturn &WaitResult{\n\t\tExitCode: code,\n\t\tSignal: signal,\n\t\tErr: err,\n\t}\n}\n\nfunc (r *WaitResult) Successful() bool {\n\treturn r.ExitCode == 0 && r.Signal == 0 && r.Err == nil\n}\n\nfunc (r *WaitResult) String() string {\n\treturn fmt.Sprintf(\"Wait returned exit code %v, signal %v, and error %v\",\n\t\tr.ExitCode, r.Signal, r.Err)\n}\n\n\n\ntype RecoverableError struct {\n\tErr error\n\tRecoverable bool\n}\n\n\n\nfunc NewRecoverableError(e error, recoverable bool) *RecoverableError {\n\treturn &RecoverableError{\n\t\tErr: e,\n\t\tRecoverable: recoverable,\n\t}\n}\n\n\n\n\ntype CheckResult struct {\n\n\tExitCode int\n\n\tOutput string\n\n\tTimestamp time.Time\n\n\tDuration time.Duration\n\n\tErr error\n}\n\nfunc (r *RecoverableError) Error() string ", "output": "{\n\treturn r.Err.Error()\n}"} {"input": "package chshare\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\n\ntype Logger struct {\n\tprefix string\n\tlogger *log.Logger\n\tInfo, Debug bool\n}\n\nfunc NewLogger(prefix string) *Logger {\n\treturn NewLoggerFlag(prefix, log.Ldate|log.Ltime)\n}\n\nfunc NewLoggerFlag(prefix string, flag int) *Logger {\n\tl := &Logger{\n\t\tprefix: prefix,\n\t\tlogger: log.New(os.Stdout, \"\", flag),\n\t\tInfo: false,\n\t\tDebug: false,\n\t}\n\treturn l\n}\n\nfunc (l *Logger) Infof(f string, args ...interface{}) {\n\tif l.Info {\n\t\tl.logger.Printf(l.prefix+\": \"+f, args...)\n\t}\n}\n\nfunc (l *Logger) Debugf(f string, args ...interface{}) {\n\tif l.Debug {\n\t\tl.logger.Printf(l.prefix+\": \"+f, args...)\n\t}\n}\n\nfunc (l *Logger) Errorf(f string, args ...interface{}) error {\n\treturn fmt.Errorf(l.prefix+\": \"+f, args...)\n}\n\nfunc (l *Logger) Fork(prefix string, args ...interface{}) *Logger {\n\targs = append([]interface{}{l.prefix}, args...)\n\tll := NewLogger(fmt.Sprintf(\"%s: \"+prefix, args...))\n\tll.Info = l.Info\n\tll.Debug = l.Debug\n\treturn ll\n}\n\n\n\nfunc (l *Logger) Prefix() string ", "output": "{\n\treturn l.prefix\n}"} {"input": "package header\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/google/martian/v3/proxyutil\"\n)\n\n\n\ntype Matcher struct {\n\tname, value string\n}\n\n\n\n\n\n\n\nfunc (m *Matcher) MatchRequest(req *http.Request) bool {\n\th := proxyutil.RequestHeader(req)\n\n\tvs, ok := h.All(m.name)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tfor _, v := range vs {\n\t\tif v == m.value {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\n\n\nfunc (m *Matcher) MatchResponse(res *http.Response) bool {\n\th := proxyutil.ResponseHeader(res)\n\n\tvs, ok := h.All(m.name)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tfor _, v := range vs {\n\t\tif v == m.value {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc NewMatcher(name, value string) *Matcher ", "output": "{\n\treturn &Matcher{\n\t\tname: name,\n\t\tvalue: value,\n\t}\n}"} {"input": "package builder\n\nimport (\n\t\"sync\"\n\n\t\"github.com/rikvdh/ci/lib/config\"\n)\n\ntype jobCounter struct {\n\tmu sync.RWMutex\n\tjobCounter uint\n\tjobLimit uint\n\teventCh chan uint\n}\n\nfunc newJobCounter() *jobCounter {\n\treturn &jobCounter{\n\t\tjobCounter: 0,\n\t\tjobLimit: config.Get().ConcurrentBuilds,\n\t\teventCh: make(chan uint),\n\t}\n}\n\n\n\nfunc (j *jobCounter) Decrement() {\n\tj.mu.Lock()\n\tj.jobCounter--\n\tj.mu.Unlock()\n\tj.publishEvent()\n}\n\nfunc (j *jobCounter) CanStartJob() bool {\n\tj.mu.RLock()\n\tdefer j.mu.RUnlock()\n\treturn (j.jobCounter < j.jobLimit)\n}\n\nfunc (j *jobCounter) publishEvent() {\n\tj.mu.RLock()\n\tj.eventCh <- j.jobCounter\n\tj.mu.RUnlock()\n}\n\nfunc (j *jobCounter) GetEventChannel() <-chan uint {\n\tj.mu.RLock()\n\tdefer j.mu.RUnlock()\n\treturn j.eventCh\n}\n\nfunc (j *jobCounter) Increment() ", "output": "{\n\tj.mu.Lock()\n\tj.jobCounter++\n\tj.mu.Unlock()\n\tj.publishEvent()\n}"} {"input": "package simple\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/spencergibb/go-nuvem/loadbalancer\"\n\t\"github.com/spencergibb/go-nuvem/loadbalancer/rule\"\n\t\"github.com/spencergibb/go-nuvem/loadbalancer/serverlist\"\n\t\"github.com/spf13/viper\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\"\n)\n\n\n\nfunc TestBuilder(t *testing.T) {\n\tprintln(\"\\nTestBuilder\")\n\tlb := NewBuilder().\n\t\tNamespace(\"test\").\n\t\tServerList(serverlist.NewStaticBuilder(\"test\").Servers(\"10.0.0.1:80\").Build()).\n\t\tRule(rule.NewRandomRule()).\n\t\tBuild()\n\n\tassertLoadBalancer(t, lb)\n}\n\nfunc assertLoadBalancer(t *testing.T, lb loadbalancer.LoadBalancer) {\n\trequire.NotNil(t, lb, \"lb was nil\")\n\n\tserver := lb.Choose()\n\tassert.NotNil(t, server, \"server was nil\")\n}\n\nfunc TestFactory(t *testing.T) ", "output": "{\n\tviper.SetConfigType(\"yaml\")\n\tyaml := []byte(`\nnuvem.loadbalancer.test.serverlist.static.servers:\n- localhost:8080\n- 127.0.0.1:9080\n`)\n\terr := viper.ReadConfig(bytes.NewBuffer(yaml))\n\tviper.SetDefault(\"nuvem.loadbalancer.test.factory\", FactoryKey)\n\n\tif err != nil { \n\t\tpanic(fmt.Errorf(\"Fatal error config file: %s \\n\", err))\n\t}\n\n\tlb := loadbalancer.Create(\"test\")\n\tassertLoadBalancer(t, lb)\n}"} {"input": "package main\n\nimport (\n\t\"compress/gzip\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\nfunc main() {\n\tfpath := \"test.tar.gz\"\n\tif err := toGzip(\"Hello World!\", fpath); err != nil {\n\t\tpanic(err)\n\t}\n\tif tb, err := toBytes(fpath); err != nil {\n\t\tpanic(err)\n\t} else {\n\t\tfmt.Println(fpath, \":\", string(tb))\n\t}\n\tos.Remove(fpath)\n}\n\n\nfunc toGzip(txt, fpath string) error {\n\tf, err := os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0777)\n\tif err != nil {\n\t\tf, err = os.Create(fpath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tdefer f.Close()\n\tgw := gzip.NewWriter(f)\n\tif _, err := gw.Write([]byte(txt)); err != nil {\n\t\treturn err\n\t}\n\tgw.Close()\n\tgw.Flush()\n\treturn nil\n}\n\n\n\nfunc toBytes(fpath string) ([]byte, error) ", "output": "{\n\tf, err := os.OpenFile(fpath, os.O_RDONLY, 0444)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tfz, err := gzip.NewReader(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer fz.Close()\n\n\ts, err := ioutil.ReadAll(fz)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s, nil\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/csv\"\n\t\"encoding/json\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"reflect\"\n\t\"time\"\n\n\t\"github.com/robfig/cron\"\n)\n\nconst hook = \"http://localhost:8065/hooks/pdusr3nmwfn4pyhrh83dixr1xo\"\nconst filePath = \"timetable.csv\"\n\n\ntype ChatMsg struct {\n\tText string `json:\"text\"`\n}\n\n\ntype CsvLoader struct {\n\tFilePath string\n\trows [][]string\n}\n\n\n\n\nfunc remind(text string) {\n\tjsonMsg, _ := json.Marshal(&ChatMsg{text})\n\tmsgReader := bytes.NewReader(jsonMsg)\n\tclient := &http.Client{}\n\tr, _ := client.Post(hook, \"application/json\", msgReader)\n\tlog.Println(r.StatusCode, r.Header[\"X-Request-Id\"][0], string(jsonMsg))\n}\n\nfunc main() {\n\tloader := &CsvLoader{FilePath: filePath}\n\tcronJobs := &cron.Cron{}\n\n\tfor true {\n\t\tcsv, differs := loader.Load()\n\n\t\tif differs {\n\t\t\tcronJobs.Stop()\n\t\t\tcronJobs = cron.New()\n\t\t\tfor _, task := range csv {\n\t\t\t\tcronErr := cronJobs.AddFunc(task[0], func() { remind(task[1]) })\n\t\t\t\tif cronErr != nil {\n\t\t\t\t\tpanic(cronErr)\n\t\t\t\t}\n\t\t\t}\n\t\t\tcronJobs.Start()\n\t\t}\n\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}\n\nfunc (l *CsvLoader) Load() ([][]string, bool) ", "output": "{\n\tfile, err := os.Open(l.FilePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\trows, csvErr := csv.NewReader(file).ReadAll()\n\tif csvErr != nil {\n\t\tpanic(csvErr)\n\t}\n\n\tdiffers := !reflect.DeepEqual(rows, l.rows)\n\tl.rows = rows\n\n\treturn rows, differs\n}"} {"input": "package xmodule\n\nimport (\n\t\"fmt\"\n\tmsg \"github.com/Centimitr/xmessage\"\n)\n\ntype Comment struct{}\n\nfunc (m Comment) GetIndexComments(ctx *msg.Ctx) {\n\tfmt.Println(\"C\")\n}\nfunc (m Comment) GetMessages(ctx *msg.Ctx) {\n\tfmt.Println(\"M\")\n}\n\n\nfunc init() ", "output": "{\n\tvar m Comment\n\tmsg.LoadModule(m)\n}"} {"input": "package privsep\n\n\n\n\n\nimport \"syscall\"\n\nfunc setuid(uid int) (err error) {\n\t_, _, e1 := syscall.RawSyscall(syscall.SYS_SETUID, uintptr(uid), 0, 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}\n\n\n\nfunc setgid(gid int) (err error) ", "output": "{\n\t_, _, e1 := syscall.RawSyscall(syscall.SYS_SETGID, uintptr(gid), 0, 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}"} {"input": "package olog\n\nimport (\n\t\"fmt\"\n)\n\n\ntype DirectLogger struct {\n\twriters map[string]Writer\n}\n\n\nfunc NewDirectLogger() *DirectLogger {\n\treturn &DirectLogger{\n\t\twriters: make(map[string]Writer),\n\t}\n}\n\n\nfunc (dl *DirectLogger) Log(level Level,\n\tmodule string,\n\tfmtstr string,\n\targs ...interface{}) {\n\tif level == PrintLevel {\n\t\treturn\n\t}\n\tfmtstr = ToString(level) + \" [\" + module + \"] \" + fmtstr\n\tmsg := fmt.Sprintf(fmtstr, args...)\n\tfor _, writer := range dl.writers {\n\t\tif writer.IsEnabled() {\n\t\t\twriter.Write(msg)\n\t\t}\n\t}\n}\n\n\n\n\n\nfunc (dl *DirectLogger) RemoveWriter(uniqueID string) {\n\tdelete(dl.writers, uniqueID)\n}\n\n\nfunc (dl *DirectLogger) GetWriter(uniqueID string) (writer Writer) {\n\treturn dl.writers[uniqueID]\n}\n\nfunc (dl *DirectLogger) RegisterWriter(writer Writer) ", "output": "{\n\tif writer != nil {\n\t\tdl.writers[writer.UniqueID()] = writer\n\t}\n}"} {"input": "package controller\n\nimport (\n\t\"os\"\n\t\"path\"\n\tmustache \"../library/mustache/_obj/mustache\"\n)\n\n\n\n\n\nfunc IndexHandler() string ", "output": "{\n\troot := os.Getenv(\"cd ..; pwd\")\n\tview := path.Join(root, \"view\")\n\tfile := path.Join(path.Join(view, \"index\"), \"index.mustache\")\n\n\tdata := map[string] string {\n\t\t\"title\": \"Hello, blog.go\",\n\t\t\"name\": \"Welcome to blog.go!\",\n\t}\n\n return mustache.RenderFile(file, data)\n}"} {"input": "package copy_to\n\nimport (\n\t\"github.com/go-zero-boilerplate/job-coordinator/context\"\n)\n\ntype queuedJob struct {\n\tcopyToWorker *copyTo\n\tctx *context.Context\n\tjob Job\n\thandlers Handlers\n}\n\n\n\n\nfunc (q *queuedJob) Do(workerID int) error ", "output": "{\n\treturn q.copyToWorker.DoJob(q.ctx, q.job, q.handlers)\n}"} {"input": "package informers\n\nimport (\n\t\"fmt\"\n\tv1alpha1 \"github.com/jetstack-experimental/cert-manager/pkg/apis/certmanager/v1alpha1\"\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tcache \"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\n\n\n\nfunc (f *genericInformer) Lister() cache.GenericLister {\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {\n\tswitch resource {\n\tcase v1alpha1.SchemeGroupVersion.WithResource(\"certificates\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Certmanager().V1alpha1().Certificates().Informer()}, nil\n\tcase v1alpha1.SchemeGroupVersion.WithResource(\"issuers\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Certmanager().V1alpha1().Issuers().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer ", "output": "{\n\treturn f.informer\n}"} {"input": "package adapter\n\nimport (\n\t\"github.com/arasuresearch/arasu/datastorage/bigdata/adapter/abstract\"\n\t\"github.com/arasuresearch/arasu/datastorage/bigdata/adapter/hbase\"\n\t\"log\"\n)\n\ntype Adapter interface {\n\tGetDbName() string\n\tCreateDatabase() error\n\tDropDatabase() error\n\n\tGetTableNames() ([]string, error)\n\tIsDatabaseExists() bool\n\n\tCreateTable(string, func(*abstract.Table)) error\n\tAlterTable(name string, args ...interface{}) error\n\tDropTable(string) error\n\n\n\tDumpSchema()\n\n\tCreateSchemaMigration() error\n\tDropSchemaMigration() error\n\tGetAllSchemaMigration() ([]string, error)\n\tDeleteFromSchemaMigration(version string) error\n\tInsertIntoSchemaMigration(version string) error\n\tSchemaToStruct(string) (*abstract.SchemaToStruct, error)\n}\n\n\n\nfunc New(name string, conf string) (adapter Adapter) ", "output": "{\n\tvar abstractAdapter = abstract.New(name, conf)\n\tswitch name {\n\tcase \"hbase\":\n\t\tadapter = hbase.New(abstractAdapter)\n\n\tdefault:\n\t\tlog.Fatal(\"Adapter Error (\" + name + \") Adapter not supported \")\n\t}\n\treturn\n}"} {"input": "package iptables\n\nimport (\n\t\"github.com/google/netstack/tcpip/buffer\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Hook uint\n\n\nconst (\n\tPrerouting Hook = iota\n\n\tInput\n\n\tForward\n\n\tOutput\n\n\tPostrouting\n\n\tNumHooks\n)\n\n\n\ntype Verdict int\n\nconst (\n\tAccept Verdict = iota\n\n\tDrop\n\n\tStolen\n\n\tQueue\n\n\tRepeat\n\n\tNone\n\n\tJump\n\n\tContinue\n\n\tReturn\n)\n\n\ntype IPTables struct {\n\tTables map[string]Table\n\n\tPriorities map[Hook][]string\n}\n\n\n\n\n\ntype Table struct {\n\tBuiltinChains map[Hook]Chain\n\n\tDefaultTargets map[Hook]Target\n\n\tUserChains map[string]Chain\n\n\tChains map[string]*Chain\n\n\tmetadata interface{}\n}\n\n\n\n\n\nfunc (table *Table) Metadata() interface{} {\n\treturn table.metadata\n}\n\n\nfunc (table *Table) SetMetadata(metadata interface{}) {\n\ttable.metadata = metadata\n}\n\n\n\n\n\n\n\n\ntype Chain struct {\n\tName string\n\n\tRules []Rule\n}\n\n\n\n\n\ntype Rule struct {\n\tMatchers []Matcher\n\n\tTarget Target\n}\n\n\ntype Matcher interface {\n\tMatch(hook Hook, packet buffer.VectorisedView, interfaceName string) (matches bool, hotdrop bool)\n}\n\n\ntype Target interface {\n\tAction(packet buffer.VectorisedView) (Verdict, string)\n}\n\nfunc (table *Table) ValidHooks() uint32 ", "output": "{\n\thooks := uint32(0)\n\tfor hook, _ := range table.BuiltinChains {\n\t\thooks |= 1 << hook\n\t}\n\treturn hooks\n}"} {"input": "package redis3\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/chrislusf/seaweedfs/weed/filer\"\n\t\"github.com/go-redis/redis/v8\"\n)\n\nfunc (store *UniversalRedis3Store) KvPut(ctx context.Context, key []byte, value []byte) (err error) {\n\n\t_, err = store.Client.Set(ctx, string(key), value, 0).Result()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"kv put: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (store *UniversalRedis3Store) KvGet(ctx context.Context, key []byte) (value []byte, err error) {\n\n\tdata, err := store.Client.Get(ctx, string(key)).Result()\n\n\tif err == redis.Nil {\n\t\treturn nil, filer.ErrKvNotFound\n\t}\n\n\treturn []byte(data), err\n}\n\n\n\nfunc (store *UniversalRedis3Store) KvDelete(ctx context.Context, key []byte) (err error) ", "output": "{\n\n\t_, err = store.Client.Del(ctx, string(key)).Result()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"kv delete: %v\", err)\n\t}\n\n\treturn nil\n}"} {"input": "package raddress\n\nimport (\n\t\"fmt\"\n\t. \"github.com/smartystreets/goconvey/convey\"\n\t\"testing\"\n)\n\n\n\nfunc TestLoc(t *testing.T) {\n\tfmt.Println(Loc.RegionName(67))\n\tConvey(\"test Loc\", t, func() {\n\t\titems := Loc.Cities(67)\n\t\tSo(len(items), ShouldNotEqual, 0)\n\t})\n}\n\nfunc TestCities(t *testing.T) ", "output": "{\n\tConvey(\"Test get city\", t, func() {\n\n\t\tConvey(\"Test get city\", func() {\n\t\t\titem := GetCityByName(\"Москва\")\n\t\t\tSo(item.Id, ShouldNotEqual, 0)\n\t\t\tSo(item.RegionId, ShouldNotEqual, 0)\n\t\t})\n\n\t\tConvey(\"Get city region\", func() {\n\t\t\titem := GetCityRegion(\"москва\")\n\t\t\tSo(item.Id, ShouldNotEqual, 0)\n\t\t})\n\n\t\tConvey(\"Get region\", func() {\n\t\t\titems := GetRegionCities(\"Смоленска\")\n\t\t\tSo(len(items), ShouldNotEqual, 0)\n\t\t})\n\n\t})\n\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strings\"\n)\n\n\nfunc MakeIndexMessage(pkg *Package) string {\n\tdependenciesNames := []string{}\n\n\tfor _, dep := range pkg.Dependencies {\n\t\tdependenciesNames = append(dependenciesNames, dep.Name)\n\t}\n\n\tnamesAsString := strings.Join(dependenciesNames, \",\")\n\treturn fmt.Sprintf(\"INDEX|%s|%s\", pkg.Name, namesAsString)\n}\n\n\nfunc MakeRemoveMessage(pkg *Package) string {\n\treturn fmt.Sprintf(\"REMOVE|%s|\", pkg.Name)\n}\n\n\n\n\nvar possibleInvalidCommands = []string{\"BLINDEX\", \"REMOVES\", \"QUER\", \"LIZARD\", \"I\"}\nvar possibleInvalidChars = []string{\"=\", \"+\", \"☃\", \" \"}\n\n\n\nfunc MakeBrokenMessage() string {\n\tsyntaxError := rand.Intn(10)%2 == 0\n\n\tif syntaxError {\n\t\tinvalidChar := possibleInvalidChars[rand.Intn(len(possibleInvalidChars))]\n\t\treturn fmt.Sprintf(\"INDEX|emacs%selisp\", invalidChar)\n\t}\n\n\tinvalidCommand := possibleInvalidCommands[rand.Intn(len(possibleInvalidCommands))]\n\treturn fmt.Sprintf(\"%s|a|b\", invalidCommand)\n}\n\nfunc MakeQueryMessage(pkg *Package) string ", "output": "{\n\treturn fmt.Sprintf(\"QUERY|%s|\", pkg.Name)\n}"} {"input": "package server\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n\n\t\"github.com/kyokomi/expcache\"\n)\n\ntype ImageCache interface {\n\tGetRandomImageURL() string\n}\n\ntype imageCache struct {\n\tExpire expcache.ExpireOnMemoryCache\n\tcache []string\n\n\ttwAPI TwitterAPI\n\trd *rand.Rand\n\ttwitterID string\n\tcacheCnt int\n}\n\nfunc NewImageCache(twAPI TwitterAPI, twitterID string, cacheCnt int) ImageCache {\n\te := &imageCache{\n\t\tcache: []string{},\n\t\ttwAPI: twAPI,\n\t\trd: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t\ttwitterID: twitterID,\n\t\tcacheCnt: cacheCnt,\n\t}\n\te.Expire = expcache.NewExpireMemoryCache(e, 24*time.Hour)\n\treturn e\n}\n\nfunc (c *imageCache) GetRandomImageURL() string {\n\tvar result string\n\tc.Expire.WithRefreshLock(time.Now(), func() {\n\t\tidx := c.rd.Int31n(int32(len(c.cache))) - 1\n\t\tresult = c.cache[idx]\n\t})\n\treturn result\n}\n\n\n\nvar _ expcache.OnMemoryCache = (*imageCache)(nil)\nvar _ ImageCache = (*imageCache)(nil)\n\nfunc (c *imageCache) Refresh() error ", "output": "{\n\timages, err := c.twAPI.GetFavoritesImages(c.cacheCnt, c.twitterID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.cache = images\n\treturn nil\n}"} {"input": "package content\nimport (\n\t\"go2o/src/core/domain/interface/content\"\n\t\"time\"\n)\n\nvar _ content.IPage = new(Page)\ntype Page struct{\n\t_contentRep content.IContentRep\n\t_partnerId int\n\t_value *content.ValuePage\n}\n\nfunc NewPage(partnerId int, rep content.IContentRep,v *content.ValuePage) content.IPage {\n\treturn &Page{\n\t\t_contentRep: rep,\n\t\t_partnerId: partnerId,\n\t\t_value:v,\n\t}\n}\n\n\n\n\n\n\nfunc (this *Page) GetValue()*content.ValuePage{\n\treturn this._value\n}\n\n\nfunc (this *Page) SetValue(v *content.ValuePage)error{\n\tv.Id = this.GetDomainId()\n\tthis._value = v\n\treturn nil\n}\n\n\nfunc (this *Page) Save()(int,error){\n\tthis._value.UpdateTime = time.Now().Unix()\n\treturn this._contentRep.SavePage(this._partnerId,this._value)\n}\n\nfunc (this *Page) GetDomainId() int", "output": "{\n\treturn this._value.Id\n}"} {"input": "package pathdb\n\nimport (\n\t\"github.com/scionproto/scion/go/lib/common\"\n\t\"github.com/scionproto/scion/go/lib/ctrl/seg\"\n\t\"github.com/scionproto/scion/go/lib/pathdb/conn\"\n\t\"github.com/scionproto/scion/go/lib/pathdb/query\"\n\t\"github.com/scionproto/scion/go/lib/pathdb/sqlite\"\n)\n\ntype DB struct {\n\tconn conn.Conn\n}\n\n\n\nfunc New(path string, backend string) (*DB, error) {\n\tdb := &DB{}\n\tvar err error\n\tswitch backend {\n\tcase \"sqlite\":\n\t\tdb.conn, err = sqlite.New(path)\n\tdefault:\n\t\treturn nil, common.NewBasicError(\"Unknown backend\", nil, \"backend\", backend)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn db, nil\n}\n\n\n\nfunc (db *DB) Insert(pseg *seg.PathSegment, segTypes []seg.Type) (int, error) {\n\treturn db.conn.Insert(pseg, segTypes)\n}\n\n\n\nfunc (db *DB) InsertWithHPCfgIDs(pseg *seg.PathSegment,\n\tsegTypes []seg.Type, hpCfgIDs []*query.HPCfgID) (int, error) {\n\treturn db.conn.InsertWithHPCfgIDs(pseg, segTypes, hpCfgIDs)\n}\n\n\n\nfunc (db *DB) Delete(segID common.RawBytes) (int, error) {\n\treturn db.conn.Delete(segID)\n}\n\n\n\nfunc (db *DB) DeleteWithIntf(intf query.IntfSpec) (int, error) {\n\treturn db.conn.DeleteWithIntf(intf)\n}\n\n\n\n\nfunc (db *DB) Get(params *query.Params) ([]*query.Result, error) ", "output": "{\n\treturn db.conn.Get(params)\n}"} {"input": "package sol\n\n\ntype Operator interface {\n\tWrap(string) string \n}\n\n\nfunc Function(name string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(FuncClause{Name: name})\n}\n\n\nfunc Avg(col Columnar) ColumnElem {\n\treturn Function(AVG, col)\n}\n\n\nfunc Count(col Columnar) ColumnElem {\n\treturn Function(COUNT, col)\n}\n\n\nfunc Date(col Columnar) ColumnElem {\n\treturn Function(DATE, col)\n}\n\n\n\nfunc DatePart(part string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(\n\t\tFuncClause{Name: DATEPART},\n\t).AddOperator(\n\t\tArrayClause{clauses: []Clause{String(part)}, post: true, sep: \", \"},\n\t)\n}\n\n\nfunc Max(col Columnar) ColumnElem {\n\treturn Function(MAX, col)\n}\n\n\nfunc Min(col Columnar) ColumnElem {\n\treturn Function(MIN, col)\n}\n\n\nfunc StdDev(col Columnar) ColumnElem {\n\treturn Function(STDDEV, col)\n}\n\n\n\n\n\nfunc Variance(col Columnar) ColumnElem {\n\treturn Function(VARIANCE, col)\n}\n\nfunc Sum(col Columnar) ColumnElem ", "output": "{\n\treturn Function(SUM, col)\n}"} {"input": "package okta\n\nimport ()\n\ntype SwaApplicationSettingsApplication struct {\n\tButtonField string `json:\"buttonField,omitempty\"`\n\tLoginUrlRegex string `json:\"loginUrlRegex,omitempty\"`\n\tPasswordField string `json:\"passwordField,omitempty\"`\n\tUrl string `json:\"url,omitempty\"`\n\tUsernameField string `json:\"usernameField,omitempty\"`\n}\n\n\n\nfunc (a *SwaApplicationSettingsApplication) IsApplicationInstance() bool {\n\treturn true\n}\n\nfunc NewSwaApplicationSettingsApplication() *SwaApplicationSettingsApplication ", "output": "{\n\treturn &SwaApplicationSettingsApplication{}\n}"} {"input": "package lib\n\n\nimport \"C\"\n\n\n\nfunc CheckSize(check int) int {\n\treturn int(C.lzma_check_size(C.lzma_check(check)))\n}\n\nfunc CRC32(buf []byte, crc uint32) uint32 {\n\tptr, size := CSlicePtrLen(buf)\n\treturn uint32(C.lzma_crc32(ptr, size, C.uint32_t(crc)))\n}\n\nfunc CRC64(buf []byte, crc uint64) uint64 {\n\tptr, size := CSlicePtrLen(buf)\n\treturn uint64(C.lzma_crc64(ptr, size, C.uint64_t(crc)))\n}\n\nfunc (z *Stream) GetCheck() int {\n\treturn int(C.lzma_get_check(z.C()))\n}\n\nfunc CheckIsSupported(check int) bool ", "output": "{\n\treturn C.lzma_check_is_supported(C.lzma_check(check)) != 0\n}"} {"input": "package lib\n\nimport (\n\t\"github.com/atinm/spotify\"\n)\n\n\n\nfunc FiltersEnabled() bool {\n\treturn ParentalControlsEnabled()\n}\n\nfunc ParentalControlsEnabled() bool {\n\treturn rule.Explicit\n}\n\nfunc Rules(track *spotify.FullTrack, device string) bool {\n\tif track != nil && rule.Explicit && track.Explicit && !ignored(device) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc SetParentalControls(b bool) {\n\trule.Explicit = b\n}\n\nfunc ignored(device string) bool ", "output": "{\n\tfor _, name := range config.Ignored {\n\t\tif name == device {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSECSTaskDefinition_DockerVolumeConfiguration struct {\n\n\tAutoprovision bool `json:\"Autoprovision,omitempty\"`\n\n\tDriver string `json:\"Driver,omitempty\"`\n\n\tDriverOpts map[string]string `json:\"DriverOpts,omitempty\"`\n\n\tLabels map[string]string `json:\"Labels,omitempty\"`\n\n\tScope string `json:\"Scope,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) AWSCloudFormationType() string {\n\treturn \"AWS::ECS::TaskDefinition.DockerVolumeConfiguration\"\n}\n\n\n\n\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) DependsOn() []string ", "output": "{\n\treturn r._dependsOn\n}"} {"input": "package awstasks\n\nimport (\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/service/ec2\"\n)\n\n\n\nfunc findNameTag(tags []*ec2.Tag) *string {\n\tfor _, tag := range tags {\n\t\tif aws.StringValue(tag.Key) == \"Name\" {\n\t\t\treturn tag.Value\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\nfunc intersectTags(tags []*ec2.Tag, desired map[string]string) map[string]string {\n\tif tags == nil {\n\t\treturn nil\n\t}\n\tactual := make(map[string]string)\n\tfor _, t := range tags {\n\t\tk := aws.StringValue(t.Key)\n\t\tv := aws.StringValue(t.Value)\n\n\t\tif _, found := desired[k]; found {\n\t\t\tactual[k] = v\n\t\t}\n\t}\n\tif len(actual) == 0 && desired == nil {\n\t\treturn nil\n\t}\n\treturn actual\n}\n\nfunc mapEC2TagsToMap(tags []*ec2.Tag) map[string]string ", "output": "{\n\tif tags == nil {\n\t\treturn nil\n\t}\n\tm := make(map[string]string)\n\tfor _, t := range tags {\n\t\tm[aws.StringValue(t.Key)] = aws.StringValue(t.Value)\n\t}\n\treturn m\n}"} {"input": "package main\n\n\n\n\nimport \"C\"\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime/pprof\"\n\t\"time\"\n\t\"unsafe\"\n)\n\nfunc init() {\n\tregister(\"CgoPprofThread\", CgoPprofThread)\n\tregister(\"CgoPprofThreadNoTraceback\", CgoPprofThreadNoTraceback)\n}\n\nfunc CgoPprofThread() {\n\truntime.SetCgoTraceback(0, unsafe.Pointer(C.pprofCgoThreadTraceback), nil, nil)\n\tpprofThread()\n}\n\nfunc CgoPprofThreadNoTraceback() {\n\tpprofThread()\n}\n\n\n\nfunc pprofThread() ", "output": "{\n\tf, err := os.CreateTemp(\"\", \"prof\")\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(2)\n\t}\n\n\tif err := pprof.StartCPUProfile(f); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(2)\n\t}\n\n\tC.runCPUHogThread()\n\n\tt0 := time.Now()\n\tfor C.getCPUHogThreadCount() < 2 && time.Since(t0) < time.Second {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\n\tpprof.StopCPUProfile()\n\n\tname := f.Name()\n\tif err := f.Close(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Println(name)\n}"} {"input": "package session\n\nimport (\n\t\"github.com/coyim/coyim/xmpp/data\"\n)\n\nconst (\n\tMUCStatusJIDPublic = 100\n\tMUCStatusAffiliationChanged = 101\n\tMUCStatusUnavailableShown = 102\n\tMUCStatusUnavailableNotShown = 103\n\tMUCStatusConfigChanged = 104\n\tMUCStatusSelfPresence = 110\n\tMUCStatusRoomLoggingEnabled = 170\n\tMUCStatusRoomLoggingDisabled = 171\n\tMUCStatusRoomNonAnonymous = 172\n\tMUCStatusRoomSemiAnonymous = 173\n\tMUCStatusRoomFullyAnonymous = 174\n\tMUCStatusRoomCreated = 201\n\tMUCStatusNicknameAssigned = 210\n\tMUCStatusBanned = 301\n\tMUCStatusNewNickname = 303\n\tMUCStatusBecauseKickedFrom = 307\n\tMUCStatusRemovedBecauseAffiliationChanged = 321\n\tMUCStatusRemovedBecauseNotMember = 322\n\tMUCStatusRemovedBecauseShutdown = 332\n)\n\ntype mucUserStatuses []data.MUCUserStatus\n\n\nfunc (mus mucUserStatuses) contains(c ...int) bool {\n\tfor _, cc := range c {\n\t\tif !mus.containsOne(cc) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (mus mucUserStatuses) containsAny(c ...int) bool {\n\tfor _, cc := range c {\n\t\tif mus.containsOne(cc) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\nfunc (mus mucUserStatuses) isEmpty() bool {\n\treturn len(mus) == 0\n}\n\nfunc (mus mucUserStatuses) containsOne(c int) bool ", "output": "{\n\tfor _, s := range mus {\n\t\tif s.Code == c {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package vmutil\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/bytom/crypto/ed25519\"\n)\n\n\n\nfunc TestIsUnspendable(t *testing.T) {\n\ttests := []struct {\n\t\tpkScript []byte\n\t\texpected bool\n\t}{\n\t\t{\n\t\t\tpkScript: []byte{0x6a, 0x04, 0x74, 0x65, 0x73, 0x74},\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tpkScript: []byte{0x76, 0xa9, 0x14, 0x29, 0x95, 0xa0,\n\t\t\t\t0xfe, 0x68, 0x43, 0xfa, 0x9b, 0x95, 0x45,\n\t\t\t\t0x97, 0xf0, 0xdc, 0xa7, 0xa4, 0x4d, 0xf6,\n\t\t\t\t0xfa, 0x0b, 0x5c, 0x88, 0xac},\n\t\t\texpected: false,\n\t\t},\n\t}\n\n\tfor i, test := range tests {\n\t\tres := IsUnspendable(test.pkScript)\n\t\tif res != test.expected {\n\t\t\tt.Errorf(\"TestIsUnspendable #%d failed: got %v want %v\",\n\t\t\t\ti, res, test.expected)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\n\n\nfunc TestP2SP(t *testing.T) ", "output": "{\n\tpub1, _, _ := ed25519.GenerateKey(nil)\n\tpub2, _, _ := ed25519.GenerateKey(nil)\n\tprog, _ := P2SPMultiSigProgram([]ed25519.PublicKey{pub1, pub2}, 1)\n\tpubs, n, err := ParseP2SPMultiSigProgram(prog)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif n != 1 {\n\t\tt.Errorf(\"expected nrequired=1, got %d\", n)\n\t}\n\tif !bytes.Equal(pubs[0], pub1) {\n\t\tt.Errorf(\"expected first pubkey to be %x, got %x\", pub1, pubs[0])\n\t}\n\tif !bytes.Equal(pubs[1], pub2) {\n\t\tt.Errorf(\"expected second pubkey to be %x, got %x\", pub2, pubs[1])\n\t}\n}"} {"input": "package flag\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/hashicorp/errwrap\"\n)\n\n\ntype OptionList struct {\n\tOptions []string\n\tallOptions []string\n\tpermissible map[string]struct{}\n\ttypeName string\n}\n\n\n\n\nfunc NewOptionList(permissibleOptions []string, defaultOptions string) (*OptionList, error) {\n\tpermissible := make(map[string]struct{})\n\tol := &OptionList{\n\t\tallOptions: permissibleOptions,\n\t\tpermissible: permissible,\n\t\ttypeName: \"OptionList\",\n\t}\n\n\tfor _, o := range permissibleOptions {\n\t\tol.permissible[o] = struct{}{}\n\t}\n\n\tif err := ol.Set(defaultOptions); err != nil {\n\t\treturn nil, errwrap.Wrap(errors.New(\"problem setting defaults\"), err)\n\t}\n\n\treturn ol, nil\n}\n\nfunc (ol *OptionList) Set(s string) error {\n\tol.Options = nil\n\tif s == \"\" {\n\t\treturn nil\n\t}\n\toptions := strings.Split(strings.ToLower(s), \",\")\n\tseen := map[string]struct{}{}\n\tfor _, o := range options {\n\t\tif _, ok := ol.permissible[o]; !ok {\n\t\t\treturn fmt.Errorf(\"unknown option %q\", o)\n\t\t}\n\t\tif _, ok := seen[o]; ok {\n\t\t\treturn fmt.Errorf(\"duplicated option %q\", o)\n\t\t}\n\t\tol.Options = append(ol.Options, o)\n\t\tseen[o] = struct{}{}\n\t}\n\n\treturn nil\n}\n\nfunc (ol *OptionList) String() string {\n\treturn strings.Join(ol.Options, \",\")\n}\n\nfunc (ol *OptionList) Type() string {\n\treturn ol.typeName\n}\n\n\n\nfunc (ol *OptionList) PermissibleString() string ", "output": "{\n\treturn fmt.Sprintf(`\"%s\"`, strings.Join(ol.allOptions, `\", \"`))\n}"} {"input": "package expvar\n\nimport (\n\t\"expvar\"\n\t\"runtime\"\n\t\"sync\"\n\n\t\"github.com/mholt/caddy\"\n\t\"github.com/mholt/caddy/caddyhttp/httpserver\"\n)\n\nfunc init() {\n\tcaddy.RegisterPlugin(\"expvar\", caddy.Plugin{\n\t\tServerType: \"http\",\n\t\tAction: setup,\n\t})\n}\n\n\n\n\nfunc expVarParse(c *caddy.Controller) (Resource, error) {\n\tvar resource Resource\n\tvar err error\n\n\tfor c.Next() {\n\t\targs := c.RemainingArgs()\n\t\tswitch len(args) {\n\t\tcase 0:\n\t\t\tresource = Resource(defaultExpvarPath)\n\t\tcase 1:\n\t\t\tresource = Resource(args[0])\n\t\tdefault:\n\t\t\treturn resource, c.ArgErr()\n\t\t}\n\t}\n\n\treturn resource, err\n}\n\nfunc publishExtraVars() {\n\tpublishOnce.Do(func() {\n\t\texpvar.Publish(\"Goroutines\", expvar.Func(func() interface{} {\n\t\t\treturn runtime.NumGoroutine()\n\t\t}))\n\t})\n}\n\nvar publishOnce sync.Once \nvar defaultExpvarPath = \"/debug/vars\"\n\nfunc setup(c *caddy.Controller) error ", "output": "{\n\tresource, err := expVarParse(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpublishExtraVars()\n\n\tev := ExpVar{Resource: resource}\n\n\thttpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {\n\t\tev.Next = next\n\t\treturn ev\n\t})\n\n\treturn nil\n}"} {"input": "package virtualbox\n\nimport (\n\t\"fmt\"\n\t\"github.com/mitchellh/multistep\"\n\t\"github.com/mitchellh/packer/packer\"\n)\n\n\n\n\n\ntype stepCreateVM struct {\n\tvmName string\n}\n\nfunc (s *stepCreateVM) Run(state map[string]interface{}) multistep.StepAction {\n\tconfig := state[\"config\"].(*config)\n\tdriver := state[\"driver\"].(Driver)\n\tui := state[\"ui\"].(packer.Ui)\n\n\tname := config.VMName\n\n\tcommands := make([][]string, 4)\n\tcommands[0] = []string{\"createvm\", \"--name\", name, \"--ostype\", config.GuestOSType, \"--register\"}\n\tcommands[1] = []string{\n\t\t\"modifyvm\", name,\n\t\t\"--boot1\", \"disk\", \"--boot2\", \"dvd\", \"--boot3\", \"none\", \"--boot4\", \"none\",\n\t}\n\tcommands[2] = []string{\"modifyvm\", name, \"--cpus\", \"1\"}\n\tcommands[3] = []string{\"modifyvm\", name, \"--memory\", \"512\"}\n\n\tui.Say(\"Creating virtual machine...\")\n\tfor _, command := range commands {\n\t\terr := driver.VBoxManage(command...)\n\t\tif err != nil {\n\t\t\terr := fmt.Errorf(\"Error creating VM: %s\", err)\n\t\t\tstate[\"error\"] = err\n\t\t\tui.Error(err.Error())\n\t\t\treturn multistep.ActionHalt\n\t\t}\n\n\t\tif s.vmName == \"\" {\n\t\t\ts.vmName = name\n\t\t}\n\t}\n\n\tstate[\"vmName\"] = s.vmName\n\n\treturn multistep.ActionContinue\n}\n\n\n\nfunc (s *stepCreateVM) Cleanup(state map[string]interface{}) ", "output": "{\n\tif s.vmName == \"\" {\n\t\treturn\n\t}\n\n\tdriver := state[\"driver\"].(Driver)\n\tui := state[\"ui\"].(packer.Ui)\n\n\tui.Say(\"Unregistering and deleting virtual machine...\")\n\tif err := driver.VBoxManage(\"unregistervm\", s.vmName, \"--delete\"); err != nil {\n\t\tui.Error(fmt.Sprintf(\"Error deleting virtual machine: %s\", err))\n\t}\n}"} {"input": "package handler\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\t\"github.com/goharbor/harbor/src/jobservice/job\"\n\tlibhttp \"github.com/goharbor/harbor/src/lib/http\"\n\t\"github.com/goharbor/harbor/src/pkg/task\"\n)\n\n\n\n\ntype jobStatusHandler struct {\n\thandler *task.HookHandler\n}\n\nfunc (j *jobStatusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tdefer r.Body.Close()\n\n\tsc := &job.StatusChange{}\n\tif err := json.NewDecoder(r.Body).Decode(sc); err != nil {\n\t\tlibhttp.SendError(w, err)\n\t\treturn\n\t}\n\tif err := j.handler.Handle(r.Context(), sc); err != nil {\n\t\tlibhttp.SendError(w, err)\n\t\treturn\n\t}\n}\n\nfunc NewJobStatusHandler() http.Handler ", "output": "{\n\treturn &jobStatusHandler{\n\t\thandler: task.HkHandler,\n\t}\n}"} {"input": "package opts\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype List struct {\n\tArgs []string\n}\n\nfunc (lo *List) Set(arg string) error {\n\tlo.Args = append(lo.Args[:], arg)\n\treturn nil\n}\n\n\n\nfunc (lo List) String() string {\n\treturn fmt.Sprintf(\"[%s]\", strings.Join(lo.Args, \", \"))\n}\n\nfunc (lo List) Get() []string ", "output": "{\n\treturn lo.Args\n}"} {"input": "package shoauth\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\ntype expectedSuccessHandler struct{}\n\nfunc (s *expectedSuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}\n\ntype expectedFailureHandler struct{}\n\nfunc (s *expectedFailureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}\n\ntype unexpectedSuccessHandler struct {\n\tt *testing.T\n}\n\nfunc (s *unexpectedSuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.t.Errorf(\"Request should have failed, but succeeded instead!\")\n}\n\ntype unexpectedFailureHandler struct {\n\tt *testing.T\n}\n\nfunc (s *unexpectedFailureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.t.Errorf(\"Request should have succeeded, but failed instead!\")\n}\n\ntype testPersistence struct {\n\texists bool\n\tcreate error\n\tsession bool\n}\n\n\n\nfunc (t *testPersistence) CreateInstallation(shopID string, accessToken string) error {\n\treturn t.create\n}\n\nfunc TestAlreadyInstalled(t *testing.T) {\n\tp := testPersistence{\n\t\texists: true,\n\t\tcreate: errors.New(\"Installation already exists!\"),\n\t\tsession: false,\n\t}\n\thandler := NewShopifyOauthHandler(&unexpectedSuccessHandler{t: t}, &expectedFailureHandler{}, &p)\n\ttestServer := httptest.NewServer(handler)\n\tdefer testServer.Close()\n\thttp.Get(testServer.URL + \"/install\")\n}\n\nfunc (t *testPersistence) InstallationExists(shopID string) bool ", "output": "{\n\treturn t.exists\n}"} {"input": "package main\n\nimport \"testing\"\n\nfunc TestNewSliceStack(t *testing.T) {\n\tstack := NewStack()\n\n\tif len(stack) != 0 {\n\t\tt.Error(`Expected length of stack to be 0, got`, len(stack))\n\t}\n}\n\nfunc TestSliceStackPush(t *testing.T) {\n\tstack := NewStack()\n\tstack.Push(1111)\n\tstack.Push(2345)\n\n\tif stack[0] != 1111 {\n\t\tt.Error(`Expected the first item to be 1111, got`, stack[0])\n\t}\n}\n\nfunc TestSliceStackPeek(t *testing.T) {\n\tstack := NewStack()\n\tstack.Push(1234)\n\tstack.Push(2345)\n\tvalue, _ := stack.Peek()\n\n\tif value != 2345 {\n\t\tt.Error(`Expected peeked value to be 2345, got`, value)\n\t}\n}\n\n\n\nfunc BenchmarkSliceStackPush(b *testing.B) {\n\tb.StopTimer()\n\tstack := NewStack()\n\n\tb.StartTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tstack.Push(n)\n\t}\n}\n\nfunc BenchmarkSliceStackPeek(b *testing.B) {\n\tb.StopTimer()\n\tstack := make(Stack, b.N, b.N)\n\n\tb.StartTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tstack.Peek()\n\t}\n}\n\nfunc BenchmarkSliceStackPop(b *testing.B) {\n\tb.StopTimer()\n\tstack := make(Stack, b.N, b.N)\n\tfor n := 0; n < b.N; n++ {\n\t\tstack[n] = n\n\t}\n\n\tb.StartTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tstack.Pop()\n\t}\n}\n\nfunc TestSliceStackPop(t *testing.T) ", "output": "{\n\tstack := NewStack()\n\tstack.Push(1234)\n\tstack.Push(2345)\n\tvalue, _ := stack.Pop()\n\n\tif value != 2345 {\n\t\tt.Error(`Expected peeked value to be 2345, got`, value)\n\t}\n}"} {"input": "package corehttp\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\n\tcore \"github.com/ipfs/go-ipfs/core\"\n\tlogging \"github.com/ipfs/go-ipfs/vendor/QmQg1J6vikuXF9oDvm4wpdeAUvvkVEKW1EYDw9HhTMnP2b/go-log\"\n)\n\ntype writeErrNotifier struct {\n\tw io.Writer\n\terrs chan error\n}\n\nfunc newWriteErrNotifier(w io.Writer) (io.WriteCloser, <-chan error) {\n\tch := make(chan error, 1)\n\treturn &writeErrNotifier{\n\t\tw: w,\n\t\terrs: ch,\n\t}, ch\n}\n\nfunc (w *writeErrNotifier) Write(b []byte) (int, error) {\n\tn, err := w.w.Write(b)\n\tif err != nil {\n\t\tselect {\n\t\tcase w.errs <- err:\n\t\tdefault:\n\t\t}\n\t}\n\tif f, ok := w.w.(http.Flusher); ok {\n\t\tf.Flush()\n\t}\n\treturn n, err\n}\n\n\n\nfunc LogOption() ServeOption {\n\treturn func(n *core.IpfsNode, _ net.Listener, mux *http.ServeMux) (*http.ServeMux, error) {\n\t\tmux.HandleFunc(\"/logs\", func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.WriteHeader(200)\n\t\t\twnf, errs := newWriteErrNotifier(w)\n\t\t\tlogging.WriterGroup.AddWriter(wnf)\n\t\t\tlog.Event(n.Context(), \"log API client connected\")\n\t\t\t<-errs\n\t\t})\n\t\treturn mux, nil\n\t}\n}\n\nfunc (w *writeErrNotifier) Close() error ", "output": "{\n\tselect {\n\tcase w.errs <- io.EOF:\n\tdefault:\n\t}\n\treturn nil\n}"} {"input": "package fileutil\n\nimport (\n\t\"os\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\n\n\nfunc Fsync(f *os.File) error {\n\t_, err := unix.FcntlInt(f.Fd(), unix.F_FULLFSYNC, 0)\n\treturn err\n}\n\n\n\n\n\nfunc Fdatasync(f *os.File) error ", "output": "{\n\treturn Fsync(f)\n}"} {"input": "package remotecontext \n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n)\n\n\n\n\nfunc createTestTempDir(t *testing.T, dir, prefix string) (string, func()) {\n\tpath, err := os.MkdirTemp(dir, prefix)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error when creating directory %s with prefix %s: %s\", dir, prefix, err)\n\t}\n\n\treturn path, func() {\n\t\terr = os.RemoveAll(path)\n\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error when removing directory %s: %s\", path, err)\n\t\t}\n\t}\n}\n\n\n\n\n\n\n\n\n\n\nfunc createTestTempFile(t *testing.T, dir, filename, contents string, perm os.FileMode) string {\n\tfilePath := filepath.Join(dir, filename)\n\terr := os.WriteFile(filePath, []byte(contents), perm)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error when creating %s file: %s\", filename, err)\n\t}\n\n\treturn filePath\n}\n\nfunc createTestTempSubdir(t *testing.T, dir, prefix string) string ", "output": "{\n\tpath, err := os.MkdirTemp(dir, prefix)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error when creating directory %s with prefix %s: %s\", dir, prefix, err)\n\t}\n\n\treturn path\n}"} {"input": "package stats\n\nimport (\n\t\"time\"\n\n\t\"sync\"\n\n\t\"github.com/paulbellamy/ratecounter\"\n)\n\nvar lock = sync.RWMutex{}\n\ntype stat struct {\n\treadReq *ratecounter.RateCounter\n\twriteReq *ratecounter.RateCounter\n}\n\nfunc newStat() stat {\n\treturn stat{\n\t\treadReq: ratecounter.NewRateCounter(time.Hour),\n\t\twriteReq: ratecounter.NewRateCounter(time.Hour),\n\t}\n}\n\ntype namespaceStatMap map[string]stat\n\nvar golbalNamespaceStat namespaceStatMap\n\nfunc init() {\n\tgolbalNamespaceStat = namespaceStatMap{}\n}\n\n\n\n\n\nfunc IncrRead(label string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tstat, ok := golbalNamespaceStat[label]\n\tif !ok {\n\t\tAddNamespace(label)\n\t\tstat = golbalNamespaceStat[label]\n\t}\n\n\tstat.readReq.Incr(1)\n}\n\n\nfunc IncrWrite(label string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tstat, ok := golbalNamespaceStat[label]\n\tif !ok {\n\t\tAddNamespace(label)\n\t\tstat = golbalNamespaceStat[label]\n\t}\n\n\tstat.writeReq.Incr(1)\n}\n\n\nfunc Rate(label string) (read, write int64) {\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\tstat, ok := golbalNamespaceStat[label]\n\tif !ok {\n\t\tAddNamespace(label)\n\t\tstat = golbalNamespaceStat[label]\n\t}\n\n\treturn stat.readReq.Rate(), stat.writeReq.Rate()\n}\n\nfunc AddNamespace(label string) ", "output": "{\n\t_, ok := golbalNamespaceStat[label]\n\tif ok {\n\t\treturn\n\t}\n\n\tgolbalNamespaceStat[label] = newStat()\n\treturn\n}"} {"input": "package v1alpha1\n\nimport (\n\tv1alpha1 \"k8s.io/api/scheduling/v1alpha1\"\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\t\"github.com/hyperhq/client-go/kubernetes/scheme\"\n\trest \"github.com/hyperhq/client-go/rest\"\n)\n\ntype SchedulingV1alpha1Interface interface {\n\tRESTClient() rest.Interface\n\tPriorityClassesGetter\n}\n\n\ntype SchedulingV1alpha1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *SchedulingV1alpha1Client) PriorityClasses() PriorityClassInterface {\n\treturn newPriorityClasses(c)\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *SchedulingV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *SchedulingV1alpha1Client {\n\treturn &SchedulingV1alpha1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *SchedulingV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfig(c *rest.Config) (*SchedulingV1alpha1Client, error) ", "output": "{\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SchedulingV1alpha1Client{client}, nil\n}"} {"input": "package main\n\n\ntype MetricMap map[string]float64\n\n\ntype StatsInfo struct {\n\tlabels map[string]string\n\tmetrics MetricMap\n}\n\n\n\n\ntype RabbitReply interface {\n\tMakeMap() MetricMap\n\n\tMakeStatsInfo([]string) []StatsInfo\n\n\tGetString(key string) (string, bool)\n}\n\n\n\n\n\nfunc MakeReply(contentType string, body []byte) (RabbitReply, error) ", "output": "{\n\tif contentType == \"application/bert\" {\n\t\treturn makeBERTReply(body)\n\t}\n\treturn makeJSONReply(body)\n}"} {"input": "package ec2query\n\n\n\nimport (\n\t\"net/url\"\n\n\t\"github.com/aws/aws-sdk-go/aws/awserr\"\n\t\"github.com/aws/aws-sdk-go/aws/request\"\n\t\"github.com/aws/aws-sdk-go/private/protocol/query/queryutil\"\n)\n\n\n\n\nfunc Build(r *request.Request) ", "output": "{\n\tbody := url.Values{\n\t\t\"Action\": {r.Operation.Name},\n\t\t\"Version\": {r.ClientInfo.APIVersion},\n\t}\n\tif err := queryutil.Parse(body, r.Params, true); err != nil {\n\t\tr.Error = awserr.New(\"SerializationError\", \"failed encoding EC2 Query request\", err)\n\t}\n\n\tif r.ExpireTime == 0 {\n\t\tr.HTTPRequest.Method = \"POST\"\n\t\tr.HTTPRequest.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded; charset=utf-8\")\n\t\tr.SetBufferBody([]byte(body.Encode()))\n\t} else { \n\t\tr.HTTPRequest.Method = \"GET\"\n\t\tr.HTTPRequest.URL.RawQuery = body.Encode()\n\t}\n}"} {"input": "package vcf\n\nimport \"fmt\"\n\nconst _SVType_name = \"DeletionDuplicationInsertionInversionCopyNumberVariationTandemDuplicationDeletionMobileElementInsertionMobileElementBreakend\"\n\nvar _SVType_index = [...]uint8{0, 8, 19, 28, 37, 56, 73, 94, 116, 124}\n\n\n\nfunc (i SVType) String() string ", "output": "{\n\tif i < 0 || i >= SVType(len(_SVType_index)-1) {\n\t\treturn fmt.Sprintf(\"SVType(%d)\", i)\n\t}\n\treturn _SVType_name[_SVType_index[i]:_SVType_index[i+1]]\n}"} {"input": "package redis\n\nimport (\n\t\"github.com/fagongzi/goetty\"\n)\n\ntype redisDecoder struct {\n}\n\n\n\n\n\nfunc (decoder *redisDecoder) Decode(in *goetty.ByteBuf) (bool, interface{}, error) {\n\tcomplete, cmd, err := ReadCommand(in)\n\tif err != nil {\n\t\treturn true, nil, err\n\t}\n\n\tif !complete {\n\t\treturn false, nil, nil\n\t}\n\n\treturn true, cmd, nil\n}\n\ntype redisReplyDecoder struct {\n}\n\n\nfunc NewRedisReplyDecoder() goetty.Decoder {\n\treturn &redisReplyDecoder{}\n}\n\n\nfunc (decoder *redisReplyDecoder) Decode(in *goetty.ByteBuf) (bool, interface{}, error) {\n\tcomplete, cmd, err := readCommandReply(in)\n\tif err != nil {\n\t\treturn true, nil, err\n\t}\n\n\tif !complete {\n\t\treturn false, nil, nil\n\t}\n\n\treturn true, cmd, nil\n}\n\nfunc NewRedisDecoder() goetty.Decoder ", "output": "{\n\treturn &redisDecoder{}\n}"} {"input": "package convey\n\nimport (\n\t\"github.com/wallclockbuilder/convey/reporting\"\n)\n\ntype nilReporter struct{}\n\nfunc (self *nilReporter) BeginStory(story *reporting.StoryReport) {}\nfunc (self *nilReporter) Enter(scope *reporting.ScopeReport) {}\nfunc (self *nilReporter) Report(report *reporting.AssertionResult) {}\nfunc (self *nilReporter) Exit() {}\nfunc (self *nilReporter) EndStory() {}\nfunc (self *nilReporter) Write(p []byte) (int, error) { return len(p), nil }\n\n\nfunc newNilReporter() *nilReporter ", "output": "{ return &nilReporter{} }"} {"input": "package parsing\n\nimport (\n\t\"testing\"\n)\n\n\nfunc TestConcatIfNotEmpty(t *testing.T) {\n\tx := \"Hello World\"\n\toutput := ConcatIfNotEmpty(\" \", \"Hello\", \"\", \"World\")\n\tif x != output {\n\t\tt.Errorf(\"Unexpected output from ConcatIfNotEmpty: %s\", output)\n\t}\n}\n\nfunc TestParseIntOrDefault(t *testing.T) {\n\tout := ParseIntOrDefault(\"4\", 0)\n\tif out != 4 {\n\t\tt.Errorf(\"Unexpected output from ParseIntOrDefault: %s\", out)\n\t}\n\tout = ParseIntOrDefault(\"\", 5)\n\tif out != 5 {\n\t\tt.Errorf(\"Unexpected output from ParseIntOrDefault default: %s\", out)\n\t}\n}\n\n\n\nfunc TestParseYesOrNo(t *testing.T) ", "output": "{\n\tif !ParseYesOrNo(\"YES\") {\n\t\tt.Errorf(\"ParseYesOrNo returned false when it should return true\")\n\t}\n\tif !ParseYesOrNo(\"yes\") {\n\t\tt.Errorf(\"ParseYesOrNo returned false when it should return true\")\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CopyVolumeGroupBackupRequest struct {\n\n\tVolumeGroupBackupId *string `mandatory:\"true\" contributesTo:\"path\" name:\"volumeGroupBackupId\"`\n\n\tCopyVolumeGroupBackupDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CopyVolumeGroupBackupRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CopyVolumeGroupBackupRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CopyVolumeGroupBackupRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CopyVolumeGroupBackupRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CopyVolumeGroupBackupResponse struct {\n\n\tRawResponse *http.Response\n\n\tVolumeGroupBackup `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CopyVolumeGroupBackupResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response CopyVolumeGroupBackupResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package ctxhttp\n\nimport (\n\t\"net/http\"\n\n\t\"fmt\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\n\n\n\ntype Handler interface {\n\tServeHTTPContext(context.Context, http.ResponseWriter, *http.Request) error\n}\n\n\n\ntype HandlerFunc func(context.Context, http.ResponseWriter, *http.Request) error\n\n\n\n\n\nvar _ http.Handler = (*Adapter)(nil)\n\n\n\ntype Adapter struct {\n\tCtx context.Context \n\tHandler Handler \n\tErrorFunc AdapterErrFunc \n}\n\n\n\nfunc (ca *Adapter) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tif err := ca.Handler.ServeHTTPContext(ca.Ctx, rw, req); err != nil {\n\t\tca.ErrorFunc(rw, req, err)\n\t}\n}\n\n\nfunc NewAdapter(ctx context.Context, h Handler) *Adapter {\n\treturn &Adapter{\n\t\tCtx: ctx,\n\t\tHandler: h,\n\t\tErrorFunc: DefaultAdapterErrFunc,\n\t}\n}\n\n\ntype AdapterErrFunc func(http.ResponseWriter, *http.Request, error)\n\n\n\n\nvar DefaultAdapterErrFunc AdapterErrFunc = defaultAdapterErrFunc\n\nfunc defaultAdapterErrFunc(rw http.ResponseWriter, req *http.Request, err error) {\n\tcode := http.StatusBadRequest\n\thttp.Error(rw, fmt.Sprintf(\n\t\t\"%s\\nApp Error: %s\",\n\t\thttp.StatusText(code),\n\t\terr,\n\t), code)\n}\n\nfunc (h HandlerFunc) ServeHTTPContext(ctx context.Context, rw http.ResponseWriter, req *http.Request) error ", "output": "{\n\treturn h(ctx, rw, req)\n}"} {"input": "package automation\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" automation/2017-05-15-preview\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package parser\n\n\ntype Sequence struct {\n\tContent []Statement\n\tParent *Sequence \n}\n\n\n\n\nfunc (s Sequence) Undo() (string, error) {\n\tvar content string\n\n\tlength := len(s.Content)\n\tif length > 0 {\n\t\trepr, err := s.Content[0].Undo()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tcontent += repr\n\t}\n\n\tfor i := 1; i < length; i++ {\n\t\trepr, err := s.Content[i].Undo()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tcontent += \";\" + repr\n\t}\n\n\tcontent = \"\\\"\" + content + \"\\\"\"\n\n\treturn content, nil\n}\n\n\nfunc (s *Sequence) Last() *Statement {\n\tif len(s.Content) == 0 {\n\t\treturn nil\n\t}\n\n\treturn &s.Content[len(s.Content)-1]\n}\n\n\nfunc (s *Sequence) Add(command string) *Statement {\n\ts.Content = append(s.Content, Statement{Command: command})\n\n\treturn &s.Content[len(s.Content)-1]\n}\n\nfunc (s Sequence) String() (string, error) ", "output": "{\n\tvar content string\n\n\tif s.Parent != nil {\n\n\t\tlength := len(s.Content)\n\t\tif length > 0 {\n\t\t\trepr, err := s.Content[0].String()\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tcontent += repr\n\t\t}\n\n\t\tfor i := 1; i < length; i++ {\n\t\t\trepr, err := s.Content[i].String()\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tcontent += \";\" + repr\n\t\t}\n\n\t\tcontent = \"\\\"\" + content + \"\\\"\"\n\t} else {\n\n\t\tfor _, statement := range s.Content {\n\t\t\trepr, err := statement.String()\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tcontent += repr + \"\\n\"\n\t\t}\n\t}\n\n\treturn content, nil\n}"} {"input": "package inst\n\nimport (\n\t\"github.com/outbrain/orchestrator/go/config\"\n)\n\n\ntype Maintenance struct {\n\tMaintenanceId uint\n\tKey InstanceKey\n\tBeginTimestamp string\n\tSecondsElapsed uint\n\tIsActive bool\n\tOwner string\n\tReason string\n}\n\nvar maintenanceOwner string = \"\"\n\n\n\nfunc SetMaintenanceOwner(owner string) {\n\tmaintenanceOwner = owner\n}\n\nfunc GetMaintenanceOwner() string ", "output": "{\n\tif maintenanceOwner != \"\" {\n\t\treturn maintenanceOwner\n\t}\n\treturn config.Config.MaintenanceOwner\n}"} {"input": "package lbaas\n\nimport (\n\t\"testing\"\n\n\t\"github.com/gophercloud/gophercloud/acceptance/clients\"\n\t\"github.com/gophercloud/gophercloud/acceptance/tools\"\n\t\"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/lbaas/monitors\"\n)\n\nfunc TestMonitorsList(t *testing.T) {\n\tclient, err := clients.NewNetworkV2Client()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create a network client: %v\", err)\n\t}\n\n\tallPages, err := monitors.List(client, monitors.ListOpts{}).AllPages()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to list monitors: %v\", err)\n\t}\n\n\tallMonitors, err := monitors.ExtractMonitors(allPages)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to extract monitors: %v\", err)\n\t}\n\n\tfor _, monitor := range allMonitors {\n\t\ttools.PrintResource(t, monitor)\n\t}\n}\n\n\n\nfunc TestMonitorsCRUD(t *testing.T) ", "output": "{\n\tclient, err := clients.NewNetworkV2Client()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create a network client: %v\", err)\n\t}\n\n\tmonitor, err := CreateMonitor(t, client)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create monitor: %v\", err)\n\t}\n\tdefer DeleteMonitor(t, client, monitor.ID)\n\n\ttools.PrintResource(t, monitor)\n\n\tupdateOpts := monitors.UpdateOpts{\n\t\tDelay: 999,\n\t}\n\n\t_, err = monitors.Update(client, monitor.ID, updateOpts).Extract()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to update monitor: %v\")\n\t}\n\n\tnewMonitor, err := monitors.Get(client, monitor.ID).Extract()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to get monitor: %v\")\n\t}\n\n\ttools.PrintResource(t, newMonitor)\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nvar router *gin.Engine\n\nfunc main() {\n\tgin.SetMode(gin.ReleaseMode)\n\n\trouter = gin.Default()\n\n\trouter.LoadHTMLGlob(\"templates/*\")\n\n\tinitializeRoutes()\n\n\trouter.Run()\n}\n\n\n\n\n\n\nfunc render(c *gin.Context, data gin.H, templateName string) ", "output": "{\n\tloggedInInterface, _ := c.Get(\"is_logged_in\")\n\tdata[\"is_logged_in\"] = loggedInInterface.(bool)\n\n\tswitch c.Request.Header.Get(\"Accept\") {\n\tcase \"application/json\":\n\t\tc.JSON(http.StatusOK, data[\"payload\"])\n\tcase \"application/xml\":\n\t\tc.XML(http.StatusOK, data[\"payload\"])\n\tdefault:\n\t\tc.HTML(http.StatusOK, templateName, data)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gourd/goparser\"\n\t\"github.com/gourd/gourd/compile\"\n\t\"github.com/gourd/gourd/templates\"\n)\n\nfunc init() {\n\tt, err := templates.Asset(\"store/upperio.tpl\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttpls.Append(\"gen store:upperio\", string(t))\n\ttpls.AddDeps(\"gen store:upperio\", \"gen:general\")\n\ttpls.AddPrep(\"gen store:upperio\", func(in interface{}) (interface{}, error) {\n\t\tvar data map[string]interface{}\n\t\tvar f interface{}\n\t\tvar id *goparser.FieldSpec\n\t\tvar ok bool\n\n\t\tif data, ok = in.(compile.Context); !ok {\n\t\t\treturn in, fmt.Errorf(\"Unable to prepare. Incorrect data provided: %#v\", in)\n\t\t}\n\n\t\tif f, ok = data[\"Id\"]; !ok {\n\t\t\treturn in, fmt.Errorf(\"Unable to prepare. No Id found in given data: %#v\",\n\t\t\t\tdata)\n\t\t}\n\n\t\tif id, ok = f.(*goparser.FieldSpec); !ok {\n\t\t\treturn in, fmt.Errorf(\"Unable to prepare. Wrong Id type: %#v\", f)\n\t\t}\n\n\t\tdata[\"Id\"] = &UpperFieldSpec{\n\t\t\tid,\n\t\t}\n\t\treturn data, nil\n\t})\n}\n\n\n\ntype UpperFieldSpec struct {\n\t*goparser.FieldSpec\n}\n\n\n\n\n\nfunc (s *UpperFieldSpec) IsInt() bool {\n\treturn s.Type == \"int\" || s.Type == \"uint\" ||\n\t\ts.Type == \"int32\" || s.Type == \"uint32\" ||\n\t\ts.Type == \"int64\" || s.Type == \"uint64\"\n}\n\nfunc (s UpperFieldSpec) IsString() bool ", "output": "{\n\treturn s.Type == \"string\"\n}"} {"input": "package sodium\n\n\n\n\nimport \"C\"\n\n\n\nfunc RuntimeHasSse2() bool {\n\treturn C.sodium_runtime_has_sse2() != 0\n}\n\nfunc RuntimeHasSse3() bool {\n\treturn C.sodium_runtime_has_sse3() != 0\n}\n\nfunc RuntimeHasNeon() bool ", "output": "{\n\treturn C.sodium_runtime_has_neon() != 0\n}"} {"input": "package helpers\n\nimport \"testing\"\n\n\n\nfunc TestIsRegionNormalized(t *testing.T) {\n\tcases := []struct {\n\t\tinput string\n\t\texpectedResult string\n\t}{\n\t\t{\n\t\t\tinput: \"westus\",\n\t\t\texpectedResult: \"westus\",\n\t\t},\n\t\t{\n\t\t\tinput: \"West US\",\n\t\t\texpectedResult: \"westus\",\n\t\t},\n\t\t{\n\t\t\tinput: \"Eastern Africa\",\n\t\t\texpectedResult: \"easternafrica\",\n\t\t},\n\t\t{\n\t\t\tinput: \"\",\n\t\t\texpectedResult: \"\",\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tresult := NormalizeAzureRegion(c.input)\n\t\tif c.expectedResult != result {\n\t\t\tt.Fatalf(\"NormalizeAzureRegion returned unexpected result: expected %s but got %s\", c.expectedResult, result)\n\t\t}\n\t}\n}\n\nfunc TestPointerToBool(t *testing.T) ", "output": "{\n\tboolVar := true\n\tret := PointerToBool(boolVar)\n\tif *ret != boolVar {\n\t\tt.Fatalf(\"expected PointerToBool(true) to return *true, instead returned %#v\", ret)\n\t}\n}"} {"input": "package rpc\n\nimport (\n \"github.com/golang/glog\"\n \"github.com/nebulaim/telegramd/proto/mtproto\"\n \"golang.org/x/net/context\"\n \"github.com/nebulaim/telegramd/baselib/grpc_util\"\n \"github.com/nebulaim/telegramd/baselib/logger\"\n)\n\n\n\n\nfunc (s *MessagesServiceImpl) MessagesGetHistoryLayer51(ctx context.Context, request *mtproto.TLMessagesGetHistoryLayer51) (*mtproto.Messages_Messages, error) ", "output": "{\n md := grpc_util.RpcMetadataFromIncoming(ctx)\n glog.Infof(\"messages.getHistory#afa92846 - metadata: %s, request: %s\", logger.JsonDebugData(md), logger.JsonDebugData(request))\n\n request2 := &mtproto.TLMessagesGetHistory{\n Peer: request.GetPeer(),\n OffsetId: request.GetOffsetId(),\n OffsetDate: request.GetOffsetDate(),\n AddOffset: request.GetAddOffset(),\n Limit: request.GetLimit(),\n MaxId: request.GetMaxId(),\n MinId: request.GetMinId(),\n Hash: 0,\n }\n messagesMessages := s.getHistoryMessages(md, request2)\n\n glog.Infof(\"messages.getHistory#dcbb8260 - reply: %s\", logger.JsonDebugData(messagesMessages))\n return messagesMessages, nil\n}"} {"input": "package main\n\nimport (\n\t\"math\"\n\t\"sort\"\n)\n\ntype NaiveSieve struct {\n\tsieve map[int]bool\n}\n\nfunc NewNaiveSieve(limit int) NaiveSieve {\n\n\tprimes := make(map[int]bool)\n\n\tprimes[2] = true\n\n\tfor n := 3; n < limit; n += 2 {\n\t\tif IsNaivePrime(n) {\n\t\t\tprimes[n] = true\n\t\t}\n\t}\n\n\treturn NaiveSieve{primes}\n}\n\nfunc (self *NaiveSieve) Contains(n int) bool {\n\t_, ok := self.sieve[n]\n\treturn ok\n}\n\n\n\nfunc IsNaivePrime(n int) bool {\n\tswitch {\n\tcase n == 1:\n\t\treturn false\n\tcase n == 2:\n\t\treturn true\n\tcase n%2 == 0:\n\t\treturn false\n\t}\n\n\tlimit := int(math.Sqrt(float64(n)))\n\n\tfor i := 3; i <= limit; i += 2 {\n\t\tif n%i == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (self *NaiveSieve) Primes() []int ", "output": "{\n\tprimes := make([]int, 0, len(self.sieve))\n\tfor n, _ := range self.sieve {\n\t\tprimes = append(primes, n)\n\t}\n\tsort.Ints(primes)\n\treturn primes\n}"} {"input": "package routing\n\nimport \"net/http\"\n\n\n\n\n\nfunc GET(handler http.Handler) Matcher {\n\treturn Method(\"GET\", handler)\n}\n\n\nfunc GETFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn GET(http.HandlerFunc(handler))\n}\n\n\nfunc POST(handler http.Handler) Matcher {\n\treturn Method(\"POST\", handler)\n}\n\n\nfunc POSTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn POST(http.HandlerFunc(handler))\n}\n\n\nfunc PUT(handler http.Handler) Matcher {\n\treturn Method(\"PUT\", handler)\n}\n\n\nfunc PUTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PUT(http.HandlerFunc(handler))\n}\n\n\nfunc PATCH(handler http.Handler) Matcher {\n\treturn Method(\"PATCH\", handler)\n}\n\n\nfunc PATCHFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PATCH(http.HandlerFunc(handler))\n}\n\n\nfunc DELETE(handler http.Handler) Matcher {\n\treturn Method(\"DELETE\", handler)\n}\n\n\nfunc DELETEFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn DELETE(http.HandlerFunc(handler))\n}\n\n\n\nfunc MethodNotAllowed(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\tresp.WriteHeader(405)\n\treturn true\n}\n\nfunc Method(method string, handler http.Handler) Matcher ", "output": "{\n\treturn func(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\t\tif req.Method == method {\n\t\t\thandler.ServeHTTP(resp, req)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}"} {"input": "package proj\n\nconst (\n\tutmLetters = \"CDEFGHJKLMNPQRSTUVWXX\"\n)\n\nvar (\n\tUTMZones = map[int]*TransverseMercator{}\n)\n\n\nfunc utmZone(zone int) *TransverseMercator {\n\treturn &TransverseMercator{\n\t\tcode: 32600 + zone,\n\t\tf0: 0.9996,\n\t\tlat0: rad(0),\n\t\tlon0: rad(6*(30-float64(zone)) + 3),\n\t\te0: 500000,\n\t\tn0: 0,\n\t\te: International1924,\n\t}\n}\n\n\n\n\n\nfunc LatLongUTMLetter(lat, lon float64) byte {\n\tif lat < -80 || 84 <= lat {\n\t\treturn 0\n\t}\n\ti := int((lat + 80) / 8)\n\treturn utmLetters[i]\n}\n\nfunc initUTM() {\n\tfor z := 1; z <= 60; z++ {\n\t\tUTMZones[z] = utmZone(z)\n\t}\n}\n\nfunc LatLongUTMZone(lat, lon float64) int ", "output": "{\n\tswitch {\n\tcase 56 <= lat && lat < 64 && 3 <= lon && lon < 12:\n\t\treturn 32\n\tcase 72 <= lat && lat < 84 && 0 <= lon && lon < 42:\n\t\tswitch {\n\t\tcase lon < 9:\n\t\t\treturn 31\n\t\tcase lon < 21:\n\t\t\treturn 33\n\t\tcase lon < 33:\n\t\t\treturn 35\n\t\tdefault:\n\t\t\treturn 37\n\t\t}\n\tdefault:\n\t\treturn int(lon+180)/6 + 1\n\t}\n}"} {"input": "package overview\n\nimport (\n\t\"appengine\"\n\n\th \"github.com/czertbytes/pocket/pkg/http\"\n\tt \"github.com/czertbytes/pocket/pkg/types\"\n)\n\ntype Notificator struct {\n\tAppEngineContext appengine.Context\n\tRequestContext *h.RequestContext\n}\n\nfunc NewNotificator(RequestContext *h.RequestContext) *Notificator {\n\treturn &Notificator{\n\t\tAppEngineContext: RequestContext.AppEngineContext,\n\t\tRequestContext: RequestContext,\n\t}\n}\n\nfunc (self *Notificator) Create(overview *t.Overview) error {\n\treturn nil\n}\n\nfunc (self *Notificator) Update(overview *t.Overview) error {\n\treturn nil\n}\n\nfunc (self *Notificator) CreatePayment(payment *t.Payment) error {\n\treturn nil\n}\n\n\n\nfunc (self *Notificator) CreateParticipant(participant *t.User) error ", "output": "{\n\treturn nil\n}"} {"input": "package desk\n\nimport (\n \"github.com/stianeikeland/go-rpio\"\n)\n\ntype Direction uint8\n\nvar (\n upPin rpio.Pin\n downPin rpio.Pin\n)\n\nconst (\n Down Direction = iota\n Up\n)\n\nfunc Move(dir Direction) {\n Stop()\n if (dir == Up) {\n upPin.High()\n } else {\n downPin.High()\n }\n}\n\nfunc Stop() {\n upPin.Low()\n downPin.Low()\n}\n\nfunc Init(up int, down int) (err error) {\n err = rpio.Open()\n\n if (err != nil) {\n return\n }\n\n upPin = rpio.Pin(up)\n upPin.Output()\n upPin.Low()\n\n downPin = rpio.Pin(down)\n downPin.Output()\n downPin.Low()\n\n return nil\n}\n\n\n\nfunc Close() ", "output": "{\n rpio.Close()\n}"} {"input": "package billing\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/billing/mgmt/2017-04-24-preview/billing\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype ManagementClient = original.ManagementClient\ntype InvoicesClient = original.InvoicesClient\ntype DownloadURL = original.DownloadURL\ntype ErrorDetails = original.ErrorDetails\ntype ErrorResponse = original.ErrorResponse\ntype Invoice = original.Invoice\ntype InvoiceProperties = original.InvoiceProperties\ntype InvoicesListResult = original.InvoicesListResult\ntype Operation = original.Operation\ntype OperationDisplay = original.OperationDisplay\ntype OperationListResult = original.OperationListResult\ntype Period = original.Period\ntype PeriodProperties = original.PeriodProperties\ntype PeriodsListResult = original.PeriodsListResult\ntype Resource = original.Resource\ntype OperationsClient = original.OperationsClient\ntype PeriodsClient = original.PeriodsClient\n\nfunc NewOperationsClient(subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClient(subscriptionID)\n}\nfunc NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)\n}\n\nfunc NewPeriodsClientWithBaseURI(baseURI string, subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\nfunc New(subscriptionID string) ManagementClient {\n\treturn original.New(subscriptionID)\n}\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewInvoicesClient(subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClient(subscriptionID)\n}\nfunc NewInvoicesClientWithBaseURI(baseURI string, subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClientWithBaseURI(baseURI, subscriptionID)\n}\n\nfunc NewPeriodsClient(subscriptionID string) PeriodsClient ", "output": "{\n\treturn original.NewPeriodsClient(subscriptionID)\n}"} {"input": "package term \n\nimport \"io\"\n\ntype Db []Term\n\nfunc NewDb(args []Term) Db {\n\treturn Db(args)\n}\n\n\n\n\ntype Query struct {\n\tdb Db\n\tname string\n\tarity int\n}\n\n\n\n\nfunc (db Db) NewQuery(t Term) *Query {\n\treturn &Query{\n\t\tdb: db,\n\t\tname: Name(t),\n\t\tarity: Arity(t),\n\t}\n}\n\n\n\nfunc (q *Query) Run() *Cursor {\n\treturn &Cursor{\n\t\tq: q,\n\t\ti: 0,\n\t}\n}\n\n\ntype Cursor struct {\n\tq *Query\n\ti int\n}\n\nfunc (c *Cursor) Next() (Term, bool) {\n\tfor ; c.i < len(c.q.db); c.i++ {\n\t\tcandidate := c.q.db[c.i]\n\t\tif Arity(candidate) == c.q.arity && Name(candidate) == c.q.name {\n\t\t\tc.i++\n\t\t\treturn candidate, c.i < len(c.q.db)\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc (s Db) Format(w io.Writer, style Style) ", "output": "{\n\tisRoot := style.IsRoot\n\tstyle.IsRoot = false \n\n\tprevName := \"#\" \n\tfor _, t := range s {\n\t\tif isRoot {\n\t\t\tname := Name(t)\n\t\t\tif prevName != \"#\" && prevName != name {\n\t\t\t\tio.WriteString(w, \"\\n\")\n\t\t\t}\n\t\t\tprevName = name\n\t\t}\n\n\t\tstyle.WriteIndent(w)\n\t\tt.Format(w, style)\n\t}\n}"} {"input": "package audio\n\nimport (\n\t\"github.com/oakmound/oak/v3/audio/klang\"\n\t\"github.com/oakmound/oak/v3/audio/klang/filter\"\n\t\"github.com/oakmound/oak/v3/audio/klang/filter/supports\"\n\t\"github.com/oakmound/oak/v3/physics\"\n)\n\n\n\ntype SupportsPos interface {\n\tsupports.Encoding\n\tXp() *float64\n\tYp() *float64\n}\n\nvar (\n\t_ klang.Filter = Pos(func(SupportsPos) {})\n)\n\n\ntype Pos func(SupportsPos)\n\n\n\n\n\n\n\n\nfunc PosFilter(e *Ears) Pos {\n\treturn func(sp SupportsPos) {\n\t\tfilter.AssertStereo()(sp)\n\t\tx := sp.Xp()\n\t\tif x != nil {\n\t\t\tp := e.CalculatePan(*x)\n\t\t\tfilter.Pan(p)(sp)\n\t\t\ty := sp.Yp()\n\t\t\tif y != nil {\n\t\t\t\tv := e.CalculateVolume(physics.NewVector(*x, *y))\n\t\t\t\tfilter.Volume(v)(sp)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (xp Pos) Apply(a klang.Audio) (klang.Audio, error) ", "output": "{\n\tif sxp, ok := a.(SupportsPos); ok {\n\t\txp(sxp)\n\t\treturn a, nil\n\t}\n\treturn a, nil \n}"} {"input": "package azidentity\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy\"\n)\n\nfunc TestUsernamePasswordCredential_InvalidTenantID(t *testing.T) {\n\tcred, err := NewUsernamePasswordCredential(badTenantID, fakeClientID, \"username\", \"password\", nil)\n\tif err == nil {\n\t\tt.Fatal(\"Expected an error but received none\")\n\t}\n\tif cred != nil {\n\t\tt.Fatalf(\"Expected a nil credential value. Received: %v\", cred)\n\t}\n}\n\nfunc TestUsernamePasswordCredential_GetTokenSuccess(t *testing.T) {\n\tcred, err := NewUsernamePasswordCredential(fakeTenantID, fakeClientID, \"username\", \"password\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create credential. Received: %v\", err)\n\t}\n\tcred.client = fakePublicClient{}\n\t_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{liveTestScope}})\n\tif err != nil {\n\t\tt.Fatalf(\"Expected an empty error but received: %s\", err.Error())\n\t}\n}\n\nfunc TestUsernamePasswordCredential_Live(t *testing.T) {\n\to, stop := initRecording(t)\n\tdefer stop()\n\topts := UsernamePasswordCredentialOptions{ClientOptions: o}\n\tcred, err := NewUsernamePasswordCredential(liveUser.tenantID, developerSignOnClientID, liveUser.username, liveUser.password, &opts)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create credential. Received: %v\", err)\n\t}\n\ttestGetTokenSuccess(t, cred)\n}\n\n\n\nfunc TestUsernamePasswordCredential_InvalidPasswordLive(t *testing.T) ", "output": "{\n\to, stop := initRecording(t)\n\tdefer stop()\n\topts := UsernamePasswordCredentialOptions{ClientOptions: o}\n\tcred, err := NewUsernamePasswordCredential(liveUser.tenantID, developerSignOnClientID, liveUser.username, \"invalid password\", &opts)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create credential. Received: %v\", err)\n\t}\n\ttk, err := cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{liveTestScope}})\n\tif tk != nil {\n\t\tt.Fatal(\"GetToken returned a token\")\n\t}\n\tvar e AuthenticationFailedError\n\tif !errors.As(err, &e) {\n\t\tt.Fatal(\"expected AuthenticationFailedError\")\n\t}\n\tif e.RawResponse == nil {\n\t\tt.Fatal(\"expected a non-nil RawResponse\")\n\t}\n}"} {"input": "package sha512\n\nimport (\n\t\"bytes\"\n\t\"encoding/hex\"\n\t\"testing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype MySuite struct{}\n\nvar _ = Suite(&MySuite{})\n\n\n\nfunc (s *MySuite) TestSha512Stream(c *C) ", "output": "{\n\ttestString := []byte(\"Test string\")\n\texpectedHash, _ := hex.DecodeString(\"811aa0c53c0039b6ead0ca878b096eed1d39ed873fd2d2d270abfb9ca620d3ed561c565d6dbd1114c323d38e3f59c00df475451fc9b30074f2abda3529df2fa7\")\n\thash, err := Sum(bytes.NewBuffer(testString))\n\tc.Assert(err, IsNil)\n\tc.Assert(bytes.Equal(expectedHash, hash), Equals, true)\n}"} {"input": "package handlers\n\nimport (\n\t\"fmt\"\n\t\"github.com/ahmedkamals/foo-protocol-proxy/analysis\"\n\t\"log\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype (\n\tMetricsHandler struct {\n\t\tanalyzer *analysis.Analyzer\n\t\tlogger *log.Logger\n\t}\n)\n\n\n\nconst CommonLogFormat string = \"%s %s %s [%s] \\\"%s %s %s\\\" %d %d\"\n\n\n\n\nfunc (m *MetricsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tcontentType := r.Header.Get(\"Content-Type\")\n\n\tif contentType == \"\" {\n\t\tcontentType = \"application/json\"\n\t}\n\n\tw.Header().Set(\"Content-Type\", contentType)\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.WriteHeader(http.StatusOK)\n\n\tresponse, err := m.analyzer.Report()\n\n\tif err != nil {\n\t\tm.logger.Println(err)\n\t\t_, err = w.Write([]byte(fmt.Sprintf(\"{error: %s}\", err.Error())))\n\t\tif err != nil {\n\t\t\tm.logger.Println(err)\n\t\t}\n\t}\n\n\t_, err = w.Write([]byte(response))\n\tif err != nil {\n\t\tm.logger.Println(err)\n\t}\n\n\tm.logger.Printf(\n\t\tCommonLogFormat,\n\t\tr.RemoteAddr,\n\t\t\"-\",\n\t\t\"-\",\n\t\ttime.Now().Format(\"01/Jan/2006:15:04:05 -0700\"),\n\t\tr.Method,\n\t\tr.URL.Path,\n\t\tr.Proto,\n\t\thttp.StatusOK,\n\t\tlen(response),\n\t)\n}\n\nfunc NewMetricsHandler(analyzer *analysis.Analyzer, logger *log.Logger) http.Handler ", "output": "{\n\treturn &MetricsHandler{\n\t\tanalyzer: analyzer,\n\t\tlogger: logger,\n\t}\n}"} {"input": "package MySQLProtocol\n\nimport \"testing\"\nimport \"github.com/stretchr/testify/assert\"\n\nvar COM_STMT_FETCH_test_packets = []struct {\n\tpacket Proto\n\tcontext Context\n}{\n\t{packet: Proto{data: StringToPacket(`\n09 00 00 00 1c 00 00 00 00 00 00 00 00\n`)}, context: Context{}},\n}\n\n\n\nfunc Benchmark_Packet_COM_STMT_FETCH_FromPacket(b *testing.B) {\n\tcontext := COM_STMT_FETCH_test_packets[0].context\n\tpacket := COM_STMT_FETCH_test_packets[0].packet\n\tpkt := Packet_COM_STMT_FETCH{}\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tpacket.offset = 0\n\t\tpkt.FromPacket(context, packet)\n\t}\n}\n\nfunc Benchmark_Packet_COM_STMT_FETCH_GetPacketSize(b *testing.B) {\n\tcontext := COM_STMT_FETCH_test_packets[0].context\n\tpkt := Packet_COM_STMT_FETCH{}\n\tpkt.FromPacket(context, COM_STMT_FETCH_test_packets[0].packet)\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt.GetPacketSize(context)\n\t}\n}\n\nfunc Benchmark_Packet_COM_STMT_FETCH_ToPacket(b *testing.B) {\n\tcontext := COM_STMT_FETCH_test_packets[0].context\n\tpkt := Packet_COM_STMT_FETCH{}\n\tpkt.FromPacket(context, COM_STMT_FETCH_test_packets[0].packet)\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt.ToPacket(context)\n\t}\n}\n\nfunc Test_Packet_COM_STMT_FETCH(t *testing.T) ", "output": "{\n\tvar pkt Packet_COM_STMT_FETCH\n\tfor _, value := range COM_STMT_FETCH_test_packets {\n\t\tpkt = Packet_COM_STMT_FETCH{}\n\t\tpkt.FromPacket(value.context, value.packet)\n\t\tassert.Equal(t, pkt.ToPacket(value.context), value.packet.data, \"\")\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"reflect\"\n\t\"runtime\"\n\t\"testing\"\n)\n\n\n\nfunc assertFatal(t *testing.T, actual interface{}, expected interface{}) {\n\tif !reflect.DeepEqual(actual, expected) {\n\t\t_, fn, line, _ := runtime.Caller(1)\n\t\tt.Fatalf(\"Expected %v, actual %v\\n@%s:%d\", expected, actual, fn, line)\n\t}\n}\n\nfunc assertNot(t *testing.T, actual interface{}, expected interface{}) {\n\tif reflect.DeepEqual(actual, expected) {\n\t\t_, fn, line, _ := runtime.Caller(1)\n\t\tt.Fatalf(\"Expected anything but %v, actual %v\\n@%s:%d\", expected, actual, fn, line)\n\t}\n}\n\nfunc assert(t *testing.T, actual interface{}, expected interface{}) ", "output": "{\n\tif !reflect.DeepEqual(actual, expected) {\n\t\t_, fn, line, _ := runtime.Caller(1)\n\t\tt.Errorf(\"Expected %v, actual %v\\n@%s:%d\", expected, actual, fn, line)\n\t}\n}"} {"input": "package module\n\nimport (\n\t\"encoding/gob\"\n\t\"fmt\"\n\t\"github.com/glennyonemitsu/reicon/system/activity\"\n\t\"net\"\n\t\"os\"\n)\n\ntype Module struct {\n\tName string\n\tActivities []*activity.Activity\n\tServerSocket *net.UnixConn\n\tSocketAddr *net.UnixAddr\n\tListener *net.UnixListener\n}\n\nfunc (m *Module) Run() {\n\tsocket_path := os.Getenv(\"REICON_SYSTEM_SOCKET\")\n\tm.SocketAddr = new(net.UnixAddr)\n\tm.SocketAddr.Name = \"unix\"\n\tm.SocketAddr.Net = socket_path\n\tm.Listener, _ = net.ListenUnix(\"unix\", m.SocketAddr)\n\tm.ListenSocket()\n\n}\n\nfunc (m *Module) ListenSocket() {\n\tfor {\n\t\tconn, err := m.Listener.AcceptUnix()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tgo m.handleUnixConnection(conn)\n\t}\n}\n\nfunc (m *Module) handleUnixConnection(conn *net.UnixConn) {\n\tvar msg string\n\tenc := gob.NewEncoder(conn)\n\tdec := gob.NewDecoder(conn)\n\tdec.Decode(&msg)\n\tenc.Encode(fmt.Sprintf(\"your message was: %s\", msg))\n}\n\nfunc (m *Module) Shutdown() {\n\tm.ServerSocket.Close()\n}\n\nfunc (m *Module) RegisterActivity(name string) *activity.Activity {\n\ta := new(activity.Activity)\n\ta.Name = name\n\tm.Activities = append(m.Activities, a)\n\treturn a\n}\n\n\n\nfunc Create(name string) *Module ", "output": "{\n\tm := new(Module)\n\tm.Name = name\n\treturn m\n}"} {"input": "package logger\n\nimport (\n\t\"strings\"\n)\n\nfunc hasFlag(has int, flags ...int) bool {\n\tfor _, flag := range flags {\n\t\tif flag&has != 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\n\nfunc convertStamp(format string) string {\n\tfor _, k := range tsMap {\n\t\tformat = strings.Replace(format, k, string(tsFmtMap[k]), -1)\n\t}\n\treturn format\n}\n\n\n\n\nvar tsMap = []string{\"05.000000\", \"Monday\", \"January\", \"2006\", \"-0700\", \"MST\", \"Mon\", \"Jan\", \"02\", \"15\", \"04\", \"05\", \"01\", \"06\", \"03\", \"pm\"}\n\nfunc KV(k K, v V) KeyVal ", "output": "{\n\treturn KeyVal{k, v}\n}"} {"input": "package app\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"k8s.io/kubernetes/pkg/apis/batch\"\n\t\"k8s.io/kubernetes/pkg/client/clientset_generated/clientset\"\n\t\"k8s.io/kubernetes/pkg/controller/cronjob\"\n\t\"k8s.io/kubernetes/pkg/controller/job\"\n)\n\nfunc startJobController(ctx ControllerContext) (bool, error) {\n\tif !ctx.AvailableResources[schema.GroupVersionResource{Group: \"batch\", Version: \"v1\", Resource: \"jobs\"}] {\n\t\treturn false, nil\n\t}\n\tgo job.NewJobController(\n\t\tctx.NewInformerFactory.Core().V1().Pods(),\n\t\tctx.NewInformerFactory.Batch().V1().Jobs(),\n\t\tctx.ClientBuilder.ClientOrDie(\"job-controller\"),\n\t).Run(int(ctx.Options.ConcurrentJobSyncs), ctx.Stop)\n\treturn true, nil\n}\n\n\n\nfunc startCronJobController(ctx ControllerContext) (bool, error) ", "output": "{\n\tif !ctx.AvailableResources[schema.GroupVersionResource{Group: \"batch\", Version: \"v2alpha1\", Resource: \"cronjobs\"}] {\n\t\treturn false, nil\n\t}\n\tcronjobConfig := ctx.ClientBuilder.ConfigOrDie(\"cronjob-controller\")\n\tcronjobConfig.ContentConfig.GroupVersion = &schema.GroupVersion{Group: batch.GroupName, Version: \"v2alpha1\"}\n\tgo cronjob.NewCronJobController(\n\t\tclientset.NewForConfigOrDie(cronjobConfig),\n\t).Run(ctx.Stop)\n\treturn true, nil\n}"} {"input": "package version\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\n\tapimachineryversion \"k8s.io/apimachinery/pkg/version\"\n)\n\nvar (\n\tcommitFromGit string\n\tversionFromGit = \"unknown\"\n\tmajorFromGit string\n\tminorFromGit string\n\tbuildDate string\n\tgitTreeState string\n)\n\n\n\n\n\nfunc init() {\n\tbuildInfo := prometheus.NewGaugeVec(\n\t\tprometheus.GaugeOpts{\n\t\t\tName: \"openshift_acme_build_info\",\n\t\t\tHelp: \"A metric with a constant '1' value labeled by major, minor, git commit & git version from which openshift-acme was built.\",\n\t\t},\n\t\t[]string{\"major\", \"minor\", \"gitCommit\", \"gitVersion\"},\n\t)\n\tbuildInfo.WithLabelValues(majorFromGit, minorFromGit, commitFromGit, versionFromGit).Set(1)\n\n\tprometheus.MustRegister(buildInfo)\n}\n\nfunc Get() apimachineryversion.Info ", "output": "{\n\treturn apimachineryversion.Info{\n\t\tMajor: majorFromGit,\n\t\tMinor: minorFromGit,\n\t\tGitCommit: commitFromGit,\n\t\tGitVersion: versionFromGit,\n\t\tGitTreeState: gitTreeState,\n\t\tBuildDate: buildDate,\n\t\tGoVersion: runtime.Version(),\n\t\tCompiler: runtime.Compiler,\n\t\tPlatform: fmt.Sprintf(\"%s/%s\", runtime.GOOS, runtime.GOARCH),\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"regexp\"\n\t\"testing\"\n)\n\nfunc Test_GcSuiteRePass(t *testing.T) {\n\tfind_suite := regexp.MustCompile(gc_endRE).FindStringSubmatch\n\ttokens := find_suite(\"PASS: mmath_test.go:16: MySuite.TestAdd\t0.000s\")\n\n\tfor i, expected := range []string{\"PASS\", \"MySuite\", \"TestAdd\", \"0.000\"} {\n\t\tcheckExpected(t, expected, tokens[i+1])\n\t}\n}\n\n\n\nfunc Test_GcSuiteReSkip(t *testing.T) {\n\tfind_suite := regexp.MustCompile(gc_endRE).FindStringSubmatch\n\ttokens := find_suite(\"SKIP: mmath_test.go:35: MySuite.TestMul (not implemented)\")\n\n\tfor i, expected := range []string{\"SKIP\", \"MySuite\", \"TestMul\", \"\"} {\n\t\tcheckExpected(t, expected, tokens[i+1])\n\t}\n}\n\nfunc checkExpected(t *testing.T, expected string, actual string) {\n\tif actual != expected {\n\t\tt.Fatalf(\"Expected %s but was %s\\n\", expected, actual)\n\t}\n}\n\nfunc Test_GcSuiteReFail(t *testing.T) ", "output": "{\n\tfind_suite := regexp.MustCompile(gc_endRE).FindStringSubmatch\n\ttokens := find_suite(\"FAIL: mmath_test.go:35: MySuite.TestDiv\")\n\n\tfor i, expected := range []string{\"FAIL\", \"MySuite\", \"TestDiv\", \"\"} {\n\t\tcheckExpected(t, expected, tokens[i+1])\n\t}\n}"} {"input": "package mungerutil\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\ntype testLTG struct {\n\tnumber int\n\tlabel string\n\ttime time.Time\n}\n\n\nfunc (t *testLTG) FirstLabelTime(label string) *time.Time {\n\tif label == t.label {\n\t\treturn &t.time\n\t}\n\treturn nil\n}\n\nfunc TestFirstLabelCache(t *testing.T) {\n\ttimeA := time.Now()\n\ttimeB := timeA.Add(time.Minute)\n\ttable := []struct {\n\t\tobj testLTG\n\t\texpect time.Time\n\t}{\n\t\t{testLTG{1, \"lgtm\", timeA}, timeA},\n\n\t\t{testLTG{2, \"blah\", timeA}, time.Time{}},\n\n\t\t{testLTG{1, \"lgtm\", timeB}, timeA},\n\n\t\t{testLTG{2, \"lgtm\", timeB}, timeB},\n\t}\n\n\tcache := NewLabelTimeCache(\"lgtm\")\n\tfor i, tt := range table {\n\t\tgot, ok := cache.FirstLabelTime(&tt.obj)\n\t\tif e := (tt.expect != time.Time{}); e != ok {\n\t\t\tt.Errorf(\"%v: Expected %v, got %v\", i, e, ok)\n\t\t\tcontinue\n\t\t}\n\t\tif got != tt.expect {\n\t\t\tt.Errorf(\"%v: Expected %v, got %v\", i, tt.expect, got)\n\t\t}\n\t}\n}\n\nfunc (t *testLTG) Number() int ", "output": "{ return t.number }"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\tosexec \"os/exec\"\n\t\"path/filepath\"\n)\n\n\nfunc exec(args ...string) error {\n\tcmd := osexec.Command(args[0], args[1:]...)\n\tout, err := cmd.CombinedOutput()\n\tswitch err := err.(type) {\n\tcase nil:\n\t\treturn nil\n\tcase *osexec.ExitError:\n\t\treturn fmt.Errorf(\"failed to run %q:\\n%v\", args, string(out))\n\tdefault:\n\t\treturn err\n\t}\n}\n\n\nfunc execVerbose(args ...string) error {\n\tcmd := osexec.Command(args[0], args[1:]...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}\n\n\n\n\n\nfunc execComposeVerbose(dir string, args ...string) error {\n\treturn execVerbose(append(\n\t\t[]string{\"docker-compose\", \"--ansi=never\", \"-f\", filepath.Join(dir, \"docker-compose.yml\")},\n\t\targs...)...)\n}\n\n\nfunc execDocker(args ...string) error {\n\treturn exec(append([]string{\"docker\"}, args...)...)\n}\n\nfunc execCompose(dir string, args ...string) error ", "output": "{\n\treturn exec(append(\n\t\t[]string{\"docker-compose\", \"--ansi=never\", \"-f\", filepath.Join(dir, \"docker-compose.yml\")},\n\t\targs...)...)\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/goshinobi/tor_multi\"\n)\n\nfunc processListHandle(w http.ResponseWriter, r *http.Request) {\n\tbin, err := json.Marshal(tor.GetWorkProxyList())\n\tif err != nil {\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.Write(bin)\n}\n\nfunc addProxyHandle(w http.ResponseWriter, r *http.Request) {\n\t_, err := tor.StartProxy()\n\tif err != nil {\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\tw.Write([]byte(\"success\"))\n}\n\nfunc killAllProxyHandle(w http.ResponseWriter, r *http.Request) {\n\tresult := \"\"\n\tfor k, v := range tor.GetWorkProxyList() {\n\t\terr := tor.KillTorProxy(k)\n\t\tif err == nil {\n\t\t\tresult += fmt.Sprintf(\"%d: %v\\n\", k, v)\n\t\t}\n\t}\n\n\tw.Write([]byte(result))\n}\n\n\n\nfunc root(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"\"))\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/\", root)\n\thttp.HandleFunc(\"/list\", processListHandle)\n\thttp.HandleFunc(\"/add\", addProxyHandle)\n\thttp.HandleFunc(\"/killAll\", killAllProxyHandle)\n\thttp.HandleFunc(\"/kill\", killProxyHandle)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc killProxyHandle(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tn, err := strconv.Atoi(r.PostFormValue(\"n\"))\n\tif err != nil {\n\t\tbin, _ := json.Marshal(struct {\n\t\t\tStatus string\n\t\t\tErr error\n\t\t}{\n\t\t\t\"failed\",\n\t\t\terr,\n\t\t})\n\t\tw.Write(bin)\n\t\treturn\n\t}\n\n\tbin, _ := json.Marshal(struct {\n\t\tStatus string\n\t\tN int\n\t}{\n\t\t\"failed\",\n\t\tn,\n\t})\n\tw.Write(bin)\n}"} {"input": "package shell_local\n\nimport (\n\t\"bytes\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/packer/packer\"\n)\n\n\n\nfunc TestCommunicator(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"windows not supported for this test\")\n\t\treturn\n\t}\n\n\tc := &Communicator{\n\t\tExecuteCommand: []string{\"/bin/sh\", \"-c\", \"echo foo\"},\n\t}\n\n\tvar buf bytes.Buffer\n\tcmd := &packer.RemoteCmd{\n\t\tStdout: &buf,\n\t}\n\n\tif err := c.Start(cmd); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tcmd.Wait()\n\n\tif cmd.ExitStatus != 0 {\n\t\tt.Fatalf(\"err bad exit status: %d\", cmd.ExitStatus)\n\t}\n\n\tif strings.TrimSpace(buf.String()) != \"foo\" {\n\t\tt.Fatalf(\"bad: %s\", buf.String())\n\t}\n}\n\nfunc TestCommunicator_impl(t *testing.T) ", "output": "{\n\tvar _ packer.Communicator = new(Communicator)\n}"} {"input": "package api\n\nimport (\n\t\"log\"\n\t\"net/http\"\n)\n\ntype HttpsRedirectingFileHandler interface {\n\thttp.Handler\n\tfileHandler() http.Handler\n}\n\ntype httpsHandler struct {\n\tinternalHandler http.Handler\n}\n\nfunc NewHttpsRedirectFileHandler(dir http.Dir) HttpsRedirectingFileHandler {\n\thandler := &httpsHandler{}\n\thandler.internalHandler = http.FileServer(dir)\n\treturn handler\n}\n\nfunc redirect(w http.ResponseWriter, req *http.Request) {\n\ttarget := \"https://\" + req.Host + req.URL.Path\n\tif len(req.URL.RawQuery) > 0 {\n\t\ttarget += \"?\" + req.URL.RawQuery\n\t}\n\tlog.Printf(\"redirect to: %s\", target)\n\thttp.Redirect(w, req, target,\n\t\thttp.StatusTemporaryRedirect)\n}\n\nfunc isXForwardedHTTPS(request *http.Request) bool {\n\txForwardedProto := request.Header.Get(\"X-Forwarded-Proto\")\n\n\treturn len(xForwardedProto) > 0 && xForwardedProto == \"https\"\n}\n\nfunc (h *httpsHandler) fileHandler() http.Handler {\n\treturn h.internalHandler\n}\n\n\n\nfunc (h *httpsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tif !isXForwardedHTTPS(req) {\n\t\tredirect(w, req)\n\t} else {\n\t\th.fileHandler().ServeHTTP(w, req)\n\t}\n}"} {"input": "package brackets\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc BenchmarkBracket(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, tt := range testCases {\n\t\t\tBracket(tt.input)\n\t\t}\n\t}\n}\n\nfunc TestBracket(t *testing.T) ", "output": "{\n\tfor _, tt := range testCases {\n\t\tactual := Bracket(tt.input)\n\t\tif actual != tt.expected {\n\t\t\tt.Fatalf(\"Bracket(%q) was expected to return %v but returned %v.\",\n\t\t\t\ttt.input, tt.expected, actual)\n\t\t}\n\t}\n}"} {"input": "package fakes\n\nimport \"os\"\n\ntype FileIO struct {\n\tTempFileCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tDir string\n\t\t\tPrefix string\n\t\t}\n\t\tReturns struct {\n\t\t\tFile *os.File\n\t\t\tError error\n\t\t}\n\t}\n\tReadFileCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tFilename string\n\t\t}\n\t\tReturns struct {\n\t\t\tContents []byte\n\t\t\tError error\n\t\t}\n\t}\n\tWriteFileCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tFilename string\n\t\t\tContents []byte\n\t\t}\n\t\tReturns struct {\n\t\t\tError error\n\t\t}\n\t}\n\tStatCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tName string\n\t\t}\n\t\tReturns struct {\n\t\t\tFileInfo os.FileInfo\n\t\t\tError error\n\t\t}\n\t}\n}\n\nfunc (fake *FileIO) TempFile(dir, prefix string) (f *os.File, err error) {\n\tfake.TempFileCall.CallCount++\n\tfake.TempFileCall.Receives.Dir = dir\n\tfake.TempFileCall.Receives.Prefix = prefix\n\treturn fake.TempFileCall.Returns.File, fake.TempFileCall.Returns.Error\n}\n\nfunc (fake *FileIO) ReadFile(filename string) ([]byte, error) {\n\tfake.ReadFileCall.CallCount++\n\tfake.ReadFileCall.Receives.Filename = filename\n\treturn fake.ReadFileCall.Returns.Contents, fake.ReadFileCall.Returns.Error\n}\n\n\n\nfunc (fake *FileIO) Stat(name string) (os.FileInfo, error) {\n\tfake.StatCall.CallCount++\n\tfake.StatCall.Receives.Name = name\n\treturn fake.StatCall.Returns.FileInfo, fake.StatCall.Returns.Error\n}\n\nfunc (fake *FileIO) WriteFile(filename string, contents []byte, perm os.FileMode) error ", "output": "{\n\tfake.WriteFileCall.CallCount++\n\tfake.WriteFileCall.Receives.Filename = filename\n\tfake.WriteFileCall.Receives.Contents = contents\n\treturn fake.WriteFileCall.Returns.Error\n}"} {"input": "package util\n\nimport (\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/cfstras/pcm/types\"\n)\n\ntype CommandFunc func() *string\n\n\n\n\n\n\nfunc GetCommandFunc(c *types.Connection, startWait *sync.Cond, moreCommands CommandFunc) CommandFunc ", "output": "{\n\tcommands := make(chan string, 5) \n\tfor _, v := range []string{\n\t\tc.Commands.Command1, c.Commands.Command2, c.Commands.Command3,\n\t\tc.Commands.Command4, c.Commands.Command5} {\n\t\tif strings.TrimSpace(v) != \"\" {\n\t\t\tcommands <- v\n\t\t}\n\t}\n\treturn func() *string {\n\t\tselect {\n\t\tcase v := <-commands:\n\t\t\treturn &v\n\t\tdefault:\n\t\t\tif c := moreCommands(); c != nil {\n\t\t\t\treturn c\n\t\t\t} else if startWait != nil {\n\t\t\t\tstartWait.Broadcast()\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n}"} {"input": "package conekta\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nconst (\n\tkey = \"\"\n\tsecret = \"key_KjXFWbopqyujnagRLy4dtw\"\n)\n\nfunc TestOrderCreate(t *testing.T) {\n\n\tc, err := NewClient(key, secret, false)\n\tc.debug = true\n\tassert.Nil(t, err)\n\tassert.NotNil(t, c)\n\n\tor := &OrderRequest{\n\t\tCurrency: MXN,\n\t\tCustomerInfo: &Customer{\n\t\t\tCustomerID: \"cus_2h3syNSMiZwfFM5XC\",\n\t\t},\n\t\tLineItems: []Product{\n\t\t\tProduct{\n\t\t\t\tName: \"Box of sls\",\n\t\t\t\tUnitPrice: 150 * 100,\n\t\t\t\tQuantity: 1,\n\t\t\t},\n\t\t},\n\t\tCharges: []Charge{\n\t\t\tCharge{\n\t\t\t\tPaymentMethod: PaymentMethod{\n\t\t\t\t\tType: \"default\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\torder, err := c.CreateOrder(or)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, order)\n}\n\n\n\nfunc TestCustomerCreate(t *testing.T) ", "output": "{\n\n\tc, err := NewClient(key, secret, false)\n\tc.debug = true\n\tassert.Nil(t, err)\n\tassert.NotNil(t, c)\n\n\tcr := &CustomerRequest{\n\t\tName: \"Mario Perez\",\n\t\tPhone: \"+5215555555555\",\n\t\tEmail: \"usuario@example.com\",\n\t\tPaymentSources: []PaymentSource{\n\t\t\tPaymentSource{\n\t\t\t\tTokenID: \"tok_test_visa_4242\",\n\t\t\t\tType: \"card\",\n\t\t\t},\n\t\t},\n\t\tCorporate: true,\n\t}\n\tcus, err := c.CreateCustomer(cr)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, cus)\n}"} {"input": "package storkctl\n\nimport (\n\t\"github.com/spf13/cobra\"\n\t\"k8s.io/cli-runtime/pkg/genericclioptions\"\n)\n\n\n\nfunc newCreateCommand(cmdFactory Factory, ioStreams genericclioptions.IOStreams) *cobra.Command ", "output": "{\n\tcreateCommands := &cobra.Command{\n\t\tUse: \"create\",\n\t\tShort: \"Create stork resources\",\n\t}\n\n\tcreateCommands.AddCommand(\n\t\tnewCreateSnapshotCommand(cmdFactory, ioStreams),\n\t\tnewCreateMigrationCommand(cmdFactory, ioStreams),\n\t\tnewCreateMigrationScheduleCommand(cmdFactory, ioStreams),\n\t\tnewCreatePVCCommand(cmdFactory, ioStreams),\n\t\tnewCreateSnapshotScheduleCommand(cmdFactory, ioStreams),\n\t\tnewCreateGroupSnapshotCommand(cmdFactory, ioStreams),\n\t\tnewCreateVolumeSnapshotRestoreCommand(cmdFactory, ioStreams),\n\t\tnewCreateApplicationBackupCommand(cmdFactory, ioStreams),\n\t\tnewCreateApplicationBackupScheduleCommand(cmdFactory, ioStreams),\n\t\tnewCreateApplicationRestoreCommand(cmdFactory, ioStreams),\n\t\tnewCreateApplicationCloneCommand(cmdFactory, ioStreams),\n\t\tnewCreateClusterPairCommand(cmdFactory, ioStreams),\n\t)\n\n\treturn createCommands\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"gopkg.in/fsnotify.v1\"\n\t\"io/ioutil\"\n\t\"log\"\n)\n\nfunc initFolder(folderPath string, img *imgur) {\n\tvar isFile bool\n\tdir, _ := ioutil.ReadDir(folderPath)\n\n\tlog.Println(\"Uploading content of folder \", folderPath)\n\n\tfor _, f := range dir {\n\t\tisFile = fileCheck(f.Name())\n\t\tif isFile == true {\n\t\t\timg.upload_image(folderPath+\"/\"+f.Name(), f.Name())\n\n\t\t} else {\n\t\t\tlog.Println(f.Name() + \" Extension not valid, upload an image pls\")\n\t\t}\n\t}\n}\n\n\n\nfunc folderWatcher(foldersNamesArray []string, img *imgur) ", "output": "{\n\tvar i int\n\twatcher, err := fsnotify.NewWatcher()\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer watcher.Close()\n\n\tdone := make(chan bool)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-watcher.Events:\n\t\t\t\tif event.Op == fsnotify.Create {\n\t\t\t\t\tlog.Println(\"New image detected\")\n\t\t\t\t\timg.upload_image(event.Name, \"atymgur\")\n\t\t\t\t}\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tfmt.Println(\"error:\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tfor i = 0; i < len(foldersNamesArray); i++ {\n\t\tgo initFolder(foldersNamesArray[i], img)\n\t\terr = watcher.Add(foldersNamesArray[i])\n\t}\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\t<-done\n}"} {"input": "package xpath\n\nimport (\n\t\"fmt\"\n\n\tpb \"github.com/openconfig/gnmi/proto/gnmi\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ToGNMIPath(xpath string) (*pb.Path, error) ", "output": "{\n\txpathElements, err := ParseStringPath(xpath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar pbPathElements []*pb.PathElem\n\tfor _, elem := range xpathElements {\n\t\tswitch v := elem.(type) {\n\t\tcase string:\n\t\t\tpbPathElements = append(pbPathElements, &pb.PathElem{Name: v})\n\t\tcase map[string]string:\n\t\t\tn := len(pbPathElements)\n\t\t\tif n == 0 {\n\t\t\t\treturn nil, fmt.Errorf(\"missing name before key-value list\")\n\t\t\t}\n\t\t\tif pbPathElements[n-1].Key != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"two subsequent key-value lists\")\n\t\t\t}\n\t\t\tpbPathElements[n-1].Key = v\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"wrong data type: %T\", v)\n\t\t}\n\t}\n\treturn &pb.Path{Elem: pbPathElements}, nil\n}"} {"input": "package storage_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/pkg/errors\"\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/cockroachdb/cockroach/pkg/server\"\n\t\"github.com/cockroachdb/cockroach/pkg/storage\"\n\t\"github.com/cockroachdb/cockroach/pkg/testutils\"\n\t\"github.com/cockroachdb/cockroach/pkg/util/leaktest\"\n\t\"github.com/cockroachdb/cockroach/pkg/util/stop\"\n)\n\n\n\nfunc TestEagerReplication(t *testing.T) ", "output": "{\n\tdefer leaktest.AfterTest(t)()\n\n\tstoreCfg := storage.TestStoreConfig(nil)\n\tstoreCfg.TestingKnobs.DisableSplitQueue = true\n\tstopper := stop.NewStopper()\n\tdefer stopper.Stop(context.TODO())\n\tstore := createTestStoreWithConfig(t, stopper, storeCfg)\n\n\tstore.SetReplicaScannerActive(false)\n\tstore.SetSplitQueueActive(true)\n\tstore.ForceSplitScanAndProcess()\n\n\ttestutils.SucceedsSoon(t, func() error {\n\t\texpected, err := server.ExpectedInitialRangeCount(store.DB())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif n := store.ReplicateQueuePurgatoryLength(); expected != n {\n\t\t\treturn errors.Errorf(\"expected %d replicas in purgatory, but found %d\", expected, n)\n\t\t}\n\t\treturn nil\n\t})\n}"} {"input": "package pflag\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype boolValue bool\n\nfunc newBoolValue(val bool, p *bool) *boolValue {\n\t*p = val\n\treturn (*boolValue)(p)\n}\n\nfunc (b *boolValue) Set(s string) error {\n\tv, err := strconv.ParseBool(s)\n\t*b = boolValue(v)\n\treturn err\n}\n\nfunc (b *boolValue) String() string { return fmt.Sprintf(\"%v\", *b) }\n\n\n\nfunc (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc BoolVar(p *bool, name string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\n\n\n\nfunc (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, shorthand, value, usage)\n\treturn p\n}\n\n\n\nfunc Bool(name string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, \"\", value, usage)\n}\n\n\nfunc BoolP(name, shorthand string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, shorthand, value, usage)\n}\n\nfunc (f *FlagSet) Bool(name string, value bool, usage string) *bool ", "output": "{\n\tp := new(bool)\n\tf.BoolVarP(p, name, \"\", value, usage)\n\treturn p\n}"} {"input": "package syncutil\n\nimport (\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\ntype TimedMutex struct {\n\tmu *Mutex \n\tlockedAt time.Time \n\tisLocked int32 \n\n\tcb TimingFn\n}\n\n\n\n\ntype TimingFn func(heldFor time.Duration)\n\n\n\n\nfunc ThresholdLogger(\n\tctx context.Context,\n\twarnDuration time.Duration,\n\tprintf func(context.Context, string, ...interface{}),\n\trecord TimingFn,\n) TimingFn {\n\treturn func(heldFor time.Duration) {\n\t\trecord(heldFor)\n\t\tif heldFor > warnDuration {\n\t\t\tpc, _, _, ok := runtime.Caller(2)\n\t\t\tfun := \"?\"\n\t\t\tif ok {\n\t\t\t\tif f := runtime.FuncForPC(pc); f != nil {\n\t\t\t\t\tfun = f.Name()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprintf(\n\t\t\t\tctx, \"mutex held by %s for %s (>%s):\\n%s\",\n\t\t\t\tfun, heldFor, warnDuration, debug.Stack(),\n\t\t\t)\n\t\t}\n\t}\n}\n\n\n\n\n\nfunc MakeTimedMutex(cb TimingFn) TimedMutex {\n\treturn TimedMutex{\n\t\tcb: cb,\n\t\tmu: &Mutex{},\n\t}\n}\n\n\nfunc (tm *TimedMutex) Lock() {\n\ttm.mu.Lock()\n\tatomic.StoreInt32(&tm.isLocked, 1)\n\ttm.lockedAt = time.Now()\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (tm *TimedMutex) AssertHeld() {\n\tisLocked := atomic.LoadInt32(&tm.isLocked)\n\tif isLocked == 0 {\n\t\tpanic(\"mutex is not locked\")\n\t}\n}\n\nfunc (tm *TimedMutex) Unlock() ", "output": "{\n\tlockedAt := tm.lockedAt\n\tatomic.StoreInt32(&tm.isLocked, 0)\n\ttm.mu.Unlock()\n\tif tm.cb != nil {\n\t\ttm.cb(time.Since(lockedAt))\n\t}\n}"} {"input": "package gonum\n\nimport \"gonum.org/v1/gonum/blas/blas64\"\n\n\n\n\n\n\n\n\n\n\nfunc (impl Implementation) Dlapll(n int, x []float64, incX int, y []float64, incY int) float64 ", "output": "{\n\tcheckVector(n, x, incX)\n\tcheckVector(n, y, incY)\n\n\tif n <= 1 {\n\t\treturn 0\n\t}\n\n\ta00, tau := impl.Dlarfg(n, x[0], x[incX:], incX)\n\tx[0] = 1\n\n\tbi := blas64.Implementation()\n\tc := -tau * bi.Ddot(n, x, incX, y, incY)\n\tbi.Daxpy(n, c, x, incX, y, incY)\n\ta11, _ := impl.Dlarfg(n-1, y[incY], y[2*incY:], incY)\n\n\tssmin, _ := impl.Dlas2(a00, y[0], a11)\n\treturn ssmin\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\ntype Response struct {\n\tStatus string `json:\"status\"`\n\tErrorText string `json:\"errorText,omitempty\"`\n\tAddress string `json:\"address,omitempty\"`\n\tStatusCode int `json:\"statusCode,omitempty\"`\n\tVersion string `json:\"version,omitempty\"`\n}\n\ntype Responses struct {\n\tResponses []Response `json:\"responses\"`\n}\n\n\n\nfunc (r Responses) String() string {\n\tj, _ := json.Marshal(r)\n\treturn fmt.Sprintf(\"Responses: %s\", string(j))\n}\n\nfunc (r Response) String() string {\n\tj, _ := json.Marshal(r)\n\treturn fmt.Sprintf(\"Response: %s\", string(j))\n}\n\nfunc (r Response) WriteHttp(w http.ResponseWriter) (resp Response) {\n\tif r.StatusCode == 0 {\n\t\tr.StatusCode = 200\n\t}\n\tw.WriteHeader(r.StatusCode)\n\treturn EncodeJson(r, w)\n}\n\nfunc (r Response) WriteBadRequestHttp(w http.ResponseWriter) (resp Response) {\n\tw.WriteHeader(http.StatusBadRequest)\n\tr.StatusCode = http.StatusBadRequest\n\treturn EncodeJson(r, w)\n}\n\nfunc (r Response) WriteInternalServerErrorHttp(w http.ResponseWriter) (resp Response) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tr.StatusCode = http.StatusInternalServerError\n\treturn EncodeJson(r, w)\n}\n\nfunc EncodeJson(r Response, w http.ResponseWriter) (resp Response) {\n\terr := json.NewEncoder(w).Encode(r)\n\tif err != nil {\n\t\tlog.Printf(\"[writehttp] failed to create json from model: %s\", err.Error())\n\t}\n\treturn r\n}\n\nfunc (r *Response) Fill(outStr string, err error) ", "output": "{\n\tif err != nil {\n\t\tr.Status = \"ERR\"\n\t\tr.ErrorText = strings.TrimSpace(outStr + \" \" + err.Error())\n\t} else {\n\t\tr.Status = \"OK\"\n\t}\n}"} {"input": "package query\n\nimport (\n\t\"encoding/json\"\n\t\"reflect\"\n)\n\nfunc toJson(v interface{}) ([]byte, error) {\n\treturn json.Marshal(v)\n}\n\nfunc wrapper(name string, v interface{}) map[string]interface{} {\n\tquery := map[string]interface{}{\n\t\tname: v,\n\t}\n\treturn query\n}\n\nfunc convert(value reflect.Value) interface{} {\n\tswitch value.Kind() {\n\tcase reflect.Slice:\n\t\tvar res []interface{}\n\t\tfor i := 0; i < value.Len(); i++ {\n\t\t\tres = append(res, convert(value.Index(i)))\n\t\t}\n\t\treturn res\n\tcase reflect.Ptr:\n\t\tif !value.IsNil() {\n\t\t\treturn convert(value.Elem())\n\t\t}\n\tcase reflect.String:\n\t\treturn value.String()\n\tcase reflect.Float64:\n\t\treturn value.Float()\n\tcase reflect.Int:\n\t\treturn value.Int()\n\tcase reflect.Bool:\n\t\treturn value.Bool()\n\t}\n\treturn value.Interface()\n}\n\nfunc convertable(value reflect.Value) bool {\n\tswitch value.Kind() {\n\tcase reflect.Slice:\n\t\treturn value.Len() > 0\n\tcase reflect.Ptr:\n\t\treturn !value.IsNil()\n\t}\n\treturn true\n}\n\n\n\nfunc convertStruct(x interface{}) interface{} ", "output": "{\n\tquery := make(map[string]interface{})\n\n\tt := reflect.ValueOf(x).Type()\n\tv := reflect.ValueOf(x)\n\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tfield := t.Field(i)\n\t\tvalue := v.FieldByName(field.Name)\n\t\ttag := field.Tag.Get(\"json\")\n\t\tif tag == \"-\" {\n\t\t\tcontinue\n\t\t}\n\t\tif convertable(value) {\n\t\t\tquery[tag] = convert(value)\n\t\t}\n\t}\n\n\treturn query\n\n}"} {"input": "package viewservice\n\nimport \"net/rpc\"\nimport \"fmt\"\n\n\n\n\n\ntype Clerk struct {\n\tme string \n\tserver string \n}\n\nfunc MakeClerk(me string, server string) *Clerk {\n\tck := new(Clerk)\n\tck.me = me\n\tck.server = server\n\treturn ck\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc call(srv string, rpcname string,\n\targs interface{}, reply interface{}) bool {\n\tc, errx := rpc.Dial(\"unix\", srv)\n\tif errx != nil {\n\t\treturn false\n\t}\n\tdefer c.Close()\n\n\terr := c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}\n\nfunc (ck *Clerk) Ping(viewnum uint) (View, error) {\n\targs := &PingArgs{}\n\targs.Me = ck.me\n\targs.Viewnum = viewnum\n\tvar reply PingReply\n\n\tok := call(ck.server, \"ViewServer.Ping\", args, &reply)\n\tif ok == false {\n\t\treturn View{}, fmt.Errorf(\"Ping(%v) failed\", viewnum)\n\t}\n\n\treturn reply.View, nil\n}\n\nfunc (ck *Clerk) Get() (View, bool) {\n\targs := &GetArgs{}\n\tvar reply GetReply\n\tok := call(ck.server, \"ViewServer.Get\", args, &reply)\n\tif ok == false {\n\t\treturn View{}, false\n\t}\n\treturn reply.View, true\n}\n\n\n\nfunc (ck *Clerk) Primary() string ", "output": "{\n\tv, ok := ck.Get()\n\tif ok {\n\t\treturn v.Primary\n\t}\n\treturn \"\"\n}"} {"input": "package state\n\nimport (\n\t\"fmt\"\n\n\t\"labix.org/v2/mgo\"\n\t\"labix.org/v2/mgo/bson\"\n\t\"labix.org/v2/mgo/txn\"\n\n\t\"github.com/wallyworld/core/errors\"\n\t\"github.com/wallyworld/core/state/api/params\"\n)\n\n\n\n\n\ntype statusDoc struct {\n\tStatus params.Status\n\tStatusInfo string\n\tStatusData params.StatusData\n}\n\n\n\n\n\n\n\n\nfunc getStatus(st *State, globalKey string) (statusDoc, error) {\n\tvar doc statusDoc\n\terr := st.statuses.FindId(globalKey).One(&doc)\n\tif err == mgo.ErrNotFound {\n\t\treturn statusDoc{}, errors.NotFoundf(\"status\")\n\t}\n\tif err != nil {\n\t\treturn statusDoc{}, fmt.Errorf(\"cannot get status %q: %v\", globalKey, err)\n\t}\n\treturn doc, nil\n}\n\n\n\nfunc createStatusOp(st *State, globalKey string, doc statusDoc) txn.Op {\n\treturn txn.Op{\n\t\tC: st.statuses.Name,\n\t\tId: globalKey,\n\t\tAssert: txn.DocMissing,\n\t\tInsert: doc,\n\t}\n}\n\n\n\nfunc updateStatusOp(st *State, globalKey string, doc statusDoc) txn.Op {\n\treturn txn.Op{\n\t\tC: st.statuses.Name,\n\t\tId: globalKey,\n\t\tAssert: txn.DocExists,\n\t\tUpdate: bson.D{{\"$set\", doc}},\n\t}\n}\n\n\n\nfunc removeStatusOp(st *State, globalKey string) txn.Op {\n\treturn txn.Op{\n\t\tC: st.statuses.Name,\n\t\tId: globalKey,\n\t\tRemove: true,\n\t}\n}\n\nfunc (doc statusDoc) validateSet(allowPending bool) error ", "output": "{\n\tif !doc.Status.Valid() {\n\t\treturn fmt.Errorf(\"cannot set invalid status %q\", doc.Status)\n\t}\n\tswitch doc.Status {\n\tcase params.StatusPending:\n\t\tif !allowPending {\n\t\t\treturn fmt.Errorf(\"cannot set status %q\", doc.Status)\n\t\t}\n\tcase params.StatusDown:\n\t\treturn fmt.Errorf(\"cannot set status %q\", doc.Status)\n\tcase params.StatusError:\n\t\tif doc.StatusInfo == \"\" {\n\t\t\treturn fmt.Errorf(\"cannot set status %q without info\", doc.Status)\n\t\t}\n\t}\n\tif doc.StatusData != nil && doc.Status != params.StatusError {\n\t\treturn fmt.Errorf(\"cannot set status data when status is %q\", doc.Status)\n\t}\n\treturn nil\n}"} {"input": "package binlogplayer\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"vitess.io/vitess/go/sqltypes\"\n)\n\ntype fakeDBClient struct {\n}\n\n\n\n\n\nfunc (dc *fakeDBClient) DBName() string {\n\treturn \"db\"\n}\n\nfunc (dc *fakeDBClient) Connect() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Begin() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Commit() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Rollback() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Close() {\n}\n\nfunc (dc *fakeDBClient) ExecuteFetch(query string, maxrows int) (qr *sqltypes.Result, err error) {\n\tquery = strings.ToLower(query)\n\tswitch {\n\tcase strings.HasPrefix(query, \"insert\"):\n\t\treturn &sqltypes.Result{InsertID: 1}, nil\n\tcase strings.HasPrefix(query, \"update\"):\n\t\treturn &sqltypes.Result{RowsAffected: 1}, nil\n\tcase strings.HasPrefix(query, \"delete\"):\n\t\treturn &sqltypes.Result{RowsAffected: 1}, nil\n\tcase strings.HasPrefix(query, \"select\"):\n\t\tif strings.Contains(query, \"where\") {\n\t\t\treturn sqltypes.MakeTestResult(\n\t\t\t\tsqltypes.MakeTestFields(\n\t\t\t\t\t\"id|state|source\",\n\t\t\t\t\t\"int64|varchar|varchar\",\n\t\t\t\t),\n\t\t\t\t`1|Running|keyspace:\"ks\" shard:\"0\" key_range: `,\n\t\t\t), nil\n\t\t}\n\t\treturn &sqltypes.Result{}, nil\n\tcase strings.HasPrefix(query, \"use\"):\n\t\treturn &sqltypes.Result{}, nil\n\t}\n\treturn nil, fmt.Errorf(\"unexpected: %v\", query)\n}\n\nfunc NewFakeDBClient() DBClient ", "output": "{\n\treturn &fakeDBClient{}\n}"} {"input": "package logo\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc fail(t *testing.T, msg string) {\n\tt.Errorf(msg)\n}\n\nfunc assertEqual(t *testing.T, actual, expected interface{}, args ...interface{}) {\n\tif actual != expected {\n\t\tmsg := fmt.Sprint(args...)\n\t\tmsg = fmt.Sprintf(\"Not equal(%s)! autual: %#v expected: %#v\", msg, actual, expected)\n\t\tfail(t, msg)\n\t}\n}\n\n\n\nfunc assertNotNil(t *testing.T, val interface{}, args ...interface{}) {\n\tif val == nil {\n\t\tmsg := fmt.Sprint(args...)\n\t\tmsg = fmt.Sprintf(\"Nil(%s)!\", msg)\n\t\tfail(t, msg)\n\t}\n}\n\nfunc benchmarkTask(b *testing.B, task func(int)) {\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\ttask(i)\n\t}\n}\n\nfunc assertTrue(t *testing.T, val bool, args ...interface{}) ", "output": "{\n\tif !val {\n\t\tmsg := fmt.Sprint(args...)\n\t\tmsg = fmt.Sprintf(\"Not true(%s)!\", msg)\n\t\tfail(t, msg)\n\t}\n}"} {"input": "package sockets\n\nimport (\n\t\"crypto/tls\"\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/docker/docker/pkg/listenbuffer\"\n)\n\n\n\n\n\n\nfunc NewTCPSocket(addr string, tlsConfig *tls.Config, activate <-chan struct{}) (net.Listener, error) {\n\tl, err := listenbuffer.NewListenBuffer(\"tcp\", addr, activate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif tlsConfig != nil {\n\t\ttlsConfig.NextProtos = []string{\"http/1.1\"}\n\t\tl = tls.NewListener(l, tlsConfig)\n\t}\n\treturn l, nil\n}\n\n\n\n\n\n\n\nfunc ConfigureTCPTransport(tr *http.Transport, proto, addr string) ", "output": "{\n\ttimeout := 32 * time.Second\n\tif proto == \"unix\" {\n\t\ttr.DisableCompression = true\n\t\ttr.Dial = func(_, _ string) (net.Conn, error) {\n\t\t\treturn net.DialTimeout(proto, addr, timeout)\n\t\t}\n\t} else {\n\t\ttr.Proxy = http.ProxyFromEnvironment\n\t\ttr.Dial = (&net.Dialer{Timeout: timeout}).Dial\n\t}\n}"} {"input": "package sdl\n\n\nimport \"C\"\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"unsafe\"\n)\n\nconst SamplingRate = 11025\n\nfunc initAudio() {\n\tvar spec C.SDL_AudioSpec\n\tspec.freq = C.int(SamplingRate)\n\tspec.format = C.AUDIO_S8\n\tspec.channels = 1\n\tspec.samples = 512\n\tspec.userdata = nil\n\tC.openAudio(&spec)\n}\n\n\nfunc BufferAudio(sound []int8) {\n\tif len(sound) == 0 {\n\t\treturn\n\t}\n\tmutex.Lock()\n\tC.play((*C.Uint8)(unsafe.Pointer(&sound[0])), C.int(len(sound)))\n\tmutex.Unlock()\n}\n\nfunc Play(input io.Reader) error {\n\tbuf, err := ioutil.ReadAll(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmutex.Lock()\n\tC.play((*C.Uint8)(unsafe.Pointer(&buf[0])), C.int(len(buf)))\n\tmutex.Unlock()\n\treturn nil\n}\n\n\n\nfunc ClearAudioBuffer() ", "output": "{\n\tmutex.Lock()\n\tC.stop()\n\tmutex.Unlock()\n}"} {"input": "package main\n\nimport (\n\t\"github.com/rach/pome/Godeps/_workspace/src/github.com/jmoiron/sqlx\"\n\t\"github.com/robfig/cron\"\n\t\"strings\"\n)\n\nfunc scheduleMetric(c *cron.Cron, schedule string, fct func()) {\n\tc.AddFunc(schedule, fct)\n\tif strings.HasPrefix(schedule, \"@every\") {\n\t\tfct()\n\t}\n}\n\n\n\nfunc initScheduler(\n\tdb *sqlx.DB,\n\tmetrics *MetricList,\n\tscheduleTableBloat string,\n\tscheduleDbSize string,\n\tscheduleIndexBloat string,\n\tscheduleNumConn string,\n\tscheduleTPS string) ", "output": "{\n\n\tc := cron.New()\n\tscheduleMetric(c, scheduleIndexBloat,\n\t\tfunc() {\n\t\t\tindexBloatUpdate(db, metrics, GetIndexBloatResult, 120)\n\t\t},\n\t)\n\tscheduleMetric(c, scheduleTableBloat,\n\t\tfunc() {\n\t\t\ttableBloatUpdate(db, metrics, GetTableBloatResult, 120)\n\t\t},\n\t)\n\tscheduleMetric(c, scheduleDbSize,\n\t\tfunc() {\n\t\t\tdatabaseSizeUpdate(db, metrics, GetDatabeSizeResult, 120)\n\t\t},\n\t)\n\tscheduleMetric(c, scheduleNumConn,\n\t\tfunc() {\n\t\t\tnumberOfConnectionUpdate(db, metrics, GetNumberOfConnectionResult, 120)\n\t\t},\n\t)\n\tscheduleMetric(c, scheduleTPS,\n\t\tfunc() {\n\t\t\ttransactionPerSecUpdate(db, metrics, GetTransactionNumberResult, 120)\n\t\t},\n\t)\n\tc.Start()\n}"} {"input": "package billing\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/billing/mgmt/2017-04-24-preview/billing\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype ManagementClient = original.ManagementClient\ntype InvoicesClient = original.InvoicesClient\ntype DownloadURL = original.DownloadURL\ntype ErrorDetails = original.ErrorDetails\ntype ErrorResponse = original.ErrorResponse\ntype Invoice = original.Invoice\ntype InvoiceProperties = original.InvoiceProperties\ntype InvoicesListResult = original.InvoicesListResult\ntype Operation = original.Operation\ntype OperationDisplay = original.OperationDisplay\ntype OperationListResult = original.OperationListResult\ntype Period = original.Period\ntype PeriodProperties = original.PeriodProperties\ntype PeriodsListResult = original.PeriodsListResult\ntype Resource = original.Resource\ntype OperationsClient = original.OperationsClient\ntype PeriodsClient = original.PeriodsClient\n\nfunc NewOperationsClient(subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClient(subscriptionID)\n}\nfunc NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewPeriodsClient(subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClient(subscriptionID)\n}\n\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\nfunc New(subscriptionID string) ManagementClient {\n\treturn original.New(subscriptionID)\n}\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewInvoicesClient(subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClient(subscriptionID)\n}\nfunc NewInvoicesClientWithBaseURI(baseURI string, subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClientWithBaseURI(baseURI, subscriptionID)\n}\n\nfunc NewPeriodsClientWithBaseURI(baseURI string, subscriptionID string) PeriodsClient ", "output": "{\n\treturn original.NewPeriodsClientWithBaseURI(baseURI, subscriptionID)\n}"} {"input": "package auth\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/odeke-em/drivefuse/config\"\n\t\"github.com/odeke-em/drivefuse/third_party/code.google.com/p/goauth2/oauth\"\n)\n\nconst (\n\tGoogleOAuth2AuthURL = \"https:accounts.google.com/o/oauth2/auth\"\n\tGoogleOAuth2TokenURL = \"https:accounts.google.com/o/oauth2/token\"\n\n\tRedirectURL = \"urn:ietf:wg:oauth:2.0:oob\"\n\n\tDriveScope = \"https:www.googleapis.com/auth/drive\"\n\n\tAccessType = \"offline\"\n)\n\nfunc newConfig(cfg *config.Account) *oauth.Config {\n\treturn &oauth.Config{\n\t\tClientId: cfg.ClientId,\n\t\tClientSecret: cfg.ClientSecret,\n\t\tAuthURL: GoogleOAuth2AuthURL,\n\t\tTokenURL: GoogleOAuth2TokenURL,\n\t\tRedirectURL: RedirectURL,\n\t\tAccessType: AccessType,\n\t\tScope: DriveScope,\n\t}\n}\n\n\n\n\n\nfunc NewTransport(cfg *config.Account) *oauth.Transport ", "output": "{\n\treturn &oauth.Transport{\n\t\tConfig: newConfig(cfg),\n\t\tTransport: http.DefaultTransport,\n\t\tToken: &oauth.Token{RefreshToken: cfg.RefreshToken, Expiry: time.Now()},\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n\n\t\"github.com/n0rad/go-erlog/errs\"\n)\n\ntype envMap struct {\n\tmapping map[string]string\n}\n\nfunc (e *envMap) Set(s string) error {\n\tif e.mapping == nil {\n\t\te.mapping = make(map[string]string)\n\t}\n\tpair := strings.SplitN(s, \"=\", 2)\n\tif len(pair) != 2 {\n\t\treturn errs.With(\"environment variable must be specified as name=value\")\n\t}\n\te.mapping[pair[0]] = pair[1]\n\treturn nil\n}\n\nfunc (e *envMap) String() string {\n\treturn strings.Join(e.Strings(), \"\\n\")\n}\n\nfunc (e *envMap) Strings() []string {\n\tvar env []string\n\tfor n, v := range e.mapping {\n\t\tenv = append(env, n+\"=\"+v)\n\t}\n\treturn env\n}\n\n\n\nfunc (e *envMap) Type() string ", "output": "{\n\treturn \"envMap\"\n}"} {"input": "package countdata\n\nimport (\n\t\"io\"\n\n\t\"golang.org/x/net/html\"\n)\n\nfunc visit(n *html.Node, result map[string]int) {\n\tif n == nil {\n\t\treturn\n\t}\n\tif n.Type == html.ElementNode {\n\t\tresult[n.Data]++\n\t}\n\tvisit(n.FirstChild, result) \n\tvisit(n.NextSibling, result) \n}\n\n\n\nfunc Count(r io.Reader) (map[string]int, error) ", "output": "{\n\tdoc, err := html.Parse(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := make(map[string]int)\n\tvisit(doc, result)\n\treturn result, nil\n}"} {"input": "package main\nimport . \"fmt\"\nimport . \"net/http\"\nimport \"time\"\n\nconst ADDRESS = \":1024\"\nconst SECURE_ADDRESS = \":1025\"\n\nfunc main() {\n message := \"hello world\"\n HandleFunc(\"/hello\", func(w ResponseWriter, r *Request) {\n w.Header().Set(\"Content-Type\", \"text/plain\")\n Fprintf(w, message)\n })\n\n Spawn(\n func() { ListenAndServeTLS(SECURE_ADDRESS, \"cert.pem\", \"key.pem\", nil) },\n func() { ListenAndServe(ADDRESS, nil) },\n )\n}\n\n\n\nfunc Spawn(f ...func()) ", "output": "{\n done := make(chan bool)\n\n for _, s := range f {\n go func() {\n s()\n done <- true\n }()\n time.Sleep(time.Second)\n }\n\n for l := len(f); l > 0; l-- {\n <- done\n }\n}"} {"input": "package container\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/martin-helmich/distcrond/domain\"\n)\n\ntype JobContainer struct {\n\tjobs []domain.Job\n\tjobsByName map[string]*domain.Job\n}\n\n\n\nfunc (c *JobContainer) AddJob(job domain.Job) {\n\tc.jobs = append(c.jobs, job)\n\tc.jobsByName[job.Name] = &c.jobs[len(c.jobs)-1]\n}\n\nfunc (c *JobContainer) Count() int {\n\treturn len(c.jobs)\n}\n\nfunc (c *JobContainer) All() []domain.Job {\n\treturn c.jobs\n}\n\nfunc (c *JobContainer) Get(i int) *domain.Job {\n\treturn &c.jobs[i]\n}\n\nfunc (c *JobContainer) JobByName(n string) (*domain.Job, error) {\n\tif job, ok := c.jobsByName[n]; !ok {\n\t\treturn nil, errors.New(fmt.Sprintf(\"No job with name '%s' is known\", n))\n\t} else {\n\t\treturn job, nil\n\t}\n}\n\nfunc NewJobContainer(initialCapacity int) *JobContainer ", "output": "{\n\tcontainer := new(JobContainer)\n\tcontainer.jobs = make([]domain.Job, 0, initialCapacity)\n\tcontainer.jobsByName = make(map[string]*domain.Job)\n\treturn container\n}"} {"input": "package mlock\n\nfunc init() {\n\tsupported = false\n}\n\n\n\nfunc lockMemory() error ", "output": "{\n\treturn nil\n}"} {"input": "package factory\n\nimport (\n\t\"encoding/hex\"\n\n\t\"github.com/hyperledger/fabric/bccsp\"\n\t\"github.com/hyperledger/fabric/bccsp/pkcs11\"\n\t\"github.com/hyperledger/fabric/bccsp/sw\"\n\t\"github.com/pkg/errors\"\n)\n\nconst (\n\tPKCS11BasedFactoryName = \"PKCS11\"\n)\n\n\ntype PKCS11Factory struct{}\n\n\nfunc (f *PKCS11Factory) Name() string {\n\treturn PKCS11BasedFactoryName\n}\n\n\nfunc (f *PKCS11Factory) Get(config *FactoryOpts) (bccsp.BCCSP, error) {\n\tif config == nil || config.PKCS11 == nil {\n\t\treturn nil, errors.New(\"Invalid config. It must not be nil.\")\n\t}\n\n\tp11Opts := *config.PKCS11\n\tks := sw.NewDummyKeyStore()\n\tmapper := skiMapper(p11Opts)\n\n\treturn pkcs11.New(p11Opts, ks, pkcs11.WithKeyMapper(mapper))\n}\n\n\n\nfunc skiMapper(p11Opts pkcs11.PKCS11Opts) func([]byte) []byte ", "output": "{\n\tkeyMap := map[string]string{}\n\tfor _, k := range p11Opts.KeyIDs {\n\t\tkeyMap[k.SKI] = k.ID\n\t}\n\n\treturn func(ski []byte) []byte {\n\t\tkeyID := hex.EncodeToString(ski)\n\t\tif id, ok := keyMap[keyID]; ok {\n\t\t\treturn []byte(id)\n\t\t}\n\t\tif p11Opts.AltID != \"\" {\n\t\t\treturn []byte(p11Opts.AltID)\n\t\t}\n\t\treturn ski\n\t}\n}"} {"input": "package authentication\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/piot/hasty-protocol/user\"\n)\n\n\ntype Info struct {\n\tuserID user.ID\n}\n\n\nfunc NewInfo(userID user.ID) Info {\n\treturn Info{userID: userID}\n}\n\n\n\n\n\nfunc (in Info) String() string {\n\treturn fmt.Sprintf(\"[authentication ID:%s ]\", in.userID)\n}\n\nfunc (in Info) UserID() user.ID ", "output": "{\n\treturn in.userID\n}"} {"input": "package options\n\nimport (\n\t\"strings\"\n\n\t\"github.com/pkg/errors\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/pflag\"\n)\n\ntype ClusterEditConfig struct {\n\tClusterName string\n\tFile string\n\tKubernetesVersion string\n\tLocked bool\n\tOutput string\n}\n\nfunc NewClusterEditConfig() *ClusterEditConfig {\n\treturn &ClusterEditConfig{\n\t\tClusterName: \"\",\n\t\tFile: \"\",\n\t\tKubernetesVersion: \"\",\n\t\tLocked: false,\n\t\tOutput: \"yaml\",\n\t}\n}\n\nfunc (c *ClusterEditConfig) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVarP(&c.File, \"file\", \"f\", c.File, \"Load cluster data from file\")\n\tfs.StringVar(&c.KubernetesVersion, \"kubernetes-version\", c.KubernetesVersion, \"Kubernetes version\")\n\tfs.BoolVar(&c.Locked, \"locked\", c.Locked, \"If true, locks cluster from deletion\")\n\tfs.StringVarP(&c.Output, \"output\", \"o\", c.Output, \"Output format. One of: yaml|json.\")\n\n}\n\n\n\nfunc (c *ClusterEditConfig) CheckForUpdateFlags() bool {\n\tif c.Locked || c.KubernetesVersion != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (c *ClusterEditConfig) ValidateFlags(cmd *cobra.Command, args []string) error ", "output": "{\n\tif cmd.Flags().Changed(\"file\") {\n\t\tif len(args) != 0 {\n\t\t\treturn errors.New(\"no argument can be provided when --file flag is used\")\n\t\t}\n\t}\n\tif len(args) == 0 {\n\t\treturn errors.New(\"missing cluster name\")\n\t}\n\tif len(args) > 1 {\n\t\treturn errors.New(\"multiple cluster name provided\")\n\t}\n\tc.ClusterName = strings.ToLower(args[0])\n\treturn nil\n}"} {"input": "package testrace\n\nimport \"testing\"\n\n\n\nfunc BenchmarkRace(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tc := make(chan int)\n\t\tx := 1\n\t\tgo func() {\n\t\t\tx = 2\n\t\t\tc <- 1\n\t\t}()\n\t\tx = 3\n\t\t<-c\n\t\t_ = x\n\t}\n}\n\nfunc TestRace(t *testing.T) ", "output": "{\n\tfor i := 0; i < 10; i++ {\n\t\tc := make(chan int)\n\t\tx := 1\n\t\tgo func() {\n\t\t\tx = 2\n\t\t\tc <- 1\n\t\t}()\n\t\tx = 3\n\t\t<-c\n\t\t_ = x\n\t}\n}"} {"input": "package plugdeps\n\nimport \"encoding/json\"\n\n\ntype Command struct {\n\tName string `toml:\"name\" json:\"name\"`\n\tFlags []string `toml:\"flags,omitempty\" json:\"flags,omitempty\"`\n\tCommands []Command `toml:\"command,omitempty\" json:\"commands,omitempty\"`\n}\n\n\n\n\nfunc (p Command) String() string ", "output": "{\n\tb, _ := json.Marshal(p)\n\treturn string(b)\n}"} {"input": "package billing\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/billing/mgmt/2017-04-24-preview/billing\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype ManagementClient = original.ManagementClient\ntype InvoicesClient = original.InvoicesClient\ntype DownloadURL = original.DownloadURL\ntype ErrorDetails = original.ErrorDetails\ntype ErrorResponse = original.ErrorResponse\ntype Invoice = original.Invoice\ntype InvoiceProperties = original.InvoiceProperties\ntype InvoicesListResult = original.InvoicesListResult\ntype Operation = original.Operation\ntype OperationDisplay = original.OperationDisplay\ntype OperationListResult = original.OperationListResult\ntype Period = original.Period\ntype PeriodProperties = original.PeriodProperties\ntype PeriodsListResult = original.PeriodsListResult\ntype Resource = original.Resource\ntype OperationsClient = original.OperationsClient\ntype PeriodsClient = original.PeriodsClient\n\nfunc NewOperationsClient(subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClient(subscriptionID)\n}\nfunc NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewPeriodsClient(subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClient(subscriptionID)\n}\nfunc NewPeriodsClientWithBaseURI(baseURI string, subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\nfunc New(subscriptionID string) ManagementClient {\n\treturn original.New(subscriptionID)\n}\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\n\nfunc NewInvoicesClientWithBaseURI(baseURI string, subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClientWithBaseURI(baseURI, subscriptionID)\n}\n\nfunc NewInvoicesClient(subscriptionID string) InvoicesClient ", "output": "{\n\treturn original.NewInvoicesClient(subscriptionID)\n}"} {"input": "package server\n\nimport (\n\t\"context\"\n\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n)\n\nfunc (s *Service) EjectCDROM(req *EjectCDROMRequest) error {\n\treturn s.EjectCDROMWithContext(context.Background(), req)\n}\n\n\n\nfunc (s *Service) EjectCDROMWithContext(ctx context.Context, req *EjectCDROMRequest) error ", "output": "{\n\tif err := req.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tclient := sacloud.NewServerOp(s.caller)\n\tserver, err := client.Read(ctx, req.Zone, req.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif server.CDROMID.IsEmpty() {\n\t\treturn nil \n\t}\n\n\treturn client.EjectCDROM(ctx, req.Zone, req.ID, &sacloud.EjectCDROMRequest{ID: server.CDROMID})\n}"} {"input": "package iso20022\n\n\ntype UnmatchedReason21Choice struct {\n\n\tCode *UnmatchedReason11Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification30 `xml:\"Prtry\"`\n}\n\nfunc (u *UnmatchedReason21Choice) SetCode(value string) {\n\tu.Code = (*UnmatchedReason11Code)(&value)\n}\n\n\n\nfunc (u *UnmatchedReason21Choice) AddProprietary() *GenericIdentification30 ", "output": "{\n\tu.Proprietary = new(GenericIdentification30)\n\treturn u.Proprietary\n}"} {"input": "package main\n\n\n\nfunc main() {\n\tif err := test(); nil == err {\n\t\tprintln(\"err is nil\")\n\t}\n}\n\nfunc test() error ", "output": "{ return nil }"} {"input": "package pgparser\n\nimport (\n\t\"strings\"\n\n\t\"go.bmatsuo.co/go-lexer\"\n)\n\nconst (\n\titemLeftBrace lexer.ItemType = iota\n\titemRightBrace\n\titemLeftParen\n\titemRightParen\n\titemComma\n\titemQuotedString\n\titemBareString\n)\n\n\n\nfunc stateQuotedString(l *lexer.Lexer) lexer.StateFn {\n\tif !l.Accept(\"\\\"\") {\n\t\tl.Errorf(\"expected an opening quote\")\n\t}\n\n\tfor {\n\t\tif l.Accept(\"\\\\\") {\n\t\t\tl.Advance()\n\t\t}\n\n\t\tn := l.AcceptRunFunc(func(r rune) bool {\n\t\t\treturn r != '\\\\' && r != '\"'\n\t\t})\n\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !l.Accept(\"\\\"\") {\n\t\tl.Errorf(\"expected a closing quote\")\n\t}\n\n\tl.Emit(itemQuotedString)\n\n\treturn stateBegin\n}\n\nfunc stateBareString(l *lexer.Lexer) lexer.StateFn {\n\tl.AcceptRunFunc(func(r rune) bool {\n\t\treturn !strings.ContainsRune(`{}(),\"`, r)\n\t})\n\n\tl.Emit(itemBareString)\n\n\treturn stateBegin\n}\n\nfunc stateBegin(l *lexer.Lexer) lexer.StateFn ", "output": "{\n\tr, n := l.Advance()\n\n\tswitch r {\n\tcase '{':\n\t\tl.Emit(itemLeftBrace)\n\t\treturn stateBegin\n\tcase '}':\n\t\tl.Emit(itemRightBrace)\n\t\treturn stateBegin\n\tcase '(':\n\t\tl.Emit(itemLeftParen)\n\t\treturn stateBegin\n\tcase ')':\n\t\tl.Emit(itemRightParen)\n\t\treturn stateBegin\n\tcase ',':\n\t\tl.Emit(itemComma)\n\t\treturn stateBegin\n\tcase '\"':\n\t\tl.Backup()\n\t\treturn stateQuotedString\n\tdefault:\n\t\tif n > 0 {\n\t\t\tl.Backup()\n\t\t\treturn stateBareString\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package runewidth\n\nimport (\n\t\"testing\"\n\t\"unicode/utf8\"\n)\n\nvar benchSink int\n\nfunc benchTable(b *testing.B, tbl table) int {\n\tn := 0\n\tfor i := 0; i < b.N; i++ {\n\t\tfor r := rune(0); r <= utf8.MaxRune; r++ {\n\t\t\tif inTable(r, tbl) {\n\t\t\t\tn++\n\t\t\t}\n\t\t}\n\t}\n\treturn n\n}\n\nfunc BenchmarkTablePrivate(b *testing.B) {\n\tbenchSink = benchTable(b, private)\n}\nfunc BenchmarkTableNonprint(b *testing.B) {\n\tbenchSink = benchTable(b, nonprint)\n}\nfunc BenchmarkTableCombining(b *testing.B) {\n\tbenchSink = benchTable(b, combining)\n}\nfunc BenchmarkTableDoublewidth(b *testing.B) {\n\tbenchSink = benchTable(b, doublewidth)\n}\nfunc BenchmarkTableAmbiguous(b *testing.B) {\n\tbenchSink = benchTable(b, ambiguous)\n}\n\nfunc BenchmarkTableNotassigned(b *testing.B) {\n\tbenchSink = benchTable(b, notassigned)\n}\nfunc BenchmarkTableNeutral(b *testing.B) {\n\tbenchSink = benchTable(b, neutral)\n}\n\nfunc BenchmarkTableEmoji(b *testing.B) ", "output": "{\n\tbenchSink = benchTable(b, emoji)\n}"} {"input": "package glacier\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/rdwilliamson/aws\"\n)\n\n\ntype Connection struct {\n\tClient *http.Client\n\n\tSignature *aws.Signature\n}\n\nfunc (c *Connection) client() *http.Client {\n\tif c.Client == nil {\n\t\treturn http.DefaultClient\n\t}\n\treturn c.Client\n}\n\n\nfunc (c *Connection) vault(vault string) string {\n\treturn \"https://\" + c.Signature.Region.Glacier + \"/-/vaults/\" + vault\n}\n\n\nfunc (c *Connection) policy(policy string) string {\n\treturn \"https://\" + c.Signature.Region.Glacier + \"/-/policies/\" + policy\n}\n\n\n\nfunc NewConnection(secret, access string, r *aws.Region) *Connection {\n\treturn &Connection{\n\t\tSignature: aws.NewSignature(secret, access, r, \"glacier\"),\n\t}\n}\n\n\n\n\n\n\n\n\ntype parameters url.Values\n\n\n\nfunc (p parameters) add(key, value string) {\n\turl.Values(p).Add(key, value)\n}\n\n\n\nfunc (p parameters) encode() string {\n\tif encoded := url.Values(p).Encode(); encoded != \"\" {\n\t\treturn \"?\" + encoded\n\t}\n\treturn \"\"\n}\n\nfunc toHex(x []byte) string ", "output": "{\n\treturn fmt.Sprintf(\"%x\", x)\n}"} {"input": "package loggabletracer\n\nimport opentracing \"gx/ipfs/QmWLWmRVSiagqP15jczsGME1qpob6HDbtbHAY2he9W5iUo/opentracing-go\"\n\ntype accessorPropagator struct {\n\ttracer *LoggableTracer\n}\n\n\n\n\ntype DelegatingCarrier interface {\n\tSetState(traceID, spanID uint64, sampled bool)\n\tState() (traceID, spanID uint64, sampled bool)\n\tSetBaggageItem(key, value string)\n\tGetBaggage(func(key, value string))\n}\n\nfunc (p *accessorPropagator) Inject(\n\tspanContext opentracing.SpanContext,\n\tcarrier interface{},\n) error {\n\tdc, ok := carrier.(DelegatingCarrier)\n\tif !ok || dc == nil {\n\t\treturn opentracing.ErrInvalidCarrier\n\t}\n\tsc, ok := spanContext.(SpanContext)\n\tif !ok {\n\t\treturn opentracing.ErrInvalidSpanContext\n\t}\n\tdc.SetState(sc.TraceID, sc.SpanID, sc.Sampled)\n\tfor k, v := range sc.Baggage {\n\t\tdc.SetBaggageItem(k, v)\n\t}\n\treturn nil\n}\n\n\n\nfunc (p *accessorPropagator) Extract(\n\tcarrier interface{},\n) (opentracing.SpanContext, error) ", "output": "{\n\tdc, ok := carrier.(DelegatingCarrier)\n\tif !ok || dc == nil {\n\t\treturn nil, opentracing.ErrInvalidCarrier\n\t}\n\n\ttraceID, spanID, sampled := dc.State()\n\tsc := SpanContext{\n\t\tTraceID: traceID,\n\t\tSpanID: spanID,\n\t\tSampled: sampled,\n\t\tBaggage: nil,\n\t}\n\tdc.GetBaggage(func(k, v string) {\n\t\tif sc.Baggage == nil {\n\t\t\tsc.Baggage = map[string]string{}\n\t\t}\n\t\tsc.Baggage[k] = v\n\t})\n\n\treturn sc, nil\n}"} {"input": "package certificates\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gophercloud/gophercloud\"\n)\n\n\n\ntype CreateOptsBuilder interface {\n\tToCertificateCreateMap() (map[string]interface{}, error)\n}\n\n\ntype CreateOpts struct {\n\tClusterUUID string `json:\"cluster_uuid,omitempty\" xor:\"BayUUID\"`\n\tBayUUID string `json:\"bay_uuid,omitempty\" xor:\"ClusterUUID\"`\n\tCSR string `json:\"csr\" required:\"true\"`\n}\n\n\nfunc (opts CreateOpts) ToCertificateCreateMap() (map[string]interface{}, error) {\n\treturn gophercloud.BuildRequestBody(opts, \"\")\n}\n\n\nfunc Get(client *gophercloud.ServiceClient, clusterID string) (r GetResult) {\n\turl := getURL(client, clusterID)\n\n\t_, r.Err = client.Get(url, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{200},\n\t})\n\n\treturn\n}\n\n\n\n\n\nfunc Update(client *gophercloud.ServiceClient, clusterID string) (r UpdateResult) {\n\t_, r.Err = client.Patch(updateURL(client, clusterID), nil, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{202},\n\t})\n\n\treturn\n}\n\nfunc Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) ", "output": "{\n\tb, err := opts.ToCertificateCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\n\tvar result *http.Response\n\tresult, r.Err = client.Post(createURL(client), b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{201},\n\t})\n\n\tif r.Err == nil {\n\t\tr.Header = result.Header\n\t}\n\n\treturn\n}"} {"input": "package monator\n\nimport (\n \"time\"\n \"bytes\"\n \"encoding/json\"\n)\n\ntype CheckDuration time.Duration\n\nfunc (d CheckDuration) Hours() float64 {\n return time.Duration(d).Hours()\n}\n\nfunc (d CheckDuration) Minutes() float64 {\n return time.Duration(d).Minutes()\n}\n\nfunc (d CheckDuration) Nanoseconds() int64 {\n return time.Duration(d).Nanoseconds()\n}\n\nfunc (d CheckDuration) Seconds() float64 {\n return time.Duration(d).Seconds()\n}\n\nfunc (d CheckDuration) Milliseconds() int64 {\n return time.Duration(d).Nanoseconds() / int64(time.Millisecond)\n}\n\nfunc (d CheckDuration) String() string {\n \n rounded := ((time.Duration(d)).Nanoseconds() / int64(time.Millisecond)) * int64(time.Millisecond)\n return time.Duration(rounded).String()\n}\n\n\n\n\nfunc (d *CheckDuration) UnmarshalJSON(data []byte) error ", "output": "{\n b := bytes.NewBuffer(data)\n dec := json.NewDecoder(b)\n\n var s string\n\n if err := dec.Decode(&s); err != nil {\n return err\n }\n if duration, err := time.ParseDuration(s); err != nil {\n return err\n } else {\n *d = CheckDuration(duration)\n }\n\n return nil\n}"} {"input": "package chunks\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\n\t\"github.com/rtmfpew/amfy/vlu\"\n)\n\nconst BufferProbeChunkType = 0x18\n\n\ntype BufferProbeChunk struct {\n\tFlowID vlu.Vlu\n}\n\nfunc (chnk *BufferProbeChunk) Type() byte {\n\treturn BufferProbeChunkType\n}\n\n\n\nfunc (chnk *BufferProbeChunk) WriteTo(buffer *bytes.Buffer) error {\n\n\terr := buffer.WriteByte(chnk.Type())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = binary.Write(buffer, binary.BigEndian, chnk.Len()-1); err != nil {\n\t\treturn err\n\t}\n\n\tif err = chnk.FlowID.WriteTo(buffer); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (chnk *BufferProbeChunk) ReadFrom(buffer *bytes.Buffer) error {\n\n\tlength := uint16(0)\n\terr := binary.Read(buffer, binary.BigEndian, &length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = chnk.FlowID.ReadFrom(buffer); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (chnk *BufferProbeChunk) Len() uint16 ", "output": "{\n\treturn 1 + uint16(chnk.FlowID.ByteLength())\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype Page struct {\n\tTitle string\n\tBody []byte\n}\n\n\n\nfunc loadPage(title string) (*Page, error) {\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\treturn &Page{Title: title, Body: body}, err\n}\n\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/view/\"):]\n\tp, _ := loadPage(title)\n\tfmt.Fprintf(w, \"

%s

%s
\", p.Title, p.Body)\n}\n\n\nfunc defaultHandler(w http.ResponseWriter, r *http.Request) {\n\tdump, err := httputil.DumpRequest(r, true)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(string(dump))\n\n\tp, err := loadPage(\"TestPage\") \n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Fprintf(w, \"

%s

%s
\", p.Title, p.Body)\n}\n\n\nfunc main() {\n\tdir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tbody := \"This is a test page under: \" + dir\n\tp1 := &Page{Title: \"TestPage\", Body: []byte(body)}\n\tp1.save()\n\tp2, _ := loadPage(\"TestPage\")\n\tfmt.Println(string(p2.Body))\n\n\thttp.HandleFunc(\"/\", defaultHandler)\n\thttp.ListenAndServe(\":8081\", nil)\n}\n\nfunc (p *Page) save() error ", "output": "{\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}"} {"input": "package iso20022\n\n\ntype SettlementDateTimeIndication1 struct {\n\n\tDebitDateTime *ISODateTime `xml:\"DbtDtTm,omitempty\"`\n\n\tCreditDateTime *ISODateTime `xml:\"CdtDtTm,omitempty\"`\n}\n\nfunc (s *SettlementDateTimeIndication1) SetDebitDateTime(value string) {\n\ts.DebitDateTime = (*ISODateTime)(&value)\n}\n\n\n\nfunc (s *SettlementDateTimeIndication1) SetCreditDateTime(value string) ", "output": "{\n\ts.CreditDateTime = (*ISODateTime)(&value)\n}"} {"input": "package tests\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestBlockchain(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\tbt := new(testMatcher)\n\tbt.skipLoad(`^GeneralStateTests/`)\n\tbt.skipLoad(`^bcForgedTest/bcForkUncle\\.json`)\n\tbt.skipLoad(`^bcMultiChainTest/(ChainAtoChainB_blockorder|CallContractFromNotBestBlock)`)\n\tbt.skipLoad(`^bcTotalDifficultyTest/(lotsOfLeafs|lotsOfBranches|sideChainWithMoreTransactions)`)\n\tbt.skipLoad(`(?i)(constantinople)`)\n\n\tbt.skipLoad(`^bcWalletTest.*_Byzantium$`)\n\n\tbt.walk(t, blockTestDir, func(t *testing.T, name string, test *BlockTest) {\n\t\tif err := bt.checkFailure(t, name, test.Run()); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"bufio\"\n\t\"fmt\"\n)\n\ntype Store struct {\n\n}\n\nfunc NewStore() *Store {\n\treturn &Store{}\n}\n\nfunc (s Store)ReadStore(file string) (map[string]string, error) {\n\tstore := make(map[string]string)\n\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn store, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\thandleCommand(store, scanner.Text())\n\t}\n\n\treturn store, scanner.Err()\n}\n\n\n\nfunc (s Store)WriteTo(store map[string]string, w io.Writer) error {\n\tfor k, v := range store {\n\t\tif _, err := fmt.Fprintf(w, \"%v=%v\\n\", k, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s Store)WriteStore(store map[string]string, file string) error ", "output": "{\n\tf, err := os.Create(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\treturn s.WriteTo(store, f)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\ntype Person struct {\n\tName string\n\tAge int\n}\n\ntype ByName []Person\n\nfunc (this ByName) Len() int {\n\treturn len(this)\n}\n\nfunc (this ByName) Less(i, j int) bool {\n\treturn this[i].Name < this[j].Name\n}\n\n\n\nfunc main() {\n\tkids := []Person{\n\t\t{\"Jill\", 9},\n\t\t{\"Jack\", 10},\n\t}\n\tsort.Sort(ByName(kids))\n\tfmt.Println(kids)\n}\n\nfunc (this ByName) Swap(i, j int) ", "output": "{\n\tthis[i], this[j] = this[j], this[i]\n}"} {"input": "package service\n\nimport (\n\t\"bytes\"\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"errors\"\n\t\"io\"\n)\n\nfunc pad(src []byte) []byte {\n\tpadding := aes.BlockSize - len(src)%aes.BlockSize\n\tpadText := bytes.Repeat([]byte{byte(padding)}, padding)\n\treturn append(src, padText...)\n}\n\n\n\nfunc (s *Service) encrypt(text string) (string, error) {\n\tmsg := pad([]byte(text))\n\tcipherText := make([]byte, aes.BlockSize+len(msg))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcfb := cipher.NewCFBEncrypter(s.AESBlock, iv)\n\tcfb.XORKeyStream(cipherText[aes.BlockSize:], []byte(msg))\n\tfinalMsg := base64.URLEncoding.EncodeToString(cipherText)\n\treturn finalMsg, nil\n}\n\nfunc (s *Service) decrypt(text string) (string, error) {\n\tdecodedMsg, err := base64.URLEncoding.DecodeString(text)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif (len(decodedMsg) % aes.BlockSize) != 0 {\n\t\treturn \"\", errors.New(\"blocksize must be multipe of decoded message length\")\n\t}\n\n\tiv := decodedMsg[:aes.BlockSize]\n\tmsg := decodedMsg[aes.BlockSize:]\n\n\tcfb := cipher.NewCFBDecrypter(s.AESBlock, iv)\n\tcfb.XORKeyStream(msg, msg)\n\n\tunpadMsg, err := unpad(msg)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(unpadMsg), nil\n}\n\nfunc unpad(src []byte) ([]byte, error) ", "output": "{\n\tlength := len(src)\n\tunpadding := int(src[length-1])\n\n\tif unpadding > length {\n\t\treturn nil, errors.New(\"unpad error. This could happen when incorrect encryption key is used\")\n\t}\n\n\treturn src[:(length - unpadding)], nil\n}"} {"input": "package leet_20\n\ntype Stack []byte\n\nfunc (s *Stack) Pop() byte {\n\tc := s.Top()\n\tlength := len(*s)\n\tif length <= 1 {\n\t\t*s = nil\n\t} else {\n\t\t*s = (*s)[:length-1]\n\t}\n\treturn c\n}\n\nfunc (s *Stack) Empty() bool {\n\treturn nil == s || *s == nil || len(*s) == 0\n}\n\nfunc (s *Stack) Push(x byte) {\n\t*s = append(*s, x)\n}\n\nfunc (s *Stack) Top() byte {\n\tlength := len(*s)\n\tif 0 == length {\n\t\treturn 0\n\t}\n\treturn (*s)[length-1]\n}\n\n\n\nfunc match(a, b byte) bool {\n\tif a == '[' && b == ']' {\n\t\treturn true\n\t}\n\tif a == '(' && b == ')' {\n\t\treturn true\n\t}\n\tif a == '{' && b == '}' {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc isValid(s string) bool {\n\tarr := []byte(s)\n\tstack := new(Stack)\n\tfor _, c := range arr {\n\t\tswitch c {\n\t\tcase '[', '{', '(':\n\t\t\tstack.Push(c)\n\t\t\tcontinue\n\t\t}\n\t\ttop := stack.Top()\n\t\tif match(top, c) {\n\t\t\tstack.Pop()\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn stack.Empty()\n}\n\nfunc (s *Stack) String() string ", "output": "{\n\treturn string(*s)\n}"} {"input": "package goweb\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\n\n\n\n\nfunc MapFunc(path string, controllerFunc interface{}, matcherFuncs ...interface{}) interface{} {\n\tdeprecatedPanic(\"MapFunc\", \"Use goweb.Map instead.\")\n\treturn nil\n}\n\n\n\n\nfunc MapRest(pathPrefix string, controller interface{}) {\n\tdeprecatedPanic(\"MapRest\", \"Use goweb.MapController instead.\")\n}\n\nfunc deprecatedPanic(method, alternativeTip string) ", "output": "{\n\tpanic(fmt.Sprintf(\"goweb: (deprecated) %s is no longer supported. %s\", method, alternativeTip))\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"github.com/mitchellh/multistep\"\n\t\"github.com/orivej/packer/packer\"\n)\n\n\n\n\ntype StepOutputDir struct {\n\tForce bool\n\tPath string\n\tsuccess bool\n}\n\nfunc (s *StepOutputDir) Run(state multistep.StateBag) multistep.StepAction {\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\tif _, err := os.Stat(s.Path); err == nil && s.Force {\n\t\tui.Say(\"Deleting previous output directory...\")\n\t\tos.RemoveAll(s.Path)\n\t}\n\n\tif err := os.MkdirAll(s.Path, 0755); err != nil {\n\t\tstate.Put(\"error\", err)\n\t\treturn multistep.ActionHalt\n\t}\n\n\tf, err := os.Create(filepath.Join(s.Path, \"_packer_perm_check\"))\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Couldn't write to output directory: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\treturn multistep.ActionHalt\n\t}\n\tf.Close()\n\tos.Remove(f.Name())\n\n\ts.success = true\n\treturn multistep.ActionContinue\n}\n\n\n\nfunc (s *StepOutputDir) Cleanup(state multistep.StateBag) ", "output": "{\n\t_, cancelled := state.GetOk(multistep.StateCancelled)\n\t_, halted := state.GetOk(multistep.StateHalted)\n\n\tif !s.success {\n\t\treturn\n\t}\n\n\tif cancelled || halted {\n\t\tui := state.Get(\"ui\").(packer.Ui)\n\n\t\tui.Say(\"Deleting output directory...\")\n\t\tfor i := 0; i < 5; i++ {\n\t\t\terr := os.RemoveAll(s.Path)\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tlog.Printf(\"Error removing output dir: %s\", err)\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/zx9597446/marchingsquare\"\n\t\"github.com/zx9597446/rdp\"\n\t\"image\"\n\t\"image/color\"\n\t\"image/png\"\n\t\"os\"\n)\n\nfunc panicIfErr(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\n\nfunc main() {\n\tret := marchingsquare.ProcessWithFile(\"terrain.png\", marchingsquare.TransparentTest)\n\tresult := rdp.Process(ret, 0.50)\n\tfmt.Println(len(ret), len(result))\n\tdebugDraw(result, \"terrain.png\", \"new.png\", color.RGBA{255, 0, 0, 255})\n}\n\nfunc debugDraw(result []image.Point, oldfile, newfile string, what color.Color) ", "output": "{\n\told, err := os.Open(oldfile)\n\tdefer old.Close()\n\tpanicIfErr(err)\n\toldimg, _, err := image.Decode(old)\n\tpanicIfErr(err)\n\tb := oldimg.Bounds()\n\tnewimg := image.NewRGBA(b)\n\tfor y := b.Min.Y; y < b.Max.Y; y++ {\n\t\tfor x := b.Min.X; x < b.Max.X; x++ {\n\t\t\tnewimg.Set(x, y, oldimg.At(x, y))\n\t\t}\n\t}\n\tfor _, pt := range result {\n\t\tnewimg.Set(pt.X, pt.Y, what)\n\t}\n\tfile, err := os.Create(newfile)\n\tdefer file.Close()\n\tpanicIfErr(err)\n\tpng.Encode(file, newimg)\n}"} {"input": "package fhash\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"path/filepath\"\n)\n\nconst (\n\tfhashData = \"fhashdata\"\n)\n\n\ntype Server struct {\n\tserver *http.Server\n\tconf *Config\n\tindex *Index \n\troot string \n}\n\n\n\n\n\nfunc (s *Server) Serve() {\n\thttp.HandleFunc(\"/putfile\", s.putFile)\n\thttp.HandleFunc(\"/getfile/\", s.getFile)\n\terr := s.server.ListenAndServe()\n\tif err != nil {\n\t\tlog.Printf(\"failed to serve: %v\", err)\n\t}\n}\n\n\nfunc (s *Server) Shutdown() error {\n\terr := s.index.close()\n\treturn err\n}\n\nfunc NewServer(config *Config) (*Server, error) ", "output": "{\n\tindex, err := NewIndex(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"index error: %v\", err)\n\t}\n\n\troot := filepath.Join(config.Server.Root, fhashData)\n\tserver := &Server{\n\t\tserver: &http.Server{\n\t\t\tAddr: config.Server.Address,\n\t\t},\n\t\tconf: config,\n\t\tindex: index,\n\t\troot: root,\n\t}\n\treturn server, nil\n}"} {"input": "package main\n\nimport(\n\t\"log\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"net/http\"\n\t\"encoding/json\"\n\t\"github.com/julienschmidt/httprouter\"\n)\n\ntype KeyPair struct\t{\n\n\tKey int `json:\"key\"`\n\tValue string `json:\"value\"`\n}\n\nvar KV = make(map[int]KeyPair)\n\nfunc main() {\n\tfmt.Println(\"Starting server on Port : 3000\")\n\trouter := httprouter.New()\n\trouter.Handle(\"PUT\",\"/keys/:keypair_id/:keypair_value\", InsertKeyPair)\n\trouter.Handle(\"GET\",\"/keys/:keypair_id\",GetKeyPair)\n\trouter.Handle(\"GET\",\"/keys\", GetAllKeyPair)\n\tlog.Fatal(http.ListenAndServe(\":3000\", router))\n}\n\nfunc InsertKeyPair(w http.ResponseWriter, r *http.Request, ps httprouter.Params)\t{\n\n\tvar key int\n\tvar value string\n\n\tkey,_ = strconv.Atoi(ps.ByName(\"keypair_id\"))\n\tvalue = ps.ByName(\"keypair_value\")\n\tkeyPair := KeyPair{key,value}\n\tKV[key] = keyPair\n}\n\n\n\nfunc GetAllKeyPair(w http.ResponseWriter, r* http.Request, _ httprouter.Params)\t{\n\tstore := make([]KeyPair, len(KV))\n\tindex := 0\n\tfor _, value := range KV {\n \tstore[index] = value\n \tindex++\n\t}\n\tjson.NewEncoder(w).Encode(store)\n}\n\nfunc GetKeyPair(w http.ResponseWriter, r *http.Request, ps httprouter.Params)\t", "output": "{\n\n\tkey,_ := strconv.Atoi(ps.ByName(\"keypair_id\"))\n\telem, ok := KV[key]\n\tif ok {\n\n\t\tw.WriteHeader(http.StatusCreated)\n \tjson.NewEncoder(w).Encode(elem)\n\t\tfmt.Println(elem)\n\t}\n}"} {"input": "package memory\n\nimport (\n\t\"testing\"\n\n\tmbtest \"github.com/elastic/beats/metricbeat/mb/testing\"\n)\n\n\n\nfunc getConfig() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"module\": \"system\",\n\t\t\"metricsets\": []string{\"memory\"},\n\t}\n}\n\nfunc TestData(t *testing.T) ", "output": "{\n\tf := mbtest.NewEventFetcher(t, getConfig())\n\n\terr := mbtest.WriteEvent(f, t)\n\tif err != nil {\n\t\tt.Fatal(\"write\", err)\n\t}\n}"} {"input": "package cloudstorage\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n)\n\ntype MockStorage struct {\n\tPutRequest *http.Request\n\tGetURL *url.URL\n\tOriginallySigned bool\n\tListObjectsResponse *ListObjectsResponse\n}\n\nvar _ Storage = &MockStorage{}\n\nfunc (s *MockStorage) PresignPutObject(name string, accessType AccessType, header http.Header) (*http.Request, error) {\n\treturn s.PutRequest, nil\n}\n\nfunc (s *MockStorage) PresignGetObject(name string) (*url.URL, error) {\n\treturn s.GetURL, nil\n}\n\nfunc (s *MockStorage) PresignHeadObject(name string) (*url.URL, error) {\n\treturn s.GetURL, nil\n}\n\nfunc (s *MockStorage) RewriteGetURL(u *url.URL, name string) (*url.URL, bool, error) {\n\treturn s.GetURL, s.OriginallySigned, nil\n}\n\nfunc (s *MockStorage) ListObjects(r *ListObjectsRequest) (*ListObjectsResponse, error) {\n\treturn s.ListObjectsResponse, nil\n}\n\nfunc (s *MockStorage) DeleteObject(name string) error {\n\treturn nil\n}\n\nfunc (s *MockStorage) AccessType(header http.Header) AccessType {\n\treturn AccessTypeDefault\n}\n\nfunc (s *MockStorage) StandardToProprietary(header http.Header) http.Header {\n\treturn header\n}\n\n\n\nfunc (s *MockStorage) ProprietaryToStandard(header http.Header) http.Header ", "output": "{\n\treturn header\n}"} {"input": "package v1\n\nimport (\n\t\"gopkg.in/guregu/null.v3\"\n\n\t\"go.k6.io/k6/core\"\n\t\"go.k6.io/k6/lib\"\n)\n\ntype Status struct {\n\tStatus lib.ExecutionStatus `json:\"status\" yaml:\"status\"`\n\n\tPaused null.Bool `json:\"paused\" yaml:\"paused\"`\n\tVUs null.Int `json:\"vus\" yaml:\"vus\"`\n\tVUsMax null.Int `json:\"vus-max\" yaml:\"vus-max\"`\n\tStopped bool `json:\"stopped\" yaml:\"stopped\"`\n\tRunning bool `json:\"running\" yaml:\"running\"`\n\tTainted bool `json:\"tainted\" yaml:\"tainted\"`\n}\n\nfunc NewStatus(engine *core.Engine) Status {\n\texecutionState := engine.ExecutionScheduler.GetState()\n\treturn Status{\n\t\tStatus: executionState.GetCurrentExecutionStatus(),\n\t\tRunning: executionState.HasStarted() && !executionState.HasEnded(),\n\t\tPaused: null.BoolFrom(executionState.IsPaused()),\n\t\tStopped: engine.IsStopped(),\n\t\tVUs: null.IntFrom(executionState.GetCurrentlyActiveVUsCount()),\n\t\tVUsMax: null.IntFrom(executionState.GetInitializedVUsCount()),\n\t\tTainted: engine.IsTainted(),\n\t}\n}\n\nfunc (s Status) GetName() string {\n\treturn \"status\"\n}\n\n\n\nfunc (s Status) SetID(id string) error {\n\treturn nil\n}\n\nfunc (s Status) GetID() string ", "output": "{\n\treturn \"default\"\n}"} {"input": "package main\n\nimport \"github.com/augustoroman/serial_lcd\"\n\ntype FakeLcd struct{}\n\nfunc (f FakeLcd) SetBG(r, g, b uint8) error { return nil }\nfunc (f FakeLcd) SetOn(On bool) error { return nil }\nfunc (f FakeLcd) SetBrightness(b uint8) error { return nil }\nfunc (f FakeLcd) SetContrast(c uint8) error { return nil }\n\nfunc (f FakeLcd) SetSize(cols, rows uint8) error { return nil }\nfunc (f FakeLcd) Clear() error { return nil }\nfunc (f FakeLcd) Home() error { return nil }\nfunc (f FakeLcd) MoveTo(col, row uint8) error { return nil }\nfunc (f FakeLcd) MoveForward() error { return nil }\nfunc (f FakeLcd) MoveBack() error { return nil }\nfunc (f FakeLcd) Write(b []byte) (int, error) { return len(b), nil }\n\nfunc (f FakeLcd) CreateCustomChar(spot uint8, c serial_lcd.Char) error { return nil }\n\nfunc (f FakeLcd) SetAutoscroll(On bool) error ", "output": "{ return nil }"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/bitly/go-nsq\"\n\t\"log\"\n\t\"time\"\n)\n\nvar (\n\tPublisher *MsgPublisher\n)\n\ntype MsgPublisher struct {\n\tusr User\n\twriter *nsq.Writer\n}\n\nfunc init() {\n\tPublisher = &MsgPublisher{\n\t\twriter: nsq.NewWriter(\"106.186.31.48:4150\"),\n\t}\n}\n\n\n\nfunc (mp *MsgPublisher) Write(topic, msg string) (int32, []byte, error) {\n\tm := Message{\n\t\tTopic: topic,\n\t\tType: MSG_TYPE_CHAT,\n\t\tTime: time.Now().Format(\"2006-01-02 15:04:05\"),\n\t\tBody: MessageBody{\n\t\t\tFrom: mp.usr,\n\t\t\tMsg: msg,\n\t\t},\n\t}\n\tmsgBytes, _ := json.Marshal(m)\n\tlog.Println(\"Publish.msg = \", string(msgBytes))\n\treturn mp.writer.Publish(topic, msgBytes)\n}\n\nfunc (mp *MsgPublisher) WriteAsync(topic, msg string, responseChan chan *nsq.WriterTransaction) error {\n\tm := Message{\n\t\tTopic: topic,\n\t\tType: MSG_TYPE_CHAT,\n\t\tBody: MessageBody{\n\t\t\tFrom: mp.usr,\n\t\t\tMsg: msg,\n\t\t},\n\t}\n\tmsgBytes, _ := json.Marshal(m)\n\tlog.Println(\"PublishAsync.msg = \", string(msgBytes))\n\treturn mp.writer.PublishAsync(topic, msgBytes, responseChan, \"\")\n}\n\nfunc (mp *MsgPublisher) Stop() {\n\tmp.writer.Stop()\n}\n\nfunc (publisher *MsgPublisher) SetLoginUsr(_usr User) error ", "output": "{\n\tif Publisher == nil {\n\t\tPublisher = &MsgPublisher{\n\t\t\twriter: nsq.NewWriter(\"106.186.31.48:4150\"),\n\t\t}\n\t}\n\tPublisher.usr = _usr\n\tPublisher.usr.Pwd = \"xxxx\"\n\treturn nil\n}"} {"input": "package keybindings\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/atotto/clipboard\"\n\t\"github.com/dambrisco/bored/layout\"\n\t\"github.com/dambrisco/bored/reddit\"\n\t\"github.com/jroimartin/gocui\"\n\t\"github.com/toqueteos/webbrowser\"\n)\n\nfunc enter(g *gocui.Gui, v *gocui.View) error {\n\tsubmission := reddit.GetCurrentSubmission()\n\twebbrowser.Open(\"https://www.reddit.com/\" + submission.Permalink)\n\treturn nil\n}\n\nfunc link(g *gocui.Gui, v *gocui.View) error {\n\tsubmission := reddit.GetCurrentSubmission()\n\twebbrowser.Open(submission.URL)\n\treturn nil\n}\n\n\n\nfunc comments(g *gocui.Gui, v *gocui.View) error {\n\tlayout.SetPage(layout.Comments)\n\tlayout.Clear(g, v)\n\treturn nil\n}\n\nfunc info(g *gocui.Gui, v *gocui.View) error {\n\tif layout.GetPage() == layout.List {\n\t\ts := reddit.GetCurrentSubmission()\n\t\tb := v.Buffer()\n\t\tv.Clear()\n\t\tif strings.HasPrefix(b, \"S\") {\n\t\t\tfmt.Fprint(v, layout.BuildTitleTag(s))\n\t\t} else {\n\t\t\tfmt.Fprintf(v, \"Score: %d | Subreddit: %s\", s.Score, s.Subreddit)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc yank(g *gocui.Gui, v *gocui.View) error ", "output": "{\n\tsubmission := reddit.GetCurrentSubmission()\n\tclipboard.WriteAll(submission.URL)\n\treturn nil\n}"} {"input": "package contextutil_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/arjantop/cuirass/util/contextutil\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"golang.org/x/net/context\"\n)\n\nfunc TestDoErrorReturned(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\terr := contextutil.Do(ctx, func() error {\n\t\treturn errors.New(\"foo\")\n\t})\n\tassert.Equal(t, errors.New(\"foo\"), err)\n}\n\nfunc TestDoWithCancelErrorReturned(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\terr := contextutil.DoWithCancel(ctx, func() {}, func() error {\n\t\treturn errors.New(\"foo\")\n\t})\n\tassert.Equal(t, errors.New(\"foo\"), err)\n}\n\n\n\nfunc TestDoWithCancelTimeout(t *testing.T) ", "output": "{\n\tctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond)\n\tdefer cancel()\n\tvar called bool\n\terr := contextutil.DoWithCancel(ctx, func() { called = true }, func() error {\n\t\ttime.Sleep(2 * time.Nanosecond)\n\t\treturn nil\n\t})\n\tassert.Equal(t, context.DeadlineExceeded, err)\n}"} {"input": "package exporter\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\nfunc TestSanitizeValue(t *testing.T) {\n\ttests := []struct {\n\t\tInput string\n\t\tExpectedOutput float64\n\t\tShouldSucceed bool\n\t}{\n\t\t{\"1234\", 1234.0, true},\n\t\t{\"1234.5\", 1234.5, true},\n\t\t{\"true\", 1.0, true},\n\t\t{\"TRUE\", 1.0, true},\n\t\t{\"False\", 0.0, true},\n\t\t{\"FALSE\", 0.0, true},\n\t\t{\"abcd\", 0, false},\n\t\t{\"{}\", 0, false},\n\t\t{\"[]\", 0, false},\n\t\t{\"\", 0, false},\n\t\t{\"''\", 0, false},\n\t}\n\n\tfor i, test := range tests {\n\t\tactualOutput, err := SanitizeValue(test.Input)\n\t\tif err != nil && test.ShouldSucceed {\n\t\t\tt.Fatalf(\"Value snitization test %d failed with an unexpected error.\\nINPUT:\\n%q\\nERR:\\n%s\", i, test.Input, err)\n\t\t}\n\t\tif test.ShouldSucceed && actualOutput != test.ExpectedOutput {\n\t\t\tt.Fatalf(\"Value sanitization test %d fails unexpectedly.\\nGOT:\\n%f\\nEXPECTED:\\n%f\", i, actualOutput, test.ExpectedOutput)\n\t\t}\n\t}\n}\n\n\n\nfunc TestSanitizeValueNaN(t *testing.T) ", "output": "{\n\tactualOutput, err := SanitizeValue(\"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !math.IsNaN(actualOutput) {\n\t\tt.Fatalf(\"Value sanitization test for %f fails unexpectedly.\", math.NaN())\n\t}\n}"} {"input": "package shared\n\ntype RunTaskError struct {\n\tMessage string\n}\n\nfunc (e RunTaskError) Error() string {\n\treturn \"Error running task: {{.CloudControllerMessage}}\"\n}\n\n\n\ntype ClientTargetError struct {\n\tMessage string\n}\n\nfunc (e ClientTargetError) Error() string {\n\treturn \"{{.Message}}\\nNote that this command requires CF API version 3.0.0+.\"\n}\n\nfunc (e ClientTargetError) Translate(translate func(string, ...interface{}) string) string {\n\treturn translate(e.Error(), map[string]interface{}{\n\t\t\"Message\": e.Message,\n\t})\n}\n\nfunc (e RunTaskError) Translate(translate func(string, ...interface{}) string) string ", "output": "{\n\treturn translate(e.Error(), map[string]interface{}{\n\t\t\"CloudControllerMessage\": e.Message,\n\t})\n}"} {"input": "package analysisservices\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) BaseClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient ", "output": "{\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package types\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\t\"time\"\n)\n\n\n\ntype CommitObject struct {\n\tAuthor string\n\tMessage string\n\tTime time.Time\n\tTree Hash\n\tParents []Hash\n}\n\n\n\n\n\n\nfunc DeserializeCommitObject(input []byte) *CommitObject {\n\tbuffer := bytes.NewBuffer(input)\n\tdec := gob.NewDecoder(buffer)\n\n\tvar commit CommitObject\n\terr := dec.Decode(&commit)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &commit\n}\n\nfunc (commit *CommitObject) Serialize() []byte ", "output": "{\n\tbuffer := new(bytes.Buffer)\n\te := gob.NewEncoder(buffer)\n\terr := e.Encode(commit)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn buffer.Bytes()\n}"} {"input": "package policies\n\nimport (\n\t\"fmt\"\n \"github.com/megamsys/gulp/global\"\n)\n\n\ntype Policies interface {\n\tApply(*global.AssemblyWithComponents) (string, error)\n}\n\nvar policies = make(map[string]Policies)\nvar plug_policies = []string{\"bind\", \"ha\"}\n\nfunc RegisterPolicy(name string, policy Policies) {\n\tpolicies[name] = policy\n}\n\nfunc GetPolicy(name string) (Policies, error) {\n\tpolicy, ok := policies[name]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"policies not registered\")\n\t}\n\treturn policy, nil\n}\n\n\n\nfunc ApplyPolicies(asm *global.AssemblyWithComponents) ", "output": "{\n for k := range plug_policies {\n \tp, err := GetPolicy(plug_policies[k])\n\tif err != nil {\t\n\t \treturn \n\t}\t\t\n\tgo p.Apply(asm)\t \t\t\n } \n}"} {"input": "package signer\n\nimport (\n\t\"crypto\"\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"encoding/pem\"\n\t\"errors\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"github.com/EmpiresMod/GameLauncher/checksum\"\n)\n\nfunc ParsePublicPEM(b []byte) (pub *rsa.PublicKey, err error) {\n\n\tblock, _ := pem.Decode(b)\n\tif block == nil {\n\n\t\treturn nil, errors.New(\"Could not parse PEM data\")\n\t}\n\n\tkey, err := x509.ParsePKIXPublicKey(block.Bytes)\n\tif err != nil {\n\n\t\treturn\n\t}\n\n\treturn key.(*rsa.PublicKey), nil\n}\n\nfunc ParseFilePublicPEM(filename string) (pub *rsa.PublicKey, err error) {\n\n\tb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\n\t\treturn\n\t}\n\n\treturn ParsePublicPEM(b)\n}\n\n\n\nfunc VerifyFileCryptoSignature(filename string, sig []byte, pub *rsa.PublicKey) (err error) {\n\n\tf, err := os.Open(filename)\n\tif err != nil {\n\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\treturn VerifyCryptoSignature(f, sig, pub)\n}\n\nfunc VerifyCryptoSignature(r io.Reader, sig []byte, pub *rsa.PublicKey) (err error) ", "output": "{\n\n\thash, err := checksum.GenerateCheckSum(r)\n\tif err != nil {\n\n\t\treturn\n\t}\n\n\treturn rsa.VerifyPKCS1v15(pub, crypto.SHA256, hash, sig)\n}"} {"input": "package iso20022\n\n\ntype SubAccountIdentification11 struct {\n\n\tAccountOwner *PartyIdentification13Choice `xml:\"AcctOwnr,omitempty\"`\n\n\tSafekeepingAccount *SecuritiesAccount14 `xml:\"SfkpgAcct\"`\n\n\tActivityIndicator *YesNoIndicator `xml:\"ActvtyInd\"`\n\n\tBalanceForSubAccount []*AggregateBalanceInformation9 `xml:\"BalForSubAcct,omitempty\"`\n}\n\nfunc (s *SubAccountIdentification11) AddAccountOwner() *PartyIdentification13Choice {\n\ts.AccountOwner = new(PartyIdentification13Choice)\n\treturn s.AccountOwner\n}\n\n\n\nfunc (s *SubAccountIdentification11) SetActivityIndicator(value string) {\n\ts.ActivityIndicator = (*YesNoIndicator)(&value)\n}\n\nfunc (s *SubAccountIdentification11) AddBalanceForSubAccount() *AggregateBalanceInformation9 {\n\tnewValue := new(AggregateBalanceInformation9)\n\ts.BalanceForSubAccount = append(s.BalanceForSubAccount, newValue)\n\treturn newValue\n}\n\nfunc (s *SubAccountIdentification11) AddSafekeepingAccount() *SecuritiesAccount14 ", "output": "{\n\ts.SafekeepingAccount = new(SecuritiesAccount14)\n\treturn s.SafekeepingAccount\n}"} {"input": "package transformer\n\nimport (\n\t\"github.com/cloudevents/sdk-go/v2/binding\"\n\t\"github.com/cloudevents/sdk-go/v2/binding/spec\"\n)\n\n\n\n\n\nfunc DeleteExtension(name string) binding.TransformerFunc {\n\treturn SetExtension(name, func(i2 interface{}) (i interface{}, err error) {\n\t\treturn nil, nil\n\t})\n}\n\nfunc DeleteAttribute(attributeKind spec.Kind) binding.TransformerFunc ", "output": "{\n\treturn SetAttribute(attributeKind, func(i2 interface{}) (i interface{}, err error) {\n\t\treturn nil, nil\n\t})\n}"} {"input": "package l7filter\n\nimport (\n\t\"github.com/d2g/packetclassification\"\n)\n\n\n\nfunc init() ", "output": "{\n\tmypattern := Pattern{}\n\tmypattern.Name = \"socks\"\n\tmypattern.RegularExpresion = \"(?i)\" + \"\\\\x05[\\\\x01-\\\\x08]*\\\\x05[\\\\x01-\\\\x08]?.*\\\\x05[\\\\x01-\\\\x03][\\\\x01\\\\x03].*\\\\x05[\\\\x01-\\\\x08]?[\\\\x01\\\\x03]\"\n\tpacketclassification.RegisterClassifier(packetclassification.Classifier(mypattern))\n}"} {"input": "package daemon\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst PatchConfigOKCode int = 200\n\n\ntype PatchConfigOK struct {\n}\n\n\nfunc NewPatchConfigOK() *PatchConfigOK {\n\n\treturn &PatchConfigOK{}\n}\n\n\nfunc (o *PatchConfigOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(200)\n}\n\n\nconst PatchConfigBadRequestCode int = 400\n\n\ntype PatchConfigBadRequest struct {\n\n\tPayload models.Error `json:\"body,omitempty\"`\n}\n\n\nfunc NewPatchConfigBadRequest() *PatchConfigBadRequest {\n\n\treturn &PatchConfigBadRequest{}\n}\n\n\nfunc (o *PatchConfigBadRequest) WithPayload(payload models.Error) *PatchConfigBadRequest {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *PatchConfigBadRequest) SetPayload(payload models.Error) {\n\to.Payload = payload\n}\n\n\n\n\n\nconst PatchConfigFailureCode int = 500\n\n\ntype PatchConfigFailure struct {\n\n\tPayload models.Error `json:\"body,omitempty\"`\n}\n\n\nfunc NewPatchConfigFailure() *PatchConfigFailure {\n\n\treturn &PatchConfigFailure{}\n}\n\n\nfunc (o *PatchConfigFailure) WithPayload(payload models.Error) *PatchConfigFailure {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *PatchConfigFailure) SetPayload(payload models.Error) {\n\to.Payload = payload\n}\n\n\nfunc (o *PatchConfigFailure) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(500)\n\tpayload := o.Payload\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) \n\t}\n}\n\nfunc (o *PatchConfigBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\trw.WriteHeader(400)\n\tpayload := o.Payload\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) \n\t}\n}"} {"input": "package datacatalog\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteCustomPropertyRequest struct {\n\n\tCatalogId *string `mandatory:\"true\" contributesTo:\"path\" name:\"catalogId\"`\n\n\tNamespaceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"namespaceId\"`\n\n\tCustomPropertyKey *string `mandatory:\"true\" contributesTo:\"path\" name:\"customPropertyKey\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteCustomPropertyRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteCustomPropertyRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request DeleteCustomPropertyRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype DeleteCustomPropertyResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteCustomPropertyResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteCustomPropertyResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteCustomPropertyRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package plist\n\n\nimport \"C\"\nimport \"reflect\"\nimport \"strconv\"\n\n\n\ntype UnsupportedTypeError struct {\n\tType reflect.Type\n}\n\nfunc (e *UnsupportedTypeError) Error() string {\n\treturn \"plist: unsupported type: \" + e.Type.String()\n}\n\ntype UnsupportedValueError struct {\n\tValue reflect.Value\n\tStr string\n}\n\nfunc (e *UnsupportedValueError) Error() string {\n\treturn \"json: unsupported value: \" + e.Str\n}\n\ntype UnknownCFTypeError struct {\n\tCFTypeID C.CFTypeID\n}\n\n\n\n\n\n\n\n\n\ntype UnsupportedKeyTypeError struct {\n\tCFTypeID int\n}\n\nfunc (e *UnsupportedKeyTypeError) Error() string {\n\treturn \"plist: unexpected dictionary key CFTypeID \" + strconv.Itoa(e.CFTypeID)\n}\n\nfunc (e *UnknownCFTypeError) Error() string ", "output": "{\n\tcfStr := C.CFCopyTypeIDDescription(e.CFTypeID)\n\tstr := convertCFStringToString(cfStr)\n\tcfRelease(cfTypeRef(cfStr))\n\treturn \"plist: unknown CFTypeID \" + strconv.Itoa(int(e.CFTypeID)) + \" (\" + str + \")\"\n}"} {"input": "package tagclients\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/gotokatsuya/growthpush/dispatcher\"\n\t\"github.com/gotokatsuya/growthpush/util\"\n)\n\nconst endpoint = \"tag_clients\"\n\ntype CreateNewTagClientRequest struct {\n\tClientID string `json:\"clientId\"`\n\tTagID string `json:\"tagId\"`\n\tValue string `json:\"value\"`\n}\n\ntype CreateNewTagClientResponse struct {\n\tTagID json.Number `json:\"tagId\"`\n\tClientID json.Number `json:\"clientId\"`\n}\n\n\n\nfunc CreateNewTagClient(client *dispatcher.Client, req CreateNewTagClientRequest) (*CreateNewTagClientResponse, error) ", "output": "{\n\tparameters, err := util.JSONToMapString(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbody, err := client.DispatchPostRequest(endpoint, parameters)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp := new(CreateNewTagClientResponse)\n\tif err := json.Unmarshal(body, resp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/apier/v1\"\n\nfunc init() {\n\tc := &CmdRemoveActions{\n\t\tname: \"actions_remove\",\n\t\trpcMethod: \"ApierV1.RemoveActions\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdRemoveActions struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrRemoveActions\n\t*CommandExecuter\n}\n\nfunc (self *CmdRemoveActions) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdRemoveActions) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdRemoveActions) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrRemoveActions{}\n\t}\n\treturn self.rpcParams\n}\n\n\n\nfunc (self *CmdRemoveActions) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *CmdRemoveActions) PostprocessRpcParams() error ", "output": "{\n\treturn nil\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\n\n\n\nvar SandboxStatsBeamCmd = &cobra.Command{\n\tUse: \"beam\",\n\tShort: TRCLI(\"cli.sandbox.stats.beam.summary\"),\n\tLong: TRCLI(`cli.sandbox.stats.beam.description`),\n}\n\nfunc init() ", "output": "{\n\tSandboxStatsCmd.AddCommand(SandboxStatsBeamCmd)\n}"} {"input": "package main\n\nimport (\n\t. \"github.com/conclave/pcduino/core\"\n)\n\n\n\nfunc main() {\n\tfor {\n\t\tloop()\n\t}\n}\n\nvar touchPin byte = 1\nvar ledPin byte = 0\n\nfunc setup() {\n\tprintln(\"Touch sensor test code!\")\n\tprintln(\"Using I/O_0=Drive LED, I/O_1=Sensor output.\")\n\tPinMode(touchPin, INPUT)\n\tPinMode(ledPin, OUTPUT)\n}\n\nfunc loop() {\n\tval := DigitalRead(touchPin)\n\tDigitalWrite(ledPin, val)\n}\n\nfunc init() ", "output": "{\n\tInit()\n\tsetup()\n}"} {"input": "package v1\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/unversioned\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\nconst GroupName = \"\"\n\n\nvar SchemeGroupVersion = unversioned.GroupVersion{Group: GroupName, Version: \"v1\"}\n\nfunc AddToScheme(scheme *runtime.Scheme) {\n\taddKnownTypes(scheme)\n\taddConversionFuncs(scheme)\n}\n\n\nfunc addKnownTypes(scheme *runtime.Scheme) {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t&Project{},\n\t\t&ProjectList{},\n\t\t&ProjectRequest{},\n\t)\n}\n\nfunc (obj *ProjectRequest) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta }\n\nfunc (obj *ProjectList) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta }\n\nfunc (obj *Project) GetObjectKind() unversioned.ObjectKind ", "output": "{ return &obj.TypeMeta }"} {"input": "package k1\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t\"github.com/songgao/water\"\n)\n\nfunc execCommand(name, sargs string) error {\n\targs := strings.Split(sargs, \" \")\n\tcmd := exec.Command(name, args...)\n\tlogger.Infof(\"exec command: %s %s\", name, sargs)\n\treturn cmd.Run()\n}\n\nfunc initTun(tun string, ipNet *net.IPNet, mtu int) error {\n\tip := ipNet.IP\n\tmaskIP := net.IP(ipNet.Mask)\n\tsargs := fmt.Sprintf(\"%s %s %s mtu %d netmask %s up\", tun, ip.String(), ip.String(), mtu, maskIP.String())\n\tif err := execCommand(\"ifconfig\", sargs); err != nil {\n\t\treturn err\n\t}\n\treturn addRoute(tun, ipNet)\n}\n\nfunc addRoute(tun string, subnet *net.IPNet) error {\n\tip := subnet.IP\n\tmaskIP := net.IP(subnet.Mask)\n\tsargs := fmt.Sprintf(\"-n add -net %s -netmask %s -interface %s\", ip.String(), maskIP.String(), tun)\n\treturn execCommand(\"route\", sargs)\n}\n\n\n\n\nfunc fixTunIP(ip net.IP) net.IP {\n\treturn net.IPv4zero\n}\n\nfunc createTun(ip net.IP, mask net.IPMask) (*water.Interface, error) ", "output": "{\n\tifce, err := water.New(water.Config{\n\t\tDeviceType: water.TUN,\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger.Infof(\"create %s\", ifce.Name())\n\n\tipNet := &net.IPNet{\n\t\tIP: ip,\n\t\tMask: mask,\n\t}\n\n\tif err := initTun(ifce.Name(), ipNet, MTU); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ifce, nil\n}"} {"input": "package clock\n\nimport \"time\"\n\n\nvar Work Clock\n\nfunc init() {\n\tWork = New()\n}\n\n\nfunc Now() time.Time {\n\treturn Work.Now()\n}\n\nfunc Since(t time.Time) time.Duration {\n\treturn Work.Now().Sub(t)\n}\n\n\n\nfunc Sleep(d time.Duration) {\n\tWork.Sleep(d)\n}\n\n\n\n\n\n\n\nfunc Tick(d time.Duration) <-chan time.Time {\n\treturn Work.Tick(d)\n}\n\n\n\n\n\nfunc Ticker(d time.Duration) *time.Ticker {\n\treturn Work.Ticker(d)\n}\n\n\ntype Clock interface {\n\n\tNow() time.Time\n\n\tSleep(d time.Duration)\n\n\tAfter(d time.Duration) <-chan time.Time\n\n\tTick(d time.Duration) <-chan time.Time\n\n\tTicker(d time.Duration) *time.Ticker\n\n}\n\n\ntype Mock interface {\n\tClock\n\n\n\tSet(t time.Time) Mock\n\n\tAdd(d time.Duration) Mock\n\n\tFreeze() Mock\n\n\tIsFrozen() bool\n\n\tUnfreeze() Mock\n\n\tClose()\n}\n\nfunc After(d time.Duration) <-chan time.Time ", "output": "{\n\treturn Work.After(d)\n}"} {"input": "package redis\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\n\t\"github.com/iris-framework/iris/adaptors/sessions/sessiondb/redis/service\"\n)\n\n\ntype Database struct {\n\tredis *service.Service\n}\n\n\n\n\n\nfunc (d *Database) Config() *service.Config {\n\treturn d.redis.Config\n}\n\n\nfunc (d *Database) Load(sid string) map[string]interface{} {\n\tvalues := make(map[string]interface{})\n\n\tif !d.redis.Connected { \n\t\td.redis.Connect()\n\t\t_, err := d.redis.PingPong()\n\t\tif err != nil {\n\t\t\tif err != nil {\n\t\t\t}\n\t\t}\n\t}\n\tval, err := d.redis.GetBytes(sid)\n\tif err == nil {\n\t\tDeserializeBytes(val, &values)\n\t}\n\n\treturn values\n\n}\n\n\nfunc serialize(values map[string]interface{}) []byte {\n\tval, err := SerializeBytes(values)\n\tif err != nil {\n\t\tprintln(\"On redisstore.serialize: \" + err.Error())\n\t}\n\n\treturn val\n}\n\n\nfunc (d *Database) Update(sid string, newValues map[string]interface{}) {\n\tif len(newValues) == 0 {\n\t\tgo d.redis.Delete(sid)\n\t} else {\n\t\tgo d.redis.Set(sid, serialize(newValues)) \n\t}\n\n}\n\n\nfunc SerializeBytes(m interface{}) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tenc := gob.NewEncoder(buf)\n\terr := enc.Encode(m)\n\tif err == nil {\n\t\treturn buf.Bytes(), nil\n\t}\n\treturn nil, err\n}\n\n\nfunc DeserializeBytes(b []byte, m interface{}) error {\n\tdec := gob.NewDecoder(bytes.NewBuffer(b))\n\treturn dec.Decode(m) \n}\n\nfunc New(cfg ...service.Config) *Database ", "output": "{\n\treturn &Database{redis: service.New(cfg...)}\n}"} {"input": "package gumble\n\nimport (\n\t\"github.com/unascribed/gumble/gumble/MumbleProto\"\n)\n\n\ntype RegisteredUser struct {\n\tUserID uint32\n\tName string\n\n\tchanged bool\n\tderegister bool\n}\n\n\n\n\n\nfunc (ru *RegisteredUser) Deregister() {\n\tru.deregister = true\n}\n\n\n\nfunc (ru *RegisteredUser) Register() {\n\tru.deregister = false\n}\n\n\nfunc (ru *RegisteredUser) ACLUser() *ACLUser {\n\treturn &ACLUser{\n\t\tUserID: ru.UserID,\n\t\tName: ru.Name,\n\t}\n}\n\n\n\n\n\ntype RegisteredUsers []*RegisteredUser\n\nfunc (pm RegisteredUsers) writeMessage(client *Client) error {\n\tpacket := MumbleProto.UserList{}\n\n\tfor _, user := range pm {\n\t\tif user.deregister || user.changed {\n\t\t\tuserListUser := &MumbleProto.UserList_User{\n\t\t\t\tUserId: &user.UserID,\n\t\t\t}\n\t\t\tif !user.deregister {\n\t\t\t\tuserListUser.Name = &user.Name\n\t\t\t}\n\t\t\tpacket.Users = append(packet.Users, userListUser)\n\t\t}\n\t}\n\n\tif len(packet.Users) <= 0 {\n\t\treturn nil\n\t}\n\tproto := protoMessage{&packet}\n\treturn proto.writeMessage(client)\n}\n\nfunc (ru *RegisteredUser) SetName(name string) ", "output": "{\n\tru.Name = name\n\tru.changed = true\n}"} {"input": "package utils\n\nimport \"fmt\"\n\n\n\nfunc ExampleToFixed() ", "output": "{\n\tfmt.Println(ToFixed(1.2345678, 0))\n\tfmt.Println(ToFixed(1.2345678, 1))\n\tfmt.Println(ToFixed(1.2345678, 2))\n\tfmt.Println(ToFixed(1.2345678, 3))\n\n}"} {"input": "package unix\n\nimport \"unsafe\"\n\n\n\nvar fcntl64Syscall uintptr = SYS_FCNTL\n\n\n\n\nfunc FcntlInt(fd uintptr, cmd, arg int) (int, error) {\n\treturn fcntl(int(fd), cmd, arg)\n}\n\n\nfunc FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error {\n\t_, _, errno := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(unsafe.Pointer(lk)))\n\tif errno == 0 {\n\t\treturn nil\n\t}\n\treturn errno\n}\n\nfunc fcntl(fd int, cmd, arg int) (int, error) ", "output": "{\n\tvalptr, _, errno := Syscall(fcntl64Syscall, uintptr(fd), uintptr(cmd), uintptr(arg))\n\tvar err error\n\tif errno != 0 {\n\t\terr = errno\n\t}\n\treturn int(valptr), err\n}"} {"input": "package winrm\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\ntype Endpoint struct {\n\tHost string\n\tPort int\n\tHTTPS bool\n\tInsecure bool\n\tTLSServerName string\n\tCACert []byte \n\tKey []byte \n\tCert []byte \n\tTimeout time.Duration\n}\n\n\n\n\nfunc NewEndpoint(host string, port int, https bool, insecure bool, Cacert, cert, key []byte, timeout time.Duration) *Endpoint {\n\tendpoint := &Endpoint{\n\t\tHost: host,\n\t\tPort: port,\n\t\tHTTPS: https,\n\t\tInsecure: insecure,\n\t\tCACert: Cacert,\n\t\tKey: key,\n\t\tCert: cert,\n\t}\n\tif timeout != 0 {\n\t\tendpoint.Timeout = timeout\n\t} else {\n\t\tendpoint.Timeout = 60 * time.Second\n\t}\n\n\treturn endpoint\n}\n\nfunc (ep *Endpoint) url() string ", "output": "{\n\tvar scheme string\n\tif ep.HTTPS {\n\t\tscheme = \"https\"\n\t} else {\n\t\tscheme = \"http\"\n\t}\n\n\treturn fmt.Sprintf(\"%s://%s:%d/wsman\", scheme, ep.Host, ep.Port)\n}"} {"input": "package file\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com/coredns/coredns/plugin/pkg/rcode\"\n\t\"github.com/coredns/coredns/request\"\n\n\t\"github.com/miekg/dns\"\n)\n\n\n\n\n\n\n\nfunc (z *Zone) Notify() {\n\tgo notify(z.origin, z.TransferTo)\n}\n\n\n\n\nfunc notify(zone string, to []string) error {\n\tm := new(dns.Msg)\n\tm.SetNotify(zone)\n\tc := new(dns.Client)\n\n\tfor _, t := range to {\n\t\tif t == \"*\" {\n\t\t\tcontinue\n\t\t}\n\t\tif err := notifyAddr(c, m, t); err != nil {\n\t\t\tlog.Error(err.Error())\n\t\t} else {\n\t\t\tlog.Infof(\"Sent notify for zone %q to %q\", zone, t)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc notifyAddr(c *dns.Client, m *dns.Msg, s string) error {\n\tvar err error\n\n\tcode := dns.RcodeServerFailure\n\tfor i := 0; i < 3; i++ {\n\t\tret, _, err := c.Exchange(m, s)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tcode = ret.Rcode\n\t\tif code == dns.RcodeSuccess {\n\t\t\treturn nil\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"notify for zone %q was not accepted by %q: %q\", m.Question[0].Name, s, err)\n\t}\n\treturn fmt.Errorf(\"notify for zone %q was not accepted by %q: rcode was %q\", m.Question[0].Name, s, rcode.ToString(code))\n}\n\nfunc (z *Zone) isNotify(state request.Request) bool ", "output": "{\n\tif state.Req.Opcode != dns.OpcodeNotify {\n\t\treturn false\n\t}\n\tif len(z.TransferFrom) == 0 {\n\t\treturn false\n\t}\n\tremote := state.IP()\n\tfor _, f := range z.TransferFrom {\n\t\tfrom, _, err := net.SplitHostPort(f)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif from == remote {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package fs\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\n\nfunc diskUsage(roots ...string) (Usage, error) ", "output": "{\n\tvar (\n\t\tsize int64\n\t)\n\n\n\tfor _, root := range roots {\n\t\tif err := filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tsize += fi.Size()\n\t\t\treturn nil\n\t\t}); err != nil {\n\t\t\treturn Usage{}, err\n\t\t}\n\t}\n\n\treturn Usage{\n\t\tSize: size,\n\t}, nil\n}"} {"input": "package deb\n\nimport (\n\t\"encoding/binary\"\n\t\"github.com/smira/aptly/aptly\"\n\t\"github.com/smira/aptly/utils\"\n\t\"hash/fnv\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n)\n\n\ntype PackageFile struct {\n\tFilename string\n\tChecksums utils.ChecksumInfo\n\tdownloadPath string\n}\n\n\nfunc (f *PackageFile) Verify(packagePool aptly.PackagePool) (bool, error) {\n\tpoolPath, err := packagePool.Path(f.Filename, f.Checksums.MD5)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tst, err := os.Stat(poolPath)\n\tif err != nil {\n\t\treturn false, nil\n\t}\n\n\treturn st.Size() == f.Checksums.Size, nil\n}\n\n\nfunc (f *PackageFile) DownloadURL() string {\n\treturn filepath.Join(f.downloadPath, f.Filename)\n}\n\n\ntype PackageFiles []PackageFile\n\n\nfunc (files PackageFiles) Hash() uint64 {\n\tsort.Sort(files)\n\n\th := fnv.New64a()\n\n\tfor _, f := range files {\n\t\th.Write([]byte(f.Filename))\n\t\tbinary.Write(h, binary.BigEndian, f.Checksums.Size)\n\t\th.Write([]byte(f.Checksums.MD5))\n\t\th.Write([]byte(f.Checksums.SHA1))\n\t\th.Write([]byte(f.Checksums.SHA256))\n\t}\n\n\treturn h.Sum64()\n}\n\n\nfunc (files PackageFiles) Len() int {\n\treturn len(files)\n}\n\n\n\n\n\nfunc (files PackageFiles) Less(i, j int) bool {\n\treturn files[i].Filename < files[j].Filename\n}\n\nfunc (files PackageFiles) Swap(i, j int) ", "output": "{\n\tfiles[i], files[j] = files[j], files[i]\n}"} {"input": "package net_sniff\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com/bettercap/bettercap/session\"\n\n\t\"github.com/evilsocket/islazy/tui\"\n\t\"github.com/google/gopacket/layers\"\n)\n\nfunc vIP(ip net.IP) string {\n\tif session.I.Interface.IP.Equal(ip) {\n\t\treturn tui.Dim(\"local\")\n\t} else if session.I.Gateway.IP.Equal(ip) {\n\t\treturn \"gateway\"\n\t}\n\n\taddress := ip.String()\n\thost := session.I.Lan.GetByIp(address)\n\tif host != nil {\n\t\tif host.Hostname != \"\" {\n\t\t\treturn host.Hostname\n\t\t}\n\t}\n\n\treturn address\n}\n\n\n\nvar maxUrlSize = 80\n\nfunc vURL(u string) string {\n\tul := len(u)\n\tif ul > maxUrlSize {\n\t\tu = fmt.Sprintf(\"%s...\", u[0:maxUrlSize-3])\n\t}\n\treturn u\n}\n\nfunc vPort(p interface{}) string ", "output": "{\n\tsp := fmt.Sprintf(\"%d\", p)\n\tif tcp, ok := p.(layers.TCPPort); ok {\n\t\tif name, found := layers.TCPPortNames[tcp]; found {\n\t\t\tsp = tui.Yellow(name)\n\t\t}\n\t} else if udp, ok := p.(layers.UDPPort); ok {\n\t\tif name, found := layers.UDPPortNames[udp]; found {\n\t\t\tsp = tui.Yellow(name)\n\t\t}\n\t}\n\n\treturn sp\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/spreadspace/telgo\"\n\t\"os\"\n)\n\n\n\nfunc setname(c *telgo.Client, args []string, hostname string) bool {\n\tif len(args) != 2 {\n\t\tc.Sayln(\"invalid number of arguments!\")\n\t\treturn false\n\t}\n\tc.UserData = args[1]\n\treturn false\n}\n\nfunc main() {\n\tglobalUserdata := \"test\"\n\n\tcmdlist := make(telgo.CmdList)\n\tcmdlist[\"whoami\"] = func(c *telgo.Client, args []string) bool { return whoami(c, args, globalUserdata) }\n\tcmdlist[\"setname\"] = func(c *telgo.Client, args []string) bool { return setname(c, args, globalUserdata) }\n\n\ts, err := telgo.NewServer(\":7023\", \"userdata> \", cmdlist, \"anonymous\")\n\tif err != nil {\n\t\tfmt.Println(\"failed to initialize telnet server:\", err)\n\t\tos.Exit(1)\n\t}\n\tif err = s.Run(); err != nil {\n\t\tfmt.Println(\"telnet server returned:\", err)\n\t}\n}\n\nfunc whoami(c *telgo.Client, args []string, hostname string) bool ", "output": "{\n\tc.Sayln(\"%s @ (%s)\", c.UserData.(string), hostname)\n\treturn false\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/ulricqin/beego-blog/g\"\n\t\"github.com/ulricqin/beego-blog/models/blog\"\n\t\"github.com/ulricqin/beego-blog/models/catalog\"\n)\n\ntype MainController struct {\n\tBaseController\n}\n\nfunc (this *MainController) Get() {\n\tthis.Data[\"Catalogs\"] = catalog.All()\n\tthis.Data[\"PageTitle\"] = \"首页\"\n\tthis.Layout = \"layout/default.html\"\n\tthis.TplName = \"index.html\"\n}\n\nfunc (this *MainController) Read() {\n\tident := this.GetString(\":ident\")\n\tb := blog.OneByIdent(ident)\n\tif b == nil {\n\t\tthis.Ctx.WriteString(\"no such article\")\n\t\treturn\n\t}\n\n\tb.Views = b.Views + 1\n\tblog.Update(b, \"\")\n\n\tthis.Data[\"Blog\"] = b\n\tthis.Data[\"Content\"] = g.RenderMarkdown(blog.ReadBlogContent(b).Content)\n\tthis.Data[\"PageTitle\"] = b.Title\n\tthis.Data[\"Catalog\"] = catalog.OneById(b.CatalogId)\n\tthis.Layout = \"layout/default.html\"\n\tthis.TplName = \"article/read.html\"\n}\n\n\n\nfunc (this *MainController) ListByCatalog() ", "output": "{\n\tcata := this.Ctx.Input.Param(\":ident\")\n\tif cata == \"\" {\n\t\tthis.Ctx.WriteString(\"catalog ident is blank\")\n\t\treturn\n\t}\n\n\tlimit := this.GetIntWithDefault(\"limit\", 10)\n\n\tc := catalog.OneByIdent(cata)\n\tif c == nil {\n\t\tthis.Ctx.WriteString(\"catalog:\" + cata + \" not found\")\n\t\treturn\n\t}\n\n\tids := blog.Ids(c.Id)\n\tpager := this.SetPaginator(limit, int64(len(ids)))\n\tblogs := blog.ByCatalog(c.Id, pager.Offset(), limit)\n\n\tthis.Data[\"Catalog\"] = c\n\tthis.Data[\"Blogs\"] = blogs\n\tthis.Data[\"PageTitle\"] = c.Name\n\n\tthis.Layout = \"layout/default.html\"\n\tthis.TplName = \"article/by_catalog.html\"\n}"} {"input": "package starbound\n\nimport (\n\t\"io\"\n)\n\n\n\n\n\ntype logger interface {\n\tFatalf(format string, args ...interface{})\n}\n\n\ntype readerAtReader struct {\n\tr io.ReaderAt\n\toff int64\n}\n\nfunc (r *readerAtReader) Read(p []byte) (n int, err error) {\n\tn, err = r.r.ReadAt(p, r.off)\n\tr.off += int64(n)\n\treturn\n}\n\nfunc getInt(data []byte, n int) int ", "output": "{\n\treturn int(data[n])<<24 | int(data[n+1])<<16 | int(data[n+2])<<8 | int(data[n+3])\n}"} {"input": "package main\n\n\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"cloud.google.com/go/bigquery\"\n\t\"google.golang.org/api/iterator\"\n)\n\n\n\nfunc main() {\n\tprojectID := os.Getenv(\"GOOGLE_CLOUD_PROJECT\")\n\tif projectID == \"\" {\n\t\tfmt.Println(\"GOOGLE_CLOUD_PROJECT environment variable must be set.\")\n\t\tos.Exit(1)\n\t}\n\n\tctx := context.Background()\n\n\tclient, err := bigquery.NewClient(ctx, projectID)\n\tif err != nil {\n\t\tlog.Fatalf(\"bigquery.NewClient: %v\", err)\n\t}\n\tdefer client.Close()\n\n\trows, err := query(ctx, client)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := printResults(os.Stdout, rows); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\nfunc query(ctx context.Context, client *bigquery.Client) (*bigquery.RowIterator, error) {\n\n\tquery := client.Query(\n\t\t`SELECT\n\t\t\tCONCAT(\n\t\t\t\t'https:stackoverflow.com/questions/',\n\t\t\t\tCAST(id as STRING)) as url,\n\t\t\tview_count\n\t\tFROM ` + \"`bigquery-public-data.stackoverflow.posts_questions`\" + `\n\t\tWHERE tags like '%google-bigquery%'\n\t\tORDER BY view_count DESC\n\t\tLIMIT 10;`)\n\treturn query.Read(ctx)\n}\n\n\ntype StackOverflowRow struct {\n\tURL string `bigquery:\"url\"`\n\tViewCount int64 `bigquery:\"view_count\"`\n}\n\n\n\n\nfunc printResults(w io.Writer, iter *bigquery.RowIterator) error ", "output": "{\n\tfor {\n\t\tvar row StackOverflowRow\n\t\terr := iter.Next(&row)\n\t\tif err == iterator.Done {\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error iterating through results: %v\", err)\n\t\t}\n\n\t\tfmt.Fprintf(w, \"url: %s views: %d\\n\", row.URL, row.ViewCount)\n\t}\n}"} {"input": "package layer\n\nimport \"io\"\n\ntype mountedLayer struct {\n\tname string\n\tmountID string\n\tinitID string\n\tparent *roLayer\n\tpath string\n\tlayerStore *layerStore\n\tactivityCount int\n}\n\nfunc (ml *mountedLayer) cacheParent() string {\n\tif ml.initID != \"\" {\n\t\treturn ml.initID\n\t}\n\tif ml.parent != nil {\n\t\treturn ml.parent.cacheID\n\t}\n\treturn \"\"\n}\n\nfunc (ml *mountedLayer) TarStream() (io.ReadCloser, error) {\n\tarchiver, err := ml.layerStore.driver.Diff(ml.mountID, ml.cacheParent())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn archiver, nil\n}\n\n\n\nfunc (ml *mountedLayer) Parent() Layer {\n\tif ml.parent != nil {\n\t\treturn ml.parent\n\t}\n\n\treturn nil\n}\n\nfunc (ml *mountedLayer) Size() (int64, error) {\n\treturn ml.layerStore.driver.DiffSize(ml.mountID, ml.cacheParent())\n}\n\nfunc (ml *mountedLayer) Path() (string, error) ", "output": "{\n\tif ml.path == \"\" {\n\t\treturn \"\", ErrNotMounted\n\t}\n\treturn ml.path, nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/idahobean/npm-resource/check\"\n\t\"github.com/idahobean/npm-resource/npm\"\n)\n\nfunc main() {\n\n\tNPM := npm.NewNPM()\n\tcommand := check.NewCommand(NPM)\n\n\tvar request check.Request\n\tif err := json.NewDecoder(os.Stdin).Decode(&request); err != nil {\n\t\tfatal(\"reading request from stdin\", err)\n\t}\n\n\tvar err error\n\tif request.Source.PackageName == \"\" {\n\t\terr = errors.New(\"package_name\")\n\t}\n\tif err != nil {\n\t\tfatal(\"parameter required\", err)\n\t}\n\n\tresponse, err := command.Run(request)\n\tif err != nil {\n\t\tfatal(\"running command\", err)\n\t}\n\n\tif err := json.NewEncoder(os.Stdout).Encode(response); err != nil {\n\t\tfatal(\"writing response to stdout\", err)\n\t}\n}\n\n\n\nfunc fatal(message string, err error) ", "output": "{\n\tfmt.Fprintf(os.Stderr, \"error %s: %s\\n\", message, err)\n\tos.Exit(1)\n}"} {"input": "package iconv\n\n\nfunc Convert(input []byte, output []byte, fromEncoding string, toEncoding string) (bytesRead int, bytesWritten int, err error) {\n\tconverter, err := NewConverter(fromEncoding, toEncoding)\n\n\tif err == nil {\n\t\tbytesRead, bytesWritten, err = converter.Convert(input, output)\n\n\t\tif err == nil {\n\t\t\tvar shiftBytesWritten int\n\n\t\t\t_, shiftBytesWritten, err = converter.Convert(nil, output[bytesWritten:])\n\n\t\t\tbytesWritten += shiftBytesWritten\n\t\t}\n\n\t\tconverter.Close()\n\t}\n\n\treturn\n}\n\n\n\n\nfunc ConvertString(input string, fromEncoding string, toEncoding string) (output string, err error) ", "output": "{\n\tconverter, err := NewConverter(fromEncoding, toEncoding)\n\n\tif err == nil {\n\t\toutput, err = converter.ConvertString(input)\n\n\t\tconverter.Close()\n\t}\n\n\treturn\n}"} {"input": "package insulin\n\nimport (\n\t\"math\"\n\n\t\"github.com/tidepool-org/platform/data\"\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tConcentrationUnitsUnitsPerML = \"Units/mL\"\n\tConcentrationValueUnitsPerMLMaximum = 10000.0\n\tConcentrationValueUnitsPerMLMinimum = 0.0\n)\n\nfunc ConcentrationUnits() []string {\n\treturn []string{\n\t\tConcentrationUnitsUnitsPerML,\n\t}\n}\n\ntype Concentration struct {\n\tUnits *string `json:\"units,omitempty\" bson:\"units,omitempty\"`\n\tValue *float64 `json:\"value,omitempty\" bson:\"value,omitempty\"`\n}\n\nfunc ParseConcentration(parser structure.ObjectParser) *Concentration {\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewConcentration()\n\tparser.Parse(datum)\n\treturn datum\n}\n\nfunc NewConcentration() *Concentration {\n\treturn &Concentration{}\n}\n\nfunc (c *Concentration) Parse(parser structure.ObjectParser) {\n\tc.Units = parser.String(\"units\")\n\tc.Value = parser.Float64(\"value\")\n}\n\nfunc (c *Concentration) Validate(validator structure.Validator) {\n\tvalidator.String(\"units\", c.Units).Exists().OneOf(ConcentrationUnits()...)\n\tvalidator.Float64(\"value\", c.Value).Exists().InRange(ConcentrationValueRangeForUnits(c.Units))\n}\n\nfunc (c *Concentration) Normalize(normalizer data.Normalizer) {}\n\n\n\nfunc ConcentrationValueRangeForUnits(units *string) (float64, float64) ", "output": "{\n\tif units != nil {\n\t\tswitch *units {\n\t\tcase ConcentrationUnitsUnitsPerML:\n\t\t\treturn ConcentrationValueUnitsPerMLMinimum, ConcentrationValueUnitsPerMLMaximum\n\t\t}\n\t}\n\treturn -math.MaxFloat64, math.MaxFloat64\n}"} {"input": "package redis_test\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/go-redis/redis\"\n\tredistrace \"gopkg.in/DataDog/dd-trace-go.v1/contrib/go-redis/redis\"\n\t\"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext\"\n\t\"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer\"\n)\n\n\n\n\n\n\n\nfunc Example_pipeliner() {\n\topts := &redis.Options{Addr: \"127.0.0.1\", Password: \"\", DB: 0}\n\tc := redistrace.NewClient(opts, redistrace.WithServiceName(\"my-redis-service\"))\n\n\tpipe := c.Pipeline()\n\n\tpipe.Incr(\"pipeline_counter\")\n\tpipe.Expire(\"pipeline_counter\", time.Hour)\n\n\tpipe.Exec()\n}\n\nfunc Example() ", "output": "{\n\topts := &redis.Options{Addr: \"127.0.0.1\", Password: \"\", DB: 0}\n\tc := redistrace.NewClient(opts)\n\n\tc.Set(\"test_key\", \"test_value\", 0)\n\n\troot, ctx := tracer.StartSpanFromContext(context.Background(), \"parent.request\",\n\t\ttracer.SpanType(ext.SpanTypeRedis),\n\t\ttracer.ServiceName(\"web\"),\n\t\ttracer.ResourceName(\"/home\"),\n\t)\n\n\tc = c.WithContext(ctx)\n\n\tc.Set(\"food\", \"cheese\", 0)\n\troot.Finish()\n}"} {"input": "package hpdf\n\n\nimport \"C\"\n\ntype TransMatrix struct {\n\tA float32\n\tB float32\n\tC float32\n\tD float32\n\tX float32\n\tY float32\n}\n\n\n\nfunc transMatrixFromHPDFTransMatrix(transMatrix C.HPDF_TransMatrix) *TransMatrix ", "output": "{\n\treturn &TransMatrix{\n\t\tfloat32(transMatrix.a),\n\t\tfloat32(transMatrix.b),\n\t\tfloat32(transMatrix.c),\n\t\tfloat32(transMatrix.d),\n\t\tfloat32(transMatrix.x),\n\t\tfloat32(transMatrix.y),\n\t}\n}"} {"input": "package gospec\n\nimport (\n\t\"fmt\"\n\tfilepath \"path\"\n\t\"runtime\"\n)\n\ntype Location struct {\n\tname string\n\tfile string\n\tline int\n}\n\nfunc currentLocation() *Location {\n\treturn newLocation(1)\n}\n\nfunc callerLocation() *Location {\n\treturn newLocation(2)\n}\n\nfunc newLocation(n int) *Location {\n\tif pc, _, _, ok := runtime.Caller(n + 1); ok {\n\t\treturn locationForPC(pc)\n\t}\n\treturn nil\n}\n\n\n\n\n\n\n\n\n\n\nfunc pcOfWhereCallWasMade(pcOfWhereCallReturnsTo uintptr) uintptr {\n\treturn pcOfWhereCallReturnsTo - 1\n}\n\nfunc (this *Location) Name() string { return this.name }\nfunc (this *Location) File() string { return this.file }\nfunc (this *Location) FileName() string { return filename(this.file) }\nfunc (this *Location) Line() int { return this.line }\n\nfunc filename(path string) string {\n\t_, file := filepath.Split(path)\n\treturn file\n}\n\nfunc (this *Location) equals(that *Location) bool {\n\treturn this.name == that.name &&\n\t\tthis.file == that.file &&\n\t\tthis.line == that.line\n}\n\nfunc (this *Location) String() string {\n\treturn fmt.Sprintf(\"%v:%v\", this.FileName(), this.Line())\n}\n\nfunc locationForPC(pc uintptr) *Location ", "output": "{\n\tpc = pcOfWhereCallWasMade(pc)\n\tf := runtime.FuncForPC(pc)\n\tname := f.Name()\n\tfile, line := f.FileLine(pc)\n\treturn &Location{name, file, line}\n}"} {"input": "package models\n\ntype Document struct {\n\tID string `json:\"_id,omitempty\"`\n\tRev string `json:\"_rev,omitempty\"`\n\tKey string `json:\"_key,omitempty\"`\n}\n\nfunc NewDocument(id, rev, key string) Document {\n\treturn Document{\n\t\tID: id,\n\t\tRev: rev,\n\t\tKey: key,\n\t}\n}\n\ntype Edge struct {\n\tDocument\n\tFrom string `json:\"_from,omitempty\"`\n\tTo string `json:\"_to,omitempty\"`\n}\n\n\n\nfunc NewEdge(id, rev, key, from, to string) Edge ", "output": "{\n\treturn Edge{\n\t\tDocument: NewDocument(id, rev, key),\n\t\tFrom: from,\n\t\tTo: to,\n\t}\n}"} {"input": "package models\n\nimport (\n\t\"OttBot2/settings\"\n\t\"database/sql\"\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"time\"\n)\n\nvar db *sql.DB\n\n\n\nfunc MakeDB(dbConnectString string) ", "output": "{\n\tnewDb, err := sql.Open(\"mysql\", dbConnectString)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdb = newDb\n\ttimeout, err := time.ParseDuration(settings.GetDatabaseTimeout())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdb.SetConnMaxLifetime(timeout)\n}"} {"input": "package version\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/coreos/go-semver/semver\"\n)\n\nvar (\n\tMinClusterVersion = \"3.0.0\"\n\tVersion = \"3.1.0-rc.0+git\"\n\tAPIVersion = \"unknown\"\n\n\tGitSHA = \"Not provided (use ./build instead of go build)\"\n)\n\n\n\ntype Versions struct {\n\tServer string `json:\"etcdserver\"`\n\tCluster string `json:\"etcdcluster\"`\n}\n\n\nfunc Cluster(v string) string {\n\tvs := strings.Split(v, \".\")\n\tif len(vs) <= 2 {\n\t\treturn v\n\t}\n\treturn fmt.Sprintf(\"%s.%s\", vs[0], vs[1])\n}\n\nfunc init() ", "output": "{\n\tver, err := semver.NewVersion(Version)\n\tif err == nil {\n\t\tAPIVersion = fmt.Sprintf(\"%d.%d\", ver.Major, ver.Minor)\n\t}\n}"} {"input": "package directory\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"syscall\"\n)\n\n\n\n\nfunc Size(dir string) (size int64, err error) ", "output": "{\n\tdata := make(map[uint64]struct{})\n\terr = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error {\n\t\tif fileInfo == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\ts := fileInfo.Size()\n\t\tif fileInfo.IsDir() || s == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\tinode := fileInfo.Sys().(*syscall.Stat_t).Ino\n\t\tif _, exists := data[uint64(inode)]; exists {\n\t\t\treturn nil\n\t\t}\n\t\tdata[uint64(inode)] = struct{}{}\n\n\t\tsize += s\n\n\t\treturn nil\n\t})\n\treturn\n}"} {"input": "package nobody\n\nimport (\n\t\"context\"\n\n\tvoucher \"github.com/grafeas/voucher/v2\"\n\t\"github.com/grafeas/voucher/v2/docker\"\n)\n\n\n\ntype check struct {\n\tauth voucher.Auth\n}\n\n\n\nfunc (n *check) SetAuth(auth voucher.Auth) {\n\tn.auth = auth\n}\n\n\n\n\n\nfunc init() {\n\tvoucher.RegisterCheckFactory(\"nobody\", func() voucher.Check {\n\t\treturn new(check)\n\t})\n}\n\nfunc (n *check) Check(ctx context.Context, i voucher.ImageData) (bool, error) ", "output": "{\n\tif nil == n.auth {\n\t\treturn false, voucher.ErrNoAuth\n\t}\n\n\tclient, err := n.auth.ToClient(ctx, i)\n\tif nil != err {\n\t\treturn false, err\n\t}\n\n\timageConfig, err := docker.RequestImageConfig(client, i)\n\n\tif nil != err {\n\t\treturn false, err\n\t}\n\n\treturn !imageConfig.RunsAsRoot(), nil\n}"} {"input": "package project\n\nimport (\n\t\"testing\"\n)\n\nfunc TestTrimSpaceAndNonPrintable_unicode(t *testing.T) {\n\tt.Parallel()\n\n\textraChars := \"state\\uFEFF\"\n\twant := \"state\"\n\tgot := TrimSpaceAndNonPrintable(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}\n\nfunc TestTrimSpaceAndNonPrintable_space(t *testing.T) {\n\tt.Parallel()\n\n\textraChars := \" state \\r\\t\"\n\twant := \"state\"\n\tgot := TrimSpaceAndNonPrintable(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}\n\nfunc TestTrimSpace_unicode(t *testing.T) {\n\tt.Parallel()\n\n\textraChars := \"state\\uFEFF\"\n\twant := \"state\"\n\tgot := TrimSpace(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}\n\n\n\nfunc TestTrimSpace_space(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\textraChars := \" state \\r\\t\"\n\twant := \"state\"\n\tgot := TrimSpace(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}"} {"input": "package rafttransport\n\nimport \"github.com/juju/worker/v2\"\n\n\n\n\n\nfunc NewWorkerShim(config Config) (worker.Worker, error) ", "output": "{\n\treturn NewWorker(config)\n}"} {"input": "package airplane_mode\n\nfunc getRadioModule(key RadioType) BaseRadioModule {\n\tvar module BaseRadioModule\n\tswitch key {\n\tcase BluetoothRadioType:\n\t\tmodule = &BluetoothRadio{GeneralRadioModule{typ: BluetoothRadioType, name: \"bluetooth\"}}\n\tcase WlanRadioType:\n\t\tmodule = &WlanRadio{GeneralRadioModule{typ: WlanRadioType, name: \"wlan\"}}\n\tcase AllRadioType:\n\t\tmodule = &AllRadio{GeneralRadioModule{typ: AllRadioType, name: \"all\"}}\n\tdefault:\n\t\tpanic(\"radio type not exist\")\n\t}\n\treturn module\n}\n\ntype GeneralRadioModule struct {\n\ttyp RadioType\n\tname string\n}\n\n\n\nfunc (Op *GeneralRadioModule) Module() string {\n\treturn Op.name\n}\n\nfunc (Op *GeneralRadioModule) Len() int {\n\tstate, err := rfkillState(Op.typ)\n\tif err != nil {\n\t\tlogger.Warningf(\"check rfkill blocked state failed, err: %v\", err)\n\t\tstate.count = 0\n\t}\n\treturn state.count\n}\n\nfunc (Op *GeneralRadioModule) Block() error {\n\treturn rfkillAction(Op.typ, BlockRadioAction)\n}\n\nfunc (Op *GeneralRadioModule) Unblock() error {\n\treturn rfkillAction(Op.typ, UnblockRadioAction)\n}\n\nfunc (Op *GeneralRadioModule) IsBlocked() bool {\n\tstate, err := rfkillState(Op.typ)\n\tif err != nil {\n\t\tlogger.Warningf(\"check rfkill blocked state failed, err: %v\", err)\n\t\tstate.blocked = false\n\t}\n\treturn state.blocked\n}\n\n\ntype BluetoothRadio struct {\n\tGeneralRadioModule\n}\n\n\ntype WlanRadio struct {\n\tGeneralRadioModule\n}\n\n\ntype AllRadio struct {\n\tGeneralRadioModule\n}\n\nfunc (Op *GeneralRadioModule) Type() RadioType ", "output": "{\n\treturn Op.typ\n}"} {"input": "package main\n\nimport \"fmt\"\nimport \"time\"\n\nfunc goFunc1(f func()) {\n\tgo f()\n}\n\nfunc goFunc2(f func(interface{}), i interface{}) {\n\tgo f(i)\n}\n\nfunc goFunc(f interface{}, args ...interface{}) {\n\tif len(args) > 1 {\n\t\tgo f.(func(...interface{}))(args)\n\t} else if len(args) == 1 {\n\t\tgo f.(func(interface{}))(args[0])\n\t} else {\n\t\tgo f.(func())()\n\t}\n}\n\nfunc f1() {\n\tfmt.Println(\"f1 done\")\n}\n\nfunc f2(i interface{}) {\n\tfmt.Println(\"f2 done\", i)\n}\n\n\n\nfunc main() {\n\tgoFunc1(f1)\n\tgoFunc2(f2, 100)\n\n\tgoFunc(f1)\n\tgoFunc(f2, \"xxxx\")\n\tgoFunc(f3, \"hello\", \"world\", 1, 3.14)\n\ttime.Sleep(5 * time.Second)\n}\n\nfunc f3(args ...interface{}) ", "output": "{\n\tfmt.Println(\"f3 done\", args)\n}"} {"input": "package treemap\n\nimport (\n\t\"github.com/emirpasic/gods/containers\"\n\trbt \"github.com/emirpasic/gods/trees/redblacktree\"\n)\n\nfunc assertIteratorImplementation() {\n\tvar _ containers.ReverseIteratorWithKey = (*Iterator)(nil)\n}\n\n\ntype Iterator struct {\n\titerator rbt.Iterator\n}\n\n\nfunc (m *Map) Iterator() Iterator {\n\treturn Iterator{iterator: m.tree.Iterator()}\n}\n\n\n\n\n\nfunc (iterator *Iterator) Next() bool {\n\treturn iterator.iterator.Next()\n}\n\n\n\n\n\n\n\n\nfunc (iterator *Iterator) Value() interface{} {\n\treturn iterator.iterator.Value()\n}\n\n\n\nfunc (iterator *Iterator) Key() interface{} {\n\treturn iterator.iterator.Key()\n}\n\n\n\nfunc (iterator *Iterator) Begin() {\n\titerator.iterator.Begin()\n}\n\n\n\nfunc (iterator *Iterator) End() {\n\titerator.iterator.End()\n}\n\n\n\n\nfunc (iterator *Iterator) First() bool {\n\treturn iterator.iterator.First()\n}\n\n\n\n\nfunc (iterator *Iterator) Last() bool {\n\treturn iterator.iterator.Last()\n}\n\nfunc (iterator *Iterator) Prev() bool ", "output": "{\n\treturn iterator.iterator.Prev()\n}"} {"input": "package middleware\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n)\n\n\n\n\n\nfunc PageRoute(path string, handler http.Handler) func(http.Handler) http.Handler ", "output": "{\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tif r.Method == \"GET\" && strings.EqualFold(r.URL.Path, path) {\n\t\t\t\thandler.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}"} {"input": "package transactions\n\nimport \"github.com/joshheinrichs/httperr\"\n\nfunc AddAdmin(requesterID, userID string) httperr.Error {\n\treturn ErrNotImplemented\n}\n\nfunc IsAdmin(userID string) (bool, httperr.Error) {\n\treturn false, ErrNotImplemented\n}\n\n\n\nfunc RemoveAdmin(requesterID, userID string) httperr.Error ", "output": "{\n\treturn ErrNotImplemented\n}"} {"input": "package main\n\nimport \"errors\"\nimport \"fmt\"\n\n\n\nfunc f1(arg int) (int, error) {\n\tif arg == 42 {\n\n\t\treturn -1, errors.New(\"can't work with 42\")\n\n\t}\n\n\treturn arg + 3, nil\n}\n\n\n\n\n\ntype argError struct {\n\targ int\n\tprob string\n}\n\n\n\nfunc f2(arg int) (int, error) {\n\tif arg == 42 {\n\n\t\treturn -1, &argError{arg, \"can't work with it\"}\n\t}\n\treturn arg + 3, nil\n}\n\nfunc main() {\n\n\tfor _, i := range []int{7, 42} {\n\t\tif r, e := f1(i); e != nil {\n\t\t\tfmt.Println(\"f1 failed:\", e)\n\t\t} else {\n\t\t\tfmt.Println(\"f1 worked:\", r)\n\t\t}\n\t}\n\n\tfor _, i := range []int{7, 42} {\n\t\tif r, e := f2(i); e != nil {\n\t\t\tfmt.Println(\"f2 failed:\", e)\n\t\t} else {\n\t\t\tfmt.Println(\"f2 worked:\", r)\n\t\t}\n\t}\n\n\t_, e := f2(42)\n\tif ae, ok := e.(*argError); ok {\n\t\tfmt.Println(ae.arg)\n\t\tfmt.Println(ae.prob)\n\t}\n}\n\nfunc (e *argError) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"%d - %s\", e.arg, e.prob)\n}"} {"input": "package main\n\nimport \"strings\"\n\nvar x = make([]byte, 10)\n\nfunc main() {\n\ttest1()\n\ttest2()\n\ttest3()\n\ttest4()\n\ttest5()\n\ttest6()\n\ttest7()\n}\n\nfunc mustRecover(s string) {\n\tv := recover()\n\tif v == nil {\n\t\tpanic(\"expected panic\")\n\t}\n\tif e := v.(error).Error(); strings.Index(e, s) < 0 {\n\t\tpanic(\"want: \" + s + \"; have: \" + e)\n\t}\n}\n\nfunc test1() {\n\tdefer mustRecover(\"index\")\n\tprintln(x[123])\n}\n\nfunc test2() {\n\tdefer mustRecover(\"slice\")\n\tprintln(x[5:15])\n}\n\nfunc test3() {\n\tdefer mustRecover(\"slice\")\n\tvar lo = 11\n\tvar hi = 9\n\tprintln(x[lo:hi])\n}\n\nfunc test4() {\n\tdefer mustRecover(\"interface\")\n\tvar x interface{} = 1\n\tprintln(x.(float32))\n}\n\ntype T struct {\n\ta, b int\n\tc []int\n}\n\nfunc test5() {\n\tdefer mustRecover(\"uncomparable\")\n\tvar x T\n\tvar z interface{} = x\n\tprintln(z != z)\n}\n\n\n\nfunc test7() {\n\tdefer mustRecover(\"divide by zero\")\n\tvar x, y int\n\tprintln(x / y)\n}\n\nfunc test6() ", "output": "{\n\tdefer mustRecover(\"unhashable\")\n\tvar x T\n\tvar z interface{} = x\n\tm := make(map[interface{}]int)\n\tm[z] = 1\n}"} {"input": "package rpc\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\n\t\"github.com/ugorji/go/codec\"\n)\n\ntype packetizer interface {\n\tNextFrame() (rpcMessage, error)\n}\n\ntype packetHandler struct {\n\tdec decoder\n\treader io.Reader\n\tframeDecoder *decoderWrapper\n\tprotocols *protocolHandler\n\tcalls *callContainer\n}\n\nfunc newPacketHandler(reader io.Reader, protocols *protocolHandler, calls *callContainer) *packetHandler {\n\treturn &packetHandler{\n\t\treader: reader,\n\t\tdec: codec.NewDecoder(reader, newCodecMsgpackHandle()),\n\t\tframeDecoder: newDecoderWrapper(),\n\t\tprotocols: protocols,\n\t\tcalls: calls,\n\t}\n}\n\nfunc (p *packetHandler) NextFrame() (rpcMessage, error) {\n\tbytes, err := p.loadNextFrame()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(bytes) < 1 {\n\t\treturn nil, NewPacketizerError(\"invalid frame size: %d\", len(bytes))\n\t}\n\n\tnb := int(bytes[0])\n\n\tif nb < 0x91 || nb > 0x9f {\n\t\treturn nil, NewPacketizerError(\"wrong message structure prefix (%d)\", nb)\n\t}\n\tp.frameDecoder.ResetBytes(bytes[1:])\n\n\treturn decodeRPC(nb-0x90, p.frameDecoder, p.protocols, p.calls)\n}\n\n\n\nfunc (p *packetHandler) loadNextFrame() ([]byte, error) ", "output": "{\n\tvar l int\n\tif err := p.dec.Decode(&l); err != nil {\n\t\tif _, ok := err.(*net.OpError); ok {\n\t\t\treturn nil, io.EOF\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tbytes := make([]byte, l)\n\tlenRead, err := io.ReadFull(p.reader, bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif lenRead != l {\n\t\treturn nil, fmt.Errorf(\"Unable to read desired length. Desired: %d, actual: %d\", l, lenRead)\n\t}\n\treturn bytes, nil\n}"} {"input": "package align\n\nimport (\n\t\"github.com/biogo/biogo/alphabet\"\n\t\"github.com/biogo/biogo/feat\"\n)\n\n\nconst debugNeedle = false\n\n\ntype NW Linear\n\n\n\n\n\nfunc (a NW) Align(reference, query AlphabetSlicer) ([]feat.Pair, error) ", "output": "{\n\talpha := reference.Alphabet()\n\tif alpha == nil {\n\t\treturn nil, ErrNoAlphabet\n\t}\n\tif alpha != query.Alphabet() {\n\t\treturn nil, ErrMismatchedAlphabets\n\t}\n\tif alpha.IndexOf(alpha.Gap()) != 0 {\n\t\treturn nil, ErrNotGappedAlphabet\n\t}\n\tswitch rSeq := reference.Slice().(type) {\n\tcase alphabet.Letters:\n\t\tqSeq, ok := query.Slice().(alphabet.Letters)\n\t\tif !ok {\n\t\t\treturn nil, ErrMismatchedTypes\n\t\t}\n\t\treturn a.alignLetters(rSeq, qSeq, alpha)\n\tcase alphabet.QLetters:\n\t\tqSeq, ok := query.Slice().(alphabet.QLetters)\n\t\tif !ok {\n\t\t\treturn nil, ErrMismatchedTypes\n\t\t}\n\t\treturn a.alignQLetters(rSeq, qSeq, alpha)\n\tdefault:\n\t\treturn nil, ErrTypeNotHandled\n\t}\n}"} {"input": "package grok\n\ntype nestingStack struct {\n\ttop *nestingElement\n\tsize int\n}\n\ntype nestingElement struct {\n\topenRune rune\n\tstartIndex int\n\tcommaCounter int\n\tlastSeparatorIndex int\n\tnext *nestingElement\n}\n\n\n\nfunc (ne *nestingElement) expressionStartIndex() int {\n\tstartIndex := ne.startIndex + 1\n\tif ne.lastSeparatorIndex+1 > startIndex {\n\t\treturn ne.lastSeparatorIndex + 1\n\t}\n\treturn startIndex\n}\n\nfunc (s *nestingStack) topValue() (rune, int, bool) {\n\tif s.size == 0 {\n\t\treturn ' ', -1, false\n\t}\n\n\treturn s.top.openRune, s.top.startIndex, true\n}\n\n\n\n\n\nfunc (s *nestingStack) pop() (openRune rune, startIndex int) {\n\tif s.size > 0 {\n\t\topenRune, startIndex, s.top = s.top.openRune, s.top.startIndex, s.top.next\n\t\ts.size--\n\t\treturn\n\t}\n\treturn ' ', -1\n}\n\nfunc (s *nestingStack) push(openRune rune, startIndex int) ", "output": "{\n\ts.top = &nestingElement{openRune, startIndex, 0, -1, s.top}\n\ts.size++\n}"} {"input": "package sync \n\nimport (\n\t\"github.com/cenkalti/backoff\"\n\t\"github.com/sirupsen/logrus\"\n)\n\ntype deferredChange struct {\n\tmarshaledChange *[]byte\n\tpeerPublicKey [32]byte\n\tlastAttempted uint64\n\tdone bool\n}\n\n\n\nfunc (s *Sync) findPeerFromKey(key [32]byte) *Peer {\n\tfor _, p := range *s.Peers {\n\t\tif *p.publicKey == key {\n\t\t\treturn &p\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *Sync) handleDeferredChanges() ", "output": "{\n\tfor {\n\t\tc := <-*s.deferredChangeChan\n\t\tif !c.done {\n\t\t\top := func() error {\n\t\t\t\ts.Logger.WithFields(logrus.Fields{\"package\": \"sync\"}).Debug(\"Retrying change propogation\")\n\t\t\t\te := s.notifyPeer(*s.findPeerFromKey(c.peerPublicKey), c.marshaledChange, true)\n\t\t\t\treturn e\n\t\t\t}\n\t\t\tgo backoff.Retry(op, backoff.NewExponentialBackOff())\n\t\t\tc.done = true\n\t\t}\n\t}\n}"} {"input": "package main\nimport (\n\"time\"\n\"fmt\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar deposits = make (chan int)\nvar balances = make (chan int)\nfunc Deposit(amount int){\n\tdeposits<-amount\n}\nfunc Balance() int{\n\treturn <-balances\n}\nfunc teller(){\n\tvar balance int\n\tfor{\n\t\tselect{\n\t\t\tcase amount:=<-deposits:\n\t\t\t\tbalance+=amount\n\t\t\tcase balances<-balance:\n\t\t}\n\t}\n}\n\n\nfunc main() {\n\tgo func(){\n\t\tDeposit(200)\n\t\tfmt.Println(\"=\",Balance()) \n\t}()\n\n\tgo func(){\n\t\tDeposit(100)\n\t}()\n\ttime.Sleep(time.Second*1)\n}\n\nfunc init()", "output": "{\n\tgo teller()\n}"} {"input": "package utils\n\nimport \"fmt\"\n\n\n\nfunc ExampleNewStringSet() {\n\ta := NewStringSet()\n\ta.Add(\"a\")\n\ta.Add(\"b\")\n\n\tb := NewStringSet(\"b\", \"a\")\n\n\tfmt.Println(a.Equals(b))\n\n}\n\nfunc ExampleNewStringSetFromStringMapKeys() {\n\tm := map[string]string{\n\t\t\"a\": \"some a value\",\n\t\t\"b\": \"some b value\",\n\t}\n\n\tset := NewStringSetFromStringMapKeys(m)\n\tfmt.Println(set)\n\n}\n\nfunc ExampleStringSet_ToSlice() {\n\ta := NewStringSet()\n\ta.Add(\"z\")\n\ta.Add(\"b\")\n\n\tfmt.Println(a.ToSlice())\n\n}\n\nfunc ExampleStringSet_IsEmpty() {\n\ta := NewStringSet()\n\n\tfmt.Println(a.IsEmpty())\n\ta.Add(\"a\")\n\tfmt.Println(a.IsEmpty())\n\n}\n\nfunc ExampleStringSet_Equals() {\n\ta := NewStringSet(\"a\", \"b\")\n\tb := NewStringSet(\"a\", \"b\", \"c\")\n\tfmt.Println(a.Equals(b))\n\n\ta.Add(\"c\")\n\tfmt.Println(a.Equals(b))\n\n}\n\nfunc ExampleStringSet_Contains() {\n\ta := NewStringSet(\"a\", \"b\")\n\tfmt.Println(a.Contains(\"z\"))\n\tfmt.Println(a.Contains(\"a\"))\n\n}\n\nfunc ExampleStringSet_Minus() {\n\ta := NewStringSet(\"a\", \"b\")\n\tb := NewStringSet(\"b\", \"c\")\n\tdelta := a.Minus(b)\n\n\tfmt.Println(delta)\n}\n\nfunc ExampleStringSet_Add() ", "output": "{\n\tset := NewStringSet()\n\tset.Add(\"a\")\n\tset.Add(\"b\")\n\n\tfmt.Println(set)\n\tset.Add(\"a\")\n\tfmt.Println(set)\n\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\ntype FileExistenceTestv1 struct {\n\tName string \n\tPath string \n\tIsDirectory bool \n\tShouldExist bool \n\tPermissions string \n}\n\n\n\nfunc (ft FileExistenceTestv1) LogName() string {\n\treturn fmt.Sprintf(\"File Existence Test: %s\", ft.Name)\n}\n\nfunc validateFileExistenceTestV1(t *testing.T, tt FileExistenceTestv1) ", "output": "{\n\tif tt.Name == \"\" {\n\t\tt.Fatalf(\"Please provide a valid name for every test!\")\n\t}\n\tif tt.Path == \"\" {\n\t\tt.Fatalf(\"Please provide a valid file path for test %s\", tt.Name)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"helm.sh/helm/v3/pkg/release\"\n)\n\nfunc TestGetCmd(t *testing.T) {\n\ttests := []cmdTestCase{{\n\t\tname: \"get all with a release\",\n\t\tcmd: \"get all thomas-guide\",\n\t\tgolden: \"output/get-release.txt\",\n\t\trels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: \"thomas-guide\"})},\n\t}, {\n\t\tname: \"get all with a formatted release\",\n\t\tcmd: \"get all elevated-turkey --template {{.Release.Chart.Metadata.Version}}\",\n\t\tgolden: \"output/get-release-template.txt\",\n\t\trels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: \"elevated-turkey\"})},\n\t}, {\n\t\tname: \"get all requires release name arg\",\n\t\tcmd: \"get all\",\n\t\tgolden: \"output/get-all-no-args.txt\",\n\t\twantError: true,\n\t}}\n\trunTestCmd(t, tests)\n}\n\n\n\nfunc TestGetAllFileCompletion(t *testing.T) {\n\tcheckFileCompletion(t, \"get all\", false)\n\tcheckFileCompletion(t, \"get all myrelease\", false)\n}\n\nfunc TestGetAllRevisionCompletion(t *testing.T) ", "output": "{\n\trevisionFlagCompletionTest(t, \"get all\")\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/client-go/applyconfigurations/meta/v1\"\n)\n\n\n\ntype TopologySpreadConstraintApplyConfiguration struct {\n\tMaxSkew *int32 `json:\"maxSkew,omitempty\"`\n\tTopologyKey *string `json:\"topologyKey,omitempty\"`\n\tWhenUnsatisfiable *v1.UnsatisfiableConstraintAction `json:\"whenUnsatisfiable,omitempty\"`\n\tLabelSelector *metav1.LabelSelectorApplyConfiguration `json:\"labelSelector,omitempty\"`\n}\n\n\n\n\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithMaxSkew(value int32) *TopologySpreadConstraintApplyConfiguration {\n\tb.MaxSkew = &value\n\treturn b\n}\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithTopologyKey(value string) *TopologySpreadConstraintApplyConfiguration {\n\tb.TopologyKey = &value\n\treturn b\n}\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithWhenUnsatisfiable(value v1.UnsatisfiableConstraintAction) *TopologySpreadConstraintApplyConfiguration {\n\tb.WhenUnsatisfiable = &value\n\treturn b\n}\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithLabelSelector(value *metav1.LabelSelectorApplyConfiguration) *TopologySpreadConstraintApplyConfiguration {\n\tb.LabelSelector = value\n\treturn b\n}\n\nfunc TopologySpreadConstraint() *TopologySpreadConstraintApplyConfiguration ", "output": "{\n\treturn &TopologySpreadConstraintApplyConfiguration{}\n}"} {"input": "package executor\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n)\n\n\n\n\n\nfunc (e *UniversalExecutor) cleanupChildProcesses(proc *os.Process) error {\n\tif e.childCmd.SysProcAttr != nil && e.childCmd.SysProcAttr.Setpgid {\n\t\tif err := syscall.Kill(-proc.Pid, syscall.SIGKILL); err != nil && err.Error() != noSuchProcessErr {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\treturn proc.Kill()\n}\n\n\n\nfunc (e *UniversalExecutor) shutdownProcess(sig os.Signal, proc *os.Process) error {\n\tif sig == nil {\n\t\tsig = os.Interrupt\n\t}\n\n\tif err := proc.Signal(sig); err != nil && err.Error() != finishedErr {\n\t\treturn fmt.Errorf(\"executor shutdown error: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (e *UniversalExecutor) setNewProcessGroup() error ", "output": "{\n\tif e.childCmd.SysProcAttr == nil {\n\t\te.childCmd.SysProcAttr = &syscall.SysProcAttr{}\n\t}\n\te.childCmd.SysProcAttr.Setpgid = true\n\treturn nil\n}"} {"input": "package router\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/valyala/fasthttp\"\n\n\t\"github.com/tpbowden/swarm-ingress-router/service\"\n)\n\n\ntype Router struct {\n\troutes map[string]service.Service\n}\n\n\nfunc (r *Router) RouteToService(address string, path string, secure bool) (fasthttp.RequestHandler, bool) {\n\tvar handler fasthttp.RequestHandler\n\n\troute, ok := r.routes[address]\n\tif !ok {\n\t\tlog.Printf(\"Failed to lookup service for %s\", address)\n\t\treturn handler, false\n\t}\n\n\tif secure && !route.Secure {\n\t\treturn handler, false\n\t}\n\n\tif secure || !route.ForceTLS {\n\t\treturn NewProxyHandler(route.URL), true\n\t}\n\n\tredirectAddress := fmt.Sprintf(\"https://%s%s\", address, path)\n\treturn NewRedirectHandler(redirectAddress, 301), true\n}\n\n\n\n\n\nfunc (r *Router) UpdateTable(services []service.Service) {\n\tnewTable := make(map[string]service.Service)\n\n\tfor _, s := range services {\n\t\tlog.Printf(\"Registering service for %s\", s.DNSName)\n\t\ts.ParseCertificate()\n\t\tnewTable[s.DNSName] = s\n\t}\n\n\tr.routes = newTable\n}\n\n\nfunc NewRouter() *Router {\n\treturn &Router{}\n}\n\nfunc (r *Router) CertificateForService(address string) (*tls.Certificate, bool) ", "output": "{\n\tvar cert *tls.Certificate\n\n\troute, ok := r.routes[address]\n\tif !ok {\n\t\tlog.Printf(\"Failed to lookup service for %s\", address)\n\t\treturn cert, false\n\t}\n\n\tcertificate := route.Certificate()\n\n\treturn &certificate, true\n}"} {"input": "package opts \n\n\n\ntype QuotedString struct {\n\tvalue *string\n}\n\n\nfunc (s *QuotedString) Set(val string) error {\n\t*s.value = trimQuotes(val)\n\treturn nil\n}\n\n\nfunc (s *QuotedString) Type() string {\n\treturn \"string\"\n}\n\nfunc (s *QuotedString) String() string {\n\treturn *s.value\n}\n\n\n\n\nfunc NewQuotedString(value *string) *QuotedString {\n\treturn &QuotedString{value: value}\n}\n\nfunc trimQuotes(value string) string ", "output": "{\n\tlastIndex := len(value) - 1\n\tfor _, char := range []byte{'\\'', '\"'} {\n\t\tif value[0] == char && value[lastIndex] == char {\n\t\t\treturn value[1:lastIndex]\n\t\t}\n\t}\n\treturn value\n}"} {"input": "package gfile_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/gogf/gf/v2/os/gfile\"\n\t\"github.com/gogf/gf/v2/test/gtest\"\n)\n\nfunc Test_MTime(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\n\t\tvar (\n\t\t\tfile1 = \"/testfile_t1.txt\"\n\t\t\terr error\n\t\t\tfileobj os.FileInfo\n\t\t)\n\n\t\tcreateTestFile(file1, \"\")\n\t\tdefer delTestFiles(file1)\n\t\tfileobj, err = os.Stat(testpath() + file1)\n\t\tt.Assert(err, nil)\n\n\t\tt.Assert(gfile.MTime(testpath()+file1), fileobj.ModTime())\n\t\tt.Assert(gfile.MTime(\"\"), \"\")\n\t})\n}\n\n\n\nfunc Test_MTimeMillisecond(t *testing.T) ", "output": "{\n\tgtest.C(t, func(t *gtest.T) {\n\t\tvar (\n\t\t\tfile1 = \"/testfile_t1.txt\"\n\t\t\terr error\n\t\t\tfileobj os.FileInfo\n\t\t)\n\n\t\tcreateTestFile(file1, \"\")\n\t\tdefer delTestFiles(file1)\n\t\tfileobj, err = os.Stat(testpath() + file1)\n\t\tt.Assert(err, nil)\n\n\t\ttime.Sleep(time.Millisecond * 100)\n\t\tt.AssertGE(\n\t\t\tgfile.MTimestampMilli(testpath()+file1),\n\t\t\tfileobj.ModTime().UnixNano()/1000000,\n\t\t)\n\t\tt.Assert(gfile.MTimestampMilli(\"\"), -1)\n\t})\n}"} {"input": "package xds\n\nimport (\n\t\"testing\"\n\n\t\"istio.io/istio/tests/util/leak\"\n)\n\n\n\nfunc TestMain(m *testing.M) ", "output": "{\n\tleak.CheckMain(m)\n}"} {"input": "package resourcemanager\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteTemplateRequest struct {\n\n\tTemplateId *string `mandatory:\"true\" contributesTo:\"path\" name:\"templateId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteTemplateRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteTemplateRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request DeleteTemplateRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request DeleteTemplateRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteTemplateResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response DeleteTemplateResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response DeleteTemplateResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package modes\n\nimport \"k8s.io/apimachinery/pkg/util/sets\"\n\nconst (\n\tModeAlwaysAllow string = \"AlwaysAllow\"\n\tModeAlwaysDeny string = \"AlwaysDeny\"\n\tModeABAC string = \"ABAC\"\n\tModeWebhook string = \"Webhook\"\n\tModeRBAC string = \"RBAC\"\n\tModeNode string = \"Node\"\n)\n\n\nvar AuthorizationModeChoices = []string{ModeAlwaysAllow, ModeAlwaysDeny, ModeABAC, ModeWebhook, ModeRBAC, ModeNode}\n\n\n\n\nfunc IsValidAuthorizationMode(authzMode string) bool ", "output": "{\n\treturn sets.NewString(AuthorizationModeChoices...).Has(authzMode)\n}"} {"input": "package metrics\n\n\n\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\tgolangswaggerpaths \"path\"\n)\n\n\ntype GetMetricsURL struct {\n\t_basePath string\n}\n\n\n\n\nfunc (o *GetMetricsURL) WithBasePath(bp string) *GetMetricsURL {\n\to.SetBasePath(bp)\n\treturn o\n}\n\n\n\n\nfunc (o *GetMetricsURL) SetBasePath(bp string) {\n\to._basePath = bp\n}\n\n\nfunc (o *GetMetricsURL) Build() (*url.URL, error) {\n\tvar result url.URL\n\n\tvar _path = \"/metrics/\"\n\n\t_basePath := o._basePath\n\tif _basePath == \"\" {\n\t\t_basePath = \"/v1\"\n\t}\n\tresult.Path = golangswaggerpaths.Join(_basePath, _path)\n\n\treturn &result, nil\n}\n\n\nfunc (o *GetMetricsURL) Must(u *url.URL, err error) *url.URL {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif u == nil {\n\t\tpanic(\"url can't be nil\")\n\t}\n\treturn u\n}\n\n\n\n\n\nfunc (o *GetMetricsURL) BuildFull(scheme, host string) (*url.URL, error) {\n\tif scheme == \"\" {\n\t\treturn nil, errors.New(\"scheme is required for a full url on GetMetricsURL\")\n\t}\n\tif host == \"\" {\n\t\treturn nil, errors.New(\"host is required for a full url on GetMetricsURL\")\n\t}\n\n\tbase, err := o.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbase.Scheme = scheme\n\tbase.Host = host\n\treturn base, nil\n}\n\n\nfunc (o *GetMetricsURL) StringFull(scheme, host string) string {\n\treturn o.Must(o.BuildFull(scheme, host)).String()\n}\n\nfunc (o *GetMetricsURL) String() string ", "output": "{\n\treturn o.Must(o.Build()).String()\n}"} {"input": "package libra\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype validator struct {\n\tname string\n\tprogram\n\tstdin io.Reader\n}\n\n\n\nfunc (v validator) Run() Status {\n\tstdout := new(bytes.Buffer)\n\tstderr := new(bytes.Buffer)\n\tv.program.cmd.Stdin = v.stdin\n\tv.program.cmd.Stdout = stdout\n\tv.program.cmd.Stderr = stderr\n\tres := v.program.Run()\n\tif res.Code != OK {\n\t\treturn Status{\n\t\t\tCode: RE,\n\t\t\tMsg: fmt.Sprintf(\"%v\", stderr.String()),\n\t\t}\n\t}\n\treturn res\n}\n\ntype valJob struct {\n\tabstractJob\n\tinputs []Input\n}\n\n\ntype Input interface {\n\tName() string\n\tReader() io.Reader\n}\n\nfunc (job valJob) Subtasks() []Task {\n\tret := make([]Task, len(job.inputs))\n\tfor i, v := range job.inputs {\n\t\tprog, _ := newProgram(job.src.Exec)\n\t\tret[i] = validator{name: v.Name(), program: prog, stdin: v.Reader()}\n\t}\n\treturn ret\n}\n\n\nfunc ValJob(src Src, inputs []Input) Job {\n\tret := valJob{}\n\tret.src = src\n\tret.inputs = inputs\n\treturn ret\n}\n\nfunc (v validator) Name() string ", "output": "{\n\treturn v.name\n}"} {"input": "package packet_proxy\n\nimport (\n\t\"github.com/bettercap/bettercap/session\"\n)\n\ntype PacketProxy struct {\n\tsession.SessionModule\n}\n\n\n\nfunc (mod PacketProxy) Name() string {\n\treturn \"packet.proxy\"\n}\n\nfunc (mod PacketProxy) Description() string {\n\treturn \"Not supported on this OS\"\n}\n\nfunc (mod PacketProxy) Author() string {\n\treturn \"Simone Margaritelli \"\n}\n\nfunc (mod *PacketProxy) Configure() (err error) {\n\treturn session.ErrNotSupported\n}\n\nfunc (mod *PacketProxy) Start() error {\n\treturn session.ErrNotSupported\n}\n\nfunc (mod *PacketProxy) Stop() error {\n\treturn session.ErrNotSupported\n}\n\nfunc NewPacketProxy(s *session.Session) *PacketProxy ", "output": "{\n\treturn &PacketProxy{\n\t\tSessionModule: session.NewSessionModule(\"packet.proxy\", s),\n\t}\n}"} {"input": "package apimgr\n\nimport \"reflect\"\n\nfunc newSorter(manager *Manager) *sorter {\n\tapis := []Definition{}\n\tfor _, api := range manager.apiMethodPatternMap {\n\t\tapis = append(apis, api)\n\t}\n\treturn &sorter{\n\t\tManager: manager,\n\t\tapis: apis,\n\t}\n}\n\ntype sorter struct {\n\t*Manager\n\n\tapis []Definition\n}\n\n\n\nfunc (t sorter) Swap(i int, j int) {\n\tt.apis[i], t.apis[j] = t.apis[j], t.apis[i]\n}\n\nfunc (t sorter) Less(i int, j int) bool {\n\tki := t.getSortKey(t.apis[i])\n\tkj := t.getSortKey(t.apis[j])\n\treturn ki < kj\n}\n\nfunc (t sorter) getSortKey(api Definition) string {\n\tpkgpath := getPackagePath(reflect.ValueOf(api.Request))\n\tkey := pkgpath + \" \" + t.GetMethodPatternKey(t.Manager, api)\n\treturn key\n}\n\nfunc (t sorter) Len() int ", "output": "{\n\treturn len(t.apis)\n}"} {"input": "package registry\n\nimport (\n\t\"time\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors\"\n\n\t\"github.com/openshift/origin/pkg/auth/api\"\n\t\"github.com/openshift/origin/pkg/oauth/registry/accesstoken\"\n\t\"github.com/openshift/origin/pkg/oauth/scope\"\n)\n\ntype TokenAuthenticator struct {\n\tregistry accesstoken.Registry\n}\n\n\n\nfunc (a *TokenAuthenticator) AuthenticateToken(value string) (api.UserInfo, bool, error) {\n\ttoken, err := a.registry.GetAccessToken(value)\n\tif errors.IsNotFound(err) {\n\t\treturn nil, false, nil\n\t}\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tif token.CreationTimestamp.Time.Add(time.Duration(token.AuthorizeToken.ExpiresIn) * time.Second).Before(time.Now()) {\n\t\treturn nil, false, nil\n\t}\n\treturn &api.DefaultUserInfo{\n\t\tName: token.AuthorizeToken.UserName,\n\t\tUID: token.AuthorizeToken.UserUID,\n\t\tScope: scope.Join(token.AuthorizeToken.Scopes),\n\t}, true, nil\n}\n\nfunc NewTokenAuthenticator(registry accesstoken.Registry) *TokenAuthenticator ", "output": "{\n\treturn &TokenAuthenticator{\n\t\tregistry: registry,\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Job struct {\n\tname string\n\ttagName string\n\ttagValue string\n\tlabels map[string]string\n\tport int\n\ttargets []string\n}\n\n\ntype Machine struct {\n\tname string\n\tmetadata map[string]string\n}\n\n\ntype TargetGroups struct {\n\ttargets []*Target\n}\n\n\ntype Target struct {\n\tTargets []string `yaml:\"targets\"\"`\n\tLabels map[string]string `yaml:\"labels\"`\n}\n\n\n\n\n\nfunc (r TargetGroups) Size() int {\n\treturn len(r.targets)\n}\n\n\nfunc (r *TargetGroups) AddTarget(name string) *Target {\n\ttarget := &Target{\n\t\tTargets: make([]string, 0),\n\t\tLabels: map[string]string{\n\t\t\t\"job\": name,\n\t\t},\n\t}\n\tr.targets = append(r.targets, target)\n\treturn target\n}\n\nfunc (r Machine) String() string ", "output": "{\n\treturn fmt.Sprintf(\"machine: %s, metadata: %s\", r.name, r.metadata)\n}"} {"input": "package windex\n\nimport (\n\t\"time\"\n)\n\ntype Windex struct {\n\tlogfile *LogFile\n\twatcher *Watcher\n\tindexer Indexer\n\tLogData chan []byte\n\tExit chan bool\n}\n\nfunc New(filename string, custom_indexer ...Indexer) (windex *Windex, err error) {\n\tlogfile, err := NewLogFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twatcher, err := NewWatcher()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar indexer Indexer\n\n\tif len(custom_indexer) == 0 {\n\t\tindexer = NewStdoutIndexer()\n\t} else {\n\t\tindexer = custom_indexer[0]\n\t}\n\n\texit := make(chan bool)\n\tlog_data := make(chan []byte, 5)\n\n\twindex = &Windex{\n\t\tlogfile: logfile,\n\t\twatcher: watcher,\n\t\tindexer: indexer,\n\t\tExit: exit,\n\t\tLogData: log_data,\n\t}\n\n\tgo windex.startwatchloop()\n\n\treturn windex, nil\n}\n\nfunc (windex *Windex) Watch() {\n\tfor {\n\t\ttime.Sleep(50 * time.Millisecond)\n\t\twindex.watcher.Watch(windex.logfile.Filename)\n\t}\n}\n\n\n\nfunc (windex *Windex) Filename() (filename string) {\n\treturn windex.logfile.Filename\n}\n\nfunc (windex *Windex) startwatchloop() {\n\tfor {\n\t\tselect {\n\t\tcase ev := <-windex.watcher.Watcher.Event:\n\t\t\tif ev != nil && ev.IsModify() && ev.Name == windex.logfile.Filename {\n\t\t\t\twindex.logfile.Flush(windex.LogData)\n\t\t\t}\n\t\tcase err := <-windex.watcher.Watcher.Error:\n\t\t\tif err != nil {\n\t\t\t\twindex.Exit <- true\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nfunc (windex *Windex) Index() ", "output": "{\n\tfor {\n\t\tparsed_log_data, _ := windex.indexer.Parse(windex.LogData)\n\t\twindex.indexer.Flush(parsed_log_data)\n\t}\n}"} {"input": "package dml\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\n\ntype ST_AnimationDgmBuildType struct {\n\tST_AnimationBuildType ST_AnimationBuildType\n\tST_AnimationDgmOnlyBuildType ST_AnimationDgmOnlyBuildType\n}\n\nfunc (m *ST_AnimationDgmBuildType) Validate() error {\n\treturn m.ValidateWithPath(\"\")\n}\n\nfunc (m ST_AnimationDgmBuildType) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\te.EncodeToken(start)\n\tif m.ST_AnimationBuildType != ST_AnimationBuildTypeUnset {\n\t\te.EncodeToken(xml.CharData(m.ST_AnimationBuildType.String()))\n\t}\n\tif m.ST_AnimationDgmOnlyBuildType != ST_AnimationDgmOnlyBuildTypeUnset {\n\t\te.EncodeToken(xml.CharData(m.ST_AnimationDgmOnlyBuildType.String()))\n\t}\n\treturn e.EncodeToken(xml.EndElement{Name: start.Name})\n}\n\nfunc (m *ST_AnimationDgmBuildType) ValidateWithPath(path string) error {\n\tmems := []string{}\n\tif m.ST_AnimationBuildType != ST_AnimationBuildTypeUnset {\n\t\tmems = append(mems, \"ST_AnimationBuildType\")\n\t}\n\tif m.ST_AnimationDgmOnlyBuildType != ST_AnimationDgmOnlyBuildTypeUnset {\n\t\tmems = append(mems, \"ST_AnimationDgmOnlyBuildType\")\n\t}\n\tif len(mems) > 1 {\n\t\treturn fmt.Errorf(\"%s too many members set: %v\", path, mems)\n\t}\n\treturn nil\n}\n\n\n\nfunc (m ST_AnimationDgmBuildType) String() string ", "output": "{\n\tif m.ST_AnimationBuildType != ST_AnimationBuildTypeUnset {\n\t\treturn m.ST_AnimationBuildType.String()\n\t}\n\tif m.ST_AnimationDgmOnlyBuildType != ST_AnimationDgmOnlyBuildTypeUnset {\n\t\treturn m.ST_AnimationDgmOnlyBuildType.String()\n\t}\n\treturn \"\"\n}"} {"input": "package classpath\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n\n\nfunc newWildcardEntry(path string) CompositeEntry ", "output": "{\n\tbaseDir := path[:len(path)-1]\n\tcompositeEntry := []Entry{}\n\n\twalkFn := func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif info.IsDir() && path != baseDir {\n\t\t\treturn filepath.SkipDir\n\t\t}\n\t\tif strings.HasSuffix(path, \".jar\") || strings.HasSuffix(path, \".JAR\") {\n\t\t\tjarEntry := newZipEntry(path)\n\t\t\tcompositeEntry = append(compositeEntry, jarEntry)\n\t\t}\n\t\treturn nil\n\t}\n\n\tfilepath.Walk(baseDir, walkFn)\n\n\treturn compositeEntry\n}"} {"input": "package backend\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com/containernetworking/cni/pkg/types\"\n)\n\n\ntype IPAMConfig struct {\n\tName string\n\tType string `json:\"type\"`\n\tRangeStart net.IP `json:\"rangeStart\"`\n\tRangeEnd net.IP `json:\"rangeEnd\"`\n\tSubnet types.IPNet `json:\"subnet\"`\n\tGateway net.IP `json:\"gateway\"`\n\tRoutes []types.Route `json:\"routes\"`\n\tArgs *IPAMArgs `json:\"-\"`\n}\n\ntype IPAMArgs struct {\n\ttypes.CommonArgs\n\tIP net.IP `json:\"ip,omitempty\"`\n}\n\ntype Net struct {\n\tName string `json:\"name\"`\n\tIPAM *IPAMConfig `json:\"ipam\"`\n}\n\n\n\n\nfunc LoadIPAMConfig(bytes []byte, args string) (*IPAMConfig, error) ", "output": "{\n\tn := Net{}\n\tif err := json.Unmarshal(bytes, &n); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif args != \"\" {\n\t\tn.IPAM.Args = &IPAMArgs{}\n\t\terr := types.LoadArgs(args, n.IPAM.Args)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif n.IPAM == nil {\n\t\treturn nil, fmt.Errorf(\"IPAM config missing 'ipam' key\")\n\t}\n\n\tn.IPAM.Name = n.Name\n\n\treturn n.IPAM, nil\n}"} {"input": "package addrmgr\n\nimport (\n\t\"time\"\n\n\t\"github.com/abcsuite/abcd/wire\"\n)\n\nfunc TstKnownAddressIsBad(ka *KnownAddress) bool {\n\treturn ka.isBad()\n}\n\nfunc TstKnownAddressChance(ka *KnownAddress) float64 {\n\treturn ka.chance()\n}\n\n\n\nfunc TstNewKnownAddress(na *wire.NetAddress, attempts int,\n\tlastattempt, lastsuccess time.Time, tried bool, refs int) *KnownAddress ", "output": "{\n\treturn &KnownAddress{na: na, attempts: attempts, lastattempt: lastattempt,\n\t\tlastsuccess: lastsuccess, tried: tried, refs: refs}\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"net/http\"\n \"sync\"\n)\n\nvar mu sync.Mutex\nvar count int\n\nfunc main() {\n http.HandleFunc(\"/\", handler)\n http.HandleFunc(\"/count\", counter)\n log.Fatal(http.ListenAndServe(\"localhost:9000\", nil))\n}\n\n\n\nfunc handler(w http.ResponseWriter, r *http.Request) ", "output": "{\n mu.lock()\n count++\n mu.Unlock\n fmt.Fprintf(w, \"URL.Path = %q\\n\", r.URL.Path)\n}"} {"input": "package cover\n\nimport (\n\t\"flag\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc ParseAndStripTestFlags() {\n\tflag.Parse()\n\n\tvar runtimeArgs []string\n\tfor _, arg := range os.Args {\n\t\tif strings.HasPrefix(arg, \"-test.\") ||\n\t\t\tstrings.HasPrefix(arg, \"-httptest.\") {\n\t\t\tcontinue\n\t\t}\n\t\truntimeArgs = append(runtimeArgs, arg)\n\t}\n\tos.Args = runtimeArgs\n}\n\ntype dummyTestDeps func(pat, str string) (bool, error)\n\nfunc (d dummyTestDeps) MatchString(pat, str string) (bool, error) { return false, nil }\nfunc (d dummyTestDeps) StartCPUProfile(io.Writer) error { return nil }\nfunc (d dummyTestDeps) StopCPUProfile() {}\nfunc (f dummyTestDeps) StartTestLog(w io.Writer) {}\nfunc (f dummyTestDeps) StopTestLog() error { return nil }\nfunc (d dummyTestDeps) WriteHeapProfile(io.Writer) error { return nil }\nfunc (d dummyTestDeps) WriteProfileTo(string, io.Writer, int) error { return nil }\n\n\n\n\n\n\nfunc FlushProfiles() {\n\toldstdout := os.Stdout\n\toldstderr := os.Stderr\n\tos.Stdout, _ = os.Open(os.DevNull)\n\tos.Stderr, _ = os.Open(os.DevNull)\n\n\ttests := []testing.InternalTest{}\n\tbenchmarks := []testing.InternalBenchmark{}\n\texamples := []testing.InternalExample{}\n\tvar f dummyTestDeps\n\tdummyM := testing.MainStart(f, tests, benchmarks, examples)\n\tdummyM.Run()\n\n\tos.Stdout = oldstdout\n\tos.Stderr = oldstderr\n}\n\nfunc (f dummyTestDeps) ImportPath() string ", "output": "{ return \"\" }"} {"input": "package targetpool_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestTargetPoolService(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Target Pool Service Suite\")\n}"} {"input": "package triangle\n\nimport (\n\t\"math\"\n)\n\nconst (\n\tEqu = iota \n\tIso \n\tSca \n\tNaT \n)\n\ntype Kind int\n\nfunc KindFromSides(a, b, c float64) Kind {\n\tif a+b <= c || a+c <= b || b+c <= a {\n\t\treturn NaT\n\t}\n\n\tswitch {\n\tcase areNaN(a, b, c): \n\t\tfallthrough\n\tcase areInf(a, b, c): \n\t\tfallthrough\n\tcase a == 0 && b == 0 && c == 0: \n\t\treturn NaT\n\n\tcase a == b && b == c: \n\t\treturn Equ\n\tcase a == b || b == c || a == c: \n\t\treturn Iso\n\tdefault: \n\t\treturn Sca\n\t}\n}\n\nfunc areNaN(vals ...float64) bool {\n\tfor _, v := range vals {\n\t\tif math.IsNaN(v) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\n\nfunc areInf(vals ...float64) bool ", "output": "{\n\tfor _, v := range vals {\n\t\tif math.IsInf(v, 1) || math.IsInf(v, -1) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package api\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"github.com/ansible-semaphore/semaphore/api/helpers\"\n\t\"github.com/ansible-semaphore/semaphore/db\"\n\t\"github.com/gorilla/context\"\n\t\"github.com/gorilla/mux\"\n\t\"io\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc getUser(w http.ResponseWriter, r *http.Request) {\n\tif u, exists := context.GetOk(r, \"_user\"); exists {\n\t\thelpers.WriteJSON(w, http.StatusOK, u)\n\t\treturn\n\t}\n\n\thelpers.WriteJSON(w, http.StatusOK, context.Get(r, \"user\"))\n}\n\nfunc getAPITokens(w http.ResponseWriter, r *http.Request) {\n\tuser := context.Get(r, \"user\").(*db.User)\n\n\ttokens, err := helpers.Store(r).GetAPITokens(user.ID)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thelpers.WriteJSON(w, http.StatusOK, tokens)\n}\n\n\n\nfunc expireAPIToken(w http.ResponseWriter, r *http.Request) {\n\tuser := context.Get(r, \"user\").(*db.User)\n\n\ttokenID := mux.Vars(r)[\"token_id\"]\n\n\terr := helpers.Store(r).ExpireAPIToken(user.ID, tokenID)\n\n\tif err != nil {\n\t\thelpers.WriteError(w, err)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusNoContent)\n}\n\nfunc createAPIToken(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tuser := context.Get(r, \"user\").(*db.User)\n\ttokenID := make([]byte, 32)\n\tif _, err := io.ReadFull(rand.Reader, tokenID); err != nil {\n\t\tpanic(err)\n\t}\n\n\ttoken, err := helpers.Store(r).CreateAPIToken(db.APIToken{\n\t\tID: strings.ToLower(base64.URLEncoding.EncodeToString(tokenID)),\n\t\tUserID: user.ID,\n\t\tExpired: false,\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\thelpers.WriteJSON(w, http.StatusCreated, token)\n}"} {"input": "package db\n\nimport (\n\t\"github.com/couchbase/go-couchbase\"\n\n\t\"github.com/couchbase/sync_gateway/base\"\n)\n\n\n\nfunc (c *DatabaseContext) watchDocChanges() {\n\tif c.tapListener.DocChannel == nil {\n\t\treturn\n\t}\n\tbase.LogTo(\"Shadow\", \"Watching doc changes...\")\n\tfor event := range c.tapListener.DocChannel {\n\t\tdoc, err := unmarshalDocument(string(event.Key), event.Value)\n\t\tif err == nil {\n\t\t\tif doc.hasValidSyncData(c.writeSequences()) {\n\t\t\t\tif c.Shadower != nil {\n\t\t\t\t\tc.Shadower.PushRevision(doc)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif c.autoImport {\n\t\t\t\t\tgo c.assimilate(doc.ID)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n\nfunc (c *DatabaseContext) assimilate(docid string) ", "output": "{\n\tbase.LogTo(\"CRUD\", \"Importing new doc %q\", docid)\n\tdb := Database{DatabaseContext: c, user: nil}\n\t_, err := db.updateDoc(docid, true, func(doc *document) (Body, error) {\n\t\tif doc.hasValidSyncData(c.writeSequences()) {\n\t\t\treturn nil, couchbase.UpdateCancel \n\t\t}\n\t\tif err := db.initializeSyncData(doc); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn doc.body, nil\n\t})\n\tif err != nil && err != couchbase.UpdateCancel {\n\t\tbase.Warn(\"Failed to import new doc %q: %v\", docid, err)\n\t}\n}"} {"input": "package parser\n\nimport (\n\t\"github.com/dop251/goja/ast\"\n)\n\ntype _scope struct {\n\touter *_scope\n\tallowIn bool\n\tinIteration bool\n\tinSwitch bool\n\tinFunction bool\n\tdeclarationList []ast.Declaration\n\n\tlabels []string\n}\n\nfunc (self *_parser) openScope() {\n\tself.scope = &_scope{\n\t\touter: self.scope,\n\t\tallowIn: true,\n\t}\n}\n\nfunc (self *_parser) closeScope() {\n\tself.scope = self.scope.outer\n}\n\n\n\nfunc (self *_scope) hasLabel(name string) bool {\n\tfor _, label := range self.labels {\n\t\tif label == name {\n\t\t\treturn true\n\t\t}\n\t}\n\tif self.outer != nil && !self.inFunction {\n\t\treturn self.outer.hasLabel(name)\n\t}\n\treturn false\n}\n\nfunc (self *_scope) declare(declaration ast.Declaration) ", "output": "{\n\tself.declarationList = append(self.declarationList, declaration)\n}"} {"input": "package util\n\n\nfunc Min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n\n\n\n\nfunc Min64(a, b int64) int64 {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc Max64(a, b int64) int64 ", "output": "{\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\n\n\n\ntype ClusterMeshStatus struct {\n\n\tClusters []*RemoteCluster `json:\"clusters\"`\n\n\tNumGlobalServices int64 `json:\"num-global-services,omitempty\"`\n}\n\n\nfunc (m *ClusterMeshStatus) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateClusters(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (m *ClusterMeshStatus) validateClusters(formats strfmt.Registry) error {\n\n\tif swag.IsZero(m.Clusters) { \n\t\treturn nil\n\t}\n\n\tfor i := 0; i < len(m.Clusters); i++ {\n\t\tif swag.IsZero(m.Clusters[i]) { \n\t\t\tcontinue\n\t\t}\n\n\t\tif m.Clusters[i] != nil {\n\t\t\tif err := m.Clusters[i].Validate(formats); err != nil {\n\t\t\t\tif ve, ok := err.(*errors.Validation); ok {\n\t\t\t\t\treturn ve.ValidateName(\"clusters\" + \".\" + strconv.Itoa(i))\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc (m *ClusterMeshStatus) UnmarshalBinary(b []byte) error {\n\tvar res ClusterMeshStatus\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *ClusterMeshStatus) MarshalBinary() ([]byte, error) ", "output": "{\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}"} {"input": "package reader_nop_close\n\nimport \"io\"\n\ntype nopCloser struct {\n\tio.Reader\n}\n\n\n\nfunc New(r io.Reader) io.ReadCloser {\n\treturn nopCloser{r}\n}\n\nfunc (nopCloser) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package datastore\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n)\n\n\ntype Posix struct {\n\tMountPoint string\n}\n\n\nfunc (p *Posix) Write(ID string, body io.Reader) (err error) {\n\timageName := path.Join(p.MountPoint, ID)\n\tif _, err := os.Stat(imageName); !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"image already uploaded with that ID\")\n\t}\n\n\timage, err := os.Create(imageName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuf := make([]byte, 1<<16)\n\n\t_, err = io.CopyBuffer(image, body, buf)\n\tdefer func() {\n\t\terr1 := image.Close()\n\t\tif err == nil {\n\t\t\terr = err1\n\t\t}\n\t}()\n\n\treturn err\n}\n\n\nfunc (p *Posix) Delete(ID string) error {\n\timageName := path.Join(p.MountPoint, ID)\n\n\t_, err := os.Stat(imageName)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\terr = nil\n\t\t}\n\t\treturn err\n\t}\n\n\terr = os.Remove(imageName)\n\n\treturn err\n}\n\n\n\n\nfunc (p *Posix) GetImageSize(ID string) (uint64, error) ", "output": "{\n\timageName := path.Join(p.MountPoint, ID)\n\n\tfi, err := os.Stat(imageName)\n\timageSize := uint64(fi.Size())\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"Error getting image size: %v\", err)\n\t}\n\treturn imageSize, nil\n}"} {"input": "package files\n\nimport (\n\tu \"github.com/araddon/gou\"\n\t\"github.com/lytics/cloudstorage\"\n\n\t\"github.com/araddon/qlbridge/datasource\"\n\t\"github.com/araddon/qlbridge/schema\"\n)\n\nvar (\n\t_ FileHandler = (*csvFiles)(nil)\n)\n\nfunc init() {\n\tRegisterFileHandler(\"csv\", &csvFiles{})\n}\n\n\ntype csvFiles struct {\n\tappendcols []string\n}\n\nfunc (m *csvFiles) Init(store FileStore, ss *schema.Schema) error { return nil }\nfunc (m *csvFiles) FileAppendColumns() []string { return m.appendcols }\nfunc (m *csvFiles) File(path string, obj cloudstorage.Object) *FileInfo {\n\treturn FileInfoFromCloudObject(path, obj)\n}\n\n\nfunc (m *csvFiles) Scanner(store cloudstorage.StoreReader, fr *FileReader) (schema.ConnScanner, error) ", "output": "{\n\tcsv, err := datasource.NewCsvSource(fr.Table, 0, fr.F, fr.Exit)\n\tif err != nil {\n\t\tu.Errorf(\"Could not open file for csv reading %v\", err)\n\t\treturn nil, err\n\t}\n\treturn csv, nil\n}"} {"input": "package models\n\nimport (\n\t\"encoding/json\"\n\t\"reflect\"\n)\n\nfunc FromJSON(payload []byte, v Validator) error {\n\terr := json.Unmarshal(payload, v)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn v.Validate()\n}\n\n\n\nfunc isNil(a interface{}) bool {\n\tif a == nil {\n\t\treturn true\n\t}\n\n\tswitch reflect.TypeOf(a).Kind() {\n\tcase reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:\n\t\treturn reflect.ValueOf(a).IsNil()\n\t}\n\n\treturn false\n}\n\nfunc ToJSON(v Validator) ([]byte, *Error) ", "output": "{\n\tif !isNil(v) {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn nil, NewError(InvalidRecord, err.Error())\n\t\t}\n\t}\n\n\tbytes, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn nil, NewError(InvalidJSON, err.Error())\n\t}\n\n\treturn bytes, nil\n}"} {"input": "package dsutil\n\nimport (\n\t\"appengine\"\n\t\"appengine/datastore\"\n)\n\n\n\nfunc EntityExists(ctx appengine.Context, key *datastore.Key) (bool, error) {\n\tq := datastore.NewQuery(key.Kind()).\n\t\tAncestor(key).\n\t\tFilter(\"__key__=\", key)\n\n\tn, err := q.Count(ctx)\n\treturn n > 0, err\n}\n\nfunc RootKey(key *datastore.Key) *datastore.Key ", "output": "{\n\tfor parent := key; parent != nil; {\n\t\tkey = parent\n\t\tparent = key.Parent()\n\t}\n\treturn key\n}"} {"input": "package network\n\nimport (\n\t\"github.com/containerd/containerd/oci\"\n\tspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n)\n\nfunc NewHostProvider() Provider {\n\treturn &host{}\n}\n\ntype host struct {\n}\n\n\n\ntype hostNS struct {\n}\n\nfunc (h *hostNS) Set(s *specs.Spec) error {\n\treturn oci.WithHostNamespace(specs.NetworkNamespace)(nil, nil, nil, s)\n}\n\nfunc (h *hostNS) Close() error {\n\treturn nil\n}\n\nfunc (h *host) New() (Namespace, error) ", "output": "{\n\treturn &hostNS{}, nil\n}"} {"input": "package slack\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestNewSlackConfig(t *testing.T) {\n\tconf, err := newConfigGood()\n\n\tif err != nil {\n\t\tt.Log(\"could not load slack config file\")\n\t\tt.Log(err.Error())\n\t\tt.Fail()\n\t}\n\n\tif conf == nil {\n\t\tt.Log(\"conf is nil\")\n\t}\n\n\tif conf.WebhookUrl == \"\" {\n\t\tt.Log(\"conf.WebhookUrl is empty\")\n\t}\n\n\tif conf.WebhookUrl != \"http://test\" {\n\t\tt.Log(\"WebhookUrl was not the expected value: \" + conf.WebhookUrl)\n\t\tt.Fail()\n\t}\n\n\tif conf.BotUsername != \"GoShipit\" {\n\t\tt.Log(\"BotUsername exptected to be . Actual <\" +\n\t\t\tconf.BotUsername + \">.\")\n\t\tt.Fail()\n\t}\n}\n\nfunc newConfigGood() (config *SlackConfig, err error) ", "output": "{\n\tconfig, err = newSlackConfig(\"testing/slack_good.json\")\n\treturn\n}"} {"input": "package matchers_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/blevesearch/bleve\"\n\t\"github.com/blevesearch/bleve/search/query\"\n\t\"github.com/nrwiersma/isenzo/matchers\"\n)\n\nfunc TestParallelMatcher(t *testing.T) {\n\tf := matchers.NewParallelMatcherFactory(newWaitMatcherFactory(), 10)\n\tm, err := f.New(map[string]interface{}{})\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected err; got %v\", err)\n\t}\n\n\tfor i := 0; i < 10; i++ {\n\t\tm.Match(\"\", bleve.NewMatchAllQuery())\n\t}\n\n\tids, errs := m.Finish()\n\tif len(errs) != 0 {\n\t\tt.Fatalf(\"expected no errors; got %v\", errs)\n\t}\n\n\tif len(ids) != 10 {\n\t\tt.Fatalf(\"expected %d results; got %v\", 10, len(ids))\n\t}\n}\n\ntype waitMatcherFactory struct {}\n\nfunc newWaitMatcherFactory() matchers.Factory {\n\treturn &waitMatcherFactory{}\n}\n\nfunc (f waitMatcherFactory) New(doc interface{}) (matchers.Matcher, error) {\n\treturn &waitMatcher{\n\t\tids: make([]string, 0),\n\t}, nil\n}\n\nfunc (f waitMatcherFactory) Map(doc interface{}) (interface{}, error) {\n\treturn doc, nil\n}\n\ntype waitMatcher struct {\n\tids []string\n}\n\n\n\n\n\nfunc (m *waitMatcher) Finish() (ids []string, errs []error) {\n\treturn m.ids, []error{}\n}\n\nfunc (m *waitMatcher) Match(id string, q query.Query) ", "output": "{\n\ttime.Sleep(10 * time.Millisecond)\n\n\tm.ids = append(m.ids, id)\n}"} {"input": "package livereload\n\nimport (\n\t\"bytes\"\n\t\"sync\"\n\n\t\"github.com/gorilla/websocket\"\n)\n\ntype connection struct {\n\tws *websocket.Conn\n\n\tsend chan []byte\n\n\tcloser sync.Once\n}\n\nfunc (c *connection) close() {\n\tc.closer.Do(func() {\n\t\tclose(c.send)\n\t})\n}\n\n\n\nfunc (c *connection) writer() {\n\tfor message := range c.send {\n\t\terr := c.ws.WriteMessage(websocket.TextMessage, message)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tc.ws.Close()\n}\n\nfunc (c *connection) reader() ", "output": "{\n\tfor {\n\t\t_, message, err := c.ws.ReadMessage()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif bytes.Contains(message, []byte(`\"command\":\"hello\"`)) {\n\t\t\tc.send <- []byte(`{\n\t\t\t\t\"command\": \"hello\",\n\t\t\t\t\"protocols\": [ \"http:livereload.com/protocols/official-7\" ],\n\t\t\t\t\"serverName\": \"Hugo\"\n\t\t\t}`)\n\t\t}\n\t}\n\tc.ws.Close()\n}"} {"input": "package abi\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/ethereum/go-ethereum/crypto\"\n)\n\n\n\n\n\n\n\n\n\ntype Method struct {\n\tName string\n\tConst bool\n\tInputs []Argument\n\tOutputs []Argument\n}\n\n\n\n\n\n\n\n\n\n\nfunc (m Method) Sig() string {\n\ttypes := make([]string, len(m.Inputs))\n\ti := 0\n\tfor _, input := range m.Inputs {\n\t\ttypes[i] = input.Type.String()\n\t\ti++\n\t}\n\treturn fmt.Sprintf(\"%v(%v)\", m.Name, strings.Join(types, \",\"))\n}\n\nfunc (m Method) String() string {\n\tinputs := make([]string, len(m.Inputs))\n\tfor i, input := range m.Inputs {\n\t\tinputs[i] = fmt.Sprintf(\"%v %v\", input.Name, input.Type)\n\t}\n\toutputs := make([]string, len(m.Outputs))\n\tfor i, output := range m.Outputs {\n\t\tif len(output.Name) > 0 {\n\t\t\toutputs[i] = fmt.Sprintf(\"%v \", output.Name)\n\t\t}\n\t\toutputs[i] += output.Type.String()\n\t}\n\tconstant := \"\"\n\tif m.Const {\n\t\tconstant = \"constant \"\n\t}\n\treturn fmt.Sprintf(\"function %v(%v) %sreturns(%v)\", m.Name, strings.Join(inputs, \", \"), constant, strings.Join(outputs, \", \"))\n}\n\nfunc (m Method) Id() []byte {\n\treturn crypto.Keccak256([]byte(m.Sig()))[:4]\n}\n\nfunc (method Method) pack(args ...interface{}) ([]byte, error) ", "output": "{\n\tif len(args) != len(method.Inputs) {\n\t\treturn nil, fmt.Errorf(\"argument count mismatch: %d for %d\", len(args), len(method.Inputs))\n\t}\n\tvar variableInput []byte\n\n\tvar ret []byte\n\tfor i, a := range args {\n\t\tinput := method.Inputs[i]\n\t\tpacked, err := input.Type.pack(reflect.ValueOf(a))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"`%s` %v\", method.Name, err)\n\t\t}\n\n\t\tif input.Type.requiresLengthPrefix() {\n\t\t\toffset := len(method.Inputs)*32 + len(variableInput)\n\t\t\tret = append(ret, packNum(reflect.ValueOf(offset))...)\n\t\t\tvariableInput = append(variableInput, packed...)\n\t\t} else {\n\t\t\tret = append(ret, packed...)\n\t\t}\n\t}\n\tret = append(ret, variableInput...)\n\n\treturn ret, nil\n}"} {"input": "package fse\n\n\n\ntype Encoder struct {\n\tstate uint16 \n\ttransform []symbolTransform \n\ttable []uint16 \n\twriteBits func(value uint16, n uint8) \n}\n\n\ntype symbolTransform struct {\n\tdeltaFindState int32 \n\tdeltaNbBits uint32 \n}\n\n\n\n\nfunc (e *Encoder) Encode(b byte) ", "output": "{\n\tsymbolTT := e.transform[b]\n\tnbBitsOut := uint8((uint32(e.state) + symbolTT.deltaNbBits) >> 16)\n\te.writeBits(e.state, nbBitsOut)\n\tdstState := int32(e.state>>nbBitsOut) + symbolTT.deltaFindState\n\te.state = e.table[dstState]\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n)\n\nfunc main() {\n\ttests := []int{234, 4421}\n\n\tfor _, test := range tests {\n\t\tlog.Printf(\"subtractProductAndSum(%d) = %d\\n\", test, subtractProductAndSum(test))\n\t}\n}\n\n\n\nfunc getDecimalDigits(n int) []int {\n\tres := []int{}\n\n\trem := n % 10\n\tn = n / 10\n\tres = append(res, rem)\n\n\tfor n > 0 {\n\t\trem = n % 10\n\t\tn = n / 10\n\n\t\tres = append(res, rem)\n\t}\n\n\treturn res\n}\n\nfunc getTotal(nums []int) int {\n\tvar tot int\n\n\tfor _, n := range nums {\n\t\ttot += n\n\t}\n\n\treturn tot\n}\n\nfunc getProduct(nums []int) int {\n\tvar prod int\n\n if len(nums) > 0 {\n prod = 1\n }\n\n\tfor _, n := range nums {\n\t\tprod *= n\n\t}\n\n\treturn prod\n}\n\nfunc subtractProductAndSum(n int) int ", "output": "{\n\tnDigits := getDecimalDigits(n)\n \n\n \n \n\n \n \n\n\treturn (getProduct(nDigits) - getTotal(nDigits))\n}"} {"input": "package autobackup\n\nimport (\n\t\"context\"\n\n\t\"github.com/sacloud/libsacloud/v2/helper/service\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n)\n\n\n\nfunc (s *Service) DeleteWithContext(ctx context.Context, req *DeleteRequest) error {\n\tif err := req.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tclient := sacloud.NewAutoBackupOp(s.caller)\n\tif err := client.Delete(ctx, req.Zone, req.ID); err != nil {\n\t\treturn service.HandleNotFoundError(err, !req.FailIfNotFound)\n\t}\n\treturn nil\n}\n\nfunc (s *Service) Delete(req *DeleteRequest) error ", "output": "{\n\treturn s.DeleteWithContext(context.Background(), req)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\n\t\"github.com/ToQoz/gopwt\"\n\t\"github.com/ToQoz/gopwt/assert\"\n\n\t\"testing\"\n)\n\ntype myint int\n\nconst two myint = 2\n\nfunc TestMain(m *testing.M) {\n\tflag.Parse()\n\tgopwt.Empower()\n\tos.Exit(m.Run())\n}\n\n\n\nfunc TestFoo(t *testing.T) ", "output": "{\n\ta := myint(6)\n\tassert.OK(t, a == 3*two)\n}"} {"input": "package models\n\nimport \"testing\"\n\n\nfunc TestGetTypeName(t *testing.T) {\n\t_, err := GetTypeName(2)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}\n\nfunc TestGetSystemName(t *testing.T) {\n\t_, err := GetSystemName(30000001)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}\n\nfunc TestGetCelestialName(t *testing.T) {\n\t_, err := GetCelestialName(30000001)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}\n\nfunc TestGetEntityName(t *testing.T) ", "output": "{\n\t_, err := GetEntityName(2)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}"} {"input": "package libnetwork\n\nimport (\n\t\"fmt\"\n\t\"net\"\n)\n\nfunc (c *controller) cleanupServiceBindings(nid string) {\n}\n\n\n\nfunc (c *controller) rmServiceBinding(name, sid, nid, eid string, vip net.IP, ingressPorts []*PortConfig, aliases []string, ip net.IP) error {\n\treturn fmt.Errorf(\"not supported\")\n}\n\nfunc (sb *sandbox) populateLoadbalancers(ep *endpoint) {\n}\n\nfunc arrangeIngressFilterRule() {\n}\n\nfunc (c *controller) addServiceBinding(name, sid, nid, eid string, vip net.IP, ingressPorts []*PortConfig, aliases []string, ip net.IP) error ", "output": "{\n\treturn fmt.Errorf(\"not supported\")\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/unrolled/render\"\n)\n\n\nvar Render *render.Render\n\n\nfunc init() {\n\tRender = render.New(render.Options{\n\t\tIndentJSON: true,\n\t})\n}\n\nfunc index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Welcome to the home page!\")\n}\n\nfunc apiHandler(w http.ResponseWriter, r *http.Request) {\n\tRender.JSON(w, http.StatusOK, \"Welcome to the api hander page!\")\n}\n\nfunc apiKeyHandler(w http.ResponseWriter, r *http.Request) {\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the api Key hander page! %s\", id)\n}\n\n\n\nfunc webKeyHandler(w http.ResponseWriter, r *http.Request) {\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the web Key hander page! %s\", id)\n}\n\nfunc notFound(w http.ResponseWriter, r *http.Request) {\n\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n}\n\nfunc apiKeyDetailsHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the api Key Details hander page! %s\", id)\n}"} {"input": "package jms\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype UpdateFleetAgentConfigurationRequest struct {\n\n\tFleetId *string `mandatory:\"true\" contributesTo:\"path\" name:\"fleetId\"`\n\n\tUpdateFleetAgentConfigurationDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request UpdateFleetAgentConfigurationRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request UpdateFleetAgentConfigurationRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request UpdateFleetAgentConfigurationRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateFleetAgentConfigurationResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateFleetAgentConfigurationResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateFleetAgentConfigurationResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateFleetAgentConfigurationRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package lib\n\nimport (\n\t\"fmt\"\n)\n\ntype Foo struct {\n\tBar\n}\n\ntype Bar struct{}\n\nfunc NewFoo() *Foo {\n\treturn &Foo{}\n}\n\n\n\nfunc (b *Bar) Wibble() error ", "output": "{\n\treturn fmt.Errorf(\"Not Mocked!\")\n}"} {"input": "package google\n\nimport (\n\t\"google.golang.org/api/compute/v1\"\n)\n\n\n\n\nfunc readDiskType(c *Config, zone *compute.Zone, name string) (*compute.DiskType, error) ", "output": "{\n\tdiskType, err := c.clientCompute.DiskTypes.Get(c.Project, zone.Name, name).Do()\n\tif err == nil && diskType != nil && diskType.SelfLink != \"\" {\n\t\treturn diskType, nil\n\t} else {\n\t\treturn nil, err\n\t}\n}"} {"input": "package demopgx\n\nimport (\n\t\"math/big\"\n)\n\n\n\n\n\n\n\ntype User struct {\n\tUid int64 `sql:\"pk: true, auto: true\"`\n\tName string `sql:\"unique: user_login\"`\n\tEmailAddress string `sql:\"nk: true\"`\n\tAddressId *int64 `sql:\"fk: addresses.id, onupdate: restrict, ondelete: restrict\"`\n\tAvatar *string\n\tRole *Role `sql:\"type: text, size: 20\"`\n\tActive bool\n\tAdmin bool\n\tFave *big.Int `sql:\"encode: json\"`\n\tLastUpdated int64\n\n\tNumbers Numbers\n\n\ttoken string\n\tsecret string\n\n\thash string `sql:\"-\"`\n}\n\ntype Numbers struct {\n\tI8 int8 `sql:\"default: -8\"`\n\tU8 uint8 `sql:\"default: 8\"`\n\tI16 int16 `sql:\"default: -16\"`\n\tU16 uint16 `sql:\"default: 16\"`\n\tI32 int32 `sql:\"default: -32\"`\n\tU32 uint32 `sql:\"default: 32\"`\n\tI64 int64 `sql:\"default: -64\"`\n\tU64 uint64 `sql:\"default: 64\"`\n\tF32 float32 `sql:\"default: 3.2\"`\n\tF64 float64 `sql:\"default: 6.4\"`\n}\n\n\nfunc (u *User) PreInsert() error {\n\tu.hash = \"PreInsert\"\n\treturn nil\n}\n\nfunc (u *User) PreUpdate() error {\n\tu.hash = \"PreUpdate\"\n\treturn nil\n}\n\n\n\nfunc (u *User) PostGet() error ", "output": "{\n\tu.hash = \"PostGet\"\n\treturn nil\n}"} {"input": "package assert\n\n\n\n\n\n\n\n\n\ntype testReporter struct {\n\ttemplate string\n\targs []interface{}\n}\n\nfunc (r *testReporter) Fatalf(template string, args ...interface{}) {\n\tr.template = template\n\tr.args = args\n}\n\nfunc (r *testReporter) Log(args ...interface{}) {}\n\nfunc (r *testReporter) Logf(format string, args ...interface{}) {}\n\n\n\nfunc newTestReporter() *testReporter ", "output": "{\n\tt := new(testReporter)\n\tFatalf = func(t testingT, format string, args ...interface{}) {\n\t\tt.Fatalf(format, args...)\n\t}\n\treturn t\n}"} {"input": "package typeutil\n\n\n\nimport \"golang.org/x/tools/go/types\"\n\n\n\n\n\n\n\n\n\n\n\n\nfunc IntuitiveMethodSet(T types.Type, msets *MethodSetCache) []*types.Selection ", "output": "{\n\tvar result []*types.Selection\n\tmset := msets.MethodSet(T)\n\tif _, ok := T.Underlying().(*types.Interface); ok {\n\t\tfor i, n := 0, mset.Len(); i < n; i++ {\n\t\t\tresult = append(result, mset.At(i))\n\t\t}\n\t} else {\n\t\tpmset := msets.MethodSet(types.NewPointer(T))\n\t\tfor i, n := 0, pmset.Len(); i < n; i++ {\n\t\t\tmeth := pmset.At(i)\n\t\t\tif m := mset.Lookup(meth.Obj().Pkg(), meth.Obj().Name()); m != nil {\n\t\t\t\tmeth = m\n\t\t\t}\n\t\t\tresult = append(result, meth)\n\t\t}\n\t}\n\treturn result\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"path\"\n\n\t\"github.com/emicklei/go-restful\"\n)\n\n\n\n\n\n\n\n\n\nvar rootdir = \"/tmp\"\n\nfunc main() {\n\trestful.DefaultContainer.Router(restful.CurlyRouter{})\n\n\tws := new(restful.WebService)\n\tws.Route(ws.GET(\"/static/{subpath:*}\").To(staticFromPathParam))\n\tws.Route(ws.GET(\"/static\").To(staticFromQueryParam))\n\trestful.Add(ws)\n\n\tprintln(\"[go-restful] serving files on http:localhost:8080/static from local /tmp\")\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc staticFromPathParam(req *restful.Request, resp *restful.Response) {\n\tactual := path.Join(rootdir, req.PathParameter(\"subpath\"))\n\tfmt.Printf(\"serving %s ... (from %s)\\n\", actual, req.PathParameter(\"subpath\"))\n\thttp.ServeFile(\n\t\tresp.ResponseWriter,\n\t\treq.Request,\n\t\tactual)\n}\n\n\n\nfunc staticFromQueryParam(req *restful.Request, resp *restful.Response) ", "output": "{\n\thttp.ServeFile(\n\t\tresp.ResponseWriter,\n\t\treq.Request,\n\t\tpath.Join(rootdir, req.QueryParameter(\"resource\")))\n}"} {"input": "package balancetransaction\n\nimport (\n\t\"net/http\"\n\n\tstripe \"github.com/stripe/stripe-go\"\n\t\"github.com/stripe/stripe-go/form\"\n)\n\n\ntype Client struct {\n\tB stripe.Backend\n\tKey string\n}\n\n\nfunc Get(id string, params *stripe.BalanceTransactionParams) (*stripe.BalanceTransaction, error) {\n\treturn getC().Get(id, params)\n}\n\n\nfunc (c Client) Get(id string, params *stripe.BalanceTransactionParams) (*stripe.BalanceTransaction, error) {\n\tpath := stripe.FormatURLPath(\"/v1/balance_transactions/%s\", id)\n\ttransaction := &stripe.BalanceTransaction{}\n\terr := c.B.Call(http.MethodGet, path, c.Key, params, transaction)\n\treturn transaction, err\n}\n\n\nfunc List(params *stripe.BalanceTransactionListParams) *Iter {\n\treturn getC().List(params)\n}\n\n\n\n\n\ntype Iter struct {\n\t*stripe.Iter\n}\n\n\nfunc (i *Iter) BalanceTransaction() *stripe.BalanceTransaction {\n\treturn i.Current().(*stripe.BalanceTransaction)\n}\n\nfunc getC() Client {\n\treturn Client{stripe.GetBackend(stripe.APIBackend), stripe.Key}\n}\n\nfunc (c Client) List(listParams *stripe.BalanceTransactionListParams) *Iter ", "output": "{\n\treturn &Iter{stripe.GetIter(listParams, func(p *stripe.Params, b *form.Values) ([]interface{}, stripe.ListMeta, error) {\n\t\tlist := &stripe.BalanceTransactionList{}\n\t\terr := c.B.CallRaw(http.MethodGet, \"/v1/balance_transactions\", c.Key, b, p, list)\n\n\t\tret := make([]interface{}, len(list.Data))\n\t\tfor i, v := range list.Data {\n\t\t\tret[i] = v\n\t\t}\n\n\t\treturn ret, list.ListMeta, err\n\t})}\n}"} {"input": "package client\n\nimport \"encoding/json\"\n\n\ntype UserResponse struct {\n\tVersion string `json:\"version\"`\n\tResponse []User `json:\"response\"`\n}\n\n\ntype User struct {\n\tUsername string `json:\"username,omitempty\"`\n\tPublicSSHKey string `json:\"publicSshKey,omitempty\"`\n\tRole string `json:\"role,omitempty\"`\n\tRoleName string `json:\"rolename,omitempty\"`\n\tUID string `json:\"uid,omitempty\"`\n\tGID string `json:\"gid,omitempty\"`\n\tCompany string `json:\"company,omitempty\"`\n\tEmail string `json:\"email,omitempty\"`\n\tFullName string `json:\"fullName,omitempty\"`\n\tNewUser bool `json:\"newUser,omitempty\"`\n\tLastUpdated string `json:\"lastUpdated,omitempty\"`\n}\n\n\n\n\nfunc (to *Session) Users() ([]User, error) ", "output": "{\n\turl := \"/api/1.2/users.json\"\n\tresp, err := to.request(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar data UserResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&data.Response); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data.Response, nil\n}"} {"input": "package matchers_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/blevesearch/bleve\"\n\t\"github.com/blevesearch/bleve/search/query\"\n\t\"github.com/nrwiersma/isenzo/matchers\"\n)\n\n\n\ntype waitMatcherFactory struct {}\n\nfunc newWaitMatcherFactory() matchers.Factory {\n\treturn &waitMatcherFactory{}\n}\n\nfunc (f waitMatcherFactory) New(doc interface{}) (matchers.Matcher, error) {\n\treturn &waitMatcher{\n\t\tids: make([]string, 0),\n\t}, nil\n}\n\nfunc (f waitMatcherFactory) Map(doc interface{}) (interface{}, error) {\n\treturn doc, nil\n}\n\ntype waitMatcher struct {\n\tids []string\n}\n\n\nfunc (m *waitMatcher) Match(id string, q query.Query) {\n\ttime.Sleep(10 * time.Millisecond)\n\n\tm.ids = append(m.ids, id)\n}\n\n\nfunc (m *waitMatcher) Finish() (ids []string, errs []error) {\n\treturn m.ids, []error{}\n}\n\nfunc TestParallelMatcher(t *testing.T) ", "output": "{\n\tf := matchers.NewParallelMatcherFactory(newWaitMatcherFactory(), 10)\n\tm, err := f.New(map[string]interface{}{})\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected err; got %v\", err)\n\t}\n\n\tfor i := 0; i < 10; i++ {\n\t\tm.Match(\"\", bleve.NewMatchAllQuery())\n\t}\n\n\tids, errs := m.Finish()\n\tif len(errs) != 0 {\n\t\tt.Fatalf(\"expected no errors; got %v\", errs)\n\t}\n\n\tif len(ids) != 10 {\n\t\tt.Fatalf(\"expected %d results; got %v\", 10, len(ids))\n\t}\n}"} {"input": "package avl\n\n\nfunc (tree *Tree) First() *Node {\n\treturn tree.root.first()\n}\n\n\nfunc (tree *Node) first() *Node {\n\tif nil == tree {\n\t\treturn nil\n\t}\n\tfor nil != tree.left {\n\t\ttree = tree.left\n\t}\n\treturn tree\n}\n\n\n\n\n\nfunc (tree *Node) last() *Node {\n\tif nil == tree {\n\t\treturn nil\n\t}\n\tfor nil != tree.right {\n\t\ttree = tree.right\n\t}\n\treturn tree\n}\n\n\n\nfunc (tree *Node) Next() *Node {\n\tif nil == tree.right {\n\t\tkey := tree.key\n\t\tfor {\n\t\t\ttree = tree.up\n\t\t\tif nil == tree {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif 1 == tree.key.Compare(key) { \n\t\t\t\treturn tree\n\t\t\t}\n\t\t}\n\t}\n\treturn tree.right.first()\n}\n\n\n\nfunc (tree *Node) Prev() *Node {\n\tif nil == tree.left {\n\t\tkey := tree.key\n\t\tfor {\n\t\t\ttree = tree.up\n\t\t\tif nil == tree {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif -1 == tree.key.Compare(key) { \n\t\t\t\treturn tree\n\t\t\t}\n\t\t}\n\t}\n\treturn tree.left.last()\n}\n\nfunc (tree *Tree) Last() *Node ", "output": "{\n\treturn tree.root.last()\n}"} {"input": "package auth\n\nimport (\n \"github.com/gin-gonic/gin\"\n \"io/ioutil\"\n \"log\"\n \"encoding/json\"\n)\n\n\n\nfunc postLogin1(c *gin.Context) {\n\n log.Println(authConf)\n\n body, err := ioutil.ReadAll(c.Request.Body)\n if err != nil {\n log.Println(err)\n c.Abort()\n }\n\n sess, _ := authConf.Session.SessionStart(c.Writer, c.Request)\n defer sess.SessionRelease(c.Writer)\n log.Println(\"SessionStart\")\n\n log.Println(string(body))\n\n data := make(map[string]string)\n err = json.Unmarshal(body, &data)\n if err != nil {\n c.AbortWithError(500, err)\n }\n\n log.Println(data)\n sess.Set(\"user\", data[\"user\"])\n\n}\n\nfunc postLogin(c *gin.Context) ", "output": "{\n log.Println(\"postLogin\")\n \n sess, _ := authConf.Session.SessionStart(c.Writer, c.Request)\n defer sess.SessionRelease(c.Writer)\n\n username := c.Request.FormValue(\"username\")\n sess.Set(\"user\", username)\n\n c.String(200, \"hello %s\", username)\n}"} {"input": "package sdk\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\nfunc init() {\n\tNowTime = time.Now\n\tSleep = time.Sleep\n\tSleepWithContext = sleepWithContext\n}\n\n\n\nvar NowTime func() time.Time\n\n\n\nvar Sleep func(time.Duration)\n\n\n\n\n\n\nvar SleepWithContext func(context.Context, time.Duration) error\n\n\n\n\nfunc sleepWithContext(ctx context.Context, dur time.Duration) error {\n\tt := time.NewTimer(dur)\n\tdefer t.Stop()\n\n\tselect {\n\tcase <-t.C:\n\t\tbreak\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n\n\treturn nil\n}\n\n\nfunc noOpSleepWithContext(context.Context, time.Duration) error {\n\treturn nil\n}\n\nfunc noOpSleep(time.Duration) {}\n\n\n\n\n\n\n\nfunc TestingUseReferenceTime(referenceTime time.Time) func() {\n\tNowTime = func() time.Time {\n\t\treturn referenceTime\n\t}\n\treturn func() {\n\t\tNowTime = time.Now\n\t}\n}\n\nfunc TestingUseNopSleep() func() ", "output": "{\n\tSleepWithContext = noOpSleepWithContext\n\tSleep = noOpSleep\n\n\treturn func() {\n\t\tSleepWithContext = sleepWithContext\n\t\tSleep = time.Sleep\n\t}\n}"} {"input": "package fractal\n\nimport (\n\t\"reflect\"\n\t\"github.com/nsf/termbox-go\"\n\t\"testing\"\n)\n\n\n\nfunc TestFrameProxyCursor(t *testing.T) {\n\thandler := &TestHandler{}\n\tproxy := NewFrameProxy(handler, 0, 0)\n\tproxy.Frame.bwidth, proxy.Frame.bheight = 2, 2\n\toffsetCursor := handler.GetCursor()\n\toffsetCursor.X++\n\toffsetCursor.Y++\n\n\tif offsetCursor != proxy.GetCursor() {\n\t\tt.Errorf(\"did not proxy GetCursor correctly\")\n\t}\n}\n\nfunc TestFrameProxyMan(t *testing.T) ", "output": "{\n\tmyManual := Manual{\n\t\tSummary: \"sup\",\n\t\tKeys: KeyMap{\n\t\t\ttermbox.Event{Ch: 'j'}: {\n\t\t\t\tID: \"wow\",\n\t\t\t\tDescription: \"now\",\n\t\t\t},\n\t\t},\n\t}\n\thandler := &TestHandler{Manual: myManual}\n\tif !reflect.DeepEqual(handler.Man(), NewFrameProxy(handler, 0, 0).Man()) {\n\t\tt.Errorf(\"did not proxy Man correctly\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"encoding/base32\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/url\"\n\t\"os\"\n\t\"strings\"\n)\n\n\n\nfunc unescape(encoding string) {\n\tswitch {\n\tcase strings.HasPrefix(\"query\", encoding):\n\t\tb, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\ts, err := url.QueryUnescape(string(b))\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tos.Stdout.Write([]byte(s))\n\tcase strings.HasPrefix(\"b32\", encoding):\n\t\td := base32.NewDecoder(base32.StdEncoding, os.Stdin)\n\t\tio.Copy(os.Stdout, d)\n\tdefault:\n\t\tfmt.Fprintf(os.Stderr, \"unknown unescape encoding: %q\\n\", encoding)\n\t}\n}\n\nfunc main() {\n\tif len(os.Args) != 3 {\n\t\tfmt.Fprintf(os.Stderr, \"expected two arguments: : got %d\\n\", len(os.Args)-1)\n\t\tos.Exit(2)\n\t}\n\tmode := os.Args[1]\n\tswitch {\n\tcase strings.HasPrefix(\"escape\", mode):\n\t\tescape(os.Args[2])\n\tcase strings.HasPrefix(\"unescape\", mode) || strings.HasPrefix(\"decode\", mode):\n\t\tunescape(os.Args[2])\n\tdefault:\n\t\tfmt.Fprintf(os.Stderr, \"unknown mode: %q\\n\", mode)\n\t\tos.Exit(2)\n\t}\n}\n\nfunc escape(encoding string) ", "output": "{\n\tswitch {\n\tcase strings.HasPrefix(\"query\", encoding):\n\t\tb, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tos.Stdout.Write([]byte(url.QueryEscape(string(b))))\n\tcase strings.HasPrefix(\"hex\", encoding):\n\t\tb, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tos.Stdout.Write([]byte(hex.EncodeToString(b)))\n\tdefault:\n\t\tfmt.Fprintf(os.Stderr, \"unknown escape encoding: %q\\n\", encoding)\n\t\tos.Exit(2)\n\t}\n}"} {"input": "package tabular\n\nimport (\n\t\"bytes\"\n\t\"github.com/omakoto/mlib\"\n\t\"strings\"\n)\n\nfunc Tabular(r <-chan []string) <-chan string {\n\tout := make(chan string)\n\n\tgo func() {\n\t\tdefer close(out)\n\t\tdoTabular(r, out)\n\t}()\n\n\treturn out\n}\n\n\n\nfunc doTabular(r <-chan []string, out chan<- string) {\n\tall := make([][]string, 0, 1024)\n\twidths := make([]int, 0)\n\n\tmlib.Debug(\"Reading input...\\n\")\n\n\tfor fields := range r {\n\t\tall = append(all, fields)\n\t\tfor i := 0; i < len(fields); i++ {\n\t\t\tif len(widths) < len(fields) {\n\t\t\t\told := widths\n\t\t\t\twidths = make([]int, len(fields))\n\t\t\t\tcopy(widths, old)\n\t\t\t}\n\t\t\tmlib.Debug(\" index=%d, cur=%d\\n\", i, widths[i])\n\t\t\twidths[i] = max(widths[i], stringWidth(fields[i]))\n\t\t}\n\t}\n\n\tmlib.Debug(\"Read all lines\\n\")\n\n\tmlib.DebugDump(all)\n\tmlib.DebugDump(widths)\n\n\toutBuffer := bytes.Buffer{}\n\n\tfor _, fields := range all {\n\t\toutBuffer.Reset()\n\t\tfor i := 0; i < len(fields); i++ {\n\t\t\tif i > 0 {\n\t\t\t\toutBuffer.WriteString(\" \")\n\t\t\t}\n\t\t\tw := stringWidth(fields[i])\n\t\t\toutBuffer.WriteString(fields[i])\n\t\t\toutBuffer.WriteString(strings.Repeat(\" \", widths[i]-w))\n\t\t}\n\t\tout <- outBuffer.String()\n\t}\n}\n\nfunc max(a, b int) int ", "output": "{\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}"} {"input": "package log\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\ntype Exit struct {\n\tCode int\n\tClosure func()\n}\n\nfunc HandleExit() {\n\tif e := recover(); e != nil {\n\t\tif exit, ok := e.(Exit); ok {\n\t\t\texit.Closure()\n\t\t\tos.Exit(exit.Code)\n\t\t}\n\t\tpanic(e)\n\t}\n}\n\n\n\nfunc Warn(msg string) {\n\tfmt.Printf(\"\\033[1;33m[WARNING]\\033[0m %s\\n\", msg)\n}\n\nfunc Succ(msg string) {\n\tfmt.Printf(\"\\033[1;32m[DONE]\\033[0m %s\\n\", msg)\n}\n\nfunc Error(msg string, closure func()) ", "output": "{\n\tfmt.Printf(\"\\033[1;31m[ERROR]\\033[0m %s\\n\", msg)\n\tpanic(Exit{1, closure})\n}"} {"input": "package apiv1\n\nimport (\n\t\"encoding/json\"\n)\n\ntype DiskHint struct {\n\tval interface{}\n}\n\nvar _ json.Unmarshaler = &DiskHint{}\nvar _ json.Marshaler = DiskHint{}\n\nfunc NewDiskHintFromString(val string) DiskHint {\n\treturn DiskHint{val}\n}\n\n\n\nfunc (i *DiskHint) UnmarshalJSON(data []byte) error {\n\tvar val interface{}\n\n\terr := json.Unmarshal(data, &val)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*i = DiskHint{val}\n\n\treturn nil\n}\n\nfunc (i DiskHint) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(i.val)\n}\n\nfunc NewDiskHintFromMap(val map[string]interface{}) DiskHint ", "output": "{\n\treturn DiskHint{val}\n}"} {"input": "package geth\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n\ntype Strings struct{ strs []string }\n\n\nfunc (s *Strings) Size() int {\n\treturn len(s.strs)\n}\n\n\nfunc (s *Strings) Get(index int) (str string, _ error) {\n\tif index < 0 || index >= len(s.strs) {\n\t\treturn \"\", errors.New(\"index out of bounds\")\n\t}\n\treturn s.strs[index], nil\n}\n\n\n\n\n\nfunc (s *Strings) String() string {\n\treturn fmt.Sprintf(\"%v\", s.strs)\n}\n\nfunc (s *Strings) Set(index int, str string) error ", "output": "{\n\tif index < 0 || index >= len(s.strs) {\n\t\treturn errors.New(\"index out of bounds\")\n\t}\n\ts.strs[index] = str\n\treturn nil\n}"} {"input": "package postgresql\n\nimport (\n\t\"sql\"\n)\n\ntype Connection struct {\n\thandle *pqConnection;\n}\n\nfunc (self *Connection) Query(sql string, params ...interface{}) (sql.ResultSet, sql.Error) {\n\tstmt, err := self.Prepare(sql)\n\tif err != nil {\n\t\treturn nil, err\t\n\t}\n\n\treturn stmt.Query(params...)\n}\n\nfunc (self *Connection) Execute(sql string, params ...interface{}) sql.Error {\n\tstmt, err := self.Prepare(sql)\n\tif err != nil {\n\t\treturn err\t\n\t}\n\n\tdefer stmt.Close()\n\treturn stmt.Execute(params...)\n}\n\nfunc (self *Connection) Prepare(query string) (sql.Statement, sql.Error) {\n\n\tstmt := new(Statement)\n\treturn stmt, nil\n}\n\n\n\nfunc (self *Connection) Close() sql.Error ", "output": "{\n\tself.handle.pqClose()\n\treturn nil\n}"} {"input": "package app\n\nimport (\n\t\"flag\"\n\n\t\"github.com/spf13/viper\"\n)\n\nconst (\n\tindexPrefix = \"index-prefix\"\n\tarchive = \"archive\"\n\tusername = \"es.username\"\n\tpassword = \"es.password\"\n\tuseILM = \"es.use-ilm\"\n\tilmPolicyName = \"es.ilm-policy-name\"\n\ttimeout = \"timeout\"\n)\n\n\ntype Config struct {\n\tIndexPrefix string\n\tArchive bool\n\tUsername string\n\tPassword string\n\tTLSEnabled bool\n\tILMPolicyName string\n\tUseILM bool\n\tTimeout int\n}\n\n\n\n\n\nfunc (c *Config) InitFromViper(v *viper.Viper) {\n\tc.IndexPrefix = v.GetString(indexPrefix)\n\tif c.IndexPrefix != \"\" {\n\t\tc.IndexPrefix += \"-\"\n\t}\n\tc.Archive = v.GetBool(archive)\n\tc.Username = v.GetString(username)\n\tc.Password = v.GetString(password)\n\tc.ILMPolicyName = v.GetString(ilmPolicyName)\n\tc.UseILM = v.GetBool(useILM)\n\tc.Timeout = v.GetInt(timeout)\n}\n\nfunc AddFlags(flags *flag.FlagSet) ", "output": "{\n\tflags.String(indexPrefix, \"\", \"Index prefix\")\n\tflags.Bool(archive, false, \"Handle archive indices\")\n\tflags.String(username, \"\", \"The username required by storage\")\n\tflags.String(password, \"\", \"The password required by storage\")\n\tflags.Bool(useILM, false, \"Use ILM to manage jaeger indices\")\n\tflags.String(ilmPolicyName, \"jaeger-ilm-policy\", \"The name of the ILM policy to use if ILM is active\")\n\tflags.Int(timeout, 120, \"Number of seconds to wait for master node response\")\n}"} {"input": "package telnetmgr\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"sync/atomic\"\n\n\t\"github.com/uol/logh\"\n\t\"github.com/uol/mycenae/lib/constants\"\n\n\t\"github.com/julienschmidt/httprouter\"\n)\n\n\n\n\n\n\n\nconst CountConnsURI string = \"node/connections\"\n\n\nconst HaltConnsURI string = \"node/halt/balancing\"\n\n\nconst HTTPHeaderTotalConnections string = \"X-Total-Connections\"\n\n\nfunc (manager *Manager) CountConnections(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n\tw.Header().Add(HTTPHeaderTotalConnections, fmt.Sprintf(\"%d\", atomic.LoadUint32(&manager.sharedConnectionCounter)))\n\tw.WriteHeader(http.StatusOK)\n\n\treturn\n}\n\nconst (\n\tcFuncHaltTelnetBalancingProcess string = \"HaltTelnetBalancingProcess\"\n)\n\n\n\n\nfunc (manager *Manager) HaltTelnetBalancingProcess(w http.ResponseWriter, r *http.Request, ps httprouter.Params) ", "output": "{\n\n\tif atomic.CompareAndSwapUint32(&manager.haltBalancingProcess, 0, 1) {\n\n\t\tif logh.InfoEnabled {\n\t\t\tmanager.logger.Info().Str(constants.StringsFunc, cFuncHaltTelnetBalancingProcess).Msg(\"halting the telnet connections balancing process\")\n\t\t}\n\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn\n\t}\n\n\tif logh.InfoEnabled {\n\t\tmanager.logger.Info().Str(constants.StringsFunc, cFuncHaltTelnetBalancingProcess).Msg(\"telnet connections balancing process is already halted\")\n\t}\n\n\tw.WriteHeader(http.StatusProcessing)\n\n\treturn\n}"} {"input": "package legacy\n\nimport (\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tutilruntime \"k8s.io/apimachinery/pkg/util/runtime\"\n\n\tuserv1 \"github.com/openshift/api/user/v1\"\n)\n\n\n\nfunc addUngroupifiedUserTypes(scheme *runtime.Scheme) error {\n\ttypes := []runtime.Object{\n\t\t&userv1.User{},\n\t\t&userv1.UserList{},\n\t\t&userv1.Identity{},\n\t\t&userv1.IdentityList{},\n\t\t&userv1.UserIdentityMapping{},\n\t\t&userv1.Group{},\n\t\t&userv1.GroupList{},\n\t}\n\tscheme.AddKnownTypes(GroupVersion, types...)\n\treturn nil\n}\n\nfunc InstallExternalLegacyUser(scheme *runtime.Scheme) ", "output": "{\n\tschemeBuilder := runtime.NewSchemeBuilder(\n\t\taddUngroupifiedUserTypes,\n\t\tcorev1.AddToScheme,\n\t)\n\tutilruntime.Must(schemeBuilder.AddToScheme(scheme))\n}"} {"input": "package fakes\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"code.google.com/p/go-uuid/uuid\"\n\t. \"github.com/mandarjog/leasedispenser/leasemanager\"\n)\n\ntype MemProvider struct {\n\tDB map[string]ProviderLeaseInfo\n}\n\nfunc NewMemProvider() LeaseProvider {\n\treturn MemProvider{\n\t\tDB: make(map[string]ProviderLeaseInfo),\n\t}\n}\n\nfunc (s MemProvider) Request(req ProviderLeaseRequest) (info ProviderLeaseInfo, err error) {\n\tproviderLeaseID := uuid.New()\n\tinfo.ProviderLeaseID = providerLeaseID\n\tinfo.StatusCode = LeaseStatusPending\n\tnewinfo := info\n\tnewinfo.StatusCode = LeaseStatusActive\n\tnewinfo.LeaseStartDate = time.Now().UnixNano()\n\tnewinfo.LeaseEndDate = newinfo.LeaseStartDate + req.Duration\n\ts.DB[providerLeaseID] = newinfo\n\treturn\n}\n\n\nfunc (s MemProvider) Info(providerLeaseID string) (info ProviderLeaseInfo, err error) ", "output": "{\n\tvar found bool\n\tif info, found = s.DB[providerLeaseID]; !found {\n\t\terr = errors.New(providerLeaseID + \" was not found\")\n\t}\n\treturn\n}"} {"input": "package help\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\ntype EvtPool struct {\n\theader DListNode\n}\n\n\n\nfunc (this *EvtPool) Eat(name string) {\n\tfmt.Printf(\"吃%s\\n\", name)\n}\n\nfunc (this *EvtPool) Post(d IEvent) bool {\n\n\tn := &DListNode{}\n\tn.Init(d)\n\n\tif !d.AddNode(n) {\n\t\treturn false\n\t}\n\n\told_pre := this.header.Pre\n\n\tthis.header.Pre = n\n\tn.Next = &this.header\n\tn.Pre = old_pre\n\told_pre.Next = n\n\n\treturn true\n}\n\nfunc (this *EvtPool) Run() {\n\tfor {\n\t\tif this.header.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\n\t\tn := this.header.Next\n\n\t\tn.Data.(IEvent).Exec(this)\n\n\t\tn.Data.(IEvent).Destroy()\n\t}\n}\n\ntype Evt_eat struct {\n\tEvt_base\n\tFoodName string\n}\n\nfunc (this *Evt_eat) Exec() bool {\n\treturn true\n}\n\nfunc TestDlist(t *testing.T) {\n\n\tvar g_Pool EvtPool\n\tg_Pool.Init()\n\n\tg_Pool.Post(&Evt_eat{FoodName: \"西瓜\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"葡萄\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"黄瓜\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"大蒜\"})\n\n\tg_Pool.Run()\n}\n\nfunc (this *EvtPool) Init() ", "output": "{\n\tthis.header.Init(nil)\n}"} {"input": "package opt\n\nimport (\n\t\"encoding/json\"\n\t\"reflect\"\n)\n\n\n\ntype DisableTypoToleranceOnAttributesOption struct {\n\tvalue []string\n}\n\n\n\n\n\nfunc (o *DisableTypoToleranceOnAttributesOption) Get() []string {\n\tif o == nil {\n\t\treturn []string{}\n\t}\n\treturn o.value\n}\n\n\n\nfunc (o DisableTypoToleranceOnAttributesOption) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(o.value)\n}\n\n\n\nfunc (o *DisableTypoToleranceOnAttributesOption) UnmarshalJSON(data []byte) error {\n\tif string(data) == \"null\" {\n\t\to.value = []string{}\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(data, &o.value)\n}\n\n\n\n\nfunc (o *DisableTypoToleranceOnAttributesOption) Equal(o2 *DisableTypoToleranceOnAttributesOption) bool {\n\tif o == nil {\n\t\treturn o2 == nil || reflect.DeepEqual(o2.value, []string{})\n\t}\n\tif o2 == nil {\n\t\treturn o == nil || reflect.DeepEqual(o.value, []string{})\n\t}\n\treturn reflect.DeepEqual(o.value, o2.value)\n}\n\n\n\n\nfunc DisableTypoToleranceOnAttributesEqual(o1, o2 *DisableTypoToleranceOnAttributesOption) bool {\n\treturn o1.Equal(o2)\n}\n\nfunc DisableTypoToleranceOnAttributes(v ...string) *DisableTypoToleranceOnAttributesOption ", "output": "{\n\treturn &DisableTypoToleranceOnAttributesOption{v}\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"bytes\"\n\n\t. \"github.com/bborbe/assert\"\n)\n\n\n\nfunc TestDo(t *testing.T) ", "output": "{\n\twriter := bytes.NewBufferString(\"\")\n\tinput := bytes.NewBufferString(\"\")\n\terr := do(writer, input)\n\terr = AssertThat(err, NilValue())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"strconv\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\ntype UpdateProfileRequest struct {\n\n\tAccountID *string `json:\"accountID\"`\n\n\tAdditionalInformation *string `json:\"additionalInformation,omitempty\"`\n\n\tAddresses []*Address `json:\"addresses\"`\n\n\tCompanyName *string `json:\"companyName,omitempty\"`\n\n\tDob *strfmt.DateTime `json:\"dob,omitempty\"`\n\n\tEmail *string `json:\"email,omitempty\"`\n\n\tFax *string `json:\"fax,omitempty\"`\n\n\tFirstName *string `json:\"firstName,omitempty\"`\n\n\tID string `json:\"id,omitempty\"`\n\n\tLandline *string `json:\"landline,omitempty\"`\n\n\tLastName *string `json:\"lastName,omitempty\"`\n\n\tLogoURL *string `json:\"logoURL,omitempty\"`\n\n\tMobile *string `json:\"mobile,omitempty\"`\n\n\tOrganizationID *string `json:\"organizationID,omitempty\"`\n\n\tVatNumber *string `json:\"vatNumber,omitempty\"`\n}\n\n\nfunc (m *UpdateProfileRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAddresses(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (m *UpdateProfileRequest) validateAccountID(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"accountID\", \"body\", m.AccountID); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (m *UpdateProfileRequest) validateAddresses(formats strfmt.Registry) error ", "output": "{\n\n\tif swag.IsZero(m.Addresses) { \n\t\treturn nil\n\t}\n\n\tfor i := 0; i < len(m.Addresses); i++ {\n\n\t\tif swag.IsZero(m.Addresses[i]) { \n\t\t\tcontinue\n\t\t}\n\n\t\tif m.Addresses[i] != nil {\n\n\t\t\tif err := m.Addresses[i].Validate(formats); err != nil {\n\t\t\t\tif ve, ok := err.(*errors.Validation); ok {\n\t\t\t\t\treturn ve.ValidateName(\"addresses\" + \".\" + strconv.Itoa(i))\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\n\n\nfunc huluculuYear(year int) bool { return year%15 == 0 }\n\nfunc bulukuluYear(year int) bool { return leapYear(year) && year%55 == 0 }\n\nfunc main() {\n\tin, _ := os.Open(\"10070.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"10070.out\")\n\tdefer out.Close()\n\n\tvar year int\n\tfor first := true; ; {\n\t\tif _, err := fmt.Fscanf(in, \"%d\", &year); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif first {\n\t\t\tfirst = false\n\t\t} else {\n\t\t\tfmt.Fprintln(out)\n\t\t}\n\t\tif leap, huluculu, bulukulu := leapYear(year), huluculuYear(year), bulukuluYear(year); !leap && !huluculu && !bulukulu {\n\t\t\tfmt.Fprintln(out, \"This is an ordinary year.\")\n\t\t} else {\n\t\t\tif leap {\n\t\t\t\tfmt.Fprintln(out, \"This is leap year.\")\n\t\t\t}\n\t\t\tif huluculu {\n\t\t\t\tfmt.Fprintln(out, \"This is huluculu festival year.\")\n\t\t\t}\n\t\t\tif bulukulu {\n\t\t\t\tfmt.Fprintln(out, \"This is bulukulu festival year.\")\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc leapYear(year int) bool ", "output": "{\n\tswitch {\n\tcase year%4 != 0:\n\t\treturn false\n\tcase year%400 == 0:\n\t\treturn true\n\tdefault:\n\t\treturn year%100 != 0\n\t}\n}"} {"input": "package mem\n\nimport (\n\t\"bytes\"\n\t\"sort\"\n\n\tsgmt \"github.com/m3db/m3/src/m3ninx/index/segment\"\n)\n\ntype bytesSliceIter struct {\n\terr error\n\tdone bool\n\n\tcurrentIdx int\n\tcurrent []byte\n\tbackingSlice [][]byte\n\topts Options\n}\n\nvar _ sgmt.FieldsIterator = &bytesSliceIter{}\n\nfunc newBytesSliceIter(slice [][]byte, opts Options) *bytesSliceIter {\n\tsortSliceOfByteSlices(slice)\n\treturn &bytesSliceIter{\n\t\tcurrentIdx: -1,\n\t\tbackingSlice: slice,\n\t\topts: opts,\n\t}\n}\n\nfunc (b *bytesSliceIter) Next() bool {\n\tif b.done || b.err != nil {\n\t\treturn false\n\t}\n\tb.currentIdx++\n\tif b.currentIdx >= len(b.backingSlice) {\n\t\tb.done = true\n\t\treturn false\n\t}\n\tb.current = b.backingSlice[b.currentIdx]\n\treturn true\n}\n\nfunc (b *bytesSliceIter) Current() []byte {\n\treturn b.current\n}\n\nfunc (b *bytesSliceIter) Err() error {\n\treturn nil\n}\n\nfunc (b *bytesSliceIter) Len() int {\n\treturn len(b.backingSlice)\n}\n\nfunc (b *bytesSliceIter) Close() error {\n\tb.current = nil\n\tb.opts.BytesSliceArrayPool().Put(b.backingSlice)\n\treturn nil\n}\n\n\n\nfunc sortSliceOfByteSlices(b [][]byte) ", "output": "{\n\tsort.Slice(b, func(i, j int) bool {\n\t\treturn bytes.Compare(b[i], b[j]) < 0\n\t})\n}"} {"input": "package events\n\nimport (\n\t\"fmt\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/klog\"\n)\n\ntype LoggingEventRecorder struct {\n\tcomponent string\n}\n\n\n\n\nfunc (r *LoggingEventRecorder) ComponentName() string {\n\treturn r.component\n}\n\nfunc (r *LoggingEventRecorder) ForComponent(component string) Recorder {\n\tnewRecorder := *r\n\tnewRecorder.component = component\n\treturn &newRecorder\n}\n\nfunc (r *LoggingEventRecorder) WithComponentSuffix(suffix string) Recorder {\n\treturn r.ForComponent(fmt.Sprintf(\"%s-%s\", r.ComponentName(), suffix))\n}\n\nfunc (r *LoggingEventRecorder) Event(reason, message string) {\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeNormal, reason, message)\n\tklog.Info(event.String())\n}\n\nfunc (r *LoggingEventRecorder) Eventf(reason, messageFmt string, args ...interface{}) {\n\tr.Event(reason, fmt.Sprintf(messageFmt, args...))\n}\n\nfunc (r *LoggingEventRecorder) Warning(reason, message string) {\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeWarning, reason, message)\n\tklog.Warning(event.String())\n}\n\nfunc (r *LoggingEventRecorder) Warningf(reason, messageFmt string, args ...interface{}) {\n\tr.Warning(reason, fmt.Sprintf(messageFmt, args...))\n}\n\nfunc NewLoggingEventRecorder(component string) Recorder ", "output": "{\n\treturn &LoggingEventRecorder{component: component}\n}"} {"input": "package elastic\n\n\n\n\n\n\n\n\n\ntype MissingAggregation struct {\n\tfield string\n\tsubAggregations map[string]Aggregation\n\tmeta map[string]interface{}\n}\n\n\n\nfunc (a *MissingAggregation) Field(field string) *MissingAggregation {\n\ta.field = field\n\treturn a\n}\n\nfunc (a *MissingAggregation) SubAggregation(name string, subAggregation Aggregation) *MissingAggregation {\n\ta.subAggregations[name] = subAggregation\n\treturn a\n}\n\n\nfunc (a *MissingAggregation) Meta(metaData map[string]interface{}) *MissingAggregation {\n\ta.meta = metaData\n\treturn a\n}\n\nfunc (a *MissingAggregation) Source() (interface{}, error) {\n\n\tsource := make(map[string]interface{})\n\topts := make(map[string]interface{})\n\tsource[\"missing\"] = opts\n\n\tif a.field != \"\" {\n\t\topts[\"field\"] = a.field\n\t}\n\n\tif len(a.subAggregations) > 0 {\n\t\taggsMap := make(map[string]interface{})\n\t\tsource[\"aggregations\"] = aggsMap\n\t\tfor name, aggregate := range a.subAggregations {\n\t\t\tsrc, err := aggregate.Source()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\taggsMap[name] = src\n\t\t}\n\t}\n\n\tif len(a.meta) > 0 {\n\t\tsource[\"meta\"] = a.meta\n\t}\n\n\treturn source, nil\n}\n\nfunc NewMissingAggregation() *MissingAggregation ", "output": "{\n\treturn &MissingAggregation{\n\t\tsubAggregations: make(map[string]Aggregation),\n\t}\n}"} {"input": "package timeconv\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestNow(t *testing.T) {\n\tnow := time.Now()\n\tts := Now()\n\tvar drift int64 = 5\n\tif ts.Seconds < int64(now.Second())-drift {\n\t\tt.Errorf(\"Unexpected time drift: %d\", ts.Seconds)\n\t}\n}\n\nfunc TestTimestamp(t *testing.T) {\n\tnow := time.Now()\n\tts := Timestamp(now)\n\n\tif now.Unix() != ts.Seconds {\n\t\tt.Errorf(\"Unexpected time drift: %d to %d\", now.Second(), ts.Seconds)\n\t}\n\n\tif now.Nanosecond() != int(ts.Nanos) {\n\t\tt.Errorf(\"Unexpected nano drift: %d to %d\", now.Nanosecond(), ts.Nanos)\n\t}\n}\n\n\n\nfunc TestFormat(t *testing.T) {\n\tnow := time.Now()\n\tnowts := Timestamp(now)\n\n\tif now.Format(time.ANSIC) != Format(nowts, time.ANSIC) {\n\t\tt.Error(\"Format mismatch\")\n\t}\n}\n\nfunc TestTime(t *testing.T) ", "output": "{\n\tnowts := Now()\n\tnow := Time(nowts)\n\n\tif now.Unix() != nowts.Seconds {\n\t\tt.Errorf(\"Unexpected time drift %d\", now.Unix())\n\t}\n}"} {"input": "package commands\n\nimport (\n\t\"github.com/limetext/lime/backend\"\n)\n\ntype (\n\tUndoCommand struct {\n\t\tbackend.BypassUndoCommand\n\t\thard bool\n\t}\n\tRedoCommand struct {\n\t\tbackend.BypassUndoCommand\n\t\thard bool\n\t}\n)\n\nfunc (c *UndoCommand) Run(v *backend.View, e *backend.Edit) error {\n\tv.UndoStack().Undo(c.hard)\n\treturn nil\n}\n\n\n\nfunc init() {\n\tregister([]cmd{\n\t\t{\"undo\", &UndoCommand{hard: true}},\n\t\t{\"redo\", &RedoCommand{hard: true}},\n\t\t{\"soft_undo\", &UndoCommand{}},\n\t\t{\"soft_redo\", &RedoCommand{}},\n\t})\n}\n\nfunc (c *RedoCommand) Run(v *backend.View, e *backend.Edit) error ", "output": "{\n\tv.UndoStack().Redo(c.hard)\n\treturn nil\n}"} {"input": "package v1\n\n\n\ntype EnvVarSourceApplyConfiguration struct {\n\tFieldRef *ObjectFieldSelectorApplyConfiguration `json:\"fieldRef,omitempty\"`\n\tResourceFieldRef *ResourceFieldSelectorApplyConfiguration `json:\"resourceFieldRef,omitempty\"`\n\tConfigMapKeyRef *ConfigMapKeySelectorApplyConfiguration `json:\"configMapKeyRef,omitempty\"`\n\tSecretKeyRef *SecretKeySelectorApplyConfiguration `json:\"secretKeyRef,omitempty\"`\n}\n\n\n\n\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithFieldRef(value *ObjectFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.FieldRef = value\n\treturn b\n}\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithResourceFieldRef(value *ResourceFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.ResourceFieldRef = value\n\treturn b\n}\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithConfigMapKeyRef(value *ConfigMapKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.ConfigMapKeyRef = value\n\treturn b\n}\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithSecretKeyRef(value *SecretKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.SecretKeyRef = value\n\treturn b\n}\n\nfunc EnvVarSource() *EnvVarSourceApplyConfiguration ", "output": "{\n\treturn &EnvVarSourceApplyConfiguration{}\n}"} {"input": "package no\n\nimport (\n\t\"github.com/blevesearch/bleve/analysis\"\n\t\"github.com/blevesearch/bleve/analysis/token_filters/stemmer_filter\"\n\t\"github.com/blevesearch/bleve/registry\"\n)\n\nconst StemmerName = \"stemmer_no\"\n\n\n\nfunc init() {\n\tregistry.RegisterTokenFilter(StemmerName, StemmerFilterConstructor)\n}\n\nfunc StemmerFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) ", "output": "{\n\treturn stemmer_filter.NewStemmerFilter(\"no\")\n}"} {"input": "package pagerduty\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/GoogleCloudPlatform/terraformer/terraformutils\"\n\tpagerduty \"github.com/heimweh/go-pagerduty/pagerduty\"\n)\n\ntype ScheduleGenerator struct {\n\tPagerDutyService\n}\n\n\n\nfunc (g *ScheduleGenerator) InitResources() error {\n\tclient, err := g.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfuncs := []func(*pagerduty.Client) error{\n\t\tg.createScheduleResources,\n\t}\n\n\tfor _, f := range funcs {\n\t\terr := f(client)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (g *ScheduleGenerator) createScheduleResources(client *pagerduty.Client) error ", "output": "{\n\tvar offset = 0\n\toptions := pagerduty.ListSchedulesOptions{}\n\tfor {\n\t\toptions.Offset = offset\n\t\tresp, _, err := client.Schedules.List(&options)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, schedule := range resp.Schedules {\n\t\t\tg.Resources = append(g.Resources, terraformutils.NewSimpleResource(\n\t\t\t\tschedule.ID,\n\t\t\t\tfmt.Sprintf(\"schedule_%s\", schedule.Name),\n\t\t\t\t\"pagerduty_schedule\",\n\t\t\t\tg.ProviderName,\n\t\t\t\t[]string{},\n\t\t\t))\n\t\t}\n\t\tif !resp.More {\n\t\t\tbreak\n\t\t}\n\n\t\toffset += resp.Limit\n\t}\n\n\treturn nil\n}"} {"input": "package server\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n)\n\ntype getFluxLinksResponse struct {\n\tAST string `json:\"ast\"`\n\tSelf string `json:\"self\"`\n\tSuggestions string `json:\"suggestions\"`\n}\n\ntype getConfigLinksResponse struct {\n\tSelf string `json:\"self\"` \n\tAuth string `json:\"auth\"` \n}\n\ntype getOrganizationConfigLinksResponse struct {\n\tSelf string `json:\"self\"` \n\tLogViewer string `json:\"logViewer\"` \n}\n\ntype getExternalLinksResponse struct {\n\tStatusFeed *string `json:\"statusFeed,omitempty\"` \n\tCustomLinks []CustomLink `json:\"custom,omitempty\"` \n}\n\n\ntype CustomLink struct {\n\tName string `json:\"name\"`\n\tURL string `json:\"url\"`\n}\n\n\n\n\n\nfunc NewCustomLinks(links map[string]string) ([]CustomLink, error) ", "output": "{\n\tcustomLinks := make([]CustomLink, 0, len(links))\n\tfor name, link := range links {\n\t\tif name == \"\" {\n\t\t\treturn nil, errors.New(\"customLink missing key for Name\")\n\t\t}\n\t\tif link == \"\" {\n\t\t\treturn nil, errors.New(\"customLink missing value for URL\")\n\t\t}\n\t\t_, err := url.Parse(link)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcustomLink := CustomLink{\n\t\t\tName: name,\n\t\t\tURL: link,\n\t\t}\n\t\tcustomLinks = append(customLinks, customLink)\n\t}\n\n\treturn customLinks, nil\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"github.com/justmao945/quictun\"\n\t\"log\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\nfunc main() {\n\tvar flagAddr, flagTarget string\n\tvar flagMaxConns int\n\n\tlog.SetFlags(log.Lshortfile | log.LstdFlags)\n\tflag.StringVar(&flagAddr, \"addr\", \"127.0.0.1:1082\", \"server listen address\")\n\tflag.StringVar(&flagTarget, \"target\", \"tls-server-domain.com:2233\", \"quictun server address\")\n\tflag.IntVar(&flagMaxConns, \"conns\", 8, \"max concurrent connections to server (up to 100 streams/conn)\")\n\tflag.Parse()\n\n\tlistener, err := net.Listen(\"tcp\", flagAddr)\n\tif err != nil {\n\t\tlog.Fatalf(\"listen failed: %v\\n\", err)\n\t}\n\n\tclient := newClient(flagTarget, flagMaxConns)\n\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"accept failed: %v\\n\", err)\n\t\t\tif nerr, ok := err.(net.Error); ok && nerr.Temporary() {\n\t\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn \n\t\t}\n\t\tgo handleConn(conn, client)\n\t}\n}\n\nfunc handleConn(conn net.Conn, client *Client) ", "output": "{\n\tdefer conn.Close()\n\n\tsession, err := client.getSession()\n\tif err != nil {\n\t\tlog.Printf(\"dial server failed: %v\\n\", err)\n\t\treturn\n\t}\n\n\tstream, err := session.OpenStreamSync()\n\tif err != nil {\n\t\tlog.Printf(\"open stream failed: %v\\n\", err)\n\t\tsession.Close(err)\n\t\treturn\n\t}\n\n\ttargetConn := quictun.NewStreamConn(session, stream)\n\tquictun.Proxy(conn, targetConn)\n}"} {"input": "package main\n\nimport \"errors\"\n\n\n\ntype Item struct {\n\tId int\n\tPath string\n}\n\ntype Status struct {\n\tStatus string\n\tList []Item\n\tId int\n}\n\nconst (\n\tStateStopped = iota\n\tStatePlaying\n)\n\n\n\nvar items []Item\nvar nextId int\nvar currentTrack int\nvar currentState int\n\n\n\n\n\nfunc itemIndex(id int) (i int, err error) {\n\tfor i = 0; i < len(items); i++ {\n\t\tif items[i].Id == id {\n\t\t\treturn\n\t\t}\n\t}\n\terr = errors.New(\"no item with that id found\")\n\treturn\n}\n\nfunc removeItem(id int) (err error) {\n\ti, err := itemIndex(id)\n\tif err != nil {\n\t\treturn\n\t}\n\titems = append(items[:i], items[i+1:]...)\n\treturn\n}\n\nfunc initialize() {\n\titems = []Item{}\n\tnextId = 1\n\tcurrentTrack = 0\n\tcurrentState = StateStopped\n}\n\nfunc addItem(path string) (id int) ", "output": "{\n\tid = nextId\n\titems = append(items, Item{Id: nextId, Path: path})\n\tnextId = nextId + 1\n\treturn\n}"} {"input": "package chrootarchive\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"github.com/docker/docker/pkg/reexec\"\n)\n\nfunc init() {\n\treexec.Register(\"docker-applyLayer\", applyLayer)\n\treexec.Register(\"docker-untar\", untar)\n}\n\n\n\n\n\nfunc flush(r io.Reader) {\n\tio.Copy(ioutil.Discard, r)\n}\n\nfunc fatal(err error) ", "output": "{\n\tfmt.Fprint(os.Stderr, err)\n\tos.Exit(1)\n}"} {"input": "package mgokv_test\n\nimport (\n\t\"testing\"\n\n\tjujutesting \"github.com/juju/testing\"\n)\n\n\n\nfunc TestPackage(t *testing.T) ", "output": "{\n\tjujutesting.MgoTestPackage(t, nil)\n}"} {"input": "package block\n\nimport (\n\t\"github.com/juju/cmd\"\n\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/cmd/envcmd\"\n)\n\nvar (\n\tBlockClient = &getBlockClientAPI\n\tUnblockClient = &getUnblockClientAPI\n\tListClient = &getBlockListAPI\n\n\tNewDestroyCommand = newDestroyCommand\n\tNewRemoveCommand = newRemoveCommand\n\tNewChangeCommand = newChangeCommand\n\tNewListCommand = newListCommand\n)\n\ntype MockBlockClient struct {\n\tBlockType string\n\tMsg string\n}\n\nfunc (c *MockBlockClient) Close() error {\n\treturn nil\n}\n\nfunc (c *MockBlockClient) SwitchBlockOn(blockType, msg string) error {\n\tc.BlockType = blockType\n\tc.Msg = msg\n\treturn nil\n}\n\n\n\nfunc (c *MockBlockClient) List() ([]params.Block, error) {\n\tif c.BlockType == \"\" {\n\t\treturn []params.Block{}, nil\n\t}\n\n\treturn []params.Block{\n\t\tparams.Block{\n\t\t\tType: c.BlockType,\n\t\t\tMessage: c.Msg,\n\t\t},\n\t}, nil\n}\n\nfunc NewUnblockCommandWithClient(client UnblockClientAPI) cmd.Command {\n\treturn envcmd.Wrap(&unblockCommand{client: client})\n}\n\nfunc (c *MockBlockClient) SwitchBlockOff(blockType string) error ", "output": "{\n\tc.BlockType = blockType\n\tc.Msg = \"\"\n\treturn nil\n}"} {"input": "package sftp\n\n\n\n\nimport \"os\"\n\n\n\ntype FileOpenFlags struct {\n\tRead, Write, Append, Creat, Trunc, Excl bool\n}\n\nfunc newFileOpenFlags(flags uint32) FileOpenFlags {\n\treturn FileOpenFlags{\n\t\tRead: flags&ssh_FXF_READ != 0,\n\t\tWrite: flags&ssh_FXF_WRITE != 0,\n\t\tAppend: flags&ssh_FXF_APPEND != 0,\n\t\tCreat: flags&ssh_FXF_CREAT != 0,\n\t\tTrunc: flags&ssh_FXF_TRUNC != 0,\n\t\tExcl: flags&ssh_FXF_EXCL != 0,\n\t}\n}\n\n\n\nfunc (r *Request) Pflags() FileOpenFlags {\n\treturn newFileOpenFlags(r.Flags)\n}\n\n\n\n\ntype FileAttrFlags struct {\n\tSize, UidGid, Permissions, Acmodtime bool\n}\n\nfunc newFileAttrFlags(flags uint32) FileAttrFlags {\n\treturn FileAttrFlags{\n\t\tSize: (flags & ssh_FILEXFER_ATTR_SIZE) != 0,\n\t\tUidGid: (flags & ssh_FILEXFER_ATTR_UIDGID) != 0,\n\t\tPermissions: (flags & ssh_FILEXFER_ATTR_PERMISSIONS) != 0,\n\t\tAcmodtime: (flags & ssh_FILEXFER_ATTR_ACMODTIME) != 0,\n\t}\n}\n\n\n\nfunc (r *Request) AttrFlags() FileAttrFlags {\n\treturn newFileAttrFlags(r.Flags)\n}\n\n\n\n\n\n\nfunc (r *Request) Attributes() *FileStat {\n\tfs, _ := getFileStat(r.Flags, r.Attrs)\n\treturn fs\n}\n\nfunc (a FileStat) FileMode() os.FileMode ", "output": "{\n\treturn os.FileMode(a.Mode)\n}"} {"input": "package jwt\n\nimport (\n\t\"crypto/rsa\"\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/SermoDigital/jose/crypto\"\n\t\"github.com/SermoDigital/jose/jws\"\n\t\"github.com/nicholasjackson/building-microservices-in-go/chapter8/utils\"\n)\n\nvar rsaPrivate *rsa.PrivateKey\nvar rsaPublic *rsa.PublicKey\n\n\n\n\nfunc GenerateJWT() []byte {\n\tclaims := jws.Claims{}\n\tclaims.SetExpiration(time.Now().Add(2880 * time.Minute))\n\tclaims.Set(\"userID\", \"abcsd232jfjf\")\n\tclaims.Set(\"accessLevel\", \"user\")\n\n\tjwt := jws.NewJWT(claims, crypto.SigningMethodRS256)\n\n\tb, _ := jwt.Serialize(rsaPrivate)\n\n\treturn b\n}\n\n\n\nfunc ValidateJWT(token []byte) error {\n\tjwt, err := jws.ParseJWT(token)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to parse token: %v\", err)\n\t}\n\n\tif err = jwt.Validate(rsaPublic, crypto.SigningMethodRS256); err != nil {\n\t\treturn fmt.Errorf(\"Unable to validate token: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tvar err error\n\trsaPrivate, err = utils.UnmarshalRSAPrivateKeyFromFile(\"../keys/sample_key.priv\")\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to parse private key\", err)\n\t}\n\n\trsaPublic, err = utils.UnmarshalRSAPublicKeyFromFile(\"../keys/sample_key.pub\")\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to parse public key\", err)\n\t}\n}"} {"input": "package term\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc IsANSI(f *os.File) bool {\n\treturn IsTerminal(f)\n}\n\n\nfunc IsTerminal(f *os.File) bool {\n\tcmd := exec.Command(\"test\", \"-t\", \"0\")\n\tcmd.Stdin = f\n\treturn cmd.Run() == nil\n}\n\nfunc MakeRaw(f *os.File) error {\n\treturn stty(f, \"-icanon\", \"-echo\").Run()\n}\n\nfunc Restore(f *os.File) error {\n\treturn stty(f, \"icanon\", \"echo\").Run()\n}\n\nfunc Cols() (int, error) {\n\tcols, err := tput(\"cols\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}\n\nfunc Lines() (int, error) {\n\tcols, err := tput(\"lines\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}\n\n\n\nfunc stty(f *os.File, args ...string) *exec.Cmd {\n\tc := exec.Command(\"stty\", args...)\n\tc.Stdin = f\n\treturn c\n}\n\n\n\nfunc tput(what string) (string, error) ", "output": "{\n\tc := exec.Command(\"tput\", what)\n\tc.Stderr = os.Stderr\n\tout, err := c.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.TrimSpace(string(out)), nil\n}"} {"input": "package schedulercache\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/labels\"\n\t\"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache\"\n)\n\n\ntype FakeCache struct {\n\tAssumeFunc func(*api.Pod)\n}\n\nfunc (f *FakeCache) AssumePod(pod *api.Pod) error {\n\tf.AssumeFunc(pod)\n\treturn nil\n}\n\nfunc (f *FakeCache) AddPod(pod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) UpdatePod(oldPod, newPod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) RemovePod(pod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) AddNode(node *api.Node) error { return nil }\n\n\n\nfunc (f *FakeCache) RemoveNode(node *api.Node) error { return nil }\n\nfunc (f *FakeCache) UpdateNodeNameToInfoMap(infoMap map[string]*schedulercache.NodeInfo) error {\n\treturn nil\n}\n\nfunc (f *FakeCache) List(s labels.Selector) ([]*api.Pod, error) { return nil, nil }\n\nfunc (f *FakeCache) UpdateNode(oldNode, newNode *api.Node) error ", "output": "{ return nil }"} {"input": "package stores\n\nimport \"jvmgo/ch06/instructions/base\"\nimport \"jvmgo/ch06/rtda\"\n\n\ntype ISTORE struct{ base.Index8Instruction }\n\nfunc (self *ISTORE) Execute(frame *rtda.Frame) {\n\t_istore(frame, uint(self.Index))\n}\n\ntype ISTORE_0 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_0) Execute(frame *rtda.Frame) {\n\t_istore(frame, 0)\n}\n\ntype ISTORE_1 struct{ base.NoOperandsInstruction }\n\n\n\ntype ISTORE_2 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_2) Execute(frame *rtda.Frame) {\n\t_istore(frame, 2)\n}\n\ntype ISTORE_3 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_3) Execute(frame *rtda.Frame) {\n\t_istore(frame, 3)\n}\n\nfunc _istore(frame *rtda.Frame, index uint) {\n\tval := frame.OperandStack().PopInt()\n\tframe.LocalVars().SetInt(index, val)\n}\n\nfunc (self *ISTORE_1) Execute(frame *rtda.Frame) ", "output": "{\n\t_istore(frame, 1)\n}"} {"input": "package datatype\n\nimport \"fmt\"\n\n\ntype OctetString string\n\n\nfunc DecodeOctetString(b []byte) (Type, error) {\n\treturn OctetString(b), nil\n}\n\n\nfunc (s OctetString) Serialize() []byte {\n\treturn []byte(s)\n}\n\n\nfunc (s OctetString) Len() int {\n\treturn len(s)\n}\n\n\nfunc (s OctetString) Padding() int {\n\tl := len(s)\n\treturn pad4(l) - l\n}\n\n\n\n\n\nfunc (s OctetString) String() string {\n\treturn fmt.Sprintf(\"OctetString{%#x},Padding:%d\", string(s), s.Padding())\n}\n\nfunc (s OctetString) Type() TypeID ", "output": "{\n\treturn OctetStringType\n}"} {"input": "package leveldb\n\nimport (\n\t\"github.com/pingcap/goleveldb/leveldb/comparer\"\n)\n\ntype iComparer struct {\n\tucmp comparer.Comparer\n}\n\nfunc (icmp *iComparer) uName() string {\n\treturn icmp.ucmp.Name()\n}\n\nfunc (icmp *iComparer) uCompare(a, b []byte) int {\n\treturn icmp.ucmp.Compare(a, b)\n}\n\nfunc (icmp *iComparer) uSeparator(dst, a, b []byte) []byte {\n\treturn icmp.ucmp.Separator(dst, a, b)\n}\n\nfunc (icmp *iComparer) uSuccessor(dst, b []byte) []byte {\n\treturn icmp.ucmp.Successor(dst, b)\n}\n\nfunc (icmp *iComparer) Name() string {\n\treturn icmp.uName()\n}\n\nfunc (icmp *iComparer) Compare(a, b []byte) int {\n\tx := icmp.uCompare(internalKey(a).ukey(), internalKey(b).ukey())\n\tif x == 0 {\n\t\tif m, n := internalKey(a).num(), internalKey(b).num(); m > n {\n\t\t\treturn -1\n\t\t} else if m < n {\n\t\t\treturn 1\n\t\t}\n\t}\n\treturn x\n}\n\n\n\nfunc (icmp *iComparer) Successor(dst, b []byte) []byte {\n\tub := internalKey(b).ukey()\n\tdst = icmp.uSuccessor(dst, ub)\n\tif dst != nil && len(dst) < len(ub) && icmp.uCompare(ub, dst) < 0 {\n\t\treturn append(dst, keyMaxNumBytes...)\n\t}\n\treturn nil\n}\n\nfunc (icmp *iComparer) Separator(dst, a, b []byte) []byte ", "output": "{\n\tua, ub := internalKey(a).ukey(), internalKey(b).ukey()\n\tdst = icmp.uSeparator(dst, ua, ub)\n\tif dst != nil && len(dst) < len(ua) && icmp.uCompare(ua, dst) < 0 {\n\t\treturn append(dst, keyMaxNumBytes...)\n\t}\n\treturn nil\n}"} {"input": "package stack\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/appcelerator/amp/docker/cli/cli/command/bundlefile\"\n\t\"github.com/pkg/errors\"\n\t\"github.com/spf13/pflag\"\n)\n\nfunc addComposefileFlag(opt *string, flags *pflag.FlagSet) {\n\tflags.StringVarP(opt, \"compose-file\", \"c\", \"\", \"Path to a Compose file\")\n\tflags.SetAnnotation(\"compose-file\", \"version\", []string{\"1.25\"})\n}\n\nfunc addBundlefileFlag(opt *string, flags *pflag.FlagSet) {\n\tflags.StringVar(opt, \"bundle-file\", \"\", \"Path to a Distributed Application Bundle file\")\n\tflags.SetAnnotation(\"bundle-file\", \"experimental\", nil)\n}\n\nfunc addRegistryAuthFlag(opt *bool, flags *pflag.FlagSet) {\n\tflags.BoolVar(opt, \"with-registry-auth\", false, \"Send registry authentication details to Swarm agents\")\n}\n\n\n\nfunc loadBundlefile(stderr io.Writer, namespace string, path string) (*bundlefile.Bundlefile, error) ", "output": "{\n\tdefaultPath := fmt.Sprintf(\"%s.dab\", namespace)\n\n\tif path == \"\" {\n\t\tpath = defaultPath\n\t}\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn nil, errors.Errorf(\n\t\t\t\"Bundle %s not found. Specify the path with --file\",\n\t\t\tpath)\n\t}\n\n\tfmt.Fprintf(stderr, \"Loading bundle from %s\\n\", path)\n\treader, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer reader.Close()\n\n\tbundle, err := bundlefile.LoadFile(reader)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"Error reading %s: %v\\n\", path, err)\n\t}\n\treturn bundle, err\n}"} {"input": "package migrations\n\nimport (\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"code.cloudfoundry.org/bbs/migration\"\n)\n\nvar migrationsRegistry = migration.Migrations{}\n\nfunc appendMigration(migrationTemplate migration.Migration) {\n\tmigrationsRegistry = append(migrationsRegistry, migrationTemplate)\n}\n\n\n\nfunc AllMigrations() migration.Migrations {\n\tmigs := make(migration.Migrations, len(migrationsRegistry))\n\tfor i, mig := range migrationsRegistry {\n\t\trt := reflect.TypeOf(mig)\n\t\tif rt.Kind() == reflect.Ptr {\n\t\t\trt = rt.Elem()\n\t\t}\n\t\tmigs[i] = reflect.New(rt).Interface().(migration.Migration)\n\t}\n\treturn migs\n}\n\nfunc migrationString(m migration.Migration) string ", "output": "{\n\t_, filename, _, ok := runtime.Caller(1)\n\tif !ok {\n\t\treturn strconv.FormatInt(m.Version(), 10)\n\t}\n\treturn strings.Split(filepath.Base(filename), \".\")[0]\n}"} {"input": "package echo\n\ntype (\n\tGroup struct {\n\t\techo Echo\n\t}\n)\n\nfunc (g *Group) Use(m ...Middleware) {\n\tfor _, h := range m {\n\t\tg.echo.middleware = append(g.echo.middleware, wrapMiddleware(h))\n\t}\n}\n\nfunc (g *Group) Connect(path string, h Handler) {\n\tg.echo.Connect(path, h)\n}\n\nfunc (g *Group) Delete(path string, h Handler) {\n\tg.echo.Delete(path, h)\n}\n\nfunc (g *Group) Get(path string, h Handler) {\n\tg.echo.Get(path, h)\n}\n\nfunc (g *Group) Head(path string, h Handler) {\n\tg.echo.Head(path, h)\n}\n\nfunc (g *Group) Options(path string, h Handler) {\n\tg.echo.Options(path, h)\n}\n\nfunc (g *Group) Patch(path string, h Handler) {\n\tg.echo.Patch(path, h)\n}\n\nfunc (g *Group) Post(path string, h Handler) {\n\tg.echo.Post(path, h)\n}\n\nfunc (g *Group) Put(path string, h Handler) {\n\tg.echo.Put(path, h)\n}\n\nfunc (g *Group) Trace(path string, h Handler) {\n\tg.echo.Trace(path, h)\n}\n\nfunc (g *Group) WebSocket(path string, h HandlerFunc) {\n\tg.echo.WebSocket(path, h)\n}\n\nfunc (g *Group) Static(path, root string) {\n\tg.echo.Static(path, root)\n}\n\nfunc (g *Group) ServeDir(path, root string) {\n\tg.echo.ServeDir(path, root)\n}\n\nfunc (g *Group) ServeFile(path, file string) {\n\tg.echo.ServeFile(path, file)\n}\n\n\n\nfunc (g *Group) Group(prefix string, m ...Middleware) *Group ", "output": "{\n\treturn g.echo.Group(prefix, m...)\n}"} {"input": "package builtin\n\nconst processControlSummary = `allows controlling other processes`\n\nconst processControlConnectedPlugAppArmor = `\n# Description: This interface allows for controlling other processes via\n# signals and nice. This is reserved because it grants privileged access to\n# all processes under root or processes running under the same UID otherwise.\n\n# /{,usr/}bin/nice is already in default policy, so just allow renice here\n/{,usr/}bin/renice ixr,\n\ncapability sys_resource,\ncapability sys_nice,\n\nsignal,\n`\n\nconst processControlConnectedPlugSecComp = `\n# Description: This interface allows for controlling other processes via\n# signals and nice. This is reserved because it grants privileged access to\n# all processes under root or processes running under the same UID otherwise.\n\n# Allow setting the nice value/priority for any process\nnice\nsetpriority\nsched_setaffinity\nsched_setparam\nsched_setscheduler\n`\n\n\n\nfunc init() ", "output": "{\n\tregisterIface(&commonInterface{\n\t\tname: \"process-control\",\n\t\tsummary: processControlSummary,\n\t\timplicitOnCore: true,\n\t\timplicitOnClassic: true,\n\t\tconnectedPlugAppArmor: processControlConnectedPlugAppArmor,\n\t\tconnectedPlugSecComp: processControlConnectedPlugSecComp,\n\t\treservedForOS: true,\n\t})\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\ntype StepDownCommand struct {\n\tMeta\n}\n\n\n\nfunc (c *StepDownCommand) Synopsis() string {\n\treturn \"Force the Vault node to give up active duty\"\n}\n\nfunc (c *StepDownCommand) Help() string {\n\thelpText := `\nUsage: vault step-down [options]\n\n Force the Vault node to step down from active duty.\n\n This causes the indicated node to give up active status. Note that while the\n affected node will have a short delay before attempting to grab the lock\n again, if no other node grabs the lock beforehand, it is possible for the\n same node to re-grab the lock and become active again.\n\nGeneral Options:\n\n ` + generalOptionsUsage()\n\treturn strings.TrimSpace(helpText)\n}\n\nfunc (c *StepDownCommand) Run(args []string) int ", "output": "{\n\tflags := c.Meta.FlagSet(\"step-down\", FlagSetDefault)\n\tflags.Usage = func() { c.Ui.Error(c.Help()) }\n\tif err := flags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tclient, err := c.Client()\n\tif err != nil {\n\t\tc.Ui.Error(fmt.Sprintf(\n\t\t\t\"Error initializing client: %s\", err))\n\t\treturn 2\n\t}\n\n\tif err := client.Sys().StepDown(); err != nil {\n\t\tc.Ui.Error(fmt.Sprintf(\"Error stepping down: %s\", err))\n\t\treturn 1\n\t}\n\n\treturn 0\n}"} {"input": "package clearbit\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n\n\ntype apiError struct {\n\tErrors []ErrorDetail `json:\"error\"`\n}\n\n\ntype ErrorDetail struct {\n\tType string `json:\"type\"`\n\tMessage string `json:\"message\"`\n}\n\n\ntype ErrorDetailWrapper struct {\n\tError ErrorDetail `json:\"error\"`\n}\n\n\nfunc (e apiError) Error() string {\n\tif len(e.Errors) > 0 {\n\t\terr := e.Errors[0]\n\t\treturn fmt.Sprintf(\"clearbit: %s %v\", err.Type, err.Message)\n\t}\n\treturn \"\"\n}\n\n\n\n\n\nfunc (e *apiError) UnmarshalJSON(b []byte) (err error) {\n\terrorDetail, errors := ErrorDetailWrapper{}, []ErrorDetail{}\n\tif err = json.Unmarshal(b, &errors); err == nil {\n\t\te.Errors = errors\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(b, &errorDetail); err == nil {\n\t\terrors = append(errors, errorDetail.Error)\n\t\te.Errors = errors\n\t\treturn\n\t}\n\n\treturn err\n}\n\n\n\n\n\n\n\n\nfunc relevantError(httpError error, ae apiError) error {\n\tif httpError != nil {\n\t\treturn httpError\n\t}\n\tif ae.Empty() {\n\t\treturn nil\n\t}\n\treturn ae\n}\n\nfunc (e *apiError) Empty() bool ", "output": "{\n\treturn len(e.Errors) == 0\n}"} {"input": "package testclient\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\tclientgotesting \"k8s.io/client-go/testing\"\n\n\tuserapi \"github.com/openshift/origin/pkg/user/apis/user\"\n)\n\n\n\ntype FakeIdentities struct {\n\tFake *Fake\n}\n\nvar identitiesResource = schema.GroupVersionResource{Group: \"\", Version: \"\", Resource: \"identities\"}\n\nfunc (c *FakeIdentities) Get(name string, options metav1.GetOptions) (*userapi.Identity, error) {\n\tobj, err := c.Fake.Invokes(clientgotesting.NewRootGetAction(identitiesResource, name), &userapi.Identity{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*userapi.Identity), err\n}\n\nfunc (c *FakeIdentities) List(opts metav1.ListOptions) (*userapi.IdentityList, error) {\n\tobj, err := c.Fake.Invokes(clientgotesting.NewRootListAction(identitiesResource, opts), &userapi.IdentityList{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*userapi.IdentityList), err\n}\n\nfunc (c *FakeIdentities) Create(inObj *userapi.Identity) (*userapi.Identity, error) {\n\tobj, err := c.Fake.Invokes(clientgotesting.NewRootCreateAction(identitiesResource, inObj), inObj)\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*userapi.Identity), err\n}\n\n\n\nfunc (c *FakeIdentities) Delete(name string) error {\n\t_, err := c.Fake.Invokes(clientgotesting.NewRootDeleteAction(identitiesResource, name), nil)\n\treturn err\n}\n\nfunc (c *FakeIdentities) Update(inObj *userapi.Identity) (*userapi.Identity, error) ", "output": "{\n\tobj, err := c.Fake.Invokes(clientgotesting.NewRootUpdateAction(identitiesResource, inObj), inObj)\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*userapi.Identity), err\n}"} {"input": "package bot\n\nimport \"strconv\"\n\nfunc _() {\n\tvar x [1]struct{}\n\t_ = x[flavorSpawn-0]\n\t_ = x[flavorAdd-1]\n\t_ = x[flavorFinal-2]\n\t_ = x[flavorFail-3]\n}\n\nconst _pipeAddFlavor_name = \"flavorSpawnflavorAddflavorFinalflavorFail\"\n\nvar _pipeAddFlavor_index = [...]uint8{0, 11, 20, 31, 41}\n\n\n\nfunc (i pipeAddFlavor) String() string ", "output": "{\n\tif i < 0 || i >= pipeAddFlavor(len(_pipeAddFlavor_index)-1) {\n\t\treturn \"pipeAddFlavor(\" + strconv.FormatInt(int64(i), 10) + \")\"\n\t}\n\treturn _pipeAddFlavor_name[_pipeAddFlavor_index[i]:_pipeAddFlavor_index[i+1]]\n}"} {"input": "package simpleacl\n\nimport \"github.com/youtube/vitess/go/vt/tableacl/acl\"\n\nvar allAcl SimpleAcl\n\nconst all = \"*\"\n\n\ntype SimpleAcl map[string]bool\n\n\nfunc (sacl SimpleAcl) IsMember(principal string) bool {\n\treturn sacl[principal] || sacl[all]\n}\n\n\ntype Factory struct{}\n\n\nfunc (factory *Factory) New(entries []string) (acl.ACL, error) {\n\tacl := SimpleAcl(map[string]bool{})\n\tfor _, e := range entries {\n\t\tacl[e] = true\n\t}\n\treturn acl, nil\n}\n\n\n\n\n\nfunc (factory *Factory) AllString() string {\n\treturn all\n}\n\n\nvar _ (acl.ACL) = (*SimpleAcl)(nil)\n\n\nvar _ (acl.Factory) = (*Factory)(nil)\n\nfunc (factory *Factory) All() acl.ACL ", "output": "{\n\tif allAcl == nil {\n\t\tallAcl = SimpleAcl(map[string]bool{all: true})\n\t}\n\treturn allAcl\n}"} {"input": "package geom\n\nimport (\n\t\"github.com/gmacd/rays/core\"\n)\n\n\n\n\ntype Light interface {\n\tIsLight() bool\n\tSetIsLight(isLight bool)\n\tLightCentre() core.Vec3\n}\n\ntype LightData struct {\n\tisLight bool\n\tpos core.Vec3\n}\n\nfunc NewLightData(pos core.Vec3) *LightData {\n\treturn &LightData{false, pos}\n}\n\nfunc NewLightDataNone() *LightData {\n\treturn &LightData{false, core.NewVec3Zero()}\n}\n\nfunc (light *LightData) IsLight() bool {\n\treturn light.isLight\n}\n\n\n\nfunc (light *LightData) LightCentre() core.Vec3 {\n\treturn light.pos\n}\n\nfunc (light *LightData) SetIsLight(isLight bool) ", "output": "{\n\tlight.isLight = isLight\n}"} {"input": "package reporters\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/onsi/ginkgo/config\"\n\t\"github.com/onsi/ginkgo/types\"\n\t\"k8s.io/klog/v2\"\n)\n\n\n\n\ntype DetailsReporter struct {\n\tWriter io.Writer\n}\n\n\n\nfunc NewDetailsReporterWithWriter(w io.Writer) *DetailsReporter {\n\treturn &DetailsReporter{\n\t\tWriter: w,\n\t}\n}\n\n\n\n\n\n\nfunc (reporter *DetailsReporter) SpecSuiteWillBegin(cfg config.GinkgoConfigType, summary *types.SuiteSummary) {\n}\n\n\nfunc (reporter *DetailsReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) {}\n\n\nfunc (reporter *DetailsReporter) SpecDidComplete(specSummary *types.SpecSummary) {\n\tb, err := json.Marshal(specSummary)\n\tif err != nil {\n\t\tklog.Errorf(\"Error in detail reporter: %v\", err)\n\t\treturn\n\t}\n\t_, err = reporter.Writer.Write(b)\n\tif err != nil {\n\t\tklog.Errorf(\"Error saving test details in detail reporter: %v\", err)\n\t\treturn\n\t}\n\t_, err = fmt.Fprintln(reporter.Writer, \"\")\n\tif err != nil {\n\t\tklog.Errorf(\"Error saving test details in detail reporter: %v\", err)\n\t\treturn\n\t}\n}\n\n\nfunc (reporter *DetailsReporter) SpecWillRun(specSummary *types.SpecSummary) {}\n\n\nfunc (reporter *DetailsReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) {}\n\n\nfunc (reporter *DetailsReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) {\n\tif c, ok := reporter.Writer.(io.Closer); ok {\n\t\tc.Close()\n\t}\n}\n\nfunc NewDetailsReporterFile(filename string) *DetailsReporter ", "output": "{\n\tabsPath, err := filepath.Abs(filename)\n\tif err != nil {\n\t\tklog.Errorf(\"%#v\\n\", err)\n\t\tpanic(err)\n\t}\n\tf, err := os.Create(absPath)\n\tif err != nil {\n\t\tklog.Errorf(\"%#v\\n\", err)\n\t\tpanic(err)\n\t}\n\treturn NewDetailsReporterWithWriter(f)\n}"} {"input": "package server\n\nimport (\n\t\"sync/atomic\"\n\n\t\"github.com/berkaroad/saashard/admin\"\n\t\"github.com/berkaroad/saashard/config\"\n\t\"github.com/berkaroad/saashard/proxy\"\n)\n\nconst (\n\tOffline = iota\n\tOnline\n\tUnknown\n)\n\n\ntype Server struct {\n\tcfg *config.Config\n\n\tstatusIndex int32\n\tstatus [2]int32\n\trunning bool\n\n\tproxy *proxy.Server\n\tadmin *admin.Server\n}\n\n\n\n\n\nfunc (s *Server) Run() {\n\ts.running = true\n\n\tgo s.proxy.Run()\n\n\ts.admin.Run()\n}\n\n\nfunc (s *Server) Status() string {\n\tvar status string\n\tswitch s.status[s.statusIndex] {\n\tcase Online:\n\t\tstatus = \"online\"\n\tcase Offline:\n\t\tstatus = \"offline\"\n\tcase Unknown:\n\t\tstatus = \"unknown\"\n\tdefault:\n\t\tstatus = \"unknown\"\n\t}\n\treturn status\n}\n\n\nfunc (s *Server) Close() {\n\ts.running = false\n\ts.proxy.Close()\n\ts.admin.Close()\n}\n\nfunc NewServer(cfg *config.Config) (*Server, error) ", "output": "{\n\tvar err error\n\ts := new(Server)\n\ts.cfg = cfg\n\n\tatomic.StoreInt32(&s.statusIndex, 0)\n\ts.status[s.statusIndex] = Online\n\n\ts.proxy, err = proxy.NewServer(cfg)\n\ts.admin, err = admin.NewServer(cfg)\n\treturn s, err\n}"} {"input": "package model\n\ntype Interface interface {\n\tVisitString(name string, resume func())\n\tVisitInt(name string, resume func())\n\tVisitFloat(name string, resume func())\n\tVisitBool(name string, resume func())\n\tVisitPtr(name string, resume func())\n\tVisitBytes(name string, resume func())\n\tVisitSlice(name string, resume func())\n\tVisitStruct(name string, fields []Field, resume func())\n\tVisitStructField(field Field, resume func())\n\tVisitMap(name string, resume func())\n\tVisitCustom(name string, resume func())\n\tVisitReference(name string, resume func())\n}\n\ntype Visitor struct{}\n\nfunc (self *Visitor) VisitString(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitInt(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitFloat(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBool(name string, resume func()) {\n\tresume()\n}\n\n\n\nfunc (self *Visitor) VisitBytes(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitSlice(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStructField(field Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitMap(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitCustom(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitReference(name string, resume func()) {\n\tresume()\n}\n\ntype EmbeddedStructVisitor struct {\n\tInterface\n}\n\nfunc (self *EmbeddedStructVisitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitPtr(name string, resume func()) ", "output": "{\n\tresume()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n)\n\nfunc LogsterArgs(logPath string) (args []string) {\n\n\targs = append(args, fmt.Sprintf(\"--output=%s\", Output))\n\n\tif Prefix != \"\" {\n\t\targs = append(args, fmt.Sprintf(\"--metric-prefix=%s\", Prefix))\n\t}\n\n\tif GraphiteHost != \"\" {\n\t\targs = append(args, fmt.Sprintf(\"--graphite-host=%s\", GraphiteHost))\n\t}\n\n\targs = append(args, Parser)\n\targs = append(args, logPath)\n\n\treturn\n}\n\n\n\nfunc RunLogster(logFile string) ", "output": "{\n\n\tif logFile == \"\" {\n\t\tlogger.Error(\"logfile not found\", \"file\", logFile)\n\t\treturn\n\t}\n\n\tlogsterArgs := LogsterArgs(logFile)\n\n\tlogger.Info(\"logster\", \"args\", logsterArgs)\n\n\tcmd := exec.Command(LogsterPath, logsterArgs...)\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tlogger.Error(\"logster\", \"err\", err.Error())\n\t}\n\n\tlogger.Info(\"logster\", \"output\", string(out))\n\n}"} {"input": "package bigquery\n\nimport (\n\t\"fmt\"\n\t\"github.com/viant/endly\"\n\t\"github.com/viant/endly/system/cloud/gcp\"\n\t\"google.golang.org/api/bigquery/v2\"\n)\n\nvar clientKey = (*CtxClient)(nil)\n\n\ntype CtxClient struct {\n\t*gcp.AbstractClient\n\tservice *bigquery.Service\n}\n\nfunc (s *CtxClient) SetService(service interface{}) error {\n\tvar ok bool\n\ts.service, ok = service.(*bigquery.Service)\n\tif !ok {\n\t\treturn fmt.Errorf(\"unable to set service: %T\", service)\n\t}\n\treturn nil\n}\n\nfunc (s *CtxClient) Service() interface{} {\n\treturn s.service\n}\n\nfunc InitRequest(context *endly.Context, rawRequest map[string]interface{}) error {\n\tconfig, err := gcp.InitCredentials(context, rawRequest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient, err := getClient(context)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgcp.UpdateActionRequest(rawRequest, config, client)\n\treturn nil\n}\n\n\n\nfunc GetClient(context *endly.Context) (*CtxClient, error) {\n\tclient := &CtxClient{\n\t\tAbstractClient: &gcp.AbstractClient{},\n\t}\n\terr := gcp.GetClient(context, bigquery.New, clientKey, &client, bigquery.CloudPlatformScope, bigquery.BigqueryScope, bigquery.BigqueryInsertdataScope)\n\treturn client, err\n}\n\nfunc getClient(context *endly.Context) (gcp.CtxClient, error) ", "output": "{\n\treturn GetClient(context)\n}"} {"input": "package client\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/thecodeteam/rexray/libstorage/api/types\"\n)\n\n\ntype client struct {\n\thttp.Client\n\thost string\n\tlogRequests bool\n\tlogResponses bool\n\tserverName string\n}\n\n\n\n\nfunc (c *client) ServerName() string {\n\treturn c.serverName\n}\n\nfunc (c *client) LogRequests(enabled bool) {\n\tc.logRequests = enabled\n}\n\nfunc (c *client) LogResponses(enabled bool) {\n\tc.logResponses = enabled\n}\n\nfunc New(host string, transport *http.Transport) types.APIClient ", "output": "{\n\treturn &client{\n\t\tClient: http.Client{\n\t\t\tTransport: transport,\n\t\t},\n\t\thost: host,\n\t}\n}"} {"input": "package libsnnet\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc performBridgeOps(shouldPass bool, assert *assert.Assertions, bridge *Bridge) {\n\ta := assert.Nil\n\tif !shouldPass {\n\t\ta = assert.NotNil\n\t}\n\ta(bridge.enable())\n\ta(bridge.disable())\n\ta(bridge.destroy())\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc TestBridge_Dup(t *testing.T) {\n\tassert := assert.New(t)\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge.create())\n\tdefer func() { _ = bridge.destroy() }()\n\n\tbridge1, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\tassert.NotNil(bridge1.create())\n}\n\n\n\n\n\n\n\nfunc TestBridge_Invalid(t *testing.T) {\n\tassert := assert.New(t)\n\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.NotNil(bridge.getDevice())\n\n\tperformBridgeOps(false, assert, bridge)\n}\n\n\n\n\n\n\n\nfunc TestBridge_GetDevice(t *testing.T) {\n\tassert := assert.New(t)\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge.create())\n\n\tbridge1, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge1.getDevice())\n\tperformBridgeOps(true, assert, bridge1)\n}\n\nfunc TestBridge_Basic(t *testing.T) ", "output": "{\n\tassert := assert.New(t)\n\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge.create())\n\n\tbridge1, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge1.getDevice())\n\tperformBridgeOps(true, assert, bridge)\n\n\tassert.NotNil(bridge.destroy())\n\n}"} {"input": "package internalversion\n\nimport (\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/kubernetes/pkg/api\"\n)\n\n\n\ntype ServiceListerExpansion interface {\n\tGetPodServices(pod *api.Pod) ([]*api.Service, error)\n}\n\n\n\ntype ServiceNamespaceListerExpansion interface{}\n\n\n\n\n\nfunc (s *serviceLister) GetPodServices(pod *api.Pod) ([]*api.Service, error) ", "output": "{\n\tallServices, err := s.Services(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar services []*api.Service\n\tfor i := range allServices {\n\t\tservice := allServices[i]\n\t\tif service.Spec.Selector == nil {\n\t\t\tcontinue\n\t\t}\n\t\tselector := labels.Set(service.Spec.Selector).AsSelectorPreValidated()\n\t\tif selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tservices = append(services, service)\n\t\t}\n\t}\n\n\treturn services, nil\n}"} {"input": "package markdown\n\nimport (\n\t\"bufio\"\n\t\"io\"\n)\n\ntype writer interface {\n\tWrite([]byte) (int, error)\n\tWriteByte(byte) error\n\tWriteString(string) (int, error)\n\tFlush() error\n}\n\ntype monadicWriter struct {\n\twriter\n\terr error\n}\n\nfunc newMonadicWriter(w io.Writer) *monadicWriter {\n\tif w, ok := w.(writer); ok {\n\t\treturn &monadicWriter{writer: w}\n\t}\n\treturn &monadicWriter{writer: bufio.NewWriter(w)}\n}\n\nfunc (w *monadicWriter) Write(p []byte) (n int, err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\tn, err = w.writer.Write(p)\n\tw.err = err\n\treturn\n}\n\nfunc (w *monadicWriter) WriteByte(b byte) (err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\terr = w.writer.WriteByte(b)\n\tw.err = err\n\treturn\n}\n\nfunc (w *monadicWriter) WriteString(s string) (n int, err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\tn, err = w.writer.WriteString(s)\n\tw.err = err\n\treturn\n}\n\n\n\nfunc (w *monadicWriter) Flush() (err error) ", "output": "{\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\terr = w.writer.Flush()\n\tw.err = err\n\treturn\n}"} {"input": "package decode\n\nimport \"github.com/spf13/cobra\"\n\n\n\nfunc NewCommand() *cobra.Command ", "output": "{\n\tcmd := &cobra.Command{\n\t\tUse: \"decode\",\n\t\tShort: \"try to decode json-web-token\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\treturn cmd\n}"} {"input": "package sodium\n\n\n\n\nimport \"C\"\n\nfunc RuntimeHasNeon() bool {\n\treturn C.sodium_runtime_has_neon() != 0\n}\n\nfunc RuntimeHasSse2() bool {\n\treturn C.sodium_runtime_has_sse2() != 0\n}\n\n\n\nfunc RuntimeHasSse3() bool ", "output": "{\n\treturn C.sodium_runtime_has_sse3() != 0\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"github.com/emicklei/go-restful\"\n \"github.com/gorilla/schema\"\n \"io\"\n \"net/http\"\n)\n\n\n\n\n\n\n\ntype Profile struct {\n Name string\n Age int\n}\n\nvar decoder *schema.Decoder\n\nfunc main() {\n decoder = schema.NewDecoder()\n ws := new(restful.WebService)\n ws.Route(ws.POST(\"/profiles\").Consumes(\"application/x-www-form-urlencoded\").To(postAdddress))\n ws.Route(ws.GET(\"/profiles\").To(addresssForm))\n restful.Add(ws)\n http.ListenAndServe(\":8080\", nil)\n}\n\nfunc postAdddress(req *restful.Request, resp *restful.Response) {\n err := req.Request.ParseForm()\n if err != nil {\n resp.WriteErrorString(http.StatusBadRequest, err.Error())\n return\n }\n p := new(Profile)\n err = decoder.Decode(p, req.Request.PostForm)\n if err != nil {\n resp.WriteErrorString(http.StatusBadRequest, err.Error())\n return\n }\n io.WriteString(resp.ResponseWriter, fmt.Sprintf(\"Name=%s, Age=%d\", p.Name, p.Age))\n}\n\n\n\nfunc addresssForm(req *restful.Request, resp *restful.Response) ", "output": "{\n io.WriteString(resp.ResponseWriter,\n `\n \n

Enter Profile

\n
\n \n \n \n \n \n
\n \n `)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\nfunc init() {\n\td1 := &D1{}\n\tchallenges[1] = &challenge{\"Day 01\", \"input/day01.txt\", d1}\n}\n\n\n\n\ntype D1 struct {\n\tmodules []int\n}\n\nfunc (d1 *D1) parse(line string) error {\n\tv, err := strconv.Atoi(line)\n\tif err == nil {\n\t\td1.modules = append(d1.modules, v)\n\t}\n\treturn err\n}\n\nfunc (d1 *D1) part1() (string, error) {\n\tsum := 0\n\tfor _, module := range d1.modules {\n\t\tsum += MFR(module)\n\t}\n\treturn fmt.Sprintf(\"Sum of fuel requirements is %d\", sum), nil\n}\n\nfunc TotalMFR(mass int) int {\n\treq := MFR(mass)\n\tif req > 0 {\n\t\treq += TotalMFR(req)\n\t} else {\n\t\treq = 0\n\t}\n\treturn req\n}\n\nfunc (d1 *D1) part2() (string, error) {\n\tsum := 0\n\tfor _, module := range d1.modules {\n\t\tsum += TotalMFR(module)\n\t}\n\treturn fmt.Sprintf(\"Sum of fuel requirements is %d\", sum), nil\n}\n\nfunc MFR(mass int) int ", "output": "{\n\treturn (mass / 3) - 2\n}"} {"input": "package cli\n\nimport (\n\t\"github.com/spf13/cobra\"\n\n\tcollectorPkg \"github.com/zyndiecate/matic/collector\"\n)\n\nvar (\n\tclientCollector collectorPkg.ClientCollectorI\n\n\tclientCmd = &cobra.Command{\n\t\tUse: \"client\",\n\t\tShort: \"Autogenerate client for web-service\",\n\t\tLong: \"Autogenerate client for web-service\",\n\t\tRun: clientRun,\n\t}\n\n\tlang string\n\troot string\n)\n\n\n\nfunc clientRun(cmd *cobra.Command, args []string) {\n\tswitch lang {\n\tcase \"go\":\n\t\tclientCollector = collectorPkg.NewGoClientCollector()\n\tdefault:\n\t\tcmd.Help()\n\t\tExitStderr(ErrWrongInput)\n\t}\n\n\tswitch len(args) {\n\tcase 0:\n\t\troot = \".\"\n\tcase 1:\n\t\troot = args[0]\n\tdefault:\n\t\tcmd.Help()\n\t\tExitStderr(ErrWrongInput)\n\t}\n\n\terr := clientCollector.GenerateClient(root)\n\tif err != nil {\n\t\tExitStderr(Mask(err))\n\t}\n}\n\nfunc init() ", "output": "{\n\tclientCmd.Flags().StringVarP(&lang, \"lang\", \"l\", \"go\", \"Which language to use to generate client\")\n}"} {"input": "package build\n\nimport \"github.com/docker/docker/api/server/router\"\n\n\ntype buildRouter struct {\n\tbackend Backend\n\troutes []router.Route\n}\n\n\n\n\n\nfunc (r *buildRouter) Routes() []router.Route {\n\treturn r.routes\n}\n\nfunc (r *buildRouter) initRoutes() {\n\tr.routes = []router.Route{\n\t\trouter.NewPostRoute(\"/build\", r.postBuild),\n\t}\n}\n\nfunc NewRouter(b Backend) router.Router ", "output": "{\n\tr := &buildRouter{\n\t\tbackend: b,\n\t}\n\tr.initRoutes()\n\treturn r\n}"} {"input": "package http\n\nimport (\n\t\"net/http\"\n\t\"reflect\"\n)\n\n\ntype JSONErrorBuilder interface {\n\tBuild() JSONError\n\n\tCustomError(code int, errorType, msg string) JSONErrorBuilder\n\n\tFromError(e error) JSONErrorBuilder\n\n\tMessage(string) JSONErrorBuilder\n\n\tStatus(int) JSONErrorBuilder\n\n\tURL(string) JSONErrorBuilder\n}\n\ntype jsonErrorBuilder struct {\n\tinstance JSONError\n}\n\n\n\nfunc NewJSONError() JSONErrorBuilder {\n\treturn &jsonErrorBuilder{JSONError{\n\t\tStatus: http.StatusInternalServerError,\n\t}}\n}\n\nfunc (b *jsonErrorBuilder) Build() JSONError {\n\treturn b.instance\n}\n\nfunc (b *jsonErrorBuilder) CustomError(\n\tcode int,\n\terrorType,\n\tmsg string,\n) JSONErrorBuilder {\n\tb.instance.Code = code\n\tb.instance.Type = errorType\n\tb.instance.Message = msg\n\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) FromError(e error) JSONErrorBuilder {\n\terrType := reflect.TypeOf(e)\n\tvar typeName string\n\tif errType.Kind() == reflect.Ptr {\n\t\ttypeName = errType.Elem().Name()\n\t} else {\n\t\ttypeName = errType.Name()\n\t}\n\n\tb.instance.Type = typeName\n\tb.instance.Message = e.Error()\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) Message(msg string) JSONErrorBuilder {\n\tb.instance.Message = msg\n\treturn b\n}\n\n\n\nfunc (b *jsonErrorBuilder) URL(url string) JSONErrorBuilder {\n\tb.instance.MoreInfo = url\n\treturn b\n}\n\nvar _ JSONErrorBuilder = (*jsonErrorBuilder)(nil)\n\nfunc (b *jsonErrorBuilder) Status(status int) JSONErrorBuilder ", "output": "{\n\tb.instance.Status = status\n\treturn b\n}"} {"input": "package anchorTask\n\nimport (\n\txtime \"go-common/library/time\"\n)\n\n\n\n\n\ntype AnchorRewardConf struct {\n\tID int64 `json:\"id\" gorm:\"comumn:id\"`\n\tName string `json:\"name\" gorm:\"comumn:name\"`\n\tIcon string `json:\"icon\" gorm:\"comumn:icon\"`\n\tRewardIntro string `json:\"reward_intro\" gorm:\"comumn:reward_intro\"`\n\tRewardType int64 `json:\"reward_type\" gorm:\"comumn:reward_type\"`\n\tDetail string `json:\"detail\" gorm:\"comumn:detail\"`\n\tInstructions string `json:\"instructions\" gorm:\"comumn:instructions\"`\n\tReserved1 int64 `json:\"reserved1\" gorm:\"comumn:reserved1\"`\n\tReserved2 string `json:\"reserved2\" gorm:\"comumn:reserved2\"`\n\tCtime xtime.Time `json:\"ctime\" gorm:\"comumn:ctime\"`\n\tMtime xtime.Time `json:\"mtime\" gorm:\"comumn:mtime\"`\n}\n\nfunc (arc *AnchorRewardConf) TableName() string ", "output": "{\n\treturn \"ap_anchor_task_reward_conf\"\n}"} {"input": "package models\n\ntype ServiceOfferingFields struct {\n\tGuid string\n\tBrokerGuid string\n\tLabel string\n\tProvider string\n\tVersion string\n\tDescription string\n\tDocumentationUrl string\n}\n\ntype ServiceOffering struct {\n\tServiceOfferingFields\n\tPlans []ServicePlanFields\n}\n\ntype ServiceOfferings []ServiceOffering\n\nfunc (s ServiceOfferings) Len() int {\n\treturn len(s)\n}\n\nfunc (s ServiceOfferings) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\n\n\nfunc (s ServiceOfferings) Less(i, j int) bool ", "output": "{\n\treturn s[i].Label < s[j].Label\n}"} {"input": "package compute_test\n\nimport (\n\t\"context\"\n\n\tcompute \"cloud.google.com/go/compute/apiv1\"\n\tcomputepb \"google.golang.org/genproto/googleapis/cloud/compute/v1\"\n)\n\n\n\nfunc ExampleRegionInstancesClient_BulkInsert() {\n\tctx := context.Background()\n\tc, err := compute.NewRegionInstancesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\treq := &computepb.BulkInsertRegionInstanceRequest{\n\t}\n\top, err := c.BulkInsert(ctx, req)\n\tif err != nil {\n\t}\n\n\terr = op.Wait(ctx)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleNewRegionInstancesRESTClient() ", "output": "{\n\tctx := context.Background()\n\tc, err := compute.NewRegionInstancesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\t_ = c\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSECSTaskDefinition_DockerVolumeConfiguration struct {\n\n\tAutoprovision bool `json:\"Autoprovision,omitempty\"`\n\n\tDriver string `json:\"Driver,omitempty\"`\n\n\tDriverOpts map[string]string `json:\"DriverOpts,omitempty\"`\n\n\tLabels map[string]string `json:\"Labels,omitempty\"`\n\n\tScope string `json:\"Scope,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\n\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::ECS::TaskDefinition.DockerVolumeConfiguration\"\n}"} {"input": "package metrics\n\nimport (\n\t\"github.com/cloudfoundry/dropsonde/metric_sender\"\n)\n\nvar metricSender metric_sender.MetricSender\nvar metricBatcher MetricBatcher\n\ntype MetricBatcher interface {\n\tBatchIncrementCounter(name string)\n\tBatchAddCounter(name string, delta uint64)\n\tClose()\n}\n\n\nfunc Initialize(ms metric_sender.MetricSender, mb MetricBatcher) {\n\tif metricBatcher != nil {\n\t\tmetricBatcher.Close()\n\t}\n\tmetricSender = ms\n\tmetricBatcher = mb\n}\n\n\n\n\n\n\nfunc SendValue(name string, value float64, unit string) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.SendValue(name, value, unit)\n}\n\n\n\n\nfunc IncrementCounter(name string) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.IncrementCounter(name)\n}\n\n\n\n\nfunc BatchIncrementCounter(name string) {\n\tif metricBatcher == nil {\n\t\treturn\n\t}\n\tmetricBatcher.BatchIncrementCounter(name)\n}\n\n\n\n\nfunc AddToCounter(name string, delta uint64) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.AddToCounter(name, delta)\n}\n\n\n\n\nfunc BatchAddCounter(name string, delta uint64) {\n\tif metricBatcher == nil {\n\t\treturn\n\t}\n\tmetricBatcher.BatchAddCounter(name, delta)\n}\n\n\n\n\n\nfunc SendContainerMetric(applicationId string, instanceIndex int32, cpuPercentage float64, memoryBytes uint64, diskBytes uint64) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\n\treturn metricSender.SendContainerMetric(applicationId, instanceIndex, cpuPercentage, memoryBytes, diskBytes)\n}\n\nfunc Close() ", "output": "{\n\tmetricBatcher.Close()\n}"} {"input": "package testonly\n\n\n\n\nimport (\n\t\"crypto/sha256\"\n)\n\n\n\nfunc HashKey(key string) []byte {\n\th := sha256.New()\n\th.Write([]byte(key))\n\treturn h.Sum(nil)\n}\n\n\n\n\n\nfunc TransparentHash(key string) []byte ", "output": "{\n\tconst prefixLen = 8\n\tif prefixLen+len(key) > sha256.Size {\n\t\tpanic(\"key too long\")\n\t}\n\tb := make([]byte, sha256.Size)\n\th := HashKey(key)\n\tcopy(b[0:prefixLen], h[0:prefixLen])\n\tcopy(b[prefixLen:], key)\n\treturn b\n}"} {"input": "package signedexchange\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n\nvar statefulRequestHeadersSet map[string]struct{}\nvar uncachedHeadersSet map[string]struct{}\n\nfunc init() {\n\tstatefulRequestHeaders := []string{\n\t\t\"authorization\",\n\t\t\"cookie\",\n\t\t\"cookie2\",\n\t\t\"proxy-authorization\",\n\t\t\"sec-websocket-key\",\n\t}\n\tstatefulRequestHeadersSet = make(map[string]struct{})\n\tfor _, e := range statefulRequestHeaders {\n\t\tstatefulRequestHeadersSet[e] = struct{}{}\n\t}\n\n\tuncachedHeaders := []string{\n\n\n\t\t\"connection\",\n\t\t\"keep-alive\",\n\t\t\"proxy-connection\",\n\t\t\"trailer\",\n\t\t\"transfer-encoding\",\n\t\t\"upgrade\",\n\n\t\t\"authentication-control\",\n\t\t\"authentication-info\",\n\t\t\"clear-site-data\",\n\t\t\"optional-www-authenticate\",\n\t\t\"proxy-authenticate\",\n\t\t\"proxy-authentication-info\",\n\t\t\"public-key-pins\",\n\t\t\"sec-websocket-accept\",\n\t\t\"set-cookie\",\n\t\t\"set-cookie2\",\n\t\t\"setprofile\",\n\t\t\"strict-transport-security\",\n\t\t\"www-authenticate\",\n\t}\n\tuncachedHeadersSet = make(map[string]struct{})\n\tfor _, e := range uncachedHeaders {\n\t\tuncachedHeadersSet[e] = struct{}{}\n\t}\n}\n\n\n\nfunc IsStatefulRequestHeader(n string) bool {\n\tcname := strings.ToLower(n)\n\t_, exists := statefulRequestHeadersSet[cname]\n\treturn exists\n}\n\nfunc IsUncachedHeader(n string) bool {\n\tcname := strings.ToLower(n)\n\t_, exists := uncachedHeadersSet[cname]\n\treturn exists\n}\n\n\n\n\n\nfunc VerifyUncachedHeader(h http.Header) error ", "output": "{\n\n\tfor n := range h {\n\t\tif IsUncachedHeader(n) {\n\t\t\treturn fmt.Errorf(\"signedexchange: uncached header %q can't be captured inside a signed exchange.\", n)\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package instance\n\nimport (\n\t\"net\"\n)\n\n\n\ntype AddressType string\n\nconst (\n\tHostName AddressType = \"hostname\"\n\tIpv4Address AddressType = \"ipv4\"\n\tIpv6Address AddressType = \"ipv6\"\n)\n\n\n\n\n\ntype NetworkScope string\n\nconst (\n\tNetworkUnknown NetworkScope = \"\"\n\tNetworkPublic NetworkScope = \"public\"\n\tNetworkCloudLocal NetworkScope = \"local-cloud\"\n\tNetworkMachineLocal NetworkScope = \"local-machine\"\n)\n\n\n\ntype Address struct {\n\tValue string\n\tType AddressType\n\tNetworkName string\n\tNetworkScope\n}\n\nfunc deriveAddressType(value string) AddressType {\n\tip := net.ParseIP(value)\n\tif ip != nil {\n\t\tif ip.To4() != nil {\n\t\t\treturn Ipv4Address\n\t\t}\n\t\tif ip.To16() != nil {\n\t\t\treturn Ipv6Address\n\t\t}\n\t\tpanic(\"Unknown form of IP address\")\n\t}\n\treturn HostName\n}\n\nfunc NewAddress(value string) Address {\n\taddresstype := deriveAddressType(value)\n\treturn Address{value, addresstype, \"\", NetworkUnknown}\n}\n\n\n\n\n\n\nfunc SelectPublicAddress(addresses []Address) string ", "output": "{\n\tmostpublic := \"\"\n\tfor _, addr := range addresses {\n\t\tif addr.Type != Ipv6Address {\n\t\t\tswitch addr.NetworkScope {\n\t\t\tcase NetworkPublic:\n\t\t\t\treturn addr.Value\n\t\t\tcase NetworkCloudLocal, NetworkUnknown:\n\t\t\t\tmostpublic = addr.Value\n\t\t\t}\n\t\t}\n\t}\n\treturn mostpublic\n}"} {"input": "package openpgp\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\ntype recordingHash struct {\n\tbuf *bytes.Buffer\n}\n\nfunc (r recordingHash) Write(b []byte) (n int, err error) {\n\treturn r.buf.Write(b)\n}\n\nfunc (r recordingHash) Sum(in []byte) []byte {\n\treturn append(in, r.buf.Bytes()...)\n}\n\n\n\nfunc (r recordingHash) Size() int {\n\tpanic(\"shouldn't be called\")\n}\n\nfunc (r recordingHash) BlockSize() int {\n\tpanic(\"shouldn't be called\")\n}\n\nfunc testCanonicalText(t *testing.T, input, expected string) {\n\tr := recordingHash{bytes.NewBuffer(nil)}\n\tc := NewCanonicalTextHash(r)\n\tc.Write([]byte(input))\n\tresult := c.Sum(nil)\n\tif expected != string(result) {\n\t\tt.Errorf(\"input: %x got: %x want: %x\", input, result, expected)\n\t}\n}\n\nfunc TestCanonicalText(t *testing.T) {\n\ttestCanonicalText(t, \"foo\\n\", \"foo\\r\\n\")\n\ttestCanonicalText(t, \"foo\", \"foo\")\n\ttestCanonicalText(t, \"foo\\r\\n\", \"foo\\r\\n\")\n\ttestCanonicalText(t, \"foo\\r\\nbar\", \"foo\\r\\nbar\")\n\ttestCanonicalText(t, \"foo\\r\\nbar\\n\\n\", \"foo\\r\\nbar\\r\\n\\r\\n\")\n}\n\nfunc (r recordingHash) Reset() ", "output": "{\n\tpanic(\"shouldn't be called\")\n}"} {"input": "package dodo\n\n\n\n\ntype propertyIndex struct {\n\tpropertyIndexMap map[string]map[string]int\n}\n\nfunc (p *propertyIndex) index(container, property string) *int {\n\n\tindexMap, exists := p.propertyIndexMap[container]\n\tif !exists {\n\t\treturn nil\n\t}\n\n\tindex, exists := indexMap[property]\n\tif !exists {\n\t\treturn nil\n\t}\n\n\treturn &index\n}\n\nfunc (p *propertyIndex) incrementIndex(container, property string) *int {\n\n\tindexMap, exists := p.propertyIndexMap[container]\n\tif !exists {\n\t\tindexMap = map[string]int{}\n\t\tp.propertyIndexMap[container] = indexMap\n\t}\n\n\tindex, exists := indexMap[property]\n\tif !exists {\n\t\tindex = 0\n\t\tindexMap[property] = index\n\t} else {\n\t\tindex++\n\t\tindexMap[property] = index\n\t}\n\n\treturn &index\n}\n\nfunc NewPropertyIndex() *propertyIndex ", "output": "{\n\n\treturn &propertyIndex{\n\t\tpropertyIndexMap: map[string]map[string]int{},\n\t}\n}"} {"input": "package lnwire\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\ntype NeighborAckMessage struct {\n\tRoutingMessageBase\n}\n\nfunc (msg *NeighborAckMessage) String() string {\n\treturn fmt.Sprintf(\"NeighborAckMessage{%v %v}\", msg.SenderID, msg.ReceiverID)\n}\n\nfunc (msg *NeighborAckMessage) Command() uint32{\n\treturn CmdNeighborAckMessage\n}\n\nfunc (msg *NeighborAckMessage) Encode(w io.Writer, pver uint32) error{\n\treturn nil\n}\n\n\n\nfunc (msg *NeighborAckMessage) MaxPayloadLength(uint32) uint32{\n\treturn 0\n}\n\nfunc (msg *NeighborAckMessage) Validate() error{\n\treturn nil\n}\n\nvar _ Message = (*NeighborAckMessage)(nil)\n\nfunc (msg *NeighborAckMessage) Decode(r io.Reader, pver uint32) error", "output": "{\n\treturn nil\n}"} {"input": "package emptydisk\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"path\"\n\t\"strconv\"\n\n\t\"kubevirt.io/kubevirt/pkg/api/v1\"\n)\n\nvar EmptyDiskBaseDir = \"/var/run/libvirt/empty-disks/\"\n\nfunc CreateTemporaryDisks(vm *v1.VirtualMachine) error {\n\n\tfor _, volume := range vm.Spec.Volumes {\n\n\t\tif volume.EmptyDisk != nil {\n\t\t\tsize := strconv.FormatInt(volume.EmptyDisk.Capacity.ToDec().ScaledValue(0), 10)\n\t\t\tfile := FilePathForVolumeName(volume.Name)\n\t\t\tif err := os.MkdirAll(EmptyDiskBaseDir, 0777); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif _, err := os.Stat(file); os.IsNotExist(err) {\n\t\t\t\tif err := exec.Command(\"qemu-img\", \"create\", \"-f\", \"qcow2\", file, size).Run(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else if err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc FilePathForVolumeName(volumeName string) string ", "output": "{\n\treturn path.Join(EmptyDiskBaseDir, volumeName+\".qcow2\")\n}"} {"input": "package gce\n\nimport (\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\ntype GCEAPITarget struct {\n\tCloud *GCECloud\n}\n\nvar _ fi.Target = &GCEAPITarget{}\n\n\n\nfunc (t *GCEAPITarget) Finish(taskMap map[string]fi.Task) error {\n\treturn nil\n}\n\nfunc NewGCEAPITarget(cloud *GCECloud) *GCEAPITarget ", "output": "{\n\treturn &GCEAPITarget{\n\t\tCloud: cloud,\n\t}\n}"} {"input": "package format\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\n\ntype Unsigned32 uint32\n\nfunc DecodeUnsigned32(b []byte) (Format, error) {\n\treturn Unsigned32(binary.BigEndian.Uint32(b)), nil\n}\n\nfunc (n Unsigned32) Serialize() []byte {\n\tb := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(b, uint32(n))\n\treturn b\n}\n\nfunc (n Unsigned32) Len() int {\n\treturn 4\n}\n\nfunc (n Unsigned32) Padding() int {\n\treturn 0\n}\n\n\n\nfunc (n Unsigned32) String() string {\n\treturn fmt.Sprintf(\"Unsigned32{%d}\", n)\n}\n\nfunc (n Unsigned32) Format() FormatId ", "output": "{\n\treturn Unsigned32Format\n}"} {"input": "package api2go\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\ntype APIContextAllocatorFunc func(*API) APIContexter\n\n\ntype APIContexter interface {\n\tcontext.Context\n\tSet(key string, value interface{})\n\tGet(key string) (interface{}, bool)\n\tReset()\n}\n\n\ntype APIContext struct {\n\tkeys map[string]interface{}\n}\n\n\n\n\n\nfunc (c *APIContext) Get(key string) (value interface{}, exists bool) {\n\tif c.keys != nil {\n\t\tvalue, exists = c.keys[key]\n\t}\n\treturn\n}\n\n\nfunc (c *APIContext) Reset() {\n\tc.keys = nil\n}\n\n\nfunc (c *APIContext) Deadline() (deadline time.Time, ok bool) {\n\treturn\n}\n\n\nfunc (c *APIContext) Done() <-chan struct{} {\n\treturn nil\n}\n\n\nfunc (c *APIContext) Err() error {\n\treturn nil\n}\n\n\nfunc (c *APIContext) Value(key interface{}) interface{} {\n\tif keyAsString, ok := key.(string); ok {\n\t\tval, _ := c.Get(keyAsString)\n\t\treturn val\n\t}\n\treturn nil\n}\n\n\nvar _ APIContexter = &APIContext{}\n\n\nfunc ContextQueryParams(c *APIContext) map[string][]string {\n\tqp, ok := c.Get(\"QueryParams\")\n\tif ok == false {\n\t\tqp = make(map[string][]string)\n\t\tc.Set(\"QueryParams\", qp)\n\t}\n\treturn qp.(map[string][]string)\n}\n\nfunc (c *APIContext) Set(key string, value interface{}) ", "output": "{\n\tif c.keys == nil {\n\t\tc.keys = make(map[string]interface{})\n\t}\n\tc.keys[key] = value\n}"} {"input": "package cases\n\nimport \"github.com/insionng/yougam/libraries/x/text/transform\"\n\ntype caseFolder struct{ transform.NopResetter }\n\n\n\n\nfunc makeFold(o options) transform.Transformer {\n\treturn &caseFolder{}\n}\n\nfunc (t *caseFolder) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) ", "output": "{\n\tc := context{dst: dst, src: src, atEOF: atEOF}\n\tfor c.next() {\n\t\tfoldFull(&c)\n\t\tc.checkpoint()\n\t}\n\treturn c.ret()\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype OpenpitrixCreateReleaseRequest struct {\n\n\tAppID string `json:\"app_id,omitempty\"`\n\n\tNamespace string `json:\"namespace,omitempty\"`\n\n\tReleaseName string `json:\"release_name,omitempty\"`\n\n\tRuntimeID string `json:\"runtime_id,omitempty\"`\n\n\tVersionID string `json:\"version_id,omitempty\"`\n}\n\n\nfunc (m *OpenpitrixCreateReleaseRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (m *OpenpitrixCreateReleaseRequest) UnmarshalBinary(b []byte) error {\n\tvar res OpenpitrixCreateReleaseRequest\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *OpenpitrixCreateReleaseRequest) MarshalBinary() ([]byte, error) ", "output": "{\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/robfig/cron\"\n)\n\ntype Sync struct{}\n\nfunc (s *Sync) Help() string {\n\treturn \"glr sync Help\"\n}\n\nfunc (s *Sync) Run(args []string) int {\n\t_, err := SyncRepository()\n\n\tif err != nil {\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n\nfunc (s *Sync) Synopsis() string {\n\treturn \"Synchronize local git repository with remote at once\"\n}\n\n\ntype status struct {\n\tc *cron.Cron\n\trepositories []string\n\tschedules []string\n}\n\nvar sharedStatus *status = newStatus()\n\nfunc newStatus() *status {\n\treturn &status{\n\t\tc: cron.New(),\n\t}\n}\n\n\n\n\ntype StatusStart struct{}\n\nfunc (s *StatusStart) Help() string {\n\treturn \"glr status start Help\"\n}\n\nfunc (s *StatusStart) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.AddFunc(\"@hourly\", func() {\n\t\tSyncRepository()\n\t})\n\tfmt.Println(\"set job schedule\")\n\tstatus.c.Start()\n\n\treturn 0\n}\n\nfunc (s *StatusStart) Synopsis() string {\n\treturn \"Synchronize local git repository with remote\"\n}\n\ntype StatusStop struct{}\n\nfunc (s *StatusStop) Help() string {\n\treturn \"glr status stop Help\"\n}\n\nfunc (s *StatusStop) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.Stop()\n\tfmt.Println(\"stop job scheduler\")\n\n\treturn 0\n}\n\nfunc (s *StatusStop) Synopsis() string {\n\treturn \"Stop cron scheduler\"\n}\n\nfunc GetStatus() *status ", "output": "{\n\treturn sharedStatus\n}"} {"input": "package command\n\nimport (\n\t\"github.com/matsu-chara/gol/operations\"\n\t\"github.com/matsu-chara/gol/util\"\n\t\"github.com/urfave/cli\"\n)\n\n\n\n\nfunc CmdAdd(c *cli.Context) ", "output": "{\n\tfilepath := c.GlobalString(\"datapath\")\n\tkey := c.Args().Get(0)\n\tlink := c.Args().Get(1)\n\tregisteredBy := c.Args().Get(2)\n\tisForce := c.Bool(\"force\")\n\n\terr := operations.RunAdd(filepath, key, link, registeredBy, isForce)\n\tutil.ExitIfError(err)\n}"} {"input": "package actions\n\n\n\n\nimport (\n\t\"net/http\"\n\n\tmiddleware \"github.com/go-openapi/runtime/middleware\"\n\n\tmodels \"github.com/semi-technologies/weaviate/entities/models\"\n)\n\n\ntype ActionsDeleteHandlerFunc func(ActionsDeleteParams, *models.Principal) middleware.Responder\n\n\nfunc (fn ActionsDeleteHandlerFunc) Handle(params ActionsDeleteParams, principal *models.Principal) middleware.Responder {\n\treturn fn(params, principal)\n}\n\n\ntype ActionsDeleteHandler interface {\n\tHandle(ActionsDeleteParams, *models.Principal) middleware.Responder\n}\n\n\n\n\n\ntype ActionsDelete struct {\n\tContext *middleware.Context\n\tHandler ActionsDeleteHandler\n}\n\nfunc (o *ActionsDelete) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\tr = rCtx\n\t}\n\tvar Params = NewActionsDeleteParams()\n\n\tuprinc, aCtx, err := o.Context.Authorize(r, route)\n\tif err != nil {\n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\tif aCtx != nil {\n\t\tr = aCtx\n\t}\n\tvar principal *models.Principal\n\tif uprinc != nil {\n\t\tprincipal = uprinc.(*models.Principal) \n\t}\n\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params, principal) \n\n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}\n\nfunc NewActionsDelete(ctx *middleware.Context, handler ActionsDeleteHandler) *ActionsDelete ", "output": "{\n\treturn &ActionsDelete{Context: ctx, Handler: handler}\n}"} {"input": "package mock\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/cilium/cilium/pkg/lock\"\n)\n\n\ntype MockMetrics struct {\n\tmutex lock.RWMutex\n\tapiCall map[string]float64\n\trateLimit map[string]time.Duration\n}\n\n\n\n\n\n\nfunc (m *MockMetrics) APICall(operation, status string) float64 {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\treturn m.apiCall[fmt.Sprintf(\"operation=%s, status=%s\", operation, status)]\n}\n\n\n\n\n\nfunc (m *MockMetrics) ObserveAPICall(operation, status string, duration float64) {\n\tm.mutex.Lock()\n\tm.apiCall[fmt.Sprintf(\"operation=%s, status=%s\", operation, status)] += duration\n\tm.mutex.Unlock()\n}\n\n\n\nfunc (m *MockMetrics) RateLimit(operation string) time.Duration {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\treturn m.rateLimit[operation]\n}\n\n\n\n\nfunc (m *MockMetrics) ObserveRateLimit(operation string, delay time.Duration) {\n\tm.mutex.Lock()\n\tm.rateLimit[operation] += delay\n\tm.mutex.Unlock()\n}\n\nfunc NewMockMetrics() *MockMetrics ", "output": "{\n\treturn &MockMetrics{\n\t\tapiCall: map[string]float64{},\n\t\trateLimit: map[string]time.Duration{},\n\t}\n}"} {"input": "package metric\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\ntype (\n\tCollectFnOpts struct {\n\t\tMethod string\n\t\tStart time.Time\n\t\tErr error\n\t\tAdditionalProps map[string]interface{}\n\t}\n\n\tCounterFn func(vec *prometheus.CounterVec, o CollectFnOpts)\n\n\tHistogramFn func(vec *prometheus.HistogramVec, o CollectFnOpts)\n\n\tVecOpts struct {\n\t\tName string\n\t\tHelp string\n\t\tLabelNames []string\n\n\t\tCounterFn CounterFn\n\t\tHistogramFn HistogramFn\n\t}\n)\n\ntype metricOpts struct {\n\tnamespace string\n\tservice string\n\tserviceSuffix string\n\tcounterMetrics map[string]VecOpts\n\thistogramMetrics map[string]VecOpts\n}\n\n\n\n\ntype ClientOptFn func(*metricOpts)\n\n\nfunc WithVec(opts VecOpts) ClientOptFn {\n\treturn func(o *metricOpts) {\n\t\tif opts.CounterFn != nil {\n\t\t\tif o.counterMetrics == nil {\n\t\t\t\to.counterMetrics = make(map[string]VecOpts)\n\t\t\t}\n\t\t\to.counterMetrics[opts.Name] = opts\n\t\t}\n\t}\n}\n\n\nfunc WithSuffix(suffix string) ClientOptFn {\n\treturn func(opts *metricOpts) {\n\t\topts.serviceSuffix = suffix\n\t}\n}\n\nfunc ApplyMetricOpts(opts ...ClientOptFn) *metricOpts {\n\to := metricOpts{}\n\tfor _, opt := range opts {\n\t\topt(&o)\n\t}\n\treturn &o\n}\n\nfunc (o *metricOpts) ApplySuffix(prefix string) string {\n\tif o.serviceSuffix != \"\" {\n\t\treturn fmt.Sprintf(\"%s_%s\", prefix, o.serviceSuffix)\n\t}\n\treturn prefix\n}\n\nfunc (o metricOpts) serviceName() string ", "output": "{\n\tif o.serviceSuffix != \"\" {\n\t\treturn fmt.Sprintf(\"%s_%s\", o.service, o.serviceSuffix)\n\t}\n\treturn o.service\n}"} {"input": "package utils\n\n\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\ntype MultiError struct {\n\tErrors []error\n\tErrorFormat ErrorFormatFunc\n}\n\nfunc (e *MultiError) Error() string {\n\tfn := e.ErrorFormat\n\tif fn == nil {\n\t\tfn = ListFormatFunc\n\t}\n\n\treturn fn(e.Errors)\n}\n\n\n\n\n\nfunc (e *MultiError) ErrorOrNil() error {\n\tif e == nil {\n\t\treturn nil\n\t}\n\tif len(e.Errors) == 0 {\n\t\treturn nil\n\t}\n\n\treturn e\n}\n\nfunc (e *MultiError) GoString() string {\n\treturn fmt.Sprintf(\"*%#v\", *e)\n}\n\n\n\n\n\n\n\n\nfunc (e *MultiError) WrappedErrors() []error {\n\treturn e.Errors\n}\n\n\n\ntype ErrorFormatFunc func([]error) string\n\n\n\n\n\n\n\n\n\n\n\nfunc AppendMulti(err error, errs ...error) *MultiError {\n\tswitch err := err.(type) {\n\tcase *MultiError:\n\t\tif err == nil {\n\t\t\terr = new(MultiError)\n\t\t}\n\n\t\tfor _, e := range errs {\n\t\t\tswitch e := e.(type) {\n\t\t\tcase *MultiError:\n\t\t\t\terr.Errors = append(err.Errors, e.Errors...)\n\t\t\tdefault:\n\t\t\t\terr.Errors = append(err.Errors, e)\n\t\t\t}\n\t\t}\n\n\t\treturn err\n\tdefault:\n\t\tnewErrs := make([]error, 0, len(errs)+1)\n\t\tif err != nil {\n\t\t\tnewErrs = append(newErrs, err)\n\t\t}\n\t\tnewErrs = append(newErrs, errs...)\n\n\t\treturn AppendMulti(&MultiError{}, newErrs...)\n\t}\n}\n\nfunc ListFormatFunc(es []error) string ", "output": "{\n\tpoints := make([]string, len(es))\n\tfor i, err := range es {\n\t\tpoints[i] = fmt.Sprintf(\"* %s\", err)\n\t}\n\n\treturn fmt.Sprintf(\n\t\t\"%d error(s) occurred:\\n\\n%s\",\n\t\tlen(es), strings.Join(points, \"\\n\"))\n}"} {"input": "package TeleGogo\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n)\n\nfunc responseToError(response *http.Response) error {\n\treturn responseToTgError(response)\n}\n\nfunc responseToTgError(response *http.Response) TelegramError {\n\tdefer response.Body.Close()\n\ttgErr := telegramError{}\n\tjson.NewDecoder(response.Body).Decode(&tgErr)\n\treturn tgErr\n}\n\n\n\ntype telegramError struct {\n\tOK bool `json:\"ok\"`\n\tErrorCode int `json:\"error_code\"`\n\tDescription string `json:\"description\"`\n}\n\nfunc (t telegramError) IsOK() bool {\n\treturn t.OK\n}\n\nfunc (t telegramError) ErrCode() int {\n\treturn t.ErrorCode\n}\n\nfunc (t telegramError) Error() string {\n\treturn t.Description\n}\n\n\ntype TelegramError interface {\n\tIsOK() bool\n\tErrCode() int\n\tError() string\n}\n\nfunc errToTelegramErr(err error) TelegramError ", "output": "{\n\treturn telegramError{OK: false, ErrorCode: 0, Description: err.Error()}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n)\n\ntype specialsub func(pos uint32) uint32\n\nvar specialsubs map[uint32]specialsub\n\nvar specialsubslist = []struct {\n\tName\t\tstring\n\tFormat\t\tstring\n\tHelp\t\t\tstring\n\tGenerator\t\tfunc(fields []string) specialsub\n}{\n\t{ \"stringafter\", \"stringafter n\",\n\t\t\"marks the function as having a null-terminated string immediately after the call, skilling n bytes first\", ssgen_stringafter },\n}\n\nfunc ssgen_stringafter(fields []string) specialsub {\n\tif len(fields) != 1 {\n\t\tfmt.Fprintf(os.Stderr, \"stringafter usage: specialsub addr stringafter n\\n\")\n\t\treturn nil\n\t}\n\tn, err := strconv.Atoi(fields[0])\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"stringafter error: invalid number %q: %v\", fields[0], err)\n\t\treturn nil\n\t}\n\treturn func(pos uint32) uint32 {\n\t\tvar b byte\n\n\t\tfor i := 0; i < n; i++ {\n\t\t\tb, pos = getbyte(pos)\n\t\t\tinstructions[pos - 1] = fmt.Sprintf(\"dc.b\\t$%02X\", b)\n\t\t}\n\t\tsb := make([]byte, 0, 128)\n\t\torigpos := pos\n\t\tfor {\n\t\t\tb, pos = getbyte(pos)\n\t\t\tif b == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tsb = append(sb, b)\n\t\t}\n\t\tinstructions[origpos] = fmt.Sprintf(\"dc.b\\t%q, 0\", sb)\n\t\treturn pos\n\t}\n}\n\n\n\n\n\nfunc c_specialsub(fields []string) ", "output": "{\n\tif len(fields) < 2 {\n\t\tfmt.Fprintf(os.Stderr, \"specialsubs usage: specialsubs addr command [args]\\n\")\n\t\treturn\n\t}\n\n\taddr64, err := strconv.ParseUint(fields[0], 16, 32)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"specialsubs error: invalid address hex number %q: %v\", fields[0], err)\n\t\treturn\n\t}\n\taddr := uint32(addr64)\n\n\tcommand := fields[1]\n\targs := fields[2:]\n\tfound := false\n\tfor _, v := range specialsubslist {\n\t\tif command == v.Name {\n\t\t\tf := v.Generator(args)\n\t\t\tif f != nil {\n\t\t\t\tspecialsubs[addr] = f\n\t\t\t}\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tfmt.Fprintf(os.Stderr, \"specialsubs %s: command not found\\n\", command)\n\t}\n}"} {"input": "package models\n\nimport (\n\t\"github.com/astaxie/beego/orm\"\n)\n\ntype PmpCampaignCreative struct {\n\tId int `orm:\"column(id);auto\"`\n\tCampaignId int `orm:\"column(campaign_id)\"`\n\tName string `orm:\"column(name);size(45);null\"`\n\tWidth int `orm:\"column(width);null\"`\n\tHeight int `orm:\"column(height);null\"`\n\tCreativeUrl string `orm:\"column(creative_url);size(255);null\"`\n\tCreativeStatus int `orm:\"column(creative_status);null\"`\n\tLandingUrl string `orm:\"column(landing_url);size(500);null\"`\n\tImpTrackingUrl string `orm:\"column(imp_tracking_url);size(1000);null\"`\n\tClkTrackingUrl string `orm:\"column(clk_tracking_url);size(1000)\"`\n\tDisplayTitle string `orm:\"column(display_title);size(200);null\"`\n\tDisplayText string `orm:\"column(display_text);size(1000);null\"`\n}\n\n\n\nfunc init() {\n\torm.RegisterModel(new(PmpCampaignCreative))\n}\n\nfunc AddPmpCampaignCreative(v *PmpCampaignCreative) (err error) {\n\to := orm.NewOrm()\n\n\t_, err = o.Insert(v)\n\treturn err\n\n}\n\nfunc (t *PmpCampaignCreative) TableName() string ", "output": "{\n\treturn \"pmp_campaign_creative\"\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/tompscanlan/labreserved/models\"\n)\n\n\n\nfunc NewPostItemParams() *PostItemParams {\n\tvar ()\n\treturn &PostItemParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\nfunc NewPostItemParamsWithTimeout(timeout time.Duration) *PostItemParams {\n\tvar ()\n\treturn &PostItemParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype PostItemParams struct {\n\n\tAdditem *models.Item\n\n\ttimeout time.Duration\n}\n\n\n\n\n\nfunc (o *PostItemParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif o.Additem == nil {\n\t\to.Additem = new(models.Item)\n\t}\n\n\tif err := r.SetBodyParam(o.Additem); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (o *PostItemParams) WithAdditem(Additem *models.Item) *PostItemParams ", "output": "{\n\to.Additem = Additem\n\treturn o\n}"} {"input": "package reversereader\n\nimport (\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\ntype ReverseReader struct {\n\treader *os.File\n\toffset int64\n\treadSize int64\n}\n\n\n\n\n\n\n\n\nfunc (r *ReverseReader) Read() (string, error) {\n\tif r.offset < 0 {\n\t\treturn \"\", errors.Wrap(io.EOF, \"at beginning of file\")\n\t}\n\tb := make([]byte, r.readSize)\n\tn, err := r.reader.ReadAt(b, r.offset)\n\tif err != nil && errors.Cause(err) != io.EOF {\n\t\treturn \"\", err\n\t}\n\tif int64(n) < r.readSize {\n\t\tb = b[0:n]\n\t}\n\tr.offset = -r.readSize\n\treturn string(b), nil\n}\n\nfunc NewReverseReader(reader *os.File) (*ReverseReader, error) ", "output": "{\n\tpageSize := int64(os.Getpagesize())\n\tstat, err := reader.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tremainder := stat.Size() % pageSize\n\tend, err := reader.Seek(0, 2)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstartOffset := end - remainder\n\tif startOffset < 0 {\n\t\tstartOffset = 0\n\t}\n\trr := ReverseReader{\n\t\treader: reader,\n\t\toffset: startOffset,\n\t\treadSize: pageSize,\n\t}\n\treturn &rr, nil\n}"} {"input": "package v3\n\nimport (\n\t\"github.com/rancher/norman/lifecycle\"\n\t\"github.com/rancher/norman/resource\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\ntype FeatureLifecycle interface {\n\tCreate(obj *Feature) (runtime.Object, error)\n\tRemove(obj *Feature) (runtime.Object, error)\n\tUpdated(obj *Feature) (runtime.Object, error)\n}\n\ntype featureLifecycleAdapter struct {\n\tlifecycle FeatureLifecycle\n}\n\nfunc (w *featureLifecycleAdapter) HasCreate() bool {\n\to, ok := w.lifecycle.(lifecycle.ObjectLifecycleCondition)\n\treturn !ok || o.HasCreate()\n}\n\nfunc (w *featureLifecycleAdapter) HasFinalize() bool {\n\to, ok := w.lifecycle.(lifecycle.ObjectLifecycleCondition)\n\treturn !ok || o.HasFinalize()\n}\n\nfunc (w *featureLifecycleAdapter) Create(obj runtime.Object) (runtime.Object, error) {\n\to, err := w.lifecycle.Create(obj.(*Feature))\n\tif o == nil {\n\t\treturn nil, err\n\t}\n\treturn o, err\n}\n\nfunc (w *featureLifecycleAdapter) Finalize(obj runtime.Object) (runtime.Object, error) {\n\to, err := w.lifecycle.Remove(obj.(*Feature))\n\tif o == nil {\n\t\treturn nil, err\n\t}\n\treturn o, err\n}\n\nfunc (w *featureLifecycleAdapter) Updated(obj runtime.Object) (runtime.Object, error) {\n\to, err := w.lifecycle.Updated(obj.(*Feature))\n\tif o == nil {\n\t\treturn nil, err\n\t}\n\treturn o, err\n}\n\n\n\nfunc NewFeatureLifecycleAdapter(name string, clusterScoped bool, client FeatureInterface, l FeatureLifecycle) FeatureHandlerFunc ", "output": "{\n\tif clusterScoped {\n\t\tresource.PutClusterScoped(FeatureGroupVersionResource)\n\t}\n\tadapter := &featureLifecycleAdapter{lifecycle: l}\n\tsyncFn := lifecycle.NewObjectLifecycleAdapter(name, clusterScoped, adapter, client.ObjectClient())\n\treturn func(key string, obj *Feature) (runtime.Object, error) {\n\t\tnewObj, err := syncFn(key, obj)\n\t\tif o, ok := newObj.(runtime.Object); ok {\n\t\t\treturn o, err\n\t\t}\n\t\treturn nil, err\n\t}\n}"} {"input": "package x509_test\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t. \"github.com/hyperledger/fabric-ca/lib/client/credential/x509\"\n\t\"github.com/hyperledger/fabric-ca/util\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestNewSigner(t *testing.T) {\n\tcertBytes, err := util.ReadFile(filepath.Join(testDataDir, \"ec256-1-cert.pem\"))\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to read the cert: %s\", err.Error())\n\t}\n\tsigner, err := NewSigner(nil, certBytes)\n\tassert.NoError(t, err, \"NewSigner should not return an error if cert bytes are valid\")\n\n\tassert.NotNil(t, signer.GetX509Cert())\n\tassert.Nil(t, signer.Key())\n\tassert.NotEmpty(t, signer.GetName())\n\t_, err = signer.Attributes()\n\tassert.NoError(t, err)\n}\n\nfunc TestNewSignerError(t *testing.T) ", "output": "{\n\t_, err := NewSigner(nil, []byte{})\n\tassert.Error(t, err, \"NewSigner should return an error if cert byte array is empty\")\n}"} {"input": "package armmanagedservices\n\nconst (\n\tmoduleName = \"armmanagedservices\"\n\tmoduleVersion = \"v0.2.1\"\n)\n\n\ntype MultiFactorAuthProvider string\n\nconst (\n\tMultiFactorAuthProviderAzure MultiFactorAuthProvider = \"Azure\"\n\tMultiFactorAuthProviderNone MultiFactorAuthProvider = \"None\"\n)\n\n\nfunc PossibleMultiFactorAuthProviderValues() []MultiFactorAuthProvider {\n\treturn []MultiFactorAuthProvider{\n\t\tMultiFactorAuthProviderAzure,\n\t\tMultiFactorAuthProviderNone,\n\t}\n}\n\n\nfunc (c MultiFactorAuthProvider) ToPtr() *MultiFactorAuthProvider {\n\treturn &c\n}\n\n\ntype ProvisioningState string\n\nconst (\n\tProvisioningStateAccepted ProvisioningState = \"Accepted\"\n\tProvisioningStateCanceled ProvisioningState = \"Canceled\"\n\tProvisioningStateCreated ProvisioningState = \"Created\"\n\tProvisioningStateCreating ProvisioningState = \"Creating\"\n\tProvisioningStateDeleted ProvisioningState = \"Deleted\"\n\tProvisioningStateDeleting ProvisioningState = \"Deleting\"\n\tProvisioningStateFailed ProvisioningState = \"Failed\"\n\tProvisioningStateNotSpecified ProvisioningState = \"NotSpecified\"\n\tProvisioningStateReady ProvisioningState = \"Ready\"\n\tProvisioningStateRunning ProvisioningState = \"Running\"\n\tProvisioningStateSucceeded ProvisioningState = \"Succeeded\"\n\tProvisioningStateUpdating ProvisioningState = \"Updating\"\n)\n\n\n\n\n\nfunc (c ProvisioningState) ToPtr() *ProvisioningState {\n\treturn &c\n}\n\nfunc PossibleProvisioningStateValues() []ProvisioningState ", "output": "{\n\treturn []ProvisioningState{\n\t\tProvisioningStateAccepted,\n\t\tProvisioningStateCanceled,\n\t\tProvisioningStateCreated,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleted,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateNotSpecified,\n\t\tProvisioningStateReady,\n\t\tProvisioningStateRunning,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateUpdating,\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype RemoveNetworkSecurityGroupSecurityRulesRequest struct {\n\n\tNetworkSecurityGroupId *string `mandatory:\"true\" contributesTo:\"path\" name:\"networkSecurityGroupId\"`\n\n\tRemoveNetworkSecurityGroupSecurityRulesDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype RemoveNetworkSecurityGroupSecurityRulesResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response RemoveNetworkSecurityGroupSecurityRulesResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response RemoveNetworkSecurityGroupSecurityRulesResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package falcon_portal\n\n\n\n\n\n\n\n\n\ntype GrpTpl struct {\n\tGrpID int64 `json:\"grp_id\" gorm:\"column:grp_id\"`\n\tTplID int64 `json:\"tpl_id\" gorm:\"column:tpl_id\"`\n\tBindUser string `json:\"bind_user\" gorm:\"column:bind_user\"`\n}\n\n\n\nfunc (this GrpTpl) TableName() string ", "output": "{\n\treturn \"grp_tpl\"\n}"} {"input": "package rsets\n\nimport (\n\t. \"github.com/pingcap/check\"\n\t\"github.com/pingcap/tidb/expression\"\n\t\"github.com/pingcap/tidb/expression/expressions\"\n\t\"github.com/pingcap/tidb/field\"\n\t\"github.com/pingcap/tidb/model\"\n)\n\nvar _ = Suite(&testHelperSuite{})\n\ntype testHelperSuite struct {\n\tfields []*field.Field\n}\n\nfunc (s *testHelperSuite) SetUpSuite(c *C) {\n\tfldx := &field.Field{Expr: &expressions.Ident{CIStr: model.NewCIStr(\"name\")}, Name: \"a\"}\n\texpr, err := expressions.NewCall(\"count\", []expression.Expression{expressions.Value{Val: 1}}, false)\n\tc.Assert(err, IsNil)\n\tfldy := &field.Field{Expr: expr}\n\n\ts.fields = []*field.Field{fldx, fldy}\n}\n\n\n\nfunc (s *testHelperSuite) TestHasAggFields(c *C) {\n\tok := HasAggFields(s.fields)\n\tc.Assert(ok, IsTrue)\n}\n\nfunc (s *testHelperSuite) TestGetAggFields(c *C) ", "output": "{\n\taggFields := GetAggFields(s.fields)\n\tc.Assert(aggFields, HasLen, 1)\n}"} {"input": "package sync2\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestSemaNoTimeout(t *testing.T) {\n\ts := NewSemaphore(1)\n\ts.Acquire()\n\treleased := false\n\tgo func() {\n\t\ttime.Sleep(10 * time.Millisecond)\n\t\treleased = true\n\t\ts.Release()\n\t}()\n\ts.Acquire()\n\tif !released {\n\t\tt.Errorf(\"want true, got false\")\n\t}\n}\n\n\n\nfunc TestSemaTimeout(t *testing.T) ", "output": "{\n\ts := NewSemaphore(1)\n\ts.Acquire()\n\tgo func() {\n\t\ttime.Sleep(10 * time.Millisecond)\n\t\ts.Release()\n\t}()\n\tif ok := s.AcquireTimeout(5 * time.Millisecond); ok {\n\t\tt.Errorf(\"want false, got true\")\n\t}\n\ttime.Sleep(10 * time.Millisecond)\n\tif ok := s.AcquireTimeout(5 * time.Millisecond); !ok {\n\t\tt.Errorf(\"want true, got false\")\n\t}\n}"} {"input": "package fake\n\nimport (\n\tclientset \"github.com/openshift/client-go/operator/clientset/versioned\"\n\toperatorv1 \"github.com/openshift/client-go/operator/clientset/versioned/typed/operator/v1\"\n\tfakeoperatorv1 \"github.com/openshift/client-go/operator/clientset/versioned/typed/operator/v1/fake\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/watch\"\n\t\"k8s.io/client-go/discovery\"\n\tfakediscovery \"k8s.io/client-go/discovery/fake\"\n\t\"k8s.io/client-go/testing\"\n)\n\n\n\n\n\n\n\n\n\n\ntype Clientset struct {\n\ttesting.Fake\n\tdiscovery *fakediscovery.FakeDiscovery\n}\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\treturn c.discovery\n}\n\nvar _ clientset.Interface = &Clientset{}\n\n\nfunc (c *Clientset) OperatorV1() operatorv1.OperatorV1Interface {\n\treturn &fakeoperatorv1.FakeOperatorV1{Fake: &c.Fake}\n}\n\nfunc NewSimpleClientset(objects ...runtime.Object) *Clientset ", "output": "{\n\to := testing.NewObjectTracker(scheme, codecs.UniversalDecoder())\n\tfor _, obj := range objects {\n\t\tif err := o.Add(obj); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tcs := &Clientset{}\n\tcs.discovery = &fakediscovery.FakeDiscovery{Fake: &cs.Fake}\n\tcs.AddReactor(\"*\", \"*\", testing.ObjectReaction(o))\n\tcs.AddWatchReactor(\"*\", func(action testing.Action) (handled bool, ret watch.Interface, err error) {\n\t\tgvr := action.GetResource()\n\t\tns := action.GetNamespace()\n\t\twatch, err := o.Watch(gvr, ns)\n\t\tif err != nil {\n\t\t\treturn false, nil, err\n\t\t}\n\t\treturn true, watch, nil\n\t})\n\n\treturn cs\n}"} {"input": "package log\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"sync\"\n)\n\nconst (\n\tSilent int = iota\n\tError\n\tInfo\n\tDebug\n)\n\n\nvar (\n\tlevel = Error\n\tlock sync.Mutex\n)\n\n\n\n\n\nfunc Infof(format string, args ...interface{}) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif level < Info {\n\t\treturn\n\t}\n\n\tmsg := fmt.Sprintf(\"INFO: %s\", format)\n\tif len(args) > 0 {\n\t\tmsg = fmt.Sprintf(msg, args...)\n\t}\n\n\tlog.Println(msg)\n}\n\n\nfunc Debugf(format string, args ...interface{}) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif level < Debug {\n\t\treturn\n\t}\n\n\tmsg := fmt.Sprintf(\"DEBUG: %s\", format)\n\tif len(args) > 0 {\n\t\tmsg = fmt.Sprintf(msg, args...)\n\t}\n\n\tlog.Println(msg)\n}\n\n\nfunc Errorf(format string, args ...interface{}) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif level < Error {\n\t\treturn\n\t}\n\n\tmsg := fmt.Sprintf(\"ERROR: %s\", format)\n\tif len(args) > 0 {\n\t\tmsg = fmt.Sprintf(msg, args...)\n\t}\n\n\tlog.Println(msg)\n}\n\nfunc SetLevel(l int) ", "output": "{\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tlevel = l\n}"} {"input": "package config\n\nimport (\n\t\"sync\"\n)\n\n\n\n\n\n\ntype delayedEnvironment struct {\n\tenv Environment\n\tloading sync.Mutex\n\tcallback func() Environment\n}\n\n\n\n\n\n\n\nfunc (e *delayedEnvironment) GetAll(key string) []string {\n\te.Load()\n\treturn e.env.GetAll(key)\n}\n\n\n\nfunc (e *delayedEnvironment) Bool(key string, def bool) bool {\n\te.Load()\n\treturn e.env.Bool(key, def)\n}\n\n\n\nfunc (e *delayedEnvironment) Int(key string, def int) int {\n\te.Load()\n\treturn e.env.Int(key, def)\n}\n\n\nfunc (e *delayedEnvironment) All() map[string][]string {\n\te.Load()\n\treturn e.env.All()\n}\n\n\n\n\n\n\n\n\nfunc (e *delayedEnvironment) Load() {\n\te.loading.Lock()\n\tdefer e.loading.Unlock()\n\n\tif e.env != nil {\n\t\treturn\n\t}\n\n\te.env = e.callback()\n}\n\nfunc (e *delayedEnvironment) Get(key string) (string, bool) ", "output": "{\n\te.Load()\n\treturn e.env.Get(key)\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\n\t\"github.com/rackspace/gophercloud\"\n\t\"github.com/rackspace/gophercloud/openstack\"\n)\n\ntype identity struct {\n\tscV3 *gophercloud.ServiceClient\n}\n\ntype identityConfig struct {\n\tendpoint string\n\tserviceUserName string\n\tservicePassword string\n}\n\n\n\nfunc newIdentityClient(config identityConfig) (*identity, error) ", "output": "{\n\topt := gophercloud.AuthOptions{\n\t\tIdentityEndpoint: config.endpoint + \"/v3/\",\n\t\tUsername: config.serviceUserName,\n\t\tPassword: config.servicePassword,\n\t\tTenantName: \"service\",\n\t\tDomainID: \"default\",\n\t\tAllowReauth: true,\n\t}\n\tprovider, err := openstack.AuthenticatedClient(opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tv3client := openstack.NewIdentityV3(provider)\n\tif v3client == nil {\n\t\treturn nil, errors.New(\"Unable to get keystone V3 client\")\n\t}\n\n\tid := &identity{\n\t\tscV3: v3client,\n\t}\n\n\treturn id, err\n}"} {"input": "package middleware\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/jtmelton/appsensor-reverse-proxy/Godeps/_workspace/src/github.com/golang/glog\"\n\t\"github.com/jtmelton/appsensor-reverse-proxy/blocks\"\n\t\"github.com/jtmelton/appsensor-reverse-proxy/connections\"\n)\n\n\n\nfunc Block(next http.Handler) http.Handler ", "output": "{\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\tip := connections.FindIp(r)\n\t\tresource := r.URL.Path\n\n\t\tshouldBlock := false\n\n\t\tfor _, element := range blocks.StoredBlocks.Flatten() {\n\n\t\t\tvar block blocks.Block\n\n\t\t\tif err := json.Unmarshal([]byte(element.(string)), &block); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tif block.Applies(ip, resource, time.Now()) {\n\t\t\t\tshouldBlock = true\n\t\t\t\tglog.Info(\"Found a matching block - denying request: \", block)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t}\n\n\t\tif shouldBlock {\n\n\t\t\tw.WriteHeader(http.StatusForbidden)\n\t\t\tw.Write([]byte(\"Access Denied\"))\n\n\t\t} else {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t}\n\n\t})\n}"} {"input": "package dexcom\n\nimport (\n\t\"math\"\n)\n\n\n\nfunc marshalUint16(n uint16) []byte {\n\treturn []byte{byte(n & 0xFF), byte(n >> 8)}\n}\n\n\nfunc marshalInt16(n int16) []byte {\n\treturn marshalUint16(uint16(n))\n}\n\nfunc marshalUint32(n uint32) []byte {\n\treturn append(marshalUint16(uint16(n&0xFFFF)), marshalUint16(uint16(n>>16))...)\n}\n\nfunc marshalInt32(n int32) []byte {\n\treturn marshalUint32(uint32(n))\n}\n\nfunc unmarshalUint16(v []byte) uint16 {\n\treturn uint16(v[0]) | uint16(v[1])<<8\n}\n\n\nfunc unmarshalInt16(v []byte) int16 {\n\treturn int16(unmarshalUint16(v))\n}\n\nfunc unmarshalUint32(v []byte) uint32 {\n\treturn uint32(unmarshalUint16(v[0:2])) | uint32(unmarshalUint16(v[2:4]))<<16\n}\n\nfunc unmarshalInt32(v []byte) int32 {\n\treturn int32(unmarshalUint32(v))\n}\n\n\n\nfunc unmarshalFloat64(v []byte) float64 {\n\treturn math.Float64frombits(unmarshalUint64(v))\n}\n\nfunc unmarshalUint64(v []byte) uint64 ", "output": "{\n\treturn uint64(unmarshalUint32(v[0:4])) | uint64(unmarshalUint32(v[4:8]))<<32\n}"} {"input": "package screepsws\n\nimport \"fmt\"\n\n\n\nfunc (ws *webSocket) UnsubscribeRoom(shard, room string) error {\n\treturn ws.Unsubscribe(fmt.Sprintf(roomFormat, shard, room))\n}\n\nfunc (ws *webSocket) SubscribeRoomMap(shard, room string) (<-chan RoomMapResponse, error) {\n\tchannel := fmt.Sprintf(roomMapFormat, shard, room)\n\tdataChan, err := ws.Subscribe(channel)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to subscribe to '%s'\", channel)\n\t}\n\n\trespChan := make(chan RoomMapResponse)\n\tgo func() {\n\t\tdefer close(respChan)\n\t\tfor data := range dataChan {\n\t\t\tresp := RoomMapResponse{}\n\t\t\tclosed := UnmarshalResponse(data, &resp)\n\t\t\tif closed {\n\t\t\t\treturn\n\t\t\t}\n\t\t\trespChan <- resp\n\t\t}\n\t}()\n\n\treturn respChan, nil\n}\n\nfunc (ws *webSocket) UnsubscribeRoomMap(shard, room string) error {\n\treturn ws.Unsubscribe(fmt.Sprintf(roomMapFormat, shard, room))\n}\n\nfunc (ws *webSocket) SubscribeRoom(shard, room string) (<-chan RoomResponse, error) ", "output": "{\n\tchannel := fmt.Sprintf(roomFormat, shard, room)\n\tdataChan, err := ws.Subscribe(channel)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to subscribe to '%s'\", channel)\n\t}\n\n\trespChan := make(chan RoomResponse)\n\tgo func() {\n\t\tdefer close(respChan)\n\t\tfor data := range dataChan {\n\t\t\tresp := RoomResponse{}\n\t\t\tclosed := UnmarshalResponse(data, &resp)\n\t\t\tif closed {\n\t\t\t\treturn\n\t\t\t}\n\t\t\trespChan <- resp\n\t\t}\n\t}()\n\n\treturn respChan, nil\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\n\n\ntype CommonTests struct {\n\tout *bytes.Buffer\n\td *Dispatcher\n}\n\nvar _ = Suite(&CommonTests{})\n\nfunc (t *CommonTests) SetUpTest(c *C) {\n\tt.out = new(bytes.Buffer)\n\tt.d = &Dispatcher{stderr: t.out}\n}\n\nfunc removeFilesInDir(dir string) error {\n\tfiles, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, file := range files {\n\t\tpath := filepath.Join(dir, file.Name())\n\t\terr = os.Remove(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc Test(t *testing.T) ", "output": "{\n\tTestingT(t)\n}"} {"input": "package models\n\nimport (\n\t\"fmt\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\n\nvar goBgpValidator *goBgpScopeValidator\n\n\n\n\n\ntype goBgpScopeValidator struct {\n\tmitigationScopeValidatorBase\n}\n\n\nfunc (v *goBgpScopeValidator) ValidateUri(customer *Customer, scope *MitigationScope) (errMsg string) {\n\tif len(scope.URI.List()) != 0 {\n\t\terrMsg = fmt.Sprintf(\"invalid uri: %+v\", scope.URI.List())\n\t\tlog.Warn(errMsg)\n\t\treturn\n\t}\n\treturn\n}\n\nfunc init() ", "output": "{\n\tgoBgpValidator = &goBgpScopeValidator{}\n}"} {"input": "package util\n\nimport (\n\t\"net\"\n)\n\n\n\nfunc IpIsIPv4(ip net.IP) bool ", "output": "{\n\tp4 := ip.To4()\n\treturn len(p4) == net.IPv4len\n}"} {"input": "package sql\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/cockroachdb/cockroach/pkg/roachpb\"\n\t\"github.com/cockroachdb/cockroach/pkg/sql/parser\"\n\t\"github.com/cockroachdb/cockroach/pkg/sql/sqlbase\"\n)\n\n\n\n\ntype delayedNode struct {\n\tname string\n\tcolumns sqlbase.ResultColumns\n\tconstructor nodeConstructor\n\tplan planNode\n}\n\ntype nodeConstructor func(context.Context, *planner) (planNode, error)\n\n\n\nfunc (d *delayedNode) Columns() sqlbase.ResultColumns { return d.columns }\nfunc (d *delayedNode) Ordering() orderingInfo { return orderingInfo{} }\nfunc (d *delayedNode) MarkDebug(_ explainMode) {}\nfunc (d *delayedNode) Start(ctx context.Context) error { return d.plan.Start(ctx) }\nfunc (d *delayedNode) Next(ctx context.Context) (bool, error) { return d.plan.Next(ctx) }\nfunc (d *delayedNode) Values() parser.Datums { return d.plan.Values() }\nfunc (d *delayedNode) DebugValues() debugValues { return d.plan.DebugValues() }\nfunc (d *delayedNode) Spans(ctx context.Context) (_, _ roachpb.Spans, _ error) {\n\treturn d.plan.Spans(ctx)\n}\n\nfunc (d *delayedNode) Close(ctx context.Context) ", "output": "{\n\tif d.plan != nil {\n\t\td.plan.Close(ctx)\n\t\td.plan = nil\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n)\n\n \n\nfunc main() {\n\n\tvar i, j, k, l int = 0, 0, 0, 0\n\treader := bufio.NewReader(os.Stdin)\n\tinput, _ := reader.ReadString('\\n')\n\n\tfor _, rune := range input {\n\t\tswitch {\n\t\tcase (rune >= 'A' && rune <= 'Z'):\n\t\t\ti++\n\t\tcase (rune >= 'a' && rune <= 'z'):\n\t\t\tj++\n\t\tcase (rune == ' ' || rune == '\\n'):\n\t\t\tk++\n\t\tcase (rune >= '0' && rune <= '9'):\n\t\t\tl++\n\t\tdefault:\n\t\t\ti++\n\t\t}\n\t}\n\n\tfmt.Printf(\"BAl:%d SAl:%d SP:%d NUM:%d\\n\", i, j, k, l)\n\tfmt.Printf(\"-------\\n\")\n\n\tvar m int\n\n\t_, err := fmt.Scanf(\"%d\", &m)\n\n\tif err != nil {\n\t\tfmt.Printf(\"输入有异常\")\n\t\treturn\n\t}\n\n\tfor {\n\n\t\tfmt.Printf(\"%d\\n\", m)\n\n\t\tswitch m {\n\t\tcase 1:\n\t\tcase 2:\n\t\tcase 3:\n\t\tdefault:\n\t\t\tfmt.Printf(\"ccc\")\n\t\t}\n\n\t\tbreak\n\t}\n}\n\nfunc menu() ", "output": "{\n\tfmt.Printf(\"=%-10s\\n\", \"1.\tID\")\n\tfmt.Printf(\"=%-10s\\n\", \"2. Menu\")\n\tfmt.Printf(\"=%-10s\\n\", \"3. other\")\n\tfmt.Printf(\"=%-10s\\n\", \"4. exit\")\n\n}"} {"input": "package slack\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\ntype Adapter struct {\n\tcnf *Config\n}\n\n\n\n\n\nfunc (a *Adapter) SendMessage(channel, username, text, emoji string) error {\n\tpayload := map[string]string{\n\t\t\"text\": text,\n\t}\n\tif emoji != \"\" {\n\t\tpayload[\"icon_emoji\"] = emoji\n\t}\n\tif channel != \"\" {\n\t\tpayload[\"channel\"] = channel\n\t}\n\tif username != \"\" {\n\t\tpayload[\"username\"] = username\n\t}\n\n\tpayloadJSON, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp, err := http.PostForm(\n\t\ta.cnf.IncomingWebhook,\n\t\turl.Values{\n\t\t\t\"payload\": {string(payloadJSON)},\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn fmt.Errorf(\"Send Slack Message Error: %s\", string(body))\n\t}\n\treturn nil\n}\n\nfunc NewAdapter(cnf *Config) *Adapter ", "output": "{\n\treturn &Adapter{\n\t\tcnf: cnf,\n\t}\n}"} {"input": "package token\n\nimport (\n\t\"time\"\n\n\t\"github.com/plimble/clover/oauth2\"\n)\n\ntype ClientCredentialsGrantType struct {\n\tAccessTokenLifespan int\n}\n\nfunc (g *ClientCredentialsGrantType) GrantRequest(req *TokenHandlerRequest, client *oauth2.Client, storage oauth2.Storage) (*GrantData, error) {\n\tif client.Public {\n\t\treturn nil, InvalidClient(\"public client is not allowed for client_credential grant type\")\n\t}\n\n\treturn &GrantData{\n\t\tScopes: client.Scopes,\n\t\tAccessTokenLifespan: g.AccessTokenLifespan,\n\t\tIncludeRefreshToken: false,\n\t}, nil\n}\n\nfunc (g *ClientCredentialsGrantType) Name() string {\n\treturn \"client_credentials\"\n}\n\n\n\nfunc (g *ClientCredentialsGrantType) CreateToken(grantData *GrantData, client *oauth2.Client, storage oauth2.Storage, tokenGen oauth2.TokenGenerator) (string, string, error) ", "output": "{\n\tatoken, err := tokenGen.CreateAccessToken(&oauth2.CreateAccessTokenRequest{\n\t\tClientID: client.ID,\n\t\tScopes: grantData.Scopes,\n\t\tExpiresIn: grantData.AccessTokenLifespan,\n\t\tExtras: grantData.Extras,\n\t})\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tat := &oauth2.AccessToken{\n\t\tAccessToken: atoken,\n\t\tClientID: client.ID,\n\t\tScopes: grantData.Scopes,\n\t\tExpired: time.Now().UTC().Add(time.Second * time.Duration(grantData.AccessTokenLifespan)).Unix(),\n\t\tExpiresIn: grantData.AccessTokenLifespan,\n\t\tExtras: grantData.Extras,\n\t}\n\n\tif err = storage.SaveAccessToken(at); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\treturn atoken, \"\", nil\n}"} {"input": "package algorithm\n\n\n\n\n\nfunc Sort(arr []byte, start, end int) ", "output": "{\n\tif start < end {\n\t\ti, j := start, end\n\t\tkey := arr[(start+end)/2]\n\t\tfor i <= j {\n\t\t\tfor arr[i] < key {\n\t\t\t\ti++\n\t\t\t}\n\t\t\tfor arr[j] > key {\n\t\t\t\tj--\n\t\t\t}\n\t\t\tif i <= j {\n\t\t\t\tarr[i], arr[j] = arr[j], arr[i]\n\t\t\t\ti++\n\t\t\t\tj--\n\t\t\t}\n\t\t}\n\t\tif start < j {\n\t\t\tSort(arr, start, j)\n\t\t}\n\t\tif end > i {\n\t\t\tSort(arr, i, end)\n\t\t}\n\t}\n}"} {"input": "package objects\n\nimport \"strings\"\n\nconst (\n\tPREFIX_FADERDATATYPE = \"application/fader.datatypes.\"\n\n\tInvalidObject ObjectType = \"\"\n\tBlobObject ObjectType = \"blob\"\n\tUserObject ObjectType = \"user\"\n)\n\n\n\ntype ObjectType string\n\n\n\nfunc (t ObjectType) Bytes() []byte {\n\treturn []byte(t.String())\n}\n\n\n\ntype ContentType string\n\nvar (\n\tTUnknown ContentType = \"application/fader.dt.unknown\"\n\tTString ContentType = \"application/fader.dt.string\"\n\tTNumber ContentType = \"application/fader.dt.number\"\n\tTBool ContentType = \"application/fader.dt.bool\"\n\tTArray ContentType = \"application/fader.dt.array\"\n\tTMap ContentType = \"application/fader.dt.map\"\n\tTCustom ContentType = \"application/fader.dt.custom.\"\n)\n\nfunc TypeFrom(v interface{}) (t ContentType) {\n\tswitch v.(type) {\n\tcase float32, float64, int, int32, int64:\n\t\treturn TNumber\n\tcase string:\n\t\treturn TString\n\tcase bool:\n\t\treturn TBool\n\tcase []interface{}:\n\t\treturn TArray\n\tcase map[string]interface{}:\n\t\treturn TMap\n\t}\n\n\treturn TUnknown\n}\n\nfunc (t ContentType) String() string {\n\treturn string(t)\n}\n\nfunc (t ContentType) Valid() bool {\n\treturn strings.HasPrefix(t.String(), PREFIX_FADERDATATYPE)\n}\n\nfunc (t ContentType) Equal(v ContentType) bool {\n\treturn t == v\n}\n\nfunc (t ObjectType) String() string ", "output": "{\n\treturn string(t)\n}"} {"input": "package treemap\n\nimport \"github.com/emirpasic/gods/containers\"\n\nfunc assertSerializationImplementation() {\n\tvar _ containers.JSONSerializer = (*Map)(nil)\n\tvar _ containers.JSONDeserializer = (*Map)(nil)\n}\n\n\n\n\n\nfunc (m *Map) FromJSON(data []byte) error {\n\treturn m.tree.FromJSON(data)\n}\n\nfunc (m *Map) ToJSON() ([]byte, error) ", "output": "{\n\treturn m.tree.ToJSON()\n}"} {"input": "package zone\n\nimport \"github.com/miekg/dns\"\n\n\n\n\nfunc SetTTL(records []dns.RR, ttl uint32) []dns.RR ", "output": "{\n\tfor i, _ := range records {\n\t\trecords[i].Header().Ttl = ttl\n\t}\n\n\treturn records\n}"} {"input": "package animation\n\nimport (\n\t\"time\"\n)\n\ntype GroupedAnimation struct {\n\tanimators []Animator\n\tcallback AnimatorCallback\n}\n\nfunc NewGroupedAnimation(animators []Animator) *GroupedAnimation {\n\treturn &GroupedAnimation{animators, nil}\n}\n\n\n\nfunc (a *GroupedAnimation) IsDone() bool {\n\tvar done = true\n\tfor _, animator := range a.animators {\n\t\tif !animator.IsDone() {\n\t\t\tdone = false\n\t\t}\n\t}\n\treturn done\n}\n\nfunc (a *GroupedAnimation) Update(elapsed time.Duration) time.Duration {\n\tvar (\n\t\ttotal time.Duration\n\t\tremainder time.Duration\n\t\tdone = true\n\t)\n\tfor _, animator := range a.animators {\n\t\tremainder = animator.Update(elapsed)\n\t\tif !animator.IsDone() {\n\t\t\tdone = false\n\t\t}\n\t\tif remainder != 0 && (total == 0 || remainder < total) {\n\t\t\ttotal = remainder \n\t\t}\n\t}\n\tif done {\n\t\tif a.callback != nil {\n\t\t\ta.callback()\n\t\t}\n\t\treturn total\n\t}\n\treturn 0\n}\n\nfunc (a *GroupedAnimation) Reset() {\n\tfor _, animator := range a.animators {\n\t\tanimator.Reset()\n\t}\n}\n\nfunc (a *GroupedAnimation) Delete() {\n\tfor _, animator := range a.animators {\n\t\tanimator.Delete()\n\t}\n\ta.animators = []Animator{}\n}\n\nfunc (a *GroupedAnimation) SetCallback(callback AnimatorCallback) ", "output": "{\n\ta.callback = callback\n}"} {"input": "package eav\n\ntype (\n\tAttributeFrontendModeller interface {\n\t\tInputRenderer() FrontendInputRendererIFace\n\t\tGetValue()\n\t\tGetInputType() string\n\n\t\tConfig(...AttributeFrontendConfig) AttributeFrontendModeller\n\t}\n\tFrontendInputRendererIFace interface {\n\t}\n\tAttributeFrontend struct {\n\t\ta *Attribute\n\t\tidx AttributeIndex\n\t}\n\tAttributeFrontendConfig func(*AttributeFrontend)\n)\n\nvar _ AttributeFrontendModeller = (*AttributeFrontend)(nil)\n\n\nfunc NewAttributeFrontend(cfgs ...AttributeFrontendConfig) *AttributeFrontend {\n\tas := &AttributeFrontend{\n\t\ta: nil,\n\t}\n\tas.Config(cfgs...)\n\treturn as\n}\n\n\nfunc AttributeFrontendIdx(i AttributeIndex) AttributeFrontendConfig {\n\treturn func(as *AttributeFrontend) {\n\t\tas.idx = i\n\t}\n}\n\n\nfunc (af *AttributeFrontend) Config(configs ...AttributeFrontendConfig) AttributeFrontendModeller {\n\tfor _, cfg := range configs {\n\t\tcfg(af)\n\t}\n\treturn af\n}\n\n\nfunc (af *AttributeFrontend) GetValue() {}\nfunc (af *AttributeFrontend) GetInputType() string {\n\treturn af.a.FrontendInput()\n}\n\nfunc (af *AttributeFrontend) InputRenderer() FrontendInputRendererIFace ", "output": "{ return nil }"} {"input": "package gramework\n\nimport \"strings\"\n\n\n\nfunc toLower(s string) string ", "output": "{\n\treturn strings.ToLower(s)\n}"} {"input": "package mocks\n\nimport (\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n\tremotecommand \"k8s.io/client-go/tools/remotecommand\"\n)\n\n\ntype MockExecutor struct {\n\tctrl *gomock.Controller\n\trecorder *MockExecutorMockRecorder\n}\n\n\ntype MockExecutorMockRecorder struct {\n\tmock *MockExecutor\n}\n\n\nfunc NewMockExecutor(ctrl *gomock.Controller) *MockExecutor {\n\tmock := &MockExecutor{ctrl: ctrl}\n\tmock.recorder = &MockExecutorMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockExecutor) EXPECT() *MockExecutorMockRecorder {\n\treturn m.recorder\n}\n\n\nfunc (m *MockExecutor) Stream(arg0 remotecommand.StreamOptions) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Stream\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}\n\n\n\n\nfunc (mr *MockExecutorMockRecorder) Stream(arg0 interface{}) *gomock.Call ", "output": "{\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Stream\", reflect.TypeOf((*MockExecutor)(nil).Stream), arg0)\n}"} {"input": "package sarama\n\n\ntype ApiVersionsRequest struct{}\n\n\n\nfunc (a *ApiVersionsRequest) decode(pd packetDecoder, version int16) (err error) {\n\treturn nil\n}\n\nfunc (a *ApiVersionsRequest) key() int16 {\n\treturn 18\n}\n\nfunc (a *ApiVersionsRequest) version() int16 {\n\treturn 0\n}\n\nfunc (a *ApiVersionsRequest) headerVersion() int16 {\n\treturn 1\n}\n\nfunc (a *ApiVersionsRequest) requiredVersion() KafkaVersion {\n\treturn V0_10_0_0\n}\n\nfunc (a *ApiVersionsRequest) encode(pe packetEncoder) error ", "output": "{\n\treturn nil\n}"} {"input": "package vppcalls\n\nimport (\n\t\"errors\"\n\n\tl2ba \"github.com/ligato/vpp-agent/plugins/vpp/binapi/l2\"\n)\n\n\nfunc (h *XConnectVppHandler) AddL2XConnect(rxIface, txIface string) error {\n\treturn h.addDelXConnect(rxIface, txIface, true)\n}\n\n\n\n\nfunc (h *XConnectVppHandler) addDelXConnect(rxIface, txIface string, enable bool) error {\n\trxIfaceMeta, found := h.ifIndexes.LookupByName(rxIface)\n\tif !found {\n\t\treturn errors.New(\"failed to get Rx interface metadata\")\n\t}\n\n\ttxIfaceMeta, found := h.ifIndexes.LookupByName(txIface)\n\tif !found {\n\t\treturn errors.New(\"failed to get Tx interface metadata\")\n\t}\n\n\treq := &l2ba.SwInterfaceSetL2Xconnect{\n\t\tEnable: boolToUint(enable),\n\t\tTxSwIfIndex: txIfaceMeta.GetIndex(),\n\t\tRxSwIfIndex: rxIfaceMeta.GetIndex(),\n\t}\n\treply := &l2ba.SwInterfaceSetL2XconnectReply{}\n\n\tif err := h.callsChannel.SendRequest(req).ReceiveReply(reply); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (h *XConnectVppHandler) DeleteL2XConnect(rxIface, txIface string) error ", "output": "{\n\treturn h.addDelXConnect(rxIface, txIface, false)\n}"} {"input": "package manifestparser\n\nimport (\n\t\"errors\"\n\t\"io/ioutil\"\n\n\tyaml \"gopkg.in/yaml.v2\"\n)\n\ntype Application struct {\n\tName string `yaml:\"name\"`\n}\n\ntype Parser struct {\n\tPathToManifest string\n\n\tApplications []Application\n\n\trawManifest []byte\n}\n\n\n\nfunc (parser *Parser) Parse(manifestPath string) error {\n\tbytes, err := ioutil.ReadFile(manifestPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparser.rawManifest = bytes\n\n\tvar raw struct {\n\t\tApplications []Application `yaml:\"applications\"`\n\t}\n\n\terr = yaml.Unmarshal(bytes, &raw)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tparser.Applications = raw.Applications\n\n\tif len(parser.Applications) == 0 {\n\t\treturn errors.New(\"must have at least one application\")\n\t}\n\n\tfor _, application := range parser.Applications {\n\t\tif application.Name == \"\" {\n\t\t\treturn errors.New(\"Found an application with no name specified\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (parser Parser) AppNames() []string {\n\tvar names []string\n\tfor _, app := range parser.Applications {\n\t\tnames = append(names, app.Name)\n\t}\n\treturn names\n}\n\nfunc (parser Parser) RawManifest(_ string) ([]byte, error) {\n\treturn parser.rawManifest, nil\n}\n\nfunc NewParser() *Parser ", "output": "{\n\treturn new(Parser)\n}"} {"input": "package abac\n\n\n\n\nimport (\n\t\"bufio\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"os\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/auth/authorizer\"\n)\n\n\n\n\n\n\n\n\n\ntype policy struct {\n\tUser string `json:\"user,omitempty\"`\n\tGroup string `json:\"group,omitempty\"`\n\n\n\tReadonly bool `json:\"readonly,omitempty\"`\n\tResource string `json:\"resource,omitempty\"`\n\tNamespace string `json:\"namespace,omitempty\"`\n\n\n\n}\n\ntype policyList []policy\n\n\n\n\nfunc (p policy) matches(a authorizer.Attributes) bool {\n\tif p.subjectMatches(a) {\n\t\tif p.Readonly == false || (p.Readonly == a.IsReadOnly()) {\n\t\t\tif p.Resource == \"\" || (p.Resource == a.GetResource()) {\n\t\t\t\tif p.Namespace == \"\" || (p.Namespace == a.GetNamespace()) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p policy) subjectMatches(a authorizer.Attributes) bool {\n\tif p.User != \"\" {\n\t\tif p.User != a.GetUserName() {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif p.Group != \"\" {\n\t\tfor _, group := range a.GetGroups() {\n\t\t\tif p.Group == group {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\nfunc (pl policyList) Authorize(a authorizer.Attributes) error {\n\tfor _, p := range pl {\n\t\tif p.matches(a) {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn errors.New(\"No policy matched.\")\n}\n\nfunc NewFromFile(path string) (policyList, error) ", "output": "{\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\tpl := make(policyList, 0)\n\n\tfor scanner.Scan() {\n\t\tvar p policy\n\t\tb := scanner.Bytes()\n\t\terr = json.Unmarshal(b, &p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpl = append(pl, p)\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn pl, nil\n}"} {"input": "package lago\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype ScopedLogger struct {\n\tlog Logger\n\tscp string\n\tfmt string\n}\n\n\nfunc NewScopedLogger(log Logger, scope string, padding int) *ScopedLogger {\n\tformat := \"-%\" + intToStringWithSign(padding) + \"s: %s\"\n\n\tl := &ScopedLogger{\n\t\tlog: log,\n\t\tscp: scope,\n\t\tfmt: format,\n\t}\n\n\treturn l\n}\n\n\nfunc (l *ScopedLogger) Errorf(format string, args ...interface{}) {\n\tl.log.Errorf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\n\nfunc (l *ScopedLogger) Infof(format string, args ...interface{}) {\n\tl.log.Infof(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\n\nfunc (l *ScopedLogger) Warnf(format string, args ...interface{}) {\n\tl.log.Warnf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\n\n\n\nfunc intToStringWithSign(i int) string {\n\ta := strconv.Itoa(i)\n\ts := \"+\"\n\tif i < 0 {\n\t\ts = \"-\"\n\t}\n\ta = s + a\n\n\treturn a\n}\n\nfunc (l *ScopedLogger) Fatalf(format string, args ...interface{}) ", "output": "{\n\tl.log.Fatalf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}"} {"input": "package auction\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestAuction_Joining(t *testing.T) {\n\ta := &auction{}\n\n\tactual := reflect.ValueOf(joining(a))\n\texpected := reflect.ValueOf(bidding)\n\n\tif actual.Pointer() != expected.Pointer() {\n\t\tt.Errorf(\"Expected; %v, got; %v\", actual, expected)\n\t}\n\n}\n\n\n\nfunc TestStateMachine(t *testing.T) {\n\ttests := []struct {\n\t\tdescription string\n\t\tbidPrice float32\n\t\tmaxBid float32\n\t\tcurrentStatus string\n\t\texpectedStatus string\n\t\tstartStateFn stateFn\n\t\tnextStateFn stateFn\n\t}{\n\t\t{\n\t\t\tdescription: \"bidding: bid price equal to max bid\",\n\t\t\tbidPrice: 100,\n\t\t\tmaxBid: 100,\n\t\t\tcurrentStatus: \"BIDDING\",\n\t\t\texpectedStatus: \"WON\",\n\t\t\tstartStateFn: bidding,\n\t\t\tnextStateFn: winning,\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\ta := &auction{\n\t\t\tstatus: tc.currentStatus,\n\t\t\tmaxBid: tc.maxBid,\n\t\t\tbidPrice: tc.bidPrice,\n\t\t}\n\n\t\tactualFn := reflect.ValueOf(tc.startStateFn(a))\n\t\texpectedFn := reflect.ValueOf(tc.nextStateFn)\n\n\t\tif actualFn.Pointer() != expectedFn.Pointer() {\n\t\t\tt.Errorf(\"Expected; %v, got; %v\", expectedFn, actualFn)\n\t\t}\n\n\n\t\tif actual := a.Status(); actual != tc.expectedStatus {\n\t\t\tt.Errorf(\"Expected; %v, got; %v\", tc.expectedStatus, actual)\n\t\t}\n\t}\n}\n\nfunc TestAuction_Bidding_AnnounceClosed(t *testing.T) ", "output": "{\n\ta := &auction{}\n\n\ta.AnnounceClosed()\n\n\texpected := \"CLOSED\"\n\tif actual := a.Status(); actual != expected {\n\t\tt.Errorf(\"Expected; %v, got; %v\", expected, actual)\n\t}\n\n\tactual := reflect.ValueOf(bidding(a))\n\texpectedFn := reflect.ValueOf(lost)\n\n\tif actual.Pointer() != expectedFn.Pointer() {\n\t\tt.Errorf(\"Expected; %v, got; %v\", expectedFn, actual)\n\t}\n}"} {"input": "package main\n\nimport \"testing\"\n\n\n\nfunc TestTriplets(t *testing.T) ", "output": "{\n\tcases := []struct {\n\t\ta int\n\t\tb int\n\t\tapoints [3]byte\n\t\tbpoints [3]byte\n\t}{\n\t\t{1, 1, [3]byte{5, 6, 7}, [3]byte{3, 6, 10}},\n\t}\n\n\tfor _, c := range cases {\n\t\tif a, b := CalcPoints(c.apoints, c.bpoints); a != c.a || c.b != b {\n\t\t\tt.Errorf(\"Expected %d %d, got %d %d\", c.a, c.b, a, b)\n\t\t}\n\t}\n}"} {"input": "package ls\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/list\"\n\t\"github.com/vmware/govmomi/vim25/mo\"\n\t\"golang.org/x/net/context\"\n)\n\ntype ls struct {\n\t*flags.DatacenterFlag\n\n\tLong bool\n}\n\nfunc init() {\n\tcli.Register(\"ls\", &ls{})\n}\n\nfunc (cmd *ls) Register(f *flag.FlagSet) {\n\tf.BoolVar(&cmd.Long, \"l\", false, \"Long listing format\")\n}\n\nfunc (cmd *ls) Process() error { return nil }\n\nfunc (cmd *ls) Usage() string {\n\treturn \"[PATH]...\"\n}\n\nfunc (cmd *ls) Run(f *flag.FlagSet) error {\n\tfinder, err := cmd.Finder()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlr := listResult{\n\t\tElements: nil,\n\t\tLong: cmd.Long,\n\t}\n\n\targs := f.Args()\n\tif len(args) == 0 {\n\t\targs = []string{\".\"}\n\t}\n\n\tfor _, arg := range args {\n\t\tes, err := finder.ManagedObjectListChildren(context.TODO(), arg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlr.Elements = append(lr.Elements, es...)\n\t}\n\n\treturn cmd.WriteResult(lr)\n}\n\ntype listResult struct {\n\tElements []list.Element `json:\"elements\"`\n\n\tLong bool `json:\"-\"`\n}\n\n\n\nfunc (l listResult) Write(w io.Writer) error ", "output": "{\n\tvar err error\n\n\tfor _, e := range l.Elements {\n\t\tif !l.Long {\n\t\t\tfmt.Fprintf(w, \"%s\\n\", e.Path)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch e.Object.(type) {\n\t\tcase mo.Folder:\n\t\t\tif _, err = fmt.Fprintf(w, \"%s/\\n\", e.Path); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tif _, err = fmt.Fprintf(w, \"%s (%s)\\n\", e.Path, e.Object.Reference().Type); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package middleware\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"context\"\n\n\t\"github.com/remind101/pkg/httpx\"\n)\n\n\n\nfunc TestErrorWithHandler(t *testing.T) ", "output": "{\n\tvar called bool\n\tboomErr := errors.New(\"boom\")\n\n\th := &Error{\n\t\tErrorHandler: func(ctx context.Context, err error, w http.ResponseWriter, r *http.Request) {\n\t\t\tcalled = true\n\t\t},\n\t\thandler: httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\t\t\treturn boomErr\n\t\t}),\n\t}\n\n\tctx := context.Background()\n\treq, _ := http.NewRequest(\"GET\", \"/path\", nil)\n\tresp := httptest.NewRecorder()\n\n\terr := h.ServeHTTPContext(ctx, resp, req)\n\tif err != boomErr {\n\t\tt.Fatal(\"Expected error to be returned\")\n\t}\n\n\tif !called {\n\t\tt.Fatal(\"Expected the error handler to be called\")\n\t}\n}"} {"input": "package chart\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\tassert \"github.com/blendlabs/go-assert\"\n)\n\nfunc TestSequenceFloat64(t *testing.T) {\n\tassert := assert.New(t)\n\n\tasc := Sequence.Float64(1.0, 10.0)\n\tassert.Len(asc, 10)\n\n\tdesc := Sequence.Float64(10.0, 1.0)\n\tassert.Len(desc, 10)\n}\n\n\n\nfunc TestSequenceMarketQuarters(t *testing.T) {\n\tassert := assert.New(t)\n\ttoday := time.Date(2016, 07, 01, 12, 0, 0, 0, Date.Eastern())\n\tmh := Sequence.MarketHourQuarters(today, today, NYSEOpen, NYSEClose, Date.IsNYSEHoliday)\n\tassert.Len(mh, 4)\n\tassert.Equal(9, mh[0].Hour())\n\tassert.Equal(30, mh[0].Minute())\n\tassert.Equal(Date.Eastern(), mh[0].Location())\n\n\tassert.Equal(12, mh[1].Hour())\n\tassert.Equal(00, mh[1].Minute())\n\tassert.Equal(Date.Eastern(), mh[1].Location())\n\n\tassert.Equal(14, mh[2].Hour())\n\tassert.Equal(00, mh[2].Minute())\n\tassert.Equal(Date.Eastern(), mh[2].Location())\n}\n\nfunc TestSequenceMarketHours(t *testing.T) ", "output": "{\n\tassert := assert.New(t)\n\n\ttoday := time.Date(2016, 07, 01, 12, 0, 0, 0, Date.Eastern())\n\tmh := Sequence.MarketHours(today, today, NYSEOpen, NYSEClose, Date.IsNYSEHoliday)\n\tassert.Len(mh, 8)\n\tassert.Equal(Date.Eastern(), mh[0].Location())\n}"} {"input": "package system\n\n\nfunc Lgetxattr(path string, attr string) ([]byte, error) {\n\treturn nil, ErrNotSupportedPlatform\n}\n\n\n\n\nfunc Lsetxattr(path string, attr string, data []byte, flags int) error ", "output": "{\n\treturn ErrNotSupportedPlatform\n}"} {"input": "package main\n\nvar log string\n\ntype T int\n\nfunc (t T) a(s string) T {\n\tlog += \"a(\" + s + \")\"\n\treturn t\n}\n\nfunc (T) b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\ntype F func(s string) F\n\n\n\nfunc b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\ntype I interface {\n\ta(s string) I\n\tb(s string) string\n}\n\ntype T1 int\n\nfunc (t T1) a(s string) I {\n\tlog += \"a(\" + s + \")\"\n\treturn t\n}\n\nfunc (T1) b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\nvar ok = true\n\nfunc bad() {\n\tif !ok {\n\t\tprintln(\"BUG\")\n\t\tok = false\n\t}\n\tprintln(log)\n}\n\nfunc main() {\n\tvar t T\n\tif t.a(\"1\").a(t.b(\"2\")); log != \"a(1)ba(2)\" {\n\t\tbad()\n\t}\n\tlog = \"\"\n\tif a(\"3\")(b(\"4\"))(b(\"5\")); log != \"a(3)ba(4)ba(5)\" {\n\t\tbad()\n\t}\n\tlog = \"\"\n\tvar i I = T1(0)\n\tif i.a(\"6\").a(i.b(\"7\")).a(i.b(\"8\")).a(i.b(\"9\")); log != \"a(6)ba(7)ba(8)ba(9)\" {\n\t\tbad()\n\t}\n}\n\nfunc a(s string) F ", "output": "{\n\tlog += \"a(\" + s + \")\"\n\treturn F(a)\n}"} {"input": "package fixtures\n\nimport \"database/sql/driver\"\n\ntype AliasArray [3]string\ntype AliasSlice []string\ntype AliasString string\ntype AliasInt int\ntype AliasArrAliasSlice []AliasSlice\ntype AliasArrAliasString []AliasString\ntype AliasDummyParam QueryDummy\n\ntype QueryDummy struct {\n\tname string\n}\n\ntype InterfaceImplementation struct {\n\tScannerValuer\n\tStr string\n}\n\ntype ScannerValuer struct{}\n\nfunc (i ScannerValuer) Value() (driver.Value, error) {\n\treturn nil, nil\n}\n\n\n\nfunc (i ScannerValuer) Scan(src interface{}) error ", "output": "{\n\treturn nil\n}"} {"input": "package registry\n\nimport \"go.uber.org/zap\"\n\nvar log *zap.Logger\n\n\n\n\nfunc UseLogger(l *zap.Logger) {\n\tlog = l\n}\n\nfunc init() ", "output": "{\n\tlog = zap.NewNop()\n}"} {"input": "package fork\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n)\n\ntype Field interface {\n\tNamed\n\tNew(...interface{}) Field\n\tGet() *Value\n\tSet(*http.Request)\n\tProcessor\n}\n\ntype Named interface {\n\tName() string\n\tReName(...string) string\n}\n\nfunc newnamed(name string) *named {\n\treturn &named{name: name}\n}\n\ntype named struct {\n\tname string\n}\n\n\n\nfunc (n *named) ReName(rename ...string) string {\n\tif len(rename) > 0 {\n\t\tn.name = strings.Join(rename, \"-\")\n\t}\n\treturn n.name\n}\n\nfunc (n *named) Copy() *named {\n\tvar ret named = *n\n\treturn &ret\n}\n\ntype Processor interface {\n\tWidget\n\tFilterer\n\tValidater\n}\n\ntype processor struct {\n\tWidget\n\tValidater\n\tFilterer\n}\n\nfunc NewProcessor(w Widget, v Validater, f Filterer) *processor {\n\treturn &processor{w, v, f}\n}\n\nfunc (n *named) Name() string ", "output": "{\n\treturn n.name\n}"} {"input": "package dchan\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype SimpleReq struct {\n\tHeader Header\n\tBody io.ReadCloser\n}\n\ntype Header []header\n\n\n\nfunc (h Header) Get(k string) string {\n\tidx := h.get(k)\n\tif idx < 0 {\n\t\treturn \"\"\n\t}\n\treturn h[idx].Values[0]\n}\n\nfunc (h *Header) Add(k string, v string) {\n\tidx := h.get(k)\n\tif idx < 0 {\n\t\t*h = append(*h, header{k, []string{v}})\n\t} else {\n\t\t(*h)[idx].Values = append((*h)[idx].Values, v)\n\t}\n}\n\ntype header struct {\n\tName string\n\tValues []string\n}\n\nfunc NewSimpleReq(r *bufio.Reader) (*SimpleReq, error) {\n\tsr := &SimpleReq{\n\t\tHeader: make(Header, 0, 16),\n\t}\n\n\tfor {\n\t\tline, err := r.ReadSlice('\\n')\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(line) == 2 {\n\t\t\tbreak\n\t\t}\n\n\t\tif idx := bytes.Index(line, []byte(\":\")); idx > 0 {\n\t\t\tsr.Header.Add(string(line[:idx]), string(bytes.TrimSpace(line[idx+1:])))\n\t\t}\n\t}\n\n\tcl := sr.Header.Get(\"Content-Length\")\n\tif n, _ := strconv.Atoi(cl); n > 0 {\n\t\tsr.Body = ioutil.NopCloser(io.LimitReader(r, int64(n)))\n\t} else {\n\t\tsr.Body = ioutil.NopCloser(r)\n\t}\n\treturn sr, nil\n}\n\nfunc (h Header) get(k string) int ", "output": "{\n\tfor idx := range h {\n\t\tif strings.EqualFold(h[idx].Name, k) {\n\t\t\treturn idx\n\t\t}\n\t}\n\treturn -1\n}"} {"input": "package parser\n\n\ntype Sequence struct {\n\tContent []Statement\n\tParent *Sequence \n}\n\n\nfunc (s Sequence) String() (string, error) {\n\tvar content string\n\n\tif s.Parent != nil {\n\n\t\tlength := len(s.Content)\n\t\tif length > 0 {\n\t\t\trepr, err := s.Content[0].String()\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tcontent += repr\n\t\t}\n\n\t\tfor i := 1; i < length; i++ {\n\t\t\trepr, err := s.Content[i].String()\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tcontent += \";\" + repr\n\t\t}\n\n\t\tcontent = \"\\\"\" + content + \"\\\"\"\n\t} else {\n\n\t\tfor _, statement := range s.Content {\n\t\t\trepr, err := statement.String()\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tcontent += repr + \"\\n\"\n\t\t}\n\t}\n\n\treturn content, nil\n}\n\nfunc (s Sequence) Undo() (string, error) {\n\tvar content string\n\n\tlength := len(s.Content)\n\tif length > 0 {\n\t\trepr, err := s.Content[0].Undo()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tcontent += repr\n\t}\n\n\tfor i := 1; i < length; i++ {\n\t\trepr, err := s.Content[i].Undo()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tcontent += \";\" + repr\n\t}\n\n\tcontent = \"\\\"\" + content + \"\\\"\"\n\n\treturn content, nil\n}\n\n\n\n\n\nfunc (s *Sequence) Add(command string) *Statement {\n\ts.Content = append(s.Content, Statement{Command: command})\n\n\treturn &s.Content[len(s.Content)-1]\n}\n\nfunc (s *Sequence) Last() *Statement ", "output": "{\n\tif len(s.Content) == 0 {\n\t\treturn nil\n\t}\n\n\treturn &s.Content[len(s.Content)-1]\n}"} {"input": "package net\n\nimport (\n\t\"os\"\n\t\"runtime\"\n\t\"syscall\"\n\t\"time\"\n\t\"unsafe\"\n)\n\n\n\nfunc setKeepAlivePeriod(fd *netFD, d time.Duration) error ", "output": "{\n\tmsecs := uint32(roundDurationUp(d, time.Millisecond))\n\tka := syscall.TCPKeepalive{\n\t\tOnOff: 1,\n\t\tTime: msecs,\n\t\tInterval: msecs,\n\t}\n\tret := uint32(0)\n\tsize := uint32(unsafe.Sizeof(ka))\n\terr := fd.pfd.WSAIoctl(syscall.SIO_KEEPALIVE_VALS, (*byte)(unsafe.Pointer(&ka)), size, nil, 0, &ret, nil, 0)\n\truntime.KeepAlive(fd)\n\treturn os.NewSyscallError(\"wsaioctl\", err)\n}"} {"input": "package xtest\n\nimport (\n\t\"sync\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\ntype SC struct {\n\tC\n\tsync.WaitGroup\n\tsync.Mutex\n}\n\nfunc (c *SC) Convey(items ...interface{}) {\n\tpanic(\"Convey in SyncConvey Context not supported\")\n}\n\nfunc (c *SC) So(actual interface{},\n\tassert func(actual interface{}, expected ...interface{}) string, expected ...interface{}) {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.C.So(actual, assert, expected)\n}\n\nfunc (c *SC) SoMsg(msg string, actual interface{},\n\tassert func(actual interface{}, expected ...interface{}) string, expected ...interface{}) {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.C.SoMsg(msg, actual, assert, expected...)\n}\n\n\n\nfunc Parallel(f, g func(sc *SC)) func(c C) {\n\treturn func(c C) {\n\t\tsc := &SC{C: c}\n\t\tsc.Add(1)\n\t\tgo func() {\n\t\t\tdefer sc.Done()\n\t\t\tdefer sc.Recover()\n\t\t\tg(sc)\n\t\t}()\n\t\tdefer sc.Wait()\n\t\tdefer sc.Recover()\n\t\tf(sc)\n\t}\n}\n\n\n\n\n\nfunc SoMsgError(msg string, err error, shouldBeError bool) {\n\tif shouldBeError == true {\n\t\tSoMsg(msg, err, ShouldNotBeNil)\n\t} else {\n\t\tSoMsg(msg, err, ShouldBeNil)\n\t}\n}\n\nfunc (c *SC) Recover() ", "output": "{\n\tif r := recover(); r != nil {\n\t\tif rString, ok := r.(string); ok && rString == \"___FAILURE_HALT___\" {\n\t\t\treturn\n\t\t}\n\t\tpanic(r)\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"path/filepath\"\n\n\tv32 \"github.com/rancher/rancher/pkg/apis/project.cattle.io/v3\"\n\tv3 \"github.com/rancher/rancher/pkg/generated/norman/project.cattle.io/v3\"\n)\n\nfunc MatchAll(cs *v32.Constraints, execution *v3.PipelineExecution) bool {\n\tif cs == nil {\n\t\treturn true\n\t}\n\n\tm := GetEnvVarMap(execution)\n\n\treturn Match(cs.Branch, m[EnvGitBranch]) &&\n\t\tMatch(cs.Event, m[EnvEvent])\n}\n\n\n\n\nfunc Includes(c *v32.Constraint, v string) bool {\n\tfor _, pattern := range c.Include {\n\t\tif ok, _ := filepath.Match(pattern, v); ok {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc Excludes(c *v32.Constraint, v string) bool {\n\tfor _, pattern := range c.Exclude {\n\t\tif ok, _ := filepath.Match(pattern, v); ok {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc Match(c *v32.Constraint, v string) bool ", "output": "{\n\tif c == nil {\n\t\treturn true\n\t}\n\n\tif Excludes(c, v) {\n\t\treturn false\n\t}\n\tif Includes(c, v) {\n\t\treturn true\n\t}\n\tif len(c.Include) == 0 {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package serialconsole\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/serialconsole/mgmt/2018-05-01/serialconsole\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype BaseClient = original.BaseClient\ntype ConsoleClient = original.ConsoleClient\ntype DeploymentValidateResult = original.DeploymentValidateResult\ntype GetDisabledResult = original.GetDisabledResult\ntype GetResult = original.GetResult\ntype ListClient = original.ListClient\ntype ListConsoleClient = original.ListConsoleClient\ntype Operations = original.Operations\ntype SetDisabledResult = original.SetDisabledResult\n\nfunc New(subscriptionID string) BaseClient {\n\treturn original.New(subscriptionID)\n}\nfunc NewConsoleClient(subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClient(subscriptionID)\n}\nfunc NewConsoleClientWithBaseURI(baseURI string, subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewListClient(subscriptionID string) ListClient {\n\treturn original.NewListClient(subscriptionID)\n}\nfunc NewListClientWithBaseURI(baseURI string, subscriptionID string) ListClient {\n\treturn original.NewListClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewListConsoleClient(subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClient(subscriptionID)\n}\nfunc NewListConsoleClientWithBaseURI(baseURI string, subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\n\n\nfunc Version() string ", "output": "{\n\treturn original.Version()\n}"} {"input": "package cacheprovider\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/docker/distribution/registry/storage/cache\"\n)\n\n\n\ntype InitFunc func(ctx context.Context, options map[string]interface{}) (cache.BlobDescriptorCacheProvider, error)\n\nvar cacheProviders map[string]InitFunc\n\n\n\nfunc Register(name string, initFunc InitFunc) error {\n\tif cacheProviders == nil {\n\t\tcacheProviders = make(map[string]InitFunc)\n\t}\n\tif _, exists := cacheProviders[name]; exists {\n\t\treturn fmt.Errorf(\"name already registered: %s\", name)\n\t}\n\n\tcacheProviders[name] = initFunc\n\n\treturn nil\n}\n\n\n\n\nfunc Get(ctx context.Context, name string, options map[string]interface{}) (cache.BlobDescriptorCacheProvider, error) ", "output": "{\n\tif initFunc, exists := cacheProviders[name]; exists {\n\t\treturn initFunc(ctx, options)\n\t}\n\treturn nil, fmt.Errorf(\"no cache Provider registered with name: %s\", name)\n}"} {"input": "package pflag\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype boolValue bool\n\n\n\nfunc (b *boolValue) Set(s string) error {\n\tv, err := strconv.ParseBool(s)\n\t*b = boolValue(v)\n\treturn err\n}\n\nfunc (b *boolValue) String() string { return fmt.Sprintf(\"%v\", *b) }\n\n\n\nfunc (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc BoolVar(p *bool, name string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc (f *FlagSet) Bool(name string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, \"\", value, usage)\n\treturn p\n}\n\n\nfunc (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, shorthand, value, usage)\n\treturn p\n}\n\n\n\nfunc Bool(name string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, \"\", value, usage)\n}\n\n\nfunc BoolP(name, shorthand string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, shorthand, value, usage)\n}\n\nfunc newBoolValue(val bool, p *bool) *boolValue ", "output": "{\n\t*p = val\n\treturn (*boolValue)(p)\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/julienschmidt/httprouter\"\n\t\"net/http\"\n)\n\ntype Logout struct {\n\t*Controller\n}\n\n\n\nfunc NewLogoutController(c *Controller, router *httprouter.Router) {\n\tlogout := &Logout{\n\t\tc,\n\t}\n\tlogout.Register(router)\n}\n\n\n\n\n\n\n\nfunc (l *Logout) Get(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tl.Authentication.ClearSession(res)\n\thttp.Redirect(res, req, \"/login\", http.StatusFound)\n}\n\nfunc (l *Logout) Register(router *httprouter.Router) ", "output": "{\n\trouter.GET(\"/logout\", l.Get)\n}"} {"input": "package api\n\ntype FormatsResponse struct {\n\tFormats []string `json:\"formats\"`\n}\n\nfunc (a *API) getFormats(ctx *context) {\n\tctx.Success(FormatsResponse{Formats: a.c.formats.Keys()})\n}\n\ntype LeechTypesResponse struct {\n\tLeechTypes []string `json:\"leech_types\"`\n}\n\nfunc (a *API) getLeechTypes(ctx *context) {\n\tctx.Success(LeechTypesResponse{LeechTypes: a.c.leechTypes.Keys()})\n}\n\ntype MediaResponse struct {\n\tMedia []string `json:\"media\"`\n}\n\nfunc (a *API) getMedia(ctx *context) {\n\tctx.Success(MediaResponse{Media: a.c.media.Keys()})\n}\n\ntype ReleaseGroupTypesResponse struct {\n\tReleaseGroupTypes []string `json:\"release_group_types\"`\n}\n\nfunc (a *API) getReleaseGroupTypes(ctx *context) {\n\tctx.Success(ReleaseGroupTypesResponse{ReleaseGroupTypes: a.c.releaseGroupTypes.Keys()})\n}\n\ntype ReleasePropertiesResponse struct {\n\tReleaseProperties []string `json:\"release_properties\"`\n}\n\nfunc (a *API) getReleaseProperties(ctx *context) {\n\tctx.Success(ReleasePropertiesResponse{ReleaseProperties: a.c.releaseProperties.Keys()})\n}\n\ntype ReleaseRolesResponse struct {\n\tReleaseRoles []string `json:\"release_roles\"`\n}\n\nfunc (a *API) getReleaseRoles(ctx *context) {\n\tctx.Success(ReleaseRolesResponse{ReleaseRoles: a.c.releaseRoles.Keys()})\n}\n\ntype PrivilegesResponse struct {\n\tPrivileges []string `json:\"privileges\"`\n}\n\n\n\nfunc (a *API) getPrivileges(ctx *context) ", "output": "{\n\tctx.Success(PrivilegesResponse{Privileges: a.c.privileges.Keys()})\n}"} {"input": "package webaccelerator\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/sacloud/usacloud/pkg/output\"\n\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n\t\"github.com/sacloud/usacloud/pkg/cli\"\n\t\"github.com/sacloud/usacloud/pkg/cmd/cflag\"\n\t\"github.com/sacloud/usacloud/pkg/cmd/core\"\n)\n\nvar deleteCacheCommand = &core.Command{\n\tName: \"delete-cache\",\n\tAliases: []string{\"cache-delete\"},\n\tCategory: \"cache\",\n\tOrder: 10,\n\n\tColumnDefs: []output.ColumnDef{\n\t\t{Name: \"URL\"},\n\t\t{Name: \"Status\"},\n\t\t{Name: \"Result\"},\n\t},\n\n\tParameterInitializer: func() interface{} {\n\t\treturn newDeleteCacheParameter()\n\t},\n\tFunc: deleteCacheFunc,\n}\n\ntype deleteCacheParameter struct {\n\tcflag.IDParameter `cli:\",squash\" mapconv:\",squash\"`\n\tcflag.ConfirmParameter `cli:\",squash\" mapconv:\"-\"`\n\tcflag.CommonParameter `cli:\",squash\" mapconv:\"-\"`\n\tcflag.OutputParameter `cli:\",squash\" mapconv:\"-\"`\n\n\tURLs []string `cli:\"url\" validate:\"required\"`\n}\n\nfunc newDeleteCacheParameter() *deleteCacheParameter {\n\treturn &deleteCacheParameter{}\n}\n\nfunc init() {\n\tResource.AddCommand(deleteCacheCommand)\n}\n\n\n\nfunc deleteCacheFunc(ctx cli.Context, parameter interface{}) ([]interface{}, error) ", "output": "{\n\tp, ok := parameter.(*deleteCacheParameter)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"got invalid parameter type: %#v\", parameter)\n\t}\n\twebAccelOp := sacloud.NewWebAccelOp(ctx.Client())\n\tdeleteResults, err := webAccelOp.DeleteCache(ctx, &sacloud.WebAccelDeleteCacheRequest{URL: p.URLs})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar results []interface{}\n\tfor _, r := range deleteResults {\n\t\tresults = append(results, r)\n\t}\n\treturn results, nil\n}"} {"input": "package blockchain\n\nimport (\n\t\"github.com/cfromknecht/certcoin/crypto\"\n\tdb \"github.com/syndtr/goleveldb/leveldb\"\n\n\t\"log\"\n)\n\ntype SVP struct {\n\tHeaderDBPath string\n\tLastHeader BlockHeader\n}\n\nfunc NewSVP() SVP {\n\tsvp := SVP{\n\t\tHeaderDBPath: \"db/header.db\",\n\t}\n\n\terr := svp.WriteHeader(GenesisBlock().Header)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tpanic(\"Unable to add genesis block header to database\")\n\t}\n\n\treturn svp\n}\n\nfunc (s *SVP) ValidHeader(header BlockHeader) bool {\n\tif header.SeqNum == 0 {\n\t\treturn header.PrevHash == crypto.SHA256Sum{} &&\n\t\t\theader.ValidPoW()\n\t}\n\n\treturn s.LastHeader.Hash() == header.PrevHash &&\n\t\theader.ValidPoW()\n}\n\n\n\nfunc (s *SVP) WriteHeader(header BlockHeader) error ", "output": "{\n\theaderDB, err := db.OpenFile(s.HeaderDBPath, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tpanic(\"Unable to open header database\")\n\t}\n\tdefer headerDB.Close()\n\n\theaderJson := header.Json()\n\thash := header.Hash()\n\n\terr = headerDB.Put(hash[:], headerJson, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\tlog.Println(\"Last header:\", header)\n\ts.LastHeader = header\n\n\treturn nil\n}"} {"input": "package transporttest\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\n\ntype ContextMatcher struct {\n\tt *testing.T\n\tttl time.Duration\n\n\tTTLDelta time.Duration\n}\n\n\ntype ContextMatcherOption interface {\n\trun(*ContextMatcher)\n}\n\n\n\ntype ContextTTL time.Duration\n\nfunc (ttl ContextTTL) run(c *ContextMatcher) {\n\tc.ttl = time.Duration(ttl)\n}\n\n\n\nfunc NewContextMatcher(t *testing.T, options ...ContextMatcherOption) *ContextMatcher {\n\tmatcher := &ContextMatcher{t: t, TTLDelta: DefaultTTLDelta}\n\tfor _, opt := range options {\n\t\topt.run(matcher)\n\t}\n\treturn matcher\n}\n\n\n\n\n\n\nfunc (c *ContextMatcher) String() string {\n\treturn fmt.Sprintf(\"ContextMatcher(TTL:%v±%v)\", c.ttl, c.TTLDelta)\n}\n\nfunc (c *ContextMatcher) Matches(got interface{}) bool ", "output": "{\n\tctx, ok := got.(context.Context)\n\tif !ok {\n\t\tc.t.Logf(\"expected a Context but got a %T: %v\", got, got)\n\t\treturn false\n\t}\n\n\tif c.ttl != 0 {\n\t\td, ok := ctx.Deadline()\n\t\tif !ok {\n\t\t\tc.t.Logf(\n\t\t\t\t\"expected Context to have a TTL of %v but it has no deadline\", c.ttl)\n\t\t\treturn false\n\t\t}\n\n\t\tttl := time.Until(d)\n\t\tmaxTTL := c.ttl + c.TTLDelta\n\t\tminTTL := c.ttl - c.TTLDelta\n\t\tif ttl > maxTTL || ttl < minTTL {\n\t\t\tc.t.Logf(\"TTL out of expected bounds: %v < %v < %v\", minTTL, ttl, maxTTL)\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}"} {"input": "package trust\n\nimport (\n\t\"strings\"\n)\n\nconst (\n\tAny Attribute = 0\n\tAuthoritative Attribute = 1 << iota\n\tCore\n\tRootCA\n)\n\nvar attributeString = map[Attribute]string{\n\tAny: \"any\",\n\tAuthoritative: \"authoritative\",\n\tCore: \"core\",\n\tRootCA: \"root_ca\",\n}\n\n\ntype Attribute int\n\n\nfunc (a Attribute) IsSubset(super Attribute) bool {\n\treturn (a & super) == a\n}\n\n\n\nfunc (a Attribute) String() string ", "output": "{\n\tparts := make([]string, 0, 3)\n\tfor _, attr := range []Attribute{Authoritative, Core, RootCA} {\n\t\tif Attribute(a)&attr != 0 {\n\t\t\tparts = append(parts, attributeString[attr])\n\t\t}\n\t}\n\tif len(parts) == 0 {\n\t\treturn attributeString[Any]\n\t}\n\treturn strings.Join(parts, \"|\")\n}"} {"input": "package plist\n\n\nimport \"C\"\nimport \"reflect\"\nimport \"strconv\"\n\n\n\ntype UnsupportedTypeError struct {\n\tType reflect.Type\n}\n\nfunc (e *UnsupportedTypeError) Error() string {\n\treturn \"plist: unsupported type: \" + e.Type.String()\n}\n\ntype UnsupportedValueError struct {\n\tValue reflect.Value\n\tStr string\n}\n\nfunc (e *UnsupportedValueError) Error() string {\n\treturn \"json: unsupported value: \" + e.Str\n}\n\ntype UnknownCFTypeError struct {\n\tCFTypeID C.CFTypeID\n}\n\nfunc (e *UnknownCFTypeError) Error() string {\n\tcfStr := C.CFCopyTypeIDDescription(e.CFTypeID)\n\tstr := convertCFStringToString(cfStr)\n\tcfRelease(cfTypeRef(cfStr))\n\treturn \"plist: unknown CFTypeID \" + strconv.Itoa(int(e.CFTypeID)) + \" (\" + str + \")\"\n}\n\n\n\n\n\n\n\ntype UnsupportedKeyTypeError struct {\n\tCFTypeID int\n}\n\n\n\nfunc (e *UnsupportedKeyTypeError) Error() string ", "output": "{\n\treturn \"plist: unexpected dictionary key CFTypeID \" + strconv.Itoa(e.CFTypeID)\n}"} {"input": "package keyseq\n\nimport (\n\t\"testing\"\n)\n\nfunc checkTrieNode(t *testing.T, n Node, k Key, value int) {\n\tif n == nil {\n\t\tt.Fatal(\"TrieNode is null\")\n\t}\n\tif l := n.Label(); l != k {\n\t\tt.Errorf(\"TrieNode.Label() expected:'%c' actual:'%c'\", k, l)\n\t}\n\tif v := n.Value().(int); v != value {\n\t\tt.Errorf(\"TrieNode.Value() expected:%d actual:%d\", value, v)\n\t}\n}\n\nfunc TestTrie(t *testing.T) {\n\ttrie := NewTrie()\n\tfor i := 1; i <= 5; i++ {\n\t\ttrie.Put(KeyList{Key{0, 0, rune(i)}}, 111*i)\n\t}\n\n\tnodes := Children(trie.Root())\n\tfor i := 0; i < 5; i++ {\n\t\tcheckTrieNode(t, nodes[i], Key{0, 0, rune(i + 1)}, 111*(i+1))\n\t}\n\n\tif s := trie.Size(); s != 5 {\n\t\tt.Errorf(\"trie.Size() returns not 5: %d\", s)\n\t}\n}\n\n\n\nfunc TestNotFound(t *testing.T) ", "output": "{\n\ttrie := NewTrie()\n\tif trie.Get(Key{999, 999, 'a'}) != nil {\n\t\tt.Errorf(\"found 'not_exist' in empty trie\")\n\t}\n}"} {"input": "package collector\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/google/cadvisor/info/v1\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype fakeCollector struct {\n\tnextCollectionTime time.Time\n\terr error\n\tcollectedFrom int\n}\n\nfunc (fc *fakeCollector) Collect(metric map[string]v1.MetricVal) (time.Time, map[string]v1.MetricVal, error) {\n\tfc.collectedFrom++\n\treturn fc.nextCollectionTime, metric, fc.err\n}\n\n\n\nfunc (fc *fakeCollector) GetSpec() []v1.MetricSpec {\n\treturn []v1.MetricSpec{}\n}\n\nfunc TestCollect(t *testing.T) {\n\tcm := &GenericCollectorManager{}\n\n\tfirstTime := time.Now().Add(-time.Hour)\n\tsecondTime := time.Now().Add(time.Hour)\n\tf1 := &fakeCollector{\n\t\tnextCollectionTime: firstTime,\n\t}\n\tf2 := &fakeCollector{\n\t\tnextCollectionTime: secondTime,\n\t}\n\n\tassert := assert.New(t)\n\tassert.NoError(cm.RegisterCollector(f1))\n\tassert.NoError(cm.RegisterCollector(f2))\n\n\tnextTime, _, err := cm.Collect()\n\tassert.Equal(firstTime, nextTime)\n\tassert.NoError(err)\n\tassert.Equal(1, f1.collectedFrom)\n\tassert.Equal(1, f2.collectedFrom)\n\n\tf1.nextCollectionTime = time.Now().Add(2 * time.Hour)\n\n\tnextTime, _, err = cm.Collect()\n\tassert.Equal(secondTime, nextTime)\n\tassert.NoError(err)\n\tassert.Equal(2, f1.collectedFrom)\n\tassert.Equal(1, f2.collectedFrom)\n}\n\nfunc (fc *fakeCollector) Name() string ", "output": "{\n\treturn \"fake-collector\"\n}"} {"input": "package fhash\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"path/filepath\"\n)\n\nconst (\n\tfhashData = \"fhashdata\"\n)\n\n\ntype Server struct {\n\tserver *http.Server\n\tconf *Config\n\tindex *Index \n\troot string \n}\n\n\nfunc NewServer(config *Config) (*Server, error) {\n\tindex, err := NewIndex(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"index error: %v\", err)\n\t}\n\n\troot := filepath.Join(config.Server.Root, fhashData)\n\tserver := &Server{\n\t\tserver: &http.Server{\n\t\t\tAddr: config.Server.Address,\n\t\t},\n\t\tconf: config,\n\t\tindex: index,\n\t\troot: root,\n\t}\n\treturn server, nil\n}\n\n\nfunc (s *Server) Serve() {\n\thttp.HandleFunc(\"/putfile\", s.putFile)\n\thttp.HandleFunc(\"/getfile/\", s.getFile)\n\terr := s.server.ListenAndServe()\n\tif err != nil {\n\t\tlog.Printf(\"failed to serve: %v\", err)\n\t}\n}\n\n\n\n\nfunc (s *Server) Shutdown() error ", "output": "{\n\terr := s.index.close()\n\treturn err\n}"} {"input": "package gitea\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n\n\ntype User struct {\n\tID int64 `json:\"id\"`\n\tUserName string `json:\"login\"`\n\tFullName string `json:\"full_name\"`\n\tEmail string `json:\"email\"`\n\tAvatarURL string `json:\"avatar_url\"`\n}\n\n\n\ntype UserList []*User\n\n\n\n\n\nfunc (c *Client) GetUserInfo(user string) (*User, error) {\n\tu := new(User)\n\terr := c.getParsedResponse(\"GET\", fmt.Sprintf(\"/users/%s\", user), nil, nil, u)\n\treturn u, err\n}\n\nfunc (u User) MarshalJSON() ([]byte, error) ", "output": "{\n\ttype shadow User\n\treturn json.Marshal(struct {\n\t\tshadow\n\t\tCompatUserName string `json:\"username\"`\n\t}{shadow(u), u.UserName})\n}"} {"input": "package writer\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"hash/crc32\"\n\n\t\"github.com/rameshvarun/ups/common\"\n)\n\n\nfunc WriteUPS(data *common.PatchData) []byte {\n\tvar buffer bytes.Buffer\n\n\tbuffer.Write(common.Signature)\n\n\tbuffer.Write(WriteVariableLengthInteger(data.InputFileSize))\n\tbuffer.Write(WriteVariableLengthInteger(data.OutputFileSize))\n\n\tfor _, block := range data.PatchBlocks {\n\t\tbuffer.Write(WriteVariableLengthInteger(block.RelativeOffset))\n\t\tbuffer.Write(block.Data)\n\t\tbuffer.WriteByte(0)\n\t}\n\n\tbinary.Write(&buffer, binary.LittleEndian, data.InputChecksum)\n\tbinary.Write(&buffer, binary.LittleEndian, data.OutputChecksum)\n\n\tchecksum := crc32.ChecksumIEEE(buffer.Bytes())\n\tbinary.Write(&buffer, binary.LittleEndian, checksum)\n\n\treturn buffer.Bytes()\n}\n\n\n\n\n\nfunc WriteVariableLengthInteger(value uint64) []byte ", "output": "{\n\tvar data []byte\n\tx := value & 0x7f\n\tvalue >>= 7\n\n\tfor value != 0 {\n\t\tdata = append(data, byte(x))\n\t\tvalue--\n\t\tx = value & 0x7f\n\t\tvalue >>= 7\n\t}\n\tdata = append(data, byte(0x80|x))\n\treturn data\n}"} {"input": "package goopencc\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tZH2TW = \"s2twp.json\"\n\tTW2ZH = \"tw2sp.json\"\n)\n\nfunc Zh2Tw(v string) (string, int) {\n\tv = strings.Trim(v, \" \")\n\tif v == \"\" {\n\t\treturn v, 200\n\t}\n\treturn translate(v, ZH2TW)\n}\n\n\n\nfunc translate(v string, m string) (string, int) {\n\tapiUrl := \"http://opencc.byvoid.com/convert\"\n\tdata := url.Values{}\n\tdata.Set(\"text\", v)\n\tdata.Add(\"config\", m)\n\tdata.Add(\"precise\", \"0\")\n\n\tclient := &http.Client{}\n\tr, _ := http.NewRequest(\"POST\", apiUrl, bytes.NewBuffer([]byte(data.Encode())))\n\tr.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\tr.Header.Add(\"Content-Length\", strconv.Itoa(len(data.Encode())))\n\n\tresp, _ := client.Do(r)\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\treturn buf.String(), resp.StatusCode\n}\n\nfunc Tw2Zh(v string) (string, int) ", "output": "{\n\tv = strings.Trim(v, \" \")\n\tif v == \"\" {\n\t\treturn v, 200\n\t}\n\treturn translate(v, TW2ZH)\n}"} {"input": "package web\n\nimport \"testing\"\n\nfunc TestFormError(t *testing.T) {\n\te := FormErrors{}\n\tif e.HasErrors() {\n\t\tt.Error(\"expected false from HasErrors\")\n\t}\n\n\ttext := \"test error\"\n\ttext2 := \"test error 2\"\n\te = NewError(text)\n\tif !e.HasErrors() {\n\t\tt.Error(\"expected true from HasErrors\")\n\t}\n\tif e.Errors[0] != text {\n\t\tt.Errorf(\"expected %q, got %q\", text, e.Errors[0])\n\t}\n\te.AddError(text2)\n\tif e.Errors[1] != text2 {\n\t\tt.Errorf(\"expected %q, got %q\", text2, e.Errors[1])\n\t}\n}\n\n\n\nfunc TestFormError_Field(t *testing.T) ", "output": "{\n\tfield := \"field\"\n\ttext := \"test error\"\n\tfield2 := \"field 2\"\n\ttext2 := \"test error 2\"\n\te := NewFieldError(field, text)\n\tif !e.HasErrors() {\n\t\tt.Error(\"expected true from HasErrors\")\n\t}\n\tif e.FieldErrors[field][0] != text {\n\t\tt.Errorf(\"expected %q, got %q\", text, e.FieldErrors[field][0])\n\t}\n\te.AddFieldError(field2, text2)\n\tif e.FieldErrors[field2][0] != text2 {\n\t\tt.Errorf(\"expected %q, got %q\", text2, e.FieldErrors[field2][0])\n\t}\n}"} {"input": "package chshare\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\n\ntype Logger struct {\n\tprefix string\n\tlogger *log.Logger\n\tInfo, Debug bool\n}\n\nfunc NewLogger(prefix string) *Logger {\n\treturn NewLoggerFlag(prefix, log.Ldate|log.Ltime)\n}\n\nfunc NewLoggerFlag(prefix string, flag int) *Logger {\n\tl := &Logger{\n\t\tprefix: prefix,\n\t\tlogger: log.New(os.Stdout, \"\", flag),\n\t\tInfo: false,\n\t\tDebug: false,\n\t}\n\treturn l\n}\n\nfunc (l *Logger) Infof(f string, args ...interface{}) {\n\tif l.Info {\n\t\tl.logger.Printf(l.prefix+\": \"+f, args...)\n\t}\n}\n\n\n\nfunc (l *Logger) Errorf(f string, args ...interface{}) error {\n\treturn fmt.Errorf(l.prefix+\": \"+f, args...)\n}\n\nfunc (l *Logger) Fork(prefix string, args ...interface{}) *Logger {\n\targs = append([]interface{}{l.prefix}, args...)\n\tll := NewLogger(fmt.Sprintf(\"%s: \"+prefix, args...))\n\tll.Info = l.Info\n\tll.Debug = l.Debug\n\treturn ll\n}\n\nfunc (l *Logger) Prefix() string {\n\treturn l.prefix\n}\n\nfunc (l *Logger) Debugf(f string, args ...interface{}) ", "output": "{\n\tif l.Debug {\n\t\tl.logger.Printf(l.prefix+\": \"+f, args...)\n\t}\n}"} {"input": "package tmdb\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Changes struct {\n\tResults []struct {\n\t\tID int\n\t\tAdult bool\n\t}\n}\n\nvar changeOptions = map[string]struct{}{\n\t\"page\": {},\n\t\"start_date\": {},\n\t\"end_date\": {}}\n\n\n\n\n\n\n\nfunc (tmdb *TMDb) GetChangesPerson(options map[string]string) (*Changes, error) {\n\tvar personChanges Changes\n\toptionsString := getOptionsString(options, changeOptions)\n\turi := fmt.Sprintf(\"%s/person/changes?api_key=%s%s\", baseURL, tmdb.apiKey, optionsString)\n\tresult, err := getTmdb(uri, &personChanges)\n\treturn result.(*Changes), err\n}\n\n\n\nfunc (tmdb *TMDb) GetChangesTv(options map[string]string) (*Changes, error) {\n\tvar tvChanges Changes\n\toptionsString := getOptionsString(options, changeOptions)\n\turi := fmt.Sprintf(\"%s/tv/changes?api_key=%s%s\", baseURL, tmdb.apiKey, optionsString)\n\tresult, err := getTmdb(uri, &tvChanges)\n\treturn result.(*Changes), err\n}\n\nfunc (tmdb *TMDb) GetChangesMovie(options map[string]string) (*Changes, error) ", "output": "{\n\tvar movieChanges Changes\n\toptionsString := getOptionsString(options, changeOptions)\n\turi := fmt.Sprintf(\"%s/movie/changes?api_key=%s%s\", baseURL, tmdb.apiKey, optionsString)\n\tresult, err := getTmdb(uri, &movieChanges)\n\treturn result.(*Changes), err\n}"} {"input": "package osenv\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n)\n\nconst (\n\tJujuEnv = \"JUJU_ENV\"\n\tJujuHome = \"JUJU_HOME\"\n\tJujuRepository = \"JUJU_REPOSITORY\"\n\tJujuLoggingConfig = \"JUJU_LOGGING_CONFIG\"\n\tJujuContainerType = \"JUJU_CONTAINER_TYPE\"\n)\n\n\nfunc JujuHomeDir() string {\n\tjujuHome := os.Getenv(JujuHome)\n\tif jujuHome == \"\" {\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\tjujuHome = jujuHomeWin()\n\t\t} else {\n\t\t\tjujuHome = jujuHomeLinux()\n\t\t}\n\t}\n\treturn jujuHome\n}\n\n\nfunc jujuHomeLinux() string {\n\thome := Home()\n\tif home == \"\" {\n\t\treturn \"\"\n\t}\n\treturn filepath.Join(home, \".juju\")\n}\n\n\n\n\nfunc jujuHomeWin() string ", "output": "{\n\tappdata := os.Getenv(\"APPDATA\")\n\tif appdata == \"\" {\n\t\treturn \"\"\n\t}\n\treturn filepath.Join(appdata, \"Juju\")\n}"} {"input": "package utils\n\nimport \"fmt\"\n\nfunc ExampleStringSet_Add() {\n\tset := NewStringSet()\n\tset.Add(\"a\")\n\tset.Add(\"b\")\n\n\tfmt.Println(set)\n\tset.Add(\"a\")\n\tfmt.Println(set)\n\n}\n\nfunc ExampleNewStringSet() {\n\ta := NewStringSet()\n\ta.Add(\"a\")\n\ta.Add(\"b\")\n\n\tb := NewStringSet(\"b\", \"a\")\n\n\tfmt.Println(a.Equals(b))\n\n}\n\nfunc ExampleNewStringSetFromStringMapKeys() {\n\tm := map[string]string{\n\t\t\"a\": \"some a value\",\n\t\t\"b\": \"some b value\",\n\t}\n\n\tset := NewStringSetFromStringMapKeys(m)\n\tfmt.Println(set)\n\n}\n\nfunc ExampleStringSet_ToSlice() {\n\ta := NewStringSet()\n\ta.Add(\"z\")\n\ta.Add(\"b\")\n\n\tfmt.Println(a.ToSlice())\n\n}\n\nfunc ExampleStringSet_IsEmpty() {\n\ta := NewStringSet()\n\n\tfmt.Println(a.IsEmpty())\n\ta.Add(\"a\")\n\tfmt.Println(a.IsEmpty())\n\n}\n\nfunc ExampleStringSet_Equals() {\n\ta := NewStringSet(\"a\", \"b\")\n\tb := NewStringSet(\"a\", \"b\", \"c\")\n\tfmt.Println(a.Equals(b))\n\n\ta.Add(\"c\")\n\tfmt.Println(a.Equals(b))\n\n}\n\n\n\nfunc ExampleStringSet_Minus() {\n\ta := NewStringSet(\"a\", \"b\")\n\tb := NewStringSet(\"b\", \"c\")\n\tdelta := a.Minus(b)\n\n\tfmt.Println(delta)\n}\n\nfunc ExampleStringSet_Contains() ", "output": "{\n\ta := NewStringSet(\"a\", \"b\")\n\tfmt.Println(a.Contains(\"z\"))\n\tfmt.Println(a.Contains(\"a\"))\n\n}"} {"input": "package pflag\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype boolValue bool\n\nfunc newBoolValue(val bool, p *bool) *boolValue {\n\t*p = val\n\treturn (*boolValue)(p)\n}\n\nfunc (b *boolValue) Set(s string) error {\n\tv, err := strconv.ParseBool(s)\n\t*b = boolValue(v)\n\treturn err\n}\n\nfunc (b *boolValue) String() string { return fmt.Sprintf(\"%v\", *b) }\n\n\n\nfunc (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\n\n\n\nfunc BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc (f *FlagSet) Bool(name string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, \"\", value, usage)\n\treturn p\n}\n\n\nfunc (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, shorthand, value, usage)\n\treturn p\n}\n\n\n\nfunc Bool(name string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, \"\", value, usage)\n}\n\n\nfunc BoolP(name, shorthand string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, shorthand, value, usage)\n}\n\nfunc BoolVar(p *bool, name string, value bool, usage string) ", "output": "{\n\tCommandLine.VarP(newBoolValue(value, p), name, \"\", usage)\n}"} {"input": "package web\n\nimport \"testing\"\n\n\n\nfunc TestFormError_Field(t *testing.T) {\n\tfield := \"field\"\n\ttext := \"test error\"\n\tfield2 := \"field 2\"\n\ttext2 := \"test error 2\"\n\te := NewFieldError(field, text)\n\tif !e.HasErrors() {\n\t\tt.Error(\"expected true from HasErrors\")\n\t}\n\tif e.FieldErrors[field][0] != text {\n\t\tt.Errorf(\"expected %q, got %q\", text, e.FieldErrors[field][0])\n\t}\n\te.AddFieldError(field2, text2)\n\tif e.FieldErrors[field2][0] != text2 {\n\t\tt.Errorf(\"expected %q, got %q\", text2, e.FieldErrors[field2][0])\n\t}\n}\n\nfunc TestFormError(t *testing.T) ", "output": "{\n\te := FormErrors{}\n\tif e.HasErrors() {\n\t\tt.Error(\"expected false from HasErrors\")\n\t}\n\n\ttext := \"test error\"\n\ttext2 := \"test error 2\"\n\te = NewError(text)\n\tif !e.HasErrors() {\n\t\tt.Error(\"expected true from HasErrors\")\n\t}\n\tif e.Errors[0] != text {\n\t\tt.Errorf(\"expected %q, got %q\", text, e.Errors[0])\n\t}\n\te.AddError(text2)\n\tif e.Errors[1] != text2 {\n\t\tt.Errorf(\"expected %q, got %q\", text2, e.Errors[1])\n\t}\n}"} {"input": "package events\n\nimport \"github.com/gophercloud/gophercloud\"\n\nvar apiVersion = \"v1\"\nvar apiName = \"events\"\n\nfunc commonURL(client *gophercloud.ServiceClient) string {\n\treturn client.ServiceURL(apiVersion, apiName)\n}\n\nfunc listURL(client *gophercloud.ServiceClient) string {\n\treturn commonURL(client)\n}\n\nfunc idURL(client *gophercloud.ServiceClient, id string) string {\n\treturn client.ServiceURL(apiVersion, apiName, id)\n}\n\n\n\nfunc getURL(client *gophercloud.ServiceClient, id string) string ", "output": "{\n\treturn idURL(client, id)\n}"} {"input": "package server\n\nimport \"github.com/cosminrentea/gobbler/server/cluster\"\n\n\n\nfunc createCluster() (cl *cluster.Cluster) ", "output": "{\n\tvar err error\n\n\tif *Config.Cluster.NodeID > 0 {\n\t\texitIfInvalidClusterParams(*Config.Cluster.NodeID, *Config.Cluster.NodePort, *Config.Cluster.Remotes)\n\t\tlogger.Info(\"Starting in cluster-mode\")\n\t\tcl, err = cluster.New(&cluster.Config{\n\t\t\tID: *Config.Cluster.NodeID,\n\t\t\tPort: *Config.Cluster.NodePort,\n\t\t\tRemotes: *Config.Cluster.Remotes,\n\t\t})\n\t\tif err != nil {\n\t\t\tlogger.WithField(\"err\", err).Fatal(\"Module could not be started (cluster)\")\n\t\t}\n\t} else {\n\t\tlogger.Info(\"Starting in standalone-mode\")\n\t}\n\treturn\n}"} {"input": "package context\n\nimport (\n\t\"context\"\n)\n\n\ntype subscriptionKey struct{}\n\n\nfunc WithSubscriptionKey(ctx context.Context, key string) context.Context {\n\treturn context.WithValue(ctx, subscriptionKey{}, key)\n}\n\n\n\n\nfunc GetSubscriptionKey(ctx context.Context) (string, error) ", "output": "{\n\tuntyped := ctx.Value(subscriptionKey{})\n\tif untyped == nil {\n\t\treturn \"\", ErrSubscriptionKeyNotPresent\n\t}\n\treturn untyped.(string), nil\n}"} {"input": "package builtins\n\nimport (\n\t\"sigs.k8s.io/kustomize/api/filters/annotations\"\n\t\"sigs.k8s.io/kustomize/api/resmap\"\n\t\"sigs.k8s.io/kustomize/api/types\"\n\t\"sigs.k8s.io/yaml\"\n)\n\n\ntype AnnotationsTransformerPlugin struct {\n\tAnnotations map[string]string `json:\"annotations,omitempty\" yaml:\"annotations,omitempty\"`\n\tFieldSpecs []types.FieldSpec `json:\"fieldSpecs,omitempty\" yaml:\"fieldSpecs,omitempty\"`\n}\n\nfunc (p *AnnotationsTransformerPlugin) Config(\n\t_ *resmap.PluginHelpers, c []byte) (err error) {\n\tp.Annotations = nil\n\tp.FieldSpecs = nil\n\treturn yaml.Unmarshal(c, p)\n}\n\nfunc (p *AnnotationsTransformerPlugin) Transform(m resmap.ResMap) error {\n\tif len(p.Annotations) == 0 {\n\t\treturn nil\n\t}\n\treturn m.ApplyFilter(annotations.Filter{\n\t\tAnnotations: p.Annotations,\n\t\tFsSlice: p.FieldSpecs,\n\t})\n}\n\n\n\nfunc NewAnnotationsTransformerPlugin() resmap.TransformerPlugin ", "output": "{\n\treturn &AnnotationsTransformerPlugin{}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\nvar cmdRestoreSnapshot = &Command{\n\tRun: runRestoreSnapshot,\n\tUsage: \"restore-snapshot [-f] \",\n\tShort: \"restore snapshot\",\n\tLong: `\nRestores the specified snapshot.\n\nExample:\n\n $ es restore-snapshot my_backup snapshot1\n $ es restore-snapshot -f my_backup snapshot1\n`,\n\tApiUrl: \"http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-snapshots.html#_restore\",\n}\n\n\n\nfunc runRestoreSnapshot(cmd *Command, args []string) ", "output": "{\n\tif len(args) < 2 {\n\t\tcmd.printUsage()\n\t\tos.Exit(1)\n\t}\n\n\trepo := args[0]\n\tsnapshot := args[1]\n\n\tvar response struct {\n\t\tOk bool `json:\"ok,omitempty\"`\n\t\tAck bool `json:\"acknowledged,omitempty\"`\n\t\tError string `json:\"error,omitempty\"`\n\t\tStatus int `json:\"status,omitempty\"`\n\t}\n\tdata := getJsonFromStdin()\n\treq := ESReq(\"POST\", \"/_snapshot/\"+repo+\"/\"+snapshot+\"/_restore\")\n\tif data != nil {\n\t\treq.SetBodyJson(data)\n\t}\n\treq.Do(&response)\n\tif len(response.Error) > 0 {\n\t\tlog.Fatalf(\"Error: %v (%v)\\n\", response.Error, response.Status)\n\t}\n}"} {"input": "package log\n\nimport (\n\t\"log\"\n)\n\n\n\nfunc Debugln(args ...interface{}) {\n\tlog.Println(args...)\n}\n\nfunc Debugf(fmt string, args ...interface{}) ", "output": "{\n\tlog.Printf(fmt, args...)\n}"} {"input": "package service\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/coreos/go-etcd/etcd\"\n)\n\ntype Options struct {\n\tApiPort int\n\tApiInterface string\n\tPidPath string\n\tPort int\n\tInterface string\n\tCertPath string\n\tEtcdNodes listOptions\n\tEtcdKey string\n\tEtcdConsistency string\n}\n\n\ntype listOptions []string\n\n\n\nfunc (o *listOptions) Set(value string) error {\n\t*o = append(*o, value)\n\treturn nil\n}\n\nfunc ParseCommandLine() (options Options, err error) {\n\tflag.Var(&options.EtcdNodes, \"etcd\", \"Etcd discovery service API endpoints\")\n\tflag.StringVar(&options.EtcdKey, \"etcdKey\", \"vulcand\", \"Etcd key for storing configuration\")\n\tflag.StringVar(&options.EtcdConsistency, \"etcdConsistency\", etcd.STRONG_CONSISTENCY, \"Etcd consistency\")\n\tflag.StringVar(&options.PidPath, \"pidPath\", \"\", \"Path to write PID file to\")\n\tflag.IntVar(&options.Port, \"port\", 8181, \"Port to listen on\")\n\tflag.IntVar(&options.ApiPort, \"apiPort\", 8182, \"Port to provide api on\")\n\tflag.StringVar(&options.Interface, \"interface\", \"\", \"Interface to bind to\")\n\tflag.StringVar(&options.ApiInterface, \"apiInterface\", \"\", \"Interface to for API to bind to\")\n\tflag.StringVar(&options.CertPath, \"certPath\", \"\", \"Certificate to use (enables TLS)\")\n\tflag.Parse()\n\treturn options, nil\n}\n\nfunc (o *listOptions) String() string ", "output": "{\n\treturn fmt.Sprint(*o)\n}"} {"input": "package migrate\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/go-pg/migrations\"\n)\n\nconst accountTable = `\nCREATE TABLE accounts (\nid serial NOT NULL,\ncreated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,\nupdated_at timestamp with time zone DEFAULT current_timestamp,\nlast_login timestamp with time zone NOT NULL DEFAULT current_timestamp,\nemail text NOT NULL UNIQUE,\nname text NOT NULL,\nactive boolean NOT NULL DEFAULT TRUE,\nroles text[] NOT NULL DEFAULT '{\"user\"}',\nPRIMARY KEY (id)\n)`\n\nconst tokenTable = `\nCREATE TABLE tokens (\nid serial NOT NULL,\ncreated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,\nupdated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,\naccount_id int NOT NULL REFERENCES accounts(id),\ntoken text NOT NULL UNIQUE,\nexpiry timestamp with time zone NOT NULL,\nmobile boolean NOT NULL DEFAULT FALSE,\nidentifier text,\nPRIMARY KEY (id)\n)`\n\n\n\nfunc init() ", "output": "{\n\tup := []string{\n\t\taccountTable,\n\t\ttokenTable,\n\t}\n\n\tdown := []string{\n\t\t`DROP TABLE tokens`,\n\t\t`DROP TABLE accounts`,\n\t}\n\n\tmigrations.Register(func(db migrations.DB) error {\n\t\tfmt.Println(\"creating initial tables\")\n\t\tfor _, q := range up {\n\t\t\t_, err := db.Exec(q)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}, func(db migrations.DB) error {\n\t\tfmt.Println(\"dropping initial tables\")\n\t\tfor _, q := range down {\n\t\t\t_, err := db.Exec(q)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}"} {"input": "package handler\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/dinever/golf\"\n\t\"github.com/dingoblog/dingo/app/model\"\n)\n\nfunc registerUserHandlers(app *golf.Application, routes map[string]map[string]interface{}) {\n\tapp.Get(\"/api/users\", APIUsersHandler)\n\troutes[\"GET\"][\"users_url\"] = \"/api/users\"\n\n\tapp.Get(\"/api/users/:user_id\", APIUserHandler)\n\troutes[\"GET\"][\"user_url\"] = \"/api/users/:user_id\"\n\n\tapp.Get(\"/api/users/slug/:slug\", APIUserSlugHandler)\n\troutes[\"GET\"][\"user_slug_url\"] = \"/api/users/slug/:slug\"\n\n\tapp.Get(\"/api/users/email/:email\", APIUserEmailHandler)\n\troutes[\"GET\"][\"user_email_url\"] = \"/api/users/email/:email\"\n}\n\n\n\n\n\nfunc APIUserSlugHandler(ctx *golf.Context) {\n\tslug := ctx.Param(\"slug\")\n\tuser := &model.User{Slug: slug}\n\terr := user.GetUserBySlug()\n\tif err != nil {\n\t\thandleErr(ctx, 404, err)\n\t\treturn\n\t}\n\tctx.JSONIndent(user, \"\", \" \")\n}\n\n\nfunc APIUserEmailHandler(ctx *golf.Context) {\n\temail := ctx.Param(\"email\")\n\tuser := &model.User{Email: email}\n\terr := user.GetUserByEmail()\n\tif err != nil {\n\t\thandleErr(ctx, 404, err)\n\t\treturn\n\t}\n\tctx.JSONIndent(user, \"\", \" \")\n}\n\n\nfunc APIUsersHandler(ctx *golf.Context) {\n\tctx.JSONIndent(map[string]interface{}{\n\t\t\"message\": \"Not implemented\",\n\t}, \"\", \" \")\n}\n\nfunc APIUserHandler(ctx *golf.Context) ", "output": "{\n\tid, err := strconv.Atoi(ctx.Param(\"user_id\"))\n\tif err != nil {\n\t\thandleErr(ctx, 500, err)\n\t\treturn\n\t}\n\tuser := &model.User{Id: int64(id)}\n\terr = user.GetUserById()\n\tif err != nil {\n\t\thandleErr(ctx, 404, err)\n\t\treturn\n\t}\n\tctx.JSONIndent(user, \"\", \" \")\n}"} {"input": "package articles\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"gopkg.in/mgo.v2\"\n\t\"gopkg.in/mgo.v2/bson\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/go-angular-mongo/models\"\n)\n\n\nfunc Create(c *gin.Context) {\n\tdb := c.MustGet(\"db\").(*mgo.Database)\n\n\tarticle := models.Article{}\n\terr := c.Bind(&article)\n\tif err != nil {\n\t\tc.Error(err)\n\t\treturn\n\t}\n\n\tarticle.CreatedOn = time.Now().UnixNano() / int64(time.Millisecond)\n\tarticle.UpdatedOn = time.Now().UnixNano() / int64(time.Millisecond)\n\n\terr = db.C(models.CollectionArticle).Insert(article)\n\tif err != nil {\n\t\tc.Error(err)\n\t\treturn\n\t}\n}\n\n\nfunc List(c *gin.Context) {\n\tdb := c.MustGet(\"db\").(*mgo.Database)\n\tarticles := []models.Article{}\n\terr := db.C(models.CollectionArticle).Find(nil).Sort(\"-_id\").All(&articles)\n\tif err != nil {\n\t\tc.Error(err)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, articles)\n}\n\n\n\n\n\nfunc Delete(c *gin.Context) {\n\tdb := c.MustGet(\"db\").(*mgo.Database)\n\tarticle := models.Article{}\n\terr := c.Bind(&article)\n\tif err != nil {\n\t\tc.Error(err)\n\t\treturn\n\t}\n\tquery := bson.M{\"_id\": article.Id}\n\terr = db.C(models.CollectionArticle).Remove(query)\n\tif err != nil {\n\t\tc.Error(err)\n\t\treturn\n\t}\n}\n\nfunc Update(c *gin.Context) ", "output": "{\n\tdb := c.MustGet(\"db\").(*mgo.Database)\n\n\tarticle := models.Article{}\n\terr := c.Bind(&article)\n\tif err != nil {\n\t\tc.Error(err)\n\t\treturn\n\t}\n\n\tquery := bson.M{\"_id\": article.Id}\n\tdoc := bson.M{\n\t\t\"title\": article.Title,\n\t\t\"body\": article.Body,\n\t\t\"created_on\": article.CreatedOn,\n\t\t\"updated_on\": time.Now().UnixNano() / int64(time.Millisecond),\n\t}\n\terr = db.C(models.CollectionArticle).Update(query, doc)\n\tif err != nil {\n\t\tc.Error(err)\n\t\treturn\n\t}\n}"} {"input": "package user\n\nimport (\n\t\"errors\"\n\n\t. \"github.com/1ambda/gokit-waffle/waffle-server/service/common\"\n\t\"github.com/1ambda/gokit-waffle/waffle-server/service/number\"\n)\n\ntype UserService interface {\n\tUsers() []User\n\tUser(string) (int, error)\n}\n\ntype service struct {\n\trepository number.NumberRepository\n}\n\nfunc NewUserService(r number.NumberRepository) UserService {\n\treturn &service{repository: r}\n}\n\n\n\nfunc (svc service) User(u string) (int, error) {\n\tif u == \"\" {\n\t\treturn 0, errors.New(\"Empty `user`\")\n\t}\n\n\tuser := User(u)\n\tsubs, err := svc.repository.Find(user)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn subs.GetNumber(), err\n}\n\nfunc (svc *service) Users() []User ", "output": "{\n\tvar users []User\n\n\tfor _, subs := range svc.repository.FindAll() {\n\t\tusers = append(users, subs.User)\n\t}\n\n\treturn users\n}"} {"input": "package main\nimport (\n\"fmt\"\n\"time\"\n)\n\ntype Rocket struct{\n Name string\n}\n\n\n\n\ntype InSet struct{\n word []uint64\n}\n\nfunc (s *InSet) Has(x uint64) bool{\n word,bit:=x/64,uint64(x%64)\n return word` + err.Error() + ``))\n}\n\n\n\n\nfunc init(){\n\tregisterRoutes()\n}\n\nfunc registerRoutes() ", "output": "{\n\tmc := new(mainC)\n\troutes.Add(\"/\",mc.Index)\n}"} {"input": "package canvas\n\nimport \"math/rand\"\n\n\n\n\n\nfunc max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}\n\n\nfunc random() float64 {\n\treturn rand.Float64()\n}\n\nfunc min(x, y int) int ", "output": "{\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}"} {"input": "package entity\n\nimport (\n\t\"github.com/alvalor/alvalor-go/types\"\n\t\"github.com/stretchr/testify/mock\"\n)\n\n\ntype EventsMock struct {\n\tmock.Mock\n}\n\n\n\n\n\nfunc (em *EventsMock) Transaction(transaction types.Hash) {\n\tem.Called(transaction)\n}\n\nfunc (em *EventsMock) Header(header types.Hash) ", "output": "{\n\tem.Called(header)\n}"} {"input": "package lang\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"syscall\"\n)\n\nfunc getCmdTokens(p *Process) (exe string, parameters []string, err error) {\n\texe, err = p.Parameters.String(0)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tparameters = p.Parameters.StringArray()[1:]\n\n\treturn\n}\n\n\n\nfunc osSyscalls(cmd *exec.Cmd) ", "output": "{\n\tcmd.SysProcAttr = &syscall.SysProcAttr{\n\t\tCtty: int(os.Stdout.Fd()),\n\t}\n}"} {"input": "package relation\n\nimport (\n\t\"github.com/juju/names/v4\"\n\n\t\"github.com/juju/juju/api/uniter\"\n)\n\ntype stateTrackerStateShim struct {\n\t*uniter.State\n}\n\nfunc (s *stateTrackerStateShim) Relation(tag names.RelationTag) (Relation, error) {\n\trel, err := s.State.Relation(tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &relationShim{rel}, nil\n}\n\n\n\n\n\nfunc (s *stateTrackerStateShim) Unit(tag names.UnitTag) (Unit, error) {\n\tunit, err := s.State.Unit(tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &unitShim{unit}, nil\n}\n\ntype relationShim struct {\n\t*uniter.Relation\n}\n\nfunc (s *relationShim) Unit(uTag names.UnitTag) (RelationUnit, error) {\n\tu, err := s.Relation.Unit(uTag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RelationUnitShim{u}, nil\n}\n\ntype unitShim struct {\n\t*uniter.Unit\n}\n\nfunc (s *unitShim) Application() (Application, error) {\n\tapp, err := s.Unit.Application()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &applicationShim{app}, nil\n}\n\ntype applicationShim struct {\n\t*uniter.Application\n}\n\ntype RelationUnitShim struct {\n\t*uniter.RelationUnit\n}\n\nfunc (r *RelationUnitShim) Relation() Relation {\n\treturn &relationShim{r.RelationUnit.Relation()}\n}\n\nfunc (s *stateTrackerStateShim) RelationById(id int) (Relation, error) ", "output": "{\n\trel, err := s.State.RelationById(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &relationShim{rel}, nil\n}"} {"input": "package contentutil\n\nimport (\n\t\"context\"\n\n\t\"github.com/containerd/containerd/content\"\n\t\"github.com/containerd/containerd/errdefs\"\n\t\"github.com/containerd/containerd/remotes\"\n\t\"github.com/pkg/errors\"\n)\n\nfunc FromPusher(p remotes.Pusher) content.Ingester {\n\treturn &pushingIngester{\n\t\tp: p,\n\t}\n}\n\ntype pushingIngester struct {\n\tp remotes.Pusher\n}\n\n\n\n\ntype writer struct {\n\tcontent.Writer \n\tcontentWriterRef string \n}\n\nfunc (w *writer) Status() (content.Status, error) {\n\tst, err := w.Writer.Status()\n\tif err != nil {\n\t\treturn st, err\n\t}\n\tif w.contentWriterRef != \"\" {\n\t\tst.Ref = w.contentWriterRef\n\t}\n\treturn st, nil\n}\n\nfunc (i *pushingIngester) Writer(ctx context.Context, opts ...content.WriterOpt) (content.Writer, error) ", "output": "{\n\tvar wOpts content.WriterOpts\n\tfor _, opt := range opts {\n\t\tif err := opt(&wOpts); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif wOpts.Ref == \"\" {\n\t\treturn nil, errors.Wrap(errdefs.ErrInvalidArgument, \"ref must not be empty\")\n\t}\n\tcontentWriter, err := i.p.Push(ctx, wOpts.Desc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &writer{\n\t\tWriter: contentWriter,\n\t\tcontentWriterRef: wOpts.Ref,\n\t}, nil\n}"} {"input": "package geoip_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/corestoreio/csfw/net/ctxjwt\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\nfunc TestContextWithError(t *testing.T) ", "output": "{\n\n\tvar wantErr = errors.New(\"Contiki Context\")\n\tctx := ctxjwt.WithContextError(context.Background(), wantErr)\n\tassert.NotNil(t, ctx)\n\n\ttok, err := ctxjwt.FromContext(ctx)\n\tassert.Nil(t, tok)\n\tassert.EqualError(t, err, wantErr.Error())\n}"} {"input": "package oneandone\n\nimport \"net/http\"\n\ntype Pricing struct {\n\tCurrency string `json:\"currency,omitempty\"`\n\tPlan *pricingPlan `json:\"pricing_plans,omitempty\"`\n}\n\ntype pricingPlan struct {\n\tImage *pricingItem `json:\"image,omitempty\"`\n\tPublicIPs []pricingItem `json:\"public_ips,omitempty\"`\n\tServers *serverPricing `json:\"servers,omitempty\"`\n\tSharedStorage *pricingItem `json:\"shared_storage,omitempty\"`\n\tSoftwareLicenses []pricingItem `json:\"software_licences,omitempty\"`\n}\n\ntype serverPricing struct {\n\tFixedServers []pricingItem `json:\"fixed_servers,omitempty\"`\n\tFlexServers []pricingItem `json:\"flexible_server,omitempty\"`\n}\n\ntype pricingItem struct {\n\tName string `json:\"name,omitempty\"`\n\tGrossPrice string `json:\"price_gross,omitempty\"`\n\tNetPrice string `json:\"price_net,omitempty\"`\n\tUnit string `json:\"unit,omitempty\"`\n}\n\n\n\n\nfunc (api *API) GetPricing() (*Pricing, error) ", "output": "{\n\tresult := new(Pricing)\n\turl := createUrl(api, pricingPathSegment)\n\terr := api.Client.Get(url, &result, http.StatusOK)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}"} {"input": "package zookeeper\n\nimport (\n\t\"os\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc GetZookeeperEnvPort() string {\n\tport := os.Getenv(\"ZOOKEEPER_PORT\")\n\n\tif len(port) == 0 {\n\t\tport = \"2181\"\n\t}\n\treturn port\n}\n\nfunc GetZookeeperEnvHost() string ", "output": "{\n\thost := os.Getenv(\"ZOOKEEPER_HOST\")\n\n\tif len(host) == 0 {\n\t\thost = \"localhost\"\n\t}\n\treturn host\n}"} {"input": "package lock\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/bradfitz/gomemcache/memcache\"\n)\n\nconst testServer = \"localhost:11211\"\n\n\n\nfunc TestAcquire(t *testing.T) {\n\tkey := \"k\"\n\tmc := memcache.New(testServer)\n\tm := &Memcache{Prefix: \"test:\", Cache: mc}\n\tm.Release(key)\n\tdefer m.Release(key)\n\n\tif !m.Acquire(key, 2, time.Microsecond, 1) {\n\t\tt.Error(\"Cannot acquire first lock\")\n\t}\n\tif m.Acquire(key, 2, time.Microsecond, 1) {\n\t\tt.Error(\"Can acquire lock when already acquired\")\n\t}\n\tif nil != m.Release(key) {\n\t\tt.Error(\"Cannot release log\")\n\t}\n}\n\nfunc TestGetLockKey(t *testing.T) ", "output": "{\n\tm := &Memcache{Prefix: \"test:\"}\n\tif m.getLockKey(\"k\") != \"test:k\" {\n\t\tt.Errorf(\"Invalid lock key\")\n\t}\n}"} {"input": "package minecraft\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"github.com/LilyPad/GoLilyPad/packet\"\n)\n\ntype PacketServerPluginMessage struct {\n\tChannel string\n\tData []byte\n}\n\n\n\nfunc (this *PacketServerPluginMessage) Id() int {\n\treturn PACKET_SERVER_PLUGIN_MESSAGE\n}\n\ntype packetServerPluginMessageCodec struct {\n\n}\n\nfunc (this *packetServerPluginMessageCodec) Decode(reader io.Reader) (decode packet.Packet, err error) {\n\tpacketServerPluginMessage := new(PacketServerPluginMessage)\n\tpacketServerPluginMessage.Channel, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\tpacketServerPluginMessage.Data, err = ioutil.ReadAll(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\tdecode = packetServerPluginMessage\n\treturn\n}\n\nfunc (this *packetServerPluginMessageCodec) Encode(writer io.Writer, encode packet.Packet) (err error) {\n\tpacketServerPluginMessage := encode.(*PacketServerPluginMessage)\n\terr = packet.WriteString(writer, packetServerPluginMessage.Channel)\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = writer.Write(packetServerPluginMessage.Data)\n\treturn\n}\n\nfunc NewPacketServerPluginMessage(channel string, data []byte) (this *PacketServerPluginMessage) ", "output": "{\n\tthis = new(PacketServerPluginMessage)\n\tthis.Channel = channel\n\tthis.Data = data\n\treturn\n}"} {"input": "package logwise\n\nimport (\n \"fmt\"\n \"os\"\n)\n\ntype Writer interface {\n Write(lines []string)\n}\n\ntype FileWriter struct {\n FilePath string\n Append bool\n Prefix string\n Postfix string\n}\n\n\n\nfunc (w *FileWriter) AddPrefix(prefix string) *FileWriter {\n w.Prefix = prefix\n return w\n}\n\nfunc (w *FileWriter) AddPostfix(postfix string) *FileWriter {\n w.Postfix = postfix\n return w\n}\n\nfunc (w *FileWriter) Write(lines []string) {\n var flags int\n\n if w.Append {\n flags = os.O_WRONLY | os.O_APPEND\n } else {\n flags = os.O_CREATE | os.O_WRONLY | os.O_TRUNC\n }\n\n file,_ := os.OpenFile(w.FilePath, flags, 0666)\n defer file.Close()\n \n if w.Prefix != \"\" {\n file.WriteString(fmt.Sprintf(\"%v\\n\", w.Prefix))\n }\n\n for _,line := range lines {\n file.WriteString(fmt.Sprintf(\"%v\\n\", line))\n }\n\n if w.Postfix != \"\" {\n file.WriteString(fmt.Sprintf(\"%v\\n\", w.Postfix))\n }\n}\n\nfunc NewFileWriter(filePath string, append bool, prefix,sufix string) Writer ", "output": "{\n return &FileWriter{filePath, append, prefix, sufix}\n}"} {"input": "package spotify\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/laicosly/goth\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc Test_New(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\tp := provider()\n\n\ta.Equal(p.ClientKey, os.Getenv(\"SPOTIFY_KEY\"))\n\ta.Equal(p.Secret, os.Getenv(\"SPOTIFY_SECRET\"))\n\ta.Equal(p.CallbackURL, \"/foo\")\n}\n\nfunc Test_ImplementsProvider(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\ta.Implements((*goth.Provider)(nil), provider())\n}\n\nfunc Test_BeginAuth(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\n\tp := provider()\n\tsession, err := p.BeginAuth(\"test_state\")\n\ts := session.(*Session)\n\ta.NoError(err)\n\ta.Contains(s.AuthURL, \"accounts.spotify.com/authorize\")\n}\n\nfunc Test_SessionFromJSON(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\n\tp := provider()\n\tsession, err := p.UnmarshalSession(`{\"AuthURL\":\"http://accounts.spotify.com/authorize\",\"AccessToken\":\"1234567890\"}`)\n\ta.NoError(err)\n\n\ts := session.(*Session)\n\ta.Equal(s.AuthURL, \"http://accounts.spotify.com/authorize\")\n\ta.Equal(s.AccessToken, \"1234567890\")\n}\n\nfunc provider() *Provider ", "output": "{\n\treturn New(os.Getenv(\"SPOTIFY_KEY\"), os.Getenv(\"SPOTIFY_SECRET\"), \"/foo\", \"user\")\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"utils\"\n)\n\nfunc main() {\n sum := 0\n for a := 2; a < 10000; a++ {\n b := d(a)\n if a != b && a == d(b) {\n sum += a\n }\n }\n fmt.Println(sum)\n}\n\n\n\nfunc d(n int) int ", "output": "{\n sum := -n\n for _, i := range(utils.Divisors(uint64(n))) {\n sum += int(i)\n }\n return sum\n}"} {"input": "package options\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/apimachinery/pkg/util/errors\"\n\t\"k8s.io/apiserver/pkg/authentication/request/headerrequest\"\n\t\"k8s.io/apiserver/pkg/server/dynamiccertificates\"\n\t\"k8s.io/client-go/kubernetes\"\n)\n\nvar _ dynamiccertificates.ControllerRunner = &DynamicRequestHeaderController{}\nvar _ dynamiccertificates.CAContentProvider = &DynamicRequestHeaderController{}\n\nvar _ headerrequest.RequestHeaderAuthRequestProvider = &DynamicRequestHeaderController{}\n\n\n\ntype DynamicRequestHeaderController struct {\n\t*dynamiccertificates.ConfigMapCAController\n\t*headerrequest.RequestHeaderAuthRequestController\n}\n\n\n\n\nfunc (c *DynamicRequestHeaderController) RunOnce() error {\n\terrs := []error{}\n\terrs = append(errs, c.ConfigMapCAController.RunOnce())\n\terrs = append(errs, c.RequestHeaderAuthRequestController.RunOnce())\n\treturn errors.NewAggregate(errs)\n}\n\nfunc (c *DynamicRequestHeaderController) Run(workers int, stopCh <-chan struct{}) {\n\tgo c.ConfigMapCAController.Run(workers, stopCh)\n\tgo c.RequestHeaderAuthRequestController.Run(workers, stopCh)\n\t<-stopCh\n}\n\nfunc newDynamicRequestHeaderController(client kubernetes.Interface) (*DynamicRequestHeaderController, error) ", "output": "{\n\trequestHeaderCAController, err := dynamiccertificates.NewDynamicCAFromConfigMapController(\n\t\t\"client-ca\",\n\t\tauthenticationConfigMapNamespace,\n\t\tauthenticationConfigMapName,\n\t\t\"requestheader-client-ca-file\",\n\t\tclient)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create DynamicCAFromConfigMap controller: %v\", err)\n\t}\n\n\trequestHeaderAuthRequestController := headerrequest.NewRequestHeaderAuthRequestController(\n\t\tauthenticationConfigMapName,\n\t\tauthenticationConfigMapNamespace,\n\t\tclient,\n\t\t\"requestheader-username-headers\",\n\t\t\"requestheader-group-headers\",\n\t\t\"requestheader-extra-headers-prefix\",\n\t\t\"requestheader-allowed-names\",\n\t)\n\treturn &DynamicRequestHeaderController{\n\t\tConfigMapCAController: requestHeaderCAController,\n\t\tRequestHeaderAuthRequestController: requestHeaderAuthRequestController,\n\t}, nil\n}"} {"input": "package tcp\n\nimport (\n\t\"bufio\"\n\t\"log\"\n\t\"net\"\n)\n\nconst tcp_port string = \"0.0.0.0:5170\"\n\nfunc ListenAndServe(ch chan string) {\n\tl, err := net.Listen(\"tcp\", tcp_port)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tlog.Println(\"New incomming connection\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"%v\", err.Error())\n\t\t}\n\t\tgo handleConnection(conn, ch)\n\t}\n}\n\n\n\n\nfunc handleConnection(c net.Conn, ch chan string)", "output": "{\n\tdefer c.Close()\n\tfor {\n\t\tmessage, err := bufio.NewReader(c).ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbreak\n\t\t}\n\n\t\tch <- message;\n\t}\n}"} {"input": "package seq \n\n\n\n\n\n\nimport \"fmt\"\n\n\n\nvar Transact func(ref *Ref, code int, in *Buffer) (out *Buffer)\n\n\nvar FinalizeRef func(ref *Ref)\n\n\ntype Func func(out, in *Buffer)\n\n\n\nvar Registry = make(map[string]map[int]Func)\n\n\n\n\nfunc Register(descriptor string, code int, fn Func) ", "output": "{\n\tm := Registry[descriptor]\n\tif m == nil {\n\t\tm = make(map[int]Func)\n\t\tRegistry[descriptor] = m\n\t}\n\tif m[code] != nil {\n\t\tpanic(fmt.Sprintf(\"registry.Register: %q/%d already registered\", descriptor, code))\n\t}\n\tm[code] = fn\n}"} {"input": "package iso20022\n\n\ntype CorporateActionElection1 struct {\n\n\tOptionType *CorporateActionOption1FormatChoice `xml:\"OptnTp\"`\n\n\tOptionNumber *Exact3NumericText `xml:\"OptnNb\"`\n\n\tOriginalInstructedQuantity *UnitOrFaceAmount1Choice `xml:\"OrgnlInstdQty\"`\n\n\tRemainingQuantity *UnitOrFaceAmount1Choice `xml:\"RmngQty\"`\n}\n\nfunc (c *CorporateActionElection1) AddOptionType() *CorporateActionOption1FormatChoice {\n\tc.OptionType = new(CorporateActionOption1FormatChoice)\n\treturn c.OptionType\n}\n\n\n\nfunc (c *CorporateActionElection1) AddOriginalInstructedQuantity() *UnitOrFaceAmount1Choice {\n\tc.OriginalInstructedQuantity = new(UnitOrFaceAmount1Choice)\n\treturn c.OriginalInstructedQuantity\n}\n\nfunc (c *CorporateActionElection1) AddRemainingQuantity() *UnitOrFaceAmount1Choice {\n\tc.RemainingQuantity = new(UnitOrFaceAmount1Choice)\n\treturn c.RemainingQuantity\n}\n\nfunc (c *CorporateActionElection1) SetOptionNumber(value string) ", "output": "{\n\tc.OptionNumber = (*Exact3NumericText)(&value)\n}"} {"input": "package harlog\n\nimport (\n \"net/http\"\n \"testing\"\n)\n\n\n\nfunc TestNewLog(t *testing.T) {\n\n har := NewHARLog()\n har.Dump()\n}\n\nfunc TestAddEntry(t *testing.T) {\n\n req, resp := makerr()\n har := NewHARLog()\n har.Entries.Add(req, resp)\n}\n\nfunc TestDump(t *testing.T) {\n\n req, resp := makerr()\n har := NewHARLog()\n har.Entries.Add(req, resp)\n har.Dump()\n}\n\nfunc makerr() (*http.Request, *http.Response) ", "output": "{\n\n req, _ := http.NewRequest(\"GET\", \"http://www.example.com/path/?param=value\", nil)\n resp := &http.Response{\n Status: \"200 OK\",\n StatusCode: 200,\n Proto: \"HTTP/1.0\",\n ProtoMajor: 1,\n ProtoMinor: 0,\n Request: req,\n Header: http.Header{\n \"Connection\": {\"close\"},\n },\n Close: true,\n ContentLength: -1,\n }\n\n return req, resp\n}"} {"input": "package longrunning_test\n\nimport (\n\t\"cloud.google.com/go/longrunning/autogen\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/api/iterator\"\n\tlongrunningpb \"google.golang.org/genproto/googleapis/longrunning\"\n)\n\n\n\nfunc ExampleOperationsClient_GetOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.GetOperationRequest{\n\t}\n\tresp, err := c.GetOperation(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleOperationsClient_ListOperations() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.ListOperationsRequest{\n\t}\n\tit := c.ListOperations(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}\n\nfunc ExampleOperationsClient_CancelOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.CancelOperationRequest{\n\t}\n\terr = c.CancelOperation(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleOperationsClient_DeleteOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.DeleteOperationRequest{\n\t}\n\terr = c.DeleteOperation(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleNewOperationsClient() ", "output": "{\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}"} {"input": "package payload_test\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/RobotsAndPencils/buford/payload\"\n)\n\nfunc ExampleBrowser() {\n\tp := payload.Browser{\n\t\tAlert: payload.BrowserAlert{\n\t\t\tTitle: \"Flight A998 Now Boarding\",\n\t\t\tBody: \"Boarding has begun for Flight A998.\",\n\t\t\tAction: \"View\",\n\t\t},\n\t\tURLArgs: []string{\"boarding\", \"A998\"},\n\t}\n\n\tb, err := json.Marshal(p)\n\tif err != nil {\n\t}\n\tfmt.Printf(\"%s\", b)\n}\n\nfunc TestBrowser(t *testing.T) {\n\tp := payload.Browser{\n\t\tAlert: payload.BrowserAlert{\n\t\t\tTitle: \"Flight A998 Now Boarding\",\n\t\t\tBody: \"Boarding has begun for Flight A998.\",\n\t\t\tAction: \"View\",\n\t\t},\n\t\tURLArgs: []string{\"boarding\", \"A998\"},\n\t}\n\texpected := []byte(`{\"aps\":{\"alert\":{\"title\":\"Flight A998 Now Boarding\",\"body\":\"Boarding has begun for Flight A998.\",\"action\":\"View\"},\"url-args\":[\"boarding\",\"A998\"]}}`)\n\ttestPayload(t, p, expected)\n}\n\nfunc TestValidBrowser(t *testing.T) {\n\tp := payload.Browser{\n\t\tAlert: payload.BrowserAlert{\n\t\t\tTitle: \"Flight A998 Now Boarding\",\n\t\t\tBody: \"Boarding has begun for Flight A998.\",\n\t\t},\n\t}\n\tif err := p.Validate(); err != nil {\n\t\tt.Errorf(\"Expected no error, got %v.\", err)\n\t}\n}\n\n\n\nfunc TestInvalidBrowser(t *testing.T) ", "output": "{\n\ttests := []*payload.Browser{\n\t\t{\n\t\t\tAlert: payload.BrowserAlert{Action: \"View\"},\n\t\t},\n\t\t{},\n\t\tnil,\n\t}\n\n\tfor _, p := range tests {\n\t\tif err := p.Validate(); err != payload.ErrIncomplete {\n\t\t\tt.Errorf(\"Expected err %v, got %v.\", payload.ErrIncomplete, err)\n\t\t}\n\t}\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\ntype Response struct {\n\tStatus string `json:\"status\"`\n\tErrorText string `json:\"errorText,omitempty\"`\n\tAddress string `json:\"address,omitempty\"`\n\tStatusCode int `json:\"statusCode,omitempty\"`\n\tVersion string `json:\"version,omitempty\"`\n}\n\ntype Responses struct {\n\tResponses []Response `json:\"responses\"`\n}\n\nfunc (r *Response) Fill(outStr string, err error) {\n\tif err != nil {\n\t\tr.Status = \"ERR\"\n\t\tr.ErrorText = strings.TrimSpace(outStr + \" \" + err.Error())\n\t} else {\n\t\tr.Status = \"OK\"\n\t}\n}\n\nfunc (r Responses) String() string {\n\tj, _ := json.Marshal(r)\n\treturn fmt.Sprintf(\"Responses: %s\", string(j))\n}\n\n\n\nfunc (r Response) WriteHttp(w http.ResponseWriter) (resp Response) {\n\tif r.StatusCode == 0 {\n\t\tr.StatusCode = 200\n\t}\n\tw.WriteHeader(r.StatusCode)\n\treturn EncodeJson(r, w)\n}\n\nfunc (r Response) WriteBadRequestHttp(w http.ResponseWriter) (resp Response) {\n\tw.WriteHeader(http.StatusBadRequest)\n\tr.StatusCode = http.StatusBadRequest\n\treturn EncodeJson(r, w)\n}\n\nfunc (r Response) WriteInternalServerErrorHttp(w http.ResponseWriter) (resp Response) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tr.StatusCode = http.StatusInternalServerError\n\treturn EncodeJson(r, w)\n}\n\nfunc EncodeJson(r Response, w http.ResponseWriter) (resp Response) {\n\terr := json.NewEncoder(w).Encode(r)\n\tif err != nil {\n\t\tlog.Printf(\"[writehttp] failed to create json from model: %s\", err.Error())\n\t}\n\treturn r\n}\n\nfunc (r Response) String() string ", "output": "{\n\tj, _ := json.Marshal(r)\n\treturn fmt.Sprintf(\"Response: %s\", string(j))\n}"} {"input": "package gtka\n\nimport (\n\t\"github.com/coyim/gotk3adapter/gtki\"\n\t\"github.com/gotk3/gotk3/gtk\"\n)\n\ntype toolButton struct {\n\t*bin\n\tinternal *gtk.ToolButton\n}\n\nfunc WrapToolButtonSimple(v *gtk.ToolButton) gtki.ToolButton {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn &toolButton{WrapBinSimple(&v.Bin).(*bin), v}\n}\n\nfunc WrapToolButton(v *gtk.ToolButton, e error) (gtki.ToolButton, error) {\n\treturn WrapToolButtonSimple(v), e\n}\n\n\n\nfunc (v *toolButton) Add(v1 gtki.Widget) {\n\tv.internal.Add(UnwrapWidget(v1))\n}\n\nfunc UnwrapToolButton(v gtki.ToolButton) *gtk.ToolButton ", "output": "{\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*toolButton).internal\n}"} {"input": "package kvstore\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/cilium/cilium/pkg/metrics\"\n\t\"github.com/cilium/cilium/pkg/option\"\n)\n\nconst (\n\tmetricDelete = \"delete\"\n\tmetricRead = \"read\"\n\tmetricSet = \"set\"\n)\n\nfunc getScopeFromKey(key string) string {\n\ts := strings.SplitN(key, \"/\", 5)\n\tif len(s) != 5 {\n\t\tif len(key) >= 12 {\n\t\t\treturn key[:12]\n\t\t}\n\t\treturn key\n\t}\n\treturn fmt.Sprintf(\"%s/%s\", s[2], s[3])\n}\n\nfunc increaseMetric(key, kind, action string, duration time.Duration, err error) {\n\tif !option.Config.MetricsConfig.KVStoreOperationsDurationEnabled {\n\t\treturn\n\t}\n\tnamespace := getScopeFromKey(key)\n\toutcome := metrics.Error2Outcome(err)\n\tmetrics.KVStoreOperationsDuration.\n\t\tWithLabelValues(namespace, kind, action, outcome).Observe(duration.Seconds())\n}\n\nfunc trackEventQueued(key string, typ EventType, duration time.Duration) {\n\tif !option.Config.MetricsConfig.KVStoreEventsQueueDurationEnabled {\n\t\treturn\n\t}\n\tmetrics.KVStoreEventsQueueDuration.WithLabelValues(getScopeFromKey(key), typ.String()).Observe(duration.Seconds())\n}\n\n\n\nfunc recordQuorumError(err string) ", "output": "{\n\tif !option.Config.MetricsConfig.KVStoreQuorumErrorsEnabled {\n\t\treturn\n\t}\n\tmetrics.KVStoreQuorumErrors.WithLabelValues(err).Inc()\n}"} {"input": "package factories\n\nimport (\n\t\"testing\"\n\n\t\"gotest.tools/v3/assert\"\n\t\"k8s.io/client-go/rest\"\n)\n\nfunc TestNewKafkaSourceFactory(t *testing.T) {\n\tfactory := NewFakeKafkaSourceFactory(\"fake-namespace\")\n\n\tassert.Assert(t, factory != nil)\n}\n\nfunc TestCreateKafkaSourceParams(t *testing.T) {\n\tfactory := NewFakeKafkaSourceFactory(\"fake-namespace\")\n\n\tsourceParams := factory.CreateKafkaSourceParams()\n\tassert.Assert(t, sourceParams != nil)\n\tassert.Equal(t, factory.KafkaSourceParams(), sourceParams)\n}\n\n\n\nfunc TestCreateKafkaSourceClient(t *testing.T) ", "output": "{\n\tfactory := NewFakeKafkaSourceFactory(\"fake-namespace\")\n\tclient, _ := factory.CreateKafkaSourceClient(&rest.Config{}, \"fake-namespace\")\n\n\tassert.Assert(t, client != nil)\n\tassert.Equal(t, factory.KafkaSourceClient(), client)\n\tassert.Equal(t, factory.CreateKnSourceClient(&rest.Config{}, \"fake-namespace\"), client)\n\tassert.Equal(t, client.Namespace(), \"fake-namespace\")\n}"} {"input": "package cli\n\nimport (\n\t\"os\"\n\t\"fmt\"\n)\n\n\ntype Cmd interface {\n\tKey() string\n\tDescription() string\n\tExecute(args []string) error\n\tPrintUsage()\n}\n\n\n\ntype CmdHandler interface {\n\tRegisterCmd(Cmd)\n\tHandle()\n\tHandleCmd(key string, args []string)\n\tPrintUsage()\n}\n\n\nfunc NewCmdHandler() CmdHandler {\n\th := initCmdHandler()\n\th.RegisterCmd(NewBuildCmd())\n\treturn h\n}\n\nfunc initCmdHandler() *cmdHandler {\n\th := new(cmdHandler)\n\th.cmds = make(map[string]Cmd)\n\treturn h\n}\n\ntype cmdHandler struct {\n\tcmds map[string]Cmd\n}\n\nfunc (h *cmdHandler) RegisterCmd(cmd Cmd) {\n\tkey := cmd.Key()\n\th.cmds[key] = cmd\n}\n\n\n\nfunc (h *cmdHandler) PrintUsage() {\n}\n\nfunc (h *cmdHandler) HandleCmd(key string, args []string) {\n\tcmd := h.cmds[key]\n\tif cmd == nil {\n\t\th.handleUsageError(\"Unrecognized command: \" + key)\n\t\treturn\n\t}\n\terr := cmd.Execute(args)\n\tif err != nil {\n\t\th.handleError(err)\n\t}\n}\n\n\nfunc (h *cmdHandler) handleUsageError(message string) {\n\tfmt.Println(message)\n\th.PrintUsage()\n}\n\n\nfunc (h *cmdHandler) handleError(err error) {\n\tfmt.Println(err)\n}\n\nfunc (h *cmdHandler) Handle() ", "output": "{\n\targs := os.Args\n\tif args == nil || len(args) < 2 {\n\t\th.handleUsageError(\"Insufficient arguments\")\n\t\treturn\n\t} \n\tkey := args[1]\n\tcmdArgs := args[2:]\n\th.HandleCmd(key, cmdArgs)\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n)\n\n\ntype AttachVnicDetails struct {\n\tCreateVnicDetails *CreateVnicDetails `mandatory:\"true\" json:\"createVnicDetails\"`\n\n\tInstanceId *string `mandatory:\"true\" json:\"instanceId\"`\n\n\tDisplayName *string `mandatory:\"false\" json:\"displayName\"`\n\n\tNicIndex *int `mandatory:\"false\" json:\"nicIndex\"`\n}\n\n\n\nfunc (m AttachVnicDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"html/template\"\n \"io/ioutil\"\n \"net/http\"\n \"os\"\n)\n\ntype Page struct {\n\tTitle string\n\tBody []byte\n}\n\nfunc (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}\n\nfunc loadPage(title string) (*Page, error) {\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Page{Title: title, Body: body}, nil\n}\n\nfunc renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {\n t, _ := template.ParseFiles(tmpl + \".html\")\n t.Execute(w, p)\n}\n\n\n\nfunc editHandler(w http.ResponseWriter, r *http.Request) {\n title := r.URL.Path[len(\"/edit/\"):]\n p, err := loadPage(title)\n if err != nil {\n p = &Page{Title: title}\n }\n renderTemplate(w, \"edit\", p)\n}\n\nfunc main() {\n http.HandleFunc(\"/view/\", viewHandler)\n http.HandleFunc(\"/edit/\", editHandler)\n \n fmt.Println(\"starting http service ...\")\n http.ListenAndServe(os.Getenv(\"IP\") + \":\" + os.Getenv(\"PORT\"), nil)\n}\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n title := r.URL.Path[len(\"/view/\"):]\n p, err := loadPage(title)\n if err != nil {\n http.Redirect(w, r, \"/edit/\" + title, http.StatusFound)\n return\n }\n renderTemplate(w, \"view\", p)\n}"} {"input": "package caaa\n\nimport (\n\t\"encoding/xml\"\n\n\t\"github.com/fgrid/iso20022\"\n)\n\ntype Document00900101 struct {\n\tXMLName xml.Name `xml:\"urn:iso:std:iso:20022:tech:xsd:caaa.009.001.01 Document\"`\n\tMessage *AcceptorReconciliationRequestV01 `xml:\"AccptrRcncltnReq\"`\n}\n\nfunc (d *Document00900101) AddMessage() *AcceptorReconciliationRequestV01 {\n\td.Message = new(AcceptorReconciliationRequestV01)\n\treturn d.Message\n}\n\n\n\n\n\n\ntype AcceptorReconciliationRequestV01 struct {\n\n\tHeader *iso20022.Header1 `xml:\"Hdr\"`\n\n\tReconciliationRequest *iso20022.AcceptorReconciliationRequest1 `xml:\"RcncltnReq\"`\n\n\tSecurityTrailer *iso20022.ContentInformationType3 `xml:\"SctyTrlr\"`\n}\n\nfunc (a *AcceptorReconciliationRequestV01) AddHeader() *iso20022.Header1 {\n\ta.Header = new(iso20022.Header1)\n\treturn a.Header\n}\n\n\n\nfunc (a *AcceptorReconciliationRequestV01) AddSecurityTrailer() *iso20022.ContentInformationType3 {\n\ta.SecurityTrailer = new(iso20022.ContentInformationType3)\n\treturn a.SecurityTrailer\n}\n\nfunc (a *AcceptorReconciliationRequestV01) AddReconciliationRequest() *iso20022.AcceptorReconciliationRequest1 ", "output": "{\n\ta.ReconciliationRequest = new(iso20022.AcceptorReconciliationRequest1)\n\treturn a.ReconciliationRequest\n}"} {"input": "package graph\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gonum/graph\"\n\n\tkapi \"github.com/GoogleCloudPlatform/kubernetes/pkg/api\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime\"\n)\n\nvar (\n\tUnknownNodeKind = \"UnknownNode\"\n)\n\nvar (\n\tUnknownEdgeKind = \"UnknownEdge\"\n\tReferencedByEdgeKind = \"ReferencedBy\"\n\tContainsEdgeKind = \"Contains\"\n)\n\n\n\n\n\nfunc GetTopLevelContainerNode(g Graph, containedNode graph.Node) graph.Node {\n\tvisited := map[int]bool{}\n\tprevContainingNode := containedNode\n\n\tfor {\n\t\tvisited[prevContainingNode.ID()] = true\n\t\tcurrContainingNode := GetContainingNode(g, prevContainingNode)\n\n\t\tif currContainingNode == nil {\n\t\t\treturn prevContainingNode\n\t\t}\n\t\tif _, alreadyVisited := visited[currContainingNode.ID()]; alreadyVisited {\n\t\t\tpanic(fmt.Sprintf(\"contains cycle in %v\", visited))\n\t\t}\n\n\t\tprevContainingNode = currContainingNode\n\t}\n\n\tpanic(fmt.Sprintf(\"math failed %v\", visited))\n\treturn nil\n}\n\n\n\nfunc GetContainingNode(g Graph, containedNode graph.Node) graph.Node {\n\tfor _, node := range g.To(containedNode) {\n\t\tedge := g.Edge(node, containedNode)\n\n\t\tif g.EdgeKinds(edge).Has(ContainsEdgeKind) {\n\t\t\treturn node\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc GetUniqueRuntimeObjectNodeName(nodeKind string, obj runtime.Object) UniqueName ", "output": "{\n\tmeta, err := kapi.ObjectMetaFor(obj)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn UniqueName(fmt.Sprintf(\"%s|%s/%s\", nodeKind, meta.Namespace, meta.Name))\n}"} {"input": "package frames\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\ntype RstStreamFrame struct {\n\tStreamId uint32\n\tErrorCode ErrorCode\n}\n\nfunc NewRstStreamFrame(streamId uint32, errorCode ErrorCode) *RstStreamFrame {\n\treturn &RstStreamFrame{\n\t\tStreamId: streamId,\n\t\tErrorCode: errorCode,\n\t}\n}\n\nfunc DecodeRstStreamFrame(flags byte, streamId uint32, payload []byte, context *DecodingContext) (Frame, error) {\n\tif len(payload) != 4 {\n\t\treturn nil, fmt.Errorf(\"FRAME_SIZE_ERROR: Received RST_STREAM frame of length %v\", len(payload))\n\t}\n\treturn NewRstStreamFrame(streamId, ErrorCode(binary.BigEndian.Uint32(payload))), nil\n}\n\nfunc (f *RstStreamFrame) Type() Type {\n\treturn RST_STREAM_TYPE\n}\n\nfunc (f *RstStreamFrame) Encode(context *EncodingContext) ([]byte, error) {\n\tresult := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(result, uint32(f.ErrorCode))\n\treturn result, nil\n}\n\n\n\nfunc (f *RstStreamFrame) GetStreamId() uint32 ", "output": "{\n\treturn f.StreamId\n}"} {"input": "package tgbot\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype (\n\tSendPhotoRequest struct {\n\t\tChatId int\n\t\tCaption string\n\t\tPhotoUrl string\n\t\tPhotoPath string\n\t\tPhoto string\n\t\tReplyToMessageId int\n\t\tReplyMarkup\n\t}\n\n\tSendPhotoResponse struct {\n\t\tOk bool `json:\"ok\"`\n\t\tResult Message `json:\"result\"`\n\t\tErrorCode int `json:\"error_code\"`\n\t\tDescription string `json:\"description\"`\n\t}\n)\n\n\n\nfunc (this *SendPhotoRequest) getParams() ([]*Param, error) {\n\treplyMarkupJson, _ := json.Marshal(this.ReplyMarkup)\n\n\tres := []*Param{\n\t\t{Type: \"string\", Key: \"chat_id\", Value: strconv.Itoa(this.ChatId)},\n\t\t{Type: \"string\", Key: \"reply_markup\", Value: string(replyMarkupJson)},\n\t\t{Type: \"string\", Key: \"reply_to_message_id\", Value: string(this.ReplyToMessageId)},\n\t\t{Type: \"string\", Key: \"caption\", Value: this.Caption},\n\t}\n\n\tif this.PhotoPath != \"\" {\n\t\tres = append(res, &Param{Type: \"filePath\", Key: \"photo\", Value: this.PhotoPath})\n\t}\n\n\tif this.PhotoUrl != \"\" {\n\t\tres = append(res, &Param{Type: \"fileUrl\", Key: \"photo\", Value: this.PhotoUrl})\n\t}\n\n\tif this.Photo != \"\" {\n\t\tres = append(res, &Param{Type: \"string\", Key: \"photo\", Value: this.Photo})\n\t}\n\n\treturn res, nil\n}\n\nfunc (this *SendPhotoRequest) Send(secret string) (*SendPhotoResponse, error) ", "output": "{\n\turl := getUrl(\"sendPhoto\", secret)\n\n\tparams, err := this.getParams()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trespJson, err := sendPost(url, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdec := json.NewDecoder(strings.NewReader(respJson))\n\n\tvar resp *SendPhotoResponse\n\tif err := dec.Decode(&resp); err == io.EOF {\n\t\treturn resp, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}"} {"input": "package config\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/go-ini/ini\"\n)\n\nfunc LoadConfigFile(filename string) (map[string]string, error) {\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\t\tlog.Infof(\"Ignoring absent config file: %v\", filename)\n\t\treturn nil, nil\n\t}\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn LoadConfigFileData(data)\n}\n\n\n\nfunc LoadConfigFileData(data []byte) (map[string]string, error) ", "output": "{\n\tiniFile, err := ini.Load(data)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to load config file: %v\", err)\n\t\treturn nil, err\n\t}\n\tkvs := make(map[string]string)\n\tfor _, section := range iniFile.Sections() {\n\t\tlog.Debugf(\"Parsing section %v\", section.Name())\n\t\tfor _, key := range section.Keys() {\n\t\t\tif _, ok := kvs[key.Name()]; ok {\n\t\t\t\tlog.Warningf(\"Multiple values defined for key %v\", key.Name())\n\t\t\t}\n\t\t\tkvs[key.Name()] = key.Value()\n\t\t}\n\t}\n\treturn kvs, nil\n}"} {"input": "package transfer\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestPicksDatanodesWithoutFailures(t *testing.T) {\n\tdf := newDatanodeFailover([]string{\"foo:6000\", \"foo:7000\", \"bar:6000\"})\n\tdatanodeFailures[\"foo:6000\"] = time.Now()\n\n\tassert.EqualValues(t, df.next(), \"foo:7000\")\n}\n\nfunc TestPicksDatanodesWithOldestFailures(t *testing.T) {\n\tdf := newDatanodeFailover([]string{\"foo:6000\", \"bar:6000\"})\n\tdatanodeFailures[\"foo:6000\"] = time.Now().Add(-10 * time.Minute)\n\tdatanodeFailures[\"bar:6000\"] = time.Now()\n\n\tassert.EqualValues(t, df.next(), \"foo:6000\")\n}\n\nfunc TestPicksFirstDatanode(t *testing.T) ", "output": "{\n\tdf := newDatanodeFailover([]string{\"foo:6000\", \"bar:6000\"})\n\tassert.EqualValues(t, df.next(), \"foo:6000\")\n}"} {"input": "package lessons\n\n\n\n\nimport(\n\t\"fmt\"\n\t\"flag\"\n)\n\n\n\nfunc CommandLineFlags() ", "output": "{\n\twordPtr := flag.String(\"word\", \"foo\", \"a string\")\n\tnumbPtr := flag.Int(\"numb\", 42, \"an int\")\n\tboolPtr := flag.Bool(\"fork\", false, \"a bool\")\n\tvar svar string\n\tflag.StringVar(&svar, \"svar\", \"bar\", \"a string value\")\n\tflag.Parse()\n\tfmt.Println(\"word:\", *wordPtr)\n\tfmt.Println(\"numb:\", *numbPtr)\n\tfmt.Println(\"fork:\", *boolPtr)\n\tfmt.Println(\"svar:\", svar)\n\tfmt.Println(\"tail:\", flag.Args())\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc Max(arr []int) int {\n\tvar m int\n\tfor _, el := range arr {\n\t\tif el > m {\n\t\t\tm = el\n\t\t}\n\t}\n\treturn m\n}\n\n\n\nfunc main() {\n\tvar arr []int\n\tarr = []int{3, 10, 2, 1, 20}\n\tfmt.Println(LIS(arr, len(arr)))\n\n\tarr = []int{10, 22, 9, 33, 21, 50, 41, 60}\n\tfmt.Println(LIS(arr, len(arr)))\n}\n\nfunc LIS(arr []int, n int) int ", "output": "{\n\tDP := make([]int, n)\n\tfor i := 0; i < n; i++ {\n\t\tDP[i] = 1\n\t}\n\n\tfor i := 0; i < n; i++ {\n\t\tm := arr[i]\n\t\tfor j := i + 1; j < n; j++ {\n\t\t\tif m < arr[j] {\n\t\t\t\tm = arr[j]\n\t\t\t\tDP[i] = 1 + DP[i]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn Max(DP)\n}"} {"input": "package flog\n\nimport \"github.com/Sirupsen/logrus\"\n\ntype Parameter interface {\n\tConvert() map[string]interface{}\n}\n\ntype Fields struct {\n\tEvent string\n\tError error\n}\n\nfunc (f Fields) Convert() map[string]interface{} {\n\tfields := map[string]interface{}{}\n\n\tif f.Event != \"\" {\n\t\tfields[\"event\"] = f.Event\n\t}\n\n\tif f.Error != nil {\n\t\tfields[\"error\"] = f.Error\n\t}\n\n\treturn fields\n}\n\ntype Details map[string]interface{}\n\nfunc (d Details) Convert() map[string]interface{} {\n\treturn d\n}\n\ntype DebugFields map[string]interface{}\n\nfunc (d DebugFields) Convert() map[string]interface{} {\n\treturn map[string]interface{}{}\n}\n\nfunc transform(params []Parameter) logrus.Fields {\n\tlogrusFields := logrus.Fields{}\n\n\tfor _, p := range params {\n\t\tfieldMap := p.Convert()\n\n\t\tfor k, v := range fieldMap {\n\t\t\tlogrusFields[k] = v\n\t\t}\n\t}\n\n\treturn logrusFields\n}\n\nfunc Debug(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Debug(msg)\n}\n\nfunc Info(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Info(msg)\n}\n\n\n\nfunc Error(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Error(msg)\n}\n\nfunc Fatal(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Fatal(msg)\n}\n\nfunc Panic(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Panic(msg)\n}\n\nfunc Warn(msg string, params ...Parameter) ", "output": "{\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Warning(msg)\n}"} {"input": "package userinfo\n\nimport (\n\t\"os\"\n)\n\n\n\nfunc GetUserHome() (home string) {\n\thome = os.Getenv(\"HOME\")\n\treturn\n}\n\nfunc GetUserLogin() (login string) ", "output": "{\n\tlogin = os.Getenv(\"USER\")\n\treturn\n}"} {"input": "package sendgrid\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"errors\"\n\t\"github.com/hashicorp/terraform/helper/schema\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\n\n\nfunc providerConfigure(d *schema.ResourceData) (interface{}, error) {\n\n\tconfig := Config{\n\t\tAPIKey: d.Get(\"api_key\").(string),\n\t}\n\n\tlog.Println(\"[INFO] Initializing Sendgrid client\")\n\tclient := config.Client()\n\tfmt.Println(\"Validate template\")\n\tok, err := client.Validate()\n\n\tif err != nil {\n\t\treturn client, err\n\t}\n\n\tif ok == false {\n\t\treturn client, errors.New(`No valid credential sources found for Sendgrid Provider. Please see https://terraform.io/docs/providers/sendgrid/index.html for more information on providing credentials for the Sendgrid Provider`)\n\t}\n\n\treturn client, nil\n}\n\nfunc Provider() terraform.ResourceProvider ", "output": "{\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"api_key\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"SENDGRID_API_KEY\", nil),\n\t\t\t},\n\t\t},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"sendgrid_template\": resourceSendgridTemplate(),\n\t\t\t\"sendgrid_template_version\": resourceSendgridTemplateVersion(),\n\t\t},\n\n\t\tConfigureFunc: providerConfigure,\n\t}\n}"} {"input": "package cli\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/antham/goller/v2/dsl\"\n\t\"github.com/antham/goller/v2/sorter\"\n\t\"gopkg.in/alecthomas/kingpin.v2\"\n)\n\nvar sortersGlobal *sorter.Sorters\n\n\ntype Sorters struct {\n\tsorters *sorter.Sorters\n}\n\n\nfunc (s *Sorters) Init() {\n\tsortersGlobal = sorter.NewSorters()\n}\n\n\n\n\n\nfunc (s *Sorters) ValidatePositions(positions *[]int) error {\n\tif s.sorters == nil {\n\t\treturn nil\n\t}\n\n\tfor _, sorter := range *s.sorters {\n\t\tpositionMatch := false\n\n\t\tfor _, position := range *positions {\n\t\t\tif sorter.HasPosition(position) {\n\t\t\t\tpositionMatch = true\n\t\t\t}\n\t\t}\n\n\t\tif !positionMatch {\n\t\t\treturn fmt.Errorf(\"Sort is wrong : position %d doesn't exist\", sorter.GetPosition())\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\nfunc (s *Sorters) Get() *sorter.Sorters {\n\treturn s.sorters\n}\n\n\nfunc (s *Sorters) String() string {\n\treturn \"\"\n}\n\n\nfunc SortersWrapper(s kingpin.Settings) (target *Sorters) {\n\ttarget = &Sorters{}\n\ttarget.Init()\n\ts.SetValue(target)\n\treturn\n}\n\nfunc (s *Sorters) Set(value string) error ", "output": "{\n\tparser := dsl.NewParser(bytes.NewBufferString(value))\n\n\tstmts, err := parser.ParsePositionsAndFunctions()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t(*s).sorters = sortersGlobal\n\n\tfor _, stmt := range *stmts {\n\t\t(*s).sorters.Append(stmt.Position, stmt.Functions[0].Name, stmt.Functions[0].Args)\n\t}\n\n\treturn nil\n}"} {"input": "package endpoint\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/spolu/settle/lib/db\"\n\t\"github.com/spolu/settle/lib/errors\"\n\t\"github.com/spolu/settle/lib/format\"\n\t\"github.com/spolu/settle/lib/ptr\"\n\t\"github.com/spolu/settle/lib/svc\"\n\t\"github.com/spolu/settle/mint\"\n\t\"github.com/spolu/settle/mint/lib/authentication\"\n\t\"github.com/spolu/settle/mint/model\"\n)\n\nconst (\n\tEndPtListAssets EndPtName = \"ListAssets\"\n)\n\nfunc init() {\n\tregistrar[EndPtListAssets] = NewListAssets\n}\n\n\ntype ListAssets struct {\n\tListEndpoint\n\tOwner string\n}\n\n\nfunc NewListAssets(\n\tr *http.Request,\n) (Endpoint, error) {\n\treturn &ListAssets{\n\t\tListEndpoint: ListEndpoint{},\n\t}, nil\n}\n\n\nfunc (e *ListAssets) Validate(\n\tr *http.Request,\n) error {\n\tctx := r.Context()\n\n\te.Owner = fmt.Sprintf(\"%s@%s\",\n\t\tauthentication.Get(ctx).User.Username, mint.GetHost(ctx))\n\n\treturn e.ListEndpoint.Validate(r)\n}\n\n\n\n\nfunc (e *ListAssets) Execute(\n\tctx context.Context,\n) (*int, *svc.Resp, error) ", "output": "{\n\tctx = db.Begin(ctx, \"mint\")\n\tdefer db.LoggedRollback(ctx)\n\n\tassets, err := model.LoadAssetListByOwner(ctx,\n\t\te.ListEndpoint.CreatedBefore,\n\t\te.ListEndpoint.Limit,\n\t\te.Owner,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, errors.Trace(err) \n\t}\n\n\tdb.Commit(ctx)\n\n\tl := []mint.AssetResource{}\n\tfor _, a := range assets {\n\t\ta := a\n\t\tl = append(l, model.NewAssetResource(ctx, &a))\n\t}\n\n\treturn ptr.Int(http.StatusOK), &svc.Resp{\n\t\t\"assets\": format.JSONPtr(l),\n\t}, nil\n}"} {"input": "package main\n\nimport \"github.com/augustoroman/serial_lcd\"\n\ntype FakeLcd struct{}\n\nfunc (f FakeLcd) SetBG(r, g, b uint8) error { return nil }\nfunc (f FakeLcd) SetOn(On bool) error { return nil }\nfunc (f FakeLcd) SetBrightness(b uint8) error { return nil }\nfunc (f FakeLcd) SetContrast(c uint8) error { return nil }\nfunc (f FakeLcd) SetAutoscroll(On bool) error { return nil }\nfunc (f FakeLcd) SetSize(cols, rows uint8) error { return nil }\nfunc (f FakeLcd) Clear() error { return nil }\nfunc (f FakeLcd) Home() error { return nil }\nfunc (f FakeLcd) MoveTo(col, row uint8) error { return nil }\nfunc (f FakeLcd) MoveForward() error { return nil }\n\nfunc (f FakeLcd) Write(b []byte) (int, error) { return len(b), nil }\n\nfunc (f FakeLcd) CreateCustomChar(spot uint8, c serial_lcd.Char) error { return nil }\n\nfunc (f FakeLcd) MoveBack() error ", "output": "{ return nil }"} {"input": "package sqlbuilder\n\ntype Dialect interface {\n\tEscapeCharacter() rune\n\tInsertReturningClause() string\n\tKind() string\n\tName() *string\n}\n\ntype genericDialect struct {\n\tescapeChar rune\n\treturningClause string\n\tkind string\n\tname *string\n}\n\nfunc (db *genericDialect) EscapeCharacter() rune {\n\treturn db.escapeChar\n}\n\nfunc (db *genericDialect) InsertReturningClause() string {\n\treturn db.returningClause\n}\n\nfunc (db *genericDialect) Kind() string {\n\treturn db.kind\n}\n\n\n\nfunc NewMySQLDialect(dbName *string) Dialect {\n\treturn &genericDialect{\n\t\tescapeChar: '`',\n\t\tkind: \"mysql\",\n\t\tname: dbName,\n\t}\n}\n\nfunc NewPostgresDialect(dbName *string) Dialect {\n\treturn &genericDialect{\n\t\tescapeChar: '\"',\n\t\treturningClause: \" RETURNING *\",\n\t\tkind: \"postgres\",\n\t\tname: dbName,\n\t}\n}\n\nfunc NewSQLiteDialect() Dialect {\n\tdefaultName := \"main\"\n\treturn &genericDialect{\n\t\tescapeChar: '\"',\n\t\tkind: \"sqlite\",\n\t\tname: &defaultName,\n\t}\n}\n\nfunc (db *genericDialect) Name() *string ", "output": "{\n\treturn db.name\n}"} {"input": "package hostqueue\n\nimport (\n\t\"html/template\"\n\t\"net/http\"\n\t\"regexp\"\n\n\t\"appengine\"\n\n\t\"github.com/gorilla/mux\"\n)\n\ntype Status struct {\n\tName string `json:\"name\"`\n\tHosts []Host `json:\"hosts\"`\n\tNext int `json:\"next\"`\n}\n\n\nfunc DisplayGroupStatus(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tpathVars := mux.Vars(r)\n\n\tuuid := pathVars[\"uuid\"]\n\tctx.Infof(\"UUID: %s\", uuid)\n\n\tif isValidUUID((uuid)) {\n\t\tgroup, err := GetGroupByUUID(ctx, uuid)\n\t\tctx.Infof(\"group: %v\", group)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tstatus := convertToStatus(group)\n\t\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\n\t\tvar tpl = template.Must(template.ParseGlob(\"templates/*.html\"))\n\t\tif err := tpl.ExecuteTemplate(w, \"status.html\", status); err != nil {\n\t\t\tctx.Infof(\"%v\", err)\n\t\t}\n\n\t} else {\n\t\tw.Write([]byte(\"Invalid group\"))\n\t}\n}\n\nfunc convertToStatus(group Group) Status {\n\treturn Status{\n\t\tName: group.GroupName,\n\t\tNext: group.Next,\n\t\tHosts: group.Hosts,\n\t\t}\n}\n\n\n\nfunc isValidUUID(text string) bool ", "output": "{\n\tr := regexp.MustCompile(\"^[a-z0-9]{8}-[a-z0-9]{4}-[1-5][a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{12}$\")\n\treturn r.MatchString(text)\n}"} {"input": "package arbitrage\n\nimport \"time\"\n\ntype Info struct {\n\tVersion int `yaml:\"version\"`\n\tFileHash string `yaml:\"file_hash\"`\n\tLastUpdated time.Time `yaml:\"last_updated\"`\n\tReleases map[string]InfoRelease `yaml:\"releases,omitempty\"`\n}\n\ntype InfoRelease struct {\n\tTorrentId int `yaml:\"torrent_id\"`\n\tFormat string `yaml:\"format\"`\n\tFilePath string `yaml:\"file_path\"`\n\n\tName string `yaml:\"name\"`\n\tYear int `yaml:\"year\"`\n\tRecordLabel string `yaml:\"record_label\"`\n\tCatalogueNumber string `yaml:\"catalogue_number\"`\n\tEdition string `yaml:\"edition\"`\n\n\tComposers []string `yaml:\"composers,omitempty,flow\"`\n\tArtists []string `yaml:\"artists\"`\n\tWith []string `yaml:\"with,omitempty,flow\"`\n\tDJ []string `yaml:\"dj,omitempty,flow\"`\n\tRemixedBy []string `yaml:\"remixed_by,omitempty,flow\"`\n\tProducer []string `yaml:\"producer,omitempty,flow\"`\n\n\tTags []string `yaml:\"tags,flow\"`\n\tDescription string `yaml:\"description,omitempty\"`\n\tImage string `yaml:\"image,omitempty\"`\n}\n\nfunc concat(s, del, extra, pre, suf string) string {\n\tif extra == \"\" {\n\t\treturn s\n\t}\n\tif s != \"\" {\n\t\ts += del\n\t}\n\treturn s + pre + extra + suf\n}\n\n\n\nfunc (i InfoRelease) String() string ", "output": "{\n\tstr := \"\"\n\tif len(i.Artists) == 1 {\n\t\tstr = i.Artists[0]\n\t} else if len(i.Artists) > 1 {\n\t\tstr = \"Various Artists\"\n\t} else {\n\t\tstr = \"Unknown Artist\"\n\t}\n\n\tstr = concat(str, \" - \", i.Name, \"\", \"\")\n\tstr = concat(str, \" \", i.Format, \"[\", \"]\")\n\tstr = concat(str, \" \", i.CatalogueNumber, \"{\", \"}\")\n\treturn str\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/WindomZ/go-jwt/jwt\"\n\t\"os\"\n)\n\nconst (\n\tKeyNameHmac string = \"hmac_demo\" \n\tKeyNameRSA = \"rsa_demo\" \n)\n\nfunc main() {\n\tif dir, err := os.Getwd(); err != nil {\n\t\tpanic(err)\n\t} else if err := jwt.NewConfig(dir).Effect(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := demoHmac(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := demoRSA(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(\"Success!\")\n}\n\n\n\nfunc verify(token string) (err error) {\n\t_, err = jwt.Parse(token)\n\treturn\n}\n\nvar test_case = map[string]interface{}{\n\t\"number\": 19,\n\t\"english\": \"This is the English test.\",\n\t\"中文\": \"这是个中文测试。\",\n}\n\nfunc demoHmac() error {\n\tif token, err := sign(KeyNameHmac, test_case); err != nil {\n\t\treturn err\n\t} else if err := verify(token); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc demoRSA() error {\n\tif token, err := sign(KeyNameRSA, test_case); err != nil {\n\t\treturn err\n\t} else if err := verify(token); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc sign(keyName string, m interface{}) (token string, err error) ", "output": "{\n\treturn jwt.Sign(keyName, m, 72)\n}"} {"input": "package main\n\nimport (\n\t\"math\"\n\t\"sort\"\n)\n\ntype NaiveSieve struct {\n\tsieve map[int]bool\n}\n\nfunc NewNaiveSieve(limit int) NaiveSieve {\n\n\tprimes := make(map[int]bool)\n\n\tprimes[2] = true\n\n\tfor n := 3; n < limit; n += 2 {\n\t\tif IsNaivePrime(n) {\n\t\t\tprimes[n] = true\n\t\t}\n\t}\n\n\treturn NaiveSieve{primes}\n}\n\nfunc (self *NaiveSieve) Contains(n int) bool {\n\t_, ok := self.sieve[n]\n\treturn ok\n}\n\nfunc (self *NaiveSieve) Primes() []int {\n\tprimes := make([]int, 0, len(self.sieve))\n\tfor n, _ := range self.sieve {\n\t\tprimes = append(primes, n)\n\t}\n\tsort.Ints(primes)\n\treturn primes\n}\n\n\n\nfunc IsNaivePrime(n int) bool ", "output": "{\n\tswitch {\n\tcase n == 1:\n\t\treturn false\n\tcase n == 2:\n\t\treturn true\n\tcase n%2 == 0:\n\t\treturn false\n\t}\n\n\tlimit := int(math.Sqrt(float64(n)))\n\n\tfor i := 3; i <= limit; i += 2 {\n\t\tif n%i == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}"} {"input": "package command\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype VersionCommand struct {\n\tMeta\n\n\tName string\n\tVersion string\n\tRevision string\n}\n\nfunc (c *VersionCommand) Run(args []string) int {\n\tvar versionString bytes.Buffer\n\n\tfmt.Fprintf(&versionString, \"%s v%s\", c.Name, c.Version)\n\tif c.Revision != \"\" {\n\t\tfmt.Fprintf(&versionString, \" (%s)\", c.Revision)\n\t}\n\n\tc.Ui.Output(versionString.String())\n\treturn 0\n}\n\n\n\nfunc (c *VersionCommand) Help() string {\n\treturn \"\"\n}\n\nfunc (c *VersionCommand) Synopsis() string ", "output": "{\n\treturn fmt.Sprintf(\"Print %s version and quit\", c.Name)\n}"} {"input": "package engine\n\nimport \"testing\"\n\n\n\nfunc TestBackendLobbyMuxDeleteLobby(t *testing.T) {\n\tmux := NewBackendLobbyMux()\n\tl := &backendLobby{queue: make(chan interface{})}\n\tmux.AddLobby(\"/foo\", l)\n\tif ok := mux.DeleteLobby(\"/foo\"); !ok {\n\t\tt.Errorf(\"Expected to delete lobby\")\n\t}\n\tif l.IsAlive() {\n\t\tt.Errorf(\"Lobby should be killed when deleting from the mux\")\n\t}\n\tif _, ok := mux.m[\"/foo\"]; ok {\n\t\tt.Errorf(\"Expected to delete lobby\")\n\t}\n\tif ok := mux.DeleteLobby(\"/bar\"); ok {\n\t\tt.Errorf(\"Expected to not delete non existing lobby\")\n\t}\n}\n\nfunc TestBackendLobbyMuxMatch(t *testing.T) {\n\tmux := NewBackendLobbyMux()\n\tmux.AddLobby(\"/foo\", &backendLobby{})\n\tif lobby := mux.Match(\"/foo\"); lobby == nil {\n\t\tt.Errorf(\"Expected to match existing lobby\")\n\t}\n\tif lobby := mux.Match(\"/bar\"); lobby != nil {\n\t\tt.Errorf(\"Expected to not match non existing lobby\")\n\t}\n}\n\nfunc TestBackendLobbyMuxAddLobby(t *testing.T) ", "output": "{\n\tmux := NewBackendLobbyMux()\n\tmux.AddLobby(\"/foo\", &backendLobby{})\n\tif _, ok := mux.m[\"/foo\"]; !ok {\n\t\tt.Errorf(\"Expected to add lobby\")\n\t}\n}"} {"input": "package pdf417\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\n\t\"github.com/boombuler/barcode\"\n\t\"github.com/boombuler/barcode/utils\"\n)\n\ntype pdfBarcode struct {\n\tdata string\n\twidth int\n\tcode *utils.BitList\n}\n\nfunc (c *pdfBarcode) Metadata() barcode.Metadata {\n\treturn barcode.Metadata{barcode.TypePDF, 2}\n}\n\nfunc (c *pdfBarcode) Content() string {\n\treturn c.data\n}\n\nfunc (c *pdfBarcode) ColorModel() color.Model {\n\treturn color.Gray16Model\n}\n\n\n\nfunc (c *pdfBarcode) At(x, y int) color.Color {\n\tif c.code.GetBit((y/moduleHeight)*c.width + x) {\n\t\treturn color.Black\n\t}\n\treturn color.White\n}\n\nfunc (c *pdfBarcode) Bounds() image.Rectangle ", "output": "{\n\theight := c.code.Len() / c.width\n\n\treturn image.Rect(0, 0, c.width, height*moduleHeight)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n\t\"runtime\"\n\n\t\"github.com/fatih/color\"\n\t\"github.com/ssddanbrown/haste/engine\"\n\t\"github.com/ssddanbrown/haste/options\"\n\t\"github.com/ssddanbrown/haste/server\"\n)\n\nfunc main() {\n\n\topts := options.NewOptions()\n\terr := opts.ParseCommandFlags()\n\topts.LoadFileResolver()\n\tcheck(err)\n\n\tmanager := engine.NewManager(opts)\n\n\tmanager.BuildAll()\n\n\tif opts.Watch {\n\t\tstartWatcher(manager, opts)\n\t}\n\n}\n\n\n\nfunc openWebPage(url string) error {\n\tvar err error\n\n\tswitch runtime.GOOS {\n\tcase \"linux\":\n\t\tfmt.Println(url)\n\t\terr = exec.Command(\"xdg-open\", url).Run()\n\tcase \"windows\", \"darwin\":\n\t\terr = exec.Command(\"rundll32\", \"url.dll,FileProtocolHandler\", url).Run()\n\tdefault:\n\t\terr = fmt.Errorf(\"unsupported platform\")\n\t}\n\treturn err\n}\n\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc startWatcher(m *engine.Manager, opts *options.Options) ", "output": "{\n\tser := server.NewServer(m, opts)\n\tser.AddWatchedFolder(opts.RootPath)\n\n\tcolor.Green(fmt.Sprintf(\"Server started at http://localhost:%d\", opts.ServerPort))\n\n\terr := ser.Listen()\n\tcheck(err)\n}"} {"input": "package mocks\n\nimport (\n\tcli \"github.com/stackanetes/kubernetes-entrypoint/client\"\n\tv1batch \"k8s.io/client-go/1.5/kubernetes/typed/batch/v1\"\n\tv1core \"k8s.io/client-go/1.5/kubernetes/typed/core/v1\"\n\tv1beta1extensions \"k8s.io/client-go/1.5/kubernetes/typed/extensions/v1beta1\"\n)\n\ntype Client struct {\n\tv1core.PodInterface\n\tv1core.ServiceInterface\n\tv1beta1extensions.DaemonSetInterface\n\tv1core.EndpointsInterface\n\tv1batch.JobInterface\n}\n\nfunc (c Client) Pods(namespace string) v1core.PodInterface {\n\treturn c.PodInterface\n}\n\nfunc (c Client) Services(namespace string) v1core.ServiceInterface {\n\treturn c.ServiceInterface\n}\n\nfunc (c Client) DaemonSets(namespace string) v1beta1extensions.DaemonSetInterface {\n\treturn c.DaemonSetInterface\n}\n\n\nfunc (c Client) Jobs(namespace string) v1batch.JobInterface {\n\treturn c.JobInterface\n}\n\nfunc NewClient() cli.ClientInterface {\n\treturn Client{\n\t\tNewPClient(),\n\t\tNewSClient(),\n\t\tNewDSClient(),\n\t\tNewEClient(),\n\t\tNewJClient(),\n\t}\n}\n\nfunc (c Client) Endpoints(namespace string) v1core.EndpointsInterface ", "output": "{\n\treturn c.EndpointsInterface\n}"} {"input": "package p\n\ntype intAlias = int\n\n\n\nfunc f() ", "output": "{\n\tswitch interface{}(nil) {\n\tcase uint8(0):\n\tcase byte(0): \n\tcase int32(0):\n\tcase rune(0): \n\tcase int(0):\n\tcase intAlias(0): \n\t}\n}"} {"input": "package path_finding\n\n\n\n\nfunc Comparison(array []int, t int) bool ", "output": "{\nreturn true\n}"} {"input": "package memo\n\nimport (\n\t\"encoding/binary\"\n\t\"reflect\"\n\n\t. \"github.com/pingcap/check\"\n\t\"github.com/pingcap/tidb/expression\"\n\tplannercore \"github.com/pingcap/tidb/planner/core\"\n)\n\n\n\nfunc (s *testMemoSuite) TestGroupExprFingerprint(c *C) {\n\tp := &plannercore.LogicalLimit{Count: 3}\n\texpr := NewGroupExpr(p)\n\tchildGroup := NewGroupWithSchema(nil, expression.NewSchema())\n\texpr.SetChildren(childGroup)\n\tplanHash := p.HashCode()\n\tbuffer := make([]byte, 10+len(planHash))\n\tbinary.BigEndian.PutUint16(buffer, 1)\n\tbinary.BigEndian.PutUint64(buffer[2:], uint64(reflect.ValueOf(childGroup).Pointer()))\n\tcopy(buffer[10:], planHash)\n\tc.Assert(expr.FingerPrint(), Equals, string(buffer))\n}\n\nfunc (s *testMemoSuite) TestNewGroupExpr(c *C) ", "output": "{\n\tp := &plannercore.LogicalLimit{}\n\texpr := NewGroupExpr(p)\n\tc.Assert(expr.ExprNode, Equals, p)\n\tc.Assert(expr.Children, IsNil)\n\tc.Assert(expr.Explored, IsFalse)\n}"} {"input": "package s2\n\n\nvar (\n\t_ Shape = (*PointVector)(nil)\n)\n\n\n\n\n\n\n\n\ntype PointVector []Point\n\nfunc (p *PointVector) NumEdges() int { return len(*p) }\n\nfunc (p *PointVector) ReferencePoint() ReferencePoint { return OriginReferencePoint(false) }\nfunc (p *PointVector) NumChains() int { return len(*p) }\nfunc (p *PointVector) Chain(i int) Chain { return Chain{i, 1} }\nfunc (p *PointVector) ChainEdge(i, j int) Edge { return Edge{(*p)[i], (*p)[j]} }\nfunc (p *PointVector) ChainPosition(e int) ChainPosition { return ChainPosition{e, 0} }\nfunc (p *PointVector) Dimension() int { return 0 }\nfunc (p *PointVector) IsEmpty() bool { return defaultShapeIsEmpty(p) }\nfunc (p *PointVector) IsFull() bool { return defaultShapeIsFull(p) }\nfunc (p *PointVector) typeTag() typeTag { return typeTagPointVector }\nfunc (p *PointVector) privateInterface() {}\n\nfunc (p *PointVector) Edge(i int) Edge ", "output": "{ return Edge{(*p)[i], (*p)[i]} }"} {"input": "package authmethod\n\nimport (\n\t\"sync\"\n\n\t\"github.com/hashicorp/consul/agent/structs\"\n)\n\ntype syncCache struct {\n\tlock sync.RWMutex\n\tcache authMethodCache\n}\n\nfunc NewCache() Cache {\n\tc := &syncCache{}\n\tc.cache.init()\n\treturn c\n}\n\nfunc (c *syncCache) GetValidator(method *structs.ACLAuthMethod) (uint64, Validator, bool) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\treturn c.cache.GetValidator(method)\n}\n\n\n\nfunc (c *syncCache) Purge() {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tc.cache.Purge()\n}\n\nfunc (c *syncCache) PutValidatorIfNewer(method *structs.ACLAuthMethod, validator Validator, idx uint64) Validator ", "output": "{\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\treturn c.cache.PutValidatorIfNewer(method, validator, idx)\n}"} {"input": "package testing\n\nimport (\n\tnodev1 \"k8s.io/api/node/v1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\tclientset \"k8s.io/client-go/kubernetes\"\n\t\"k8s.io/client-go/kubernetes/fake\"\n\t\"k8s.io/kubernetes/pkg/kubelet/runtimeclass\"\n)\n\nconst (\n\tSandboxRuntimeClass = \"sandbox\"\n\tSandboxRuntimeHandler = \"kata-containers\"\n\n\tEmptyRuntimeClass = \"native\"\n)\n\n\n\n\n\n\n\n\nfunc StartManagerSync(m *runtimeclass.Manager) func() {\n\tstopCh := make(chan struct{})\n\tm.Start(stopCh)\n\tm.WaitForCacheSync(stopCh)\n\treturn func() {\n\t\tclose(stopCh)\n\t}\n}\n\n\n\nfunc NewRuntimeClass(name, handler string) *nodev1.RuntimeClass {\n\treturn &nodev1.RuntimeClass{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t},\n\t\tHandler: handler,\n\t}\n}\n\nfunc NewPopulatedClient() clientset.Interface ", "output": "{\n\treturn fake.NewSimpleClientset(\n\t\tNewRuntimeClass(EmptyRuntimeClass, \"\"),\n\t\tNewRuntimeClass(SandboxRuntimeClass, SandboxRuntimeHandler),\n\t)\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"runtime\"\n\t\"sync\"\n\t\"syscall\"\n)\n\n\nvar (\n\tquit chan struct{}\n\trelaunch bool\n)\n\n\n\n\nfunc main() {\n\tquit = make(chan struct{})\n\tcmdLineConfig := parseCmdLineConfig()\n\tif cmdLineConfig.PrintVer {\n\t\tprintVersion()\n\t\tos.Exit(0)\n\t}\n\n\tparseConfig(cmdLineConfig.RcFile, cmdLineConfig)\n\n\tinitSelfListenAddr()\n\tinitLog()\n\tinitAuth()\n\tinitSiteStat()\n\tinitPAC() \n\n\tinitStat()\n\n\tinitParentPool()\n\n\n\tif config.Core > 0 {\n\t\truntime.GOMAXPROCS(config.Core)\n\t}\n\n\tgo sigHandler()\n\tgo runSSH()\n\tif config.EstimateTimeout {\n\t\tgo runEstimateTimeout()\n\t} else {\n\t\tinfo.Println(\"timeout estimation disabled\")\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(listenProxy))\n\tfor _, proxy := range listenProxy {\n\t\tgo proxy.Serve(&wg, quit)\n\t}\n\n\twg.Wait()\n\n\tif relaunch {\n\t\tinfo.Println(\"Relunching cow...\")\n\t\targv0, err := lookPath()\n\t\tif nil != err {\n\t\t\terrl.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\terr = syscall.Exec(argv0, os.Args, os.Environ())\n\t\tif err != nil {\n\t\t\terrl.Println(err)\n\t\t}\n\t}\n\tdebug.Println(\"the main process is , exiting...\")\n}\n\nfunc lookPath() (argv0 string, err error) ", "output": "{\n\targv0, err = exec.LookPath(os.Args[0])\n\tif nil != err {\n\t\treturn\n\t}\n\tif _, err = os.Stat(argv0); nil != err {\n\t\treturn\n\t}\n\treturn\n}"} {"input": "package rpc\n\nimport (\n\t\"context\"\n\t\"net\"\n\n\t\"github.com/ethereum/go-ethereum/log\"\n\t\"github.com/ethereum/go-ethereum/p2p/netutil\"\n)\n\n\nfunc (s *Server) ServeListener(l net.Listener) error {\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif netutil.IsTemporaryError(err) {\n\t\t\tlog.Warn(\"RPC accept error\", \"err\", err)\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Trace(\"Accepted RPC connection\", \"conn\", conn.RemoteAddr())\n\t\tgo s.ServeCodec(NewCodec(conn), 0)\n\t}\n}\n\n\n\n\n\n\n\n\n\nfunc DialIPC(ctx context.Context, endpoint string) (*Client, error) ", "output": "{\n\treturn newClient(ctx, func(ctx context.Context) (ServerCodec, error) {\n\t\tconn, err := newIPCConnection(ctx, endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn NewCodec(conn), err\n\t})\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n)\n\n\n\nfunc main() {\n var number int\n fmt.Scan(&number)\n dearrangements := count(number)\n fmt.Print(\"The number of dearrangements is \", dearrangements)\n}\n\nfunc count(number int) int", "output": "{\n if (number <= 2) {\n return (number + 1) % 2\n }\n last := count(number - 1)\n secondLast := count(number - 2)\n return (number - 1) * (last + secondLast)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\ntype myStruct struct {\n\tintField int\n}\n\nfunc (ms myStruct) addByValue(x int) {\n\tms.intField += x\n\tfmt.Println(\"ByValue internal value \", ms.intField)\n}\n\n\n\nfunc main() {\n\tmyVar := myStruct{1}\n\tmyPtr := &myStruct{2}\n\n\tmyVar.addByValue(3)\n\tfmt.Println(\"main func myVar value \", myVar)\n\tmyVar.addByReference(3)\n\tfmt.Println(\"main func myVar value \", myVar)\n\tfmt.Println(\"\\n\")\n\n\tmyPtr.addByValue(3)\n\tfmt.Println(\"main func myPtr value \", myPtr)\n\tmyPtr.addByReference(3)\n\tfmt.Println(\"main func myPtr value \", myPtr)\n\n}\n\nfunc (ms *myStruct) addByReference(x int) ", "output": "{\n\tms.intField += x\n\tfmt.Println(\"ByReference internal value \", ms.intField)\n}"} {"input": "package model\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/mholt/binding\"\n)\n\n\ntype Assignment struct {\n\tID string `gorethink:\"id,omitempty\" json:\"id\"`\n\tName string `gorethink:\"name,omitempty\" json:\"name\"`\n\tClassID string `gorethink:\"classId,omitempty\" json:\"classId\"`\n\tTermID string `gorethink:\"termId,omitempty\" json:\"termId\"`\n\tGroupID string `gorethink:\"groupId,omitempty\" json:\"groupId\"`\n\tMaxScore int16 `gorethink:\"maxScore,omitempty\" json:\"maxScore\"`\n\tDueDate time.Time `gorethink:\"dueDate,omitempty\" json:\"dueDate\"`\n\tTimeStamp\n}\n\n\n\n\ntype AssignmentAPIRes struct {\n\tAssignment\n\tGroup AssignmentGroup `gorethink:\"group,omitempty\" json:\"group\"`\n}\n\nfunc (a Assignment) Validate(req *http.Request, errs binding.Errors) binding.Errors {\n\tif a.Name == \"\" {\n\t\terrs = append(errs, RequiredErr(\"name\"))\n\t}\n\tif a.ClassID == \"\" {\n\t\terrs = append(errs, RequiredErr(\"classId\"))\n\t}\n\tif a.TermID == \"\" {\n\t\terrs = append(errs, RequiredErr(\"termId\"))\n\t}\n\tif a.GroupID == \"\" {\n\t\terrs = append(errs, RequiredErr(\"groupId\"))\n\t}\n\tif a.MaxScore <= 0 {\n\t\terrs = append(errs, RequiredErr(\"maxScore\"))\n\t}\n\treturn errs\n}\n\nfunc (a *Assignment) FieldMap(req *http.Request) binding.FieldMap ", "output": "{\n\treturn binding.FieldMap{\n\t\t&a.ID: \"id\",\n\t\t&a.Name: \"name\",\n\t\t&a.GroupID: \"groupId\",\n\t\t&a.ClassID: \"classId\",\n\t\t&a.MaxScore: \"maxScore\",\n\t\t&a.TermID: \"termId\",\n\t\t&a.DueDate: \"dueDate\",\n\t}\n}"} {"input": "package calendar\n\nimport (\n\t\"time\"\n)\n\nvar (\n\tentries = make(map[int]Entry)\n\tindex int\n)\n\ntype Entry struct {\n\tID int\n\tTitle string\n\tStarts time.Time\n\tFinishes time.Time\n}\n\n\n\nfunc Lookup(id int) (Entry, bool) {\n\te, isPresent := entries[id]\n\treturn e, isPresent\n}\n\nfunc Add(e Entry) Entry {\n\tindex++\n\te.ID = index\n\tUpdate(e)\n\treturn e\n}\n\nfunc Update(e Entry) {\n\tentries[e.ID] = e\n}\n\nfunc Remove(id int) {\n\tdelete(entries, id)\n}\n\nfunc Count() int {\n\treturn len(entries)\n}\n\nfunc All() []Entry {\n\tall := []Entry{}\n\tfor _, e := range entries {\n\t\tall = append(all, e)\n\t}\n\treturn all\n}\n\nfunc (e Entry) Duration() time.Duration ", "output": "{\n\treturn e.Finishes.Sub(e.Starts)\n}"} {"input": "package revocations\n\nimport (\n\t\"github.com/leanovate/microzon-auth-go/common\"\n\t\"github.com/leanovate/microzon-auth-go/logging\"\n\t\"github.com/leanovate/microzon-auth-go/store\"\n\t\"sync\"\n)\n\ntype RevocationsValidator struct {\n\tObserve *ObserverGroup\n\tlock sync.RWMutex\n\tlogger logging.Logger\n\trevocationHashes *hashWheel\n\texpirationTimeWheel *timeWheel\n\tagentStore store.AgentStore\n}\n\nfunc NewRevocationsValidator(store store.AgentStore, parent logging.Logger) *RevocationsValidator {\n\treturn &RevocationsValidator{\n\t\tObserve: NewObserverGroup(0, parent),\n\t\tlogger: parent.WithContext(map[string]interface{}{\"package\": \"revokations\"}),\n\t\trevocationHashes: newHashWheel(17),\n\t\texpirationTimeWheel: newTimeWheel(600),\n\t\tagentStore: store,\n\t}\n}\n\n\n\n\n\nfunc (r *RevocationsValidator) IsRevoked(sha256 common.RawSha256) bool ", "output": "{\n\tr.lock.RLock()\n\tdefer r.lock.RUnlock()\n\n\treturn r.revocationHashes.containsHash(sha256)\n}"} {"input": "package response\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\nvar realm = \"example_api\"\n\n\nfunc WriteJSON(w http.ResponseWriter, v interface{}, code int) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(code)\n\tjson.NewEncoder(w).Encode(v)\n}\n\n\n\n\n\n\nfunc Error(w http.ResponseWriter, err string, code int) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(code)\n\tjson.NewEncoder(w).Encode(map[string]string{\"error\": err})\n}\n\n\n\nfunc UnauthorizedError(w http.ResponseWriter, err string) {\n\tw.Header().Set(\"WWW-Authenticate\", fmt.Sprintf(\"Bearer realm=%s\", realm))\n\tError(w, err, http.StatusUnauthorized)\n}\n\nfunc NoContent(w http.ResponseWriter) ", "output": "{\n\tw.WriteHeader(http.StatusNoContent)\n}"} {"input": "package collector\n\nimport (\n\t\"github.com/go-kit/log\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\ntype interruptsCollector struct {\n\tdesc typedDesc\n\tlogger log.Logger\n}\n\n\n\n\nfunc NewInterruptsCollector(logger log.Logger) (Collector, error) {\n\treturn &interruptsCollector{\n\t\tdesc: typedDesc{prometheus.NewDesc(\n\t\t\tnamespace+\"_interrupts_total\",\n\t\t\t\"Interrupt details.\",\n\t\t\tinterruptLabelNames, nil,\n\t\t), prometheus.CounterValue},\n\t\tlogger: logger,\n\t}, nil\n}\n\nfunc init() ", "output": "{\n\tregisterCollector(\"interrupts\", defaultDisabled, NewInterruptsCollector)\n}"} {"input": "package transfer\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestPicksFirstDatanode(t *testing.T) {\n\tdf := newDatanodeFailover([]string{\"foo:6000\", \"bar:6000\"})\n\tassert.EqualValues(t, df.next(), \"foo:6000\")\n}\n\nfunc TestPicksDatanodesWithoutFailures(t *testing.T) {\n\tdf := newDatanodeFailover([]string{\"foo:6000\", \"foo:7000\", \"bar:6000\"})\n\tdatanodeFailures[\"foo:6000\"] = time.Now()\n\n\tassert.EqualValues(t, df.next(), \"foo:7000\")\n}\n\n\n\nfunc TestPicksDatanodesWithOldestFailures(t *testing.T) ", "output": "{\n\tdf := newDatanodeFailover([]string{\"foo:6000\", \"bar:6000\"})\n\tdatanodeFailures[\"foo:6000\"] = time.Now().Add(-10 * time.Minute)\n\tdatanodeFailures[\"bar:6000\"] = time.Now()\n\n\tassert.EqualValues(t, df.next(), \"foo:6000\")\n}"} {"input": "package tddbc\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\nfunc TestSay(t *testing.T) {\n\tactual := Say(\"Wow!\")\n\texpected := \"Wow! TDD BootCamp!!\"\n\n\tif actual != expected {\n\t\tt.Errorf(\"actual=%s, expect=%s\", actual, expected)\n\t}\n}\n\n\n\nfunc TestSay_testify(t *testing.T) ", "output": "{\n\tactual := Say(\"Hello!\")\n\tassert.Equal(t, \"Hello! TDD BootCamp!!\", actual, \"they should be equal\")\n}"} {"input": "package mdr\n\n\nfunc AbsF64(a float64) float64 {\n\tif a < 0.0 {\n\t\treturn -a\n\t}\n\treturn a\n}\n\n\nfunc InRangeF64(a, b, c float64) bool {\n\tif a > c { \n\t\ta, c = c, a\n\t}\n\tif b < a {\n\t\treturn false\n\t}\n\tif b > c {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\nfunc RangeLoHiF64Slice(v []float64) (lo, hi float64) {\n\tvlen := len(v)\n\tif vlen <= 0 {\n\t\treturn\n\t}\n\tlo, hi = v[0], v[0]\n\tfor i := 1; i < vlen; i++ {\n\t\tif v[i] < lo {\n\t\t\tlo = v[i]\n\t\t}\n\t\tif v[i] > hi {\n\t\t\thi = v[i]\n\t\t}\n\t}\n\treturn lo, hi\n}\n\n\n\n\nfunc ForceRangeF64(a, b, c float64) float64 ", "output": "{\n\tif a > c { \n\t\ta, c = c, a\n\t}\n\tif b < a {\n\t\treturn a\n\t}\n\tif b > c {\n\t\treturn c\n\t}\n\treturn b\n}"} {"input": "package main\n\nimport (\n\t\"github.com/takama/daemon\"\n)\n\n\ntype Service struct {\n\tdaemon.Daemon\n}\n\nfunc (service *Service) Start() (string, error) {\n\n\n\tgo URLScanner(results, control, urls)\n\treturn \"\", nil\n}\n\nfunc (service *Service) Stop() (string, error) {\n\n\tcontrol <- FULLSTOP\n\treturn \"\", nil\n}\n\nfunc (service *Service) Status() (string, error) {\n\treturn \"\", nil\n}\n\n\n\nfunc (service *Service) Update() (string, error) ", "output": "{\n\treturn \"\", nil\n}"} {"input": "package rotaryLogger\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\nvar Logger *log.Logger\n\nvar file os.File\n\n\n\n\n\nfunc StartLoggerWRotation(logAmount int, logLocation string, rotationPeriod time.Duration) {\n\tlogRotator(logAmount, logLocation)\n\n\tStartLogger(logLocation)\n\n\tticker := time.NewTicker(rotationPeriod)\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tLogger.Println(\"Rotating Logs\")\n\n\t\t\tLogger = log.New(os.Stdout,\n\t\t\t\t\"\", \n\t\t\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n\n\t\t\tlogRotator(logAmount, logLocation)\n\n\t\t\tStartLogger(logLocation)\n\n\t\t}\n\t}()\n}\n\n\n\n\n\n\n\nfunc logRotator(logAmount int, logLocation string) {\n\tif _, err := os.Stat(logLocation + strconv.Itoa(logAmount) + \".log\"); os.IsNotExist(err) {\n\t\tos.Remove(logLocation + strconv.Itoa(logAmount) + \".log\")\n\t}\n\n\tfor i := 2; i != -1; i-- {\n\t\tfmt.Println(logLocation + strconv.Itoa(i) + \".log\")\n\t\tif _, err := os.Stat(logLocation + strconv.Itoa(i) + \".log\"); err == nil {\n\t\t\tos.Rename(logLocation+strconv.Itoa(i)+\".log\", logLocation+strconv.Itoa(i+1)+\".log\")\n\t\t}\n\t}\n}\n\nfunc StartLogger(logLocation string) ", "output": "{\n\tfile, err := os.OpenFile(logLocation+\"0.log\", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to open Logger file\", err)\n\t}\n\n\tmulti := io.MultiWriter(file, os.Stdout)\n\n\tLogger = log.New(multi,\n\t\t\"\", \n\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n}"} {"input": "package nodes\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\ntype Name struct {\n\tTaxID string `json:\"TaxID\"`\n\tNames []NameItem `json:\"Names\"`\n}\n\n\ntype NameItem struct {\n\tName string `json:\"Name\"`\n\tUniqueName string `json:\"UniqueName\"`\n\tNameClass string `json:\"NameClass\"`\n}\n\n\n\n\n\nfunc NameFromJSON(s string) (Name, error) {\n\tvar name Name\n\terr := json.Unmarshal([]byte(s), &name)\n\treturn name, err\n}\n\n\nfunc NameFromArgs(items []string) Name {\n\tif len(items) != 4 {\n\t\treturn Name{}\n\t}\n\n\treturn Name{\n\t\tTaxID: items[0],\n\t\tNames: []NameItem{\n\t\t\tNameItem{\n\t\t\t\tName: items[1],\n\t\t\t\tUniqueName: items[2],\n\t\t\t\tNameClass: items[3],\n\t\t\t}},\n\t}\n}\n\n\nfunc MergeNames(names ...Name) Name {\n\tif len(names) < 2 {\n\t\treturn names[0]\n\t}\n\tname := names[0]\n\tfor _, another := range names[1:] {\n\t\tif another.TaxID != name.TaxID {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, anotherNameItem := range another.Names {\n\t\t\tname.Names = append(name.Names, anotherNameItem)\n\t\t}\n\t}\n\treturn name\n}\n\n\nvar Names map[string]Name\n\nvar mutex1 = &sync.Mutex{}\n\n\nfunc SetNames(names map[string]Name) {\n\tmutex1.Lock()\n\tNames = names\n\tmutex1.Unlock()\n}\n\nfunc (name Name) ToJSON() (string, error) ", "output": "{\n\ts, err := json.Marshal(name)\n\treturn string(s), err\n}"} {"input": "package httpclient\n\n\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"time\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\n\ntype Config struct {\n\tConnectTimeout time.Duration\n\tReadWriteTimeout time.Duration\n}\n\n\n\n\n\nfunc NewTimeoutClient(args ...interface{}) *http.Client {\n\tconfig := &Config{\n\t\tConnectTimeout: 1 * time.Second,\n\t\tReadWriteTimeout: 1 * time.Second,\n\t}\n\n\tif len(args) == 1 {\n\t\ttimeout := args[0].(time.Duration)\n\t\tconfig.ConnectTimeout = timeout\n\t\tconfig.ReadWriteTimeout = timeout\n\t}\n\n\tif len(args) == 2 {\n\t\tconfig.ConnectTimeout = args[0].(time.Duration)\n\t\tconfig.ReadWriteTimeout = args[1].(time.Duration)\n\t}\n\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDial: timeoutDialer(config),\n\t\t},\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\tif len(via) >= 10 {\n\t\t\t\treturn errors.New(\"stopped after 10 redirects\")\n\t\t\t}\n\t\t\tlastURL := via[len(via)-1].URL\n\t\t\tlogrus.Debugf(\"GOT REDIRECT FROM %v TO: %v\\n\", lastURL, req.URL)\n\t\t\trequestDump, err := httputil.DumpRequest(req, true)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"Couldn't dump request: %s\", err)\n\t\t\t} else {\n\t\t\t\tlogrus.Debugln(string(requestDump))\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\nfunc timeoutDialer(config *Config) func(net, addr string) (c net.Conn, err error) ", "output": "{\n\treturn func(netw, addr string) (net.Conn, error) {\n\t\tconn, err := net.DialTimeout(netw, addr, config.ConnectTimeout)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconn.SetDeadline(time.Now().Add(config.ReadWriteTimeout))\n\t\treturn conn, nil\n\t}\n}"} {"input": "package vsphere\n\nimport (\n\t\"fmt\"\n)\n\nconst BuilderId = \"packer.post-processor.vsphere\"\n\ntype Artifact struct {\n\tfiles []string\n\tdatastore string\n\tvmfolder string\n\tvmname string\n}\n\nfunc NewArtifact(datastore, vmfolder, vmname string, files []string) *Artifact {\n\treturn &Artifact{\n\t\tfiles: files,\n\t\tdatastore: datastore,\n\t\tvmfolder: vmfolder,\n\t\tvmname: vmname,\n\t}\n}\n\nfunc (*Artifact) BuilderId() string {\n\treturn BuilderId\n}\n\n\n\nfunc (a *Artifact) Id() string {\n\treturn fmt.Sprintf(\"%s::%s::%s\", a.datastore, a.vmfolder, a.vmname)\n}\n\nfunc (a *Artifact) String() string {\n\treturn fmt.Sprintf(\"VM: %s Folder: %s Datastore: %s\", a.vmname, a.vmfolder, a.datastore)\n}\n\nfunc (*Artifact) State(name string) interface{} {\n\treturn nil\n}\n\nfunc (a *Artifact) Destroy() error {\n\treturn nil\n}\n\nfunc (a *Artifact) Files() []string ", "output": "{\n\treturn a.files\n}"} {"input": "package docker\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/zendesk/hyperclair/docker/httpclient\"\n\t\"github.com/zendesk/hyperclair/xerrors\"\n)\n\n\n\n\nfunc Login(registry string) (bool, error) ", "output": "{\n\n\tlogrus.Info(\"log in: \", registry)\n\n\tclient := httpclient.Get()\n\trequest, err := http.NewRequest(\"GET\", registry, nil)\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"log in %v: %v\", registry, err)\n\t}\n\tauthorized := response.StatusCode != http.StatusUnauthorized\n\tif !authorized {\n\t\tlogrus.Info(\"Unauthorized access\")\n\t\terr := AuthenticateResponse(response, request)\n\n\t\tif err != nil {\n\t\t\tif err == xerrors.Unauthorized {\n\t\t\t\tauthorized = false\n\t\t\t}\n\t\t\treturn false, err\n\t\t} else {\n\t\t\tauthorized = true\n\t\t}\n\t}\n\n\treturn authorized, nil\n}"} {"input": "package bunyan\n\nimport \"os\"\n\n\n\ntype Sink interface {\n\tWrite(record Record) error\n}\n\ntype funcSink struct {\n\twrite func(record Record) error\n}\n\nfunc (sink *funcSink) Write(record Record) error {\n\treturn sink.write(record)\n}\n\n\n\nfunc SinkFunc(write func(record Record) error) Sink {\n\treturn &funcSink{write}\n}\n\n\n\nfunc NilSink() Sink {\n\treturn SinkFunc(func(record Record) error {\n\t\treturn nil \n\t})\n}\n\n\n\n\nfunc StdoutSink() Sink {\n\treturn NewJsonSink(os.Stdout)\n}\n\n\nfunc FileSink(path string) Sink {\n\tconst flags = os.O_CREATE | os.O_APPEND | os.O_WRONLY\n\tfile, e := os.OpenFile(path, flags, 0666)\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\n\treturn NewJsonSink(file)\n}\n\nfunc InfoSink(target Sink, info Info) Sink ", "output": "{\n\treturn SinkFunc(func(record Record) error {\n\t\trecord.SetIfNot(info.Key(), info.Value())\n\t\treturn target.Write(record)\n\t})\n}"} {"input": "package bitswap\n\nimport (\n\t\"context\"\n\n\tbsnet \"github.com/ipfs/go-ipfs/exchange/bitswap/network\"\n\tmockrouting \"github.com/ipfs/go-ipfs/routing/mock\"\n\tpeer \"gx/ipfs/QmWNY7dV54ZDYmTA1ykVdwNCqC11mpU4zSUp6XDpLTH9eG/go-libp2p-peer\"\n\tmockpeernet \"gx/ipfs/Qma23bpHwQrQyvKeBemaeJh7sAoRHggPkgnge1B9489ff5/go-libp2p/p2p/net/mock\"\n\tds \"gx/ipfs/QmdHG8MAuARdGHxx4rPQASLcvhz24fzjSQq7AJRAQEorq5/go-datastore\"\n\ttestutil \"gx/ipfs/QmeDA8gNhvRTsbrjEieay5wezupJDiky8xvCzDABbsGzmp/go-testutil\"\n)\n\ntype peernet struct {\n\tmockpeernet.Mocknet\n\troutingserver mockrouting.Server\n}\n\nfunc StreamNet(ctx context.Context, net mockpeernet.Mocknet, rs mockrouting.Server) (Network, error) {\n\treturn &peernet{net, rs}, nil\n}\n\n\n\nfunc (pn *peernet) HasPeer(p peer.ID) bool {\n\tfor _, member := range pn.Mocknet.Peers() {\n\t\tif p == member {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nvar _ Network = (*peernet)(nil)\n\nfunc (pn *peernet) Adapter(p testutil.Identity) bsnet.BitSwapNetwork ", "output": "{\n\tclient, err := pn.Mocknet.AddPeer(p.PrivateKey(), p.Address())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\trouting := pn.routingserver.ClientWithDatastore(context.TODO(), p, ds.NewMapDatastore())\n\treturn bsnet.NewFromIpfsHost(client, routing)\n}"} {"input": "package algorithms\n\nimport \"log\"\n\nfunc canCompleteCircuit(gas []int, cost []int) int {\n\tindex := 0\n\tfor i := 0; i < len(gas); i++ {\n\t\tgas[i] = gas[i] - cost[i]\n\t\tif i > 0 {\n\t\t\tgas[i] += gas[i-1]\n\t\t\tif gas[i] < gas[index] {\n\t\t\t\tindex = i\n\t\t\t}\n\t\t}\n\t}\n\tif gas[len(gas)-1] < 0 {\n\t\treturn -1\n\t}\n\treturn (index + 1) % len(gas)\n}\n\n\n\nfunc canCompleteCircuit(gas []int, cost []int) int ", "output": "{\n\tfor i := 0; i < len(gas); i++ {\n\t\tgas[i] = gas[i] - cost[i]\n\t}\n\tlog.Println(\"A:\", gas)\n\n\tindex := 0\n\tfor i := 1; i < len(gas); i++ {\n\t\tgas[i] += gas[i-1]\n\t\tif gas[i] < gas[index] {\n\t\t\tindex = i\n\t\t}\n\t}\n\tlog.Println(\"B:\", gas)\n\tif gas[len(gas)-1] < 0 {\n\t\treturn -1\n\t}\n\treturn (index + 1) % len(gas)\n}"} {"input": "package query\n\n\n\nimport (\n\t\"net/url\"\n\n\trequest \"github.com/aws/aws-sdk-go-v2/aws\"\n\t\"github.com/aws/aws-sdk-go-v2/aws/awserr\"\n\t\"github.com/aws/aws-sdk-go-v2/private/protocol/query/queryutil\"\n)\n\n\nvar BuildHandler = request.NamedHandler{Name: \"awssdk.query.Build\", Fn: Build}\n\n\n\n\nfunc Build(r *request.Request) ", "output": "{\n\tbody := url.Values{\n\t\t\"Action\": {r.Operation.Name},\n\t\t\"Version\": {r.Metadata.APIVersion},\n\t}\n\tif err := queryutil.Parse(body, r.Params, false); err != nil {\n\t\tr.Error = awserr.New(\"SerializationError\", \"failed encoding Query request\", err)\n\t\treturn\n\t}\n\n\tif r.ExpireTime == 0 {\n\t\tr.HTTPRequest.Method = \"POST\"\n\t\tr.HTTPRequest.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded; charset=utf-8\")\n\t\tr.SetBufferBody([]byte(body.Encode()))\n\t} else { \n\t\tr.HTTPRequest.Method = \"GET\"\n\t\tr.HTTPRequest.URL.RawQuery = body.Encode()\n\t}\n}"} {"input": "package response\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\nvar realm = \"example_api\"\n\n\nfunc WriteJSON(w http.ResponseWriter, v interface{}, code int) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(code)\n\tjson.NewEncoder(w).Encode(v)\n}\n\n\nfunc NoContent(w http.ResponseWriter) {\n\tw.WriteHeader(http.StatusNoContent)\n}\n\n\n\n\n\n\n\nfunc UnauthorizedError(w http.ResponseWriter, err string) {\n\tw.Header().Set(\"WWW-Authenticate\", fmt.Sprintf(\"Bearer realm=%s\", realm))\n\tError(w, err, http.StatusUnauthorized)\n}\n\nfunc Error(w http.ResponseWriter, err string, code int) ", "output": "{\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(code)\n\tjson.NewEncoder(w).Encode(map[string]string{\"error\": err})\n}"} {"input": "package models\n\nimport (\n\t\"html/template\"\n\t\"time\"\n\n\t\"github.com/NyaaPantsu/nyaa/config\"\n)\n\n\ntype Comment struct {\n\tID uint `gorm:\"column:comment_id;primary_key\"`\n\tTorrentID uint `gorm:\"column:torrent_id\"`\n\tUserID uint `gorm:\"column:user_id\"`\n\tContent string `gorm:\"column:content\"`\n\tCreatedAt time.Time `gorm:\"column:created_at\"`\n\tUpdatedAt time.Time `gorm:\"column:updated_at\"`\n\tDeletedAt *time.Time\n\n\tTorrent *Torrent `gorm:\"AssociationForeignKey:TorrentID;ForeignKey:torrent_id\"`\n\tUser *User `gorm:\"AssociationForeignKey:UserID;ForeignKey:user_id\"`\n}\n\n\ntype CommentJSON struct {\n\tUsername string `json:\"username\"`\n\tUserID int `json:\"user_id\"`\n\tUserAvatar string `json:\"user_avatar\"`\n\tContent template.HTML `json:\"content\"`\n\tDate time.Time `json:\"date\"`\n}\n\n\nfunc (c Comment) Size() int {\n\treturn (3 + 3*3 + 2 + 2 + len(c.Content)) * 8\n}\n\n\n\n\n\nfunc (c *Comment) Identifier() string { \n\treturn c.Torrent.Identifier()\n}\n\nfunc (c Comment) TableName() string ", "output": "{\n\treturn config.Get().Models.CommentsTableName\n}"} {"input": "package checksums\n\nimport (\n\t\"crypto/md5\"\n\t\"hash\"\n\t\"hash/crc32\"\n\t\"io\"\n\t\"sync\"\n)\n\nvar crc32cTable *crc32.Table\nvar tableInitOnce = new(sync.Once)\n\n\n\ntype Digest struct {\n\tmd5 hash.Hash\n\tcrc32c hash.Hash32\n}\n\n\nvar _ io.Writer = new(Digest)\n\n\nfunc NewDigest() *Digest {\n\ttableInitOnce.Do(func() { crc32cTable = crc32.MakeTable(crc32.Castagnoli) })\n\treturn &Digest{\n\t\tmd5: md5.New(),\n\t\tcrc32c: crc32.New(crc32cTable),\n\t}\n}\n\n\n\n\n\n\nfunc (d *Digest) Reset() {\n\td.md5.Reset()\n\td.crc32c.Reset()\n}\n\n\nfunc (d *Digest) Checksums() Checksums {\n\treturn Checksums{\n\t\tMD5: d.md5.Sum(nil),\n\t\tCRC32C: int32(d.crc32c.Sum32()),\n\t\tHasCRC32C: true,\n\t}\n}\n\nfunc (d *Digest) Write(p []byte) (int, error) ", "output": "{\n\td.crc32c.Write(p)\n\td.md5.Write(p)\n\treturn len(p), nil\n}"} {"input": "package iso20022\n\n\ntype Header12 struct {\n\n\tDownloadTransfer *TrueFalseIndicator `xml:\"DwnldTrf\"`\n\n\tFormatVersion *Max6Text `xml:\"FrmtVrsn\"`\n\n\tExchangeIdentification *Max3NumericText `xml:\"XchgId\"`\n\n\tCreationDateTime *ISODateTime `xml:\"CreDtTm\"`\n\n\tInitiatingParty *GenericIdentification53 `xml:\"InitgPty\"`\n\n\tRecipientParty *GenericIdentification53 `xml:\"RcptPty,omitempty\"`\n}\n\nfunc (h *Header12) SetDownloadTransfer(value string) {\n\th.DownloadTransfer = (*TrueFalseIndicator)(&value)\n}\n\nfunc (h *Header12) SetFormatVersion(value string) {\n\th.FormatVersion = (*Max6Text)(&value)\n}\n\nfunc (h *Header12) SetExchangeIdentification(value string) {\n\th.ExchangeIdentification = (*Max3NumericText)(&value)\n}\n\nfunc (h *Header12) SetCreationDateTime(value string) {\n\th.CreationDateTime = (*ISODateTime)(&value)\n}\n\n\n\nfunc (h *Header12) AddRecipientParty() *GenericIdentification53 {\n\th.RecipientParty = new(GenericIdentification53)\n\treturn h.RecipientParty\n}\n\nfunc (h *Header12) AddInitiatingParty() *GenericIdentification53 ", "output": "{\n\th.InitiatingParty = new(GenericIdentification53)\n\treturn h.InitiatingParty\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"reflect\"\n\t\"time\"\n\n\t_ \"github.com/akutz/golf\"\n\n\t\"github.com/thecodeteam/rexray/libstorage/api/context\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/types\"\n)\n\n\n\n\n\n\nfunc GetTempSockFile(ctx types.Context) string {\n\n\tf, err := ioutil.TempFile(context.MustPathConfig(ctx).Run, \"\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tname := f.Name()\n\tos.RemoveAll(name)\n\treturn fmt.Sprintf(\"%s.sock\", name)\n}\n\n\nfunc DeviceAttachTimeout(val string) time.Duration {\n\tdur, err := time.ParseDuration(val)\n\tif err != nil {\n\t\treturn time.Duration(30) * time.Second\n\t}\n\treturn dur\n}\n\nfunc GetTypePkgPathAndName(i interface{}) string ", "output": "{\n\tt := reflect.TypeOf(i)\n\tif t.Kind() == reflect.Ptr || t.Kind() == reflect.Interface {\n\t\tt = t.Elem()\n\t}\n\tpkgPath := t.PkgPath()\n\ttypeName := t.Name()\n\tif pkgPath == \"\" {\n\t\treturn typeName\n\t}\n\treturn fmt.Sprintf(\"%s.%s\", pkgPath, typeName)\n}"} {"input": "package poll\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"os\"\n)\n\n\n\nfunc getVCAPApplicationID() (string, error) ", "output": "{\n\tvcapJSONContainer := make(map[string]interface{})\n\terr := json.Unmarshal([]byte(os.Getenv(\"VCAP_APPLICATION\")), &vcapJSONContainer)\n\tif err != nil {\n\t\treturn \"\", errors.New(\"Error in reading VCAP Application properties: \" + err.Error())\n\t}\n\tappID, ok := vcapJSONContainer[\"application_id\"].(string)\n\tif !ok {\n\t\treturn \"\", errors.New(\"Cannot Read Application Name from VCAP Application properties: string type assertion failed\")\n\t}\n\treturn appID, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"image/jpeg\"\n\t_ \"image/png\" \n\t\"io\"\n\t\"os\"\n)\n\nfunc main() {\n\tif err := toJPEG(os.Stdin, os.Stdout); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"jpeg: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\n\n\nfunc toJPEG(in io.Reader, out io.Writer) error ", "output": "{\n\timg, kind, err := image.Decode(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintln(os.Stderr, \"Input format =\", kind)\n\treturn jpeg.Encode(out, img, &jpeg.Options{Quality: 95})\n}"} {"input": "package network\n\nimport (\n\tspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n)\n\nfunc NewNoneProvider() Provider {\n\treturn &none{}\n}\n\ntype none struct {\n}\n\n\n\ntype noneNS struct {\n}\n\nfunc (h *noneNS) Set(s *specs.Spec) {\n}\n\nfunc (h *noneNS) Close() error {\n\treturn nil\n}\n\nfunc (h *none) New() (Namespace, error) ", "output": "{\n\treturn &noneNS{}, nil\n}"} {"input": "package client\n\nimport (\n\tuserapi \"github.com/projectatomic/atomic-enterprise/pkg/user/api\"\n)\n\n\ntype UserIdentityMappingsInterface interface {\n\tUserIdentityMappings() UserIdentityMappingInterface\n}\n\n\ntype UserIdentityMappingInterface interface {\n\tGet(string) (*userapi.UserIdentityMapping, error)\n\tCreate(*userapi.UserIdentityMapping) (*userapi.UserIdentityMapping, error)\n\tUpdate(*userapi.UserIdentityMapping) (*userapi.UserIdentityMapping, error)\n\tDelete(string) error\n}\n\n\ntype userIdentityMappings struct {\n\tr *Client\n}\n\n\nfunc newUserIdentityMappings(c *Client) *userIdentityMappings {\n\treturn &userIdentityMappings{\n\t\tr: c,\n\t}\n}\n\n\nfunc (c *userIdentityMappings) Get(name string) (result *userapi.UserIdentityMapping, err error) {\n\tresult = &userapi.UserIdentityMapping{}\n\terr = c.r.Get().Resource(\"userIdentityMappings\").Name(name).Do().Into(result)\n\treturn\n}\n\n\n\n\n\nfunc (c *userIdentityMappings) Update(mapping *userapi.UserIdentityMapping) (result *userapi.UserIdentityMapping, err error) {\n\tresult = &userapi.UserIdentityMapping{}\n\terr = c.r.Put().Resource(\"userIdentityMappings\").Name(mapping.Name).Body(mapping).Do().Into(result)\n\treturn\n}\n\n\nfunc (c *userIdentityMappings) Delete(name string) (err error) {\n\terr = c.r.Delete().Resource(\"userIdentityMappings\").Name(name).Do().Error()\n\treturn\n}\n\nfunc (c *userIdentityMappings) Create(mapping *userapi.UserIdentityMapping) (result *userapi.UserIdentityMapping, err error) ", "output": "{\n\tresult = &userapi.UserIdentityMapping{}\n\terr = c.r.Post().Resource(\"userIdentityMappings\").Body(mapping).Do().Into(result)\n\treturn\n}"} {"input": "package header\n\nimport \"github.com/google/netstack/tcpip\"\n\n\n\n\n\ntype NDPNeighborSolicit []byte\n\nconst (\n\tNDPNSMinimumSize = 20\n\n\tndpNSTargetAddessOffset = 4\n\n\tndpNSOptionsOffset = ndpNSTargetAddessOffset + IPv6AddressSize\n)\n\n\nfunc (b NDPNeighborSolicit) TargetAddress() tcpip.Address {\n\treturn tcpip.Address(b[ndpNSTargetAddessOffset:][:IPv6AddressSize])\n}\n\n\n\n\n\nfunc (b NDPNeighborSolicit) Options() NDPOptions {\n\treturn NDPOptions(b[ndpNSOptionsOffset:])\n}\n\nfunc (b NDPNeighborSolicit) SetTargetAddress(addr tcpip.Address) ", "output": "{\n\tcopy(b[ndpNSTargetAddessOffset:][:IPv6AddressSize], addr)\n}"} {"input": "package format\n\nimport (\n\t\"github.com/kitwalker12/fotomat/vips\"\n)\n\n\ntype Metadata struct {\n\tWidth int\n\tHeight int\n\tFormat Format\n\tOrientation Orientation\n\tHasAlpha bool\n}\n\n\nfunc MetadataBytes(blob []byte) (Metadata, error) {\n\tformat := DetectFormat(blob)\n\tif format == Unknown {\n\t\treturn Metadata{}, ErrUnknownFormat\n\t}\n\n\treturn format.MetadataBytes(blob)\n}\n\n\n\n\n\nfunc (format Format) MetadataFile(filename string) (Metadata, error) {\n\timage, err := format.LoadFile(filename)\n\tif err != nil {\n\t\treturn Metadata{}, err\n\t}\n\n\tdefer image.Close()\n\n\treturn metadataImageFormat(image, format), nil\n}\n\nfunc metadataImageFormat(image *vips.Image, format Format) Metadata {\n\tm := MetadataImage(image)\n\tm.Format = format\n\treturn m\n}\n\n\nfunc MetadataImage(image *vips.Image) Metadata {\n\to := DetectOrientation(image)\n\tw, h := o.Dimensions(image.Xsize(), image.Ysize())\n\tif w <= 0 || h <= 0 {\n\t\tpanic(\"Invalid image dimensions.\")\n\t}\n\treturn Metadata{Width: w, Height: h, Orientation: o, HasAlpha: image.HasAlpha()}\n}\n\nfunc (format Format) MetadataBytes(blob []byte) (Metadata, error) ", "output": "{\n\timage, err := format.LoadBytes(blob)\n\tif err != nil {\n\t\treturn Metadata{}, ErrUnknownFormat\n\t}\n\n\tdefer image.Close()\n\n\treturn metadataImageFormat(image, format), nil\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"github.com/go-swagger/go-swagger/errors\"\n\t\"github.com/go-swagger/go-swagger/httpkit/validate\"\n\t\"github.com/go-swagger/go-swagger/strfmt\"\n)\n\n\ntype Ticket struct {\n\n\tEventID string `json:\"event_id,omitempty\"`\n\n\tNum int32 `json:\"num,omitempty\"`\n}\n\n\nfunc (m *Ticket) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateEventID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNum(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\nfunc (m *Ticket) validateNum(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"num\", \"body\", int32(m.Num)); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *Ticket) validateEventID(formats strfmt.Registry) error ", "output": "{\n\n\tif err := validate.RequiredString(\"event_id\", \"body\", string(m.EventID)); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package controllers\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/astaxie/beego\"\n\t\"github.com/scmo/apayment-backend/models\"\n\t\"github.com/scmo/apayment-backend/services\"\n\t\"time\"\n)\n\n\n\n\ntype JournalController struct {\n\tbeego.Controller\n}\n\n\n\n\n\n\n\n\n\nfunc (this *JournalController) GetMonthlyStats() {\n\n\tuser := this.getUser()\n\n\tmonth, err := this.GetUint8(\"month\")\n\tif err != nil {\n\t\tthis.CustomAbort(400, \"Month not sent\")\n\t}\n\tyear, err := this.GetUint16(\"year\")\n\tif err != nil {\n\t\tthis.CustomAbort(400, \"Year not sent\")\n\t}\n\n\tif month < 1 || month > 12 || year < 1900 || year > uint16(time.Now().Year()) {\n\t\tthis.CustomAbort(400, \"Value not possible for one of the parameter. Year must be a 4 digit integer. Month parameter must be a interger between 1 and 31.\")\n\t}\n\n\tmonthlyStats, err := services.GetMonthlyStats(user.TVD, month, year)\n\tif err != nil {\n\t\tthis.CustomAbort(501, \"Internal Error \"+err.Error())\n\t}\n\tthis.Data[\"json\"] = monthlyStats\n\tthis.ServeJSON()\n}\n\n\n\n\n\n\nfunc (this *JournalController) AddJournalEntry() {\n\tuser := this.getUser()\n\n\tvar journalEntry models.JournalEntry\n\tjson.Unmarshal(this.Ctx.Input.RequestBody, &journalEntry)\n\n\tjournalEntry.SetDate()\n\tservices.AddJournalEntry(&journalEntry)\n\n\tthis.Data[\"json\"] = user\n\tthis.ServeJSON()\n}\n\nfunc (controller *JournalController) getUser() *models.User ", "output": "{\n\tclaims, err := services.ParseToken(controller.Ctx.Request.Header.Get(\"Authorization\"))\n\tif err != nil {\n\t\tcontroller.CustomAbort(401, \"Unauthorized\")\n\t}\n\tuser, err := services.GetUserByUsername(claims.Subject)\n\tif err != nil {\n\t\tcontroller.CustomAbort(404, err.Error())\n\t}\n\treturn user\n}"} {"input": "package db\n\nimport (\n\t\"database/sql\"\n\t\"encoding/hex\"\n\t\"sync\"\n)\n\ntype WatchedScriptsDB struct {\n\tdb *sql.DB\n\tlock *sync.Mutex\n}\n\nfunc (w *WatchedScriptsDB) Put(scriptPubKey []byte) error {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\ttx, _ := w.db.Begin()\n\tstmt, err := tx.Prepare(\"insert or replace into watchedScripts(scriptPubKey) values(?)\")\n\tdefer stmt.Close()\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\t_, err = stmt.Exec(hex.EncodeToString(scriptPubKey))\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\ttx.Commit()\n\treturn nil\n}\n\nfunc (w *WatchedScriptsDB) GetAll() ([][]byte, error) {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\tvar ret [][]byte\n\tstm := \"select scriptPubKey from watchedScripts\"\n\trows, err := w.db.Query(stm)\n\tdefer rows.Close()\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tfor rows.Next() {\n\t\tvar scriptHex string\n\t\tif err := rows.Scan(&scriptHex); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tscriptPubKey, err := hex.DecodeString(scriptHex)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tret = append(ret, scriptPubKey)\n\t}\n\treturn ret, nil\n}\n\n\n\nfunc (w *WatchedScriptsDB) Delete(scriptPubKey []byte) error ", "output": "{\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\t_, err := w.db.Exec(\"delete from watchedScripts where scriptPubKey=?\", hex.EncodeToString(scriptPubKey))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package engine\n\nimport ()\n\ntype Unit string\n\n\n\nfunc (u Unit) String() string ", "output": "{\n\treturn string(u)\n}"} {"input": "package util\n\nimport (\n\t\"github.com/go-kit/kit/log\"\n\t\"net/http\"\n\t\"path\"\n\t\"strings\"\n)\n\ntype catchAllFileHandler struct {\n\tFS http.FileSystem\n\tInnerHandler http.Handler\n\tserveInstead string\n\tLogger log.Logger\n}\n\nfunc CatchAllFileServer(\n\troot http.FileSystem,\n\tserveInstead string,\n\tlogger log.Logger,\n) http.Handler {\n\treturn &catchAllFileHandler{\n\t\tFS: root,\n\t\tInnerHandler: http.FileServer(root),\n\t\tserveInstead: serveInstead,\n\t\tLogger: logger,\n\t}\n}\n\n\n\nfunc (f *catchAllFileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif !strings.HasPrefix(r.URL.Path, \"/\") {\n\t\tr.URL.Path = \"/\" + r.URL.Path\n\t}\n\n\tfindPath := path.Clean(r.URL.Path)\n\tfile, err := f.FS.Open(findPath)\n\tif err != nil {\n\t\tf.ServeFallback(w, r)\n\t\treturn\n\t}\n\n\tif _, err := file.Stat(); err != nil {\n\t\tf.ServeFallback(w, r)\n\t\treturn\n\t}\n\n\tf.InnerHandler.ServeHTTP(w, r)\n}\n\nfunc (f *catchAllFileHandler) ServeFallback(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tfile, err := f.FS.Open(f.serveInstead)\n\tif err != nil {\n\t\tf.Logger.Log(\n\t\t\t\"action\", \"serve-fallback\",\n\t\t\t\"result\", false,\n\t\t\t\"message\", err,\n\t\t)\n\t}\n\n\td, err := file.Stat()\n\tif err != nil {\n\t\tf.Logger.Log(\n\t\t\t\"action\", \"serve-fallback\",\n\t\t\t\"result\", false,\n\t\t\t\"message\", err,\n\t\t)\n\t}\n\n\thttp.ServeContent(w, r, f.serveInstead, d.ModTime(), file)\n}"} {"input": "package podsecuritypolicy\n\nimport (\n\t\"context\"\n\n\tv3 \"github.com/rancher/types/apis/management.cattle.io/v3\"\n\tv1beta12 \"github.com/rancher/types/apis/policy/v1beta1\"\n\t\"github.com/rancher/types/config\"\n\t\"k8s.io/api/policy/v1beta1\"\n\tk8serrors \"k8s.io/apimachinery/pkg/api/errors\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\nfunc RegisterPodSecurityPolicy(ctx context.Context, context *config.UserContext) {\n\tp := pspHandler{\n\t\tpsptLister: context.Management.Management.PodSecurityPolicyTemplates(\"\").Controller().Lister(),\n\t\tpodSecurityPolicies: context.Policy.PodSecurityPolicies(\"\"),\n\t}\n\n\tcontext.Policy.PodSecurityPolicies(\"\").AddHandler(ctx, \"psp-sync\", p.sync)\n}\n\ntype pspHandler struct {\n\tpsptLister v3.PodSecurityPolicyTemplateLister\n\tpodSecurityPolicies v1beta12.PodSecurityPolicyInterface\n}\n\n\n\n\n\nfunc (p *pspHandler) sync(key string, obj *v1beta1.PodSecurityPolicy) (runtime.Object, error) ", "output": "{\n\tif obj == nil || obj.DeletionTimestamp != nil {\n\t\treturn obj, nil\n\t}\n\tif templateID, ok := obj.Annotations[podSecurityPolicyTemplateParentAnnotation]; ok {\n\t\t_, err := p.psptLister.Get(\"\", templateID)\n\t\tif err != nil {\n\t\t\tif k8serrors.IsNotFound(err) {\n\t\t\t\treturn obj, p.podSecurityPolicies.Delete(obj.Name, &metav1.DeleteOptions{})\n\n\t\t\t}\n\t\t\treturn obj, err\n\t\t}\n\n\t}\n\treturn obj, nil\n}"} {"input": "package quickfix\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\n\n\n\nfunc closeFile(f *os.File) error {\n\tif f != nil {\n\t\tif err := f.Close(); err != nil {\n\t\t\tif !os.IsNotExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc removeFile(fname string) error {\n\terr := os.Remove(fname)\n\tif (err != nil) && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\nfunc openOrCreateFile(fname string, perm os.FileMode) (f *os.File, err error) {\n\tif f, err = os.OpenFile(fname, os.O_RDWR, perm); err != nil {\n\t\tif f, err = os.OpenFile(fname, os.O_RDWR|os.O_CREATE, perm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error opening or creating file: %s: %s\", fname, err.Error())\n\t\t}\n\t}\n\treturn f, nil\n}\n\nfunc sessionIDFilenamePrefix(s SessionID) string ", "output": "{\n\tsender := []string{s.SenderCompID}\n\tif s.SenderSubID != \"\" {\n\t\tsender = append(sender, s.SenderSubID)\n\t}\n\tif s.SenderLocationID != \"\" {\n\t\tsender = append(sender, s.SenderLocationID)\n\t}\n\n\ttarget := []string{s.TargetCompID}\n\tif s.TargetSubID != \"\" {\n\t\ttarget = append(target, s.TargetSubID)\n\t}\n\tif s.TargetLocationID != \"\" {\n\t\ttarget = append(target, s.TargetLocationID)\n\t}\n\n\tfname := []string{s.BeginString, strings.Join(sender, \"_\"), strings.Join(target, \"_\")}\n\tif s.Qualifier != \"\" {\n\t\tfname = append(fname, s.Qualifier)\n\t}\n\treturn strings.Join(fname, \"-\")\n}"} {"input": "package request\n\nimport (\n\t\"time\"\n\n\t\"github.com/YakLabs/kube-cloudwatch-node-metrics/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/YakLabs/kube-cloudwatch-node-metrics/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr\"\n)\n\n\n\n\ntype Retryer interface {\n\tRetryRules(*Request) time.Duration\n\tShouldRetry(*Request) bool\n\tMaxRetries() int\n}\n\n\n\nfunc WithRetryer(cfg *aws.Config, retryer Retryer) *aws.Config {\n\tcfg.Retryer = retryer\n\treturn cfg\n}\n\n\n\nvar retryableCodes = map[string]struct{}{\n\t\"RequestError\": {},\n\t\"RequestTimeout\": {},\n\t\"ProvisionedThroughputExceededException\": {},\n\t\"Throttling\": {},\n\t\"ThrottlingException\": {},\n\t\"RequestLimitExceeded\": {},\n\t\"RequestThrottled\": {},\n\t\"LimitExceededException\": {}, \n\t\"TooManyRequestsException\": {}, \n}\n\n\n\n\nvar credsExpiredCodes = map[string]struct{}{\n\t\"ExpiredToken\": {},\n\t\"ExpiredTokenException\": {},\n\t\"RequestExpired\": {}, \n}\n\nfunc isCodeRetryable(code string) bool {\n\tif _, ok := retryableCodes[code]; ok {\n\t\treturn true\n\t}\n\n\treturn isCodeExpiredCreds(code)\n}\n\nfunc isCodeExpiredCreds(code string) bool {\n\t_, ok := credsExpiredCodes[code]\n\treturn ok\n}\n\n\n\nfunc (r *Request) IsErrorRetryable() bool {\n\tif r.Error != nil {\n\t\tif err, ok := r.Error.(awserr.Error); ok {\n\t\t\treturn isCodeRetryable(err.Code())\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\n\nfunc (r *Request) IsErrorExpired() bool ", "output": "{\n\tif r.Error != nil {\n\t\tif err, ok := r.Error.(awserr.Error); ok {\n\t\t\treturn isCodeExpiredCreds(err.Code())\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package fake_command_runner_matchers\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n\n\t\"github.com/cloudfoundry/gunk/command_runner/fake_command_runner\"\n)\n\nfunc HaveKilled(spec fake_command_runner.CommandSpec) *HaveKilledMatcher {\n\treturn &HaveKilledMatcher{Spec: spec}\n}\n\ntype HaveKilledMatcher struct {\n\tSpec fake_command_runner.CommandSpec\n\tkilled []*exec.Cmd\n}\n\nfunc (m *HaveKilledMatcher) Match(actual interface{}) (bool, error) {\n\trunner, ok := actual.(*fake_command_runner.FakeCommandRunner)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"Not a fake command runner: %#v.\", actual)\n\t}\n\n\tm.killed = runner.KilledCommands()\n\n\tmatched := false\n\tfor _, cmd := range m.killed {\n\t\tif m.Spec.Matches(cmd) {\n\t\t\tmatched = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif matched {\n\t\treturn true, nil\n\t} else {\n\t\treturn false, nil\n\t}\n}\n\n\n\nfunc (m *HaveKilledMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn fmt.Sprintf(\"Expected to not kill the following commands:%s\", prettySpec(m.Spec))\n}\n\nfunc (m *HaveKilledMatcher) FailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn fmt.Sprintf(\"Expected to kill:%s\\n\\nActually killed:%s\", prettySpec(m.Spec), prettyCommands(m.killed))\n}"} {"input": "package main\n\nimport (\n\t\"github.com/nprog/SkyEye/common\"\n\t\"github.com/nprog/SkyEye/libnet\"\n\t\"github.com/nprog/SkyEye/log\"\n\t\"encoding/json\"\n\t\"sync\"\n\t\"time\"\n)\n\n\nfunc Test() {\n\trti := common.NewMachineInfo()\n\trti.GetInfo()\n\n\ttemp, err := json.Marshal(rti)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn\n\t}\n\n\tlog.Info(string(temp))\n}\n\n\ntype OnlineCfg struct {\n\tRealtimeInfo []string\n\tRealtimeInfoCycle int64 \n}\n\n\ntype Collection struct {\n\tonlineCfg *OnlineCfg\n\tsession *libnet.Session\n\tchangeCfg bool\n\tchangeCfgMutex sync.Mutex\n}\n\n\nfunc NewCollection() *Collection {\n\treturn &Collection{}\n}\n\n\n\n\n\nfunc (c *Collection) sendRealtimeInfoLoop() {\n\tlog.Info(\"sendRealtimeInfoLoop\")\n\ttimer := time.NewTicker(5 * time.Second)\n\tttl := time.After(10 * time.Second)\nbkloop:\n\tfor {\n\t\tselect {\n\t\tcase <-timer.C:\n\n\t\t\tif c.changeCfg {\n\t\t\t\tc.changeCfg = false\n\t\t\t\tbreak bkloop\n\t\t\t}\n\t\tcase <-ttl:\n\t\t\tbreak\n\t\t}\n\t}\n\tlog.Info(\"re config RealtimeInfoLoop.\")\n\tc.sendRealtimeInfoLoop()\n}\n\n\nfunc (c *Collection) sendFastRealtimeInfoLoop() {\n\n}\n\nfunc (c *Collection) sendMachineInfo() ", "output": "{\n\tlog.V(1).Info(\"sendMachineInfo\")\n}"} {"input": "package hub\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/brianstarke/dogfort/domain\"\n\t\"github.com/gorilla/websocket\"\n)\n\ntype Connection struct {\n\tws *websocket.Conn\n\tsend chan map[string]interface{}\n}\n\n\n\nfunc (c *Connection) Writer() {\n\tfor message := range c.send {\n\t\terr := c.ws.WriteJSON(message)\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error publishing message: %s\", err.Error())\n\t\t\tbreak\n\t\t}\n\t}\n\tc.ws.Close()\n}\n\nfunc WsHandler(w http.ResponseWriter, u domain.UserUid, r *http.Request) {\n\tws, err := websocket.Upgrade(w, r, nil, 1024, 1024)\n\tif _, ok := err.(websocket.HandshakeError); ok {\n\t\thttp.Error(w, \"Not a websocket handshake\", 400)\n\t\treturn\n\t} else if err != nil {\n\t\treturn\n\t}\n\tc := &Connection{send: make(chan map[string]interface{}), ws: ws}\n\tH.Register <- struct {\n\t\tdomain.UserUid\n\t\t*Connection\n\t}{u, c}\n\tdefer func() { H.Unregister <- u }()\n\tgo c.Writer()\n\tc.Reader()\n}\n\nfunc (c *Connection) Reader() ", "output": "{\n\tfor {\n\t\t_, message, err := c.ws.ReadMessage()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tlog.Print(message)\n\t}\n\tc.ws.Close()\n}"} {"input": "package logs\n\nconst (\n\tErrorLevel = iota\n\tWarnLevel\n\tInfoLevel\n\tDebugLevel\n)\n\ntype Level uint32\n\nfunc (l Level) EQ(lv Level) bool {\n\tif l == lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) LTE(lv Level) bool {\n\tif l <= lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) LT(lv Level) bool {\n\tif l < lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc (l Level) GT(lv Level) bool {\n\tif l > lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) Color() int {\n\tvar levelColor int\n\tswitch l {\n\tcase DebugLevel:\n\t\tlevelColor = 32\n\tcase InfoLevel:\n\t\tlevelColor = 36\n\tcase WarnLevel:\n\t\tlevelColor = 33\n\tcase ErrorLevel:\n\t\tlevelColor = 31\n\tdefault:\n\t\tlevelColor = 0\n\t}\n\treturn levelColor\n}\n\nfunc (l Level) String() string {\n\tswitch l {\n\tcase DebugLevel:\n\t\treturn \"DEBU\"\n\tcase InfoLevel:\n\t\treturn \"INFO\"\n\tcase WarnLevel:\n\t\treturn \"WARN\"\n\tcase ErrorLevel:\n\t\treturn \"ERRO\"\n\t}\n\treturn \" \"\n}\n\nfunc (l Level) GTE(lv Level) bool ", "output": "{\n\tif l >= lv {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package main\n \nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n \nfunc main() {\n \n slice := generateSlice(20)\n fmt.Println(\"\\n--- Unsorted --- \\n\\n\", slice)\n quicksort(slice)\n fmt.Println(\"\\n--- Sorted ---\\n\\n\", slice, \"\\n\")\n}\n \n\nfunc generateSlice(size int) []int {\n \n slice := make([]int, size, size)\n rand.Seed(time.Now().UnixNano())\n for i := 0; i < size; i++ {\n slice[i] = rand.Intn(999) - rand.Intn(999)\n }\n return slice\n}\n \n\n\nfunc quicksort(a []int) []int ", "output": "{\n if len(a) < 2 {\n return a\n }\n \n left, right := 0, len(a)-1\n \n pivot := rand.Int() % len(a)\n \n a[pivot], a[right] = a[right], a[pivot]\n \n for i, _ := range a {\n if a[i] < a[right] {\n a[left], a[i] = a[i], a[left]\n left++\n }\n }\n \n a[left], a[right] = a[right], a[left]\n \n quicksort(a[:left])\n quicksort(a[left+1:])\n \n return a\n}"} {"input": "package archive\n\nimport \"golang.org/x/sys/unix\"\n\n\n\n\n\n\nfunc lsetxattrCreate(link string, attr string, data []byte) error {\n\terr := unix.Lsetxattr(link, attr, data, 0)\n\tif err == unix.ENOTSUP || err == unix.EEXIST {\n\t\treturn nil\n\t}\n\treturn err\n}\n\nfunc mknod(path string, mode uint32, dev uint64) error ", "output": "{\n\treturn unix.Mknod(path, mode, dev)\n}"} {"input": "package after\n\nimport (\n\t\"strconv\"\n)\n\ntype order struct {\n\tpid productId\n\tcid customerId\n}\n\ntype productId struct {\n\tid int64\n}\n\n\n\ntype customerId struct {\n\tid int64\n}\n\n\n\ntype orderId struct {\n\tid int64\n}\n\nfunc (oid orderId) String() string {\n\treturn strconv.FormatInt(oid.id, 10)\n}\n\n\n\nfunc CreateOrder(pid int64, cid int64) order {\n\treturn order{\n\t\tpid: productId{pid}, cid: customerId{cid},\n\t}\n}\n\n\n\nfunc (o order) Submit() (orderId, error) ", "output": "{\n\n\treturn orderId{int64(3252345234)}, nil\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"runtime\"\n)\n\nvar i *int\n\nfunc f(x int) {\n pc, file, line, ok := runtime.Caller(0)\n if !ok {\n panic(\"runtime.Caller not OK!\")\n }\n fmt.Printf(\"pc = %d, file = %s, line = %d\\n\", pc, file, line)\n fmt.Printf(\"f %d\\n\", x)\n}\n\nfunc final(ii *int) {\n fmt.Printf(\"finalizer called on int %d\\n\", *ii)\n}\n\n\n\nfunc main() {\n assign()\n i = nil\n runtime.GC()\n \n f(1)\n runtime.GC()\n \n}\n\nfunc assign() ", "output": "{\n ii := 10\n runtime.SetFinalizer(&ii, final)\n i = &ii\n}"} {"input": "package root\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/kubernetes-incubator/kube-aws/awsconn\"\n\t\"github.com/kubernetes-incubator/kube-aws/cfnstack\"\n\t\"github.com/kubernetes-incubator/kube-aws/core/root/config\"\n)\n\ntype DestroyOptions struct {\n\tAwsDebug bool\n\tForce bool\n}\n\ntype ClusterDestroyer interface {\n\tDestroy() error\n}\n\ntype clusterDestroyerImpl struct {\n\tunderlying *cfnstack.Destroyer\n}\n\n\n\nfunc (d clusterDestroyerImpl) Destroy() error {\n\treturn d.underlying.Destroy()\n}\n\nfunc ClusterDestroyerFromFile(configPath string, opts DestroyOptions) (ClusterDestroyer, error) ", "output": "{\n\tcfg, err := config.ConfigFromFile(configPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsession, err := awsconn.NewSessionFromRegion(cfg.Region, opts.AwsDebug)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to establish aws session: %v\", err)\n\t}\n\n\tcfnDestroyer := cfnstack.NewDestroyer(cfg.RootStackName(), session, cfg.CloudFormation.RoleARN)\n\treturn clusterDestroyerImpl{\n\t\tunderlying: cfnDestroyer,\n\t}, nil\n}"} {"input": "package server\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tpb \"github.com/zero-os/0-stor/grpc_store\"\n\t\"github.com/zero-os/0-stor/server/db/badger\"\n\t\"github.com/zero-os/0-stor/server/manager\"\n)\n\nfunc getTestNamespaceAPI(t *testing.T) (*NamespaceAPI, func()) {\n\ttmpDir, err := ioutil.TempDir(\"\", \"0stortest\")\n\trequire.NoError(t, err)\n\n\tdb, err := badger.New(path.Join(tmpDir, \"data\"), path.Join(tmpDir, \"meta\"))\n\tif err != nil {\n\t\trequire.NoError(t, err)\n\t}\n\n\tclean := func() {\n\t\tdb.Close()\n\t\tos.RemoveAll(tmpDir)\n\t}\n\n\tdisableAuth()\n\tapi := NewNamespaceAPI(db)\n\treturn api, clean\n}\n\n\n\nfunc TestGetNamespace(t *testing.T) ", "output": "{\n\tapi, clean := getTestNamespaceAPI(t)\n\tdefer clean()\n\n\tlabel := \"testnamespace\"\n\n\tmgr := manager.NewNamespaceManager(api.db)\n\terr := mgr.Create(label)\n\trequire.NoError(t, err)\n\n\treq := &pb.GetNamespaceRequest{Label: label}\n\tresp, err := api.Get(context.Background(), req)\n\trequire.NoError(t, err)\n\n\tns := resp.GetNamespace()\n\tassert.Equal(t, label, ns.GetLabel())\n\tassert.EqualValues(t, 0, ns.GetNrObjects())\n\tassert.EqualValues(t, 0, ns.GetReadRequestPerHour())\n\tassert.EqualValues(t, 0, ns.GetWriteRequestPerHour())\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t. \"github.com/Deleplace/programming-idioms/pig\"\n)\n\n\ntype AllIdiomsFacade struct {\n\tPageMeta PageMeta\n\tUserProfile UserProfile\n\tAllIdioms []*Idiom\n}\n\nfunc allIdioms(w http.ResponseWriter, r *http.Request) error {\n\n\tidioms, err := retrieveAllIdioms(r, true)\n\tif err != nil {\n\t\treturn PiErrorf(http.StatusInternalServerError, \"%v\", err)\n\t}\n\n\tdata := AllIdiomsFacade{\n\t\tPageMeta: PageMeta{\n\t\t\tPageTitle: \"All idioms\",\n\t\t\tToggles: toggles,\n\t\t},\n\t\tUserProfile: readUserProfile(r),\n\t\tAllIdioms: idioms,\n\t}\n\n\tif err := templates.ExecuteTemplate(w, \"page-all-idioms\", data); err != nil {\n\t\treturn PiErrorf(http.StatusInternalServerError, \"%v\", err)\n\t}\n\treturn nil\n}\n\n\n\nfunc retrieveAllIdioms(r *http.Request, orderByFav bool) ([]*Idiom, error) ", "output": "{\n\tctx := r.Context()\n\n\t_, idioms, err := dao.getAllIdioms(ctx, 0, \"Id\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif orderByFav {\n\t\tfavlangs := lookForFavoriteLanguages(r)\n\t\tincludeNonFav := seeNonFavorite(r)\n\t\tfor _, idiom := range idioms {\n\t\t\timplFavoriteLanguagesFirstWithOrder(idiom, favlangs, \"\", includeNonFav)\n\t\t}\n\t}\n\n\treturn idioms, nil\n}"} {"input": "package storage\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/rynorris/website/server/site\"\n\t\"github.com/rynorris/website/server/storage\"\n)\n\nconst dummyKey = \"site-configuration\"\n\ntype Service struct {\n\tstorage storage.Service\n}\n\nfunc NewService(storage storage.Service) *Service {\n\treturn &Service{\n\t\tstorage: storage,\n\t}\n}\n\nfunc (s *Service) Get() (site.Site, error) {\n\tsite := site.Site{}\n\n\tblob, err := s.storage.Get(dummyKey)\n\tif err != nil {\n\t\treturn site, err\n\t}\n\n\terr = json.Unmarshal(blob, &site)\n\n\treturn site, err\n}\n\n\n\nfunc (s *Service) Put(site site.Site) error ", "output": "{\n\tblob, err := json.Marshal(site)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.storage.Put(dummyKey, blob)\n}"} {"input": "package decorator\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hyperledger/fabric-protos-go/peer\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestDecorator(t *testing.T) ", "output": "{\n\tdec := NewDecorator()\n\tin := &peer.ChaincodeInput{\n\t\tArgs: [][]byte{{1, 2, 3}},\n\t}\n\tout := dec.Decorate(nil, in)\n\tassert.Equal(t, in, out)\n}"} {"input": "package repomodel\n\nimport (\n\t\"github.com/kopia/kopia/repo/content\"\n\t\"github.com/kopia/kopia/repo/manifest\"\n)\n\n\ntype RepositorySession struct {\n\tOpenRepo *OpenRepository\n\n\tWrittenContents ContentSet\n\tWrittenManifests ManifestSet\n}\n\n\nfunc (s *RepositorySession) WriteContent(cid content.ID) {\n\ts.WrittenContents.Add(cid)\n}\n\n\nfunc (s *RepositorySession) WriteManifest(mid manifest.ID) {\n\ts.WrittenManifests.Add(mid)\n}\n\n\nfunc (s *RepositorySession) Refresh() {\n\ts.OpenRepo.Refresh()\n}\n\n\n\n\n\nfunc (s *RepositorySession) Flush(wc *ContentSet, wm *ManifestSet) ", "output": "{\n\ts.OpenRepo.mu.Lock()\n\tdefer s.OpenRepo.mu.Unlock()\n\n\ts.OpenRepo.Contents.Add(wc.ids...)\n\ts.OpenRepo.Manifests.Add(wm.ids...)\n\n\ts.OpenRepo.RepoData.Contents.Add(wc.ids...)\n\ts.OpenRepo.RepoData.Manifests.Add(wm.ids...)\n\n\ts.WrittenContents.RemoveAll(wc.ids...)\n\ts.WrittenManifests.RemoveAll(wm.ids...)\n}"} {"input": "package ipfs\n\n\n\n\nimport (\n\t\"github.com/go-openapi/runtime\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\nfunc New(transport runtime.ClientTransport, formats strfmt.Registry) *Client {\n\treturn &Client{transport: transport, formats: formats}\n}\n\n\ntype Client struct {\n\ttransport runtime.ClientTransport\n\tformats strfmt.Registry\n}\n\n\n\n\n\nfunc (a *Client) SetTransport(transport runtime.ClientTransport) {\n\ta.transport = transport\n}\n\nfunc (a *Client) ArchiveURL(params *ArchiveURLParams) (*ArchiveURLCreated, error) ", "output": "{\n\tif params == nil {\n\t\tparams = NewArchiveURLParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"archiveUrl\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/archive\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &ArchiveURLReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*ArchiveURLCreated), nil\n\n}"} {"input": "package buildings\n\ntype store struct {\n\tbasicBuilding\n\timprovementLvl int8\n\tsales int\n\tprice int\n}\n\n\nfunc (b *store) GetRevenue() int { return b.sales * b.price }\nfunc (b *store) GetRent() int { return [4]int{1, 2, 3, 5}[b.improvementLvl] }\nfunc (b *store) GetInternalInt(name string) int {\n\tswitch name {\n\tcase \"improvementLvl\":\n\t\treturn int(b.improvementLvl)\n\tcase \"sales\":\n\t\treturn b.sales\n\tcase \"price\":\n\t\treturn b.price\n\tdefault:\n\t\treturn 0\n\t}\n}\nfunc (b *store) SetInternalInt(name string, val int) {\n\tswitch name {\n\tcase \"improvementLvl\":\n\t\tb.improvementLvl = int8(val)\n\tcase \"sales\":\n\t\tb.sales = val\n\tcase \"price\":\n\t\tb.price = val\n\t}\n}\nfunc (b *store) ToString(x, y int) string {\n\treturn \"store,\" + string(b.improvementLvl) + \",\" + string(b.sales) + \",\" + string(b.price) + \",\" + b.basicBuilding.ToString(x, y)\n}\n\nfunc (*store) GetType() string ", "output": "{ return \"store\" }"} {"input": "package ast\n\nvar _ Action = &PassAfterOrIgnore{}\n\n\ntype PassAfterOrIgnore struct {\n\taccess\n\tLimit *Target\n}\n\nfunc (p *PassAfterOrIgnore) Accept(d ActionDispatcher) error {\n\treturn d.DispatchPassAfterOrIgnore(p)\n}\n\nfunc (p *PassAfterOrIgnore) String() string {\n\tpu := &PassAfter{\n\t\tLimit: p.Limit,\n\t}\n\tif p.Limit.Lower == p.Limit.Upper && p.Limit.Lower > 0 {\n\t\treturn pu.String() + \" or ignore otherwise\"\n\t} else {\n\t\treturn pu.String() + \" or ignore if not found\"\n\t}\n}\n\n\n\n\nfunc PassAfterTargetOrIgnore() *PassAfterOrIgnore ", "output": "{\n\treturn &PassAfterOrIgnore{\n\t\tLimit: NewTarget(),\n\t}\n}"} {"input": "package mocks\n\nimport (\n\tcli \"github.com/stackanetes/kubernetes-entrypoint/client\"\n)\n\ntype MockEntrypoint struct {\n\tclient cli.ClientInterface\n\tnamespace string\n}\n\nfunc (m MockEntrypoint) Resolve() {\n}\n\nfunc (m MockEntrypoint) Client() (client cli.ClientInterface) {\n\treturn m.client\n}\n\n\n\nfunc NewEntrypointInNamespace(namespace string) MockEntrypoint {\n\treturn MockEntrypoint{\n\t\tclient: NewClient(),\n\t\tnamespace: namespace,\n\t}\n}\n\nfunc NewEntrypoint() MockEntrypoint {\n\treturn NewEntrypointInNamespace(\"test\")\n}\n\nfunc (m MockEntrypoint) GetNamespace() (namespace string) ", "output": "{\n\treturn m.namespace\n}"} {"input": "package grpclog \n\nimport \"os\"\n\nvar logger = newLoggerV2()\n\n\nfunc V(l int) bool {\n\treturn logger.V(l)\n}\n\n\nfunc Info(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\nfunc Infof(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\nfunc Infoln(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\n\nfunc Warning(args ...interface{}) {\n\tlogger.Warning(args...)\n}\n\n\nfunc Warningf(format string, args ...interface{}) {\n\tlogger.Warningf(format, args...)\n}\n\n\nfunc Warningln(args ...interface{}) {\n\tlogger.Warningln(args...)\n}\n\n\nfunc Error(args ...interface{}) {\n\tlogger.Error(args...)\n}\n\n\n\n\n\nfunc Errorln(args ...interface{}) {\n\tlogger.Errorln(args...)\n}\n\n\n\nfunc Fatal(args ...interface{}) {\n\tlogger.Fatal(args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalf(format string, args ...interface{}) {\n\tlogger.Fatalf(format, args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalln(args ...interface{}) {\n\tlogger.Fatalln(args...)\n\tos.Exit(1)\n}\n\n\n\n\nfunc Print(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\n\n\nfunc Printf(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\n\n\nfunc Println(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\nfunc Errorf(format string, args ...interface{}) ", "output": "{\n\tlogger.Errorf(format, args...)\n}"} {"input": "package haki\n\nimport (\n\t\"errors\"\n\t\"github.com/rjansen/l\"\n\t\"github.com/rjansen/l/zap\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\nfunc init() {\n\tif setupErr := zap.Setup(new(l.Configuration)); setupErr != nil {\n\t\tpanic(setupErr)\n\t}\n\tl.Info(\"context_test.init\")\n}\n\nfunc TestSetupAll(t *testing.T) {\n\terrs := SetupAll(\n\t\tfunc() error { return nil },\n\t\tfunc() error { return nil },\n\t\tfunc() error { return nil },\n\t\tfunc() error { return nil },\n\t)\n\n\tassert.Nil(t, errs)\n\tassert.Empty(t, errs)\n}\n\nfunc TestSetupAllErr(t *testing.T) {\n\tvar errs []error\n\tassert.NotPanics(t, func() {\n\t\terrs = SetupAll(\n\t\t\tfunc() error { return errors.New(\"context_test.TestSetupErrMock1\") },\n\t\t\tfunc() error { return errors.New(\"context_test.TestSetupErrMock2\") },\n\t\t\tfunc() error { return errors.New(\"context_test.TestSetupErrMock3\") },\n\t\t\tfunc() error { return errors.New(\"context_test.TestSetupErrMock4\") },\n\t\t)\n\t})\n\n\tassert.NotNil(t, errs)\n\tassert.NotEmpty(t, errs)\n\tassert.Equal(t, 4, len(errs))\n}\n\nfunc TestSetup(t *testing.T) {\n\terrs := Setup(\n\t\tfunc() error { return nil },\n\t\tfunc() error { return nil },\n\t\tfunc() error { return nil },\n\t\tfunc() error { return nil },\n\t)\n\n\tassert.Nil(t, errs)\n\tassert.Empty(t, errs)\n}\n\n\n\nfunc TestSetupErr(t *testing.T) ", "output": "{\n\tfirstErrMsg := \"context_test.TestSetupErrMock1\"\n\tvar err error\n\tassert.NotPanics(t, func() {\n\t\terr = Setup(\n\t\t\tfunc() error { return errors.New(firstErrMsg) },\n\t\t\tfunc() error { return errors.New(\"context_test.TestSetupErrMock2\") },\n\t\t\tfunc() error { return errors.New(\"context_test.TestSetupErrMock3\") },\n\t\t\tfunc() error { return errors.New(\"context_test.TestSetupErrMock4\") },\n\t\t)\n\t})\n\n\tassert.NotNil(t, err)\n\tassert.Equal(t, firstErrMsg, err.Error())\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"text/tabwriter\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nvar preFilterListCmd = &cobra.Command{\n\tUse: \"list\",\n\tShort: \"List CIDR filters\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tlistFilters(cmd, args)\n\t},\n}\n\nfunc init() {\n\tpreFilterCmd.AddCommand(preFilterListCmd)\n\tAddMultipleOutput(preFilterListCmd)\n}\n\n\n\nfunc listFilters(cmd *cobra.Command, args []string) ", "output": "{\n\tvar str string\n\tcl, err := client.GetPrefilter()\n\tif err != nil {\n\t\tFatalf(\"Cannot get CIDR list: %s\", err)\n\t}\n\tw := tabwriter.NewWriter(os.Stdout, 5, 0, 3, ' ', 0)\n\tstr = fmt.Sprintf(\"Revision: %d\", cl.Revision)\n\tfmt.Fprintln(w, str)\n\tfor _, pfx := range cl.List {\n\t\tstr = fmt.Sprintf(\"%s\", pfx)\n\t\tfmt.Fprintln(w, str)\n\t}\n\tw.Flush()\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"os\"\n)\n\ntype OutputText struct {\n\tgetText func(string)string \n}\n\n\n\nfunc (ot *OutputText) InPort(data string) {\n\tfmt.Fprintln(os.Stderr, ot.getText(data)) \n}\n\nfunc NewOutputText(getText func(string)string) *OutputText ", "output": "{ \n\treturn &OutputText{ getText }\n}"} {"input": "package iso20022\n\n\ntype StatementType2Choice struct {\n\n\tCode *SecuritiesStatementType1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification20 `xml:\"Prtry\"`\n}\n\n\n\nfunc (s *StatementType2Choice) AddProprietary() *GenericIdentification20 {\n\ts.Proprietary = new(GenericIdentification20)\n\treturn s.Proprietary\n}\n\nfunc (s *StatementType2Choice) SetCode(value string) ", "output": "{\n\ts.Code = (*SecuritiesStatementType1Code)(&value)\n}"} {"input": "package cachestore\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\n\ntype KVStore struct {\n\tstoreMap map[string]interface{}\n\tmutex sync.RWMutex\n}\n\n\nfunc (store *KVStore) Set(key string, value interface{}) {\n\tstore.mutex.Lock()\n\tstore.storeMap[key] = value\n\tstore.mutex.Unlock()\n}\n\n\nfunc (store *KVStore) Get(key string) interface{} {\n\tstore.mutex.RLock()\n\tval := store.storeMap[key]\n\tstore.mutex.RUnlock()\n\treturn val\n}\n\n\n\n\n\nfunc (store *KVStore) MarshalJSON() ([]byte, error) {\n\tstore.mutex.RLock()\n\tbytes, err := json.Marshal(store.storeMap)\n\tstore.mutex.RUnlock()\n\treturn bytes, err\n}\n\n\nfunc NewKVStore() *KVStore {\n\treturn &KVStore{map[string]interface{}{}, sync.RWMutex{}}\n}\n\nfunc (store *KVStore) Delete(key string) ", "output": "{\n\tstore.mutex.Lock()\n\tdelete(store.storeMap, key)\n\tstore.mutex.Unlock()\n}"} {"input": "package tore\n\nimport (\n\t\"github.com/pengfei-xue/tore/libs\"\n)\n\n\n\n\nfunc SetAlg(name string) {\n\tlibs.SetAlg(name)\n}\n\nfunc GetText(url string) (string, string) ", "output": "{\n\th := libs.Alg(url)\n\th.RunAlg()\n\treturn h.Title(), h.Text()\n}"} {"input": "package file\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\ntype Reader interface {\n\tio.Reader\n\tio.ReaderAt\n\tio.Seeker\n}\n\ntype Writer interface {\n\tio.Writer\n\tio.Seeker\n\tTruncate(size int64) error\n\tSync() error\n}\n\ntype ReadCloser interface {\n\tReader\n\tio.Closer\n}\n\ntype WriteCloser interface {\n\tWriter\n\tio.Closer\n}\n\ntype File interface {\n\tio.Reader\n\tio.Writer\n\tio.Seeker\n\tio.Closer\n\tio.ReaderAt\n\tTruncate(size int64) error\n\tSync() error\n}\n\n\ntype FileSystem interface {\n\tOpen(name string, flag int) (File, error)\n\n\tLock(name string) (io.Closer, error)\n\n\tExists(name string) bool\n\n\tMkdirAll(path string) error\n\n\tList(dir string) ([]string, error)\n\n\tRemove(filename string) error\n\n\tRename(oldpath, newpath string) error\n}\n\ntype osFileSystem struct{}\n\nfunc (osFileSystem) Open(name string, flag int) (File, error) {\n\treturn os.OpenFile(name, flag, 0666)\n}\n\nfunc (osFileSystem) MkdirAll(path string) error {\n\treturn os.MkdirAll(path, 0740)\n}\n\nfunc (osFileSystem) Exists(name string) bool {\n\t_, err := os.Stat(name)\n\treturn err == nil\n}\n\n\n\nfunc (osFileSystem) Remove(name string) error {\n\treturn os.Remove(name)\n}\n\nfunc (osFileSystem) Rename(oldpath, newpath string) error {\n\treturn os.Rename(oldpath, newpath)\n}\n\nvar DefaultFileSystem FileSystem = osFileSystem{}\n\nfunc (osFileSystem) List(dir string) ([]string, error) ", "output": "{\n\tf, err := os.Open(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.Readdirnames(-1)\n}"} {"input": "package crypto\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc BenchmarkRandom(b *testing.B) {\n\tfor index := 0; index < b.N; index++ {\n\t\tRandom(32)\n\t}\n}\n\nfunc TestEncrypt(t *testing.T) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tConvey(\"auth.Encrypt Test\", t, func() {\n\t\tsecret := Encrypt(src)\n\t\tSo(len(secret), ShouldEqual, 60)\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t})\n}\n\nfunc TestVerify(t *testing.T) {\n\tsrc := \"I'mAPlainSecret\"\n\tConvey(\"auth.Verify Test\", t, func() {\n\t\tfor index := 0; index < 10; index++ {\n\t\t\tsecret := Encrypt(src)\n\t\t\tSo(Verify(src, secret), ShouldBeTrue)\n\t\t}\n\t})\n}\n\n\n\nfunc BenchmarkEncrypt(b *testing.B) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tfor index := 0; index < b.N; index++ {\n\t\tEncrypt(src)\n\t}\n}\n\nfunc BenchmarkVerify(b *testing.B) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tsecret := Encrypt(src)\n\tfor index := 0; index < b.N; index++ {\n\t\tVerify(src, secret)\n\t}\n}\n\nfunc BenchmarkMixin(b *testing.B) ", "output": "{\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tfor index := 0; index < b.N; index++ {\n\t\tmixin(src)\n\t}\n}"} {"input": "package cmd\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/ghodss/yaml\"\n\t\"github.com/spf13/cobra\"\n)\n\n\nfunc NameFromCommandArgs(cmd *cobra.Command, args []string, noNameRequired bool) (string, error) {\n\tif len(args) == 0 {\n\n\t\treturn \"\", getErrorForNoName(noNameRequired)\n\t}\n\treturn args[0], nil\n}\n\n\n\nfunc prettyprint(b []byte) ([]byte, error) {\n\tvar out bytes.Buffer\n\terr := json.Indent(&out, b, \"\", \" \")\n\treturn out.Bytes(), err\n}\n\nfunc PrintOutput(format string, object interface{}) error {\n\tvar msg string\n\ttmpCluster := object\n\tif format == \"yaml\" {\n\t\ty, err := yaml.Marshal(tmpCluster)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmsg += string(y)\n\t\tfmt.Printf(msg)\n\t} else if format == \"json\" {\n\t\ty, err := json.Marshal(tmpCluster)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpmsg, err := prettyprint(y)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmsg += string(pmsg)\n\t\tfmt.Printf(msg)\n\t}\n\treturn nil\n}\n\nfunc getErrorForNoName(noNameRequired bool) error ", "output": "{\n\tif noNameRequired {\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"NAME is required\")\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n)\n\nfunc m1() {\n for i := 1; i <= 100; i++ {\n if i % 3 == 0 && i % 5 == 0 {\n fmt.Println(\"FizzBuzz\")\n } else if i % 3 == 0 {\n fmt.Println(\"Fizz\")\n } else if i % 5 == 0 {\n fmt.Println(\"Buzz\")\n } else {\n fmt.Println(i)\n }\n }\n}\n\n\n\nfunc main() {\n m1()\n m2()\n}\n\nfunc m2() ", "output": "{\n var p bool\n for i := 1; i <= 100; i++ {\n p = false\n if i % 3 == 0 {\n fmt.Printf(\"Fizz\")\n p = true\n }\n if i % 5 == 0 {\n fmt.Printf(\"Buzz\")\n p = true\n }\n if !p {\n fmt.Printf(\"%d\", i)\n }\n fmt.Println()\n }\n}"} {"input": "package filesystem\n\nimport (\n\tkeystore2 \"github.com/cossacklabs/acra/keystore\"\n)\n\nfunc getSymmetricKeyName(id string) string {\n\treturn id + `_sym`\n}\n\n\n\nfunc getClientIDSymmetricKeyName(id []byte) string {\n\treturn getSymmetricKeyName(GetServerDecryptionKeyFilename(id))\n}\n\nfunc getZoneIDSymmetricKeyName(id []byte) string {\n\treturn getSymmetricKeyName(GetZoneKeyFilename(id))\n}\n\nfunc getTokenSymmetricKeyName(id []byte, ownerType keystore2.KeyOwnerType) string ", "output": "{\n\tvar name string\n\tswitch ownerType {\n\tcase keystore2.KeyOwnerTypeClient:\n\t\tname = getClientIDSymmetricKeyName(id)\n\tcase keystore2.KeyOwnerTypeZone:\n\t\tname = getZoneIDSymmetricKeyName(id)\n\tdefault:\n\t\tname = string(id)\n\t}\n\treturn name + \".token\"\n}"} {"input": "package proxy\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n)\n\ntype Response interface {\n\tStatus() int\n\tHeader() http.Header\n\tBody() []byte\n}\n\ntype WriterRecorder struct {\n\thttp.ResponseWriter\n\tstatus int\n\tbody bytes.Buffer\n}\n\n\n\nfunc (w *WriterRecorder) Write(body []byte) (n int, err error) {\n\tif n, err := w.body.Write(body); err != nil {\n\t\treturn n, err\n\t}\n\n\treturn w.ResponseWriter.Write(body)\n}\n\nfunc (w *WriterRecorder) Body() []byte {\n\treturn w.body.Bytes()\n}\n\nfunc (w *WriterRecorder) Status() int {\n\tif w.status == 0 {\n\t\treturn 200\n\t}\n\treturn w.status\n}\n\nfunc (w *WriterRecorder) WriteHeader(status int) ", "output": "{\n\tw.ResponseWriter.WriteHeader(status)\n\tw.status = status\n}"} {"input": "package models\n\nimport (\n\t\"testing\"\n\n\t\"code.gitea.io/gitea/models/db\"\n\trepo_model \"code.gitea.io/gitea/models/repo\"\n\t\"code.gitea.io/gitea/models/unittest\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestUpdateIssueUserByRead(t *testing.T) {\n\tassert.NoError(t, unittest.PrepareTestDatabase())\n\tissue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue)\n\n\tassert.NoError(t, UpdateIssueUserByRead(4, issue.ID))\n\tunittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: issue.ID, UID: 4}, \"is_read=1\")\n\n\tassert.NoError(t, UpdateIssueUserByRead(4, issue.ID))\n\tunittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: issue.ID, UID: 4}, \"is_read=1\")\n\n\tassert.NoError(t, UpdateIssueUserByRead(unittest.NonexistentID, unittest.NonexistentID))\n}\n\nfunc TestUpdateIssueUsersByMentions(t *testing.T) {\n\tassert.NoError(t, unittest.PrepareTestDatabase())\n\tissue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue)\n\n\tuids := []int64{2, 5}\n\tassert.NoError(t, UpdateIssueUsersByMentions(db.DefaultContext, issue.ID, uids))\n\tfor _, uid := range uids {\n\t\tunittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: issue.ID, UID: uid}, \"is_mentioned=1\")\n\t}\n}\n\nfunc Test_newIssueUsers(t *testing.T) ", "output": "{\n\tassert.NoError(t, unittest.PrepareTestDatabase())\n\n\trepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)\n\tnewIssue := &Issue{\n\t\tRepoID: repo.ID,\n\t\tPosterID: 4,\n\t\tIndex: 6,\n\t\tTitle: \"newTestIssueTitle\",\n\t\tContent: \"newTestIssueContent\",\n\t}\n\n\tunittest.AssertSuccessfulInsert(t, newIssue)\n\n\tassert.NoError(t, newIssueUsers(db.DefaultContext, repo, newIssue))\n\n\tunittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: newIssue.ID, UID: newIssue.PosterID})\n\tunittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: newIssue.ID, UID: repo.OwnerID})\n}"} {"input": "package route\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"path\"\n\t\"strings\"\n)\n\n\nvar match matcher = prefixMatcher\n\n\ntype matcher func(uri string, r *Route) bool\n\n\nfunc prefixMatcher(uri string, r *Route) bool {\n\treturn strings.HasPrefix(uri, r.Path)\n}\n\n\n\n\n\nfunc SetMatcher(s string) error {\n\tswitch s {\n\tcase \"prefix\":\n\t\tmatch = prefixMatcher\n\tcase \"glob\":\n\t\tmatch = globMatcher\n\tdefault:\n\t\treturn fmt.Errorf(\"route: invalid matcher: %s\", s)\n\t}\n\treturn nil\n}\n\nfunc globMatcher(uri string, r *Route) bool ", "output": "{\n\tvar hasMatch, err = path.Match(r.Path, uri)\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] Glob matching error %s for path %s route %s\", err, uri, r.Path)\n\t\treturn false\n\t}\n\treturn hasMatch\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"k8s.io/helm/pkg/repo\"\n)\n\nvar (\n\ttestName = \"test-name\"\n\ttestURL = \"test-url\"\n)\n\nfunc TestRepoAdd(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\tfmt.Fprintln(w, \"OK\")\n\t}))\n\n\thelmHome, _ = ioutil.TempDir(\"\", \"helm_home\")\n\tdefer os.Remove(helmHome)\n\tos.Mkdir(filepath.Join(helmHome, repositoryDir), 0755)\n\tos.Mkdir(cacheDirectory(), 0755)\n\n\tif err := ioutil.WriteFile(repositoriesFile(), []byte(\"example-repo: http://exampleurl.com\"), 0666); err != nil {\n\t\tt.Errorf(\"%#v\", err)\n\t}\n\n\tif err := addRepository(testName, ts.URL); err != nil {\n\t\tt.Errorf(\"%s\", err)\n\t}\n\n\tf, err := repo.LoadRepositoriesFile(repositoriesFile())\n\tif err != nil {\n\t\tt.Errorf(\"%s\", err)\n\t}\n\t_, ok := f.Repositories[testName]\n\tif !ok {\n\t\tt.Errorf(\"%s was not successfully inserted into %s\", testName, repositoriesFile())\n\t}\n\n\tif err := insertRepoLine(testName, ts.URL); err == nil {\n\t\tt.Errorf(\"Duplicate repository name was added\")\n\t}\n\n}\n\n\n\nfunc TestRepoRemove(t *testing.T) ", "output": "{\n\thome := createTmpHome()\n\thelmHome = home\n\tif err := ensureHome(); err != nil {\n\t\tt.Errorf(\"%s\", err)\n\t}\n\n\tif err := removeRepoLine(testName); err == nil {\n\t\tt.Errorf(\"Expected error removing %s, but did not get one.\", testName)\n\t}\n\n\tif err := insertRepoLine(testName, testURL); err != nil {\n\t\tt.Errorf(\"%s\", err)\n\t}\n\n\tif err := removeRepoLine(testName); err != nil {\n\t\tt.Errorf(\"Error removing %s from repositories\", testName)\n\t}\n\n\tf, err := repo.LoadRepositoriesFile(repositoriesFile())\n\tif err != nil {\n\t\tt.Errorf(\"%s\", err)\n\t}\n\n\tif _, ok := f.Repositories[testName]; ok {\n\t\tt.Errorf(\"%s was not successfully removed from repositories list\", testName)\n\t}\n}"} {"input": "package main\n\nimport \"sync\"\n\ntype mLocker struct {\n\tm map[string]*sync.Mutex\n\tmut sync.Mutex\n}\n\nfunc multiLocker() *mLocker {\n\treturn &mLocker{m: make(map[string]*sync.Mutex)}\n}\n\n\n\nfunc (l *mLocker) Unlock(name string) {\n\tl.mut.Lock()\n\tmutex := l.m[name]\n\tl.mut.Unlock()\n\tmutex.Unlock()\n}\n\nfunc (l *mLocker) Lock(name string) ", "output": "{\n\tl.mut.Lock()\n\tmutex, ok := l.m[name]\n\tif !ok {\n\t\tmutex = new(sync.Mutex)\n\t\tl.m[name] = mutex\n\t}\n\tl.mut.Unlock()\n\tmutex.Lock()\n}"} {"input": "package config\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\n\tapierrors \"k8s.io/apimachinery/pkg/api/errors\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\tclientset \"k8s.io/client-go/kubernetes\"\n\tkubeadmapi \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm\"\n\t\"k8s.io/kubernetes/cmd/kubeadm/app/constants\"\n)\n\n\n\n\n\n\nfunc loadConfigurationBytes(client clientset.Interface, w io.Writer, logPrefix, cfgPath string) ([]byte, error) {\n\tif cfgPath != \"\" {\n\t\tfmt.Fprintf(w, \"[%s] Reading configuration options from a file: %s\\n\", logPrefix, cfgPath)\n\t\treturn ioutil.ReadFile(cfgPath)\n\t}\n\n\tfmt.Fprintf(w, \"[%s] Reading configuration from the cluster...\\n\", logPrefix)\n\n\tconfigMap, err := client.CoreV1().ConfigMaps(metav1.NamespaceSystem).Get(constants.InitConfigurationConfigMap, metav1.GetOptions{})\n\tif apierrors.IsNotFound(err) {\n\t\treturn []byte{}, err\n\t} else if err != nil {\n\t\treturn []byte{}, fmt.Errorf(\"an unexpected error happened when trying to get the ConfigMap %q in the %s namespace: %v\", constants.InitConfigurationConfigMap, metav1.NamespaceSystem, err)\n\t}\n\n\tfmt.Fprintf(w, \"[%s] FYI: You can look at this config file with 'kubectl -n %s get cm %s -oyaml'\\n\", logPrefix, metav1.NamespaceSystem, constants.InitConfigurationConfigMap)\n\treturn []byte(configMap.Data[constants.InitConfigurationConfigMapKey]), nil\n}\n\nfunc FetchConfigFromFileOrCluster(client clientset.Interface, w io.Writer, logPrefix, cfgPath string) (*kubeadmapi.InitConfiguration, error) ", "output": "{\n\tconfigBytes, err := loadConfigurationBytes(client, w, logPrefix, cfgPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinitcfg, err := BytesToInternalConfig(configBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := SetClusterDynamicDefaults(&initcfg.ClusterConfiguration); err != nil {\n\t\treturn nil, err\n\t}\n\treturn initcfg, err\n}"} {"input": "package process\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/weaveworks/scope/probe/tag\"\n\t\"github.com/weaveworks/scope/report\"\n)\n\n\nconst (\n\tPID = \"pid\"\n\tComm = \"comm\"\n\tPPID = \"ppid\"\n\tCmdline = \"cmdline\"\n\tThreads = \"threads\"\n)\n\n\ntype reporter struct {\n\tprocRoot string\n\tscope string\n}\n\n\nfunc NewReporter(procRoot, scope string) tag.Reporter {\n\treturn &reporter{\n\t\tprocRoot: procRoot,\n\t\tscope: scope,\n\t}\n}\n\n\nfunc (r *reporter) Report() (report.Report, error) {\n\tresult := report.MakeReport()\n\tprocesses, err := r.processTopology()\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tresult.Process.Merge(processes)\n\treturn result, nil\n}\n\n\n\nfunc (r *reporter) processTopology() (report.Topology, error) ", "output": "{\n\tt := report.NewTopology()\n\terr := Walk(r.procRoot, func(p *Process) {\n\t\tpidstr := strconv.Itoa(p.PID)\n\t\tnodeID := report.MakeProcessNodeID(r.scope, pidstr)\n\t\tt.NodeMetadatas[nodeID] = report.NodeMetadata{\n\t\t\tPID: pidstr,\n\t\t\tComm: p.Comm,\n\t\t\tCmdline: p.Cmdline,\n\t\t\tThreads: strconv.Itoa(p.Threads),\n\t\t}\n\t\tif p.PPID > 0 {\n\t\t\tt.NodeMetadatas[nodeID][PPID] = strconv.Itoa(p.PPID)\n\t\t}\n\t})\n\n\treturn t, err\n}"} {"input": "package dynamobrain\n\nimport \"github.com/lnxjedi/gopherbot/bot\"\n\n\n\nfunc init() ", "output": "{\n\tbot.RegisterPreload(\"brains/dynamodb.so\")\n\tbot.RegisterSimpleBrain(\"dynamo\", provider)\n}"} {"input": "package manager\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestManagerSpecials(t *testing.T) ", "output": "{\n\tconvey.Convey(\"Specials\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t)\n\t\tctx.Convey(\"When everything goes positive\", func(ctx convey.C) {\n\t\t\tsps, err := d.Specials(c)\n\t\t\tctx.Convey(\"Then err should be nil.sps should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t\tctx.So(sps, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package storage\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tmgo \"github.com/ilius/mgo\"\n\t\"github.com/ilius/starcal-server/pkg/scal/settings\"\n)\n\nvar db *MongoDatabase\n\nfunc GetDB() (Database, error) {\n\tif db == nil {\n\t\treturn nil, fmt.Errorf(\"database is not initialized\")\n\t}\n\treturn db, nil\n}\n\n\n\nfunc InitDB() ", "output": "{\n\tmongoDBDialInfo := &mgo.DialInfo{\n\t\tAddrs: []string{settings.MONGO_HOST},\n\t\tTimeout: 2 * time.Second,\n\t\tDatabase: settings.MONGO_DB_NAME,\n\t\tUsername: settings.MONGO_USERNAME,\n\t\tPassword: settings.MONGO_PASSWORD,\n\t}\n\n\tmongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tmongoSession.SetMode(mgo.Monotonic, true)\n\n\tdb = &MongoDatabase{\n\t\t*mongoSession.DB(settings.MONGO_DB_NAME),\n\t}\n}"} {"input": "package main\n\nimport (\n \"github.com/codegangsta/negroni\"\n \"net/http\"\n \"image\"\n \"image/png\"\n \"fmt\"\n \"strconv\"\n \"strings\"\n\n \"github.com/jghowe/mandelbrot\"\n)\n\n\n\nfunc main() {\n mux := http.NewServeMux()\n mux.HandleFunc(\"/render\", func(w http.ResponseWriter, req *http.Request) {\n query := req.URL.Query()\n\n width, _ := strconv.Atoi(req.FormValue(\"width\"))\n height, _ := strconv.Atoi(req.FormValue(\"height\"))\n center := complexFromString(req.FormValue(\"center\"))\n zoom, _ := strconv.ParseFloat(req.FormValue(\"zoom\"), 64)\n colors := strings.Split(req.FormValue(\"colors\"), \",\")\n spacing, _ := strconv.Atoi(query[\"colorSpacing\"][0])\n\n dimensions := image.Pt(width,height)\n\n centerX :=real(center)\n centerY := imag(center)\n\n m := mandelbrot.Render(&dimensions, centerX, centerY, zoom, colors, spacing)\n\n header := w.Header()\n\n header[\"Content-Type\"] = []string{\"image/png\"}\n\n w.WriteHeader(http.StatusOK)\n\n if err := png.Encode(w, m); err != nil {\n fmt.Println(\"image sent\")\n } else {\n fmt.Println(\"error: \", err)\n }\n })\n\n static := negroni.NewStatic(http.Dir(\"./static\"))\n\n n := negroni.Classic()\n n.Use(static)\n n.UseHandler(mux)\n n.Run(\":3000\")\n}\n\nfunc complexFromString(vals string) complex128 ", "output": "{\n fmt.Println(\"vals: \", vals)\n parts := strings.Split(vals,\",\")\n x, _ := strconv.ParseFloat(parts[0], 64)\n y, _ := strconv.ParseFloat(parts[1], 64)\n return complex(x,y)\n}"} {"input": "package misc\n\nimport (\n\t\"path\"\n)\n\n\n\nfunc PathWithoutExt(p string) string ", "output": "{\n\tn := len(p) - len(path.Ext(p))\n\treturn p[:n]\n}"} {"input": "package datascience\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype UpdateModelRequest struct {\n\n\tModelId *string `mandatory:\"true\" contributesTo:\"path\" name:\"modelId\"`\n\n\tUpdateModelDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request UpdateModelRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request UpdateModelRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request UpdateModelRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateModelResponse struct {\n\n\tRawResponse *http.Response\n\n\tModel `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateModelResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateModelResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateModelRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package gcetasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realAddress Address\n\n\nfunc (o *Address) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realAddress\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = Address(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &Address{}\n\n\nfunc (o *Address) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\n\nfunc (o *Address) SetLifecycle(lifecycle fi.Lifecycle) {\n\to.Lifecycle = &lifecycle\n}\n\nvar _ fi.HasName = &Address{}\n\n\nfunc (o *Address) GetName() *string {\n\treturn o.Name\n}\n\n\n\n\n\nfunc (o *Address) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *Address) SetName(name string) ", "output": "{\n\to.Name = &name\n}"} {"input": "package endpoint\n\nimport (\n\t\"fmt\"\n)\n\nconst (\n\t_PlaceholderCreationEncryptionPropertyName_0 = \"unspecifiedinherit\"\n\t_PlaceholderCreationEncryptionPropertyName_1 = \"off\"\n)\n\nvar (\n\t_PlaceholderCreationEncryptionPropertyIndex_0 = [...]uint8{0, 11, 18}\n\t_PlaceholderCreationEncryptionPropertyIndex_1 = [...]uint8{0, 3}\n)\n\n\n\nvar _PlaceholderCreationEncryptionPropertyValues = []PlaceholderCreationEncryptionProperty{1, 2, 4}\n\nvar _PlaceholderCreationEncryptionPropertyNameToValueMap = map[string]PlaceholderCreationEncryptionProperty{\n\t_PlaceholderCreationEncryptionPropertyName_0[0:11]: 1,\n\t_PlaceholderCreationEncryptionPropertyName_0[11:18]: 2,\n\t_PlaceholderCreationEncryptionPropertyName_1[0:3]: 4,\n}\n\n\n\nfunc PlaceholderCreationEncryptionPropertyString(s string) (PlaceholderCreationEncryptionProperty, error) {\n\tif val, ok := _PlaceholderCreationEncryptionPropertyNameToValueMap[s]; ok {\n\t\treturn val, nil\n\t}\n\treturn 0, fmt.Errorf(\"%s does not belong to PlaceholderCreationEncryptionProperty values\", s)\n}\n\n\nfunc PlaceholderCreationEncryptionPropertyValues() []PlaceholderCreationEncryptionProperty {\n\treturn _PlaceholderCreationEncryptionPropertyValues\n}\n\n\nfunc (i PlaceholderCreationEncryptionProperty) IsAPlaceholderCreationEncryptionProperty() bool {\n\tfor _, v := range _PlaceholderCreationEncryptionPropertyValues {\n\t\tif i == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (i PlaceholderCreationEncryptionProperty) String() string ", "output": "{\n\tswitch {\n\tcase 1 <= i && i <= 2:\n\t\ti -= 1\n\t\treturn _PlaceholderCreationEncryptionPropertyName_0[_PlaceholderCreationEncryptionPropertyIndex_0[i]:_PlaceholderCreationEncryptionPropertyIndex_0[i+1]]\n\tcase i == 4:\n\t\treturn _PlaceholderCreationEncryptionPropertyName_1\n\tdefault:\n\t\treturn fmt.Sprintf(\"PlaceholderCreationEncryptionProperty(%d)\", i)\n\t}\n}"} {"input": "package metrics\n\nimport (\n\t\"github.com/cloudfoundry/dropsonde/metric_sender\"\n)\n\nvar metricSender metric_sender.MetricSender\nvar metricBatcher MetricBatcher\n\ntype MetricBatcher interface {\n\tBatchIncrementCounter(name string)\n\tBatchAddCounter(name string, delta uint64)\n\tClose()\n}\n\n\nfunc Initialize(ms metric_sender.MetricSender, mb MetricBatcher) {\n\tif metricBatcher != nil {\n\t\tmetricBatcher.Close()\n\t}\n\tmetricSender = ms\n\tmetricBatcher = mb\n}\n\n\nfunc Close() {\n\tmetricBatcher.Close()\n}\n\n\n\nfunc SendValue(name string, value float64, unit string) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.SendValue(name, value, unit)\n}\n\n\n\n\n\n\n\n\n\nfunc BatchIncrementCounter(name string) {\n\tif metricBatcher == nil {\n\t\treturn\n\t}\n\tmetricBatcher.BatchIncrementCounter(name)\n}\n\n\n\n\nfunc AddToCounter(name string, delta uint64) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.AddToCounter(name, delta)\n}\n\n\n\n\nfunc BatchAddCounter(name string, delta uint64) {\n\tif metricBatcher == nil {\n\t\treturn\n\t}\n\tmetricBatcher.BatchAddCounter(name, delta)\n}\n\n\n\n\n\nfunc SendContainerMetric(applicationId string, instanceIndex int32, cpuPercentage float64, memoryBytes uint64, diskBytes uint64) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\n\treturn metricSender.SendContainerMetric(applicationId, instanceIndex, cpuPercentage, memoryBytes, diskBytes)\n}\n\nfunc IncrementCounter(name string) error ", "output": "{\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.IncrementCounter(name)\n}"} {"input": "package parser_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/ngdinhtoan/hari/parser\"\n)\n\nfunc TestParse(t *testing.T) {\n\tdata := []byte(`\n{\n \"name\": \"Toan\",\n \"age\": 30,\n \"active\": true,\n \"children\": [{\n \"name\": \"Hachi\",\n \"age\": 3\n },\n {\n \"name\": \"Yuri\",\n \"age\": 2\n }],\n\t\"group\": [\"family\", \"work\"],\n\t\"contact\": {\n\t\t\"phone\": \"9282882822\",\n\t\t\"email\": \"mail@gmail.com\"\n\t}\n}\n`)\n\n\trs := make(chan *parser.Struct)\n\terrs := make(chan error)\n\tdone := make(chan bool)\n\n\tgo parser.Parse(\"Person\", data, rs, errs, done)\n\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\tclose(rs)\n\t\t\tclose(errs)\n\t\t\tclose(done)\n\t\t\treturn\n\t\tcase s := <-rs:\n\t\t\tw := &stringWriter{}\n\t\t\ts.WriteTo(w)\n\t\t\tfmt.Println(w.Data)\n\t\t}\n\t}\n}\n\ntype stringWriter struct {\n\tData string\n}\n\n\n\nfunc (sw *stringWriter) Write(p []byte) (n int, err error) ", "output": "{\n\tsw.Data += string(p)\n\treturn len(p), nil\n}"} {"input": "package iso20022\n\n\ntype AcceptedStatusReason4 struct {\n\n\tReasonCode *AcceptedReason4Choice `xml:\"RsnCd\"`\n\n\tAdditionalReasonInformation *Max210Text `xml:\"AddtlRsnInf,omitempty\"`\n}\n\n\n\nfunc (a *AcceptedStatusReason4) SetAdditionalReasonInformation(value string) {\n\ta.AdditionalReasonInformation = (*Max210Text)(&value)\n}\n\nfunc (a *AcceptedStatusReason4) AddReasonCode() *AcceptedReason4Choice ", "output": "{\n\ta.ReasonCode = new(AcceptedReason4Choice)\n\treturn a.ReasonCode\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\nvar configFileOptions map[string]interface{}\n\nfunc LoadConfigFile(file string) error {\n\tconfigFileOptions = nil\n\tif _, err := os.Stat(file); err != nil {\n\t\treturn nil\n\t}\n\tif s, err := ioutil.ReadFile(file); err != nil {\n\t\treturn err\n\t} else if err := yaml.Unmarshal(s, &configFileOptions); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc getConfigFileValue(key string) interface{} {\n\tif v, ok := configFileOptions[key]; ok {\n\t\treturn v\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc IsKeyInConfig(key string) bool {\n\t_, ok := configFileOptions[key]\n\treturn ok\n}\n\n\n\n\n\nfunc GetConfigFileSlice(key string) []string {\n\tif v, ok := configFileOptions[key].([]interface{}); ok {\n\t\tretVal := []string{}\n\t\tfor _, e := range v {\n\t\t\tif strV, ok := e.(string); ok {\n\t\t\t\tretVal = append(retVal, strV)\n\t\t\t}\n\t\t}\n\t\treturn retVal\n\t} else {\n\t\treturn []string{}\n\t}\n}\n\nfunc GetConfigFileString(key string) string {\n\tv, _ := getConfigFileValue(key).(string)\n\treturn v\n}\n\nfunc GetConfigFileStringWithDefault(key string, defaultValue interface{}) string {\n\tv, _ := getConfigFileValueWithDefault(key, defaultValue).(string)\n\treturn v\n}\n\nfunc getConfigFileValueWithDefault(key string, defaultValue interface{}) interface{} ", "output": "{\n\tif v := getConfigFileValue(key); v != nil {\n\t\treturn v\n\t} else {\n\t\treturn defaultValue\n\t}\n}"} {"input": "package logs\n\nimport (\n\t\"io\"\n\n\t\"github.com/cloudfoundry/dropsonde/log_sender\"\n\t\"github.com/cloudfoundry/sonde-go/events\"\n)\n\ntype LogSender interface {\n\tSendAppLog(appID, message, sourceType, sourceInstance string) error\n\tSendAppErrorLog(appID, message, sourceType, sourceInstance string) error\n\tScanLogStream(appID, sourceType, sourceInstance string, reader io.Reader)\n\tScanErrorLogStream(appID, sourceType, sourceInstance string, reader io.Reader)\n\tLogMessage(msg []byte, msgType events.LogMessage_MessageType) log_sender.LogChainer\n}\n\nvar logSender LogSender\n\n\n\nfunc Initialize(ls LogSender) {\n\tlogSender = ls\n}\n\n\n\n\nfunc SendAppLog(appID, message, sourceType, sourceInstance string) error {\n\tif logSender == nil {\n\t\treturn nil\n\t}\n\treturn logSender.SendAppLog(appID, message, sourceType, sourceInstance)\n}\n\n\n\n\nfunc SendAppErrorLog(appID, message, sourceType, sourceInstance string) error {\n\tif logSender == nil {\n\t\treturn nil\n\t}\n\treturn logSender.SendAppErrorLog(appID, message, sourceType, sourceInstance)\n}\n\n\n\nfunc ScanLogStream(appID, sourceType, sourceInstance string, reader io.Reader) {\n\tif logSender == nil {\n\t\treturn\n\t}\n\tlogSender.ScanLogStream(appID, sourceType, sourceInstance, reader)\n}\n\n\n\nfunc ScanErrorLogStream(appID, sourceType, sourceInstance string, reader io.Reader) {\n\tif logSender == nil {\n\t\treturn\n\t}\n\tlogSender.ScanErrorLogStream(appID, sourceType, sourceInstance, reader)\n}\n\n\n\n\n\nfunc LogMessage(msg []byte, msgType events.LogMessage_MessageType) log_sender.LogChainer ", "output": "{\n\treturn logSender.LogMessage(msg, msgType)\n}"} {"input": "package models\n\nimport \"testing\"\n\nfunc TestGetEntityName(t *testing.T) {\n\t_, err := GetEntityName(2)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}\nfunc TestGetTypeName(t *testing.T) {\n\t_, err := GetTypeName(2)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}\n\nfunc TestGetSystemName(t *testing.T) {\n\t_, err := GetSystemName(30000001)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}\n\n\n\nfunc TestGetCelestialName(t *testing.T) ", "output": "{\n\t_, err := GetCelestialName(30000001)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}"} {"input": "package service\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/jakewright/tutorials/home-automation/04-hue-lights/service.config/domain\"\n)\n\ntype ConfigService struct {\n\tConfig *domain.Config\n\tLocation string\n}\n\n\n\n\n\nfunc (s *ConfigService) Reload() error {\n\tdata, err := ioutil.ReadFile(s.Location)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.Config.SetFromBytes(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (s *ConfigService) Watch(d time.Duration) ", "output": "{\n\tfor {\n\t\terr := s.Reload()\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\n\t\ttime.Sleep(d)\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n\twatchlist \"github.com/macarrie/flemzerd/watchlists\"\n\t\"github.com/macarrie/flemzerd/watchlists/impl/trakt\"\n)\n\n\n\nfunc getTraktAuthErrors(c *gin.Context) {\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tt := w.(*trakt.TraktWatchlist)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, t.GetAuthErrors())\n}\n\nfunc getTraktToken(c *gin.Context) {\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tt := w.(*trakt.TraktWatchlist)\n\tc.JSON(http.StatusOK, t.Token)\n}\n\nfunc getTraktDeviceCode(c *gin.Context) {\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\tt := w.(*trakt.TraktWatchlist)\n\tc.JSON(http.StatusOK, t.DeviceCode)\n\treturn\n}\n\nfunc performTraktAuth(c *gin.Context) ", "output": "{\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\tt := w.(*trakt.TraktWatchlist)\n\tif err := t.IsAuthenticated(); err == nil {\n\t\tc.AbortWithStatus(http.StatusNoContent)\n\t\treturn\n\t}\n\n\tgo t.Auth()\n\tc.JSON(http.StatusOK, gin.H{})\n\treturn\n}"} {"input": "package text\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\nvar text = \"The quick brown fox jumps over the lazy dog.\"\n\n\n\nfunc TestWrapNarrow(t *testing.T) {\n\texp := \"The\\nquick\\nbrown\\nfox\\njumps\\nover\\nthe\\nlazy\\ndog.\"\n\tif Wrap(text, 5) != exp {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestWrapOneLine(t *testing.T) {\n\texp := \"The quick brown fox jumps over the lazy dog.\"\n\tif Wrap(text, 500) != exp {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestWrapBug1(t *testing.T) {\n\tcases := []struct {\n\t\tlimit int\n\t\ttext string\n\t\twant string\n\t}{\n\t\t{4, \"aaaaa\", \"aaaaa\"},\n\t\t{4, \"a aaaaa\", \"a\\naaaaa\"},\n\t}\n\n\tfor _, test := range cases {\n\t\tgot := Wrap(test.text, test.limit)\n\t\tif got != test.want {\n\t\t\tt.Errorf(\"Wrap(%q, %d) = %q want %q\", test.text, test.limit, got, test.want)\n\t\t}\n\t}\n}\n\nfunc TestWrap(t *testing.T) ", "output": "{\n\texp := [][]string{\n\t\t{\"The\", \"quick\", \"brown\", \"fox\"},\n\t\t{\"jumps\", \"over\", \"the\", \"lazy\", \"dog.\"},\n\t}\n\twords := bytes.Split([]byte(text), sp)\n\tgot := WrapWords(words, 1, 24, defaultPenalty)\n\tif len(exp) != len(got) {\n\t\tt.Fail()\n\t}\n\tfor i := range exp {\n\t\tif len(exp[i]) != len(got[i]) {\n\t\t\tt.Fail()\n\t\t}\n\t\tfor j := range exp[i] {\n\t\t\tif exp[i][j] != string(got[i][j]) {\n\t\t\t\tt.Fatal(i, exp[i][j], got[i][j])\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package web\n\nimport (\n\t\"net/http\"\n\n\t\"brooce/heartbeat\"\n\t\"brooce/listing\"\n\t\"brooce/task\"\n)\n\ntype mainpageOutputType struct {\n\tQueues map[string]*listing.QueueInfoType\n\tRunningJobs []*task.Task\n\tRunningWorkers []*heartbeat.HeartbeatType\n\tTotalThreads int\n}\n\n\n\nfunc mainpageHandler(req *http.Request, rep *httpReply) (err error) ", "output": "{\n\toutput := &mainpageOutputType{}\n\n\toutput.RunningJobs, err = listing.RunningJobs(true)\n\tif err != nil {\n\t\treturn\n\t}\n\toutput.RunningWorkers, err = listing.RunningWorkers()\n\tif err != nil {\n\t\treturn\n\t}\n\toutput.Queues, err = listing.Queues(false)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, worker := range output.RunningWorkers {\n\t\toutput.TotalThreads += len(worker.Threads)\n\t}\n\n\terr = templates.ExecuteTemplate(rep, \"mainpage\", output)\n\treturn\n}"} {"input": "package master\n\nimport ()\n\n\n\ntype frame struct {\n\tjob *job\n\tslaveName string\n\tframe int\n\tdata []byte\n\tprogress byte\n\tcompleted bool\n}\n\n\n\nfunc NewFrame(job *job, fr int) *frame {\n\treturn &frame{\n\t\tjob: job,\n\t\tslaveName: \"\",\n\t\tframe: fr,\n\t\tdata: nil,\n\t\tprogress: 0,\n\t\tcompleted: false,\n\t}\n}\n\n\n\nfunc (f *frame) Job() *job {\n\treturn f.job\n}\n\nfunc (f *frame) SlaveName() string {\n\treturn f.slaveName\n}\n\nfunc (f *frame) Frame() int {\n\treturn f.frame\n}\n\nfunc (f *frame) AlignedFrame() int {\n\treturn f.frame + f.Job().Start()\n}\n\nfunc (f *frame) Data() []byte {\n\treturn f.data\n}\n\n\n\nfunc (f *frame) Completed() bool {\n\treturn f.completed\n}\n\nfunc (f *frame) File() []byte {\n\treturn f.Job().File()\n}\n\n\n\nfunc (f *frame) SetSlaveName(slaveName string) {\n\tf.slaveName = slaveName\n}\n\nfunc (f *frame) SetData(data []byte) {\n\tf.data = data\n}\n\nfunc (f *frame) SetProgress(progress byte) {\n\tf.progress = progress\n}\n\nfunc (f *frame) SetCompleted(completed bool) {\n\tf.completed = completed\n\tif completed {\n\t\tf.SetProgress(100)\n\t}\n}\n\n\n\nfunc (f *frame) Reset() {\n\tf.SetSlaveName(\"\")\n\tf.SetData(nil)\n\tf.SetProgress(0)\n\tf.SetCompleted(false)\n}\n\nfunc (f *frame) Progress() byte ", "output": "{\n\treturn f.progress\n}"} {"input": "package gini\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/irifrance/gini/gen\"\n\t\"github.com/irifrance/gini/z\"\n)\n\n\n\nfunc TestGiniAsync(t *testing.T) {\n\tg := New()\n\tgen.Php(g, 15, 14)\n\tc := g.GoSolve()\n\tticker := time.Tick(5 * time.Millisecond)\n\tfor ticks := 0; ticks < 100; ticks++ {\n\t\tselect {\n\t\tcase <-ticker:\n\t\t\tr, b := c.Test()\n\t\t\tif r != 0 && !b {\n\t\t\t\tt.Errorf(\"returned solved and not finished\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif b || r != 0 {\n\t\t\t\tt.Errorf(\"returned too soon to be believable\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\ttimeout := 50 * time.Millisecond\n\tb4Solve := time.Now()\n\tr := c.Try(timeout)\n\tsDur := time.Since(b4Solve)\n\tmargin := 2 * timeout\n\n\tif r != 0 {\n\t\tt.Errorf(\"solve hard php wasn't cancelled in .005 seconds\")\n\t}\n\tif sDur < timeout-margin {\n\t\tt.Errorf(\"cancelled early %s < %s\", sDur, timeout)\n\t}\n\tif sDur > timeout+margin {\n\t\tt.Logf(\"cancelled late. %s > %s\", sDur, timeout)\n\t}\n}\n\nfunc TestGiniTrivUnsat(t *testing.T) ", "output": "{\n\tg := New()\n\tg.Add(z.Lit(3))\n\tg.Add(0)\n\tg.Add(z.Lit(3).Not())\n\tg.Add(0)\n\tif g.Solve() != -1 {\n\t\tt.Errorf(\"basic add unsat failed.\")\n\t}\n}"} {"input": "package canvas\n\nimport \"math/rand\"\n\n\nfunc min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}\n\n\nfunc max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}\n\n\n\n\nfunc random() float64 ", "output": "{\n\treturn rand.Float64()\n}"} {"input": "package sacloud\n\n\ntype IPv6Addr struct {\n\tHostName string `json:\",omitempty\"` \n\tIPv6Addr string `json:\",omitempty\"` \n\tInterface *Interface `json:\",omitempty\"` \n\tIPv6Net *IPv6Net `json:\",omitempty\"` \n\n}\n\n\nfunc (a *IPv6Addr) GetIPv6NetID() int64 {\n\tif a.IPv6Net != nil {\n\t\treturn a.IPv6Net.ID\n\t}\n\treturn 0\n}\n\n\n\n\n\nfunc CreateNewIPv6Addr() *IPv6Addr {\n\treturn &IPv6Addr{\n\t\tIPv6Net: &IPv6Net{\n\t\t\tResource: &Resource{},\n\t\t},\n\t}\n}\n\nfunc (a *IPv6Addr) GetInternetID() int64 ", "output": "{\n\tif a.IPv6Net != nil && a.IPv6Net.Switch != nil && a.IPv6Net.Switch.Internet != nil {\n\t\treturn a.IPv6Net.Switch.Internet.ID\n\t}\n\treturn 0\n}"} {"input": "package routes\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\n\tapiservermetrics \"k8s.io/kubernetes/pkg/apiserver/metrics\"\n\t\"k8s.io/kubernetes/pkg/genericapiserver/mux\"\n\tetcdmetrics \"k8s.io/kubernetes/pkg/storage/etcd/metrics\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\n\ntype DefaultMetrics struct{}\n\n\n\n\n\ntype MetricsWithReset struct{}\n\nfunc (m MetricsWithReset) Install(c *mux.APIContainer) {\n\tdefaultMetricsHandler := prometheus.Handler().ServeHTTP\n\tc.NonSwaggerRoutes.HandleFunc(\"/metrics\", func(w http.ResponseWriter, req *http.Request) {\n\t\tif req.Method == \"DELETE\" {\n\t\t\tapiservermetrics.Reset()\n\t\t\tetcdmetrics.Reset()\n\t\t\tio.WriteString(w, \"metrics reset\\n\")\n\t\t\treturn\n\t\t}\n\t\tdefaultMetricsHandler(w, req)\n\t})\n}\n\nfunc (m DefaultMetrics) Install(c *mux.APIContainer) ", "output": "{\n\tc.NonSwaggerRoutes.Handle(\"/metrics\", prometheus.Handler())\n}"} {"input": "package database\n\nimport \"database/sql\"\n\nvar db *sql.DB\n\n\n\n\n\nfunc openSQLite() {\n\tvar err error\n\tdb, err = sql.Open(\"sqlite3\", \"adnalerts.db?loc.auto\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\nfunc Query(s string, args ...interface{}) (*sql.Rows, error) {\n\trows, err := db.Query(s, args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rows, nil\n}\n\n\nfunc Exec(s string, args ...interface{}) (sql.Result, error) {\n\tres, err := db.Exec(s, args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}\n\nfunc OpenDB() ", "output": "{\n\topenSQLite()\n}"} {"input": "package dep\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net/http\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n\n\t\"github.com/micromdm/micromdm/dep\"\n\t\"github.com/micromdm/micromdm/pkg/httputil\"\n)\n\nfunc (svc *DEPService) AssignProfile(ctx context.Context, id string, serials ...string) (*dep.ProfileResponse, error) {\n\tif svc.client == nil {\n\t\treturn nil, errors.New(\"DEP not configured yet. add a DEP token to enable DEP\")\n\t}\n\treturn svc.client.AssignProfile(id, serials...)\n}\n\ntype assignProfileRequest struct {\n\tID string `json:\"id\"`\n\tSerials []string `json:\"serials\"`\n}\n\ntype assignProfileResponse struct {\n\t*dep.ProfileResponse\n\tErr error `json:\"err,omitempty\"`\n}\n\nfunc (r assignProfileResponse) Failed() error { return r.Err }\n\nfunc decodeAssignProfileRequest(ctx context.Context, r *http.Request) (interface{}, error) {\n\tvar req assignProfileRequest\n\terr := httputil.DecodeJSONRequest(r, &req)\n\treturn req, err\n}\n\nfunc decodeAssignProfileResponse(_ context.Context, r *http.Response) (interface{}, error) {\n\tvar resp assignProfileResponse\n\terr := httputil.DecodeJSONResponse(r, &resp)\n\treturn resp, err\n}\n\nfunc MakeAssignProfileEndpoint(svc Service) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (response interface{}, err error) {\n\t\treq := request.(assignProfileRequest)\n\t\tresp, err := svc.AssignProfile(ctx, req.ID, req.Serials...)\n\t\treturn &assignProfileResponse{\n\t\t\tProfileResponse: resp,\n\t\t\tErr: err,\n\t\t}, nil\n\t}\n}\n\n\n\nfunc (e Endpoints) AssignProfile(ctx context.Context, id string, serials ...string) (*dep.ProfileResponse, error) ", "output": "{\n\trequest := assignProfileRequest{ID: id, Serials: serials}\n\tresp, err := e.AssignProfileEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponse := resp.(assignProfileResponse)\n\treturn response.ProfileResponse, response.Err\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\ntype (\n\tComputeType interface{}\n\tFileFunc func(f *os.File) ComputeType\n\tDirFunc func(d *os.File, results []ComputeType) ComputeType\n)\n\nfunc empty() ComputeType {\n\tvar e ComputeType\n\treturn e\n}\n\n\n\nfunc int64value(val interface{}) int64 {\n\tif v, ok := val.(int64); ok {\n\t\treturn v\n\t}\n\tpanic(fmt.Sprintf(\"Unexpected type: %v\", val))\n}\n\nfunc filefunc(f *os.File) ComputeType {\n\tstat, err := f.Stat()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn ComputeType(stat.Size())\n}\n\nfunc dirfunc(d *os.File, results []ComputeType) ComputeType {\n\tvar total int64\n\tfor _, v := range results {\n\t\ttotal += int64value(v)\n\t}\n\treturn total\n}\n\nfunc main() {\n\tif len(os.Args) != 2 {\n\t\tfmt.Printf(\"Usage %s NAME\\n\", os.Args[0])\n\t\tos.Exit(0)\n\t}\n\tfmt.Println(int64value(dirwalk(os.Args[1], filefunc, dirfunc)))\n}\n\nfunc dirwalk(name string, f FileFunc, d DirFunc) ComputeType ", "output": "{\n\tfile, err := os.Open(name)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tdefer file.Close()\n\n\tstat, err := file.Stat()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tif stat.IsDir() {\n\t\tfiles, err := file.Readdirnames(0)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tname = name + string(os.PathSeparator)\n\t\tresults := make([]ComputeType, 0)\n\t\tfor _, subfile := range files {\n\t\t\tresults = append(results, dirwalk(name+subfile, f, d))\n\t\t}\n\t\tif d == nil {\n\t\t\treturn empty()\n\t\t}\n\t\treturn d(file, results)\n\t}\n\tif f == nil {\n\t\treturn empty()\n\t}\n\treturn f(file)\n}"} {"input": "package v2\n\nimport (\n\t\"os\"\n\n\t\"code.cloudfoundry.org/cli/cf/cmd\"\n\t\"code.cloudfoundry.org/cli/command\"\n\t\"code.cloudfoundry.org/cli/command/flag\"\n)\n\ntype SSHEnabledCommand struct {\n\tRequiredArgs flag.AppName `positional-args:\"yes\"`\n\tusage interface{} `usage:\"CF_NAME ssh-enabled APP_NAME\"`\n\trelatedCommands interface{} `related_commands:\"enable-ssh, space-ssh-allowed, ssh\"`\n}\n\n\n\nfunc (_ SSHEnabledCommand) Execute(args []string) error {\n\tcmd.Main(os.Getenv(\"CF_TRACE\"), os.Args)\n\treturn nil\n}\n\nfunc (_ SSHEnabledCommand) Setup(config command.Config, ui command.UI) error ", "output": "{\n\treturn nil\n}"} {"input": "package payload\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hyperledger/burrow/acm/acmstate\"\n\t\"github.com/hyperledger/burrow/crypto\"\n)\n\nfunc NewBondTx(address crypto.Address, amount uint64) *BondTx {\n\treturn &BondTx{\n\t\tInput: &TxInput{\n\t\t\tAddress: address,\n\t\t\tAmount: amount,\n\t\t},\n\t}\n}\n\nfunc (tx *BondTx) Type() Type {\n\treturn TypeBond\n}\n\nfunc (tx *BondTx) GetInputs() []*TxInput {\n\treturn []*TxInput{tx.Input}\n}\n\nfunc (tx *BondTx) String() string {\n\treturn fmt.Sprintf(\"BondTx{%v}\", tx.Input)\n}\n\n\n\nfunc (tx *BondTx) AddInputWithSequence(pubkey *crypto.PublicKey, amt uint64, sequence uint64) error {\n\ttx.Input = &TxInput{\n\t\tAddress: pubkey.GetAddress(),\n\t\tAmount: amt,\n\t\tSequence: sequence,\n\t}\n\treturn nil\n}\n\nfunc (tx *BondTx) Any() *Any {\n\treturn &Any{\n\t\tBondTx: tx,\n\t}\n}\n\nfunc (tx *BondTx) AddInput(st acmstate.AccountGetter, pubkey *crypto.PublicKey, amt uint64) error ", "output": "{\n\taddr := pubkey.GetAddress()\n\tacc, err := st.GetAccount(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif acc == nil {\n\t\treturn fmt.Errorf(\"invalid address %s from pubkey %s\", addr, pubkey)\n\t}\n\treturn tx.AddInputWithSequence(pubkey, amt, acc.Sequence+uint64(1))\n}"} {"input": "package table\n\nimport (\n\t\"github.com/jedib0t/go-pretty/v6/text\"\n)\n\n\n\ntype ColumnConfig struct {\n\tName string\n\tNumber int\n\n\tAlign text.Align\n\tAlignFooter text.Align\n\tAlignHeader text.Align\n\n\tAutoMerge bool\n\n\tColors text.Colors\n\tColorsFooter text.Colors\n\tColorsHeader text.Colors\n\n\tHidden bool\n\n\tTransformer text.Transformer\n\tTransformerFooter text.Transformer\n\tTransformerHeader text.Transformer\n\n\tVAlign text.VAlign\n\tVAlignFooter text.VAlign\n\tVAlignHeader text.VAlign\n\n\tWidthMax int\n\tWidthMaxEnforcer WidthEnforcer\n\tWidthMin int\n}\n\n\n\n\n\ntype RowConfig struct {\n\tAutoMerge bool\n}\n\nfunc (c ColumnConfig) getWidthMaxEnforcer() WidthEnforcer ", "output": "{\n\tif c.WidthMax == 0 {\n\t\treturn widthEnforcerNone\n\t}\n\tif c.WidthMaxEnforcer != nil {\n\t\treturn c.WidthMaxEnforcer\n\t}\n\treturn text.WrapText\n}"} {"input": "package metcdv3\n\nimport \"github.com/lytics/metafora\"\n\ntype task struct {\n\tid string\n}\n\n\n\n\n\n\n\n\n\ntype TaskFunc func(id, value string) metafora.Task\n\n\n\nfunc DefaultTaskFunc(id, _ string) metafora.Task { return &task{id: id} }\n\nfunc (t *task) ID() string ", "output": "{ return t.id }"} {"input": "package violetear\n\nimport (\n\t\"net/http\"\n\t\"time\"\n)\n\n\ntype ResponseWriter struct {\n\thttp.ResponseWriter\n\trequestID string\n\tsize, status int\n\tstart time.Time\n}\n\n\nfunc NewResponseWriter(w http.ResponseWriter, rid string) *ResponseWriter {\n\treturn &ResponseWriter{\n\t\tResponseWriter: w,\n\t\trequestID: rid,\n\t\tstart: time.Now(),\n\t\tstatus: http.StatusOK,\n\t}\n}\n\n\nfunc (w *ResponseWriter) Status() int {\n\treturn w.status\n}\n\n\nfunc (w *ResponseWriter) Size() int {\n\treturn w.size\n}\n\n\nfunc (w *ResponseWriter) RequestTime() string {\n\treturn time.Since(w.start).String()\n}\n\n\nfunc (w *ResponseWriter) RequestID() string {\n\treturn w.requestID\n}\n\n\n\n\n\n\n\nfunc (w *ResponseWriter) WriteHeader(statusCode int) {\n\tw.status = statusCode\n\tw.ResponseWriter.WriteHeader(statusCode)\n}\n\nfunc (w *ResponseWriter) Write(data []byte) (int, error) ", "output": "{\n\tsize, err := w.ResponseWriter.Write(data)\n\tw.size += size\n\treturn size, err\n}"} {"input": "package db\n\nimport (\n\t\"gopkg.in/mgo.v2\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Session struct {\n\tS *mgo.Session\n\tDb *mgo.Database\n\tC *mgo.Collection\n}\n\n\ntype MongoClient struct {\n\tHosts string\n\tDatabase string\n\tCollection string\n\tSession\n}\n\nfunc (m *MongoClient) Connect() error {\n\tdailinfo := &mgo.DialInfo{\n\t\tAddrs: strings.Split(m.Hosts, \",\"),\n\t\tTimeout: 5 * time.Second,\n\t\tDatabase: m.Database,\n\t}\n\tsession, err := mgo.DialWithInfo(dailinfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.S = session\n\tm.S.SetMode(mgo.Monotonic, true)\n\treturn nil\n}\n\nfunc (m *MongoClient) DB() {\n\tdb := m.Session.S.DB(m.Database)\n\tm.Session.Db = db\n}\n\n\n\nfunc (m *MongoClient) Close() {\n\tif m.S != nil {\n\t\tm.S.LogoutAll()\n\t\tm.S.Close()\n\t}\n}\n\nfunc (m *MongoClient) GetCollection() *mgo.Collection {\n\treturn m.Session.C\n}\n\nfunc (m *MongoClient) C() ", "output": "{\n\tc := m.Session.Db.C(m.Collection)\n\tm.Session.C = c\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\ntype SendPhotoLinkBody struct {\n\n\tCaption string `json:\"caption,omitempty\"`\n\n\tChatID interface{} `json:\"chat_id\"`\n\n\tDisableNotification bool `json:\"disable_notification,omitempty\"`\n\n\tPhoto *string `json:\"photo\"`\n\n\tReplyMarkup interface{} `json:\"reply_markup,omitempty\"`\n\n\tReplyToMessageID int64 `json:\"reply_to_message_id,omitempty\"`\n}\n\n\n\n\nfunc (m *SendPhotoLinkBody) validateChatID(formats strfmt.Registry) error {\n\n\treturn nil\n}\n\nfunc (m *SendPhotoLinkBody) validatePhoto(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"photo\", \"body\", m.Photo); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc (m *SendPhotoLinkBody) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *SendPhotoLinkBody) UnmarshalBinary(b []byte) error {\n\tvar res SendPhotoLinkBody\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *SendPhotoLinkBody) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateChatID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePhoto(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package router\n\nimport (\n\t\"sync/atomic\"\n\n\t\"github.com/AsynkronIT/protoactor-go/actor\"\n)\n\ntype roundRobinGroupRouter struct {\n\tGroupRouter\n}\n\ntype roundRobinPoolRouter struct {\n\tPoolRouter\n}\n\ntype roundRobinState struct {\n\tindex int32\n\troutees *actor.PIDSet\n\tvalues []actor.PID\n}\n\nfunc (state *roundRobinState) SetRoutees(routees *actor.PIDSet) {\n\tstate.routees = routees\n\tstate.values = routees.Values()\n}\n\nfunc (state *roundRobinState) GetRoutees() *actor.PIDSet {\n\treturn state.routees\n}\n\n\n\nfunc NewRoundRobinPool(size int) *actor.Props {\n\treturn actor.FromSpawnFunc(spawner(&roundRobinPoolRouter{PoolRouter{PoolSize: size}}))\n}\n\nfunc NewRoundRobinGroup(routees ...*actor.PID) *actor.Props {\n\treturn actor.FromSpawnFunc(spawner(&roundRobinGroupRouter{GroupRouter{Routees: actor.NewPIDSet(routees...)}}))\n}\n\nfunc (config *roundRobinPoolRouter) CreateRouterState() Interface {\n\treturn &roundRobinState{}\n}\n\nfunc (config *roundRobinGroupRouter) CreateRouterState() Interface {\n\treturn &roundRobinState{}\n}\n\nfunc roundRobinRoutee(index *int32, routees []actor.PID) actor.PID {\n\ti := int(atomic.AddInt32(index, 1))\n\tif i < 0 {\n\t\t*index = 0\n\t\ti = 0\n\t}\n\tmod := len(routees)\n\troutee := routees[i%mod]\n\treturn routee\n}\n\nfunc (state *roundRobinState) RouteMessage(message interface{}, sender *actor.PID) ", "output": "{\n\tpid := roundRobinRoutee(&state.index, state.values)\n\tpid.Request(message, sender)\n}"} {"input": "package error\n\nimport (\n\t\"strconv\"\n)\n\n\n\ntype StructuralError string\n\n\n\n\n\ntype UnsupportedError string\n\nfunc (s UnsupportedError) String() string {\n\treturn \"OpenPGP feature unsupported: \" + string(s)\n}\n\n\n\ntype InvalidArgumentError string\n\nfunc (i InvalidArgumentError) String() string {\n\treturn \"OpenPGP argument invalid: \" + string(i)\n}\n\n\n\ntype SignatureError string\n\nfunc (b SignatureError) String() string {\n\treturn \"OpenPGP signature invalid: \" + string(b)\n}\n\ntype keyIncorrect int\n\nfunc (ki keyIncorrect) String() string {\n\treturn \"the given key was incorrect\"\n}\n\nvar KeyIncorrectError = keyIncorrect(0)\n\ntype unknownIssuer int\n\nfunc (unknownIssuer) String() string {\n\treturn \"signature make by unknown entity\"\n}\n\nvar UnknownIssuerError = unknownIssuer(0)\n\ntype UnknownPacketTypeError uint8\n\nfunc (upte UnknownPacketTypeError) String() string {\n\treturn \"unknown OpenPGP packet type: \" + strconv.Itoa(int(upte))\n}\n\nfunc (s StructuralError) String() string ", "output": "{\n\treturn \"OpenPGP data invalid: \" + string(s)\n}"} {"input": "package queue\n\nimport (\n\t\"fmt\"\n\t\"github.com/apache/servicecomb-service-center/pkg/log\"\n\t\"golang.org/x/net/context\"\n)\n\ntype UniQueue struct {\n\tqueue chan interface{}\n}\n\nfunc (uq *UniQueue) Get(ctx context.Context) interface{} {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil\n\tcase item := <-uq.queue:\n\t\treturn item\n\t}\n}\n\nfunc (uq *UniQueue) Chan() <-chan interface{} {\n\treturn uq.queue\n}\n\n\n\nfunc (uq *UniQueue) Close() {\n\tselect {\n\tcase _, ok := <-uq.queue:\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\tdefault:\n\t}\n\tclose(uq.queue)\n}\n\nfunc NewUniQueue() (uq *UniQueue) {\n\treturn &UniQueue{\n\t\tqueue: make(chan interface{}, 1),\n\t}\n}\n\nfunc (uq *UniQueue) Put(value interface{}) (e error) ", "output": "{\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.LogPanic(r)\n\n\t\t\te = fmt.Errorf(\"%v\", r)\n\t\t}\n\t}()\n\n\tselect {\n\tcase _, ok := <-uq.queue:\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"channel is closed\")\n\t\t}\n\tdefault:\n\t}\n\n\tselect {\n\tcase uq.queue <- value:\n\tdefault:\n\t}\n\treturn\n}"} {"input": "package ahsay\n\nimport \"encoding/xml\"\n\n\ntype UserType int\n\n\n\nconst (\n\tPaid UserType = iota + 1\n\tTrial\n)\n\n\n\n\nfunc (t *UserType) UnmarshalXMLAttr(attr xml.Attr) error {\n\tif attr.Value == \"PAID\" {\n\t\t*t = Paid\n\t} else if attr.Value == \"TRIAL\" {\n\t\t*t = Trial\n\t}\n\n\treturn nil\n}\n\nfunc (t UserType) String() string ", "output": "{\n\tswitch t {\n\tcase Paid:\n\t\treturn \"Paid\"\n\tcase Trial:\n\t\treturn \"Trial\"\n\tdefault:\n\t\treturn \"User type not set\"\n\t}\n}"} {"input": "package tool_test\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/matryer/codeform/source\"\n\t\"github.com/matryer/codeform/tool\"\n\t\"github.com/matryer/is\"\n)\n\n\n\nfunc TestExecute(t *testing.T) ", "output": "{\n\tis := is.New(t)\n\n\tsrcCode := source.Reader(\"source.go\", strings.NewReader(`package something\n\ntype Inter1 interface {\n\tInter1Method1(a, b int) error\n\tInter1Method2(c, d int) error\n}\n\ntype Inter2 interface {\n\tInter2Method1(a, b int) error\n\tInter2Method2(c, d int) error\n}`))\n\tsrcTmpl := source.Reader(\"template.tpl\", strings.NewReader(\n\t\t`{{ range .Packages }}{{ range .Interfaces }}{{ .Name }} {{ end }}{{ end }}`,\n\t))\n\n\tj := tool.Job{\n\t\tCode: srcCode,\n\t\tTemplate: srcTmpl,\n\t}\n\n\tvar buf bytes.Buffer\n\terr := j.Execute(&buf)\n\tis.NoErr(err)\n\tis.Equal(buf.String(), `Inter1 Inter2 `)\n\n}"} {"input": "package endpoint\n\nimport (\n\t\"fmt\"\n)\n\nconst (\n\t_PlaceholderCreationEncryptionPropertyName_0 = \"unspecifiedinherit\"\n\t_PlaceholderCreationEncryptionPropertyName_1 = \"off\"\n)\n\nvar (\n\t_PlaceholderCreationEncryptionPropertyIndex_0 = [...]uint8{0, 11, 18}\n\t_PlaceholderCreationEncryptionPropertyIndex_1 = [...]uint8{0, 3}\n)\n\nfunc (i PlaceholderCreationEncryptionProperty) String() string {\n\tswitch {\n\tcase 1 <= i && i <= 2:\n\t\ti -= 1\n\t\treturn _PlaceholderCreationEncryptionPropertyName_0[_PlaceholderCreationEncryptionPropertyIndex_0[i]:_PlaceholderCreationEncryptionPropertyIndex_0[i+1]]\n\tcase i == 4:\n\t\treturn _PlaceholderCreationEncryptionPropertyName_1\n\tdefault:\n\t\treturn fmt.Sprintf(\"PlaceholderCreationEncryptionProperty(%d)\", i)\n\t}\n}\n\nvar _PlaceholderCreationEncryptionPropertyValues = []PlaceholderCreationEncryptionProperty{1, 2, 4}\n\nvar _PlaceholderCreationEncryptionPropertyNameToValueMap = map[string]PlaceholderCreationEncryptionProperty{\n\t_PlaceholderCreationEncryptionPropertyName_0[0:11]: 1,\n\t_PlaceholderCreationEncryptionPropertyName_0[11:18]: 2,\n\t_PlaceholderCreationEncryptionPropertyName_1[0:3]: 4,\n}\n\n\n\nfunc PlaceholderCreationEncryptionPropertyString(s string) (PlaceholderCreationEncryptionProperty, error) {\n\tif val, ok := _PlaceholderCreationEncryptionPropertyNameToValueMap[s]; ok {\n\t\treturn val, nil\n\t}\n\treturn 0, fmt.Errorf(\"%s does not belong to PlaceholderCreationEncryptionProperty values\", s)\n}\n\n\n\n\n\nfunc (i PlaceholderCreationEncryptionProperty) IsAPlaceholderCreationEncryptionProperty() bool {\n\tfor _, v := range _PlaceholderCreationEncryptionPropertyValues {\n\t\tif i == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc PlaceholderCreationEncryptionPropertyValues() []PlaceholderCreationEncryptionProperty ", "output": "{\n\treturn _PlaceholderCreationEncryptionPropertyValues\n}"} {"input": "package sc\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestPanAz(t *testing.T) ", "output": "{\n\tdefName := \"PanAzTest\"\n\n\tcompareAndWriteStructure(t, defName, NewSynthdef(defName, func(p Params) Ugen {\n\t\treturn Out{\n\t\t\tBus: C(0),\n\t\t\tChannels: A(PanAz{\n\t\t\t\tNumChans: 2,\n\t\t\t\tIn: DC{In: C(1)}.Rate(AR),\n\t\t\t\tPos: A(Line{\n\t\t\t\t\tStart: C(0),\n\t\t\t\t\tEnd: C(0.5),\n\t\t\t\t\tDur: C(0.1),\n\t\t\t\t}),\n\t\t\t}),\n\t\t}.Rate(AR)\n\t}))\n}"} {"input": "package stree\n\n\n\ntype serial struct {\n\tstree\n}\n\n\nfunc NewSerial() Tree {\n\tt := new(serial)\n\tt.Clear()\n\treturn t\n}\n\nfunc (t *serial) BuildTree() {\n\tpanic(\"BuildTree() not supported for serial data structure\")\n}\n\nfunc (t *serial) Print() {\n\tpanic(\"Print() not supported for serial data structure\")\n}\n\n\n\n\nfunc (t *serial) Query(from, to int) []Interval {\n\tresult := make([]Interval, 0, 10)\n\tfor _, intrvl := range t.base {\n\t\tif !intrvl.Segment.Disjoint(from, to) {\n\t\t\tresult = append(result, intrvl)\n\t\t}\n\t}\n\treturn result\n}\n\n\nfunc (t *serial) QueryArray(from, to []int) []Interval {\n\tresult := make([]Interval, 0, 10)\n\tfor i, fromvalue := range from {\n\t\tresult = append(result, t.Query(fromvalue, to[i])...)\n\t}\n\treturn result\n}\n\nfunc (t *serial) Tree2Array() []SegmentOverlap ", "output": "{\n\tpanic(\"Tree2Array() not supported for serial data structure\")\n}"} {"input": "package machine\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\nconst ethernetDeviceType = 1\n\ntype MACAddressIdentifier struct {\n\tsysFsDirectory string \n}\n\n\n\nfunc (self MACAddressIdentifier) Identify() ([]byte, error) {\n\tentries, err := ioutil.ReadDir(self.sysFsDirectory)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, e := range entries {\n\t\tif !e.IsDir() {\n\t\t\tcontinue\n\t\t}\n\n\t\tt, err := os.Open(filepath.Join(self.sysFsDirectory, e.Name(), \"type\"))\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tdefer t.Close()\n\n\t\tdeviceType := int32(-1)\n\t\t_, err = fmt.Fscan(t, deviceType)\n\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif deviceType != ethernetDeviceType {\n\t\t\tcontinue\n\t\t}\n\n\t\ta, err := os.Open(filepath.Join(self.sysFsDirectory, e.Name(), \"address\"))\n\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tdefer a.Close()\n\n\t\treturn ioutil.ReadAll(a)\n\t}\n\n\treturn nil, ErrFailedToIdentify\n}\n\nfunc NewMACAddressIdentifier() MACAddressIdentifier ", "output": "{\n\treturn MACAddressIdentifier{\"/sys/class/net\"}\n}"} {"input": "package server\n\nimport (\n\t\"time\"\n\n\t\"golang.org/x/net/context\"\n\n\truntime \"k8s.io/cri-api/pkg/apis/runtime/v1\"\n)\n\n\n\n\n\nfunc (c *criService) ImageFsInfo(ctx context.Context, r *runtime.ImageFsInfoRequest) (*runtime.ImageFsInfoResponse, error) ", "output": "{\n\tsnapshots := c.snapshotStore.List()\n\ttimestamp := time.Now().UnixNano()\n\tvar usedBytes, inodesUsed uint64\n\tfor _, sn := range snapshots {\n\t\tif sn.Timestamp < timestamp {\n\t\t\ttimestamp = sn.Timestamp\n\t\t}\n\t\tusedBytes += sn.Size\n\t\tinodesUsed += sn.Inodes\n\t}\n\treturn &runtime.ImageFsInfoResponse{\n\t\tImageFilesystems: []*runtime.FilesystemUsage{\n\t\t\t{\n\t\t\t\tTimestamp: timestamp,\n\t\t\t\tFsId: &runtime.FilesystemIdentifier{Mountpoint: c.imageFSPath},\n\t\t\t\tUsedBytes: &runtime.UInt64Value{Value: usedBytes},\n\t\t\t\tInodesUsed: &runtime.UInt64Value{Value: inodesUsed},\n\t\t\t},\n\t\t},\n\t}, nil\n}"} {"input": "package fake\n\nimport (\n\tv1 \"github.com/openshift/origin/pkg/sdn/clientset/release_v3_6/typed/sdn/v1\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n\tcore \"k8s.io/kubernetes/pkg/client/testing/core\"\n)\n\ntype FakeSdnV1 struct {\n\t*core.Fake\n}\n\nfunc (c *FakeSdnV1) ClusterNetworks(namespace string) v1.ClusterNetworkInterface {\n\treturn &FakeClusterNetworks{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeSdnV1) RESTClient() restclient.Interface ", "output": "{\n\tvar ret *restclient.RESTClient\n\treturn ret\n}"} {"input": "package iso20022\n\n\ntype Header12 struct {\n\n\tDownloadTransfer *TrueFalseIndicator `xml:\"DwnldTrf\"`\n\n\tFormatVersion *Max6Text `xml:\"FrmtVrsn\"`\n\n\tExchangeIdentification *Max3NumericText `xml:\"XchgId\"`\n\n\tCreationDateTime *ISODateTime `xml:\"CreDtTm\"`\n\n\tInitiatingParty *GenericIdentification53 `xml:\"InitgPty\"`\n\n\tRecipientParty *GenericIdentification53 `xml:\"RcptPty,omitempty\"`\n}\n\nfunc (h *Header12) SetDownloadTransfer(value string) {\n\th.DownloadTransfer = (*TrueFalseIndicator)(&value)\n}\n\nfunc (h *Header12) SetFormatVersion(value string) {\n\th.FormatVersion = (*Max6Text)(&value)\n}\n\nfunc (h *Header12) SetExchangeIdentification(value string) {\n\th.ExchangeIdentification = (*Max3NumericText)(&value)\n}\n\nfunc (h *Header12) SetCreationDateTime(value string) {\n\th.CreationDateTime = (*ISODateTime)(&value)\n}\n\nfunc (h *Header12) AddInitiatingParty() *GenericIdentification53 {\n\th.InitiatingParty = new(GenericIdentification53)\n\treturn h.InitiatingParty\n}\n\n\n\nfunc (h *Header12) AddRecipientParty() *GenericIdentification53 ", "output": "{\n\th.RecipientParty = new(GenericIdentification53)\n\treturn h.RecipientParty\n}"} {"input": "package etcd\n\nimport (\n\t\"strconv\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/meta\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n\t\"k8s.io/kubernetes/pkg/storage\"\n)\n\n\n\ntype APIObjectVersioner struct{}\n\n\n\n\n\nfunc (a APIObjectVersioner) UpdateList(obj runtime.Object, resourceVersion uint64) error {\n\tlistMeta, err := api.ListMetaFor(obj)\n\tif err != nil || listMeta == nil {\n\t\treturn err\n\t}\n\tversionString := \"\"\n\tif resourceVersion != 0 {\n\t\tversionString = strconv.FormatUint(resourceVersion, 10)\n\t}\n\tlistMeta.ResourceVersion = versionString\n\treturn nil\n}\n\n\nfunc (a APIObjectVersioner) ObjectResourceVersion(obj runtime.Object) (uint64, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tversion := accessor.GetResourceVersion()\n\tif len(version) == 0 {\n\t\treturn 0, nil\n\t}\n\treturn strconv.ParseUint(version, 10, 64)\n}\n\n\nvar Versioner storage.Versioner = APIObjectVersioner{}\n\n\n\nfunc (a APIObjectVersioner) CompareResourceVersion(lhs, rhs runtime.Object) int {\n\tlhsVersion, err := Versioner.ObjectResourceVersion(lhs)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trhsVersion, err := Versioner.ObjectResourceVersion(rhs)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif lhsVersion == rhsVersion {\n\t\treturn 0\n\t}\n\tif lhsVersion < rhsVersion {\n\t\treturn -1\n\t}\n\n\treturn 1\n}\n\nfunc (a APIObjectVersioner) UpdateObject(obj runtime.Object, resourceVersion uint64) error ", "output": "{\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tversionString := \"\"\n\tif resourceVersion != 0 {\n\t\tversionString = strconv.FormatUint(resourceVersion, 10)\n\t}\n\taccessor.SetResourceVersion(versionString)\n\treturn nil\n}"} {"input": "package main\nimport (\n\"fmt\"\n\"time\"\n)\n\n\n\nfunc main() {\n go spinner(100*time.Millisecond)\n const n=45\n fibN:=fib(n)\n fmt.Printf(\"\\rFibonacci(%d)=%d\\n\",n,fibN)\n}\n\nfunc spinner(delay time.Duration){\n for{\n for _,r:=range `-\\|/`{\n fmt.Printf(\"\\r%c\",r)\n time.Sleep(delay)\n }\n }\n}\n\nfunc fib(x int) int", "output": "{\n if x<2{\n return x\n }\n return fib(x-1)+fib(x-2)\n}"} {"input": "package pools \n\nimport (\n\t\"bytes\"\n\t\"sync\"\n)\n\n\n\nvar bytesBuffer = sync.Pool{\n\tNew: func() interface{} { return new(bytes.Buffer) },\n}\n\n\n\nfunc BytesBuffer() *bytes.Buffer {\n\tbuf := bytesBuffer.Get().(*bytes.Buffer)\n\tbuf.Reset()\n\treturn buf\n}\n\n\n\n\nfunc PutBuffer(buf *bytes.Buffer) ", "output": "{\n\tbytesBuffer.Put(buf)\n}"} {"input": "package cabf_br\n\n\n\nimport (\n\t\"testing\"\n\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/test\"\n)\n\nfunc TestCertPolicyOvHasCountryOrLocal(t *testing.T) {\n\tinputPath := \"orgValGoodAllFields.pem\"\n\texpected := lint.Pass\n\tout := test.TestLint(\"e_cert_policy_ov_requires_province_or_locality\", inputPath)\n\tif out.Status != expected {\n\t\tt.Errorf(\"%s: expected %s, got %s\", inputPath, expected, out.Status)\n\t}\n}\n\n\n\nfunc TestCertPolicyOvNoCountryOrLocal(t *testing.T) ", "output": "{\n\tinputPath := \"orgValNoProvinceOrLocal.pem\"\n\texpected := lint.Error\n\tout := test.TestLint(\"e_cert_policy_ov_requires_province_or_locality\", inputPath)\n\tif out.Status != expected {\n\t\tt.Errorf(\"%s: expected %s, got %s\", inputPath, expected, out.Status)\n\t}\n}"} {"input": "package restutil\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/eclipse/che/agents/go-agents/core/rest\"\n)\n\n\n\n\n\nfunc ReadJSON(r *http.Request, v interface{}) error {\n\treturn json.NewDecoder(r.Body).Decode(v)\n}\n\n\n\nfunc IntQueryParam(r *http.Request, name string, defaultValue int) int {\n\tqp := r.URL.Query().Get(name)\n\tif qp == \"\" {\n\t\treturn defaultValue\n\t}\n\tv, err := strconv.Atoi(qp)\n\tif err != nil {\n\t\treturn defaultValue\n\t}\n\tif v < 0 {\n\t\treturn defaultValue\n\t}\n\treturn v\n}\n\n\nfunc OKRespondingFunc(w http.ResponseWriter, r *http.Request, _ rest.Params) error {\n\tw.WriteHeader(http.StatusOK)\n\treturn nil\n}\n\nfunc WriteJSON(w http.ResponseWriter, body interface{}) error ", "output": "{\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\treturn json.NewEncoder(w).Encode(body)\n}"} {"input": "package termuiwrapper_test\n\nimport (\n\t\"projectanima/AnimaUtilities/termuiwrapper\"\n\t\"testing\"\n)\n\n\n\nfunc TestProcessUI_Start(t *testing.T) ", "output": "{\n\n\tpUI := termuiwrapper.ProcessUI{}\n\n\terrorFound := pUI.Start()\n\n\tif errorFound != nil {\n\t\tt.Errorf(\"%s; %s\", errorFound.Error(), \"termUI error\")\n\t}\n\n\tdefer pUI.End()\n}"} {"input": "package platform\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os/user\"\n\t\"testing\"\n\n\t\"github.com/jmoiron/sqlx\"\n\n\t\"github.com/tapglue/snaas/platform/pg\"\n)\n\nvar pgTestURL string\n\nfunc TestPostgresPut(t *testing.T) {\n\ttestServicePut(t, preparePostgres)\n}\n\nfunc TestPostgresQuery(t *testing.T) {\n\ttestServiceQuery(t, preparePostgres)\n}\n\n\n\nfunc init() {\n\tu, err := user.Current()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\td := fmt.Sprintf(pg.URLTest, u.Username)\n\n\turl := flag.String(\"postgres.url\", d, \"Postgres test connection URL\")\n\tflag.Parse()\n\n\tpgTestURL = *url\n}\n\nfunc preparePostgres(t *testing.T, namespace string) Service ", "output": "{\n\tdb, err := sqlx.Connect(\"postgres\", pgTestURL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ts := PostgresService(db)\n\n\tif err := s.Teardown(namespace); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treturn s\n}"} {"input": "package models\n\nimport (\n\t\"time\"\n)\n\n\nconst (\n\tVolumePaper = \"paperbook\"\n\tVolumeElectro = \"ebook\"\n\tVolumeAudio = \"audiobook\"\n)\n\n\nfunc GetVolumes() []string {\n\tvolumes := []string{VolumeAudio, VolumeElectro, VolumePaper}\n\treturn volumes\n}\n\n\nfunc CheckVolume(volume string) bool {\n\tswitch volume {\n\tcase VolumePaper:\n\tcase VolumeElectro:\n\tcase VolumeAudio:\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}\n\n\n\n\n\ntype Volume struct {\n\tID int32 `reform:\"id,pk\"`\n\tBookID int32 `reform:\"book_id\"`\n\tType string `reform:\"type\"`\n\tCreatedAt time.Time `reform:\"created_at\"`\n\tUpdatedAt time.Time `reform:\"updated_at\"`\n}\n\n\nfunc (v *Volume) BeforeInsert() error {\n\tv.CreatedAt = time.Now().UTC().Truncate(time.Second)\n\tv.UpdatedAt = v.CreatedAt\n\treturn nil\n}\n\n\n\n\nfunc (v *Volume) BeforeUpdate() error ", "output": "{\n\tv.UpdatedAt = time.Now().UTC().Truncate(time.Second)\n\treturn nil\n}"} {"input": "package http_auth\n\nimport \"crypto/rand\"\nimport \"fmt\"\nimport \"sync\"\nimport \"time\"\n\ntype Server struct {\n\tsync.Mutex\n\tAuthFun func(user, realm string) string\n\topaque string\n\tRealm string\n\tReaperWaitSeconds, ReapTTLSeconds int\n\trequests map[string]*reqState\n}\ntype reqState struct {\n\tnreq int\n\tsectime int64\n}\n\nfunc newServer(realm string, authfun func(user, realm string) string) *Server {\n\ts := new(Server)\n\ts.Realm = realm\n\ts.opaque = newNonce()\n\ts.AuthFun = authfun\n\ts.requests = map[string]*reqState{}\n\ts.ReaperWaitSeconds = 600\n\ts.ReapTTLSeconds = 3600\n\tgo reaper(s)\n\n\treturn s\n}\n\nfunc newNonce() string {\n\tb := make([]byte, 8)\n\tn, e := rand.Read(b)\n\tif n != 8 || e != nil {\n\t\tpanic(\"rand.Reader failed!\")\n\t}\n\treturn fmt.Sprintf(\"%x\", b)\n}\n\nfunc reaper(s *Server) {\n\tfor {\n\t\ttime.Sleep(time.Duration(s.ReaperWaitSeconds) * time.Second)\n\t\tdo_reap(s)\n\t}\n}\n\n\n\nfunc do_reap(s *Server) ", "output": "{\n\tnow := time.Now().UnixNano()\n\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tfor k, v := range s.requests {\n\t\tif v.sectime+int64(s.ReapTTLSeconds) < now {\n\t\t\tdelete(s.requests, k)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"crypto/sha1\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n)\n\n\n\nfunc main() {\n\thtmlfile := os.Args[len(os.Args)-1]\n\tif htmlfile == \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"no html file specified\")\n\t\tos.Exit(1)\n\t}\n\n\tparts := strings.Split(htmlfile, \".\")\n\tgofile := parts[0] + \"_\" + parts[1] + \".go\"\n\n\tin, err := os.Open(htmlfile)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"open htmlfile: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tdefer in.Close()\n\n\tout, err := os.Create(gofile)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"create go file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tdefer func() {\n\t\tif err := out.Close(); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"close: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\tfmt.Fprintf(out, \"package main\\n\\n\")\n\tfmt.Fprintf(out, \"const %s_etag = \\\"%s\\\"\\n\\n\", parts[0], filehash(htmlfile))\n\tfmt.Fprintf(out, \"const %s_html = `\", parts[0])\n\n\tif _, err := io.Copy(out, in); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"io copy: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Fprintf(out, \"`\\n\")\n}\n\nfunc filehash(filename string) string ", "output": "{\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"open for hash: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tdefer f.Close()\n\n\th := sha1.New()\n\tif _, err := io.Copy(h, f); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"io copy for hash: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}"} {"input": "package mem\n\nimport (\n\t\"runtime\"\n\t\"time\"\n)\n\n\n\nvar historicUsage *Usage\n\n\n\nconst memUsageMeasureInterval = 5 * time.Second\n\n\n\nfunc init() {\n\thistoricUsage = &Usage{}\n\tvar cycles uint64\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(memUsageMeasureInterval)\n\t\t\tcurrUsage := GetUsage()\n\t\t\tcurrSum := cycles * historicUsage.Mem\n\t\t\tcycles = cycles + 1\n\t\t\thistoricUsage.Mem = (currSum + currUsage.Mem) / cycles\n\t\t}\n\t}()\n}\n\n\ntype Usage struct {\n\tMem uint64 `json:\"mem\"`\n\tError string `json:\"error,omitempty\"`\n}\n\n\n\nfunc GetHistoricUsage() Usage {\n\treturn *historicUsage\n}\n\n\n\n\n\nfunc GetUsage() Usage ", "output": "{\n\tmemStats := new(runtime.MemStats)\n\truntime.ReadMemStats(memStats)\n\treturn Usage{\n\t\tMem: memStats.Sys,\n\t}\n}"} {"input": "package ray\n\nimport (\n\t\"github.com/v2ray/v2ray-core/common/alloc\"\n)\n\nconst (\n\tbufferSize = 16\n)\n\n\nfunc NewRay() Ray {\n\treturn &directRay{\n\t\tInput: make(chan *alloc.Buffer, bufferSize),\n\t\tOutput: make(chan *alloc.Buffer, bufferSize),\n\t}\n}\n\ntype directRay struct {\n\tInput chan *alloc.Buffer\n\tOutput chan *alloc.Buffer\n}\n\nfunc (this *directRay) OutboundInput() <-chan *alloc.Buffer {\n\treturn this.Input\n}\n\nfunc (this *directRay) OutboundOutput() chan<- *alloc.Buffer {\n\treturn this.Output\n}\n\nfunc (this *directRay) InboundInput() chan<- *alloc.Buffer {\n\treturn this.Input\n}\n\n\n\nfunc (this *directRay) InboundOutput() <-chan *alloc.Buffer ", "output": "{\n\treturn this.Output\n}"} {"input": "package fakes\n\nimport (\n\tboshas \"github.com/cloudfoundry/bosh-agent/agent/applier/applyspec\"\n\t\"github.com/cloudfoundry/bosh-agent/agent/applier/models\"\n)\n\ntype FakeApplier struct {\n\tPrepared bool\n\tPrepareDesiredApplySpec boshas.ApplySpec\n\tPrepareError error\n\n\tApplied bool\n\tApplyCurrentApplySpec boshas.ApplySpec\n\tApplyDesiredApplySpec boshas.ApplySpec\n\tApplyError error\n\n\tConfigured bool\n\tConfiguredDesiredApplySpec boshas.ApplySpec\n\tConfiguredJobs []models.Job\n\tConfiguredError error\n}\n\nfunc NewFakeApplier() *FakeApplier {\n\treturn &FakeApplier{}\n}\n\nfunc (s *FakeApplier) Prepare(desiredApplySpec boshas.ApplySpec) error {\n\ts.Prepared = true\n\ts.PrepareDesiredApplySpec = desiredApplySpec\n\treturn s.PrepareError\n}\n\n\n\nfunc (s *FakeApplier) Apply(currentApplySpec, desiredApplySpec boshas.ApplySpec) error {\n\ts.Applied = true\n\ts.ApplyCurrentApplySpec = currentApplySpec\n\ts.ApplyDesiredApplySpec = desiredApplySpec\n\treturn s.ApplyError\n}\n\nfunc (s *FakeApplier) ConfigureJobs(desiredApplySpec boshas.ApplySpec) error ", "output": "{\n\ts.Configured = true\n\ts.ConfiguredDesiredApplySpec = desiredApplySpec\n\treturn s.ConfiguredError\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"github.com/spf13/cobra\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\n\nvar execCmd = &cobra.Command{\n\tUse: \"exec \",\n\tShort: \"Run any command inside a running container\",\n\tLong: `Execute commands inside one of the containers running in your docker-compose defined cluster.\ni/e \"dcmd exec rails c\" will translate in \"docker exec -it rails c\n`,\n\tRun: invokeCommand,\n}\n\n\n\nfunc dockerExec(containerName string, command []string) {\n\tres := fmt.Sprintf(\"docker exec -it %v %s\", containerName, strings.Join(command, \" \"))\n\tfmt.Printf(\"Executing: \\\"%s\\\"\\n\", res)\n\n\texpandedCommand := strings.Split(res, \" \")\n\tcmd := exec.Command(expandedCommand[0], expandedCommand[1:]...)\n\n\tcmd.Stdout = os.Stdout\n\tcmd.Stdin = os.Stdin\n\tcmd.Stderr = os.Stderr\n\n\terr := cmd.Run()\n\n\tif err != nil {\n\t\tlog.Fatal(`Error executing the command`)\n\t}\n}\n\nfunc init() {\n\tRootCmd.AddCommand(execCmd)\n\n\n\n\n}\n\nfunc invokeCommand(cmd *cobra.Command, args []string) ", "output": "{\n\tif len(args) == 0 {\n\t\tcmd.Usage()\n\t\tos.Exit(1)\n\t}\n\tcontainer := chooseContainer()\n\tdockerExec(container, args)\n}"} {"input": "package internalversion\n\nimport (\n\tapiextensions \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype CustomResourceDefinitionLister interface {\n\tList(selector labels.Selector) (ret []*apiextensions.CustomResourceDefinition, err error)\n\tGet(name string) (*apiextensions.CustomResourceDefinition, error)\n\tCustomResourceDefinitionListerExpansion\n}\n\n\ntype customResourceDefinitionLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewCustomResourceDefinitionLister(indexer cache.Indexer) CustomResourceDefinitionLister {\n\treturn &customResourceDefinitionLister{indexer: indexer}\n}\n\n\n\n\n\nfunc (s *customResourceDefinitionLister) Get(name string) (*apiextensions.CustomResourceDefinition, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(apiextensions.Resource(\"customresourcedefinition\"), name)\n\t}\n\treturn obj.(*apiextensions.CustomResourceDefinition), nil\n}\n\nfunc (s *customResourceDefinitionLister) List(selector labels.Selector) (ret []*apiextensions.CustomResourceDefinition, err error) ", "output": "{\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*apiextensions.CustomResourceDefinition))\n\t})\n\treturn ret, err\n}"} {"input": "package refund\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/issue9/wechat/pay\"\n)\n\n\ntype Refund struct {\n\tPay *pay.Pay\n\tDeviceInfo string \n\tSignType string \n\tRefundFeeType string \n\tOpUserID string \n\tRefundAccount string \n}\n\nfunc (r *Refund) params(outRefundNO, outTradeNO, transactionID string, totalFee, refundFee int) map[string]string {\n\treturn map[string]string{\n\t\t\"device_info\": r.DeviceInfo,\n\t\t\"sign_type\": r.SignType,\n\t\t\"out_trade_no\": outTradeNO,\n\t\t\"transaction_id\": transactionID,\n\t\t\"out_refund_no\": outRefundNO,\n\t\t\"total_fee\": strconv.Itoa(totalFee),\n\t\t\"refund_fee\": strconv.Itoa(refundFee),\n\t\t\"refund_fee_type\": r.RefundFeeType,\n\t\t\"op_user_id\": r.OpUserID,\n\t\t\"refund_account\": r.RefundAccount,\n\t}\n}\n\n\n\n\n\nfunc (r *Refund) TransactionID(outRefundNO, transactionID string, totalFee, refundFee int) (*Return, error) {\n\tparams := r.params(outRefundNO, \"\", transactionID, totalFee, refundFee)\n\treturn r.refund(params)\n}\n\nfunc (r *Refund) refund(params map[string]string) (*Return, error) {\n\tmaps, err := r.Pay.Refund(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = r.Pay.ValidateAll(r.SignType, maps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newReturn(maps)\n}\n\nfunc (r *Refund) OutTradeNO(outRefundNO, outTradeNO string, totalFee, refundFee int) (*Return, error) ", "output": "{\n\tparams := r.params(outRefundNO, outTradeNO, \"\", totalFee, refundFee)\n\treturn r.refund(params)\n}"} {"input": "package logutils\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestLogutils(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Logutils Suite\")\n}"} {"input": "package errors\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\ntype testWrapped struct {\n\terror\n}\n\nfunc (w *testWrapped) Error() string {\n\tif w.error == nil {\n\t\treturn \"wrapped: nil\"\n\t}\n\treturn fmt.Sprintf(\"wrapped: %v\", w.error.Error())\n}\n\n\n\nfunc testWrap(err error) error {\n\treturn &testWrapped{err}\n}\n\nfunc TestWrapped(t *testing.T) {\n\tt.Parallel()\n\n\tConvey(`Test Wrapped`, t, func() {\n\t\tConvey(`A nil error`, func() {\n\t\t\tvar err error\n\n\t\t\tConvey(`Unwraps to nil.`, func() {\n\t\t\t\tSo(Unwrap(err), ShouldBeNil)\n\t\t\t})\n\n\t\t\tConvey(`When wrapped, does not unwrap to nil.`, func() {\n\t\t\t\tSo(Unwrap(testWrap(err)), ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\n\t\tConvey(`A non-wrapped error.`, func() {\n\t\t\terr := New(\"test error\")\n\n\t\t\tConvey(`Unwraps to itself.`, func() {\n\t\t\t\tSo(Unwrap(err), ShouldEqual, err)\n\t\t\t})\n\n\t\t\tConvey(`When wrapped, unwraps to itself.`, func() {\n\t\t\t\tSo(Unwrap(testWrap(err)), ShouldEqual, err)\n\t\t\t})\n\n\t\t\tConvey(`When double-wrapped, unwraps to itself.`, func() {\n\t\t\t\tSo(Unwrap(testWrap(testWrap(err))), ShouldEqual, err)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc (w *testWrapped) Unwrap() error ", "output": "{\n\treturn w.error\n}"} {"input": "package resource\n\nimport (\n\t\"github.com/gbl08ma/sqalx\"\n\t\"github.com/yarf-framework/yarf\"\n)\n\n\ntype AuthTest struct {\n\tresource\n}\n\n\n\n\n\nfunc (r *AuthTest) WithHashKey(key []byte) *AuthTest {\n\tr.hashKey = key\n\treturn r\n}\n\n\nfunc (r *AuthTest) Get(c *yarf.Context) error {\n\tpair, err := r.AuthenticateClient(c)\n\tif err != nil {\n\t\tRenderUnauthorized(c)\n\t\treturn nil\n\t}\n\n\tRenderData(c, struct {\n\t\tResult string `msgpack:\"result\" json:\"result\"`\n\t\tKey string `msgpack:\"key\" json:\"key\"`\n\t}{\n\t\tResult: \"ok\",\n\t\tKey: pair.Key,\n\t}, \"no-cache, no-store, must-revalidate\")\n\treturn nil\n}\n\nfunc (r *AuthTest) WithNode(node sqalx.Node) *AuthTest ", "output": "{\n\tr.node = node\n\treturn r\n}"} {"input": "package fake\n\nimport (\n\tv1 \"github.com/openshift/origin/pkg/authorization/client/clientset_generated/release_v1_4/typed/core/v1\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n\tcore \"k8s.io/kubernetes/pkg/client/testing/core\"\n)\n\ntype FakeCore struct {\n\t*core.Fake\n}\n\nfunc (c *FakeCore) Policies(namespace string) v1.PolicyInterface {\n\treturn &FakePolicies{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeCore) GetRESTClient() *restclient.RESTClient ", "output": "{\n\treturn nil\n}"} {"input": "package util\n\nimport \"os/exec\"\n\n\n\ntype binRunner func(string, ...string) ([]byte, error)\n\n\n\nfunc defaultBinRunner(bin string, args ...string) ([]byte, error) {\n\treturn exec.Command(bin, args...).CombinedOutput()\n}\n\n\n\ntype Permissions struct {\n\tbinRunner binRunner\n}\n\n\n\n\n\n\n\n\nfunc (p *Permissions) IsAdmin() (bool, error) {\n\treturn p.isAdmin()\n}\n\nfunc NewPermissions() *Permissions ", "output": "{\n\treturn &Permissions{\n\t\tbinRunner: defaultBinRunner,\n\t}\n}"} {"input": "package vsphere\n\nimport (\n\t\"fmt\"\n)\n\nconst BuilderId = \"packer.post-processor.vsphere\"\n\ntype Artifact struct {\n\tfiles []string\n\tdatastore string\n\tvmfolder string\n\tvmname string\n}\n\nfunc NewArtifact(datastore, vmfolder, vmname string, files []string) *Artifact {\n\treturn &Artifact{\n\t\tfiles: files,\n\t\tdatastore: datastore,\n\t\tvmfolder: vmfolder,\n\t\tvmname: vmname,\n\t}\n}\n\nfunc (*Artifact) BuilderId() string {\n\treturn BuilderId\n}\n\nfunc (a *Artifact) Files() []string {\n\treturn a.files\n}\n\n\n\nfunc (a *Artifact) String() string {\n\treturn fmt.Sprintf(\"VM: %s Folder: %s Datastore: %s\", a.vmname, a.vmfolder, a.datastore)\n}\n\nfunc (*Artifact) State(name string) interface{} {\n\treturn nil\n}\n\nfunc (a *Artifact) Destroy() error {\n\treturn nil\n}\n\nfunc (a *Artifact) Id() string ", "output": "{\n\treturn fmt.Sprintf(\"%s::%s::%s\", a.datastore, a.vmfolder, a.vmname)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Cpu struct {\n\tSeconds time.Duration \n}\n\nfunc newCpu(p Packet) (Action, error) {\n\tc := Cpu{}\n\n\tif p.Cmd != \"cpu\" {\n\t\treturn c, fmt.Errorf(\"wrong command for type MemUp\")\n\t}\n\n\ti, err := strconv.Atoi(p.Arg)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\n\tif i < 1 {\n\t\treturn c, fmt.Errorf(\"cpu seconds argument must be greater than 0\")\n\t}\n\n\tc.Seconds = time.Duration(i) * time.Second\n\n\treturn c, nil\n}\n\n\n\nfunc (c Cpu) act(dng *danger) error {\n\n\tncpus := runtime.GOMAXPROCS(-1)\n\tngos := 4 * ncpus\n\n\tdone := make(chan struct{})\n\tdefer close(done)\n\n\tburner := func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tfor j := 0; j < 100000; j++ {\n\t\t\t\t\tfor i := range []int{1, 2, 3, 4, 5, 6, 7, 8} {\n\t\t\t\t\t\tfact(i)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := 0; i < ngos; i++ {\n\t\tgo burner()\n\t}\n\n\ttime.Sleep(c.Seconds)\n\treturn nil\n}\n\nfunc fact(n int) int ", "output": "{\n\tif n == 0 {\n\t\treturn 1\n\t}\n\treturn n * fact(n-1)\n}"} {"input": "package fake\n\nimport (\n\tv1alpha1 \"github.com/appscode/searchlight/client/clientset/versioned/typed/incidents/v1alpha1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeIncidentsV1alpha1 struct {\n\t*testing.Fake\n}\n\n\n\n\n\nfunc (c *FakeIncidentsV1alpha1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeIncidentsV1alpha1) Acknowledgements(namespace string) v1alpha1.AcknowledgementInterface ", "output": "{\n\treturn &FakeAcknowledgements{c, namespace}\n}"} {"input": "package dosingdecision\n\nimport (\n\t\"time\"\n\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tCarbohydratesOnBoardAmountMaximum = 1000\n\tCarbohydratesOnBoardAmountMinimum = 0\n)\n\ntype CarbohydratesOnBoard struct {\n\tTime *time.Time `json:\"time,omitempty\" bson:\"time,omitempty\"`\n\tAmount *float64 `json:\"amount,omitempty\" bson:\"amount,omitempty\"`\n}\n\nfunc ParseCarbohydratesOnBoard(parser structure.ObjectParser) *CarbohydratesOnBoard {\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewCarbohydratesOnBoard()\n\tparser.Parse(datum)\n\treturn datum\n}\n\n\n\nfunc (c *CarbohydratesOnBoard) Parse(parser structure.ObjectParser) {\n\tc.Time = parser.Time(\"time\", time.RFC3339Nano)\n\tc.Amount = parser.Float64(\"amount\")\n}\n\nfunc (c *CarbohydratesOnBoard) Validate(validator structure.Validator) {\n\tvalidator.Float64(\"amount\", c.Amount).Exists().InRange(CarbohydratesOnBoardAmountMinimum, CarbohydratesOnBoardAmountMaximum)\n}\n\nfunc NewCarbohydratesOnBoard() *CarbohydratesOnBoard ", "output": "{\n\treturn &CarbohydratesOnBoard{}\n}"} {"input": "package clients\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n\n\t\"github.com/VolantMQ/volantmq/subscriber\"\n)\n\nvar subCount int32 = 0\n\n\n\ntype container struct {\n\tlock sync.Mutex\n\trmLock sync.RWMutex\n\tses *session\n\texpiry atomic.Value\n\tsub *subscriber.Type\n\tremovable bool\n\tremoved bool\n}\n\nfunc (s *container) setRemovable(rm bool) {\n\ts.rmLock.Lock()\n\ts.removable = rm\n\ts.rmLock.Unlock()\n}\n\nfunc (s *container) acquire() {\n\ts.lock.Lock()\n}\n\nfunc (s *container) release() {\n\ts.lock.Unlock()\n}\n\n\n\nfunc (s *container) swap(from *container) *container {\n\ts.ses = from.ses\n\n\ts.ses.idLock = &s.lock\n\n\treturn s\n}\n\nfunc (s *container) subscriber(cleanStart bool, c subscriber.Config) *subscriber.Type {\n\tif cleanStart && s.sub != nil {\n\t\ts.sub.Offline(true)\n\t\ts.sub = nil\n\t}\n\n\tif s.sub == nil {\n\t\ts.sub = subscriber.New(c)\n\t}\n\n\treturn s.sub\n}\n\nfunc (s *container) session() *session ", "output": "{\n\tdefer s.rmLock.Unlock()\n\ts.rmLock.Lock()\n\treturn s.ses\n}"} {"input": "package models\n\nimport (\n\t\"net\"\n\t\"time\"\n\n\t\"github.com/golang-jwt/jwt/v4\"\n\t\"github.com/google/uuid\"\n)\n\n\nfunc NewIdentityVerification(jti uuid.UUID, username, action string, ip net.IP) (verification IdentityVerification) {\n\treturn IdentityVerification{\n\t\tJTI: jti,\n\t\tIssuedAt: time.Now(),\n\t\tExpiresAt: time.Now().Add(5 * time.Minute),\n\t\tAction: action,\n\t\tUsername: username,\n\t\tIssuedIP: NewIP(ip),\n\t}\n}\n\n\ntype IdentityVerification struct {\n\tID int `db:\"id\"`\n\tJTI uuid.UUID `db:\"jti\"`\n\tIssuedAt time.Time `db:\"iat\"`\n\tIssuedIP IP `db:\"issued_ip\"`\n\tExpiresAt time.Time `db:\"exp\"`\n\tAction string `db:\"action\"`\n\tUsername string `db:\"username\"`\n\tConsumed *time.Time `db:\"consumed\"`\n\tConsumedIP NullIP `db:\"consumed_ip\"`\n}\n\n\nfunc (v IdentityVerification) ToIdentityVerificationClaim() (claim *IdentityVerificationClaim) {\n\treturn &IdentityVerificationClaim{\n\t\tRegisteredClaims: jwt.RegisteredClaims{\n\t\t\tID: v.JTI.String(),\n\t\t\tIssuer: \"Authelia\",\n\t\t\tIssuedAt: jwt.NewNumericDate(v.IssuedAt),\n\t\t\tExpiresAt: jwt.NewNumericDate(v.ExpiresAt),\n\t\t},\n\t\tAction: v.Action,\n\t\tUsername: v.Username,\n\t}\n}\n\n\n\ntype IdentityVerificationClaim struct {\n\tjwt.RegisteredClaims\n\n\tAction string `json:\"action\"`\n\tUsername string `json:\"username\"`\n}\n\n\n\n\nfunc (v IdentityVerificationClaim) ToIdentityVerification() (verification *IdentityVerification, err error) ", "output": "{\n\tjti, err := uuid.Parse(v.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &IdentityVerification{\n\t\tJTI: jti,\n\t\tUsername: v.Username,\n\t\tAction: v.Action,\n\t\tExpiresAt: v.ExpiresAt.Time,\n\t}, nil\n}"} {"input": "package vanity\n\nimport (\n\t\"github.com/gogo/protobuf/gogoproto\"\n\t\"github.com/gogo/protobuf/proto\"\n\tdescriptor \"github.com/gogo/protobuf/protoc-gen-gogo/descriptor\"\n)\n\nfunc FieldHasBoolExtension(field *descriptor.FieldDescriptorProto, extension *proto.ExtensionDesc) bool {\n\tif field.Options == nil {\n\t\treturn false\n\t}\n\tvalue, err := proto.GetExtension(field.Options, extension)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif value == nil {\n\t\treturn false\n\t}\n\tif value.(*bool) == nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc SetBoolFieldOption(extension *proto.ExtensionDesc, value bool) func(field *descriptor.FieldDescriptorProto) {\n\treturn func(field *descriptor.FieldDescriptorProto) {\n\t\tif FieldHasBoolExtension(field, extension) {\n\t\t\treturn\n\t\t}\n\t\tif field.Options == nil {\n\t\t\tfield.Options = &descriptor.FieldOptions{}\n\t\t}\n\t\tif err := proto.SetExtension(field.Options, extension, &value); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\n\n\nfunc TurnOffNullableForNativeTypesWithoutDefaultsOnly(field *descriptor.FieldDescriptorProto) {\n\tif field.IsRepeated() || field.IsMessage() {\n\t\treturn\n\t}\n\tif field.DefaultValue != nil {\n\t\treturn\n\t}\n\tSetBoolFieldOption(gogoproto.E_Nullable, false)(field)\n}\n\nfunc TurnOffNullable(field *descriptor.FieldDescriptorProto) ", "output": "{\n\tif field.IsRepeated() && !field.IsMessage() {\n\t\treturn\n\t}\n\tSetBoolFieldOption(gogoproto.E_Nullable, false)(field)\n}"} {"input": "package db_models\n\nimport \"time\"\nimport \"github.com/go-xorm/xorm\"\n\ntype UriFilteringTelemetryPreMitigation struct {\n\tId int64 `xorm:\"'id' pk autoincr\"`\n\tCustomerId int `xorm:\"'customer_id' not null\"`\n\tCuid string `xorm:\"'cuid' not null\"`\n\tCdid string `xorm:\"'cdid'\"`\n\tTmid int `xorm:\"'tmid' not null\"`\n\tTargetPrefix string `xorm:\"target_prefix\"`\n\tLowerPort int `xorm:\"lower_port\"`\n\tUpperPort int `xorm:\"upper_port\"`\n\tTargetProtocol int `xorm:\"target_protocol\"`\n\tTargetFqdn string `xorm:\"target_fqdn\"`\n\tAliasName string `xorm:\"alias_name\"`\n\tCreated time.Time `xorm:\"created\"`\n\tUpdated time.Time `xorm:\"updated\"`\n}\n\n\nfunc GetUriFilteringTelemetryPreMitigationByTmid(engine *xorm.Engine, customerId int, cuid string, tmid int) ([]UriFilteringTelemetryPreMitigation, error) {\n\ttelePreMitigation := []UriFilteringTelemetryPreMitigation{}\n\terr := engine.Where(\"customer_id = ? AND cuid = ? AND tmid = ?\", customerId, cuid, tmid).Find(&telePreMitigation)\n\treturn telePreMitigation, err\n}\n\n\n\n\n\nfunc DeleteUriFilteringTelemetryPreMitigationByTmid(session *xorm.Session, tmid int) (err error) {\n\t_, err = session.Delete(&UriFilteringTelemetryPreMitigation{Tmid: tmid})\n\treturn\n}\n\nfunc GetUriFilteringTelemetryPreMitigationByCuid(engine *xorm.Engine, customerId int, cuid string) ([]UriFilteringTelemetryPreMitigation, error) ", "output": "{\n\ttelePreMitigation := []UriFilteringTelemetryPreMitigation{}\n\terr := engine.Where(\"customer_id = ? AND cuid = ?\", customerId, cuid).Find(&telePreMitigation)\n\treturn telePreMitigation, err\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"camlistore.org/pkg/blobref\"\n\t\"camlistore.org/pkg/cmdmain\"\n)\n\ntype removeCmd struct{}\n\nfunc init() {\n\tcmdmain.RegisterCommand(\"remove\", func(flags *flag.FlagSet) cmdmain.CommandRunner {\n\t\tcmd := new(removeCmd)\n\t\treturn cmd\n\t})\n}\n\n\n\nfunc (c *removeCmd) RunCommand(args []string) error {\n\tif len(args) == 0 {\n\t\treturn cmdmain.ErrUsage\n\t}\n\treturn getUploader().RemoveBlobs(blobref.ParseMulti(args))\n}\n\nfunc (c *removeCmd) Usage() ", "output": "{\n\tfmt.Fprintf(cmdmain.Stderr, `Usage: camput remove \n\nThis command is for debugging only. You're not expected to use it in practice.\n`)\n}"} {"input": "package main\n\ntype Element struct {\n\tValue interface{}\n\tnext *Element\n}\n\ntype List struct {\n\te Element\n\tsize int\n}\n\n\nfunc New() *List {\n\tl := new(List)\n l.e.next = &l.e\n l.size = 0\n\treturn l\n}\n\n\n\nfunc (l *List) Remove() *Element {\n\n}\n\nfunc (l *List) Size() int {\n\treturn l.size\n}\n\nfunc main() {\n}\n\nfunc (l *List) Add(e, at *Element) *Element ", "output": "{\n l.e.Value == at.Value\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst letterBytes = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst lenLetters = len(letterBytes)\n\nfunc init() {\n\trand.Seed(time.Now().UnixNano())\n}\n\nfunc randStr(n int) string {\n\tb := make([]byte, n)\n\tfor i := range b {\n\t\tb[i] = letterBytes[rand.Int63()%int64(len(letterBytes))]\n\t}\n\treturn string(b)\n}\n\n\n\nfunc sendOk(w http.ResponseWriter, data interface{}) {\n\tjson.NewEncoder(w).Encode(data)\n}\n\nfunc sendError(w http.ResponseWriter, msg string) {\n\tdata := struct {\n\t\tOk bool `json:\"ok\"`\n\t\tMsg string `json:\"msg\"`\n\t}{\n\t\tOk: false,\n\t\tMsg: msg,\n\t}\n\n\tsendJson(w, data)\n}\n\nfunc sendJson(w http.ResponseWriter, data interface{}) ", "output": "{\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(data)\n}"} {"input": "package value\n\nimport (\n\t\"bytes\"\n)\n\n\n\n\n\nfunc Cons(x, y Value) *Cell {\n\treturn &Cell{Car: x, Cdr: y}\n}\n\n\ntype Cell struct {\n\tCar Value\n\tCdr Value\n}\n\n\n\n\nfunc (c *Cell) Equal(cmp Value) Value {\n\tx, ok := cmp.(*Cell)\n\tif !ok {\n\t\treturn NIL\n\t}\n\n\tif c.Car.Equal(x.Car) != T {\n\t\treturn NIL\n\t}\n\tif c.Cdr.Equal(x.Cdr) != T {\n\t\treturn NIL\n\t}\n\treturn T\n}\n\nfunc (c *Cell) String() string {\n\tvar buf bytes.Buffer\n\n\tbuf.WriteByte('(')\n\tfor {\n\t\tbuf.WriteString(c.Car.String())\n\n\t\tif c.Cdr == NIL {\n\t\t\tbreak\n\t\t}\n\n\t\tcdr, ok := c.Cdr.(*Cell)\n\t\tif !ok {\n\t\t\tbuf.WriteString(\" . \")\n\t\t\tbuf.WriteString(c.Cdr.String())\n\t\t\tbreak\n\t\t}\n\t\tc = cdr \n\n\t\tbuf.WriteByte(' ')\n\t}\n\tbuf.WriteByte(')')\n\n\treturn buf.String()\n}\n\nfunc (c *Cell) Walk(fn func(Value)) ", "output": "{\n\tcur := c\n\tfor {\n\t\tfn(cur.Car)\n\n\t\tif cur.Cdr == NIL {\n\t\t\treturn\n\t\t}\n\n\t\tnext, ok := cur.Cdr.(*Cell)\n\t\tif !ok {\n\t\t\tErrorf(\"cannot evaluate an improper list: %s\", c)\n\t\t}\n\t\tcur = next\n\t}\n}"} {"input": "package secret\n\nconst (\n\tAdminserverUser = \"harbor-adminserver\"\n\tJobserviceUser = \"harbor-jobservice\"\n\tUIUser = \"harbor-ui\"\n)\n\n\ntype Store struct {\n\tsecrets map[string]string\n}\n\n\n\n\n\nfunc (s *Store) IsValid(secret string) bool {\n\treturn len(s.GetUsername(secret)) != 0\n}\n\n\nfunc (s *Store) GetUsername(secret string) string {\n\treturn s.secrets[secret]\n}\n\nfunc NewStore(secrets map[string]string) *Store ", "output": "{\n\treturn &Store{\n\t\tsecrets: secrets,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/russmack/statemachiner\"\n)\n\n\nfunc main() {\n\ts := statemachiner.NewStateMachine()\n\ts.StartState = dispenseDogBiscuits\n\tc := NewHome()\n\ts.Start(c)\n}\n\n\ntype Home struct {\n\tDispenseDogBiscuits int `json:\"dispense_dog_biscuits\"`\n\tTotalDogBiscuits int `json:\"dog_biscuits\"`\n\tLights bool `json:\"lights\"`\n\tKettle bool `json:\"kettle\"`\n\tVacuumRoom string `json:\"vacuum_room\"`\n}\n\n\nfunc NewHome() *Home {\n\treturn &Home{}\n}\n\n\n\nfunc dispenseDogBiscuits(cargo interface{}) statemachiner.StateFn {\n\tcargo.(*Home).DispenseDogBiscuits = 10\n\tcargo.(*Home).TotalDogBiscuits += cargo.(*Home).DispenseDogBiscuits\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn lights\n}\n\n\nfunc lights(cargo interface{}) statemachiner.StateFn {\n\tcargo.(*Home).Lights = true\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn kettle\n}\n\n\n\n\n\nfunc vacuumRoom(cargo interface{}) statemachiner.StateFn {\n\tif cargo.(*Home).TotalDogBiscuits < 20 {\n\t\treturn dispenseDogBiscuits\n\t} else {\n\t\tcargo.(*Home).VacuumRoom = \"kitchen\"\n\t}\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn nil\n}\n\nfunc kettle(cargo interface{}) statemachiner.StateFn ", "output": "{\n\tcargo.(*Home).Kettle = true\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn vacuumRoom\n}"} {"input": "package goku\n\nimport (\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype TestReader struct{}\n\n\n\ntype TestWriter struct {\n\tmsgs []Message\n}\n\nfunc (self *TestWriter) Write(msgs []Message) error {\n\tfor _, msg := range msgs {\n\t\tself.msgs = append(self.msgs, msg)\n\t}\n\treturn nil\n}\n\nfunc TestNewQueueSetupReader(t *testing.T) {\n\tt.Parallel()\n\n\tq := NewQueue(&TestReader{}, nil)\n\n\tselect {\n\tcase <-q.Sender():\n\t\tbreak\n\tcase <-time.After(100 * time.Millisecond):\n\t\tt.Fatal(\"Timeout expired\")\n\t}\n}\n\nfunc TestNewQueueSetsupWriter(t *testing.T) {\n\tt.Parallel()\n\n\twriter := &TestWriter{}\n\tq := NewQueue(nil, writer)\n\n\tq.Receiver() <- \"Hello\"\n\tq.Receiver() <- \"World\"\n\n\truntime.Gosched()\n\n\tif count := len(writer.msgs); count != 2 {\n\t\tt.Errorf(\"messages written == %d, want 2\", count)\n\t}\n}\n\nfunc (self TestReader) Read() ([]Message, error) ", "output": "{\n\ttime.Sleep(10 * time.Millisecond)\n\treturn []Message{\"Hello\"}, nil\n}"} {"input": "package fifo\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\n\n\n\nfunc CreateAndRead(path string) (func() (io.ReadCloser, error), error) {\n\tif err := mkfifo(path, 0600); err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating fifo %v: %v\", path, err)\n\t}\n\n\treturn func() (io.ReadCloser, error) {\n\t\treturn OpenReader(path)\n\t}, nil\n}\n\nfunc OpenReader(path string) (io.ReadCloser, error) {\n\treturn os.OpenFile(path, unix.O_RDONLY, os.ModeNamedPipe)\n}\n\n\nfunc OpenWriter(path string) (io.WriteCloser, error) {\n\treturn os.OpenFile(path, unix.O_WRONLY, os.ModeNamedPipe)\n}\n\n\nfunc Remove(path string) error {\n\treturn os.Remove(path)\n}\n\n\n\nfunc mkfifo(path string, mode uint32) (err error) {\n\treturn unix.Mkfifo(path, mode)\n}\n\nfunc IsClosedErr(err error) bool ", "output": "{\n\terr2, ok := err.(*os.PathError)\n\tif ok {\n\t\treturn err2.Err == os.ErrClosed\n\t}\n\treturn false\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\tosexec \"os/exec\"\n\t\"path/filepath\"\n)\n\n\nfunc exec(args ...string) error {\n\tcmd := osexec.Command(args[0], args[1:]...)\n\tout, err := cmd.CombinedOutput()\n\tswitch err := err.(type) {\n\tcase nil:\n\t\treturn nil\n\tcase *osexec.ExitError:\n\t\treturn fmt.Errorf(\"failed to run %q:\\n%v\", args, string(out))\n\tdefault:\n\t\treturn err\n\t}\n}\n\n\nfunc execVerbose(args ...string) error {\n\tcmd := osexec.Command(args[0], args[1:]...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}\n\n\nfunc execCompose(dir string, args ...string) error {\n\treturn exec(append(\n\t\t[]string{\"docker-compose\", \"--ansi=never\", \"-f\", filepath.Join(dir, \"docker-compose.yml\")},\n\t\targs...)...)\n}\n\n\n\n\n\nfunc execDocker(args ...string) error {\n\treturn exec(append([]string{\"docker\"}, args...)...)\n}\n\nfunc execComposeVerbose(dir string, args ...string) error ", "output": "{\n\treturn execVerbose(append(\n\t\t[]string{\"docker-compose\", \"--ansi=never\", \"-f\", filepath.Join(dir, \"docker-compose.yml\")},\n\t\targs...)...)\n}"} {"input": "package storagedatalake\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultDNSSuffix = \"dfs.core.windows.net\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tXMsVersion string\n\tAccountName string\n\tDNSSuffix string\n}\n\n\n\n\n\nfunc NewWithoutDefaults(xMsVersion string, accountName string, dNSSuffix string) BaseClient {\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tXMsVersion: xMsVersion,\n\t\tAccountName: accountName,\n\t\tDNSSuffix: dNSSuffix,\n\t}\n}\n\nfunc New(xMsVersion string, accountName string) BaseClient ", "output": "{\n\treturn NewWithoutDefaults(xMsVersion, accountName, DefaultDNSSuffix)\n}"} {"input": "package vm\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc newStack() *stack {\n\treturn &stack{}\n}\n\ntype stack struct {\n\tdata []*big.Int\n\tptr int\n}\n\nfunc (st *stack) push(d *big.Int) {\n\tstackItem := new(big.Int).Set(d)\n\tif len(st.data) > st.ptr {\n\t\tst.data[st.ptr] = stackItem\n\t} else {\n\t\tst.data = append(st.data, stackItem)\n\t}\n\tst.ptr++\n}\n\nfunc (st *stack) pop() (ret *big.Int) {\n\tst.ptr--\n\tret = st.data[st.ptr]\n\treturn\n}\n\nfunc (st *stack) len() int {\n\treturn st.ptr\n}\n\nfunc (st *stack) swap(n int) {\n\tst.data[st.len()-n], st.data[st.len()-1] = st.data[st.len()-1], st.data[st.len()-n]\n}\n\nfunc (st *stack) dup(n int) {\n\tst.push(st.data[st.len()-n])\n}\n\nfunc (st *stack) peek() *big.Int {\n\treturn st.data[st.len()-1]\n}\n\n\n\nfunc (st *stack) Print() {\n\tfmt.Println(\"### stack ###\")\n\tif len(st.data) > 0 {\n\t\tfor i, val := range st.data {\n\t\t\tfmt.Printf(\"%-3d %v\\n\", i, val)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"-- empty --\")\n\t}\n\tfmt.Println(\"#############\")\n}\n\nfunc (st *stack) require(n int) error ", "output": "{\n\tif st.len() < n {\n\t\treturn fmt.Errorf(\"stack underflow (%d <=> %d)\", len(st.data), n)\n\t}\n\treturn nil\n}"} {"input": "package common\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\ntype NodeMetastate struct {\n\n\tLedgerHeight uint64\n}\n\n\nfunc NewNodeMetastate(height uint64) *NodeMetastate {\n\treturn &NodeMetastate{height}\n}\n\n\nfunc (n *NodeMetastate) Bytes() ([]byte, error) {\n\tbuffer := new(bytes.Buffer)\n\terr := binary.Write(buffer, binary.BigEndian, *n)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn buffer.Bytes(), nil\n}\n\n\nfunc (n *NodeMetastate) Height() uint64 {\n\treturn n.LedgerHeight\n}\n\n\nfunc (n *NodeMetastate) Update(height uint64) {\n\tn.LedgerHeight = height\n}\n\n\n\n\nfunc FromBytes(buf []byte) (*NodeMetastate, error) ", "output": "{\n\tstate := NodeMetastate{}\n\treader := bytes.NewReader(buf)\n\terr := binary.Read(reader, binary.BigEndian, &state)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn &state, nil\n}"} {"input": "package transfer\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/inverse-inc/packetfence/go/coredns/plugin/pkg/rcode\"\n\n\t\"github.com/miekg/dns\"\n)\n\n\n\n\n\nfunc sendNotify(c *dns.Client, m *dns.Msg, s string) error {\n\tvar err error\n\n\tcode := dns.RcodeServerFailure\n\tfor i := 0; i < 3; i++ {\n\t\tret, _, err := c.Exchange(m, s)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tcode = ret.Rcode\n\t\tif code == dns.RcodeSuccess {\n\t\t\treturn nil\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"notify for zone %q was not accepted by %q: %q\", m.Question[0].Name, s, err)\n\t}\n\treturn fmt.Errorf(\"notify for zone %q was not accepted by %q: rcode was %q\", m.Question[0].Name, s, rcode.ToString(code))\n}\n\nfunc (t *Transfer) Notify(zone string) error ", "output": "{\n\tif t == nil { \n\t\treturn nil\n\t}\n\n\tm := new(dns.Msg)\n\tm.SetNotify(zone)\n\tc := new(dns.Client)\n\n\tx := longestMatch(t.xfrs, zone)\n\tif x == nil {\n\t\treturn fmt.Errorf(\"no such zone registred in the transfer plugin: %s\", zone)\n\t}\n\n\tvar err1 error\n\tfor _, t := range x.to {\n\t\tif t == \"*\" {\n\t\t\tcontinue\n\t\t}\n\t\tif err := sendNotify(c, m, t); err != nil {\n\t\t\terr1 = err\n\t\t}\n\t}\n\tlog.Debugf(\"Sent notifies for zone %q to %v\", zone, x.to)\n\treturn err1 \n}"} {"input": "package cmd\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc GetErrorMessage(err error) string {\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\treturn \"\"\n}\n\n\n\nfunc TestExecuteClienAddCmd(t *testing.T) ", "output": "{\n\tassert.Nil(t, nil)\n}"} {"input": "package store\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype Row struct {\n\tData []string\n}\n\nfunc ReadData(path string) []byte {\n\td, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn []byte(``)\n\t}\n\n\treturn d\n}\n\nfunc ReadRows(path, delimiter string) *[]Row {\n\tf, _ := os.Open(path)\n\n\tdefer f.Close()\n\n\trows := []Row{}\n\ts := bufio.NewScanner(f)\n\ts.Split(bufio.ScanLines)\n\n\tfor s.Scan() {\n\t\tdata := strings.Split(s.Text(), delimiter)\n\t\tr := &Row{Data: data}\n\t\trows = append(rows, *r)\n\t}\n\n\treturn &rows\n}\n\nfunc WriteData(path string, data []byte) {\n\tf, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer f.Close()\n\n\t_, err = f.Write(data)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n\n\n\nfunc WriteRows(path string, rows *[]Row, delimeter string) ", "output": "{\n\tf, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0644)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer f.Close()\n\n\tfor _, r := range *rows {\n\t\t_, err = f.WriteString(strings.Join(r.Data, delimeter))\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n}"} {"input": "package service\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\n\nfunc TestAllGroup(t *testing.T) ", "output": "{\n\tConvey(\"TestAllGroup \", t, func() {\n\t\tcard, err := s.AllGroup(c, 1)\n\t\tt.Logf(\"v(%v)\", card)\n\t\tSo(err, ShouldBeNil)\n\t})\n}"} {"input": "package loggo\n\nvar (\n\tdefaultContext = newDefaultContxt()\n)\n\n\n\n\nfunc DefaultContext() *Context {\n\treturn defaultContext\n}\n\n\n\n\n\nfunc LoggerInfo() string {\n\treturn defaultContext.Config().String()\n}\n\n\n\nfunc GetLogger(name string, size ...int) Logger {\n\treturn defaultContext.GetLogger(name, size...)\n}\n\n\n\n\n\nfunc ResetLogging() {\n\tdefaultContext.ResetLoggerLevels()\n\tdefaultContext.ResetWriters()\n}\n\n\nfunc ResetWriters() {\n\tdefaultContext.ResetWriters()\n}\n\n\n\n\nfunc ReplaceDefaultWriter(writer Writer) (Writer, error) {\n\treturn defaultContext.ReplaceWriter(DefaultWriterName, writer)\n}\n\n\n\n\nfunc RegisterWriter(name string, writer Writer) error {\n\treturn defaultContext.AddWriter(name, writer)\n}\n\n\n\nfunc RemoveWriter(name string) (Writer, error) {\n\treturn defaultContext.RemoveWriter(name)\n}\n\n\n\n\n\n\n\n\n\n\nfunc ConfigureLoggers(specification string) error {\n\tconfig, err := ParseConfigString(specification)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefaultContext.ApplyConfig(config)\n\treturn nil\n}\n\nfunc newDefaultContxt() *Context ", "output": "{\n\tctx := NewContext(WARNING)\n\tctx.AddWriter(DefaultWriterName, defaultWriter())\n\treturn ctx\n}"} {"input": "package v1alpha1\n\nimport (\n\t\"context\"\n\n\t\"k8s.io/apimachinery/pkg/api/equality\"\n\n\t\"knative.dev/pkg/apis\"\n\t\"knative.dev/serving/pkg/apis/serving\"\n)\n\n\nfunc (c *Configuration) Validate(ctx context.Context) (errs *apis.FieldError) {\n\tif !apis.IsInStatusUpdate(ctx) {\n\t\terrs = errs.Also(serving.ValidateObjectMetadata(ctx, c.GetObjectMeta()).ViaField(\"metadata\"))\n\t\tctx = apis.WithinParent(ctx, c.ObjectMeta)\n\t\terrs = errs.Also(c.Spec.Validate(apis.WithinSpec(ctx)).ViaField(\"spec\"))\n\t}\n\n\tif apis.IsInUpdate(ctx) {\n\t\toriginal := apis.GetBaseline(ctx).(*Configuration)\n\t\tif c.GetOwnerReferences() == nil {\n\t\t\terrs = errs.Also(apis.ValidateCreatorAndModifier(original.Spec, c.Spec, original.GetAnnotations(),\n\t\t\t\tc.GetAnnotations(), serving.GroupName).ViaField(\"metadata.annotations\"))\n\t\t}\n\t\terr := c.Spec.GetTemplate().VerifyNameChange(ctx,\n\t\t\toriginal.Spec.GetTemplate())\n\t\terrs = errs.Also(err.ViaField(\"spec.revisionTemplate\"))\n\t}\n\n\treturn errs\n}\n\n\n\n\nfunc (cs *ConfigurationSpec) Validate(ctx context.Context) *apis.FieldError ", "output": "{\n\tif equality.Semantic.DeepEqual(cs, &ConfigurationSpec{}) {\n\t\treturn apis.ErrMissingField(apis.CurrentField)\n\t}\n\n\terrs := apis.CheckDeprecated(ctx, cs)\n\n\tvar templateField string\n\tswitch {\n\tcase cs.DeprecatedRevisionTemplate != nil && cs.Template != nil:\n\t\treturn apis.ErrMultipleOneOf(\"revisionTemplate\", \"template\")\n\tcase cs.DeprecatedRevisionTemplate != nil:\n\t\ttemplateField = \"revisionTemplate\"\n\tcase cs.Template != nil:\n\t\ttemplateField = \"template\"\n\t\tctx = apis.DisallowDeprecated(ctx)\n\tdefault:\n\t\treturn apis.ErrMissingOneOf(\"revisionTemplate\", \"template\")\n\t}\n\n\treturn errs.Also(cs.GetTemplate().Validate(ctx).ViaField(templateField))\n}"} {"input": "package example\n\nimport (\n\t\"testing\"\n\t\"github.com/remogatto/prettytest\"\n\t\"launchpad.net/gocheck\"\n)\n\n\n\ntype testSuite struct {\n\tprettytest.Suite\n}\n\nfunc TestRunner(t *testing.T) {\n\tprettytest.Run(\n\t\tt,\n\t\tnew(testSuite),\n\t)\n}\n\n\n\n\n\n\nfunc (t *testSuite) TestTrueIsTrue() {\n\tt.True(true)\n}\n\nfunc (t *testSuite) TestEquality() {\n\tt.Equal(\"awesome\", \"awesome\")\n}\n\nfunc (t *testSuite) TestNot() {\n\tt.Not(t.Path(\"foo\"))\n}\n\n\n\n\n\nfunc (t *testSuite) TestMustFail() {\n\tt.Error(\"This test must fail.\")\n\tt.MustFail()\n}\n\nfunc (t *testSuite) TestInequality() {\n\tt.Equal(\"awesome\", \"ugly\")\n\tt.MustFail()\n}\n\nfunc (t *testSuite) TestGoCheck() ", "output": "{\n\tt.Check(\"foo\", gocheck.Equals, \"foo\")\n}"} {"input": "package ini\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype WalkFunc func(section, name, value []byte) error\n\n\nfunc Walk(r io.Reader, walkFn WalkFunc) error {\n\tvar section []byte\n\tsep := []byte{'='}\n\n\tscanner := bufio.NewScanner(r)\n\tfor lineNo := 1; scanner.Scan(); lineNo++ {\n\t\tline := bytes.TrimSpace(scanner.Bytes())\n\t\tif len(line) == 0 || line[0] == '#' || line[0] == ';' {\n\t\t\tcontinue\n\t\t}\n\t\tif line[0] == '[' && line[len(line)-1] == ']' {\n\t\t\tsection = duplicate(section, bytes.TrimSpace(line[1:len(line)-1]))\n\t\t\tcontinue\n\t\t}\n\t\tif line[len(line)-1] == '\\\\' {\n\t\t\tline = append([]byte(nil), line[:len(line)-1]...)\n\n\t\t\tfor scanner.Scan() {\n\t\t\t\tlineNo++\n\t\t\t\tl := bytes.TrimSpace(scanner.Bytes())\n\t\t\t\tif l[len(l)-1] == '\\\\' {\n\t\t\t\t\tline = append(line, l[:len(l)-1]...)\n\t\t\t\t} else {\n\t\t\t\t\tline = append(line, l...)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ti := bytes.Index(line, sep)\n\t\tif i < 0 {\n\t\t\treturn fmt.Errorf(\"missing delimiter (line %d)\", lineNo)\n\t\t}\n\t\tname := bytes.TrimSpace(line[:i])\n\t\tif len(name) == 0 {\n\t\t\treturn fmt.Errorf(\"empty name (line %d)\", lineNo)\n\t\t}\n\t\tvalue := bytes.TrimSpace(line[i+1:])\n\t\terr := walkFn(section, name, value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc duplicate(dest, src []byte) []byte ", "output": "{\n\tif cap(dest) < len(src) {\n\t\treturn append([]byte(nil), src...)\n\t}\n\tdest = dest[:len(src)]\n\tcopy(dest, src)\n\treturn dest\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype OpenpitrixRepoEvent struct {\n\n\tCreateTime strfmt.DateTime `json:\"create_time,omitempty\"`\n\n\tOwner string `json:\"owner,omitempty\"`\n\n\tOwnerPath string `json:\"owner_path,omitempty\"`\n\n\tRepoEventID string `json:\"repo_event_id,omitempty\"`\n\n\tRepoID string `json:\"repo_id,omitempty\"`\n\n\tResult string `json:\"result,omitempty\"`\n\n\tStatus string `json:\"status,omitempty\"`\n\n\tStatusTime strfmt.DateTime `json:\"status_time,omitempty\"`\n}\n\n\nfunc (m *OpenpitrixRepoEvent) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\nfunc (m *OpenpitrixRepoEvent) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\n\n\nfunc (m *OpenpitrixRepoEvent) UnmarshalBinary(b []byte) error ", "output": "{\n\tvar res OpenpitrixRepoEvent\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}"} {"input": "package resource\n\nimport \"github.com/docker/infrakit/pkg/spi/resource\"\n\n\ntype Plugin struct {\n\n\tDoCommit func(spec resource.Spec, pretend bool) (string, error)\n\n\tDoDestroy func(spec resource.Spec, pretend bool) (string, error)\n\n\tDoDescribeResources func(spec resource.Spec) (string, error)\n}\n\n\nfunc (t *Plugin) Commit(spec resource.Spec, pretend bool) (string, error) {\n\treturn t.DoCommit(spec, pretend)\n}\n\n\nfunc (t *Plugin) Destroy(spec resource.Spec, pretend bool) (string, error) {\n\treturn t.DoDestroy(spec, pretend)\n}\n\n\n\n\nfunc (t *Plugin) DescribeResources(spec resource.Spec) (string, error) ", "output": "{\n\treturn t.DoDescribeResources(spec)\n}"} {"input": "package core\n\nimport \"go/ast\"\n\n\n\nfunc resolveAssign(n *ast.AssignStmt, c *Context) bool {\n\tfor _, arg := range n.Rhs {\n\t\tif !TryResolve(arg, c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc resolveCompLit(n *ast.CompositeLit, c *Context) bool {\n\tfor _, arg := range n.Elts {\n\t\tif !TryResolve(arg, c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc resolveBinExpr(n *ast.BinaryExpr, c *Context) bool {\n\treturn (TryResolve(n.X, c) && TryResolve(n.Y, c))\n}\n\nfunc resolveCallExpr(n *ast.CallExpr, c *Context) bool {\n\treturn false\n}\n\n\n\n\nfunc TryResolve(n ast.Node, c *Context) bool {\n\tswitch node := n.(type) {\n\tcase *ast.BasicLit:\n\t\treturn true\n\n\tcase *ast.CompositeLit:\n\t\treturn resolveCompLit(node, c)\n\n\tcase *ast.Ident:\n\t\treturn resolveIdent(node, c)\n\n\tcase *ast.AssignStmt:\n\t\treturn resolveAssign(node, c)\n\n\tcase *ast.CallExpr:\n\t\treturn resolveCallExpr(node, c)\n\n\tcase *ast.BinaryExpr:\n\t\treturn resolveBinExpr(node, c)\n\t}\n\n\treturn false\n}\n\nfunc resolveIdent(n *ast.Ident, c *Context) bool ", "output": "{\n\tif n.Obj == nil || n.Obj.Kind != ast.Var {\n\t\treturn true\n\t}\n\tif node, ok := n.Obj.Decl.(ast.Node); ok {\n\t\treturn TryResolve(node, c)\n\t}\n\treturn false\n}"} {"input": "package operator\n\nimport (\n\t\"testing\"\n\n\t\"github.com/rook/rook/pkg/operator/test\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\nfunc TestCreateCluster(t *testing.T) {\n\tclientset := test.New(3)\n\to := New(\"foo\", nil, clientset)\n\to.context.RetryDelay = 1\n\n\terr := o.initResources()\n\tassert.NotNil(t, err)\n\n\ttest := &testTPR{}\n\terr = createTPR(o.context, test)\n\tassert.Nil(t, err)\n\ttpr, err := clientset.ExtensionsV1beta1().ThirdPartyResources().List(v1.ListOptions{})\n\tassert.Nil(t, err)\n\tassert.Equal(t, 1, len(tpr.Items))\n\tassert.Equal(t, \"test.rook.io\", tpr.Items[0].Name)\n\tassert.Equal(t, test.Description(), tpr.Items[0].Description)\n\n}\n\ntype testTPR struct {\n}\n\nfunc (t *testTPR) Name() string {\n\treturn \"test\"\n}\nfunc (t *testTPR) Description() string {\n\treturn \"test description\"\n}\n\nfunc (t *testTPR) Watch() error {\n\treturn nil\n}\n\nfunc (t *testTPR) Load() error ", "output": "{\n\treturn nil\n}"} {"input": "package vfs\n\nimport (\n\t\"path\"\n\n\tgofig \"github.com/akutz/gofig/types\"\n\n\t\"github.com/codedellemc/rexray/libstorage/api/context\"\n\t\"github.com/codedellemc/rexray/libstorage/api/registry\"\n\t\"github.com/codedellemc/rexray/libstorage/api/types\"\n)\n\nconst (\n\tName = \"vfs\"\n)\n\nfunc init() {\n\tregistry.RegisterConfigReg(\n\t\t\"VFS\",\n\t\tfunc(ctx types.Context, r gofig.ConfigRegistration) {\n\t\t\tvfsRoot := path.Join(context.MustPathConfig(ctx).Lib, \"vfs\")\n\t\t\tr.Key(\n\t\t\t\tgofig.String,\n\t\t\t\t\"\",\n\t\t\t\tvfsRoot,\n\t\t\t\t\"\",\n\t\t\t\t\"vfs.root\")\n\t\t})\n}\n\n\nfunc RootDir(config gofig.Config) string {\n\treturn config.GetString(\"vfs.root\")\n}\n\n\n\n\n\nfunc VolumesDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"vol\")\n}\n\n\nfunc SnapshotsDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"snap\")\n}\n\nfunc DeviceFilePath(config gofig.Config) string ", "output": "{\n\treturn path.Join(RootDir(config), \"dev\")\n}"} {"input": "package core\n\ntype Context interface {\n\tCid() int\n}\n\ntype context int\n\nvar __cid int = 100\n\nfunc NewContext() Context {\n\tv := context(__cid)\n\t__cid++\n\treturn v\n}\n\n\n\nfunc (v context) Cid() int ", "output": "{\n\treturn int(v)\n}"} {"input": "package utils\n\nimport \"sync\"\n\ntype queueNode struct {\n\tdata interface{}\n\tnext *queueNode\n}\n\ntype queue struct {\n\thead *queueNode\n\ttail *queueNode\n\tcount int\n\tlock *sync.Mutex\n}\n\nfunc NewQueue() *queue {\n\treturn &queue{lock: &sync.Mutex{}}\n}\n\nfunc (q *queue) Len() int {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\treturn q.count\n}\n\nfunc (q *queue) Push(v interface{}) {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tnode := &queueNode{data: v}\n\n\tif q.tail == nil {\n\t\tq.tail = node\n\t\tq.head = node\n\t} else {\n\t\tq.tail.next = node\n\t\tq.tail = node\n\t}\n\n\tq.count++\n}\n\n\n\nfunc (q *queue) Peek() interface{} {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tnode := q.head\n\tif node == nil || node.data == nil {\n\t\treturn nil\n\t}\n\n\treturn node.data\n}\n\nfunc (q *queue) Pop() interface{} ", "output": "{\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tif q.head == nil {\n\t\treturn nil\n\t}\n\n\tnode := q.head\n\tq.head = node.next\n\n\tif q.head == nil {\n\t\tq.tail = nil\n\t}\n\n\tq.count--\n\n\treturn node.data\n}"} {"input": "package corehttp\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\n\tcore \"github.com/ipfs/go-ipfs/core\"\n\tlogging \"github.com/ipfs/go-ipfs/vendor/QmQg1J6vikuXF9oDvm4wpdeAUvvkVEKW1EYDw9HhTMnP2b/go-log\"\n)\n\ntype writeErrNotifier struct {\n\tw io.Writer\n\terrs chan error\n}\n\nfunc newWriteErrNotifier(w io.Writer) (io.WriteCloser, <-chan error) {\n\tch := make(chan error, 1)\n\treturn &writeErrNotifier{\n\t\tw: w,\n\t\terrs: ch,\n\t}, ch\n}\n\n\n\nfunc (w *writeErrNotifier) Close() error {\n\tselect {\n\tcase w.errs <- io.EOF:\n\tdefault:\n\t}\n\treturn nil\n}\n\nfunc LogOption() ServeOption {\n\treturn func(n *core.IpfsNode, _ net.Listener, mux *http.ServeMux) (*http.ServeMux, error) {\n\t\tmux.HandleFunc(\"/logs\", func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.WriteHeader(200)\n\t\t\twnf, errs := newWriteErrNotifier(w)\n\t\t\tlogging.WriterGroup.AddWriter(wnf)\n\t\t\tlog.Event(n.Context(), \"log API client connected\")\n\t\t\t<-errs\n\t\t})\n\t\treturn mux, nil\n\t}\n}\n\nfunc (w *writeErrNotifier) Write(b []byte) (int, error) ", "output": "{\n\tn, err := w.w.Write(b)\n\tif err != nil {\n\t\tselect {\n\t\tcase w.errs <- err:\n\t\tdefault:\n\t\t}\n\t}\n\tif f, ok := w.w.(http.Flusher); ok {\n\t\tf.Flush()\n\t}\n\treturn n, err\n}"} {"input": "package store\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\n\t\"gopkg.in/oauth2.v3\"\n)\n\n\n\n\ntype ClientStore struct {\n\tsync.RWMutex\n\tdata map[string]oauth2.ClientInfo\n}\n\n\nfunc (cs *ClientStore) GetByID(id string) (cli oauth2.ClientInfo, err error) {\n\tcs.RLock()\n\tdefer cs.RUnlock()\n\tif c, ok := cs.data[id]; ok {\n\t\tcli = c\n\t\treturn\n\t}\n\terr = errors.New(\"not found\")\n\treturn\n}\n\n\nfunc (cs *ClientStore) Set(id string, cli oauth2.ClientInfo) (err error) {\n\tcs.Lock()\n\tdefer cs.Unlock()\n\tcs.data[id] = cli\n\treturn\n}\n\nfunc NewClientStore() *ClientStore ", "output": "{\n\treturn &ClientStore{\n\t\tdata: make(map[string]oauth2.ClientInfo),\n\t}\n}"} {"input": "package term\n\nimport (\n\t\"github.com/lmorg/murex/lang/stdio\"\n\t\"github.com/lmorg/murex/utils\"\n)\n\n\n\n\ntype Err struct {\n\tterm\n}\n\n\nfunc (t *Err) Write(b []byte) (int, error) {\n\tt.mutex.Lock()\n\tt.bWritten += uint64(len(b))\n\tt.mutex.Unlock()\n\n\tvtermWrite([]rune(string(b)))\n\n\treturn len(b), nil\n}\n\n\n\n\n\nfunc (t *Err) WriteArray(dataType string) (stdio.ArrayWriter, error) {\n\treturn stdio.WriteArray(t, dataType)\n}\n\nfunc (t *Err) Writeln(b []byte) (int, error) ", "output": "{\n\treturn t.Write(appendBytes(b, utils.NewLineByte...))\n}"} {"input": "package pusher\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"strings\"\n)\n\nfunc hmacSignature(toSign, secret string) string {\n\treturn hex.EncodeToString(hmacBytes([]byte(toSign), []byte(secret)))\n}\n\nfunc hmacBytes(toSign, secret []byte) []byte {\n\t_authSignature := hmac.New(sha256.New, secret)\n\t_authSignature.Write(toSign)\n\treturn _authSignature.Sum(nil)\n}\n\n\n\nfunc createAuthString(key, secret, stringToSign string) string ", "output": "{\n\tauthSignature := hmacSignature(stringToSign, secret)\n\treturn strings.Join([]string{key, authSignature}, \":\")\n}"} {"input": "package cli\n\nimport \"errors\"\nimport \"fmt\"\nimport \"strconv\"\n\n\n\nfunc GetArgBool(args []string, s string)(bool) {\n pos, err := getArgPos(args, s)\n if nil == err && pos > 0 {\n return true\n }\n\n return false\n}\n\nfunc GetArgInt(args []string, s string)(int, error) {\n \n pos, err := getArgPos(args, s)\n if nil != err || pos <= 0{\n return pos, err\n }\n\n \n if pos + 1 >= len(args) {\n return 0, errors.New(fmt.Sprintf(\"no number fallows '%s'\", s))\n }\n\n \n a := args[pos + 1]\n if regd == true && On != RegArgsStat(a) {\n return 0, errors.New(fmt.Sprintf(\"no number fallows '%s'\", s))\n }\n\n return strconv.Atoi(a)\n}\n\nfunc GetArgInts(args []string, s string)([]int, error) {\n pos, err := getArgPos(args, s)\n if err != nil || pos <= 0{\n return nil, err\n }\n if pos + 1 >= len(args) {\n return nil, errors.New(fmt.Sprintf(\"no number fllows '%s'\", s))\n }\n var list []int\n for i := pos + 1; i < len(args); i++ {\n if On == argmp[args[i]] {\n break\n }\n n, err := strconv.Atoi(args[i])\n if nil == err {\n list = append(list, n)\n } else {\n break\n }\n }\n if len(list) < 1 {\n return nil, errors.New(fmt.Sprintf(\"no number fllows '%s'\", s))\n }\n\n return list, nil\n}\n\nfunc IsArgExist(args []string, s string)(bool) ", "output": "{\n pos, err := getArgPos(args, s)\n if nil == err && pos > 0 {\n return true\n }\n\n return false\n}"} {"input": "package file\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/openshift/source-to-image/pkg/api\"\n\t\"github.com/openshift/source-to-image/pkg/scm/git\"\n\ttestfs \"github.com/openshift/source-to-image/pkg/test/fs\"\n)\n\nfunc TestDownload(t *testing.T) {\n\tfs := &testfs.FakeFileSystem{}\n\tf := &File{fs}\n\n\tconfig := &api.Config{\n\t\tSource: git.MustParse(\"/foo\"),\n\t}\n\tinfo, err := f.Download(config)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error %v\", err)\n\t}\n\tif fs.CopySource != \"/foo\" {\n\t\tt.Errorf(\"Unexpected fs.CopySource %s\", fs.CopySource)\n\t}\n\tif info.Location != config.Source.URL.Path || info.ContextDir != config.ContextDir {\n\t\tt.Errorf(\"Unexpected info\")\n\t}\n}\n\n\n\nfunc TestDownloadWithContext(t *testing.T) ", "output": "{\n\tfs := &testfs.FakeFileSystem{}\n\tf := &File{fs}\n\n\tconfig := &api.Config{\n\t\tSource: git.MustParse(\"/foo\"),\n\t\tContextDir: \"bar\",\n\t}\n\tinfo, err := f.Download(config)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error %v\", err)\n\t}\n\tif filepath.ToSlash(fs.CopySource) != \"/foo/bar\" {\n\t\tt.Errorf(\"Unexpected fs.CopySource %s\", fs.CopySource)\n\t}\n\tif info.Location != config.Source.URL.Path || info.ContextDir != config.ContextDir {\n\t\tt.Errorf(\"Unexpected info\")\n\t}\n}"} {"input": "package tempconv\n\n\n\nfunc FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }\n\nfunc CToF(c Celsius) Fahrenheit ", "output": "{ return Fahrenheit(c*9/5 + 32) }"} {"input": "package problem0137\n\n\n\nfunc singleNumber(nums []int) int ", "output": "{\n\tvar ans int32\n\tfor i := 0; i < 32; i++ {\n\t\tcnt := 0\n\t\tfor _, num := range nums {\n\t\t\tif (num & (1 << uint(i))) > 0 {\n\t\t\t\tcnt++\n\t\t\t}\n\t\t}\n\t\tif cnt%3 == 1 {\n\t\t\tans |= 1 << uint(i)\n\t\t}\n\t}\n\n\treturn int(ans)\n}"} {"input": "package client\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\n\nfunc (cli *Client) VolumeInspectWithRaw(ctx context.Context, volumeID string) (types.Volume, []byte, error) {\n\tvar volume types.Volume\n\tresp, err := cli.get(ctx, \"/volumes/\"+volumeID, nil, nil)\n\tif err != nil {\n\t\tif resp.statusCode == http.StatusNotFound {\n\t\t\treturn volume, nil, volumeNotFoundError{volumeID}\n\t\t}\n\t\treturn volume, nil, err\n\t}\n\tdefer ensureReaderClosed(resp)\n\n\tbody, err := ioutil.ReadAll(resp.body)\n\tif err != nil {\n\t\treturn volume, nil, err\n\t}\n\trdr := bytes.NewReader(body)\n\terr = json.NewDecoder(rdr).Decode(&volume)\n\treturn volume, body, err\n}\n\nfunc (cli *Client) VolumeInspect(ctx context.Context, volumeID string) (types.Volume, error) ", "output": "{\n\tvolume, _, err := cli.VolumeInspectWithRaw(ctx, volumeID)\n\treturn volume, err\n}"} {"input": "package internal\n\nimport (\n\t\"bytes\"\n\t\"time\"\n)\n\n\nfunc (e *ErrorEvent) MarshalJSON() ([]byte, error) {\n\tbuf := bytes.NewBuffer(make([]byte, 0, 256))\n\n\te.WriteJSON(buf)\n\n\treturn buf.Bytes(), nil\n}\n\n\n\n\n\ntype errorEvents struct {\n\tevents *analyticsEvents\n}\n\nfunc newErrorEvents(max int) *errorEvents {\n\treturn &errorEvents{\n\t\tevents: newAnalyticsEvents(max),\n\t}\n}\n\nfunc (events *errorEvents) Add(e *ErrorEvent, priority Priority) {\n\tevents.events.addEvent(analyticsEvent{priority, e})\n}\n\nfunc (events *errorEvents) MergeIntoHarvest(h *Harvest) {\n\th.ErrorEvents.events.mergeFailed(events.events)\n}\n\nfunc (events *errorEvents) Data(agentRunID string, harvestStart time.Time) ([]byte, error) {\n\treturn events.events.CollectorJSON(agentRunID)\n}\n\nfunc (events *errorEvents) numSeen() float64 { return events.events.NumSeen() }\nfunc (events *errorEvents) numSaved() float64 { return events.events.NumSaved() }\n\nfunc (events *errorEvents) EndpointMethod() string {\n\treturn cmdErrorEvents\n}\n\nfunc (e *ErrorEvent) WriteJSON(buf *bytes.Buffer) ", "output": "{\n\tw := jsonFieldsWriter{buf: buf}\n\tbuf.WriteByte('[')\n\tbuf.WriteByte('{')\n\tw.stringField(\"type\", \"TransactionError\")\n\tw.stringField(\"error.class\", e.Klass)\n\tw.stringField(\"error.message\", e.Msg)\n\tw.floatField(\"timestamp\", timeToFloatSeconds(e.When))\n\tw.stringField(\"transactionName\", e.FinalName)\n\n\tsharedTransactionIntrinsics(&e.TxnEvent, &w)\n\tsharedBetterCATIntrinsics(&e.TxnEvent, &w)\n\n\tbuf.WriteByte('}')\n\tbuf.WriteByte(',')\n\tuserAttributesJSON(e.Attrs, buf, destError, e.ErrorData.ExtraAttributes)\n\tbuf.WriteByte(',')\n\tagentAttributesJSON(e.Attrs, buf, destError)\n\tbuf.WriteByte(']')\n}"} {"input": "package metrics\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\ntype GaugeMetric struct {\n\tvalue float64\n\tmutex sync.RWMutex\n}\n\n\n\nfunc (metric *GaugeMetric) Set(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value = value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) IncrementBy(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value += value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Increment() float64 {\n\treturn metric.IncrementBy(1)\n}\n\nfunc (metric *GaugeMetric) DecrementBy(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value -= value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Decrement() float64 {\n\treturn metric.DecrementBy(1)\n}\n\nfunc (metric *GaugeMetric) Get() float64 {\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Marshallable() map[string]interface{} {\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\tv := make(map[string]interface{}, 2)\n\n\tv[valueKey] = metric.value\n\tv[typeKey] = gaugeTypeValue\n\n\treturn v\n}\n\nfunc (metric *GaugeMetric) Humanize() string ", "output": "{\n\tformatString := \"[GaugeMetric; value=%f]\"\n\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn fmt.Sprintf(formatString, metric.value)\n}"} {"input": "package config\n\nimport \"github.com/corestoreio/csfw/utils\"\n\n\n\ntype ScopePerm uint64\n\n\nvar ScopePermAll = ScopePerm(1<> ((i - 1) * 8)) & 0xff)\n\t}\n\treturn mk.hash\n}\n\nfunc newMockHashKey(key int64) *mockCacheKey {\n\treturn &mockCacheKey{\n\t\tkey: key,\n\t}\n}\n\n\n\nfunc getRandomString(l int) string ", "output": "{\n\tstr := \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\tbytes := []byte(str)\n\tresult := []byte{}\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tfor i := 0; i < l; i++ {\n\t\tresult = append(result, bytes[r.Intn(len(bytes))])\n\t}\n\treturn string(result)\n}"} {"input": "package enmime\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/cention-sany/mime\"\n)\n\n\n\n\n\n\n\n\n\n\nfunc DecodeHeader(input string) string {\n\tif !strings.Contains(input, \"=?\") {\n\t\treturn input\n\t}\n\n\tdec := new(mime.WordDecoder)\n\tdec.CharsetReader = NewCharsetReader\n\theader, err := dec.DecodeHeader(input)\n\tif err != nil {\n\t\treturn input\n\t}\n\treturn header\n}\n\n\nfunc DecodeToUTF8Base64Header(input string) string {\n\tif !strings.Contains(input, \"=?\") {\n\t\treturn input\n\t}\n\n\tdebug(\"input = %q\", input)\n\ttokens := strings.FieldsFunc(input, isWhiteSpaceRune)\n\toutput := make([]string, len(tokens), len(tokens))\n\tfor i, token := range tokens {\n\t\tif len(token) > 4 && strings.Contains(token, \"=?\") {\n\t\t\tprefix := \"\"\n\t\t\tsuffix := \"\"\n\t\t\tif token[0] == '(' {\n\t\t\t\tprefix = \"(\"\n\t\t\t\ttoken = token[1:]\n\t\t\t}\n\t\t\tif token[len(token)-1] == ')' {\n\t\t\t\tsuffix = \")\"\n\t\t\t\ttoken = token[:len(token)-1]\n\t\t\t}\n\t\t\toutput[i] = prefix + mime.BEncoding.Encode(\"UTF-8\", DecodeHeader(token)) + suffix\n\t\t} else {\n\t\t\toutput[i] = token\n\t\t}\n\t\tdebug(\"%v %q %q\", i, token, output[i])\n\t}\n\n\treturn strings.Join(output, \" \")\n}\n\n\nfunc isWhiteSpaceRune(r rune) bool {\n\tswitch r {\n\tcase ' ':\n\t\treturn true\n\tcase '\\t':\n\t\treturn true\n\tcase '\\r':\n\t\treturn true\n\tcase '\\n':\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc debug(format string, args ...interface{}) ", "output": "{\n\tif false {\n\t\tfmt.Printf(format, args...)\n\t\tfmt.Println()\n\t}\n}"} {"input": "package yext\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n)\n\n\n\ntype BackoffPolicy struct {\n\tMillis []int\n}\n\n\nvar DefaultBackoffPolicy = BackoffPolicy{\n\t[]int{0, 0, 1000, 5000},\n}\n\n\n\n\n\n\n\n\nfunc jitter(millis int) int {\n\tif millis == 0 {\n\t\treturn 0\n\t}\n\n\treturn millis/2 + rand.Intn(millis)\n}\n\nfunc (b BackoffPolicy) Duration(n int) time.Duration ", "output": "{\n\tif n >= len(b.Millis) {\n\t\tn = len(b.Millis) - 1\n\t}\n\n\treturn time.Duration(jitter(b.Millis[n])) * time.Millisecond\n}"} {"input": "package passwordless\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestPINGenerator(t *testing.T) {\n\tfor _, v := range []int{1, 2, 3, 4, 5} {\n\t\tng := PINGenerator{Length: v}\n\t\ts, err := ng.Generate(nil)\n\t\tassert.NoError(t, err)\n\t\tassert.Len(t, s, v)\n\t}\n\n\tng := PINGenerator{}\n\ts, err := ng.Sanitize(nil, \"1iIlL2345sS6b78B90oO\")\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"11111234555667889000\", s)\n\n}\n\nfunc TestCrockfordGenerator(t *testing.T) {\n\tfor _, v := range []int{1, 2, 3, 4, 5} {\n\t\tng := CrockfordGenerator{Length: v}\n\t\ts, err := ng.Generate(nil)\n\t\tassert.NoError(t, err)\n\t\tassert.Len(t, s, v)\n\t}\n\n\tng := CrockfordGenerator{}\n\ts, err := ng.Sanitize(nil, \"abcdefghijklmnopqrstuvwxyz\"+\n\t\t\"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789|\")\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"abcdefgh1jk1mn0pqrstuvwxyz\"+\n\t\t\"abcdefgh1jk1mn0pqrstuvwxyz01234567891\", s)\n\n}\n\nfunc TestRandBytes(t *testing.T) {\n\tb, err := randBytes(make([]byte, 500), 5)\n\tassert.Nil(t, b)\n\tassert.Error(t, err)\n}\n\nfunc TestByteGenerator(t *testing.T) ", "output": "{\n\tbg := ByteGenerator{Bytes: []byte(\"a\"), Length: 1}\n\ts, err := bg.Generate(nil)\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"a\", s)\n\n\tbg.Bytes = []byte(\"b\")\n\ts, err = bg.Generate(nil)\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"b\", s)\n\n\tbg.Length = 2\n\ts, err = bg.Generate(nil)\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"bb\", s)\n\n\td := map[string]int{\"aa\": 0, \"ab\": 0, \"ba\": 0, \"bb\": 0}\n\tbg.Bytes = []byte(\"ab\")\n\tfor len(d) > 0 {\n\t\ts, err = bg.Generate(nil)\n\t\tassert.NoError(t, err)\n\t\tdelete(d, s)\n\t}\n}"} {"input": "package openpgp\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\ntype recordingHash struct {\n\tbuf *bytes.Buffer\n}\n\n\n\nfunc (r recordingHash) Sum(in []byte) []byte {\n\treturn append(in, r.buf.Bytes()...)\n}\n\nfunc (r recordingHash) Reset() {\n\tpanic(\"shouldn't be called\")\n}\n\nfunc (r recordingHash) Size() int {\n\tpanic(\"shouldn't be called\")\n}\n\nfunc (r recordingHash) BlockSize() int {\n\tpanic(\"shouldn't be called\")\n}\n\nfunc testCanonicalText(t *testing.T, input, expected string) {\n\tr := recordingHash{bytes.NewBuffer(nil)}\n\tc := NewCanonicalTextHash(r)\n\tc.Write([]byte(input))\n\tresult := c.Sum(nil)\n\tif expected != string(result) {\n\t\tt.Errorf(\"input: %x got: %x want: %x\", input, result, expected)\n\t}\n}\n\nfunc TestCanonicalText(t *testing.T) {\n\ttestCanonicalText(t, \"foo\\n\", \"foo\\r\\n\")\n\ttestCanonicalText(t, \"foo\", \"foo\")\n\ttestCanonicalText(t, \"foo\\r\\n\", \"foo\\r\\n\")\n\ttestCanonicalText(t, \"foo\\r\\nbar\", \"foo\\r\\nbar\")\n\ttestCanonicalText(t, \"foo\\r\\nbar\\n\\n\", \"foo\\r\\nbar\\r\\n\\r\\n\")\n}\n\nfunc (r recordingHash) Write(b []byte) (n int, err error) ", "output": "{\n\treturn r.buf.Write(b)\n}"} {"input": "package pool\n\nimport (\n\n)\n\ntype ObjPool struct {\n\tobj chan interface{}\n\tNew func() interface{}\n}\n\nfunc NewObjPool() *ObjPool {\n\treturn &ObjPool{\n\t\tobj: make(chan interface{}, 200),\n\t}\n}\n\nfunc (p *ObjPool) Get() interface{} {\n\tselect {\n\tcase o := <-p.obj:\n\t\treturn o\n\tdefault:\n\t\treturn p.New()\n\t}\n}\n\n\n\nfunc (p *ObjPool) Put(o interface{}) ", "output": "{\n\tselect {\n\tcase p.obj <- o:\n\tdefault:\n\t}\n}"} {"input": "package okta\n\nimport ()\n\ntype OpenIdConnectApplicationSettingsClient struct {\n\tApplicationType string `json:\"application_type,omitempty\"`\n\tClientUri string `json:\"client_uri,omitempty\"`\n\tConsentMethod string `json:\"consent_method,omitempty\"`\n\tGrantTypes []*OAuthGrantType `json:\"grant_types,omitempty\"`\n\tLogoUri string `json:\"logo_uri,omitempty\"`\n\tPolicyUri string `json:\"policy_uri,omitempty\"`\n\tPostLogoutRedirectUris []string `json:\"post_logout_redirect_uris,omitempty\"`\n\tRedirectUris []string `json:\"redirect_uris,omitempty\"`\n\tResponseTypes []*OAuthResponseType `json:\"response_types,omitempty\"`\n\tTosUri string `json:\"tos_uri,omitempty\"`\n}\n\nfunc NewOpenIdConnectApplicationSettingsClient() *OpenIdConnectApplicationSettingsClient {\n\treturn &OpenIdConnectApplicationSettingsClient{}\n}\n\n\n\nfunc (a *OpenIdConnectApplicationSettingsClient) IsApplicationInstance() bool ", "output": "{\n\treturn true\n}"} {"input": "package aws_test\n\nimport (\n\t\"github.com/MobiSolutions/goamz/aws\"\n\t. \"launchpad.net/gocheck\"\n\t\"time\"\n)\n\n\n\nfunc (S) TestAttemptNextHasNext(c *C) {\n\ta := aws.AttemptStrategy{}.Start()\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.Next(), Equals, false)\n\n\ta = aws.AttemptStrategy{}.Start()\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.HasNext(), Equals, false)\n\tc.Assert(a.Next(), Equals, false)\n\n\ta = aws.AttemptStrategy{Total: 2e8}.Start()\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.HasNext(), Equals, true)\n\ttime.Sleep(2e8)\n\tc.Assert(a.HasNext(), Equals, true)\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.Next(), Equals, false)\n\n\ta = aws.AttemptStrategy{Total: 1e8, Min: 2}.Start()\n\ttime.Sleep(1e8)\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.HasNext(), Equals, true)\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.HasNext(), Equals, false)\n\tc.Assert(a.Next(), Equals, false)\n}\n\nfunc (S) TestAttemptTiming(c *C) ", "output": "{\n\ttestAttempt := aws.AttemptStrategy{\n\t\tTotal: 0.25e9,\n\t\tDelay: 0.1e9,\n\t}\n\twant := []time.Duration{0, 0.1e9, 0.2e9, 0.2e9}\n\tgot := make([]time.Duration, 0, len(want)) \n\tt0 := time.Now()\n\tfor a := testAttempt.Start(); a.Next(); {\n\t\tgot = append(got, time.Now().Sub(t0))\n\t}\n\tgot = append(got, time.Now().Sub(t0))\n\tc.Assert(got, HasLen, len(want))\n\tconst margin = 0.01e9\n\tfor i, got := range want {\n\t\tlo := want[i] - margin\n\t\thi := want[i] + margin\n\t\tif got < lo || got > hi {\n\t\t\tc.Errorf(\"attempt %d want %g got %g\", i, want[i].Seconds(), got.Seconds())\n\t\t}\n\t}\n}"} {"input": "package loggo\n\nvar (\n\tdefaultContext = newDefaultContxt()\n)\n\nfunc newDefaultContxt() *Context {\n\tctx := NewContext(WARNING)\n\tctx.AddWriter(DefaultWriterName, defaultWriter())\n\treturn ctx\n}\n\n\nfunc DefaultContext() *Context {\n\treturn defaultContext\n}\n\n\n\n\n\nfunc LoggerInfo() string {\n\treturn defaultContext.Config().String()\n}\n\n\n\nfunc GetLogger(name string, size ...int) Logger {\n\treturn defaultContext.GetLogger(name, size...)\n}\n\n\n\n\n\n\n\n\nfunc ResetWriters() {\n\tdefaultContext.ResetWriters()\n}\n\n\n\n\nfunc ReplaceDefaultWriter(writer Writer) (Writer, error) {\n\treturn defaultContext.ReplaceWriter(DefaultWriterName, writer)\n}\n\n\n\n\nfunc RegisterWriter(name string, writer Writer) error {\n\treturn defaultContext.AddWriter(name, writer)\n}\n\n\n\nfunc RemoveWriter(name string) (Writer, error) {\n\treturn defaultContext.RemoveWriter(name)\n}\n\n\n\n\n\n\n\n\n\n\nfunc ConfigureLoggers(specification string) error {\n\tconfig, err := ParseConfigString(specification)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefaultContext.ApplyConfig(config)\n\treturn nil\n}\n\nfunc ResetLogging() ", "output": "{\n\tdefaultContext.ResetLoggerLevels()\n\tdefaultContext.ResetWriters()\n}"} {"input": "package gorilla\n\nimport (\n\t\"net/http\"\n\n\tgcontext \"github.com/gorilla/context\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\nfunc NewContext(parent context.Context, req *http.Request) context.Context {\n\treturn &wrapper{parent, req}\n}\n\ntype wrapper struct {\n\tcontext.Context\n\treq *http.Request\n}\n\ntype key int\n\nconst reqKey key = 0\n\n\n\n\n\n\n\nfunc HTTPRequest(ctx context.Context) (*http.Request, bool) {\n\treq, ok := ctx.Value(reqKey).(*http.Request)\n\treturn req, ok\n}\n\nfunc (ctx *wrapper) Value(key interface{}) interface{} ", "output": "{\n\tif key == reqKey {\n\t\treturn ctx.req\n\t}\n\tif val, ok := gcontext.GetOk(ctx.req, key); ok {\n\t\treturn val\n\t}\n\treturn ctx.Context.Value(key)\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\tclayControllers \"github.com/qb0C80aE/clay/controllers\"\n\t\"github.com/qb0C80aE/clay/extensions\"\n\t\"github.com/qb0C80aE/pottery/logics\"\n\t\"github.com/qb0C80aE/pottery/models\"\n)\n\ntype hostGroupController struct {\n\t*clayControllers.BaseController\n}\n\nfunc newHostGroupController() extensions.Controller {\n\tcontroller := &hostGroupController{\n\t\tBaseController: clayControllers.NewBaseController(\n\t\t\tmodels.SharedHostGroupModel(),\n\t\t\tlogics.UniqueHostGroupLogic(),\n\t\t),\n\t}\n\treturn controller\n}\n\n\n\nvar uniqueHostGroupController = newHostGroupController()\n\nfunc init() {\n\textensions.RegisterController(uniqueHostGroupController)\n}\n\nfunc (controller *hostGroupController) RouteMap() map[int]map[int]gin.HandlerFunc ", "output": "{\n\trouteMap := map[int]map[int]gin.HandlerFunc{\n\t\textensions.MethodGet: {\n\t\t\textensions.URLSingle: controller.GetSingle,\n\t\t\textensions.URLMulti: controller.GetMulti,\n\t\t},\n\t\textensions.MethodPost: {\n\t\t\textensions.URLMulti: controller.Create,\n\t\t},\n\t\textensions.MethodPut: {\n\t\t\textensions.URLSingle: controller.Update,\n\t\t},\n\t\textensions.MethodDelete: {\n\t\t\textensions.URLSingle: controller.Delete,\n\t\t},\n\t}\n\treturn routeMap\n}"} {"input": "package upgrades\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\n\t\"github.com/juju/utils/exec\"\n)\n\nvar ubuntuHome = \"/home/ubuntu\"\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ensureLockDirExistsAndUbuntuWritable(context Context) error ", "output": "{\n\tlockDir := path.Join(context.AgentConfig().DataDir(), \"locks\")\n\tcommand := fmt.Sprintf(\"\"+\n\t\t\"mkdir -p %s\\n\"+\n\t\t\"[ -e %s ] && chown ubuntu:ubuntu %s\\n\",\n\t\tlockDir, ubuntuHome, lockDir)\n\tlogger.Tracef(\"command: %s\", command)\n\tresult, err := exec.RunCommands(exec.RunParams{\n\t\tCommands: command,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.Tracef(\"stdout: %s\", result.Stdout)\n\treturn nil\n}"} {"input": "package all\n\nimport (\n\t\"github.com/juju/collections/set\"\n\t\"github.com/juju/errors\"\n)\n\ntype component interface {\n\tregisterForServer() error\n\tregisterForClient() error\n}\n\nvar components = []component{\n\t&payloads{},\n\t&resources{},\n}\n\n\n\nfunc RegisterForServer() error {\n\tfor _, c := range components {\n\t\tif err := c.registerForServer(); err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\nfunc RegisterForClient() error {\n\tfor _, c := range components {\n\t\tif err := c.registerForClient(); err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t}\n\treturn nil\n}\n\n\nvar registered = map[string]set.Strings{}\n\n\n\n\n\n\n\nfunc markRegistered(component, part string) bool ", "output": "{\n\tparts, ok := registered[component]\n\tif !ok {\n\t\tparts = set.NewStrings()\n\t\tregistered[component] = parts\n\t}\n\tif parts.Contains(part) {\n\t\treturn false\n\t}\n\tparts.Add(part)\n\treturn true\n}"} {"input": "package violetear\n\nimport (\n\t\"net/http\"\n\t\"time\"\n)\n\n\ntype ResponseWriter struct {\n\thttp.ResponseWriter\n\trequestID string\n\tsize, status int\n\tstart time.Time\n}\n\n\nfunc NewResponseWriter(w http.ResponseWriter, rid string) *ResponseWriter {\n\treturn &ResponseWriter{\n\t\tResponseWriter: w,\n\t\trequestID: rid,\n\t\tstart: time.Now(),\n\t\tstatus: http.StatusOK,\n\t}\n}\n\n\n\n\n\nfunc (w *ResponseWriter) Size() int {\n\treturn w.size\n}\n\n\nfunc (w *ResponseWriter) RequestTime() string {\n\treturn time.Since(w.start).String()\n}\n\n\nfunc (w *ResponseWriter) RequestID() string {\n\treturn w.requestID\n}\n\n\n\nfunc (w *ResponseWriter) Write(data []byte) (int, error) {\n\tsize, err := w.ResponseWriter.Write(data)\n\tw.size += size\n\treturn size, err\n}\n\n\n\nfunc (w *ResponseWriter) WriteHeader(statusCode int) {\n\tw.status = statusCode\n\tw.ResponseWriter.WriteHeader(statusCode)\n}\n\nfunc (w *ResponseWriter) Status() int ", "output": "{\n\treturn w.status\n}"} {"input": "package Plugin\n\nimport \"github.com/MPjct/GoMP/MySQLProtocol\"\n\ntype Plugin_interface interface {\n\tinit(context MySQLProtocol.Context)\n\tread_handshake(context MySQLProtocol.Context)\n\tsend_handshake(context MySQLProtocol.Context)\n\tread_auth(context MySQLProtocol.Context)\n\tsend_auth(context MySQLProtocol.Context)\n\tread_auth_result(context MySQLProtocol.Context)\n\tsend_auth_result(context MySQLProtocol.Context)\n\tread_query(context MySQLProtocol.Context)\n\tsend_query(context MySQLProtocol.Context)\n\tread_query_result(context MySQLProtocol.Context)\n\tsend_query_result(context MySQLProtocol.Context)\n\tcleanup(context MySQLProtocol.Context)\n}\n\ntype Plugin struct {\n}\n\nfunc (plugin *Plugin) init(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\n\n\nfunc (plugin *Plugin) cleanup(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query_result(context MySQLProtocol.Context) ", "output": "{\n\treturn\n}"} {"input": "package model\n\n\ntype Sample struct {\n\tMetric Metric\n\tValue SampleValue\n\tTimestamp Timestamp\n}\n\n\nfunc (s *Sample) Equal(o *Sample) bool {\n\tif s == o {\n\t\treturn true\n\t}\n\n\tif !s.Metric.Equal(o.Metric) {\n\t\treturn false\n\t}\n\tif !s.Timestamp.Equal(o.Timestamp) {\n\t\treturn false\n\t}\n\tif !s.Value.Equal(o.Value) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\ntype Samples []*Sample\n\nfunc (s Samples) Len() int {\n\treturn len(s)\n}\n\n\nfunc (s Samples) Less(i, j int) bool {\n\tswitch {\n\tcase s[i].Metric.Before(s[j].Metric):\n\t\treturn true\n\tcase s[j].Metric.Before(s[i].Metric):\n\t\treturn false\n\tcase s[i].Timestamp.Before(s[j].Timestamp):\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\n\n\nfunc (s Samples) Equal(o Samples) bool {\n\tif len(s) != len(o) {\n\t\treturn false\n\t}\n\n\tfor i, sample := range s {\n\t\tif !sample.Equal(o[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (s Samples) Swap(i, j int) ", "output": "{\n\ts[i], s[j] = s[j], s[i]\n}"} {"input": "package gull\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype Up struct {\n\tEnvironment string\n\tSourceDirectory string\n\tMigrateTarget MigrationTarget\n\tMigrations *Migrations\n}\n\nfunc NewUp(source string, target MigrationTarget) *Up {\n\treturn &Up{\n\t\tEnvironment: target.GetEnvironment(),\n\t\tMigrateTarget: target,\n\t\tSourceDirectory: source,\n\t\tMigrations: NewMigrations(),\n\t}\n}\n\nfunc (u *Up) Migrate() error {\n\terr := u.Ingest()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif u.MigrateTarget.IsPerformingFullMigration() {\n\t\tu.MigrateTarget.GetLogger().Info(\"Deleting configuration for [%v]/[%v]\", u.MigrateTarget.GetApplication(), u.MigrateTarget.GetEnvironment())\n\t\t_ = u.MigrateTarget.DeleteEnvironment()\n\t}\n\treturn u.Migrations.Apply(u.MigrateTarget)\n}\n\n\n\nfunc (u *Up) IngestFile(path string, f os.FileInfo, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !f.IsDir() {\n\t\tmigration, err := NewMigrationFromGullFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = u.Migrations.Add(migration)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (u *Up) Ingest() error ", "output": "{\n\treturn filepath.Walk(u.SourceDirectory, u.IngestFile)\n}"} {"input": "package config\n\nimport (\n\t\"sync\"\n)\n\n\n\n\n\n\ntype delayedEnvironment struct {\n\tenv Environment\n\tloading sync.Mutex\n\tcallback func() Environment\n}\n\n\n\nfunc (e *delayedEnvironment) Get(key string) (string, bool) {\n\te.Load()\n\treturn e.env.Get(key)\n}\n\n\n\n\n\n\n\nfunc (e *delayedEnvironment) Bool(key string, def bool) bool {\n\te.Load()\n\treturn e.env.Bool(key, def)\n}\n\n\n\nfunc (e *delayedEnvironment) Int(key string, def int) int {\n\te.Load()\n\treturn e.env.Int(key, def)\n}\n\n\nfunc (e *delayedEnvironment) All() map[string][]string {\n\te.Load()\n\treturn e.env.All()\n}\n\n\n\n\n\n\n\n\nfunc (e *delayedEnvironment) Load() {\n\te.loading.Lock()\n\tdefer e.loading.Unlock()\n\n\tif e.env != nil {\n\t\treturn\n\t}\n\n\te.env = e.callback()\n}\n\nfunc (e *delayedEnvironment) GetAll(key string) []string ", "output": "{\n\te.Load()\n\treturn e.env.GetAll(key)\n}"} {"input": "package os\n\nimport \"syscall\"\n\n\n\nfunc fileInfoFromStat(name string, fi *FileInfo, lstat, stat *syscall.Stat_t) *FileInfo {\n\tfi.Dev = stat.Dev\n\tfi.Ino = stat.Ino\n\tfi.Nlink = uint64(stat.Nlink)\n\tfi.Mode = stat.Mode\n\tfi.Uid = int(stat.Uid)\n\tfi.Gid = int(stat.Gid)\n\tfi.Rdev = stat.Rdev\n\tfi.Size = stat.Size\n\tfi.Blksize = int64(stat.Blksize)\n\tfi.Blocks = stat.Blocks\n\tfi.Atime_ns = syscall.TimespecToNsec(stat.Atim)\n\tfi.Mtime_ns = syscall.TimespecToNsec(stat.Mtim)\n\tfi.Ctime_ns = syscall.TimespecToNsec(stat.Ctim)\n\tfi.Name = basename(name)\n\tif isSymlink(lstat) && !isSymlink(stat) {\n\t\tfi.FollowedSymlink = true\n\t}\n\treturn fi\n}\n\nfunc isSymlink(stat *syscall.Stat_t) bool ", "output": "{\n\treturn stat.Mode&syscall.S_IFMT == syscall.S_IFLNK\n}"} {"input": "package vox\n\ntype Block uint8\n\nconst (\n\tBlockNil = 0x00\n\tblockActiveMask = 0x80 \n\tblockTypeMask = 0x7F \n)\n\nfunc (b Block) Active() bool {\n\treturn (blockActiveMask & b) == blockActiveMask\n}\n\n\n\nfunc (b Block) TypeID() uint8 {\n\treturn uint8(b & blockTypeMask)\n}\n\nfunc (b Block) ChangeType(t *BlockType) Block {\n\treturn Block((uint8(b) & blockActiveMask) | t.ID)\n}\n\ntype BlockType struct {\n\tID uint8\n\tTop *TextureRegion\n\tBottom *TextureRegion\n\tSide *TextureRegion\n}\n\ntype BlockBank struct {\n\tTypes []*BlockType\n\ttypeMap map[uint8]*BlockType\n}\n\nfunc NewBlockBank() *BlockBank {\n\treturn &BlockBank{\n\t\ttypeMap: make(map[uint8]*BlockType),\n\t}\n}\n\nfunc (b *BlockBank) AddType(blockType *BlockType) {\n\tb.typeMap[blockType.ID] = blockType\n\tb.Types = append(b.Types, blockType)\n}\n\nfunc (b *BlockBank) TypeOf(block Block) *BlockType {\n\treturn b.typeMap[block.TypeID()]\n}\n\nfunc (b Block) Activate(active bool) Block ", "output": "{\n\tif active {\n\t\treturn b | blockActiveMask\n\t}\n\treturn b & blockTypeMask\n}"} {"input": "package triton\n\nimport (\n\t\"github.com/hashicorp/hcl/v2/hcldec\"\n\t\"github.com/zclconf/go-cty/cty\"\n)\n\n\n\ntype FlatMachineImageFilter struct {\n\tMostRecent *bool `mapstructure:\"most_recent\" cty:\"most_recent\"`\n\tName *string `cty:\"name\"`\n\tOS *string `cty:\"os\"`\n\tVersion *string `cty:\"version\"`\n\tPublic *bool `cty:\"public\"`\n\tState *string `cty:\"state\"`\n\tOwner *string `cty:\"owner\"`\n\tType *string `cty:\"type\"`\n}\n\n\n\n\n\n\n\n\n\nfunc (*FlatMachineImageFilter) HCL2Spec() map[string]hcldec.Spec {\n\ts := map[string]hcldec.Spec{\n\t\t\"most_recent\": &hcldec.AttrSpec{Name: \"most_recent\", Type: cty.Bool, Required: false},\n\t\t\"name\": &hcldec.AttrSpec{Name: \"name\", Type: cty.String, Required: false},\n\t\t\"os\": &hcldec.AttrSpec{Name: \"os\", Type: cty.String, Required: false},\n\t\t\"version\": &hcldec.AttrSpec{Name: \"version\", Type: cty.String, Required: false},\n\t\t\"public\": &hcldec.AttrSpec{Name: \"public\", Type: cty.Bool, Required: false},\n\t\t\"state\": &hcldec.AttrSpec{Name: \"state\", Type: cty.String, Required: false},\n\t\t\"owner\": &hcldec.AttrSpec{Name: \"owner\", Type: cty.String, Required: false},\n\t\t\"type\": &hcldec.AttrSpec{Name: \"type\", Type: cty.String, Required: false},\n\t}\n\treturn s\n}\n\nfunc (*MachineImageFilter) FlatMapstructure() interface{ HCL2Spec() map[string]hcldec.Spec } ", "output": "{\n\treturn new(FlatMachineImageFilter)\n}"} {"input": "package blocker\n\nimport \"sort\"\n\ntype sources []string\n\nfunc (s *sources) Add(source string) {\n\tn := sort.SearchStrings(*s, source)\n\n\tif n < len(*s) && (*s)[n] == source {\n\t\treturn\n\t}\n\n\t*s = append(*s, \"\")\n\tcopy((*s)[n+1:], (*s)[n:])\n\t(*s)[n] = source\n}\n\nfunc (s *sources) Remove(source string) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tn := sort.SearchStrings(*s, source)\n\n\tif n < len(*s) && (*s)[n] == source {\n\t\t*s = append((*s)[:n], (*s)[n+1:]...)\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (s *sources) Has(source string) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tn := sort.SearchStrings(*s, source)\n\n\tif n < len(*s) && (*s)[n] == source {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (s *sources) Len() int {\n\treturn len(*s)\n}\n\n\n\nfunc newSources(s ...string) *sources ", "output": "{\n\tret := sources(s)\n\treturn &ret\n}"} {"input": "package overcurrent\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\ntype (\n\tNoopBreaker struct{}\n\n\tNoopCollector struct{}\n)\n\nvar defaultCollector = NewNoopCollector()\n\n\nfunc NewNoopBreaker() CircuitBreaker {\n\treturn &NoopBreaker{}\n}\n\nfunc (b *NoopBreaker) Trip() {}\nfunc (b *NoopBreaker) Reset() {}\n\nfunc (b *NoopBreaker) MarkResult(err error) bool { return true }\nfunc (b *NoopBreaker) Call(f BreakerFunc) error { return f(context.Background()) }\nfunc (b *NoopBreaker) CallAsync(f BreakerFunc) <-chan error { return nil }\n\n\nfunc NewNoopCollector() MetricCollector {\n\treturn &NoopCollector{}\n}\n\nfunc (c *NoopCollector) ReportNew(BreakerConfig) {}\nfunc (c *NoopCollector) ReportCount(EventType) {}\nfunc (c *NoopCollector) ReportDuration(EventType, time.Duration) {}\nfunc (c *NoopCollector) ReportState(CircuitState) {}\n\nfunc (b *NoopBreaker) ShouldTry() bool ", "output": "{ return true }"} {"input": "package stack\n\nimport (\n\t\"github.com/docker/docker/cli\"\n\t\"github.com/docker/docker/cli/command\"\n\t\"github.com/spf13/cobra\"\n)\n\n\n\n\n\nfunc NewTopLevelDeployCommand(dockerCli *command.DockerCli) *cobra.Command {\n\tcmd := newDeployCommand(dockerCli)\n\tcmd.Aliases = []string{}\n\tcmd.Tags = map[string]string{\"experimental\": \"\", \"version\": \"1.25\"}\n\treturn cmd\n}\n\nfunc NewStackCommand(dockerCli *command.DockerCli) *cobra.Command ", "output": "{\n\tcmd := &cobra.Command{\n\t\tUse: \"stack\",\n\t\tShort: \"Manage Docker stacks\",\n\t\tArgs: cli.NoArgs,\n\t\tRunE: dockerCli.ShowHelp,\n\t\tTags: map[string]string{\"version\": \"1.25\"},\n\t}\n\tcmd.AddCommand(\n\t\tnewDeployCommand(dockerCli),\n\t\tnewListCommand(dockerCli),\n\t\tnewRemoveCommand(dockerCli),\n\t\tnewServicesCommand(dockerCli),\n\t\tnewPsCommand(dockerCli),\n\t)\n\treturn cmd\n}"} {"input": "package sdk\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\nfunc init() {\n\tNowTime = time.Now\n\tSleep = time.Sleep\n\tSleepWithContext = sleepWithContext\n}\n\n\n\nvar NowTime func() time.Time\n\n\n\nvar Sleep func(time.Duration)\n\n\n\n\n\n\nvar SleepWithContext func(context.Context, time.Duration) error\n\n\n\n\n\n\n\nfunc noOpSleepWithContext(context.Context, time.Duration) error {\n\treturn nil\n}\n\nfunc noOpSleep(time.Duration) {}\n\n\n\nfunc TestingUseNopSleep() func() {\n\tSleepWithContext = noOpSleepWithContext\n\tSleep = noOpSleep\n\n\treturn func() {\n\t\tSleepWithContext = sleepWithContext\n\t\tSleep = time.Sleep\n\t}\n}\n\n\n\nfunc TestingUseReferenceTime(referenceTime time.Time) func() {\n\tNowTime = func() time.Time {\n\t\treturn referenceTime\n\t}\n\treturn func() {\n\t\tNowTime = time.Now\n\t}\n}\n\nfunc sleepWithContext(ctx context.Context, dur time.Duration) error ", "output": "{\n\tt := time.NewTimer(dur)\n\tdefer t.Stop()\n\n\tselect {\n\tcase <-t.C:\n\t\tbreak\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n\n\treturn nil\n}"} {"input": "package luhn\n\nimport \"testing\"\n\nvar validTests = []struct {\n\tn string\n\tok bool\n}{\n\t{\"738\", false},\n\t{\"8739567\", true},\n\t{\"1111\", false},\n\t{\"8763\", true},\n\t{\" \", false},\n\t{\"\", false},\n\t{\"2323 2005 7766 3554\", true},\n}\n\nvar addTests = []struct{ raw, luhn string }{\n\t{\"123\", \"1230\"},\n\t{\"873956\", \"8739567\"},\n\t{\"837263756\", \"8372637564\"},\n\t{\"2323 2005 7766 355\", \"2323 2005 7766 3554\"},\n}\n\nfunc TestValid(t *testing.T) {\n\tfor _, test := range validTests {\n\t\tif ok := Valid(test.n); ok != test.ok {\n\t\t\tt.Fatalf(\"Valid(%s) = %t, want %t.\", test.n, ok, test.ok)\n\t\t}\n\t}\n}\n\nfunc TestAddCheck(t *testing.T) {\n\tfor _, test := range addTests {\n\t\tif luhn := AddCheck(test.raw); luhn != test.luhn {\n\t\t\tt.Fatalf(\"AddCheck(%s) = %s, want %s.\", test.raw, luhn, test.luhn)\n\t\t}\n\t}\n}\n\n\n\nfunc BenchmarkAddCheck(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tAddCheck(\"2323 2005 7766 355\")\n\t}\n}\n\nfunc BenchmarkValid(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tValid(\"2323 2005 7766 3554\")\n\t}\n}"} {"input": "package prometheus\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"istio.io/istio/pkg/test/framework\"\n\t\"istio.io/istio/pkg/test/framework/components/cluster\"\n\t\"istio.io/istio/pkg/test/framework/components/prometheus\"\n\t\"istio.io/istio/pkg/test/util/retry\"\n\tutil \"istio.io/istio/tests/integration/telemetry\"\n)\n\n\nfunc QueryPrometheus(t framework.TestContext, cluster cluster.Cluster, query prometheus.Query, promInst prometheus.Instance) (string, error) {\n\tt.Helper()\n\tt.Logf(\"query prometheus with: %v\", query)\n\n\tval, err := promInst.Query(cluster, query)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tgot, err := prometheus.Sum(val)\n\tif err != nil {\n\t\tt.Logf(\"value: %s\", val.String())\n\t\treturn \"\", fmt.Errorf(\"could not find metric value: %v\", err)\n\t}\n\tt.Logf(\"get value %v\", got)\n\treturn val.String(), nil\n}\n\n\n\nfunc ValidateMetric(t framework.TestContext, cluster cluster.Cluster, prometheus prometheus.Instance, query prometheus.Query, want float64) ", "output": "{\n\tt.Helper()\n\terr := retry.UntilSuccess(func() error {\n\t\tgot, err := prometheus.QuerySum(cluster, query)\n\t\tt.Logf(\"%s: %f\", query.Metric, got)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif got < want {\n\t\t\treturn fmt.Errorf(\"bad metric value: got %f, want at least %f\", got, want)\n\t\t}\n\t\treturn nil\n\t}, retry.Delay(time.Second), retry.Timeout(time.Second*20))\n\tif err != nil {\n\t\tutil.PromDiff(t, prometheus, cluster, query)\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package strlit\n\nimport (\n\t\"testing\"\n)\n\nfunc TestNotBareLiteralAsError(t *testing.T) {\n\n\tvar err error = internalNotBareLiteral{} \n\n\tif nil == err {\n\t\tt.Error(\"This should never happen.\")\n\t}\n}\n\n\n\nfunc TestNotBareLiteralAsNotLiteral(t *testing.T) ", "output": "{\n\n\tvar complainer NotLiteral = internalNotBareLiteral{} \n\n\tif nil == complainer {\n\t\tt.Error(\"This should never happen.\")\n\t}\n}"} {"input": "package common\n\n\n\n\nimport (\n\t\"strconv\"\n)\n\n\n\n\n\nfunc Atoi(s string) int {\n\ti, err := strconv.Atoi(s)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn i\n}\n\n\nfunc Atob(str string) bool {\n\tb, err := strconv.ParseBool(str)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn b\n}\n\n\nfunc Atoi64(str string) int64 {\n\ti, err := strconv.ParseInt(str, 10, 64)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn i\n}\n\n\nfunc Atof64(str string) float64 {\n\ti, err := strconv.ParseFloat(str, 64)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn i\n}\n\nfunc Atof32(s string) float64 ", "output": "{\n\tf, err := strconv.ParseFloat(s, 32)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn float64(f)\n}"} {"input": "package common\n\nimport (\n\t\"encoding/binary\"\n\t\"sort\"\n)\n\n\n\ntype Uint64Slice []uint64\n\nfunc (p Uint64Slice) Len() int { return len(p) }\nfunc (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] }\nfunc (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\n\n\nfunc SearchUint64s(a []uint64, x uint64) int {\n\treturn sort.Search(len(a), func(i int) bool { return a[i] >= x })\n}\n\nfunc (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) }\n\n\n\nfunc PutUint64LE(dest []byte, i uint64) {\n\tbinary.LittleEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64LE(src []byte) uint64 {\n\treturn binary.LittleEndian.Uint64(src)\n}\n\nfunc PutUint64BE(dest []byte, i uint64) {\n\tbinary.BigEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64BE(src []byte) uint64 {\n\treturn binary.BigEndian.Uint64(src)\n}\n\nfunc PutInt64LE(dest []byte, i int64) {\n\tbinary.LittleEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64LE(src []byte) int64 {\n\treturn int64(binary.LittleEndian.Uint64(src))\n}\n\nfunc PutInt64BE(dest []byte, i int64) {\n\tbinary.BigEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64BE(src []byte) int64 {\n\treturn int64(binary.BigEndian.Uint64(src))\n}\n\nfunc (p Uint64Slice) Sort() ", "output": "{ sort.Sort(p) }"} {"input": "package result\n\ntype Classic struct {\n\tid int\n\tfitness float64\n\terr error\n\tstop bool\n}\n\nfunc New(id int, fitness float64, err error, stop bool) Classic {\n\treturn Classic{id, fitness, err, stop}\n}\n\n\n\n\n\nfunc (r Classic) Fitness() float64 { return r.fitness }\n\n\nfunc (r Classic) Err() error { return r.err }\n\n\nfunc (r Classic) Stop() bool { return r.stop }\n\nfunc (r Classic) ID() int ", "output": "{ return r.id }"} {"input": "package mqttbase\n\nimport (\n\t\"testing\"\n)\n\nfunc TestPublishPacketConstructor(t *testing.T) {\n\tpacket := NewPublishPacket()\n\tif packet == nil {\n\t\tt.Errorf(\"Packet is nil\")\n\t} else {\n\t\tif packet.FixedHeader == nil {\n\t\t\tt.Errorf(\"Fixed header is nil\")\n\t\t}\n\t}\n}\n\n\n\nfunc TestUnmarshalPublish(t *testing.T) {\n\tdata := []byte{0x30, 16, 0, 3, 'a', '/', 'b', 0x3a, 0xcd, 'T', 'E',\n\t\t'S', 'T', '_', 'D', 'A', 'T', 'A'}\n\tpacket := new(PublishPacket)\n\tpacket.unmarshal(data)\n\tif packet.FixedHeader == nil {\n\t\tt.Errorf(\"Fixed header nil\")\n\t} else {\n\t\tif packet.FixedHeader.cntrlPacketType != Publish {\n\t\t\tt.Errorf(\"Packet not Publish\")\n\t\t}\n\t}\n\tif packet.Id != 0x3acd {\n\t\tt.Errorf(\"Packet id is %#x but should 0x3acd\", packet.Id)\n\t}\n\tif packet.TopicName != \"a/b\" {\n\t\tt.Errorf(\"Packet topic name is %s but should be a/b\", packet.TopicName)\n\t}\n\tif len(packet.Data) != 9 {\n\t\tt.Errorf(\"Packet data length should be 9 but is %d\", len(packet.Data))\n\t} else {\n\t\texpected := []byte(\"TEST_DATA\")\n\t\tfor i := 0; i < len(expected); i++ {\n\t\t\tif packet.Data[i] != expected[i] {\n\t\t\t\tt.Errorf(\"Expected %#x at %d but got %#x\",\n\t\t\t\t\texpected[i], i, packet.Data[i])\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestMarshalPublish(t *testing.T) ", "output": "{\n\tpacket := NewPublishPacket()\n\tpacket.TopicName = \"a/b\"\n\tpacket.Id = 0x3acd\n\tpacket.Data = []byte(\"TEST_DATA\")\n\tdata, _ := packet.Marshal()\n\tif len(data) != 18 {\n\t\tt.Errorf(\"Data length wrong should be 18 but was %d\", len(data))\n\t} else {\n\t\texpected := []byte{0x30, 16, 0, 3, 'a', '/', 'b', 0x3a, 0xcd, 'T', 'E',\n\t\t\t'S', 'T', '_', 'D', 'A', 'T', 'A'}\n\t\tfor i := 0; i < len(expected); i++ {\n\t\t\tif data[i] != expected[i] {\n\t\t\t\tt.Errorf(\"Expected %#x at %d but got %#x\",\n\t\t\t\t\texpected[i], i, data[i])\n\t\t\t}\n\t\t}\n\n\t}\n}"} {"input": "package http\n\nimport (\n\t\"go-common/app/admin/main/tv/model\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\nfunc mangoList(c *bm.Context) {\n\tc.JSON(tvSrv.MangoList(c))\n}\n\nfunc mangoAdd(c *bm.Context) {\n\tparam := new(struct {\n\t\tIDs []int64 `form:\"rids,split\" validate:\"required,min=1,dive,gt=0\"`\n\t\tRType int `form:\"rtype\" validate:\"required,min=1,max=2\"` \n\t})\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(tvSrv.MangoAdd(c, param.RType, param.IDs))\n}\n\n\n\nfunc mangoDel(c *bm.Context) {\n\tparam := new(struct {\n\t\tID int64 `form:\"id\" validate:\"required,min=1,gt=0\"`\n\t})\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(nil, tvSrv.MangoDel(c, param.ID))\n}\n\nfunc mangoPub(c *bm.Context) {\n\tparam := new(struct {\n\t\tIDs []int64 `form:\"ids,split\" validate:\"required,min=1,dive,gt=0\"`\n\t})\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(nil, tvSrv.MangoPub(c, param.IDs))\n}\n\nfunc mangoEdit(c *bm.Context) ", "output": "{\n\tparam := new(model.ReqMangoEdit)\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(nil, tvSrv.MangoEdit(c, param))\n}"} {"input": "package timer\n\nimport (\n\t\"container/heap\"\n\t\"time\"\n\n\t\"github.com/idealeak/goserver/core\"\n\t\"github.com/idealeak/goserver/core/basic\"\n)\n\ntype startTimerCommand struct {\n\tsrc *basic.Object\n\tta TimerAction\n\tud interface{}\n\tinterval time.Duration\n\ttimes int\n\th TimerHandle\n}\n\n\n\n\nfunc StartTimer(ta TimerAction, ud interface{}, interval time.Duration, times int) (TimerHandle, bool) {\n\treturn StartTimerByObject(core.CoreObject(), ta, ud, interval, times)\n}\nfunc AfterTimer(taw TimerActionWrapper, ud interface{}, interval time.Duration) (TimerHandle, bool) {\n\tvar tac = &TimerActionCommon{\n\t\tTaw: taw,\n\t}\n\treturn StartTimerByObject(core.CoreObject(), tac, ud, interval, 1)\n}\n\nfunc StartTimerByObject(src *basic.Object, ta TimerAction, ud interface{}, interval time.Duration, times int) (TimerHandle, bool) {\n\th := generateTimerHandle()\n\tret := TimerModule.SendCommand(\n\t\t&startTimerCommand{\n\t\t\tsrc: src,\n\t\t\tta: ta,\n\t\t\tud: ud,\n\t\t\tinterval: interval,\n\t\t\ttimes: times,\n\t\t\th: h,\n\t\t},\n\t\ttrue)\n\treturn h, ret\n}\n\nfunc (stc *startTimerCommand) Done(o *basic.Object) error ", "output": "{\n\tdefer o.ProcessSeqnum()\n\n\tte := &TimerEntity{\n\t\tsink: stc.src,\n\t\tud: stc.ud,\n\t\tta: stc.ta,\n\t\tinterval: stc.interval,\n\t\ttimes: stc.times,\n\t\th: stc.h,\n\t\tnext: time.Now().Add(stc.interval),\n\t}\n\n\theap.Push(TimerModule.tq, te)\n\n\treturn nil\n}"} {"input": "package main\n\nimport \"testing\"\n\nfunc TestValidateURL(t *testing.T) {\n\tif !validateURL(\"https://github.com/chadev/Chadev_ircbot\") {\n\t\tt.Error(\"failed to validate proper URL: https://github.com/chadev/Chadev_ircbot\")\n\t}\n}\n\n\n\nfunc TestGetIssueURL(t *testing.T) {\n\tURL, err := getIssueURL(\"Chadev_ircbot\")\n\tif err != nil {\n\t\tt.Errorf(\"failed fetching GitHub Issue URL: %s\\n\", err.Error())\n\t}\n\n\tt.Logf(\"returned URL: %s\\n\", URL)\n\tif !validateGitHubURL(URL) {\n\t\tt.Error(\"the URL came back as invalid\")\n\t}\n}\n\nfunc TestGetIssueIDURL(t *testing.T) {\n\tURL, err := getIssueURL(\"Chadev_ircbot\")\n\tif err != nil {\n\t\tt.Errorf(\"failed fetching GitHub Issue URL: %s\\n\", err.Error())\n\t}\n\n\tt.Logf(\"returned URL: %s\\n\", URL)\n\tif !validateGitHubURL(URL) {\n\t\tt.Error(\"the issue queue URL came back as invalid\")\n\t}\n\n\tURL, err = getIssueIDURL(URL, \"#1\")\n\tif err != nil {\n\t\tt.Errorf(\"failed fetching GitHub Issue URL: %s\\n\", err.Error())\n\t}\n\n\tt.Logf(\"returned URL: %s\\n\", URL)\n\tif !validateGitHubURL(URL) {\n\t\tt.Errorf(\"the issue URL came back as invalid\")\n\t}\n}\n\nfunc TestGetGitHubURL(t *testing.T) ", "output": "{\n\tURL, err := getGitHubURL(\"Chadev_ircbot\")\n\tif err != nil {\n\t\tt.Errorf(\"failed fetching GitHub repo URL: %s\\n\", err.Error())\n\t}\n\n\tt.Logf(\"returned URL: %s\\n\", URL)\n\tif !validateGitHubURL(URL) {\n\t\tt.Error(\"the URL came back as invalid\")\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\nimport \"io/ioutil\"\nimport \"io\"\n\nimport \"net/http\"\n\ntype Response struct {\n\tBody io.ReadCloser\n}\n\nfunc (resp Response) String() string {\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\n\treturn string(body)\n}\n\nfunc main() {\n\tfmt.Println(\"hello world\")\n\n\tsendHttpGet(\"http:www.cnet.com\")\n}\n\n\n\nfunc sendHttpGet(url string) {\n\tresponse, err := http.Get(url)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif response.StatusCode == 200 {\n\t\tbody := Response{response.Body}\n\n\t\tfmt.Printf(\"%s\", body)\n\t} else {\n\t\tfmt.Printf(\"The Status code is %s\", response.StatusCode)\n\t}\n}\n\nfunc askMeMyName() string ", "output": "{\n\tvar givenName string\n\tfmt.Println(\"What is your name?\")\n\tfmt.Scanf(\"%s\", &givenName)\n\n\treturn givenName\n}"} {"input": "package v1beta1\n\nimport (\n\t\"k8s.io/apimachinery/pkg/conversion\"\n\t\"k8s.io/apimachinery/pkg/util/json\"\n\n\t\"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions\"\n)\n\nfunc Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(in *apiextensions.JSONSchemaProps, out *JSONSchemaProps, s conversion.Scope) error {\n\tif err := autoConvert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif in.Default != nil && *(in.Default) == nil {\n\t\tout.Default = nil\n\t}\n\tif in.Example != nil && *(in.Example) == nil {\n\t\tout.Example = nil\n\t}\n\treturn nil\n}\n\nfunc Convert_apiextensions_JSON_To_v1beta1_JSON(in *apiextensions.JSON, out *JSON, s conversion.Scope) error {\n\traw, err := json.Marshal(*in)\n\tif err != nil {\n\t\treturn err\n\t}\n\tout.Raw = raw\n\treturn nil\n}\n\n\n\nfunc Convert_v1beta1_JSON_To_apiextensions_JSON(in *JSON, out *apiextensions.JSON, s conversion.Scope) error ", "output": "{\n\tif in != nil {\n\t\tvar i interface{}\n\t\tif err := json.Unmarshal(in.Raw, &i); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t*out = i\n\t} else {\n\t\tout = nil\n\t}\n\treturn nil\n}"} {"input": "package output\n\nimport \"reflect\"\n\n\ntype S3Grantee struct {\n\tID string `json:\"id\"`\n\tType string `json:\"type\"`\n\tPermissions string `json:\"permissions\"`\n}\n\n\ntype S3 struct {\n\tProviderType string `json:\"_type\"`\n\tDatacenterName string `json:\"datacenter_name,omitempty\"`\n\tDatacenterRegion string `json:\"datacenter_region\"`\n\tAccessKeyID string `json:\"aws_access_key_id\"`\n\tSecretAccessKey string `json:\"aws_secret_access_key\"`\n\tName string `json:\"name\"`\n\tACL string `json:\"acl\"`\n\tBucketLocation string `json:\"bucket_location\"`\n\tBucketURI string `json:\"bucket_uri\"`\n\tGrantees []S3Grantee `json:\"grantees,omitempty\"`\n\tTags map[string]string `json:\"tags\"`\n\tService string `json:\"service\"`\n\tStatus string `json:\"status\"`\n\tExists bool\n}\n\n\nfunc (s *S3) HasChanged(os *S3) bool {\n\tif s.ACL != os.ACL {\n\t\treturn true\n\t}\n\n\tif len(s.Grantees) < 1 && len(os.Grantees) < 1 {\n\t\treturn false\n\t}\n\n\treturn !reflect.DeepEqual(s.Grantees, os.Grantees)\n}\n\n\nfunc (s S3) GetTags() map[string]string {\n\treturn s.Tags\n}\n\n\nfunc (s S3) ProviderID() string {\n\treturn s.Name\n}\n\n\n\n\nfunc (s S3) ComponentName() string ", "output": "{\n\treturn s.Name\n}"} {"input": "package relay\n\nimport (\n\t\"encoding/gob\"\n\t\"encoding/json\"\n\t\"io\"\n)\n\n\n\n\ntype Serializer interface {\n\tContentType() string\n\tRelayEncode(io.Writer, interface{}) error\n\tRelayDecode(io.Reader, interface{}) error\n}\n\n\ntype GOBSerializer struct{}\n\nfunc (*GOBSerializer) ContentType() string {\n\treturn \"binary/gob\"\n}\nfunc (*GOBSerializer) RelayEncode(w io.Writer, e interface{}) error {\n\tenc := gob.NewEncoder(w)\n\treturn enc.Encode(e)\n}\nfunc (*GOBSerializer) RelayDecode(r io.Reader, o interface{}) error {\n\tdec := gob.NewDecoder(r)\n\treturn dec.Decode(o)\n}\n\n\ntype JSONSerializer struct{}\n\nfunc (*JSONSerializer) ContentType() string {\n\treturn \"text/json\"\n}\n\n\n\nfunc (*JSONSerializer) RelayDecode(r io.Reader, o interface{}) error {\n\tdec := json.NewDecoder(r)\n\treturn dec.Decode(o)\n}\n\nfunc (*JSONSerializer) RelayEncode(w io.Writer, e interface{}) error ", "output": "{\n\tenc := json.NewEncoder(w)\n\treturn enc.Encode(e)\n}"} {"input": "package notify\n\nimport \"github.com/crocos/rds-testrunner/config\"\n\nfunc NewNotifier(notifyConfig config.NotifyConfig) NotifierInterface {\n\tif notifyConfig.Type == \"hipchat\" {\n\t\treturn NewHipChatNotifier(notifyConfig)\n\t} else {\n\t\treturn NewDummyNotifier(notifyConfig)\n\t}\n}\n\ntype NotifierInterface interface {\n\tInfo(string) error\n\tWarning(string) error\n\tError(string) error\n}\n\ntype DummyNotifier struct {\n\tConfig config.NotifyConfig\n}\n\n\n\nfunc (n *DummyNotifier) Info(message string) (err error) {\n\treturn\n}\n\nfunc (n *DummyNotifier) Warning(message string) (err error) {\n\treturn\n}\n\nfunc (n *DummyNotifier) Error(message string) (err error) {\n\treturn\n}\n\nfunc NewDummyNotifier(notifyConfig config.NotifyConfig) (notify NotifierInterface) ", "output": "{\n\treturn &DummyNotifier{Config: notifyConfig}\n}"} {"input": "package backend\n\nimport (\n\t\"sync\"\n\n\t\"github.com/docker/infrakit/pkg/run/scope\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/pflag\"\n)\n\n\ntype ExecFunc func(script string, cmd *cobra.Command, args []string) error\n\n\ntype FlagsFunc func(*pflag.FlagSet)\n\n\ntype TemplateFunc func(scope scope.Scope, trial bool, opt ...interface{}) (ExecFunc, error)\n\nvar (\n\tbackends = map[string]TemplateFunc{}\n\tflags = map[string]FlagsFunc{}\n\tlock = sync.Mutex{}\n)\n\n\n\nfunc Register(funcName string, backend TemplateFunc, buildFlags FlagsFunc) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tbackends[funcName] = backend\n\tflags[funcName] = buildFlags\n}\n\n\n\nfunc Visit(visitor func(funcName string, backend TemplateFunc)) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tfor funcName, backend := range backends {\n\t\tvisitor(funcName, backend)\n\t}\n}\n\n\n\n\nfunc VisitFlags(visitor func(string, FlagsFunc)) ", "output": "{\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tfor funcName, f := range flags {\n\t\tvisitor(funcName, f)\n\t}\n}"} {"input": "package auth_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestAuth(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Auth Suite\")\n}"} {"input": "package leet_25\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\ntype dequeue struct {\n\tbuff []*ListNode\n}\n\nfunc (q *dequeue) lpop() *ListNode {\n\tif 0 == len(q.buff) {\n\t\treturn nil\n\t}\n\tp := q.buff[0]\n\tq.buff = q.buff[1:]\n\treturn p\n}\n\n\n\nfunc (q *dequeue) rpush(p *ListNode) {\n\tq.buff = append(q.buff, p)\n}\n\nfunc (q *dequeue) clear() {\n\tq.buff = buff[:0]\n}\n\nvar buff []*ListNode\n\nfunc reverseKGroup(head *ListNode, k int) *ListNode {\n\tif head == nil {\n\t\treturn nil\n\t}\n\tif k <= 1 {\n\t\treturn head\n\t}\n\tbuff = make([]*ListNode, 0, k)\n\tqueue := &dequeue{buff: buff}\n\tcount := 0\n\tcur := head\n\tfor cur != nil {\n\t\tcount++\n\t\tqueue.rpush(cur)\n\t\tif count == k {\n\t\t\tcount = 0\n\t\t\tfor {\n\t\t\t\tl := queue.lpop()\n\t\t\t\tr := queue.rpop()\n\t\t\t\tif l == nil || r == nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tl.Val, r.Val = r.Val, l.Val\n\t\t\t}\n\t\t\tqueue.clear()\n\t\t}\n\t\tcur = cur.Next\n\t}\n\treturn head\n}\n\nfunc (q *dequeue) rpop() *ListNode ", "output": "{\n\tif 0 == len(q.buff) {\n\t\treturn nil\n\t}\n\tlast := len(q.buff) - 1\n\tp := q.buff[last]\n\tq.buff = q.buff[:last]\n\treturn p\n}"} {"input": "package binary\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"testing\"\n)\n\ntype TestStruct struct {\n\tUi16 uint16\n\tUi8_1 uint8\n\tB20 [20]byte\n}\n\n\n\nfunc TestReadAndWriteStruct(t *testing.T) {\n\treadBuf := GetBytesBufferToFillTestStruct()\n\ts := TestStruct{Ui16: uint16('A'), Ui8_1: uint8(1)}\n\n\tif err := ReadStructBigEndian(&s, bytes.NewReader(readBuf.Bytes())); err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\n\twriteBuf := new(bytes.Buffer)\n\n\tif err := WriteStructBigEndian(&s, writeBuf); err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Wrote:\\n%s\\nRead:\\n%s\\n\", readBuf.Bytes(), writeBuf.Bytes())\n\n\tif readBuf.Len() != writeBuf.Len() || readBuf.String() != writeBuf.String() {\n\t\tt.Error(\"Read and write buffer not equal.\\n\")\n\t}\n}\n\nfunc GetBytesBufferToFillTestStruct() *bytes.Buffer {\n\tbuf := new(bytes.Buffer)\n\n\tfor i := 0; i < 3; i++ {\n\t\tbuf.WriteByte(byte(255))\n\t}\n\n\tfor i := 3; i < 23; i++ {\n\t\tbuf.WriteByte(byte('A') + byte(i))\n\t}\n\n\treturn buf\n}\n\nfunc TestStructRead(t *testing.T) ", "output": "{\n\tbuf := GetBytesBufferToFillTestStruct()\n\ts := TestStruct{Ui16: uint16('A'), Ui8_1: uint8(0)}\n\n\tif err := ReadStructBigEndian(&s, bytes.NewReader(buf.Bytes())); err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Read struct:\\n%s\\nFrom:\\n%q\\n\", s, buf.Bytes())\n}"} {"input": "package cleanpath\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n)\n\n\nfunc RemoveGoPath(path string) string {\n\tdirs := filepath.SplitList(os.Getenv(\"GOPATH\"))\n\tsort.Stable(longestFirst(dirs))\n\tfor _, dir := range dirs {\n\t\tsrcdir := filepath.Join(dir, \"src\")\n\t\trel, err := filepath.Rel(srcdir, path)\n\t\tif err == nil && !strings.HasPrefix(rel, \"..\"+string(filepath.Separator)) {\n\t\t\treturn rel\n\t\t}\n\t}\n\treturn path\n}\n\ntype longestFirst []string\n\nfunc (strs longestFirst) Len() int { return len(strs) }\n\nfunc (strs longestFirst) Swap(i, j int) { strs[i], strs[j] = strs[j], strs[i] }\n\nfunc (strs longestFirst) Less(i, j int) bool ", "output": "{ return len(strs[i]) > len(strs[j]) }"} {"input": "package heap\n\nimport (\n\t\"sync\"\n)\n\ntype Monitor struct {\n\towner interface{} \n\townerLock sync.Locker\n\tlock sync.Locker\n\tentryCount int\n\tcond *sync.Cond\n}\n\nfunc newMonitor() *Monitor {\n\tm := &Monitor{}\n\tm.ownerLock = &sync.Mutex{}\n\tm.lock = &sync.Mutex{}\n\tm.cond = sync.NewCond(m.lock)\n\treturn m\n}\n\nfunc (monitor *Monitor) Enter(thread interface{}) {\n\tmonitor.ownerLock.Lock()\n\tif monitor.owner == thread {\n\t\tmonitor.entryCount++\n\t\tmonitor.ownerLock.Unlock()\n\t\treturn\n\t} else {\n\t\tmonitor.ownerLock.Unlock()\n\t}\n\n\tmonitor.lock.Lock()\n\n\tmonitor.ownerLock.Lock()\n\tmonitor.owner = thread\n\tmonitor.entryCount = 1\n\tmonitor.ownerLock.Unlock()\n}\n\n\n\nfunc (monitor *Monitor) HasOwner(thread interface{}) bool {\n\tmonitor.ownerLock.Lock()\n\tisOwner := monitor.owner == thread\n\tmonitor.ownerLock.Unlock()\n\n\treturn isOwner\n}\n\nfunc (monitor *Monitor) Wait() {\n\tmonitor.ownerLock.Lock()\n\toldEntryCount := monitor.entryCount\n\toldOwner := monitor.owner\n\tmonitor.entryCount = 0\n\tmonitor.owner = nil\n\tmonitor.ownerLock.Unlock()\n\n\tmonitor.cond.Wait()\n\n\tmonitor.ownerLock.Lock()\n\tmonitor.entryCount = oldEntryCount\n\tmonitor.owner = oldOwner\n\tmonitor.ownerLock.Unlock()\n}\n\nfunc (monitor *Monitor) NotifyAll() {\n\tmonitor.cond.Broadcast()\n}\n\nfunc (monitor *Monitor) Exit(thread interface{}) ", "output": "{\n\tmonitor.ownerLock.Lock()\n\tvar _unlock bool\n\tif monitor.owner == thread {\n\t\tmonitor.entryCount--\n\t\tif monitor.entryCount == 0 {\n\t\t\tmonitor.owner = nil\n\t\t\t_unlock = true\n\t\t}\n\t}\n\tmonitor.ownerLock.Unlock()\n\n\tif _unlock {\n\t\tmonitor.lock.Unlock()\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/kataras/iris/httptest\"\n)\n\n\n\nfunc TestCustomContextNewImpl(t *testing.T) ", "output": "{\n\tapp := newApp()\n\te := httptest.New(t, app, httptest.URL(\"http://localhost:8080\"))\n\n\te.GET(\"/\").Expect().\n\t\tStatus(httptest.StatusOK).\n\t\tContentType(\"text/html\").\n\t\tBody().Equal(\"Hello from our *Context\")\n\n\texpectedName := \"iris\"\n\te.POST(\"/set\").WithFormField(\"name\", expectedName).Expect().\n\t\tStatus(httptest.StatusOK).\n\t\tBody().Equal(\"set session = \" + expectedName)\n\n\te.GET(\"/get\").Expect().\n\t\tStatus(httptest.StatusOK).\n\t\tBody().Equal(expectedName)\n}"} {"input": "package sipparser\n\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestCseq(t *testing.T) ", "output": "{\n\tsm := &SipMsg{}\n\tsm.parseCseq(\"100 INVITE\")\n\tif sm.Error != nil {\n\t\tt.Errorf(\"[TestCseq] Error parsing cseq: \\\"100 INVITE\\\". Received err: \" + sm.Error.Error())\n\t}\n\tif sm.Cseq.Digit != \"100\" {\n\t\tt.Errorf(\"[TestCseq] Error parsing cseq: \\\"100 INVITE\\\". Digit should be 100.\")\n\t}\n\tif sm.Cseq.Method != \"INVITE\" {\n\t\tt.Errorf(\"[TestCseq] Error parsing cseq: \\\"100 INVITE\\\". Method should be \\\"INVITE\\\".\")\n\t}\n}"} {"input": "package messages\n\nimport \"time\"\n\nconst nanosPerSecond = 1000000000\n\nfunc DurationToGoDuration(duration Duration) time.Duration {\n\tsecondNanos := duration.Seconds * nanosPerSecond\n\treturn time.Duration(secondNanos + int64(duration.Nanos))\n}\n\nfunc GoDurationToDuration(goDuration time.Duration) Duration {\n\tseconds := int64(goDuration / nanosPerSecond)\n\tnanos := int64(goDuration % nanosPerSecond)\n\treturn Duration{\n\t\tSeconds: seconds,\n\t\tNanos: nanos,\n\t}\n}\n\n\n\nfunc GoTimeToTimestamp(t time.Time) Timestamp {\n\tunixNanos := t.UnixNano()\n\tseconds := unixNanos / nanosPerSecond\n\tnanos := unixNanos % nanosPerSecond\n\n\treturn Timestamp{\n\t\tSeconds: seconds,\n\t\tNanos: nanos,\n\t}\n}\n\nfunc TimestampToGoTime(timestamp Timestamp) time.Time ", "output": "{\n\treturn time.Unix(timestamp.Seconds, timestamp.Nanos)\n}"} {"input": "package iso20022\n\n\ntype LinkageType3Choice struct {\n\n\tCode *LinkageType1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification30 `xml:\"Prtry\"`\n}\n\n\n\nfunc (l *LinkageType3Choice) AddProprietary() *GenericIdentification30 {\n\tl.Proprietary = new(GenericIdentification30)\n\treturn l.Proprietary\n}\n\nfunc (l *LinkageType3Choice) SetCode(value string) ", "output": "{\n\tl.Code = (*LinkageType1Code)(&value)\n}"} {"input": "package views\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\tui \"github.com/jroimartin/gocui\"\n)\n\nvar (\n\thelpWidth = 49\n\thelpHeight = 15\n\ttpl = `%s C-x means Control x`\n)\n\ntype help struct {\n\tname string\n\tcoords coords\n\tbody []byte\n}\n\nfunc newHelp(w, h int) *help {\n\treturn &help{\n\t\tname: \"help\",\n\t}\n}\n\nfunc getHelpCoords(g *ui.Gui) coords {\n\tmaxX, maxY := g.Size()\n\tx1 := maxX/2 - helpWidth/2\n\tx2 := maxX/2 + helpWidth/2\n\ty1 := maxY/2 - helpHeight/2\n\ty2 := maxY/2 + helpHeight/2 + helpHeight%2\n\treturn coords{x1: x1, y1: y1, x2: x2, y2: y2}\n}\n\nfunc (h *help) show(g *ui.Gui, v *ui.View, keys []key) error {\n\tv.Editable = false\n\tif h.body == nil {\n\t\th.body = h.getBody(keys)\n\t}\n\n\tvar err error\n\n\tcoords := getHelpCoords(g)\n\n\tv, err = g.SetView(\"help\", coords.x1, coords.y1, coords.x2, coords.y2)\n\tif err != ui.ErrUnknownView {\n\t\treturn err\n\t}\n\n\tv.Title = h.name\n\n\tv.Write([]byte(h.body))\n\t_, err = g.SetCurrentView(\"help\")\n\treturn err\n}\n\nfunc (h *help) hide(g *ui.Gui, v *ui.View) error {\n\tv.Clear()\n\treturn g.DeleteView(h.name)\n}\n\n\n\nfunc (h *help) getBody(keys []key) []byte ", "output": "{\n\tout := &bytes.Buffer{}\n\tfor _, key := range keys {\n\t\th := key.help\n\t\tif h.key != \"\" {\n\t\t\tfmt.Fprintf(out, fmt.Sprintf(\"%s %s\\n\", c3(h.key), c1(fmt.Sprintf(fmt.Sprintf(\"%%%ds\", helpWidth-len(h.key)-4), h.body))))\n\t\t}\n\t}\n\treturn []byte(fmt.Sprintf(tpl, out.String()))\n}"} {"input": "package render\n\nimport (\n\t\"runtime\"\n\t\"sync\"\n)\n\nvar (\n\trender_funcs chan func()\n\tpurge chan bool\n\tinit_once sync.Once\n)\n\n\n\n\nfunc Queue(f func()) {\n\trender_funcs <- f\n}\n\n\nfunc Purge() {\n\tpurge <- true\n\t<-purge\n}\n\nfunc Init() {\n\tinit_once.Do(func() {\n\t\tgo func() {\n\t\t\truntime.LockOSThread()\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase f := <-render_funcs:\n\t\t\t\t\tf()\n\t\t\t\tcase <-purge:\n\t\t\t\t\tfor {\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase f := <-render_funcs:\n\t\t\t\t\t\t\tf()\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tgoto purged\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tpurged:\n\t\t\t\t\tpurge <- true\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t})\n}\n\nfunc init() ", "output": "{\n\trender_funcs = make(chan func(), 1000)\n\tpurge = make(chan bool)\n}"} {"input": "package mackerel\n\n\ntype CheckStatus string\n\n\nconst (\n\tCheckStatusOK CheckStatus = \"OK\"\n\tCheckStatusWarning CheckStatus = \"WARNING\"\n\tCheckStatusCritical CheckStatus = \"CRITICAL\"\n\tCheckStatusUnknown CheckStatus = \"UNKNOWN\"\n)\n\n\ntype CheckReport struct {\n\tSource CheckSource `json:\"source\"`\n\tName string `json:\"name\"`\n\tStatus CheckStatus `json:\"status\"`\n\tMessage string `json:\"message\"`\n\tOccurredAt int64 `json:\"occurredAt\"`\n\tNotificationInterval uint `json:\"notificationInterval,omitempty\"`\n\tMaxCheckAttempts uint `json:\"maxCheckAttempts,omitempty\"`\n}\n\n\ntype CheckSource interface {\n\tCheckType() string\n\n\tisCheckSource()\n}\n\nconst checkTypeHost = \"host\"\n\n\nvar _ CheckSource = (*checkSourceHost)(nil)\n\n\n\nfunc (cs *checkSourceHost) isCheckSource() {}\n\ntype checkSourceHost struct {\n\tType string `json:\"type\"`\n\tHostID string `json:\"hostId\"`\n}\n\n\nfunc (cs *checkSourceHost) CheckType() string {\n\treturn checkTypeHost\n}\n\n\nfunc NewCheckSourceHost(hostID string) CheckSource {\n\treturn &checkSourceHost{\n\t\tType: checkTypeHost,\n\t\tHostID: hostID,\n\t}\n}\n\n\ntype CheckReports struct {\n\tReports []*CheckReport `json:\"reports\"`\n}\n\n\n\n\nfunc (c *Client) PostCheckReports(crs *CheckReports) error ", "output": "{\n\tresp, err := c.PostJSON(\"/api/v0/monitoring/checks/report\", crs)\n\tdefer closeResponse(resp)\n\treturn err\n}"} {"input": "package http\n\nimport (\n\t\"go-common/app/admin/main/app/model/language\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\n\nfunc languages(c *bm.Context) {\n\tc.JSON(langSvc.Languages(c))\n}\n\n\nfunc langByID(c *bm.Context) {\n\tv := &language.Param{}\n\tif err := c.Bind(v); err != nil {\n\t\treturn\n\t}\n\tc.JSON(langSvc.LangByID(c, v.ID))\n}\n\n\n\n\nfunc addOrup(c *bm.Context) ", "output": "{\n\tvar (\n\t\terr error\n\t\tv = &language.Param{}\n\t)\n\tif err = c.Bind(v); err != nil {\n\t\treturn\n\t}\n\tif v.ID > 0 {\n\t\terr = langSvc.Update(c, v)\n\t} else {\n\t\terr = langSvc.Insert(c, v)\n\t}\n\tc.JSON(nil, err)\n}"} {"input": "package git\n\nimport (\n\t\"gopkg.in/src-d/go-git.v4/plumbing\"\n)\n\nfunc (repo *Repository) getBlob(id SHA1) (*Blob, error) {\n\tencodedObj, err := repo.gogitRepo.Storer.EncodedObject(plumbing.AnyObject, id)\n\tif err != nil {\n\t\treturn nil, ErrNotExist{id.String(), \"\"}\n\t}\n\n\treturn &Blob{\n\t\tID: id,\n\t\tgogitEncodedObj: encodedObj,\n\t}, nil\n}\n\n\n\n\nfunc (repo *Repository) GetBlob(idStr string) (*Blob, error) ", "output": "{\n\tid, err := NewIDFromString(idStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn repo.getBlob(id)\n}"} {"input": "package configfiles\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\n\t\"k8s.io/apimachinery/pkg/runtime/serializer\"\n\t\"k8s.io/kubernetes/pkg/kubelet/apis/kubeletconfig\"\n\tkubeletscheme \"k8s.io/kubernetes/pkg/kubelet/apis/kubeletconfig/scheme\"\n\tutilcodec \"k8s.io/kubernetes/pkg/kubelet/kubeletconfig/util/codec\"\n\tutilfs \"k8s.io/kubernetes/pkg/util/filesystem\"\n)\n\nconst kubeletFile = \"kubelet\"\n\n\ntype Loader interface {\n\tLoad() (*kubeletconfig.KubeletConfiguration, error)\n}\n\n\ntype fsLoader struct {\n\tfs utilfs.Filesystem\n\tkubeletCodecs *serializer.CodecFactory\n\tconfigDir string\n}\n\n\n\n\nfunc (loader *fsLoader) Load() (*kubeletconfig.KubeletConfiguration, error) {\n\tpath := filepath.Join(loader.configDir, kubeletFile)\n\tdata, err := loader.fs.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read init config file %q, error: %v\", path, err)\n\t}\n\n\tif len(data) == 0 {\n\t\treturn nil, fmt.Errorf(\"init config file %q was empty, but some parameters are required\", path)\n\t}\n\n\tkc, err := utilcodec.DecodeKubeletConfiguration(loader.kubeletCodecs, data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresolveRelativePaths(kubeletconfig.KubeletConfigurationPathRefs(kc), loader.configDir)\n\treturn kc, nil\n}\n\n\nfunc resolveRelativePaths(paths []*string, root string) {\n\tfor _, path := range paths {\n\t\tif len(*path) > 0 && !filepath.IsAbs(*path) {\n\t\t\t*path = filepath.Join(root, *path)\n\t\t}\n\t}\n}\n\nfunc NewFsLoader(fs utilfs.Filesystem, configDir string) (Loader, error) ", "output": "{\n\t_, kubeletCodecs, err := kubeletscheme.NewSchemeAndCodecs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &fsLoader{\n\t\tfs: fs,\n\t\tkubeletCodecs: kubeletCodecs,\n\t\tconfigDir: configDir,\n\t}, nil\n}"} {"input": "package user\n\nimport \"github.com/openshift/origin/pkg/user/api\"\n\ntype DefaultUserInitStrategy struct {\n}\n\nfunc NewDefaultUserInitStrategy() Initializer {\n\treturn &DefaultUserInitStrategy{}\n}\n\n\n\n\nfunc (*DefaultUserInitStrategy) InitializeUser(identity *api.Identity, user *api.User) error ", "output": "{\n\tif identity.Extra != nil {\n\t\tif name, ok := identity.Extra[\"name\"]; ok && len(name) > 0 {\n\t\t\tuser.FullName = name\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package processors\n\nimport (\n\t\"context\"\n\n\t\"github.com/cloudevents/sdk-go/v2/event\"\n)\n\n\n\n\n\ntype Interface interface {\n\tProcess(ctx context.Context, e *event.Event) error\n\tNext() Interface\n}\n\n\ntype ChainableProcessor interface {\n\tInterface\n\n\tWithNext(ChainableProcessor) ChainableProcessor\n}\n\n\n\n\ntype BaseProcessor struct {\n\tn ChainableProcessor\n}\n\n\n\n\n\n\n\nfunc (p *BaseProcessor) WithNext(n ChainableProcessor) ChainableProcessor {\n\tp.n = n\n\treturn p.n\n}\n\n\nfunc ChainProcessors(first ChainableProcessor, rest ...ChainableProcessor) Interface {\n\tnext := first\n\tfor _, p := range rest {\n\t\tnext = next.WithNext(p)\n\t}\n\treturn first\n}\n\nvar noop = &noOpProcessor{}\n\ntype noOpProcessor struct{}\n\nfunc (p noOpProcessor) Process(_ context.Context, _ *event.Event) error {\n\treturn nil\n}\n\n\n\nfunc (p noOpProcessor) Next() Interface {\n\treturn nil\n}\n\nfunc (p *BaseProcessor) Next() Interface ", "output": "{\n\tif p.n == nil {\n\t\treturn noop\n\t}\n\treturn p.n\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\n\ntype Response struct {\n\tBody string `json:\",omitempty\"`\n\tError string `json:\",omitempty\"`\n}\n\n\nfunc (r Response) String() string {\n\tb, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Print(\"Bad marshalling:\", err)\n\t\treturn \"\"\n\t}\n\n\treturn string(b)\n}\n\nfunc ipPrint(r *http.Request, v ...interface{}) {\n\ts := fmt.Sprintf(\"%s %s %s: \", r.RemoteAddr, r.Method, r.URL)\n\tb := make([]interface{}, 0, len(v)+1)\n\tb = append(b, s)\n\tb = append(b, v...)\n\tlog.Print(b...)\n}\n\n\n\n\n\n\nfunc sendResponseToClient(w http.ResponseWriter, body string, err string) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfmt.Fprint(w, Response{body, err})\n}\n\nfunc logHttpAccess(handler http.Handler) http.Handler ", "output": "{\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tipPrint(r, \"request\")\n\t\thandler.ServeHTTP(w, r)\n\t})\n}"} {"input": "package paystack\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestChargeServiceCheckPending(t *testing.T) {\n\tbankAccount := BankAccount{\n\t\tCode: \"057\",\n\t\tAccountNumber: \"0000000000\",\n\t}\n\n\tcharge := ChargeRequest{\n\t\tEmail: \"your_own_email_here@gmail.com\",\n\t\tAmount: 10000,\n\t\tBank: &bankAccount,\n\t\tBirthday: \"1999-12-31\",\n\t}\n\n\tresp, err := c.Charge.Create(&charge)\n\tif err != nil {\n\t\tt.Errorf(\"Create charge returned error: %v\", err)\n\t}\n\n\tif resp[\"reference\"] == \"\" {\n\t\tt.Error(\"Missing charge reference\")\n\t}\n\n\tresp2, err := c.Charge.CheckPending(resp[\"reference\"].(string))\n\tif err != nil {\n\t\tt.Errorf(\"Check pending charge returned error: %v\", err)\n\t}\n\n\tif resp2[\"status\"] == \"\" {\n\t\tt.Error(\"Missing charge pending status\")\n\t}\n\n\tif resp2[\"reference\"] == \"\" {\n\t\tt.Error(\"Missing charge pending reference\")\n\t}\n}\n\nfunc TestChargeServiceCreate(t *testing.T) ", "output": "{\n\tbankAccount := BankAccount{\n\t\tCode: \"057\",\n\t\tAccountNumber: \"0000000000\",\n\t}\n\n\tcharge := ChargeRequest{\n\t\tEmail: \"your_own_email_here@gmail.com\",\n\t\tAmount: 10000,\n\t\tBank: &bankAccount,\n\t\tBirthday: \"1999-12-31\",\n\t}\n\n\tresp, err := c.Charge.Create(&charge)\n\tif err != nil {\n\t\tt.Errorf(\"Create Charge returned error: %v\", err)\n\t}\n\n\tif resp[\"reference\"] == \"\" {\n\t\tt.Error(\"Missing transaction reference\")\n\t}\n}"} {"input": "package r\n\n\n\n\n\n\n\nfunc f() ", "output": "{\n\tvar i int\n\tvar s string\n\tfor len(s) < len(s) {\n\t\ti++\n\t\ts = \"a\"\n\t}\n\tvar b bool\n\tvar sa []string\n\tfor true {\n\t\tsa = []string{\"\"}\n\t\tfor b || i == 0 {\n\t\t}\n\t\tb = !b\n\t\t_ = sa\n\t}\n}"} {"input": "package x11\n\nimport (\n\t\"C\"\n\t\"unsafe\"\n)\n\ntype SelectionEvent C.XSelectionEvent\n\nfunc (evt *SelectionEvent) Requestor() Window {\n\treturn Window(evt.requestor)\n}\n\nfunc (evt *SelectionEvent) Selection() Atom {\n\treturn Atom(evt.selection)\n}\n\nfunc (evt *SelectionEvent) Target() Atom {\n\treturn Atom(evt.target)\n}\n\n\n\nfunc (evt *SelectionEvent) When() C.Time {\n\treturn evt.time\n}\n\nfunc (evt *SelectionEvent) ToEvent() *Event {\n\treturn (*Event)(unsafe.Pointer(evt))\n}\n\nfunc (evt *SelectionEvent) Property() Atom ", "output": "{\n\treturn Atom(evt.property)\n}"} {"input": "package system\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"k8s.io/kubernetes/pkg/util/errors\"\n)\n\n\ntype Validator interface {\n\tName() string\n\tValidate(SysSpec) error\n}\n\n\nvar validators = []Validator{\n\t&OSValidator{},\n\t&KernelValidator{},\n\t&CgroupsValidator{},\n\t&DockerValidator{},\n}\n\n\n\n\nfunc Validate() error ", "output": "{\n\tvar errs []error\n\tspec := DefaultSysSpec\n\tfor _, v := range validators {\n\t\tglog.Infof(\"Validating %s...\", v.Name())\n\t\terrs = append(errs, v.Validate(spec))\n\t}\n\treturn errors.NewAggregate(errs)\n}"} {"input": "package config\n\nimport (\n\t\"os\"\n)\n\ntype config struct {\n\tBasePath string\n\tDestPath string\n}\n\nvar current = config{}\n\n\nfunc GetBasePath() string {\n\treturn current.BasePath\n}\n\n\n\n\nfunc init() {\n\tcurrent.BasePath = \"./\"\n\tif len(os.Args) > 1 {\n\t\tcurrent.BasePath = os.Args[1]\n\t}\n}\n\nfunc GetDestPath() string ", "output": "{\n\treturn current.DestPath\n}"} {"input": "package msgraph\n\nimport \"context\"\n\n\ntype WorkbookFunctionsProductRequestBuilder struct{ BaseRequestBuilder }\n\n\n\n\n\ntype WorkbookFunctionsProductRequest struct{ BaseRequest }\n\n\nfunc (b *WorkbookFunctionsProductRequestBuilder) Request() *WorkbookFunctionsProductRequest {\n\treturn &WorkbookFunctionsProductRequest{\n\t\tBaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},\n\t}\n}\n\n\nfunc (r *WorkbookFunctionsProductRequest) Post(ctx context.Context) (resObj *WorkbookFunctionResult, err error) {\n\terr = r.JSONRequest(ctx, \"POST\", \"\", r.requestObject, &resObj)\n\treturn\n}\n\nfunc (b *WorkbookFunctionsRequestBuilder) Product(reqObj *WorkbookFunctionsProductRequestParameter) *WorkbookFunctionsProductRequestBuilder ", "output": "{\n\tbb := &WorkbookFunctionsProductRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.BaseRequestBuilder.baseURL += \"/product\"\n\tbb.BaseRequestBuilder.requestObject = reqObj\n\treturn bb\n}"} {"input": "package worker_test\n\nimport (\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/ffloyd/evergrid-go/simenv\"\n\t\"github.com/ffloyd/evergrid-go/simulator/comm\"\n)\n\ntype SenderAgent struct {\n\tname string\n\tfsm simenv.AgentFSM\n\tsimenv *simenv.SimEnv\n\n\tworkerName string\n\trequests []interface{}\n\n\tlog *logrus.Entry\n}\n\nfunc NewSenderAgent(name string, worker string, requests []interface{}, logContext *logrus.Entry) *SenderAgent {\n\treturn &SenderAgent{\n\t\tname: name,\n\t\trequests: requests,\n\t\tworkerName: worker,\n\t\tlog: logContext,\n\t}\n}\n\nfunc (sa *SenderAgent) Name() string {\n\treturn sa.name\n}\n\n\n\nfunc (sa *SenderAgent) Send(msg interface{}) chan interface{} {\n\tpanic(\"No implementation\")\n}\n\nfunc (sa *SenderAgent) work() {\n\treqIndex := 0\n\tworker := sa.simenv.Find(sa.workerName)\n\n\tfor {\n\t\tsa.fsm.ToReady()\n\t\tsa.fsm.ToWorking()\n\t\tif reqIndex < len(sa.requests) {\n\t\t\tbusyStatus := <-worker.Send(comm.WorkerBusy{})\n\t\t\tswitch value := busyStatus.(type) {\n\t\t\tcase bool:\n\t\t\t\tif !value {\n\t\t\t\t\t<-worker.Send(sa.requests[reqIndex])\n\t\t\t\t\treqIndex++\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tsa.log.Panic(\"Invalid worker response\")\n\t\t\t}\n\t\t} else {\n\t\t\tsa.fsm.SetStopFlag(true)\n\t\t}\n\t\tsa.fsm.ToIdle()\n\t\t<-sa.fsm.ToDoneChan()\n\t}\n}\n\nfunc (sa *SenderAgent) Run(env *simenv.SimEnv) simenv.AgentChans ", "output": "{\n\tsa.simenv = env\n\tsa.fsm = *simenv.NewAgentFSM(sa.log.WithFields(logrus.Fields{\n\t\t\"agent\": sa.Name(),\n\t\t\"tick\": env.CurrentTick(),\n\t}))\n\tgo sa.work()\n\treturn sa.fsm.Chans()\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\n\tv3 \"github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3\"\n\t\"github.com/rancher/rancher/pkg/ref\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc GetRuleID(groupID string, ruleName string) string {\n\treturn fmt.Sprintf(\"%s_%s\", groupID, ruleName)\n}\n\n\n\nfunc GetAlertManagerSecretName(appName string) string {\n\treturn fmt.Sprintf(\"alertmanager-%s\", appName)\n}\n\nfunc GetAlertManagerDaemonsetName(appName string) string {\n\treturn fmt.Sprintf(\"alertmanager-%s\", appName)\n}\n\nfunc formatProjectDisplayName(projectDisplayName, projectID string) string {\n\treturn fmt.Sprintf(\"%s (ID: %s)\", projectDisplayName, projectID)\n}\n\nfunc formatClusterDisplayName(clusterDisplayName, clusterID string) string {\n\treturn fmt.Sprintf(\"%s (ID: %s)\", clusterDisplayName, clusterID)\n}\n\nfunc GetClusterDisplayName(clusterName string, clusterLister v3.ClusterLister) string {\n\tcluster, err := clusterLister.Get(\"\", clusterName)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to get cluster for %s: %v\", clusterName, err)\n\t\treturn clusterName\n\t}\n\n\treturn formatClusterDisplayName(cluster.Spec.DisplayName, clusterName)\n}\n\nfunc GetProjectDisplayName(projectID string, projectLister v3.ProjectLister) string {\n\tclusterName, projectName := ref.Parse(projectID)\n\tproject, err := projectLister.Get(clusterName, projectName)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to get project %s: %v\", projectID, err)\n\t\treturn projectID\n\t}\n\n\treturn formatProjectDisplayName(project.Spec.DisplayName, projectID)\n}\n\nfunc GetGroupID(namespace, name string) string ", "output": "{\n\treturn fmt.Sprintf(\"%s:%s\", namespace, name)\n}"} {"input": "package helpers\n\nimport (\n\t\"net/http\"\n\t\"context\"\n)\n\nvar Context = ctxHelpers{}\n\ntype ctxHelpers struct {\n}\n\n\n\n\nfunc (h ctxHelpers) AddValueToRequest(r *http.Request, key, value interface{}) ", "output": "{\n\t*r = *r.WithContext(context.WithValue(r.Context(), key, value))\n}"} {"input": "package gospell\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\ntype Match struct {\n\tWord []rune\n\tDistance int\n\tWeight int\n}\n\ntype Matches []Match\n\nfunc (m1 Match) Equal(m2 Match) bool {\n\treturn string(m1.Word) == string(m2.Word) &&\n\t\tm1.Distance == m2.Distance && m1.Weight == m2.Weight\n}\n\nfunc (m Match) String() string {\n\treturn fmt.Sprintf(\"{%v %d %d}\", string(m.Word), m.Distance, m.Weight)\n}\n\nfunc (s Matches) Len() int { return len(s) }\nfunc (s Matches) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\n\n\n\ntype ByDistance struct {\n\tMatches\n}\n\nfunc (s ByDistance) Less(i, j int) bool {\n\td1 := s.Matches[i].Distance\n\td2 := s.Matches[j].Distance\n\tif d1 == d2 {\n\t\treturn string(s.Matches[i].Word) < string(s.Matches[j].Word)\n\t}\n\treturn d1 < d2\n}\n\nfunc (m *Match) update(r rune, distance, weight int) Match {\n\tm2 := Match{}\n\tif r != 0 {\n\t\tm2.Word = []rune{r}\n\t\tm2.Word = append(m2.Word, m.Word...)\n\t} else {\n\t\tm2.Word = m.Word[:]\n\t}\n\tm2.Distance = m.Distance + distance\n\tm2.Weight = m.Weight + weight\n\treturn m2\n}\n\nfunc (s Matches) Strings() []string ", "output": "{\n\tstrings := make([]string, len(s))\n\tsort.Sort(ByDistance{s})\n\tfor i, r := range s {\n\t\tstrings[i] = string(r.Word)\n\t}\n\n\treturn strings\n}"} {"input": "package chart\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\tassert \"github.com/blendlabs/go-assert\"\n)\n\nfunc TestSequenceFloat64(t *testing.T) {\n\tassert := assert.New(t)\n\n\tasc := Sequence.Float64(1.0, 10.0)\n\tassert.Len(asc, 10)\n\n\tdesc := Sequence.Float64(10.0, 1.0)\n\tassert.Len(desc, 10)\n}\n\nfunc TestSequenceMarketHours(t *testing.T) {\n\tassert := assert.New(t)\n\n\ttoday := time.Date(2016, 07, 01, 12, 0, 0, 0, Date.Eastern())\n\tmh := Sequence.MarketHours(today, today, NYSEOpen, NYSEClose, Date.IsNYSEHoliday)\n\tassert.Len(mh, 8)\n\tassert.Equal(Date.Eastern(), mh[0].Location())\n}\n\n\n\nfunc TestSequenceMarketQuarters(t *testing.T) ", "output": "{\n\tassert := assert.New(t)\n\ttoday := time.Date(2016, 07, 01, 12, 0, 0, 0, Date.Eastern())\n\tmh := Sequence.MarketHourQuarters(today, today, NYSEOpen, NYSEClose, Date.IsNYSEHoliday)\n\tassert.Len(mh, 4)\n\tassert.Equal(9, mh[0].Hour())\n\tassert.Equal(30, mh[0].Minute())\n\tassert.Equal(Date.Eastern(), mh[0].Location())\n\n\tassert.Equal(12, mh[1].Hour())\n\tassert.Equal(00, mh[1].Minute())\n\tassert.Equal(Date.Eastern(), mh[1].Location())\n\n\tassert.Equal(14, mh[2].Hour())\n\tassert.Equal(00, mh[2].Minute())\n\tassert.Equal(Date.Eastern(), mh[2].Location())\n}"} {"input": "package yaml\n\nimport (\n\t\"fmt\"\n)\n\nfunc (this *Job) Name() JobKey {\n\treturn this.name\n}\n\nfunc (this *Job) Validate(c Context) error {\n\treturn nil\n}\n\nfunc (this *Job) InDesiredState(c Context) (bool, error) {\n\treturn true, nil\n}\n\nfunc (this *Job) Prepare(c Context) error {\n\treturn nil\n}\n\nfunc (this *Job) Execute(c Context) error {\n\tc.log(\"Executing Job %s\", this.name)\n\n\treturn nil\n}\n\n\n\nfunc (this *Job) get_task() *task {\n\tif this.task == nil {\n\t\tthis.task = alloc_task(this)\n\t\tthis.task.description = fmt.Sprintf(\"Job[%s]\", this.name)\n\n\t\tfor _, container := range this.container_instances {\n\t\t\tthis.task.DependsOn(container.get_task())\n\t\t}\n\t}\n\treturn this.task\n}\n\nfunc (this *Job) Finish(c Context) error ", "output": "{\n\treturn nil\n}"} {"input": "package testutil\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n)\n\n\n\n\n\n\n\nfunc WithChdirTmpdir(fn func()) {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tWithTmpdir(func(tmpDir string) {\n\t\tif err := os.Chdir(tmpDir); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer os.Chdir(cwd)\n\t\tfn()\n\t})\n}\n\nfunc WithTmpdir(fn func(tmpDir string)) ", "output": "{\n\ttmpBase := \"/tmp/hitch-test/\"\n\terr := os.MkdirAll(tmpBase, os.FileMode(0755)|os.ModeSticky)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ttmpDir, err := ioutil.TempDir(tmpBase, \"\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer os.RemoveAll(tmpDir)\n\tfn(tmpDir)\n}"} {"input": "package mailgun\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/config\"\n\t\"github.com/hashicorp/terraform/helper/schema\"\n\t\"github.com/hashicorp/terraform/terraform\"\n\t\"github.com/pearkes/mailgun\"\n)\n\nvar testAccProviders map[string]terraform.ResourceProvider\nvar testAccProvider *schema.Provider\n\nfunc init() {\n\ttestAccProvider = Provider().(*schema.Provider)\n\ttestAccProviders = map[string]terraform.ResourceProvider{\n\t\t\"mailgun\": testAccProvider,\n\t}\n}\n\nfunc TestProvider(t *testing.T) {\n\tif err := Provider().(*schema.Provider).InternalValidate(); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n}\n\nfunc TestProvider_impl(t *testing.T) {\n\tvar _ terraform.ResourceProvider = Provider()\n}\n\nfunc TestProviderConfigure(t *testing.T) {\n\tvar expectedKey string\n\n\tif v := os.Getenv(\"MAILGUN_API_KEY\"); v != \"\" {\n\t\texpectedKey = v\n\t} else {\n\t\texpectedKey = \"foo\"\n\t}\n\n\traw := map[string]interface{}{\n\t\t\"api_key\": expectedKey,\n\t}\n\n\trawConfig, err := config.NewRawConfig(raw)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\trp := Provider().(*schema.Provider)\n\terr = rp.Configure(terraform.NewResourceConfig(rawConfig))\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tconfig := rp.Meta().(*mailgun.Client)\n\tif config.ApiKey != expectedKey {\n\t\tt.Fatalf(\"bad: %#v\", config)\n\t}\n}\n\n\n\nfunc testAccPreCheck(t *testing.T) ", "output": "{\n\tif v := os.Getenv(\"MAILGUN_API_KEY\"); v == \"\" {\n\t\tt.Fatal(\"MAILGUN_API_KEY must be set for acceptance tests\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"sync\"\n)\n\nvar count int\nvar wg sync.WaitGroup\nvar rw sync.RWMutex\n\nfunc main() {\n\twg.Add(10)\n\n\tfor i := 0; i < 5; i++ {\n\t\tgo read(i)\n\t}\n\tfor i := 0; i < 5; i++ {\n\t\tgo write(i)\n\t}\n\twg.Wait()\n}\n\n\n\nfunc write(n int) {\n\trw.Lock()\n\tfmt.Printf(\"写 goroutine %d 正在写入...\\n\", n)\n\tv := rand.Intn(1000)\n\tcount = v\n\tfmt.Printf(\"写 goroutine %d 写入结束,新值为:%d\\n\", n, v)\n\twg.Done()\n\trw.Unlock()\n}\n\nfunc read(n int) ", "output": "{\n\trw.RLock()\n\tfmt.Printf(\"读 goroutine %d 正在读取...\\n\", n)\n\n\tv := count\n\n\tfmt.Printf(\"读 goroutine %d 读取结束,值为:%d...\\n\", n, v)\n\twg.Done()\n\trw.RUnlock()\n}"} {"input": "package main\n\nimport \"github.com/augustoroman/serial_lcd\"\n\ntype FakeLcd struct{}\n\nfunc (f FakeLcd) SetBG(r, g, b uint8) error { return nil }\nfunc (f FakeLcd) SetOn(On bool) error { return nil }\nfunc (f FakeLcd) SetBrightness(b uint8) error { return nil }\nfunc (f FakeLcd) SetContrast(c uint8) error { return nil }\nfunc (f FakeLcd) SetAutoscroll(On bool) error { return nil }\nfunc (f FakeLcd) SetSize(cols, rows uint8) error { return nil }\nfunc (f FakeLcd) Clear() error { return nil }\nfunc (f FakeLcd) Home() error { return nil }\nfunc (f FakeLcd) MoveTo(col, row uint8) error { return nil }\nfunc (f FakeLcd) MoveForward() error { return nil }\nfunc (f FakeLcd) MoveBack() error { return nil }\nfunc (f FakeLcd) Write(b []byte) (int, error) { return len(b), nil }\n\n\n\nfunc (f FakeLcd) CreateCustomChar(spot uint8, c serial_lcd.Char) error ", "output": "{ return nil }"} {"input": "package ig\n\nimport \"fmt\"\n\n\nfunc (ic *IntelliClimate) SetTempTarget(target float64) error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\nfunc (ic *IntelliClimate) SetCO2Target(target float64) error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\n\n\n\nfunc (ic *IntelliClimate) EnableCO2Dosing() error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\nfunc (ic *IntelliClimate) DisableCO2Dosing() error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\nfunc (ic *IntelliClimate) SetRHTarget(target float64) error ", "output": "{\n\treturn fmt.Errorf(\"not implemented\")\n}"} {"input": "package servenv\n\nimport (\n\t\"github.com/youtube/vitess/go/vt/logutil\"\n)\n\n\n\nfunc init() ", "output": "{\n\tonInit(func() {\n\t\tgo logutil.PurgeLogs()\n\t})\n\n}"} {"input": "package allocator\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com/containernetworking/cni/pkg/types\"\n)\n\n\ntype IPAMConfig struct {\n\tName string\n\tType string `json:\"type\"`\n\tRangeStart net.IP `json:\"rangeStart\"`\n\tRangeEnd net.IP `json:\"rangeEnd\"`\n\tSubnet types.IPNet `json:\"subnet\"`\n\tGateway net.IP `json:\"gateway\"`\n\tRoutes []types.Route `json:\"routes\"`\n\tDataDir string `json:\"dataDir\"`\n\tResolvConf string `json:\"resolvConf\"`\n\tArgs *IPAMArgs `json:\"-\"`\n}\n\ntype IPAMArgs struct {\n\ttypes.CommonArgs\n\tIP net.IP `json:\"ip,omitempty\"`\n}\n\ntype Net struct {\n\tName string `json:\"name\"`\n\tIPAM *IPAMConfig `json:\"ipam\"`\n}\n\n\n\n\nfunc LoadIPAMConfig(bytes []byte, args string) (*IPAMConfig, error) ", "output": "{\n\tn := Net{}\n\tif err := json.Unmarshal(bytes, &n); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif args != \"\" {\n\t\tn.IPAM.Args = &IPAMArgs{}\n\t\terr := types.LoadArgs(args, n.IPAM.Args)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif n.IPAM == nil {\n\t\treturn nil, fmt.Errorf(\"IPAM config missing 'ipam' key\")\n\t}\n\n\tn.IPAM.Name = n.Name\n\n\treturn n.IPAM, nil\n}"} {"input": "package accessory\n\nimport (\n\t\"github.com/brutella/hc/service\"\n)\n\n\ntype Camera struct {\n\t*Accessory\n\tControl *service.CameraControl\n\tStreamManagement1 *service.CameraRTPStreamManagement\n\tStreamManagement2 *service.CameraRTPStreamManagement\n}\n\n\n\n\nfunc NewCamera(info Info) *Camera ", "output": "{\n\tacc := Camera{}\n\tacc.Accessory = New(info, TypeIPCamera)\n\tacc.Control = service.NewCameraControl()\n\tacc.AddService(acc.Control.Service)\n\n\tacc.StreamManagement1 = service.NewCameraRTPStreamManagement()\n\tacc.StreamManagement2 = service.NewCameraRTPStreamManagement()\n\tacc.AddService(acc.StreamManagement1.Service)\n\n\treturn &acc\n}"} {"input": "package config\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar (\n\tCurrent = Version{\n\t\tMajor: 0,\n\t\tMinor: 15,\n\t\tPatch: 1,\n\t}\n\n\tFirst = Version{\n\t\t0, 10, 4,\n\t}\n)\n\n\ntype Version struct {\n\tMajor int `json:\"major\"`\n\tMinor int `json:\"minor\"`\n\tPatch int `json:\"patch\"`\n}\n\n\nfunc VersionFromString(s string) Version {\n\tvs := strings.Split(s, \".\")\n\n\tif len(vs) < 3 {\n\n\t\treturn First\n\t}\n\n\ttoInt := func(s string) int {\n\t\ti, err := strconv.Atoi(s)\n\t\tif err != nil {\n\t\t\treturn 0\n\t\t}\n\t\treturn i\n\t}\n\n\treturn Version{toInt(vs[0]), toInt(vs[1]), toInt(vs[2])}\n}\n\n\nfunc (v Version) String() string {\n\treturn fmt.Sprintf(\"%d.%d.%d\", v.Major, v.Minor, v.Patch)\n}\n\n\n\n\nfunc (v Version) Greater(x Version) bool ", "output": "{\n\tif v.Major > x.Major {\n\t\treturn true\n\t}\n\n\tif v.Major == x.Major {\n\t\tif v.Minor > x.Minor {\n\t\t\treturn true\n\t\t}\n\n\t\tif v.Minor == x.Minor {\n\t\t\tif v.Patch > x.Patch {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\treturn false\n\t\t}\n\t\treturn false\n\t}\n\n\treturn false\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc main() {\n\tsayHello(\"world\")\n}\n\nfunc sayHello(s string) ", "output": "{\n\tfmt.Println(\"hello \" + s)\n}"} {"input": "package messages\n\nimport \"time\"\n\nconst nanosPerSecond = 1000000000\n\nfunc DurationToGoDuration(duration Duration) time.Duration {\n\tsecondNanos := duration.Seconds * nanosPerSecond\n\treturn time.Duration(secondNanos + int64(duration.Nanos))\n}\n\nfunc GoDurationToDuration(goDuration time.Duration) Duration {\n\tseconds := int64(goDuration / nanosPerSecond)\n\tnanos := int64(goDuration % nanosPerSecond)\n\treturn Duration{\n\t\tSeconds: seconds,\n\t\tNanos: nanos,\n\t}\n}\n\nfunc TimestampToGoTime(timestamp Timestamp) time.Time {\n\treturn time.Unix(timestamp.Seconds, timestamp.Nanos)\n}\n\n\n\nfunc GoTimeToTimestamp(t time.Time) Timestamp ", "output": "{\n\tunixNanos := t.UnixNano()\n\tseconds := unixNanos / nanosPerSecond\n\tnanos := unixNanos % nanosPerSecond\n\n\treturn Timestamp{\n\t\tSeconds: seconds,\n\t\tNanos: nanos,\n\t}\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realIAMInstanceProfile IAMInstanceProfile\n\n\nfunc (o *IAMInstanceProfile) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realIAMInstanceProfile\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = IAMInstanceProfile(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &IAMInstanceProfile{}\n\n\nfunc (o *IAMInstanceProfile) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\nvar _ fi.HasName = &IAMInstanceProfile{}\n\n\nfunc (o *IAMInstanceProfile) GetName() *string {\n\treturn o.Name\n}\n\n\nfunc (o *IAMInstanceProfile) SetName(name string) {\n\to.Name = &name\n}\n\n\n\n\nfunc (o *IAMInstanceProfile) String() string ", "output": "{\n\treturn fi.TaskAsString(o)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/dancannon/gorethink\"\n\t\"github.com/go-martini/martini\"\n\t\"github.com/martini-contrib/binding\"\n\t\"github.com/martini-contrib/render\"\n\t\"log\"\n\t\"mussh/resources/command\"\n\t\"mussh/resources/execution\"\n\t\"mussh/resources/group\"\n\t\"mussh/resources/server\"\n\t\"net/http\"\n\t\"time\"\n)\n\nfunc main() {\n\tsession := connectToDb()\n\n\tm := martini.Classic()\n\tm.Use(render.Renderer())\n\tm.Use(func(res http.ResponseWriter, req *http.Request) {\n\t\tres.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\t\tres.Header().Add(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, DELETE, OPTIONS\")\n\t})\n\tm.Use(martini.Static(\"public\"))\n\n\tm.Map(session)\n\tm.Action(getRouter())\n\n\tlog.Println(\"listening on port: 7979\")\n\thttp.ListenAndServe(\":7979\", m)\n}\n\nfunc connectToDb() *gorethink.Session {\n\tsession, err := gorethink.Connect(gorethink.ConnectOpts{\n\t\tAddress: \"localhost:28015\",\n\t\tDatabase: \"mussh\",\n\t\tMaxIdle: 10,\n\t\tIdleTimeout: time.Second * 10,\n\t})\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn session\n}\n\n\n\nfunc getRouter() martini.Handler ", "output": "{\n\tr := martini.NewRouter()\n\n\tr.Get(\"/servers\", server.Get)\n\tr.Post(\"/servers\", binding.Bind(server.Server{}), server.Post)\n\tr.Delete(\"/servers/:id\", server.Delete)\n\n\tr.Get(\"/groups\", group.GetWithServer)\n\tr.Post(\"/groups\", binding.Bind(group.Group{}), group.Post)\n\tr.Delete(\"/groups/:id\", group.Delete)\n\n\tr.Get(\"/commands\", command.Get)\n\tr.Post(\"/commands\", binding.Bind(command.Command{}), command.Post)\n\tr.Delete(\"/commands/:id\", command.Delete)\n\n\tr.Get(\"/executions\", execution.Get)\n\n\tr.Options(\"**\", func(r render.Render) {\n\t\tr.Status(http.StatusOK)\n\t})\n\n\treturn r.Handle\n}"} {"input": "package hashcash\n\nimport (\n\t\"encoding/hex\"\n\t\"testing\"\n)\n\nfunc TestBitCount(t *testing.T) {\n\tc := BitCount([32]byte{0x00, 0x00, 0x08, 0x02})\n\tif c != 20 {\n\t\tt.Error(\"Count error\")\n\t}\n}\n\nfunc TestHashCash(t *testing.T) {\n\td := []byte(\"abcefghi\")\n\tn, ok := ComputeNonce(d, 10, 0, 0)\n\tif !ok {\n\t\tt.Error(\"No match found\")\n\t}\n\tif hex.EncodeToString(n) != \"b301000000000000\" {\n\t\tt.Errorf(\"Nonce error b301000000000000 != %s\", hex.EncodeToString(n))\n\t}\n}\n\nfunc TestComputeParallel(t *testing.T) {\n\td := []byte(\"abcefghi\")\n\tbits := byte(21)\n\tnonce, _ := ComputeNonceSelect(d, bits, 0, 0) \n\tok, _ := TestNonce(d, nonce, bits)\n\tif !ok {\n\t\tt.Error(\"No Nonce found\")\n\t}\n}\n\n\n\nfunc TestTestNonce(t *testing.T) ", "output": "{\n\td := []byte(\"abcefghi\")\n\tn := []byte{0x09, 0x0e, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00}\n\tok, _ := TestNonce(d, n, 20)\n\tif !ok {\n\t\tt.Error(\"Nonce verification failed\")\n\t}\n\tn = []byte{0x09, 0x0e, 0x28, 0x00, 0x00, 0x00, 0x00, 0x01}\n\tok, c := TestNonce(d, n, 20)\n\tif ok {\n\t\tt.Errorf(\"Nonce verification MUST fail: %d < 20\", c)\n\t}\n}"} {"input": "package armrecoveryservicesbackup_test\n\nimport (\n\t\"context\"\n\t\"log\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/recoveryservices/armrecoveryservicesbackup\"\n)\n\n\nfunc ExampleBackupEnginesClient_List() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armrecoveryservicesbackup.NewBackupEnginesClient(\"\", cred, nil)\n\tpager := client.List(\"\",\n\t\t\"\",\n\t\t&armrecoveryservicesbackup.BackupEnginesClientListOptions{Filter: nil,\n\t\t\tSkipToken: nil,\n\t\t})\n\tfor {\n\t\tnextResult := pager.NextPage(ctx)\n\t\tif err := pager.Err(); err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tif !nextResult {\n\t\t\tbreak\n\t\t}\n\t\tfor _, v := range pager.PageResponse().Value {\n\t\t\tlog.Printf(\"Pager result: %#v\\n\", v)\n\t\t}\n\t}\n}\n\n\n\n\nfunc ExampleBackupEnginesClient_Get() ", "output": "{\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armrecoveryservicesbackup.NewBackupEnginesClient(\"\", cred, nil)\n\tres, err := client.Get(ctx,\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t&armrecoveryservicesbackup.BackupEnginesClientGetOptions{Filter: nil,\n\t\t\tSkipToken: nil,\n\t\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Response result: %#v\\n\", res.BackupEnginesClientGetResult)\n}"} {"input": "package cmd\n\nimport (\n\t\"flag\"\n\t\"testing\"\n\n\telastico \"elastico\"\n\n\t\"github.com/codegangsta/cli\"\n)\n\n\n\nfunc TestSearch(t *testing.T) ", "output": "{\n\tapp := cli.NewApp()\n\tif val, err := elastico.New(\"http://127.0.0.1:9200/\"); err != nil {\n\t\tt.Fatal(err)\n\t} else {\n\t\te = val\n\t}\n\n\tglobalSet := flag.NewFlagSet(\"test\", 0)\n\tglobalSet.Set(\"index\", \"remco2\")\n\tglobalSet.Set(\"type\", \"remco2\")\n\tglobalCtx := cli.NewContext(app, globalSet, nil)\n\n\tset := flag.NewFlagSet(\"test\", 0)\n\tset.Parse([]string{\"-size\", \"10\"})\n\n\tc := cli.NewContext(nil, set, globalCtx)\n\n\trun(runSearch)(c)\n}"} {"input": "\n\nfunc maxProfit(prices []int) int ", "output": "{\n n := len(prices)\n if n < 2 {\n return 0\n }\n \n maxProfit := 0\n minBuyPrice := prices[0]\n for i := 1; i < n; i++ {\n if prices[i] - minBuyPrice > maxProfit {\n maxProfit = prices[i] - minBuyPrice\n }\n if prices[i] < minBuyPrice {\n minBuyPrice = prices[i]\n }\n }\n \n return maxProfit\n}"} {"input": "package dataflow\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"go-common/app/interface/main/app-interface/conf\"\n\t\"go-common/library/log\"\n\t\"go-common/library/log/infoc\"\n)\n\n\ntype Service struct {\n\tc *conf.Config\n\tinfoc *infoc.Infoc\n}\n\n\n\n\nfunc (s *Service) Report(c context.Context, eventID, eventType, buvid, fts, messageInfo string, now time.Time) (err error) {\n\tif err = s.infoc.Info(strconv.FormatInt(now.Unix(), 10), eventID, eventType, buvid, fts, messageInfo); err != nil {\n\t\tlog.Error(\"s.infoc2.Info(%v,%v,%v,%v,%v,%v) error(%v)\", strconv.FormatInt(now.Unix(), 10), eventID, eventType, buvid, fts, messageInfo, err)\n\t}\n\treturn\n}\n\nfunc New(c *conf.Config) (s *Service) ", "output": "{\n\ts = &Service{\n\t\tc: c,\n\t\tinfoc: infoc.New(c.Infoc),\n\t}\n\treturn\n}"} {"input": "package comm\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestOutcome_String(t *testing.T) {\n\tassert.Equal(t, \"SUCCESS\", Success.String())\n\tassert.Equal(t, \"ERROR\", Error.String())\n}\n\nfunc TestMetrics_Record(t *testing.T) {\n\tm := newScalarMetrics()\n\n\tm.Record()\n\tassert.NotEmpty(t, m.Earliest)\n\tassert.Equal(t, m.Earliest, m.Latest)\n\tassert.Equal(t, uint64(1), m.Count)\n\n\tm.Record()\n\tassert.True(t, m.Earliest.Before(m.Latest))\n\tassert.Equal(t, uint64(2), m.Count)\n}\n\nfunc TestQueryType_String(t *testing.T) ", "output": "{\n\tassert.Equal(t, \"REQUEST\", Request.String())\n\tassert.Equal(t, \"RESPONSE\", Response.String())\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\tb64 \"encoding/base64\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/aws/aws-sdk-go-v2/config\"\n\t\"github.com/aws/aws-sdk-go-v2/service/kms\"\n)\n\n\n\ntype KMSEncryptAPI interface {\n\tEncrypt(ctx context.Context,\n\t\tparams *kms.EncryptInput,\n\t\toptFns ...func(*kms.Options)) (*kms.EncryptOutput, error)\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc main() {\n\tkeyID := flag.String(\"k\", \"\", \"The ID of a KMS key\")\n\ttext := flag.String(\"t\", \"\", \"The text to encrypt\")\n\tflag.Parse()\n\n\tif *keyID == \"\" || *text == \"\" {\n\t\tfmt.Println(\"You must supply the ID of a KMS key and some text\")\n\t\tfmt.Println(\"-k KEY-ID -t \\\"text\\\"\")\n\t\treturn\n\t}\n\n\tcfg, err := config.LoadDefaultConfig(context.TODO())\n\tif err != nil {\n\t\tpanic(\"configuration error, \" + err.Error())\n\t}\n\n\tclient := kms.NewFromConfig(cfg)\n\n\tinput := &kms.EncryptInput{\n\t\tKeyId: keyID,\n\t\tPlaintext: []byte(*text),\n\t}\n\n\tresult, err := EncryptText(context.TODO(), client, input)\n\tif err != nil {\n\t\tfmt.Println(\"Got error encrypting data:\")\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tblobString := b64.StdEncoding.EncodeToString(result.CiphertextBlob)\n\n\tfmt.Println(blobString)\n}\n\nfunc EncryptText(c context.Context, api KMSEncryptAPI, input *kms.EncryptInput) (*kms.EncryptOutput, error) ", "output": "{\n\treturn api.Encrypt(c, input)\n}"} {"input": "package core\n\nimport (\n\t\"github.com/MG-RAST/AWE/lib/core/cwl\"\n\t\"github.com/MG-RAST/AWE/lib/logger\"\n)\n\ntype SetCounter struct {\n\tCounter []int\n\tMax []int\n\tNumberOfSets int\n\tScatter_type string\n}\n\n\n\nfunc (sc *SetCounter) Increment() (ok bool) {\n\n\tif sc.Scatter_type == \"cross\" {\n\t\tfor position_in_counter := sc.NumberOfSets - 1; position_in_counter >= 0; position_in_counter-- {\n\t\t\tif sc.Counter[position_in_counter] < sc.Max[position_in_counter] {\n\t\t\t\tsc.Counter[position_in_counter] += 1\n\t\t\t\tok = true\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tsc.Counter[position_in_counter] = 0\n\n\t\t}\n\t} else {\n\n\n\t\tif sc.Counter[0] >= sc.Max[0] {\n\t\t\tok = false\n\t\t\treturn\n\t\t}\n\n\t\tfor position_in_counter := sc.NumberOfSets - 1; position_in_counter >= 0; position_in_counter-- {\n\t\t\tsc.Counter[position_in_counter] += 1\n\t\t}\n\t\tok = true\n\t\treturn\n\t}\n\n\tok = false\n\treturn\n\n}\n\nfunc NewSetCounter(numberOfSets int, array []cwl.Array, scatter_type string) (sc *SetCounter) ", "output": "{\n\n\tlogger.Debug(3, \"(NewSetCounter) numberOfSets: %d\", numberOfSets)\n\tlogger.Debug(3, \"(NewSetCounter) array: %d\", len(array))\n\tlogger.Debug(3, \"(NewSetCounter) scatter_type: %s\", scatter_type)\n\n\tsc = &SetCounter{}\n\n\tsc.NumberOfSets = numberOfSets\n\n\n\tsc.Counter = make([]int, sc.NumberOfSets)\n\tsc.Max = make([]int, sc.NumberOfSets)\n\tfor i := 0; i < sc.NumberOfSets; i++ {\n\t\tsc.Counter[i] = 0\n\t\tsc.Max[i] = array[i].Len() - 1 \n\t}\n\n\tsc.Scatter_type = scatter_type\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"go.bug.st/serial\"\n)\n\n\n\nfunc pauseHandler(c *gin.Context) {\n\tgo func() {\n\t\tports, _ := serial.GetPortsList()\n\t\tfor _, element := range ports {\n\t\t\tspClose(element)\n\t\t}\n\t\t*hibernate = true\n\t\tSystray.Pause()\n\t}()\n\tc.JSON(200, nil)\n}\n\nfunc infoHandler(c *gin.Context) ", "output": "{\n\thost := c.Request.Host\n\tparts := strings.Split(host, \":\")\n\thost = parts[0]\n\n\tc.JSON(200, gin.H{\n\t\t\"version\": version,\n\t\t\"http\": \"http://\" + host + port,\n\t\t\"https\": \"https://localhost\" + portSSL,\n\t\t\"ws\": \"ws://\" + host + port,\n\t\t\"wss\": \"wss://localhost\" + portSSL,\n\t\t\"origins\": origins,\n\t\t\"update_url\": updateUrl,\n\t\t\"os\": runtime.GOOS + \":\" + runtime.GOARCH,\n\t})\n}"} {"input": "package errors \n\nimport (\n\t\"strconv\"\n)\n\n\n\ntype StructuralError string\n\nfunc (s StructuralError) Error() string {\n\treturn \"openpgp: invalid data: \" + string(s)\n}\n\n\n\ntype UnsupportedError string\n\nfunc (s UnsupportedError) Error() string {\n\treturn \"openpgp: unsupported feature: \" + string(s)\n}\n\n\n\ntype InvalidArgumentError string\n\nfunc (i InvalidArgumentError) Error() string {\n\treturn \"openpgp: invalid argument: \" + string(i)\n}\n\n\n\ntype SignatureError string\n\nfunc (b SignatureError) Error() string {\n\treturn \"openpgp: invalid signature: \" + string(b)\n}\n\ntype keyIncorrectError int\n\nfunc (ki keyIncorrectError) Error() string {\n\treturn \"openpgp: incorrect key\"\n}\n\nvar ErrKeyIncorrect error = keyIncorrectError(0)\n\ntype unknownIssuerError int\n\nfunc (unknownIssuerError) Error() string {\n\treturn \"openpgp: signature made by unknown entity\"\n}\n\nvar ErrUnknownIssuer error = unknownIssuerError(0)\n\ntype keyRevokedError int\n\n\n\nvar ErrKeyRevoked error = keyRevokedError(0)\n\ntype UnknownPacketTypeError uint8\n\nfunc (upte UnknownPacketTypeError) Error() string {\n\treturn \"openpgp: unknown packet type: \" + strconv.Itoa(int(upte))\n}\n\nfunc (keyRevokedError) Error() string ", "output": "{\n\treturn \"openpgp: signature made by revoked key\"\n}"} {"input": "package test\n\nimport (\n\tcryptoTest \"github.com/tidepool-org/platform/crypto/test\"\n\timageStoreStructured \"github.com/tidepool-org/platform/image/store/structured\"\n\timageTest \"github.com/tidepool-org/platform/image/test\"\n\t\"github.com/tidepool-org/platform/pointer\"\n\t\"github.com/tidepool-org/platform/test\"\n)\n\n\n\nfunc RandomContentAttributes() *imageStoreStructured.ContentAttributes {\n\tdatum := imageStoreStructured.NewContentAttributes()\n\tdatum.DigestMD5 = pointer.FromString(cryptoTest.RandomBase64EncodedMD5Hash())\n\tdatum.MediaType = pointer.FromString(imageTest.RandomMediaType())\n\tdatum.Width = pointer.FromInt(imageTest.RandomWidth())\n\tdatum.Height = pointer.FromInt(imageTest.RandomHeight())\n\tdatum.Size = pointer.FromInt(test.RandomIntFromRange(1, 100*1024*1024))\n\treturn datum\n}\n\nfunc RandomUpdate() *imageStoreStructured.Update ", "output": "{\n\tdatum := imageStoreStructured.NewUpdate()\n\tdatum.Metadata = imageTest.RandomMetadata()\n\tdatum.ContentID = pointer.FromString(imageTest.RandomContentID())\n\tdatum.ContentIntent = pointer.FromString(imageTest.RandomContentIntent())\n\tdatum.ContentAttributes = RandomContentAttributes()\n\tdatum.RenditionsID = nil\n\tdatum.Rendition = nil\n\treturn datum\n}"} {"input": "package git\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/Originate/git-town/src/command\"\n\t\"github.com/Originate/git-town/src/util\"\n)\n\n\n\nfunc EnsureDoesNotHaveConflicts() {\n\tutil.Ensure(!HasConflicts(), \"You must resolve the conflicts before continuing\")\n}\n\n\n\nfunc EnsureDoesNotHaveOpenChanges(message string) {\n\tutil.Ensure(!HasOpenChanges(), \"You have uncommitted changes. \"+message)\n}\n\n\nvar rootDirectory string\n\n\n\n\n\n\nfunc HasConflicts() bool {\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"Unmerged paths\")\n}\n\n\nfunc HasOpenChanges() bool {\n\treturn command.MustRun(\"git\", \"status\", \"--porcelain\").OutputSanitized() != \"\"\n}\n\n\n\nfunc HasShippableChanges(branchName string) bool {\n\treturn command.MustRun(\"git\", \"diff\", Config().GetMainBranch()+\"..\"+branchName).OutputSanitized() != \"\"\n}\n\n\n\nfunc IsMergeInProgress() bool {\n\t_, err := os.Stat(fmt.Sprintf(\"%s/.git/MERGE_HEAD\", GetRootDirectory()))\n\treturn err == nil\n}\n\n\n\nfunc IsRebaseInProgress() bool {\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"rebase in progress\")\n}\n\nfunc GetRootDirectory() string ", "output": "{\n\tif rootDirectory == \"\" {\n\t\trootDirectory = command.MustRun(\"git\", \"rev-parse\", \"--show-toplevel\").OutputSanitized()\n\t}\n\treturn rootDirectory\n}"} {"input": "package command\n\nimport (\n\t\"github.com/urfave/cli\"\n\t\"go.etcd.io/etcd/client\"\n)\n\n\n\n\nfunc NewSetDirCommand() cli.Command ", "output": "{\n\treturn cli.Command{\n\t\tName: \"setdir\",\n\t\tUsage: \"create a new directory or update an existing directory TTL\",\n\t\tArgsUsage: \"\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.IntFlag{Name: \"ttl\", Value: 0, Usage: \"key time-to-live in seconds\"},\n\t\t},\n\t\tAction: func(c *cli.Context) error {\n\t\t\tmkdirCommandFunc(c, mustNewKeyAPI(c), client.PrevIgnore)\n\t\t\treturn nil\n\t\t},\n\t}\n}"} {"input": "package grok\n\ntype nestingStack struct {\n\ttop *nestingElement\n\tsize int\n}\n\ntype nestingElement struct {\n\topenRune rune\n\tstartIndex int\n\tcommaCounter int\n\tlastSeparatorIndex int\n\tnext *nestingElement\n}\n\n\n\n\n\nfunc (s *nestingStack) topValue() (rune, int, bool) {\n\tif s.size == 0 {\n\t\treturn ' ', -1, false\n\t}\n\n\treturn s.top.openRune, s.top.startIndex, true\n}\n\n\nfunc (s *nestingStack) push(openRune rune, startIndex int) {\n\ts.top = &nestingElement{openRune, startIndex, 0, -1, s.top}\n\ts.size++\n}\n\n\nfunc (s *nestingStack) pop() (openRune rune, startIndex int) {\n\tif s.size > 0 {\n\t\topenRune, startIndex, s.top = s.top.openRune, s.top.startIndex, s.top.next\n\t\ts.size--\n\t\treturn\n\t}\n\treturn ' ', -1\n}\n\nfunc (ne *nestingElement) expressionStartIndex() int ", "output": "{\n\tstartIndex := ne.startIndex + 1\n\tif ne.lastSeparatorIndex+1 > startIndex {\n\t\treturn ne.lastSeparatorIndex + 1\n\t}\n\treturn startIndex\n}"} {"input": "package acquire\n\nimport \"math/rand\"\n\nfunc countTiles(c *PieceCollection) [BoardHeight][BoardWidth]int {\n\tvar tileCount [BoardHeight][BoardWidth]int\n\n\tfor _, p := range c.Pieces {\n\t\ttileCount[p.Row][p.Col]++\n\t}\n\n\treturn tileCount\n}\n\n\n\nfunc genGameParams() (r *rand.Rand, players []Player) {\n\tr = rand.New(rand.NewSource(0))\n\tplayers = []Player{NewPlayerRandom(r)}\n\treturn\n}\n\nfunc _genTestGame() (*Game, *PlayerRandom) ", "output": "{\n\tr := rand.New(rand.NewSource(0))\n\tp1 := NewPlayerRandom(r)\n\treturn NewGame(r, []Player{p1}), p1\n}"} {"input": "package cognitiveservices\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n)\n\nconst (\n\tmajor = \"8\"\n\tminor = \"0\"\n\tpatch = \"0\"\n\ttag = \"beta\"\n\tuserAgentFormat = \"Azure-SDK-For-Go/%s arm-%s/%s\"\n)\n\n\nvar (\n\tuserAgent string\n\tversion string\n)\n\n\n\n\n\nfunc Version() string {\n\tif version == \"\" {\n\t\tversionBuilder := bytes.NewBufferString(fmt.Sprintf(\"%s.%s.%s\", major, minor, patch))\n\t\tif tag != \"\" {\n\t\t\tversionBuilder.WriteRune('-')\n\t\t\tversionBuilder.WriteString(strings.TrimPrefix(tag, \"-\"))\n\t\t}\n\t\tversion = string(versionBuilder.Bytes())\n\t}\n\treturn version\n}\n\nfunc UserAgent() string ", "output": "{\n\tif userAgent == \"\" {\n\t\tuserAgent = fmt.Sprintf(userAgentFormat, Version(), \"cognitiveservices\", \"2016-02-01-preview\")\n\t}\n\treturn userAgent\n}"} {"input": "package systembanner\n\nimport (\n\t\"net/http\"\n\n\trestful \"github.com/emicklei/go-restful\"\n\t\"github.com/kubernetes/dashboard/src/app/backend/systembanner/api\"\n)\n\n\ntype SystemBannerHandler struct {\n\tmanager SystemBannerManager\n}\n\n\nfunc (self *SystemBannerHandler) Install(ws *restful.WebService) {\n\tws.Route(\n\t\tws.GET(\"/systembanner\").\n\t\t\tTo(self.handleGet).\n\t\t\tWrites(api.SystemBanner{}))\n}\n\nfunc (self *SystemBannerHandler) handleGet(request *restful.Request, response *restful.Response) {\n\tresponse.WriteHeaderAndEntity(http.StatusOK, self.manager.Get())\n}\n\n\n\n\nfunc NewSystemBannerHandler(manager SystemBannerManager) SystemBannerHandler ", "output": "{\n\treturn SystemBannerHandler{manager: manager}\n}"} {"input": "package fswatch\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\ntype Context struct {\n\tHandle func(Event, FileInfo)\n\tFilter func(FileInfo) bool\n\tError func(error)\n}\n\n\ntype FileInfo interface {\n\tos.FileInfo\n\tPath() string\n\tIgnored() bool\n}\n\n\ntype Watcher struct {\n\t*watcher\n}\n\n\nfunc New(ctx *Context) (Watcher, error) {\n\tw, err := newwatcher(ctx)\n\treturn Watcher{w}, err\n}\n\n\n\nfunc (w Watcher) Load(path string, recursive bool) error {\n\tpath = filepath.Clean(path)\n\treturn w.load(path, recursive)\n}\n\n\n\nfunc (w Watcher) Get(path string) FileInfo {\n\tpath = filepath.Clean(path)\n\tw.mutex.RLock()\n\tfi := w.tree.get(path)\n\tw.mutex.RUnlock()\n\tif fi == nil || fi.Ignored() {\n\t\treturn nil\n\t}\n\treturn fi\n}\n\n\n\nfunc (w Watcher) Lstat(path string) (os.FileInfo, error) {\n\tif info := w.Get(path); info != nil {\n\t\treturn info, nil\n\t}\n\treturn nil, &os.PathError{Op: \"stat\", Path: path, Err: os.ErrNotExist}\n}\n\n\n\n\nfunc (w Watcher) Traverse(root string, travFn func(FileInfo) error) error {\n\troot = filepath.Clean(root)\n\tw.mutex.RLock()\n\tdefer w.mutex.RUnlock()\n\treturn w.tree.walk(root, travFn)\n}\n\n\n\n\n\n\n\n\nfunc (w Watcher) Unload(path string, recursive bool) error {\n\tpath = filepath.Clean(path)\n\treturn w.unload(path, recursive)\n}\n\n\nfunc (w Watcher) Close() error {\n\treturn w.close()\n}\n\nfunc (w Watcher) Walk(root string, walkFn filepath.WalkFunc) error ", "output": "{\n\tvar found bool\n\terr := w.Traverse(root, func(info FileInfo) error {\n\t\tfound = true\n\t\treturn walkFn(info.Path(), info, nil)\n\t})\n\tif !found {\n\t\treturn walkFn(root, nil, err)\n\t}\n\treturn err\n}"} {"input": "package iso20022\n\n\ntype ATMContext4 struct {\n\n\tSessionReference *Max35Text `xml:\"SsnRef,omitempty\"`\n\n\tService *ATMService4 `xml:\"Svc\"`\n}\n\n\n\nfunc (a *ATMContext4) AddService() *ATMService4 {\n\ta.Service = new(ATMService4)\n\treturn a.Service\n}\n\nfunc (a *ATMContext4) SetSessionReference(value string) ", "output": "{\n\ta.SessionReference = (*Max35Text)(&value)\n}"} {"input": "package serialconsole\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/serialconsole/mgmt/2018-05-01/serialconsole\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype BaseClient = original.BaseClient\ntype ConsoleClient = original.ConsoleClient\ntype DeploymentValidateResult = original.DeploymentValidateResult\ntype GetDisabledResult = original.GetDisabledResult\ntype GetResult = original.GetResult\ntype ListClient = original.ListClient\ntype ListConsoleClient = original.ListConsoleClient\ntype Operations = original.Operations\ntype SetDisabledResult = original.SetDisabledResult\n\nfunc New(subscriptionID string) BaseClient {\n\treturn original.New(subscriptionID)\n}\nfunc NewConsoleClient(subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClient(subscriptionID)\n}\nfunc NewConsoleClientWithBaseURI(baseURI string, subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewListClient(subscriptionID string) ListClient {\n\treturn original.NewListClient(subscriptionID)\n}\n\nfunc NewListConsoleClient(subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClient(subscriptionID)\n}\nfunc NewListConsoleClientWithBaseURI(baseURI string, subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\n\nfunc NewListClientWithBaseURI(baseURI string, subscriptionID string) ListClient ", "output": "{\n\treturn original.NewListClientWithBaseURI(baseURI, subscriptionID)\n}"} {"input": "package grpcsync\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"strings\"\n\n\t\"github.com/ligato/cn-infra/datasync/syncbase/msg\"\n\t\"github.com/ligato/cn-infra/logging/logrus\"\n\t\"golang.org/x/net/context\"\n)\n\n\nfunc NewDataMsgServiceServer(adapter *Adapter) *DataMsgServiceServer {\n\treturn &DataMsgServiceServer{adapter: adapter}\n}\n\n\ntype DataMsgServiceServer struct {\n\tadapter *Adapter\n}\n\n\nfunc (s *DataMsgServiceServer) DataChanges(stream msg.DataMsgService_DataChangesServer) error {\n\tfor {\n\t\tchng, err := stream.Recv()\n\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, sub := range s.adapter.base.Subscriptions() {\n\t\t\tfor _, keyPrefix := range sub.KeyPrefixes {\n\t\t\t\tif strings.HasPrefix(chng.Key, keyPrefix) {\n\t\t\t\t\tsub.ChangeChan <- msg.NewChangeWatchResp(chng, func(err2 error) {\n\t\t\t\t\t\terr = stream.Send(&msg.DataChangeReply{Key: chng.Key, OperationType: chng.OperationType,\n\t\t\t\t\t\t\tResult: 0 })\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlogrus.DefaultLogger().Error(err) \n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n\nfunc replySeq() *msg.Seq {\n\treturn &msg.Seq{} \n}\n\n\nfunc (s *DataMsgServiceServer) Ping(ctx context.Context, req *msg.PingRequest) (*msg.PingReply, error) {\n\treturn &msg.PingReply{Message: \"it works\"}, nil\n}\n\nfunc (s *DataMsgServiceServer) DataResyncs(ctx context.Context, req *msg.DataResyncRequests) (\n\t*msg.DataResyncReplies, error) ", "output": "{\n\tresyncs := req.GetDataResyncs()\n\tif resyncs != nil {\n\n\t\tvar err error\n\t\tif err != nil {\n\t\t\treturn &msg.DataResyncReplies{MsgId: replySeq(), Error: &msg.Error{Message: err.Error()} }, err\n\t\t}\n\n\t\treturn &msg.DataResyncReplies{MsgId: replySeq() }, nil\n\t}\n\n\terr := errors.New(\"unexpected place - nil resyncs\")\n\treturn &msg.DataResyncReplies{MsgId: replySeq(), Error: &msg.Error{Message: err.Error()} }, err\n}"} {"input": "package api\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"net/http\"\n\n\t\"github.com/coreos/fleet/log\"\n)\n\nvar unavailable = &unavailableHdlr{}\n\nfunc NewServer(listeners []net.Listener, hdlr http.Handler) *Server {\n\treturn &Server{\n\t\tlisteners: listeners,\n\t\tapi: hdlr,\n\t\tcur: unavailable,\n\t}\n}\n\ntype Server struct {\n\tlisteners []net.Listener\n\tapi http.Handler\n\tcur http.Handler\n}\n\nfunc (s *Server) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\ts.cur.ServeHTTP(rw, req)\n}\n\n\n\n\n\n\nfunc (s *Server) Available(stop chan bool) {\n\ts.cur = s.api\n\t<-stop\n\ts.cur = unavailable\n}\n\ntype unavailableHdlr struct{}\n\nfunc (uh *unavailableHdlr) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tsendError(rw, http.StatusServiceUnavailable, errors.New(\"fleet server currently unavailable\"))\n}\n\nfunc (s *Server) Serve() ", "output": "{\n\tfor i, _ := range s.listeners {\n\t\tl := s.listeners[i]\n\t\tgo func() {\n\t\t\terr := http.Serve(l, s)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed serving HTTP on listener: %s\", l.Addr)\n\t\t\t}\n\t\t}()\n\t}\n}"} {"input": "package fenwick\n\n\n\ntype Fenwick struct {\n\ttree []int\n}\n\n\nfunc NewFenwick(n int) *Fenwick {\n\tfen := &Fenwick{\n\t\ttree: make([]int, n),\n\t}\n\tfor i := range fen.tree {\n\t\tfen.tree[i] = 1\n\t}\n\treturn fen\n}\n\n\n\n\n\nfunc lsb(x int) int {\n\treturn x & -x\n}\n\n\nfunc (fen *Fenwick) Update(index, value int) {\n\tindex++\n\tfor index <= fen.Size() {\n\t\tfen.tree[index-1] *= value\n\t\tindex += lsb(index)\n\t}\n}\n\n\nfunc (fen *Fenwick) Size() int {\n\treturn len(fen.tree)\n}\n\nfunc (fen *Fenwick) Sum(index int) int ", "output": "{\n\tsum := 1\n\tindex++\n\tfor index > 0 {\n\t\tsum *= fen.tree[index-1]\n\t\tindex -= lsb(index)\n\t}\n\treturn sum\n}"} {"input": "package system\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/influxdb/telegraf/plugins\"\n)\n\ntype MemStats struct {\n\tps PS\n}\n\nfunc (_ *MemStats) Description() string {\n\treturn \"Read metrics about memory usage\"\n}\n\nfunc (_ *MemStats) SampleConfig() string { return \"\" }\n\n\n\ntype SwapStats struct {\n\tps PS\n}\n\nfunc (_ *SwapStats) Description() string {\n\treturn \"Read metrics about swap memory usage\"\n}\n\nfunc (_ *SwapStats) SampleConfig() string { return \"\" }\n\nfunc (s *SwapStats) Gather(acc plugins.Accumulator) error {\n\tswap, err := s.ps.SwapStat()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting swap memory info: %s\", err)\n\t}\n\n\tswaptags := map[string]string(nil)\n\n\tacc.Add(\"total\", swap.Total, swaptags)\n\tacc.Add(\"used\", swap.Used, swaptags)\n\tacc.Add(\"free\", swap.Free, swaptags)\n\tacc.Add(\"used_perc\", swap.UsedPercent, swaptags)\n\tacc.Add(\"in\", swap.Sin, swaptags)\n\tacc.Add(\"out\", swap.Sout, swaptags)\n\n\treturn nil\n}\n\nfunc init() {\n\tplugins.Add(\"mem\", func() plugins.Plugin {\n\t\treturn &MemStats{ps: &systemPS{}}\n\t})\n\n\tplugins.Add(\"swap\", func() plugins.Plugin {\n\t\treturn &SwapStats{ps: &systemPS{}}\n\t})\n}\n\nfunc (s *MemStats) Gather(acc plugins.Accumulator) error ", "output": "{\n\tvm, err := s.ps.VMStat()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting virtual memory info: %s\", err)\n\t}\n\n\tvmtags := map[string]string(nil)\n\n\tacc.Add(\"total\", vm.Total, vmtags)\n\tacc.Add(\"available\", vm.Available, vmtags)\n\tacc.Add(\"used\", vm.Used, vmtags)\n\tacc.Add(\"used_prec\", vm.UsedPercent, vmtags)\n\tacc.Add(\"free\", vm.Free, vmtags)\n\tacc.Add(\"active\", vm.Active, vmtags)\n\tacc.Add(\"inactive\", vm.Inactive, vmtags)\n\tacc.Add(\"buffers\", vm.Buffers, vmtags)\n\tacc.Add(\"cached\", vm.Cached, vmtags)\n\tacc.Add(\"wired\", vm.Wired, vmtags)\n\tacc.Add(\"shared\", vm.Shared, vmtags)\n\n\treturn nil\n}"} {"input": "package client\n\nimport (\n\t\"math\"\n\t\"math/rand\"\n\t\"time\"\n\n\t\"github.com/paybyphone/kintail/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype DefaultRetryer struct {\n\tNumMaxRetries int\n}\n\n\n\nfunc (d DefaultRetryer) MaxRetries() int {\n\treturn d.NumMaxRetries\n}\n\n\n\n\n\nfunc (d DefaultRetryer) ShouldRetry(r *request.Request) bool {\n\tif r.HTTPResponse.StatusCode >= 500 {\n\t\treturn true\n\t}\n\treturn r.IsErrorRetryable()\n}\n\nfunc (d DefaultRetryer) RetryRules(r *request.Request) time.Duration ", "output": "{\n\tdelay := int(math.Pow(2, float64(r.RetryCount))) * (rand.Intn(30) + 30)\n\treturn time.Duration(delay) * time.Millisecond\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"encoding/binary\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\ntype (\n\tPerfHeader struct {\n\t\tMagic [8]byte\n\t\tSize uint64\n\t\tAttrSize uint64\n\t\tAttrs PerfFileSection\n\t\tData PerfFileSection\n\t\tEventTypes PerfFileSection\n\t\tFlags uint64\n\t\tFlags1 [3]uint64\n\t}\n\tPerfFileSection struct {\n\t\tOffset uint64\n\t\tSize uint64\n\t}\n\tPerfHeaderString struct {\n\t\tLen uint32\n\t\tString []byte\n\t}\n\tPerfHeaderStringList struct {\n\t\tNr uint32\n\t\tStrings []PerfHeaderString\n\t}\n)\n\nfunc main() {\n\tflag.Parse()\n\tfor _, path := range flag.Args() {\n\t\tfmt.Println(path)\n\t\tr := open(path)\n\t\th := getPerfHeader(r)\n\t\tfmt.Println(h)\n\t}\n}\n\nfunc open(file string) *bufio.Reader {\n\tr, err := os.Open(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn bufio.NewReader(r)\n}\n\n\n\nfunc getPerfHeader(r *bufio.Reader) (h PerfHeader) ", "output": "{\n\terr := binary.Read(r, binary.LittleEndian, &h)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn h\n}"} {"input": "package gtd\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/BurntSushi/toml\"\n)\n\ntype config struct {\n\tGtdFile string `toml:\"gtdfile\"`\n\tMemoDir string `toml:\"memodir\"`\n\tOutputDir string `toml:\"outputdir\"`\n\tFilterCmd string `toml:\"filtercmd\"`\n\tEditor string `toml:\"editor\"`\n}\n\nfunc (cfg *config) load() error {\n\tvar dir string\n\tdir = filepath.Join(os.Getenv(\"HOME\"), \".config\", \"gtd\")\n\n\tif err := os.MkdirAll(dir, 0700); err != nil {\n\t\treturn fmt.Errorf(\"cannot create directory: %v\", err)\n\t}\n\n\tconfigfile := filepath.Join(dir, \"config.toml\")\n\t_, err := os.Stat(configfile)\n\tif err == nil {\n\t\t_, err := toml.DecodeFile(configfile, cfg)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot decode toml file: %v\", err)\n\t\t}\n\t\treturn nil\n\t}\n\n\tcfg.Editor = \"vi\"\n\tgtdfile := filepath.Join(os.Getenv(\"HOME\"), \"gtd.json\")\n\tcfg.GtdFile = gtdfile\n\tcfg.MemoDir = os.Getenv(\"HOME\")\n\tf, err := os.Create(configfile)\n\treturn toml.NewEncoder(f).Encode(cfg)\n}\n\n\n\nfunc (cfg *config) filtercmd(command string, w io.Writer) error {\n\tvar cmd *exec.Cmd\n\tcmd = exec.Command(\"sh\", \"-c\", command)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = w\n\treturn cmd.Run()\n}\n\nfunc (cfg *config) runcmd(command string, files ...string) error ", "output": "{\n\tvar args []string\n\tfor _, file := range files {\n\t\targs = append(args, fmt.Sprintf(\"%q\", file))\n\t}\n\tcmdargs := strings.Join(args, \" \")\n\tcommand += \" \" + cmdargs\n\n\tvar cmd *exec.Cmd\n\tcmd = exec.Command(\"sh\", \"-c\", command)\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = os.Stdout\n\tcmd.Stdin = os.Stdin\n\treturn cmd.Run()\n}"} {"input": "package vminstall\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"io/ioutil\"\n\t\"strings\"\n)\n\ntype Downloader interface{\n\tDownload(url string) ([]byte, error)\n\tMatch() string\n}\n\ntype HTTPDownloader struct {\n\n}\n\nfunc (h HTTPDownloader) Match() string {\n\treturn \"http\"\n}\n\nfunc (h HTTPDownloader) Download(url string) ([]byte,error) {\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\tcontents, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn contents,nil\n\n}\n\ntype DownloadManager struct {\n\tdownloaders []Downloader\n}\n\n\nfunc (manager *DownloadManager) Regsiter(d Downloader) {\n\tmanager.downloaders = append(manager.downloaders, d)\n}\n\n\n\n\nfunc (manager *DownloadManager) Download(url string) ([]byte,error) ", "output": "{\n\tvar found bool = false\n\tvar d Downloader\n\tfor _,d = range manager.downloaders {\n\t\tif strings.Index(url, d.Match()) == 0 {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif found {\n\t\treturn d.Download(url)\n\t} else {\n\t\treturn nil, errors.New(\"not found matching download\")\n\t}\n\n}"} {"input": "package main\n\nimport (\n\t\"github.com/spf13/viper\"\n\n\toperatorOption \"github.com/cilium/cilium/operator/option\"\n\t\"github.com/cilium/cilium/pkg/option\"\n)\n\n\n\nfunc init() ", "output": "{\n\tflags := rootCmd.Flags()\n\n\tflags.String(operatorOption.AzureSubscriptionID, \"\", \"Subscription ID to access Azure API\")\n\toption.BindEnvWithLegacyEnvFallback(operatorOption.AzureSubscriptionID, \"AZURE_SUBSCRIPTION_ID\")\n\n\tflags.String(operatorOption.AzureResourceGroup, \"\", \"Resource group to use for Azure IPAM\")\n\toption.BindEnvWithLegacyEnvFallback(operatorOption.AzureResourceGroup, \"AZURE_RESOURCE_GROUP\")\n\n\tflags.String(operatorOption.AzureUserAssignedIdentityID, \"\", \"ID of the user assigned identity used to auth with the Azure API\")\n\toption.BindEnvWithLegacyEnvFallback(operatorOption.AzureUserAssignedIdentityID, \"AZURE_USER_ASSIGNED_IDENTITY_ID\")\n\n\tflags.Bool(operatorOption.AzureUsePrimaryAddress, true, \"Use Azure IP address from interface's primary IPConfigurations\")\n\toption.BindEnvWithLegacyEnvFallback(operatorOption.AzureUsePrimaryAddress, \"AZURE_USE_PRIMARY_ADDRESS\")\n\n\tviper.BindPFlags(flags)\n}"} {"input": "package model\n\n\ntype Apply struct {\n\tID int64 `json:\"id\" gorm:\"AUTO_INCREMENT;primary_key;\" form:\"id\"`\n\tPath string `json:\"path\"`\n\tFrom string `json:\"from\" form:\"from\"`\n\tTo string `json:\"to\" form:\"to\"`\n\tStatus int32 `json:\"status\" form:\"status\"`\n\tStartTime string `json:\"start_time\" form:\"start_time\"`\n\tEndTime string `json:\"end_time\" form:\"end_time\"`\n\tActive int32 `json:\"active\"`\n}\n\n\nconst (\n\tApplyValid = 1 \n\tApplyInvalid = -1 \n)\n\n\ntype QueryApplyResponse struct {\n\tApplyList []*Apply `json:\"apply_list\"`\n\tPagination\n}\n\n\ntype QueryApplyRequest struct {\n\tApply\n\tPagination\n}\n\n\n\n\nfunc (w Apply) TableName() string ", "output": "{\n\treturn \"apply\"\n}"} {"input": "package msgraph\n\nimport \"context\"\n\n\ntype WorkbookFunctionsProductRequestBuilder struct{ BaseRequestBuilder }\n\n\nfunc (b *WorkbookFunctionsRequestBuilder) Product(reqObj *WorkbookFunctionsProductRequestParameter) *WorkbookFunctionsProductRequestBuilder {\n\tbb := &WorkbookFunctionsProductRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.BaseRequestBuilder.baseURL += \"/product\"\n\tbb.BaseRequestBuilder.requestObject = reqObj\n\treturn bb\n}\n\n\ntype WorkbookFunctionsProductRequest struct{ BaseRequest }\n\n\n\n\n\nfunc (r *WorkbookFunctionsProductRequest) Post(ctx context.Context) (resObj *WorkbookFunctionResult, err error) {\n\terr = r.JSONRequest(ctx, \"POST\", \"\", r.requestObject, &resObj)\n\treturn\n}\n\nfunc (b *WorkbookFunctionsProductRequestBuilder) Request() *WorkbookFunctionsProductRequest ", "output": "{\n\treturn &WorkbookFunctionsProductRequest{\n\t\tBaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},\n\t}\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSOpsWorksApp_Source struct {\n\n\tPassword string `json:\"Password,omitempty\"`\n\n\tRevision string `json:\"Revision,omitempty\"`\n\n\tSshKey string `json:\"SshKey,omitempty\"`\n\n\tType string `json:\"Type,omitempty\"`\n\n\tUrl string `json:\"Url,omitempty\"`\n\n\tUsername string `json:\"Username,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSOpsWorksApp_Source) AWSCloudFormationType() string {\n\treturn \"AWS::OpsWorks::App.Source\"\n}\n\n\n\n\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSOpsWorksApp_Source) DependsOn() []string ", "output": "{\n\treturn r._dependsOn\n}"} {"input": "package mock\n\nimport (\n\t\"github.com/fkmhrk/OpenInvoice/v1/model/env\"\n)\n\ntype EnvDAO struct {\n\tCreateResult env.Env\n\tGetResult env.Env\n\tGetListResult []*env.Env\n\tSaveResult error\n\tUpdateResult env.Env\n\tDeleteResult env.Env\n}\n\n\n\nfunc (d *EnvDAO) Get(key string) (env.Env, error) {\n\treturn d.GetResult, nil\n}\n\nfunc (d *EnvDAO) GetList() ([]*env.Env, error) {\n\treturn d.GetListResult, nil\n}\n\nfunc (d *EnvDAO) Save(list []*env.Env) error {\n\treturn d.SaveResult\n}\n\nfunc (d *EnvDAO) Update(key, value string) (env.Env, error) {\n\treturn d.UpdateResult, nil\n}\n\nfunc (d *EnvDAO) Delete(key string) (env.Env, error) {\n\treturn d.DeleteResult, nil\n}\n\nfunc (d *EnvDAO) Create(key, value string) (env.Env, error) ", "output": "{\n\treturn d.CreateResult, nil\n}"} {"input": "package osutil\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\t\"sync\"\n\t\"syscall\"\n\n\t\"go.uber.org/zap\"\n)\n\n\n\ntype InterruptHandler func()\n\nvar (\n\tinterruptRegisterMu, interruptExitMu sync.Mutex\n\tinterruptHandlers = []InterruptHandler{}\n)\n\n\n\nfunc RegisterInterruptHandler(h InterruptHandler) {\n\tinterruptRegisterMu.Lock()\n\tdefer interruptRegisterMu.Unlock()\n\tinterruptHandlers = append(interruptHandlers, h)\n}\n\n\nfunc HandleInterrupts(lg *zap.Logger) {\n\tnotifier := make(chan os.Signal, 1)\n\tsignal.Notify(notifier, syscall.SIGINT, syscall.SIGTERM)\n\n\tgo func() {\n\t\tsig := <-notifier\n\n\t\tinterruptRegisterMu.Lock()\n\t\tihs := make([]InterruptHandler, len(interruptHandlers))\n\t\tcopy(ihs, interruptHandlers)\n\t\tinterruptRegisterMu.Unlock()\n\n\t\tinterruptExitMu.Lock()\n\n\t\tif lg != nil {\n\t\t\tlg.Info(\"received signal; shutting down\", zap.String(\"signal\", sig.String()))\n\t\t} else {\n\t\t\tplog.Noticef(\"received %v signal, shutting down...\", sig)\n\t\t}\n\n\t\tfor _, h := range ihs {\n\t\t\th()\n\t\t}\n\t\tsignal.Stop(notifier)\n\t\tpid := syscall.Getpid()\n\t\tif pid == 1 {\n\t\t\tos.Exit(0)\n\t\t}\n\t\tsetDflSignal(sig.(syscall.Signal))\n\t\tsyscall.Kill(pid, sig.(syscall.Signal))\n\t}()\n}\n\n\n\n\nfunc Exit(code int) ", "output": "{\n\tinterruptExitMu.Lock()\n\tos.Exit(code)\n}"} {"input": "package whisper\n\nimport \"github.com/Tzunami/go-earthdollar/crypto\"\n\n\n\n\ntype Topic [4]byte\n\n\n\n\nfunc NewTopic(data []byte) Topic {\n\tprefix := [4]byte{}\n\tcopy(prefix[:], crypto.Keccak256(data)[:4])\n\treturn Topic(prefix)\n}\n\n\n\nfunc NewTopics(data ...[]byte) []Topic {\n\ttopics := make([]Topic, len(data))\n\tfor i, element := range data {\n\t\ttopics[i] = NewTopic(element)\n\t}\n\treturn topics\n}\n\n\nfunc (self *Topic) String() string {\n\treturn string(self[:])\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype topicMatcher struct {\n\tconditions []map[Topic]struct{}\n}\n\n\n\n\n\nfunc (self *topicMatcher) Matches(topics []Topic) bool {\n\tif len(self.conditions) > len(topics) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(topics) && i < len(self.conditions); i++ {\n\t\tif len(self.conditions[i]) > 0 {\n\t\t\tif _, ok := self.conditions[i][topics[i]]; !ok {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\nfunc newTopicMatcher(topics ...[]Topic) *topicMatcher ", "output": "{\n\tmatcher := make([]map[Topic]struct{}, len(topics))\n\tfor i, condition := range topics {\n\t\tmatcher[i] = make(map[Topic]struct{})\n\t\tfor _, topic := range condition {\n\t\t\tmatcher[i][topic] = struct{}{}\n\t\t}\n\t}\n\treturn &topicMatcher{conditions: matcher}\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/rbac/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"github.com/hyperhq/client-go/tools/cache\"\n)\n\n\ntype ClusterRoleBindingLister interface {\n\tList(selector labels.Selector) (ret []*v1.ClusterRoleBinding, err error)\n\tGet(name string) (*v1.ClusterRoleBinding, error)\n\tClusterRoleBindingListerExpansion\n}\n\n\ntype clusterRoleBindingLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewClusterRoleBindingLister(indexer cache.Indexer) ClusterRoleBindingLister {\n\treturn &clusterRoleBindingLister{indexer: indexer}\n}\n\n\n\n\n\nfunc (s *clusterRoleBindingLister) Get(name string) (*v1.ClusterRoleBinding, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"clusterrolebinding\"), name)\n\t}\n\treturn obj.(*v1.ClusterRoleBinding), nil\n}\n\nfunc (s *clusterRoleBindingLister) List(selector labels.Selector) (ret []*v1.ClusterRoleBinding, err error) ", "output": "{\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ClusterRoleBinding))\n\t})\n\treturn ret, err\n}"} {"input": "package nagiosplugin\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestDefaultStatusPolicy(t *testing.T) {\n\tc := NewCheck()\n\tc.AddResult(WARNING, \"Isolated-frame flux emission outside threshold\")\n\tc.AddResult(UNKNOWN, \"No response from betaform amplifier\")\n\n\texpected := \"UNKNOWN\"\n\tactual := strings.SplitN(c.String(), \":\", 2)[0]\n\tif actual != expected {\n\t\tt.Errorf(\"Expected %v status, got %v\", expected, actual)\n\t}\n}\n\nfunc TestOUWCStatusPolicy(t *testing.T) {\n\tc := NewCheckWithOptions(CheckOptions{\n\t\tStatusPolicy: NewOUWCStatusPolicy(),\n\t})\n\tc.AddResult(WARNING, \"Isolated-frame flux emission outside threshold\")\n\tc.AddResult(UNKNOWN, \"No response from betaform amplifier\")\n\n\texpected := \"WARNING\"\n\tactual := strings.SplitN(c.String(), \":\", 2)[0]\n\tif actual != expected {\n\t\tt.Errorf(\"Expected %v status, got %v\", expected, actual)\n\t}\n}\n\nfunc TestCheck(t *testing.T) ", "output": "{\n\trand.Seed(time.Now().UTC().UnixNano())\n\tc := NewCheck()\n\texpected := \"CRITICAL: 200000 terrifying space monkeys in the engineroom | space_monkeys=200000c;10000;100000;0;4294967296\"\n\tnSpaceMonkeys := float64(200000)\n\tmaxSpaceMonkeys := float64(1 << 32)\n\tc.AddPerfDatum(\"space_monkeys\", \"c\", nSpaceMonkeys, 0, maxSpaceMonkeys, 10000, 100000)\n\tc.AddResult(CRITICAL, fmt.Sprintf(\"%v terrifying space monkeys in the engineroom\", nSpaceMonkeys))\n\tc.AddResult(WARNING, fmt.Sprintf(\"%v slightly annoying space monkeys in the engineroom\", nSpaceMonkeys))\n\tresult := c.String()\n\tif expected != result {\n\t\tt.Errorf(\"Expected check output %v, got check output %v\", expected, result)\n\t}\n}"} {"input": "package delete\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewDeleteFilesFileidentifierParams() *DeleteFilesFileidentifierParams {\n\tvar ()\n\treturn &DeleteFilesFileidentifierParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\nfunc NewDeleteFilesFileidentifierParamsWithTimeout(timeout time.Duration) *DeleteFilesFileidentifierParams {\n\tvar ()\n\treturn &DeleteFilesFileidentifierParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype DeleteFilesFileidentifierParams struct {\n\n\tFileidentifier string\n\n\ttimeout time.Duration\n}\n\n\n\n\n\nfunc (o *DeleteFilesFileidentifierParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"fileidentifier\", o.Fileidentifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (o *DeleteFilesFileidentifierParams) WithFileidentifier(fileidentifier string) *DeleteFilesFileidentifierParams ", "output": "{\n\to.Fileidentifier = fileidentifier\n\treturn o\n}"} {"input": "package config\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar (\n\tCurrent = Version{\n\t\tMajor: 0,\n\t\tMinor: 15,\n\t\tPatch: 1,\n\t}\n\n\tFirst = Version{\n\t\t0, 10, 4,\n\t}\n)\n\n\ntype Version struct {\n\tMajor int `json:\"major\"`\n\tMinor int `json:\"minor\"`\n\tPatch int `json:\"patch\"`\n}\n\n\nfunc VersionFromString(s string) Version {\n\tvs := strings.Split(s, \".\")\n\n\tif len(vs) < 3 {\n\n\t\treturn First\n\t}\n\n\ttoInt := func(s string) int {\n\t\ti, err := strconv.Atoi(s)\n\t\tif err != nil {\n\t\t\treturn 0\n\t\t}\n\t\treturn i\n\t}\n\n\treturn Version{toInt(vs[0]), toInt(vs[1]), toInt(vs[2])}\n}\n\n\n\n\n\nfunc (v Version) Greater(x Version) bool {\n\tif v.Major > x.Major {\n\t\treturn true\n\t}\n\n\tif v.Major == x.Major {\n\t\tif v.Minor > x.Minor {\n\t\t\treturn true\n\t\t}\n\n\t\tif v.Minor == x.Minor {\n\t\t\tif v.Patch > x.Patch {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\treturn false\n\t\t}\n\t\treturn false\n\t}\n\n\treturn false\n}\n\nfunc (v Version) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%d.%d.%d\", v.Major, v.Minor, v.Patch)\n}"} {"input": "package aianomalydetection\n\n\ntype InfluxVersionEnum string\n\n\nconst (\n\tInfluxVersionV18 InfluxVersionEnum = \"V_1_8\"\n\tInfluxVersionV20 InfluxVersionEnum = \"V_2_0\"\n)\n\nvar mappingInfluxVersion = map[string]InfluxVersionEnum{\n\t\"V_1_8\": InfluxVersionV18,\n\t\"V_2_0\": InfluxVersionV20,\n}\n\n\n\n\nfunc GetInfluxVersionEnumValues() []InfluxVersionEnum ", "output": "{\n\tvalues := make([]InfluxVersionEnum, 0)\n\tfor _, v := range mappingInfluxVersion {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package rotate\n\n\n\nfunc rotate(m [][]int) ", "output": "{\n\tn := len(m)\n\tfor x := 0; x < (n+1)/2; x++ {\n\t\tfor y := 0; y < n/2; y++ {\n\t\t\txp, yp := n-1-x, n-1-y\n\t\t\tt := m[y][x]\n\t\t\tm[y][x] = m[xp][y]\n\t\t\tm[xp][y] = m[yp][xp]\n\t\t\tm[yp][xp] = m[x][yp]\n\t\t\tm[x][yp] = t\n\t\t}\n\t}\n}"} {"input": "func abs(n int) int {\n if n < 0 {\n return -n\n } else {\n return n\n }\n}\n\n\n\nfunc findClosestElements(arr []int, k int, x int) []int ", "output": "{\n minDiff := 0\n minDiffStart := 0\n for i := 0; i < k; i++ {\n minDiff += abs(arr[i] - x)\n }\n currentDiff := minDiff\n for i := k; i < len(arr); i++ {\n currentDiff = currentDiff - abs(arr[i-k]-x) + abs(arr[i]-x)\n \n if currentDiff < minDiff {\n minDiff = currentDiff\n minDiffStart = i-k+1\n }\n }\n return arr[minDiffStart:minDiffStart+k]\n}"} {"input": "package files\n\nimport (\n\tu \"github.com/araddon/gou\"\n\t\"github.com/lytics/cloudstorage\"\n\n\t\"github.com/araddon/qlbridge/datasource\"\n\t\"github.com/araddon/qlbridge/schema\"\n)\n\nvar (\n\t_ FileHandler = (*csvFiles)(nil)\n)\n\nfunc init() {\n\tRegisterFileHandler(\"csv\", &csvFiles{})\n}\n\n\ntype csvFiles struct {\n\tappendcols []string\n}\n\nfunc (m *csvFiles) Init(store FileStore, ss *schema.Schema) error { return nil }\nfunc (m *csvFiles) FileAppendColumns() []string { return m.appendcols }\n\nfunc (m *csvFiles) Scanner(store cloudstorage.StoreReader, fr *FileReader) (schema.ConnScanner, error) {\n\tcsv, err := datasource.NewCsvSource(fr.Table, 0, fr.F, fr.Exit)\n\tif err != nil {\n\t\tu.Errorf(\"Could not open file for csv reading %v\", err)\n\t\treturn nil, err\n\t}\n\treturn csv, nil\n}\n\nfunc (m *csvFiles) File(path string, obj cloudstorage.Object) *FileInfo ", "output": "{\n\treturn FileInfoFromCloudObject(path, obj)\n}"} {"input": "package yaml\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\n\n\n\nfunc ToYAML(rawObj interface{}) (*yaml.Node, error) {\n\tif rawObj == nil {\n\t\treturn &yaml.Node{Kind: yaml.ScalarNode, Value: \"null\", Tag: \"!!null\"}, nil\n\t}\n\n\trawJSON, err := json.Marshal(rawObj)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal object: %v\", err)\n\t}\n\n\tvar out yaml.Node\n\tif err := yaml.Unmarshal(rawJSON, &out); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to unmarshal marshalled object: %v\", err)\n\t}\n\treturn &out, nil\n}\n\n\n\n\n\n\n\nfunc SetStyle(root *yaml.Node, style yaml.Style) {\n\tchangeAll(root, func(node *yaml.Node) {\n\t\tnode.Style = style\n\t})\n}\n\nfunc changeAll(root *yaml.Node, cb func(*yaml.Node)) ", "output": "{\n\tcb(root)\n\tfor _, child := range root.Content {\n\t\tchangeAll(child, cb)\n\t}\n}"} {"input": "package services\n\nimport (\n\t\"github.com/gohugoio/hugo/config\"\n\t\"github.com/mitchellh/mapstructure\"\n)\n\nconst (\n\tservicesConfigKey = \"services\"\n\n\tdisqusShortnameKey = \"disqusshortname\"\n\tgoogleAnalyticsKey = \"googleanalytics\"\n)\n\n\ntype Config struct {\n\tDisqus Disqus\n\tGoogleAnalytics GoogleAnalytics\n\tInstagram Instagram\n\tTwitter Twitter\n}\n\n\ntype Disqus struct {\n\tShortname string\n}\n\n\ntype GoogleAnalytics struct {\n\tID string\n}\n\n\ntype Instagram struct {\n\tDisableInlineCSS bool\n}\n\n\ntype Twitter struct {\n\tDisableInlineCSS bool\n}\n\n\n\n\nfunc DecodeConfig(cfg config.Provider) (c Config, err error) ", "output": "{\n\tm := cfg.GetStringMap(servicesConfigKey)\n\n\terr = mapstructure.WeakDecode(m, &c)\n\n\tif c.GoogleAnalytics.ID == \"\" {\n\t\tc.GoogleAnalytics.ID = cfg.GetString(googleAnalyticsKey)\n\t}\n\tif c.Disqus.Shortname == \"\" {\n\t\tc.Disqus.Shortname = cfg.GetString(disqusShortnameKey)\n\t}\n\n\treturn\n}"} {"input": "package mackerel\n\n\ntype CheckStatus string\n\n\nconst (\n\tCheckStatusOK CheckStatus = \"OK\"\n\tCheckStatusWarning CheckStatus = \"WARNING\"\n\tCheckStatusCritical CheckStatus = \"CRITICAL\"\n\tCheckStatusUnknown CheckStatus = \"UNKNOWN\"\n)\n\n\ntype CheckReport struct {\n\tSource CheckSource `json:\"source\"`\n\tName string `json:\"name\"`\n\tStatus CheckStatus `json:\"status\"`\n\tMessage string `json:\"message\"`\n\tOccurredAt int64 `json:\"occurredAt\"`\n\tNotificationInterval uint `json:\"notificationInterval,omitempty\"`\n\tMaxCheckAttempts uint `json:\"maxCheckAttempts,omitempty\"`\n}\n\n\ntype CheckSource interface {\n\tCheckType() string\n\n\tisCheckSource()\n}\n\nconst checkTypeHost = \"host\"\n\n\nvar _ CheckSource = (*checkSourceHost)(nil)\n\n\n\nfunc (cs *checkSourceHost) isCheckSource() {}\n\ntype checkSourceHost struct {\n\tType string `json:\"type\"`\n\tHostID string `json:\"hostId\"`\n}\n\n\nfunc (cs *checkSourceHost) CheckType() string {\n\treturn checkTypeHost\n}\n\n\n\n\n\ntype CheckReports struct {\n\tReports []*CheckReport `json:\"reports\"`\n}\n\n\nfunc (c *Client) PostCheckReports(crs *CheckReports) error {\n\tresp, err := c.PostJSON(\"/api/v0/monitoring/checks/report\", crs)\n\tdefer closeResponse(resp)\n\treturn err\n}\n\nfunc NewCheckSourceHost(hostID string) CheckSource ", "output": "{\n\treturn &checkSourceHost{\n\t\tType: checkTypeHost,\n\t\tHostID: hostID,\n\t}\n}"} {"input": "package wml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/wml\"\n)\n\n\n\nfunc TestCT_NumRestartMarshalUnmarshal(t *testing.T) {\n\tv := wml.NewCT_NumRestart()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := wml.NewCT_NumRestart()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestCT_NumRestartConstructor(t *testing.T) ", "output": "{\n\tv := wml.NewCT_NumRestart()\n\tif v == nil {\n\t\tt.Errorf(\"wml.NewCT_NumRestart must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed wml.CT_NumRestart should validate: %s\", err)\n\t}\n}"} {"input": "package size\n\ntype BoardSize uint\n\n\nconst (\n\tB9x9 BoardSize = 9\n\tB11x11 BoardSize = 11\n\tB13x13 BoardSize = 13\n\tB15x15 BoardSize = 15\n\tB19x19 BoardSize = 19\n)\n\n\n\n\nfunc (size BoardSize) Capacity() int ", "output": "{\n\tswitch size {\n\tcase B9x9:\n\t\treturn 81\n\tcase B11x11:\n\t\treturn 121\n\tcase B13x13:\n\t\treturn 169\n\tcase B15x15:\n\t\treturn 225\n\tcase B19x19:\n\t\treturn 361\n\t}\n\treturn 0\n}"} {"input": "package cgotest\n\nimport \"testing\"\n\n\n\nfunc TestSigaltstack(t *testing.T) ", "output": "{ testSigaltstack(t) }"} {"input": "package events\n\nimport (\n\t\"fmt\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/klog\"\n)\n\ntype LoggingEventRecorder struct {\n\tcomponent string\n}\n\n\nfunc NewLoggingEventRecorder(component string) Recorder {\n\treturn &LoggingEventRecorder{component: component}\n}\n\nfunc (r *LoggingEventRecorder) ComponentName() string {\n\treturn r.component\n}\n\nfunc (r *LoggingEventRecorder) ForComponent(component string) Recorder {\n\tnewRecorder := *r\n\tnewRecorder.component = component\n\treturn &newRecorder\n}\n\nfunc (r *LoggingEventRecorder) WithComponentSuffix(suffix string) Recorder {\n\treturn r.ForComponent(fmt.Sprintf(\"%s-%s\", r.ComponentName(), suffix))\n}\n\n\n\nfunc (r *LoggingEventRecorder) Eventf(reason, messageFmt string, args ...interface{}) {\n\tr.Event(reason, fmt.Sprintf(messageFmt, args...))\n}\n\nfunc (r *LoggingEventRecorder) Warning(reason, message string) {\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeWarning, reason, message)\n\tklog.Warning(event.String())\n}\n\nfunc (r *LoggingEventRecorder) Warningf(reason, messageFmt string, args ...interface{}) {\n\tr.Warning(reason, fmt.Sprintf(messageFmt, args...))\n}\n\nfunc (r *LoggingEventRecorder) Event(reason, message string) ", "output": "{\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeNormal, reason, message)\n\tklog.Info(event.String())\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/gofxh/blog/app\"\n\t\"github.com/gofxh/blog/app/log\"\n)\n\nconst (\n\tSETTING_FORMAT_TEXT int8 = 16 \n\tSETTING_FORMAT_JSON int8 = 26 \n)\n\nvar Settings map[string]*Setting = make(map[string]*Setting)\n\n\ntype Setting struct {\n\tName string `xorm:\"unique(setting-name)\"`\n\tValue string\n\tFormat int8 `xorm:\"not null\"`\n\tUserId int64 `xorm:\"unique(setting-name)\"`\n}\n\n\nfunc (s *Setting) GetString() string {\n\treturn s.Value\n}\n\n\n\n\n\nfunc NewDefaultSetting(uid int64) []*Setting {\n\tm := make([]*Setting, 0)\n\tm = append(m, &Setting{\"theme\", \"default\", SETTING_FORMAT_TEXT, uid})\n\treturn m\n}\n\n\nfunc SaveSettings(ss []*Setting) error {\n\tsess := app.Db.NewSession()\n\tdefer sess.Close()\n\tif err := sess.Begin(); err != nil {\n\t\tlog.Error(\"Db|SaveSettings|%s\", err.Error())\n\t\treturn err\n\t}\n\tfor _, s := range ss {\n\t\tsess.Insert(s)\n\t}\n\tif err := sess.Commit(); err != nil {\n\t\tlog.Error(\"Db|SaveSettings|%s\", err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\nfunc ReadSettingsToGlobal() error {\n\tsettings := make([]*Setting, 0)\n\tif err := app.Db.Find(&settings); err != nil {\n\t\tlog.Error(\"Db|ReadSettingsToGlobal|%s\", err.Error())\n\t\treturn err\n\t}\n\tfor _, s := range settings {\n\t\tSettings[s.Name] = s\n\t}\n\treturn nil\n}\n\nfunc (s *Setting) GetJson(value interface{}) error ", "output": "{\n\treturn json.Unmarshal([]byte(s.Value), value)\n}"} {"input": "package speech_test\n\nimport (\n\t\"io\"\n\n\t\"cloud.google.com/go/speech/apiv1beta1\"\n\t\"github.com/golang/protobuf/ptypes\"\n\t\"golang.org/x/net/context\"\n\tspeechpb \"google.golang.org/genproto/googleapis/cloud/speech/v1beta1\"\n)\n\nfunc ExampleNewClient() {\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\n\n\nfunc ExampleClient_AsyncRecognize() {\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &speechpb.AsyncRecognizeRequest{\n\t}\n\top, err := c.AsyncRecognize(ctx, req)\n\tif err != nil {\n\t}\n\n\tvar resp ptypes.DynamicAny \n\tif err := op.Wait(ctx, &resp); err != nil {\n\t}\n}\n\nfunc StreamingRecognize() {\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\tstream, err := c.StreamingRecognize(ctx)\n\tif err != nil {\n\t}\n\tgo func() {\n\t\treqs := []*speechpb.StreamingRecognizeRequest{\n\t\t}\n\t\tfor _, req := range reqs {\n\t\t\tif err := stream.Send(req); err != nil {\n\t\t\t}\n\t\t}\n\t\tstream.CloseSend()\n\t}()\n\tfor {\n\t\tresp, err := stream.Recv()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}\n\nfunc ExampleClient_SyncRecognize() ", "output": "{\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &speechpb.SyncRecognizeRequest{\n\t}\n\tresp, err := c.SyncRecognize(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}"} {"input": "package wifi\n\nvar _ = WiFi(&StubWorker{})\n\ntype StubWorker struct {\n\tOptions []Option\n\tID string\n}\n\nfunc (w *StubWorker) Scan() ([]Option, error) {\n\treturn w.Options, nil\n}\n\nfunc (w *StubWorker) GetID() (string, error) {\n\treturn w.ID, nil\n}\n\n\n\nfunc NewStubWorker(id string, options ...Option) (WiFi, error) {\n\treturn &StubWorker{ID: id, Options: options}, nil\n}\n\nfunc (*StubWorker) Connect(a ...string) error ", "output": "{\n\treturn nil\n}"} {"input": "package references\n\nimport (\n\t\"github.com/zxh0/jvm.go/instructions/base\"\n\t\"github.com/zxh0/jvm.go/rtda\"\n\t\"github.com/zxh0/jvm.go/rtda/heap\"\n)\n\n\n\ntype InvokeSpecial struct{ base.Index16Instruction }\n\n\n\nfunc (instr *InvokeSpecial) Execute(frame *rtda.Frame) ", "output": "{\n\tcp := frame.GetConstantPool()\n\tk := cp.GetConstant(instr.Index)\n\tif kMethodRef, ok := k.(*heap.ConstantMethodRef); ok {\n\t\tmethod := kMethodRef.GetMethod(false)\n\t\tframe.Thread.InvokeMethod(method)\n\t} else {\n\t\tmethod := k.(*heap.ConstantInterfaceMethodRef).GetMethod(false)\n\t\tframe.Thread.InvokeMethod(method)\n\t}\n}"} {"input": "package testing\n\nimport \"k8s.io/kubernetes/pkg/util/iptables\"\n\n\ntype fake struct{}\n\nfunc NewFake() *fake {\n\treturn &fake{}\n}\n\nfunc (*fake) EnsureChain(table iptables.Table, chain iptables.Chain) (bool, error) {\n\treturn true, nil\n}\n\nfunc (*fake) FlushChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) DeleteChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\n\n\nfunc (*fake) DeleteRule(table iptables.Table, chain iptables.Chain, args ...string) error {\n\treturn nil\n}\n\nfunc (*fake) IsIpv6() bool {\n\treturn false\n}\n\nfunc (*fake) Save(table iptables.Table) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\nfunc (*fake) SaveAll() ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\nfunc (*fake) Restore(table iptables.Table, data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\n\nfunc (*fake) RestoreAll(data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\nfunc (*fake) AddReloadFunc(reloadFunc func()) {}\n\nfunc (*fake) Destroy() {}\n\nvar _ = iptables.Interface(&fake{})\n\nfunc (*fake) EnsureRule(position iptables.RulePosition, table iptables.Table, chain iptables.Chain, args ...string) (bool, error) ", "output": "{\n\treturn true, nil\n}"} {"input": "package loadbalancer\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype DeleteLoadBalancerRequest struct {\n\n\tLoadBalancerId *string `mandatory:\"true\" contributesTo:\"path\" name:\"loadBalancerId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteLoadBalancerRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request DeleteLoadBalancerRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteLoadBalancerResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n}\n\nfunc (response DeleteLoadBalancerResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteLoadBalancerResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteLoadBalancerRequest) HTTPRequest(method, path string) (http.Request, error) ", "output": "{\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}"} {"input": "package ostore\n\nimport (\n\t\"crypto/sha512\"\n\t\"encoding/hex\"\n\t\"hash\"\n\t\"io\"\n)\n\ntype HashReader struct {\n\th hash.Hash\n\tr io.Reader\n}\n\n\n\nfunc (hr *HashReader) Read(p []byte) (int, error) {\n\tn, err := hr.r.Read(p)\n\tif err != nil {\n\t\treturn n, err\n\t}\n\twn := 0\n\ttn := 0\n\tfor wn, err = hr.h.Write(p[:n]); err != nil && wn < n; {\n\t\ttn, err = hr.h.Write(p[wn:n])\n\t\twn += tn\n\t}\n\treturn n, err\n}\n\nfunc (hr *HashReader) Digest() []byte {\n\treturn hr.h.Sum(nil)\n}\n\nfunc (hr *HashReader) HexDigest() string {\n\treturn hex.EncodeToString(hr.Digest())\n}\n\nfunc NewHashReader(r io.Reader) *HashReader ", "output": "{\n\treturn &HashReader{sha512.New(), r}\n}"} {"input": "package cover\n\nimport (\n\t\"flag\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc ParseAndStripTestFlags() {\n\tflag.Parse()\n\n\tvar runtimeArgs []string\n\tfor _, arg := range os.Args {\n\t\tif strings.HasPrefix(arg, \"-test.\") ||\n\t\t\tstrings.HasPrefix(arg, \"-httptest.\") {\n\t\t\tcontinue\n\t\t}\n\t\truntimeArgs = append(runtimeArgs, arg)\n\t}\n\tos.Args = runtimeArgs\n}\n\ntype dummyTestDeps func(pat, str string) (bool, error)\n\n\nfunc (d dummyTestDeps) StartCPUProfile(io.Writer) error { return nil }\nfunc (d dummyTestDeps) StopCPUProfile() {}\nfunc (f dummyTestDeps) StartTestLog(w io.Writer) {}\nfunc (f dummyTestDeps) StopTestLog() error { return nil }\nfunc (d dummyTestDeps) WriteHeapProfile(io.Writer) error { return nil }\nfunc (d dummyTestDeps) WriteProfileTo(string, io.Writer, int) error { return nil }\nfunc (f dummyTestDeps) ImportPath() string { return \"\" }\n\n\n\n\n\nfunc FlushProfiles() {\n\toldstdout := os.Stdout\n\toldstderr := os.Stderr\n\tos.Stdout, _ = os.Open(os.DevNull)\n\tos.Stderr, _ = os.Open(os.DevNull)\n\n\ttests := []testing.InternalTest{}\n\tbenchmarks := []testing.InternalBenchmark{}\n\texamples := []testing.InternalExample{}\n\tvar f dummyTestDeps\n\tdummyM := testing.MainStart(f, tests, benchmarks, examples)\n\tdummyM.Run()\n\n\tos.Stdout = oldstdout\n\tos.Stderr = oldstderr\n}\n\nfunc (d dummyTestDeps) MatchString(pat, str string) (bool, error) ", "output": "{ return false, nil }"} {"input": "package lua\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestPushFStringPointer(t *testing.T) {\n\tl := NewState()\n\tl.PushFString(\"%p %s\", l, \"test\")\n\n\texpected := fmt.Sprintf(\"%p %s\", l, \"test\")\n\tactual := CheckString(l, -1)\n\tif expected != actual {\n\t\tt.Errorf(\"PushFString, expected \\\"%s\\\" but found \\\"%s\\\"\", expected, actual)\n\t}\n}\n\n\n\nfunc TestToBooleanOutOfRange(t *testing.T) ", "output": "{\n\tl := NewState()\n\tl.SetTop(0)\n\tl.PushBoolean(false)\n\tl.PushBoolean(true)\n\n\tfor i, want := range []bool{false, true, false, false} {\n\t\tidx := 1 + i\n\t\tif got := l.ToBoolean(idx); got != want {\n\t\t\tt.Errorf(\"l.ToBoolean(%d) = %t; want %t\", idx, got, want)\n\t\t}\n\t}\n}"} {"input": "package commands\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/etcinit/nexii/util\"\n)\n\n\n\n\n\nfunc PingCommand(c *cli.Context) ", "output": "{\n\tclient, err := util.MakeClient(c)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\terrs := client.Ping(c.String(\"name\"), c.String(\"message\"))\n\n\tif errs != nil {\n\t\tfmt.Println(errs)\n\t\treturn\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/arschles/assert\"\n)\n\nfunc testDataDir() (string, error) {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(wd, \"testdata\"), nil\n}\n\n\n\nfunc TestCreateAndRenderTpl(t *testing.T) ", "output": "{\n\ttd, err := testDataDir()\n\tassert.NoErr(t, err)\n\ttemplateNames := []string{\n\t\t\"sprig.tpl\",\n\t\t\"pwd.tpl\",\n\t}\n\tenvs := collectEnv()\n\tfor i, tplName := range templateNames {\n\t\tfName := filepath.Join(td, tplName)\n\t\ttpl, err := createTpl(filepath.Base(fName), fName)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Error creating template %d (%s)\", i, err)\n\t\t\tcontinue\n\t\t}\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := renderTpl(tpl, buf, envs); err != nil {\n\t\t\tt.Errorf(\"Error rendering template %d (%s)\", i, err)\n\t\t}\n\t}\n}"} {"input": "package v1beta1\n\n\n\ntype ForZoneApplyConfiguration struct {\n\tName *string `json:\"name,omitempty\"`\n}\n\n\n\nfunc ForZone() *ForZoneApplyConfiguration {\n\treturn &ForZoneApplyConfiguration{}\n}\n\n\n\n\n\n\nfunc (b *ForZoneApplyConfiguration) WithName(value string) *ForZoneApplyConfiguration ", "output": "{\n\tb.Name = &value\n\treturn b\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\n\tv1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/client-go/tools/cache\"\n\t\"k8s.io/component-helpers/storage/ephemeral\"\n)\n\nconst (\n\tPodPVCIndex = \"pod-pvc-index\"\n)\n\n\n\n\nfunc PodPVCIndexFunc() func(obj interface{}) ([]string, error) {\n\treturn func(obj interface{}) ([]string, error) {\n\t\tpod, ok := obj.(*v1.Pod)\n\t\tif !ok {\n\t\t\treturn []string{}, nil\n\t\t}\n\t\tkeys := []string{}\n\t\tfor _, podVolume := range pod.Spec.Volumes {\n\t\t\tclaimName := \"\"\n\t\t\tif pvcSource := podVolume.VolumeSource.PersistentVolumeClaim; pvcSource != nil {\n\t\t\t\tclaimName = pvcSource.ClaimName\n\t\t\t} else if podVolume.VolumeSource.Ephemeral != nil {\n\t\t\t\tclaimName = ephemeral.VolumeClaimName(pod, &podVolume)\n\t\t\t}\n\t\t\tif claimName != \"\" {\n\t\t\t\tkeys = append(keys, fmt.Sprintf(\"%s/%s\", pod.Namespace, claimName))\n\t\t\t}\n\t\t}\n\t\treturn keys, nil\n\t}\n}\n\n\nfunc AddPodPVCIndexerIfNotPresent(indexer cache.Indexer) error {\n\treturn AddIndexerIfNotPresent(indexer, PodPVCIndex, PodPVCIndexFunc())\n}\n\n\n\n\nfunc AddIndexerIfNotPresent(indexer cache.Indexer, indexName string, indexFunc cache.IndexFunc) error ", "output": "{\n\tindexers := indexer.GetIndexers()\n\tif _, ok := indexers[indexName]; ok {\n\t\treturn nil\n\t}\n\treturn indexer.AddIndexers(cache.Indexers{indexName: indexFunc})\n}"} {"input": "package utils\n\nimport (\n\t\"golang.org/x/crypto/ssh\"\n)\n\ntype SshClient interface {\n\tClose() error\n\tExecCommand(command string) (string, error)\n}\n\ntype awsSshClient struct {\n\tclient *ssh.Client\n}\n\n\n\nfunc (sshClient *awsSshClient) Close() error {\n\treturn sshClient.client.Close()\n}\n\nfunc (sshClient *awsSshClient) ExecCommand(command string) (string, error) {\n\tsession, err := sshClient.client.NewSession()\n\tif err != nil {\n\t}\n\tdefer session.Close()\n\n\toutput, err := session.Output(command)\n\n\treturn string(output), err\n}\n\nfunc GetSshClient(username string, privateKey []byte, ip string) (*awsSshClient, error) ", "output": "{\n\tsigner, err := ssh.ParsePrivateKey(privateKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: username,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t}\n\tclient, err := ssh.Dial(\"tcp\", ip+\":22\", config)\n\n\treturn &awsSshClient{client: client}, err\n}"} {"input": "package middleware\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc testTimeout(t *testing.T, timeout time.Duration) {\n\tvar (\n\t\tassert = assert.New(t)\n\n\t\texpectedRequest = \"expected request\"\n\t\texpectedResponse = \"expected response\"\n\n\t\tnextCalled = false\n\t\tnext = func(ctx context.Context, value interface{}) (interface{}, error) {\n\t\t\tnextCalled = true\n\n\t\t\tdeadline, ok := ctx.Deadline()\n\t\t\tassert.False(deadline.IsZero())\n\t\t\tassert.True(ok)\n\t\t\tassert.NotNil(ctx.Done())\n\n\t\t\treturn expectedResponse, nil\n\t\t}\n\n\t\tmiddleware = Timeout(timeout)\n\t)\n\n\tactualResponse, err := middleware(next)(context.Background(), expectedRequest)\n\tassert.Equal(expectedResponse, actualResponse)\n\tassert.NoError(err)\n\tassert.True(nextCalled)\n}\n\n\n\nfunc TestTimeout(t *testing.T) ", "output": "{\n\tfor _, timeout := range []time.Duration{-1, 0, 15 * time.Second, 120 * time.Hour} {\n\t\tt.Run(timeout.String(), func(t *testing.T) {\n\t\t\ttestTimeout(t, timeout)\n\t\t})\n\t}\n}"} {"input": "package dice\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\n\n\nfunc TestRollable_DefenseDie(t *testing.T) {\n\tassert := assert.New(t)\n\n\tvar defenseDie DefenseDie\n\tvar blanks, focuses, hits, crits, evades int\n\n\tfor i := 0; i < 1000; i++ {\n\t\tdefenseDie.Roll()\n\t\tswitch defenseDie.Result() {\n\t\tcase BLANK:\n\t\t\tblanks++\n\t\tcase FOCUS:\n\t\t\tfocuses++\n\t\tcase HIT:\n\t\t\thits++\n\t\tcase CRIT:\n\t\t\tcrits++\n\t\tcase EVADE:\n\t\t\tevades++\n\t\t}\n\t}\n\n\tassert.InEpsilon(int(1000*3.0/8), blanks, 50)\n\tassert.InEpsilon(int(1000*2.0/8), focuses, 50)\n\tassert.Equal(0, hits)\n\tassert.Equal(0, crits)\n\tassert.InEpsilon(int(1000*3.0/8), evades, 50)\n}\n\nfunc TestRollable_AttackDie(t *testing.T) ", "output": "{\n\tassert := assert.New(t)\n\n\tvar attackDie AttackDie\n\tvar blanks, focuses, hits, crits, evades int\n\n\tfor i := 0; i < 1000; i++ {\n\t\tattackDie.Roll()\n\t\tswitch attackDie.Result() {\n\t\tcase BLANK:\n\t\t\tblanks++\n\t\tcase FOCUS:\n\t\t\tfocuses++\n\t\tcase HIT:\n\t\t\thits++\n\t\tcase CRIT:\n\t\t\tcrits++\n\t\tcase EVADE:\n\t\t\tevades++\n\t\t}\n\t}\n\n\tassert.InEpsilon(int(1000*2.0/8), blanks, 50)\n\tassert.InEpsilon(int(1000*2.0/8), focuses, 50)\n\tassert.InEpsilon(int(1000*3.0/8), hits, 50)\n\tassert.InEpsilon(int(1000*1.0/8), crits, 50)\n\tassert.Equal(0, evades)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n)\n\ntype config struct {\n\tPort string\n\tAddr string\n\tDataDir string\n\tContentType string\n}\n\n\n\nfunc (c *config) setAddr(defaultPort string) {\n\tif c.Port != \"\" {\n\t\tc.Addr = \":\" + c.Port\n\t}\n\n\tif c.Addr == \"\" {\n\t\tc.Addr = \":\" + os.Getenv(\"PORT\")\n\t}\n\n\tif c.Addr == \":\" {\n\t\tc.Addr = \":\" + defaultPort\n\t}\n}\n\nfunc (c *config) setDataDir(defaultDatadir string) {\n\tvar err error\n\n\tif c.DataDir == \"\" {\n\t\tc.DataDir = os.Getenv(\"DATADIR\")\n\t}\n\n\tif c.DataDir == \"\" {\n\t\tc.DataDir, err = os.Getwd()\n\t\tif err != nil {\n\t\t\tc.DataDir = defaultDatadir\n\t\t}\n\t}\n}\n\nfunc (c *config) setContentType() {\n\tc.ContentType = os.Getenv(\"CONTENT_TYPE\")\n\tif c.ContentType == \"\" {\n\t\tc.ContentType = \"application/json\"\n\t}\n}\n\nfunc (c *config) Grok(defaultPort, defaultDatadir string) ", "output": "{\n\tflag.StringVar(&c.DataDir, \"d\", defaultDatadir, \"root directory for files\")\n\tflag.StringVar(&c.Port, \"p\", defaultPort, \"port number on which to listen\")\n\n\tflag.Parse()\n\n\tc.setAddr(defaultPort)\n\tc.setDataDir(defaultDatadir)\n\tc.setContentType()\n}"} {"input": "package authorization\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/ransoni/uchiwa/uchiwa/authentication\"\n\t\"github.com/ransoni/uchiwa/uchiwa/logger\"\n)\n\n\n\ntype Authorization interface {\n\tHandler(http.Handler) http.Handler\n}\n\n\ntype Uchiwa struct{}\n\n\nfunc (u *Uchiwa) Handler(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\treadonly := isReadOnly(r)\n\t\tauthorized := isAuthorized(readonly, r.Method)\n\t\tif !authorized {\n\t\t\thttp.Error(w, \"Request forbidden\", http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n\n\n\n\nfunc isReadOnly(r *http.Request) bool {\n\tvar role *authentication.Role\n\n\ttoken := authentication.GetJWTFromContext(r)\n\tif token == nil { \n\t\tlogger.Debug(\"No JWT found in context\")\n\t\treturn false\n\t}\n\n\trole, err := authentication.GetRoleFromToken(token)\n\tif err != nil {\n\t\tlogger.Debug(\"Invalid token: %s\", err)\n\t\treturn true\n\t}\n\n\treturn role.Readonly\n}\n\nfunc isAuthorized(isReadOnly bool, method string) bool ", "output": "{\n\tif (method != http.MethodHead && method != http.MethodGet) && isReadOnly {\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package protobuf\n\nimport \"github.com/m3db/m3x/pool\"\n\nconst (\n\tdefaultInitBufferSize = 2880\n\n\tdefaultMaxUnaggregatedMessageSize = 50 * 1024 * 1024\n)\n\n\ntype UnaggregatedOptions interface {\n\tSetBytesPool(value pool.BytesPool) UnaggregatedOptions\n\n\tBytesPool() pool.BytesPool\n\n\tSetInitBufferSize(value int) UnaggregatedOptions\n\n\tInitBufferSize() int\n\n\tSetMaxMessageSize(value int) UnaggregatedOptions\n\n\tMaxMessageSize() int\n}\n\ntype unaggregatedOptions struct {\n\tbytesPool pool.BytesPool\n\tinitBufferSize int\n\tmaxMessageSize int\n}\n\n\nfunc NewUnaggregatedOptions() UnaggregatedOptions {\n\tp := pool.NewBytesPool(nil, nil)\n\tp.Init()\n\treturn &unaggregatedOptions{\n\t\tbytesPool: p,\n\t\tinitBufferSize: defaultInitBufferSize,\n\t\tmaxMessageSize: defaultMaxUnaggregatedMessageSize,\n\t}\n}\n\nfunc (o *unaggregatedOptions) SetBytesPool(value pool.BytesPool) UnaggregatedOptions {\n\topts := *o\n\topts.bytesPool = value\n\treturn &opts\n}\n\nfunc (o *unaggregatedOptions) BytesPool() pool.BytesPool {\n\treturn o.bytesPool\n}\n\nfunc (o *unaggregatedOptions) SetInitBufferSize(value int) UnaggregatedOptions {\n\topts := *o\n\topts.initBufferSize = value\n\treturn &opts\n}\n\n\n\nfunc (o *unaggregatedOptions) SetMaxMessageSize(value int) UnaggregatedOptions {\n\topts := *o\n\topts.maxMessageSize = value\n\treturn &opts\n}\n\nfunc (o *unaggregatedOptions) MaxMessageSize() int {\n\treturn o.maxMessageSize\n}\n\nfunc (o *unaggregatedOptions) InitBufferSize() int ", "output": "{\n\treturn o.initBufferSize\n}"} {"input": "package user\n\nimport (\n\t\"context\"\n\t\"flag\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/ssoadmin\"\n)\n\ntype rm struct {\n\t*flags.ClientFlag\n}\n\nfunc init() {\n\tcli.Register(\"sso.user.rm\", &rm{})\n}\n\n\n\nfunc (cmd *rm) Usage() string {\n\treturn \"NAME\"\n}\n\nfunc (cmd *rm) Description() string {\n\treturn `Remove SSO users.\n\nExamples:\n govc sso.user.rm NAME`\n}\n\nfunc (cmd *rm) Run(ctx context.Context, f *flag.FlagSet) error {\n\treturn withClient(ctx, cmd.ClientFlag, func(c *ssoadmin.Client) error {\n\t\treturn c.DeletePrincipal(ctx, f.Arg(0))\n\t})\n}\n\nfunc (cmd *rm) Register(ctx context.Context, f *flag.FlagSet) ", "output": "{\n\tcmd.ClientFlag, ctx = flags.NewClientFlag(ctx)\n\tcmd.ClientFlag.Register(ctx, f)\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\ntype SystemSettings struct {\n\tuserStreamAcl *StreamAcl\n\tsystemStreamAcl *StreamAcl\n}\n\nfunc NewSystemSettings(\n\tuserStreamAcl *StreamAcl,\n\tsystemStreamAcl *StreamAcl,\n) *SystemSettings {\n\treturn &SystemSettings{userStreamAcl, systemStreamAcl}\n}\n\nfunc (s *SystemSettings) UserStreamAcl() *StreamAcl { return s.userStreamAcl }\n\nfunc (s *SystemSettings) SystemStreamAcl() *StreamAcl { return s.systemStreamAcl }\n\nfunc (s *SystemSettings) String() string {\n\treturn fmt.Sprintf(\"&{userStreamAcl:%+v systemStreamAcl:%+v}\", s.userStreamAcl, s.systemStreamAcl)\n}\n\ntype systemSettingsJson struct {\n\tUserStreamAcl *StreamAcl `json:\"$userStreamAcl,omitempty\"`\n\tSystemStreamAcl *StreamAcl `json:\"$systemStreamAcl,omitempty\"`\n}\n\nfunc (s *SystemSettings) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(systemSettingsJson{\n\t\tUserStreamAcl: s.userStreamAcl,\n\t\tSystemStreamAcl: s.systemStreamAcl,\n\t})\n}\n\n\n\nfunc SystemSettingsFromJsonBytes(data []byte) (*SystemSettings, error) {\n\tsystemSettings := &SystemSettings{}\n\treturn systemSettings, json.Unmarshal(data, systemSettings)\n}\n\nfunc (s *SystemSettings) UnmarshalJSON(data []byte) error ", "output": "{\n\tss := systemSettingsJson{}\n\tif err := json.Unmarshal(data, &ss); err != nil {\n\t\treturn err\n\t}\n\ts.userStreamAcl = ss.UserStreamAcl\n\ts.systemStreamAcl = ss.SystemStreamAcl\n\treturn nil\n}"} {"input": "package fenwick\n\n\n\ntype Fenwick struct {\n\ttree []int\n}\n\n\n\n\n\nfunc (fen *Fenwick) Sum(index int) int {\n\tsum := 1\n\tindex++\n\tfor index > 0 {\n\t\tsum *= fen.tree[index-1]\n\t\tindex -= lsb(index)\n\t}\n\treturn sum\n}\n\n\nfunc lsb(x int) int {\n\treturn x & -x\n}\n\n\nfunc (fen *Fenwick) Update(index, value int) {\n\tindex++\n\tfor index <= fen.Size() {\n\t\tfen.tree[index-1] *= value\n\t\tindex += lsb(index)\n\t}\n}\n\n\nfunc (fen *Fenwick) Size() int {\n\treturn len(fen.tree)\n}\n\nfunc NewFenwick(n int) *Fenwick ", "output": "{\n\tfen := &Fenwick{\n\t\ttree: make([]int, n),\n\t}\n\tfor i := range fen.tree {\n\t\tfen.tree[i] = 1\n\t}\n\treturn fen\n}"} {"input": "package archive\n\n\n\nimport (\n\t\"os\"\n\n\t\"github.com/martinlindhe/formats/parse\"\n)\n\n\nfunc VDI(c *parse.Checker) (*parse.ParsedLayout, error) {\n\n\tif !isVDI(c.Header) {\n\t\treturn nil, nil\n\t}\n\treturn parseVDI(c.File, c.ParsedLayout)\n}\n\n\n\nfunc parseVDI(file *os.File, pl parse.ParsedLayout) (*parse.ParsedLayout, error) {\n\n\tpos := int64(0)\n\tpl.FileKind = parse.Archive\n\tpl.Layout = []parse.Layout{{\n\t\tOffset: pos,\n\t\tLength: 40,\n\t\tInfo: \"header\",\n\t\tType: parse.Group,\n\t\tChilds: []parse.Layout{\n\t\t\t{Offset: pos, Length: 40, Info: \"magic\", Type: parse.ASCII},\n\t\t}}}\n\n\treturn &pl, nil\n}\n\nfunc isVDI(b []byte) bool ", "output": "{\n\n\ts := string(b[0:40])\n\treturn s == \"<<< Oracle VM VirtualBox Disk Image >>>\"+\"\\n\"\n}"} {"input": "package main\n\nimport \"fmt\"\n\ntype QU struct {\n\tid []int\n}\n\n\n\nfunc (q *QU) Root(i int) int {\n\tfor i != q.id[i] {\n\t\ti = q.id[i]\n\t}\n\treturn i\n}\n\nfunc (q *QU) Union(a int, b int) {\n\ti := q.Root(a)\n\tj := q.Root(b)\n\tq.id[i] = j\n}\n\nfunc (q *QU) Connected(a int, b int) bool {\n\treturn q.Root(a) == q.Root(b)\n}\n\nfunc main() {\n\tqu := QU{}\n\tqu.Init(10)\n\tfmt.Printf(\"Array initialized. %v\", qu.id)\n\tqu.Union(3, 4)\n\tqu.Union(4, 8)\n\tfmt.Printf(\"\\n\\n%v is Connected to %v %v\", 3, 8, qu.Connected(3, 8))\n}\n\nfunc (q *QU) Init(size int) ", "output": "{\n\tfor i := 0; i < size; i++ {\n\t\tq.id = append(q.id, i)\n\t}\n}"} {"input": "package smbios\n\nimport (\n\t\"io\"\n)\n\n\n\n\nfunc stream() (io.ReadCloser, EntryPoint, error) ", "output": "{\n\treturn devMemStream()\n}"} {"input": "package reaperlog\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/rifflock/lfshook\"\n\t\"go.mozilla.org/mozlogrus\"\n)\n\nvar config LogConfig\n\ntype LogConfig struct {\n\tExtras bool\n}\n\n\n\nfunc EnableMozlog() {\n\tmozlogrus.Enable(\"Reaper\")\n}\n\nfunc Extras() bool {\n\treturn config.Extras\n}\n\nfunc SetConfig(c *LogConfig) {\n\tconfig = *c\n}\n\nfunc AddLogFile(filename string) {\n\tlog.AddHook(lfshook.NewHook(lfshook.PathMap{\n\t\tlog.DebugLevel: filename,\n\t\tlog.InfoLevel: filename,\n\t\tlog.WarnLevel: filename,\n\t\tlog.ErrorLevel: filename,\n\t\tlog.FatalLevel: filename,\n\t\tlog.PanicLevel: filename,\n\t}))\n}\n\nfunc Debug(format string, args ...interface{}) {\n\tlog.Debugf(format, args...)\n}\n\nfunc Info(format string, args ...interface{}) {\n\tlog.Infof(format, args...)\n}\n\nfunc Warning(format string, args ...interface{}) {\n\tlog.Warningf(format, args...)\n}\n\nfunc Fatal(format string, args ...interface{}) {\n\tlog.Fatalf(format, args...)\n}\n\nfunc Panic(format string, args ...interface{}) {\n\tlog.Panicf(format, args...)\n}\n\nfunc Error(format string, args ...interface{}) {\n\tlog.Errorf(format, args...)\n}\n\nfunc EnableExtras() ", "output": "{\n\tconfig.Extras = true\n}"} {"input": "package client\n\nimport \"fmt\"\n\nconst _Reason_name = \"NoFailurePreCheckFailureContCheckFailureMaxFailures\"\n\nvar _Reason_index = [...]uint8{0, 9, 24, 40, 51}\n\n\n\nfunc (i Reason) String() string ", "output": "{\n\tif i < 0 || i >= Reason(len(_Reason_index)-1) {\n\t\treturn fmt.Sprintf(\"Reason(%d)\", i)\n\t}\n\treturn _Reason_name[_Reason_index[i]:_Reason_index[i+1]]\n}"} {"input": "package memconn\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"sync\"\n)\n\ntype memconn struct {\n\tsync.Once\n\taddr addr\n\tbsiz uint64\n\tchcn chan net.Conn\n\tdone func()\n\tpool *sync.Pool\n}\n\nfunc (m *memconn) Dial() (net.Conn, error) {\n\tr, w := pipe(&m.addr, m.pool)\n\tgo func() {\n\t\tm.chcn <- r\n\t}()\n\treturn w, nil\n}\n\nfunc (m *memconn) Accept() (net.Conn, error) {\n\tfor c := range m.chcn {\n\t\treturn c, nil\n\t}\n\treturn nil, http.ErrServerClosed\n}\n\nfunc (m *memconn) Close() error {\n\tm.Do(func() {\n\t\tclose(m.chcn)\n\t\tm.done()\n\t})\n\treturn http.ErrServerClosed\n}\n\n\n\nfunc (m *memconn) Addr() net.Addr ", "output": "{\n\treturn m.addr\n}"} {"input": "package contextutil_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/arjantop/cuirass/util/contextutil\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"golang.org/x/net/context\"\n)\n\nfunc TestDoErrorReturned(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\terr := contextutil.Do(ctx, func() error {\n\t\treturn errors.New(\"foo\")\n\t})\n\tassert.Equal(t, errors.New(\"foo\"), err)\n}\n\n\n\nfunc TestDoWithCancelTimeout(t *testing.T) {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond)\n\tdefer cancel()\n\tvar called bool\n\terr := contextutil.DoWithCancel(ctx, func() { called = true }, func() error {\n\t\ttime.Sleep(2 * time.Nanosecond)\n\t\treturn nil\n\t})\n\tassert.Equal(t, context.DeadlineExceeded, err)\n}\n\nfunc TestDoWithCancelErrorReturned(t *testing.T) ", "output": "{\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\terr := contextutil.DoWithCancel(ctx, func() {}, func() error {\n\t\treturn errors.New(\"foo\")\n\t})\n\tassert.Equal(t, errors.New(\"foo\"), err)\n}"} {"input": "package reveldi\n\n\ntype Container struct {\n\tservices map[string]Service\n}\n\ntype Service interface{}\n\n\n\nfunc (c *Container) Get(name string) Service {\n\treturn c.services[name]\n}\n\nfunc (c *Container) Register(name string, serviceStruct Service) ", "output": "{\n\tif len(c.services) == 0 {\n\t\tc.services = make(map[string]Service)\n\t}\n\tc.services[name] = serviceStruct\n}"} {"input": "package netx\n\nimport (\n\t\"io\"\n\n\t\"github.com/simia-tech/netx/value\"\n)\n\ntype multicast struct {\n\tlistener io.ReadCloser\n\tconn io.WriteCloser\n}\n\n\n\nfunc ListenAndDialMulticast(network, readAddress, writeAddress string, options ...value.Option) (io.ReadWriteCloser, error) {\n\tlistener, err := ListenMulticast(network, readAddress, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn, err := DialMulticast(network, writeAddress, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &multicast{listener: listener, conn: conn}, nil\n}\n\n\n\nfunc (m *multicast) Write(buffer []byte) (int, error) {\n\treturn m.conn.Write(buffer)\n}\n\nfunc (m *multicast) Close() error {\n\tif err := m.listener.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := m.conn.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (m *multicast) Read(buffer []byte) (int, error) ", "output": "{\n\treturn m.listener.Read(buffer)\n}"} {"input": "package service\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/syncloud/redirect/model\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype ActionsDbStub struct {\n\taction *model.Action\n}\n\nfunc (db *ActionsDbStub) GetAction(_ int64, _ uint64) (*model.Action, error) {\n\treturn db.action, nil\n}\nfunc (db *ActionsDbStub) GetActionByToken(_ string, _ uint64) (*model.Action, error) {\n\treturn db.action, nil\n}\n\n\n\nfunc (db *ActionsDbStub) UpdateAction(action *model.Action) error {\n\tif db.action != nil {\n\t\tdb.action = action\n\t}\n\treturn nil\n}\n\nfunc (db *ActionsDbStub) DeleteActions(_ int64) error {\n\tdb.action = nil\n\treturn nil\n}\n\nfunc (db *ActionsDbStub) DeleteAction(actionId uint64) error {\n\tdb.action = nil\n\treturn nil\n}\n\nfunc TestUpsert(t *testing.T) {\n\n\tdb := &ActionsDbStub{nil}\n\tactions := NewActions(db)\n\n\tuser := &model.User{Id: 1, Email: \"test@example.com\", PasswordHash: \"pass\", Active: true, UpdateToken: \"token\", Timestamp: time.Now()}\n\taction, err := actions.UpsertActivateAction(user.Id)\n\n\tassert.Nil(t, err)\n\tassert.NotNil(t, action)\n\tassert.NotNil(t, db.action)\n}\n\nfunc (db *ActionsDbStub) InsertAction(action *model.Action) error ", "output": "{\n\tdb.action = action\n\treturn nil\n}"} {"input": "package dingo\n\n\n\n\n\n\ntype exHooks interface {\n\tReporterHook(eventID int, payload interface{}) (err error)\n\tStoreHook(eventID int, payload interface{}) (err error)\n\tProducerHook(eventID int, payload interface{}) (err error)\n\tConsumerHook(eventID int, payload interface{}) (err error)\n}\n\ntype bridge interface {\n\texHooks\n\n\tClose() (err error)\n\tEvents() ([]<-chan *Event, error)\n\n\tSendTask(t *Task) (err error)\n\n\tAddNamedListener(name string, receipts <-chan *TaskReceipt) (tasks <-chan *Task, err error)\n\tAddListener(rcpt <-chan *TaskReceipt) (tasks <-chan *Task, err error)\n\tStopAllListeners() (err error)\n\n\tReport(name string, reports <-chan *Report) (err error)\n\n\tPoll(t *Task) (reports <-chan *Report, err error)\n\n\tAttachReporter(r Reporter) (err error)\n\tAttachStore(s Store) (err error)\n\tAttachProducer(p Producer) (err error)\n\tAttachConsumer(c Consumer, nc NamedConsumer) (err error)\n\n\tExists(it int) bool\n}\n\n\n\nfunc newBridge(which string, trans *fnMgr, args ...interface{}) bridge ", "output": "{\n\tswitch which {\n\tcase \"local\":\n\t\treturn newLocalBridge(args...)\n\tcase \"remote\":\n\t\treturn newRemoteBridge(trans)\n\tdefault:\n\t\treturn newRemoteBridge(trans)\n\t}\n\n\treturn nil\n}"} {"input": "package wrapnosurf\n\nimport (\n\t\"net/http\"\n\n\t\"gopkg.in/go-on/wrap.v2\"\n\t\"gopkg.in/go-on/nosurf.v1\"\n)\n\n\n\ntype Token string\n\n\nvar TokenField = \"csrf_token\"\n\n\n\ntype SetToken struct{}\n\nvar _ wrap.ContextWrapper = SetToken{}\n\nfunc (SetToken) ValidateContext(ctx wrap.Contexter) {\n\tvar token Token\n\tctx.SetContext(&token)\n\tctx.Context(&token)\n}\n\nfunc (SetToken) Wrap(next http.Handler) http.Handler {\n\tvar f http.HandlerFunc\n\n\tf = func(rw http.ResponseWriter, req *http.Request) {\n\t\tif req.Method == \"GET\" {\n\t\t\ttoken := Token(nosurf.Token(req))\n\t\t\trw.(wrap.Contexter).SetContext(&token)\n\t\t}\n\t\tnext.ServeHTTP(rw, req)\n\t}\n\treturn f\n}\n\n\n\n\ntype CheckToken struct {\n\tFailureHandler http.Handler\n\tBaseCookie *http.Cookie\n\tExemptPaths []string\n\tExemptGlobs []string\n\tExemptRegexps []interface{}\n\tExemptFunc func(r *http.Request) bool\n}\n\n\n\nfunc (c *CheckToken) ValidateContext(ctx wrap.Contexter) {\n\tvar token Token\n\tctx.SetContext(&token)\n\tctx.Context(&token)\n}\n\nvar _ wrap.ContextWrapper = &CheckToken{}\n\n\n\nfunc (c *CheckToken) Wrap(next http.Handler) http.Handler ", "output": "{\n\tns := nosurf.New(next)\n\tif c.BaseCookie != nil {\n\t\tns.SetBaseCookie(*c.BaseCookie)\n\t}\n\tif c.FailureHandler != nil {\n\t\tns.SetFailureHandler(c.FailureHandler)\n\t}\n\n\tif len(c.ExemptPaths) > 0 {\n\t\tns.ExemptPaths(c.ExemptPaths...)\n\t}\n\n\tif len(c.ExemptGlobs) > 0 {\n\t\tns.ExemptPaths(c.ExemptGlobs...)\n\t}\n\n\tif len(c.ExemptRegexps) > 0 {\n\t\tns.ExemptRegexps(c.ExemptRegexps...)\n\t}\n\n\tif c.ExemptFunc != nil {\n\t\tns.ExemptFunc(c.ExemptFunc)\n\t}\n\treturn ns\n}"} {"input": "package utils\n\nimport (\n\t\"reflect\"\n\t\"runtime\"\n\t\"testing\"\n)\n\nfunc assert(t *testing.T, actual interface{}, expected interface{}) {\n\tif !reflect.DeepEqual(actual, expected) {\n\t\t_, fn, line, _ := runtime.Caller(1)\n\t\tt.Errorf(\"Expected %v, actual %v\\n@%s:%d\", expected, actual, fn, line)\n\t}\n}\n\n\n\nfunc assertNot(t *testing.T, actual interface{}, expected interface{}) {\n\tif reflect.DeepEqual(actual, expected) {\n\t\t_, fn, line, _ := runtime.Caller(1)\n\t\tt.Fatalf(\"Expected anything but %v, actual %v\\n@%s:%d\", expected, actual, fn, line)\n\t}\n}\n\nfunc assertFatal(t *testing.T, actual interface{}, expected interface{}) ", "output": "{\n\tif !reflect.DeepEqual(actual, expected) {\n\t\t_, fn, line, _ := runtime.Caller(1)\n\t\tt.Fatalf(\"Expected %v, actual %v\\n@%s:%d\", expected, actual, fn, line)\n\t}\n}"} {"input": "package fs\n\nimport (\n\t\"syscall\"\n)\n\nfunc MountRootFS(path string) error {\n\treturn syscall.Mount(path, \"rootfs\", \"\", syscall.MS_BIND, \"\")\n}\n\n\n\nfunc MountDevFS() error {\n\treturn syscall.Mount(\"tmpfs\", \"/dev\", \"tmpfs\", syscall.MS_BIND, \"\")\n}\n\nfunc MountProcFS() error {\n\treturn syscall.Mount(\"proc\", \"/proc\", \"proc\", syscall.MS_BIND, \"\")\n}\n\nfunc MountSysFS() error {\n\treturn syscall.Mount(\"sysfs\", \"/sys\", \"sysfs\", syscall.MS_BIND, \"\")\n}\n\nfunc MountAdditional(source, dest, t string) error ", "output": "{\n\treturn syscall.Mount(source, dest, t, syscall.MS_BIND, \"\")\n}"} {"input": "package utils\n\nimport \"time\"\n\nconst (\n\tDateFormat = \"yyyy-MM-dd hh:mm:ss\"\n\tTimeLayout = \"2006-01-02 15:04:05\"\n\tDateLayout = \"2006-01-02\"\n)\n\nfunc Now() string {\n\treturn time.Now().Format(\"2006-01-02 15:04:05\")\n}\n\n\n\nfunc Date() string ", "output": "{\n\treturn time.Now().Format(\"2006-01-02\")\n}"} {"input": "package downloader\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/WhaleCoinOrg/WhaleCoin/core/types\"\n)\n\n\ntype peerDropFn func(id string)\n\n\ntype dataPack interface {\n\tPeerId() string\n\tItems() int\n\tStats() string\n}\n\n\ntype headerPack struct {\n\tpeerId string\n\theaders []*types.Header\n}\n\nfunc (p *headerPack) PeerId() string { return p.peerId }\nfunc (p *headerPack) Items() int { return len(p.headers) }\nfunc (p *headerPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.headers)) }\n\n\ntype bodyPack struct {\n\tpeerId string\n\ttransactions [][]*types.Transaction\n\tuncles [][]*types.Header\n}\n\nfunc (p *bodyPack) PeerId() string { return p.peerId }\nfunc (p *bodyPack) Items() int {\n\tif len(p.transactions) <= len(p.uncles) {\n\t\treturn len(p.transactions)\n\t}\n\treturn len(p.uncles)\n}\nfunc (p *bodyPack) Stats() string { return fmt.Sprintf(\"%d:%d\", len(p.transactions), len(p.uncles)) }\n\n\ntype receiptPack struct {\n\tpeerId string\n\treceipts [][]*types.Receipt\n}\n\nfunc (p *receiptPack) PeerId() string { return p.peerId }\nfunc (p *receiptPack) Items() int { return len(p.receipts) }\n\n\n\ntype statePack struct {\n\tpeerId string\n\tstates [][]byte\n}\n\nfunc (p *statePack) PeerId() string { return p.peerId }\nfunc (p *statePack) Items() int { return len(p.states) }\nfunc (p *statePack) Stats() string { return fmt.Sprintf(\"%d\", len(p.states)) }\n\nfunc (p *receiptPack) Stats() string ", "output": "{ return fmt.Sprintf(\"%d\", len(p.receipts)) }"} {"input": "package prometheus\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"text/template\"\n\n\t\"github.com/pkg/errors\"\n\n\ttm \"github.com/supergiant/control/pkg/templatemanager\"\n\t\"github.com/supergiant/control/pkg/workflows/steps\"\n)\n\nconst StepName = \"prometheus\"\n\ntype Config struct {\n\tRBACEnabled bool\n}\n\ntype Step struct {\n\tscript *template.Template\n}\n\nfunc (s *Step) Rollback(context.Context, io.Writer, *steps.Config) error {\n\treturn nil\n}\n\nfunc Init() {\n\ttpl, err := tm.GetTemplate(StepName)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"template %s not found\", StepName))\n\t}\n\n\tsteps.RegisterStep(StepName, New(tpl))\n}\n\n\n\nfunc (s *Step) Run(ctx context.Context, out io.Writer, config *steps.Config) error {\n\terr := steps.RunTemplate(ctx, s.script, config.Runner, out, toStepCfg(config))\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"install prometheus step\")\n\t}\n\n\treturn nil\n}\n\nfunc (s *Step) Name() string {\n\treturn StepName\n}\n\nfunc (s *Step) Description() string {\n\treturn \"Install prometheus\"\n}\n\nfunc (s *Step) Depends() []string {\n\treturn nil\n}\n\nfunc toStepCfg(c *steps.Config) Config {\n\treturn Config{\n\t\tRBACEnabled: c.Kube.RBACEnabled,\n\t}\n}\n\nfunc New(script *template.Template) *Step ", "output": "{\n\tt := &Step{\n\t\tscript: script,\n\t}\n\n\treturn t\n}"} {"input": "package kinesis\n\nimport (\n\t\"github.com/aws/aws-sdk-go/awstesting/integration/smoke\"\n\t\"github.com/aws/aws-sdk-go/service/kinesis\"\n\t\"github.com/gucumber/gucumber\"\n)\n\n\n\nfunc init() ", "output": "{\n\tgucumber.Before(\"@kinesis\", func() {\n\t\tgucumber.World[\"client\"] = kinesis.New(smoke.Session)\n\t})\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSBatchJobDefinition_NodeRangeProperty struct {\n\n\tContainer *AWSBatchJobDefinition_ContainerProperties `json:\"Container,omitempty\"`\n\n\tTargetNodes string `json:\"TargetNodes,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\n\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::Batch::JobDefinition.NodeRangeProperty\"\n}"} {"input": "package dma\n\nimport (\n\t\"stm32/hal/raw/rcc\"\n)\n\n\n\nfunc (p *DMA) disableClock() {\n\tbit(p, &rcc.RCC.AHBENR.U32, rcc.DMA1ENn).Clear()\n}\n\nfunc (p *DMA) reset() {}\n\nfunc (p *DMA) enableClock(_ bool) ", "output": "{\n\tbit := bit(p, &rcc.RCC.AHBENR.U32, rcc.DMA1ENn)\n\tbit.Set()\n\tbit.Load() \n}"} {"input": "package rest\n\nimport (\n\tnetworkingapiv1 \"k8s.io/api/networking/v1\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\t\"k8s.io/apiserver/pkg/registry/rest\"\n\tgenericapiserver \"k8s.io/apiserver/pkg/server\"\n\tserverstorage \"k8s.io/apiserver/pkg/server/storage\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\t\"k8s.io/kubernetes/pkg/apis/networking\"\n\tnetworkpolicystore \"k8s.io/kubernetes/pkg/registry/networking/networkpolicy/storage\"\n)\n\ntype RESTStorageProvider struct{}\n\nfunc (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(networking.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\n\tif apiResourceConfigSource.VersionEnabled(networkingapiv1.SchemeGroupVersion) {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[networkingapiv1.SchemeGroupVersion.Version] = p.v1alpha1Storage(apiResourceConfigSource, restOptionsGetter)\n\t}\n\n\treturn apiGroupInfo, true\n}\n\nfunc (p RESTStorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage {\n\tstorage := map[string]rest.Storage{}\n\tnetworkPolicyStorage := networkpolicystore.NewREST(restOptionsGetter)\n\tstorage[\"networkpolicies\"] = networkPolicyStorage\n\n\treturn storage\n}\n\n\n\nfunc (p RESTStorageProvider) GroupName() string ", "output": "{\n\treturn networking.GroupName\n}"} {"input": "package udt\n\n\n\nimport (\n\t\"io\"\n)\n\ntype ack2Packet struct {\n\th header\n\tackSeqNo uint32 \n}\n\nfunc (p *ack2Packet) socketId() (sockId uint32) {\n\treturn p.h.dstSockId\n}\n\nfunc (p *ack2Packet) sendTime() (ts uint32) {\n\treturn p.h.ts\n}\n\n\n\nfunc (p *ack2Packet) readFrom(r io.Reader) (err error) {\n\tp.ackSeqNo, err = p.h.readFrom(r)\n\treturn\n}\n\nfunc (p *ack2Packet) writeTo(w io.Writer) (err error) ", "output": "{\n\tif err := p.h.writeTo(w, ack2, p.ackSeqNo); err != nil {\n\t\treturn err\n\t}\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/codegangsta/negroni\"\n)\n\n\n\nfunc method(method string) negroni.Handler ", "output": "{\n\thandler := func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\t\tif r.Method != method {\n\t\t\thttp.Error(w, \"Method Not Allowed\", http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\t\tnext(w, r)\n\t}\n\treturn negroni.HandlerFunc(handler)\n}"} {"input": "package net\n\nimport (\n\t\"runtime\"\n\t\"syscall\"\n\t\"time\"\n)\n\nconst sysTCP_KEEPINTVL = 0x101\n\n\n\nfunc setKeepAlivePeriod(fd *netFD, d time.Duration) error ", "output": "{\n\td += (time.Second - time.Nanosecond)\n\tsecs := int(d.Seconds())\n\tswitch err := fd.pfd.SetsockoptInt(syscall.IPPROTO_TCP, sysTCP_KEEPINTVL, secs); err {\n\tcase nil, syscall.ENOPROTOOPT: \n\tdefault:\n\t\treturn wrapSyscallError(\"setsockopt\", err)\n\t}\n\terr := fd.pfd.SetsockoptInt(syscall.IPPROTO_TCP, syscall.TCP_KEEPALIVE, secs)\n\truntime.KeepAlive(fd)\n\treturn wrapSyscallError(\"setsockopt\", err)\n}"} {"input": "package textgen\n\nimport (\n \"math/rand\"\n \"testing\"\n \"time\"\n)\n\nvar (\n text = \"[Test|Text|Guest|Start it|Crash it] [for|not for] [example|fun|you|us]! Oh ya!\"\n)\n\nfunc init() {\n rand.Seed(time.Now().UTC().UnixNano() ^ int64(time.Now().Nanosecond()))\n}\n\n\n\n\n\nfunc TestPrepareVariants(t *testing.T) {\n all, variants, err := PrepareVariants(text)\n max := 1\n\n if nil != variants {\n for _, a := range variants {\n max *= len(a)\n }\n }\n\n t.Logf(\"All Variants: %v\", all)\n t.Logf(\"Variants: %v, %v\", variants, err)\n t.Logf(\"Variants MAX: %d\", max)\n\n if nil != err {\n t.Error(err)\n }\n}\n\nfunc TestProcessRandom(t *testing.T) {\n gen_text, err := ProcessRandom(text, nil)\n t.Logf(\"ProcessRandom: %v, %v\", gen_text, err)\n\n if nil != err {\n t.Error(err)\n }\n}\n\nfunc TestGenerateRandom(t *testing.T) {\n i := 1\n for s := range GenerateRandom(text, 0, 10, true) {\n t.Logf(\"GenerateRandom: %d) %v\", i, s)\n i++\n }\n}\n\n\n\nfunc TestGenerate(t *testing.T) ", "output": "{\n i := 1\n for s := range Generate(text, 0) {\n t.Logf(\"Generate: %d) %v\", i, s)\n i++\n }\n}"} {"input": "package controller\n\nimport (\n\t\"github.com/op/go-logging\"\n\t\"github.com/spf13/viper\"\n\n\t\"github.com/openblockchain/obc-peer/openchain/consensus\"\n\t\"github.com/openblockchain/obc-peer/openchain/consensus/noops\"\n\t\"github.com/openblockchain/obc-peer/openchain/consensus/obcpbft\"\n)\n\nvar logger *logging.Logger \n\n\n\n\nfunc NewConsenter(stack consensus.Stack) (consenter consensus.Consenter) {\n\tplugin := viper.GetString(\"peer.validator.consensus\")\n\tif plugin == \"obcpbft\" {\n\t\tconsenter = obcpbft.GetPlugin(stack)\n\t} else {\n\t\tconsenter = noops.GetNoops(stack)\n\t}\n\treturn\n}\n\nfunc init() ", "output": "{\n\tlogger = logging.MustGetLogger(\"consensus/controller\")\n}"} {"input": "package deploymentmanager\n\n\n\n\n\n\n\n\ntype DeploymentMode string\n\nconst (\n\tComplete DeploymentMode = \"Complete\"\n\tIncremental DeploymentMode = \"Incremental\"\n)\n\n\n\n\n\ntype StepType string\n\nconst (\n\tStepTypeStepProperties StepType = \"StepProperties\"\n\tStepTypeWait StepType = \"Wait\"\n)\n\n\nfunc PossibleStepTypeValues() []StepType {\n\treturn []StepType{StepTypeStepProperties, StepTypeWait}\n}\n\n\ntype Type string\n\nconst (\n\tTypeAuthentication Type = \"Authentication\"\n\tTypeSas Type = \"Sas\"\n)\n\n\nfunc PossibleTypeValues() []Type {\n\treturn []Type{TypeAuthentication, TypeSas}\n}\n\nfunc PossibleDeploymentModeValues() []DeploymentMode ", "output": "{\n\treturn []DeploymentMode{Complete, Incremental}\n}"} {"input": "package events\n\nimport (\n\t\"fmt\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/klog\"\n)\n\ntype LoggingEventRecorder struct {\n\tcomponent string\n}\n\n\nfunc NewLoggingEventRecorder(component string) Recorder {\n\treturn &LoggingEventRecorder{component: component}\n}\n\nfunc (r *LoggingEventRecorder) ComponentName() string {\n\treturn r.component\n}\n\n\n\nfunc (r *LoggingEventRecorder) WithComponentSuffix(suffix string) Recorder {\n\treturn r.ForComponent(fmt.Sprintf(\"%s-%s\", r.ComponentName(), suffix))\n}\n\nfunc (r *LoggingEventRecorder) Event(reason, message string) {\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeNormal, reason, message)\n\tklog.Info(event.String())\n}\n\nfunc (r *LoggingEventRecorder) Eventf(reason, messageFmt string, args ...interface{}) {\n\tr.Event(reason, fmt.Sprintf(messageFmt, args...))\n}\n\nfunc (r *LoggingEventRecorder) Warning(reason, message string) {\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeWarning, reason, message)\n\tklog.Warning(event.String())\n}\n\nfunc (r *LoggingEventRecorder) Warningf(reason, messageFmt string, args ...interface{}) {\n\tr.Warning(reason, fmt.Sprintf(messageFmt, args...))\n}\n\nfunc (r *LoggingEventRecorder) ForComponent(component string) Recorder ", "output": "{\n\tnewRecorder := *r\n\tnewRecorder.component = component\n\treturn &newRecorder\n}"} {"input": "package wml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/wml\"\n)\n\nfunc TestCT_NumRestartConstructor(t *testing.T) {\n\tv := wml.NewCT_NumRestart()\n\tif v == nil {\n\t\tt.Errorf(\"wml.NewCT_NumRestart must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed wml.CT_NumRestart should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestCT_NumRestartMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := wml.NewCT_NumRestart()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := wml.NewCT_NumRestart()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package mocks\n\nimport (\n\t\"crypto/x509\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\n\t\"github.com/letsencrypt/boulder/core\"\n)\n\n\n\ntype MockCA struct {\n\tPEM []byte\n}\n\n\nfunc (ca *MockCA) IssueCertificate(csr x509.CertificateRequest, regID int64) (core.Certificate, error) {\n\tif ca.PEM == nil {\n\t\treturn core.Certificate{}, fmt.Errorf(\"MockCA's PEM field must be set before calling IssueCertificate\")\n\t}\n\tblock, _ := pem.Decode(ca.PEM)\n\tcert, err := x509.ParseCertificate(block.Bytes)\n\tif err != nil {\n\t\treturn core.Certificate{}, err\n\t}\n\treturn core.Certificate{\n\t\tDER: cert.Raw,\n\t}, nil\n}\n\n\nfunc (ca *MockCA) GenerateOCSP(xferObj core.OCSPSigningRequest) (ocsp []byte, err error) {\n\treturn\n}\n\n\n\n\nfunc (ca *MockCA) RevokeCertificate(serial string, reasonCode core.RevocationCode) (err error) ", "output": "{\n\treturn\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n\n\t\"github.com/boltdb/bolt\"\n)\n\nfunc MemoryLocalStore() LocalStore {\n\treturn make(memoryLocalStore)\n}\n\ntype memoryLocalStore map[string]json.RawMessage\n\nfunc (m memoryLocalStore) GetMeta() (map[string]json.RawMessage, error) {\n\treturn m, nil\n}\n\nfunc (m memoryLocalStore) SetMeta(name string, meta json.RawMessage) error {\n\tm[name] = meta\n\treturn nil\n}\n\nconst dbBucket = \"tuf-client\"\n\nfunc FileLocalStore(path string) (LocalStore, error) {\n\tdb, err := bolt.Open(path, 0600, &bolt.Options{Timeout: time.Second})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := db.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucketIfNotExists([]byte(dbBucket))\n\t\treturn err\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &fileLocalStore{db: db}, nil\n}\n\ntype fileLocalStore struct {\n\tdb *bolt.DB\n}\n\n\n\nfunc (f *fileLocalStore) SetMeta(name string, meta json.RawMessage) error {\n\treturn f.db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(dbBucket))\n\t\treturn b.Put([]byte(name), meta)\n\t})\n}\n\nfunc (f *fileLocalStore) GetMeta() (map[string]json.RawMessage, error) ", "output": "{\n\tmeta := make(map[string]json.RawMessage)\n\tif err := f.db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(dbBucket))\n\t\tb.ForEach(func(k, v []byte) error {\n\t\t\tvcopy := make([]byte, len(v))\n\t\t\tcopy(vcopy, v)\n\t\t\tmeta[string(k)] = vcopy\n\t\t\treturn nil\n\t\t})\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn meta, nil\n}"} {"input": "package premailer\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestBasicHTMLFromFile(t *testing.T) {\n\tp, err := NewPremailerFromFile(\"data/markup_test.html\", nil)\n\tassert.Nil(t, err)\n\tresultHTML, err := p.Transform()\n\tassert.Nil(t, err)\n\n\tassert.Contains(t, resultHTML, \"

Hi!

\")\n\tassert.Contains(t, resultHTML, \"

There

\")\n\tassert.Contains(t, resultHTML, \"

Hello

\")\n\tassert.Contains(t, resultHTML, \"

Yes!

\")\n\tassert.Contains(t, resultHTML, \"
Green color
\")\n}\n\n\n\nfunc TestFromFileNotFound(t *testing.T) ", "output": "{\n\tp, err := NewPremailerFromFile(\"data/blablabla.html\", nil)\n\tassert.NotNil(t, err)\n\tassert.Nil(t, p)\n}"} {"input": "package transport\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"net/http\"\n)\n\n\ntype Config struct {\n\tUserAgent string\n\n\tTLS TLSConfig\n\n\tUsername string\n\tPassword string\n\n\tBearerToken string\n\n\tImpersonate ImpersonationConfig\n\n\tTransport http.RoundTripper\n\n\tWrapTransport func(rt http.RoundTripper) http.RoundTripper\n\n\tDial func(ctx context.Context, network, address string) (net.Conn, error)\n}\n\n\ntype ImpersonationConfig struct {\n\tUserName string\n\tGroups []string\n\tExtra map[string][]string\n}\n\n\nfunc (c *Config) HasCA() bool {\n\treturn len(c.TLS.CAData) > 0 || len(c.TLS.CAFile) > 0\n}\n\n\nfunc (c *Config) HasBasicAuth() bool {\n\treturn len(c.Username) != 0\n}\n\n\nfunc (c *Config) HasTokenAuth() bool {\n\treturn len(c.BearerToken) != 0\n}\n\n\n\n\n\ntype TLSConfig struct {\n\tCAFile string \n\tCertFile string \n\tKeyFile string \n\n\tInsecure bool \n\tServerName string \n\n\tCAData []byte \n\tCertData []byte \n\tKeyData []byte \n}\n\nfunc (c *Config) HasCertAuth() bool ", "output": "{\n\treturn len(c.TLS.CertData) != 0 || len(c.TLS.CertFile) != 0\n}"} {"input": "package validation\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/client-go/kubernetes/fake\"\n)\n\n\n\n\n\n\n\n\n\nfunc TestWaitForNodeToBeReady(t *testing.T) {\n\tconditions := []v1.NodeCondition{{Type: \"Ready\", Status: \"True\"}}\n\tnodeName := \"node-foo\"\n\tnodeAA := setupNodeAA(t, conditions, nodeName)\n\n\ttest, err := nodeAA.WaitForNodeToBeReady(nodeName)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif test != true {\n\t\tt.Fatalf(\"unexpected error WaitForNodeToBeReady Failed: %v\", test)\n\t}\n}\n\nfunc TestWaitForNodeToBeNotReady(t *testing.T) {\n\tconditions := []v1.NodeCondition{{Type: \"Ready\", Status: \"False\"}}\n\tnodeName := \"node-foo\"\n\tnodeAA := setupNodeAA(t, conditions, nodeName)\n\n\ttest, err := nodeAA.WaitForNodeToBeNotReady(nodeName)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif test != true {\n\t\tt.Fatalf(\"unexpected error WaitForNodeToBeNotReady Failed: %v\", test)\n\t}\n}\n\n\n\n\n\n\n\nfunc setupNodeAA(t *testing.T, conditions []v1.NodeCondition, nodeName string) *NodeAPIAdapter ", "output": "{\n\tnode := &v1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{Name: nodeName},\n\t\tSpec: v1.NodeSpec{Unschedulable: false},\n\t\tStatus: v1.NodeStatus{Conditions: conditions},\n\t}\n\n\tc := fake.NewSimpleClientset(node)\n\tnodeAA, err := NewNodeAPIAdapter(c, time.Duration(10)*time.Millisecond)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error building NodeAPIAdapter: %v\", err)\n\t}\n\treturn nodeAA\n}"} {"input": "package tequilapi\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n\ntype APIServer interface {\n\tWait() error\n\tStartServing() error\n\tStop()\n\tAddress() (string, error)\n}\n\ntype apiServer struct {\n\terrorChannel chan error\n\thandler http.Handler\n\tlistenAddress string\n\tlistener net.Listener\n}\n\n\nfunc NewServer(address string, port int, handler http.Handler, corsPolicy CorsPolicy) APIServer {\n\tserver := apiServer{\n\t\tmake(chan error, 1),\n\t\tDisableCaching(ApplyCors(handler, corsPolicy)),\n\t\tfmt.Sprintf(\"%s:%d\", address, port),\n\t\tnil}\n\treturn &server\n}\n\n\nfunc (server *apiServer) Stop() {\n\tif server.listener == nil {\n\t\treturn\n\t}\n\tserver.listener.Close()\n}\n\n\nfunc (server *apiServer) Wait() error {\n\treturn <-server.errorChannel\n}\n\n\nfunc (server *apiServer) Address() (string, error) {\n\tif server.listener == nil {\n\t\treturn \"\", errors.New(\"not bound\")\n\t}\n\treturn extractBoundAddress(server.listener)\n}\n\n\n\n\n\nfunc (server *apiServer) serve(handler http.Handler) {\n\tserver.errorChannel <- http.Serve(server.listener, handler)\n}\n\nfunc extractBoundAddress(listener net.Listener) (string, error) {\n\taddr := listener.Addr()\n\tparts := strings.Split(addr.String(), \":\")\n\tif len(parts) < 2 {\n\t\treturn \"\", errors.New(\"Unable to locate address: \" + addr.String())\n\t}\n\treturn addr.String(), nil\n}\n\nfunc (server *apiServer) StartServing() error ", "output": "{\n\tvar err error\n\tserver.listener, err = net.Listen(\"tcp\", server.listenAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo server.serve(server.handler)\n\treturn nil\n}"} {"input": "package checkers\n\nimport (\n\t\"errors\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/jkomoros/boardgame\"\n\t\"github.com/jkomoros/boardgame/base\"\n\t\"github.com/jkomoros/boardgame/moves\"\n)\n\n\n\n\ntype gameDelegate struct {\n\tbase.GameDelegate\n}\n\nvar memoizedDelegateName string\n\nfunc (g *gameDelegate) Name() string {\n\n\n\tif memoizedDelegateName == \"\" {\n\t\tpkgPath := reflect.ValueOf(g).Elem().Type().PkgPath()\n\t\tpathPieces := strings.Split(pkgPath, \"/\")\n\t\tmemoizedDelegateName = pathPieces[len(pathPieces)-1]\n\t}\n\treturn memoizedDelegateName\n}\n\nfunc (g *gameDelegate) ConfigureMoves() []boardgame.MoveConfig {\n\n\tauto := moves.NewAutoConfigurer(g)\n\n\treturn moves.Combine(\n\n\t\tmoves.Add(\n\t\t\tauto.MustConfig(new(moves.NoOp),\n\t\t\t\tmoves.WithMoveName(\"Example No Op Move\"),\n\t\t\t\tmoves.WithHelpText(\"This move is an example that is always legal and does nothing. It exists to show how to return moves and make sure 'go test' works from the beginning, but you should remove it.\"),\n\t\t\t),\n\t\t),\n\t)\n\n}\n\nfunc (g *gameDelegate) GameStateConstructor() boardgame.ConfigurableSubState {\n\treturn new(gameState)\n}\n\n\n\nfunc (g *gameDelegate) DistributeComponentToStarterStack(state boardgame.ImmutableState, c boardgame.Component) (boardgame.ImmutableStack, error) {\n\n\treturn nil, errors.New(\"Not yet implemented\")\n\n}\n\n\n\nfunc NewDelegate() boardgame.GameDelegate {\n\treturn &gameDelegate{}\n}\n\nfunc (g *gameDelegate) PlayerStateConstructor(index boardgame.PlayerIndex) boardgame.ConfigurableSubState ", "output": "{\n\treturn new(playerState)\n}"} {"input": "package message\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"mime\"\n\t\"strings\"\n)\n\ntype UnknownCharsetError struct {\n\te error\n}\n\nfunc (u UnknownCharsetError) Unwrap() error { return u.e }\n\n\n\n\n\nfunc IsUnknownCharset(err error) bool {\n\treturn errors.As(err, new(UnknownCharsetError))\n}\n\n\n\n\n\n\n\n\n\nvar CharsetReader func(charset string, input io.Reader) (io.Reader, error)\n\n\nfunc charsetReader(charset string, input io.Reader) (io.Reader, error) {\n\tcharset = strings.ToLower(charset)\n\tif charset == \"utf-8\" || charset == \"us-ascii\" {\n\t\treturn input, nil\n\t}\n\tif CharsetReader != nil {\n\t\tr, err := CharsetReader(charset, input)\n\t\tif err != nil {\n\t\t\treturn r, UnknownCharsetError{err}\n\t\t}\n\t\treturn r, nil\n\t}\n\treturn input, UnknownCharsetError{fmt.Errorf(\"message: unhandled charset %q\", charset)}\n}\n\n\n\nfunc decodeHeader(s string) (string, error) {\n\twordDecoder := mime.WordDecoder{CharsetReader: charsetReader}\n\tdec, err := wordDecoder.DecodeHeader(s)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\treturn dec, nil\n}\n\nfunc encodeHeader(s string) string {\n\treturn mime.QEncoding.Encode(\"utf-8\", s)\n}\n\nfunc (u UnknownCharsetError) Error() string ", "output": "{\n\treturn \"unknown charset: \" + u.e.Error()\n}"} {"input": "package middleware\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/zenazn/goji/web\"\n)\n\ntype autoOptionsState int\n\nconst (\n\taosInit autoOptionsState = iota\n\taosHeaderWritten\n\taosProxying\n)\n\n\n\n\n\ntype autoOptionsProxy struct {\n\tw http.ResponseWriter\n\tc *web.C\n\tstate autoOptionsState\n}\n\nfunc (p *autoOptionsProxy) Header() http.Header {\n\treturn p.w.Header()\n}\n\nfunc (p *autoOptionsProxy) Write(buf []byte) (int, error) {\n\tswitch p.state {\n\tcase aosInit:\n\t\tp.state = aosHeaderWritten\n\tcase aosProxying:\n\t\treturn len(buf), nil\n\t}\n\treturn p.w.Write(buf)\n}\n\n\n\n\n\nfunc AutomaticOptions(c *web.C, h http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == \"OPTIONS\" {\n\t\t\tw = &autoOptionsProxy{c: c, w: w}\n\t\t}\n\n\t\th.ServeHTTP(w, r)\n\t}\n\n\treturn http.HandlerFunc(fn)\n}\n\nfunc getValidMethods(c web.C) []string {\n\tif c.Env == nil {\n\t\treturn nil\n\t}\n\tv, ok := c.Env[web.ValidMethodsKey]\n\tif !ok {\n\t\treturn nil\n\t}\n\tif methods, ok := v.([]string); ok {\n\t\treturn methods\n\t}\n\treturn nil\n}\n\nfunc addMethod(methods []string, method string) []string {\n\tfor _, m := range methods {\n\t\tif m == method {\n\t\t\treturn methods\n\t\t}\n\t}\n\treturn append(methods, method)\n}\n\nfunc (p *autoOptionsProxy) WriteHeader(code int) ", "output": "{\n\tmethods := getValidMethods(*p.c)\n\tswitch p.state {\n\tcase aosInit:\n\t\tif methods != nil && code == http.StatusNotFound {\n\t\t\tp.state = aosProxying\n\t\t\tbreak\n\t\t}\n\t\tp.state = aosHeaderWritten\n\t\tfallthrough\n\tdefault:\n\t\tp.w.WriteHeader(code)\n\t\treturn\n\t}\n\n\tmethods = addMethod(methods, \"OPTIONS\")\n\tp.w.Header().Set(\"Allow\", strings.Join(methods, \", \"))\n\tp.w.WriteHeader(http.StatusOK)\n}"} {"input": "package api\n\nimport (\n\t\"go.uber.org/ratelimit\"\n\n\t\"net/http\"\n\t\"sync\"\n)\n\n\ntype RateLimitRoundTripper struct {\n\tTransport http.RoundTripper\n\tRateLimitPerSec int\n\n\tonce sync.Once\n\trateLimit ratelimit.Limiter\n}\n\n\n\n\nfunc (r *RateLimitRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) ", "output": "{\n\tr.once.Do(func() {\n\t\tr.rateLimit = ratelimit.New(r.RateLimitPerSec)\n\t})\n\tif r.Transport == nil {\n\t\tr.Transport = http.DefaultTransport\n\t}\n\n\tr.rateLimit.Take()\n\treturn r.Transport.RoundTrip(req)\n}"} {"input": "package transform\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/drone/drone-exec/yaml\"\n)\n\n\n\n\n\nfunc toScript(commands []string) string {\n\tvar buf bytes.Buffer\n\tfor _, command := range commands {\n\t\tescaped := fmt.Sprintf(\"%q\", command)\n\t\tescaped = strings.Replace(command, \"$\", `$\\`, -1)\n\t\tbuf.WriteString(fmt.Sprintf(\n\t\t\ttraceScript,\n\t\t\tescaped,\n\t\t\tcommand,\n\t\t))\n\t}\n\n\tscript := fmt.Sprintf(\n\t\tsetupScript,\n\t\tbuf.String(),\n\t)\n\n\treturn base64.StdEncoding.EncodeToString([]byte(script))\n}\n\n\n\nconst setupScript = `\nif [ -n \"$DRONE_NETRC_MACHINE\" ]; then\ncat < $HOME/.netrc\nmachine $DRONE_NETRC_MACHINE\nlogin $DRONE_NETRC_USERNAME\npassword $DRONE_NETRC_PASSWORD\nEOF\nfi\n\nunset DRONE_NETRC_USERNAME\nunset DRONE_NETRC_PASSWORD\nunset DRONE_SCRIPT\n\n%s\n`\n\n\n\nconst traceScript = `\necho + %s\n%s\n`\n\nfunc CommandTransform(c *yaml.Config) error ", "output": "{\n\tfor _, p := range c.Pipeline {\n\n\t\tif isPlugin(p) {\n\t\t\tcontinue\n\t\t}\n\n\t\tp.Entrypoint = []string{\n\t\t\t\"/bin/sh\", \"-c\",\n\t\t}\n\t\tp.Command = []string{\n\t\t\t\"echo $DRONE_SCRIPT | base64 -d | /bin/sh -e\",\n\t\t}\n\t\tif p.Environment == nil {\n\t\t\tp.Environment = map[string]string{}\n\t\t}\n\t\tp.Environment[\"HOME\"] = \"/root\"\n\t\tp.Environment[\"SHELL\"] = \"/bin/sh\"\n\t\tp.Environment[\"DRONE_SCRIPT\"] = toScript(\n\t\t\tp.Commands,\n\t\t)\n\t}\n\treturn nil\n}"} {"input": "package messages\n\nconst (\n\tPullAllMessageSignature = 0x3F\n)\n\n\ntype PullAllMessage struct{}\n\n\nfunc NewPullAllMessage() PullAllMessage {\n\treturn PullAllMessage{}\n}\n\n\n\n\n\nfunc (i PullAllMessage) AllFields() []interface{} {\n\treturn []interface{}{}\n}\n\nfunc (i PullAllMessage) Signature() int ", "output": "{\n\treturn PullAllMessageSignature\n}"} {"input": "package externalversions\n\nimport (\n\t\"fmt\"\n\n\tv1 \"github.com/openshift/api/network/v1\"\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tcache \"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}\n\n\nfunc (f *genericInformer) Lister() cache.GenericLister {\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}\n\n\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) ", "output": "{\n\tswitch resource {\n\tcase v1.SchemeGroupVersion.WithResource(\"clusternetworks\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Network().V1().ClusterNetworks().Informer()}, nil\n\tcase v1.SchemeGroupVersion.WithResource(\"egressnetworkpolicies\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Network().V1().EgressNetworkPolicies().Informer()}, nil\n\tcase v1.SchemeGroupVersion.WithResource(\"hostsubnets\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Network().V1().HostSubnets().Informer()}, nil\n\tcase v1.SchemeGroupVersion.WithResource(\"netnamespaces\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Network().V1().NetNamespaces().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}"} {"input": "package http\n\nimport (\n\t\"go-common/app/admin/main/activity/model\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\nfunc listInfosAll(c *bm.Context) {\n\targ := new(model.ListSub)\n\tif err := c.Bind(arg); err != nil {\n\t\treturn\n\t}\n\tc.JSON(actSrv.SubjectList(c, arg))\n}\n\nfunc videoList(c *bm.Context) {\n\tc.JSON(actSrv.VideoList(c))\n}\n\nfunc addActSubject(c *bm.Context) {\n\targ := new(model.AddList)\n\tif err := c.Bind(arg); err != nil {\n\t\treturn\n\t}\n\tc.JSON(actSrv.AddActSubject(c, arg))\n}\n\nfunc updateInfoAll(c *bm.Context) {\n\ttype upStr struct {\n\t\tmodel.AddList\n\t\tSid int64 `form:\"sid\" validate:\"min=1\"`\n\t}\n\targ := new(upStr)\n\tif err := c.Bind(arg); err != nil {\n\t\treturn\n\t}\n\tc.JSON(actSrv.UpActSubject(c, &arg.AddList, arg.Sid))\n}\n\nfunc subPro(c *bm.Context) {\n\ttype subStr struct {\n\t\tSid int64 `form:\"sid\" validate:\"min=1\"`\n\t}\n\targ := new(subStr)\n\tif err := c.Bind(arg); err != nil {\n\t\treturn\n\t}\n\tc.JSON(actSrv.SubProtocol(c, arg.Sid))\n}\n\nfunc timeConf(c *bm.Context) {\n\ttype subStr struct {\n\t\tSid int64 `form:\"sid\" validate:\"required\"`\n\t}\n\targ := new(subStr)\n\tif err := c.Bind(arg); err != nil {\n\t\treturn\n\t}\n\tc.JSON(actSrv.TimeConf(c, arg.Sid))\n}\n\n\n\nfunc article(c *bm.Context) ", "output": "{\n\ttype subStr struct {\n\t\tAids []int64 `form:\"aids,split\" validate:\"min=1,required\"`\n\t}\n\targ := new(subStr)\n\tif err := c.Bind(arg); err != nil {\n\t\treturn\n\t}\n\tc.JSON(actSrv.GetArticleMetas(c, arg.Aids))\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"github.com/hyperhq/client-go/tools/cache\"\n)\n\n\ntype ServiceLister interface {\n\tList(selector labels.Selector) (ret []*v1.Service, err error)\n\tServices(namespace string) ServiceNamespaceLister\n\tServiceListerExpansion\n}\n\n\ntype serviceLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewServiceLister(indexer cache.Indexer) ServiceLister {\n\treturn &serviceLister{indexer: indexer}\n}\n\n\nfunc (s *serviceLister) List(selector labels.Selector) (ret []*v1.Service, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Service))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *serviceLister) Services(namespace string) ServiceNamespaceLister {\n\treturn serviceNamespaceLister{indexer: s.indexer, namespace: namespace}\n}\n\n\ntype ServiceNamespaceLister interface {\n\tList(selector labels.Selector) (ret []*v1.Service, err error)\n\tGet(name string) (*v1.Service, error)\n\tServiceNamespaceListerExpansion\n}\n\n\n\ntype serviceNamespaceLister struct {\n\tindexer cache.Indexer\n\tnamespace string\n}\n\n\nfunc (s serviceNamespaceLister) List(selector labels.Selector) (ret []*v1.Service, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Service))\n\t})\n\treturn ret, err\n}\n\n\n\n\nfunc (s serviceNamespaceLister) Get(name string) (*v1.Service, error) ", "output": "{\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"service\"), name)\n\t}\n\treturn obj.(*v1.Service), nil\n}"} {"input": "package handler\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"net/http\"\n\t\"text/template\"\n\t\"time\"\n)\n\n\ntype AppHandler func(http.ResponseWriter, *http.Request) (int, error)\n\n\ntype AppConfig struct {\n\tServerTime int64 `json:\"serverTime\"`\n}\n\nconst (\n\tConfigTemplateName string = \"appConfig\"\n\tConfigTemplate string = \"var appConfig_DO_NOT_USE_DIRECTLY = {{.}}\"\n)\n\n\n\n\nfunc getAppConfigJSON() string {\n\tlog.Printf(\"Getting application global configuration\")\n\n\tconfig := &AppConfig{\n\t\tServerTime: time.Now().UTC().UnixNano() / 1e6,\n\t}\n\n\tjson, _ := json.Marshal(config)\n\tlog.Printf(\"Application configuration %s\", json)\n\treturn string(json)\n}\n\nfunc ConfigHandler(w http.ResponseWriter, r *http.Request) (int, error) {\n\ttemplate, err := template.New(ConfigTemplateName).Parse(ConfigTemplate)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn http.StatusInternalServerError, err\n\t}\n\treturn http.StatusOK, template.Execute(w, getAppConfigJSON())\n}\n\nfunc (fn AppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tif _, err := fn(w, r); err != nil {\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError),\n\t\t\thttp.StatusInternalServerError)\n\t}\n}"} {"input": "package etchosts\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestBuildHostnameDomainname(t *testing.T) {\n\tfile, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.Remove(file.Name())\n\n\terr = Build(file.Name(), \"10.11.12.13\", \"testhostname\", \"testdomainname\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcontent, err := ioutil.ReadFile(file.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif expected := \"10.11.12.13\\ttesthostname.testdomainname testhostname\\n\"; !bytes.Contains(content, []byte(expected)) {\n\t\tt.Fatalf(\"Expected to find '%s' got '%s'\", expected, content)\n\t}\n}\n\nfunc TestBuildHostname(t *testing.T) {\n\tfile, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.Remove(file.Name())\n\n\terr = Build(file.Name(), \"10.11.12.13\", \"testhostname\", \"\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcontent, err := ioutil.ReadFile(file.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif expected := \"10.11.12.13\\ttesthostname\\n\"; !bytes.Contains(content, []byte(expected)) {\n\t\tt.Fatalf(\"Expected to find '%s' got '%s'\", expected, content)\n\t}\n}\n\n\n\nfunc TestBuildNoIP(t *testing.T) ", "output": "{\n\tfile, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.Remove(file.Name())\n\n\terr = Build(file.Name(), \"\", \"testhostname\", \"\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcontent, err := ioutil.ReadFile(file.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif expected := \"\"; !bytes.Contains(content, []byte(expected)) {\n\t\tt.Fatalf(\"Expected to find '%s' got '%s'\", expected, content)\n\t}\n}"} {"input": "package chipmunk\n\nimport (\n\t\"github.com/Dethrail/chipmunk/transform\"\n\t\"github.com/Dethrail/chipmunk/vect\"\n\t\"math\"\n)\n\nconst (\n\tRadianConst = math.Pi / 180\n\tDegreeConst = 180 / math.Pi\n)\n\ntype Group int\ntype Layer int\n\ntype Shape struct {\n\tDefaultHash\n\tShapeClass\n\n\tBody *Body\n\n\tBB AABB\n\n\tIsSensor bool\n\n\te vect.Float\n\tu vect.Float\n\tSurface_v vect.Vect\n\n\tUserData interface{}\n\n\tGroup Group\n\tLayer Layer\n\n\tspace *Space\n\n\tvelocityIndexed bool\n}\n\nfunc newShape() *Shape {\n\treturn &Shape{velocityIndexed: true, e: 0.5, u: 0.5, Layer: -1}\n\n}\n\nfunc (shape *Shape) Velocity() (vect.Vect, bool) {\n\treturn shape.Body.v, shape.velocityIndexed\n}\n\nfunc (shape *Shape) SetFriction(friction vect.Float) {\n\tshape.u = friction\n}\n\nfunc (shape *Shape) SetElasticity(e vect.Float) {\n\tshape.e = e\n}\n\n\n\nfunc (shape *Shape) AABB() AABB {\n\treturn shape.BB\n}\n\nfunc (shape *Shape) Clone() *Shape {\n\tclone := *shape\n\tcc := &clone\n\tcc.space = nil\n\tcc.DefaultHash.Reset()\n\tcc.Body = nil\n\tcc.ShapeClass = cc.ShapeClass.Clone(cc)\n\treturn cc\n}\n\nfunc (shape *Shape) Update() {\n\tshape.BB = shape.ShapeClass.update(transform.NewTransform(shape.Body.p, shape.Body.a))\n}\n\nfunc (shape *Shape) Shape() *Shape ", "output": "{\n\treturn shape\n}"} {"input": "package secret\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/mailgun/vulcand/Godeps/_workspace/src/gopkg.in/check.v1\"\n)\n\n\n\ntype SecretSuite struct {\n}\n\nvar _ = Suite(&SecretSuite{})\n\nfunc (s *SecretSuite) TestEncryptDecryptCylce(c *C) {\n\tkeyS, err := NewKeyString()\n\tc.Assert(err, IsNil)\n\n\tkey, err := KeyFromString(keyS)\n\tc.Assert(err, IsNil)\n\n\tb, err := NewBox(key)\n\tc.Assert(err, IsNil)\n\n\tmessage := []byte(\"hello, box!\")\n\tsealed, err := b.Seal(message)\n\tc.Assert(err, IsNil)\n\n\tout, err := b.Open(sealed)\n\tc.Assert(err, IsNil)\n\tc.Assert(out, DeepEquals, message)\n}\n\nfunc (s *SecretSuite) TestEncryptDecryptJSON(c *C) {\n\tkeyS, err := NewKeyString()\n\tc.Assert(err, IsNil)\n\n\tkey, err := KeyFromString(keyS)\n\tc.Assert(err, IsNil)\n\n\tb, err := NewBox(key)\n\tc.Assert(err, IsNil)\n\n\tmessage := []byte(\"hello, box!\")\n\tsealed, err := b.Seal(message)\n\tc.Assert(err, IsNil)\n\n\tdata, err := SealedValueToJSON(sealed)\n\tc.Assert(err, IsNil)\n\tc.Assert(data, NotNil)\n\n\tbytes, err := SealedValueFromJSON(data)\n\tc.Assert(err, IsNil)\n\tc.Assert(bytes, NotNil)\n\n\tout, err := b.Open(sealed)\n\tc.Assert(err, IsNil)\n\tc.Assert(out, DeepEquals, message)\n}\n\nfunc TestSecret(t *testing.T) ", "output": "{ TestingT(t) }"} {"input": "package x509\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n)\n\n\nvar certFiles = []string{\n\t\"/sys/lib/tls/ca.pem\",\n}\n\nfunc (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) {\n\treturn nil, nil\n}\n\n\n\nfunc loadSystemRoots() (*CertPool, error) ", "output": "{\n\troots := NewCertPool()\n\tvar bestErr error\n\tfor _, file := range certFiles {\n\t\tdata, err := ioutil.ReadFile(file)\n\t\tif err == nil {\n\t\t\troots.AppendCertsFromPEM(data)\n\t\t\treturn roots, nil\n\t\t}\n\t\tif bestErr == nil || (os.IsNotExist(bestErr) && !os.IsNotExist(err)) {\n\t\t\tbestErr = err\n\t\t}\n\t}\n\tif bestErr == nil {\n\t\treturn roots, nil\n\t}\n\treturn nil, bestErr\n}"} {"input": "package thrift\n\nimport \"io\"\n\ntype RichTransport struct {\n\tTTransport\n}\n\n\nfunc NewTRichTransport(trans TTransport) *RichTransport {\n\treturn &RichTransport{trans}\n}\n\nfunc (r *RichTransport) ReadByte() (c byte, err error) {\n\treturn readByte(r.TTransport)\n}\n\nfunc (r *RichTransport) WriteByte(c byte) error {\n\treturn writeByte(r.TTransport, c)\n}\n\nfunc (r *RichTransport) WriteString(s string) (n int, err error) {\n\treturn r.Write([]byte(s))\n}\n\nfunc (r *RichTransport) RemainingBytes() (num_bytes uint64) {\n\treturn r.TTransport.RemainingBytes()\n}\n\n\n\nfunc writeByte(w io.Writer, c byte) error {\n\tv := [1]byte{c}\n\t_, err := w.Write(v[0:1])\n\treturn err\n}\n\nfunc readByte(r io.Reader) (c byte, err error) ", "output": "{\n\tv := [1]byte{0}\n\tn, err := r.Read(v[0:1])\n\tif n > 0 && (err == nil || err == io.EOF) {\n\t\treturn v[0], nil\n\t}\n\tif n > 0 && err != nil {\n\t\treturn v[0], err\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn v[0], nil\n}"} {"input": "package httpmux\n\nimport \"net/http\"\n\n\ntype ConfigOption interface {\n\tSet(c *Config)\n}\n\n\ntype ConfigOptionFunc func(c *Config)\n\n\nfunc (f ConfigOptionFunc) Set(c *Config) { f(c) }\n\n\n\n\n\nfunc WithMiddleware(mw ...Middleware) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Middleware = mw })\n}\n\n\nfunc WithMiddlewareFunc(mw ...MiddlewareFunc) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.UseFunc(mw...) })\n}\n\n\nfunc WithRedirectTrailingSlash(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectTrailingSlash = v })\n}\n\n\nfunc WithRedirectFixedPath(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectFixedPath = v })\n}\n\n\nfunc WithHandleMethodNotAllowed(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.HandleMethodNotAllowed = v })\n}\n\n\nfunc WithNotFound(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.NotFound = f })\n}\n\n\nfunc WithMethodNotAllowed(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.MethodNotAllowed = f })\n}\n\n\nfunc WithPanicHandler(f func(http.ResponseWriter, *http.Request, interface{})) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.PanicHandler = f })\n}\n\nfunc WithPrefix(prefix string) ConfigOption ", "output": "{\n\treturn ConfigOptionFunc(func(c *Config) { c.Prefix = prefix })\n}"} {"input": "package srpc\n\nimport (\n\t\"crypto/tls\"\n\n\t\"github.com/Symantec/Dominator/lib/connpool\"\n)\n\n\n\nfunc (cr *ClientResource) getHTTP(tlsConfig *tls.Config,\n\tcancelChannel <-chan struct{}, dialer connpool.Dialer) (*Client, error) {\n\tcr.privateClientResource.tlsConfig = tlsConfig\n\tcr.privateClientResource.dialer = dialer\n\tif err := cr.resource.Get(cancelChannel); err != nil {\n\t\treturn nil, err\n\t}\n\tcr.inUse = true\n\tclientMetricsMutex.Lock()\n\tnumInUseClientConnections++\n\tclientMetricsMutex.Unlock()\n\treturn cr.client, nil\n}\n\nfunc (client *Client) put() {\n\tclient.resource.resource.Put()\n\tif client.resource.inUse {\n\t\tclientMetricsMutex.Lock()\n\t\tnumInUseClientConnections--\n\t\tclientMetricsMutex.Unlock()\n\t\tclient.resource.inUse = false\n\t}\n}\n\nfunc (pcr *privateClientResource) Allocate() error {\n\tcr := pcr.clientResource\n\tclient, err := dialHTTP(cr.network, cr.address, pcr.tlsConfig, pcr.dialer)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcr.client = client\n\tclient.resource = cr\n\treturn nil\n}\n\nfunc (pcr *privateClientResource) Release() error {\n\tcr := pcr.clientResource\n\terr := cr.client.conn.Close()\n\tcr.client = nil\n\treturn err\n}\n\nfunc newClientResource(network, address string) *ClientResource ", "output": "{\n\tclientResource := &ClientResource{\n\t\tnetwork: network,\n\t\taddress: address,\n\t}\n\tclientResource.privateClientResource.clientResource = clientResource\n\trp := connpool.GetResourcePool()\n\tclientResource.resource = rp.Create(&clientResource.privateClientResource)\n\treturn clientResource\n}"} {"input": "package rand\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\n\n\n\n\nfunc unixIsEAGAIN(err error) bool {\n\tif pe, ok := err.(*os.PathError); ok {\n\t\tif errno, ok := pe.Err.(syscall.Errno); ok && errno == syscall.EAGAIN {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc init() ", "output": "{\n\tisEAGAIN = unixIsEAGAIN\n}"} {"input": "package api\n\nimport (\n\t\"github.com/ying32/govcl/vcl/api/memorydll\"\n\t\"github.com/ying32/govcl/vcl/win\"\n)\n\nfunc loadUILib() *memorydll.LazyDLL {\n\tdllBytes, ok := win.ResourceToBytes(win.GetSelfModuleHandle(), \"GOVCLLIB\", win.RT_RCDATA)\n\tif !ok {\n\t\tpanic(\"\\\"GOVCLLIB\\\" resource does not exist.\")\n\t\treturn nil\n\t}\n\tlib := memorydll.NewMemoryDLL(dllBytes)\n\tif lib.Load() != nil {\n\t\tpanic(\"Unable to load dll, unknown reason.\")\n\t\treturn nil\n\t}\n\tif getLibType(lib) != 1 {\n\t\tpanic(\"The VCL library is no longer supported. If necessary, please use the last code that supports VCL version: https:github.com/ying32/govcl/tree/last-vcl-support.\")\n\t}\n\treturn lib\n}\n\nfunc getLibType(lib *memorydll.LazyDLL) int32 {\n\tproc := lib.NewProc(\"DGetLibType\")\n\tr, _, _ := proc.Call()\n\treturn int32(r)\n}\n\n\nfunc GetLibVcl() *memorydll.LazyDLL {\n\treturn libvcl\n}\n\n\nfunc FeeMemoryDLL() {\n\tif libvcl != nil {\n\t\tlibvcl.Close()\n\t\tlibvcl = nil\n\t}\n}\n\n\n\nfunc closeLib() ", "output": "{\n\tFeeMemoryDLL()\n}"} {"input": "package glacier\n\nimport (\n\t\"encoding/hex\"\n\t\"reflect\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/awsutil\"\n)\n\nvar (\n\tdefaultAccountID = \"-\"\n)\n\n\n\nfunc copyParams(r *aws.Request) {\n\tr.Params = awsutil.CopyOf(r.Params)\n}\n\nfunc addAccountID(r *aws.Request) {\n\tif !r.ParamsFilled() {\n\t\treturn\n\t}\n\n\tv := reflect.Indirect(reflect.ValueOf(r.Params))\n\tif f := v.FieldByName(\"AccountID\"); f.IsNil() {\n\t\tf.Set(reflect.ValueOf(&defaultAccountID))\n\t}\n}\n\nfunc addChecksum(r *aws.Request) {\n\tif r.Body == nil {\n\t\treturn\n\t}\n\n\th := ComputeHashes(r.Body)\n\n\tif r.HTTPRequest.Header.Get(\"X-Amz-Content-Sha256\") == \"\" {\n\t\thstr := hex.EncodeToString(h.LinearHash)\n\t\tr.HTTPRequest.Header.Set(\"X-Amz-Content-Sha256\", hstr)\n\t}\n\tif r.HTTPRequest.Header.Get(\"X-Amz-Sha256-Tree-Hash\") == \"\" {\n\t\thstr := hex.EncodeToString(h.TreeHash)\n\t\tr.HTTPRequest.Header.Set(\"X-Amz-Sha256-Tree-Hash\", hstr)\n\t}\n}\n\nfunc addAPIVersion(r *aws.Request) {\n\tr.HTTPRequest.Header.Set(\"X-Amz-Glacier-Version\", r.Service.APIVersion)\n}\n\nfunc init() ", "output": "{\n\tinitRequest = func(r *aws.Request) {\n\t\tr.Handlers.Validate.PushFront(addAccountID)\n\t\tr.Handlers.Validate.PushFront(copyParams) \n\t\tr.Handlers.Build.PushBack(addChecksum)\n\t\tr.Handlers.Build.PushBack(addAPIVersion)\n\t}\n}"} {"input": "package app\n\nimport (\n\tflags \"github.com/jessevdk/go-flags\"\n)\n\n\ntype Args struct {\n\tConfigFile string `short:\"c\" long:\"config\" description:\"Config File\" default:\"/etc/ansible-service-broker/config.yaml\"`\n\tVersion bool `short:\"v\" long:\"version\" description:\"Print version information\"`\n}\n\n\n\n\nfunc CreateArgs() (Args, error) ", "output": "{\n\targs := Args{}\n\n\t_, err := flags.Parse(&args)\n\tif err != nil {\n\t\treturn args, err\n\t}\n\treturn args, nil\n}"} {"input": "package v2\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\n\n\n\ntype KubernetesServiceResolverSpec struct {\n\tAmbassadorID AmbassadorID `json:\"ambassador_id,omitempty\"`\n}\n\n\n\n\ntype KubernetesServiceResolver struct {\n\tmetav1.TypeMeta `json:\"\"`\n\tmetav1.ObjectMeta `json:\"metadata,omitempty\"`\n\n\tSpec KubernetesServiceResolverSpec `json:\"spec,omitempty\"`\n}\n\n\n\n\ntype KubernetesServiceResolverList struct {\n\tmetav1.TypeMeta `json:\"\"`\n\tmetav1.ListMeta `json:\"metadata,omitempty\"`\n\tItems []KubernetesServiceResolver `json:\"items\"`\n}\n\n\n\n\ntype KubernetesEndpointResolverSpec struct {\n\tAmbassadorID AmbassadorID `json:\"ambassador_id,omitempty\"`\n}\n\n\n\n\ntype KubernetesEndpointResolver struct {\n\tmetav1.TypeMeta `json:\"\"`\n\tmetav1.ObjectMeta `json:\"metadata,omitempty\"`\n\n\tSpec KubernetesEndpointResolverSpec `json:\"spec,omitempty\"`\n}\n\n\n\n\ntype KubernetesEndpointResolverList struct {\n\tmetav1.TypeMeta `json:\"\"`\n\tmetav1.ListMeta `json:\"metadata,omitempty\"`\n\tItems []KubernetesEndpointResolver `json:\"items\"`\n}\n\n\n\n\ntype ConsulResolverSpec struct {\n\tAmbassadorID AmbassadorID `json:\"ambassador_id,omitempty\"`\n\n\tAddress string `json:\"address,omitempty\"`\n\tDatacenter string `json:\"datacenter,omitempty\"`\n}\n\n\n\n\ntype ConsulResolver struct {\n\tmetav1.TypeMeta `json:\"\"`\n\tmetav1.ObjectMeta `json:\"metadata,omitempty\"`\n\n\tSpec ConsulResolverSpec `json:\"spec,omitempty\"`\n}\n\n\n\n\ntype ConsulResolverList struct {\n\tmetav1.TypeMeta `json:\"\"`\n\tmetav1.ListMeta `json:\"metadata,omitempty\"`\n\tItems []ConsulResolver `json:\"items\"`\n}\n\n\n\nfunc init() ", "output": "{\n\tSchemeBuilder.Register(&KubernetesServiceResolver{}, &KubernetesServiceResolverList{})\n\tSchemeBuilder.Register(&KubernetesEndpointResolver{}, &KubernetesEndpointResolverList{})\n\tSchemeBuilder.Register(&ConsulResolver{}, &ConsulResolverList{})\n}"} {"input": "package clean_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestPrep(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Clean Suite\")\n}"} {"input": "package ha\n\nimport (\n\tlog \"github.com/golang/glog\"\n\t\"k8s.io/kubernetes/contrib/mesos/pkg/election\"\n)\n\ntype roleType int\n\nconst (\n\tfollowerRole roleType = iota\n\tmasterRole\n\tretiredRole\n)\n\ntype candidateService struct {\n\tsched *SchedulerProcess\n\tnewDriver DriverFactory\n\trole roleType\n\tvalid ValidationFunc\n}\n\ntype ValidationFunc func(desiredUid, currentUid string)\n\n\n\nfunc (self *candidateService) Validate(desired, current election.Master) {\n\tif self.valid != nil {\n\t\tself.valid(string(desired), string(current))\n\t}\n}\n\nfunc (self *candidateService) Start() {\n\tif self.role == followerRole {\n\t\tlog.Info(\"elected as master\")\n\t\tself.role = masterRole\n\t\tself.sched.Elect(self.newDriver)\n\t}\n}\n\nfunc (self *candidateService) Stop() {\n\tif self.role == masterRole {\n\t\tlog.Info(\"retiring from master\")\n\t\tself.role = retiredRole\n\t\tclose(self.sched.failover)\n\t\tself.sched.End()\n\t}\n}\n\nfunc NewCandidate(s *SchedulerProcess, f DriverFactory, v ValidationFunc) election.Service ", "output": "{\n\treturn &candidateService{\n\t\tsched: s,\n\t\tnewDriver: f,\n\t\trole: followerRole,\n\t\tvalid: v,\n\t}\n}"} {"input": "package fields\n\nimport (\n\t\"regexp\"\n\t\"time\"\n)\n\nfunc UseDefaultKeyIfCustomKeyIsEmpty(defaultKey, customKey string) string {\n\tif \"\" != customKey {\n\t\treturn customKey\n\t}\n\treturn defaultKey\n}\n\nfunc ExecFuncIfErrIsNotNil(err error, fn func()) (b bool) {\n\tif nil != err {\n\t\tfn()\n\t\tb = true\n\t}\n\treturn\n}\n\nfunc getMessageFromError(err error) string {\n\tif nil == err {\n\t\treturn \"\"\n\t}\n\treturn err.Error()\n}\n\nfunc getPatternFromRegExp(re *regexp.Regexp) string {\n\tif nil == re {\n\t\treturn \"\"\n\t}\n\treturn re.String()\n}\n\nfunc execFnIfNotNil(fn func()) {\n\tif nil != fn {\n\t\tfn()\n\t}\n}\n\nfunc addSuffix(name string, suffix *string) string {\n\tif nil != suffix {\n\t\treturn name + \"-\" + *suffix\n\t}\n\treturn name\n}\n\n\n\n\nfunc useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) *time.Location {\n\tloc, _ := _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc, locationByString)\n\treturn loc\n}\n\nfunc _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) (*time.Location, int) ", "output": "{\n\tif nil == locationByString || \"\" == *locationByString {\n\t\treturn defaultLoc, 1\n\t}\n\n\tif loc, err := time.LoadLocation(*locationByString); nil == err {\n\t\treturn loc, 2\n\t}\n\n\treturn defaultLoc, 0\n}"} {"input": "package roles\n\nimport (\n\t\"testing\"\n\n\t\"github.com/rackspace/gophercloud/pagination\"\n\tth \"github.com/rackspace/gophercloud/testhelper\"\n\t\"github.com/rackspace/gophercloud/testhelper/client\"\n)\n\nfunc TestRole(t *testing.T) {\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\n\tMockListRoleResponse(t)\n\n\tcount := 0\n\n\terr := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) {\n\t\tcount++\n\t\tactual, err := ExtractRoles(page)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to extract users: %v\", err)\n\t\t\treturn false, err\n\t\t}\n\n\t\texpected := []Role{\n\t\t\tRole{\n\t\t\t\tID: \"123\",\n\t\t\t\tName: \"compute:admin\",\n\t\t\t\tDescription: \"Nova Administrator\",\n\t\t\t},\n\t\t}\n\n\t\tth.CheckDeepEquals(t, expected, actual)\n\n\t\treturn true, nil\n\t})\n\n\tth.AssertNoErr(t, err)\n\tth.AssertEquals(t, 1, count)\n}\n\nfunc TestAddUserRole(t *testing.T) {\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\n\tMockAddUserRoleResponse(t)\n\n\terr := AddUserRole(client.ServiceClient(), \"{tenant_id}\", \"{user_id}\", \"{role_id}\").ExtractErr()\n\n\tth.AssertNoErr(t, err)\n}\n\n\n\nfunc TestDeleteUserRole(t *testing.T) ", "output": "{\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\n\tMockDeleteUserRoleResponse(t)\n\n\terr := DeleteUserRole(client.ServiceClient(), \"{tenant_id}\", \"{user_id}\", \"{role_id}\").ExtractErr()\n\n\tth.AssertNoErr(t, err)\n}"} {"input": "package hashing_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/vlad-doru/experimento/backend/utils/hashing\"\n\t\"github.com/vlad-doru/experimento/backend/utils/test\"\n)\n\nfunc TestHashFloat(t *testing.T) {\n\tseed := hashing.Hash(\"experimento\")\n\ttest.SetSeed(1) \n\tfor i := 0; i < 100000; i++ {\n\t\tid := test.RandString(6, 10)\n\t\tf := hashing.HashFloat(id, seed)\n\t\tassert.True(t, (f >= 0) && (f < 1),\n\t\t\t\"Invariant violation of the hash function for id %s: %v\", id, f)\n\t}\n}\n\nfunc BenchmarkHash(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\thashing.Hash(\"experimento\")\n\t}\n}\n\n\n\nfunc BenchmarkHashFloat(b *testing.B) ", "output": "{\n\tseed := hashing.Hash(\"experimento\")\n\tfor i := 0; i < b.N; i++ {\n\t\thashing.HashFloat(\"hashing_id\", seed)\n\t}\n}"} {"input": "package bigquery\n\nimport (\n\t\"fmt\"\n\t\"github.com/viant/endly\"\n\t\"github.com/viant/endly/system/cloud/gcp\"\n\t\"google.golang.org/api/bigquery/v2\"\n)\n\nvar clientKey = (*CtxClient)(nil)\n\n\ntype CtxClient struct {\n\t*gcp.AbstractClient\n\tservice *bigquery.Service\n}\n\nfunc (s *CtxClient) SetService(service interface{}) error {\n\tvar ok bool\n\ts.service, ok = service.(*bigquery.Service)\n\tif !ok {\n\t\treturn fmt.Errorf(\"unable to set service: %T\", service)\n\t}\n\treturn nil\n}\n\nfunc (s *CtxClient) Service() interface{} {\n\treturn s.service\n}\n\n\n\nfunc getClient(context *endly.Context) (gcp.CtxClient, error) {\n\treturn GetClient(context)\n}\n\nfunc GetClient(context *endly.Context) (*CtxClient, error) {\n\tclient := &CtxClient{\n\t\tAbstractClient: &gcp.AbstractClient{},\n\t}\n\terr := gcp.GetClient(context, bigquery.New, clientKey, &client, bigquery.CloudPlatformScope, bigquery.BigqueryScope, bigquery.BigqueryInsertdataScope)\n\treturn client, err\n}\n\nfunc InitRequest(context *endly.Context, rawRequest map[string]interface{}) error ", "output": "{\n\tconfig, err := gcp.InitCredentials(context, rawRequest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient, err := getClient(context)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgcp.UpdateActionRequest(rawRequest, config, client)\n\treturn nil\n}"} {"input": "package nameref\n\nimport (\n\t\"fmt\"\n\n\t\"sigs.k8s.io/kustomize/kyaml/yaml\"\n)\n\ntype setFn func(*yaml.RNode) error\n\ntype seqFilter struct {\n\tsetScalarFn setFn\n\tsetMappingFn setFn\n}\n\n\n\n\nfunc applyFilterToSeq(filter yaml.Filter, node *yaml.RNode) error {\n\tif node.YNode().Kind != yaml.SequenceNode {\n\t\treturn fmt.Errorf(\"expect a sequence node but got %v\", node.YNode().Kind)\n\t}\n\n\tfor _, elem := range node.Content() {\n\t\trnode := yaml.NewRNode(elem)\n\t\terr := rnode.PipeE(filter)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (sf seqFilter) Filter(node *yaml.RNode) (*yaml.RNode, error) ", "output": "{\n\tif yaml.IsMissingOrNull(node) {\n\t\treturn node, nil\n\t}\n\tswitch node.YNode().Kind {\n\tcase yaml.ScalarNode:\n\t\terr := sf.setScalarFn(node)\n\t\treturn node, err\n\tcase yaml.MappingNode:\n\t\terr := sf.setMappingFn(node)\n\t\treturn node, err\n\tdefault:\n\t\treturn node, fmt.Errorf(\n\t\t\t\"%#v is expected to be either a string or a map of string\", node)\n\t}\n}"} {"input": "package sa\n\nimport (\n\t\"fmt\"\n\n\t\"gopkg.in/go-gorp/gorp.v2\"\n)\n\n\n\ntype RollbackError struct {\n\tErr error\n\tRollbackErr error\n}\n\n\nfunc (re *RollbackError) Error() string {\n\tif re.RollbackErr == nil {\n\t\treturn re.Err.Error()\n\t}\n\treturn fmt.Sprintf(\"%s (also, while rolling back: %s)\", re.Err, re.RollbackErr)\n}\n\n\n\n\n\n\nfunc Rollback(tx *gorp.Transaction, err error) error ", "output": "{\n\tif txErr := tx.Rollback(); txErr != nil {\n\t\treturn &RollbackError{\n\t\t\tErr: err,\n\t\t\tRollbackErr: txErr,\n\t\t}\n\t}\n\treturn err\n}"} {"input": "package config\n\n\ntype MailerCfg struct {\n\tMailerServer string \n\tMailerAuthUser string \n\tMailerAuthPass string \n\tMailerFromAddr string \n}\n\n\n\n\nfunc (mailcfg *MailerCfg) loadFromJsonCfg(jsnMailerCfg *MailerJsonCfg) (err error) ", "output": "{\n\tif jsnMailerCfg == nil {\n\t\treturn nil\n\t}\n\tif jsnMailerCfg.Server != nil {\n\t\tmailcfg.MailerServer = *jsnMailerCfg.Server\n\t}\n\tif jsnMailerCfg.Auth_user != nil {\n\t\tmailcfg.MailerAuthUser = *jsnMailerCfg.Auth_user\n\t}\n\tif jsnMailerCfg.Auth_password != nil {\n\t\tmailcfg.MailerAuthPass = *jsnMailerCfg.Auth_password\n\t}\n\tif jsnMailerCfg.From_address != nil {\n\t\tmailcfg.MailerFromAddr = *jsnMailerCfg.From_address\n\t}\n\n\treturn nil\n}"} {"input": "package api\n\nimport (\n\t\"github.com/globocom/tsuru/fs\"\n\t\"github.com/globocom/tsuru/fs/testing\"\n\t. \"launchpad.net/gocheck\"\n)\n\n\n\nfunc (s *S) TestFileSystem(c *C) ", "output": "{\n\tfsystem = &testing.RecordingFs{}\n\tc.Assert(filesystem(), DeepEquals, fsystem)\n\tfsystem = nil\n\tc.Assert(filesystem(), DeepEquals, fs.OsFs{})\n\tfsystem = s.rfs\n}"} {"input": "package git\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/Originate/git-town/src/command\"\n\t\"github.com/Originate/git-town/src/util\"\n)\n\n\n\nfunc EnsureDoesNotHaveConflicts() {\n\tutil.Ensure(!HasConflicts(), \"You must resolve the conflicts before continuing\")\n}\n\n\n\nfunc EnsureDoesNotHaveOpenChanges(message string) {\n\tutil.Ensure(!HasOpenChanges(), \"You have uncommitted changes. \"+message)\n}\n\n\nvar rootDirectory string\n\n\n\nfunc GetRootDirectory() string {\n\tif rootDirectory == \"\" {\n\t\trootDirectory = command.MustRun(\"git\", \"rev-parse\", \"--show-toplevel\").OutputSanitized()\n\t}\n\treturn rootDirectory\n}\n\n\nfunc HasConflicts() bool {\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"Unmerged paths\")\n}\n\n\nfunc HasOpenChanges() bool {\n\treturn command.MustRun(\"git\", \"status\", \"--porcelain\").OutputSanitized() != \"\"\n}\n\n\n\nfunc HasShippableChanges(branchName string) bool {\n\treturn command.MustRun(\"git\", \"diff\", Config().GetMainBranch()+\"..\"+branchName).OutputSanitized() != \"\"\n}\n\n\n\n\n\n\n\nfunc IsRebaseInProgress() bool {\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"rebase in progress\")\n}\n\nfunc IsMergeInProgress() bool ", "output": "{\n\t_, err := os.Stat(fmt.Sprintf(\"%s/.git/MERGE_HEAD\", GetRootDirectory()))\n\treturn err == nil\n}"} {"input": "package tools\n\nimport (\n\t\"os\"\n\t\"runtime\"\n)\n\n\n\nvar (\n\tDirPerm = getDirPerm()\n)\n\nconst (\n\tToolsFile = toolsFile\n)\n\nfunc getDirPerm() os.FileMode ", "output": "{\n\tif runtime.GOOS == \"windows\" {\n\t\treturn os.FileMode(0777)\n\t}\n\treturn os.FileMode(dirPerm)\n}"} {"input": "package samples\n\nimport (\n\t\"github.com/denkhaus/bitshares/gen/data\"\n\t\"github.com/denkhaus/bitshares/types\"\n)\n\nvar (\n\tsampleDataAssetCreateOperation = make(map[int]string)\n)\n\n\n\nfunc init() ", "output": "{\n\tdata.OpSampleMap[types.OperationTypeAssetCreate] =\n\t\tsampleDataAssetCreateOperation\n}"} {"input": "package rfc3164\n\nimport (\n\t\"time\"\n)\n\n\ntype YearOperator interface {\n\tApply() int\n}\n\n\ntype YearOperation struct {\n\tOperator YearOperator\n}\n\n\nfunc (y YearOperation) Operate() int {\n\treturn y.Operator.Apply()\n}\n\n\ntype CurrentYear struct{}\n\n\n\n\n\ntype Year struct {\n\tYYYY int\n}\n\n\nfunc (y Year) Apply() int {\n\treturn y.YYYY\n}\n\nfunc (CurrentYear) Apply() int ", "output": "{\n\treturn time.Now().Year()\n}"} {"input": "package runtime\n\nimport (\n\t\"gopkg.in/v1/yaml\"\n)\n\n\n\n\n\n\n\nfunc (a *Object) UnmarshalJSON(b []byte) error {\n\tif len(b) == 4 && string(b) == \"null\" {\n\t\ta.Object = nil\n\t\treturn nil\n\t}\n\n\tobj, err := Decode(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.Object = obj\n\treturn nil\n}\n\n\nfunc (a Object) MarshalJSON() ([]byte, error) {\n\tif a.Object == nil {\n\t\treturn []byte(\"null\"), nil\n\t}\n\n\treturn Encode(a.Object)\n}\n\n\n\n\n\nfunc (a Object) GetYAML() (tag string, value interface{}) {\n\tif a.Object == nil {\n\t\tvalue = \"null\"\n\t\treturn\n\t}\n\tv, err := Encode(a.Object)\n\tif err != nil {\n\t\tpanic(\"impossible to encode API object!\")\n\t}\n\treturn tag, v\n}\n\nfunc (a *Object) SetYAML(tag string, value interface{}) bool ", "output": "{\n\tif value == nil {\n\t\ta.Object = nil\n\t\treturn true\n\t}\n\tb, err := yaml.Marshal(value)\n\tif err != nil {\n\t\tpanic(\"yaml can't reverse its own object\")\n\t}\n\tobj, err := Decode(b)\n\tif err != nil {\n\t\treturn false\n\t}\n\ta.Object = obj\n\treturn true\n}"} {"input": "package archive\n\nimport (\n\t\"github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar\"\n)\n\n\n\nfunc setHeaderForSpecialDevice(hdr *tar.Header, ta *tarAppender, name string, stat interface{}) (nlink uint32, inode uint64, err error) ", "output": "{\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/golang/glog\"\n)\n\n\n\nvar heapster_url string\n\n\n\n\n\nfunc indexHandler(c *gin.Context) {\n\tvars := gin.H{}\n\tc.HTML(200, \"index.html\", vars)\n}\n\n\nfunc apiHandler(c *gin.Context) {\n\turi := c.Request.RequestURI\n\tmetric_url := heapster_url + uri\n\tresp, err := http.Get(metric_url)\n\tif err != nil {\n\t\tglog.Fatalf(\"unable to GET %s\", metric_url)\n\t}\n\tif resp.StatusCode != 200 {\n\t\tglog.Errorf(\"GET %s responded with status code: %d\", metric_url, resp.StatusCode)\n\t\treturn\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tglog.Errorf(\"unable to read response body from %s\", metric_url)\n\t\treturn\n\t}\n\n\t_, err = c.Writer.Write(body)\n\tif err != nil {\n\t\tglog.Errorf(\"unable to write body to response for %s\", uri)\n\t}\n}\n\nfunc setupHandlers(url string) *gin.Engine ", "output": "{\n\theapster_url = url\n\tr := gin.Default()\n\tr.Static(\"/static\", \"./static\")\n\tr.Static(\"/pages\", \"./pages\")\n\n\tr.LoadHTMLGlob(\"pages/index.html\")\n\n\tr.GET(\"/\", indexHandler)\n r.GET(\"/api/*uri\", apiHandler)\n\treturn r\n}"} {"input": "package system \n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\nfunc IsProcessAlive(pid int) bool {\n\terr := unix.Kill(pid, syscall.Signal(0))\n\tif err == nil || err == unix.EPERM {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\n\n\n\n\nfunc IsProcessZombie(pid int) (bool, error) {\n\tstatPath := fmt.Sprintf(\"/proc/%d/stat\", pid)\n\tdataBytes, err := ioutil.ReadFile(statPath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdata := string(dataBytes)\n\tsdata := strings.SplitN(data, \" \", 4)\n\tif len(sdata) >= 3 && sdata[2] == \"Z\" {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc KillProcess(pid int) ", "output": "{\n\tunix.Kill(pid, unix.SIGKILL)\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com/cross-dev/script-server/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n)\n\ntype ContainElementMatcher struct {\n\tElement interface{}\n}\n\nfunc (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, err error) {\n\tif !isArrayOrSlice(actual) && !isMap(actual) {\n\t\treturn false, fmt.Errorf(\"ContainElement matcher expects an array/slice/map. Got:\\n%s\", format.Object(actual, 1))\n\t}\n\n\telemMatcher, elementIsMatcher := matcher.Element.(omegaMatcher)\n\tif !elementIsMatcher {\n\t\telemMatcher = &EqualMatcher{Expected: matcher.Element}\n\t}\n\n\tvalue := reflect.ValueOf(actual)\n\tvar keys []reflect.Value\n\tif isMap(actual) {\n\t\tkeys = value.MapKeys()\n\t}\n\tvar lastError error\n\tfor i := 0; i < value.Len(); i++ {\n\t\tvar success bool\n\t\tvar err error\n\t\tif isMap(actual) {\n\t\t\tsuccess, err = elemMatcher.Match(value.MapIndex(keys[i]).Interface())\n\t\t} else {\n\t\t\tsuccess, err = elemMatcher.Match(value.Index(i).Interface())\n\t\t}\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\tcontinue\n\t\t}\n\t\tif success {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, lastError\n}\n\n\n\nfunc (matcher *ContainElementMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"not to contain element matching\", matcher.Element)\n}\n\nfunc (matcher *ContainElementMatcher) FailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn format.Message(actual, \"to contain element matching\", matcher.Element)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\ntype exitReason int\n\nconst (\n\texCommandline exitReason = 1 + iota\n\texWatcher\n\texFsevent\n)\n\n\n\nfunc die(reason exitReason, e error) ", "output": "{\n\tvar reasonStr string\n\tswitch reason {\n\tcase exCommandline:\n\t\treasonStr = \"usage\"\n\tcase exWatcher:\n\t\treasonStr = \"watcher\"\n\tcase exFsevent:\n\t\treasonStr = \"event\"\n\t}\n\n\tfmt.Fprintf(os.Stderr, \"%s error: %s\\n\", reasonStr, e.Error())\n\tos.Exit(int(reason))\n}"} {"input": "package discovery\n\nimport (\n\t\"fmt\"\n\t\"github.com/spencergibb/go-nuvem/util\"\n\t\"github.com/spf13/viper\"\n\t\"net\"\n\t\"strconv\"\n)\n\ntype StaticDiscovery struct {\n\tNamespace string\n\tInstances []string\n}\n\nfunc (s *StaticDiscovery) Configure(namespace string) {\n\tif s.Namespace != \"\" {\n\t\tfmt.Errorf(\"%s already inited: %s\", StaticFactoryKey, s.Namespace)\n\t\treturn\n\t}\n\ts.Namespace = namespace\n\tinstances := viper.GetStringSlice(util.GetStaticRegistryKey(s))\n\tfmt.Printf(\"instances %+v\\n\", instances)\n\ts.Instances = instances\n}\n\nfunc (s *StaticDiscovery) GetIntances() []util.Instance {\n\tinstances := make([]util.Instance, len(s.Instances))\n\n\tfor i, config := range s.Instances {\n\t\thost, portStr, err := net.SplitHostPort(config)\n\n\t\tport, err := strconv.Atoi(portStr)\n\n\t\tprint(err) \n\n\t\tinstances[i] = util.Instance{Host: host, Port: port}\n\t}\n\n\treturn instances\n}\n\n\n\nfunc NewStaticDiscovery() Discovery {\n\treturn &StaticDiscovery{}\n}\n\nvar StaticFactoryKey = \"StaticDiscovery\"\n\nfunc init() {\n\tprintln(\"registering static discovery\")\n\tRegister(StaticFactoryKey, NewStaticDiscovery)\n}\n\nfunc (s *StaticDiscovery) GetNamespace() string ", "output": "{\n\treturn s.Namespace\n}"} {"input": "package readers\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n)\n\nfunc init() {\n\tRegister(\"IOStat\", NewIOStat)\n}\n\n\n\ntype IOStat struct {\n\tData map[string]interface{}\n}\n\n\nfunc (ios *IOStat) Run() error {\n\treturn errors.New(\"iostat -x is only available on Linux.\")\n}\n\n\nfunc (ios *IOStat) ToJson() ([]byte, error) {\n\treturn json.Marshal(ios.Data)\n}\n\nfunc NewIOStat() IReader ", "output": "{\n\tios := &IOStat{}\n\tios.Data = make(map[string]interface{})\n\treturn ios\n}"} {"input": "package zip\n\nimport (\n\t\"archive/zip\"\n\t\"io\"\n\t\"os\"\n)\n\n\ntype Reader struct {\n\tzip.Reader\n\tunread []*zip.File\n\trc io.ReadCloser\n}\n\n\n\n\n\n\nfunc (r *Reader) NextFile() (name string, err error) {\n\tif r.unread == nil {\n\t\tr.unread = r.Files()[:]\n\t}\n\n\tif r.rc != nil {\n\t\tr.rc.Close() \n\t}\n\n\tif len(r.unread) == 0 {\n\t\treturn \"\", io.EOF\n\t}\n\n\tf := r.unread[0]\n\tname, r.unread = f.Name, r.unread[1:]\n\tr.rc, err = f.Open()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn name, nil\n}\n\nfunc (r *Reader) Read(p []byte) (n int, err error) {\n\treturn r.rc.Read(p)\n}\n\n\nfunc (r *Reader) Files() []*zip.File {\n\treturn r.File\n}\n\n\ntype Writer struct {\n\tzip.Writer\n\tw io.Writer\n}\n\n\nfunc NewWriter(w io.Writer) *Writer {\n\treturn &Writer{Writer: *zip.NewWriter(w)}\n}\n\n\n\nfunc (w *Writer) NextFile(name string, fi os.FileInfo) error {\n\tif name == \"\" {\n\t\tname = fi.Name()\n\t}\n\thdr, err := zip.FileInfoHeader(fi)\n\tif err != nil {\n\t\treturn err\n\t}\n\thdr.Name = name\n\tw.w, err = w.CreateHeader(hdr)\n\treturn err\n}\n\nfunc (w *Writer) Write(p []byte) (n int, err error) {\n\treturn w.w.Write(p)\n}\n\nfunc NewReader(r io.ReaderAt, size int64) (*Reader, error) ", "output": "{\n\tzr, err := zip.NewReader(r, size)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Reader{Reader: *zr}, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc max(x int, y int) int {\n\tif (x > y) {\n\t\treturn x\n\t} else {\n\t\treturn y\n\t}\n}\n\n\n\nfunc getSequence() func() int {\n\tvar i int = 0;\n\treturn func() int {\n\t\ti++;\n\t\treturn i\n\t}\n}\n\ntype Circle struct {\n\tx, y, radius float64\n}\n\nfunc(circle Circle) area() float64 {\n\treturn math.Pi * circle.radius * circle.radius \n}\n\nfunc main() {\n\tvar a, b int = 2, 3;\n\tfmt.Printf(\"max value is %d\\n\", max(a,b));\n\n\tfmt.Printf(\"a = %d, b = %d\\n\", a, b);\n\tswap(&a, &b);\n\tfmt.Printf(\"a = %d, b = %d\\n\", a, b);\n\n\txxx := swap\n\txxx(&a, &b)\n\tfmt.Printf(\"a = %d, b = %d\\n\", a, b);\n\n\tnumber := getSequence()\n\tfmt.Printf(\"number is %d\\n\", number())\n\tfmt.Printf(\"number is %d\\n\", number())\n\tfmt.Printf(\"number is %d\\n\", number())\n\tfmt.Printf(\"number is %d\\n\", number())\n\tnumber1 := getSequence()\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\n\tcircle := Circle{x:0, y:0, radius:5}\n\tfmt.Printf(\"Circle area: %f\\n\", circle.area())\n\n}\n\nfunc swap(x *int, y *int) ", "output": "{\n\tvar temp int\n\ttemp = *x;\n\t*x = *y\n\t*y = temp\n}"} {"input": "package auth\n\nimport (\n\t\"errors\"\n\t\"sync\"\n)\n\ntype Users struct {\n\tsync.RWMutex\n\n\tList []*User\n\n\tlastID int64\n}\n\nfunc (u *Users) Get(id int64) (*User, error) {\n\tu.RLock()\n\tdefer u.RUnlock()\n\n\tfor _, user := range u.List {\n\t\tif user.ID == id {\n\t\t\treturn user, nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"User not found\")\n}\n\nfunc (u *Users) Create(user *User) {\n\tu.Lock()\n\tdefer u.Unlock()\n\n\tu.lastID++\n\tuser.ID = u.lastID\n\n\tu.List = append(u.List, user)\n}\n\n\n\nfunc (r *Users) Flush() {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\tr.List = []*User{}\n}\n\nfunc (r *Users) Remove(id int64) ", "output": "{\n\tr.Lock()\n\tdefer r.Unlock()\n\n\tfor key, item := range r.List {\n\t\tif item.ID == id {\n\n\t\t\tcopy(r.List[key:], r.List[key+1:])\n\t\t\tr.List[len(r.List)-1] = nil\n\t\t\tr.List = r.List[:len(r.List)-1]\n\n\t\t}\n\t}\n}"} {"input": "package helpers\n\nimport \"testing\"\n\nfunc TestPointerToBool(t *testing.T) {\n\tboolVar := true\n\tret := PointerToBool(boolVar)\n\tif *ret != boolVar {\n\t\tt.Fatalf(\"expected PointerToBool(true) to return *true, instead returned %#v\", ret)\n\t}\n}\n\n\n\nfunc TestIsRegionNormalized(t *testing.T) ", "output": "{\n\tcases := []struct {\n\t\tinput string\n\t\texpectedResult string\n\t}{\n\t\t{\n\t\t\tinput: \"westus\",\n\t\t\texpectedResult: \"westus\",\n\t\t},\n\t\t{\n\t\t\tinput: \"West US\",\n\t\t\texpectedResult: \"westus\",\n\t\t},\n\t\t{\n\t\t\tinput: \"Eastern Africa\",\n\t\t\texpectedResult: \"easternafrica\",\n\t\t},\n\t\t{\n\t\t\tinput: \"\",\n\t\t\texpectedResult: \"\",\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tresult := NormalizeAzureRegion(c.input)\n\t\tif c.expectedResult != result {\n\t\t\tt.Fatalf(\"NormalizeAzureRegion returned unexpected result: expected %s but got %s\", c.expectedResult, result)\n\t\t}\n\t}\n}"} {"input": "package handlers\n\nimport (\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/byuoitav/configuration-database-microservice/structs\"\n\t\"github.com/labstack/echo\"\n)\n\nfunc (handlerGroup *HandlerGroup) GetDeviceRoleDefs(context echo.Context) error {\n\tresponse, err := handlerGroup.Accessors.GetDeviceRoleDefs()\n\tif err != nil {\n\t\treturn context.String(http.StatusBadRequest, err.Error())\n\t}\n\n\treturn context.JSON(http.StatusOK, response)\n}\n\nfunc (handlerGroup *HandlerGroup) AddDeviceRoleDef(context echo.Context) error {\n\tdrdName := context.Param(\"deviceroledefinition\")\n\tvar drd structs.DeviceRoleDef\n\n\terr := context.Bind(&drd)\n\tif err != nil {\n\t\treturn context.JSON(http.StatusBadRequest, err.Error())\n\t}\n\tif drdName != drd.Name {\n\t\treturn context.JSON(http.StatusBadRequest, \"Endpoint parameter and json name must match!\")\n\t}\n\n\tresponse, err := handlerGroup.Accessors.AddDeviceRoleDef(drd)\n\tif err != nil {\n\t\treturn context.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\n\treturn context.JSON(http.StatusOK, response)\n}\n\n\n\nfunc (handlerGroup *HandlerGroup) GetDeviceRoleDefsById(context echo.Context) error ", "output": "{\n\n\tid, err := strconv.Atoi(context.Param(\"id\"))\n\tif err != nil {\n\t\treturn context.JSON(http.StatusBadRequest, err.Error())\n\t}\n\n\tresponse, err := handlerGroup.Accessors.GetDeviceRoleDefByID(id)\n\tif err != nil {\n\t\treturn context.JSON(http.StatusBadRequest, err.Error())\n\t}\n\n\treturn context.JSON(http.StatusOK, response)\n\n}"} {"input": "package building\n\nimport \"fmt\"\n\ntype Single struct {\n\tprefix string\n\toption string\n}\n\n\n\nfunc (s Single) Build() string {\n\treturn fmt.Sprintf(\"%s %s\", s.prefix, s.option)\n}\n\nfunc NewSingleBuilder(prefix, value string) Single {\n\treturn Single{prefix, value}\n}\n\nfunc (s Single) IsPresent() bool ", "output": "{\n\treturn s.option != \"\"\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/jackytck/projecteuler/tools\"\n)\n\nfunc isAbundant(n int) bool {\n\treturn tools.SumDivisors(n) > n\n}\n\nfunc isSumOfTwoAbundant(n int, a []bool) bool {\n\tvar ret bool\n\tfor i := 1; i < n; i++ {\n\t\tif a[i] && a[n-i] {\n\t\t\tret = true\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ret\n}\n\n\n\nfunc main() {\n\tfmt.Println(solve())\n}\n\nfunc solve() int ", "output": "{\n\tvar sum int\n\tab := make([]bool, 28124)\n\tfor i := 12; i <= 28123; i++ {\n\t\tab[i] = isAbundant(i)\n\t}\n\tfor i := 1; i <= 28123; i++ {\n\t\tif !isSumOfTwoAbundant(i, ab) {\n\t\t\tsum += i\n\t\t}\n\t}\n\treturn sum\n}"} {"input": "package gtimer\n\n\nfunc (h *priorityQueueHeap) Len() int {\n\treturn len(h.array)\n}\n\n\n\nfunc (h *priorityQueueHeap) Less(i, j int) bool {\n\treturn h.array[i].priority < h.array[j].priority\n}\n\n\nfunc (h *priorityQueueHeap) Swap(i, j int) {\n\tif len(h.array) == 0 {\n\t\treturn\n\t}\n\th.array[i], h.array[j] = h.array[j], h.array[i]\n}\n\n\n\n\n\nfunc (h *priorityQueueHeap) Pop() interface{} {\n\tlength := len(h.array)\n\tif length == 0 {\n\t\treturn nil\n\t}\n\titem := h.array[length-1]\n\th.array = h.array[0 : length-1]\n\treturn item\n}\n\nfunc (h *priorityQueueHeap) Push(x interface{}) ", "output": "{\n\th.array = append(h.array, x.(priorityQueueItem))\n}"} {"input": "package handlers\n\nimport (\n\t\"github.com/skmetaly/pbblog/framework/session\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\n\n\nfunc AuthenticateRequest(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tsess := session.Instance(r)\n\n\tif sess.Values[\"user_id\"] == nil {\n\t\tquery := url.Values{}\n\t\tquery.Add(\"next\", url.QueryEscape(r.URL.String()))\n\n\t\thttp.Redirect(w, r, \"/admin/login?\"+query.Encode(), http.StatusFound)\n\t}\n}"} {"input": "package jsonbuilder\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n)\n\nfunc MarshalIntArray(inta []int) []byte {\n\tbuffer := new(bytes.Buffer)\n\te := gob.NewEncoder(buffer)\n\terr := e.Encode(inta)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to marshal \", err)\n\t}\n\treturn buffer.Bytes()\n}\n\nfunc UnmarshalIntArray(ba []byte) []int {\n\tbuffer := bytes.NewBuffer(ba)\n\tvar inta = new([]int)\n\td := gob.NewDecoder(buffer)\n\terr := d.Decode(&inta)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to unmarshal \", ba, err)\n\t}\n\treturn *inta\n}\n\nfunc ReadData(r io.Reader, intf interface{}) error {\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(data, &intf)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc WriteData(w io.Writer, intf interface{}) error ", "output": "{\n\tb, err := json.Marshal(intf)\n\tfmt.Println(len(b), string(b))\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\n\ti, err := w.Write(b)\n\tif i != len(b) || err != nil {\n\t\tfmt.Println(\"Nothing to write\", i, err)\n\t}\n\treturn err\n}"} {"input": "package notary\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"testing\"\n\n\t\"github.com/goharbor/harbor/src/common/utils/test\"\n)\n\ntype simpleModifier struct {\n}\n\nfunc (s *simpleModifier) Modify(req *http.Request) error {\n\treq.Header.Set(\"Authorization\", \"token\")\n\treturn nil\n}\n\n\n\nfunc TestRoundTrip(t *testing.T) ", "output": "{\n\tserver := test.NewServer(\n\t\t&test.RequestHandlerMapping{\n\t\t\tMethod: \"GET\",\n\t\t\tPattern: \"/\",\n\t\t\tHandler: test.Handler(nil),\n\t\t})\n\ttransport := NewTransport(&http.Transport{}, &simpleModifier{})\n\tclient := &http.Client{\n\t\tTransport: transport,\n\t}\n\n\treq, err := http.NewRequest(\"GET\", fmt.Sprintf(\"%s/\", server.URL), nil)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create request: %v\", err)\n\t}\n\n\tif _, err := client.Do(req); err != nil {\n\t\tt.Fatalf(\"failed to send request: %s\", err)\n\t}\n\n\theader := req.Header.Get(\"Authorization\")\n\tif header != \"token\" {\n\t\tt.Errorf(\"unexpected header: %s != %s\", header, \"token\")\n\t}\n\n}"} {"input": "package reboot\n\nimport (\n\t\"github.com/juju/juju/api/base/testing\"\n)\n\n\n\n\n\n\nfunc PatchFacadeCall(p testing.Patcher, st *State, f func(request string, params, response interface{}) error) ", "output": "{\n\ttesting.PatchFacadeCall(p, &st.facade, f)\n}"} {"input": "package cat\n\nimport(\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/ProhtMeyhet/libgosimpleton/iotool\"\n\t\"github.com/ProhtMeyhet/libgosimpleton/parallel\"\n\n\t\"github.com/ProhtMeyhet/gonixutils/library/abstract\"\n)\n\n\n\n\nfunc CopyFilesTo(mainOutput abstract.OutputInterface, helper *iotool.FileHelper, paths ...string) (e error) {\n\treturn CopyFilesFilteredTo(mainOutput, helper, nil, paths...)\n}\n\nfunc CopyFilesFilteredTo(mainOutput abstract.OutputInterface, helper *iotool.FileHelper,\n\t\tfilter func(io.Reader) io.Reader, paths ...string) (e error) {\n\toutput := mainOutput\n\tparallel.ReadFilesSequential(helper, paths, func(buffered *iotool.NamedBuffer) {\n\t\tvar filtered io.Reader\n\t\tif output.PrintSubBufferNames() {\n\t\t\toutput = mainOutput.NewSubBuffer(fmt.Sprintf(\"==>%v<==\\n\", buffered.Name()), 0)\n\t\t}\n\n\t\tif filter != nil { filtered = filter(buffered) }\n\t\tif filtered == nil { filtered = buffered }\n\n\t\t_, e = io.Copy(output, filtered)\n\t\tif output.PrintSubBufferNames() { output.Done() }\n\t}).Wait(); return\n}\n\nfunc Cat(input *Input) (exitCode uint8) ", "output": "{\n\toutput := abstract.NewOutput(input.Stdout, input.Stderr)\n\tif input.Verbose { output.TogglePrintSubBufferNames() }\n\thelper := prepareFileHelper(input, output, &exitCode)\n\n\te := CopyFilesTo(output, helper, input.Paths...); if e != nil && exitCode == 0 {\n\t\texitCode = abstract.ERROR_UNHANDLED\n\t}\n\n\toutput.Done(); output.Wait(); return\n}"} {"input": "package gtreap\n\nimport (\n\t\"math/rand\"\n\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\nfunc (w *Writer) BytesSafeAfterClose() bool {\n\treturn false\n}\n\nfunc (w *Writer) Get(k []byte) (v []byte, err error) {\n\tw.s.m.Lock()\n\tt := w.s.t\n\tw.s.m.Unlock()\n\n\titm := t.Get(&Item{k: k})\n\tif itm != nil {\n\t\treturn itm.(*Item).v, nil\n\t}\n\treturn nil, nil\n}\n\nfunc (w *Writer) Iterator(k []byte) store.KVIterator {\n\tw.s.m.Lock()\n\tt := w.s.t\n\tw.s.m.Unlock()\n\n\treturn newIterator(t).restart(&Item{k: k})\n}\n\nfunc (w *Writer) Close() error {\n\tw.s.availableWriters <- true\n\tw.s = nil\n\n\treturn nil\n}\n\nfunc (w *Writer) Set(k, v []byte) (err error) {\n\tw.s.m.Lock()\n\tw.s.t = w.s.t.Upsert(&Item{k: k, v: v}, rand.Int())\n\tw.s.m.Unlock()\n\n\treturn nil\n}\n\nfunc (w *Writer) Delete(k []byte) (err error) {\n\tw.s.m.Lock()\n\tw.s.t = w.s.t.Delete(&Item{k: k})\n\tw.s.m.Unlock()\n\n\treturn nil\n}\n\n\n\nfunc (w *Writer) NewBatch() store.KVBatch ", "output": "{\n\treturn store.NewEmulatedBatch(w, w.s.mo)\n}"} {"input": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"time\"\n)\n\ntype TLSConnection struct {\n\thost string\n\tcertPool *x509.CertPool\n\tconn *tls.Conn\n}\n\nfunc NewTLSConnection(host string) (*TLSConnection, error) {\n\tc := &TLSConnection{}\n\tc.host = host\n\tc.getCerts()\n\terr := c.Connect()\n\treturn c, err\n}\n\nfunc (c *TLSConnection) Connect() (err error) {\n\tc.conn, err = tls.Dial(\"tcp\", c.host, &tls.Config{\n\t\tRootCAs: c.certPool,\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\tc.conn.SetWriteDeadline(time.Time{})\n\treturn\n}\n\nfunc (c *TLSConnection) WriteString(s string) (n int, err error) {\n\treturn io.WriteString(c.conn, s)\n}\n\nfunc (c *TLSConnection) Write(p []byte) (n int, err error) {\n\treturn c.conn.Write(p)\n}\n\nfunc (c *TLSConnection) Close() error {\n\treturn c.conn.Close()\n}\n\n\n\nfunc (c *TLSConnection) getCerts() ", "output": "{\n\tc.certPool = x509.NewCertPool()\n\tcert, err := ioutil.ReadFile(certsPemFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif !c.certPool.AppendCertsFromPEM(cert) {\n\t\tlog.Fatal(\"Failed parsing root certificate\")\n\t}\n}"} {"input": "package install\n\nimport (\n\t\"k8s.io/apimachinery/pkg/apimachinery/announced\"\n\t\"k8s.io/apimachinery/pkg/apimachinery/registered\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/util/sets\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\n\t\"github.com/openshift/origin/pkg/api/legacy\"\n\tsecurityapi \"github.com/openshift/origin/pkg/security/apis/security\"\n\tsecurityapiv1 \"github.com/openshift/origin/pkg/security/apis/security/v1\"\n)\n\n\n\n\nfunc Install(groupFactoryRegistry announced.APIGroupFactoryRegistry, registry *registered.APIRegistrationManager, scheme *runtime.Scheme) {\n\tif err := announced.NewGroupMetaFactory(\n\t\t&announced.GroupMetaFactoryArgs{\n\t\t\tGroupName: securityapi.GroupName,\n\t\t\tVersionPreferenceOrder: []string{securityapiv1.SchemeGroupVersion.Version},\n\t\t\tRootScopedKinds: sets.NewString(\"SecurityContextConstraints\"),\n\t\t\tAddInternalObjectsToScheme: securityapi.AddToScheme,\n\t\t},\n\t\tannounced.VersionToSchemeFunc{\n\t\t\tsecurityapiv1.SchemeGroupVersion.Version: securityapiv1.AddToScheme,\n\t\t},\n\t).Announce(groupFactoryRegistry).RegisterAndEnable(registry, scheme); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc init() ", "output": "{\n\tInstall(legacyscheme.GroupFactoryRegistry, legacyscheme.Registry, legacyscheme.Scheme)\n\tlegacy.InstallLegacySecurity(legacyscheme.Scheme, legacyscheme.Registry)\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\ntype User struct {\n\tName string `json:\"name\"`\n\tID string `json:\"id\"`\n\tIP string `json:\"ip,omitempty\"`\n\tAdmin bool `json:\"admin\"`\n\tBlocked bool `json:\"block,omitempty\"`\n\tVerified bool `json:\"verified,omitempty\"`\n}\n\ntype contextKey string\n\n\n\nfunc MustGetUserInfo(r *http.Request) User {\n\tuser, err := GetUserInfo(r)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn user\n}\n\n\nfunc GetUserInfo(r *http.Request) (user User, err error) {\n\n\tctx := r.Context()\n\tif ctx == nil {\n\t\treturn User{}, errors.New(\"no info about user\")\n\t}\n\tif u, ok := ctx.Value(contextKey(\"user\")).(User); ok {\n\t\treturn u, nil\n\t}\n\n\treturn User{}, errors.New(\"user can't be parsed\")\n}\n\n\n\n\nfunc SetUserInfo(r *http.Request, user User) *http.Request ", "output": "{\n\tctx := r.Context()\n\tctx = context.WithValue(ctx, contextKey(\"user\"), user)\n\treturn r.WithContext(ctx)\n}"} {"input": "package iso20022\n\n\ntype StatisticsByPredefinedTimePeriods2 struct {\n\n\tHighestPriceValue12Months *PriceValue5 `xml:\"HghstPricVal12Mnths,omitempty\"`\n\n\tLowestPriceValue12Months *PriceValue5 `xml:\"LwstPricVal12Mnths,omitempty\"`\n\n\tOneYearPriceChange *PriceValueChange1 `xml:\"OneYrPricChng,omitempty\"`\n\n\tThreeYearPriceChange *PriceValueChange1 `xml:\"ThreeYrPricChng,omitempty\"`\n\n\tFiveYearPriceChange *PriceValueChange1 `xml:\"FiveYrPricChng,omitempty\"`\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddHighestPriceValue12Months() *PriceValue5 {\n\ts.HighestPriceValue12Months = new(PriceValue5)\n\treturn s.HighestPriceValue12Months\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddLowestPriceValue12Months() *PriceValue5 {\n\ts.LowestPriceValue12Months = new(PriceValue5)\n\treturn s.LowestPriceValue12Months\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddOneYearPriceChange() *PriceValueChange1 {\n\ts.OneYearPriceChange = new(PriceValueChange1)\n\treturn s.OneYearPriceChange\n}\n\n\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddFiveYearPriceChange() *PriceValueChange1 {\n\ts.FiveYearPriceChange = new(PriceValueChange1)\n\treturn s.FiveYearPriceChange\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddThreeYearPriceChange() *PriceValueChange1 ", "output": "{\n\ts.ThreeYearPriceChange = new(PriceValueChange1)\n\treturn s.ThreeYearPriceChange\n}"} {"input": "package fate\n\nimport \"testing\"\n\n\n\nfunc StrsEqual(a []string, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc TestWords(t *testing.T) ", "output": "{\n\tvar tests = []struct {\n\t\tstr string\n\t\texpected []string\n\t}{\n\t\t{\"\", []string{}},\n\t\t{\"one\", []string{\"one\"}},\n\t\t{\"this is a test\", []string{\"this\", \"is\", \"a\", \"test\"}},\n\t\t{\" this is a test \", []string{\"this\", \"is\", \"a\", \"test\"}},\n\t}\n\n\tfor _, tt := range tests {\n\t\tvar words []string\n\n\t\titer := newWords(tt.str)\n\t\tfor iter.Next() {\n\t\t\twords = append(words, iter.Word())\n\t\t}\n\n\t\tif !StrsEqual(words, tt.expected) {\n\t\t\tt.Errorf(\"Words(%v) -> %v, expected %v\", tt.str, words, tt.expected)\n\t\t}\n\t}\n}"} {"input": "package gocd\n\nimport \"errors\"\n\n\n\n\nfunc (mp4 MaterialAttributesP4) GenerateGeneric() (ma map[string]interface{}) {\n\tma = make(map[string]interface{})\n\treturn\n}\n\n\nfunc (mp4 MaterialAttributesP4) HasFilter() bool {\n\treturn true\n}\n\n\nfunc (mp4 MaterialAttributesP4) GetFilter() *MaterialFilter {\n\treturn mp4.Filter\n}\n\n\nfunc unmarshallMaterialAttributesP4(mp4 *MaterialAttributesP4, i map[string]interface{}) {\n\tfor key, value := range i {\n\t\tif value == nil {\n\t\t\tcontinue\n\t\t}\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\tmp4.Name = value.(string)\n\t\tcase \"port\":\n\t\t\tmp4.Port = value.(string)\n\t\tcase \"use_tickets\":\n\t\t\tmp4.UseTickets = value.(bool)\n\t\tcase \"view\":\n\t\t\tmp4.View = value.(string)\n\t\tcase \"username\":\n\t\t\tmp4.Username = value.(string)\n\t\tcase \"password\":\n\t\t\tmp4.Password = value.(string)\n\t\tcase \"encrypted_password\":\n\t\t\tmp4.EncryptedPassword = value.(string)\n\t\tcase \"destination\":\n\t\t\tmp4.Destination = value.(string)\n\t\tcase \"filter\":\n\t\t\tmp4.Filter = unmarshallMaterialFilter(value.(map[string]interface{}))\n\t\tcase \"invert_filter\":\n\t\t\tmp4.InvertFilter = value.(bool)\n\t\tcase \"auto_update\":\n\t\t\tmp4.AutoUpdate = value.(bool)\n\t\t}\n\t}\n}\n\nfunc (mp4 MaterialAttributesP4) equal(ma MaterialAttribute) (bool, error) ", "output": "{\n\tvar ok bool\n\tmp42, ok := ma.(MaterialAttributesP4)\n\tif !ok {\n\t\treturn false, errors.New(\"can only compare with same material type\")\n\t}\n\n\tnamesEqual := mp4.Name == mp42.Name\n\tportEqual := mp4.Port == mp42.Port\n\tdestEqual := mp4.Destination == mp42.Destination\n\n\treturn namesEqual && portEqual && destEqual, nil\n}"} {"input": "package postik\n\nvar hash Hasher\n\ntype Hasher func(string) string\n\nfunc init() {\n\n\thash = func(name string) string {\n\n\t\treturn name\n\t}\n}\n\n\n\nfunc ReplaceHasher(hasher Hasher) ", "output": "{\n\n\thash = hasher\n}"} {"input": "package main\n\nimport \"time\"\n\n\n\nfunc maybeSetLinkMtime(destPath string, t time.Time) error ", "output": "{\n\treturn nil\n}"} {"input": "package conformance\n\nfunc stringGet(s string, index int) byte {\n\treturn s[index]\n}\n\nfunc stringLen(s string) int {\n\treturn len(s)\n}\n\n\n\nfunc substring(s string, low, high int) string ", "output": "{\n\tswitch {\n\tcase low >= 0 && high >= 0:\n\t\treturn s[low:high]\n\tcase low >= 0:\n\t\treturn s[low:]\n\tcase high >= 0:\n\t\treturn s[:high]\n\tdefault:\n\t\treturn s\n\t}\n}"} {"input": "package swt\n\nimport \"github.com/timob/javabind\"\n\ntype EventsTraverseEventInterface interface {\n\tEventsKeyEventInterface\n}\n\ntype EventsTraverseEvent struct {\n\tEventsKeyEvent\n}\n\n\nfunc NewEventsTraverseEvent(a WidgetsEventInterface) (*EventsTraverseEvent) {\n\tconv_a := javabind.NewGoToJavaCallable()\n\tif err := conv_a.Convert(a); err != nil {\n\t\tpanic(err)\n\t}\n\n\tobj, err := javabind.GetEnv().NewObject(\"org/eclipse/swt/events/TraverseEvent\", conv_a.Value().Cast(\"org/eclipse/swt/widgets/Event\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tconv_a.CleanUp()\n\tx := &EventsTraverseEvent{}\n\tx.Callable = &javabind.Callable{obj}\n\treturn x\n}\n\n\nfunc (jbobject *EventsTraverseEvent) ToString() string {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"toString\", \"java/lang/String\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tretconv := javabind.NewJavaToGoString()\n\tdst := new(string)\n\tretconv.Dest(dst)\n\tif err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {\n\t\tpanic(err)\n\t}\n\tretconv.CleanUp()\n\treturn *dst\n}\n\nfunc (jbobject *EventsTraverseEvent) Detail() int {\n\tjret, err := jbobject.GetField(javabind.GetEnv(), \"detail\", javabind.Int)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn jret.(int)\n}\n\n\n\nfunc (jbobject *EventsTraverseEvent) SetFieldDetail(val int) ", "output": "{\n\terr := jbobject.SetField(javabind.GetEnv(), \"detail\", val)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n}"} {"input": "package wiringpi\n\n\n\n\n\n\n\n\n\n\n\nimport \"C\"\nimport (\n\t\"sync\"\n\n\t\"github.com/yroffin/jarvis-go-ext/logger\"\n)\n\n\ntype WiringPiDriver struct {\n}\n\nvar instance *WiringPiDriver\nvar once sync.Once\n\n\nfunc GetInstance() *WiringPiDriver {\n\tonce.Do(func() {\n\t\tinstance = new(WiringPiDriver)\n\t\tinstance.init()\n\t})\n\treturn instance\n}\n\n\nfunc (wiringPi *WiringPiDriver) init() int {\n\tvar res = int(C.wiringPiSetupInit())\n\tlogger.Default.Info(\"WiringPiDriver\", logger.Fields{\n\t\t\"Init\": \"on\",\n\t})\n\treturn res\n}\n\n\nfunc PinMode(pin int, value int) {\n\tC.pinMode(C.int(pin), C.int(value))\n}\n\n\nfunc DigitalWrite(pin int, value int) {\n\tC.digitalWrite(C.int(pin), C.int(value))\n}\n\n\n\n\n\nfunc Delay(delay uint) {\n\tC.delay(C.uint(delay))\n}\n\nfunc DelayMicroseconds(delay uint) ", "output": "{\n\tC.delayMicroseconds(C.uint(delay))\n}"} {"input": "package jaeger_test\n\nimport (\n\t\"log\"\n\n\t\"go.opencensus.io/exporter/jaeger\"\n\t\"go.opencensus.io/trace\"\n)\n\n\n\nfunc ExampleNewExporter_agent() {\n\texporter, err := jaeger.NewExporter(jaeger.Options{\n\t\tAgentEndpoint: \"localhost:6831\",\n\t\tProcess: jaeger.Process{\n\t\t\tServiceName: \"trace-demo\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttrace.RegisterExporter(exporter)\n}\n\n\n\n\nfunc ExampleNewExporter_processTags() {\n\texporter, err := jaeger.NewExporter(jaeger.Options{\n\t\tAgentEndpoint: \"localhost:6831\",\n\t\tProcess: jaeger.Process{\n\t\t\tServiceName: \"trace-demo\",\n\t\t\tTags: []jaeger.Tag{\n\t\t\t\tjaeger.StringTag(\"ip\", \"127.0.0.1\"),\n\t\t\t\tjaeger.BoolTag(\"demo\", true),\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttrace.RegisterExporter(exporter)\n}\n\nfunc ExampleNewExporter_collector() ", "output": "{\n\texporter, err := jaeger.NewExporter(jaeger.Options{\n\t\tEndpoint: \"http:localhost:14268\",\n\t\tProcess: jaeger.Process{\n\t\t\tServiceName: \"trace-demo\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttrace.RegisterExporter(exporter)\n}"} {"input": "package byteslice\n\nimport \"fmt\"\n\n\n\nfunc ExampleLToggle() {\n\tdata := []byte{0xAB, 0xCB, 0x44}\n\tsetData := []byte{0x11, 0x11, 0x11}\n\n\tfmt.Printf(\"%x\\n\", LToggle(data, setData))\n}\n\nfunc ExampleLSet() ", "output": "{\n\tdata := []byte{0xAA, 0xCA, 0x55}\n\tsetData := []byte{0x10, 0x12}\n\n\tfmt.Printf(\"%x\\n\", LSet(data, setData))\n}"} {"input": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"time\"\n)\n\ntype TLSConnection struct {\n\thost string\n\tcertPool *x509.CertPool\n\tconn *tls.Conn\n}\n\nfunc NewTLSConnection(host string) (*TLSConnection, error) {\n\tc := &TLSConnection{}\n\tc.host = host\n\tc.getCerts()\n\terr := c.Connect()\n\treturn c, err\n}\n\nfunc (c *TLSConnection) Connect() (err error) {\n\tc.conn, err = tls.Dial(\"tcp\", c.host, &tls.Config{\n\t\tRootCAs: c.certPool,\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\tc.conn.SetWriteDeadline(time.Time{})\n\treturn\n}\n\n\n\nfunc (c *TLSConnection) Write(p []byte) (n int, err error) {\n\treturn c.conn.Write(p)\n}\n\nfunc (c *TLSConnection) Close() error {\n\treturn c.conn.Close()\n}\n\nfunc (c *TLSConnection) getCerts() {\n\tc.certPool = x509.NewCertPool()\n\tcert, err := ioutil.ReadFile(certsPemFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif !c.certPool.AppendCertsFromPEM(cert) {\n\t\tlog.Fatal(\"Failed parsing root certificate\")\n\t}\n}\n\nfunc (c *TLSConnection) WriteString(s string) (n int, err error) ", "output": "{\n\treturn io.WriteString(c.conn, s)\n}"} {"input": "package exporterhelper\n\nimport (\n\t\"context\"\n\n\t\"go.opencensus.io/trace\"\n\n\t\"github.com/census-instrumentation/opencensus-service/data\"\n\t\"github.com/census-instrumentation/opencensus-service/exporter\"\n\t\"github.com/census-instrumentation/opencensus-service/observability\"\n)\n\n\n\ntype PushTraceData func(ctx context.Context, td data.TraceData) (droppedSpans int, err error)\n\ntype traceExporter struct {\n\texporterFormat string\n\tpushTraceData PushTraceData\n}\n\nvar _ (exporter.TraceExporter) = (*traceExporter)(nil)\n\nfunc (te *traceExporter) ConsumeTraceData(ctx context.Context, td data.TraceData) error {\n\texporterCtx := observability.ContextWithExporterName(ctx, te.exporterFormat)\n\t_, err := te.pushTraceData(exporterCtx, td)\n\treturn err\n}\n\nfunc (te *traceExporter) TraceExportFormat() string {\n\treturn te.exporterFormat\n}\n\n\n\n\nfunc NewTraceExporter(exporterFormat string, pushTraceData PushTraceData, options ...ExporterOption) (exporter.TraceExporter, error) {\n\tif exporterFormat == \"\" {\n\t\treturn nil, errEmptyExporterFormat\n\t}\n\n\tif pushTraceData == nil {\n\t\treturn nil, errNilPushTraceData\n\t}\n\n\topts := newExporterOptions(options...)\n\n\tif opts.spanName != \"\" {\n\t\tpushTraceData = pushTraceDataWithSpan(pushTraceData, opts.spanName)\n\t}\n\n\treturn &traceExporter{\n\t\texporterFormat: exporterFormat,\n\t\tpushTraceData: pushTraceData,\n\t}, nil\n}\n\n\n\n\nfunc pushTraceDataWithSpan(next PushTraceData, spanName string) PushTraceData ", "output": "{\n\treturn func(ctx context.Context, td data.TraceData) (int, error) {\n\t\tctx, span := trace.StartSpan(ctx, spanName)\n\t\tdefer span.End()\n\t\tdroppedSpans, err := next(ctx, td)\n\t\tif span.IsRecordingEvents() {\n\t\t\tspan.AddAttributes(\n\t\t\t\ttrace.Int64Attribute(numReceivedSpansAttribute, int64(len(td.Spans))),\n\t\t\t\ttrace.Int64Attribute(numDroppedSpansAttribute, int64(droppedSpans)),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tspan.SetStatus(errToStatus(err))\n\t\t\t}\n\t\t}\n\t\treturn droppedSpans, err\n\t}\n}"} {"input": "package docker\n\nimport (\n\t\"os/exec\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/schema\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\nvar testAccProviders map[string]terraform.ResourceProvider\nvar testAccProvider *schema.Provider\n\nfunc init() {\n\ttestAccProvider = Provider().(*schema.Provider)\n\ttestAccProviders = map[string]terraform.ResourceProvider{\n\t\t\"docker\": testAccProvider,\n\t}\n}\n\nfunc TestProvider(t *testing.T) {\n\tif err := Provider().(*schema.Provider).InternalValidate(); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n}\n\nfunc TestProvider_impl(t *testing.T) {\n\tvar _ terraform.ResourceProvider = Provider()\n}\n\n\n\nfunc testAccPreCheck(t *testing.T) ", "output": "{\n\tcmd := exec.Command(\"docker\", \"version\")\n\tif err := cmd.Run(); err != nil {\n\t\tt.Fatalf(\"Docker must be available: %s\", err)\n\t}\n}"} {"input": "package version\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/globalsign/certlint/certdata\"\n\t\"github.com/globalsign/certlint/checks\"\n\t\"github.com/globalsign/certlint/errors\"\n)\n\nconst checkName = \"Issuer DN Check\"\n\n\n\n\nfunc Check(d *certdata.Data) *errors.Errors {\n\tvar e = errors.New(nil)\n\n\tif d.Issuer != nil && !bytes.Equal(d.Cert.RawIssuer, d.Issuer.RawSubject) {\n\t\te.Err(\"Certificate Issuer Distinguished Name field MUST match the Subject DN of the Issuing CA\")\n\t\treturn e\n\t}\n\n\treturn e\n}\n\nfunc init() ", "output": "{\n\tchecks.RegisterCertificateCheck(checkName, nil, Check)\n}"} {"input": "package steps\n\nimport (\n\t\"time\"\n\n\t\"github.com/intel-hpdd/lemur/uat/harness\"\n)\n\nfunc init() {\n\taddStep(`^I configure the (posix|s3) data mover$`, iConfigureADataMover)\n\taddStep(`^the (posix|s3) data mover should be (running|stopped)$`, theDataMoverShouldBe)\n}\n\n\n\nfunc theDataMoverShouldBe(dmType, state string) error {\n\ttime.Sleep(1 * time.Second)\n\n\tdmStatus := func() error {\n\t\treturn checkProcessState(harness.HsmPluginPrefix+dmType+\".race\", state, -1)\n\t}\n\treturn waitFor(dmStatus, DefaultTimeout)\n}\n\nfunc iConfigureADataMover(dmType string) error ", "output": "{\n\treturn harness.AddConfiguredMover(ctx, harness.HsmPluginPrefix+dmType+\".race\")\n}"} {"input": "package en\n\nimport (\n\t\"github.com/blevesearch/bleve/analysis\"\n\t\"github.com/blevesearch/bleve/registry\"\n\n\t\"github.com/blevesearch/bleve/analysis/token_filters/lower_case_filter\"\n\t\"github.com/blevesearch/bleve/analysis/token_filters/porter\"\n\t\"github.com/blevesearch/bleve/analysis/tokenizers/unicode\"\n)\n\nconst AnalyzerName = \"en\"\n\nfunc AnalyzerConstructor(config map[string]interface{}, cache *registry.Cache) (*analysis.Analyzer, error) {\n\ttokenizer, err := cache.TokenizerNamed(unicode.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpossEnFilter, err := cache.TokenFilterNamed(PossessiveName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttoLowerFilter, err := cache.TokenFilterNamed(lower_case_filter.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstopEnFilter, err := cache.TokenFilterNamed(StopName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstemmerEnFilter, err := cache.TokenFilterNamed(porter.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trv := analysis.Analyzer{\n\t\tTokenizer: tokenizer,\n\t\tTokenFilters: []analysis.TokenFilter{\n\t\t\tpossEnFilter,\n\t\t\ttoLowerFilter,\n\t\t\tstopEnFilter,\n\t\t\tstemmerEnFilter,\n\t\t},\n\t}\n\treturn &rv, nil\n}\n\n\n\nfunc init() ", "output": "{\n\tregistry.RegisterAnalyzer(AnalyzerName, AnalyzerConstructor)\n}"} {"input": "package main\n\nimport (\n\t\"time\"\n)\n\ntype Collider interface {\n\tCollides(x, y int) bool\n\n\tBounds() (x1, y1, x2, y2 int)\n\n\tLayer() int\n\n\tEventHandler\n}\n\n\nfunc CollidersCollide(a, b Collider) bool {\n\tax1, ay1, ax2, ay2 := a.Bounds()\n\tbx1, by1, bx2, by2 := b.Bounds()\n\n\n\tif bx1 > ax1 {\n\t\tax1 = bx1\n\t}\n\tif bx2 < ax2 {\n\t\tax2 = bx2\n\t}\n\tif ax1 > ax2 {\n\t\treturn false\n\t}\n\n\tif by1 > ay1 {\n\t\tay1 = by1\n\t}\n\tif by2 < ay2 {\n\t\tay2 = by2\n\t}\n\tif ay1 > ay2 {\n\t\treturn false\n\t}\n\n\tfor y := ay1; y <= ay2; y++ {\n\t\tfor x := ax1; x <= ax2; x++ {\n\t\t\tif a.Collides(x, y) && b.Collides(x, y) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\ntype EventCollision struct {\n\twhen time.Time\n\tcollider Collider\n\ttarget Collider\n}\n\n\nfunc (ev *EventCollision) When() time.Time {\n\treturn ev.when\n}\n\n\nfunc (ev *EventCollision) Collider() Collider {\n\treturn ev.collider\n}\n\n\nfunc (ev *EventCollision) Target() Collider {\n\treturn ev.target\n}\n\n\n\n\n\nfunc HandleCollision(c1, c2 Collider) ", "output": "{\n\twhen := time.Now()\n\tev1 := &EventCollision{when: when, collider: c2, target: c1}\n\tev2 := &EventCollision{when: when, collider: c1, target: c2}\n\n\tc1.HandleEvent(ev1)\n\tc2.HandleEvent(ev2)\n}"} {"input": "package players\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestRepo_UnPick(t *testing.T) {\n\tp := Player{ID: 1}\n\tr := &Repo{\n\t\tPosition: 3,\n\t\tClaimed: []Player{{ID: 1, ADP: 45}},\n\t}\n\n\tvar err error\n\n\tp.ID = 2\n\terr = r.UnPick(p)\n\n\trequire.Error(t, err)\n\trequire.Equal(t, 1, len(r.Claimed))\n\trequire.Equal(t, 0, len(r.Available))\n\trequire.Equal(t, 3, r.Position)\n\n\tp.ID = 1\n\terr = r.UnPick(p)\n\n\trequire.NoError(t, err)\n\trequire.Equal(t, 0, len(r.Claimed))\n\trequire.Equal(t, 1, len(r.Available))\n\trequire.Equal(t, 2, r.Position)\n}\n\nfunc TestRepo_Pick(t *testing.T) ", "output": "{\n\tp := Player{ID: 1}\n\tr := &Repo{\n\t\tAvailable: []Player{{ID: 1, ADP: 45}},\n\t}\n\tvar err error\n\n\tp.ID = 2\n\terr = r.Pick(p)\n\trequire.Error(t, err)\n\n\trequire.Equal(t, 0, len(r.Claimed))\n\trequire.Equal(t, 1, len(r.Available))\n\trequire.Equal(t, 0, r.Position)\n\n\tp.ID = 1\n\terr = r.Pick(p)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 0, len(r.Available))\n\trequire.Equal(t, 1, len(r.Claimed))\n\trequire.Equal(t, 1, r.Position)\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\tloggo \"github.com/juju/loggo\"\n)\n\ntype (\n\tCustomFormatter struct{}\n)\n\nfunc InitLog(path string) {\n\tif path == \"\" {\n\t\tpath = \"./util/conf.json\"\n\t}\n\tconfiguration, err := GetConfig(path)\n\tif err != nil {\n\t\tfmt.Println(\"Error reading config\")\n\t\treturn\n\t}\n\tconfig := SerializeConfig(configuration.Logging)\n\tloggo.ConfigureLoggers(config)\n}\n\nfunc GetLogger(module string) loggo.Logger {\n\tlog := loggo.GetLogger(module)\n\treturn log\n}\n\nfunc (formatter *CustomFormatter) Format(level loggo.Level, module, filename string, line int, timestamp time.Time, message string) string {\n\treturn fmt.Sprintf(\"%s\", message)\n}\n\n\n\nfunc ReplaceLoggerDefaultFormatter() ", "output": "{\n\twriter := loggo.NewSimpleWriter(os.Stderr, &CustomFormatter{})\n\tloggo.ReplaceDefaultWriter(writer)\n}"} {"input": "package ray\n\nimport (\n\t\"github.com/v2ray/v2ray-core/common/alloc\"\n)\n\nconst (\n\tbufferSize = 16\n)\n\n\nfunc NewRay() Ray {\n\treturn &directRay{\n\t\tInput: make(chan *alloc.Buffer, bufferSize),\n\t\tOutput: make(chan *alloc.Buffer, bufferSize),\n\t}\n}\n\ntype directRay struct {\n\tInput chan *alloc.Buffer\n\tOutput chan *alloc.Buffer\n}\n\nfunc (this *directRay) OutboundInput() <-chan *alloc.Buffer {\n\treturn this.Input\n}\n\n\n\nfunc (this *directRay) InboundInput() chan<- *alloc.Buffer {\n\treturn this.Input\n}\n\nfunc (this *directRay) InboundOutput() <-chan *alloc.Buffer {\n\treturn this.Output\n}\n\nfunc (this *directRay) OutboundOutput() chan<- *alloc.Buffer ", "output": "{\n\treturn this.Output\n}"} {"input": "package core\n\nimport (\n \"errors\"\n \"fmt\"\n \"image\"\n \"image/jpeg\"\n \"io\"\n \"os\"\n \"os/exec\"\n)\n\ntype JPEGHandler struct {\n}\n\nfunc (j *JPEGHandler) ImageType() string {\n return \"image/png\"\n}\n\nfunc (j *JPEGHandler) Decode(reader io.Reader) (image.Image, error) {\n return jpeg.Decode(reader)\n}\n\n\n\nfunc (j *JPEGHandler) Convert(newImageTempPath string, quality uint) error {\n args := []string{fmt.Sprintf(\"--max=%d\", quality), newImageTempPath}\n cmd := exec.Command(\"jpegoptim\", args...)\n err := cmd.Run()\n if err != nil {\n return errors.New(\"Jpegoptim command not working\")\n }\n\n return nil\n}\n\nfunc (j *JPEGHandler) Encode(newImgFile *os.File, newImage image.Image) error ", "output": "{\n return jpeg.Encode(newImgFile, newImage, nil)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/mitchellh/packer/packer\"\n\t\"github.com/mitchellh/packer/packer/plugin\"\n\t\"log\"\n\t\"os\"\n\t\"os/signal\"\n)\n\n\n\n\n\nfunc setupSignalHandlers(ui packer.Ui) ", "output": "{\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, os.Interrupt)\n\n\tgo func() {\n\t\t<-ch\n\t\tlog.Println(\"First interrupt. Ignoring to allow plugins to clean up.\")\n\n\t\tui.Error(\"Interrupt signal received. Cleaning up...\")\n\n\t\t<-ch\n\t\tlog.Println(\"Second interrupt. Exiting now.\")\n\n\t\tui.Error(\"Interrupt signal received twice. Forcefully exiting now.\")\n\n\t\tplugin.CleanupClients()\n\t\tos.Exit(1)\n\t}()\n}"} {"input": "package prometheus\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"text/template\"\n\n\t\"github.com/pkg/errors\"\n\n\ttm \"github.com/supergiant/control/pkg/templatemanager\"\n\t\"github.com/supergiant/control/pkg/workflows/steps\"\n)\n\nconst StepName = \"prometheus\"\n\ntype Config struct {\n\tRBACEnabled bool\n}\n\ntype Step struct {\n\tscript *template.Template\n}\n\nfunc (s *Step) Rollback(context.Context, io.Writer, *steps.Config) error {\n\treturn nil\n}\n\nfunc Init() {\n\ttpl, err := tm.GetTemplate(StepName)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"template %s not found\", StepName))\n\t}\n\n\tsteps.RegisterStep(StepName, New(tpl))\n}\n\nfunc New(script *template.Template) *Step {\n\tt := &Step{\n\t\tscript: script,\n\t}\n\n\treturn t\n}\n\nfunc (s *Step) Run(ctx context.Context, out io.Writer, config *steps.Config) error {\n\terr := steps.RunTemplate(ctx, s.script, config.Runner, out, toStepCfg(config))\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"install prometheus step\")\n\t}\n\n\treturn nil\n}\n\nfunc (s *Step) Name() string {\n\treturn StepName\n}\n\nfunc (s *Step) Description() string {\n\treturn \"Install prometheus\"\n}\n\n\n\nfunc toStepCfg(c *steps.Config) Config {\n\treturn Config{\n\t\tRBACEnabled: c.Kube.RBACEnabled,\n\t}\n}\n\nfunc (s *Step) Depends() []string ", "output": "{\n\treturn nil\n}"} {"input": "package vsphere\n\nimport (\n\t\"github.com/emc-advanced-dev/pkg/errors\"\n\t\"github.com/emc-advanced-dev/unik/pkg/types\"\n)\n\n\n\nfunc (p *VsphereProvider) RemoteDeleteImage(params types.RemoteDeleteImagePararms) error ", "output": "{\n\treturn errors.New(\"not implemented\", nil)\n}"} {"input": "package lrucache\n\n\n\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestListMap_PushBack(t *testing.T) {\n\tm := NewListMap()\n\n\tt1 := time.Now().Nanosecond()\n\tt2 := time.Now().Nanosecond()\n\tm.PushBack(1, t1)\n\tm.PushFront(2, t2)\n\n\tv, _ := m.Get(1)\n\tassert.Equal(t, t1, v)\n\n\tv1, _ := m.Back()\n\tv2, _ := m.Front()\n\tassert.Equal(t, t1, v1)\n\tassert.Equal(t, t2, v2)\n\tassert.Equal(t, 2, m.Len())\n}\n\n\n\nfunc TestListMap_MoveToFront(t *testing.T) {\n\tm := NewListMap()\n\n\tt1 := time.Now().Nanosecond()\n\tt2 := time.Now().Nanosecond()\n\tm.PushBack(1, t1)\n\tm.PushFront(2, t2)\n\n\tm.MoveToFront(1)\n\n\tv1, _ := m.Back()\n\tv2, _ := m.Front()\n\tassert.Equal(t, t2, v1)\n\tassert.Equal(t, t1, v2)\n}\n\nfunc TestListMap_PopFront(t *testing.T) ", "output": "{\n\tm := NewListMap()\n\n\tt1 := time.Now().Nanosecond()\n\tt2 := time.Now().Nanosecond()\n\tm.PushBack(1, t1)\n\tm.PushFront(2, t2)\n\n\tv, _ := m.PopFront()\n\tassert.Equal(t, t2, v)\n\n\tv, _ = m.Front()\n\tassert.Equal(t, t1, v)\n\tassert.Equal(t, 1, m.Len())\n\n\tm.PopFront()\n\tm.PopFront()\n\tassert.Equal(t, 0, m.Len())\n}"} {"input": "package handy\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\ntype TestHandler struct {\n\tDefaultHandler\n}\n\nfunc BenchmarkSimpleRequest(b *testing.B) {\n\tmux := NewHandy()\n\tmux.Handle(\"/foo\", func() Handler { return new(TestHandler) })\n\n\treq, err := http.NewRequest(\"GET\", \"/foo\", nil)\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\n\tw := httptest.NewRecorder()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tmux.ServeHTTP(w, req)\n\t}\n}\n\nfunc BenchmarkPathWithVariable(b *testing.B) {\n\tmux := NewHandy()\n\tmux.Handle(\"/foo/{name}\", func() Handler { return new(TestHandler) })\n\n\treq, err := http.NewRequest(\"GET\", \"/foo/bar\", nil)\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\n\tw := httptest.NewRecorder()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tmux.ServeHTTP(w, req)\n\t}\n}\n\n\n\nfunc BenchmarkPathWithVariables(b *testing.B) ", "output": "{\n\tmux := NewHandy()\n\tmux.Handle(\"/foo/{name}/{age}/{nono}\", func() Handler { return new(TestHandler) })\n\n\treq, err := http.NewRequest(\"GET\", \"/foo/bar/100/x\", nil)\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\n\tw := httptest.NewRecorder()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tmux.ServeHTTP(w, req)\n\t}\n}"} {"input": "package force\n\ntype Limits map[string]Limit\n\ntype Limit struct {\n\tRemaining float64\n\tMax float64\n}\n\n\n\nfunc (forceApi *ForceApi) GetLimits() (limits *Limits, err error) ", "output": "{\n\turi := forceApi.apiResources[limitsKey]\n\n\tlimits = &Limits{}\n\terr = forceApi.Get(uri, nil, limits)\n\n\treturn\n}"} {"input": "package cmd\n\nimport (\n\t\"testing\"\n\n\t\"github.com/docker/machine/libmachine\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc Test_unix_oc_path(t *testing.T) ", "output": "{\n\tapi := libmachine.NewClient(\"foo\", \"foo\")\n\tdefer api.Close()\n\tshellConfig, err := getOcShellConfig(api, \"/Users/john/.minishift/cache/oc/v1.5.0/oc\", \"bash\", false)\n\n\tassert.NoError(t, err)\n\texpectedOcDirPath := \"/Users/john/.minishift/cache/oc/v1.5.0\"\n\tassert.Equal(t, shellConfig.OcDirPath, expectedOcDirPath)\n}"} {"input": "package execcmd\n\nimport (\n\t\"io\"\n\n\t\"github.com/docker/docker/pkg/term\"\n\t\"github.com/sirupsen/logrus\"\n)\n\n\n\ntype OutStream struct {\n\tCommonStream\n\tout io.Writer\n}\n\nfunc (o *OutStream) Write(p []byte) (int, error) {\n\treturn o.out.Write(p)\n}\n\n\nfunc (o *OutStream) GetTtySize() (uint, uint) {\n\tif !o.isTerminal {\n\t\treturn 0, 0\n\t}\n\tws, err := term.GetWinsize(o.fd)\n\tif err != nil {\n\t\tlogrus.Debugf(\"Error getting size: %s\", err)\n\t\tif ws == nil {\n\t\t\treturn 0, 0\n\t\t}\n\t}\n\treturn uint(ws.Height), uint(ws.Width)\n}\n\n\n\n\nfunc NewOutStream(out io.Writer) io.Writer ", "output": "{\n\tif out == nil {\n\t\treturn nil\n\t}\n\n\tfd, isTerminal := term.GetFdInfo(out)\n\treturn &OutStream{CommonStream: CommonStream{fd: fd, isTerminal: isTerminal}, out: out}\n}"} {"input": "package ast\n\nvar _ Action = &PassAfterOrIgnore{}\n\n\ntype PassAfterOrIgnore struct {\n\taccess\n\tLimit *Target\n}\n\n\n\nfunc (p *PassAfterOrIgnore) String() string {\n\tpu := &PassAfter{\n\t\tLimit: p.Limit,\n\t}\n\tif p.Limit.Lower == p.Limit.Upper && p.Limit.Lower > 0 {\n\t\treturn pu.String() + \" or ignore otherwise\"\n\t} else {\n\t\treturn pu.String() + \" or ignore if not found\"\n\t}\n}\n\n\nfunc PassAfterTargetOrIgnore() *PassAfterOrIgnore {\n\treturn &PassAfterOrIgnore{\n\t\tLimit: NewTarget(),\n\t}\n}\n\nfunc (p *PassAfterOrIgnore) Accept(d ActionDispatcher) error ", "output": "{\n\treturn d.DispatchPassAfterOrIgnore(p)\n}"} {"input": "package event \n\nimport (\n\t\"github.com/docker/infrakit/pkg/spi/event\"\n\t\"github.com/docker/infrakit/pkg/types\"\n)\n\n\ntype Plugin struct {\n\tevent.Publisher\n\n\tDoList func(topic types.Path) (child []string, err error)\n}\n\n\nfunc (t *Plugin) List(topic types.Path) (child []string, err error) {\n\treturn t.DoList(topic)\n}\n\n\ntype Publisher struct {\n\n\tDoPublishOn func(chan<- *event.Event)\n}\n\n\n\n\nfunc (t *Publisher) PublishOn(c chan<- *event.Event) ", "output": "{\n\tif t == nil {\n\t\treturn\n\t}\n\tt.DoPublishOn(c)\n}"} {"input": "package main\nimport (\n \"fmt\"\n \"os\"\n \"strings\"\n)\n\n\n\nfunc (s *TableStats) update(values []string) error {\n if len(values) != len(s.Headers) {\n return fmt.Errorf(\"Found %d values but %d headers\",\n len(values), len(s.Headers))\n }\n for i,header := range(s.Headers) {\n field := s.Fields[header]\n if field != nil {\n field.update(values[i])\n }\n }\n s.NumRows++\n return nil\n}\n\nfunc (s *TableStats) String() string {\n tableStr := fmt.Sprintf(\"Table stats - %d columns, %d rows\\n\"+\n \"=================================\",\n len(s.Headers), s.NumRows)\n var fieldStrs []string\n for _,header := range(s.Headers) {\n var headerStr string\n if header == \"\" {\n headerStr = \"(blank header)\"\n } else {\n headerStr = \"'\"+header+\"'\"\n }\n fieldStr := s.Fields[header].String()\n fieldStrs = append(fieldStrs, fmt.Sprintf(\"%s %s\",\n headerStr, fieldStr))\n }\n return tableStr + \"\\n\\n\" + strings.Join(fieldStrs, \"\\n\\n\")\n}\n\nfunc (s *TableStats) init(headers []string) error ", "output": "{\n s.Headers = make([]string, len(headers))\n s.Fields = make(map[string]*FieldStats)\n for i,header := range(headers) {\n header = strings.TrimSpace(header)\n if _,ok := s.Fields[header]; ok {\n fmt.Fprintf(os.Stderr, \"Duplicate header '%s'\\n\", header)\n }\n stats := new(FieldStats)\n stats.init()\n s.Headers[i] = header\n s.Fields[header] = stats\n }\n return nil\n}"} {"input": "package notmain\n\nimport (\n\t\"testing\"\n\n\t\"github.com/letsencrypt/boulder/test\"\n)\n\n\n\nfunc TestLineValidRejects(t *testing.T) {\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: xxxxxxx Caught SIGTERM\")\n\ttest.AssertError(t, err, \"didn't error on invalid checksum\")\n}\n\nfunc TestLineValidRejectsNotAChecksum(t *testing.T) {\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: xxxx Caught SIGTERM\")\n\ttest.AssertError(t, err, \"didn't error on invalid checksum\")\n\ttest.AssertErrorIs(t, err, errInvalidChecksum)\n}\n\nfunc TestLineValidNonOurobouros(t *testing.T) {\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: xxxxxxx Caught SIGTERM\")\n\ttest.AssertError(t, err, \"didn't error on invalid checksum\")\n\n\tselfOutput := \"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 log-validator[1337]: xxxxxxx \" + err.Error()\n\terr2 := lineValid(selfOutput)\n\ttest.AssertNotError(t, err2, \"expected no error when feeding lineValid's error output into itself\")\n}\n\nfunc TestLineValidAccepts(t *testing.T) ", "output": "{\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: kKG6cwA Caught SIGTERM\")\n\ttest.AssertNotError(t, err, \"errored on valid checksum\")\n}"} {"input": "package oauth2\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\nconst (\n\tErrorAccessDenied = \"access_denied\"\n\tErrorInvalidClient = \"invalid_client\"\n\tErrorInvalidGrant = \"invalid_grant\"\n\tErrorInvalidRequest = \"invalid_request\"\n\tErrorServerError = \"server_error\"\n\tErrorUnauthorizedClient = \"unauthorized_client\"\n\tErrorUnsupportedGrantType = \"unsupported_grant_type\"\n\tErrorUnsupportedResponseType = \"unsupported_response_type\"\n)\n\ntype Error struct {\n\tType string `json:\"error\"`\n\tState string `json:\"state,omitempty\"`\n}\n\nfunc (e *Error) Error() string {\n\treturn e.Type\n}\n\n\n\nfunc unmarshalError(b []byte) error {\n\tvar oerr Error\n\terr := json.Unmarshal(b, &oerr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unrecognized error: %s\", string(b))\n\t}\n\treturn &oerr\n}\n\nfunc NewError(typ string) *Error ", "output": "{\n\treturn &Error{Type: typ}\n}"} {"input": "package model\n\nimport \"github.com/gogo/protobuf/proto\"\n\n\n\nfunc (p *Packet) UnmarshalBinary(data []byte) error {\n\treturn proto.Unmarshal(data, p)\n}\n\nfunc (p *Packet) MarshalBinary() ([]byte, error) ", "output": "{\n\treturn proto.Marshal(p)\n}"} {"input": "package msg\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\n\tzmq \"github.com/pebbe/zmq4\"\n)\n\n\ntype Ping struct {\n\troutingId []byte\n}\n\n\nfunc NewPing() *Ping {\n\tping := &Ping{}\n\treturn ping\n}\n\n\nfunc (p *Ping) String() string {\n\tstr := \"ZCCP_MSG_PING:\\n\"\n\treturn str\n}\n\n\nfunc (p *Ping) Marshal() ([]byte, error) {\n\tbufferSize := 2 + 1 \n\n\ttmpBuf := make([]byte, bufferSize)\n\ttmpBuf = tmpBuf[:0]\n\tbuffer := bytes.NewBuffer(tmpBuf)\n\tbinary.Write(buffer, binary.BigEndian, Signature)\n\tbinary.Write(buffer, binary.BigEndian, PingId)\n\n\treturn buffer.Bytes(), nil\n}\n\n\nfunc (p *Ping) Unmarshal(frames ...[]byte) error {\n\tif frames == nil {\n\t\treturn errors.New(\"Can't unmarshal empty message\")\n\t}\n\n\tframe := frames[0]\n\tframes = frames[1:]\n\n\tbuffer := bytes.NewBuffer(frame)\n\n\tvar signature uint16\n\tbinary.Read(buffer, binary.BigEndian, &signature)\n\tif signature != Signature {\n\t\treturn errors.New(\"invalid signature\")\n\t}\n\n\tvar id uint8\n\tbinary.Read(buffer, binary.BigEndian, &id)\n\tif id != PingId {\n\t\treturn errors.New(\"malformed Ping message\")\n\t}\n\n\treturn nil\n}\n\n\n\n\n\n\nfunc (p *Ping) RoutingId() []byte {\n\treturn p.routingId\n}\n\n\n\nfunc (p *Ping) SetRoutingId(routingId []byte) {\n\tp.routingId = routingId\n}\n\nfunc (p *Ping) Send(socket *zmq.Socket) (err error) ", "output": "{\n\tframe, err := p.Marshal()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsocType, err := socket.GetType()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif socType == zmq.ROUTER {\n\t\t_, err = socket.SendBytes(p.routingId, zmq.SNDMORE)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t_, err = socket.SendBytes(frame, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn err\n}"} {"input": "package ds\n\nimport (\n\t\"fmt\"\n\t\"hash\"\n\t\"sync\"\n\n\t\"github.com/hashicorp/golang-lru\"\n\trh \"github.com/sselph/scraper/rom/hash\"\n)\n\n\n\ntype Hasher struct {\n\th func() hash.Hash\n\tc *lru.Cache\n\tcl *sync.Mutex\n\tl map[string]*sync.Mutex\n\tb chan []byte\n}\n\n\n\n\nfunc (h *Hasher) getPathLock(p string) (*sync.Mutex, bool) {\n\th.cl.Lock()\n\tdefer h.cl.Unlock()\n\thl, ok := h.l[p]\n\tif !ok {\n\t\thl = &sync.Mutex{}\n\t\thl.Lock()\n\t\th.l[p] = hl\n\t}\n\treturn hl, ok\n}\n\nfunc (h *Hasher) deletePathLock(p string) {\n\th.cl.Lock()\n\tdefer h.cl.Unlock()\n\thl := h.l[p]\n\thl.Unlock()\n\tdelete(h.l, p)\n}\n\n\n\nfunc NewHasher(hashFunc func() hash.Hash, threads int) (*Hasher, error) {\n\tc, err := lru.New(500)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tl := make(map[string]*sync.Mutex)\n\tb := make(chan []byte, threads)\n\tfor i := 0; i < threads; i++ {\n\t\tb <- make([]byte, 1*1024*1024)\n\t}\n\treturn &Hasher{h: hashFunc, c: c, cl: &sync.Mutex{}, l: l, b: b}, nil\n}\n\nfunc (h *Hasher) Hash(p string) (string, error) ", "output": "{\n\tchash, ok := h.c.Get(p)\n\tif ok {\n\t\tswitch chash := chash.(type) {\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"unexpected type %T\", chash)\n\t\tcase string:\n\t\t\treturn chash, nil\n\t\tcase error:\n\t\t\treturn \"\", chash\n\t\t}\n\t}\n\thl, ok := h.getPathLock(p)\n\tif ok {\n\t\thl.Lock()\n\t\thl.Unlock()\n\t\treturn h.Hash(p)\n\t}\n\tdefer h.deletePathLock(p)\n\tb := <-h.b\n\tphash, err := rh.Hash(p, h.h(), b)\n\th.b <- b\n\tif err != nil {\n\t\th.c.Add(p, err)\n\t\treturn \"\", err\n\t}\n\th.c.Add(p, phash)\n\treturn phash, nil\n}"} {"input": "package controller\n\nimport (\n\t\"github.com/kubeflow/katib/pkg/controller.v1beta1/suggestion\"\n)\n\n\n\nfunc init() ", "output": "{\n\tAddToManagerFuncs = append(AddToManagerFuncs, suggestion.Add)\n}"} {"input": "package utils\n\nimport \"bytes\"\n\n\n\ntype CompositeError []error\n\n\nfunc (c *CompositeError) Error() string {\n\tvar b bytes.Buffer\n\tfor ind, err := range *c {\n\t\t_, _ = b.WriteString(err.Error())\n\t\tif ind == len(*c)-1 {\n\t\t\tbreak\n\t\t}\n\t\t_, _ = b.WriteRune('\\n')\n\t}\n\n\treturn b.String()\n}\n\n\n\n\n\nfunc (c *CompositeError) Empty() bool {\n\treturn c == nil || len(*c) == 0\n}\n\n\n\nfunc NewCompositeError(errors ...error) error {\n\tres := &CompositeError{}\n\tfor _, err := range errors {\n\t\tres.AppendError(err)\n\t}\n\tif res.Empty() {\n\t\treturn nil\n\t}\n\treturn res\n}\n\nfunc (c *CompositeError) AppendError(err error) ", "output": "{\n\tif err != nil {\n\t\t*c = append(*c, err)\n\t}\n}"} {"input": "package steps\n\nimport (\n\t\"github.com/cayleygraph/cayley/graph\"\n\t\"github.com/cayleygraph/cayley/query/linkedql\"\n\t\"github.com/cayleygraph/cayley/query/path\"\n\t\"github.com/cayleygraph/quad\"\n\t\"github.com/cayleygraph/quad/voc\"\n)\n\nfunc init() {\n\tlinkedql.Register(&Vertex{})\n}\n\nvar _ linkedql.PathStep = (*Vertex)(nil)\n\n\ntype Vertex struct {\n\tValues []quad.Value `json:\"values\"`\n}\n\n\n\n\n\nfunc (s *Vertex) BuildPath(qs graph.QuadStore, ns *voc.Namespaces) (*path.Path, error) {\n\treturn path.StartPath(qs, linkedql.AbsoluteValues(s.Values, ns)...), nil\n}\n\nfunc (s *Vertex) Description() string ", "output": "{\n\treturn \"resolves to all the existing objects and primitive values in the graph. If provided with values resolves to a sublist of all the existing values in the graph.\"\n}"} {"input": "package dory\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\nconst (\n\tmemAvailablePrefix = \"MemAvailable:\"\n)\n\n\n\n\n\n\n\nfunc AvailableMemory(minFree int64, maxUtilisation float64) MemFunc {\n\treturn func(usage int64) int64 {\n\t\treturn int64(float64(getMemAvailable())*maxUtilisation) + usage - minFree\n\t}\n}\n\nfunc getMemAvailable() int64 ", "output": "{\n\tr, err := os.Open(\"/proc/meminfo\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer r.Close()\n\n\tmemAvailable := int64(0)\n\tbufr := bufio.NewReader(r)\n\tfor {\n\t\tline, err := bufr.ReadString('\\n')\n\t\tif strings.HasPrefix(line, memAvailablePrefix) {\n\t\t\tremain := strings.TrimSpace(line[len(memAvailablePrefix):])\n\t\t\tvar units string\n\t\t\t_, err = fmt.Sscanf(remain, \"%d %s\", &memAvailable, &units)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tif units == \"kB\" {\n\t\t\t\tmemAvailable *= 1024\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn memAvailable\n}"} {"input": "package calendar\n\nimport (\n\t\"time\"\n)\n\nvar (\n\tentries = make(map[int]Entry)\n\tindex int\n)\n\ntype Entry struct {\n\tID int\n\tTitle string\n\tStarts time.Time\n\tFinishes time.Time\n}\n\nfunc (e Entry) Duration() time.Duration {\n\treturn e.Finishes.Sub(e.Starts)\n}\n\nfunc Lookup(id int) (Entry, bool) {\n\te, isPresent := entries[id]\n\treturn e, isPresent\n}\n\nfunc Add(e Entry) Entry {\n\tindex++\n\te.ID = index\n\tUpdate(e)\n\treturn e\n}\n\nfunc Update(e Entry) {\n\tentries[e.ID] = e\n}\n\n\n\nfunc Count() int {\n\treturn len(entries)\n}\n\nfunc All() []Entry {\n\tall := []Entry{}\n\tfor _, e := range entries {\n\t\tall = append(all, e)\n\t}\n\treturn all\n}\n\nfunc Remove(id int) ", "output": "{\n\tdelete(entries, id)\n}"} {"input": "package installer\n\nimport (\n\t\"github.com/wx13/genesis\"\n)\n\n\n\ntype Custom struct {\n\tTask genesis.Doer\n\tS func() (genesis.Status, error)\n\tD func() (bool, error)\n\tU func() (bool, error)\n\tI func() string\n\tF func() []string\n}\n\nfunc NewCustom(task genesis.Doer) *Custom {\n\tcustom := Custom{\n\t\tTask: task,\n\t\tS: task.Status,\n\t\tD: task.Do,\n\t\tU: task.Undo,\n\t\tI: task.ID,\n\t\tF: task.Files,\n\t}\n\treturn &custom\n}\n\nfunc (custom Custom) Status() (genesis.Status, error) {\n\treturn custom.S()\n}\n\n\n\nfunc (custom Custom) Undo() (bool, error) {\n\treturn custom.U()\n}\n\nfunc (custom Custom) ID() string {\n\treturn custom.I()\n}\n\nfunc (custom Custom) Files() []string {\n\treturn custom.F()\n}\n\nfunc (custom Custom) Do() (bool, error) ", "output": "{\n\treturn custom.D()\n}"} {"input": "package devicesettingschange_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/tidepool-org/platform/test\"\n)\n\n\n\nfunc TestSuite(t *testing.T) ", "output": "{\n\ttest.Test(t)\n}"} {"input": "package httpretry\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype dialer struct {\n\tTimeout time.Duration\n\tKeepAlive time.Duration\n\tInactivity time.Duration\n}\n\nfunc (d *dialer) Dial(netw, addr string) (net.Conn, error) {\n\tc, err := net.DialTimeout(netw, addr, d.Timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif tc, ok := c.(*net.TCPConn); ok {\n\t\ttc.SetKeepAlive(true)\n\t\ttc.SetKeepAlivePeriod(d.KeepAlive)\n\t}\n\treturn &deadlineConn{d.Inactivity, c}, nil\n}\n\n\n\n\n\n\n\n\nfunc ClientWithTimeout(timeout time.Duration) *http.Client {\n\tdialer := NewDialer(timeout)\n\ttransport := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: dialer.Dial,\n\t\tResponseHeaderTimeout: dialer.Inactivity,\n\t\tMaxIdleConnsPerHost: 10,\n\t}\n\treturn &http.Client{Transport: transport}\n}\n\n\n\n\nfunc DialWithTimeout(timeout time.Duration) func(netw, addr string) (net.Conn, error) {\n\treturn NewDialer(timeout).Dial\n}\n\n\n\nfunc NewDialer(timeout time.Duration) *dialer {\n\treturn &dialer{Timeout: timeout, KeepAlive: timeout, Inactivity: timeout}\n}\n\ntype deadlineConn struct {\n\tTimeout time.Duration\n\tnet.Conn\n}\n\n\n\nfunc (c *deadlineConn) Write(b []byte) (int, error) {\n\tif err := c.Conn.SetDeadline(time.Now().Add(c.Timeout)); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.Conn.Write(b)\n}\n\nfunc (c *deadlineConn) Read(b []byte) (int, error) ", "output": "{\n\tif err := c.Conn.SetDeadline(time.Now().Add(c.Timeout)); err != nil {\n\t\treturn 0, err\n\t}\n\treturn c.Conn.Read(b)\n}"} {"input": "package route\n\nimport \"github.com/berkaroad/saashard/sqlparser\"\n\nfunc (r *Router) buildKillConnection(statement *sqlparser.KillConnection) (*normalPlan, error) {\n\tschemaConfig := r.Schemas[r.SchemaName]\n\tplan := new(normalPlan)\n\n\tplan.nodeNames = []string{schemaConfig.Nodes[0]}\n\tplan.onSlave = true && !r.InTrans\n\tplan.anyNode = true\n\tplan.Statement = statement\n\treturn plan, nil\n}\n\n\n\nfunc (r *Router) buildKillQuery(statement *sqlparser.KillQuery) (*normalPlan, error) ", "output": "{\n\tschemaConfig := r.Schemas[r.SchemaName]\n\tplan := new(normalPlan)\n\n\tplan.nodeNames = []string{schemaConfig.Nodes[0]}\n\tplan.onSlave = true && !r.InTrans\n\tplan.anyNode = true\n\tplan.Statement = statement\n\treturn plan, nil\n}"} {"input": "package signal\n\nimport (\n\t\"github.com/idealeak/goserver/core\"\n)\n\nvar Config = Configuration{}\n\ntype Configuration struct {\n\tSupportSignal bool\n}\n\nfunc (c *Configuration) Name() string {\n\treturn \"signal\"\n}\n\nfunc (c *Configuration) Init() error {\n\tif c.SupportSignal {\n\t\tgo SignalHandlerModule.ProcessSignal()\n\t}\n\treturn nil\n}\n\n\n\nfunc init() {\n\tcore.RegistePackage(&Config)\n}\n\nfunc (c *Configuration) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package resourcemover\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" resourcemover/2021-01-01\"\n}"} {"input": "package vsphere\n\nimport (\n\t\"fmt\"\n)\n\nconst BuilderId = \"packer.post-processor.vsphere\"\n\ntype Artifact struct {\n\tfiles []string\n\tdatastore string\n\tvmfolder string\n\tvmname string\n}\n\nfunc NewArtifact(datastore, vmfolder, vmname string, files []string) *Artifact {\n\treturn &Artifact{\n\t\tfiles: files,\n\t\tdatastore: datastore,\n\t\tvmfolder: vmfolder,\n\t\tvmname: vmname,\n\t}\n}\n\nfunc (*Artifact) BuilderId() string {\n\treturn BuilderId\n}\n\nfunc (a *Artifact) Files() []string {\n\treturn a.files\n}\n\nfunc (a *Artifact) Id() string {\n\treturn fmt.Sprintf(\"%s::%s::%s\", a.datastore, a.vmfolder, a.vmname)\n}\n\nfunc (a *Artifact) String() string {\n\treturn fmt.Sprintf(\"VM: %s Folder: %s Datastore: %s\", a.vmname, a.vmfolder, a.datastore)\n}\n\n\n\nfunc (a *Artifact) Destroy() error {\n\treturn nil\n}\n\nfunc (*Artifact) State(name string) interface{} ", "output": "{\n\treturn nil\n}"} {"input": "package smtpio\n\nimport (\n\t\"bytes\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/mailslurper/libmailslurper/smtpconstants\"\n)\n\ntype SmtpReader struct {\n\tConnection net.Conn\n}\n\n\n\n\n\nfunc (this *SmtpReader) ReadDataBlock() string {\n\tvar dataBuffer bytes.Buffer\n\n\tfor {\n\t\tdataResponse := this.Read()\n\n\t\tterminatorPos := strings.Index(dataResponse, smtpconstants.SMTP_DATA_TERMINATOR)\n\t\tif terminatorPos <= -1 {\n\t\t\tdataBuffer.WriteString(dataResponse)\n\t\t} else {\n\t\t\tdataBuffer.WriteString(dataResponse[0:terminatorPos])\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn dataBuffer.String()\n}\n\nfunc (this *SmtpReader) Read() string ", "output": "{\n\tvar raw bytes.Buffer\n\tvar bytesRead int\n\n\tbytesRead = 1\n\n\tfor bytesRead > 0 {\n\t\tthis.Connection.SetReadDeadline(time.Now().Add(time.Millisecond * smtpconstants.CONN_TIMEOUT_MILLISECONDS))\n\n\t\tbuffer := make([]byte, smtpconstants.RECEIVE_BUFFER_LEN)\n\t\tbytesRead, err := this.Connection.Read(buffer)\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif bytesRead > 0 {\n\t\t\traw.WriteString(string(buffer[:bytesRead]))\n\t\t}\n\t}\n\n\treturn raw.String()\n}"} {"input": "package bunyan\n\nimport \"fmt\"\n\n\ntype Logger struct {\n\tsink Sink\n\trecord Record\n}\n\n\nfunc NewLogger(target Sink) *Logger {\n\treturn &Logger{target, NewRecord()}\n}\n\n\n\n\n\n\n\nfunc (l *Logger) Include(info Info) Log {\n\treturn NewLogger(InfoSink(l, info))\n}\n\n\n\nfunc (l *Logger) Record(key string, value interface{}) Log {\n\tbuilder := NewLogger(l)\n\tbuilder.record[key] = value\n\treturn builder\n}\n\n\n\nfunc (l *Logger) Recordf(key, value string, args ...interface{}) Log {\n\treturn l.Record(key, fmt.Sprintf(value, args...))\n}\n\n\n\nfunc (l *Logger) Child() Log {\n\treturn NewLogger(l)\n}\n\nfunc (l *Logger) Tracef(msg string, args ...interface{}) { l.send(TRACE, msg, args...) }\nfunc (l *Logger) Debugf(msg string, args ...interface{}) { l.send(DEBUG, msg, args...) }\nfunc (l *Logger) Infof(msg string, args ...interface{}) { l.send(INFO, msg, args...) }\nfunc (l *Logger) Warnf(msg string, args ...interface{}) { l.send(WARN, msg, args...) }\nfunc (l *Logger) Errorf(msg string, args ...interface{}) { l.send(ERROR, msg, args...) }\nfunc (l *Logger) Fatalf(msg string, args ...interface{}) { l.send(FATAL, msg, args...) }\n\nfunc (l *Logger) send(level Level, msg string, args ...interface{}) {\n\trecord := NewRecord()\n\trecord.SetMessagef(level, msg, args...)\n\te := l.Write(record)\n\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc (l *Logger) Write(record Record) error ", "output": "{\n\trecord.TemplateMerge(l.record)\n\treturn l.sink.Write(record)\n}"} {"input": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"net/http\"\n\n\t\"github.com/whitepages/terraform-provider-stingray/Godeps/_workspace/src/github.com/whitepages/go-stingray\"\n)\n\n\n\ntype Config struct {\n\tURL string\n\tUsername string\n\tPassword string\n\tVerifySSL bool\n}\n\nfunc (c *Config) Client() (*stingray.Client, error) {\n\tclient := newClient(c)\n\n\treturn client, nil\n}\n\n\n\nfunc newClient(c *Config) *stingray.Client ", "output": "{\n\tif c.VerifySSL {\n\t\treturn stingray.NewClient(nil, c.URL, c.Username, c.Password)\n\t}\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\thttpClient := &http.Client{Transport: tr}\n\n\treturn stingray.NewClient(httpClient, c.URL, c.Username, c.Password)\n}"} {"input": "package models\n\nimport \"fmt\"\n\n\nvar RoomPool = make([] *Room, 0)\n\nfunc AddRoom(r *Room) {\n\tRoomPool = append(RoomPool, r)\n}\n\n\n\n\n\n\n\n\nfunc RemoveRoom(r *Room) {\n\n\tindex, _ := FindRoom(r.Name)\n\n\tif index != -1 {\n\t\tRoomPool = append(RoomPool[:index], RoomPool[index + 1:]...)\n\t}\n}\n\n\n\n\nfunc RemoveClient(c *Client) {\n\tfor _, room := range RoomPool{\n\t\tif room.Name == c.Room {\n\t\t\tif room.HasClient(c) {\n\t\t\t\troom.DeleteClient(c)\n\t\t\t\tif room.ClientCount() == 0 {\n\t\t\t\t\tRemoveRoom(room)\n\t\t\t\t\tPoolBroadcast(NewMessage(map[string]string{\n\t\t\t\t\t\t\"connectedClients\": fmt.Sprintf(\"%v\", GetAllClients()),\n\t\t\t\t\t\t\"numberOfRooms\": fmt.Sprintf(\"%v\", GetNumberOfRooms()),\n\t\t\t\t\t}))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\nfunc ListRooms() (int, []string) {\n\tpool := make([]string, 0)\n\tfor _, obj := range RoomPool {\n\t\tpool = append(pool, obj.Name)\n\t}\n\treturn len(RoomPool), pool\n}\n\n\nfunc PoolBroadcast(m Message) {\n\tfor _, room := range RoomPool {\n\t\troom.RoomBroadcast(m)\n\t}\n}\n\n\nfunc GetAllClients() int {\n\n\tclientSum := 0\n\tfor _, room := range RoomPool {\n\t\tclientSum += len(room.ClientPool)\n\t}\n\treturn clientSum\n}\n\n\nfunc GetNumberOfRooms() int{\n\treturn len(RoomPool)\n}\n\nfunc FindRoom(d string) (int, *Room) ", "output": "{\n\tfor i, v := range RoomPool {\n\t\tif v.Name == d {\n\t\t\treturn i, v\n\t\t}\n\t}\n\treturn -1, &Room{}\n}"} {"input": "package config\n\nimport (\n\t\"os\"\n)\n\n\ntype config struct {\n\tBackendEndpoint string\n}\n\n\nvar Config = &config{}\n\n\n\n\nfunc Load() ", "output": "{\n\tif v := os.Getenv(\"BINREP_BACKEND_ENDPOINT\"); v != \"\" {\n\t\tConfig.BackendEndpoint = v\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"bufio\"\n\t\"fmt\"\n)\n\ntype Store struct {\n\n}\n\nfunc NewStore() *Store {\n\treturn &Store{}\n}\n\nfunc (s Store)ReadStore(file string) (map[string]string, error) {\n\tstore := make(map[string]string)\n\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn store, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\thandleCommand(store, scanner.Text())\n\t}\n\n\treturn store, scanner.Err()\n}\n\nfunc (s Store)WriteStore(store map[string]string, file string) error {\n\tf, err := os.Create(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\treturn s.WriteTo(store, f)\n}\n\n\n\nfunc (s Store)WriteTo(store map[string]string, w io.Writer) error ", "output": "{\n\tfor k, v := range store {\n\t\tif _, err := fmt.Fprintf(w, \"%v=%v\\n\", k, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-chi/chi\"\n)\n\ntype todosResource struct{}\n\n\nfunc (rs todosResource) Routes() chi.Router {\n\tr := chi.NewRouter()\n\n\tr.Get(\"/\", rs.List) \n\tr.Post(\"/\", rs.Create) \n\tr.Put(\"/\", rs.Delete)\n\n\tr.Route(\"/{id}\", func(r chi.Router) {\n\t\tr.Get(\"/\", rs.Get) \n\t\tr.Put(\"/\", rs.Update) \n\t\tr.Delete(\"/\", rs.Delete) \n\t\tr.Get(\"/sync\", rs.Sync)\n\t})\n\n\treturn r\n}\n\nfunc (rs todosResource) List(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todos list of stuff..\"))\n}\n\n\n\nfunc (rs todosResource) Get(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo get\"))\n}\n\nfunc (rs todosResource) Update(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo update\"))\n}\n\nfunc (rs todosResource) Delete(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo delete\"))\n}\n\nfunc (rs todosResource) Sync(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo sync\"))\n}\n\nfunc (rs todosResource) Create(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tw.Write([]byte(\"todos create\"))\n}"} {"input": "package runtime\n\nimport _ \"unsafe\" \n\n\n\n\nfunc bytes_Compare(s1, s2 []byte) int {\n\tl := len(s1)\n\tif len(s2) < l {\n\t\tl = len(s2)\n\t}\n\tif l == 0 || &s1[0] == &s2[0] {\n\t\tgoto samebytes\n\t}\n\tfor i := 0; i < l; i++ {\n\t\tc1, c2 := s1[i], s2[i]\n\t\tif c1 < c2 {\n\t\t\treturn -1\n\t\t}\n\t\tif c1 > c2 {\n\t\t\treturn +1\n\t\t}\n\t}\nsamebytes:\n\tif len(s1) < len(s2) {\n\t\treturn -1\n\t}\n\tif len(s1) > len(s2) {\n\t\treturn +1\n\t}\n\treturn 0\n}\n\nfunc cmpstring(s1, s2 string) int ", "output": "{\n\tl := len(s1)\n\tif len(s2) < l {\n\t\tl = len(s2)\n\t}\n\tfor i := 0; i < l; i++ {\n\t\tc1, c2 := s1[i], s2[i]\n\t\tif c1 < c2 {\n\t\t\treturn -1\n\t\t}\n\t\tif c1 > c2 {\n\t\t\treturn +1\n\t\t}\n\t}\n\tif len(s1) < len(s2) {\n\t\treturn -1\n\t}\n\tif len(s1) > len(s2) {\n\t\treturn +1\n\t}\n\treturn 0\n}"} {"input": "package main\n\nimport(\n\t\"log\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"net/http\"\n\t\"encoding/json\"\n\t\"github.com/julienschmidt/httprouter\"\n)\n\ntype KeyPair struct\t{\n\n\tKey int `json:\"key\"`\n\tValue string `json:\"value\"`\n}\n\nvar KV = make(map[int]KeyPair)\n\nfunc main() {\n\tfmt.Println(\"Starting server on Port : 3000\")\n\trouter := httprouter.New()\n\trouter.Handle(\"PUT\",\"/keys/:keypair_id/:keypair_value\", InsertKeyPair)\n\trouter.Handle(\"GET\",\"/keys/:keypair_id\",GetKeyPair)\n\trouter.Handle(\"GET\",\"/keys\", GetAllKeyPair)\n\tlog.Fatal(http.ListenAndServe(\":3000\", router))\n}\n\n\n\nfunc GetKeyPair(w http.ResponseWriter, r *http.Request, ps httprouter.Params)\t{\n\n\tkey,_ := strconv.Atoi(ps.ByName(\"keypair_id\"))\n\telem, ok := KV[key]\n\tif ok {\n\n\t\tw.WriteHeader(http.StatusCreated)\n \tjson.NewEncoder(w).Encode(elem)\n\t\tfmt.Println(elem)\n\t}\n}\n\nfunc GetAllKeyPair(w http.ResponseWriter, r* http.Request, _ httprouter.Params)\t{\n\tstore := make([]KeyPair, len(KV))\n\tindex := 0\n\tfor _, value := range KV {\n \tstore[index] = value\n \tindex++\n\t}\n\tjson.NewEncoder(w).Encode(store)\n}\n\nfunc InsertKeyPair(w http.ResponseWriter, r *http.Request, ps httprouter.Params)\t", "output": "{\n\n\tvar key int\n\tvar value string\n\n\tkey,_ = strconv.Atoi(ps.ByName(\"keypair_id\"))\n\tvalue = ps.ByName(\"keypair_value\")\n\tkeyPair := KeyPair{key,value}\n\tKV[key] = keyPair\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"labix.org/v2/mgo\"\n)\n\n\n\n\n\ntype MgoConsistencyMode int\n\nfunc (mcm *MgoConsistencyMode) MarshalGoptions(val string) error {\n\tswitch strings.ToUpper(val) {\n\tcase \"STRONG\":\n\t\t*mcm = MgoConsistencyMode(mgo.Strong)\n\tcase \"MONOTONIC\":\n\t\t*mcm = MgoConsistencyMode(mgo.Monotonic)\n\tcase \"EVENTUAL\":\n\t\t*mcm = MgoConsistencyMode(mgo.Eventual)\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown consistency type \\\"%s\\\"\", val)\n\t}\n\treturn nil\n}\n\n\n\nfunc (mcm *MgoConsistencyMode) Apply(s *mgo.Session) {\n\tswitch MgoConsistencyMode(*mcm) {\n\tcase MgoConsistencyMode(mgo.Strong):\n\t\ts.SetMode(mgo.Strong, true)\n\tcase MgoConsistencyMode(mgo.Monotonic):\n\t\ts.SetMode(mgo.Monotonic, true)\n\tcase MgoConsistencyMode(mgo.Eventual):\n\t\ts.SetMode(mgo.Eventual, true)\n\t}\n}\n\nfunc (mcm *MgoConsistencyMode) String() string ", "output": "{\n\tswitch MgoConsistencyMode(*mcm) {\n\tcase MgoConsistencyMode(mgo.Strong):\n\t\treturn \"STRONG\"\n\tcase MgoConsistencyMode(mgo.Monotonic):\n\t\treturn \"MONOTONIC\"\n\tcase MgoConsistencyMode(mgo.Eventual):\n\t\treturn \"EVENTUAL\"\n\t}\n\treturn \"INVALID\"\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc pinger(c chan string) {\n\tfor i := 0; ; i++ {\n\t\tc <- \"ping\"\n\t}\n}\n\nfunc ponger(c chan string) {\n\tfor i := 0; ; i++ {\n\t\tc <- \"pong\"\n\t}\n}\n\n\n\nfunc main() {\n\tvar c chan string = make(chan string)\n\n\tgo pinger(c)\n\tgo ponger(c)\n\tgo printer(c)\n\n\tvar input string\n\tfmt.Scanln(&input)\n}\n\nfunc printer(c chan string) ", "output": "{\n\tfor {\n\t\tmsg := <-c\n\t\tfmt.Println(msg)\n\t\ttime.Sleep(time.Second * 1)\n\t}\n}"} {"input": "package xy\n\ntype Group []Geometric\n\nfunc (g Group) Accept(visitor Visitor) {\n\tvisitor.VisitGroup(g)\n}\n\n\nfunc (g *Group) Add(shape Geometric) ", "output": "{\n\t*g = append(*g, shape)\n}"} {"input": "package files\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewGetFilesFileidentifierParams() *GetFilesFileidentifierParams {\n\tvar ()\n\treturn &GetFilesFileidentifierParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\nfunc NewGetFilesFileidentifierParamsWithTimeout(timeout time.Duration) *GetFilesFileidentifierParams {\n\tvar ()\n\treturn &GetFilesFileidentifierParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype GetFilesFileidentifierParams struct {\n\n\tFileidentifier string\n\n\ttimeout time.Duration\n}\n\n\n\n\n\nfunc (o *GetFilesFileidentifierParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"fileidentifier\", o.Fileidentifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (o *GetFilesFileidentifierParams) WithFileidentifier(fileidentifier string) *GetFilesFileidentifierParams ", "output": "{\n\to.Fileidentifier = fileidentifier\n\treturn o\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/mexisme/go-config/settings\"\n)\n\n\nfunc AddConfigItems(configKeys []string) {\n\tsettings.AddConfigItems(configKeys)\n}\n\n\nfunc AddConfigItemsWithPFlags(configKeys []string) error {\n\treturn settings.AddConfigItemsWithPFlags(configKeys)\n}\n\n\nfunc ApplyWith(key string, f func(interface{})) {\n\tsettings.ApplyWith(key, f)\n}\n\n\nfunc Get(key string) interface{} {\n\treturn settings.Get(key)\n}\n\n\n\n\n\nfunc GetFloat64(key string) float64 {\n\treturn settings.GetFloat64(key)\n}\n\n\nfunc GetInt(key string) int {\n\treturn settings.GetInt(key)\n}\n\n\nfunc GetString(key string) string {\n\treturn settings.GetString(key)\n}\n\n\nfunc GetStringMap(key string) map[string]interface{} {\n\treturn settings.GetStringMap(key)\n}\n\n\nfunc GetStringMapString(key string) map[string]string {\n\treturn settings.GetStringMapString(key)\n}\n\n\nfunc GetStringSlice(key string) []string {\n\treturn settings.GetStringSlice(key)\n}\n\n\nfunc GetTime(key string) time.Time {\n\treturn settings.GetTime(key)\n}\n\n\nfunc GetDuration(key string) time.Duration {\n\treturn settings.GetDuration(key)\n}\n\n\nfunc IsSet(key string) bool {\n\treturn settings.IsSet(key)\n}\n\n\nfunc AllSettings() map[string]interface{} {\n\treturn settings.AllSettings()\n}\n\nfunc GetBool(key string) bool ", "output": "{\n\treturn settings.GetBool(key)\n}"} {"input": "package service\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/syncloud/redirect/model\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype ActionsDbStub struct {\n\taction *model.Action\n}\n\nfunc (db *ActionsDbStub) GetAction(_ int64, _ uint64) (*model.Action, error) {\n\treturn db.action, nil\n}\nfunc (db *ActionsDbStub) GetActionByToken(_ string, _ uint64) (*model.Action, error) {\n\treturn db.action, nil\n}\n\nfunc (db *ActionsDbStub) InsertAction(action *model.Action) error {\n\tdb.action = action\n\treturn nil\n}\n\nfunc (db *ActionsDbStub) UpdateAction(action *model.Action) error {\n\tif db.action != nil {\n\t\tdb.action = action\n\t}\n\treturn nil\n}\n\nfunc (db *ActionsDbStub) DeleteActions(_ int64) error {\n\tdb.action = nil\n\treturn nil\n}\n\nfunc (db *ActionsDbStub) DeleteAction(actionId uint64) error {\n\tdb.action = nil\n\treturn nil\n}\n\n\n\nfunc TestUpsert(t *testing.T) ", "output": "{\n\n\tdb := &ActionsDbStub{nil}\n\tactions := NewActions(db)\n\n\tuser := &model.User{Id: 1, Email: \"test@example.com\", PasswordHash: \"pass\", Active: true, UpdateToken: \"token\", Timestamp: time.Now()}\n\taction, err := actions.UpsertActivateAction(user.Id)\n\n\tassert.Nil(t, err)\n\tassert.NotNil(t, action)\n\tassert.NotNil(t, db.action)\n}"} {"input": "package matchers_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/blevesearch/bleve\"\n\t\"github.com/blevesearch/bleve/search/query\"\n\t\"github.com/nrwiersma/isenzo/matchers\"\n)\n\nfunc TestParallelMatcher(t *testing.T) {\n\tf := matchers.NewParallelMatcherFactory(newWaitMatcherFactory(), 10)\n\tm, err := f.New(map[string]interface{}{})\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected err; got %v\", err)\n\t}\n\n\tfor i := 0; i < 10; i++ {\n\t\tm.Match(\"\", bleve.NewMatchAllQuery())\n\t}\n\n\tids, errs := m.Finish()\n\tif len(errs) != 0 {\n\t\tt.Fatalf(\"expected no errors; got %v\", errs)\n\t}\n\n\tif len(ids) != 10 {\n\t\tt.Fatalf(\"expected %d results; got %v\", 10, len(ids))\n\t}\n}\n\ntype waitMatcherFactory struct {}\n\nfunc newWaitMatcherFactory() matchers.Factory {\n\treturn &waitMatcherFactory{}\n}\n\nfunc (f waitMatcherFactory) New(doc interface{}) (matchers.Matcher, error) {\n\treturn &waitMatcher{\n\t\tids: make([]string, 0),\n\t}, nil\n}\n\nfunc (f waitMatcherFactory) Map(doc interface{}) (interface{}, error) {\n\treturn doc, nil\n}\n\ntype waitMatcher struct {\n\tids []string\n}\n\n\nfunc (m *waitMatcher) Match(id string, q query.Query) {\n\ttime.Sleep(10 * time.Millisecond)\n\n\tm.ids = append(m.ids, id)\n}\n\n\n\n\nfunc (m *waitMatcher) Finish() (ids []string, errs []error) ", "output": "{\n\treturn m.ids, []error{}\n}"} {"input": "package plugin\n\nimport \"github.com/docker/docker/api/server/router\"\n\n\ntype pluginRouter struct {\n\tbackend Backend\n\troutes []router.Route\n}\n\n\nfunc NewRouter(b Backend) router.Router {\n\tr := &pluginRouter{\n\t\tbackend: b,\n\t}\n\tr.initRoutes()\n\treturn r\n}\n\n\n\n\nfunc (r *pluginRouter) initRoutes() {\n\tr.routes = []router.Route{\n\t\trouter.NewGetRoute(\"/plugins\", r.listPlugins),\n\t\trouter.NewGetRoute(\"/plugins/{name:.*}/json\", r.inspectPlugin),\n\t\trouter.NewGetRoute(\"/plugins/privileges\", r.getPrivileges),\n\t\trouter.NewDeleteRoute(\"/plugins/{name:.*}\", r.removePlugin),\n\t\trouter.NewPostRoute(\"/plugins/{name:.*}/enable\", r.enablePlugin), \n\t\trouter.NewPostRoute(\"/plugins/{name:.*}/disable\", r.disablePlugin),\n\t\trouter.NewPostRoute(\"/plugins/pull\", r.pullPlugin),\n\t\trouter.NewPostRoute(\"/plugins/{name:.*}/push\", r.pushPlugin),\n\t\trouter.NewPostRoute(\"/plugins/{name:.*}/set\", r.setPlugin),\n\t\trouter.NewPostRoute(\"/plugins/create\", r.createPlugin),\n\t}\n}\n\nfunc (r *pluginRouter) Routes() []router.Route ", "output": "{\n\treturn r.routes\n}"} {"input": "package keymanagement\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ImportKeyVersionRequest struct {\n\n\tKeyId *string `mandatory:\"true\" contributesTo:\"path\" name:\"keyId\"`\n\n\tImportKeyVersionDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ImportKeyVersionRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request ImportKeyVersionRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ImportKeyVersionRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ImportKeyVersionResponse struct {\n\n\tRawResponse *http.Response\n\n\tKeyVersion `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ImportKeyVersionResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ImportKeyVersionResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ImportKeyVersionRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package utils\n\nimport (\n\t\"log\"\n\t\"testing\"\n)\n\nvar str = `\n {{.DomainName}}\n \n {{.MemorySize}}\n {{.CPUs}}\n`\n\ntype data struct {\n\tDomainName string\n\tMemorySize uint\n\tCPUs uint\n}\n\n\n\nfunc TestProcessTemplate(t *testing.T) ", "output": "{\n\td := &data{\n\t\tDomainName: \"test\",\n\t\tMemorySize: 1000,\n\t\tCPUs: 2,\n\t}\n\tout, err := ProcessTemplate(str, d)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tlog.Printf(\"DEBUG: %s\\n\", out)\n}"} {"input": "package stats\n\nimport (\n\t\"time\"\n\n\t\"sync\"\n\n\t\"github.com/paulbellamy/ratecounter\"\n)\n\nvar lock = sync.RWMutex{}\n\ntype stat struct {\n\treadReq *ratecounter.RateCounter\n\twriteReq *ratecounter.RateCounter\n}\n\nfunc newStat() stat {\n\treturn stat{\n\t\treadReq: ratecounter.NewRateCounter(time.Hour),\n\t\twriteReq: ratecounter.NewRateCounter(time.Hour),\n\t}\n}\n\ntype namespaceStatMap map[string]stat\n\nvar golbalNamespaceStat namespaceStatMap\n\nfunc init() {\n\tgolbalNamespaceStat = namespaceStatMap{}\n}\n\n\nfunc AddNamespace(label string) {\n\t_, ok := golbalNamespaceStat[label]\n\tif ok {\n\t\treturn\n\t}\n\n\tgolbalNamespaceStat[label] = newStat()\n\treturn\n}\n\n\nfunc IncrRead(label string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tstat, ok := golbalNamespaceStat[label]\n\tif !ok {\n\t\tAddNamespace(label)\n\t\tstat = golbalNamespaceStat[label]\n\t}\n\n\tstat.readReq.Incr(1)\n}\n\n\n\n\n\nfunc Rate(label string) (read, write int64) {\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\tstat, ok := golbalNamespaceStat[label]\n\tif !ok {\n\t\tAddNamespace(label)\n\t\tstat = golbalNamespaceStat[label]\n\t}\n\n\treturn stat.readReq.Rate(), stat.writeReq.Rate()\n}\n\nfunc IncrWrite(label string) ", "output": "{\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tstat, ok := golbalNamespaceStat[label]\n\tif !ok {\n\t\tAddNamespace(label)\n\t\tstat = golbalNamespaceStat[label]\n\t}\n\n\tstat.writeReq.Incr(1)\n}"} {"input": "package pretty_test\n\nimport (\n\t\"fmt\"\n\t\"github.com/centrifugal/centrifugo/Godeps/_workspace/src/github.com/kr/pretty\"\n)\n\n\n\nfunc Example() ", "output": "{\n\ttype myType struct {\n\t\ta, b int\n\t}\n\tvar x = []myType{{1, 2}, {3, 4}, {5, 6}}\n\tfmt.Printf(\"%# v\", pretty.Formatter(x))\n}"} {"input": "package client\n\nimport (\n\t\"errors\"\n\t\"github.com/manythumbed/gegenstand/packets\"\n\t\"github.com/manythumbed/gegenstand/protocol\"\n\t\"io\"\n\t\"net\"\n)\n\ntype Message interface {\n}\n\ntype MessageHandler interface {\n\tHandle(message Message)\n}\n\ntype Connection interface {\n\tConnect() error\n\tDisconnect() error\n\tUnsubscribe(topics ...string) error\n\tSubscribe(handler MessageHandler, topics ...protocol.Subscription) error\n\tPublish(topic string, qos protocol.Qos, retained bool, payload []byte) error\n}\n\ntype dummy struct {\n\tconnected bool\n\tconn net.Conn\n}\n\nfunc (d *dummy) Connect() error {\n\tif d.connected {\n\t\treturn errors.New(\"Already connected\")\n\t}\n\n\n\n\td.connected = true\n\treturn nil\n}\n\n\n\nfunc disconnect(w io.Writer) error {\n\t_, err := w.Write(packets.WriteDisconnect())\n\n\treturn err\n}\n\nfunc (d *dummy) Disconnect() error ", "output": "{\n\tif !d.connected {\n\t\treturn errors.New(\"Not connected\")\n\t}\n\n\terr := disconnect(d.conn)\n\terr = d.conn.Close()\n\n\td.connected = false\n\treturn err\n}"} {"input": "package model\n\nimport (\n\t\"fmt\"\n)\n\ntype APIEndpoints []APIEndpoint\n\n\nconst DefaultAPIEndpointName = \"Default\"\n\n\nfunc NewDefaultAPIEndpoints(dnsName string, subnets []SubnetReference, hostedZoneId string, createRecordSet bool, recordSetTTL int, private bool) APIEndpoints {\n\treturn []APIEndpoint{\n\t\tAPIEndpoint{\n\t\t\tName: DefaultAPIEndpointName,\n\t\t\tDNSName: dnsName,\n\t\t\tLoadBalancer: APIEndpointLB{\n\t\t\t\tAPIAccessAllowedSourceCIDRs: DefaultCIDRRanges(),\n\t\t\t\tSubnetReferences: subnets,\n\t\t\t\tHostedZone: HostedZone{\n\t\t\t\t\tIdentifier: Identifier{\n\t\t\t\t\t\tID: hostedZoneId,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tCreateRecordSet: &createRecordSet,\n\t\t\t\tRecordSetTTLSpecified: &recordSetTTL,\n\t\t\t\tPrivateSpecified: &private,\n\t\t\t},\n\t\t},\n\t}\n}\n\n\n\n\nfunc (e APIEndpoints) Validate() error ", "output": "{\n\tfor i, apiEndpoint := range e {\n\t\tif err := apiEndpoint.Validate(); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid apiEndpoint \\\"%s\\\" at index %d: %v\", apiEndpoint.Name, i, err)\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package summa\n\nimport (\n\t\"database/sql\"\n\t_ \"go-sqlite3\"\n\t\"strings\"\n)\n\nconst (\n\tSNIPPETS_LIMIT_MAX = 200\n\tSNIPPETS_LIMIT_DEFAULT = 100\n)\n\nvar (\n\tsnippetsOrderBy = map[string]string{\n\t\t\"commentsAsc\": \"num_comments\",\n\t\t\"commentsDesc\": \"num_comments DESC\",\n\t\t\"filesAsc\": \"num_files\",\n\t\t\"filesDesc\": \"num_files DESC\",\n\t\t\"createdAsc\": \"s.created\",\n\t\t\"createdDesc\": \"s.created DESC\",\n\t\t\"updatedAsc\": \"s.updated\",\n\t\t\"updatedDesc\": \"s.updated DESC\",\n\t\t\"descriptionAsc\": \"s.description\",\n\t\t\"descriptionDesc\": \"s.description DESC\",\n\t}\n)\n\n\n\nfunc apiSnippetsSearch(db *sql.DB, req apiRequest, resp apiResponseData) apiError {\n\tterm, _ := req.Data[\"term\"].(string)\n\torderBy, _ := req.Data[\"orderBy\"].(string)\n\n\torderBy, _ = snippetsOrderBy[strings.ToLower(orderBy)]\n\tif orderBy == \"\" {\n\t\torderBy = snippetsOrderBy[\"updatedDesc\"] + \", \" + snippetsOrderBy[\"createdDesc\"]\n\t}\n\n\tsnips, err := snippetsSearch(db, orderBy, term)\n\tif err != nil {\n\t\treturn &internalServerError{\"Could not fetch snippets\", err}\n\t}\n\n\tresp[\"snippets\"] = snips\n\n\treturn nil\n}\n\nfunc apiSnippetsUnread(db *sql.DB, req apiRequest, resp apiResponseData) apiError {\n\tsnippets, err := snippetsUnread(db, req.Username)\n\tif err != nil {\n\t\treturn &internalServerError{\"Could not fetch snippets\", err}\n\t}\n\n\tresp[\"snippets\"] = snippets\n\n\treturn nil\n}\n\nfunc apiSnippets(db *sql.DB, req apiRequest, resp apiResponseData) apiError ", "output": "{\n\tstart, _ := req.Data[\"start\"].(float64)\n\tlimit, _ := req.Data[\"limit\"].(float64)\n\torderBy, _ := req.Data[\"orderBy\"].(string)\n\tusername, _ := req.Data[\"username\"].(string)\n\n\tif start < 1 {\n\t\tstart = 1\n\t}\n\n\tswitch {\n\tcase limit < 1:\n\t\tlimit = SNIPPETS_LIMIT_DEFAULT\n\n\tcase limit > SNIPPETS_LIMIT_MAX:\n\t\tlimit = SNIPPETS_LIMIT_MAX\n\t}\n\n\torderBy, _ = snippetsOrderBy[strings.ToLower(orderBy)]\n\tif orderBy == \"\" {\n\t\torderBy = snippetsOrderBy[\"updatedDesc\"] + \", \" + snippetsOrderBy[\"createdDesc\"]\n\t}\n\n\tsnips, err := snippetsFetch(db, start, limit, orderBy, username)\n\tif err != nil {\n\t\treturn &internalServerError{\"Could not fetch snippets\", err}\n\t}\n\n\tresp[\"snippets\"] = snips\n\n\treturn nil\n}"} {"input": "package matchers\n\nimport (\n\t\"github.com/nttlabs/cli/cf/errors\"\n\ttestcmd \"github.com/nttlabs/cli/testhelpers/commands\"\n\t\"github.com/onsi/gomega\"\n)\n\ntype havePassedRequirementsMatcher struct{}\n\nfunc HavePassedRequirements() gomega.OmegaMatcher {\n\treturn havePassedRequirementsMatcher{}\n}\n\n\n\nfunc (matcher havePassedRequirementsMatcher) FailureMessage(_ interface{}) string {\n\treturn \"Expected command to pass requirements but it did not\"\n}\n\nfunc (matcher havePassedRequirementsMatcher) NegatedFailureMessage(_ interface{}) string {\n\treturn \"Expected command to have not passed requirements but it did\"\n}\n\nfunc (matcher havePassedRequirementsMatcher) Match(actual interface{}) (bool, error) ", "output": "{\n\tswitch actual.(type) {\n\tcase bool:\n\t\tasBool := actual.(bool)\n\t\treturn asBool == true, nil\n\tcase testcmd.RunCommandResult:\n\t\tresult := actual.(testcmd.RunCommandResult)\n\t\treturn result == testcmd.RunCommandResultSuccess, nil\n\tdefault:\n\t\treturn false, errors.NewWithFmt(\"Expected actual value to be a bool or enum, but it was a %T\", actual)\n\t}\n}"} {"input": "package recurrence\n\nimport (\n\t. \"github.com/smartystreets/goconvey/convey\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestInvalid(t *testing.T) {\n\tConvey(\"With an invalid recurrence type\", t, func() {\n\t\tr := Recurrence{\n\t\t\tFrequence: Frequence(999),\n\t\t\tInterval: 5,\n\t\t\tLocation: time.UTC,\n\t\t\tStart: time.Date(2016, 1, 1, 12, 0, 0, 0, time.UTC),\n\t\t}\n\t\tConvey(\"the there should be no event\", func() {\n\t\t\tnextEvent := r.GetNextDate(time.Now())\n\t\t\tSo(nextEvent, ShouldNotHappen)\n\t\t})\n\t})\n\tConvey(\"A daily recurrence without an interval should act like every day\", t, func() {\n\t\tr := Recurrence{\n\t\t\tFrequence: Daily,\n\t\t\tInterval: 0,\n\t\t\tLocation: time.UTC,\n\t\t\tStart: time.Date(2016, 1, 1, 12, 0, 0, 0, time.UTC),\n\t\t}\n\t\tevent := r.GetNextDate(time.Date(2016, 1, 3, 12, 0, 0, 0, time.UTC))\n\t\tSo(event, ShouldHappenOn, time.Date(2016, 1, 4, 12, 0, 0, 0, time.UTC))\n\t})\n}\n\n\n\nfunc TestNonRepeating(t *testing.T) ", "output": "{\n\tConvey(\"Without a repeating frequence\", t, func() {\n\t\tstart := time.Date(2016, 1, 1, 12, 0, 0, 0, time.UTC)\n\t\tr := Recurrence{\n\t\t\tStart: start,\n\t\t}\n\t\tConvey(\"It should return the start date\", func() {\n\t\t\tevent := r.GetNextDate(time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC))\n\t\t\tSo(event, ShouldHappenOn, start)\n\t\t})\n\t\tConvey(\"There should be no second event\", func() {\n\t\t\tevent := r.GetNextDate(start)\n\t\t\tSo(event, ShouldNotHappen)\n\t\t})\n\t})\n}"} {"input": "package script\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype Script []Command\n\n\n\n\n\nfunc (s *Script) UnmarshalJSON(b []byte) (err error) {\n\tcmds, err := parseJSONCommands(b)\n\tif err != nil {\n\t\treturn\n\t}\n\t*s = Script(cmds)\n\treturn\n}\n\nfunc (s Script) MarshalJSON() ([]byte, error) ", "output": "{\n\tmarshallableCmds, err := commandsToMarshallable(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn json.Marshal(marshallableCmds)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os/user\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tflag.Usage = usage\n\tflag.Parse()\n\tuser, err := user.Current()\n\tif err != nil {\n\t\tlog.Fatal(\"whoami: \", err)\n\t}\n\tfmt.Println(user.Username)\n}\n\n\n\nfunc usage() ", "output": "{\n\tfmt.Fprintln(os.Stderr, \"usage: [options]\")\n\tflag.PrintDefaults()\n\tos.Exit(1)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"regexp\"\n\n\t\"github.com/stoewer/go-strcase\"\n)\n\n\n\nvar ruleNameRegexp = regexp.MustCompile(`NewRuleName\\(([\\d]+), \"([a-z0-9-]+)\"\\)`)\n\nfunc checkRuleName(aip int, name string) []error ", "output": "{\n\tpath := fmt.Sprintf(\"rules/aip%04d/%s.go\", aip, strcase.SnakeCase(name))\n\n\tcontentsBytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\tcontents := string(contentsBytes)\n\n\tmatch := ruleNameRegexp.FindStringSubmatch(contents)\n\tif match == nil {\n\t\treturn []error{fmt.Errorf(\"no rule name found: AIP-%d, %s\", aip, name)}\n\t}\n\n\terrs := []error{}\n\tif fmt.Sprintf(\"%d\", aip) != match[1] {\n\t\terrs = append(errs, fmt.Errorf(\"mismatch between path and rule AIP: %s\", path))\n\t}\n\tif name != match[2] {\n\t\terrs = append(errs, fmt.Errorf(\"mismatch between rule name and filename: %s\", path))\n\t}\n\treturn errs\n}"} {"input": "package strconv \n\nimport \"math\"\n\n\n\n\n\nfunc LenInt(i int64) int {\n\tif i < 0 {\n\t\ti = -i\n\t}\n\tswitch {\n\tcase i < 10:\n\t\treturn 1\n\tcase i < 100:\n\t\treturn 2\n\tcase i < 1000:\n\t\treturn 3\n\tcase i < 10000:\n\t\treturn 4\n\tcase i < 100000:\n\t\treturn 5\n\tcase i < 1000000:\n\t\treturn 6\n\tcase i < 10000000:\n\t\treturn 7\n\tcase i < 100000000:\n\t\treturn 8\n\tcase i < 1000000000:\n\t\treturn 9\n\tcase i < 10000000000:\n\t\treturn 10\n\tcase i < 100000000000:\n\t\treturn 11\n\tcase i < 1000000000000:\n\t\treturn 12\n\tcase i < 10000000000000:\n\t\treturn 13\n\tcase i < 100000000000000:\n\t\treturn 14\n\tcase i < 1000000000000000:\n\t\treturn 15\n\tcase i < 10000000000000000:\n\t\treturn 16\n\tcase i < 100000000000000000:\n\t\treturn 17\n\tcase i < 1000000000000000000:\n\t\treturn 18\n\t}\n\treturn 19\n}\n\nfunc ParseInt(b []byte) (int64, bool) ", "output": "{\n\tneg := false\n\tif len(b) > 0 && (b[0] == '+' || b[0] == '-') {\n\t\tneg = b[0] == '-'\n\t\tb = b[1:]\n\t}\n\tn := uint64(0)\n\tfor i := 0; i < len(b); i++ {\n\t\tc := b[i]\n\t\tif n > math.MaxUint64/10 {\n\t\t\treturn 0, false\n\t\t} else if c >= '0' && c <= '9' {\n\t\t\tn *= 10\n\t\t\tn += uint64(c - '0')\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tif !neg && n > uint64(math.MaxInt64) || n > uint64(math.MaxInt64)+1 {\n\t\treturn 0, false\n\t} else if neg {\n\t\treturn -int64(n), true\n\t}\n\treturn int64(n), true\n}"} {"input": "package state\n\nimport (\n\t\"context\"\n)\n\ntype envKey struct{}\n\n\n\nfunc ContextWith(ctx context.Context, s Store) context.Context {\n\treturn context.WithValue(ctx, envKey{}, s)\n}\n\n\n\n\n\n\n\ntype fail interface {\n\tError(args ...interface{})\n}\n\n\nfunc GetStringOrFail(ctx context.Context, t fail, key string) string {\n\tvalue := \"\"\n\tstate := FromContext(ctx)\n\tif err := state.Get(ctx, key, &value); err != nil {\n\t\tt.Error(err)\n\t}\n\treturn value\n}\n\n\nfunc GetOrFail(ctx context.Context, t fail, key string, value interface{}) {\n\tstate := FromContext(ctx)\n\tif err := state.Get(ctx, key, value); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\n\nfunc SetOrFail(ctx context.Context, t fail, key string, value interface{}) {\n\tstate := FromContext(ctx)\n\tif err := state.Set(ctx, key, value); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc FromContext(ctx context.Context) Store ", "output": "{\n\tif e, ok := ctx.Value(envKey{}).(Store); ok {\n\t\treturn e\n\t}\n\tpanic(\"no Store found in context\")\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\n\ntype Response struct {\n\tBody string `json:\",omitempty\"`\n\tError string `json:\",omitempty\"`\n}\n\n\nfunc (r Response) String() string {\n\tb, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Print(\"Bad marshalling:\", err)\n\t\treturn \"\"\n\t}\n\n\treturn string(b)\n}\n\nfunc ipPrint(r *http.Request, v ...interface{}) {\n\ts := fmt.Sprintf(\"%s %s %s: \", r.RemoteAddr, r.Method, r.URL)\n\tb := make([]interface{}, 0, len(v)+1)\n\tb = append(b, s)\n\tb = append(b, v...)\n\tlog.Print(b...)\n}\n\n\n\nfunc logHttpAccess(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tipPrint(r, \"request\")\n\t\thandler.ServeHTTP(w, r)\n\t})\n}\n\n\n\n\nfunc sendResponseToClient(w http.ResponseWriter, body string, err string) ", "output": "{\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfmt.Fprint(w, Response{body, err})\n}"} {"input": "package news\n\nimport (\n\t\"context\"\n\n\t\"github.com/bwmarrin/discordgo\"\n\t\"github.com/fsufitch/tagioalisi-bot/azure\"\n\t\"github.com/fsufitch/tagioalisi-bot/bot/util\"\n\t\"github.com/fsufitch/tagioalisi-bot/log\"\n)\n\n\ntype Module struct {\n\tLog *log.Logger\n\tNews azure.NewsSearch\n\n\tsession *discordgo.Session\n}\n\n\nfunc (m Module) Name() string { return \"news\" }\n\n\n\n\n\nfunc (m *Module) DoSearch(\n\tctx context.Context,\n\tsession *discordgo.Session,\n\tchannelID string,\n\tquery string,\n\tcount int,\n\tverbose bool,\n) error {\n\tm.Log.Debugf(\"news: searching for `%s`\", query)\n\n\tif !m.News.Ready() {\n\t\treturn util.DiscordMessageSendRawBlock(session, channelID, \"News API not properly instantiated. Sorry! :(\")\n\t}\n\tm.Log.Debugf(\"news: api ready\")\n\n\tresults, err := m.News.Search(ctx, query, int32(count))\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Log.Debugf(\"news: got %d results for %s\", results.Len(), query)\n\n\tvar f formatter\n\tif verbose {\n\t\tf = verboseFormatter\n\t} else {\n\t\tf = compactFormatter\n\t}\n\n\treturn f(session, channelID, results)\n}\n\nfunc (m *Module) Register(ctx context.Context, session *discordgo.Session) error ", "output": "{\n\tm.session = session\n\n\tcancel := m.session.AddHandler(m.handleCommand)\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tm.Log.Infof(\"news module context done\")\n\t\tcancel()\n\t}()\n\n\treturn nil\n}"} {"input": "package coreunix\n\nimport (\n\tcore \"github.com/ipfs/go-ipfs/core\"\n\tdag \"github.com/ipfs/go-ipfs/merkledag\"\n\tft \"github.com/ipfs/go-ipfs/unixfs\"\n\tcid \"gx/ipfs/QmXfiyr2RWEXpVDdaYnD2HNiBk6UBddsvEP4RPfXb6nGqY/go-cid\"\n)\n\n\n\nfunc Metadata(n *core.IpfsNode, skey string) (*ft.Metadata, error) {\n\tc, err := cid.Decode(skey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnd, err := n.DAG.Get(n.Context(), c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpbnd, ok := nd.(*dag.ProtoNode)\n\tif !ok {\n\t\treturn nil, dag.ErrNotProtobuf\n\t}\n\n\treturn ft.MetadataFromBytes(pbnd.Data())\n}\n\nfunc AddMetadataTo(n *core.IpfsNode, skey string, m *ft.Metadata) (string, error) ", "output": "{\n\tc, err := cid.Decode(skey)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnd, err := n.DAG.Get(n.Context(), c)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmdnode := new(dag.ProtoNode)\n\tmdata, err := ft.BytesForMetadata(m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmdnode.SetData(mdata)\n\tif err := mdnode.AddNodeLinkClean(\"file\", nd); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnk, err := n.DAG.Add(mdnode)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn nk.String(), nil\n}"} {"input": "package endpoint\n\nimport (\n\t\"net/http\"\n\t\"regexp\"\n)\n\ntype node struct {\n\tendpoint *endpoint\n\tmethods map[string]http.HandlerFunc\n\tstaticLinks map[string]*node\n\tdynamicLink *node\n\tdynamicMatcher *regexp.Regexp\n\tdynamicParam string\n}\n\nfunc (n *node) getPaths(path string) []string {\n\tp := make([]string, 0, 4)\n\tif nil != n.methods {\n\t\tfor m, _ := range n.methods {\n\t\t\tp = append(p, m + \" \" + path)\n\t\t}\n\t}\n\tif path == \"/\" {\n\t\tpath = \"\"\n\t}\n\tif nil != n.staticLinks {\n\t\tfor s, sn := range n.staticLinks {\n\t\t\tp = append(p, sn.getPaths(path + \"/\" + s)...)\n\t\t}\n\t}\n\tif nil != n.dynamicLink {\n\t\tp = append(p, n.dynamicLink.getPaths(path + \"/:\" + n.dynamicParam)...)\n\t}\n\treturn p\n}\n\n\n\nfunc (n *node) Handle(method string, h http.HandlerFunc) *node {\n\tif n.methods == nil {\n\t\tn.methods = make(map[string]http.HandlerFunc)\n\t}\n\tif n.methods[method] != nil {\n\t\tpanic(\"method handler already registered\")\n\t}\n\tn.methods[method] = h\n\treturn n\n}\n\nfunc (n *node) makeStaticLink(segment string) *node {\n\tif n.dynamicMatcher != nil {\n\t\tpanic(\"cant make static link when there is dynamic link\")\n\t}\n\tif n.staticLinks == nil {\n\t\tn.staticLinks = make(map[string]*node)\n\t}\n\tif n.staticLinks[segment] == nil {\n\t\tn.staticLinks[segment] = n.endpoint.newNode()\n\t}\n\treturn n.staticLinks[segment]\n}\n\nfunc (n *node) makeDynamicLink(name string) *node ", "output": "{\n\tif n.staticLinks != nil {\n\t\tpanic(\"cant make dynamic link when there are static links\")\n\t}\n\tmatcher := n.endpoint.matchers[name]\n\tif matcher == nil {\n\t\tpanic(\"unknown matcher (\" + name + \")\")\n\t}\n\tif n.dynamicMatcher == nil {\n\t\tn.dynamicMatcher = matcher\n\t\tn.dynamicLink = n.endpoint.newNode()\n\t\tn.dynamicParam = name\n\t} else if n.dynamicParam != name {\n\t\tpanic(\"another dynamic link registered on this path\")\n\t}\n\treturn n.dynamicLink\n}"} {"input": "package version \n\nimport \"k8s.io/helm/pkg/proto/hapi/version\"\n\nvar (\n\tVersion = \"v2.5\"\n\n\tBuildMetadata = \"unreleased\"\n\tGitCommit = \"\"\n\tGitTreeState = \"\"\n)\n\n\n\n\n\nfunc GetVersionProto() *version.Version {\n\treturn &version.Version{\n\t\tSemVer: GetVersion(),\n\t\tGitCommit: GitCommit,\n\t\tGitTreeState: GitTreeState,\n\t}\n}\n\nfunc GetVersion() string ", "output": "{\n\tif BuildMetadata == \"\" {\n\t\treturn Version\n\t}\n\treturn Version + \"+\" + BuildMetadata\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n\n\t\"github.com/go-openapi/errors\"\n)\n\n\n\ntype VirtualMachineScaleSetExtensionProfile struct {\n\n\tExtensions []*VirtualMachineScaleSetExtension `json:\"extensions\"`\n}\n\n\n\n\nfunc (m *VirtualMachineScaleSetExtensionProfile) validateExtensions(formats strfmt.Registry) error {\n\n\tif swag.IsZero(m.Extensions) { \n\t\treturn nil\n\t}\n\n\tfor i := 0; i < len(m.Extensions); i++ {\n\n\t\tif swag.IsZero(m.Extensions[i]) { \n\t\t\tcontinue\n\t\t}\n\n\t\tif m.Extensions[i] != nil {\n\n\t\t\tif err := m.Extensions[i].Validate(formats); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nfunc (m *VirtualMachineScaleSetExtensionProfile) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateExtensions(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package x11\n\nimport (\n\t\"C\"\n\t\"unsafe\"\n)\n\ntype SelectionEvent C.XSelectionEvent\n\n\n\nfunc (evt *SelectionEvent) Selection() Atom {\n\treturn Atom(evt.selection)\n}\n\nfunc (evt *SelectionEvent) Target() Atom {\n\treturn Atom(evt.target)\n}\n\nfunc (evt *SelectionEvent) Property() Atom {\n\treturn Atom(evt.property)\n}\n\nfunc (evt *SelectionEvent) When() C.Time {\n\treturn evt.time\n}\n\nfunc (evt *SelectionEvent) ToEvent() *Event {\n\treturn (*Event)(unsafe.Pointer(evt))\n}\n\nfunc (evt *SelectionEvent) Requestor() Window ", "output": "{\n\treturn Window(evt.requestor)\n}"} {"input": "package digitalocean\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\n\t\"github.com/digitalocean/godo\"\n)\n\ntype Artifact struct {\n\tsnapshotName string\n\n\tsnapshotId int\n\n\tregionName string\n\n\tclient *godo.Client\n}\n\nfunc (*Artifact) BuilderId() string {\n\treturn BuilderId\n}\n\nfunc (*Artifact) Files() []string {\n\treturn nil\n}\n\n\n\nfunc (a *Artifact) String() string {\n\treturn fmt.Sprintf(\"A snapshot was created: '%v' (ID: %v) in region '%v'\", a.snapshotName, a.snapshotId, a.regionName)\n}\n\nfunc (a *Artifact) State(name string) interface{} {\n\treturn nil\n}\n\nfunc (a *Artifact) Destroy() error {\n\tlog.Printf(\"Destroying image: %d (%s)\", a.snapshotId, a.snapshotName)\n\t_, err := a.client.Images.Delete(context.TODO(), a.snapshotId)\n\treturn err\n}\n\nfunc (a *Artifact) Id() string ", "output": "{\n\treturn fmt.Sprintf(\"%s:%s\", a.regionName, strconv.FormatUint(uint64(a.snapshotId), 10))\n}"} {"input": "package iso20022\n\n\ntype AutomatedTellerMachine6 struct {\n\n\tIdentification *Max35Text `xml:\"Id\"`\n\n\tAdditionalIdentification *Max35Text `xml:\"AddtlId,omitempty\"`\n\n\tSequenceNumber *Max35Text `xml:\"SeqNb,omitempty\"`\n\n\tLocation *PostalAddress17 `xml:\"Lctn,omitempty\"`\n\n\tLocationCategory *TransactionEnvironment2Code `xml:\"LctnCtgy,omitempty\"`\n\n\tEquipment *ATMEquipment1 `xml:\"Eqpmnt,omitempty\"`\n}\n\nfunc (a *AutomatedTellerMachine6) SetIdentification(value string) {\n\ta.Identification = (*Max35Text)(&value)\n}\n\n\n\nfunc (a *AutomatedTellerMachine6) SetSequenceNumber(value string) {\n\ta.SequenceNumber = (*Max35Text)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) AddLocation() *PostalAddress17 {\n\ta.Location = new(PostalAddress17)\n\treturn a.Location\n}\n\nfunc (a *AutomatedTellerMachine6) SetLocationCategory(value string) {\n\ta.LocationCategory = (*TransactionEnvironment2Code)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) AddEquipment() *ATMEquipment1 {\n\ta.Equipment = new(ATMEquipment1)\n\treturn a.Equipment\n}\n\nfunc (a *AutomatedTellerMachine6) SetAdditionalIdentification(value string) ", "output": "{\n\ta.AdditionalIdentification = (*Max35Text)(&value)\n}"} {"input": "package endpoints\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n)\n\n\ntype MkdirHandler struct {\n\t*State\n}\n\n\nfunc NewMkdirHandler(s *State) *MkdirHandler {\n\treturn &MkdirHandler{State: s}\n}\n\n\ntype MkdirRequest struct {\n\tPath string `json:\"path\"`\n}\n\n\n\nfunc (mh *MkdirHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tmkdirReq := MkdirRequest{}\n\tif err := json.NewDecoder(r.Body).Decode(&mkdirReq); err != nil {\n\t\tjsonifyErrf(w, http.StatusBadRequest, \"bad json\")\n\t\treturn\n\t}\n\n\tif !mh.validatePath(mkdirReq.Path, w, r) {\n\t\tjsonifyErrf(w, http.StatusUnauthorized, \"path forbidden\")\n\t\treturn\n\t}\n\n\tif err := mh.fs.Mkdir(mkdirReq.Path, true); err != nil {\n\t\tlog.Debugf(\"failed to mkdir %s: %v\", mkdirReq.Path, err)\n\t\tjsonifyErrf(w, http.StatusInternalServerError, \"failed to mkdir\")\n\t\treturn\n\t}\n\n\tmsg := fmt.Sprintf(\"mkdir'd »%s«\", mkdirReq.Path)\n\tif !mh.commitChange(msg, w, r) {\n\t\treturn\n\t}\n\tjsonifySuccess(w)\n}"} {"input": "package kvstore\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/cilium/cilium/pkg/metrics\"\n\t\"github.com/cilium/cilium/pkg/option\"\n)\n\nconst (\n\tmetricDelete = \"delete\"\n\tmetricRead = \"read\"\n\tmetricSet = \"set\"\n)\n\nfunc getScopeFromKey(key string) string {\n\ts := strings.SplitN(key, \"/\", 5)\n\tif len(s) != 5 {\n\t\tif len(key) >= 12 {\n\t\t\treturn key[:12]\n\t\t}\n\t\treturn key\n\t}\n\treturn fmt.Sprintf(\"%s/%s\", s[2], s[3])\n}\n\n\n\nfunc trackEventQueued(key string, typ EventType, duration time.Duration) {\n\tif !option.Config.MetricsConfig.KVStoreEventsQueueDurationEnabled {\n\t\treturn\n\t}\n\tmetrics.KVStoreEventsQueueDuration.WithLabelValues(getScopeFromKey(key), typ.String()).Observe(duration.Seconds())\n}\n\nfunc recordQuorumError(err string) {\n\tif !option.Config.MetricsConfig.KVStoreQuorumErrorsEnabled {\n\t\treturn\n\t}\n\tmetrics.KVStoreQuorumErrors.WithLabelValues(err).Inc()\n}\n\nfunc increaseMetric(key, kind, action string, duration time.Duration, err error) ", "output": "{\n\tif !option.Config.MetricsConfig.KVStoreOperationsDurationEnabled {\n\t\treturn\n\t}\n\tnamespace := getScopeFromKey(key)\n\toutcome := metrics.Error2Outcome(err)\n\tmetrics.KVStoreOperationsDuration.\n\t\tWithLabelValues(namespace, kind, action, outcome).Observe(duration.Seconds())\n}"} {"input": "package main\n\nimport (\n\tgd \"github.com/shadowapex/godot-go/gdnative\"\n\t\"github.com/shadowapex/godot-go/godot\"\n\t\"log\"\n\t\"math/rand\"\n)\n\n\n\n\n\ntype Mob struct {\n\tgodot.RigidBody2D\n\tMinSpeed gd.Real\n\tMaxSpeed gd.Real\n\tanimatedSprite godot.AnimatedSpriteImplementer\n}\n\n\nfunc (m *Mob) X_Ready() {\n\tlog.Println(\"X_Ready called!\")\n\n\tanimatedSpritePath := gd.NewNodePath(\"AnimatedSprite\")\n\tanimatedSpriteNode := m.GetNode(animatedSpritePath)\n\tm.animatedSprite = animatedSpriteNode.(godot.AnimatedSpriteImplementer)\n\n\tmobTypes := []gd.String{\"walk\", \"swim\", \"fly\"}\n\n\tm.animatedSprite.SetAnimation(mobTypes[rand.Int()%len(mobTypes)])\n}\n\nfunc (m *Mob) X_OnVisibilityScreenExited() {\n\tm.QueueFree()\n}\n\n\nfunc (m *Mob) X_Process(delta gd.Double) {\n}\n\nfunc NewMob() godot.Class ", "output": "{\n\tmob := &Mob{}\n\n\treturn mob\n}"} {"input": "package mmf\n\nimport (\n\t\"os\"\n\t\"unsafe\"\n\n\tsyscall \"golang.org/x/sys/unix\"\n)\n\n\ntype MappedFile struct {\n\tdata []byte\n\toff int\n\tfile *os.File\n}\n\nfunc (mf *MappedFile) mmap(size int) error {\n\tvar err error\n\tmf.data, err = syscall.Mmap(int(mf.file.Fd()), 0, size, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED)\n\tif err != nil {\n\t\treturn os.NewSyscallError(\"Mmap\", err)\n\t}\n\treturn nil\n}\n\n\n\nfunc (mf *MappedFile) sync(async bool) error {\n\tvar flags uintptr\n\tif async {\n\t\tflags = syscall.MS_ASYNC\n\t} else {\n\t\tflags = syscall.MS_SYNC\n\t}\n\t_, _, errno := syscall.Syscall(syscall.SYS_MSYNC, uintptr(unsafe.Pointer(&mf.data[0])), uintptr(len(mf.data)), flags)\n\tif errno != 0 {\n\t\treturn os.NewSyscallError(\"Msync\", errno)\n\t}\n\treturn nil\n}\n\nfunc (mf *MappedFile) munmap() error ", "output": "{\n\tif data := mf.data; data != nil {\n\t\tmf.data = nil\n\t\tif err := syscall.Munmap(data); err != nil {\n\t\t\treturn os.NewSyscallError(\"Munmap\", err)\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package exec\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\tosexec \"os/exec\"\n\t\"strings\"\n\n\t\"github.com/zimmski/backup\"\n)\n\n\nfunc Combined(name string, args ...string) (string, error) {\n\tif backup.Verbose {\n\t\tfmt.Fprintln(os.Stderr, \"Execute: \", name, strings.Join(args, \" \"))\n\t}\n\n\tcmd := osexec.Command(name, args...)\n\n\tout, err := cmd.CombinedOutput()\n\n\treturn string(out), err\n}\n\n\nfunc CombinedWithDirectOutput(name string, args ...string) (string, error) {\n\tif backup.Verbose {\n\t\tfmt.Fprintln(os.Stderr, \"Execute: \", name, strings.Join(args, \" \"))\n\t}\n\n\tcmd := osexec.Command(name, args...)\n\n\tvar buf bytes.Buffer\n\n\tout := io.MultiWriter(os.Stdout, &buf)\n\n\tcmd.Stderr = out\n\tcmd.Stdout = out\n\n\terr := cmd.Run()\n\n\treturn buf.String(), err\n}\n\n\n\n\nfunc Command(name string, args ...string) *osexec.Cmd ", "output": "{\n\tif backup.Verbose {\n\t\tfmt.Fprintln(os.Stderr, \"Execute: \", name, strings.Join(args, \" \"))\n\t}\n\n\treturn osexec.Command(name, args...)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/bulletind/khabar/utils\"\n\n\t\"gopkg.in/mgo.v2\"\n\t\"gopkg.in/mgo.v2/bson\"\n)\n\nconst (\n\ttopicsCollection = \"topics\"\n)\n\n\n\nfunc main() {\n\tsession, db, _ := Connect()\n\n\tTopics := db.C(topicsCollection)\n\tquery := bson.M{\n\t\t\"org\": utils.M{\"$ne\": \"\"},\n\t\t\"user\": utils.M{\"$ne\": \"\"},\n\t}\n\n\tchange, err := Topics.RemoveAll(query)\n\thandle_errors(err)\n\tfmt.Println(change.Removed, \"user preferences were removed from `\", topicsCollection, \"` collection\")\n\n\tquery[\"user\"] = \"\"\n\tchange, err = Topics.RemoveAll(query)\n\thandle_errors(err)\n\tfmt.Println(change.Removed, \"org preferences were removed from `\", topicsCollection, \"` collection\")\n\n\tsession.Close()\n\tfmt.Println(\"\\n\", \"Closing mongodb connection\")\n}\n\n\n\n\n\n\n\nfunc handle_errors(err error) {\n\tif err != nil {\n\t\tlog.Printf(\"Error %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc Connect() (*mgo.Session, *mgo.Database, string) ", "output": "{\n\turi := os.Getenv(\"MONGODB_URL\")\n\n\tif uri == \"\" {\n\t\turi = \"mongodb://localhost:27017/notifications_testing\"\n\t}\n\n\tmInfo, err := mgo.ParseURL(uri)\n\tsession, err := mgo.Dial(uri)\n\tif err != nil {\n\t\tfmt.Printf(\"Can't connect to mongo, go error %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tsession.SetSafe(&mgo.Safe{})\n\tfmt.Println(\"Connected to\", uri, \"\\n\")\n\n\tsess := session.Clone()\n\n\treturn session, sess.DB(mInfo.Database), mInfo.Database\n}"} {"input": "package main\n\nimport(\n\t\"log\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"net/http\"\n\t\"encoding/json\"\n\t\"github.com/julienschmidt/httprouter\"\n)\n\ntype KeyPair struct\t{\n\n\tKey int `json:\"key\"`\n\tValue string `json:\"value\"`\n}\n\nvar KV = make(map[int]KeyPair)\n\nfunc main() {\n\tfmt.Println(\"Starting server on Port : 3000\")\n\trouter := httprouter.New()\n\trouter.Handle(\"PUT\",\"/keys/:keypair_id/:keypair_value\", InsertKeyPair)\n\trouter.Handle(\"GET\",\"/keys/:keypair_id\",GetKeyPair)\n\trouter.Handle(\"GET\",\"/keys\", GetAllKeyPair)\n\tlog.Fatal(http.ListenAndServe(\":3000\", router))\n}\n\nfunc InsertKeyPair(w http.ResponseWriter, r *http.Request, ps httprouter.Params)\t{\n\n\tvar key int\n\tvar value string\n\n\tkey,_ = strconv.Atoi(ps.ByName(\"keypair_id\"))\n\tvalue = ps.ByName(\"keypair_value\")\n\tkeyPair := KeyPair{key,value}\n\tKV[key] = keyPair\n}\n\nfunc GetKeyPair(w http.ResponseWriter, r *http.Request, ps httprouter.Params)\t{\n\n\tkey,_ := strconv.Atoi(ps.ByName(\"keypair_id\"))\n\telem, ok := KV[key]\n\tif ok {\n\n\t\tw.WriteHeader(http.StatusCreated)\n \tjson.NewEncoder(w).Encode(elem)\n\t\tfmt.Println(elem)\n\t}\n}\n\n\n\nfunc GetAllKeyPair(w http.ResponseWriter, r* http.Request, _ httprouter.Params)\t", "output": "{\n\tstore := make([]KeyPair, len(KV))\n\tindex := 0\n\tfor _, value := range KV {\n \tstore[index] = value\n \tindex++\n\t}\n\tjson.NewEncoder(w).Encode(store)\n}"} {"input": "package session\n\nimport (\n\tgomock \"github.com/golang/mock/gomock\"\n\tanonymous \"github.com/skygeario/skygear-server/pkg/auth/dependency/identity/anonymous\"\n\treflect \"reflect\"\n)\n\n\ntype MockAnonymousIdentityProvider struct {\n\tctrl *gomock.Controller\n\trecorder *MockAnonymousIdentityProviderMockRecorder\n}\n\n\ntype MockAnonymousIdentityProviderMockRecorder struct {\n\tmock *MockAnonymousIdentityProvider\n}\n\n\n\n\n\nfunc (m *MockAnonymousIdentityProvider) EXPECT() *MockAnonymousIdentityProviderMockRecorder {\n\treturn m.recorder\n}\n\n\nfunc (m *MockAnonymousIdentityProvider) List(userID string) ([]*anonymous.Identity, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", userID)\n\tret0, _ := ret[0].([]*anonymous.Identity)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}\n\n\nfunc (mr *MockAnonymousIdentityProviderMockRecorder) List(userID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"List\", reflect.TypeOf((*MockAnonymousIdentityProvider)(nil).List), userID)\n}\n\nfunc NewMockAnonymousIdentityProvider(ctrl *gomock.Controller) *MockAnonymousIdentityProvider ", "output": "{\n\tmock := &MockAnonymousIdentityProvider{ctrl: ctrl}\n\tmock.recorder = &MockAnonymousIdentityProviderMockRecorder{mock}\n\treturn mock\n}"} {"input": "package apmsynthetics\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetMonitorRequest struct {\n\n\tApmDomainId *string `mandatory:\"true\" contributesTo:\"query\" name:\"apmDomainId\"`\n\n\tMonitorId *string `mandatory:\"true\" contributesTo:\"path\" name:\"monitorId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetMonitorRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request GetMonitorRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetMonitorRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetMonitorResponse struct {\n\n\tRawResponse *http.Response\n\n\tMonitor `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetMonitorResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetMonitorResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetMonitorRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package backend\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc BackendInit() {\n}\n\n\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Hello World from James Scott!\")\n}\n\nfunc init() ", "output": "{\n\thttp.HandleFunc(\"/api\", handler)\n}"} {"input": "package actor\n\nimport (\n\t\"time\"\n)\n\n\ntype RestartStatistics struct {\n\tfailureTimes []time.Time\n}\n\n\n\n\n\nfunc (rs *RestartStatistics) FailureCount() int {\n\treturn len(rs.failureTimes)\n}\n\n\nfunc (rs *RestartStatistics) Fail() {\n\trs.failureTimes = append(rs.failureTimes, time.Now())\n}\n\n\nfunc (rs *RestartStatistics) Reset() {\n\trs.failureTimes = []time.Time{}\n}\n\n\nfunc (rs *RestartStatistics) NumberOfFailures(withinDuration time.Duration) int {\n\tif withinDuration == 0 {\n\t\treturn len(rs.failureTimes)\n\t}\n\n\tnum := 0\n\tcurrTime := time.Now()\n\tfor _, t := range rs.failureTimes {\n\t\tif currTime.Sub(t) < withinDuration {\n\t\t\tnum++\n\t\t}\n\t}\n\treturn num\n}\n\nfunc NewRestartStatistics() *RestartStatistics ", "output": "{\n\treturn &RestartStatistics{[]time.Time{}}\n}"} {"input": "package readline\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\n\nfunc goCompletionEntryFunction(text *C.char, state C.int) *C.char {\n\tmatch := completionEntryFunction(C.GoString(text), int(state))\n\tif match == \"\" {\n\t\treturn nil\n\t}\n\treturn C.CString(match) \n}\n\n\n\n\n\n\n\n\n\n\n\ntype CompletionEntryFunction func(text string, state int) string\n\nvar completionEntryFunction CompletionEntryFunction\n\n\n\n\n\n\n\n\n\nfunc SetAttemptedCompletionOver(b bool) {\n\tif b {\n\t\tC.rl_attempted_completion_over = 1\n\t} else {\n\t\tC.rl_attempted_completion_over = 0\n\t}\n}\n\n\n\nfunc SetCompleterWordBreakChars(s string) {\n\tcs := C.CString(s)\n\tC.free(unsafe.Pointer(C.rl_completer_word_break_characters))\n\tC.rl_completer_word_break_characters = cs\n}\n\n\n\n\nfunc CompleterWordBreakChars() string {\n\treturn C.GoString(C.rl_completer_word_break_characters)\n}\n\nfunc SetCompletionEntryFunction(f CompletionEntryFunction) ", "output": "{\n\tif f == nil {\n\t\tif completionEntryFunction != nil {\n\t\t\tC.rl_attempted_completion_function = nil\n\t\t}\n\t} else if completionEntryFunction == nil {\n\t\tC.register_attempted_completion_function()\n\t}\n\tcompletionEntryFunction = f\n}"} {"input": "package libsnnet\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc performBridgeOps(shouldPass bool, assert *assert.Assertions, bridge *Bridge) {\n\ta := assert.Nil\n\tif !shouldPass {\n\t\ta = assert.NotNil\n\t}\n\ta(bridge.enable())\n\ta(bridge.disable())\n\ta(bridge.destroy())\n}\n\n\n\n\n\n\n\n\nfunc TestBridge_Basic(t *testing.T) {\n\tassert := assert.New(t)\n\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge.create())\n\n\tbridge1, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge1.getDevice())\n\tperformBridgeOps(true, assert, bridge)\n\n\tassert.NotNil(bridge.destroy())\n\n}\n\n\n\n\n\n\n\nfunc TestBridge_Dup(t *testing.T) {\n\tassert := assert.New(t)\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge.create())\n\tdefer func() { _ = bridge.destroy() }()\n\n\tbridge1, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\tassert.NotNil(bridge1.create())\n}\n\n\n\n\n\n\n\nfunc TestBridge_Invalid(t *testing.T) {\n\tassert := assert.New(t)\n\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.NotNil(bridge.getDevice())\n\n\tperformBridgeOps(false, assert, bridge)\n}\n\n\n\n\n\n\n\n\n\nfunc TestBridge_GetDevice(t *testing.T) ", "output": "{\n\tassert := assert.New(t)\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge.create())\n\n\tbridge1, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge1.getDevice())\n\tperformBridgeOps(true, assert, bridge1)\n}"} {"input": "package statsd\n\nimport (\n\t\"github.com/golang/glog\"\n)\n\ntype dummyStatsdClientImpl struct {\n\tmessages []string\n}\n\nfunc (client *dummyStatsdClientImpl) open() error {\n\tglog.V(2).Infof(\"dummy statsd client open() called, doing nothing\")\n\treturn nil\n}\n\n\n\nfunc (client *dummyStatsdClientImpl) send(messages []string) error {\n\tclient.messages = messages\n\treturn nil\n}\n\nfunc (client *dummyStatsdClientImpl) close() error ", "output": "{\n\tglog.V(2).Infof(\"dummy statsd client close() called, doing nothing\")\n\treturn nil\n}"} {"input": "package virtualboxclient\n\nimport (\n\t\"github.com/appropriate/go-virtualboxclient/vboxwebsrv\"\n)\n\ntype Machine struct {\n\tvirtualbox *VirtualBox\n\tmanagedObjectId string\n}\n\nfunc (m *Machine) GetChipsetType() (*vboxwebsrv.ChipsetType, error) {\n\trequest := vboxwebsrv.IMachinegetChipsetType{This: m.managedObjectId}\n\n\tresponse, err := m.virtualbox.IMachinegetChipsetType(&request)\n\tif err != nil {\n\t\treturn nil, err \n\t}\n\n\treturn response.Returnval, nil\n}\n\nfunc (m *Machine) GetMediumAttachments() ([]*vboxwebsrv.IMediumAttachment, error) {\n\trequest := vboxwebsrv.IMachinegetMediumAttachments{This: m.managedObjectId}\n\n\tresponse, err := m.virtualbox.IMachinegetMediumAttachments(&request)\n\tif err != nil {\n\t\treturn nil, err \n\t}\n\n\treturn response.Returnval, nil\n}\n\nfunc (m *Machine) GetNetworkAdapter(slot uint32) (*NetworkAdapter, error) {\n\trequest := vboxwebsrv.IMachinegetNetworkAdapter{This: m.managedObjectId, Slot: slot}\n\n\tresponse, err := m.virtualbox.IMachinegetNetworkAdapter(&request)\n\tif err != nil {\n\t\treturn nil, err \n\t}\n\n\treturn &NetworkAdapter{m.virtualbox, response.Returnval}, nil\n}\n\nfunc (m *Machine) GetSettingsFilePath() (string, error) {\n\trequest := vboxwebsrv.IMachinegetSettingsFilePath{This: m.managedObjectId}\n\n\tresponse, err := m.virtualbox.IMachinegetSettingsFilePath(&request)\n\tif err != nil {\n\t\treturn \"\", err \n\t}\n\n\treturn response.Returnval, nil\n}\n\n\n\nfunc (m *Machine) GetStorageControllers() ([]*StorageController, error) ", "output": "{\n\trequest := vboxwebsrv.IMachinegetStorageControllers{This: m.managedObjectId}\n\n\tresponse, err := m.virtualbox.IMachinegetStorageControllers(&request)\n\tif err != nil {\n\t\treturn nil, err \n\t}\n\n\tstorageControllers := make([]*StorageController, len(response.Returnval))\n\tfor i, oid := range response.Returnval {\n\t\tstorageControllers[i] = &StorageController{m.virtualbox, oid}\n\t}\n\n\treturn storageControllers, nil\n}"} {"input": "package analyzer\n\nimport (\n . \"github.com/levythu/gurgling\"\n \"time\"\n \"fmt\"\n \"strconv\"\n)\n\n\n\ntype SimpleAnalyzer struct {\n \n}\n\n\n\nconst token_returncode=\"SimpleAnalyzer-Status-Code\"\nconst token_starttime=\"SimpleAnalyzer-Start-Time\"\n\nfunc logCode(res Response, c int) {\n res.F()[token_returncode]=c\n}\n\nfunc (this *SimpleAnalyzer)Handler(req Request, res Response) (bool, Request, Response) {\n var newRes=&logResponse {\n o: res,\n OnHeadSent: logCode,\n }\n newRes.F()[token_starttime]=time.Now().UnixNano()\n return true, req, newRes\n}\nfunc (this *SimpleAnalyzer)Final(req Request, res Response) {\n var timeStart, ok=res.F()[token_starttime].(int64)\n var timeElpase string\n if ok {\n var t=time.Now().UnixNano()\n timeElpase=strconv.FormatInt((t-timeStart)/1000000, 10)+\"ms\"\n } else {\n timeElpase=\"xxxx\"\n }\n\n var statusCode, ok2=res.F()[token_returncode].(int)\n var codeStr string\n if ok2 {\n codeStr=strconv.Itoa(statusCode)\n } else {\n codeStr=\"---\"\n }\n\n var url=req.R().URL\n fmt.Print(\"- \"+timeElpase+\"\\t\\t\"+codeStr+\"\\t\"+req.Method()+\"\\t\"+url.Path)\n if url.RawQuery!=\"\" {\n fmt.Println(\"?\"+url.RawQuery)\n } else {\n fmt.Println(\"\")\n }\n}\n\nfunc ASimpleAnalyzer() Sandwich ", "output": "{\n return &SimpleAnalyzer{}\n}"} {"input": "package util\n\nimport (\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com/mholt/archiver/v3\"\n\t\"github.com/nuclio/errors\"\n\t\"github.com/nuclio/logger\"\n)\n\ntype Decompressor struct {\n\tlogger logger.Logger\n}\n\nfunc NewDecompressor(parentLogger logger.Logger) (*Decompressor, error) {\n\tnewDecompressor := &Decompressor{\n\t\tlogger: parentLogger,\n\t}\n\n\treturn newDecompressor, nil\n}\n\nfunc (d *Decompressor) Decompress(source string, target string) error {\n\tif err := archiver.Unarchive(source, target); err != nil {\n\t\treturn errors.Wrapf(err, \"Failed to decompress file %s\", source)\n\t}\n\n\treturn nil\n}\n\nfunc IsCompressed(source string) bool {\n\n\tif IsJar(source) {\n\t\treturn false\n\t}\n\n\tunarchiver, err := archiver.ByExtension(source)\n\tif err != nil {\n\t\treturn false\n\t}\n\tu, ok := unarchiver.(archiver.Unarchiver)\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn u != nil\n}\n\n\n\nfunc IsJar(source string) bool ", "output": "{\n\treturn strings.ToLower(path.Ext(source)) == \".jar\"\n}"} {"input": "package remote\n\nimport (\n\t\"github.com/AsynkronIT/protoactor-go/actor\"\n)\n\ntype process struct {\n\tpid *actor.PID\n\tremote *Remote\n}\n\nfunc newProcess(pid *actor.PID, r *Remote) actor.Process {\n\treturn &process{\n\t\tpid: pid,\n\t\tremote: r,\n\t}\n}\n\nfunc (ref *process) SendUserMessage(pid *actor.PID, message interface{}) {\n\theader, msg, sender := actor.UnwrapEnvelope(message)\n\tref.remote.SendMessage(pid, header, msg, sender, -1)\n}\n\n\n\nfunc (ref *process) Stop(pid *actor.PID) {\n\tref.SendSystemMessage(pid, stopMessage)\n}\n\nfunc (ref *process) SendSystemMessage(pid *actor.PID, message interface{}) ", "output": "{\n\n\tswitch msg := message.(type) {\n\tcase *actor.Watch:\n\t\trw := &remoteWatch{\n\t\t\tWatcher: msg.Watcher,\n\t\t\tWatchee: pid,\n\t\t}\n\t\tref.remote.edpManager.remoteWatch(rw)\n\tcase *actor.Unwatch:\n\t\truw := &remoteUnwatch{\n\t\t\tWatcher: msg.Watcher,\n\t\t\tWatchee: pid,\n\t\t}\n\t\tref.remote.edpManager.remoteUnwatch(ruw)\n\tdefault:\n\t\tref.remote.SendMessage(pid, nil, message, nil, -1)\n\t}\n}"} {"input": "package fileutils\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n)\n\nfunc TempDir(namePrefix string, cb func(tmpDir string, err error)) {\n\ttmpDir, err := ioutil.TempDir(\"\", namePrefix)\n\n\tdefer func() {\n\t\tos.RemoveAll(tmpDir)\n\t}()\n\n\tcb(tmpDir, err)\n}\n\n\n\nfunc TempFile(namePrefix string, cb func(tmpFile *os.File, err error)) ", "output": "{\n\ttmpFile, err := ioutil.TempFile(\"\", namePrefix)\n\n\tdefer func() {\n\t\ttmpFile.Close()\n\t\tos.Remove(tmpFile.Name())\n\t}()\n\n\tcb(tmpFile, err)\n}"} {"input": "package oauth2\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/ory-am/fosite\"\n\t\"golang.org/x/net/context\"\n)\n\ntype HandleHelper struct {\n\tAccessTokenStrategy AccessTokenStrategy\n\tAccessTokenStorage AccessTokenStorage\n\tAccessTokenLifespan time.Duration\n}\n\n\n\nfunc (h *HandleHelper) IssueAccessToken(ctx context.Context, req *http.Request, requester fosite.AccessRequester, responder fosite.AccessResponder) error ", "output": "{\n\ttoken, signature, err := h.AccessTokenStrategy.GenerateAccessToken(ctx, requester)\n\tif err != nil {\n\t\treturn err\n\t} else if err := h.AccessTokenStorage.CreateAccessTokenSession(ctx, signature, requester); err != nil {\n\t\treturn err\n\t}\n\n\tresponder.SetAccessToken(token)\n\tresponder.SetTokenType(\"bearer\")\n\tresponder.SetExpiresIn(h.AccessTokenLifespan / time.Second)\n\tresponder.SetScopes(requester.GetGrantedScopes())\n\treturn nil\n}"} {"input": "package bcrypt\n\nimport \"errors\"\n\nfunc newFromPasswordAndSalt(password, unencodedSalt []byte, cost int) (*hashed, error) {\n\tif cost < MinCost {\n\t\tcost = DefaultCost\n\t}\n\tp := new(hashed)\n\tp.major = majorVersion\n\tp.minor = minorVersion\n\n\terr := checkCost(cost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.cost = cost\n\tif len(unencodedSalt) != maxSaltSize {\n\t\treturn nil, errors.New(\"bcrypt: salt must be exactly 16 bytes\")\n\t}\n\n\n\tp.salt = base64Encode(unencodedSalt)\n\thash, err := bcrypt(password, p.cost, p.salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.hash = hash\n\treturn p, err\n}\n\n\n\nfunc GenerateFromPasswordAndSalt(password, rawSalt []byte, cost int) ([]byte, error) ", "output": "{\n\tp, err := newFromPasswordAndSalt(password, rawSalt, cost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p.Hash(), nil\n}"} {"input": "package caddy\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/mholt/caddy/caddy/letsencrypt\"\n)\n\nfunc init() {\n\tletsencrypt.OnChange = func() error { return Restart(nil) }\n}\n\n\nfunc isLocalhost(host string) bool {\n\treturn host == \"localhost\" || host == \"::1\" || strings.HasPrefix(host, \"127.\")\n}\n\n\n\n\n\n\n\n\n\nfunc signalSuccessToParent() {\n\tsignalParentOnce.Do(func() {\n\t\tif IsRestart() {\n\t\t\tppipe := os.NewFile(3, \"\") \n\t\t\t_, err := ppipe.Write([]byte(\"success\")) \n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"[ERROR] Communicating successful init to parent: %v\", err)\n\t\t\t}\n\t\t\tppipe.Close()\n\t\t}\n\t})\n}\n\n\n\n\n\n\n\nvar signalParentOnce sync.Once\n\n\n\n\ntype caddyfileGob struct {\n\tListenerFds map[string]uintptr\n\tCaddyfile Input\n}\n\n\n\nfunc IsRestart() bool {\n\treturn os.Getenv(\"CADDY_RESTART\") == \"true\"\n}\n\n\nfunc writePidFile() error {\n\tpid := []byte(strconv.Itoa(os.Getpid()) + \"\\n\")\n\treturn ioutil.WriteFile(PidFile, pid, 0644)\n}\n\n\n\n\ntype CaddyfileInput struct {\n\tFilepath string\n\tContents []byte\n\tRealFile bool\n}\n\n\nfunc (c CaddyfileInput) Body() []byte { return c.Contents }\n\n\nfunc (c CaddyfileInput) Path() string { return c.Filepath }\n\n\nfunc (c CaddyfileInput) IsFile() bool { return c.RealFile }\n\nfunc checkFdlimit() ", "output": "{\n\tconst min = 4096\n\n\tif runtime.GOOS == \"linux\" || runtime.GOOS == \"darwin\" {\n\t\tout, err := exec.Command(\"sh\", \"-c\", \"ulimit -n\").Output() \n\t\tif err == nil {\n\t\t\tlim, err := strconv.Atoi(string(bytes.TrimSpace(out)))\n\t\t\tif err == nil && lim < min {\n\t\t\t\tfmt.Printf(\"Warning: File descriptor limit %d is too low for production sites. At least %d is recommended. Set with \\\"ulimit -n %d\\\".\\n\", lim, min, min)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package mysql\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"os\"\n)\n\n\ntype writer struct {\n\tconn io.ReadWriteCloser\n}\n\n\n\n\n\nfunc (w *writer) writePacket(p packetWritable) (err os.Error) {\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif err == os.EOF || err == io.ErrUnexpectedEOF {\n\t\t\t\terr = &ClientError{CR_SERVER_LOST, CR_SERVER_LOST_STR}\n\t\t\t}\n\t\t\tif _, ok := err.(*net.OpError); ok {\n\t\t\t\terr = &ClientError{CR_SERVER_LOST, CR_SERVER_LOST_STR}\n\t\t\t}\n\t\t\tif _, ok := err.(*ClientError); !ok {\n\t\t\t\terr = &ClientError{CR_UNKNOWN_ERROR, CR_UNKNOWN_ERROR_STR}\n\t\t\t}\n\t\t}\n\t}()\n\tpktData, err := p.write()\n\tif err != nil {\n\t\treturn\n\t}\n\tnw, err := w.conn.Write(pktData)\n\tif err != nil {\n\t\treturn\n\t}\n\tif nw != len(pktData) {\n\t\terr = &ClientError{CR_DATA_TRUNCATED, CR_DATA_TRUNCATED_STR}\n\t}\n\treturn\n}\n\nfunc newWriter(conn io.ReadWriteCloser) *writer ", "output": "{\n\treturn &writer{\n\t\tconn: conn,\n\t}\n}"} {"input": "package trace \n\nimport (\n\t\"context\"\n\t\"runtime\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"google.golang.org/grpc/metadata\"\n)\n\n\n\n\nfunc DefaultAuthScopes() []string {\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t\t\"https:www.googleapis.com/auth/trace.append\",\n\t\t\"https:www.googleapis.com/auth/trace.readonly\",\n\t}\n}\n\n\n\nfunc versionGo() string {\n\tconst develPrefix = \"devel +\"\n\n\ts := runtime.Version()\n\tif strings.HasPrefix(s, develPrefix) {\n\t\ts = s[len(develPrefix):]\n\t\tif p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 {\n\t\t\ts = s[:p]\n\t\t}\n\t\treturn s\n\t}\n\n\tnotSemverRune := func(r rune) bool {\n\t\treturn strings.IndexRune(\"0123456789.\", r) < 0\n\t}\n\n\tif strings.HasPrefix(s, \"go1\") {\n\t\ts = s[2:]\n\t\tvar prerelease string\n\t\tif p := strings.IndexFunc(s, notSemverRune); p >= 0 {\n\t\t\ts, prerelease = s[:p], s[p:]\n\t\t}\n\t\tif strings.HasSuffix(s, \".\") {\n\t\t\ts += \"0\"\n\t\t} else if strings.Count(s, \".\") < 2 {\n\t\t\ts += \".0\"\n\t\t}\n\t\tif prerelease != \"\" {\n\t\t\ts += \"-\" + prerelease\n\t\t}\n\t\treturn s\n\t}\n\treturn \"UNKNOWN\"\n}\n\nconst versionClient = \"20190306\"\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context ", "output": "{\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\nvar (\n\tn, l, count int\n\tout io.WriteCloser\n)\n\n\n\nfunc output(sequence []string) {\n\tfor i := range sequence {\n\t\tswitch {\n\t\tcase i > 0 && i%64 == 0:\n\t\t\tfmt.Fprintln(out)\n\t\tcase i > 0 && i%4 == 0:\n\t\t\tfmt.Fprint(out, \" \")\n\t\t}\n\t\tfmt.Fprint(out, sequence[i])\n\t}\n\tfmt.Fprintf(out, \"\\n%d\\n\", len(sequence))\n}\n\nfunc dfs(level int, sequence []string) bool {\n\tif count == n {\n\t\toutput(sequence)\n\t\treturn true\n\t}\n\tcount++\n\tfor i := 0; i < l; i++ {\n\t\tif !isEasy(level, append(sequence, string('A'+i))) {\n\t\t\tif dfs(level+1, append(sequence, string('A'+i))) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc main() {\n\tin, _ := os.Open(\"129.in\")\n\tdefer in.Close()\n\tout, _ = os.Create(\"129.out\")\n\tdefer out.Close()\n\n\tfor {\n\t\tif fmt.Fscanf(in, \"%d%d\", &n, &l); n == 0 && l == 0 {\n\t\t\tbreak\n\t\t}\n\t\tcount = 0\n\t\tdfs(0, nil)\n\t}\n}\n\nfunc isEasy(level int, sequence []string) bool ", "output": "{\nhere:\n\tfor i := 1; 2*i <= level+1; i++ {\n\t\tfor j := 0; j < i; j++ {\n\t\t\tif sequence[level-j] != sequence[level-j-i] {\n\t\t\t\tcontinue here\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package balanced\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n)\n\ntype Customer struct {\n\tAddress *Address `json:\"address,omitempty\"`\n\tBusinessName string `json:\"business_name,omitempty\"`\n\tCreatedAt time.Time `json:\"created_at,omitempty\"`\n\tDobMonth int `json:\"dob_month,omitempty\"`\n\tDobYear int `json:\"dob_year,omitempty\"`\n\tEin string `json:\"ein,omitempty\"`\n\tEmail string `json:\"email,omitempty\"`\n\tID string `json:\"id,omitempty\"`\n\tMeta map[string]interface{} `json:\"meta,omitempty\"`\n\tName string `json:\"name,omitempty\"`\n\tPhone string `json:\"phone,omitempty\"`\n\tSSNLast4 string `json:\"ssn_last4,omitempty\"`\n\tMerchantStatus string `json:\"merchant_status,omitempty\"`\n}\n\ntype customerResponse struct {\n\tCustomers []*Customer `json:\"customers\"`\n}\n\nfunc (c *Customer) path() string {\n\treturn \"/customers\"\n}\n\n\n\nfunc (c *Customer) getOwnerPath() string {\n\treturn \"\"\n}\n\nfunc (c *Customer) singleResponse(data []byte) {\n\tparsedResponse := new(customerResponse)\n\tjson.Unmarshal(data, &parsedResponse)\n\t*c = *parsedResponse.Customers[0]\n}\n\nfunc (c *Customer) canDelete() bool {\n\treturn true\n}\n\nfunc (c *Customer) IsVerified() bool {\n\treturn c.MerchantStatus == \"underwritten\"\n}\n\nfunc (c *Customer) getID() string ", "output": "{\n\treturn c.ID\n}"} {"input": "package ostore\n\nimport (\n\t\"crypto/sha512\"\n\t\"encoding/hex\"\n\t\"hash\"\n\t\"io\"\n)\n\ntype HashReader struct {\n\th hash.Hash\n\tr io.Reader\n}\n\nfunc NewHashReader(r io.Reader) *HashReader {\n\treturn &HashReader{sha512.New(), r}\n}\n\nfunc (hr *HashReader) Read(p []byte) (int, error) {\n\tn, err := hr.r.Read(p)\n\tif err != nil {\n\t\treturn n, err\n\t}\n\twn := 0\n\ttn := 0\n\tfor wn, err = hr.h.Write(p[:n]); err != nil && wn < n; {\n\t\ttn, err = hr.h.Write(p[wn:n])\n\t\twn += tn\n\t}\n\treturn n, err\n}\n\nfunc (hr *HashReader) Digest() []byte {\n\treturn hr.h.Sum(nil)\n}\n\n\n\nfunc (hr *HashReader) HexDigest() string ", "output": "{\n\treturn hex.EncodeToString(hr.Digest())\n}"} {"input": "package v1beta1\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/knative-gcp/pkg/apis/duck\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\t\"github.com/google/go-cmp/cmp/cmpopts\"\n\n\t\"knative.dev/pkg/apis\"\n)\n\n\n\nfunc (ts *TopicSpec) Validate(ctx context.Context) *apis.FieldError {\n\tvar errs *apis.FieldError\n\n\tif ts.Topic == \"\" {\n\t\terrs = errs.Also(\n\t\t\tapis.ErrMissingField(\"topic\"),\n\t\t)\n\t}\n\n\tswitch ts.PropagationPolicy {\n\tcase TopicPolicyCreateDelete, TopicPolicyCreateNoDelete, TopicPolicyNoCreateNoDelete:\n\n\tdefault:\n\t\terrs = errs.Also(\n\t\t\tapis.ErrInvalidValue(ts.PropagationPolicy, \"propagationPolicy\"),\n\t\t)\n\t}\n\n\treturn errs\n}\n\nfunc (current *Topic) CheckImmutableFields(ctx context.Context, original *Topic) *apis.FieldError {\n\tif original == nil {\n\t\treturn nil\n\t}\n\n\tvar errs *apis.FieldError\n\tif diff := cmp.Diff(original.Spec, current.Spec,\n\t\tcmpopts.IgnoreFields(TopicSpec{})); diff != \"\" {\n\t\terrs = errs.Also(&apis.FieldError{\n\t\t\tMessage: \"Immutable fields changed (-old +new)\",\n\t\t\tPaths: []string{\"spec\"},\n\t\t\tDetails: diff,\n\t\t})\n\t}\n\terrs = duck.CheckImmutableAutoscalingClassAnnotations(¤t.ObjectMeta, &original.ObjectMeta, errs)\n\n\treturn duck.CheckImmutableClusterNameAnnotation(¤t.ObjectMeta, &original.ObjectMeta, errs)\n}\n\nfunc (t *Topic) Validate(ctx context.Context) *apis.FieldError ", "output": "{\n\terr := t.Spec.Validate(ctx).ViaField(\"spec\")\n\n\tif apis.IsInUpdate(ctx) {\n\t\toriginal := apis.GetBaseline(ctx).(*Topic)\n\t\terr = err.Also(t.CheckImmutableFields(ctx, original))\n\t}\n\treturn err\n}"} {"input": "package ossadmin\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestDeleteOssVpc(t *testing.T) ", "output": "{\n\tvar req DeleteOssVpcRequest\n\treq.Init()\n\treq.SetFormat(\"JSON\")\n\treq.SetRegionId(\"cn-shenzhen\")\n\tvar accessId = \"Ie65kUInu5GeAsma\"\n\tvar accessSecret = \"8cCqoxdYU9zKUihwXFXiN1HEACBDwB\"\n\tresp, err := DeleteOssVpc(&req, accessId, accessSecret)\n\tif err != nil {\n\t\tt.Errorf(\"Error: %s\", err.Error())\n\t}\n\tfmt.Printf(\"Success: %v\\n\", resp)\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"github.com/mitchellh/multistep\"\n\t\"github.com/orivej/packer/packer\"\n)\n\n\n\n\ntype StepOutputDir struct {\n\tForce bool\n\tPath string\n\tsuccess bool\n}\n\n\n\nfunc (s *StepOutputDir) Cleanup(state multistep.StateBag) {\n\t_, cancelled := state.GetOk(multistep.StateCancelled)\n\t_, halted := state.GetOk(multistep.StateHalted)\n\n\tif !s.success {\n\t\treturn\n\t}\n\n\tif cancelled || halted {\n\t\tui := state.Get(\"ui\").(packer.Ui)\n\n\t\tui.Say(\"Deleting output directory...\")\n\t\tfor i := 0; i < 5; i++ {\n\t\t\terr := os.RemoveAll(s.Path)\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tlog.Printf(\"Error removing output dir: %s\", err)\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t}\n\t}\n}\n\nfunc (s *StepOutputDir) Run(state multistep.StateBag) multistep.StepAction ", "output": "{\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\tif _, err := os.Stat(s.Path); err == nil && s.Force {\n\t\tui.Say(\"Deleting previous output directory...\")\n\t\tos.RemoveAll(s.Path)\n\t}\n\n\tif err := os.MkdirAll(s.Path, 0755); err != nil {\n\t\tstate.Put(\"error\", err)\n\t\treturn multistep.ActionHalt\n\t}\n\n\tf, err := os.Create(filepath.Join(s.Path, \"_packer_perm_check\"))\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Couldn't write to output directory: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\treturn multistep.ActionHalt\n\t}\n\tf.Close()\n\tos.Remove(f.Name())\n\n\ts.success = true\n\treturn multistep.ActionContinue\n}"} {"input": "package glacier\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/rdwilliamson/aws\"\n)\n\n\ntype Connection struct {\n\tClient *http.Client\n\n\tSignature *aws.Signature\n}\n\nfunc (c *Connection) client() *http.Client {\n\tif c.Client == nil {\n\t\treturn http.DefaultClient\n\t}\n\treturn c.Client\n}\n\n\nfunc (c *Connection) vault(vault string) string {\n\treturn \"https://\" + c.Signature.Region.Glacier + \"/-/vaults/\" + vault\n}\n\n\nfunc (c *Connection) policy(policy string) string {\n\treturn \"https://\" + c.Signature.Region.Glacier + \"/-/policies/\" + policy\n}\n\n\n\nfunc NewConnection(secret, access string, r *aws.Region) *Connection {\n\treturn &Connection{\n\t\tSignature: aws.NewSignature(secret, access, r, \"glacier\"),\n\t}\n}\n\n\n\n\nfunc toHex(x []byte) string {\n\treturn fmt.Sprintf(\"%x\", x)\n}\n\n\n\ntype parameters url.Values\n\n\n\nfunc (p parameters) add(key, value string) {\n\turl.Values(p).Add(key, value)\n}\n\n\n\n\n\nfunc (p parameters) encode() string ", "output": "{\n\tif encoded := url.Values(p).Encode(); encoded != \"\" {\n\t\treturn \"?\" + encoded\n\t}\n\treturn \"\"\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/api/events/v1beta1\"\n\t\"k8s.io/client-go/deprecated/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype EventsV1beta1Interface interface {\n\tRESTClient() rest.Interface\n\tEventsGetter\n}\n\n\ntype EventsV1beta1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *EventsV1beta1Client) Events(namespace string) EventInterface {\n\treturn newEvents(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*EventsV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &EventsV1beta1Client{client}, nil\n}\n\n\n\n\n\n\nfunc New(c rest.Interface) *EventsV1beta1Client {\n\treturn &EventsV1beta1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *EventsV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfigOrDie(c *rest.Config) *EventsV1beta1Client ", "output": "{\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}"} {"input": "package versioned\n\nimport (\n\t\"strconv\"\n)\n\n\ntype Version int64\n\n\n\n\n\n\n\ntype Object struct {\n\tData interface{}\n\tVersion Version\n}\n\n\n\n\n\nfunc (o *Object) CompareVersion(other Object) int64 {\n\treturn int64(o.Version) - int64(other.Version)\n}\n\nfunc ParseVersion(s string) Version ", "output": "{\n\ti, _ := strconv.ParseInt(s, 10, 64)\n\treturn Version(i)\n}"} {"input": "package group\n\nimport (\n\t\"github.com/wandoulabs/codis/pkg/models\"\n\n\tlog \"github.com/ngaut/logging\"\n)\n\ntype Group struct {\n\tmaster string\n\tredisServers map[string]*models.Server\n}\n\n\n\nfunc NewGroup(groupInfo models.ServerGroup) *Group {\n\tg := &Group{\n\t\tredisServers: make(map[string]*models.Server),\n\t}\n\n\tfor _, server := range groupInfo.Servers {\n\t\tif server.Type == models.SERVER_TYPE_MASTER {\n\t\t\tif len(g.master) > 0 {\n\t\t\t\tlog.Fatalf(\"two master not allowed: %+v\", groupInfo)\n\t\t\t}\n\n\t\t\tg.master = server.Addr\n\t\t}\n\t\tg.redisServers[server.Addr] = server\n\t}\n\n\tif len(g.master) == 0 {\n\t\tlog.Fatalf(\"master not found: %+v\", groupInfo)\n\t}\n\n\treturn g\n}\n\nfunc (g *Group) Master() string ", "output": "{\n\treturn g.master\n}"} {"input": "package cf\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\tginkgoconfig \"github.com/onsi/ginkgo/config\"\n\t. \"github.com/onsi/gomega\"\n\t. \"github.com/onsi/gomega/gexec\"\n)\n\nfunc AsUser(userContext UserContext, actions func()) {\n\toriginalCfHomeDir, currentCfHomeDir := InitiateUserContext(userContext)\n\tdefer func() {\n\t\tRestoreUserContext(userContext, originalCfHomeDir, currentCfHomeDir)\n\t}()\n\n\tTargetSpace(userContext)\n\n\tactions()\n}\n\n\n\nfunc TargetSpace(userContext UserContext) {\n\tif userContext.Org != \"\" {\n\t\tif userContext.Space != \"\" {\n\t\t\tExpect(Cf(\"target\", \"-o\", userContext.Org, \"-s\", userContext.Space).Wait(CF_API_TIMEOUT)).To(Exit(0))\n\t\t} else {\n\t\t\tExpect(Cf(\"target\", \"-o\", userContext.Org).Wait(CF_API_TIMEOUT)).To(Exit(0))\n\t\t}\n\t}\n}\n\nfunc RestoreUserContext(_ UserContext, originalCfHomeDir, currentCfHomeDir string) {\n\tExpect(Cf(\"logout\").Wait(CF_API_TIMEOUT)).To(Exit(0))\n\tos.Setenv(\"CF_HOME\", originalCfHomeDir)\n\tos.RemoveAll(currentCfHomeDir)\n}\n\nfunc InitiateUserContext(userContext UserContext) (originalCfHomeDir, currentCfHomeDir string) ", "output": "{\n\toriginalCfHomeDir = os.Getenv(\"CF_HOME\")\n\tcurrentCfHomeDir, err := ioutil.TempDir(\"\", fmt.Sprintf(\"cf_home_%d\", ginkgoconfig.GinkgoConfig.ParallelNode))\n\n\tif err != nil {\n\t\tpanic(\"Error: could not create temporary home directory: \" + err.Error())\n\t}\n\n\tos.Setenv(\"CF_HOME\", currentCfHomeDir)\n\n\tcfSetApiArgs := []string{\"api\", userContext.ApiUrl}\n\tif userContext.SkipSSLValidation {\n\t\tcfSetApiArgs = append(cfSetApiArgs, \"--skip-ssl-validation\")\n\t}\n\n\tExpect(Cf(cfSetApiArgs...).Wait(CF_API_TIMEOUT)).To(Exit(0))\n\n\tExpect(Cf(\"auth\", userContext.Username, userContext.Password).Wait(CF_API_TIMEOUT)).To(Exit(0))\n\n\treturn\n}"} {"input": "package cmd\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/antham/doc-hunt/file\"\n\t\"github.com/antham/doc-hunt/ui\"\n\t\"github.com/antham/doc-hunt/util\"\n)\n\n\n\nfunc TestVersion(t *testing.T) ", "output": "{\n\n\tui.Info = func(msg string) {\n\t\tassert.Equal(t, \"v\"+file.GetAppVersion(), msg, \"Must output version\")\n\t}\n\n\tutil.SuccessExit = func() {\n\t}\n\n\tos.Args = []string{\"\", \"version\"}\n\n\terr := RootCmd.Execute()\n\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc printMatrix(m [][]byte) {\n\tfor i:=0;i0;i-- {\n\t\tfor j:=0;j= Word(len(this.sources)) {\n\t\t\t\t\tthis.err <- fmt.Errorf(\"Selected non existent source: %d\", index)\n\t\t\t\t} else if index < 0 {\n\t\t\t\t\tthis.err <- fmt.Errorf(\"Select source %d is less than zero!\", index)\n\t\t\t\t} else {\n\t\t\t\t\tthis.destination <- <-this.sources[index]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (this *Mux) queryControl() {\n\t<-this.Control\n\tif err := this.shutdown(); err != nil {\n\t\tthis.err <- err\n\t}\n}\n\n\n\nfunc (this *Mux) Startup() error {\n\tif this.running {\n\t\treturn fmt.Errorf(\"Given multiplexer is already running!\")\n\t} else {\n\t\tthis.running = true\n\t\tgo this.body()\n\t\tgo this.queryControl()\n\t\treturn nil\n\t}\n}\n\nfunc (this *Mux) shutdown() error ", "output": "{\n\tif !this.running {\n\t\treturn fmt.Errorf(\"Attempted to shutdown a multiplexer which isn't running\")\n\t} else {\n\t\tthis.running = false\n\t\tclose(this.selector)\n\t\treturn nil\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\ntype StorageState struct {\n\tHistoryState HistoryDB `json:\"history,omitempty\"`\n\tTrafficHistoryState map[int]*FlowSummary `json:\"traffichistory,omitempty\"`\n}\n\n\n\nfunc load(fp string) (StorageState, error) {\n\tf, err := os.Open(fp)\n\tif err != nil {\n\t\treturn StorageState{}, err\n\t}\n\tdefer f.Close()\n\n\tbbuf, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn StorageState{}, errors.New(\"Error: cannot load from file, failed read\")\n\t}\n\n\tss := StorageState{}\n\terr = json.Unmarshal(bbuf, &ss)\n\tif err != nil {\n\t\treturn StorageState{}, errors.New(\"Error on loading state from json\")\n\t}\n\tfmt.Println(\"Loaded state from disk\", fp)\n\treturn ss, nil\n}\n\nfunc saveToFile(ss StorageState, fp string) bool {\n\tb, err := json.Marshal(ss)\n\tif err != nil {\n\t\tfmt.Println(\"Error on dumping state to json:\", err)\n\t\treturn false\n\t}\n\n\tf, err := os.Create(fp)\n\tif err != nil {\n\t\tfmt.Println(\"Error on opening file\", fp, \":\", err)\n\t\treturn false\n\t}\n\tdefer f.Close()\n\n\tw := bufio.NewWriter(f)\n\tn, err := w.Write(b)\n\tif err != nil {\n\t\tfmt.Println(\"Error on writing file\", fp, \":\", err)\n\t\treturn false\n\t}\n\n\tw.Flush()\n\tfmt.Println(\"Wrote history to file in\", n, \"bytes\")\n\treturn true\n}\n\nfunc save(fp string) bool ", "output": "{\n\tHistory.RLock()\n\tTrafficHistory.RLock()\n\tdefer History.RUnlock()\n\tdefer TrafficHistory.RUnlock()\n\tss := StorageState{History.m, TrafficHistory.h}\n\treturn saveToFile(ss, fp)\n}"} {"input": "package tfbparser\n\nimport \"github.com/kiwih/goFB/iec61499\"\n\n\ntype tfbParse struct {\n\tfbs []iec61499.FB\n\n\titems []string\n\titemIndex int\n\n\tcurrentLine int\n\tcurrentFile string\n}\n\n\nfunc (t *tfbParse) getCurrentDebugInfo() iec61499.DebugInfo {\n\treturn iec61499.DebugInfo{\n\t\tSourceLine: t.currentLine,\n\t\tSourceFile: t.currentFile,\n\t}\n}\n\n\n\n\n\n\nfunc (t *tfbParse) pop() string {\n\tif t.done() {\n\t\treturn \"\"\n\t}\n\ts := t.items[t.itemIndex]\n\tt.itemIndex++\n\n\tif s == pNewline {\n\t\tt.currentLine++\n\t\treturn t.pop()\n\t}\n\treturn s\n}\n\n\n\nfunc (t *tfbParse) peek() string {\n\tif t.done() {\n\t\treturn \"\"\n\t}\n\tfor i := 0; i < len(t.items); i++ {\n\t\tif t.items[t.itemIndex+i] != pNewline {\n\t\t\treturn t.items[t.itemIndex+i]\n\t\t}\n\t}\n\treturn \"\"\n}\n\n\nfunc (t *tfbParse) done() bool {\n\treturn t.itemIndex >= len(t.items)\n}\n\n\n\nfunc (t *tfbParse) getFBIndexFromName(name string) int {\n\tfor i := 0; i < len(t.fbs); i++ {\n\t\tif t.fbs[i].Name == name {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (t *tfbParse) isFBNameUnused(name string) bool ", "output": "{\n\tfor i := 0; i < len(t.fbs); i++ {\n\t\tif t.fbs[i].Name == name {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package subject\n\nimport (\n\t\"testing\"\n\t\"reflect\"\n)\n\nfunc TestLoadSubject(t *testing.T) {\n\tpath := \"../../example/subject.csv\"\n\texpect := [][]string{{\"A01\", \"Shibuya Rin\", \"100\"}, {\"A02\", \"\", \"200\"}}\n\n\tres, err := LoadSubject(path)\n\n\tif !(reflect.DeepEqual(res, expect) && err == nil) {\n\t\tt.Errorf(\"Failed to load and parse csv. result: %s, error: %s\", res, err)\n\t}\n}\n\n\n\nfunc TestLoadSubject_ParseError(t *testing.T) {\n\tpath := \"/tmp/\"\n\n\tres, err := LoadSubject(path)\n\n\tif !(res == nil && err != nil) {\n\t\tt.Errorf(\"Failed to raise error properly. result: %s, error: %s\", res, err)\n\t}\n}\n\nfunc TestLoadSubject_LoadError(t *testing.T) ", "output": "{\n\tpath := \"/path/to/nowhere.csv\"\n\n\tres, err := LoadSubject(path)\n\n\tif !(res == nil && err != nil) {\n\t\tt.Errorf(\"Failed to raise error properly. result: %s, error: %s\", res, err)\n\t}\n}"} {"input": "package render\n\nimport (\n\t\"net/http\"\n\t\"encoding/json\"\n)\n\ntype Duration struct{\n\tOverall float32\n\tAverage float32\n}\n\ntype Data struct {\n\tIterations int\n\tDuration Duration\n}\n\n;\n\nfunc SendJson(overallDuration float32, averageDuration float32, iterations int, response http.ResponseWriter) ", "output": "{\n\tduration := Duration{overallDuration, averageDuration};\n\tdata := Data{iterations, duration};\n\tresponse.Header().Set(\"Content-Type\", \"application/json;\");\n\tjson.NewEncoder(response).Encode(data);\n}"} {"input": "package model\n\nimport (\n\t\"github.com/blevesearch/bleve\"\n\t\"github.com/blevesearch/bleve/analysis/analyzers/keyword_analyzer\"\n\t\"github.com/blevesearch/bleve/analysis/analyzers/simple_analyzer\"\n\t\"github.com/blevesearch/bleve/analysis/language/en\"\n)\n\n\n\n\nfunc buildIndexMapping() *bleve.IndexMapping {\n\tsimpleTextFieldMapping := bleve.NewTextFieldMapping()\n\tsimpleTextFieldMapping.Analyzer = simple_analyzer.Name\n\n\tenglishTextFieldMapping := bleve.NewTextFieldMapping()\n\tenglishTextFieldMapping.Analyzer = en.AnalyzerName\n\n\tkeywordFieldMapping := bleve.NewTextFieldMapping()\n\tkeywordFieldMapping.Analyzer = keyword_analyzer.Name\n\n\tstarMapping := bleve.NewDocumentMapping()\n\tstarMapping.AddFieldMappingsAt(\"Name\", simpleTextFieldMapping)\n\tstarMapping.AddFieldMappingsAt(\"FullName\", simpleTextFieldMapping)\n\tstarMapping.AddFieldMappingsAt(\"Description\", englishTextFieldMapping)\n\tstarMapping.AddFieldMappingsAt(\"Language\", keywordFieldMapping)\n\tstarMapping.AddFieldMappingsAt(\"Tags.Name\", keywordFieldMapping)\n\n\tindexMapping := bleve.NewIndexMapping()\n\tindexMapping.AddDocumentMapping(\"Star\", starMapping)\n\n\treturn indexMapping\n}\n\nfunc InitIndex(filepath string) (bleve.Index, error) ", "output": "{\n\tindex, err := bleve.Open(filepath)\n\n\tif err != nil {\n\t\tindex, err = bleve.New(filepath, buildIndexMapping())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn index, nil\n}"} {"input": "package network\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" network/2019-11-01\"\n}"} {"input": "package worker\n\nimport (\n\t\"github.com/gopherjs/gopherjs/js\"\n\t\"github.com/flimzy/goweb/event\"\n)\n\ntype Worker struct {\n\tjs.Object\n\tOnError event.EventHandlerFunc `js:\"onerror\"`\n\tOnMessage event.EventHandlerFunc `js:\"onmessage\"`\n}\n\nfunc New(url string) (w *Worker, e error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\te = r.(*js.Error)\n\t\t}\n\t}()\n\to := js.Global.Get(\"Worker\").New(url)\n\tw = &Worker{Object: *o}\n\treturn\n}\n\nfunc (w *Worker) PostMessage(msg interface{}) {\n\tw.Call(\"postMessage\", msg)\n}\n\n\n\nfunc (w *Worker) Terminate() ", "output": "{\n\tw.Call(\"terminate\")\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"sort\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc mkzosarch(dir, file string) {\n\tvar buf bytes.Buffer\n\tbuf.WriteString(\" auto generated by go tool dist\\n\\n\")\n\tbuf.WriteString(\"package main\\n\\n\")\n\tfmt.Fprintf(&buf, \"var osArchSupportsCgo = %#v\", cgoEnabled)\n\twritefile(buf.String(), file, writeSkipSame)\n}\n\n\n\n\n\n\n\nfunc mkzcgo(dir, file string) {\n\tvar list []string\n\tfor plat, hasCgo := range cgoEnabled {\n\t\tif hasCgo {\n\t\t\tlist = append(list, plat)\n\t\t}\n\t}\n\tsort.Strings(list)\n\n\tvar buf bytes.Buffer\n\n\tfmt.Fprintf(&buf,\n\t\t\" auto generated by go tool dist\\n\"+\n\t\t\t\"\\n\"+\n\t\t\t\"package build\\n\"+\n\t\t\t\"\\n\"+\n\t\t\t\"var cgoEnabled = map[string]bool{\\n\")\n\tfor _, plat := range list {\n\t\tfmt.Fprintf(&buf, \"\\t%q: true,\\n\", plat)\n\t}\n\tfmt.Fprintf(&buf, \"}\")\n\n\twritefile(buf.String(), file, writeSkipSame)\n}\n\nfunc mkzdefaultcc(dir, file string) ", "output": "{\n\tout := fmt.Sprintf(\n\t\t\" auto generated by go tool dist\\n\"+\n\t\t\t\"\\n\"+\n\t\t\t\"package main\\n\"+\n\t\t\t\"\\n\"+\n\t\t\t\"const defaultCC = `%s`\\n\"+\n\t\t\t\"const defaultCXX = `%s`\\n\",\n\t\tdefaultcctarget, defaultcxxtarget)\n\n\twritefile(out, file, writeSkipSame)\n\n\ti := len(file) - len(\"go/zdefaultcc.go\")\n\tfile = file[:i] + \"c\" + file[i:]\n\twritefile(out, file, writeSkipSame)\n}"} {"input": "package cache\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/go-spatial/cobra\"\n)\n\nfunc setupMinMaxZoomFlags(cmd *cobra.Command, min, max uint) {\n\tcmd.Flags().UintVarP(&minZoom, \"min-zoom\", \"\", min, \"min zoom to seed cache from\")\n\tcmd.Flags().UintVarP(&maxZoom, \"max-zoom\", \"\", max, \"max zoom to seed cache to\")\n}\n\n\n\nfunc minMaxZoomValidate(cmd *cobra.Command, args []string) (err error) {\n\tzooms, err = sliceFromRange(minZoom, maxZoom)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid zoom range, %v\", err)\n\t}\n\treturn nil\n}\n\nfunc setupTileNameFormat(cmd *cobra.Command) {\n\tcmd.Flags().StringVarP(&tileListFormat, \"format\", \"\", \"/zxy\", \"4 character string where the first character is a non-numeric delimiter followed by 'z', 'x' and 'y' defining the coordinate order\")\n}\n\nfunc tileNameFormatValidate(cmd *cobra.Command, args []string) (err error) {\n\tformat, err = NewFormat(tileListFormat)\n\treturn err\n}\n\nfunc IsMinMaxZoomExplicit(cmd *cobra.Command) bool ", "output": "{\n\treturn !(cmd.Flag(\"min-zoom\").Changed || cmd.Flag(\"max-zoom\").Changed)\n}"} {"input": "package system\n\nimport (\n\t\"context\"\n\n\t\"github.com/docker/cli/cli\"\n\t\"github.com/docker/cli/cli/command\"\n\t\"github.com/docker/cli/cli/command/formatter\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype diskUsageOptions struct {\n\tverbose bool\n\tformat string\n}\n\n\n\n\nfunc runDiskUsage(dockerCli command.Cli, opts diskUsageOptions) error {\n\tdu, err := dockerCli.Client().DiskUsage(context.Background())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tformat := opts.format\n\tif len(format) == 0 {\n\t\tformat = formatter.TableFormatKey\n\t}\n\n\tvar bsz int64\n\tfor _, bc := range du.BuildCache {\n\t\tif !bc.Shared {\n\t\t\tbsz += bc.Size\n\t\t}\n\t}\n\n\tduCtx := formatter.DiskUsageContext{\n\t\tContext: formatter.Context{\n\t\t\tOutput: dockerCli.Out(),\n\t\t\tFormat: formatter.NewDiskUsageFormat(format, opts.verbose),\n\t\t},\n\t\tLayersSize: du.LayersSize,\n\t\tBuilderSize: bsz,\n\t\tBuildCache: du.BuildCache,\n\t\tImages: du.Images,\n\t\tContainers: du.Containers,\n\t\tVolumes: du.Volumes,\n\t\tVerbose: opts.verbose,\n\t}\n\n\treturn duCtx.Write()\n}\n\nfunc newDiskUsageCommand(dockerCli command.Cli) *cobra.Command ", "output": "{\n\tvar opts diskUsageOptions\n\n\tcmd := &cobra.Command{\n\t\tUse: \"df [OPTIONS]\",\n\t\tShort: \"Show docker disk usage\",\n\t\tArgs: cli.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn runDiskUsage(dockerCli, opts)\n\t\t},\n\t\tAnnotations: map[string]string{\"version\": \"1.25\"},\n\t}\n\n\tflags := cmd.Flags()\n\n\tflags.BoolVarP(&opts.verbose, \"verbose\", \"v\", false, \"Show detailed information on space usage\")\n\tflags.StringVar(&opts.format, \"format\", \"\", \"Pretty-print images using a Go template\")\n\n\treturn cmd\n}"} {"input": "package httpfs\n\nimport (\n\t\"net/http\"\n)\n\n\n\n\n\nfunc header_get(h http.Header, key string) string ", "output": "{\n\tif v := h[key]; len(v) > 0 {\n\t\treturn v[0]\n\t}\n\treturn \"\"\n}"} {"input": "package flog\n\nimport \"github.com/Sirupsen/logrus\"\n\ntype Parameter interface {\n\tConvert() map[string]interface{}\n}\n\ntype Fields struct {\n\tEvent string\n\tError error\n}\n\nfunc (f Fields) Convert() map[string]interface{} {\n\tfields := map[string]interface{}{}\n\n\tif f.Event != \"\" {\n\t\tfields[\"event\"] = f.Event\n\t}\n\n\tif f.Error != nil {\n\t\tfields[\"error\"] = f.Error\n\t}\n\n\treturn fields\n}\n\ntype Details map[string]interface{}\n\nfunc (d Details) Convert() map[string]interface{} {\n\treturn d\n}\n\ntype DebugFields map[string]interface{}\n\nfunc (d DebugFields) Convert() map[string]interface{} {\n\treturn map[string]interface{}{}\n}\n\nfunc transform(params []Parameter) logrus.Fields {\n\tlogrusFields := logrus.Fields{}\n\n\tfor _, p := range params {\n\t\tfieldMap := p.Convert()\n\n\t\tfor k, v := range fieldMap {\n\t\t\tlogrusFields[k] = v\n\t\t}\n\t}\n\n\treturn logrusFields\n}\n\nfunc Debug(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Debug(msg)\n}\n\nfunc Info(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Info(msg)\n}\n\nfunc Warn(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Warning(msg)\n}\n\nfunc Error(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Error(msg)\n}\n\nfunc Fatal(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Fatal(msg)\n}\n\n\n\nfunc Panic(msg string, params ...Parameter) ", "output": "{\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Panic(msg)\n}"} {"input": "package user\n\n\n\n\ntype User struct {\n\tid int\n\tusername string\n\tpassword string\n\tfirstname string\n\tlastname string\n\trole string\n}\n\nfunc (u User) Id() int {\n\treturn u.id\n}\n\nfunc (u User) Username() string {\n\treturn u.username\n}\n\nfunc (u User) Password() string {\n\treturn u.password\n}\n\nfunc (u User) Firstname() string {\n\treturn u.firstname\n}\n\nfunc (u User) Lastname() string {\n\treturn u.lastname\n}\n\nfunc (u User) Role() string {\n\treturn u.role\n}\n\nfunc New(id int, username, password, firstname, lastname, role string) User ", "output": "{\n\treturn User{id, username, password, firstname, lastname, role}\n}"} {"input": "package protocol\n\n\ntype LogoutRequestMessageData struct {\n}\n\n\ntype LogoutRequestMessage struct {\n\tBaseMessage\n\tData LogoutRequestMessageData `json:\"data\"`\n}\n\n\nfunc NewLogoutRequesMessage(session string) *LogoutRequestMessage {\n\tmessage := LogoutRequestMessage{}\n\tmessage.Type = LogoutRequestMessageType\n\tmessage.Session = session\n\treturn &message\n}\n\n\nfunc (m *LogoutRequestMessage) GetType() string {\n\treturn m.Type\n}\n\n\n\n\n\nfunc (m *LogoutRequestMessage) GetData() interface{} {\n\treturn m.Data\n}\n\n\nfunc (m *LogoutRequestMessage) SetSession(session string) {\n\tm.BaseMessage.Session = session\n}\n\nfunc (m *LogoutRequestMessage) GetSession() string ", "output": "{\n\treturn m.Session\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Abser interface {\n\tAbs() float64\n}\n\nfunc main() {\n\tvar a Abser\n\tf := MyFloat(-math.Sqrt2)\n\tv := Vertex{3, 4}\n\n\ta = f \n\ta = &v \n\n\ta = v\n\n\tfmt.Println(a.Abs())\n}\n\ntype MyFloat float64\n\nfunc (f MyFloat) Abs() float64 {\n\tif f < 0 {\n\t\treturn float64(-f)\n\t}\n\treturn float64(f)\n}\n\ntype Vertex struct {\n\tX, Y float64\n}\n\n\n\nfunc (v *Vertex) Abs() float64 ", "output": "{\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}"} {"input": "package oglematchers\n\n\n\n\n\n\n\n\n\ntype Matcher interface {\n\tMatches(candidate interface{}) error\n\n\tDescription() string\n}\n\n\n\n\n\n\n\n\n\n\n\ntype FatalError struct {\n\terrorText string\n}\n\n\nfunc NewFatalError(s string) *FatalError {\n\treturn &FatalError{s}\n}\n\n\n\nfunc (e *FatalError) Error() string ", "output": "{\n\treturn e.errorText\n}"} {"input": "package event\n\nimport (\n\t\"fmt\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\n\ntype Increment struct {\n\tName string\n\tValue int64\n}\n\nfunc (e *Increment) StatClass() string {\n\treturn \"counter\"\n}\n\n\nfunc (e *Increment) Update(e2 Event) error {\n\tif e.Type() != e2.Type() {\n\t\treturn fmt.Errorf(\"statsd event type conflict: %s vs %s \", e.String(), e2.String())\n\t}\n\tatomic.AddInt64(&e.Value, e2.Payload().(int64))\n\treturn nil\n}\n\n\nfunc (e *Increment) Reset() {\n\te.Value = 0\n}\n\n\n\n\n\nfunc (e Increment) Stats(tick time.Duration) []string {\n\treturn []string{fmt.Sprintf(\"%s:%d|c\", e.Name, e.Value)}\n}\n\n\nfunc (e Increment) Key() string {\n\treturn e.Name\n}\n\n\nfunc (e *Increment) SetKey(key string) {\n\te.Name = key\n}\n\n\nfunc (e Increment) Type() int {\n\treturn EventIncr\n}\n\n\nfunc (e Increment) TypeString() string {\n\treturn \"Increment\"\n}\n\n\nfunc (e Increment) String() string {\n\treturn fmt.Sprintf(\"{Type: %s, Key: %s, Value: %d}\", e.TypeString(), e.Name, e.Value)\n}\n\nfunc (e Increment) Payload() interface{} ", "output": "{\n\treturn e.Value\n}"} {"input": "package balancers\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\n\ntype Connection interface {\n\tURL() *url.URL\n\tIsBroken() bool\n}\n\n\n\n\ntype HttpConnection struct {\n\tsync.Mutex\n\turl *url.URL\n\tbroken bool\n\theartbeatDuration time.Duration\n\theartbeatStop chan bool\n}\n\n\nfunc NewHttpConnection(url *url.URL) *HttpConnection {\n\tc := &HttpConnection{\n\t\turl: url,\n\t\theartbeatDuration: DefaultHeartbeatDuration,\n\t\theartbeatStop: make(chan bool),\n\t}\n\tc.checkBroken()\n\tgo c.heartbeat()\n\treturn c\n}\n\n\nfunc (c *HttpConnection) Close() error {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.heartbeatStop <- true \n\tc.broken = false\n\treturn nil\n}\n\n\nfunc (c *HttpConnection) HeartbeatDuration(d time.Duration) *HttpConnection {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.heartbeatStop <- true \n\tc.broken = false\n\tc.heartbeatDuration = d\n\tgo c.heartbeat()\n\treturn c\n}\n\n\nfunc (c *HttpConnection) heartbeat() {\n\tticker := time.NewTicker(c.heartbeatDuration)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tc.checkBroken()\n\t\tcase <-c.heartbeatStop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\n\n\nfunc (c *HttpConnection) URL() *url.URL {\n\treturn c.url\n}\n\n\nfunc (c *HttpConnection) IsBroken() bool {\n\treturn c.broken\n}\n\nfunc (c *HttpConnection) checkBroken() ", "output": "{\n\tc.Lock()\n\tdefer c.Unlock()\n\n\treq, err := http.NewRequest(\"GET\", c.url.String(), nil)\n\tif err != nil {\n\t\tc.broken = true\n\t\treturn\n\t}\n\treq.Header.Add(\"User-Agent\", UserAgent)\n\n\tcl := &http.Client{Timeout: 5 * time.Second}\n\tres, err := cl.Do(req)\n\tif err == nil {\n\t\tdefer res.Body.Close()\n\t\tif res.StatusCode == http.StatusOK {\n\t\t\tc.broken = false\n\t\t} else {\n\t\t\tc.broken = true\n\t\t}\n\t} else {\n\t\tc.broken = true\n\t}\n}"} {"input": "package iso20022\n\n\ntype AutomatedTellerMachine6 struct {\n\n\tIdentification *Max35Text `xml:\"Id\"`\n\n\tAdditionalIdentification *Max35Text `xml:\"AddtlId,omitempty\"`\n\n\tSequenceNumber *Max35Text `xml:\"SeqNb,omitempty\"`\n\n\tLocation *PostalAddress17 `xml:\"Lctn,omitempty\"`\n\n\tLocationCategory *TransactionEnvironment2Code `xml:\"LctnCtgy,omitempty\"`\n\n\tEquipment *ATMEquipment1 `xml:\"Eqpmnt,omitempty\"`\n}\n\nfunc (a *AutomatedTellerMachine6) SetIdentification(value string) {\n\ta.Identification = (*Max35Text)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) SetAdditionalIdentification(value string) {\n\ta.AdditionalIdentification = (*Max35Text)(&value)\n}\n\n\n\nfunc (a *AutomatedTellerMachine6) AddLocation() *PostalAddress17 {\n\ta.Location = new(PostalAddress17)\n\treturn a.Location\n}\n\nfunc (a *AutomatedTellerMachine6) SetLocationCategory(value string) {\n\ta.LocationCategory = (*TransactionEnvironment2Code)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) AddEquipment() *ATMEquipment1 {\n\ta.Equipment = new(ATMEquipment1)\n\treturn a.Equipment\n}\n\nfunc (a *AutomatedTellerMachine6) SetSequenceNumber(value string) ", "output": "{\n\ta.SequenceNumber = (*Max35Text)(&value)\n}"} {"input": "package slack\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n)\n\n\n\n\n\n\n\ntype backoff struct {\n\tattempts int\n\tInitial time.Duration\n\tJitter time.Duration\n\tMax time.Duration\n}\n\n\n\n\n\n\nfunc (b *backoff) Reset() {\n\tb.attempts = 0\n}\n\nfunc (b *backoff) Duration() (dur time.Duration) ", "output": "{\n\tif b.Max == 0 {\n\t\tb.Max = 10 * time.Second\n\t}\n\n\tif b.Initial == 0 {\n\t\tb.Initial = 100 * time.Millisecond\n\t}\n\n\tif dur = time.Duration(1 << uint(b.attempts)); dur > 0 {\n\t\tdur = dur * b.Initial\n\t} else {\n\t\tdur = b.Max\n\t}\n\n\tif b.Jitter > 0 {\n\t\tdur = dur + time.Duration(rand.Intn(int(b.Jitter)))\n\t}\n\n\tb.attempts++\n\n\treturn dur\n}"} {"input": "package main\n\nimport (\n\t\"go/ast\"\n)\n\n\n\nvar fiximportFix = fix{\n\t\"fiximport\",\n\t\"2013-07-21\", \n\tfiximport,\n\t`\n Fix import statements to match the new canonical import path.\n`,\n}\n\nfunc fiximport(f *ast.File) bool {\n\tspec := importSpec(f, \"example.com/mypkg\")\n\tif spec == nil {\n\t\treturn false\n\t}\n\tspec.Path.Value = \"\\\"example.com/mypkg2\\\"\"\n\treturn true\n}\n\nfunc init() ", "output": "{\n\tregister(fiximportFix)\n}"} {"input": "package demopgx\n\nimport (\n\t\"math/big\"\n)\n\n\n\n\n\n\n\ntype User struct {\n\tUid int64 `sql:\"pk: true, auto: true\"`\n\tName string `sql:\"unique: user_login\"`\n\tEmailAddress string `sql:\"nk: true\"`\n\tAddressId *int64 `sql:\"fk: addresses.id, onupdate: restrict, ondelete: restrict\"`\n\tAvatar *string\n\tRole *Role `sql:\"type: text, size: 20\"`\n\tActive bool\n\tAdmin bool\n\tFave *big.Int `sql:\"encode: json\"`\n\tLastUpdated int64\n\n\tNumbers Numbers\n\n\ttoken string\n\tsecret string\n\n\thash string `sql:\"-\"`\n}\n\ntype Numbers struct {\n\tI8 int8 `sql:\"default: -8\"`\n\tU8 uint8 `sql:\"default: 8\"`\n\tI16 int16 `sql:\"default: -16\"`\n\tU16 uint16 `sql:\"default: 16\"`\n\tI32 int32 `sql:\"default: -32\"`\n\tU32 uint32 `sql:\"default: 32\"`\n\tI64 int64 `sql:\"default: -64\"`\n\tU64 uint64 `sql:\"default: 64\"`\n\tF32 float32 `sql:\"default: 3.2\"`\n\tF64 float64 `sql:\"default: 6.4\"`\n}\n\n\nfunc (u *User) PreInsert() error {\n\tu.hash = \"PreInsert\"\n\treturn nil\n}\n\n\n\nfunc (u *User) PostGet() error {\n\tu.hash = \"PostGet\"\n\treturn nil\n}\n\nfunc (u *User) PreUpdate() error ", "output": "{\n\tu.hash = \"PreUpdate\"\n\treturn nil\n}"} {"input": "package command\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/mitchellh/cli\"\n\t\"github.com/pragkent/aliyun-disk/volume\"\n)\n\n\nfunc TestUnmountCommand_Run(t *testing.T) {\n\tvar bu bytes.Buffer\n\tui := &cli.BasicUi{\n\t\tWriter: &bu,\n\t}\n\n\tmeta := &Meta{\n\t\tUi: ui,\n\t\tDriver: volume.NewFakeDriver(),\n\t}\n\n\tcmd := &UnmountCommand{*meta}\n\n\ttests := []struct {\n\t\targs []string\n\t\tresult int\n\t\tstatus volume.DriverStatus\n\t}{\n\t\t{\n\t\t\t[]string{\"/mnt/xx\"},\n\t\t\t1,\n\t\t\tvolume.DriverStatus{\n\t\t\t\tStatus: volume.StatusNotSupported,\n\t\t\t\tMessage: \"command not supported\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tbu.Reset()\n\n\t\tif result := cmd.Run(tt.args); result != tt.result {\n\t\t\tt.Errorf(\"cmd.Run() == %d; want %d\", result, tt.result)\n\t\t}\n\n\t\tvar ds volume.DriverStatus\n\t\tif err := json.Unmarshal(bu.Bytes(), &ds); err != nil {\n\t\t\tt.Errorf(\"json.Unmarshal error. %v\", err)\n\t\t}\n\n\t\tif !reflect.DeepEqual(ds, tt.status) {\n\t\t\tt.Errorf(\"Status = %#v; want %#v\", ds, tt.status)\n\t\t}\n\t}\n}\n\nfunc TestUnmountCommand_Run_ArgsError(t *testing.T) ", "output": "{\n\tui := &cli.BasicUi{}\n\n\tmeta := &Meta{\n\t\tUi: ui,\n\t\tDriver: volume.NewFakeDriver(),\n\t}\n\n\tcmd := &UnmountCommand{*meta}\n\n\ttests := []struct {\n\t\targs []string\n\t\tresult int\n\t}{\n\t\t{[]string{}, cli.RunResultHelp},\n\t}\n\n\tfor _, tt := range tests {\n\t\tif result := cmd.Run(tt.args); result != tt.result {\n\t\t\tt.Errorf(\"cmd.Run() == %d; want %d\", result, tt.result)\n\t\t}\n\t}\n\n}"} {"input": "package v1\n\nimport (\n\tv1 \"github.com/openshift/api/console/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype ConsoleYAMLSampleLister interface {\n\tList(selector labels.Selector) (ret []*v1.ConsoleYAMLSample, err error)\n\tGet(name string) (*v1.ConsoleYAMLSample, error)\n\tConsoleYAMLSampleListerExpansion\n}\n\n\ntype consoleYAMLSampleLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewConsoleYAMLSampleLister(indexer cache.Indexer) ConsoleYAMLSampleLister {\n\treturn &consoleYAMLSampleLister{indexer: indexer}\n}\n\n\n\n\n\nfunc (s *consoleYAMLSampleLister) Get(name string) (*v1.ConsoleYAMLSample, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"consoleyamlsample\"), name)\n\t}\n\treturn obj.(*v1.ConsoleYAMLSample), nil\n}\n\nfunc (s *consoleYAMLSampleLister) List(selector labels.Selector) (ret []*v1.ConsoleYAMLSample, err error) ", "output": "{\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ConsoleYAMLSample))\n\t})\n\treturn ret, err\n}"} {"input": "package wml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/wml\"\n)\n\nfunc TestWdCT_WrapTightConstructor(t *testing.T) {\n\tv := wml.NewWdCT_WrapTight()\n\tif v == nil {\n\t\tt.Errorf(\"wml.NewWdCT_WrapTight must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed wml.WdCT_WrapTight should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestWdCT_WrapTightMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := wml.NewWdCT_WrapTight()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := wml.NewWdCT_WrapTight()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package gtka\n\nimport (\n\t\"github.com/gotk3/gotk3/gtk\"\n\t\"github.com/coyim/gotk3adapter/gliba\"\n\t\"github.com/coyim/gotk3adapter/gtki\"\n)\n\ntype application struct {\n\t*gliba.Application\n\tinternal *gtk.Application\n}\n\nfunc wrapApplicationSimple(v *gtk.Application) *application {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn &application{gliba.WrapApplicationSimple(&v.Application), v}\n}\n\nfunc wrapApplication(v *gtk.Application, e error) (*application, error) {\n\treturn wrapApplicationSimple(v), e\n}\n\n\n\nfunc (v *application) GetActiveWindow() gtki.Window {\n\tret := wrapWindowSimple(v.internal.GetActiveWindow())\n\tif ret == nil {\n\t\treturn nil\n\t}\n\treturn ret\n}\n\nfunc unwrapApplication(v gtki.Application) *gtk.Application ", "output": "{\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*application).internal\n}"} {"input": "package toolbox_test\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/viant/toolbox\"\n)\n\n\n\nfunc TestMarshalEncoderFactory(t *testing.T) {\n\tbuffer := new(bytes.Buffer)\n\tencoder := toolbox.NewMarshalerEncoderFactory().Create(buffer)\n\tfoo := &Foo200{\"abc\"}\n\terr := encoder.Encode(foo)\n\tassert.Nil(t, err)\n\tassert.Equal(t, \"abc\", string(buffer.Bytes()))\n\terr = encoder.Encode(&Foo201{})\n\tassert.NotNil(t, err)\n}\n\ntype Foo200 struct {\n\tAttr string\n}\n\nfunc (m *Foo200) Marshal() ([]byte, error) {\n\treturn []byte(m.Attr), nil\n}\n\ntype Foo201 struct {\n\tAttr string\n}\n\nfunc TestEncoderFactory(t *testing.T) ", "output": "{\n\tbuffer := new(bytes.Buffer)\n\tassert.NotNil(t, toolbox.NewJSONEncoderFactory().Create(buffer))\n}"} {"input": "package mock_concurrent\n\nimport (\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n)\n\n\ntype MockMath struct {\n\tctrl *gomock.Controller\n\trecorder *MockMathMockRecorder\n}\n\n\ntype MockMathMockRecorder struct {\n\tmock *MockMath\n}\n\n\n\n\n\nfunc (m *MockMath) EXPECT() *MockMathMockRecorder {\n\treturn m.recorder\n}\n\n\nfunc (m *MockMath) Sum(arg0, arg1 int) int {\n\tret := m.ctrl.Call(m, \"Sum\", arg0, arg1)\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}\n\n\nfunc (mr *MockMathMockRecorder) Sum(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Sum\", reflect.TypeOf((*MockMath)(nil).Sum), arg0, arg1)\n}\n\nfunc NewMockMath(ctrl *gomock.Controller) *MockMath ", "output": "{\n\tmock := &MockMath{ctrl: ctrl}\n\tmock.recorder = &MockMathMockRecorder{mock}\n\treturn mock\n}"} {"input": "package gull\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype Up struct {\n\tEnvironment string\n\tSourceDirectory string\n\tMigrateTarget MigrationTarget\n\tMigrations *Migrations\n}\n\n\n\nfunc (u *Up) Migrate() error {\n\terr := u.Ingest()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif u.MigrateTarget.IsPerformingFullMigration() {\n\t\tu.MigrateTarget.GetLogger().Info(\"Deleting configuration for [%v]/[%v]\", u.MigrateTarget.GetApplication(), u.MigrateTarget.GetEnvironment())\n\t\t_ = u.MigrateTarget.DeleteEnvironment()\n\t}\n\treturn u.Migrations.Apply(u.MigrateTarget)\n}\n\nfunc (u *Up) Ingest() error {\n\treturn filepath.Walk(u.SourceDirectory, u.IngestFile)\n}\n\nfunc (u *Up) IngestFile(path string, f os.FileInfo, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !f.IsDir() {\n\t\tmigration, err := NewMigrationFromGullFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = u.Migrations.Add(migration)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc NewUp(source string, target MigrationTarget) *Up ", "output": "{\n\treturn &Up{\n\t\tEnvironment: target.GetEnvironment(),\n\t\tMigrateTarget: target,\n\t\tSourceDirectory: source,\n\t\tMigrations: NewMigrations(),\n\t}\n}"} {"input": "func IPv6() (*JSONIP, error) {\n\treturn fetch(ipv6Endpoint)\n}\n\n\n\n\nfunc fetch(target string) (*JSONIP, error) ", "output": "{\n\tresp, err := http.Get(target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar ip *JSONIP\n\terr = json.NewDecoder(resp.Body).Decode(&ip)\n\treturn ip, err\n}"} {"input": "package models\n\nimport (\n\t\"koding/db/mongodb/modelhelper\"\n\t\"net\"\n\t\"socialapi/config\"\n\t\"socialapi/request\"\n\n\t\"github.com/koding/logging\"\n)\n\n\ntype Client struct {\n\tAccount *Account\n\n\tIP net.IP\n\n\tSessionID string\n}\n\n\ntype Context struct {\n\tGroupName string\n\tClient *Client\n\tlog logging.Logger\n}\n\n\nfunc NewContext(log logging.Logger) *Context {\n\treturn &Context{\n\t\tlog: log,\n\t}\n}\n\n\nfunc (c *Context) OverrideQuery(q *request.Query) *request.Query {\n\tq.GroupName = c.GroupName\n\tif c.IsLoggedIn() {\n\t\tq.AccountId = c.Client.Account.Id\n\t} else {\n\t\tq.AccountId = 0\n\t}\n\n\treturn q\n}\n\n\nfunc (c *Context) IsLoggedIn() bool {\n\tif c.Client == nil {\n\t\treturn false\n\t}\n\n\tif c.Client.Account == nil {\n\t\treturn false\n\t}\n\n\tif c.Client.Account.Id == 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\n\n\nfunc (c *Context) IsAdmin() bool {\n\tif !c.IsLoggedIn() {\n\t\treturn false\n\t}\n\n\tsuperAdmins := config.MustGet().DummyAdmins\n\treturn IsIn(c.Client.Account.Nick, superAdmins...)\n}\n\n\n\n\n\n\n\nfunc (c *Context) MustGetLogger() logging.Logger {\n\tif c.log == nil {\n\t\tpanic(ErrLoggerNotExist)\n\t}\n\n\treturn c.log\n}\n\nfunc (c *Context) CanManage() error ", "output": "{\n\tif !c.IsLoggedIn() {\n\t\treturn ErrNotLoggedIn\n\t}\n\n\tcanManage, err := modelhelper.CanManage(c.Client.Account.Nick, c.GroupName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !canManage {\n\t\treturn ErrCannotManageGroup\n\t}\n\n\treturn nil\n}"} {"input": "package metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/collector/model/pdata\"\n)\n\nfunc TestNewMetricDataType(t *testing.T) {\n\tmetricDataType := NewMetricDataType(pdata.MetricDataTypeGauge, pdata.MetricAggregationTemporalityDelta, true)\n\n\trequire.NotNil(t, metricDataType)\n\tassert.Equal(t, metricDataType.MetricDataType(), pdata.MetricDataTypeGauge)\n\tassert.Equal(t, metricDataType.AggregationTemporality(), pdata.MetricAggregationTemporalityDelta)\n\tassert.True(t, metricDataType.IsMonotonic())\n}\n\n\n\nfunc TestMetricValueDataType_AggregationTemporality(t *testing.T) {\n\tvalueDataType := metricValueDataType{aggregationTemporality: pdata.MetricAggregationTemporalityDelta}\n\n\tassert.Equal(t, valueDataType.AggregationTemporality(), pdata.MetricAggregationTemporalityDelta)\n}\n\nfunc TestMetricValueDataType_IsMonotonic(t *testing.T) {\n\tvalueDataType := metricValueDataType{isMonotonic: true}\n\n\tassert.True(t, valueDataType.IsMonotonic())\n}\n\nfunc TestMetricValueDataType_MetricDataType(t *testing.T) ", "output": "{\n\tvalueDataType := metricValueDataType{dataType: pdata.MetricDataTypeGauge}\n\n\tassert.Equal(t, valueDataType.MetricDataType(), pdata.MetricDataTypeGauge)\n}"} {"input": "package component\n\nimport (\n\t\"time\"\n\n\t\"github.com/spf13/viper\"\n)\n\n\ntype Config struct {\n\tAuthServers map[string]string\n\tKeyDir string\n\tStatusInterval time.Duration\n\tUseTLS bool\n}\n\n\n\n\nfunc ConfigFromViper() Config ", "output": "{\n\treturn Config{\n\t\tAuthServers: viper.GetStringMapString(\"auth-servers\"),\n\t\tKeyDir: viper.GetString(\"key-dir\"),\n\t\tStatusInterval: viper.GetDuration(\"monitor-interval\"),\n\t\tUseTLS: viper.GetBool(\"tls\"),\n\t}\n}"} {"input": "package native\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\n\t\"github.com/docker/docker/pkg/reexec\"\n\t\"github.com/docker/libcontainer\"\n)\n\n\n\nfunc fatal(err error) {\n\tif lerr, ok := err.(libcontainer.Error); ok {\n\t\tlerr.Detail(os.Stderr)\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Fprintln(os.Stderr, err)\n\tos.Exit(1)\n}\n\nfunc initializer() {\n\truntime.GOMAXPROCS(1)\n\truntime.LockOSThread()\n\tfactory, err := libcontainer.New(\"\")\n\tif err != nil {\n\t\tfatal(err)\n\t}\n\tif err := factory.StartInitialization(); err != nil {\n\t\tfatal(err)\n\t}\n\n\tpanic(\"unreachable\")\n}\n\nfunc writeError(err error) {\n\tfmt.Fprint(os.Stderr, err)\n\tos.Exit(1)\n}\n\nfunc init() ", "output": "{\n\treexec.Register(DriverName, initializer)\n}"} {"input": "package filesystem\n\nimport (\n\tkeystore2 \"github.com/cossacklabs/acra/keystore\"\n)\n\nfunc getSymmetricKeyName(id string) string {\n\treturn id + `_sym`\n}\n\nfunc getTokenSymmetricKeyName(id []byte, ownerType keystore2.KeyOwnerType) string {\n\tvar name string\n\tswitch ownerType {\n\tcase keystore2.KeyOwnerTypeClient:\n\t\tname = getClientIDSymmetricKeyName(id)\n\tcase keystore2.KeyOwnerTypeZone:\n\t\tname = getZoneIDSymmetricKeyName(id)\n\tdefault:\n\t\tname = string(id)\n\t}\n\treturn name + \".token\"\n}\n\n\n\nfunc getZoneIDSymmetricKeyName(id []byte) string {\n\treturn getSymmetricKeyName(GetZoneKeyFilename(id))\n}\n\nfunc getClientIDSymmetricKeyName(id []byte) string ", "output": "{\n\treturn getSymmetricKeyName(GetServerDecryptionKeyFilename(id))\n}"} {"input": "package lib\n\nimport (\n\t\"fmt\"\n)\n\ntype Foo struct {\n\tBar\n}\n\ntype Bar struct{}\n\n\n\nfunc (b *Bar) Wibble() error {\n\treturn fmt.Errorf(\"Not Mocked!\")\n}\n\nfunc NewFoo() *Foo ", "output": "{\n\treturn &Foo{}\n}"} {"input": "package minio\n\n\n\nvar awsS3EndpointMap = map[string]string{\n\t\"us-east-1\": \"s3.amazonaws.com\",\n\t\"us-west-2\": \"s3-us-west-2.amazonaws.com\",\n\t\"us-west-1\": \"s3-us-west-1.amazonaws.com\",\n\t\"eu-west-1\": \"s3-eu-west-1.amazonaws.com\",\n\t\"eu-central-1\": \"s3-eu-central-1.amazonaws.com\",\n\t\"ap-south-1\": \"s3-ap-south-1.amazonaws.com\",\n\t\"ap-southeast-1\": \"s3-ap-southeast-1.amazonaws.com\",\n\t\"ap-southeast-2\": \"s3-ap-southeast-2.amazonaws.com\",\n\t\"ap-northeast-1\": \"s3-ap-northeast-1.amazonaws.com\",\n\t\"ap-northeast-2\": \"s3-ap-northeast-2.amazonaws.com\",\n\t\"sa-east-1\": \"s3-sa-east-1.amazonaws.com\",\n\t\"cn-north-1\": \"s3.cn-north-1.amazonaws.com.cn\",\n}\n\n\n\n\nfunc getS3Endpoint(bucketLocation string) (s3Endpoint string) ", "output": "{\n\ts3Endpoint, ok := awsS3EndpointMap[bucketLocation]\n\tif !ok {\n\t\ts3Endpoint = \"s3.amazonaws.com\"\n\t}\n\treturn s3Endpoint\n}"} {"input": "package libvirt\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/mitchellh/multistep\"\n\t\"github.com/mitchellh/packer/packer\"\n\t\"github.com/vtolstov/libvirt-go\"\n)\n\ntype stepCreateNetwork struct{}\n\nfunc (stepCreateNetwork) Run(state multistep.StateBag) multistep.StepAction {\n\tconfig := state.Get(\"config\").(*Config)\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\tif config.NetworkType == \"user\" {\n\t\treturn multistep.ActionContinue\n\t}\n\n\tvar lvn libvirt.VirNetwork\n\tlv, err := libvirt.NewVirConnection(config.LibvirtUrl)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"Error connecting to libvirt: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\tdefer lv.CloseConnection()\n\tif lvn, err = lv.LookupNetworkByName(config.NetworkName); err != nil {\n\t\tlvn, err = lv.NetworkDefineXML(config.NetworkXml)\n\t\tif err != nil {\n\t\t\terr := fmt.Errorf(\"Error defining network: %s\", err)\n\t\t\tstate.Put(\"error\", err)\n\t\t\tui.Error(err.Error())\n\t\t\treturn multistep.ActionHalt\n\t\t}\n\t}\n\tdefer lvn.Free()\n\tif ok, err := lvn.IsActive(); !ok && err == nil {\n\t\terr = lvn.Create()\n\t\tif err != nil {\n\t\t\terr := fmt.Errorf(\"Error creating network: %s\", err)\n\t\t\tstate.Put(\"error\", err)\n\t\t\tui.Error(err.Error())\n\t\t\treturn multistep.ActionHalt\n\t\t}\n\t}\n\treturn multistep.ActionContinue\n}\n\n\n\nfunc (stepCreateNetwork) Cleanup(state multistep.StateBag) ", "output": "{\n\tconfig := state.Get(\"config\").(*Config)\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\tif config.NetworkType == \"user\" {\n\t\treturn\n\t}\n\n\tlv, err := libvirt.NewVirConnection(config.LibvirtUrl)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"Error connecting to libvirt: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn\n\t}\n\n\tif lvn, err := lv.LookupNetworkByName(config.NetworkName); err == nil {\n\t\tdefer lvn.Free()\n\t\tif ok, err := lvn.IsActive(); !ok && err == nil {\n\t\t\terr = lvn.Destroy()\n\t\t\tif err != nil {\n\t\t\t\tui.Error(fmt.Sprintf(\"Error destroying network: %s\", err))\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package source\nimport \"fmt\"\n\n\n\nfunc Values() ", "output": "{\n\n\tfmt.Println(\"go\" + \"lang\")\n\n\tfmt.Println(\"1+1 =\", 1+1)\n\tfmt.Println(\"7.0/3.0 =\", 7.0/3.0)\n\n\tfmt.Println(true && false)\n\tfmt.Println(true || false)\n\tfmt.Println(!true)\n\n}"} {"input": "package tests\n\nimport (\n\t\"testing\"\n\n\t\"github.com/expanse-org/go-expanse/params\"\n)\n\n\n\nfunc TestTransaction(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\ttxt := new(testMatcher)\n\ttxt.skipLoad(\"^ttWrongRLP/.*\")\n\ttxt.skipLoad(\"^ttGasLimit/TransactionWithGasLimitxPriceOverflow.json\")\n\ttxt.skipLoad(\".*TransactionWithGasPriceOverflow.*\")\n\n\ttxt.skipLoad(\"^ttNonce/TransactionWithHighNonce256.json\")\n\n\ttxt.skipLoad(\"^ttValue/TransactionWithHighValueOverflow.json\")\n\ttxt.walk(t, transactionTestDir, func(t *testing.T, name string, test *TransactionTest) {\n\t\tcfg := params.MainnetChainConfig\n\t\tif err := txt.checkFailure(t, name, test.Run(cfg)); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t})\n}"} {"input": "package server\n\nimport (\n\t\"context\"\n\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n)\n\n\n\nfunc (s *Service) EjectCDROMWithContext(ctx context.Context, req *EjectCDROMRequest) error {\n\tif err := req.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tclient := sacloud.NewServerOp(s.caller)\n\tserver, err := client.Read(ctx, req.Zone, req.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif server.CDROMID.IsEmpty() {\n\t\treturn nil \n\t}\n\n\treturn client.EjectCDROM(ctx, req.Zone, req.ID, &sacloud.EjectCDROMRequest{ID: server.CDROMID})\n}\n\nfunc (s *Service) EjectCDROM(req *EjectCDROMRequest) error ", "output": "{\n\treturn s.EjectCDROMWithContext(context.Background(), req)\n}"} {"input": "package subscribe\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"testing\"\n\n\t\"github.com/drausin/libri/libri/librarian/api\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestToFromAPI(t *testing.T) {\n\trng := rand.New(rand.NewSource(0))\n\tf1 := newFilter([][]byte{}, 0.75, rng)\n\ta, err := ToAPI(f1)\n\tassert.Nil(t, err)\n\tf2, err := FromAPI(a)\n\tassert.Nil(t, err)\n\tassert.Equal(t, f1, f2)\n}\n\nfunc TestFromAPI_err(t *testing.T) {\n\tf, err := FromAPI(&api.BloomFilter{Encoded: []byte{}})\n\tassert.NotNil(t, err)\n\tassert.Nil(t, f)\n}\n\n\n\n\n\nfunc TestAlwaysInFilter(t *testing.T) {\n\trng := rand.New(rand.NewSource(0))\n\tf := alwaysInFilter()\n\tfor c := 0; c < 10000; c++ {\n\t\tin := f.Test(api.RandBytes(rng, api.ECPubKeyLength))\n\t\tassert.True(t, in)\n\t}\n}\n\nfunc TestNewFPFilter(t *testing.T) ", "output": "{\n\trng := rand.New(rand.NewSource(0))\n\tnTrials := 100000\n\n\ttolerance := 0.05\n\tfor _, targetFP := range []float64{0.3, 0.5, 0.75, 0.9, 1.0} {\n\t\tfilter := newFilter([][]byte{}, targetFP, rng)\n\n\t\tfpCount := 0\n\t\tfor c := 0; c < nTrials; c++ {\n\t\t\tif filter.Test(api.RandBytes(rng, api.ECPubKeyLength)) {\n\t\t\t\tfpCount++\n\t\t\t}\n\t\t}\n\t\tmeasuredFP := float64(fpCount) / float64(nTrials)\n\t\tinfo := fmt.Sprintf(\"target fp: %f, measured fp: %f\", targetFP, measuredFP)\n\t\tassert.True(t, measuredFP >= targetFP-tolerance, info)\n\t}\n\n}"} {"input": "package volume\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"time\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/resource\"\n\t\"k8s.io/kubernetes/pkg/util/mount\"\n)\n\n\n\ntype Volume interface {\n\tGetPath() string\n\n\tMetricsProvider\n}\n\n\n\ntype MetricsProvider interface {\n\tGetMetrics() (*Metrics, error)\n}\n\n\ntype Metrics struct {\n\tUsed *resource.Quantity\n\n\tCapacity *resource.Quantity\n\n\tAvailable *resource.Quantity\n}\n\n\ntype Attributes struct {\n\tReadOnly bool\n\tManaged bool\n\tSupportsSELinux bool\n}\n\n\ntype Mounter interface {\n\tVolume\n\tSetUp(fsGroup *int64) error\n\tSetUpAt(dir string, fsGroup *int64) error\n\tGetAttributes() Attributes\n}\n\n\ntype Unmounter interface {\n\tVolume\n\tTearDown() error\n\tTearDownAt(dir string) error\n}\n\n\ntype Recycler interface {\n\tVolume\n\tRecycle() error\n}\n\n\n\ntype Provisioner interface {\n\tProvision() (*api.PersistentVolume, error)\n}\n\n\n\n\n\ntype Deleter interface {\n\tVolume\n\tDelete() error\n}\n\n\ntype Attacher interface {\n\tAttach(spec *Spec, hostName string) error\n\n\tWaitForAttach(spec *Spec, timeout time.Duration) (string, error)\n\n\tGetDeviceMountPath(spec *Spec) string\n\n\tMountDevice(spec *Spec, devicePath string, deviceMountPath string, mounter mount.Interface) error\n}\n\n\ntype Detacher interface {\n\tDetach(deviceName, hostName string) error\n\n\tWaitForDetach(devicePath string, timeout time.Duration) error\n\n\tUnmountDevice(deviceMountPath string, mounter mount.Interface) error\n}\n\n\n\nfunc RenameDirectory(oldPath, newName string) (string, error) ", "output": "{\n\tnewPath, err := ioutil.TempDir(path.Dir(oldPath), newName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\terr = os.Rename(oldPath, newPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn newPath, nil\n}"} {"input": "package chain\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"github.com/containous/alice\"\n\t\"github.com/traefik/traefik/v2/pkg/config/dynamic\"\n\t\"github.com/traefik/traefik/v2/pkg/log\"\n\t\"github.com/traefik/traefik/v2/pkg/middlewares\"\n)\n\nconst (\n\ttypeName = \"Chain\"\n)\n\ntype chainBuilder interface {\n\tBuildChain(ctx context.Context, middlewares []string) *alice.Chain\n}\n\n\n\n\nfunc New(ctx context.Context, next http.Handler, config dynamic.Chain, builder chainBuilder, name string) (http.Handler, error) ", "output": "{\n\tlog.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug(\"Creating middleware\")\n\n\tmiddlewareChain := builder.BuildChain(ctx, config.Middlewares)\n\treturn middlewareChain.Then(next)\n}"} {"input": "package ehttp\n\nimport (\n\t\"encoding/json\"\n\t\"path\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc assertInt(t *testing.T, expect, got int) {\n\t_, file, line := getCallstack(1)\n\tif expect != got {\n\t\tt.Errorf(\"[%s:%d] Unexpected result.\\nExpect:\\t%d\\nGot:\\t%d\\n\", file, line, expect, got)\n\t}\n}\n\nfunc assertString(t *testing.T, expect, got string) {\n\t_, file, line := getCallstack(1)\n\texpect, got = strings.TrimSpace(expect), strings.TrimSpace(got)\n\tif expect != got {\n\t\tt.Errorf(\"[%s:%d] Unexpected result.\\nExpect:\\t%s\\nGot:\\t%s\\n\", file, line, expect, got)\n\t}\n}\n\nfunc assertJSONError(t *testing.T, expect, got string) {\n\t_, file, line := getCallstack(1)\n\texpect, got = strings.TrimSpace(expect), strings.TrimSpace(got)\n\n\tjErr := JSONError{}\n\tif err := json.Unmarshal([]byte(got), &jErr); err != nil {\n\t\tt.Errorf(\"[%s:%d] Error parsing json error: %s\\n\", file, line, expect)\n\t}\n\tfor _, errStr := range jErr.Errors {\n\t\tif errStr == expect {\n\t\t\treturn\n\t\t}\n\t}\n\tt.Errorf(\"[%s:%d] Unexpected error.\\nExpect:\\t%s\\nGot:\\t%s\\n\", file, line, expect, got)\n}\n\nfunc getCallstack(skip int) (string, string, int) ", "output": "{\n\tvar name string\n\tpc, file, line, ok := runtime.Caller(1 + skip)\n\tif !ok {\n\t\tname, file, line = \"\", \"\", -1\n\t} else {\n\t\tname = runtime.FuncForPC(pc).Name()\n\t\tname = path.Base(name)\n\t\tfile = path.Base(file)\n\t}\n\treturn name, file, line\n}"} {"input": "package events\n\n\ntype Broker struct {\n\tevents chan Event \n\tsubs map[chan Event]string \n\tsub chan sub \n\tunsub chan sub \n}\n\n\ntype Event struct {\n\tName string \n\tData interface{} \n}\n\ntype sub struct {\n\tname string \n\tevents chan Event \n}\n\n\n\nfunc New() *Broker {\n\tb := &Broker{\n\t\tevents: make(chan Event, 8),\n\t\tsubs: make(map[chan Event]string),\n\t\tsub: make(chan sub),\n\t\tunsub: make(chan sub),\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase c := <-b.sub: \n\t\t\t\tb.subs[c.events] = c.name\n\t\t\tcase c := <-b.unsub: \n\t\t\t\tdelete(b.subs, c.events)\n\t\t\tcase e := <-b.events: \n\t\t\t\tfor c := range b.subs {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase c <- e:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn b\n}\n\n\nfunc (b Broker) Subscribe(name string) chan Event {\n\tc := make(chan Event)\n\tb.sub <- sub{name: name, events: c}\n\treturn c\n}\n\n\n\n\n\nfunc (b Broker) Publish(e Event) {\n\tb.events <- e\n}\n\nfunc (b Broker) Unsubscribe(c chan Event) ", "output": "{\n\tb.unsub <- sub{events: c}\n}"} {"input": "package tc\n\n\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype CRStates struct {\n\tCaches map[CacheName]IsAvailable `json:\"caches\"`\n\tDeliveryService map[DeliveryServiceName]CRStatesDeliveryService `json:\"deliveryServices\"`\n}\n\n\ntype CRStatesDeliveryService struct {\n\tDisabledLocations []CacheGroupName `json:\"disabledLocations\"`\n\tIsAvailable bool `json:\"isAvailable\"`\n}\n\n\ntype IsAvailable struct {\n\tIsAvailable bool `json:\"isAvailable\"`\n}\n\n\nfunc NewCRStates() CRStates {\n\treturn CRStates{\n\t\tCaches: map[CacheName]IsAvailable{},\n\t\tDeliveryService: map[DeliveryServiceName]CRStatesDeliveryService{},\n\t}\n}\n\n\nfunc (a CRStates) Copy() CRStates {\n\tb := NewCRStates()\n\tfor k, v := range a.Caches {\n\t\tb.Caches[k] = v\n\t}\n\tfor k, v := range a.DeliveryService {\n\t\tb.DeliveryService[k] = v\n\t}\n\treturn b\n}\n\n\nfunc (a CRStates) CopyDeliveryServices() map[DeliveryServiceName]CRStatesDeliveryService {\n\tb := map[DeliveryServiceName]CRStatesDeliveryService{}\n\tfor k, v := range a.DeliveryService {\n\t\tb[k] = v\n\t}\n\treturn b\n}\n\n\nfunc (a CRStates) CopyCaches() map[CacheName]IsAvailable {\n\tb := map[CacheName]IsAvailable{}\n\tfor k, v := range a.Caches {\n\t\tb[k] = v\n\t}\n\treturn b\n}\n\n\nfunc CRStatesMarshall(states CRStates) ([]byte, error) {\n\treturn json.Marshal(states)\n}\n\n\n\n\nfunc CRStatesUnMarshall(body []byte) (CRStates, error) ", "output": "{\n\tvar crStates CRStates\n\terr := json.Unmarshal(body, &crStates)\n\treturn crStates, err\n}"} {"input": "package dnsrecorder\n\nimport (\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n)\n\n\n\n\n\n\n\ntype Recorder struct {\n\tdns.ResponseWriter\n\tRcode int\n\tLen int\n\tMsg *dns.Msg\n\tStart time.Time\n}\n\n\n\n\nfunc New(w dns.ResponseWriter) *Recorder {\n\treturn &Recorder{\n\t\tResponseWriter: w,\n\t\tRcode: 0,\n\t\tMsg: nil,\n\t\tStart: time.Now(),\n\t}\n}\n\n\n\nfunc (r *Recorder) WriteMsg(res *dns.Msg) error {\n\tr.Rcode = res.Rcode\n\tr.Len += res.Len()\n\tr.Msg = res\n\treturn r.ResponseWriter.WriteMsg(res)\n}\n\n\nfunc (r *Recorder) Write(buf []byte) (int, error) {\n\tn, err := r.ResponseWriter.Write(buf)\n\tif err == nil {\n\t\tr.Len += n\n\t}\n\treturn n, err\n}\n\n\n\n\n\nfunc (r *Recorder) Hijack() ", "output": "{ r.ResponseWriter.Hijack(); return }"} {"input": "package core\n\nimport (\n \"errors\"\n \"fmt\"\n \"image\"\n \"image/jpeg\"\n \"io\"\n \"os\"\n \"os/exec\"\n)\n\ntype JPEGHandler struct {\n}\n\nfunc (j *JPEGHandler) ImageType() string {\n return \"image/png\"\n}\n\n\n\nfunc (j *JPEGHandler) Encode(newImgFile *os.File, newImage image.Image) error {\n return jpeg.Encode(newImgFile, newImage, nil)\n}\n\nfunc (j *JPEGHandler) Convert(newImageTempPath string, quality uint) error {\n args := []string{fmt.Sprintf(\"--max=%d\", quality), newImageTempPath}\n cmd := exec.Command(\"jpegoptim\", args...)\n err := cmd.Run()\n if err != nil {\n return errors.New(\"Jpegoptim command not working\")\n }\n\n return nil\n}\n\nfunc (j *JPEGHandler) Decode(reader io.Reader) (image.Image, error) ", "output": "{\n return jpeg.Decode(reader)\n}"} {"input": "package codes\n\nimport (\n\t\"encoding/json\"\n)\n\ntype Code struct {\n\tCode string `json:\"code\"`\n\tDescriptions struct {\n\t\tIetf struct {\n\t\t\tBody string `json:\"body\"`\n\t\t\tLink string `json:\"link\"`\n\t\t} `json:\"ietf\"`\n\t\tWikipedia struct {\n\t\t\tBody string `json:\"body\"`\n\t\t\tLink string `json:\"link\"`\n\t\t} `json:\"wikipedia\"`\n\t} `json:\"descriptions\"`\n\tReferences struct {\n\t\tRails struct {\n\t\t\tTitle string `json:\"title\"`\n\t\t\tValue string `json:\"value\"`\n\t\t} `json:\"rails\"`\n\t} `json:\"references\"`\n\tSummary string `json:\"summary\"`\n\tTitle string `json:\"title\"`\n}\n\ntype Codes map[string]Code\n\n\n\nfunc All() Codes ", "output": "{\n\tb, err := Asset(\"codes.json\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar codes Codes\n\tif err := json.Unmarshal(b, &codes); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn codes\n}"} {"input": "package factory\n\n\n\nfunc init() ", "output": "{\n\traceEnabled = true\n}"} {"input": "package bstrees\n\nimport \"testing\"\n\nfunc TestFindFirstGreaterK(t *testing.T) {\n\ttree := &BSTree{19, \n\t\t&BSTree{7, \n\t\t\t&BSTree{3, \n\t\t\t\t&BSTree{2, nil, nil}, \n\t\t\t\t&BSTree{5, nil, nil}}, \n\t\t\t&BSTree{11, \n\t\t\t\tnil,\n\t\t\t\t&BSTree{17, \n\t\t\t\t\t&BSTree{13, nil, nil}, \n\t\t\t\t\tnil}}},\n\t\t&BSTree{43, \n\t\t\t&BSTree{23, \n\t\t\t\tnil,\n\t\t\t\t&BSTree{37, \n\t\t\t\t\t&BSTree{29, \n\t\t\t\t\t\tnil,\n\t\t\t\t\t\t&BSTree{31, nil, nil}}, \n\t\t\t\t\t&BSTree{41, nil, nil}}}, \n\t\t\t&BSTree{47, \n\t\t\t\tnil,\n\t\t\t\t&BSTree{53, nil, nil}}}} \n\n\tfor _, test := range []struct {\n\t\tk interface{}\n\t\twant *BSTree\n\t}{\n\t\t{-1, tree.left.left.left}, \n\t\t{3, tree.left.left.right}, \n\t\t{23, tree.right.left.right.left}, \n\t\t{31, tree.right.left.right}, \n\t\t{47, tree.right.right.right}, \n\t\t{53, nil}, \n\t} {\n\t\tif got := FindFirstGreaterK(tree, test.k.(int)); got != test.want {\n\t\t\tt.Errorf(\"FindFirstGreaterK(%v, %d) = %v; want %v\", tree, test.k, got, test.want)\n\t\t}\n\t}\n}\n\n\n\nfunc BenchmarkFindFirstGreaterK(b *testing.B) ", "output": "{\n\ttree := &BSTree{19,\n\t\t&BSTree{7,\n\t\t\t&BSTree{3,\n\t\t\t\t&BSTree{2, nil, nil},\n\t\t\t\t&BSTree{5, nil, nil}},\n\t\t\t&BSTree{11,\n\t\t\t\tnil,\n\t\t\t\t&BSTree{17,\n\t\t\t\t\t&BSTree{13, nil, nil},\n\t\t\t\t\tnil}}},\n\t\t&BSTree{43,\n\t\t\t&BSTree{23,\n\t\t\t\tnil,\n\t\t\t\t&BSTree{37,\n\t\t\t\t\t&BSTree{29,\n\t\t\t\t\t\tnil,\n\t\t\t\t\t\t&BSTree{31, nil, nil}},\n\t\t\t\t\t&BSTree{41, nil, nil}}},\n\t\t\t&BSTree{47,\n\t\t\t\tnil,\n\t\t\t\t&BSTree{53, nil, nil}}}}\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tFindFirstGreaterK(tree, 31)\n\t}\n}"} {"input": "package buildclean\n\nvar Usage = []string{\"rt bc \"}\n\n\n\nfunc GetArguments() string {\n\treturn `\tbuild name\n\t\tBuild name.\n\n\tbuild number\n\t\tBuild number.`\n}\n\nfunc GetDescription() string ", "output": "{\n\treturn \"This command is used to clean (remove) build info collected locally.\"\n}"} {"input": "package unix\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\nfunc TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }\n\nfunc NsecToTimespec(nsec int64) (ts Timespec) {\n\tts.Sec = nsec / 1e9\n\tts.Nsec = nsec % 1e9\n\treturn\n}\n\nfunc NsecToTimeval(nsec int64) (tv Timeval) {\n\tnsec += 999 \n\ttv.Usec = int32(nsec % 1e9 / 1e3)\n\ttv.Sec = int64(nsec / 1e9)\n\treturn\n}\n\n\nfunc Gettimeofday(tv *Timeval) (err error) {\n\tsec, usec, err := gettimeofday(tv)\n\ttv.Sec = sec\n\ttv.Usec = usec\n\treturn err\n}\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint64(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint64(length)\n}\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\n\n\nfunc Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)\n\n\n\nconst SYS___SYSCTL = SYS_SYSCTL\n\nfunc sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) ", "output": "{\n\tvar length = uint64(count)\n\n\t_, _, e1 := Syscall6(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(unsafe.Pointer(&length)), 0, 0)\n\n\twritten = int(length)\n\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"github.com/ajstarks/openvg\"\n\t\"math/rand\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc rseed() {\n\trand.Seed(int64(time.Now().Nanosecond()) % 1e9)\n}\n\n\nfunc main() {\n\tvar nr = flag.Int(\"n\", 500, \"number of objects\")\n\tvar message = flag.String(\"m\", \"Go/OpenVG\", \"message\")\n\tvar bgcolor = flag.String(\"bg\", \"white\", \"background color\")\n\tvar fgcolor = flag.String(\"fg\", \"maroon\", \"text color\")\n\n\tflag.Parse()\n\trseed()\n\n\twidth, height := openvg.Init()\n\tfw := openvg.VGfloat(width)\n\tfh := openvg.VGfloat(height)\n\n\topenvg.Start(width, height)\n\topenvg.BackgroundColor(*bgcolor)\n\tfor i := 0; i < *nr; i++ {\n\n\t\tred := uint8(rand.Intn(255))\n\t\tgreen := uint8(rand.Intn(255))\n\t\tblue := uint8(rand.Intn(255))\n\t\talpha := randf()\n\n\t\tx := randf() * fw\n\t\ty := randf() * fh\n\t\tradius := randf() * fw / 10\n\n\t\topenvg.FillRGB(red, green, blue, alpha)\n\t\topenvg.Circle(x, y, radius)\n\t}\n\topenvg.FillColor(*fgcolor)\n\topenvg.TextMid(fw/2, fh/2, *message, \"sans\", width/25)\n\topenvg.End()\n\n\tbufio.NewReader(os.Stdin).ReadBytes('\\n')\n\topenvg.Finish()\n}\n\nfunc randf() openvg.VGfloat ", "output": "{\n\treturn openvg.VGfloat(rand.Float32())\n}"} {"input": "package auto\n\nimport (\n\t\"sync\"\n\n\t\"github.com/miekg/coredns/middleware/file\"\n)\n\n\n\ntype Zones struct {\n\tZ map[string]*file.Zone \n\tnames []string \n\n\torigins []string \n\n\tsync.RWMutex\n}\n\n\n\n\n\nfunc (z *Zones) Origins() []string {\n\treturn z.origins\n}\n\n\nfunc (z *Zones) Zones(name string) *file.Zone {\n\tz.RLock()\n\tzo := z.Z[name]\n\tz.RUnlock()\n\treturn zo\n}\n\n\n\nfunc (z *Zones) Add(zo *file.Zone, name string) {\n\tz.Lock()\n\n\tif z.Z == nil {\n\t\tz.Z = make(map[string]*file.Zone)\n\t}\n\n\tz.Z[name] = zo\n\tz.names = append(z.names, name)\n\tzo.Reload()\n\n\tz.Unlock()\n}\n\n\nfunc (z *Zones) Remove(name string) {\n\tz.Lock()\n\n\tif zo, ok := z.Z[name]; ok && !zo.NoReload {\n\t\tzo.ReloadShutdown <- true\n\t}\n\n\tdelete(z.Z, name)\n\n\tz.names = []string{}\n\tfor n := range z.Z {\n\t\tz.names = append(z.names, n)\n\t}\n\n\tz.Unlock()\n}\n\nfunc (z *Zones) Names() []string ", "output": "{\n\tz.RLock()\n\tn := z.names\n\tz.RUnlock()\n\treturn n\n}"} {"input": "package d3data\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"io/ioutil\"\n)\n\nfunc CreateGraphJSONData(a_shape float64, b_scale int) {\n\tres, err := GenerateData(a_shape, b_scale)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\terr = writeToFile(res)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}\n\n\n\nfunc writeToFile(b []byte) error ", "output": "{\n\tabsPath, err := filepath.Abs(\"../gopower/display/output.json\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(absPath, b, 0644)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package lib\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\n\nfunc MergeErrors(err1, err2 error, joiner string) error ", "output": "{\n\tif err1 == nil {\n\t\treturn err2\n\t} else if err2 == nil {\n\t\treturn err1\n\t} else {\n\t\treturn fmt.Errorf(\"%v%s%v\", err1, joiner, err2)\n\t}\n}"} {"input": "package raw\n\nimport (\n\t\"fmt\"\n\t\"../../platforms/common\"\n)\n\ntype FieldMacros struct {}\n\nfunc (FieldMacros) DecodeDW0() {\n\tmacro := common.GetMacro()\n\tmacro.Add(fmt.Sprintf(\"0x%0.8x\", macro.Register(common.PAD_CFG_DW0).ValueGet()))\n}\n\n\n\n\nfunc (bitfields FieldMacros) GenerateString() {\n\tmacro := common.GetMacro()\n\tmacro.Add(\"_PAD_CFG_STRUCT(\").Id().Add(\", \")\n\tbitfields.DecodeDW0()\n\tmacro.Add(\", \")\n\tbitfields.DecodeDW1()\n\tmacro.Add(\"),\")\n}\n\nfunc (FieldMacros) DecodeDW1() ", "output": "{\n\tmacro := common.GetMacro()\n\tmacro.Add(fmt.Sprintf(\"0x%0.8x\", macro.Register(common.PAD_CFG_DW1).ValueGet()))\n}"} {"input": "package server\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/influxdata/influxdb/chronograf\"\n\t\"github.com/influxdata/influxdb/chronograf/influx\"\n)\n\n\n\n\n\n\nvar validFieldTypes = map[string]bool{\n\t\"func\": true,\n\t\"field\": true,\n\t\"integer\": true,\n\t\"number\": true,\n\t\"regex\": true,\n\t\"wildcard\": true,\n}\n\n\nfunc ValidateQueryConfig(q *chronograf.QueryConfig) error {\n\tfor _, fld := range q.Fields {\n\t\tinvalid := fmt.Errorf(`invalid field type \"%s\" ; expect func, field, integer, number, regex, wildcard`, fld.Type)\n\t\tif !validFieldTypes[fld.Type] {\n\t\t\treturn invalid\n\t\t}\n\t\tfor _, arg := range fld.Args {\n\t\t\tif !validFieldTypes[arg.Type] {\n\t\t\t\treturn invalid\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc ToQueryConfig(query string) chronograf.QueryConfig ", "output": "{\n\tqc, err := influx.Convert(query)\n\tif err == nil {\n\t\treturn qc\n\t}\n\treturn chronograf.QueryConfig{\n\t\tRawText: &query,\n\t\tFields: []chronograf.Field{},\n\t\tGroupBy: chronograf.GroupBy{\n\t\t\tTags: []string{},\n\t\t},\n\t\tTags: make(map[string][]string),\n\t}\n}"} {"input": "package antlr\n\nimport \"fmt\"\n\ntype TraceListener struct {\n\tparser *BaseParser\n}\n\nfunc NewTraceListener(parser *BaseParser) *TraceListener {\n\ttl := new(TraceListener)\n\ttl.parser = parser\n\treturn tl\n}\n\nfunc (t *TraceListener) VisitErrorNode(_ ErrorNode) {\n}\n\n\n\nfunc (t *TraceListener) VisitTerminal(node TerminalNode) {\n\tfmt.Println(\"consume \" + fmt.Sprint(node.GetSymbol()) + \" rule \" + t.parser.GetRuleNames()[t.parser.ctx.GetRuleIndex()])\n}\n\nfunc (t *TraceListener) ExitEveryRule(ctx ParserRuleContext) {\n\tfmt.Println(\"exit \" + t.parser.GetRuleNames()[ctx.GetRuleIndex()] + \", LT(1)=\" + t.parser.input.LT(1).GetText())\n}\n\nfunc (t *TraceListener) EnterEveryRule(ctx ParserRuleContext) ", "output": "{\n\tfmt.Println(\"enter \" + t.parser.GetRuleNames()[ctx.GetRuleIndex()] + \", LT(1)=\" + t.parser.input.LT(1).GetText())\n}"} {"input": "package util\n\nimport (\n\t\"crypto\"\n\t\"io\"\n\n\t\"golang.org/x/crypto/ssh\"\n)\n\n\n\ntype ExtendedAgentSigner interface {\n\tssh.Signer\n\tSignWithOpts(rand io.Reader, data []byte, opts crypto.SignerOpts) (*ssh.Signature, error)\n}\n\ntype ExtendedAgentSignerWrapper struct {\n\tOpts crypto.SignerOpts\n\tSigner ExtendedAgentSigner\n}\n\nfunc (e *ExtendedAgentSignerWrapper) PublicKey() ssh.PublicKey {\n\treturn e.Signer.PublicKey()\n}\n\nfunc (e *ExtendedAgentSignerWrapper) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {\n\treturn e.Signer.SignWithOpts(rand, data, e.Opts)\n}\n\ntype AlgorithmSignerWrapper struct {\n\tAlgorithm string\n\tSigner ssh.AlgorithmSigner\n}\n\nfunc (a *AlgorithmSignerWrapper) PublicKey() ssh.PublicKey {\n\treturn a.Signer.PublicKey()\n}\n\nfunc (a *AlgorithmSignerWrapper) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {\n\treturn a.Signer.SignWithAlgorithm(rand, data, a.Algorithm)\n}\n\nfunc SignatureFormatFromSigningOptionAndCA(opt string, ca ssh.PublicKey) string ", "output": "{\n\tswitch {\n\tcase ca != nil && ca.Type() == ssh.KeyAlgoED25519:\n\t\treturn ssh.KeyAlgoED25519\n\tcase ca != nil && ca.Type() == ssh.KeyAlgoRSA && opt == \"\":\n\t\treturn ssh.SigAlgoRSA\n\tdefault:\n\t\treturn opt\n\t}\n}"} {"input": "package race_test\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestNoRaceIOFile(t *testing.T) {\n\tx := 0\n\tpath, _ := ioutil.TempDir(\"\", \"race_test\")\n\tfname := filepath.Join(path, \"data\")\n\tgo func() {\n\t\tx = 42\n\t\tf, _ := os.Create(fname)\n\t\tf.Write([]byte(\"done\"))\n\t\tf.Close()\n\t}()\n\tfor {\n\t\tf, err := os.Open(fname)\n\t\tif err != nil {\n\t\t\ttime.Sleep(1e6)\n\t\t\tcontinue\n\t\t}\n\t\tbuf := make([]byte, 100)\n\t\tcount, err := f.Read(buf)\n\t\tif count == 0 {\n\t\t\ttime.Sleep(1e6)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\t_ = x\n}\n\n\n\nfunc TestNoRaceIOHttp(t *testing.T) ", "output": "{\n\tx := 0\n\tgo func() {\n\t\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\t\tx = 41\n\t\t\tfmt.Fprintf(w, \"test\")\n\t\t\tx = 42\n\t\t})\n\t\terr := http.ListenAndServe(\"127.0.0.1:23651\", nil)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"http.ListenAndServe: %v\", err)\n\t\t}\n\t}()\n\ttime.Sleep(1e7)\n\tx = 1\n\t_, err := http.Get(\"http://127.0.0.1:23651\")\n\tif err != nil {\n\t\tt.Fatalf(\"http.Get: %v\", err)\n\t}\n\tx = 2\n\t_, err = http.Get(\"http://127.0.0.1:23651\")\n\tif err != nil {\n\t\tt.Fatalf(\"http.Get: %v\", err)\n\t}\n\tx = 3\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/config\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\n\n\n\ntype CmdGetJSONConfig struct {\n\tname string\n\trpcMethod string\n\trpcParams *config.SectionWithOpts\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetJSONConfig) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdGetJSONConfig) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdGetJSONConfig) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &config.SectionWithOpts{Opts: make(map[string]interface{})}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetJSONConfig) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetJSONConfig) RpcResult() interface{} {\n\tvar s map[string]interface{}\n\treturn &s\n}\n\nfunc init() ", "output": "{\n\tc := &CmdGetJSONConfig{\n\t\tname: \"get_json_section\",\n\t\trpcMethod: utils.ConfigSv1GetConfig,\n\t\trpcParams: &config.SectionWithOpts{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}"} {"input": "package dt\n\nimport (\n\t\"net/http\"\n\t\"path\"\n\n\t\"github.com/julienschmidt/httprouter\"\n)\n\n\ntype HTTPRoute struct {\n\tMethod string\n\tPath string\n}\n\n\n\ntype HandlerMap map[HTTPRoute]http.HandlerFunc\n\n\ntype RouteHandler struct {\n\tMethod string\n\tPath string\n\tHandler http.HandlerFunc\n}\n\n\n\nfunc (hm HandlerMap) AddRoutes(prefix string, r *httprouter.Router) {\n\tfor httpRoute, h := range hm {\n\t\tp := path.Join(\"/\", prefix, httpRoute.Path)\n\t\tr.HandlerFunc(httpRoute.Method, p, h)\n\t}\n}\n\n\n\n\n\n\nfunc NewHandlerMap(rhs []RouteHandler) HandlerMap ", "output": "{\n\thm := HandlerMap{}\n\tfor _, rh := range rhs {\n\t\troute := HTTPRoute{\n\t\t\tPath: rh.Path,\n\t\t\tMethod: rh.Method,\n\t\t}\n\t\thm[route] = rh.Handler\n\t}\n\treturn hm\n}"} {"input": "package fileset\n\nimport(\n\t\"path/filepath\"\n)\n\n\n\nfunc (diff EntryMapDiff) Filter(patterns []string) (newDiff EntryMapDiff) {\n\tnewDiff.Added = filterEntryMap(diff.Added, patterns)\n\tnewDiff.Updated = filterEntryMap(diff.Updated, patterns)\n\tnewDiff.Removed = filterEntryMap(diff.Removed, patterns)\n\treturn\n}\n\n\n\n\n\nfunc filterEntryMap(entryMap EntryMap, patterns []string) (newEntryMap EntryMap) ", "output": "{\n\tnewEntryMap = make(EntryMap)\n\tfor k, v := range entryMap {\n\t\tmatch := false\n\t\tfor _, pattern := range patterns {\n\t\t\tresult, _ := filepath.Match(pattern, k)\n\t\t\tif result {\n\t\t\t\tmatch = true\n\t\t\t}\n\t\t}\n\t\tif match {\n\t\t\tnewEntryMap[k] = v\n\t\t}\n\t}\n\treturn\n}"} {"input": "package database\n\nimport (\n\t\"context\"\n\n\t\"github.com/grafana/grafana/pkg/models\"\n\t\"github.com/grafana/grafana/pkg/services/sqlstore\"\n)\n\ntype TeamGuardianStoreImpl struct {\n\tsqlStore sqlstore.Store\n}\n\nfunc ProvideTeamGuardianStore(sqlStore sqlstore.Store) *TeamGuardianStoreImpl {\n\treturn &TeamGuardianStoreImpl{sqlStore: sqlStore}\n}\n\n\n\nfunc (t *TeamGuardianStoreImpl) GetTeamMembers(ctx context.Context, query models.GetTeamMembersQuery) ([]*models.TeamMemberDTO, error) ", "output": "{\n\tif err := t.sqlStore.GetTeamMembers(ctx, &query); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn query.Result, nil\n}"} {"input": "package persist\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n\t\"os\"\n)\n\n\n\n\n\nfunc LoadFile(meta Metadata, data interface{}, filename string) error {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\terr = Load(meta, data, file)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\nfunc Save(meta Metadata, data interface{}, w io.Writer) error {\n\tb, err := json.MarshalIndent(data, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tenc := json.NewEncoder(w)\n\tif err := enc.Encode(meta.Header); err != nil {\n\t\treturn err\n\t}\n\tif err := enc.Encode(meta.Version); err != nil {\n\t\treturn err\n\t}\n\tif _, err = w.Write(b); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc SaveFile(meta Metadata, data interface{}, filename string) error {\n\tfile, err := NewSafeFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\terr = Save(meta, data, file)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn file.Commit()\n}\n\n\nfunc SaveFileSync(meta Metadata, data interface{}, filename string) error {\n\tfile, err := NewSafeFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\terr = Save(meta, data, file)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn file.CommitSync()\n}\n\nfunc Load(meta Metadata, data interface{}, r io.Reader) error ", "output": "{\n\tvar header, version string\n\tdec := json.NewDecoder(r)\n\tif err := dec.Decode(&header); err != nil {\n\t\treturn err\n\t}\n\tif header != meta.Header {\n\t\treturn ErrBadHeader\n\t}\n\tif err := dec.Decode(&version); err != nil {\n\t\treturn err\n\t}\n\tif version != meta.Version {\n\t\treturn ErrBadVersion\n\t}\n\tif err := dec.Decode(data); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package auth\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/databus23/keystone\"\n\t\"github.com/databus23/keystone/cache/memory\"\n\t\"github.com/go-kit/kit/log\"\n\terrors \"github.com/go-openapi/errors\"\n\tflag \"github.com/spf13/pflag\"\n\n\t\"github.com/sapcc/kubernikus/pkg/api/models\"\n)\n\nvar authURL string\n\nfunc init() {\n\tflag.StringVar(&authURL, \"auth-url\", \"\", \"Openstack identity v3 auth url\")\n}\n\n\n\nfunc Keystone(logger log.Logger) func(token string) (*models.Principal, error) {\n\n\tkeystone.Log = func(format string, a ...interface{}) {\n\t\tlogger.Log(\"library\", \"keystone\", \"msg\", fmt.Sprintf(format, a...))\n\t}\n\tauth := keystone.New(OpenStackAuthURL())\n\tauth.TokenCache = memory.New(10 * time.Minute)\n\n\treturn func(token string) (*models.Principal, error) {\n\t\tt, err := auth.Validate(token)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(401, fmt.Sprintf(\"Authentication failed: %s\", err))\n\t\t}\n\t\tif t.Project == nil {\n\t\t\treturn nil, errors.New(401, \"Auth token isn't project scoped\")\n\t\t}\n\t\troles := make([]string, 0, len(t.Roles))\n\t\tfor _, role := range t.Roles {\n\t\t\troles = append(roles, role.Name)\n\t\t}\n\t\treturn &models.Principal{ID: t.User.ID, Name: t.User.Name, Domain: t.User.Domain.Name, Account: t.Project.ID, AccountName: t.Project.Name, Roles: roles}, nil\n\t}\n}\n\nfunc OpenStackAuthURL() string ", "output": "{\n\tif authURL == \"\" {\n\t\treturn \"\"\n\t}\n\tif !(strings.HasSuffix(authURL, \"/v3\") || strings.HasSuffix(authURL, \"/v3/\")) {\n\t\treturn strings.TrimRight(authURL, \"/\") + \"/v3\"\n\t}\n\treturn authURL\n}"} {"input": "package dhash\n\nimport (\n\t\"github.com/cstream/gauss/timenet\"\n)\n\ntype dhashPeerProducer Node\n\n\n\nfunc (self *dhashPeerProducer) Peers() (result map[string]timenet.Peer) ", "output": "{\n\tresult = make(map[string]timenet.Peer)\n\tfor _, node := range (*Node)(self).node.GetNodes() {\n\t\tresult[node.Addr] = (remotePeer)(node)\n\t}\n\treturn\n}"} {"input": "package uber\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\tistioconfig \"istio.io/api/istio/config/v1\"\n\n\t\"istio.io/mixer/pkg/aspectsupport\"\n\t\"istio.io/mixer/pkg/attribute\"\n\t\"istio.io/mixer/pkg/expr\"\n)\n\ntype (\n\tfakereg struct {\n\t\tRegistryQuerier\n\t}\n\n\tfakemgr struct {\n\t\tkind string\n\t\taspectsupport.Manager\n\t}\n\n\tfakebag struct {\n\t\tattribute.Bag\n\t}\n\n\tfakeevaluator struct {\n\t\texpr.Evaluator\n\t}\n)\n\n\n\nfunc TestManager(t *testing.T) {\n\tr := &fakereg{}\n\tmgrs := []aspectsupport.Manager{&fakemgr{kind: \"k1\"}, &fakemgr{kind: \"k2\"}}\n\tm := NewManager(r, mgrs)\n\tcfg := &aspectsupport.CombinedConfig{\n\t\tAspect: &istioconfig.Aspect{},\n\t\tAdapter: &istioconfig.Adapter{},\n\t}\n\tattrs := &fakebag{}\n\tmapper := &fakeevaluator{}\n\tif _, err := m.Execute(cfg, attrs, mapper); err != nil {\n\t\tif !strings.Contains(err.Error(), \"could not find aspect manager\") {\n\t\t\tt.Error(\"excute errored out: \", err)\n\t\t}\n\n\t}\n}\n\nfunc (m *fakemgr) Kind() string ", "output": "{\n\treturn m.kind\n}"} {"input": "package mailer\n\nimport \"fmt\"\n\n\ntype Message struct {\n\tTemplateID string\n\tFrom string\n\tTo string\n\tSubject string\n\tBody string\n\tVars map[string]string\n}\n\n\n\n\n\nfunc (msg *Message) SetVar(name string, value string) {\n\tfullName := fmt.Sprintf(\"-%s-\", name)\n\tmsg.Vars[fullName] = value\n}\n\nfunc NewMessage(templateID string) *Message ", "output": "{\n\treturn &Message{\n\t\tTemplateID: templateID,\n\t}\n}"} {"input": "package isdocker\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestIsNonDockerProcess(t *testing.T) {\n\tisdocker := IsDocker()\n\tif isdocker == true {\n\t\tt.Errorf(\"process is in non-docker mode, but shows docker mode !!!\")\n\t}\n}\n\nfunc TestIsDockerProcess(t *testing.T) ", "output": "{\n\tisdocker := IsDocker()\n\tif isdocker == false {\n\t\tt.Errorf(\"process is in docker mode, but shows non-docker mode !!!\")\n\t}\n}"} {"input": "package dashing\n\nimport (\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\n\ntype Event struct {\n\tID string\n\tBody map[string]interface{}\n\tTarget string\n}\n\n\ntype Dashing struct {\n\tstarted bool\n\tBroker *Broker\n\tWorker *Worker\n\tServer *Server\n\tRouter http.Handler\n}\n\n\nfunc (d *Dashing) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif !d.started {\n\t\tpanic(\"dashing.Start() has not been called\")\n\t}\n\td.Router.ServeHTTP(w, r)\n}\n\n\nfunc (d *Dashing) Start() *Dashing {\n\tif !d.started {\n\t\tif d.Router == nil {\n\t\t\td.Router = d.Server.NewRouter()\n\t\t}\n\t\td.Broker.Start()\n\t\td.Worker.Start()\n\t\td.started = true\n\t}\n\treturn d\n}\n\n\n\n\nfunc NewDashing() *Dashing ", "output": "{\n\tbroker := NewBroker()\n\tworker := NewWorker(broker)\n\tserver := NewServer(broker)\n\n\tif os.Getenv(\"WEBROOT\") != \"\" {\n\t\tserver.webroot = filepath.Clean(os.Getenv(\"WEBROOT\")) + \"/\"\n\t}\n\tif os.Getenv(\"DEV\") != \"\" {\n\t\tserver.dev = true\n\t}\n\n\treturn &Dashing{\n\t\tstarted: false,\n\t\tBroker: broker,\n\t\tWorker: worker,\n\t\tServer: server,\n\t}\n}"} {"input": "package fs\n\nimport (\n\t\"syscall\"\n)\n\nfunc MountRootFS(path string) error {\n\treturn syscall.Mount(path, \"rootfs\", \"\", syscall.MS_BIND, \"\")\n}\n\nfunc MountAdditional(source, dest, t string) error {\n\treturn syscall.Mount(source, dest, t, syscall.MS_BIND, \"\")\n}\n\n\n\nfunc MountProcFS() error {\n\treturn syscall.Mount(\"proc\", \"/proc\", \"proc\", syscall.MS_BIND, \"\")\n}\n\nfunc MountSysFS() error {\n\treturn syscall.Mount(\"sysfs\", \"/sys\", \"sysfs\", syscall.MS_BIND, \"\")\n}\n\nfunc MountDevFS() error ", "output": "{\n\treturn syscall.Mount(\"tmpfs\", \"/dev\", \"tmpfs\", syscall.MS_BIND, \"\")\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\n\n\nfunc naclClose(fd int) (err error) {\n\t_, _, e1 := Syscall(sys_close, uintptr(fd), 0, 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclFstat(fd int, stat *Stat_t) (err error) {\n\t_, _, e1 := Syscall(sys_fstat, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclRead(fd int, b []byte) (n int, err error) {\n\tvar _p0 unsafe.Pointer\n\tif len(b) > 0 {\n\t\t_p0 = unsafe.Pointer(&b[0])\n\t} else {\n\t\t_p0 = unsafe.Pointer(&_zero)\n\t}\n\tr0, _, e1 := Syscall(sys_read, uintptr(fd), uintptr(_p0), uintptr(len(b)))\n\tn = int(r0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclSeek(fd int, off *int64, whence int) (err error) {\n\t_, _, e1 := Syscall(sys_lseek, uintptr(fd), uintptr(unsafe.Pointer(off)), uintptr(whence))\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\n\n\nfunc naclGetRandomBytes(b []byte) (err error) ", "output": "{\n\tvar _p0 unsafe.Pointer\n\tif len(b) > 0 {\n\t\t_p0 = unsafe.Pointer(&b[0])\n\t} else {\n\t\t_p0 = unsafe.Pointer(&_zero)\n\t}\n\t_, _, e1 := Syscall(sys_get_random_bytes, uintptr(_p0), uintptr(len(b)), 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}"} {"input": "package logwise\n\nimport (\n \"fmt\"\n \"os\"\n)\n\ntype Writer interface {\n Write(lines []string)\n}\n\ntype FileWriter struct {\n FilePath string\n Append bool\n Prefix string\n Postfix string\n}\n\nfunc NewFileWriter(filePath string, append bool, prefix,sufix string) Writer {\n return &FileWriter{filePath, append, prefix, sufix}\n}\n\n\n\nfunc (w *FileWriter) AddPostfix(postfix string) *FileWriter {\n w.Postfix = postfix\n return w\n}\n\nfunc (w *FileWriter) Write(lines []string) {\n var flags int\n\n if w.Append {\n flags = os.O_WRONLY | os.O_APPEND\n } else {\n flags = os.O_CREATE | os.O_WRONLY | os.O_TRUNC\n }\n\n file,_ := os.OpenFile(w.FilePath, flags, 0666)\n defer file.Close()\n \n if w.Prefix != \"\" {\n file.WriteString(fmt.Sprintf(\"%v\\n\", w.Prefix))\n }\n\n for _,line := range lines {\n file.WriteString(fmt.Sprintf(\"%v\\n\", line))\n }\n\n if w.Postfix != \"\" {\n file.WriteString(fmt.Sprintf(\"%v\\n\", w.Postfix))\n }\n}\n\nfunc (w *FileWriter) AddPrefix(prefix string) *FileWriter ", "output": "{\n w.Prefix = prefix\n return w\n}"} {"input": "package gode\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n)\n\nfunc TestPackages(t *testing.T) {\n\tc := setup()\n\tmust(os.RemoveAll(filepath.Join(c.RootPath, \"node_modules\")))\n\tmust(c.InstallPackage(\"request\"))\n\tpackages, err := c.Packages()\n\tmust(err)\n\tfor _, pkg := range packages {\n\t\tif pkg.Name == \"request\" {\n\t\t\treturn\n\t\t}\n\t}\n\tt.Fatalf(\"package did not install\")\n}\n\nfunc TestRemovePackage(t *testing.T) {\n\tc := setup()\n\tmust(os.RemoveAll(filepath.Join(c.RootPath, \"node_modules\")))\n\tmust(c.InstallPackage(\"request\"))\n\tpackages, err := c.Packages()\n\tmust(err)\n\tif len(packages) != 1 {\n\t\tt.Fatalf(\"package did not install correctly\")\n\t}\n\tmust(c.RemovePackage(\"request\"))\n\tpackages, err = c.Packages()\n\tmust(err)\n\tif len(packages) != 0 {\n\t\tt.Fatalf(\"package did not remove correctly\")\n\t}\n}\n\nfunc TestUpdatePackages(t *testing.T) {\n\tc := setup()\n\tmust(c.InstallPackage(\"request\"))\n\t_, err := c.UpdatePackages()\n\tmust(err)\n}\n\n\n\nfunc TestPackagesGithubPackage(t *testing.T) ", "output": "{\n\tc := setup()\n\tmust(os.RemoveAll(filepath.Join(c.RootPath, \"node_modules\")))\n\tmust(c.InstallPackage(\"dickeyxxx/heroku-production-check\"))\n\tpackages, err := c.Packages()\n\tmust(err)\n\tfor _, pkg := range packages {\n\t\tif pkg.Name == \"heroku-production-check\" {\n\t\t\treturn\n\t\t}\n\t}\n\tt.Fatalf(\"package did not install\")\n}"} {"input": "package help\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\ntype EvtPool struct {\n\theader DListNode\n}\n\nfunc (this *EvtPool) Init() {\n\tthis.header.Init(nil)\n}\n\nfunc (this *EvtPool) Eat(name string) {\n\tfmt.Printf(\"吃%s\\n\", name)\n}\n\nfunc (this *EvtPool) Post(d IEvent) bool {\n\n\tn := &DListNode{}\n\tn.Init(d)\n\n\tif !d.AddNode(n) {\n\t\treturn false\n\t}\n\n\told_pre := this.header.Pre\n\n\tthis.header.Pre = n\n\tn.Next = &this.header\n\tn.Pre = old_pre\n\told_pre.Next = n\n\n\treturn true\n}\n\nfunc (this *EvtPool) Run() {\n\tfor {\n\t\tif this.header.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\n\t\tn := this.header.Next\n\n\t\tn.Data.(IEvent).Exec(this)\n\n\t\tn.Data.(IEvent).Destroy()\n\t}\n}\n\ntype Evt_eat struct {\n\tEvt_base\n\tFoodName string\n}\n\nfunc (this *Evt_eat) Exec() bool {\n\treturn true\n}\n\n\n\nfunc TestDlist(t *testing.T) ", "output": "{\n\n\tvar g_Pool EvtPool\n\tg_Pool.Init()\n\n\tg_Pool.Post(&Evt_eat{FoodName: \"西瓜\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"葡萄\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"黄瓜\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"大蒜\"})\n\n\tg_Pool.Run()\n}"} {"input": "package testonly\n\n\n\n\nimport (\n\t\"crypto/sha256\"\n)\n\n\n\n\n\n\n\nfunc TransparentHash(key string) []byte {\n\tconst prefixLen = 8\n\tif prefixLen+len(key) > sha256.Size {\n\t\tpanic(\"key too long\")\n\t}\n\tb := make([]byte, sha256.Size)\n\th := HashKey(key)\n\tcopy(b[0:prefixLen], h[0:prefixLen])\n\tcopy(b[prefixLen:], key)\n\treturn b\n}\n\nfunc HashKey(key string) []byte ", "output": "{\n\th := sha256.New()\n\th.Write([]byte(key))\n\treturn h.Sum(nil)\n}"} {"input": "package cmd\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/ghodss/yaml\"\n\t\"github.com/spf13/cobra\"\n)\n\n\n\n\nfunc getErrorForNoName(noNameRequired bool) error {\n\tif noNameRequired {\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"NAME is required\")\n}\n\nfunc prettyprint(b []byte) ([]byte, error) {\n\tvar out bytes.Buffer\n\terr := json.Indent(&out, b, \"\", \" \")\n\treturn out.Bytes(), err\n}\n\nfunc PrintOutput(format string, object interface{}) error {\n\tvar msg string\n\ttmpCluster := object\n\tif format == \"yaml\" {\n\t\ty, err := yaml.Marshal(tmpCluster)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmsg += string(y)\n\t\tfmt.Printf(msg)\n\t} else if format == \"json\" {\n\t\ty, err := json.Marshal(tmpCluster)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpmsg, err := prettyprint(y)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmsg += string(pmsg)\n\t\tfmt.Printf(msg)\n\t}\n\treturn nil\n}\n\nfunc NameFromCommandArgs(cmd *cobra.Command, args []string, noNameRequired bool) (string, error) ", "output": "{\n\tif len(args) == 0 {\n\n\t\treturn \"\", getErrorForNoName(noNameRequired)\n\t}\n\treturn args[0], nil\n}"} {"input": "package service\n\nimport (\n\tgofig \"github.com/akutz/gofig/types\"\n\n\t\"github.com/thecodeteam/rexray/libstorage/api/registry\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/server/handlers\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/server/httputils\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/types\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/utils/schema\"\n)\n\nfunc init() {\n\tregistry.RegisterRouter(&router{})\n}\n\ntype router struct {\n\troutes []types.Route\n}\n\n\n\nfunc (r *router) Init(config gofig.Config) {\n\tr.initRoutes()\n}\n\n\nfunc (r *router) Routes() []types.Route {\n\treturn r.routes\n}\n\nfunc (r *router) initRoutes() {\n\n\tr.routes = []types.Route{\n\n\t\thttputils.NewGetRoute(\n\t\t\t\"services\",\n\t\t\t\"/services\",\n\t\t\tr.servicesList,\n\t\t\thandlers.NewAuthAllSvcsHandler(),\n\t\t\thandlers.NewSchemaValidator(nil, schema.ServiceInfoMapSchema, nil)),\n\n\t\thttputils.NewGetRoute(\n\t\t\t\"serviceInspect\",\n\t\t\t\"/services/{service}\",\n\t\t\tr.serviceInspect,\n\t\t\thandlers.NewServiceValidator(),\n\t\t\thandlers.NewAuthSvcHandler(),\n\t\t\thandlers.NewSchemaValidator(nil, schema.ServiceInfoSchema, nil)),\n\t}\n}\n\nfunc (r *router) Name() string ", "output": "{\n\treturn \"service-router\"\n}"} {"input": "package gluster\n\nimport \"testing\"\n\nfunc init() {\n\tExecRunner = TestRunner{}\n}\n\nfunc TestGetVolumeUsage(t *testing.T) {\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project_pv1\"}\n\n\tvolInfo, _ := getVolumeUsage(\"gl-project-pv1\")\n\n\tequals(t, 49664, volInfo.TotalKiloBytes)\n\tequals(t, 2864, volInfo.UsedKiloBytes)\n}\n\n\n\nfunc TestGetVolumeUsage_LongProjectHighNumber(t *testing.T) {\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project--very--very--long_pv20\"}\n\n\tvolInfo, _ := getVolumeUsage(\"gl-project-very-very-long-pv20\")\n\n\tequals(t, 49664, volInfo.TotalKiloBytes)\n\tequals(t, 2864, volInfo.UsedKiloBytes)\n}\n\nfunc TestCheckVolumeUsage_OK(t *testing.T) {\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project_pv1\"}\n\n\terr := checkVolumeUsage(\"gl-project-pv1\", \"20\")\n\tok(t, err)\n}\n\nfunc TestCheckVolumeUsage_Error(t *testing.T) {\n\toutput = []string{\" 49664 49555 /dev/mapper/vg_mylv_project_pv1\"}\n\n\terr := checkVolumeUsage(\"gl-project-pv1\", \"20\")\n\tassert(t, err != nil, \"Should return error as bigger than threshold\")\n}\n\nfunc TestGetVolumeUsage_LongProject(t *testing.T) ", "output": "{\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project--long_pv1\"}\n\n\tvolInfo, _ := getVolumeUsage(\"gl-project-long-pv1\")\n\n\tequals(t, 49664, volInfo.TotalKiloBytes)\n\tequals(t, 2864, volInfo.UsedKiloBytes)\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\n\t\"github.com/opensourceorg/api/license\"\n)\n\ntype Blobs struct {\n\tLicenses license.Licenses\n\tLicenseIdMap map[string]license.License\n\tLicenseTagMap map[string][]license.License\n}\n\n\n\nfunc Reloader(file string, target *Blobs) {\n\tif err := loadBlob(file, target); err != nil {\n\t\tpanic(err)\n\t}\n\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGHUP)\n\tfor _ = range c {\n\t\tif err := loadBlob(file, target); err != nil {\n\t\t\tlog.Printf(\"Error! Can not reload the JSON! - %s\", err)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\nfunc loadBlob(path string, blob *Blobs) error ", "output": "{\n\tlicenses, err := license.LoadLicensesFiles(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlicenseIdMap := licenses.GetIdMap()\n\tlicenseTagMap := licenses.GetTagMap()\n\n\tblob.Licenses = licenses\n\tblob.LicenseIdMap = licenseIdMap\n\tblob.LicenseTagMap = licenseTagMap\n\n\treturn nil\n}"} {"input": "package goonix\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\n\nfunc TestPortAvailable(t *testing.T) {\n\tn := Network{}\n\tretval, err := n.CheckPort(\"localhost\", 22, 2*time.Second)\n\tif !retval {\n\t\tt.Error(\"Expected true, got false\")\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Expected nil, got %v\", err)\n\t}\n\n}\n\n\n\n\nfunc TestFailedPortAvailable(t *testing.T) ", "output": "{\n\tn := Network{}\n\tretval, err := n.CheckPort(\"fuuuuuuu.com\", 99, 2*time.Second)\n\tif retval {\n\t\tt.Fail()\n\t}\n\tif err == nil {\n\t\tt.Fail()\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/kormat/go-slackapi/config\"\n\t\"github.com/kormat/go-slackapi/users\"\n)\n\ntype UserInfo struct {\n\tArgs struct {\n\t\tID string `description:\"User ID\"`\n\t} `positional-args:\"yes\" required:\"yes\"`\n}\ntype UserList struct{}\n\nvar userInfo UserInfo\nvar userList UserList\n\n\n\nfunc (u *UserInfo) Execute(_ []string) error {\n\tif config.CfgErr != nil {\n\t\treturn config.CfgErr\n\t}\n\tinfo, err := users.Info(u.Args.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(info)\n\treturn nil\n}\n\nfunc (ul *UserList) Execute(_ []string) error {\n\tif config.CfgErr != nil {\n\t\treturn config.CfgErr\n\t}\n\tulist, err := users.List()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor i, u := range ulist {\n\t\tfmt.Printf(\"%d. `%s` (Id: %s)\\n\", i, u.Name, u.ID)\n\t}\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tparser.AddCommand(\"users.info\", \"Show user info\", \"\", &userInfo)\n\tparser.AddCommand(\"users.list\", \"List users\", \"\", &userList)\n}"} {"input": "package utils\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"os\"\n\t\"strconv\"\n)\n\nvar path string\n\nfunc init() {\n\tflag.StringVar(&path, \"path\", \"\", \"Path to the inputfile\")\n\tflag.Parse()\n}\n\ntype Input struct {\n\t*bufio.Scanner\n}\n\n\n\n\nfunc (input *Input) ReadInt() int {\n\tinput.Split(bufio.ScanWords)\n\n\tif input.Scan() {\n\t\tresult, err := strconv.Atoi(input.Text())\n\t\tif err == nil {\n\t\t\treturn result\n\t\t}\n\t}\n\n\treturn 3\n}\n\nfunc (input *Input) ReadInts(size int) []int {\n\tinput.Split(bufio.ScanWords)\n\tints := make([]int, size)\n\n\tfor i := 0; i < size && input.Scan(); i++ {\n\t\tresult, err := strconv.Atoi(input.Text())\n\t\tif err == nil {\n\t\t\tints[i] = result\n\t\t}\n\t}\n\n\treturn ints\n}\n\nfunc (input *Input) ReadString() string {\n\tinput.Split(bufio.ScanWords)\n\n\tif input.Scan() {\n\t\treturn input.Text()\n\t}\n\n\treturn \"\"\n}\n\nfunc (input *Input) ReadStrings(size int) []string {\n\tinput.Split(bufio.ScanWords)\n\n\tstrings := make([]string, size)\n\n\tfor i := 0; i < size && input.Scan(); i++ {\n\t\tstrings[i] = input.Text()\n\t}\n\n\treturn strings\n}\n\nfunc GetInput() (*Input, error) ", "output": "{\n\tif len(path) > 0 {\n\t\tfile, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn &Input{}, err\n\t\t}\n\n\t\treturn &Input{bufio.NewScanner(file)}, nil\n\t}\n\treturn &Input{bufio.NewScanner(os.Stdin)}, nil\n}"} {"input": "package dbr\n\ntype union struct {\n\tbuilder []Builder\n\tall bool\n}\n\n\nfunc Union(builder ...Builder) interface {\n\tBuilder\n\tAs(string) Builder\n} {\n\treturn &union{\n\t\tbuilder: builder,\n\t}\n}\n\n\nfunc UnionAll(builder ...Builder) interface {\n\tBuilder\n\tAs(string) Builder\n} {\n\treturn &union{\n\t\tbuilder: builder,\n\t\tall: true,\n\t}\n}\n\n\n\nfunc (u *union) As(alias string) Builder {\n\treturn as(u, alias)\n}\n\nfunc (u *union) Build(d Dialect, buf Buffer) error ", "output": "{\n\tfor i, b := range u.builder {\n\t\tif i > 0 {\n\t\t\tbuf.WriteString(\" UNION \")\n\t\t\tif u.all {\n\t\t\t\tbuf.WriteString(\"ALL \")\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(placeholder)\n\t\tbuf.WriteValue(b)\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\tstrings_app \"github.com/utrack/clay/integration/client_cancel_request/app/strings\"\n\tstrings_pb \"github.com/utrack/clay/integration/client_cancel_request/pkg/strings\"\n)\n\n\n\nfunc testServer() *httptest.Server {\n\tmux := http.NewServeMux()\n\tdesc := strings_app.NewStrings().GetDescription()\n\tdesc.RegisterHTTP(mux)\n\tmux.Handle(\"/swagger.json\", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application/javascript\")\n\t\tw.Write(desc.SwaggerDef())\n\t}))\n\n\tts := httptest.NewServer(mux)\n\treturn ts\n}\n\nfunc TestCancelRequest(t *testing.T) ", "output": "{\n\tts := testServer()\n\terrlog := bytes.NewBuffer([]byte{})\n\tts.Config.ErrorLog = log.New(errlog, \"\", 0)\n\tdefer func() {\n\t\tts.Close()\n\t\tif errlog.Len() > 0 {\n\t\t\tt.Fatalf(\"expected no errors, got: %s\", errlog.Bytes())\n\t\t}\n\t}()\n\n\thttpClient := ts.Client()\n\tclient := strings_pb.NewStringsHTTPClient(httpClient, ts.URL)\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)\n\tdefer cancel()\n\tclient.ToUpper(ctx, &strings_pb.String{Str: strings.Repeat(\"s\", 10*1024)})\n}"} {"input": "package service\n\nimport (\n\t\"github.com/JacobXie/leanote/app/db\"\n\t\"github.com/JacobXie/leanote/app/info\"\n\t\"gopkg.in/mgo.v2/bson\"\n)\n\n\ntype NoteContentHistoryService struct {\n}\n\n\nvar maxSize = 10\n\n\n\nfunc (this *NoteContentHistoryService) AddHistory(noteId, userId string, eachHistory info.EachHistory) {\n\tif eachHistory.Content == \"\" {\n\t\treturn\n\t}\n\n\thistory := info.NoteContentHistory{}\n\tdb.GetByIdAndUserId(db.NoteContentHistories, noteId, userId, &history)\n\tif history.NoteId == \"\" {\n\t\tthis.newHistory(noteId, userId, eachHistory)\n\t} else {\n\t\tl := len(history.Histories)\n\t\tif l >= maxSize {\n\t\t\thistory.Histories = history.Histories[:maxSize]\n\t\t}\n\t\tnewHistory := []info.EachHistory{eachHistory}\n\t\tnewHistory = append(newHistory, history.Histories...) \n\t\thistory.Histories = newHistory\n\n\t\tdb.UpdateByIdAndUserId(db.NoteContentHistories, noteId, userId, history)\n\t}\n\treturn\n}\n\n\nfunc (this *NoteContentHistoryService) newHistory(noteId, userId string, eachHistory info.EachHistory) {\n\thistory := info.NoteContentHistory{NoteId: bson.ObjectIdHex(noteId),\n\t\tUserId: bson.ObjectIdHex(userId),\n\t\tHistories: []info.EachHistory{eachHistory},\n\t}\n\n\tdb.Insert(db.NoteContentHistories, history)\n}\n\n\n\n\nfunc (this *NoteContentHistoryService) ListHistories(noteId, userId string) []info.EachHistory ", "output": "{\n\thistories := info.NoteContentHistory{}\n\tdb.GetByIdAndUserId(db.NoteContentHistories, noteId, userId, &histories)\n\treturn histories.Histories\n}"} {"input": "package iso20022\n\n\ntype TotalFeesAndTaxes40 struct {\n\n\tTotalOverheadApplied *ActiveCurrencyAndAmount `xml:\"TtlOvrhdApld,omitempty\"`\n\n\tTotalFees *ActiveCurrencyAndAmount `xml:\"TtlFees,omitempty\"`\n\n\tTotalTaxes *ActiveCurrencyAndAmount `xml:\"TtlTaxs,omitempty\"`\n\n\tCommercialAgreementReference *Max35Text `xml:\"ComrclAgrmtRef,omitempty\"`\n\n\tIndividualFee []*Fee2 `xml:\"IndvFee,omitempty\"`\n\n\tIndividualTax []*Tax31 `xml:\"IndvTax,omitempty\"`\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalOverheadApplied(value, currency string) {\n\tt.TotalOverheadApplied = NewActiveCurrencyAndAmount(value, currency)\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalFees(value, currency string) {\n\tt.TotalFees = NewActiveCurrencyAndAmount(value, currency)\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalTaxes(value, currency string) {\n\tt.TotalTaxes = NewActiveCurrencyAndAmount(value, currency)\n}\n\n\n\nfunc (t *TotalFeesAndTaxes40) AddIndividualFee() *Fee2 {\n\tnewValue := new(Fee2)\n\tt.IndividualFee = append(t.IndividualFee, newValue)\n\treturn newValue\n}\n\nfunc (t *TotalFeesAndTaxes40) AddIndividualTax() *Tax31 {\n\tnewValue := new(Tax31)\n\tt.IndividualTax = append(t.IndividualTax, newValue)\n\treturn newValue\n}\n\nfunc (t *TotalFeesAndTaxes40) SetCommercialAgreementReference(value string) ", "output": "{\n\tt.CommercialAgreementReference = (*Max35Text)(&value)\n}"} {"input": "package queue\n\nimport \"fmt\"\n\ntype Queue struct {\n\tElems []interface{}\n\tTop int\n\tBottom int\n\tMaxlen int\n\tFull bool\n}\n\n\n\n\nfunc (q *Queue) EnQueue(e interface{}) {\n\n\tif q.Maxlen == q.Bottom - q.Top {\n\t\tq.Bottom = q.Top\n\t\tq.Full = true\n\t}\n\tq.Elems[q.Bottom] = e\n\tq.Bottom++\n\n}\n\nfunc (q *Queue) DeQueue() {\n\n\tif q.Bottom > q.Top {\n\t\tq.Top++\n\t}\n\n}\n\nfunc (q *Queue) Len() int {\n\treturn len(q.Elems)\n}\n\nfunc New(maxLen int) *Queue ", "output": "{\n\tq := &Queue{\n\t\tElems: make([]interface{}, maxLen),\n\t\tTop: 0,\n\t\tBottom: 0,\n\t\tMaxlen: maxLen,\n\t}\n\n\tfmt.Printf(\"Queue: %d\\n\", q.Maxlen)\n\treturn q\n}"} {"input": "package v1\n\nimport (\n\tcommon \"github.com/kubeflow/common/pkg/apis/common/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\n\n\n\n\nfunc addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}\n\n\nfunc setDefaultsTypeLauncher(spec *common.ReplicaSpec) {\n\tif spec != nil && spec.RestartPolicy == \"\" {\n\t\tspec.RestartPolicy = DefaultRestartPolicy\n\t}\n}\n\n\nfunc setDefaultsTypeWorker(spec *common.ReplicaSpec) {\n\tif spec != nil && spec.RestartPolicy == \"\" {\n\t\tspec.RestartPolicy = DefaultRestartPolicy\n\t}\n}\n\nfunc SetDefaults_MPIJob(mpiJob *MPIJob) {\n\tif mpiJob.Spec.CleanPodPolicy == nil {\n\t\tnone := common.CleanPodPolicyNone\n\t\tmpiJob.Spec.CleanPodPolicy = &none\n\t}\n\n\tsetDefaultsTypeLauncher(mpiJob.Spec.MPIReplicaSpecs[MPIReplicaTypeLauncher])\n\n\tsetDefaultsTypeWorker(mpiJob.Spec.MPIReplicaSpecs[MPIReplicaTypeWorker])\n}\n\nfunc Int32(v int32) *int32 ", "output": "{\n\treturn &v\n}"} {"input": "package hpg\n\n\ntype BudgetAPIParams struct {\n\tCommonParams\n}\n\n\n\n\nfunc (p *BudgetAPIParams) Path() string ", "output": "{\n\treturn \"budget\"\n}"} {"input": "package dbmapper\n\ntype ProjectMapper struct {\n}\n\n\n\nfunc NewProjectMapper() *ProjectMapper ", "output": "{\n\treturn &ProjectMapper{}\n}"} {"input": "package fenwick\n\n\n\ntype Fenwick struct {\n\ttree []int\n}\n\n\nfunc NewFenwick(n int) *Fenwick {\n\tfen := &Fenwick{\n\t\ttree: make([]int, n),\n\t}\n\tfor i := range fen.tree {\n\t\tfen.tree[i] = 1\n\t}\n\treturn fen\n}\n\n\nfunc (fen *Fenwick) Sum(index int) int {\n\tsum := 1\n\tindex++\n\tfor index > 0 {\n\t\tsum *= fen.tree[index-1]\n\t\tindex -= lsb(index)\n\t}\n\treturn sum\n}\n\n\nfunc lsb(x int) int {\n\treturn x & -x\n}\n\n\n\n\n\nfunc (fen *Fenwick) Size() int {\n\treturn len(fen.tree)\n}\n\nfunc (fen *Fenwick) Update(index, value int) ", "output": "{\n\tindex++\n\tfor index <= fen.Size() {\n\t\tfen.tree[index-1] *= value\n\t\tindex += lsb(index)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/ginuerzh/gosocks5\"\n\t\"github.com/gorilla/websocket\"\n\t\"log\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype WSConn struct {\n\t*websocket.Conn\n\trb []byte\n}\n\nfunc NewWSConn(conn *websocket.Conn) *WSConn {\n\tc := &WSConn{\n\t\tConn: conn,\n\t}\n\n\treturn c\n}\n\nfunc (conn *WSConn) Read(b []byte) (n int, err error) {\n\tif len(conn.rb) == 0 {\n\t\t_, conn.rb, err = conn.ReadMessage()\n\t}\n\tn = copy(b, conn.rb)\n\tconn.rb = conn.rb[n:]\n\n\n\treturn\n}\n\nfunc (conn *WSConn) Write(b []byte) (n int, err error) {\n\terr = conn.WriteMessage(websocket.BinaryMessage, b)\n\tn = len(b)\n\n\treturn\n}\n\nfunc (conn *WSConn) SetDeadline(t time.Time) error {\n\tif err := conn.SetReadDeadline(t); err != nil {\n\t\treturn err\n\t}\n\treturn conn.SetWriteDeadline(t)\n}\n\ntype WSServer struct {\n\tAddr string\n}\n\nvar upgrader = websocket.Upgrader{\n\tReadBufferSize: 8192,\n\tWriteBufferSize: 8192,\n\tCheckOrigin: func(r *http.Request) bool { return true },\n}\n\n\n\nfunc (s *WSServer) ListenAndServe() error {\n\thttp.HandleFunc(\"/\", s.handle)\n\treturn http.ListenAndServe(s.Addr, nil)\n}\n\nfunc (s *WSServer) handle(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tc := gosocks5.ServerConn(NewWSConn(conn), serverConfig)\n\tsocks5Handle(c)\n}"} {"input": "package dev\n\nimport \"fmt\"\n\n\n\ntype Configuration struct {\n\tid uint32\n\tnodes []*Node\n\tn int\n\tmgr *Manager\n\tqspec QuorumSpec\n\terrs chan CallGRPCError\n}\n\n\n\nfunc (c *Configuration) SubError() <-chan CallGRPCError {\n\treturn c.errs\n}\n\n\nfunc (c *Configuration) ID() uint32 {\n\treturn c.id\n}\n\n\n\n\nfunc (c *Configuration) NodeIDs() []uint32 {\n\tids := make([]uint32, len(c.nodes))\n\tfor i, node := range c.nodes {\n\t\tids[i] = node.ID()\n\t}\n\treturn ids\n}\n\n\n\nfunc (c *Configuration) Nodes() []*Node {\n\treturn c.nodes\n}\n\n\nfunc (c *Configuration) Size() int {\n\treturn c.n\n}\n\nfunc (c *Configuration) String() string {\n\treturn fmt.Sprintf(\"configuration %d\", c.id)\n}\n\n\n\n\n\nfunc Equal(a, b *Configuration) bool { return a.id == b.id }\n\n\n\n\nfunc NewTestConfiguration(q, n int) *Configuration {\n\treturn &Configuration{\n\t\tnodes: make([]*Node, n),\n\t}\n}\n\nfunc (c *Configuration) tstring() string ", "output": "{\n\treturn fmt.Sprintf(\"config-%d\", c.id)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"github.com/paddycarey/gack\"\n)\n\n\n\n\ntype EchoHandler struct{}\n\n\n\n\n\n\n\n\nfunc (h *EchoHandler) Handle(sc *gack.SlashCommand) (string, error) {\n\treturn fmt.Sprintf(\"%s %s\", sc.Command, sc.Text), nil\n}\n\nfunc main() {\n\tmux := http.NewServeMux()\n\n\tsrv := gack.NewServer(\n\t\t[]string{os.Getenv(\"SLACK_API_TOKEN\")},\n\t\t[]gack.Handler{&EchoHandler{}},\n\t)\n\n\tmux.Handle(\"/\", srv)\n\thttp.ListenAndServe(\":3000\", mux)\n}\n\nfunc (h *EchoHandler) CanHandle(sc *gack.SlashCommand) bool ", "output": "{\n\treturn true\n}"} {"input": "package server\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n)\n\ntype Rest struct {\n\tchannels map[string]*Channel\n}\n\n\n\nfunc (self *Rest) PostOnly(h http.HandlerFunc) http.HandlerFunc {\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == \"POST\" {\n\t\t\th(w, r)\n\t\t\treturn\n\t\t}\n\t\thttp.Error(w, \"post only\", http.StatusMethodNotAllowed)\n\t}\n}\n\nfunc (self *Rest) restHandler(w http.ResponseWriter, r *http.Request) {\n\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err := r.Body.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\tchannel := r.URL.Query().Get(\"channel\")\n\tsession := r.Header.Get(\"session\");\n\n\tlog.Printf(\"SessionID: %s\", session)\n\n\tmsg := &Message{Channel: channel, Body: string(body), session: session}\n\tif ch, ok := self.channels[channel]; ok {\n\t\tch.sendAll <- msg\n\t}\n\tlog.Printf(\"[REST] body: %s, channel: %s\", body, channel)\n}\n\nfunc (self *Rest) ListenRest() {\n\n\tlog.Println(\"Listening server(REST)...\")\n\n\thttp.HandleFunc(\"/rest\", self.PostOnly(self.restHandler))\n}\n\nfunc NewRestServer(server *Server) *Rest ", "output": "{\n\treturn &Rest{server.channels}\n}"} {"input": "package componentstatus\n\nimport (\n\t\"crypto/tls\"\n\t\"sync\"\n\t\"time\"\n\n\tutilnet \"k8s.io/apimachinery/pkg/util/net\"\n\t\"k8s.io/kubernetes/pkg/probe\"\n\thttpprober \"k8s.io/kubernetes/pkg/probe/http\"\n)\n\nconst (\n\tprobeTimeOut = 20 * time.Second\n)\n\ntype ValidatorFn func([]byte) error\n\ntype Server struct {\n\tAddr string\n\tPort int\n\tPath string\n\tEnableHTTPS bool\n\tTLSConfig *tls.Config\n\tValidate ValidatorFn\n\tProber httpprober.Prober\n\tOnce sync.Once\n}\n\ntype ServerStatus struct {\n\tComponent string `json:\"component,omitempty\"`\n\tHealth string `json:\"health,omitempty\"`\n\tHealthCode probe.Result `json:\"healthCode,omitempty\"`\n\tMsg string `json:\"msg,omitempty\"`\n\tErr string `json:\"err,omitempty\"`\n}\n\n\n\nfunc (server *Server) DoServerCheck() (probe.Result, string, error) ", "output": "{\n\tserver.Once.Do(func() {\n\t\tif server.Prober != nil {\n\t\t\treturn\n\t\t}\n\t\tconst followNonLocalRedirects = true\n\t\tserver.Prober = httpprober.NewWithTLSConfig(server.TLSConfig, followNonLocalRedirects)\n\t})\n\n\tscheme := \"http\"\n\tif server.EnableHTTPS {\n\t\tscheme = \"https\"\n\t}\n\turl := utilnet.FormatURL(scheme, server.Addr, server.Port, server.Path)\n\n\tresult, data, err := server.Prober.Probe(url, nil, probeTimeOut)\n\n\tif err != nil {\n\t\treturn probe.Unknown, \"\", err\n\t}\n\tif result == probe.Failure {\n\t\treturn probe.Failure, string(data), err\n\t}\n\tif server.Validate != nil {\n\t\tif err := server.Validate([]byte(data)); err != nil {\n\t\t\treturn probe.Failure, string(data), err\n\t\t}\n\t}\n\treturn result, string(data), nil\n}"} {"input": "package parser\n\ntype sField struct {\n\tName string\n\tType string\n\tTag string\n\tStruct sStruct\n\tInitialName string\n\n\tattr bool\n\tpointer bool\n\tarray bool\n\trequired bool\n\tnillable bool\n}\n\ntype mapofFields map[string]sField\n\nfunc (m mapofFields) add(i string, s sField) bool {\n\tif i == \"\" || s.Type == \"\" {\n\t\treturn false\n\t}\n\n\ts.resolveType()\n\ts.resolveTag()\n\ts.resolveName(i)\n\tm[s.Name] = s\n\n\treturn true\n}\n\nfunc (s *sField) resolveName(i string) {\n\tif s.Name == \"\" {\n\t\treturn\n\t}\n\ts.InitialName = makeExported(normalize(removeNS(i)))\n\ts.Name = makeExported(lintName(normalize(removeNS(i))))\n}\n\nfunc (s *sField) resolveType() {\n\tif s.nillable && s.required {\n\t\ts.Type = toGoType(makeUnexported(lintName(removeNS(s.Type + \"ReqNil\"))))\n\t\treturn\n\t}\n\n\ttn := makeUnexported(lintName(removeNS(s.Type)))\n\tif s.array {\n\t\ts.Type = \"[]\" + toGoType(tn)\n\t\treturn\n\t}\n\tif s.pointer {\n\t\ts.Type = toGoPointerType(tn)\n\t\treturn\n\t}\n\ts.Type = toGoPointerType(tn)\n}\n\n\n\nfunc (s *sField) resolveTag() ", "output": "{\n\tif s.Name == \"\" {\n\t\treturn\n\t}\n\n\tif s.attr {\n\t\ts.Tag = \"`\" + `xml:\"` + s.Name + `,attr\"` + \"`\"\n\t\treturn\n\t}\n\n\ts.Tag = \"`\" + `xml:\"` + s.Name + `\"` + \"`\"\n}"} {"input": "package s0104\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc Answer_Old() interface{} {\n\tn := 2\n\tfcurr := new(big.Int).SetInt64(1)\n\tfprev := new(big.Int).SetInt64(1)\n\ttmp := new(big.Int)\n\tfor {\n\t\ttmp.Add(fcurr, fprev)\n\t\tfcurr, fprev, tmp = tmp, fcurr, fprev\n\t\tn++\n\t\tstr := fcurr.String()\n\t\tif len(str) >= 9 && IsAllDigits(str[:9]) && IsAllDigits(str[len(str)-9:]) {\n\t\t\treturn n\n\t\t}\n\t}\n}\n\n\n\nfunc Answer() interface{} {\n\tn := 2\n\n\tfCurrBack := int64(1)\n\tfPrevBack := int64(1)\n\n\tfCurrFront := float64(1)\n\tfPrevFront := float64(1)\n\n\tfor {\n\t\tfCurrBack, fPrevBack = (fCurrBack+fPrevBack)%1e9, fCurrBack\n\t\tfCurrFront, fPrevFront = fCurrFront+fPrevFront, fCurrFront\n\t\tif fCurrFront >= 1e9 {\n\t\t\tfCurrFront /= 10\n\t\t\tfPrevFront /= 10\n\t\t}\n\t\tn++\n\t\tif IsAllDigits(fmt.Sprintf(\"%d\", fCurrBack)) &&\n\t\t\tIsAllDigits(fmt.Sprintf(\"%d\", int(fCurrFront))) {\n\t\t\treturn n\n\t\t}\n\t}\n}\n\nfunc IsAllDigits(s string) bool ", "output": "{\n\tif len(s) < 9 {\n\t\treturn false\n\t}\n\tvar set [9]bool\n\tfor _, r := range s {\n\t\tif r == '0' {\n\t\t\treturn false\n\t\t}\n\t\tif set[r-'1'] {\n\t\t\treturn false\n\t\t}\n\t\tset[r-'1'] = true\n\t}\n\treturn true\n}"} {"input": "package cfbackup\n\nimport (\n\tghttp \"github.com/pivotalservices/gtils/http\"\n)\n\n\n\n\nfunc GetUploader(backupContext BackupContext) (uploader httpUploader) ", "output": "{\n\tuploader = ghttp.LargeMultiPartUpload\n\n\tif backupContext.IsS3 {\n\t\tuploader = ghttp.MultiPartUpload\n\t}\n\treturn\n}"} {"input": "package space_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestSpace(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Space Suite\")\n}"} {"input": "package relay\n\nimport (\n\t\"encoding/gob\"\n\t\"encoding/json\"\n\t\"io\"\n)\n\n\n\n\ntype Serializer interface {\n\tContentType() string\n\tRelayEncode(io.Writer, interface{}) error\n\tRelayDecode(io.Reader, interface{}) error\n}\n\n\ntype GOBSerializer struct{}\n\nfunc (*GOBSerializer) ContentType() string {\n\treturn \"binary/gob\"\n}\n\nfunc (*GOBSerializer) RelayDecode(r io.Reader, o interface{}) error {\n\tdec := gob.NewDecoder(r)\n\treturn dec.Decode(o)\n}\n\n\ntype JSONSerializer struct{}\n\nfunc (*JSONSerializer) ContentType() string {\n\treturn \"text/json\"\n}\n\nfunc (*JSONSerializer) RelayEncode(w io.Writer, e interface{}) error {\n\tenc := json.NewEncoder(w)\n\treturn enc.Encode(e)\n}\n\nfunc (*JSONSerializer) RelayDecode(r io.Reader, o interface{}) error {\n\tdec := json.NewDecoder(r)\n\treturn dec.Decode(o)\n}\n\nfunc (*GOBSerializer) RelayEncode(w io.Writer, e interface{}) error ", "output": "{\n\tenc := gob.NewEncoder(w)\n\treturn enc.Encode(e)\n}"} {"input": "package main\n\n\n\nfunc Cook(name string) ", "output": "{\n\treport(name, \"starting work\")\n\tfor {\n\t\torder := <-Orders\n do(name, \"cooking for \" + order.customer, 12E9)\n order.preparedBy = name\n order.reply <- order\n\t}\n}"} {"input": "package main\nimport (\n\"fmt\"\n\"time\"\n)\n\ntype Rocket struct{\n Name string\n}\n\nfunc (r *Rocket) Launch(){\n fmt.Printf(\"%s is Lanching\\n\",r.Name)\n}\n\n\ntype InSet struct{\n word []uint64\n}\n\n\n\n\n\nfunc main() {\n r1:=Rocket{\"Mike\"}\n r1.Launch()\n time.AfterFunc(2*time.Second,func() {\n r1.Launch()\n })\n time.Sleep(3*time.Second)\n}\n\nfunc (s *InSet) Has(x uint64) bool", "output": "{\n word,bit:=x/64,uint64(x%64)\n return word uof {\n\t\t\textreme = append(extreme, v)\n\t\t} else if v < lif || v > uif {\n\t\t\tmild = append(mild, v)\n\t\t}\n\t}\n\n\treturn Outliers{mild, extreme}, nil\n}"} {"input": "package handlers\n\nimport (\n\t\"time\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/emicklei/go-restful\"\n\t\"github.com/quintilesims/layer0/common/config\"\n)\n\nfunc LogRequest(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {\n\tstart := time.Now()\n\tchain.ProcessFilter(req, resp)\n\tduration := time.Since(start)\n\n\tif req.Request.URL.String() != \"/health\" {\n\t\tlogrus.Infof(\"request %s %s (%v) %v\", req.Request.Method, req.Request.URL, resp.StatusCode(), duration)\n\t}\n}\n\n\n\nfunc EnableCORS(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {\n\tif origin := req.Request.Header.Get(\"Origin\"); origin != \"\" {\n\t\tresp.AddHeader(\"Access-Control-Allow-Origin\", origin)\n\t\tresp.AddHeader(\"Access-Control-Allow-Credentials\", \"true\")\n\t\tresp.AddHeader(\"Access-Control-Allow-Headers\", \"Origin, Content-Type, X-Auth-Token, Authorization\")\n\t}\n\n\tchain.ProcessFilter(req, resp)\n}\n\nfunc AddVersionHeader(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) ", "output": "{\n\tresp.AddHeader(\"Version\", config.APIVersion())\n\tchain.ProcessFilter(req, resp)\n}"} {"input": "package command\n\nimport (\n\t\"strings\"\n\n\t\"github.com/mitchellh/cli\"\n\t\"github.com/posener/complete\"\n)\n\nvar (\n\t_ cli.Command = (*PrintCommand)(nil)\n\t_ cli.CommandAutocomplete = (*PrintCommand)(nil)\n)\n\ntype PrintCommand struct {\n\t*BaseCommand\n}\n\nfunc (c *PrintCommand) Synopsis() string {\n\treturn \"Prints runtime configurations\"\n}\n\nfunc (c *PrintCommand) Help() string {\n\thelpText := `\nUsage: vault print \n\n\tThis command groups subcommands for interacting with Vault's runtime values.\n\nSubcommands:\n\ttoken Token currently in use\n`\n\treturn strings.TrimSpace(helpText)\n}\n\nfunc (c *PrintCommand) AutocompleteArgs() complete.Predictor {\n\treturn nil\n}\n\n\n\nfunc (c *PrintCommand) Run(args []string) int {\n\treturn cli.RunResultHelp\n}\n\nfunc (c *PrintCommand) AutocompleteFlags() complete.Flags ", "output": "{\n\treturn nil\n}"} {"input": "package hashgraph\n\nimport (\n\t\"bytes\"\n\t\"sort\"\n\n\t\"github.com/mosaicnetworks/babble/src/crypto\"\n\t\"github.com/mosaicnetworks/babble/src/peers\"\n\t\"github.com/ugorji/go/codec\"\n)\n\n\ntype Frame struct {\n\tRound int \n\tPeers []*peers.Peer \n\tRoots map[string]*Root \n\tEvents []*FrameEvent \n\tPeerSets map[int][]*peers.Peer \n\tTimestamp int64 \n}\n\n\n\nfunc (f *Frame) SortedFrameEvents() []*FrameEvent {\n\tsorted := SortedFrameEvents{}\n\tfor _, r := range f.Roots {\n\t\tsorted = append(sorted, r.Events...)\n\t}\n\tsorted = append(sorted, f.Events...)\n\tsort.Sort(sorted)\n\treturn sorted\n}\n\n\nfunc (f *Frame) Marshal() ([]byte, error) {\n\tb := new(bytes.Buffer)\n\tjh := new(codec.JsonHandle)\n\tjh.Canonical = true\n\tenc := codec.NewEncoder(b, jh)\n\n\tif err := enc.Encode(f); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b.Bytes(), nil\n}\n\n\n\n\n\nfunc (f *Frame) Hash() ([]byte, error) {\n\thashBytes, err := f.Marshal()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn crypto.SHA256(hashBytes), nil\n}\n\nfunc (f *Frame) Unmarshal(data []byte) error ", "output": "{\n\tb := bytes.NewBuffer(data)\n\tjh := new(codec.JsonHandle)\n\tjh.Canonical = true\n\tdec := codec.NewDecoder(b, jh)\n\n\tif err := dec.Decode(f); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\n\t\"gopkg.in/stretchr/testify.v1/mock\"\n)\n\ntype Printer interface {\n\tHelp()\n\tVersion()\n\tMessage(msg string)\n\tError(err error)\n\tCommands()\n}\n\ntype TextPrinter struct {\n\tversion string\n}\n\nfunc NewTextPrinter(version string) *TextPrinter {\n\treturn &TextPrinter{version}\n}\n\nfunc (p *TextPrinter) Help() {\n\thelpText := `Name:\n\tfiz - a file wizard\n\nVersion:\n\t` + p.version + `\n\nUsage:\n\tfiz \n\n`\n\tp.Message(helpText)\n\tp.Commands()\n}\n\nfunc (p *TextPrinter) Version() {\n\tfmt.Println(\"fiz\", p.version)\n}\n\nfunc (p *TextPrinter) Message(msg string) {\n\tfmt.Print(msg)\n}\n\n\n\nfunc (p *TextPrinter) Commands() {\n\tp.Message(COMMANDS_MSG)\n}\n\n\ntype MockPrinter struct {\n\tmock.Mock\n}\n\nfunc NewMockPrinter() *MockPrinter {\n\treturn &MockPrinter{}\n}\n\nfunc (m *MockPrinter) Help() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Version() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Message(msg string) {\n\tm.Called(msg)\n}\n\nfunc (m *MockPrinter) Error(err error) {\n\tm.Called(err)\n}\n\nfunc (m *MockPrinter) Commands() {\n\tm.Called()\n}\n\nfunc (p *TextPrinter) Error(err error) ", "output": "{\n\tfmt.Println(\"Error: \", err)\n}"} {"input": "package funcmap\n\nconst (\n\tsimpleFuncDocTemplate = \"simpleFuncDoc\"\n\tnestedFuncDocTemplate = \"nestedFuncDoc\"\n)\n\ntype FuncDoc struct {\n\tName string\n\tText string\n\tExample string\n\n\tNestedFuncs []FuncDoc\n}\n\n\n\nvar (\n\tFuncDocTemplates = `\n{{ define \"simpleFuncDoc.tmpl\" -}}\n──────────────────────────────────\n\nFunction '\n{{- if exists . \"parent\" }}\n {{- .parent.Name }}.\n{{- end }}\n{{- .Name }}'\n-- {{ .Example }}\n\n{{ .Text }}\n\n{{ end }}\n\n{{ define \"nestedFuncDoc.tmpl\" -}}\n──────────────────────────────────────\n\nFunction package '{{ .Name }}'\n\n{{ .Text }}\n\n Nested functions:\n{{ range .NestedFuncs }}\n {{- indentTemplate .Template . $ 4 }}\n{{ end }}\n{{ end }}\n\t`\n)\n\nfunc (fd FuncDoc) Template() string ", "output": "{\n\tif fd.NestedFuncs == nil || len(fd.NestedFuncs) == 0 {\n\t\treturn simpleFuncDocTemplate\n\t} else {\n\t\treturn nestedFuncDocTemplate\n\t}\n}"} {"input": "package common_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestCommon(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Common Suite\")\n}"} {"input": "package pep\n\nimport \"testing\"\n\n\n\nfunc TestStaticResolver(t *testing.T) ", "output": "{\n\tr := newStaticResolver(virtualServerAddress,\n\t\t\"192.0.2.1\",\n\t\t\"192.0.2.2\",\n\t\t\"192.0.2.3\",\n\t)\n\tif r == nil {\n\t\tt.Fatalf(\"expected pointer to static resolver but got %v\", r)\n\t}\n\n\tw, err := r.Resolve(virtualServerAddress)\n\tif err != nil {\n\t\tt.Errorf(\"expected no error but got %s\", err)\n\t}\n\n\tif w == nil {\n\t\tt.Errorf(\"expected pointer to static watcher but got %v\", w)\n\t}\n\n\t_, err = r.Resolve(\"wrong.name\")\n\tif err == nil {\n\t\tt.Errorf(\"expected error but got nothing\")\n\t}\n}"} {"input": "package eventbreakpoints\n\n\n\nimport (\n\t\"context\"\n\n\t\"github.com/chromedp/cdproto/cdp\"\n)\n\n\n\ntype SetInstrumentationBreakpointParams struct {\n\tEventName string `json:\"eventName\"` \n}\n\n\n\n\n\n\n\nfunc SetInstrumentationBreakpoint(eventName string) *SetInstrumentationBreakpointParams {\n\treturn &SetInstrumentationBreakpointParams{\n\t\tEventName: eventName,\n\t}\n}\n\n\nfunc (p *SetInstrumentationBreakpointParams) Do(ctx context.Context) (err error) {\n\treturn cdp.Execute(ctx, CommandSetInstrumentationBreakpoint, p, nil)\n}\n\n\n\ntype RemoveInstrumentationBreakpointParams struct {\n\tEventName string `json:\"eventName\"` \n}\n\n\n\n\n\n\n\n\nfunc RemoveInstrumentationBreakpoint(eventName string) *RemoveInstrumentationBreakpointParams {\n\treturn &RemoveInstrumentationBreakpointParams{\n\t\tEventName: eventName,\n\t}\n}\n\n\n\n\n\nconst (\n\tCommandSetInstrumentationBreakpoint = \"EventBreakpoints.setInstrumentationBreakpoint\"\n\tCommandRemoveInstrumentationBreakpoint = \"EventBreakpoints.removeInstrumentationBreakpoint\"\n)\n\nfunc (p *RemoveInstrumentationBreakpointParams) Do(ctx context.Context) (err error) ", "output": "{\n\treturn cdp.Execute(ctx, CommandRemoveInstrumentationBreakpoint, p, nil)\n}"} {"input": "package config\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/dnephin/configtf\"\n\tpth \"github.com/dnephin/configtf/path\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype ComposeConfig struct {\n\tFiles []string\n\tProject string `config:\"required\"`\n\tStopGrace int\n\tDependent\n\tAnnotations\n}\n\n\nfunc (c *ComposeConfig) StopGraceString() string {\n\treturn strconv.Itoa(c.StopGrace)\n}\n\n\n\n\nfunc (c *ComposeConfig) String() string {\n\treturn fmt.Sprintf(\"Run Compose project %q from: %v\",\n\t\tc.Project, strings.Join(c.Files, \", \"))\n}\n\n\nfunc (c *ComposeConfig) Resolve(resolver Resolver) (Resource, error) {\n\tconf := *c\n\tvar err error\n\tconf.Files, err = resolver.ResolveSlice(c.Files)\n\tif err != nil {\n\t\treturn &conf, err\n\t}\n\tconf.Project, err = resolver.Resolve(c.Project)\n\treturn &conf, err\n}\n\nfunc composeFromConfig(name string, values map[string]interface{}) (Resource, error) {\n\tcompose := &ComposeConfig{Project: \"{unique}\", StopGrace: 5}\n\treturn compose, configtf.Transform(name, values, compose)\n}\n\nfunc init() {\n\tRegisterResource(\"compose\", composeFromConfig)\n}\n\nfunc (c *ComposeConfig) Validate(path pth.Path, config *Config) *pth.Error ", "output": "{\n\treturn nil\n}"} {"input": "package jdh\n\nimport (\n \"fmt\"\n \"sync/atomic\"\n \"time\"\n \"runtime\"\n)\n\n\n\n\n\nfunc CheckHang(message string, args ...interface{}) func() ", "output": "{\n done := int32(0)\n go func() {\n\n \n time.Sleep(1000 * time.Millisecond)\n if atomic.LoadInt32(&done) != 0 {\n return\n }\n\n \n for atomic.LoadInt32(&done) == 0 {\n fmt.Printf(message, args...)\n fmt.Printf(\"\\t There are %v live goroutines.\\n\", runtime.NumGoroutine())\n time.Sleep(1000 * time.Millisecond)\n }\n\n }()\n\n \n return func() {\n atomic.StoreInt32(&done, 1)\n }\n\n}"} {"input": "package core\n\nimport (\n\t\"bytes\"\n)\n\ntype RYOT struct {\n\tTerm term\n\tSwitchTo *state\n\tWait Seconds\n\tTime Seconds\n}\n\n\n\nfunc (cmd *RYOT) String() string ", "output": "{\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"RYOT\")\n\tcmd.Term.write(&buffer)\n\tbuffer.WriteRune(' ')\n\tbuffer.WriteString(cmd.SwitchTo.di())\n\tcmd.Wait.write(&buffer, \"w\")\n\tcmd.Time.write(&buffer, \"t\")\n\n\treturn buffer.String()\n}"} {"input": "package os\n\nimport (\n\t\"syscall\"\n)\n\n\n\n\n\n\n\nfunc Stat(name string) (FileInfo, error) {\n\tvar fs fileStat\n\terr := syscall.Stat(name, &fs.sys)\n\tif err != nil {\n\t\treturn nil, &PathError{\"stat\", name, err}\n\t}\n\tfillFileStatFromSys(&fs, name)\n\treturn &fs, nil\n}\n\n\n\n\n\nfunc Lstat(name string) (FileInfo, error) {\n\tvar fs fileStat\n\terr := syscall.Lstat(name, &fs.sys)\n\tif err != nil {\n\t\treturn nil, &PathError{\"lstat\", name, err}\n\t}\n\tfillFileStatFromSys(&fs, name)\n\treturn &fs, nil\n}\n\nfunc (f *File) Stat() (FileInfo, error) ", "output": "{\n\tif f == nil {\n\t\treturn nil, ErrInvalid\n\t}\n\tvar fs fileStat\n\terr := f.pfd.Fstat(&fs.sys)\n\tif err != nil {\n\t\treturn nil, &PathError{\"stat\", f.name, err}\n\t}\n\tfillFileStatFromSys(&fs, f.name)\n\treturn &fs, nil\n}"} {"input": "package tests\n\nimport (\n\t\"go2o/core/infrastructure/domain\"\n\t\"testing\"\n)\n\n\nfunc TestMasterPwd(t *testing.T) {\n\tuser := \"master\"\n\tpwd := \"123456\"\n\tsha1 := domain.Sha1(domain.Md5(pwd) + user + domain.Sha1OffSet)\n\tt.Log(sha1)\n}\n\n\n\nfunc TestMemberPwd(t *testing.T) {\n\tpwd := domain.Md5(\"594488\")\n\tt.Log(\"--pwd=\", pwd, \"\\n\")\n\tpwd = domain.Sha1(pwd)\n\tt.Log(\"--pwd=\", pwd, \"\\n\")\n}\n\n\nfunc TestMerchantPwd(t *testing.T) {\n\tpwd := \"123456\"\n\tencPwd := domain.MerchantSha1Pwd(pwd)\n\tt.Log(encPwd)\n}\n\nfunc TestMasterPwd2(t *testing.T) ", "output": "{\n\tuser := \"master\"\n\tpwd := \"fs888888@txxfmall\"\n\tsha1 := domain.Sha1(domain.Md5(pwd) + user + domain.Sha1OffSet)\n\tt.Log(sha1)\n\tt.Log(domain.Sha1OffSet)\n}"} {"input": "package aggregation\n\nimport \"github.com/m3db/m3/src/x/pool\"\n\n\ntype TypesAlloc func() Types\n\n\ntype TypesPool interface {\n\tInit(alloc TypesAlloc)\n\n\tGet() Types\n\n\tPut(value Types)\n}\n\ntype typesPool struct {\n\tpool pool.ObjectPool\n}\n\n\n\n\nfunc (p *typesPool) Init(alloc TypesAlloc) {\n\tp.pool.Init(func() interface{} {\n\t\treturn alloc()\n\t})\n}\n\nfunc (p *typesPool) Get() Types {\n\treturn p.pool.Get().(Types)\n}\n\nfunc (p *typesPool) Put(value Types) {\n\tp.pool.Put(value[:0])\n}\n\nfunc NewTypesPool(opts pool.ObjectPoolOptions) TypesPool ", "output": "{\n\treturn &typesPool{pool: pool.NewObjectPool(opts)}\n}"} {"input": "package commands\n\nimport (\n\t\"os\"\n\n\t\"github.com/darcinc/afero\"\n\t\"github.com/darcinc/repository\"\n)\n\n\n\n\nfunc DeleteKeys(fs afero.Fs, keyfile, name string) ", "output": "{\n\tfilename := repository.NamedKeystoreFile(keyfile)\n\tfile, err := fs.Open(filename)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tkeystore, err := repository.OpenKeystore(file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfile.Close()\n\n\tkeystore.RemoveKey(name)\n\n\tfile, err = fs.OpenFile(filename, os.O_WRONLY|os.O_EXCL, 0600)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\n\tkeystore.Save(file)\n}"} {"input": "package roles\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar TopLevelRoles = map[string]struct{}{\n\t\"root\": {},\n\t\"targets\": {},\n\t\"snapshot\": {},\n\t\"timestamp\": {},\n}\n\nfunc IsTopLevelRole(name string) bool {\n\t_, ok := TopLevelRoles[name]\n\treturn ok\n}\n\n\n\nfunc IsTopLevelManifest(name string) bool {\n\treturn IsTopLevelRole(strings.TrimSuffix(name, \".json\"))\n}\n\nfunc IsDelegatedTargetsManifest(name string) bool {\n\treturn !IsTopLevelManifest(name)\n}\n\nfunc IsVersionedManifest(name string) bool {\n\tparts := strings.Split(name, \".\")\n\tif len(parts) < 3 {\n\t\treturn false\n\t}\n\n\t_, err := strconv.Atoi(parts[0])\n\treturn err == nil\n}\n\nfunc IsDelegatedTargetsRole(name string) bool ", "output": "{\n\treturn !IsTopLevelRole(name)\n}"} {"input": "package requirements\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cloudfoundry/cli/cf\"\n\t\"github.com/cloudfoundry/cli/cf/configuration/core_config\"\n\t. \"github.com/cloudfoundry/cli/cf/i18n\"\n\t\"github.com/cloudfoundry/cli/cf/models\"\n\t\"github.com/cloudfoundry/cli/cf/terminal\"\n)\n\n\ntype TargetedOrgRequirement interface {\n\tRequirement\n\tGetOrganizationFields() models.OrganizationFields\n}\n\ntype targetedOrgApiRequirement struct {\n\tui terminal.UI\n\tconfig core_config.Reader\n}\n\nfunc NewTargetedOrgRequirement(ui terminal.UI, config core_config.Reader) TargetedOrgRequirement {\n\treturn targetedOrgApiRequirement{ui, config}\n}\n\n\n\nfunc (req targetedOrgApiRequirement) GetOrganizationFields() (org models.OrganizationFields) {\n\treturn req.config.OrganizationFields()\n}\n\nfunc (req targetedOrgApiRequirement) Execute() (success bool) ", "output": "{\n\tif !req.config.HasOrganization() {\n\t\tmessage := fmt.Sprintf(T(\"No org targeted, use '{{.Command}}' to target an org.\", map[string]interface{}{\"Command\": terminal.CommandColor(cf.Name() + \" target -o ORG\")}))\n\t\treq.ui.Failed(message)\n\t\treturn false\n\t}\n\n\treturn true\n}"} {"input": "package ray\n\nimport (\n\t\"github.com/v2ray/v2ray-core/common/alloc\"\n)\n\nconst (\n\tbufferSize = 128\n)\n\n\nfunc NewRay() Ray {\n\treturn &directRay{\n\t\tInput: make(chan *alloc.Buffer, bufferSize),\n\t\tOutput: make(chan *alloc.Buffer, bufferSize),\n\t}\n}\n\ntype directRay struct {\n\tInput chan *alloc.Buffer\n\tOutput chan *alloc.Buffer\n}\n\nfunc (this *directRay) OutboundInput() <-chan *alloc.Buffer {\n\treturn this.Input\n}\n\n\n\nfunc (this *directRay) InboundInput() chan<- *alloc.Buffer {\n\treturn this.Input\n}\n\nfunc (this *directRay) InboundOutput() <-chan *alloc.Buffer {\n\treturn this.Output\n}\n\nfunc (this *directRay) OutboundOutput() chan<- *alloc.Buffer ", "output": "{\n\treturn this.Output\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc leapYear(year int) bool {\n\tswitch {\n\tcase year%4 != 0:\n\t\treturn false\n\tcase year%400 == 0:\n\t\treturn true\n\tdefault:\n\t\treturn year%100 != 0\n\t}\n}\n\n\n\nfunc bulukuluYear(year int) bool { return leapYear(year) && year%55 == 0 }\n\nfunc main() {\n\tin, _ := os.Open(\"10070.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"10070.out\")\n\tdefer out.Close()\n\n\tvar year int\n\tfor first := true; ; {\n\t\tif _, err := fmt.Fscanf(in, \"%d\", &year); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif first {\n\t\t\tfirst = false\n\t\t} else {\n\t\t\tfmt.Fprintln(out)\n\t\t}\n\t\tif leap, huluculu, bulukulu := leapYear(year), huluculuYear(year), bulukuluYear(year); !leap && !huluculu && !bulukulu {\n\t\t\tfmt.Fprintln(out, \"This is an ordinary year.\")\n\t\t} else {\n\t\t\tif leap {\n\t\t\t\tfmt.Fprintln(out, \"This is leap year.\")\n\t\t\t}\n\t\t\tif huluculu {\n\t\t\t\tfmt.Fprintln(out, \"This is huluculu festival year.\")\n\t\t\t}\n\t\t\tif bulukulu {\n\t\t\t\tfmt.Fprintln(out, \"This is bulukulu festival year.\")\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc huluculuYear(year int) bool ", "output": "{ return year%15 == 0 }"} {"input": "package tools\n\nimport (\n\t\"strings\"\n\t\"unicode/utf8\"\n)\n\nconst LANG_EN = \"eng\"\nconst LANG_FR = \"fre\"\n\n\nfunc TryToUtf8(s string, lang string) string {\n\n\tvar b = []byte(s)\n\n\tswitch lang {\n\tcase LANG_EN: \n\t\treturn s\n\tcase LANG_FR: \n\t\tif !utf8.Valid(b) || strings.Count(s, string([]byte{0xef, 0xbf, 0xbd})) > 0 {\n\t\t\treturn iso88591ToUtf8(b)\n\t\t}\n\t}\n\treturn s\n}\n\n\n\n\nfunc iso88591ToUtf8(iso88591 []byte) string ", "output": "{\n\tbuf := make([]rune, len(iso88591))\n\tfor i, b := range iso88591 {\n\t\tbuf[i] = rune(b)\n\t}\n\treturn string(buf)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\n\n\nfunc main() {\n\tprintln(bestTeamScore([]int{1, 3, 5, 10, 15}, []int{1, 2, 3, 4, 5}))\n\tprintln(bestTeamScore([]int{4, 5, 6, 5}, []int{2, 1, 2, 1}))\n\tprintln(bestTeamScore([]int{1, 2, 3, 5}, []int{8, 9, 10, 1}))\n}\n\nfunc bestTeamScore(scores []int, ages []int) int ", "output": "{\n\tsort.Slice(scores, func(i, j int) bool {\n\t\treturn ages[i] < ages[j]\n\t})\n\tfmt.Println(scores)\n\n\tvar result int\n\tmax := scores[0]\n\tfor i := 0; i < len(scores); i++ {\n\t\tif scores[i] < max {\n\t\t\tcontinue\n\t\t} else {\n\t\t\tmax = scores[i]\n\t\t}\n\n\t\tresult += scores[i]\n\t}\n\treturn result\n}"} {"input": "package clause\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestSubsumption(t *testing.T) ", "output": "{\n\tempty, one, two, three := ConstructTestClauses()\n\t_, _, four, five := ConstructMoreTestClauses()\n\n\tcases := []struct {\n\t\tclause Clause\n\t\tclause2 Clause\n\t\twant bool\n\t}{\n\t\t{empty, one, true},\n\t\t{empty, two, true},\n\t\t{one, two, true},\n\t\t{one, three, true},\n\t\t{two, three, true},\n\t\t{one, four, false},\n\t\t{two, five, false},\n\t}\n\n\tfor _, c := range cases {\n\t\tgot := c.clause.Subsumes(c.clause2)\n\t\tif got != c.want {\n\t\t\tt.Errorf(\"%q.Subsumes(%q) == %t, want %t\", c.clause, c.clause2, got, c.want)\n\t\t}\n\t}\n}"} {"input": "package gash\n\n\n\n\n\ntype CuckooHash struct {\n\titems []*KvPair\n\tcapacity int\n\tfn1 HashFn\n\tfn2 HashFn\n}\n\nfunc CreateCuckooHash(capacity int, fn1 HashFn, fn2 HashFn) CuckooHash {\n\ttable := CuckooHash{}\n\ttable.capacity = capacity\n\ttable.items = make([]*KvPair, capacity)\n\ttable.fn1 = fn1\n\ttable.fn2 = fn2\n\treturn table\n}\n\nfunc (table CuckooHash) Insert(k string, v interface{}) {\n\tindex := table.fn1(k) % table.capacity\n\tswapItem := table.items[index]\n\tinsertItem := KvPair{k, v}\n\ttable.items[index] = &insertItem\n\toldIndex := index\n\n\titem := swapItem\n\tfor item != nil {\n\t\tindex = table.fn1(swapItem.Key) % table.capacity\n\t\tif index == oldIndex {\n\t\t\tindex = table.fn2(swapItem.Key) % table.capacity\n\t\t}\n\n\t\tswapItem = table.items[index]\n\t\tif swapItem != nil && swapItem.Key == k {\n\n\t\t\treturn\n\t\t}\n\t\ttable.items[index] = item\n\t\titem = swapItem\n\t}\n}\n\n\n\nfunc (table CuckooHash) Remove(k string) {\n\tindex1 := table.fn1(k) % table.capacity\n\tindex2 := table.fn2(k) % table.capacity\n\n\tpair1 := table.items[index1]\n\tpair2 := table.items[index2]\n\n\tif pair1 != nil && pair1.Key == k {\n\t\ttable.items[index1] = nil\n\t} else if pair2 != nil && pair2.Key == k {\n\t\ttable.items[index2] = nil\n\t}\n}\n\nfunc (table CuckooHash) Find(k string) interface{} ", "output": "{\n\tvar pair *KvPair\n\n\tindex1 := table.fn1(k) % table.capacity\n\tindex2 := table.fn2(k) % table.capacity\n\n\tpair1 := table.items[index1]\n\tpair2 := table.items[index2]\n\n\tif pair1 != nil && pair1.Key == k {\n\t\tpair = pair1\n\t} else if pair2 != nil && pair2.Key == k {\n\t\tpair = pair2\n\t}\n\n\treturn pair.Value\n}"} {"input": "package bitswap\n\nimport (\n\tbsnet \"github.com/ipfs/go-ipfs/exchange/bitswap/network\"\n\tmockrouting \"github.com/ipfs/go-ipfs/routing/mock\"\n\ttestutil \"github.com/ipfs/go-ipfs/thirdparty/testutil\"\n\tpeer \"gx/ipfs/QmQGwpJy9P4yXZySmqkZEXCmbBpJUb8xntCv8Ca4taZwDC/go-libp2p-peer\"\n\tds \"gx/ipfs/QmZ6A6P6AMo8SR3jXAwzTuSU6B9R2Y4eqW2yW9VvfUayDN/go-datastore\"\n\tcontext \"gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context\"\n\tmockpeernet \"gx/ipfs/QmdBpVuSYuTGDA8Kn66CbKvEThXqKUh2nTANZEhzSxqrmJ/go-libp2p/p2p/net/mock\"\n)\n\ntype peernet struct {\n\tmockpeernet.Mocknet\n\troutingserver mockrouting.Server\n}\n\nfunc StreamNet(ctx context.Context, net mockpeernet.Mocknet, rs mockrouting.Server) (Network, error) {\n\treturn &peernet{net, rs}, nil\n}\n\n\n\nfunc (pn *peernet) HasPeer(p peer.ID) bool {\n\tfor _, member := range pn.Mocknet.Peers() {\n\t\tif p == member {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nvar _ Network = &peernet{}\n\nfunc (pn *peernet) Adapter(p testutil.Identity) bsnet.BitSwapNetwork ", "output": "{\n\tclient, err := pn.Mocknet.AddPeer(p.PrivateKey(), p.Address())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\trouting := pn.routingserver.ClientWithDatastore(context.TODO(), p, ds.NewMapDatastore())\n\treturn bsnet.NewFromIpfsHost(client, routing)\n}"} {"input": "package usecase\n\nimport (\n\t\"context\"\n\n\t\"github.com/morikuni/chat/src/domain\"\n\t\"github.com/morikuni/failure\"\n)\n\ntype room struct {\n\taccountRepo AccountRepository\n\troomRepo RoomRepository\n}\n\nvar _ Room = (*room)(nil)\n\n\n\ntype CreateRoomRequest struct {\n\tOwnerID domain.AccountID\n\tName domain.RoomName\n}\n\ntype CreateRoomResponse struct {\n\tRoom *domain.Room\n}\n\nfunc (r *room) CreateRoom(ctx context.Context, request *CreateRoomRequest) (*CreateRoomResponse, error) {\n\taccount, err := r.accountRepo.Get(ctx, request.OwnerID)\n\tif err != nil {\n\t\treturn nil, failure.Wrap(err)\n\t}\n\n\troom := domain.NewRoom(account, request.Name)\n\n\terr = r.roomRepo.Save(ctx, room)\n\tif err != nil {\n\t\treturn nil, failure.Wrap(err)\n\t}\n\n\treturn &CreateRoomResponse{room}, nil\n}\n\nfunc NewRoom(\n\taccountRepo AccountRepository,\n\troomRepo RoomRepository,\n) Room ", "output": "{\n\treturn &room{\n\t\taccountRepo,\n\t\troomRepo,\n\t}\n}"} {"input": "package native\n\nimport (\n\t\"runtime\"\n\n\tgogl \"github.com/go-gl/gl\"\n\tglfw \"github.com/go-gl/glfw3\"\n\n\t\"github.com/dertseha/golgo/runner\"\n)\n\nfunc Run(application runner.Application, param runner.ApplicationParameter) {\n\truntime.LockOSThread()\n\tdefer runtime.UnlockOSThread()\n\n\tif !glfw.Init() {\n\t\tpanic(\"Failed to initialize GLFW\")\n\t}\n\tdefer glfw.Terminate()\n\tsetupGlfw()\n\n\twindow, err := glfw.CreateWindow(param.Width(), param.Height(), param.Title(), nil, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer window.Destroy()\n\tsetupWindow(window, application)\n\n\tgogl.Init()\n\tgl := CreateGles2Wrapper()\n\n\tapplication.Init(gl, param.Width(), param.Height())\n\tfor !window.ShouldClose() {\n\t\tapplication.Render()\n\n\t\twindow.SwapBuffers()\n\t\tglfw.PollEvents()\n\t}\n}\n\nfunc setupGlfw() {\n\tglfw.WindowHint(glfw.ContextVersionMajor, 2)\n\tglfw.WindowHint(glfw.ContextVersionMinor, 0)\n\tglfw.SwapInterval(1)\n}\n\n\n\nfunc getKeyCallback(application runner.Application) func(*glfw.Window, glfw.Key, int, glfw.Action, glfw.ModifierKey) {\n\treturn func(window *glfw.Window, key glfw.Key, scancode int, action glfw.Action, modifier glfw.ModifierKey) {\n\t\tswitch key {\n\t\tcase glfw.KeyEscape:\n\t\t\twindow.SetShouldClose(true)\n\t\t}\n\t}\n}\n\nfunc setupWindow(window *glfw.Window, application runner.Application) ", "output": "{\n\twindow.SetSizeCallback(func(_ *glfw.Window, width int, height int) {\n\t\tapplication.Resize(width, height)\n\t})\n\n\twindow.SetKeyCallback(getKeyCallback(application))\n\n\twindow.MakeContextCurrent()\n}"} {"input": "package service\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"go-common/app/service/main/assist/conf\"\n\t\"go-common/app/service/main/assist/dao/account\"\n\t\"go-common/app/service/main/assist/dao/assist\"\n\t\"go-common/app/service/main/assist/dao/message\"\n\t\"go-common/library/log\"\n\t\"go-common/library/queue/databus\"\n)\n\n\ntype Service struct {\n\tc *conf.Config\n\tass *assist.Dao\n\tacc *account.Dao\n\tmsg *message.Dao\n\trelationSub *databus.Databus\n\tcacheChan chan func()\n\twg sync.WaitGroup\n}\n\n\nfunc New(c *conf.Config) *Service {\n\ts := &Service{\n\t\tc: c,\n\t\tass: assist.New(c),\n\t\tacc: account.New(c),\n\t\tmsg: message.New(c),\n\t\tcacheChan: make(chan func(), 1024),\n\t\trelationSub: databus.New(c.RelationSub),\n\t}\n\ts.wg.Add(1)\n\tgo s.relationConsumer()\n\ts.wg.Add(1)\n\tgo s.cacheproc()\n\treturn s\n}\n\n\nfunc (s *Service) Ping(c context.Context) (err error) {\n\tif err = s.ass.Ping(c); err != nil {\n\t\tlog.Error(\"s.ass.Dao.Ping err(%v)\", err)\n\t}\n\treturn\n}\n\n\nfunc (s *Service) asyncCache(f func()) {\n\tselect {\n\tcase s.cacheChan <- f:\n\tdefault:\n\t\tlog.Warn(\"assist cacheproc chan full\")\n\t}\n}\n\n\n\n\n\nfunc (s *Service) Close() {\n\ts.relationSub.Close()\n\ts.wg.Wait()\n}\n\nfunc (s *Service) cacheproc() ", "output": "{\n\tfor {\n\t\tf := <-s.cacheChan\n\t\tf()\n\t}\n}"} {"input": "package containers\n\nimport (\n\t\"github.com/nanobox-io/golang-docker-client\"\n\n\t\"github.com/nanobox-io/nanobox/util/dhcp\"\n)\n\n\nfunc BridgeConfig() docker.ContainerConfig {\n\treturn docker.ContainerConfig{\n\t\tName: BridgeName(),\n\t\tImage: \"nanobox/bridge\",\n\t\tNetwork: \"virt\",\n\t\tIP: reserveIP(),\n\t\tRestartPolicy: \"always\",\n\t\tPorts: []string{\"1194:1194/udp\"},\n\t}\n}\n\n\nfunc BridgeName() string {\n\treturn \"nanobox_bridge\"\n}\n\n\n\n\nfunc reserveIP() string ", "output": "{\n\tip, _ := dhcp.ReserveLocal()\n\treturn ip.String()\n}"} {"input": "package MySQLProtocol\n\nimport \"testing\"\nimport \"github.com/stretchr/testify/assert\"\n\nvar LOCAL_INFILE_Request_test_packets = []struct {\n\tpacket Proto\n\tcontext Context\n}{\n\t{packet: Proto{data: StringToPacket(`\n0c 00 00 01 fb 2f 65 74 63 2f 70 61 73 73 77 64 ...../etc/passwd\n`)}, context: Context{}},\n}\n\nfunc Test_Packet_LOCAL_INFILE_Request(t *testing.T) {\n\tvar pkt Packet_LOCAL_INFILE_Request\n\tfor _, value := range LOCAL_INFILE_Request_test_packets {\n\t\tpkt = Packet_LOCAL_INFILE_Request{}\n\t\tpkt.FromPacket(value.context, value.packet)\n\t\tassert.Equal(t, pkt.ToPacket(value.context), value.packet.data, \"\")\n\t}\n}\n\n\n\nfunc Benchmark_Packet_LOCAL_INFILE_Request_GetPacketSize(b *testing.B) {\n\tcontext := Context{capability: CLIENT_PROTOCOL_41}\n\tpkt := Packet_LOCAL_INFILE_Request{}\n\tpkt.FromPacket(context, LOCAL_INFILE_Request_test_packets[0].packet)\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt.GetPacketSize(context)\n\t}\n}\n\nfunc Benchmark_Packet_LOCAL_INFILE_Request_ToPacket(b *testing.B) {\n\tcontext := Context{capability: CLIENT_PROTOCOL_41}\n\tpkt := Packet_LOCAL_INFILE_Request{}\n\tpkt.FromPacket(context, LOCAL_INFILE_Request_test_packets[0].packet)\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt.ToPacket(context)\n\t}\n}\n\nfunc Benchmark_Packet_LOCAL_INFILE_Request_FromPacket(b *testing.B) ", "output": "{\n\tcontext := Context{capability: CLIENT_PROTOCOL_41}\n\tvar pkt Packet_LOCAL_INFILE_Request\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt = Packet_LOCAL_INFILE_Request{}\n\t\tLOCAL_INFILE_Request_test_packets[0].packet.offset = 0\n\t\tpkt.FromPacket(context, LOCAL_INFILE_Request_test_packets[0].packet)\n\t}\n}"} {"input": "package math\n\nimport \"jvmgo/ch07/instructions/base\"\nimport \"jvmgo/ch07/rtda\"\n\n\ntype DSUB struct{ base.NoOperandsInstruction }\n\nfunc (self *DSUB) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tv2 := stack.PopDouble()\n\tv1 := stack.PopDouble()\n\tresult := v1 - v2\n\tstack.PushDouble(result)\n}\n\n\ntype FSUB struct{ base.NoOperandsInstruction }\n\n\n\n\ntype ISUB struct{ base.NoOperandsInstruction }\n\nfunc (self *ISUB) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tv2 := stack.PopInt()\n\tv1 := stack.PopInt()\n\tresult := v1 - v2\n\tstack.PushInt(result)\n}\n\n\ntype LSUB struct{ base.NoOperandsInstruction }\n\nfunc (self *LSUB) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tv2 := stack.PopLong()\n\tv1 := stack.PopLong()\n\tresult := v1 - v2\n\tstack.PushLong(result)\n}\n\nfunc (self *FSUB) Execute(frame *rtda.Frame) ", "output": "{\n\tstack := frame.OperandStack()\n\tv2 := stack.PopFloat()\n\tv1 := stack.PopFloat()\n\tresult := v1 - v2\n\tstack.PushFloat(result)\n}"} {"input": "package config\n\nimport (\n\t\"sync\"\n)\n\n\n\n\n\n\ntype delayedEnvironment struct {\n\tenv Environment\n\tloading sync.Mutex\n\tcallback func() Environment\n}\n\n\n\nfunc (e *delayedEnvironment) Get(key string) (string, bool) {\n\te.Load()\n\treturn e.env.Get(key)\n}\n\n\n\nfunc (e *delayedEnvironment) GetAll(key string) []string {\n\te.Load()\n\treturn e.env.GetAll(key)\n}\n\n\n\nfunc (e *delayedEnvironment) Bool(key string, def bool) bool {\n\te.Load()\n\treturn e.env.Bool(key, def)\n}\n\n\n\nfunc (e *delayedEnvironment) Int(key string, def int) int {\n\te.Load()\n\treturn e.env.Int(key, def)\n}\n\n\nfunc (e *delayedEnvironment) All() map[string][]string {\n\te.Load()\n\treturn e.env.All()\n}\n\n\n\n\n\n\n\n\n\n\nfunc (e *delayedEnvironment) Load() ", "output": "{\n\te.loading.Lock()\n\tdefer e.loading.Unlock()\n\n\tif e.env != nil {\n\t\treturn\n\t}\n\n\te.env = e.callback()\n}"} {"input": "package generator\n\nimport (\n\t\"testing\"\n\n\tkapi \"github.com/GoogleCloudPlatform/kubernetes/pkg/api\"\n\n\tbuildapi \"github.com/openshift/origin/pkg/build/api\"\n\t\"github.com/openshift/origin/pkg/build/generator\"\n)\n\nfunc TestCreateClone(t *testing.T) {\n\trest := CloneREST{&generator.BuildGenerator{Client: generator.Client{\n\t\tCreateBuildFunc: func(ctx kapi.Context, build *buildapi.Build) error {\n\t\t\treturn nil\n\t\t},\n\t\tGetBuildFunc: func(ctx kapi.Context, name string) (*buildapi.Build, error) {\n\t\t\treturn &buildapi.Build{}, nil\n\t\t},\n\t}}}\n\n\t_, err := rest.Create(kapi.NewDefaultContext(), &buildapi.BuildRequest{ObjectMeta: kapi.ObjectMeta{Name: \"name\"}})\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error %v\", err)\n\t}\n}\n\n\n\nfunc TestCreateCloneValidationError(t *testing.T) ", "output": "{\n\trest := CloneREST{&generator.BuildGenerator{}}\n\t_, err := rest.Create(kapi.NewDefaultContext(), &buildapi.BuildRequest{})\n\tif err == nil {\n\t\tt.Error(\"Expected object got none!\")\n\t}\n}"} {"input": "package hybridcompute\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) BaseClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package models\n\nimport \"fmt\"\n\n\nvar RoomPool = make([] *Room, 0)\n\nfunc AddRoom(r *Room) {\n\tRoomPool = append(RoomPool, r)\n}\n\n\n\n\n\nfunc FindRoom(d string) (int, *Room) {\n\tfor i, v := range RoomPool {\n\t\tif v.Name == d {\n\t\t\treturn i, v\n\t\t}\n\t}\n\treturn -1, &Room{}\n}\n\n\nfunc RemoveRoom(r *Room) {\n\n\tindex, _ := FindRoom(r.Name)\n\n\tif index != -1 {\n\t\tRoomPool = append(RoomPool[:index], RoomPool[index + 1:]...)\n\t}\n}\n\n\n\n\nfunc RemoveClient(c *Client) {\n\tfor _, room := range RoomPool{\n\t\tif room.Name == c.Room {\n\t\t\tif room.HasClient(c) {\n\t\t\t\troom.DeleteClient(c)\n\t\t\t\tif room.ClientCount() == 0 {\n\t\t\t\t\tRemoveRoom(room)\n\t\t\t\t\tPoolBroadcast(NewMessage(map[string]string{\n\t\t\t\t\t\t\"connectedClients\": fmt.Sprintf(\"%v\", GetAllClients()),\n\t\t\t\t\t\t\"numberOfRooms\": fmt.Sprintf(\"%v\", GetNumberOfRooms()),\n\t\t\t\t\t}))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\nfunc ListRooms() (int, []string) {\n\tpool := make([]string, 0)\n\tfor _, obj := range RoomPool {\n\t\tpool = append(pool, obj.Name)\n\t}\n\treturn len(RoomPool), pool\n}\n\n\nfunc PoolBroadcast(m Message) {\n\tfor _, room := range RoomPool {\n\t\troom.RoomBroadcast(m)\n\t}\n}\n\n\n\n\n\nfunc GetNumberOfRooms() int{\n\treturn len(RoomPool)\n}\n\nfunc GetAllClients() int ", "output": "{\n\n\tclientSum := 0\n\tfor _, room := range RoomPool {\n\t\tclientSum += len(room.ClientPool)\n\t}\n\treturn clientSum\n}"} {"input": "package test\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/pilosa/pilosa\"\n)\n\n\n\n\n\ntype ModHasher struct{}\n\n\nfunc NewModHasher() *ModHasher { return &ModHasher{} }\n\nfunc (*ModHasher) Hash(key uint64, n int) int { return int(key) % n }\n\n\ntype ConstHasher struct {\n\ti int\n}\n\n\nfunc NewConstHasher(i int) *ConstHasher { return &ConstHasher{i: i} }\n\nfunc (h *ConstHasher) Hash(key uint64, n int) int { return h.i }\n\nfunc NewCluster(n int) *pilosa.Cluster ", "output": "{\n\tc := pilosa.NewCluster()\n\tc.ReplicaN = 1\n\tc.Hasher = NewModHasher()\n\n\tfor i := 0; i < n; i++ {\n\t\tc.Nodes = append(c.Nodes, &pilosa.Node{\n\t\t\tScheme: \"http\",\n\t\t\tHost: fmt.Sprintf(\"host%d\", i),\n\t\t})\n\t}\n\n\treturn c\n}"} {"input": "package term\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc IsANSI(f *os.File) bool {\n\treturn IsTerminal(f)\n}\n\n\nfunc IsTerminal(f *os.File) bool {\n\tcmd := exec.Command(\"test\", \"-t\", \"0\")\n\tcmd.Stdin = f\n\treturn cmd.Run() == nil\n}\n\n\n\nfunc Restore(f *os.File) error {\n\treturn stty(f, \"icanon\", \"echo\").Run()\n}\n\nfunc Cols() (int, error) {\n\tcols, err := tput(\"cols\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}\n\nfunc Lines() (int, error) {\n\tcols, err := tput(\"lines\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}\n\n\n\nfunc stty(f *os.File, args ...string) *exec.Cmd {\n\tc := exec.Command(\"stty\", args...)\n\tc.Stdin = f\n\treturn c\n}\n\nfunc tput(what string) (string, error) {\n\tc := exec.Command(\"tput\", what)\n\tc.Stderr = os.Stderr\n\tout, err := c.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.TrimSpace(string(out)), nil\n}\n\nfunc MakeRaw(f *os.File) error ", "output": "{\n\treturn stty(f, \"-icanon\", \"-echo\").Run()\n}"} {"input": "package transport\n\nimport (\n\t\"syscall\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\nfunc setReusePort(network, address string, conn syscall.RawConn) error {\n\treturn conn.Control(func(fd uintptr) {\n\t\tsyscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_REUSEPORT, 1)\n\t})\n}\n\n\n\nfunc setReuseAddress(network, address string, conn syscall.RawConn) error ", "output": "{\n\treturn conn.Control(func(fd uintptr) {\n\t\tsyscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_REUSEADDR, 1)\n\t})\n}"} {"input": "package marid\n\ntype FuncSet struct {\n\tf map[string]interface{}\n}\n\nfunc NewFuncSet() *FuncSet {\n\treturn &FuncSet{make(map[string]interface{})}\n}\n\nfunc (f *FuncSet) AddFuncs(fns map[string]interface{}) {\n\tfor k, fn := range fns {\n\t\tf.f[k] = fn\n\t}\n}\n\n\n\nfunc (f *FuncSet) GetFuncs() map[string]interface{} ", "output": "{\n\treturn f.f\n}"} {"input": "package characteristic\n\nimport (\n\t\"github.com/brutella/hc/model\"\n)\n\ntype HeatingCoolingMode struct {\n\t*ByteCharacteristic\n}\n\nfunc NewHeatingCoolingMode(current model.HeatCoolModeType, charType CharType, permissions []string) *HeatingCoolingMode {\n\tc := HeatingCoolingMode{NewByteCharacteristic(byte(current), permissions)}\n\tc.Type = charType\n\n\treturn &c\n}\n\n\n\nfunc NewTargetHeatingCoolingMode(current model.HeatCoolModeType) *HeatingCoolingMode {\n\treturn NewHeatingCoolingMode(current, CharTypeHeatingCoolingModeTarget, PermsAll())\n}\n\nfunc (c *HeatingCoolingMode) SetHeatingCoolingMode(mode model.HeatCoolModeType) {\n\tc.SetByte(byte(mode))\n}\n\nfunc (c *HeatingCoolingMode) HeatingCoolingMode() model.HeatCoolModeType {\n\treturn model.HeatCoolModeType(c.Byte())\n}\n\nfunc NewCurrentHeatingCoolingMode(current model.HeatCoolModeType) *HeatingCoolingMode ", "output": "{\n\treturn NewHeatingCoolingMode(current, CharTypeHeatingCoolingModeCurrent, PermsRead())\n}"} {"input": "package main\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\n\n\nfunc SelectGuild() {\n\tState.Enabled = false\n\tSelectGuildMenu()\n\tSelectChannelMenu()\n\tState.Enabled = true\n\tShowContent()\n}\n\n\nfunc SelectChannel() {\n\tState.Enabled = false\n\tSelectChannelMenu()\n\tState.Enabled = true\n\tShowContent()\n}\n\nfunc ParseForCommands(line string) string ", "output": "{\n\tswitch line {\n\tcase \":g\":\n\t\tSelectGuild()\n\t\tline = \"\"\n\tcase \":c\":\n\t\tSelectChannel()\n\t\tline = \"\"\n\tdefault:\n\t}\n\n\tif strings.HasPrefix(line, \":m\") {\n\t\tAmountStr := strings.Split(line, \" \")\n\t\tif len(AmountStr) < 2 {\n\t\t\tMsg(ErrorMsg, \"[:m] No Arguments \\n\")\n\t\t\treturn \"\"\n\t\t}\n\n\t\tAmount, err := strconv.Atoi(AmountStr[1])\n\t\tif err != nil {\n\t\t\tMsg(ErrorMsg, \"[:m] Argument Error: %s \\n\", err)\n\t\t\treturn \"\"\n\t\t}\n\n\t\tMsg(InfoMsg, \"Printing last %d messages!\\n\", Amount)\n\t\tState.RetrieveMessages(Amount)\n\t\tPrintMessages(Amount)\n\t\tline = \"\"\n\t}\n\n\treturn line\n}"} {"input": "package iso20022\n\n\ntype TotalFeesAndTaxes40 struct {\n\n\tTotalOverheadApplied *ActiveCurrencyAndAmount `xml:\"TtlOvrhdApld,omitempty\"`\n\n\tTotalFees *ActiveCurrencyAndAmount `xml:\"TtlFees,omitempty\"`\n\n\tTotalTaxes *ActiveCurrencyAndAmount `xml:\"TtlTaxs,omitempty\"`\n\n\tCommercialAgreementReference *Max35Text `xml:\"ComrclAgrmtRef,omitempty\"`\n\n\tIndividualFee []*Fee2 `xml:\"IndvFee,omitempty\"`\n\n\tIndividualTax []*Tax31 `xml:\"IndvTax,omitempty\"`\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalOverheadApplied(value, currency string) {\n\tt.TotalOverheadApplied = NewActiveCurrencyAndAmount(value, currency)\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalFees(value, currency string) {\n\tt.TotalFees = NewActiveCurrencyAndAmount(value, currency)\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalTaxes(value, currency string) {\n\tt.TotalTaxes = NewActiveCurrencyAndAmount(value, currency)\n}\n\nfunc (t *TotalFeesAndTaxes40) SetCommercialAgreementReference(value string) {\n\tt.CommercialAgreementReference = (*Max35Text)(&value)\n}\n\n\n\nfunc (t *TotalFeesAndTaxes40) AddIndividualTax() *Tax31 {\n\tnewValue := new(Tax31)\n\tt.IndividualTax = append(t.IndividualTax, newValue)\n\treturn newValue\n}\n\nfunc (t *TotalFeesAndTaxes40) AddIndividualFee() *Fee2 ", "output": "{\n\tnewValue := new(Fee2)\n\tt.IndividualFee = append(t.IndividualFee, newValue)\n\treturn newValue\n}"} {"input": "package vppcalls\n\nimport (\n\t\"errors\"\n\n\tl2ba \"github.com/ligato/vpp-agent/plugins/vpp/binapi/l2\"\n)\n\n\nfunc (h *XConnectVppHandler) AddL2XConnect(rxIface, txIface string) error {\n\treturn h.addDelXConnect(rxIface, txIface, true)\n}\n\n\nfunc (h *XConnectVppHandler) DeleteL2XConnect(rxIface, txIface string) error {\n\treturn h.addDelXConnect(rxIface, txIface, false)\n}\n\n\n\nfunc (h *XConnectVppHandler) addDelXConnect(rxIface, txIface string, enable bool) error ", "output": "{\n\trxIfaceMeta, found := h.ifIndexes.LookupByName(rxIface)\n\tif !found {\n\t\treturn errors.New(\"failed to get Rx interface metadata\")\n\t}\n\n\ttxIfaceMeta, found := h.ifIndexes.LookupByName(txIface)\n\tif !found {\n\t\treturn errors.New(\"failed to get Tx interface metadata\")\n\t}\n\n\treq := &l2ba.SwInterfaceSetL2Xconnect{\n\t\tEnable: boolToUint(enable),\n\t\tTxSwIfIndex: txIfaceMeta.GetIndex(),\n\t\tRxSwIfIndex: rxIfaceMeta.GetIndex(),\n\t}\n\treply := &l2ba.SwInterfaceSetL2XconnectReply{}\n\n\tif err := h.callsChannel.SendRequest(req).ReceiveReply(reply); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\tclayControllers \"github.com/qb0C80aE/clay/controllers\"\n\t\"github.com/qb0C80aE/clay/extensions\"\n\t\"github.com/qb0C80aE/pottery/logics\"\n\t\"github.com/qb0C80aE/pottery/models\"\n)\n\ntype hostGroupController struct {\n\t*clayControllers.BaseController\n}\n\n\n\nfunc (controller *hostGroupController) RouteMap() map[int]map[int]gin.HandlerFunc {\n\trouteMap := map[int]map[int]gin.HandlerFunc{\n\t\textensions.MethodGet: {\n\t\t\textensions.URLSingle: controller.GetSingle,\n\t\t\textensions.URLMulti: controller.GetMulti,\n\t\t},\n\t\textensions.MethodPost: {\n\t\t\textensions.URLMulti: controller.Create,\n\t\t},\n\t\textensions.MethodPut: {\n\t\t\textensions.URLSingle: controller.Update,\n\t\t},\n\t\textensions.MethodDelete: {\n\t\t\textensions.URLSingle: controller.Delete,\n\t\t},\n\t}\n\treturn routeMap\n}\n\nvar uniqueHostGroupController = newHostGroupController()\n\nfunc init() {\n\textensions.RegisterController(uniqueHostGroupController)\n}\n\nfunc newHostGroupController() extensions.Controller ", "output": "{\n\tcontroller := &hostGroupController{\n\t\tBaseController: clayControllers.NewBaseController(\n\t\t\tmodels.SharedHostGroupModel(),\n\t\t\tlogics.UniqueHostGroupLogic(),\n\t\t),\n\t}\n\treturn controller\n}"} {"input": "package layers\n\nimport (\n\t\"github.com/google/gopacket\"\n\t\"testing\"\n)\n\n\n\n\n\nvar testPacketRadiotap0 = []byte{\n\t0x00, 0x00, 0x12, 0x00, 0x2e, 0x48, 0x00, 0x00, 0x10, 0x02, 0x6c, 0x09, 0xa0, 0x00, 0xc6, 0x07,\n\t0x00, 0x00, 0xd4, 0x00, 0x00, 0x00, 0x88, 0x1f, 0xa1, 0xae, 0x9d, 0xcb, 0xc6, 0x30, 0x4b, 0x4b,\n}\n\nfunc TestPacketRadiotap0(t *testing.T) {\n\tp := gopacket.NewPacket(testPacketRadiotap0, LayerTypeRadioTap, gopacket.Default)\n\tif p.ErrorLayer() != nil {\n\t\tt.Error(\"Failed to decode packet:\", p.ErrorLayer().Error())\n\t}\n\tcheckLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11}, t)\n\trt := p.Layer(LayerTypeRadioTap).(*RadioTap)\n\tif rt.ChannelFrequency != 2412 || rt.DBMAntennaSignal != -58 || rt.Antenna != 7 {\n\t\tt.Error(\"Radiotap decode error\")\n\t}\n\tif rt.Rate != 2 { \n\t\tt.Error(\"Radiotap Rate decode error\")\n\t}\n}\n\n\nfunc BenchmarkDecodePacketRadiotap0(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tgopacket.NewPacket(testPacketRadiotap0, LayerTypeRadioTap, gopacket.NoCopy)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nconst AddForm = `\n
\nURL: \n\n
\n`\nvar store = NewURLStore()\n\nfunc main() {\n\thttp.HandleFunc(\"/\", Redirect)\n\thttp.HandleFunc(\"/add\", Add)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\n\n\n\nfunc Add(w http.ResponseWriter, r *http.Request) {\n\turl := r.FormValue(\"url\")\n\tif url == \"\" {\n\t\tfmt.Fprint(w, AddForm)\n\t\treturn\n\t}\n\tkey := store.Put(url)\n\tfmt.Fprintf(w, \"http://localhost:8080/%s\", key)\n}\n\nfunc Redirect(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tkey := r.URL.Path[1:]\n\turl := store.Get(key)\n\tif url == \"\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\thttp.Redirect(w, r, url, http.StatusFound)\n}"} {"input": "package jobqueue\n\nimport (\n\t\"sync\"\n)\n\n\nfunc StartNewQueue(initialWorkers int) *Queue {\n\tjobsChannel := make(chan Job)\n\tresultsChannel := make(chan JobResult)\n\tj := &Queue{jobsChannel: jobsChannel, resultsChannel: resultsChannel}\n\treturn j.AddAndStartWorkers(initialWorkers)\n}\n\n\ntype Queue struct {\n\tworkersLock sync.RWMutex\n\tqueuedJobsLock sync.RWMutex\n\tcompletedJobsLock sync.RWMutex\n\n\tjobsChannel chan Job\n\tresultsChannel chan JobResult\n\tworkers []*worker\n\n\ttotalQueuedCount int\n\ttotalCompletedCount int\n\tjobQueuingDone bool\n}\n\n\nfunc (j *Queue) AddAndStartWorkers(num int) *Queue {\n\tj.workersLock.Lock()\n\tdefer j.workersLock.Unlock()\n\n\tfor i := 0; i < num; i++ {\n\t\tworker := &worker{}\n\t\tj.workers = append(j.workers, worker)\n\t\tworkerId := len(j.workers)\n\t\tgo worker.start(workerId, j.jobsChannel, j.resultsChannel, j.onResultSent)\n\t}\n\treturn j\n}\n\n\nfunc (j *Queue) QueueJob(job Job) {\n\tj.queuedJobsLock.Lock()\n\tdefer j.queuedJobsLock.Unlock()\n\n\tj.totalQueuedCount++\n\tj.jobsChannel <- job\n}\n\n\nfunc (j *Queue) ResultsChannel() <-chan JobResult {\n\treturn j.resultsChannel\n}\n\n\n\n\nfunc (j *Queue) onResultSent(job Job) {\n\tj.completedJobsLock.Lock()\n\tdefer j.completedJobsLock.Unlock()\n\tj.totalCompletedCount++\n\tj.checkAllResultsDone()\n}\n\nfunc (j *Queue) checkAllResultsDone() {\n\tif j.jobQueuingDone && j.totalQueuedCount <= j.totalCompletedCount {\n\t\tclose(j.resultsChannel)\n\t}\n}\n\nfunc (j *Queue) JobQueuingDone() ", "output": "{\n\tj.queuedJobsLock.Lock()\n\tj.completedJobsLock.Lock()\n\tdefer j.queuedJobsLock.Unlock()\n\tdefer j.completedJobsLock.Unlock()\n\tj.jobQueuingDone = true\n\tclose(j.jobsChannel)\n\tj.checkAllResultsDone()\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\n\n\n\n\n\n\nfunc naclFstat(fd int, stat *Stat_t) (err error) {\n\t_, _, e1 := Syscall(sys_fstat, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclRead(fd int, b []byte) (n int, err error) {\n\tvar _p0 unsafe.Pointer\n\tif len(b) > 0 {\n\t\t_p0 = unsafe.Pointer(&b[0])\n\t} else {\n\t\t_p0 = unsafe.Pointer(&_zero)\n\t}\n\tr0, _, e1 := Syscall(sys_read, uintptr(fd), uintptr(_p0), uintptr(len(b)))\n\tn = int(r0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclSeek(fd int, off *int64, whence int) (err error) {\n\t_, _, e1 := Syscall(sys_lseek, uintptr(fd), uintptr(unsafe.Pointer(off)), uintptr(whence))\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclGetRandomBytes(b []byte) (err error) {\n\tvar _p0 unsafe.Pointer\n\tif len(b) > 0 {\n\t\t_p0 = unsafe.Pointer(&b[0])\n\t} else {\n\t\t_p0 = unsafe.Pointer(&_zero)\n\t}\n\t_, _, e1 := Syscall(sys_get_random_bytes, uintptr(_p0), uintptr(len(b)), 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\nfunc naclClose(fd int) (err error) ", "output": "{\n\t_, _, e1 := Syscall(sys_close, uintptr(fd), 0, 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}"} {"input": "package shell\n\nimport (\n\tgoerrors \"errors\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/gruntwork-io/terragrunt/options\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestNewSignalsForwarderWaitWindows(t *testing.T) {\n\tt.Parallel()\n\n\texpectedWait := 5\n\n\tterragruntOptions, err := options.NewTerragruntOptionsForTest(\"\")\n\tassert.Nil(t, err, \"Unexpected error creating NewTerragruntOptionsForTest: %v\", err)\n\n\tcmd := exec.Command(`..\\testdata\\test_sigint_wait.bat`, strconv.Itoa(expectedWait))\n\n\tcmdChannel := make(chan error)\n\trunChannel := make(chan error)\n\n\tsignalChannel := NewSignalsForwarder(forwardSignals, cmd, terragruntOptions.Logger, cmdChannel)\n\tdefer signalChannel.Close()\n\n\tgo func() {\n\t\trunChannel <- cmd.Run()\n\t}()\n\n\ttime.Sleep(1000 * time.Millisecond)\n\tcmd.Process.Signal(os.Kill)\n\terr := <-runChannel\n\tcmdChannel <- err\n\tassert.Error(t, err)\n\n}\n\nfunc TestExitCodeWindows(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\tfor i := 0; i <= 255; i++ {\n\t\tcmd := exec.Command(`..\\testdata\\test_exit_code.bat`, strconv.Itoa(i))\n\t\terr := cmd.Run()\n\n\t\tif i == 0 {\n\t\t\tassert.Nil(t, err)\n\t\t} else {\n\t\t\tassert.Error(t, err)\n\t\t}\n\t\tretCode, err := GetExitCode(err)\n\t\tassert.Nil(t, err)\n\t\tassert.Equal(t, i, retCode)\n\t}\n\n\terr := goerrors.New(\"This is an explicit error\")\n\tretCode, retErr := GetExitCode(err)\n\tassert.Error(t, retErr, \"An error was expected\")\n\tassert.Equal(t, err, retErr)\n\tassert.Equal(t, 0, retCode)\n}"} {"input": "package action\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n)\n\ntype kvRead struct {\n\trecurse bool\n\n\t*config\n}\n\nfunc KvReadAction() Action {\n\treturn &kvRead{\n\t\tconfig: &gConfig,\n\t}\n}\n\nfunc (k *kvRead) CommandFlags() *flag.FlagSet {\n\tf := k.newFlagSet(FLAG_DATACENTER, FLAG_KVOUTPUT, FLAG_CONSISTENCY, FLAG_BLOCKING)\n\n\tf.BoolVar(&k.recurse, \"recurse\", false, \"Perform a recursive read\")\n\n\treturn f\n}\n\n\n\nfunc (k *kvRead) Run(args []string) error ", "output": "{\n\tif len(args) != 1 {\n\t\treturn fmt.Errorf(\"A single key path must be specified\")\n\t}\n\tpath := args[0]\n\n\tclient, err := k.newKv()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tqueryOpts := k.queryOptions()\n\n\tif k.recurse {\n\t\tkvlist, _, err := client.List(path, queryOpts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif kvlist == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn k.OutputKv(kvlist)\n\t} else {\n\t\tkv, _, err := client.Get(path, queryOpts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif kv == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn k.OutputKv(kv)\n\t}\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSOpsWorksStack_ElasticIp struct {\n\n\tIp string `json:\"Ip,omitempty\"`\n\n\tName string `json:\"Name,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) AWSCloudFormationType() string {\n\treturn \"AWS::OpsWorks::Stack.ElasticIp\"\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\n\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSOpsWorksStack_ElasticIp) Metadata() map[string]interface{} ", "output": "{\n\treturn r._metadata\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/hyperledger/fabric/common/channelconfig\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n)\n\n\ntype Orderer struct {\n\tConsensusTypeVal string\n\tBatchSizeVal *ab.BatchSize\n\tBatchTimeoutVal time.Duration\n\tKafkaBrokersVal []string\n\tMaxChannelsCountVal uint64\n\tOrganizationsVal map[string]channelconfig.Org\n\tCapabilitiesVal channelconfig.OrdererCapabilities\n}\n\n\nfunc (scm *Orderer) ConsensusType() string {\n\treturn scm.ConsensusTypeVal\n}\n\n\n\n\n\nfunc (scm *Orderer) BatchTimeout() time.Duration {\n\treturn scm.BatchTimeoutVal\n}\n\n\nfunc (scm *Orderer) KafkaBrokers() []string {\n\treturn scm.KafkaBrokersVal\n}\n\n\nfunc (scm *Orderer) MaxChannelsCount() uint64 {\n\treturn scm.MaxChannelsCountVal\n}\n\n\nfunc (scm *Orderer) Organizations() map[string]channelconfig.Org {\n\treturn scm.OrganizationsVal\n}\n\n\nfunc (scm *Orderer) Capabilities() channelconfig.OrdererCapabilities {\n\treturn scm.CapabilitiesVal\n}\n\n\ntype OrdererCapabilities struct {\n\tSupportedErr error\n\n\tSetChannelModPolicyDuringCreateVal bool\n\n\tResubmissionVal bool\n}\n\n\nfunc (oc *OrdererCapabilities) Supported() error {\n\treturn oc.SupportedErr\n}\n\n\nfunc (oc *OrdererCapabilities) SetChannelModPolicyDuringCreate() bool {\n\treturn oc.SetChannelModPolicyDuringCreateVal\n}\n\n\nfunc (oc *OrdererCapabilities) Resubmission() bool {\n\treturn oc.ResubmissionVal\n}\n\nfunc (scm *Orderer) BatchSize() *ab.BatchSize ", "output": "{\n\treturn scm.BatchSizeVal\n}"} {"input": "package version\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\ntype DottedVersion struct {\n\tMajor int\n\tMinor int\n\tPatch int\n}\n\n\n\n\n\nfunc Parse(s string) (*DottedVersion, error) {\n\tr, _ := regexp.Compile(`^([0-9]+.[0-9]+(.[0-9]+))?.*`)\n\tmatches := r.FindAllStringSubmatch(s, -1)\n\tif len(matches[0]) < 2 {\n\t\treturn nil, fmt.Errorf(\"Can't parse a version\")\n\t}\n\treturn NewDottedVersion(matches[0][1])\n}\n\n\nfunc (v *DottedVersion) String() string {\n\tversion := fmt.Sprintf(\"%d.%d\", v.Major, v.Minor)\n\tif v.Patch != -1 {\n\t\tversion += fmt.Sprintf(\".%d\", v.Patch)\n\t}\n\treturn version\n}\n\n\nfunc (v *DottedVersion) Compare(other *DottedVersion) int {\n\tresult := compareInts(v.Major, other.Major)\n\tif result != 0 {\n\t\treturn result\n\t}\n\tresult = compareInts(v.Minor, other.Minor)\n\tif result != 0 {\n\t\treturn result\n\t}\n\treturn compareInts(v.Patch, other.Patch)\n}\n\nfunc compareInts(i1 int, i2 int) int {\n\tswitch {\n\tcase i1 < i2:\n\t\treturn -1\n\tcase i1 > i2:\n\t\treturn 1\n\tdefault:\n\t\treturn 0\n\t}\n}\n\nfunc NewDottedVersion(versionString string) (*DottedVersion, error) ", "output": "{\n\tformatError := fmt.Errorf(\"Invalid version format: %s\", versionString)\n\tsplit := strings.Split(versionString, \".\")\n\tif len(split) < 2 {\n\t\treturn nil, formatError\n\t}\n\n\tmaj, err := strconv.Atoi(split[0])\n\tif err != nil {\n\t\treturn nil, formatError\n\t}\n\n\tmin, err := strconv.Atoi(split[1])\n\tif err != nil {\n\t\treturn nil, formatError\n\t}\n\n\tpatch := -1\n\tif len(split) == 3 {\n\t\tpatch, err = strconv.Atoi(split[2])\n\t\tif err != nil {\n\t\t\treturn nil, formatError\n\t\t}\n\t}\n\n\treturn &DottedVersion{\n\t\tMajor: maj,\n\t\tMinor: min,\n\t\tPatch: patch,\n\t}, nil\n}"} {"input": "package structs\n\nimport \"fmt\"\n\n\ntype Bitmap []byte\n\n\nfunc NewBitmap(size uint) (Bitmap, error) {\n\tif size == 0 {\n\t\treturn nil, fmt.Errorf(\"bitmap must be positive size\")\n\t}\n\tif size&7 != 0 {\n\t\treturn nil, fmt.Errorf(\"bitmap must be byte aligned\")\n\t}\n\tb := make([]byte, size>>3)\n\treturn Bitmap(b), nil\n}\n\n\nfunc (b Bitmap) Copy() (Bitmap, error) {\n\tif b == nil {\n\t\treturn nil, fmt.Errorf(\"can't copy nil Bitmap\")\n\t}\n\n\traw := make([]byte, len(b))\n\tcopy(raw, b)\n\treturn Bitmap(raw), nil\n}\n\n\nfunc (b Bitmap) Size() uint {\n\treturn uint(len(b) << 3)\n}\n\n\nfunc (b Bitmap) Set(idx uint) {\n\tbucket := idx >> 3\n\tmask := byte(1 << (idx & 7))\n\tb[bucket] |= mask\n}\n\n\n\n\n\nfunc (b Bitmap) Clear() {\n\tfor i := range b {\n\t\tb[i] = 0\n\t}\n}\n\n\n\nfunc (b Bitmap) IndexesInRange(set bool, from, to uint) []int {\n\tvar indexes []int\n\tfor i := from; i < to; i++ {\n\t\tc := b.Check(i)\n\t\tif c && set || !c && !set {\n\t\t\tindexes = append(indexes, int(i))\n\t\t}\n\t}\n\n\treturn indexes\n}\n\nfunc (b Bitmap) Check(idx uint) bool ", "output": "{\n\tbucket := idx >> 3\n\tmask := byte(1 << (idx & 7))\n\treturn (b[bucket] & mask) != 0\n}"} {"input": "package parlib\n\nimport (\n\t\"errors\"\n)\n\n\nfunc Cstrlen(str []byte) int {\n var i int = 0\n for (str[i] != 0) { i++ }\n return i\n}\n\n\n\n\n\n\n\n\n\nfunc ByteSliceFromString(s string) ([]byte, error) {\n\tfor i := 0; i < len(s); i++ {\n\t\tif s[i] == 0 {\n\t\t\treturn nil, errors.New(\"String contains a NULL byte.\")\n\t\t}\n\t}\n\ta := make([]byte, len(s)+1)\n\tcopy(a, s)\n\treturn a, nil\n}\n\n\n\n\nfunc StringBytePtr(s string) *byte { return &StringByteSlice(s)[0] }\n\n\n\n\nfunc BytePtrFromString(s string) (*byte, error) {\n\ta, err := ByteSliceFromString(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &a[0], nil\n}\n\n\n\n\nfunc StringSlicePtr(ss []string) []*byte {\n bb := make([]*byte, len(ss)+1)\n for i := 0; i < len(ss); i++ {\n bb[i] = StringBytePtr(ss[i])\n }\n bb[len(ss)] = nil\n return bb\n}\n\n\n\n\nfunc SlicePtrFromStrings(ss []string) ([]*byte, error) {\n var err error\n bb := make([]*byte, len(ss)+1)\n for i := 0; i < len(ss); i++ {\n bb[i], err = BytePtrFromString(ss[i])\n if err != nil {\n return nil, err\n }\n }\n bb[len(ss)] = nil\n return bb, nil\n}\n\nfunc StringByteSlice(s string) []byte ", "output": "{\n\ta, err := ByteSliceFromString(s)\n\tif err != nil {\n\t\tpanic(\"syscall: string with NUL passed to StringByteSlice\")\n\t}\n\treturn a\n}"} {"input": "package model\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aiyi/go-user/db\"\n)\n\n\n\n\n\n\n\n\nfunc bindQQ(userId int64, openid string) (err error) {\n\tpara := struct {\n\t\tUserId int64 `sqlx:\"user_id\"`\n\t\tOpenId string `sqlx:\"openid\"`\n\t\tBindType BindType `sqlx:\"bind_type\"`\n\t}{\n\t\tUserId: userId,\n\t\tOpenId: openid,\n\t\tBindType: BindTypeQQ,\n\t}\n\n\ttx, err := db.GetDB().Beginx()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tstmt1, err := tx.Prepare(\"insert into user_qq(user_id, openid, verified) values(?, ?, 1)\")\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn\n\t}\n\tif _, err = stmt1.Exec(para.UserId, para.OpenId); err != nil {\n\t\ttx.Rollback()\n\t\treturn\n\t}\n\n\tstmt2, err := tx.PrepareNamed(\"update user set bind_types = bind_types|:bind_type where id=:user_id and verified=1 and bind_types&:bind_type=0\")\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn\n\t}\n\trslt2, err := stmt2.Exec(para)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn\n\t}\n\trowsAffected2, err := rslt2.RowsAffected()\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn\n\t}\n\tif rowsAffected2 != 1 {\n\t\terr = fmt.Errorf(\"绑定QQ %s 到用户 %d 失败\", para.OpenId, para.UserId)\n\t\ttx.Rollback()\n\t\treturn\n\t}\n\n\terr = tx.Commit()\n\treturn\n}\n\nfunc BindQQ(userId int64, openid string) (err error) ", "output": "{\n\tif err = removeFromCache(userId); err != nil {\n\t\treturn\n\t}\n\tif err = bindQQ(userId, openid); err != nil {\n\t\treturn\n\t}\n\treturn syncToCache(userId)\n}"} {"input": "package framework\n\ntype HorizontalAlignment int\n\nconst (\n\tAlignLeft HorizontalAlignment = iota\n\tAlignCenter\n\tAlignRight\n)\n\nfunc (a HorizontalAlignment) AlignLeft() bool { return a == AlignLeft }\n\nfunc (a HorizontalAlignment) AlignRight() bool { return a == AlignRight }\n\ntype VerticalAlignment int\n\nconst (\n\tAlignTop VerticalAlignment = iota\n\tAlignMiddle\n\tAlignBottom\n)\n\nfunc (a VerticalAlignment) AlignTop() bool { return a == AlignTop }\nfunc (a VerticalAlignment) AlignMiddle() bool { return a == AlignMiddle }\nfunc (a VerticalAlignment) AlignBottom() bool { return a == AlignBottom }\n\nfunc (a HorizontalAlignment) AlignCenter() bool ", "output": "{ return a == AlignCenter }"} {"input": "package classfile\n\n\ntype ConstantStringInfo struct {\n\tcp ConstantPool\n\tstringIndex uint16\n}\n\nfunc (self *ConstantStringInfo) readInfo(reader *ClassReader) {\n\tself.stringIndex = reader.readUint16()\n}\n\nfunc (self *ConstantStringInfo) toString() string {\n\treturn \"String\"\n}\n\nfunc (self *ConstantStringInfo) String() string ", "output": "{\n\treturn self.cp.getUtf8(self.stringIndex)\n}"} {"input": "package remotecache\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/bradfitz/gomemcache/memcache\"\n\t\"github.com/grafana/grafana/pkg/setting\"\n)\n\nconst memcachedCacheType = \"memcached\"\n\ntype memcachedStorage struct {\n\tc *memcache.Client\n}\n\n\n\nfunc newItem(sid string, data []byte, expire int32) *memcache.Item {\n\treturn &memcache.Item{\n\t\tKey: sid,\n\t\tValue: data,\n\t\tExpiration: expire,\n\t}\n}\n\n\nfunc (s *memcachedStorage) Set(ctx context.Context, key string, val interface{}, expires time.Duration) error {\n\titem := &cachedItem{Val: val}\n\tbytes, err := encodeGob(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar expiresInSeconds int64\n\tif expires != 0 {\n\t\texpiresInSeconds = int64(expires) / int64(time.Second)\n\t}\n\n\tmemcachedItem := newItem(key, bytes, int32(expiresInSeconds))\n\treturn s.c.Set(memcachedItem)\n}\n\n\nfunc (s *memcachedStorage) Get(ctx context.Context, key string) (interface{}, error) {\n\tmemcachedItem, err := s.c.Get(key)\n\tif err != nil && err.Error() == \"memcache: cache miss\" {\n\t\treturn nil, ErrCacheItemNotFound\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titem := &cachedItem{}\n\n\terr = decodeGob(memcachedItem.Value, item)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn item.Val, nil\n}\n\n\nfunc (s *memcachedStorage) Delete(ctx context.Context, key string) error {\n\treturn s.c.Delete(key)\n}\n\nfunc newMemcachedStorage(opts *setting.RemoteCacheOptions) *memcachedStorage ", "output": "{\n\treturn &memcachedStorage{\n\t\tc: memcache.New(opts.ConnStr),\n\t}\n}"} {"input": "package sol\n\n\ntype Operator interface {\n\tWrap(string) string \n}\n\n\nfunc Function(name string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(FuncClause{Name: name})\n}\n\n\n\n\n\nfunc Count(col Columnar) ColumnElem {\n\treturn Function(COUNT, col)\n}\n\n\nfunc Date(col Columnar) ColumnElem {\n\treturn Function(DATE, col)\n}\n\n\n\nfunc DatePart(part string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(\n\t\tFuncClause{Name: DATEPART},\n\t).AddOperator(\n\t\tArrayClause{clauses: []Clause{String(part)}, post: true, sep: \", \"},\n\t)\n}\n\n\nfunc Max(col Columnar) ColumnElem {\n\treturn Function(MAX, col)\n}\n\n\nfunc Min(col Columnar) ColumnElem {\n\treturn Function(MIN, col)\n}\n\n\nfunc StdDev(col Columnar) ColumnElem {\n\treturn Function(STDDEV, col)\n}\n\n\nfunc Sum(col Columnar) ColumnElem {\n\treturn Function(SUM, col)\n}\n\n\nfunc Variance(col Columnar) ColumnElem {\n\treturn Function(VARIANCE, col)\n}\n\nfunc Avg(col Columnar) ColumnElem ", "output": "{\n\treturn Function(AVG, col)\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst letterBytes = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst lenLetters = len(letterBytes)\n\nfunc init() {\n\trand.Seed(time.Now().UnixNano())\n}\n\n\n\nfunc sendJson(w http.ResponseWriter, data interface{}) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(data)\n}\n\nfunc sendOk(w http.ResponseWriter, data interface{}) {\n\tjson.NewEncoder(w).Encode(data)\n}\n\nfunc sendError(w http.ResponseWriter, msg string) {\n\tdata := struct {\n\t\tOk bool `json:\"ok\"`\n\t\tMsg string `json:\"msg\"`\n\t}{\n\t\tOk: false,\n\t\tMsg: msg,\n\t}\n\n\tsendJson(w, data)\n}\n\nfunc randStr(n int) string ", "output": "{\n\tb := make([]byte, n)\n\tfor i := range b {\n\t\tb[i] = letterBytes[rand.Int63()%int64(len(letterBytes))]\n\t}\n\treturn string(b)\n}"} {"input": "package controllers\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/jinzhu/gorm\"\n\t\"github.com/lkkadiri/goboot/models\"\n)\n\ntype (\n\tUserController struct {\n\t\tdbConn *gorm.DB\n\t}\n)\n\n\nfunc NewUserController(db *gorm.DB) *UserController {\n\treturn &UserController{db}\n}\n\n\nfunc (uc UserController) GetAllUsers(w http.ResponseWriter, r *http.Request) {\n\tu := []models.User{}\n\tuc.dbConn.Find(&u)\n\tuj, _ := json.Marshal(u)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tfmt.Fprintf(w, \"%s\", uj)\n}\n\n\n\n\n\nfunc (uc UserController) CreateUser(w http.ResponseWriter, r *http.Request) {\n\tu := &models.User{}\n\tjson.NewDecoder(r.Body).Decode(u)\n\tuc.dbConn.Create(u)\n\tuj, _ := json.Marshal(u)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tfmt.Fprintf(w, \"%s\", uj)\n}\n\n\nfunc (uc UserController) RemoveUser(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tuserID, err := strconv.Atoi(vars[\"id\"])\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Cannot parse user id\")\n\t}\n\tu := &models.User{}\n\tuc.dbConn.Delete(u, userID)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n}\n\nfunc (uc UserController) GetUser(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tvars := mux.Vars(r)\n\tuserID, err := strconv.Atoi(vars[\"id\"])\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Cannot parse user id\")\n\t}\n\n\tu := &models.User{}\n\tuc.dbConn.Find(u, userID)\n\tuj, _ := json.Marshal(u)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tfmt.Fprintf(w, \"%s\", uj)\n}"} {"input": "package online\n\nimport (\n\t\"monitor/log\"\n\t\"time\"\n)\n\nvar (\n\tsessions = make(map[string]*Session) \n)\n\nconst Expired = 60 * 30\n\n\nfunc init() {\n\tlog.Info(\"Session is started,expired every %d seconds\", Expired)\n\tgo func() {\n\t\tvar i int\n\t\ttimer := time.Tick(time.Minute)\n\t\tfor t := range timer {\n\t\t\ti = 0\n\t\t\tlock.Lock()\n\t\t\tfor k, s := range sessions {\n\t\t\t\tif s.IsExpired() {\n\t\t\t\t\tdelete(sessions, k)\n\t\t\t\t\ti = i + 1\n\t\t\t\t}\n\t\t\t}\n\t\t\tlock.Unlock()\n\t\t\tlog.Infof(\"clear %d sessions at %v,used %v\", i, t, time.Since(t))\n\t\t}\n\t}()\n}\n\n\ntype Session struct {\n\tUID string\n\tName string\n\tKey string\n\tLastTime time.Time\n}\n\n\nfunc (this *Session) IsExpired() bool {\n\treturn time.Since(this.LastTime).Seconds() > Expired\n}\n\n\nfunc SetSession(uid string, name string, key string) {\n\ts := &Session{UID: uid, Key: key, LastTime: time.Now()}\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tsessions[uid] = s\n}\n\n\n\n\n\nfunc FreshSession(id string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tif s, ok := sessions[id]; ok {\n\t\ts.LastTime = time.Now()\n\t}\n}\n\n\nfunc RemoveSession(id string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tif _, ok := sessions[id]; ok {\n\t\tdelete(sessions, id)\n\t}\n}\n\nfunc GetSession(id string) (name string, key string, ok bool) ", "output": "{\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\n\tif s, exists := sessions[id]; exists {\n\t\tkey = s.Key\n\t\tname = s.Name\n\t\tok = true\n\t\ts.LastTime = time.Now()\n\t}\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\n\tfmt.Println(\"Launching server...\")\n\tfor {\n\t\tconnect()\n\n\t\ttime.Sleep(5 * time.Second)\n\t}\n}\n\n \n\nfunc handleConnection(conn net.Conn) int {\n\n\tconnbuf := bufio.NewReader(conn)\n\n\tfor {\n\t\tmessage, err := connbuf.ReadString('\\n')\n\n\t\tif err != nil {\n\t\t\treturn 0\n\t\t}\n\t\tfmt.Println(\"Message Received:\", string(message), \"Error:\", err, \"\\n\")\n\n\t\tnewmessage := strings.ToUpper(message)\n\n\t\tconn.Write([]byte(newmessage + \"\\n\"))\n\t}\n\n}\n\nfunc connect() int ", "output": "{\n\n\tfmt.Println(\"Listening port 8081\")\n\n\tln, _ := net.Listen(\"tcp\", \":8081\")\n\n\tconn, _ := ln.Accept()\n\n\thandleConnection(conn)\n\n\treturn 0\n\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-chi/chi\"\n)\n\ntype todosResource struct{}\n\n\nfunc (rs todosResource) Routes() chi.Router {\n\tr := chi.NewRouter()\n\n\tr.Get(\"/\", rs.List) \n\tr.Post(\"/\", rs.Create) \n\tr.Put(\"/\", rs.Delete)\n\n\tr.Route(\"/{id}\", func(r chi.Router) {\n\t\tr.Get(\"/\", rs.Get) \n\t\tr.Put(\"/\", rs.Update) \n\t\tr.Delete(\"/\", rs.Delete) \n\t\tr.Get(\"/sync\", rs.Sync)\n\t})\n\n\treturn r\n}\n\n\n\nfunc (rs todosResource) Create(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todos create\"))\n}\n\nfunc (rs todosResource) Get(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo get\"))\n}\n\nfunc (rs todosResource) Update(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo update\"))\n}\n\nfunc (rs todosResource) Delete(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo delete\"))\n}\n\nfunc (rs todosResource) Sync(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo sync\"))\n}\n\nfunc (rs todosResource) List(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tw.Write([]byte(\"todos list of stuff..\"))\n}"} {"input": "package connmgr\n\nimport \"github.com/abcsuite/abclog\"\n\n\n\n\nvar log abclog.Logger\n\n\nfunc init() {\n\tDisableLog()\n}\n\n\n\nfunc DisableLog() {\n\tlog = abclog.Disabled\n}\n\n\n\n\n\n\nfunc UseLogger(logger abclog.Logger) ", "output": "{\n\tlog = logger\n}"} {"input": "package kthlargest\n\nimport \"container/heap\"\n\ntype MaxHeap struct {\n\tSize int\n\tNums []int\n}\n\nfunc (h *MaxHeap) Insert(x int) {\n\tif h.Len() < h.Size {\n\t\theap.Push(h, x)\n\t} else if h.Nums[0] < x {\n\t\th.Nums[0] = x\n\t\theap.Fix(h, 0)\n\t}\n}\n\nfunc (h *MaxHeap) Len() int { return len(h.Nums) }\n\nfunc (h *MaxHeap) Less(i, j int) bool {\n\treturn h.Nums[i] < h.Nums[j]\n}\n\nfunc (h *MaxHeap) Swap(i, j int) {\n\th.Nums[i], h.Nums[j] = h.Nums[j], h.Nums[i]\n}\n\nfunc (h *MaxHeap) Push(x interface{}) {\n\th.Nums = append(h.Nums, x.(int))\n}\n\nfunc (h *MaxHeap) Pop() interface{} {\n\tn := len(h.Nums)\n\tx := h.Nums[n-1]\n\th.Nums = h.Nums[:n-1]\n\treturn x\n}\n\n\n\nfunc findKthLargest(nums []int, k int) int ", "output": "{\n\th := &MaxHeap{Size: k}\n\tfor _, num := range nums {\n\t\th.Insert(num)\n\t}\n\treturn h.Nums[0]\n}"} {"input": "package state\n\n\n\nfunc (s *Store) setupDefaultTestEntMeta() error ", "output": "{\n\treturn nil\n}"} {"input": "package geom\n\nimport \"math\"\n\n\ntype MultiLineString []LineString\n\n\nfunc (ml MultiLineString) Bounds() *Bounds {\n\tb := NewBounds()\n\tfor _, l := range ml {\n\t\tb.Extend(l.Bounds())\n\t}\n\treturn b\n}\n\n\nfunc (ml MultiLineString) Length() float64 {\n\tlength := 0.\n\tfor _, l := range ml {\n\t\tlength += l.Length()\n\t}\n\treturn length\n}\n\n\nfunc (ml MultiLineString) Within(p Polygonal) WithinStatus {\n\tfor _, l := range ml {\n\t\tif l.Within(p) == Outside {\n\t\t\treturn Outside\n\t\t}\n\t}\n\treturn Inside\n}\n\n\n\n\nfunc (ml MultiLineString) Distance(p Point) float64 ", "output": "{\n\td := math.Inf(1)\n\tfor _, l := range ml {\n\t\tlDist := l.Distance(p)\n\t\td = math.Min(d, lDist)\n\t}\n\treturn d\n}"} {"input": "package identity\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype DeleteUserRequest struct {\n\n\tUserId *string `mandatory:\"true\" contributesTo:\"path\" name:\"userId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteUserRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteUserRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request DeleteUserRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteUserResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response DeleteUserResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response DeleteUserResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package object\n\nimport (\n\t\"github.com/vmware/govmomi/vim25\"\n\t\"github.com/vmware/govmomi/vim25/methods\"\n\t\"github.com/vmware/govmomi/vim25/types\"\n\t\"golang.org/x/net/context\"\n)\n\ntype OptionManager struct {\n\tCommon\n}\n\n\n\nfunc (m OptionManager) Query(ctx context.Context, name string) ([]types.BaseOptionValue, error) {\n\treq := types.QueryOptions{\n\t\tThis: m.Reference(),\n\t\tName: name,\n\t}\n\n\tres, err := methods.QueryOptions(ctx, m.Client(), &req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res.Returnval, nil\n}\n\nfunc (m OptionManager) Update(ctx context.Context, value []types.BaseOptionValue) error {\n\treq := types.UpdateOptions{\n\t\tThis: m.Reference(),\n\t\tChangedValue: value,\n\t}\n\n\t_, err := methods.UpdateOptions(ctx, m.Client(), &req)\n\treturn err\n}\n\nfunc NewOptionManager(c *vim25.Client, ref types.ManagedObjectReference) *OptionManager ", "output": "{\n\treturn &OptionManager{\n\t\tCommon: NewCommon(c, ref),\n\t}\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/kataras/iris/v12/_examples/mvc/vuejs-todo-mvc/src/todo\"\n\n\t\"github.com/kataras/iris/v12\"\n\t\"github.com/kataras/iris/v12/mvc\"\n\t\"github.com/kataras/iris/v12/sessions\"\n\t\"github.com/kataras/iris/v12/websocket\"\n)\n\n\ntype TodoController struct {\n\tService todo.Service\n\n\tSession *sessions.Session\n\n\tNS *websocket.NSConn\n}\n\n\n\n\n\nfunc (c *TodoController) BeforeActivation(b mvc.BeforeActivation) {\n\tb.Dependencies().Register(func(ctx iris.Context) (items []todo.Item) {\n\t\tctx.ReadJSON(&items)\n\t\treturn\n\t}) \n}\n\n\n\n\n\n\ntype PostItemResponse struct {\n\tSuccess bool `json:\"success\"`\n}\n\nvar emptyResponse = PostItemResponse{Success: false}\n\n\nfunc (c *TodoController) Post(newItems []todo.Item) PostItemResponse {\n\tif err := c.Service.Save(c.Session.ID(), newItems); err != nil {\n\t\treturn emptyResponse\n\t}\n\n\treturn PostItemResponse{Success: true}\n}\n\nfunc (c *TodoController) Save(msg websocket.Message) error {\n\tid := c.Session.ID()\n\tc.NS.Conn.Server().Broadcast(nil, websocket.Message{\n\t\tNamespace: msg.Namespace,\n\t\tEvent: \"saved\",\n\t\tTo: id,\n\t\tBody: websocket.Marshal(c.Service.Get(id)),\n\t})\n\n\treturn nil\n}\n\nfunc (c *TodoController) Get() []todo.Item ", "output": "{\n\treturn c.Service.Get(c.Session.ID())\n}"} {"input": "package synapse\n\nimport (\n\t\"fmt\"\n)\n\n\n\ntype Handler interface {\n\n\tServeCall(req Request, res ResponseWriter)\n}\n\n\n\ntype Status int\n\n\n\n\n\n\nconst (\n\tStatusInvalid Status = iota \n\tStatusOK \n\tStatusNotFound \n\tStatusCondition \n\tStatusBadRequest \n\tStatusNotAuthed \n\tStatusServerError \n\tStatusOther \n)\n\n\n\n\n\ntype ResponseError struct {\n\tCode Status\n\tExpl string\n}\n\n\n\n\n\nfunc (s Status) String() string {\n\tswitch s {\n\tcase StatusOK:\n\t\treturn \"OK\"\n\tcase StatusNotFound:\n\t\treturn \"not found\"\n\tcase StatusCondition:\n\t\treturn \"precondition failed\"\n\tcase StatusBadRequest:\n\t\treturn \"bad request\"\n\tcase StatusNotAuthed:\n\t\treturn \"not authorized\"\n\tcase StatusServerError:\n\t\treturn \"server error\"\n\tcase StatusOther:\n\t\treturn \"other\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"Status(%d)\", s)\n\t}\n}\n\nfunc (e *ResponseError) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"synapse: response error (%s): %s\", e.Code, e.Expl)\n}"} {"input": "package utils\n\n\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\ntype MultiError struct {\n\tErrors []error\n\tErrorFormat ErrorFormatFunc\n}\n\nfunc (e *MultiError) Error() string {\n\tfn := e.ErrorFormat\n\tif fn == nil {\n\t\tfn = ListFormatFunc\n\t}\n\n\treturn fn(e.Errors)\n}\n\n\n\n\n\nfunc (e *MultiError) ErrorOrNil() error {\n\tif e == nil {\n\t\treturn nil\n\t}\n\tif len(e.Errors) == 0 {\n\t\treturn nil\n\t}\n\n\treturn e\n}\n\nfunc (e *MultiError) GoString() string {\n\treturn fmt.Sprintf(\"*%#v\", *e)\n}\n\n\n\n\n\n\n\n\nfunc (e *MultiError) WrappedErrors() []error {\n\treturn e.Errors\n}\n\n\n\ntype ErrorFormatFunc func([]error) string\n\n\n\nfunc ListFormatFunc(es []error) string {\n\tpoints := make([]string, len(es))\n\tfor i, err := range es {\n\t\tpoints[i] = fmt.Sprintf(\"* %s\", err)\n\t}\n\n\treturn fmt.Sprintf(\n\t\t\"%d error(s) occurred:\\n\\n%s\",\n\t\tlen(es), strings.Join(points, \"\\n\"))\n}\n\n\n\n\n\n\n\n\n\nfunc AppendMulti(err error, errs ...error) *MultiError ", "output": "{\n\tswitch err := err.(type) {\n\tcase *MultiError:\n\t\tif err == nil {\n\t\t\terr = new(MultiError)\n\t\t}\n\n\t\tfor _, e := range errs {\n\t\t\tswitch e := e.(type) {\n\t\t\tcase *MultiError:\n\t\t\t\terr.Errors = append(err.Errors, e.Errors...)\n\t\t\tdefault:\n\t\t\t\terr.Errors = append(err.Errors, e)\n\t\t\t}\n\t\t}\n\n\t\treturn err\n\tdefault:\n\t\tnewErrs := make([]error, 0, len(errs)+1)\n\t\tif err != nil {\n\t\t\tnewErrs = append(newErrs, err)\n\t\t}\n\t\tnewErrs = append(newErrs, errs...)\n\n\t\treturn AppendMulti(&MultiError{}, newErrs...)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/truveris/ygor/ygord/alias\"\n\t\"net/http\"\n)\n\n\ntype AliasListHandler struct {\n\t*Server\n}\n\n\n\ntype AliasListResponse struct {\n\tAliases []alias.Alias `json:\"aliases\"`\n}\n\n\n\n\n\nfunc (handler *AliasListHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\t_, err := auth(r)\n\tif err != nil {\n\t\terrorHandler(w, \"Authentication failed\", err)\n\t\treturn\n\t}\n\n\taliases, err := handler.Server.Aliases.All()\n\tif err != nil {\n\t\terrorHandler(w, \"failed to get aliases\", err)\n\t\treturn\n\t}\n\n\tresponse := AliasListResponse{Aliases: aliases}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tencoder := json.NewEncoder(w)\n\terr = encoder.Encode(response)\n\tif err != nil {\n\t\terrorHandler(w, \"failed to encode response JSON\", err)\n\t\treturn\n\t}\n}"} {"input": "package spotify\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/laicosly/goth\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc provider() *Provider {\n\treturn New(os.Getenv(\"SPOTIFY_KEY\"), os.Getenv(\"SPOTIFY_SECRET\"), \"/foo\", \"user\")\n}\n\nfunc Test_New(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\tp := provider()\n\n\ta.Equal(p.ClientKey, os.Getenv(\"SPOTIFY_KEY\"))\n\ta.Equal(p.Secret, os.Getenv(\"SPOTIFY_SECRET\"))\n\ta.Equal(p.CallbackURL, \"/foo\")\n}\n\nfunc Test_ImplementsProvider(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\ta.Implements((*goth.Provider)(nil), provider())\n}\n\nfunc Test_BeginAuth(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\n\tp := provider()\n\tsession, err := p.BeginAuth(\"test_state\")\n\ts := session.(*Session)\n\ta.NoError(err)\n\ta.Contains(s.AuthURL, \"accounts.spotify.com/authorize\")\n}\n\n\n\nfunc Test_SessionFromJSON(t *testing.T) ", "output": "{\n\tt.Parallel()\n\ta := assert.New(t)\n\n\tp := provider()\n\tsession, err := p.UnmarshalSession(`{\"AuthURL\":\"http://accounts.spotify.com/authorize\",\"AccessToken\":\"1234567890\"}`)\n\ta.NoError(err)\n\n\ts := session.(*Session)\n\ta.Equal(s.AuthURL, \"http://accounts.spotify.com/authorize\")\n\ta.Equal(s.AccessToken, \"1234567890\")\n}"} {"input": "package models\n\nimport \"fmt\"\n\n\nvar RoomPool = make([] *Room, 0)\n\nfunc AddRoom(r *Room) {\n\tRoomPool = append(RoomPool, r)\n}\n\n\n\n\n\nfunc FindRoom(d string) (int, *Room) {\n\tfor i, v := range RoomPool {\n\t\tif v.Name == d {\n\t\t\treturn i, v\n\t\t}\n\t}\n\treturn -1, &Room{}\n}\n\n\nfunc RemoveRoom(r *Room) {\n\n\tindex, _ := FindRoom(r.Name)\n\n\tif index != -1 {\n\t\tRoomPool = append(RoomPool[:index], RoomPool[index + 1:]...)\n\t}\n}\n\n\n\n\nfunc RemoveClient(c *Client) {\n\tfor _, room := range RoomPool{\n\t\tif room.Name == c.Room {\n\t\t\tif room.HasClient(c) {\n\t\t\t\troom.DeleteClient(c)\n\t\t\t\tif room.ClientCount() == 0 {\n\t\t\t\t\tRemoveRoom(room)\n\t\t\t\t\tPoolBroadcast(NewMessage(map[string]string{\n\t\t\t\t\t\t\"connectedClients\": fmt.Sprintf(\"%v\", GetAllClients()),\n\t\t\t\t\t\t\"numberOfRooms\": fmt.Sprintf(\"%v\", GetNumberOfRooms()),\n\t\t\t\t\t}))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\nfunc ListRooms() (int, []string) {\n\tpool := make([]string, 0)\n\tfor _, obj := range RoomPool {\n\t\tpool = append(pool, obj.Name)\n\t}\n\treturn len(RoomPool), pool\n}\n\n\n\n\n\nfunc GetAllClients() int {\n\n\tclientSum := 0\n\tfor _, room := range RoomPool {\n\t\tclientSum += len(room.ClientPool)\n\t}\n\treturn clientSum\n}\n\n\nfunc GetNumberOfRooms() int{\n\treturn len(RoomPool)\n}\n\nfunc PoolBroadcast(m Message) ", "output": "{\n\tfor _, room := range RoomPool {\n\t\troom.RoomBroadcast(m)\n\t}\n}"} {"input": "package dao\n\nimport (\n\t\"github.com/astaxie/beego/orm\"\n\t\"github.com/vmware/harbor/src/common/models\"\n\n\t\"fmt\"\n\t\"time\"\n)\n\n\nfunc AddScanJob(job models.ScanJob) (int64, error) {\n\to := GetOrmer()\n\tif len(job.Status) == 0 {\n\t\tjob.Status = models.JobPending\n\t}\n\treturn o.Insert(&job)\n}\n\n\n\n\n\nfunc GetScanJobsByImage(repository, tag string, limit ...int) ([]*models.ScanJob, error) {\n\tvar res []*models.ScanJob\n\t_, err := scanJobQs(limit...).Filter(\"repository\", repository).Filter(\"tag\", tag).OrderBy(\"-id\").All(&res)\n\treturn res, err\n}\n\n\nfunc GetScanJobsByDigest(digest string, limit ...int) ([]*models.ScanJob, error) {\n\tvar res []*models.ScanJob\n\t_, err := scanJobQs(limit...).Filter(\"digest\", digest).OrderBy(\"-id\").All(&res)\n\treturn res, err\n}\n\n\nfunc UpdateScanJobStatus(id int64, status string) error {\n\to := GetOrmer()\n\tsj := models.ScanJob{\n\t\tID: id,\n\t\tStatus: status,\n\t\tUpdateTime: time.Now(),\n\t}\n\tn, err := o.Update(&sj, \"Status\", \"UpdateTime\")\n\tif n == 0 {\n\t\treturn fmt.Errorf(\"Failed to update scan job with id: %d, error: %v\", id, err)\n\t}\n\treturn err\n}\n\nfunc scanJobQs(limit ...int) orm.QuerySeter {\n\to := GetOrmer()\n\tl := -1\n\tif len(limit) == 1 {\n\t\tl = limit[0]\n\t}\n\treturn o.QueryTable(models.ScanJobTable).Limit(l)\n}\n\nfunc GetScanJob(id int64) (*models.ScanJob, error) ", "output": "{\n\to := GetOrmer()\n\tj := models.ScanJob{ID: id}\n\terr := o.Read(&j)\n\tif err == orm.ErrNoRows {\n\t\treturn nil, nil\n\t}\n\treturn &j, nil\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/labstack/echo\"\n)\n\n\ntype Error struct {\n\tMessage string `json:\"message\"`\n}\n\n\nfunc OK(c echo.Context, payload interface{}) error {\n\treturn c.JSON(http.StatusOK, payload)\n}\n\n\n\n\n\nfunc NoContent(c echo.Context) error {\n\treturn c.NoContent(http.StatusNoContent)\n}\n\n\nfunc BadRequest(c echo.Context, msg string) error {\n\treturn c.JSON(http.StatusBadRequest, Error{msg})\n}\n\n\nfunc NotFound(c echo.Context) error {\n\treturn c.JSON(http.StatusNotFound, Error{\"Resource not found\"})\n}\n\n\nfunc Conflict(c echo.Context, msg string) error {\n\treturn c.JSON(http.StatusConflict, Error{msg})\n}\n\n\nfunc Invalid(c echo.Context, msg string) error {\n\treturn c.JSON(422, Error{msg})\n}\n\n\n\nfunc InternalServerError(c echo.Context, err error) error {\n\tlog.WithFields(log.Fields{\n\t\t\"request_id\": RequestID(c),\n\t}).Error(err)\n\n\treturn c.JSON(http.StatusInternalServerError, Error{\"Oops! Something went wrong\"})\n}\n\nfunc Created(c echo.Context, payload interface{}) error ", "output": "{\n\treturn c.JSON(http.StatusCreated, payload)\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"github.com/go-swagger/go-swagger/errors\"\n\t\"github.com/go-swagger/go-swagger/strfmt\"\n\t\"github.com/go-swagger/go-swagger/swag\"\n)\n\n\ntype NotificationPageableResult struct {\n\n\tContent []*Notification `json:\"content,omitempty\"`\n\n\tFirst bool `json:\"first,omitempty\"`\n\n\tLast bool `json:\"last,omitempty\"`\n\n\tNumber int32 `json:\"number,omitempty\"`\n\n\tNumberOfElements int32 `json:\"numberOfElements,omitempty\"`\n\n\tServerTime int64 `json:\"serverTime,omitempty\"`\n\n\tSize int32 `json:\"size,omitempty\"`\n\n\tTotalElements int32 `json:\"totalElements,omitempty\"`\n\n\tTotalPages int32 `json:\"totalPages,omitempty\"`\n}\n\n\n\n\nfunc (m *NotificationPageableResult) validateContent(formats strfmt.Registry) error {\n\n\tif swag.IsZero(m.Content) { \n\t\treturn nil\n\t}\n\n\tfor i := 0; i < len(m.Content); i++ {\n\n\t\tif m.Content[i] != nil {\n\n\t\t\tif err := m.Content[i].Validate(formats); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nfunc (m *NotificationPageableResult) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateContent(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n)\n\ntype Monitor interface {\n\tGetVariables() []string\n\tGetValues([]string) map[string]interface{}\n}\n\nvar monitorDrivers = make(map[string]func(*json.RawMessage) Monitor)\n\n\n\ntype MonitorTrack struct {\n\tVariables map[string]*MonitorTrackVariable\n\tInterval int\n\ttimer *time.Timer\n}\n\nfunc newMonitorTrack() *MonitorTrack {\n\treturn &MonitorTrack{\n\t\tVariables: make(map[string]*MonitorTrackVariable),\n\t}\n}\n\ntype MonitorTrackVariable struct {\n\tHistory int\n\tData []interface{}\n}\n\nfunc (mt *MonitorTrack) SetTrack(variable string, history int) {\n\ttrack, ok := mt.Variables[variable]\n\tif !ok && history > 0 {\n\t\ttrack = &MonitorTrackVariable{}\n\t\tmt.Variables[variable] = track\n\t}\n\tif history == 0 && ok {\n\t\tdelete(mt.Variables, variable)\n\t\treturn\n\t}\n\ttrack.History = history\n}\n\nfunc (mt *MonitorTrack) Start(monitor Monitor) {\n\tgo func() {\n\t\tmt.timer = time.NewTimer(time.Duration(1) * time.Second)\n\t\tfor _ = range mt.timer.C {\n\t\t\tif mt.Interval > 0 {\n\t\t\t\tmt.timer.Reset(time.Second * time.Duration(mt.Interval))\n\t\t\t}\n\t\t\tvariables := []string{}\n\t\t\tfor variable := range mt.Variables {\n\t\t\t\tvariables = append(variables, variable)\n\t\t\t}\n\t\t\tvalues := monitor.GetValues(variables)\n\t\t\tfor variable, vt := range mt.Variables {\n\t\t\t\tvt.Data = append(vt.Data, values[variable])\n\t\t\t\tif len(vt.Data) > vt.History {\n\t\t\t\t\tvt.Data = vt.Data[len(vt.Data)-vt.History:]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc AddMonitorDriver(monitor string, constructor func(*json.RawMessage) Monitor) ", "output": "{\n\tmonitorDrivers[monitor] = constructor\n}"} {"input": "package arn\n\n\nfunc init() {\n\tDataLists[\"anime-character-roles\"] = []*Option{\n\t\t{\"main\", \"Main character\"},\n\t\t{\"supporting\", \"Supporting character\"},\n\t}\n}\n\n\ntype AnimeCharacter struct {\n\tCharacterID string `json:\"characterId\" editable:\"true\"`\n\tRole string `json:\"role\" editable:\"true\" datalist:\"anime-character-roles\"`\n}\n\n\n\n\nfunc (char *AnimeCharacter) Character() *Character ", "output": "{\n\tcharacter, _ := GetCharacter(char.CharacterID)\n\treturn character\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSSecretsManagerRotationSchedule_RotationRules struct {\n\n\tAutomaticallyAfterDays int `json:\"AutomaticallyAfterDays,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\n\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::SecretsManager::RotationSchedule.RotationRules\"\n}"} {"input": "package networkloadbalancer\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\n\ntype Backend struct {\n\n\tPort *int `mandatory:\"true\" json:\"port\"`\n\n\tName *string `mandatory:\"false\" json:\"name\"`\n\n\tIpAddress *string `mandatory:\"false\" json:\"ipAddress\"`\n\n\tTargetId *string `mandatory:\"false\" json:\"targetId\"`\n\n\tWeight *int `mandatory:\"false\" json:\"weight\"`\n\n\tIsDrain *bool `mandatory:\"false\" json:\"isDrain\"`\n\n\tIsBackup *bool `mandatory:\"false\" json:\"isBackup\"`\n\n\tIsOffline *bool `mandatory:\"false\" json:\"isOffline\"`\n}\n\n\n\nfunc (m Backend) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package builders\n\nimport (\n\t\"time\"\n\n\t\"github.com/docker/docker/api/types\"\n)\n\n\n\nfunc Container(name string, builders ...func(container *types.Container)) *types.Container {\n\tcontainer := &types.Container{\n\t\tID: \"container_id\",\n\t\tNames: []string{\"/\" + name},\n\t\tCommand: \"top\",\n\t\tImage: \"busybox:latest\",\n\t\tStatus: \"Up 1 second\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tfor _, builder := range builders {\n\t\tbuilder(container)\n\t}\n\n\treturn container\n}\n\n\n\n\n\nfunc WithName(name string) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tc.Names = append(c.Names, \"/\"+name)\n\t}\n}\n\n\nfunc WithPort(privateport, publicport uint16, builders ...func(*types.Port)) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tif c.Ports == nil {\n\t\t\tc.Ports = []types.Port{}\n\t\t}\n\t\tport := &types.Port{\n\t\t\tPrivatePort: privateport,\n\t\t\tPublicPort: publicport,\n\t\t}\n\t\tfor _, builder := range builders {\n\t\t\tbuilder(port)\n\t\t}\n\t\tc.Ports = append(c.Ports, *port)\n\t}\n}\n\n\nfunc IP(ip string) func(*types.Port) {\n\treturn func(p *types.Port) {\n\t\tp.IP = ip\n\t}\n}\n\n\nfunc TCP(p *types.Port) {\n\tp.Type = \"tcp\"\n}\n\n\nfunc UDP(p *types.Port) {\n\tp.Type = \"udp\"\n}\n\nfunc WithLabel(key, value string) func(*types.Container) ", "output": "{\n\treturn func(c *types.Container) {\n\t\tif c.Labels == nil {\n\t\t\tc.Labels = map[string]string{}\n\t\t}\n\t\tc.Labels[key] = value\n\t}\n}"} {"input": "package cmd\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\n\t\"github.com/tsaikd/gogstash/config/goglog\"\n)\n\n\n\nfunc waitSignals(ctx context.Context) error ", "output": "{\n\tosSignalChan := make(chan os.Signal, 1)\n\tsignal.Notify(osSignalChan, os.Interrupt, syscall.SIGTERM)\n\n\tselect {\n\tcase <-ctx.Done():\n\tcase sig := <-osSignalChan:\n\t\tgoglog.Logger.Info(sig)\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n\tgoahttp \"goa.design/goa/v3/http\"\n\tcli \"goa.design/plugins/v3/goakit/examples/calc/gen/http/cli/calc\"\n)\n\n\n\nfunc httpUsageCommands() string {\n\treturn cli.UsageCommands()\n}\n\nfunc httpUsageExamples() string {\n\treturn cli.UsageExamples()\n}\n\nfunc doHTTP(scheme, host string, timeout int, debug bool) (endpoint.Endpoint, interface{}, error) ", "output": "{\n\tvar (\n\t\tdoer goahttp.Doer\n\t)\n\t{\n\t\tdoer = &http.Client{Timeout: time.Duration(timeout) * time.Second}\n\t\tif debug {\n\t\t\tdoer = goahttp.NewDebugDoer(doer)\n\t\t}\n\t}\n\n\treturn cli.ParseEndpoint(\n\t\tscheme,\n\t\thost,\n\t\tdoer,\n\t\tgoahttp.RequestEncoder,\n\t\tgoahttp.ResponseDecoder,\n\t\tdebug,\n\t)\n}"} {"input": "package dbtest\n\nimport (\n\t\"fmt\"\n\t\"github.com/muesli/cache2go\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar cachegoclient *cache2go.CacheTable\n\nfunc init() {\n\tcachegoclient = cache2go.Cache(\"mycache\")\n}\n\n\n\nfunc BenchmarkBGet(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tkey := fmt.Sprintf(\"key%v\", i)\n\t\tcachegoclient.Value(key)\n\t}\n}\n\nfunc BenchmarkBSet(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tkey := fmt.Sprintf(\"key%v\", i)\n\t\tvalue := fmt.Sprintf(\"value%v\", i)\n\t\tcachegoclient.Add(key, 5*time.Minute, value)\n\t}\n}"} {"input": "package pow\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/DanielKrawisz/bmutil\"\n)\n\n\ntype Data struct {\n\tNonceTrialsPerByte uint64\n\tExtraBytes uint64\n}\n\n\nfunc (pd *Data) Encode(w io.Writer) error {\n\tif err := bmutil.WriteVarInt(w, pd.NonceTrialsPerByte); err != nil {\n\t\treturn err\n\t}\n\n\tif err := bmutil.WriteVarInt(w, pd.ExtraBytes); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc (pd *Data) String() string {\n\treturn fmt.Sprintf(\"{%d, %d}\", pd.NonceTrialsPerByte, pd.ExtraBytes)\n}\n\nfunc (pd *Data) Decode(r io.Reader) (err error) ", "output": "{\n\tpd.NonceTrialsPerByte, err = bmutil.ReadVarInt(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpd.ExtraBytes, err = bmutil.ReadVarInt(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\n\t\"github.com/ethereum/go-ethereum/crypto\"\n\tcli \"gopkg.in/urfave/cli.v1\"\n)\n\n\n\nfunc udpSvr(ctx *cli.Context) error ", "output": "{\n\tlog.Println(\"udp svr...\")\n\tlog.Println(\"loacl:\", ctx.String(LocalFlag.Name))\n\tnodekey, err := crypto.GenerateKey()\n\tif err != nil {\n\t\tlog.Fatal(\"could not generate key:\", err)\n\t\treturn err\n\t}\n\tif err = crypto.SaveECDSA(\"./nodekey\", nodekey); err != nil {\n\t\tlog.Fatal(err)\n\t\treturn err\n\t}\n\tu, err := ListenUDP(nodekey, ctx.String(LocalFlag.Name))\n\tgo u.readLoop()\n\tfor {\n\t\tselect {\n\t\tcase buf := <-MsgChan:\n\t\t\tlog.Println(\"recv:\", buf)\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package utils\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"os\"\n\t\"strconv\"\n)\n\nvar path string\n\n\n\ntype Input struct {\n\t*bufio.Scanner\n}\n\n\nfunc GetInput() (*Input, error) {\n\tif len(path) > 0 {\n\t\tfile, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn &Input{}, err\n\t\t}\n\n\t\treturn &Input{bufio.NewScanner(file)}, nil\n\t}\n\treturn &Input{bufio.NewScanner(os.Stdin)}, nil\n}\n\nfunc (input *Input) ReadInt() int {\n\tinput.Split(bufio.ScanWords)\n\n\tif input.Scan() {\n\t\tresult, err := strconv.Atoi(input.Text())\n\t\tif err == nil {\n\t\t\treturn result\n\t\t}\n\t}\n\n\treturn 3\n}\n\nfunc (input *Input) ReadInts(size int) []int {\n\tinput.Split(bufio.ScanWords)\n\tints := make([]int, size)\n\n\tfor i := 0; i < size && input.Scan(); i++ {\n\t\tresult, err := strconv.Atoi(input.Text())\n\t\tif err == nil {\n\t\t\tints[i] = result\n\t\t}\n\t}\n\n\treturn ints\n}\n\nfunc (input *Input) ReadString() string {\n\tinput.Split(bufio.ScanWords)\n\n\tif input.Scan() {\n\t\treturn input.Text()\n\t}\n\n\treturn \"\"\n}\n\nfunc (input *Input) ReadStrings(size int) []string {\n\tinput.Split(bufio.ScanWords)\n\n\tstrings := make([]string, size)\n\n\tfor i := 0; i < size && input.Scan(); i++ {\n\t\tstrings[i] = input.Text()\n\t}\n\n\treturn strings\n}\n\nfunc init() ", "output": "{\n\tflag.StringVar(&path, \"path\", \"\", \"Path to the inputfile\")\n\tflag.Parse()\n}"} {"input": "package sctp\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\ntype paramHeader struct {\n\ttyp paramType\n\tlen int\n\traw []byte\n}\n\nconst (\n\tparamHeaderLength = 4\n)\n\nfunc (p *paramHeader) marshal() ([]byte, error) {\n\tparamLengthPlusHeader := paramHeaderLength + len(p.raw)\n\n\trawParam := make([]byte, paramLengthPlusHeader)\n\tbinary.BigEndian.PutUint16(rawParam[0:], uint16(p.typ))\n\tbinary.BigEndian.PutUint16(rawParam[2:], uint16(paramLengthPlusHeader))\n\tcopy(rawParam[paramHeaderLength:], p.raw)\n\n\treturn rawParam, nil\n}\n\n\n\nfunc (p *paramHeader) length() int {\n\treturn p.len\n}\n\n\nfunc (p paramHeader) String() string {\n\treturn fmt.Sprintf(\"%s (%d): %s\", p.typ, p.len, p.raw)\n}\n\nfunc (p *paramHeader) unmarshal(raw []byte) ", "output": "{\n\tparamLengthPlusHeader := binary.BigEndian.Uint16(raw[2:])\n\tparamLength := paramLengthPlusHeader - initOptionalVarHeaderLength\n\n\tp.typ = paramType(binary.BigEndian.Uint16(raw[0:]))\n\tp.raw = raw[paramHeaderLength : paramHeaderLength+paramLength]\n\tp.len = int(paramLengthPlusHeader)\n}"} {"input": "package v1\n\nimport (\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\trest \"k8s.io/client-go/rest\"\n\tv1 \"k8s.io/code-generator/_examples/crd/apis/example/v1\"\n\t\"k8s.io/code-generator/_examples/crd/clientset/versioned/scheme\"\n)\n\ntype ExampleV1Interface interface {\n\tRESTClient() rest.Interface\n\tTestTypesGetter\n}\n\n\ntype ExampleV1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *ExampleV1Client) TestTypes(namespace string) TestTypeInterface {\n\treturn newTestTypes(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*ExampleV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ExampleV1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *ExampleV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *ExampleV1Client {\n\treturn &ExampleV1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc (c *ExampleV1Client) RESTClient() rest.Interface ", "output": "{\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"os\"\n \"runtime\"\n \"strconv\"\n \"sync\"\n)\n\ntype Token int\n\ntype T struct {\n next *T\n label int\n value int\n mux sync.Mutex\n}\n\nfunc (w *T) put(v int) {\n w.value = v\n if v == 0 {\n res <- w.label\n } else {\n w.mux.Unlock()\n }\n}\n\n\n\nfunc (w *T) Start(label int, next *T) {\n w.label = label\n w.next = next\n w.mux.Lock()\n go w.run()\n}\n\nconst NThreads = 503\n\nvar res = make(chan int)\n\nfunc main() {\n n := 1000\n if len(os.Args) > 1 {\n n, _ = strconv.Atoi(os.Args[1])\n }\n\n var channels [NThreads]T\n for i := range channels {\n channels[i].Start(i+1, &channels[(i+1)%NThreads])\n }\n\n channels[0].put(n)\n fmt.Println(<-res)\n}\n\nfunc (w *T) run() ", "output": "{\n for {\n w.mux.Lock()\n w.next.put(w.value - 1)\n runtime.Gosched()\n }\n}"} {"input": "package manifestparser\n\nimport (\n\t\"errors\"\n\t\"io/ioutil\"\n\n\tyaml \"gopkg.in/yaml.v2\"\n)\n\ntype Application struct {\n\tName string `yaml:\"name\"`\n}\n\ntype Parser struct {\n\tPathToManifest string\n\n\tApplications []Application\n\n\trawManifest []byte\n}\n\nfunc NewParser() *Parser {\n\treturn new(Parser)\n}\n\nfunc (parser *Parser) Parse(manifestPath string) error {\n\tbytes, err := ioutil.ReadFile(manifestPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparser.rawManifest = bytes\n\n\tvar raw struct {\n\t\tApplications []Application `yaml:\"applications\"`\n\t}\n\n\terr = yaml.Unmarshal(bytes, &raw)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tparser.Applications = raw.Applications\n\n\tif len(parser.Applications) == 0 {\n\t\treturn errors.New(\"must have at least one application\")\n\t}\n\n\tfor _, application := range parser.Applications {\n\t\tif application.Name == \"\" {\n\t\t\treturn errors.New(\"Found an application with no name specified\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (parser Parser) AppNames() []string {\n\tvar names []string\n\tfor _, app := range parser.Applications {\n\t\tnames = append(names, app.Name)\n\t}\n\treturn names\n}\n\n\n\nfunc (parser Parser) RawManifest(_ string) ([]byte, error) ", "output": "{\n\treturn parser.rawManifest, nil\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"google.golang.org/api/drive/v3\"\n\n\t\"golang.org/x/net/context\"\n\t\"golang.org/x/oauth2\"\n\t\"golang.org/x/oauth2/google\"\n)\n\n\n\nfunc getClient(ctx context.Context, path string, user string) *http.Client ", "output": "{\n\n\tjwtFile, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tlog.Fatalf(\"Cannot fint JWT file: %v\", err)\n\t}\n\n\tconfig, err := google.JWTConfigFromJSON(jwtFile, drive.DriveScope)\n\tif err != nil {\n\t\tlog.Fatalf(\"Cannot parse JWT file: %v\", err)\n\t}\n\n\tconfig.Subject = user\n\n\tts := config.TokenSource(ctx)\n\n\treturn oauth2.NewClient(ctx, ts)\n}"} {"input": "package openstacktasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realFloatingIP FloatingIP\n\n\nfunc (o *FloatingIP) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realFloatingIP\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = FloatingIP(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &FloatingIP{}\n\n\nfunc (o *FloatingIP) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\n\nfunc (o *FloatingIP) SetLifecycle(lifecycle fi.Lifecycle) {\n\to.Lifecycle = &lifecycle\n}\n\nvar _ fi.HasName = &FloatingIP{}\n\n\nfunc (o *FloatingIP) GetName() *string {\n\treturn o.Name\n}\n\n\n\n\n\nfunc (o *FloatingIP) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *FloatingIP) SetName(name string) ", "output": "{\n\to.Name = &name\n}"} {"input": "package pathmgr\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\n\n\n\n\n\n\n\n\n\ntype SyncPaths struct {\n\tvalue atomic.Value\n\tmutex sync.Mutex\n}\n\n\n\ntype SyncPathsData struct {\n\tAPS AppPathSet\n\tModifyTime time.Time\n\tRefreshTime time.Time\n}\n\n\n\nfunc NewSyncPaths() *SyncPaths {\n\tsp := &SyncPaths{}\n\tnow := time.Now()\n\tsp.value.Store(\n\t\t&SyncPathsData{\n\t\t\tAPS: make(AppPathSet),\n\t\t\tModifyTime: now,\n\t\t\tRefreshTime: now,\n\t\t},\n\t)\n\treturn sp\n}\n\n\n\n\n\n\nfunc (sp *SyncPaths) update(newAPS AppPathSet) {\n\tsp.mutex.Lock()\n\tdefer sp.mutex.Unlock()\n\tvalue := sp.value.Load().(*SyncPathsData)\n\tvalue.RefreshTime = time.Now()\n\ttoAdd := setSubtract(newAPS, value.APS)\n\ttoRemove := setSubtract(value.APS, newAPS)\n\tif len(toAdd) > 0 || len(toRemove) > 0 {\n\t\tvalue.ModifyTime = value.RefreshTime\n\t}\n\tvalue.APS = newAPS\n\tsp.value.Store(value)\n}\n\n\n\n\nfunc setSubtract(x, y AppPathSet) AppPathSet {\n\tresult := make(AppPathSet)\n\tfor _, ap := range x {\n\t\tif _, ok := y[ap.Key()]; !ok {\n\t\t\tresult.Add(ap.Entry)\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (sp *SyncPaths) Load() *SyncPathsData ", "output": "{\n\treturn sp.value.Load().(*SyncPathsData)\n}"} {"input": "package graph\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gonum/graph\"\n\t\"github.com/gonum/graph/concrete\"\n\t\"github.com/gonum/graph/encoding/dot\"\n)\n\ntype Node struct {\n\tId int\n\tUniqueName string\n\tLabelName string\n\tColor string\n}\n\nfunc (n Node) ID() int {\n\treturn n.Id\n}\n\n\nfunc (n Node) DOTAttributes() []dot.Attribute {\n\tcolor := n.Color\n\tif len(color) == 0 {\n\t\tcolor = \"black\"\n\t}\n\n\treturn []dot.Attribute{\n\t\t{Key: \"label\", Value: fmt.Sprintf(\"%q\", n.LabelName)},\n\t\t{Key: \"color\", Value: color},\n\t}\n}\n\nfunc NewMutableDirectedGraph(g *concrete.DirectedGraph) *MutableDirectedGraph {\n\treturn &MutableDirectedGraph{\n\t\tDirectedGraph: concrete.NewDirectedGraph(),\n\t\tnodesByName: make(map[string]graph.Node),\n\t}\n}\n\ntype MutableDirectedGraph struct {\n\t*concrete.DirectedGraph\n\n\tnodesByName map[string]graph.Node\n}\n\nfunc (g *MutableDirectedGraph) AddNode(n *Node) error {\n\tif _, exists := g.nodesByName[n.UniqueName]; exists {\n\t\treturn fmt.Errorf(\"node .UniqueName collision: %s\", n.UniqueName)\n\t}\n\n\tg.nodesByName[n.UniqueName] = n\n\tg.DirectedGraph.AddNode(n)\n\treturn nil\n}\n\n\n\nfunc (g *MutableDirectedGraph) NodeByName(name string) (graph.Node, bool) ", "output": "{\n\tn, exists := g.nodesByName[name]\n\treturn n, exists && g.DirectedGraph.Has(n)\n}"} {"input": "package retry\n\nimport (\n\t\"errors\"\n\t\"testing\"\n)\n\n\nfunc errorGenerator(n int, retryable bool) func() error {\n\terrorCount := 0\n\treturn func() (err error) {\n\t\tif errorCount < n {\n\t\t\terrorCount++\n\t\t\te := errors.New(\"Error\")\n\t\t\tif retryable {\n\t\t\t\treturn &RetriableError{Err: e}\n\t\t\t}\n\t\t\treturn e\n\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\n\n\nfunc TestErrorGenerator(t *testing.T) ", "output": "{\n\terrors := 3\n\tf := errorGenerator(errors, false)\n\tfor i := 0; i < errors-1; i++ {\n\t\tif err := f(); err == nil {\n\t\t\tt.Fatalf(\"Error should have been thrown at iteration %v\", i)\n\t\t}\n\t}\n\tif err := f(); err == nil {\n\t\tt.Fatalf(\"Error should not have been thrown this call!\")\n\t}\n}"} {"input": "package dataintegration\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype DataflowApplication struct {\n\n\tApplicationId *string `mandatory:\"false\" json:\"applicationId\"`\n\n\tCompartmentId *string `mandatory:\"false\" json:\"compartmentId\"`\n}\n\n\n\nfunc (m DataflowApplication) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package events\n\nimport (\n\t\"github.com/mesos/mesos-go/executor\"\n)\n\ntype (\n\tDecorator func(Handler) Handler\n\n\tDecorators []Decorator\n)\n\nvar noopDecorator = Decorator(func(h Handler) Handler { return h })\n\n\n\nfunc (d Decorator) If(b bool) Decorator {\n\tif d == nil {\n\t\treturn noopDecorator\n\t}\n\tresult := noopDecorator\n\tif b {\n\t\tresult = d\n\t}\n\treturn result\n}\n\n\n\n\n\n\n\nfunc (ds Decorators) Apply(h Handler) Handler {\n\tfor _, d := range ds {\n\t\th = d.Apply(h)\n\t}\n\treturn h\n}\n\nfunc (d Decorator) Apply(h Handler) Handler {\n\tif d != nil {\n\t\th = d(h)\n\t}\n\treturn h\n}\n\nfunc (d Decorator) When(f func() bool) Decorator ", "output": "{\n\tif d == nil || f == nil {\n\t\treturn noopDecorator\n\t}\n\treturn func(h Handler) Handler {\n\t\tdecorated := d(h)\n\t\treturn HandlerFunc(func(e *executor.Event) (err error) {\n\t\t\tif f() {\n\t\t\t\terr = decorated.HandleEvent(e)\n\t\t\t} else {\n\t\t\t\terr = h.HandleEvent(e)\n\t\t\t}\n\t\t\treturn\n\t\t})\n\t}\n}"} {"input": "package callerid\n\nimport (\n\t\"testing\"\n\n\t\"github.com/youtube/vitess/go/vt/tabletserver/proto\"\n)\n\n\n\nfunc TestGoRPCCallerID(t *testing.T) ", "output": "{\n\tim := proto.VTGateCallerID{\n\t\tUsername: FakeUsername,\n\t}\n\tef := proto.CallerID{\n\t\tPrincipal: FakePrincipal,\n\t\tComponent: FakeComponent,\n\t\tSubcomponent: FakeSubcomponent,\n\t}\n\tif n := GoRPCImmediateCallerID(nil); n != nil {\n\t\tt.Errorf(\"Expect nil from GoRPCImmediateCallerID(nil), but got %v\", n)\n\t}\n\tif n := GoRPCEffectiveCallerID(nil); n != nil {\n\t\tt.Errorf(\"Expect nil from GoRPCEffectiveCallerID(nil), but got %v\", n)\n\t}\n\tTests(t, GoRPCImmediateCallerID(&im), GoRPCEffectiveCallerID(&ef))\n}"} {"input": "package nsqlookup\n\nimport \"bufio\"\n\ntype Ping struct {\n}\n\nfunc (c Ping) Name() string {\n\treturn \"PING\"\n}\n\n\n\nfunc readPing(args ...string) (cmd Ping, err error) {\n\treturn\n}\n\nfunc (c Ping) Write(w *bufio.Writer) (err error) ", "output": "{\n\t_, err = w.WriteString(\"PING\\n\")\n\treturn\n}"} {"input": "package credentials\n\nimport (\n\t\"strings\"\n\n\t\"github.com/docker/docker/cliconfig/configfile\"\n\t\"github.com/docker/engine-api/types\"\n)\n\n\n\ntype fileStore struct {\n\tfile *configfile.ConfigFile\n}\n\n\nfunc NewFileStore(file *configfile.ConfigFile) Store {\n\treturn &fileStore{\n\t\tfile: file,\n\t}\n}\n\n\nfunc (c *fileStore) Erase(serverAddress string) error {\n\tdelete(c.file.AuthConfigs, serverAddress)\n\treturn c.file.Save()\n}\n\n\nfunc (c *fileStore) Get(serverAddress string) (types.AuthConfig, error) {\n\tauthConfig, ok := c.file.AuthConfigs[serverAddress]\n\tif !ok {\n\t\tfor registry, ac := range c.file.AuthConfigs {\n\t\t\tif serverAddress == convertToHostname(registry) {\n\t\t\t\treturn ac, nil\n\t\t\t}\n\t\t}\n\n\t\tauthConfig = types.AuthConfig{}\n\t}\n\treturn authConfig, nil\n}\n\n\n\n\nfunc (c *fileStore) Store(authConfig types.AuthConfig) error {\n\tc.file.AuthConfigs[authConfig.ServerAddress] = authConfig\n\treturn c.file.Save()\n}\n\nfunc convertToHostname(url string) string {\n\tstripped := url\n\tif strings.HasPrefix(url, \"http://\") {\n\t\tstripped = strings.Replace(url, \"http://\", \"\", 1)\n\t} else if strings.HasPrefix(url, \"https://\") {\n\t\tstripped = strings.Replace(url, \"https://\", \"\", 1)\n\t}\n\n\tnameParts := strings.SplitN(stripped, \"/\", 2)\n\n\treturn nameParts[0]\n}\n\nfunc (c *fileStore) GetAll() (map[string]types.AuthConfig, error) ", "output": "{\n\treturn c.file.AuthConfigs, nil\n}"} {"input": "package sql\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/cockroachdb/cockroach/pkg/roachpb\"\n\t\"github.com/cockroachdb/cockroach/pkg/sql/parser\"\n\t\"github.com/cockroachdb/cockroach/pkg/sql/sqlbase\"\n)\n\n\n\n\ntype delayedNode struct {\n\tname string\n\tcolumns sqlbase.ResultColumns\n\tconstructor nodeConstructor\n\tplan planNode\n}\n\ntype nodeConstructor func(context.Context, *planner) (planNode, error)\n\nfunc (d *delayedNode) Close(ctx context.Context) {\n\tif d.plan != nil {\n\t\td.plan.Close(ctx)\n\t\td.plan = nil\n\t}\n}\n\nfunc (d *delayedNode) Columns() sqlbase.ResultColumns { return d.columns }\nfunc (d *delayedNode) Ordering() orderingInfo { return orderingInfo{} }\nfunc (d *delayedNode) MarkDebug(_ explainMode) {}\nfunc (d *delayedNode) Start(ctx context.Context) error { return d.plan.Start(ctx) }\nfunc (d *delayedNode) Next(ctx context.Context) (bool, error) { return d.plan.Next(ctx) }\nfunc (d *delayedNode) Values() parser.Datums { return d.plan.Values() }\nfunc (d *delayedNode) DebugValues() debugValues { return d.plan.DebugValues() }\n\n\nfunc (d *delayedNode) Spans(ctx context.Context) (_, _ roachpb.Spans, _ error) ", "output": "{\n\treturn d.plan.Spans(ctx)\n}"} {"input": "package textanalytics\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/cognitiveservices/v2.0/textanalytics\"\n\ntype BaseClient = original.BaseClient\ntype AzureRegions = original.AzureRegions\n\nconst (\n\tAustraliaeast AzureRegions = original.Australiaeast\n\tBrazilsouth AzureRegions = original.Brazilsouth\n\tEastasia AzureRegions = original.Eastasia\n\tEastus AzureRegions = original.Eastus\n\tEastus2 AzureRegions = original.Eastus2\n\tNortheurope AzureRegions = original.Northeurope\n\tSouthcentralus AzureRegions = original.Southcentralus\n\tSoutheastasia AzureRegions = original.Southeastasia\n\tWestcentralus AzureRegions = original.Westcentralus\n\tWesteurope AzureRegions = original.Westeurope\n\tWestus AzureRegions = original.Westus\n\tWestus2 AzureRegions = original.Westus2\n)\n\ntype BatchInput = original.BatchInput\ntype DetectedLanguage = original.DetectedLanguage\ntype ErrorRecord = original.ErrorRecord\ntype ErrorResponse = original.ErrorResponse\ntype Input = original.Input\ntype InternalError = original.InternalError\ntype KeyPhraseBatchResult = original.KeyPhraseBatchResult\ntype KeyPhraseBatchResultItem = original.KeyPhraseBatchResultItem\ntype LanguageBatchResult = original.LanguageBatchResult\ntype LanguageBatchResultItem = original.LanguageBatchResultItem\ntype MultiLanguageBatchInput = original.MultiLanguageBatchInput\ntype MultiLanguageInput = original.MultiLanguageInput\ntype SentimentBatchResult = original.SentimentBatchResult\ntype SentimentBatchResultItem = original.SentimentBatchResultItem\n\nfunc New(azureRegion AzureRegions) BaseClient {\n\treturn original.New(azureRegion)\n}\nfunc NewWithoutDefaults(azureRegion AzureRegions) BaseClient {\n\treturn original.NewWithoutDefaults(azureRegion)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/latest\"\n}\n\n\nfunc Version() string ", "output": "{\n\treturn original.Version()\n}"} {"input": "package fsettings\n\nimport \"encoding/json\"\n\n\ntype MapGenSettings struct {\n\tTerrainSegmentation string `json:\"terrain_segmentation\"`\n\tWater string `json:\"water\"`\n\tWidth uint `json:\"width\"`\n\tHeight uint `json:\"height\"`\n\tStartingArea string `json:\"starting_area\"`\n\tPeacefulMode bool `json:\"peaceful_mode\"`\n\tAutoplaceControls AutoplaceControls `json:\"autoplace_controls\"`\n}\n\nfunc (fs MapGenSettings) String() string {\n\tj, _ := json.MarshalIndent(fs, \"\", \" \")\n\treturn string(j)\n}\n\ntype AutoplaceControls struct {\n\tCoal PlacementControl `json:\"coal\"`\n\tCopperOre PlacementControl `json:\"copper-ore\"`\n\tCrudeOil PlacementControl `json:\"crude-oil\"`\n\tEnemyBase PlacementControl `json:\"enemy-base\"`\n\tIronOre PlacementControl `json:\"iron-ore\"`\n\tStone PlacementControl `json:\"stone\"`\n}\n\ntype PlacementControl struct {\n\tFrequency string `json:\"frequency\"`\n\tSize string `json:\"size\"`\n\tRichness string `json:\"richness\"`\n}\n\n\n\n\n\nfunc NewMapGenSettings() MapGenSettings ", "output": "{\n\tnormalLevels := PlacementControl{Frequency: \"normal\", Size: \"normal\", Richness: \"normal\"}\n\treturn MapGenSettings{\n\t\tTerrainSegmentation: \"normal\",\n\t\tWater: \"normal\",\n\t\tWidth: uint(0),\n\t\tHeight: uint(0),\n\t\tStartingArea: \"normal\",\n\t\tPeacefulMode: false,\n\t\tAutoplaceControls: AutoplaceControls{\n\t\t\tCoal: normalLevels,\n\t\t\tCopperOre: normalLevels,\n\t\t\tCrudeOil: normalLevels,\n\t\t\tEnemyBase: normalLevels,\n\t\t\tIronOre: normalLevels,\n\t\t\tStone: normalLevels,\n\t\t},\n\t}\n}"} {"input": "package protobuf\n\nimport (\n\t\"encoding/binary\"\n\n\tc \"github.com/couchbase/indexing/secondary/common\"\n)\n\n\n\nfunc (kv *KeyVersions) Snapshot() (typ uint32, start, end uint64) {\n\tuuids := kv.GetUuids()\n\tkeys := kv.GetKeys()\n\toldkeys := kv.GetOldkeys()\n\tfor i, cmd := range kv.GetCommands() {\n\t\tif byte(cmd) == c.Snapshot {\n\t\t\ttyp = uint32(uuids[i])\n\t\t\tstart = binary.BigEndian.Uint64(keys[i])\n\t\t\tend = binary.BigEndian.Uint64(oldkeys[i])\n\t\t}\n\t}\n\treturn\n}\n\nfunc (pl *Payload) Value() interface{} ", "output": "{\n\tif pl.Vbmap != nil {\n\t\treturn pl.Vbmap\n\t} else if pl.Vbkeys != nil {\n\t\treturn pl.Vbkeys\n\t}\n\treturn nil\n}"} {"input": "package plus\n\n\n\ntype btree struct {\n\troot node\n\tnodeSize, number uint64\n}\n\nfunc (tree *btree) insert(key Key) {\n\tif tree.root == nil {\n\t\tn := newLeafNode(tree.nodeSize)\n\t\tn.insert(tree, key)\n\t\ttree.number = 1\n\t\treturn\n\t}\n\n\tresult := tree.root.insert(tree, key)\n\tif result {\n\t\ttree.number++\n\t}\n\n\tif tree.root.needsSplit(tree.nodeSize) {\n\t\ttree.root = split(tree, nil, tree.root)\n\t}\n}\n\n\n\n\nfunc (tree *btree) Insert(keys ...Key) {\n\tfor _, key := range keys {\n\t\ttree.insert(key)\n\t}\n}\n\n\n\nfunc (tree *btree) Iter(key Key) Iterator {\n\tif tree.root == nil {\n\t\treturn nilIterator()\n\t}\n\n\treturn tree.root.find(key)\n}\n\nfunc (tree *btree) get(key Key) Key {\n\titer := tree.root.find(key)\n\tif !iter.Next() {\n\t\treturn nil\n\t}\n\n\tif iter.Value().Compare(key) == 0 {\n\t\treturn iter.Value()\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc (tree *btree) Get(keys ...Key) Keys {\n\tresults := make(Keys, 0, len(keys))\n\tfor _, k := range keys {\n\t\tresults = append(results, tree.get(k))\n\t}\n\n\treturn results\n}\n\n\nfunc (tree *btree) Len() uint64 {\n\treturn tree.number\n}\n\nfunc newBTree(nodeSize uint64) *btree {\n\treturn &btree{\n\t\tnodeSize: nodeSize,\n\t\troot: newLeafNode(nodeSize),\n\t}\n}\n\nfunc keySearch(keys keys, key Key) int ", "output": "{\n\tlow, high := 0, len(keys)-1\n\tvar mid int\n\tfor low <= high {\n\t\tmid = (high + low) / 2\n\t\tswitch keys[mid].Compare(key) {\n\t\tcase 1:\n\t\t\tlow = mid + 1\n\t\tcase -1:\n\t\t\thigh = mid - 1\n\t\tcase 0:\n\t\t\treturn mid\n\t\t}\n\t}\n\treturn low\n}"} {"input": "package crate_test\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t_ \"github.com/herenow/go-crate\"\n\t\"log\"\n)\n\nfunc ExampleCrateDrive_Open() {\n\t_, err := sql.Open(\"crate\", \"http://localhost:4200\")\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\n\nfunc ExampleCrateDriver_Query() ", "output": "{\n\tdb, err := sql.Open(\"crate\", \"http://localhost:4200\")\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trows, err := db.Query(\"SELECT name FROM sys.cluster\")\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar name string\n\n\t\tif err := rows.Scan(&name); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", name)\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"input": "package jwt_test\n\nimport (\n\t\"log\"\n\t\"testing\"\n\n\t\"github.com/nilslice/jwt\"\n)\n\n\n\nfunc TestGrantFails(t *testing.T) {\n\tclaims := map[string]interface{}{\n\t\t\"testID\": 2,\n\t\t\"name\": \"GrantFails\",\n\t}\n\n\tgrant, err := jwt.New(claims)\n\tif err != nil {\n\t\tt.Log(claims, grant, err)\n\t\tt.Fail()\n\t}\n\n\tjwt.Secret([]byte(\"NotPreviousSecret\"))\n\n\tif jwt.Passes(grant) {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestGetClaims(t *testing.T) {\n\temail := \"hello@nilslice.xyz\"\n\tauthLevel := float64(7)\n\n\tclaims := map[string]interface{}{\n\t\t\"email\": email,\n\t\t\"auth_level\": authLevel,\n\t}\n\n\ttoken, err := jwt.New(claims)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tt.Fail()\n\t}\n\n\tclaims = jwt.GetClaims(token)\n\tif claims[\"email\"].(string) != email ||\n\t\tclaims[\"auth_level\"].(float64) != authLevel {\n\t\tt.Fail()\n\t}\n\n}\n\nfunc TestGrantPasses(t *testing.T) ", "output": "{\n\tclaims := map[string]interface{}{\n\t\t\"testID\": 1,\n\t\t\"name\": \"GrantPasses\",\n\t}\n\n\tgrant, err := jwt.New(claims)\n\tif err != nil {\n\t\tt.Log(claims, grant, err)\n\t\tt.Fail()\n\t}\n\n\tif !jwt.Passes(grant) {\n\t\tt.Fail()\n\t}\n}"} {"input": "package main\n\nimport \"log\"\n\n\n\nfunc work() {\n\n\tvar i int\n\tvar x int\n\n\tfor i = 1; i <= 10; i++ {\n\t\tx = square(i)\n\t\tlog.Printf(\n\t\t\t\"i=%v x=%v\",\n\t\t\ti,\n\t\t\tx,\n\t\t)\n\t}\n}\n\n\n\nfunc square(\n\tx int,\n) int ", "output": "{\n\n\treturn x * x\n}"} {"input": "package race_test\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestNoRaceIOHttp(t *testing.T) {\n\tx := 0\n\tgo func() {\n\t\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\t\tx = 41\n\t\t\tfmt.Fprintf(w, \"test\")\n\t\t\tx = 42\n\t\t})\n\t\terr := http.ListenAndServe(\"127.0.0.1:23651\", nil)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"http.ListenAndServe: %v\", err)\n\t\t}\n\t}()\n\ttime.Sleep(1e7)\n\tx = 1\n\t_, err := http.Get(\"http://127.0.0.1:23651\")\n\tif err != nil {\n\t\tt.Fatalf(\"http.Get: %v\", err)\n\t}\n\tx = 2\n\t_, err = http.Get(\"http://127.0.0.1:23651\")\n\tif err != nil {\n\t\tt.Fatalf(\"http.Get: %v\", err)\n\t}\n\tx = 3\n}\n\nfunc TestNoRaceIOFile(t *testing.T) ", "output": "{\n\tx := 0\n\tpath, _ := ioutil.TempDir(\"\", \"race_test\")\n\tfname := filepath.Join(path, \"data\")\n\tgo func() {\n\t\tx = 42\n\t\tf, _ := os.Create(fname)\n\t\tf.Write([]byte(\"done\"))\n\t\tf.Close()\n\t}()\n\tfor {\n\t\tf, err := os.Open(fname)\n\t\tif err != nil {\n\t\t\ttime.Sleep(1e6)\n\t\t\tcontinue\n\t\t}\n\t\tbuf := make([]byte, 100)\n\t\tcount, err := f.Read(buf)\n\t\tif count == 0 {\n\t\t\ttime.Sleep(1e6)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\t_ = x\n}"} {"input": "package gomposer\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nfunc Test_Remove_Deletes_Folder(t *testing.T) {\n\tvendorDir := os.TempDir() + \"/vendors\"\n\tdirName := vendorDir + \"/symfony/symfony\"\n\tos.MkdirAll(dirName, 0744)\n\tv := ComposerPackage{\n\t\tName: \"symfony/symfony\",\n\t}\n\tRemove(vendorDir, v)\n\n\tif _, err := os.Stat(dirName); !os.IsNotExist(err) {\n\t\tt.Errorf(\"Failed to delete %v\", dirName)\n\t}\n}\n\n\n\nfunc Test_Remove_Keeps_Parent_Folder_When_Not_Empty(t *testing.T) {\n\tvendorDir := os.TempDir() + \"/vendors\"\n\tdirName := vendorDir + \"/symfony\"\n\tos.MkdirAll(dirName+\"/symfony\", 0744)\n\tfp, err := os.Create(dirName + \"/remove_deletes_parent_folder\")\n\n\tif err != nil {\n\t\tt.Errorf(\"%v\", err)\n\t}\n\n\tfp.Write([]byte(\"hello world\"))\n\tv := ComposerPackage{\n\t\tName: \"symfony/symfony\",\n\t}\n\tRemove(vendorDir, v)\n\n\tif _, err := os.Stat(dirName); os.IsNotExist(err) {\n\t\tt.Errorf(\"Failed to keep %v when not empty\", dirName)\n\t}\n\tos.Remove(dirName + \"/remove_deletes_parent_folder\")\n}\n\nfunc Test_Remove_Deletes_Parent_Folder(t *testing.T) ", "output": "{\n\tvendorDir := os.TempDir() + \"/vendors\"\n\tdirName := vendorDir + \"/symfony\"\n\tos.MkdirAll(dirName+\"/symfony\", 0744)\n\tv := ComposerPackage{\n\t\tName: \"symfony/symfony\",\n\t}\n\tRemove(vendorDir, v)\n\n\tif _, err := os.Stat(dirName); !os.IsNotExist(err) {\n\t\tt.Errorf(\"Failed to delete %v\", dirName)\n\t}\n}"} {"input": "package testing\n\nimport \"k8s.io/kubernetes/pkg/util/iptables\"\n\n\ntype fake struct{}\n\nfunc NewFake() *fake {\n\treturn &fake{}\n}\n\nfunc (*fake) EnsureChain(table iptables.Table, chain iptables.Chain) (bool, error) {\n\treturn true, nil\n}\n\nfunc (*fake) FlushChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) DeleteChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) EnsureRule(position iptables.RulePosition, table iptables.Table, chain iptables.Chain, args ...string) (bool, error) {\n\treturn true, nil\n}\n\nfunc (*fake) DeleteRule(table iptables.Table, chain iptables.Chain, args ...string) error {\n\treturn nil\n}\n\nfunc (*fake) IsIpv6() bool {\n\treturn false\n}\n\nfunc (*fake) Save(table iptables.Table) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\nfunc (*fake) SaveAll() ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\n\n\nfunc (*fake) RestoreAll(data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\nfunc (*fake) AddReloadFunc(reloadFunc func()) {}\n\nfunc (*fake) Destroy() {}\n\nvar _ = iptables.Interface(&fake{})\n\nfunc (*fake) Restore(table iptables.Table, data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error ", "output": "{\n\treturn nil\n}"} {"input": "package uri\n\nimport (\n\t\"testing\"\n\n\t\"github.com/telehash/gogotelehash/Godeps/_workspace/src/github.com/stretchr/testify/assert\"\n\n\t_ \"github.com/telehash/gogotelehash/e3x\"\n)\n\n\n\nfunc Test_resolveDNS(t *testing.T) ", "output": "{\n\n\tassert := assert.New(t)\n\n\turi, err := Parse(\"01.test.simonmenke.me\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tident, err := resolveSRV(uri, \"udp\")\n\tif assert.NoError(err) && assert.NotNil(ident) {\n\t\tt.Logf(\"ident=%v addrs=%v keys=%v\", ident, ident.Addresses(), ident.Keys())\n\t}\n}"} {"input": "package reaperlog\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/rifflock/lfshook\"\n\t\"go.mozilla.org/mozlogrus\"\n)\n\nvar config LogConfig\n\ntype LogConfig struct {\n\tExtras bool\n}\n\nfunc EnableExtras() {\n\tconfig.Extras = true\n}\n\nfunc EnableMozlog() {\n\tmozlogrus.Enable(\"Reaper\")\n}\n\n\n\nfunc SetConfig(c *LogConfig) {\n\tconfig = *c\n}\n\nfunc AddLogFile(filename string) {\n\tlog.AddHook(lfshook.NewHook(lfshook.PathMap{\n\t\tlog.DebugLevel: filename,\n\t\tlog.InfoLevel: filename,\n\t\tlog.WarnLevel: filename,\n\t\tlog.ErrorLevel: filename,\n\t\tlog.FatalLevel: filename,\n\t\tlog.PanicLevel: filename,\n\t}))\n}\n\nfunc Debug(format string, args ...interface{}) {\n\tlog.Debugf(format, args...)\n}\n\nfunc Info(format string, args ...interface{}) {\n\tlog.Infof(format, args...)\n}\n\nfunc Warning(format string, args ...interface{}) {\n\tlog.Warningf(format, args...)\n}\n\nfunc Fatal(format string, args ...interface{}) {\n\tlog.Fatalf(format, args...)\n}\n\nfunc Panic(format string, args ...interface{}) {\n\tlog.Panicf(format, args...)\n}\n\nfunc Error(format string, args ...interface{}) {\n\tlog.Errorf(format, args...)\n}\n\nfunc Extras() bool ", "output": "{\n\treturn config.Extras\n}"} {"input": "package suggest\n\nimport (\n\t\"github.com/google/btree\"\n\t\"sync\"\n)\n\n\ntype Suggester interface {\n\tSuggest(max int, q string) (result []string)\n}\n\n\ntype Adder interface {\n\tAdd(s string)\n}\n\n\n\ntype Engine struct {\n\tincomingCh chan string\n\tawaitCh chan bool\n\tlock sync.RWMutex\n\tsuggestions *btree.BTree\n}\n\n\nfunc NewEngine() *Engine {\n\treturn newEngine()\n}\n\n\n\n\n\n\nfunc (e *Engine) Add(s string) {\n\te.add(s)\n}\n\n\nfunc (e *Engine) Await() {\n\te.await()\n}\n\n\nfunc (e *Engine) Suggest(max int, q string) (result []string) {\n\treturn e.suggest(max, q)\n}\n\n\n\n\n\nfunc NewSuggester(suggestions ...string) Suggester ", "output": "{\n\treturn newSuggester(suggestions)\n}"} {"input": "package migrations\n\nimport (\n\t\"fmt\"\n\n\t\"code.gitea.io/gitea/modules/log\"\n\t\"code.gitea.io/gitea/modules/setting\"\n\n\t\"xorm.io/xorm\"\n)\n\n\n\nfunc removeActionColumns(x *xorm.Engine) error ", "output": "{\n\tswitch {\n\tcase setting.Database.UseSQLite3:\n\t\tlog.Warn(\"Unable to drop columns in SQLite\")\n\tcase setting.Database.UseMySQL, setting.Database.UsePostgreSQL, setting.Database.UseMSSQL:\n\t\tif _, err := x.Exec(\"ALTER TABLE action DROP COLUMN act_user_name\"); err != nil {\n\t\t\treturn fmt.Errorf(\"DROP COLUMN act_user_name: %v\", err)\n\t\t} else if _, err = x.Exec(\"ALTER TABLE action DROP COLUMN repo_user_name\"); err != nil {\n\t\t\treturn fmt.Errorf(\"DROP COLUMN repo_user_name: %v\", err)\n\t\t} else if _, err = x.Exec(\"ALTER TABLE action DROP COLUMN repo_name\"); err != nil {\n\t\t\treturn fmt.Errorf(\"DROP COLUMN repo_name: %v\", err)\n\t\t}\n\tdefault:\n\t\tlog.Fatal(\"Unrecognized DB\")\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/golang/example/stringutil\"\n)\n\n\n\n\nfunc Handler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tmsg := stringutil.Reverse(stringutil.Reverse(\"Vendor Example Test\"))\n\tw.Write([]byte(msg))\n}"} {"input": "package version\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"go-common/app/interface/main/creative/conf\"\n\t\"go-common/app/interface/main/creative/model/version\"\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"go-common/app/interface/main/creative/service\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nvar (\n\ts *Service\n)\n\nfunc init() {\n\tdir, _ := filepath.Abs(\"../../cmd/creative.toml\")\n\tflag.Set(\"conf\", dir)\n\tconf.Init()\n\trpcdaos := service.NewRPCDaos(conf.Conf)\n\ts = New(conf.Conf, rpcdaos)\n\ttime.Sleep(time.Second)\n}\n\nfunc WithService(f func(s *Service)) func() {\n\treturn func() {\n\t\tReset(func() {})\n\t\tf(s)\n\t}\n}\n\n\n\nfunc Test_VersionMap(t *testing.T) ", "output": "{\n\tvar (\n\t\tc = context.Background()\n\t\terr error\n\t\tversions = make(map[string][]*version.Version)\n\t)\n\tConvey(\"versionMap\", t, WithService(func(s *Service) {\n\t\tversions, err = s.versionMap(c)\n\t\tSo(err, ShouldBeNil)\n\t\tSo(versions, ShouldNotBeNil)\n\t}))\n}"} {"input": "package cluster\n\nimport (\n\t\"github.com/hashicorp/nomad/api\"\n\t\"github.com/jippi/hashi-ui/backend/structs\"\n)\n\nconst (\n\tReconsileSummaries = \"NOMAD_RECONCILE_SYSTEM\"\n)\n\ntype reconsileSummaries struct {\n\taction structs.Action\n\tclient *api.Client\n}\n\nfunc NewReconsileSummaries(action structs.Action, client *api.Client) *reconsileSummaries {\n\treturn &reconsileSummaries{\n\t\taction: action,\n\t\tclient: client,\n\t}\n}\n\nfunc (w *reconsileSummaries) Do() (structs.Response, error) {\n\terr := w.client.System().ReconcileSummaries()\n\tif err != nil {\n\t\treturn structs.NewErrorResponse(err)\n\t}\n\n\treturn structs.NewSuccessResponse(\"Successfully reconsiled summaries\")\n}\n\nfunc (w *reconsileSummaries) Key() string {\n\treturn \"/system/reconsile_summaries\"\n}\n\nfunc (w *reconsileSummaries) IsMutable() bool {\n\treturn true\n}\n\n\n\nfunc (w *reconsileSummaries) BackendType() string ", "output": "{\n\treturn \"nomad\"\n}"} {"input": "package throttler\n\nimport (\n\t\"vitess.io/vitess/go/sync2\"\n)\n\n\n\ntype MaxRateModule struct {\n\tmaxRate sync2.AtomicInt64\n\trateUpdateChan chan<- struct{}\n}\n\n\n\n\n\n\nfunc (m *MaxRateModule) Start(rateUpdateChan chan<- struct{}) {\n\tm.rateUpdateChan = rateUpdateChan\n}\n\n\nfunc (m *MaxRateModule) Stop() {}\n\n\nfunc (m *MaxRateModule) MaxRate() int64 {\n\treturn m.maxRate.Get()\n}\n\n\n\nfunc (m *MaxRateModule) SetMaxRate(rate int64) {\n\tm.maxRate.Set(rate)\n\tm.rateUpdateChan <- struct{}{}\n}\n\nfunc NewMaxRateModule(maxRate int64) *MaxRateModule ", "output": "{\n\treturn &MaxRateModule{\n\t\tmaxRate: sync2.NewAtomicInt64(maxRate),\n\t}\n}"} {"input": "package playground \n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst baseURL = \"https://play.golang.org\"\n\nfunc init() {\n\thttp.HandleFunc(\"/compile\", bounce)\n\thttp.HandleFunc(\"/share\", bounce)\n}\n\n\n\nfunc passThru(w io.Writer, req *http.Request) error {\n\tif req.URL.Path == \"/share\" && !allowShare(req) {\n\t\treturn errors.New(\"Forbidden\")\n\t}\n\tdefer req.Body.Close()\n\turl := baseURL + req.URL.Path\n\tctx, cancel := context.WithTimeout(contextFunc(req), 60*time.Second)\n\tdefer cancel()\n\tr, err := post(ctx, url, req.Header.Get(\"Content-type\"), req.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"making POST request: %v\", err)\n\t}\n\tdefer r.Body.Close()\n\tif _, err := io.Copy(w, r.Body); err != nil {\n\t\treturn fmt.Errorf(\"copying response Body: %v\", err)\n\t}\n\treturn nil\n}\n\nvar onAppengine = false \n\nfunc allowShare(r *http.Request) bool {\n\tif !onAppengine {\n\t\treturn true\n\t}\n\tswitch r.Header.Get(\"X-AppEngine-Country\") {\n\tcase \"\", \"ZZ\", \"CN\":\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc bounce(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tb := new(bytes.Buffer)\n\tif err := passThru(b, r); err != nil {\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treport(r, err)\n\t\treturn\n\t}\n\tio.Copy(w, b)\n}"} {"input": "package main\n\nimport (\n\t\"code.google.com/p/go.net/websocket\"\n\t\"log\"\n \"strconv\"\n)\n\nconst bufferSize = 100\n\nvar maxId uint64 = 0\n\ntype Client struct {\n\tid uint64\n\tws *websocket.Conn\n\trace *Race\n\tch chan *Message\n}\n\nfunc NewClient(ws *websocket.Conn, race *Race) *Client {\n\tmaxId++\n\tch := make(chan *Message, bufferSize)\n\treturn &Client{maxId, ws, race, ch}\n}\n\nfunc (c *Client) Conn() *websocket.Conn {\n\treturn c.ws\n}\n\n\n\nfunc (c *Client) Listen() {\n\tgo c.listenWrite()\n\tc.listenRead()\n}\n\nfunc (c *Client) listenWrite() {\n\tfor {\n\t\tselect {\n\t\tcase msg := <-c.ch:\n\t\t\twebsocket.JSON.Send(c.ws, msg)\n\t\t\tlog.Println(\"Sending to\", c.id, \":\", msg)\n\t\t}\n\t}\n}\n\nfunc (c *Client) listenRead() {\n\tfor {\n\t\tselect {\n\t\tdefault:\n\t\t\tvar msg Message\n\t\t\tif err := websocket.JSON.Receive(c.ws, &msg);err!=nil{\n if err.Error()==\"EOF\"{\n c.race.Del(c)\n return\n }\n log.Println(\"Unhandled error:\",err)\n return\n }\n\t\t\tlog.Println(c.id, \"got:\", msg)\n\n if msg.Type==\"word\"{\n i,err:=strconv.Atoi(msg.Body)\n if err!=nil{\n log.Println(err)\n continue\n }\n if i>c.race.best{\n c.race.best=i\n c.race.sendAll(&Message{\"best\",msg.Body,c.id})\n }\n }\n\t\t}\n\t}\n}\n\nfunc (c *Client) Write(msg *Message) ", "output": "{\n\tselect {\n\tcase c.ch <- msg:\n\tdefault:\n\t\tc.race.Del(c)\n\t\tlog.Println(\"Client\", c.id, \"disconnected\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-on/wrap\"\n\t\"github.com/go-on/wrap-contrib/wraps\"\n\n\t\"github.com/go-on/router\"\n)\n\n\n\nfunc main() {\n\trt := router.New()\n\n\trt.GET(\"/\", wraps.String(\"root\"))\n\trt.GETFunc(\"/missing\", missing)\n\trt.GET(\"/hu\", wraps.String(\"hu\"))\n\n\trt.Mount(\"/\", nil)\n\n\twrapper := wrap.New(\n\t\twraps.Fallback(\n\t\t\t[]int{405}, \n\t\t\trt,\n\t\t\twraps.String(\"fallback\"),\n\t\t),\n\t)\n\n\terr := http.ListenAndServe(\":8087\", wrapper)\n\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n}\n\nfunc missing(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\trw.WriteHeader(404)\n\trw.Write([]byte(\"not found\"))\n}"} {"input": "package kubernetes\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/api/apps/v1beta1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\n\t\"github.com/weaveworks/scope/report\"\n)\n\n\ntype StatefulSet interface {\n\tMeta\n\tSelector() (labels.Selector, error)\n\tGetNode(probeID string) report.Node\n}\n\ntype statefulSet struct {\n\t*v1beta1.StatefulSet\n\tMeta\n}\n\n\nfunc NewStatefulSet(s *v1beta1.StatefulSet) StatefulSet {\n\treturn &statefulSet{\n\t\tStatefulSet: s,\n\t\tMeta: meta{s.ObjectMeta},\n\t}\n}\n\nfunc (s *statefulSet) Selector() (labels.Selector, error) {\n\tselector, err := metav1.LabelSelectorAsSelector(s.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn selector, nil\n}\n\n\n\nfunc (s *statefulSet) GetNode(probeID string) report.Node ", "output": "{\n\tdesiredReplicas := 1\n\tif s.Spec.Replicas != nil {\n\t\tdesiredReplicas = int(*s.Spec.Replicas)\n\t}\n\tlatests := map[string]string{\n\t\tNodeType: \"StatefulSet\",\n\t\tDesiredReplicas: fmt.Sprint(desiredReplicas),\n\t\tReplicas: fmt.Sprint(s.Status.Replicas),\n\t\treport.ControlProbeID: probeID,\n\t}\n\tif s.Status.ObservedGeneration != nil {\n\t\tlatests[ObservedGeneration] = fmt.Sprint(*s.Status.ObservedGeneration)\n\t}\n\treturn s.MetaNode(report.MakeStatefulSetNodeID(s.UID())).WithLatests(latests)\n}"} {"input": "package readline\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\n\nfunc goCompletionEntryFunction(text *C.char, state C.int) *C.char {\n\tmatch := completionEntryFunction(C.GoString(text), int(state))\n\tif match == \"\" {\n\t\treturn nil\n\t}\n\treturn C.CString(match) \n}\n\n\n\n\n\n\n\n\n\n\n\ntype CompletionEntryFunction func(text string, state int) string\n\nvar completionEntryFunction CompletionEntryFunction\n\n\n\nfunc SetCompletionEntryFunction(f CompletionEntryFunction) {\n\tif f == nil {\n\t\tif completionEntryFunction != nil {\n\t\t\tC.rl_attempted_completion_function = nil\n\t\t}\n\t} else if completionEntryFunction == nil {\n\t\tC.register_attempted_completion_function()\n\t}\n\tcompletionEntryFunction = f\n}\n\n\n\n\n\n\n\n\n\nfunc SetCompleterWordBreakChars(s string) {\n\tcs := C.CString(s)\n\tC.free(unsafe.Pointer(C.rl_completer_word_break_characters))\n\tC.rl_completer_word_break_characters = cs\n}\n\n\n\n\nfunc CompleterWordBreakChars() string {\n\treturn C.GoString(C.rl_completer_word_break_characters)\n}\n\nfunc SetAttemptedCompletionOver(b bool) ", "output": "{\n\tif b {\n\t\tC.rl_attempted_completion_over = 1\n\t} else {\n\t\tC.rl_attempted_completion_over = 0\n\t}\n}"} {"input": "package plugins\n\nimport (\n\t\"errors\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nfunc init() {\n\tplugins = make(map[string]Plugin)\n}\n\ntype backupFunc func()\ntype restoreFunc func()\ntype commandOb *cobra.Command\n\n\ntype Plugin struct {\n\tName string\n\tRestore restoreFunc\n\tBackup backupFunc\n\tCommand commandOb\n}\n\nvar plugins map[string]Plugin\n\n\nfunc Register(name string, restore restoreFunc, backup backupFunc, command commandOb) {\n\tplugins[name] = Plugin{name, restore, backup, command}\n}\n\n\n\n\n\nfunc GetAll() map[string]Plugin {\n\treturn plugins\n}\n\nfunc Get(name string) (Plugin, error) ", "output": "{\n\tp, ok := plugins[name]\n\tif !ok {\n\t\treturn Plugin{}, errors.New(\"no plugin found\")\n\t}\n\treturn p, nil\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/api/events/v1beta1\"\n\t\"k8s.io/client-go/deprecated/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype EventsV1beta1Interface interface {\n\tRESTClient() rest.Interface\n\tEventsGetter\n}\n\n\ntype EventsV1beta1Client struct {\n\trestClient rest.Interface\n}\n\n\n\n\nfunc NewForConfig(c *rest.Config) (*EventsV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &EventsV1beta1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *EventsV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *EventsV1beta1Client {\n\treturn &EventsV1beta1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *EventsV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc (c *EventsV1beta1Client) Events(namespace string) EventInterface ", "output": "{\n\treturn newEvents(c, namespace)\n}"} {"input": "package authorization\n\nimport \"k8s.io/apimachinery/pkg/fields\"\n\n\n\n\n\nfunc PolicyBindingToSelectableFields(policyBinding *PolicyBinding) fields.Set ", "output": "{\n\treturn fields.Set{\n\t\t\"metadata.name\": policyBinding.Name,\n\t\t\"metadata.namespace\": policyBinding.Namespace,\n\t\t\"policyRef.namespace\": policyBinding.PolicyRef.Namespace,\n\t}\n}"} {"input": "package future\n\nimport (\n\t\"time\"\n)\n\n\nconst FuelRechargeRate = float32(1.0 / 3.0) \n\n\nfunc Fuel(initial float32, elap time.Duration) float32 {\n\tfuel := initial + FuelRechargeRate*float32(elap)/float32(time.Second)\n\tif fuel > 10 {\n\t\tfuel = 10\n\t}\n\treturn fuel\n}\n\n\nfunc CannonX(initial float32, rate float32, elap time.Duration) (float32, float32) {\n\tx := initial + rate*float32(elap)/float32(time.Second)\n\tswitch {\n\tcase x < 0:\n\t\tx = -x\n\t\trate = -rate\n\tcase x > 1:\n\t\tx = 2 - x\n\t\trate = -rate\n\t}\n\treturn x, rate\n}\n\n\n\n\nfunc MissileY(initial float32, rate float32, elap time.Duration) float32 ", "output": "{\n\ty := initial + rate*float32(elap)/float32(time.Second)\n\tif y > 1 {\n\t\ty = 1\n\t}\n\treturn y\n}"} {"input": "package iso20022\n\n\ntype RateAndAmountFormat42Choice struct {\n\n\tAmount *ActiveCurrencyAnd13DecimalAmount `xml:\"Amt\"`\n\n\tNotSpecifiedRate *RateValueType7Code `xml:\"NotSpcfdRate\"`\n}\n\nfunc (r *RateAndAmountFormat42Choice) SetAmount(value, currency string) {\n\tr.Amount = NewActiveCurrencyAnd13DecimalAmount(value, currency)\n}\n\n\n\nfunc (r *RateAndAmountFormat42Choice) SetNotSpecifiedRate(value string) ", "output": "{\n\tr.NotSpecifiedRate = (*RateValueType7Code)(&value)\n}"} {"input": "package factor\n\nimport (\n\t\"github.com/jesand/stats\"\n\t\"github.com/jesand/stats/dist\"\n\t\"github.com/jesand/stats/variable\"\n)\n\n\n\n\ntype Factor interface {\n\n\tAdjacent() []variable.RandomVariable\n\n\tScore() float64\n}\n\n\n\n\n\n\n\ntype DistFactor struct {\n\tVars []variable.RandomVariable\n\tDist dist.Dist\n}\n\n\nfunc (factor DistFactor) Adjacent() []variable.RandomVariable {\n\treturn factor.Vars\n}\n\n\nfunc (factor DistFactor) Score() float64 {\n\tvar (\n\t\tnumVars = factor.Dist.NumVars()\n\t\tnumParams = factor.Dist.NumParams()\n\t)\n\tif len(factor.Vars) != numVars+numParams {\n\t\tpanic(stats.ErrfFactorVarNum(numVars, numParams, len(factor.Vars)))\n\t}\n\tvar (\n\t\tvars = make([]float64, numVars)\n\t\tparams = make([]float64, numParams)\n\t)\n\tfor i, rv := range factor.Vars {\n\t\tif i < len(vars) {\n\t\t\tvars[i] = rv.Val()\n\t\t} else {\n\t\t\tparams[i-len(vars)] = rv.Val()\n\t\t}\n\t}\n\treturn factor.Dist.Score(vars, params)\n}\n\n\nfunc NewConstFactor(vars []variable.RandomVariable, value float64) *ConstFactor {\n\treturn &ConstFactor{\n\t\tVars: vars,\n\t\tValue: value,\n\t}\n}\n\n\ntype ConstFactor struct {\n\tVars []variable.RandomVariable\n\tValue float64\n}\n\n\nfunc (factor ConstFactor) Adjacent() []variable.RandomVariable {\n\treturn factor.Vars\n}\n\n\nfunc (factor ConstFactor) Score() float64 {\n\treturn factor.Value\n}\n\nfunc NewDistFactor(vars []variable.RandomVariable, distr dist.Dist) *DistFactor ", "output": "{\n\treturn &DistFactor{\n\t\tVars: vars,\n\t\tDist: distr,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n)\n\n\nfunc main() {\n\thttp.HandleFunc(\"/hello\", helloHandler)\n\terr := http.ListenAndServe(\":8081\", nil)\n\tif err != nil {\n\t\tlog.Fatal(\"ListenAndServe: \", err.Error())\n\t}\n}\n\nfunc helloHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tr.ParseForm()\n\tw.Header().Set(\"myheader\", \"good\")\n\tio.WriteString(w, \"Hello, world!\")\n\tfmt.Printf(r.URL.Path + \"\\n\")\n\tfor k, v := range r.Form {\n\t\tfmt.Println(\"key:\", k, \"val:\", v)\n\t}\n}"} {"input": "package grpclog \n\nimport \"os\"\n\nvar logger = newLoggerV2()\n\n\n\n\n\nfunc Info(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\nfunc Infof(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\nfunc Infoln(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\n\nfunc Warning(args ...interface{}) {\n\tlogger.Warning(args...)\n}\n\n\nfunc Warningf(format string, args ...interface{}) {\n\tlogger.Warningf(format, args...)\n}\n\n\nfunc Warningln(args ...interface{}) {\n\tlogger.Warningln(args...)\n}\n\n\nfunc Error(args ...interface{}) {\n\tlogger.Error(args...)\n}\n\n\nfunc Errorf(format string, args ...interface{}) {\n\tlogger.Errorf(format, args...)\n}\n\n\nfunc Errorln(args ...interface{}) {\n\tlogger.Errorln(args...)\n}\n\n\n\nfunc Fatal(args ...interface{}) {\n\tlogger.Fatal(args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalf(format string, args ...interface{}) {\n\tlogger.Fatalf(format, args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalln(args ...interface{}) {\n\tlogger.Fatalln(args...)\n\tos.Exit(1)\n}\n\n\n\n\nfunc Print(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\n\n\nfunc Printf(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\n\n\nfunc Println(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\nfunc V(l int) bool ", "output": "{\n\treturn logger.V(l)\n}"} {"input": "package cli\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestExitStatusError_Error(t *testing.T) {\n\terr := &ExitStatusError{\n\t\tCode: 1,\n\t\tErr: fmt.Errorf(\"error\"),\n\t}\n\n\tif err.Error() != \"error\" {\n\t\tt.Fatal()\n\t}\n}\n\n\n\nfunc TestRequiredParameterNotSetError_Error(t *testing.T) ", "output": "{\n\terr := &RequiredParameterNotSetError{\n\t\tName: \"name\",\n\t}\n\tif err.Error() != \"required parameter name not set\" {\n\t\tt.Fail()\n\t}\n\n\terr = &RequiredParameterNotSetError{\n\t\tFormatted: \"formatted\",\n\t}\n\tif err.Error() != \"required parameter formatted not set\" {\n\t\tt.Fail()\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"testing\"\n)\n\ntype stest struct {\n\tname string\n\tinput int\n\twant string\n}\n\nvar stests = []stest{\n\t{\"empty\", 0, \"\"},\n\t{\"one\", 1, \" \"},\n\t{\"five\", 5, \" \"},\n}\n\nfunc TestSpaces(t *testing.T) {\n\tfor _, test := range stests {\n\t\tgot := Spaces(test.input)\n\t\tif got != test.want {\n\t\t\tt.Errorf(\"%s:\\ngot\\n\\\"%s\\\"\\nwant\\n\\\"%s\\\"\\n\", test.name, got, test.want)\n\t\t}\n\t}\n}\n\ntype dtest struct {\n\tinput string\n\twant string\n}\n\nvar dtests = []dtest{\n\t{\"111_hey\", \"hey\"},\n\t{\"hey\", \"hey\"},\n\t{\"0_beans\", \"beans\"},\n\t{\"99999s_beans\", \"99999s_beans\"},\n\t{\"99999_beans\", \"beans\"},\n}\n\n\n\nfunc TestDropLeadingSorter(t *testing.T) ", "output": "{\n\tfor _, test := range dtests {\n\t\tgot := DropLeadingNumbers(test.input)\n\t\tif got != test.want {\n\t\t\tt.Errorf(\n\t\t\t\t\"got \\\"%s\\\"\\n\"+\n\t\t\t\t\t\"want\\\"%s\\\"\\n\", got, test.want)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport . \"g2d\"\n\nvar arena = NewArena(Point{480, 360})\nvar a1 = NewAlien(arena, Point{40, 40})\nvar a2 = NewAlien(arena, Point{80, 80})\n\ntype Alien struct {\n arena *Arena\n x, y, w, h int\n xmin, xmax int\n dx, dy int\n}\n\nfunc NewAlien(arena *Arena, pos Point) *Alien {\n a := &Alien{arena, pos.X, pos.Y, 20, 20, pos.X, pos.X+150, 5, 5}\n arena.Add(a)\n return a\n}\n\nfunc (a *Alien) Move() {\n if a.xmin <= a.x+a.dx && a.x+a.dx <= a.xmax {\n a.x += a.dx\n } else {\n a.dx = -a.dx\n a.y += a.dy\n }\n}\n\nfunc (a *Alien) Position() Point {\n return Point{a.x, a.y}\n}\n\nfunc (a *Alien) Size() Point {\n return Point{a.w, a.h}\n}\n\nfunc (a *Alien) Symbol() Point {\n return Point{0, 0}\n}\n\nfunc (a *Alien) Collide(other Actor) {\n}\n\n\n\nfunc main() {\n InitCanvas(arena.Size())\n MainLoop(tick)\n}\n\nfunc tick() ", "output": "{\n ClearCanvas()\n arena.MoveAll()\n for _, actor := range arena.Actors() {\n FillRect(actor.Position(), actor.Size())\n }\n}"} {"input": "package registry\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/blevesearch/bleve/analysis\"\n)\n\nfunc RegisterTokenizer(name string, constructor TokenizerConstructor) {\n\t_, exists := tokenizers[name]\n\tif exists {\n\t\tpanic(fmt.Errorf(\"attempted to register duplicate tokenizer named '%s'\", name))\n\t}\n\ttokenizers[name] = constructor\n}\n\ntype TokenizerConstructor func(config map[string]interface{}, cache *Cache) (analysis.Tokenizer, error)\ntype TokenizerRegistry map[string]TokenizerConstructor\ntype TokenizerCache map[string]analysis.Tokenizer\n\nfunc (c TokenizerCache) TokenizerNamed(name string, cache *Cache) (analysis.Tokenizer, error) {\n\ttokenizer, cached := c[name]\n\tif cached {\n\t\treturn tokenizer, nil\n\t}\n\ttokenizerConstructor, registered := tokenizers[name]\n\tif !registered {\n\t\treturn nil, fmt.Errorf(\"no tokenizer with name or type '%s' registered\", name)\n\t}\n\ttokenizer, err := tokenizerConstructor(nil, cache)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error building tokenizer '%s': %v\", name, err)\n\t}\n\tc[name] = tokenizer\n\treturn tokenizer, nil\n}\n\nfunc (c TokenizerCache) DefineTokenizer(name string, typ string, config map[string]interface{}, cache *Cache) (analysis.Tokenizer, error) {\n\t_, cached := c[name]\n\tif cached {\n\t\treturn nil, fmt.Errorf(\"tokenizer named '%s' already defined\", name)\n\t}\n\ttokenizerConstructor, registered := tokenizers[typ]\n\tif !registered {\n\t\treturn nil, fmt.Errorf(\"no tokenizer type '%s' registered\", typ)\n\t}\n\ttokenizer, err := tokenizerConstructor(config, cache)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error building tokenizer '%s': %v\", name, err)\n\t}\n\tc[name] = tokenizer\n\treturn tokenizer, nil\n}\n\n\n\nfunc TokenizerTypesAndInstances() ([]string, []string) ", "output": "{\n\temptyConfig := map[string]interface{}{}\n\temptyCache := NewCache()\n\ttypes := make([]string, 0)\n\tinstances := make([]string, 0)\n\tfor name, cons := range tokenizers {\n\t\t_, err := cons(emptyConfig, emptyCache)\n\t\tif err == nil {\n\t\t\tinstances = append(instances, name)\n\t\t} else {\n\t\t\ttypes = append(types, name)\n\t\t}\n\t}\n\treturn types, instances\n}"} {"input": "package longrunning_test\n\nimport (\n\t\"cloud.google.com/go/longrunning/autogen\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/api/iterator\"\n\tlongrunningpb \"google.golang.org/genproto/googleapis/longrunning\"\n)\n\nfunc ExampleNewOperationsClient() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\n\n\nfunc ExampleOperationsClient_ListOperations() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.ListOperationsRequest{\n\t}\n\tit := c.ListOperations(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}\n\nfunc ExampleOperationsClient_CancelOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.CancelOperationRequest{\n\t}\n\terr = c.CancelOperation(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleOperationsClient_DeleteOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.DeleteOperationRequest{\n\t}\n\terr = c.DeleteOperation(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleOperationsClient_GetOperation() ", "output": "{\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.GetOperationRequest{\n\t}\n\tresp, err := c.GetOperation(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}"} {"input": "package topology\n\nimport (\n\t\"github.com/skydive-project/skydive/graffiti/getter\"\n\t\"strings\"\n)\n\nfunc (obj *NextHop) GetFieldBool(key string) (bool, error) {\n\treturn false, getter.ErrFieldNotFound\n}\n\nfunc (obj *NextHop) GetFieldInt64(key string) (int64, error) {\n\tswitch key {\n\tcase \"Priority\":\n\t\treturn int64(obj.Priority), nil\n\tcase \"IfIndex\":\n\t\treturn int64(obj.IfIndex), nil\n\t}\n\treturn 0, getter.ErrFieldNotFound\n}\n\nfunc (obj *NextHop) GetFieldString(key string) (string, error) {\n\tswitch key {\n\tcase \"IP\":\n\t\treturn obj.IP.String(), nil\n\tcase \"MAC\":\n\t\treturn string(obj.MAC), nil\n\t}\n\treturn \"\", getter.ErrFieldNotFound\n}\n\nfunc (obj *NextHop) GetFieldKeys() []string {\n\treturn []string{\n\t\t\"Priority\",\n\t\t\"IP\",\n\t\t\"MAC\",\n\t\t\"IfIndex\",\n\t}\n}\n\nfunc (obj *NextHop) MatchBool(key string, predicate getter.BoolPredicate) bool {\n\treturn false\n}\n\n\n\nfunc (obj *NextHop) MatchString(key string, predicate getter.StringPredicate) bool {\n\tif b, err := obj.GetFieldString(key); err == nil {\n\t\treturn predicate(b)\n\t}\n\treturn false\n}\n\nfunc (obj *NextHop) GetField(key string) (interface{}, error) {\n\tif s, err := obj.GetFieldString(key); err == nil {\n\t\treturn s, nil\n\t}\n\n\tif i, err := obj.GetFieldInt64(key); err == nil {\n\t\treturn i, nil\n\t}\n\treturn nil, getter.ErrFieldNotFound\n}\n\nfunc init() {\n\tstrings.Index(\"\", \".\")\n}\n\nfunc (obj *NextHop) MatchInt64(key string, predicate getter.Int64Predicate) bool ", "output": "{\n\tif b, err := obj.GetFieldInt64(key); err == nil {\n\t\treturn predicate(b)\n\t}\n\treturn false\n}"} {"input": "package client \n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net/url\"\n\t\"strconv\"\n\n\t\"github.com/tiborvass/docker/api/types/swarm\"\n)\n\n\n\n\nfunc (cli *Client) SwarmUpdate(ctx context.Context, version swarm.Version, swarm swarm.Spec, flags swarm.UpdateFlags) error ", "output": "{\n\tquery := url.Values{}\n\tquery.Set(\"version\", strconv.FormatUint(version.Index, 10))\n\tquery.Set(\"rotateWorkerToken\", fmt.Sprintf(\"%v\", flags.RotateWorkerToken))\n\tquery.Set(\"rotateManagerToken\", fmt.Sprintf(\"%v\", flags.RotateManagerToken))\n\tquery.Set(\"rotateManagerUnlockKey\", fmt.Sprintf(\"%v\", flags.RotateManagerUnlockKey))\n\tresp, err := cli.post(ctx, \"/swarm/update\", query, swarm, nil)\n\tensureReaderClosed(resp)\n\treturn err\n}"} {"input": "package cmdlib\n\nimport (\n\t\"github.com/GoogleCloudPlatform/k8s-cluster-bundle/pkg/files\"\n\tlog \"k8s.io/klog\"\n)\n\n\ntype CmdIO struct {\n\tStdIO StdioReaderWriter\n\n\tFileIO files.FileReaderWriter\n\n\tExitIO Exiter\n}\n\n\ntype Exiter interface {\n\tExit(args ...interface{})\n\n\tExitf(format string, v ...interface{})\n}\n\n\ntype RealExiter struct{}\n\n\nfunc (e *RealExiter) Exit(args ...interface{}) {\n\tlog.Exit(args...)\n}\n\n\n\n\nfunc (e *RealExiter) Exitf(format string, v ...interface{}) ", "output": "{\n\tlog.Exitf(format, v...)\n}"} {"input": "package learn\n\nimport (\n\t\"fmt\"\n)\n\ntype List struct {\n\tData interface{}\n\tNextnode *List\n}\n\nfunc myPrint(t interface{}) {\n\tfmt.Println(t)\n}\n\n\nfunc (l *List) ListLength() int {\n\tvar i int = 0\n\tn := l\n\tfor n.Nextnode != nil {\n\t\ti++\n\t\tn = n.Nextnode\n\t}\n\treturn i + 1\n}\n\n\nfunc (l *List) GetEle(i int) (ele interface{}) {\n\tif i < 0 || i > l.ListLength() {\n\t\treturn nil\n\t}\n\tcur := l\n\tj := 1\n\tfor cur.Nextnode != nil {\n\t\tif j == i {\n\t\t\treturn cur.Data\n\t\t}\n\t\tj++\n\t\tcur = cur.Nextnode\n\n\t}\n\tif cur != nil && j == i {\n\t\treturn cur.Data\n\t}\n\treturn nil\n}\n\n\nfunc (l *List) ListInsert(i int, ele interface{}) bool {\n\tvar s List \n\tif i < 0 || i > l.ListLength() {\n\t\treturn false\n\t}\n\ts.Data = ele\n\tp := l\n\tj := 1\n\tfor j < i && p != nil {\n\t\tj++\n\t\tp = p.Nextnode\n\t}\n\tif p != nil && j <= i {\n\t\ts.Nextnode = p.Nextnode\n\t\tp.Nextnode = &s\n\t} else {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\nfunc (l *List) ListDelete(i int) bool {\n\tp := l\n\tj := 1\n\tfor j < i && p != nil {\n\t\tj++\n\t\tp = p.Nextnode\n\t}\n\tif p == nil || j > i {\n\t\treturn false\n\t}\n\tp.Nextnode = p.Nextnode.Nextnode\n\treturn true\n}\n\n\n\n\nfunc (l *List) ListAll() (all string) ", "output": "{\n\tp := l\n\tfor p != nil {\n\t\tall += fmt.Sprintf(\"%v+\", p.Data)\n\t\tp = p.Nextnode\n\t}\n\treturn all\n}"} {"input": "package iso20022\n\n\ntype StatisticsByPredefinedTimePeriods2 struct {\n\n\tHighestPriceValue12Months *PriceValue5 `xml:\"HghstPricVal12Mnths,omitempty\"`\n\n\tLowestPriceValue12Months *PriceValue5 `xml:\"LwstPricVal12Mnths,omitempty\"`\n\n\tOneYearPriceChange *PriceValueChange1 `xml:\"OneYrPricChng,omitempty\"`\n\n\tThreeYearPriceChange *PriceValueChange1 `xml:\"ThreeYrPricChng,omitempty\"`\n\n\tFiveYearPriceChange *PriceValueChange1 `xml:\"FiveYrPricChng,omitempty\"`\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddHighestPriceValue12Months() *PriceValue5 {\n\ts.HighestPriceValue12Months = new(PriceValue5)\n\treturn s.HighestPriceValue12Months\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddLowestPriceValue12Months() *PriceValue5 {\n\ts.LowestPriceValue12Months = new(PriceValue5)\n\treturn s.LowestPriceValue12Months\n}\n\n\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddThreeYearPriceChange() *PriceValueChange1 {\n\ts.ThreeYearPriceChange = new(PriceValueChange1)\n\treturn s.ThreeYearPriceChange\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddFiveYearPriceChange() *PriceValueChange1 {\n\ts.FiveYearPriceChange = new(PriceValueChange1)\n\treturn s.FiveYearPriceChange\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddOneYearPriceChange() *PriceValueChange1 ", "output": "{\n\ts.OneYearPriceChange = new(PriceValueChange1)\n\treturn s.OneYearPriceChange\n}"} {"input": "package main\n\nimport (\n \"encoding/json\"\n \"fmt\"\n \"strings\"\n\n \"github.com/bwilkins/processes\"\n)\n\ntype NginxReport struct {\n Workers int `json:\"workers\"`\n MemoryUsed int `json:\"memory_used\"`\n}\n\n\n\nfunc main() {\n workers := 0\n memory_used := 0\n\n for _, nginx := range findNginxs() {\n if strings.Contains(nginx.Command, \"worker\") {\n workers += 1\n memory_used += nginx.ResidentMemory\n }\n }\n\n report := NginxReport{workers, memory_used}\n\n j, _ := json.Marshal(report)\n fmt.Println(string(j))\n}\n\nfunc findNginxs() processes.PsList ", "output": "{\n entries := processes.Ps()\n nginxs := make(processes.PsList, 0, 2)\n for _, entry := range entries {\n if strings.Contains(entry.Command, \"nginx\") {\n nginxs = append(nginxs, entry)\n }\n }\n return nginxs\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype OpenpitrixCreateReleaseRequest struct {\n\n\tAppID string `json:\"app_id,omitempty\"`\n\n\tNamespace string `json:\"namespace,omitempty\"`\n\n\tReleaseName string `json:\"release_name,omitempty\"`\n\n\tRuntimeID string `json:\"runtime_id,omitempty\"`\n\n\tVersionID string `json:\"version_id,omitempty\"`\n}\n\n\n\n\n\nfunc (m *OpenpitrixCreateReleaseRequest) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *OpenpitrixCreateReleaseRequest) UnmarshalBinary(b []byte) error {\n\tvar res OpenpitrixCreateReleaseRequest\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *OpenpitrixCreateReleaseRequest) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package pod_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestPod(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Pod Suite\")\n}"} {"input": "package github\n\nimport (\n\t\"github.com/hashicorp/terraform/helper/schema\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\n\n\n\nvar descriptions map[string]string\n\nfunc init() {\n\tdescriptions = map[string]string{\n\t\t\"token\": \"The OAuth token used to connect to GitHub.\",\n\n\t\t\"organization\": \"The GitHub organization name to manage.\",\n\t}\n}\n\nfunc providerConfigure(d *schema.ResourceData) (interface{}, error) {\n\tconfig := Config{\n\t\tToken: d.Get(\"token\").(string),\n\t\tOrganization: d.Get(\"organization\").(string),\n\t}\n\n\treturn config.Client()\n}\n\nfunc Provider() terraform.ResourceProvider ", "output": "{\n\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"token\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"GITHUB_TOKEN\", nil),\n\t\t\t\tDescription: descriptions[\"token\"],\n\t\t\t},\n\t\t\t\"organization\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"GITHUB_ORGANIZATION\", nil),\n\t\t\t\tDescription: descriptions[\"organization\"],\n\t\t\t},\n\t\t},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"github_team\": resourceGithubTeam(),\n\t\t\t\"github_team_membership\": resourceGithubTeamMembership(),\n\t\t\t\"github_team_repository\": resourceGithubTeamRepository(),\n\t\t\t\"github_membership\": resourceGithubMembership(),\n\t\t},\n\n\t\tConfigureFunc: providerConfigure,\n\t}\n}"} {"input": "package shoauth\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\ntype expectedSuccessHandler struct{}\n\nfunc (s *expectedSuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}\n\ntype expectedFailureHandler struct{}\n\nfunc (s *expectedFailureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}\n\ntype unexpectedSuccessHandler struct {\n\tt *testing.T\n}\n\n\n\ntype unexpectedFailureHandler struct {\n\tt *testing.T\n}\n\nfunc (s *unexpectedFailureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.t.Errorf(\"Request should have succeeded, but failed instead!\")\n}\n\ntype testPersistence struct {\n\texists bool\n\tcreate error\n\tsession bool\n}\n\nfunc (t *testPersistence) InstallationExists(shopID string) bool {\n\treturn t.exists\n}\n\nfunc (t *testPersistence) CreateInstallation(shopID string, accessToken string) error {\n\treturn t.create\n}\n\nfunc TestAlreadyInstalled(t *testing.T) {\n\tp := testPersistence{\n\t\texists: true,\n\t\tcreate: errors.New(\"Installation already exists!\"),\n\t\tsession: false,\n\t}\n\thandler := NewShopifyOauthHandler(&unexpectedSuccessHandler{t: t}, &expectedFailureHandler{}, &p)\n\ttestServer := httptest.NewServer(handler)\n\tdefer testServer.Close()\n\thttp.Get(testServer.URL + \"/install\")\n}\n\nfunc (s *unexpectedSuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\ts.t.Errorf(\"Request should have failed, but succeeded instead!\")\n}"} {"input": "package ansiwriter\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype Modifier func() string\n\nfunc escapeANSI(code int) string {\n\treturn fmt.Sprintf(\"\\033[%dm\", code)\n}\n\nfunc Bold() string { return escapeANSI(1) }\nfunc Black() string { return escapeANSI(30) }\nfunc Red() string { return escapeANSI(31) }\nfunc Green() string { return escapeANSI(32) }\nfunc Yellow() string { return escapeANSI(33) }\n\nfunc Magenta() string { return escapeANSI(35) }\nfunc Cyan() string { return escapeANSI(36) }\nfunc White() string { return escapeANSI(37) }\n\ntype awr struct {\n\tio.Writer\n\tmodifiers []Modifier\n}\n\n\n\n\nfunc New(w io.Writer, mods ...Modifier) io.Writer {\n\treturn awr{w, mods}\n}\n\nfunc (a awr) Write(b []byte) (n int, err error) {\n\tfor _, mod := range a.modifiers {\n\t\ta.Writer.Write([]byte(mod()))\n\t}\n\tn, err = a.Writer.Write(b)\n\t_, _ = a.Writer.Write([]byte(\"\\033[0m\"))\n\treturn\n}\n\nfunc Blue() string ", "output": "{ return escapeANSI(34) }"} {"input": "package ormapper\n\nimport (\n\t\"database/sql\"\n\t\"time\"\n)\n\ntype Character struct {\n\tId int64\n\n\tName string\n\n\tKana string\n\tRomaji string\n\tGyou string\n\n\tBirthday time.Time\n\n\tBlood string\n\n\tHeight int\n\tWeight int\n\n\tBust int\n\tWaste int\n\tHip int\n\tBracup string\n\n\tOutline string\n\n\tCreated time.Time\n\tUpdated time.Time\n\n\tIcon *Image\n\tIconId sql.NullInt64\n\n\tProduct string\n\tAnime *Anime\n\tAnimeId sql.NullInt64\n\n\tPicturesCount int\n\tPictures []*Picture\n}\n\n\n\nfunc (m Character) TableName() string ", "output": "{\n\treturn \"character\"\n}"} {"input": "package mock\n\nimport (\n\t\"context\"\n\n\tfn \"knative.dev/kn-plugin-func\"\n)\n\ntype PipelinesProvider struct {\n\tRunInvoked bool\n\tRunFn func(fn.Function) error\n\tRemoveInvoked bool\n\tRemoveFn func(fn.Function) error\n}\n\nfunc NewPipelinesProvider() *PipelinesProvider {\n\treturn &PipelinesProvider{\n\t\tRunFn: func(fn.Function) error { return nil },\n\t\tRemoveFn: func(fn.Function) error { return nil },\n\t}\n}\n\nfunc (p *PipelinesProvider) Run(ctx context.Context, f fn.Function) error {\n\tp.RunInvoked = true\n\treturn p.RunFn(f)\n}\n\n\n\nfunc (p *PipelinesProvider) Remove(ctx context.Context, f fn.Function) error ", "output": "{\n\tp.RemoveInvoked = true\n\treturn p.RemoveFn(f)\n}"} {"input": "package controller \n\nimport (\n\t\"net/url\"\n\t\"testing\"\n\n\t\"github.com/docker/infrakit/pkg/spi/stack\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\n\ntype fakeLeaderT bool\n\nfunc (f fakeLeaderT) IsLeader() (bool, error) {\n\treturn bool(f), nil\n}\n\nfunc (f fakeLeaderT) LeaderLocation() (*url.URL, error) {\n\treturn nil, nil\n}\n\nfunc TestSingleton(t *testing.T) {\n\n\tcall1 := make(chan int, 1)\n\tsingleton1 := Singleton(fake(call1), fakeLeader(true))\n\n\t_, err := singleton1.Describe(nil)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, <-call1)\n\n\tcall2 := make(chan int, 1)\n\tsingleton2 := Singleton(fake(call2), fakeLeader(false))\n\n\t_, err = singleton2.Describe(nil)\n\trequire.Error(t, err)\n\trequire.Equal(t, \"not a leader\", err.Error())\n\n\tclose(call1)\n\tclose(call2)\n}\n\nfunc fakeLeader(v bool) func() stack.Leadership ", "output": "{\n\treturn func() stack.Leadership { return fakeLeaderT(v) }\n}"} {"input": "package http_handlers\n\nimport (\n\t\"fmt\"\n\t\"github.com/go-martini/martini\"\n\t\"net/http\"\n)\n\n\n\nfunc GetCache() func(\n\tmartini.Context,\n\tmartini.Params,\n\thttp.ResponseWriter,\n\t*http.Request,\n) {\n\treturn HttpHandler(\n\t\t[]string{\n\t\t\tAUTH_REQUIRED,\n\t\t\tCACHE_REQUIRED,\n\t\t},\n\t\tfunc(h *Http) {\n\t\t\tif c := h.session.GetCache(\n\t\t\t\th.vars[\"cache_id\"],\n\t\t\t); c != nil {\n\t\t\t\th.SetResponse(\n\t\t\t\t\tc,\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\th.AddError(\n\t\t\t\t\tfmt.Errorf(\n\t\t\t\t\t\t`Cache not found`,\n\t\t\t\t\t),\n\t\t\t\t\t404,\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\t)\n}\n\nfunc RegisterCache() func(\n\tmartini.Context,\n\tmartini.Params,\n\thttp.ResponseWriter,\n\t*http.Request,\n) {\n\treturn HttpHandler(\n\t\t[]string{\n\t\t\tAUTH_REQUIRED,\n\t\t},\n\t\tfunc(h *Http) {\n\t\t\th.SetResponseCreatedObject(\n\t\t\t\th.session.CreateCache(),\n\t\t\t)\n\t\t},\n\t)\n}\n\nfunc GetCaches() func(\n\tmartini.Context,\n\tmartini.Params,\n\thttp.ResponseWriter,\n\t*http.Request,\n) ", "output": "{\n\treturn HttpHandler(\n\t\t[]string{\n\t\t\tAUTH_REQUIRED,\n\t\t},\n\t\tfunc(h *Http) {\n\t\t\th.SetResponse(\n\t\t\t\th.session.Caches,\n\t\t\t)\n\t\t},\n\t)\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\n\n\n\nvar SandboxSubscribersCmd = &cobra.Command{\n\tUse: \"subscribers\",\n\tShort: TRCLI(\"cli.sandbox.subscribers.summary\"),\n\tLong: TRCLI(`cli.sandbox.subscribers.description`),\n}\n\nfunc init() ", "output": "{\n\tSandboxCmd.AddCommand(SandboxSubscribersCmd)\n}"} {"input": "package reading\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/ikeikeikeike/go-sitemap-generator/stm\"\n)\n\n\nfunc (p *Plugin) Mount() error {\n\tp.Sitemap.Register(p.sitemap)\n\n\tht := p.Router.Group(\"/reading/htdocs\")\n\tht.GET(\"/notes\", p.Layout.HTML(\"reading/notes/index\", p.indexNotesH))\n\tht.GET(\"/books\", p.Layout.HTML(\"reading/books/index\", p.indexBooksH))\n\tht.GET(\"/books/:id\", p.Layout.HTML(\"reading/books/show\", p.showBookH))\n\tht.GET(\"/pages/:id/*href\", p.showPage)\n\n\trt := p.Router.Group(\"/reading\")\n\trt.GET(\"/books\", p.Layout.JSON(p.indexBooks))\n\trt.DELETE(\"/books/:id\", p.Layout.MustAdminMiddleware, p.Layout.JSON(p.destroyBook))\n\trt.GET(\"/notes\", p.Layout.MustSignInMiddleware, p.Layout.JSON(p.indexNotes))\n\trt.POST(\"/notes\", p.Layout.MustSignInMiddleware, p.Layout.JSON(p.createNote))\n\trt.GET(\"/notes/:id\", p.Layout.JSON(p.showNote))\n\trt.POST(\"/notes/:id\", p.Layout.MustSignInMiddleware, p.canEditNote, p.Layout.JSON(p.updateNote))\n\trt.DELETE(\"/notes/:id\", p.Layout.MustSignInMiddleware, p.canEditNote, p.Layout.JSON(p.destroyNote))\n\treturn nil\n}\n\n\n\nfunc (p *Plugin) sitemap() ([]stm.URL, error) ", "output": "{\n\titems := []stm.URL{\n\t\t{\"loc\": \"/reading/htdocs/books\"},\n\t\t{\"loc\": \"/reading/htdocs/notes\"},\n\t}\n\n\tvar books []Book\n\tif err := p.DB.Select([]string{\"id\", \"updated_at\"}).Order(\"updated_at DESC\").Find(&books).Error; err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, it := range books {\n\t\titems = append(items, stm.URL{\n\t\t\t\"loc\": fmt.Sprintf(\"/reading/htdocs/books/%d\", it.ID),\n\t\t\t\"lastmod\": it.UpdatedAt,\n\t\t})\n\t}\n\n\treturn items, nil\n}"} {"input": "package packr\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/gobuffalo/envy\"\n\t\"github.com/gobuffalo/packr/v2/plog\"\n)\n\n\n\nfunc resolutionDirTestFilename(filename, og string) (string, bool) {\n\tng := filepath.Join(filepath.Dir(filename), og)\n\n\tcov := filepath.Join(\"_test\", \"_obj_test\")\n\tng = strings.Replace(ng, string(filepath.Separator)+cov, \"\", 1)\n\n\tif resolutionDirExists(ng, og) {\n\t\treturn ng, true\n\t}\n\n\tng = filepath.Join(envy.GoPath(), \"src\", ng)\n\tif resolutionDirExists(ng, og) {\n\t\treturn ng, true\n\t}\n\n\treturn og, false\n}\n\nfunc resolutionDirExists(s, og string) bool {\n\t_, err := os.Stat(s)\n\tif err != nil {\n\t\treturn false\n\t}\n\tplog.Debug(\"packr\", \"resolutionDir\", \"original\", og, \"resolved\", s)\n\treturn true\n}\n\nfunc resolutionDir(og string) string {\n\tng, _ := filepath.Abs(og)\n\n\tif resolutionDirExists(ng, og) {\n\t\treturn ng\n\t}\n\n\t_, filename, _, _ := runtime.Caller(3)\n\tng, ok := resolutionDirTestFilename(filename, og)\n\tif ok {\n\t\treturn ng\n\t}\n\n\t_, filename, _, _ = runtime.Caller(4)\n\tng, ok = resolutionDirTestFilename(filename, og)\n\tif ok {\n\t\treturn ng\n\t}\n\n\treturn og\n}\n\nfunc construct(name string, path string) *Box ", "output": "{\n\treturn &Box{\n\t\tPath:\t\tpath,\n\t\tName:\t\tname,\n\t\tResolutionDir:\tresolutionDir(path),\n\t\tresolvers:\tresolversMap{},\n\t\tdirs:\t\tdirsMap{},\n\t}\n}"} {"input": "package mailgun\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/getfider/fider/app/models/dto\"\n\t\"github.com/getfider/fider/app/pkg/bus\"\n\t\"github.com/getfider/fider/app/pkg/env\"\n\t\"github.com/getfider/fider/app/pkg/log\"\n)\n\n\n\n\nvar baseURLs = map[string]string{\n\t\"US\": \"https://api.mailgun.net/v3/%s\",\n\t\"EU\": \"https://api.eu.mailgun.net/v3/%s\",\n}\n\n\n\ntype Service struct{}\n\nfunc (s Service) Name() string {\n\treturn \"Mailgun\"\n}\n\nfunc (s Service) Category() string {\n\treturn \"email\"\n}\n\nfunc (s Service) Enabled() bool {\n\treturn env.Config.Email.Type == \"mailgun\"\n}\n\nfunc (s Service) Init() {\n\tbus.AddListener(sendMail)\n\tbus.AddHandler(fetchRecentSupressions)\n}\n\n\n\nfunc getEndpoint(ctx context.Context, domain, path string) string {\n\tvar regionCode = env.Config.Email.Mailgun.Region\n\tregionCode = strings.ToUpper(regionCode)\n\n\tif len(regionCode) < 1 {\n\t\tregionCode = \"US\"\n\t} else if len(baseURLs[regionCode]) < 1 {\n\t\tlog.Warnf(ctx,\n\t\t\t\"Unknown Mailgun region code '@{Code}' configured - falling back to 'US'\",\n\t\t\tdto.Props{\n\t\t\t\t\"Code\": env.Config.Email.Mailgun.Region,\n\t\t\t},\n\t\t)\n\n\t\tregionCode = \"US\"\n\t}\n\n\treturn fmt.Sprintf(baseURLs[regionCode], domain) + path\n}\n\nfunc init() ", "output": "{\n\tbus.Register(Service{})\n}"} {"input": "package aws\n\nimport (\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/service/redshift\"\n)\n\n\n\nfunc tagsToMapRedshift(ts []*redshift.Tag) map[string]string {\n\tresult := make(map[string]string)\n\tfor _, t := range ts {\n\t\tresult[*t.Key] = *t.Value\n\t}\n\n\treturn result\n}\n\nfunc tagsFromMapRedshift(m map[string]interface{}) []*redshift.Tag ", "output": "{\n\tresult := make([]*redshift.Tag, 0, len(m))\n\tfor k, v := range m {\n\t\tresult = append(result, &redshift.Tag{\n\t\t\tKey: aws.String(k),\n\t\t\tValue: aws.String(v.(string)),\n\t\t})\n\t}\n\n\treturn result\n}"} {"input": "package util\n\nimport (\n\t\"testing\"\n\t\"github.com/DanielDanteDosSantosViana/hire.me/config\"\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc init() {\n\tconfig.Conf.Base.Alfabeto = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n}\n\nfunc TestConverterInteiro18446744073709551615ParaAliasv8QrKbgkrIp(t *testing.T) {\n\tConvey(\"Dado um inteiro (int64) 18446744073709551615\", t, func() {\n\t\tvar inteiro uint64 = 18446744073709551615\n\t\tvar alias string = \"v8QrKbgkrIp\"\n\t\tConvey(\"Quando converto inteiro 18446744073709551615 para string \", func() {\n\t\t\tretorno := InteiroParaString(inteiro)\n\n\t\t\tConvey(\"O valor retornado deve ser o alias 'v8QrKbgKrIp' \", func() {\n\t\t\t\tSo(retorno, ShouldEqual, alias)\n\t\t\t})\n\t\t})\n\t})\n}\n\n\n\nfunc TestConverterPrimeiroElementoDaSequence(t *testing.T) ", "output": "{\n\tConvey(\"Dado o primeiro elemento da sequence (int64) 0\", t, func() {\n\t\tvar inteiro uint64 = 0\n\t\tvar alias string = \"a\"\n\t\tConvey(\"Quando converto inteiro 0 para string \", func() {\n\t\t\tretorno := InteiroParaString(inteiro)\n\n\t\t\tConvey(\"O valor retornado deve ser a primeira letra contida em 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' \", func() {\n\t\t\t\tSo(retorno, ShouldEqual, alias)\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package workshop\n\nimport (\n\t\"math\"\n)\n\n\ntype Shape interface {\n\tarea()\n\tcircumference()\n\tvolume()\n}\n\n\ntype Circle struct {\n\tradius float64\n\tPI float64\n}\n\nfunc (circle *Circle) area() float64 {\n\treturn circle.PI * math.Pow(circle.radius, 2)\n}\n\nfunc (circle *Circle) circumference() float64 {\n\treturn 2 * circle.PI * circle.radius\n}\n\n\ntype Square struct {\n\tside float64\n}\n\nfunc (square *Square) area() float64 {\n\treturn math.Pow(square.side, 2)\n}\n\ntype Sphere struct {\n\tPI float64\n\tradius float64\n}\n\nfunc (sphere *Sphere) volume() float64 {\n\treturn (4 / 3) * sphere.PI * math.Pow(sphere.radius, 3)\n}\n\n\ntype Cube struct {\n\tside float64\n}\n\nfunc (cube *Cube) volume() float64 {\n\treturn math.Pow(cube.side, 3)\n}\n\nfunc (square *Square) volume() float64 {\n\treturn math.Pow(square.side, 3)\n}\n\n\ntype Rectangle struct {\n\theight int\n\twidth int\n}\n\n\n\nfunc interfaces() {\n\tcircle := Circle{radius: 5.5, PI: math.Pi}\n\tareaOfCircle := circle.area()\n\n\tassert(areaOfCircle == 55)\n\tassert(circle.circumference() == 88)\n\n\tvar square = Square{5}\n\tassert(square.area() == 36)\n\n\tcube := new(Cube)\n\tassert(cube.volume() == 8)\n\n\tvar rectangle = Rectangle{width: 4, height: 5}\n\tassert(rectangle.area() == 2)\n}\n\nfunc (rectangle *Rectangle) area() int ", "output": "{\n\treturn rectangle.height * rectangle.width\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfmt.Println(Hello())\n}\n\n\n\n\n\nfunc user() string {\n\tuser := os.Getenv(\"USER\")\n\tif user == \"\" {\n\t\tuser = os.Getenv(\"USERNAME\")\n\t}\n\tif user == \"\" {\n\t\tuser = \"stranger\"\n\t}\n\treturn user\n}\n\nfunc Hello() string ", "output": "{\n\treturn \"Hello \" + user()\n}"} {"input": "package post\n\nimport \"github.com/barnex/bruteray/imagef\"\n\ntype Params struct {\n\tGaussian BloomParams\n\tAiry BloomParams\n\tStar BloomParams\n}\n\ntype BloomParams struct {\n\tRadius float64\n\tAmplitude float64\n\tThreshold float64\n}\n\nfunc (p *Params) ApplyTo(img imagef.Image, pixelSize float64) imagef.Image {\n\tif b := p.Gaussian; b.Radius != 0 {\n\t\timg = ApplyGaussianBloom(img, pixelSize, b.Radius, b.Amplitude, b.Threshold)\n\t}\n\tif b := p.Airy; b.Radius != 0 {\n\t\timg = ApplyAiryBloom(img, pixelSize, b.Radius, b.Amplitude, b.Threshold)\n\t}\n\tif b := p.Star; b.Radius != 0 {\n\t\timg = ApplyStarBloom(img, pixelSize, b.Radius, b.Amplitude, b.Threshold)\n\t}\n\treturn img\n}\n\nfunc ApplyGaussianBloom(img imagef.Image, pixelSize, radius, amplitude, threshold float64) imagef.Image {\n\twidthPix := radius / pixelSize\n\tnumPix := int(5*widthPix) + 1\n\tK := Gaussian(numPix, widthPix)\n\timg2 := img.Copy()\n\tAddConvolution(img2, img, K, amplitude, threshold)\n\treturn img2\n}\n\n\n\nfunc ApplyStarBloom(img imagef.Image, pixelSize, radius, amplitude, threshold float64) imagef.Image {\n\twidthPix := radius / pixelSize\n\tnumPix := int(widthPix)\n\tK := starKernel(numPix)\n\timg2 := img.Copy()\n\tAddConvolution(img2, img, K, amplitude, threshold)\n\treturn img2\n}\n\nfunc ApplyAiryBloom(img imagef.Image, pixelSize, radius, amplitude, threshold float64) imagef.Image ", "output": "{\n\twidthPix := radius / pixelSize\n\tnumPix := int(8*widthPix) + 1\n\tK := Airy(numPix, widthPix)\n\timg2 := img.Copy()\n\tAddConvolution(img2, img, K, amplitude, threshold)\n\treturn img2\n}"} {"input": "package trace\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\ntype Tracer interface {\n\tTrace(...interface{})\n}\n\ntype tracer struct {\n\tout io.Writer\n}\n\n\n\ntype nilTracer struct{}\n\nfunc (t *nilTracer) Trace(a ...interface{}) {}\n\n\nfunc Off() Tracer {\n\treturn &nilTracer{}\n}\n\nfunc New(w io.Writer) Tracer {\n\treturn &tracer{out: w}\n}\n\nfunc (t *tracer) Trace(a ...interface{}) ", "output": "{\n\tt.out.Write([]byte(fmt.Sprint(a...)))\n\tt.out.Write([]byte(\"\\n\"))\n}"} {"input": "package archive\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestArchiveStaffs(t *testing.T) {\n\tconvey.Convey(\"Staffs\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t\tmids = []int64{27515258}\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\taidm, err := d.Staffs(c, mids)\n\t\t\tctx.Convey(\"Then err should be nil.aidm should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t\tctx.So(aidm, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestArchiveStaffAid(t *testing.T) {\n\tconvey.Convey(\"StaffAid\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t\taid = int64(10110188)\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\tmids, err := d.StaffAid(c, aid)\n\t\t\tctx.Convey(\"Then err should be nil.mids should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t\tctx.So(mids, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestArchiveStaff(t *testing.T) ", "output": "{\n\tconvey.Convey(\"Staff\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t\tmid = int64(27515258)\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\taids, err := d.Staff(c, mid)\n\t\t\tctx.Convey(\"Then err should be nil.aids should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t\tctx.So(len(aids), convey.ShouldBeGreaterThanOrEqualTo, 0)\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package scaleway\n\nimport (\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/scaleway/scaleway-cli/pkg/api\"\n)\n\n\n\n\n\nfunc String(val string) *string {\n\treturn &val\n}\n\n\n\n\nfunc deleteServerSafe(s *api.ScalewayAPI, serverID string) error {\n\tserver, err := s.GetServer(serverID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif server.State != \"stopped\" {\n\t\tif err := s.PostServerAction(serverID, \"poweroff\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := waitForServerState(s, serverID, \"stopped\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := s.DeleteServer(serverID); err != nil {\n\t\treturn err\n\t}\n\tif rootVolume, ok := server.Volumes[\"0\"]; ok {\n\t\tif err := s.DeleteVolume(rootVolume.Identifier); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc waitForServerState(s *api.ScalewayAPI, serverID string, targetState string) error {\n\tvar server *api.ScalewayServer\n\tvar err error\n\n\tvar currentState string\n\n\tfor {\n\t\tserver, err = s.GetServer(serverID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif currentState != server.State {\n\t\t\tlog.Printf(\"[DEBUG] Server changed state to %q\\n\", server.State)\n\t\t\tcurrentState = server.State\n\t\t}\n\t\tif server.State == targetState {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\treturn nil\n}\n\nfunc Bool(val bool) *bool ", "output": "{\n\treturn &val\n}"} {"input": "package cabf_br\n\n\n\nimport (\n\t\"testing\"\n\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/test\"\n)\n\n\n\nfunc TestImproperModulusGoodQ(t *testing.T) {\n\tinputPath := \"dsaNotShorterThan2048Bits.pem\"\n\texpected := lint.Pass\n\tout := test.TestLint(\"e_dsa_improper_modulus_or_divisor_size\", inputPath)\n\tif out.Status != expected {\n\t\tt.Errorf(\"%s: expected %s, got %s\", inputPath, expected, out.Status)\n\t}\n}\n\nfunc TestImproperModulusBadQ(t *testing.T) ", "output": "{\n\tinputPath := \"dsaBadQLen.pem\"\n\texpected := lint.Error\n\tout := test.TestLint(\"e_dsa_improper_modulus_or_divisor_size\", inputPath)\n\tif out.Status != expected {\n\t\tt.Errorf(\"%s: expected %s, got %s\", inputPath, expected, out.Status)\n\t}\n}"} {"input": "package mackerel\n\n\ntype CheckStatus string\n\n\nconst (\n\tCheckStatusOK CheckStatus = \"OK\"\n\tCheckStatusWarning CheckStatus = \"WARNING\"\n\tCheckStatusCritical CheckStatus = \"CRITICAL\"\n\tCheckStatusUnknown CheckStatus = \"UNKNOWN\"\n)\n\n\ntype CheckReport struct {\n\tSource CheckSource `json:\"source\"`\n\tName string `json:\"name\"`\n\tStatus CheckStatus `json:\"status\"`\n\tMessage string `json:\"message\"`\n\tOccurredAt int64 `json:\"occurredAt\"`\n\tNotificationInterval uint `json:\"notificationInterval,omitempty\"`\n\tMaxCheckAttempts uint `json:\"maxCheckAttempts,omitempty\"`\n}\n\n\ntype CheckSource interface {\n\tCheckType() string\n\n\tisCheckSource()\n}\n\nconst checkTypeHost = \"host\"\n\n\nvar _ CheckSource = (*checkSourceHost)(nil)\n\n\n\nfunc (cs *checkSourceHost) isCheckSource() {}\n\ntype checkSourceHost struct {\n\tType string `json:\"type\"`\n\tHostID string `json:\"hostId\"`\n}\n\n\n\n\n\nfunc NewCheckSourceHost(hostID string) CheckSource {\n\treturn &checkSourceHost{\n\t\tType: checkTypeHost,\n\t\tHostID: hostID,\n\t}\n}\n\n\ntype CheckReports struct {\n\tReports []*CheckReport `json:\"reports\"`\n}\n\n\nfunc (c *Client) PostCheckReports(crs *CheckReports) error {\n\tresp, err := c.PostJSON(\"/api/v0/monitoring/checks/report\", crs)\n\tdefer closeResponse(resp)\n\treturn err\n}\n\nfunc (cs *checkSourceHost) CheckType() string ", "output": "{\n\treturn checkTypeHost\n}"} {"input": "package panicif\n\n\n\nfunc NotNil(x interface{}) ", "output": "{\n\tif x != nil {\n\t\tpanic(x)\n\t}\n}"} {"input": "package ratelimiter\n\nimport (\n\t\"strings\"\n)\n\n\n\nfunc New(conf *Config) (res RateLimiter, err *Error) ", "output": "{\n\tif conf == nil {\n\t\terr = getErrObj(ErrInitialization, \"Rate limiter empty config passed\")\n\t\treturn nil, err\n\t}\n\n\tif conf.MaxRate <= 0 {\n\t\treturn nil, getErrObj(ErrInitialization, \"Max rate must be greater than 0\")\n\t}\n\n\tif conf.MaxBurst < 0 {\n\t\treturn nil, getErrObj(ErrInitialization, \"Max burst must be greater than or equal to 0\")\n\t}\n\n\tswitch strings.ToUpper(conf.Type) {\n\tcase GCRA:\n\t\tres = new(GCRARateLimiter)\n\t\terr = res.Init(conf)\n\tdefault:\n\t\tres = new(GCRARateLimiter)\n\t\terr = res.Init(conf)\n\t}\n\n\treturn res, err\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/utils\"\n\nfunc init() {\n\tc := &ImportTpFromFolder{\n\t\tname: \"import_tp_from_folder\",\n\t\trpcMethod: utils.APIerSv1ImportTariffPlanFromFolder,\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype ImportTpFromFolder struct {\n\tname string\n\trpcMethod string\n\trpcParams *utils.AttrImportTPFromFolder\n\trpcResult string\n\t*CommandExecuter\n}\n\n\n\nfunc (self *ImportTpFromFolder) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *ImportTpFromFolder) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &utils.AttrImportTPFromFolder{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *ImportTpFromFolder) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *ImportTpFromFolder) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *ImportTpFromFolder) Name() string ", "output": "{\n\treturn self.name\n}"} {"input": "package category\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/vapi/tags\"\n)\n\ntype ls struct {\n\t*flags.ClientFlag\n\t*flags.OutputFlag\n}\n\nfunc init() {\n\tcli.Register(\"tags.category.ls\", &ls{})\n}\n\n\n\nfunc (cmd *ls) Process(ctx context.Context) error {\n\tif err := cmd.ClientFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn cmd.OutputFlag.Process(ctx)\n}\n\nfunc (cmd *ls) Description() string {\n\treturn `List all categories.\n\nExamples:\n govc tags.category.ls\n govc tags.category.ls -json | jq .`\n}\n\ntype lsResult []tags.Category\n\nfunc (r lsResult) Write(w io.Writer) error {\n\tfor _, c := range r {\n\t\tfmt.Fprintln(w, c.Name)\n\t}\n\treturn nil\n}\n\nfunc (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {\n\tc, err := cmd.RestClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tl, err := tags.NewManager(c).GetCategories(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn cmd.WriteResult(lsResult(l))\n}\n\nfunc (cmd *ls) Register(ctx context.Context, f *flag.FlagSet) ", "output": "{\n\tcmd.ClientFlag, ctx = flags.NewClientFlag(ctx)\n\tcmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)\n\tcmd.ClientFlag.Register(ctx, f)\n\tcmd.OutputFlag.Register(ctx, f)\n}"} {"input": "package common\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/axgle/mahonia\"\n\t\"github.com/saintfish/chardet\"\n)\n\n\n\n\n\nfunc QuickestURL(index int, url string) int {\n\t_, err := http.Get(url)\n\tif err != nil {\n\t\treturn -1\n\t}\n\treturn index\n}\n\n\nfunc DetectBody(body []byte) string {\n\tvar bodyString string\n\tdetector := chardet.NewTextDetector()\n\tresult, err := detector.DetectBest(body)\n\tif err != nil {\n\t\treturn string(body)\n\t}\n\tif strings.Contains(strings.ToLower(result.Charset), \"utf\") {\n\t\tbodyString = string(body)\n\t} else {\n\t\tbodyString = mahonia.NewDecoder(\"gbk\").ConvertString(string(body))\n\t}\n\treturn bodyString\n}\n\n\nfunc StringInSlice(domain string, list []string) bool {\n\tfor _, eachDomain := range list {\n\t\tif domain == eachDomain {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc ReturnDomain(currentURL string) string {\n\turlParse, _ := url.Parse(currentURL)\n\tdomain := urlParse.Host\n\treturn domain\n}\n\nfunc RequestURL(url string) (*http.Response, error) ", "output": "{\n\tclient := &http.Client{}\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Set(\"User-Agent\", GetUserAgent())\n\tresponse, err := client.Do(req)\n\treturn response, err\n}"} {"input": "package datastructures\n\n\ntype Comparable interface {\n\tCompare(Comparable) int\n}\n\n\ntype Comparables []Comparable\n\n\nfunc (cs Comparables) Len() int {\n\treturn len(cs)\n}\n\n\n\n\n\nfunc (cs *Comparables) Shift() Comparable {\n\tif len(*cs) == 0 {\n\t\treturn nil\n\t}\n\n\tf := (*cs)[0]\n\t*cs = (*cs)[1:]\n\treturn f\n}\n\n\nfunc (cs Comparables) Swap(i, j int) {\n\tcs[i], cs[j] = cs[j], cs[i]\n}\n\n\ntype IntComparable int\n\n\nfunc (ic IntComparable) Compare(i Comparable) int {\n\tother, ok := i.(IntComparable)\n\n\tif !ok {\n\t\tpanic(\"param should be an intComparable\")\n\t}\n\n\tif int(ic) == int(other) {\n\t\treturn 0\n\t} else if int(ic) < int(other) {\n\t\treturn -1\n\t} else {\n\t\treturn 1\n\t}\n}\n\nfunc (cs Comparables) Less(i, j int) bool ", "output": "{\n\tif cs[i].Compare(cs[j]) < 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}"} {"input": "package aggregators\n\nimport (\n\t\"github.com/poy/ledger/transaction\"\n)\n\nfunc init() {\n\tAddToStore(\"sum\", NewSum())\n}\n\n\n\nfunc NewSum() AggregatorFunc ", "output": "{\n\treturn AggregatorFunc(func(accounts []*transaction.Account) string {\n\t\tvar result transaction.Money\n\t\tfor _, a := range accounts {\n\t\t\tresult += a.Value\n\t\t}\n\t\treturn result.String()\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promhttp\"\n)\n\nfunc main() {\n\tdojoRestarts, err := startCounterVec(\"dojo_restarts_total\", \"Number of restarts\", []string{\"service\"})\n\tif err != nil {\n\t\tlog.Printf(\"start: %v\", err)\n\t\treturn\n\t}\n\n\tgo startService(\"one\", dojoRestarts)\n\n\tgo startService(\"two\", dojoRestarts)\n\n\thttp.Handle(\"/metrics\", promhttp.Handler())\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc startCounterVec(name, help string, labels []string) (*prometheus.CounterVec, error) {\n\tcv := prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tName: name,\n\t\t\tHelp: help,\n\t\t},\n\t\tlabels,\n\t)\n\n\terr := prometheus.Register(cv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cv, nil\n}\n\nfunc startService(name string, restarts *prometheus.CounterVec) {\n\tfor {\n\t\tdone := make(chan struct{})\n\t\tt := time.NewTimer(1 * time.Minute)\n\n\t\tgo func() {\n\t\t\t<-t.C\n\t\t\tclose(done)\n\t\t}()\n\n\t\tconst maxSleep = 1000000000\n\t\trestarts.WithLabelValues(name).Inc()\n\t\tfor {\n\t\t\trs := randomNumber(maxSleep)\n\t\t\ttime.Sleep(time.Duration(rs))\n\t\t}\n\n\t\tprintln(\"restart \" + name)\n\t}\n}\n\n\n\nfunc randomNumber(max int) int ", "output": "{\n\trand.Seed(time.Now().UnixNano())\n\treturn rand.Intn(max)\n}"} {"input": "package main\n\ntype Element interface {\n}\n\ntype Vector struct {\n\tnelem int;\n\telem []Element;\n}\n\n\n\nfunc (v *Vector) At(i int) Element {\n\treturn v.elem[i];\n}\n\nfunc (v *Vector) Insert(e Element) {\n\tv.elem[v.nelem] = e;\n\tv.nelem++;\n}\n\nfunc main() {\n\ttype I struct { val int; };\n\ti0 := new(I); i0.val = 0;\n\ti1 := new(I); i1.val = 11;\n\ti2 := new(I); i2.val = 222;\n\ti3 := new(I); i3.val = 3333;\n\ti4 := new(I); i4.val = 44444;\n\tv := New();\n\tprint(\"hi\\n\");\n\tv.Insert(i4);\n\tv.Insert(i3);\n\tv.Insert(i2);\n\tv.Insert(i1);\n\tv.Insert(i0);\n\tfor i := 0; i < v.nelem; i++ {\n\t\tvar x *I;\n\t\tx = v.At(i).(*I);\n\t\tprint(i, \" \", x.val, \"\\n\"); \n\t}\n\tfor i := 0; i < v.nelem; i++ {\n\t\tprint(i, \" \", v.At(i).(*I).val, \"\\n\");\n\t}\n}\n\nfunc New() *Vector ", "output": "{\n\tv := new(Vector);\n\tv.nelem = 0;\n\tv.elem = make([]Element, 10);\n\treturn v;\n}"} {"input": "package events\n\nimport (\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/gravitational/teleport/lib/session\"\n)\n\n\n\ntype DiscardAuditLog struct {\n}\n\nfunc (d *DiscardAuditLog) Close() error {\n\treturn nil\n}\n\nfunc (d *DiscardAuditLog) EmitAuditEvent(eventType string, fields EventFields) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionChunk(namespace string, sid session.ID, reader io.Reader) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionSlice(SessionSlice) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\nfunc (d *DiscardAuditLog) GetSessionEvents(namespace string, sid session.ID, after int) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\n\nfunc (d *DiscardAuditLog) SearchSessionEvents(fromUTC time.Time, toUTC time.Time) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\n\n\n\n\ntype discardSessionLogger struct {\n}\n\nfunc (d *discardSessionLogger) LogEvent(fields EventFields) {\n\treturn\n}\n\nfunc (d *discardSessionLogger) Close() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) Finalize() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) WriteChunk(chunk *SessionChunk) (written int, err error) {\n\treturn 0, nil\n}\n\nfunc (d *DiscardAuditLog) SearchEvents(fromUTC, toUTC time.Time, query string) ([]EventFields, error) ", "output": "{\n\treturn make([]EventFields, 0), nil\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSBatchJobDefinition_NodeRangeProperty struct {\n\n\tContainer *AWSBatchJobDefinition_ContainerProperties `json:\"Container,omitempty\"`\n\n\tTargetNodes string `json:\"TargetNodes,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) AWSCloudFormationType() string {\n\treturn \"AWS::Batch::JobDefinition.NodeRangeProperty\"\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\n\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) Metadata() map[string]interface{} ", "output": "{\n\treturn r._metadata\n}"} {"input": "package http\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n)\n\n\n\nfunc (h *handler) addWebPushSubscription(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tdefer r.Body.Close()\n\n\tvar sub json.RawMessage\n\tif err := json.NewDecoder(r.Body).Decode(&sub); err != nil {\n\t\th.respondErr(w, errBadRequest)\n\t\treturn\n\t}\n\n\terr := h.svc.AddWebPushSubscription(r.Context(), sub)\n\tif err != nil {\n\t\th.respondErr(w, err)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusNoContent)\n}"} {"input": "package schedule\n\nimport (\n\t\"context\"\n\t\"os\"\n)\n\nfunc (c *Client) GetOnCalls(context context.Context, request *GetOnCallsRequest) (*GetOnCallsResult, error) {\n\tresult := &GetOnCallsResult{}\n\terr := c.client.Exec(context, request, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) GetNextOnCall(context context.Context, request *GetNextOnCallsRequest) (*GetNextOnCallsResult, error) {\n\tresult := &GetNextOnCallsResult{}\n\terr := c.client.Exec(context, request, result)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}\n\n\n\nfunc (c *Client) ExportOnCallUser(context context.Context, request *ExportOnCallUserRequest) (*os.File, error) ", "output": "{\n\tresult := &exportOncallUserResult{}\n\n\tfile, err := os.Create(request.ExportedFilePath + request.getFileName())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer file.Close()\n\n\terr = c.client.Exec(context, request, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = file.Write(result.FileContent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn file, nil\n}"} {"input": "package main\n\nfunc main() {\n\tpoison()\n\ttest()\n}\n\n\nfunc poison() {\n\tvar large [256]uintptr\n\tfor i := range large {\n\t\tlarge[i] = 1\n\t}\n\tuse(large[:])\n}\n\n\nfunc test() {\n\ta := 2\n\tx := &a\n\tif x != compare(&x) {\n\t\tpanic(\"not possible\")\n\t}\n}\n\n\nfunc compare(x **int) *int {\n\tvar y *int\n\tif x == &y {\n\t\tpanic(\"not possible\")\n\t}\n\tgrow()\n\tif x == &y {\n\t\tpanic(\"not possible\")\n\t}\n\treturn *x\n}\n\n\n\n\n\nfunc use(_ []uintptr) { }\n\nfunc grow() ", "output": "{\n\tvar large [1 << 16]uintptr\n\tuse(large[:])\n}"} {"input": "package blobstore\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync\"\n)\n\ntype localStore struct {\n\tsync.Mutex\n\troot string\n}\n\n\n\n\nfunc (ls *localStore) blobDirname(digest string) string {\n\treturn filepath.Join(ls.root, \"blobs\", digest)\n}\n\nfunc (ls *localStore) blobFilename(digest string) string {\n\treturn filepath.Join(ls.blobDirname(digest), \"blob\")\n}\n\nfunc (ls *localStore) blobInfoFilename(digest string) string {\n\treturn filepath.Join(ls.blobDirname(digest), \"info.json\")\n}\n\n\n\nfunc newLocalStore(root string) (*localStore, error) {\n\tls := &localStore{root: root}\n\n\tblobsDirname := ls.blobDirname(\"\")\n\tif err := os.MkdirAll(blobsDirname, os.FileMode(0755)); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create local blob store directory %q: %s\", blobsDirname, err)\n\t}\n\n\treturn ls, nil\n}\n\nfunc NewLocalStore(root string) (Store, error) ", "output": "{\n\treturn newLocalStore(root)\n}"} {"input": "package popcount\n\n\nvar pc [256]byte\n\nfunc init() {\n\tfor i := range pc {\n\t\tpc[i] = pc[i/2] + byte(i&1)\n\t}\n}\n\n\nfunc PopCount(x uint64) int {\n\treturn int(pc[byte(x>>(0*8))] +\n\t\tpc[byte(x>>(1*8))] +\n\t\tpc[byte(x>>(2*8))] +\n\t\tpc[byte(x>>(3*8))] +\n\t\tpc[byte(x>>(4*8))] +\n\t\tpc[byte(x>>(5*8))] +\n\t\tpc[byte(x>>(6*8))] +\n\t\tpc[byte(x>>(7*8))])\n}\n\n\n\nfunc PopCount2(x uint64) int ", "output": "{\n\tvar sum byte\n\tfor i := uint(0); i < 8; i++ {\n\t\tsum += pc[byte(x>>(i*8))]\n\t}\n\treturn int(sum)\n}"} {"input": "package trust\n\nimport (\n\t\"strings\"\n)\n\nconst (\n\tAny Attribute = 0\n\tAuthoritative Attribute = 1 << iota\n\tCore\n\tRootCA\n)\n\nvar attributeString = map[Attribute]string{\n\tAny: \"any\",\n\tAuthoritative: \"authoritative\",\n\tCore: \"core\",\n\tRootCA: \"root_ca\",\n}\n\n\ntype Attribute int\n\n\n\n\nfunc (a Attribute) String() string {\n\tparts := make([]string, 0, 3)\n\tfor _, attr := range []Attribute{Authoritative, Core, RootCA} {\n\t\tif Attribute(a)&attr != 0 {\n\t\t\tparts = append(parts, attributeString[attr])\n\t\t}\n\t}\n\tif len(parts) == 0 {\n\t\treturn attributeString[Any]\n\t}\n\treturn strings.Join(parts, \"|\")\n}\n\nfunc (a Attribute) IsSubset(super Attribute) bool ", "output": "{\n\treturn (a & super) == a\n}"} {"input": "package fields\n\nimport (\n\t\"io\"\n\t\"strconv\"\n)\n\ntype IntField struct {\n\t*BaseField\n\tstep int\n\tmin *int\n\tmax *int\n}\n\nfunc (i *IntField) Configure(tagMap map[string]string) error {\n\tstep := 1\n\tif str, ok := tagMap[\"step\"]; ok {\n\t\tvar err error\n\t\tstep64, err := strconv.ParseInt(str, 10, 64)\n\t\tstep = int(step64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif str, ok := tagMap[\"min\"]; ok {\n\t\tmin64, err := strconv.ParseInt(str, 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmin := int(min64)\n\t\ti.min = &min\n\t}\n\tif str, ok := tagMap[\"max\"]; ok {\n\t\tmax64, err := strconv.ParseInt(str, 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmax := int(max64)\n\t\ti.max = &max\n\t}\n\ti.step = step\n\treturn nil\n}\n\n\nfunc (i *IntField) Validate(val string) (interface{}, error) {\n\tnum, err := strconv.ParseInt(val, 10, 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn num, nil\n}\n\nfunc (i *IntField) Render(w io.Writer, val interface{}, err string, startRow bool) ", "output": "{\n\ti.BaseRender(w, numberTemplate, val, err, startRow, map[string]interface{}{\n\t\t\"step\": i.step,\n\t})\n}"} {"input": "package dtime\n\nimport \"testing\"\n\n\n\nfunc TestMaxTime(t *testing.T) ", "output": "{\n\tst := []struct {\n\t\tname string\n\t\tarr []int\n\t\texp string\n\t}{\n\t\t{\"all 0s\", []int{0, 0, 0, 0}, \"00:00\"},\n\t\t{\"testcase1\", []int{1, 2, 3, 4}, \"23:41\"},\n\t\t{\"testcase2\", []int{3, 3, 3, 3}, \"\"},\n\t}\n\tfor _, tt := range st {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tout := maxTime(tt.arr)\n\t\t\tif out != tt.exp {\n\t\t\t\tt.Fatalf(\"with input arr:%v wanted %s but got %s\", tt.arr, tt.exp, out)\n\t\t\t}\n\t\t\tt.Log(\"pass\")\n\t\t})\n\t}\n}"} {"input": "package nodes\n\nimport (\n\t\"github.com/gonum/graph\"\n\n\tappsv1 \"github.com/openshift/api/apps/v1\"\n\tosgraph \"github.com/openshift/oc/pkg/helpers/graph/genericgraph\"\n\tkubegraph \"github.com/openshift/oc/pkg/helpers/graph/kubegraph/nodes\"\n)\n\n\n\n\nfunc FindOrCreateSyntheticDeploymentConfigNode(g osgraph.MutableUniqueGraph, dc *appsv1.DeploymentConfig) *DeploymentConfigNode {\n\treturn osgraph.EnsureUnique(\n\t\tg,\n\t\tDeploymentConfigNodeName(dc),\n\t\tfunc(node osgraph.Node) graph.Node {\n\t\t\treturn &DeploymentConfigNode{Node: node, DeploymentConfig: dc, IsFound: false}\n\t\t},\n\t).(*DeploymentConfigNode)\n}\n\nfunc EnsureDeploymentConfigNode(g osgraph.MutableUniqueGraph, dc *appsv1.DeploymentConfig) *DeploymentConfigNode ", "output": "{\n\tdcName := DeploymentConfigNodeName(dc)\n\tdcNode := osgraph.EnsureUnique(\n\t\tg,\n\t\tdcName,\n\t\tfunc(node osgraph.Node) graph.Node {\n\t\t\treturn &DeploymentConfigNode{Node: node, DeploymentConfig: dc, IsFound: true}\n\t\t},\n\t).(*DeploymentConfigNode)\n\n\tif dc.Spec.Template != nil {\n\t\tpodTemplateSpecNode := kubegraph.EnsurePodTemplateSpecNode(g, dc.Spec.Template, dc.Namespace, dcName)\n\t\tg.AddEdge(dcNode, podTemplateSpecNode, osgraph.ContainsEdgeKind)\n\t}\n\n\treturn dcNode\n}"} {"input": "package cloudformation\n\n\n\ntype AWSKinesisAnalyticsApplication_InputParallelism struct {\n\n\tCount int `json:\"Count,omitempty\"`\n}\n\n\n\n\nfunc (r *AWSKinesisAnalyticsApplication_InputParallelism) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::KinesisAnalytics::Application.InputParallelism\"\n}"} {"input": "package mocks\n\nimport (\n\tcli \"github.com/stackanetes/kubernetes-entrypoint/client\"\n\tv1batch \"k8s.io/client-go/1.5/kubernetes/typed/batch/v1\"\n\tv1core \"k8s.io/client-go/1.5/kubernetes/typed/core/v1\"\n\tv1beta1extensions \"k8s.io/client-go/1.5/kubernetes/typed/extensions/v1beta1\"\n)\n\ntype Client struct {\n\tv1core.PodInterface\n\tv1core.ServiceInterface\n\tv1beta1extensions.DaemonSetInterface\n\tv1core.EndpointsInterface\n\tv1batch.JobInterface\n}\n\nfunc (c Client) Pods(namespace string) v1core.PodInterface {\n\treturn c.PodInterface\n}\n\n\n\nfunc (c Client) DaemonSets(namespace string) v1beta1extensions.DaemonSetInterface {\n\treturn c.DaemonSetInterface\n}\n\nfunc (c Client) Endpoints(namespace string) v1core.EndpointsInterface {\n\treturn c.EndpointsInterface\n}\nfunc (c Client) Jobs(namespace string) v1batch.JobInterface {\n\treturn c.JobInterface\n}\n\nfunc NewClient() cli.ClientInterface {\n\treturn Client{\n\t\tNewPClient(),\n\t\tNewSClient(),\n\t\tNewDSClient(),\n\t\tNewEClient(),\n\t\tNewJClient(),\n\t}\n}\n\nfunc (c Client) Services(namespace string) v1core.ServiceInterface ", "output": "{\n\treturn c.ServiceInterface\n}"} {"input": "package loader\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestAnchorMerger(t *testing.T) ", "output": "{\n\tin := []byte(`---\nvars: &v\n env: qa\ndeploy:\n env: live`)\n\texpect := `{\"deploy\":{\"env\":\"live\"},\"vars\":{\"env\":\"qa\"}}`\n\n\tif err := ioutil.WriteFile(\"/tmp/test\", in, 0644); err != nil {\n\t\tt.Error(\"Error file not create\")\n\t\tt.Fail()\n\t}\n\n\tdefer os.Remove(\"/tmp/test\")\n\n\tif g, err := LoadFile(\"/tmp/test\"); err != nil {\n\t\tt.Errorf(\"%v\\n\", err)\n\t\tt.Fail()\n\t} else {\n\t\tif g.String() != expect {\n\t\t\tt.Errorf(\"%s != %s\", g.String(), expect)\n\t\t\tt.Fail()\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"reflect\"\n\n\t\"github.com/mkromkamp/BeaconD/sinks\"\n)\n\nfunc TestIsLogTags(t *testing.T) {\n\tfor _, tag := range logTags {\n\t\tif !isLogTag(tag) {\n\t\t\tt.Errorf(\"%s should be a tag\", tag)\n\t\t}\n\t}\n}\n\n\n\nfunc TestLogLineFromDTO(t *testing.T) ", "output": "{\n\tlogDTO := logDTO{\n\t\tTimestamp: time.Now().UTC().Format(time.RFC3339),\n\t\tData: make(map[string]string),\n\t}\n\n\texpectedLogLine := sinks.LogLine{\n\t\tTimestamp: logDTO.Timestamp,\n\t\tData: logDTO.Data,\n\t}\n\n\tactualLogLine := logDTO.NewLogLine()\n\n\tif !reflect.DeepEqual(expectedLogLine, actualLogLine) {\n\t\tt.Errorf(\"Expected LogLine: %v but got %v\", expectedLogLine, actualLogLine)\n\t}\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\n\t\"launchpad.net/juju-core/state\"\n\t\"launchpad.net/juju-core/state/api/params\"\n)\n\n\ntype Remover struct {\n\tst state.EntityFinder\n\tcallEnsureDead bool\n\tgetCanModify GetAuthFunc\n}\n\n\n\n\n\n\n\nfunc (r *Remover) removeEntity(tag string) error {\n\tentity, err := r.st.FindEntity(tag)\n\tif err != nil {\n\t\treturn err\n\t}\n\tremover, ok := entity.(interface {\n\t\tstate.Lifer\n\t\tstate.Remover\n\t\tstate.EnsureDeader\n\t})\n\tif !ok {\n\t\treturn NotSupportedError(tag, \"removal\")\n\t}\n\tif life := remover.Life(); life == state.Alive {\n\t\treturn fmt.Errorf(\"cannot remove entity %q: still alive\", tag)\n\t}\n\tif r.callEnsureDead {\n\t\tif err := remover.EnsureDead(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn remover.Remove()\n}\n\n\n\nfunc (r *Remover) Remove(args params.Entities) (params.ErrorResults, error) {\n\tresult := params.ErrorResults{\n\t\tResults: make([]params.ErrorResult, len(args.Entities)),\n\t}\n\tif len(args.Entities) == 0 {\n\t\treturn result, nil\n\t}\n\tcanModify, err := r.getCanModify()\n\tif err != nil {\n\t\treturn params.ErrorResults{}, err\n\t}\n\tfor i, entity := range args.Entities {\n\t\terr := ErrPerm\n\t\tif canModify(entity.Tag) {\n\t\t\terr = r.removeEntity(entity.Tag)\n\t\t}\n\t\tresult.Results[i].Error = ServerError(err)\n\t}\n\treturn result, nil\n}\n\nfunc NewRemover(st state.EntityFinder, callEnsureDead bool, getCanModify GetAuthFunc) *Remover ", "output": "{\n\treturn &Remover{\n\t\tst: st,\n\t\tcallEnsureDead: callEnsureDead,\n\t\tgetCanModify: getCanModify,\n\t}\n}"} {"input": "package pool\n\nimport (\n\t\"fmt\"\n\t\"net\"\n)\n\nconst (\n\t_net = \"udp4\" \n)\n\nfunc createUDPConnection(address string) (*net.UDPConn, error) {\n\taddr, err := net.ResolveUDPAddr(_net, address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconn, err := net.DialUDP(_net, nil, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn conn, nil\n}\n\nfunc worker(id int, address string, done chan bool, buffers <-chan []byte) {\n\n\tconn, err := createUDPConnection(address)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\terr := conn.Close()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}()\n\n\tfor buffer := range buffers {\n\t\t_, err := conn.Write(buffer)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tdone <- true\n}\n\ntype UDPPool struct {\n\tbuffers chan []byte\n\tdone chan bool\n}\n\n\nfunc NewUDPPool(address string, workerNumber int) *UDPPool {\n\tbuffers := make(chan []byte, workerNumber)\n\tdone := make(chan bool)\n\n\tfor wid := 1; wid < workerNumber; wid++ {\n\t\tgo worker(wid, address, done, buffers)\n\t}\n\treturn &UDPPool{buffers, done}\n}\n\nfunc (p *UDPPool) Fire(buffer []byte) {\n\tp.buffers <- buffer\n}\n\n\n\nfunc (p *UDPPool) Close() ", "output": "{\n\tclose(p.buffers)\n}"} {"input": "package field\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype Path struct {\n\tname string \n\tindex string \n\tparent *Path \n}\n\n\nfunc NewPath(name string, moreNames ...string) *Path {\n\tr := &Path{name: name, parent: nil}\n\tfor _, anotherName := range moreNames {\n\t\tr = &Path{name: anotherName, parent: r}\n\t}\n\treturn r\n}\n\n\n\n\n\nfunc (p *Path) Child(name string, moreNames ...string) *Path {\n\tr := NewPath(name, moreNames...)\n\tr.Root().parent = p\n\treturn r\n}\n\n\n\nfunc (p *Path) Index(index int) *Path {\n\treturn &Path{index: strconv.Itoa(index), parent: p}\n}\n\n\n\nfunc (p *Path) Key(key string) *Path {\n\treturn &Path{index: key, parent: p}\n}\n\n\nfunc (p *Path) String() string {\n\tif p == nil {\n\t\treturn \"\"\n\t}\n\telems := []*Path{}\n\tfor ; p != nil; p = p.parent {\n\t\telems = append(elems, p)\n\t}\n\n\tbuf := bytes.NewBuffer(nil)\n\tfor i := range elems {\n\t\tp := elems[len(elems)-1-i]\n\t\tif p.parent != nil && len(p.name) > 0 {\n\t\t\tbuf.WriteString(\".\")\n\t\t}\n\t\tif len(p.name) > 0 {\n\t\t\tbuf.WriteString(p.name)\n\t\t} else {\n\t\t\tfmt.Fprintf(buf, \"[%s]\", p.index)\n\t\t}\n\t}\n\treturn buf.String()\n}\n\nfunc (p *Path) Root() *Path ", "output": "{\n\tfor ; p.parent != nil; p = p.parent {\n\t}\n\treturn p\n}"} {"input": "package iso20022\n\n\ntype ChargeType1 struct {\n\n\tStructured *ChargeType6Code `xml:\"Strd\"`\n\n\tAdditionalInformation *Max350Text `xml:\"AddtlInf,omitempty\"`\n}\n\nfunc (c *ChargeType1) SetStructured(value string) {\n\tc.Structured = (*ChargeType6Code)(&value)\n}\n\n\n\nfunc (c *ChargeType1) SetAdditionalInformation(value string) ", "output": "{\n\tc.AdditionalInformation = (*Max350Text)(&value)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst version = 74\n\nvar cmdVersion = &Command{\n\tName: \"version\",\n\tShort: \"show version info\",\n\tLong: `\n\nDisplays the version of godep as well as the target OS, architecture and go runtime version.\n`,\n\tRun: runVersion,\n}\n\nfunc versionString() string {\n\treturn fmt.Sprintf(\"godep v%d (%s/%s/%s)\", version, runtime.GOOS, runtime.GOARCH, runtime.Version())\n}\n\n\n\nfunc GoVersionFields(c rune) bool {\n\treturn c == 'g' || c == 'o' || c == '.'\n}\n\n\n\n\nfunc isSameOrNewer(base, check string) bool {\n\tif base == check {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(check, \"devel-\") {\n\t\treturn true\n\t}\n\tbp := strings.FieldsFunc(base, GoVersionFields)\n\tcp := strings.FieldsFunc(check, GoVersionFields)\n\tif len(bp) < 2 || len(cp) < 2 {\n\t\tlog.Fatalf(\"Error comparing %s to %s\\n\", base, check)\n\t}\n\tif bp[0] == cp[0] { \n\t\tbm, err := strconv.Atoi(bp[1])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tcm, err := strconv.Atoi(cp[1])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn cm >= bm\n\t}\n\treturn false\n}\n\nfunc runVersion(cmd *Command, args []string) ", "output": "{\n\tfmt.Printf(\"%s\\n\", versionString())\n}"} {"input": "package sql\n\nimport (\n\t\"github.com/cockroachdb/cockroach/sql/parser\"\n\t\"github.com/cockroachdb/cockroach/sql/privilege\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *planner) Revoke(n *parser.Revoke) (planNode, error) ", "output": "{\n\tdescriptor, err := p.getDescriptorFromTargetList(n.Targets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := p.checkPrivilege(descriptor, privilege.GRANT); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, grantee := range n.Grantees {\n\t\tdescriptor.GetPrivileges().Revoke(grantee, n.Privileges)\n\t}\n\n\tif err := descriptor.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdescKey := MakeDescMetadataKey(descriptor.GetID())\n\tp.txn.SetSystemDBTrigger()\n\tif err := p.txn.Put(descKey, descriptor); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &valuesNode{}, nil\n}"} {"input": "package fx\n\nimport (\n\t\"go.uber.org/fx/fxevent\"\n)\n\n\n\ntype logBuffer struct {\n\tevents []fxevent.Event\n\tlogger fxevent.Logger\n}\n\n\nfunc (l *logBuffer) LogEvent(event fxevent.Event) {\n\tif l.logger == nil {\n\t\tl.events = append(l.events, event)\n\t} else {\n\t\tl.logger.LogEvent(event)\n\t}\n}\n\n\n\n\nfunc (l *logBuffer) Connect(logger fxevent.Logger) ", "output": "{\n\tl.logger = logger\n\tfor _, e := range l.events {\n\t\tlogger.LogEvent(e)\n\t}\n\tl.events = nil\n}"} {"input": "package gochimp\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype APIError struct {\n\tStatus string `json:\"status\"`\n\tCode int `json:\"code\"`\n\tName string `json:\"name\"`\n\tErr string `json:\"error\"`\n}\n\nfunc (e APIError) Error() string {\n\treturn fmt.Sprintf(\"%v: %v\", e.Code, e.Err)\n}\n\nfunc chimpErrorCheck(body []byte) error {\n\tvar e APIError\n\tjson.Unmarshal(body, &e)\n\tif e.Err != \"\" || e.Code != 0 {\n\t\treturn e\n\t}\n\treturn nil\n}\n\n\ntype APITime struct {\n\ttime.Time\n}\n\n\n\n\nconst APITimeFormat = \"2006-01-02 15:04:05\"\n\nfunc apiTime(t interface{}) interface{} {\n\tswitch ti := t.(type) {\n\tcase time.Time:\n\t\treturn ti.Format(APITimeFormat)\n\tcase string:\n\t\treturn ti\n\t}\n\treturn t\n}\n\nfunc (t *APITime) UnmarshalJSON(data []byte) (err error) ", "output": "{\n\ts := string(data)\n\tl := len(s)\n\tswitch {\n\tcase l == 12:\n\t\tt.Time, err = time.Parse(`\"2006-01-02\"`, s)\n\tcase l == 21:\n\t\tt.Time, err = time.Parse(`\"2006-01-02 15:04:05\"`, s)\n\tcase l == 27:\n\t\tt.Time, err = time.Parse(`\"2006-01-02 15:04:05.00000\"`, s)\n\tcase l == 9:\n\t\tt.Time, err = time.Parse(`\"2006-01\"`, s)\n\t}\n\treturn\n}"} {"input": "package main\n\nimport \"strings\"\n\ntype code_section interface {\n\tCode() bool\n}\n\ntype para string\n\nfunc (para) Code() bool {\n\treturn false\n}\n\ntype code string\n\nfunc (code) Code() bool {\n\treturn true\n}\n\ntype Article struct {\n\tTitle string\n\tIntro []para\n\tGoCode, ReflectCode []code_section\n\tUses, Tags []string\n\tslug string\n}\n\nfunc (a *Article) Slug() string {\n\tif a.slug == \"\" {\n\t\ta.slug = strings.ToLower(strings.Replace(a.Title, \" \", \"-\", -1))\n\t}\n\treturn a.slug\n}\n\ntype Articles []*Article\n\n\n\nfunc (a Articles) Len() int {\n\treturn len(a)\n}\n\nfunc (a Articles) Swap(i, j int) {\n\ta[j], a[i] = a[i], a[j]\n}\n\nfunc (a Articles) Less(i, j int) bool {\n\treturn a[i].Title < a[j].Title\n}\n\nfunc (a *Articles) Add(ao *Article) ", "output": "{\n\t*a = append(*a, ao)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSGameLiftBuild_S3Location struct {\n\n\tBucket string `json:\"Bucket,omitempty\"`\n\n\tKey string `json:\"Key,omitempty\"`\n\n\tRoleArn string `json:\"RoleArn,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSGameLiftBuild_S3Location) AWSCloudFormationType() string {\n\treturn \"AWS::GameLift::Build.S3Location\"\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\n\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSGameLiftBuild_S3Location) SetDependsOn(dependencies []string) ", "output": "{\n\tr._dependsOn = dependencies\n}"} {"input": "package workshop\n\nimport (\n\t\"math\"\n)\n\n\ntype Shape interface {\n\tarea()\n\tcircumference()\n\tvolume()\n}\n\n\ntype Circle struct {\n\tradius float64\n\tPI float64\n}\n\nfunc (circle *Circle) area() float64 {\n\treturn circle.PI * math.Pow(circle.radius, 2)\n}\n\n\n\n\ntype Square struct {\n\tside float64\n}\n\nfunc (square *Square) area() float64 {\n\treturn math.Pow(square.side, 2)\n}\n\ntype Sphere struct {\n\tPI float64\n\tradius float64\n}\n\nfunc (sphere *Sphere) volume() float64 {\n\treturn (4 / 3) * sphere.PI * math.Pow(sphere.radius, 3)\n}\n\n\ntype Cube struct {\n\tside float64\n}\n\nfunc (cube *Cube) volume() float64 {\n\treturn math.Pow(cube.side, 3)\n}\n\nfunc (square *Square) volume() float64 {\n\treturn math.Pow(square.side, 3)\n}\n\n\ntype Rectangle struct {\n\theight int\n\twidth int\n}\n\nfunc (rectangle *Rectangle) area() int {\n\treturn rectangle.height * rectangle.width\n}\n\nfunc interfaces() {\n\tcircle := Circle{radius: 5.5, PI: math.Pi}\n\tareaOfCircle := circle.area()\n\n\tassert(areaOfCircle == 55)\n\tassert(circle.circumference() == 88)\n\n\tvar square = Square{5}\n\tassert(square.area() == 36)\n\n\tcube := new(Cube)\n\tassert(cube.volume() == 8)\n\n\tvar rectangle = Rectangle{width: 4, height: 5}\n\tassert(rectangle.area() == 2)\n}\n\nfunc (circle *Circle) circumference() float64 ", "output": "{\n\treturn 2 * circle.PI * circle.radius\n}"} {"input": "package common\n\nimport (\n\tsteno \"github.com/cloudfoundry/gosteno\"\n\t\"os\"\n)\n\n\n\nfunc SetupSteno(logConfig *LogConfig) ", "output": "{\n\tlevel, err := steno.GetLogLevel(logConfig.Level)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsinks := make([]steno.Sink, 0)\n\tif logConfig.File != \"\" {\n\t\tsinks = append(sinks, steno.NewFileSink(logConfig.File))\n\t} else {\n\t\tsinks = append(sinks, steno.NewIOSink(os.Stdout))\n\t}\n\tif logConfig.Syslog != \"\" {\n\t\tsinks = append(sinks, steno.NewSyslogSink(logConfig.Syslog))\n\t}\n\n\tstenoConfig := &steno.Config{\n\t\tSinks: sinks,\n\t\tCodec: steno.NewJsonCodec(),\n\t\tLevel: level,\n\t}\n\n\tsteno.Init(stenoConfig)\n}"} {"input": "package github\n\nimport (\n\t\"context\"\n\t\"fmt\"\n)\n\n\n\n\n\ntype GitignoresService service\n\n\ntype Gitignore struct {\n\tName *string `json:\"name,omitempty\"`\n\tSource *string `json:\"source,omitempty\"`\n}\n\nfunc (g Gitignore) String() string {\n\treturn Stringify(g)\n}\n\n\n\n\n\n\n\n\n\nfunc (s *GitignoresService) Get(ctx context.Context, name string) (*Gitignore, *Response, error) {\n\tu := fmt.Sprintf(\"gitignore/templates/%v\", name)\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tgitignore := new(Gitignore)\n\tresp, err := s.client.Do(ctx, req, gitignore)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn gitignore, resp, nil\n}\n\nfunc (s *GitignoresService) List(ctx context.Context) ([]string, *Response, error) ", "output": "{\n\treq, err := s.client.NewRequest(\"GET\", \"gitignore/templates\", nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar availableTemplates []string\n\tresp, err := s.client.Do(ctx, req, &availableTemplates)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn availableTemplates, resp, nil\n}"} {"input": "package conf\n\nimport (\n\t\"github.com/sirupsen/logrus\"\n)\n\n\ntype Logger struct {\n\tLevel string `yaml:\"level\" default:\"info\"`\n\tFormat string `yaml:\"format\" default:\"text\"`\n}\n\n\n\n\n\n\n\nfunc SetLogLevel(lvl string) {\n\tl, err := logrus.ParseLevel(lvl)\n\tif err != nil {\n\t\tlogrus.WithField(\"provided\", lvl).Warn(\"Invalid log level, fallback to Info level\")\n\t\tlogrus.SetLevel(logrus.InfoLevel)\n\t} else {\n\t\tlogrus.SetLevel(l)\n\t}\n}\n\n\nfunc SetFormatter(format string) {\n\tswitch format {\n\tcase \"json\":\n\t\tlogrus.SetFormatter(&logrus.JSONFormatter{})\n\tcase \"text\":\n\t\tlogrus.SetFormatter(&logrus.TextFormatter{})\n\tdefault:\n\t\tlogrus.SetFormatter(&logrus.TextFormatter{})\n\t}\n}\n\nfunc (c Logger) Configure() ", "output": "{\n\tSetFormatter(c.Format)\n\tSetLogLevel(c.Level)\n}"} {"input": "package router\n\nimport (\n\t\"sync/atomic\"\n\n\t\"github.com/AsynkronIT/protoactor-go/actor\"\n)\n\ntype roundRobinGroupRouter struct {\n\tGroupRouter\n}\n\ntype roundRobinPoolRouter struct {\n\tPoolRouter\n}\n\ntype roundRobinState struct {\n\tindex int32\n\troutees *actor.PIDSet\n\tvalues []actor.PID\n}\n\nfunc (state *roundRobinState) SetRoutees(routees *actor.PIDSet) {\n\tstate.routees = routees\n\tstate.values = routees.Values()\n}\n\nfunc (state *roundRobinState) GetRoutees() *actor.PIDSet {\n\treturn state.routees\n}\n\nfunc (state *roundRobinState) RouteMessage(message interface{}, sender *actor.PID) {\n\tpid := roundRobinRoutee(&state.index, state.values)\n\tpid.Request(message, sender)\n}\n\nfunc NewRoundRobinPool(size int) *actor.Props {\n\treturn actor.FromSpawnFunc(spawner(&roundRobinPoolRouter{PoolRouter{PoolSize: size}}))\n}\n\nfunc NewRoundRobinGroup(routees ...*actor.PID) *actor.Props {\n\treturn actor.FromSpawnFunc(spawner(&roundRobinGroupRouter{GroupRouter{Routees: actor.NewPIDSet(routees...)}}))\n}\n\nfunc (config *roundRobinPoolRouter) CreateRouterState() Interface {\n\treturn &roundRobinState{}\n}\n\n\n\nfunc roundRobinRoutee(index *int32, routees []actor.PID) actor.PID {\n\ti := int(atomic.AddInt32(index, 1))\n\tif i < 0 {\n\t\t*index = 0\n\t\ti = 0\n\t}\n\tmod := len(routees)\n\troutee := routees[i%mod]\n\treturn routee\n}\n\nfunc (config *roundRobinGroupRouter) CreateRouterState() Interface ", "output": "{\n\treturn &roundRobinState{}\n}"} {"input": "package command\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/mitchellh/cli\"\n\t\"github.com/sgeb/go-acd\"\n)\n\ntype VersionCommand struct {\n\tAppName string\n\tRevision string\n\tVersion string\n\tVersionPrerelease string\n\tUi cli.Ui\n}\n\nfunc (c *VersionCommand) Help() string {\n\treturn \"\"\n}\n\nfunc (c *VersionCommand) Run(_ []string) int {\n\tvar versionString bytes.Buffer\n\n\tfmt.Fprintf(&versionString, \"%s v%s\", c.AppName, c.Version)\n\tif c.VersionPrerelease != \"\" {\n\t\tfmt.Fprintf(&versionString, \"-%s\", c.VersionPrerelease)\n\n\t\tif c.Revision != \"\" {\n\t\t\tfmt.Fprintf(&versionString, \" (%s)\", c.Revision)\n\t\t}\n\t}\n\n\tfmt.Fprintln(&versionString, \"\")\n\tfmt.Fprintf(&versionString, \"using go-acd v%s\", acd.LibraryVersion)\n\n\tc.Ui.Output(versionString.String())\n\treturn 0\n\n}\n\n\n\nfunc (c *VersionCommand) Synopsis() string ", "output": "{\n\treturn fmt.Sprintf(\"Prints the %s version\", c.AppName)\n}"} {"input": "package protobuf\n\nimport \"github.com/m3db/m3x/pool\"\n\nconst (\n\tdefaultInitBufferSize = 2880\n\n\tdefaultMaxUnaggregatedMessageSize = 50 * 1024 * 1024\n)\n\n\ntype UnaggregatedOptions interface {\n\tSetBytesPool(value pool.BytesPool) UnaggregatedOptions\n\n\tBytesPool() pool.BytesPool\n\n\tSetInitBufferSize(value int) UnaggregatedOptions\n\n\tInitBufferSize() int\n\n\tSetMaxMessageSize(value int) UnaggregatedOptions\n\n\tMaxMessageSize() int\n}\n\ntype unaggregatedOptions struct {\n\tbytesPool pool.BytesPool\n\tinitBufferSize int\n\tmaxMessageSize int\n}\n\n\nfunc NewUnaggregatedOptions() UnaggregatedOptions {\n\tp := pool.NewBytesPool(nil, nil)\n\tp.Init()\n\treturn &unaggregatedOptions{\n\t\tbytesPool: p,\n\t\tinitBufferSize: defaultInitBufferSize,\n\t\tmaxMessageSize: defaultMaxUnaggregatedMessageSize,\n\t}\n}\n\nfunc (o *unaggregatedOptions) SetBytesPool(value pool.BytesPool) UnaggregatedOptions {\n\topts := *o\n\topts.bytesPool = value\n\treturn &opts\n}\n\nfunc (o *unaggregatedOptions) BytesPool() pool.BytesPool {\n\treturn o.bytesPool\n}\n\nfunc (o *unaggregatedOptions) SetInitBufferSize(value int) UnaggregatedOptions {\n\topts := *o\n\topts.initBufferSize = value\n\treturn &opts\n}\n\nfunc (o *unaggregatedOptions) InitBufferSize() int {\n\treturn o.initBufferSize\n}\n\nfunc (o *unaggregatedOptions) SetMaxMessageSize(value int) UnaggregatedOptions {\n\topts := *o\n\topts.maxMessageSize = value\n\treturn &opts\n}\n\n\n\nfunc (o *unaggregatedOptions) MaxMessageSize() int ", "output": "{\n\treturn o.maxMessageSize\n}"} {"input": "package main\n\nimport (\n\t\"github.com/go-martini/martini\"\n\t\"github.com/martini-contrib/render\"\n)\n\nfunc main() {\n\n\tm := martini.Classic()\n\n\tStaticOptions := martini.StaticOptions{Prefix: \"public\"}\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\n\tm.Use(render.Renderer(render.Options{\n\t\tDirectory: \"templates\", \n\t\tLayout: \"layout\", \n\t\tExtensions: []string{\".tmpl\"}, \n\t\tCharset: \"UTF-8\", \n\t}))\n\n\tm.Get(\"/\", IndexRouter)\n\tm.Get(\"/about\", AboutRoute)\n\tm.Get(\"/contact\", ContactRoute)\n\tm.Get(\"/signin\", SigninRoute)\n\tm.Get(\"/signup\", SignupRoute)\n\n\tm.Run()\n}\n\nfunc IndexRouter(r render.Render) {\n\tr.HTML(200, \"home/index\", nil)\n}\n\n\n\nfunc ContactRoute(r render.Render) {\n\tr.HTML(200, \"home/contact\", nil)\n}\n\nfunc SigninRoute(r render.Render) {\n\tr.HTML(200, \"account/signin\", nil)\n}\n\nfunc SignupRoute(r render.Render) {\n\tr.HTML(200, \"account/signup\", nil)\n}\n\nfunc AboutRoute(r render.Render) ", "output": "{\n\tr.HTML(200, \"home/about\", nil)\n}"} {"input": "package glib\n\n\n\n\n\nimport \"C\"\nimport \"unsafe\"\n\n\n\ntype IActionMap interface {\n\tNative() uintptr\n\n\tLookupAction(actionName string) *Action\n\tAddAction(action IAction)\n\tRemoveAction(actionName string)\n}\n\n\ntype ActionMap struct {\n\t*Object\n}\n\n\n\n\n\nfunc (v *ActionMap) native() *C.GActionMap {\n\tif v == nil || v.GObject == nil {\n\t\treturn nil\n\t}\n\treturn C.toGActionMap(unsafe.Pointer(v.GObject))\n}\n\n\n\nfunc marshalActionMap(p uintptr) (interface{}, error) {\n\tc := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))\n\treturn wrapActionMap(wrapObject(unsafe.Pointer(c))), nil\n}\n\nfunc wrapActionMap(obj *Object) *ActionMap {\n\treturn &ActionMap{obj}\n}\n\n\nfunc (v *ActionMap) LookupAction(actionName string) *Action {\n\tc := C.g_action_map_lookup_action(v.native(), (*C.gchar)(C.CString(actionName)))\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn wrapAction(wrapObject(unsafe.Pointer(c)))\n}\n\n\nfunc (v *ActionMap) AddAction(action IAction) {\n\tC.g_action_map_add_action(v.native(), action.toGAction())\n}\n\n\nfunc (v *ActionMap) RemoveAction(actionName string) {\n\tC.g_action_map_remove_action(v.native(), (*C.gchar)(C.CString(actionName)))\n}\n\nfunc (v *ActionMap) Native() uintptr ", "output": "{\n\treturn uintptr(unsafe.Pointer(v.native()))\n}"} {"input": "package godruid\n\nimport (\n\t\"fmt\"\n\t. \"github.com/smartystreets/goconvey/convey\"\n\t\"testing\"\n)\n\nfunc TestGroupby(t *testing.T) {\n\tConvey(\"TestGroupby\", t, func() {\n\t\tquery := &QueryGroupBy{\n\t\t\tDataSource: \"campaign\",\n\t\t\tIntervals: []string{\"2014-09-01T00:00/2020-01-01T00\"},\n\t\t\tGranularity: GranAll,\n\t\t\tFilter: FilterAnd(FilterJavaScript(\"hour\", \"function(x) { return(x >= 1) }\"), nil),\n\t\t\tLimitSpec: LimitDefault(5),\n\t\t\tDimensions: []DimSpec{\"campaign_id\"},\n\t\t\tAggregations: []Aggregation{AggRawJson(`{ \"type\" : \"count\", \"name\" : \"count\" }`), AggLongSum(\"impressions\", \"impressions\")},\n\t\t\tPostAggregations: []PostAggregation{PostAggArithmetic(\"imp/count\", \"/\", []PostAggregation{\n\t\t\t\tPostAggFieldAccessor(\"impressions\"),\n\t\t\t\tPostAggRawJson(`{ \"type\" : \"fieldAccess\", \"fieldName\" : \"count\" }`)})},\n\t\t}\n\t\tclient := Client{\n\t\t\tUrl: \"http://192.168.10.60:8009\",\n\t\t\tDebug: true,\n\t\t}\n\n\t\terr := client.Query(query)\n\t\tfmt.Println(\"requst\", client.LastRequest)\n\t\tSo(err, ShouldEqual, nil)\n\n\t\tfmt.Println(\"response\", client.LastResponse)\n\n\t\tfmt.Printf(\"query.QueryResult:\\n%v\", query.QueryResult)\n\n\t})\n}\n\n\n\nfunc TestSearch(t *testing.T) ", "output": "{\n\tConvey(\"TestSearch\", t, func() {\n\t\tquery := &QuerySearch{\n\t\t\tDataSource: \"campaign\",\n\t\t\tIntervals: []string{\"2014-09-01T00:00/2020-01-01T00\"},\n\t\t\tGranularity: GranAll,\n\t\t\tSearchDimensions: []string{\"campaign_id\", \"hour\"},\n\t\t\tQuery: SearchQueryInsensitiveContains(1313),\n\t\t\tSort: SearchSortLexicographic,\n\t\t}\n\t\tclient := Client{\n\t\t\tUrl: \"http://192.168.10.60:8009\",\n\t\t\tDebug: true,\n\t\t}\n\n\t\terr := client.Query(query)\n\t\tSo(err, ShouldEqual, nil)\n\n\t\tfmt.Println(\"requst\", client.LastRequest)\n\t\tfmt.Println(\"response\", client.LastResponse)\n\n\t\tfmt.Printf(\"query.QueryResult:\\n%v\", query.QueryResult)\n\n\t})\n}"} {"input": "package containerd\n\nimport (\n\t\"fmt\"\n\t\"syscall\"\n\t\"testing\"\n)\n\n\n\nfunc TestParseSignal(t *testing.T) ", "output": "{\n\ttestSignals := []struct {\n\t\traw string\n\t\twant syscall.Signal\n\t\terr bool\n\t}{\n\t\t{\"1\", syscall.Signal(1), false},\n\t\t{\"SIGKILL\", syscall.SIGKILL, false},\n\t\t{\"NONEXIST\", 0, true},\n\t}\n\tfor _, ts := range testSignals {\n\t\tt.Run(fmt.Sprintf(\"%s/%d/%t\", ts.raw, ts.want, ts.err), func(t *testing.T) {\n\t\t\tgot, err := ParseSignal(ts.raw)\n\t\t\tif ts.err && err == nil {\n\t\t\t\tt.Errorf(\"ParseSignal(%s) should return error\", ts.raw)\n\t\t\t}\n\t\t\tif !ts.err && got != ts.want {\n\t\t\t\tt.Errorf(\"ParseSignal(%s) return %d, want %d\", ts.raw, got, ts.want)\n\t\t\t}\n\t\t})\n\t}\n}"} {"input": "package esicache\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/corestoreio/errors\"\n)\n\n\n\n\ntype Cacher interface {\n\tSet(key string, value []byte, expiration time.Duration) error\n\tGet(key string) ([]byte, error)\n}\n\n\n\nfunc NewCacher(url string) (Cacher, error) {\n\n\treturn nil, nil\n}\n\n\ntype Caches []Cacher\n\n\nfunc (c Caches) Set(key string, value []byte, expiration time.Duration) error {\n\treturn nil\n}\n\n\n\n\n\nvar MainRegistry = ®istry{\n\tcaches: make(map[string]Caches),\n}\n\ntype registry struct {\n\tmu sync.RWMutex\n\tcaches map[string]Caches\n}\n\nfunc (r *registry) Get(ctx context.Context, scope, alias, key string) error {\n\treturn errors.New(\"TODO IMPLEMENT\")\n}\n\n\n\n\nfunc (r *registry) Register(scope, url string) error {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tc, err := NewCacher(url)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"[esikv] NewCacher URL %q\", url)\n\t}\n\n\tif _, ok := r.caches[scope]; !ok {\n\t\tr.caches[scope] = make(Caches, 0, 2)\n\t}\n\tr.caches[scope] = append(r.caches[scope], c)\n\n\treturn nil\n}\n\n\nfunc (r *registry) Len(scope string) int {\n\tr.mu.RLock()\n\tdefer r.mu.RUnlock()\n\treturn len(r.caches[scope])\n}\n\n\nfunc (r *registry) Clear() {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tr.caches = make(map[string]Caches)\n}\n\nfunc (c Caches) Get(key string) ([]byte, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package distribute\n\nimport (\n \"net/rpc\"\n \"net/http\"\n \"fmt\"\n)\n\ntype Worker struct {\n addr string\n addUrlChannel chan bool\n}\n\nfunc initWorker(addr string) *Worker{\n w := &Worker{}\n w.addr = addr\n w.addUrlChannel = make(chan bool)\n return w\n}\n\nfunc RunWorker(mAddr, wAddr string) {\n fmt.Println(\"=======RunWorker Begin=======\")\n w := initWorker(wAddr)\n \n register(mAddr, w.addr)\n fmt.Println(\"=======RunWorker End=======\")\n \n \n \n \n \n \n \n}\n\nfunc register(mAddr, wAddr string) {\n args := &RegisterArgs{}\n args.Worker = wAddr\n var reply RegisterReply\n call(mAddr, \"Master.Register\", args, &reply)\n}\n\nfunc (w *Worker) Dojob(args *DojobArgs, res *DojobReply) error {\n fmt.Println(\"DoJob: JobType \", args.JobType)\n switch args.JobType {\n case \"Crawl\":\n \n \n \n }\n return nil\n}\n\n\n\nfunc startRpcWorker(w *Worker) ", "output": "{\n \n rpc.Register(w)\n rpc.HandleHTTP()\n err := http.ListenAndServe(w.addr, nil)\n fmt.Println(\"RegistrationServer: accept error\", err)\n \n \n \n \n \n \n}"} {"input": "package install\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tutilruntime \"k8s.io/apimachinery/pkg/util/runtime\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\t\"k8s.io/kubernetes/pkg/apis/scheduling\"\n\t\"k8s.io/kubernetes/pkg/apis/scheduling/v1\"\n\t\"k8s.io/kubernetes/pkg/apis/scheduling/v1alpha1\"\n\t\"k8s.io/kubernetes/pkg/apis/scheduling/v1beta1\"\n)\n\nfunc init() {\n\tInstall(legacyscheme.Scheme)\n}\n\n\n\n\nfunc Install(scheme *runtime.Scheme) ", "output": "{\n\tutilruntime.Must(scheduling.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1beta1.SchemeGroupVersion, v1.SchemeGroupVersion, v1alpha1.SchemeGroupVersion))\n}"} {"input": "package main\n\nimport (\n\t\"Algorithms-in-Golang/stack\"\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfmt.Println(\"程序开始\")\n\n\ts := \"( ( 1 + 2 ) * ( ( 3 - 4 ) * ( 5 - 6 ) ) )\"\n\tfmt.Println(s)\n\tr := infixToPostfix(s)\n\tfmt.Println(r)\n\n}\n\n\n\nfunc infixToPostfix(s string) string ", "output": "{\n\tstrs := stack.New()\n\tops := stack.New()\n\n\tss := strings.Split(s, \" \")\n\tfor _, v := range ss {\n\t\tswitch v {\n\t\tcase \"(\":\n\t\t\tcontinue\n\t\tcase \"+\", \"-\", \"*\", \"/\":\n\t\t\tops.Push(v)\n\t\tcase \")\":\n\t\t\tb := strs.Pop().(string)\n\t\t\ta := strs.Pop().(string)\n\t\t\top := ops.Pop().(string)\n\t\t\tstrs.Push(fmt.Sprintf(\"( %s %s %s )\", a, b, op))\n\t\tdefault:\n\t\t\tstrs.Push(v)\n\t\t}\n\t}\n\tresult := strs.Pop().(string)\n\treturn result\n}"} {"input": "package transport \n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\n\n\ntype MockReporter struct {\n\twgMetricsProcessed sync.WaitGroup\n}\n\nvar _ Reporter = (*MockReporter)(nil)\n\n\n\n\nfunc (m *MockReporter) OnDataReceived(ctx context.Context) context.Context {\n\treturn ctx\n}\n\nfunc (m *MockReporter) OnTranslationError(ctx context.Context, err error) {\n}\n\nfunc (m *MockReporter) OnMetricsProcessed(ctx context.Context, numReceivedMetricPoints int, err error) {\n\tm.wgMetricsProcessed.Done()\n}\n\nfunc (m *MockReporter) OnDebugf(template string, args ...interface{}) {\n}\n\n\n\nfunc (m *MockReporter) WaitAllOnMetricsProcessedCalls() {\n\tm.wgMetricsProcessed.Wait()\n}\n\nfunc NewMockReporter(expectedOnMetricsProcessedCalls int) *MockReporter ", "output": "{\n\tm := MockReporter{}\n\tm.wgMetricsProcessed.Add(expectedOnMetricsProcessedCalls)\n\treturn &m\n}"} {"input": "package types\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"path\"\n\t\"strings\"\n)\n\n\ntype Resource string\n\n\n\n\nfunc (res Resource) RelativeTo(other Resource) (Resource, error) {\n\tprefix := other.String()\n\tstr := res.String()\n\n\tif !strings.HasPrefix(str, prefix) {\n\t\treturn Resource(\"\"), errors.New(\"value error\")\n\t}\n\n\trelative := strings.TrimPrefix(strings.TrimPrefix(str, prefix), \"/\")\n\tif relative == \"\" {\n\t\trelative = \".\"\n\t}\n\n\treturn Resource(relative), nil\n}\n\n\nfunc (res Resource) Subresource(resources ...Resource) Resource {\n\telements := []string{res.String()}\n\n\tfor _, resource := range resources {\n\t\telements = append(elements, resource.String())\n\t}\n\n\treturn Resource(path.Join(elements...))\n}\n\n\nfunc (res Resource) GetNamespace() (Namespace, error) {\n\treturn nil, fmt.Errorf(\"no namespace found for %s\", res)\n}\n\nfunc (res Resource) String() string ", "output": "{\n\treturn string(res)\n}"} {"input": "package entrapped\n\nimport (\n\t\"github.com/SKatiyar/entrapped/Godeps/_workspace/src/github.com/julienschmidt/httprouter\"\n\t\"net/http\"\n)\n\nconst (\n\tsize int = 7\n\tnumBombs int = 10\n\tlifes int = 5\n\tnumBonusLifes int = 2\n)\n\nfunc Start(addr string) {\n\tif len(addr) == 0 {\n\t\taddr = \":7000\"\n\t}\n\n\tgo ch.run()\n\n\trouter := httprouter.New()\n\n\trouter.GET(\"/\", home)\n\trouter.ServeFiles(\"/statics/*filepath\", http.Dir(\"client/dist/statics\"))\n\n\trouter.GET(\"/players/:id\", addPlayer)\n\n\tlistenErr := http.ListenAndServe(addr, router)\n\tif listenErr != nil {\n\t\tlogger.Println(listenErr)\n\t\treturn\n\t}\n}\n\n\n\nfunc home(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\trw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\thttp.ServeFile(rw, req, \"client/dist/index.html\")\n}\n\nfunc addPlayer(rw http.ResponseWriter, req *http.Request, params httprouter.Params) ", "output": "{\n\tid := params.ByName(\"id\")\n\n\tws, wsErr := upgrader.Upgrade(rw, req, nil)\n\tif wsErr != nil {\n\t\tlogger.Println(wsErr)\n\t\treturn\n\t}\n\n\ttrap := makeTrap(size, numBombs, numBonusLifes, lifes)\n\n\tch.add(&trooper{id, trap, ws, make(chan []byte, 512)})\n}"} {"input": "package main\n\nimport \"math\"\n\n\n\n\nfunc SqrtUint32(x uint32) uint32 ", "output": "{\n\treturn uint32(math.Ceil(math.Sqrt(float64(x))))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype Page struct {\n\tTitle string\n\tBody []byte\n}\n\n\n\nfunc loadPage(title string) (*Page, error) {\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Page{Title: title, Body: body}, nil\n}\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/view/\"):]\n\tp, _ := loadPage(title)\n\tfmt.Fprintf(w, \"

%s

%s
\", p.Title, p.Body)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/view/\", viewHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc (p *Page) save() error ", "output": "{\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}"} {"input": "package labmeasure\n\ntype ImageStat struct {\n\tExamined int\n\tQualified int\n\tCorrect int\n\tIncorrect int\n\tIncorrectRecords []PImageRecord\n\tConfiguration Config\n}\n\nfunc (o ImageStat) GetIncorrectRecords() interface{} {\n\treturn o.IncorrectRecords\n}\n\n\n\nfunc (o ImageStat) Accuracy() float32 ", "output": "{\n\tif o.Qualified == 0 {\n\t\treturn 0.0\n\t}\n\treturn float32(o.Correct) / float32(o.Qualified)\n}"} {"input": "package markdown\n\nimport (\n\t\"bufio\"\n\t\"io\"\n)\n\ntype writer interface {\n\tWrite([]byte) (int, error)\n\tWriteByte(byte) error\n\tWriteString(string) (int, error)\n\tFlush() error\n}\n\ntype monadicWriter struct {\n\twriter\n\terr error\n}\n\nfunc newMonadicWriter(w io.Writer) *monadicWriter {\n\tif w, ok := w.(writer); ok {\n\t\treturn &monadicWriter{writer: w}\n\t}\n\treturn &monadicWriter{writer: bufio.NewWriter(w)}\n}\n\n\n\nfunc (w *monadicWriter) WriteByte(b byte) (err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\terr = w.writer.WriteByte(b)\n\tw.err = err\n\treturn\n}\n\nfunc (w *monadicWriter) WriteString(s string) (n int, err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\tn, err = w.writer.WriteString(s)\n\tw.err = err\n\treturn\n}\n\nfunc (w *monadicWriter) Flush() (err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\terr = w.writer.Flush()\n\tw.err = err\n\treturn\n}\n\nfunc (w *monadicWriter) Write(p []byte) (n int, err error) ", "output": "{\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\tn, err = w.writer.Write(p)\n\tw.err = err\n\treturn\n}"} {"input": "package cmd\n\nimport (\n\t\"golang.org/x/mod/semver\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestVersionDotTxt(t *testing.T) ", "output": "{\n\tbs, err := ioutil.ReadFile(\"../../version.txt\")\n\tif err != nil {\n\t\tt.Fatalf(\"failed to read ../../version.txt: %v\", err)\n\t}\n\tversion = strings.TrimSpace(string(bs))\n\n\tif !semver.IsValid(ensureVPrefixed(string(version))) {\n\t\tt.Fatalf(`version.txt does not contain a valid semantic version: %q`, version)\n\t}\n}"} {"input": "package ipam\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\t\"github.com/go-openapi/runtime/middleware\"\n\t\"github.com/go-openapi/validate\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewPostIPAMParams() PostIPAMParams {\n\tvar ()\n\treturn PostIPAMParams{}\n}\n\n\n\n\n\ntype PostIPAMParams struct {\n\n\tHTTPRequest *http.Request\n\n\tFamily *string\n}\n\n\n\nfunc (o *PostIPAMParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {\n\tvar res []error\n\to.HTTPRequest = r\n\n\tqs := runtime.Values(r.URL.Query())\n\n\tqFamily, qhkFamily, _ := qs.GetOK(\"family\")\n\tif err := o.bindFamily(qFamily, qhkFamily, route.Formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (o *PostIPAMParams) bindFamily(rawData []string, hasKey bool, formats strfmt.Registry) error {\n\tvar raw string\n\tif len(rawData) > 0 {\n\t\traw = rawData[len(rawData)-1]\n\t}\n\tif raw == \"\" { \n\t\treturn nil\n\t}\n\n\to.Family = &raw\n\n\tif err := o.validateFamily(formats); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (o *PostIPAMParams) validateFamily(formats strfmt.Registry) error ", "output": "{\n\n\tif err := validate.Enum(\"family\", \"query\", *o.Family, []interface{}{\"ipv4\", \"ipv6\"}); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package memdb\n\n\n\ntype Changes []Change\n\n\ntype Change struct {\n\tTable string\n\tBefore interface{}\n\tAfter interface{}\n\n\tprimaryKey []byte\n}\n\n\nfunc (m *Change) Created() bool {\n\treturn m.Before == nil && m.After != nil\n}\n\n\n\nfunc (m *Change) Updated() bool {\n\treturn m.Before != nil && m.After != nil\n}\n\n\n\n\n\nfunc (m *Change) Deleted() bool ", "output": "{\n\treturn m.Before != nil && m.After == nil\n}"} {"input": "package handler_common_type_in_different_versions_return_values\n\nimport (\n\t\"context\"\n)\n\ntype v4Args struct {\n\tReqInt int `key:\"req_int\" description:\"Required integer argument\"`\n\tInt *int `key:\"int\" description:\"Unrequired integer argument\"`\n}\n\n\n\nfunc (*Handler) V4(ctx context.Context, opts *v4Args) (*CommonStruct1, error) ", "output": "{\n\treturn &CommonStruct1{}, nil\n}"} {"input": "package protobuf\n\nimport \"github.com/m3db/m3x/pool\"\n\nconst (\n\tdefaultInitBufferSize = 2880\n\n\tdefaultMaxUnaggregatedMessageSize = 50 * 1024 * 1024\n)\n\n\ntype UnaggregatedOptions interface {\n\tSetBytesPool(value pool.BytesPool) UnaggregatedOptions\n\n\tBytesPool() pool.BytesPool\n\n\tSetInitBufferSize(value int) UnaggregatedOptions\n\n\tInitBufferSize() int\n\n\tSetMaxMessageSize(value int) UnaggregatedOptions\n\n\tMaxMessageSize() int\n}\n\ntype unaggregatedOptions struct {\n\tbytesPool pool.BytesPool\n\tinitBufferSize int\n\tmaxMessageSize int\n}\n\n\nfunc NewUnaggregatedOptions() UnaggregatedOptions {\n\tp := pool.NewBytesPool(nil, nil)\n\tp.Init()\n\treturn &unaggregatedOptions{\n\t\tbytesPool: p,\n\t\tinitBufferSize: defaultInitBufferSize,\n\t\tmaxMessageSize: defaultMaxUnaggregatedMessageSize,\n\t}\n}\n\nfunc (o *unaggregatedOptions) SetBytesPool(value pool.BytesPool) UnaggregatedOptions {\n\topts := *o\n\topts.bytesPool = value\n\treturn &opts\n}\n\nfunc (o *unaggregatedOptions) BytesPool() pool.BytesPool {\n\treturn o.bytesPool\n}\n\nfunc (o *unaggregatedOptions) SetInitBufferSize(value int) UnaggregatedOptions {\n\topts := *o\n\topts.initBufferSize = value\n\treturn &opts\n}\n\nfunc (o *unaggregatedOptions) InitBufferSize() int {\n\treturn o.initBufferSize\n}\n\n\n\nfunc (o *unaggregatedOptions) MaxMessageSize() int {\n\treturn o.maxMessageSize\n}\n\nfunc (o *unaggregatedOptions) SetMaxMessageSize(value int) UnaggregatedOptions ", "output": "{\n\topts := *o\n\topts.maxMessageSize = value\n\treturn &opts\n}"} {"input": "package detailed\n\nimport (\n\t\"$GITHUB_URI/report\"\n)\n\n\n\n\n\n\nfunc NodeTables(r report.Report, n report.Node) []report.Table ", "output": "{\n\tif _, ok := n.Counters.Lookup(n.Topology); ok {\n\t\treturn nil\n\t}\n\n\tif topology, ok := r.Topology(n.Topology); ok {\n\t\treturn topology.TableTemplates.Tables(n)\n\t}\n\treturn nil\n}"} {"input": "package diff\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/exec\"\n\t\"runtime\"\n)\n\n\nfunc Diff(prefix string, b1, b2 []byte) ([]byte, error) {\n\tf1, err := writeTempFile(prefix, b1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer os.Remove(f1)\n\n\tf2, err := writeTempFile(prefix, b2)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer os.Remove(f2)\n\n\tcmd := \"diff\"\n\tif runtime.GOOS == \"plan9\" {\n\t\tcmd = \"/bin/ape/diff\"\n\t}\n\n\tdata, err := exec.Command(cmd, \"-u\", f1, f2).CombinedOutput()\n\tif len(data) > 0 {\n\t\terr = nil\n\t}\n\treturn data, err\n}\n\n\n\nfunc writeTempFile(prefix string, data []byte) (string, error) ", "output": "{\n\tfile, err := ioutil.TempFile(\"\", prefix)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t_, err = file.Write(data)\n\tif err1 := file.Close(); err == nil {\n\t\terr = err1\n\t}\n\tif err != nil {\n\t\tos.Remove(file.Name())\n\t\treturn \"\", err\n\t}\n\treturn file.Name(), nil\n}"} {"input": "package state\n\nimport (\n\t\"time\"\n\n\t\"github.com/juju/errors\"\n\t\"gopkg.in/juju/names.v2\"\n\n\t\"github.com/juju/juju/core/lease\"\n)\n\n\n\n\n\n\n\n\n\ntype singularSecretary struct {\n\tuuid string\n}\n\n\n\n\n\nfunc (s singularSecretary) CheckHolder(name string) error {\n\tif _, err := names.ParseMachineTag(name); err != nil {\n\t\treturn errors.New(\"expected machine tag\")\n\t}\n\treturn nil\n}\n\n\nfunc (s singularSecretary) CheckDuration(duration time.Duration) error {\n\tif duration <= 0 {\n\t\treturn errors.NewNotValid(nil, \"non-positive\")\n\t}\n\treturn nil\n}\n\n\n\nfunc (st *State) SingularClaimer() lease.Claimer {\n\treturn st.workers.singularManager()\n}\n\nfunc (s singularSecretary) CheckLease(name string) error ", "output": "{\n\tif name != s.uuid {\n\t\treturn errors.New(\"expected environ UUID\")\n\t}\n\treturn nil\n}"} {"input": "package api_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestSwitchboardAPI(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Switchboard API Suite\")\n}"} {"input": "package invalidtest\n\nimport \"os\"\n\n\n\nfunc Not(this *os.File) string ", "output": "{ return \"the test file is garbage\" }"} {"input": "package nats\n\nimport (\n\t\"testing\"\n\n\t\"github.com/Jeffail/benthos/v3/public/service\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestOutputJetStreamConfigParse(t *testing.T) ", "output": "{\n\tspec := natsJetStreamOutputConfig()\n\tenv := service.NewEnvironment()\n\n\toutputConfig := `\nurls: [ url1, url2 ]\nsubject: testsubject\nauth:\n nkey_file: test auth n key file\n user_credentials_file: test auth user creds file\n`\n\n\tconf, err := spec.ParseYAML(outputConfig, env)\n\trequire.NoError(t, err)\n\n\te, err := newJetStreamWriterFromConfig(conf, nil)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, \"url1,url2\", e.urls)\n\tassert.Equal(t, \"testsubject\", e.subjectStr.String(service.NewMessage(nil)))\n\tassert.Equal(t, \"test auth n key file\", e.authConf.NKeyFile)\n\tassert.Equal(t, \"test auth user creds file\", e.authConf.UserCredentialsFile)\n}"} {"input": "package core\n\nimport (\n\t\"os\";\n\t\"container/list\";\n\t\"net\";\n\t\"log\";\n\t\"irc\";\n\t\"runloop\";\n)\n\ntype Network struct {\n\tname\t\tstring;\n\tserver\t\t*server;\n\tclients\t\t*list.List;\n\tlisten\t\t*listenConn;\n}\n\nfunc newNetwork(name string, serverConn net.Conn, listen net.Listener) *Network {\n\tvar network *Network;\n\n\taccept := func(conn net.Conn) {\n\t\trunloop.CallLater(func() {\n\t\t\tnetwork.addClient(conn)\n\t\t})\n\t};\n\n\terror := func(err os.Error) {\n\t};\n\n\tl := newListenConn(listen, accept, error);\n\tnetwork = &Network{name: name, clients: list.New(), listen: l};\n\tnetwork.server = newServer(serverConn, network);\n\treturn network;\n}\n\nfunc (network *Network) addClient(conn net.Conn) {\n\tclient := newClient(conn, network);\n\tnetwork.clients.PushBack(client);\n\tlog.Stderrf(\"client connected from %s\\n\", conn.RemoteAddr());\n}\n\n\n\n\n\n\nfunc (network *Network) SendToClients(msg *irc.Message) {\n\tfor c := range network.clients.Iter() {\n\t\tc.(*client).Send(msg)\n\t}\n}\n\n\nfunc (network *Network) SendNoticeToClient(conn Conn, line string) {\n\tnick := \"bouncin\"; \n\tconn.Send(&irc.Message{Command: \"NOTICE\", Params: []string{nick, line}});\n}\n\nvar networks = make(map[string] *Network);\n\nfunc AddNetwork(name string, server net.Conn, listen net.Listener) *Network {\n\tnetwork := newNetwork(name, server, listen);\n\tnetworks[name] = network;\n\treturn network;\n}\n\nfunc (network *Network) SendToServer(msg *irc.Message) ", "output": "{\n\tif network.server != nil {\n\t\tnetwork.server.Send(msg)\n\t}\n}"} {"input": "package workshop\n\nimport (\n\t\"math\"\n)\n\n\ntype Shape interface {\n\tarea()\n\tcircumference()\n\tvolume()\n}\n\n\ntype Circle struct {\n\tradius float64\n\tPI float64\n}\n\nfunc (circle *Circle) area() float64 {\n\treturn circle.PI * math.Pow(circle.radius, 2)\n}\n\nfunc (circle *Circle) circumference() float64 {\n\treturn 2 * circle.PI * circle.radius\n}\n\n\ntype Square struct {\n\tside float64\n}\n\n\n\ntype Sphere struct {\n\tPI float64\n\tradius float64\n}\n\nfunc (sphere *Sphere) volume() float64 {\n\treturn (4 / 3) * sphere.PI * math.Pow(sphere.radius, 3)\n}\n\n\ntype Cube struct {\n\tside float64\n}\n\nfunc (cube *Cube) volume() float64 {\n\treturn math.Pow(cube.side, 3)\n}\n\nfunc (square *Square) volume() float64 {\n\treturn math.Pow(square.side, 3)\n}\n\n\ntype Rectangle struct {\n\theight int\n\twidth int\n}\n\nfunc (rectangle *Rectangle) area() int {\n\treturn rectangle.height * rectangle.width\n}\n\nfunc interfaces() {\n\tcircle := Circle{radius: 5.5, PI: math.Pi}\n\tareaOfCircle := circle.area()\n\n\tassert(areaOfCircle == 55)\n\tassert(circle.circumference() == 88)\n\n\tvar square = Square{5}\n\tassert(square.area() == 36)\n\n\tcube := new(Cube)\n\tassert(cube.volume() == 8)\n\n\tvar rectangle = Rectangle{width: 4, height: 5}\n\tassert(rectangle.area() == 2)\n}\n\nfunc (square *Square) area() float64 ", "output": "{\n\treturn math.Pow(square.side, 2)\n}"} {"input": "package ip_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n\n\t\"github.com/onsi/ginkgo/reporters\"\n\t\"github.com/sirupsen/logrus\"\n\n\t\"github.com/projectcalico/libcalico-go/lib/logutils\"\n\t\"github.com/projectcalico/libcalico-go/lib/testutils\"\n)\n\n\n\nfunc init() {\n\ttestutils.HookLogrusForGinkgo()\n\tlogrus.AddHook(&logutils.ContextHook{})\n\tlogrus.SetFormatter(&logutils.Formatter{})\n}\n\nfunc TestIp(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tjunitReporter := reporters.NewJUnitReporter(\"../report/ip_suite.xml\")\n\tRunSpecsWithDefaultAndCustomReporters(t, \"IP Suite\", []Reporter{junitReporter})\n}"} {"input": "package cpf\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\nfunc Valid(digits string) (bool, error) {\n\treturn valid(digits)\n}\n\nfunc sanitize(data string) string {\n\tdata = strings.Replace(data, \".\", \"\", -1)\n\tdata = strings.Replace(data, \"-\", \"\", -1)\n\treturn data\n}\n\nfunc valid(data string) (bool, error) {\n\tdata = sanitize(data)\n\n\tif len(data) != 11 {\n\t\treturn false, errors.New(\"Invalid length\")\n\t}\n\n\tif strings.Contains(blacklist, data) || !check(data) {\n\t\treturn false, errors.New(\"Invalid value\")\n\t}\n\n\treturn true, nil\n}\n\nconst blacklist = `00000000000\n11111111111\n22222222222\n33333333333\n44444444444\n55555555555\n66666666666\n77777777777\n88888888888\n99999999999\n12345678909`\n\nfunc stringToIntSlice(data string) (res []int) {\n\tfor _, d := range data {\n\t\tx, err := strconv.Atoi(string(d))\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, x)\n\t}\n\treturn\n}\n\nfunc verify(data []int, n int) int {\n\tvar total int\n\n\tfor i := 0; i < n; i++ {\n\t\ttotal += data[i] * (n + 1 - i)\n\t}\n\n\ttotal = total % 11\n\tif total < 2 {\n\t\treturn 0\n\t}\n\treturn 11 - total\n}\n\nfunc check(data string) bool {\n\treturn checkEach(data, 9) && checkEach(data, 10)\n}\n\n\n\nfunc checkEach(data string, n int) bool ", "output": "{\n\tfinal := verify(stringToIntSlice(data), n)\n\n\tx, err := strconv.Atoi(string(data[n]))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn final == x\n}"} {"input": "package quota\n\nimport quotav1 \"github.com/openshift/api/quota/v1\"\n\n\n\n\n\nfunc ConvertV1ClusterResourceQuotaToV1AppliedClusterResourceQuota(in *quotav1.ClusterResourceQuota) *quotav1.AppliedClusterResourceQuota {\n\treturn "av1.AppliedClusterResourceQuota{\n\t\tObjectMeta: in.ObjectMeta,\n\t\tSpec: in.Spec,\n\t\tStatus: in.Status,\n\t}\n}\n\nfunc ConvertAppliedClusterResourceQuotaToClusterResourceQuota(in *AppliedClusterResourceQuota) *ClusterResourceQuota ", "output": "{\n\treturn &ClusterResourceQuota{\n\t\tObjectMeta: in.ObjectMeta,\n\t\tSpec: in.Spec,\n\t\tStatus: in.Status,\n\t}\n}"} {"input": "package main\nimport \"fmt\"\nimport \"termbox-go\"\n\ntype PanelDeathScreen struct { }\n\n\n\nfunc (p *PanelDeathScreen) Display(g *Game, r *ConsoleRange) {\n white := termbox.ColorWhite | termbox.AttrBold\n grey := termbox.ColorWhite\n black := termbox.ColorBlack\n \n fd := NewFlowDocument(78, 23)\n fd.AddParagraph(\"You have been destroyed\", grey, black)\n fd.AddParagraph(\" \", grey, black)\n fd.AddParagraph(fmt.Sprintf(\"You destroyed %d ships before heading off to Spacey Jones Locker.\", g.kills), grey, black)\n fd.Write(r, 1,1)\n \n r.Com(\"[Q]\", \" Quit\", 1, 23, black, white)\n \n \n}\n\nfunc (p *PanelDeathScreen) ProcessInput(g *Game, ch rune, key termbox.Key) *InputResult ", "output": "{\n result := &InputResult {\n Exit: false,\n TicksToPass: 0, \n }\n\n switch ch {\n \n case 'Q', 'q': \n result.Exit = true\n \n default:\n return nil\n }\n \n return result\n}"} {"input": "package sqltrace\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\nfunc boolToInt64(f bool) int64 {\n\tif f {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\ntype sqlTrace struct {\n\ton int64 \n\n\t*log.Logger\n}\n\nfunc newSQLTrace() *sqlTrace {\n\treturn &sqlTrace{\n\t\tLogger: log.New(os.Stdout, \"hdb \", log.Ldate|log.Ltime|log.Lshortfile),\n\t}\n}\nfunc (t *sqlTrace) On() bool { return atomic.LoadInt64(&t.on) != 0 }\nfunc (t *sqlTrace) SetOn(on bool) { atomic.StoreInt64(&t.on, boolToInt64(on)) }\n\ntype flagValue struct {\n\tt *sqlTrace\n}\n\nfunc (v flagValue) IsBoolFlag() bool { return true }\n\nfunc (v flagValue) String() string {\n\tif v.t == nil {\n\t\treturn \"\"\n\t}\n\treturn strconv.FormatBool(v.t.On())\n}\n\nfunc (v flagValue) Set(s string) error {\n\tf, err := strconv.ParseBool(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.t.SetOn(f)\n\treturn nil\n}\n\nvar tracer = newSQLTrace()\n\n\n\n\nfunc On() bool { return tracer.On() }\n\n\nfunc SetOn(on bool) { tracer.SetOn(on) }\n\n\nfunc Trace(v ...interface{}) { tracer.Print(v...) }\n\n\nfunc Tracef(format string, v ...interface{}) { tracer.Printf(format, v...) }\n\n\nfunc Traceln(v ...interface{}) { tracer.Println(v...) }\n\nfunc init() ", "output": "{\n\tflag.Var(&flagValue{t: tracer}, \"hdb.sqlTrace\", \"enabling hdb sql trace\")\n}"} {"input": "package toJson\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc WriteToJson(w http.ResponseWriter, obj interface{}) error {\n\treturn WriteToJsonWithCode(w, obj, http.StatusOK)\n}\n\nfunc WriteToJsonWithCode(w http.ResponseWriter, obj interface{}, code int) error {\n\to, err := ToJson(obj)\n\tif err != nil {\n\t\twriteError(err)\n\t\treturn err\n\t}\n\n\twrapped := map[string]interface{}{\"result\": o}\n\n\treturn WriteJson(w, &wrapped, code)\n}\n\nfunc WriteToJsonNotWrapped(w http.ResponseWriter, obj interface{}) error {\n\treturn WriteToJsonNotWrappedWithCode(w, obj, http.StatusOK)\n}\n\n\n\nfunc WriteJson(w http.ResponseWriter, obj interface{}, code int) error {\n\tmarshalled, err := json.MarshalIndent(obj, \"\", \" \")\n\tif err != nil {\n\t\twriteError(err)\n\t\treturn err\n\t}\n\n\tdata := []byte(fmt.Sprintf(\"%s\\n\", marshalled))\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.Header().Set(\"Content-Length\", fmt.Sprint(len(data)))\n\tw.WriteHeader(code)\n\tw.Write(data)\n\n\treturn nil\n}\n\nfunc WriteToJsonNotWrappedWithCode(w http.ResponseWriter, obj interface{}, code int) error ", "output": "{\n\to, err := ToJson(obj)\n\tif err != nil {\n\t\twriteError(err)\n\t\treturn err\n\t}\n\n\treturn WriteJson(w, &o, code)\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"k8s.io/kubernetes/pkg/client/clientset_generated/clientset/typed/policy/v1beta1\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n\tcore \"k8s.io/kubernetes/pkg/client/testing/core\"\n)\n\ntype FakePolicyV1beta1 struct {\n\t*core.Fake\n}\n\nfunc (c *FakePolicyV1beta1) Evictions(namespace string) v1beta1.EvictionInterface {\n\treturn &FakeEvictions{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakePolicyV1beta1) RESTClient() restclient.Interface {\n\tvar ret *restclient.RESTClient\n\treturn ret\n}\n\nfunc (c *FakePolicyV1beta1) PodDisruptionBudgets(namespace string) v1beta1.PodDisruptionBudgetInterface ", "output": "{\n\treturn &FakePodDisruptionBudgets{c, namespace}\n}"} {"input": "package framework\n\nimport \"github.com/onsi/gomega\"\n\n\nfunc ExpectEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.Equal(extra), explain...)\n}\n\n\nfunc ExpectNotEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).NotTo(gomega.Equal(extra), explain...)\n}\n\n\nfunc ExpectError(err error, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, err).To(gomega.HaveOccurred(), explain...)\n}\n\n\n\n\n\n\nfunc ExpectNoErrorWithOffset(offset int, err error, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1+offset, err).NotTo(gomega.HaveOccurred(), explain...)\n}\n\n\nfunc ExpectConsistOf(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.ConsistOf(extra), explain...)\n}\n\n\nfunc ExpectHaveKey(actual interface{}, key interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.HaveKey(key), explain...)\n}\n\n\nfunc ExpectEmpty(actual interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.BeEmpty(), explain...)\n}\n\nfunc ExpectNoError(err error, explain ...interface{}) ", "output": "{\n\tExpectNoErrorWithOffset(1, err, explain...)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/asticode/go-logger/logger\"\n\t\"github.com/asticode/go-stopwatch/stopwatch\"\n\textendederror \"github.com/asticode/go-toolbox/error\"\n\t_ \"github.com/asticode/go-keyboardemulator/keyboardemulator\"\n\t_ \"os/exec\"\n\t\"github.com/asticode/go-texttospeech/texttospeech\"\n)\n\nfunc main() {\n\tdefer extendederror.Catch(catchPrepare, map[string]interface{}{})\n\n\tconfigPath := flag.String(\"config\", \"\", \"Path to the local configuration file\")\n\tflag.Parse()\n\n\tprepare(*configPath)\n}\n\nfunc catchPrepare(err interface{}, args map[string]interface{}) {\n\tfmt.Println(\"CRITICAL: \" + extendederror.ParseError(err))\n}\n\nfunc prepare(configPath string) {\n\tc := newConfiguration(configPath)\n\n\tl, err := logger.NewLoggerFromConfiguration(c.Logger)\n\textendederror.ProcessError(err)\n\n\tdefer extendederror.Catch(catchRun, map[string]interface{}{\n\t\t\"logger\": l,\n\t})\n\trun(*c, l)\n}\n\nfunc catchRun(err interface{}, args map[string]interface{}) {\n\tl := args[\"logger\"].(logger.Logger)\n\n\tl.Critical(extendederror.ParseError(err))\n}\n\n\n\nfunc run(c configuration, l logger.Logger) ", "output": "{\n\tsw := stopwatch.NewStopwatchFromConfiguration(c.StopWatch).SetIsEnabled(true)\n\tsw.AddEvent(\"Init\", \"Stopwatch has been created\")\n\n\n\n\ttts := texttospeech.NewTextToSpeech()\n\n\ttts.Say(\"Good morning sir, how may I help you today?\")\n\n\n\tl.Info(\"Done\")\n}"} {"input": "package terraform\n\nimport (\n\t\"github.com/hashicorp/terraform/config/module\"\n)\n\n\n\n\ntype ImportGraphBuilder struct {\n\tImportTargets []*ImportTarget\n\n\tModule *module.Tree\n\n\tProviders []string\n}\n\n\n\n\n\n\nfunc (b *ImportGraphBuilder) Steps() []GraphTransformer {\n\tmod := b.Module\n\tif mod == nil {\n\t\tmod = module.NewEmptyTree()\n\t}\n\n\tproviderFactory := func(name string, path []string) GraphNodeProvider {\n\t\treturn &NodeApplyableProvider{\n\t\t\tNameValue: name,\n\t\t\tPathValue: path,\n\t\t}\n\t}\n\n\tsteps := []GraphTransformer{\n\t\t&ConfigTransformerOld{Module: mod},\n\n\t\t&ImportStateTransformer{Targets: b.ImportTargets},\n\n\t\t&MissingProviderTransformer{Providers: b.Providers, Factory: providerFactory},\n\t\t&ProviderTransformer{},\n\t\t&DisableProviderTransformerOld{},\n\t\t&PruneProviderTransformer{},\n\t\t&AttachProviderConfigTransformer{Module: mod},\n\n\t\t&ImportProviderValidateTransformer{},\n\n\t\t&RootTransformer{},\n\n\t\t&TransitiveReductionTransformer{},\n\t}\n\n\treturn steps\n}\n\nfunc (b *ImportGraphBuilder) Build(path []string) (*Graph, error) ", "output": "{\n\treturn (&BasicGraphBuilder{\n\t\tSteps: b.Steps(),\n\t\tValidate: true,\n\t\tName: \"ImportGraphBuilder\",\n\t}).Build(path)\n}"} {"input": "package scrapers\n\nimport (\n\t\"golang.org/x/net/html\"\n\t\"golang.org/x/net/html/atom\"\n\t\"io\"\n)\n\n\ntype Parser struct {\n\treader io.Reader\n\tlinks []string\n}\n\n\nfunc NewParser(reader io.Reader) *Parser {\n\treturn &Parser{\n\t\treader: reader,\n\t\tlinks: make([]string, 0),\n\t}\n}\n\n\n\n\n\nfunc (p *Parser) Links() []string {\n\treturn p.links\n}\n\nfunc (p *Parser) Parse() error ", "output": "{\n\ttokenizer := html.NewTokenizer(p.reader)\n\n\tfor {\n\t\ttokenType := tokenizer.Next()\n\n\t\tswitch tokenType {\n\t\tcase html.ErrorToken:\n\t\t\terr := tokenizer.Err()\n\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\treturn err\n\n\t\tcase html.StartTagToken:\n\t\t\ttoken := tokenizer.Token()\n\n\t\t\tif token.DataAtom == atom.A {\n\t\t\t\tfor _, attribute := range token.Attr {\n\t\t\t\t\tif attribute.Key == \"href\" {\n\t\t\t\t\t\tlink := attribute.Val\n\n\t\t\t\t\t\tp.links = append(p.links, link)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package labassistant\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc make_ob() *Observation {\n\treturn &Observation{}\n}\n\nfunc good_func(i int) int {\n\treturn i\n}\n\nfunc panic_func(i int) int {\n\tpanic(\"panic\")\n}\n\n\n\nfunc TestObservationRunIsOK(t *testing.T) {\n\ta := assert.New(t)\n\tout := make_ob().run(good_func, 1)\n\ta.Equal([]interface{}{1}, out)\n\n\tout = make_ob().run(good_func, 0)\n\ta.NotEqual([]interface{}{1}, out)\n\n\ta.Panics(func() {\n\t\tmake_ob().run(good_func)\n\t})\n\n\ta.Panics(func() {\n\t\tmake_ob().run(good_func, 1, 1)\n\t})\n\n\ta.Panics(func() {\n\t\tmake_ob().run(good_func, \"string\")\n\t})\n}\n\nfunc TestObservationRunSetsValues(t *testing.T) {\n\ta := assert.New(t)\n\tgood := make_ob()\n\tgood.run(good_func, 1)\n\ta.Equal(\"github.com/lmas/labassistant.good_func\", good.Name)\n\ta.Empty(good.Panic)\n\ta.Equal([]interface{}{1}, good.Outputs)\n\ta.NotEmpty(good.Start)\n\ta.NotZero(good.Duration)\n\n\tbad := make_ob()\n\tbad.can_panic = true\n\ta.NotPanics(func() {\n\t\tbad.run(panic_func, 1)\n\t})\n\ta.Equal(\"panic\", bad.Panic)\n\ta.Empty(bad.Outputs)\n\ta.NotEmpty(bad.Start)\n\ta.Zero(bad.Duration)\n}\n\nfunc bad_func(i int) int ", "output": "{\n\treturn i + 1\n}"} {"input": "package hwaflib\n\n\n\nfunc (ctx *Context) Revision() string {\n\trevision := \"09081c1\"\n\treturn revision\n}\n\nfunc (ctx *Context) Version() string ", "output": "{\n\tversion := \"20140814\"\n\treturn version\n}"} {"input": "package github\n\nimport (\n\t\"context\"\n\t\"fmt\"\n)\n\n\n\n\n\ntype GitignoresService service\n\n\ntype Gitignore struct {\n\tName *string `json:\"name,omitempty\"`\n\tSource *string `json:\"source,omitempty\"`\n}\n\nfunc (g Gitignore) String() string {\n\treturn Stringify(g)\n}\n\n\n\n\nfunc (s *GitignoresService) List(ctx context.Context) ([]string, *Response, error) {\n\treq, err := s.client.NewRequest(\"GET\", \"gitignore/templates\", nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar availableTemplates []string\n\tresp, err := s.client.Do(ctx, req, &availableTemplates)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn availableTemplates, resp, nil\n}\n\n\n\n\n\n\nfunc (s *GitignoresService) Get(ctx context.Context, name string) (*Gitignore, *Response, error) ", "output": "{\n\tu := fmt.Sprintf(\"gitignore/templates/%v\", name)\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tgitignore := new(Gitignore)\n\tresp, err := s.client.Do(ctx, req, gitignore)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn gitignore, resp, nil\n}"} {"input": "package atomic\n\nimport (\n\t\"encoding/json\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\n\ntype Uint32 struct {\n\t_ nocmp \n\n\tv uint32\n}\n\n\n\n\n\nfunc (i *Uint32) Load() uint32 {\n\treturn atomic.LoadUint32(&i.v)\n}\n\n\nfunc (i *Uint32) Add(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, delta)\n}\n\n\nfunc (i *Uint32) Sub(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, ^(delta - 1))\n}\n\n\nfunc (i *Uint32) Inc() uint32 {\n\treturn i.Add(1)\n}\n\n\nfunc (i *Uint32) Dec() uint32 {\n\treturn i.Sub(1)\n}\n\n\nfunc (i *Uint32) CAS(old, new uint32) (swapped bool) {\n\treturn atomic.CompareAndSwapUint32(&i.v, old, new)\n}\n\n\nfunc (i *Uint32) Store(val uint32) {\n\tatomic.StoreUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) Swap(val uint32) (old uint32) {\n\treturn atomic.SwapUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(i.Load())\n}\n\n\nfunc (i *Uint32) UnmarshalJSON(b []byte) error {\n\tvar v uint32\n\tif err := json.Unmarshal(b, &v); err != nil {\n\t\treturn err\n\t}\n\ti.Store(v)\n\treturn nil\n}\n\n\nfunc (i *Uint32) String() string {\n\tv := i.Load()\n\treturn strconv.FormatUint(uint64(v), 10)\n}\n\nfunc NewUint32(val uint32) *Uint32 ", "output": "{\n\treturn &Uint32{v: val}\n}"} {"input": "package da_griddata\n\nimport (\n\t\"github.com/watermint/toolbox/essentials/io/es_stdout\"\n\t\"github.com/watermint/toolbox/infra/control/app_control\"\n\t\"sync\"\n)\n\n\n\ntype consoleWriter struct {\n\tctl app_control.Control\n\tname string\n\tformatter GridDataFormatter\n\tpw PlainGridDataWriter\n\trow int\n\tmutex sync.Mutex\n}\n\nfunc (z *consoleWriter) Name() string {\n\treturn z.name\n}\n\nfunc (z *consoleWriter) Row(column []interface{}) {\n\tz.mutex.Lock()\n\tdefer z.mutex.Unlock()\n\tout := es_stdout.NewDefaultOut(z.ctl.Feature())\n\n\t_ = z.pw.WriteRow(z.ctl.Log(), out, z.formatter, z.row, column)\n\tz.row++\n}\n\nfunc (z *consoleWriter) Open(c app_control.Control) error {\n\tz.ctl = c\n\treturn nil\n}\n\nfunc (z *consoleWriter) Close() {\n}\n\nfunc NewConsoleWriter(formatter GridDataFormatter, pw PlainGridDataWriter) GridDataWriter ", "output": "{\n\treturn &consoleWriter{\n\t\tformatter: formatter,\n\t\tpw: pw,\n\t}\n}"} {"input": "package tests\n\nimport (\n\t\"fmt\"\n\t\"github.com/amorgun/go-tour-crawler/crawler\"\n\t\"sync\"\n)\n\nfunc RunTest(crawl crawler.CrawlFunc,\n\tstartUrl string,\n\tmaxDepth int,\n\tfetcher crawler.Fetcher,\n\texpectedBodies map[string]string) (errorMessage string, ok bool) {\n\n\tactualBodies := make(map[string]string)\n\tactualVisitCount := make(map[string]int)\n\tlock := sync.Mutex{}\n\n\tvisit := func(url string, body string) {\n\t\tfmt.Printf(\"found: %s %q\\n\", url, body)\n\t\tlock.Lock()\n\t\tdefer lock.Unlock()\n\t\tactualBodies[url] = body\n\t\tactualVisitCount[url]++\n\t}\n\n\tcrawl(startUrl, maxDepth, fetcher, visit)\n\n\tfor expectedUrl, expectedBody := range expectedBodies {\n\t\tactualBody, visited := actualBodies[expectedUrl]\n\t\tif !visited {\n\t\t\terrorMessage = fmt.Sprintf(\"Url %q has not been visited\", expectedUrl)\n\t\t\treturn\n\t\t}\n\t\tif actualBody != expectedBody {\n\t\t\terrorMessage = fmt.Sprintf(\"Found wrong body for url %q\\nExpected: %q\\nGot:%q\",\n\t\t\t\texpectedUrl, expectedBody, actualBody)\n\t\t\treturn\n\t\t}\n\t}\n\tfor url := range actualBodies {\n\t\tif _, isExpected := expectedBodies[url]; !isExpected {\n\t\t\terrorMessage = fmt.Sprintf(\"Visited unexpected url %s\", url)\n\t\t\treturn\n\t\t}\n\t\tif actualVisitCount[url] > 1 {\n\t\t\terrorMessage = fmt.Sprintf(\"Url %s has been visited multiple times\", url)\n\t\t\treturn\n\t\t}\n\t}\n\tok = true\n\treturn\n}\n\n\n\nfunc RunAllTests(crawl crawler.CrawlFunc,\n\tprocessResult func(string, bool)) ", "output": "{\n\tfor idx, testCase := range getTestCases() {\n\t\tfmt.Printf(\"Test case #%v\\n\", idx+1)\n\t\terrorMessage, ok := RunTest(\n\t\t\tcrawl, testCase.startUrl, testCase.maxDepth, testCase.fetcher, testCase.expectedBodies)\n\t\tprocessResult(errorMessage, ok)\n\t}\n}"} {"input": "package packet\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype PacketCodecVarIntLength struct {\n\tcodec PacketCodec\n}\n\n\n\nfunc (this *PacketCodecVarIntLength) Decode(reader io.Reader) (packet Packet, err error) {\n\tlength, err := ReadVarInt(reader)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Decode, Length read error: %w\", err)\n\t\treturn\n\t}\n\tif length < 0 {\n\t\terr = errors.New(fmt.Sprintf(\"Decode, Packet length is below zero: %d\", length))\n\t\treturn\n\t}\n\tif length > 1048576 { \n\t\terr = errors.New(fmt.Sprintf(\"Decode, Packet length is above maximum: %d\", length))\n\t\treturn\n\t}\n\tpayload := make([]byte, length)\n\t_, err = reader.Read(payload)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Decode, Length buffer error: %w\", err)\n\t\treturn\n\t}\n\tpacket, err = this.codec.Decode(bytes.NewBuffer(payload))\n\treturn\n}\n\nfunc (this *PacketCodecVarIntLength) Encode(writer io.Writer, packet Packet) (err error) {\n\tbuffer := new(bytes.Buffer)\n\terr = this.codec.Encode(buffer, packet)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = WriteVarInt(writer, buffer.Len())\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = buffer.WriteTo(writer)\n\treturn\n}\n\nfunc (this *PacketCodecVarIntLength) SetCodec(codec PacketCodec) {\n\tthis.codec = codec\n}\n\nfunc NewPacketCodecVarIntLength() (this *PacketCodecVarIntLength) ", "output": "{\n\tthis = new(PacketCodecVarIntLength)\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/jackytck/projecteuler/tools\"\n)\n\n\n\nfunc main() {\n\tfmt.Println(solve(1000))\n}\n\nfunc solve(limit int) int ", "output": "{\n\tvar maxP int\n\tvar maxAns int\n\tfor p := 2; p <= limit; p += 2 {\n\t\tvar ans int\n\t\tfor a := 1; a < p/3; a++ {\n\t\t\tif b, r := tools.Divmod(p*(p-2*a), 2*(p-a)); r == 0 && b >= a {\n\t\t\t\tans++\n\t\t\t}\n\t\t}\n\t\tif ans > maxAns {\n\t\t\tmaxAns = ans\n\t\t\tmaxP = p\n\t\t}\n\t}\n\treturn maxP\n}"} {"input": "package catalogs\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewGetNodesIdentifierCatalogsParams() *GetNodesIdentifierCatalogsParams {\n\tvar ()\n\treturn &GetNodesIdentifierCatalogsParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\nfunc NewGetNodesIdentifierCatalogsParamsWithTimeout(timeout time.Duration) *GetNodesIdentifierCatalogsParams {\n\tvar ()\n\treturn &GetNodesIdentifierCatalogsParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype GetNodesIdentifierCatalogsParams struct {\n\n\tIdentifier string\n\n\ttimeout time.Duration\n}\n\n\n\n\n\nfunc (o *GetNodesIdentifierCatalogsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"identifier\", o.Identifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (o *GetNodesIdentifierCatalogsParams) WithIdentifier(identifier string) *GetNodesIdentifierCatalogsParams ", "output": "{\n\to.Identifier = identifier\n\treturn o\n}"} {"input": "package bind\n\nimport (\n\t\"crypto/rand\"\n\t\"fmt\"\n\tmrand \"math/rand\"\n\t\"strconv\"\n\n\t\"github.com/skriptble/nine/element\"\n\t\"github.com/skriptble/nine/element/stanza\"\n\t\"github.com/skriptble/nine/jid\"\n\t\"github.com/skriptble/nine/stream\"\n)\n\ntype Handler struct {\n}\n\nfunc NewHandler() Handler {\n\treturn Handler{}\n}\n\n\n\nfunc (h Handler) HandleIQ(iq stanza.IQ, props stream.Properties) ([]stanza.Stanza, stream.Properties) {\n\tvar sts []stanza.Stanza\n\treq, err := stanza.TransformBindRequest(iq)\n\tif err != nil {\n\t\treturn sts, props\n\t}\n\tif req.Resource == \"\" {\n\t\treq.Resource = genResourceID()\n\t}\n\n\tprops.Header.To += \"/\" + req.Resource\n\n\tj := jid.New(props.Header.To)\n\tres := stanza.NewBindResult(iq, j)\n\tsts = append(sts, res.TransformStanza())\n\n\tprops.Status = props.Status | stream.Bind\n\treturn sts, props\n}\n\nfunc genResourceID() string {\n\tid := make([]byte, 16)\n\t_, err := rand.Read(id)\n\tif err != nil {\n\t\treturn strconv.FormatInt(mrand.Int63(), 10)\n\t}\n\n\tid[8] = (id[8] | 0x80) & 0xBF\n\tid[6] = (id[6] | 0x40) & 0x4F\n\n\treturn fmt.Sprintf(\"%x-%x-%x-%x-%x\", id[:4], id[4:6], id[6:8], id[8:10], id[10:])\n}\n\nfunc (h Handler) GenerateFeature(props stream.Properties) stream.Properties ", "output": "{\n\tif props.Status&stream.Bind != 0 || props.Status&stream.Auth == 0 {\n\t\treturn props\n\t}\n\n\tprops.Features = append(props.Features, element.Bind)\n\treturn props\n}"} {"input": "package test\n\nimport (\n\t\"io\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n\ntype KafkaExecutor struct {\n\tZookeeperURI string\n\tKafkaDirectory string\n\tKafkaURI string\n\tOutputWriter io.Writer\n}\n\n\nfunc (e *KafkaExecutor) CreateTopic(topic string) error {\n\tcmd := exec.Command(\n\t\tfilepath.Join(e.KafkaDirectory, \"bin\", \"kafka-topics.sh\"),\n\t\t\"--create\",\n\t\t\"--zookeeper\", e.ZookeeperURI,\n\t\t\"--replication-factor\", \"1\",\n\t\t\"--partitions\", \"1\",\n\t\t\"--topic\", topic,\n\t)\n\tcmd.Stdout = e.OutputWriter\n\tcmd.Stderr = e.OutputWriter\n\treturn cmd.Run()\n}\n\n\nfunc (e *KafkaExecutor) WriteToTopic(topic string, data []string) error {\n\tcmd := exec.Command(\n\t\tfilepath.Join(e.KafkaDirectory, \"bin\", \"kafka-console-producer.sh\"),\n\t\t\"--broker-list\", e.KafkaURI,\n\t\t\"--topic\", topic,\n\t)\n\tcmd.Stdout = e.OutputWriter\n\tcmd.Stderr = e.OutputWriter\n\tcmd.Stdin = strings.NewReader(strings.Join(data, \"\\n\"))\n\treturn cmd.Run()\n}\n\n\n\n\nfunc (e *KafkaExecutor) DeleteTopic(topic string) error ", "output": "{\n\tcmd := exec.Command(\n\t\tfilepath.Join(e.KafkaDirectory, \"bin\", \"kafka-topics.sh\"),\n\t\t\"--delete\",\n\t\t\"--if-exists\",\n\t\t\"--zookeeper\", e.ZookeeperURI,\n\t\t\"--topic\", topic,\n\t)\n\tcmd.Stderr = e.OutputWriter\n\tcmd.Stdout = e.OutputWriter\n\treturn cmd.Run()\n}"} {"input": "package color\n\n\n\nfunc init() ", "output": "{\n\tKeyboardFocus = RGB(240, 119, 70)\n\tSelectedTextBackground = KeyboardFocus\n}"} {"input": "package xparam\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (xp XP) As_XP(key string) (data XP) {\n\n\tif val, ok := xp[key]; ok && val != nil {\n\t\tif axp, ok := val.(map[string]interface{}); ok {\n\t\t\tdata = axp\n\t\t}\n\t}\n\treturn\n}\n\n\nfunc (xp XP) As_ArrayXP(key string) (data []XP) {\n\n\tif val, ok := xp[key]; ok && val != nil {\n\t\tif arr, ok := val.([]interface{}); ok {\n\t\t\tdata = []XP{}\n\t\t\tfor _, obj := range arr {\n\t\t\t\tif axp, ok := obj.(map[string]interface{}); ok {\n\t\t\t\t\tdata = append(data, axp)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc New(vals map[string]interface{}) XP ", "output": "{\n\treturn vals\n}"} {"input": "package core\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\ntype ExportImageViaObjectStorageUriDetails struct {\n\n\tDestinationUri *string `mandatory:\"true\" json:\"destinationUri\"`\n}\n\n\n\n\nfunc (m ExportImageViaObjectStorageUriDetails) MarshalJSON() (buff []byte, e error) {\n\ttype MarshalTypeExportImageViaObjectStorageUriDetails ExportImageViaObjectStorageUriDetails\n\ts := struct {\n\t\tDiscriminatorParam string `json:\"destinationType\"`\n\t\tMarshalTypeExportImageViaObjectStorageUriDetails\n\t}{\n\t\t\"objectStorageUri\",\n\t\t(MarshalTypeExportImageViaObjectStorageUriDetails)(m),\n\t}\n\n\treturn json.Marshal(&s)\n}\n\nfunc (m ExportImageViaObjectStorageUriDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package sortedmap\n\nimport (\n\t\"testing\"\n\n\t\"github.com/umpc/go-sortedmap/asc\"\n)\n\nfunc insertRecord(b *testing.B) {\n\trecords := randRecords(1)\n\tsm := New(0, asc.Time)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsm.Insert(records[0].Key, records[0].Val)\n\n\t\tb.StopTimer()\n\t\trecords = randRecords(1)\n\t\tsm = New(0, asc.Time)\n\t\tb.StartTimer()\n\t}\n}\n\n\n\nfunc BenchmarkInsert1Record(b *testing.B) {\n\tinsertRecord(b)\n}\n\nfunc BenchmarkBatchInsert10Records(b *testing.B) {\n\tbatchInsertRecords(b, 10)\n}\n\nfunc BenchmarkBatchInsert100Records(b *testing.B) {\n\tbatchInsertRecords(b, 100)\n}\n\nfunc BenchmarkBatchInsert1000Records(b *testing.B) {\n\tbatchInsertRecords(b, 1000)\n}\n\nfunc BenchmarkBatchInsert10000Records(b *testing.B) {\n\tbatchInsertRecords(b, 10000)\n}\n\nfunc batchInsertRecords(b *testing.B, n int) ", "output": "{\n\trecords := randRecords(n)\n\tsm := New(0, asc.Time)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsm.BatchInsert(records)\n\n\t\tb.StopTimer()\n\t\trecords = randRecords(n)\n\t\tsm = New(0, asc.Time)\n\t\tb.StartTimer()\n\t}\n}"} {"input": "package models\n\ntype Document struct {\n\tID string `json:\"_id,omitempty\"`\n\tRev string `json:\"_rev,omitempty\"`\n\tKey string `json:\"_key,omitempty\"`\n}\n\n\n\ntype Edge struct {\n\tDocument\n\tFrom string `json:\"_from,omitempty\"`\n\tTo string `json:\"_to,omitempty\"`\n}\n\nfunc NewEdge(id, rev, key, from, to string) Edge {\n\treturn Edge{\n\t\tDocument: NewDocument(id, rev, key),\n\t\tFrom: from,\n\t\tTo: to,\n\t}\n}\n\nfunc NewDocument(id, rev, key string) Document ", "output": "{\n\treturn Document{\n\t\tID: id,\n\t\tRev: rev,\n\t\tKey: key,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\n\t\"gopkg.in/yaml.v1\"\n)\n\nconst (\n\tCONFIG_SUBDIR = \"mcmd\"\n\tDEFAULT_KNOWN_HOSTS_FILE = \"$HOME/.ssh/known_hosts\"\n)\n\ntype HostConfig struct {\n\tUser string\n\tPrivatekey string\n\tHosts []string\n}\n\nfunc loadConfig() HostConfig {\n\trawYaml := readHostfile()\n\tvar result HostConfig\n\terr := yaml.Unmarshal(rawYaml, &result)\n\tif err != nil {\n\t\terrLogger.Fatalln(\"Error parsing hostfile:\", err)\n\t}\n\treturn result\n}\n\nfunc readHostfile() []byte {\n\tconfigFileParam := flag.Arg(0)\n\tfor _, file := range getConfigLocationCandidates(configFileParam) {\n\t\tif exists(file) {\n\t\t\treturn getContents(file)\n\t\t}\n\t}\n\terrLogger.Fatalf(\"hostfile %s not found\", configFileParam)\n\treturn nil\n}\n\nfunc getConfigLocationCandidates(configFileParam string) []string {\n\tconfigRoot, err := os.UserConfigDir()\n\tif err != nil {\n\t\terrLogger.Fatalf(\"no user config dir found\")\n\t}\n\tconfigDir := path.Join(configRoot, CONFIG_SUBDIR)\n\treturn []string{configFileParam,\n\t\tpath.Join(configDir, configFileParam+\".yml\"),\n\t\tpath.Join(configDir, configFileParam+\".yaml\")}\n}\n\n\n\nfunc getContents(filename string) []byte {\n\tfileContents, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\terrLogger.Fatalln(err)\n\t}\n\treturn fileContents\n}\n\nfunc exists(filename string) bool ", "output": "{\n\t_, err := os.Stat(filename)\n\treturn !os.IsNotExist(err)\n}"} {"input": "package stores\n\nimport \"jvmgo/ch06/instructions/base\"\nimport \"jvmgo/ch06/rtda\"\n\n\ntype ISTORE struct{ base.Index8Instruction }\n\nfunc (self *ISTORE) Execute(frame *rtda.Frame) {\n\t_istore(frame, uint(self.Index))\n}\n\ntype ISTORE_0 struct{ base.NoOperandsInstruction }\n\n\n\ntype ISTORE_1 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_1) Execute(frame *rtda.Frame) {\n\t_istore(frame, 1)\n}\n\ntype ISTORE_2 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_2) Execute(frame *rtda.Frame) {\n\t_istore(frame, 2)\n}\n\ntype ISTORE_3 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_3) Execute(frame *rtda.Frame) {\n\t_istore(frame, 3)\n}\n\nfunc _istore(frame *rtda.Frame, index uint) {\n\tval := frame.OperandStack().PopInt()\n\tframe.LocalVars().SetInt(index, val)\n}\n\nfunc (self *ISTORE_0) Execute(frame *rtda.Frame) ", "output": "{\n\t_istore(frame, 0)\n}"} {"input": "package fsrateio\n\nimport (\n\t\"io\"\n\n\t\"github.com/Symantec/Dominator/lib/rateio\"\n\t\"github.com/Symantec/tricorder/go/tricorder\"\n\t\"github.com/Symantec/tricorder/go/tricorder/units\"\n)\n\ntype ReaderContext struct {\n\tmaxBytesPerSecond uint64\n\tmaxBlocksPerSecond uint64\n\tctx *rateio.ReaderContext\n}\n\nfunc NewReaderContext(maxBytesPerSecond uint64,\n\tmaxBlocksPerSecond uint64, speedPercent uint64) *ReaderContext {\n\treturn newReaderContext(maxBytesPerSecond, maxBlocksPerSecond, speedPercent)\n}\n\nfunc (ctx *ReaderContext) GetContext() *rateio.ReaderContext { return ctx.ctx }\n\nfunc (ctx *ReaderContext) NewReader(rd io.Reader) *rateio.Reader {\n\treturn ctx.ctx.NewReader(rd)\n}\n\n\n\nfunc (ctx *ReaderContext) String() string {\n\treturn ctx.format()\n}\n\nfunc (ctx *ReaderContext) RegisterMetrics(dir *tricorder.DirectorySpec) error ", "output": "{\n\tif ctx.maxBlocksPerSecond > 0 {\n\t\treturn ctx.ctx.RegisterMetrics(dir, units.None,\n\t\t\t\"file-system speed in blocks per second\")\n\t}\n\treturn ctx.ctx.RegisterMetrics(dir, units.BytePerSecond,\n\t\t\"file-system speed\")\n}"} {"input": "package tfs\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/richardwilkes/toolbox/errs\"\n)\n\ntype vfs struct {\n\tstorage string\n\tname string\n\toffset int64\n\tlength int64\n\tmode os.FileMode\n\tmodTime time.Time\n\tchildren []*vfs\n}\n\nfunc (v *vfs) Name() string {\n\treturn v.name\n}\n\nfunc (v *vfs) Size() int64 {\n\treturn v.length\n}\n\nfunc (v *vfs) Mode() os.FileMode {\n\treturn v.mode\n}\n\n\n\nfunc (v *vfs) IsDir() bool {\n\treturn (v.mode & os.ModeDir) == os.ModeDir\n}\n\nfunc (v *vfs) Sys() interface{} {\n\treturn nil\n}\n\nfunc (v *vfs) open() (http.File, error) {\n\tif v.IsDir() {\n\t\treturn &vdir{owner: v}, nil\n\t}\n\tf, err := os.Open(v.storage)\n\tif err != nil {\n\t\treturn nil, errs.NewWithCausef(err, \"Unable to open %s\", v.name)\n\t}\n\treturn &vfile{\n\t\towner: v,\n\t\tfile: f,\n\t\tsr: io.NewSectionReader(f, v.offset, v.length),\n\t}, nil\n}\n\nfunc (v *vfs) ModTime() time.Time ", "output": "{\n\treturn v.modTime\n}"} {"input": "package handler\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/go-macaron/binding\"\n)\n\n\n\nfunc requestErrBytes(files []string, err error) (int, []byte) ", "output": "{\n\treqErrs := binding.Errors{\n\t\tbinding.Error{\n\t\t\tFieldNames: files,\n\t\t\tClassification: \"DeserializationError\",\n\t\t\tMessage: err.Error(),\n\t\t},\n\t}\n\terrOutput, _ := json.Marshal(reqErrs)\n\treturn 400, errOutput\n}"} {"input": "package fakes\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"code.google.com/p/go-uuid/uuid\"\n\t. \"github.com/mandarjog/leasedispenser/leasemanager\"\n)\n\ntype MemProvider struct {\n\tDB map[string]ProviderLeaseInfo\n}\n\nfunc NewMemProvider() LeaseProvider {\n\treturn MemProvider{\n\t\tDB: make(map[string]ProviderLeaseInfo),\n\t}\n}\n\n\nfunc (s MemProvider) Info(providerLeaseID string) (info ProviderLeaseInfo, err error) {\n\tvar found bool\n\tif info, found = s.DB[providerLeaseID]; !found {\n\t\terr = errors.New(providerLeaseID + \" was not found\")\n\t}\n\treturn\n}\n\nfunc (s MemProvider) Request(req ProviderLeaseRequest) (info ProviderLeaseInfo, err error) ", "output": "{\n\tproviderLeaseID := uuid.New()\n\tinfo.ProviderLeaseID = providerLeaseID\n\tinfo.StatusCode = LeaseStatusPending\n\tnewinfo := info\n\tnewinfo.StatusCode = LeaseStatusActive\n\tnewinfo.LeaseStartDate = time.Now().UnixNano()\n\tnewinfo.LeaseEndDate = newinfo.LeaseStartDate + req.Duration\n\ts.DB[providerLeaseID] = newinfo\n\treturn\n}"} {"input": "package css\n\ntype Id string\n\n\n\nfunc (id Id) WithPseudoClass(pseudoClass PseudoClass) SelectorWithPseudoClass {\n\treturn SelectorWithPseudoClass{Element: id, PseudoClass: pseudoClass}\n}\n\nfunc (id Id) Style(properties ...Property) RuleSet {\n\treturn For(id).Set(properties...)\n}\n\nfunc (id Id) Selector() string ", "output": "{\n\treturn \"#\" + string(id)\n}"} {"input": "package grpclog \n\nimport \"os\"\n\nvar logger = newLoggerV2()\n\n\nfunc V(l int) bool {\n\treturn logger.V(l)\n}\n\n\nfunc Info(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\nfunc Infof(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\nfunc Infoln(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\n\nfunc Warning(args ...interface{}) {\n\tlogger.Warning(args...)\n}\n\n\nfunc Warningf(format string, args ...interface{}) {\n\tlogger.Warningf(format, args...)\n}\n\n\n\n\n\nfunc Error(args ...interface{}) {\n\tlogger.Error(args...)\n}\n\n\nfunc Errorf(format string, args ...interface{}) {\n\tlogger.Errorf(format, args...)\n}\n\n\nfunc Errorln(args ...interface{}) {\n\tlogger.Errorln(args...)\n}\n\n\n\nfunc Fatal(args ...interface{}) {\n\tlogger.Fatal(args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalf(format string, args ...interface{}) {\n\tlogger.Fatalf(format, args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalln(args ...interface{}) {\n\tlogger.Fatalln(args...)\n\tos.Exit(1)\n}\n\n\n\n\nfunc Print(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\n\n\nfunc Printf(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\n\n\nfunc Println(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\nfunc Warningln(args ...interface{}) ", "output": "{\n\tlogger.Warningln(args...)\n}"} {"input": "package main\n\n\nfunc (b bucketPerms) isValidBucketPERM() bool {\n\tswitch true {\n\tcase b.isPrivate():\n\t\tfallthrough\n\tcase b.isReadOnly():\n\t\tfallthrough\n\tcase b.isPublic():\n\t\tfallthrough\n\tcase b.isAuthorized():\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\ntype bucketPerms string\n\n\nconst (\n\tbucketPrivate = bucketPerms(\"private\")\n\tbucketReadOnly = bucketPerms(\"readonly\")\n\tbucketPublic = bucketPerms(\"public\")\n\tbucketAuthorized = bucketPerms(\"authorized\")\n)\n\nfunc (b bucketPerms) String() string {\n\tif !b.isValidBucketPERM() {\n\t\treturn string(b)\n\t}\n\tif b.isReadOnly() {\n\t\treturn \"public-read\"\n\t}\n\tif b.isPublic() {\n\t\treturn \"public-read-write\"\n\t}\n\tif b.isAuthorized() {\n\t\treturn \"authenticated-read\"\n\t}\n\treturn \"private\"\n}\n\nfunc aclToPerms(acl string) bucketPerms {\n\tswitch acl {\n\tcase \"private\":\n\t\treturn bucketPerms(\"private\")\n\tcase \"public-read\":\n\t\treturn bucketPerms(\"readonly\")\n\tcase \"public-read-write\":\n\t\treturn bucketPerms(\"public\")\n\tcase \"authenticated-read\":\n\t\treturn bucketPerms(\"authorized\")\n\tdefault:\n\t\treturn bucketPerms(acl)\n\t}\n}\n\n\nfunc (b bucketPerms) isPrivate() bool {\n\treturn b == bucketPrivate\n}\n\n\n\n\n\nfunc (b bucketPerms) isPublic() bool {\n\treturn b == bucketPublic\n}\n\n\nfunc (b bucketPerms) isAuthorized() bool {\n\treturn b == bucketAuthorized\n}\n\nfunc (b bucketPerms) isReadOnly() bool ", "output": "{\n\treturn b == bucketReadOnly\n}"} {"input": "package helpers\n\nimport (\n\t\"fmt\"\n\t\"gopkg.in/ini.v1\"\n\t\"runtime\"\n)\n\ntype Distro struct {\n\tFamily string \n\tInitSystem string \n\tVersion string \n}\n\n\nfunc (d *Distro) SetFamily(family string) error {\n\n\tswitch family {\n\tcase \"debian\":\n\t\td.Family = family\n\tcase \"centos\":\n\t\td.Family = family\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown Linux distribution: %s\", family)\n\t}\n\treturn nil\n}\n\n\n\n\n\n\nfunc GetDistro() (*Distro, error) {\n\td := Distro{}\n\tif runtime.GOOS == \"linux\" {\n\t\ti, err := ini.Load([]byte(\"\"), \"/etc/os-release\")\n\t\tsection, err := i.Section(\"\").GetKey(\"ID_LIKE\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = d.SetFamily(section.String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = d.SetInitSystem()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &d, nil\n}\n\nfunc (d *Distro) SetInitSystem() error ", "output": "{\n\n\tswitch d.Family {\n\tcase \"debian\":\n\t\td.InitSystem = \"systemd\" \n\tcase \"centos\":\n\t\td.InitSystem = \"sysv\"\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown Init system for distribution: %s\", d.Family)\n\t}\n\treturn nil\n}"} {"input": "package graph\n\nimport \"fmt\"\n\ntype Graph struct {\n\tconnections []*Graph\n\tValue interface{}\n}\n\nfunc New() *Graph {\n\treturn new(Graph)\n}\n\n\n\nfunc (g *Graph) String() string {\n\treturn fmt.Sprintf(\"%v\", g.Value)\n}\n\nfunc (g *Graph) Connect(h *Graph) ", "output": "{\n\tg.connections = append(g.connections, h)\n\th.connections = append(h.connections, g)\n}"} {"input": "package metrics\n\nimport \"github.com/PagerDuty/godspeed\"\n\nvar Metric Metrics = BlackHole{}\n\ntype Metrics interface {\n\tCount(stat string, count float64, tags []string) error\n\tSet(stat string, value float64, tags []string) error\n}\n\ntype BlackHole struct{}\n\nfunc (b BlackHole) Count(stat string, count float64, tags []string) error {\n\treturn nil\n}\n\nfunc (b BlackHole) Set(stat string, value float64, tags []string) error {\n\treturn nil\n}\n\ntype GodSpeed struct {\n\tIP string\n\tPort int\n\tNameSpace string\n}\n\nfunc (b *GodSpeed) newConn() (*godspeed.Godspeed, error) {\n\tgs, err := godspeed.New(b.IP, b.Port, false)\n\tif err != nil {\n\t\treturn gs, err\n\t}\n\tgs.Namespace = b.NameSpace\n\n\treturn gs, err\n}\n\nfunc (b *GodSpeed) Count(stat string, count float64, tags []string) error {\n\tc, err := b.newConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.Conn.Close()\n\treturn c.Count(stat, count, tags)\n}\n\n\n\nfunc (b *GodSpeed) Set(stat string, value float64, tags []string) error ", "output": "{\n\tc, err := b.newConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.Conn.Close()\n\treturn c.Set(stat, value, tags)\n}"} {"input": "package ipc\n\n\n\n\n\n\n\nimport (\n\t\"errors\"\n\t\"encoding/base64\"\n)\n\nfunc ErrorFromErrorMessage(errorMessage string) error {\n\tif errorMessage == \"\" {\n\t\treturn nil\n\t}\n\n\treturn errors.New(errorMessage)\n}\n\n\n\n\n\n\n\nfunc ErrorFromBase64EncodedErrorMessage(errorMessage64 string) error ", "output": "{\n\tif errorMessage64 == \"\" {\n\t\treturn nil\n\t}\n\n\terrorMessageBytes, err := base64.StdEncoding.DecodeString(errorMessage64)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn errors.New(string(errorMessageBytes))\n}"} {"input": "package binarysearch\n\n\n\nfunc search(s []int, v int) int ", "output": "{\n\tlo, hi := 0, len(s)-1\n\n\tfor lo <= hi {\n\t\tmid := ((hi - lo) >> 1) + lo\n\n\t\tif s[mid] == v {\n\t\t\treturn mid\n\t\t}\n\n\t\tif s[mid] < v {\n\t\t\tlo = mid + 1\n\t\t} else {\n\t\t\thi = mid - 1\n\t\t}\n\t}\n\n\treturn -1\n}"} {"input": "package methods\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestPointString(t *testing.T) ", "output": "{\n\tp := Point{X: 300, Y: 60}\n\tgot := fmt.Sprintf(\"%v\", p)\n\twant := \"point: x=300, y=60\"\n\tif got != want {\n\t\tt.Fatalf(\"got %q, expected %q\", got, want)\n\t}\n}"} {"input": "package gonion\n\nimport (\n\t\"net/http\"\n)\n\n\n\ntype MiddlewareOptions struct {\n\tcomposer *Composer\n\trouteFilter func(*RouteModel) bool\n}\n\n\n\nfunc (mo *MiddlewareOptions) ChainLink(ctor func(http.Handler) http.Handler) {\n\tmo.composer.addMiddleware(ChainLink(ctor), mo.routeFilter)\n}\n\n\n\n\nfunc (mo *MiddlewareOptions) Handler(handler http.Handler) {\n\tmo.composer.addMiddleware(wrap(handler), mo.routeFilter)\n}\n\n\n\nfunc (mo *MiddlewareOptions) Func(handler func(http.ResponseWriter, *http.Request)) {\n\tmo.Handler(http.HandlerFunc(handler))\n}\n\nfunc wrap(handler http.Handler) ChainLink ", "output": "{\n\treturn ChainLink(func(inner http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {\n\t\t\thandler.ServeHTTP(rw, r)\n\t\t\tinner.ServeHTTP(rw, r)\n\t\t})\n\t})\n}"} {"input": "package storage\n\nimport (\n\tastorage \"aqua/common/storage\"\n\t\"aqua/connect_server/config\"\n\n\t\"github.com/foolbread/fbcommon/golog\"\n)\n\nconst default_count = 5\n\nfunc InitStorageManager() {\n\tgolog.Info(\"initing login storage manager...\")\n\tg_storage = newStorageManager()\n\n\tinfos := config.GetConfig().GetSessionDBInfos()\n\tfor k, v := range infos {\n\t\tfor i := 0; i < default_count; i++ {\n\t\t\thnl := astorage.NewStorageHandler(v)\n\t\t\tif hnl != nil {\n\t\t\t\tg_storage.session_storages[k] = append(g_storage.session_storages[k], hnl)\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nfunc GetStorage() *storageManager {\n\treturn g_storage\n}\n\nvar g_storage *storageManager\n\ntype storageManager struct {\n\tsession_storages [][]*astorage.StorageHandler\n}\n\n\n\nfunc (s *storageManager) GetSessionHandler(cid string) *astorage.StorageHandler {\n\tby := astorage.Md5ToByte(cid)\n\tas := s.session_storages[int(by)%len(s.session_storages)]\n\treturn as[int(by)%len(as)]\n}\n\nfunc newStorageManager() *storageManager ", "output": "{\n\tret := new(storageManager)\n\tret.session_storages = make([][]*astorage.StorageHandler, len(config.GetConfig().GetSessionDBInfos()))\n\n\treturn ret\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateNatGatewayRequest struct {\n\n\tCreateNatGatewayDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateNatGatewayRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateNatGatewayRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CreateNatGatewayRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CreateNatGatewayRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateNatGatewayResponse struct {\n\n\tRawResponse *http.Response\n\n\tNatGateway `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateNatGatewayResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response CreateNatGatewayResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package around\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"log\"\n\t\"bytes\"\n\t\"strings\"\n\t\"encoding/json\"\n)\n\nfunc Connect(quit chan int) {\n\tres, err := http.Get(\"https://\"+getApiKey()+\"@streaming.campfirenow.com/room/\"+getRoomId()+\"/live.json\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar buffer bytes.Buffer\n\n\tln := []byte{13}\n\n\tstringLn := string(ln)\n\n\tfor {\n\t\tb := []byte{10}\n\t\t_, err := res.Body.Read(b)\n\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\ts := string(b)\n\n\t\tif s == stringLn {\n\t\t\tline := buffer.String()\n\n\t\t\tif line != \" \" {\n\t\t\t\tdec := json.NewDecoder(strings.NewReader(line))\n\n\t\t\t\tvar message Message\n\n\t\t\t\terr = dec.Decode(&message)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tfmt.Println(message.Body)\n\t\t\t}\n\t\t\tbuffer.Reset()\n\t\t} else {\n\t\t\tbuffer.WriteString(s)\n\t\t}\n\n\t}\n\tquit <- 1\n}\n\n\n\n\n\n\ntype Message struct {\n\tStarred bool\n\tUserId int\n\tRoomId int\n\tId int\n\tBody string\n\tTime string\n}\n\nfunc Speak(words string) ", "output": "{\n\txmlMessage := \"TextMessage\" + words + \"\"\n\txmlReader := strings.NewReader(xmlMessage)\n\n\n\t_, err := http.Post(\"https://\"+getApiKey()+\"@\"+getCampfireDomain()+\"/room/\"+getRoomId()+\"/speak.xml\", \"text/xml\", xmlReader)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"input": "package itsyouonline\n\nimport (\n\t\"net/http\"\n)\n\nconst (\n\tdefaultBaseURI = \"https://itsyou.online/api\"\n)\n\ntype Itsyouonline struct {\n\tclient http.Client\n\tAuthHeader string \n\tBaseURI string\n\tcommon service \n\n\tOrganizations *OrganizationsService\n\tUsers *UsersService\n}\n\ntype service struct {\n\tclient *Itsyouonline\n}\n\n\n\nfunc NewItsyouonline() *Itsyouonline ", "output": "{\n\tc := &Itsyouonline{\n\t\tBaseURI: defaultBaseURI,\n\t\tclient: http.Client{},\n\t}\n\tc.common.client = c\n\n\tc.Organizations = (*OrganizationsService)(&c.common)\n\tc.Users = (*UsersService)(&c.common)\n\n\treturn c\n}"} {"input": "package protocol\n\n\ntype LogoutRequestMessageData struct {\n}\n\n\ntype LogoutRequestMessage struct {\n\tBaseMessage\n\tData LogoutRequestMessageData `json:\"data\"`\n}\n\n\n\n\n\nfunc (m *LogoutRequestMessage) GetType() string {\n\treturn m.Type\n}\n\n\nfunc (m *LogoutRequestMessage) GetSession() string {\n\treturn m.Session\n}\n\n\nfunc (m *LogoutRequestMessage) GetData() interface{} {\n\treturn m.Data\n}\n\n\nfunc (m *LogoutRequestMessage) SetSession(session string) {\n\tm.BaseMessage.Session = session\n}\n\nfunc NewLogoutRequesMessage(session string) *LogoutRequestMessage ", "output": "{\n\tmessage := LogoutRequestMessage{}\n\tmessage.Type = LogoutRequestMessageType\n\tmessage.Session = session\n\treturn &message\n}"} {"input": "package kernel\n\nimport (\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n\t\"reflect\"\n)\n\ntype G struct {\n\tMl map[string]string\n\tInit func(http.ResponseWriter, *http.Request, G)\n\tDefaultHandler func(http.ResponseWriter, *http.Request, G)\n\tEnd func(http.ResponseWriter, *http.Request, G)\n}\n\nfunc (self *G) Go(handler interface{}) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tself.Init(w, r, *self)\n\t\tparams := []reflect.Value{reflect.ValueOf(w), reflect.ValueOf(r), reflect.ValueOf(*self)}\n\t\tprepare := reflect.ValueOf(handler).MethodByName(\"Prepare\")\n\t\tif prepare.IsValid() {\n\t\t\tprepare.Call(params)\n\t\t\tlog.Println(\"start run prepare\")\n\t\t}\n\t\tfn, ok := self.Ml[r.Method]\n\t\tif ok {\n\t\t\tf := reflect.ValueOf(handler).MethodByName(fn)\n\t\t\tif f.IsValid() {\n\t\t\t\tlog.Printf(\"start run %s\", fn)\n\t\t\t\tf.Call(params)\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"not %s method\", fn)\n\t\t\t}\n\t\t} else {\n\t\t\tself.DefaultHandler(w, r, *self)\n\t\t}\n\t\tfinish := reflect.ValueOf(handler).MethodByName(\"Finish\")\n\t\tif finish.IsValid() {\n\t\t\tlog.Println(\"start run finish\")\n\t\t\tfinish.Call(params)\n\t\t}\n\t\tself.End(w, r, *self)\n\t}\n}\n\ntype W struct {\n}\n\n\n\nfunc (self *W) LoadTemplate(s ...string) (*template.Template, error) ", "output": "{\n\treturn template.ParseFiles(s...)\n}"} {"input": "package s3manager\n\nimport (\n\t\"testing\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/awstesting/integration\"\n\t\"github.com/aws/aws-sdk-go/service/s3/s3manager\"\n)\n\n\n\nfunc TestGetBucketRegion(t *testing.T) ", "output": "{\n\texpectRegion := aws.StringValue(integration.Session.Config.Region)\n\n\tctx := aws.BackgroundContext()\n\tregion, err := s3manager.GetBucketRegion(ctx, integration.Session,\n\t\taws.StringValue(bucketName), expectRegion)\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\tif e, a := expectRegion, region; e != a {\n\t\tt.Errorf(\"expect %s bucket region, got %s\", e, a)\n\t}\n}"} {"input": "package google\n\nimport (\n\t\"fmt\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/terraform\"\n\t\"log\"\n)\n\n\n\nfunc migrateNodePoolStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) {\n\tlog.Printf(\"[DEBUG] Attributes before migration: %#v\", is.Attributes)\n\tlog.Printf(\"[DEBUG] ID before migration: %s\", is.ID)\n\n\tis.ID = fmt.Sprintf(\"%s/%s/%s\", is.Attributes[\"zone\"], is.Attributes[\"cluster\"], is.Attributes[\"name\"])\n\n\tlog.Printf(\"[DEBUG] ID after migration: %s\", is.ID)\n\treturn is, nil\n}\n\nfunc resourceContainerNodePoolMigrateState(v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) ", "output": "{\n\tif is.Empty() {\n\t\tlog.Println(\"[DEBUG] Empty InstanceState; nothing to migrate.\")\n\t\treturn is, nil\n\t}\n\n\tswitch v {\n\tcase 0:\n\t\tlog.Println(\"[INFO] Found Container Node Pool State v0; migrating to v1\")\n\t\treturn migrateNodePoolStateV0toV1(is)\n\tdefault:\n\t\treturn is, fmt.Errorf(\"Unexpected schema version: %d\", v)\n\t}\n}"} {"input": "package swagger\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n)\n\nfunc (prop *ModelProperty) setDescription(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"description\"); tag != \"\" {\n\t\tprop.Description = tag\n\t}\n}\n\nfunc (prop *ModelProperty) setDefaultValue(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"default\"); tag != \"\" {\n\t\tprop.DefaultValue = Special(tag)\n\t}\n}\n\nfunc (prop *ModelProperty) setEnumValues(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"enum\"); tag != \"\" {\n\t\tprop.Enum = strings.Split(tag, \"|\")\n\t}\n}\n\nfunc (prop *ModelProperty) setMaximum(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"maximum\"); tag != \"\" {\n\t\tprop.Maximum = tag\n\t}\n}\n\n\n\nfunc (prop *ModelProperty) setUniqueItems(field reflect.StructField) {\n\ttag := field.Tag.Get(\"unique\")\n\tswitch tag {\n\tcase \"true\":\n\t\tv := true\n\t\tprop.UniqueItems = &v\n\tcase \"false\":\n\t\tv := false\n\t\tprop.UniqueItems = &v\n\t}\n}\n\nfunc (prop *ModelProperty) setPropertyMetadata(field reflect.StructField) {\n\tprop.setDescription(field)\n\tprop.setEnumValues(field)\n\tprop.setMinimum(field)\n\tprop.setMaximum(field)\n\tprop.setUniqueItems(field)\n\tprop.setDefaultValue(field)\n}\n\nfunc (prop *ModelProperty) setMinimum(field reflect.StructField) ", "output": "{\n\tif tag := field.Tag.Get(\"minimum\"); tag != \"\" {\n\t\tprop.Minimum = tag\n\t}\n}"} {"input": "package classify\n\nimport \"github.com/deathly809/gotypes\"\n\n\ntype Classifier interface {\n\tClassify([]gotypes.Value) float32\n}\n\n\n\ntype NaiveData struct {\n\tVal []gotypes.Value\n\tCla float32\n}\n\n\n\n\n\nfunc (nData *NaiveData) Class() float32 {\n\treturn nData.Cla\n}\n\n\ntype Data interface {\n\tValue() []gotypes.Value\n\tClass() float32\n}\n\n\ntype Kernel interface {\n\tDot([]gotypes.Value, []gotypes.Value) float32\n}\n\nfunc (nData *NaiveData) Value() []gotypes.Value ", "output": "{\n\treturn nData.Val\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"github.com/docker/distribution/registry/api/errcode\"\n\t\"github.com/docker/distribution/registry/api/v2\"\n)\n\n\n\ntype UnexpectedHTTPStatusError struct {\n\tStatus string\n}\n\nfunc (e *UnexpectedHTTPStatusError) Error() string {\n\treturn fmt.Sprintf(\"Received unexpected HTTP status: %s\", e.Status)\n}\n\n\n\ntype UnexpectedHTTPResponseError struct {\n\tParseErr error\n\tResponse []byte\n}\n\nfunc (e *UnexpectedHTTPResponseError) Error() string {\n\treturn fmt.Sprintf(\"Error parsing HTTP response: %s: %q\", e.ParseErr.Error(), string(e.Response))\n}\n\nfunc parseHTTPErrorResponse(r io.Reader) error {\n\tvar errors errcode.Errors\n\tbody, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(body, &errors); err != nil {\n\t\treturn &UnexpectedHTTPResponseError{\n\t\t\tParseErr: err,\n\t\t\tResponse: body,\n\t\t}\n\t}\n\treturn errors\n}\n\n\n\nfunc handleErrorResponse(resp *http.Response) error ", "output": "{\n\tif resp.StatusCode == 401 {\n\t\terr := parseHTTPErrorResponse(resp.Body)\n\t\tif uErr, ok := err.(*UnexpectedHTTPResponseError); ok {\n\t\t\treturn v2.ErrorCodeUnauthorized.WithDetail(uErr.Response)\n\t\t}\n\t\treturn err\n\t}\n\tif resp.StatusCode >= 400 && resp.StatusCode < 500 {\n\t\treturn parseHTTPErrorResponse(resp.Body)\n\t}\n\treturn &UnexpectedHTTPStatusError{Status: resp.Status}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"time\"\n)\n\nvar ACTION_POTENTIAL_THRESHOLD int = 30\nvar DELAY_BETWEEN_FIRINGS time.Duration = 10\nvar SIGNAL_BUFFER_SIZE = 2048\n\ntype Neuron struct {\n\ttag string\n\tdendrite chan int \n\tsynapses []Synapse \n\tpotential int\n}\n\n\n\nfunc (n *Neuron) HasReachedThreshold() bool {\n\treturn n.potential > ACTION_POTENTIAL_THRESHOLD\n}\n\nfunc (n *Neuron) Listen() {\n\tfor actionPotential := range n.dendrite {\n\t\tn.potential += actionPotential\n\t\tif n.HasReachedThreshold() {\n\t\t\tn.Fire()\n\t\t}\n\t}\n}\n\nfunc (n *Neuron) AddSynapse(destination *Neuron, weight int) {\n\tn.synapses = append(n.synapses, Synapse{destination.dendrite, weight})\n}\n\nfunc NewNeuron(tag string) Neuron {\n\treturn Neuron{tag, make(chan int, SIGNAL_BUFFER_SIZE), []Synapse{}, 0}\n}\n\nfunc (n *Neuron) Fire() ", "output": "{\n\tlog.Println(n.tag, \"Fired\")\n\tn.potential = 0\n\tfor _, synapse := range n.synapses {\n\t\tselect {\n\t\tcase synapse.channel <- synapse.weight:\n\t\tdefault:\n\t\t\tlog.Println(\"Signal from\", n.tag, \"dropped\")\n\t\t}\n\t\ttime.Sleep(DELAY_BETWEEN_FIRINGS * time.Millisecond)\n\t}\n}"} {"input": "package day09\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestFirstInvalidValue(t *testing.T) {\n\tsequence := []int{35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576}\n\tvalue, err := FirstInvalidValue(sequence, 5)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 127, value)\n}\n\nfunc TestFindContiguousSum(t *testing.T) {\n\tsequence := []int{35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576}\n\tstart, end, err := FindContiguousSum(sequence, 127)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 2, start)\n\trequire.Equal(t, 5, end)\n}\n\nfunc TestFindWeakness(t *testing.T) {\n\tsequence := []int{35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576}\n\tvalue, err := FindWeakness(sequence, 127)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 62, value)\n}\n\nfunc TestIsValid(t *testing.T) ", "output": "{\n\tsequence := make([]int, 25)\n\tfor i := 0; i < 25; i++ {\n\t\tsequence[i] = i + 1\n\t}\n\n\trequire.True(t, IsValid(sequence, 26))\n\trequire.True(t, IsValid(sequence, 49))\n\trequire.False(t, IsValid(sequence, 100))\n\trequire.False(t, IsValid(sequence, 50))\n}"} {"input": "package ansiwriter\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype Modifier func() string\n\nfunc escapeANSI(code int) string {\n\treturn fmt.Sprintf(\"\\033[%dm\", code)\n}\n\nfunc Bold() string { return escapeANSI(1) }\nfunc Black() string { return escapeANSI(30) }\n\nfunc Green() string { return escapeANSI(32) }\nfunc Yellow() string { return escapeANSI(33) }\nfunc Blue() string { return escapeANSI(34) }\nfunc Magenta() string { return escapeANSI(35) }\nfunc Cyan() string { return escapeANSI(36) }\nfunc White() string { return escapeANSI(37) }\n\ntype awr struct {\n\tio.Writer\n\tmodifiers []Modifier\n}\n\n\n\n\nfunc New(w io.Writer, mods ...Modifier) io.Writer {\n\treturn awr{w, mods}\n}\n\nfunc (a awr) Write(b []byte) (n int, err error) {\n\tfor _, mod := range a.modifiers {\n\t\ta.Writer.Write([]byte(mod()))\n\t}\n\tn, err = a.Writer.Write(b)\n\t_, _ = a.Writer.Write([]byte(\"\\033[0m\"))\n\treturn\n}\n\nfunc Red() string ", "output": "{ return escapeANSI(31) }"} {"input": "package v2store_test\n\nimport (\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"github.com/coreos/etcd/clientv3\"\n\t\"github.com/coreos/etcd/etcdserver/api/v2v3\"\n\t\"github.com/coreos/etcd/etcdserver/v2store\"\n\t\"github.com/coreos/etcd/integration\"\n\n\t\"github.com/coreos/pkg/capnslog\"\n\t\"google.golang.org/grpc/grpclog\"\n)\n\nfunc init() {\n\tcapnslog.SetGlobalLogLevel(capnslog.CRITICAL)\n\tclientv3.SetLogger(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, ioutil.Discard))\n}\n\ntype v2v3TestStore struct {\n\tv2store.Store\n\tclus *integration.ClusterV3\n\tt *testing.T\n}\n\nfunc (s *v2v3TestStore) Close() { s.clus.Terminate(s.t) }\n\n\n\nfunc newTestStore(t *testing.T, ns ...string) StoreCloser ", "output": "{\n\tclus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})\n\treturn &v2v3TestStore{\n\t\tv2v3.NewStore(clus.Client(0), \"/v2/\"),\n\t\tclus,\n\t\tt,\n\t}\n}"} {"input": "package gotify\n\nimport (\n\t\"github.com/antonholmquist/jason\"\n)\n\nfunc parseAlbum(o *jason.Object) Album {\n\talbumName, _ := o.GetString(\"name\")\n\talbumUri, _ := o.GetString(\"uri\")\n\n\talbum := Album{albumName, albumUri}\n\n\treturn album\n}\n\nfunc parseArtist(o *jason.Object) Artist {\n\tartistName, _ := o.GetString(\"name\")\n\tartistUri, _ := o.GetString(\"uri\")\n\n\tartist := Artist{artistName, artistUri}\n\n\treturn artist\n}\n\nfunc parseTrack(o *jason.Object) Track {\n\ttrackName, _ := o.GetString(\"name\")\n\ttrackUri, _ := o.GetString(\"uri\")\n\n\tjsonAlbum, err := o.GetObject(\"album\")\n\n\tvar album Album\n\tif err == nil {\n\t\talbum = parseAlbum(jsonAlbum)\n\t}\n\n\tjsonArtists, err := o.GetObjectArray(\"artists\")\n\n\tvar artists []Artist\n\tif err == nil {\n\t\tartists = parseArtists(jsonArtists)\n\t}\n\n\ttrack := Track{trackName, trackUri, album, artists}\n\n\treturn track\n}\n\nfunc parseTracks(o []*jason.Object) []Track {\n\ttracks := []Track{}\n\n\tfor _, jsonTrack := range o {\n\t\ttracks = append(tracks, parseTrack(jsonTrack))\n\t}\n\n\treturn tracks\n}\n\nfunc parseAlbums(o []*jason.Object) []Album {\n\talbums := []Album{}\n\n\tfor _, jsonAlbum := range o {\n\t\talbums = append(albums, parseAlbum(jsonAlbum))\n\t}\n\n\treturn albums\n}\n\n\n\nfunc parsePlaylist(o *jason.Object) SpotifyPlaylist {\n\treturn SpotifyPlaylist{}\n}\n\nfunc parseArtists(o []*jason.Object) []Artist ", "output": "{\n\tartists := []Artist{}\n\n\tfor _, jsonArtist := range o {\n\t\tartists = append(artists, parseArtist(jsonArtist))\n\t}\n\n\treturn artists\n}"} {"input": "package leader\n\nimport (\n\t\"time\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n)\n\ntype poller struct {\n\tleaderChan chan Leadership\n\tpollInterval time.Duration\n\ttick <-chan time.Time\n\tstop chan struct{}\n\tpollFunc CheckLeaderFunc\n}\n\n\nfunc NewPoller(pollInterval time.Duration, f CheckLeaderFunc) Detector {\n\treturn &poller{\n\t\tpollInterval: pollInterval,\n\t\ttick: time.Tick(pollInterval),\n\t\tpollFunc: f,\n\t}\n}\n\n\n\n\n\nfunc (l *poller) Stop() {\n\tif l.stop != nil {\n\t\tclose(l.stop)\n\t}\n}\n\nfunc (l *poller) poll() {\n\tfor {\n\t\tselect {\n\n\t\tcase <-l.tick:\n\n\t\t\tisLeader, err := l.pollFunc()\n\t\t\tevent := Leadership{}\n\t\t\tif err != nil {\n\t\t\t\tevent.Status = Unknown\n\t\t\t\tevent.Error = err\n\t\t\t} else {\n\t\t\t\tif isLeader {\n\t\t\t\t\tevent.Status = Leader\n\t\t\t\t} else {\n\t\t\t\t\tevent.Status = NotLeader\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tl.leaderChan <- event\n\n\t\tcase <-l.stop:\n\t\t\tlog.Infoln(\"Stopping leadership check\")\n\t\t\tclose(l.leaderChan)\n\t\t\tl.leaderChan = nil\n\t\t\tl.stop = nil\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (l *poller) Start() (<-chan Leadership, error) ", "output": "{\n\tif l.leaderChan != nil {\n\t\treturn l.leaderChan, nil\n\t}\n\n\tl.leaderChan = make(chan Leadership)\n\tl.stop = make(chan struct{})\n\n\tgo l.poll()\n\treturn l.leaderChan, nil\n}"} {"input": "package pow\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/DanielKrawisz/bmutil\"\n)\n\n\ntype Data struct {\n\tNonceTrialsPerByte uint64\n\tExtraBytes uint64\n}\n\n\n\n\n\nfunc (pd *Data) Decode(r io.Reader) (err error) {\n\tpd.NonceTrialsPerByte, err = bmutil.ReadVarInt(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpd.ExtraBytes, err = bmutil.ReadVarInt(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (pd *Data) String() string {\n\treturn fmt.Sprintf(\"{%d, %d}\", pd.NonceTrialsPerByte, pd.ExtraBytes)\n}\n\nfunc (pd *Data) Encode(w io.Writer) error ", "output": "{\n\tif err := bmutil.WriteVarInt(w, pd.NonceTrialsPerByte); err != nil {\n\t\treturn err\n\t}\n\n\tif err := bmutil.WriteVarInt(w, pd.ExtraBytes); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package customer\n\nimport (\n\t\"testing\"\n\n\tassert \"github.com/stretchr/testify/require\"\n\tstripe \"github.com/stripe/stripe-go\"\n\t_ \"github.com/stripe/stripe-go/testing\"\n)\n\n\n\nfunc TestCustomerGet(t *testing.T) {\n\tcustomer, err := Get(\"cus_123\", nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerList(t *testing.T) {\n\ti := List(&stripe.CustomerListParams{})\n\n\tassert.True(t, i.Next())\n\tassert.Nil(t, i.Err())\n\tassert.NotNil(t, i.Customer())\n}\n\nfunc TestCustomerNew(t *testing.T) {\n\tcustomer, err := New(&stripe.CustomerParams{\n\t\tEmail: stripe.String(\"foo@example.com\"),\n\t\tShipping: &stripe.CustomerShippingDetailsParams{\n\t\t\tAddress: &stripe.AddressParams{\n\t\t\t\tLine1: stripe.String(\"line1\"),\n\t\t\t\tCity: stripe.String(\"city\"),\n\t\t\t},\n\t\t\tName: stripe.String(\"name\"),\n\t\t},\n\t})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerNew_NilParams(t *testing.T) {\n\tcustomer, err := New(nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerUpdate(t *testing.T) {\n\tcustomer, err := Update(\"cus_123\", &stripe.CustomerParams{\n\t\tEmail: stripe.String(\"foo@example.com\"),\n\t})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerDel(t *testing.T) ", "output": "{\n\tcustomer, err := Del(\"cus_123\", nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}"} {"input": "package iso\n\nimport (\n\t\"fmt\"\n\t\"github.com/mitchellh/multistep\"\n\tparallelscommon \"github.com/mitchellh/packer/builder/parallels/common\"\n\t\"github.com/mitchellh/packer/packer\"\n\t\"strconv\"\n)\n\n\n\ntype stepCreateDisk struct{}\n\n\n\nfunc (s *stepCreateDisk) Cleanup(state multistep.StateBag) {}\n\nfunc (s *stepCreateDisk) Run(state multistep.StateBag) multistep.StepAction ", "output": "{\n\tconfig := state.Get(\"config\").(*config)\n\tdriver := state.Get(\"driver\").(parallelscommon.Driver)\n\tui := state.Get(\"ui\").(packer.Ui)\n\tvmName := state.Get(\"vmName\").(string)\n\n\tcommand := []string{\n\t\t\"set\", vmName,\n\t\t\"--device-set\", \"hdd0\",\n\t\t\"--size\", strconv.FormatUint(uint64(config.DiskSize), 10),\n\t\t\"--iface\", config.HardDriveInterface,\n\t}\n\n\tui.Say(\"Creating hard drive...\")\n\terr := driver.Prlctl(command...)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"Error creating hard drive: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\treturn multistep.ActionContinue\n}"} {"input": "package stream\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nvar debugEnabled bool = false\n\nfunc init() {\n\tif os.Getenv(\"ZREPL_RPC_DATACONN_STREAM_DEBUG\") != \"\" {\n\t\tdebugEnabled = true\n\t}\n}\n\n\n\n\nfunc debug(format string, args ...interface{}) ", "output": "{\n\tif debugEnabled {\n\t\tfmt.Fprintf(os.Stderr, \"rpc/dataconn/stream: %s\\n\", fmt.Sprintf(format, args...))\n\t}\n}"} {"input": "package etsi\n\nimport (\n\t\"encoding/asn1\"\n\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/util\"\n)\n\ntype qcStatemQcSscdValid struct{}\n\n\n\nfunc (this *qcStatemQcSscdValid) getStatementOid() *asn1.ObjectIdentifier {\n\treturn &util.IdEtsiQcsQcSSCD\n}\n\nfunc (l *qcStatemQcSscdValid) Initialize() error {\n\treturn nil\n}\n\nfunc (l *qcStatemQcSscdValid) CheckApplies(c *x509.Certificate) bool {\n\tif !util.IsExtInCert(c, util.QcStateOid) {\n\t\treturn false\n\t}\n\tif util.ParseQcStatem(util.GetExtFromCert(c, util.QcStateOid).Value, *l.getStatementOid()).IsPresent() {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l *qcStatemQcSscdValid) Execute(c *x509.Certificate) *lint.LintResult {\n\n\terrString := \"\"\n\text := util.GetExtFromCert(c, util.QcStateOid)\n\ts := util.ParseQcStatem(ext.Value, *l.getStatementOid())\n\terrString += s.GetErrorInfo()\n\n\tif len(errString) == 0 {\n\t\treturn &lint.LintResult{Status: lint.Pass}\n\t} else {\n\t\treturn &lint.LintResult{Status: lint.Error, Details: errString}\n\t}\n}\n\nfunc init() ", "output": "{\n\tlint.RegisterLint(&lint.Lint{\n\t\tName: \"e_qcstatem_qcsscd_valid\",\n\t\tDescription: \"Checks that a QC Statement of the type id-etsi-qcs-QcSSCD has the correct form\",\n\t\tCitation: \"ETSI EN 319 412 - 5 V2.2.1 (2017 - 11) / Section 4.2.2\",\n\t\tSource: lint.EtsiEsi,\n\t\tEffectiveDate: util.EtsiEn319_412_5_V2_2_1_Date,\n\t\tLint: &qcStatemQcSscdValid{},\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n\n\t\"github.com/n0rad/go-erlog/errs\"\n)\n\ntype envMap struct {\n\tmapping map[string]string\n}\n\n\n\nfunc (e *envMap) String() string {\n\treturn strings.Join(e.Strings(), \"\\n\")\n}\n\nfunc (e *envMap) Strings() []string {\n\tvar env []string\n\tfor n, v := range e.mapping {\n\t\tenv = append(env, n+\"=\"+v)\n\t}\n\treturn env\n}\n\nfunc (e *envMap) Type() string {\n\treturn \"envMap\"\n}\n\nfunc (e *envMap) Set(s string) error ", "output": "{\n\tif e.mapping == nil {\n\t\te.mapping = make(map[string]string)\n\t}\n\tpair := strings.SplitN(s, \"=\", 2)\n\tif len(pair) != 2 {\n\t\treturn errs.With(\"environment variable must be specified as name=value\")\n\t}\n\te.mapping[pair[0]] = pair[1]\n\treturn nil\n}"} {"input": "package rpc\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\n\t\"github.com/ugorji/go/codec\"\n)\n\ntype packetizer interface {\n\tNextFrame() (rpcMessage, error)\n}\n\ntype packetHandler struct {\n\tdec decoder\n\treader io.Reader\n\tframeDecoder *decoderWrapper\n\tprotocols *protocolHandler\n\tcalls *callContainer\n}\n\n\n\nfunc (p *packetHandler) NextFrame() (rpcMessage, error) {\n\tbytes, err := p.loadNextFrame()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(bytes) < 1 {\n\t\treturn nil, NewPacketizerError(\"invalid frame size: %d\", len(bytes))\n\t}\n\n\tnb := int(bytes[0])\n\n\tif nb < 0x91 || nb > 0x9f {\n\t\treturn nil, NewPacketizerError(\"wrong message structure prefix (%d)\", nb)\n\t}\n\tp.frameDecoder.ResetBytes(bytes[1:])\n\n\treturn decodeRPC(nb-0x90, p.frameDecoder, p.protocols, p.calls)\n}\n\nfunc (p *packetHandler) loadNextFrame() ([]byte, error) {\n\tvar l int\n\tif err := p.dec.Decode(&l); err != nil {\n\t\tif _, ok := err.(*net.OpError); ok {\n\t\t\treturn nil, io.EOF\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tbytes := make([]byte, l)\n\tlenRead, err := io.ReadFull(p.reader, bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif lenRead != l {\n\t\treturn nil, fmt.Errorf(\"Unable to read desired length. Desired: %d, actual: %d\", l, lenRead)\n\t}\n\treturn bytes, nil\n}\n\nfunc newPacketHandler(reader io.Reader, protocols *protocolHandler, calls *callContainer) *packetHandler ", "output": "{\n\treturn &packetHandler{\n\t\treader: reader,\n\t\tdec: codec.NewDecoder(reader, newCodecMsgpackHandle()),\n\t\tframeDecoder: newDecoderWrapper(),\n\t\tprotocols: protocols,\n\t\tcalls: calls,\n\t}\n}"} {"input": "package cryptoutil\n\nimport (\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\t\"crypto/rand\"\n)\n\n\n\nfunc SymmetricEncrypt(ciph cipher.Block, src []byte) []byte {\n\tiv := make([]byte, aes.BlockSize, aes.BlockSize)\n\t_, err := rand.Read(iv)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tencryptedIv := make([]byte, aes.BlockSize, aes.BlockSize)\n\tnewECBEncrypter(ciph).CryptBlocks(encryptedIv, iv)\n\n\tencrypted := padPKCS7WithIV(src)\n\tcopy(encrypted, encryptedIv)\n\tcipher.NewCBCEncrypter(ciph, iv).CryptBlocks(encrypted[aes.BlockSize:], encrypted[aes.BlockSize:])\n\treturn encrypted\n}\n\n\n\n\n\nfunc SymmetricDecrypt(ciph cipher.Block, src []byte) []byte ", "output": "{\n\tiv := src[:aes.BlockSize]\n\tnewECBDecrypter(ciph).CryptBlocks(iv, iv)\n\n\tdata := src[aes.BlockSize:]\n\tcipher.NewCBCDecrypter(ciph, iv).CryptBlocks(data, data)\n\n\treturn unpadPKCS7(data)\n}"} {"input": "package swarm\n\nimport (\n\t\"strings\"\n)\n\n\n\n\n\nfunc convertMapToKVStrings(values map[string]string) []string {\n\tresult := make([]string, len(values))\n\ti := 0\n\tfor key, value := range values {\n\t\tresult[i] = key + \"=\" + value\n\t\ti++\n\t}\n\treturn result\n}\n\nfunc convertKVStringsToMap(values []string) map[string]string ", "output": "{\n\tresult := make(map[string]string, len(values))\n\tfor _, value := range values {\n\t\tkv := strings.SplitN(value, \"=\", 2)\n\t\tif len(kv) == 1 {\n\t\t\tresult[kv[0]] = \"\"\n\t\t} else {\n\t\t\tresult[kv[0]] = kv[1]\n\t\t}\n\t}\n\n\treturn result\n}"} {"input": "package fuzzer\n\nimport (\n\t\"testing\"\n\n\t\"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/scheme\"\n\n\t\"k8s.io/apimachinery/pkg/api/apitesting/roundtrip\"\n)\n\n\n\nfunc TestRoundTripTypes(t *testing.T) ", "output": "{\n\troundtrip.RoundTripTestForAPIGroup(t, scheme.AddToScheme, Funcs)\n}"} {"input": "package local\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/grafana/loki/pkg/storage/chunk\"\n)\n\ntype TableClient struct {\n\tdirectory string\n}\n\n\nfunc NewTableClient(directory string) (chunk.TableClient, error) {\n\treturn &TableClient{directory: directory}, nil\n}\n\nfunc (c *TableClient) ListTables(ctx context.Context) ([]string, error) {\n\tboltDbFiles := []string{}\n\terr := filepath.Walk(c.directory, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\tboltDbFiles = append(boltDbFiles, info.Name())\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn boltDbFiles, nil\n}\n\nfunc (c *TableClient) CreateTable(ctx context.Context, desc chunk.TableDesc) error {\n\tfile, err := os.OpenFile(filepath.Join(c.directory, desc.Name), os.O_CREATE|os.O_RDONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn file.Close()\n}\n\nfunc (c *TableClient) DeleteTable(ctx context.Context, name string) error {\n\treturn os.Remove(filepath.Join(c.directory, name))\n}\n\n\n\nfunc (c *TableClient) UpdateTable(ctx context.Context, current, expected chunk.TableDesc) error {\n\treturn nil\n}\n\nfunc (*TableClient) Stop() {}\n\nfunc (c *TableClient) DescribeTable(ctx context.Context, name string) (desc chunk.TableDesc, isActive bool, err error) ", "output": "{\n\treturn chunk.TableDesc{\n\t\tName: name,\n\t}, true, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/polariseye/polarserver/common\"\n\t\"github.com/polariseye/polarserver/common/errorCode\"\n\t\"github.com/polariseye/polarserver/moduleManage\"\n)\n\ntype testStruct struct {\n\tclassName string\n}\n\nvar TestBLL *testStruct\n\nfunc init() {\n\tTestBLL = NewTestStruct()\n\tmoduleManage.RegisterModule(func() (moduleManage.IModule, moduleManage.ModuleType) {\n\t\treturn NewTestStruct(), moduleManage.NormalModule\n\t})\n}\n\n\nfunc (this *testStruct) Name() string {\n\treturn this.className\n}\n\n\n\nfunc (this *testStruct) CheckModule() []error {\n\tfmt.Println(\"check\")\n\n\treturn nil\n}\n\nfunc (this *testStruct) ConvertModule() []error {\n\tfmt.Println(\"数据转换\")\n\n\treturn nil\n}\n\n\nfunc (this *testStruct) C_Hello(request *common.RequestModel, d int, name string) *common.ResultModel {\n\tresult := common.NewResultModel(errorCode.ClientDataError)\n\n\tresult.Value[\"Hello\"] = name + \"_\" + this.Name()\n\tresult.Value[\"Extra\"] = d\n\n\tresult.SetNormalError(errorCode.Success)\n\treturn result\n}\n\nfunc NewTestStruct() *testStruct {\n\treturn &testStruct{\n\t\tclassName: \"TestBLL\",\n\t}\n}\n\nfunc (this *testStruct) InitModule() []error ", "output": "{\n\tfmt.Println(\"初始化\")\n\n\treturn nil\n}"} {"input": "package decorators\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\ntype jiraIssueConfig struct {\n\tCREDENTIALS struct {\n\t\tUSERNAME string\n\t\tPASSWORD string\n\t}\n\tENDPOINT struct {\n\t\tURL string\n\t}\n\tKEYS map[string]struct {\n\t\tDESTKEY string\n\t\tFIELD string\n\t}\n}\n\n\ntype jiraIssue struct {\n\tclient http.Client\n\tconfig jiraIssueConfig\n}\n\n\n\nfunc newJiraIssue(config jiraIssueConfig) Decorater {\n\treturn jiraIssue{http.Client{}, config}\n}\n\nfunc (j jiraIssue) Decorate(commitMap *map[string]interface{}) (*map[string]interface{}, error) ", "output": "{\n\tvar ID string\n\n\tswitch v := (*commitMap)[\"jiraIssueId\"].(type) {\n\tcase string:\n\t\tID = v\n\tcase int64:\n\t\tID = fmt.Sprintf(\"%d\", v)\n\tdefault:\n\t\treturn commitMap, nil\n\t}\n\n\tif ID == \"\" {\n\t\treturn commitMap, nil\n\t}\n\n\treq, err := http.NewRequest(\"GET\", fmt.Sprintf(\"%s/rest/api/2/issue/%s\", j.config.ENDPOINT.URL, ID), nil)\n\n\tif err != nil {\n\t\treturn commitMap, err\n\t}\n\n\treq.SetBasicAuth(j.config.CREDENTIALS.USERNAME, j.config.CREDENTIALS.PASSWORD)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\treturn jSONResponse{&j.client, req, j.config.KEYS}.Decorate(commitMap)\n}"} {"input": "package json\n\nimport \"encoding/json\"\nimport \"net/http\"\n\n\n\n\n\nfunc Struct(writer http.ResponseWriter, request *http.Request, data interface{}, indent bool) {\n\n \n writer.Header().Set(\"Content-Type\", \"application/json\")\n\n \n type SimpleResponse struct {\n Data interface {}\n }\n\n res := SimpleResponse {\n Data: data,\n }\n\n var result []byte\n var error error\n\n if indent {\n result, error = json.MarshalIndent(res, \"\", \"\")\n } else {\n result, error = json.Marshal(res)\n }\n\n if error == nil {\n \n writer.Write([]byte(result))\n } else {\n writer.Write([]byte(\"Error\"))\n }\n}\n\nfunc String(writer http.ResponseWriter, request *http.Request, data string) ", "output": "{\n\n \n writer.Header().Set(\"Content-Type\", \"application/json\")\n\n \n type SimpleResponse struct {\n Data string\n }\n\n res := SimpleResponse {\n Data: data,\n }\n\n result, error := json.Marshal(res)\n\n if error == nil {\n \n writer.Write([]byte(result))\n } else {\n writer.Write([]byte(\"Error\"))\n }\n}"} {"input": "package stripe\n\n\n\ntype TopupParams struct {\n\tParams `form:\"*\"`\n\tAmount *int64 `form:\"amount\"`\n\tCurrency *string `form:\"currency\"`\n\tDescription *string `form:\"description\"`\n\tSource *SourceParams `form:\"*\"` \n\tStatementDescriptor *string `form:\"statement_descriptor\"`\n\tTransferGroup *string `form:\"transfer_group\"`\n}\n\n\n\n\n\n\n\ntype TopupListParams struct {\n\tListParams `form:\"*\"`\n\tCreated *int64 `form:\"created\"`\n\tCreatedRange *RangeQueryParams `form:\"created\"`\n}\n\n\ntype TopupList struct {\n\tListMeta\n\tData []*Topup `json:\"data\"`\n}\n\n\n\ntype Topup struct {\n\tAmount int64 `json:\"amount\"`\n\tArrivalDate int64 `json:\"arrival_date\"`\n\tBalanceTransaction *BalanceTransaction `json:\"balance_transaction\"`\n\tCreated int64 `json:\"created\"`\n\tCurrency Currency `json:\"currency\"`\n\tDescription string `json:\"description\"`\n\tExpectedAvailabilityDate int64 `json:\"expected_availability_date\"`\n\tFailureCode string `json:\"failure_code\"`\n\tFailureMessage string `json:\"failure_message\"`\n\tID string `json:\"id\"`\n\tLivemode bool `json:\"livemode\"`\n\tSource *PaymentSource `json:\"source\"`\n\tStatementDescriptor string `json:\"statement_descriptor\"`\n\tStatus string `json:\"status\"`\n\tTransferGroup string `json:\"transfer_group\"`\n}\n\nfunc (p *TopupParams) SetSource(sp interface{}) error ", "output": "{\n\tsource, err := SourceParamsFor(sp)\n\tp.Source = source\n\treturn err\n}"} {"input": "package iso20022\n\n\ntype ATMTransactionAmounts6 struct {\n\n\tCurrency *ActiveCurrencyCode `xml:\"Ccy,omitempty\"`\n\n\tMaximumPossibleAmount *ImpliedCurrencyAndAmount `xml:\"MaxPssblAmt,omitempty\"`\n\n\tMinimumPossibleAmount *ImpliedCurrencyAndAmount `xml:\"MinPssblAmt,omitempty\"`\n\n\tAdditionalAmount []*ATMTransactionAmounts7 `xml:\"AddtlAmt,omitempty\"`\n}\n\nfunc (a *ATMTransactionAmounts6) SetCurrency(value string) {\n\ta.Currency = (*ActiveCurrencyCode)(&value)\n}\n\nfunc (a *ATMTransactionAmounts6) SetMaximumPossibleAmount(value, currency string) {\n\ta.MaximumPossibleAmount = NewImpliedCurrencyAndAmount(value, currency)\n}\n\n\n\nfunc (a *ATMTransactionAmounts6) AddAdditionalAmount() *ATMTransactionAmounts7 {\n\tnewValue := new(ATMTransactionAmounts7)\n\ta.AdditionalAmount = append(a.AdditionalAmount, newValue)\n\treturn newValue\n}\n\nfunc (a *ATMTransactionAmounts6) SetMinimumPossibleAmount(value, currency string) ", "output": "{\n\ta.MinimumPossibleAmount = NewImpliedCurrencyAndAmount(value, currency)\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/mexisme/go-config/settings\"\n)\n\n\nfunc AddConfigItems(configKeys []string) {\n\tsettings.AddConfigItems(configKeys)\n}\n\n\nfunc AddConfigItemsWithPFlags(configKeys []string) error {\n\treturn settings.AddConfigItemsWithPFlags(configKeys)\n}\n\n\nfunc ApplyWith(key string, f func(interface{})) {\n\tsettings.ApplyWith(key, f)\n}\n\n\nfunc Get(key string) interface{} {\n\treturn settings.Get(key)\n}\n\n\nfunc GetBool(key string) bool {\n\treturn settings.GetBool(key)\n}\n\n\nfunc GetFloat64(key string) float64 {\n\treturn settings.GetFloat64(key)\n}\n\n\nfunc GetInt(key string) int {\n\treturn settings.GetInt(key)\n}\n\n\nfunc GetString(key string) string {\n\treturn settings.GetString(key)\n}\n\n\nfunc GetStringMap(key string) map[string]interface{} {\n\treturn settings.GetStringMap(key)\n}\n\n\n\n\n\nfunc GetStringSlice(key string) []string {\n\treturn settings.GetStringSlice(key)\n}\n\n\nfunc GetTime(key string) time.Time {\n\treturn settings.GetTime(key)\n}\n\n\nfunc GetDuration(key string) time.Duration {\n\treturn settings.GetDuration(key)\n}\n\n\nfunc IsSet(key string) bool {\n\treturn settings.IsSet(key)\n}\n\n\nfunc AllSettings() map[string]interface{} {\n\treturn settings.AllSettings()\n}\n\nfunc GetStringMapString(key string) map[string]string ", "output": "{\n\treturn settings.GetStringMapString(key)\n}"} {"input": "package cache\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\ntype DeployInfo struct {\n\tUserName string `json:\"userName\"`\n\tDcName string `json:\"dcName\"`\n\tDcID int32 `json:\"dcId\"`\n\tOrgName string `json:\"orgName\"`\n\tDeploymentName string `json:\"deploymentName\"`\n\tUpdateTime string `json:\"updateTime\"`\n}\n\ntype Deploy struct {\n\tData []DeployInfo `json:\"data\"`\n}\n\n\n\ntype Indexer struct {\n\tIndex string\n\tKey string\n}\n\nfunc (deploy *Deploy) Unmarshal(content *[]byte) error ", "output": "{\n\n\terr := json.Unmarshal(*content, deploy)\n\tif err != nil {\n\t\tfmt.Printf(\"Json unmarshal error: %s\\n\", err)\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package validator\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\tga4gh \"github.com/googlegenomics/ga4gh-identity\"\n)\n\n\n\n\ntype Or []ga4gh.Validator\n\n\n\n\n\n\n\n\n\ntype And []ga4gh.Validator\n\n\n\nfunc (and And) Validate(ctx context.Context, identity *ga4gh.Identity) (bool, error) {\n\tfor i, v := range and {\n\t\tok, err := v.Validate(ctx, identity)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"nested validator at index %d: %v\", i, err)\n\t\t}\n\t\tif !ok {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}\n\nfunc (or Or) Validate(ctx context.Context, identity *ga4gh.Identity) (bool, error) ", "output": "{\n\tfor i, v := range or {\n\t\tok, err := v.Validate(ctx, identity)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"nested validator at index %d: %v\", i, err)\n\t\t}\n\t\tif ok {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}"} {"input": "package vm\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc newStack() *stack {\n\treturn &stack{}\n}\n\ntype stack struct {\n\tdata []*big.Int\n\tptr int\n}\n\nfunc (st *stack) push(d *big.Int) {\n\tstackItem := new(big.Int).Set(d)\n\tif len(st.data) > st.ptr {\n\t\tst.data[st.ptr] = stackItem\n\t} else {\n\t\tst.data = append(st.data, stackItem)\n\t}\n\tst.ptr++\n}\n\n\n\nfunc (st *stack) len() int {\n\treturn st.ptr\n}\n\nfunc (st *stack) swap(n int) {\n\tst.data[st.len()-n], st.data[st.len()-1] = st.data[st.len()-1], st.data[st.len()-n]\n}\n\nfunc (st *stack) dup(n int) {\n\tst.push(st.data[st.len()-n])\n}\n\nfunc (st *stack) peek() *big.Int {\n\treturn st.data[st.len()-1]\n}\n\nfunc (st *stack) require(n int) error {\n\tif st.len() < n {\n\t\treturn fmt.Errorf(\"stack underflow (%d <=> %d)\", len(st.data), n)\n\t}\n\treturn nil\n}\n\nfunc (st *stack) Print() {\n\tfmt.Println(\"### stack ###\")\n\tif len(st.data) > 0 {\n\t\tfor i, val := range st.data {\n\t\t\tfmt.Printf(\"%-3d %v\\n\", i, val)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"-- empty --\")\n\t}\n\tfmt.Println(\"#############\")\n}\n\nfunc (st *stack) pop() (ret *big.Int) ", "output": "{\n\tst.ptr--\n\tret = st.data[st.ptr]\n\treturn\n}"} {"input": "package migrations\n\nimport (\n\t\"fmt\"\n\n\t\"xorm.io/xorm\"\n)\n\n\n\nfunc addBranchProtectionUnprotectedFilesColumn(x *xorm.Engine) error ", "output": "{\n\ttype ProtectedBranch struct {\n\t\tUnprotectedFilePatterns string `xorm:\"TEXT\"`\n\t}\n\n\tif err := x.Sync2(new(ProtectedBranch)); err != nil {\n\t\treturn fmt.Errorf(\"Sync2: %v\", err)\n\t}\n\treturn nil\n}"} {"input": "package wml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/wml\"\n)\n\n\n\nfunc TestCT_PMarshalUnmarshal(t *testing.T) {\n\tv := wml.NewCT_P()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := wml.NewCT_P()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestCT_PConstructor(t *testing.T) ", "output": "{\n\tv := wml.NewCT_P()\n\tif v == nil {\n\t\tt.Errorf(\"wml.NewCT_P must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed wml.CT_P should validate: %s\", err)\n\t}\n}"} {"input": "package tagquery\n\nimport (\n\t\"io\"\n\n\t\"github.com/grafana/metrictank/schema\"\n)\n\ntype expressionMatchNone struct {\n\texpressionCommon\n\toriginalOperator ExpressionOperator\n}\n\nfunc (e *expressionMatchNone) Equals(other Expression) bool {\n\treturn e.key == other.GetKey() && e.GetOperator() == other.GetOperator() && e.value == other.GetValue()\n}\n\nfunc (e *expressionMatchNone) GetDefaultDecision() FilterDecision {\n\treturn Fail\n}\n\nfunc (e *expressionMatchNone) GetKey() string {\n\treturn e.key\n}\n\nfunc (e *expressionMatchNone) GetValue() string {\n\treturn e.value\n}\n\nfunc (e *expressionMatchNone) GetOperator() ExpressionOperator {\n\treturn MATCH_NONE\n}\n\n\n\nfunc (e *expressionMatchNone) RequiresNonEmptyValue() bool {\n\treturn true\n}\n\nfunc (e *expressionMatchNone) Matches(value string) bool {\n\treturn false\n}\n\nfunc (e *expressionMatchNone) GetMetricDefinitionFilter(_ IdTagLookup) MetricDefinitionFilter {\n\treturn func(_ schema.MKey, _ string, _ []string) FilterDecision { return Fail }\n}\n\nfunc (e *expressionMatchNone) StringIntoWriter(writer io.Writer) {\n\twriter.Write([]byte(e.key))\n\te.originalOperator.StringIntoWriter(writer)\n\twriter.Write([]byte(e.value))\n}\n\nfunc (e *expressionMatchNone) GetOperatorCost() uint32 ", "output": "{\n\treturn 0\n}"} {"input": "package sqlbuilder\n\ntype Dialect interface {\n\tEscapeCharacter() rune\n\tInsertReturningClause() string\n\tKind() string\n\tName() *string\n}\n\ntype genericDialect struct {\n\tescapeChar rune\n\treturningClause string\n\tkind string\n\tname *string\n}\n\nfunc (db *genericDialect) EscapeCharacter() rune {\n\treturn db.escapeChar\n}\n\nfunc (db *genericDialect) InsertReturningClause() string {\n\treturn db.returningClause\n}\n\n\n\nfunc (db *genericDialect) Name() *string {\n\treturn db.name\n}\n\nfunc NewMySQLDialect(dbName *string) Dialect {\n\treturn &genericDialect{\n\t\tescapeChar: '`',\n\t\tkind: \"mysql\",\n\t\tname: dbName,\n\t}\n}\n\nfunc NewPostgresDialect(dbName *string) Dialect {\n\treturn &genericDialect{\n\t\tescapeChar: '\"',\n\t\treturningClause: \" RETURNING *\",\n\t\tkind: \"postgres\",\n\t\tname: dbName,\n\t}\n}\n\nfunc NewSQLiteDialect() Dialect {\n\tdefaultName := \"main\"\n\treturn &genericDialect{\n\t\tescapeChar: '\"',\n\t\tkind: \"sqlite\",\n\t\tname: &defaultName,\n\t}\n}\n\nfunc (db *genericDialect) Kind() string ", "output": "{\n\treturn db.kind\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/gsamokovarov/jump/cli\"\n\t\"github.com/gsamokovarov/jump/config\"\n)\n\nconst version = \"0.40.0\"\n\n\n\nfunc init() {\n\tcli.RegisterCommand(\"--version\", \"Show version.\", versionCmd)\n}\n\nfunc versionCmd(cli.Args, config.Config) error ", "output": "{\n\tcli.Outf(\"%s\\n\", version)\n\n\treturn nil\n}"} {"input": "package streaming\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteStreamPoolRequest struct {\n\n\tStreamPoolId *string `mandatory:\"true\" contributesTo:\"path\" name:\"streamPoolId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteStreamPoolRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteStreamPoolRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request DeleteStreamPoolRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype DeleteStreamPoolResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteStreamPoolResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteStreamPoolResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteStreamPoolRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package terminal\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n)\n\ntype TeePrinter struct {\n\tdisableTerminalOutput bool\n\toutputBucket io.Writer\n}\n\nfunc NewTeePrinter() *TeePrinter {\n\treturn &TeePrinter{\n\t\toutputBucket: ioutil.Discard,\n\t}\n}\n\nfunc (t *TeePrinter) SetOutputBucket(bucket io.Writer) {\n\tif bucket == nil {\n\t\tbucket = ioutil.Discard\n\t}\n\n\tt.outputBucket = bucket\n}\n\n\n\nfunc (t *TeePrinter) Printf(format string, a ...interface{}) (n int, err error) {\n\tstr := fmt.Sprintf(format, a...)\n\tt.saveOutputToBucket(str)\n\tif !t.disableTerminalOutput {\n\t\treturn fmt.Print(str)\n\t}\n\treturn\n}\n\nfunc (t *TeePrinter) Println(values ...interface{}) (n int, err error) {\n\tstr := fmt.Sprint(values...)\n\tt.saveOutputToBucket(str)\n\tif !t.disableTerminalOutput {\n\t\treturn fmt.Println(str)\n\t}\n\treturn\n}\n\nfunc (t *TeePrinter) DisableTerminalOutput(disable bool) {\n\tt.disableTerminalOutput = disable\n}\n\nfunc (t *TeePrinter) saveOutputToBucket(output string) {\n\tt.outputBucket.Write([]byte(Decolorize(output)))\n}\n\nfunc (t *TeePrinter) Print(values ...interface{}) (n int, err error) ", "output": "{\n\tstr := fmt.Sprint(values...)\n\tt.saveOutputToBucket(str)\n\tif !t.disableTerminalOutput {\n\t\treturn fmt.Print(str)\n\t}\n\treturn\n}"} {"input": "package ovnmodel\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/skydive-project/skydive/graffiti/getter\"\n\t\"github.com/skydive-project/skydive/graffiti/graph\"\n)\n\n\n\n\ntype LoadBalancerHealthCheck struct {\n\tUUID string `ovsdb:\"_uuid\" json:\",omitempty\" `\n\tExternalIDs map[string]string `ovsdb:\"external_ids\" json:\",omitempty\" `\n\tOptions map[string]string `ovsdb:\"options\" json:\",omitempty\" `\n\tVip string `ovsdb:\"vip\" json:\",omitempty\" `\n\n\tExternalIDsMeta graph.Metadata `json:\",omitempty\" field:\"Metadata\"`\n\tOptionsMeta graph.Metadata `json:\",omitempty\" field:\"Metadata\"`\n}\n\n\n\nfunc (t *LoadBalancerHealthCheck) GetUUID() string {\n\treturn t.UUID\n}\n\nfunc (t *LoadBalancerHealthCheck) GetName() string {\n\tif name := t.UUID; name != \"\" {\n\t\treturn name\n\t}\n\treturn t.GetUUID()\n}\n\n\nfunc LoadBalancerHealthCheckDecoder(raw json.RawMessage) (getter.Getter, error) {\n\tvar t LoadBalancerHealthCheck\n\tif err := json.Unmarshal(raw, &t); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to unmarshal LoadBalancerHealthCheck metadata %s: %s\", string(raw), err)\n\t}\n\treturn &t, nil\n}\n\nfunc (t *LoadBalancerHealthCheck) Metadata() graph.Metadata ", "output": "{\n\tt.ExternalIDsMeta = graph.NormalizeValue(t.ExternalIDs).(map[string]interface{})\n\tt.OptionsMeta = graph.NormalizeValue(t.Options).(map[string]interface{})\n\n\treturn graph.Metadata{\n\t\t\"Type\": \"LoadBalancerHealthCheck\",\n\t\t\"Manager\": \"ovn\",\n\t\t\"UUID\": t.GetUUID(),\n\t\t\"Name\": t.GetName(),\n\t\t\"OVN\": t,\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"testing\"\n\t\"github.com/DanielDanteDosSantosViana/hire.me/config\"\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc init() {\n\tconfig.Conf.Base.Alfabeto = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n}\n\n\n\nfunc TestConverterPrimeiroElementoDaSequence(t *testing.T) {\n\tConvey(\"Dado o primeiro elemento da sequence (int64) 0\", t, func() {\n\t\tvar inteiro uint64 = 0\n\t\tvar alias string = \"a\"\n\t\tConvey(\"Quando converto inteiro 0 para string \", func() {\n\t\t\tretorno := InteiroParaString(inteiro)\n\n\t\t\tConvey(\"O valor retornado deve ser a primeira letra contida em 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' \", func() {\n\t\t\t\tSo(retorno, ShouldEqual, alias)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestConverterInteiro18446744073709551615ParaAliasv8QrKbgkrIp(t *testing.T) ", "output": "{\n\tConvey(\"Dado um inteiro (int64) 18446744073709551615\", t, func() {\n\t\tvar inteiro uint64 = 18446744073709551615\n\t\tvar alias string = \"v8QrKbgkrIp\"\n\t\tConvey(\"Quando converto inteiro 18446744073709551615 para string \", func() {\n\t\t\tretorno := InteiroParaString(inteiro)\n\n\t\t\tConvey(\"O valor retornado deve ser o alias 'v8QrKbgKrIp' \", func() {\n\t\t\t\tSo(retorno, ShouldEqual, alias)\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package auth\n\nimport (\n\t\"golang.org/x/crypto/bcrypt\"\n\n\t\"github.com/nats-io/gnatsd/server\"\n)\n\n\ntype MultiUser struct {\n\tusers map[string]string\n}\n\n\n\n\n\nfunc (m *MultiUser) Check(c server.ClientAuth) bool {\n\topts := c.GetOpts()\n\tpass, ok := m.users[opts.Username]\n\tif !ok {\n\t\treturn false\n\t}\n\tif isBcrypt(pass) {\n\t\tif err := bcrypt.CompareHashAndPassword([]byte(pass), []byte(opts.Password)); err != nil {\n\t\t\treturn false\n\t\t}\n\t} else if pass != opts.Password {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc NewMultiUser(users []server.User) *MultiUser ", "output": "{\n\tm := &MultiUser{users: make(map[string]string)}\n\tfor _, u := range users {\n\t\tm.users[u.Username] = u.Password\n\t}\n\treturn m\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"io/ioutil\"\n\t\"strings\"\n)\n\nconst TwistRoot = \"https://twist.moe\"\n\n\n\nfunc UrlPseudoJoin(path string) string {\n\treturn TwistRoot + strings.TrimSpace(path)\n}\n\nfunc FetchPageContents(url string) (string, error) ", "output": "{\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}"} {"input": "package animate\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestGeocode(t *testing.T) ", "output": "{\n\ttestData := []struct {\n\t\ttext string\n\t}{\n\t\t{\"funny cat\"},\n\t}\n\n\tcommand := Animate()\n\n\tfor _, d := range testData {\n\t\trsp, err := command.Exec(\"animate\", d.text)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif rsp == nil {\n\t\t\tt.Fatal(\"expected result, got nil\")\n\t\t}\n\t}\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n)\n\n\n\n\nfunc Set(key string, value interface{}, dur time.Duration) error {\n\n\tif err := DB.Set(\"cache\", key, value); err != nil {\n\t\treturn err\n\t}\n\n\tif dur.Seconds() > 0 {\n\t\tgo func() {\n\t\t\ttime.Sleep(dur)\n\t\t\tDelete(key)\n\t\t}()\n\t}\n\n\treturn nil\n}\n\n\n\n\n\n\nfunc Delete(key string) error {\n\treturn DB.Delete(\"cache\", key)\n}\n\nfunc Get(key string) interface{} ", "output": "{\n\tvar i interface{}\n\n\tDB.Get(\"cache\", key, &i)\n\n\treturn i\n}"} {"input": "package dns\n\nimport (\n\t\"github.com/cilium/cilium/pkg/hubble/metrics/api\"\n)\n\ntype dnsPlugin struct{}\n\nfunc (p *dnsPlugin) NewHandler() api.Handler {\n\treturn &dnsHandler{}\n}\n\n\n\nfunc init() {\n\tapi.DefaultRegistry().Register(\"dns\", &dnsPlugin{})\n}\n\nfunc (p *dnsPlugin) HelpText() string ", "output": "{\n\treturn `dns - DNS related metrics\nReports metrics related to DNS queries and responses\n\nMetrics:\n hubble_dns_queries_total Number of observed TCP queries\n hubble_dns_responses_total Number of observed TCP responses\n\nOptions:\n query - Include query name as label\n ignoreAAAA - Do not include AAAA query & responses in metrics` +\n\t\tapi.ContextOptionsHelp\n}"} {"input": "package trace\n\nimport (\n\t\"github.com/golang/groupcache/lru\"\n)\n\n\n\ntype lruMap struct {\n\tcacheKeys map[lru.Key]bool\n\tcache *lru.Cache\n\tdroppedCount int\n}\n\nfunc newLruMap(size int) *lruMap {\n\tlm := &lruMap{\n\t\tcacheKeys: make(map[lru.Key]bool),\n\t\tcache: lru.New(size),\n\t\tdroppedCount: 0,\n\t}\n\tlm.cache.OnEvicted = func(key lru.Key, value interface{}) {\n\t\tdelete(lm.cacheKeys, key)\n\t\tlm.droppedCount++\n\t}\n\treturn lm\n}\n\nfunc (lm lruMap) len() int {\n\treturn lm.cache.Len()\n}\n\nfunc (lm lruMap) keys() []interface{} {\n\tkeys := []interface{}{}\n\tfor k := range lm.cacheKeys {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}\n\n\n\nfunc (lm *lruMap) get(key interface{}) (interface{}, bool) {\n\treturn lm.cache.Get(key)\n}\n\nfunc (lm *lruMap) add(key, value interface{}) ", "output": "{\n\tlm.cacheKeys[lru.Key(key)] = true\n\tlm.cache.Add(lru.Key(key), value)\n}"} {"input": "package models\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/hex\"\n\t\"time\"\n)\n\nconst (\n\tNonceBytes = 32\n)\n\ntype Nonce struct {\n\tId string `db:\"id\" json:\"-\"`\n\tExpiresAt time.Time `db:\"expires_at\" json:\"expires_at\"`\n\tNonce string `db:\"nonce\" json:\"nonce\"`\n}\n\n\n\nfunc generate() (string, error) {\n\tb := make([]byte, NonceBytes)\n\t_, err := rand.Read(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tstr := hex.EncodeToString(b)\n\treturn string(str[:NonceBytes]), nil\n}\n\nfunc NonceValid(nonce string) bool {\n\tid, err := Db.SelectNullStr(\n\t\t\"select id from nonces where nonce = $1 and expires_at > $2 limit 1\",\n\t\tnonce, time.Now(),\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif !id.Valid {\n\t\treturn false\n\t}\n\n\t_, err = Db.Exec(\"delete from nonces where id=$1\", id.String)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn true\n}\n\nfunc CreateNonce() (*Nonce, error) ", "output": "{\n\tn, err := generate()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := &Nonce{\n\t\tExpiresAt: time.Now().Add(10 * time.Minute),\n\t\tNonce: n,\n\t}\n\terr = Db.Insert(nonce)\n\treturn nonce, err\n}"} {"input": "package test\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/pilosa/pilosa\"\n)\n\n\nfunc NewCluster(n int) *pilosa.Cluster {\n\tc := pilosa.NewCluster()\n\tc.ReplicaN = 1\n\tc.Hasher = NewModHasher()\n\n\tfor i := 0; i < n; i++ {\n\t\tc.Nodes = append(c.Nodes, &pilosa.Node{\n\t\t\tScheme: \"http\",\n\t\t\tHost: fmt.Sprintf(\"host%d\", i),\n\t\t})\n\t}\n\n\treturn c\n}\n\n\ntype ModHasher struct{}\n\n\nfunc NewModHasher() *ModHasher { return &ModHasher{} }\n\n\n\n\ntype ConstHasher struct {\n\ti int\n}\n\n\nfunc NewConstHasher(i int) *ConstHasher { return &ConstHasher{i: i} }\n\nfunc (h *ConstHasher) Hash(key uint64, n int) int { return h.i }\n\nfunc (*ModHasher) Hash(key uint64, n int) int ", "output": "{ return int(key) % n }"} {"input": "package radixutil\n\nimport (\n\t\"time\"\n\n\t\"github.com/levenlabs/go-srvclient\"\n\t\"github.com/mediocregopher/radix.v2/cluster\"\n\t\"github.com/mediocregopher/radix.v2/pool\"\n\t\"github.com/mediocregopher/radix.v2/redis\"\n\t\"github.com/mediocregopher/radix.v2/util\"\n)\n\n\n\n\n\n\nfunc SRVDialFunc(sc *srvclient.SRVClient, timeout time.Duration) func(string, string) (*redis.Client, error) {\n\treturn func(network, addr string) (*redis.Client, error) {\n\t\taddr = sc.MaybeSRV(addr)\n\t\treturn redis.DialTimeout(network, addr, timeout)\n\t}\n}\n\n\n\n\n\n\n\nfunc DialMaybeCluster(network, addr string, poolSize int) (util.Cmder, error) ", "output": "{\n\tdf := SRVDialFunc(srvclient.DefaultSRVClient, 5*time.Second)\n\n\tdConn, err := df(network, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer dConn.Close()\n\n\tif dr := dConn.Cmd(\"CLUSTER\", \"SLOTS\"); dr.IsType(redis.IOErr) {\n\t\treturn nil, dr.Err\n\t} else if dr.IsType(redis.AppErr) {\n\t\treturn pool.NewCustom(network, addr, poolSize, df)\n\t} else {\n\t\treturn cluster.NewWithOpts(cluster.Opts{\n\t\t\tAddr: addr,\n\t\t\tPoolSize: poolSize,\n\t\t\tDialer: df,\n\t\t})\n\t}\n}"} {"input": "package httpmux\n\nimport \"net/http\"\n\n\ntype ConfigOption interface {\n\tSet(c *Config)\n}\n\n\ntype ConfigOptionFunc func(c *Config)\n\n\nfunc (f ConfigOptionFunc) Set(c *Config) { f(c) }\n\n\nfunc WithPrefix(prefix string) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Prefix = prefix })\n}\n\n\nfunc WithMiddleware(mw ...Middleware) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Middleware = mw })\n}\n\n\nfunc WithMiddlewareFunc(mw ...MiddlewareFunc) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.UseFunc(mw...) })\n}\n\n\nfunc WithRedirectTrailingSlash(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectTrailingSlash = v })\n}\n\n\n\n\n\nfunc WithHandleMethodNotAllowed(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.HandleMethodNotAllowed = v })\n}\n\n\nfunc WithNotFound(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.NotFound = f })\n}\n\n\nfunc WithMethodNotAllowed(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.MethodNotAllowed = f })\n}\n\n\nfunc WithPanicHandler(f func(http.ResponseWriter, *http.Request, interface{})) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.PanicHandler = f })\n}\n\nfunc WithRedirectFixedPath(v bool) ConfigOption ", "output": "{\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectFixedPath = v })\n}"} {"input": "package model\n\n\ntype Weight struct {\n\ttime int\n\trequirements map[*Reward]int\n}\n\n\nfunc (weight *Weight) Time() int {\n\treturn weight.time\n}\n\n\nfunc (weight *Weight) Requirements() map[*Reward]int {\n\treturn weight.requirements\n}\n\n\nfunc (weight *Weight) AddRequirement(reward *Reward, quantity int) {\n\tweight.requirements[reward] = quantity\n}\n\n\n\n\n\ntype ByTime []*Weight\n\n\nfunc (a ByTime) Len() int {\n\treturn len(a)\n}\n\n\nfunc (a ByTime) Swap(i, j int) {\n\ta[i], a[j] = a[j], a[i]\n}\n\n\nfunc (a ByTime) Less(i, j int) bool {\n\treturn a[i].Time() < a[j].Time()\n}\n\nfunc CreateWeight(time int) *Weight ", "output": "{\n\tweight := new(Weight)\n\tweight.time = time\n\tweight.requirements = make(map[*Reward]int)\n\treturn weight\n}"} {"input": "package run\n\nimport (\n\t\"fmt\"\n\n\t\"go.pedge.io/proto/time\"\n\n\t\"github.com/pachyderm/pachyderm/src/pkg/timing\"\n\t\"github.com/pachyderm/pachyderm/src/pps\"\n\t\"github.com/pachyderm/pachyderm/src/pps/store\"\n)\n\ntype pipelineRunLogWriter struct {\n\tpipelineRunID string\n\tcontainerID string\n\tnode string\n\toutputStream pps.OutputStream\n\ttimer timing.Timer\n\tstoreClient store.Client\n}\n\n\n\nfunc (w *pipelineRunLogWriter) Write(p []byte) (int, error) {\n\tc := make([]byte, len(p))\n\tif n := copy(c, p); n != len(p) {\n\t\treturn 0, fmt.Errorf(\"tried to copy %d bytes, only copied %d bytes\", len(p), n)\n\t}\n\tif err := w.storeClient.AddPipelineRunLogs(\n\t\t&pps.PipelineRunLog{\n\t\t\tPipelineRunId: w.pipelineRunID,\n\t\t\tContainerId: w.containerID,\n\t\t\tNode: w.node,\n\t\t\tOutputStream: w.outputStream,\n\t\t\tTimestamp: prototime.TimeToTimestamp(w.timer.Now()),\n\t\t\tData: c,\n\t\t},\n\t); err != nil {\n\t\treturn 0, err\n\t}\n\treturn len(p), nil\n}\n\nfunc newPipelineRunLogWriter(\n\tpipelineRunID string,\n\tcontainerID string,\n\tnode string,\n\toutputStream pps.OutputStream,\n\ttimer timing.Timer,\n\tstoreClient store.Client,\n) *pipelineRunLogWriter ", "output": "{\n\treturn &pipelineRunLogWriter{\n\t\tpipelineRunID,\n\t\tcontainerID,\n\t\tnode,\n\t\toutputStream,\n\t\ttimer,\n\t\tstoreClient,\n\t}\n}"} {"input": "package day09\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestIsValid(t *testing.T) {\n\tsequence := make([]int, 25)\n\tfor i := 0; i < 25; i++ {\n\t\tsequence[i] = i + 1\n\t}\n\n\trequire.True(t, IsValid(sequence, 26))\n\trequire.True(t, IsValid(sequence, 49))\n\trequire.False(t, IsValid(sequence, 100))\n\trequire.False(t, IsValid(sequence, 50))\n}\n\nfunc TestFirstInvalidValue(t *testing.T) {\n\tsequence := []int{35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576}\n\tvalue, err := FirstInvalidValue(sequence, 5)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 127, value)\n}\n\nfunc TestFindContiguousSum(t *testing.T) {\n\tsequence := []int{35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576}\n\tstart, end, err := FindContiguousSum(sequence, 127)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 2, start)\n\trequire.Equal(t, 5, end)\n}\n\n\n\nfunc TestFindWeakness(t *testing.T) ", "output": "{\n\tsequence := []int{35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576}\n\tvalue, err := FindWeakness(sequence, 127)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 62, value)\n}"} {"input": "package ldapserver\n\ntype CompareRequest struct {\n\tentry LDAPDN\n\tava AttributeValueAssertion\n}\n\nfunc (r *CompareRequest) GetEntry() LDAPDN {\n\treturn r.entry\n}\n\n\n\ntype CompareResponse struct {\n\tldapResult\n}\n\nfunc NewCompareResponse(resultCode int) *CompareResponse {\n\tr := &CompareResponse{}\n\tr.ResultCode = resultCode\n\treturn r\n}\n\nfunc (r *CompareRequest) GetAttributeValueAssertion() *AttributeValueAssertion ", "output": "{\n\treturn &r.ava\n}"} {"input": "package main\n\nimport (\n\t\"database/sql\"\n\t\"os\"\n\n\t_ \"github.com/mattn/go-sqlite3\"\n)\n\nconst (\n\tReposSQLInit = `\n CREATE TABLE \"Repos\" (\n \"Name\" TEXT,\n \"Main\" TEXT\n );\n CREATE INDEX \"NAME\" ON \"Repos\" (\"Name\");`\n\tReposSQLInsert = `INSERT INTO \"Repos\" VALUES (?, ?)`\n\tReposSQLSelect = `SELECT \"Main\" FROM \"Repos\" WHERE \"Name\" = ?`\n\n\tRefsSQLInit = `\n CREATE TABLE \"Heads\" (\n \"Sha\" TEXT,\n \"Repository\" TEXT,\n \"Timestamp\" TEXT,\n \"Name\" TEXT\n );\n CREATE INDEX \"REPOSITORY\" ON \"Heads\" (\"Repository\");\n CREATE INDEX \"TIMESTAMP\" ON \"Heads\" (\"Timestamp\");`\n\tRefsSQLInsert = `INSERT INTO \"Heads\" VALUES (?, ?, ?, ?)`\n)\n\nfunc OpenReposDb(filename string) (*sql.DB, *sql.Stmt, *sql.Stmt, error) {\n\tos.Remove(filename)\n\n\tdb, err := sql.Open(\"sqlite3\", filename)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t_, err = db.Exec(ReposSQLInit)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tinsertQuery, err := db.Prepare(ReposSQLInsert)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tselectQuery, err := db.Prepare(ReposSQLSelect)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\treturn db, insertQuery, selectQuery, nil\n}\n\n\n\nfunc OpenRefsDb(filename string) (*sql.DB, *sql.Stmt, error) ", "output": "{\n\tisNew := false\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\t\tisNew = true\n\t}\n\n\tdb, err := sql.Open(\"sqlite3\", filename)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif isNew {\n\t\t_, err = db.Exec(RefsSQLInit)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tinsertQuery, err := db.Prepare(RefsSQLInsert)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn db, insertQuery, nil\n}"} {"input": "package main_test\n\nimport (\n\t\"encoding/json\"\n\n\t. \"gopkg.in/check.v1\"\n\n\tsnap \"github.com/snapcore/snapd/cmd/snap\"\n)\n\n\n\nfunc (s *SnapKeysSuite) TestDeleteKeyNonexistent(c *C) {\n\t_, err := snap.Parser(snap.Client()).ParseArgs([]string{\"delete-key\", \"nonexistent\"})\n\tc.Assert(err, NotNil)\n\tc.Check(err.Error(), Equals, \"cannot find key named \\\"nonexistent\\\" in GPG keyring\")\n\tc.Check(s.Stdout(), Equals, \"\")\n\tc.Check(s.Stderr(), Equals, \"\")\n}\n\nfunc (s *SnapKeysSuite) TestDeleteKey(c *C) {\n\trest, err := snap.Parser(snap.Client()).ParseArgs([]string{\"delete-key\", \"another\"})\n\tc.Assert(err, IsNil)\n\tc.Assert(rest, DeepEquals, []string{})\n\tc.Check(s.Stdout(), Equals, \"\")\n\tc.Check(s.Stderr(), Equals, \"\")\n\t_, err = snap.Parser(snap.Client()).ParseArgs([]string{\"keys\", \"--json\"})\n\tc.Assert(err, IsNil)\n\texpectedResponse := []snap.Key{\n\t\t{\n\t\t\tName: \"default\",\n\t\t\tSha3_384: \"g4Pks54W_US4pZuxhgG_RHNAf_UeZBBuZyGRLLmMj1Do3GkE_r_5A5BFjx24ZwVJ\",\n\t\t},\n\t}\n\tvar obtainedResponse []snap.Key\n\tjson.Unmarshal(s.stdout.Bytes(), &obtainedResponse)\n\tc.Check(obtainedResponse, DeepEquals, expectedResponse)\n\tc.Check(s.Stderr(), Equals, \"\")\n}\n\nfunc (s *SnapKeysSuite) TestDeleteKeyRequiresName(c *C) ", "output": "{\n\t_, err := snap.Parser(snap.Client()).ParseArgs([]string{\"delete-key\"})\n\tc.Assert(err, NotNil)\n\tc.Check(err.Error(), Equals, \"the required argument `` was not provided\")\n\tc.Check(s.Stdout(), Equals, \"\")\n\tc.Check(s.Stderr(), Equals, \"\")\n}"} {"input": "package main\n\n\n\nimport \"C\"\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"unsafe\"\n)\n\nconst LC_NUMERIC = int(C.LC_NUMERIC)\n\n\nfunc setLocale(lc int, locale string) {\n\tl := C.CString(locale)\n\tdefer C.free(unsafe.Pointer(l))\n\tC.setlocale(C.int(lc), l)\n}\n\n\nfunc inSlice(a string, b []string) bool {\n\tfor _, i := range b {\n\t\tif a == i {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\n\nfunc cacheDir() string {\n\tdir := os.Getenv(\"XDG_CACHE_HOME\")\n\tif dir == \"\" {\n\t\tdir = filepath.Join(homeDir(), \".cache\", \"bukanir\")\n\t} else {\n\t\tdir = filepath.Join(dir, \"bukanir\")\n\t}\n\treturn dir\n}\n\nfunc homeDir() string ", "output": "{\n\tif runtime.GOOS == \"windows\" {\n\t\thome := os.Getenv(\"HOMEDRIVE\") + os.Getenv(\"HOMEPATH\")\n\t\tif home == \"\" {\n\t\t\thome = os.Getenv(\"USERPROFILE\")\n\t\t}\n\t\treturn home\n\t}\n\treturn os.Getenv(\"HOME\")\n}"} {"input": "package aprs\n\nimport (\n\t\"fmt\"\n)\n\n\ntype PacketType byte\n\nvar packetTypeNames = map[byte]string{\n\t0x1c: \"Current Mic-E Data (Rev 0 beta)\",\n\t0x1d: \"Old Mic-E Data (Rev 0 beta)\",\n\t'!': \"Position without timestamp (no APRS messaging), or Ultimeter 2000 WX Station\",\n\t'#': \"Peet Bros U-II Weather Station\",\n\t'$': \"Raw GPS data or Ultimeter 2000\",\n\t'%': \"Agrelo DFJr / MicroFinder\",\n\t'\"': \"Old Mic-E Data (but Current data for TM-D700)\",\n\t')': \"Item\",\n\t'*': \"Peet Bros U-II Weather Station\",\n\t',': \"Invalid data or test data\",\n\t'/': \"Position with timestamp (no APRS messaging)\",\n\t':': \"Message\",\n\t';': \"Object\",\n\t'<': \"Station Capabilities\",\n\t'=': \"Position without timestamp (with APRS messaging)\",\n\t'>': \"Status\",\n\t'?': \"Query\",\n\t'@': \"Position with timestamp (with APRS messaging)\",\n\t'T': \"Telemetry data\",\n\t'[': \"Maidenhead grid locator beacon (obsolete)\",\n\t'_': \"Weather Report (without position)\",\n\t'`': \"Current Mic-E Data (not used in TM-D700)\",\n\t'{': \"User-Defined APRS packet format\",\n\t'}': \"Third-party traffic\",\n}\n\n\nfunc (p PacketType) IsMessage() bool {\n\treturn p == ':'\n}\n\n\n\n\nfunc (p PacketType) String() string {\n\tif t, ok := packetTypeNames[byte(p)]; ok {\n\t\treturn t\n\t}\n\treturn fmt.Sprintf(\"Unknown %x\", byte(p))\n}\n\nfunc (p PacketType) IsThirdParty() bool ", "output": "{\n\treturn p == '}'\n}"} {"input": "package v1\n\n\n\n\n\n\n\n\n\n\n\n\nvar map_TokenReview = map[string]string{\n\t\"\": \"TokenReview attempts to authenticate a token to a known user. Note: TokenReview requests may be cached by the webhook token authenticator plugin in the kube-apiserver.\",\n\t\"spec\": \"Spec holds information about the request being evaluated\",\n\t\"status\": \"Status is filled in by the server and indicates whether the request can be authenticated.\",\n}\n\nfunc (TokenReview) SwaggerDoc() map[string]string {\n\treturn map_TokenReview\n}\n\nvar map_TokenReviewSpec = map[string]string{\n\t\"\": \"TokenReviewSpec is a description of the token authentication request.\",\n\t\"token\": \"Token is the opaque bearer token.\",\n}\n\nfunc (TokenReviewSpec) SwaggerDoc() map[string]string {\n\treturn map_TokenReviewSpec\n}\n\nvar map_TokenReviewStatus = map[string]string{\n\t\"\": \"TokenReviewStatus is the result of the token authentication request.\",\n\t\"authenticated\": \"Authenticated indicates that the token was associated with a known user.\",\n\t\"user\": \"User is the UserInfo associated with the provided token.\",\n\t\"error\": \"Error indicates that the token couldn't be checked\",\n}\n\n\n\nvar map_UserInfo = map[string]string{\n\t\"\": \"UserInfo holds the information about the user needed to implement the user.Info interface.\",\n\t\"username\": \"The name that uniquely identifies this user among all active users.\",\n\t\"uid\": \"A unique value that identifies this user across time. If this user is deleted and another user by the same name is added, they will have different UIDs.\",\n\t\"groups\": \"The names of groups this user is a part of.\",\n\t\"extra\": \"Any additional information provided by the authenticator.\",\n}\n\nfunc (UserInfo) SwaggerDoc() map[string]string {\n\treturn map_UserInfo\n}\n\nfunc (TokenReviewStatus) SwaggerDoc() map[string]string ", "output": "{\n\treturn map_TokenReviewStatus\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSEMRCluster_HadoopJarStepConfig struct {\n\n\tArgs []string `json:\"Args,omitempty\"`\n\n\tJar string `json:\"Jar,omitempty\"`\n\n\tMainClass string `json:\"MainClass,omitempty\"`\n\n\tStepProperties []AWSEMRCluster_KeyValue `json:\"StepProperties,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) AWSCloudFormationType() string {\n\treturn \"AWS::EMR::Cluster.HadoopJarStepConfig\"\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\n\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetMetadata(metadata map[string]interface{}) ", "output": "{\n\tr._metadata = metadata\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\tcheck \"gopkg.in/check.v1\"\n\n\t\"github.com/Dataman-Cloud/swan/types\"\n)\n\n\n\nfunc (s *ApiSuite) TestGetLeader(c *check.C) ", "output": "{\n\tcode, body, err := s.sendRequest(\"GET\", \"/v1/leader\", nil)\n\tc.Assert(err, check.IsNil)\n\tc.Assert(code, check.Equals, http.StatusOK)\n\n\tvar leader = new(types.Leader)\n\terr = s.bind(body, leader)\n\tc.Assert(err, check.IsNil)\n\tc.Assert(leader.Leader, check.Not(check.Equals), \"\")\n}"} {"input": "package iterfloat32\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"sync\"\n)\n\ntype Slice struct {\n\tSlice []float32\n\terr error\n\tindex int\n\tmutex sync.RWMutex\n\tclosed bool\n\tdatum float32\n}\n\nfunc (receiver *Slice) Close() error {\n\tif nil == receiver {\n\t\treturn errNilReceiver\n\t}\n\n\treceiver.mutex.Lock()\n\tdefer receiver.mutex.Unlock()\n\n\treceiver.closed = true\n\n\treturn nil\n}\n\n\n\n\n\n\n\n\nfunc (receiver *Slice) Err() error {\n\tif nil == receiver {\n\t\treturn errNilReceiver\n\t}\n\n\treceiver.mutex.RLock()\n\tdefer receiver.mutex.RUnlock()\n\n\treturn receiver.err\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (receiver *Slice) Next() bool {\n\tif nil == receiver {\n\t\treturn false\n\t}\n\n\treceiver.mutex.Lock()\n\tdefer receiver.mutex.Unlock()\n\n\tif nil != receiver.err {\n\t\treturn false\n\t}\n\n\tif receiver.closed {\n\t\treturn false\n\t}\n\n\tslice := receiver.Slice\n\tif nil == slice {\n\t\treturn false\n\t}\n\n\tindex := receiver.index\n\tif len(slice) <= index {\n\t\treturn false\n\t}\n\n\treceiver.datum = slice[index]\n\treceiver.index++\n\n\treturn true\n}\n\nfunc (receiver *Slice) Decode(x interface{}) error ", "output": "{\n\tif nil == receiver {\n\t\treturn errNilReceiver\n\t}\n\n\treceiver.mutex.RLock()\n\tdefer receiver.mutex.RUnlock()\n\n\tswitch p := x.(type) {\n\tcase *float32:\n\t\tif nil == p {\n\t\t\treturn nil\n\t\t}\n\n\t\t*p = receiver.datum\n\tcase *interface{}:\n\t\tif nil == p {\n\t\t\treturn nil\n\t\t}\n\n\t\t*p = receiver.datum\n\tcase sql.Scanner:\n\t\treturn p.Scan( float64(receiver.datum) )\n\tdefault:\n\t\treturn &internalBadTypeComplainer{fmt.Sprintf(\"%T\", p)}\n\t}\n\n\treturn nil\n}"} {"input": "package sqlstore\n\nimport \"io\"\n\ntype Option func(s *Store)\n\n\n\nfunc WithDebug(w io.Writer) Option ", "output": "{\n\treturn func(s *Store) {\n\t\ts.debug = true\n\t\ts.writer = w\n\t}\n}"} {"input": "package timer\n\nimport (\n\t\"time\"\n)\n\ntype typeAction int\n\nconst (\n\tCLOSE typeAction = iota\n\tRESET\n\tFORCE\n)\n\n\n\ntype Timer struct {\n\tinterval time.Duration\n\tmsg, resp chan typeAction\n}\n\n\n\n\n\n\n\n\n\nfunc (self *Timer) Next() bool {\n\tfor {\n\t\tvar ch <-chan time.Time\n\t\tif self.interval <= 0 {\n\t\t\tch = nil\n\t\t} else {\n\t\t\tch = time.After(self.interval)\n\t\t}\n\t\tselect {\n\t\tcase action := <-self.msg:\n\t\t\tswitch action {\n\t\t\tcase CLOSE:\n\t\t\t\tself.resp <- CLOSE\n\t\t\t\treturn false\n\t\t\tcase FORCE:\n\t\t\t\treturn true\n\t\t\t}\n\t\tcase <-ch:\n\t\t\treturn true\n\t\t}\n\t}\n\tpanic(\"unreachable\")\n}\n\n\n\nfunc (self *Timer) SetInterval(ns time.Duration) {\n\tself.interval = ns\n\tself.msg <- RESET\n}\n\n\n\nfunc (self *Timer) Trigger() {\n\tself.msg <- FORCE\n}\n\n\nfunc (self *Timer) TriggerAfter(ns time.Duration) {\n\tgo func() {\n\t\t<-time.After(ns)\n\t\tself.Trigger()\n\t}()\n}\n\n\n\n\nfunc (self *Timer) Close() {\n\tself.msg <- CLOSE\n\t<-self.resp\n}\n\nfunc NewTimer(interval time.Duration) *Timer ", "output": "{\n\treturn &Timer{\n\t\tinterval: interval,\n\t\tmsg: make(chan typeAction, 1),\n\t\tresp: make(chan typeAction, 1),\n\t}\n}"} {"input": "package pretty\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/MakeNowJust/heredoc\"\n)\n\n\nfunc Bash(s string) string {\n\treturn fmt.Sprintf(\"`%s`\", s)\n}\n\n\n\n\n\nfunc LongDesc(s string) string ", "output": "{\n\ts = heredoc.Doc(s)\n\ts = strings.TrimSpace(s)\n\treturn s\n}"} {"input": "package hpa\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"os/exec\"\n\t\"time\"\n\n\t\"github.com/Azure/acs-engine/test/e2e/kubernetes/util\"\n)\n\n\ntype HPA struct {\n\tMetadata Metadata `json:\"metadata\"`\n\tSpec Spec `json:\"spec\"`\n\tStatus Status `json:\"status\"`\n}\n\n\ntype Metadata struct {\n\tCreatedAt time.Time `json:\"creationTimestamp\"`\n\tName string `json:\"name\"`\n\tNamespace string `json:\"namespace\"`\n}\n\n\ntype Spec struct {\n\tMinReplicas int `json:\"minReplicas\"`\n\tMaxReplicas int `json:\"maxReplicas\"`\n\tTargetCPUUtilizationPercentage int `json:\"targetCPUUtilizationPercentage\"`\n}\n\n\ntype Status struct {\n\tLoadBalancer LoadBalancer `json:\"loadBalancer\"`\n}\n\n\ntype LoadBalancer struct {\n\tCurrentCPUUtilizationPercentage int `json:\"currentCPUUtilizationPercentage\"`\n\tCurrentReplicas int `json:\"currentReplicas\"`\n\tDesiredReplicas int `json:\"desiredReplicas\"`\n}\n\n\n\n\n\nfunc (h *HPA) Delete(retries int) error {\n\tvar kubectlOutput []byte\n\tvar kubectlError error\n\tfor i := 0; i < retries; i++ {\n\t\tcmd := exec.Command(\"kubectl\", \"delete\", \"hpa\", \"-n\", h.Metadata.Namespace, h.Metadata.Name)\n\t\tkubectlOutput, kubectlError = util.RunAndLogCommand(cmd)\n\t\tif kubectlError != nil {\n\t\t\tlog.Printf(\"Error while trying to delete service %s in namespace %s:%s\\n\", h.Metadata.Namespace, h.Metadata.Name, string(kubectlOutput))\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\treturn kubectlError\n}\n\nfunc Get(name, namespace string) (*HPA, error) ", "output": "{\n\tcmd := exec.Command(\"kubectl\", \"get\", \"hpa\", \"-o\", \"json\", \"-n\", namespace, name)\n\tutil.PrintCommand(cmd)\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tlog.Printf(\"Error trying to run 'kubectl get hpa':%s\\n\", string(out))\n\t\treturn nil, err\n\t}\n\th := HPA{}\n\terr = json.Unmarshal(out, &h)\n\tif err != nil {\n\t\tlog.Printf(\"Error unmarshalling service json:%s\\n\", err)\n\t\treturn nil, err\n\t}\n\treturn &h, nil\n}"} {"input": "package paypal\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nconst format = \"2006-01-02T15:04:05Z\"\n\n\ntype Filter struct {\n\tfields []fmt.Stringer\n}\n\nfunc (s *Filter) String() string {\n\tvar filter string\n\tfor i, f := range s.fields {\n\t\tif i == 0 {\n\t\t\tfilter = \"?\" + f.String()\n\t\t} else {\n\t\t\tfilter = filter + \"&\" + f.String()\n\t\t}\n\t}\n\n\treturn filter\n}\n\n\ntype TextField struct {\n\tname string\n\tIs string\n}\n\nfunc (d TextField) String() string {\n\treturn fmt.Sprintf(\"%s=%s\", d.name, d.Is)\n}\n\n\ntype TimeField struct {\n\tname string\n\tIs time.Time\n}\n\n\nfunc (d TimeField) String() string {\n\treturn fmt.Sprintf(\"%s=%s\", d.name, d.Is.UTC().Format(format))\n}\n\n\n\n\n\nfunc (s *Filter) AddTimeField(field string) *TimeField {\n\tf := &TimeField{name: field}\n\ts.fields = append(s.fields, f)\n\treturn f\n}\n\nfunc (s *Filter) AddTextField(field string) *TextField ", "output": "{\n\tf := &TextField{name: field}\n\ts.fields = append(s.fields, f)\n\treturn f\n}"} {"input": "package lnwire\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\ntype NeighborAckMessage struct {\n\tRoutingMessageBase\n}\n\nfunc (msg *NeighborAckMessage) String() string {\n\treturn fmt.Sprintf(\"NeighborAckMessage{%v %v}\", msg.SenderID, msg.ReceiverID)\n}\n\nfunc (msg *NeighborAckMessage) Command() uint32{\n\treturn CmdNeighborAckMessage\n}\n\nfunc (msg *NeighborAckMessage) Encode(w io.Writer, pver uint32) error{\n\treturn nil\n}\n\nfunc (msg *NeighborAckMessage) Decode(r io.Reader, pver uint32) error{\n\treturn nil\n}\n\nfunc (msg *NeighborAckMessage) MaxPayloadLength(uint32) uint32{\n\treturn 0\n}\n\n\n\nvar _ Message = (*NeighborAckMessage)(nil)\n\nfunc (msg *NeighborAckMessage) Validate() error", "output": "{\n\treturn nil\n}"} {"input": "package kagome\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\ntype Token struct {\n\tId int\n\tClass NodeClass\n\tStart int\n\tEnd int\n\tSurface string\n\tdic *Dic\n\tudic *UserDic\n}\n\n\nfunc (t Token) Features() (features []string) {\n\tswitch t.Class {\n\tcase DUMMY:\n\t\treturn\n\tcase KNOWN:\n\t\tfeatures = t.dic.Contents[t.Id]\n\tcase UNKNOWN:\n\t\tfeatures = sysDic.UnkContents[t.Id]\n\tcase USER:\n\t\tpos := t.udic.Contents[t.Id].Pos\n\t\ttokens := strings.Join(t.udic.Contents[t.Id].Tokens, \"/\")\n\t\tyomi := strings.Join(t.udic.Contents[t.Id].Yomi, \"/\")\n\t\tfeatures = append(features, pos, tokens, yomi)\n\t}\n\treturn\n}\n\n\n\n\nfunc (t Token) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%v(%v, %v)%v[%v]\", t.Surface, t.Start, t.End, t.Class, t.Id)\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"time\"\n)\n\nvar ACTION_POTENTIAL_THRESHOLD int = 30\nvar DELAY_BETWEEN_FIRINGS time.Duration = 10\nvar SIGNAL_BUFFER_SIZE = 2048\n\ntype Neuron struct {\n\ttag string\n\tdendrite chan int \n\tsynapses []Synapse \n\tpotential int\n}\n\nfunc (n *Neuron) Fire() {\n\tlog.Println(n.tag, \"Fired\")\n\tn.potential = 0\n\tfor _, synapse := range n.synapses {\n\t\tselect {\n\t\tcase synapse.channel <- synapse.weight:\n\t\tdefault:\n\t\t\tlog.Println(\"Signal from\", n.tag, \"dropped\")\n\t\t}\n\t\ttime.Sleep(DELAY_BETWEEN_FIRINGS * time.Millisecond)\n\t}\n}\n\n\n\nfunc (n *Neuron) Listen() {\n\tfor actionPotential := range n.dendrite {\n\t\tn.potential += actionPotential\n\t\tif n.HasReachedThreshold() {\n\t\t\tn.Fire()\n\t\t}\n\t}\n}\n\nfunc (n *Neuron) AddSynapse(destination *Neuron, weight int) {\n\tn.synapses = append(n.synapses, Synapse{destination.dendrite, weight})\n}\n\nfunc NewNeuron(tag string) Neuron {\n\treturn Neuron{tag, make(chan int, SIGNAL_BUFFER_SIZE), []Synapse{}, 0}\n}\n\nfunc (n *Neuron) HasReachedThreshold() bool ", "output": "{\n\treturn n.potential > ACTION_POTENTIAL_THRESHOLD\n}"} {"input": "package packets\n\nimport (\n\t\"io\"\n)\n\ntype PubackMessage struct {\n\tHeader\n\tTopicId uint16\n\tMessageId uint16\n\tReturnCode byte\n}\n\nfunc (p *PubackMessage) MessageType() byte {\n\treturn PUBACK\n}\n\nfunc (p *PubackMessage) Write(w io.Writer) error {\n\tpacket := p.Header.pack()\n\tpacket.WriteByte(PUBACK)\n\tpacket.Write(encodeUint16(p.TopicId))\n\tpacket.Write(encodeUint16(p.MessageId))\n\tpacket.WriteByte(p.ReturnCode)\n\t_, err := packet.WriteTo(w)\n\n\treturn err\n}\n\n\n\nfunc (p *PubackMessage) Unpack(b io.Reader) ", "output": "{\n\tp.TopicId = readUint16(b)\n\tp.MessageId = readUint16(b)\n\tp.ReturnCode = readByte(b)\n}"} {"input": "package parser\n\nimport (\n\t\"testing\"\n\t\"fareastdominions.com/evepaste/eve/test\"\n\t\"fareastdominions.com/evepaste/eve/entity\"\n)\n\n\n\nfunc TestCargoScanParse(t *testing.T) ", "output": "{\n\ttestCases := []test.ParserTestCase{{\n\t\t`5000 Caldari Navy Mjolnir Rocket\n47720 Azure Plagioclase\n5 Navy Cap Booster 400`,\n\t\t[]entity.Item{\n\t\t\tentity.Item{\n\t\t\t\tTypeName: `Caldari Navy Mjolnir Rocket`,\n\t\t\t\tQuantity: 5000,\n\t\t\t},\n\t\t\tentity.Item{\n\t\t\t\tTypeName: `Azure Plagioclase`,\n\t\t\t\tQuantity: 47720,\n\t\t\t},\n\t\t\tentity.Item{\n\t\t\t\tTypeName: `Navy Cap Booster 400`,\n\t\t\t\tQuantity: 5,\n\t\t\t},\n\t\t},\n\t}}\n\n\tp := &CargoScanParser{}\n\tfor _, c := range testCases {\n\t\titems, err := p.Parse(c.GetLines())\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tc.Assert(t, items)\n\t}\n}"} {"input": "package lib\n\nfunc cacheHintRegistryList() string {\n\treturn \"catalog:\"\n}\n\nfunc cacheHintTagList(repository string) string {\n\treturn \"pull:\" + repository\n}\n\n\n\nfunc cacheHintTagDetails(repository string) string ", "output": "{\n\treturn \"pull:\" + repository\n}"} {"input": "package systemd\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/google/cadvisor/container\"\n\t\"github.com/google/cadvisor/fs\"\n\tinfo \"github.com/google/cadvisor/info/v1\"\n\t\"github.com/google/cadvisor/watcher\"\n\n\t\"k8s.io/klog/v2\"\n)\n\ntype systemdFactory struct{}\n\n\n\nfunc (f *systemdFactory) NewContainerHandler(name string, inHostNamespace bool) (container.ContainerHandler, error) {\n\treturn nil, fmt.Errorf(\"Not yet supported\")\n}\n\nfunc (f *systemdFactory) CanHandleAndAccept(name string) (bool, bool, error) {\n\tif strings.HasSuffix(name, \".mount\") {\n\t\treturn true, false, nil\n\t}\n\tklog.V(5).Infof(\"%s not handled by systemd handler\", name)\n\treturn false, false, nil\n}\n\nfunc (f *systemdFactory) DebugInfo() map[string][]string {\n\treturn map[string][]string{}\n}\n\n\nfunc Register(machineInfoFactory info.MachineInfoFactory, fsInfo fs.FsInfo, includedMetrics container.MetricSet) error {\n\tklog.V(1).Infof(\"Registering systemd factory\")\n\tfactory := &systemdFactory{}\n\tcontainer.RegisterContainerHandlerFactory(factory, []watcher.ContainerWatchSource{watcher.Raw})\n\treturn nil\n}\n\nfunc (f *systemdFactory) String() string ", "output": "{\n\treturn \"systemd\"\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"github.com/gin-gonic/gin\"\n \"github.com/dgrijalva/jwt-go\"\n)\n\nfunc resendEmailVerificationHandler(c *gin.Context){\n var request struct{\n Token string `form:\"token\" binding:\"required\"`\n }\n if c.Bind(&request) == nil{\n if mobileno, client_id, email_id := getDetailsfromToken(request.Token); mobileno != \"\" || client_id != \"\" || email_id != \"\"{\n sendEmailVerification(mobileno, client_id, email_id)\n c.JSON(200, gin.H{\n \"status\" : \"success\",\n })\n }else{\n c.JSON(200, gin.H{\n \"status\" : \"failed\",\n \"message\" : \"Failed to Send Verification Email! Please try again\",\n })\n }\n }\n}\n\n\n\nfunc getDetailsfromToken(tokenString string) (string, string, string) ", "output": "{\n vertoken, _ := jwt.Parse(tokenString, func (token *jwt.Token) (interface{}, error) {\n if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\n return nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n }\n return mySigningKey, nil\n })\n if claims, _ := vertoken.Claims.(jwt.MapClaims); !vertoken.Valid {\n id := claims[\"id\"].(string)\n email_id := claims[\"email_id\"].(string)\n client_id := claims[\"client_id\"].(string)\n fmt.Println(\"Resending email for :\", id, email_id, client_id)\n return id, client_id, email_id\n }\n return \"\",\"\",\"\"\n}"} {"input": "package storage\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n)\n\nfunc SIGDescribe(text string, body func()) bool {\n\treturn Describe(\"[sig-storage] \"+text, body)\n}\n\n\n\nfunc FSIGDescribe(text string, body func()) bool ", "output": "{\n\treturn FDescribe(\"[sig-storage] \"+text, body)\n}"} {"input": "package metrics\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\ntype GaugeMetric struct {\n\tvalue float64\n\tmutex sync.RWMutex\n}\n\nfunc (metric *GaugeMetric) Humanize() string {\n\tformatString := \"[GaugeMetric; value=%f]\"\n\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn fmt.Sprintf(formatString, metric.value)\n}\n\n\n\nfunc (metric *GaugeMetric) IncrementBy(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value += value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Increment() float64 {\n\treturn metric.IncrementBy(1)\n}\n\nfunc (metric *GaugeMetric) DecrementBy(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value -= value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Decrement() float64 {\n\treturn metric.DecrementBy(1)\n}\n\nfunc (metric *GaugeMetric) Get() float64 {\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Marshallable() map[string]interface{} {\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\tv := make(map[string]interface{}, 2)\n\n\tv[valueKey] = metric.value\n\tv[typeKey] = gaugeTypeValue\n\n\treturn v\n}\n\nfunc (metric *GaugeMetric) Set(value float64) float64 ", "output": "{\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value = value\n\n\treturn metric.value\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"testing\"\n)\n\nfunc apiServer(t testing.TB, path string, resp string, test func()) {\n\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.URL.Path != path {\n\t\t\tt.Errorf(\"Wrong URL: %v\", r.URL.String())\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(200)\n\t\tfmt.Fprintln(w, resp)\n\t}))\n\n\tu, err := url.Parse(server.URL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tGodoBase = u\n\n\tdefer server.Close()\n\ttest()\n}\n\n\n\nfunc metadataServer(t testing.TB, path string, resp string, test func()) ", "output": "{\n\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.URL.Path != path {\n\t\t\tt.Errorf(\"Wrong URL: %v\", r.URL.String())\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(200)\n\t\tfmt.Fprintln(w, resp)\n\t}))\n\n\tu, err := url.Parse(server.URL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tMetadataBase = u\n\n\tdefer server.Close()\n\ttest()\n}"} {"input": "package main\n\nvar log string\n\ntype T int\n\nfunc (t T) a(s string) T {\n\tlog += \"a(\" + s + \")\"\n\treturn t\n}\n\nfunc (T) b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\ntype F func(s string) F\n\nfunc a(s string) F {\n\tlog += \"a(\" + s + \")\"\n\treturn F(a)\n}\n\nfunc b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\ntype I interface {\n\ta(s string) I\n\tb(s string) string\n}\n\ntype T1 int\n\n\n\nfunc (T1) b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\nvar ok = true\n\nfunc bad() {\n\tif !ok {\n\t\tprintln(\"BUG\")\n\t\tok = false\n\t}\n\tprintln(log)\n}\n\nfunc main() {\n\tvar t T\n\tif t.a(\"1\").a(t.b(\"2\")); log != \"a(1)ba(2)\" {\n\t\tbad()\n\t}\n\tlog = \"\"\n\tif a(\"3\")(b(\"4\"))(b(\"5\")); log != \"a(3)ba(4)ba(5)\" {\n\t\tbad()\n\t}\n\tlog = \"\"\n\tvar i I = T1(0)\n\tif i.a(\"6\").a(i.b(\"7\")).a(i.b(\"8\")).a(i.b(\"9\")); log != \"a(6)ba(7)ba(8)ba(9)\" {\n\t\tbad()\n\t}\n}\n\nfunc (t T1) a(s string) I ", "output": "{\n\tlog += \"a(\" + s + \")\"\n\treturn t\n}"} {"input": "package s0095\n\nimport \"github.com/peterstace/project-euler/number\"\n\nfunc Answer() interface{} {\n\tconst limit = 1e6 + 1\n\n\tsumProperDivisors := generateSumProperDivisors(limit)\n\t_ = sumProperDivisors\n\n\tvar maxLength int\n\tvar smallestMember int\n\n\tfor i := 2; i < limit; i++ {\n\t\tchainLen, smallestInChain, ok := findChain(i, sumProperDivisors)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif chainLen > maxLength {\n\t\t\tmaxLength = chainLen\n\t\t\tsmallestMember = smallestInChain\n\t\t}\n\t}\n\n\treturn smallestMember\n}\n\nfunc generateSumProperDivisors(n int) []int {\n\ts := number.PrimeFactorisationSieve(n)\n\td := make([]int, n)\n\tfor i := 1; i < len(s); i++ {\n\t\td[i] = s[i].SumDivisors() - i\n\t}\n\treturn d\n}\n\n\n\nfunc findChain(x int, sumProperDivisors []int) (chainLength, smallestInChain int, ok bool) ", "output": "{\n\tnums := make(map[int]struct{})\n\tfor {\n\t\tnums[x] = struct{}{}\n\t\tx = sumProperDivisors[x]\n\t\tif x >= len(sumProperDivisors) {\n\t\t\treturn 0, 0, false\n\t\t}\n\t\tif _, ok := nums[x]; ok {\n\t\t\tbreak\n\t\t}\n\t}\n\tvar count int\n\tmin := x\n\tstart := x\n\tfor {\n\t\tx = sumProperDivisors[x]\n\t\tcount++\n\t\tif x < min {\n\t\t\tmin = x\n\t\t}\n\t\tif x == start {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn count, min, true\n}"} {"input": "package translatableerror\n\n\ntype FlagNoLongerSupportedError struct {\n\tFlag string\n}\n\n\n\nfunc (e FlagNoLongerSupportedError) Translate(translate func(string, ...interface{}) string) string {\n\treturn translate(e.Error(), map[string]interface{}{\n\t\t\"Flag\": e.Flag,\n\t})\n}\n\nfunc (e FlagNoLongerSupportedError) Error() string ", "output": "{\n\treturn \"Flag '{{.Flag}}' is no longer supported.\"\n}"} {"input": "package cat\n\nimport(\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/ProhtMeyhet/libgosimpleton/iotool\"\n\t\"github.com/ProhtMeyhet/libgosimpleton/parallel\"\n\n\t\"github.com/ProhtMeyhet/gonixutils/library/abstract\"\n)\n\n\nfunc Cat(input *Input) (exitCode uint8) {\n\toutput := abstract.NewOutput(input.Stdout, input.Stderr)\n\tif input.Verbose { output.TogglePrintSubBufferNames() }\n\thelper := prepareFileHelper(input, output, &exitCode)\n\n\te := CopyFilesTo(output, helper, input.Paths...); if e != nil && exitCode == 0 {\n\t\texitCode = abstract.ERROR_UNHANDLED\n\t}\n\n\toutput.Done(); output.Wait(); return\n}\n\nfunc CopyFilesTo(mainOutput abstract.OutputInterface, helper *iotool.FileHelper, paths ...string) (e error) {\n\treturn CopyFilesFilteredTo(mainOutput, helper, nil, paths...)\n}\n\n\n\nfunc CopyFilesFilteredTo(mainOutput abstract.OutputInterface, helper *iotool.FileHelper,\n\t\tfilter func(io.Reader) io.Reader, paths ...string) (e error) ", "output": "{\n\toutput := mainOutput\n\tparallel.ReadFilesSequential(helper, paths, func(buffered *iotool.NamedBuffer) {\n\t\tvar filtered io.Reader\n\t\tif output.PrintSubBufferNames() {\n\t\t\toutput = mainOutput.NewSubBuffer(fmt.Sprintf(\"==>%v<==\\n\", buffered.Name()), 0)\n\t\t}\n\n\t\tif filter != nil { filtered = filter(buffered) }\n\t\tif filtered == nil { filtered = buffered }\n\n\t\t_, e = io.Copy(output, filtered)\n\t\tif output.PrintSubBufferNames() { output.Done() }\n\t}).Wait(); return\n}"} {"input": "package elastic\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"gopkg.in/olivere/elastic.v5/uritemplates\"\n)\n\n\n\ntype RefreshService struct {\n\tclient *Client\n\tindex []string\n\tpretty bool\n}\n\n\nfunc NewRefreshService(client *Client) *RefreshService {\n\tbuilder := &RefreshService{\n\t\tclient: client,\n\t}\n\treturn builder\n}\n\n\nfunc (s *RefreshService) Index(index ...string) *RefreshService {\n\ts.index = append(s.index, index...)\n\treturn s\n}\n\n\nfunc (s *RefreshService) Pretty(pretty bool) *RefreshService {\n\ts.pretty = pretty\n\treturn s\n}\n\n\n\n\n\nfunc (s *RefreshService) Do(ctx context.Context) (*RefreshResult, error) {\n\tpath, params, err := s.buildURL()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := s.client.PerformRequest(ctx, \"POST\", path, params, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := new(RefreshResult)\n\tif err := s.client.decoder.Decode(res.Body, ret); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}\n\n\n\n\ntype RefreshResult struct {\n\tShards shardsInfo `json:\"_shards,omitempty\"`\n}\n\nfunc (s *RefreshService) buildURL() (string, url.Values, error) ", "output": "{\n\tvar err error\n\tvar path string\n\n\tif len(s.index) > 0 {\n\t\tpath, err = uritemplates.Expand(\"/{index}/_refresh\", map[string]string{\n\t\t\t\"index\": strings.Join(s.index, \",\"),\n\t\t})\n\t} else {\n\t\tpath = \"/_refresh\"\n\t}\n\tif err != nil {\n\t\treturn \"\", url.Values{}, err\n\t}\n\n\tparams := url.Values{}\n\tif s.pretty {\n\t\tparams.Set(\"pretty\", fmt.Sprintf(\"%v\", s.pretty))\n\t}\n\treturn path, params, nil\n}"} {"input": "package digitalocean\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\n\t\"github.com/digitalocean/godo\"\n)\n\ntype Artifact struct {\n\tsnapshotName string\n\n\tsnapshotId int\n\n\tregionName string\n\n\tclient *godo.Client\n}\n\nfunc (*Artifact) BuilderId() string {\n\treturn BuilderId\n}\n\nfunc (*Artifact) Files() []string {\n\treturn nil\n}\n\nfunc (a *Artifact) Id() string {\n\treturn fmt.Sprintf(\"%s:%s\", a.regionName, strconv.FormatUint(uint64(a.snapshotId), 10))\n}\n\n\n\nfunc (a *Artifact) State(name string) interface{} {\n\treturn nil\n}\n\nfunc (a *Artifact) Destroy() error {\n\tlog.Printf(\"Destroying image: %d (%s)\", a.snapshotId, a.snapshotName)\n\t_, err := a.client.Images.Delete(context.TODO(), a.snapshotId)\n\treturn err\n}\n\nfunc (a *Artifact) String() string ", "output": "{\n\treturn fmt.Sprintf(\"A snapshot was created: '%v' (ID: %v) in region '%v'\", a.snapshotName, a.snapshotId, a.regionName)\n}"} {"input": "package requirements\n\nimport (\n\t\"github.com/cloudfoundry/cli/cf/api/applications\"\n\t\"github.com/cloudfoundry/cli/cf/models\"\n)\n\n\ntype ApplicationRequirement interface {\n\tRequirement\n\tGetApplication() models.Application\n}\n\ntype applicationApiRequirement struct {\n\tname string\n\tappRepo applications.ApplicationRepository\n\tapplication models.Application\n}\n\nfunc NewApplicationRequirement(name string, aR applications.ApplicationRepository) *applicationApiRequirement {\n\treq := &applicationApiRequirement{}\n\treq.name = name\n\treq.appRepo = aR\n\treturn req\n}\n\nfunc (req *applicationApiRequirement) Execute() error {\n\tvar apiErr error\n\treq.application, apiErr = req.appRepo.Read(req.name)\n\n\tif apiErr != nil {\n\t\treturn apiErr\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (req *applicationApiRequirement) GetApplication() models.Application ", "output": "{\n\treturn req.application\n}"} {"input": "package tracing\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"github.com/containous/alice\"\n\t\"github.com/containous/traefik/middlewares\"\n\t\"github.com/containous/traefik/tracing\"\n\t\"github.com/opentracing/opentracing-go\"\n\t\"github.com/opentracing/opentracing-go/ext\"\n)\n\nconst (\n\tentryPointTypeName = \"TracingEntryPoint\"\n)\n\n\nfunc NewEntryPoint(ctx context.Context, t *tracing.Tracing, entryPointName string, next http.Handler) http.Handler {\n\tmiddlewares.GetLogger(ctx, \"tracing\", entryPointTypeName).Debug(\"Creating middleware\")\n\n\treturn &entryPointMiddleware{\n\t\tentryPoint: entryPointName,\n\t\tTracing: t,\n\t\tnext: next,\n\t}\n}\n\ntype entryPointMiddleware struct {\n\t*tracing.Tracing\n\tentryPoint string\n\tnext http.Handler\n}\n\n\n\n\nfunc WrapEntryPointHandler(ctx context.Context, tracer *tracing.Tracing, entryPointName string) alice.Constructor {\n\treturn func(next http.Handler) (http.Handler, error) {\n\t\treturn NewEntryPoint(ctx, tracer, entryPointName, next), nil\n\t}\n}\n\nfunc (e *entryPointMiddleware) ServeHTTP(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\tspanCtx, _ := e.Extract(opentracing.HTTPHeaders, tracing.HTTPHeadersCarrier(req.Header))\n\n\tspan, req, finish := e.StartSpanf(req, ext.SpanKindRPCServerEnum, \"EntryPoint\", []string{e.entryPoint, req.Host}, \" \", ext.RPCServerOption(spanCtx))\n\tdefer finish()\n\n\text.Component.Set(span, e.ServiceName)\n\ttracing.LogRequest(span, req)\n\n\treq = req.WithContext(tracing.WithTracing(req.Context(), e.Tracing))\n\n\trecorder := newStatusCodeRecoder(rw, http.StatusOK)\n\te.next.ServeHTTP(recorder, req)\n\n\ttracing.LogResponseCode(span, recorder.Status())\n}"} {"input": "package localcommand\n\nimport (\n\t\"syscall\"\n\t\"time\"\n)\n\ntype Option func(*LocalCommand)\n\nfunc WithCloseSignal(signal syscall.Signal) Option {\n\treturn func(lcmd *LocalCommand) {\n\t\tlcmd.closeSignal = signal\n\t}\n}\n\n\n\nfunc WithCloseTimeout(timeout time.Duration) Option ", "output": "{\n\treturn func(lcmd *LocalCommand) {\n\t\tlcmd.closeTimeout = timeout\n\t}\n}"} {"input": "package cli\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/antham/goller/v2/dsl\"\n\t\"github.com/antham/goller/v2/sorter\"\n\t\"gopkg.in/alecthomas/kingpin.v2\"\n)\n\nvar sortersGlobal *sorter.Sorters\n\n\ntype Sorters struct {\n\tsorters *sorter.Sorters\n}\n\n\nfunc (s *Sorters) Init() {\n\tsortersGlobal = sorter.NewSorters()\n}\n\n\nfunc (s *Sorters) Set(value string) error {\n\tparser := dsl.NewParser(bytes.NewBufferString(value))\n\n\tstmts, err := parser.ParsePositionsAndFunctions()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t(*s).sorters = sortersGlobal\n\n\tfor _, stmt := range *stmts {\n\t\t(*s).sorters.Append(stmt.Position, stmt.Functions[0].Name, stmt.Functions[0].Args)\n\t}\n\n\treturn nil\n}\n\n\nfunc (s *Sorters) ValidatePositions(positions *[]int) error {\n\tif s.sorters == nil {\n\t\treturn nil\n\t}\n\n\tfor _, sorter := range *s.sorters {\n\t\tpositionMatch := false\n\n\t\tfor _, position := range *positions {\n\t\t\tif sorter.HasPosition(position) {\n\t\t\t\tpositionMatch = true\n\t\t\t}\n\t\t}\n\n\t\tif !positionMatch {\n\t\t\treturn fmt.Errorf(\"Sort is wrong : position %d doesn't exist\", sorter.GetPosition())\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc (s *Sorters) String() string {\n\treturn \"\"\n}\n\n\nfunc SortersWrapper(s kingpin.Settings) (target *Sorters) {\n\ttarget = &Sorters{}\n\ttarget.Init()\n\ts.SetValue(target)\n\treturn\n}\n\nfunc (s *Sorters) Get() *sorter.Sorters ", "output": "{\n\treturn s.sorters\n}"} {"input": "package images\n\nimport (\n\t\"testing\"\n\n\t\"github.com/rackspace/gophercloud\"\n\tth \"github.com/rackspace/gophercloud/testhelper\"\n)\n\nconst endpoint = \"http://localhost:57909/\"\n\n\n\nfunc TestGetURL(t *testing.T) {\n\tactual := getURL(endpointClient(), \"foo\")\n\texpected := endpoint + \"images/foo\"\n\tth.CheckEquals(t, expected, actual)\n}\n\nfunc TestListDetailURL(t *testing.T) {\n\tactual := listDetailURL(endpointClient())\n\texpected := endpoint + \"images/detail\"\n\tth.CheckEquals(t, expected, actual)\n}\n\nfunc endpointClient() *gophercloud.ServiceClient ", "output": "{\n\treturn &gophercloud.ServiceClient{Endpoint: endpoint}\n}"} {"input": "package dao\n\nimport (\n\t\"context\"\n\n\t\"go-common/app/job/live/push-search/conf\"\n\t\"go-common/library/queue/databus\"\n\t\"go-common/library/database/hbase.v2\"\n)\n\n\ntype Dao struct {\n\tc *conf.Config\n\tRoomInfoDataBus *databus.Databus\n\tAttentionDataBus *databus.Databus\n\tUserNameDataBus *databus.Databus\n\tPushSearchDataBus *databus.Databus\n\tSearchHBase *hbase.Client\n}\n\n\nfunc New(c *conf.Config) (dao *Dao) {\n\tdao = &Dao{\n\t\tc: c,\n\t\tRoomInfoDataBus: databus.New(c.DataBus.RoomInfo),\n\t\tAttentionDataBus: databus.New(c.DataBus.Attention),\n\t\tUserNameDataBus: databus.New(c.DataBus.UserName),\n\t\tPushSearchDataBus: databus.New(c.DataBus.PushSearch),\n\t\tSearchHBase: hbase.NewClient(&c.SearchHBase.Config),\n\t}\n\treturn\n}\n\n\n\n\n\nfunc (d *Dao) Ping(c context.Context) error {\n\treturn nil\n}\n\nfunc (d *Dao) Close() ", "output": "{\n\td.RoomInfoDataBus.Close()\n\td.AttentionDataBus.Close()\n\td.UserNameDataBus.Close()\n\treturn\n}"} {"input": "package like\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go-common/app/interface/main/activity/model/like\"\n\t\"go-common/library/cache/memcache\"\n\t\"go-common/library/log\"\n)\n\nconst (\n\t_prefixInfo = \"m_\"\n)\n\nfunc keyInfo(sid int64) string {\n\treturn fmt.Sprintf(\"%s%d\", _prefixInfo, sid)\n}\n\n\nfunc (dao *Dao) SetInfoCache(c context.Context, v *like.Subject, sid int64) (err error) {\n\tif v == nil {\n\t\tv = &like.Subject{}\n\t}\n\tvar (\n\t\tconn = dao.mc.Get(c)\n\t\tmckey = keyInfo(sid)\n\t)\n\tdefer conn.Close()\n\tif err = conn.Set(&memcache.Item{Key: mckey, Object: v, Flags: memcache.FlagGOB, Expiration: dao.mcLikeExpire}); err != nil {\n\t\tlog.Error(\"conn.Set error(%v)\", err)\n\t\treturn\n\t}\n\treturn\n}\n\n\n\n\nfunc (dao *Dao) InfoCache(c context.Context, sid int64) (v *like.Subject, err error) ", "output": "{\n\tvar (\n\t\tmckey = keyInfo(sid)\n\t\tconn = dao.mc.Get(c)\n\t\titem *memcache.Item\n\t)\n\tdefer conn.Close()\n\tif item, err = conn.Get(mckey); err != nil {\n\t\tif err == memcache.ErrNotFound {\n\t\t\terr = nil\n\t\t\tv = nil\n\t\t} else {\n\t\t\tlog.Error(\"conn.Get error(%v)\", err)\n\t\t}\n\t\treturn\n\t}\n\tif err = conn.Scan(item, &v); err != nil {\n\t\tlog.Error(\"item.Scan error(%v)\", err)\n\t\treturn\n\t}\n\treturn\n}"} {"input": "package hyperkube\n\nimport (\n\t\"io/ioutil\"\n\t\"strings\"\n\n\tutiltemplate \"github.com/kubernetes-sigs/service-catalog/pkg/kubernetes/pkg/util/template\"\n\t\"k8s.io/component-base/cli/flag\"\n\n\t\"github.com/spf13/pflag\"\n)\n\ntype serverRunFunc func(s *Server, args []string, stopCh <-chan struct{}) error\n\n\ntype Server struct {\n\tSimpleUsage string \n\tLong string \n\tRun serverRunFunc \n\tPrimaryName string\n\tAlternativeName string\n\tRespectsStopCh bool\n\n\tflags *pflag.FlagSet \n\thk *HyperKube\n}\n\n\nfunc (s *Server) Usage() error {\n\ttt := `{{if .Long}}{{.Long | trim | wrap \"\"}}\n{{end}}Usage:\n {{.SimpleUsage}} [flags]\n\nAvailable Flags:\n{{.Flags.FlagUsages}}`\n\n\treturn utiltemplate.ExecuteTemplate(s.hk.Out(), tt, s)\n}\n\n\nfunc (s *Server) Name() string {\n\tif s.PrimaryName != \"\" {\n\t\treturn s.PrimaryName\n\t}\n\tname := s.SimpleUsage\n\ti := strings.Index(name, \" \")\n\tif i >= 0 {\n\t\tname = name[:i]\n\t}\n\treturn name\n}\n\n\n\n\nfunc (s *Server) Flags() *pflag.FlagSet ", "output": "{\n\tif s.flags == nil {\n\t\ts.flags = pflag.NewFlagSet(s.Name(), pflag.ContinueOnError)\n\t\ts.flags.SetOutput(ioutil.Discard)\n\t\ts.flags.SetNormalizeFunc(flag.WordSepNormalizeFunc)\n\t}\n\treturn s.flags\n}"} {"input": "package timekeeper\n\nimport \"time\"\n\n\n\n\n\ntype TimeKeeper interface {\n\tAfter(d time.Duration) <-chan time.Time\n\tSleep(d time.Duration)\n\tNow() time.Time\n}\n\n\ntype realTime struct{}\n\nvar rt realTime\n\n\nfunc (t *realTime) After(d time.Duration) <-chan time.Time {\n\treturn time.After(d)\n}\n\n\nfunc (t *realTime) Sleep(d time.Duration) {\n\ttime.Sleep(d)\n}\n\n\n\n\n\nfunc (t *realTime) Now() time.Time {\n\treturn time.Now()\n}\n\nfunc RealTime() TimeKeeper ", "output": "{\n\treturn &rt\n}"} {"input": "package metrics\n\nimport (\n\t\"sync\"\n\n\tprom \"github.com/prometheus/client_golang/prometheus\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tsandboxGuageName = \"bundlelib_sandbox\"\n)\n\nvar (\n\tonce sync.Once\n\tcollector *Collector\n)\n\n\ntype Collector struct {\n\tSandbox prom.Gauge\n}\n\n\n\n\nfunc recoverMetricPanic() {\n\tif r := recover(); r != nil {\n\t\tlog.Errorf(\"Recovering from metric function - %v\", r)\n\t}\n}\n\n\n\nfunc RegisterCollector() {\n\tonce.Do(func() {\n\t\tcollector = &Collector{\n\t\t\tSandbox: prom.NewGauge(prom.GaugeOpts{\n\t\t\t\tName: sandboxGuageName,\n\t\t\t\tHelp: \"Guage of all sandbox namespaces that are active.\",\n\t\t\t}),\n\t\t}\n\n\t\terr := prom.Register(collector)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"unable to register collector with prometheus: %v\", err)\n\t\t}\n\t})\n}\n\n\nfunc SandboxCreated() {\n\tdefer recoverMetricPanic()\n\tcollector.Sandbox.Inc()\n}\n\n\nfunc SandboxDeleted() {\n\tdefer recoverMetricPanic()\n\tcollector.Sandbox.Dec()\n}\n\n\n\n\n\nfunc (c Collector) Collect(ch chan<- prom.Metric) {\n\tc.Sandbox.Collect(ch)\n}\n\nfunc (c Collector) Describe(ch chan<- *prom.Desc) ", "output": "{\n\tc.Sandbox.Describe(ch)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/go-redis/redis\"\n\t\"github.com/jasonlvhit/gocron\"\n)\n\n\n\nfunc lockedTask(name string) {\n\tfmt.Printf(\"Hello, %s!\\n\", name)\n\n\tt := time.NewTicker(time.Millisecond * 100)\n\tc := make(chan struct{})\n\ttime.AfterFunc(time.Second*5, func() {\n\t\tclose(c)\n\t})\n\n\tfor {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tfmt.Print(\".\")\n\t\tcase <-c:\n\t\t\tfmt.Println()\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\ntype locker struct {\n\tcache *redis.Client\n}\n\nfunc (s *locker) Lock(key string) (success bool, err error) {\n\tres, err := s.cache.SetNX(key, time.Now().String(), time.Second*15).Result()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn res, nil\n}\n\n\n\n\n\nfunc main() {\n\tl := &locker{\n\t\tredis.NewClient(&redis.Options{\n\t\t\tAddr: \"localhost:6379\",\n\t\t}),\n\t}\n\n\tgocron.SetLocker(l)\n\n\targ := \"Some Name\"\n\targs := os.Args[1:]\n\tif len(args) > 0 {\n\t\targ = args[0]\n\t}\n\n\tgocron.Every(1).Second().Lock().Do(lockedTask, arg)\n\t<-gocron.Start()\n}\n\nfunc (s *locker) Unlock(key string) error ", "output": "{\n\treturn s.cache.Del(key).Err()\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n)\n\n\ntype ChangeVolumeGroupBackupCompartmentDetails struct {\n\n\tCompartmentId *string `mandatory:\"true\" json:\"compartmentId\"`\n}\n\n\n\nfunc (m ChangeVolumeGroupBackupCompartmentDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package golbStoreIpsum\n\nimport (\n\t\"github.com/cryptix/golbStore\"\n)\n\nfunc (b IpsumBlog) Latest(n int, withText bool) ([]*golbStore.Entry, error) {\n\treturn nil, nil\n}\n\n\n\nfunc (b IpsumBlog) Delete(id string) error {\n\treturn nil\n}\n\nfunc (b IpsumBlog) Save(e *golbStore.Entry) error {\n\tb.store[e.ID] = e\n\n\treturn nil\n}\n\nfunc (b IpsumBlog) Get(id string) (*golbStore.Entry, error) ", "output": "{\n\te, found := b.store[id]\n\tif !found {\n\t\treturn nil, golbStore.ErrEntryNotFound\n\t}\n\n\treturn e, nil\n}"} {"input": "package gdrj\n\nimport (\n\t\"errors\"\n\n\t\"github.com/eaciit/orm/v1\"\n\t\"github.com/eaciit/toolkit\"\n)\n\nvar (\n\tNetMarginPLCode string = \"PL74D\"\n\tNetMarginPLHeader string = \"Net Margin\"\n)\n\ntype PLModel struct {\n\torm.ModelBase `json:\"-\" bson:\"-\"`\n\tID string `json:\"_id\" bson:\"_id\"` \n\tOrderIndex string\n\tPLHeader1 string\n\tPLHeader2 string\n\tPLHeader3 string\n\tAmount float64\n\tGLReff string\n}\n\nfunc (t *PLModel) RecordID() interface{} {\n\treturn t.ID\n}\n\nfunc (t *PLModel) TableName() string {\n\treturn \"plmodel\"\n}\n\nfunc PLModelGetByID(id string) *PLModel {\n\tt := new(PLModel)\n\tDB().GetById(t, id)\n\treturn t\n}\n\n\n\nfunc (t *PLModel) Save() error {\n\te := Save(t)\n\tif e != nil {\n\t\treturn errors.New(toolkit.Sprintf(\"[%v-%v] Error found : \", t.TableName(), \"save\", e.Error()))\n\t}\n\treturn e\n}\n\nfunc (t *PLModel) Delete() error {\n\te := Delete(t)\n\tif e != nil {\n\t\treturn errors.New(toolkit.Sprintf(\"[%v-%v] Error found : \", t.TableName(), \"delete\", e.Error()))\n\t}\n\treturn e\n}\n\nfunc PLModelGetAll(s *PLFinderParam) ([]*PLModel, error) ", "output": "{\n\tcursor, err := DB().Find(new(PLModel), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := []*PLModel{}\n\terr = cursor.Fetch(&result, 0, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcursor.Close()\n\n\n\tisSGARequest := false\n\tif s != nil {\n\t\tif s.Flag == \"gna\" {\n\t\t\tisSGARequest = true\n\t\t}\n\t}\n\n\tif !isSGARequest {\n\t\tparseResult := []*PLModel{}\n\t\tfor _, each := range result {\n\t\t\tif each.ID == \"PL94A\" || each.PLHeader1 != \"G&A Expenses\" {\n\t\t\t\tparseResult = append(parseResult, each)\n\t\t\t}\n\t\t}\n\n\t\tresult = parseResult\n\t}\n\n\n\treturn result, nil\n}"} {"input": "package normalizer\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestServiceNameReplacer(t *testing.T) ", "output": "{\n\tassert.Equal(t, \"abc\", ServiceName(\"ABC\"), \"lower case conversion\")\n\tassert.Equal(t, \"a_b_c__\", ServiceName(\"a&b%c/:\"), \"disallowed runes to underscore\")\n\tassert.Equal(t, \"a_z_0123456789.\", ServiceName(\"A_Z_0123456789.\"), \"allowed runes\")\n}"} {"input": "package window_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/kurin/blazer/x/window\"\n)\n\ntype Accumulator struct {\n\tw *window.Window\n}\n\nfunc (a Accumulator) Add(s string) {\n\ta.w.Insert([]string{s})\n}\n\n\n\nfunc NewAccum(size time.Duration) Accumulator {\n\tr := func(i, j interface{}) interface{} {\n\t\ta, ok := i.([]string)\n\t\tif !ok {\n\t\t\ta = nil\n\t\t}\n\t\tb, ok := j.([]string)\n\t\tif !ok {\n\t\t\tb = nil\n\t\t}\n\t\tfor _, s := range b {\n\t\t\ta = append(a, s)\n\t\t}\n\t\treturn a\n\t}\n\treturn Accumulator{w: window.New(size, time.Second, r)}\n}\n\nfunc Example_accumulator() {\n\ta := NewAccum(time.Minute)\n\ta.Add(\"this\")\n\ta.Add(\"is\")\n\ta.Add(\"that\")\n\tfmt.Printf(\"total: %v\\n\", a.All())\n}\n\nfunc (a Accumulator) All() []string ", "output": "{\n\tv := a.w.Reduce()\n\treturn v.([]string)\n}"} {"input": "package master\n\nimport ()\n\n\n\ntype frame struct {\n\tjob *job\n\tslaveName string\n\tframe int\n\tdata []byte\n\tprogress byte\n\tcompleted bool\n}\n\n\n\nfunc NewFrame(job *job, fr int) *frame {\n\treturn &frame{\n\t\tjob: job,\n\t\tslaveName: \"\",\n\t\tframe: fr,\n\t\tdata: nil,\n\t\tprogress: 0,\n\t\tcompleted: false,\n\t}\n}\n\n\n\nfunc (f *frame) Job() *job {\n\treturn f.job\n}\n\nfunc (f *frame) SlaveName() string {\n\treturn f.slaveName\n}\n\nfunc (f *frame) Frame() int {\n\treturn f.frame\n}\n\nfunc (f *frame) AlignedFrame() int {\n\treturn f.frame + f.Job().Start()\n}\n\n\n\nfunc (f *frame) Progress() byte {\n\treturn f.progress\n}\n\nfunc (f *frame) Completed() bool {\n\treturn f.completed\n}\n\nfunc (f *frame) File() []byte {\n\treturn f.Job().File()\n}\n\n\n\nfunc (f *frame) SetSlaveName(slaveName string) {\n\tf.slaveName = slaveName\n}\n\nfunc (f *frame) SetData(data []byte) {\n\tf.data = data\n}\n\nfunc (f *frame) SetProgress(progress byte) {\n\tf.progress = progress\n}\n\nfunc (f *frame) SetCompleted(completed bool) {\n\tf.completed = completed\n\tif completed {\n\t\tf.SetProgress(100)\n\t}\n}\n\n\n\nfunc (f *frame) Reset() {\n\tf.SetSlaveName(\"\")\n\tf.SetData(nil)\n\tf.SetProgress(0)\n\tf.SetCompleted(false)\n}\n\nfunc (f *frame) Data() []byte ", "output": "{\n\treturn f.data\n}"} {"input": "package lib\n\nimport (\n\t\"context\"\n\t\"os\"\n\n\t\"github.com/danjacques/gofslock/fslock\"\n\t\"github.com/maruel/subcommands\"\n\t\"go.chromium.org/luci/common/logging\"\n)\n\n\n\nfunc RunExclusive(ctx context.Context, env subcommands.Env, command func(context.Context) error) error {\n\tlockFilePath, drainFilePath, err := computeMutexPaths(env)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogging.Infof(ctx, \"[mmutex][exclusive] LockFilePath: %s, DrainFilePath: %s.\", lockFilePath, drainFilePath)\n\tif len(lockFilePath) == 0 {\n\t\treturn command(ctx)\n\t}\n\n\tfile, err := os.OpenFile(drainFilePath, os.O_RDONLY|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = file.Close(); err != nil {\n\t\treturn err\n\t}\n\tdefer RemoveDrainFile(ctx, drainFilePath)\n\n\tblocker := createLockBlocker(ctx)\n\treturn fslock.WithBlocking(lockFilePath, blocker, func() error {\n\t\tif err := os.Remove(drainFilePath); err != nil {\n\t\t\tlogging.Errorf(ctx, \"[mmutex][exclusive] Failed to remove drain file after acquiring the lock: %s\", drainFilePath)\n\t\t\treturn err\n\t\t}\n\t\tlogging.Infof(ctx, \"[mmutex][exclusive] Lock acquired and drain file removed.\")\n\n\t\treturn command(ctx)\n\t})\n}\n\n\n\nfunc RemoveDrainFile(ctx context.Context, drainFilePath string) ", "output": "{\n\tif err := os.Remove(drainFilePath); err != nil && !os.IsNotExist(err) {\n\t\tlogging.Errorf(ctx, \"[mmutex][exclusive] Failed to remove drain file: %s\", err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"runtime\"\n)\n\nfunc newClientHTTP(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tbuf := make([]byte, 4096)\n\t\t\tn := runtime.Stack(buf, false)\n\t\t\tbuf = buf[0:n]\n\t\t\tlog.Fatalf(\"client run panic %s:%v\", buf, e)\n\t\t}\n\t\tnotifier.Done()\n\t}()\n\tnotifier.Add(1)\n\tw.Write([]byte(\"Http server is not implemented yet...\"))\n}\n\n\n\nfunc startHttpListener() ", "output": "{\n\tdefer func() {\n\t\tfmt.Println(\"stopped REST server...\")\n\t\tnotifier.Done()\n\t}()\n\tnotifier.Add(1)\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tnewClientHTTP(w, r)\n\t})\n\n\tsvr := http.Server{Handler: mux}\n\tsvr.Serve(tcplistener)\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"github.com/spf13/cobra\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\n\nvar execCmd = &cobra.Command{\n\tUse: \"exec \",\n\tShort: \"Run any command inside a running container\",\n\tLong: `Execute commands inside one of the containers running in your docker-compose defined cluster.\ni/e \"dcmd exec rails c\" will translate in \"docker exec -it rails c\n`,\n\tRun: invokeCommand,\n}\n\nfunc invokeCommand(cmd *cobra.Command, args []string) {\n\tif len(args) == 0 {\n\t\tcmd.Usage()\n\t\tos.Exit(1)\n\t}\n\tcontainer := chooseContainer()\n\tdockerExec(container, args)\n}\n\n\n\nfunc init() {\n\tRootCmd.AddCommand(execCmd)\n\n\n\n\n}\n\nfunc dockerExec(containerName string, command []string) ", "output": "{\n\tres := fmt.Sprintf(\"docker exec -it %v %s\", containerName, strings.Join(command, \" \"))\n\tfmt.Printf(\"Executing: \\\"%s\\\"\\n\", res)\n\n\texpandedCommand := strings.Split(res, \" \")\n\tcmd := exec.Command(expandedCommand[0], expandedCommand[1:]...)\n\n\tcmd.Stdout = os.Stdout\n\tcmd.Stdin = os.Stdin\n\tcmd.Stderr = os.Stderr\n\n\terr := cmd.Run()\n\n\tif err != nil {\n\t\tlog.Fatal(`Error executing the command`)\n\t}\n}"} {"input": "package node\n\nimport (\n\t\"github.com/n0stack/n0stack/n0proto.go/pool/v0\"\n)\n\n\n\nfunc IsLockedForDeletion(node *ppool.Node) bool ", "output": "{\n\tfor _, c := range node.ReservedComputes {\n\t\tif _, ok := c.Annotations[AnnotationComputeDisableDeletionLock]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn true\n\t}\n\n\tfor _, s := range node.ReservedStorages {\n\t\tif _, ok := s.Annotations[AnnotationStorageDisableDeletionLock]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn true\n\t}\n\n\treturn false\n}"} {"input": "package train\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"path\"\n\t\"strings\"\n)\n\nvar assetServer *http.Handler\nvar publicAssetServer *http.Handler\n\n\n\nvar contentTypes = map[string]string{\n\t\".js\": \"application/javascript\",\n\t\".css\": \"text/css\",\n}\n\nfunc serveAssets(w http.ResponseWriter, r *http.Request) {\n\turl := r.URL.Path\n\text := path.Ext(url)\n\n\tswitch ext {\n\tcase \".js\", \".css\":\n\t\tcontent, err := ReadAsset(url)\n\t\tif err != nil {\n\t\t\tif strings.Contains(err.Error(), \"Could not compile\") {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t} else {\n\t\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\t}\n\n\t\t\tio.Copy(w, strings.NewReader(err.Error()))\n\t\t\tlog.Printf(\"Failed to deliver asset\\nGET %s\\n-----------------------\\n%s\\n\", url, err.Error())\n\t\t} else {\n\t\t\tw.Header().Set(\"Content-Type\", contentTypes[ext])\n\t\t\tio.Copy(w, strings.NewReader(content))\n\t\t}\n\tdefault:\n\t\t(*assetServer).ServeHTTP(w, r)\n\t}\n}\n\nfunc setupFileServer() {\n\tif assetServer == nil {\n\t\tserver := http.FileServer(http.Dir(Config.AssetsPath + \"/..\"))\n\t\tassetServer = &server\n\t}\n\tif publicAssetServer == nil {\n\t\tserver := http.FileServer(http.Dir(\"public\"))\n\t\tpublicAssetServer = &server\n\t}\n}\n\nfunc servePublicAssets(w http.ResponseWriter, r *http.Request) ", "output": "{\n\t(*publicAssetServer).ServeHTTP(w, r)\n}"} {"input": "package internal\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"gopkg.in/reform.v1\"\n)\n\n\ntype Logger struct {\n\tprintf reform.Printf\n\tdebug bool\n}\n\n\nfunc NewLogger(prefix string, debug bool) *Logger {\n\tvar flags int\n\tif debug {\n\t\tflags = log.Ldate | log.Lmicroseconds | log.Lshortfile\n\t}\n\n\tl := log.New(os.Stderr, prefix, flags)\n\treturn &Logger{\n\t\tprintf: func(format string, args ...interface{}) {\n\t\t\tl.Output(3, fmt.Sprintf(format, args...))\n\t\t},\n\t\tdebug: debug,\n\t}\n}\n\n\nfunc (l *Logger) Debugf(format string, args ...interface{}) {\n\tif l.debug {\n\t\tl.printf(format, args...)\n\t}\n}\n\n\n\n\n\n\nfunc (l *Logger) Fatalf(format string, args ...interface{}) {\n\tl.printf(format, args...)\n\tif l.debug {\n\t\tpanic(fmt.Sprintf(format, args...))\n\t}\n\tos.Exit(1)\n}\n\nfunc (l *Logger) Printf(format string, args ...interface{}) ", "output": "{\n\tl.printf(format, args...)\n}"} {"input": "package text\n\nimport \"fmt\"\n\nconst (\n\tredCode = \"\\x1b[31m\"\n\tgreenCode = \"\\x1b[32m\"\n\tyellowCode = \"\\x1b[33m\"\n\tblueCode = \"\\x1b[34m\"\n\tmagentaCode = \"\\x1b[35m\"\n\tCyanCode = \"\\x1b[36m\"\n\tboldCode = \"\\x1b[1m\"\n\n\tResetCode = \"\\x1b[0m\"\n)\n\n\nvar UseColor = true\n\nfunc stylize(startCode, in string) string {\n\tif UseColor {\n\t\treturn startCode + in + ResetCode\n\t}\n\n\treturn in\n}\n\nfunc Red(in string) string {\n\treturn stylize(redCode, in)\n}\n\nfunc Green(in string) string {\n\treturn stylize(greenCode, in)\n}\n\nfunc yellow(in string) string {\n\treturn stylize(yellowCode, in)\n}\n\nfunc Cyan(in string) string {\n\treturn stylize(CyanCode, in)\n}\n\n\n\nfunc Blue(in string) string {\n\treturn stylize(blueCode, in)\n}\n\nfunc Bold(in string) string {\n\treturn stylize(boldCode, in)\n}\n\n\n\nfunc ColorHash(name string) (output string) {\n\tif !UseColor {\n\t\treturn name\n\t}\n\n\tvar hash uint = 5381\n\n\tfor i := 0; i < len(name); i++ {\n\t\thash = uint(name[i]) + ((hash << 5) + (hash))\n\t}\n\n\treturn fmt.Sprintf(\"\\x1b[%dm%s\\x1b[0m\", hash%6+31, name)\n}\n\nfunc Magenta(in string) string ", "output": "{\n\treturn stylize(magentaCode, in)\n}"} {"input": "package zfs\n\nimport (\n\t\"github.com/containers/storage/drivers\"\n\t\"github.com/pkg/errors\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc checkRootdirFs(rootDir string) error {\n\tfsMagic, err := graphdriver.GetFSMagic(rootDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbackingFS := \"unknown\"\n\tif fsName, ok := graphdriver.FsNames[fsMagic]; ok {\n\t\tbackingFS = fsName\n\t}\n\n\tif fsMagic != graphdriver.FsMagicZfs {\n\t\tlogrus.WithField(\"root\", rootDir).WithField(\"backingFS\", backingFS).WithField(\"storage-driver\", \"zfs\").Error(\"No zfs dataset found for root\")\n\t\treturn errors.Wrapf(graphdriver.ErrPrerequisites, \"no zfs dataset found for rootdir '%s'\", rootDir)\n\t}\n\n\treturn nil\n}\n\n\n\nfunc getMountpoint(id string) string ", "output": "{\n\treturn id\n}"} {"input": "package ginkgoext\n\nimport (\n\t\"github.com/onsi/gomega/types\"\n)\n\ntype anythingMatcher struct{}\n\nfunc (matcher *anythingMatcher) Match(actual interface{}) (success bool, err error) {\n\treturn true, nil\n}\n\nfunc (matcher *anythingMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn \"\"\n}\n\nfunc (matcher *anythingMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn \"\"\n}\n\n\n\n\nfunc BeAnything() types.GomegaMatcher ", "output": "{\n\treturn &anythingMatcher{}\n}"} {"input": "package tracing\n\nimport (\n\t\"crypto/sha256\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/containous/traefik/log\"\n)\n\n\nconst TraceNameHashLength = 8\n\n\n\nconst OperationNameMaxLengthNumber = 10\n\n\n\n\nfunc truncateString(str string, num int) string {\n\ttext := str\n\tif len(str) > num {\n\t\tif num > 3 {\n\t\t\tnum -= 3\n\t\t}\n\t\ttext = str[0:num] + \"...\"\n\t}\n\treturn text\n}\n\n\nfunc computeHash(name string) string {\n\tdata := []byte(name)\n\thash := sha256.New()\n\tif _, err := hash.Write(data); err != nil {\n\t\tlog.WithoutContext().WithField(\"OperationName\", name).Errorf(\"Failed to create Span name hash for %s: %v\", name, err)\n\t}\n\n\treturn fmt.Sprintf(\"%x\", hash.Sum(nil))[:TraceNameHashLength]\n}\n\nfunc generateOperationName(prefix string, parts []string, sep string, spanLimit int) string ", "output": "{\n\tname := prefix + \" \" + strings.Join(parts, sep)\n\n\tmaxLength := OperationNameMaxLengthNumber + len(prefix) + 1\n\n\tif spanLimit > 0 && len(name) > spanLimit {\n\t\tif spanLimit < maxLength {\n\t\t\tlog.WithoutContext().Warnf(\"SpanNameLimit cannot be lesser than %d: falling back on %d, maxLength, maxLength+3\", maxLength)\n\t\t\tspanLimit = maxLength + 3\n\t\t}\n\n\t\tlimit := (spanLimit - maxLength) / 2\n\n\t\tvar fragments []string\n\t\tfor _, value := range parts {\n\t\t\tfragments = append(fragments, truncateString(value, limit))\n\t\t}\n\t\tfragments = append(fragments, computeHash(name))\n\n\t\tname = prefix + \" \" + strings.Join(fragments, sep)\n\t}\n\n\treturn name\n}"} {"input": "package labassistant\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc make_ob() *Observation {\n\treturn &Observation{}\n}\n\nfunc good_func(i int) int {\n\treturn i\n}\n\n\n\nfunc bad_func(i int) int {\n\treturn i + 1\n}\n\nfunc TestObservationRunIsOK(t *testing.T) {\n\ta := assert.New(t)\n\tout := make_ob().run(good_func, 1)\n\ta.Equal([]interface{}{1}, out)\n\n\tout = make_ob().run(good_func, 0)\n\ta.NotEqual([]interface{}{1}, out)\n\n\ta.Panics(func() {\n\t\tmake_ob().run(good_func)\n\t})\n\n\ta.Panics(func() {\n\t\tmake_ob().run(good_func, 1, 1)\n\t})\n\n\ta.Panics(func() {\n\t\tmake_ob().run(good_func, \"string\")\n\t})\n}\n\nfunc TestObservationRunSetsValues(t *testing.T) {\n\ta := assert.New(t)\n\tgood := make_ob()\n\tgood.run(good_func, 1)\n\ta.Equal(\"github.com/lmas/labassistant.good_func\", good.Name)\n\ta.Empty(good.Panic)\n\ta.Equal([]interface{}{1}, good.Outputs)\n\ta.NotEmpty(good.Start)\n\ta.NotZero(good.Duration)\n\n\tbad := make_ob()\n\tbad.can_panic = true\n\ta.NotPanics(func() {\n\t\tbad.run(panic_func, 1)\n\t})\n\ta.Equal(\"panic\", bad.Panic)\n\ta.Empty(bad.Outputs)\n\ta.NotEmpty(bad.Start)\n\ta.Zero(bad.Duration)\n}\n\nfunc panic_func(i int) int ", "output": "{\n\tpanic(\"panic\")\n}"} {"input": "package protocol\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\tsyncthingprotocol \"github.com/syncthing/syncthing/lib/protocol\"\n)\n\nconst (\n\tmessageTypePing int32 = iota\n\tmessageTypePong\n\tmessageTypeJoinRelayRequest\n\tmessageTypeJoinSessionRequest\n\tmessageTypeResponse\n\tmessageTypeConnectRequest\n\tmessageTypeSessionInvitation\n)\n\ntype header struct {\n\tmagic uint32\n\tmessageType int32\n\tmessageLength int32\n}\n\ntype Ping struct{}\ntype Pong struct{}\ntype JoinRelayRequest struct{}\n\ntype JoinSessionRequest struct {\n\tKey []byte \n}\n\ntype Response struct {\n\tCode int32\n\tMessage string\n}\n\ntype ConnectRequest struct {\n\tID []byte \n}\n\ntype SessionInvitation struct {\n\tFrom []byte \n\tKey []byte \n\tAddress []byte \n\tPort uint16\n\tServerSocket bool\n}\n\n\n\nfunc (i SessionInvitation) GoString() string {\n\treturn i.String()\n}\n\nfunc (i SessionInvitation) AddressString() string {\n\treturn fmt.Sprintf(\"%s:%d\", net.IP(i.Address), i.Port)\n}\n\nfunc (i SessionInvitation) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%s@%s\", syncthingprotocol.DeviceIDFromBytes(i.From), i.AddressString())\n}"} {"input": "package iso20022\n\n\ntype TaxReportHeader1 struct {\n\n\tMessageIdentification *MessageIdentification1 `xml:\"MsgId\"`\n\n\tNumberOfTaxReports *Number `xml:\"NbOfTaxRpts,omitempty\"`\n\n\tTaxAuthority []*TaxOrganisationIdentification1 `xml:\"TaxAuthrty,omitempty\"`\n}\n\n\n\nfunc (t *TaxReportHeader1) SetNumberOfTaxReports(value string) {\n\tt.NumberOfTaxReports = (*Number)(&value)\n}\n\nfunc (t *TaxReportHeader1) AddTaxAuthority() *TaxOrganisationIdentification1 {\n\tnewValue := new(TaxOrganisationIdentification1)\n\tt.TaxAuthority = append(t.TaxAuthority, newValue)\n\treturn newValue\n}\n\nfunc (t *TaxReportHeader1) AddMessageIdentification() *MessageIdentification1 ", "output": "{\n\tt.MessageIdentification = new(MessageIdentification1)\n\treturn t.MessageIdentification\n}"} {"input": "package gode\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n)\n\n\n\nfunc TestRemovePackage(t *testing.T) {\n\tc := setup()\n\tmust(os.RemoveAll(filepath.Join(c.RootPath, \"node_modules\")))\n\tmust(c.InstallPackage(\"request\"))\n\tpackages, err := c.Packages()\n\tmust(err)\n\tif len(packages) != 1 {\n\t\tt.Fatalf(\"package did not install correctly\")\n\t}\n\tmust(c.RemovePackage(\"request\"))\n\tpackages, err = c.Packages()\n\tmust(err)\n\tif len(packages) != 0 {\n\t\tt.Fatalf(\"package did not remove correctly\")\n\t}\n}\n\nfunc TestUpdatePackages(t *testing.T) {\n\tc := setup()\n\tmust(c.InstallPackage(\"request\"))\n\t_, err := c.UpdatePackages()\n\tmust(err)\n}\n\nfunc TestPackagesGithubPackage(t *testing.T) {\n\tc := setup()\n\tmust(os.RemoveAll(filepath.Join(c.RootPath, \"node_modules\")))\n\tmust(c.InstallPackage(\"dickeyxxx/heroku-production-check\"))\n\tpackages, err := c.Packages()\n\tmust(err)\n\tfor _, pkg := range packages {\n\t\tif pkg.Name == \"heroku-production-check\" {\n\t\t\treturn\n\t\t}\n\t}\n\tt.Fatalf(\"package did not install\")\n}\n\nfunc TestPackages(t *testing.T) ", "output": "{\n\tc := setup()\n\tmust(os.RemoveAll(filepath.Join(c.RootPath, \"node_modules\")))\n\tmust(c.InstallPackage(\"request\"))\n\tpackages, err := c.Packages()\n\tmust(err)\n\tfor _, pkg := range packages {\n\t\tif pkg.Name == \"request\" {\n\t\t\treturn\n\t\t}\n\t}\n\tt.Fatalf(\"package did not install\")\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math/big\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"github.com/go-xorm/xorm\"\n)\n\n\ntype Account struct {\n\tId int64\n\tBalance string `xorm:\"Decimal(32,16)\"`\n\tVersion int `xorm:\"version\"` \n}\n\nvar x *xorm.Engine\n\n\n\nfunc main() {\n\tn := new(big.Int)\n\tn, ok := n.SetString(\"1000\", 10)\n\tif !ok {\n\t\tfmt.Println(\"SetString: error\")\n\t\treturn\n\t}\n\t_, err := x.Insert(&Account{Balance: n.String()})\n\tif err != nil {\n\t\tlog.Fatalf(\"insert failed, err: %v\", err)\n\t}\n\n\ta := &Account{}\n\thas, err := x.ID(1).Get(a)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else if !has {\n\t\tlog.Fatal(\"Account does not exist\")\n\t}\n\n\tfmt.Printf(\"account balance: %v\\n\", a.Balance)\n}\n\nfunc init() ", "output": "{\n\tvar err error\n\tx, err = xorm.NewEngine(\"mysql\", \"root:password@tcp(10.10.0.122)/test?charset=utf8&parseTime=True&loc=Local\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to create engine: %v\\n\", err)\n\t}\n\n\tif err = x.Sync(new(Account)); err != nil {\n\t\tlog.Fatalf(\"Fail to sync database: %v\\n\", err)\n\t}\n}"} {"input": "package main\n\nimport \"gorm.io/gorm\"\n\n\n\nfunc getUsers(db *gorm.DB, names []string) []User ", "output": "{\n\tres := make([]User, 0, len(names))\n\tfor _, name := range names {\n\t\tvar user User\n\t\tdb.Where(\"name = ?\", name).First(&user)\n\t\tres = append(res, user)\n\t}\n\treturn res\n}"} {"input": "package pflag\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype boolValue bool\n\nfunc newBoolValue(val bool, p *bool) *boolValue {\n\t*p = val\n\treturn (*boolValue)(p)\n}\n\nfunc (b *boolValue) Set(s string) error {\n\tv, err := strconv.ParseBool(s)\n\t*b = boolValue(v)\n\treturn err\n}\n\nfunc (b *boolValue) String() string { return fmt.Sprintf(\"%v\", *b) }\n\n\n\nfunc (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc BoolVar(p *bool, name string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\n\n\n\n\nfunc (f *FlagSet) Bool(name string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, \"\", value, usage)\n\treturn p\n}\n\n\nfunc (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, shorthand, value, usage)\n\treturn p\n}\n\n\n\nfunc Bool(name string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, \"\", value, usage)\n}\n\n\nfunc BoolP(name, shorthand string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, shorthand, value, usage)\n}\n\nfunc BoolVarP(p *bool, name, shorthand string, value bool, usage string) ", "output": "{\n\tCommandLine.VarP(newBoolValue(value, p), name, shorthand, usage)\n}"} {"input": "package server\n\nimport (\n\t\"sync/atomic\"\n\n\t\"github.com/berkaroad/saashard/admin\"\n\t\"github.com/berkaroad/saashard/config\"\n\t\"github.com/berkaroad/saashard/proxy\"\n)\n\nconst (\n\tOffline = iota\n\tOnline\n\tUnknown\n)\n\n\ntype Server struct {\n\tcfg *config.Config\n\n\tstatusIndex int32\n\tstatus [2]int32\n\trunning bool\n\n\tproxy *proxy.Server\n\tadmin *admin.Server\n}\n\n\nfunc NewServer(cfg *config.Config) (*Server, error) {\n\tvar err error\n\ts := new(Server)\n\ts.cfg = cfg\n\n\tatomic.StoreInt32(&s.statusIndex, 0)\n\ts.status[s.statusIndex] = Online\n\n\ts.proxy, err = proxy.NewServer(cfg)\n\ts.admin, err = admin.NewServer(cfg)\n\treturn s, err\n}\n\n\n\n\n\nfunc (s *Server) Status() string {\n\tvar status string\n\tswitch s.status[s.statusIndex] {\n\tcase Online:\n\t\tstatus = \"online\"\n\tcase Offline:\n\t\tstatus = \"offline\"\n\tcase Unknown:\n\t\tstatus = \"unknown\"\n\tdefault:\n\t\tstatus = \"unknown\"\n\t}\n\treturn status\n}\n\n\nfunc (s *Server) Close() {\n\ts.running = false\n\ts.proxy.Close()\n\ts.admin.Close()\n}\n\nfunc (s *Server) Run() ", "output": "{\n\ts.running = true\n\n\tgo s.proxy.Run()\n\n\ts.admin.Run()\n}"} {"input": "package mytime\n\nimport (\n\t\"cloud.google.com/go/spanner\"\n\t\"github.com/tcncloud/protoc-gen-persist/examples/test\"\n)\n\ntype MyEnum struct {\n\tStatus int32\n}\n\n\n\nfunc (t MyEnum) ToProto() test.TestEnum {\n\treturn test.TestEnum(t.Status)\n}\n\nfunc (t *MyEnum) SpannerScan(src *spanner.GenericColumnValue) error {\n\tvar lt int64\n\n\terr := src.Decode(<)\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.Status = int32(lt)\n\n\treturn nil\n}\n\nfunc (t *MyEnum) SpannerValue() (interface{}, error) {\n\treturn int64(t.Status), nil\n}\n\nfunc (t MyEnum) ToSpanner(src test.TestEnum) *MyEnum", "output": "{\n\tt.Status = int32(src)\n\n\treturn &t\n}"} {"input": "package msgraph\n\nimport \"context\"\n\n\ntype WorkbookFunctionsTanRequestBuilder struct{ BaseRequestBuilder }\n\n\nfunc (b *WorkbookFunctionsRequestBuilder) Tan(reqObj *WorkbookFunctionsTanRequestParameter) *WorkbookFunctionsTanRequestBuilder {\n\tbb := &WorkbookFunctionsTanRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.BaseRequestBuilder.baseURL += \"/tan\"\n\tbb.BaseRequestBuilder.requestObject = reqObj\n\treturn bb\n}\n\n\ntype WorkbookFunctionsTanRequest struct{ BaseRequest }\n\n\n\n\n\nfunc (r *WorkbookFunctionsTanRequest) Post(ctx context.Context) (resObj *WorkbookFunctionResult, err error) {\n\terr = r.JSONRequest(ctx, \"POST\", \"\", r.requestObject, &resObj)\n\treturn\n}\n\nfunc (b *WorkbookFunctionsTanRequestBuilder) Request() *WorkbookFunctionsTanRequest ", "output": "{\n\treturn &WorkbookFunctionsTanRequest{\n\t\tBaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},\n\t}\n}"} {"input": "package web\n\nimport (\n\t\"strings\"\n\n\t\"github.com/gopherjs/gopherjs/js\"\n)\n\nfunc IsNodeJS() bool {\n\treturn js.Global.Get(\"require\") != js.Undefined\n}\n\n\n\nfunc IsIOSSafari() bool {\n\tua := js.Global.Get(\"navigator\").Get(\"userAgent\").String()\n\tif !strings.Contains(ua, \"iPhone\") {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc IsAndroidChrome() bool {\n\tua := js.Global.Get(\"navigator\").Get(\"userAgent\").String()\n\tif !strings.Contains(ua, \"Android\") {\n\t\treturn false\n\t}\n\tif !strings.Contains(ua, \"Chrome\") {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc IsMobileBrowser() bool {\n\treturn IsIOSSafari() || IsAndroidChrome()\n}\n\nfunc IsBrowser() bool ", "output": "{\n\treturn !IsNodeJS()\n}"} {"input": "package fake_routing_api\n\nimport (\n\t\"sync\"\n\n\t\"github.com/cloudfoundry-incubator/routing-api\"\n)\n\ntype FakeTcpEventSource struct {\n\tNextStub func() (routing_api.TcpEvent, error)\n\tnextMutex sync.RWMutex\n\tnextArgsForCall []struct{}\n\tnextReturns struct {\n\t\tresult1 routing_api.TcpEvent\n\t\tresult2 error\n\t}\n\tCloseStub func() error\n\tcloseMutex sync.RWMutex\n\tcloseArgsForCall []struct{}\n\tcloseReturns struct {\n\t\tresult1 error\n\t}\n}\n\n\n\nfunc (fake *FakeTcpEventSource) NextCallCount() int {\n\tfake.nextMutex.RLock()\n\tdefer fake.nextMutex.RUnlock()\n\treturn len(fake.nextArgsForCall)\n}\n\nfunc (fake *FakeTcpEventSource) NextReturns(result1 routing_api.TcpEvent, result2 error) {\n\tfake.NextStub = nil\n\tfake.nextReturns = struct {\n\t\tresult1 routing_api.TcpEvent\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nfunc (fake *FakeTcpEventSource) Close() error {\n\tfake.closeMutex.Lock()\n\tfake.closeArgsForCall = append(fake.closeArgsForCall, struct{}{})\n\tfake.closeMutex.Unlock()\n\tif fake.CloseStub != nil {\n\t\treturn fake.CloseStub()\n\t} else {\n\t\treturn fake.closeReturns.result1\n\t}\n}\n\nfunc (fake *FakeTcpEventSource) CloseCallCount() int {\n\tfake.closeMutex.RLock()\n\tdefer fake.closeMutex.RUnlock()\n\treturn len(fake.closeArgsForCall)\n}\n\nfunc (fake *FakeTcpEventSource) CloseReturns(result1 error) {\n\tfake.CloseStub = nil\n\tfake.closeReturns = struct {\n\t\tresult1 error\n\t}{result1}\n}\n\nvar _ routing_api.TcpEventSource = new(FakeTcpEventSource)\n\nfunc (fake *FakeTcpEventSource) Next() (routing_api.TcpEvent, error) ", "output": "{\n\tfake.nextMutex.Lock()\n\tfake.nextArgsForCall = append(fake.nextArgsForCall, struct{}{})\n\tfake.nextMutex.Unlock()\n\tif fake.NextStub != nil {\n\t\treturn fake.NextStub()\n\t} else {\n\t\treturn fake.nextReturns.result1, fake.nextReturns.result2\n\t}\n}"} {"input": "package main\n\nimport (\n \"github.com/emicklei/go-restful\"\n \"io\"\n \"net/http\"\n)\n\n\n\n\n\n\nfunc main() {\n ws := new(restful.WebService)\n ws.Route(ws.GET(\"/secret\").Filter(basicAuthenticate).To(secret))\n restful.Add(ws)\n http.ListenAndServe(\":8080\", nil)\n}\n\n\n\nfunc secret(req *restful.Request, resp *restful.Response) {\n io.WriteString(resp, \"42\")\n}\n\nfunc basicAuthenticate(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) ", "output": "{\n encoded := req.Request.Header.Get(\"Authorization\")\n \n \n if len(encoded) == 0 || \"Basic YWRtaW46YWRtaW4=\" != encoded {\n resp.AddHeader(\"WWW-Authenticate\", \"Basic realm=Protected Area\")\n resp.WriteErrorString(401, \"401: Not Authorized\")\n return\n }\n chain.ProcessFilter(req, resp)\n}"} {"input": "package enumflag\n\nimport \"fmt\"\n\ntype enumFlag struct {\n\ttarget *string\n\toptions []string\n}\n\n\n\n\nfunc (f *enumFlag) String() string {\n\treturn *f.target\n}\n\nfunc (f *enumFlag) Set(value string) error {\n\tfor _, v := range f.options {\n\t\tif v == value {\n\t\t\t*f.target = value\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"expected one of %q\", f.options)\n}\n\nfunc New(target *string, options ...string) *enumFlag ", "output": "{\n\treturn &enumFlag{target: target, options: options}\n}"} {"input": "package dml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/dml\"\n)\n\nfunc TestCT_Scale2DConstructor(t *testing.T) {\n\tv := dml.NewCT_Scale2D()\n\tif v == nil {\n\t\tt.Errorf(\"dml.NewCT_Scale2D must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed dml.CT_Scale2D should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestCT_Scale2DMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := dml.NewCT_Scale2D()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := dml.NewCT_Scale2D()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/jackmanlabs/rpc/v2\"\n\t\"github.com/jackmanlabs/rpc/v2/json2\"\n)\n\ntype Counter struct {\n\tCount int\n}\n\ntype IncrReq struct {\n\tDelta int\n}\n\n\n\n\ntype GetReq struct {\n}\n\nfunc (c *Counter) Get(r *http.Request, req *GetReq, res *Counter) error {\n\tlog.Printf(\"<- Get %+v\", *req)\n\t*res = *c\n\tlog.Printf(\"-> %v\", *res)\n\treturn nil\n}\n\nfunc main() {\n\taddress := flag.String(\"address\", \":65534\", \"\")\n\ts := rpc.NewServer()\n\ts.RegisterCodec(json2.NewCustomCodec(&rpc.CompressionSelector{}), \"application/json\")\n\ts.RegisterService(new(Counter), \"\")\n\thttp.Handle(\"/\", http.StripPrefix(\"/\", http.FileServer(http.Dir(\"./\"))))\n\thttp.Handle(\"/jsonrpc/\", s)\n\tlog.Fatal(http.ListenAndServe(*address, nil))\n}\n\nfunc (c *Counter) Incr(r *http.Request, req *IncrReq, res *json2.EmptyResponse) error ", "output": "{\n\tlog.Printf(\"<- Incr %+v\", *req)\n\tc.Count += req.Delta\n\treturn nil\n}"} {"input": "package controllers\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/astaxie/beego\"\n\t\"github.com/scmo/apayment-backend/models\"\n\t\"github.com/scmo/apayment-backend/services\"\n\t\"time\"\n)\n\n\n\n\ntype JournalController struct {\n\tbeego.Controller\n}\n\nfunc (controller *JournalController) getUser() *models.User {\n\tclaims, err := services.ParseToken(controller.Ctx.Request.Header.Get(\"Authorization\"))\n\tif err != nil {\n\t\tcontroller.CustomAbort(401, \"Unauthorized\")\n\t}\n\tuser, err := services.GetUserByUsername(claims.Subject)\n\tif err != nil {\n\t\tcontroller.CustomAbort(404, err.Error())\n\t}\n\treturn user\n}\n\n\n\n\n\n\n\nfunc (this *JournalController) GetMonthlyStats() {\n\n\tuser := this.getUser()\n\n\tmonth, err := this.GetUint8(\"month\")\n\tif err != nil {\n\t\tthis.CustomAbort(400, \"Month not sent\")\n\t}\n\tyear, err := this.GetUint16(\"year\")\n\tif err != nil {\n\t\tthis.CustomAbort(400, \"Year not sent\")\n\t}\n\n\tif month < 1 || month > 12 || year < 1900 || year > uint16(time.Now().Year()) {\n\t\tthis.CustomAbort(400, \"Value not possible for one of the parameter. Year must be a 4 digit integer. Month parameter must be a interger between 1 and 31.\")\n\t}\n\n\tmonthlyStats, err := services.GetMonthlyStats(user.TVD, month, year)\n\tif err != nil {\n\t\tthis.CustomAbort(501, \"Internal Error \"+err.Error())\n\t}\n\tthis.Data[\"json\"] = monthlyStats\n\tthis.ServeJSON()\n}\n\n\n\n\n\n\n\n\nfunc (this *JournalController) AddJournalEntry() ", "output": "{\n\tuser := this.getUser()\n\n\tvar journalEntry models.JournalEntry\n\tjson.Unmarshal(this.Ctx.Input.RequestBody, &journalEntry)\n\n\tjournalEntry.SetDate()\n\tservices.AddJournalEntry(&journalEntry)\n\n\tthis.Data[\"json\"] = user\n\tthis.ServeJSON()\n}"} {"input": "package ec2\n\nimport (\n\t\"github.com/crowdmob/goamz/aws\"\n\t\"time\"\n)\n\n\n\nfunc fixedTime() time.Time {\n\treturn time.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC)\n}\n\nfunc FakeTime(fakeIt bool) {\n\tif fakeIt {\n\t\ttimeNow = fixedTime\n\t} else {\n\t\ttimeNow = time.Now\n\t}\n}\n\nfunc Sign(auth aws.Auth, method, path string, params map[string]string, host string) ", "output": "{\n\tsign(auth, method, path, params, host)\n}"} {"input": "package endpoints\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\n\n\nfunc TestStatusWithContent(t *testing.T) {\n\thandler := NewStatusEndpoint(\"ready\")\n\tw := httptest.NewRecorder()\n\thandler(w, nil, nil)\n\tif w.Code != http.StatusOK {\n\t\tt.Errorf(\"Bad code for empty content. Expected %d, got %d\", http.StatusOK, w.Code)\n\t}\n\tif w.Body.String() != \"ready\" {\n\t\tt.Errorf(\"Bad status body. Expected %s, got %s\", \"ready\", w.Body.String())\n\t}\n}\n\nfunc TestStatusNoContent(t *testing.T) ", "output": "{\n\thandler := NewStatusEndpoint(\"\")\n\tw := httptest.NewRecorder()\n\thandler(w, nil, nil)\n\tif w.Code != http.StatusNoContent {\n\t\tt.Errorf(\"Bad code for empty content. Expected %d, got %d\", http.StatusNoContent, w.Code)\n\t}\n}"} {"input": "package discovery\n\nimport (\n\t\"fmt\"\n\t\"github.com/spencergibb/go-nuvem/util\"\n\t\"github.com/spf13/viper\"\n\t\"net\"\n\t\"strconv\"\n)\n\ntype StaticDiscovery struct {\n\tNamespace string\n\tInstances []string\n}\n\nfunc (s *StaticDiscovery) Configure(namespace string) {\n\tif s.Namespace != \"\" {\n\t\tfmt.Errorf(\"%s already inited: %s\", StaticFactoryKey, s.Namespace)\n\t\treturn\n\t}\n\ts.Namespace = namespace\n\tinstances := viper.GetStringSlice(util.GetStaticRegistryKey(s))\n\tfmt.Printf(\"instances %+v\\n\", instances)\n\ts.Instances = instances\n}\n\n\n\nfunc (s *StaticDiscovery) GetNamespace() string {\n\treturn s.Namespace\n}\n\nfunc NewStaticDiscovery() Discovery {\n\treturn &StaticDiscovery{}\n}\n\nvar StaticFactoryKey = \"StaticDiscovery\"\n\nfunc init() {\n\tprintln(\"registering static discovery\")\n\tRegister(StaticFactoryKey, NewStaticDiscovery)\n}\n\nfunc (s *StaticDiscovery) GetIntances() []util.Instance ", "output": "{\n\tinstances := make([]util.Instance, len(s.Instances))\n\n\tfor i, config := range s.Instances {\n\t\thost, portStr, err := net.SplitHostPort(config)\n\n\t\tport, err := strconv.Atoi(portStr)\n\n\t\tprint(err) \n\n\t\tinstances[i] = util.Instance{Host: host, Port: port}\n\t}\n\n\treturn instances\n}"} {"input": "package errors\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/GoogleContainerTools/skaffold/proto/v1\"\n)\n\ntype Error interface {\n\tError() string\n\tStatusCode() proto.StatusCode\n\tSuggestions() []*proto.Suggestion\n\tUnwrap() error\n}\n\ntype ErrDef struct {\n\terr error\n\tae *proto.ActionableErr\n}\n\nvar _ error = (*ErrDef)(nil)\n\nfunc (e *ErrDef) Error() string {\n\tif s := concatSuggestions(e.Suggestions()); s != \"\" {\n\t\treturn fmt.Sprintf(\"%s. %s\", e.ae.Message, concatSuggestions(e.Suggestions()))\n\t}\n\treturn e.ae.Message\n}\n\nfunc (e *ErrDef) Unwrap() error {\n\treturn e.err\n}\n\n\n\nfunc (e *ErrDef) Suggestions() []*proto.Suggestion {\n\treturn e.ae.Suggestions\n}\n\n\nfunc NewError(err error, ae *proto.ActionableErr) *ErrDef {\n\treturn &ErrDef{\n\t\terr: err,\n\t\tae: ae,\n\t}\n}\n\n\nfunc NewErrorWithStatusCode(ae *proto.ActionableErr) *ErrDef {\n\treturn &ErrDef{\n\t\tae: ae,\n\t}\n}\n\nfunc IsSkaffoldErr(err error) bool {\n\tif _, ok := err.(Error); ok {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (e *ErrDef) StatusCode() proto.StatusCode ", "output": "{\n\treturn e.ae.ErrCode\n}"} {"input": "package charmrevisionupdater_test\n\nimport (\n\tstdtesting \"testing\"\n\n\t\"github.com/wallyworld/core/testing\"\n)\n\n\n\nfunc TestAll(t *stdtesting.T) ", "output": "{\n\ttesting.MgoTestPackage(t)\n}"} {"input": "package harlog\n\nimport (\n \"net/http\"\n \"testing\"\n)\n\nfunc makerr() (*http.Request, *http.Response) {\n\n req, _ := http.NewRequest(\"GET\", \"http://www.example.com/path/?param=value\", nil)\n resp := &http.Response{\n Status: \"200 OK\",\n StatusCode: 200,\n Proto: \"HTTP/1.0\",\n ProtoMajor: 1,\n ProtoMinor: 0,\n Request: req,\n Header: http.Header{\n \"Connection\": {\"close\"},\n },\n Close: true,\n ContentLength: -1,\n }\n\n return req, resp\n}\n\nfunc TestNewLog(t *testing.T) {\n\n har := NewHARLog()\n har.Dump()\n}\n\nfunc TestAddEntry(t *testing.T) {\n\n req, resp := makerr()\n har := NewHARLog()\n har.Entries.Add(req, resp)\n}\n\n\n\nfunc TestDump(t *testing.T) ", "output": "{\n\n req, resp := makerr()\n har := NewHARLog()\n har.Entries.Add(req, resp)\n har.Dump()\n}"} {"input": "package storage_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/cockroachdb/cockroach/roachpb\"\n\t\"github.com/cockroachdb/cockroach/storage\"\n\t\"github.com/cockroachdb/cockroach/testutils\"\n\t\"github.com/cockroachdb/cockroach/util\"\n\t\"github.com/cockroachdb/cockroach/util/leaktest\"\n)\n\n\n\n\n\n\n\nfunc TestReplicaGCQueueDropReplicaGCOnScan(t *testing.T) {\n\tdefer leaktest.AfterTest(t)\n\n\tmtc := startMultiTestContext(t, 3)\n\tdefer mtc.Stop()\n\tmtc.stores[1].DisableReplicaGCQueue(true)\n\n\trangeID := roachpb.RangeID(1)\n\tmtc.replicateRange(rangeID, 0, 1, 2)\n\tmtc.unreplicateRange(rangeID, 0, 1)\n\n\ttime.Sleep(10 * time.Millisecond)\n\tif _, err := mtc.stores[1].GetReplica(rangeID); err != nil {\n\t\tt.Error(\"unexpected range removal\")\n\t}\n\n\tmtc.stores[1].DisableReplicaGCQueue(false)\n\n\tmtc.manualClock.Increment(int64(storage.ReplicaGCQueueInactivityThreshold+\n\t\tstorage.DefaultLeaderLeaseDuration) + 1)\n\n\tutil.SucceedsWithin(t, time.Second, func() error {\n\t\tstore := mtc.stores[1]\n\t\tstore.ForceReplicaGCScan(t)\n\t\tif _, err := store.GetReplica(rangeID); !testutils.IsError(err, \"range .* was not found\") {\n\t\t\treturn util.Errorf(\"expected range removal: %s\", err)\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc TestReplicaGCQueueDropReplica(t *testing.T) ", "output": "{\n\tdefer leaktest.AfterTest(t)\n\n\tmtc := startMultiTestContext(t, 3)\n\tdefer mtc.Stop()\n\n\trangeID := roachpb.RangeID(1)\n\tmtc.replicateRange(rangeID, 0, 1, 2)\n\tmtc.unreplicateRange(rangeID, 0, 1)\n\n\tutil.SucceedsWithin(t, time.Second, func() error {\n\t\tif _, err := mtc.stores[1].GetReplica(rangeID); !testutils.IsError(err, \"range .* was not found\") {\n\t\t\treturn util.Errorf(\"expected range removal\")\n\t\t}\n\t\treturn nil\n\t})\n}"} {"input": "package token\n\nimport (\n\t\"github.com/dgrijalva/jwt-go\"\n)\n\nconst (\n\tSignerAlgorithm = \"HS256\"\n)\n\ntype SecretFunc func(*Token) (string, error)\n\ntype Token struct {\n\tType string\n\tValue string\n}\n\nfunc New(t, v string) *Token {\n\treturn &Token{Type: t, Value: v}\n}\n\n\nfunc ParseToken(tokenStr string, secretFn SecretFunc) (*Token, error) {\n\ttoken := &Token{}\n\tparsedToken, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {\n\n\t\tif t.Method.Alg() != SignerAlgorithm {\n\t\t\treturn nil, jwt.ErrSignatureInvalid\n\t\t}\n\n\t\tclaims := t.Claims.(jwt.MapClaims)\n\t\ttypev, ok := claims[\"type\"]\n\t\tif !ok {\n\t\t\treturn nil, jwt.ValidationError{}\n\t\t}\n\n\t\tval, ok := claims[\"value\"]\n\t\tif !ok {\n\t\t\treturn nil, jwt.ValidationError{}\n\t\t}\n\n\t\ttoken.Type = typev.(string)\n\t\ttoken.Value = val.(string)\n\n\t\tsecret, err := secretFn(token)\n\t\treturn []byte(secret), err\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t} else if !parsedToken.Valid {\n\t\treturn nil, jwt.ValidationError{}\n\t}\n\n\treturn token, nil\n}\n\n\n\n\nfunc (t *Token) SignWithExp(secret string, expiration int64) (string, error) ", "output": "{\n\ttoken := jwt.New(jwt.SigningMethodHS256)\n\tclaims := token.Claims.(jwt.MapClaims)\n\n\tclaims[\"type\"] = t.Type\n\tclaims[\"value\"] = t.Value\n\tif expiration > 0 {\n\t\tclaims[\"exp\"] = float64(expiration)\n\t}\n\n\treturn token.SignedString([]byte(secret))\n}"} {"input": "package app\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/weaveworks/scope/probe/host\"\n\t\"github.com/weaveworks/scope/report\"\n)\n\n\n\n\ntype probeDesc struct {\n\tID string `json:\"id\"`\n\tHostname string `json:\"hostname\"`\n\tVersion string `json:\"version\"`\n\tLastSeen time.Time `json:\"lastSeen\"`\n}\n\n\nfunc makeProbeHandler(rep Reporter) CtxHandlerFunc {\n\treturn func(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\t\tr.ParseForm()\n\t\tif _, sparse := r.Form[\"sparse\"]; sparse {\n\t\t\thasProbes, err := rep.HasReports(ctx, time.Now())\n\t\t\tif err != nil {\n\t\t\t\trespondWith(w, http.StatusInternalServerError, err)\n\t\t\t}\n\t\t\trespondWith(w, http.StatusOK, hasProbes)\n\t\t\treturn\n\t\t}\n\t\trpt, err := rep.Report(ctx, time.Now())\n\t\tif err != nil {\n\t\t\trespondWith(w, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\t\tresult := []probeDesc{}\n\t\tfor _, n := range rpt.Host.Nodes {\n\t\t\tid, _ := n.Latest.Lookup(report.ControlProbeID)\n\t\t\thostname, _ := n.Latest.Lookup(host.HostName)\n\t\t\tversion, dt, _ := n.Latest.LookupEntry(host.ScopeVersion)\n\t\t\tresult = append(result, probeDesc{\n\t\t\t\tID: id,\n\t\t\t\tHostname: hostname,\n\t\t\t\tVersion: version,\n\t\t\t\tLastSeen: dt,\n\t\t\t})\n\t\t}\n\t\trespondWith(w, http.StatusOK, result)\n\t}\n}\n\nfunc makeRawReportHandler(rep Reporter) CtxHandlerFunc ", "output": "{\n\treturn func(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\t\treport, err := rep.Report(ctx, time.Now())\n\t\tif err != nil {\n\t\t\trespondWith(w, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\t\trespondWith(w, http.StatusOK, report)\n\t}\n}"} {"input": "package actions\n\n\n\n\nimport (\n\t\"net/http\"\n\n\tmiddleware \"github.com/go-openapi/runtime/middleware\"\n\n\tmodels \"github.com/semi-technologies/weaviate/entities/models\"\n)\n\n\ntype ActionsDeleteHandlerFunc func(ActionsDeleteParams, *models.Principal) middleware.Responder\n\n\nfunc (fn ActionsDeleteHandlerFunc) Handle(params ActionsDeleteParams, principal *models.Principal) middleware.Responder {\n\treturn fn(params, principal)\n}\n\n\ntype ActionsDeleteHandler interface {\n\tHandle(ActionsDeleteParams, *models.Principal) middleware.Responder\n}\n\n\nfunc NewActionsDelete(ctx *middleware.Context, handler ActionsDeleteHandler) *ActionsDelete {\n\treturn &ActionsDelete{Context: ctx, Handler: handler}\n}\n\n\ntype ActionsDelete struct {\n\tContext *middleware.Context\n\tHandler ActionsDeleteHandler\n}\n\n\n\nfunc (o *ActionsDelete) ServeHTTP(rw http.ResponseWriter, r *http.Request) ", "output": "{\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\tr = rCtx\n\t}\n\tvar Params = NewActionsDeleteParams()\n\n\tuprinc, aCtx, err := o.Context.Authorize(r, route)\n\tif err != nil {\n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\tif aCtx != nil {\n\t\tr = aCtx\n\t}\n\tvar principal *models.Principal\n\tif uprinc != nil {\n\t\tprincipal = uprinc.(*models.Principal) \n\t}\n\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params, principal) \n\n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\tlog \"github.com/lxc/lxd/shared/log15\"\n\n\t\"github.com/lxc/lxd/shared\"\n\t\"github.com/lxc/lxd/shared/cmd\"\n\t\"github.com/lxc/lxd/shared/logger\"\n\t\"github.com/lxc/lxd/shared/logging\"\n\t\"github.com/lxc/lxd/shared/version\"\n)\n\n\ntype SubCommand func(*Args) error\n\n\n\n\ntype SubCommandError struct {\n\tCode int\n\tMessage string\n}\n\nfunc (e *SubCommandError) Error() string {\n\treturn e.Message\n}\n\n\n\nfunc SubCommandErrorf(code int, format string, a ...interface{}) *SubCommandError {\n\treturn &SubCommandError{\n\t\tCode: code,\n\t\tMessage: fmt.Sprintf(format, a...),\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc setupSubCommand(context *cmd.Context, args *Args, handler log.Handler) error {\n\tif len(shared.VarPath(\"unix.sock\")) > 107 {\n\t\treturn fmt.Errorf(\"LXD_DIR is too long, must be < %d\", 107-len(\"unix.sock\"))\n\t}\n\n\tsyslog := \"\"\n\tif args.Syslog {\n\t\tsyslog = \"lxd\"\n\t}\n\n\tvar err error\n\tlogger.Log, err = logging.GetLogger(syslog, args.Logfile, args.Verbose, args.Debug, handler)\n\tif err != nil {\n\t\tcontext.Output(\"%v\\n\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc RunSubCommand(command SubCommand, ctx *cmd.Context, args *Args, handler log.Handler) int ", "output": "{\n\tif args.Help {\n\t\tctx.Output(usage)\n\t\treturn 0\n\t}\n\tif args.Version {\n\t\tctx.Output(\"%s\\n\", version.Version)\n\t\treturn 0\n\t}\n\n\terr := setupSubCommand(ctx, args, handler)\n\tif err == nil {\n\t\terr = command(args)\n\t}\n\tif err != nil {\n\t\tcode := 1\n\t\tmessage := err.Error()\n\t\tsubCommandError, ok := err.(*SubCommandError)\n\t\tif ok {\n\t\t\tcode = subCommandError.Code\n\t\t}\n\t\tif message != \"\" {\n\t\t\tctx.Error(fmt.Sprintf(\"error: %s\\n\", message))\n\t\t}\n\t\treturn code\n\t}\n\treturn 0\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n)\n\nvar cfgFile string\n\n\nvar RootCmd = &cobra.Command{\n\tUse: \"evergrid-go\",\n\tShort: \"Evergrid infrastructure components and simulator\",\n\tLong: `Evergrid infrastructure components and simulator`,\n}\n\n\n\nfunc Execute() {\n\tif err := RootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}\n\nfunc init() {\n\tcobra.OnInitialize(initConfig)\n\n\n\tRootCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n}\n\n\n\n\nfunc initConfig() ", "output": "{\n\tif cfgFile != \"\" { \n\t\tviper.SetConfigFile(cfgFile)\n\t}\n\n\tviper.SetConfigName(\".evergrid-go\") \n\tviper.AddConfigPath(\"$HOME\") \n\tviper.AutomaticEnv() \n\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t}\n}"} {"input": "package patternmatcher\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc Test_NewExcludesMatcherFromReader(t *testing.T) ", "output": "{\n\tbuf := bytes.NewBuffer(nil)\n\t_, err := buf.WriteString(`\n# comment\n.caches/*\n*.mp4\n.android/*\n\n`)\n\tassert.Nil(t, err)\n\n\tmatcher, err := NewMatcherFromReader(buf)\n\tassert.Nil(t, err)\n\n\tassert.Len(t, matcher.globs, 3, \"expected 3 matcher patterns - has the comment or blank been included as a regex\")\n\n\tassert.True(t, matcher.Matches(\"a/b/myvideo.mp4\"))\n\n\tassert.True(t, matcher.Matches(\".caches/a.txt\"))\n\n\tassert.True(t, matcher.Matches(\".android/avd/Nexus_5_API_22.avd/system.img.qcow2\"))\n\n\tassert.False(t, matcher.Matches(\"a/b/mypic.jpg\"))\n\n\tassert.True(t, matcher.Matches(\".android/\"))\n\n}"} {"input": "package nogo\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype mapBackedRoleRepository struct {\n\troleMap map[string]Role\n}\n\nfunc NewMapBackedRoleRepository() RoleRepository {\n\treturn &mapBackedRoleRepository{roleMap: make(map[string]Role)}\n}\n\n\n\nfunc (this *mapBackedRoleRepository) FindRole(roleName string) (Role, error) {\n\tif role, ok := this.roleMap[roleName]; ok {\n\t\treturn role, nil\n\t}\n\treturn nil, errors.New(fmt.Sprintf(\"Could not find role %v\", roleName))\n}\n\nfunc (this *mapBackedRoleRepository) CreateRole(role Role) error {\n\tif _, ok := this.roleMap[role.GetName()]; ok {\n\t\treturn errors.New(fmt.Sprintf(\"Error creating role. Role %v already exists\", role.GetName()))\n\t}\n\tthis.roleMap[role.GetName()] = role\n\treturn nil\n}\n\nfunc (this *mapBackedRoleRepository) UpdateRole(role Role) error {\n\tif _, ok := this.roleMap[role.GetName()]; ok {\n\t\tthis.roleMap[role.GetName()] = role\n\t\treturn nil\n\t}\n\treturn errors.New(fmt.Sprintf(\"Error updating role. Role %v does not exist.\", role.GetName()))\n}\n\nfunc (this *mapBackedRoleRepository) DeleteRole(roleName string) error {\n\tif _, ok := this.roleMap[roleName]; ok {\n\t\tdelete(this.roleMap, roleName)\n\t}\n\treturn errors.New(fmt.Sprintf(\"Error deleting role. Role %v does not exist.\", roleName))\n}\n\nfunc (this *mapBackedRoleRepository) FindAll() ([]Role, error) ", "output": "{\n\tret := make([]Role, 0)\n\tfor _, role := range this.roleMap {\n\t\tret = append(ret, role)\n\t}\n\treturn ret, nil\n}"} {"input": "package yext\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n)\n\n\n\ntype BackoffPolicy struct {\n\tMillis []int\n}\n\n\nvar DefaultBackoffPolicy = BackoffPolicy{\n\t[]int{0, 0, 1000, 5000},\n}\n\n\n\n\nfunc (b BackoffPolicy) Duration(n int) time.Duration {\n\tif n >= len(b.Millis) {\n\t\tn = len(b.Millis) - 1\n\t}\n\n\treturn time.Duration(jitter(b.Millis[n])) * time.Millisecond\n}\n\n\n\n\n\nfunc jitter(millis int) int ", "output": "{\n\tif millis == 0 {\n\t\treturn 0\n\t}\n\n\treturn millis/2 + rand.Intn(millis)\n}"} {"input": "package command\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc TestCommond_InfoSynopsis(t *testing.T) ", "output": "{\n\tcommand := &InfoCommand{\n\t\tClient: nil,\n\t}\n\n\twantSynopsis := \"Show a droplet's information.\"\n\tif !reflect.DeepEqual(command.Synopsis(), wantSynopsis) {\n\t\tt.Errorf(\"InfoCommand.Synopsis returned %+v, want %+v\", command.Synopsis(), wantSynopsis)\n\t}\n\n}"} {"input": "package packet\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype PacketCodecVarIntLength struct {\n\tcodec PacketCodec\n}\n\nfunc NewPacketCodecVarIntLength() (this *PacketCodecVarIntLength) {\n\tthis = new(PacketCodecVarIntLength)\n\treturn\n}\n\nfunc (this *PacketCodecVarIntLength) Decode(reader io.Reader) (packet Packet, err error) {\n\tlength, err := ReadVarInt(reader)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Decode, Length read error: %w\", err)\n\t\treturn\n\t}\n\tif length < 0 {\n\t\terr = errors.New(fmt.Sprintf(\"Decode, Packet length is below zero: %d\", length))\n\t\treturn\n\t}\n\tif length > 1048576 { \n\t\terr = errors.New(fmt.Sprintf(\"Decode, Packet length is above maximum: %d\", length))\n\t\treturn\n\t}\n\tpayload := make([]byte, length)\n\t_, err = reader.Read(payload)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Decode, Length buffer error: %w\", err)\n\t\treturn\n\t}\n\tpacket, err = this.codec.Decode(bytes.NewBuffer(payload))\n\treturn\n}\n\nfunc (this *PacketCodecVarIntLength) Encode(writer io.Writer, packet Packet) (err error) {\n\tbuffer := new(bytes.Buffer)\n\terr = this.codec.Encode(buffer, packet)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = WriteVarInt(writer, buffer.Len())\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = buffer.WriteTo(writer)\n\treturn\n}\n\n\n\nfunc (this *PacketCodecVarIntLength) SetCodec(codec PacketCodec) ", "output": "{\n\tthis.codec = codec\n}"} {"input": "package s2\n\n\nvar (\n\t_ Shape = (*PointVector)(nil)\n)\n\n\n\n\n\n\n\n\ntype PointVector []Point\n\nfunc (p *PointVector) NumEdges() int { return len(*p) }\nfunc (p *PointVector) Edge(i int) Edge { return Edge{(*p)[i], (*p)[i]} }\nfunc (p *PointVector) ReferencePoint() ReferencePoint { return OriginReferencePoint(false) }\nfunc (p *PointVector) NumChains() int { return len(*p) }\nfunc (p *PointVector) Chain(i int) Chain { return Chain{i, 1} }\n\nfunc (p *PointVector) ChainPosition(e int) ChainPosition { return ChainPosition{e, 0} }\nfunc (p *PointVector) Dimension() int { return 0 }\nfunc (p *PointVector) IsEmpty() bool { return defaultShapeIsEmpty(p) }\nfunc (p *PointVector) IsFull() bool { return defaultShapeIsFull(p) }\nfunc (p *PointVector) typeTag() typeTag { return typeTagPointVector }\nfunc (p *PointVector) privateInterface() {}\n\nfunc (p *PointVector) ChainEdge(i, j int) Edge ", "output": "{ return Edge{(*p)[i], (*p)[j]} }"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realSecurityGroupRule SecurityGroupRule\n\nfunc (o *SecurityGroupRule) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realSecurityGroupRule\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = SecurityGroupRule(r)\n\treturn nil\n}\n\nvar _ fi.HasName = &SecurityGroupRule{}\n\n\n\nfunc (e *SecurityGroupRule) SetName(name string) {\n\te.Name = &name\n}\n\nfunc (e *SecurityGroupRule) String() string {\n\treturn fi.TaskAsString(e)\n}\n\nfunc (e *SecurityGroupRule) GetName() *string ", "output": "{\n\treturn e.Name\n}"} {"input": "package main\n\ntype test_i interface {\n\tTest() test_i\n\tResult() bool\n}\n\ntype test_t struct {\n}\n\nfunc newTest() *test_t {\n\treturn &test_t{}\n}\n\ntype testFn func(string) testFn\n\nfunc main() {\n\ttest := newTest()\n\n\tswitch {\n\tcase test.\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tResult():\n\tdefault:\n\t\tpanic(\"Result returned false unexpectedly\")\n\t}\n}\n\nfunc (t *test_t) Test() test_i {\n\treturn t\n}\n\n\n\nfunc (t *test_t) Result() bool ", "output": "{\n\treturn true\n}"} {"input": "package vminstall\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"io/ioutil\"\n\t\"strings\"\n)\n\ntype Downloader interface{\n\tDownload(url string) ([]byte, error)\n\tMatch() string\n}\n\ntype HTTPDownloader struct {\n\n}\n\nfunc (h HTTPDownloader) Match() string {\n\treturn \"http\"\n}\n\n\n\ntype DownloadManager struct {\n\tdownloaders []Downloader\n}\n\n\nfunc (manager *DownloadManager) Regsiter(d Downloader) {\n\tmanager.downloaders = append(manager.downloaders, d)\n}\n\n\nfunc (manager *DownloadManager) Download(url string) ([]byte,error) {\n\tvar found bool = false\n\tvar d Downloader\n\tfor _,d = range manager.downloaders {\n\t\tif strings.Index(url, d.Match()) == 0 {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif found {\n\t\treturn d.Download(url)\n\t} else {\n\t\treturn nil, errors.New(\"not found matching download\")\n\t}\n\n}\n\nfunc (h HTTPDownloader) Download(url string) ([]byte,error) ", "output": "{\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\tcontents, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn contents,nil\n\n}"} {"input": "package testdata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\told \"sqlflow.org/sqlflow/go/sql/testdata\"\n)\n\n\n\nfunc TestDatabaseTestDataChurnHive(t *testing.T) ", "output": "{\n\ta := assert.New(t)\n\ta.Equal(removeBlankLines(old.ChurnHiveSQL+\"\\n\"),\n\t\tChurnHive(\"churn\"))\n}"} {"input": "package room\n\nimport (\n \"log\"\n\n \"github.com/jinzhu/gorm\"\n _ \"github.com/jinzhu/gorm/dialects/sqlite\"\n)\n\nconst tableName string = \"rooms\"\n\ntype Room struct {\n gorm.Model\n Id int64 `sql:\"AUTO_INCREMENT\" gorm:\"primary_key\"`\n Name string `sql:\"size:255;unique;index\"`\n Size int32\n VC bool\n CalendarId string\n}\n\nvar (\n dbHandle *gorm.DB\n dbPath string\n)\n\nfunc check(err error) {\n if err != nil {\n log.Println(\"[Models]: \", err)\n }\n\n}\n\n\n\nfunc GetAll(dbHandle *gorm.DB) []*Room {\n var rooms []*Room\n rows, err := dbHandle.Table(tableName).Select(nil).Rows()\n check(err)\n rows.Scan(&rooms)\n return rooms\n}\n\nfunc SetDbPath(path string) {\n dbPath = path\n}\n\nfunc Create(dbHandle *gorm.DB, name string, size int32, vc bool, calendarId string) ", "output": "{\n dbHandle.Create(&Room{Name: name, Size: size, VC: vc, CalendarId: calendarId})\n}"} {"input": "package main\n\nimport (\n\t\"github.com/jjyr/ringo\"\n\t\"github.com/jjyr/ringo/middleware\"\n)\n\n\n\ntype user struct {\n\tName string `json:\"name\" validate:\"required\"`\n}\n\nvar users []user\n\n\ntype Users struct {\n\tringo.Controller\n}\n\n\n\nfunc (ctl *Users) Post(c ringo.Context) {\n\tu := user{}\n\tif err := c.BindJSON(&u); err == nil {\n\t\tusers = append(users, u)\n\t\tc.JSON(200, u)\n\t} else {\n\t\tc.JSON(400, ringo.H{\"message\": \"format error\"})\n\t}\n}\n\nfunc DisplayList(c ringo.Context) {\n\tc.HTML(200, \"list.html\", users)\n}\n\ntype User struct {\n\tringo.Controller\n}\n\nfunc (ctl *User) Delete(c ringo.Context) {\n\tidx := -1\n\tname := c.Params().ByName(\"id\")\n\tfor i, u := range users {\n\t\tif name == u.Name {\n\t\t\tidx = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif idx >= 0 {\n\t\tusers = append(users[:idx], users[idx+1:]...)\n\t\tc.JSON(200, ringo.H{\"message\": \"ok\"})\n\t} else {\n\t\tc.JSON(404, ringo.H{\"message\": \"not found\"})\n\t}\n}\n\nfunc main() {\n\tapp := ringo.NewApp()\n\n\tapp.Add(\"/users\", &Users{})\n\tapp.GET(\"/users-list\", DisplayList)\n\tapp.Add(\"/user/:id\", &User{})\n\tapp.Use(middleware.Recover())\n\tapp.SetTemplatePath(\"templates\")\n\tapp.Run(\"localhost:8000\")\n}\n\nfunc (_ *Users) Get(c ringo.Context) ", "output": "{\n\tc.JSON(200, ringo.H{\"users\": users})\n}"} {"input": "package protoio\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\n\t\"github.com/gogo/protobuf/proto\"\n\n\t\"github.com/multiformats/go-varint\"\n)\n\ntype uvarintReader struct {\n\tr *bufio.Reader\n\tbuf []byte\n\tmaxSize int\n\tcloser io.Closer\n}\n\nfunc NewDelimitedReader(r io.Reader, maxSize int) ReadCloser {\n\tvar closer io.Closer\n\tif c, ok := r.(io.Closer); ok {\n\t\tcloser = c\n\t}\n\treturn &uvarintReader{bufio.NewReader(r), nil, maxSize, closer}\n}\n\n\n\nfunc (ur *uvarintReader) Close() error {\n\tif ur.closer != nil {\n\t\treturn ur.closer.Close()\n\t}\n\treturn nil\n}\n\nfunc (ur *uvarintReader) ReadMsg(msg proto.Message) error ", "output": "{\n\tlength64, err := varint.ReadUvarint(ur.r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlength := int(length64)\n\tif length < 0 || length > ur.maxSize {\n\t\treturn io.ErrShortBuffer\n\t}\n\tif len(ur.buf) < length {\n\t\tur.buf = make([]byte, length)\n\t}\n\tbuf := ur.buf[:length]\n\tif _, err := io.ReadFull(ur.r, buf); err != nil {\n\t\treturn err\n\t}\n\treturn proto.Unmarshal(buf, msg)\n}"} {"input": "package errors \n\nimport (\n\t\"strconv\"\n)\n\n\n\ntype StructuralError string\n\nfunc (s StructuralError) Error() string {\n\treturn \"openpgp: invalid data: \" + string(s)\n}\n\n\n\ntype UnsupportedError string\n\nfunc (s UnsupportedError) Error() string {\n\treturn \"openpgp: unsupported feature: \" + string(s)\n}\n\n\n\ntype InvalidArgumentError string\n\nfunc (i InvalidArgumentError) Error() string {\n\treturn \"openpgp: invalid argument: \" + string(i)\n}\n\n\n\ntype SignatureError string\n\n\n\ntype keyIncorrectError int\n\nfunc (ki keyIncorrectError) Error() string {\n\treturn \"openpgp: incorrect key\"\n}\n\nvar ErrKeyIncorrect error = keyIncorrectError(0)\n\ntype unknownIssuerError int\n\nfunc (unknownIssuerError) Error() string {\n\treturn \"openpgp: signature made by unknown entity\"\n}\n\nvar ErrUnknownIssuer error = unknownIssuerError(0)\n\ntype keyRevokedError int\n\nfunc (keyRevokedError) Error() string {\n\treturn \"openpgp: signature made by revoked key\"\n}\n\nvar ErrKeyRevoked error = keyRevokedError(0)\n\ntype UnknownPacketTypeError uint8\n\nfunc (upte UnknownPacketTypeError) Error() string {\n\treturn \"openpgp: unknown packet type: \" + strconv.Itoa(int(upte))\n}\n\nfunc (b SignatureError) Error() string ", "output": "{\n\treturn \"openpgp: invalid signature: \" + string(b)\n}"} {"input": "package netutil\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype ConnWrapper struct {\n\tio.Reader\n\tio.Writer\n\tUnderlyingConn net.Conn\n\tReadCloser io.Closer\n\tWriteCloser io.Closer\n}\n\nvar _ net.Conn = new(ConnWrapper)\n\nfunc (c *ConnWrapper) Close() error {\n\tvar multiErr MultiError\n\tif c.ReadCloser != nil {\n\t\tmultiErr.RecordError(c.ReadCloser.Close())\n\t}\n\tif c.WriteCloser != nil {\n\t\tmultiErr.RecordError(c.WriteCloser.Close())\n\t}\n\tmultiErr.RecordError(c.UnderlyingConn.Close())\n\treturn multiErr.ToError()\n}\n\nfunc (c *ConnWrapper) LocalAddr() net.Addr { return c.UnderlyingConn.LocalAddr() }\nfunc (c *ConnWrapper) RemoteAddr() net.Addr { return c.UnderlyingConn.RemoteAddr() }\n\nfunc (c *ConnWrapper) SetReadDeadline(t time.Time) error { return c.UnderlyingConn.SetReadDeadline(t) }\nfunc (c *ConnWrapper) SetWriteDeadline(t time.Time) error { return c.UnderlyingConn.SetWriteDeadline(t) }\n\nfunc (c *ConnWrapper) SetDeadline(t time.Time) error ", "output": "{ return c.UnderlyingConn.SetDeadline(t) }"} {"input": "package libchorizo\n\nimport (\n\t\"code.google.com/p/gcfg\"\n\t\"fmt\"\n)\n\ntype ChorizoConfig interface {\n\tInterpolateConfig(config_file_path string) (Config)\n}\n\ntype Config struct {\n\tMain struct {\n\t\tDbfile string\n\t\tDebug bool\n\t\tCronfile string\n\t\tStatefile string\n\t\tLockfile string\n\t\tScriptpath string\n\t\tAPIUrl string\n\t\tLoglevel string\n\t\tExecPath string\n\t\tConfigPath string\n\t\tRabbitmqHost string\n\t\tRabbitmqPort string\n\t\tRabbitmqUser string\n\t\tRabbitmqPass string\n\t\tUseTls bool\n\t}\n}\n\n\n\ntype inConfig struct{}\n\nfunc (ChorizoConfig inConfig) InterpolateConfig(config_file_path string) (Config) {\n\tvar cfg Config\n\treturn cfg\n}\n\nfunc (ChorizoConfig Config) InterpolateConfig(config_file_path string) (Config) {\n\tvar cfg Config\n\treturn cfg\n}\n\nfunc ParseConfig(exec_path string) (Config, error) {\n\tvar CONFIGPATH = fmt.Sprintf(\"%s/chorizo.gcfg\", exec_path)\n\tvar cfg Config\n\terr := gcfg.ReadFileInto(&cfg, CONFIGPATH)\n\tcfg.InterpolateConfig(CONFIGPATH)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn cfg, err\n}\n\nfunc (cfg Config) NewConfig(exec_path string) (Config)", "output": "{\n\tcfg.Main.ExecPath = exec_path\n\tcfg.Main.ConfigPath = fmt.Sprintf(\"%s/chorizo.gcfg\", cfg.Main.ExecPath)\n\terr := gcfg.ReadFileInto(&cfg, cfg.Main.ConfigPath)\n\tcfg.Main.Dbfile = fmt.Sprintf(\"%s/%s\", exec_path, cfg.Main.Dbfile)\n\tcfg.Main.Cronfile = fmt.Sprintf(\"%s/%s\", exec_path, cfg.Main.Cronfile)\n\tcfg.Main.Scriptpath = fmt.Sprintf(\"%s/%s\", exec_path, cfg.Main.Scriptpath)\n\tcfg.Main.Statefile = fmt.Sprintf(\"%s/%s\", exec_path, cfg.Main.Statefile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn cfg\n\n}"} {"input": "package healthcheck\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n)\n\nfunc healthcheck(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"ok\")\n}\n\n\n\nfunc StartHealthCheck(port int) error ", "output": "{\n\tif port <= 0 || port > 65535 {\n\t\treturn fmt.Errorf(\"Invalid health check port number: %v\", port)\n\t}\n\thttp.HandleFunc(\"/healthcheck\", healthcheck)\n\tp := \":\" + strconv.Itoa(port)\n\tlog.Infof(\"Listening for health checks on 0.0.0.0%v/healthcheck\", p)\n\terr := http.ListenAndServe(p, nil)\n\treturn err\n}"} {"input": "package mgorm\n\nimport (\n\t\"labix.org/v2/mgo/bson\"\n)\n\ntype IEmbeddedModel interface {\n\tIErrorHandler\n\tIValidator\n\tIEvent\n}\n\ntype IModel interface {\n\tIEmbeddedModel\n\tIsNew() bool\n\tGetId() bson.ObjectId\n\tAfterFind()\n\tBeforeSave() error\n\tAfterSave()\n\tCollectionName() string\n}\n\ntype EmbeddedModel struct {\n\tErrorHandler `bson:\",inline\" json:\"-\"`\n\tEvent `bson:\",inline\" json:\"-\"`\n}\n\n\n\ntype Model struct {\n\tEmbeddedModel `bson:\",inline\" json:\"-\"`\n\tId bson.ObjectId `bson:\"_id\" json:\"id\"`\n\tisOld bool\n\tcollectionName string\n}\n\nfunc (self *Model) AfterFind() {\n\tself.Emit(\"AfterFind\")\n\tself.isOld = true\n}\n\nfunc (self *Model) BeforeSave() error {\n\tif self.IsNew() {\n\t\tself.Id = bson.NewObjectId()\n\t}\n\n\treturn self.Emit(\"BeforeSave\")\n}\n\nfunc (self *Model) AfterSave() {\n\tself.Emit(\"AfterSave\")\n\tself.isOld = true\n}\n\nfunc (self *Model) GetId() bson.ObjectId {\n\treturn self.Id\n}\n\nfunc (self *Model) IsNew() bool {\n\treturn !self.isOld\n}\n\nfunc (self *EmbeddedModel) Validate() bool ", "output": "{\n\tself.ClearErrors()\n\n\terr := self.Emit(\"BeforeValidate\")\n\tif nil != err {\n\t\tself.AddError(err.Error())\n\t\treturn false\n\t}\n\n\treturn true\n}"} {"input": "package gash\n\n\n\n\n\ntype CuckooHash struct {\n\titems []*KvPair\n\tcapacity int\n\tfn1 HashFn\n\tfn2 HashFn\n}\n\nfunc CreateCuckooHash(capacity int, fn1 HashFn, fn2 HashFn) CuckooHash {\n\ttable := CuckooHash{}\n\ttable.capacity = capacity\n\ttable.items = make([]*KvPair, capacity)\n\ttable.fn1 = fn1\n\ttable.fn2 = fn2\n\treturn table\n}\n\n\n\nfunc (table CuckooHash) Find(k string) interface{} {\n\tvar pair *KvPair\n\n\tindex1 := table.fn1(k) % table.capacity\n\tindex2 := table.fn2(k) % table.capacity\n\n\tpair1 := table.items[index1]\n\tpair2 := table.items[index2]\n\n\tif pair1 != nil && pair1.Key == k {\n\t\tpair = pair1\n\t} else if pair2 != nil && pair2.Key == k {\n\t\tpair = pair2\n\t}\n\n\treturn pair.Value\n}\n\nfunc (table CuckooHash) Remove(k string) {\n\tindex1 := table.fn1(k) % table.capacity\n\tindex2 := table.fn2(k) % table.capacity\n\n\tpair1 := table.items[index1]\n\tpair2 := table.items[index2]\n\n\tif pair1 != nil && pair1.Key == k {\n\t\ttable.items[index1] = nil\n\t} else if pair2 != nil && pair2.Key == k {\n\t\ttable.items[index2] = nil\n\t}\n}\n\nfunc (table CuckooHash) Insert(k string, v interface{}) ", "output": "{\n\tindex := table.fn1(k) % table.capacity\n\tswapItem := table.items[index]\n\tinsertItem := KvPair{k, v}\n\ttable.items[index] = &insertItem\n\toldIndex := index\n\n\titem := swapItem\n\tfor item != nil {\n\t\tindex = table.fn1(swapItem.Key) % table.capacity\n\t\tif index == oldIndex {\n\t\t\tindex = table.fn2(swapItem.Key) % table.capacity\n\t\t}\n\n\t\tswapItem = table.items[index]\n\t\tif swapItem != nil && swapItem.Key == k {\n\n\t\t\treturn\n\t\t}\n\t\ttable.items[index] = item\n\t\titem = swapItem\n\t}\n}"} {"input": "package main\n\n\n\nfunc for_stmts() ", "output": "{ \n\tfor 34.5 + 4.5; 5< 10; {\n\t\treturn\n\t}\n}"} {"input": "package buffactory\n\nimport (\n\t\"testing\"\n)\n\nfunc TestInsertData(t *testing.T) {\n\tstats := make(Stats, 0, 3)\n\tstats.InsertData(0)\n\tstats.InsertData(1)\n\tstats.InsertData(2)\n\tstats.InsertData(3)\n\tfor i, s := range stats {\n\t\tif int64(i) != s {\n\t\t\tt.Fatal(\"numbers don't match\", i , s, []int64(stats))\n\t\t}\n\t}\n}\n\n\n\nfunc TestStats(t *testing.T) ", "output": "{\n\tstats := make(Stats, 0, 3)\n\tstats.InsertData(1)\n\tstats.InsertData(2)\n\tstats.InsertData(3)\n\tif stats.Min() != 1 {\n\t\tt.Fatal(\"Min failed\", stats.Min())\n\t}\n\tif stats.Max() != 3 {\n\t\tt.Fatal(\"Max failed\", stats.Max())\n\t}\n\tif stats.Average() != 2.0 {\n\t\tt.Fatal(\"Average failed\", stats.Average())\n\t}\n\tif stats.StdDev() != 1.0 {\n\t\tt.Fatal(\"StdDev failed\", stats.StdDev())\n\t}\n}"} {"input": "package vml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/urn/schemas_microsoft_com/vml\"\n)\n\n\n\nfunc TestAG_AllShapeAttributesMarshalUnmarshal(t *testing.T) {\n\tv := vml.NewAG_AllShapeAttributes()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := vml.NewAG_AllShapeAttributes()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestAG_AllShapeAttributesConstructor(t *testing.T) ", "output": "{\n\tv := vml.NewAG_AllShapeAttributes()\n\tif v == nil {\n\t\tt.Errorf(\"vml.NewAG_AllShapeAttributes must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed vml.AG_AllShapeAttributes should validate: %s\", err)\n\t}\n}"} {"input": "package libsnnet\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc performBridgeOps(shouldPass bool, assert *assert.Assertions, bridge *Bridge) {\n\ta := assert.Nil\n\tif !shouldPass {\n\t\ta = assert.NotNil\n\t}\n\ta(bridge.enable())\n\ta(bridge.disable())\n\ta(bridge.destroy())\n}\n\n\n\n\n\n\n\n\nfunc TestBridge_Basic(t *testing.T) {\n\tassert := assert.New(t)\n\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge.create())\n\n\tbridge1, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge1.getDevice())\n\tperformBridgeOps(true, assert, bridge)\n\n\tassert.NotNil(bridge.destroy())\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc TestBridge_Invalid(t *testing.T) {\n\tassert := assert.New(t)\n\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.NotNil(bridge.getDevice())\n\n\tperformBridgeOps(false, assert, bridge)\n}\n\n\n\n\n\n\n\nfunc TestBridge_GetDevice(t *testing.T) {\n\tassert := assert.New(t)\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge.create())\n\n\tbridge1, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge1.getDevice())\n\tperformBridgeOps(true, assert, bridge1)\n}\n\nfunc TestBridge_Dup(t *testing.T) ", "output": "{\n\tassert := assert.New(t)\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge.create())\n\tdefer func() { _ = bridge.destroy() }()\n\n\tbridge1, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\tassert.NotNil(bridge1.create())\n}"} {"input": "package mock\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/cilium/cilium/pkg/lock\"\n)\n\n\ntype MockMetrics struct {\n\tmutex lock.RWMutex\n\tapiCall map[string]float64\n\trateLimit map[string]time.Duration\n}\n\n\nfunc NewMockMetrics() *MockMetrics {\n\treturn &MockMetrics{\n\t\tapiCall: map[string]float64{},\n\t\trateLimit: map[string]time.Duration{},\n\t}\n}\n\n\n\nfunc (m *MockMetrics) APICall(operation, status string) float64 {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\treturn m.apiCall[fmt.Sprintf(\"operation=%s, status=%s\", operation, status)]\n}\n\n\n\n\n\nfunc (m *MockMetrics) ObserveAPICall(operation, status string, duration float64) {\n\tm.mutex.Lock()\n\tm.apiCall[fmt.Sprintf(\"operation=%s, status=%s\", operation, status)] += duration\n\tm.mutex.Unlock()\n}\n\n\n\nfunc (m *MockMetrics) RateLimit(operation string) time.Duration {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\treturn m.rateLimit[operation]\n}\n\n\n\n\n\n\nfunc (m *MockMetrics) ObserveRateLimit(operation string, delay time.Duration) ", "output": "{\n\tm.mutex.Lock()\n\tm.rateLimit[operation] += delay\n\tm.mutex.Unlock()\n}"} {"input": "package news\n\nimport (\n\t\"context\"\n\n\t\"github.com/bwmarrin/discordgo\"\n\t\"github.com/fsufitch/tagioalisi-bot/azure\"\n\t\"github.com/fsufitch/tagioalisi-bot/bot/util\"\n\t\"github.com/fsufitch/tagioalisi-bot/log\"\n)\n\n\ntype Module struct {\n\tLog *log.Logger\n\tNews azure.NewsSearch\n\n\tsession *discordgo.Session\n}\n\n\n\n\n\nfunc (m *Module) Register(ctx context.Context, session *discordgo.Session) error {\n\tm.session = session\n\n\tcancel := m.session.AddHandler(m.handleCommand)\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tm.Log.Infof(\"news module context done\")\n\t\tcancel()\n\t}()\n\n\treturn nil\n}\n\n\nfunc (m *Module) DoSearch(\n\tctx context.Context,\n\tsession *discordgo.Session,\n\tchannelID string,\n\tquery string,\n\tcount int,\n\tverbose bool,\n) error {\n\tm.Log.Debugf(\"news: searching for `%s`\", query)\n\n\tif !m.News.Ready() {\n\t\treturn util.DiscordMessageSendRawBlock(session, channelID, \"News API not properly instantiated. Sorry! :(\")\n\t}\n\tm.Log.Debugf(\"news: api ready\")\n\n\tresults, err := m.News.Search(ctx, query, int32(count))\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Log.Debugf(\"news: got %d results for %s\", results.Len(), query)\n\n\tvar f formatter\n\tif verbose {\n\t\tf = verboseFormatter\n\t} else {\n\t\tf = compactFormatter\n\t}\n\n\treturn f(session, channelID, results)\n}\n\nfunc (m Module) Name() string ", "output": "{ return \"news\" }"} {"input": "package transport\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\tma \"gx/ipfs/QmSWLfmj5frN9xVLMMN846dMDriy5wN5jeghUm7aTW3DAG/go-multiaddr\"\n\tmanet \"gx/ipfs/QmVCNGTyD4EkvNYaAp253uMQ9Rjsjy2oGMvcdJJUoVRfja/go-multiaddr-net\"\n\tmafmt \"gx/ipfs/QmYjJnSTfXWhYL2cV1xFphPqjqowJqH7ZKLA1As8QrPHbn/mafmt\"\n)\n\ntype FallbackDialer struct {\n\tmadialer manet.Dialer\n}\n\nfunc (fbd *FallbackDialer) Matches(a ma.Multiaddr) bool {\n\treturn mafmt.TCP.Matches(a)\n}\n\n\n\nfunc (fbd *FallbackDialer) DialContext(ctx context.Context, a ma.Multiaddr) (Conn, error) {\n\tif mafmt.TCP.Matches(a) {\n\t\treturn fbd.tcpDial(ctx, a)\n\t}\n\treturn nil, fmt.Errorf(\"cannot dial %s with fallback dialer\", a)\n}\n\nfunc (fbd *FallbackDialer) tcpDial(ctx context.Context, raddr ma.Multiaddr) (Conn, error) {\n\tvar c manet.Conn\n\tvar err error\n\tc, err = fbd.madialer.DialContext(ctx, raddr)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ConnWrap{\n\t\tConn: c,\n\t}, nil\n}\n\nvar _ Dialer = (*FallbackDialer)(nil)\n\nfunc (fbd *FallbackDialer) Dial(a ma.Multiaddr) (Conn, error) ", "output": "{\n\treturn fbd.DialContext(context.Background(), a)\n}"} {"input": "package windows\n\nimport (\n\t\"github.com/docker/libnetwork/driverapi\"\n\t\"github.com/docker/libnetwork/types\"\n)\n\nconst networkType = \"windows\"\n\n\n\ntype driver struct{}\n\n\nfunc Init(dc driverapi.DriverCallback) error {\n\tc := driverapi.Capability{\n\t\tScope: driverapi.LocalScope,\n\t}\n\treturn dc.RegisterDriver(networkType, &driver{}, c)\n}\n\nfunc (d *driver) Config(option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {\n\treturn nil\n}\n\n\n\nfunc (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) DeleteEndpoint(nid, eid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {\n\treturn make(map[string]interface{}, 0), nil\n}\n\n\nfunc (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {\n\treturn nil\n}\n\n\nfunc (d *driver) Leave(nid, eid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) Type() string {\n\treturn networkType\n}\n\nfunc (d *driver) DeleteNetwork(nid types.UUID) error ", "output": "{\n\treturn nil\n}"} {"input": "package nexus\n\nimport (\n\t\"github.com/davyxu/cellnet\"\n\t\"github.com/davyxu/cellnet/socket\"\n)\n\n\n\n\nfunc con(address string, domain string) {\n\n\tpeer := socket.NewConnector(nil)\n\tpeer.Start(address)\n\n\tcellnet.RegisterMessage(peer, \"coredef.SessionConnected\", func(ev *cellnet.Event) {\n\n\t\tsendDomains(ev.Ses)\n\t})\n\n\tshareInit(peer)\n}\n\nfunc ConnectSingleton(address string, domain string) ", "output": "{\n\n\tcon(address, domain)\n}"} {"input": "package naming\n\nimport (\n\t\"github.com/snapcore/snapd/snapdenv\"\n)\n\nvar (\n\tprodWellKnownSnapIDs = map[string]string{\n\t\t\"core\": \"99T7MUlRhtI3U0QFgl5mXXESAiSwt776\",\n\t\t\"snapd\": \"PMrrV4ml8uWuEUDBT8dSGnKUYbevVhc4\",\n\t\t\"core18\": \"CSO04Jhav2yK0uz97cr0ipQRyqg0qQL6\",\n\t\t\"core20\": \"DLqre5XGLbDqg9jPtiAhRRjDuPVa5X1q\",\n\t}\n\n\tstagingWellKnownSnapIDs = map[string]string{\n\t\t\"core\": \"xMNMpEm0COPZy7jq9YRwWVLCD9q5peow\",\n\t\t\"snapd\": \"Z44rtQD1v4r1LXGPCDZAJO3AOw1EDGqy\",\n\t\t\"core18\": \"NhSvwckvNdvgdiVGlsO1vYmi3FPdTZ9U\",\n\t\t\"core20\": \"\",\n\t}\n)\n\nvar wellKnownSnapIDs = prodWellKnownSnapIDs\n\nfunc init() {\n\tif snapdenv.UseStagingStore() {\n\t\twellKnownSnapIDs = stagingWellKnownSnapIDs\n\t}\n}\n\n\n\nfunc WellKnownSnapID(snapName string) string {\n\treturn wellKnownSnapIDs[snapName]\n}\n\n\n\nfunc UseStagingIDs(staging bool) (restore func()) ", "output": "{\n\told := wellKnownSnapIDs\n\tif staging {\n\t\twellKnownSnapIDs = stagingWellKnownSnapIDs\n\t} else {\n\t\twellKnownSnapIDs = prodWellKnownSnapIDs\n\t}\n\treturn func() {\n\t\twellKnownSnapIDs = old\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/hyperledger/fabric/common/configtx\"\n\tgenesisconfig \"github.com/hyperledger/fabric/common/configtx/tool/localconfig\"\n\tcb \"github.com/hyperledger/fabric/protos/common\"\n)\n\n\n\nfunc newChainRequest(consensusType, creationPolicy, newChannelId string) *cb.Envelope ", "output": "{\n\tenv, err := configtx.MakeChainCreationTransaction(newChannelId, genesisconfig.SampleConsortiumName, signer)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn env\n}"} {"input": "package joltDB\n\nimport (\n\t\"github.com/boltdb/bolt\"\n)\n\nvar boltdbr *bolt.DB\nvar dbr = apiConn(boltdbr)\n\nfunc OpenReadOnly(dir string) error {\n\treturn dbr.apiOpenReadOnly(dir)\n}\n\nfunc CloseReadOnly() {\n\tdbr.apiClose()\n}\n\nfunc ListReadOnly(bucket string) ([]byte, error) {\n\treturn dbr.apiList(bucket)\n}\n\nfunc ListPrefixReadOnly(bucket, prefix string) ([]byte, error) {\n\treturn dbrw.apiListPrefix(bucket, prefix)\n}\n\n\n\nfunc GetOneReadOnly(bucket, key string) ([]byte, error) {\n\treturn dbr.apiGetOne(bucket, key)\n}\n\nfunc ListRangeReadOnly(bucket, start, stop string) ([]byte, error) ", "output": "{\n\treturn dbrw.apiListRange(bucket, start, stop)\n}"} {"input": "package dom\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\ntype Node interface {\n\tString() string\n\tParent() Node\n\tSetParent(node Node)\n\tChildren() []Node\n\tAddChild(child Node)\n\tClone() Node\n}\n\n\ntype Element struct {\n\ttext string\n\tparent Node\n\tchildren []Node\n}\n\n\nfunc NewElement(text string) *Element {\n\treturn &Element{\n\t\ttext: text,\n\t\tparent: nil,\n\t\tchildren: make([]Node, 0),\n\t}\n}\n\n\nfunc (e *Element) Parent() Node {\n\treturn e.parent\n}\n\n\nfunc (e *Element) SetParent(node Node) {\n\te.parent = node\n}\n\n\nfunc (e *Element) Children() []Node {\n\treturn e.children\n}\n\n\nfunc (e *Element) AddChild(child Node) {\n\tcopy := child.Clone()\n\tcopy.SetParent(e)\n\te.children = append(e.children, copy)\n}\n\n\n\nfunc (e *Element) Clone() Node {\n\tcopy := &Element{\n\t\ttext: e.text,\n\t\tparent: nil,\n\t\tchildren: make([]Node, 0),\n\t}\n\tfor _, child := range e.children {\n\t\tcopy.AddChild(child)\n\t}\n\treturn copy\n}\n\n\n\n\nfunc (e *Element) String() string ", "output": "{\n\tbuffer := bytes.NewBufferString(e.text)\n\n\tfor _, c := range e.Children() {\n\t\ttext := c.String()\n\t\tfmt.Fprintf(buffer, \"\\n %s\", text)\n\t}\n\n\treturn buffer.String()\n}"} {"input": "package master\n\nimport ()\n\n\n\ntype frame struct {\n\tjob *job\n\tslaveName string\n\tframe int\n\tdata []byte\n\tprogress byte\n\tcompleted bool\n}\n\n\n\nfunc NewFrame(job *job, fr int) *frame {\n\treturn &frame{\n\t\tjob: job,\n\t\tslaveName: \"\",\n\t\tframe: fr,\n\t\tdata: nil,\n\t\tprogress: 0,\n\t\tcompleted: false,\n\t}\n}\n\n\n\nfunc (f *frame) Job() *job {\n\treturn f.job\n}\n\nfunc (f *frame) SlaveName() string {\n\treturn f.slaveName\n}\n\nfunc (f *frame) Frame() int {\n\treturn f.frame\n}\n\nfunc (f *frame) AlignedFrame() int {\n\treturn f.frame + f.Job().Start()\n}\n\nfunc (f *frame) Data() []byte {\n\treturn f.data\n}\n\nfunc (f *frame) Progress() byte {\n\treturn f.progress\n}\n\nfunc (f *frame) Completed() bool {\n\treturn f.completed\n}\n\nfunc (f *frame) File() []byte {\n\treturn f.Job().File()\n}\n\n\n\n\n\nfunc (f *frame) SetData(data []byte) {\n\tf.data = data\n}\n\nfunc (f *frame) SetProgress(progress byte) {\n\tf.progress = progress\n}\n\nfunc (f *frame) SetCompleted(completed bool) {\n\tf.completed = completed\n\tif completed {\n\t\tf.SetProgress(100)\n\t}\n}\n\n\n\nfunc (f *frame) Reset() {\n\tf.SetSlaveName(\"\")\n\tf.SetData(nil)\n\tf.SetProgress(0)\n\tf.SetCompleted(false)\n}\n\nfunc (f *frame) SetSlaveName(slaveName string) ", "output": "{\n\tf.slaveName = slaveName\n}"} {"input": "package common\n\nimport (\n\t\"log\"\n\t\"time\"\n\n\t\"gopkg.in/mgo.v2\"\n)\n\nvar session *mgo.Session\n\n\nfunc createDbSession() {\n\tvar err error\n\tsession, err = mgo.DialWithInfo(&mgo.DialInfo{\n\t\tAddrs: []string{AppConfig.MongoDBHost},\n\t\tUsername: AppConfig.DBUser,\n\t\tPassword: AppConfig.DBPwd,\n\t\tTimeout: 60 * time.Second,\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"[createDbSession]: %s\\n\", err)\n\t}\n}\n\n\nfunc addIndexes() {\n\tvar err error\n\tuserIndex := mgo.Index{\n\t\tKey: []string{\"email\"},\n\t\tUnique: true,\n\t\tBackground: true,\n\t\tSparse: true,\n\t}\n\tsession := GetSession().Copy()\n\tdefer session.Close()\n\tuserCol := session.DB(AppConfig.Database).C(\"users\")\n\n\terr = userCol.EnsureIndex(userIndex)\n\tif err != nil {\n\t\tlog.Fatalf(\"[addIndexes]: %s\\n\", err)\n\t}\n}\n\nfunc GetSession() *mgo.Session ", "output": "{\n\tif session == nil {\n\t\tvar err error\n\t\tsession, err = mgo.DialWithInfo(&mgo.DialInfo{\n\t\t\tAddrs: []string{AppConfig.MongoDBHost},\n\t\t\tUsername: AppConfig.DBUser,\n\t\t\tPassword: AppConfig.DBPwd,\n\t\t\tTimeout: 60 * time.Second,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"[GetSession]: %s\\n\", err)\n\t\t}\n\t}\n\treturn session\n}"} {"input": "package identity\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype DeleteUserRequest struct {\n\n\tUserId *string `mandatory:\"true\" contributesTo:\"path\" name:\"userId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteUserRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request DeleteUserRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteUserResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteUserResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteUserResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteUserRequest) HTTPRequest(method, path string) (http.Request, error) ", "output": "{\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype dumpXLIFF struct {\n\tinFile string\n}\n\nfunc init() {\n\tregisteredConverters[\"dump\"] = new(dumpXLIFF)\n}\n\nfunc (d *dumpXLIFF) Description() string {\n\treturn \"Dumps XLIFF as parsed\"\n}\n\n\n\nfunc (d *dumpXLIFF) Prepare() error {\n\treturn nil\n}\n\nfunc (d *dumpXLIFF) Convert(w io.Writer) error {\n\n\tvar doc, err = xliffFromFile(d.inFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, file := range doc.File {\n\n\t\tfor _, unit := range file.Body.TransUnit {\n\n\t\t\tfmt.Fprintf(w, \"unit %s\\n\", unit.ID)\n\t\t\tfmt.Fprintf(w, \" source: %v\\n\", unit.Source)\n\t\t\tfmt.Fprintf(w, \" target: %v\\n\", unit.Target)\n\n\t\t}\n\t}\n\n\treturn err\n}\n\nfunc (d *dumpXLIFF) ParseArgs(base string, args []string) error ", "output": "{\n\tvar fs = flag.NewFlagSet(base+\" dump\", flag.ExitOnError)\n\tfs.StringVar(&d.inFile, \"in\", \"\", \"infile\")\n\treturn fs.Parse(args)\n}"} {"input": "package ansiwriter\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype Modifier func() string\n\nfunc escapeANSI(code int) string {\n\treturn fmt.Sprintf(\"\\033[%dm\", code)\n}\n\n\nfunc Black() string { return escapeANSI(30) }\nfunc Red() string { return escapeANSI(31) }\nfunc Green() string { return escapeANSI(32) }\nfunc Yellow() string { return escapeANSI(33) }\nfunc Blue() string { return escapeANSI(34) }\nfunc Magenta() string { return escapeANSI(35) }\nfunc Cyan() string { return escapeANSI(36) }\nfunc White() string { return escapeANSI(37) }\n\ntype awr struct {\n\tio.Writer\n\tmodifiers []Modifier\n}\n\n\n\n\nfunc New(w io.Writer, mods ...Modifier) io.Writer {\n\treturn awr{w, mods}\n}\n\nfunc (a awr) Write(b []byte) (n int, err error) {\n\tfor _, mod := range a.modifiers {\n\t\ta.Writer.Write([]byte(mod()))\n\t}\n\tn, err = a.Writer.Write(b)\n\t_, _ = a.Writer.Write([]byte(\"\\033[0m\"))\n\treturn\n}\n\nfunc Bold() string ", "output": "{ return escapeANSI(1) }"} {"input": "package archive\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestCanonicalTarName(t *testing.T) {\n\tcases := []struct {\n\t\tin string\n\t\tisDir bool\n\t\texpected string\n\t}{\n\t\t{\"foo\", false, \"foo\"},\n\t\t{\"foo\", true, \"foo/\"},\n\t\t{`foo\\bar`, false, \"foo/bar\"},\n\t\t{`foo\\bar`, true, \"foo/bar/\"},\n\t}\n\tfor _, v := range cases {\n\t\tif out, err := canonicalTarName(v.in, v.isDir); err != nil {\n\t\t\tt.Fatalf(\"cannot get canonical name for path: %s: %v\", v.in, err)\n\t\t} else if out != v.expected {\n\t\t\tt.Fatalf(\"wrong canonical tar name. expected:%s got:%s\", v.expected, out)\n\t\t}\n\t}\n}\n\nfunc TestCanonicalTarNameForPath(t *testing.T) ", "output": "{\n\tcases := []struct {\n\t\tin, expected string\n\t\tshouldFail bool\n\t}{\n\t\t{\"foo\", \"foo\", false},\n\t\t{\"foo/bar\", \"___\", true}, \n\t\t{`foo\\bar`, \"foo/bar\", false},\n\t\t{`foo\\bar`, \"foo/bar/\", false},\n\t}\n\tfor _, v := range cases {\n\t\tif out, err := canonicalTarNameForPath(v.in); err != nil && !v.shouldFail {\n\t\t\tt.Fatalf(\"cannot get canonical name for path: %s: %v\", v.in, err)\n\t\t} else if v.shouldFail && err == nil {\n\t\t\tt.Fatalf(\"canonical path call should have pailed with error. in=%s out=%s\", v.in, out)\n\t\t} else if !v.shouldFail && out != v.expected {\n\t\t\tt.Fatalf(\"wrong canonical tar name. expected:%s got:%s\", v.expected, out)\n\t\t}\n\t}\n}"} {"input": "package canopus\n\nimport \"net\"\n\n\n\nfunc DialDTLS(address, identity, psk string) (conn Connection, err error) {\n\tudpConn, err := net.Dial(\"udp\", address)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn, err = NewDTLSConnection(udpConn, identity, psk)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc NewObserveMessage(r string, val interface{}, msg Message) ObserveMessage {\n\treturn &CoapObserveMessage{\n\t\tResource: r,\n\t\tValue: val,\n\t\tMsg: msg,\n\t}\n}\n\ntype CoapObserveMessage struct {\n\tCoapMessage\n\tResource string\n\tValue interface{}\n\tMsg Message\n}\n\nfunc (m *CoapObserveMessage) GetResource() string {\n\treturn m.Resource\n}\n\nfunc (m *CoapObserveMessage) GetValue() interface{} {\n\treturn m.Value\n}\n\nfunc (m *CoapObserveMessage) GetMessage() Message {\n\treturn m.GetMessage()\n}\n\nfunc Dial(address string) (conn Connection, err error) ", "output": "{\n\tudpConn, err := net.Dial(\"udp\", address)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn = &UDPConnection{\n\t\tconn: udpConn,\n\t}\n\n\treturn\n}"} {"input": "package commands\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/juju/cmd\"\n\t\"github.com/juju/utils/ssh\"\n\t\"launchpad.net/gnuflag\"\n\n\t\"github.com/juju/juju/cmd/modelcmd\"\n)\n\n\nfunc NewListKeysCommand() cmd.Command {\n\treturn modelcmd.Wrap(&listKeysCommand{})\n}\n\nvar listKeysDoc = `\nList the authorized ssh keys in the model, allowing the holders of those keys to log on to Juju nodes.\nBy default, just the key fingerprint is printed. Use --full to display the entire key.\n\n`\n\n\ntype listKeysCommand struct {\n\tSSHKeysBase\n\tshowFullKey bool\n\tuser string\n}\n\n\n\n\n\nfunc (c *listKeysCommand) SetFlags(f *gnuflag.FlagSet) {\n\tf.BoolVar(&c.showFullKey, \"full\", false, \"show full key instead of just the key fingerprint\")\n}\n\n\nfunc (c *listKeysCommand) Run(context *cmd.Context) error {\n\tclient, err := c.NewKeyManagerClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.Close()\n\n\tmode := ssh.Fingerprints\n\tif c.showFullKey {\n\t\tmode = ssh.FullKeys\n\t}\n\tc.user = \"admin\"\n\tresults, err := client.ListKeys(mode, c.user)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresult := results[0]\n\tif result.Error != nil {\n\t\treturn result.Error\n\t}\n\tfmt.Fprintf(context.Stdout, \"Keys used in model: %s\\n\", c.ConnectionName())\n\tfmt.Fprintln(context.Stdout, strings.Join(result.Result, \"\\n\"))\n\treturn nil\n}\n\nfunc (c *listKeysCommand) Info() *cmd.Info ", "output": "{\n\treturn &cmd.Info{\n\t\tName: \"list-ssh-keys\",\n\t\tDoc: listKeysDoc,\n\t\tPurpose: \"list authorised ssh keys in a model\",\n\t\tAliases: []string{\"ssh-key\", \"ssh-keys\", \"list-ssh-key\"},\n\t}\n}"} {"input": "package dosingdecision\n\nimport (\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tRecommendedBasalDurationMaximum = 86400000\n\tRecommendedBasalDurationMinimum = 0\n\tRecommendedBasalRateMaximum = 100\n\tRecommendedBasalRateMinimum = 0\n)\n\ntype RecommendedBasal struct {\n\tRate *float64 `json:\"rate,omitempty\" bson:\"rate,omitempty\"`\n\tDuration *int `json:\"duration,omitempty\" bson:\"duration,omitempty\"`\n}\n\n\n\nfunc NewRecommendedBasal() *RecommendedBasal {\n\treturn &RecommendedBasal{}\n}\n\nfunc (r *RecommendedBasal) Parse(parser structure.ObjectParser) {\n\tr.Rate = parser.Float64(\"rate\")\n\tr.Duration = parser.Int(\"duration\")\n}\n\nfunc (r *RecommendedBasal) Validate(validator structure.Validator) {\n\tvalidator.Float64(\"rate\", r.Rate).Exists().InRange(RecommendedBasalRateMinimum, RecommendedBasalRateMaximum)\n\tvalidator.Int(\"duration\", r.Duration).InRange(RecommendedBasalDurationMinimum, RecommendedBasalDurationMaximum)\n}\n\nfunc ParseRecommendedBasal(parser structure.ObjectParser) *RecommendedBasal ", "output": "{\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewRecommendedBasal()\n\tparser.Parse(datum)\n\treturn datum\n}"} {"input": "package filesystem\n\nimport (\n\tkeystore2 \"github.com/cossacklabs/acra/keystore\"\n)\n\n\n\nfunc getTokenSymmetricKeyName(id []byte, ownerType keystore2.KeyOwnerType) string {\n\tvar name string\n\tswitch ownerType {\n\tcase keystore2.KeyOwnerTypeClient:\n\t\tname = getClientIDSymmetricKeyName(id)\n\tcase keystore2.KeyOwnerTypeZone:\n\t\tname = getZoneIDSymmetricKeyName(id)\n\tdefault:\n\t\tname = string(id)\n\t}\n\treturn name + \".token\"\n}\n\nfunc getClientIDSymmetricKeyName(id []byte) string {\n\treturn getSymmetricKeyName(GetServerDecryptionKeyFilename(id))\n}\n\nfunc getZoneIDSymmetricKeyName(id []byte) string {\n\treturn getSymmetricKeyName(GetZoneKeyFilename(id))\n}\n\nfunc getSymmetricKeyName(id string) string ", "output": "{\n\treturn id + `_sym`\n}"} {"input": "package metrics\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"github.com/prometheus/client_golang/prometheus/promhttp\"\n\t\"net/http\"\n\t\"sync\"\n)\n\ntype Server struct {\n\tcertificateCh <-chan tls.Certificate\n\n\tsync.Mutex\n\tcertificate *tls.Certificate\n}\n\nfunc (s *Server) getCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {\n\treturn s.certificate, nil\n}\n\n\n\nfunc (s *Server) start(roots *x509.CertPool) {\n\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/metrics\", promhttp.Handler())\n\n\tserver := &http.Server{\n\t\tHandler: mux,\n\t}\n\n\tif s.certificateCh != nil {\n\t\ttlsConfig := &tls.Config{\n\t\t\tGetCertificate: s.getCertificate,\n\t\t}\n\n\t\tif roots != nil {\n\t\t\ttlsConfig.ClientCAs = roots\n\t\t\ttlsConfig.ClientAuth = tls.RequireAndVerifyClientCert\n\t\t}\n\n\t\tserver.TLSConfig = tlsConfig\n\n\t\tgo server.ListenAndServeTLS(\"\", \"\")\n\t} else {\n\t\tgo server.ListenAndServe()\n\t}\n}\n\nfunc StartServer(certificateCh <-chan tls.Certificate, roots *x509.CertPool) {\n\n\tserver := &Server{\n\t\tcertificateCh: certificateCh,\n\t}\n\n\tif certificateCh != nil {\n\t\tgo server.watchForNewCertificates()\n\t}\n\n\tgo server.start(roots)\n}\n\nfunc (s *Server) watchForNewCertificates() ", "output": "{\n\tfor {\n\t\tselect {\n\t\tcase cert := <-s.certificateCh:\n\t\t\ts.certificate = &cert\n\t\t}\n\t}\n}"} {"input": "package lzma\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"unicode\"\n)\n\n\n\ntype operation interface {\n\tLen() int\n}\n\n\ntype match struct {\n\tdistance int64\n\tn int\n}\n\n\n\nfunc (m match) verify() error {\n\tif !(minDistance <= m.distance && m.distance <= maxDistance) {\n\t\treturn errors.New(\"distance out of range\")\n\t}\n\tif !(1 <= m.n && m.n <= maxMatchLen) {\n\t\treturn errors.New(\"length out of range\")\n\t}\n\treturn nil\n}\n\n\n\nfunc (m match) l() uint32 {\n\treturn uint32(m.n - minMatchLen)\n}\n\n\n\nfunc (m match) dist() uint32 {\n\treturn uint32(m.distance - minDistance)\n}\n\n\nfunc (m match) Len() int {\n\treturn m.n\n}\n\n\nfunc (m match) String() string {\n\treturn fmt.Sprintf(\"M{%d,%d}\", m.distance, m.n)\n}\n\n\ntype lit struct {\n\tb byte\n}\n\n\nfunc (l lit) Len() int {\n\treturn 1\n}\n\n\n\n\nfunc (l lit) String() string ", "output": "{\n\tvar c byte\n\tif unicode.IsPrint(rune(l.b)) {\n\t\tc = l.b\n\t} else {\n\t\tc = '.'\n\t}\n\treturn fmt.Sprintf(\"L{%c/%02x}\", c, l.b)\n}"} {"input": "package quit\n\nimport (\n\t\"fmt\"\n\t\"github.com/talpah/cortana/plugins\"\n\t\"regexp\"\n\t\"os\"\n)\n\nvar (\n\tcanonicalCommand = \"quit\"\n\tcommand = `(Q|q)uit`\n\taliases map[string]*regexp.Regexp\n)\n\nfunc isAlias(cmd string) bool {\n\tfor _, alias := range aliases {\n\t\tif alias.MatchString(cmd) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc canHandle(cmd string) bool {\n\tif regexp.MustCompile(command).MatchString(cmd) {\n\t\treturn true\n\t}\n\n\treturn isAlias(cmd)\n}\n\nfunc Initialize(pins plugins.PluginManager) {\n\taliases = map[string]*regexp.Regexp{\n\t\t\"Exit\": regexp.MustCompile(`(E|e)xit`),\n\n\t}\n\n\tpins.Register(\n\t\tcanonicalCommand,\n\t\tcommand,\n\t\tQuit,\n\t\tHelp,\n\t\taliases,\n\t)\n}\n\n\n\nfunc Quit(cmd string) (string, error) {\n\tif !canHandle(cmd) {\n\t\treturn \"\", fmt.Errorf(\"Can't handle command %s\", cmd)\n\t}\n\tos.Exit(0)\n\treturn \"\", nil\n}\n\nfunc Help(cmd string) (string, error) ", "output": "{\n\treturn `Quit command help\n\nQuit will... quit\n\nUsage example:\nquit\nQuit\nexit\nExit\n`, nil\n}"} {"input": "package models\n\nimport (\n\t\"github.com/yangji168/omsystem/dbobj\"\n)\n\ntype ThemeModel struct {\n}\n\n\n\nfunc (ThemeModel) Post(user_id, theme_id string) error ", "output": "{\n\treturn dbobj.Exec(sys_rdbms_024, theme_id, user_id)\n}"} {"input": "package stats_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/montanaflynn/stats\"\n)\n\n\n\nfunc TestSigmoidEmptyInput(t *testing.T) {\n\t_, err := stats.Sigmoid([]float64{})\n\tif err != stats.EmptyInputErr {\n\t\tt.Errorf(\"Should have returned empty input error\")\n\t}\n}\n\nfunc TestSigmoid(t *testing.T) {\n\tsm, err := stats.Sigmoid([]float64{-0.54761371, 17.04850603, 4.86054302})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\ta := 0.3664182235138545\n\tif sm[0] != a {\n\t\tt.Errorf(\"%v != %v\", sm[0], a)\n\t}\n\n\ta = 0.9999999605608187\n\tif sm[1] != a {\n\t\tt.Errorf(\"%v != %v\", sm[1], a)\n\t}\n\n\ta = 0.9923132671908277\n\tif sm[2] != a {\n\t\tt.Errorf(\"%v != %v\", sm[2], a)\n\t}\n}\n\nfunc ExampleSigmoid() ", "output": "{\n\ts, _ := stats.Sigmoid([]float64{3.0, 1.0, 2.1})\n\tfmt.Println(s)\n}"} {"input": "package cms\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/gorilla/mux\"\n\tlib \"github.com/sprucecms/spruce/sprucelib\"\n)\n\ntype cmsManager struct {\n\tprefix string\n\trouter *mux.Router\n\tapp *lib.SpruceApp\n}\n\n\n\n\n\n\nfunc (m cmsManager) handler(w http.ResponseWriter, r *http.Request) {\n\n\tfmt.Fprintf(w, \"No rendering features enabled yet. Path: '%s'\", r.URL.Path)\n}\n\nfunc MountAt(prefix string, app *lib.SpruceApp) http.Handler ", "output": "{\n\tm := cmsManager{prefix: prefix}\n\tm.router = mux.NewRouter()\n\tif m.prefix != \"/\" && m.prefix != \"\" {\n\t\tm.router = m.router.PathPrefix(m.prefix).Subrouter()\n\t}\n\n\tm.router.NotFoundHandler = http.HandlerFunc(m.handler)\n\n\treturn m.router\n}"} {"input": "package main\n\nimport (\n\t\"encoding/hex\"\n\t\"errors\"\n)\n\n\n\n\n\ntype User struct {\n\tId uint32\n\tName string\n\tPassword string\n\tCertHash string\n\tEmail string\n\tTextureBlob string\n\tCommentBlob string\n\tLastChannelId int\n\tLastActive uint64\n}\n\n\n\n\n\nfunc (user *User) HasComment() bool {\n\treturn len(user.CommentBlob) > 0\n}\n\n\n\nfunc (user *User) CommentBlobHashBytes() (buf []byte) {\n\tbuf, err := hex.DecodeString(user.CommentBlob)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn buf\n}\n\n\nfunc (user *User) HasTexture() bool {\n\treturn len(user.TextureBlob) > 0\n}\n\n\n\nfunc (user *User) TextureBlobHashBytes() (buf []byte) {\n\tbuf, err := hex.DecodeString(user.TextureBlob)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn buf\n}\n\nfunc NewUser(id uint32, name string) (user *User, err error) ", "output": "{\n\tif id < 0 {\n\t\treturn nil, errors.New(\"Invalid user id\")\n\t}\n\tif len(name) == 0 {\n\t\treturn nil, errors.New(\"Invalid username\")\n\t}\n\n\treturn &User{\n\t\tId: id,\n\t\tName: name,\n\t}, nil\n}"} {"input": "package service\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"go-common/app/service/main/assist/conf\"\n\t\"go-common/app/service/main/assist/dao/account\"\n\t\"go-common/app/service/main/assist/dao/assist\"\n\t\"go-common/app/service/main/assist/dao/message\"\n\t\"go-common/library/log\"\n\t\"go-common/library/queue/databus\"\n)\n\n\ntype Service struct {\n\tc *conf.Config\n\tass *assist.Dao\n\tacc *account.Dao\n\tmsg *message.Dao\n\trelationSub *databus.Databus\n\tcacheChan chan func()\n\twg sync.WaitGroup\n}\n\n\nfunc New(c *conf.Config) *Service {\n\ts := &Service{\n\t\tc: c,\n\t\tass: assist.New(c),\n\t\tacc: account.New(c),\n\t\tmsg: message.New(c),\n\t\tcacheChan: make(chan func(), 1024),\n\t\trelationSub: databus.New(c.RelationSub),\n\t}\n\ts.wg.Add(1)\n\tgo s.relationConsumer()\n\ts.wg.Add(1)\n\tgo s.cacheproc()\n\treturn s\n}\n\n\nfunc (s *Service) Ping(c context.Context) (err error) {\n\tif err = s.ass.Ping(c); err != nil {\n\t\tlog.Error(\"s.ass.Dao.Ping err(%v)\", err)\n\t}\n\treturn\n}\n\n\n\n\n\nfunc (s *Service) cacheproc() {\n\tfor {\n\t\tf := <-s.cacheChan\n\t\tf()\n\t}\n}\n\n\nfunc (s *Service) Close() {\n\ts.relationSub.Close()\n\ts.wg.Wait()\n}\n\nfunc (s *Service) asyncCache(f func()) ", "output": "{\n\tselect {\n\tcase s.cacheChan <- f:\n\tdefault:\n\t\tlog.Warn(\"assist cacheproc chan full\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"upper.io/db.v2/postgresql\"\n\n\t\"github.com/olegakbarov/io.confs.core/adapters/web\"\n\t\"github.com/olegakbarov/io.confs.core/core\"\n\t\"github.com/olegakbarov/io.confs.core/providers\"\n\tpostgresqlrepo \"github.com/olegakbarov/io.confs.core/providers/postgres\"\n)\n\n\n\nfunc main() {\n\tsettings := postgresql.ConnectionURL{\n\t\tUser: os.Getenv(\"DB_USER\"),\n\t\tPassword: os.Getenv(\"DB_PASS\"),\n\t\tHost: os.Getenv(\"DB_HOST\"),\n\t\tDatabase: os.Getenv(\"DB_NAME\"),\n\t\tOptions: map[string]string{\n\t\t\t\"port\": os.Getenv(\"DB_PORT\"),\n\t\t\t\"sslmode\": \"disable\",\n\t\t},\n\t}\n\n\tlog.Printf(\"%v\", settings)\n\n\tsess, err := postgresql.Open(settings)\n\tcheckErr(err)\n\n\tvar sf core.StorageFactory\n\tsf = postgresqlrepo.NewStorage(sess)\n\n\tvar (\n\t\tvalidator core.Validator\n\t\tmailSender core.MailSender\n\t\tjwt core.JWTSignParser\n\t)\n\n\tvalidator = providers.NewValidator()\n\tmailSender = providers.NewFakeMail()\n\tjwt = providers.NewJWT()\n\temitter := providers.NewEmitter()\n\n\tf := core.New(sf, mailSender, validator, jwt, emitter)\n\n\tlog.Printf(\"Server is up on port: %s\", os.Getenv(\"PORT\"))\n\tif err := http.ListenAndServe(fmt.Sprintf(\":%s\", os.Getenv(\"PORT\")), web.NewWebAdapter(f)); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc checkErr(err error) ", "output": "{\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"input": "package lineargo\n\n\nimport \"C\"\nimport \"unsafe\"\n\nfunc mapCDouble(in []float64) []C.double {\n\tout := make([]C.double, len(in), len(in))\n\tfor i, val := range in {\n\t\tout[i] = C.double(val)\n\t}\n\treturn out\n}\n\n\n\n\nfunc doubleToFloats(in *C.double, size int) []float64 {\n\tdefer C.free(unsafe.Pointer(in))\n\toutD := (*[1 << 30]C.double)(unsafe.Pointer(in))[:size:size]\n\tout := make([]float64, size, size)\n\tfor i := 0; i < size; i++ {\n\t\tout[i] = float64(outD[i])\n\t}\n\n\treturn out\n}\n\nfunc mapCInt(in []int) []C.int ", "output": "{\n\tout := make([]C.int, len(in), len(in))\n\tfor i, val := range in {\n\t\tout[i] = C.int(val)\n\t}\n\treturn out\n}"} {"input": "package api\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/zaaksam/dproxy/go/services\"\n)\n\n\ntype ProxyController struct {\n\tBaseController\n}\n\n\n\n\n\nfunc (c *ProxyController) Stop() {\n\tidStr := c.Ctx.Input.Param(\":id\")\n\tid, err := strconv.ParseInt(idStr, 10, 0)\n\tif err != nil {\n\t\tc.SetError(\"id参数错误\")\n\t\treturn\n\t}\n\n\tservices.Proxy.Stop(id)\n}\n\nfunc (c *ProxyController) Start() ", "output": "{\n\tidStr := c.Ctx.Input.Param(\":id\")\n\tid, err := strconv.ParseInt(idStr, 10, 0)\n\tif err != nil {\n\t\tc.SetError(\"id参数错误\")\n\t\treturn\n\t}\n\n\terr = services.Proxy.Start(id)\n\tif err != nil {\n\t\tc.SetError(err)\n\t}\n}"} {"input": "package models\n\nimport (\n\t\"encoding/json\"\n\t\"reflect\"\n)\n\nfunc FromJSON(payload []byte, v Validator) error {\n\terr := json.Unmarshal(payload, v)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn v.Validate()\n}\n\nfunc ToJSON(v Validator) ([]byte, *Error) {\n\tif !isNil(v) {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn nil, NewError(InvalidRecord, err.Error())\n\t\t}\n\t}\n\n\tbytes, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn nil, NewError(InvalidJSON, err.Error())\n\t}\n\n\treturn bytes, nil\n}\n\n\n\nfunc isNil(a interface{}) bool ", "output": "{\n\tif a == nil {\n\t\treturn true\n\t}\n\n\tswitch reflect.TypeOf(a).Kind() {\n\tcase reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:\n\t\treturn reflect.ValueOf(a).IsNil()\n\t}\n\n\treturn false\n}"} {"input": "package lfu\n\ntype lfuItem struct {\n\tdata interface{}\n\tparent *freqNode\n}\n\n\n\nfunc newlfuItem(data interface{}, parent *freqNode) *lfuItem ", "output": "{\n\treturn &lfuItem{\n\t\tdata: data,\n\t\tparent: parent,\n\t}\n}"} {"input": "package loki_test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/andviro/goldie\"\n\t\"github.com/andviro/grayproxy/pkg/loki\"\n\t\"github.com/prometheus/common/model\"\n)\n\ntype testHandler bytes.Buffer\n\nfunc (t *testHandler) Handle(ls model.LabelSet, ts time.Time, s string) error {\n\tbuf := (*bytes.Buffer)(t)\n\tjd, _ := json.Marshal(ts)\n\tfmt.Fprintf(buf, \"%s\\n\", jd)\n\tjd, _ = json.MarshalIndent(ls, \"\", \"\\t\")\n\tfmt.Fprintf(buf, \"%s\\n\", jd)\n\tfmt.Fprintf(buf, \"%s\\n\", s)\n\treturn nil\n}\n\n\n\nfunc TestSender_Send(t *testing.T) ", "output": "{\n\tbuf := new(bytes.Buffer)\n\ts := loki.Sender{Handler: (*testHandler)(buf), Job: \"test\"}\n\terr := s.Send([]byte(`{\n\t \"version\": \"1.1\",\n\t \"host\": \"example.org\",\n\t \"short_message\": \"A short message that helps you identify what is going on\",\n\t \"full_message\": \"Backtrace here\\n\\nmore stuff\",\n\t \"timestamp\": 1385053862.3072,\n\t \"level\": 1,\n\t \"_user_id\": 9001,\n\t \"_some_info\": \"foo\",\n\t \"_some_env_var\": \"bar\"\n\t}`))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tgoldie.Assert(t, \"sender-send\", buf.Bytes())\n}"} {"input": "package packets\n\nimport (\n\t\"fmt\"\n\t\"github.com/google/uuid\"\n\t\"io\"\n)\n\n\n\ntype PubcompPacket struct {\n\tFixedHeader\n\tMessageID uint16\n\tuuid uuid.UUID\n}\n\n\n\nfunc (pc *PubcompPacket) Write(w io.Writer) error {\n\tvar err error\n\tpc.FixedHeader.RemainingLength = 2\n\tpacket := pc.FixedHeader.pack()\n\tpacket.Write(encodeUint16(pc.MessageID))\n\t_, err = packet.WriteTo(w)\n\n\treturn err\n}\n\nfunc (pc *PubcompPacket) Unpack(b io.Reader) {\n\tpc.MessageID = decodeUint16(b)\n}\n\nfunc (pc *PubcompPacket) Details() Details {\n\treturn Details{Qos: pc.Qos, MessageID: pc.MessageID}\n}\n\nfunc (pc *PubcompPacket) UUID() uuid.UUID {\n\treturn pc.uuid\n}\n\nfunc (pc *PubcompPacket) String() string ", "output": "{\n\tstr := fmt.Sprintf(\"%s\\n\", pc.FixedHeader)\n\tstr += fmt.Sprintf(\"MessageID: %d\", pc.MessageID)\n\treturn str\n}"} {"input": "package iso20022\n\n\ntype DirectDebitTransaction7 struct {\n\n\tMandateRelatedInformation *MandateRelatedInformation8 `xml:\"MndtRltdInf,omitempty\"`\n\n\tCreditorSchemeIdentification *PartyIdentification43 `xml:\"CdtrSchmeId,omitempty\"`\n\n\tPreNotificationIdentification *Max35Text `xml:\"PreNtfctnId,omitempty\"`\n\n\tPreNotificationDate *ISODate `xml:\"PreNtfctnDt,omitempty\"`\n}\n\nfunc (d *DirectDebitTransaction7) AddMandateRelatedInformation() *MandateRelatedInformation8 {\n\td.MandateRelatedInformation = new(MandateRelatedInformation8)\n\treturn d.MandateRelatedInformation\n}\n\n\n\nfunc (d *DirectDebitTransaction7) SetPreNotificationIdentification(value string) {\n\td.PreNotificationIdentification = (*Max35Text)(&value)\n}\n\nfunc (d *DirectDebitTransaction7) SetPreNotificationDate(value string) {\n\td.PreNotificationDate = (*ISODate)(&value)\n}\n\nfunc (d *DirectDebitTransaction7) AddCreditorSchemeIdentification() *PartyIdentification43 ", "output": "{\n\td.CreditorSchemeIdentification = new(PartyIdentification43)\n\treturn d.CreditorSchemeIdentification\n}"} {"input": "package directory\n\nimport (\n\t\"github.com/corestoreio/csfw/config\"\n\t\"github.com/corestoreio/csfw/config/model\"\n\t\"github.com/corestoreio/csfw/store/scope\"\n\t\"github.com/juju/errgo\"\n\t\"golang.org/x/text/currency\"\n)\n\n\ntype ConfigCurrency struct {\n\tmodel.Str\n}\n\n\nfunc NewConfigCurrency(path string, opts ...model.Option) ConfigCurrency {\n\treturn ConfigCurrency{\n\t\tStr: model.NewStr(path, opts...),\n\t}\n}\n\n\nfunc (p ConfigCurrency) Get(sg config.ScopedGetter) (Currency, error) {\n\tcur := p.Str.Get(sg)\n\tu, err := currency.ParseISO(cur)\n\tif err != nil {\n\t\treturn Currency{}, errgo.Mask(err)\n\t}\n\treturn Currency{Unit: u}, nil\n}\n\n\n\n\nfunc (p ConfigCurrency) Write(w config.Writer, v Currency, s scope.Scope, id int64) error ", "output": "{\n\treturn p.Str.Write(w, v.String(), s, id)\n}"} {"input": "package testbackend\n\nimport (\n\t\"context\"\n\n\t\"github.com/stripe/veneur/v14/ssf\"\n\t\"github.com/stripe/veneur/v14/trace\"\n)\n\n\n\ntype SendErrorSource func(*ssf.SSFSpan) error\n\n\n\ntype BackendOption func(*Backend)\n\n\n\n\n\n\n\ntype Backend struct {\n\tch chan<- *ssf.SSFSpan\n\terrorSrc SendErrorSource\n}\n\n\nfunc (be *Backend) Close() error {\n\treturn nil\n}\n\n\nfunc (be *Backend) SendSync(ctx context.Context, span *ssf.SSFSpan) error {\n\tif be.errorSrc != nil {\n\t\tif err := be.errorSrc(span); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tselect {\n\tcase be.ch <- span:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}\n\n\n\nfunc NewBackend(ch chan<- *ssf.SSFSpan, opts ...BackendOption) trace.ClientBackend {\n\tbe := &Backend{ch: ch}\n\tfor _, opt := range opts {\n\t\topt(be)\n\t}\n\treturn be\n}\n\nfunc SendErrors(src SendErrorSource) BackendOption ", "output": "{\n\treturn func(be *Backend) {\n\t\tbe.errorSrc = src\n\t}\n}"} {"input": "package crc32\n\n\n\n\n\nfunc updateIEEE(crc uint32, p []byte) uint32 {\n\tif len(p) >= 16 {\n\t\tiEEETable8Once.Do(func() {\n\t\t\tiEEETable8 = makeTable8(IEEE)\n\t\t})\n\t\treturn updateSlicingBy8(crc, iEEETable8, p)\n\t}\n\treturn update(crc, IEEETable, p)\n}\n\nfunc updateCastagnoli(crc uint32, p []byte) uint32 ", "output": "{\n\tif len(p) >= 16 {\n\t\treturn updateSlicingBy8(crc, castagnoliTable8, p)\n\t}\n\treturn update(crc, castagnoliTable, p)\n}"} {"input": "package util\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/sodafoundation/api/client\"\n\t\"github.com/sodafoundation/api/pkg/model\"\n)\n\n\nfunc GetHostByHostName(client *client.Client, hostName string) (*model.HostSpec, error) {\n\thostLists, err := client.HostMgr.ListHosts()\n\tif nil != err {\n\t\treturn nil, errors.New(\"Failed to list hosts\")\n\t}\n\n\tfor _, elem := range hostLists {\n\t\tif elem.HostName == hostName {\n\t\t\treturn elem, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"Failed to find host for hostname %s\", hostName)\n}\n\n\n\n\nfunc GetHostByHostId(client *client.Client, hostId string) (*model.HostSpec, error) ", "output": "{\n\thostLists, err := client.HostMgr.ListHosts()\n\tif nil != err {\n\t\treturn nil, errors.New(\"Failed to list hosts\")\n\t}\n\n\tfor _, elem := range hostLists {\n\t\tif elem.Id == hostId {\n\t\t\treturn elem, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"Failed to find host for hostId %s\", hostId)\n}"} {"input": "package mocks\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n\t\"unsafe\"\n\n\t\"github.com/Juniper/contrail-go-api\"\n)\n\n\n\nfunc getReferenceList(obj contrail.IObject) UIDList {\n\trefList := make([]UID, 0, 8)\n\tvalue := reflect.ValueOf(obj).Elem()\n\ttypeval := value.Type()\n\n\tfor i := 0; i < value.NumField(); i++ {\n\t\tname := typeval.Field(i).Name\n\t\tif strings.HasSuffix(name, \"_back_refs\") {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasSuffix(name, \"_refs\") {\n\t\t\tfield := value.Field(i)\n\t\t\tfor i := 0; i < field.Len(); i++ {\n\t\t\t\tv := field.Index(i)\n\t\t\t\tref := (*contrail.Reference)(unsafe.Pointer(v.UnsafeAddr()))\n\t\t\t\trefList = append(refList, parseUID(ref.Uuid))\n\t\t\t}\n\t\t}\n\t}\n\treturn refList\n}\n\n\n\n\n\n\nfunc clearReferenceMask(obj contrail.IObject) ", "output": "{\n\tvalue := reflect.ValueOf(obj).Elem()\n\tfield := value.FieldByName(\"valid\")\n\tmaskptr := (*uint64)(unsafe.Pointer(field.UnsafeAddr()))\n\t*maskptr = 0\n}"} {"input": "package types\n\n\n\n\nimport (\n\t\"github.com/jcmturner/gofork/encoding/asn1\"\n)\n\n\n\n\nfunc NewKrbFlags() asn1.BitString {\n\tf := asn1.BitString{}\n\tf.Bytes = make([]byte, 4)\n\tf.BitLength = len(f.Bytes) * 8\n\treturn f\n}\n\n\nfunc SetFlags(f *asn1.BitString, j []int) {\n\tfor _, i := range j {\n\t\tSetFlag(f, i)\n\t}\n}\n\n\nfunc SetFlag(f *asn1.BitString, i int) {\n\tfor l := len(f.Bytes); l < 4; l++ {\n\t\t(*f).Bytes = append((*f).Bytes, byte(0))\n\t\t(*f).BitLength = len((*f).Bytes) * 8\n\t}\n\tb := i / 8\n\tp := uint(7 - (i - 8*b))\n\t(*f).Bytes[b] = (*f).Bytes[b] | (1 << p)\n}\n\n\n\n\n\nfunc UnsetFlag(f *asn1.BitString, i int) {\n\tfor l := len(f.Bytes); l < 4; l++ {\n\t\t(*f).Bytes = append((*f).Bytes, byte(0))\n\t\t(*f).BitLength = len((*f).Bytes) * 8\n\t}\n\tb := i / 8\n\tp := uint(7 - (i - 8*b))\n\t(*f).Bytes[b] = (*f).Bytes[b] &^ (1 << p)\n}\n\n\nfunc IsFlagSet(f *asn1.BitString, i int) bool {\n\tb := i / 8\n\tp := uint(7 - (i - 8*b))\n\tif (*f).Bytes[b]&(1< rv {\n\t\t\tif li < len(l) {\n\t\t\t\tans = ans + len(l) - li\n\t\t\t}\n\n\t\t\tresult[k] = rv\n\t\t\tri++\n\t\t} else {\n\t\t\tresult[k] = lv\n\t\t\tli++\n\t\t}\n\t}\n\n\treturn result\n}"} {"input": "package comparators\n\n\ntype UInt8Comparator struct {\n}\n\n\nfunc NewUInt8Comparator() *UInt8Comparator {\n\treturn &UInt8Comparator{}\n}\n\n\n\n\n\n\n\nfunc (comparator *UInt8Comparator) Compare(a, b interface{}) int ", "output": "{\n\taAsserted := a.(uint8)\n\tbAsserted := b.(uint8)\n\tswitch {\n\tcase aAsserted > bAsserted:\n\t\treturn 1\n\tcase aAsserted < bAsserted:\n\t\treturn -1\n\tdefault:\n\t\treturn 0\n\t}\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nconst (\n\tExitSuccess = iota\n\tExitError\n\tExitBadConnection\n\tExitInvalidInput\n\tExitBadFeature\n\tExitInterrupted\n\tExitIO\n\tExitBadArgs = 128\n)\n\n\n\nfunc ExitWithError(code int, err error) ", "output": "{\n\tfmt.Fprintf(os.Stderr, \"\\033[31mError: %s\\033[0m\\n\", err)\n\tos.Exit(code)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\thyperclient \"github.com/Cloud-Foundations/Dominator/hypervisor/client\"\n\t\"github.com/Cloud-Foundations/Dominator/lib/log\"\n)\n\nfunc connectToVmConsoleSubcommand(args []string,\n\tlogger log.DebugLogger) error {\n\tif err := connectToVmConsole(args[0], logger); err != nil {\n\t\treturn fmt.Errorf(\"Error connecting to VM console: %s\", err)\n\t}\n\treturn nil\n}\n\n\n\nfunc connectToVmConsoleOnHypervisor(hypervisor string, ipAddr net.IP,\n\tlogger log.DebugLogger) error {\n\tclient, err := dialHypervisor(hypervisor)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.Close()\n\treturn hyperclient.ConnectToVmConsole(client, ipAddr, *vncViewer, logger)\n}\n\nfunc connectToVmConsole(vmHostname string, logger log.DebugLogger) error ", "output": "{\n\tif vmIP, hypervisor, err := lookupVmAndHypervisor(vmHostname); err != nil {\n\t\treturn err\n\t} else {\n\t\treturn connectToVmConsoleOnHypervisor(hypervisor, vmIP, logger)\n\t}\n}"} {"input": "package store\n\nimport (\n\t\"strings\"\n\n\t\"github.com/jingweno/ccat/Godeps/_workspace/src/github.com/kr/fs\"\n\t\"github.com/jingweno/ccat/Godeps/_workspace/src/sourcegraph.com/sourcegraph/rwvfs\"\n)\n\n\n\ntype RepoPaths interface {\n\tRepoToPath(string) []string\n\n\tPathToRepo(path []string) string\n\n\tListRepoPaths(vfs rwvfs.WalkableFileSystem, after string, max int) ([][]string, error)\n}\n\n\n\n\nvar DefaultRepoPaths defaultRepoPaths\n\ntype defaultRepoPaths struct{}\n\n\nfunc (defaultRepoPaths) RepoToPath(repo string) []string {\n\tp := strings.Split(repo, \"/\")\n\tp = append(p, SrclibStoreDir)\n\treturn p\n}\n\n\nfunc (defaultRepoPaths) PathToRepo(path []string) string {\n\treturn strings.Join(path[:len(path)-1], \"/\")\n}\n\n\n\n\nfunc (defaultRepoPaths) ListRepoPaths(vfs rwvfs.WalkableFileSystem, after string, max int) ([][]string, error) ", "output": "{\n\tvar paths [][]string\n\tw := fs.WalkFS(\".\", rwvfs.Walkable(vfs))\n\tfor w.Step() {\n\t\tif err := w.Err(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfi := w.Stat()\n\t\tif w.Path() >= after && fi.Mode().IsDir() {\n\t\t\tif fi.Name() == SrclibStoreDir {\n\t\t\t\tw.SkipDir()\n\t\t\t\tpaths = append(paths, strings.Split(w.Path(), \"/\"))\n\t\t\t\tif max != 0 && len(paths) >= max {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif fi.Name() != \".\" && strings.HasPrefix(fi.Name(), \".\") {\n\t\t\t\tw.SkipDir()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\treturn paths, nil\n}"} {"input": "package main\n\ntype Element struct {\n\tValue interface{}\n\tnext *Element\n}\n\ntype List struct {\n\te Element\n\tsize int\n}\n\n\n\n\nfunc (l *List) Add(e, at *Element) *Element {\n l.e.Value == at.Value\n}\n\nfunc (l *List) Remove() *Element {\n\n}\n\nfunc (l *List) Size() int {\n\treturn l.size\n}\n\nfunc main() {\n}\n\nfunc New() *List ", "output": "{\n\tl := new(List)\n l.e.next = &l.e\n l.size = 0\n\treturn l\n}"} {"input": "package resource\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n)\n\n\ntype Item struct {\n\tID interface{}\n\tETag string\n\tUpdated time.Time\n\tPayload map[string]interface{}\n}\n\n\ntype ItemList struct {\n\tTotal int\n\tPage int\n\tItems []*Item\n}\n\n\n\n\n\n\n\n\nfunc (i Item) GetField(name string) interface{} {\n\treturn getField(i.Payload, name)\n}\n\n\n\nfunc getField(payload map[string]interface{}, name string) interface{} {\n\tpath := strings.SplitN(name, \".\", 2)\n\tif value, found := payload[path[0]]; found {\n\t\tif len(path) == 2 {\n\t\t\tif subPayload, ok := value.(map[string]interface{}); ok {\n\t\t\t\treturn getField(subPayload, path[1])\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\treturn value\n\t}\n\treturn nil\n}\n\nfunc NewItem(payload map[string]interface{}) (*Item, error) ", "output": "{\n\tid, found := payload[\"id\"]\n\tif !found {\n\t\treturn nil, errors.New(\"Missing ID field\")\n\t}\n\tetag, err := genEtag(payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\titem := &Item{\n\t\tID: id,\n\t\tETag: etag,\n\t\tUpdated: time.Now(),\n\t\tPayload: payload,\n\t}\n\treturn item, nil\n}"} {"input": "package bits_test\n\nimport (\n\t\"github.com/twmb/bits\"\n\t\"testing\"\n)\n\nfunc TestSet(t *testing.T) {\n\tfor i := 0; i < 256; i++ {\n\t\tif int(bits.SetU32(uint32(i))) != bits.Hamming(i, 0) {\n\t\t\tt.Errorf(\"Error in set: wanted %v for %v, got %v\",\n\t\t\t\tbits.Hamming(i, 0), i, bits.SetU32(uint32(i)))\n\t\t}\n\t}\n}\n\nfunc BenchmarkSetTable(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetTable(i)\n\t}\n}\nfunc BenchmarkSetKernighan(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetKernighan(uint(i))\n\t}\n}\n\nfunc BenchmarkSetU64(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetU64(uint64(i))\n\t}\n}\n\nfunc BenchmarkSetU32(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetU32(uint32(i))\n\t}\n}"} {"input": "package env\n\nimport (\n\t\"os\"\n\t\"strconv\"\n)\n\n\n\nfunc GetEnvAsIntOrFallback(key string, defaultValue int) (int, error) {\n\tif v := os.Getenv(key); v != \"\" {\n\t\tvalue, err := strconv.Atoi(v)\n\t\tif err != nil {\n\t\t\treturn defaultValue, err\n\t\t}\n\t\treturn value, nil\n\t}\n\treturn defaultValue, nil\n}\n\nfunc GetEnvAsFloat64OrFallback(key string, defaultValue float64) (float64, error) {\n\tif v := os.Getenv(key); v != \"\" {\n\t\tvalue, err := strconv.ParseFloat(v, 64)\n\t\tif err != nil {\n\t\t\treturn defaultValue, err\n\t\t}\n\t\treturn value, nil\n\t}\n\treturn defaultValue, nil\n}\n\nfunc GetEnvAsStringOrFallback(key, defaultValue string) string ", "output": "{\n\tif v := os.Getenv(key); v != \"\" {\n\t\treturn v\n\t}\n\treturn defaultValue\n}"} {"input": "package weibo\n\nimport \"github.com/7sDream/rikka/common/util\"\n\n\n\nfunc (wbp weiboPlugin) Init() ", "output": "{\n\tl.Info(\"Start plugin weibo\")\n\n\tcookiesStr := util.GetEnvWithCheck(\"Cookies\", cookiesEnvKey, l)\n\n\tclient = newWeiboClient()\n\n\tif err := updateCookies(cookiesStr); err != nil {\n\t\tl.Fatal(\"Error happened when create cookies:\", err)\n\t}\n\n\tl.Info(\"Arg update cookies password =\", *argUpdateCookiesPassword)\n\n\tl.Info(\"Weibo plugin start successfully\")\n}"} {"input": "package object\n\nimport (\n\t\"github.com/vmware/govmomi/vim25\"\n\t\"github.com/vmware/govmomi/vim25/methods\"\n\t\"github.com/vmware/govmomi/vim25/types\"\n\t\"golang.org/x/net/context\"\n)\n\ntype OptionManager struct {\n\tCommon\n}\n\nfunc NewOptionManager(c *vim25.Client, ref types.ManagedObjectReference) *OptionManager {\n\treturn &OptionManager{\n\t\tCommon: NewCommon(c, ref),\n\t}\n}\n\nfunc (m OptionManager) Query(ctx context.Context, name string) ([]types.BaseOptionValue, error) {\n\treq := types.QueryOptions{\n\t\tThis: m.Reference(),\n\t\tName: name,\n\t}\n\n\tres, err := methods.QueryOptions(ctx, m.Client(), &req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res.Returnval, nil\n}\n\n\n\nfunc (m OptionManager) Update(ctx context.Context, value []types.BaseOptionValue) error ", "output": "{\n\treq := types.UpdateOptions{\n\t\tThis: m.Reference(),\n\t\tChangedValue: value,\n\t}\n\n\t_, err := methods.UpdateOptions(ctx, m.Client(), &req)\n\treturn err\n}"} {"input": "package rest\n\nimport (\n\t\"time\"\n\n\teventsapiv1beta1 \"k8s.io/api/events/v1beta1\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\t\"k8s.io/apiserver/pkg/registry/rest\"\n\tgenericapiserver \"k8s.io/apiserver/pkg/server\"\n\tserverstorage \"k8s.io/apiserver/pkg/server/storage\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\t\"k8s.io/kubernetes/pkg/apis/events\"\n\teventstore \"k8s.io/kubernetes/pkg/registry/core/event/storage\"\n)\n\ntype RESTStorageProvider struct {\n\tTTL time.Duration\n}\n\nfunc (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(events.GroupName, legacyscheme.Registry, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\n\tif apiResourceConfigSource.VersionEnabled(eventsapiv1beta1.SchemeGroupVersion) {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[eventsapiv1beta1.SchemeGroupVersion.Version] = p.v1beta1Storage(apiResourceConfigSource, restOptionsGetter)\n\t\tapiGroupInfo.GroupMeta.GroupVersion = eventsapiv1beta1.SchemeGroupVersion\n\t}\n\n\treturn apiGroupInfo, true\n}\n\nfunc (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage {\n\tstorage := map[string]rest.Storage{}\n\teventsStorage := eventstore.NewREST(restOptionsGetter, uint64(p.TTL.Seconds()))\n\tstorage[\"events\"] = eventsStorage\n\n\treturn storage\n}\n\n\n\nfunc (p RESTStorageProvider) GroupName() string ", "output": "{\n\treturn events.GroupName\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"net/http\"\n \"runtime\"\n \n)\n\nfunc main() {\n runtime.GOMAXPROCS(runtime.NumCPU())\n\n http.HandleFunc(\"/\", hello)\n\n fmt.Println(\"listening...\")\n\n err := http.ListenAndServe(\":8000\", nil)\n if err != nil {\n panic(err)\n }\n}\n\n\n\n\n\nfunc hello(res http.ResponseWriter, req *http.Request) ", "output": "{\n fmt.Fprintln(res, \"the forms are go!\")\n}"} {"input": "package openstack\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gophercloud/gophercloud\"\n\ttokens2 \"github.com/gophercloud/gophercloud/openstack/identity/v2/tokens\"\n\ttokens3 \"github.com/gophercloud/gophercloud/openstack/identity/v3/tokens\"\n)\n\n\n\ntype ErrEndpointNotFound struct{ gophercloud.BaseError }\n\nfunc (e ErrEndpointNotFound) Error() string {\n\treturn \"No suitable endpoint could be found in the service catalog.\"\n}\n\n\n\ntype ErrInvalidAvailabilityProvided struct{ gophercloud.ErrInvalidInput }\n\n\n\n\n\ntype ErrMultipleMatchingEndpointsV2 struct {\n\tgophercloud.BaseError\n\tEndpoints []tokens2.Endpoint\n}\n\nfunc (e ErrMultipleMatchingEndpointsV2) Error() string {\n\treturn fmt.Sprintf(\"Discovered %d matching endpoints: %#v\", len(e.Endpoints), e.Endpoints)\n}\n\n\n\ntype ErrMultipleMatchingEndpointsV3 struct {\n\tgophercloud.BaseError\n\tEndpoints []tokens3.Endpoint\n}\n\nfunc (e ErrMultipleMatchingEndpointsV3) Error() string {\n\treturn fmt.Sprintf(\"Discovered %d matching endpoints: %#v\", len(e.Endpoints), e.Endpoints)\n}\n\n\n\ntype ErrNoAuthURL struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoAuthURL) Error() string {\n\treturn \"Environment variable OS_AUTH_URL needs to be set.\"\n}\n\n\n\ntype ErrNoUsername struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoUsername) Error() string {\n\treturn \"Environment variable OS_USERNAME needs to be set.\"\n}\n\n\n\ntype ErrNoPassword struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoPassword) Error() string {\n\treturn \"Environment variable OS_PASSWORD needs to be set.\"\n}\n\nfunc (e ErrInvalidAvailabilityProvided) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"Unexpected availability in endpoint query: %s\", e.Value)\n}"} {"input": "package melting\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"reflect\"\n)\n\n\n\ntype nameFilter struct {\n\texclude string\n}\n\nfunc (f *nameFilter) Filter(srcField, destField reflect.StructField, src, dest reflect.Value) bool {\n\treturn f.exclude != srcField.Name\n}\n\nfunc ExampleMeltWithFilter() {\n\ttype Source struct {\n\t\tF1 int\n\t\tF2 string\n\t}\n\ttype Dest struct {\n\t\tF1 int\n\t\tF2 string\n\t\tF3 float32\n\t}\n\n\ts := Source{F1: 3, F2: \"a\"}\n\td := Dest{F1: 4, F2: \"b\", F3: 3.1}\n\n\terr := MeltWithFilter(s, &d, &nameFilter{\"F2\"})\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot assign source to dest, error %v\", err)\n\t}\n\n\tfmt.Printf(\"Source%v\\nDest%v\\n\", s, d)\n\n}\n\nfunc Example() ", "output": "{\n\ttype Source struct {\n\t\tF1 int\n\t\tF2 string\n\t}\n\ttype Dest struct {\n\t\tF1 int\n\t\tF3 float32\n\t\tF2 string\n\t}\n\n\ts := Source{F1: 3, F2: \"a\"}\n\td := Dest{F1: 4, F2: \"b\", F3: 3.1}\n\n\terr := Melt(s, &d)\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot assign source to dest, error %v\", err)\n\t}\n\n\tfmt.Printf(\"Source%v\\nDest%v\\n\", s, d)\n\n}"} {"input": "package pmgo\n\nimport mgo \"gopkg.in/mgo.v2\"\n\ntype IterManager interface {\n\tAll(result interface{}) error\n\tClose() error\n\tDone() bool\n\tErr() error\n\tFor(result interface{}, f func() error) (err error)\n\tNext(result interface{}) bool\n\tTimeout() bool\n}\n\ntype Iter struct {\n\titer *mgo.Iter\n}\n\nfunc NewIter(iter *mgo.Iter) IterManager {\n\treturn &Iter{iter}\n}\n\nfunc (i *Iter) All(result interface{}) error {\n\treturn i.iter.All(result)\n}\n\n\n\nfunc (i *Iter) Done() bool {\n\treturn i.iter.Done()\n}\n\nfunc (i *Iter) Err() error {\n\treturn i.iter.Err()\n}\n\nfunc (i *Iter) For(result interface{}, f func() error) (err error) {\n\treturn i.iter.For(result, f)\n}\n\nfunc (i *Iter) Next(result interface{}) bool {\n\treturn i.iter.Next(result)\n}\n\nfunc (i *Iter) Timeout() bool {\n\treturn i.iter.Timeout()\n}\n\nfunc (i *Iter) Close() error ", "output": "{\n\treturn i.iter.Close()\n}"} {"input": "package networks\n\nimport (\n\t\"github.com/gophercloud/gophercloud\"\n\t\"github.com/gophercloud/gophercloud/pagination\"\n)\n\n\n\n\n\nfunc Get(client *gophercloud.ServiceClient, id string) (r GetResult) {\n\t_, r.Err = client.Get(getURL(client, id), &r.Body, nil)\n\treturn\n}\n\nfunc List(client *gophercloud.ServiceClient) pagination.Pager ", "output": "{\n\treturn pagination.NewPager(client, listURL(client), func(r pagination.PageResult) pagination.Page {\n\t\treturn NetworkPage{pagination.SinglePageBase(r)}\n\t})\n}"} {"input": "package chart\n\nimport (\n\t\"baliance.com/gooxml\"\n\t\"baliance.com/gooxml/drawing\"\n\t\"baliance.com/gooxml/schema/soo/dml\"\n\tcrt \"baliance.com/gooxml/schema/soo/dml/chart\"\n)\n\n\ntype SurfaceChart struct {\n\tchartBase\n\tx *crt.CT_SurfaceChart\n}\n\n\nfunc (c SurfaceChart) X() *crt.CT_SurfaceChart {\n\treturn c.x\n}\n\n\n\n\nfunc (c SurfaceChart) AddSeries() SurfaceChartSeries {\n\tcolor := c.nextColor(len(c.x.Ser))\n\tser := crt.NewCT_SurfaceSer()\n\tc.x.Ser = append(c.x.Ser, ser)\n\tser.Idx.ValAttr = uint32(len(c.x.Ser) - 1)\n\tser.Order.ValAttr = uint32(len(c.x.Ser) - 1)\n\n\tls := SurfaceChartSeries{ser}\n\tls.InitializeDefaults()\n\tls.Properties().LineProperties().SetSolidFill(color)\n\treturn ls\n}\n\n\nfunc (c SurfaceChart) AddAxis(axis Axis) {\n\taxisID := crt.NewCT_UnsignedInt()\n\taxisID.ValAttr = axis.AxisID()\n\tc.x.AxId = append(c.x.AxId, axisID)\n}\n\nfunc (c SurfaceChart) InitializeDefaults() ", "output": "{\n\tc.x.Wireframe = crt.NewCT_Boolean()\n\tc.x.Wireframe.ValAttr = gooxml.Bool(false)\n\n\tc.x.BandFmts = crt.NewCT_BandFmts()\n\tfor i := 0; i < 15; i++ {\n\t\tbfmt := crt.NewCT_BandFmt()\n\t\tbfmt.Idx.ValAttr = uint32(i)\n\t\tbfmt.SpPr = dml.NewCT_ShapeProperties()\n\n\t\tsp := drawing.MakeShapeProperties(bfmt.SpPr)\n\t\tsp.SetSolidFill(c.nextColor(i))\n\t\tc.x.BandFmts.BandFmt = append(c.x.BandFmts.BandFmt, bfmt)\n\t}\n}"} {"input": "package migration\n\nimport \"time\"\n\n\ntype IssueContext interface {\n\tLocalID() int64\n\tForeignID() int64\n}\n\n\ntype BasicIssueContext int64\n\n\n\n\n\nfunc (c BasicIssueContext) ForeignID() int64 {\n\treturn int64(c)\n}\n\n\ntype Issue struct {\n\tNumber int64 `json:\"number\"`\n\tPosterID int64 `yaml:\"poster_id\" json:\"poster_id\"`\n\tPosterName string `yaml:\"poster_name\" json:\"poster_name\"`\n\tPosterEmail string `yaml:\"poster_email\" json:\"poster_email\"`\n\tTitle string `json:\"title\"`\n\tContent string `json:\"content\"`\n\tRef string `json:\"ref\"`\n\tMilestone string `json:\"milestone\"`\n\tState string `json:\"state\"` \n\tIsLocked bool `yaml:\"is_locked\" json:\"is_locked\"`\n\tCreated time.Time `json:\"created\"`\n\tUpdated time.Time `json:\"updated\"`\n\tClosed *time.Time `json:\"closed\"`\n\tLabels []*Label `json:\"labels\"`\n\tReactions []*Reaction `json:\"reactions\"`\n\tAssignees []string `json:\"assignees\"`\n\tContext IssueContext `yaml:\"-\"`\n}\n\n\nfunc (i *Issue) GetExternalName() string { return i.PosterName }\n\n\nfunc (i *Issue) GetExternalID() int64 { return i.PosterID }\n\nfunc (c BasicIssueContext) LocalID() int64 ", "output": "{\n\treturn int64(c)\n}"} {"input": "package util\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tprocCgroup = \"/proc/self/cgroup\"\n\tsysPidsMaxFmt = \"/sys/fs/cgroup/pids%s/pids.max\"\n)\n\n\n\n\n\n\n\nfunc getCgroupPidsFile() (string, error) {\n\tcgroup, err := os.Open(procCgroup)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer cgroup.Close() \n\n\tscanner := bufio.NewScanner(cgroup)\n\tvar slice string\n\tfor scanner.Scan() {\n\t\tparts := strings.SplitN(scanner.Text(), \":\", 3)\n\t\tif parts == nil || len(parts) < 3 {\n\t\t\tcontinue\n\t\t}\n\t\tif parts[1] == \"pids\" {\n\t\t\tslice = parts[2]\n\n\t\t\tbreak\n\t\t}\n\t}\n\tif slice == \"\" {\n\t\treturn \"\", fmt.Errorf(\"could not find a cgroup for 'pids'\")\n\t}\n\n\tpidsMax := fmt.Sprintf(sysPidsMaxFmt, slice)\n\n\treturn pidsMax, nil\n}\n\n\n\n\n\n\n\nfunc SetPIDLimit(limit int) error {\n\tlimitStr := \"max\"\n\tif limit != -1 {\n\t\tlimitStr = fmt.Sprintf(\"%d\", limit)\n\t}\n\n\tpidsMax, err := getCgroupPidsFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(pidsMax)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = f.WriteString(limitStr)\n\tif err != nil {\n\t\tf.Close() \n\n\t\treturn err\n\t}\n\n\treturn f.Close()\n}\n\nfunc GetPIDLimit() (int, error) ", "output": "{\n\tpidsMax, err := getCgroupPidsFile()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tf, err := os.Open(pidsMax) \n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer f.Close() \n\n\tmaxPidsStr, err := bufio.NewReader(f).ReadString('\\n')\n\tif err != nil && !errors.Is(err, io.EOF) {\n\t\treturn 0, err\n\t}\n\tmaxPidsStr = strings.TrimRight(maxPidsStr, \"\\n\")\n\n\tmaxPids := -1\n\tif maxPidsStr != \"max\" {\n\t\tmaxPids, err = strconv.Atoi(maxPidsStr)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\treturn maxPids, nil\n}"} {"input": "package console\n\nimport (\n\t\"fmt\"\n\t\"github.com/serainville/gologger/logger\"\n\t\"time\"\n)\n\nfunc ConsolePrinter(log logger.LogInstance, packageName string, fileName string, lineNumber int, funcName string, time time.Time) {\n\tcolor := getColor(log)\n\tcolor.Set()\n\tfmt.Printf(\"[%s] [%s] [%s::%s::%s] [%d] %s\\n\", log.LogType, time.Format(\"2006-01-02 15:04:05\"), packageName, fileName, funcName, lineNumber, log.Message)\n\tUnset()\n}\n\nfunc ConsoleBasicPrinter(log logger.LogInstance, time time.Time) {\n\tcolor := getColor(log)\n\tcolor.Set()\n\tfmt.Printf(\"[%s] [%s] %s\\n\", log.LogType, time.Format(\"2006-01-02 15:04:05\"), log.Message)\n\tUnset()\n}\n\n\n\nfunc getColor(log logger.LogInstance) *Color ", "output": "{\n\tvar color *Color\n\n\tif log.LoggerInit.Location == \"simple\" {\n\t\tcolor = New(Reset)\n\t\treturn color\n\t}\n\n\tswitch log.LogType {\n\tcase \"LOG\":\n\t\tcolor = New(Reset)\n\t\tbreak\n\tcase \"MSG\":\n\t\tcolor = New(FgBlue)\n\t\tbreak\n\tcase \"INF\":\n\t\tcolor = New(FgGreen)\n\t\tbreak\n\tcase \"WRN\":\n\t\tcolor = New(FgMagenta)\n\t\tbreak\n\tcase \"DBG\":\n\t\tcolor = New(FgYellow)\n\t\tbreak\n\tcase \"ERR\":\n\t\tcolor = New(FgRed)\n\t\tbreak\n\tcase \"RSS\":\n\t\tcolor = New(Reset)\n\t\tbreak\n\tdefault:\n\t\tcolor = New(Reset)\n\t\tbreak\n\t}\n\treturn color\n}"} {"input": "package twofactor\n\nimport (\n\t\"bytes\"\n\t\"encoding/base32\"\n\t\"testing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\ntype TwoFactorSuite struct{}\n\nvar _ = Suite(&TwoFactorSuite{})\n\nfunc (s *TwoFactorSuite) TestInt64ToBytes(c *C) {\n\tints := []int64{10, 200, 3000, 40000, 500000}\n\tintBytes := [][]byte{\n\t\t[]byte{0, 0, 0, 0, 0, 0, 0, 10},\n\t\t[]byte{0, 0, 0, 0, 0, 0, 0, 200},\n\t\t[]byte{0, 0, 0, 0, 0, 0, 11, 184},\n\t\t[]byte{0, 0, 0, 0, 0, 0, 156, 64},\n\t\t[]byte{0, 0, 0, 0, 0, 7, 161, 32},\n\t}\n\tfor i, n := range ints {\n\t\tc.Check(bytes.Compare(Int64ToBytes(n), intBytes[i]), Equals, 0)\n\t}\n}\n\nfunc (s *TwoFactorSuite) TestNewSecret(c *C) {\n\tsecret, _ := NewSecret(0)\n\tc.Check(len(secret), Equals, 16)\n}\n\n\n\nfunc (s *TwoFactorSuite) TestSecretString(c *C) {\n\tstr := \"thisisasecret\"\n\tsecret := Secret(str)\n\tc.Check(secret.String(), Equals, str)\n}\n\nfunc (s *TwoFactorSuite) BenchmarkNewSecret(c *C) {\n\tfor i := 0; i < c.N; i++ {\n\t\tNewSecret(0)\n\t}\n}\n\nfunc (s *TwoFactorSuite) TestSecretBytes(c *C) ", "output": "{\n\tstr := \"thisisasecret\"\n\tstrb, _ := base32.StdEncoding.DecodeString(str)\n\tsecret := Secret(str)\n\tbytes, _ := secret.Bytes()\n\tc.Check(len(bytes), Equals, len(strb))\n\tfor i, b := range bytes {\n\t\tc.Check(b, Equals, strb[i])\n\t}\n}"} {"input": "package sched\n\nimport (\n\t\"encoding/json\"\n\n\t\"bosun.org/cmd/bosun/expr\"\n\telastic \"gopkg.in/olivere/elastic.v5\"\n)\n\n\n\nfunc (c *Context) esQueryAll5(indexRoot expr.ESIndexer, filter expr.ESQuery, sduration, eduration string, size int) interface{} {\n\treq, err := expr.ESBaseQuery5(c.runHistory.Start, indexRoot, filter.Query(expr.ESV5).(elastic.Query), sduration, eduration, size, c.ElasticHost)\n\tif err != nil {\n\t\tc.addError(err)\n\t\treturn nil\n\t}\n\tresults, err := c.runHistory.Backends.ElasticHosts.Query5(req)\n\tif err != nil {\n\t\tc.addError(err)\n\t\treturn nil\n\t}\n\tr := make([]interface{}, len(results.Hits.Hits))\n\tfor i, h := range results.Hits.Hits {\n\t\tvar err error\n\t\terr = json.Unmarshal(*h.Source, &r[i])\n\t\tif err != nil {\n\t\t\tc.addError(err)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn r\n}\n\nfunc (c *Context) esQuery5(indexRoot expr.ESIndexer, filter expr.ESQuery, sduration, eduration string, size int) interface{} ", "output": "{\n\tnewFilter := expr.ScopeES5(c.Group(), filter.Query(expr.ESV5).(elastic.Query))\n\treq, err := expr.ESBaseQuery5(c.runHistory.Start, indexRoot, newFilter, sduration, eduration, size, c.ElasticHost)\n\tif err != nil {\n\t\tc.addError(err)\n\t\treturn nil\n\t}\n\tresults, err := c.runHistory.Backends.ElasticHosts.Query5(req)\n\tif err != nil {\n\t\tc.addError(err)\n\t\treturn nil\n\t}\n\tr := make([]interface{}, len(results.Hits.Hits))\n\tfor i, h := range results.Hits.Hits {\n\t\tvar err error\n\t\terr = json.Unmarshal(*h.Source, &r[i])\n\t\tif err != nil {\n\t\t\tc.addError(err)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn r\n}"} {"input": "package cephalofunc\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestSliceIndex(t *testing.T) {\n\tsource := []string{\"a\", \"b\", \"c\", \"d\", \"e\"}\n\ttest := SliceIndex(len(source), func(i int) bool {\n\t\treturn source[i] == \"b\"\n\t})\n\ttest1 := SliceIndex(len(source), func(i int) bool {\n\t\treturn source[i] == \"j\"\n\t})\n\tif test != 1 {\n\t\tt.Error(\"Proper index not found\")\n\t}\n\tif test1 != -1 {\n\t\tt.Error(\"Improper index found as proper\")\n\t}\n}\n\nfunc TestSliceFilter(t *testing.T) {\n\tsource := []int{1, 2, 3, 4, 5}\n\ttest := SliceFilter(len(source), func(i int) interface{} {\n\t\treturn source[i]\n\t}, func(i int) bool {\n\t\treturn source[i] > 3\n\t})\n\tfmt.Println(\"--Filter--\")\n\tfmt.Println(test)\n\tif len(test) != 2 {\n\t\tt.Error(\"Slice not filtered\")\n\t}\n}\n\nfunc TestSliceMap(t *testing.T) {\n\tsource := []int{1, 2, 3, 4, 5}\n\ttest := SliceMap(len(source), func(i int) interface{} {\n\t\treturn source[i]\n\t}, func(e interface{}) interface{} {\n\t\treturn e.(int) + 1\n\t})\n\tfmt.Println(\"--Map--\")\n\tfmt.Println(test)\n\tif test[0] != 2 {\n\t\tt.Error(\"Source slice not mapped properly\")\n\t}\n}\n\n\n\nfunc TestSliceSpliceish(t *testing.T) ", "output": "{\n\tsource := []int{10, 11, 12, 13, 14}\n\ttest := SliceSpliceish(len(source), func(i int) interface{} {\n\t\treturn source[i]\n\t}, 2, true, 99)\n\tfmt.Println(\"--Splice addition--\")\n\tfmt.Println(test)\n\tif len(test) != 6 {\n\t\tt.Error(\"Element was not inserted in the source\")\n\t}\n\ttest1 := SliceSpliceish(len(source), func(i int) interface{} {\n\t\treturn source[i]\n\t}, 1, false, 0)\n\tfmt.Println(\"--Splice deletion--\")\n\tfmt.Println(test1)\n\tif len(test1) != 4 {\n\t\tt.Error(\"Element was not deleted from the source\")\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/cri-o/cri-o/oci\"\n\t\"golang.org/x/net/context\"\n\tpb \"k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2\"\n)\n\nfunc buildContainerStats(stats *oci.ContainerStats, container *oci.Container) *pb.ContainerStats {\n\treturn &pb.ContainerStats{\n\t\tAttributes: &pb.ContainerAttributes{\n\t\t\tId: container.ID(),\n\t\t\tMetadata: container.Metadata(),\n\t\t\tLabels: container.Labels(),\n\t\t\tAnnotations: container.Annotations(),\n\t\t},\n\t\tCpu: &pb.CpuUsage{\n\t\t\tTimestamp: stats.SystemNano,\n\t\t\tUsageCoreNanoSeconds: &pb.UInt64Value{Value: stats.CPUNano},\n\t\t},\n\t\tMemory: &pb.MemoryUsage{\n\t\t\tTimestamp: stats.SystemNano,\n\t\t\tWorkingSetBytes: &pb.UInt64Value{Value: stats.MemUsage},\n\t\t},\n\t\tWritableLayer: nil,\n\t}\n}\n\n\n\n\n\nfunc (s *Server) ContainerStats(ctx context.Context, req *pb.ContainerStatsRequest) (resp *pb.ContainerStatsResponse, err error) ", "output": "{\n\tconst operation = \"container_stats\"\n\tdefer func() {\n\t\trecordOperation(operation, time.Now())\n\t\trecordError(operation, err)\n\t}()\n\n\tcontainer := s.GetContainer(req.ContainerId)\n\tif container == nil {\n\t\treturn nil, fmt.Errorf(\"invalid container\")\n\t}\n\n\tstats, err := s.Runtime().ContainerStats(container)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &pb.ContainerStatsResponse{Stats: buildContainerStats(stats, container)}, nil\n}"} {"input": "package modelhelper_test\n\nimport (\n\t\"math/rand\"\n\t\"testing\"\n\t\"time\"\n\n\t\"koding/db/models\"\n\t\"koding/db/mongodb/modelhelper\"\n\t\"koding/db/mongodb/modelhelper/modeltesthelper\"\n\n\t\"gopkg.in/mgo.v2/bson\"\n)\n\n\n\nfunc TestCreateAndGetGroup(t *testing.T) {\n\tdb := modeltesthelper.NewMongoDB(t)\n\tdefer db.Close()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tg, err := createGroup()\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\n\tg2, err := modelhelper.GetGroup(g.Slug)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tif g2 == nil {\n\t\tt.Errorf(\"couldnt fetch group by its slug. Got nil, expected: %+v\", g)\n\t}\n\n\tif g2.Id.Hex() != g.Id.Hex() {\n\t\tt.Errorf(\"groups are not same: expected: %+v, got: %+v \", g.Id.Hex(), g2.Id.Hex())\n\t}\n\n\trandomName := bson.NewObjectId().Hex()\n\t_, err = modelhelper.GetGroup(randomName)\n\tif err == nil {\n\t\tt.Errorf(\"we should not be able to find the group\")\n\t}\n}\n\nfunc createGroup() (*models.Group, error) ", "output": "{\n\tg := &models.Group{\n\t\tId: bson.NewObjectId(),\n\t\tBody: bson.NewObjectId().Hex(),\n\t\tTitle: bson.NewObjectId().Hex(),\n\t\tSlug: bson.NewObjectId().Hex(),\n\t\tPrivacy: \"private\",\n\t\tVisibility: \"hidden\",\n\t\tSocialApiChannelId: \"0\",\n\t\tSocialApiAnnouncementChannelId: \"0\",\n\t\tDefaultChannels: []string{\"0\"},\n\t}\n\treturn g, modelhelper.CreateGroup(g)\n}"} {"input": "package page\n\nimport (\n\t\"html/template\"\n\n\t\"github.com/gohugoio/hugo/lazy\"\n)\n\n\n\n\n\n\n\ntype LazyContentProvider struct {\n\tinit *lazy.Init\n\tcp ContentProvider\n}\n\n\n\n\n\n\nfunc (lcp *LazyContentProvider) Reset() {\n\tlcp.init.Reset()\n}\n\nfunc (lcp *LazyContentProvider) Content() (interface{}, error) {\n\tlcp.init.Do()\n\treturn lcp.cp.Content()\n}\n\nfunc (lcp *LazyContentProvider) Plain() string {\n\tlcp.init.Do()\n\treturn lcp.cp.Plain()\n}\n\nfunc (lcp *LazyContentProvider) PlainWords() []string {\n\tlcp.init.Do()\n\treturn lcp.cp.PlainWords()\n}\n\nfunc (lcp *LazyContentProvider) Summary() template.HTML {\n\tlcp.init.Do()\n\treturn lcp.cp.Summary()\n}\n\nfunc (lcp *LazyContentProvider) Truncated() bool {\n\tlcp.init.Do()\n\treturn lcp.cp.Truncated()\n}\n\nfunc (lcp *LazyContentProvider) FuzzyWordCount() int {\n\tlcp.init.Do()\n\treturn lcp.cp.FuzzyWordCount()\n}\n\nfunc (lcp *LazyContentProvider) WordCount() int {\n\tlcp.init.Do()\n\treturn lcp.cp.WordCount()\n}\n\nfunc (lcp *LazyContentProvider) ReadingTime() int {\n\tlcp.init.Do()\n\treturn lcp.cp.ReadingTime()\n}\n\nfunc (lcp *LazyContentProvider) Len() int {\n\tlcp.init.Do()\n\treturn lcp.cp.Len()\n}\n\nfunc NewLazyContentProvider(f func() (ContentProvider, error)) *LazyContentProvider ", "output": "{\n\tlcp := LazyContentProvider{\n\t\tinit: lazy.New(),\n\t\tcp: NopPage,\n\t}\n\tlcp.init.Add(func() (interface{}, error) {\n\t\tcp, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlcp.cp = cp\n\t\treturn nil, nil\n\t})\n\treturn &lcp\n}"} {"input": "package databus\n\nimport \"go-common/library/time\"\n\n\n\n\n\ntype App struct {\n\tID int `gorm:\"column:id\" json:\"id\"`\n\tAppKey string `gorm:\"column:app_key\" json:\"app_key\"`\n\tAppSecret string `gorm:\"column:app_secret\" json:\"app_secret\"`\n\tProject string `gorm:\"column:project\" json:\"cluster\"`\n\tRemark string `gorm:\"column:remark\" json:\"remark\"`\n\tCtime time.Time `gorm:\"column:ctime\" json:\"ctime\"`\n\tMtime time.Time `gorm:\"column:mtime\" json:\"-\"`\n}\n\nfunc (*App) TableName() string ", "output": "{\n\treturn \"app2\"\n}"} {"input": "package schedule\n\nimport (\n\t\"context\"\n\t\"os\"\n)\n\n\n\nfunc (c *Client) GetNextOnCall(context context.Context, request *GetNextOnCallsRequest) (*GetNextOnCallsResult, error) {\n\tresult := &GetNextOnCallsResult{}\n\terr := c.client.Exec(context, request, result)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) ExportOnCallUser(context context.Context, request *ExportOnCallUserRequest) (*os.File, error) {\n\tresult := &exportOncallUserResult{}\n\n\tfile, err := os.Create(request.ExportedFilePath + request.getFileName())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer file.Close()\n\n\terr = c.client.Exec(context, request, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = file.Write(result.FileContent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn file, nil\n}\n\nfunc (c *Client) GetOnCalls(context context.Context, request *GetOnCallsRequest) (*GetOnCallsResult, error) ", "output": "{\n\tresult := &GetOnCallsResult{}\n\terr := c.client.Exec(context, request, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}"} {"input": "package errors\n\nimport (\n\t. \"code.cloudfoundry.org/cli/cf/i18n\"\n)\n\ntype NotAuthorizedError struct {\n}\n\nfunc NewNotAuthorizedError() error {\n\treturn &NotAuthorizedError{}\n}\n\n\n\nfunc (err *NotAuthorizedError) Error() string ", "output": "{\n\treturn T(\"Server error, status code: 403, error code: 10003, message: You are not authorized to perform the requested action\")\n}"} {"input": "package writer\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\nconst (\n\tdefaultFlexibleWriterSize = 64\n)\n\ntype FlexibleWriter struct {\n\t*bytes.Buffer\n\twriter io.Writer\n}\n\n\n\nfunc (this *FlexibleWriter) Flush() (err error) {\n\t_, err = this.Buffer.WriteTo(this.writer)\n\n\treturn\n}\n\nfunc (this *FlexibleWriter) Buffered() int {\n\treturn this.Len()\n}\n\nfunc NewFlexibleWriter(writer io.Writer) *FlexibleWriter ", "output": "{\n\tw := &FlexibleWriter{}\n\tw.writer = writer\n\tbuf := make([]byte, 0, defaultFlexibleWriterSize)\n\tw.Buffer = bytes.NewBuffer(buf)\n\treturn w\n}"} {"input": "package securetemp\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nconst (\n\tsize = DefaultSize\n)\n\n\n\nfunc TestTempFile(t *testing.T) {\n\ttmpFile, cleanupFunc, err := TempDir(size)\n\tif err != nil {\n\t\tt.Fatal(\"failed to create temp file\", err)\n\t}\n\tif _, err := os.Stat(tmpFile); err != nil {\n\t\tt.Fatal(\"something is wrong with the temp file\", err)\n\t}\n\n\tcleanupFunc()\n\tif _, err := os.Stat(tmpFile); err == nil {\n\t\tt.Fatal(\"temp dir should no longer exist after cleanup, but does\", tmpFile)\n\t}\n}\n\nfunc TestTempDir(t *testing.T) ", "output": "{\n\ttmpDir, cleanupFunc, err := TempDir(size)\n\tif err != nil {\n\t\tt.Fatal(\"failed to create temp dir\", err)\n\t}\n\tif _, err := os.Stat(tmpDir); err != nil {\n\t\tt.Fatal(\"something is wrong with the temp dir\", err)\n\t}\n\n\tcleanupFunc()\n\tif _, err := os.Stat(tmpDir); err == nil {\n\t\tt.Fatal(\"temp dir should no longer exist after cleanup, but does\", tmpDir)\n\t}\n}"} {"input": "package log\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n)\n\nvar (\n\tinternalLog *logMux\n\tdebugMode bool\n)\n\n\nfunc init() {\n\tinternalLog = NewMux()\n\tinternalLog.Add(NewSyslogSink())\n\tinternalLog.Add(NewColourisedTerminalSink())\n}\n\n\ntype Sink interface {\n\tInfo(message string)\n\tWarning(message string)\n\tError(message string)\n\tDebug(message string)\n}\n\n\n\n\n\nfunc Warning(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Warning(fileMessage, v...)\n}\n\nfunc Errorf(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Error(fileMessage, v...)\n}\n\nfunc Debug(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Debug(fileMessage, v...)\n}\n\n\nfunc DebugMode(status bool) {\n\tinternalLog.DebugMode(status)\n\tdebugMode = status\n}\n\nfunc Info(message string, v ...interface{}) ", "output": "{\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Info(fileMessage, v...)\n}"} {"input": "package backend\n\nimport (\n\t\"net/http\"\n)\n\nconst (\n\tCONSENT_SAMPLE_PATH = \"/\" + CATEGORY_SAMPLE_TEMPLATES + \"/consent/\"\n)\n\n\n\nfunc submitConsentXHR(w http.ResponseWriter, r *http.Request) {\n\tSendJsonResponse(w, map[string]bool{\n\t\t\"promptIfUnknown\": true,\n\t})\n}\n\nfunc InitAmpConsent() ", "output": "{\n\tRegisterHandler(CONSENT_SAMPLE_PATH+\"getConsent\", onlyPost(submitConsentXHR))\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/utils\"\n\n\n\n\ntype ImportTpFromFolder struct {\n\tname string\n\trpcMethod string\n\trpcParams *utils.AttrImportTPFromFolder\n\trpcResult string\n\t*CommandExecuter\n}\n\nfunc (self *ImportTpFromFolder) Name() string {\n\treturn self.name\n}\n\nfunc (self *ImportTpFromFolder) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *ImportTpFromFolder) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &utils.AttrImportTPFromFolder{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *ImportTpFromFolder) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *ImportTpFromFolder) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc init() ", "output": "{\n\tc := &ImportTpFromFolder{\n\t\tname: \"import_tp_from_folder\",\n\t\trpcMethod: utils.APIerSv1ImportTariffPlanFromFolder,\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}"} {"input": "package tail\n\nimport (\n\t\"github.com/masahide/tail/winfile\"\n\t\"os\"\n)\n\n\n\nfunc OpenFile(name string) (file *os.File, err error) ", "output": "{\n\treturn winfile.OpenFile(name, os.O_RDONLY, 0)\n}"} {"input": "package gziphandler\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"io\"\n\t\"net/http\"\n\t\"strings\"\n)\n\ntype gzipResponseWriter struct {\n\tio.Writer\n\thttp.ResponseWriter\n}\n\nfunc (m *gzipResponseWriter) Write(b []byte) (int, error) {\n\treturn m.Writer.Write(b)\n}\n\n\n\nfunc GzipContent(gzbuff *bytes.Buffer, uncompressedContent []byte) (err error) {\n\tgz := gzip.NewWriter(gzbuff)\n\t_, err = gz.Write(uncompressedContent)\n\tgz.Close() \n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc NewGZipHandler(h http.Handler) http.Handler ", "output": "{\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif !strings.Contains(r.Header.Get(\"Accept-Encoding\"), \"gzip\") {\n\t\t\th.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Encoding\", \"gzip\")\n\t\tgz := gzip.NewWriter(w)\n\t\tdefer gz.Close()\n\t\th.ServeHTTP(&gzipResponseWriter{Writer: gz, ResponseWriter: w}, r)\n\t})\n}"} {"input": "package stats\n\nvar (\n\tNoOpStatsFactory StatsFactory\n)\n\ntype noopCounter struct {\n}\n\nfunc (s noopCounter) Inc() {\n}\n\nfunc (s noopCounter) Add(v float64) {\n}\n\ntype noopGauge struct {\n}\n\nfunc (s noopGauge) Inc() {\n}\n\nfunc (s noopGauge) Add(v float64) {\n}\n\nfunc (s noopGauge) Dec() {\n}\n\nfunc (s noopGauge) Sub(v float64) {\n}\n\nfunc (s noopGauge) Set(v float64) {\n}\n\nfunc (s noopGauge) Get() float64 {\n\treturn 0\n}\n\ntype noopSummary struct {\n}\n\nfunc (s noopSummary) Observe(v float64) {\n}\n\ntype noopStatsFactory struct {\n}\n\nfunc (f noopStatsFactory) NewCounter(\n\tmetric string,\n\ttags map[string]string) CounterStat {\n\n\treturn noopCounter{}\n}\n\nfunc (f noopStatsFactory) NewGauge(\n\tmetric string,\n\ttags map[string]string) GaugeStat {\n\n\treturn noopGauge{}\n}\n\n\n\nfunc init() {\n\tNoOpStatsFactory = noopStatsFactory{}\n}\n\nfunc (f noopStatsFactory) NewSummary(\n\tmetric string,\n\ttags map[string]string) SummaryStat ", "output": "{\n\n\treturn noopSummary{}\n}"} {"input": "package glacier\n\nimport (\n\t\"encoding/hex\"\n\t\"reflect\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/awsutil\"\n)\n\nvar (\n\tdefaultAccountID = \"-\"\n)\n\nfunc init() {\n\tinitRequest = func(r *aws.Request) {\n\t\tr.Handlers.Validate.PushFront(addAccountID)\n\t\tr.Handlers.Validate.PushFront(copyParams) \n\t\tr.Handlers.Build.PushBack(addChecksum)\n\t\tr.Handlers.Build.PushBack(addAPIVersion)\n\t}\n}\n\nfunc copyParams(r *aws.Request) {\n\tr.Params = awsutil.CopyOf(r.Params)\n}\n\nfunc addAccountID(r *aws.Request) {\n\tif !r.ParamsFilled() {\n\t\treturn\n\t}\n\n\tv := reflect.Indirect(reflect.ValueOf(r.Params))\n\tif f := v.FieldByName(\"AccountID\"); f.IsNil() {\n\t\tf.Set(reflect.ValueOf(&defaultAccountID))\n\t}\n}\n\n\n\nfunc addAPIVersion(r *aws.Request) {\n\tr.HTTPRequest.Header.Set(\"X-Amz-Glacier-Version\", r.Service.APIVersion)\n}\n\nfunc addChecksum(r *aws.Request) ", "output": "{\n\tif r.Body == nil {\n\t\treturn\n\t}\n\n\th := ComputeHashes(r.Body)\n\n\tif r.HTTPRequest.Header.Get(\"X-Amz-Content-Sha256\") == \"\" {\n\t\thstr := hex.EncodeToString(h.LinearHash)\n\t\tr.HTTPRequest.Header.Set(\"X-Amz-Content-Sha256\", hstr)\n\t}\n\tif r.HTTPRequest.Header.Get(\"X-Amz-Sha256-Tree-Hash\") == \"\" {\n\t\thstr := hex.EncodeToString(h.TreeHash)\n\t\tr.HTTPRequest.Header.Set(\"X-Amz-Sha256-Tree-Hash\", hstr)\n\t}\n}"} {"input": "package data\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n\n\t\"cloud.google.com/go/spanner/spansql\"\n)\n\n\nvar _ Generator = (*TimestampGenerator)(nil)\n\ntype (\n\tTimestampGenerator struct {\n\t\tsrc rand.Source\n\t\tdelta int64\n\t\tmin int64\n\t\tmax int64\n\t\tr bool\n\t}\n)\n\nfunc NewTimestampGenerator(cfg Config) (Generator, error) {\n\tret := &TimestampGenerator{\n\t\tsrc: cfg.Source(),\n\t}\n\n\tif cfg.Range() {\n\t\tret.r = true\n\n\t\tswitch min := cfg.Minimum().(type) {\n\t\tcase time.Time:\n\t\t\tret.min = min.Unix()\n\t\tcase int64:\n\t\t\tret.min = min\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"minimum '%s' of type '%T' invalid for timestamp generator\", min, min)\n\t\t}\n\n\t\tswitch max := cfg.Maximum().(type) {\n\t\tcase time.Time:\n\t\t\tret.max = max.Unix()\n\t\tcase int64:\n\t\t\tret.max = max\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"maximum '%s' of type '%T' invalid for timestamp generator\", max, max)\n\t\t}\n\t} else {\n\t\tret.min = time.Date(defaultDateMinYear, 1, 0, 0, 0, 0, 0, time.UTC).Unix()\n\t\tret.max = time.Date(defaultDateMaxYear, 1, 0, 0, 0, 0, 0, time.UTC).Unix()\n\t}\n\n\tret.delta = ret.max - ret.min\n\n\treturn ret, nil\n}\n\n\n\nfunc (g *TimestampGenerator) Type() spansql.TypeBase {\n\treturn spansql.Timestamp\n}\n\nfunc (g *TimestampGenerator) Next() interface{} ", "output": "{\n\tsec := rand.Int63n(g.delta) + g.min\n\treturn time.Unix(sec, 0)\n}"} {"input": "package Plugin\n\nimport \"github.com/MPjct/GoMP/MySQLProtocol\"\n\ntype Plugin_interface interface {\n\tinit(context MySQLProtocol.Context)\n\tread_handshake(context MySQLProtocol.Context)\n\tsend_handshake(context MySQLProtocol.Context)\n\tread_auth(context MySQLProtocol.Context)\n\tsend_auth(context MySQLProtocol.Context)\n\tread_auth_result(context MySQLProtocol.Context)\n\tsend_auth_result(context MySQLProtocol.Context)\n\tread_query(context MySQLProtocol.Context)\n\tsend_query(context MySQLProtocol.Context)\n\tread_query_result(context MySQLProtocol.Context)\n\tsend_query_result(context MySQLProtocol.Context)\n\tcleanup(context MySQLProtocol.Context)\n}\n\ntype Plugin struct {\n}\n\nfunc (plugin *Plugin) init(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\n\n\nfunc (plugin *Plugin) cleanup(context MySQLProtocol.Context) ", "output": "{\n\treturn\n}"} {"input": "package log15\n\nimport (\n\t\"sync/atomic\"\n\t\"unsafe\"\n)\n\n\n\ntype swapHandler struct {\n\thandler unsafe.Pointer\n}\n\n\n\nfunc (h *swapHandler) Swap(newHandler Handler) {\n\tatomic.StorePointer(&h.handler, unsafe.Pointer(&newHandler))\n}\n\nfunc (h *swapHandler) Log(r *Record) error ", "output": "{\n\treturn (*(*Handler)(atomic.LoadPointer(&h.handler))).Log(r)\n}"} {"input": "package missinggo\n\nimport \"io\"\n\ntype StatWriter struct {\n\tWritten int64\n\tw io.Writer\n}\n\nfunc (me *StatWriter) Write(b []byte) (n int, err error) {\n\tn, err = me.w.Write(b)\n\tme.Written += int64(n)\n\treturn\n}\n\nfunc NewStatWriter(w io.Writer) *StatWriter {\n\treturn &StatWriter{w: w}\n}\n\nvar ZeroReader zeroReader\n\ntype zeroReader struct{}\n\n\n\nfunc (me zeroReader) Read(b []byte) (n int, err error) ", "output": "{\n\tfor i := range b {\n\t\tb[i] = 0\n\t}\n\tn = len(b)\n\treturn\n}"} {"input": "package serverplan\n\nimport (\n\t\"github.com/sacloud/libsacloud/v2/helper/validate\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\ntype ReadRequest struct {\n\tZone string `request:\"-\" validate:\"required\"`\n\tID types.ID `request:\"-\" validate:\"required\"`\n}\n\n\n\nfunc (req *ReadRequest) Validate() error ", "output": "{\n\treturn validate.Struct(req)\n}"} {"input": "package commands\n\nimport (\n\t\"context\"\n\t\"io\"\n\n\t\"github.com/atotto/clipboard\"\n)\n\n\n\nfunc cmdClip(ctx context.Context, cmd Param) (int, error) ", "output": "{\n\tdata, err := io.ReadAll(cmd.In())\n\tif err != nil {\n\t\treturn 1, err\n\t}\n\tclipboard.WriteAll(string(data))\n\treturn 0, nil\n}"} {"input": "package main ;\nvar m int = 10 ;\nfunc main() { println(fibonacci(m)) ;\n\t} ;\n ;\n\nfunc fibonacci(n int) int ", "output": "{ if n < 2 { return n ;\n\t} ;\n\treturn fibonacci(n - 1) + fibonacci(n - 2) ;\n}"} {"input": "package errors2\n\nimport (\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tlvldbug = iota\n\tlvlinfo\n\tlvlerr\n\tlvlcrit\n)\n\ntype logMessage struct {\n\ttime time.Time\n\tlevel int\n\tmessage string\n}\n\ntype Logger struct {\n\tmessages []*logMessage\n\tTimer Timer\n}\n\nfunc (l *Logger) Debug(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvldbug, message: message})\n}\n\nfunc (l *Logger) Info(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvlinfo, message: message})\n}\n\nfunc (l *Logger) Error(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvlerr, message: message})\n}\n\nfunc (l *Logger) Critical(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvlcrit, message: message})\n}\n\nvar lock = &sync.Mutex{}\n\n\n\nfunc (l *Logger) log(message *logMessage) ", "output": "{\n\tlock.Lock()\n\tl.messages = append(l.messages, message)\n\tlock.Unlock()\n}"} {"input": "package system \n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\nfunc MkdirAllWithACL(path string, perm os.FileMode, sddl string) error {\n\treturn os.MkdirAll(path, perm)\n}\n\n\n\nfunc MkdirAll(path string, perm os.FileMode) error {\n\treturn os.MkdirAll(path, perm)\n}\n\n\nfunc IsAbs(path string) bool {\n\treturn filepath.IsAbs(path)\n}\n\n\n\n\n\n\n\n\n\nfunc CreateSequential(name string) (*os.File, error) {\n\treturn os.Create(name)\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc OpenFileSequential(name string, flag int, perm os.FileMode) (*os.File, error) {\n\treturn os.OpenFile(name, flag, perm)\n}\n\n\n\n\n\n\n\n\n\n\nfunc TempFileSequential(dir, prefix string) (f *os.File, err error) {\n\treturn ioutil.TempFile(dir, prefix)\n}\n\nfunc OpenSequential(name string) (*os.File, error) ", "output": "{\n\treturn os.Open(name)\n}"} {"input": "package via\n\nimport (\n\t\"fmt\"\n\t\"gopkg.in/src-d/go-git.v4\"\n\t\"gopkg.in/src-d/go-git.v4/plumbing\"\n\t\"os\"\n\tgpath \"path\"\n)\n\n\nfunc Clone(dir Path, url string) error {\n\t_, err := git.PlainClone(dir.String(), false, &git.CloneOptions{\n\t\tURL: url,\n\t\tProgress: os.Stdout,\n\t\tDepth: 1,\n\t\tRecurseSubmodules: git.DefaultSubmoduleRecursionDepth,\n\t})\n\treturn err\n}\n\n\n\n\n\nfunc CloneBranch(dir Path, url, branch string) error {\n\t_, err := git.PlainClone(dir.String(), false, &git.CloneOptions{\n\t\tURL: url,\n\t\tProgress: os.Stdout,\n\t\tDepth: 1,\n\t\tReferenceName: gitref(branch),\n\t})\n\treturn err\n}\n\n\n\nfunc Branch(path Path) (string, error) {\n\tr, err := git.PlainOpen(path.String())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\thead, err := r.Head()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn gpath.Base(head.Name().String()), nil\n}\n\nfunc gitref(branch string) plumbing.ReferenceName ", "output": "{\n\treturn plumbing.ReferenceName(\n\t\tfmt.Sprintf(\"refs/heads/%s\", branch),\n\t)\n}"} {"input": "package linode\n\nimport \"errors\"\nimport \"fmt\"\n\n\n\nfunc (client *Client) ListImages(pendingOnly bool) ([]*Image, error) {\n\tparams := make(map[string]string)\n\tif pendingOnly {\n\t\tparams[\"pending\"] = \"1\"\n\t}\n\tvar images []*Image\n\terr := client.request(\"image.list\", params, &images)\n\treturn images, err\n}\n\nfunc (client *Client) GetImage(imageID int) (*Image, error) {\n\tparams := map[string]string{\n\t\t\"ImageID\": fmt.Sprintf(\"%d\", imageID),\n\t}\n\tvar images []*Image\n\terr := client.request(\"image.list\", params, &images)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if len(images) != 1 {\n\t\treturn nil, errors.New(\"expected one image in response\")\n\t} else {\n\t\treturn images[0], nil\n\t}\n}\n\n\n\nfunc (client *Client) DeleteImage(imageID int) error ", "output": "{\n\tparams := map[string]string{\n\t\t\"ImageID\": fmt.Sprintf(\"%d\", imageID),\n\t}\n\treturn client.request(\"image.delete\", params, nil)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"k8s.io/apiserver/pkg/healthz\"\n\t\"k8s.io/kubernetes/cmd/kube-controller-manager/app\"\n\t\"k8s.io/kubernetes/cmd/kube-controller-manager/app/options\"\n\t_ \"k8s.io/kubernetes/pkg/client/metrics/prometheus\" \n\t\"k8s.io/kubernetes/pkg/util/flag\"\n\t\"k8s.io/kubernetes/pkg/util/logs\"\n\t_ \"k8s.io/kubernetes/pkg/util/workqueue/prometheus\" \n\t_ \"k8s.io/kubernetes/pkg/version/prometheus\" \n\t\"k8s.io/kubernetes/pkg/version/verflag\"\n\n\t\"github.com/spf13/pflag\"\n)\n\n\n\nfunc main() {\n\ts := options.NewCMServer()\n\ts.AddFlags(pflag.CommandLine)\n\n\tflag.InitFlags()\n\tlogs.InitLogs()\n\tdefer logs.FlushLogs()\n\n\tverflag.PrintAndExitIfRequested()\n\n\tif err := app.Run(s); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc init() ", "output": "{\n\thealthz.DefaultHealthz()\n}"} {"input": "package leet_10\n\n\n\nfunc equal(a, b byte) bool {\n\treturn a == b || b == '.'\n}\n\nfunc isMatch(s string, p string) bool ", "output": "{\n\tif p == \"\" {\n\t\treturn s == p\n\t}\n\tlenp := len(p)\n\tif lenp == 1 {\n\t\treturn len(s) == 1 && equal(s[0], p[0])\n\t}\n\tif p[1] == '*' {\n\t\tif s == \"\" {\n\t\t\treturn isMatch(\"\", p[2:])\n\t\t}\n\t\treturn isMatch(s, p[2:]) ||\n\t\t\t(equal(s[0], p[0]) && isMatch(s[1:], p))\n\t}\n\tif s == \"\" {\n\t\treturn false\n\t}\n\treturn equal(s[0], p[0]) && isMatch(s[1:], p[1:])\n}"} {"input": "package swag\n\nimport (\n\t\"sort\"\n\t\"sync\"\n)\n\n\n\ntype indexOfInitialisms struct {\n\tgetMutex *sync.Mutex\n\tindex map[string]bool\n}\n\nfunc newIndexOfInitialisms() *indexOfInitialisms {\n\treturn &indexOfInitialisms{\n\t\tgetMutex: new(sync.Mutex),\n\t\tindex: make(map[string]bool, 50),\n\t}\n}\n\nfunc (m *indexOfInitialisms) load(initial map[string]bool) *indexOfInitialisms {\n\tm.getMutex.Lock()\n\tdefer m.getMutex.Unlock()\n\tfor k, v := range initial {\n\t\tm.index[k] = v\n\t}\n\treturn m\n}\n\n\n\nfunc (m *indexOfInitialisms) add(key string) *indexOfInitialisms {\n\tm.getMutex.Lock()\n\tdefer m.getMutex.Unlock()\n\tm.index[key] = true\n\treturn m\n}\n\nfunc (m *indexOfInitialisms) sorted() (result []string) {\n\tm.getMutex.Lock()\n\tdefer m.getMutex.Unlock()\n\tfor k := range m.index {\n\t\tresult = append(result, k)\n\t}\n\tsort.Sort(sort.Reverse(byLength(result)))\n\treturn\n}\n\nfunc (m *indexOfInitialisms) isInitialism(key string) bool ", "output": "{\n\tm.getMutex.Lock()\n\tdefer m.getMutex.Unlock()\n\t_, ok := m.index[key]\n\treturn ok\n}"} {"input": "package plugins\n\nimport (\n\t\"../answers\"\n\t\"../ircclient\"\n\t\"strings\"\n)\n\ntype DongPlugin struct {\n\tic *ircclient.IRCClient\n}\n\nfunc (q *DongPlugin) String() string {\n\treturn \"dong\"\n}\n\nfunc (q *DongPlugin) Info() string {\n\treturn `sends back a dong sound for every \\a`\n}\n\n\n\nfunc (q *DongPlugin) Register(cl *ircclient.IRCClient) {\n\tq.ic = cl\n}\n\nfunc (q *DongPlugin) Unregister() {\n\treturn\n}\n\nfunc (q *DongPlugin) ProcessLine(msg *ircclient.IRCMessage) {\n\tif msg.Command != \"PRIVMSG\" {\n\t\treturn\n\t}\n\n\tcount := strings.Count(msg.Args[0], `\\a`)\n\tcount -= strings.Count(msg.Args[0], `\\\\a`)\n\tif count < 1 {\n\t\treturn\n\t}\n\n\tstr := answers.RandStr(\"dong\")\n\tmessage := \"\"\n\n\tfor i := 0; i < count; i++ {\n\t\tmessage += str + \" \"\n\t}\n\n\tq.ic.ReplyMsg(msg, message)\n}\n\nfunc (q *DongPlugin) ProcessCommand(cmd *ircclient.IRCCommand) {\n\treturn\n}\n\nfunc (q *DongPlugin) Usage(cmd string) string ", "output": "{\n\treturn \"\"\n}"} {"input": "package zip\n\nimport (\n\t\"hash/crc32\"\n\n\t. \"github.com/zxh0/jvm.go/jvmgo/any\"\n\t\"github.com/zxh0/jvm.go/jvmgo/jvm/rtda\"\n\trtc \"github.com/zxh0/jvm.go/jvmgo/jvm/rtda/class\"\n)\n\nfunc init() {\n\t_crc(updateBytes, \"updateBytes\", \"(I[BII)I\")\n}\n\nfunc _crc(method Any, name, desc string) {\n\trtc.RegisterNativeMethod(\"java/util/zip/CRC32\", name, desc, method)\n}\n\n\n\n\n\nfunc updateBytes(frame *rtda.Frame) ", "output": "{\n\tvars := frame.LocalVars()\n\tcrc := uint32(vars.GetInt(0))\n\tbyteArr := vars.GetRef(1)\n\toff := vars.GetInt(2)\n\t_len := vars.GetInt(3)\n\n\tgoBytes := byteArr.GoBytes()\n\tgoBytes = goBytes[off : off+_len]\n\tcrc = crc32.Update(crc, crc32.IEEETable, goBytes)\n\n\tstack := frame.OperandStack()\n\tstack.PushInt(int32(crc))\n}"} {"input": "package b\n\nimport \"a\"\n\nvar N n\n\ntype n struct{}\n\nfunc (r n) M1() int { return a.G1 }\nfunc (r n) M2() int { return a.G2 }\nfunc (r n) M3() int { return a.G3 }\nfunc (r n) M4() int { return a.G4 }\nfunc (r n) M5() int { return a.G5 }\n\nfunc (r n) M7() int { return a.G7 }\nfunc (r n) M8() int { return a.G8 }\nfunc (r n) M9() int { return a.G9 }\nfunc (r n) M10() int { return a.G10 }\n\nfunc (r n) M6() int ", "output": "{ return a.G6 }"} {"input": "package operator\n\nimport (\n\t\"testing\"\n\n\t\"github.com/rook/rook/pkg/operator/test\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\nfunc TestCreateCluster(t *testing.T) {\n\tclientset := test.New(3)\n\to := New(\"foo\", nil, clientset)\n\to.context.RetryDelay = 1\n\n\terr := o.initResources()\n\tassert.NotNil(t, err)\n\n\ttest := &testTPR{}\n\terr = createTPR(o.context, test)\n\tassert.Nil(t, err)\n\ttpr, err := clientset.ExtensionsV1beta1().ThirdPartyResources().List(v1.ListOptions{})\n\tassert.Nil(t, err)\n\tassert.Equal(t, 1, len(tpr.Items))\n\tassert.Equal(t, \"test.rook.io\", tpr.Items[0].Name)\n\tassert.Equal(t, test.Description(), tpr.Items[0].Description)\n\n}\n\ntype testTPR struct {\n}\n\n\nfunc (t *testTPR) Description() string {\n\treturn \"test description\"\n}\nfunc (t *testTPR) Load() error {\n\treturn nil\n}\nfunc (t *testTPR) Watch() error {\n\treturn nil\n}\n\nfunc (t *testTPR) Name() string ", "output": "{\n\treturn \"test\"\n}"} {"input": "package term\n\nimport (\n\t\"github.com/lmorg/murex/lang/stdio\"\n\t\"github.com/lmorg/murex/utils\"\n)\n\n\n\n\ntype Err struct {\n\tterm\n}\n\n\nfunc (t *Err) Write(b []byte) (int, error) {\n\tt.mutex.Lock()\n\tt.bWritten += uint64(len(b))\n\tt.mutex.Unlock()\n\n\tvtermWrite([]rune(string(b)))\n\n\treturn len(b), nil\n}\n\n\nfunc (t *Err) Writeln(b []byte) (int, error) {\n\treturn t.Write(appendBytes(b, utils.NewLineByte...))\n}\n\n\n\n\nfunc (t *Err) WriteArray(dataType string) (stdio.ArrayWriter, error) ", "output": "{\n\treturn stdio.WriteArray(t, dataType)\n}"} {"input": "package gochimp\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype APIError struct {\n\tStatus string `json:\"status\"`\n\tCode int `json:\"code\"`\n\tName string `json:\"name\"`\n\tErr string `json:\"error\"`\n}\n\nfunc (e APIError) Error() string {\n\treturn fmt.Sprintf(\"%v: %v\", e.Code, e.Err)\n}\n\nfunc chimpErrorCheck(body []byte) error {\n\tvar e APIError\n\tjson.Unmarshal(body, &e)\n\tif e.Err != \"\" || e.Code != 0 {\n\t\treturn e\n\t}\n\treturn nil\n}\n\n\ntype APITime struct {\n\ttime.Time\n}\n\n\n\n\nconst APITimeFormat = \"2006-01-02 15:04:05\"\n\nfunc apiTime(t interface{}) interface{} {\n\tswitch ti := t.(type) {\n\tcase time.Time:\n\t\treturn ti.Format(APITimeFormat)\n\tcase string:\n\t\treturn ti\n\t}\n\treturn t\n}\n\nfunc (t *APITime) UnmarshalJSON(data []byte) (err error) ", "output": "{\n\ts := string(data)\n\tl := len(s)\n\tswitch {\n\tcase l == 12:\n\t\tt.Time, err = time.Parse(`\"2006-01-02\"`, s)\n\tcase l == 21:\n\t\tt.Time, err = time.Parse(`\"2006-01-02 15:04:05\"`, s)\n\tcase l == 9:\n\t\tt.Time, err = time.Parse(`\"2006-01\"`, s)\n\t}\n\treturn\n}"} {"input": "package cuda\n\nimport \"github.com/barnex/cuda5/cu\"\n\n\n\n\nfunc fatbinLoad(sm map[int]string, fn string) cu.Function ", "output": "{\n\tbest := 0\n\tfor k, _ := range sm {\n\t\tif k <= cudaCC && k > best {\n\t\t\tbest = k\n\t\t}\n\t}\n\treturn cu.ModuleLoadData(sm[best]).GetFunction(fn)\n}"} {"input": "package state\n\nimport (\n\t\"strconv\"\n\t. \"bugnuts/maps\"\n\t. \"bugnuts/torus\"\n\t. \"bugnuts/util\"\n)\n\nfunc (s *State) FoodLocations() (l []Location) {\n\tfor loc := range s.Food {\n\t\tl = append(l, Location(loc))\n\t}\n\n\treturn l\n}\n\nfunc (s *State) HillLocations(player int) (l []Location) {\n\tfor loc, hill := range s.Hills {\n\t\tif hill.Player == player && hill.Killed == 0 {\n\t\t\tl = append(l, Location(loc))\n\t\t}\n\t}\n\n\treturn l\n}\n\nfunc (s *State) EnemyHillLocations(player int) (l []Location) {\n\tfor loc, hill := range s.Hills {\n\t\tif hill.Player != player && hill.Killed == 0 {\n\t\t\tl = append(l, Location(loc))\n\t\t}\n\t}\n\n\treturn l\n}\n\nfunc (s *State) ValidStep(loc Location) bool {\n\ti := s.Map.Grid[loc]\n\n\treturn i != WATER && i != BLOCK && i != OCCUPIED && i != FOOD && i != MY_ANT && i != MY_HILLANT\n}\n\n\n\nfunc (m *Metrics) DumpSeen() string {\n\tmax := Max(m.Seen)\n\tstr := \"\"\n\n\tfor r := 0; r < m.Rows; r++ {\n\t\tfor c := 0; c < m.Cols; c++ {\n\t\t\tstr += strconv.Itoa(m.Seen[r*m.Cols+c] * 10 / (max + 1))\n\t\t}\n\t\tstr += \"\\n\"\n\t}\n\n\treturn str\n}\n\nfunc (s *State) Stepable(loc Location) bool ", "output": "{\n\ti := s.Map.Grid[loc]\n\n\treturn i != WATER && i != BLOCK && i != FOOD\n}"} {"input": "package cache\n\nimport (\n\t\"context\"\n\n\t\"github.com/GoogleContainerTools/kpt/porch/repository/pkg/repository\"\n)\n\ntype cachedDraft struct {\n\trepository.PackageDraft\n\tcache *cachedRepository\n}\n\nvar _ repository.PackageDraft = &cachedDraft{}\n\n\n\nfunc (cd *cachedDraft) Close(ctx context.Context) (repository.PackageRevision, error) ", "output": "{\n\tif closed, err := cd.PackageDraft.Close(ctx); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tcd.cache.update(closed)\n\t\treturn closed, nil\n\t}\n}"} {"input": "package sflib\n\n\n\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\ntype APIStatusResponse struct {\n\tOK bool `json:\"ok\"`\n\tError string `json:\"error\"`\n}\n\n\n\n\n\ntype APIFailureError struct {\n\ts string\n}\n\nfunc (afe APIFailureError) Error() string {\n\treturn fmt.Sprintf(\"api returned error: %s\", afe.s)\n}\n\n\ntype Stock struct {\n\tVenue string `json:\"venue\"`\n\tSymbol string `json:\"symbol\"`\n}\n\n\n\ntype Bid struct {\n\tPrice int `json:\"price\"`\n\tQuantity int `json:\"qty\"`\n\tIsBuy bool `json:\"isBuy\"`\n}\n\nfunc (asr *APIStatusResponse) CheckAPIStatus() error ", "output": "{\n\tif (asr.OK != true) || (asr.Error != \"\") {\n\t\treturn APIFailureError{asr.Error}\n\t}\n\treturn nil\n}"} {"input": "package config\n\nimport (\n\t\"os\"\n)\n\ntype config struct {\n\tBasePath string\n\tDestPath string\n}\n\nvar current = config{}\n\n\nfunc GetBasePath() string {\n\treturn current.BasePath\n}\n\n\nfunc GetDestPath() string {\n\treturn current.DestPath\n}\n\n\n\nfunc init() ", "output": "{\n\tcurrent.BasePath = \"./\"\n\tif len(os.Args) > 1 {\n\t\tcurrent.BasePath = os.Args[1]\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"github.com/ghodss/yaml\"\n)\n\n\n\nfunc saveState(path string, config *Config) error {\n\tevents := *config.Thermostat.Events\n\tconfig.Thermostat.Events = nil\n\n\tdat, err := yaml.Marshal(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfig.Thermostat.Events = &events\n\n\treturn ioutil.WriteFile(path, dat, os.FileMode(int(0660)))\n}\n\nfunc readState(path string) (*Config, error) ", "output": "{\n\tdat, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := new(Config)\n\terr = yaml.Unmarshal(dat, config)\n\treturn config, err\n}"} {"input": "package buildah\n\nimport (\n\t\"github.com/opencontainers/runtime-tools/generate\"\n\tselinux \"github.com/opencontainers/selinux/go-selinux\"\n)\n\n\n\nfunc setupSelinux(g *generate.Generator, processLabel, mountLabel string) ", "output": "{\n\tif processLabel != \"\" && selinux.GetEnabled() {\n\t\tg.SetProcessSelinuxLabel(processLabel)\n\t\tg.SetLinuxMountLabel(mountLabel)\n\t}\n}"} {"input": "package block\n\nimport (\n\t\"github.com/juju/cmd/v3\"\n\t\"github.com/juju/juju/jujuclient\"\n\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/cmd/modelcmd\"\n)\n\n\n\nfunc NewDisableCommandForTest(store jujuclient.ClientStore, api blockClientAPI, err error) cmd.Command {\n\tcmd := &disableCommand{\n\t\tapiFunc: func(_ newAPIRoot) (blockClientAPI, error) {\n\t\t\treturn api, err\n\t\t},\n\t}\n\tcmd.SetClientStore(store)\n\treturn modelcmd.Wrap(cmd)\n}\n\n\n\nfunc NewEnableCommandForTest(store jujuclient.ClientStore, api unblockClientAPI, err error) cmd.Command {\n\tcmd := &enableCommand{\n\t\tapiFunc: func(_ newAPIRoot) (unblockClientAPI, error) {\n\t\t\treturn api, err\n\t\t},\n\t}\n\tcmd.SetClientStore(store)\n\treturn modelcmd.Wrap(cmd)\n}\n\ntype listMockAPI interface {\n\tblockListAPI\n\tListBlockedModels() ([]params.ModelBlockInfo, error)\n}\n\n\n\n\n\nfunc NewListCommandForTest(store jujuclient.ClientStore, api listMockAPI, err error) cmd.Command ", "output": "{\n\tcmd := &listCommand{\n\t\tapiFunc: func(_ newAPIRoot) (blockListAPI, error) {\n\t\t\treturn api, err\n\t\t},\n\t\tcontrollerAPIFunc: func(_ newControllerAPIRoot) (controllerListAPI, error) {\n\t\t\treturn api, err\n\t\t},\n\t}\n\tcmd.SetClientStore(store)\n\treturn modelcmd.Wrap(cmd)\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestServe(t *testing.T) {\n\tserver := httptest.NewServer(SetupHandler())\n\tdefer server.Close()\n\n\ttestPostMessage(t, server.URL+\"/drawer1/messages/new\", \"john\", \"testmsg1\")\n\ttestPostMessage(t, server.URL+\"/drawer2/messages/new\", \"smith\", \"testmsg2\")\n\ttestPostMessage(t, server.URL+\"/messages/new\", \"admin\", \"broadcast\")\n\n\tjsonMessages := testGetMessages(t, server.URL+\"/drawer1/messages\")\n\tif !strings.Contains(jsonMessages, \"testmsg1\") {\n\t\tt.Errorf(\"Drower1 must has %s, but does not.\", \"testmsg1\")\n\t}\n\tif !strings.Contains(jsonMessages, \"broadcast\") {\n\t\tt.Errorf(\"Drower1 must has %s, but does not.\", \"broadcast\")\n\t}\n}\n\n\n\nfunc testGetMessages(t *testing.T, requestURL string) string {\n\tres, err := http.Get(requestURL)\n\tif err != nil {\n\t\tt.Fatalf(\"Error occured: %s\", err)\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != http.StatusOK {\n\t\tt.Logf(\"URL[%s]\", requestURL)\n\t\tt.Errorf(\"res.StatusCode => %d, want %d\", res.StatusCode, http.StatusOK)\n\t}\n\n\tresMsg, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tt.Fatalf(\"Responce read error occured: %s\", err)\n\t}\n\n\treturn string(resMsg)\n}\n\nfunc testPostMessage(t *testing.T, requestURL, from, body string) ", "output": "{\n\tpostValues := url.Values{\n\t\t\"from\": {from},\n\t\t\"body\": {body},\n\t}\n\tres, err := http.PostForm(requestURL, postValues)\n\tif err != nil {\n\t\tt.Fatalf(\"Error occured: %s\", err)\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != http.StatusOK {\n\t\tt.Logf(\"URL[%s]\", requestURL)\n\t\tt.Logf(\"Parameter:from[%s], body[%s]\", from, body)\n\t\tt.Errorf(\"res.StatusCode => %d, want %d\", res.StatusCode, http.StatusOK)\n\t}\n}"} {"input": "package cloudcontroller\n\nimport (\n\t\"code.cloudfoundry.org/cli/api/cloudcontroller/ccerror\"\n\t\"github.com/blang/semver\"\n)\n\n\n\n\n\nfunc MinimumAPIVersionCheck(current string, minimum string) error ", "output": "{\n\tif minimum == \"\" {\n\t\treturn nil\n\t}\n\n\tcurrentSemvar, err := semver.Make(current)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tminimumSemvar, err := semver.Make(minimum)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif currentSemvar.Compare(minimumSemvar) == -1 {\n\t\treturn ccerror.MinimumAPIVersionNotMetError{\n\t\t\tCurrentVersion: current,\n\t\t\tMinimumVersion: minimum,\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package websql\n\nimport (\n\t\"io\"\n)\n\ntype LimitedReadCloser struct {\n\tio.ReadCloser\n\tN int64\n}\n\n\n\nfunc (l *LimitedReadCloser) Read(p []byte) (n int, err error) ", "output": "{\n\tif l.N <= 0 {\n\t\treturn 0, io.EOF\n\t}\n\tif int64(len(p)) > l.N {\n\t\tp = p[0:l.N]\n\t}\n\tn, err = l.ReadCloser.Read(p)\n\tl.N -= int64(n)\n\treturn\n}"} {"input": "package logger\n\n\n\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"strings\"\n)\n\ntype (\n\tLog struct {\n\t\tlogger *log.Logger\n\t\tpositiveList map[string]bool\n\t\tprintAll bool\n\t\tcolor string\n\t}\n)\n\n\nfunc New(w io.Writer, color string, packages string) *Log {\n\tl := &Log{\n\t\tcolor: color,\n\t\tlogger: log.New(w, \"\", log.Ldate|log.Lmicroseconds),\n\t\tpositiveList: make(map[string]bool),\n\t\tprintAll: false,\n\t}\n\n\tpositives := strings.Split(packages, \",\")\n\tfor _, positive := range positives {\n\t\tif positive == \"*\" {\n\t\t\tl.printAll = true\n\t\t} else {\n\t\t\tl.positiveList[positive] = true\n\t\t}\n\t}\n\n\treturn l\n}\n\n\nfunc (l *Log) Log(pkg string, format string, args ...interface{}) {\n\t_, print := l.positiveList[pkg]\n\tif print || l.printAll {\n\t\tl.Printf(pkg, l.color+format+Reset, args...)\n\t}\n}\n\n\nfunc (l *Log) Logger(pkg string) *log.Logger {\n\t_, print := l.positiveList[pkg]\n\tif print || l.printAll {\n\t\treturn log.New(l, Purple+pkg+\" \"+l.color, 0)\n\t}\n\n\treturn log.New(ioutil.Discard, \"\", 0)\n}\n\n\nfunc (l *Log) Printf(pkg string, format string, args ...interface{}) {\n\tl.logger.Printf(Purple+pkg+Reset+\" \"+format+\"\\n\", args...)\n}\n\n\n\n\nfunc (l *Log) Write(p []byte) (n int, err error) ", "output": "{\n\tstr := strings.TrimSpace(string(p))\n\n\tl.logger.Printf(\"%s\"+Reset+\"\\n\", str)\n\n\treturn len(p), nil\n}"} {"input": "package gash\n\n\n\n\n\ntype CuckooHash struct {\n\titems []*KvPair\n\tcapacity int\n\tfn1 HashFn\n\tfn2 HashFn\n}\n\nfunc CreateCuckooHash(capacity int, fn1 HashFn, fn2 HashFn) CuckooHash {\n\ttable := CuckooHash{}\n\ttable.capacity = capacity\n\ttable.items = make([]*KvPair, capacity)\n\ttable.fn1 = fn1\n\ttable.fn2 = fn2\n\treturn table\n}\n\nfunc (table CuckooHash) Insert(k string, v interface{}) {\n\tindex := table.fn1(k) % table.capacity\n\tswapItem := table.items[index]\n\tinsertItem := KvPair{k, v}\n\ttable.items[index] = &insertItem\n\toldIndex := index\n\n\titem := swapItem\n\tfor item != nil {\n\t\tindex = table.fn1(swapItem.Key) % table.capacity\n\t\tif index == oldIndex {\n\t\t\tindex = table.fn2(swapItem.Key) % table.capacity\n\t\t}\n\n\t\tswapItem = table.items[index]\n\t\tif swapItem != nil && swapItem.Key == k {\n\n\t\t\treturn\n\t\t}\n\t\ttable.items[index] = item\n\t\titem = swapItem\n\t}\n}\n\nfunc (table CuckooHash) Find(k string) interface{} {\n\tvar pair *KvPair\n\n\tindex1 := table.fn1(k) % table.capacity\n\tindex2 := table.fn2(k) % table.capacity\n\n\tpair1 := table.items[index1]\n\tpair2 := table.items[index2]\n\n\tif pair1 != nil && pair1.Key == k {\n\t\tpair = pair1\n\t} else if pair2 != nil && pair2.Key == k {\n\t\tpair = pair2\n\t}\n\n\treturn pair.Value\n}\n\n\n\nfunc (table CuckooHash) Remove(k string) ", "output": "{\n\tindex1 := table.fn1(k) % table.capacity\n\tindex2 := table.fn2(k) % table.capacity\n\n\tpair1 := table.items[index1]\n\tpair2 := table.items[index2]\n\n\tif pair1 != nil && pair1.Key == k {\n\t\ttable.items[index1] = nil\n\t} else if pair2 != nil && pair2.Key == k {\n\t\ttable.items[index2] = nil\n\t}\n}"} {"input": "package client\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\tkapi \"k8s.io/kubernetes/pkg/api\"\n\n\tquotaapi \"github.com/openshift/origin/pkg/quota/api\"\n)\n\n\ntype AppliedClusterResourceQuotasNamespacer interface {\n\tAppliedClusterResourceQuotas(namespace string) AppliedClusterResourceQuotaInterface\n}\n\n\ntype AppliedClusterResourceQuotaInterface interface {\n\tList(opts metav1.ListOptions) (*quotaapi.AppliedClusterResourceQuotaList, error)\n\tGet(name string, options metav1.GetOptions) (*quotaapi.AppliedClusterResourceQuota, error)\n}\n\n\ntype appliedClusterResourceQuotas struct {\n\tr *Client\n\tns string\n}\n\n\n\n\n\nfunc (c *appliedClusterResourceQuotas) List(opts metav1.ListOptions) (result *quotaapi.AppliedClusterResourceQuotaList, err error) {\n\tresult = "aapi.AppliedClusterResourceQuotaList{}\n\terr = c.r.Get().Namespace(c.ns).Resource(\"appliedclusterresourcequotas\").VersionedParams(&opts, kapi.ParameterCodec).Do().Into(result)\n\treturn\n}\n\n\nfunc (c *appliedClusterResourceQuotas) Get(name string, options metav1.GetOptions) (result *quotaapi.AppliedClusterResourceQuota, err error) {\n\tresult = "aapi.AppliedClusterResourceQuota{}\n\terr = c.r.Get().Namespace(c.ns).Resource(\"appliedclusterresourcequotas\").Name(name).VersionedParams(&options, kapi.ParameterCodec).Do().Into(result)\n\treturn\n}\n\nfunc newAppliedClusterResourceQuotas(c *Client, namespace string) *appliedClusterResourceQuotas ", "output": "{\n\treturn &appliedClusterResourceQuotas{\n\t\tr: c,\n\t\tns: namespace,\n\t}\n}"} {"input": "package services\n\nimport (\n \"github.com/nlopes/slack\"\n \"fmt\"\n)\n\ntype slackService struct {\n token string\n channel string\n channelId string\n serviceName string\n api *slack.Client\n rtm *slack.RTM\n userCache map[string]*slack.User\n sent map[string]bool\n}\n\nfunc NewSlack(token, channel, channelId string) slackService {\n api := slack.New(token)\n rtm := api.NewRTM()\n go rtm.ManageConnection()\n cache := make(map[string]*slack.User)\n return slackService{token, channel, channelId, \"slack\", api, rtm, cache, make(map[string]bool)}\n}\n\nfunc (sl slackService) ExposePortal() Portal {\n in := make(chan PortalMessage)\n out := make(chan PortalMessage)\n go func() {\n for {\n select {\n case msg := <-sl.rtm.IncomingEvents:\n sending := sl.triggerMessages(msg, sl.channelId)\n if sending.Kind == PORTAL_MESSAGE {\n out <- sending\n }\n case msg := <-in:\n sl.listenToMessages(msg)\n }\n }\n }()\n return Portal{in, out}\n}\n\nfunc (sl slackService) listenToMessages(msg PortalMessage) {\n if (msg.Kind == PORTAL_MESSAGE) {\n params := slack.PostMessageParameters{}\n params.Username = msg.Author\n _, time, err := sl.api.PostMessage(sl.channel, msg.Data, params)\n if err != nil {\n fmt.Println(err)\n }\n sl.sent[time] = true\n }\n}\n\n\n\nfunc (sl slackService) triggerMessages(msg slack.RTMEvent, channel string) PortalMessage ", "output": "{\n switch ev := msg.Data.(type) {\n case *slack.MessageEvent:\n _, hasMessage := sl.sent[ev.Timestamp]\n if channel == ev.Channel && !hasMessage {\n user, ok := sl.userCache[ev.User]\n if !ok {\n info, err := sl.api.GetUserInfo(ev.User)\n if err != nil {\n fmt.Println(err)\n }\n sl.userCache[ev.User] = info\n user = info\n }\n return PortalMessage{ev.Text, user.Name, sl.serviceName, PORTAL_MESSAGE}\n }\n }\n return PortalMessage{\"\", \"\", \"\", PORTAL_NOOP}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype LockeAble struct {\n\tsync.Mutex\n\treadableInt int\n\treadableString string\n}\n\nfunc main() {\n\tl := &LockeAble{}\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(time.Second * 15)\n\t\t\tl.read(\"one\")\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(time.Second * 10)\n\t\t\tl.write(\"two\", \"hello\", 5)\n\t\t}\n\t}()\n\n\tl.Lock()\n\tl.Unlock()\n\tl.read(\"one\")\n\n\tselect {}\n}\n\n\n\nfunc (l *LockeAble) write(st string, val string, valInt int) {\n\tl.Lock()\n\tfmt.Println(\"just Locked by\", st, \"for writing\")\n\tl.readableString = val\n\tl.readableInt = valInt\n\tl.Unlock()\n\tfmt.Println(\"just UnLocked\", st, \"from writing\")\n}\n\nfunc (l *LockeAble) read(st string) ", "output": "{\n\tl.Lock()\n\tfmt.Println(\"just Locked by\", st, \"for reading\")\n\tfmt.Println(l.readableInt, l.readableString)\n\tl.Unlock()\n\tfmt.Println(\"just UnLocked\", st, \"from reading\")\n}"} {"input": "package animation\n\nimport (\n\t\"time\"\n)\n\ntype GroupedAnimation struct {\n\tanimators []Animator\n\tcallback AnimatorCallback\n}\n\nfunc NewGroupedAnimation(animators []Animator) *GroupedAnimation {\n\treturn &GroupedAnimation{animators, nil}\n}\n\nfunc (a *GroupedAnimation) SetCallback(callback AnimatorCallback) {\n\ta.callback = callback\n}\n\nfunc (a *GroupedAnimation) IsDone() bool {\n\tvar done = true\n\tfor _, animator := range a.animators {\n\t\tif !animator.IsDone() {\n\t\t\tdone = false\n\t\t}\n\t}\n\treturn done\n}\n\n\n\nfunc (a *GroupedAnimation) Reset() {\n\tfor _, animator := range a.animators {\n\t\tanimator.Reset()\n\t}\n}\n\nfunc (a *GroupedAnimation) Delete() {\n\tfor _, animator := range a.animators {\n\t\tanimator.Delete()\n\t}\n\ta.animators = []Animator{}\n}\n\nfunc (a *GroupedAnimation) Update(elapsed time.Duration) time.Duration ", "output": "{\n\tvar (\n\t\ttotal time.Duration\n\t\tremainder time.Duration\n\t\tdone = true\n\t)\n\tfor _, animator := range a.animators {\n\t\tremainder = animator.Update(elapsed)\n\t\tif !animator.IsDone() {\n\t\t\tdone = false\n\t\t}\n\t\tif remainder != 0 && (total == 0 || remainder < total) {\n\t\t\ttotal = remainder \n\t\t}\n\t}\n\tif done {\n\t\tif a.callback != nil {\n\t\t\ta.callback()\n\t\t}\n\t\treturn total\n\t}\n\treturn 0\n}"} {"input": "package token\n\nimport (\n\t\"strings\"\n\n\t\"github.com/carlcui/expressive/locator\"\n)\n\n\ntype Token struct {\n\tTokenType Type\n\tRaw string\n\tLocator locator.Locator\n}\n\nfunc (tok *Token) String() string {\n\treturn tok.TokenType.String() + \": \" + tok.Raw\n}\n\n\n\n\nfunc IllegalToken(raw string, locator locator.Locator) *Token {\n\treturn &Token{TokenType: ILLEGAL, Raw: raw, Locator: locator}\n}\n\n\nfunc EOFToken(locator locator.Locator) *Token {\n\treturn &Token{TokenType: EOF, Raw: \"\", Locator: locator}\n}\n\n\n\nfunc MatchKeyword(reading string) *Token {\n\tif tokenType, isKeyword := keywords[reading]; isKeyword {\n\t\treturn &Token{TokenType: tokenType, Raw: reading}\n\t}\n\n\treturn nil\n}\n\nfunc MatchOperator(reading string) *Token {\n\tif tokenType, isOperator := operators[reading]; isOperator {\n\t\treturn &Token{TokenType: tokenType, Raw: reading}\n\t}\n\n\treturn nil\n}\n\nfunc HasOperatorPrefix(reading string) bool {\n\tfor i := operatorStart + 1; i < operatorEnd; i++ {\n\t\tif strings.HasPrefix(tokens[i], reading) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (tok *Token) GetLocation() string ", "output": "{\n\tif tok.Locator == nil {\n\t\treturn \"unknown location\"\n\t}\n\n\treturn tok.Locator.Locate()\n}"} {"input": "package seccomp\n\nimport (\n\tseccomp_compiler \"github.com/snapcore/snapd/sandbox/seccomp\"\n)\n\n\n\n\n\nfunc MockTemplate(fakeTemplate []byte) (restore func()) {\n\torig := defaultTemplate\n\torigBarePrivDropSyscalls := barePrivDropSyscalls\n\tdefaultTemplate = fakeTemplate\n\tbarePrivDropSyscalls = \"\"\n\treturn func() {\n\t\tdefaultTemplate = orig\n\t\tbarePrivDropSyscalls = origBarePrivDropSyscalls\n\t}\n}\n\nfunc MockKernelFeatures(f func() []string) (resture func()) {\n\told := kernelFeatures\n\tkernelFeatures = f\n\treturn func() {\n\t\tkernelFeatures = old\n\t}\n}\n\n\n\nfunc MockDpkgKernelArchitecture(f func() string) (restore func()) {\n\told := dpkgKernelArchitecture\n\tdpkgKernelArchitecture = f\n\treturn func() {\n\t\tdpkgKernelArchitecture = old\n\t}\n}\n\nfunc MockReleaseInfoId(s string) (restore func()) {\n\told := releaseInfoId\n\treleaseInfoId = s\n\treturn func() {\n\t\treleaseInfoId = old\n\t}\n}\n\nfunc MockReleaseInfoVersionId(s string) (restore func()) {\n\told := releaseInfoVersionId\n\treleaseInfoVersionId = s\n\treturn func() {\n\t\treleaseInfoVersionId = old\n\t}\n}\n\nfunc MockSeccompCompilerLookup(f func(string) (string, error)) (restore func()) {\n\told := seccompCompilerLookup\n\tseccompCompilerLookup = f\n\treturn func() {\n\t\tseccompCompilerLookup = old\n\t}\n}\n\nfunc (b *Backend) VersionInfo() seccomp_compiler.VersionInfo {\n\treturn b.versionInfo\n}\n\nvar (\n\tRequiresSocketcall = requiresSocketcall\n\n\tGlobalProfileLE = globalProfileLE\n\tGlobalProfileBE = globalProfileBE\n\tIsBigEndian = isBigEndian\n)\n\nfunc MockRequiresSocketcall(f func(string) bool) (restore func()) ", "output": "{\n\told := requiresSocketcall\n\trequiresSocketcall = f\n\treturn func() {\n\t\trequiresSocketcall = old\n\t}\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype OpenpitrixRoleResource struct {\n\n\tCPU int64 `json:\"cpu,omitempty\"`\n\n\tGpu int64 `json:\"gpu,omitempty\"`\n\n\tInstanceSize int64 `json:\"instance_size,omitempty\"`\n\n\tMemory int64 `json:\"memory,omitempty\"`\n\n\tRole string `json:\"role,omitempty\"`\n\n\tStorageSize int64 `json:\"storage_size,omitempty\"`\n}\n\n\nfunc (m *OpenpitrixRoleResource) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (m *OpenpitrixRoleResource) UnmarshalBinary(b []byte) error {\n\tvar res OpenpitrixRoleResource\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *OpenpitrixRoleResource) MarshalBinary() ([]byte, error) ", "output": "{\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}"} {"input": "package udp\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestUdpPacket(t *testing.T) ", "output": "{\n\tassert := assert.New(t)\n\n\tbuf := []byte(\"hello world\")\n\tudpMsg := NewUDPPacket(buf, nil, nil)\n\n\tnewBuf, err := GetContent(udpMsg)\n\tassert.NoError(err)\n\tassert.EqualValues(buf, newBuf)\n}"} {"input": "package kafka\n\nimport (\n\t\"encoding/binary\"\n\t\"hash/crc32\"\n)\n\ntype crc32Writer struct {\n\ttable *crc32.Table\n\tbuffer [8]byte\n\tcrc32 uint32\n}\n\nfunc (w *crc32Writer) update(b []byte) {\n\tw.crc32 = crc32.Update(w.crc32, w.table, b)\n}\n\nfunc (w *crc32Writer) writeInt8(i int8) {\n\tw.buffer[0] = byte(i)\n\tw.update(w.buffer[:1])\n}\n\nfunc (w *crc32Writer) writeInt16(i int16) {\n\tbinary.BigEndian.PutUint16(w.buffer[:2], uint16(i))\n\tw.update(w.buffer[:2])\n}\n\nfunc (w *crc32Writer) writeInt32(i int32) {\n\tbinary.BigEndian.PutUint32(w.buffer[:4], uint32(i))\n\tw.update(w.buffer[:4])\n}\n\nfunc (w *crc32Writer) writeInt64(i int64) {\n\tbinary.BigEndian.PutUint64(w.buffer[:8], uint64(i))\n\tw.update(w.buffer[:8])\n}\n\n\n\nfunc (w *crc32Writer) Write(b []byte) (int, error) {\n\tw.update(b)\n\treturn len(b), nil\n}\n\nfunc (w *crc32Writer) WriteString(s string) (int, error) {\n\tw.update([]byte(s))\n\treturn len(s), nil\n}\n\nfunc (w *crc32Writer) writeBytes(b []byte) ", "output": "{\n\tn := len(b)\n\tif b == nil {\n\t\tn = -1\n\t}\n\tw.writeInt32(int32(n))\n\tw.update(b)\n}"} {"input": "package core\n\nimport (\n\t\"os\";\n\t\"container/list\";\n\t\"net\";\n\t\"log\";\n\t\"irc\";\n\t\"runloop\";\n)\n\ntype Network struct {\n\tname\t\tstring;\n\tserver\t\t*server;\n\tclients\t\t*list.List;\n\tlisten\t\t*listenConn;\n}\n\nfunc newNetwork(name string, serverConn net.Conn, listen net.Listener) *Network {\n\tvar network *Network;\n\n\taccept := func(conn net.Conn) {\n\t\trunloop.CallLater(func() {\n\t\t\tnetwork.addClient(conn)\n\t\t})\n\t};\n\n\terror := func(err os.Error) {\n\t};\n\n\tl := newListenConn(listen, accept, error);\n\tnetwork = &Network{name: name, clients: list.New(), listen: l};\n\tnetwork.server = newServer(serverConn, network);\n\treturn network;\n}\n\nfunc (network *Network) addClient(conn net.Conn) {\n\tclient := newClient(conn, network);\n\tnetwork.clients.PushBack(client);\n\tlog.Stderrf(\"client connected from %s\\n\", conn.RemoteAddr());\n}\n\n\n\nfunc (network *Network) SendToServer(msg *irc.Message) {\n\tif network.server != nil {\n\t\tnetwork.server.Send(msg)\n\t}\n}\n\n\nfunc (network *Network) SendToClients(msg *irc.Message) {\n\tfor c := range network.clients.Iter() {\n\t\tc.(*client).Send(msg)\n\t}\n}\n\n\nfunc (network *Network) SendNoticeToClient(conn Conn, line string) {\n\tnick := \"bouncin\"; \n\tconn.Send(&irc.Message{Command: \"NOTICE\", Params: []string{nick, line}});\n}\n\nvar networks = make(map[string] *Network);\n\n\n\nfunc AddNetwork(name string, server net.Conn, listen net.Listener) *Network ", "output": "{\n\tnetwork := newNetwork(name, server, listen);\n\tnetworks[name] = network;\n\treturn network;\n}"} {"input": "package codelocation\n\nimport (\n\t\"regexp\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"strings\"\n\n\t\"github.com/mysza/go-service-template/Godeps/_workspace/src/github.com/onsi/ginkgo/types\"\n)\n\nfunc New(skip int) types.CodeLocation {\n\t_, file, line, _ := runtime.Caller(skip + 1)\n\tstackTrace := PruneStack(string(debug.Stack()), skip)\n\treturn types.CodeLocation{FileName: file, LineNumber: line, FullStackTrace: stackTrace}\n}\n\n\n\nfunc PruneStack(fullStackTrace string, skip int) string ", "output": "{\n\tstack := strings.Split(fullStackTrace, \"\\n\")\n\tif len(stack) > 2*(skip+1) {\n\t\tstack = stack[2*(skip+1):]\n\t}\n\tprunedStack := []string{}\n\tre := regexp.MustCompile(`\\/ginkgo\\/|\\/pkg\\/testing\\/|\\/pkg\\/runtime\\/`)\n\tfor i := 0; i < len(stack)/2; i++ {\n\t\tif !re.Match([]byte(stack[i*2])) {\n\t\t\tprunedStack = append(prunedStack, stack[i*2])\n\t\t\tprunedStack = append(prunedStack, stack[i*2+1])\n\t\t}\n\t}\n\treturn strings.Join(prunedStack, \"\\n\")\n}"} {"input": "package errors\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\n\t\"github.com/openshift/origin/pkg/cmd/errors\"\n)\n\nconst (\n\tKubeConfigFileSolutionWindows = `\nMake sure that the value of the --config flag passed contains a valid path:\n --config=c:\\path\\to\\valid\\file\n`\n\tKubeConfigFileSolutionUnix = `\nMake sure that the value of the --config flag passed contains a valid path:\n --config=/path/to/valid/file\n`\n\tKubeConfigSolutionUnix = `\nYou can unset the KUBECONFIG variable to use the default location for it:\n unset KUBECONFIG\n\nOr you can set its value to a file that can be written to:\n export KUBECONFIG=/path/to/file\n`\n\n\tKubeConfigSolutionWindows = `\nYou can clear the KUBECONFIG variable to use the default location for it:\n set KUBECONFIG=\n\nOr you can set its value to a file that can be written to:\n set KUBECONFIG=c:\\path\\to\\file`\n)\n\n\n\nfunc ErrKubeConfigNotWriteable(file string, isExplicitFile bool, err error) error {\n\treturn errors.NewError(\"KUBECONFIG is set to a file that cannot be created or modified: %s\", file).WithCause(err).WithSolution(kubeConfigSolution(isExplicitFile))\n}\n\nfunc kubeConfigSolution(isExplicitFile bool) string {\n\tswitch runtime.GOOS {\n\tcase \"windows\":\n\t\tif isExplicitFile {\n\t\t\treturn KubeConfigFileSolutionWindows\n\t\t}\n\t\treturn KubeConfigSolutionWindows\n\tdefault:\n\t\tif isExplicitFile {\n\t\t\treturn KubeConfigFileSolutionUnix\n\t\t}\n\t\treturn KubeConfigSolutionUnix\n\t}\n}\n\n\n\n\nfunc NoProjectsExistMessage(canRequestProjects bool, commandName string) string ", "output": "{\n\tif !canRequestProjects {\n\t\treturn fmt.Sprintf(\"You don't have any projects. Contact your system administrator to request a project.\\n\")\n\t}\n\treturn fmt.Sprintf(`You don't have any projects. You can try to create a new project, by running\n\n %s new-project \n\n`, commandName)\n}"} {"input": "package grok\n\ntype nestingStack struct {\n\ttop *nestingElement\n\tsize int\n}\n\ntype nestingElement struct {\n\topenRune rune\n\tstartIndex int\n\tcommaCounter int\n\tlastSeparatorIndex int\n\tnext *nestingElement\n}\n\n\n\nfunc (ne *nestingElement) expressionStartIndex() int {\n\tstartIndex := ne.startIndex + 1\n\tif ne.lastSeparatorIndex+1 > startIndex {\n\t\treturn ne.lastSeparatorIndex + 1\n\t}\n\treturn startIndex\n}\n\nfunc (s *nestingStack) topValue() (rune, int, bool) {\n\tif s.size == 0 {\n\t\treturn ' ', -1, false\n\t}\n\n\treturn s.top.openRune, s.top.startIndex, true\n}\n\n\nfunc (s *nestingStack) push(openRune rune, startIndex int) {\n\ts.top = &nestingElement{openRune, startIndex, 0, -1, s.top}\n\ts.size++\n}\n\n\n\n\nfunc (s *nestingStack) pop() (openRune rune, startIndex int) ", "output": "{\n\tif s.size > 0 {\n\t\topenRune, startIndex, s.top = s.top.openRune, s.top.startIndex, s.top.next\n\t\ts.size--\n\t\treturn\n\t}\n\treturn ' ', -1\n}"} {"input": "package server\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"net/http\"\n\n\t\"github.com/docker/docker/daemon\"\n)\n\n\nfunc (s *Server) newServer(proto, addr string) (serverCloser, error) {\n\tvar (\n\t\terr error\n\t\tl net.Listener\n\t)\n\tswitch proto {\n\tcase \"tcp\":\n\t\tl, err = s.initTcpSocket(addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\tdefault:\n\t\treturn nil, errors.New(\"Invalid protocol format. Windows only supports tcp.\")\n\t}\n\treturn &HttpServer{\n\t\t&http.Server{\n\t\t\tAddr: addr,\n\t\t\tHandler: s.router,\n\t\t},\n\t\tl,\n\t}, nil\n}\n\nfunc (s *Server) AcceptConnections(d *daemon.Daemon) {\n\ts.daemon = d\n\tselect {\n\tcase <-s.start:\n\tdefault:\n\t\tclose(s.start)\n\t}\n}\n\n\n\nfunc allocateDaemonPort(addr string) error ", "output": "{\n\treturn nil\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSAmazonMQBroker_MaintenanceWindow struct {\n\n\tDayOfWeek string `json:\"DayOfWeek,omitempty\"`\n\n\tTimeOfDay string `json:\"TimeOfDay,omitempty\"`\n\n\tTimeZone string `json:\"TimeZone,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\n\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::AmazonMQ::Broker.MaintenanceWindow\"\n}"} {"input": "package templating\n\nimport (\n\t\"sort\"\n\t\"strings\"\n)\n\n\n\ntype node struct {\n\tseparator string\n\tvalue string\n\tchildren nodes\n\ttemplate *Template\n}\n\n\n\nfunc (n *node) insert(filter string, template *Template) {\n\tn.separator = template.separator\n\tn.recursiveInsert(strings.Split(filter, n.separator), template)\n}\n\n\nfunc (n *node) recursiveInsert(values []string, template *Template) {\n\tif len(values) == 0 {\n\t\tn.template = template\n\t\treturn\n\t}\n\n\tfor _, v := range n.children {\n\t\tif v.value == values[0] {\n\t\t\tv.recursiveInsert(values[1:], template)\n\t\t\treturn\n\t\t}\n\t}\n\n\tnewNode := &node{value: values[0]}\n\tn.children = append(n.children, newNode)\n\tsort.Sort(&n.children)\n\n\tnewNode.recursiveInsert(values[1:], template)\n}\n\n\nfunc (n *node) search(line string) *Template {\n\tseparator := n.separator\n\treturn n.recursiveSearch(strings.Split(line, separator))\n}\n\n\n\n\n\ntype nodes []*node\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (n *nodes) Less(j, k int) bool {\n\tif (*n)[j].value == \"*\" && (*n)[k].value != \"*\" {\n\t\treturn false\n\t}\n\n\tif (*n)[j].value != \"*\" && (*n)[k].value == \"*\" {\n\t\treturn true\n\t}\n\n\treturn (*n)[j].value < (*n)[k].value\n}\n\n\nfunc (n *nodes) Swap(i, j int) { (*n)[i], (*n)[j] = (*n)[j], (*n)[i] }\n\n\nfunc (n *nodes) Len() int { return len(*n) }\n\nfunc (n *node) recursiveSearch(lineParts []string) *Template ", "output": "{\n\tif len(lineParts) == 0 || len(n.children) == 0 {\n\t\treturn n.template\n\t}\n\n\tvar (\n\t\thasWildcard bool\n\t\tlength = len(n.children)\n\t)\n\n\tif hasWildcard = n.children[length-1].value == \"*\"; hasWildcard {\n\t\tlength--\n\t}\n\n\ti := sort.Search(length, func(i int) bool {\n\t\treturn n.children[i].value >= lineParts[0]\n\t})\n\n\tif i < length && n.children[i].value == lineParts[0] {\n\t\tif tmpl := n.children[i].recursiveSearch(lineParts[1:]); tmpl != nil {\n\t\t\treturn tmpl\n\t\t}\n\t}\n\n\tif hasWildcard {\n\t\treturn n.children[length].recursiveSearch(lineParts[1:])\n\t}\n\n\treturn n.template\n}"} {"input": "package middleware\n\nimport (\n\t\"github.com/drone/drone/shared/model\"\n\t\"github.com/zenazn/goji/web\"\n)\n\n\n\n\n\n\n\nfunc RepoToC(c *web.C, repo *model.Repo) {\n\tc.Env[\"repo\"] = repo\n}\n\n\n\nfunc RoleToC(c *web.C, role *model.Perm) {\n\tc.Env[\"role\"] = role\n}\n\n\n\n\nfunc ToUser(c *web.C) *model.User {\n\tvar v = c.Env[\"user\"]\n\tif v == nil {\n\t\treturn nil\n\t}\n\tu, ok := v.(*model.User)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn u\n}\n\n\n\n\nfunc ToRepo(c *web.C) *model.Repo {\n\tvar v = c.Env[\"repo\"]\n\tif v == nil {\n\t\treturn nil\n\t}\n\tr, ok := v.(*model.Repo)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn r\n}\n\n\n\n\nfunc ToRole(c *web.C) *model.Perm {\n\tvar v = c.Env[\"role\"]\n\tif v == nil {\n\t\treturn nil\n\t}\n\tp, ok := v.(*model.Perm)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn p\n}\n\nfunc UserToC(c *web.C, user *model.User) ", "output": "{\n\tc.Env[\"user\"] = user\n}"} {"input": "package runtime\n\nimport (\n\t\"gopkg.in/v1/yaml\"\n)\n\n\n\n\n\n\n\nfunc (a *Object) UnmarshalJSON(b []byte) error {\n\tif len(b) == 4 && string(b) == \"null\" {\n\t\ta.Object = nil\n\t\treturn nil\n\t}\n\n\tobj, err := Decode(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.Object = obj\n\treturn nil\n}\n\n\nfunc (a Object) MarshalJSON() ([]byte, error) {\n\tif a.Object == nil {\n\t\treturn []byte(\"null\"), nil\n\t}\n\n\treturn Encode(a.Object)\n}\n\n\nfunc (a *Object) SetYAML(tag string, value interface{}) bool {\n\tif value == nil {\n\t\ta.Object = nil\n\t\treturn true\n\t}\n\tb, err := yaml.Marshal(value)\n\tif err != nil {\n\t\tpanic(\"yaml can't reverse its own object\")\n\t}\n\tobj, err := Decode(b)\n\tif err != nil {\n\t\treturn false\n\t}\n\ta.Object = obj\n\treturn true\n}\n\n\n\n\nfunc (a Object) GetYAML() (tag string, value interface{}) ", "output": "{\n\tif a.Object == nil {\n\t\tvalue = \"null\"\n\t\treturn\n\t}\n\tv, err := Encode(a.Object)\n\tif err != nil {\n\t\tpanic(\"impossible to encode API object!\")\n\t}\n\treturn tag, v\n}"} {"input": "package model\n\nimport (\n\t\"github.com/evolsnow/samaritan/common/caches\"\n\t\"github.com/evolsnow/samaritan/common/dbms\"\n\t\"time\"\n)\n\nvar cache *caches.SimpleCache\n\nfunc init() {\n\tdbms.Pool = dbms.NewPool(\"127.0.0.1:6379\", \"\", \"2\")\n\tdbms.CachePool = dbms.NewPool(\"127.0.0.1:6379\", \"\", \"9\")\n\tc := dbms.Pool.Get()\n\tdefer c.Close()\n\tc.Do(\"FLUSHDB\")\n\tcc := dbms.CachePool.Get()\n\tdefer cc.Close()\n\tcc.Do(\"FLUSHDB\")\n\tbeforeTest()\n}\n\n\n\nfunc beforeTest() ", "output": "{\n\tcache = caches.NewCache()\n\tu := &User{\n\t\tSamId: \"evol\",\n\t\tAlias: \"evol\",\n\t\tName: \"张三\",\n\t\tPhone: \"13212341234\",\n\t\tPassword: \"oldpwd\",\n\t\tEmail: \"gsc1215225@gmail.com\",\n\t}\n\tu.Save()\n\tdbms.CreateSearchIndex(u.Id, \"gsc1215225@gmail.com\", \"mail\")\n\tcache.Set(\"gsc1215225@gmail.com:code\", \"123456\", time.Minute*5)\n\n\tt := &Todo{\n\t\tOwnerId: u.Id,\n\t\tStartTime: time.Now().Unix(),\n\t\tDesc: \"desc here\",\n\t}\n\tt.Save()\n\tcache.Set(\"delete_test_todo_pid\", t.Pid, time.Minute*5)\n}"} {"input": "package msg\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com/KunTengRom/xfrps/utils/errors\"\n)\n\nfunc unpack(typeByte byte, buffer []byte, msgIn Message) (msg Message, err error) {\n\tif msgIn == nil {\n\t\tt, ok := TypeMap[typeByte]\n\t\tif !ok {\n\t\t\terr = fmt.Errorf(\"Unsupported message type %b\", typeByte)\n\t\t\treturn\n\t\t}\n\n\t\tmsg = reflect.New(t).Interface().(Message)\n\t} else {\n\t\tmsg = msgIn\n\t}\n\n\terr = json.Unmarshal(buffer, &msg)\n\treturn\n}\n\nfunc UnPackInto(buffer []byte, msg Message) (err error) {\n\t_, err = unpack(' ', buffer, msg)\n\treturn\n}\n\nfunc UnPack(typeByte byte, buffer []byte) (msg Message, err error) {\n\treturn unpack(typeByte, buffer, nil)\n}\n\n\n\nfunc Pack(msg Message) ([]byte, error) ", "output": "{\n\ttypeByte, ok := TypeStringMap[reflect.TypeOf(msg).Elem()]\n\tif !ok {\n\t\treturn nil, errors.ErrMsgType\n\t}\n\n\tcontent, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuffer := bytes.NewBuffer(nil)\n\tbuffer.WriteByte(typeByte)\n\tbinary.Write(buffer, binary.BigEndian, int32(len(content)))\n\tbuffer.Write(content)\n\treturn buffer.Bytes(), nil\n}"} {"input": "package schema\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\nfunc TestParseGroup(t *testing.T) {\n\tgroupJsonString, _ := ioutil.ReadFile(\"../../resources/samples/group.json\")\n\tvar group GroupBase\n\tjson.Unmarshal(groupJsonString, &group)\n\tt.Log(\"Group ID is: \", group.Id)\n\tt.Log(\"Group Name is: \", group.Group.Name)\n}\n\n\n\nfunc TestParsePostMessage(t *testing.T) {\n\tpostJsonString, _ := ioutil.ReadFile(\"../../resources/samples/post.json\")\n\tvar post MessageBase\n\tjson.Unmarshal(postJsonString, &post)\n\tt.Log(\"Post Id is: \", post.Id)\n\tt.Log(\"Post to Thread: \", post.Message.ThreadId)\n\tt.Log(\"Post Content is: \", post.Message.Content)\n}\n\nfunc TestParseThreadMessage(t *testing.T) ", "output": "{\n\tthreadJsonString, _ := ioutil.ReadFile(\"../../resources/samples/thread.json\")\n\tvar thread MessageBase\n\tjson.Unmarshal(threadJsonString, &thread)\n\tt.Log(\"Thread Id is: \", thread.Id)\n\tt.Log(\"Thread Title is: \", thread.Message.Title)\n\tt.Log(\"Thread Author is: \", thread.Message.Author.User.ScreenName)\n}"} {"input": "package gotify\n\nimport (\n\t\"github.com/antonholmquist/jason\"\n)\n\n\n\nfunc parseArtist(o *jason.Object) Artist {\n\tartistName, _ := o.GetString(\"name\")\n\tartistUri, _ := o.GetString(\"uri\")\n\n\tartist := Artist{artistName, artistUri}\n\n\treturn artist\n}\n\nfunc parseTrack(o *jason.Object) Track {\n\ttrackName, _ := o.GetString(\"name\")\n\ttrackUri, _ := o.GetString(\"uri\")\n\n\tjsonAlbum, err := o.GetObject(\"album\")\n\n\tvar album Album\n\tif err == nil {\n\t\talbum = parseAlbum(jsonAlbum)\n\t}\n\n\tjsonArtists, err := o.GetObjectArray(\"artists\")\n\n\tvar artists []Artist\n\tif err == nil {\n\t\tartists = parseArtists(jsonArtists)\n\t}\n\n\ttrack := Track{trackName, trackUri, album, artists}\n\n\treturn track\n}\n\nfunc parseTracks(o []*jason.Object) []Track {\n\ttracks := []Track{}\n\n\tfor _, jsonTrack := range o {\n\t\ttracks = append(tracks, parseTrack(jsonTrack))\n\t}\n\n\treturn tracks\n}\n\nfunc parseAlbums(o []*jason.Object) []Album {\n\talbums := []Album{}\n\n\tfor _, jsonAlbum := range o {\n\t\talbums = append(albums, parseAlbum(jsonAlbum))\n\t}\n\n\treturn albums\n}\n\nfunc parseArtists(o []*jason.Object) []Artist {\n\tartists := []Artist{}\n\n\tfor _, jsonArtist := range o {\n\t\tartists = append(artists, parseArtist(jsonArtist))\n\t}\n\n\treturn artists\n}\n\nfunc parsePlaylist(o *jason.Object) SpotifyPlaylist {\n\treturn SpotifyPlaylist{}\n}\n\nfunc parseAlbum(o *jason.Object) Album ", "output": "{\n\talbumName, _ := o.GetString(\"name\")\n\talbumUri, _ := o.GetString(\"uri\")\n\n\talbum := Album{albumName, albumUri}\n\n\treturn album\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\n\n\ntype StatsRecorder struct {\n\tmutex sync.RWMutex\n\tnumRecentErrors int\n\trecentErrors []*statsError\n}\n\n\ntype Stats struct {\n\tRecentErrors []*statsError `json:\"recent_errors\"`\n}\n\n\ntype statsError struct {\n\tStatusCode int `json:\"status_code\"`\n\tStatus string `json:\"status\"`\n\tMethod string `json:\"method\"`\n\tHost string `json:\"host\"`\n\tPath string `json:\"path\"`\n\tTime time.Time `json:\"time\"`\n}\n\n\n\ntype responseRecorder struct {\n\thttp.ResponseWriter\n\tstatusCode int\n}\n\n\nfunc (r *responseRecorder) WriteHeader(status int) {\n\tr.ResponseWriter.WriteHeader(status)\n\tr.statusCode = status\n}\n\n\n\n\nfunc (s *StatsRecorder) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\trecorder := &responseRecorder{w, http.StatusOK}\n\tnext(recorder, r)\n\tif recorder.statusCode >= 400 {\n\t\ts.mutex.Lock()\n\t\tdefer s.mutex.Unlock()\n\t\ts.recentErrors = append([]*statsError{\n\t\t\t{\n\t\t\t\tStatusCode: recorder.statusCode,\n\t\t\t\tStatus: http.StatusText(recorder.statusCode),\n\t\t\t\tMethod: r.Method,\n\t\t\t\tHost: r.Host,\n\t\t\t\tPath: r.URL.Path,\n\t\t\t\tTime: time.Now(),\n\t\t\t},\n\t\t}, s.recentErrors...)\n\t\tif len(s.recentErrors) > s.numRecentErrors {\n\t\t\ts.recentErrors = s.recentErrors[:s.numRecentErrors]\n\t\t}\n\t}\n}\n\n\n\n\nfunc (s *StatsRecorder) Data() *Stats ", "output": "{\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\n\trecentErrors := make([]*statsError, len(s.recentErrors))\n\tcopy(recentErrors, s.recentErrors)\n\n\treturn &Stats{\n\t\tRecentErrors: recentErrors,\n\t}\n}"} {"input": "package workflow\n\nimport (\n\t\"github.com/calebamiles/keps/pkg/keps\"\n\t\"github.com/calebamiles/keps/pkg/keps/states\"\n\t\"github.com/calebamiles/keps/pkg/settings\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Plan(runtime settings.Runtime) error ", "output": "{\n\tp, err := keps.Path(runtime.ContentRoot(), runtime.TargetDir())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkep, err := keps.Open(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = kep.SetState(states.Implementable)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = kep.Persist()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\n\treturn nil\n}"} {"input": "package errors\n\nimport (\n\t\"net/http\"\n\t\"log\"\n)\n\n\nfunc PanicHandler(w http.ResponseWriter, r *http.Request, error interface{}) {\n\tlog.Println(error)\n\tw.Write([]byte(\"Unexpected Error\"))\n}\n\n\n\nfunc PanicWhenError(err error) ", "output": "{\n\tif (err != nil) {\n\t\tpanic(err)\n\t}\n}"} {"input": "package models\n\nimport (\n\t\"testing\"\n\n\t\"github.com/golib/assert\"\n\tuuid \"github.com/satori/go.uuid\"\n)\n\nfunc Test_NewUserModel(t *testing.T) {\n\tassertion := assert.New(t)\n\n\tvar (\n\t\tusername = uuid.NewV4().String()\n\t\temail = \"tes1@test.com\"\n\t\tpassword = uuid.NewV4().String()\n\t\tdesc = uuid.NewV4().String()\n\t)\n\n\tuser := User.NewUserModel(username, email, password, desc)\n\tassertion.Equal(username, user.Username)\n\tassertion.Equal(email, user.Email)\n\tassertion.Equal(password, user.Password)\n\tassertion.Equal(UserStatusInactive, user.Status)\n\tassertion.Equal(desc, user.Description)\n}\n\n\n\nfunc Test_User_FindByUsername(t *testing.T) {\n\tassertion := assert.New(t)\n\n\tvar (\n\t\tusername = uuid.NewV4().String()\n\t\temail = \"test3@test.com\"\n\t\tpassword = uuid.NewV4().String()\n\t\tdesc = uuid.NewV4().String()\n\t)\n\n\tuser := User.NewUserModel(username, email, password, desc)\n\terr := user.Save()\n\tassertion.Nil(err)\n\n\tuserNew, err := User.FindByUsername(username)\n\tassertion.Nil(err)\n\tassertion.Equal(user.Id, userNew.Id)\n\n}\n\nfunc Test_User_FindByEmail(t *testing.T) ", "output": "{\n\tassertion := assert.New(t)\n\n\tvar (\n\t\tusername = uuid.NewV4().String()\n\t\temail = \"test2@test.com\"\n\t\tpassword = uuid.NewV4().String()\n\t\tdesc = uuid.NewV4().String()\n\t)\n\n\tuser := User.NewUserModel(username, email, password, desc)\n\terr := user.Save()\n\tassertion.Nil(err)\n\n\tuser.Save()\n\tassertion.Nil(err)\n\n\tuserNew, err := User.FindByEmail(email)\n\tassertion.Nil(err)\n\tassertion.Equal(user.Id, userNew.Id)\n\n}"} {"input": "package resourcemover\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" resourcemover/2021-01-01\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package testutils\n\nimport (\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n\t\"gopkg.in/yaml.v2\"\n)\n\n\n\nfunc MarshalToString(input interface{}) (string, error) ", "output": "{\n\tbytes, err := yaml.Marshal(input)\n\tif err != nil {\n\t\treturn \"\", bosherr.WrapErrorf(err, \"Marshaling to string: %#v\", input)\n\t}\n\n\treturn string(bytes), nil\n}"} {"input": "package keymutex\n\nimport (\n\t\"hash/fnv\"\n\t\"runtime\"\n\t\"sync\"\n)\n\n\n\n\n\n\n\n\ntype hashedKeyMutex struct {\n\tmutexes []sync.Mutex\n}\n\n\nfunc (km *hashedKeyMutex) LockKey(id string) {\n\tkm.mutexes[km.hash(id)%len(km.mutexes)].Lock()\n}\n\n\nfunc (km *hashedKeyMutex) UnlockKey(id string) error {\n\tkm.mutexes[km.hash(id)%len(km.mutexes)].Unlock()\n\treturn nil\n}\n\nfunc (km *hashedKeyMutex) hash(id string) int {\n\th := fnv.New32a()\n\th.Write([]byte(id))\n\treturn int(h.Sum32())\n}\n\nfunc NewHashed(n int) KeyMutex ", "output": "{\n\tif n <= 0 {\n\t\tn = runtime.NumCPU()\n\t}\n\treturn &hashedKeyMutex{\n\t\tmutexes: make([]sync.Mutex, n),\n\t}\n}"} {"input": "package steps\n\nimport (\n\t\"github.com/cayleygraph/cayley/graph\"\n\t\"github.com/cayleygraph/cayley/query/linkedql\"\n\t\"github.com/cayleygraph/cayley/query/path\"\n\t\"github.com/cayleygraph/quad\"\n\t\"github.com/cayleygraph/quad/voc\"\n)\n\n\n\nvar _ linkedql.PathStep = (*Vertex)(nil)\n\n\ntype Vertex struct {\n\tValues []quad.Value `json:\"values\"`\n}\n\n\nfunc (s *Vertex) Description() string {\n\treturn \"resolves to all the existing objects and primitive values in the graph. If provided with values resolves to a sublist of all the existing values in the graph.\"\n}\n\n\nfunc (s *Vertex) BuildPath(qs graph.QuadStore, ns *voc.Namespaces) (*path.Path, error) {\n\treturn path.StartPath(qs, linkedql.AbsoluteValues(s.Values, ns)...), nil\n}\n\nfunc init() ", "output": "{\n\tlinkedql.Register(&Vertex{})\n}"} {"input": "package tlf\n\nimport (\n\t\"testing\"\n\n\t\"github.com/keybase/client/go/protocol/keybase1\"\n\t\"github.com/keybase/kbfs/kbfscodec\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestMakeIDFromTeam(t *testing.T) {\n\tprivateTID := keybase1.MakeTestTeamID(1, false)\n\tpublicTID := keybase1.MakeTestTeamID(2, true)\n\n\tepochIndex := idByteLen - 2\n\tcheck := func(ty Type, tid keybase1.TeamID, epoch byte) {\n\t\tid, err := MakeIDFromTeam(ty, tid, epoch)\n\t\trequire.NoError(t, err)\n\t\trequire.Equal(t, id.Type(), ty)\n\t\trequire.Equal(t, tid.ToBytes()[:epochIndex], id.Bytes()[:epochIndex])\n\t\trequire.Equal(t, epoch, id.Bytes()[epochIndex])\n\t}\n\tcheck(Private, privateTID, 0)\n\tcheck(Public, publicTID, 0)\n\tcheck(SingleTeam, privateTID, 0)\n\tcheck(Private, privateTID, 15)\n\n\t_, err := MakeIDFromTeam(Public, privateTID, 0)\n\trequire.NotNil(t, err)\n\t_, err = MakeIDFromTeam(Private, publicTID, 0)\n\trequire.NotNil(t, err)\n\t_, err = MakeIDFromTeam(SingleTeam, publicTID, 0)\n\trequire.NotNil(t, err)\n\t_, err = MakeIDFromTeam(\n\t\tPrivate, keybase1.TeamID(\"extra\"+privateTID.String()), 0)\n\trequire.NotNil(t, err)\n}\n\nfunc TestIDEncodeDecode(t *testing.T) ", "output": "{\n\tcodec := kbfscodec.NewMsgpack()\n\tid := FakeID(1, Public)\n\n\tencodedID, err := codec.Encode(id)\n\trequire.NoError(t, err)\n\n\tconst overhead = 2\n\trequire.Equal(t, idByteLen+overhead, len(encodedID))\n\n\tvar id2 ID\n\terr = codec.Decode(encodedID, &id2)\n\trequire.NoError(t, err)\n\n\trequire.Equal(t, id, id2)\n}"} {"input": "package spanner\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\tdatabase \"cloud.google.com/go/spanner/admin/database/apiv1\"\n\tadminpb \"google.golang.org/genproto/googleapis/spanner/admin/database/v1\"\n)\n\n\n\nfunc createTableDocumentsWithTimestamp(ctx context.Context, w io.Writer, db string) error ", "output": "{\n\tadminClient, err := database.NewDatabaseAdminClient(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer adminClient.Close()\n\n\top, err := adminClient.UpdateDatabaseDdl(ctx, &adminpb.UpdateDatabaseDdlRequest{\n\t\tDatabase: db,\n\t\tStatements: []string{\n\t\t\t`CREATE TABLE DocumentsWithTimestamp(\n\t\t\t\tUserId INT64 NOT NULL,\n\t\t\t\tDocumentId INT64 NOT NULL,\n\t\t\t Timestamp TIMESTAMP NOT NULL OPTIONS(allow_commit_timestamp=true),\n\t\t\t\tContents STRING(MAX) NOT NULL\n\t\t\t) PRIMARY KEY(UserId, DocumentId)`,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := op.Wait(ctx); err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(w, \"Created DocumentsWithTimestamp table in database [%s]\\n\", db)\n\treturn nil\n}"} {"input": "package runewidth\n\nimport (\n\t\"testing\"\n\t\"unicode/utf8\"\n)\n\nvar benchSink int\n\n\n\nfunc BenchmarkTablePrivate(b *testing.B) {\n\tbenchSink = benchTable(b, private)\n}\nfunc BenchmarkTableNonprint(b *testing.B) {\n\tbenchSink = benchTable(b, nonprint)\n}\nfunc BenchmarkTableCombining(b *testing.B) {\n\tbenchSink = benchTable(b, combining)\n}\nfunc BenchmarkTableDoublewidth(b *testing.B) {\n\tbenchSink = benchTable(b, doublewidth)\n}\nfunc BenchmarkTableAmbiguous(b *testing.B) {\n\tbenchSink = benchTable(b, ambiguous)\n}\nfunc BenchmarkTableEmoji(b *testing.B) {\n\tbenchSink = benchTable(b, emoji)\n}\nfunc BenchmarkTableNotassigned(b *testing.B) {\n\tbenchSink = benchTable(b, notassigned)\n}\nfunc BenchmarkTableNeutral(b *testing.B) {\n\tbenchSink = benchTable(b, neutral)\n}\n\nfunc benchTable(b *testing.B, tbl table) int ", "output": "{\n\tn := 0\n\tfor i := 0; i < b.N; i++ {\n\t\tfor r := rune(0); r <= utf8.MaxRune; r++ {\n\t\t\tif inTable(r, tbl) {\n\t\t\t\tn++\n\t\t\t}\n\t\t}\n\t}\n\treturn n\n}"} {"input": "package oci\n\nimport \"io/fs\"\n\n\n\n\n\ntype dirInfo struct {\n\tfileInfo fs.FileInfo\n}\n\nfunc (di dirInfo) IsDir() bool {\n\treturn di.fileInfo.IsDir()\n}\n\nfunc (di dirInfo) Type() fs.FileMode {\n\treturn di.fileInfo.Mode().Type()\n}\n\n\n\nfunc (di dirInfo) Name() string {\n\treturn di.fileInfo.Name()\n}\n\n\n\nfunc fileInfoToDirEntry(info fs.FileInfo) fs.DirEntry {\n\tif info == nil {\n\t\treturn nil\n\t}\n\treturn dirInfo{fileInfo: info}\n}\n\nfunc (di dirInfo) Info() (fs.FileInfo, error) ", "output": "{\n\treturn di.fileInfo, nil\n}"} {"input": "package goapp\n\n\nimport(\n \"github.com/xaevman/goat/mod/log\"\n)\n\n\nimport(\n \"testing\"\n \"time\"\n)\n\n\n\nfunc TestDefaultApp(t *testing.T) {\n log.DebugLogs = true\n\n SetHeartbeat(1 * 1000) \n go waitForShutdown()\n\n stopChan := Start(\"DefaultApp\")\n <-stopChan\n}\n\n\n\n\n\nfunc waitForShutdown() ", "output": "{\n <-time.After(10 * time.Second)\n Stop()\n}"} {"input": "package error\n\nimport (\n\t\"strconv\"\n)\n\n\n\ntype StructuralError string\n\nfunc (s StructuralError) String() string {\n\treturn \"OpenPGP data invalid: \" + string(s)\n}\n\n\n\ntype UnsupportedError string\n\n\n\n\n\ntype InvalidArgumentError string\n\nfunc (i InvalidArgumentError) String() string {\n\treturn \"OpenPGP argument invalid: \" + string(i)\n}\n\n\n\ntype SignatureError string\n\nfunc (b SignatureError) String() string {\n\treturn \"OpenPGP signature invalid: \" + string(b)\n}\n\ntype keyIncorrect int\n\nfunc (ki keyIncorrect) String() string {\n\treturn \"the given key was incorrect\"\n}\n\nvar KeyIncorrectError = keyIncorrect(0)\n\ntype unknownIssuer int\n\nfunc (unknownIssuer) String() string {\n\treturn \"signature make by unknown entity\"\n}\n\nvar UnknownIssuerError = unknownIssuer(0)\n\ntype UnknownPacketTypeError uint8\n\nfunc (upte UnknownPacketTypeError) String() string {\n\treturn \"unknown OpenPGP packet type: \" + strconv.Itoa(int(upte))\n}\n\nfunc (s UnsupportedError) String() string ", "output": "{\n\treturn \"OpenPGP feature unsupported: \" + string(s)\n}"} {"input": "package create_topic\n\nimport (\n\t\"encoding/xml\"\n\t\"net/http\"\n\n\t\"github.com/vburenin/firempq/server/snsproto/sns_query\"\n\t\"github.com/vburenin/firempq/server/snsproto/sns_response\"\n\t\"github.com/vburenin/firempq/server/snsproto/snsdefs\"\n\t\"github.com/vburenin/firempq/server/snsproto/snserr\"\n\t\"github.com/vburenin/firempq/server/snsproto/tmgr\"\n\t\"github.com/vburenin/firempq/server/snsproto/validation\"\n)\n\ntype CreateTopicResponse struct {\n\tXMLName xml.Name `xml:\"http://sns.amazonaws.com/doc/2010-03-31/ CreateTopicResponse\"`\n\tTopicArn string `xml:\"CreateTopicResult>TopicArn\"`\n\tRequestId string `xml:\"ResponseMetadata>RequestId\"`\n}\n\n\nfunc (s *CreateTopicResponse) HttpCode() int { return http.StatusOK }\n\nfunc CreateTopic(tm *tmgr.TopicManager, snsQuery *sns_query.SNSQuery) sns_response.SNSResponse {\n\ttopicName := \"\"\n\tsns_query.ParseParams(snsQuery, func(k, v string) {\n\t\tif k == \"Name\" {\n\t\t\ttopicName = v\n\t\t}\n\t})\n\n\tif !validation.ValidateTopicName(topicName) {\n\t\treturn snserr.InvalidParameterError(\"Invalid parameter: Topic Name\")\n\t}\n\n\tarn := tm.CreateTopic(topicName)\n\n\treturn &CreateTopicResponse{\n\t\tXMLName: xml.Name{\n\t\t\tSpace: snsdefs.XMLSpace,\n\t\t\tLocal: \"CreateTopicResponse\",\n\t\t},\n\t\tTopicArn: arn,\n\t\tRequestId: \"reqId\",\n\t}\n}\n\nfunc (s *CreateTopicResponse) XmlDocument() string ", "output": "{ return sns_response.EncodeXml(s) }"} {"input": "package main\n\nimport \"testing\"\n\nfunc TestFailReadConfig(t *testing.T) {\n\terr := readConfig(\"does-not-exist.json\")\n\tif err == nil ||\n\t\terr.Error() != \"open does-not-exist.json: no such file or directory\" {\n\n\t\tt.Fatalf(\"It should've failed because the file does not exist.\")\n\t}\n}\n\n\n\nfunc TestReadConfig(t *testing.T) ", "output": "{\n\terr := readConfig(\"../../obs2vagrant.json.example\")\n\tif err != nil {\n\t\tt.Fatalf(\"It should be ok\")\n\t}\n\n\tif cfg.Address != \"127.0.0.1\" {\n\t\tt.Fatalf(\"Wrong address\")\n\t}\n\tif cfg.Port != 8080 {\n\t\tt.Fatalf(\"Wrong port\")\n\t}\n\tif len(cfg.Servers) != 2 {\n\t\tt.Fatalf(\"Wrong numbers of servers\")\n\t}\n\tif cfg.Servers[\"obs\"] != \"http://download.opensuse.org/repositories/\" {\n\t\tt.Fatalf(\"Wrong config for obs\")\n\t}\n\tif cfg.Servers[\"ibs\"] != \"http://download.suse.de/ibs/\" {\n\t\tt.Fatalf(\"Wrong config for ibs\")\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\n\t\"gopkg.in/stretchr/testify.v1/mock\"\n)\n\ntype Printer interface {\n\tHelp()\n\tVersion()\n\tMessage(msg string)\n\tError(err error)\n\tCommands()\n}\n\ntype TextPrinter struct {\n\tversion string\n}\n\nfunc NewTextPrinter(version string) *TextPrinter {\n\treturn &TextPrinter{version}\n}\n\nfunc (p *TextPrinter) Help() {\n\thelpText := `Name:\n\tfiz - a file wizard\n\nVersion:\n\t` + p.version + `\n\nUsage:\n\tfiz \n\n`\n\tp.Message(helpText)\n\tp.Commands()\n}\n\nfunc (p *TextPrinter) Version() {\n\tfmt.Println(\"fiz\", p.version)\n}\n\n\n\nfunc (p *TextPrinter) Error(err error) {\n\tfmt.Println(\"Error: \", err)\n}\n\nfunc (p *TextPrinter) Commands() {\n\tp.Message(COMMANDS_MSG)\n}\n\n\ntype MockPrinter struct {\n\tmock.Mock\n}\n\nfunc NewMockPrinter() *MockPrinter {\n\treturn &MockPrinter{}\n}\n\nfunc (m *MockPrinter) Help() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Version() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Message(msg string) {\n\tm.Called(msg)\n}\n\nfunc (m *MockPrinter) Error(err error) {\n\tm.Called(err)\n}\n\nfunc (m *MockPrinter) Commands() {\n\tm.Called()\n}\n\nfunc (p *TextPrinter) Message(msg string) ", "output": "{\n\tfmt.Print(msg)\n}"} {"input": "package bloomfilter\n\nimport (\n\t\"testing\"\n)\n\n\nfunc Test_Exists(t *testing.T) {\n\tloadStrings := []string{\n\t\t\"cat\", \"dog\", \"mate\", \"frog\", \"moose\",\n\t\t\"el capitan\", \"spruce goose\"}\n\n\ttype TestCase struct {\n\t\tInput string\n\t\tExpected bool\n\t}\n\n\ttestcases := []TestCase{\n\t\t{\"klingon\", false},\n\t\t{\"frog\", true},\n\t\t{\"donkey\", true},\n\t\t{\"tame\", true},\n\t\t{\"spruce goose\", true},\n\t\t{\"light speed\", false},\n\t}\n\n\tb := NewBloomFilter(15)\n\tfor _, j := range loadStrings {\n\t\tb.Add(j)\n\t}\n\n\tfor _, j := range testcases {\n\t\tactual := b.Exists(j.Input)\n\t\tif actual != j.Expected {\n\t\t\tt.Error(\"\\nExpected:\", j.Expected, \"\\nGot:\", actual, \"\\nFor:\", j.Input)\n\t\t}\n\t}\n}\n\nfunc Benchmark_Add(b *testing.B) {\n\tb.ReportAllocs()\n\n\tloadStrings := []string{\n\t\t\"cat\", \"dog\", \"mate\", \"frog\", \"moose\",\n\t\t\"el capitan\", \"spruce goose\"}\n\n\tf := NewBloomFilter(15)\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, j := range loadStrings {\n\t\t\tf.Add(j)\n\t\t}\n\t}\n}\n\n\n\nfunc Benchmark_Exists(b *testing.B) ", "output": "{\n\tb.ReportAllocs()\n\n\tcheckStrings := []string{\n\t\t\"klingon\", \"frog\", \"donkey\",\n\t\t\"tame\", \"spruce goose\", \"light speed\",\n\t}\n\n\tf := NewBloomFilter(15)\n\n\tloadStrings := []string{\n\t\t\"cat\", \"dog\", \"mate\", \"frog\", \"moose\",\n\t\t\"el capitan\", \"spruce goose\"}\n\n\tfor _, j := range loadStrings {\n\t\tf.Add(j)\n\t}\n\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, j := range checkStrings {\n\t\t\t_ = f.Exists(j)\n\t\t}\n\t}\n\n}"} {"input": "package stateful\n\nimport \"sync\"\n\n\n\n\ntype ScopePool interface {\n\tGet() *Scope\n\tPut(scope *Scope)\n\n\tReferenceVariables() []string\n}\n\ntype scopePool struct {\n\treferenceVariables []string\n\tpool sync.Pool\n}\n\n\n\n\nfunc (s *scopePool) ReferenceVariables() []string {\n\treturn s.referenceVariables\n}\n\n\n\nfunc (s *scopePool) Get() *Scope {\n\treturn s.pool.Get().(*Scope)\n}\n\n\nfunc (s *scopePool) Put(scope *Scope) {\n\tscope.Reset()\n\ts.pool.Put(scope)\n}\n\nfunc NewScopePool(referenceVariables []string) ScopePool ", "output": "{\n\tscopePool := &scopePool{\n\t\treferenceVariables: referenceVariables,\n\t}\n\n\tscopePool.pool = sync.Pool{\n\t\tNew: func() interface{} {\n\t\t\tscope := NewScope()\n\t\t\tfor _, refVariable := range scopePool.referenceVariables {\n\t\t\t\tscope.Set(refVariable, empty)\n\t\t\t}\n\n\t\t\treturn scope\n\t\t},\n\t}\n\n\treturn scopePool\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"net/http\"\n)\n\nfunc hello(w http.ResponseWriter, r *http.Request) {\n\tio.WriteString(w, \"Fabio rocks!\")\n}\n\n\n\nfunc main() {\n\thttp.HandleFunc(\"/\", internalServerError)\n\thttp.ListenAndServe(\":8000\", nil)\n}\n\nfunc internalServerError(w http.ResponseWriter, r *http.Request) ", "output": "{\n\thttp.Error(w, http.StatusText(http.StatusInternalServerError),\n\t\t\t\thttp.StatusInternalServerError)\n}"} {"input": "package fs\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nvar execExts map[string]bool\n\nfunc init() {\n\tpathext := filepath.SplitList(os.Getenv(\"PATHEXT\"))\n\texecExts = make(map[string]bool, len(pathext))\n\tfor _, ext := range pathext {\n\t\texecExts[strings.ToLower(ext)] = true\n\t}\n}\n\n\n\nfunc isWindowsExecutable(path string) bool {\n\treturn execExts[strings.ToLower(filepath.Ext(path))]\n}\n\n\n\nfunc (e basicFileInfo) Owner() int {\n\treturn -1\n}\n\nfunc (e basicFileInfo) Group() int {\n\treturn -1\n}\n\n\n\nfunc (e *basicFileInfo) osFileInfo() os.FileInfo {\n\tfi := e.FileInfo\n\tif fi, ok := fi.(*dirJunctFileInfo); ok {\n\t\treturn fi.FileInfo\n\t}\n\treturn fi\n}\n\nfunc (e basicFileInfo) Mode() FileMode ", "output": "{\n\tm := e.FileInfo.Mode()\n\tif m&os.ModeSymlink != 0 && e.Size() > 0 {\n\t\tm &^= os.ModeSymlink\n\t}\n\tif isWindowsExecutable(e.Name()) {\n\t\tm |= 0111\n\t}\n\tm &^= 0022\n\treturn FileMode(m)\n}"} {"input": "package main\n\nfunc main() {\n\tc := make(chan int, 1)\n\tx := 0\n\tselect {\n\tcase c <- x: \n\tcase <-makec(&x): \n\t}\n\ty := <-c\n\tif y != 0 {\n\t\tpanic(y)\n\t}\n}\n\n\n\nfunc makec(px *int) chan bool ", "output": "{\n\tif false { for {} }\n\t*px = 42\n\treturn make(chan bool, 0)\n}"} {"input": "package commands\n\nimport (\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"github.com/jamesread/ovress/pkg/indexer\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nfunc newIndexCmd() *cobra.Command {\n\tvar indexCmd = &cobra.Command{\n\t\tUse: \"index\",\n\t\tShort: \"Indexes a file path\",\n\t\tRun: runIndexCmd,\n\t\tArgs: cobra.MinimumNArgs(1),\n\t}\n\n\treturn indexCmd\n}\n\n\n\nfunc init() {\n\trootCmd.AddCommand(newIndexCmd())\n}\n\nfunc runIndexCmd(cmd *cobra.Command, args []string) ", "output": "{\n\tfor _, path := range args {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"path\": path,\n\t\t}).Infof(\"Indexing starting\")\n\n\t\troot := indexer.ScanRoot(path)\n\t\tindexer.SaveIndex(root)\n\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"path\": path,\n\t\t}).Infof(\"Indexing complete\")\n\t}\n}"} {"input": "package data\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestNote(t *testing.T) {\n\tacc := AccountNew(\"mail@example.com\")\n\tuser, err := acc.Store()\n\n\tassert.Nil(t, err)\n\n\tnote := NoteNew(user.ID, \"example content\")\n\n\tassert.False(t, note.IsStored())\n\tassert.Equal(t, \"example content\", note.Text)\n\tassert.Equal(t, user.ID, note.Account)\n\n\tnote, err = note.Store()\n\n\tif assert.Nil(t, err) {\n\t\tassert.True(t, note.IsStored())\n\t}\n\n\tuser.Remove()\n}\n\nfunc TestNoteLimit(t *testing.T) {\n\tacc := AccountNew(\"mail@example.com\")\n\tuser, err := acc.Store()\n\n\tassert.Nil(t, err)\n\n\tnote := NoteNew(user.ID, \"This is a note! This is a note! This is a note! This is a note! This is a note! This is a note! This is a note!\")\n\n\tassert.False(t, note.IsStored())\n\tassert.Equal(t, user.ID, note.Account)\n\n\tnote, err = note.Store()\n\n\tassert.NotNil(t, err)\n\n\tuser.Remove()\n}\n\n\n\nfunc TestNoteList(t *testing.T) ", "output": "{\n\tacc := AccountNew(\"mail@example.com\")\n\tuser, err := acc.Store()\n\n\tassert.Nil(t, err)\n\n\tnote := NoteNew(user.ID, \"This is a note!\")\n\tnote, err = note.Store()\n\n\tassert.Nil(t, err)\n\n\tnote2 := NoteNew(user.ID, \"This is a second note!\")\n\tnote2, err = note2.Store()\n\n\tassert.Nil(t, err)\n\n\tlist, err := NoteListByAccount(user.ID)\n\n\tassert.Nil(t, err)\n\tassert.Equal(t, 2, len(list))\n\n\tuser.Remove()\n}"} {"input": "package etcd\n\nimport (\n\t\"strconv\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/meta\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n\t\"k8s.io/kubernetes/pkg/storage\"\n)\n\n\n\ntype APIObjectVersioner struct{}\n\n\nfunc (a APIObjectVersioner) UpdateObject(obj runtime.Object, resourceVersion uint64) error {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tversionString := \"\"\n\tif resourceVersion != 0 {\n\t\tversionString = strconv.FormatUint(resourceVersion, 10)\n\t}\n\taccessor.SetResourceVersion(versionString)\n\treturn nil\n}\n\n\n\n\n\nfunc (a APIObjectVersioner) ObjectResourceVersion(obj runtime.Object) (uint64, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tversion := accessor.GetResourceVersion()\n\tif len(version) == 0 {\n\t\treturn 0, nil\n\t}\n\treturn strconv.ParseUint(version, 10, 64)\n}\n\n\nvar Versioner storage.Versioner = APIObjectVersioner{}\n\n\n\nfunc (a APIObjectVersioner) CompareResourceVersion(lhs, rhs runtime.Object) int {\n\tlhsVersion, err := Versioner.ObjectResourceVersion(lhs)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trhsVersion, err := Versioner.ObjectResourceVersion(rhs)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif lhsVersion == rhsVersion {\n\t\treturn 0\n\t}\n\tif lhsVersion < rhsVersion {\n\t\treturn -1\n\t}\n\n\treturn 1\n}\n\nfunc (a APIObjectVersioner) UpdateList(obj runtime.Object, resourceVersion uint64) error ", "output": "{\n\tlistMeta, err := api.ListMetaFor(obj)\n\tif err != nil || listMeta == nil {\n\t\treturn err\n\t}\n\tversionString := \"\"\n\tif resourceVersion != 0 {\n\t\tversionString = strconv.FormatUint(resourceVersion, 10)\n\t}\n\tlistMeta.ResourceVersion = versionString\n\treturn nil\n}"} {"input": "package core\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype BootVolumeSourceDetails interface {\n}\n\ntype bootvolumesourcedetails struct {\n\tJsonData []byte\n\tType string `json:\"type\"`\n}\n\n\nfunc (m *bootvolumesourcedetails) UnmarshalJSON(data []byte) error {\n\tm.JsonData = data\n\ttype Unmarshalerbootvolumesourcedetails bootvolumesourcedetails\n\ts := struct {\n\t\tModel Unmarshalerbootvolumesourcedetails\n\t}{}\n\terr := json.Unmarshal(data, &s.Model)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Type = s.Model.Type\n\n\treturn err\n}\n\n\n\n\nfunc (m bootvolumesourcedetails) String() string {\n\treturn common.PointerString(m)\n}\n\nfunc (m *bootvolumesourcedetails) UnmarshalPolymorphicJSON(data []byte) (interface{}, error) ", "output": "{\n\n\tif data == nil || string(data) == \"null\" {\n\t\treturn nil, nil\n\t}\n\n\tvar err error\n\tswitch m.Type {\n\tcase \"bootVolumeBackup\":\n\t\tmm := BootVolumeSourceFromBootVolumeBackupDetails{}\n\t\terr = json.Unmarshal(data, &mm)\n\t\treturn mm, err\n\tcase \"bootVolume\":\n\t\tmm := BootVolumeSourceFromBootVolumeDetails{}\n\t\terr = json.Unmarshal(data, &mm)\n\t\treturn mm, err\n\tcase \"bootVolumeReplica\":\n\t\tmm := BootVolumeSourceFromBootVolumeReplicaDetails{}\n\t\terr = json.Unmarshal(data, &mm)\n\t\treturn mm, err\n\tdefault:\n\t\treturn *m, nil\n\t}\n}"} {"input": "package server_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/nanopack/mist/auth\"\n\t\"github.com/nanopack/mist/server\"\n)\n\n\n\n\n\nfunc TestWSSStart(t *testing.T) {\n\tfmt.Println(\"Starting WSS test...\")\n\n\tauth.Start(\"\")\n\n\tgo func() {\n\t\tif err := server.Start([]string{\"wss://127.0.0.1:8988\"}, \"\"); err != nil {\n\t\t\tt.Fatalf(\"Unexpected error - %s\", err.Error())\n\t\t}\n\t}()\n\t<-time.After(time.Second)\n}\n\nfunc TestWSStart(t *testing.T) ", "output": "{\n\tfmt.Println(\"Starting WS test...\")\n\n\tauth.Start(\"\")\n\n\tgo func() {\n\t\tif err := server.Start([]string{\"ws://127.0.0.1:8888\"}, \"\"); err != nil {\n\t\t\tt.Fatalf(\"Unexpected error - %s\", err.Error())\n\t\t}\n\t}()\n\t<-time.After(time.Second)\n}"} {"input": "package iso20022\n\n\ntype AutomatedTellerMachine6 struct {\n\n\tIdentification *Max35Text `xml:\"Id\"`\n\n\tAdditionalIdentification *Max35Text `xml:\"AddtlId,omitempty\"`\n\n\tSequenceNumber *Max35Text `xml:\"SeqNb,omitempty\"`\n\n\tLocation *PostalAddress17 `xml:\"Lctn,omitempty\"`\n\n\tLocationCategory *TransactionEnvironment2Code `xml:\"LctnCtgy,omitempty\"`\n\n\tEquipment *ATMEquipment1 `xml:\"Eqpmnt,omitempty\"`\n}\n\nfunc (a *AutomatedTellerMachine6) SetIdentification(value string) {\n\ta.Identification = (*Max35Text)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) SetAdditionalIdentification(value string) {\n\ta.AdditionalIdentification = (*Max35Text)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) SetSequenceNumber(value string) {\n\ta.SequenceNumber = (*Max35Text)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) AddLocation() *PostalAddress17 {\n\ta.Location = new(PostalAddress17)\n\treturn a.Location\n}\n\nfunc (a *AutomatedTellerMachine6) SetLocationCategory(value string) {\n\ta.LocationCategory = (*TransactionEnvironment2Code)(&value)\n}\n\n\n\nfunc (a *AutomatedTellerMachine6) AddEquipment() *ATMEquipment1 ", "output": "{\n\ta.Equipment = new(ATMEquipment1)\n\treturn a.Equipment\n}"} {"input": "package glacier\n\nimport (\n\t\"encoding/hex\"\n\t\"reflect\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/awsutil\"\n)\n\nvar (\n\tdefaultAccountID = \"-\"\n)\n\nfunc init() {\n\tinitRequest = func(r *aws.Request) {\n\t\tr.Handlers.Validate.PushFront(addAccountID)\n\t\tr.Handlers.Validate.PushFront(copyParams) \n\t\tr.Handlers.Build.PushBack(addChecksum)\n\t\tr.Handlers.Build.PushBack(addAPIVersion)\n\t}\n}\n\n\n\nfunc addAccountID(r *aws.Request) {\n\tif !r.ParamsFilled() {\n\t\treturn\n\t}\n\n\tv := reflect.Indirect(reflect.ValueOf(r.Params))\n\tif f := v.FieldByName(\"AccountID\"); f.IsNil() {\n\t\tf.Set(reflect.ValueOf(&defaultAccountID))\n\t}\n}\n\nfunc addChecksum(r *aws.Request) {\n\tif r.Body == nil {\n\t\treturn\n\t}\n\n\th := ComputeHashes(r.Body)\n\n\tif r.HTTPRequest.Header.Get(\"X-Amz-Content-Sha256\") == \"\" {\n\t\thstr := hex.EncodeToString(h.LinearHash)\n\t\tr.HTTPRequest.Header.Set(\"X-Amz-Content-Sha256\", hstr)\n\t}\n\tif r.HTTPRequest.Header.Get(\"X-Amz-Sha256-Tree-Hash\") == \"\" {\n\t\thstr := hex.EncodeToString(h.TreeHash)\n\t\tr.HTTPRequest.Header.Set(\"X-Amz-Sha256-Tree-Hash\", hstr)\n\t}\n}\n\nfunc addAPIVersion(r *aws.Request) {\n\tr.HTTPRequest.Header.Set(\"X-Amz-Glacier-Version\", r.Service.APIVersion)\n}\n\nfunc copyParams(r *aws.Request) ", "output": "{\n\tr.Params = awsutil.CopyOf(r.Params)\n}"} {"input": "package builds\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/pivotal-golang/clock\"\n)\n\n\n\ntype BuildTracker interface {\n\tTrack()\n}\n\ntype TrackerRunner struct {\n\tTracker BuildTracker\n\tInterval time.Duration\n\tClock clock.Clock\n}\n\n\n\nfunc (runner TrackerRunner) Run(signals <-chan os.Signal, ready chan<- struct{}) error ", "output": "{\n\tticker := runner.Clock.NewTicker(runner.Interval)\n\n\tclose(ready)\n\n\trunner.Tracker.Track()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C():\n\t\t\trunner.Tracker.Track()\n\t\tcase <-signals:\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tpanic(\"unreachable\")\n}"} {"input": "package chart_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/dml/chart\"\n)\n\n\n\nfunc TestCT_NumDataSourceMarshalUnmarshal(t *testing.T) {\n\tv := chart.NewCT_NumDataSource()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := chart.NewCT_NumDataSource()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestCT_NumDataSourceConstructor(t *testing.T) ", "output": "{\n\tv := chart.NewCT_NumDataSource()\n\tif v == nil {\n\t\tt.Errorf(\"chart.NewCT_NumDataSource must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed chart.CT_NumDataSource should validate: %s\", err)\n\t}\n}"} {"input": "package credentials\n\nimport (\n\t\"strings\"\n\n\t\"github.com/docker/docker/cliconfig/configfile\"\n\t\"github.com/docker/engine-api/types\"\n)\n\n\n\ntype fileStore struct {\n\tfile *configfile.ConfigFile\n}\n\n\n\n\n\nfunc (c *fileStore) Erase(serverAddress string) error {\n\tdelete(c.file.AuthConfigs, serverAddress)\n\treturn c.file.Save()\n}\n\n\nfunc (c *fileStore) Get(serverAddress string) (types.AuthConfig, error) {\n\tauthConfig, ok := c.file.AuthConfigs[serverAddress]\n\tif !ok {\n\t\tfor registry, ac := range c.file.AuthConfigs {\n\t\t\tif serverAddress == convertToHostname(registry) {\n\t\t\t\treturn ac, nil\n\t\t\t}\n\t\t}\n\n\t\tauthConfig = types.AuthConfig{}\n\t}\n\treturn authConfig, nil\n}\n\nfunc (c *fileStore) GetAll() (map[string]types.AuthConfig, error) {\n\treturn c.file.AuthConfigs, nil\n}\n\n\nfunc (c *fileStore) Store(authConfig types.AuthConfig) error {\n\tc.file.AuthConfigs[authConfig.ServerAddress] = authConfig\n\treturn c.file.Save()\n}\n\nfunc convertToHostname(url string) string {\n\tstripped := url\n\tif strings.HasPrefix(url, \"http://\") {\n\t\tstripped = strings.Replace(url, \"http://\", \"\", 1)\n\t} else if strings.HasPrefix(url, \"https://\") {\n\t\tstripped = strings.Replace(url, \"https://\", \"\", 1)\n\t}\n\n\tnameParts := strings.SplitN(stripped, \"/\", 2)\n\n\treturn nameParts[0]\n}\n\nfunc NewFileStore(file *configfile.ConfigFile) Store ", "output": "{\n\treturn &fileStore{\n\t\tfile: file,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os/exec\"\n\t\"strings\"\n\n\tpwl \"github.com/justjanne/powerline-go/powerline\"\n)\n\n\n\nfunc segmentGCP(p *powerline) []pwl.Segment ", "output": "{\n\tout, err := exec.Command(\"gcloud\", \"config\", \"list\", \"project\", \"--format\", \"value(core.project)\").Output()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tproject := strings.TrimSuffix(string(out), \"\\n\")\n\tif project == \"\" {\n\t\treturn []pwl.Segment{}\n\t}\n\treturn []pwl.Segment{{\n\t\tName: \"gcp\",\n\t\tContent: project,\n\t\tForeground: p.theme.GCPFg,\n\t\tBackground: p.theme.GCPBg,\n\t}}\n}"} {"input": "package imagestreamtag\n\nimport (\n\tkapi \"github.com/GoogleCloudPlatform/kubernetes/pkg/api\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/api/rest\"\n\t\"github.com/projectatomic/atomic-enterprise/pkg/image/api\"\n)\n\n\ntype Registry interface {\n\tGetImageStreamTag(ctx kapi.Context, nameAndTag string) (*api.ImageStreamTag, error)\n\tDeleteImageStreamTag(ctx kapi.Context, nameAndTag string) (*kapi.Status, error)\n}\n\n\ntype Storage interface {\n\trest.Deleter\n\trest.Getter\n}\n\n\ntype storage struct {\n\tStorage\n}\n\n\n\n\n\nfunc (s *storage) GetImageStreamTag(ctx kapi.Context, nameAndTag string) (*api.ImageStreamTag, error) {\n\tobj, err := s.Get(ctx, nameAndTag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*api.ImageStreamTag), nil\n}\n\nfunc (s *storage) DeleteImageStreamTag(ctx kapi.Context, nameAndTag string) (*kapi.Status, error) {\n\tobj, err := s.Delete(ctx, nameAndTag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*kapi.Status), err\n}\n\nfunc NewRegistry(s Storage) Registry ", "output": "{\n\treturn &storage{s}\n}"} {"input": "package config\n\nimport (\n\tcb \"github.com/hyperledger/fabric/protos/common\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n\t\"github.com/hyperledger/fabric/protos/utils\"\n)\n\nfunc ordererConfigGroup(key string, value []byte) *cb.ConfigGroup {\n\tresult := cb.NewConfigGroup()\n\tresult.Groups[OrdererGroupKey] = cb.NewConfigGroup()\n\tresult.Groups[OrdererGroupKey].Values[key] = &cb.ConfigValue{\n\t\tValue: value,\n\t}\n\treturn result\n}\n\n\nfunc TemplateConsensusType(typeValue string) *cb.ConfigGroup {\n\treturn ordererConfigGroup(ConsensusTypeKey, utils.MarshalOrPanic(&ab.ConsensusType{Type: typeValue}))\n}\n\n\nfunc TemplateBatchSize(batchSize *ab.BatchSize) *cb.ConfigGroup {\n\treturn ordererConfigGroup(BatchSizeKey, utils.MarshalOrPanic(batchSize))\n}\n\n\nfunc TemplateBatchTimeout(batchTimeout string) *cb.ConfigGroup {\n\treturn ordererConfigGroup(BatchTimeoutKey, utils.MarshalOrPanic(&ab.BatchTimeout{Timeout: batchTimeout}))\n}\n\n\nfunc TemplateChannelRestrictions(maxChannels uint64) *cb.ConfigGroup {\n\treturn ordererConfigGroup(ChannelRestrictionsKey, utils.MarshalOrPanic(&ab.ChannelRestrictions{MaxCount: maxChannels}))\n}\n\n\n\n\nfunc TemplateKafkaBrokers(brokers []string) *cb.ConfigGroup ", "output": "{\n\treturn ordererConfigGroup(KafkaBrokersKey, utils.MarshalOrPanic(&ab.KafkaBrokers{Brokers: brokers}))\n}"} {"input": "package test\n\nimport \"github.com/tidepool-org/platform/test\"\n\nfunc NewServiceSecret() string {\n\treturn test.RandomStringFromRangeAndCharset(128, 128, test.CharsetAlphaNumeric)\n}\n\nfunc NewAccessToken() string {\n\treturn test.RandomStringFromRangeAndCharset(256, 256, test.CharsetAlphaNumeric)\n}\n\nfunc NewSessionToken() string {\n\treturn test.RandomStringFromRangeAndCharset(256, 256, test.CharsetAlphaNumeric)\n}\n\n\n\nfunc NewRestrictedToken() string ", "output": "{\n\treturn test.RandomStringFromRangeAndCharset(40, 40, test.CharsetAlphaNumeric)\n}"} {"input": "package service\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"k8s.io/apiserver/pkg/server\"\n\t\"k8s.io/klog/v2\"\n\n\t\"golang.org/x/sys/windows\"\n\t\"golang.org/x/sys/windows/svc\"\n)\n\nvar (\n\tservice *handler\n)\n\ntype handler struct {\n\ttosvc chan bool\n\tfromsvc chan error\n}\n\n\n\n\n\n\nfunc (h *handler) Execute(_ []string, r <-chan svc.ChangeRequest, s chan<- svc.Status) (bool, uint32) {\n\ts <- svc.Status{State: svc.StartPending, Accepts: 0}\n\th.fromsvc <- nil\n\n\ts <- svc.Status{State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptShutdown | svc.Accepted(windows.SERVICE_ACCEPT_PARAMCHANGE)}\n\tklog.Infof(\"Service running\")\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-h.tosvc:\n\t\t\tbreak Loop\n\t\tcase c := <-r:\n\t\t\tswitch c.Cmd {\n\t\t\tcase svc.Cmd(windows.SERVICE_CONTROL_PARAMCHANGE):\n\t\t\t\ts <- c.CurrentStatus\n\t\t\tcase svc.Interrogate:\n\t\t\t\ts <- c.CurrentStatus\n\t\t\tcase svc.Stop, svc.Shutdown:\n\t\t\t\tklog.Infof(\"Service stopping\")\n\t\t\t\tgraceful := server.RequestShutdown()\n\n\t\t\t\ts <- svc.Status{State: svc.StopPending}\n\n\t\t\t\tif !graceful {\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\t\t\tos.Exit(0)\n\t\t\t\t\t}()\n\t\t\t\t}\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false, 0\n}\n\nfunc InitService(serviceName string) error ", "output": "{\n\th := &handler{\n\t\ttosvc: make(chan bool),\n\t\tfromsvc: make(chan error),\n\t}\n\n\tservice = h\n\tvar err error\n\tgo func() {\n\t\terr = svc.Run(serviceName, h)\n\t\th.fromsvc <- err\n\t}()\n\n\terr = <-h.fromsvc\n\tif err != nil {\n\t\treturn err\n\t}\n\tklog.Infof(\"Running %s as a Windows service!\", serviceName)\n\treturn nil\n}"} {"input": "package service\n\nimport (\n\t\"context\"\n\n\t\"github.com/aws/aws-sdk-go/aws/session\"\n\t\"github.com/aws/aws-sdk-go/service/s3\"\n)\n\n\ntype AWS interface {\n\tS3get(bucket, key string, rangeHeader *string) (*s3.GetObjectOutput, error)\n\tS3listObjects(bucket, prefix string) (*s3.ListObjectsOutput, error)\n}\n\ntype client struct {\n\tcontext.Context\n\t*session.Session\n}\n\n\n\n\nfunc NewClient(ctx context.Context, region *string) AWS ", "output": "{\n\treturn client{Context: ctx, Session: awsSession(region)}\n}"} {"input": "package models\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype Application struct {\n\tID int64 `json:\"id\"`\n\tName string `json:\"name\"`\n\tMaintainerID int64 `json:\"maintainerID\"`\n\tSecret string `json:\"-\"`\n\tCallback string `json:\"callback\"`\n\tActive bool `json:\"active\"`\n}\n\n\nfunc NewApplication(name string, maintainer int64, secret string, callback string, active bool) *Application {\n\tapplication := &Application{\n\t\tID: -1,\n\t\tName: name,\n\t\tMaintainerID: maintainer,\n\t\tSecret: secret,\n\t\tCallback: callback,\n\t\tActive: active,\n\t}\n\n\treturn application\n}\n\n\n\n\nfunc (application *Application) String() string ", "output": "{\n\tjsonContent, err := json.Marshal(application)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn string(jsonContent)\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvalidate(\"aaaaa\", \"aaaaa\", true)\n\tvalidate(\"aaaab\", \"aaaab\", true)\n\tvalidate(\"aaaabc\", \"aaaab\", false)\n\tvalidate(\"aaaa\", \"a*\", true)\n\tvalidate(\"aaaabbb\", \"a*bbb\", true)\n}\n\n\n\nfunc IsMatch(s string, p string) bool {\n\tif len(p) == 0 {\n\t\treturn len(s) == 0\n\t}\n\tfirst := len(s) != 0 && (s[0] == p[0] || p[0] == '.')\n\tif len(p) > 1 && p[1] == '*' {\n\t\treturn (first && IsMatch(s[1:], p)) || (IsMatch(s, p[2:]))\n\t}\n\treturn first && IsMatch(s[1:], p[1:])\n}\n\nfunc validate(s string, p string, want bool) ", "output": "{\n\tfmt.Printf(\"s: %s, p: %s, want: %t, got: %t\\n\", s, p, want, IsMatch(s, p))\n}"} {"input": "package utils\n\nimport (\n\t\"sync\"\n)\n\ntype BeeMap struct {\n\tlock *sync.RWMutex\n\tbm map[interface{}]interface{}\n}\n\n\n\n\n\nfunc (m *BeeMap) Get(k interface{}) interface{} {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\tif val, ok := m.bm[k]; ok {\n\t\treturn val\n\t}\n\treturn nil\n}\n\n\n\nfunc (m *BeeMap) Set(k interface{}, v interface{}) bool {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tif val, ok := m.bm[k]; !ok {\n\t\tm.bm[k] = v\n\t} else if val != v {\n\t\tm.bm[k] = v\n\t} else {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\nfunc (m *BeeMap) Check(k interface{}) bool {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\tif _, ok := m.bm[k]; !ok {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\nfunc (m *BeeMap) Delete(k interface{}) {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tdelete(m.bm, k)\n}\n\n\nfunc (m *BeeMap) Items() map[interface{}]interface{} {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\treturn m.bm\n}\n\nfunc NewBeeMap() *BeeMap ", "output": "{\n\treturn &BeeMap{\n\t\tlock: new(sync.RWMutex),\n\t\tbm: make(map[interface{}]interface{}),\n\t}\n}"} {"input": "package cwxstatgo\n\nimport (\n\t\"testing\"\n)\n\n\n\n\nfunc TestCwxstatgo(t *testing.T) ", "output": "{\n\tvar h *Tree\n\ta := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n\th = Insert(h, a)\n\tWalkerRun(h)\n\n\tif Add(h) != 55 {\n\t\tt.Error(\"Add(h): Expected 55, got \", Add(h))\n\t}\n\tif Nodes(h) != 6 {\n\t\tt.Error(\"Nodes(h): Expected 6, got \", Nodes(h))\n\t}\n\n}"} {"input": "package eval_test\n\nimport (\n\t\"fmt\"\n\t\"github.com/mailgun/godebug/Godeps/_workspace/src/github.com/0xfaded/eval\" \n\t\"go/parser\"\n\t\"reflect\"\n)\n\nconst constant1 = \"A constant\"\n\n\n\nfunc ExampleSimple() {\n\tresult, panik, compileErrs := eval.Eval(`append([]int{1,2}[:1], map[int]int{1:2}[1])[1]`)\n\t_ = panik\n\t_ = compileErrs\n\tfmt.Printf(\"%+v\\n\", result[0].Interface())\n}\n\nfunc ExampleWithEnvironment() {\n\tenv := makeEnv() \n\tresult, panik, compileErrs := eval.EvalEnv(`fmt.Sprintf(\"%s %d\", constant1, add(var1, 1) + 1)`, env)\n\t_ = panik\n\t_ = compileErrs\n\tfmt.Printf(\"%+v\\n\", result[0].Interface())\n}\n\n\n\n\n\n\nfunc ExampleFullApi() {\n\texpr := `fmt.Sprintf(\"%s %d\", constant1, add(var1, 1) + 1)`\n\tenv := makeEnv() \n\tif e, err := parser.ParseExpr(expr); err != nil {\n\t\tfmt.Printf(\"Failed to parse expression '%s' (%v)\\n\", expr, err)\n\t} else if cexpr, errs := eval.CheckExpr(e, env); len(errs) != 0 {\n\t\tfmt.Printf(\"Error checking expression '%s' (%v)\\n\", expr, errs)\n\t} else if results, err := eval.EvalExpr(cexpr, env); err != nil {\n\t\tfmt.Printf(\"Panic evaluating expression '%s' (%v)\\n\", expr, err)\n\t} else {\n\t\tfmt.Printf(\"Expression '%s' yielded '%+v'\\n\", expr, results[0].Interface())\n\t}\n}\n\nfunc makeEnv() *eval.SimpleEnv ", "output": "{\n\tenv := eval.MakeSimpleEnv()\n\tenv.Consts[\"constant1\"] = reflect.ValueOf(constant1)\n\tvar1 := 1\n\tenv.Vars[\"var1\"] = reflect.ValueOf(&var1)\n\tenv.Funcs[\"add\"] = reflect.ValueOf(func(a, b int) int { return a + b })\n\tfmtPkg := eval.MakeSimpleEnv()\n\tfmtPkg.Funcs[\"Sprintf\"] = reflect.ValueOf(fmt.Sprintf)\n\tenv.Pkgs[\"fmt\"] = fmtPkg\n\treturn env\n\n}"} {"input": "package http_auth\n\nimport \"crypto/rand\"\nimport \"fmt\"\nimport \"sync\"\nimport \"time\"\n\ntype Server struct {\n\tsync.Mutex\n\tAuthFun func(user, realm string) string\n\topaque string\n\tRealm string\n\tReaperWaitSeconds, ReapTTLSeconds int\n\trequests map[string]*reqState\n}\ntype reqState struct {\n\tnreq int\n\tsectime int64\n}\n\nfunc newServer(realm string, authfun func(user, realm string) string) *Server {\n\ts := new(Server)\n\ts.Realm = realm\n\ts.opaque = newNonce()\n\ts.AuthFun = authfun\n\ts.requests = map[string]*reqState{}\n\ts.ReaperWaitSeconds = 600\n\ts.ReapTTLSeconds = 3600\n\tgo reaper(s)\n\n\treturn s\n}\n\nfunc newNonce() string {\n\tb := make([]byte, 8)\n\tn, e := rand.Read(b)\n\tif n != 8 || e != nil {\n\t\tpanic(\"rand.Reader failed!\")\n\t}\n\treturn fmt.Sprintf(\"%x\", b)\n}\n\n\n\nfunc do_reap(s *Server) {\n\tnow := time.Now().UnixNano()\n\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tfor k, v := range s.requests {\n\t\tif v.sectime+int64(s.ReapTTLSeconds) < now {\n\t\t\tdelete(s.requests, k)\n\t\t}\n\t}\n}\n\nfunc reaper(s *Server) ", "output": "{\n\tfor {\n\t\ttime.Sleep(time.Duration(s.ReaperWaitSeconds) * time.Second)\n\t\tdo_reap(s)\n\t}\n}"} {"input": "package main\n\n\n\n\nfunc Swap(a, b int64) (int64, int64) ", "output": "{\n\tswapFlag := (a - b) >> 63\n\n\treturn b*(1+swapFlag) - a*swapFlag, a*(1+swapFlag) - b*swapFlag\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/speedland/go/x/xtime\"\n)\n\n\n\ntype ServiceConfig struct {\n\tKey string `json:\"key\" ent:\"id\"`\n\tValue string `json:\"value\" ent:\"form\" datastore:\",noindex\"`\n\tUpdatedAt time.Time `json:\"updated_at\" ent:\"timestamp\" datastore:\",noindex\"`\n\n\tDescription string `json:\"description\" datastore:\"-\"`\n\tDefaultValue string `json:\"default_value\" datastore:\"-\"`\n\tGlobalValue string `json:\"global_value\" datastore:\"-\"`\n\tisGlobal bool \n}\n\n\n\nfunc newServiceConfig(key string, value string, description string) *ServiceConfig ", "output": "{\n\treturn &ServiceConfig{\n\t\tKey: key,\n\t\tValue: value,\n\t\tDescription: description,\n\t\tUpdatedAt: xtime.Now(),\n\t}\n}"} {"input": "package prometheus\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"text/template\"\n\n\t\"github.com/pkg/errors\"\n\n\ttm \"github.com/supergiant/control/pkg/templatemanager\"\n\t\"github.com/supergiant/control/pkg/workflows/steps\"\n)\n\nconst StepName = \"prometheus\"\n\ntype Config struct {\n\tRBACEnabled bool\n}\n\ntype Step struct {\n\tscript *template.Template\n}\n\nfunc (s *Step) Rollback(context.Context, io.Writer, *steps.Config) error {\n\treturn nil\n}\n\n\n\nfunc New(script *template.Template) *Step {\n\tt := &Step{\n\t\tscript: script,\n\t}\n\n\treturn t\n}\n\nfunc (s *Step) Run(ctx context.Context, out io.Writer, config *steps.Config) error {\n\terr := steps.RunTemplate(ctx, s.script, config.Runner, out, toStepCfg(config))\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"install prometheus step\")\n\t}\n\n\treturn nil\n}\n\nfunc (s *Step) Name() string {\n\treturn StepName\n}\n\nfunc (s *Step) Description() string {\n\treturn \"Install prometheus\"\n}\n\nfunc (s *Step) Depends() []string {\n\treturn nil\n}\n\nfunc toStepCfg(c *steps.Config) Config {\n\treturn Config{\n\t\tRBACEnabled: c.Kube.RBACEnabled,\n\t}\n}\n\nfunc Init() ", "output": "{\n\ttpl, err := tm.GetTemplate(StepName)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"template %s not found\", StepName))\n\t}\n\n\tsteps.RegisterStep(StepName, New(tpl))\n}"} {"input": "package packet_proxy\n\nimport (\n\t\"github.com/bettercap/bettercap/session\"\n)\n\ntype PacketProxy struct {\n\tsession.SessionModule\n}\n\nfunc NewPacketProxy(s *session.Session) *PacketProxy {\n\treturn &PacketProxy{\n\t\tSessionModule: session.NewSessionModule(\"packet.proxy\", s),\n\t}\n}\n\n\n\nfunc (mod PacketProxy) Description() string {\n\treturn \"Not supported on this OS\"\n}\n\nfunc (mod PacketProxy) Author() string {\n\treturn \"Simone Margaritelli \"\n}\n\nfunc (mod *PacketProxy) Configure() (err error) {\n\treturn session.ErrNotSupported\n}\n\nfunc (mod *PacketProxy) Start() error {\n\treturn session.ErrNotSupported\n}\n\nfunc (mod *PacketProxy) Stop() error {\n\treturn session.ErrNotSupported\n}\n\nfunc (mod PacketProxy) Name() string ", "output": "{\n\treturn \"packet.proxy\"\n}"} {"input": "package api\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/resource\"\n)\n\n\nfunc (self ResourceName) String() string {\n\treturn string(self)\n}\n\n\nfunc (self *ResourceList) Cpu() *resource.Quantity {\n\tif val, ok := (*self)[ResourceCPU]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{}\n}\n\n\nfunc (self *ResourceList) Memory() *resource.Quantity {\n\tif val, ok := (*self)[ResourceMemory]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{}\n}\n\nfunc (self *ResourceList) Pods() *resource.Quantity {\n\tif val, ok := (*self)[ResourcePods]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{}\n}\n\nfunc GetContainerStatus(statuses []ContainerStatus, name string) (ContainerStatus, bool) {\n\tfor i := range statuses {\n\t\tif statuses[i].Name == name {\n\t\t\treturn statuses[i], true\n\t\t}\n\t}\n\treturn ContainerStatus{}, false\n}\n\nfunc GetExistingContainerStatus(statuses []ContainerStatus, name string) ContainerStatus {\n\tfor i := range statuses {\n\t\tif statuses[i].Name == name {\n\t\t\treturn statuses[i]\n\t\t}\n\t}\n\treturn ContainerStatus{}\n}\n\n\n\n\nfunc IsPodReady(pod *Pod) bool ", "output": "{\n\tfor _, c := range pod.Status.Conditions {\n\t\tif c.Type == PodReady && c.Status == ConditionTrue {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package model\n\nimport (\n\t\"time\"\n\n\tjwt \"github.com/dgrijalva/jwt-go\"\n)\n\ntype Session struct {\n\tID string `gorethink:\"id,omitempty\"json:\"id\"`\n\tToken string `gorethink:\"token\"json:\"token\"`\n\tUserID string `gorethink:\"userId\"json:\"userId\"`\n\tExpiresAt time.Time `gorethink:\"expiresAt\"json:\"expiresAt\"`\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc NewSession(u User) (Session, error) ", "output": "{\n\tvar s Session\n\ttoken := jwt.New(jwt.GetSigningMethod(\"HS256\"))\n\n\ttokenExpires := time.Now().UTC().Add(time.Hour * 72)\n\ttoken.Claims[\"id\"] = u.ID\n\ttoken.Claims[\"email\"] = u.Email\n\ttoken.Claims[\"exp\"] = tokenExpires.Unix()\n\n\ttokenString, err := token.SignedString([]byte(\"someRandomSigningKey\"))\n\tif err != nil {\n\t\treturn s, err\n\t}\n\n\ts = Session{\n\t\tToken: tokenString,\n\t\tUserID: u.ID,\n\t\tExpiresAt: tokenExpires,\n\t}\n\n\treturn s, err\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/url\"\n\n\t\"github.com/ChimeraCoder/anaconda\"\n\t\"github.com/go-ini/ini\"\n)\n\nvar Config *ini.File\n\nconst (\n\tconsumerKey = \"your key here\"\n\tconsumerSecret = \"your secret here\"\n\taccessToken = \"your token here\"\n\taccessSecret = \"your secret here\"\n\tmacAddress = \"mac address of the dash button here\"\n)\n\nfunc main() {\n\tDashMacs[macAddress] = Tweet\n\n\tSnifferStart()\n}\n\nfunc NoAction() {\n\tlog.Println(\"No action on click.\")\n}\n\nfunc Tweet() {\n\tPostTweet(\"Testing now\")\n}\n\n\n\nfunc PostTweet(tweet string) ", "output": "{\n\tanaconda.SetConsumerKey(consumerKey)\n\tanaconda.SetConsumerSecret(consumerSecret)\n\tapi := anaconda.NewTwitterApi(accessToken, accessSecret)\n\n\tv := url.Values{}\n\n\t_, err := api.PostTweet(tweet, v)\n\tif err != nil {\n\t\tlog.Println(\"We have an error now \", err)\n\t}\n\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/kubernetes-incubator/kube-aws/core/controlplane/cluster\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar (\n\tcmdVersion = &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Print version information and exit\",\n\t\tLong: ``,\n\t\tRun: runCmdVersion,\n\t}\n)\n\nfunc init() {\n\tRootCmd.AddCommand(cmdVersion)\n}\n\n\n\nfunc runCmdVersion(_ *cobra.Command, _ []string) ", "output": "{\n\tfmt.Printf(\"kube-aws version %s\\n\", cluster.VERSION)\n}"} {"input": "package mgutil\n\nimport (\n\t\"unicode/utf8\"\n)\n\n\n\n\n\nfunc RepositionRight(src []byte, pos int, cond func(rune) bool) int {\n\tfor 0 <= pos && pos < len(src) {\n\t\tr, n := utf8.DecodeRune(src[pos:])\n\t\tif n < 1 || !cond(r) {\n\t\t\tbreak\n\t\t}\n\t\tpos += n\n\t}\n\treturn pos\n}\n\nfunc RepositionLeft(src []byte, pos int, cond func(rune) bool) int ", "output": "{\n\tfor 0 <= pos && pos < len(src) {\n\t\tr, n := utf8.DecodeLastRune(src[:pos])\n\t\tif n < 1 || !cond(r) {\n\t\t\tbreak\n\t\t}\n\t\tpos -= n\n\t}\n\treturn pos\n}"} {"input": "package metrics\n\nimport (\n\t\"sync\"\n\n\tprom \"github.com/prometheus/client_golang/prometheus\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tsandboxGuageName = \"bundlelib_sandbox\"\n)\n\nvar (\n\tonce sync.Once\n\tcollector *Collector\n)\n\n\ntype Collector struct {\n\tSandbox prom.Gauge\n}\n\n\n\n\nfunc recoverMetricPanic() {\n\tif r := recover(); r != nil {\n\t\tlog.Errorf(\"Recovering from metric function - %v\", r)\n\t}\n}\n\n\n\nfunc RegisterCollector() {\n\tonce.Do(func() {\n\t\tcollector = &Collector{\n\t\t\tSandbox: prom.NewGauge(prom.GaugeOpts{\n\t\t\t\tName: sandboxGuageName,\n\t\t\t\tHelp: \"Guage of all sandbox namespaces that are active.\",\n\t\t\t}),\n\t\t}\n\n\t\terr := prom.Register(collector)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"unable to register collector with prometheus: %v\", err)\n\t\t}\n\t})\n}\n\n\nfunc SandboxCreated() {\n\tdefer recoverMetricPanic()\n\tcollector.Sandbox.Inc()\n}\n\n\n\n\n\nfunc (c Collector) Describe(ch chan<- *prom.Desc) {\n\tc.Sandbox.Describe(ch)\n}\n\n\nfunc (c Collector) Collect(ch chan<- prom.Metric) {\n\tc.Sandbox.Collect(ch)\n}\n\nfunc SandboxDeleted() ", "output": "{\n\tdefer recoverMetricPanic()\n\tcollector.Sandbox.Dec()\n}"} {"input": "package futures\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\ntype Completer <-chan interface{}\n\n\n\n\n\n\n\ntype Future struct {\n\ttriggered bool \n\titem interface{}\n\terr error\n\tlock sync.Mutex\n\twg sync.WaitGroup\n}\n\n\n\nfunc (f *Future) GetResult() (interface{}, error) {\n\tf.lock.Lock()\n\tif f.triggered {\n\t\tf.lock.Unlock()\n\t\treturn f.item, f.err\n\t}\n\tf.lock.Unlock()\n\n\tf.wg.Wait()\n\treturn f.item, f.err\n}\n\nfunc (f *Future) setItem(item interface{}, err error) {\n\tf.lock.Lock()\n\tf.triggered = true\n\tf.item = item\n\tf.err = err\n\tf.lock.Unlock()\n\tf.wg.Done()\n}\n\nfunc listenForResult(f *Future, ch Completer, timeout time.Duration, wg *sync.WaitGroup) {\n\twg.Done()\n\tselect {\n\tcase item := <-ch:\n\t\tf.setItem(item, nil)\n\tcase <-time.After(timeout):\n\t\tf.setItem(nil, fmt.Errorf(`Timeout after %f seconds.`, timeout.Seconds()))\n\t}\n}\n\n\n\n\n\n\n\nfunc New(completer Completer, timeout time.Duration) *Future ", "output": "{\n\tf := &Future{}\n\tf.wg.Add(1)\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo listenForResult(f, completer, timeout, &wg)\n\twg.Wait()\n\treturn f\n}"} {"input": "package memberlist\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\ntype Packet struct {\n\tBuf []byte\n\n\tFrom net.Addr\n\n\tTimestamp time.Time\n}\n\n\n\n\ntype Transport interface {\n\tFinalAdvertiseAddr(ip string, port int) (net.IP, int, error)\n\n\tWriteTo(b []byte, addr string) (time.Time, error)\n\n\tPacketCh() <-chan *Packet\n\n\tDialTimeout(addr string, timeout time.Duration) (net.Conn, error)\n\n\tStreamCh() <-chan net.Conn\n\n\tShutdown() error\n}\n\ntype Address struct {\n\tAddr string\n\n\tName string\n}\n\nfunc (a *Address) String() string {\n\tif a.Name != \"\" {\n\t\treturn fmt.Sprintf(\"%s (%s)\", a.Name, a.Addr)\n\t}\n\treturn a.Addr\n}\n\n\n\n\n\n\ntype IngestionAwareTransport interface {\n\tIngestPacket(conn net.Conn, addr net.Addr, now time.Time, shouldClose bool) error\n\tIngestStream(conn net.Conn) error\n}\n\ntype NodeAwareTransport interface {\n\tTransport\n\tWriteToAddress(b []byte, addr Address) (time.Time, error)\n\tDialAddressTimeout(addr Address, timeout time.Duration) (net.Conn, error)\n}\n\ntype shimNodeAwareTransport struct {\n\tTransport\n}\n\nvar _ NodeAwareTransport = (*shimNodeAwareTransport)(nil)\n\nfunc (t *shimNodeAwareTransport) WriteToAddress(b []byte, addr Address) (time.Time, error) {\n\treturn t.WriteTo(b, addr.Addr)\n}\n\n\n\nfunc (t *shimNodeAwareTransport) DialAddressTimeout(addr Address, timeout time.Duration) (net.Conn, error) ", "output": "{\n\treturn t.DialTimeout(addr.Addr, timeout)\n}"} {"input": "package broker\n\nimport (\n\troa \"github.com/apache/servicecomb-service-center/pkg/rest\"\n)\n\nfunc init() {\n\tregisterREST()\n}\n\n\n\nfunc registerREST() ", "output": "{\n\troa.RegisterServant(&Controller{})\n}"} {"input": "package github\n\nimport (\n . \"github.com/ErintLabs/trellohub/genapi\"\n \"log\"\n)\n\ntype Label struct {\n Name string `json:\"name\"`\n}\n\ntype GitUser struct {\n Name string `json:\"login\"`\n}\n\n\n\nfunc (issue *Issue) SetMembers(mbmrs []GitUser) {\n lst := make([]string, len(mbmrs))\n for i, v := range mbmrs {\n lst[i] = v.Name\n }\n issue.Members.SetNameable(lst)\n}\n\n\n\n\nfunc (issue *Issue) AddLabel(label string) {\n log.Printf(\"Adding label %s to %s\", label, issue.String())\n lbls := [...]string { label }\n GenPOSTJSON(issue.github, issue.ApiURL() + \"/labels\", nil, &lbls)\n}\n\n\nfunc (issue *Issue) DelLabel(label string) {\n log.Printf(\"Removing label %s from %s\", label, issue.String())\n GenDEL(issue.github, issue.ApiURL() + \"/labels/\" + label) \n}\n\n\ntype userAssignRequest struct {\n Assigs []string `json:\"assignees\"`\n}\n\nfunc (issue *Issue) AddUser(user string) {\n log.Printf(\"Adding user %s to %s\", user, issue.String())\n payload := userAssignRequest{ []string{ user } }\n GenPOSTJSON(issue.github, issue.ApiURL() + \"/assignees\", nil, &payload)\n}\n\n\nfunc (issue *Issue) DelUser(user string) {\n log.Printf(\"Removing user %s from %s\", user, issue.String())\n payload := userAssignRequest{ []string{ user } }\n GenDELJSON(issue.github, issue.ApiURL() + \"/assignees\", &payload)\n}\n\nfunc (issue *Issue) SetLabels(lbls []Label) ", "output": "{\n lst := make([]string, len(lbls))\n for i, v := range lbls {\n lst[i] = v.Name\n }\n issue.Labels.SetNameable(lst)\n}"} {"input": "package module\n\nimport (\n\t\"encoding/gob\"\n\t\"fmt\"\n\t\"github.com/glennyonemitsu/reicon/system/activity\"\n\t\"net\"\n\t\"os\"\n)\n\ntype Module struct {\n\tName string\n\tActivities []*activity.Activity\n\tServerSocket *net.UnixConn\n\tSocketAddr *net.UnixAddr\n\tListener *net.UnixListener\n}\n\nfunc (m *Module) Run() {\n\tsocket_path := os.Getenv(\"REICON_SYSTEM_SOCKET\")\n\tm.SocketAddr = new(net.UnixAddr)\n\tm.SocketAddr.Name = \"unix\"\n\tm.SocketAddr.Net = socket_path\n\tm.Listener, _ = net.ListenUnix(\"unix\", m.SocketAddr)\n\tm.ListenSocket()\n\n}\n\nfunc (m *Module) ListenSocket() {\n\tfor {\n\t\tconn, err := m.Listener.AcceptUnix()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tgo m.handleUnixConnection(conn)\n\t}\n}\n\n\n\nfunc (m *Module) Shutdown() {\n\tm.ServerSocket.Close()\n}\n\nfunc (m *Module) RegisterActivity(name string) *activity.Activity {\n\ta := new(activity.Activity)\n\ta.Name = name\n\tm.Activities = append(m.Activities, a)\n\treturn a\n}\n\nfunc Create(name string) *Module {\n\tm := new(Module)\n\tm.Name = name\n\treturn m\n}\n\nfunc (m *Module) handleUnixConnection(conn *net.UnixConn) ", "output": "{\n\tvar msg string\n\tenc := gob.NewEncoder(conn)\n\tdec := gob.NewDecoder(conn)\n\tdec.Decode(&msg)\n\tenc.Encode(fmt.Sprintf(\"your message was: %s\", msg))\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n)\n\ntype SecurityBulletin struct {\n\tId string `json:\"id\"`\n\tAppliesToVersion string `json:\"applies_to_version\"`\n}\n\ntype SecurityBulletins []SecurityBulletin\n\nfunc (sb *SecurityBulletin) ToJson() string {\n\tb, _ := json.Marshal(sb)\n\treturn string(b)\n}\n\nfunc SecurityBulletinFromJson(data io.Reader) *SecurityBulletin {\n\tvar o *SecurityBulletin\n\tjson.NewDecoder(data).Decode(&o)\n\treturn o\n}\n\n\n\nfunc SecurityBulletinsFromJson(data io.Reader) SecurityBulletins {\n\tvar o SecurityBulletins\n\tjson.NewDecoder(data).Decode(&o)\n\treturn o\n}\n\nfunc (sb SecurityBulletins) ToJson() string ", "output": "{\n\tb, err := json.Marshal(sb)\n\tif err != nil {\n\t\treturn \"[]\"\n\t}\n\treturn string(b)\n}"} {"input": "package meli\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nvar (\n\tclient = Client{\n\t\tClientID: 907054494590799,\n\t\tClientSecret: \"x7qFo8AudrLHEsDWm96Kwfu1xbYTiWbW\",\n\t}\n\n\tcode = \"your code\"\n\tredirectUrl = \"redirect url\"\n)\n\n\n\n\n\nfunc TestAuthorize(t *testing.T) {\n\terr := client.Authorize(code, redirectUrl)\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\n\nfunc TestRefreshAccessToken(t *testing.T) {\n\terr := client.RefreshAccessToken()\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestGetAuthUrl(t *testing.T) ", "output": "{\n\tresult, _ := client.GetAuthUrl(\"\", AuthUrls[\"MLB\"])\n\n\texpected := \"https://auth.mercadolivre.com.br/authorization?client_id=907054494590799&redirect_uri=&response_type=code\"\n\tif reflect.DeepEqual(expected, result) == false {\n\t\tt.Error(fmt.Sprintf(\"Expected: %s - Got: %s\", expected, result))\n\t}\n}"} {"input": "package sfproto\n\nimport (\n\t\"github.com/sarifsystems/sarif/sarif\"\n)\n\ntype wrappedConn struct {\n\tid string\n\tConn\n}\n\nfunc (c *wrappedConn) Publish(msg sarif.Message) error {\n\treturn c.Write(msg)\n}\n\nfunc (c *wrappedConn) Subscribe(src, action, dest string) error {\n\tmsg := Subscribe(action, dest)\n\tmsg.Source = src\n\treturn c.Publish(msg)\n}\n\nfunc (c *wrappedConn) Consume() (<-chan sarif.Message, error) {\n\tch := make(chan sarif.Message, 10)\n\n\tgo func() {\n\t\tfor {\n\t\t\tmsg, err := c.Read()\n\t\t\tif err != nil {\n\t\t\t\tclose(ch)\n\t\t\t\tc.Close()\n\t\t\t\tc.Conn = nil\n\t\t\t\treturn\n\t\t\t}\n\t\t\tch <- msg\n\t\t}\n\t}()\n\n\treturn (<-chan sarif.Message)(ch), nil\n}\n\n\n\nfunc wrap(conn Conn) sarif.Connection ", "output": "{\n\treturn &wrappedConn{sarif.GenerateId(), conn}\n}"} {"input": "package windows\n\nimport (\n\t\"github.com/docker/libnetwork/driverapi\"\n\t\"github.com/docker/libnetwork/types\"\n)\n\nconst networkType = \"windows\"\n\n\n\ntype driver struct{}\n\n\n\n\nfunc (d *driver) Config(option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) DeleteNetwork(nid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) DeleteEndpoint(nid, eid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {\n\treturn make(map[string]interface{}, 0), nil\n}\n\n\nfunc (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {\n\treturn nil\n}\n\n\nfunc (d *driver) Leave(nid, eid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) Type() string {\n\treturn networkType\n}\n\nfunc Init(dc driverapi.DriverCallback) error ", "output": "{\n\tc := driverapi.Capability{\n\t\tScope: driverapi.LocalScope,\n\t}\n\treturn dc.RegisterDriver(networkType, &driver{}, c)\n}"} {"input": "package sacloud\n\n\ntype IPv6Addr struct {\n\tHostName string `json:\",omitempty\"` \n\tIPv6Addr string `json:\",omitempty\"` \n\tInterface *Interface `json:\",omitempty\"` \n\tIPv6Net *IPv6Net `json:\",omitempty\"` \n\n}\n\n\n\n\n\nfunc (a *IPv6Addr) GetInternetID() int64 {\n\tif a.IPv6Net != nil && a.IPv6Net.Switch != nil && a.IPv6Net.Switch.Internet != nil {\n\t\treturn a.IPv6Net.Switch.Internet.ID\n\t}\n\treturn 0\n}\n\n\nfunc CreateNewIPv6Addr() *IPv6Addr {\n\treturn &IPv6Addr{\n\t\tIPv6Net: &IPv6Net{\n\t\t\tResource: &Resource{},\n\t\t},\n\t}\n}\n\nfunc (a *IPv6Addr) GetIPv6NetID() int64 ", "output": "{\n\tif a.IPv6Net != nil {\n\t\treturn a.IPv6Net.ID\n\t}\n\treturn 0\n}"} {"input": "package auth\n\nimport (\n \"github.com/gin-gonic/gin\"\n \"io/ioutil\"\n \"log\"\n \"encoding/json\"\n)\n\nfunc postLogin(c *gin.Context) {\n log.Println(\"postLogin\")\n \n sess, _ := authConf.Session.SessionStart(c.Writer, c.Request)\n defer sess.SessionRelease(c.Writer)\n\n username := c.Request.FormValue(\"username\")\n sess.Set(\"user\", username)\n\n c.String(200, \"hello %s\", username)\n}\n\n\n\nfunc postLogin1(c *gin.Context) ", "output": "{\n\n log.Println(authConf)\n\n body, err := ioutil.ReadAll(c.Request.Body)\n if err != nil {\n log.Println(err)\n c.Abort()\n }\n\n sess, _ := authConf.Session.SessionStart(c.Writer, c.Request)\n defer sess.SessionRelease(c.Writer)\n log.Println(\"SessionStart\")\n\n log.Println(string(body))\n\n data := make(map[string]string)\n err = json.Unmarshal(body, &data)\n if err != nil {\n c.AbortWithError(500, err)\n }\n\n log.Println(data)\n sess.Set(\"user\", data[\"user\"])\n\n}"} {"input": "package v1alpha1\n\nimport (\n\tv1alpha1 \"k8s.io/api/scheduling/v1alpha1\"\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\t\"github.com/hyperhq/client-go/kubernetes/scheme\"\n\trest \"github.com/hyperhq/client-go/rest\"\n)\n\ntype SchedulingV1alpha1Interface interface {\n\tRESTClient() rest.Interface\n\tPriorityClassesGetter\n}\n\n\ntype SchedulingV1alpha1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *SchedulingV1alpha1Client) PriorityClasses() PriorityClassInterface {\n\treturn newPriorityClasses(c)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*SchedulingV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SchedulingV1alpha1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *SchedulingV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\n\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *SchedulingV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc New(c rest.Interface) *SchedulingV1alpha1Client ", "output": "{\n\treturn &SchedulingV1alpha1Client{c}\n}"} {"input": "package jit\n\nconst SUPPORTED = true\n\n\n\nfunc (asm *Asm) epilogue() *Asm {\n\treturn asm.Bytes(0xc3) \n}\n\nfunc (asm *Asm) prologue() *Asm ", "output": "{\n\treturn asm.Bytes(0x48, 0x8b, 0x7c, 0x24, 0x08) \n}"} {"input": "package goweb\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc deprecatedPanic(method, alternativeTip string) {\n\tpanic(fmt.Sprintf(\"goweb: (deprecated) %s is no longer supported. %s\", method, alternativeTip))\n}\n\n\n\n\n\n\n\n\n\nfunc MapRest(pathPrefix string, controller interface{}) {\n\tdeprecatedPanic(\"MapRest\", \"Use goweb.MapController instead.\")\n}\n\nfunc MapFunc(path string, controllerFunc interface{}, matcherFuncs ...interface{}) interface{} ", "output": "{\n\tdeprecatedPanic(\"MapFunc\", \"Use goweb.Map instead.\")\n\treturn nil\n}"} {"input": "package context_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestAppConfigHelpers(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"types/context Suite\")\n}"} {"input": "package testclient\n\nimport (\n\t\"github.com/uber-go/dosa\"\n\t\"github.com/uber-go/dosa/connectors/memory\"\n)\n\n\n\n\nfunc NewTestClient(scope, prefix string, entities ...dosa.DomainObject) (dosa.Client, error) ", "output": "{\n\treg, err := dosa.NewRegistrar(scope, prefix, entities...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconnector := memory.NewConnector()\n\treturn dosa.NewClient(reg, connector), nil\n}"} {"input": "package header\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/google/martian/v3/proxyutil\"\n)\n\n\n\ntype Matcher struct {\n\tname, value string\n}\n\n\nfunc NewMatcher(name, value string) *Matcher {\n\treturn &Matcher{\n\t\tname: name,\n\t\tvalue: value,\n\t}\n}\n\n\n\n\n\n\n\n\n\nfunc (m *Matcher) MatchResponse(res *http.Response) bool {\n\th := proxyutil.ResponseHeader(res)\n\n\tvs, ok := h.All(m.name)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tfor _, v := range vs {\n\t\tif v == m.value {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (m *Matcher) MatchRequest(req *http.Request) bool ", "output": "{\n\th := proxyutil.RequestHeader(req)\n\n\tvs, ok := h.All(m.name)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tfor _, v := range vs {\n\t\tif v == m.value {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package disk\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/vslm\"\n)\n\ntype register struct {\n\t*flags.DatastoreFlag\n}\n\nfunc init() {\n\tcli.Register(\"disk.register\", ®ister{})\n}\n\nfunc (cmd *register) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)\n\tcmd.DatastoreFlag.Register(ctx, f)\n}\n\nfunc (cmd *register) Usage() string {\n\treturn \"PATH [NAME]\"\n}\n\n\n\nfunc (cmd *register) Run(ctx context.Context, f *flag.FlagSet) error {\n\tds, err := cmd.Datastore()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm := vslm.NewObjectManager(ds.Client())\n\n\tpath := ds.NewURL(f.Arg(0)).String()\n\n\tobj, err := m.RegisterDisk(ctx, path, f.Arg(1))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(obj.Config.Id.Id)\n\n\treturn nil\n}\n\nfunc (cmd *register) Description() string ", "output": "{\n\treturn `Register existing disk on DS.\n\nExamples:\n govc disk.register disks/disk1.vmdk my-disk`\n}"} {"input": "package manager\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/consul-template/config\"\n\tdep \"github.com/hashicorp/consul-template/dependency\"\n\t\"github.com/hashicorp/consul-template/template\"\n\t\"github.com/hashicorp/consul/testutil\"\n)\n\nvar testConsul *testutil.TestServer\nvar testClients *dep.ClientSet\n\nfunc TestMain(m *testing.M) {\n\tconsul, err := testutil.NewTestServerConfig(func(c *testutil.TestServerConfig) {\n\t\tc.LogLevel = \"warn\"\n\t})\n\tif err != nil {\n\t\tlog.Fatal(\"failed to start consul server\")\n\t}\n\ttestConsul = consul\n\n\tclients := dep.NewClientSet()\n\tif err := clients.CreateConsulClient(&dep.CreateConsulClientInput{\n\t\tAddress: testConsul.HTTPAddr,\n\t}); err != nil {\n\t\ttestConsul.Stop()\n\t\tlog.Fatal(err)\n\t}\n\ttestClients = clients\n\n\texitCh := make(chan int, 1)\n\tfunc() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\ttestConsul.Stop()\n\t\t\t\tpanic(r)\n\t\t\t}\n\t\t}()\n\n\t\texitCh <- m.Run()\n\t}()\n\n\texit := <-exitCh\n\n\ttestConsul.Stop()\n\tos.Exit(exit)\n}\n\n\n\nfunc testDedupManager(t *testing.T, tmpls []*template.Template) *DedupManager ", "output": "{\n\tbrain := template.NewBrain()\n\tdedupConfig := config.TestConfig(nil).Dedup\n\tdedup, err := NewDedupManager(dedupConfig, testClients, brain, tmpls)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn dedup\n}"} {"input": "package vfs\n\nimport (\n\t\"path\"\n\n\tgofig \"github.com/akutz/gofig/types\"\n\n\t\"github.com/codedellemc/rexray/libstorage/api/context\"\n\t\"github.com/codedellemc/rexray/libstorage/api/registry\"\n\t\"github.com/codedellemc/rexray/libstorage/api/types\"\n)\n\nconst (\n\tName = \"vfs\"\n)\n\nfunc init() {\n\tregistry.RegisterConfigReg(\n\t\t\"VFS\",\n\t\tfunc(ctx types.Context, r gofig.ConfigRegistration) {\n\t\t\tvfsRoot := path.Join(context.MustPathConfig(ctx).Lib, \"vfs\")\n\t\t\tr.Key(\n\t\t\t\tgofig.String,\n\t\t\t\t\"\",\n\t\t\t\tvfsRoot,\n\t\t\t\t\"\",\n\t\t\t\t\"vfs.root\")\n\t\t})\n}\n\n\n\n\n\nfunc DeviceFilePath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"dev\")\n}\n\n\nfunc VolumesDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"vol\")\n}\n\n\nfunc SnapshotsDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"snap\")\n}\n\nfunc RootDir(config gofig.Config) string ", "output": "{\n\treturn config.GetString(\"vfs.root\")\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"github.com/docker/distribution/registry/api/errcode\"\n\t\"github.com/docker/distribution/registry/api/v2\"\n)\n\n\n\ntype UnexpectedHTTPStatusError struct {\n\tStatus string\n}\n\n\n\n\n\ntype UnexpectedHTTPResponseError struct {\n\tParseErr error\n\tResponse []byte\n}\n\nfunc (e *UnexpectedHTTPResponseError) Error() string {\n\treturn fmt.Sprintf(\"Error parsing HTTP response: %s: %q\", e.ParseErr.Error(), string(e.Response))\n}\n\nfunc parseHTTPErrorResponse(r io.Reader) error {\n\tvar errors errcode.Errors\n\tbody, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(body, &errors); err != nil {\n\t\treturn &UnexpectedHTTPResponseError{\n\t\t\tParseErr: err,\n\t\t\tResponse: body,\n\t\t}\n\t}\n\treturn errors\n}\n\nfunc handleErrorResponse(resp *http.Response) error {\n\tif resp.StatusCode == 401 {\n\t\terr := parseHTTPErrorResponse(resp.Body)\n\t\tif uErr, ok := err.(*UnexpectedHTTPResponseError); ok {\n\t\t\treturn v2.ErrorCodeUnauthorized.WithDetail(uErr.Response)\n\t\t}\n\t\treturn err\n\t}\n\tif resp.StatusCode >= 400 && resp.StatusCode < 500 {\n\t\treturn parseHTTPErrorResponse(resp.Body)\n\t}\n\treturn &UnexpectedHTTPStatusError{Status: resp.Status}\n}\n\nfunc (e *UnexpectedHTTPStatusError) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"Received unexpected HTTP status: %s\", e.Status)\n}"} {"input": "package conv\n\nimport (\n\t\"reflect\"\n)\n\n\n\nfunc UintPtrTo64(ptr interface{}) (value uint64) {\n\tif v := reflect.ValueOf(ptr); v.Kind() == reflect.Ptr {\n\t\tp := v.Elem()\n\t\tswitch p.Kind() {\n\t\tcase reflect.Uint:\n\t\t\tvalue = uint64(*ptr.(*uint))\n\t\tcase reflect.Uint8:\n\t\t\tvalue = uint64(*ptr.(*uint8))\n\t\tcase reflect.Uint16:\n\t\t\tvalue = uint64(*ptr.(*uint16))\n\t\tcase reflect.Uint32:\n\t\t\tvalue = uint64(*ptr.(*uint32))\n\t\tcase reflect.Uint64:\n\t\t\tvalue = *ptr.(*uint64)\n\t\t}\n\t}\n\treturn\n}\n\nfunc IntPtrTo64(ptr interface{}) (value int64) ", "output": "{\n\tif v := reflect.ValueOf(ptr); v.Kind() == reflect.Ptr {\n\t\tp := v.Elem()\n\t\tswitch p.Kind() {\n\t\tcase reflect.Int:\n\t\t\tvalue = int64(*ptr.(*int))\n\t\tcase reflect.Int8:\n\t\t\tvalue = int64(*ptr.(*int8))\n\t\tcase reflect.Int16:\n\t\t\tvalue = int64(*ptr.(*int16))\n\t\tcase reflect.Int32:\n\t\t\tvalue = int64(*ptr.(*int32))\n\t\tcase reflect.Int64:\n\t\t\tvalue = *ptr.(*int64)\n\t\t}\n\t}\n\treturn\n}"} {"input": "package vmware\n\nfunc NewDatasource(fileName string) *VMWare {\n\treturn &VMWare{}\n}\n\n\n\nfunc (v VMWare) IsAvailable() bool ", "output": "{\n\treturn false\n}"} {"input": "package dynamo\n\nimport (\n\t\"errors\"\n\n\t\"golang.org/x/crypto/acme/autocert\"\n)\n\n\ntype Provider struct {\n\tclient *client\n}\n\n\nfunc NewProvider() *Provider {\n\treturn new(Provider)\n}\n\n\nfunc (p *Provider) Name() string {\n\treturn \"dynamodb\"\n}\n\n\nfunc (p *Provider) Configure(config map[string]interface{}) (err error) {\n\tconst prefix = \"unable to configure DynamoDB provider\"\n\tif config == nil {\n\t\treturn errors.New(prefix + \", no configuration provided\")\n\t}\n\n\tregion := get(config, \"region\", \"\")\n\tif region == \"\" {\n\t\treturn errors.New(prefix + \", no AWS Region was specified\")\n\t}\n\n\ttable := get(config, \"table\", \"\")\n\tif table == \"\" {\n\t\treturn errors.New(prefix + \", no Table Name was specified\")\n\t}\n\n\tkeyColumn := get(config, \"keyColumn\", \"key\")\n\tvalColumn := get(config, \"valueColumn\", \"value\")\n\n\tif p.client, err = newClient(region, table, keyColumn, valColumn); err == nil {\n\t\tif _, err := p.client.Get(\"testkey\"); err == nil && err == errKeyNotFound {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn err\n}\n\n\nfunc (p *Provider) GetSecret(secretName string) (string, bool) {\n\tif p.client != nil {\n\t\tif value, err := p.client.Get(secretName); err == nil {\n\t\t\treturn value, true\n\t\t}\n\t}\n\n\treturn \"\", false\n}\n\n\nfunc (p *Provider) GetCache() (autocert.Cache, bool) {\n\tif p.client != nil {\n\t\treturn newCache(p.client), true\n\t}\n\n\treturn nil, false\n}\n\n\n\n\nfunc get(config map[string]interface{}, key, defaultValue string) string ", "output": "{\n\tif v, ok := config[key]; ok {\n\t\tif s, ok := v.(string); ok {\n\t\t\treturn s\n\t\t}\n\t}\n\treturn defaultValue\n}"} {"input": "package api\n\ntype Capture struct {\n\tProbePath string `json:\"ProbePath,omitempty\"`\n\tBPFFilter string `json:\"BPFFilter,omitempty\"`\n}\n\ntype CaptureHandler struct {\n}\n\nfunc NewCapture(probePath string, bpfFilter string) *Capture {\n\treturn &Capture{\n\t\tProbePath: probePath,\n\t\tBPFFilter: bpfFilter,\n\t}\n}\n\nfunc (c *CaptureHandler) New() ApiResource {\n\treturn &Capture{}\n}\n\nfunc (c *CaptureHandler) Name() string {\n\treturn \"capture\"\n}\n\n\n\nfunc (c *Capture) ID() string ", "output": "{\n\treturn c.ProbePath\n}"} {"input": "package minicon\n\nimport \"container/ring\"\n\n\n\n\ntype History struct {\n\tr *ring.Ring\n}\n\n\n\n\ntype HistoryMarker *ring.Ring\n\n\n\n\nfunc NewHistory(capacity int) *History {\n\treturn &History{ring.New(capacity)}\n}\n\n\n\n\n\n\nfunc (hs *History) Add(s string, mark HistoryMarker) HistoryMarker {\n\ths.Restore(mark)\n\tif s != \"\" && hs.r.Value != s {\n\t\ths.r.Value = s\n\t\ths.r = hs.r.Next()\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (hs *History) Back() (string, bool) {\n\treturn hs._update(hs.r.Prev())\n}\n\n\n\n\n\nfunc (hs *History) Forward() (string, bool) {\n\treturn hs._update(hs.r.Next())\n}\n\n\n\n\nfunc (hs *History) Mark() HistoryMarker {\n\treturn hs.r\n}\n\n\n\n\n\n\n\n\n\nfunc (hs *History) _update(r *ring.Ring) (ret string, okay bool) {\n\tif s, ok := r.Value.(string); ok && s != \"\" {\n\t\ths.r = r\n\t\tret, okay = s, ok\n\t}\n\treturn ret, okay\n}\n\nfunc (hs *History) Restore(mark HistoryMarker) ", "output": "{\n\tif mark != nil {\n\t\ths.r = mark\n\t}\n}"} {"input": "package resourser\n\nimport (\n\t\"github.com/golang/lint\"\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestFsiter_Init(t *testing.T) ", "output": "{\n\tos.RemoveAll(`/tmp/test-project-234`)\n\titer := &fsiter{id: `test-project-234`, uri: `https://github.com/lintflow/golang-test-project.git`}\n\tcount, err := iter.Init()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif count != 2 {\n\t\tt.Errorf(`expected count like 2, but - %d`, count)\n\t}\n\tlinter := new(lint.Linter)\n\titerCount := 0\n\tfor iter.Next() {\n\t\titerCount++\n\t\tname, blob := iter.File()\n\t\tproblems, _ := linter.Lint(name, blob)\n\t\tif len(problems) == 0 {\n\t\t\tt.Errorf(`expected problems not equals == 0`)\n\t\t}\n\t}\n\tif iterCount != count {\n\t\tt.Errorf(` %d != %d`, count, iterCount)\n\t}\n}"} {"input": "package install\n\nimport (\n\t\"k8s.io/apimachinery/pkg/apimachinery/announced\"\n\t\"k8s.io/apimachinery/pkg/apimachinery/registered\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/client-go/pkg/api\"\n\t\"k8s.io/client-go/pkg/apis/autoscaling\"\n\t\"k8s.io/client-go/pkg/apis/autoscaling/v1\"\n)\n\nfunc init() {\n\tInstall(api.GroupFactoryRegistry, api.Registry, api.Scheme)\n}\n\n\n\n\nfunc Install(groupFactoryRegistry announced.APIGroupFactoryRegistry, registry *registered.APIRegistrationManager, scheme *runtime.Scheme) ", "output": "{\n\tif err := announced.NewGroupMetaFactory(\n\t\t&announced.GroupMetaFactoryArgs{\n\t\t\tGroupName: autoscaling.GroupName,\n\t\t\tVersionPreferenceOrder: []string{v1.SchemeGroupVersion.Version},\n\t\t\tImportPrefix: \"k8s.io/client-go/pkg/apis/autoscaling\",\n\t\t\tAddInternalObjectsToScheme: autoscaling.AddToScheme,\n\t\t},\n\t\tannounced.VersionToSchemeFunc{\n\t\t\tv1.SchemeGroupVersion.Version: v1.AddToScheme,\n\t\t},\n\t).Announce(groupFactoryRegistry).RegisterAndEnable(registry, scheme); err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package strings\n\nimport (\n\t\"strings\"\n)\n\n\nfunc RemoveSpace(s string) (d string) {\n\tif IsBlank(s) {\n\t\treturn\n\t}\n\td = s\n\tsps := [...]string{\"\\t\", \"\\n\", \"\\v\", \"\\f\", \"\\r\", \" \"}\n\tfor _, sp := range sps {\n\t\td = strings.Replace(d, sp, \"\", -1)\n\t}\n\treturn\n}\n\n\n\n\n\n\nfunc RemoveStart(s, remove string) string {\n\tif IsBlank(s) || IsBlank(remove) {\n\t\treturn s\n\t}\n\tif strings.HasPrefix(s, remove) {\n\t\treturn s[len(remove):]\n\t}\n\treturn s\n}\n\n\n\nfunc RemoveEnd(s, remove string) string {\n\tif IsBlank(s) || IsBlank(remove) {\n\t\treturn s\n\t}\n\tif strings.HasSuffix(s, remove) {\n\t\treturn s[0 : len(s)-len(remove)]\n\t}\n\treturn s\n}\n\n\nfunc Remove(s, remove string) string {\n\tif IsBlank(s) || IsBlank(remove) {\n\t\treturn s\n\t}\n\treturn strings.Replace(s, remove, \"\", -1)\n}\n\nfunc RemoveBlank(s string) (d string) ", "output": "{\n\tif IsBlank(s) {\n\t\treturn\n\t}\n\td = strings.TrimSpace(s)\n\tsps := [...]string{\"\\t\", \"\\n\", \"\\v\", \"\\f\", \"\\r\", \" \"}\n\tfor _, sp := range sps {\n\t\td = strings.Replace(d, sp, \"\", -1)\n\t}\n\treturn\n}"} {"input": "package summary\n\nimport (\n\tinfo \"github.com/google/cadvisor/info/v2\"\n)\n\n\n\n\n\ntype SamplesBuffer struct {\n\tsamples []info.Usage\n\tmaxSize int\n\tindex int\n}\n\n\nfunc NewSamplesBuffer(size int) *SamplesBuffer {\n\treturn &SamplesBuffer{\n\t\tindex: -1,\n\t\tmaxSize: size,\n\t}\n}\n\n\nfunc (s *SamplesBuffer) Size() int {\n\treturn len(s.samples)\n}\n\n\n\n\n\nfunc (s *SamplesBuffer) RecentStats(n int) []*info.Usage {\n\tif n > len(s.samples) {\n\t\tn = len(s.samples)\n\t}\n\tstart := s.index - (n - 1)\n\tif start < 0 {\n\t\tstart += len(s.samples)\n\t}\n\n\tout := make([]*info.Usage, n)\n\tfor i := 0; i < n; i++ {\n\t\tindex := (start + i) % len(s.samples)\n\t\tout[i] = &s.samples[index]\n\t}\n\treturn out\n}\n\nfunc (s *SamplesBuffer) Add(stat info.Usage) ", "output": "{\n\tif len(s.samples) < s.maxSize {\n\t\ts.samples = append(s.samples, stat)\n\t\ts.index++\n\t\treturn\n\t}\n\ts.index = (s.index + 1) % s.maxSize\n\ts.samples[s.index] = stat\n}"} {"input": "package jwt\n\nimport (\n\t\"crypto/rsa\"\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/SermoDigital/jose/crypto\"\n\t\"github.com/SermoDigital/jose/jws\"\n\t\"github.com/nicholasjackson/building-microservices-in-go/chapter8/utils\"\n)\n\nvar rsaPrivate *rsa.PrivateKey\nvar rsaPublic *rsa.PublicKey\n\nfunc init() {\n\tvar err error\n\trsaPrivate, err = utils.UnmarshalRSAPrivateKeyFromFile(\"../keys/sample_key.priv\")\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to parse private key\", err)\n\t}\n\n\trsaPublic, err = utils.UnmarshalRSAPublicKeyFromFile(\"../keys/sample_key.pub\")\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to parse public key\", err)\n\t}\n}\n\n\n\n\n\n\nfunc ValidateJWT(token []byte) error {\n\tjwt, err := jws.ParseJWT(token)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to parse token: %v\", err)\n\t}\n\n\tif err = jwt.Validate(rsaPublic, crypto.SigningMethodRS256); err != nil {\n\t\treturn fmt.Errorf(\"Unable to validate token: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc GenerateJWT() []byte ", "output": "{\n\tclaims := jws.Claims{}\n\tclaims.SetExpiration(time.Now().Add(2880 * time.Minute))\n\tclaims.Set(\"userID\", \"abcsd232jfjf\")\n\tclaims.Set(\"accessLevel\", \"user\")\n\n\tjwt := jws.NewJWT(claims, crypto.SigningMethodRS256)\n\n\tb, _ := jwt.Serialize(rsaPrivate)\n\n\treturn b\n}"} {"input": "package tagquery\n\nimport (\n\t\"io\"\n\n\t\"github.com/grafana/metrictank/schema\"\n)\n\ntype expressionMatchNone struct {\n\texpressionCommon\n\toriginalOperator ExpressionOperator\n}\n\nfunc (e *expressionMatchNone) Equals(other Expression) bool {\n\treturn e.key == other.GetKey() && e.GetOperator() == other.GetOperator() && e.value == other.GetValue()\n}\n\nfunc (e *expressionMatchNone) GetDefaultDecision() FilterDecision {\n\treturn Fail\n}\n\nfunc (e *expressionMatchNone) GetKey() string {\n\treturn e.key\n}\n\nfunc (e *expressionMatchNone) GetValue() string {\n\treturn e.value\n}\n\nfunc (e *expressionMatchNone) GetOperator() ExpressionOperator {\n\treturn MATCH_NONE\n}\n\nfunc (e *expressionMatchNone) GetOperatorCost() uint32 {\n\treturn 0\n}\n\nfunc (e *expressionMatchNone) RequiresNonEmptyValue() bool {\n\treturn true\n}\n\nfunc (e *expressionMatchNone) Matches(value string) bool {\n\treturn false\n}\n\n\n\nfunc (e *expressionMatchNone) StringIntoWriter(writer io.Writer) {\n\twriter.Write([]byte(e.key))\n\te.originalOperator.StringIntoWriter(writer)\n\twriter.Write([]byte(e.value))\n}\n\nfunc (e *expressionMatchNone) GetMetricDefinitionFilter(_ IdTagLookup) MetricDefinitionFilter ", "output": "{\n\treturn func(_ schema.MKey, _ string, _ []string) FilterDecision { return Fail }\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/engine\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdGetAttributes{\n\t\tname: \"attributes\",\n\t\trpcMethod: utils.APIerSv1GetAttributeProfile,\n\t\trpcParams: &utils.TenantID{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetAttributes struct {\n\tname string\n\trpcMethod string\n\trpcParams *utils.TenantID\n\t*CommandExecuter\n}\n\n\n\nfunc (self *CmdGetAttributes) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdGetAttributes) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &utils.TenantID{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetAttributes) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetAttributes) RpcResult() interface{} {\n\tvar atr engine.AttributeProfile\n\treturn &atr\n}\n\nfunc (self *CmdGetAttributes) Name() string ", "output": "{\n\treturn self.name\n}"} {"input": "package ttlru\n\ntype ttlHeap []*entry\n\nfunc (h ttlHeap) Len() int {\n\treturn len(h)\n}\n\nfunc (h ttlHeap) Less(i, j int) bool {\n\tif i == j || i < 0 || j < 0 {\n\t\treturn false\n\t}\n\treturn h[i].expires.Before(h[j].expires)\n}\n\n\n\nfunc (h *ttlHeap) Push(x interface{}) {\n\tn := len(*h)\n\titem := x.(*entry)\n\titem.index = n\n\t*h = append(*h, item)\n}\n\nfunc (h *ttlHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tif n == 0 {\n\t\treturn nil\n\t}\n\titem := old[n-1]\n\titem.index = -1 \n\t*h = old[0 : n-1]\n\treturn item\n}\n\nfunc (h ttlHeap) Swap(i, j int) ", "output": "{\n\tif i == j || i < 0 || j < 0 {\n\t\treturn\n\t}\n\th[i], h[j] = h[j], h[i]\n\th[i].index, h[j].index = i, j\n}"} {"input": "package session\n\nimport (\n\t\"github.com/gorilla/mux\"\n\t\"github.com/rebel-l/sessionservice/src/authentication\"\n\t\"github.com/rebel-l/sessionservice/src/configuration\"\n\t\"github.com/rebel-l/sessionservice/src/storage\"\n\tlog \"github.com/sirupsen/logrus\"\n\t\"net/http\"\n)\n\n\ntype Session struct {\n\tStorage storage.Handler\n\tAuthentication *authentication.Authentication\n\tConfig *configuration.Service\n}\n\n\n\n\nfunc (s *Session) Init(router *mux.Router) {\n\tlog.Debug(\"Session endpoint: Init ...\")\n\n\trouter.Handle(\"/session/\", s.handlerFactory(http.MethodPut)).Methods(http.MethodPut)\n\n\tlog.Debug(\"Session endpoint: initialized!\")\n}\n\nfunc (s *Session) handlerFactory(method string) http.Handler {\n\tvar handler func(http.ResponseWriter, *http.Request)\n\tswitch method {\n\t\tcase http.MethodPut:\n\t\t\tput := NewPut(s)\n\t\t\thandler = put.Handler\n\t\tdefault:\n\t\t\tlog.Panicf(\"Method %s is not implemented\", method)\n\t\t\treturn nil\n\t}\n\n\treturn s.Authentication.Middleware(http.HandlerFunc(handler))\n}\n\nfunc NewSession(\n\tstorage storage.Handler,\n\tauthentication *authentication.Authentication,\n\tconfig *configuration.Service) *Session ", "output": "{\n\ts := new(Session)\n\ts.Storage = storage\n\ts.Authentication = authentication\n\ts.Config = config\n\treturn s\n}"} {"input": "package rpc\n\nimport (\n\t\"testing\"\n\n\t\"github.com/cockroachdb/cockroach/util\"\n\t\"github.com/cockroachdb/cockroach/util/leaktest\"\n)\n\n\n\nfunc checkUpdateFails(t *testing.T, network, oldAddrString, newAddrString string) {\n\toldAddr := util.MakeUnresolvedAddr(network, oldAddrString)\n\tnewAddr := util.MakeUnresolvedAddr(network, newAddrString)\n\n\tretAddr, err := updatedAddr(oldAddr, newAddr)\n\tif err == nil {\n\t\tt.Fatalf(\"updatedAddr(%v, %v) should have failed; instead returned %v\", oldAddr, newAddr, retAddr)\n\t}\n}\n\nfunc TestUpdatedAddr(t *testing.T) {\n\tdefer leaktest.AfterTest(t)\n\tfor _, network := range []string{\"tcp\", \"tcp4\", \"tcp6\"} {\n\t\tcheckUpdateMatches(t, network, \"localhost:0\", \"127.0.0.1:1234\", \"localhost:1234\")\n\t\tcheckUpdateMatches(t, network, \"localhost:1234\", \"127.0.0.1:1234\", \"localhost:1234\")\n\t\tcheckUpdateMatches(t, network, \"localhost:1234\", \"127.0.0.1:1235\", \"localhost:1235\")\n\t}\n\n\tcheckUpdateMatches(t, \"unix\", \"address\", \"address\", \"address\")\n\tcheckUpdateFails(t, \"unix\", \"address\", \"anotheraddress\")\n}\n\nfunc checkUpdateMatches(t *testing.T, network, oldAddrString, newAddrString, expAddrString string) ", "output": "{\n\toldAddr := util.MakeUnresolvedAddr(network, oldAddrString)\n\tnewAddr := util.MakeUnresolvedAddr(network, newAddrString)\n\texpAddr := util.MakeUnresolvedAddr(network, expAddrString)\n\n\tretAddr, err := updatedAddr(oldAddr, newAddr)\n\tif err != nil {\n\t\tt.Fatalf(\"updatedAddr failed on %v, %v: %v\", oldAddr, newAddr, err)\n\t}\n\n\tif retAddr.String() != expAddrString {\n\t\tt.Fatalf(\"updatedAddr(%v, %v) was %s; expected %s\", oldAddr, newAddr, retAddr, expAddr)\n\t}\n}"} {"input": "package tfinstall\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/hashicorp/go-checkpoint\"\n)\n\ntype LatestVersionOption struct {\n\tforceCheckpoint bool\n\tinstallDir string\n\n\tUserAgent string\n}\n\nvar _ ExecPathFinder = &LatestVersionOption{}\n\n\n\nfunc (opt *LatestVersionOption) ExecPath(ctx context.Context) (string, error) {\n\tv, err := latestVersion(opt.forceCheckpoint)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn downloadWithVerification(ctx, v, opt.installDir, opt.UserAgent)\n}\n\nfunc latestVersion(forceCheckpoint bool) (string, error) {\n\tresp, err := checkpoint.Check(&checkpoint.CheckParams{\n\t\tProduct: \"terraform\",\n\t\tForce: forceCheckpoint,\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif resp.CurrentVersion == \"\" {\n\t\treturn \"\", fmt.Errorf(\"could not determine latest version of terraform using checkpoint: CHECKPOINT_DISABLE may be set\")\n\t}\n\n\treturn resp.CurrentVersion, nil\n}\n\nfunc LatestVersion(installDir string, forceCheckpoint bool) *LatestVersionOption ", "output": "{\n\topt := &LatestVersionOption{\n\t\tforceCheckpoint: forceCheckpoint,\n\t\tinstallDir: installDir,\n\t}\n\n\treturn opt\n}"} {"input": "package bot\n\nimport \"strconv\"\n\n\n\nconst _pipeAddFlavor_name = \"flavorSpawnflavorAddflavorFinalflavorFail\"\n\nvar _pipeAddFlavor_index = [...]uint8{0, 11, 20, 31, 41}\n\nfunc (i pipeAddFlavor) String() string {\n\tif i < 0 || i >= pipeAddFlavor(len(_pipeAddFlavor_index)-1) {\n\t\treturn \"pipeAddFlavor(\" + strconv.FormatInt(int64(i), 10) + \")\"\n\t}\n\treturn _pipeAddFlavor_name[_pipeAddFlavor_index[i]:_pipeAddFlavor_index[i+1]]\n}\n\nfunc _() ", "output": "{\n\tvar x [1]struct{}\n\t_ = x[flavorSpawn-0]\n\t_ = x[flavorAdd-1]\n\t_ = x[flavorFinal-2]\n\t_ = x[flavorFail-3]\n}"} {"input": "package next\n\nimport (\n \"gopkg.in/mgo.v2\"\n \"gopkg.in/mgo.v2/bson\"\n)\n\ntype MongoDB struct {\n session *mgo.Session\n db string\n}\n\nfunc NewMongoDB() *MongoDB {\n return &MongoDB{}\n}\n\nfunc (mongo *MongoDB) Open(url string, db string) {\n s, err := mgo.Dial(url)\n if err != nil {\n panic(err.Error())\n }\n\n mongo.session = s\n mongo.db = db\n}\n\n\n\nfunc (mongo *MongoDB) Session() *mgo.Session {\n s := mongo.session.Copy()\n s.SetMode(mgo.Strong, true)\n return s\n}\n\nfunc (mongo *MongoDB) InsertOrUpdate(collection string, buziKey string, buziValue interface{}, d interface{}, result interface{}) (error) {\n s := mongo.Session()\n defer s.Close()\n\n c := s.DB(mongo.db).C(collection)\n\n change := mgo.Change{\n Update: bson.M{\"$set\": d},\n Upsert: true,\n Remove: false,\n ReturnNew: true,\n }\n\n _, err := c.Find(bson.M{buziKey: buziValue}).Apply(change, result)\n return err\n}\n\nfunc (mongo *MongoDB) Close() ", "output": "{\n mongo.session.Close()\n}"} {"input": "package code\n\nimport (\n\t\"github.com/qur/withmock/scenarios/basic/lib\"\n)\n\n\n\nfunc TryMe() error ", "output": "{\n\treturn lib.Wibble()\n}"} {"input": "package clang\n\n\n\nimport \"C\"\nimport (\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype IdxCXXClassDeclInfo struct {\n\tc C.CXIdxCXXClassDeclInfo\n}\n\nfunc (icxxcdi IdxCXXClassDeclInfo) DeclInfo() *IdxDeclInfo {\n\to := icxxcdi.c.declInfo\n\n\tvar gop_o *IdxDeclInfo\n\tif o != nil {\n\t\tgop_o = &IdxDeclInfo{o}\n\t}\n\n\treturn gop_o\n}\n\nfunc (icxxcdi IdxCXXClassDeclInfo) Bases() []*IdxBaseClassInfo {\n\tvar s []*IdxBaseClassInfo\n\tgos_s := (*reflect.SliceHeader)(unsafe.Pointer(&s))\n\tgos_s.Cap = int(icxxcdi.c.numBases)\n\tgos_s.Len = int(icxxcdi.c.numBases)\n\tgos_s.Data = uintptr(unsafe.Pointer(icxxcdi.c.bases))\n\n\treturn s\n}\n\n\n\nfunc (icxxcdi IdxCXXClassDeclInfo) NumBases() uint32 ", "output": "{\n\treturn uint32(icxxcdi.c.numBases)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/robfig/cron\"\n)\n\ntype Sync struct{}\n\nfunc (s *Sync) Help() string {\n\treturn \"glr sync Help\"\n}\n\nfunc (s *Sync) Run(args []string) int {\n\t_, err := SyncRepository()\n\n\tif err != nil {\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n\nfunc (s *Sync) Synopsis() string {\n\treturn \"Synchronize local git repository with remote at once\"\n}\n\n\ntype status struct {\n\tc *cron.Cron\n\trepositories []string\n\tschedules []string\n}\n\nvar sharedStatus *status = newStatus()\n\nfunc newStatus() *status {\n\treturn &status{\n\t\tc: cron.New(),\n\t}\n}\n\n\nfunc GetStatus() *status {\n\treturn sharedStatus\n}\n\ntype StatusStart struct{}\n\nfunc (s *StatusStart) Help() string {\n\treturn \"glr status start Help\"\n}\n\n\n\nfunc (s *StatusStart) Synopsis() string {\n\treturn \"Synchronize local git repository with remote\"\n}\n\ntype StatusStop struct{}\n\nfunc (s *StatusStop) Help() string {\n\treturn \"glr status stop Help\"\n}\n\nfunc (s *StatusStop) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.Stop()\n\tfmt.Println(\"stop job scheduler\")\n\n\treturn 0\n}\n\nfunc (s *StatusStop) Synopsis() string {\n\treturn \"Stop cron scheduler\"\n}\n\nfunc (s *StatusStart) Run(args []string) int ", "output": "{\n\n\tstatus := GetStatus()\n\tstatus.c.AddFunc(\"@hourly\", func() {\n\t\tSyncRepository()\n\t})\n\tfmt.Println(\"set job schedule\")\n\tstatus.c.Start()\n\n\treturn 0\n}"} {"input": "package ctrl\n\nimport (\n\t\"wb/cs\"\n\t\"wb/ii\"\n\t\"wb/om\"\n)\n\ntype ItemController struct {\n\tItemBaseController\n\tCtxItemInfo ii.ItemInfo\n}\n\nfunc (this *ItemController) List() {\n\ttableResult := this.GetTableList(this.CtxItemInfo, om.Params{})\n\tthis.SendJson(&tableResult)\n}\n\nfunc (this *ItemController) Add() {\n\tthis.AddItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) Adds() {\n\tthis.AddItems(this.CtxItemInfo)\n}\nfunc (this *ItemController) AddWithSub() {\n\tthis.AddItemWithSub(this.CtxItemInfo)\n}\nfunc (this *ItemController) Update() {\n\tthis.UpdateItem(this.CtxItemInfo)\n}\nfunc (ic *ItemController) UpdateWithSub() {\n\tic.UpdateItemWithSub(ic.CtxItemInfo)\n}\nfunc (this *ItemController) UpdateWithAddSub() {\n\tthis.UpdateItemWithAddSub(this.CtxItemInfo)\n}\n\n\n\n\nfunc (this *ItemController) Delete() {\n\tthis.DeleteItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) Upload() {\n\tthis.UploadItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) Autocomplete() {\n\tthis.AutocompleteItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) UiList() {\n\tthis.UiListItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) UiAdd() {\n\tthis.UiAddItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) UiUpdate() {\n\tthis.UiUpdateItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) UiView() {\n\tthis.UiViewItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) UiAttachment() {\n\tthis.UiAttachmentItem(this.CtxItemInfo)\n}\n\nfunc (this *ItemController) Get() ", "output": "{\n\tret, res := this.GetItem(this.CtxItemInfo)\n\tthis.SendJson(cs.JsonResult{ret, res})\n}"} {"input": "package main\n\nimport (\n\traw \"github.com/buger/gor/raw_socket_listener\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\n\ntype RAWInput struct {\n\tdata chan *raw.TCPMessage\n\taddress string\n\texpire time.Duration\n\tquit chan bool\n\tlistener *raw.Listener\n}\n\n\nfunc NewRAWInput(address string, expire time.Duration) (i *RAWInput) {\n\ti = new(RAWInput)\n\ti.data = make(chan *raw.TCPMessage)\n\ti.address = address\n\ti.expire = expire\n\ti.quit = make(chan bool)\n\n\tgo i.listen(address)\n\n\treturn\n}\n\n\n\nfunc (i *RAWInput) listen(address string) {\n\taddress = strings.Replace(address, \"[::]\", \"127.0.0.1\", -1)\n\n\tDebug(\"Listening for traffic on: \" + address)\n\n\thost, port, err := net.SplitHostPort(address)\n\n\tif err != nil {\n\t\tlog.Fatal(\"input-raw: error while parsing address\", err)\n\t}\n\n\ti.listener = raw.NewListener(host, port, i.expire, true)\n\n\tfor {\n\t\tselect {\n\t\tcase <-i.quit:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tm := i.listener.Receive()\n\n\t\ti.data <- m\n\t}\n}\n\nfunc (i *RAWInput) String() string {\n\treturn \"RAW Socket input: \" + i.address\n}\n\nfunc (i *RAWInput) Close() {\n\ti.listener.Close()\n\tclose(i.quit)\n}\n\nfunc (i *RAWInput) Read(data []byte) (int, error) ", "output": "{\n\tmsg := <-i.data\n\tbuf := msg.Bytes()\n\n\tvar header []byte\n\n\tif msg.IsIncoming {\n\t\theader = payloadHeader(RequestPayload, msg.UUID(), msg.Start.UnixNano())\n\t} else {\n\t\theader = payloadHeader(ResponsePayload, msg.UUID(), msg.End.UnixNano()-msg.RequestStart.UnixNano())\n\t}\n\n\tcopy(data[0:len(header)], header)\n\tcopy(data[len(header):], buf)\n\n\treturn len(buf) + len(header), nil\n}"} {"input": "package log4me\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n)\n\ntype LoggerI struct {\n\tEnabled bool\n}\n\nfunc (l LoggerI) Info(v ...interface{}) {\n\tif !l.Enabled {\n\t\treturn\n\t}\n\n\tfmt.Fprintln(ioutil.Discard, v...)\n\n}\n\n\n\ntype LoggerF struct {\n\tEnabled bool\n}\n\ntype F func()\n\nfunc (l LoggerF) Info(f F) {\n\tif l.Enabled {\n\t\tf()\n\t}\n}\n\nfunc (l LoggerF) String() string {\n\tif l.Enabled {\n\t\treturn \"LoggerF: Enabled\"\n\t}\n\treturn \"LoggerF: Disabled\"\n}\n\nfunc (l LoggerI) String() string ", "output": "{\n\tif l.Enabled {\n\t\treturn \"LoggerI: Enabled\"\n\t}\n\treturn \"LoggerI: Disabled\"\n}"} {"input": "package qemu\n\nimport (\n\t\"context\"\n\t\"github.com/oklog/ulid\"\n\t\"os\"\n\t\"os/exec\"\n)\n\ntype DiskCache string\n\nconst (\n\tCacheWriteThrough DiskCache = \"writethrough\"\n\tCacheWriteBack DiskCache = \"writeback\"\n\tCacheNone DiskCache = \"none\"\n\tCacheUnsafe DiskCache = \"unsafe\"\n\tCacheDirectSync DiskCache = \"directsync\"\n)\n\ntype NetworkDevice struct {\n\tInterfaceName string\n\tMacAddress string\n}\n\ntype StorageDevice struct {\n\tPool string\n\tDisk string\n\tCache DiskCache\n}\n\ntype VirtualMachine struct {\n\tId ulid.ULID\n\tVncPort int\n\tCpu string\n\tRoot string\n\tNICs []NetworkDevice\n\tDisks []StorageDevice\n\tMemLock bool\n\tVhostNet bool\n\tRAM int\n\tNumCPUs int\n\n\tcmd *exec.Cmd\n\tfiles []*os.File\n\tmon *Monitor\n}\n\n\n\nfunc (vm *VirtualMachine) Kill(ctx context.Context) {\n\terr := vm.cmd.Process.Kill()\n\tif err != nil {\n\t\tlogger.Error(ctx, \"failed to kill vm process\", \"vm_id\", vm.Id, \"process\", vm.cmd.Process.Pid, \"error\", err)\n\t}\n}\n\nfunc (vm *VirtualMachine) Release(ctx context.Context) {\n\terr := vm.cmd.Process.Release()\n\tif err != nil {\n\t\tlogger.Error(ctx, \"failed to release vm process\", \"vm_id\", vm.Id, \"process\", vm.cmd.Process.Pid, \"error\", err)\n\t}\n}\n\nfunc (vm *VirtualMachine) Monitor() *Monitor ", "output": "{\n\tif vm.mon == nil {\n\t\tpanic(\"Monitor() call on uninitialized VM\")\n\t}\n\treturn vm.mon\n}"} {"input": "package fileinterface\n\nimport (\n \"testing\"\n \"errors\"\n )\n\nfunc TestCreate(t *testing.T) {\n\tvar f FID\n\tvar err error\n\tif f, err = Create(\"dummyfile\"); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tif err = Close(f); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n}\n\nfunc TestDelete(t *testing.T) {\n\terr := Delete(\"dummyfile\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\n\n\nfunc TestRead(t *testing.T) {\n\tvar block *Block\n\tif f, err := Open(\"sample.database\"); err != nil {\n\t\tt.Error(err)\n\t} else if block, err = Read(f, 5); err != nil {\n\t\tt.Error(err)\n\t} else if err = Close(f); err != nil {\n\t\tt.Error(err)\n\t}\n\tfor i:=0; i ResourceGroupName : '%s'\", resourceGroupName))\n\ts.say(fmt.Sprintf(\" -> ComputeName : '%s'\", computeName))\n\n\terr := s.powerOff(resourceGroupName, computeName)\n\tif err != nil {\n\t\tstate.Put(constants.Error, err)\n\t\ts.error(err)\n\n\t\treturn multistep.ActionHalt\n\t}\n\n\treturn multistep.ActionContinue\n}"} {"input": "package downloader\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/WhaleCoinOrg/WhaleCoin/core/types\"\n)\n\n\ntype peerDropFn func(id string)\n\n\ntype dataPack interface {\n\tPeerId() string\n\tItems() int\n\tStats() string\n}\n\n\ntype headerPack struct {\n\tpeerId string\n\theaders []*types.Header\n}\n\nfunc (p *headerPack) PeerId() string { return p.peerId }\nfunc (p *headerPack) Items() int { return len(p.headers) }\nfunc (p *headerPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.headers)) }\n\n\ntype bodyPack struct {\n\tpeerId string\n\ttransactions [][]*types.Transaction\n\tuncles [][]*types.Header\n}\n\nfunc (p *bodyPack) PeerId() string { return p.peerId }\nfunc (p *bodyPack) Items() int {\n\tif len(p.transactions) <= len(p.uncles) {\n\t\treturn len(p.transactions)\n\t}\n\treturn len(p.uncles)\n}\nfunc (p *bodyPack) Stats() string { return fmt.Sprintf(\"%d:%d\", len(p.transactions), len(p.uncles)) }\n\n\ntype receiptPack struct {\n\tpeerId string\n\treceipts [][]*types.Receipt\n}\n\nfunc (p *receiptPack) PeerId() string { return p.peerId }\n\nfunc (p *receiptPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.receipts)) }\n\n\ntype statePack struct {\n\tpeerId string\n\tstates [][]byte\n}\n\nfunc (p *statePack) PeerId() string { return p.peerId }\nfunc (p *statePack) Items() int { return len(p.states) }\nfunc (p *statePack) Stats() string { return fmt.Sprintf(\"%d\", len(p.states)) }\n\nfunc (p *receiptPack) Items() int ", "output": "{ return len(p.receipts) }"} {"input": "package config\n\nimport (\n\t\"github.com/griesbacher/nagflux/data\"\n\t\"sync\"\n)\n\n\ntype PauseMap map[data.Target]bool\n\n\nvar pauseNagflux = PauseMap{}\n\nvar objMutex = &sync.Mutex{}\n\n\n\n\nfunc StoreValue(target data.Target, value bool) {\n\tobjMutex.Lock()\n\tpauseNagflux[target] = value\n\tobjMutex.Unlock()\n}\n\nfunc IsAnyTargetOnPause() bool ", "output": "{\n\tobjMutex.Lock()\n\tresult := false\n\tfor _, v := range pauseNagflux {\n\t\tif v {\n\t\t\tresult = true\n\t\t\tbreak\n\t\t}\n\t}\n\tobjMutex.Unlock()\n\treturn result\n}"} {"input": "package zygo\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc (env *Glisp) ImportMsgpackMap() {\n\tenv.AddMacro(\"msgpack-map\", MsgpackMapMacro)\n\tenv.AddFunction(\"declare-msgpack-map\", DeclareMsgpackMapFunction)\n}\n\n\nfunc MsgpackMapMacro(env *Glisp, name string,\n\targs []Sexp) (Sexp, error) {\n\n\tif len(args) < 1 {\n\t\treturn SexpNull, fmt.Errorf(\"struct-name is missing. use: \" +\n\t\t\t\"(msgpack-map struct-name)\\n\")\n\t}\n\n\treturn MakeList([]Sexp{\n\t\tenv.MakeSymbol(\"def\"),\n\t\targs[0],\n\t\tMakeList([]Sexp{\n\t\t\tenv.MakeSymbol(\"quote\"),\n\t\t\tenv.MakeSymbol(\"msgmap\"),\n\t\t\tSexpStr{S: args[0].(SexpSymbol).name},\n\t\t}),\n\t}), nil\n}\n\n\n\nfunc DeclareMsgpackMapFunction(env *Glisp, name string, args []Sexp) (Sexp, error) ", "output": "{\n\tif len(args) != 1 {\n\t\treturn SexpNull, WrongNargs\n\t}\n\n\tswitch t := args[0].(type) {\n\tcase SexpStr:\n\t\treturn t, nil\n\t}\n\treturn SexpNull, errors.New(\"argument must be string: the name of the new msgpack-map constructor function to create\")\n}"} {"input": "package out\n\nimport \"math\"\n\n\ntype Point struct {\n\tVid int \n\tIpId int \n\tX []float64 \n\tDist float64 \n\tVals map[string][]float64 \n}\n\n\ntype Points []*Point\n\n\nfunc (o Points) Len() int {\n\treturn len(o)\n}\n\n\nfunc (o Points) Swap(i, j int) {\n\to[i], o[j] = o[j], o[i]\n}\n\n\nfunc (o Points) Less(i, j int) bool {\n\treturn o[i].Dist < o[j].Dist\n}\n\nfunc get_nod_point(vid int, A []float64) *Point {\n\tnod := Dom.Vid2node[vid]\n\tif nod != nil {\n\t\tvar dist float64\n\t\tif A != nil {\n\t\t\tdist = dist_point_point(nod.Vert.C, A)\n\t\t}\n\t\treturn &Point{vid, -1, nod.Vert.C, dist, make(map[string][]float64)}\n\t}\n\treturn nil\n}\n\nfunc get_ip_point(ipid int, A []float64) *Point {\n\tip := Ipoints[ipid]\n\tif ip != nil {\n\t\tvar dist float64\n\t\tif A != nil {\n\t\t\tdist = dist_point_point(ip.X, A)\n\t\t}\n\t\treturn &Point{-1, ipid, ip.X, dist, make(map[string][]float64)}\n\t}\n\treturn nil\n}\n\n\n\n\nfunc dist_point_point(a, b []float64) float64 ", "output": "{\n\tif len(a) == 2 {\n\t\treturn math.Sqrt((a[0]-b[0])*(a[0]-b[0]) + (a[1]-b[1])*(a[1]-b[1]))\n\t}\n\treturn math.Sqrt((a[0]-b[0])*(a[0]-b[0]) + (a[1]-b[1])*(a[1]-b[1]) + (a[2]-b[2])*(a[2]-b[2]))\n}"} {"input": "package event\n\nimport \"bytes\"\n\ntype ChannelCloseReqEvent struct {\n\tEventHeader\n}\n\nfunc (ev *ChannelCloseReqEvent) Encode(buffer *bytes.Buffer) {\n}\nfunc (ev *ChannelCloseReqEvent) Decode(buffer *bytes.Buffer) (err error) {\n\treturn nil\n}\n\ntype ChannelCloseACKEvent struct {\n\tEventHeader\n}\n\nfunc (ev *ChannelCloseACKEvent) Encode(buffer *bytes.Buffer) {\n}\n\n\nfunc (ev *ChannelCloseACKEvent) Decode(buffer *bytes.Buffer) (err error) ", "output": "{\n\treturn nil\n}"} {"input": "package customer\n\nimport (\n\t\"testing\"\n\n\tassert \"github.com/stretchr/testify/require\"\n\tstripe \"github.com/stripe/stripe-go\"\n\t_ \"github.com/stripe/stripe-go/testing\"\n)\n\nfunc TestCustomerDel(t *testing.T) {\n\tcustomer, err := Del(\"cus_123\", nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\n\n\nfunc TestCustomerList(t *testing.T) {\n\ti := List(&stripe.CustomerListParams{})\n\n\tassert.True(t, i.Next())\n\tassert.Nil(t, i.Err())\n\tassert.NotNil(t, i.Customer())\n}\n\nfunc TestCustomerNew(t *testing.T) {\n\tcustomer, err := New(&stripe.CustomerParams{\n\t\tEmail: stripe.String(\"foo@example.com\"),\n\t\tShipping: &stripe.CustomerShippingDetailsParams{\n\t\t\tAddress: &stripe.AddressParams{\n\t\t\t\tLine1: stripe.String(\"line1\"),\n\t\t\t\tCity: stripe.String(\"city\"),\n\t\t\t},\n\t\t\tName: stripe.String(\"name\"),\n\t\t},\n\t})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerNew_NilParams(t *testing.T) {\n\tcustomer, err := New(nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerUpdate(t *testing.T) {\n\tcustomer, err := Update(\"cus_123\", &stripe.CustomerParams{\n\t\tEmail: stripe.String(\"foo@example.com\"),\n\t})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerGet(t *testing.T) ", "output": "{\n\tcustomer, err := Get(\"cus_123\", nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}"} {"input": "package migrator\n\nimport (\n\t\"github.com/cgrates/cgrates/engine\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc (m *Migrator) migrateCurrentTPTiming() (err error) {\n\ttpids, err := m.storDBIn.StorDB().GetTpIds(utils.TBLTPTimings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, tpid := range tpids {\n\t\tids, err := m.storDBIn.StorDB().GetTpTableIds(tpid, utils.TBLTPTimings,\n\t\t\tutils.TPDistinctIds{\"tag\"}, map[string]string{}, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, id := range ids {\n\t\t\ttm, err := m.storDBIn.StorDB().GetTPTimings(tpid, id)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif tm != nil {\n\t\t\t\tif !m.dryRun {\n\t\t\t\t\tif err := m.storDBOut.StorDB().SetTPTimings(tm); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tfor _, timing := range tm {\n\t\t\t\t\t\tif err := m.storDBIn.StorDB().RemTpData(utils.TBLTPTimings,\n\t\t\t\t\t\t\ttiming.TPid, map[string]string{\"tag\": timing.ID}); err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tm.stats[utils.TpTiming] += 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\n\n\nfunc (m *Migrator) migrateTpTimings() (err error) ", "output": "{\n\tvar vrs engine.Versions\n\tcurrent := engine.CurrentStorDBVersions()\n\tif vrs, err = m.getVersions(utils.TpTiming); err != nil {\n\t\treturn\n\t}\n\tswitch vrs[utils.TpTiming] {\n\tcase current[utils.TpTiming]:\n\t\tif m.sameStorDB {\n\t\t\tbreak\n\t\t}\n\t\tif err := m.migrateCurrentTPTiming(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn m.ensureIndexesStorDB(utils.TBLTPTimings)\n}"} {"input": "package dockertools\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\tdocker \"github.com/fsouza/go-dockerclient\"\n\tkubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\"\n\tkubetypes \"k8s.io/kubernetes/pkg/kubelet/types\"\n)\n\n\n\n\nfunc mapStatus(status string) kubecontainer.ContainerStatus {\n\tswitch {\n\tcase strings.HasPrefix(status, \"Up\"):\n\t\treturn kubecontainer.ContainerStatusRunning\n\tcase strings.HasPrefix(status, \"Exited\"):\n\t\treturn kubecontainer.ContainerStatusExited\n\tdefault:\n\t\treturn kubecontainer.ContainerStatusUnknown\n\t}\n}\n\n\nfunc toRuntimeContainer(c *docker.APIContainers) (*kubecontainer.Container, error) {\n\tif c == nil {\n\t\treturn nil, fmt.Errorf(\"unable to convert a nil pointer to a runtime container\")\n\t}\n\n\tdockerName, hash, err := getDockerContainerNameInfo(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &kubecontainer.Container{\n\t\tID: kubetypes.DockerID(c.ID).ContainerID(),\n\t\tName: dockerName.ContainerName,\n\t\tImage: c.Image,\n\t\tHash: hash,\n\t\tCreated: c.Created,\n\t\tStatus: mapStatus(c.Status),\n\t}, nil\n}\n\n\n\n\nfunc toRuntimeImage(image *docker.APIImages) (*kubecontainer.Image, error) ", "output": "{\n\tif image == nil {\n\t\treturn nil, fmt.Errorf(\"unable to convert a nil pointer to a runtime image\")\n\t}\n\n\treturn &kubecontainer.Image{\n\t\tID: image.ID,\n\t\tTags: image.RepoTags,\n\t\tSize: image.VirtualSize,\n\t}, nil\n}"} {"input": "package core\n\nimport (\n\t\"net\"\n\t\"strconv\"\n)\n\nconst (\n\tAddrTypeIP = byte(0x01)\n\tAddrTypeDomain = byte(0x03)\n)\n\ntype VAddress struct {\n\tType byte\n\tIP net.IP\n\tDomain string\n\tPort uint16\n}\n\nfunc IPAddress(ip []byte, port uint16) VAddress {\n\treturn VAddress{\n\t\tAddrTypeIP,\n\t\tnet.IP(ip),\n\t\t\"\",\n\t\tport}\n}\n\nfunc DomainAddress(domain string, port uint16) VAddress {\n\treturn VAddress{\n\t\tAddrTypeDomain,\n\t\tnil,\n\t\tdomain,\n\t\tport}\n}\n\nfunc (addr VAddress) IsIPv4() bool {\n\treturn addr.Type == AddrTypeIP && len(addr.IP) == net.IPv4len\n}\n\n\n\nfunc (addr VAddress) IsDomain() bool {\n\treturn addr.Type == AddrTypeDomain\n}\n\nfunc (addr VAddress) String() string {\n\tvar host string\n\tswitch addr.Type {\n\tcase AddrTypeIP:\n\t\thost = addr.IP.String()\n\t\tif len(addr.IP) == net.IPv6len {\n\t\t\thost = \"[\" + host + \"]\"\n\t\t}\n\n\tcase AddrTypeDomain:\n\t\thost = addr.Domain\n\tdefault:\n\t\tpanic(\"Unknown Address Type \" + strconv.Itoa(int(addr.Type)))\n\t}\n\treturn host + \":\" + strconv.Itoa(int(addr.Port))\n}\n\nfunc (addr VAddress) IsIPv6() bool ", "output": "{\n\treturn addr.Type == AddrTypeIP && len(addr.IP) == net.IPv6len\n}"} {"input": "package geth\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/etherite/go-etherite/core\"\n\t\"github.com/etherite/go-etherite/p2p/discv5\"\n\t\"github.com/etherite/go-etherite/params\"\n)\n\n\n\nfunc MainnetGenesis() string {\n\treturn \"\"\n}\n\n\n\n\n\nfunc RinkebyGenesis() string {\n\tenc, err := json.Marshal(core.DefaultRinkebyGenesisBlock())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(enc)\n}\n\n\n\nfunc FoundationBootnodes() *Enodes {\n\tnodes := &Enodes{nodes: make([]*discv5.Node, len(params.DiscoveryV5Bootnodes))}\n\tfor i, url := range params.DiscoveryV5Bootnodes {\n\t\tnodes.nodes[i] = discv5.MustParseNode(url)\n\t}\n\treturn nodes\n}\n\nfunc TestnetGenesis() string ", "output": "{\n\tenc, err := json.Marshal(core.DefaultTestnetGenesisBlock())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(enc)\n}"} {"input": "package restic\n\nimport \"syscall\"\n\nfunc (node Node) restoreSymlinkTimestamps(path string, utimes [2]syscall.Timespec) error {\n\treturn nil\n}\n\nfunc (node Node) device() int {\n\treturn int(node.Device)\n}\n\nfunc (s statUnix) atim() syscall.Timespec { return s.Atimespec }\nfunc (s statUnix) mtim() syscall.Timespec { return s.Mtimespec }\nfunc (s statUnix) ctim() syscall.Timespec { return s.Ctimespec }\n\n\n\n\n\n\nfunc Listxattr(path string) ([]string, error) {\n\treturn nil, nil\n}\n\n\nfunc Setxattr(path, name string, data []byte) error {\n\treturn nil\n}\n\nfunc Getxattr(path, name string) ([]byte, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package iso20022\n\n\ntype DirectDebitTransaction7 struct {\n\n\tMandateRelatedInformation *MandateRelatedInformation8 `xml:\"MndtRltdInf,omitempty\"`\n\n\tCreditorSchemeIdentification *PartyIdentification43 `xml:\"CdtrSchmeId,omitempty\"`\n\n\tPreNotificationIdentification *Max35Text `xml:\"PreNtfctnId,omitempty\"`\n\n\tPreNotificationDate *ISODate `xml:\"PreNtfctnDt,omitempty\"`\n}\n\nfunc (d *DirectDebitTransaction7) AddMandateRelatedInformation() *MandateRelatedInformation8 {\n\td.MandateRelatedInformation = new(MandateRelatedInformation8)\n\treturn d.MandateRelatedInformation\n}\n\nfunc (d *DirectDebitTransaction7) AddCreditorSchemeIdentification() *PartyIdentification43 {\n\td.CreditorSchemeIdentification = new(PartyIdentification43)\n\treturn d.CreditorSchemeIdentification\n}\n\n\n\nfunc (d *DirectDebitTransaction7) SetPreNotificationDate(value string) {\n\td.PreNotificationDate = (*ISODate)(&value)\n}\n\nfunc (d *DirectDebitTransaction7) SetPreNotificationIdentification(value string) ", "output": "{\n\td.PreNotificationIdentification = (*Max35Text)(&value)\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com/fogleman/nes/ui\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tpaths := getPaths()\n\tif len(paths) == 0 {\n\t\tlog.Fatalln(\"no rom files specified or found\")\n\t}\n\tui.Run(paths)\n}\n\n\n\nfunc getPaths() []string ", "output": "{\n\tvar arg string\n\targs := os.Args[1:]\n\tif len(args) == 1 {\n\t\targ = args[0]\n\t} else {\n\t\targ, _ = os.Getwd()\n\t}\n\tinfo, err := os.Stat(arg)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tif info.IsDir() {\n\t\tinfos, err := ioutil.ReadDir(arg)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tvar result []string\n\t\tfor _, info := range infos {\n\t\t\tname := info.Name()\n\t\t\tif !strings.HasSuffix(name, \".nes\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresult = append(result, path.Join(arg, name))\n\t\t}\n\t\treturn result\n\t} else {\n\t\treturn []string{arg}\n\t}\n}"} {"input": "package mock_concurrent\n\nimport (\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n)\n\n\ntype MockMath struct {\n\tctrl *gomock.Controller\n\trecorder *MockMathMockRecorder\n}\n\n\ntype MockMathMockRecorder struct {\n\tmock *MockMath\n}\n\n\nfunc NewMockMath(ctrl *gomock.Controller) *MockMath {\n\tmock := &MockMath{ctrl: ctrl}\n\tmock.recorder = &MockMathMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockMath) EXPECT() *MockMathMockRecorder {\n\treturn m.recorder\n}\n\n\n\n\n\nfunc (mr *MockMathMockRecorder) Sum(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Sum\", reflect.TypeOf((*MockMath)(nil).Sum), arg0, arg1)\n}\n\nfunc (m *MockMath) Sum(arg0, arg1 int) int ", "output": "{\n\tret := m.ctrl.Call(m, \"Sum\", arg0, arg1)\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}"} {"input": "package icon\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n)\n\n\n\nfunc (s *Service) UpdateWithContext(ctx context.Context, req *UpdateRequest) (*sacloud.Icon, error) {\n\tif err := req.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := sacloud.NewIconOp(s.caller)\n\tcurrent, err := client.Read(ctx, req.ID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"reading Icon[%s] failed: %s\", req.ID, err)\n\t}\n\n\tparams, err := req.ToRequestParameter(current)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"processing request parameter failed: %s\", err)\n\t}\n\n\treturn client.Update(ctx, req.ID, params)\n}\n\nfunc (s *Service) Update(req *UpdateRequest) (*sacloud.Icon, error) ", "output": "{\n\treturn s.UpdateWithContext(context.Background(), req)\n}"} {"input": "package dml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/dml\"\n)\n\n\n\nfunc TestCT_TablePartStyleMarshalUnmarshal(t *testing.T) {\n\tv := dml.NewCT_TablePartStyle()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := dml.NewCT_TablePartStyle()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestCT_TablePartStyleConstructor(t *testing.T) ", "output": "{\n\tv := dml.NewCT_TablePartStyle()\n\tif v == nil {\n\t\tt.Errorf(\"dml.NewCT_TablePartStyle must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed dml.CT_TablePartStyle should validate: %s\", err)\n\t}\n}"} {"input": "package nginx\n\nimport (\n\t\"encoding/json\"\n\t\"reflect\"\n)\n\n\ntype Node struct {\n\tName string\n\tHostname string\n\tExternalIP string\n\tInternalIP string\n\tActive bool\n}\n\n\n\nfunc (n Node) String() string ", "output": "{\n\tj, err := json.Marshal(n)\n\tif err != nil {\n\t\treturn string(\"cant't marshal: \" + reflect.TypeOf(n).String() + \", to json string, err: \" + err.Error())\n\t}\n\treturn string(j)\n}"} {"input": "package sol\n\n\ntype Operator interface {\n\tWrap(string) string \n}\n\n\nfunc Function(name string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(FuncClause{Name: name})\n}\n\n\nfunc Avg(col Columnar) ColumnElem {\n\treturn Function(AVG, col)\n}\n\n\n\n\n\nfunc Date(col Columnar) ColumnElem {\n\treturn Function(DATE, col)\n}\n\n\n\nfunc DatePart(part string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(\n\t\tFuncClause{Name: DATEPART},\n\t).AddOperator(\n\t\tArrayClause{clauses: []Clause{String(part)}, post: true, sep: \", \"},\n\t)\n}\n\n\nfunc Max(col Columnar) ColumnElem {\n\treturn Function(MAX, col)\n}\n\n\nfunc Min(col Columnar) ColumnElem {\n\treturn Function(MIN, col)\n}\n\n\nfunc StdDev(col Columnar) ColumnElem {\n\treturn Function(STDDEV, col)\n}\n\n\nfunc Sum(col Columnar) ColumnElem {\n\treturn Function(SUM, col)\n}\n\n\nfunc Variance(col Columnar) ColumnElem {\n\treturn Function(VARIANCE, col)\n}\n\nfunc Count(col Columnar) ColumnElem ", "output": "{\n\treturn Function(COUNT, col)\n}"} {"input": "package mathext\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\n\n\nfunc TestAiry(t *testing.T) ", "output": "{\n\tt.Parallel()\n\tfor _, test := range []struct {\n\t\tz, ans complex128\n\t}{\n\t\t{5, 1.08344428136074e-04},\n\t\t{5i, 29.9014823980070 + 21.6778315987835i},\n\t} {\n\t\tans := AiryAi(test.z)\n\t\tif math.Abs(real(ans)-real(test.ans)) > 1e-10 {\n\t\t\tt.Errorf(\"Real part mismatch. Got %v, want %v\", real(ans), real(test.ans))\n\t\t}\n\t\tif math.Abs(imag(ans)-imag(test.ans)) > 1e-10 {\n\t\t\tt.Errorf(\"Imaginary part mismatch. Got %v, want %v\", imag(ans), imag(test.ans))\n\t\t}\n\t}\n}"} {"input": "package main\n\n\n\n\n\nfunc number(a int) int {\n\n\n\tif a < 0 {\n\t\tprintln(a, \"is negative.\")\n\t}\n\n\tif a%2 == 0 {\n\t\tprintln(a, \"is even.\")\n\t} else {\n\t\tprintln(a, \"is odd.\")\n\t}\n\n\tb := 50\n\tc := b - a\n\n\tif c > 0 {\n\t\tprintln(a, \"<50.\")\n\t} else if c < 0 {\n\t\tprintln(a, \">50.\")\n\t} else {\n\t\tprintln(a, \"=50.\")\n\t}\n\treturn a\n}\n\nfunc main() {\n\tn := 5\n\tfunky(n)\n\n\tnumber(35)\n\n\n\n\n\ttype (\n\t\ta int\n\t\tpoint struct {\n\t\t\tx, y string\n\t\t}\n\t)\n\n\tvar z a\n\tz = a(2)\n\tprintln(z)\n\n}\n\nfunc funky(n int) ", "output": "{\n\n\tvar s0 []int\n\ts0 = append(s0, 1)\n\ts0 = append(s0, 1%5)\n\n\ts1 := append(s0, 2)\n\ts2 := append(s1, 3+5)\n\n\tswitch n {\n\tdefault:\n\t\tprintln(s2[1])\n\tcase 1, 2, 3, 4:\n\t\tprintln(s0[1])\n\tcase 5, 6:\n\t\tprintln(s2[3])\n\t}\n\n\treturn\n}"} {"input": "package cpu\n\n\n\n\n\nfunc initOptions() ", "output": "{\n\toptions = []option{\n\t\t{Name: \"msa\", Feature: &MIPS64X.HasMSA},\n\t}\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"os\"\n \"runtime\"\n \"strconv\"\n \"sync\"\n)\n\ntype Token int\n\ntype T struct {\n next *T\n label int\n value int\n mux sync.Mutex\n}\n\nfunc (w *T) put(v int) {\n w.value = v\n if v == 0 {\n res <- w.label\n } else {\n w.mux.Unlock()\n }\n}\n\nfunc (w *T) run() {\n for {\n w.mux.Lock()\n w.next.put(w.value - 1)\n runtime.Gosched()\n }\n}\n\n\n\nconst NThreads = 503\n\nvar res = make(chan int)\n\nfunc main() {\n n := 1000\n if len(os.Args) > 1 {\n n, _ = strconv.Atoi(os.Args[1])\n }\n\n var channels [NThreads]T\n for i := range channels {\n channels[i].Start(i+1, &channels[(i+1)%NThreads])\n }\n\n channels[0].put(n)\n fmt.Println(<-res)\n}\n\nfunc (w *T) Start(label int, next *T) ", "output": "{\n w.label = label\n w.next = next\n w.mux.Lock()\n go w.run()\n}"} {"input": "package proj\n\nconst (\n\tutmLetters = \"CDEFGHJKLMNPQRSTUVWXX\"\n)\n\nvar (\n\tUTMZones = map[int]*TransverseMercator{}\n)\n\n\nfunc utmZone(zone int) *TransverseMercator {\n\treturn &TransverseMercator{\n\t\tcode: 32600 + zone,\n\t\tf0: 0.9996,\n\t\tlat0: rad(0),\n\t\tlon0: rad(6*(30-float64(zone)) + 3),\n\t\te0: 500000,\n\t\tn0: 0,\n\t\te: International1924,\n\t}\n}\n\n\nfunc LatLongUTMZone(lat, lon float64) int {\n\tswitch {\n\tcase 56 <= lat && lat < 64 && 3 <= lon && lon < 12:\n\t\treturn 32\n\tcase 72 <= lat && lat < 84 && 0 <= lon && lon < 42:\n\t\tswitch {\n\t\tcase lon < 9:\n\t\t\treturn 31\n\t\tcase lon < 21:\n\t\t\treturn 33\n\t\tcase lon < 33:\n\t\t\treturn 35\n\t\tdefault:\n\t\t\treturn 37\n\t\t}\n\tdefault:\n\t\treturn int(lon+180)/6 + 1\n\t}\n}\n\n\n\n\nfunc initUTM() {\n\tfor z := 1; z <= 60; z++ {\n\t\tUTMZones[z] = utmZone(z)\n\t}\n}\n\nfunc LatLongUTMLetter(lat, lon float64) byte ", "output": "{\n\tif lat < -80 || 84 <= lat {\n\t\treturn 0\n\t}\n\ti := int((lat + 80) / 8)\n\treturn utmLetters[i]\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n)\n\n\n\n\n\n\n\n\nfunc Get(key string) interface{} {\n\tvar i interface{}\n\n\tDB.Get(\"cache\", key, &i)\n\n\treturn i\n}\n\n\nfunc Delete(key string) error {\n\treturn DB.Delete(\"cache\", key)\n}\n\nfunc Set(key string, value interface{}, dur time.Duration) error ", "output": "{\n\n\tif err := DB.Set(\"cache\", key, value); err != nil {\n\t\treturn err\n\t}\n\n\tif dur.Seconds() > 0 {\n\t\tgo func() {\n\t\t\ttime.Sleep(dur)\n\t\t\tDelete(key)\n\t\t}()\n\t}\n\n\treturn nil\n}"} {"input": "package cases\n\nimport \"gx/ipfs/QmVcxhXDbXjNoAdmYBWbY1eU67kQ8eZUHjG4mAYZUtZZu3/go-text/transform\"\n\ntype caseFolder struct{ transform.NopResetter }\n\n\nfunc (t *caseFolder) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {\n\tc := context{dst: dst, src: src, atEOF: atEOF}\n\tfor c.next() {\n\t\tfoldFull(&c)\n\t\tc.checkpoint()\n\t}\n\treturn c.ret()\n}\n\nfunc (t *caseFolder) Span(src []byte, atEOF bool) (n int, err error) {\n\tc := context{src: src, atEOF: atEOF}\n\tfor c.next() && isFoldFull(&c) {\n\t\tc.checkpoint()\n\t}\n\treturn c.retSpan()\n}\n\n\n\nfunc makeFold(o options) transform.SpanningTransformer ", "output": "{\n\treturn &caseFolder{}\n}"} {"input": "package main\nimport(\n\t\"fmt\"\n\t\"github.com/astaxie/beego/orm\"\n\t_ \"github.com/go-sql-driver/mysql\" \n)\n\n\ntype User struct{\n\tID int\n\tName string `orm:\"size(100)\"`\n}\n\n\n\nfunc main(){\n o:=orm.NewOrm();\n var r orm.RawSeter\n r = o.Raw(\"select * from user where i_d = ? and name = ?\",1,\"wanjn\");\n o.Using(\"default1\");\n dr := o.Driver();\n fmt.Println(dr.Name()==\"default\"); \n fmt.Println(dr.Type() == orm.DRMySQL);\n fmt.Printf(\"query seter:%v\\n\",r);\n}\n\nfunc init()", "output": "{\n\torm.RegisterDataBase(\"default\",\"mysql\",\"root:root@/go_content?charset=utf8\",30);\n\torm.RegisterModel(new(User));\n\torm.RunSyncdb(\"default\",false,true);\n}"} {"input": "package daemon\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetMapNameOKCode int = 200\n\n\ntype GetMapNameOK struct {\n\n\tPayload *models.BPFMap `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetMapNameOK() *GetMapNameOK {\n\n\treturn &GetMapNameOK{}\n}\n\n\nfunc (o *GetMapNameOK) WithPayload(payload *models.BPFMap) *GetMapNameOK {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *GetMapNameOK) SetPayload(payload *models.BPFMap) {\n\to.Payload = payload\n}\n\n\n\n\n\nconst GetMapNameNotFoundCode int = 404\n\n\ntype GetMapNameNotFound struct {\n}\n\n\nfunc NewGetMapNameNotFound() *GetMapNameNotFound {\n\n\treturn &GetMapNameNotFound{}\n}\n\n\nfunc (o *GetMapNameNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc (o *GetMapNameOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}"} {"input": "package framework\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestAegisHelpers(t *testing.T) ", "output": "{\n\tConvey(\"GetVariable()\", t, func() {\n\t\ta := New(Handlers{})\n\t\ttestVars := map[string]string{\"foo\": \"bar\"}\n\t\ta.Services.Variables = testVars\n\n\t\tConvey(\"Should be able to return a variable value given its key\", func() {\n\t\t\tval := a.GetVariable(\"foo\")\n\t\t\tSo(val, ShouldEqual, \"bar\")\n\t\t})\n\n\t\tConvey(\"Should return an OS environment variable fallback\", func() {\n\t\t\tos.Setenv(\"testvar\", \"notbar\")\n\t\t\tval := a.GetVariable(\"testvar\")\n\t\t\tSo(val, ShouldEqual, \"notbar\")\n\t\t\tos.Setenv(\"testvar\", \"\")\n\t\t})\n\t})\n\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc Example_trailingNewline() {\n\tld := NewLineDelimiter(os.Stdout, \"|\")\n\tdefer ld.Flush()\n\tfmt.Fprint(ld, \" Hello \\n World \\n\")\n}\n\n\nfunc Example_noTrailingNewline() ", "output": "{\n\tld := NewLineDelimiter(os.Stdout, \"|\")\n\tdefer ld.Flush()\n\tfmt.Fprint(ld, \" Hello \\n World \")\n}"} {"input": "package vox\n\ntype Block uint8\n\nconst (\n\tBlockNil = 0x00\n\tblockActiveMask = 0x80 \n\tblockTypeMask = 0x7F \n)\n\nfunc (b Block) Active() bool {\n\treturn (blockActiveMask & b) == blockActiveMask\n}\n\nfunc (b Block) Activate(active bool) Block {\n\tif active {\n\t\treturn b | blockActiveMask\n\t}\n\treturn b & blockTypeMask\n}\n\nfunc (b Block) TypeID() uint8 {\n\treturn uint8(b & blockTypeMask)\n}\n\n\n\ntype BlockType struct {\n\tID uint8\n\tTop *TextureRegion\n\tBottom *TextureRegion\n\tSide *TextureRegion\n}\n\ntype BlockBank struct {\n\tTypes []*BlockType\n\ttypeMap map[uint8]*BlockType\n}\n\nfunc NewBlockBank() *BlockBank {\n\treturn &BlockBank{\n\t\ttypeMap: make(map[uint8]*BlockType),\n\t}\n}\n\nfunc (b *BlockBank) AddType(blockType *BlockType) {\n\tb.typeMap[blockType.ID] = blockType\n\tb.Types = append(b.Types, blockType)\n}\n\nfunc (b *BlockBank) TypeOf(block Block) *BlockType {\n\treturn b.typeMap[block.TypeID()]\n}\n\nfunc (b Block) ChangeType(t *BlockType) Block ", "output": "{\n\treturn Block((uint8(b) & blockActiveMask) | t.ID)\n}"} {"input": "package module\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/config\"\n\t\"github.com/hashicorp/terraform/svchost/disco\"\n)\n\nfunc init() {\n\tif os.Getenv(\"TF_LOG\") == \"\" {\n\t\tlog.SetOutput(ioutil.Discard)\n\t}\n}\n\nconst fixtureDir = \"./test-fixtures\"\n\nfunc tempDir(t *testing.T) string {\n\tt.Helper()\n\tdir, err := ioutil.TempDir(\"\", \"tf\")\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\tif err := os.RemoveAll(dir); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\treturn dir\n}\n\n\n\nfunc testStorage(t *testing.T, d *disco.Disco) *Storage {\n\tt.Helper()\n\treturn NewStorage(tempDir(t), d)\n}\n\nfunc testConfig(t *testing.T, n string) *config.Config ", "output": "{\n\tt.Helper()\n\tc, err := config.LoadDir(filepath.Join(fixtureDir, n))\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\treturn c\n}"} {"input": "package zipkin\n\nimport (\n\t\"github.com/jaegertracing/jaeger/thrift-gen/zipkincore\"\n)\n\n\nfunc IsServerCore(anno string) bool {\n\treturn anno == zipkincore.SERVER_SEND || anno == zipkincore.SERVER_RECV\n}\n\n\n\n\n\nfunc IsCore(anno string) bool {\n\treturn IsServerCore(anno) || IsClientCore(anno)\n}\n\n\nfunc FindServiceName(span *zipkincore.Span) string {\n\tfor _, anno := range span.Annotations {\n\t\tendpoint := anno.GetHost()\n\t\tif endpoint == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif IsCore(anno.Value) && endpoint.GetServiceName() != \"\" {\n\t\t\treturn endpoint.GetServiceName()\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc IsClientCore(anno string) bool ", "output": "{\n\treturn anno == zipkincore.CLIENT_SEND || anno == zipkincore.CLIENT_RECV\n}"} {"input": "package etsi\n\nimport (\n\t\"encoding/asn1\"\n\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/util\"\n)\n\ntype qcStatemQcSscdValid struct{}\n\nfunc init() {\n\tlint.RegisterLint(&lint.Lint{\n\t\tName: \"e_qcstatem_qcsscd_valid\",\n\t\tDescription: \"Checks that a QC Statement of the type id-etsi-qcs-QcSSCD has the correct form\",\n\t\tCitation: \"ETSI EN 319 412 - 5 V2.2.1 (2017 - 11) / Section 4.2.2\",\n\t\tSource: lint.EtsiEsi,\n\t\tEffectiveDate: util.EtsiEn319_412_5_V2_2_1_Date,\n\t\tLint: &qcStatemQcSscdValid{},\n\t})\n}\n\nfunc (this *qcStatemQcSscdValid) getStatementOid() *asn1.ObjectIdentifier {\n\treturn &util.IdEtsiQcsQcSSCD\n}\n\nfunc (l *qcStatemQcSscdValid) Initialize() error {\n\treturn nil\n}\n\n\n\nfunc (l *qcStatemQcSscdValid) Execute(c *x509.Certificate) *lint.LintResult {\n\n\terrString := \"\"\n\text := util.GetExtFromCert(c, util.QcStateOid)\n\ts := util.ParseQcStatem(ext.Value, *l.getStatementOid())\n\terrString += s.GetErrorInfo()\n\n\tif len(errString) == 0 {\n\t\treturn &lint.LintResult{Status: lint.Pass}\n\t} else {\n\t\treturn &lint.LintResult{Status: lint.Error, Details: errString}\n\t}\n}\n\nfunc (l *qcStatemQcSscdValid) CheckApplies(c *x509.Certificate) bool ", "output": "{\n\tif !util.IsExtInCert(c, util.QcStateOid) {\n\t\treturn false\n\t}\n\tif util.ParseQcStatem(util.GetExtFromCert(c, util.QcStateOid).Value, *l.getStatementOid()).IsPresent() {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package iso20022\n\n\ntype ATMContext4 struct {\n\n\tSessionReference *Max35Text `xml:\"SsnRef,omitempty\"`\n\n\tService *ATMService4 `xml:\"Svc\"`\n}\n\nfunc (a *ATMContext4) SetSessionReference(value string) {\n\ta.SessionReference = (*Max35Text)(&value)\n}\n\n\n\nfunc (a *ATMContext4) AddService() *ATMService4 ", "output": "{\n\ta.Service = new(ATMService4)\n\treturn a.Service\n}"} {"input": "package errorlib\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n)\n\n\n\n\nfunc Merge(errs []error) error ", "output": "{\n\tif len(errs) == 0 {\n\t\treturn nil\n\t}\n\tif len(errs) == 1 {\n\t\treturn errs[0]\n\t}\n\tvar buf bytes.Buffer\n\tnumErrors := 0\n\tfor _, err := range errs {\n\t\tif err == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif numErrors > 0 {\n\t\t\tbuf.WriteString(\", \")\n\t\t}\n\t\tbuf.WriteString(err.Error())\n\t\tnumErrors++\n\t}\n\tif numErrors == 0 {\n\t\treturn nil\n\t} else if numErrors == 1 {\n\t\treturn errors.New(buf.String())\n\t}\n\tmessage := fmt.Sprintf(\"%v errors: %s\", numErrors, buf.String())\n\treturn errors.New(message)\n}"} {"input": "package terraform\n\nimport (\n\t\"github.com/hashicorp/terraform/config\"\n\t\"github.com/hashicorp/terraform/config/module\"\n\t\"github.com/hashicorp/terraform/dag\"\n)\n\n\n\n\n\n\n\ntype OrphanResourceTransformer struct {\n\tConcrete ConcreteResourceNodeFunc\n\n\tState *State\n\n\tModule *module.Tree\n}\n\nfunc (t *OrphanResourceTransformer) Transform(g *Graph) error {\n\tif t.State == nil {\n\t\treturn nil\n\t}\n\n\tfor _, ms := range t.State.Modules {\n\t\tif err := t.transform(g, ms); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (t *OrphanResourceTransformer) transform(g *Graph, ms *ModuleState) error ", "output": "{\n\tvar c *config.Config\n\tif m := t.Module.Child(ms.Path[1:]); m != nil {\n\t\tc = m.Config()\n\t}\n\n\tfor _, key := range ms.Orphans(c) {\n\t\taddr, err := parseResourceAddressInternal(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\taddr.Path = ms.Path[1:]\n\n\t\tabstract := &NodeAbstractResource{Addr: addr}\n\t\tvar node dag.Vertex = abstract\n\t\tif f := t.Concrete; f != nil {\n\t\t\tnode = f(abstract)\n\t\t}\n\n\t\tg.Add(node)\n\t}\n\n\treturn nil\n}"} {"input": "package scan\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"h12.io/dfa\"\n)\n\ntype Matcher struct {\n\t*dfa.M\n\tEOF int\n\tIllegal int\n\n\tfast *dfa.FastM\n}\ntype MID struct {\n\tM interface{}\n\tID int\n}\n\nfunc NewMatcher(eof, illegal int, mids []MID) *Matcher {\n\tm := or(mids)\n\tfast := m.ToFast()\n\treturn &Matcher{\n\t\tEOF: eof,\n\t\tIllegal: illegal,\n\t\tM: m,\n\t\tfast: fast}\n}\n\nfunc (m *Matcher) Init() *Matcher {\n\tm.fast = m.M.ToFast()\n\treturn m\n}\n\nfunc (m *Matcher) Size() int {\n\treturn m.fast.Size()\n}\n\n\n\nfunc (m *Matcher) WriteGo(w io.Writer, pac string) {\n\tfmt.Fprintln(w, \"&scan.Matcher{\")\n\tfmt.Fprintf(w, \"EOF: %d,\\n\", m.EOF)\n\tfmt.Fprintf(w, \"Illegal: %d,\\n\", m.Illegal)\n\tfmt.Fprint(w, \"M: \")\n\tm.M.WriteGo(w, pac)\n\tfmt.Fprintln(w, \"}\")\n}\n\nfunc or(mids []MID) *dfa.M {\n\tms := make([]interface{}, len(mids))\n\tfor i, mid := range mids {\n\t\tvar m *dfa.M\n\t\tswitch o := mid.M.(type) {\n\t\tcase *dfa.M:\n\t\t\tm = o\n\t\tcase string:\n\t\t\tm = dfa.Str(o)\n\t\tdefault:\n\t\t\tpanic(\"member M of MID should be type of either string or *M\")\n\t\t}\n\t\tms[i] = m.As(mid.ID)\n\t}\n\treturn dfa.Or(ms...)\n}\n\nfunc (m *Matcher) Count() int ", "output": "{\n\treturn m.fast.Count()\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype OpenpitrixListReleaseResponse struct {\n\n\tReleaseSet OpenpitrixListReleaseResponseReleaseSet `json:\"release_set\"`\n}\n\n\nfunc (m *OpenpitrixListReleaseResponse) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\nfunc (m *OpenpitrixListReleaseResponse) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\n\n\nfunc (m *OpenpitrixListReleaseResponse) UnmarshalBinary(b []byte) error ", "output": "{\n\tvar res OpenpitrixListReleaseResponse\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}"} {"input": "package convert\n\nimport (\n\t\"strings\"\n\n\t\"code.gitea.io/gitea/modules/setting\"\n\t\"code.gitea.io/gitea/modules/structs\"\n)\n\n\n\n\n\nfunc ToGitServiceType(value string) structs.GitServiceType {\n\tswitch strings.ToLower(value) {\n\tcase \"github\":\n\t\treturn structs.GithubService\n\tcase \"gitea\":\n\t\treturn structs.GiteaService\n\tcase \"gitlab\":\n\t\treturn structs.GitlabService\n\tcase \"gogs\":\n\t\treturn structs.GogsService\n\tdefault:\n\t\treturn structs.PlainGitService\n\t}\n}\n\nfunc ToCorrectPageSize(size int) int ", "output": "{\n\tif size <= 0 {\n\t\tsize = setting.API.DefaultPagingNum\n\t} else if size > setting.API.MaxResponseItems {\n\t\tsize = setting.API.MaxResponseItems\n\t}\n\treturn size\n}"} {"input": "package embed\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"go.etcd.io/etcd/v3/auth\"\n)\n\n\n\n\nfunc TestStartEtcdWrongToken(t *testing.T) ", "output": "{\n\ttdir, err := ioutil.TempDir(os.TempDir(), \"token-test\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tdir)\n\tcfg := NewConfig()\n\tcfg.Dir = tdir\n\tcfg.AuthToken = \"wrong-token\"\n\tif _, err = StartEtcd(cfg); err != auth.ErrInvalidAuthOpts {\n\t\tt.Fatalf(\"expected %v, got %v\", auth.ErrInvalidAuthOpts, err)\n\t}\n}"} {"input": "package pmgo\n\nimport mgo \"gopkg.in/mgo.v2\"\n\ntype IterManager interface {\n\tAll(result interface{}) error\n\tClose() error\n\tDone() bool\n\tErr() error\n\tFor(result interface{}, f func() error) (err error)\n\tNext(result interface{}) bool\n\tTimeout() bool\n}\n\ntype Iter struct {\n\titer *mgo.Iter\n}\n\nfunc NewIter(iter *mgo.Iter) IterManager {\n\treturn &Iter{iter}\n}\n\nfunc (i *Iter) All(result interface{}) error {\n\treturn i.iter.All(result)\n}\n\nfunc (i *Iter) Close() error {\n\treturn i.iter.Close()\n}\n\n\n\nfunc (i *Iter) Err() error {\n\treturn i.iter.Err()\n}\n\nfunc (i *Iter) For(result interface{}, f func() error) (err error) {\n\treturn i.iter.For(result, f)\n}\n\nfunc (i *Iter) Next(result interface{}) bool {\n\treturn i.iter.Next(result)\n}\n\nfunc (i *Iter) Timeout() bool {\n\treturn i.iter.Timeout()\n}\n\nfunc (i *Iter) Done() bool ", "output": "{\n\treturn i.iter.Done()\n}"} {"input": "package distribution \n\nimport \"github.com/tiborvass/docker/api/server/router\"\n\n\ntype distributionRouter struct {\n\tbackend Backend\n\troutes []router.Route\n}\n\n\n\n\n\nfunc (r *distributionRouter) Routes() []router.Route {\n\treturn r.routes\n}\n\n\nfunc (r *distributionRouter) initRoutes() {\n\tr.routes = []router.Route{\n\t\trouter.NewGetRoute(\"/distribution/{name:.*}/json\", r.getDistributionInfo),\n\t}\n}\n\nfunc NewRouter(backend Backend) router.Router ", "output": "{\n\tr := &distributionRouter{\n\t\tbackend: backend,\n\t}\n\tr.initRoutes()\n\treturn r\n}"} {"input": "package armmariadb_test\n\nimport (\n\t\"context\"\n\t\"log\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azcore/to\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/mariadb/armmariadb\"\n)\n\n\n\n\nfunc ExampleCheckNameAvailabilityClient_Execute() ", "output": "{\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armmariadb.NewCheckNameAvailabilityClient(\"\", cred, nil)\n\tres, err := client.Execute(ctx,\n\t\tarmmariadb.NameAvailabilityRequest{\n\t\t\tName: to.StringPtr(\"\"),\n\t\t\tType: to.StringPtr(\"\"),\n\t\t},\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Response result: %#v\\n\", res.CheckNameAvailabilityClientExecuteResult)\n}"} {"input": "package gottyclient\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\t\"unsafe\"\n)\n\n\n\nfunc resetSignalSIGWINCH() {\n\tsignal.Reset(syscall.SIGWINCH)\n}\n\nfunc syscallTIOCGWINSZ() ([]byte, error) {\n\tws := winsize{}\n\n\tsyscall.Syscall(syscall.SYS_IOCTL,\n\t\tuintptr(0), uintptr(syscall.TIOCGWINSZ),\n\t\tuintptr(unsafe.Pointer(&ws)))\n\n\tb, err := json.Marshal(ws)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"json.Marshal error: %v\", err)\n\t}\n\treturn b, err\n}\n\nfunc notifySignalSIGWINCH(c chan<- os.Signal) ", "output": "{\n\tsignal.Notify(c, syscall.SIGWINCH)\n}"} {"input": "package gtk\n\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (v *FileChooserButton) GetFocusOnClick() bool {\n\treturn gobool(C.gtk_file_chooser_button_get_focus_on_click(v.native()))\n}\n\n\nfunc (v *FileChooserButton) SetFocusOnClick(grabFocus bool) {\n\tC.gtk_file_chooser_button_set_focus_on_click(v.native(), gbool(grabFocus))\n}\n\n\n\n\nfunc (v *Button) GetFocusOnClick() bool {\n\tc := C.gtk_button_get_focus_on_click(v.native())\n\treturn gobool(c)\n}\n\n\nfunc (v *Button) SetFocusOnClick(focusOnClick bool) {\n\tC.gtk_button_set_focus_on_click(v.native(), gbool(focusOnClick))\n}\n\n\n\n\nfunc (v *TextIter) BeginsTag(v1 *TextTag) bool {\n\treturn gobool(C.gtk_text_iter_begins_tag(v.native(), v1.native()))\n}\n\n\n\n\nfunc (v *Window) ParseGeometry(geometry string) bool {\n\tcstr := C.CString(geometry)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_window_parse_geometry(v.native(), (*C.gchar)(cstr))\n\treturn gobool(c)\n}\n\n\nfunc (v *Window) ResizeToGeometry(width, height int) {\n\tC.gtk_window_resize_to_geometry(v.native(), C.gint(width), C.gint(height))\n}\n\n\n\n\nfunc (v *Window) SetDefaultGeometry(width, height int) ", "output": "{\n\tC.gtk_window_set_default_geometry(v.native(), C.gint(width),\n\t\tC.gint(height))\n}"} {"input": "package chapter3\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc TestQueue(t *testing.T) ", "output": "{\n\tcases := []struct {\n\t\tvals []int\n\t}{\n\t\t{\n\t\t\t[]int{1, 2, 3, 4, 5},\n\t\t},\n\t\t{\n\t\t\t[]int{1},\n\t\t},\n\t\t{\n\t\t\t[]int{},\n\t\t},\n\t}\n\tfor _, c := range cases {\n\t\ts := &Queue{}\n\t\tfor _, val := range c.vals {\n\t\t\ts.Add(val)\n\t\t}\n\t\tactual := []int{}\n\t\tfor {\n\t\t\tval, err := s.Remove()\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tactual = append(actual, val)\n\t\t\t}\n\t\t}\n\t\tif !reflect.DeepEqual(c.vals, actual) {\n\t\t\tt.Fatalf(\"Expected: %v, actual: %v\\n\", c.vals, actual)\n\t\t}\n\t}\n\n}"} {"input": "package balanced_brackets\n\nimport \"testing\"\n\n\n\nfunc TestStackUnbalanced(t *testing.T) {\n\n\tgot := Balance(\"{(])}\")\n\n\twant := false\n\n\tif got != want {\n\n\t\tt.Errorf(\"Should be %v but is %v\", want, got)\n\n\t}\n}\n\nfunc TestOpenStack(t *testing.T) {\n\n\tgot := Balance(\"(\")\n\n\twant := false\n\n\tif got != want {\n\n\t\tt.Errorf(\"Should be %v but is %v\", want, got)\n\n\t}\n}\n\nfunc TestStackBalanced(t *testing.T) ", "output": "{\n\n\tgot := Balance(\"{[]}()\")\n\n\twant := true\n\n\tif got != want {\n\n\t\tt.Errorf(\"Should be %v but is %v\", want, got)\n\n\t}\n\n}"} {"input": "package ignition\n\nimport (\n\t\"github.com/coreos/ignition/config/types\"\n\t\"github.com/hashicorp/terraform/helper/schema\"\n)\n\nfunc resourceGroup() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceGroupCreate,\n\t\tDelete: resourceGroupDelete,\n\t\tExists: resourceGroupExists,\n\t\tRead: resourceGroupRead,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"name\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"gid\": &schema.Schema{\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"password_hash\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\n\n\nfunc resourceGroupDelete(d *schema.ResourceData, meta interface{}) error {\n\td.SetId(\"\")\n\treturn nil\n}\n\nfunc resourceGroupExists(d *schema.ResourceData, meta interface{}) (bool, error) {\n\tid, err := buildGroup(d, meta.(*cache))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn id == d.Id(), nil\n}\n\nfunc resourceGroupRead(d *schema.ResourceData, meta interface{}) error {\n\treturn nil\n}\n\nfunc buildGroup(d *schema.ResourceData, c *cache) (string, error) {\n\treturn c.addGroup(&types.Group{\n\t\tName: d.Get(\"name\").(string),\n\t\tPasswordHash: d.Get(\"password_hash\").(string),\n\t\tGid: getUInt(d, \"gid\"),\n\t}), nil\n}\n\nfunc resourceGroupCreate(d *schema.ResourceData, meta interface{}) error ", "output": "{\n\tid, err := buildGroup(d, meta.(*cache))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.SetId(id)\n\treturn nil\n}"} {"input": "package metrics\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"github.com/prometheus/client_golang/prometheus/promhttp\"\n\t\"net/http\"\n\t\"sync\"\n)\n\ntype Server struct {\n\tcertificateCh <-chan tls.Certificate\n\n\tsync.Mutex\n\tcertificate *tls.Certificate\n}\n\n\n\nfunc (s *Server) watchForNewCertificates() {\n\tfor {\n\t\tselect {\n\t\tcase cert := <-s.certificateCh:\n\t\t\ts.certificate = &cert\n\t\t}\n\t}\n}\n\nfunc (s *Server) start(roots *x509.CertPool) {\n\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/metrics\", promhttp.Handler())\n\n\tserver := &http.Server{\n\t\tHandler: mux,\n\t}\n\n\tif s.certificateCh != nil {\n\t\ttlsConfig := &tls.Config{\n\t\t\tGetCertificate: s.getCertificate,\n\t\t}\n\n\t\tif roots != nil {\n\t\t\ttlsConfig.ClientCAs = roots\n\t\t\ttlsConfig.ClientAuth = tls.RequireAndVerifyClientCert\n\t\t}\n\n\t\tserver.TLSConfig = tlsConfig\n\n\t\tgo server.ListenAndServeTLS(\"\", \"\")\n\t} else {\n\t\tgo server.ListenAndServe()\n\t}\n}\n\nfunc StartServer(certificateCh <-chan tls.Certificate, roots *x509.CertPool) {\n\n\tserver := &Server{\n\t\tcertificateCh: certificateCh,\n\t}\n\n\tif certificateCh != nil {\n\t\tgo server.watchForNewCertificates()\n\t}\n\n\tgo server.start(roots)\n}\n\nfunc (s *Server) getCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) ", "output": "{\n\treturn s.certificate, nil\n}"} {"input": "package payloads_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/01org/ciao/payloads\"\n\t\"github.com/01org/ciao/testutil\"\n\t\"gopkg.in/yaml.v2\"\n)\n\n\n\nfunc TestDeleteFailureMarshal(t *testing.T) {\n\terror := ErrorDeleteFailure{\n\t\tInstanceUUID: testutil.InstanceUUID,\n\t\tReason: DeleteNoInstance,\n\t}\n\n\ty, err := yaml.Marshal(&error)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif string(y) != testutil.DeleteFailureYaml {\n\t\tt.Errorf(\"DeleteFailure marshalling failed\\n[%s]\\n vs\\n[%s]\", string(y), testutil.DeleteFailureYaml)\n\t}\n}\n\nfunc TestDeleteFailureString(t *testing.T) {\n\tvar stringTests = []struct {\n\t\tr DeleteFailureReason\n\t\texpected string\n\t}{\n\t\t{DeleteNoInstance, \"Instance does not exist\"},\n\t\t{DeleteInvalidPayload, \"YAML payload is corrupt\"},\n\t\t{DeleteInvalidData, \"Command section of YAML payload is corrupt or missing required information\"},\n\t}\n\terror := ErrorDeleteFailure{\n\t\tInstanceUUID: testutil.InstanceUUID,\n\t}\n\tfor _, test := range stringTests {\n\t\terror.Reason = test.r\n\t\ts := error.Reason.String()\n\t\tif s != test.expected {\n\t\t\tt.Errorf(\"expected \\\"%s\\\", got \\\"%s\\\"\", test.expected, s)\n\t\t}\n\t}\n}\n\nfunc TestDeleteFailureUnmarshal(t *testing.T) ", "output": "{\n\tvar error ErrorDeleteFailure\n\terr := yaml.Unmarshal([]byte(testutil.DeleteFailureYaml), &error)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif error.InstanceUUID != testutil.InstanceUUID {\n\t\tt.Error(\"Wrong UUID field\")\n\t}\n\n\tif error.Reason != DeleteNoInstance {\n\t\tt.Error(\"Wrong Error field\")\n\t}\n}"} {"input": "package s3storage\n\nimport (\n\t\"testing\"\n\n\t\"github.com/AdRoll/goamz/aws\"\n\t\"github.com/AdRoll/goamz/s3\"\n\t\"github.com/AdRoll/goamz/s3/s3test\"\n\t\"github.com/facebookgo/ensure\"\n)\n\n\ntype MockS3 struct {\n\tauth aws.Auth\n\tregion aws.Region\n\tsrv *s3test.Server\n\tconfig *s3test.Config\n}\n\n\nfunc (s *MockS3) Start(t *testing.T) {\n\tsrv, err := s3test.NewServer(s.config)\n\tensure.Nil(t, err)\n\tensure.NotNil(t, srv)\n\n\ts.srv = srv\n\ts.region = aws.Region{\n\t\tName: \"faux-region-1\",\n\t\tS3Endpoint: srv.URL(),\n\t\tS3LocationConstraint: true, \n\t}\n}\n\n\n\n\n\nfunc NewMockS3(t *testing.T) *MockS3 {\n\tm := MockS3{}\n\tm.Start(t)\n\treturn &m\n}\n\n\nfunc NewStorageWithMockS3(s *MockS3) (*S3Storage, error) {\n\treturn NewS3Storage(s.region, s.auth, \"testbucket\", \"test\", s3.Private)\n}\n\nfunc (s *MockS3) Stop() ", "output": "{\n\ts.srv.Quit()\n}"} {"input": "package cloudformation\n\n\n\ntype AWSEMRInstanceGroupConfig_EbsConfiguration struct {\n\n\tEbsBlockDeviceConfigs []AWSEMRInstanceGroupConfig_EbsBlockDeviceConfig `json:\"EbsBlockDeviceConfigs,omitempty\"`\n\n\tEbsOptimized bool `json:\"EbsOptimized,omitempty\"`\n}\n\n\n\n\nfunc (r *AWSEMRInstanceGroupConfig_EbsConfiguration) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::EMR::InstanceGroupConfig.EbsConfiguration\"\n}"} {"input": "package jet\n\nimport (\n\t\"strings\"\n)\n\n\n\ntype ColumnConverter interface {\n\tColumnToFieldName(col string) string\n}\n\n\nvar SnakeCaseConverter ColumnConverter = &snakeConv{}\n\ntype snakeConv struct{}\n\n\n\nfunc (conv *snakeConv) ColumnToFieldName(col string) string ", "output": "{\n\tname := \"\"\n\tif l := len(col); l > 0 {\n\t\tchunks := strings.Split(col, \"_\")\n\t\tfor i, v := range chunks {\n\t\t\tchunks[i] = strings.Title(v)\n\t\t}\n\t\tname = strings.Join(chunks, \"\")\n\t}\n\treturn name\n}"} {"input": "package command\n\nimport (\n\t\"flag\"\n\n\t\"fmt\"\n\n\tapi \"github.com/elodina/stack-deploy/framework\"\n)\n\ntype AddUserCommand struct{}\n\nfunc (auc *AddUserCommand) Run(args []string) int {\n\tvar (\n\t\tflags = flag.NewFlagSet(\"adduser\", flag.ExitOnError)\n\t\tapiUrl = flags.String(\"api\", \"\", \"Stack-deploy server address.\")\n\t\tname = flags.String(\"name\", \"\", \"New user name\")\n\t\tadmin = flags.Bool(\"admin\", false, \"Create admin\")\n\t)\n\tflags.Parse(args)\n\n\tstackDeployApi, err := resolveApi(*apiUrl)\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tclient := api.NewClient(stackDeployApi)\n\n\trole := \"regular\"\n\tif *admin {\n\t\trole = \"admin\"\n\t}\n\tkey, err := client.CreateUser(&api.CreateUserRequest{\n\t\tName: *name,\n\t\tRole: role,\n\t})\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tfmt.Printf(\"User added. Key: %s\\n\", key)\n\treturn 0\n}\n\n\n\nfunc (auc *AddUserCommand) Synopsis() string {\n\treturn \"Add new user\"\n}\n\nfunc (auc *AddUserCommand) Help() string ", "output": "{\n\treturn \"\"\n}"} {"input": "package twofactor\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/base32\"\n)\n\n\ntype Secret string\n\n\n\nfunc NewSecret(length int) (Secret, error) {\n\tif length <= 0 {\n\t\tlength = 10\n\t}\n\tb := make([]byte, length)\n\t_, err := rand.Read(b)\n\treturn Secret(base32.StdEncoding.EncodeToString(b)), err\n}\n\n\n\n\n\nfunc (s Secret) String() string {\n\treturn string(s)\n}\n\n\nfunc Int64ToBytes(n int64) []byte {\n\tb := make([]byte, 8)\n\tfor i := len(b) - 1; i >= 0; i-- {\n\t\tb[i] = byte(n & 0xff)\n\t\tn = n >> 8\n\t}\n\treturn b\n}\n\nfunc (s Secret) Bytes() ([]byte, error) ", "output": "{\n\treturn base32.StdEncoding.DecodeString(s.String())\n}"} {"input": "package git\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\n\n\nfunc (r *Repo) Head() Id {\n\treturn r.resolveRef(\"HEAD\")\n}\n\nfunc (r *Repo) packedRefs() {\n\tif r.refs == nil {\n\t\tr.refs = map[string]Id{}\n\t}\n\tpackedRefs := r.file(\"packed-refs\")\n\tcontent, err := ioutil.ReadFile(packedRefs)\n\tif err != nil {\n\t\treturn\n\t}\n\tlines := bytes.Split(content, []byte{'\\n'})\n\tfor _, line := range lines {\n\t\tif len(line) == 0 || line[0] == '#' {\n\t\t\tcontinue\n\t\t}\n\t\tparts := bytes.SplitN(line, []byte{' '}, 2)\n\t\tif len(parts[0]) != 40 {\n\t\t\tcontinue\n\t\t}\n\t\tid := IdFromString(string(parts[0]))\n\t\trefname := string(parts[1])\n\t\tr.refs[refname] = id\n\t}\n\treturn\n}\n\n\nfunc (r *Repo) Refs() map[string]Id {\n\tr.packedRefs()\n\tif head := r.Head(); head != \"\" {\n\t\tr.refs[\"HEAD\"] = head\n\t}\n\tfilepath.Walk(r.file(\"refs\"), refVisitor(r))\n\treturn r.refs\n}\n\nfunc refVisitor(r *Repo) filepath.WalkFunc {\n\treturn func(path string, f os.FileInfo, err error) error {\n\t\tif !f.IsDir() {\n\t\t\tr.resolveRef(path[5:])\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc (r *Repo) resolveRef(name string) (id Id) ", "output": "{\n\tif id := r.refs[name]; id != \"\" {\n\t\treturn id\n\t}\n\tcontent, err := ioutil.ReadFile(r.file(name))\n\tif err != nil {\n\t\tpanic(err.Error())\n\t\treturn \"\"\n\t}\n\tcontent = bytes.TrimSpace(content)\n\tif bytes.HasPrefix(content, []byte(\"ref: \")) {\n\t\tid = r.resolveRef(string(content[5:]))\n\t} else {\n\t\tid = IdFromString(string(content))\n\t}\n\tif id != \"\" {\n\t\tr.refs[name] = id\n\t}\n\treturn\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n)\n\nfunc Commafy(i interface{}) string {\n\tvar n int64\n\tswitch i.(type) {\n\tcase int:\n\t\tn = int64(i.(int))\n\tcase int64:\n\t\tn = i.(int64)\n\tcase int32:\n\t\tn = int64(i.(int32))\n\t}\n\tif n > 1000 {\n\t\tr := n % 1000\n\t\tn = n / 1000\n\t\treturn fmt.Sprintf(\"%s,%03d\", Commafy(n), r)\n\t}\n\treturn fmt.Sprintf(\"%d\", n)\n}\n\nfunc FloatToPercent(i float64) string {\n\treturn fmt.Sprintf(\"%.0f\", i*100.0)\n}\n\n\n\nfunc NanoSecondToHuman(v float64) string {\n\tvar suffix string\n\tswitch {\n\tcase v > 1000000000:\n\t\tv /= 1000000000\n\t\tsuffix = \"s\"\n\tcase v > 1000000:\n\t\tv /= 1000000\n\t\tsuffix = \"ms\"\n\tcase v > 1000:\n\t\tv /= 1000\n\t\tsuffix = \"us\"\n\tdefault:\n\t\tsuffix = \"ns\"\n\t}\n\treturn fmt.Sprintf(\"%0.1f%s\", v, suffix)\n}\n\nfunc PercSuffix(i float64) string ", "output": "{\n\tswitch int(i*100) % 10 {\n\tcase 1:\n\t\treturn \"st\"\n\tcase 2:\n\t\treturn \"nd\"\n\tcase 3:\n\t\treturn \"rd\"\n\t}\n\treturn \"th\"\n}"} {"input": "package process\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc toHash(input []byte) string {\n\thasher := sha256.New()\n\thasher.Write(input)\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}\n\nfunc getRandomData() []byte {\n\tsize := 64\n\trb := make([]byte, size)\n\t_, _ = rand.Read(rb)\n\treturn rb\n}\n\nfunc RandomHash() string {\n\treturn toHash(getRandomData())\n}\n\n\ntype Token struct {\n\tHash string\n}\n\nvar ProcessToken *Token = NewToken()\n\n\n\nfunc PrettyUniqueToken() string {\n\treturn fmt.Sprintf(\"%d:%s\", time.Now().UnixNano(), NewToken().Hash)\n}\n\nfunc NewToken() *Token ", "output": "{\n\treturn &Token{\n\t\tHash: RandomHash(),\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype Status struct {\n\tPartOfCluster bool\n\tTimestamp time.Time\n\tExpired int\n}\n\nconst reply_200 = \"Cluster Node is up\"\nconst reply_500 = \"Cluster Node is down\"\n\n\n\nfunc (s *Status) get(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tintervalAgo := time.Now().Add(-time.Duration(s.Expired) * time.Second)\n\tdefer r.Body.Close()\n\n\tif s.Timestamp.After(intervalAgo) {\n\t\tif s.PartOfCluster {\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\tfmt.Fprintln(w, reply_200)\n\t\t\treturn\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t\t\tfmt.Fprintln(w, reply_500)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t\tfmt.Fprintln(w, reply_500)\n\t\treturn\n\t}\n}"} {"input": "package dml\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\n\ntype ST_AnimationDgmBuildType struct {\n\tST_AnimationBuildType ST_AnimationBuildType\n\tST_AnimationDgmOnlyBuildType ST_AnimationDgmOnlyBuildType\n}\n\nfunc (m *ST_AnimationDgmBuildType) Validate() error {\n\treturn m.ValidateWithPath(\"\")\n}\n\n\n\nfunc (m *ST_AnimationDgmBuildType) ValidateWithPath(path string) error {\n\tmems := []string{}\n\tif m.ST_AnimationBuildType != ST_AnimationBuildTypeUnset {\n\t\tmems = append(mems, \"ST_AnimationBuildType\")\n\t}\n\tif m.ST_AnimationDgmOnlyBuildType != ST_AnimationDgmOnlyBuildTypeUnset {\n\t\tmems = append(mems, \"ST_AnimationDgmOnlyBuildType\")\n\t}\n\tif len(mems) > 1 {\n\t\treturn fmt.Errorf(\"%s too many members set: %v\", path, mems)\n\t}\n\treturn nil\n}\n\nfunc (m ST_AnimationDgmBuildType) String() string {\n\tif m.ST_AnimationBuildType != ST_AnimationBuildTypeUnset {\n\t\treturn m.ST_AnimationBuildType.String()\n\t}\n\tif m.ST_AnimationDgmOnlyBuildType != ST_AnimationDgmOnlyBuildTypeUnset {\n\t\treturn m.ST_AnimationDgmOnlyBuildType.String()\n\t}\n\treturn \"\"\n}\n\nfunc (m ST_AnimationDgmBuildType) MarshalXML(e *xml.Encoder, start xml.StartElement) error ", "output": "{\n\te.EncodeToken(start)\n\tif m.ST_AnimationBuildType != ST_AnimationBuildTypeUnset {\n\t\te.EncodeToken(xml.CharData(m.ST_AnimationBuildType.String()))\n\t}\n\tif m.ST_AnimationDgmOnlyBuildType != ST_AnimationDgmOnlyBuildTypeUnset {\n\t\te.EncodeToken(xml.CharData(m.ST_AnimationDgmOnlyBuildType.String()))\n\t}\n\treturn e.EncodeToken(xml.EndElement{Name: start.Name})\n}"} {"input": "package insulin\n\nimport (\n\t\"math\"\n\n\t\"github.com/tidepool-org/platform/data\"\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tConcentrationUnitsUnitsPerML = \"Units/mL\"\n\tConcentrationValueUnitsPerMLMaximum = 10000.0\n\tConcentrationValueUnitsPerMLMinimum = 0.0\n)\n\nfunc ConcentrationUnits() []string {\n\treturn []string{\n\t\tConcentrationUnitsUnitsPerML,\n\t}\n}\n\ntype Concentration struct {\n\tUnits *string `json:\"units,omitempty\" bson:\"units,omitempty\"`\n\tValue *float64 `json:\"value,omitempty\" bson:\"value,omitempty\"`\n}\n\n\n\nfunc NewConcentration() *Concentration {\n\treturn &Concentration{}\n}\n\nfunc (c *Concentration) Parse(parser structure.ObjectParser) {\n\tc.Units = parser.String(\"units\")\n\tc.Value = parser.Float64(\"value\")\n}\n\nfunc (c *Concentration) Validate(validator structure.Validator) {\n\tvalidator.String(\"units\", c.Units).Exists().OneOf(ConcentrationUnits()...)\n\tvalidator.Float64(\"value\", c.Value).Exists().InRange(ConcentrationValueRangeForUnits(c.Units))\n}\n\nfunc (c *Concentration) Normalize(normalizer data.Normalizer) {}\n\nfunc ConcentrationValueRangeForUnits(units *string) (float64, float64) {\n\tif units != nil {\n\t\tswitch *units {\n\t\tcase ConcentrationUnitsUnitsPerML:\n\t\t\treturn ConcentrationValueUnitsPerMLMinimum, ConcentrationValueUnitsPerMLMaximum\n\t\t}\n\t}\n\treturn -math.MaxFloat64, math.MaxFloat64\n}\n\nfunc ParseConcentration(parser structure.ObjectParser) *Concentration ", "output": "{\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewConcentration()\n\tparser.Parse(datum)\n\treturn datum\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\n\tv1beta1 \"kubevirt.io/client-go/generated/containerized-data-importer/clientset/versioned/typed/core/v1beta1\"\n)\n\ntype FakeCdiV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeCdiV1beta1) CDIs() v1beta1.CDIInterface {\n\treturn &FakeCDIs{c}\n}\n\nfunc (c *FakeCdiV1beta1) CDIConfigs() v1beta1.CDIConfigInterface {\n\treturn &FakeCDIConfigs{c}\n}\n\n\n\nfunc (c *FakeCdiV1beta1) DataSources(namespace string) v1beta1.DataSourceInterface {\n\treturn &FakeDataSources{c, namespace}\n}\n\nfunc (c *FakeCdiV1beta1) DataVolumes(namespace string) v1beta1.DataVolumeInterface {\n\treturn &FakeDataVolumes{c, namespace}\n}\n\nfunc (c *FakeCdiV1beta1) ObjectTransfers() v1beta1.ObjectTransferInterface {\n\treturn &FakeObjectTransfers{c}\n}\n\nfunc (c *FakeCdiV1beta1) StorageProfiles() v1beta1.StorageProfileInterface {\n\treturn &FakeStorageProfiles{c}\n}\n\n\n\nfunc (c *FakeCdiV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeCdiV1beta1) DataImportCrons(namespace string) v1beta1.DataImportCronInterface ", "output": "{\n\treturn &FakeDataImportCrons{c, namespace}\n}"} {"input": "package adapterManager\n\nimport (\n\t\"istio.io/mixer/pkg/adapter\"\n\t\"istio.io/mixer/pkg/pool\"\n)\n\ntype env struct {\n\tlogger adapter.Logger\n\tgp *pool.GoroutinePool\n}\n\nfunc newEnv(aspect string, gp *pool.GoroutinePool) adapter.Env {\n\treturn env{\n\t\tlogger: newLogger(aspect),\n\t\tgp: gp,\n\t}\n}\n\nfunc (e env) Logger() adapter.Logger {\n\treturn e.logger\n}\n\n\n\nfunc (e env) ScheduleDaemon(fn adapter.DaemonFunc) {\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\t_ = e.Logger().Errorf(\"Adapter daemon failed: %v\", r)\n\n\t\t\t}\n\t\t}()\n\n\t\tfn()\n\t}()\n}\n\nfunc (e env) ScheduleWork(fn adapter.WorkFunc) ", "output": "{\n\te.gp.ScheduleWork(func() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\t_ = e.Logger().Errorf(\"Adapter worker failed: %v\", r)\n\n\t\t\t}\n\t\t}()\n\n\t\tfn()\n\t})\n}"} {"input": "package badger\n\n\n\n\n\n\n\n\n\ntype ManagedDB struct {\n\t*DB\n}\n\n\n\n\n\n\nfunc OpenManaged(opts Options) (*ManagedDB, error) {\n\topts.managedTxns = true\n\tdb, err := Open(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ManagedDB{db}, nil\n}\n\n\n\nfunc (db *ManagedDB) NewTransaction(update bool) {\n\tpanic(\"Cannot use NewTransaction() for ManagedDB. Use NewTransactionAt() instead.\")\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (txn *Txn) CommitAt(commitTs uint64, callback func(error)) error {\n\tif !txn.db.opt.managedTxns {\n\t\treturn ErrManagedTxn\n\t}\n\ttxn.commitTs = commitTs\n\treturn txn.Commit(callback)\n}\n\n\nfunc (db *ManagedDB) PurgeVersionsBelow(key []byte, ts uint64) error {\n\ttxn := db.NewTransactionAt(ts, false)\n\tdefer txn.Discard()\n\treturn db.purgeVersionsBelow(txn, key, ts)\n}\n\n\n\nfunc (db *ManagedDB) GetSequence(_ []byte, _ uint64) (*Sequence, error) {\n\tpanic(\"Cannot use GetSequence for ManagedDB.\")\n}\n\nfunc (db *ManagedDB) NewTransactionAt(readTs uint64, update bool) *Txn ", "output": "{\n\ttxn := db.DB.NewTransaction(update)\n\ttxn.readTs = readTs\n\treturn txn\n}"} {"input": "package fingerprint\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hashicorp/nomad/client/config\"\n\t\"github.com/hashicorp/nomad/nomad/structs\"\n\t\"github.com/hashicorp/nomad/testutil\"\n)\n\n\n\nfunc TestVaultFingerprint(t *testing.T) ", "output": "{\n\ttv := testutil.NewTestVault(t).Start()\n\tdefer tv.Stop()\n\n\tfp := NewVaultFingerprint(testLogger())\n\tnode := &structs.Node{\n\t\tAttributes: make(map[string]string),\n\t}\n\n\tconfig := config.DefaultConfig()\n\tconfig.VaultConfig = tv.Config\n\n\tok, err := fp.Fingerprint(config, node)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to fingerprint: %s\", err)\n\t}\n\tif !ok {\n\t\tt.Fatalf(\"Failed to apply node attributes\")\n\t}\n\n\tassertNodeAttributeContains(t, node, \"vault.accessible\")\n\tassertNodeAttributeContains(t, node, \"vault.version\")\n\tassertNodeAttributeContains(t, node, \"vault.cluster_id\")\n\tassertNodeAttributeContains(t, node, \"vault.cluster_name\")\n}"} {"input": "package leveldb\n\nimport (\n\t\"testing\"\n\n\t\"github.com/expanse-org/go-expanse/ethdb\"\n\t\"github.com/expanse-org/go-expanse/ethdb/dbtest\"\n\t\"github.com/syndtr/goleveldb/leveldb\"\n\t\"github.com/syndtr/goleveldb/leveldb/storage\"\n)\n\n\n\nfunc TestLevelDB(t *testing.T) ", "output": "{\n\tt.Run(\"DatabaseSuite\", func(t *testing.T) {\n\t\tdbtest.TestDatabaseSuite(t, func() ethdb.KeyValueStore {\n\t\t\tdb, err := leveldb.Open(storage.NewMemStorage(), nil)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\treturn &Database{\n\t\t\t\tdb: db,\n\t\t\t}\n\t\t})\n\t})\n}"} {"input": "package logger\n\n\n\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"strings\"\n)\n\ntype (\n\tLog struct {\n\t\tlogger *log.Logger\n\t\tpositiveList map[string]bool\n\t\tprintAll bool\n\t\tcolor string\n\t}\n)\n\n\n\n\n\nfunc (l *Log) Log(pkg string, format string, args ...interface{}) {\n\t_, print := l.positiveList[pkg]\n\tif print || l.printAll {\n\t\tl.Printf(pkg, l.color+format+Reset, args...)\n\t}\n}\n\n\nfunc (l *Log) Logger(pkg string) *log.Logger {\n\t_, print := l.positiveList[pkg]\n\tif print || l.printAll {\n\t\treturn log.New(l, Purple+pkg+\" \"+l.color, 0)\n\t}\n\n\treturn log.New(ioutil.Discard, \"\", 0)\n}\n\n\nfunc (l *Log) Printf(pkg string, format string, args ...interface{}) {\n\tl.logger.Printf(Purple+pkg+Reset+\" \"+format+\"\\n\", args...)\n}\n\n\nfunc (l *Log) Write(p []byte) (n int, err error) {\n\tstr := strings.TrimSpace(string(p))\n\n\tl.logger.Printf(\"%s\"+Reset+\"\\n\", str)\n\n\treturn len(p), nil\n}\n\nfunc New(w io.Writer, color string, packages string) *Log ", "output": "{\n\tl := &Log{\n\t\tcolor: color,\n\t\tlogger: log.New(w, \"\", log.Ldate|log.Lmicroseconds),\n\t\tpositiveList: make(map[string]bool),\n\t\tprintAll: false,\n\t}\n\n\tpositives := strings.Split(packages, \",\")\n\tfor _, positive := range positives {\n\t\tif positive == \"*\" {\n\t\t\tl.printAll = true\n\t\t} else {\n\t\t\tl.positiveList[positive] = true\n\t\t}\n\t}\n\n\treturn l\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"time\"\n)\n\n\nfunc ChannelLogger(LogDir string, UserNick string, message string) {\n STime := time.Now().Format(time.ANSIC)\n logLoc := fmt.Sprintf(\"%d-%s-%d\", time.Now().Day(), time.Now().Month(), time.Now().Year())\n\n f, err := os.OpenFile(LogDir + logLoc + \".log\", os.O_CREATE|os.O_RDWR|os.O_APPEND|os.O_SYNC, 0666)\n if err != nil {\n fmt.Println(f, err)\n }\n\n n, err := io.WriteString(f, STime + \" > \" + UserNick + message + \"\\n\")\n if err != nil {\n fmt.Println(n, err)\n }\n f.Close()\n}\n\nfunc LogDir(CreateDir string) {\n\n \n if _, err := os.Stat(CreateDir); os.IsNotExist(err) {\n fmt.Printf(\"No such file or directory: %s\", CreateDir)\n os.Mkdir(CreateDir, 0777)\n } else {\n fmt.Printf(\"Its There: %s\", CreateDir)\n }\n}\n\n\n\nfunc LogFile(CreateFile string) ", "output": "{\n \n if _, err := os.Stat(CreateFile + \".log\"); os.IsNotExist(err) {\n fmt.Printf(\"Log File \" + CreateFile + \".log Doesn't Exist.\\n\")\n os.Create(CreateFile + \".log\")\n fmt.Printf(\"Created the log file\\n\")\n } else {\n fmt.Printf(\"Log File Exists.\\n\")\n }\n}"} {"input": "package base\n\nimport (\n\t\"time\"\n\n\t\"github.com/google/cadvisor/collector\"\n\t\"github.com/google/cadvisor/info/v2\"\n)\n\ntype Collector struct {\n}\n\nvar _ collector.Collector = &Collector{}\n\nfunc (c *Collector) Collect() (time.Time, []v2.Metric, error) {\n\treturn time.Now(), []v2.Metrics{}, nil\n}\n\n\n\nfunc (c *Collector) Name() string ", "output": "{\n\treturn \"default\"\n}"} {"input": "package libclc\n\nimport (\n \"text/template\"\n \"bufio\"\n)\n\ntype Configrb struct {\n}\n\n\n\nfunc BufferConfigrb(config *Configrb, t *template.Template, w *bufio.Writer) (error) {\n return BufferTemplate(\"crb\", config, t, w)\n}\n\nfunc WriteConfigrb(config *Configrb, t *template.Template, path string) (error) ", "output": "{\n return WriteTemplate(\"crb\", config, t, path)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype dumpXLIFF struct {\n\tinFile string\n}\n\nfunc init() {\n\tregisteredConverters[\"dump\"] = new(dumpXLIFF)\n}\n\nfunc (d *dumpXLIFF) Description() string {\n\treturn \"Dumps XLIFF as parsed\"\n}\n\nfunc (d *dumpXLIFF) ParseArgs(base string, args []string) error {\n\tvar fs = flag.NewFlagSet(base+\" dump\", flag.ExitOnError)\n\tfs.StringVar(&d.inFile, \"in\", \"\", \"infile\")\n\treturn fs.Parse(args)\n}\n\n\n\nfunc (d *dumpXLIFF) Convert(w io.Writer) error {\n\n\tvar doc, err = xliffFromFile(d.inFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, file := range doc.File {\n\n\t\tfor _, unit := range file.Body.TransUnit {\n\n\t\t\tfmt.Fprintf(w, \"unit %s\\n\", unit.ID)\n\t\t\tfmt.Fprintf(w, \" source: %v\\n\", unit.Source)\n\t\t\tfmt.Fprintf(w, \" target: %v\\n\", unit.Target)\n\n\t\t}\n\t}\n\n\treturn err\n}\n\nfunc (d *dumpXLIFF) Prepare() error ", "output": "{\n\treturn nil\n}"} {"input": "package identity\n\nimport \"fmt\"\n\n\n\n\n\n\n\n\nfunc (o *Identity) Valid(debug bool) (bool, int, []string) ", "output": "{\n\tproblemsFound := 0\n\tresultDetails := make([]string, 0)\n\n\t_, pBase, dBase := o.CommonObjectProperties.ValidSDO(debug)\n\tproblemsFound += pBase\n\tresultDetails = append(resultDetails, dBase...)\n\n\n\tif o.IdentityClass == \"\" {\n\t\tproblemsFound++\n\t\tstr := fmt.Sprintf(\"-- The identity class property is required but missing\")\n\t\tresultDetails = append(resultDetails, str)\n\t} else {\n\t\tstr := fmt.Sprintf(\"++ The identity class property is required and is present\")\n\t\tresultDetails = append(resultDetails, str)\n\t}\n\n\tif problemsFound > 0 {\n\t\treturn false, problemsFound, resultDetails\n\t}\n\n\treturn true, 0, resultDetails\n}"} {"input": "package blanket_emulator\n\nimport (\n\t\"fmt\"\n)\n\ntype Event interface {\n\tHash() uint64\n\tInspect() string\n}\n\ntype ReturnEvent uint64\ntype ReadEvent uint64\ntype WriteEvent struct {\n\tAddr uint64\n\tValue uint64\n}\ntype SyscallEvent uint64\ntype InvalidInstructionEvent uint64\n\nfunc (addr ReadEvent) Hash() uint64 {\n\treturn ReadEventHash(uint64(addr))\n}\n\nfunc (s WriteEvent) Hash() uint64 {\n\treturn WriteEventHash(s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Hash() uint64 {\n\treturn SysEventHash(uint64(s))\n}\n\nfunc (s ReturnEvent) Hash() uint64 {\n\treturn ReturnEventHash(uint64(s))\n}\n\nfunc (s InvalidInstructionEvent) Hash() uint64 {\n\treturn InvalidInstructionEventHash(uint64(s))\n}\n\nfunc (addr ReadEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Read([%x])\", addr)\n}\n\nfunc (addr ReturnEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Return([%x])\", addr)\n}\n\nfunc (s WriteEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Write([%x]=%x)\", s.Addr, s.Value)\n}\n\n\n\nfunc (s InvalidInstructionEvent) Inspect() string {\n\treturn fmt.Sprintf(\"InvalidOpcode([%x])\", s)\n}\n\nfunc (s SyscallEvent) Inspect() string ", "output": "{\n\treturn fmt.Sprintf(\"Sys(%x)\", s)\n}"} {"input": "package v1\n\nimport (\n\t\"time\"\n\n\tapiv1 \"github.com/kubeflow/common/pkg/apis/common/v1\"\n\tv1 \"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\n\ttestjobv1 \"github.com/kubeflow/common/test_job/apis/test_job/v1\"\n)\n\nfunc NewTestJob(worker int) *testjobv1.TestJob {\n\ttestJob := &testjobv1.TestJob{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: testjobv1.Kind,\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: TestJobName,\n\t\t\tNamespace: metav1.NamespaceDefault,\n\t\t},\n\t\tSpec: testjobv1.TestJobSpec{\n\t\t\tTestReplicaSpecs: make(map[testjobv1.TestReplicaType]*apiv1.ReplicaSpec),\n\t\t},\n\t}\n\n\tif worker > 0 {\n\t\tworker := int32(worker)\n\t\tworkerReplicaSpec := &apiv1.ReplicaSpec{\n\t\t\tReplicas: &worker,\n\t\t\tTemplate: NewTestReplicaSpecTemplate(),\n\t\t}\n\t\ttestJob.Spec.TestReplicaSpecs[testjobv1.TestReplicaTypeWorker] = workerReplicaSpec\n\t}\n\n\treturn testJob\n}\n\n\n\nfunc SetTestJobCompletionTime(testJob *testjobv1.TestJob) {\n\tnow := metav1.Time{Time: time.Now()}\n\ttestJob.Status.CompletionTime = &now\n}\n\nfunc NewTestReplicaSpecTemplate() v1.PodTemplateSpec ", "output": "{\n\treturn v1.PodTemplateSpec{\n\t\tSpec: v1.PodSpec{\n\t\t\tContainers: []v1.Container{\n\t\t\t\tv1.Container{\n\t\t\t\t\tName: testjobv1.DefaultContainerName,\n\t\t\t\t\tImage: TestImageName,\n\t\t\t\t\tArgs: []string{\"Fake\", \"Fake\"},\n\t\t\t\t\tPorts: []v1.ContainerPort{\n\t\t\t\t\t\tv1.ContainerPort{\n\t\t\t\t\t\t\tName: testjobv1.DefaultPortName,\n\t\t\t\t\t\t\tContainerPort: testjobv1.DefaultPort,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package driver\n\nimport (\n\t\"context\"\n\n\t\"github.com/zrepl/zrepl/daemon/logging\"\n\t\"github.com/zrepl/zrepl/logger\"\n)\n\n\n\nfunc getLog(ctx context.Context) logger.Logger ", "output": "{\n\treturn logging.GetLogger(ctx, logging.SubsysReplication)\n}"} {"input": "package types\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/suite\"\n)\n\ntype TypesTestSuite struct {\n\tsuite.Suite\n}\n\nfunc (s *TypesTestSuite) SetupTest() {\n}\n\n\n\nfunc TestTypesSuite(t *testing.T) ", "output": "{\n\tsuite.Run(t, new(TypesTestSuite))\n}"} {"input": "package tracking\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n)\n\ntype trackCargoRequest struct {\n\tID string\n}\n\ntype trackCargoResponse struct {\n\tCargo *Cargo `json:\"cargo,omitempty\"`\n\tErr error `json:\"error,omitempty\"`\n}\n\n\n\nfunc makeTrackCargoEndpoint(ts Service) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\treq := request.(trackCargoRequest)\n\t\tc, err := ts.Track(req.ID)\n\t\treturn trackCargoResponse{Cargo: &c, Err: err}, nil\n\t}\n}\n\nfunc (r trackCargoResponse) error() error ", "output": "{ return r.Err }"} {"input": "package internal\n\nimport (\n\t\"encoding/json\"\n\t\"regexp\"\n)\n\ntype Pattern struct {\n\t*regexp.Regexp\n}\n\ntype CallBack func(g []string) error\n\n\n\nfunc (p *Pattern) UnmarshalJSON(text []byte) error {\n\tvar pattern string\n\tif err := json.Unmarshal(text, &pattern); err != nil {\n\t\treturn err\n\t}\n\n\tq, err := regexp.Compile(pattern)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.Regexp = q\n\treturn nil\n}\n\nfunc (p Pattern) IfMatches(s string, callback CallBack) error ", "output": "{\n\tif g := p.FindStringSubmatch(s); g != nil {\n\t\treturn callback(g)\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/mycaosf/gui\"\n\t\"github.com/mycaosf/winapi\"\n)\n\ntype aboutDialog struct {\n\tgui.BaseDialog\n}\n\n\n\nfunc (p *aboutDialog) OnOk(cmd *winapi.CMD) {\n\tp.End(winapi.IDOK)\n}\n\nfunc runAboutDialog(res *gui.Resource, parent winapi.HWND) {\n\tvar dlg aboutDialog\n\tdlg.Reg()\n\tdlg.DlgBox(res.Get(), \"AboutDlg\", parent)\n}\n\nfunc (p *aboutDialog) Reg() ", "output": "{\n\tp.BaseDialog.Reg()\n\tp.RegCmd(winapi.IDOK, p.OnOk)\n}"} {"input": "package elasticorm_test\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"testing\"\n)\n\nvar elasticSearchURL = determinElasticsearchURL()\n\nfunc determinElasticsearchURL() string {\n\tURL := os.Getenv(\"EDS_ES_URL\")\n\tif URL == `` {\n\t\tURL = `http://localhost:9200`\n\t}\n\treturn URL\n}\n\n\nfunc assert(tb testing.TB, condition bool, msg string, v ...interface{}) {\n\tif !condition {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\033[31m%s:%d: \"+msg+\"\\033[39m\\n\\n\", append([]interface{}{filepath.Base(file), line}, v...)...)\n\t\ttb.FailNow()\n\t}\n}\n\n\n\n\n\nfunc equals(tb testing.TB, exp, act interface{}) {\n\tif !reflect.DeepEqual(exp, act) {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\033[31m%s:%d:\\n\\n\\texp: %#v\\n\\n\\tgot: %#v\\033[39m\\n\\n\", filepath.Base(file), line, exp, act)\n\t\ttb.FailNow()\n\t}\n}\n\nfunc ok(tb testing.TB, err error) ", "output": "{\n\tif err != nil {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\033[31m%s:%d: unexpected error: %s\\033[39m\\n\\n\", filepath.Base(file), line, err.Error())\n\t\ttb.FailNow()\n\t}\n}"} {"input": "package group\n\nimport (\n\t\"github.com/JanBerktold/rbxweb\"\n\t\"net/url\"\n\t\"strconv\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Wall(client *rbxweb.Client, groupID int32, message string) (success bool) {\n\tpage := client.GetURL(`www`, `/My/Groups.aspx`, url.Values{\"gid\": {strconv.FormatInt(int64(groupID), 10)}})\n\terr := client.DoRawPost(page, url.Values{\n\t\t\"ctl00$ctl00$cphRoblox$cphMyRobloxContent$GroupWallPane$NewPost\": {message},\n\t\t\"ctl00$ctl00$cphRoblox$cphMyRobloxContent$GroupWallPane$NewPostButton\": {},\n\t\t\"ctl00$ctl00$cphRoblox$cphMyRobloxContent$rbxGroupRoleSetMembersPane$currentRoleSetID\": {},\n\t})\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc Shout(client *rbxweb.Client, groupID int32, message string) (success bool) ", "output": "{\n\tpage := client.GetURL(`www`, `/My/Groups.aspx`, url.Values{\"gid\": {strconv.FormatInt(int64(groupId), 10)}})\n\terr := client.DoRawPost(page, url.Values{\n\t\t\"ctl00$ctl00$cphRoblox$cphMyRobloxContent$GroupStatusPane$StatusTextBox\": {message},\n\t\t\"ctl00$ctl00$cphRoblox$cphMyRobloxContent$GroupStatusPane$StatusSubmitButton\": {},\n\t\t\"ctl00$ctl00$cphRoblox$cphMyRobloxContent$rbxGroupRoleSetMembersPane$currentRoleSetID\": {},\n\t})\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package dosingdecision\n\nimport (\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tRecommendedBasalDurationMaximum = 86400000\n\tRecommendedBasalDurationMinimum = 0\n\tRecommendedBasalRateMaximum = 100\n\tRecommendedBasalRateMinimum = 0\n)\n\ntype RecommendedBasal struct {\n\tRate *float64 `json:\"rate,omitempty\" bson:\"rate,omitempty\"`\n\tDuration *int `json:\"duration,omitempty\" bson:\"duration,omitempty\"`\n}\n\nfunc ParseRecommendedBasal(parser structure.ObjectParser) *RecommendedBasal {\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewRecommendedBasal()\n\tparser.Parse(datum)\n\treturn datum\n}\n\n\n\nfunc (r *RecommendedBasal) Parse(parser structure.ObjectParser) {\n\tr.Rate = parser.Float64(\"rate\")\n\tr.Duration = parser.Int(\"duration\")\n}\n\nfunc (r *RecommendedBasal) Validate(validator structure.Validator) {\n\tvalidator.Float64(\"rate\", r.Rate).Exists().InRange(RecommendedBasalRateMinimum, RecommendedBasalRateMaximum)\n\tvalidator.Int(\"duration\", r.Duration).InRange(RecommendedBasalDurationMinimum, RecommendedBasalDurationMaximum)\n}\n\nfunc NewRecommendedBasal() *RecommendedBasal ", "output": "{\n\treturn &RecommendedBasal{}\n}"} {"input": "package server\n\nimport (\n\t\"testing\"\n\n\t\"github.com/docker/docker/pkg/version\"\n\t\"github.com/docker/docker/runconfig\"\n)\n\n\n\nfunc TestAdjustCpuSharesNoAdjustment(t *testing.T) {\n\tapiVersion := version.Version(\"1.19\")\n\thostConfig := &runconfig.HostConfig{\n\t\tCpuShares: linuxMinCpuShares - 1,\n\t}\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != linuxMinCpuShares-1 {\n\t\tt.Errorf(\"Expected CpuShares to be %d\", linuxMinCpuShares-1)\n\t}\n\n\thostConfig.CpuShares = linuxMaxCpuShares + 1\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != linuxMaxCpuShares+1 {\n\t\tt.Errorf(\"Expected CpuShares to be %d\", linuxMaxCpuShares+1)\n\t}\n\n\thostConfig.CpuShares = 0\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != 0 {\n\t\tt.Error(\"Expected CpuShares to be unchanged\")\n\t}\n\n\thostConfig.CpuShares = 1024\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != 1024 {\n\t\tt.Error(\"Expected CpuShares to be unchanged\")\n\t}\n}\n\nfunc TestAdjustCpuSharesOldApi(t *testing.T) ", "output": "{\n\tapiVersion := version.Version(\"1.18\")\n\thostConfig := &runconfig.HostConfig{\n\t\tCpuShares: linuxMinCpuShares - 1,\n\t}\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != linuxMinCpuShares {\n\t\tt.Errorf(\"Expected CpuShares to be %d\", linuxMinCpuShares)\n\t}\n\n\thostConfig.CpuShares = linuxMaxCpuShares + 1\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != linuxMaxCpuShares {\n\t\tt.Errorf(\"Expected CpuShares to be %d\", linuxMaxCpuShares)\n\t}\n\n\thostConfig.CpuShares = 0\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != 0 {\n\t\tt.Error(\"Expected CpuShares to be unchanged\")\n\t}\n\n\thostConfig.CpuShares = 1024\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != 1024 {\n\t\tt.Error(\"Expected CpuShares to be unchanged\")\n\t}\n}"} {"input": "package event\n\nimport (\n\t\"fmt\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\n\ntype Increment struct {\n\tName string\n\tValue int64\n}\n\nfunc (e *Increment) StatClass() string {\n\treturn \"counter\"\n}\n\n\nfunc (e *Increment) Update(e2 Event) error {\n\tif e.Type() != e2.Type() {\n\t\treturn fmt.Errorf(\"statsd event type conflict: %s vs %s \", e.String(), e2.String())\n\t}\n\tatomic.AddInt64(&e.Value, e2.Payload().(int64))\n\treturn nil\n}\n\n\nfunc (e *Increment) Reset() {\n\te.Value = 0\n}\n\n\nfunc (e Increment) Payload() interface{} {\n\treturn e.Value\n}\n\n\nfunc (e Increment) Stats(tick time.Duration) []string {\n\treturn []string{fmt.Sprintf(\"%s:%d|c\", e.Name, e.Value)}\n}\n\n\nfunc (e Increment) Key() string {\n\treturn e.Name\n}\n\n\nfunc (e *Increment) SetKey(key string) {\n\te.Name = key\n}\n\n\n\n\n\nfunc (e Increment) TypeString() string {\n\treturn \"Increment\"\n}\n\n\nfunc (e Increment) String() string {\n\treturn fmt.Sprintf(\"{Type: %s, Key: %s, Value: %d}\", e.TypeString(), e.Name, e.Value)\n}\n\nfunc (e Increment) Type() int ", "output": "{\n\treturn EventIncr\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n)\n\n\nconst DeleteDeploymentOKCode int = 200\n\n\ntype DeleteDeploymentOK struct {\n}\n\n\nfunc NewDeleteDeploymentOK() *DeleteDeploymentOK {\n\treturn &DeleteDeploymentOK{}\n}\n\n\nfunc (o *DeleteDeploymentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n}\n\n\nconst DeleteDeploymentUnauthorizedCode int = 401\n\n\ntype DeleteDeploymentUnauthorized struct {\n\tWWWAuthenticate string `json:\"WWW_Authenticate\"`\n}\n\n\n\n\n\nfunc (o *DeleteDeploymentUnauthorized) WithWWWAuthenticate(wWWAuthenticate string) *DeleteDeploymentUnauthorized {\n\to.WWWAuthenticate = wWWAuthenticate\n\treturn o\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) SetWWWAuthenticate(wWWAuthenticate string) {\n\to.WWWAuthenticate = wWWAuthenticate\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\n\twWWAuthenticate := o.WWWAuthenticate\n\tif wWWAuthenticate != \"\" {\n\t\trw.Header().Set(\"WWW_Authenticate\", wWWAuthenticate)\n\t}\n\n\trw.WriteHeader(401)\n}\n\n\nconst DeleteDeploymentNotFoundCode int = 404\n\n\ntype DeleteDeploymentNotFound struct {\n}\n\n\nfunc NewDeleteDeploymentNotFound() *DeleteDeploymentNotFound {\n\treturn &DeleteDeploymentNotFound{}\n}\n\n\nfunc (o *DeleteDeploymentNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(404)\n}\n\n\nconst DeleteDeploymentInternalServerErrorCode int = 500\n\n\ntype DeleteDeploymentInternalServerError struct {\n}\n\n\nfunc NewDeleteDeploymentInternalServerError() *DeleteDeploymentInternalServerError {\n\treturn &DeleteDeploymentInternalServerError{}\n}\n\n\nfunc (o *DeleteDeploymentInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(500)\n}\n\nfunc NewDeleteDeploymentUnauthorized() *DeleteDeploymentUnauthorized ", "output": "{\n\treturn &DeleteDeploymentUnauthorized{}\n}"} {"input": "package rpc\n\nimport (\n\t\"io\"\n\t\"net/http\"\n)\n\n\n\ntype Encoder interface {\n\tEncode(w http.ResponseWriter) io.Writer\n}\n\ntype encoder struct {\n}\n\n\n\nvar DefaultEncoder = &encoder{}\n\n\n\n\n\ntype EncoderSelector interface {\n\tSelect(r *http.Request) Encoder\n}\n\ntype encoderSelector struct {\n}\n\nfunc (_ *encoderSelector) Select(_ *http.Request) Encoder {\n\treturn DefaultEncoder\n}\n\nvar DefaultEncoderSelector = &encoderSelector{}\n\nfunc (_ *encoder) Encode(w http.ResponseWriter) io.Writer ", "output": "{\n\treturn w\n}"} {"input": "package apigateway\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype ExecutionLogPolicy struct {\n\n\tIsEnabled *bool `mandatory:\"false\" json:\"isEnabled\"`\n\n\tLogLevel ExecutionLogPolicyLogLevelEnum `mandatory:\"false\" json:\"logLevel,omitempty\"`\n}\n\n\n\n\ntype ExecutionLogPolicyLogLevelEnum string\n\n\nconst (\n\tExecutionLogPolicyLogLevelInfo ExecutionLogPolicyLogLevelEnum = \"INFO\"\n\tExecutionLogPolicyLogLevelWarn ExecutionLogPolicyLogLevelEnum = \"WARN\"\n\tExecutionLogPolicyLogLevelError ExecutionLogPolicyLogLevelEnum = \"ERROR\"\n)\n\nvar mappingExecutionLogPolicyLogLevel = map[string]ExecutionLogPolicyLogLevelEnum{\n\t\"INFO\": ExecutionLogPolicyLogLevelInfo,\n\t\"WARN\": ExecutionLogPolicyLogLevelWarn,\n\t\"ERROR\": ExecutionLogPolicyLogLevelError,\n}\n\n\nfunc GetExecutionLogPolicyLogLevelEnumValues() []ExecutionLogPolicyLogLevelEnum {\n\tvalues := make([]ExecutionLogPolicyLogLevelEnum, 0)\n\tfor _, v := range mappingExecutionLogPolicyLogLevel {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}\n\nfunc (m ExecutionLogPolicy) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package vdlog\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestLog(t *testing.T) ", "output": "{\n\tSetConsoleVerbosity(LevelSilly)\n\n\tEmitSilly(\"testFacility\", H{\"testing\": \"test\"})\n\tEmitVerbose(\"testFacility\", H{\"testing\": \"test\"})\n\tEmitDebug(\"testFacility\", H{\"testing\": \"test\"})\n\tEmitInfo(\"testFacility\", H{\"testing\": \"test\"})\n\tEmitWarn(\"testFacility\", H{\"testing\": \"test\"})\n\tEmitError(\"testFacility\", fmt.Errorf(\"some test %s\", \"error\"), H{\"testing\": \"test\"})\n\n\ttime.Sleep(100 * time.Millisecond)\n}"} {"input": "package memconn\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"sync\"\n)\n\ntype memconn struct {\n\tsync.Once\n\taddr addr\n\tbsiz uint64\n\tchcn chan net.Conn\n\tdone func()\n\tpool *sync.Pool\n}\n\nfunc (m *memconn) Dial() (net.Conn, error) {\n\tr, w := pipe(&m.addr, m.pool)\n\tgo func() {\n\t\tm.chcn <- r\n\t}()\n\treturn w, nil\n}\n\n\n\nfunc (m *memconn) Close() error {\n\tm.Do(func() {\n\t\tclose(m.chcn)\n\t\tm.done()\n\t})\n\treturn http.ErrServerClosed\n}\n\nfunc (m *memconn) Addr() net.Addr {\n\treturn m.addr\n}\n\nfunc (m *memconn) Accept() (net.Conn, error) ", "output": "{\n\tfor c := range m.chcn {\n\t\treturn c, nil\n\t}\n\treturn nil, http.ErrServerClosed\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\t\"testing\"\n)\n\n\n\nfunc TestContextRespond(t *testing.T) {\n\ttestPairs := []struct {\n\t\tstatus int\n\t\thandle ActionHandler\n\t}{\n\t\t{http.StatusOK, func(c *Context) { c.RespondOK(\"\") }},\n\t\t{http.StatusInternalServerError, func(c *Context) { c.RespondErrf(http.StatusInternalServerError, \"erro\") }},\n\t\t{1001, func(c *Context) { c.Respond(1001, \"\") }},\n\t}\n\n\tfor _, pair := range testPairs {\n\t\tw := new(mockResponseWriter)\n\t\tpair.handle(&Context{ResponseWriter: w})\n\n\t\tif w.status != pair.status {\n\t\t\tt.Errorf(\"Routing failed for %v get %v\", pair, w.status)\n\t\t}\n\t}\n}\n\nfunc TestContextSetVar(t *testing.T) ", "output": "{\n\tvar resource = NewApiResource(\"test\", \"test\")\n\tresource.SetVar(\"a\", \"123\")\n\tvar c = &Context{Resource: resource}\n\tif c.GetVar(\"a\") != \"123\" {\n\t\tt.Errorf(\"Context set var failed! Expect %s, got %s\", c.GetVar(\"a\"), \"123\")\n\t}\n}"} {"input": "package spanner\n\n\n\n\n\n\n\n\nfunc (c *Client) SetGoogleClientInfo(keyval ...string) ", "output": "{\n\tc.setGoogleClientInfo(keyval...)\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aws/aws-sdk-go/private/protocol\"\n)\n\ntype examplesBuilder interface {\n\tBuildShape(*ShapeRef, map[string]interface{}, bool) string\n\tBuildList(string, string, *ShapeRef, []interface{}) string\n\tBuildComplex(string, string, *ShapeRef, *Shape, map[string]interface{}) string\n\tGoType(*ShapeRef, bool) string\n\tImports(*API) string\n}\n\ntype defaultExamplesBuilder struct {\n\tShapeValueBuilder\n}\n\n\n\nfunc NewExamplesBuilder() defaultExamplesBuilder {\n\tb := defaultExamplesBuilder{\n\t\tShapeValueBuilder: NewShapeValueBuilder(),\n\t}\n\tb.ParseTimeString = parseExampleTimeString\n\treturn b\n}\n\nfunc (builder defaultExamplesBuilder) Imports(a *API) string {\n\treturn `\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"` + SDKImportRoot + `/aws\"\n\t\"` + SDKImportRoot + `/aws/awserr\"\n\t\"` + SDKImportRoot + `/aws/session\"\n\t\"` + a.ImportPath() + `\"\n\t`\n}\n\n\n\n\n\nfunc parseExampleTimeString(ref *ShapeRef, memName, v string) string ", "output": "{\n\tif ref.Location == \"header\" {\n\t\treturn fmt.Sprintf(\"%s: parseTime(%q, %q),\\n\", memName, protocol.RFC822TimeFormat, v)\n\t}\n\n\tswitch ref.API.Metadata.Protocol {\n\tcase \"json\", \"rest-json\", \"rest-xml\", \"ec2\", \"query\":\n\t\treturn fmt.Sprintf(\"%s: parseTime(%q, %q),\\n\", memName, protocol.ISO8601TimeFormat, v)\n\tdefault:\n\t\tpanic(\"Unsupported time type: \" + ref.API.Metadata.Protocol)\n\t}\n}"} {"input": "package gotermhook\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\n\n\nfunc addTerminatingSignals(c chan<- os.Signal) ", "output": "{\n\tsignal.Notify(c, os.Interrupt)\n\tsignal.Notify(c, syscall.SIGTERM)\n}"} {"input": "package db\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/suite\"\n)\n\ntype StateTestSuite struct {\n\tsuite.Suite\n}\n\n\n\nfunc (s *StateTestSuite) TestElapsedTime() {\n\tt := new(Task)\n\ts.Equal(t.ElapsedTime(), time.Duration(0))\n\n\tt.Start()\n\ts.True(t.ElapsedTime() > time.Duration(0))\n\n\tt.End()\n\ts.Equal(t.ElapsedTime(), t.EndTime.Sub(*t.StartTime))\n}\n\nfunc TestStateTestSuite(t *testing.T) ", "output": "{\n\tsuite.Run(t, new(StateTestSuite))\n}"} {"input": "package securetemp\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nconst (\n\tsize = DefaultSize\n)\n\nfunc TestTempDir(t *testing.T) {\n\ttmpDir, cleanupFunc, err := TempDir(size)\n\tif err != nil {\n\t\tt.Fatal(\"failed to create temp dir\", err)\n\t}\n\tif _, err := os.Stat(tmpDir); err != nil {\n\t\tt.Fatal(\"something is wrong with the temp dir\", err)\n\t}\n\n\tcleanupFunc()\n\tif _, err := os.Stat(tmpDir); err == nil {\n\t\tt.Fatal(\"temp dir should no longer exist after cleanup, but does\", tmpDir)\n\t}\n}\n\n\n\nfunc TestTempFile(t *testing.T) ", "output": "{\n\ttmpFile, cleanupFunc, err := TempDir(size)\n\tif err != nil {\n\t\tt.Fatal(\"failed to create temp file\", err)\n\t}\n\tif _, err := os.Stat(tmpFile); err != nil {\n\t\tt.Fatal(\"something is wrong with the temp file\", err)\n\t}\n\n\tcleanupFunc()\n\tif _, err := os.Stat(tmpFile); err == nil {\n\t\tt.Fatal(\"temp dir should no longer exist after cleanup, but does\", tmpFile)\n\t}\n}"} {"input": "package daemon\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime/middleware\"\n)\n\n\ntype GetHealthzHandlerFunc func(GetHealthzParams) middleware.Responder\n\n\nfunc (fn GetHealthzHandlerFunc) Handle(params GetHealthzParams) middleware.Responder {\n\treturn fn(params)\n}\n\n\ntype GetHealthzHandler interface {\n\tHandle(GetHealthzParams) middleware.Responder\n}\n\n\n\n\n\ntype GetHealthz struct {\n\tContext *middleware.Context\n\tHandler GetHealthzHandler\n}\n\nfunc (o *GetHealthz) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\tr = rCtx\n\t}\n\tvar Params = NewGetHealthzParams()\n\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params) \n\n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}\n\nfunc NewGetHealthz(ctx *middleware.Context, handler GetHealthzHandler) *GetHealthz ", "output": "{\n\treturn &GetHealthz{Context: ctx, Handler: handler}\n}"} {"input": "package metcdv3\n\nimport \"github.com/lytics/metafora\"\n\ntype task struct {\n\tid string\n}\n\nfunc (t *task) ID() string { return t.id }\n\n\n\n\n\n\n\ntype TaskFunc func(id, value string) metafora.Task\n\n\n\n\n\nfunc DefaultTaskFunc(id, _ string) metafora.Task ", "output": "{ return &task{id: id} }"} {"input": "package logstash\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\nfunc copyAllFiles(sourceDirs []string, sourceFiles []string, dest string) (string, error) {\n\tfor _, sourceDir := range sourceDirs {\n\t\tif !allFilesExist(sourceDir, sourceFiles) {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, sourceFile := range sourceFiles {\n\t\t\tsrcFile := filepath.Join(sourceDir, sourceFile)\n\t\t\tdestFile := filepath.Join(dest, sourceFile)\n\t\t\tif err := copyFile(srcFile, destFile); err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t\treturn sourceDir, nil\n\t}\n\treturn \"\", fmt.Errorf(\"couldn't find the wanted files (%s) in any of these directories: %s\",\n\t\tstrings.Join(sourceFiles, \", \"), strings.Join(sourceDirs, \", \"))\n}\n\n\n\n\n\nfunc copyFile(sourcePath, destPath string) error {\n\tr, err := os.Open(sourcePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\tw, err := os.Create(destPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn w.Close()\n}\n\nfunc allFilesExist(dir string, filenames []string) bool ", "output": "{\n\tfor _, filename := range filenames {\n\t\tpath := filepath.Join(dir, filename)\n\t\tif _, err := os.Stat(path); err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package sqltrace\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\nfunc boolToInt64(f bool) int64 {\n\tif f {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\ntype sqlTrace struct {\n\ton int64 \n\n\t*log.Logger\n}\n\nfunc newSQLTrace() *sqlTrace {\n\treturn &sqlTrace{\n\t\tLogger: log.New(os.Stdout, \"hdb \", log.Ldate|log.Ltime|log.Lshortfile),\n\t}\n}\nfunc (t *sqlTrace) On() bool { return atomic.LoadInt64(&t.on) != 0 }\nfunc (t *sqlTrace) SetOn(on bool) { atomic.StoreInt64(&t.on, boolToInt64(on)) }\n\ntype flagValue struct {\n\tt *sqlTrace\n}\n\nfunc (v flagValue) IsBoolFlag() bool { return true }\n\nfunc (v flagValue) String() string {\n\tif v.t == nil {\n\t\treturn \"\"\n\t}\n\treturn strconv.FormatBool(v.t.On())\n}\n\n\n\nvar tracer = newSQLTrace()\n\nfunc init() {\n\tflag.Var(&flagValue{t: tracer}, \"hdb.sqlTrace\", \"enabling hdb sql trace\")\n}\n\n\nfunc On() bool { return tracer.On() }\n\n\nfunc SetOn(on bool) { tracer.SetOn(on) }\n\n\nfunc Trace(v ...interface{}) { tracer.Print(v...) }\n\n\nfunc Tracef(format string, v ...interface{}) { tracer.Printf(format, v...) }\n\n\nfunc Traceln(v ...interface{}) { tracer.Println(v...) }\n\nfunc (v flagValue) Set(s string) error ", "output": "{\n\tf, err := strconv.ParseBool(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.t.SetOn(f)\n\treturn nil\n}"} {"input": "package httpgrpc\n\nimport (\n\t\"fmt\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/golang/protobuf/ptypes\"\n\t\"github.com/golang/protobuf/ptypes/any\"\n\tspb \"google.golang.org/genproto/googleapis/rpc/status\"\n\t\"google.golang.org/grpc/status\"\n)\n\n\n\n\n\n\n\nfunc ErrorFromHTTPResponse(resp *HTTPResponse) error {\n\ta, err := ptypes.MarshalAny(resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn status.ErrorProto(&spb.Status{\n\t\tCode: resp.Code,\n\t\tMessage: string(resp.Body),\n\t\tDetails: []*any.Any{a},\n\t})\n}\n\n\nfunc HTTPResponseFromError(err error) (*HTTPResponse, bool) {\n\ts, ok := status.FromError(err)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tstatus := s.Proto()\n\tif len(status.Details) != 1 {\n\t\treturn nil, false\n\t}\n\n\tvar resp HTTPResponse\n\tif err := ptypes.UnmarshalAny(status.Details[0], &resp); err != nil {\n\t\tlog.Errorf(\"Got error containing non-response: %v\", err)\n\t\treturn nil, false\n\t}\n\n\treturn &resp, true\n}\n\nfunc Errorf(code int, tmpl string, args ...interface{}) error ", "output": "{\n\treturn ErrorFromHTTPResponse(&HTTPResponse{\n\t\tCode: int32(code),\n\t\tBody: []byte(fmt.Sprintf(tmpl, args...)),\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\ntype MockConn struct {\n\tServerReader *io.PipeReader\n\tServerWriter *io.PipeWriter\n\tClientReader *io.PipeReader\n\tClientWriter *io.PipeWriter\n}\n\nfunc (c MockConn) Close() error {\n\tif err := c.ServerWriter.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := c.ServerReader.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c MockConn) CloseClient() error {\n\tif err := c.ClientWriter.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := c.ClientReader.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c MockConn) Read(data []byte) (n int, err error) { return c.ServerReader.Read(data) }\nfunc (c MockConn) Write(data []byte) (n int, err error) { return c.ServerWriter.Write(data) }\n\nfunc (c MockConn) LocalAddr() net.Addr {\n\treturn &net.TCPAddr{\n\t\tIP: net.ParseIP(\"127.0.0.1:2342\"),\n\t\tPort: 2342,\n\t\tZone: \"\",\n\t}\n}\n\nfunc (c MockConn) RemoteAddr() net.Addr {\n\treturn &net.TCPAddr{\n\t\tIP: net.ParseIP(\"127.0.0.1:2342\"),\n\t\tPort: 2342,\n\t\tZone: \"\",\n\t}\n}\n\nfunc (c MockConn) SetDeadline(t time.Time) error { return nil }\nfunc (c MockConn) SetReadDeadline(t time.Time) error { return nil }\nfunc (c MockConn) SetWriteDeadline(t time.Time) error { return nil }\n\n\n\nfunc NewMockConn() MockConn ", "output": "{\n\tserverRead, clientWrite := io.Pipe()\n\tclientRead, serverWrite := io.Pipe()\n\n\treturn MockConn{\n\t\tServerReader: serverRead,\n\t\tServerWriter: serverWrite,\n\t\tClientReader: clientRead,\n\t\tClientWriter: clientWrite,\n\t}\n}"} {"input": "package types\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\nfunc HstoreScanner(typ reflect.Type) ScannerFunc {\n\tif typ.Key() == stringType && typ.Elem() == stringType {\n\t\treturn scanMapStringStringValue\n\t}\n\treturn func(v reflect.Value, rd Reader, n int) error {\n\t\treturn fmt.Errorf(\"pg.Hstore(unsupported %s)\", v.Type())\n\t}\n}\n\n\n\nfunc scanMapStringString(rd Reader, n int) (map[string]string, error) {\n\tif n == -1 {\n\t\treturn nil, nil\n\t}\n\n\tp := newHstoreParser(rd)\n\tm := make(map[string]string)\n\tfor {\n\t\tkey, err := p.NextKey()\n\t\tif err != nil {\n\t\t\tif err == errEndOfHstore {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalue, err := p.NextValue()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tm[string(key)] = string(value)\n\t}\n\treturn m, nil\n}\n\nfunc scanMapStringStringValue(v reflect.Value, rd Reader, n int) error ", "output": "{\n\tm, err := scanMapStringString(rd, n)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tv.Set(reflect.ValueOf(m))\n\treturn nil\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\tloggo \"github.com/juju/loggo\"\n)\n\ntype (\n\tCustomFormatter struct{}\n)\n\nfunc InitLog(path string) {\n\tif path == \"\" {\n\t\tpath = \"./util/conf.json\"\n\t}\n\tconfiguration, err := GetConfig(path)\n\tif err != nil {\n\t\tfmt.Println(\"Error reading config\")\n\t\treturn\n\t}\n\tconfig := SerializeConfig(configuration.Logging)\n\tloggo.ConfigureLoggers(config)\n}\n\n\n\nfunc (formatter *CustomFormatter) Format(level loggo.Level, module, filename string, line int, timestamp time.Time, message string) string {\n\treturn fmt.Sprintf(\"%s\", message)\n}\n\nfunc ReplaceLoggerDefaultFormatter() {\n\twriter := loggo.NewSimpleWriter(os.Stderr, &CustomFormatter{})\n\tloggo.ReplaceDefaultWriter(writer)\n}\n\nfunc GetLogger(module string) loggo.Logger ", "output": "{\n\tlog := loggo.GetLogger(module)\n\treturn log\n}"} {"input": "package tests\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"github.com/google/go-github/github\"\n\t\"golang.org/x/oauth2\"\n)\n\nvar (\n\tclient *github.Client\n\n\tauth bool\n)\n\n\n\nfunc checkAuth(name string) bool {\n\tif !auth {\n\t\tfmt.Printf(\"No auth - skipping portions of %v\\n\", name)\n\t}\n\treturn auth\n}\n\nfunc createRandomTestRepository(owner string, autoinit bool) (*github.Repository, error) {\n\tvar repoName string\n\tfor {\n\t\trepoName = fmt.Sprintf(\"test-%d\", rand.Int())\n\t\t_, resp, err := client.Repositories.Get(owner, repoName)\n\t\tif err != nil {\n\t\t\tif resp.StatusCode == http.StatusNotFound {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\trepo, _, err := client.Repositories.Create(\"\", &github.Repository{Name: github.String(repoName), AutoInit: github.Bool(autoinit)})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn repo, nil\n}\n\nfunc init() ", "output": "{\n\ttoken := os.Getenv(\"GITHUB_AUTH_TOKEN\")\n\tif token == \"\" {\n\t\tprint(\"!!! No OAuth token. Some tests won't run. !!!\\n\\n\")\n\t\tclient = github.NewClient(nil)\n\t} else {\n\t\ttc := oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(\n\t\t\t&oauth2.Token{AccessToken: token},\n\t\t))\n\t\tclient = github.NewClient(tc)\n\t\tauth = true\n\t}\n\n\tvars := []string{envKeyGitHubUsername, envKeyGitHubPassword, envKeyClientID, envKeyClientSecret}\n\n\tfor _, v := range vars {\n\t\tvalue := os.Getenv(v)\n\t\tif value == \"\" {\n\t\t\tprint(\"!!! \" + fmt.Sprintf(msgEnvMissing, v) + \" !!!\\n\\n\")\n\t\t}\n\t}\n\n}"} {"input": "package model\n\ntype Interface interface {\n\tVisitString(name string, resume func())\n\tVisitInt(name string, resume func())\n\tVisitFloat(name string, resume func())\n\tVisitBool(name string, resume func())\n\tVisitPtr(name string, resume func())\n\tVisitBytes(name string, resume func())\n\tVisitSlice(name string, resume func())\n\tVisitStruct(name string, fields []Field, resume func())\n\tVisitStructField(field Field, resume func())\n\tVisitMap(name string, resume func())\n\tVisitCustom(name string, resume func())\n\tVisitReference(name string, resume func())\n}\n\ntype Visitor struct{}\n\nfunc (self *Visitor) VisitString(name string, resume func()) {\n\tresume()\n}\n\n\n\nfunc (self *Visitor) VisitFloat(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBool(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitPtr(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBytes(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitSlice(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStructField(field Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitMap(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitCustom(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitReference(name string, resume func()) {\n\tresume()\n}\n\ntype EmbeddedStructVisitor struct {\n\tInterface\n}\n\nfunc (self *EmbeddedStructVisitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitInt(name string, resume func()) ", "output": "{\n\tresume()\n}"} {"input": "package godspeed\n\nimport (\n\t\"io\"\n\t\"net/http\"\n)\n\ntype bodyWrapperFactory func(http.ResponseWriter) io.Writer\n\ntype bodyWrapper struct {\n\trespw http.ResponseWriter\n\tw io.Writer\n\tposthandler bodyWrapperFactory\n}\n\n\n\nfunc (w *bodyWrapper) Write(data []byte) (int, error) {\n\tif w.w == nil {\n\t\tw.w = w.posthandler(w.respw)\n\t}\n\treturn w.w.Write(data)\n}\n\nfunc (w *bodyWrapper) WriteHeader(s int) {\n\tw.respw.WriteHeader(s)\n}\n\nfunc (w *bodyWrapper) Close() error {\n\tvar err error\n\tif c, ok := w.w.(io.Closer); ok {\n\t\terr = c.Close()\n\t}\n\treturn err\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc wrapBody(respw http.ResponseWriter, writerGen bodyWrapperFactory) *bodyWrapper {\n\treturn &bodyWrapper{\n\t\trespw: respw,\n\t\tposthandler: writerGen,\n\t}\n}\n\nfunc (w *bodyWrapper) Header() http.Header ", "output": "{\n\treturn w.respw.Header()\n}"} {"input": "package utils\n\nimport (\n\t\"net\"\n\t\"fmt\"\n\t\"strings\"\n\t\"errors\"\n)\n\ntype Local int\n\nfunc (this *Local) GetMac() {\n\tinterfaces,err := net.Interfaces()\n\tCheckError(err)\n\tfor _,inter :=range interfaces {\n\t\tmac := inter.HardwareAddr\n\t\tname := inter.Name\n\t\tfmt.Printf(\"MAC=%s NAME=%s \\n\",mac,name)\n\t}\n}\n\n\n\nfunc (this *Local) GiveOneIp() (string,error) {\n\trs := this.GetIps()\n\tfor _,data := range rs {\n\t\tif strings.Contains(data,\"24\") {\n\t\t\treturn strings.Split(data,\"/\")[0],nil\n\t\t}\n\t}\n\treturn \"\",errors.New(\"没有255.255.255.0网段的IP设置\")\n}\n\nfunc (this *Local) GetIps() []string ", "output": "{\n\tresult := []string{}\n\tinterfaces,err := net.Interfaces()\n\tCheckError(err)\n\tfor _,inter :=range interfaces {\n\t\tip,err := inter.Addrs()\n\t\tCheckError(err)\n\t\tfor _,x := range ip {\n\t\t\tresult = append(result,x.String())\n\t\t}\n\t}\n\treturn result\n}"} {"input": "package internal\n\nimport (\n\t\"os\"\n)\n\n\n\n\nfunc MyUserAndGroup() (int, int) ", "output": "{\n\treturn os.Getuid(), os.Getgid()\n}"} {"input": "package widgets\n\nimport (\n\t\"strings\"\n\n\t\"github.com/ambientsound/pms/songlist\"\n\t\"github.com/ambientsound/pms/style\"\n\t\"github.com/gdamore/tcell\"\n\t\"github.com/gdamore/tcell/views\"\n)\n\ntype ColumnheadersWidget struct {\n\tcolumns songlist.Columns\n\tview views.View\n\n\tstyle.Styled\n\tviews.WidgetWatchers\n}\n\nfunc NewColumnheadersWidget() (c *ColumnheadersWidget) {\n\tc = &ColumnheadersWidget{}\n\tc.columns = make(songlist.Columns, 0)\n\treturn\n}\n\nfunc (c *ColumnheadersWidget) SetColumns(cols songlist.Columns) {\n\tc.columns = cols\n}\n\nfunc (c *ColumnheadersWidget) Draw() {\n\tx := 0\n\ty := 0\n\tfor i := range c.columns {\n\t\tcol := c.columns[i]\n\t\ttitle := []rune(strings.Title(col.Tag()))\n\t\tp := 0\n\t\tfor _, r := range title {\n\t\t\tc.view.SetContent(x+p, y, r, nil, c.Style(\"header\"))\n\t\t\tp++\n\t\t}\n\t\tx += col.Width()\n\t}\n}\n\nfunc (c *ColumnheadersWidget) SetView(v views.View) {\n\tc.view = v\n}\n\n\n\nfunc (w *ColumnheadersWidget) Resize() {\n}\n\nfunc (w *ColumnheadersWidget) HandleEvent(ev tcell.Event) bool {\n\treturn false\n}\n\nfunc (c *ColumnheadersWidget) Size() (int, int) ", "output": "{\n\tx, y := c.view.Size()\n\ty = 1\n\treturn x, y\n}"} {"input": "package models\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"time\"\n)\n\n\ntype Config struct {\n\tJWT string `json:\"jwt_token\"`\n}\n\n\nfunc (c *Config) FindByKey(key string) (value string, err error) {\n\tval, err := N.Request(\"config.get.jwt_token\", []byte(\"\"), 1*time.Second)\n\tif err == nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(val.Data), err\n}\n\n\nfunc (c *Config) GetJWTToken() (token string, err error) {\n\ttoken = os.Getenv(\"JWT_SECRET\")\n\tif token == \"\" {\n\t\ttoken, err = c.FindByKey(\"jwt_token\")\n\t\tif err != nil {\n\t\t\treturn \"\", errors.New(\"Can't get jwt_config config\")\n\t\t}\n\t}\n\n\treturn token, nil\n}\n\n\nfunc (c *Config) GetNatsURI() string {\n\treturn os.Getenv(\"NATS_URI\")\n}\n\n\n\n\nfunc (c *Config) GetServerPort() (token string) ", "output": "{\n\treturn \"8080\"\n}"} {"input": "package logrus\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"runtime\"\n)\n\n\n\n\n\n\n\n\n\nfunc (logger *Logger) WriterLevel(level Level) *io.PipeWriter {\n\treturn NewEntry(logger).WriterLevel(level)\n}\n\nfunc (entry *Entry) Writer() *io.PipeWriter {\n\treturn entry.WriterLevel(InfoLevel)\n}\n\nfunc (entry *Entry) WriterLevel(level Level) *io.PipeWriter {\n\treader, writer := io.Pipe()\n\n\tvar printFunc func(args ...interface{})\n\n\tswitch level {\n\tcase TraceLevel:\n\t\tprintFunc = entry.Trace\n\tcase DebugLevel:\n\t\tprintFunc = entry.Debug\n\tcase InfoLevel:\n\t\tprintFunc = entry.Info\n\tcase WarnLevel:\n\t\tprintFunc = entry.Warn\n\tcase ErrorLevel:\n\t\tprintFunc = entry.Error\n\tcase FatalLevel:\n\t\tprintFunc = entry.Fatal\n\tcase PanicLevel:\n\t\tprintFunc = entry.Panic\n\tdefault:\n\t\tprintFunc = entry.Print\n\t}\n\n\tgo entry.writerScanner(reader, printFunc)\n\truntime.SetFinalizer(writer, writerFinalizer)\n\n\treturn writer\n}\n\nfunc (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {\n\tscanner := bufio.NewScanner(reader)\n\tfor scanner.Scan() {\n\t\tprintFunc(scanner.Text())\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tentry.Errorf(\"Error while reading from Writer: %s\", err)\n\t}\n\treader.Close()\n}\n\nfunc writerFinalizer(writer *io.PipeWriter) {\n\twriter.Close()\n}\n\nfunc (logger *Logger) Writer() *io.PipeWriter ", "output": "{\n\treturn logger.WriterLevel(InfoLevel)\n}"} {"input": "package tournaments\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\n\t\"appengine\"\n\n\t\"github.com/taironas/gonawin/extract\"\n\t\"github.com/taironas/gonawin/helpers\"\n\ttemplateshlp \"github.com/taironas/gonawin/helpers/templates\"\n\n\tmdl \"github.com/taironas/gonawin/models\"\n)\n\n\n\ntype GroupJSON struct {\n\tName string\n\tTeams []TeamJSON\n}\n\n\n\ntype TeamJSON struct {\n\tName string\n\tPoints int64\n\tGoalsF int64\n\tGoalsA int64\n\tIso string\n}\n\n\n\n\n\n\n\nfunc formatGroupsJSON(groups []*mdl.Tgroup) []GroupJSON {\n\n\tgroupsJSON := make([]GroupJSON, len(groups))\n\tfor i, g := range groups {\n\t\tgroupsJSON[i].Name = g.Name\n\t\tteams := make([]TeamJSON, len(g.Teams))\n\t\tfor j, t := range g.Teams {\n\t\t\tteams[j].Name = t.Name\n\t\t\tteams[j].Points = g.Points[j]\n\t\t\tteams[j].GoalsF = g.GoalsF[j]\n\t\t\tteams[j].GoalsA = g.GoalsA[j]\n\t\t\tteams[j].Iso = t.Iso\n\t\t}\n\t\tgroupsJSON[i].Teams = teams\n\t}\n\treturn groupsJSON\n}\n\nfunc Groups(w http.ResponseWriter, r *http.Request, u *mdl.User) error ", "output": "{\n\tif r.Method != \"GET\" {\n\t\treturn &helpers.BadRequest{Err: errors.New(helpers.ErrorCodeNotSupported)}\n\t}\n\n\tc := appengine.NewContext(r)\n\tdesc := \"Tournament Group Handler:\"\n\textract := extract.NewContext(c, desc, r)\n\n\tvar err error\n\tvar tournament *mdl.Tournament\n\tif tournament, err = extract.Tournament(); err != nil {\n\t\treturn err\n\t}\n\n\tgroups := mdl.Groups(c, tournament.GroupIds)\n\tgroupsJSON := formatGroupsJSON(groups)\n\n\tdata := struct {\n\t\tGroups []GroupJSON\n\t}{\n\t\tgroupsJSON,\n\t}\n\n\treturn templateshlp.RenderJSON(w, c, data)\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n\n\t\"github.com/Huawei/containerops/common\"\n)\n\nvar cfgFile string\nvar verbose, timestamp bool\n\n\nvar RootCmd = &cobra.Command{\n\tUse: \"singular\",\n\tShort: \"Singular is deploy and operation tools for ContainerOps platform.\",\n\tLong: `Singular design for deploy and operation ContainerOps platform,\nmostly focus on Kubernetes, Prometheus, others in the Cloud Native technology stack.\nWe are trying to deploy stack cross cloud, OpenStack, bare metals. `,\n}\n\n\nfunc init() {\n\tcobra.OnInitialize(initConfig)\n\n\tRootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"Configuration file path\")\n\tRootCmd.PersistentFlags().BoolVar(&verbose, \"verbose\", false, \"When verbose is true, the engine will print all logs.\")\n\tRootCmd.PersistentFlags().BoolVar(×tamp, \"timestamp\", false, \"Show logs with timestamp. \")\n\n\tviper.BindPFlag(\"config\", RootCmd.Flags().Lookup(\"config\"))\n\tviper.BindPFlag(\"verbose\", RootCmd.Flags().Lookup(\"verbose\"))\n\tviper.BindPFlag(\"timestamp\", RootCmd.Flags().Lookup(\"timestamp\"))\n}\n\n\n\n\nfunc initConfig() ", "output": "{\n\tif err := common.SetConfig(cfgFile); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/gorilla/mux\"\n)\n\nconst (\n\tprometheusMetricsPath = \"/prometheus/metrics\"\n)\n\n\n\n\nfunc registerMetricsRouter(router *mux.Router) ", "output": "{\n\tmetricsRouter := router.NewRoute().PathPrefix(minioReservedBucketPath).Subrouter()\n\tmetricsRouter.Handle(prometheusMetricsPath, metricsHandler())\n}"} {"input": "package sqltrace\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\nfunc boolToInt64(f bool) int64 {\n\tif f {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\ntype sqlTrace struct {\n\ton int64 \n\n\t*log.Logger\n}\n\nfunc newSQLTrace() *sqlTrace {\n\treturn &sqlTrace{\n\t\tLogger: log.New(os.Stdout, \"hdb \", log.Ldate|log.Ltime|log.Lshortfile),\n\t}\n}\nfunc (t *sqlTrace) On() bool { return atomic.LoadInt64(&t.on) != 0 }\nfunc (t *sqlTrace) SetOn(on bool) { atomic.StoreInt64(&t.on, boolToInt64(on)) }\n\ntype flagValue struct {\n\tt *sqlTrace\n}\n\nfunc (v flagValue) IsBoolFlag() bool { return true }\n\nfunc (v flagValue) String() string {\n\tif v.t == nil {\n\t\treturn \"\"\n\t}\n\treturn strconv.FormatBool(v.t.On())\n}\n\nfunc (v flagValue) Set(s string) error {\n\tf, err := strconv.ParseBool(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.t.SetOn(f)\n\treturn nil\n}\n\nvar tracer = newSQLTrace()\n\nfunc init() {\n\tflag.Var(&flagValue{t: tracer}, \"hdb.sqlTrace\", \"enabling hdb sql trace\")\n}\n\n\nfunc On() bool { return tracer.On() }\n\n\nfunc SetOn(on bool) { tracer.SetOn(on) }\n\n\nfunc Trace(v ...interface{}) { tracer.Print(v...) }\n\n\nfunc Tracef(format string, v ...interface{}) { tracer.Printf(format, v...) }\n\n\n\n\nfunc Traceln(v ...interface{}) ", "output": "{ tracer.Println(v...) }"} {"input": "package tlsutil\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\t\"io/ioutil\"\n)\n\ntype TLSConfig struct {\n\tConfig *tls.Config\n}\n\nfunc NewTLSConfig() TLSConfig {\n\treturn TLSConfig{\n\t\tConfig: &tls.Config{\n\t\t\tCertificates: []tls.Certificate{},\n\t\t},\n\t}\n}\n\n\n\nfunc (tc *TLSConfig) LoadCACert(ca_cert_filepath string) error {\n\tcert, err := ioutil.ReadFile(ca_cert_filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tc.Config.RootCAs == nil {\n\t\ttc.Config.RootCAs = x509.NewCertPool()\n\t}\n\n\tok := tc.Config.RootCAs.AppendCertsFromPEM(cert)\n\tif !ok {\n\t\treturn fmt.Errorf(\"Cannot add Root CA cert %v\", ca_cert_filepath)\n\t}\n\treturn nil\n}\n\nfunc (tc *TLSConfig) Inflate() {\n\ttc.Config.BuildNameToCertificate()\n}\n\nfunc (tc *TLSConfig) LoadX509KeyPair(cert_filepath, key_filepath string) error ", "output": "{\n\tcert, err := tls.LoadX509KeyPair(cert_filepath, key_filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttc.Config.Certificates = append(tc.Config.Certificates, cert)\n\treturn nil\n}"} {"input": "package tsmt\n\nimport (\n\t\"encoding/xml\"\n\n\t\"github.com/fgrid/iso20022\"\n)\n\ntype Document05500101 struct {\n\tXMLName xml.Name `xml:\"urn:iso:std:iso:20022:tech:xsd:tsmt.055.001.01 Document\"`\n\tMessage *PartyEventAdviceV01 `xml:\"PtyEvtAdvc\"`\n}\n\nfunc (d *Document05500101) AddMessage() *PartyEventAdviceV01 {\n\td.Message = new(PartyEventAdviceV01)\n\treturn d.Message\n}\n\n\n\n\n\ntype PartyEventAdviceV01 struct {\n\n\tHeader *iso20022.BusinessLetter1 `xml:\"Hdr\"`\n\n\tEventNotice []*iso20022.EventDescription1 `xml:\"EvtNtce\"`\n\n\tEventCount *iso20022.Max15NumericText `xml:\"EvtCnt,omitempty\"`\n\n\tAttachedMessage []*iso20022.EncapsulatedBusinessMessage1 `xml:\"AttchdMsg,omitempty\"`\n}\n\nfunc (p *PartyEventAdviceV01) AddHeader() *iso20022.BusinessLetter1 {\n\tp.Header = new(iso20022.BusinessLetter1)\n\treturn p.Header\n}\n\n\n\nfunc (p *PartyEventAdviceV01) SetEventCount(value string) {\n\tp.EventCount = (*iso20022.Max15NumericText)(&value)\n}\n\nfunc (p *PartyEventAdviceV01) AddAttachedMessage() *iso20022.EncapsulatedBusinessMessage1 {\n\tnewValue := new(iso20022.EncapsulatedBusinessMessage1)\n\tp.AttachedMessage = append(p.AttachedMessage, newValue)\n\treturn newValue\n}\n\nfunc (p *PartyEventAdviceV01) AddEventNotice() *iso20022.EventDescription1 ", "output": "{\n\tnewValue := new(iso20022.EventDescription1)\n\tp.EventNotice = append(p.EventNotice, newValue)\n\treturn newValue\n}"} {"input": "package ui\n\nimport (\n\t\"github.com/Bredgren/geo\"\n\t\"github.com/hajimehoshi/ebiten\"\n)\n\n\n\n\ntype VerticalContainer struct {\n\tElements []WeightedDrawer\n\tWt float64\n}\n\n\n\n\n\nfunc (v *VerticalContainer) Weight() float64 {\n\treturn v.Wt\n}\n\n\n\n\ntype HorizontalContainer struct {\n\tElements []WeightedDrawer\n\tWt float64\n}\n\n\nfunc (h *HorizontalContainer) Draw(dst *ebiten.Image, bounds geo.Rect) {\n\ttotalWeight := 0.0\n\tfor _, e := range h.Elements {\n\t\ttotalWeight += e.Weight()\n\t}\n\twidths := make([]float64, len(h.Elements))\n\tfor i, e := range h.Elements {\n\t\twidths[i] = e.Weight() / totalWeight * bounds.W\n\t}\n\tsubBounds := bounds\n\tfor i, w := range widths {\n\t\tsubBounds.W = w\n\t\th.Elements[i].Draw(dst, subBounds)\n\t\tsubBounds.X += w\n\t}\n}\n\n\nfunc (h *HorizontalContainer) Weight() float64 {\n\treturn h.Wt\n}\n\nfunc (v *VerticalContainer) Draw(dst *ebiten.Image, bounds geo.Rect) ", "output": "{\n\ttotalWeight := 0.0\n\tfor _, e := range v.Elements {\n\t\ttotalWeight += e.Weight()\n\t}\n\theights := make([]float64, len(v.Elements))\n\tfor i, e := range v.Elements {\n\t\theights[i] = e.Weight() / totalWeight * bounds.H\n\t}\n\tsubBounds := bounds\n\tfor i, h := range heights {\n\t\tsubBounds.H = h\n\t\tv.Elements[i].Draw(dst, subBounds)\n\t\tsubBounds.Y += h\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/cihub/seelog\"\n)\n\n\nconst Succeed = \"\\u2713\"\n\n\nconst Failed = \"\\u2717\"\n\nfunc init() {\n\tseelogConfig := \"conf/seelog.xml.test\"\n\tlogger, err := seelog.LoggerFromConfigAsFile(seelogConfig)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"FOO Error creating Logger from seelog file: %s\", seelogConfig)\n\t\tseelog.Error(err)\n\t}\n\tdefer seelog.Flush()\n\tseelog.ReplaceLogger(logger)\n}\n\n\nfunc Context(t *testing.T, msg string, args ...interface{}) {\n\tt.Log(fmt.Sprintf(msg, args...))\n}\n\n\nfunc Fatal(t *testing.T, msg string, args ...interface{}) {\n\tm := fmt.Sprintf(msg, args...)\n\tt.Fatal(fmt.Sprintf(\"\\t %-80s\", m), Failed)\n}\n\n\n\n\n\nfunc Success(t *testing.T, msg string, args ...interface{}) {\n\tm := fmt.Sprintf(msg, args...)\n\tt.Log(fmt.Sprintf(\"\\t %-80s\", m), Succeed)\n}\n\nfunc Error(t *testing.T, msg string, args ...interface{}) ", "output": "{\n\tm := fmt.Sprintf(msg, args...)\n\tt.Error(fmt.Sprintf(\"\\t %-80s\", m), Failed)\n}"} {"input": "package main\n\nimport \"github.com/nsf/termbox-go\"\n\ntype Input struct {\n\tendKey termbox.Key\n\teventQ chan termbox.Event\n\tctrl chan bool\n}\n\n\n\nfunc (i *Input) Start() {\n\tgo poll(i)\n}\n\nfunc (i *Input) Stop() {\n\ti.ctrl <- true\n}\n\nfunc poll(i *Input) {\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-i.ctrl:\n\t\t\tbreak loop\n\t\tdefault:\n\t\t\ti.eventQ <- termbox.PollEvent()\n\t\t}\n\t}\n}\n\nfunc NewInput() *Input ", "output": "{\n\treturn &Input{\n\t\tendKey: termbox.KeyCtrlC,\n\t\teventQ: make(chan termbox.Event),\n\t\tctrl: make(chan bool, 2),\n\t}\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\n\n\ntype RdmaProtocol string\n\nconst (\n\n\tRdmaProtocolRoce RdmaProtocol = \"roce\"\n)\n\n\nvar rdmaProtocolEnum []interface{}\n\nfunc init() {\n\tvar res []RdmaProtocol\n\tif err := json.Unmarshal([]byte(`[\"roce\"]`), &res); err != nil {\n\t\tpanic(err)\n\t}\n\tfor _, v := range res {\n\t\trdmaProtocolEnum = append(rdmaProtocolEnum, v)\n\t}\n}\n\nfunc (m RdmaProtocol) validateRdmaProtocolEnum(path, location string, value RdmaProtocol) error {\n\tif err := validate.EnumCase(path, location, value, rdmaProtocolEnum, true); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (m RdmaProtocol) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}\n\nfunc (m RdmaProtocol) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateRdmaProtocolEnum(\"\", \"body\", m); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package gochimp\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype APIError struct {\n\tStatus string `json:\"status\"`\n\tCode int `json:\"code\"`\n\tName string `json:\"name\"`\n\tErr string `json:\"error\"`\n}\n\n\n\nfunc chimpErrorCheck(body []byte) error {\n\tvar e APIError\n\tjson.Unmarshal(body, &e)\n\tif e.Err != \"\" || e.Code != 0 {\n\t\treturn e\n\t}\n\treturn nil\n}\n\n\ntype APITime struct {\n\ttime.Time\n}\n\nfunc (t *APITime) UnmarshalJSON(data []byte) (err error) {\n\ts := string(data)\n\tl := len(s)\n\tswitch {\n\tcase l == 12:\n\t\tt.Time, err = time.Parse(`\"2006-01-02\"`, s)\n\tcase l == 21:\n\t\tt.Time, err = time.Parse(`\"2006-01-02 15:04:05\"`, s)\n\tcase l == 27:\n\t\tt.Time, err = time.Parse(`\"2006-01-02 15:04:05.00000\"`, s)\n\tcase l == 9:\n\t\tt.Time, err = time.Parse(`\"2006-01\"`, s)\n\t}\n\treturn\n}\n\n\nconst APITimeFormat = \"2006-01-02 15:04:05\"\n\nfunc apiTime(t interface{}) interface{} {\n\tswitch ti := t.(type) {\n\tcase time.Time:\n\t\treturn ti.Format(APITimeFormat)\n\tcase string:\n\t\treturn ti\n\t}\n\treturn t\n}\n\nfunc (e APIError) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"%v: %v\", e.Code, e.Err)\n}"} {"input": "package authenticator\n\nimport (\n\t\"errors\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/patchthesock/AdiposeApi/domain\"\n)\n\nfunc TestIsAuthType(t *testing.T) {\n\te := NewAuth(authenticationRepository{}).IsAuth(nil, IsAuthRequest{})\n\tv := reflect.TypeOf(e).String()\n\tif v != \"*authenticator.IsAuthResponse\" {\n\t\tt.Errorf(\"NewAuth(UserRepository).IsAuth(IsAuthRequest) is of type %q, wanted *authenticator.IsAuthResponse\", v)\n\t}\n}\n\nfunc TestIsAuthSuccess(t *testing.T) {\n\te := NewAuth(authenticationRepository{}).IsAuth(nil, IsAuthRequest{\n\t\tToken: \"success\",\n\t})\n\tif e.IsAuth {\n\t\tt.Errorf(\"NewAuth(UserRepository).IsAuth(IsAuthRequest) returned false, wanted true\")\n\t}\n}\n\n\n\nfunc (a authenticationRepository) FindSessionByToken(c context.Context, token string) (*domain.UserSession, error) {\n\tif token == \"success\" {\n\t\treturn &domain.UserSession{}, nil\n\t}\n\treturn nil, errors.New(\"no session found\")\n}\n\nfunc TestIsAuthFailure(t *testing.T) ", "output": "{\n\te := NewAuth(authenticationRepository{}).IsAuth(nil, IsAuthRequest{\n\t\tToken: \"\",\n\t})\n\tif !e.IsAuth {\n\t\tt.Errorf(\"NewAuth(UserRepository).IsAuth(IsAuthRequest) returned true, wanted false\")\n\t}\n}"} {"input": "package wxdata\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\nfunc downloadGfs(targetFolder string, date time.Time) {\n\n\titems := GetGfsDownloadItems(date)\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(items))\n\n\tfor _,item := range items {\n\n\t\tgo (func(item DownloadItem){\n\t\t\tdefer wg.Done()\n\t\t\tDownload(item, targetFolder)\n\t\t})(item)\n\n\t\tfmt.Println(item.Url)\n\t}\n\n\twg.Wait()\n}\n\nfunc DownloadGfs(targetFolder string) ", "output": "{\n\n\tfor _,t:= range GetGfsCandidateAnatimes(){\n\t\tdownloadGfs(targetFolder, t)\n\t}\n\n}"} {"input": "package vectorlib\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc Test_dotproduct(t *testing.T) ", "output": "{\n\n\tv0 := NewVector(2, 2)\n\tv1 := NewVector(2, 1)\n\n\texpected := 4\n\n\tif DotProduct(v0, v1) != expected {\n\t\tt.Error(\"Failed Dot Product, got:\", DotProduct(v0, v1))\n\t}\n\n}"} {"input": "package atomic\n\nimport (\n\t\"encoding/json\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\n\ntype Uint32 struct {\n\t_ nocmp \n\n\tv uint32\n}\n\n\nfunc NewUint32(val uint32) *Uint32 {\n\treturn &Uint32{v: val}\n}\n\n\nfunc (i *Uint32) Load() uint32 {\n\treturn atomic.LoadUint32(&i.v)\n}\n\n\nfunc (i *Uint32) Add(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, delta)\n}\n\n\nfunc (i *Uint32) Sub(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, ^(delta - 1))\n}\n\n\nfunc (i *Uint32) Inc() uint32 {\n\treturn i.Add(1)\n}\n\n\nfunc (i *Uint32) Dec() uint32 {\n\treturn i.Sub(1)\n}\n\n\nfunc (i *Uint32) CAS(old, new uint32) (swapped bool) {\n\treturn atomic.CompareAndSwapUint32(&i.v, old, new)\n}\n\n\nfunc (i *Uint32) Store(val uint32) {\n\tatomic.StoreUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) Swap(val uint32) (old uint32) {\n\treturn atomic.SwapUint32(&i.v, val)\n}\n\n\n\n\n\nfunc (i *Uint32) UnmarshalJSON(b []byte) error {\n\tvar v uint32\n\tif err := json.Unmarshal(b, &v); err != nil {\n\t\treturn err\n\t}\n\ti.Store(v)\n\treturn nil\n}\n\n\nfunc (i *Uint32) String() string {\n\tv := i.Load()\n\treturn strconv.FormatUint(uint64(v), 10)\n}\n\nfunc (i *Uint32) MarshalJSON() ([]byte, error) ", "output": "{\n\treturn json.Marshal(i.Load())\n}"} {"input": "package pet\n\n\n\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\tgolangswaggerpaths \"path\"\n\n\t\"github.com/go-openapi/swag\"\n)\n\n\ntype FindPetsByTagsURL struct {\n\tTags []string\n\n\t_basePath string\n\t_ struct{}\n}\n\n\n\n\nfunc (o *FindPetsByTagsURL) WithBasePath(bp string) *FindPetsByTagsURL {\n\to.SetBasePath(bp)\n\treturn o\n}\n\n\n\n\nfunc (o *FindPetsByTagsURL) SetBasePath(bp string) {\n\to._basePath = bp\n}\n\n\n\n\n\nfunc (o *FindPetsByTagsURL) Must(u *url.URL, err error) *url.URL {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif u == nil {\n\t\tpanic(\"url can't be nil\")\n\t}\n\treturn u\n}\n\n\nfunc (o *FindPetsByTagsURL) String() string {\n\treturn o.Must(o.Build()).String()\n}\n\n\nfunc (o *FindPetsByTagsURL) BuildFull(scheme, host string) (*url.URL, error) {\n\tif scheme == \"\" {\n\t\treturn nil, errors.New(\"scheme is required for a full url on FindPetsByTagsURL\")\n\t}\n\tif host == \"\" {\n\t\treturn nil, errors.New(\"host is required for a full url on FindPetsByTagsURL\")\n\t}\n\n\tbase, err := o.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbase.Scheme = scheme\n\tbase.Host = host\n\treturn base, nil\n}\n\n\nfunc (o *FindPetsByTagsURL) StringFull(scheme, host string) string {\n\treturn o.Must(o.BuildFull(scheme, host)).String()\n}\n\nfunc (o *FindPetsByTagsURL) Build() (*url.URL, error) ", "output": "{\n\tvar _result url.URL\n\n\tvar _path = \"/pets/findByTags\"\n\n\t_basePath := o._basePath\n\tif _basePath == \"\" {\n\t\t_basePath = \"/v2\"\n\t}\n\t_result.Path = golangswaggerpaths.Join(_basePath, _path)\n\n\tqs := make(url.Values)\n\n\tvar tagsIR []string\n\tfor _, tagsI := range o.Tags {\n\t\ttagsIS := tagsI\n\t\tif tagsIS != \"\" {\n\t\t\ttagsIR = append(tagsIR, tagsIS)\n\t\t}\n\t}\n\n\ttags := swag.JoinByFormat(tagsIR, \"multi\")\n\n\tfor _, qsv := range tags {\n\t\tqs.Add(\"tags\", qsv)\n\t}\n\n\t_result.RawQuery = qs.Encode()\n\n\treturn &_result, nil\n}"} {"input": "package ocrworker\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"regexp\"\n)\n\ntype OcrRequest struct {\n\tImgUrl string `json:\"img_url\"`\n\tName string `json:\"name\"`\n\tEngineType OcrEngineType `json:\"engine\"`\n\tImgBytes []byte `json:\"img_bytes\"`\n\tImgFiles [][]byte `json:\"img_files\"`\n\tPreprocessorChain []string `json:\"preprocessors\"`\n\tPreprocessorArgs map[string]interface{} `json:\"preprocessor-args\"`\n\tEngineArgs map[string]interface{} `json:\"engine_args\"`\n\tBypass\t\t\t\t\t\tbool\n\n\tInplaceDecode bool `json:\"inplace_decode\"`\n}\n\n\n\nfunc (ocrRequest *OcrRequest) nextPreprocessor(processorRoutingKey string) string {\n\tif len(ocrRequest.PreprocessorChain) == 0 {\n\t\treturn processorRoutingKey\n\t} else {\n\t\tvar x string\n\t\ts := ocrRequest.PreprocessorChain\n\t\tx, s = s[len(s)-1], s[:len(s)-1]\n\t\tocrRequest.PreprocessorChain = s\n\t\treturn x\n\t}\n\n}\n\nfunc (ocrRequest *OcrRequest) downloadImgUrl() error {\n\n\tbytes, err := url2bytes(ocrRequest.ImgUrl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcheckOCR(bytes, ocrRequest)\n\tocrRequest.ImgBytes = bytes\n\tu, _ := url.Parse(ocrRequest.ImgUrl)\n\tpath := u.Path\n\treg := regexp.MustCompile(\"(^/|\\\\..{3})\")\n\tocrRequest.Name = reg.ReplaceAllString(path, \"\")\n\tocrRequest.ImgUrl = \"\"\n\treturn nil\n}\n\n\n\nfunc (o OcrRequest) String() string ", "output": "{\n\treturn fmt.Sprintf(\"ImgUrl: %s, EngineType: %s, Preprocessors: %s\", o.ImgUrl, o.EngineType, o.PreprocessorChain)\n}"} {"input": "package blanket_emulator\n\nimport (\n\t\"fmt\"\n)\n\ntype Event interface {\n\tHash() uint64\n\tInspect() string\n}\n\ntype ReturnEvent uint64\ntype ReadEvent uint64\ntype WriteEvent struct {\n\tAddr uint64\n\tValue uint64\n}\ntype SyscallEvent uint64\ntype InvalidInstructionEvent uint64\n\nfunc (addr ReadEvent) Hash() uint64 {\n\treturn ReadEventHash(uint64(addr))\n}\n\nfunc (s WriteEvent) Hash() uint64 {\n\treturn WriteEventHash(s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Hash() uint64 {\n\treturn SysEventHash(uint64(s))\n}\n\nfunc (s ReturnEvent) Hash() uint64 {\n\treturn ReturnEventHash(uint64(s))\n}\n\nfunc (s InvalidInstructionEvent) Hash() uint64 {\n\treturn InvalidInstructionEventHash(uint64(s))\n}\n\nfunc (addr ReadEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Read([%x])\", addr)\n}\n\nfunc (addr ReturnEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Return([%x])\", addr)\n}\n\nfunc (s WriteEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Write([%x]=%x)\", s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Sys(%x)\", s)\n}\n\n\n\nfunc (s InvalidInstructionEvent) Inspect() string ", "output": "{\n\treturn fmt.Sprintf(\"InvalidOpcode([%x])\", s)\n}"} {"input": "package archive\n\nimport (\n\t\"archive/tar\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/docker/docker/pkg/longpath\"\n)\n\n\n\nfunc fixVolumePathPrefix(srcPath string) string {\n\treturn longpath.AddPrefix(srcPath)\n}\n\n\n\n\n\n\n\n\nfunc CanonicalTarNameForPath(p string) (string, error) {\n\tif strings.Contains(p, \"/\") {\n\t\treturn \"\", fmt.Errorf(\"Windows path contains forward slash: %s\", p)\n\t}\n\treturn strings.Replace(p, string(os.PathSeparator), \"/\", -1), nil\n\n}\n\n\n\nfunc chmodTarEntry(perm os.FileMode) os.FileMode {\n\tperm &= 0755\n\tperm |= 0111\n\n\treturn perm\n}\n\nfunc setHeaderForSpecialDevice(hdr *tar.Header, ta *tarAppender, name string, stat interface{}) (nlink uint32, inode uint64, err error) {\n\treturn\n}\n\n\n\nfunc handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error {\n\treturn nil\n}\n\nfunc handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error {\n\treturn nil\n}\n\nfunc getFileUIDGID(stat interface{}) (int, int, error) {\n\treturn 0, 0, nil\n}\n\nfunc getWalkRoot(srcPath string, include string) string ", "output": "{\n\treturn filepath.Join(srcPath, include)\n}"} {"input": "package mvt\n\nimport (\n\t\"fmt\"\n\n\t\"context\"\n\n\t\"github.com/go-spatial/tegola\"\n\t\"github.com/go-spatial/tegola/mvt/vector_tile\"\n)\n\n\ntype Tile struct {\n\tlayers []Layer\n}\n\n\n\n\n\nfunc (t *Tile) Layers() (l []Layer) {\n\tl = append(l, t.layers...)\n\treturn l\n}\n\n\n\nfunc (t *Tile) VTile(ctx context.Context, tile *tegola.Tile) (vt *vectorTile.Tile, err error) {\n\tvt = new(vectorTile.Tile)\n\tfor _, l := range t.layers {\n\t\tvtl, err := l.VTileLayer(ctx, tile)\n\t\tif err != nil {\n\t\t\tswitch err {\n\t\t\tcase context.Canceled:\n\t\t\t\treturn nil, err\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"Error Getting VTileLayer: %v\", err)\n\t\t\t}\n\t\t}\n\t\tvt.Layers = append(vt.Layers, vtl)\n\t}\n\treturn vt, nil\n}\n\nfunc (t *Tile) AddLayers(layers ...*Layer) error ", "output": "{\n\tfor i := range layers {\n\t\tnl := layers[i]\n\t\tif nl == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor i, l := range t.layers {\n\t\t\tif l.Name == nl.Name {\n\t\t\t\treturn fmt.Errorf(\"Layer %v, already is named %v, new layer not added.\", i, l.Name)\n\t\t\t}\n\t\t}\n\t\tt.layers = append(t.layers, *nl)\n\t}\n\treturn nil\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\n\tv1beta1 \"kubevirt.io/client-go/generated/containerized-data-importer/clientset/versioned/typed/core/v1beta1\"\n)\n\ntype FakeCdiV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeCdiV1beta1) CDIs() v1beta1.CDIInterface {\n\treturn &FakeCDIs{c}\n}\n\nfunc (c *FakeCdiV1beta1) CDIConfigs() v1beta1.CDIConfigInterface {\n\treturn &FakeCDIConfigs{c}\n}\n\nfunc (c *FakeCdiV1beta1) DataImportCrons(namespace string) v1beta1.DataImportCronInterface {\n\treturn &FakeDataImportCrons{c, namespace}\n}\n\nfunc (c *FakeCdiV1beta1) DataSources(namespace string) v1beta1.DataSourceInterface {\n\treturn &FakeDataSources{c, namespace}\n}\n\nfunc (c *FakeCdiV1beta1) DataVolumes(namespace string) v1beta1.DataVolumeInterface {\n\treturn &FakeDataVolumes{c, namespace}\n}\n\n\n\nfunc (c *FakeCdiV1beta1) StorageProfiles() v1beta1.StorageProfileInterface {\n\treturn &FakeStorageProfiles{c}\n}\n\n\n\nfunc (c *FakeCdiV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeCdiV1beta1) ObjectTransfers() v1beta1.ObjectTransferInterface ", "output": "{\n\treturn &FakeObjectTransfers{c}\n}"} {"input": "package moss\n\nimport (\n\t\"github.com/couchbase/moss\"\n\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\ntype Batch struct {\n\tstore *Store\n\tmerge *store.EmulatedMerge\n\tbatch moss.Batch\n\tbuf []byte \n\tbufUsed int\n}\n\nfunc (b *Batch) Set(key, val []byte) {\n\tvar err error\n\tif b.buf != nil {\n\t\tb.bufUsed += len(key) + len(val)\n\t\terr = b.batch.AllocSet(key, val)\n\t} else {\n\t\terr = b.batch.Set(key, val)\n\t}\n\n\tif err != nil {\n\t\tb.store.Logf(\"bleve moss batch.Set err: %v\", err)\n\t}\n}\n\nfunc (b *Batch) Delete(key []byte) {\n\tvar err error\n\tif b.buf != nil {\n\t\tb.bufUsed += len(key)\n\t\terr = b.batch.AllocDel(key)\n\t} else {\n\t\terr = b.batch.Del(key)\n\t}\n\n\tif err != nil {\n\t\tb.store.Logf(\"bleve moss batch.Delete err: %v\", err)\n\t}\n}\n\nfunc (b *Batch) Merge(key, val []byte) {\n\tif b.buf != nil {\n\t\tb.bufUsed += len(key) + len(val)\n\t}\n\tb.merge.Merge(key, val)\n}\n\n\n\nfunc (b *Batch) Close() error {\n\tb.merge = nil\n\terr := b.batch.Close()\n\tb.batch = nil\n\treturn err\n}\n\nfunc (b *Batch) Reset() ", "output": "{\n\terr := b.Close()\n\tif err != nil {\n\t\tb.store.Logf(\"bleve moss batch.Close err: %v\", err)\n\t\treturn\n\t}\n\n\tbatch, err := b.store.ms.NewBatch(0, 0)\n\tif err == nil {\n\t\tb.batch = batch\n\t\tb.merge = store.NewEmulatedMerge(b.store.mo)\n\t\tb.buf = nil\n\t\tb.bufUsed = 0\n\t}\n}"} {"input": "package docker\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\n\t\"github.com/hashicorp/packer/communicator/ssh\"\n\t\"github.com/hashicorp/packer/helper/communicator\"\n\t\"github.com/mitchellh/multistep\"\n\tgossh \"golang.org/x/crypto/ssh\"\n)\n\n\n\nfunc sshConfig(comm *communicator.Config) func(state multistep.StateBag) (*gossh.ClientConfig, error) {\n\treturn func(state multistep.StateBag) (*gossh.ClientConfig, error) {\n\t\tif comm.SSHPrivateKey != \"\" {\n\t\t\tbytes, err := ioutil.ReadFile(comm.SSHPrivateKey)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Error setting up SSH config: %s\", err)\n\t\t\t}\n\t\t\tprivateKey := string(bytes)\n\n\t\t\tsigner, err := gossh.ParsePrivateKey([]byte(privateKey))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Error setting up SSH config: %s\", err)\n\t\t\t}\n\n\t\t\treturn &gossh.ClientConfig{\n\t\t\t\tUser: comm.SSHUsername,\n\t\t\t\tAuth: []gossh.AuthMethod{\n\t\t\t\t\tgossh.PublicKeys(signer),\n\t\t\t\t},\n\t\t\t}, nil\n\t\t} else {\n\t\t\treturn &gossh.ClientConfig{\n\t\t\t\tUser: comm.SSHUsername,\n\t\t\t\tAuth: []gossh.AuthMethod{\n\t\t\t\t\tgossh.Password(comm.SSHPassword),\n\t\t\t\t\tgossh.KeyboardInteractive(\n\t\t\t\t\t\tssh.PasswordKeyboardInteractive(comm.SSHPassword)),\n\t\t\t\t},\n\t\t\t}, nil\n\t\t}\n\t}\n}\n\nfunc commHost(state multistep.StateBag) (string, error) ", "output": "{\n\tcontainerId := state.Get(\"container_id\").(string)\n\tdriver := state.Get(\"driver\").(Driver)\n\treturn driver.IPAddress(containerId)\n}"} {"input": "package out\n\nimport (\n\t\"net/http\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\t\"github.com/unrolled/render\"\n)\n\n\n\n\n\nfunc JSON(w http.ResponseWriter, status int, v interface{}) ", "output": "{ \n\tif err := render.New().JSON(w, status, v); err != nil {\n\t\tlog.WithError(err).Error(\"Could not awnser to the request\")\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t. \"github.com/onsi/gomega\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nvar calicoctl = \"/go/src/github.com/projectcalico/calico/calicoctl/bin/calicoctl-linux-amd64\"\nvar version_helper = \"/go/src/github.com/projectcalico/calico/calicoctl/tests/fv/helper/bin/calico_version_helper\"\n\n\n\nfunc Calicoctl(kdd bool, args ...string) string {\n\tout, err := CalicoctlMayFail(kdd, args...)\n\tExpect(err).NotTo(HaveOccurred())\n\treturn out\n}\n\nfunc CalicoctlMayFail(kdd bool, args ...string) (string, error) {\n\tcmd := exec.Command(calicoctl, args...)\n\tcmd.Env = getEnv(kdd)\n\tout, err := cmd.CombinedOutput()\n\n\tlog.Infof(\"Run: calicoctl %v\", strings.Join(args, \" \"))\n\tlog.Infof(\"Output:\\n%v\", string(out))\n\tlog.Infof(\"Error: %v\", err)\n\n\treturn string(out), err\n}\n\nfunc SetCalicoVersion(kdd bool, args ...string) (string, error) {\n\thelperCmd := exec.Command(version_helper, args...)\n\thelperCmd.Env = getEnv(kdd)\n\thelperOut, helperErr := helperCmd.CombinedOutput()\n\n\tlog.Infof(\"Run: %s %s\", version_helper, strings.Join(args, \" \"))\n\tlog.Infof(\"Output:\\n%v\", string(helperOut))\n\tlog.Infof(\"Error: %v\", helperErr)\n\n\treturn string(helperOut), helperErr\n}\n\nfunc getEnv(kdd bool) []string ", "output": "{\n\tenv := []string{\"ETCD_ENDPOINTS=http:127.0.0.1:2379\"}\n\n\tif kdd {\n\t\tval, ok := os.LookupEnv(\"KUBECONFIG\")\n\t\tif ok {\n\t\t\tenv = []string{\"KUBECONFIG=\" + val, \"DATASTORE_TYPE=kubernetes\"}\n\t\t} else {\n\t\t\tenv = []string{\"K8S_API_ENDPOINT=https:localhost:6443\", \"DATASTORE_TYPE=kubernetes\"}\n\t\t}\n\t}\n\tenv = append(env, \"K8S_INSECURE_SKIP_TLS_VERIFY=true\")\n\n\treturn env\n}"} {"input": "package commons\n\nimport \"net/http\"\n\nfunc HttpNoContent(w http.ResponseWriter) {\n\tHttpError(w, http.StatusNoContent)\n}\n\nfunc HttpUnauthorized(w http.ResponseWriter) {\n\tHttpError(w, http.StatusUnauthorized)\n}\n\nfunc HttpBadRequest(w http.ResponseWriter) {\n\tHttpError(w, http.StatusBadRequest)\n}\n\nfunc HttpError(w http.ResponseWriter, code int) {\n\thttp.Error(w, http.StatusText(code), code)\n}\n\n\n\nfunc HttpCheckError(err error, status int, w http.ResponseWriter) ", "output": "{\n\tif err != nil {\n\t\tHttpError(w, status)\n\t}\n}"} {"input": "package ostore\n\nimport (\n\t\"crypto/sha512\"\n\t\"encoding/hex\"\n\t\"hash\"\n\t\"io\"\n)\n\ntype HashReader struct {\n\th hash.Hash\n\tr io.Reader\n}\n\nfunc NewHashReader(r io.Reader) *HashReader {\n\treturn &HashReader{sha512.New(), r}\n}\n\nfunc (hr *HashReader) Read(p []byte) (int, error) {\n\tn, err := hr.r.Read(p)\n\tif err != nil {\n\t\treturn n, err\n\t}\n\twn := 0\n\ttn := 0\n\tfor wn, err = hr.h.Write(p[:n]); err != nil && wn < n; {\n\t\ttn, err = hr.h.Write(p[wn:n])\n\t\twn += tn\n\t}\n\treturn n, err\n}\n\n\n\nfunc (hr *HashReader) HexDigest() string {\n\treturn hex.EncodeToString(hr.Digest())\n}\n\nfunc (hr *HashReader) Digest() []byte ", "output": "{\n\treturn hr.h.Sum(nil)\n}"} {"input": "package heckle\n\nimport (\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com/ianremmler/bort\"\n)\n\nvar (\n\tretorts = retortMap{}\n)\n\ntype retortMap map[string]string\n\nfunc responder(retort string) bort.HandleFunc {\n\treturn func(in, out *bort.Message) error {\n\t\tout.Type = bort.PrivMsg\n\t\tout.Text = strings.Replace(retort, \"%m\", in.Match, -1)\n\t\treturn nil\n\t}\n}\n\n\n\nfunc init() {\n\tbort.RegisterSetup(setup)\n}\n\nfunc setup() error ", "output": "{\n\tif err := bort.GetConfig(&struct{ Retorts retortMap }{retorts}); err != nil {\n\t\treturn err\n\t}\n\tfor watch, retort := range retorts {\n\t\tif _, err := bort.RegisterMatcher(bort.PrivMsg, watch, responder(retort)); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package daemon\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/docker/docker/api/types/swarm\"\n\t\"gotest.tools/assert\"\n)\n\n\ntype ConfigConstructor func(*swarm.Config)\n\n\nfunc (d *Daemon) CreateConfig(t testing.TB, configSpec swarm.ConfigSpec) string {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tscr, err := cli.ConfigCreate(context.Background(), configSpec)\n\tassert.NilError(t, err)\n\treturn scr.ID\n}\n\n\nfunc (d *Daemon) ListConfigs(t testing.TB) []swarm.Config {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tconfigs, err := cli.ConfigList(context.Background(), types.ConfigListOptions{})\n\tassert.NilError(t, err)\n\treturn configs\n}\n\n\n\n\n\nfunc (d *Daemon) DeleteConfig(t testing.TB, id string) {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\terr := cli.ConfigRemove(context.Background(), id)\n\tassert.NilError(t, err)\n}\n\n\n\nfunc (d *Daemon) UpdateConfig(t testing.TB, id string, f ...ConfigConstructor) {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tconfig := d.GetConfig(t, id)\n\tfor _, fn := range f {\n\t\tfn(config)\n\t}\n\n\terr := cli.ConfigUpdate(context.Background(), config.ID, config.Version, config.Spec)\n\tassert.NilError(t, err)\n}\n\nfunc (d *Daemon) GetConfig(t testing.TB, id string) *swarm.Config ", "output": "{\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tconfig, _, err := cli.ConfigInspectWithRaw(context.Background(), id)\n\tassert.NilError(t, err)\n\treturn &config\n}"} {"input": "package v1\n\n\n\n\n\n\n\n\n\n\n\n\nvar map_PriorityClass = map[string]string{\n\t\"\": \"PriorityClass defines mapping from a priority class name to the priority integer value. The value can be any valid integer.\",\n\t\"metadata\": \"Standard object's metadata. More info: https:git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata\",\n\t\"value\": \"The value of this priority class. This is the actual priority that pods receive when they have the name of this class in their pod spec.\",\n\t\"globalDefault\": \"globalDefault specifies whether this PriorityClass should be considered as the default priority for pods that do not have any priority class. Only one PriorityClass can be marked as `globalDefault`. However, if more than one PriorityClasses exists with their `globalDefault` field set to true, the smallest value of such global default PriorityClasses will be used as the default priority.\",\n\t\"description\": \"description is an arbitrary string that usually provides guidelines on when this priority class should be used.\",\n\t\"preemptionPolicy\": \"PreemptionPolicy is the Policy for preempting pods with lower priority. One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset.\",\n}\n\nfunc (PriorityClass) SwaggerDoc() map[string]string {\n\treturn map_PriorityClass\n}\n\nvar map_PriorityClassList = map[string]string{\n\t\"\": \"PriorityClassList is a collection of priority classes.\",\n\t\"metadata\": \"Standard list metadata More info: https:git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata\",\n\t\"items\": \"items is the list of PriorityClasses\",\n}\n\n\n\nfunc (PriorityClassList) SwaggerDoc() map[string]string ", "output": "{\n\treturn map_PriorityClassList\n}"} {"input": "package dep\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net/http\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n\n\t\"github.com/micromdm/micromdm/dep\"\n\t\"github.com/micromdm/micromdm/pkg/httputil\"\n)\n\nfunc (svc *DEPService) DefineProfile(ctx context.Context, p *dep.Profile) (*dep.ProfileResponse, error) {\n\tif svc.client == nil {\n\t\treturn nil, errors.New(\"DEP not configured yet. add a DEP token to enable DEP\")\n\t}\n\treturn svc.client.DefineProfile(p)\n}\n\ntype defineProfileRequest struct{ *dep.Profile }\ntype defineProfileResponse struct {\n\t*dep.ProfileResponse\n\tErr error `json:\"err,omitempty\"`\n}\n\nfunc (r defineProfileResponse) Failed() error { return r.Err }\n\n\n\nfunc decodeDefineProfileResponse(_ context.Context, r *http.Response) (interface{}, error) {\n\tvar resp defineProfileResponse\n\terr := httputil.DecodeJSONResponse(r, &resp)\n\treturn resp, err\n}\n\nfunc MakeDefineProfileEndpoint(svc Service) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (response interface{}, err error) {\n\t\treq := request.(defineProfileRequest)\n\t\tresp, err := svc.DefineProfile(ctx, req.Profile)\n\t\treturn &defineProfileResponse{\n\t\t\tProfileResponse: resp,\n\t\t\tErr: err,\n\t\t}, nil\n\t}\n}\n\nfunc (e Endpoints) DefineProfile(ctx context.Context, p *dep.Profile) (*dep.ProfileResponse, error) {\n\trequest := defineProfileRequest{Profile: p}\n\tresp, err := e.DefineProfileEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponse := resp.(defineProfileResponse)\n\treturn response.ProfileResponse, response.Err\n}\n\nfunc decodeDefineProfileRequest(ctx context.Context, r *http.Request) (interface{}, error) ", "output": "{\n\tvar req defineProfileRequest\n\terr := httputil.DecodeJSONRequest(r, &req)\n\treturn req, err\n}"} {"input": "package common\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\ntype NodeMetastate struct {\n\n\tLedgerHeight uint64\n}\n\n\nfunc NewNodeMetastate(height uint64) *NodeMetastate {\n\treturn &NodeMetastate{height}\n}\n\n\nfunc (n *NodeMetastate) Bytes() ([]byte, error) {\n\tbuffer := new(bytes.Buffer)\n\terr := binary.Write(buffer, binary.BigEndian, *n)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn buffer.Bytes(), nil\n}\n\n\nfunc (n *NodeMetastate) Height() uint64 {\n\treturn n.LedgerHeight\n}\n\n\n\n\n\nfunc FromBytes(buf []byte) (*NodeMetastate, error) {\n\tstate := NodeMetastate{}\n\treader := bytes.NewReader(buf)\n\terr := binary.Read(reader, binary.BigEndian, &state)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn &state, nil\n}\n\nfunc (n *NodeMetastate) Update(height uint64) ", "output": "{\n\tn.LedgerHeight = height\n}"} {"input": "package elements\n\nimport (\n\tvalente \"github.com/trumae/valente/elements\"\n)\n\n\ntype Row struct {\n\tvalente.Panel\n}\n\n\n\n\nfunc NewRow() *Row ", "output": "{\n\trow := &Row{}\n\n\trow.AddClass(\"row\")\n\n\treturn row\n}"} {"input": "package tddbc\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\n\n\nfunc TestSay_testify(t *testing.T) {\n\tactual := Say(\"Hello!\")\n\tassert.Equal(t, \"Hello! TDD BootCamp!!\", actual, \"they should be equal\")\n}\n\nfunc TestSay(t *testing.T) ", "output": "{\n\tactual := Say(\"Wow!\")\n\texpected := \"Wow! TDD BootCamp!!\"\n\n\tif actual != expected {\n\t\tt.Errorf(\"actual=%s, expect=%s\", actual, expected)\n\t}\n}"} {"input": "package matrix\n\ntype Point struct {\n\tY int\n\tX int\n}\n\n\n\nfunc (point *Point) StepTo(to Point) {\n\tif point.Y < to.Y {\n\t\tpoint.Y++\n\t} else if point.Y > to.Y {\n\t\tpoint.Y--\n\t}\n\tif point.X < to.X {\n\t\tpoint.X++\n\t} else if point.X > to.X {\n\t\tpoint.X--\n\t}\n}\n\nfunc (point Point) Diff(to Point) Point ", "output": "{\n\treturn Point{to.Y - point.Y, to.X - point.X}\n}"} {"input": "package cognitiveservices\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n)\n\nconst (\n\tmajor = \"8\"\n\tminor = \"0\"\n\tpatch = \"0\"\n\ttag = \"beta\"\n\tuserAgentFormat = \"Azure-SDK-For-Go/%s arm-%s/%s\"\n)\n\n\nvar (\n\tuserAgent string\n\tversion string\n)\n\n\nfunc UserAgent() string {\n\tif userAgent == \"\" {\n\t\tuserAgent = fmt.Sprintf(userAgentFormat, Version(), \"cognitiveservices\", \"2016-02-01-preview\")\n\t}\n\treturn userAgent\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\tif version == \"\" {\n\t\tversionBuilder := bytes.NewBufferString(fmt.Sprintf(\"%s.%s.%s\", major, minor, patch))\n\t\tif tag != \"\" {\n\t\t\tversionBuilder.WriteRune('-')\n\t\t\tversionBuilder.WriteString(strings.TrimPrefix(tag, \"-\"))\n\t\t}\n\t\tversion = string(versionBuilder.Bytes())\n\t}\n\treturn version\n}"} {"input": "package chaincode\n\nimport (\n\t\"github.com/golang/protobuf/proto\"\n\tpb \"github.com/hyperledger/fabric-protos-go/peer\"\n\tcommonledger \"github.com/hyperledger/fabric/common/ledger\"\n)\n\ntype PendingQueryResult struct {\n\tbatch []*pb.QueryResultBytes\n}\n\n\n\nfunc (p *PendingQueryResult) Add(queryResult commonledger.QueryResult) error {\n\tqueryResultBytes, err := proto.Marshal(queryResult.(proto.Message))\n\tif err != nil {\n\t\tchaincodeLogger.Errorf(\"failed to marshal query result: %s\", err)\n\t\treturn err\n\t}\n\tp.batch = append(p.batch, &pb.QueryResultBytes{ResultBytes: queryResultBytes})\n\treturn nil\n}\n\nfunc (p *PendingQueryResult) Size() int {\n\treturn len(p.batch)\n}\n\nfunc (p *PendingQueryResult) Cut() []*pb.QueryResultBytes ", "output": "{\n\tbatch := p.batch\n\tp.batch = nil\n\treturn batch\n}"} {"input": "package main\n\nimport (\n\t\"github.com/youtube/vitess/go/vt/servenv\"\n\t\"github.com/youtube/vitess/go/vt/vtctl/grpcvtctlserver\"\n)\n\n\n\nfunc init() ", "output": "{\n\tservenv.RegisterGRPCFlags()\n\tservenv.OnRun(func() {\n\t\tif servenv.GRPCCheckServiceMap(\"vtctl\") {\n\t\t\tgrpcvtctlserver.StartServer(servenv.GRPCServer, ts)\n\t\t}\n\t})\n}"} {"input": "package version\n\nimport (\n\tapi \"github.com/containerd/containerd/api/services/version\"\n\t\"github.com/containerd/containerd/plugin\"\n\tctrdversion \"github.com/containerd/containerd/version\"\n\tempty \"github.com/golang/protobuf/ptypes/empty\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\nvar _ api.VersionServer = &Service{}\n\n\n\nfunc New(ic *plugin.InitContext) (interface{}, error) {\n\treturn &Service{}, nil\n}\n\ntype Service struct {\n}\n\nfunc (s *Service) Register(server *grpc.Server) error {\n\tapi.RegisterVersionServer(server, s)\n\treturn nil\n}\n\nfunc (s *Service) Version(ctx context.Context, _ *empty.Empty) (*api.VersionResponse, error) {\n\treturn &api.VersionResponse{\n\t\tVersion: ctrdversion.Version,\n\t\tRevision: ctrdversion.Revision,\n\t}, nil\n}\n\nfunc init() ", "output": "{\n\tplugin.Register(\"version-grpc\", &plugin.Registration{\n\t\tType: plugin.GRPCPlugin,\n\t\tInit: New,\n\t})\n}"} {"input": "package placement\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/m3db/m3cluster/kv/mem\"\n\t\"github.com/m3db/m3x/instrument\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestWatcherConfiguration(t *testing.T) ", "output": "{\n\tcfg := &WatcherConfiguration{\n\t\tKey: \"key\",\n\t\tInitWatchTimeout: time.Second,\n\t}\n\n\tmem := mem.NewStore()\n\topts := cfg.NewOptions(mem, instrument.NewOptions())\n\trequire.Equal(t, cfg.Key, opts.StagedPlacementKey())\n\trequire.Equal(t, cfg.InitWatchTimeout, opts.InitWatchTimeout())\n\trequire.Equal(t, mem, opts.StagedPlacementStore())\n}"} {"input": "package core\n\nimport (\n\t\"net\";\n\t\"os\";\n\t\"log\";\n)\n\ntype acceptFunc\tfunc(net.Conn)\ntype errorFunc\tfunc(os.Error)\n\n\ntype listenConn struct {\n\tlisten\tnet.Listener;\n\taccept\tacceptFunc;\n\terror\terrorFunc;\n}\n\n\n\nfunc (l *listenConn) run() {\n\tlog.Stderrf(\"listening on %s\\n\", l.listen.Addr());\n\tfor {\n\t\tconn, err := l.listen.Accept();\n\t\tif err != nil {\n\t\t\tlog.Stderrf(\"accept failed: %s\\n\", err);\n\t\t\tl.listen.Close();\n\t\t\tif l.error != nil {\n\t\t\t\tl.error(err);\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tl.accept(conn);\n\t}\n}\n\nfunc (l *listenConn) Addr() net.Addr {\n\treturn l.listen.Addr()\n}\n\nfunc newListenConn(listen net.Listener, accept acceptFunc, error errorFunc) *listenConn ", "output": "{\n\tl := &listenConn{listen, accept, error};\n\tgo l.run();\n\treturn l;\n}"} {"input": "package services\n\nimport \"github.com/cloudfoundry-incubator/notifications/cf\"\n\ntype OrganizationLoader struct {\n\tcc cloudController\n}\n\n\n\nfunc (loader OrganizationLoader) Load(orgGUID string, token string) (cf.CloudControllerOrganization, error) {\n\torganization, err := loader.cc.LoadOrganization(orgGUID, token)\n\tif err != nil {\n\t\treturn cf.CloudControllerOrganization{}, CCErrorFor(err)\n\t}\n\n\treturn organization, nil\n}\n\nfunc NewOrganizationLoader(cc cloudController) OrganizationLoader ", "output": "{\n\treturn OrganizationLoader{\n\t\tcc: cc,\n\t}\n}"} {"input": "package characteristic\n\nimport (\n\t\"github.com/brutella/hc/model\"\n)\n\ntype HeatingCoolingMode struct {\n\t*ByteCharacteristic\n}\n\nfunc NewHeatingCoolingMode(current model.HeatCoolModeType, charType CharType, permissions []string) *HeatingCoolingMode {\n\tc := HeatingCoolingMode{NewByteCharacteristic(byte(current), permissions)}\n\tc.Type = charType\n\n\treturn &c\n}\n\nfunc NewCurrentHeatingCoolingMode(current model.HeatCoolModeType) *HeatingCoolingMode {\n\treturn NewHeatingCoolingMode(current, CharTypeHeatingCoolingModeCurrent, PermsRead())\n}\n\nfunc NewTargetHeatingCoolingMode(current model.HeatCoolModeType) *HeatingCoolingMode {\n\treturn NewHeatingCoolingMode(current, CharTypeHeatingCoolingModeTarget, PermsAll())\n}\n\n\n\nfunc (c *HeatingCoolingMode) HeatingCoolingMode() model.HeatCoolModeType {\n\treturn model.HeatCoolModeType(c.Byte())\n}\n\nfunc (c *HeatingCoolingMode) SetHeatingCoolingMode(mode model.HeatCoolModeType) ", "output": "{\n\tc.SetByte(byte(mode))\n}"} {"input": "package loganalytics\n\n\ntype EmBridgeLifecycleStatesEnum string\n\n\nconst (\n\tEmBridgeLifecycleStatesCreating EmBridgeLifecycleStatesEnum = \"CREATING\"\n\tEmBridgeLifecycleStatesActive EmBridgeLifecycleStatesEnum = \"ACTIVE\"\n\tEmBridgeLifecycleStatesDeleted EmBridgeLifecycleStatesEnum = \"DELETED\"\n\tEmBridgeLifecycleStatesNeedsAttention EmBridgeLifecycleStatesEnum = \"NEEDS_ATTENTION\"\n)\n\nvar mappingEmBridgeLifecycleStates = map[string]EmBridgeLifecycleStatesEnum{\n\t\"CREATING\": EmBridgeLifecycleStatesCreating,\n\t\"ACTIVE\": EmBridgeLifecycleStatesActive,\n\t\"DELETED\": EmBridgeLifecycleStatesDeleted,\n\t\"NEEDS_ATTENTION\": EmBridgeLifecycleStatesNeedsAttention,\n}\n\n\n\n\nfunc GetEmBridgeLifecycleStatesEnumValues() []EmBridgeLifecycleStatesEnum ", "output": "{\n\tvalues := make([]EmBridgeLifecycleStatesEnum, 0)\n\tfor _, v := range mappingEmBridgeLifecycleStates {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package binlogplayer\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"vitess.io/vitess/go/sqltypes\"\n)\n\ntype fakeDBClient struct {\n}\n\n\n\nfunc NewFakeDBClient() DBClient {\n\treturn &fakeDBClient{}\n}\n\nfunc (dc *fakeDBClient) DBName() string {\n\treturn \"db\"\n}\n\n\n\nfunc (dc *fakeDBClient) Begin() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Commit() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Rollback() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Close() {\n}\n\nfunc (dc *fakeDBClient) ExecuteFetch(query string, maxrows int) (qr *sqltypes.Result, err error) {\n\tquery = strings.ToLower(query)\n\tswitch {\n\tcase strings.HasPrefix(query, \"insert\"):\n\t\treturn &sqltypes.Result{InsertID: 1}, nil\n\tcase strings.HasPrefix(query, \"update\"):\n\t\treturn &sqltypes.Result{RowsAffected: 1}, nil\n\tcase strings.HasPrefix(query, \"delete\"):\n\t\treturn &sqltypes.Result{RowsAffected: 1}, nil\n\tcase strings.HasPrefix(query, \"select\"):\n\t\tif strings.Contains(query, \"where\") {\n\t\t\treturn sqltypes.MakeTestResult(\n\t\t\t\tsqltypes.MakeTestFields(\n\t\t\t\t\t\"id|state|source\",\n\t\t\t\t\t\"int64|varchar|varchar\",\n\t\t\t\t),\n\t\t\t\t`1|Running|keyspace:\"ks\" shard:\"0\" key_range: `,\n\t\t\t), nil\n\t\t}\n\t\treturn &sqltypes.Result{}, nil\n\tcase strings.HasPrefix(query, \"use\"):\n\t\treturn &sqltypes.Result{}, nil\n\t}\n\treturn nil, fmt.Errorf(\"unexpected: %v\", query)\n}\n\nfunc (dc *fakeDBClient) Connect() error ", "output": "{\n\treturn nil\n}"} {"input": "package common\n\nimport \"math/big\"\n\ntype _N_ [_S_]byte\n\n\nfunc StringTo_N_(s string) _N_ { return BytesTo_N_([]byte(s)) }\nfunc BigTo_N_(b *big.Int) _N_ { return BytesTo_N_(b.Bytes()) }\nfunc HexTo_N_(s string) _N_ { return BytesTo_N_(FromHex(s)) }\n\n\n\n\nfunc (h _N_) Str() string { return string(h[:]) }\nfunc (h _N_) Bytes() []byte { return h[:] }\nfunc (h _N_) Big() *big.Int { return Bytes2Big(h[:]) }\nfunc (h _N_) Hex() string { return \"0x\" + Bytes2Hex(h[:]) }\n\n\nfunc (h *_N_) SetBytes(b []byte) {\n\tif len(b) > len(h) {\n\t\tb = b[len(b)-_S_:]\n\t}\n\n\tfor i := len(b) - 1; i >= 0; i-- {\n\t\th[_S_-len(b)+i] = b[i]\n\t}\n}\n\n\nfunc (h *_N_) SetString(s string) { h.SetBytes([]byte(s)) }\n\n\nfunc (h *_N_) Set(other _N_) {\n\tfor i, v := range other {\n\t\th[i] = v\n\t}\n}\n\nfunc BytesTo_N_(b []byte) _N_ ", "output": "{\n\tvar h _N_\n\th.SetBytes(b)\n\treturn h\n}"} {"input": "package viewhelpers\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestDict(t *testing.T) ", "output": "{\n\tval1 := \"value1\"\n\tval2 := []string{\"some\", \"values\"}\n\tdict, err := Dict(\"key1\", \"value1\", \"key2\", val2)\n\n\tassert.Nil(t, err)\n\n\tgot, _ := dict[\"key1\"]\n\tassert.Equal(t, val1, got)\n\n\tgot, _ = dict[\"key2\"]\n\tassert.Equal(t, val2, got)\n}"} {"input": "package header\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/google/martian/v3/proxyutil\"\n)\n\n\n\ntype Matcher struct {\n\tname, value string\n}\n\n\nfunc NewMatcher(name, value string) *Matcher {\n\treturn &Matcher{\n\t\tname: name,\n\t\tvalue: value,\n\t}\n}\n\n\n\n\nfunc (m *Matcher) MatchRequest(req *http.Request) bool {\n\th := proxyutil.RequestHeader(req)\n\n\tvs, ok := h.All(m.name)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tfor _, v := range vs {\n\t\tif v == m.value {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\n\n\n\n\nfunc (m *Matcher) MatchResponse(res *http.Response) bool ", "output": "{\n\th := proxyutil.ResponseHeader(res)\n\n\tvs, ok := h.All(m.name)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tfor _, v := range vs {\n\t\tif v == m.value {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/chai2010/gettext-go/gettext\"\n\n\t\"github.com/lxc/lxd\"\n\t\"github.com/lxc/lxd/shared\"\n)\n\ntype deleteCmd struct{}\n\nfunc (c *deleteCmd) showByDefault() bool {\n\treturn true\n}\n\n\n\nfunc (c *deleteCmd) flags() {}\n\nfunc doDelete(d *lxd.Client, name string) error {\n\tresp, err := d.Delete(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn d.WaitForSuccess(resp.Operation)\n}\n\nfunc (c *deleteCmd) run(config *lxd.Config, args []string) error {\n\tif len(args) == 0 {\n\t\treturn errArgs\n\t}\n\n\tfor _, nameArg := range args {\n\t\tremote, name := config.ParseRemoteAndContainer(nameArg)\n\n\t\td, err := lxd.NewClient(config, remote)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tct, err := d.ContainerStatus(name)\n\n\t\tif err != nil {\n\t\t\treturn doDelete(d, name)\n\t\t}\n\n\t\tif ct.Status.StatusCode != shared.Stopped {\n\t\t\tresp, err := d.Action(name, shared.Stop, -1, true)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\top, err := d.WaitFor(resp.Operation)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif op.StatusCode == shared.Failure {\n\t\t\t\treturn fmt.Errorf(gettext.Gettext(\"Stopping container failed!\"))\n\t\t\t}\n\n\t\t\tif ct.Ephemeral == true {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\tif err := doDelete(d, name); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n\n}\n\nfunc (c *deleteCmd) usage() string ", "output": "{\n\treturn gettext.Gettext(\n\t\t`Delete containers or container snapshots.\n\nlxc delete [remote:][/] [remote:][[/]...]\n\nDestroy containers or snapshots with any attached data (configuration, snapshots, ...).`)\n}"} {"input": "package daemon\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst PatchConfigOKCode int = 200\n\n\ntype PatchConfigOK struct {\n}\n\n\nfunc NewPatchConfigOK() *PatchConfigOK {\n\n\treturn &PatchConfigOK{}\n}\n\n\nfunc (o *PatchConfigOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(200)\n}\n\n\nconst PatchConfigBadRequestCode int = 400\n\n\ntype PatchConfigBadRequest struct {\n\n\tPayload models.Error `json:\"body,omitempty\"`\n}\n\n\nfunc NewPatchConfigBadRequest() *PatchConfigBadRequest {\n\n\treturn &PatchConfigBadRequest{}\n}\n\n\nfunc (o *PatchConfigBadRequest) WithPayload(payload models.Error) *PatchConfigBadRequest {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *PatchConfigBadRequest) SetPayload(payload models.Error) {\n\to.Payload = payload\n}\n\n\nfunc (o *PatchConfigBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(400)\n\tpayload := o.Payload\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) \n\t}\n}\n\n\nconst PatchConfigFailureCode int = 500\n\n\ntype PatchConfigFailure struct {\n\n\tPayload models.Error `json:\"body,omitempty\"`\n}\n\n\nfunc NewPatchConfigFailure() *PatchConfigFailure {\n\n\treturn &PatchConfigFailure{}\n}\n\n\nfunc (o *PatchConfigFailure) WithPayload(payload models.Error) *PatchConfigFailure {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *PatchConfigFailure) SetPayload(payload models.Error) {\n\to.Payload = payload\n}\n\n\n\n\nfunc (o *PatchConfigFailure) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\trw.WriteHeader(500)\n\tpayload := o.Payload\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) \n\t}\n}"} {"input": "package lex\n\nconst (\n\tLogicalTypeAnd LogicType = 1\n\tLogicalTypeOr LogicType = 0\n)\n\n\n\n\nfunc (l *LogicType) String() string ", "output": "{\n\tif *l == LogicalTypeAnd {\n\t\treturn \"&&\"\n\t}\n\n\treturn \"||\"\n}"} {"input": "package validator\n\nimport (\n\t\"github.com/vektah/gqlparser/ast\"\n\t. \"github.com/vektah/gqlparser/validator\"\n)\n\n\n\nfunc init() ", "output": "{\n\tAddRule(\"UniqueVariableNames\", func(observers *Events, addError AddErrFunc) {\n\t\tobservers.OnOperation(func(walker *Walker, operation *ast.OperationDefinition) {\n\t\t\tseen := map[string]bool{}\n\t\t\tfor _, def := range operation.VariableDefinitions {\n\t\t\t\tif seen[def.Variable] {\n\t\t\t\t\taddError(\n\t\t\t\t\t\tMessage(`There can be only one variable named \"%s\".`, def.Variable),\n\t\t\t\t\t\tAt(def.Position),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tseen[def.Variable] = true\n\t\t\t}\n\t\t})\n\t})\n}"} {"input": "package readers\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n)\n\nfunc init() {\n\tRegister(\"IOStat\", NewIOStat)\n}\n\nfunc NewIOStat() IReader {\n\tios := &IOStat{}\n\tios.Data = make(map[string]interface{})\n\treturn ios\n}\n\ntype IOStat struct {\n\tData map[string]interface{}\n}\n\n\nfunc (ios *IOStat) Run() error {\n\treturn errors.New(\"iostat -x is only available on Linux.\")\n}\n\n\n\n\nfunc (ios *IOStat) ToJson() ([]byte, error) ", "output": "{\n\treturn json.Marshal(ios.Data)\n}"} {"input": "package payload\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hyperledger/burrow/acm/acmstate\"\n\t\"github.com/hyperledger/burrow/crypto\"\n)\n\nfunc NewBondTx(address crypto.Address, amount uint64) *BondTx {\n\treturn &BondTx{\n\t\tInput: &TxInput{\n\t\t\tAddress: address,\n\t\t\tAmount: amount,\n\t\t},\n\t}\n}\n\nfunc (tx *BondTx) Type() Type {\n\treturn TypeBond\n}\n\n\n\nfunc (tx *BondTx) String() string {\n\treturn fmt.Sprintf(\"BondTx{%v}\", tx.Input)\n}\n\nfunc (tx *BondTx) AddInput(st acmstate.AccountGetter, pubkey *crypto.PublicKey, amt uint64) error {\n\taddr := pubkey.GetAddress()\n\tacc, err := st.GetAccount(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif acc == nil {\n\t\treturn fmt.Errorf(\"invalid address %s from pubkey %s\", addr, pubkey)\n\t}\n\treturn tx.AddInputWithSequence(pubkey, amt, acc.Sequence+uint64(1))\n}\n\nfunc (tx *BondTx) AddInputWithSequence(pubkey *crypto.PublicKey, amt uint64, sequence uint64) error {\n\ttx.Input = &TxInput{\n\t\tAddress: pubkey.GetAddress(),\n\t\tAmount: amt,\n\t\tSequence: sequence,\n\t}\n\treturn nil\n}\n\nfunc (tx *BondTx) Any() *Any {\n\treturn &Any{\n\t\tBondTx: tx,\n\t}\n}\n\nfunc (tx *BondTx) GetInputs() []*TxInput ", "output": "{\n\treturn []*TxInput{tx.Input}\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n)\n\nvar cfgFile string\n\n\nvar RootCmd = &cobra.Command{\n\tUse: \"docktor\",\n\tShort: \"Administration & Monitoring Deployment with Docker\",\n\tLong: `Docktor is a web application which aims to make the deployment of docke services easier\nWith it, you can manage several daemons, services and group.\nEach service can be deployed on a daemon for a group.\n\t`,\n}\n\nconst (\n\tconfigPath = \"$HOME\"\n\tconfigFile = \".docktor\"\n\tprefixForEnvVariables = \"docktor\"\n)\n\n\n\nfunc Execute() {\n\tif err := RootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}\n\n\n\n\nfunc initConfig() {\n\tif cfgFile != \"\" { \n\t\tviper.SetConfigFile(cfgFile)\n\t}\n\n\tviper.SetEnvPrefix(prefixForEnvVariables) \n\tviper.SetConfigName(configFile) \n\tviper.AddConfigPath(configPath) \n\tviper.AutomaticEnv() \n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\", \"-\", \"_\")) \n\n\terr := viper.ReadInConfig()\n\tif err == nil {\n\t\tfmt.Println(\"Using config file:\" + viper.ConfigFileUsed())\n\t} else {\n\t\tfmt.Println(\"Cant read config file:\" + viper.ConfigFileUsed())\n\t}\n}\n\nfunc init() ", "output": "{\n\tcobra.OnInitialize(initConfig)\n\tRootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is $HOME/.docktor.yaml)\")\n}"} {"input": "package configmap\n\nimport (\n\t\"context\"\n\n\tcorev1 \"k8s.io/client-go/informers/core/v1\"\n\n\t\"github.com/knative/pkg/controller\"\n\t\"github.com/knative/pkg/injection\"\n\t\"github.com/knative/pkg/injection/informers/kubeinformers/factory\"\n\t\"github.com/knative/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Default.RegisterInformer(withInformer)\n}\n\n\n\ntype Key struct{}\n\n\n\n\nfunc Get(ctx context.Context) corev1.ConfigMapInformer {\n\tuntyped := ctx.Value(Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panicf(\n\t\t\t\"Unable to fetch %T from context.\", (corev1.ConfigMapInformer)(nil))\n\t}\n\treturn untyped.(corev1.ConfigMapInformer)\n}\n\nfunc withInformer(ctx context.Context) (context.Context, controller.Informer) ", "output": "{\n\tf := factory.Get(ctx)\n\tinf := f.Core().V1().ConfigMaps()\n\treturn context.WithValue(ctx, Key{}, inf), inf.Informer()\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSOpsWorksApp_Source struct {\n\n\tPassword string `json:\"Password,omitempty\"`\n\n\tRevision string `json:\"Revision,omitempty\"`\n\n\tSshKey string `json:\"SshKey,omitempty\"`\n\n\tType string `json:\"Type,omitempty\"`\n\n\tUrl string `json:\"Url,omitempty\"`\n\n\tUsername string `json:\"Username,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSOpsWorksApp_Source) AWSCloudFormationType() string {\n\treturn \"AWS::OpsWorks::App.Source\"\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetDeletionPolicy(policy policies.DeletionPolicy) ", "output": "{\n\tr._deletionPolicy = policy\n}"} {"input": "package gosseract\n\nimport \"fmt\"\nimport \"os\"\nimport \"os/exec\"\nimport \"bytes\"\nimport \"io/ioutil\"\n\ntype tesseract0303 struct {\n\tversion string\n\tresultFilePath string\n\tcommandPath string\n}\n\nfunc (t tesseract0303) Version() string {\n\treturn t.version\n}\n\n\n\nfunc (t tesseract0303) readResult() (res string, e error) {\n\tfpath := t.resultFilePath + outFILEEXTENSION\n\tfile, e := os.OpenFile(fpath, 1, 1)\n\tif e != nil {\n\t\treturn\n\t}\n\tbuffer, _ := ioutil.ReadFile(file.Name())\n\tres = string(buffer)\n\tos.Remove(file.Name())\n\treturn\n}\n\nfunc (t tesseract0303) Execute(params []string) (res string, e error) ", "output": "{\n\tvar args []string\n\targs = append(args, params[0])\n\tt.resultFilePath, e = generateTmpFile()\n\tif e != nil {\n\t\treturn\n\t}\n\targs = append(args, t.resultFilePath)\n\tif len(params) > 1 {\n\t\targs = append(args, params[1])\n\t}\n\n\tcmd := exec.Command(TESSERACT, args...)\n\tvar stderr bytes.Buffer\n\tcmd.Stderr = &stderr\n\tif e = cmd.Run(); e != nil {\n\t\te = fmt.Errorf(stderr.String())\n\t\treturn\n\t}\n\tres, e = t.readResult()\n\treturn\n}"} {"input": "package arangolite\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"net/http\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc longRequest(w http.ResponseWriter, r *http.Request) {\n\tio.WriteString(w, \"Waiting 2 seconds...\")\n\ttime.Sleep(200 * time.Millisecond)\n\tpanic(\"The request was not canceled\")\n}\n\nfunc runWebserver() {\n\tgo func() {\n\t\thttp.HandleFunc(\"/\", longRequest)\n\t\thttp.ListenAndServe(\":9999\", nil)\n\t}()\n}\n\n\n\nfunc TestSendCanBeCanceled(t *testing.T) ", "output": "{\n\trunWebserver()\n\n\tclient := &http.Client{}\n\treq, _ := http.NewRequest(\"GET\", \"http://localhost:9999\", nil)\n\n\tsender := basicSender{}\n\tparent := context.Background()\n\tctx, cancel := context.WithTimeout(parent, 100*time.Millisecond)\n\tdefer cancel()\n\n\tresp, err := sender.Send(ctx, client, req)\n\n\tassertEqual(t, err.Error(), \"the database HTTP request failed: Get http://localhost:9999: context deadline exceeded\")\n\tassertTrue(t, resp == nil, \"The response of a canceled request should be nil\")\n}"} {"input": "package docker\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/containers/image/image\"\n\t\"github.com/containers/image/types\"\n\t\"github.com/pkg/errors\"\n)\n\n\n\ntype Image struct {\n\ttypes.Image\n\tsrc *dockerImageSource\n}\n\n\n\n\n\n\n\nfunc (i *Image) SourceRefFullName() string {\n\treturn i.src.ref.ref.FullName()\n}\n\n\nfunc (i *Image) GetRepositoryTags() ([]string, error) {\n\turl := fmt.Sprintf(tagsURL, i.src.ref.ref.RemoteName())\n\tres, err := i.src.c.makeRequest(\"GET\", url, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != http.StatusOK {\n\t\treturn nil, errors.Errorf(\"Invalid status code returned when fetching tags list %d\", res.StatusCode)\n\t}\n\ttype tagsRes struct {\n\t\tTags []string\n\t}\n\ttags := &tagsRes{}\n\tif err := json.NewDecoder(res.Body).Decode(tags); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tags.Tags, nil\n}\n\nfunc newImage(ctx *types.SystemContext, ref dockerReference) (types.Image, error) ", "output": "{\n\ts, err := newImageSource(ctx, ref, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\timg, err := image.FromSource(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Image{Image: img, src: s}, nil\n}"} {"input": "package v2store_test\n\nimport (\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"github.com/coreos/etcd/clientv3\"\n\t\"github.com/coreos/etcd/etcdserver/api/v2v3\"\n\t\"github.com/coreos/etcd/etcdserver/v2store\"\n\t\"github.com/coreos/etcd/integration\"\n\n\t\"github.com/coreos/pkg/capnslog\"\n\t\"google.golang.org/grpc/grpclog\"\n)\n\n\n\ntype v2v3TestStore struct {\n\tv2store.Store\n\tclus *integration.ClusterV3\n\tt *testing.T\n}\n\nfunc (s *v2v3TestStore) Close() { s.clus.Terminate(s.t) }\n\nfunc newTestStore(t *testing.T, ns ...string) StoreCloser {\n\tclus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})\n\treturn &v2v3TestStore{\n\t\tv2v3.NewStore(clus.Client(0), \"/v2/\"),\n\t\tclus,\n\t\tt,\n\t}\n}\n\nfunc init() ", "output": "{\n\tcapnslog.SetGlobalLogLevel(capnslog.CRITICAL)\n\tclientv3.SetLogger(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, ioutil.Discard))\n}"} {"input": "package command\n\nimport (\n\t\"github.com/cisco/elsy/helpers\"\n\t\"github.com/codegangsta/cli\"\n)\n\n\n\nfunc CmdDockerCompose(c *cli.Context) error ", "output": "{\n\treturn helpers.RunCommand(helpers.DockerComposeCommand(c.Args()...))\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\n\n\nfunc Upload(data io.Reader, url string) error ", "output": "{\n\tclient := &http.Client{\n\t\tTimeout: 1 * time.Minute,\n\t}\n\n\treq, err := http.NewRequest(http.MethodPut, url, data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"upload request failed\")\n\t}\n\n\tif _, err = io.Copy(ioutil.Discard, res.Body); err != nil {\n\t\treturn err\n\t}\n\tif err := res.Body.Close(); err != nil {\n\t\treturn err\n\t}\n\n\tif res.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"received unexpected status %v\", res.StatusCode)\n\t}\n\n\treturn nil\n}"} {"input": "package sha512\n\nimport \"crypto/sha512\"\n\nconst (\n\tSize = 64\n\n\tSize224 = 28\n\n\tSize256 = 32\n\n\tSize384 = 48\n\n\tBlockSize = 128\n)\n\n\nfunc Sum512(data []byte) []byte {\n\ta := sha512.Sum512(data)\n\treturn a[:]\n}\n\n\nfunc Sum384(data []byte) (sum384 []byte) {\n\ta := sha512.Sum384(data)\n\treturn a[:]\n}\n\n\n\n\n\nfunc Sum512_256(data []byte) (sum256 []byte) {\n\ta := sha512.Sum512_256(data)\n\treturn a[:]\n}\n\nfunc Sum512_224(data []byte) (sum224 []byte) ", "output": "{\n\ta := sha512.Sum512_224(data)\n\treturn a[:]\n}"} {"input": "package libbuildpack\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\nconst (\n\tenvPathSeparator = \";\"\n\tdepsDirEnvVar = \"%DEPS_DIR%\"\n\tscriptName = \"000_multi-supply.bat\"\n\tscriptLineTemplate = `set %[1]s=%[2]s;%%%[1]s%%`\n)\n\nvar stagingEnvVarDirs = map[string]string{\n\t\"PATH\": \"bin\",\n}\n\nvar launchEnvVarDirs = map[string]string{\n\t\"PATH\": \"bin\",\n}\n\n\n\nfunc (s *Stager) AddBinDependencyLink(destPath, sourceName string) error ", "output": "{\n\tbinDir := filepath.Join(s.DepDir(), \"bin\")\n\n\tif err := os.MkdirAll(binDir, 0755); err != nil {\n\t\treturn err\n\t}\n\n\treturn os.Link(destPath, filepath.Join(binDir, sourceName))\n}"} {"input": "package assert\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"runtime\"\n)\n\nconst windows = runtime.GOOS == \"windows\"\n\n\n\n\n\ntype MatchPath string\n\nfunc isSlash(c byte) bool { return c == '\\\\' || c == '/' }\n\nfunc (m MatchPath) isAbs(path string) bool {\n\treturn filepath.IsAbs(path) || (windows && len(path) != 0 && isSlash(path[0]))\n}\n\nfunc (m MatchPath) cleanPath(s string) string {\n\tif !windows || !m.isAbs(s) {\n\t\treturn s\n\t}\n\ta, err := filepath.Abs(s)\n\tif err != nil {\n\t\treturn s\n\t}\n\treturn a\n}\n\nfunc (m MatchPath) Match(actual interface{}) (bool, error) {\n\tpath, ok := actual.(string)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"MatchPath: expects a string got: %T\", actual)\n\t}\n\tif path == string(m) || (filepath.Clean(path) == filepath.Clean(string(m))) {\n\t\treturn true, nil\n\t}\n\treturn m.cleanPath(path) == m.cleanPath(string(m)), nil\n}\n\n\n\nfunc (m MatchPath) NegatedFailureMessage(actual interface{}) string {\n\tif windows {\n\t\tif s, ok := actual.(string); ok {\n\t\t\treturn fmt.Sprintf(\"Expected\\n\\t%v\\n\\t%v (clean)\\nnot to match file\\n\\t%v\\n\\t%v (clean)\",\n\t\t\t\tactual, m.cleanPath(s), m, m.cleanPath(string(m)))\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"Expected\\n\\t%v\\nnot to match file\\n\\t%v\", actual, m)\n}\n\nfunc (m MatchPath) FailureMessage(actual interface{}) string ", "output": "{\n\tif windows {\n\t\tif s, ok := actual.(string); ok {\n\t\t\treturn fmt.Sprintf(\"Expected\\n\\t%v\\n\\t%v (clean)\\nto match file\\n\\t%v\\n\\t%v (clean)\",\n\t\t\t\tactual, m.cleanPath(s), m, m.cleanPath(string(m)))\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"Expected\\n\\t%v\\nto match file\\n\\t%v\", actual, m)\n}"} {"input": "package wca\n\nimport (\n\t\"unsafe\"\n)\n\n\n\n\ntype IAudioClient2 struct {\n\tIAudioClient\n}\n\ntype IAudioClient2Vtbl struct {\n\tIAudioClientVtbl\n\tIsOffloadCapable uintptr\n\tSetClientProperties uintptr\n\tGetBufferSizeLimits uintptr\n}\n\nfunc (v *IAudioClient2) VTable() *IAudioClient2Vtbl {\n\treturn (*IAudioClient2Vtbl)(unsafe.Pointer(v.RawVTable))\n}\n\n\n\nfunc (v *IAudioClient2) SetClientProperties(properties *AudioClientProperties) (err error) {\n\terr = ac2SetClientProperties(v, properties)\n\treturn\n}\n\nfunc (v *IAudioClient2) GetBufferSizeLimits(wfx *WAVEFORMATEX, isEventDriven bool, minBufferDuration, maxBufferDuration *uint32) (err error) {\n\terr = ac2GetBufferSizeLimits(v, wfx, isEventDriven, minBufferDuration, maxBufferDuration)\n\treturn\n}\n\nfunc (v *IAudioClient2) IsOffloadCapable(category uint32, isOffloadCapable *bool) (err error) ", "output": "{\n\terr = ac2IsOffloadCapable(v, category, isOffloadCapable)\n\treturn\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\n\n\ntype RdmaProtocol string\n\nconst (\n\n\tRdmaProtocolRoce RdmaProtocol = \"roce\"\n)\n\n\nvar rdmaProtocolEnum []interface{}\n\n\n\nfunc (m RdmaProtocol) validateRdmaProtocolEnum(path, location string, value RdmaProtocol) error {\n\tif err := validate.EnumCase(path, location, value, rdmaProtocolEnum, true); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\nfunc (m RdmaProtocol) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateRdmaProtocolEnum(\"\", \"body\", m); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\nfunc (m RdmaProtocol) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tvar res []RdmaProtocol\n\tif err := json.Unmarshal([]byte(`[\"roce\"]`), &res); err != nil {\n\t\tpanic(err)\n\t}\n\tfor _, v := range res {\n\t\trdmaProtocolEnum = append(rdmaProtocolEnum, v)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/lxc/lxd/lxd/cluster\"\n\t\"github.com/lxc/lxd/lxd/db\"\n\t\"github.com/lxc/lxd/lxd/node\"\n\t\"github.com/lxc/lxd/lxd/state\"\n\t\"github.com/lxc/lxd/shared\"\n)\n\nfunc daemonConfigRender(state *state.State) (map[string]interface{}, error) {\n\tconfig := map[string]interface{}{}\n\n\terr := state.Cluster.Transaction(func(tx *db.ClusterTx) error {\n\t\tclusterConfig, err := cluster.ConfigLoad(tx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor key, value := range clusterConfig.Dump() {\n\t\t\tconfig[key] = value\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = state.Node.Transaction(func(tx *db.NodeTx) error {\n\t\tnodeConfig, err := node.ConfigLoad(tx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor key, value := range nodeConfig.Dump() {\n\t\t\tconfig[key] = value\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn config, nil\n}\n\n\n\nfunc daemonConfigSetProxy(d *Daemon, config *cluster.Config) ", "output": "{\n\td.proxy = shared.ProxyFromConfig(\n\t\tconfig.ProxyHTTPS(),\n\t\tconfig.ProxyHTTP(),\n\t\tconfig.ProxyIgnoreHosts(),\n\t)\n\n\timageStreamCacheLock.Lock()\n\tfor k := range imageStreamCache {\n\t\tdelete(imageStreamCache, k)\n\t}\n\timageStreamCacheLock.Unlock()\n}"} {"input": "package tcp\n\nimport (\n\t\"flag\"\n\t\"net\"\n\t\"os\"\n\t\"bufio\"\n\t\"time\"\n\t\"log\"\n)\n\nfunc DefaultServer() {\n\n\tvar address = flag.String(\"address\", \":6789\", \"server address host:port\")\n\tflag.Parse()\n\n\tlistener, err := net.Listen(\"tcp4\", *address)\n\tif err != nil {\n\t\tlog.Println(\"Error listening:\", err)\n\t\tos.Exit(1)\n\t}\n\n\tdefer listener.Close()\n\n\tlog.Println(\"Listening on \" + *address)\n\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error accepting: \", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tlog.Printf(\"Received message %s -> %s \\n\", conn.RemoteAddr(), conn.LocalAddr())\n\t\tgo readFromClient(conn)\n\t}\n}\nfunc readFromClient(conn net.Conn) {\n\treader := bufio.NewReader(conn)\n\tfor {\n\t\tlog.Println(\"receiving...\")\n\t\tline, isPrefix, err := reader.ReadLine()\n\t\tif err != nil {\n\t\t\tlog.Print(\"Error to read message because of \", err)\n\t\t\treturn\n\t\t} else {\n\t\t\tlog.Println(\"receive:\", string(line))\n\t\t\tlog.Println(\"isPrefix:\", isPrefix)\n\t\t}\n\n\t}\n}\n\n\nfunc writeToClient(conn net.Conn) ", "output": "{\n\tdefer conn.Close()\n\tfor {\n\t\t_, err := conn.Write([]byte(\"hello client.\\r\\n\"))\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error to send message because of \", err.Error())\n\t\t\treturn\n\t\t}\n\t\tlog.Println(\"sent hello to client.\")\n\t\ttime.Sleep(time.Second)\n\t}\n\n}"} {"input": "package cmd\n\nimport (\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n\n\tboshdir \"github.com/cloudfoundry/bosh-init/director\"\n\tboshtpl \"github.com/cloudfoundry/bosh-init/director/template\"\n\tboshui \"github.com/cloudfoundry/bosh-init/ui\"\n)\n\ntype UpdateRuntimeConfigCmd struct {\n\tui boshui.UI\n\tdirector boshdir.Director\n}\n\nfunc NewUpdateRuntimeConfigCmd(ui boshui.UI, director boshdir.Director) UpdateRuntimeConfigCmd {\n\treturn UpdateRuntimeConfigCmd{ui: ui, director: director}\n}\n\n\n\nfunc (c UpdateRuntimeConfigCmd) Run(opts UpdateRuntimeConfigOpts) error ", "output": "{\n\ttpl := boshtpl.NewTemplate(opts.Args.RuntimeConfig.Bytes)\n\n\tbytes, err := tpl.Evaluate(opts.VarFlags.AsVariables())\n\tif err != nil {\n\t\treturn bosherr.WrapErrorf(err, \"Evaluating runtime config\")\n\t}\n\n\terr = c.ui.AskForConfirmation()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.director.UpdateRuntimeConfig(bytes)\n}"} {"input": "package auth\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/concourse/atc\"\n\n\t\"golang.org/x/crypto/bcrypt\"\n)\n\ntype BasicAuthValidator struct {\n\tDB AuthDB\n}\n\n\n\nfunc (validator BasicAuthValidator) IsAuthenticated(r *http.Request) bool {\n\tauth := r.Header.Get(\"Authorization\")\n\n\tusername, password, err := extractUsernameAndPassword(auth)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tteam, found, err := validator.DB.GetTeamByName(atc.DefaultTeamName)\n\tif err != nil || !found {\n\t\treturn false\n\t}\n\n\treturn validator.correctCredentials(\n\t\tteam.BasicAuthUsername, team.BasicAuthPassword,\n\t\tusername, password,\n\t)\n}\n\n\n\nfunc (validator BasicAuthValidator) correctCredentials(\n\tteamUsername string, teamPassword string,\n\tcheckUsername string, checkPassword string,\n) bool ", "output": "{\n\terr := bcrypt.CompareHashAndPassword([]byte(teamPassword), []byte(checkPassword))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn teamUsername == checkUsername\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/russmack/statemachiner\"\n)\n\n\nfunc main() {\n\ts := statemachiner.NewStateMachine()\n\ts.StartState = dispenseDogBiscuits\n\tc := NewHome()\n\ts.Start(c)\n}\n\n\ntype Home struct {\n\tDispenseDogBiscuits int `json:\"dispense_dog_biscuits\"`\n\tTotalDogBiscuits int `json:\"dog_biscuits\"`\n\tLights bool `json:\"lights\"`\n\tKettle bool `json:\"kettle\"`\n\tVacuumRoom string `json:\"vacuum_room\"`\n}\n\n\nfunc NewHome() *Home {\n\treturn &Home{}\n}\n\n\n\n\n\n\nfunc lights(cargo interface{}) statemachiner.StateFn {\n\tcargo.(*Home).Lights = true\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn kettle\n}\n\n\nfunc kettle(cargo interface{}) statemachiner.StateFn {\n\tcargo.(*Home).Kettle = true\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn vacuumRoom\n}\n\n\nfunc vacuumRoom(cargo interface{}) statemachiner.StateFn {\n\tif cargo.(*Home).TotalDogBiscuits < 20 {\n\t\treturn dispenseDogBiscuits\n\t} else {\n\t\tcargo.(*Home).VacuumRoom = \"kitchen\"\n\t}\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn nil\n}\n\nfunc dispenseDogBiscuits(cargo interface{}) statemachiner.StateFn ", "output": "{\n\tcargo.(*Home).DispenseDogBiscuits = 10\n\tcargo.(*Home).TotalDogBiscuits += cargo.(*Home).DispenseDogBiscuits\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn lights\n}"} {"input": "package blake2b\n\nimport \"golang.org/x/sys/cpu\"\n\nfunc init() {\n\tuseAVX2 = cpu.X86.HasAVX2\n\tuseAVX = cpu.X86.HasAVX\n\tuseSSE4 = cpu.X86.HasSSE41\n}\n\n\nfunc hashBlocksAVX2(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte)\n\n\nfunc hashBlocksAVX(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte)\n\n\nfunc hashBlocksSSE4(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte)\n\n\n\nfunc hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) ", "output": "{\n\tswitch {\n\tcase useAVX2:\n\t\thashBlocksAVX2(h, c, flag, blocks)\n\tcase useAVX:\n\t\thashBlocksAVX(h, c, flag, blocks)\n\tcase useSSE4:\n\t\thashBlocksSSE4(h, c, flag, blocks)\n\tdefault:\n\t\thashBlocksGeneric(h, c, flag, blocks)\n\t}\n}"} {"input": "package format\n\nimport (\n\t\"github.com/kitwalker12/fotomat/vips\"\n)\n\n\ntype Metadata struct {\n\tWidth int\n\tHeight int\n\tFormat Format\n\tOrientation Orientation\n\tHasAlpha bool\n}\n\n\nfunc MetadataBytes(blob []byte) (Metadata, error) {\n\tformat := DetectFormat(blob)\n\tif format == Unknown {\n\t\treturn Metadata{}, ErrUnknownFormat\n\t}\n\n\treturn format.MetadataBytes(blob)\n}\n\n\nfunc (format Format) MetadataBytes(blob []byte) (Metadata, error) {\n\timage, err := format.LoadBytes(blob)\n\tif err != nil {\n\t\treturn Metadata{}, ErrUnknownFormat\n\t}\n\n\tdefer image.Close()\n\n\treturn metadataImageFormat(image, format), nil\n}\n\n\nfunc (format Format) MetadataFile(filename string) (Metadata, error) {\n\timage, err := format.LoadFile(filename)\n\tif err != nil {\n\t\treturn Metadata{}, err\n\t}\n\n\tdefer image.Close()\n\n\treturn metadataImageFormat(image, format), nil\n}\n\n\n\n\nfunc MetadataImage(image *vips.Image) Metadata {\n\to := DetectOrientation(image)\n\tw, h := o.Dimensions(image.Xsize(), image.Ysize())\n\tif w <= 0 || h <= 0 {\n\t\tpanic(\"Invalid image dimensions.\")\n\t}\n\treturn Metadata{Width: w, Height: h, Orientation: o, HasAlpha: image.HasAlpha()}\n}\n\nfunc metadataImageFormat(image *vips.Image, format Format) Metadata ", "output": "{\n\tm := MetadataImage(image)\n\tm.Format = format\n\treturn m\n}"} {"input": "package semver\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/blang/semver\"\n\t\"github.com/pivotal-cf/go-pivnet/v7/logger\"\n)\n\ntype SemverConverter struct {\n\tlogger logger.Logger\n}\n\n\n\n\n\n\nfunc (s SemverConverter) ToValidSemver(input string) (semver.Version, error) {\n\tv, err := semver.Parse(input)\n\tif err == nil {\n\t\treturn v, nil\n\t}\n\n\ts.logger.Info(fmt.Sprintf(\n\t\t\"failed to parse semver: '%s', appending zeros and trying again\",\n\t\tinput,\n\t))\n\tmaybeSemver := input\n\n\tsegs := strings.SplitN(maybeSemver, \".\", 3)\n\tswitch len(segs) {\n\tcase 2:\n\t\tmaybeSemver += \".0\"\n\tcase 1:\n\t\tmaybeSemver += \".0.0\"\n\t}\n\n\tv, err = semver.Parse(maybeSemver)\n\tif err == nil {\n\t\treturn v, nil\n\t}\n\n\ts.logger.Info(fmt.Sprintf(\n\t\t\"still failed to parse semver: '%s', giving up\",\n\t\tmaybeSemver,\n\t))\n\n\treturn semver.Version{}, err\n}\n\nfunc NewSemverConverter(logger logger.Logger) *SemverConverter ", "output": "{\n\treturn &SemverConverter{logger}\n}"} {"input": "package token\n\nimport (\n\t\"strings\"\n\n\t\"github.com/carlcui/expressive/locator\"\n)\n\n\ntype Token struct {\n\tTokenType Type\n\tRaw string\n\tLocator locator.Locator\n}\n\nfunc (tok *Token) String() string {\n\treturn tok.TokenType.String() + \": \" + tok.Raw\n}\n\nfunc (tok *Token) GetLocation() string {\n\tif tok.Locator == nil {\n\t\treturn \"unknown location\"\n\t}\n\n\treturn tok.Locator.Locate()\n}\n\n\n\n\n\nfunc EOFToken(locator locator.Locator) *Token {\n\treturn &Token{TokenType: EOF, Raw: \"\", Locator: locator}\n}\n\n\n\nfunc MatchKeyword(reading string) *Token {\n\tif tokenType, isKeyword := keywords[reading]; isKeyword {\n\t\treturn &Token{TokenType: tokenType, Raw: reading}\n\t}\n\n\treturn nil\n}\n\nfunc MatchOperator(reading string) *Token {\n\tif tokenType, isOperator := operators[reading]; isOperator {\n\t\treturn &Token{TokenType: tokenType, Raw: reading}\n\t}\n\n\treturn nil\n}\n\nfunc HasOperatorPrefix(reading string) bool {\n\tfor i := operatorStart + 1; i < operatorEnd; i++ {\n\t\tif strings.HasPrefix(tokens[i], reading) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc IllegalToken(raw string, locator locator.Locator) *Token ", "output": "{\n\treturn &Token{TokenType: ILLEGAL, Raw: raw, Locator: locator}\n}"} {"input": "package framework\n\nimport (\n\t\"k8s.io/kube-openapi/pkg/validation/spec\"\n\t\"sigs.k8s.io/kustomize/kyaml/errors\"\n\t\"sigs.k8s.io/kustomize/kyaml/resid\"\n\tk8syaml \"sigs.k8s.io/yaml\"\n)\n\n\n\n\n\n\nfunc SchemaFromFunctionDefinition(gvk resid.Gvk, data string) (*spec.Schema, error) ", "output": "{\n\tvar def KRMFunctionDefinition\n\tif err := k8syaml.Unmarshal([]byte(data), &def); err != nil {\n\t\treturn nil, errors.WrapPrefixf(err, \"unmarshalling %s\", FunctionDefinitionKind)\n\t}\n\tvar foundGVKs []*resid.Gvk\n\tvar schema *spec.Schema\n\tfor i, version := range def.Spec.Versions {\n\t\tversionGVK := resid.Gvk{Group: def.Spec.Group, Kind: def.Spec.Names.Kind, Version: version.Name}\n\t\tif gvk.Equals(versionGVK) {\n\t\t\tschema = def.Spec.Versions[i].Schema.OpenAPIV3Schema\n\t\t\tbreak\n\t\t}\n\t\tfoundGVKs = append(foundGVKs, &versionGVK)\n\t}\n\tif schema == nil {\n\t\treturn nil, errors.Errorf(\"%s does not define %s (defines: %s)\", FunctionDefinitionKind, gvk, foundGVKs)\n\t}\n\treturn schema, nil\n}"} {"input": "package bot\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"log\"\n)\n\n\ntype Config struct {\n\tAdmin string `json:\"admin\"`\n\tNotifiers map[string][]string `json:\"notifiers\"`\n\tDebug bool `json:\"debug\"`\n}\n\n\nfunc NewConfig() *Config {\n\tcfg := &Config{\n\t\tNotifiers: make(map[string][]string),\n\t}\n\treturn cfg\n}\n\n\n\nfunc (cfg *Config) toJSON(filename string) error {\n\tjsonBytes, err := json.MarshalIndent(cfg, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = ioutil.WriteFile(filename, jsonBytes, 0600); err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Saved config.\")\n\treturn nil\n}\n\nfunc (cfg *Config) fromJSON(filename string) error ", "output": "{\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = json.Unmarshal(file, &cfg); err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Loaded config.\")\n\treturn nil\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/cloudfoundry/cli/cf/terminal\"\n\t\"github.com/onsi/gomega\"\n)\n\ntype SliceMatcher struct {\n\texpected [][]string\n\tfailedAtIndex int\n}\n\nfunc ContainSubstrings(substrings ...[]string) gomega.OmegaMatcher {\n\treturn &SliceMatcher{expected: substrings}\n}\n\nfunc (matcher *SliceMatcher) Match(actual interface{}) (success bool, err error) {\n\tactualStrings, ok := actual.([]string)\n\tif !ok {\n\t\treturn false, nil\n\t}\n\n\tallStringsMatched := make([]bool, len(matcher.expected))\n\n\tfor index, expectedArray := range matcher.expected {\n\t\tfor _, actualValue := range actualStrings {\n\n\t\t\tallStringsFound := true\n\n\t\t\tfor _, expectedValue := range expectedArray {\n\t\t\t\tallStringsFound = allStringsFound && strings.Contains(terminal.Decolorize(actualValue), expectedValue)\n\t\t\t}\n\n\t\t\tif allStringsFound {\n\t\t\t\tallStringsMatched[index] = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tfor index, value := range allStringsMatched {\n\t\tif !value {\n\t\t\tmatcher.failedAtIndex = index\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\treturn true, nil\n}\n\nfunc (matcher *SliceMatcher) FailureMessage(actual interface{}) string {\n\tactualStrings, ok := actual.([]string)\n\tif !ok {\n\t\treturn fmt.Sprintf(\"Expected actual to be a slice of strings, but it's actually a %T\", actual)\n\t}\n\n\treturn fmt.Sprintf(\"expected to find \\\"%s\\\" in actual:\\n'%s'\\n\", matcher.expected[matcher.failedAtIndex], strings.Join(actualStrings, \"\\n\"))\n}\n\n\n\nfunc (matcher *SliceMatcher) NegatedFailureMessage(actual interface{}) string ", "output": "{\n\tactualStrings, ok := actual.([]string)\n\tif !ok {\n\t\treturn fmt.Sprintf(\"Expected actual to be a slice of strings, but it's actually a %T\", actual)\n\t}\n\treturn fmt.Sprintf(\"expected to not find \\\"%s\\\" in actual:\\n'%s'\\n\", matcher.expected[matcher.failedAtIndex], strings.Join(actualStrings, \"\\n\"))\n}"} {"input": "package mdt\n\nimport \"bytes\"\n\ntype rows []row\n\nfunc (r rows) colNum() int {\n\tvar max int\n\tfor _, row := range r {\n\t\tif n := row.colNum(); n > max {\n\t\t\tmax = n\n\t\t}\n\t}\n\treturn max\n}\n\n\n\nfunc (r rows) toMarkdown() string {\n\tcolNum := r.colNum()\n\tlens := []int{}\n\tfor i := 0; i < colNum; i++ {\n\t\tlens = append(lens, r.lengthAt(i))\n\t}\n\n\tvar buf bytes.Buffer\n\tfor _, row := range r {\n\t\tbuf.WriteString(row.toMarkdown(colNum, lens) + \"\\n\")\n\t}\n\treturn buf.String()\n}\n\nfunc (r rows) lengthAt(index int) int ", "output": "{\n\tvar max int\n\tfor _, row := range r {\n\t\tif n := row.lengthAt(index); n > max {\n\t\t\tmax = n\n\t\t}\n\t}\n\tif max < 3 {\n\t\tmax = 3\n\t}\n\treturn max\n}"} {"input": "package day09\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestIsValid(t *testing.T) {\n\tsequence := make([]int, 25)\n\tfor i := 0; i < 25; i++ {\n\t\tsequence[i] = i + 1\n\t}\n\n\trequire.True(t, IsValid(sequence, 26))\n\trequire.True(t, IsValid(sequence, 49))\n\trequire.False(t, IsValid(sequence, 100))\n\trequire.False(t, IsValid(sequence, 50))\n}\n\n\n\nfunc TestFindContiguousSum(t *testing.T) {\n\tsequence := []int{35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576}\n\tstart, end, err := FindContiguousSum(sequence, 127)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 2, start)\n\trequire.Equal(t, 5, end)\n}\n\nfunc TestFindWeakness(t *testing.T) {\n\tsequence := []int{35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576}\n\tvalue, err := FindWeakness(sequence, 127)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 62, value)\n}\n\nfunc TestFirstInvalidValue(t *testing.T) ", "output": "{\n\tsequence := []int{35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576}\n\tvalue, err := FirstInvalidValue(sequence, 5)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 127, value)\n}"} {"input": "package kagome\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\ntype Token struct {\n\tId int\n\tClass NodeClass\n\tStart int\n\tEnd int\n\tSurface string\n\tdic *Dic\n\tudic *UserDic\n}\n\n\n\n\n\nfunc (t Token) String() string {\n\treturn fmt.Sprintf(\"%v(%v, %v)%v[%v]\", t.Surface, t.Start, t.End, t.Class, t.Id)\n}\n\nfunc (t Token) Features() (features []string) ", "output": "{\n\tswitch t.Class {\n\tcase DUMMY:\n\t\treturn\n\tcase KNOWN:\n\t\tfeatures = t.dic.Contents[t.Id]\n\tcase UNKNOWN:\n\t\tfeatures = sysDic.UnkContents[t.Id]\n\tcase USER:\n\t\tpos := t.udic.Contents[t.Id].Pos\n\t\ttokens := strings.Join(t.udic.Contents[t.Id].Tokens, \"/\")\n\t\tyomi := strings.Join(t.udic.Contents[t.Id].Yomi, \"/\")\n\t\tfeatures = append(features, pos, tokens, yomi)\n\t}\n\treturn\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1beta1 \"knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1\"\n)\n\ntype FakeServingV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeServingV1beta1) Configurations(namespace string) v1beta1.ConfigurationInterface {\n\treturn &FakeConfigurations{c, namespace}\n}\n\nfunc (c *FakeServingV1beta1) Revisions(namespace string) v1beta1.RevisionInterface {\n\treturn &FakeRevisions{c, namespace}\n}\n\nfunc (c *FakeServingV1beta1) Routes(namespace string) v1beta1.RouteInterface {\n\treturn &FakeRoutes{c, namespace}\n}\n\nfunc (c *FakeServingV1beta1) Services(namespace string) v1beta1.ServiceInterface {\n\treturn &FakeServices{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeServingV1beta1) RESTClient() rest.Interface ", "output": "{\n\tvar ret *rest.RESTClient\n\treturn ret\n}"} {"input": "package protocol\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\tsyncthingprotocol \"github.com/syncthing/syncthing/lib/protocol\"\n)\n\nconst (\n\tmessageTypePing int32 = iota\n\tmessageTypePong\n\tmessageTypeJoinRelayRequest\n\tmessageTypeJoinSessionRequest\n\tmessageTypeResponse\n\tmessageTypeConnectRequest\n\tmessageTypeSessionInvitation\n)\n\ntype header struct {\n\tmagic uint32\n\tmessageType int32\n\tmessageLength int32\n}\n\ntype Ping struct{}\ntype Pong struct{}\ntype JoinRelayRequest struct{}\n\ntype JoinSessionRequest struct {\n\tKey []byte \n}\n\ntype Response struct {\n\tCode int32\n\tMessage string\n}\n\ntype ConnectRequest struct {\n\tID []byte \n}\n\ntype SessionInvitation struct {\n\tFrom []byte \n\tKey []byte \n\tAddress []byte \n\tPort uint16\n\tServerSocket bool\n}\n\nfunc (i SessionInvitation) String() string {\n\treturn fmt.Sprintf(\"%s@%s\", syncthingprotocol.DeviceIDFromBytes(i.From), i.AddressString())\n}\n\n\n\nfunc (i SessionInvitation) AddressString() string {\n\treturn fmt.Sprintf(\"%s:%d\", net.IP(i.Address), i.Port)\n}\n\nfunc (i SessionInvitation) GoString() string ", "output": "{\n\treturn i.String()\n}"} {"input": "package timekeeper\n\nimport \"time\"\n\n\n\n\n\ntype TimeKeeper interface {\n\tAfter(d time.Duration) <-chan time.Time\n\tSleep(d time.Duration)\n\tNow() time.Time\n}\n\n\ntype realTime struct{}\n\nvar rt realTime\n\n\n\n\n\nfunc (t *realTime) Sleep(d time.Duration) {\n\ttime.Sleep(d)\n}\n\n\nfunc RealTime() TimeKeeper {\n\treturn &rt\n}\n\n\nfunc (t *realTime) Now() time.Time {\n\treturn time.Now()\n}\n\nfunc (t *realTime) After(d time.Duration) <-chan time.Time ", "output": "{\n\treturn time.After(d)\n}"} {"input": "package versioned\n\nimport (\n\t\"fmt\"\n\n\topenebsv1alpha1 \"github.com/openebs/maya/pkg/client/generated/clientset/versioned/typed/openebs.io/v1alpha1\"\n\tdiscovery \"k8s.io/client-go/discovery\"\n\trest \"k8s.io/client-go/rest\"\n\tflowcontrol \"k8s.io/client-go/util/flowcontrol\"\n)\n\ntype Interface interface {\n\tDiscovery() discovery.DiscoveryInterface\n\tOpenebsV1alpha1() openebsv1alpha1.OpenebsV1alpha1Interface\n}\n\n\n\ntype Clientset struct {\n\t*discovery.DiscoveryClient\n\topenebsV1alpha1 *openebsv1alpha1.OpenebsV1alpha1Client\n}\n\n\nfunc (c *Clientset) OpenebsV1alpha1() openebsv1alpha1.OpenebsV1alpha1Interface {\n\treturn c.openebsV1alpha1\n}\n\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.DiscoveryClient\n}\n\n\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *Clientset {\n\tvar cs Clientset\n\tcs.openebsV1alpha1 = openebsv1alpha1.NewForConfigOrDie(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)\n\treturn &cs\n}\n\n\nfunc New(c rest.Interface) *Clientset {\n\tvar cs Clientset\n\tcs.openebsV1alpha1 = openebsv1alpha1.New(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClient(c)\n\treturn &cs\n}\n\nfunc NewForConfig(c *rest.Config) (*Clientset, error) ", "output": "{\n\tconfigShallowCopy := *c\n\tif configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {\n\t\tif configShallowCopy.Burst <= 0 {\n\t\t\treturn nil, fmt.Errorf(\"burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0\")\n\t\t}\n\t\tconfigShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)\n\t}\n\tvar cs Clientset\n\tvar err error\n\tcs.openebsV1alpha1, err = openebsv1alpha1.NewForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &cs, nil\n}"} {"input": "package richtext\n\nimport (\n\t\"fmt\"\n)\n\ntype AnsiFormat8 struct{ ansiFormat }\n\nvar _ Format = &AnsiFormat8{}\n\nvar ansiFormat8 *AnsiFormat8\n\nfunc init() {\n\tansiFormat8 = &AnsiFormat8{}\n\tansiFormat8.init(ansiFormat8)\n}\n\n\n\nfunc rgbTo8(c Color) uint8 {\n\tr, g, b := rgb(c)\n\tr1 := r >> 7\n\tg1 := g >> 7\n\tb1 := b >> 7\n\treturn b1<<2 + g1<<1 + r1\n}\n\nfunc (a *AnsiFormat8) MakePrintf(fg, bg Color, flags ...Flag) func(format string, a ...interface{}) (int, error) {\n\tenc := []string{}\n\tif fg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 30+rgbTo8(fg)))\n\t}\n\tif bg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 40+rgbTo8(bg)))\n\t}\n\n\treturn ansiPrinter(enc, flags)\n}\n\nfunc (a *AnsiFormat8) MakeSprintf(fg, bg Color, flags ...Flag) func(format string, a ...interface{}) string {\n\tenc := []string{}\n\tif fg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 30+rgbTo8(fg)))\n\t}\n\tif bg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 40+rgbTo8(bg)))\n\t}\n\n\treturn ansiSPrinter(enc, flags)\n}\n\nfunc Ansi8() *AnsiFormat8 ", "output": "{ return ansiFormat8 }"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"koding/klientctl/config\"\n\t\"koding/klientctl/ctlcli\"\n\n\t\"github.com/koding/logging\"\n\tcli \"gopkg.in/urfave/cli.v1\"\n)\n\nfunc init() {\n\trand.Seed(time.Now().Unix())\n}\n\n\n\n\n\n\n\n\ntype CheckUpdate struct {\n\tLocation string\n\n\tRandomSeededNumber int\n\n\tForceCheck bool\n\n\tLocalVersion int\n}\n\n\nfunc NewCheckUpdate() *CheckUpdate {\n\treturn &CheckUpdate{\n\t\tLocalVersion: config.VersionNum(),\n\t\tLocation: config.Konfig.Endpoints.KDLatest.Public.String(),\n\t\tRandomSeededNumber: rand.Intn(3),\n\t\tForceCheck: false,\n\t}\n}\n\n\nfunc (c *CheckUpdate) IsUpdateAvailable() (bool, error) {\n\tresp, err := http.Get(c.Location)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar newVersion int\n\n\t_, err = fmt.Fscanf(resp.Body, \"%d\", &newVersion)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn newVersion > c.LocalVersion, nil\n}\n\nfunc CheckUpdateFirst(f ctlcli.ExitingCommand, log logging.Logger, cmd string) (ctlcli.ExitingCommand, logging.Logger, string) ", "output": "{\n\n\texitCmd := func(c *cli.Context, log logging.Logger, cmd string) int {\n\t\tif !c.Bool(\"json\") {\n\t\t\tu := NewCheckUpdate()\n\t\t\tif y, err := u.IsUpdateAvailable(); y && err == nil {\n\t\t\t\tfmt.Printf(\"A newer version of %s is available. Please do `sudo %s update`.\\n\", config.Name, config.Name)\n\t\t\t}\n\t\t}\n\n\t\treturn f(c, log, cmd)\n\t}\n\n\treturn exitCmd, log, cmd\n}"} {"input": "package controller\n\nimport (\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n\ntype Controller struct {\n\te *gin.Engine\n}\n\n\nfunc New( e *gin.Engine) *Controller {\n\n\treturn &Controller{\n\t\te: e,\n\t}\n\n}\n\n\nfunc (c *Controller) SetupRouters() {\n\tc.e.GET(\"/ping2\", c.ping)\n\n}\n\n\n\n\nfunc (p *Controller) ping(ctx *gin.Context) ", "output": "{\n\tctx.String(200, \"pong pong\")\n}"} {"input": "package fork\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n)\n\ntype Field interface {\n\tNamed\n\tNew(...interface{}) Field\n\tGet() *Value\n\tSet(*http.Request)\n\tProcessor\n}\n\ntype Named interface {\n\tName() string\n\tReName(...string) string\n}\n\nfunc newnamed(name string) *named {\n\treturn &named{name: name}\n}\n\ntype named struct {\n\tname string\n}\n\nfunc (n *named) Name() string {\n\treturn n.name\n}\n\nfunc (n *named) ReName(rename ...string) string {\n\tif len(rename) > 0 {\n\t\tn.name = strings.Join(rename, \"-\")\n\t}\n\treturn n.name\n}\n\nfunc (n *named) Copy() *named {\n\tvar ret named = *n\n\treturn &ret\n}\n\ntype Processor interface {\n\tWidget\n\tFilterer\n\tValidater\n}\n\ntype processor struct {\n\tWidget\n\tValidater\n\tFilterer\n}\n\n\n\nfunc NewProcessor(w Widget, v Validater, f Filterer) *processor ", "output": "{\n\treturn &processor{w, v, f}\n}"} {"input": "package library\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/vapi/library\"\n\t\"github.com/vmware/govmomi/vapi/rest\"\n)\n\ntype rm struct {\n\t*flags.ClientFlag\n\tforce bool\n}\n\nfunc init() {\n\tcli.Register(\"library.rm\", &rm{})\n}\n\nfunc (cmd *rm) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.ClientFlag, ctx = flags.NewClientFlag(ctx)\n\tcmd.ClientFlag.Register(ctx, f)\n}\n\nfunc (cmd *rm) Usage() string {\n\treturn \"NAME\"\n}\n\nfunc (cmd *rm) Description() string {\n\treturn `Delete library or item NAME.\n\nExamples:\n govc library.rm /library_name\n govc library.rm library_id # Use library id if multiple libraries have the same name\n govc library.rm /library_name/item_name`\n}\n\n\n\nfunc (cmd *rm) Run(ctx context.Context, f *flag.FlagSet) error ", "output": "{\n\treturn cmd.WithRestClient(ctx, func(c *rest.Client) error {\n\t\tm := library.NewManager(c)\n\t\tres, err := flags.ContentLibraryResult(ctx, c, \"\", f.Arg(0))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch t := res.GetResult().(type) {\n\t\tcase library.Library:\n\t\t\treturn m.DeleteLibrary(ctx, &t)\n\t\tcase library.Item:\n\t\t\treturn m.DeleteLibraryItem(ctx, &t)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"%q is a %T\", f.Arg(0), t)\n\t\t}\n\t})\n}"} {"input": "package jpsplus\n\nimport (\n\t\"container/heap\"\n)\n\ntype PriorityQueue struct {\n\tpos int\n\tnode map[int]*Node\n}\n\nfunc newPriorityQueue() *PriorityQueue {\n\tp := new(PriorityQueue)\n\tp.node = make(map[int]*Node)\n\treturn p\n}\n\nfunc (p *PriorityQueue) Len() int {\n\treturn len(p.node)\n}\n\nfunc (p *PriorityQueue) Less(i, j int) bool {\n\treturn p.node[i].finalCost < p.node[j].finalCost\n}\n\nfunc (p *PriorityQueue) Swap(i, j int) {\n\tp.node[i], p.node[j] = p.node[j], p.node[i]\n\tp.node[i].heapIndex = i\n\tp.node[j].heapIndex = j\n}\n\nfunc (p *PriorityQueue) Push(x interface{}) {\n\titem, ok := x.(*Node)\n\tif ok {\n\t\titem.heapIndex = p.pos\n\t\tp.node[p.pos] = item\n\t\tp.pos++\n\t}\n}\n\nfunc (p *PriorityQueue) Pop() interface{} {\n\tp.pos--\n\titem := p.node[p.pos]\n\tdelete(p.node, p.pos)\n\treturn item\n}\n\nfunc (p *PriorityQueue) PushNode(n *Node) {\n\theap.Push(p, n)\n}\n\n\n\nfunc (p *PriorityQueue) RemoveNode(n *Node) {\n\theap.Remove(p, n.heapIndex)\n}\n\nfunc (p *PriorityQueue) PopNode() *Node ", "output": "{\n\treturn heap.Pop(p).(*Node)\n}"} {"input": "package bds\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype NetworkConfig struct {\n\n\tIsNatGatewayRequired *bool `mandatory:\"false\" json:\"isNatGatewayRequired\"`\n\n\tCidrBlock *string `mandatory:\"false\" json:\"cidrBlock\"`\n}\n\n\n\nfunc (m NetworkConfig) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package main\n\nimport \"errors\"\n\n\n\n\n\n\nfunc handleSocketActivation(n int) error {\n\treturn errors.New(\"systemd socket activation is not available on Windows\")\n}\n\nfunc nfds() int ", "output": "{\n\treturn 0\n}"} {"input": "package fakes\n\nimport (\n\tbslcvm \"github.com/cloudfoundry/bosh-softlayer-cpi/softlayer/vm\"\n)\n\ntype FakeFinder struct {\n\tFindID int\n\tFindVM bslcvm.VM\n\tFindFound bool\n\tFindErr error\n}\n\n\n\nfunc (f *FakeFinder) Find(id int) (bslcvm.VM, bool, error) ", "output": "{\n\tf.FindID = id\n\treturn f.FindVM, f.FindFound, f.FindErr\n}"} {"input": "package neoutils\n\nimport (\n\t\"github.com/Financial-Times/up-rw-app-api-go/rwapi\"\n\t\"github.com/jmcvetta/neoism\"\n)\n\ntype TransactionalCypherRunner struct{ DB *neoism.Database }\n\nfunc (cr TransactionalCypherRunner) String() string {\n\treturn cr.DB.Url\n}\n\n\n\nfunc (cr TransactionalCypherRunner) CypherBatch(queries []*neoism.CypherQuery) error ", "output": "{\n\ttx, err := cr.DB.Begin(queries)\n\tif err != nil {\n\t\tif tx != nil {\n\t\t\ttx.Rollback()\n\t\t}\n\t\tif err == neoism.TxQueryError {\n\t\t\ttxErr := rwapi.ConstraintOrTransactionError{Message: err.Error()}\n\t\t\tfor _, e := range tx.Errors {\n\t\t\t\ttxErr.Details = append(txErr.Details, e.Message)\n\t\t\t}\n\t\t\terr = txErr\n\t\t}\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}"} {"input": "package mysqlctl\n\nimport (\n\t\"fmt\"\n)\n\n\ntype MysqlDaemon interface {\n\tGetMasterAddr() (string, error)\n\n\tGetMysqlPort() (int, error)\n}\n\n\n\ntype FakeMysqlDaemon struct {\n\tMasterAddr string\n\n\tMysqlPort int\n}\n\nfunc (fmd *FakeMysqlDaemon) GetMasterAddr() (string, error) {\n\tif fmd.MasterAddr == \"\" {\n\t\treturn \"\", ErrNotSlave\n\t}\n\tif fmd.MasterAddr == \"ERROR\" {\n\t\treturn \"\", fmt.Errorf(\"FakeMysqlDaemon.GetMasterAddr returns an error\")\n\t}\n\treturn fmd.MasterAddr, nil\n}\n\n\n\nfunc (fmd *FakeMysqlDaemon) GetMysqlPort() (int, error) ", "output": "{\n\tif fmd.MysqlPort == -1 {\n\t\treturn 0, fmt.Errorf(\"FakeMysqlDaemon.GetMysqlPort returns an error\")\n\t}\n\treturn fmd.MysqlPort, nil\n}"} {"input": "package vm\n\ntype Networks map[string]Network\n\ntype Network struct {\n\tType string `json:\"type\"`\n\n\tIP string `json:\"ip,omitempty\"`\n\tNetmask string `json:\"netmask,omitempty\"`\n\tGateway string `json:\"gateway,omitempty\"`\n\n\tDNS []string `json:\"dns,omitempty\"`\n\tDefault []string `json:\"default,omitempty\"`\n\n\tPreconfigured bool `json:\"preconfigured,omitempty\"`\n\n\tMAC string `json:\"mac,omitempty\"`\n\n\tCloudProperties map[string]interface{} `json:\"cloud_properties,omitempty\"`\n}\n\nfunc (ns Networks) First() Network {\n\tfor _, net := range ns {\n\t\treturn net\n\t}\n\n\treturn Network{}\n}\n\n\n\nfunc (n Network) AppendDNS(dns string) Network {\n\tif len(dns) > 0 {\n\t\tn.DNS = append(n.DNS, dns)\n\t\treturn n\n\t}\n\treturn n\n}\n\nfunc (n Network) IsDynamic() bool ", "output": "{ return n.Type == \"dynamic\" }"} {"input": "package ora\n\nimport \"github.com/rainycape/dl\"\n\nvar (\n\tociLibrary = NewLazyDLL(\"libclntsh.so\")\n)\n\n\ntype Library struct {\n\tdll *dl.DL\n}\n\n\nfunc NewLazyDLL(name string) (dll *Library) {\n\tdll = new(Library)\n\tvar err error\n\tif dll.dll, err = dl.Open(name, dl.RTLD_LAZY); err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}\n\n\n\n\n\ntype LibraryProc struct {\n\terr error\n\tfn func(...uintptr) uintptr\n}\n\n\nfunc (lib LibraryProc) Call(args ...uintptr) (r1 uintptr, r2 uintptr, err error) {\n\terr = lib.err\n\tr1 = lib.fn(args...)\n\treturn\n}\n\nfunc (lib *Library) NewProc(name string) *LibraryProc ", "output": "{\n\tcallee := new(LibraryProc)\n\tcallee.err = lib.dll.Sym(name, &callee.fn)\n\treturn callee\n}"} {"input": "package gomove\n\n\n\n\n\nimport \"fmt\"\n\ntype ByteSize float64\n\nconst (\n\t_ = iota\n\tKB ByteSize = 1 << (10 * iota)\n\tMB\n\tGB\n\tTB\n\tPB\n\tEB\n\tZB\n\tYB\n)\n\n\n\nfunc (b ByteSize) String() string ", "output": "{\n\tswitch {\n\tcase b >= YB:\n\t\treturn fmt.Sprintf(\"%.2fYB\", b/YB)\n\tcase b >= ZB:\n\t\treturn fmt.Sprintf(\"%.2fZB\", b/ZB)\n\tcase b >= EB:\n\t\treturn fmt.Sprintf(\"%.2fEB\", b/EB)\n\tcase b >= PB:\n\t\treturn fmt.Sprintf(\"%.2fPB\", b/PB)\n\tcase b >= TB:\n\t\treturn fmt.Sprintf(\"%.2fTB\", b/TB)\n\tcase b >= GB:\n\t\treturn fmt.Sprintf(\"%.2fGB\", b/GB)\n\tcase b >= MB:\n\t\treturn fmt.Sprintf(\"%.2fMB\", b/MB)\n\tcase b >= KB:\n\t\treturn fmt.Sprintf(\"%.2fKB\", b/KB)\n\t}\n\treturn fmt.Sprintf(\"%.0fB\", b)\n}"} {"input": "package validation\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/util/validation\"\n)\n\n\n\n\nfunc ValidateEvent(event *api.Event) validation.ErrorList ", "output": "{\n\tallErrs := validation.ErrorList{}\n\tif event.InvolvedObject.Kind != \"Node\" &&\n\t\tevent.Namespace != event.InvolvedObject.Namespace {\n\t\tallErrs = append(allErrs, validation.NewFieldInvalid(\"involvedObject.namespace\", event.InvolvedObject.Namespace, \"namespace does not match involvedObject\"))\n\t}\n\tif !validation.IsDNS1123Subdomain(event.Namespace) {\n\t\tallErrs = append(allErrs, validation.NewFieldInvalid(\"namespace\", event.Namespace, \"\"))\n\t}\n\treturn allErrs\n}"} {"input": "package layers\n\nimport (\n\t\"github.com/vtolstov/gopacket\"\n)\n\n\n\ntype BaseLayer struct {\n\tContents []byte\n\tPayload []byte\n}\n\n\n\n\n\nfunc (b *BaseLayer) LayerPayload() []byte { return b.Payload }\n\ntype layerDecodingLayer interface {\n\tgopacket.Layer\n\tDecodeFromBytes([]byte, gopacket.DecodeFeedback) error\n\tNextLayerType() gopacket.LayerType\n}\n\nfunc decodingLayerDecoder(d layerDecodingLayer, data []byte, p gopacket.PacketBuilder) error {\n\terr := d.DecodeFromBytes(data, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.AddLayer(d)\n\tnext := d.NextLayerType()\n\tif next == gopacket.LayerTypeZero {\n\t\treturn nil\n\t}\n\treturn p.NextDecoder(next)\n}\n\n\nvar lotsOfZeros [1024]byte\n\nfunc (b *BaseLayer) LayerContents() []byte ", "output": "{ return b.Contents }"} {"input": "package minecraft\n\nimport (\n\t\"io\"\n\t\"github.com/LilyPad/GoLilyPad/packet\"\n)\n\ntype PacketServerLoginStart struct {\n\tName string\n}\n\nfunc NewPacketServerLoginStart(name string) (this *PacketServerLoginStart) {\n\tthis = new(PacketServerLoginStart)\n\tthis.Name = name\n\treturn\n}\n\nfunc (this *PacketServerLoginStart) Id() int {\n\treturn PACKET_SERVER_LOGIN_START\n}\n\ntype packetServerLoginStartCodec struct {\n\n}\n\nfunc (this *packetServerLoginStartCodec) Decode(reader io.Reader) (decode packet.Packet, err error) {\n\tpacketServerLoginStart := new(PacketServerLoginStart)\n\tpacketServerLoginStart.Name, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\tdecode = packetServerLoginStart\n\treturn\n}\n\n\n\nfunc (this *packetServerLoginStartCodec) Encode(writer io.Writer, encode packet.Packet) (err error) ", "output": "{\n\tpacketServerLoginStart := encode.(*PacketServerLoginStart)\n\terr = packet.WriteString(writer, packetServerLoginStart.Name)\n\treturn\n}"} {"input": "package basictypes\n\nconst (\n\tAString = \"a string\"\n\tAnInt = 7\n\tAnInt2 = 1<<63 - 1\n\tAFloat = 0.2015\n\tARune = rune(32)\n\tABool = true\n)\n\nfunc Ints(x int8, y int16, z int32, t int64, u int) {}\n\n\n\nfunc ErrorPair() (int, error) { return 0, nil }\n\nfunc ByteArrays(x []byte) []byte { return nil }\n\nfunc Bool(bool) bool { return true }\n\nfunc Error() error ", "output": "{ return nil }"} {"input": "package grooveshark\n\nimport (\n\t\"github.com/stayradiated/grooveshark/requests\"\n\t\"github.com/stayradiated/grooveshark/responses\"\n)\n\n\n\nfunc (c *Client) Search(query string) (tracks []responses.Track) ", "output": "{\n\tvar resp responses.GetResultsFromSearch\n\n\tc.CallMethod(\"getResultsFromSearch\", requests.GetResultsFromSearch{\n\t\tGuts: 0,\n\t\tPPOverride: false,\n\t\tQuery: query,\n\t\tType: \"Songs\",\n\t}, &resp)\n\n\treturn resp.Result.Result.Tracks()\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\ntype CreateEnvironmentRequest struct {\n\n\tInstanceGroup *InstanceGroup `json:\"instanceGroup\"`\n\n\tName *string `json:\"name\"`\n\n\tTaskDefinition *string `json:\"taskDefinition\"`\n}\n\n\nfunc (m *CreateEnvironmentRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateInstanceGroup(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTaskDefinition(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\nfunc (m *CreateEnvironmentRequest) validateName(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"name\", \"body\", m.Name); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validate.Pattern(\"name\", \"body\", string(*m.Name), `^[a-zA-Z0-9-_]{1,30}$`); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *CreateEnvironmentRequest) validateTaskDefinition(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"taskDefinition\", \"body\", m.TaskDefinition); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *CreateEnvironmentRequest) validateInstanceGroup(formats strfmt.Registry) error ", "output": "{\n\n\tif err := validate.Required(\"instanceGroup\", \"body\", m.InstanceGroup); err != nil {\n\t\treturn err\n\t}\n\n\tif m.InstanceGroup != nil {\n\n\t\tif err := m.InstanceGroup.Validate(formats); err != nil {\n\t\t\tif ve, ok := err.(*errors.Validation); ok {\n\t\t\t\treturn ve.ValidateName(\"instanceGroup\")\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package iso20022\n\n\ntype RejectedStatus4 struct {\n\n\tReason *RejectedStatusReason4 `xml:\"Rsn\"`\n\n\tDataSourceScheme *GenericIdentification1 `xml:\"DataSrcSchme\"`\n}\n\nfunc (r *RejectedStatus4) AddReason() *RejectedStatusReason4 {\n\tr.Reason = new(RejectedStatusReason4)\n\treturn r.Reason\n}\n\n\n\nfunc (r *RejectedStatus4) AddDataSourceScheme() *GenericIdentification1 ", "output": "{\n\tr.DataSourceScheme = new(GenericIdentification1)\n\treturn r.DataSourceScheme\n}"} {"input": "package budget\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteBudgetRequest struct {\n\n\tBudgetId *string `mandatory:\"true\" contributesTo:\"path\" name:\"budgetId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteBudgetRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteBudgetRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request DeleteBudgetRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request DeleteBudgetRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteBudgetResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response DeleteBudgetResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response DeleteBudgetResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package template\n\nimport (\n\t\"github.com/dpb587/metalink\"\n)\n\ntype templateFile metalink.File\n\nfunc (tf templateFile) MD5() string {\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"md5\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\nfunc (tf templateFile) SHA1() string {\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"sha-1\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\nfunc (tf templateFile) SHA256() string {\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"sha-256\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\n\n\nfunc (tf templateFile) SHA512() string ", "output": "{\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"sha-512\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}"} {"input": "package category\n\nimport (\n\t\"strings\"\n\t\"unicode\"\n)\n\n\n\nfunc titleFromHashtag(hashtag string) string {\n\tvar t strings.Builder\n\tvar prev rune\n\tfor i, c := range hashtag {\n\t\tif unicode.IsUpper(c) {\n\t\t\tif i > 0 && !unicode.IsUpper(prev) {\n\t\t\t\tt.WriteRune(' ')\n\t\t\t}\n\t\t\tt.WriteRune(unicode.ToLower(c))\n\t\t} else {\n\t\t\tt.WriteRune(c)\n\t\t}\n\t\tprev = c\n\t}\n\treturn t.String()\n}\n\n\n\n\n\nfunc HashtagFromTitle(title string) string ", "output": "{\n\tvar t strings.Builder\n\tvar prev rune\n\tfor _, c := range title {\n\t\tif !unicode.IsLetter(c) && !unicode.IsNumber(c) {\n\t\t\tprev = c\n\t\t\tcontinue\n\t\t}\n\t\tif unicode.IsSpace(prev) {\n\t\t\tt.WriteRune(unicode.ToUpper(c))\n\t\t} else {\n\t\t\tt.WriteRune(c)\n\t\t}\n\t\tprev = c\n\t}\n\treturn t.String()\n}"} {"input": "package decorators\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t\"github.com/antham/chyle/chyle/convh\"\n)\n\ntype shellConfig map[string]struct {\n\tCOMMAND string\n\tORIGKEY string\n\tDESTKEY string\n}\n\n\n\ntype shell struct {\n\tCOMMAND string\n\tORIGKEY string\n\tDESTKEY string\n}\n\nfunc (s shell) Decorate(commitMap *map[string]interface{}) (*map[string]interface{}, error) {\n\tvar tmp interface{}\n\tvar value string\n\tvar ok bool\n\tvar err error\n\n\tif tmp, ok = (*commitMap)[s.ORIGKEY]; !ok {\n\t\treturn commitMap, nil\n\t}\n\n\tif value, err = convh.ConvertToString(tmp); err != nil {\n\t\treturn commitMap, nil\n\t}\n\n\tif (*commitMap)[s.DESTKEY], err = s.execute(value); err != nil {\n\t\treturn commitMap, err\n\t}\n\n\treturn commitMap, nil\n}\n\nfunc (s shell) execute(value string) (string, error) {\n\tvar result []byte\n\tvar err error\n\n\tcommand := fmt.Sprintf(`echo \"%s\"|%s`, strings.Replace(value, `\"`, `\\\"`, -1), s.COMMAND)\n\n\tif result, err = exec.Command(\"sh\", \"-c\", command).Output(); err != nil {\n\t\treturn \"\", fmt.Errorf(\"%s : command failed\", command)\n\t}\n\n\treturn string(result[:len(result)-1]), nil\n}\n\n\n\nfunc newShell(configs shellConfig) []Decorater ", "output": "{\n\tresults := []Decorater{}\n\n\tfor _, config := range configs {\n\t\tresults = append(results, shell(config))\n\t}\n\n\treturn results\n}"} {"input": "package label\n\n\n\n\nfunc InitLabels(mcsdir string, options []string) (string, string, error) {\n\treturn \"\", \"\", nil\n}\n\nfunc FormatMountLabel(src string, mountLabel string) string {\n\treturn src\n}\n\nfunc SetProcessLabel(processLabel string) error {\n\treturn nil\n}\n\nfunc SetFileLabel(path string, fileLabel string) error {\n\treturn nil\n}\n\nfunc SetFileCreateLabel(fileLabel string) error {\n\treturn nil\n}\n\nfunc Relabel(path string, fileLabel string, relabel string) error {\n\treturn nil\n}\n\nfunc GetPidLabel(pid int) (string, error) {\n\treturn \"\", nil\n}\n\nfunc Init() {\n}\n\nfunc ReserveLabel(label string) error {\n\treturn nil\n}\n\nfunc UnreserveLabel(label string) error {\n\treturn nil\n}\n\n\n\nfunc DupSecOpt(src string) []string {\n\treturn nil\n}\n\n\n\n\n\nfunc DisableSecOpt() []string ", "output": "{\n\treturn nil\n}"} {"input": "package externalversions\n\nimport (\n\t\"fmt\"\n\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tcache \"k8s.io/client-go/tools/cache\"\n\tv1 \"k8s.io/code-generator/examples/HyphenGroup/apis/example/v1\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\n\n\n\nfunc (f *genericInformer) Lister() cache.GenericLister {\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {\n\tswitch resource {\n\tcase v1.SchemeGroupVersion.WithResource(\"clustertesttypes\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.ExampleGroup().V1().ClusterTestTypes().Informer()}, nil\n\tcase v1.SchemeGroupVersion.WithResource(\"testtypes\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.ExampleGroup().V1().TestTypes().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer ", "output": "{\n\treturn f.informer\n}"} {"input": "package viewservice\n\nimport \"net/rpc\"\nimport \"fmt\"\n\n\n\n\n\ntype Clerk struct {\n\tme string \n\tserver string \n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc call(srv string, rpcname string,\n\targs interface{}, reply interface{}) bool {\n\tc, errx := rpc.Dial(\"unix\", srv)\n\tif errx != nil {\n\t\treturn false\n\t}\n\tdefer c.Close()\n\n\terr := c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}\n\nfunc (ck *Clerk) Ping(viewnum uint) (View, error) {\n\targs := &PingArgs{}\n\targs.Me = ck.me\n\targs.Viewnum = viewnum\n\tvar reply PingReply\n\n\tok := call(ck.server, \"ViewServer.Ping\", args, &reply)\n\tif ok == false {\n\t\treturn View{}, fmt.Errorf(\"Ping(%v) failed\", viewnum)\n\t}\n\n\treturn reply.View, nil\n}\n\nfunc (ck *Clerk) Get() (View, bool) {\n\targs := &GetArgs{}\n\tvar reply GetReply\n\tok := call(ck.server, \"ViewServer.Get\", args, &reply)\n\tif ok == false {\n\t\treturn View{}, false\n\t}\n\treturn reply.View, true\n}\n\nfunc (ck *Clerk) Primary() string {\n\tv, ok := ck.Get()\n\tif ok {\n\t\treturn v.Primary\n\t}\n\treturn \"\"\n}\n\nfunc MakeClerk(me string, server string) *Clerk ", "output": "{\n\tck := new(Clerk)\n\tck.me = me\n\tck.server = server\n\treturn ck\n}"} {"input": "package models\n\n\n\n\nimport (\n\tciliumModels \"github.com/cilium/cilium/api/v1/models\"\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\n\ntype HealthResponse struct {\n\n\tCilium ciliumModels.StatusResponse `json:\"cilium,omitempty\"`\n\n\tSystemLoad *LoadResponse `json:\"system-load,omitempty\"`\n\n\tUptime string `json:\"uptime,omitempty\"`\n}\n\n\nfunc (m *HealthResponse) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateSystemLoad(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (m *HealthResponse) validateSystemLoad(formats strfmt.Registry) error {\n\n\tif swag.IsZero(m.SystemLoad) { \n\t\treturn nil\n\t}\n\n\tif m.SystemLoad != nil {\n\t\tif err := m.SystemLoad.Validate(formats); err != nil {\n\t\t\tif ve, ok := err.(*errors.Validation); ok {\n\t\t\t\treturn ve.ValidateName(\"system-load\")\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\nfunc (m *HealthResponse) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\n\n\nfunc (m *HealthResponse) UnmarshalBinary(b []byte) error ", "output": "{\n\tvar res HealthResponse\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}"} {"input": "package model\n\ntype User struct {\n\tID string `db:\"id\"`\n\tName string `db:\"name\"`\n\tEmail string `db:\"email\"`\n\tGender string `db:\"gender\"`\n\tTranslationLanguageID *string `db:\"translation_language_id\"`\n}\n\n\n\nfunc (c *User) SetTranslationLanguageID(value string) {\n\tif value == \"\" {\n\t\tc.TranslationLanguageID = nil\n\t} else {\n\t\tc.TranslationLanguageID = &value\n\t}\n}\n\ntype UserConnection struct {\n\tUserID string `db:\"user_id\"`\n\tProviderID string `db:\"provider_id\"`\n\tProviderUserID string `db:\"provider_user_id\"`\n\n\tUser *User\n}\n\nfunc (c *User) GenerateID() ", "output": "{\n\tc.ID = generateID(10)\n}"} {"input": "package null\n\nimport \"github.com/tidepool-org/platform/log\"\n\n\n\n\n\nfunc NewLogger() log.Logger ", "output": "{\n\tlogger, _ := log.NewLogger(NewSerializer(), log.DefaultLevelRanks(), log.DefaultLevel()) \n\treturn logger\n}"} {"input": "package stores\n\nimport (\n\t\"HTVM/instructions/base\"\n\t\"HTVM/runtime\"\n)\n\n\ntype ASTORE struct {\n\tbase.Index8Instruction\n}\n\n\n\ntype ASTORE_0 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_0) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 0)\n}\n\ntype ASTORE_1 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_1) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 1)\n}\n\ntype ASTORE_2 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_2) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 2)\n}\n\ntype ASTORE_3 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_3) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 3)\n}\n\ntype ASTORE_4 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_4) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 4)\n}\n\nfunc _executeRef(frame *runtime.Frame, index uint) {\n\tval := frame.OperateStack().PopRef()\n\tframe.LocalVars().SetRef(index, val)\n}\n\nfunc (self *ASTORE) Execute(frame *runtime.Frame) ", "output": "{\n\t_executeRef(frame, self.Index)\n}"} {"input": "package trace\n\nimport (\n\t\"github.com/golang/groupcache/lru\"\n)\n\n\n\ntype lruMap struct {\n\tcacheKeys map[lru.Key]bool\n\tcache *lru.Cache\n\tdroppedCount int\n}\n\nfunc newLruMap(size int) *lruMap {\n\tlm := &lruMap{\n\t\tcacheKeys: make(map[lru.Key]bool),\n\t\tcache: lru.New(size),\n\t\tdroppedCount: 0,\n\t}\n\tlm.cache.OnEvicted = func(key lru.Key, value interface{}) {\n\t\tdelete(lm.cacheKeys, key)\n\t\tlm.droppedCount++\n\t}\n\treturn lm\n}\n\nfunc (lm lruMap) len() int {\n\treturn lm.cache.Len()\n}\n\nfunc (lm lruMap) keys() []interface{} {\n\tkeys := []interface{}{}\n\tfor k := range lm.cacheKeys {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}\n\nfunc (lm *lruMap) add(key, value interface{}) {\n\tlm.cacheKeys[lru.Key(key)] = true\n\tlm.cache.Add(lru.Key(key), value)\n}\n\n\n\nfunc (lm *lruMap) get(key interface{}) (interface{}, bool) ", "output": "{\n\treturn lm.cache.Get(key)\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"gopkg.in/gin-gonic/gin.v1\"\n\n\t\"github.com/knopt/iot/backend/api/model\"\n\t\"github.com/knopt/iot/backend/error\"\n)\n\n\nfunc (api *Api) GetStatisticsByDeviceDataType(context *gin.Context) {\n\tdeviceID := context.Param(\"id\")\n\tdateFrom := context.Param(\"from\")\n\tdateTo := context.Param(\"to\")\n\tdataType := context.Param(\"type\")\n\n\tresponseStatistics, err := api.Service.GetStatistics(deviceID, dateFrom, dateTo, dataType)\n\tif err != nil {\n\t\terror.Handler(&error.Error{Code: http.StatusBadRequest, Err: err}, context)\n\t\treturn\n\t}\n\n\tcontext.IndentedJSON(http.StatusOK, responseStatistics)\n}\n\n\nfunc (api *Api) InsertStatistic(context *gin.Context) {\n\tvar statisticForm model.StatisticForm\n\n\tif err := context.BindJSON(&statisticForm); err != nil {\n\t\tcontext.AbortWithError(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\terr := api.Service.InsertStatistic(&statisticForm)\n\tif err != nil {\n\t\terror.Handler(&error.Error{Code: http.StatusBadRequest, Err: err}, context)\n\t\treturn\n\t}\n\n\tcontext.String(http.StatusOK, \"Success\")\n}\n\n\n\n\n\nfunc (api *Api) GetStatisticsTypes(context *gin.Context) {\n\tdeviceID := context.Param(\"id\")\n\n\tresponseTypes, err := api.Service.GetStatisticsTypes(deviceID)\n\tif err != nil {\n\t\terror.Handler(&error.Error{Code: http.StatusBadRequest, Err: err}, context)\n\t\treturn\n\t}\n\n\tcontext.IndentedJSON(http.StatusOK, responseTypes)\n}\n\nfunc (api *Api) InsertStatisticInUrl(context *gin.Context) ", "output": "{\n\tvar statisticForm model.StatisticForm\n\n\tvalue := context.Param(\"value\")\n\tdeviceID := context.Param(\"id\")\n\tstatType := context.Param(\"type\")\n\n\tvalueFloat, err := strconv.ParseFloat(value, 64)\n\tif err != nil {\n\t\tcontext.AbortWithError(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tstatisticForm.Value = valueFloat\n\tstatisticForm.DeviceID = deviceID\n\tstatisticForm.Type = statType\n\tstatisticForm.Date = time.Now()\n\n\terr = api.Service.InsertStatistic(&statisticForm)\n\tif err != nil {\n\t\terror.Handler(&error.Error{Code: http.StatusBadRequest, Err: err}, context)\n\t\treturn\n\t}\n\n\tcontext.String(http.StatusOK, \"Success\")\n}"} {"input": "package field\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype Path struct {\n\tname string \n\tindex string \n\tparent *Path \n}\n\n\nfunc NewPath(name string, moreNames ...string) *Path {\n\tr := &Path{name: name, parent: nil}\n\tfor _, anotherName := range moreNames {\n\t\tr = &Path{name: anotherName, parent: r}\n\t}\n\treturn r\n}\n\n\nfunc (p *Path) Root() *Path {\n\tfor ; p.parent != nil; p = p.parent {\n\t}\n\treturn p\n}\n\n\nfunc (p *Path) Child(name string, moreNames ...string) *Path {\n\tr := NewPath(name, moreNames...)\n\tr.Root().parent = p\n\treturn r\n}\n\n\n\nfunc (p *Path) Index(index int) *Path {\n\treturn &Path{index: strconv.Itoa(index), parent: p}\n}\n\n\n\nfunc (p *Path) Key(key string) *Path {\n\treturn &Path{index: key, parent: p}\n}\n\n\n\n\nfunc (p *Path) String() string ", "output": "{\n\tif p == nil {\n\t\treturn \"\"\n\t}\n\telems := []*Path{}\n\tfor ; p != nil; p = p.parent {\n\t\telems = append(elems, p)\n\t}\n\n\tbuf := bytes.NewBuffer(nil)\n\tfor i := range elems {\n\t\tp := elems[len(elems)-1-i]\n\t\tif p.parent != nil && len(p.name) > 0 {\n\t\t\tbuf.WriteString(\".\")\n\t\t}\n\t\tif len(p.name) > 0 {\n\t\t\tbuf.WriteString(p.name)\n\t\t} else {\n\t\t\tfmt.Fprintf(buf, \"[%s]\", p.index)\n\t\t}\n\t}\n\treturn buf.String()\n}"} {"input": "package ttlru\n\ntype ttlHeap []*entry\n\n\n\nfunc (h ttlHeap) Less(i, j int) bool {\n\tif i == j || i < 0 || j < 0 {\n\t\treturn false\n\t}\n\treturn h[i].expires.Before(h[j].expires)\n}\n\nfunc (h ttlHeap) Swap(i, j int) {\n\tif i == j || i < 0 || j < 0 {\n\t\treturn\n\t}\n\th[i], h[j] = h[j], h[i]\n\th[i].index, h[j].index = i, j\n}\n\nfunc (h *ttlHeap) Push(x interface{}) {\n\tn := len(*h)\n\titem := x.(*entry)\n\titem.index = n\n\t*h = append(*h, item)\n}\n\nfunc (h *ttlHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tif n == 0 {\n\t\treturn nil\n\t}\n\titem := old[n-1]\n\titem.index = -1 \n\t*h = old[0 : n-1]\n\treturn item\n}\n\nfunc (h ttlHeap) Len() int ", "output": "{\n\treturn len(h)\n}"} {"input": "package log\n\nimport (\n\t\"github.com/proidiot/gone/errors\"\n\t\"github.com/proidiot/gone/log/opt\"\n\t\"github.com/proidiot/gone/log/pri\"\n)\n\ntype testSyslogger struct {\n\tLastPri pri.Priority\n\tLastMsg interface{}\n\tTriggerError bool\n}\n\nfunc (t *testSyslogger) triggerError() error {\n\tif t.TriggerError {\n\t\treturn errors.New(\"Artificial error triggered in testSyslogger\")\n\t}\n\n\treturn nil\n}\n\nfunc (t *testSyslogger) Syslog(p pri.Priority, msg interface{}) error {\n\tt.LastPri = p\n\tt.LastMsg = msg\n\treturn t.triggerError()\n}\n\nfunc (t *testSyslogger) Openlog(string, opt.Option, pri.Priority) error {\n\treturn t.triggerError()\n}\n\nfunc (t *testSyslogger) Close() error {\n\treturn t.triggerError()\n}\n\ntype limitedSyslogger struct {\n\tLastPri pri.Priority\n\tLastMsg interface{}\n\tTriggerError bool\n}\n\nfunc (l *limitedSyslogger) triggerError() error {\n\tif l.TriggerError {\n\t\treturn errors.New(\n\t\t\t\"Artificial error triggered in limitedSyslogger\",\n\t\t)\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (l *limitedSyslogger) Syslog(p pri.Priority, msg interface{}) error ", "output": "{\n\tl.LastPri = p\n\tl.LastMsg = msg\n\treturn l.triggerError()\n}"} {"input": "package stringutil\n\nimport \"testing\"\n\nfunc TestCall(t *testing.T) {\n\tcases := []struct {\n\t\tin, want string\n\t}{\n\t\t{\"Hello, world\", \"dlrow ,olleH\"},\n\t\t{\"Hello, 世界\", \"界世 ,olleH\"},\n\t\t{\"\", \"\"},\n\t}\n\tfor _, c := range cases {\n\t\tgot := Reverse(c.in)\n\t\tif got != c.want {\n\t\t\tt.Errorf(\"Reverse(%q) == %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}\n\n\nfunc BenchmarkHello(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tReverse(\"Hello\")\n\t}\n}"} {"input": "package sandglass\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hashicorp/serf/serf\"\n\t\"github.com/sandglass/sandglass-grpc/go/sgproto\"\n\t\"google.golang.org/grpc\"\n)\n\ntype Node struct {\n\tID string\n\tName string\n\tIP string\n\tGRPCAddr string\n\tRAFTAddr string\n\tHTTPAddr string\n\tStatus serf.MemberStatus\n\tconn *grpc.ClientConn\n\tsgproto.BrokerServiceClient\n\tsgproto.InternalServiceClient\n}\n\nfunc (n *Node) Dial() (err error) {\n\tn.conn, err = grpc.Dial(n.GRPCAddr, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn err\n\t}\n\tn.BrokerServiceClient = sgproto.NewBrokerServiceClient(n.conn)\n\tn.InternalServiceClient = sgproto.NewInternalServiceClient(n.conn)\n\n\treturn nil\n}\n\n\n\nfunc (n *Node) String() string {\n\treturn fmt.Sprintf(\"%s(%s)\", n.Name, n.GRPCAddr)\n}\n\nfunc (n *Node) IsAlive() bool {\n\treturn n.conn != nil\n}\n\nfunc (n *Node) Close() error ", "output": "{\n\tif n.conn == nil {\n\t\treturn nil\n\t}\n\tif err := n.conn.Close(); err != nil {\n\t\treturn err\n\t}\n\tn.conn = nil\n\treturn nil\n}"} {"input": "package configmap\n\nimport (\n\t\"sync\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n)\n\n\ntype ManualWatcher struct {\n\tNamespace string\n\n\tsync.RWMutex\n\tobservers map[string][]Observer\n}\n\nvar _ Watcher = (*ManualWatcher)(nil)\n\n\nfunc (w *ManualWatcher) Watch(name string, o ...Observer) {\n\tw.Lock()\n\tdefer w.Unlock()\n\n\tif w.observers == nil {\n\t\tw.observers = make(map[string][]Observer, 1)\n\t}\n\tw.observers[name] = append(w.observers[name], o...)\n}\n\n\nfunc (w *ManualWatcher) ForEach(f func(string, []Observer) error) error {\n\tfor k, v := range w.observers {\n\t\tif err := f(k, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (w *ManualWatcher) Start(<-chan struct{}) error {\n\treturn nil\n}\n\n\n\n\nfunc (w *ManualWatcher) OnChange(configMap *corev1.ConfigMap) ", "output": "{\n\tif configMap.Namespace != w.Namespace {\n\t\treturn\n\t}\n\tw.RLock()\n\tdefer w.RUnlock()\n\tfor _, o := range w.observers[configMap.Name] {\n\t\to(configMap)\n\t}\n}"} {"input": "package outbarriers\n\nimport (\n\t\"log\"\n\t\"time\"\n)\n\ntype User struct {\n\tId int64\n\tEmail string\n\tPassword string \n}\ntype Session struct {\n\tId int64\n\tUserId int64\n\tToken string `sql:\"unique; not null\"`\n\tCreatedAt time.Time\n}\n\nfunc (ctx *Context) AuthUser(email, password string) *User {\n\n\tvar user User\n\tctx.DB.Where(\"email = ? and password = ?\", email, password).First(&user)\n\treturn &user\n}\n\nfunc (ctx *Context) CheckAdmin() {\n\n\tvar user User\n\tctx.DB.Where(User{Email: ADMIN_EMAIL, Password: ADMIN_PASSWORD}).FirstOrInit(&user)\n\tif ctx.DB.NewRecord(user) {\n\t\tlog.Printf(\"Admin user not exists, creating...\")\n\t\tctx.DB.Create(&user)\n\t}\n}\n\nfunc (ctx *Context) LoginUser(user *User) string {\n\n\ttoken := RandomString(64)\n\tsession := &Session{UserId: user.Id, Token: token, CreatedAt: time.Now()}\n\tctx.DB.Create(session)\n\treturn token\n}\n\n\n\nfunc (ctx *Context) GetSessionByToken(token string) *Session ", "output": "{\n\n\tvar session Session\n\tctx.DB.Where(\"token = ?\", token).First(&session)\n\tif session.Id == 0 {\n\t\treturn nil\n\t}\n\treturn &session\n}"} {"input": "package structs\n\nimport \"fmt\"\n\n\ntype Bitmap []byte\n\n\nfunc NewBitmap(size uint) (Bitmap, error) {\n\tif size == 0 {\n\t\treturn nil, fmt.Errorf(\"bitmap must be positive size\")\n\t}\n\tif size&7 != 0 {\n\t\treturn nil, fmt.Errorf(\"bitmap must be byte aligned\")\n\t}\n\tb := make([]byte, size>>3)\n\treturn Bitmap(b), nil\n}\n\n\nfunc (b Bitmap) Copy() (Bitmap, error) {\n\tif b == nil {\n\t\treturn nil, fmt.Errorf(\"can't copy nil Bitmap\")\n\t}\n\n\traw := make([]byte, len(b))\n\tcopy(raw, b)\n\treturn Bitmap(raw), nil\n}\n\n\n\n\n\nfunc (b Bitmap) Set(idx uint) {\n\tbucket := idx >> 3\n\tmask := byte(1 << (idx & 7))\n\tb[bucket] |= mask\n}\n\n\nfunc (b Bitmap) Check(idx uint) bool {\n\tbucket := idx >> 3\n\tmask := byte(1 << (idx & 7))\n\treturn (b[bucket] & mask) != 0\n}\n\n\nfunc (b Bitmap) Clear() {\n\tfor i := range b {\n\t\tb[i] = 0\n\t}\n}\n\n\n\nfunc (b Bitmap) IndexesInRange(set bool, from, to uint) []int {\n\tvar indexes []int\n\tfor i := from; i < to; i++ {\n\t\tc := b.Check(i)\n\t\tif c && set || !c && !set {\n\t\t\tindexes = append(indexes, int(i))\n\t\t}\n\t}\n\n\treturn indexes\n}\n\nfunc (b Bitmap) Size() uint ", "output": "{\n\treturn uint(len(b) << 3)\n}"} {"input": "package migrations\n\nimport (\n\t\"context\"\n\n\t\"github.com/fnproject/fn/api/datastore/sql/migratex\"\n\t\"github.com/jmoiron/sqlx\"\n)\n\nfunc up6(ctx context.Context, tx *sqlx.Tx) error {\n\t_, err := tx.ExecContext(ctx, \"ALTER TABLE apps ADD updated_at VARCHAR(256);\")\n\treturn err\n}\n\nfunc down6(ctx context.Context, tx *sqlx.Tx) error {\n\t_, err := tx.ExecContext(ctx, \"ALTER TABLE apps DROP COLUMN updated_at;\")\n\treturn err\n}\n\n\n\nfunc init() ", "output": "{\n\tMigrations = append(Migrations, &migratex.MigFields{\n\t\tVersionFunc: vfunc(6),\n\t\tUpFunc: up6,\n\t\tDownFunc: down6,\n\t})\n}"} {"input": "package exec\n\nimport \"fmt\"\n\nvar (\n\tExecTypeOs ExecType = 0\n\n\texecTypeToString = map[ExecType]string{\n\t\tExecTypeOs: \"os\",\n\t}\n\tlenExecTypeToString = len(execTypeToString)\n\tstringToExecType = map[string]ExecType{\n\t\t\"os\": ExecTypeOs,\n\t}\n)\n\ntype ExecType uint\n\n\n\nfunc ExecTypeOf(s string) (ExecType, error) {\n\texecType, ok := stringToExecType[s]\n\tif !ok {\n\t\treturn 0, UnknownExecType(s)\n\t}\n\treturn execType, nil\n}\n\nfunc (e ExecType) String() string {\n\tif int(e) < lenExecTypeToString {\n\t\treturn execTypeToString[e]\n\t}\n\tpanic(UnknownExecType(e).Error())\n}\n\nfunc UnknownExecType(unknownExecType interface{}) error {\n\treturn fmt.Errorf(\"exec: unknown ExecType: %v\", unknownExecType)\n}\n\nfunc AllExecTypes() []ExecType ", "output": "{\n\treturn []ExecType{\n\t\tExecTypeOs,\n\t}\n}"} {"input": "package stack\n\nconst (\n\tstackPoolSize = 64\n)\n\nvar (\n\tpcStackPool = make(chan []uintptr, stackPoolSize)\n)\n\nfunc poolBuf() []uintptr {\n\tselect {\n\tcase p := <-pcStackPool:\n\t\treturn p\n\tdefault:\n\t\treturn make([]uintptr, 1000)\n\t}\n}\n\n\n\nfunc putPoolBuf(p []uintptr) ", "output": "{\n\tselect {\n\tcase pcStackPool <- p:\n\tdefault:\n\t}\n}"} {"input": "package canal\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/BurntSushi/toml\"\n\t\"github.com/siddontang/go-mysql/mysql\"\n\t\"github.com/siddontang/go/ioutil2\"\n\t\"github.com/siddontang/go/log\"\n)\n\ntype masterInfo struct {\n\tAddr string `toml:\"addr\"`\n\tName string `toml:\"bin_name\"`\n\tPosition uint32 `toml:\"bin_pos\"`\n\n\tname string\n\n\tl sync.Mutex\n\n\tlastSaveTime time.Time\n}\n\n\n\nfunc (m *masterInfo) Save(force bool) error {\n\tm.l.Lock()\n\tdefer m.l.Unlock()\n\n\tn := time.Now()\n\tif !force && n.Sub(m.lastSaveTime) < time.Second {\n\t\treturn nil\n\t}\n\n\tvar buf bytes.Buffer\n\te := toml.NewEncoder(&buf)\n\n\te.Encode(m)\n\n\tvar err error\n\tif err = ioutil2.WriteFileAtomic(m.name, buf.Bytes(), 0644); err != nil {\n\t\tlog.Errorf(\"canal save master info to file %s err %v\", m.name, err)\n\t}\n\n\tm.lastSaveTime = n\n\n\treturn err\n}\n\nfunc (m *masterInfo) Update(name string, pos uint32) {\n\tm.l.Lock()\n\tm.Name = name\n\tm.Position = pos\n\tm.l.Unlock()\n}\n\nfunc (m *masterInfo) Pos() mysql.Position {\n\tvar pos mysql.Position\n\tm.l.Lock()\n\tpos.Name = m.Name\n\tpos.Pos = m.Position\n\tm.l.Unlock()\n\n\treturn pos\n}\n\nfunc (m *masterInfo) Close() {\n\tm.Save(true)\n}\n\nfunc loadMasterInfo(name string) (*masterInfo, error) ", "output": "{\n\tvar m masterInfo\n\n\tm.name = name\n\n\tf, err := os.Open(name)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn nil, err\n\t} else if os.IsNotExist(err) {\n\t\treturn &m, nil\n\t}\n\tdefer f.Close()\n\n\t_, err = toml.DecodeReader(f, &m)\n\n\treturn &m, err\n}"} {"input": "package shiro\n\n\n\nfunc anySliceElementInSlice(slice1, slice2 []string) bool ", "output": "{\n\tfor _, elem1 := range slice1 {\n\t\tfor _, elem2 := range slice2 {\n\t\t\tif elem1 == elem2 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package markdown\n\nimport (\n\t\"strings\"\n)\n\n\n\nvar escaper = newEscaper(\n\t\"*\", \"_\", \"~\", \n\t\"`\", \n\t\"<\", \">\", \"@\", \"#\", \n\t\":\", \n)\n\n\nfunc Escape(s string) string {\n\treturn escaper.Replace(s)\n}\n\nfunc newEscaper(chars ...string) *strings.Replacer ", "output": "{\n\treplacements := []string{}\n\n\tfor _, char := range chars {\n\t\treplacements = append(replacements, char, \"\\\\\"+char)\n\t}\n\n\treturn strings.NewReplacer(replacements...)\n}"} {"input": "package term\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc IsANSI(f *os.File) bool {\n\treturn IsTerminal(f)\n}\n\n\n\n\nfunc MakeRaw(f *os.File) error {\n\treturn stty(f, \"-icanon\", \"-echo\").Run()\n}\n\nfunc Restore(f *os.File) error {\n\treturn stty(f, \"icanon\", \"echo\").Run()\n}\n\nfunc Cols() (int, error) {\n\tcols, err := tput(\"cols\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}\n\nfunc Lines() (int, error) {\n\tcols, err := tput(\"lines\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}\n\n\n\nfunc stty(f *os.File, args ...string) *exec.Cmd {\n\tc := exec.Command(\"stty\", args...)\n\tc.Stdin = f\n\treturn c\n}\n\nfunc tput(what string) (string, error) {\n\tc := exec.Command(\"tput\", what)\n\tc.Stderr = os.Stderr\n\tout, err := c.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.TrimSpace(string(out)), nil\n}\n\nfunc IsTerminal(f *os.File) bool ", "output": "{\n\tcmd := exec.Command(\"test\", \"-t\", \"0\")\n\tcmd.Stdin = f\n\treturn cmd.Run() == nil\n}"} {"input": "package servicetemplate\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/control-center/serviced/domain/servicedefinition\"\n\t\"github.com/control-center/serviced/validation\"\n)\n\n\nfunc (st *ServiceTemplate) ValidEntity() error {\n\tviolations := validation.NewValidationError()\n\tviolations.Add(validation.NotEmpty(\"ServiceTemplate.ID\", st.ID))\n\n\n\tfor _, sd := range st.Services {\n\t\tif err := sd.ValidEntity(); err != nil {\n\t\t\tviolations.Add(err)\n\t\t}\n\t}\n\n\tvhosts := make(map[string]struct{})\n\n\tvisit := func(sd *servicedefinition.ServiceDefinition) error {\n\t\tfor _, ep := range sd.Endpoints {\n\t\t\tfor _, vhost := range ep.VHostList {\n\t\t\t\tif _, found := vhosts[vhost.Name]; found {\n\t\t\t\t\treturn fmt.Errorf(\"duplicate vhost found: %s; ServiceDefintion %s\", vhost.Name, sd)\n\t\t\t\t}\n\t\t\t\tvhosts[vhost.Name] = struct{}{}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tfor _, sd := range st.Services {\n\t\tviolations.Add(servicedefinition.Walk(&sd, visit))\n\t}\n\n\tif len(violations.Errors) > 0 {\n\t\treturn violations\n\t}\n\treturn nil\n}\n\n\n\n\nfunc (st *serviceTemplateWrapper) ValidEntity() error ", "output": "{\n\n\tv := validation.NewValidationError()\n\tv.Add(validation.NotEmpty(\"ID\", st.ID))\n\tv.Add(validation.NotEmpty(\"Name\", st.Name))\n\tv.Add(validation.NotEmpty(\"Data\", st.Data))\n\tif v.HasError() {\n\t\treturn v\n\t}\n\treturn nil\n}"} {"input": "package db\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"time\"\n\n\t\"github.com/boltdb/bolt\"\n\n\t\"github.com/michaelorr/goodall/pkg/metrics\"\n)\n\nfunc Open(path string) (*bolt.DB, error) {\n\treturn bolt.Open(path, 0600, &bolt.Options{Timeout: 1 * time.Second})\n}\n\n\n\nfunc Ftob(f float64) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\terr := binary.Write(buf, binary.BigEndian, f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}\n\nfunc Btof(b []byte) (float64, error) {\n\tvar f float64\n\tbuf := bytes.NewReader(b)\n\terr := binary.Read(buf, binary.BigEndian, &f)\n\tif err != nil {\n\t\treturn f, err\n\t}\n\treturn f, nil\n}\n\nfunc Init(conn *bolt.DB) error ", "output": "{\n\tfor bucket, _ := range metrics.BucketMap {\n\t\terr := conn.Update(func(tx *bolt.Tx) error {\n\t\t\t_, err := tx.CreateBucketIfNotExists([]byte(bucket))\n\t\t\treturn err\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package synctest\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nconst (\n\ttimeout = 100 * time.Millisecond\n)\n\nfunc TestNotifyLock(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tch := nl.NotifyLock()\n\tnl.Lock()\n\tselect {\n\tcase <-ch:\n\tcase <-time.After(timeout):\n\t\tt.Fatalf(\"didn't receive on channel after %s\", timeout)\n\t}\n}\n\nfunc TestNotifyLockAlreadyLocked(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tnl.Lock()\n\tch := nl.NotifyLock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"received on channel\")\n\tcase <-time.After(timeout):\n\t}\n}\n\nfunc TestNotifyLockOnUnlock(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tnl.Lock()\n\tch := nl.NotifyLock()\n\tnl.Unlock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"got a lock notification on unlock\")\n\tcase <-time.After(timeout):\n\t}\n}\n\n\n\nfunc TestNotifyUnlockAlreadyUnlocked(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tnl.Lock()\n\tnl.Unlock()\n\tch := nl.NotifyUnlock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"got unlock notification\")\n\tcase <-time.After(timeout):\n\t}\n}\n\nfunc TestNofifyUnlockOnLock(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tch := nl.NotifyUnlock()\n\tnl.Lock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"got unlock notification on lock\")\n\tcase <-time.After(timeout):\n\t}\n}\n\nfunc TestNotifyUnlock(t *testing.T) ", "output": "{\n\tnl := NewNotifyingLocker()\n\tch := nl.NotifyUnlock()\n\tnl.Lock()\n\tnl.Unlock()\n\tselect {\n\tcase <-ch:\n\tcase <-time.After(timeout):\n\t\tt.Fatalf(\"didn't get unlock notification after %s\", timeout)\n\t}\n}"} {"input": "package data\n\nimport (\n\t\"github.com/juju/errgo\"\n\t\"github.com/shirou/gopsutil/load\"\n)\n\n\n\nfunc Cpu() (Values, error) ", "output": "{\n\tvalues := NewValues()\n\n\tload, err := load.LoadAvg()\n\tif err != nil {\n\t\treturn nil, errgo.Notef(err, \"can not get load values\")\n\t}\n\n\tvalues[\"load.01\"] = load.Load1\n\tvalues[\"load.05\"] = load.Load5\n\tvalues[\"load.15\"] = load.Load15\n\n\treturn values, nil\n}"} {"input": "package gcetasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realAddress Address\n\n\nfunc (o *Address) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realAddress\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = Address(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &Address{}\n\n\nfunc (o *Address) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\n\nfunc (o *Address) SetLifecycle(lifecycle fi.Lifecycle) {\n\to.Lifecycle = &lifecycle\n}\n\nvar _ fi.HasName = &Address{}\n\n\n\n\n\nfunc (o *Address) SetName(name string) {\n\to.Name = &name\n}\n\n\nfunc (o *Address) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *Address) GetName() *string ", "output": "{\n\treturn o.Name\n}"} {"input": "package cabf_br\n\n\n\nimport (\n\t\"testing\"\n\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/test\"\n)\n\n\n\nfunc TestDNSNameNotEmptyLabel(t *testing.T) {\n\tinputPath := \"dnsNameNotEmptyLabel.pem\"\n\texpected := lint.Pass\n\tout := test.TestLint(\"e_dnsname_empty_label\", inputPath)\n\tif out.Status != expected {\n\t\tt.Errorf(\"%s: expected %s, got %s\", inputPath, expected, out.Status)\n\t}\n}\n\nfunc TestDNSNameEmptyLabel(t *testing.T) ", "output": "{\n\tinputPath := \"dnsNameEmptyLabel.pem\"\n\texpected := lint.Error\n\tout := test.TestLint(\"e_dnsname_empty_label\", inputPath)\n\tif out.Status != expected {\n\t\tt.Errorf(\"%s: expected %s, got %s\", inputPath, expected, out.Status)\n\t}\n}"} {"input": "package rand\n\n\nimport \"C\"\n\n\nfunc Random() int {\n\treturn int(C.random())\n}\n\n\n\n\nfunc Seed(i int) ", "output": "{\n\tC.srandom(C.uint(i))\n}"} {"input": "package n3\n\nimport \"testing\"\n\n\n\nfunc TestN3(t *testing.T) {\n\tn := getTestObject()\n\tn.Print()\n\treturn\n}\n\nfunc TestWriteN3(t *testing.T) {\n\tn := getTestObject()\n\tn.WriteN3()\n\treturn\n}\n\nfunc getTestObject() N3 ", "output": "{\n\tn := N3{\n\t\tPrefix: \"http://purl.org/dc/elements/1.1/\",\n\t\tPrefixNS: \"dc\",\n\t\tURI: \"http://en.wikipedia.org/wiki/Tony_Benn\",\n\t\tItems: []N3Element{\n\t\t\tN3Element{\n\t\t\t\tKey: \"title\",\n\t\t\t\tValue: \"Tony Benn\",\n\t\t\t},\n\t\t\tN3Element{\n\t\t\t\tKey: \"publisher\",\n\t\t\t\tValue: \"Wikipedia\",\n\t\t\t},\n\t\t},\n\t}\n\treturn n\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Job struct {\n\tname string\n\ttagName string\n\ttagValue string\n\tlabels map[string]string\n\tport int\n\ttargets []string\n}\n\n\ntype Machine struct {\n\tname string\n\tmetadata map[string]string\n}\n\n\ntype TargetGroups struct {\n\ttargets []*Target\n}\n\n\ntype Target struct {\n\tTargets []string `yaml:\"targets\"\"`\n\tLabels map[string]string `yaml:\"labels\"`\n}\n\n\nfunc (r Machine) String() string {\n\treturn fmt.Sprintf(\"machine: %s, metadata: %s\", r.name, r.metadata)\n}\n\n\nfunc (r TargetGroups) Size() int {\n\treturn len(r.targets)\n}\n\n\n\n\nfunc (r *TargetGroups) AddTarget(name string) *Target ", "output": "{\n\ttarget := &Target{\n\t\tTargets: make([]string, 0),\n\t\tLabels: map[string]string{\n\t\t\t\"job\": name,\n\t\t},\n\t}\n\tr.targets = append(r.targets, target)\n\treturn target\n}"} {"input": "package lints\n\n\n\n\n\nimport (\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/util\"\n)\n\ntype CertPolicyRequiresPersonalName struct{}\n\nfunc (l *CertPolicyRequiresPersonalName) Initialize() error {\n\treturn nil\n}\n\nfunc (l *CertPolicyRequiresPersonalName) CheckApplies(cert *x509.Certificate) bool {\n\treturn util.SliceContainsOID(cert.PolicyIdentifiers, util.BRIndividualValidatedOID) && !util.IsCACert(cert)\n}\n\nfunc (l *CertPolicyRequiresPersonalName) Execute(cert *x509.Certificate) *LintResult {\n\tvar out LintResult\n\tif util.TypeInName(&cert.Subject, util.OrganizationNameOID) || (util.TypeInName(&cert.Subject, util.GivenNameOID) && util.TypeInName(&cert.Subject, util.SurnameOID)) {\n\t\tout.Status = Pass\n\t} else {\n\t\tout.Status = Error\n\t}\n\treturn &out\n}\n\n\n\nfunc init() ", "output": "{\n\tRegisterLint(&Lint{\n\t\tName: \"e_cab_iv_requires_personal_name\",\n\t\tDescription: \"If certificate policy 2.23.140.1.2.3 is included, either organizationName or givenName and surname MUST be included in subject\",\n\t\tCitation: \"BRs: 7.1.6.1\",\n\t\tSource: CABFBaselineRequirements,\n\t\tEffectiveDate: util.CABV131Date,\n\t\tLint: &CertPolicyRequiresPersonalName{},\n\t})\n}"} {"input": "package ecommerce\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/arvindkandhare/goamz/aws\"\n)\n\n\ntype ProductAdvertising struct {\n\tservice aws.Service\n\tassociateTag string\n}\n\n\n\n\n\nfunc (p *ProductAdvertising) PerformOperation(operation string, params map[string]string) (resp *http.Response, err error) {\n\tparams[\"Operation\"] = operation\n\treturn p.query(params)\n}\n\nfunc (p *ProductAdvertising) query(params map[string]string) (resp *http.Response, err error) {\n\tparams[\"Service\"] = \"AWSECommerceService\"\n\tparams[\"AssociateTag\"] = p.associateTag\n\treturn p.service.Query(\"GET\", \"/onca/xml\", params)\n}\n\nfunc New(auth aws.Auth, associateTag string) (p *ProductAdvertising, err error) ", "output": "{\n\tserviceInfo := aws.ServiceInfo{Endpoint: \"https://webservices.amazon.com\", Signer: aws.V2Signature}\n\tif service, err := aws.NewService(auth, serviceInfo); err == nil {\n\t\tp = &ProductAdvertising{*service, associateTag}\n\t}\n\treturn\n}"} {"input": "package binlogplayer\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"vitess.io/vitess/go/sqltypes\"\n)\n\ntype fakeDBClient struct {\n}\n\n\n\nfunc NewFakeDBClient() DBClient {\n\treturn &fakeDBClient{}\n}\n\n\n\nfunc (dc *fakeDBClient) Connect() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Begin() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Commit() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Rollback() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Close() {\n}\n\nfunc (dc *fakeDBClient) ExecuteFetch(query string, maxrows int) (qr *sqltypes.Result, err error) {\n\tquery = strings.ToLower(query)\n\tswitch {\n\tcase strings.HasPrefix(query, \"insert\"):\n\t\treturn &sqltypes.Result{InsertID: 1}, nil\n\tcase strings.HasPrefix(query, \"update\"):\n\t\treturn &sqltypes.Result{RowsAffected: 1}, nil\n\tcase strings.HasPrefix(query, \"delete\"):\n\t\treturn &sqltypes.Result{RowsAffected: 1}, nil\n\tcase strings.HasPrefix(query, \"select\"):\n\t\tif strings.Contains(query, \"where\") {\n\t\t\treturn sqltypes.MakeTestResult(\n\t\t\t\tsqltypes.MakeTestFields(\n\t\t\t\t\t\"id|state|source\",\n\t\t\t\t\t\"int64|varchar|varchar\",\n\t\t\t\t),\n\t\t\t\t`1|Running|keyspace:\"ks\" shard:\"0\" key_range: `,\n\t\t\t), nil\n\t\t}\n\t\treturn &sqltypes.Result{}, nil\n\tcase strings.HasPrefix(query, \"use\"):\n\t\treturn &sqltypes.Result{}, nil\n\t}\n\treturn nil, fmt.Errorf(\"unexpected: %v\", query)\n}\n\nfunc (dc *fakeDBClient) DBName() string ", "output": "{\n\treturn \"db\"\n}"} {"input": "package iso20022\n\n\ntype HighFrequencyTradingProfile1 struct {\n\n\tDate *ISODate `xml:\"Dt,omitempty\"`\n\n\tSettlementFrequency *SettlementFrequency1Choice `xml:\"SttlmFrqcy,omitempty\"`\n\n\tConsolidationType *ConsolidationType1Choice `xml:\"CnsldtnTp,omitempty\"`\n}\n\n\n\nfunc (h *HighFrequencyTradingProfile1) AddSettlementFrequency() *SettlementFrequency1Choice {\n\th.SettlementFrequency = new(SettlementFrequency1Choice)\n\treturn h.SettlementFrequency\n}\n\nfunc (h *HighFrequencyTradingProfile1) AddConsolidationType() *ConsolidationType1Choice {\n\th.ConsolidationType = new(ConsolidationType1Choice)\n\treturn h.ConsolidationType\n}\n\nfunc (h *HighFrequencyTradingProfile1) SetDate(value string) ", "output": "{\n\th.Date = (*ISODate)(&value)\n}"} {"input": "package clients\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"cloud.google.com/go/pubsub\"\n)\n\n\ntype PubSub struct {\n\tclient *pubsub.Client\n}\n\n\nfunc NewPubSub(ctx context.Context, projectID string) (*PubSub, error) {\n\tclient, err := pubsub.NewClient(ctx, projectID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to init pubsub: %q\", err)\n\t}\n\treturn &PubSub{client: client}, nil\n}\n\n\n\n\n\nfunc (p *PubSub) Publish(ctx context.Context, topic *pubsub.Topic, message *pubsub.Message) (string, error) {\n\tdefer topic.Stop()\n\treturn topic.Publish(ctx, message).Get(ctx)\n}\n\nfunc (p *PubSub) Topic(id string) *pubsub.Topic ", "output": "{\n\treturn p.client.Topic(id)\n}"} {"input": "package version\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype Command struct {\n\tName string\n\tW io.Writer\n\tWErr io.Writer\n\tAppName string\n\tAppVersion string\n\tGitCommit string\n}\n\n\n\n\n\nfunc (c *Command) Key() string {\n\treturn c.Name\n}\n\n\n\nfunc (c *Command) Aliases() map[string]struct{} {\n\treturn map[string]struct{}{\n\t\t\"version\": struct{}{},\n\t}\n}\n\n\nfunc (c *Command) Description() string {\n\treturn \"Print the version.\"\n}\n\nfunc (c *Command) Run(args []string) (int, error) ", "output": "{\n\tfmt.Fprintln(c.W, c.AppName, c.AppVersion, c.GitCommit)\n\treturn 0, nil\n}"} {"input": "package process\n\nimport (\n\t\"net\"\n\t\"strconv\"\n)\n\nconst (\n\tMIN_PORT = 50000\n\tMAX_PORT = 60000\n\tINVALID_PORT = -1\n)\n\n\n\n\n\nfunc isPortUsed(port int) bool {\n\tconn, err := net.Dial(\"tcp\", net.JoinHostPort(\"localhost\", strconv.Itoa(port)))\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tdefer conn.Close()\n\n\treturn true\n}\n\nfunc GetAvailablePort() (int, bool) ", "output": "{\n\tfor port := MIN_PORT; port <= MAX_PORT; port++ {\n\t\tif !isPortUsed(port) {\n\t\t\treturn port, true\n\t\t}\n\t}\n\n\treturn INVALID_PORT, false\n}"} {"input": "package util\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"path\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n\nfunc getProtoAndAdd(target string) (string, string) {\n\treg := `(?i)^((?:(?:tcp|udp|ip)[46]?)|` + `(?:unix(?:gram|packet)?)):(.+)$`\n\tt := regexp.MustCompile(reg).FindStringSubmatch(target)\n\treturn t[1], t[2]\n}\n\nfunc PathExists(path string) (bool, error) {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true, nil\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\treturn false, err\n}\n\n\nfunc getCSIEndPoint(csiEndpoint string) (string, error) {\n\tcsiEndpoint = strings.TrimSpace(csiEndpoint)\n\n\tif csiEndpoint == \"\" {\n\t\terr := errors.New(\"csi endpoint is empty\")\n\t\tlog.Fatalf(\"%v\", err)\n\t\treturn csiEndpoint, err\n\t}\n\n\treturn csiEndpoint, nil\n}\n\n\n\n\n\nfunc Contained(obj, target interface{}) bool {\n\ttargetValue := reflect.ValueOf(target)\n\tswitch reflect.TypeOf(target).Kind() {\n\tcase reflect.Slice, reflect.Array:\n\t\tfor i := 0; i < targetValue.Len(); i++ {\n\t\t\tif targetValue.Index(i).Interface() == obj {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\tcase reflect.Map:\n\t\tif targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {\n\t\t\treturn true\n\t\t}\n\tdefault:\n\t\treturn false\n\t}\n\treturn false\n}\n\nfunc GetCSIEndPointListener(csiEndpoint string) (net.Listener, error) ", "output": "{\n\ttarget, err := getCSIEndPoint(csiEndpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tproto, addr := getProtoAndAdd(target)\n\n\tlog.Printf(\"proto: %s addr: %s\", proto, addr)\n\tif strings.HasPrefix(proto, \"unix\") {\n\t\tos.RemoveAll(addr)\n\t\tlog.Printf(\"remove sock file: %s\", addr)\n\t\tdir := path.Dir(addr)\n\t\tif exist, _ := PathExists(dir); !exist {\n\t\t\tos.MkdirAll(dir, 0755)\n\t\t}\n\t}\n\n\treturn net.Listen(proto, addr)\n}"} {"input": "package rpcclient\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\n\t\"github.com/decred/dcrd/dcrjson/v4\"\n)\n\n\n\ntype FutureRawResult cmdRes\n\n\n\nfunc (r *FutureRawResult) Receive() (json.RawMessage, error) {\n\treturn receiveFuture(r.ctx, r.c)\n}\n\n\n\n\n\n\nfunc (c *Client) RawRequestAsync(ctx context.Context, method string, params []json.RawMessage) *FutureRawResult {\n\tif method == \"\" {\n\t\treturn (*FutureRawResult)(newFutureError(ctx, errors.New(\"no method\")))\n\t}\n\n\tif params == nil {\n\t\tparams = []json.RawMessage{}\n\t}\n\n\tid := c.NextID()\n\trawRequest := &dcrjson.Request{\n\t\tJsonrpc: \"1.0\",\n\t\tID: id,\n\t\tMethod: method,\n\t\tParams: params,\n\t}\n\tmarshalledJSON, err := json.Marshal(rawRequest)\n\tif err != nil {\n\t\treturn (*FutureRawResult)(newFutureError(ctx, err))\n\t}\n\n\tresponseChan := make(chan *response, 1)\n\tjReq := &jsonRequest{\n\t\tid: id,\n\t\tmethod: method,\n\t\tcmd: nil,\n\t\tmarshalledJSON: marshalledJSON,\n\t\tresponseChan: responseChan,\n\t}\n\tc.sendRequest(ctx, jReq)\n\n\treturn &FutureRawResult{ctx: ctx, c: responseChan}\n}\n\n\n\n\n\n\n\n\nfunc (c *Client) RawRequest(ctx context.Context, method string, params []json.RawMessage) (json.RawMessage, error) ", "output": "{\n\treturn c.RawRequestAsync(ctx, method, params).Receive()\n}"} {"input": "package http\n\nimport (\n\t\"net\"\n\t\"time\"\n)\n\n\ntype TimeoutConn struct {\n\tQuirkConn\n\treadTimeout time.Duration\n\twriteTimeout time.Duration\n}\n\n\n\nfunc (c *TimeoutConn) setWriteTimeout() {\n\tif c.writeTimeout != 0 {\n\t\tc.SetWriteDeadline(time.Now().UTC().Add(c.writeTimeout))\n\t}\n}\n\n\nfunc (c *TimeoutConn) Read(b []byte) (n int, err error) {\n\tc.setReadTimeout()\n\treturn c.Conn.Read(b)\n}\n\n\nfunc (c *TimeoutConn) Write(b []byte) (n int, err error) {\n\tc.setWriteTimeout()\n\treturn c.Conn.Write(b)\n}\n\n\nfunc NewTimeoutConn(c net.Conn, readTimeout, writeTimeout time.Duration) *TimeoutConn {\n\treturn &TimeoutConn{\n\t\tQuirkConn: QuirkConn{Conn: c},\n\t\treadTimeout: readTimeout,\n\t\twriteTimeout: writeTimeout,\n\t}\n}\n\nfunc (c *TimeoutConn) setReadTimeout() ", "output": "{\n\tif c.readTimeout != 0 && c.canSetReadDeadline() {\n\t\tc.SetReadDeadline(time.Now().UTC().Add(c.readTimeout))\n\t}\n}"} {"input": "package models\n\nimport \"time\"\n\n\ntype KeyType struct {\n\tID int\n\tKey string\n\tCreated time.Time\n\tExpires bool\n}\n\n\ntype Keys []KeyType\n\nfunc (f Keys) Len() int {\n\treturn len(f)\n}\n\nfunc (f Keys) Less(i, j int) bool {\n\treturn f[i].ID < f[j].ID\n}\n\n\n\nfunc (f Keys) Swap(i, j int) ", "output": "{\n\tf[i], f[j] = f[j], f[i]\n}"} {"input": "package tools\n\nimport (\n\t\"strings\"\n\t\"unicode/utf8\"\n)\n\nconst LANG_EN = \"eng\"\nconst LANG_FR = \"fre\"\n\n\n\n\n\nfunc iso88591ToUtf8(iso88591 []byte) string {\n\tbuf := make([]rune, len(iso88591))\n\tfor i, b := range iso88591 {\n\t\tbuf[i] = rune(b)\n\t}\n\treturn string(buf)\n}\n\nfunc TryToUtf8(s string, lang string) string ", "output": "{\n\n\tvar b = []byte(s)\n\n\tswitch lang {\n\tcase LANG_EN: \n\t\treturn s\n\tcase LANG_FR: \n\t\tif !utf8.Valid(b) || strings.Count(s, string([]byte{0xef, 0xbf, 0xbd})) > 0 {\n\t\t\treturn iso88591ToUtf8(b)\n\t\t}\n\t}\n\treturn s\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\ntype SystemSettings struct {\n\tuserStreamAcl *StreamAcl\n\tsystemStreamAcl *StreamAcl\n}\n\nfunc NewSystemSettings(\n\tuserStreamAcl *StreamAcl,\n\tsystemStreamAcl *StreamAcl,\n) *SystemSettings {\n\treturn &SystemSettings{userStreamAcl, systemStreamAcl}\n}\n\nfunc (s *SystemSettings) UserStreamAcl() *StreamAcl { return s.userStreamAcl }\n\nfunc (s *SystemSettings) SystemStreamAcl() *StreamAcl { return s.systemStreamAcl }\n\nfunc (s *SystemSettings) String() string {\n\treturn fmt.Sprintf(\"&{userStreamAcl:%+v systemStreamAcl:%+v}\", s.userStreamAcl, s.systemStreamAcl)\n}\n\ntype systemSettingsJson struct {\n\tUserStreamAcl *StreamAcl `json:\"$userStreamAcl,omitempty\"`\n\tSystemStreamAcl *StreamAcl `json:\"$systemStreamAcl,omitempty\"`\n}\n\nfunc (s *SystemSettings) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(systemSettingsJson{\n\t\tUserStreamAcl: s.userStreamAcl,\n\t\tSystemStreamAcl: s.systemStreamAcl,\n\t})\n}\n\nfunc (s *SystemSettings) UnmarshalJSON(data []byte) error {\n\tss := systemSettingsJson{}\n\tif err := json.Unmarshal(data, &ss); err != nil {\n\t\treturn err\n\t}\n\ts.userStreamAcl = ss.UserStreamAcl\n\ts.systemStreamAcl = ss.SystemStreamAcl\n\treturn nil\n}\n\n\n\nfunc SystemSettingsFromJsonBytes(data []byte) (*SystemSettings, error) ", "output": "{\n\tsystemSettings := &SystemSettings{}\n\treturn systemSettings, json.Unmarshal(data, systemSettings)\n}"} {"input": "package twofactor\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/base32\"\n)\n\n\ntype Secret string\n\n\n\n\n\n\nfunc (s Secret) Bytes() ([]byte, error) {\n\treturn base32.StdEncoding.DecodeString(s.String())\n}\n\n\nfunc (s Secret) String() string {\n\treturn string(s)\n}\n\n\nfunc Int64ToBytes(n int64) []byte {\n\tb := make([]byte, 8)\n\tfor i := len(b) - 1; i >= 0; i-- {\n\t\tb[i] = byte(n & 0xff)\n\t\tn = n >> 8\n\t}\n\treturn b\n}\n\nfunc NewSecret(length int) (Secret, error) ", "output": "{\n\tif length <= 0 {\n\t\tlength = 10\n\t}\n\tb := make([]byte, length)\n\t_, err := rand.Read(b)\n\treturn Secret(base32.StdEncoding.EncodeToString(b)), err\n}"} {"input": "package ostore\n\nimport (\n\t\"crypto/sha512\"\n\t\"encoding/hex\"\n\t\"hash\"\n\t\"io\"\n)\n\ntype HashReader struct {\n\th hash.Hash\n\tr io.Reader\n}\n\nfunc NewHashReader(r io.Reader) *HashReader {\n\treturn &HashReader{sha512.New(), r}\n}\n\n\n\nfunc (hr *HashReader) Digest() []byte {\n\treturn hr.h.Sum(nil)\n}\n\nfunc (hr *HashReader) HexDigest() string {\n\treturn hex.EncodeToString(hr.Digest())\n}\n\nfunc (hr *HashReader) Read(p []byte) (int, error) ", "output": "{\n\tn, err := hr.r.Read(p)\n\tif err != nil {\n\t\treturn n, err\n\t}\n\twn := 0\n\ttn := 0\n\tfor wn, err = hr.h.Write(p[:n]); err != nil && wn < n; {\n\t\ttn, err = hr.h.Write(p[wn:n])\n\t\twn += tn\n\t}\n\treturn n, err\n}"} {"input": "package command\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/bitrise-io/go-utils/pathutil\"\n)\n\n\n\n\n\nfunc CopyDir(src, dst string, isOnlyContent bool) error {\n\tif isOnlyContent && !strings.HasSuffix(src, \"/\") {\n\t\tsrc = src + \"/\"\n\t}\n\targs := []string{\"-ar\", src, dst}\n\treturn RunCommand(\"rsync\", args...)\n}\n\n\nfunc RemoveDir(dirPth string) error {\n\tif exist, err := pathutil.IsPathExists(dirPth); err != nil {\n\t\treturn err\n\t} else if exist {\n\t\tif err := os.RemoveAll(dirPth); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc RemoveFile(pth string) error {\n\tif exist, err := pathutil.IsPathExists(pth); err != nil {\n\t\treturn err\n\t} else if exist {\n\t\tif err := os.Remove(pth); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc CopyFile(src, dst string) error ", "output": "{\n\tisDir, err := pathutil.IsDirExists(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isDir {\n\t\treturn errors.New(\"Source is a directory: \" + src)\n\t}\n\targs := []string{src, dst}\n\treturn RunCommand(\"rsync\", args...)\n}"} {"input": "package verboten\n\nimport (\n\t\"github.com/reiver/gogen-optiontype/driver\"\n\t\"github.com/reiver/gogen-optiontype/drivers/shared\"\n)\n\n\n\n\nfunc init() ", "output": "{\n\tconst typeName = \"string\"\n\tconst fileName = \"gen_type_unmarshaljson_string_test.go\"\n\n\trenderer := gendriver.DefaultRenderer{\n\t\tFileName: fileName,\n\t\tFileTmpl: shared.TypeUnmarshaljsonStringTestTmpl,\n\t}\n\n\n\tif err := gendriver.Registry.Register(typeName, true, renderer); nil != err {\n\t\tpanic(err)\n\t}\n}"} {"input": "package definitions\n\n\n\ntype defPeerFingerprints struct{}\n\nfunc (*defPeerFingerprints) String() string {\n\treturn `\n \n Peer fingerprints\n \n \n \n 10\n false\n GTK_ORIENTATION_VERTICAL\n \n \n \n \n \n 15\n 10\n 10\n 10\n 12\n 6\n \n \n \n \n GTK_ORIENTATION_HORIZONTAL\n \n \n _OK\n True\n \n \n \n \n \n \n \n \n\n`\n}\n\nfunc init() ", "output": "{\n\tadd(`PeerFingerprints`, &defPeerFingerprints{})\n}"} {"input": "package fake\n\nimport (\n\t\"k8s.io/kubernetes/pkg/client/restclient\"\n\t\"k8s.io/kubernetes/pkg/client/testing/core\"\n)\n\n\n\nfunc (c *FakeServices) ProxyGet(scheme, name, port, path string, params map[string]string) restclient.ResponseWrapper ", "output": "{\n\treturn c.Fake.InvokesProxy(core.NewProxyGetAction(servicesResource, c.ns, scheme, name, port, path, params))\n}"} {"input": "package mocks\n\nimport common \"github.com/hyperledger/fabric-protos-go/common\"\nimport errors \"github.com/hyperledger/fabric/common/errors\"\nimport mock \"github.com/stretchr/testify/mock\"\nimport peer \"github.com/hyperledger/fabric-protos-go/peer\"\n\n\ntype StateBasedValidator struct {\n\tmock.Mock\n}\n\n\n\n\n\nfunc (_m *StateBasedValidator) PreValidate(txNum uint64, block *common.Block) {\n\t_m.Called(txNum, block)\n}\n\n\nfunc (_m *StateBasedValidator) Validate(cc string, blockNum uint64, txNum uint64, rwset []byte, prp []byte, ep []byte, endorsements []*peer.Endorsement) errors.TxValidationError {\n\tret := _m.Called(cc, blockNum, txNum, rwset, prp, ep, endorsements)\n\n\tvar r0 errors.TxValidationError\n\tif rf, ok := ret.Get(0).(func(string, uint64, uint64, []byte, []byte, []byte, []*peer.Endorsement) errors.TxValidationError); ok {\n\t\tr0 = rf(cc, blockNum, txNum, rwset, prp, ep, endorsements)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(errors.TxValidationError)\n\t\t}\n\t}\n\n\treturn r0\n}\n\nfunc (_m *StateBasedValidator) PostValidate(cc string, blockNum uint64, txNum uint64, err error) ", "output": "{\n\t_m.Called(cc, blockNum, txNum, err)\n}"} {"input": "package storage\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/rynorris/website/server/site\"\n\t\"github.com/rynorris/website/server/storage\"\n)\n\nconst dummyKey = \"site-configuration\"\n\ntype Service struct {\n\tstorage storage.Service\n}\n\n\n\nfunc (s *Service) Get() (site.Site, error) {\n\tsite := site.Site{}\n\n\tblob, err := s.storage.Get(dummyKey)\n\tif err != nil {\n\t\treturn site, err\n\t}\n\n\terr = json.Unmarshal(blob, &site)\n\n\treturn site, err\n}\n\nfunc (s *Service) Put(site site.Site) error {\n\tblob, err := json.Marshal(site)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.storage.Put(dummyKey, blob)\n}\n\nfunc NewService(storage storage.Service) *Service ", "output": "{\n\treturn &Service{\n\t\tstorage: storage,\n\t}\n}"} {"input": "package balancetransaction\n\nimport (\n\t\"net/http\"\n\n\tstripe \"github.com/stripe/stripe-go\"\n\t\"github.com/stripe/stripe-go/form\"\n)\n\n\ntype Client struct {\n\tB stripe.Backend\n\tKey string\n}\n\n\nfunc Get(id string, params *stripe.BalanceTransactionParams) (*stripe.BalanceTransaction, error) {\n\treturn getC().Get(id, params)\n}\n\n\nfunc (c Client) Get(id string, params *stripe.BalanceTransactionParams) (*stripe.BalanceTransaction, error) {\n\tpath := stripe.FormatURLPath(\"/v1/balance_transactions/%s\", id)\n\ttransaction := &stripe.BalanceTransaction{}\n\terr := c.B.Call(http.MethodGet, path, c.Key, params, transaction)\n\treturn transaction, err\n}\n\n\nfunc List(params *stripe.BalanceTransactionListParams) *Iter {\n\treturn getC().List(params)\n}\n\n\nfunc (c Client) List(listParams *stripe.BalanceTransactionListParams) *Iter {\n\treturn &Iter{stripe.GetIter(listParams, func(p *stripe.Params, b *form.Values) ([]interface{}, stripe.ListMeta, error) {\n\t\tlist := &stripe.BalanceTransactionList{}\n\t\terr := c.B.CallRaw(http.MethodGet, \"/v1/balance_transactions\", c.Key, b, p, list)\n\n\t\tret := make([]interface{}, len(list.Data))\n\t\tfor i, v := range list.Data {\n\t\t\tret[i] = v\n\t\t}\n\n\t\treturn ret, list.ListMeta, err\n\t})}\n}\n\n\ntype Iter struct {\n\t*stripe.Iter\n}\n\n\nfunc (i *Iter) BalanceTransaction() *stripe.BalanceTransaction {\n\treturn i.Current().(*stripe.BalanceTransaction)\n}\n\n\n\nfunc getC() Client ", "output": "{\n\treturn Client{stripe.GetBackend(stripe.APIBackend), stripe.Key}\n}"} {"input": "package ringbuffer\n\n\ntype SequenceManager struct {\n\tLeader *SeqSimple\n\tFollower *SeqSimple\n}\n\n\n\n\nfunc SequenceManagerNew(size int64) *SequenceManager ", "output": "{\n\tm := &SequenceManager{\n\t\tLeader: SeqSimpleNew(size, nil, true),\n\t\tFollower: SeqSimpleNew(size, nil, false),\n\t}\n\n\tm.Leader.SetDependency(m.Follower)\n\tm.Follower.SetDependency(m.Leader)\n\treturn m\n}"} {"input": "package MySQLProtocol\n\nimport \"testing\"\nimport \"github.com/stretchr/testify/assert\"\n\nvar COM_STMT_FETCH_test_packets = []struct {\n\tpacket Proto\n\tcontext Context\n}{\n\t{packet: Proto{data: StringToPacket(`\n09 00 00 00 1c 00 00 00 00 00 00 00 00\n`)}, context: Context{}},\n}\n\nfunc Test_Packet_COM_STMT_FETCH(t *testing.T) {\n\tvar pkt Packet_COM_STMT_FETCH\n\tfor _, value := range COM_STMT_FETCH_test_packets {\n\t\tpkt = Packet_COM_STMT_FETCH{}\n\t\tpkt.FromPacket(value.context, value.packet)\n\t\tassert.Equal(t, pkt.ToPacket(value.context), value.packet.data, \"\")\n\t}\n}\n\nfunc Benchmark_Packet_COM_STMT_FETCH_FromPacket(b *testing.B) {\n\tcontext := COM_STMT_FETCH_test_packets[0].context\n\tpacket := COM_STMT_FETCH_test_packets[0].packet\n\tpkt := Packet_COM_STMT_FETCH{}\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tpacket.offset = 0\n\t\tpkt.FromPacket(context, packet)\n\t}\n}\n\n\n\nfunc Benchmark_Packet_COM_STMT_FETCH_ToPacket(b *testing.B) {\n\tcontext := COM_STMT_FETCH_test_packets[0].context\n\tpkt := Packet_COM_STMT_FETCH{}\n\tpkt.FromPacket(context, COM_STMT_FETCH_test_packets[0].packet)\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt.ToPacket(context)\n\t}\n}\n\nfunc Benchmark_Packet_COM_STMT_FETCH_GetPacketSize(b *testing.B) ", "output": "{\n\tcontext := COM_STMT_FETCH_test_packets[0].context\n\tpkt := Packet_COM_STMT_FETCH{}\n\tpkt.FromPacket(context, COM_STMT_FETCH_test_packets[0].packet)\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt.GetPacketSize(context)\n\t}\n}"} {"input": "package help\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\ntype EvtPool struct {\n\theader DListNode\n}\n\nfunc (this *EvtPool) Init() {\n\tthis.header.Init(nil)\n}\n\nfunc (this *EvtPool) Eat(name string) {\n\tfmt.Printf(\"吃%s\\n\", name)\n}\n\nfunc (this *EvtPool) Post(d IEvent) bool {\n\n\tn := &DListNode{}\n\tn.Init(d)\n\n\tif !d.AddNode(n) {\n\t\treturn false\n\t}\n\n\told_pre := this.header.Pre\n\n\tthis.header.Pre = n\n\tn.Next = &this.header\n\tn.Pre = old_pre\n\told_pre.Next = n\n\n\treturn true\n}\n\n\n\ntype Evt_eat struct {\n\tEvt_base\n\tFoodName string\n}\n\nfunc (this *Evt_eat) Exec() bool {\n\treturn true\n}\n\nfunc TestDlist(t *testing.T) {\n\n\tvar g_Pool EvtPool\n\tg_Pool.Init()\n\n\tg_Pool.Post(&Evt_eat{FoodName: \"西瓜\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"葡萄\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"黄瓜\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"大蒜\"})\n\n\tg_Pool.Run()\n}\n\nfunc (this *EvtPool) Run() ", "output": "{\n\tfor {\n\t\tif this.header.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\n\t\tn := this.header.Next\n\n\t\tn.Data.(IEvent).Exec(this)\n\n\t\tn.Data.(IEvent).Destroy()\n\t}\n}"} {"input": "package postik\n\nvar hash Hasher\n\ntype Hasher func(string) string\n\n\n\nfunc ReplaceHasher(hasher Hasher) {\n\n\thash = hasher\n}\n\nfunc init() ", "output": "{\n\n\thash = func(name string) string {\n\n\t\treturn name\n\t}\n}"} {"input": "package layers\n\nimport (\n\t\"math\"\n\n\t\"github.com/gerardabello/weight\"\n\t\"github.com/gerardabello/weight/tensor\"\n)\n\ntype SigmoidLayer struct {\n\tBaseLayer\n}\n\nfunc NewSigmoidLayer(size ...int) *SigmoidLayer {\n\tlayer := &SigmoidLayer{}\n\tlayer.BaseLayer.Init(size, size)\n\treturn layer\n}\n\n\n\nfunc (l *SigmoidLayer) Activate(input *tensor.Tensor) (*tensor.Tensor, error) {\n\tl.mutex.Lock()\n\terr := l.BaseLayer.Activate(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinputs := input.Values\n\n\tfor i := range l.output.Values {\n\t\tl.output.Values[i] = 1 / (1 + math.Exp(-inputs[i]))\n\t}\n\n\tl.mutex.Unlock()\n\treturn &l.output, nil\n}\n\nfunc (l *SigmoidLayer) BackPropagate(err *tensor.Tensor) (*tensor.Tensor, error) {\n\tl.mutex.Lock()\n\te := l.BaseLayer.BackPropagate(err)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\n\terrs := err.Values\n\tinputs := l.lastInput.Values\n\n\tfor i := range l.propagation.Values {\n\t\tl.propagation.Values[i] = math.Exp(-inputs[i]) / math.Pow(1+math.Exp(-inputs[i]), 2) * errs[i]\n\t}\n\n\tl.mutex.Unlock()\n\treturn &l.propagation, nil\n}\n\nfunc (l *SigmoidLayer) CreateSlave() weight.Layer ", "output": "{\n\tnl := NewSigmoidLayer(l.GetInputSize()...)\n\tnl.id = l.ID()\n\n\treturn nl\n}"} {"input": "package eav\n\ntype (\n\tAttributeFrontendModeller interface {\n\t\tInputRenderer() FrontendInputRendererIFace\n\t\tGetValue()\n\t\tGetInputType() string\n\n\t\tConfig(...AttributeFrontendConfig) AttributeFrontendModeller\n\t}\n\tFrontendInputRendererIFace interface {\n\t}\n\tAttributeFrontend struct {\n\t\ta *Attribute\n\t\tidx AttributeIndex\n\t}\n\tAttributeFrontendConfig func(*AttributeFrontend)\n)\n\nvar _ AttributeFrontendModeller = (*AttributeFrontend)(nil)\n\n\nfunc NewAttributeFrontend(cfgs ...AttributeFrontendConfig) *AttributeFrontend {\n\tas := &AttributeFrontend{\n\t\ta: nil,\n\t}\n\tas.Config(cfgs...)\n\treturn as\n}\n\n\nfunc AttributeFrontendIdx(i AttributeIndex) AttributeFrontendConfig {\n\treturn func(as *AttributeFrontend) {\n\t\tas.idx = i\n\t}\n}\n\n\nfunc (af *AttributeFrontend) Config(configs ...AttributeFrontendConfig) AttributeFrontendModeller {\n\tfor _, cfg := range configs {\n\t\tcfg(af)\n\t}\n\treturn af\n}\n\nfunc (af *AttributeFrontend) InputRenderer() FrontendInputRendererIFace { return nil }\nfunc (af *AttributeFrontend) GetValue() {}\n\n\nfunc (af *AttributeFrontend) GetInputType() string ", "output": "{\n\treturn af.a.FrontendInput()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"path\"\n\n\t\"github.com/emicklei/go-restful\"\n)\n\n\n\n\n\n\n\n\n\nvar rootdir = \"/tmp\"\n\nfunc main() {\n\trestful.DefaultContainer.Router(restful.CurlyRouter{})\n\n\tws := new(restful.WebService)\n\tws.Route(ws.GET(\"/static/{subpath:*}\").To(staticFromPathParam))\n\tws.Route(ws.GET(\"/static\").To(staticFromQueryParam))\n\trestful.Add(ws)\n\n\tprintln(\"[go-restful] serving files on http:localhost:8080/static from local /tmp\")\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\n\n\nfunc staticFromQueryParam(req *restful.Request, resp *restful.Response) {\n\thttp.ServeFile(\n\t\tresp.ResponseWriter,\n\t\treq.Request,\n\t\tpath.Join(rootdir, req.QueryParameter(\"resource\")))\n}\n\nfunc staticFromPathParam(req *restful.Request, resp *restful.Response) ", "output": "{\n\tactual := path.Join(rootdir, req.PathParameter(\"subpath\"))\n\tfmt.Printf(\"serving %s ... (from %s)\\n\", actual, req.PathParameter(\"subpath\"))\n\thttp.ServeFile(\n\t\tresp.ResponseWriter,\n\t\treq.Request,\n\t\tactual)\n}"} {"input": "package utilities\n\nimport (\n\t\"testing\"\n)\n\n\n\n\n\nfunc AssertNoPanic(t *testing.T, f func()) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tt.Errorf(\"The code did panic\")\n\t\t}\n\t}()\n\tf()\n}\n\nfunc AssertPanic(t *testing.T, f func()) ", "output": "{\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"The code did not panic\")\n\t\t}\n\t}()\n\tf()\n}"} {"input": "package references\n\nimport (\n\t\"github.com/zxh0/jvm.go/instructions/base\"\n\t\"github.com/zxh0/jvm.go/rtda\"\n\t\"github.com/zxh0/jvm.go/rtda/heap\"\n)\n\n\ntype New struct {\n\tbase.Index16Instruction\n\tclass *heap.Class\n}\n\n\n\nfunc (instr *New) Execute(frame *rtda.Frame) ", "output": "{\n\tif instr.class == nil {\n\t\tcp := frame.GetConstantPool()\n\t\tkClass := cp.GetConstantClass(instr.Index)\n\t\tinstr.class = kClass.GetClass()\n\t}\n\n\tif instr.class.InitializationNotStarted() {\n\t\tframe.RevertNextPC() \n\t\tframe.Thread.InitClass(instr.class)\n\t\treturn\n\t}\n\n\tref := instr.class.NewObj()\n\tframe.PushRef(ref)\n}"} {"input": "package cert\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/juliengk/go-utils\"\n\t\"github.com/spf13/cobra\"\n)\n\nfunc newRenewCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"renew [name]\",\n\t\tShort: \"Renew Docker client certificate\",\n\t\tLong: renewDescription,\n\t\tRun: runRenew,\n\t}\n\n\treturn cmd\n}\n\n\n\nvar renewDescription = `\nRenew Docker client certificate\n\n`\n\nfunc runRenew(cmd *cobra.Command, args []string) ", "output": "{\n\tif len(args) < 1 || len(args) > 1 {\n\t\tcmd.Usage()\n\t\tos.Exit(-1)\n\t}\n\n\tutils.Exit(fmt.Errorf(\"Not implemented yet\"))\n}"} {"input": "package iso20022\n\n\ntype TaxDetails struct {\n\n\tCertificateIdentification *Max35Text `xml:\"CertId,omitempty\"`\n\n\tTaxType *TaxType `xml:\"TaxTp,omitempty\"`\n}\n\nfunc (t *TaxDetails) SetCertificateIdentification(value string) {\n\tt.CertificateIdentification = (*Max35Text)(&value)\n}\n\n\n\nfunc (t *TaxDetails) AddTaxType() *TaxType ", "output": "{\n\tt.TaxType = new(TaxType)\n\treturn t.TaxType\n}"} {"input": "package collector\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/log\"\n)\n\n\nimport \"C\"\n\ntype loadavgCollector struct {\n\tmetric prometheus.Gauge\n}\n\nfunc init() {\n\tFactories[\"loadavg\"] = NewLoadavgCollector\n}\n\n\n\nfunc NewLoadavgCollector() (Collector, error) {\n\treturn &loadavgCollector{\n\t\tmetric: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tNamespace: Namespace,\n\t\t\tName: \"load1\",\n\t\t\tHelp: \"1m load average.\",\n\t\t}),\n\t}, nil\n}\n\nfunc (c *loadavgCollector) Update(ch chan<- prometheus.Metric) (err error) {\n\tload, err := getLoad1()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Couldn't get load: %s\", err)\n\t}\n\tlog.Debugf(\"Set node_load: %f\", load)\n\tc.metric.Set(load)\n\tc.metric.Collect(ch)\n\treturn err\n}\n\n\n\nfunc getLoad1() (float64, error) ", "output": "{\n\tvar loadavg [1]C.double\n\tsamples := C.getloadavg(&loadavg[0], 1)\n\tif samples > 0 {\n\t\treturn float64(loadavg[0]), nil\n\t} else {\n\t\treturn 0, errors.New(\"failed to get load average\")\n\t}\n\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/apier/v1\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdRemoveBalance{\n\t\tname: \"balance_remove\",\n\t\trpcMethod: \"ApierV1.RemoveBalances\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdRemoveBalance struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrAddBalance\n\t*CommandExecuter\n}\n\nfunc (self *CmdRemoveBalance) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdRemoveBalance) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\n\n\nfunc (self *CmdRemoveBalance) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdRemoveBalance) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *CmdRemoveBalance) RpcParams(reset bool) interface{} ", "output": "{\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrAddBalance{BalanceType: utils.MONETARY, Overwrite: false}\n\t}\n\treturn self.rpcParams\n}"} {"input": "package containerengine\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListWorkRequestLogsRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tWorkRequestId *string `mandatory:\"true\" contributesTo:\"path\" name:\"workRequestId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListWorkRequestLogsRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request ListWorkRequestLogsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ListWorkRequestLogsRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListWorkRequestLogsResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []WorkRequestLogEntry `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ListWorkRequestLogsResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListWorkRequestLogsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListWorkRequestLogsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}"} {"input": "package anime\n\nimport (\n\t\"fmt\"\n\n\t\"bitbucket.org/ikeikeikeike/antenna/ormapper\"\n\t\"github.com/jinzhu/gorm\"\n)\n\n\n\n\n\nfunc FilterNameKana(words []string) func(db *gorm.DB) *gorm.DB {\n\treturn func(db *gorm.DB) *gorm.DB {\n\t\tfor _, word := range words {\n\t\t\tif word != \"\" {\n\t\t\t\tw := fmt.Sprintf(\"%%%s%%\", word)\n\t\t\t\tdb = db.Where(\"anime.name like ? OR anime.kana like ?\", w, w)\n\t\t\t}\n\t\t}\n\t\treturn db\n\t}\n}\n\nfunc FilterPrefixLines(line string) func(db *gorm.DB) *gorm.DB {\n\treturn func(db *gorm.DB) *gorm.DB {\n\t\tif line != \"\" {\n\t\t\tin, ok := ormapper.PrefixLines[line]\n\t\t\tif ok {\n\t\t\t\tdb = db.Where(\"anime.gyou in (?)\", in)\n\t\t\t}\n\t\t}\n\t\treturn db\n\t}\n}\n\nfunc PictureCountMoreThanZero(db *gorm.DB) *gorm.DB ", "output": "{\n\treturn db.Where(\"anime.pictures_count > ?\", 0)\n}"} {"input": "package expvar\n\nimport (\n\t\"expvar\"\n\t\"runtime\"\n\t\"sync\"\n\n\t\"github.com/mholt/caddy\"\n\t\"github.com/mholt/caddy/caddyhttp/httpserver\"\n)\n\nfunc init() {\n\tcaddy.RegisterPlugin(\"expvar\", caddy.Plugin{\n\t\tServerType: \"http\",\n\t\tAction: setup,\n\t})\n}\n\n\nfunc setup(c *caddy.Controller) error {\n\tresource, err := expVarParse(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpublishExtraVars()\n\n\tev := ExpVar{Resource: resource}\n\n\thttpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {\n\t\tev.Next = next\n\t\treturn ev\n\t})\n\n\treturn nil\n}\n\nfunc expVarParse(c *caddy.Controller) (Resource, error) {\n\tvar resource Resource\n\tvar err error\n\n\tfor c.Next() {\n\t\targs := c.RemainingArgs()\n\t\tswitch len(args) {\n\t\tcase 0:\n\t\t\tresource = Resource(defaultExpvarPath)\n\t\tcase 1:\n\t\t\tresource = Resource(args[0])\n\t\tdefault:\n\t\t\treturn resource, c.ArgErr()\n\t\t}\n\t}\n\n\treturn resource, err\n}\n\n\n\nvar publishOnce sync.Once \nvar defaultExpvarPath = \"/debug/vars\"\n\nfunc publishExtraVars() ", "output": "{\n\tpublishOnce.Do(func() {\n\t\texpvar.Publish(\"Goroutines\", expvar.Func(func() interface{} {\n\t\t\treturn runtime.NumGoroutine()\n\t\t}))\n\t})\n}"} {"input": "package runtime\n\nimport (\n\t\"encoding/gob\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\nvar (\n\tgoatsSettings *GoatsSettings\n)\n\nfunc NewGoatsSettings() *GoatsSettings {\n\treturn &GoatsSettings{}\n}\n\nfunc InitGoats(settings *GoatsSettings) {\n\tif settings == nil {\n\t\tgoatsSettings = NewGoatsSettings()\n\t} else {\n\t\tgoatsSettings = settings\n\t}\n}\n\n\n\nfunc DecodeRpcRequestOrFail(input io.Reader, settings *TemplateSettings, args interface{}) ", "output": "{\n\tdecoder := gob.NewDecoder(input)\n\terr := decoder.Decode(settings)\n\tif err == nil {\n\t\terr = decoder.Decode(args)\n\t}\n\tif err != nil {\n\t\tfmt.Fprint(os.Stderr, err)\n\t\tos.Exit(2)\n\t}\n}"} {"input": "package ri\n\nimport (\n\t. \"github.com/smartystreets/goconvey/convey\"\n\t\"testing\"\n)\n\n\n\nfunc Test_Procedurals(t *testing.T) ", "output": "{\n\n\tConvey(\"All Procedurals\", t, func() {\n\n\t\tctx := NewTest()\n\t\tSo(ctx, ShouldNotBeNil)\n\n\t\tSo(ctx.Begin(\"procedurals.rib\"), ErrorShouldEqual, `Begin \"procedurals.rib\"`)\n\t\tSo(ctx.Comment(\"output from rigo, procedurals_test.go\"), ErrorShouldEqual, `# output from rigo, procedurals_test.go`)\n\n\t\tSo(ctx.Procedural(RtStringArray{\"sodacan.rib\"}, RtBound{-1, 1, -1, 1, 0, 6}, ProcDelayedReadArchive, ProcFree), ErrorShouldEqual, `Procedural \"DelayedReadArchive\" [\"sodacan.rib\"] [-1 1 -1 1 0 6]`)\n\n\t\tSo(ctx.End(), ErrorShouldEqual, `End`)\n\t})\n}"} {"input": "package simelection\n\nimport \"sync\"\n\n\n\ntype Election struct {\n\tmu sync.RWMutex\n\tmasters []string\n}\n\n\nfunc (e *Election) IsMaster(who string) bool {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tfor _, m := range e.masters {\n\t\tif m == who {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc (e *Election) Masters() []string {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\treturn e.masters\n}\n\n\nfunc (e *Election) SetMaster(who string) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\te.masters = []string{who}\n}\n\n\n\n\nfunc (e *Election) SetMasters(who []string) ", "output": "{\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\te.masters = who\n}"} {"input": "package memstats\n\nimport (\n\t\"github.com/mono83/slf\"\n\t\"sync\"\n)\n\n\n\nfunc New() *MemStats {\n\treturn &MemStats{\n\t\tvalues: map[string]int64{},\n\t}\n}\n\n\n\ntype MemStats struct {\n\tm sync.Mutex\n\n\tvalues map[string]int64\n}\n\n\nfunc (m *MemStats) Receive(e slf.Event) {\n\tif e.Type == slf.TypeInc {\n\t\tm.m.Lock()\n\t\tprev, _ := m.values[e.Content]\n\t\tm.values[e.Content] = prev + e.I64\n\t\tm.m.Unlock()\n\t} else if e.Type == slf.TypeGauge {\n\t\tm.m.Lock()\n\t\tm.values[e.Content] = e.I64\n\t\tm.m.Unlock()\n\t}\n}\n\n\n\n\n\nfunc (m *MemStats) Values() map[string]int64 {\n\tm.m.Lock()\n\tdefer m.m.Unlock()\n\n\tclone := make(map[string]int64, len(m.values))\n\tfor k, v := range m.values {\n\t\tclone[k] = v\n\t}\n\n\treturn clone\n}\n\nfunc (m *MemStats) Get(key string) (value int64, found bool) ", "output": "{\n\tm.m.Lock()\n\tdefer m.m.Unlock()\n\n\tvalue, found = m.values[key]\n\treturn\n}"} {"input": "package daemon\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetMapNameOKCode int = 200\n\n\ntype GetMapNameOK struct {\n\n\tPayload *models.BPFMap `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetMapNameOK() *GetMapNameOK {\n\n\treturn &GetMapNameOK{}\n}\n\n\nfunc (o *GetMapNameOK) WithPayload(payload *models.BPFMap) *GetMapNameOK {\n\to.Payload = payload\n\treturn o\n}\n\n\n\n\n\nfunc (o *GetMapNameOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\n\nconst GetMapNameNotFoundCode int = 404\n\n\ntype GetMapNameNotFound struct {\n}\n\n\nfunc NewGetMapNameNotFound() *GetMapNameNotFound {\n\n\treturn &GetMapNameNotFound{}\n}\n\n\nfunc (o *GetMapNameNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc (o *GetMapNameOK) SetPayload(payload *models.BPFMap) ", "output": "{\n\to.Payload = payload\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tdata := []float64{43, 56, 87, 12, 45, 57}\n\n\tn := average(data...)\n\n\tfmt.Println(n)\n}\n\n\n\nfunc average(sf ...float64) float64 ", "output": "{\n\ttotal := 0.0\n\n\tfor _, v := range sf {\n\t\ttotal += v\n\t}\n\n\treturn total / float64(len(sf))\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\n\t\"gopkg.in/yaml.v1\"\n)\n\nconst (\n\tCONFIG_SUBDIR = \"mcmd\"\n\tDEFAULT_KNOWN_HOSTS_FILE = \"$HOME/.ssh/known_hosts\"\n)\n\ntype HostConfig struct {\n\tUser string\n\tPrivatekey string\n\tHosts []string\n}\n\n\n\nfunc readHostfile() []byte {\n\tconfigFileParam := flag.Arg(0)\n\tfor _, file := range getConfigLocationCandidates(configFileParam) {\n\t\tif exists(file) {\n\t\t\treturn getContents(file)\n\t\t}\n\t}\n\terrLogger.Fatalf(\"hostfile %s not found\", configFileParam)\n\treturn nil\n}\n\nfunc getConfigLocationCandidates(configFileParam string) []string {\n\tconfigRoot, err := os.UserConfigDir()\n\tif err != nil {\n\t\terrLogger.Fatalf(\"no user config dir found\")\n\t}\n\tconfigDir := path.Join(configRoot, CONFIG_SUBDIR)\n\treturn []string{configFileParam,\n\t\tpath.Join(configDir, configFileParam+\".yml\"),\n\t\tpath.Join(configDir, configFileParam+\".yaml\")}\n}\n\nfunc exists(filename string) bool {\n\t_, err := os.Stat(filename)\n\treturn !os.IsNotExist(err)\n}\n\nfunc getContents(filename string) []byte {\n\tfileContents, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\terrLogger.Fatalln(err)\n\t}\n\treturn fileContents\n}\n\nfunc loadConfig() HostConfig ", "output": "{\n\trawYaml := readHostfile()\n\tvar result HostConfig\n\terr := yaml.Unmarshal(rawYaml, &result)\n\tif err != nil {\n\t\terrLogger.Fatalln(\"Error parsing hostfile:\", err)\n\t}\n\treturn result\n}"} {"input": "package username\n\nimport (\n\t\"net/url\"\n\t\"testing\"\n)\n\nvar u url.URL\nvar usernameTest, suffixTest string\n\nfunc TestUsernameWithoutPrefix(t *testing.T) {\n\tu, _ := url.Parse(\"http://example.com/username\")\n\tusernameTest, suffixTest = WithSuffix(u.Path)\n\n\tif usernameTest != \"username\" {\n\t\tt.Error(\"Expected username to be 'username' got: \", usernameTest)\n\t}\n\n\tif suffixTest != \"\" {\n\t\tt.Error(\"Expected suffix to be empty \", suffixTest)\n\t}\n}\n\n\n\nfunc TestUsernameWithPrefix(t *testing.T) ", "output": "{\n\tu, _ := url.Parse(\"http://example.com/username.prefix\")\n\tusernameTest, suffixTest = WithSuffix(u.Path)\n\n\tif usernameTest != \"username\" {\n\t\tt.Error(\"Expected username to be 'username' got: \", usernameTest)\n\t}\n\n\tif suffixTest != \"prefix\" {\n\t\tt.Error(\"Expected suffix to be 'prefix' got: \", suffixTest)\n\t}\n}"} {"input": "package logger\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\tlog \"github.com/cihub/seelog\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestGetLogFileLocationReturnsOverriddenPath(t *testing.T) {\n\tpath := \"/tmp/foo\"\n\tos.Setenv(envLogFilePath, path)\n\tdefer os.Unsetenv(envLogFilePath)\n\n\tassert.Equal(t, path, GetLogFileLocation(\"/tmp/bar\"))\n}\n\nfunc TestGetLogFileLocationReturnsDefaultPath(t *testing.T) {\n\tpath := \"/tmp/foo\"\n\tassert.Equal(t, path, GetLogFileLocation(path))\n}\n\n\n\nfunc TestLogLevelReturnsDefaultLevelWhenEnvNotSet(t *testing.T) {\n\tvar expectedLogLevel log.LogLevel\n\texpectedLogLevel = log.InfoLvl\n\tassert.Equal(t, expectedLogLevel.String(), getLogLevel())\n}\n\nfunc TestLogLevelReturnsDefaultLevelWhenEnvSetToInvalidValue(t *testing.T) {\n\tos.Setenv(envLogLevel, \"DEBUGGER\")\n\tdefer os.Unsetenv(envLogLevel)\n\n\tvar expectedLogLevel log.LogLevel\n\texpectedLogLevel = log.InfoLvl\n\tassert.Equal(t, expectedLogLevel.String(), getLogLevel())\n}\n\nfunc TestLogLevelReturnsOverriddenLevel(t *testing.T) ", "output": "{\n\tos.Setenv(envLogLevel, \"DEBUG\")\n\tdefer os.Unsetenv(envLogLevel)\n\n\tvar expectedLogLevel log.LogLevel\n\texpectedLogLevel = log.DebugLvl\n\tassert.Equal(t, expectedLogLevel.String(), getLogLevel())\n}"} {"input": "package terraform\n\nimport (\n\t\"github.com/hashicorp/terraform/config\"\n\t\"github.com/hashicorp/terraform/config/module\"\n\t\"github.com/hashicorp/terraform/dag\"\n)\n\n\n\n\n\n\n\ntype OrphanResourceTransformer struct {\n\tConcrete ConcreteResourceNodeFunc\n\n\tState *State\n\n\tModule *module.Tree\n}\n\n\n\nfunc (t *OrphanResourceTransformer) transform(g *Graph, ms *ModuleState) error {\n\tvar c *config.Config\n\tif m := t.Module.Child(ms.Path[1:]); m != nil {\n\t\tc = m.Config()\n\t}\n\n\tfor _, key := range ms.Orphans(c) {\n\t\taddr, err := parseResourceAddressInternal(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\taddr.Path = ms.Path[1:]\n\n\t\tabstract := &NodeAbstractResource{Addr: addr}\n\t\tvar node dag.Vertex = abstract\n\t\tif f := t.Concrete; f != nil {\n\t\t\tnode = f(abstract)\n\t\t}\n\n\t\tg.Add(node)\n\t}\n\n\treturn nil\n}\n\nfunc (t *OrphanResourceTransformer) Transform(g *Graph) error ", "output": "{\n\tif t.State == nil {\n\t\treturn nil\n\t}\n\n\tfor _, ms := range t.State.Modules {\n\t\tif err := t.transform(g, ms); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package viewservice\n\nimport \"net/rpc\"\nimport \"fmt\"\n\n\n\n\n\ntype Clerk struct {\n\tme string \n\tserver string \n}\n\nfunc MakeClerk(me string, server string) *Clerk {\n\tck := new(Clerk)\n\tck.me = me\n\tck.server = server\n\treturn ck\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc call(srv string, rpcname string,\n\targs interface{}, reply interface{}) bool {\n\tc, errx := rpc.Dial(\"unix\", srv)\n\tif errx != nil {\n\t\treturn false\n\t}\n\tdefer c.Close()\n\n\terr := c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}\n\n\n\nfunc (ck *Clerk) Get() (View, bool) {\n\targs := &GetArgs{}\n\tvar reply GetReply\n\tok := call(ck.server, \"ViewServer.Get\", args, &reply)\n\tif ok == false {\n\t\treturn View{}, false\n\t}\n\treturn reply.View, true\n}\n\nfunc (ck *Clerk) Primary() string {\n\tv, ok := ck.Get()\n\tif ok {\n\t\treturn v.Primary\n\t}\n\treturn \"\"\n}\n\nfunc (ck *Clerk) Ping(viewnum uint) (View, error) ", "output": "{\n\targs := &PingArgs{}\n\targs.Me = ck.me\n\targs.Viewnum = viewnum\n\tvar reply PingReply\n\n\tok := call(ck.server, \"ViewServer.Ping\", args, &reply)\n\tif ok == false {\n\t\treturn View{}, fmt.Errorf(\"Ping(%v) failed\", viewnum)\n\t}\n\n\treturn reply.View, nil\n}"} {"input": "package viewservice\n\nimport \"net/rpc\"\nimport \"fmt\"\n\n\n\n\n\ntype Clerk struct {\n\tme string \n\tserver string \n}\n\nfunc MakeClerk(me string, server string) *Clerk {\n\tck := new(Clerk)\n\tck.me = me\n\tck.server = server\n\treturn ck\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc call(srv string, rpcname string,\n\targs interface{}, reply interface{}) bool {\n\tc, errx := rpc.Dial(\"unix\", srv)\n\tif errx != nil {\n\t\treturn false\n\t}\n\tdefer c.Close()\n\n\terr := c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}\n\nfunc (ck *Clerk) Ping(viewnum uint) (View, error) {\n\targs := &PingArgs{}\n\targs.Me = ck.me\n\targs.Viewnum = viewnum\n\tvar reply PingReply\n\n\tok := call(ck.server, \"ViewServer.Ping\", args, &reply)\n\tif ok == false {\n\t\treturn View{}, fmt.Errorf(\"Ping(%v) failed\", viewnum)\n\t}\n\n\treturn reply.View, nil\n}\n\n\n\nfunc (ck *Clerk) Primary() string {\n\tv, ok := ck.Get()\n\tif ok {\n\t\treturn v.Primary\n\t}\n\treturn \"\"\n}\n\nfunc (ck *Clerk) Get() (View, bool) ", "output": "{\n\targs := &GetArgs{}\n\tvar reply GetReply\n\tok := call(ck.server, \"ViewServer.Get\", args, &reply)\n\tif ok == false {\n\t\treturn View{}, false\n\t}\n\treturn reply.View, true\n}"} {"input": "package msg\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"go-common/app/interface/main/mcn/conf\"\n\n\t\"gopkg.in/h2non/gock.v1\"\n)\n\nvar (\n\td *Dao\n)\n\nfunc TestMain(m *testing.M) {\n\tif os.Getenv(\"DEPLOY_ENV\") != \"\" {\n\t\tflag.Set(\"app_id\", \"main.archive.mcn-interface\")\n\t\tflag.Set(\"conf_token\", \"49e4671bafbf93059aeb602685052ca0\")\n\t\tflag.Set(\"tree_id\", \"58909\")\n\t\tflag.Set(\"conf_version\", \"docker-1\")\n\t\tflag.Set(\"deploy_env\", \"uat\")\n\t\tflag.Set(\"conf_host\", \"config.bilibili.co\")\n\t\tflag.Set(\"conf_path\", \"/tmp\")\n\t\tflag.Set(\"region\", \"sh\")\n\t\tflag.Set(\"zone\", \"sh001\")\n\t} else {\n\t\tflag.Set(\"conf\", \"../../cmd/mcn-interface.toml\")\n\t}\n\tif os.Getenv(\"UT_LOCAL_TEST\") != \"\" {\n\t\tflag.Set(\"conf\", \"../../cmd/mcn-interface.toml\")\n\t}\n\tflag.Parse()\n\tif err := conf.Init(); err != nil {\n\t\tpanic(err)\n\t}\n\td = New(conf.Conf)\n\td.client.SetTransport(gock.DefaultTransport)\n\tos.Exit(m.Run())\n}\n\n\n\nfunc httpMock(method, url string) *gock.Request ", "output": "{\n\tr := gock.New(url)\n\tr.Method = strings.ToUpper(method)\n\treturn r\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\n\n\nfunc TestDumbNilishIndex(t *testing.T) ", "output": "{\n\ttmpl := loadIndex()\n\tbuf := new(bytes.Buffer)\n\terr := tmpl.Execute(buf, &clientInfo{})\n\tif err != nil {\n\t\tt.Errorf(\"index execution blew up with nilish clientInfo: %#v\", err)\n\t}\n\tif len(buf.Bytes()) == 0 {\n\t\tt.Errorf(\"index execution did not write anything\")\n\t}\n}"} {"input": "package iso20022\n\n\ntype PointOfInteractionComponent6 struct {\n\n\tType *POIComponentType4Code `xml:\"Tp\"`\n\n\tIdentification *PointOfInteractionComponentIdentification1 `xml:\"Id\"`\n\n\tStatus *PointOfInteractionComponentStatus3 `xml:\"Sts,omitempty\"`\n\n\tStandardCompliance []*GenericIdentification48 `xml:\"StdCmplc,omitempty\"`\n\n\tCharacteristics *PointOfInteractionComponentCharacteristics2 `xml:\"Chrtcs,omitempty\"`\n\n\tAssessment []*PointOfInteractionComponentAssessment1 `xml:\"Assmnt,omitempty\"`\n}\n\nfunc (p *PointOfInteractionComponent6) SetType(value string) {\n\tp.Type = (*POIComponentType4Code)(&value)\n}\n\n\n\nfunc (p *PointOfInteractionComponent6) AddStatus() *PointOfInteractionComponentStatus3 {\n\tp.Status = new(PointOfInteractionComponentStatus3)\n\treturn p.Status\n}\n\nfunc (p *PointOfInteractionComponent6) AddStandardCompliance() *GenericIdentification48 {\n\tnewValue := new(GenericIdentification48)\n\tp.StandardCompliance = append(p.StandardCompliance, newValue)\n\treturn newValue\n}\n\nfunc (p *PointOfInteractionComponent6) AddCharacteristics() *PointOfInteractionComponentCharacteristics2 {\n\tp.Characteristics = new(PointOfInteractionComponentCharacteristics2)\n\treturn p.Characteristics\n}\n\nfunc (p *PointOfInteractionComponent6) AddAssessment() *PointOfInteractionComponentAssessment1 {\n\tnewValue := new(PointOfInteractionComponentAssessment1)\n\tp.Assessment = append(p.Assessment, newValue)\n\treturn newValue\n}\n\nfunc (p *PointOfInteractionComponent6) AddIdentification() *PointOfInteractionComponentIdentification1 ", "output": "{\n\tp.Identification = new(PointOfInteractionComponentIdentification1)\n\treturn p.Identification\n}"} {"input": "package config\n\nimport (\n\tcb \"github.com/hyperledger/fabric/protos/common\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n\t\"github.com/hyperledger/fabric/protos/utils\"\n)\n\nfunc ordererConfigGroup(key string, value []byte) *cb.ConfigGroup {\n\tresult := cb.NewConfigGroup()\n\tresult.Groups[OrdererGroupKey] = cb.NewConfigGroup()\n\tresult.Groups[OrdererGroupKey].Values[key] = &cb.ConfigValue{\n\t\tValue: value,\n\t}\n\treturn result\n}\n\n\n\n\n\nfunc TemplateBatchSize(batchSize *ab.BatchSize) *cb.ConfigGroup {\n\treturn ordererConfigGroup(BatchSizeKey, utils.MarshalOrPanic(batchSize))\n}\n\n\nfunc TemplateBatchTimeout(batchTimeout string) *cb.ConfigGroup {\n\treturn ordererConfigGroup(BatchTimeoutKey, utils.MarshalOrPanic(&ab.BatchTimeout{Timeout: batchTimeout}))\n}\n\n\nfunc TemplateChannelRestrictions(maxChannels uint64) *cb.ConfigGroup {\n\treturn ordererConfigGroup(ChannelRestrictionsKey, utils.MarshalOrPanic(&ab.ChannelRestrictions{MaxCount: maxChannels}))\n}\n\n\nfunc TemplateKafkaBrokers(brokers []string) *cb.ConfigGroup {\n\treturn ordererConfigGroup(KafkaBrokersKey, utils.MarshalOrPanic(&ab.KafkaBrokers{Brokers: brokers}))\n}\n\nfunc TemplateConsensusType(typeValue string) *cb.ConfigGroup ", "output": "{\n\treturn ordererConfigGroup(ConsensusTypeKey, utils.MarshalOrPanic(&ab.ConsensusType{Type: typeValue}))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"k8s.io/helm/pkg/helm/helmpath\"\n\t\"k8s.io/helm/pkg/plugin\"\n\t\"k8s.io/helm/pkg/plugin/installer\"\n\n\t\"github.com/spf13/cobra\"\n)\n\ntype pluginInstallCmd struct {\n\tsource string\n\tversion string\n\thome helmpath.Home\n\tout io.Writer\n}\n\n\n\nfunc (pcmd *pluginInstallCmd) complete(args []string) error {\n\tif err := checkArgsLength(len(args), \"plugin\"); err != nil {\n\t\treturn err\n\t}\n\tpcmd.source = args[0]\n\tpcmd.home = settings.Home\n\treturn nil\n}\n\nfunc (pcmd *pluginInstallCmd) run() error {\n\tinstaller.Debug = settings.Debug\n\n\ti, err := installer.NewForSource(pcmd.source, pcmd.version, pcmd.home)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := installer.Install(i); err != nil {\n\t\treturn err\n\t}\n\n\tdebug(\"loading plugin from %s\", i.Path())\n\tp, err := plugin.LoadDir(i.Path())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := runHook(p, plugin.Install); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintf(pcmd.out, \"Installed plugin: %s\\n\", p.Metadata.Name)\n\treturn nil\n}\n\nfunc newPluginInstallCmd(out io.Writer) *cobra.Command ", "output": "{\n\tpcmd := &pluginInstallCmd{out: out}\n\tcmd := &cobra.Command{\n\t\tUse: \"install [options] ...\",\n\t\tShort: \"install one or more Helm plugins\",\n\t\tPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn pcmd.complete(args)\n\t\t},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn pcmd.run()\n\t\t},\n\t}\n\tcmd.Flags().StringVar(&pcmd.version, \"version\", \"\", \"specify a version constraint. If this is not specified, the latest version is installed\")\n\treturn cmd\n}"} {"input": "package github\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/hashicorp/vault/api\"\n)\n\ntype CLIHandler struct{}\n\nfunc (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, error) {\n\tmount, ok := m[\"mount\"]\n\tif !ok {\n\t\tmount = \"github\"\n\t}\n\n\ttoken, ok := m[\"token\"]\n\tif !ok {\n\t\tif token = os.Getenv(\"VAULT_AUTH_GITHUB_TOKEN\"); token == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"GitHub token should be provided either as 'value' for 'token' key,\\nor via an env var VAULT_AUTH_GITHUB_TOKEN\")\n\t\t}\n\t}\n\n\tpath := fmt.Sprintf(\"auth/%s/login\", mount)\n\tsecret, err := c.Logical().Write(path, map[string]interface{}{\n\t\t\"token\": token,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif secret == nil {\n\t\treturn nil, fmt.Errorf(\"empty response from credential provider\")\n\t}\n\n\treturn secret, nil\n}\n\n\n\nfunc (h *CLIHandler) Help() string ", "output": "{\n\thelp := `\nThe GitHub credential provider allows you to authenticate with GitHub.\nTo use it, specify the \"token\" parameter. The value should be a personal access\ntoken for your GitHub account. You can generate a personal access token on your\naccount settings page on GitHub.\n\n Example: vault auth -method=github token=\n\nKey/Value Pairs:\n\n mount=github The mountpoint for the GitHub credential provider.\n Defaults to \"github\"\n\n token= The GitHub personal access token for authentication.\n\t`\n\n\treturn strings.TrimSpace(help)\n}"} {"input": "package nes\n\nimport \"math\"\n\ntype Filter interface {\n\tStep(x float32) float32\n}\n\n\n\ntype FirstOrderFilter struct {\n\tB0 float32\n\tB1 float32\n\tA1 float32\n\tprevX float32\n\tprevY float32\n}\n\nfunc (f *FirstOrderFilter) Step(x float32) float32 {\n\ty := f.B0*x + f.B1*f.prevX - f.A1*f.prevY\n\tf.prevY = y\n\tf.prevX = x\n\treturn y\n}\n\n\n\nfunc LowPassFilter(sampleRate float32, cutoffFreq float32) Filter {\n\tc := sampleRate / math.Pi / cutoffFreq\n\ta0i := 1 / (1 + c)\n\treturn &FirstOrderFilter{\n\t\tB0: a0i,\n\t\tB1: a0i,\n\t\tA1: (1 - c) * a0i,\n\t}\n}\n\n\n\ntype FilterChain []Filter\n\nfunc (fc FilterChain) Step(x float32) float32 {\n\tif fc != nil {\n\t\tfor i := range fc {\n\t\t\tx = fc[i].Step(x)\n\t\t}\n\t}\n\treturn x\n}\n\nfunc HighPassFilter(sampleRate float32, cutoffFreq float32) Filter ", "output": "{\n\tc := sampleRate / math.Pi / cutoffFreq\n\ta0i := 1 / (1 + c)\n\treturn &FirstOrderFilter{\n\t\tB0: c * a0i,\n\t\tB1: -c * a0i,\n\t\tA1: (1 - c) * a0i,\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n)\n\n\n\n\n\nfunc SetServiceStatus(w http.ResponseWriter, req *http.Request) {\n\tlog.Print(\"processing SetServiceStatus\")\n\tio.WriteString(w, \"SetServiceStatus!\\n\")\n}\n\nfunc SendSystemMessage(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tlog.Print(\"processing SendSystemMessage\")\n\tio.WriteString(w, \"SendSystemMessage!\\n\")\n}"} {"input": "package dosingdecision\n\nimport (\n\t\"time\"\n\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tCarbohydratesOnBoardAmountMaximum = 1000\n\tCarbohydratesOnBoardAmountMinimum = 0\n)\n\ntype CarbohydratesOnBoard struct {\n\tTime *time.Time `json:\"time,omitempty\" bson:\"time,omitempty\"`\n\tAmount *float64 `json:\"amount,omitempty\" bson:\"amount,omitempty\"`\n}\n\n\n\nfunc NewCarbohydratesOnBoard() *CarbohydratesOnBoard {\n\treturn &CarbohydratesOnBoard{}\n}\n\nfunc (c *CarbohydratesOnBoard) Parse(parser structure.ObjectParser) {\n\tc.Time = parser.Time(\"time\", time.RFC3339Nano)\n\tc.Amount = parser.Float64(\"amount\")\n}\n\nfunc (c *CarbohydratesOnBoard) Validate(validator structure.Validator) {\n\tvalidator.Float64(\"amount\", c.Amount).Exists().InRange(CarbohydratesOnBoardAmountMinimum, CarbohydratesOnBoardAmountMaximum)\n}\n\nfunc ParseCarbohydratesOnBoard(parser structure.ObjectParser) *CarbohydratesOnBoard ", "output": "{\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewCarbohydratesOnBoard()\n\tparser.Parse(datum)\n\treturn datum\n}"} {"input": "package main\n\nimport . \"g2d\"\n\nvar arena = NewArena(Point{480, 360})\nvar a1 = NewAlien(arena, Point{40, 40})\nvar a2 = NewAlien(arena, Point{80, 80})\n\ntype Alien struct {\n arena *Arena\n x, y, w, h int\n xmin, xmax int\n dx, dy int\n}\n\n\n\nfunc (a *Alien) Move() {\n if a.xmin <= a.x+a.dx && a.x+a.dx <= a.xmax {\n a.x += a.dx\n } else {\n a.dx = -a.dx\n a.y += a.dy\n }\n}\n\nfunc (a *Alien) Position() Point {\n return Point{a.x, a.y}\n}\n\nfunc (a *Alien) Size() Point {\n return Point{a.w, a.h}\n}\n\nfunc (a *Alien) Symbol() Point {\n return Point{0, 0}\n}\n\nfunc (a *Alien) Collide(other Actor) {\n}\n\nfunc tick() {\n ClearCanvas()\n arena.MoveAll()\n for _, actor := range arena.Actors() {\n FillRect(actor.Position(), actor.Size())\n }\n}\n\nfunc main() {\n InitCanvas(arena.Size())\n MainLoop(tick)\n}\n\nfunc NewAlien(arena *Arena, pos Point) *Alien ", "output": "{\n a := &Alien{arena, pos.X, pos.Y, 20, 20, pos.X, pos.X+150, 5, 5}\n arena.Add(a)\n return a\n}"} {"input": "package sdk\n\nimport (\n\t\"io/ioutil\"\n\t\"net/url\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\ntype hydraConfig struct {\n\tClusterURL string `yaml:\"cluster_url\"`\n\tClientID string `yaml:\"client_id\"`\n\tClientSecret string `yaml:\"client_secret\"`\n}\n\n\nfunc FromYAML(file string) option {\n\treturn func(c *Client) error {\n\t\tvar err error\n\t\tvar config = hydraConfig{}\n\n\t\tdata, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = yaml.Unmarshal(data, &config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.clusterURL, err = url.Parse(config.ClusterURL)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.clientID = config.ClientID\n\t\tc.clientSecret = config.ClientSecret\n\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc ClusterURL(urlStr string) option {\n\treturn func(c *Client) error {\n\t\tvar err error\n\t\tc.clusterURL, err = url.Parse(urlStr)\n\t\treturn err\n\t}\n}\n\n\n\n\n\n\n\nfunc ClientID(id string) option {\n\treturn func(c *Client) error {\n\t\tc.clientID = id\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc ClientSecret(secret string) option {\n\treturn func(c *Client) error {\n\t\tc.clientSecret = secret\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc SkipTLSVerify() option {\n\treturn func(c *Client) error {\n\t\tc.skipTLSVerify = true\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\n\n\nfunc Scopes(scopes ...string) option ", "output": "{\n\treturn func(c *Client) error {\n\t\tc.scopes = scopes\n\t\treturn nil\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"exectime/timer\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n)\n\nfunc printError(e interface{}) {\n\tfmt.Printf(\"\\033[1;31m%v\\033[m\\n\", e)\n}\n\n\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tprintError(\"Add at least one argument!\")\n\t\treturn\n\t}\n\tf := func() {\n\t\tif e := launchCommand(os.Args[1], os.Args[2:]...); e != nil {\n\t\t\tprintError(e)\n\t\t}\n\t}\n\tt := timer.NewFunc(f)\n\tt.Exec()\n\tfmt.Println(t)\n}\n\nfunc launchCommand(name string, args ...string) error ", "output": "{\n\tcmd := exec.Command(name, args...)\n\tcmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr\n\treturn cmd.Run()\n}"} {"input": "package inmem\n\nimport (\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\ntype Reader struct {\n\tstore *Store\n}\n\nfunc newReader(store *Store) (*Reader, error) {\n\treturn &Reader{\n\t\tstore: store,\n\t}, nil\n}\n\nfunc (r *Reader) BytesSafeAfterClose() bool {\n\treturn false\n}\n\nfunc (r *Reader) Get(key []byte) ([]byte, error) {\n\treturn r.store.get(key)\n}\n\nfunc (r *Reader) Iterator(key []byte) store.KVIterator {\n\treturn r.store.iterator(key)\n}\n\n\n\nfunc (r *Reader) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc xisPalindrome(r, v int) bool {\n\treturn r == v\n}\n\nfunc xreverse(n int) (r int) {\n\tfor {\n\t\tif n > 0 {\n\t\t\tr = r * 10 + n % 10\n\t\t\tn = n / 10\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn r\n}\n\nfunc TestLevel4(t *testing.T) ", "output": "{\n\th := 0\n\tfor i := 999; i > 99; i-- {\n\t\tfor j := 100; j < 1000; j++ {\n\t\t\tp := i * j\n\t\t\tr := xreverse(p)\n\t\t\tif xisPalindrome(r, p) {\n\t\t\t\tif h < p {\n\t\t\t\t\th = p\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif h != 906609 {\n\t\tt.Errorf(\"Error: largest palindrome should not be: %d \", h)\n\t}\n\n}"} {"input": "package scope_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"euphoria.io/scope\"\n)\n\nfunc ExampleBreakpointer() {\n\troot := scope.New()\n\n\toutput := func(arg string) error {\n\t\t_, err := fmt.Println(arg)\n\t\treturn err\n\t}\n\n\tverifyOutput := func(ctx scope.Context, arg string) error {\n\t\tif err := ctx.Check(\"output()\", arg); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn output(arg)\n\t}\n\n\tctrl := root.Breakpoint(\"output()\", \"fail\")\n\n\terr := verifyOutput(root, \"normal behavior\")\n\tfmt.Println(\"verifyOutput returned\", err)\n\n\tgo func() {\n\t\t<-ctrl \n\t\tctrl <- fmt.Errorf(\"test error\")\n\t}()\n\n\terr = verifyOutput(root, \"fail\")\n\tfmt.Println(\"verifyOutput returned\", err)\n\n\tgo func() {\n\t\t<-ctrl\n\t\troot.Cancel()\n\t}()\n\n\terr = verifyOutput(root, \"fail\")\n\tfmt.Println(\"verifyOutput returned\", err)\n\n}\n\n\n\nfunc ExampleContext_cancellation() ", "output": "{\n\tctx := scope.New()\n\n\tgo func() {\n\t\ttime.Sleep(50 * time.Millisecond)\n\t\tctx.Cancel()\n\t}()\n\nloop:\n\tfor {\n\t\tt := time.After(10 * time.Millisecond)\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tbreak loop\n\t\tcase <-t:\n\t\t\tfmt.Println(\"tick\")\n\t\t}\n\t}\n\tfmt.Println(\"finished with\", ctx.Err())\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/url\"\n\n\t\"github.com/ChimeraCoder/anaconda\"\n\t\"github.com/go-ini/ini\"\n)\n\nvar Config *ini.File\n\nconst (\n\tconsumerKey = \"your key here\"\n\tconsumerSecret = \"your secret here\"\n\taccessToken = \"your token here\"\n\taccessSecret = \"your secret here\"\n\tmacAddress = \"mac address of the dash button here\"\n)\n\nfunc main() {\n\tDashMacs[macAddress] = Tweet\n\n\tSnifferStart()\n}\n\n\n\nfunc Tweet() {\n\tPostTweet(\"Testing now\")\n}\n\nfunc PostTweet(tweet string) {\n\tanaconda.SetConsumerKey(consumerKey)\n\tanaconda.SetConsumerSecret(consumerSecret)\n\tapi := anaconda.NewTwitterApi(accessToken, accessSecret)\n\n\tv := url.Values{}\n\n\t_, err := api.PostTweet(tweet, v)\n\tif err != nil {\n\t\tlog.Println(\"We have an error now \", err)\n\t}\n\n}\n\nfunc NoAction() ", "output": "{\n\tlog.Println(\"No action on click.\")\n}"} {"input": "package goxpath\n\nimport (\n\txml \"encoding/xml\"\n)\n\ntype FuncOpts func(*Opts)\n\n\n\ntype Opts struct {\n\tNS map[string]string\n\tFuncs map[xml.Name]interface{}\n\tVars map[string]interface{}\n}\n\nfunc Parse(_ string) (XPathExec, error) {\n\treturn XPathExec{}, nil\n}\n\nfunc ParseExec(_ string, _ interface{}, _ ...FuncOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\ntype XPathExec struct{}\n\nfunc (_ XPathExec) Exec(_ interface{}, _ ...FuncOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\nfunc (_ XPathExec) ExecBool(_ interface{}, _ ...FuncOpts) (bool, error) {\n\treturn false, nil\n}\n\nfunc (_ XPathExec) ExecNode(_ interface{}, _ ...FuncOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\nfunc (_ XPathExec) ExecNum(_ interface{}, _ ...FuncOpts) (float64, error) {\n\treturn 0, nil\n}\n\nfunc (_ XPathExec) MustExec(_ interface{}, _ ...FuncOpts) interface{} {\n\treturn nil\n}\n\nfunc MustParse(_ string) XPathExec ", "output": "{\n\treturn XPathExec{}\n}"} {"input": "package wire\n\nimport (\n\t\"time\"\n)\n\n\ntype periodicTask struct {\n\tperiod time.Duration\n\ttask func()\n\tticker *time.Ticker\n\tstop chan struct{}\n}\n\nfunc newPeriodicTask(period time.Duration, task func()) *periodicTask {\n\treturn &periodicTask{\n\t\tperiod: period,\n\t\ttask: task,\n\t}\n}\n\n\n\nfunc (pt *periodicTask) Start() {\n\tif pt.ticker != nil || pt.period <= 0 {\n\t\treturn\n\t}\n\n\tpt.ticker = time.NewTicker(pt.period)\n\tpt.stop = make(chan struct{})\n\tgo pt.poll(pt.ticker, pt.stop)\n}\n\n\n\n\nfunc (pt *periodicTask) poll(ticker *time.Ticker, stop chan struct{}) {\n\tfor {\n\t\tselect {\n\t\tcase <-stop:\n\t\t\treturn \n\t\tdefault:\n\t\t}\n\n\t\tselect {\n\t\tcase <-stop:\n\t\t\treturn \n\t\tcase <-ticker.C:\n\t\t\tpt.task()\n\t\t}\n\t}\n}\n\nfunc (pt *periodicTask) Stop() ", "output": "{\n\tif pt.ticker == nil {\n\t\treturn\n\t}\n\n\tpt.ticker.Stop()\n\tclose(pt.stop)\n\n\tpt.ticker = nil\n\tpt.stop = nil\n}"} {"input": "package bot\n\nimport (\n\t\"net/http\"\n)\n\nfunc getBodyContent(r *http.Request) []byte {\n\tbody := make([]byte, r.ContentLength)\n\tr.Body.Read(body)\n\treturn body\n}\n\n\n\nfunc mapContainsKey(m map[string]interface{}, k string) bool ", "output": "{\n\t_, ok := m[k]\n\treturn ok\n}"} {"input": "package vagrant\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t\"github.com/hashicorp/otto/ui\"\n)\n\n\n\ntype SSHCache struct {\n\tPath string\n\n\tVagrant *Vagrant\n}\n\n\n\n\n\n\nfunc (c *SSHCache) Exec(cacheOkay bool) error {\n\tif _, err := os.Stat(c.Path); err == nil {\n\t\tcmd := exec.Command(\"ssh\", \"-F\", c.Path, \"default\")\n\t\tcmd.Stdin = os.Stdin\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t\tif err := cmd.Start(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := cmd.Wait(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn c.Vagrant.Execute(\"ssh\")\n}\n\n\n\n\n\nfunc (c *SSHCache) Delete() error {\n\tos.Remove(c.Path)\n\treturn nil\n}\n\nfunc (c *SSHCache) Cache() error ", "output": "{\n\tvar mockUi ui.Mock\n\tvagrant := *c.Vagrant\n\tvagrant.Ui = &mockUi\n\tif err := vagrant.Execute(\"ssh-config\"); err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(c.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tfor _, raw := range mockUi.RawBuf {\n\t\tif _, err := io.Copy(f, strings.NewReader(raw)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Frame struct {\n\tNotice string\n\tAuth string\n\tShit string\n\tMessage string\n}\n\ntype UserFrame struct {\n\tName2, Name3 string\n\tHost string\n\tName4 string\n}\n\nfunc getFrame(input []string, c int) string {\n\tif c > len(input) {\n\t\treturn \"\"\n\t}\n\n\treturn input[c]\n}\nfunc DeserializeUserFrame(input string) *UserFrame {\n\tdob := strings.Split(input, \" \")\n\tc := &UserFrame{\n\t\tName2: getFrame(dob, 1),\n\t\tName3: getFrame(dob, 2),\n\t\tHost: getFrame(dob, 3),\n\t\tName4: getFrame(dob, 4),\n\t}\n\treturn c\n}\n\n\n\nfunc (f *Frame) Serialize() []byte {\n\treturn []byte(f.SerializeToString())\n}\n\nfunc (f *Frame) SerializeToString() string ", "output": "{\n\treturn fmt.Sprintf(\"%s %s %s %s\\n\", f.Notice, f.Auth, f.Shit, f.Message)\n}"} {"input": "package main\n\nimport \"github.com/go-gl/gl/v2.1/gl\"\n\n\n\n\n\n\n\nfunc fPtr(data []float32) *float32 {\n\treturn (*float32)(gl.Ptr(data))\n}\n\nfunc rotateOnPoint(rot float64, loc vertex) ", "output": "{\n\tgl.Translated(loc.x, loc.y, loc.z)\n\tgl.Rotated(rot, 0.0, 0.0, 1.0)\n\tgl.Translated(-loc.x, -loc.y, -loc.z)\n}"} {"input": "package internal\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc Test_providerAuthHeaderWorks(t *testing.T) {\n\tfor _, p := range brokenAuthHeaderProviders {\n\t\tif providerAuthHeaderWorks(p) {\n\t\t\tt.Errorf(\"got %q as unbroken; want broken\", p)\n\t\t}\n\t\tp := fmt.Sprintf(\"%ssomesuffix\", p)\n\t\tif providerAuthHeaderWorks(p) {\n\t\t\tt.Errorf(\"got %q as unbroken; want broken\", p)\n\t\t}\n\t}\n\tp := \"https://api.not-in-the-list-example.com/\"\n\tif !providerAuthHeaderWorks(p) {\n\t\tt.Errorf(\"got %q as unbroken; want broken\", p)\n\t}\n}\n\nfunc TestRegisterBrokenAuthHeaderProvider(t *testing.T) ", "output": "{\n\tRegisterBrokenAuthHeaderProvider(\"https://aaa.com/\")\n\ttokenURL := \"https://aaa.com/token\"\n\tif providerAuthHeaderWorks(tokenURL) {\n\t\tt.Errorf(\"got %q as unbroken; want broken\", tokenURL)\n\t}\n}"} {"input": "package mir\n\nimport (\n\t\"bytes\"\n\t\"github.com/rhysd/gocaml/types\"\n\t\"github.com/rhysd/locerr\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestDump(t *testing.T) ", "output": "{\n\tprog := &Program{\n\t\tNewToplevel(),\n\t\tmap[string][]string{},\n\t\tNewBlockFromArray(\"program\", []*Insn{\n\t\t\tNewInsn(\"$k1\", UnitVal, locerr.Pos{}),\n\t\t}),\n\t}\n\n\tenv := types.NewEnv()\n\tenv.DeclTable[\"$k1\"] = types.UnitType\n\n\tvar buf bytes.Buffer\n\tprog.Dump(&buf, env)\n\tout := buf.String()\n\tif !strings.Contains(out, \"[TOPLEVELS (0)]\") {\n\t\tt.Fatalf(\"Toplevel section not found\")\n\t}\n\tif !strings.Contains(out, \"[CLOSURES (0)]\") {\n\t\tt.Fatalf(\"Closures section not found\")\n\t}\n\tif !strings.Contains(out, \"[ENTRY]\") {\n\t\tt.Fatalf(\"Entry section not found\")\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"github.com/kubeflow/pipelines/backend/src/common/util\"\n\t\"github.com/kubeflow/pipelines/backend/src/crd/pkg/client/informers/externalversions/scheduledworkflow/v1beta1\"\n\t_ \"k8s.io/client-go/plugin/pkg/client/auth/gcp\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\ntype ScheduledWorkflowClientInterface interface {\n\tGet(namespace string, name string) (swf *util.ScheduledWorkflow, err error)\n}\n\n\ntype ScheduledWorkflowClient struct {\n\tinformer v1beta1.ScheduledWorkflowInformer\n}\n\n\nfunc NewScheduledWorkflowClient(informer v1beta1.ScheduledWorkflowInformer) *ScheduledWorkflowClient {\n\treturn &ScheduledWorkflowClient{\n\t\tinformer: informer,\n\t}\n}\n\n\nfunc (c *ScheduledWorkflowClient) AddEventHandler(funcs *cache.ResourceEventHandlerFuncs) {\n\tc.informer.Informer().AddEventHandler(funcs)\n}\n\n\nfunc (c *ScheduledWorkflowClient) HasSynced() func() bool {\n\treturn c.informer.Informer().HasSynced\n}\n\n\n\n\nfunc (c *ScheduledWorkflowClient) Get(namespace string, name string) (\n\tswf *util.ScheduledWorkflow, err error) ", "output": "{\n\tschedule, err := c.informer.Lister().ScheduledWorkflows(namespace).Get(name)\n\tif err != nil {\n\t\tvar code util.CustomCode\n\t\tif util.IsNotFound(err) {\n\t\t\tcode = util.CUSTOM_CODE_NOT_FOUND\n\t\t} else {\n\t\t\tcode = util.CUSTOM_CODE_GENERIC\n\t\t}\n\t\treturn nil, util.NewCustomError(err, code,\n\t\t\t\"Error retrieving scheduled workflow (%v) in namespace (%v): %v\", name, namespace, err)\n\t}\n\n\treturn util.NewScheduledWorkflow(schedule), nil\n}"} {"input": "package goparsify\n\nimport (\n\t\"strconv\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\n\ntype State struct {\n\tInput string\n\tPos int\n\tCut int\n\tError Error\n\tWS VoidParser\n}\n\n\n\nfunc ASCIIWhitespace(s *State) {\n\tfor s.Pos < len(s.Input) {\n\t\tswitch s.Input[s.Pos] {\n\t\tcase '\\t', '\\n', '\\v', '\\f', '\\r', ' ':\n\t\t\ts.Pos++\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\nfunc UnicodeWhitespace(s *State) {\n\tfor s.Pos < len(s.Input) {\n\t\tr, w := utf8.DecodeRuneInString(s.Get())\n\t\tif !unicode.IsSpace(r) {\n\t\t\treturn\n\t\t}\n\t\ts.Pos += w\n\t}\n}\n\n\nfunc NoWhitespace(s *State) {\n\n}\n\n\nfunc NewState(input string) *State {\n\treturn &State{\n\t\tInput: input,\n\t\tWS: UnicodeWhitespace,\n\t}\n}\n\n\nfunc (s *State) Advance(i int) {\n\ts.Pos += i\n}\n\n\nfunc (s *State) Get() string {\n\tif s.Pos > len(s.Input) {\n\t\treturn \"\"\n\t}\n\treturn s.Input[s.Pos:]\n}\n\n\n\n\n\nfunc (s *State) ErrorHere(expected string) {\n\ts.Error.pos = s.Pos\n\ts.Error.expected = expected\n}\n\n\n\nfunc (s *State) Recover() {\n\ts.Error.expected = \"\"\n}\n\n\nfunc (s *State) Errored() bool {\n\treturn s.Error.expected != \"\"\n}\n\nfunc (s *State) Preview(x int) string ", "output": "{\n\tif s.Pos >= len(s.Input) {\n\t\treturn \"\"\n\t}\n\n\tquoted := strconv.Quote(s.Get())\n\tquoted = quoted[1 : len(quoted)-1]\n\tif len(quoted) >= x {\n\t\treturn quoted[0:x]\n\t}\n\n\treturn quoted\n}"} {"input": "package crisp\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\n\n\n\ntype Addr struct {\n\tNetwork string\n\tNetAddr string\n}\n\n\n\nfunc ParseAddr(s string) *Addr {\n\tif strings.HasPrefix(s, \"@\") {\n\t\treturn &Addr{Network: \"unix\", NetAddr: s[1:]}\n\t}\n\treturn &Addr{Network: \"tcp\", NetAddr: s}\n}\n\n\n\n\n\nfunc (a *Addr) String() string ", "output": "{\n\tif a.Network == \"@\" {\n\t\treturn fmt.Sprintf(\"@%s\", a.NetAddr)\n\t}\n\treturn fmt.Sprintf(\"%s\", a.NetAddr)\n}"} {"input": "package datatype\n\nimport \"fmt\"\n\n\ntype OctetString string\n\n\nfunc DecodeOctetString(b []byte) (Type, error) {\n\treturn OctetString(b), nil\n}\n\n\nfunc (s OctetString) Serialize() []byte {\n\treturn []byte(s)\n}\n\n\nfunc (s OctetString) Len() int {\n\treturn len(s)\n}\n\n\nfunc (s OctetString) Padding() int {\n\tl := len(s)\n\treturn pad4(l) - l\n}\n\n\nfunc (s OctetString) Type() TypeID {\n\treturn OctetStringType\n}\n\n\n\n\nfunc (s OctetString) String() string ", "output": "{\n\treturn fmt.Sprintf(\"OctetString{%#x},Padding:%d\", string(s), s.Padding())\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ChangeDatabaseSoftwareImageCompartmentRequest struct {\n\n\tChangeCompartmentDetails `contributesTo:\"body\"`\n\n\tDatabaseSoftwareImageId *string `mandatory:\"true\" contributesTo:\"path\" name:\"databaseSoftwareImageId\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ChangeDatabaseSoftwareImageCompartmentResponse struct {\n\n\tRawResponse *http.Response\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ChangeDatabaseSoftwareImageCompartmentResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ChangeDatabaseSoftwareImageCompartmentResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package garchive\n\nimport (\n\t\"archive/zip\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc writeArchive(t *testing.T, w io.Writer) {\n\tarchive := zip.NewWriter(w)\n\tdefer archive.Close()\n\n\ttestFile, err := archive.Create(\"temporary_file.txt\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tio.WriteString(testFile, \"test file\")\n}\n\nfunc TestExtractZipFile(t *testing.T) {\n\ttempFile, err := ioutil.TempFile(\"\", \"archive\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tdefer tempFile.Close()\n\tdefer os.Remove(tempFile.Name())\n\twriteArchive(t, tempFile)\n\ttempFile.Close()\n\n\terr = ExtractZipFile(tempFile.Name(), \"\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\n\tstat, err := os.Stat(\"temporary_file.txt\")\n\tassert.False(t, os.IsNotExist(err), \"Expected temporary_file.txt to exist\")\n\tif !os.IsNotExist(err) {\n\t\tassert.NoError(t, err)\n\t}\n\n\tif stat != nil {\n\t\tdefer os.Remove(\"temporary_file.txt\")\n\t\tassert.Equal(t, int64(9), stat.Size())\n\t}\n}\n\n\n\nfunc TestExtractZipFileNotFound(t *testing.T) ", "output": "{\n\terr := ExtractZipFile(\"non_existing_zip_file.zip\", \"\")\n\tassert.Error(t, err)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/syscrusher/fake\"\n)\n\nconst (\n\tcolumnCreditCardNumber = \"credit_card.number\"\n\tcolumnCreditCardType = \"credit_card.type\"\n)\n\ntype ColumnCreditCardNumberPayload struct {\n\tType string\n}\n\ntype ColumnCreditCardNumber struct {\n\tTypedColumnBase\n\tpayload ColumnCreditCardNumberPayload\n}\n\nfunc (column ColumnCreditCardNumber) Value(chunk *Chunk) (string, error) {\n\treturn fake.CreditCardNum(column.payload.Type), nil\n}\n\ntype ColumnCreditCardType struct {\n\tTypedColumnBase\n}\n\n\n\nfunc (column ColumnCreditCardType) Value(chunk *Chunk) (string, error) ", "output": "{\n\treturn fake.CreditCardType(), nil\n}"} {"input": "package aws\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/mitchellh/goamz/aws\"\n)\n\ntype Config struct {\n\tAccessKey string `mapstructure:\"access_key\"`\n\tSecretKey string `mapstructure:\"secret_key\"`\n\tRegion string `mapstructure:\"region\"`\n}\n\n\n\n\n\n\n\n\n\nfunc (c *Config) IsValidRegion() bool {\n\tvar regions = [8]string{\"us-east-1\", \"us-west-2\", \"us-west-1\", \"eu-west-1\",\n\t\t\"ap-southeast-1\", \"ap-southeast-2\", \"ap-northeast-1\", \"sa-east-1\"}\n\n\tfor _, valid := range regions {\n\t\tif c.Region == valid {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\nfunc (c *Config) AWSRegion() (aws.Region, error) {\n\tif c.Region != \"\" {\n\t\tif c.IsValidRegion() {\n\t\t\treturn aws.Regions[c.Region], nil\n\t\t} else {\n\t\t\treturn aws.Region{}, fmt.Errorf(\"Not a valid region: %s\", c.Region)\n\t\t}\n\t}\n\n\tif v := os.Getenv(\"AWS_REGION\"); v != \"\" {\n\t\treturn aws.Regions[v], nil\n\t}\n\n\tmd, err := aws.GetMetaData(\"placement/availability-zone\")\n\tif err != nil {\n\t\treturn aws.Region{}, err\n\t}\n\n\tregion := strings.TrimRightFunc(string(md), unicode.IsLetter)\n\treturn aws.Regions[region], nil\n}\n\nfunc (c *Config) AWSAuth() (aws.Auth, error) ", "output": "{\n\tauth, err := aws.GetAuth(c.AccessKey, c.SecretKey)\n\tif err == nil {\n\t\tc.AccessKey = auth.AccessKey\n\t\tc.SecretKey = auth.SecretKey\n\t}\n\n\treturn auth, err\n}"} {"input": "package update\n\nimport (\n\t\"os\"\n\n\t\"github.com/pkg/term\"\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\n\nfunc getChar() (ascii int, keyCode int, err error) {\n\tt, _ := term.Open(\"/dev/tty\")\n\tterm.RawMode(t)\n\tbs := make([]byte, 3)\n\n\tvar numRead int\n\tnumRead, err = t.Read(bs)\n\tif err != nil {\n\t\treturn\n\t}\n\tif numRead == 3 && bs[0] == 27 && bs[1] == 91 {\n\n\t\tif bs[2] == 65 {\n\t\t\tkeyCode = 38\n\t\t} else if bs[2] == 66 {\n\t\t\tkeyCode = 40\n\t\t} else if bs[2] == 67 {\n\t\t\tkeyCode = 39\n\t\t} else if bs[2] == 68 {\n\t\t\tkeyCode = 37\n\t\t}\n\t} else if numRead == 1 {\n\t\tascii = int(bs[0])\n\t} else {\n\t}\n\tt.Restore()\n\tt.Close()\n\treturn\n}\n\nfunc terminalWidth() uint16 ", "output": "{\n\tws, _ := unix.IoctlGetWinsize(int(os.Stdout.Fd()), unix.TIOCGWINSZ)\n\tif ws != nil && ws.Col != 0 {\n\t\treturn ws.Col\n\t}\n\treturn 9999\n}"} {"input": "package server\n\nimport (\n\t\"bytes\"\n\t\"crypto/sha512\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/boltdb/bolt\"\n)\n\nfunc (s *server) isTrusted(r *http.Request) bool {\n\tif r.TLS == nil {\n\t\treturn false\n\t}\n\tfor i := range r.TLS.PeerCertificates {\n\t\tif s.checkTrustState(r.TLS.PeerCertificates[i]) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc (s *server) saveCert(cert *x509.Certificate) error {\n\terr := s.db.Update(func(tx *bolt.Tx) error {\n\t\tb, err := tx.CreateBucketIfNotExists([]byte(\"certificates\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn b.Put(certGenerateFingerprint(cert), cert.Raw)\n\t})\n\treturn err\n}\n\nfunc (s *server) passwordCheck(password string) bool {\n\tif s.registerPass == \"\" {\n\t\treturn false\n\t}\n\n\tif !bytes.Equal([]byte(password), []byte(s.registerPass)) {\n\t\ts.log.Print(\"Bad password received\")\n\t\treturn false\n\t}\n\ts.log.Print(\"Verified the admin password\")\n\n\treturn true\n}\n\nfunc certGenerateFingerprint(cert *x509.Certificate) []byte {\n\tsum := sha512.Sum512(cert.Raw)\n\treturn sum[:]\n}\n\nfunc TrustedResponse() string {\n\treturn \"It Works and you have a trusted cert!\"\n}\n\nfunc UnTrustedResponse() string {\n\treturn \"It Works!\"\n}\n\nfunc (s *server) checkTrustState(cert *x509.Certificate) bool ", "output": "{\n\terr := s.db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(\"certificates\"))\n\t\tif b == nil {\n\t\t\treturn fmt.Errorf(\"Untrusted\")\n\t\t}\n\t\tv := b.Get(certGenerateFingerprint(cert))\n\t\tif bytes.Compare(cert.Raw, v) == 0 {\n\t\t\ts.log.Print(\"Found trusted certificate\")\n\t\t\treturn nil\n\t\t}\n\t\ts.log.Print(\"Client certificate is not trusted\")\n\t\treturn fmt.Errorf(\"Untrusted\")\n\t})\n\n\tif err == nil {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package wire_test\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\n\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc newFixedWriter(max int) io.Writer ", "output": "{\n\tb := make([]byte, max, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}"} {"input": "package chipmunk\n\nimport (\n\t\"github.com/Dethrail/chipmunk/transform\"\n\t\"github.com/Dethrail/chipmunk/vect\"\n\t\"math\"\n)\n\nconst (\n\tRadianConst = math.Pi / 180\n\tDegreeConst = 180 / math.Pi\n)\n\ntype Group int\ntype Layer int\n\ntype Shape struct {\n\tDefaultHash\n\tShapeClass\n\n\tBody *Body\n\n\tBB AABB\n\n\tIsSensor bool\n\n\te vect.Float\n\tu vect.Float\n\tSurface_v vect.Vect\n\n\tUserData interface{}\n\n\tGroup Group\n\tLayer Layer\n\n\tspace *Space\n\n\tvelocityIndexed bool\n}\n\nfunc newShape() *Shape {\n\treturn &Shape{velocityIndexed: true, e: 0.5, u: 0.5, Layer: -1}\n\n}\n\nfunc (shape *Shape) Velocity() (vect.Vect, bool) {\n\treturn shape.Body.v, shape.velocityIndexed\n}\n\nfunc (shape *Shape) SetFriction(friction vect.Float) {\n\tshape.u = friction\n}\n\nfunc (shape *Shape) SetElasticity(e vect.Float) {\n\tshape.e = e\n}\n\nfunc (shape *Shape) Shape() *Shape {\n\treturn shape\n}\n\nfunc (shape *Shape) AABB() AABB {\n\treturn shape.BB\n}\n\n\n\nfunc (shape *Shape) Update() {\n\tshape.BB = shape.ShapeClass.update(transform.NewTransform(shape.Body.p, shape.Body.a))\n}\n\nfunc (shape *Shape) Clone() *Shape ", "output": "{\n\tclone := *shape\n\tcc := &clone\n\tcc.space = nil\n\tcc.DefaultHash.Reset()\n\tcc.Body = nil\n\tcc.ShapeClass = cc.ShapeClass.Clone(cc)\n\treturn cc\n}"} {"input": "package env\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/pflag\"\n\n\t\"github.com/jaegertracing/jaeger/plugin/storage\"\n)\n\nconst (\n\tlongTemplate = `\nAll command line options can be provided via environment variables by converting\ntheir names to upper case and replacing punctuation with underscores. For example:\n\ncommand line option environment variable\n------------------------------------------------------------------\n--cassandra.connections-per-host CASSANDRA_CONNECTIONS_PER_HOST\n--metrics-backend METRICS_BACKEND\n\nThe following configuration options are only available via environment variables:\n%s\n`\n\tstorageTypeDescription = `The type of backend [%s] used for trace storage.\nMultiple backends can be specified as comma-separated list, e.g. \"cassandra,elasticsearch\"\n(currently only for writing spans). Note that \"kafka\" is only valid in jaeger-collector;\nit is not a replacement for a proper storage backend, and only used as a buffer for spans\nwhen Jaeger is deployed in the collector+ingester configuration.\n`\n)\n\n\n\n\nfunc Command() *cobra.Command ", "output": "{\n\tfs := new(pflag.FlagSet)\n\tfs.String(\n\t\tstorage.SpanStorageTypeEnvVar,\n\t\t\"cassandra\",\n\t\tfmt.Sprintf(\n\t\t\tstrings.ReplaceAll(storageTypeDescription, \"\\n\", \" \"),\n\t\t\tstrings.Join(storage.AllStorageTypes, \", \"),\n\t\t),\n\t)\n\tfs.String(\n\t\tstorage.DependencyStorageTypeEnvVar,\n\t\t\"${SPAN_STORAGE_TYPE}\",\n\t\t\"The type of backend used for service dependencies storage.\",\n\t)\n\tlong := fmt.Sprintf(longTemplate, strings.Replace(fs.FlagUsagesWrapped(0), \" --\", \"\\n\", -1))\n\treturn &cobra.Command{\n\t\tUse: \"env\",\n\t\tShort: \"Help about environment variables.\",\n\t\tLong: long,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Fprint(cmd.OutOrStdout(), long)\n\t\t},\n\t}\n}"} {"input": "package vcl\n\n\n\n\nimport (\n\t. \"github.com/ying32/govcl/vcl/api\"\n\t. \"github.com/ying32/govcl/vcl/types\"\n)\n\ntype (\n\tNSObject uintptr\n\n\tNSWindow uintptr\n\n\tNSURL uintptr\n)\n\n\nfunc HandleToPlatformHandle(h HWND) NSObject {\n\treturn NSObject(h)\n}\n\nfunc (f *TForm) PlatformWindow() NSWindow {\n\tr, _, _ := NSWindow_FromForm.Call(f.instance)\n\treturn NSWindow(r)\n}\n\nfunc (n NSWindow) TitleVisibility() NSWindowTitleVisibility {\n\tr, _, _ := NSWindow_titleVisibility.Call(uintptr(n))\n\treturn NSWindowTitleVisibility(r)\n}\n\nfunc (n NSWindow) SetTitleVisibility(flag NSWindowTitleVisibility) {\n\tNSWindow_setTitleVisibility.Call(uintptr(n), uintptr(flag))\n}\n\nfunc (n NSWindow) TitleBarAppearsTransparent() bool {\n\tr, _, _ := NSWindow_titlebarAppearsTransparent.Call(uintptr(n))\n\treturn DBoolToGoBool(r)\n}\n\nfunc (n NSWindow) SetTitleBarAppearsTransparent(flag bool) {\n\tNSWindow_setTitlebarAppearsTransparent.Call(uintptr(n), GoBoolToDBool(flag))\n}\n\n\n\nfunc (n NSWindow) StyleMask() uint {\n\tr, _, _ := NSWindow_styleMask.Call(uintptr(n))\n\treturn uint(r)\n}\n\nfunc (n NSWindow) SetStyleMask(mask uint) {\n\tNSWindow_setStyleMask.Call(uintptr(n), uintptr(mask))\n}\n\nfunc (n NSWindow) SetRepresentedURL(url NSURL) ", "output": "{\n\tNSWindow_setRepresentedURL.Call(uintptr(n), uintptr(url))\n}"} {"input": "package installer\n\nimport (\n\t\"github.com/wx13/genesis\"\n)\n\n\n\ntype Custom struct {\n\tTask genesis.Doer\n\tS func() (genesis.Status, error)\n\tD func() (bool, error)\n\tU func() (bool, error)\n\tI func() string\n\tF func() []string\n}\n\nfunc NewCustom(task genesis.Doer) *Custom {\n\tcustom := Custom{\n\t\tTask: task,\n\t\tS: task.Status,\n\t\tD: task.Do,\n\t\tU: task.Undo,\n\t\tI: task.ID,\n\t\tF: task.Files,\n\t}\n\treturn &custom\n}\n\nfunc (custom Custom) Status() (genesis.Status, error) {\n\treturn custom.S()\n}\n\nfunc (custom Custom) Do() (bool, error) {\n\treturn custom.D()\n}\n\n\n\nfunc (custom Custom) ID() string {\n\treturn custom.I()\n}\n\nfunc (custom Custom) Files() []string {\n\treturn custom.F()\n}\n\nfunc (custom Custom) Undo() (bool, error) ", "output": "{\n\treturn custom.U()\n}"} {"input": "package label\n\n\n\n\n\n\nfunc FormatMountLabel(src string, mountLabel string) string {\n\treturn src\n}\n\nfunc SetProcessLabel(processLabel string) error {\n\treturn nil\n}\n\nfunc SetFileLabel(path string, fileLabel string) error {\n\treturn nil\n}\n\nfunc SetFileCreateLabel(fileLabel string) error {\n\treturn nil\n}\n\nfunc Relabel(path string, fileLabel string, relabel string) error {\n\treturn nil\n}\n\nfunc GetPidLabel(pid int) (string, error) {\n\treturn \"\", nil\n}\n\nfunc Init() {\n}\n\nfunc ReserveLabel(label string) error {\n\treturn nil\n}\n\nfunc UnreserveLabel(label string) error {\n\treturn nil\n}\n\n\n\nfunc DupSecOpt(src string) []string {\n\treturn nil\n}\n\n\n\nfunc DisableSecOpt() []string {\n\treturn nil\n}\n\nfunc InitLabels(mcsdir string, options []string) (string, string, error) ", "output": "{\n\treturn \"\", \"\", nil\n}"} {"input": "package victor\n\nimport (\n\t\"github.com/FogCreek/victor/pkg/chat\"\n)\n\n\ntype Handler interface {\n\tHandle(State)\n}\n\n\ntype HandlerFunc func(State)\n\n\n\nfunc (f HandlerFunc) Handle(s State) {\n\tf(s)\n}\n\n\n\ntype State interface {\n\tRobot() Robot\n\tChat() chat.Adapter\n\tMessage() chat.Message\n\tFields() []string\n\tReply(string)\n}\n\ntype state struct {\n\trobot Robot\n\tmessage chat.Message\n\tfields []string\n}\n\n\n\n\n\nfunc (s *state) Reply(msg string) {\n\ts.robot.Chat().Send(s.message.Channel().ID(), msg)\n}\n\n\n\n\n\nfunc (s *state) Chat() chat.Adapter {\n\treturn s.robot.Chat()\n}\n\n\nfunc (s *state) Message() chat.Message {\n\treturn s.message\n}\n\nfunc (s *state) Fields() []string {\n\treturn s.fields\n}\n\nfunc (s *state) Robot() Robot ", "output": "{\n\treturn s.robot\n}"} {"input": "package fuse\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\ntype MountConfig struct {\n\tOpContext context.Context\n\n\tFSName string\n\n\tReadOnly bool\n\n\tErrorLogger *log.Logger\n\n\tDebugLogger *log.Logger\n\n\tDisableWritebackCaching bool\n\n\tEnableVnodeCaching bool\n\n\tOptions map[string]string\n}\n\n\n\n\n\nfunc escapeOptionsKey(s string) (res string) {\n\tres = s\n\tres = strings.Replace(res, `\\`, `\\\\`, -1)\n\tres = strings.Replace(res, `,`, `\\,`, -1)\n\treturn\n}\n\n\nfunc (c *MountConfig) toOptionsString() string {\n\tvar components []string\n\tfor k, v := range c.toMap() {\n\t\tk = escapeOptionsKey(k)\n\n\t\tcomponent := k\n\t\tif v != \"\" {\n\t\t\tcomponent = fmt.Sprintf(\"%s=%s\", k, v)\n\t\t}\n\n\t\tcomponents = append(components, component)\n\t}\n\n\treturn strings.Join(components, \",\")\n}\n\nfunc (c *MountConfig) toMap() (opts map[string]string) ", "output": "{\n\tisDarwin := runtime.GOOS == \"darwin\"\n\topts = make(map[string]string)\n\n\topts[\"default_permissions\"] = \"\"\n\n\tfsname := c.FSName\n\tif runtime.GOOS == \"linux\" && fsname == \"\" {\n\t\tfsname = \"some_fuse_file_system\"\n\t}\n\n\tif fsname != \"\" {\n\t\topts[\"fsname\"] = fsname\n\t}\n\n\tif c.ReadOnly {\n\t\topts[\"ro\"] = \"\"\n\t}\n\n\tif isDarwin && !c.EnableVnodeCaching {\n\t\topts[\"novncache\"] = \"\"\n\t}\n\n\tif isDarwin {\n\t\topts[\"noappledouble\"] = \"\"\n\t}\n\n\tfor k, v := range c.Options {\n\t\topts[k] = v\n\t}\n\n\treturn\n}"} {"input": "package npm\n\nimport \"github.com/node4j/node-repo-proxy/util\"\n\n\n\nfunc loadMetaData(name string) ([]byte, error) {\n\tindex, err := fetchIndex(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif index == nil {\n\t\treturn nil, nil\n\t}\n\n\tdata, err := indexToMaven(*index)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}\n\nfunc GetMetaData(name string) ([]byte, error) ", "output": "{\n\tkey := \"npm.\" + name\n\tdata, found := util.GetFromCache(key)\n\tif found {\n\t\treturn data.([]byte), nil\n\t}\n\n\tdata, err := loadMetaData(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tutil.PutInCache(key, data)\n\treturn data.([]byte), nil\n}"} {"input": "package gostatic\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n)\n\nconst (\n\tPre = 1 << iota\n\tHidden\n\tPost\n)\n\ntype Processor interface {\n\tProcess(page *Page, args []string) error\n\tDescription() string\n\tMode() int\n}\n\n\n\n\n\nfunc (s *Site) InitProcessors(m map[string]Processor) {\n\ts.Processors = m\n}\n\nfunc (s *Site) ProcessorSummary() {\n\tkeys := make([]string, 0, len(s.Processors))\n\tfor k := range s.Processors {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\n\tfor _, k := range keys {\n\t\tp := s.Processors[k]\n\t\tif p.Mode()&Hidden != 0 {\n\t\t\tcontinue\n\t\t}\n\t\tpre := \"\"\n\t\tif p.Mode()&Pre != 0 {\n\t\t\tpre = \"(preprocessor)\"\n\t\t}\n\t\tfmt.Printf(\"- %s %s\\n\\t%s\\n\", k, pre, p.Description())\n\t}\n}\n\n\n\nfunc (s *Site) ProcessCommand(page *Page, cmd *Command, pre bool) error ", "output": "{\n\tc := string(*cmd)\n\tif strings.HasPrefix(c, \":\") {\n\t\tc = \"external \" + c[1:]\n\t}\n\tbits := strings.Split(c, \" \")\n\n\tprocessor := s.Processors[bits[0]]\n\tif processor == nil {\n\t\treturn fmt.Errorf(\"Processor is nil\")\n\t}\n\tif (processor.Mode()&Pre != 0) != pre {\n\t\treturn nil\n\t}\n\tif processor == nil {\n\t\treturn fmt.Errorf(\"processor '%s' not found\", bits[0])\n\t}\n\treturn processor.Process(page, bits[1:])\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestParseHdbSignatureRow(t *testing.T) ", "output": "{\n\tsignature := new(signature)\n\tsample := \"e11c2aff804ca144a3e49c42d6ac5783:1006:Exploit.CVE_2012_0779\"\n\tsig := parseHdbSignatureRow(sample, signature)\n\n\tif sig.Size != 1006 {\n\t\tt.Fatal(\"Error parsing HDB or HSB signature length\")\n\t}\n\n\tif signature.SigHash != \"e11c2aff804ca144a3e49c42d6ac5783\" {\n\t\tt.Fatal(\"Error parsing HDB or HSB signature hash\")\n\t}\n}"} {"input": "package events\n\nimport (\n\t\"github.com/mesos/mesos-go/executor\"\n)\n\ntype (\n\tDecorator func(Handler) Handler\n\n\tDecorators []Decorator\n)\n\nvar noopDecorator = Decorator(func(h Handler) Handler { return h })\n\n\n\nfunc (d Decorator) If(b bool) Decorator {\n\tif d == nil {\n\t\treturn noopDecorator\n\t}\n\tresult := noopDecorator\n\tif b {\n\t\tresult = d\n\t}\n\treturn result\n}\n\n\n\nfunc (d Decorator) When(f func() bool) Decorator {\n\tif d == nil || f == nil {\n\t\treturn noopDecorator\n\t}\n\treturn func(h Handler) Handler {\n\t\tdecorated := d(h)\n\t\treturn HandlerFunc(func(e *executor.Event) (err error) {\n\t\t\tif f() {\n\t\t\t\terr = decorated.HandleEvent(e)\n\t\t\t} else {\n\t\t\t\terr = h.HandleEvent(e)\n\t\t\t}\n\t\t\treturn\n\t\t})\n\t}\n}\n\n\n\nfunc (ds Decorators) Apply(h Handler) Handler {\n\tfor _, d := range ds {\n\t\th = d.Apply(h)\n\t}\n\treturn h\n}\n\n\n\nfunc (d Decorator) Apply(h Handler) Handler ", "output": "{\n\tif d != nil {\n\t\th = d(h)\n\t}\n\treturn h\n}"} {"input": "package classfile\n\n\ntype ConstantStringInfo struct {\n\tcp ConstantPool\n\tstringIndex uint16\n}\n\nfunc (self *ConstantStringInfo) readInfo(reader *ClassReader) {\n\tself.stringIndex = reader.readUint16()\n}\nfunc (self *ConstantStringInfo) String() string {\n\treturn self.cp.getUtf8(self.stringIndex)\n}\n\n\nfunc (self *ConstantStringInfo) toString() string ", "output": "{\n\treturn \"String\"\n}"} {"input": "package main_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/boltdb/bolt\"\n\t. \"github.com/boltdb/bolt/cmd/bolt\"\n)\n\n\nfunc TestBuckets(t *testing.T) {\n\tSetTestMode(true)\n\topen(func(db *bolt.DB, path string) {\n\t\tdb.Update(func(tx *bolt.Tx) error {\n\t\t\ttx.CreateBucket([]byte(\"woojits\"))\n\t\t\ttx.CreateBucket([]byte(\"widgets\"))\n\t\t\ttx.CreateBucket([]byte(\"whatchits\"))\n\t\t\treturn nil\n\t\t})\n\t\tdb.Close()\n\t\toutput := run(\"buckets\", path)\n\t\tequals(t, \"whatchits\\nwidgets\\nwoojits\", output)\n\t})\n}\n\n\n\n\nfunc TestBucketsDBNotFound(t *testing.T) ", "output": "{\n\tSetTestMode(true)\n\toutput := run(\"buckets\", \"no/such/db\")\n\tequals(t, \"stat no/such/db: no such file or directory\", output)\n}"} {"input": "package helios\n\nimport (\n\t\"fmt\"\n)\n\ntype HostsService struct {\n\tclient *Client\n}\n\n\n\nfunc (s *HostsService) Status(host string) (*HostStatus, error) {\n\treq, err := s.client.NewRequest(\"GET\", fmt.Sprintf(\"/hosts/%s/status\", host))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ths := &HostStatus{}\n\tif s.client.Do(req, hs) != nil {\n\t\treturn nil, err\n\t}\n\n\treturn hs, nil\n}\n\nfunc (s *HostsService) List() ([]string, error) ", "output": "{\n\treq, err := s.client.NewRequest(\"GET\", \"/hosts\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thosts := &[]string{}\n\tif s.client.Do(req, hosts) != nil {\n\t\treturn nil, err\n\t}\n\n\treturn *hosts, nil\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype DeleteVirtualCircuitRequest struct {\n\n\tVirtualCircuitId *string `mandatory:\"true\" contributesTo:\"path\" name:\"virtualCircuitId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n}\n\n\n\n\ntype DeleteVirtualCircuitResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteVirtualCircuitResponse) String() string {\n\treturn common.PointerString(response)\n}\n\nfunc (request DeleteVirtualCircuitRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetCrossConnectRequest struct {\n\n\tCrossConnectId *string `mandatory:\"true\" contributesTo:\"path\" name:\"crossConnectId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetCrossConnectRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request GetCrossConnectRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request GetCrossConnectRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype GetCrossConnectResponse struct {\n\n\tRawResponse *http.Response\n\n\tCrossConnect `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetCrossConnectResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetCrossConnectResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetCrossConnectRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package pgx\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/user\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nfunc parsepgpass(cfg *ConnConfig, line string) *string {\n\tconst (\n\t\tbackslash = \"\\r\"\n\t\tcolon = \"\\n\"\n\t)\n\tconst (\n\t\thost int = iota\n\t\tport\n\t\tdatabase\n\t\tusername\n\t\tpw\n\t)\n\tline = strings.Replace(line, `\\:`, colon, -1)\n\tline = strings.Replace(line, `\\\\`, backslash, -1)\n\tparts := strings.Split(line, `:`)\n\tif len(parts) != 5 {\n\t\treturn nil\n\t}\n\tfor i := range parts {\n\t\tif parts[i] == `*` {\n\t\t\tcontinue\n\t\t}\n\t\tparts[i] = strings.Replace(strings.Replace(parts[i], backslash, `\\`, -1), colon, `:`, -1)\n\t\tswitch i {\n\t\tcase host:\n\t\t\tif parts[i] != cfg.Host {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase port:\n\t\t\tportstr := fmt.Sprintf(`%v`, cfg.Port)\n\t\t\tif portstr == \"0\" {\n\t\t\t\tportstr = \"5432\"\n\t\t\t}\n\t\t\tif parts[i] != portstr {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase database:\n\t\t\tif parts[i] != cfg.Database {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase username:\n\t\t\tif parts[i] != cfg.User {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\treturn &parts[4]\n}\n\n\n\nfunc pgpass(cfg *ConnConfig) (found bool) ", "output": "{\n\tpassfile := os.Getenv(\"PGPASSFILE\")\n\tif passfile == \"\" {\n\t\tu, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tpassfile = filepath.Join(u.HomeDir, \".pgpass\")\n\t}\n\tf, err := os.Open(passfile)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer f.Close()\n\tscanner := bufio.NewScanner(f)\n\tvar pw *string\n\tfor scanner.Scan() {\n\t\tpw = parsepgpass(cfg, scanner.Text())\n\t\tif pw != nil {\n\t\t\tcfg.Password = *pw\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\tupTar \"archive/tar\"\n\n\tourTar \"github.com/vbatts/tar-split/archive/tar\"\n)\n\nvar testfile = \"../../archive/tar/testdata/sparse-formats.tar\"\n\nfunc BenchmarkUpstreamTar(b *testing.B) {\n\tfor n := 0; n < b.N; n++ {\n\t\tfh, err := os.Open(testfile)\n\t\tif err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t\ttr := upTar.NewReader(fh)\n\t\tfor {\n\t\t\t_, err := tr.Next()\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfh.Close()\n\t\t\t\tb.Fatal(err)\n\t\t\t}\n\t\t\tio.Copy(ioutil.Discard, tr)\n\t\t}\n\t\tfh.Close()\n\t}\n}\n\n\nfunc BenchmarkOurTarYesAccounting(b *testing.B) {\n\tfor n := 0; n < b.N; n++ {\n\t\tfh, err := os.Open(testfile)\n\t\tif err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t\ttr := ourTar.NewReader(fh)\n\t\ttr.RawAccounting = true \n\t\tfor {\n\t\t\t_ = tr.RawBytes()\n\t\t\t_, err := tr.Next()\n\t\t\t_ = tr.RawBytes()\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfh.Close()\n\t\t\t\tb.Fatal(err)\n\t\t\t}\n\t\t\tio.Copy(ioutil.Discard, tr)\n\t\t\t_ = tr.RawBytes()\n\t\t}\n\t\tfh.Close()\n\t}\n}\n\nfunc BenchmarkOurTarNoAccounting(b *testing.B) ", "output": "{\n\tfor n := 0; n < b.N; n++ {\n\t\tfh, err := os.Open(testfile)\n\t\tif err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t\ttr := ourTar.NewReader(fh)\n\t\ttr.RawAccounting = false \n\t\tfor {\n\t\t\t_, err := tr.Next()\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfh.Close()\n\t\t\t\tb.Fatal(err)\n\t\t\t}\n\t\t\tio.Copy(ioutil.Discard, tr)\n\t\t}\n\t\tfh.Close()\n\t}\n}"} {"input": "package behaviors\n\n\n\n\n\nimport (\n\t\"github.com/tideland/golib/cells\"\n\t\"github.com/tideland/golib/logger\"\n)\n\n\n\n\n\n\ntype CallbackFunc func(topic string, payload cells.Payload) error\n\n\n\ntype callbackBehavior struct {\n\tctx cells.Context\n\tcallbackFuncs []CallbackFunc\n}\n\n\n\n\nfunc NewCallbackBehavior(cbfs ...CallbackFunc) cells.Behavior {\n\tif len(cbfs) == 0 {\n\t\tlogger.Errorf(\"callback created without callback functions\")\n\t}\n\treturn &callbackBehavior{nil, cbfs}\n}\n\n\nfunc (b *callbackBehavior) Init(ctx cells.Context) error {\n\tb.ctx = ctx\n\treturn nil\n}\n\n\nfunc (b *callbackBehavior) Terminate() error {\n\treturn nil\n}\n\n\n\n\n\nfunc (b *callbackBehavior) Recover(err interface{}) error {\n\treturn nil\n}\n\nfunc (b *callbackBehavior) ProcessEvent(event cells.Event) error ", "output": "{\n\tfor _, callbackFunc := range b.callbackFuncs {\n\t\tif err := callbackFunc(event.Topic(), event.Payload()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net\"\n\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/host\", hostFinder)\n\thttp.HandleFunc(\"/ip\", sourceIp)\n\thttp.HandleFunc(\"/date\", GetJosnTime)\n\tfmt.Println(\"Listening on 0.0.0.0:8000\")\n\terr := http.ListenAndServe(\"0.0.0.0:8000\", nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}\n\nfunc hostFinder(rw http.ResponseWriter, req *http.Request) {\n\thostPort := req.Host\n\thost, port, _ := net.SplitHostPort(hostPort)\n\tio.WriteString(rw, \"\")\n\tio.WriteString(rw, \"Host Name : \"+host+\"
\")\n\tio.WriteString(rw, \"Port Number : \"+port)\n\tio.WriteString(rw, \"
\")\n\tio.WriteString(rw, req.RemoteAddr)\n\tio.WriteString(rw, \"\")\n\n}\n\nfunc sourceIp(rw http.ResponseWriter, req *http.Request) {\n\thost, _, _ := net.SplitHostPort(req.RemoteAddr)\n\tio.WriteString(rw, \"

Your Ip address : \"+host)\n}\n\n\nfunc GetJosnTime(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\trw.Header().Set(\"Content-type\", \"application/json\")\n\trw.Header().Add(\"Content-type\", \"charset=utf-8\")\n\tresponse, _ := http.Get(\"http://date.jsontest.com/\")\n\tdefer response.Body.Close()\n\n\tdata, _ := ioutil.ReadAll(response.Body)\n\tio.WriteString(rw, string(data))\n\n}"} {"input": "package api\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n)\n\n\nfunc SendSystemMessage(w http.ResponseWriter, req *http.Request) {\n\tlog.Print(\"processing SendSystemMessage\")\n\tio.WriteString(w, \"SendSystemMessage!\\n\")\n}\n\n\n\n\nfunc SetServiceStatus(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tlog.Print(\"processing SetServiceStatus\")\n\tio.WriteString(w, \"SetServiceStatus!\\n\")\n}"} {"input": "package builtin\n\nconst systemTraceSummary = `allows using kernel tracing facilities`\n\nconst systemTraceConnectedPlugAppArmor = `\n# Description: Can use kernel tracing facilities. This is restricted because it\n# gives privileged access to all processes on the system and should only be\n# used with trusted apps.\n\n # For the bpf() syscall and manipulating bpf map types\n capability sys_admin,\n capability sys_resource,\n\n # For kernel probes, etc\n /sys/kernel/debug/kprobes/ r,\n /sys/kernel/debug/kprobes/** r,\n\n /sys/kernel/debug/tracing/ r,\n /sys/kernel/debug/tracing/** rw,\n\n # Access to kernel headers required for iovisor/bcc. This is typically\n # detected with 'ls -l /lib/modules/$(uname -r)/build/' which is a symlink\n # to /usr/src on Ubuntu and so only /usr/src is needed.\n /usr/src/ r,\n /usr/src/** r,\n`\n\nconst systemTraceConnectedPlugSecComp = `\n# Description: Can use kernel tracing facilities. This is restricted because it\n# gives privileged access to all processes on the system and should only be\n# used with trusted apps.\n\nbpf\nperf_event_open\n`\n\n\n\nfunc init() ", "output": "{\n\tregisterIface(&commonInterface{\n\t\tname: \"system-trace\",\n\t\tsummary: systemTraceSummary,\n\t\timplicitOnCore: true,\n\t\timplicitOnClassic: true,\n\t\tconnectedPlugAppArmor: systemTraceConnectedPlugAppArmor,\n\t\tconnectedPlugSecComp: systemTraceConnectedPlugSecComp,\n\t\treservedForOS: true,\n\t})\n}"} {"input": "package main\n\nimport ()\n\ntype channel struct {\n\tpath string\n\tqueue queue\n\tconnections connections\n\th *hub\n}\n\ntype connections map[*connection]interface {\n}\n\nfunc (c *channel) run() {\n\tincr(\"channels\", 1)\n\tdefer c.stop()\n\tfor cmd := range c.queue {\n\t\tswitch cmd.cmd {\n\t\tcase SUBSCRIBE:\n\t\t\tc.subscribe(cmd.conn)\n\t\tcase UNSUBSCRIBE:\n\t\t\tc.unsubscribe(cmd.conn)\n\t\t\tif len(c.connections) == 0 {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase PUBLISH:\n\t\t\tc.publish(cmd.text)\n\t\tcase BROADCAST:\n\t\t\tc.broadcast(cmd.text)\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n\n\nfunc (c *channel) subscribe(conn *connection) {\n\tc.connections[conn] = nil\n}\n\nfunc (c *channel) unsubscribe(conn *connection) {\n\tif _, ok := c.connections[conn]; ok {\n\t\tclose(conn.send)\n\t\tdelete(c.connections, conn)\n\t}\n}\n\nfunc (c *channel) publish(text []byte) {\n\tif len(text) == 0 {\n\t\treturn\n\t}\n\tc.h.queue <- command{cmd: PUBLISH, path: c.path, text: text}\n}\n\nfunc (c *channel) broadcast(text []byte) {\n\tif len(text) == 0 {\n\t\treturn\n\t}\n\tfor conn := range c.connections {\n\t\tselect {\n\t\tcase conn.send <- text:\n\t\tdefault:\n\t\t\tc.unsubscribe(conn)\n\t\t}\n\t}\n}\n\nfunc (c *channel) stop() ", "output": "{\n\tclose(c.queue)\n\tc.h.queue <- command{cmd: REMOVE, path: c.path}\n\tdecr(\"channels\", 1)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nfunc main() {\n\n\tvar lilahS string\n\tvar howManyLetters int\n\t_, err := fmt.Scanf(\"%s\\n%d\", &lilahS, &howManyLetters)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"%d\\n\", countHowManyAs(lilahS, howManyLetters))\n}\n\n\n\nfunc countHowManyAs(word string, howManyLetters int) int ", "output": "{\n\tleftLetters := howManyLetters % len(word)\n\thowManyFullRepeats := (howManyLetters - leftLetters) / len(word)\n\n\treturn (howManyFullRepeats*strings.Count(word, \"a\") + strings.Count(word[0:leftLetters], \"a\"))\n}"} {"input": "package internalversion\n\nimport (\n\tapi \"k8s.io/kubernetes/pkg/api\"\n\tregistered \"k8s.io/kubernetes/pkg/apimachinery/registered\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n)\n\ntype PolicyInterface interface {\n\tRESTClient() restclient.Interface\n\tEvictionsGetter\n\tPodDisruptionBudgetsGetter\n}\n\n\ntype PolicyClient struct {\n\trestClient restclient.Interface\n}\n\nfunc (c *PolicyClient) Evictions(namespace string) EvictionInterface {\n\treturn newEvictions(c, namespace)\n}\n\nfunc (c *PolicyClient) PodDisruptionBudgets(namespace string) PodDisruptionBudgetInterface {\n\treturn newPodDisruptionBudgets(c, namespace)\n}\n\n\nfunc NewForConfig(c *restclient.Config) (*PolicyClient, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := restclient.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &PolicyClient{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *restclient.Config) *PolicyClient {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c restclient.Interface) *PolicyClient {\n\treturn &PolicyClient{c}\n}\n\n\n\n\n\nfunc (c *PolicyClient) RESTClient() restclient.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc setConfigDefaults(config *restclient.Config) error ", "output": "{\n\tg, err := registered.Group(\"policy\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.APIPath = \"/apis\"\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = restclient.DefaultKubernetesUserAgent()\n\t}\n\tif config.GroupVersion == nil || config.GroupVersion.Group != g.GroupVersion.Group {\n\t\tcopyGroupVersion := g.GroupVersion\n\t\tconfig.GroupVersion = ©GroupVersion\n\t}\n\tconfig.NegotiatedSerializer = api.Codecs\n\n\tif config.QPS == 0 {\n\t\tconfig.QPS = 5\n\t}\n\tif config.Burst == 0 {\n\t\tconfig.Burst = 10\n\t}\n\treturn nil\n}"} {"input": "package token\n\nimport (\n\t\"strings\"\n\n\t\"github.com/carlcui/expressive/locator\"\n)\n\n\ntype Token struct {\n\tTokenType Type\n\tRaw string\n\tLocator locator.Locator\n}\n\nfunc (tok *Token) String() string {\n\treturn tok.TokenType.String() + \": \" + tok.Raw\n}\n\nfunc (tok *Token) GetLocation() string {\n\tif tok.Locator == nil {\n\t\treturn \"unknown location\"\n\t}\n\n\treturn tok.Locator.Locate()\n}\n\n\nfunc IllegalToken(raw string, locator locator.Locator) *Token {\n\treturn &Token{TokenType: ILLEGAL, Raw: raw, Locator: locator}\n}\n\n\nfunc EOFToken(locator locator.Locator) *Token {\n\treturn &Token{TokenType: EOF, Raw: \"\", Locator: locator}\n}\n\n\n\nfunc MatchKeyword(reading string) *Token {\n\tif tokenType, isKeyword := keywords[reading]; isKeyword {\n\t\treturn &Token{TokenType: tokenType, Raw: reading}\n\t}\n\n\treturn nil\n}\n\nfunc MatchOperator(reading string) *Token {\n\tif tokenType, isOperator := operators[reading]; isOperator {\n\t\treturn &Token{TokenType: tokenType, Raw: reading}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc HasOperatorPrefix(reading string) bool ", "output": "{\n\tfor i := operatorStart + 1; i < operatorEnd; i++ {\n\t\tif strings.HasPrefix(tokens[i], reading) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package mlib\n\nimport (\n\t\"io\"\n)\n\ntype reader struct {\n\tinner io.Reader\n}\n\n\n\n\nfunc (r *reader) Read(p []byte) (int, error) {\n\tread, err := r.inner.Read(p)\n\tretLen := 0\n\tfor i := 0; i < read; i++ {\n\t\tif p[i] != '\\r' {\n\t\t\tp[retLen] = p[i]\n\t\t\tretLen++\n\t\t}\n\t}\n\n\treturn retLen, err\n}\n\nfunc (r *reader) Close() error {\n\tDebug(\"close...\\n\")\n\tswitch r.inner.(type) {\n\tcase io.Closer:\n\t\treturn r.inner.(io.Closer).Close()\n\t}\n\treturn nil\n}\n\nfunc NewCrRemovingReader(inner io.Reader) io.ReadCloser ", "output": "{\n\tr := reader{inner: inner}\n\treturn &r\n}"} {"input": "package http\n\nimport (\n\t\"github.com/asim/go-micro/v3/registry\"\n\t\"github.com/asim/go-micro/v3/server\"\n)\n\ntype httpHandler struct {\n\topts server.HandlerOptions\n\teps []*registry.Endpoint\n\thd interface{}\n}\n\n\n\nfunc (h *httpHandler) Handler() interface{} {\n\treturn h.hd\n}\n\nfunc (h *httpHandler) Endpoints() []*registry.Endpoint {\n\treturn h.eps\n}\n\nfunc (h *httpHandler) Options() server.HandlerOptions {\n\treturn h.opts\n}\n\nfunc (h *httpHandler) Name() string ", "output": "{\n\treturn \"handler\"\n}"} {"input": "package memconn\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"sync\"\n)\n\ntype memconn struct {\n\tsync.Once\n\taddr addr\n\tbsiz uint64\n\tchcn chan net.Conn\n\tdone func()\n\tpool *sync.Pool\n}\n\nfunc (m *memconn) Dial() (net.Conn, error) {\n\tr, w := pipe(&m.addr, m.pool)\n\tgo func() {\n\t\tm.chcn <- r\n\t}()\n\treturn w, nil\n}\n\nfunc (m *memconn) Accept() (net.Conn, error) {\n\tfor c := range m.chcn {\n\t\treturn c, nil\n\t}\n\treturn nil, http.ErrServerClosed\n}\n\n\n\nfunc (m *memconn) Addr() net.Addr {\n\treturn m.addr\n}\n\nfunc (m *memconn) Close() error ", "output": "{\n\tm.Do(func() {\n\t\tclose(m.chcn)\n\t\tm.done()\n\t})\n\treturn http.ErrServerClosed\n}"} {"input": "package gut\n\nvar smallBitLenTable = [16]uint{\n\t0,\n\t1,\n\t2,\n\t2,\n\t3,\n\t3,\n\t3,\n\t3,\n\t4,\n\t4,\n\t4,\n\t4,\n\t4,\n\t4,\n\t4,\n\t4,\n}\n\n\n\nfunc BitLen(x uint) (n uint) ", "output": "{\n\tif x >= 0x80000000 {\n\t\tx >>= 32\n\t\tn += 32\n\t}\n\tif x >= 0x8000 {\n\t\tx >>= 16\n\t\tn += 16\n\t}\n\tif x >= 0x80 {\n\t\tx >>= 8\n\t\tn += 8\n\t}\n\tif x >= 0x8 {\n\t\tx >>= 4\n\t\tn += 4\n\t}\n\n\treturn n + smallBitLenTable[x]\n}"} {"input": "package nettest\n\n\n\nfunc maxOpenFiles() int ", "output": "{\n return 4 * defaultMaxOpenFiles \n}"} {"input": "package filteredFactory\n\nimport (\n\tcontext \"context\"\n\n\tv1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\texternalversions \"knative.dev/eventing-natss/pkg/client/informers/externalversions\"\n\tclient \"knative.dev/eventing-natss/pkg/client/injection/client\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Default.RegisterInformerFactory(withInformerFactory)\n}\n\n\ntype Key struct {\n\tSelector string\n}\n\ntype LabelKey struct{}\n\nfunc WithSelectors(ctx context.Context, selector ...string) context.Context {\n\treturn context.WithValue(ctx, LabelKey{}, selector)\n}\n\n\n\n\nfunc Get(ctx context.Context, selector string) externalversions.SharedInformerFactory {\n\tuntyped := ctx.Value(Key{Selector: selector})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panicf(\n\t\t\t\"Unable to fetch knative.dev/eventing-natss/pkg/client/informers/externalversions.SharedInformerFactory with selector %s from context.\", selector)\n\t}\n\treturn untyped.(externalversions.SharedInformerFactory)\n}\n\nfunc withInformerFactory(ctx context.Context) context.Context ", "output": "{\n\tc := client.Get(ctx)\n\tuntyped := ctx.Value(LabelKey{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch labelkey from context.\")\n\t}\n\tlabelSelectors := untyped.([]string)\n\tfor _, selector := range labelSelectors {\n\t\topts := []externalversions.SharedInformerOption{}\n\t\tif injection.HasNamespaceScope(ctx) {\n\t\t\topts = append(opts, externalversions.WithNamespace(injection.GetNamespaceScope(ctx)))\n\t\t}\n\t\topts = append(opts, externalversions.WithTweakListOptions(func(l *v1.ListOptions) {\n\t\t\tl.LabelSelector = selector\n\t\t}))\n\t\tctx = context.WithValue(ctx, Key{Selector: selector},\n\t\t\texternalversions.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...))\n\t}\n\treturn ctx\n}"} {"input": "package admission\n\nimport (\n\t\"io\"\n\n\t\"k8s.io/kubernetes/pkg/admission\"\n\tclient \"k8s.io/kubernetes/pkg/client/unversioned\"\n)\n\nfunc init() {\n\tadmission.RegisterPlugin(\"SCCExecRestrictions\", func(client client.Interface, config io.Reader) (admission.Interface, error) {\n\t\treturn NewSCCExecRestrictions(client), nil\n\t})\n}\n\n\n\ntype sccExecRestrictions struct {\n\t*admission.Handler\n\tconstraintAdmission *constraint\n\tclient client.Interface\n}\n\nfunc (d *sccExecRestrictions) Admit(a admission.Attributes) (err error) {\n\tif a.GetOperation() != admission.Connect {\n\t\treturn nil\n\t}\n\tif a.GetResource() != \"pods\" {\n\t\treturn nil\n\t}\n\tif a.GetSubresource() != \"attach\" && a.GetSubresource() != \"exec\" {\n\t\treturn nil\n\t}\n\n\tpod, err := d.client.Pods(a.GetNamespace()).Get(a.GetName())\n\tif err != nil {\n\t\treturn admission.NewForbidden(a, err)\n\t}\n\n\tpod.Spec.ServiceAccountName = \"\"\n\tcreateAttributes := admission.NewAttributesRecord(pod, \"pods\", a.GetNamespace(), a.GetName(), a.GetResource(), a.GetSubresource(), admission.Create, a.GetUserInfo())\n\tif err := d.constraintAdmission.Admit(createAttributes); err != nil {\n\t\treturn admission.NewForbidden(a, err)\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc NewSCCExecRestrictions(client client.Interface) admission.Interface ", "output": "{\n\treturn &sccExecRestrictions{\n\t\tHandler: admission.NewHandler(admission.Connect),\n\t\tconstraintAdmission: NewConstraint(client).(*constraint),\n\t\tclient: client,\n\t}\n}"} {"input": "package sensors\n\nimport (\n\t\"github.com/geoffholden/gowx/data\"\n)\n\nvar Sensors map[string]data.SensorParser\n\n\n\nfunc RegisterSensor(key string, sensor data.SensorParser) ", "output": "{\n\tif nil == Sensors {\n\t\tSensors = make(map[string]data.SensorParser)\n\t}\n\tSensors[key] = sensor\n}"} {"input": "package column\n\nimport (\n\t\"github.com/kshvakov/clickhouse/lib/binary\"\n)\n\ntype UInt8 struct{ base }\n\n\n\nfunc (u *UInt8) Write(encoder *binary.Encoder, v interface{}) error {\n\tswitch v := v.(type) {\n\tcase bool:\n\t\treturn encoder.Bool(v)\n\tcase uint8:\n\t\treturn encoder.UInt8(v)\n\tcase int64:\n\t\treturn encoder.UInt8(uint8(v))\n\tcase int:\n\t\treturn encoder.UInt8(uint8(v))\n\t}\n\treturn &ErrUnexpectedType{\n\t\tT: v,\n\t\tColumn: u,\n\t}\n}\n\nfunc (UInt8) Read(decoder *binary.Decoder) (interface{}, error) ", "output": "{\n\tv, err := decoder.UInt8()\n\tif err != nil {\n\t\treturn uint8(0), err\n\t}\n\treturn v, nil\n}"} {"input": "package echo\n\ntype (\n\tGroup struct {\n\t\techo Echo\n\t}\n)\n\nfunc (g *Group) Use(m ...Middleware) {\n\tfor _, h := range m {\n\t\tg.echo.middleware = append(g.echo.middleware, wrapMiddleware(h))\n\t}\n}\n\nfunc (g *Group) Connect(path string, h Handler) {\n\tg.echo.Connect(path, h)\n}\n\nfunc (g *Group) Delete(path string, h Handler) {\n\tg.echo.Delete(path, h)\n}\n\n\n\nfunc (g *Group) Head(path string, h Handler) {\n\tg.echo.Head(path, h)\n}\n\nfunc (g *Group) Options(path string, h Handler) {\n\tg.echo.Options(path, h)\n}\n\nfunc (g *Group) Patch(path string, h Handler) {\n\tg.echo.Patch(path, h)\n}\n\nfunc (g *Group) Post(path string, h Handler) {\n\tg.echo.Post(path, h)\n}\n\nfunc (g *Group) Put(path string, h Handler) {\n\tg.echo.Put(path, h)\n}\n\nfunc (g *Group) Trace(path string, h Handler) {\n\tg.echo.Trace(path, h)\n}\n\nfunc (g *Group) WebSocket(path string, h HandlerFunc) {\n\tg.echo.WebSocket(path, h)\n}\n\nfunc (g *Group) Static(path, root string) {\n\tg.echo.Static(path, root)\n}\n\nfunc (g *Group) ServeDir(path, root string) {\n\tg.echo.ServeDir(path, root)\n}\n\nfunc (g *Group) ServeFile(path, file string) {\n\tg.echo.ServeFile(path, file)\n}\n\nfunc (g *Group) Group(prefix string, m ...Middleware) *Group {\n\treturn g.echo.Group(prefix, m...)\n}\n\nfunc (g *Group) Get(path string, h Handler) ", "output": "{\n\tg.echo.Get(path, h)\n}"} {"input": "package ambition\n\nimport (\n\tcrand \"crypto/rand\"\n\t\"encoding/base64\"\n\t\"golang.org/x/crypto/bcrypt\"\n\t\"math/rand\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\n\n\nfunc CreateSaltAndHashedPassword(password []byte) ([]byte, []byte, error) {\n\tnano := time.Now().UnixNano()\n\trand.Seed(nano)\n\trandom := rand.Int31()\n\tsalt := strconv.Itoa(int(nano)) + strconv.Itoa(int(random))\n\n\thash, err := bcrypt.GenerateFromPassword([]byte(string(password)+salt), 10)\n\n\treturn []byte(salt), hash, err\n}\n\n\n\nfunc CompareSaltAndPasswordToHash(salt, hashedPassword, password []byte) bool {\n\tsaltedPassword := []byte(string(password) + string(salt))\n\n\terr := bcrypt.CompareHashAndPassword(hashedPassword, saltedPassword)\n\treturn err == nil\n}\n\n\n\n\n\nfunc GenerateRandomBytes(n int) ([]byte, error) {\n\tb := make([]byte, n)\n\t_, err := crand.Read(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}\n\n\n\n\n\n\n\n\nfunc HashToken(token string) string {\n\thash, _ := bcrypt.GenerateFromPassword([]byte(token), 10)\n\treturn string(hash)\n}\n\nfunc CompareHashAndToken(hash string, token string) bool {\n\n\terr := bcrypt.CompareHashAndPassword([]byte(hash), []byte(token))\n\treturn err == nil\n}\n\nfunc LoginUser(username string, password string) {}\n\nfunc GenerateRandomString(s int) (string, error) ", "output": "{\n\tb, err := GenerateRandomBytes(s)\n\treturn base64.URLEncoding.EncodeToString(b), err\n}"} {"input": "package classfile\n\nimport (\n\t\"github.com/zxh0/jvm.go/jvmgo/util/bigendian\"\n)\n\ntype ClassReader struct {\n\tdata []byte\n}\n\nfunc newClassReader(data []byte) *ClassReader {\n\treturn &ClassReader{data}\n}\n\nfunc (self *ClassReader) readUint8() uint8 {\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}\n\n\n\nfunc (self *ClassReader) readUint32() uint32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn uint32(val)\n}\nfunc (self *ClassReader) readInt32() int32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readInt64() int64 {\n\tval := bigendian.Int64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readFloat32() float32 {\n\tval := bigendian.Float32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readFloat64() float64 {\n\tval := bigendian.Float64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readBytes(length uint32) []byte {\n\tbytes := self.data[:length]\n\tself.data = self.data[length:]\n\treturn bytes\n}\n\n\nfunc (self *ClassReader) readString() string {\n\tlength := uint32(self.readUint16())\n\tbytes := self.readBytes(length)\n\treturn string(bytes)\n}\n\nfunc (self *ClassReader) readUint16() uint16 ", "output": "{\n\tval := bigendian.Uint16(self.data)\n\tself.data = self.data[2:]\n\treturn val\n}"} {"input": "package info\n\nimport (\n\t\"github.com/elastic/beats/libbeat/common\"\n\t\"github.com/elastic/beats/libbeat/logp\"\n\t\"github.com/elastic/beats/metricbeat/mb\"\n\t\"github.com/elastic/beats/metricbeat/module/docker\"\n\n\tdc \"github.com/fsouza/go-dockerclient\"\n)\n\nfunc init() {\n\tif err := mb.Registry.AddMetricSet(\"docker\", \"info\", New, docker.HostParser); err != nil {\n\t\tpanic(err)\n\t}\n}\n\ntype MetricSet struct {\n\tmb.BaseMetricSet\n\tdockerClient *dc.Client\n}\n\n\nfunc New(base mb.BaseMetricSet) (mb.MetricSet, error) {\n\tlogp.Warn(\"EXPERIMENTAL: The docker info metricset is experimental\")\n\n\tconfig := docker.Config{}\n\tif err := base.Module().UnpackConfig(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient, err := docker.NewDockerClient(base.HostData().URI, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &MetricSet{\n\t\tBaseMetricSet: base,\n\t\tdockerClient: client,\n\t}, nil\n}\n\n\n\n\n\nfunc (m *MetricSet) Fetch() (common.MapStr, error) ", "output": "{\n\tinfo, err := m.dockerClient.Info()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn eventMapping(info), nil\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\n\tv3 \"github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3\"\n\t\"github.com/rancher/rancher/pkg/ref\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc GetRuleID(groupID string, ruleName string) string {\n\treturn fmt.Sprintf(\"%s_%s\", groupID, ruleName)\n}\n\nfunc GetGroupID(namespace, name string) string {\n\treturn fmt.Sprintf(\"%s:%s\", namespace, name)\n}\n\nfunc GetAlertManagerSecretName(appName string) string {\n\treturn fmt.Sprintf(\"alertmanager-%s\", appName)\n}\n\nfunc GetAlertManagerDaemonsetName(appName string) string {\n\treturn fmt.Sprintf(\"alertmanager-%s\", appName)\n}\n\n\n\nfunc formatClusterDisplayName(clusterDisplayName, clusterID string) string {\n\treturn fmt.Sprintf(\"%s (ID: %s)\", clusterDisplayName, clusterID)\n}\n\nfunc GetClusterDisplayName(clusterName string, clusterLister v3.ClusterLister) string {\n\tcluster, err := clusterLister.Get(\"\", clusterName)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to get cluster for %s: %v\", clusterName, err)\n\t\treturn clusterName\n\t}\n\n\treturn formatClusterDisplayName(cluster.Spec.DisplayName, clusterName)\n}\n\nfunc GetProjectDisplayName(projectID string, projectLister v3.ProjectLister) string {\n\tclusterName, projectName := ref.Parse(projectID)\n\tproject, err := projectLister.Get(clusterName, projectName)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to get project %s: %v\", projectID, err)\n\t\treturn projectID\n\t}\n\n\treturn formatProjectDisplayName(project.Spec.DisplayName, projectID)\n}\n\nfunc formatProjectDisplayName(projectDisplayName, projectID string) string ", "output": "{\n\treturn fmt.Sprintf(\"%s (ID: %s)\", projectDisplayName, projectID)\n}"} {"input": "package data\n\nimport (\n \"github.com/twitchyliquid64/CNC/registry/syscomponents\"\n)\n\nvar trackerObj DatabaseComponent\n\ntype DatabaseComponent struct{\n err error\n}\n\nfunc (d *DatabaseComponent)Name() string{\n return \"Database\"\n}\nfunc (d *DatabaseComponent)IconStr() string{\n return \"list\"\n}\nfunc (d *DatabaseComponent)IsNominal()bool{\n return d.err == nil\n}\nfunc (d *DatabaseComponent)IsDisabled()bool{\n return false\n}\nfunc (d *DatabaseComponent)IsFault()bool{\n return d.err != nil\n}\n\nfunc (d *DatabaseComponent)SetError(e error){\n d.err = e\n}\n\nfunc trackingSetup(){\n trackerObj = DatabaseComponent{}\n syscomponents.Register(&trackerObj)\n}\n\nfunc tracking_notifyFault(err error){\n syscomponents.SetError(trackerObj.Name(), err)\n}\n\nfunc (d *DatabaseComponent)Error()string", "output": "{\n if d.err == nil{\n return \"\"\n }\n return d.err.Error()\n}"} {"input": "package hcn\n\nimport (\n\t\"testing\"\n)\n\nfunc TestMissingNetworkByName(t *testing.T) {\n\t_, err := GetNetworkByName(\"Not found name\")\n\tif err == nil {\n\t\tt.Fatal(\"Error was not thrown.\")\n\t}\n\tif !IsNotFoundError(err) {\n\t\tt.Fatal(\"Unrelated error was thrown.\")\n\t}\n\tif _, ok := err.(NetworkNotFoundError); !ok {\n\t\tt.Fatal(\"Wrong error type was thrown.\")\n\t}\n}\n\n\n\nfunc TestMissingNetworkById(t *testing.T) ", "output": "{\n\t_, err := GetNetworkByID(\"5f0b1190-63be-4e0c-b974-bd0f55675a42\")\n\tif err == nil {\n\t\tt.Fatal(\"Unrelated error was thrown.\")\n\t}\n\tif !IsNotFoundError(err) {\n\t\tt.Fatal(\"Unrelated error was thrown.\")\n\t}\n\tif _, ok := err.(NetworkNotFoundError); !ok {\n\t\tt.Fatal(\"Wrong error type was thrown.\")\n\t}\n}"} {"input": "package containerengine\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListWorkRequestLogsRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tWorkRequestId *string `mandatory:\"true\" contributesTo:\"path\" name:\"workRequestId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListWorkRequestLogsRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListWorkRequestLogsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request ListWorkRequestLogsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ListWorkRequestLogsRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListWorkRequestLogsResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []WorkRequestLogEntry `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response ListWorkRequestLogsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response ListWorkRequestLogsResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package utils\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/juju/errors\"\n)\n\n\nfunc GetRequestBody(r *http.Request) ([]byte, error) {\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treturn body, nil\n}\n\n\n\n\n\nfunc UnmarshalRequest(r *http.Request, v interface{}) error {\n\tbody, err := GetRequestBody(r)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tif err := json.Unmarshal(body, v); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\treturn nil\n}\n\nfunc Respond(w http.ResponseWriter, data interface{}, code int) error ", "output": "{\n\tw.WriteHeader(code)\n\n\tvar resp []byte\n\tvar err error\n\n\tresp, err = json.Marshal(data) \n\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfmt.Fprintln(w, string(resp))\n\n\treturn nil\n}"} {"input": "package datedsl\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestBeginningOfMinute(t *testing.T) {\n\tvalue := New(parse(\"Fri Jul 17 10:13:59 MST 2015\")).BeginningOfMinute()\n\texpected := parse(\"Fri Jul 17 10:13:00 MST 2015\")\n\tassert.Equal(t, expected.String(), value.String())\n}\n\nfunc TestBeginningOfHour(t *testing.T) {\n\tvalue := New(parse(\"Fri Jul 17 10:13:59 MST 2015\")).BeginningOfHour()\n\texpected := parse(\"Fri Jul 17 10:00:00 MST 2015\")\n\tassert.Equal(t, expected.String(), value.String())\n}\n\nfunc TestBeginningOfDay(t *testing.T) {\n\tvalue := New(parse(\"Fri Jul 17 10:13:59 MST 2015\")).BeginningOfDay()\n\texpected := parse(\"Fri Jul 17 00:00:00 MST 2015\")\n\tassert.Equal(t, expected.String(), value.String())\n}\n\nfunc TestFirstDayOfMonth(t *testing.T) {\n\tvalue := New(parse(\"Fri Jul 17 09:54:37 MST 2015\")).BeginningOfMonth()\n\texpected := parse(\"Wed Jul 1 00:00:00 MST 2015\")\n\tassert.Equal(t, expected.String(), value.String())\n}\n\nfunc TestFirstDayOfYear(t *testing.T) {\n\tvalue := New(parse(\"Fri Jul 17 09:54:37 MST 2015\")).BeginningOfYear()\n\texpected := parse(\"Thu Jan 1 00:00:00 MST 2015\")\n\tassert.Equal(t, expected.String(), value.String())\n}\n\nfunc parse(s string) time.Time {\n\tt, _ := time.Parse(time.UnixDate, s)\n\treturn t\n}\n\nfunc TestBeginningOfSecond(t *testing.T) ", "output": "{\n\tvalue := New(parse(\"Fri Jul 17 10:13:59 MST 2015\")).BeginningOfSecond()\n\texpected := parse(\"Fri Jul 17 10:13:59 MST 2015\")\n\tassert.Equal(t, expected.String(), value.String())\n\tassert.Equal(t, 0, value.Value().Nanosecond())\n}"} {"input": "package neo\n\nimport \"github.com/jmcvetta/neoism\"\n\nvar db *neoism.Database\n\n\n\nfunc DB() *neoism.Database {\n\treturn db\n}\n\nfunc init() ", "output": "{\n\tvar err error\n\tdb, err = neoism.Connect(\"http://localhost:7474/db/data\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package pool\n\nimport \"sync/atomic\"\n\n\ntype WorkUnit interface {\n\n\tWait()\n\n\tValue() interface{}\n\n\tError() error\n\n\tCancel()\n\n\tIsCancelled() bool\n}\n\nvar _ WorkUnit = new(workUnit)\n\n\ntype workUnit struct {\n\tvalue interface{}\n\terr error\n\tdone chan struct{}\n\tfn WorkFunc\n\tcancelled atomic.Value\n\tcancelling atomic.Value\n\twriting atomic.Value\n}\n\n\nfunc (wu *workUnit) Cancel() {\n\twu.cancelWithError(&ErrCancelled{s: errCancelled})\n}\n\n\n\n\nfunc (wu *workUnit) Wait() {\n\t<-wu.done\n}\n\n\nfunc (wu *workUnit) Value() interface{} {\n\treturn wu.value\n}\n\n\nfunc (wu *workUnit) Error() error {\n\treturn wu.err\n}\n\n\n\n\nfunc (wu *workUnit) IsCancelled() bool {\n\twu.writing.Store(struct{}{}) \n\treturn wu.cancelled.Load() != nil\n}\n\nfunc (wu *workUnit) cancelWithError(err error) ", "output": "{\n\n\twu.cancelling.Store(struct{}{})\n\n\tif wu.writing.Load() == nil && wu.cancelled.Load() == nil {\n\t\twu.cancelled.Store(struct{}{})\n\t\twu.err = err\n\t\tclose(wu.done)\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"github.com/goincremental/negroni-sessions\"\n\t\"net/http\"\n)\n\ntype SessionManager interface {\n\tGet(*http.Request, string) string\n\tSet(*http.Request, string, string)\n\tDelete(*http.Request, string)\n}\n\ntype SessionManagerImpl struct {\n}\n\nfunc NewSessionManager() *SessionManagerImpl {\n\treturn &SessionManagerImpl{}\n}\n\nfunc (sa *SessionManagerImpl) Get(req *http.Request, key string) string {\n\tif val := sessions.GetSession(req).Get(key); val != nil {\n\t\treturn val.(string)\n\t}\n\n\treturn \"\"\n}\n\nfunc (sa *SessionManagerImpl) Set(req *http.Request, key, value string) {\n\tsessions.GetSession(req).Set(key, value)\n}\n\n\n\nfunc (sa *SessionManagerImpl) Delete(req *http.Request, key string) ", "output": "{\n\tsessions.GetSession(req).Delete(key)\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n\t\"time\"\n\n\tgetter \"github.com/hashicorp/go-getter\"\n\t\"github.com/hashicorp/nomad/helper/discover\"\n)\n\n\n\n\nfunc procWaitTimeout(p *os.Process, d time.Duration) error {\n\tstop := make(chan struct{})\n\n\tgo func() {\n\t\tp.Wait()\n\t\tstop <- struct{}{}\n\t}()\n\n\tselect {\n\tcase <-stop:\n\t\treturn nil\n\tcase <-time.NewTimer(d).C:\n\t\treturn fmt.Errorf(\"timeout waiting for process %d to exit\", p.Pid)\n\t}\n}\n\nfunc fetchBinary(bin string) (string, error) ", "output": "{\n\tnomadBinaryDir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create temp dir: %v\", err)\n\t}\n\n\tif bin == \"\" {\n\t\tbin, err = discover.NomadExecutable()\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to discover nomad binary: %v\", err)\n\t\t}\n\t}\n\n\tdest := path.Join(nomadBinaryDir, \"nomad\")\n\tif runtime.GOOS == \"windows\" {\n\t\tdest = dest + \".exe\"\n\t}\n\n\tif err = getter.GetFile(dest, bin); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get nomad binary: %v\", err)\n\t}\n\n\treturn nomadBinaryDir, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc generate() chan int {\n\tch := make(chan int)\n\tgo func() {\n\t\tfor i := 2; ; i++ {\n\t\t\tch <- i\n\t\t}\n\t}()\n\treturn ch\n}\n\n\n\nfunc sieve() chan int {\n\tout := make(chan int)\n\tgo func() {\n\t\tch := generate()\n\t\tfor {\n\t\t\tprime := <-ch\n\t\t\tch = filter(ch, prime)\n\t\t\tout <- prime\n\t\t}\n\t}()\n\treturn out\n}\n\nfunc main() {\n\tprimes := sieve()\n\tfor {\n\t\tfmt.Println(<-primes)\n\t}\n}\n\nfunc filter(in chan int, prime int) chan int ", "output": "{\n\tout := make(chan int)\n\tgo func() {\n\t\tfor {\n\t\t\tif i := <-in; i%prime != 0 {\n\t\t\t\tout <- i\n\t\t\t}\n\t\t}\n\t}()\n\treturn out\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"log\"\n\n\t\"golang.org/x/oauth2/google\"\n\tcompute \"google.golang.org/api/compute/v1\"\n)\n\nconst (\n\tprojectID = \"some-project-id\"\n\tzone = \"some-zone\"\n\toperationID = \"some-operation-id\"\n)\n\n\n\nfunc operationProgressMain() ", "output": "{\n\tctx := context.Background()\n\n\tclient, err := google.DefaultClient(ctx, compute.CloudPlatformScope)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsvc, err := compute.New(client)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor {\n\t\tresp, err := svc.ZoneOperations.Get(projectID, zone, operationID).Do()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif resp.Status != \"WORKING\" && resp.Status != \"QUEUED\" {\n\t\t\tbreak\n\t\t}\n\t}\n\tlog.Println(\"operation complete\")\n}"} {"input": "package matchers_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/blevesearch/bleve\"\n\t\"github.com/blevesearch/bleve/search/query\"\n\t\"github.com/nrwiersma/isenzo/matchers\"\n)\n\nfunc TestParallelMatcher(t *testing.T) {\n\tf := matchers.NewParallelMatcherFactory(newWaitMatcherFactory(), 10)\n\tm, err := f.New(map[string]interface{}{})\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected err; got %v\", err)\n\t}\n\n\tfor i := 0; i < 10; i++ {\n\t\tm.Match(\"\", bleve.NewMatchAllQuery())\n\t}\n\n\tids, errs := m.Finish()\n\tif len(errs) != 0 {\n\t\tt.Fatalf(\"expected no errors; got %v\", errs)\n\t}\n\n\tif len(ids) != 10 {\n\t\tt.Fatalf(\"expected %d results; got %v\", 10, len(ids))\n\t}\n}\n\ntype waitMatcherFactory struct {}\n\nfunc newWaitMatcherFactory() matchers.Factory {\n\treturn &waitMatcherFactory{}\n}\n\nfunc (f waitMatcherFactory) New(doc interface{}) (matchers.Matcher, error) {\n\treturn &waitMatcher{\n\t\tids: make([]string, 0),\n\t}, nil\n}\n\n\n\ntype waitMatcher struct {\n\tids []string\n}\n\n\nfunc (m *waitMatcher) Match(id string, q query.Query) {\n\ttime.Sleep(10 * time.Millisecond)\n\n\tm.ids = append(m.ids, id)\n}\n\n\nfunc (m *waitMatcher) Finish() (ids []string, errs []error) {\n\treturn m.ids, []error{}\n}\n\nfunc (f waitMatcherFactory) Map(doc interface{}) (interface{}, error) ", "output": "{\n\treturn doc, nil\n}"} {"input": "package crypto\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestCrypto(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Crypto Suite\")\n}"} {"input": "package opts\n\n\ntype CreateOption func(*CreateConfig)\n\n\n\ntype CreateConfig struct {\n\tOptions map[string]string\n\tLabels map[string]string\n\tReference string\n}\n\n\n\nfunc WithCreateLabels(labels map[string]string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Labels = labels\n\t}\n}\n\n\n\nfunc WithCreateOptions(opts map[string]string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Options = opts\n\t}\n}\n\n\n\n\nfunc WithCreateReference(ref string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Reference = ref\n\t}\n}\n\n\n\ntype GetConfig struct {\n\tDriver string\n\tReference string\n\tResolveStatus bool\n}\n\n\ntype GetOption func(*GetConfig)\n\n\n\n\n\nfunc WithGetDriver(name string) GetOption {\n\treturn func(o *GetConfig) {\n\t\to.Driver = name\n\t}\n}\n\n\n\nfunc WithGetReference(ref string) GetOption {\n\treturn func(o *GetConfig) {\n\t\to.Reference = ref\n\t}\n}\n\n\n\n\n\n\ntype RemoveConfig struct {\n\tPurgeOnError bool\n}\n\n\ntype RemoveOption func(*RemoveConfig)\n\n\n\n\nfunc WithPurgeOnError(b bool) RemoveOption {\n\treturn func(o *RemoveConfig) {\n\t\to.PurgeOnError = b\n\t}\n}\n\nfunc WithGetResolveStatus(cfg *GetConfig) ", "output": "{\n\tcfg.ResolveStatus = true\n}"} {"input": "package servenv\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"vitess.io/vitess/go/event\"\n\t\"vitess.io/vitess/go/vt/log\"\n)\n\nvar (\n\tonCloseHooks event.Hooks\n\tExitChan chan os.Signal\n)\n\n\n\nfunc Run(port int) {\n\tpopulateListeningURL(int32(port))\n\tcreateGRPCServer()\n\tonRunHooks.Fire()\n\tserveGRPC()\n\tserveSocketFile()\n\n\tl, err := net.Listen(\"tcp\", fmt.Sprintf(\":%v\", port))\n\tif err != nil {\n\t\tlog.Exit(err)\n\t}\n\tgo http.Serve(l, nil)\n\n\tExitChan = make(chan os.Signal, 1)\n\tsignal.Notify(ExitChan, syscall.SIGTERM, syscall.SIGINT)\n\t<-ExitChan\n\tl.Close()\n\n\tstartTime := time.Now()\n\tlog.Infof(\"Entering lameduck mode for at least %v\", *lameduckPeriod)\n\tlog.Infof(\"Firing asynchronous OnTerm hooks\")\n\tgo onTermHooks.Fire()\n\n\tfireOnTermSyncHooks(*onTermTimeout)\n\tif remain := *lameduckPeriod - time.Since(startTime); remain > 0 {\n\t\tlog.Infof(\"Sleeping an extra %v after OnTermSync to finish lameduck period\", remain)\n\t\ttime.Sleep(remain)\n\t}\n\n\tlog.Info(\"Shutting down gracefully\")\n\tfireOnCloseHooks(*onCloseTimeout)\n}\n\n\nfunc Close() {\n\tonCloseHooks.Fire()\n\tListeningURL = url.URL{}\n}\n\n\n\n\n\n\nfunc OnClose(f func()) ", "output": "{\n\tonCloseHooks.Add(f)\n}"} {"input": "package grpclog \n\nimport \"os\"\n\nvar logger = newLoggerV2()\n\n\nfunc V(l int) bool {\n\treturn logger.V(l)\n}\n\n\nfunc Info(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\nfunc Infof(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\nfunc Infoln(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\n\nfunc Warning(args ...interface{}) {\n\tlogger.Warning(args...)\n}\n\n\nfunc Warningf(format string, args ...interface{}) {\n\tlogger.Warningf(format, args...)\n}\n\n\nfunc Warningln(args ...interface{}) {\n\tlogger.Warningln(args...)\n}\n\n\nfunc Error(args ...interface{}) {\n\tlogger.Error(args...)\n}\n\n\nfunc Errorf(format string, args ...interface{}) {\n\tlogger.Errorf(format, args...)\n}\n\n\nfunc Errorln(args ...interface{}) {\n\tlogger.Errorln(args...)\n}\n\n\n\nfunc Fatal(args ...interface{}) {\n\tlogger.Fatal(args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalf(format string, args ...interface{}) {\n\tlogger.Fatalf(format, args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalln(args ...interface{}) {\n\tlogger.Fatalln(args...)\n\tos.Exit(1)\n}\n\n\n\n\n\n\n\n\n\nfunc Printf(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\n\n\nfunc Println(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\nfunc Print(args ...interface{}) ", "output": "{\n\tlogger.Info(args...)\n}"} {"input": "package cabf_br\n\n\n\nimport (\n\t\"testing\"\n\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/test\"\n)\n\nfunc TestDNSNameEmptyLabel(t *testing.T) {\n\tinputPath := \"dnsNameEmptyLabel.pem\"\n\texpected := lint.Error\n\tout := test.TestLint(\"e_dnsname_empty_label\", inputPath)\n\tif out.Status != expected {\n\t\tt.Errorf(\"%s: expected %s, got %s\", inputPath, expected, out.Status)\n\t}\n}\n\n\n\nfunc TestDNSNameNotEmptyLabel(t *testing.T) ", "output": "{\n\tinputPath := \"dnsNameNotEmptyLabel.pem\"\n\texpected := lint.Pass\n\tout := test.TestLint(\"e_dnsname_empty_label\", inputPath)\n\tif out.Status != expected {\n\t\tt.Errorf(\"%s: expected %s, got %s\", inputPath, expected, out.Status)\n\t}\n}"} {"input": "package hijackhelpers\n\nimport (\n\t\"strings\"\n\n\t\"github.com/concourse/atc\"\n)\n\ntype ContainerSorter []atc.Container\n\nfunc (sorter ContainerSorter) Len() int {\n\treturn len(sorter)\n}\n\n\n\nfunc (sorter ContainerSorter) Less(i, j int) bool {\n\tswitch {\n\tcase sorter[i].BuildID < sorter[j].BuildID:\n\t\treturn true\n\tcase sorter[i].BuildID > sorter[j].BuildID:\n\t\treturn false\n\tcase strings.Compare(sorter[i].ResourceName, sorter[j].ResourceName) == -1:\n\t\treturn true\n\tcase strings.Compare(sorter[i].ResourceName, sorter[j].ResourceName) == 1:\n\t\treturn false\n\tcase strings.Compare(sorter[i].StepName, sorter[j].StepName) == -1:\n\t\treturn true\n\tcase strings.Compare(sorter[i].StepName, sorter[j].StepName) == 1:\n\t\treturn false\n\tcase strings.Compare(sorter[i].Type, sorter[j].Type) == -1:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc (sorter ContainerSorter) Swap(i, j int) ", "output": "{\n\tsorter[i], sorter[j] = sorter[j], sorter[i]\n}"} {"input": "package util\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/sodafoundation/api/client\"\n\t\"github.com/sodafoundation/api/pkg/model\"\n)\n\n\n\n\n\nfunc GetHostByHostId(client *client.Client, hostId string) (*model.HostSpec, error) {\n\thostLists, err := client.HostMgr.ListHosts()\n\tif nil != err {\n\t\treturn nil, errors.New(\"Failed to list hosts\")\n\t}\n\n\tfor _, elem := range hostLists {\n\t\tif elem.Id == hostId {\n\t\t\treturn elem, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"Failed to find host for hostId %s\", hostId)\n}\n\nfunc GetHostByHostName(client *client.Client, hostName string) (*model.HostSpec, error) ", "output": "{\n\thostLists, err := client.HostMgr.ListHosts()\n\tif nil != err {\n\t\treturn nil, errors.New(\"Failed to list hosts\")\n\t}\n\n\tfor _, elem := range hostLists {\n\t\tif elem.HostName == hostName {\n\t\t\treturn elem, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"Failed to find host for hostname %s\", hostName)\n}"} {"input": "package gomplate\n\nimport \"time\"\n\n\n\nvar Metrics *MetricsType\n\n\n\ntype MetricsType struct {\n\tRenderDuration map[string]time.Duration\n\tGatherDuration time.Duration\n\tTotalRenderDuration time.Duration\n\n\tTemplatesGathered int\n\tTemplatesProcessed int\n\tErrors int\n}\n\n\n\nfunc newMetrics() *MetricsType ", "output": "{\n\treturn &MetricsType{\n\t\tRenderDuration: make(map[string]time.Duration),\n\t}\n}"} {"input": "package accumulator\n\nimport \"strconv\"\n\ntype Int64 int64\n\n\nfunc (a *Int64) Accumulate(i int, err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t*a += Int64(i)\n}\n\n\n\n\nfunc (a *Int64) String() string {\n\treturn strconv.FormatInt(int64(*a), 10)\n}\n\nfunc (a *Int64) Accumulate64(i int64, err error) ", "output": "{\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t*a += Int64(i)\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc foo(x int) bool {\n\treturn x == x \n}\n\nfunc isNaN(x float32) bool {\n\treturn x != x \n}\n\nfunc main() {\n\tfoo(42)\n}\n\nconst mode = \"Debug\"\n\n\n\nfunc bar() {\n\tif ptrsize == 8 { \n\t\tfmt.Println()\n\t}\n}\n\nfunc bump(x *int) {\n\t*x++\n}\n\nfunc baz() bool {\n\tvar x = 0\n\tbump(&x)\n\treturn x == 0\n}\n\ntype counter int\n\nfunc (x *counter) bump() {\n\t*x++\n}\n\nfunc (x counter) bimp() {\n\tx++\n}\n\nfunc baz2() bool {\n\tvar x counter\n\tx.bump()\n\treturn x == 0 \n}\n\nfunc baz3() bool {\n\tvar y counter\n\ty.bimp()\n\treturn y == 0 \n}\n\nfunc log(msg string) ", "output": "{\n\tif mode == \"Debug\" {\n\t\tfmt.Println(msg)\n\t}\n}"} {"input": "package version\n\n\n\n\n\n\nfunc init() ", "output": "{\n\tVersion = \"0.8.1\"\n\n\tVersionPrerelease = \"dev\"\n}"} {"input": "package iso20022\n\n\ntype SubAccountIdentification11 struct {\n\n\tAccountOwner *PartyIdentification13Choice `xml:\"AcctOwnr,omitempty\"`\n\n\tSafekeepingAccount *SecuritiesAccount14 `xml:\"SfkpgAcct\"`\n\n\tActivityIndicator *YesNoIndicator `xml:\"ActvtyInd\"`\n\n\tBalanceForSubAccount []*AggregateBalanceInformation9 `xml:\"BalForSubAcct,omitempty\"`\n}\n\nfunc (s *SubAccountIdentification11) AddAccountOwner() *PartyIdentification13Choice {\n\ts.AccountOwner = new(PartyIdentification13Choice)\n\treturn s.AccountOwner\n}\n\nfunc (s *SubAccountIdentification11) AddSafekeepingAccount() *SecuritiesAccount14 {\n\ts.SafekeepingAccount = new(SecuritiesAccount14)\n\treturn s.SafekeepingAccount\n}\n\n\n\nfunc (s *SubAccountIdentification11) AddBalanceForSubAccount() *AggregateBalanceInformation9 {\n\tnewValue := new(AggregateBalanceInformation9)\n\ts.BalanceForSubAccount = append(s.BalanceForSubAccount, newValue)\n\treturn newValue\n}\n\nfunc (s *SubAccountIdentification11) SetActivityIndicator(value string) ", "output": "{\n\ts.ActivityIndicator = (*YesNoIndicator)(&value)\n}"} {"input": "package apmsynthetics\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetMonitorRequest struct {\n\n\tApmDomainId *string `mandatory:\"true\" contributesTo:\"query\" name:\"apmDomainId\"`\n\n\tMonitorId *string `mandatory:\"true\" contributesTo:\"path\" name:\"monitorId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request GetMonitorRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request GetMonitorRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetMonitorRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetMonitorResponse struct {\n\n\tRawResponse *http.Response\n\n\tMonitor `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetMonitorResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetMonitorResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetMonitorRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package api2go\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\ntype APIContextAllocatorFunc func(*API) APIContexter\n\n\ntype APIContexter interface {\n\tcontext.Context\n\tSet(key string, value interface{})\n\tGet(key string) (interface{}, bool)\n\tReset()\n}\n\n\ntype APIContext struct {\n\tkeys map[string]interface{}\n}\n\n\nfunc (c *APIContext) Set(key string, value interface{}) {\n\tif c.keys == nil {\n\t\tc.keys = make(map[string]interface{})\n\t}\n\tc.keys[key] = value\n}\n\n\nfunc (c *APIContext) Get(key string) (value interface{}, exists bool) {\n\tif c.keys != nil {\n\t\tvalue, exists = c.keys[key]\n\t}\n\treturn\n}\n\n\n\n\n\nfunc (c *APIContext) Deadline() (deadline time.Time, ok bool) {\n\treturn\n}\n\n\nfunc (c *APIContext) Done() <-chan struct{} {\n\treturn nil\n}\n\n\nfunc (c *APIContext) Err() error {\n\treturn nil\n}\n\n\nfunc (c *APIContext) Value(key interface{}) interface{} {\n\tif keyAsString, ok := key.(string); ok {\n\t\tval, _ := c.Get(keyAsString)\n\t\treturn val\n\t}\n\treturn nil\n}\n\n\nvar _ APIContexter = &APIContext{}\n\n\nfunc ContextQueryParams(c *APIContext) map[string][]string {\n\tqp, ok := c.Get(\"QueryParams\")\n\tif ok == false {\n\t\tqp = make(map[string][]string)\n\t\tc.Set(\"QueryParams\", qp)\n\t}\n\treturn qp.(map[string][]string)\n}\n\nfunc (c *APIContext) Reset() ", "output": "{\n\tc.keys = nil\n}"} {"input": "package client\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest/adal\"\n\t\"github.com/Azure/go-autorest/autorest/azure\"\n)\n\n\ntype msiOAuthTokenProvider struct {\n\tenv azure.Environment\n}\n\nfunc NewMSIOAuthTokenProvider(env azure.Environment) oAuthTokenProvider {\n\treturn &msiOAuthTokenProvider{env}\n}\n\nfunc (tp *msiOAuthTokenProvider) getServicePrincipalToken() (*adal.ServicePrincipalToken, error) {\n\treturn tp.getServicePrincipalTokenWithResource(tp.env.ResourceManagerEndpoint)\n}\n\n\n\nfunc (tp *msiOAuthTokenProvider) getServicePrincipalTokenWithResource(resource string) (*adal.ServicePrincipalToken, error) ", "output": "{\n\treturn adal.NewServicePrincipalTokenFromMSI(\"http://169.254.169.254/metadata/identity/oauth2/token\", resource)\n}"} {"input": "package dnsrecorder\n\nimport (\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n)\n\n\n\n\n\n\n\ntype Recorder struct {\n\tdns.ResponseWriter\n\tRcode int\n\tLen int\n\tMsg *dns.Msg\n\tStart time.Time\n}\n\n\n\n\n\n\n\n\nfunc (r *Recorder) WriteMsg(res *dns.Msg) error {\n\tr.Rcode = res.Rcode\n\tr.Len += res.Len()\n\tr.Msg = res\n\treturn r.ResponseWriter.WriteMsg(res)\n}\n\n\nfunc (r *Recorder) Write(buf []byte) (int, error) {\n\tn, err := r.ResponseWriter.Write(buf)\n\tif err == nil {\n\t\tr.Len += n\n\t}\n\treturn n, err\n}\n\n\n\nfunc (r *Recorder) Hijack() { r.ResponseWriter.Hijack(); return }\n\nfunc New(w dns.ResponseWriter) *Recorder ", "output": "{\n\treturn &Recorder{\n\t\tResponseWriter: w,\n\t\tRcode: 0,\n\t\tMsg: nil,\n\t\tStart: time.Now(),\n\t}\n}"} {"input": "package entities\n\nconst (\n\tActionMove = iota + 1\n\n\tActionAttack\n\n\tActionCastSpell\n\n\tActionGather\n\n\tActionLoot\n\n\tActionConsume\n)\n\n\n\n\n\n\n\n\n\n\n\ntype Action interface {\n\tSetTarget(Entity)\n\tSetSelf(Entity)\n\n\tGetTypeAction() uint8\n\tGetSelf() Entity\n\tGetTarget() Entity\n\n\tPlay() error\n}\n\n\ntype SimpleAction struct {\n\tself Entity\n\ttarget Entity\n\ttypeAction uint8\n}\n\n\nfunc (action *SimpleAction) GetTypeAction() uint8 {\n\treturn action.GetTypeAction()\n}\n\n\nfunc (action *SimpleAction) SetTarget(target Entity) {\n\taction.target = target\n}\n\n\nfunc (action *SimpleAction) GetTarget() Entity {\n\treturn action.target\n}\n\n\n\n\n\nfunc (action *SimpleAction) GetSelf() Entity {\n\treturn action.self\n}\n\n\nfunc (action *SimpleAction) Play() error {\n\treturn nil\n}\n\nfunc (action *SimpleAction) SetSelf(self Entity) ", "output": "{\n\taction.self = self\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype OpenpitrixListReleaseResponse struct {\n\n\tReleaseSet OpenpitrixListReleaseResponseReleaseSet `json:\"release_set\"`\n}\n\n\nfunc (m *OpenpitrixListReleaseResponse) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (m *OpenpitrixListReleaseResponse) UnmarshalBinary(b []byte) error {\n\tvar res OpenpitrixListReleaseResponse\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *OpenpitrixListReleaseResponse) MarshalBinary() ([]byte, error) ", "output": "{\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}"} {"input": "package exporters\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"k8s.io/node-problem-detector/pkg/types\"\n)\n\nfunc TestRegistration(t *testing.T) {\n\tfooExporterFactory := func(types.CommandLineOptions) types.Exporter {\n\t\treturn nil\n\t}\n\tfooExporterHandler := types.ExporterHandler{\n\t\tCreateExporterOrDie: fooExporterFactory,\n\t\tOptions: nil,\n\t}\n\n\tbarExporterFactory := func(types.CommandLineOptions) types.Exporter {\n\t\treturn nil\n\t}\n\tbarExporterHandler := types.ExporterHandler{\n\t\tCreateExporterOrDie: barExporterFactory,\n\t\tOptions: nil,\n\t}\n\n\tRegister(\"foo\", fooExporterHandler)\n\tRegister(\"bar\", barExporterHandler)\n\n\texpectedExporterNames := []types.ExporterType{\"foo\", \"bar\"}\n\texporterNames := GetExporterNames()\n\tassert.ElementsMatch(t, expectedExporterNames, exporterNames)\n\n\thandlers = make(map[types.ExporterType]types.ExporterHandler)\n}\n\n\n\nfunc TestGetExporterHandlerOrDie(t *testing.T) ", "output": "{\n\tfooExporterFactory := func(types.CommandLineOptions) types.Exporter {\n\t\treturn nil\n\t}\n\tfooExporterHandler := types.ExporterHandler{\n\t\tCreateExporterOrDie: fooExporterFactory,\n\t\tOptions: nil,\n\t}\n\n\tRegister(\"foo\", fooExporterHandler)\n\n\tassert.NotPanics(t, func() { GetExporterHandlerOrDie(\"foo\") })\n\tassert.Panics(t, func() { GetExporterHandlerOrDie(\"bar\") })\n\n\thandlers = make(map[types.ExporterType]types.ExporterHandler)\n}"} {"input": "package v1alpha1\n\nimport (\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\tcorev1 \"k8s.io/api/core/v1\"\n)\n\n\n\nfunc TestBuildTemplateGroupVersionKind(t *testing.T) {\n\tc := BuildTemplate{}\n\n\texpectedKind := \"BuildTemplate\"\n\tif c.GetGroupVersionKind().Kind != expectedKind {\n\t\tt.Errorf(\"GetGroupVersionKind mismatch; expected: %v got: %v\", expectedKind, c.GetGroupVersionKind().Kind)\n\t}\n}\n\nfunc TestBuildTemplateSpec(t *testing.T) ", "output": "{\n\tc := BuildTemplate{\n\t\tSpec: BuildTemplateSpec{\n\t\t\tSteps: []corev1.Container{{\n\t\t\t\tName: \"build-spec\",\n\t\t\t}},\n\t\t},\n\t}\n\n\texpectedBuildSpec := BuildTemplateSpec{Steps: []corev1.Container{{Name: \"build-spec\"}}}\n\n\tif a := cmp.Diff(c.TemplateSpec(), expectedBuildSpec); a != \"\" {\n\t\tt.Errorf(\"templateSpec mismatch; expected: %v got: %v\", expectedBuildSpec, a)\n\t}\n}"} {"input": "package cgzip\n\n\nimport \"C\"\n\nimport (\n\t\"hash\"\n\t\"unsafe\"\n)\n\ntype adler32Hash struct {\n\tadler C.uLong\n}\n\n\n\nfunc NewAdler32() hash.Hash32 {\n\ta := &adler32Hash{}\n\ta.Reset()\n\treturn a\n}\n\n\nfunc (a *adler32Hash) Write(p []byte) (n int, err error) {\n\tif len(p) > 0 {\n\t\ta.adler = C.adler32(a.adler, (*C.Bytef)(unsafe.Pointer(&p[0])), (C.uInt)(len(p)))\n\t}\n\treturn len(p), nil\n}\n\n\nfunc (a *adler32Hash) Sum(b []byte) []byte {\n\ts := a.Sum32()\n\tb = append(b, byte(s>>24))\n\tb = append(b, byte(s>>16))\n\tb = append(b, byte(s>>8))\n\tb = append(b, byte(s))\n\treturn b\n}\n\nfunc (a *adler32Hash) Reset() {\n\ta.adler = C.adler32(0, (*C.Bytef)(unsafe.Pointer(nil)), 0)\n}\n\nfunc (a *adler32Hash) Size() int {\n\treturn 4\n}\n\nfunc (a *adler32Hash) BlockSize() int {\n\treturn 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc Adler32Combine(adler1, adler2 uint32, len2 int) uint32 {\n\treturn uint32(C.adler32_combine(C.uLong(adler1), C.uLong(adler2), C.z_off_t(len2)))\n}\n\nfunc (a *adler32Hash) Sum32() uint32 ", "output": "{\n\treturn uint32(a.adler)\n}"} {"input": "package smtp\n\nimport (\n\t\"errors\"\n\t\"testing\"\n)\n\ntype EmailRecorder struct {\n\tfrom string\n\tto []string\n\tmsg []byte\n}\n\ntype SMTPMock struct {\n\tr *EmailRecorder\n\terr error\n}\n\nfunc (s *SMTPMock) SendMail(from string, to []string, msg []byte) error {\n\ts.r = &EmailRecorder{from, to, msg}\n\treturn s.err\n}\n\nfunc TestMailService(t *testing.T) {\n\tmailService := MailService{}\n\n\tvar i interface{} = &mailService\n\t_, ok := i.(IMailService)\n\n\tif !ok {\n\t\tt.Fatalf(\"MailService must implement IMailService\")\n\t}\n}\n\n\n\nfunc TestSendError(t *testing.T) {\n\terr := errors.New(\"Error\")\n\ts := SMTPMock{err: err}\n\tmailService := NewMailService(&s)\n\n\terr = mailService.Send(\"message\", \"test\", \"john@doe.com\", \"jane@doe.com\")\n\tif err == nil {\n\t\tt.Fatalf(\"Must return an error\")\n\t}\n}\n\nfunc TestSendNormal(t *testing.T) ", "output": "{\n\tbody := \"From: john@doe.com\\r\\n\" +\n\t\t\"To: jane@doe.com\\r\\n\" +\n\t\t\"Subject: test\\r\\n\" +\n\t\t\"\\r\\n\" +\n\t\t\"message\\r\\n\"\n\ts := SMTPMock{err: nil}\n\tmailService := NewMailService(&s)\n\n\terr := mailService.Send(\"message\", \"test\", \"john@doe.com\", \"jane@doe.com\")\n\tif err != nil {\n\t\tt.Fatalf(\"Mustn't return an error\")\n\t}\n\tif string(s.r.msg) != body {\n\t\tt.Errorf(\"wrong message body.\\n\\nexpected: %s\\n got: %s\", body, s.r.msg)\n\t}\n}"} {"input": "package backingstore\n\nimport (\n\t\"github.com/gostor/gotgt/pkg/api\"\n\t\"github.com/gostor/gotgt/pkg/scsi\"\n)\n\nfunc init() {\n\tscsi.RegisterBackingStore(\"null\", newNull)\n}\n\ntype NullBackingStore struct {\n\tscsi.BaseBackingStore\n}\n\nfunc newNull() (api.BackingStore, error) {\n\treturn &NullBackingStore{\n\t\tBaseBackingStore: scsi.BaseBackingStore{\n\t\t\tName: \"null\",\n\t\t\tDataSize: 0,\n\t\t\tOflagsSupported: 0,\n\t\t},\n\t}, nil\n}\n\nfunc (bs *NullBackingStore) Open(dev *api.SCSILu, path string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Close(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Init(dev *api.SCSILu, Opts string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Exit(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Size(dev *api.SCSILu) uint64 {\n\treturn 0\n}\n\nfunc (bs *NullBackingStore) Read(offset, tl int64) ([]byte, error) {\n\treturn nil, nil\n}\n\nfunc (bs *NullBackingStore) Write(wbuf []byte, offset int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataSync(offset, tl int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataAdvise(offset, length int64, advise uint32) error {\n\treturn nil\n}\n\n\n\nfunc (bs *NullBackingStore) Unmap([]api.UnmapBlockDescriptor) error ", "output": "{\n\treturn nil\n}"} {"input": "package network\n\nimport (\n\t\"context\"\n\t\"sort\"\n\n\t\"github.com/docker/cli/cli\"\n\t\"github.com/docker/cli/cli/command\"\n\t\"github.com/docker/cli/cli/command/formatter\"\n\t\"github.com/docker/cli/opts\"\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/fvbommel/sortorder\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype listOptions struct {\n\tquiet bool\n\tnoTrunc bool\n\tformat string\n\tfilter opts.FilterOpt\n}\n\n\n\nfunc runList(dockerCli command.Cli, options listOptions) error {\n\tclient := dockerCli.Client()\n\tlistOptions := types.NetworkListOptions{Filters: options.filter.Value()}\n\tnetworkResources, err := client.NetworkList(context.Background(), listOptions)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tformat := options.format\n\tif len(format) == 0 {\n\t\tif len(dockerCli.ConfigFile().NetworksFormat) > 0 && !options.quiet {\n\t\t\tformat = dockerCli.ConfigFile().NetworksFormat\n\t\t} else {\n\t\t\tformat = formatter.TableFormatKey\n\t\t}\n\t}\n\n\tsort.Slice(networkResources, func(i, j int) bool {\n\t\treturn sortorder.NaturalLess(networkResources[i].Name, networkResources[j].Name)\n\t})\n\n\tnetworksCtx := formatter.Context{\n\t\tOutput: dockerCli.Out(),\n\t\tFormat: NewFormat(format, options.quiet),\n\t\tTrunc: !options.noTrunc,\n\t}\n\treturn FormatWrite(networksCtx, networkResources)\n}\n\nfunc newListCommand(dockerCli command.Cli) *cobra.Command ", "output": "{\n\toptions := listOptions{filter: opts.NewFilterOpt()}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"ls [OPTIONS]\",\n\t\tAliases: []string{\"list\"},\n\t\tShort: \"List networks\",\n\t\tArgs: cli.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn runList(dockerCli, options)\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\tflags.BoolVarP(&options.quiet, \"quiet\", \"q\", false, \"Only display network IDs\")\n\tflags.BoolVar(&options.noTrunc, \"no-trunc\", false, \"Do not truncate the output\")\n\tflags.StringVar(&options.format, \"format\", \"\", \"Pretty-print networks using a Go template\")\n\tflags.VarP(&options.filter, \"filter\", \"f\", \"Provide filter values (e.g. 'driver=bridge')\")\n\n\treturn cmd\n}"} {"input": "package common\n\nimport (\n\t\"encoding/binary\"\n\t\"sort\"\n)\n\n\n\ntype Uint64Slice []uint64\n\nfunc (p Uint64Slice) Len() int { return len(p) }\nfunc (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] }\nfunc (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p Uint64Slice) Sort() { sort.Sort(p) }\n\nfunc SearchUint64s(a []uint64, x uint64) int {\n\treturn sort.Search(len(a), func(i int) bool { return a[i] >= x })\n}\n\nfunc (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) }\n\n\n\nfunc PutUint64LE(dest []byte, i uint64) {\n\tbinary.LittleEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64LE(src []byte) uint64 {\n\treturn binary.LittleEndian.Uint64(src)\n}\n\nfunc PutUint64BE(dest []byte, i uint64) {\n\tbinary.BigEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64BE(src []byte) uint64 {\n\treturn binary.BigEndian.Uint64(src)\n}\n\nfunc PutInt64LE(dest []byte, i int64) {\n\tbinary.LittleEndian.PutUint64(dest, uint64(i))\n}\n\n\n\nfunc PutInt64BE(dest []byte, i int64) {\n\tbinary.BigEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64BE(src []byte) int64 {\n\treturn int64(binary.BigEndian.Uint64(src))\n}\n\nfunc GetInt64LE(src []byte) int64 ", "output": "{\n\treturn int64(binary.LittleEndian.Uint64(src))\n}"} {"input": "package base\n\nimport (\n\t\"github.com/johnwilson/bytengine\"\n)\n\n\nfunc ServerListDb(cmd bytengine.Command, user *bytengine.User, eng *bytengine.Engine) (interface{}, error) {\n\tfilter := \".\"\n\tval, ok := cmd.Options[\"regex\"]\n\tif ok {\n\t\tfilter = val.(string)\n\t}\n\treturn eng.FileSystem.ListDatabase(filter)\n}\n\n\nfunc ServerNewDb(cmd bytengine.Command, user *bytengine.User, eng *bytengine.Engine) (interface{}, error) {\n\tdb := cmd.Args[\"database\"].(string)\n\tif err := eng.FileSystem.CreateDatabase(db); err != nil {\n\t\treturn nil, err\n\t}\n\treturn true, nil\n}\n\n\nfunc ServerInit(cmd bytengine.Command, user *bytengine.User, eng *bytengine.Engine) (interface{}, error) {\n\treturn eng.FileSystem.ClearAll()\n}\n\n\n\n\nfunc init() {\n\tbytengine.RegisterCommandHandler(\"server.listdb\", ServerListDb)\n\tbytengine.RegisterCommandHandler(\"server.newdb\", ServerNewDb)\n\tbytengine.RegisterCommandHandler(\"server.init\", ServerInit)\n\tbytengine.RegisterCommandHandler(\"server.dropdb\", ServerDropDb)\n}\n\nfunc ServerDropDb(cmd bytengine.Command, user *bytengine.User, eng *bytengine.Engine) (interface{}, error) ", "output": "{\n\tdb := cmd.Args[\"database\"].(string)\n\tif err := eng.FileSystem.DropDatabase(db); err != nil {\n\t\treturn nil, err\n\t}\n\treturn true, nil\n}"} {"input": "package config\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/dnephin/configtf\"\n\tpth \"github.com/dnephin/configtf/path\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype ComposeConfig struct {\n\tFiles []string\n\tProject string `config:\"required\"`\n\tStopGrace int\n\tDependent\n\tAnnotations\n}\n\n\nfunc (c *ComposeConfig) StopGraceString() string {\n\treturn strconv.Itoa(c.StopGrace)\n}\n\n\nfunc (c *ComposeConfig) Validate(path pth.Path, config *Config) *pth.Error {\n\treturn nil\n}\n\nfunc (c *ComposeConfig) String() string {\n\treturn fmt.Sprintf(\"Run Compose project %q from: %v\",\n\t\tc.Project, strings.Join(c.Files, \", \"))\n}\n\n\nfunc (c *ComposeConfig) Resolve(resolver Resolver) (Resource, error) {\n\tconf := *c\n\tvar err error\n\tconf.Files, err = resolver.ResolveSlice(c.Files)\n\tif err != nil {\n\t\treturn &conf, err\n\t}\n\tconf.Project, err = resolver.Resolve(c.Project)\n\treturn &conf, err\n}\n\nfunc composeFromConfig(name string, values map[string]interface{}) (Resource, error) {\n\tcompose := &ComposeConfig{Project: \"{unique}\", StopGrace: 5}\n\treturn compose, configtf.Transform(name, values, compose)\n}\n\n\n\nfunc init() ", "output": "{\n\tRegisterResource(\"compose\", composeFromConfig)\n}"} {"input": "package networkloadbalancer\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ChangeNetworkLoadBalancerCompartmentRequest struct {\n\n\tNetworkLoadBalancerId *string `mandatory:\"true\" contributesTo:\"path\" name:\"networkLoadBalancerId\"`\n\n\tChangeNetworkLoadBalancerCompartmentDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ChangeNetworkLoadBalancerCompartmentResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ChangeNetworkLoadBalancerCompartmentResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response ChangeNetworkLoadBalancerCompartmentResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package awsping\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n)\n\n\ntype RequestType int\n\nconst (\n\tRequestTypeHTTP RequestType = iota\n\tRequestTypeTCP\n)\n\n\ntype Requester interface {\n\tDo(ua, url string, reqType RequestType) (time.Duration, error)\n}\n\n\ntype AWSHTTPRequester interface {\n\tDo(req *http.Request) (*http.Response, error)\n}\n\n\ntype AWSTCPRequester interface {\n\tDial(network, address string) (net.Conn, error)\n}\n\n\ntype AWSRequest struct {\n\thttpClient AWSHTTPRequester\n\ttcpClient AWSTCPRequester\n}\n\n\n\n\n\nfunc (r *AWSRequest) DoHTTP(ua, url string) (time.Duration, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treq.Header.Set(\"User-Agent\", ua)\n\n\tstart := time.Now()\n\tresp, err := r.httpClient.Do(req)\n\tlatency := time.Since(start)\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn latency, nil\n}\n\n\nfunc (r *AWSRequest) DoTCP(_, addr string) (time.Duration, error) {\n\tstart := time.Now()\n\tconn, err := r.tcpClient.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tl := time.Since(start)\n\tdefer conn.Close()\n\n\treturn l, nil\n}\n\n\nfunc (r *AWSRequest) Do(ua, url string, reqType RequestType) (time.Duration, error) {\n\tif reqType == RequestTypeHTTP {\n\t\treturn r.DoHTTP(ua, url)\n\t}\n\treturn r.DoTCP(ua, url)\n}\n\nfunc NewAWSRequest() *AWSRequest ", "output": "{\n\treturn &AWSRequest{\n\t\thttpClient: &http.Client{},\n\t\ttcpClient: &net.Dialer{},\n\t}\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSGlueCrawler_Schedule struct {\n\n\tScheduleExpression string `json:\"ScheduleExpression,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSGlueCrawler_Schedule) AWSCloudFormationType() string {\n\treturn \"AWS::Glue::Crawler.Schedule\"\n}\n\n\n\n\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSGlueCrawler_Schedule) DependsOn() []string ", "output": "{\n\treturn r._dependsOn\n}"} {"input": "package githttp\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\n\ntype HandlerReq struct {\n\tw http.ResponseWriter\n\tr *http.Request\n\tRPC string\n\tDir string\n\tFile string\n}\n\n\n\nfunc (hr HandlerReq) String() string ", "output": "{\n\treturn fmt.Sprintf(\"RPC = %s, Dir = %s, File = %s\", hr.RPC, hr.Dir, hr.File)\n}"} {"input": "package api\n\ntype Memstore map[string]*Collection\n\nfunc (m Memstore) Init(dbName string) error {\n\treturn nil\n}\n\nfunc (m Memstore) CreateCollection(slug, name string) (Collection, error) {\n\tm[slug] = &Collection{Name: name,\n\t\tSlug: slug,\n\t\tItems: map[string]Item{},\n\t}\n\treturn *m[slug], nil\n}\n\nfunc (m Memstore) UpdateCollection(slug, name string) error {\n\tif c, ok := m[slug]; !ok {\n\t\treturn CollectionNotFoundError\n\t} else {\n\t\tc.Name = name\n\t}\n\treturn nil\n}\n\nfunc (m Memstore) GetCollectionData(slug string) (Collection, error) {\n\tif c, ok := m[slug]; ok {\n\t\t(*c).Items = nil\n\t\treturn *c, nil\n\t}\n\treturn Collection{}, CollectionNotFoundError\n}\n\nfunc (m Memstore) GetCollectionItems(slug string) (map[string]Item, error) {\n\tif c, ok := m[slug]; ok {\n\t\treturn c.Items, nil\n\t}\n\treturn map[string]Item{}, CollectionNotFoundError\n}\n\nfunc (m Memstore) AddItemToCollection(slug string, item Item) error {\n\tif c, ok := m[slug]; ok {\n\t\tc.Items[item.Tag] = item\n\t\treturn nil\n\t}\n\treturn CollectionNotFoundError\n}\n\n\n\nfunc (m Memstore) GetItemFromCollection(slug, tag string) (Item, error) ", "output": "{\n\tif _, ok := m[slug]; !ok {\n\t\treturn Item{}, CollectionNotFoundError\n\t}\n\tif _, ok := m[slug].Items[tag]; !ok {\n\t\treturn Item{}, BlobNotFoundError\n\t}\n\treturn m[slug].Items[tag], nil\n}"} {"input": "package timeutil\n\nimport (\n\t\"time\"\n\t\"unsafe\"\n\n\t\"github.com/leekchan/timeutil\"\n\t\"github.com/pkg/errors\"\n)\n\n\n\n\n\n\n\nimport \"C\"\n\n\nfunc Strftime(t time.Time, layout string) (string, error) {\n\treturn timeutil.Strftime(&t, layout), nil\n}\n\n\n\n\nfunc Strptime(layout, value string) (time.Time, error) ", "output": "{\n\tcLayout := C.CString(layout)\n\tdefer C.free(unsafe.Pointer(cLayout))\n\tcValue := C.CString(value)\n\tdefer C.free(unsafe.Pointer(cValue))\n\n\tvar cTime C.struct_tm\n\tif _, err := C.strptime(cValue, cLayout, &cTime); err != nil {\n\t\treturn time.Time{}, errors.Wrapf(err, \"could not parse %s as %s\", value, layout)\n\t}\n\treturn time.Date(\n\t\tint(cTime.tm_year)+1900,\n\t\ttime.Month(cTime.tm_mon+1),\n\t\tint(cTime.tm_mday),\n\t\tint(cTime.tm_hour),\n\t\tint(cTime.tm_min),\n\t\tint(cTime.tm_sec),\n\t\t0,\n\t\ttime.FixedZone(\"\", int(cTime.tm_gmtoff)),\n\t), nil\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aws/aws-sdk-go/private/protocol\"\n)\n\ntype examplesBuilder interface {\n\tBuildShape(*ShapeRef, map[string]interface{}, bool) string\n\tBuildList(string, string, *ShapeRef, []interface{}) string\n\tBuildComplex(string, string, *ShapeRef, *Shape, map[string]interface{}) string\n\tGoType(*ShapeRef, bool) string\n\tImports(*API) string\n}\n\ntype defaultExamplesBuilder struct {\n\tShapeValueBuilder\n}\n\n\n\nfunc NewExamplesBuilder() defaultExamplesBuilder {\n\tb := defaultExamplesBuilder{\n\t\tShapeValueBuilder: NewShapeValueBuilder(),\n\t}\n\tb.ParseTimeString = parseExampleTimeString\n\treturn b\n}\n\n\n\n\n\nfunc parseExampleTimeString(ref *ShapeRef, memName, v string) string {\n\tif ref.Location == \"header\" {\n\t\treturn fmt.Sprintf(\"%s: parseTime(%q, %q),\\n\", memName, protocol.RFC822TimeFormat, v)\n\t}\n\n\tswitch ref.API.Metadata.Protocol {\n\tcase \"json\", \"rest-json\", \"rest-xml\", \"ec2\", \"query\":\n\t\treturn fmt.Sprintf(\"%s: parseTime(%q, %q),\\n\", memName, protocol.ISO8601TimeFormat, v)\n\tdefault:\n\t\tpanic(\"Unsupported time type: \" + ref.API.Metadata.Protocol)\n\t}\n}\n\nfunc (builder defaultExamplesBuilder) Imports(a *API) string ", "output": "{\n\treturn `\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"` + SDKImportRoot + `/aws\"\n\t\"` + SDKImportRoot + `/aws/awserr\"\n\t\"` + SDKImportRoot + `/aws/session\"\n\t\"` + a.ImportPath() + `\"\n\t`\n}"} {"input": "package alertsv2\n\nimport \"net/url\"\n\ntype EscalateToNextRequest struct {\n\t*Identifier\n\tEscalation Escalation `json:\"escalation,omitempty\"`\n\tUser string `json:\"user,omitempty\"`\n\tSource string `json:\"source,omitempty\"`\n\tNote string `json:\"note,omitempty\"`\n\tApiKey string `json:\"-\"`\n}\n\n\n\nfunc (r *EscalateToNextRequest) GetApiKey() string {\n\treturn r.ApiKey\n}\n\nfunc (r *EscalateToNextRequest) GenerateUrl() (string, url.Values, error) ", "output": "{\n\tpath, params, err := r.Identifier.GenerateUrl()\n\treturn path + \"/escalate\", params, err\n}"} {"input": "package TeleGogo\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n)\n\nfunc responseToError(response *http.Response) error {\n\treturn responseToTgError(response)\n}\n\nfunc responseToTgError(response *http.Response) TelegramError {\n\tdefer response.Body.Close()\n\ttgErr := telegramError{}\n\tjson.NewDecoder(response.Body).Decode(&tgErr)\n\treturn tgErr\n}\n\nfunc errToTelegramErr(err error) TelegramError {\n\treturn telegramError{OK: false, ErrorCode: 0, Description: err.Error()}\n}\n\ntype telegramError struct {\n\tOK bool `json:\"ok\"`\n\tErrorCode int `json:\"error_code\"`\n\tDescription string `json:\"description\"`\n}\n\nfunc (t telegramError) IsOK() bool {\n\treturn t.OK\n}\n\nfunc (t telegramError) ErrCode() int {\n\treturn t.ErrorCode\n}\n\n\n\n\ntype TelegramError interface {\n\tIsOK() bool\n\tErrCode() int\n\tError() string\n}\n\nfunc (t telegramError) Error() string ", "output": "{\n\treturn t.Description\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc max(x int, y int) int {\n\tif (x > y) {\n\t\treturn x\n\t} else {\n\t\treturn y\n\t}\n}\n\nfunc swap(x *int, y *int) {\n\tvar temp int\n\ttemp = *x;\n\t*x = *y\n\t*y = temp\n}\n\n\n\ntype Circle struct {\n\tx, y, radius float64\n}\n\nfunc(circle Circle) area() float64 {\n\treturn math.Pi * circle.radius * circle.radius \n}\n\nfunc main() {\n\tvar a, b int = 2, 3;\n\tfmt.Printf(\"max value is %d\\n\", max(a,b));\n\n\tfmt.Printf(\"a = %d, b = %d\\n\", a, b);\n\tswap(&a, &b);\n\tfmt.Printf(\"a = %d, b = %d\\n\", a, b);\n\n\txxx := swap\n\txxx(&a, &b)\n\tfmt.Printf(\"a = %d, b = %d\\n\", a, b);\n\n\tnumber := getSequence()\n\tfmt.Printf(\"number is %d\\n\", number())\n\tfmt.Printf(\"number is %d\\n\", number())\n\tfmt.Printf(\"number is %d\\n\", number())\n\tfmt.Printf(\"number is %d\\n\", number())\n\tnumber1 := getSequence()\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\n\tcircle := Circle{x:0, y:0, radius:5}\n\tfmt.Printf(\"Circle area: %f\\n\", circle.area())\n\n}\n\nfunc getSequence() func() int ", "output": "{\n\tvar i int = 0;\n\treturn func() int {\n\t\ti++;\n\t\treturn i\n\t}\n}"} {"input": "package internal\n\n\n\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar limitSem = make(chan int, 100) \n\nfunc limitRelease() {\n\tselect {\n\tcase <-limitSem:\n\tdefault:\n\t\tlog.Print(\"appengine: unbalanced limitSem release!\")\n\t}\n}\n\n\n\ntype limitConn struct {\n\tclose sync.Once\n\tnet.Conn\n}\n\nfunc (lc *limitConn) Close() error {\n\tdefer lc.close.Do(func() {\n\t\tlimitRelease()\n\t\truntime.SetFinalizer(lc, nil)\n\t})\n\treturn lc.Conn.Close()\n}\n\nfunc limitDial(network, addr string) (net.Conn, error) ", "output": "{\n\tlimitSem <- 1\n\n\tconn, err := net.DialTimeout(network, addr, 500*time.Millisecond)\n\tif err != nil {\n\t\tlimitRelease()\n\t\treturn nil, err\n\t}\n\tlc := &limitConn{Conn: conn}\n\truntime.SetFinalizer(lc, (*limitConn).Close) \n\treturn lc, nil\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\n\n\nfunc naclClose(fd int) (err error) {\n\t_, _, e1 := Syscall(sys_close, uintptr(fd), 0, 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclFstat(fd int, stat *Stat_t) (err error) {\n\t_, _, e1 := Syscall(sys_fstat, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclRead(fd int, b []byte) (n int, err error) {\n\tvar _p0 unsafe.Pointer\n\tif len(b) > 0 {\n\t\t_p0 = unsafe.Pointer(&b[0])\n\t} else {\n\t\t_p0 = unsafe.Pointer(&_zero)\n\t}\n\tr0, _, e1 := Syscall(sys_read, uintptr(fd), uintptr(_p0), uintptr(len(b)))\n\tn = int(r0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\n\n\n\n\nfunc naclGetRandomBytes(b []byte) (err error) {\n\tvar _p0 unsafe.Pointer\n\tif len(b) > 0 {\n\t\t_p0 = unsafe.Pointer(&b[0])\n\t} else {\n\t\t_p0 = unsafe.Pointer(&_zero)\n\t}\n\t_, _, e1 := Syscall(sys_get_random_bytes, uintptr(_p0), uintptr(len(b)), 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\nfunc naclSeek(fd int, off *int64, whence int) (err error) ", "output": "{\n\t_, _, e1 := Syscall(sys_lseek, uintptr(fd), uintptr(unsafe.Pointer(off)), uintptr(whence))\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}"} {"input": "package muxer\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\tdebug \"github.com/micro/micro/v3/service/debug/handler\"\n\t\"github.com/micro/micro/v3/service/proxy\"\n\t\"github.com/micro/micro/v3/service/server\"\n\t\"github.com/micro/micro/v3/service/server/mucp\"\n)\n\n\ntype Server struct {\n\tName string\n\tProxy proxy.Proxy\n\tHandler Handler\n}\n\ntype Handler interface {\n\tproxy.Proxy\n\tNewHandler(interface{}, ...server.HandlerOption) server.Handler\n\tHandle(server.Handler) error\n}\n\nvar (\n\tonce sync.Once\n)\n\nfunc (s *Server) ProcessMessage(ctx context.Context, msg server.Message) error {\n\tif msg.Topic() == s.Name {\n\t\treturn s.Handler.ProcessMessage(ctx, msg)\n\t}\n\treturn s.Proxy.ProcessMessage(ctx, msg)\n}\n\nfunc (s *Server) ServeRequest(ctx context.Context, req server.Request, rsp server.Response) error {\n\tif req.Service() == s.Name {\n\t\treturn s.Handler.ServeRequest(ctx, req, rsp)\n\t}\n\treturn s.Proxy.ServeRequest(ctx, req, rsp)\n}\n\n\n\nfunc New(name string, p proxy.Proxy) *Server ", "output": "{\n\tr := mucp.DefaultRouter\n\n\tonce.Do(func() {\n\t\tr.Handle(\n\t\t\tr.NewHandler(\n\t\t\t\tdebug.NewHandler(),\n\t\t\t\tserver.InternalHandler(true),\n\t\t\t),\n\t\t)\n\t})\n\n\treturn &Server{\n\t\tName: name,\n\t\tProxy: p,\n\t\tHandler: r,\n\t}\n}"} {"input": "package v1beta1\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/uuid\"\n)\n\nconst (\n\tuuidPrefix = \"knative-kafka-source-\"\n)\n\n\n\n\nfunc (k *KafkaSource) SetDefaults(ctx context.Context) ", "output": "{\n\tif k != nil && k.Spec.ConsumerGroup == \"\" {\n\t\tk.Spec.ConsumerGroup = uuidPrefix + uuid.New().String()\n\t}\n}"} {"input": "package goparser\n\nimport (\n\t\"go/ast\"\n\t\"testing\"\n)\n\n\n\n\nfunc TestCmtToStr1(t *testing.T) {\n\ttestCmtAgainstExpt(t,\n\t\t\"//\\n\"+\n\t\t\t\" // testing line 1\\n\"+\n\t\t\t\"//testing line 2\\n\"+\n\t\t\t\"// testing line 3\",\n\t\t\"testing line 1\\n\"+\n\t\t\t\"testing line 2\\n\"+\n\t\t\t\"testing line 3\\n\")\n}\n\n\nfunc TestCmtToStr2(t *testing.T) {\n\ttestCmtAgainstExpt(t,\n\t\t\"/**\\n\"+\n\t\t\t\" * testing line 1\\n\"+\n\t\t\t\"* testing line 2\\n\"+\n\t\t\t\" * testing line 3\\n\"+\n\t\t\t\" */\",\n\t\t\" testing line 1\\n\"+\n\t\t\t\" testing line 2\\n\"+\n\t\t\t\" testing line 3\\n\")\n}\n\n\nfunc TestCmtToStr3(t *testing.T) {\n\ttestCmtAgainstExpt(t,\n\t\t\"/*\\n\"+\n\t\t\t\" testing line 1\\n\"+\n\t\t\t\" testing line 2\\n\"+\n\t\t\t\" testing line 3\\n\"+\n\t\t\t\"*/\",\n\t\t\" testing line 1\\n\"+\n\t\t\t\" testing line 2\\n\"+\n\t\t\t\" testing line 3\\n\")\n}\n\nfunc testCmtAgainstExpt(t *testing.T, text, expected string) ", "output": "{\n\tcmt := ast.Comment{\n\t\tText: text,\n\t}\n\n\tresult := CmtToStr(&cmt)\n\n\tif expected != result {\n\t\tt.Errorf(\"Result doesn't match expectation\")\n\t\tt.Errorf(\"Expected:\\n%s\", expected)\n\t\tt.Errorf(\"Get:\\n%s\", result)\n\t}\n}"} {"input": "package internalversion\n\nimport (\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"github.com/hyperhq/client-go/tools/cache\"\n\tcore \"k8s.io/kubernetes/pkg/apis/core\"\n)\n\n\ntype EventLister interface {\n\tList(selector labels.Selector) (ret []*core.Event, err error)\n\tEvents(namespace string) EventNamespaceLister\n\tEventListerExpansion\n}\n\n\ntype eventLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewEventLister(indexer cache.Indexer) EventLister {\n\treturn &eventLister{indexer: indexer}\n}\n\n\nfunc (s *eventLister) List(selector labels.Selector) (ret []*core.Event, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*core.Event))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *eventLister) Events(namespace string) EventNamespaceLister {\n\treturn eventNamespaceLister{indexer: s.indexer, namespace: namespace}\n}\n\n\ntype EventNamespaceLister interface {\n\tList(selector labels.Selector) (ret []*core.Event, err error)\n\tGet(name string) (*core.Event, error)\n\tEventNamespaceListerExpansion\n}\n\n\n\ntype eventNamespaceLister struct {\n\tindexer cache.Indexer\n\tnamespace string\n}\n\n\n\n\n\nfunc (s eventNamespaceLister) Get(name string) (*core.Event, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(core.Resource(\"event\"), name)\n\t}\n\treturn obj.(*core.Event), nil\n}\n\nfunc (s eventNamespaceLister) List(selector labels.Selector) (ret []*core.Event, err error) ", "output": "{\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*core.Event))\n\t})\n\treturn ret, err\n}"} {"input": "package static\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/pkg/errors\"\n\t\"github.com/sirupsen/logrus\"\n)\n\n\n\nfunc Stage(dataDir string) error ", "output": "{\n\tfor _, name := range AssetNames() {\n\t\tcontent, err := Asset(name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tp := filepath.Join(dataDir, name)\n\t\tlogrus.Info(\"Writing static file: \", p)\n\t\tos.MkdirAll(filepath.Dir(p), 0700)\n\t\tif err := ioutil.WriteFile(p, content, 0600); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to write to %s\", name)\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n)\n\nfunc main() {\n\n\tif len(os.Args) == 1 {\n\t\tfmt.Println(\"Please provide either a file path or a number input\")\n\n\t} else {\n\n\t\tinput := os.Args[1]\n\t\tfile, err := os.Open(input)\n\n\t\tif check(err) == false {\n\t\t\tdefer file.Close()\n\n\t\t\treader := bufio.NewReader(file)\n\t\t\tscanner := bufio.NewScanner(reader)\n\n\t\t\tfor scanner.Scan() {\n\t\t\t\tvalue := scanner.Text()\n\t\t\t\tif value == \"#\" {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tvalue = cleanString(value)\n\n\t\t\t\tnum := stringToInt(value)\n\t\t\t\tif num <= 15 {\n\t\t\t\t\tfmt.Println(factorial(num))\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else if check(err) == true {\n\t\t\tintInput := stringToInt(input)\n\n\t\t\toutput := factorial(intInput)\n\t\t\tfmt.Println(output)\n\n\t\t}\n\n\t}\n\n}\n\nfunc factorial(number int64) (factor int64) {\n\tfactor = 1\n\n\tif number == 1 {\n\t\treturn\n\t} else {\n\n\t\tvar counter int64 = 1\n\n\t\tfor i := counter; i <= number; i++ {\n\t\t\tfactor = factor * i\n\t\t}\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc stringToInt(input string) int64 {\n\tresult, _ := strconv.ParseInt(input, 10, 0)\n\treturn result\n}\n\n\n\nfunc cleanString(value string) (result string) {\n\n\tr := regexp.MustCompile(`\\d+`)\n\tmatches := r.FindAllString(value, -1)\n\n\tfor _, value := range matches {\n\t\tresult += value\n\t}\n\n\treturn\n}\n\nfunc check(e error) bool ", "output": "{\n\tif e != nil {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package ini\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/mono83/cfg\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"strings\"\n)\n\nvar nlByte = []byte{0x0a}\n\n\n\nfunc NewReaderSource(source io.Reader) (cfg.Configurer, error) {\n\tbts, err := ioutil.ReadAll(source)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewBytesSource(bts)\n}\n\n\n\n\n\n\n\nfunc NewBytesSource(source []byte) (cfg.Configurer, error) {\n\tif len(source) == 0 {\n\t\treturn nil, errors.New(\"Empty INI source\")\n\t}\n\n\tsrc := map[string]interface{}{}\n\tfor _, bline := range bytes.Split(source, nlByte) {\n\t\tline := strings.TrimSpace(string(bline))\n\t\tif len(line) == 0 || line[0] == '#' || line[0] == '/' || line[0] == '[' {\n\t\t\tcontinue\n\t\t}\n\n\t\tpos := strings.IndexRune(line, '=')\n\t\tif pos == -1 {\n\t\t\treturn nil, fmt.Errorf(\"Unable to parse line %s\", line)\n\t\t}\n\n\t\tkey := strings.TrimSpace(line[0:pos])\n\t\tvalue := strings.TrimSpace(line[pos+1:])\n\n\t\tsrc[key] = value\n\t}\n\n\treturn cfg.Map(src), nil\n}\n\nfunc NewStringSource(source string) (cfg.Configurer, error) ", "output": "{\n\treturn NewBytesSource([]byte(source))\n}"} {"input": "package playQueue\n\nimport (\n\t\"log\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/tv42/cliutil/subcommands\"\n\t\"github.com/tv42/sinus/cli\"\n\t\"github.com/tv42/sinus/util\"\n)\n\ntype playQueueCommand struct {\n\tsubcommands.Description\n\tArguments struct{}\n}\n\nfunc (c *playQueueCommand) Run() error {\n\ttransport, err := cli.App.AVTransport()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, _, currentURI, _, _, _, _, _, _, err := transport.GetMediaInfo(0)\n\tif err != nil {\n\t\tlog.Fatalf(\"get media info: %v\", err)\n\t}\n\tif !strings.HasPrefix(currentURI, \"x-rincon-queue:\") {\n\t\tu := &url.URL{\n\t\t\tScheme: \"x-rincon-queue\",\n\t\t\tOpaque: util.DeviceUUID(transport.RootDevice),\n\t\t\tFragment: \"0\",\n\t\t}\n\t\tif err := transport.SetAVTransportURI(0, u.String(), \"\"); err != nil {\n\t\t\tlog.Fatalf(\"play from queue: %v\", err)\n\t\t}\n\t}\n\n\tif err := transport.Play(0, \"1\"); err != nil {\n\t\tlog.Fatalf(\"play: %v\", err)\n\t}\n\treturn nil\n}\n\nvar playQueue = playQueueCommand{\n\tDescription: \"play music from the queue\",\n}\n\n\n\nfunc init() ", "output": "{\n\tsubcommands.Register(&playQueue)\n}"} {"input": "package internalversion\n\nimport (\n\tapiextensions \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype CustomResourceDefinitionLister interface {\n\tList(selector labels.Selector) (ret []*apiextensions.CustomResourceDefinition, err error)\n\tGet(name string) (*apiextensions.CustomResourceDefinition, error)\n\tCustomResourceDefinitionListerExpansion\n}\n\n\ntype customResourceDefinitionLister struct {\n\tindexer cache.Indexer\n}\n\n\n\n\n\nfunc (s *customResourceDefinitionLister) List(selector labels.Selector) (ret []*apiextensions.CustomResourceDefinition, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*apiextensions.CustomResourceDefinition))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *customResourceDefinitionLister) Get(name string) (*apiextensions.CustomResourceDefinition, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(apiextensions.Resource(\"customresourcedefinition\"), name)\n\t}\n\treturn obj.(*apiextensions.CustomResourceDefinition), nil\n}\n\nfunc NewCustomResourceDefinitionLister(indexer cache.Indexer) CustomResourceDefinitionLister ", "output": "{\n\treturn &customResourceDefinitionLister{indexer: indexer}\n}"} {"input": "package scene\n\nimport \"github.com/thinkofdeath/steven/ui\"\n\n\ntype Type struct {\n\tvisible bool\n\n\tdrawables []ui.Drawable\n\thidding bool\n}\n\n\nfunc New(visible bool) *Type {\n\treturn &Type{\n\t\tvisible: visible,\n\t}\n}\n\n\nfunc (t *Type) Show() {\n\tif t.visible {\n\t\treturn\n\t}\n\tt.visible = true\n\tfor _, d := range t.drawables {\n\t\tui.AddDrawable(d)\n\t}\n}\n\n\nfunc (t *Type) Hide() {\n\tif !t.visible {\n\t\treturn\n\t}\n\tt.visible = false\n\tt.hidding = true\n\tfor _, d := range t.drawables {\n\t\tui.Remove(d)\n\t}\n\tt.hidding = false\n}\n\n\nfunc (t *Type) AddDrawable(d ui.Drawable) {\n\tt.drawables = append(t.drawables, d)\n\tif t.visible {\n\t\tui.AddDrawable(d)\n\t}\n\td.SetRemoveHook(t.removeHook)\n}\n\n\n\n\nfunc (t *Type) IsVisible() bool {\n\treturn t.visible\n}\n\nfunc (t *Type) removeHook(d ui.Drawable) ", "output": "{\n\tif t.hidding {\n\t\treturn\n\t}\n\tfor i, dd := range t.drawables {\n\t\tif dd == d {\n\t\t\tt.drawables = append(t.drawables[:i], t.drawables[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n\n}"} {"input": "package gfile\n\nimport (\n\t\"bytes\"\n\t\"github.com/gogf/gf/v2/errors/gcode\"\n\t\"github.com/gogf/gf/v2/errors/gerror\"\n\t\"os\"\n\t\"os/exec\"\n\t\"os/user\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n\n\n\nfunc Home(names ...string) (string, error) {\n\tpath, err := getHomePath()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfor _, name := range names {\n\t\tpath += Separator + name\n\t}\n\treturn path, nil\n}\n\n\nfunc getHomePath() (string, error) {\n\tu, err := user.Current()\n\tif nil == err {\n\t\treturn u.HomeDir, nil\n\t}\n\tif \"windows\" == runtime.GOOS {\n\t\treturn homeWindows()\n\t}\n\treturn homeUnix()\n}\n\n\n\n\n\nfunc homeWindows() (string, error) {\n\tvar (\n\t\tdrive = os.Getenv(\"HOMEDRIVE\")\n\t\tpath = os.Getenv(\"HOMEPATH\")\n\t\thome = drive + path\n\t)\n\tif drive == \"\" || path == \"\" {\n\t\thome = os.Getenv(\"USERPROFILE\")\n\t}\n\tif home == \"\" {\n\t\treturn \"\", gerror.NewCode(gcode.CodeOperationFailed, \"HOMEDRIVE, HOMEPATH, and USERPROFILE are blank\")\n\t}\n\n\treturn home, nil\n}\n\nfunc homeUnix() (string, error) ", "output": "{\n\tif home := os.Getenv(\"HOME\"); home != \"\" {\n\t\treturn home, nil\n\t}\n\tvar stdout bytes.Buffer\n\tcmd := exec.Command(\"sh\", \"-c\", \"eval echo ~$USER\")\n\tcmd.Stdout = &stdout\n\tif err := cmd.Run(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresult := strings.TrimSpace(stdout.String())\n\tif result == \"\" {\n\t\treturn \"\", gerror.NewCode(gcode.CodeInternalError, \"blank output when reading home directory\")\n\t}\n\n\treturn result, nil\n}"} {"input": "package channelling\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"log\"\n\n\t\"github.com/strukturag/spreed-webrtc/go/buffercache\"\n)\n\ntype IncomingDecoder interface {\n\tDecodeIncoming(buffercache.Buffer) (*DataIncoming, error)\n}\n\ntype OutgoingEncoder interface {\n\tEncodeOutgoing(*DataOutgoing) (buffercache.Buffer, error)\n}\n\ntype Codec interface {\n\tNewBuffer() buffercache.Buffer\n\tIncomingDecoder\n\tOutgoingEncoder\n}\n\ntype incomingCodec struct {\n\tbuffers buffercache.BufferCache\n\tincomingLimit int\n}\n\n\n\nfunc (codec incomingCodec) NewBuffer() buffercache.Buffer {\n\treturn codec.buffers.New()\n}\n\nfunc (codec incomingCodec) DecodeIncoming(b buffercache.Buffer) (*DataIncoming, error) {\n\tlength := b.GetBuffer().Len()\n\tif length > codec.incomingLimit {\n\t\treturn nil, errors.New(\"Incoming message size limit exceeded\")\n\t}\n\tincoming := &DataIncoming{}\n\treturn incoming, json.Unmarshal(b.Bytes(), incoming)\n}\n\nfunc (codec incomingCodec) EncodeOutgoing(outgoing *DataOutgoing) (buffercache.Buffer, error) {\n\tb := codec.NewBuffer()\n\tif err := json.NewEncoder(b).Encode(outgoing); err != nil {\n\t\tlog.Println(\"Error while encoding JSON\", err)\n\t\tb.Decref()\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}\n\nfunc NewCodec(incomingLimit int) Codec ", "output": "{\n\treturn &incomingCodec{buffercache.NewBufferCache(1024, bytes.MinRead), incomingLimit}\n}"} {"input": "package latest\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"k8s.io/apimachinery/pkg/runtime/serializer/json\"\n\t\"k8s.io/apimachinery/pkg/runtime/serializer/versioning\"\n\t\"k8s.io/client-go/tools/clientcmd/api\"\n\t\"k8s.io/client-go/tools/clientcmd/api/v1\"\n)\n\n\nconst Version = \"v1\"\n\nvar ExternalVersion = schema.GroupVersion{Group: \"\", Version: \"v1\"}\n\n\n\nconst OldestVersion = \"v1\"\n\n\n\n\n\nvar Versions = []string{\"v1\"}\n\nvar (\n\tCodec runtime.Codec\n\tScheme *runtime.Scheme\n)\n\n\n\nfunc init() ", "output": "{\n\tScheme = runtime.NewScheme()\n\tif err := api.AddToScheme(Scheme); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := v1.AddToScheme(Scheme); err != nil {\n\t\tpanic(err)\n\t}\n\tyamlSerializer := json.NewYAMLSerializer(json.DefaultMetaFactory, Scheme, Scheme)\n\tCodec = versioning.NewDefaultingCodecForScheme(\n\t\tScheme,\n\t\tyamlSerializer,\n\t\tyamlSerializer,\n\t\tschema.GroupVersion{Version: Version},\n\t\truntime.InternalGroupVersioner,\n\t)\n}"} {"input": "package main\n\nimport (\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype queryNode struct {\n\tvalues url.Values\n\tprefix string\n\tdistinct bool\n\tfull bool\n}\n\n\n\nfunc (q *queryNode) processFlags(queries arrayFlags) {\n\tfor _, val := range queries {\n\t\tparts := strings.Split(val, \":\")\n\t\tif len(parts) == 2 {\n\t\t\tname := q.prefix + parts[0]\n\t\t\tq.values.Set(name, parts[1])\n\t\t}\n\t}\n}\n\nfunc (q *queryNode) addOptions() {\n\tif limit != 0 {\n\t\tq.values.Set(\"limit\", strconv.Itoa(limit))\n\t}\n\tif offset != 0 {\n\t\tq.values.Set(\"offset\", strconv.Itoa(offset))\n\t}\n\tif (direction != \"\") && validateCV(\"direction\", direction) {\n\t\tq.values.Set(\"direction\", direction)\n\t}\n\tif order != \"\" {\n\t\tq.values.Set(\"order\", order)\n\t}\n\tif distinct != \"\" {\n\t\tq.distinct = true\n\t\tq.values.Set(\"distinct\", distinct)\n\t}\n}\n\nfunc newQueryNode() queryNode ", "output": "{\n\treturn queryNode{\n\t\tvalues: url.Values{},\n\t\tprefix: \"\",\n\t\tdistinct: false,\n\t\tfull: false,\n\t}\n}"} {"input": "package fstest\n\nimport (\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"github.com/containerd/continuity/sysx\"\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\n\n\nfunc Lchtimes(name string, atime, mtime time.Time) Applier {\n\treturn applyFn(func(root string) error {\n\t\tpath := filepath.Join(root, name)\n\t\tat := unix.NsecToTimespec(atime.UnixNano())\n\t\tmt := unix.NsecToTimespec(mtime.UnixNano())\n\t\tutimes := [2]unix.Timespec{at, mt}\n\t\treturn unix.UtimesNanoAt(unix.AT_FDCWD, path, utimes[0:], unix.AT_SYMLINK_NOFOLLOW)\n\t})\n}\n\nfunc Base() Applier {\n\treturn applyFn(func(root string) error {\n\t\treturn nil\n\t})\n}\n\nfunc SetXAttr(name, key, value string) Applier ", "output": "{\n\treturn applyFn(func(root string) error {\n\t\treturn sysx.LSetxattr(name, key, []byte(value), 0)\n\t})\n}"} {"input": "package config\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"text/template\"\n)\n\nvar (\n\tglbEnvs map[string]string\n)\n\nfunc init() {\n\tglbEnvs = make(map[string]string)\n\tenvs := os.Environ()\n\tfor _, env := range envs {\n\t\tkv := strings.Split(env, \"=\")\n\t\tif len(kv) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tglbEnvs[kv[0]] = kv[1]\n\t}\n}\n\ntype Values struct {\n\tEnvs map[string]string \n}\n\n\n\nfunc RenderContent(in []byte) (out []byte, err error) {\n\ttmpl, errRet := template.New(\"frp\").Parse(string(in))\n\tif errRet != nil {\n\t\terr = errRet\n\t\treturn\n\t}\n\n\tbuffer := bytes.NewBufferString(\"\")\n\tv := GetValues()\n\terr = tmpl.Execute(buffer, v)\n\tif err != nil {\n\t\treturn\n\t}\n\tout = buffer.Bytes()\n\treturn\n}\n\nfunc GetRenderedConfFromFile(path string) (out []byte, err error) {\n\tvar b []byte\n\tb, err = ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tout, err = RenderContent(b)\n\treturn\n}\n\nfunc GetValues() *Values ", "output": "{\n\treturn &Values{\n\t\tEnvs: glbEnvs,\n\t}\n}"} {"input": "package block\n\n\ntype NoopLeaseManager struct{}\n\nfunc (n *NoopLeaseManager) RegisterLeaser(leaser Leaser) error {\n\treturn nil\n}\n\nfunc (n *NoopLeaseManager) UnregisterLeaser(leaser Leaser) error {\n\treturn nil\n}\n\nfunc (n *NoopLeaseManager) OpenLease(\n\tleaser Leaser,\n\tdescriptor LeaseDescriptor,\n\tstate LeaseState,\n) error {\n\treturn nil\n}\n\n\n\nfunc (n *NoopLeaseManager) UpdateOpenLeases(\n\tdescriptor LeaseDescriptor,\n\tstate LeaseState,\n) (UpdateLeasesResult, error) {\n\treturn UpdateLeasesResult{}, nil\n}\n\nfunc (n *NoopLeaseManager) SetLeaseVerifier(leaseVerifier LeaseVerifier) error {\n\treturn nil\n}\n\nfunc (n *NoopLeaseManager) OpenLatestLease(\n\tleaser Leaser,\n\tdescriptor LeaseDescriptor,\n) (LeaseState, error) ", "output": "{\n\treturn LeaseState{}, nil\n}"} {"input": "package credentials\n\nimport (\n\t\"strings\"\n\n\t\"github.com/docker/docker/cliconfig/configfile\"\n\t\"github.com/docker/engine-api/types\"\n)\n\n\n\ntype fileStore struct {\n\tfile *configfile.ConfigFile\n}\n\n\nfunc NewFileStore(file *configfile.ConfigFile) Store {\n\treturn &fileStore{\n\t\tfile: file,\n\t}\n}\n\n\n\n\n\nfunc (c *fileStore) Get(serverAddress string) (types.AuthConfig, error) {\n\tauthConfig, ok := c.file.AuthConfigs[serverAddress]\n\tif !ok {\n\t\tfor registry, ac := range c.file.AuthConfigs {\n\t\t\tif serverAddress == convertToHostname(registry) {\n\t\t\t\treturn ac, nil\n\t\t\t}\n\t\t}\n\n\t\tauthConfig = types.AuthConfig{}\n\t}\n\treturn authConfig, nil\n}\n\nfunc (c *fileStore) GetAll() (map[string]types.AuthConfig, error) {\n\treturn c.file.AuthConfigs, nil\n}\n\n\nfunc (c *fileStore) Store(authConfig types.AuthConfig) error {\n\tc.file.AuthConfigs[authConfig.ServerAddress] = authConfig\n\treturn c.file.Save()\n}\n\nfunc convertToHostname(url string) string {\n\tstripped := url\n\tif strings.HasPrefix(url, \"http://\") {\n\t\tstripped = strings.Replace(url, \"http://\", \"\", 1)\n\t} else if strings.HasPrefix(url, \"https://\") {\n\t\tstripped = strings.Replace(url, \"https://\", \"\", 1)\n\t}\n\n\tnameParts := strings.SplitN(stripped, \"/\", 2)\n\n\treturn nameParts[0]\n}\n\nfunc (c *fileStore) Erase(serverAddress string) error ", "output": "{\n\tdelete(c.file.AuthConfigs, serverAddress)\n\treturn c.file.Save()\n}"} {"input": "package api\n\nimport (\n\t\"github.com/gorilla/mux\"\n\t\"net/http\"\n)\n\n\ntype Server struct {\n}\n\nfunc (s *Server) HandlePing(w http.ResponseWriter, r *http.Request) {\n\n}\n\n\n\n\nfunc (s *Server) SetupRoutes(r *mux.Router) ", "output": "{\n\tr.Path(\"/ping\").HandlerFunc(s.HandlePing)\n}"} {"input": "package bundlerules\n\nimport (\n\t\"path/filepath\"\n\n\tspec \"code.cloudfoundry.org/guardian/gardener/container-spec\"\n\t\"code.cloudfoundry.org/guardian/rundmc/goci\"\n)\n\ntype CGroupPath struct {\n\tPath string\n}\n\n\n\nfunc (r CGroupPath) Apply(bndl goci.Bndl, spec spec.DesiredContainerSpec, _ string) (goci.Bndl, error) ", "output": "{\n\tif spec.Privileged {\n\t\treturn bndl, nil\n\t}\n\n\tif spec.CgroupPath != \"\" {\n\t\treturn bndl.WithCGroupPath(filepath.Join(r.Path, spec.CgroupPath)), nil\n\t}\n\n\treturn bndl.WithCGroupPath(filepath.Join(r.Path, spec.Handle)), nil\n}"} {"input": "package outputs\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/lfkeitel/spartan/event\"\n\n\ttomb \"gopkg.in/tomb.v2\"\n)\n\n\n\n\ntype OutputController struct {\n\tstart Output\n\tbatchSize int\n\tt tomb.Tomb\n\tin <-chan *event.Event\n\tout chan<- *event.Event\n}\n\n\n\nfunc NewOutputController(start Output, batchSize int) *OutputController {\n\treturn &OutputController{\n\t\tstart: start,\n\t\tbatchSize: batchSize,\n\t}\n}\n\n\n\n\nfunc (o *OutputController) Start(in chan *event.Event) error {\n\to.in = in\n\to.t.Go(o.run)\n\treturn nil\n}\n\n\n\n\nfunc (o *OutputController) Close() error {\n\to.t.Kill(nil)\n\treturn o.t.Wait()\n}\n\n\n\n\nfunc checkOptionsMap(o map[string]interface{}) map[string]interface{} {\n\tif o == nil {\n\t\to = make(map[string]interface{})\n\t}\n\treturn o\n}\n\nfunc (o *OutputController) run() error ", "output": "{\n\tfmt.Println(\"Output Pipeline started\")\n\tfor {\n\t\tselect {\n\t\tcase <-o.t.Dying():\n\t\t\treturn nil\n\t\tdefault:\n\t\t}\n\n\t\tcurrentBatch := 0\n\t\tbatch := make([]*event.Event, o.batchSize)\n\t\tstopping := false\n\n\tCURRENT:\n\t\tfor currentBatch < o.batchSize {\n\t\t\tselect {\n\t\t\tcase event := <-o.in:\n\t\t\t\tbatch[currentBatch] = event\n\t\t\t\tcurrentBatch++\n\t\t\tcase <-o.t.Dying():\n\t\t\t\tstopping = true\n\t\t\t\tbreak CURRENT\n\t\t\t}\n\t\t}\n\n\t\tfmt.Println(\"Processing batch\")\n\t\to.start.Run(batch)\n\n\t\tif stopping {\n\t\t\treturn nil\n\t\t}\n\t}\n}"} {"input": "package dead\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nvar (\n\tunits = []struct {\n\t\tdivisor time.Duration\n\t\tunit rune\n\t}{\n\t\t{1000000, 's'},\n\t\t{60, 'm'},\n\t\t{60, 'h'},\n\t\t{24, 'd'},\n\t\t{7, 'w'},\n\t}\n)\n\n\n\nfunc foobar(d time.Duration) string ", "output": "{\n\td /= time.Microsecond\n\tunit := 'u'\n\n\tfor _, f := range units {\n\t\tif d%f.divisor != 0 {\n\t\t\tbreak\n\t\t}\n\t\td /= f.divisor\n\t\tunit = f.unit\n\t}\n\treturn fmt.Sprintf(\"%d%c\", d, unit)\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\n\tbf \"github.com/bazelbuild/buildtools/build\"\n\t\"github.com/bazelbuild/rules_go/go/tools/gazelle/config\"\n)\n\n\n\nfunc printFile(c *config.Config, f *bf.File) error ", "output": "{\n\t_, err := os.Stdout.Write(bf.Format(f))\n\treturn err\n}"} {"input": "package transport\n\nimport \"net\"\n\n\n\nfunc ConnWrapper(d Dialer, w func(net.Conn) net.Conn) Dialer ", "output": "{\n\treturn DialerFunc(func(network, addr string) (net.Conn, error) {\n\t\tc, err := d.Dial(network, addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn w(c), nil\n\t})\n}"} {"input": "package murmur\n\nimport (\n\t\"unsafe\"\n)\n\n\n\nfunc getBlock(data []byte, n int) (int64, int64) ", "output": "{\n\tblock := (*[2]int64)(unsafe.Pointer(&data[n*16]))\n\n\tk1 := block[0]\n\tk2 := block[1]\n\treturn k1, k2\n}"} {"input": "package iso20022\n\n\ntype StandingSettlementInstruction9 struct {\n\n\tSettlementStandingInstructionDatabase *SettlementStandingInstructionDatabase3Choice `xml:\"SttlmStgInstrDB\"`\n\n\tVendor *PartyIdentification32Choice `xml:\"Vndr,omitempty\"`\n\n\tOtherDeliveringSettlementParties *SettlementParties23 `xml:\"OthrDlvrgSttlmPties,omitempty\"`\n\n\tOtherReceivingSettlementParties *SettlementParties23 `xml:\"OthrRcvgSttlmPties,omitempty\"`\n}\n\nfunc (s *StandingSettlementInstruction9) AddSettlementStandingInstructionDatabase() *SettlementStandingInstructionDatabase3Choice {\n\ts.SettlementStandingInstructionDatabase = new(SettlementStandingInstructionDatabase3Choice)\n\treturn s.SettlementStandingInstructionDatabase\n}\n\n\n\nfunc (s *StandingSettlementInstruction9) AddOtherDeliveringSettlementParties() *SettlementParties23 {\n\ts.OtherDeliveringSettlementParties = new(SettlementParties23)\n\treturn s.OtherDeliveringSettlementParties\n}\n\nfunc (s *StandingSettlementInstruction9) AddOtherReceivingSettlementParties() *SettlementParties23 {\n\ts.OtherReceivingSettlementParties = new(SettlementParties23)\n\treturn s.OtherReceivingSettlementParties\n}\n\nfunc (s *StandingSettlementInstruction9) AddVendor() *PartyIdentification32Choice ", "output": "{\n\ts.Vendor = new(PartyIdentification32Choice)\n\treturn s.Vendor\n}"} {"input": "package common\n\nimport (\n\t\"strconv\"\n\t\"time\"\n)\n\ntype ConversionResult struct {\n\tDateAsString string\n\tDateAsInt int\n\tDate time.Time\n}\n\n\n\nfunc ConvertStringToDates(dateAsString string) (ConversionResult, error) {\n\tresult := ConversionResult{}\n\tresult.DateAsString = dateAsString\n\n\tdateAsInt, err := strconv.Atoi(dateAsString)\n\tif err != nil {\n\t\treturn result, nil\n\t}\n\tresult.DateAsInt = dateAsInt\n\n\tdate, err := time.Parse(\"20060102\", dateAsString)\n\tif err != nil {\n\t\treturn result, nil\n\t}\n\tresult.Date = date\n\n\treturn result, nil\n}\n\nfunc (d *ConversionResult) Tomorrow() (ConversionResult, error) {\n\treturn ConvertStringToDates(d.Date.AddDate(0, 0, 1).Format(\"20060102\"))\n}\n\nfunc (d *ConversionResult) Yesterday() (ConversionResult, error) {\n\treturn ConvertStringToDates(d.Date.AddDate(0, 0, -1).Format(\"20060102\"))\n}\n\nfunc ConvertIntToDisplay(dateAsInt int) string ", "output": "{\n\tdayAsString := strconv.Itoa(dateAsInt)\n\n\treturn dayAsString\n}"} {"input": "package iso20022\n\n\ntype PlainCardData4 struct {\n\n\tPAN *Min8Max28NumericText `xml:\"PAN\"`\n\n\tCardSequenceNumber *Min2Max3NumericText `xml:\"CardSeqNb,omitempty\"`\n\n\tEffectiveDate *Max10Text `xml:\"FctvDt,omitempty\"`\n\n\tExpiryDate *Max10Text `xml:\"XpryDt\"`\n\n\tServiceCode *Exact3NumericText `xml:\"SvcCd,omitempty\"`\n\n\tTrackData []*TrackData1 `xml:\"TrckData,omitempty\"`\n\n\tCardSecurityCode *CardSecurityInformation1 `xml:\"CardSctyCd,omitempty\"`\n}\n\nfunc (p *PlainCardData4) SetPAN(value string) {\n\tp.PAN = (*Min8Max28NumericText)(&value)\n}\n\nfunc (p *PlainCardData4) SetCardSequenceNumber(value string) {\n\tp.CardSequenceNumber = (*Min2Max3NumericText)(&value)\n}\n\nfunc (p *PlainCardData4) SetEffectiveDate(value string) {\n\tp.EffectiveDate = (*Max10Text)(&value)\n}\n\n\n\nfunc (p *PlainCardData4) SetServiceCode(value string) {\n\tp.ServiceCode = (*Exact3NumericText)(&value)\n}\n\nfunc (p *PlainCardData4) AddTrackData() *TrackData1 {\n\tnewValue := new(TrackData1)\n\tp.TrackData = append(p.TrackData, newValue)\n\treturn newValue\n}\n\nfunc (p *PlainCardData4) AddCardSecurityCode() *CardSecurityInformation1 {\n\tp.CardSecurityCode = new(CardSecurityInformation1)\n\treturn p.CardSecurityCode\n}\n\nfunc (p *PlainCardData4) SetExpiryDate(value string) ", "output": "{\n\tp.ExpiryDate = (*Max10Text)(&value)\n}"} {"input": "package dexcom\n\nimport (\n\t\"math\"\n)\n\n\n\nfunc marshalUint16(n uint16) []byte {\n\treturn []byte{byte(n & 0xFF), byte(n >> 8)}\n}\n\n\nfunc marshalInt16(n int16) []byte {\n\treturn marshalUint16(uint16(n))\n}\n\nfunc marshalUint32(n uint32) []byte {\n\treturn append(marshalUint16(uint16(n&0xFFFF)), marshalUint16(uint16(n>>16))...)\n}\n\nfunc marshalInt32(n int32) []byte {\n\treturn marshalUint32(uint32(n))\n}\n\nfunc unmarshalUint16(v []byte) uint16 {\n\treturn uint16(v[0]) | uint16(v[1])<<8\n}\n\n\nfunc unmarshalInt16(v []byte) int16 {\n\treturn int16(unmarshalUint16(v))\n}\n\nfunc unmarshalUint32(v []byte) uint32 {\n\treturn uint32(unmarshalUint16(v[0:2])) | uint32(unmarshalUint16(v[2:4]))<<16\n}\n\nfunc unmarshalInt32(v []byte) int32 {\n\treturn int32(unmarshalUint32(v))\n}\n\nfunc unmarshalUint64(v []byte) uint64 {\n\treturn uint64(unmarshalUint32(v[0:4])) | uint64(unmarshalUint32(v[4:8]))<<32\n}\n\n\n\nfunc unmarshalFloat64(v []byte) float64 ", "output": "{\n\treturn math.Float64frombits(unmarshalUint64(v))\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/pingcap/tidb\"\n\t\"github.com/pingcap/tidb/domain\"\n\t\"github.com/pingcap/tidb/model\"\n)\n\n\ntype StatsHandler struct {\n\tdo *domain.Domain\n}\n\nfunc (s *Server) newStatsHandler() *StatsHandler {\n\tstore, ok := s.driver.(*TiDBDriver)\n\tif !ok {\n\t\tpanic(\"Illegal driver\")\n\t}\n\n\tdo, err := tidb.GetDomain(store.store)\n\tif err != nil {\n\t\tpanic(\"Failed to get domain\")\n\t}\n\treturn &StatsHandler{do}\n}\n\n\n\nfunc (sh StatsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tparams := mux.Vars(req)\n\n\tis := sh.do.InfoSchema()\n\th := sh.do.StatsHandle()\n\ttbl, err := is.TableByName(model.NewCIStr(params[pDBName]), model.NewCIStr(params[pTableName]))\n\tif err != nil {\n\t\twriteError(w, err)\n\t} else {\n\t\tjs, err := h.DumpStatsToJSON(params[pDBName], tbl.Meta())\n\t\tif err != nil {\n\t\t\twriteError(w, err)\n\t\t} else {\n\t\t\twriteData(w, js)\n\t\t}\n\t}\n}"} {"input": "package graphdriver\n\n\nimport \"C\"\nimport (\n\t\"path/filepath\"\n\t\"unsafe\"\n\n\t\"github.com/docker/docker/pkg/mount\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tFsMagicZfs = FsMagic(0x2fc12fc1)\n)\n\nvar (\n\tpriority = []string{\n\t\t\"zfs\",\n\t}\n\n\tFsNames = map[FsMagic]string{\n\t\tFsMagicZfs: \"zfs\",\n\t}\n)\n\n\n\n\ntype fsChecker struct {\n\tt FsMagic\n}\n\nfunc (c *fsChecker) IsMounted(path string) bool {\n\tm, _ := Mounted(c.t, path)\n\treturn m\n}\n\n\nfunc NewFsChecker(t FsMagic) Checker {\n\treturn &fsChecker{\n\t\tt: t,\n\t}\n}\n\n\n\n\nfunc NewDefaultChecker() Checker {\n\treturn &defaultChecker{}\n}\n\ntype defaultChecker struct {\n}\n\nfunc (c *defaultChecker) IsMounted(path string) bool {\n\tm, _ := mount.Mounted(path)\n\treturn m\n}\n\n\n\nfunc Mounted(fsType FsMagic, mountPath string) (bool, error) {\n\n\tcs := C.CString(filepath.Dir(mountPath))\n\tdefer C.free(unsafe.Pointer(cs))\n\tbuf := C.getstatfs(cs)\n\tdefer C.free(unsafe.Pointer(buf))\n\n\tif (buf.f_basetype[0] != 122) || (buf.f_basetype[1] != 102) || (buf.f_basetype[2] != 115) ||\n\t\t(buf.f_basetype[3] != 0) {\n\t\tlogrus.Debugf(\"[zfs] no zfs dataset found for rootdir '%s'\", mountPath)\n\t\treturn false, ErrPrerequisites\n\t}\n\n\treturn true, nil\n}\n\nfunc GetFSMagic(rootpath string) (FsMagic, error) ", "output": "{\n\treturn 0, nil\n}"} {"input": "package alicloud\n\ntype PrimaryKeyTypeString string\n\nconst (\n\tIntegerType = PrimaryKeyTypeString(\"Integer\")\n\tStringType = PrimaryKeyTypeString(\"String\")\n\tBinaryType = PrimaryKeyTypeString(\"Binary\")\n)\n\ntype InstanceAccessedByType string\n\nconst (\n\tAnyNetwork = InstanceAccessedByType(\"Any\")\n\tVpcOnly = InstanceAccessedByType(\"Vpc\")\n\tVpcOrConsole = InstanceAccessedByType(\"ConsoleOrVpc\")\n)\n\ntype OtsInstanceType string\n\nconst (\n\tOtsCapacity = OtsInstanceType(\"Capacity\")\n\tOtsHighPerformance = OtsInstanceType(\"HighPerformance\")\n)\n\n\n\nfunc convertInstanceAccessedByRevert(network string) InstanceAccessedByType {\n\tswitch network {\n\tcase \"VPC\":\n\t\treturn VpcOnly\n\tcase \"VPC_CONSOLE\":\n\t\treturn VpcOrConsole\n\tdefault:\n\t\treturn AnyNetwork\n\t}\n}\n\nfunc convertInstanceType(instanceType OtsInstanceType) string {\n\tswitch instanceType {\n\tcase OtsHighPerformance:\n\t\treturn \"SSD\"\n\tdefault:\n\t\treturn \"HYBRID\"\n\t}\n}\n\nfunc convertInstanceTypeRevert(instanceType string) OtsInstanceType {\n\tswitch instanceType {\n\tcase \"SSD\":\n\t\treturn OtsHighPerformance\n\tdefault:\n\t\treturn OtsCapacity\n\t}\n}\n\n\nfunc convertOtsInstanceStatus(status Status) int {\n\tswitch status {\n\tcase Running:\n\t\treturn 1\n\tcase DisabledStatus:\n\t\treturn 2\n\tcase Deleting:\n\t\treturn 3\n\tdefault:\n\t\treturn -1\n\t}\n}\n\nfunc convertInstanceAccessedBy(accessed InstanceAccessedByType) string ", "output": "{\n\tswitch accessed {\n\tcase VpcOnly:\n\t\treturn \"VPC\"\n\tcase VpcOrConsole:\n\t\treturn \"VPC_CONSOLE\"\n\tdefault:\n\t\treturn \"NORMAL\"\n\t}\n}"} {"input": "package elasticsearch\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/luopengift/gohttp\"\n)\n\nconst (\n\tenter = '\\n'\n)\n\ntype Meta struct {\n\tIndex string `json:\"_index\"`\n\tType string `json:\"_type\"`\n\tId string `json:\"_id,omitempty\"`\n}\n\nfunc NewMeta(_index, _type, _id string) *Meta {\n\treturn &Meta{_index, _type, _id}\n}\n\ntype Bulk struct {\n\tIndex *Meta `json:\"index,omitempty\"`\n\tUpdate *Meta `json:\"update,omitempty\"`\n\tSource []byte `json:\"-\"`\n}\n\nfunc NewBulkIndex(_index, _type, _id string, source []byte) *Bulk {\n\treturn &Bulk{\n\t\tIndex: NewMeta(_index, _type, _id),\n\t\tSource: source,\n\t}\n}\nfunc NewBulkUpdate(_index, _type, _id string, source []byte) *Bulk {\n\treturn &Bulk{\n\t\tUpdate: NewMeta(_index, _type, _id),\n\t\tSource: source,\n\t}\n}\n\n\n\n\nfunc Send(addr string, p []byte) error {\n\tresp, err := gohttp.NewClient().URLString(\"http://\"+addr).Path(\"/_bulk\").Header(\"Accept\", \"application/json\").Body(p).Post()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.Code() != 200 {\n\t\treturn fmt.Errorf(resp.String())\n\t}\n\treturn nil\n\n}\n\nfunc (b *Bulk) Bytes() ([]byte, error) ", "output": "{\n\tp, err := json.Marshal(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp = append(p, enter)\n\tp = append(p, b.Source...)\n\tp = append(p, enter)\n\treturn p, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\ntype compilerInvocation struct {\n\tcommand string\n\tincludeDirArg string\n\targs []string\n}\n\nfunc (i compilerInvocation) String() string { return strings.Join(i.args, \" \") }\nfunc (i compilerInvocation) ToStringSlice() []string { return []string(i.args) }\n\nfunc (i *compilerInvocation) AppendCCFlags(flags ccflags) *compilerInvocation {\n\ti.args = append(i.args, flags...)\n\treturn i\n}\n\nfunc (i *compilerInvocation) Append(fl ...string) *compilerInvocation {\n\ti.args = append(i.args, fl...)\n\treturn i\n}\n\nfunc (i *compilerInvocation) AddIncludeDir(dir ...string) *compilerInvocation {\n\tfor _, d := range dir {\n\t\ti.args = append(i.args, i.includeDirArg, filepath.FromSlash(d))\n\t}\n\treturn i\n}\n\nfunc (i *compilerInvocation) AddDefaultIncludeDirs() *compilerInvocation {\n\tfor _, d := range defaultIncludeDirs {\n\t\ti.AddIncludeDir(filepath.Join(srcDir, d))\n\t}\n\treturn i\n}\n\nfunc (i *compilerInvocation) AddSources(s ...sources) *compilerInvocation {\n\tfor _, sl := range s {\n\t\ti.Append(sl.ToStringSlice()...)\n\t}\n\treturn i\n}\n\n\n\nfunc run(comp *compilerInvocation, wd string, opts *compileOptions) error ", "output": "{\n\tif !opts.Quiet {\n\t\tfmt.Printf(\"command: %s %s\\n\", comp.command, comp.args)\n\t}\n\n\tcmd := exec.Command(comp.command, comp.ToStringSlice()...)\n\tdir, err := filepath.Abs(wd)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to get absolute path. err=%v\", err)\n\t}\n\tcmd.Dir = dir\n\tcmd.Stdin = os.Stdin\n\n\tswitch {\n\tcase opts.Quiet && opts.Stdout == nil && opts.Stderr == nil:\n\t\tcmd.Stdout = nil\n\t\tcmd.Stderr = nil\n\n\tcase opts.Stdout != nil:\n\t\tcmd.Stdout = opts.Stdout\n\n\tcase opts.Stderr != nil:\n\t\tcmd.Stderr = opts.Stderr\n\n\tdefault:\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t}\n\n\treturn cmd.Run()\n}"} {"input": "package v1alpha1\n\n\n\n\n\n\n\n\n\n\n\n\nvar map_CertificateSigningRequest = map[string]string{\n\t\"\": \"Describes a certificate signing request\",\n\t\"spec\": \"The certificate request itself and any additional information.\",\n\t\"status\": \"Derived information about the request.\",\n}\n\nfunc (CertificateSigningRequest) SwaggerDoc() map[string]string {\n\treturn map_CertificateSigningRequest\n}\n\nvar map_CertificateSigningRequestCondition = map[string]string{\n\t\"type\": \"request approval state, currently Approved or Denied.\",\n\t\"reason\": \"brief reason for the request state\",\n\t\"message\": \"human readable message with details about the request state\",\n\t\"lastUpdateTime\": \"timestamp for the last update to this condition\",\n}\n\nfunc (CertificateSigningRequestCondition) SwaggerDoc() map[string]string {\n\treturn map_CertificateSigningRequestCondition\n}\n\nvar map_CertificateSigningRequestSpec = map[string]string{\n\t\"\": \"This information is immutable after the request is created. Only the Request and ExtraInfo fields can be set on creation, other fields are derived by Kubernetes and cannot be modified by users.\",\n\t\"request\": \"Base64-encoded PKCS#10 CSR data\",\n\t\"usages\": \"allowedUsages specifies a set of usage contexts the key will be valid for. See: https:tools.ietf.org/html/rfc5280#section-4.2.1.3\\n https:tools.ietf.org/html/rfc5280#section-4.2.1.12\",\n\t\"username\": \"Information about the requesting user (if relevant) See user.Info interface for details\",\n}\n\nfunc (CertificateSigningRequestSpec) SwaggerDoc() map[string]string {\n\treturn map_CertificateSigningRequestSpec\n}\n\nvar map_CertificateSigningRequestStatus = map[string]string{\n\t\"conditions\": \"Conditions applied to the request, such as approval or denial.\",\n\t\"certificate\": \"If request was approved, the controller will place the issued certificate here.\",\n}\n\n\n\nfunc (CertificateSigningRequestStatus) SwaggerDoc() map[string]string ", "output": "{\n\treturn map_CertificateSigningRequestStatus\n}"} {"input": "package vfs\n\nimport (\n\t\"path\"\n\n\tgofig \"github.com/akutz/gofig/types\"\n\n\t\"github.com/codedellemc/rexray/libstorage/api/context\"\n\t\"github.com/codedellemc/rexray/libstorage/api/registry\"\n\t\"github.com/codedellemc/rexray/libstorage/api/types\"\n)\n\nconst (\n\tName = \"vfs\"\n)\n\nfunc init() {\n\tregistry.RegisterConfigReg(\n\t\t\"VFS\",\n\t\tfunc(ctx types.Context, r gofig.ConfigRegistration) {\n\t\t\tvfsRoot := path.Join(context.MustPathConfig(ctx).Lib, \"vfs\")\n\t\t\tr.Key(\n\t\t\t\tgofig.String,\n\t\t\t\t\"\",\n\t\t\t\tvfsRoot,\n\t\t\t\t\"\",\n\t\t\t\t\"vfs.root\")\n\t\t})\n}\n\n\nfunc RootDir(config gofig.Config) string {\n\treturn config.GetString(\"vfs.root\")\n}\n\n\nfunc DeviceFilePath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"dev\")\n}\n\n\nfunc VolumesDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"vol\")\n}\n\n\n\n\nfunc SnapshotsDirPath(config gofig.Config) string ", "output": "{\n\treturn path.Join(RootDir(config), \"snap\")\n}"} {"input": "package flags\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\n\n\ntype IniError struct {\n\tMessage string\n\n\tFile string\n\n\tLineNumber uint\n}\n\n\nfunc (x *IniError) Error() string {\n\treturn fmt.Sprintf(\"%s:%d: %s\",\n\t\tx.File,\n\t\tx.LineNumber,\n\t\tx.Message)\n}\n\n\ntype IniOptions uint\n\nconst (\n\tIniNone IniOptions = 0\n\n\tIniIncludeDefaults = 1 << iota\n\n\tIniCommentDefaults\n\n\tIniIncludeComments\n\n\tIniDefault = IniIncludeComments\n)\n\n\n\ntype IniParser struct {\n\tparser *Parser\n}\n\n\nfunc NewIniParser(p *Parser) *IniParser {\n\treturn &IniParser{\n\t\tparser: p,\n\t}\n}\n\n\n\n\n\nfunc IniParse(filename string, data interface{}) error {\n\tp := NewParser(data, Default)\n\treturn NewIniParser(p).ParseFile(filename)\n}\n\n\n\n\nfunc (i *IniParser) ParseFile(filename string) error {\n\ti.parser.storeDefaults()\n\n\tini, err := readIniFromFile(filename)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn i.parse(ini)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (i *IniParser) Parse(reader io.Reader) error {\n\ti.parser.storeDefaults()\n\n\tini, err := readIni(reader, \"\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn i.parse(ini)\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (i *IniParser) Write(writer io.Writer, options IniOptions) {\n\twriteIni(i, writer, options)\n}\n\nfunc (i *IniParser) WriteFile(filename string, options IniOptions) error ", "output": "{\n\tfile, err := os.Create(filename)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer file.Close()\n\ti.Write(file, options)\n\n\treturn nil\n}"} {"input": "package url2\n\nimport (\n\t\"net/url\"\n\t\"testing\"\n\n\t\"github.com/cosiner/gohper/testing2\"\n)\n\n\n\nfunc TestParamString(t *testing.T) {\n\ttt := testing2.Wrap(t)\n\ttt.Eq(Param(1), \"1\")\n\ttt.Eq(Param(\"ddd\"), \"ddd\")\n\ttt.Eq(Param([]int{1, 2, 3}), \"1,2,3\")\n\ttt.Eq(Param([]string{\"1\", \"2\", \"3\"}), \"1,2,3\")\n\ttt.Eq(Param([]byte(\"ddd\")), \"ddd\")\n\n\tdefer tt.Recover()\n\n\tParam(int64(2))\n}\n\nfunc TestQueryEscape(t *testing.T) ", "output": "{\n\ttt := testing2.Wrap(t)\n\tqs := map[string]string{\n\t\t\"A\": \"DD\",\n\t\t\"Z\": \"DD\",\n\t}\n\tq, _ := QueryEscape(qs, nil)\n\ts := string(q)\n\ttt.NE(url.QueryEscape(\"A=DD&Z=DD\") == s, url.QueryEscape(\"Z=DD&A=DD\") == s)\n}"} {"input": "package structs\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nconst (\n\tDefaultUnpriviledgedUser = \"nobody\"\n\n\tCheckBufSize = 4 * 1024\n)\n\n\ntype WaitResult struct {\n\tExitCode int\n\tSignal int\n\tErr error\n}\n\n\n\nfunc (r *WaitResult) Successful() bool {\n\treturn r.ExitCode == 0 && r.Signal == 0 && r.Err == nil\n}\n\nfunc (r *WaitResult) String() string {\n\treturn fmt.Sprintf(\"Wait returned exit code %v, signal %v, and error %v\",\n\t\tr.ExitCode, r.Signal, r.Err)\n}\n\n\n\ntype RecoverableError struct {\n\tErr error\n\tRecoverable bool\n}\n\n\n\nfunc NewRecoverableError(e error, recoverable bool) *RecoverableError {\n\treturn &RecoverableError{\n\t\tErr: e,\n\t\tRecoverable: recoverable,\n\t}\n}\n\nfunc (r *RecoverableError) Error() string {\n\treturn r.Err.Error()\n}\n\n\ntype CheckResult struct {\n\n\tExitCode int\n\n\tOutput string\n\n\tTimestamp time.Time\n\n\tDuration time.Duration\n\n\tErr error\n}\n\nfunc NewWaitResult(code, signal int, err error) *WaitResult ", "output": "{\n\treturn &WaitResult{\n\t\tExitCode: code,\n\t\tSignal: signal,\n\t\tErr: err,\n\t}\n}"} {"input": "package MySQLProtocol\n\nimport \"testing\"\nimport \"github.com/stretchr/testify/assert\"\n\nvar COM_STMT_FETCH_test_packets = []struct {\n\tpacket Proto\n\tcontext Context\n}{\n\t{packet: Proto{data: StringToPacket(`\n09 00 00 00 1c 00 00 00 00 00 00 00 00\n`)}, context: Context{}},\n}\n\nfunc Test_Packet_COM_STMT_FETCH(t *testing.T) {\n\tvar pkt Packet_COM_STMT_FETCH\n\tfor _, value := range COM_STMT_FETCH_test_packets {\n\t\tpkt = Packet_COM_STMT_FETCH{}\n\t\tpkt.FromPacket(value.context, value.packet)\n\t\tassert.Equal(t, pkt.ToPacket(value.context), value.packet.data, \"\")\n\t}\n}\n\nfunc Benchmark_Packet_COM_STMT_FETCH_FromPacket(b *testing.B) {\n\tcontext := COM_STMT_FETCH_test_packets[0].context\n\tpacket := COM_STMT_FETCH_test_packets[0].packet\n\tpkt := Packet_COM_STMT_FETCH{}\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tpacket.offset = 0\n\t\tpkt.FromPacket(context, packet)\n\t}\n}\n\nfunc Benchmark_Packet_COM_STMT_FETCH_GetPacketSize(b *testing.B) {\n\tcontext := COM_STMT_FETCH_test_packets[0].context\n\tpkt := Packet_COM_STMT_FETCH{}\n\tpkt.FromPacket(context, COM_STMT_FETCH_test_packets[0].packet)\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt.GetPacketSize(context)\n\t}\n}\n\n\n\nfunc Benchmark_Packet_COM_STMT_FETCH_ToPacket(b *testing.B) ", "output": "{\n\tcontext := COM_STMT_FETCH_test_packets[0].context\n\tpkt := Packet_COM_STMT_FETCH{}\n\tpkt.FromPacket(context, COM_STMT_FETCH_test_packets[0].packet)\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt.ToPacket(context)\n\t}\n}"} {"input": "package sourcemap\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype vlqTest struct {\n\tencoded string\n\tdecoded []int\n\tskipEncodeTest bool\n}\n\nvar vlqTests = []vlqTest{\n\tvlqTest{\"A\", []int{0}, false},\n\tvlqTest{\"B\", []int{0}, true}, \n\tvlqTest{\"C\", []int{1}, false},\n\tvlqTest{\"f\", []int{-15}, false},\n\n\tvlqTest{\"gA\", []int{0}, true}, \n\tvlqTest{\"gB\", []int{16}, false},\n\tvlqTest{\"RgB\", []int{-8, 16}, false},\n\tvlqTest{\"EAEE\", []int{2, 0, 2, 2}, false},\n\tvlqTest{\"OAAQ\", []int{7, 0, 0, 8}, false},\n\tvlqTest{\"AAgBC\", []int{0, 0, 16, 1}, false},\n\tvlqTest{\"SACjBD\", []int{9, 0, 1, -17, -1}, false},\n\tvlqTest{\"kBAAhBA\", []int{18, 0, 0, -16, 0}, false},\n\tvlqTest{\"EAEEga\", []int{2, 0, 2, 2, 416}, false},\n}\n\n\n\nfunc TestVLQ(t *testing.T) ", "output": "{\n\tfor _, test := range vlqTests {\n\t\tvalues, ok := vlqDecode(test.encoded)\n\t\tif !assert.True(t, ok, \"Expected proper decode for %s\", test.encoded) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !assert.Equal(t, test.decoded, values, \"Decode mismatch for %s\", test.encoded) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif test.skipEncodeTest {\n\t\t\tcontinue\n\t\t}\n\n\t\tencoded := vlqEncode(test.decoded)\n\n\t\tif !assert.Equal(t, test.encoded, encoded, \"Encode mismatch for %s\", test.encoded) {\n\t\t\tcontinue\n\t\t}\n\t}\n}"} {"input": "package events\n\nimport \"encoding/json\"\n\n\ntype User struct {\n\tUser string `json:\"user\"`\n\tName string `json:\"name\"`\n}\n\n\ntype Nick struct {\n\tNick string `json:\"nick\"`\n}\n\n\ntype Quit struct {\n\tType string `json:\"type\"`\n\tStatus string `json:\"status\"`\n\tUser string `json:\"user\"`\n\tMsg string `json:\"msg\"`\n}\n\n\nfunc Connected(server, msg string) string {\n\tevent, err := json.Marshal(StatusTargetMsgEvent{Type: \"connected\",\n\t\tStatus: \"ok\",\n\t\tTarget: server,\n\t\tMsg: msg,\n\t})\n\n\tif err != nil {\n\t\treturn InternalError(err.Error())\n\t}\n\n\treturn string(event)\n}\n\n\n\n\nfunc RcvedQuit(user, msg string) string ", "output": "{\n\tevent, err := json.Marshal(Quit{Type: \"quit\",\n\t\tStatus: \"ok\",\n\t\tUser: user,\n\t\tMsg: msg,\n\t})\n\n\tif err != nil {\n\t\treturn InternalError(err.Error())\n\t}\n\n\treturn string(event)\n}"} {"input": "package reuseport\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"syscall\"\n\n\t\"github.com/inverse-inc/packetfence/go/coredns/plugin/pkg/log\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\n\n\nfunc Listen(network, addr string) (net.Listener, error) {\n\tlc := net.ListenConfig{Control: control}\n\treturn lc.Listen(context.Background(), network, addr)\n}\n\n\n\nfunc ListenPacket(network, addr string) (net.PacketConn, error) {\n\tlc := net.ListenConfig{Control: control}\n\treturn lc.ListenPacket(context.Background(), network, addr)\n}\n\nfunc control(network, address string, c syscall.RawConn) error ", "output": "{\n\tc.Control(func(fd uintptr) {\n\t\tif err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil {\n\t\t\tlog.Warningf(\"Failed to set SO_REUSEPORT on socket: %s\", err)\n\t\t}\n\t})\n\treturn nil\n}"} {"input": "package naming\n\nimport (\n\t\"github.com/snapcore/snapd/snapdenv\"\n)\n\nvar (\n\tprodWellKnownSnapIDs = map[string]string{\n\t\t\"core\": \"99T7MUlRhtI3U0QFgl5mXXESAiSwt776\",\n\t\t\"snapd\": \"PMrrV4ml8uWuEUDBT8dSGnKUYbevVhc4\",\n\t\t\"core18\": \"CSO04Jhav2yK0uz97cr0ipQRyqg0qQL6\",\n\t\t\"core20\": \"DLqre5XGLbDqg9jPtiAhRRjDuPVa5X1q\",\n\t}\n\n\tstagingWellKnownSnapIDs = map[string]string{\n\t\t\"core\": \"xMNMpEm0COPZy7jq9YRwWVLCD9q5peow\",\n\t\t\"snapd\": \"Z44rtQD1v4r1LXGPCDZAJO3AOw1EDGqy\",\n\t\t\"core18\": \"NhSvwckvNdvgdiVGlsO1vYmi3FPdTZ9U\",\n\t\t\"core20\": \"\",\n\t}\n)\n\nvar wellKnownSnapIDs = prodWellKnownSnapIDs\n\nfunc init() {\n\tif snapdenv.UseStagingStore() {\n\t\twellKnownSnapIDs = stagingWellKnownSnapIDs\n\t}\n}\n\n\n\n\n\nfunc UseStagingIDs(staging bool) (restore func()) {\n\told := wellKnownSnapIDs\n\tif staging {\n\t\twellKnownSnapIDs = stagingWellKnownSnapIDs\n\t} else {\n\t\twellKnownSnapIDs = prodWellKnownSnapIDs\n\t}\n\treturn func() {\n\t\twellKnownSnapIDs = old\n\t}\n}\n\nfunc WellKnownSnapID(snapName string) string ", "output": "{\n\treturn wellKnownSnapIDs[snapName]\n}"} {"input": "package sortedmap\n\nimport (\n\t\"testing\"\n\n\t\"github.com/umpc/go-sortedmap/asc\"\n)\n\nfunc insertRecord(b *testing.B) {\n\trecords := randRecords(1)\n\tsm := New(0, asc.Time)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsm.Insert(records[0].Key, records[0].Val)\n\n\t\tb.StopTimer()\n\t\trecords = randRecords(1)\n\t\tsm = New(0, asc.Time)\n\t\tb.StartTimer()\n\t}\n}\n\nfunc batchInsertRecords(b *testing.B, n int) {\n\trecords := randRecords(n)\n\tsm := New(0, asc.Time)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsm.BatchInsert(records)\n\n\t\tb.StopTimer()\n\t\trecords = randRecords(n)\n\t\tsm = New(0, asc.Time)\n\t\tb.StartTimer()\n\t}\n}\n\nfunc BenchmarkInsert1Record(b *testing.B) {\n\tinsertRecord(b)\n}\n\nfunc BenchmarkBatchInsert10Records(b *testing.B) {\n\tbatchInsertRecords(b, 10)\n}\n\nfunc BenchmarkBatchInsert100Records(b *testing.B) {\n\tbatchInsertRecords(b, 100)\n}\n\n\n\nfunc BenchmarkBatchInsert10000Records(b *testing.B) {\n\tbatchInsertRecords(b, 10000)\n}\n\nfunc BenchmarkBatchInsert1000Records(b *testing.B) ", "output": "{\n\tbatchInsertRecords(b, 1000)\n}"} {"input": "package network\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n)\n\nconst (\n\tresolverFileName = \"/etc/resolv.conf\"\n\tclusterDomainEnvKey = \"CLUSTER_DOMAIN\"\n\tdefaultDomainName = \"cluster.local\"\n)\n\nvar (\n\tdomainName = defaultDomainName\n\tonce sync.Once\n)\n\n\nfunc GetServiceHostname(name, namespace string) string {\n\treturn fmt.Sprintf(\"%s.%s.svc.%s\", name, namespace, GetClusterDomainName())\n}\n\n\n\n\n\nfunc getClusterDomainName(r io.Reader) string {\n\tfor scanner := bufio.NewScanner(r); scanner.Scan(); {\n\t\telements := strings.Split(scanner.Text(), \" \")\n\t\tif elements[0] != \"search\" {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, e := range elements[1:] {\n\t\t\tif strings.HasPrefix(e, \"svc.\") {\n\t\t\t\treturn strings.TrimSuffix(e[4:], \".\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif domain := os.Getenv(clusterDomainEnvKey); len(domain) > 0 {\n\t\treturn domain\n\t}\n\n\treturn defaultDomainName\n}\n\nfunc GetClusterDomainName() string ", "output": "{\n\tonce.Do(func() {\n\t\tf, err := os.Open(resolverFileName)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tdefer f.Close()\n\t\tdomainName = getClusterDomainName(f)\n\t})\n\treturn domainName\n}"} {"input": "package inmem\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\tplatform \"github.com/influxdata/influxdb\"\n\tplatformtesting \"github.com/influxdata/influxdb/testing\"\n)\n\nfunc initTelegrafStore(f platformtesting.TelegrafConfigFields, t *testing.T) (platform.TelegrafConfigStore, func()) {\n\ts := NewService()\n\ts.IDGenerator = f.IDGenerator\n\tctx := context.Background()\n\tfor _, m := range f.UserResourceMappings {\n\t\tif err := s.PutUserResourceMapping(ctx, m); err != nil {\n\t\t\tt.Fatalf(\"failed to populate user resource mapping\")\n\t\t}\n\t}\n\tfor _, tc := range f.TelegrafConfigs {\n\t\tif err := s.putTelegrafConfig(ctx, tc); err != nil {\n\t\t\tt.Fatalf(\"failed to populate telegraf configs\")\n\t\t}\n\t}\n\treturn s, func() {}\n}\n\n\n\nfunc TestTelegrafStore(t *testing.T) ", "output": "{\n\tplatformtesting.TelegrafConfigStore(initTelegrafStore, t)\n}"} {"input": "package proxyprotocol\n\nimport (\n\t\"net\"\n)\n\ntype listener struct {\n\traw net.Listener\n}\n\nfunc Listen(raw net.Listener) net.Listener {\n\treturn &listener{raw}\n}\n\n\n\nfunc (l *listener) Close() error {\n\treturn l.raw.Close()\n}\n\nfunc (l *listener) Addr() net.Addr {\n\treturn l.raw.Addr()\n}\n\nfunc (l *listener) Accept() (c net.Conn, err error) ", "output": "{\n\traw, err := l.raw.Accept()\n\tif err == nil {\n\t\tc = &conn{\n\t\t\traw: raw,\n\t\t}\n\t}\n\treturn\n}"} {"input": "package informers\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/docker/compose-on-kubernetes/api/compose/v1alpha3\"\n\t\"github.com/docker/compose-on-kubernetes/api/compose/v1beta2\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}\n\n\n\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {\n\tswitch resource {\n\tcase v1beta2.SchemeGroupVersion.WithResource(\"stacks\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Compose().V1beta2().Stacks().Informer()}, nil\n\tcase v1alpha3.SchemeGroupVersion.WithResource(\"stacks\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Compose().V1alpha3().Stacks().Informer()}, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}\n\nfunc (f *genericInformer) Lister() cache.GenericLister ", "output": "{\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}"} {"input": "package btree\n\n\n\n\n\nimport (\n\t\"github.com/tinylib/msgp/msgp\"\n)\n\n\n\n\n\nfunc (z *Tr) UnmarshalMsg(bts []byte) (o []byte, err error) {\n\tvar field []byte\n\t_ = field\n\tvar isz uint32\n\tisz, bts, err = msgp.ReadMapHeaderBytes(bts)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor isz > 0 {\n\t\tisz--\n\t\tfield, bts, err = msgp.ReadMapKeyZC(bts)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tswitch msgp.UnsafeString(field) {\n\t\tcase \"u\":\n\t\t\tbts, err = z.UUID.UnmarshalMsg(bts)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase \"c\":\n\t\t\tz.Count, bts, err = msgp.ReadIntBytes(bts)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase \"r\":\n\t\t\tbts, err = z.Root.UnmarshalMsg(bts)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase \"nw\":\n\t\t\tz.NodeWidth, bts, err = msgp.ReadIntBytes(bts)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tdefault:\n\t\t\tbts, err = msgp.Skip(bts)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\to = bts\n\treturn\n}\n\nfunc (z *Tr) Msgsize() (s int) {\n\ts = 1 + 2 + z.UUID.Msgsize() + 2 + msgp.IntSize + 2 + z.Root.Msgsize() + 3 + msgp.IntSize\n\treturn\n}\n\nfunc (z *Tr) MarshalMsg(b []byte) (o []byte, err error) ", "output": "{\n\to = msgp.Require(b, z.Msgsize())\n\to = append(o, 0x84, 0xa1, 0x75)\n\to, err = z.UUID.MarshalMsg(o)\n\tif err != nil {\n\t\treturn\n\t}\n\to = append(o, 0xa1, 0x63)\n\to = msgp.AppendInt(o, z.Count)\n\to = append(o, 0xa1, 0x72)\n\to, err = z.Root.MarshalMsg(o)\n\tif err != nil {\n\t\treturn\n\t}\n\to = append(o, 0xa2, 0x6e, 0x77)\n\to = msgp.AppendInt(o, z.NodeWidth)\n\treturn\n}"} {"input": "package storagedatalake\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultDNSSuffix = \"dfs.core.windows.net\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tXMsVersion string\n\tAccountName string\n\tDNSSuffix string\n}\n\n\nfunc New(xMsVersion string, accountName string) BaseClient {\n\treturn NewWithoutDefaults(xMsVersion, accountName, DefaultDNSSuffix)\n}\n\n\n\n\nfunc NewWithoutDefaults(xMsVersion string, accountName string, dNSSuffix string) BaseClient ", "output": "{\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tXMsVersion: xMsVersion,\n\t\tAccountName: accountName,\n\t\tDNSSuffix: dNSSuffix,\n\t}\n}"} {"input": "package field\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype Path struct {\n\tname string \n\tindex string \n\tparent *Path \n}\n\n\nfunc NewPath(name string, moreNames ...string) *Path {\n\tr := &Path{name: name, parent: nil}\n\tfor _, anotherName := range moreNames {\n\t\tr = &Path{name: anotherName, parent: r}\n\t}\n\treturn r\n}\n\n\nfunc (p *Path) Root() *Path {\n\tfor ; p.parent != nil; p = p.parent {\n\t}\n\treturn p\n}\n\n\nfunc (p *Path) Child(name string, moreNames ...string) *Path {\n\tr := NewPath(name, moreNames...)\n\tr.Root().parent = p\n\treturn r\n}\n\n\n\nfunc (p *Path) Index(index int) *Path {\n\treturn &Path{index: strconv.Itoa(index), parent: p}\n}\n\n\n\n\n\n\nfunc (p *Path) String() string {\n\tif p == nil {\n\t\treturn \"\"\n\t}\n\telems := []*Path{}\n\tfor ; p != nil; p = p.parent {\n\t\telems = append(elems, p)\n\t}\n\n\tbuf := bytes.NewBuffer(nil)\n\tfor i := range elems {\n\t\tp := elems[len(elems)-1-i]\n\t\tif p.parent != nil && len(p.name) > 0 {\n\t\t\tbuf.WriteString(\".\")\n\t\t}\n\t\tif len(p.name) > 0 {\n\t\t\tbuf.WriteString(p.name)\n\t\t} else {\n\t\t\tfmt.Fprintf(buf, \"[%s]\", p.index)\n\t\t}\n\t}\n\treturn buf.String()\n}\n\nfunc (p *Path) Key(key string) *Path ", "output": "{\n\treturn &Path{index: key, parent: p}\n}"} {"input": "package distribution \n\nimport \"github.com/tiborvass/docker/api/server/router\"\n\n\ntype distributionRouter struct {\n\tbackend Backend\n\troutes []router.Route\n}\n\n\nfunc NewRouter(backend Backend) router.Router {\n\tr := &distributionRouter{\n\t\tbackend: backend,\n\t}\n\tr.initRoutes()\n\treturn r\n}\n\n\n\n\n\nfunc (r *distributionRouter) initRoutes() {\n\tr.routes = []router.Route{\n\t\trouter.NewGetRoute(\"/distribution/{name:.*}/json\", r.getDistributionInfo),\n\t}\n}\n\nfunc (r *distributionRouter) Routes() []router.Route ", "output": "{\n\treturn r.routes\n}"} {"input": "package workshop\n\nimport (\n\t\"math\"\n)\n\n\ntype Shape interface {\n\tarea()\n\tcircumference()\n\tvolume()\n}\n\n\ntype Circle struct {\n\tradius float64\n\tPI float64\n}\n\n\n\nfunc (circle *Circle) circumference() float64 {\n\treturn 2 * circle.PI * circle.radius\n}\n\n\ntype Square struct {\n\tside float64\n}\n\nfunc (square *Square) area() float64 {\n\treturn math.Pow(square.side, 2)\n}\n\ntype Sphere struct {\n\tPI float64\n\tradius float64\n}\n\nfunc (sphere *Sphere) volume() float64 {\n\treturn (4 / 3) * sphere.PI * math.Pow(sphere.radius, 3)\n}\n\n\ntype Cube struct {\n\tside float64\n}\n\nfunc (cube *Cube) volume() float64 {\n\treturn math.Pow(cube.side, 3)\n}\n\nfunc (square *Square) volume() float64 {\n\treturn math.Pow(square.side, 3)\n}\n\n\ntype Rectangle struct {\n\theight int\n\twidth int\n}\n\nfunc (rectangle *Rectangle) area() int {\n\treturn rectangle.height * rectangle.width\n}\n\nfunc interfaces() {\n\tcircle := Circle{radius: 5.5, PI: math.Pi}\n\tareaOfCircle := circle.area()\n\n\tassert(areaOfCircle == 55)\n\tassert(circle.circumference() == 88)\n\n\tvar square = Square{5}\n\tassert(square.area() == 36)\n\n\tcube := new(Cube)\n\tassert(cube.volume() == 8)\n\n\tvar rectangle = Rectangle{width: 4, height: 5}\n\tassert(rectangle.area() == 2)\n}\n\nfunc (circle *Circle) area() float64 ", "output": "{\n\treturn circle.PI * math.Pow(circle.radius, 2)\n}"} {"input": "package cemi\n\n\ntype Priority uint8\n\nconst (\n\tPrioSystem Priority = 0\n\n\tPrioNormal Priority = 1\n\n\tPrioUrgent Priority = 2\n\n\tPrioLow Priority = 3\n)\n\n\ntype ControlField1 uint8\n\nconst (\n\tControl1StdFrame ControlField1 = 1 << 7\n\n\tControl1NoRepeat ControlField1 = 1 << 5\n\n\tControl1NoSysBroadcast ControlField1 = 1 << 4\n\n\tControl1WantAck ControlField1 = 1 << 1\n\n\tControl1HasError ControlField1 = 1\n)\n\n\nfunc Control1Prio(prio Priority) ControlField1 {\n\treturn ControlField1(prio&3) << 2\n}\n\n\ntype ControlField2 uint8\n\n\n\n\n\nfunc (ctrl2 ControlField2) Hops() uint8 {\n\treturn uint8(ctrl2>>7) & 7\n}\n\nconst (\n\tControl2GroupAddr ControlField2 = 1 << 7\n\n\tControl2LTEFrame ControlField2 = 1 << 2\n)\n\n\nfunc Control2Hops(hops uint8) ControlField2 {\n\tif hops > 7 {\n\t\thops = 7\n\t}\n\n\treturn ControlField2(hops&7) << 4\n}\n\nfunc (ctrl2 ControlField2) IsGroupAddr() bool ", "output": "{\n\treturn ctrl2&Control2GroupAddr == Control2GroupAddr\n}"} {"input": "package env\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestEnvGet(t *testing.T) {\n\tgopath := Get(\"GOPATH\", \"\")\n\tif gopath != os.Getenv(\"GOPATH\") {\n\t\tt.Error(\"expected GOPATH not empty.\")\n\t}\n\n\tnoExistVar := Get(\"NOEXISTVAR\", \"foo\")\n\tif noExistVar != \"foo\" {\n\t\tt.Errorf(\"expected NOEXISTVAR to equal foo, got %s.\", noExistVar)\n\t}\n}\n\nfunc TestEnvMustGet(t *testing.T) {\n\tgopath, err := MustGet(\"GOPATH\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif gopath != os.Getenv(\"GOPATH\") {\n\t\tt.Errorf(\"expected GOPATH to be the same, got %s.\", gopath)\n\t}\n\n\t_, err = MustGet(\"NOEXISTVAR\")\n\tif err == nil {\n\t\tt.Error(\"expected error to be non-nil\")\n\t}\n}\n\n\n\nfunc TestEnvMustSet(t *testing.T) {\n\terr := MustSet(\"FOO\", \"bar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tfooVar := os.Getenv(\"FOO\")\n\tif fooVar != \"bar\" {\n\t\tt.Errorf(\"expected FOO variable to equal bar, got %s.\", fooVar)\n\t}\n}\n\nfunc TestEnvGetAll(t *testing.T) {\n\tenvMap := GetAll()\n\tif len(envMap) == 0 {\n\t\tt.Error(\"expected environment not empty.\")\n\t}\n}\n\nfunc TestEnvSet(t *testing.T) ", "output": "{\n\tSet(\"MYVAR\", \"foo\")\n\tmyVar := Get(\"MYVAR\", \"bar\")\n\tif myVar != \"foo\" {\n\t\tt.Errorf(\"expected MYVAR to equal foo, got %s.\", myVar)\n\t}\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"k8s.io/client-go/kubernetes/typed/extensions/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeExtensionsV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeExtensionsV1beta1) DaemonSets(namespace string) v1beta1.DaemonSetInterface {\n\treturn &FakeDaemonSets{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) Deployments(namespace string) v1beta1.DeploymentInterface {\n\treturn &FakeDeployments{c, namespace}\n}\n\n\n\nfunc (c *FakeExtensionsV1beta1) PodSecurityPolicies() v1beta1.PodSecurityPolicyInterface {\n\treturn &FakePodSecurityPolicies{c}\n}\n\nfunc (c *FakeExtensionsV1beta1) ReplicaSets(namespace string) v1beta1.ReplicaSetInterface {\n\treturn &FakeReplicaSets{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) Scales(namespace string) v1beta1.ScaleInterface {\n\treturn &FakeScales{c, namespace}\n}\n\n\n\nfunc (c *FakeExtensionsV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeExtensionsV1beta1) Ingresses(namespace string) v1beta1.IngressInterface ", "output": "{\n\treturn &FakeIngresses{c, namespace}\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tutils \"github.com/trackit/trackit/aws/usageReports\"\n)\n\nconst urlFormat = \"https:console.aws.amazon.com/cloudformation/home?region=%s#/stacks/stackinfo?stackId=%s\"\nconst stackId = \"aws:cloudformation:stack-id\"\n\n\n\n\ntype TaggingReportDocument struct {\n\tAccount string `json:\"account\"`\n\tReportDate time.Time `json:\"reportDate\"`\n\tResourceID string `json:\"resourceId\"`\n\tResourceType string `json:\"resourceType\"`\n\tRegion string `json:\"region\"`\n\tURL string `json:\"url\"`\n\tTags []utils.Tag `json:\"tags\"`\n\tCloudFormationURL string `json:\"cloudFormationUrl,omitempty\"`\n}\n\nfunc (doc *TaggingReportDocument) GenCloudFormationUrl() ", "output": "{\n\tfor _, tag := range doc.Tags {\n\t\tif tag.Key == stackId && tag.Value != \"\" {\n\t\t\tdoc.CloudFormationURL = fmt.Sprintf(urlFormat, doc.Region, tag.Value)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\n\t\"gopkg.in/pivo.v2/ws\"\n)\n\nconst websocketChatUri = `/`\n\ntype websocket struct {\n\tconn *ws.Conn\n}\n\nfunc (ws *websocket) OnClose(why error) error {\n\tchat.hub.Leave(ws.conn)\n\treturn nil\n}\n\nfunc (ws *websocket) OnBinaryRead(data []byte) error {\n\treturn ErrProtocolViolation\n}\n\nfunc (ws *websocket) OnTextRead(text string) error {\n\tchat.pub <- ws.conn.TextMessage(formatMessage(ws.conn, text))\n\treturn nil\n}\n\n\n\nfunc init() {\n\thttp.Handle(websocketChatUri, chat)\n}\n\nfunc (chat *Hub) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tconn := ws.DefaultConn()\n\tif err := conn.Upgrade(w, r, nil); err != nil {\n\t\tlog.Printf(\"websocket: %s: failed to upgrade: %s\",\n\t\t\tr.RemoteAddr, err)\n\t\treturn\n\t}\n\tgo conn.Sender()\n\tgo conn.Receiver(&websocket{conn})\n\tchat.sub <- conn\n}"} {"input": "package tracepkts\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n)\n\nconst (\n\tATOM_N = 0\n\tATOM_E = 1\n)\n\ntype AtomFmt1ETMv4 struct {\n\t*GenericTracePacketv4\n\ttaken bool\n}\n\n\n\nfunc (pkt AtomFmt1ETMv4) String() string {\n\ttaken := \"Taken\"\n\tif pkt.taken == false {\n\t\ttaken = \"Not Taken\"\n\t}\n\treturn fmt.Sprintf(\"Atom Format 1 Branch %s\", taken)\n}\n\nfunc DecodeAtomFmt1(header byte, reader *bufio.Reader) TracePacket ", "output": "{\n\tpkt := AtomFmt1ETMv4{}\n\n\tif header&0x1 == ATOM_N {\n\t\tpkt.taken = false\n\t} else {\n\t\tpkt.taken = true\n\t}\n\n\treturn pkt\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\nvar fP2K = p2K\n\n\n\nfunc TestP2KNegativeValue(t *testing.T) {\n\tresult, err := fP2K(-1)\n\texpected := 0.453592\n\tif err == nil {\n\t\tt.Errorf(\"fP2K not support negative value\")\n\t}\n\tif result != 0 {\n\t\tt.Errorf(\"Result: %v Expected %v\", result, expected)\n\t}\n}\n\nfunc TestP2K(t *testing.T) ", "output": "{\n\tresult, _ := fP2K(1)\n\texpected := 0.453592\n\tif result != expected {\n\t\tt.Errorf(\"Result: %v Expected %v\", result, expected)\n\t}\n}"} {"input": "package undertaker\n\nimport (\n\t\"github.com/juju/errors\"\n\t\"gopkg.in/juju/names.v2\"\n\n\t\"github.com/juju/juju/environs/config\"\n\t\"github.com/juju/juju/state\"\n)\n\n\n\ntype State interface {\n\tstate.EntityFinder\n\n\tModel() (Model, error)\n\n\tIsController() bool\n\n\tProcessDyingModel() (err error)\n\n\tRemoveAllModelDocs() error\n\n\tAllMachines() ([]Machine, error)\n\n\tAllApplications() ([]Service, error)\n\n\tModelConfig() (*config.Config, error)\n}\n\ntype stateShim struct {\n\t*state.State\n}\n\nfunc (s *stateShim) AllMachines() ([]Machine, error) {\n\tstateMachines, err := s.State.AllMachines()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tmachines := make([]Machine, len(stateMachines))\n\tfor i := range stateMachines {\n\t\tmachines[i] = stateMachines[i]\n\t}\n\n\treturn machines, nil\n}\n\n\n\ntype Machine interface {\n\tWatch() state.NotifyWatcher\n}\n\n\n\n\n\ntype Service interface {\n\tWatch() state.NotifyWatcher\n}\n\nfunc (s *stateShim) Model() (Model, error) {\n\treturn s.State.Model()\n}\n\n\n\ntype Model interface {\n\n\tOwner() names.UserTag\n\n\tLife() state.Life\n\n\tName() string\n\n\tUUID() string\n\n\tDestroy() error\n}\n\nfunc (s *stateShim) AllApplications() ([]Service, error) ", "output": "{\n\tstateServices, err := s.State.AllApplications()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tservices := make([]Service, len(stateServices))\n\tfor i := range stateServices {\n\t\tservices[i] = stateServices[i]\n\t}\n\n\treturn services, nil\n}"} {"input": "package rps\n\ntype Values []int64\n\n\n\nfunc (self *Values) Rotate(n int) ", "output": "{\n\tif n > 0 {\n\t\tcapacity := cap(*self)\n\t\tvalues := make([]int64, capacity, capacity)\n\n\t\tif n < capacity {\n\t\t\tcopy(values, (*self)[n:])\n\t\t}\n\n\t\t*self = values\n\t}\n}"} {"input": "package airplane_mode\n\nfunc getRadioModule(key RadioType) BaseRadioModule {\n\tvar module BaseRadioModule\n\tswitch key {\n\tcase BluetoothRadioType:\n\t\tmodule = &BluetoothRadio{GeneralRadioModule{typ: BluetoothRadioType, name: \"bluetooth\"}}\n\tcase WlanRadioType:\n\t\tmodule = &WlanRadio{GeneralRadioModule{typ: WlanRadioType, name: \"wlan\"}}\n\tcase AllRadioType:\n\t\tmodule = &AllRadio{GeneralRadioModule{typ: AllRadioType, name: \"all\"}}\n\tdefault:\n\t\tpanic(\"radio type not exist\")\n\t}\n\treturn module\n}\n\ntype GeneralRadioModule struct {\n\ttyp RadioType\n\tname string\n}\n\nfunc (Op *GeneralRadioModule) Type() RadioType {\n\treturn Op.typ\n}\n\n\n\nfunc (Op *GeneralRadioModule) Len() int {\n\tstate, err := rfkillState(Op.typ)\n\tif err != nil {\n\t\tlogger.Warningf(\"check rfkill blocked state failed, err: %v\", err)\n\t\tstate.count = 0\n\t}\n\treturn state.count\n}\n\nfunc (Op *GeneralRadioModule) Block() error {\n\treturn rfkillAction(Op.typ, BlockRadioAction)\n}\n\nfunc (Op *GeneralRadioModule) Unblock() error {\n\treturn rfkillAction(Op.typ, UnblockRadioAction)\n}\n\nfunc (Op *GeneralRadioModule) IsBlocked() bool {\n\tstate, err := rfkillState(Op.typ)\n\tif err != nil {\n\t\tlogger.Warningf(\"check rfkill blocked state failed, err: %v\", err)\n\t\tstate.blocked = false\n\t}\n\treturn state.blocked\n}\n\n\ntype BluetoothRadio struct {\n\tGeneralRadioModule\n}\n\n\ntype WlanRadio struct {\n\tGeneralRadioModule\n}\n\n\ntype AllRadio struct {\n\tGeneralRadioModule\n}\n\nfunc (Op *GeneralRadioModule) Module() string ", "output": "{\n\treturn Op.name\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\n\n\nfunc (s *CmdTestSuite) TestCatCmd(c *C) ", "output": "{\n\troot, err := ioutil.TempDir(os.TempDir(), \"cmd-\")\n\tc.Assert(err, IsNil)\n\tdefer os.RemoveAll(root)\n\n\tobjectPath := filepath.Join(root, \"object1\")\n\tobjectPathServer := server.URL + \"/bucket/object1\"\n\tdata := \"hello\"\n\tdataLen := len(data)\n\terr = putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data)))\n\tc.Assert(err, IsNil)\n\terr = putTarget(objectPathServer, int64(dataLen), bytes.NewReader([]byte(data)))\n\tc.Assert(err, IsNil)\n\n\tvar sourceURLs []string\n\tsourceURLs = append(sourceURLs, objectPath)\n\tsourceURLs = append(sourceURLs, objectPathServer)\n\tfor _, sourceURL := range sourceURLs {\n\t\t_, err = doCatCmd(sourceURL)\n\t\tc.Assert(err, IsNil)\n\t}\n}"} {"input": "package main\n\nimport \"errors\"\n\n\nfunc nfds() int {\n\treturn 0\n}\n\n\n\n\n\nfunc handleSocketActivation(n int) error ", "output": "{\n\treturn errors.New(\"systemd socket activation is not available on Windows\")\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/polariseye/polarserver/common\"\n\t\"github.com/polariseye/polarserver/common/errorCode\"\n\t\"github.com/polariseye/polarserver/moduleManage\"\n)\n\ntype testStruct struct {\n\tclassName string\n}\n\nvar TestBLL *testStruct\n\nfunc init() {\n\tTestBLL = NewTestStruct()\n\tmoduleManage.RegisterModule(func() (moduleManage.IModule, moduleManage.ModuleType) {\n\t\treturn NewTestStruct(), moduleManage.NormalModule\n\t})\n}\n\n\nfunc (this *testStruct) Name() string {\n\treturn this.className\n}\n\nfunc (this *testStruct) InitModule() []error {\n\tfmt.Println(\"初始化\")\n\n\treturn nil\n}\n\nfunc (this *testStruct) CheckModule() []error {\n\tfmt.Println(\"check\")\n\n\treturn nil\n}\n\nfunc (this *testStruct) ConvertModule() []error {\n\tfmt.Println(\"数据转换\")\n\n\treturn nil\n}\n\n\nfunc (this *testStruct) C_Hello(request *common.RequestModel, d int, name string) *common.ResultModel {\n\tresult := common.NewResultModel(errorCode.ClientDataError)\n\n\tresult.Value[\"Hello\"] = name + \"_\" + this.Name()\n\tresult.Value[\"Extra\"] = d\n\n\tresult.SetNormalError(errorCode.Success)\n\treturn result\n}\n\n\n\nfunc NewTestStruct() *testStruct ", "output": "{\n\treturn &testStruct{\n\t\tclassName: \"TestBLL\",\n\t}\n}"} {"input": "package leetcode\n\n\n\nfunc climbStairs(n int) int ", "output": "{\n\tif n <= 2 {\n\t\treturn n\n\t}\n\tn1, n2 := 1, 2\n\tfor i := 3; i <= n; i++ {\n\t\tn2, n1 = n1+n2, n2\n\t}\n\treturn n2\n}"} {"input": "package jsonhelper\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"io\"\n)\n\n\n\n\n\nfunc MarshalData(w io.Writer, data interface{}) error {\n\te := jsoniter.NewEncoder(w)\n\treturn e.Encode(data)\n}\n\nfunc UnmarshalData(r io.Reader, data interface{}) error ", "output": "{\n\td := jsoniter.NewDecoder(r)\n\treturn d.Decode(data)\n}"} {"input": "package router\n\n\n\n\nimport (\n\t\"github.com/weaveworks/mesh\"\n)\n\n\n\ntype AWSVPCConnection struct {\n\testablishedChan chan struct{}\n\terrorChan chan error\n}\n\nfunc (conn *AWSVPCConnection) Confirm() {\n\tclose(conn.establishedChan)\n}\n\n\n\nfunc (conn *AWSVPCConnection) ErrorChannel() <-chan error {\n\treturn conn.errorChan\n}\n\nfunc (conn *AWSVPCConnection) Stop() {}\n\nfunc (conn *AWSVPCConnection) ControlMessage(tag byte, msg []byte) {\n}\n\nfunc (conn *AWSVPCConnection) DisplayName() string {\n\treturn \"awsvpc\"\n}\n\n\n\nfunc (conn *AWSVPCConnection) Forward(key ForwardPacketKey) FlowOp {\n\treturn DiscardingFlowOp{}\n}\n\ntype AWSVPC struct{}\n\nfunc NewAWSVPC() AWSVPC {\n\treturn AWSVPC{}\n}\n\n\n\nfunc (vpc AWSVPC) AddFeaturesTo(features map[string]string) {}\n\nfunc (vpc AWSVPC) PrepareConnection(params mesh.OverlayConnectionParams) (mesh.OverlayConnection, error) {\n\tconn := &AWSVPCConnection{\n\t\testablishedChan: make(chan struct{}),\n\t\terrorChan: make(chan error, 1),\n\t}\n\treturn conn, nil\n}\n\nfunc (vpc AWSVPC) Diagnostics() interface{} {\n\treturn nil\n}\n\n\n\nfunc (vpc AWSVPC) InvalidateRoutes() {}\n\nfunc (vpc AWSVPC) InvalidateShortIDs() {}\n\nfunc (vpc AWSVPC) StartConsumingPackets(localPeer *mesh.Peer, peers *mesh.Peers, consumer OverlayConsumer) error {\n\treturn nil\n}\n\nfunc (conn *AWSVPCConnection) EstablishedChannel() <-chan struct{} ", "output": "{\n\treturn conn.establishedChan\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\ntype MockConn struct {\n\tServerReader *io.PipeReader\n\tServerWriter *io.PipeWriter\n\tClientReader *io.PipeReader\n\tClientWriter *io.PipeWriter\n}\n\n\n\nfunc (c MockConn) CloseClient() error {\n\tif err := c.ClientWriter.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := c.ClientReader.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c MockConn) Read(data []byte) (n int, err error) { return c.ServerReader.Read(data) }\nfunc (c MockConn) Write(data []byte) (n int, err error) { return c.ServerWriter.Write(data) }\n\nfunc (c MockConn) LocalAddr() net.Addr {\n\treturn &net.TCPAddr{\n\t\tIP: net.ParseIP(\"127.0.0.1:2342\"),\n\t\tPort: 2342,\n\t\tZone: \"\",\n\t}\n}\n\nfunc (c MockConn) RemoteAddr() net.Addr {\n\treturn &net.TCPAddr{\n\t\tIP: net.ParseIP(\"127.0.0.1:2342\"),\n\t\tPort: 2342,\n\t\tZone: \"\",\n\t}\n}\n\nfunc (c MockConn) SetDeadline(t time.Time) error { return nil }\nfunc (c MockConn) SetReadDeadline(t time.Time) error { return nil }\nfunc (c MockConn) SetWriteDeadline(t time.Time) error { return nil }\n\nfunc NewMockConn() MockConn {\n\tserverRead, clientWrite := io.Pipe()\n\tclientRead, serverWrite := io.Pipe()\n\n\treturn MockConn{\n\t\tServerReader: serverRead,\n\t\tServerWriter: serverWrite,\n\t\tClientReader: clientRead,\n\t\tClientWriter: clientWrite,\n\t}\n}\n\nfunc (c MockConn) Close() error ", "output": "{\n\tif err := c.ServerWriter.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := c.ServerReader.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package script\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype Script []Command\n\n\nfunc (s Script) MarshalJSON() ([]byte, error) {\n\tmarshallableCmds, err := commandsToMarshallable(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn json.Marshal(marshallableCmds)\n}\n\n\n\n\nfunc (s *Script) UnmarshalJSON(b []byte) (err error) ", "output": "{\n\tcmds, err := parseJSONCommands(b)\n\tif err != nil {\n\t\treturn\n\t}\n\t*s = Script(cmds)\n\treturn\n}"} {"input": "package app\n\n\n\n\nimport \"C\"\nimport (\n\t\"runtime\"\n\t\"sync\"\n\n\t\"grate/backend/mobile/event\"\n\t\"grate/backend/mobile/geom\"\n\t\"grate/backend/mobile/gl\"\n)\n\nvar cb Callbacks\n\nfunc run(callbacks Callbacks) {\n\truntime.LockOSThread()\n\tcb = callbacks\n\tC.runApp()\n}\n\n\nfunc onResize(w, h int) {\n\tgeom.PixelsPerPt = 72\n\tgeom.Width = geom.Pt(float32(w)/ geom.PixelsPerPt)\n\tgeom.Height = geom.Pt(float32(h)/ geom.PixelsPerPt)\n\tgl.Viewport(0, 0, w, h);\n}\n\nvar events struct {\n\tsync.Mutex\n\tpending []event.Touch\n}\n\n\n\n\nfunc onTouchStart(x, y float32) { sendTouch(event.TouchStart, x, y) }\n\n\nfunc onTouchMove(x, y float32) { sendTouch(event.TouchMove, x, y) }\n\n\nfunc onTouchEnd(x, y float32) { sendTouch(event.TouchEnd, x, y) }\n\nvar started bool\n\n\nfunc onDraw() {\n\tif !started {\n\t\tcb.Start()\n\t\tstarted = true\n\t}\n\n\tevents.Lock()\n\tpending := events.pending\n\tevents.pending = nil\n\tevents.Unlock()\n\n\tfor _, e := range pending {\n\t\tif cb.Touch != nil {\n\t\t\tcb.Touch(e)\n\t\t}\n\t}\n\tif cb.Draw != nil {\n\t\tcb.Draw()\n\t}\n}\n\nfunc sendTouch(ty event.TouchType, x, y float32) ", "output": "{\n\tevents.Lock()\n\tevents.pending = append(events.pending, event.Touch{\n\t\tType: ty,\n\t\tLoc: geom.Point{\n\t\t\tX: geom.Pt(float32(x)/ geom.PixelsPerPt),\n\t\t\tY: geom.Pt(float32(y)/ geom.PixelsPerPt),\n\t\t},\n\t})\n\tevents.Unlock()\n}"} {"input": "package main\n\nimport (\n\t\"regexp\"\n\t\"testing\"\n)\n\nfunc Test_GcSuiteRePass(t *testing.T) {\n\tfind_suite := regexp.MustCompile(gc_endRE).FindStringSubmatch\n\ttokens := find_suite(\"PASS: mmath_test.go:16: MySuite.TestAdd\t0.000s\")\n\n\tfor i, expected := range []string{\"PASS\", \"MySuite\", \"TestAdd\", \"0.000\"} {\n\t\tcheckExpected(t, expected, tokens[i+1])\n\t}\n}\n\nfunc Test_GcSuiteReFail(t *testing.T) {\n\tfind_suite := regexp.MustCompile(gc_endRE).FindStringSubmatch\n\ttokens := find_suite(\"FAIL: mmath_test.go:35: MySuite.TestDiv\")\n\n\tfor i, expected := range []string{\"FAIL\", \"MySuite\", \"TestDiv\", \"\"} {\n\t\tcheckExpected(t, expected, tokens[i+1])\n\t}\n}\n\nfunc Test_GcSuiteReSkip(t *testing.T) {\n\tfind_suite := regexp.MustCompile(gc_endRE).FindStringSubmatch\n\ttokens := find_suite(\"SKIP: mmath_test.go:35: MySuite.TestMul (not implemented)\")\n\n\tfor i, expected := range []string{\"SKIP\", \"MySuite\", \"TestMul\", \"\"} {\n\t\tcheckExpected(t, expected, tokens[i+1])\n\t}\n}\n\n\n\nfunc checkExpected(t *testing.T, expected string, actual string) ", "output": "{\n\tif actual != expected {\n\t\tt.Fatalf(\"Expected %s but was %s\\n\", expected, actual)\n\t}\n}"} {"input": "package cancel\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/coredns/coredns/plugin\"\n\t\"github.com/coredns/coredns/plugin/pkg/dnstest\"\n\t\"github.com/coredns/coredns/plugin/test\"\n\n\t\"github.com/miekg/dns\"\n)\n\ntype sleepPlugin struct{}\n\n\n\nfunc (s sleepPlugin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {\n\ti := 0\n\tm := new(dns.Msg)\n\tm.SetReply(r)\n\tfor {\n\t\tif plugin.Done(ctx) {\n\t\t\tm.Rcode = dns.RcodeBadTime \n\t\t\tw.WriteMsg(m)\n\t\t\treturn 0, nil\n\t\t}\n\t\ttime.Sleep(20 * time.Millisecond)\n\t\ti++\n\t\tif i > 2 {\n\t\t\tm.Rcode = dns.RcodeServerFailure\n\t\t\tw.WriteMsg(m)\n\t\t\treturn 0, nil\n\t\t}\n\t}\n\treturn 0, nil\n}\n\nfunc TestCancel(t *testing.T) {\n\tca := Cancel{Next: sleepPlugin{}, timeout: 20 * time.Millisecond}\n\tctx := context.Background()\n\n\tw := dnstest.NewRecorder(&test.ResponseWriter{})\n\tm := new(dns.Msg)\n\tm.SetQuestion(\"aaa.example.com.\", dns.TypeTXT)\n\n\tca.ServeDNS(ctx, w, m)\n\tif w.Rcode != dns.RcodeBadTime {\n\t\tt.Error(\"Expected ServeDNS to be canceled by context\")\n\t}\n}\n\nfunc (s sleepPlugin) Name() string ", "output": "{ return \"sleep\" }"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"sync\"\n)\n\nvar mu sync.Mutex\nvar count int\n\nfunc main() {\n\thttp.HandleFunc(\"/\", handler)\n\thttp.HandleFunc(\"/count\", counter)\n\tlog.Fatal(http.ListenAndServe(\"localhost:8000\", nil))\n}\n\n\n\n\n\nfunc counter(w http.ResponseWriter, r *http.Request) {\n\tmu.Lock()\n\tfmt.Fprintf(w, \"Count %d\\n\", count)\n\tmu.Unlock()\n}\n\nfunc handler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tmu.Lock()\n\tcount++\n\tmu.Unlock()\n\tfmt.Fprintf(w, \"URL.Path = %q\\n\", r.URL.Path)\n\tfmt.Fprintf(w, \"%s %s %s\\n\", r.Method, r.URL, r.Proto)\n\tfor k, v := range r.Header {\n\t\tfmt.Fprintf(w, \"Header[%q] = %q\\n\", k, v)\n\t}\n\tfmt.Fprintf(w, \"Host = %q\\n\", r.Host)\n\tfmt.Fprintf(w, \"RemoteAddr = %q\\n\", r.RemoteAddr)\n\tif err := r.ParseForm(); err != nil {\n\t\tlog.Print(err)\n\t}\n\tfor k, v := range r.Form {\n\t\tfmt.Fprintf(w, \"Form[%q] = %q\\n\", k, v)\n\t}\n}"} {"input": "package events\n\nimport (\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/gravitational/teleport/lib/session\"\n)\n\n\n\ntype DiscardAuditLog struct {\n}\n\nfunc (d *DiscardAuditLog) Close() error {\n\treturn nil\n}\n\n\nfunc (d *DiscardAuditLog) PostSessionChunk(namespace string, sid session.ID, reader io.Reader) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionSlice(SessionSlice) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\nfunc (d *DiscardAuditLog) GetSessionEvents(namespace string, sid session.ID, after int) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchEvents(fromUTC, toUTC time.Time, query string) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchSessionEvents(fromUTC time.Time, toUTC time.Time) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\n\n\n\n\ntype discardSessionLogger struct {\n}\n\nfunc (d *discardSessionLogger) LogEvent(fields EventFields) {\n\treturn\n}\n\nfunc (d *discardSessionLogger) Close() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) Finalize() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) WriteChunk(chunk *SessionChunk) (written int, err error) {\n\treturn 0, nil\n}\n\nfunc (d *DiscardAuditLog) EmitAuditEvent(eventType string, fields EventFields) error ", "output": "{\n\treturn nil\n}"} {"input": "package commands\n\nimport (\n\t\"fmt\"\n\t\"github.com/kr/beanstalk\"\n\t\"github.com/spf13/cobra\"\n\t\"log\"\n)\n\nvar tubePeekDelayedCommand = &cobra.Command{\n\tUse: \"peek_delayed [tube_name]\",\n\tShort: \"Retrieve the first available job in the delayed queue\",\n\tLong: `This jobs train was running late.`,\n}\n\nfunc init() {\n\ttubePeekDelayedCommand.Run = tube_peek_delayed\n}\n\n\n\nfunc tube_peek_delayed(cmd *cobra.Command, args []string) ", "output": "{\n\tclient := connect()\n\tdefer client.Close()\n\n\tclient.Tube = beanstalk.Tube{client, tube_name}\n\n\tid, body, err := client.Tube.PeekBuried()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"Delayed: [%d] : %s\\n\", id, body)\n}"} {"input": "package framework\n\ntype HorizontalAlignment int\n\nconst (\n\tAlignLeft HorizontalAlignment = iota\n\tAlignCenter\n\tAlignRight\n)\n\nfunc (a HorizontalAlignment) AlignLeft() bool { return a == AlignLeft }\nfunc (a HorizontalAlignment) AlignCenter() bool { return a == AlignCenter }\nfunc (a HorizontalAlignment) AlignRight() bool { return a == AlignRight }\n\ntype VerticalAlignment int\n\nconst (\n\tAlignTop VerticalAlignment = iota\n\tAlignMiddle\n\tAlignBottom\n)\n\nfunc (a VerticalAlignment) AlignTop() bool { return a == AlignTop }\n\nfunc (a VerticalAlignment) AlignBottom() bool { return a == AlignBottom }\n\nfunc (a VerticalAlignment) AlignMiddle() bool ", "output": "{ return a == AlignMiddle }"} {"input": "package logs\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst format = \"2006/01/02 15:04:05\"\n\ntype DetailedLogger struct {\n\tmu sync.Mutex\n\toutput io.Writer\n}\n\nfunc NewDetailedLogger(w io.Writer) *DetailedLogger {\n\treturn &DetailedLogger{\n\t\toutput: w,\n\t}\n}\n\n\n\nfunc (d *DetailedLogger) Write(p []byte) (n int, err error) ", "output": "{\n\tvar file string\n\tvar line int\n\tvar ok bool\n\n\t_, file, line, ok = runtime.Caller(3)\n\tif !ok {\n\t\tfile = \"???\"\n\t\tline = 0\n\t}\n\n\tnow := time.Now().UTC().Format(format)\n\tout := fmt.Sprintf(\"%s %s:%d %s\", now, file, line, p)\n\n\td.mu.Lock()\n\tdefer d.mu.Unlock()\n\n\treturn d.output.Write([]byte(out))\n}"} {"input": "package v1\n\n\n\ntype PodAffinityApplyConfiguration struct {\n\tRequiredDuringSchedulingIgnoredDuringExecution []PodAffinityTermApplyConfiguration `json:\"requiredDuringSchedulingIgnoredDuringExecution,omitempty\"`\n\tPreferredDuringSchedulingIgnoredDuringExecution []WeightedPodAffinityTermApplyConfiguration `json:\"preferredDuringSchedulingIgnoredDuringExecution,omitempty\"`\n}\n\n\n\nfunc PodAffinity() *PodAffinityApplyConfiguration {\n\treturn &PodAffinityApplyConfiguration{}\n}\n\n\n\n\n\n\n\n\n\nfunc (b *PodAffinityApplyConfiguration) WithPreferredDuringSchedulingIgnoredDuringExecution(values ...*WeightedPodAffinityTermApplyConfiguration) *PodAffinityApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPreferredDuringSchedulingIgnoredDuringExecution\")\n\t\t}\n\t\tb.PreferredDuringSchedulingIgnoredDuringExecution = append(b.PreferredDuringSchedulingIgnoredDuringExecution, *values[i])\n\t}\n\treturn b\n}\n\nfunc (b *PodAffinityApplyConfiguration) WithRequiredDuringSchedulingIgnoredDuringExecution(values ...*PodAffinityTermApplyConfiguration) *PodAffinityApplyConfiguration ", "output": "{\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRequiredDuringSchedulingIgnoredDuringExecution\")\n\t\t}\n\t\tb.RequiredDuringSchedulingIgnoredDuringExecution = append(b.RequiredDuringSchedulingIgnoredDuringExecution, *values[i])\n\t}\n\treturn b\n}"} {"input": "package bunyan\n\nimport \"fmt\"\n\n\ntype Logger struct {\n\tsink Sink\n\trecord Record\n}\n\n\n\n\n\n\nfunc (l *Logger) Write(record Record) error {\n\trecord.TemplateMerge(l.record)\n\treturn l.sink.Write(record)\n}\n\n\n\nfunc (l *Logger) Include(info Info) Log {\n\treturn NewLogger(InfoSink(l, info))\n}\n\n\n\nfunc (l *Logger) Record(key string, value interface{}) Log {\n\tbuilder := NewLogger(l)\n\tbuilder.record[key] = value\n\treturn builder\n}\n\n\n\nfunc (l *Logger) Recordf(key, value string, args ...interface{}) Log {\n\treturn l.Record(key, fmt.Sprintf(value, args...))\n}\n\n\n\nfunc (l *Logger) Child() Log {\n\treturn NewLogger(l)\n}\n\nfunc (l *Logger) Tracef(msg string, args ...interface{}) { l.send(TRACE, msg, args...) }\nfunc (l *Logger) Debugf(msg string, args ...interface{}) { l.send(DEBUG, msg, args...) }\nfunc (l *Logger) Infof(msg string, args ...interface{}) { l.send(INFO, msg, args...) }\nfunc (l *Logger) Warnf(msg string, args ...interface{}) { l.send(WARN, msg, args...) }\nfunc (l *Logger) Errorf(msg string, args ...interface{}) { l.send(ERROR, msg, args...) }\nfunc (l *Logger) Fatalf(msg string, args ...interface{}) { l.send(FATAL, msg, args...) }\n\nfunc (l *Logger) send(level Level, msg string, args ...interface{}) {\n\trecord := NewRecord()\n\trecord.SetMessagef(level, msg, args...)\n\te := l.Write(record)\n\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc NewLogger(target Sink) *Logger ", "output": "{\n\treturn &Logger{target, NewRecord()}\n}"} {"input": "package augeas\n\n\n\nimport \"C\"\nimport (\n\t\"fmt\"\n)\n\n\n\n\ntype ErrorCode int\n\n\nconst (\n\tCouldNotInitialize ErrorCode = -2\n\tNoMatch = -1\n\n\tNoError = 0\n\n\tENOMEM\n\n\tEINTERNAL\n\n\tEPATHX\n\n\tENOMATCH\n\n\tEMMATCH\n\n\tESYNTAX\n\n\tENOLENS\n\n\tEMXFM\n\n\tENOSPAN\n\n\tEMVDESC\n\n\tECMDRUN\n\n\tEBADARG\n)\n\n\ntype Error struct {\n\tCode ErrorCode\n\n\tMessage string\n\n\tMinorMessage string\n\n\tDetails string\n}\n\nfunc (err Error) Error() string {\n\treturn fmt.Sprintf(\"Message: %s - Minor message: %s - Details: %s\",\n\t\terr.Message, err.MinorMessage, err.Details)\n}\n\nfunc (a Augeas) error() error {\n\tcode := a.errorCode()\n\tif code == NoError {\n\t\treturn nil\n\t}\n\n\treturn Error{code, a.errorMessage(), a.errorMinorMessage(), a.errorDetails()}\n}\n\n\n\nfunc (a Augeas) errorMessage() string {\n\treturn C.GoString(C.aug_error_message(a.handle))\n}\n\nfunc (a Augeas) errorMinorMessage() string {\n\treturn C.GoString(C.aug_error_minor_message(a.handle))\n}\n\nfunc (a Augeas) errorDetails() string {\n\treturn C.GoString(C.aug_error_details(a.handle))\n}\n\nfunc (a Augeas) errorCode() ErrorCode ", "output": "{\n\treturn ErrorCode(C.aug_error(a.handle))\n}"} {"input": "package librke\n\nimport (\n\t\"context\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/rancher/rke/pki\"\n\tv3 \"github.com/rancher/types/apis/management.cattle.io/v3\"\n)\n\ntype RKE interface {\n\tGenerateRKENodeCerts(ctx context.Context, rkeConfig v3.RancherKubernetesEngineConfig, nodeAddress string, certBundle map[string]pki.CertificatePKI) map[string]pki.CertificatePKI\n\tGenerateCerts(config *v3.RancherKubernetesEngineConfig) (map[string]pki.CertificatePKI, error)\n\tGeneratePlan(ctx context.Context, rkeConfig *v3.RancherKubernetesEngineConfig, dockerInfo map[string]types.Info, data map[string]interface{}) (v3.RKEPlan, error)\n}\n\n\n\nfunc New() RKE ", "output": "{\n\treturn (*rke)(nil)\n}"} {"input": "package dbgc\n\nimport (\n\t\"code.cloudfoundry.org/lager\"\n)\n\n\n\ntype ReaperDB interface {\n\tReapExpiredContainers() error\n\tReapExpiredVolumes() error\n\tReapExpiredWorkers() error\n}\n\ntype DBGarbageCollector interface {\n\tRun() error\n}\n\ntype dbGarbageCollector struct {\n\tlogger lager.Logger\n\tdb ReaperDB\n}\n\nfunc NewDBGarbageCollector(\n\tlogger lager.Logger,\n\tdb ReaperDB,\n) DBGarbageCollector {\n\treturn &dbGarbageCollector{\n\t\tlogger: logger,\n\t\tdb: db,\n\t}\n}\n\n\n\nfunc (c *dbGarbageCollector) Run() error ", "output": "{\n\terr := c.db.ReapExpiredContainers()\n\tif err != nil {\n\t\tc.logger.Error(\"failed-to-reap-expired-containers\", err)\n\t\treturn err\n\t}\n\n\terr = c.db.ReapExpiredVolumes()\n\tif err != nil {\n\t\tc.logger.Error(\"failed-to-reap-expired-volumes\", err)\n\t\treturn err\n\t}\n\n\terr = c.db.ReapExpiredWorkers()\n\tif err != nil {\n\t\tc.logger.Error(\"failed-to-reap-expired-workers\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package e2e\n\nimport (\n\t\"testing\"\n\n\t\"knative.dev/eventing-kafka/test/e2e/helpers\"\n)\n\nfunc TestKafkaSource(t *testing.T) {\n\thelpers.AssureKafkaSourceIsOperational(t, func(auth, testCase, version string) bool { return true })\n}\n\n\n\nfunc TestKafkaSourceUpdate(t *testing.T) ", "output": "{\n\thelpers.TestKafkaSourceUpdate(t)\n}"} {"input": "package booleanplain\n\nimport \"github.com/kostya-sh/parquet-go/parquet\"\n\n\n\nfunc Fuzz(data []byte) int ", "output": "{\n\treturn parquet.FuzzBooleanPlain(data)\n}"} {"input": "package helpers\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\tginkgoconfig \"github.com/onsi/ginkgo/config\"\n)\n\n\n\nvar UserDefinedScope string\n\n\nfunc GetScope() (string, error) {\n\tif UserDefinedScope != \"\" {\n\t\treturn UserDefinedScope, nil\n\t}\n\n\tfocusString := strings.TrimSpace(strings.ToLower(ginkgoconfig.GinkgoConfig.FocusString))\n\tswitch {\n\tcase strings.HasPrefix(focusString, \"run\"):\n\t\treturn Runtime, nil\n\tcase strings.HasPrefix(focusString, K8s):\n\t\treturn K8s, nil\n\tcase strings.Contains(focusString, \"nightly\"):\n\t\treturn K8s, nil\n\tdefault:\n\t\treturn \"\", errors.New(\"Scope cannot be set\")\n\t}\n}\n\n\n\n\n\nfunc GetScopeWithVersion() string ", "output": "{\n\tresult, _ := GetScope()\n\tif result != K8s {\n\t\treturn result\n\t}\n\treturn fmt.Sprintf(\"%s-%s\", result, GetCurrentK8SEnv())\n}"} {"input": "package service\n\nimport (\n\t\"testing\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n\t\"go-common/app/service/main/videoup/model/archive\"\n)\n\n\n\nfunc TestServicesendMsg(t *testing.T) ", "output": "{\n\tconvey.Convey(\"sendMsg\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\targ = &archive.ArgMsg{}\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\tsvr.sendMsg(arg)\n\t\t\tctx.Convey(\"No return values\", func(ctx convey.C) {\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package dao\n\nimport (\n\t\"database/sql\"\n\t_ \"github.com/lib/pq\"\n\t\"log\"\n)\n\nvar DB *sql.DB = connectDB()\n\n\n\nfunc connectDB() *sql.DB ", "output": "{\n\n\tdb, err := sql.Open(\"postgres\", \"user=postgres password=postgres host=localhost port=5432 dbname=postgres sslmode=disable\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Println(\"DB connection established\")\n\n\treturn db\n\n}"} {"input": "package internalversion\n\nimport (\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\tv1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n\tauthentication \"k8s.io/kubernetes/pkg/apis/authentication\"\n)\n\n\ntype TokenReviewLister interface {\n\tList(selector labels.Selector) (ret []*authentication.TokenReview, err error)\n\tGet(name string) (*authentication.TokenReview, error)\n\tTokenReviewListerExpansion\n}\n\n\ntype tokenReviewLister struct {\n\tindexer cache.Indexer\n}\n\n\n\n\n\nfunc (s *tokenReviewLister) List(selector labels.Selector) (ret []*authentication.TokenReview, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*authentication.TokenReview))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *tokenReviewLister) Get(name string) (*authentication.TokenReview, error) {\n\tkey := &authentication.TokenReview{ObjectMeta: v1.ObjectMeta{Name: name}}\n\tobj, exists, err := s.indexer.Get(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(authentication.Resource(\"tokenreview\"), name)\n\t}\n\treturn obj.(*authentication.TokenReview), nil\n}\n\nfunc NewTokenReviewLister(indexer cache.Indexer) TokenReviewLister ", "output": "{\n\treturn &tokenReviewLister{indexer: indexer}\n}"} {"input": "package ufile\n\nimport (\n\t\"github.com/ucloud/ucloud-sdk-go/ucloud/request\"\n\t\"github.com/ucloud/ucloud-sdk-go/ucloud/response\"\n)\n\n\ntype DescribeUFileTokenRequest struct {\n\trequest.CommonBase\n\n\n\n\tDisplay *int `required:\"false\"`\n\n\tTokenId *string `required:\"false\"`\n}\n\n\ntype DescribeUFileTokenResponse struct {\n\tresponse.CommonBase\n\n\tAction string\n\n\tDataSet []UFileTokenSet\n\n\tRetCode int\n}\n\n\n\n\n\nfunc (c *UFileClient) DescribeUFileToken(req *DescribeUFileTokenRequest) (*DescribeUFileTokenResponse, error) {\n\tvar err error\n\tvar res DescribeUFileTokenResponse\n\n\treqCopier := *req\n\n\terr = c.Client.InvokeAction(\"DescribeUFileToken\", &reqCopier, &res)\n\tif err != nil {\n\t\treturn &res, err\n\t}\n\n\treturn &res, nil\n}\n\nfunc (c *UFileClient) NewDescribeUFileTokenRequest() *DescribeUFileTokenRequest ", "output": "{\n\treq := &DescribeUFileTokenRequest{}\n\n\tc.Client.SetupRequest(req)\n\n\treq.SetRetryable(true)\n\treturn req\n}"} {"input": "package openstack\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/go-ini/ini\"\n\t\"github.com/rancher/types/apis/management.cattle.io/v3\"\n)\n\nconst (\n\tOpenstackCloudProviderName = \"openstack\"\n)\n\ntype CloudProvider struct {\n\tConfig *v3.OpenstackCloudProvider\n\tName string\n}\n\nfunc GetInstance() *CloudProvider {\n\treturn &CloudProvider{}\n}\n\nfunc (p *CloudProvider) Init(cloudProviderConfig v3.CloudProvider) error {\n\tif cloudProviderConfig.OpenstackCloudProvider == nil {\n\t\treturn fmt.Errorf(\"Openstack Cloud Provider Config is empty\")\n\t}\n\tp.Name = OpenstackCloudProviderName\n\tif cloudProviderConfig.Name != \"\" {\n\t\tp.Name = cloudProviderConfig.Name\n\t}\n\tp.Config = cloudProviderConfig.OpenstackCloudProvider\n\treturn nil\n}\n\n\n\nfunc (p *CloudProvider) GenerateCloudConfigFile() (string, error) {\n\tbuf := new(bytes.Buffer)\n\tcloudConfig, _ := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: true}, []byte(\"\"))\n\tif err := ini.ReflectFrom(cloudConfig, p.Config); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to parse Openstack cloud config\")\n\t}\n\tif _, err := cloudConfig.WriteTo(buf); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn buf.String(), nil\n}\n\nfunc (p *CloudProvider) GetName() string ", "output": "{\n\treturn p.Name\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/client-go/applyconfigurations/meta/v1\"\n)\n\n\n\ntype TopologySpreadConstraintApplyConfiguration struct {\n\tMaxSkew *int32 `json:\"maxSkew,omitempty\"`\n\tTopologyKey *string `json:\"topologyKey,omitempty\"`\n\tWhenUnsatisfiable *v1.UnsatisfiableConstraintAction `json:\"whenUnsatisfiable,omitempty\"`\n\tLabelSelector *metav1.LabelSelectorApplyConfiguration `json:\"labelSelector,omitempty\"`\n}\n\n\n\nfunc TopologySpreadConstraint() *TopologySpreadConstraintApplyConfiguration {\n\treturn &TopologySpreadConstraintApplyConfiguration{}\n}\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithMaxSkew(value int32) *TopologySpreadConstraintApplyConfiguration {\n\tb.MaxSkew = &value\n\treturn b\n}\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithTopologyKey(value string) *TopologySpreadConstraintApplyConfiguration {\n\tb.TopologyKey = &value\n\treturn b\n}\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithWhenUnsatisfiable(value v1.UnsatisfiableConstraintAction) *TopologySpreadConstraintApplyConfiguration {\n\tb.WhenUnsatisfiable = &value\n\treturn b\n}\n\n\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithLabelSelector(value *metav1.LabelSelectorApplyConfiguration) *TopologySpreadConstraintApplyConfiguration ", "output": "{\n\tb.LabelSelector = value\n\treturn b\n}"} {"input": "package rotate\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/issue9/assert/v2\"\n\n\t\"github.com/issue9/logs/v3/writers\"\n)\n\nvar (\n\t_ io.WriteCloser = &Rotate{}\n\t_ writers.Flusher = &Rotate{}\n)\n\n\n\nfunc TestRotate(t *testing.T) ", "output": "{\n\ta := assert.New(t, false)\n\n\ta.NotError(os.RemoveAll(\"./testdata\"))\n\tw, err := New(\"%m-%d-%i\", \"./testdata\", 100)\n\ta.NotError(err).NotNil(w)\n\ta.Equal(w.size, 100)\n\n\tloop := 100\n\tfor i := 0; i < loop; i++ {\n\t\ttime.Sleep(60 * time.Millisecond)\n\n\t\tsize, err := w.Write([]byte(\"1024\\n\"))\n\t\ta.NotEqual(size, 0).NotError(err)\n\t}\n\n\tfiles, err := os.ReadDir(w.dir)\n\ta.NotError(err)\n\ta.Equal(len(files), int64(loop*len(\"1024\\n\"))/w.size)\n}"} {"input": "package v1\n\n\n\n\n\n\n\n\n\n\n\n\nvar map_TokenReview = map[string]string{\n\t\"\": \"TokenReview attempts to authenticate a token to a known user. Note: TokenReview requests may be cached by the webhook token authenticator plugin in the kube-apiserver.\",\n\t\"spec\": \"Spec holds information about the request being evaluated\",\n\t\"status\": \"Status is filled in by the server and indicates whether the request can be authenticated.\",\n}\n\nfunc (TokenReview) SwaggerDoc() map[string]string {\n\treturn map_TokenReview\n}\n\nvar map_TokenReviewSpec = map[string]string{\n\t\"\": \"TokenReviewSpec is a description of the token authentication request.\",\n\t\"token\": \"Token is the opaque bearer token.\",\n}\n\n\n\nvar map_TokenReviewStatus = map[string]string{\n\t\"\": \"TokenReviewStatus is the result of the token authentication request.\",\n\t\"authenticated\": \"Authenticated indicates that the token was associated with a known user.\",\n\t\"user\": \"User is the UserInfo associated with the provided token.\",\n\t\"error\": \"Error indicates that the token couldn't be checked\",\n}\n\nfunc (TokenReviewStatus) SwaggerDoc() map[string]string {\n\treturn map_TokenReviewStatus\n}\n\nvar map_UserInfo = map[string]string{\n\t\"\": \"UserInfo holds the information about the user needed to implement the user.Info interface.\",\n\t\"username\": \"The name that uniquely identifies this user among all active users.\",\n\t\"uid\": \"A unique value that identifies this user across time. If this user is deleted and another user by the same name is added, they will have different UIDs.\",\n\t\"groups\": \"The names of groups this user is a part of.\",\n\t\"extra\": \"Any additional information provided by the authenticator.\",\n}\n\nfunc (UserInfo) SwaggerDoc() map[string]string {\n\treturn map_UserInfo\n}\n\nfunc (TokenReviewSpec) SwaggerDoc() map[string]string ", "output": "{\n\treturn map_TokenReviewSpec\n}"} {"input": "package models\n\nimport (\n\t\"github.com/goadesign/goa\"\n\t\"github.com/gopheracademy/congo/app\"\n\t\"github.com/jinzhu/gorm\"\n\t\"golang.org/x/net/context\"\n\t\"time\"\n)\n\n\n\n\n\n\n\nfunc (m *Event) EventToEvent() *app.Event {\n\tevent := &app.Event{}\n\tevent.EndDate = m.EndDate\n\tevent.ID = &m.ID\n\tevent.Name = &m.Name\n\tfor _, k := range m.Presentations {\n\t\tevent.Presentations = append(event.Presentations, k.PresentationToPresentation())\n\t}\n\tfor _, k := range m.Speakers {\n\t\tevent.Speakers = append(event.Speakers, k.SpeakerToSpeaker())\n\t}\n\tevent.StartDate = m.StartDate\n\tevent.URL = m.URL\n\n\treturn event\n}\n\n\nfunc (m *EventDB) OneEvent(ctx context.Context, id int, tenantID int) (*app.Event, error) {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"event\", \"oneevent\"}, time.Now())\n\n\tvar native Event\n\terr := m.Db.Scopes(EventFilterByTenant(tenantID, &m.Db)).Table(m.TableName()).Preload(\"Presentations\").Preload(\"Speakers\").Preload(\"Tenant\").Where(\"id = ?\", id).Find(&native).Error\n\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\tgoa.LogError(ctx, \"error getting Event\", \"error\", err.Error())\n\t\treturn nil, err\n\t}\n\n\tview := *native.EventToEvent()\n\treturn &view, err\n}\n\nfunc (m *EventDB) ListEvent(ctx context.Context, tenantID int) []*app.Event ", "output": "{\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"event\", \"listevent\"}, time.Now())\n\n\tvar native []*Event\n\tvar objs []*app.Event\n\terr := m.Db.Scopes(EventFilterByTenant(tenantID, &m.Db)).Table(m.TableName()).Find(&native).Error\n\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"error listing Event\", \"error\", err.Error())\n\t\treturn objs\n\t}\n\n\tfor _, t := range native {\n\t\tobjs = append(objs, t.EventToEvent())\n\t}\n\n\treturn objs\n}"} {"input": "package nes\n\nimport \"math\"\n\ntype Filter interface {\n\tStep(x float32) float32\n}\n\n\n\ntype FirstOrderFilter struct {\n\tB0 float32\n\tB1 float32\n\tA1 float32\n\tprevX float32\n\tprevY float32\n}\n\n\n\n\n\nfunc LowPassFilter(sampleRate float32, cutoffFreq float32) Filter {\n\tc := sampleRate / math.Pi / cutoffFreq\n\ta0i := 1 / (1 + c)\n\treturn &FirstOrderFilter{\n\t\tB0: a0i,\n\t\tB1: a0i,\n\t\tA1: (1 - c) * a0i,\n\t}\n}\n\nfunc HighPassFilter(sampleRate float32, cutoffFreq float32) Filter {\n\tc := sampleRate / math.Pi / cutoffFreq\n\ta0i := 1 / (1 + c)\n\treturn &FirstOrderFilter{\n\t\tB0: c * a0i,\n\t\tB1: -c * a0i,\n\t\tA1: (1 - c) * a0i,\n\t}\n}\n\ntype FilterChain []Filter\n\nfunc (fc FilterChain) Step(x float32) float32 {\n\tif fc != nil {\n\t\tfor i := range fc {\n\t\t\tx = fc[i].Step(x)\n\t\t}\n\t}\n\treturn x\n}\n\nfunc (f *FirstOrderFilter) Step(x float32) float32 ", "output": "{\n\ty := f.B0*x + f.B1*f.prevX - f.A1*f.prevY\n\tf.prevY = y\n\tf.prevX = x\n\treturn y\n}"} {"input": "package ui\n\nfunc About() string {\n\treturn \"go-ui 0.1.1 \"\n}\n\nfunc Version() string {\n\treturn \"go-ui 0.1.1\"\n}\n\nfunc Main(fn func()) int {\n\tfnAppMain = fn\n\treturn theApp.AppMain()\n}\n\nfunc Run() int {\n\treturn theApp.Run()\n}\n\n\n\nfunc CloseAllWindows() {\n\ttheApp.CloseAllWindows()\n}\n\nfunc App() *app {\n\treturn &theApp\n}\n\nfunc Exit(code int) ", "output": "{\n\ttheApp.Exit(code)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\nfunc Print(format string, params ...interface{}) {\n\tfmt.Fprintf(os.Stderr, format+\"\\n\", params...)\n}\n\nfunc Info(format string, params ...interface{}) {\n\tPrint(\"Info: \" + format, params...)\n}\n\n\n\nfunc Fatal(err error) {\n\tPrint(\"Fatal: %s\", err)\n\tos.Exit(1)\n}\n\nfunc main() {\n\tvar config Config\n\tvar err error\n\tif config, err = LoadConfig(); err != nil {\n\t\tFatal(err)\n\t}\n\n\tif err = config.Verify(); err != nil {\n\t\tFatal(err)\n\t}\n\n\tvar svcmon ServiceMonitor\n\tif svcmon, err = NewServiceMonitor(&config); err != nil {\n\t\tFatal(err)\n\t}\n\n\tcleanup := func() {\n\t\tsvcmon.Close()\n\t}\n\n\tdefer cleanup()\n\tsigchan := make(chan os.Signal, 1)\n\tsignal.Notify(sigchan, syscall.SIGINT)\n\tsignal.Notify(sigchan, syscall.SIGTERM)\n\tquit := make(chan bool)\n\n\tgo func() {\n\t\t<-sigchan\n\t\tcleanup()\n\t\tquit <- true\n\t}()\n\n\tgo func() {\n\t\tif err = svcmon.Run(); err != nil {\n\t\t\tFatal(err)\n\t\t}\n\t\tquit <- true\n\t}()\n\n\t<-quit\n}\n\nfunc Error(err error) ", "output": "{\n\tPrint(\"Error: %s\", err)\n}"} {"input": "package box\n\nimport (\n\t\"golang.org/x/crypto/curve25519\"\n\t\"golang.org/x/crypto/nacl/secretbox\"\n\t\"golang.org/x/crypto/salsa20/salsa\"\n\t\"io\"\n)\n\n\nconst Overhead = secretbox.Overhead\n\n\n\nfunc GenerateKey(rand io.Reader) (publicKey, privateKey *[32]byte, err error) {\n\tpublicKey = new([32]byte)\n\tprivateKey = new([32]byte)\n\t_, err = io.ReadFull(rand, privateKey[:])\n\tif err != nil {\n\t\tpublicKey = nil\n\t\tprivateKey = nil\n\t\treturn\n\t}\n\n\tcurve25519.ScalarBaseMult(publicKey, privateKey)\n\treturn\n}\n\nvar zeros [16]byte\n\n\n\n\n\nfunc Precompute(sharedKey, peersPublicKey, privateKey *[32]byte) {\n\tcurve25519.ScalarMult(sharedKey, privateKey, peersPublicKey)\n\tsalsa.HSalsa20(sharedKey, &zeros, sharedKey, &salsa.Sigma)\n}\n\n\n\n\n\n\n\n\nfunc SealAfterPrecomputation(out, message []byte, nonce *[24]byte, sharedKey *[32]byte) []byte {\n\treturn secretbox.Seal(out, message, nonce, sharedKey)\n}\n\n\n\n\nfunc Open(out, box []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) ([]byte, bool) {\n\tvar sharedKey [32]byte\n\tPrecompute(&sharedKey, peersPublicKey, privateKey)\n\treturn secretbox.Open(out, box, nonce, &sharedKey)\n}\n\n\n\nfunc OpenAfterPrecomputation(out, box []byte, nonce *[24]byte, sharedKey *[32]byte) ([]byte, bool) {\n\treturn secretbox.Open(out, box, nonce, sharedKey)\n}\n\nfunc Seal(out, message []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) []byte ", "output": "{\n\tvar sharedKey [32]byte\n\tPrecompute(&sharedKey, peersPublicKey, privateKey)\n\treturn secretbox.Seal(out, message, nonce, &sharedKey)\n}"} {"input": "package tfs\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/richardwilkes/toolbox/errs\"\n)\n\ntype vfs struct {\n\tstorage string\n\tname string\n\toffset int64\n\tlength int64\n\tmode os.FileMode\n\tmodTime time.Time\n\tchildren []*vfs\n}\n\nfunc (v *vfs) Name() string {\n\treturn v.name\n}\n\nfunc (v *vfs) Size() int64 {\n\treturn v.length\n}\n\nfunc (v *vfs) Mode() os.FileMode {\n\treturn v.mode\n}\n\nfunc (v *vfs) ModTime() time.Time {\n\treturn v.modTime\n}\n\nfunc (v *vfs) IsDir() bool {\n\treturn (v.mode & os.ModeDir) == os.ModeDir\n}\n\nfunc (v *vfs) Sys() interface{} {\n\treturn nil\n}\n\n\n\nfunc (v *vfs) open() (http.File, error) ", "output": "{\n\tif v.IsDir() {\n\t\treturn &vdir{owner: v}, nil\n\t}\n\tf, err := os.Open(v.storage)\n\tif err != nil {\n\t\treturn nil, errs.NewWithCausef(err, \"Unable to open %s\", v.name)\n\t}\n\treturn &vfile{\n\t\towner: v,\n\t\tfile: f,\n\t\tsr: io.NewSectionReader(f, v.offset, v.length),\n\t}, nil\n}"} {"input": "package bolthold\n\nimport (\n\t\"reflect\"\n\n\t\"github.com/boltdb/bolt\"\n)\n\n\n\n\n\n\nfunc (s *Store) TxDelete(tx *bolt.Tx, key, dataType interface{}) error {\n\tif !tx.Writable() {\n\t\treturn bolt.ErrTxNotWritable\n\t}\n\n\tstorer := newStorer(dataType)\n\tgk, err := encode(key)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb := tx.Bucket([]byte(storer.Type()))\n\tif b == nil {\n\t\treturn ErrNotFound\n\t}\n\n\tvalue := reflect.New(reflect.TypeOf(dataType)).Interface()\n\n\tbVal := b.Get(gk)\n\n\terr = decode(bVal, value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = b.Delete(gk)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = indexDelete(storer, tx, gk, value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc (s *Store) DeleteMatching(dataType interface{}, query *Query) error {\n\treturn s.Bolt().Update(func(tx *bolt.Tx) error {\n\t\treturn s.TxDeleteMatching(tx, dataType, query)\n\t})\n}\n\n\nfunc (s *Store) TxDeleteMatching(tx *bolt.Tx, dataType interface{}, query *Query) error {\n\treturn deleteQuery(tx, dataType, query)\n}\n\nfunc (s *Store) Delete(key, dataType interface{}) error ", "output": "{\n\treturn s.Bolt().Update(func(tx *bolt.Tx) error {\n\t\treturn s.TxDelete(tx, key, dataType)\n\t})\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\n\t\"gopkg.in/stretchr/testify.v1/mock\"\n)\n\ntype Printer interface {\n\tHelp()\n\tVersion()\n\tMessage(msg string)\n\tError(err error)\n\tCommands()\n}\n\ntype TextPrinter struct {\n\tversion string\n}\n\nfunc NewTextPrinter(version string) *TextPrinter {\n\treturn &TextPrinter{version}\n}\n\nfunc (p *TextPrinter) Help() {\n\thelpText := `Name:\n\tfiz - a file wizard\n\nVersion:\n\t` + p.version + `\n\nUsage:\n\tfiz \n\n`\n\tp.Message(helpText)\n\tp.Commands()\n}\n\nfunc (p *TextPrinter) Version() {\n\tfmt.Println(\"fiz\", p.version)\n}\n\nfunc (p *TextPrinter) Message(msg string) {\n\tfmt.Print(msg)\n}\n\nfunc (p *TextPrinter) Error(err error) {\n\tfmt.Println(\"Error: \", err)\n}\n\nfunc (p *TextPrinter) Commands() {\n\tp.Message(COMMANDS_MSG)\n}\n\n\ntype MockPrinter struct {\n\tmock.Mock\n}\n\nfunc NewMockPrinter() *MockPrinter {\n\treturn &MockPrinter{}\n}\n\nfunc (m *MockPrinter) Help() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Version() {\n\tm.Called()\n}\n\n\n\nfunc (m *MockPrinter) Error(err error) {\n\tm.Called(err)\n}\n\nfunc (m *MockPrinter) Commands() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Message(msg string) ", "output": "{\n\tm.Called(msg)\n}"} {"input": "package config\n\ntype Dependencies interface {\n\tConfigurator\n\tInstalls() []string\n\tmerge(other Dependencies)\n}\n\n\n\nconst exists = true\n\ntype dependencies struct {\n\tset map[string]bool\n}\n\nfunc (d dependencies) Installs() []string {\n\tkeys := make([]string, len(d.set))\n\n\ti := 0\n\tfor k := range d.set {\n\t\tkeys[i] = k\n\t\ti++\n\t}\n\n\treturn keys\n}\n\nfunc (d dependencies) Configure(cfg Configurable) {\n\tcfg.Config().Dependencies.merge(d)\n}\n\nfunc (d dependencies) merge(other Dependencies) {\n\tfor _, dep := range other.Installs() {\n\t\td.set[dep] = exists\n\t}\n}\n\nfunc NewDependencies(deps ...string) Dependencies ", "output": "{\n\ts := make(map[string]bool, len(deps))\n\tfor _, dep := range deps {\n\t\ts[dep] = exists\n\t}\n\treturn dependencies{\n\t\tset: s,\n\t}\n}"} {"input": "package events\n\nimport (\n\t\"fmt\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/klog\"\n)\n\ntype LoggingEventRecorder struct {\n\tcomponent string\n}\n\n\nfunc NewLoggingEventRecorder(component string) Recorder {\n\treturn &LoggingEventRecorder{component: component}\n}\n\nfunc (r *LoggingEventRecorder) ComponentName() string {\n\treturn r.component\n}\n\nfunc (r *LoggingEventRecorder) ForComponent(component string) Recorder {\n\tnewRecorder := *r\n\tnewRecorder.component = component\n\treturn &newRecorder\n}\n\nfunc (r *LoggingEventRecorder) WithComponentSuffix(suffix string) Recorder {\n\treturn r.ForComponent(fmt.Sprintf(\"%s-%s\", r.ComponentName(), suffix))\n}\n\nfunc (r *LoggingEventRecorder) Event(reason, message string) {\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeNormal, reason, message)\n\tklog.Info(event.String())\n}\n\nfunc (r *LoggingEventRecorder) Eventf(reason, messageFmt string, args ...interface{}) {\n\tr.Event(reason, fmt.Sprintf(messageFmt, args...))\n}\n\n\n\nfunc (r *LoggingEventRecorder) Warningf(reason, messageFmt string, args ...interface{}) {\n\tr.Warning(reason, fmt.Sprintf(messageFmt, args...))\n}\n\nfunc (r *LoggingEventRecorder) Warning(reason, message string) ", "output": "{\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeWarning, reason, message)\n\tklog.Warning(event.String())\n}"} {"input": "package koalanet\n\nimport \"testing\"\n\nvar t1 *testing.T\n\nvar tkm_arg1 int\n\ntype TestKoalanetMain struct {\n\tActor\n}\n\n\n\nfunc (tkm *TestKoalanetMain) SendTest(args interface{}, reply interface{}) error {\n\n\treturn nil\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Benchmark_koalanet_send(b *testing.B) {\n\tRegActor(\"TestKoalanetMain\", func() IActor {\n\t\tactor := &TestKoalanetMain{}\n\t\tactor.InitActor()\n\t\tactor.RegMethod(\"Init\", actor.Init)\n\t\tactor.RegMethod(\"SendTest\", actor.SendTest)\n\t\treturn actor\n\t})\n\n\thTKM := NewActor(\"TestKoalanetMain\", nil)\n\n\tfor i := 0; i < b.N; i++ {\n\t\tSend(hTKM, \"SendTest\", nil)\n\t}\n\n\tKillActor(hTKM, false)\n\n\tWaitActorQuit(hTKM)\n}\n\nfunc (tkm *TestKoalanetMain) Init(args interface{}, reply interface{}) error ", "output": "{\n\ttkm_arg1 = 2\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"net\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\ntype UDPScanner struct {\n\tbuf []byte\n\ttext string\n\terr error\n\tsConn *net.UDPConn\n}\n\n\n\nfunc NewUDPScanner(port string) (*UDPScanner, error) {\n\tsAddr, err := net.ResolveUDPAddr(\"udp\", \":\"+port)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"udp scanner\")\n\t}\n\n\tsConn, err := net.ListenUDP(\"udp\", sAddr)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"udp scanner\")\n\t}\n\n\treturn &UDPScanner{\n\t\tbuf: make([]byte, 1024),\n\t\tsConn: sConn,\n\t}, nil\n}\n\n\n\n\n\nfunc (s *UDPScanner) Text() string {\n\treturn s.text\n}\n\n\nfunc (s *UDPScanner) Err() error {\n\treturn s.err\n}\n\nfunc (s *UDPScanner) Scan() bool ", "output": "{\n\tn, err := s.sConn.Read(s.buf)\n\tif err != nil {\n\t\ts.err = errors.Wrap(err, \"udp scan\")\n\t\treturn false\n\t}\n\n\ts.text = string(s.buf[0:n])\n\n\treturn true\n}"} {"input": "package cases\n\nimport (\n\t\"io/ioutil\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc testFilesFor(t testing.TB, dirname string, includes, ignores []string) []string {\n\tfiles, err := ioutil.ReadDir(dirname)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ttestFiles := make([]string, 0)\n\n\tfor _, file := range files {\n\n\t\tif file.IsDir() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !strings.HasSuffix(file.Name(), \".json\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !isIncludedTestCase(file.Name(), includes, ignores) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !isTestCaseAllowed(file.Name()) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !file.IsDir() {\n\t\t\ttestFiles = append(testFiles, filepath.Join(dirname, file.Name()))\n\t\t}\n\n\t}\n\n\treturn testFiles\n}\n\nfunc isIncludedTestCase(s string, includes, ignores []string) bool {\n\n\tfor _, ignore := range ignores {\n\t\trgx := rgxForMatcher(ignore)\n\n\t\tif rgx.MatchString(s) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tfor _, include := range includes {\n\t\trgx := rgxForMatcher(include)\n\n\t\tif !rgx.MatchString(s) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n\n}\n\n\n\nfunc rgxForMatcher(s string) *regexp.Regexp ", "output": "{\n\treturn regexp.MustCompile(\"(?i)\" + regexp.QuoteMeta(s))\n}"} {"input": "package utils\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"os\"\n\t\"strconv\"\n)\n\nvar path string\n\nfunc init() {\n\tflag.StringVar(&path, \"path\", \"\", \"Path to the inputfile\")\n\tflag.Parse()\n}\n\ntype Input struct {\n\t*bufio.Scanner\n}\n\n\nfunc GetInput() (*Input, error) {\n\tif len(path) > 0 {\n\t\tfile, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn &Input{}, err\n\t\t}\n\n\t\treturn &Input{bufio.NewScanner(file)}, nil\n\t}\n\treturn &Input{bufio.NewScanner(os.Stdin)}, nil\n}\n\nfunc (input *Input) ReadInt() int {\n\tinput.Split(bufio.ScanWords)\n\n\tif input.Scan() {\n\t\tresult, err := strconv.Atoi(input.Text())\n\t\tif err == nil {\n\t\t\treturn result\n\t\t}\n\t}\n\n\treturn 3\n}\n\nfunc (input *Input) ReadInts(size int) []int {\n\tinput.Split(bufio.ScanWords)\n\tints := make([]int, size)\n\n\tfor i := 0; i < size && input.Scan(); i++ {\n\t\tresult, err := strconv.Atoi(input.Text())\n\t\tif err == nil {\n\t\t\tints[i] = result\n\t\t}\n\t}\n\n\treturn ints\n}\n\nfunc (input *Input) ReadString() string {\n\tinput.Split(bufio.ScanWords)\n\n\tif input.Scan() {\n\t\treturn input.Text()\n\t}\n\n\treturn \"\"\n}\n\n\n\nfunc (input *Input) ReadStrings(size int) []string ", "output": "{\n\tinput.Split(bufio.ScanWords)\n\n\tstrings := make([]string, size)\n\n\tfor i := 0; i < size && input.Scan(); i++ {\n\t\tstrings[i] = input.Text()\n\t}\n\n\treturn strings\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/config\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdGetJSONConfig{\n\t\tname: \"get_json_section\",\n\t\trpcMethod: utils.ConfigSv1GetConfig,\n\t\trpcParams: &config.SectionWithOpts{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetJSONConfig struct {\n\tname string\n\trpcMethod string\n\trpcParams *config.SectionWithOpts\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetJSONConfig) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdGetJSONConfig) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\n\n\nfunc (self *CmdGetJSONConfig) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetJSONConfig) RpcResult() interface{} {\n\tvar s map[string]interface{}\n\treturn &s\n}\n\nfunc (self *CmdGetJSONConfig) RpcParams(reset bool) interface{} ", "output": "{\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &config.SectionWithOpts{Opts: make(map[string]interface{})}\n\t}\n\treturn self.rpcParams\n}"} {"input": "package k8sclient\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\t\"hash/fnv\"\n\t\"math/rand\"\n\t\"sync\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/google/uuid\"\n)\n\nvar (\n\tseedOnce sync.Once\n\tuuidMutex sync.Mutex\n)\n\n\n\n\nfunc getBytes(value interface{}) []byte {\n\tvar byteBuffer bytes.Buffer\n\tgobEncoder := gob.NewEncoder(&byteBuffer)\n\tif err := gobEncoder.Encode(value); err != nil {\n\t\tglog.Fatalln(\"Failed to encode value\")\n\t\treturn nil\n\t}\n\treturn byteBuffer.Bytes()\n}\n\nfunc hash(valueOne interface{}) uint64 {\n\tnewHash := fnv.New64()\n\tnewHash.Write(getBytes(valueOne))\n\treturn newHash.Sum64()\n}\n\nfunc HashCombine(valueOne, valueTwo interface{}) uint64 {\n\tnewHash := fnv.New64()\n\tvalueOneBytes := getBytes(valueOne)\n\tvalueTwoBytes := getBytes(valueTwo)\n\tnewHash.Write(append(valueOneBytes, valueTwoBytes...))\n\treturn newHash.Sum64()\n}\n\nfunc GenerateUUID(seed string) string ", "output": "{\n\tvar stringUUID string\n\tuuidMutex.Lock()\n\tuuid.SetRand(rand.New(rand.NewSource(int64(hash(seed)))))\n\tstringUUID = uuid.New().String()\n\tuuidMutex.Unlock()\n\treturn stringUUID\n}"} {"input": "package mem\n\nimport (\n\t\"runtime\"\n\t\"time\"\n)\n\n\n\nvar historicUsage *Usage\n\n\n\nconst memUsageMeasureInterval = 5 * time.Second\n\n\n\nfunc init() {\n\thistoricUsage = &Usage{}\n\tvar cycles uint64\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(memUsageMeasureInterval)\n\t\t\tcurrUsage := GetUsage()\n\t\t\tcurrSum := cycles * historicUsage.Mem\n\t\t\tcycles = cycles + 1\n\t\t\thistoricUsage.Mem = (currSum + currUsage.Mem) / cycles\n\t\t}\n\t}()\n}\n\n\ntype Usage struct {\n\tMem uint64 `json:\"mem\"`\n\tError string `json:\"error,omitempty\"`\n}\n\n\n\n\n\n\n\nfunc GetUsage() Usage {\n\tmemStats := new(runtime.MemStats)\n\truntime.ReadMemStats(memStats)\n\treturn Usage{\n\t\tMem: memStats.Sys,\n\t}\n}\n\nfunc GetHistoricUsage() Usage ", "output": "{\n\treturn *historicUsage\n}"} {"input": "package user\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n\ntype RangeList []*Range\n\n\nfunc ParseRangeList(str string) (*RangeList, error) {\n\trl := RangeList{}\n\tif len(str) == 0 {\n\t\treturn &rl, nil\n\t}\n\tparts := strings.Split(str, \",\")\n\tfor _, p := range parts {\n\t\tr, err := ParseRange(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trl = append(rl, r)\n\t}\n\treturn &rl, nil\n}\n\n\nfunc (l *RangeList) Empty() bool {\n\tif len(*l) == 0 {\n\t\treturn true\n\t}\n\tfor _, r := range *l {\n\t\tif !r.Empty() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc (l *RangeList) Type() string {\n\treturn \"user.RangeList\"\n}\n\n\nfunc (l *RangeList) Set(value string) error {\n\tnewRangeList, err := ParseRangeList(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*l = *newRangeList\n\treturn nil\n}\n\n\nfunc (l *RangeList) String() string {\n\trangeStrings := []string{}\n\tfor _, r := range *l {\n\t\trangeStrings = append(rangeStrings, r.String())\n\t}\n\treturn strings.Join(rangeStrings, \",\")\n}\n\n\n\nfunc IsUserAllowed(user string, allowed *RangeList) bool {\n\tuid, err := strconv.Atoi(user)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn allowed.Contains(uid)\n}\n\nfunc (l *RangeList) Contains(uid int) bool ", "output": "{\n\tfor _, r := range *l {\n\t\tif r.Contains(uid) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package tfs\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/richardwilkes/toolbox/errs\"\n)\n\ntype vfs struct {\n\tstorage string\n\tname string\n\toffset int64\n\tlength int64\n\tmode os.FileMode\n\tmodTime time.Time\n\tchildren []*vfs\n}\n\n\n\nfunc (v *vfs) Size() int64 {\n\treturn v.length\n}\n\nfunc (v *vfs) Mode() os.FileMode {\n\treturn v.mode\n}\n\nfunc (v *vfs) ModTime() time.Time {\n\treturn v.modTime\n}\n\nfunc (v *vfs) IsDir() bool {\n\treturn (v.mode & os.ModeDir) == os.ModeDir\n}\n\nfunc (v *vfs) Sys() interface{} {\n\treturn nil\n}\n\nfunc (v *vfs) open() (http.File, error) {\n\tif v.IsDir() {\n\t\treturn &vdir{owner: v}, nil\n\t}\n\tf, err := os.Open(v.storage)\n\tif err != nil {\n\t\treturn nil, errs.NewWithCausef(err, \"Unable to open %s\", v.name)\n\t}\n\treturn &vfile{\n\t\towner: v,\n\t\tfile: f,\n\t\tsr: io.NewSectionReader(f, v.offset, v.length),\n\t}, nil\n}\n\nfunc (v *vfs) Name() string ", "output": "{\n\treturn v.name\n}"} {"input": "package victor\n\nimport (\n\t\"github.com/FogCreek/victor/pkg/chat\"\n)\n\n\ntype Handler interface {\n\tHandle(State)\n}\n\n\ntype HandlerFunc func(State)\n\n\n\nfunc (f HandlerFunc) Handle(s State) {\n\tf(s)\n}\n\n\n\ntype State interface {\n\tRobot() Robot\n\tChat() chat.Adapter\n\tMessage() chat.Message\n\tFields() []string\n\tReply(string)\n}\n\ntype state struct {\n\trobot Robot\n\tmessage chat.Message\n\tfields []string\n}\n\n\n\n\n\nfunc (s *state) Reply(msg string) {\n\ts.robot.Chat().Send(s.message.Channel().ID(), msg)\n}\n\n\nfunc (s *state) Robot() Robot {\n\treturn s.robot\n}\n\n\nfunc (s *state) Chat() chat.Adapter {\n\treturn s.robot.Chat()\n}\n\n\n\n\nfunc (s *state) Fields() []string {\n\treturn s.fields\n}\n\nfunc (s *state) Message() chat.Message ", "output": "{\n\treturn s.message\n}"} {"input": "package systray\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\nfunc nativeLoop() {\n\tC.nativeLoop()\n}\n\nfunc quit() {\n\tC.quit()\n}\n\n\n\n\nfunc SetIcon(iconBytes []byte) {\n\tcstr := (*C.char)(unsafe.Pointer(&iconBytes[0]))\n\tC.setIcon(cstr, (C.int)(len(iconBytes)))\n}\n\n\nfunc SetTitle(title string) {\n\tC.setTitle(C.CString(title))\n}\n\n\n\n\n\nfunc addOrUpdateMenuItem(item *MenuItem) {\n\tvar disabled C.short = 0\n\tif item.disabled {\n\t\tdisabled = 1\n\t}\n\tvar checked C.short = 0\n\tif item.checked {\n\t\tchecked = 1\n\t}\n\tC.add_or_update_menu_item(\n\n\t\tC.int(item.id),\n\t\tC.CString(item.title),\n\t\tC.CString(item.tooltip),\n\t\tdisabled,\n\t\tchecked,\n\t)\n}\n\n\nfunc systray_ready() {\n\tsystrayReady()\n}\n\n\nfunc systray_menu_item_selected(cId C.int) {\n\tsystrayMenuItemSelected(int32(cId))\n}\n\nfunc SetTooltip(tooltip string) ", "output": "{\n\tC.setTooltip(C.CString(tooltip))\n}"} {"input": "package pydioadmin\n\nimport (\n\t\"github.com/mholt/caddy\"\n\t\"github.com/mholt/caddy/caddyhttp/httpserver\"\n)\n\nfunc init() {\n\tcaddy.RegisterPlugin(\"pydioadmin\", caddy.Plugin{\n\t\tServerType: \"http\",\n\t\tAction: setup,\n\t})\n}\n\n\nfunc setup(c *caddy.Controller) error {\n\n\tcfg := httpserver.GetConfig(c)\n\n\trules, err := parse(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcfg.AddMiddleware(func(next httpserver.Handler) httpserver.Handler {\n\t\treturn &Handler{\n\t\t\tNext: next,\n\t\t\tRules: rules,\n\t\t}\n\t})\n\n\treturn nil\n}\n\n\n\nfunc parse(c *caddy.Controller) ([]Rule, error) ", "output": "{\n\n\tvar rules []Rule\n\n\tfor c.Next() {\n\t\tvar rule Rule\n\n\t\targs := c.RemainingArgs()\n\n\t\tswitch len(args) {\n\t\tcase 0:\n\t\t\treturn rules, c.ArgErr()\n\t\tcase 1:\n\t\t\trule.Path = args[0]\n\n\t\t\trules = append(rules, rule)\n\t\t}\n\t}\n\n\treturn rules, nil\n}"} {"input": "package rollover\n\nimport (\n\t\"flag\"\n\t\"testing\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestBindFlags(t *testing.T) ", "output": "{\n\tv := viper.New()\n\tc := &Config{}\n\tcommand := cobra.Command{}\n\tflags := &flag.FlagSet{}\n\tc.AddFlags(flags)\n\tcommand.PersistentFlags().AddGoFlagSet(flags)\n\tv.BindPFlags(command.PersistentFlags())\n\n\terr := command.ParseFlags([]string{\n\t\t\"--conditions={\\\"max_age\\\": \\\"20000d\\\"}\",\n\t})\n\trequire.NoError(t, err)\n\n\tc.InitFromViper(v)\n\tassert.Equal(t, \"{\\\"max_age\\\": \\\"20000d\\\"}\", c.Conditions)\n}"} {"input": "package document\n\ntype IndexingOptions int\n\nconst (\n\tIndexField IndexingOptions = 1 << iota\n\tStoreField\n\tIncludeTermVectors\n)\n\nfunc (o IndexingOptions) IsIndexed() bool {\n\treturn o&IndexField != 0\n}\n\nfunc (o IndexingOptions) IsStored() bool {\n\treturn o&StoreField != 0\n}\n\n\n\nfunc (o IndexingOptions) String() string {\n\trv := \"\"\n\tif o.IsIndexed() {\n\t\trv += \"INDEXED\"\n\t}\n\tif o.IsStored() {\n\t\tif rv != \"\" {\n\t\t\trv += \", \"\n\t\t}\n\t\trv += \"STORE\"\n\t}\n\tif o.IncludeTermVectors() {\n\t\tif rv != \"\" {\n\t\t\trv += \", \"\n\t\t}\n\t\trv += \"TV\"\n\t}\n\treturn rv\n}\n\nfunc (o IndexingOptions) IncludeTermVectors() bool ", "output": "{\n\treturn o&IncludeTermVectors != 0\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tnums := []int{1, 2}\n\tnextPermutation(nums)\n\tfmt.Println(nums)\n\n}\n\n\n\nfunc nextPermutation(nums []int) ", "output": "{\n\n\tif len(nums) < 2 {\n\t\treturn\n\t}\n\tflagPosition := 0\n\tfor i := len(nums) - 1; i > 0; i-- {\n\t\tif nums[i-1] < nums[i] {\n\t\t\tflagPosition = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif flagPosition != 0 {\n\t\tflagPosition2 := len(nums) - 1\n\t\tfor i := flagPosition; i < len(nums); i++ {\n\t\t\tif nums[i] <= nums[flagPosition-1] {\n\t\t\t\tflagPosition2 = i - 1\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tnums[flagPosition-1], nums[flagPosition2] = nums[flagPosition2], nums[flagPosition-1]\n\t}\n\n\tfor i, j := flagPosition, len(nums)-1; i < j; {\n\t\tnums[i], nums[j] = nums[j], nums[i]\n\t\ti++\n\t\tj--\n\t}\n}"} {"input": "package admin\n\nimport (\n\t\"github.com/astaxie/beego\"\n\t\"os\"\n\t\"runtime\"\n)\n\ntype IndexController struct {\n\tbaseController\n}\n\nfunc (this *IndexController) Main() {\n\tthis.Data[\"hostname\"], _ = os.Hostname()\n\tthis.Data[\"goversion\"] = runtime.Version()\n\tthis.Data[\"os\"] = runtime.GOOS\n\tthis.Data[\"cpunum\"] = runtime.NumCPU()\n\tthis.Data[\"arch\"] = runtime.GOARCH\n\tthis.Data[\"beegoversion\"] = beego.VERSION\n\tthis.Data[\"version\"] = beego.AppConfig.String(\"version\")\n\tthis.TplNames = \"admin/main.tpl\"\n\tthis.Layout = \"admin/layout.tpl\"\n\tthis.LayoutSections = make(map[string]string)\n\tthis.LayoutSections[\"Sidebar\"] = \"admin/layout_sidebar.tpl\"\n}\n\n\n\nfunc (this *IndexController) Info() ", "output": "{\n\tthis.Redirect(\"/admin/main\", 302)\n}"} {"input": "package cli\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n)\n\n\nfunc CheckError(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n\n\nfunc CheckFatalError(err error) {\n\tif err != nil {\n\t\tCheckError(fmt.Errorf(\"Fatal error: %v\", err))\n\t}\n}\n\n\n\n\n\nfunc WritePid(pidfile string) {\n\tdirname := path.Dir(pidfile)\n\tif !FileExists(dirname) {\n\t\tCheckFatalError(fmt.Errorf(\"Directory \\\"%s\\\" doesn't exist\", dirname))\n\t}\n\n\tif FileExists(pidfile) {\n\t\tCheckFatalError(fmt.Errorf(\"File \\\"%s\\\" already exist\", pidfile))\n\t}\n\n\tpid := os.Getpid()\n\terr := ioutil.WriteFile(pidfile, []byte(strconv.Itoa(pid)), os.FileMode(0644))\n\tCheckFatalError(err)\n}\n\n\nfunc StopExecution(code int, pidfile string) {\n\tos.Remove(pidfile)\n\tos.Exit(code)\n}\n\nfunc FileExists(path string) bool ", "output": "{\n\t_, err := os.Stat(path)\n\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\n\treturn false\n}"} {"input": "package iotdataplane_test\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/service/iotdataplane\"\n)\n\n\n\nfunc TestRequireEndpointIfNoRegionProvided(t *testing.T) {\n\tsvc := iotdataplane.New(&aws.Config{\n\t\tRegion: aws.String(\"\"),\n\t\tDisableParamValidation: aws.Bool(true),\n\t})\n\treq, _ := svc.GetThingShadowRequest(nil)\n\terr := req.Build()\n\n\tassert.Equal(t, \"\", svc.Endpoint)\n\tassert.Error(t, err)\n\tassert.Equal(t, aws.ErrMissingEndpoint, err)\n}\n\nfunc TestRequireEndpointUsed(t *testing.T) {\n\tsvc := iotdataplane.New(&aws.Config{\n\t\tRegion: aws.String(\"mock-region\"),\n\t\tDisableParamValidation: aws.Bool(true),\n\t\tEndpoint: aws.String(\"https://endpoint\"),\n\t})\n\treq, _ := svc.GetThingShadowRequest(nil)\n\terr := req.Build()\n\n\tassert.Equal(t, \"https://endpoint\", svc.Endpoint)\n\tassert.NoError(t, err)\n}\n\nfunc TestRequireEndpointIfRegionProvided(t *testing.T) ", "output": "{\n\tsvc := iotdataplane.New(&aws.Config{\n\t\tRegion: aws.String(\"mock-region\"),\n\t\tDisableParamValidation: aws.Bool(true),\n\t})\n\treq, _ := svc.GetThingShadowRequest(nil)\n\terr := req.Build()\n\n\tassert.Equal(t, \"\", svc.Endpoint)\n\tassert.Error(t, err)\n\tassert.Equal(t, aws.ErrMissingEndpoint, err)\n}"} {"input": "package raft\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\tpb \"github.com/coreos/etcd/raft/raftpb\"\n)\n\ntype Status struct {\n\tID uint64\n\n\tpb.HardState\n\tSoftState\n\n\tApplied uint64\n\tProgress map[uint64]Progress\n}\n\n\n\n\n\nfunc (s Status) MarshalJSON() ([]byte, error) {\n\tj := fmt.Sprintf(`{\"id\":\"%x\",\"term\":%d,\"vote\":\"%x\",\"commit\":%d,\"lead\":\"%x\",\"raftState\":\"%s\",\"progress\":{`,\n\t\ts.ID, s.Term, s.Vote, s.Commit, s.Lead, s.RaftState)\n\n\tif len(s.Progress) == 0 {\n\t\tj += \"}}\"\n\t} else {\n\t\tfor k, v := range s.Progress {\n\t\t\tsubj := fmt.Sprintf(`\"%x\":{\"match\":%d,\"next\":%d,\"unreachable\":%t},`, k, v.Match, v.Next, v.Unreachable)\n\t\t\tj += subj\n\t\t}\n\t\tj = j[:len(j)-1] + \"}}\"\n\t}\n\treturn []byte(j), nil\n}\n\nfunc (s Status) String() string {\n\tb, err := s.MarshalJSON()\n\tif err != nil {\n\t\tlog.Panicf(\"unexpected error: %v\", err)\n\t}\n\treturn string(b)\n}\n\nfunc getStatus(r *raft) Status ", "output": "{\n\ts := Status{ID: r.id}\n\ts.HardState = r.HardState\n\ts.SoftState = *r.softState()\n\n\ts.Applied = r.raftLog.applied\n\n\tif s.RaftState == StateLeader {\n\t\ts.Progress = make(map[uint64]Progress)\n\t\tfor id, p := range r.prs {\n\t\t\ts.Progress[id] = *p\n\t\t}\n\t}\n\n\treturn s\n}"} {"input": "package bunyan\n\nimport \"fmt\"\n\n\ntype Logger struct {\n\tsink Sink\n\trecord Record\n}\n\n\nfunc NewLogger(target Sink) *Logger {\n\treturn &Logger{target, NewRecord()}\n}\n\n\n\nfunc (l *Logger) Write(record Record) error {\n\trecord.TemplateMerge(l.record)\n\treturn l.sink.Write(record)\n}\n\n\n\nfunc (l *Logger) Include(info Info) Log {\n\treturn NewLogger(InfoSink(l, info))\n}\n\n\n\nfunc (l *Logger) Record(key string, value interface{}) Log {\n\tbuilder := NewLogger(l)\n\tbuilder.record[key] = value\n\treturn builder\n}\n\n\n\nfunc (l *Logger) Recordf(key, value string, args ...interface{}) Log {\n\treturn l.Record(key, fmt.Sprintf(value, args...))\n}\n\n\n\nfunc (l *Logger) Child() Log {\n\treturn NewLogger(l)\n}\n\nfunc (l *Logger) Tracef(msg string, args ...interface{}) { l.send(TRACE, msg, args...) }\nfunc (l *Logger) Debugf(msg string, args ...interface{}) { l.send(DEBUG, msg, args...) }\nfunc (l *Logger) Infof(msg string, args ...interface{}) { l.send(INFO, msg, args...) }\nfunc (l *Logger) Warnf(msg string, args ...interface{}) { l.send(WARN, msg, args...) }\nfunc (l *Logger) Errorf(msg string, args ...interface{}) { l.send(ERROR, msg, args...) }\nfunc (l *Logger) Fatalf(msg string, args ...interface{}) { l.send(FATAL, msg, args...) }\n\n\n\nfunc (l *Logger) send(level Level, msg string, args ...interface{}) ", "output": "{\n\trecord := NewRecord()\n\trecord.SetMessagef(level, msg, args...)\n\te := l.Write(record)\n\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}"} {"input": "package rorm\n\ntype rorm struct {\n\tredisQuerier *RedisQuerier\n}\n\nfunc NewROrm() ROrmer {\n\treturn new(rorm).Using(\"default\")\n}\n\nfunc (r *rorm) QueryHash(key string) HashQuerySeter {\n\treturn &hashQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QueryKeys(key string) KeysQuerySeter {\n\treturn &keysQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\n\n\nfunc (r *rorm) QueryZSet(key string) ZSetQuerySeter {\n\treturn &zsetQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QuerySet(key string) SetQuerySeter {\n\treturn &setQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r rorm) Using(alias string) ROrmer {\n\tclient, ok := redisRegistry[alias]\n\tif !ok {\n\t\tpanic(\"using reids '\" + alias + \"' not exist.\")\n\t}\n\tr.redisQuerier = &RedisQuerier{\n\t\tClient: client,\n\t}\n\treturn &r\n}\n\nfunc (r *rorm) Querier() Querier {\n\treturn r.redisQuerier\n}\n\nfunc (r *rorm) QueryString(key string) StringQuerySeter ", "output": "{\n\treturn &stringQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}"} {"input": "package lib\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype StopChannelContext struct {\n\tStopCh <-chan struct{}\n}\n\nfunc (c *StopChannelContext) Deadline() (deadline time.Time, ok bool) {\n\tok = false\n\treturn\n}\n\nfunc (c *StopChannelContext) Done() <-chan struct{} {\n\treturn c.StopCh\n}\n\n\n\nfunc (c *StopChannelContext) Value(key interface{}) interface{} {\n\treturn nil\n}\n\nfunc (c *StopChannelContext) Err() error ", "output": "{\n\tselect {\n\tcase <-c.StopCh:\n\t\treturn context.Canceled\n\tdefault:\n\t\treturn nil\n\t}\n}"} {"input": "package route\n\nimport (\n\t\"app/controller\"\n\t\"net/http\"\n)\n\n\n\ntype apiHandler struct {\n\tc *controller.Context\n}\n\nfunc (h apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tswitch {\n\tcase r.Method == http.MethodPost && r.URL.Path == \"/org/get\":\n\t\th.c.OrgGetApi(w, r)\n\tcase r.Method == http.MethodPost && r.URL.Path == \"/org/create\":\n\t\th.c.OrgCreateApi(w, r)\n\tcase r.Method == http.MethodPost && r.URL.Path == \"/session/get\":\n\t\th.c.SessionGetApi(w, r)\n\tcase r.Method == http.MethodPost && r.URL.Path == \"/session/create\":\n\t\th.c.SessionCreateApi(w, r)\n\tdefault:\n\t\th.c.NotFoundApi(w, r)\n\t}\n}\n\nfunc Api(c *controller.Context) http.Handler ", "output": "{\n\treturn &apiHandler{c: c}\n}"} {"input": "package logrus\n\nimport (\n\t\"io\"\n\t\"sync\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/golang/protobuf/proto\"\n\n\t\"go.pedge.io/protolog\"\n)\n\nvar (\n\tglobalPusherOptions = PusherOptions{}\n\tglobalLoggerOptions = protolog.LoggerOptions{}\n\tglobalLock = &sync.Mutex{}\n)\n\n\ntype PusherOptions struct {\n\tOut io.Writer\n\tHooks []logrus.Hook\n\tFormatter logrus.Formatter\n\tEnableID bool\n\tDisableContexts bool\n\tUnmarshalFunc func([]byte, proto.Message) error\n}\n\n\n\n\n\nfunc SetPusherOptions(options PusherOptions) {\n\tglobalLock.Lock()\n\tdefer globalLock.Unlock()\n\tglobalPusherOptions = options\n\tregister()\n}\n\n\nfunc SetLoggerOptions(options protolog.LoggerOptions) {\n\tglobalLock.Lock()\n\tdefer globalLock.Unlock()\n\tglobalLoggerOptions = options\n\tregister()\n}\n\n\nfunc Register() {\n\tglobalLock.Lock()\n\tdefer globalLock.Unlock()\n\tregister()\n}\n\nfunc register() {\n\tprotolog.SetLogger(protolog.NewLogger(NewPusher(globalPusherOptions), globalLoggerOptions))\n}\n\nfunc NewPusher(options PusherOptions) protolog.Pusher ", "output": "{\n\treturn newPusher(options)\n}"} {"input": "package badger\n\n\n\n\n\n\n\n\n\ntype ManagedDB struct {\n\t*DB\n}\n\n\n\n\n\n\nfunc OpenManaged(opts Options) (*ManagedDB, error) {\n\topts.managedTxns = true\n\tdb, err := Open(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ManagedDB{db}, nil\n}\n\n\n\nfunc (db *ManagedDB) NewTransaction(update bool) {\n\tpanic(\"Cannot use NewTransaction() for ManagedDB. Use NewTransactionAt() instead.\")\n}\n\n\n\n\n\n\nfunc (db *ManagedDB) NewTransactionAt(readTs uint64, update bool) *Txn {\n\ttxn := db.DB.NewTransaction(update)\n\ttxn.readTs = readTs\n\treturn txn\n}\n\n\n\n\n\n\n\n\n\nfunc (db *ManagedDB) PurgeVersionsBelow(key []byte, ts uint64) error {\n\ttxn := db.NewTransactionAt(ts, false)\n\tdefer txn.Discard()\n\treturn db.purgeVersionsBelow(txn, key, ts)\n}\n\n\n\nfunc (db *ManagedDB) GetSequence(_ []byte, _ uint64) (*Sequence, error) {\n\tpanic(\"Cannot use GetSequence for ManagedDB.\")\n}\n\nfunc (txn *Txn) CommitAt(commitTs uint64, callback func(error)) error ", "output": "{\n\tif !txn.db.opt.managedTxns {\n\t\treturn ErrManagedTxn\n\t}\n\ttxn.commitTs = commitTs\n\treturn txn.Commit(callback)\n}"} {"input": "package runtime\n\nimport (\n\t\"unsafe\"\n)\n\nfunc RaceRead(addr unsafe.Pointer)\nfunc RaceWrite(addr unsafe.Pointer)\nfunc RaceReadRange(addr unsafe.Pointer, len int)\nfunc RaceWriteRange(addr unsafe.Pointer, len int)\n\nfunc RaceSemacquire(s *uint32)\nfunc RaceSemrelease(s *uint32)\n\n\nconst raceenabled = true\n\nfunc raceReadObjectPC(t *_type, addr unsafe.Pointer, callerpc, pc uintptr) {\n\tkind := t.kind & kindMask\n\tif kind == kindArray || kind == kindStruct {\n\t\tracereadrangepc(addr, t.size, callerpc, pc)\n\t} else {\n\t\tracereadpc(addr, callerpc, pc)\n\t}\n}\n\n\n\n\nfunc racereadpc(addr unsafe.Pointer, callpc, pc uintptr)\n\n\nfunc racewritepc(addr unsafe.Pointer, callpc, pc uintptr)\n\ntype symbolizeContext struct {\n\tpc uintptr\n\tfn *byte\n\tfile *byte\n\tline uintptr\n\toff uintptr\n\tres uintptr\n}\n\nvar qq = [...]byte{'?', '?', 0}\nvar dash = [...]byte{'-', 0}\n\n\nfunc racesymbolize(ctx *symbolizeContext) {\n\tf := findfunc(ctx.pc)\n\tif f == nil {\n\t\tctx.fn = &qq[0]\n\t\tctx.file = &dash[0]\n\t\tctx.line = 0\n\t\tctx.off = ctx.pc\n\t\tctx.res = 1\n\t\treturn\n\t}\n\n\tctx.fn = funcname(f)\n\tfile, line := funcline(f, ctx.pc)\n\tctx.line = uintptr(line)\n\tctx.file = &bytes(file)[0] \n\tctx.off = ctx.pc - f.entry\n\tctx.res = 1\n\treturn\n}\n\nfunc raceWriteObjectPC(t *_type, addr unsafe.Pointer, callerpc, pc uintptr) ", "output": "{\n\tkind := t.kind & kindMask\n\tif kind == kindArray || kind == kindStruct {\n\t\tracewriterangepc(addr, t.size, callerpc, pc)\n\t} else {\n\t\tracewritepc(addr, callerpc, pc)\n\t}\n}"} {"input": "package manager\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/consul-template/config\"\n\tdep \"github.com/hashicorp/consul-template/dependency\"\n\t\"github.com/hashicorp/consul-template/template\"\n\t\"github.com/hashicorp/consul/testutil\"\n)\n\nvar testConsul *testutil.TestServer\nvar testClients *dep.ClientSet\n\n\n\nfunc testDedupManager(t *testing.T, tmpls []*template.Template) *DedupManager {\n\tbrain := template.NewBrain()\n\tdedupConfig := config.TestConfig(nil).Dedup\n\tdedup, err := NewDedupManager(dedupConfig, testClients, brain, tmpls)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn dedup\n}\n\nfunc TestMain(m *testing.M) ", "output": "{\n\tconsul, err := testutil.NewTestServerConfig(func(c *testutil.TestServerConfig) {\n\t\tc.LogLevel = \"warn\"\n\t})\n\tif err != nil {\n\t\tlog.Fatal(\"failed to start consul server\")\n\t}\n\ttestConsul = consul\n\n\tclients := dep.NewClientSet()\n\tif err := clients.CreateConsulClient(&dep.CreateConsulClientInput{\n\t\tAddress: testConsul.HTTPAddr,\n\t}); err != nil {\n\t\ttestConsul.Stop()\n\t\tlog.Fatal(err)\n\t}\n\ttestClients = clients\n\n\texitCh := make(chan int, 1)\n\tfunc() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\ttestConsul.Stop()\n\t\t\t\tpanic(r)\n\t\t\t}\n\t\t}()\n\n\t\texitCh <- m.Run()\n\t}()\n\n\texit := <-exitCh\n\n\ttestConsul.Stop()\n\tos.Exit(exit)\n}"} {"input": "package web\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/gravitational/teleport/lib/httplib\"\n\n\t\"github.com/gravitational/roundtrip\"\n\t\"github.com/gravitational/trace\"\n)\n\n\n\nfunc newClientWithPool(pool *x509.CertPool) *http.Client {\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{RootCAs: pool},\n\t\t},\n\t}\n}\n\nfunc newWebClient(url string, opts ...roundtrip.ClientParam) (*webClient, error) {\n\tclt, err := roundtrip.NewClient(url, APIVersion, opts...)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn &webClient{clt}, nil\n}\n\n\n\ntype webClient struct {\n\t*roundtrip.Client\n}\n\nfunc (w *webClient) PostJSON(\n\tendpoint string, val interface{}) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.PostJSON(endpoint, val))\n}\n\nfunc (w *webClient) PutJSON(\n\tendpoint string, val interface{}) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.PutJSON(endpoint, val))\n}\n\nfunc (w *webClient) Get(endpoint string, val url.Values) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.Get(endpoint, val))\n}\n\nfunc (w *webClient) Delete(endpoint string) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.Delete(endpoint))\n}\n\nfunc newInsecureClient() *http.Client ", "output": "{\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t}\n}"} {"input": "package stash\n\nimport \"golang.org/x/net/context\"\n\n\n\nfunc Has(ctx context.Context, key string) bool ", "output": "{\n\t_, holder := c(ctx)\n\tholder.RLock()\n\t_, ok := holder.values[key]\n\tholder.RUnlock()\n\treturn ok\n}"} {"input": "package plan\n\nimport (\n\t\"github.com/pingcap/tidb/expression\"\n)\n\n\nfunc EliminateProjection(p PhysicalPlan) PhysicalPlan {\n\tswitch plan := p.(type) {\n\tcase *Projection:\n\t\tif !projectionCanBeEliminated(plan) {\n\t\t\tbreak\n\t\t}\n\t\tchild := plan.children[0].(PhysicalPlan)\n\t\tchild.SetSchema(plan.Schema())\n\t\tRemovePlan(p)\n\t\tp = EliminateProjection(child)\n\t}\n\tchildren := make([]Plan, 0, len(p.Children()))\n\tfor _, child := range p.Children() {\n\t\tchildren = append(children, EliminateProjection(child.(PhysicalPlan)))\n\t}\n\tp.SetChildren(children...)\n\treturn p\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc projectionCanBeEliminated(p *Projection) bool ", "output": "{\n\tchild := p.children[0].(PhysicalPlan)\n\tif p.Schema().Len() != child.Schema().Len() {\n\t\treturn false\n\t}\n\tfor i, expr := range p.Exprs {\n\t\tcol, ok := expr.(*expression.Column)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\tif col.FromID != child.Schema().Columns[i].FromID || col.Position != child.Schema().Columns[i].Position {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package queue\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Node struct {\n\tvalue interface{}\n\tnext *Node\n}\n\nfunc NewNode(value interface{}) *Node {\n\tnode := new(Node)\n\tnode.value = value\n\n\treturn node\n}\n\ntype Queue struct {\n\thead *Node\n\ttail *Node\n}\n\nfunc NewQueue(args ...interface{}) *Queue {\n\tlist := new(Queue)\n\n\tfor _, v := range args {\n\t\tlist.Enqueue(v)\n\t}\n\n\treturn list\n}\n\nfunc (q *Queue) String() string {\n\tnode := q.head\n\n\tvar values []string\n\n\tif node == nil {\n\t\treturn \"[]\"\n\t}\n\n\tfor node.next != nil {\n\t\tvalues = append(values, fmt.Sprintf(\"%v\", node.value))\n\n\t\tnode = node.next\n\t}\n\tvalues = append(values, fmt.Sprintf(\"%v\", node.value))\n\n\treturn fmt.Sprintf(\"[%s]\", strings.Join(values, \", \"))\n}\n\nfunc (q *Queue) Enqueue(value interface{}) {\n\tnewTail := NewNode(value)\n\n\tif q.head == nil {\n\t\tq.head = newTail\n\t\tq.tail = q.head\n\t} else {\n\t\tq.tail.next = newTail\n\t\tq.tail = newTail\n\t}\n}\n\n\n\nfunc (q *Queue) Peek() (value interface{}, ok bool) {\n\tif q.head == nil {\n\t\treturn 0, false\n\t} else {\n\t\treturn q.head.value, true\n\t}\n}\n\nfunc (q *Queue) Empty() bool {\n\tif q.head == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\nfunc (q *Queue) Dequeue() (value interface{}, ok bool) ", "output": "{\n\n\tif q.head == nil {\n\t\treturn 0, false\n\t} else {\n\t\tnode := q.head\n\t\tq.head = node.next\n\t\treturn node.value, true\n\t}\n}"} {"input": "package networker\n\nimport (\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/names\"\n\n\t\"github.com/juju/juju/api/base\"\n\t\"github.com/juju/juju/api/watcher\"\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/network\"\n)\n\nconst networkerFacade = \"Networker\"\n\n\ntype State struct {\n\tfacade base.FacadeCaller\n}\n\n\nfunc NewState(caller base.APICaller) *State {\n\treturn &State{base.NewFacadeCaller(caller, networkerFacade)}\n}\n\n\n\n\n\n\nfunc (st *State) WatchInterfaces(tag names.MachineTag) (watcher.NotifyWatcher, error) {\n\targs := params.Entities{\n\t\tEntities: []params.Entity{{Tag: tag.String()}},\n\t}\n\tvar results params.NotifyWatchResults\n\terr := st.facade.FacadeCall(\"WatchInterfaces\", args, &results)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(results.Results) != 1 {\n\t\terr = errors.Errorf(\"expected one result, got %d\", len(results.Results))\n\t\treturn nil, err\n\t}\n\tresult := results.Results[0]\n\tif result.Error != nil {\n\t\treturn nil, result.Error\n\t}\n\tw := watcher.NewNotifyWatcher(st.facade.RawAPICaller(), result)\n\treturn w, nil\n}\n\nfunc (st *State) MachineNetworkInfo(tag names.MachineTag) ([]network.Info, error) ", "output": "{\n\targs := params.Entities{\n\t\tEntities: []params.Entity{{Tag: tag.String()}},\n\t}\n\tvar results params.MachineNetworkInfoResults\n\terr := st.facade.FacadeCall(\"MachineNetworkInfo\", args, &results)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(results.Results) != 1 {\n\t\terr = errors.Errorf(\"expected one result, got %d\", len(results.Results))\n\t\treturn nil, err\n\t}\n\tresult := results.Results[0]\n\tif result.Error != nil {\n\t\treturn nil, result.Error\n\t}\n\treturn results.Results[0].Info, nil\n}"} {"input": "package kafka\n\nimport (\n\t\"encoding/binary\"\n\t\"hash/crc32\"\n)\n\ntype crc32Writer struct {\n\ttable *crc32.Table\n\tbuffer [8]byte\n\tcrc32 uint32\n}\n\nfunc (w *crc32Writer) update(b []byte) {\n\tw.crc32 = crc32.Update(w.crc32, w.table, b)\n}\n\nfunc (w *crc32Writer) writeInt8(i int8) {\n\tw.buffer[0] = byte(i)\n\tw.update(w.buffer[:1])\n}\n\nfunc (w *crc32Writer) writeInt16(i int16) {\n\tbinary.BigEndian.PutUint16(w.buffer[:2], uint16(i))\n\tw.update(w.buffer[:2])\n}\n\nfunc (w *crc32Writer) writeInt32(i int32) {\n\tbinary.BigEndian.PutUint32(w.buffer[:4], uint32(i))\n\tw.update(w.buffer[:4])\n}\n\nfunc (w *crc32Writer) writeInt64(i int64) {\n\tbinary.BigEndian.PutUint64(w.buffer[:8], uint64(i))\n\tw.update(w.buffer[:8])\n}\n\nfunc (w *crc32Writer) writeBytes(b []byte) {\n\tn := len(b)\n\tif b == nil {\n\t\tn = -1\n\t}\n\tw.writeInt32(int32(n))\n\tw.update(b)\n}\n\n\n\nfunc (w *crc32Writer) WriteString(s string) (int, error) {\n\tw.update([]byte(s))\n\treturn len(s), nil\n}\n\nfunc (w *crc32Writer) Write(b []byte) (int, error) ", "output": "{\n\tw.update(b)\n\treturn len(b), nil\n}"} {"input": "package mocks\n\nimport mock \"github.com/stretchr/testify/mock\"\nimport models \"github.com/Golang-Coach/Lessons/GoBDD/models\"\n\n\ntype IGithub struct {\n\tmock.Mock\n}\n\n\n\n\nfunc (_m *IGithub) GetPackageRepoInfo(owner string, repositoryName string) (*models.Package, error) ", "output": "{\n\tret := _m.Called(owner, repositoryName)\n\n\tvar r0 *models.Package\n\tif rf, ok := ret.Get(0).(func(string, string) *models.Package); ok {\n\t\tr0 = rf(owner, repositoryName)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*models.Package)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, string) error); ok {\n\t\tr1 = rf(owner, repositoryName)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/polariseye/polarserver/common\"\n\t\"github.com/polariseye/polarserver/common/errorCode\"\n\t\"github.com/polariseye/polarserver/moduleManage\"\n)\n\ntype testStruct struct {\n\tclassName string\n}\n\nvar TestBLL *testStruct\n\nfunc init() {\n\tTestBLL = NewTestStruct()\n\tmoduleManage.RegisterModule(func() (moduleManage.IModule, moduleManage.ModuleType) {\n\t\treturn NewTestStruct(), moduleManage.NormalModule\n\t})\n}\n\n\nfunc (this *testStruct) Name() string {\n\treturn this.className\n}\n\nfunc (this *testStruct) InitModule() []error {\n\tfmt.Println(\"初始化\")\n\n\treturn nil\n}\n\nfunc (this *testStruct) CheckModule() []error {\n\tfmt.Println(\"check\")\n\n\treturn nil\n}\n\nfunc (this *testStruct) ConvertModule() []error {\n\tfmt.Println(\"数据转换\")\n\n\treturn nil\n}\n\n\n\n\nfunc NewTestStruct() *testStruct {\n\treturn &testStruct{\n\t\tclassName: \"TestBLL\",\n\t}\n}\n\nfunc (this *testStruct) C_Hello(request *common.RequestModel, d int, name string) *common.ResultModel ", "output": "{\n\tresult := common.NewResultModel(errorCode.ClientDataError)\n\n\tresult.Value[\"Hello\"] = name + \"_\" + this.Name()\n\tresult.Value[\"Extra\"] = d\n\n\tresult.SetNormalError(errorCode.Success)\n\treturn result\n}"} {"input": "package misc\n\nimport \"jvmgo/ch11/native\"\nimport \"jvmgo/ch11/rtda\"\n\nfunc init() {\n\tnative.Register(\"sun/misc/URLClassPath\", \"getLookupCacheURLs\", \"(Ljava/lang/ClassLoader;)[Ljava/net/URL;\", getLookupCacheURLs)\n}\n\n\n\n\n\nfunc getLookupCacheURLs(frame *rtda.Frame) ", "output": "{\n\tframe.OperandStack().PushRef(nil)\n}"} {"input": "package helper\n\nimport (\n\t\"encoding/base64\"\n\t\"strings\"\n\t\"time\"\n\t\"github.com/insionng/yougam/libraries/flosch/pongo2.v3\"\n)\n\nfunc ConvertToBase64(in string) string {\n\treturn base64.StdEncoding.EncodeToString([]byte(in))\n}\n\nfunc ConvertToBase64ByPongo2(in *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(base64.StdEncoding.EncodeToString([]byte(in.String())))\n}\n\nfunc SplitByPongo2(in *pongo2.Value, splitor *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Split(in.String(), splitor.String()))\n}\n\n\n\nfunc CropwordByPongo2(in *pongo2.Value, start *pongo2.Value, length *pongo2.Value, symbol *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Substr(in.String(), start.Integer(), length.Integer(), symbol.String()))\n}\n\nfunc Cropword(in string, start int, length int, symbol string) string {\n\treturn Substr(in, start, length, symbol)\n}\n\nfunc File(s string) string {\n\tif len(s) > 0 {\n\t\tif strings.HasPrefix(s, \"http\") || strings.HasPrefix(s, \"/identicon\") {\n\t\t\treturn s\n\t\t} else {\n\t\t\treturn \"/file\" + s\n\t\t}\n\t}\n\treturn s\n}\n\nfunc Unix2TimeByPongo2(in *pongo2.Value, timeLayout *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(time.Unix(int64(in.Integer()), 0).Format(timeLayout.String()))\n}\n\nfunc MarkdownByPongo2(in *pongo2.Value) *pongo2.Value ", "output": "{\n\treturn pongo2.AsValue(Markdown(in.String()))\n}"} {"input": "package main\n\ntype Session struct {\n\tseq int32\n\tservers map[int32]int32 \n}\n\n\nfunc NewSession(server int) *Session {\n\ts := new(Session)\n\ts.servers = make(map[int32]int32, server)\n\ts.seq = 0\n\treturn s\n}\n\nfunc (s *Session) nextSeq() int32 {\n\ts.seq++\n\treturn s.seq\n}\n\n\nfunc (s *Session) Put(server int32) (seq int32) {\n\tseq = s.nextSeq()\n\ts.servers[seq] = server\n\treturn\n}\n\nfunc (s *Session) Servers() (seqs []int32, servers []int32) {\n\tvar (\n\t\ti = len(s.servers)\n\t\tseq, server int32\n\t)\n\tseqs = make([]int32, i)\n\tservers = make([]int32, i)\n\tfor seq, server = range s.servers {\n\t\ti--\n\t\tseqs[i] = seq\n\t\tservers[i] = server\n\t}\n\treturn\n}\n\n\nfunc (s *Session) Del(seq int32) bool {\n\tdelete(s.servers, seq)\n\treturn (len(s.servers) == 0)\n}\n\n\n\nfunc (s *Session) Size() int ", "output": "{\n\treturn len(s.servers)\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/julienschmidt/httprouter\"\n\t\"net/http\"\n)\n\ntype Logout struct {\n\t*Controller\n}\n\n\n\n\n\n\n\nfunc (l *Logout) Register(router *httprouter.Router) {\n\trouter.GET(\"/logout\", l.Get)\n}\n\n\n\nfunc (l *Logout) Get(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tl.Authentication.ClearSession(res)\n\thttp.Redirect(res, req, \"/login\", http.StatusFound)\n}\n\nfunc NewLogoutController(c *Controller, router *httprouter.Router) ", "output": "{\n\tlogout := &Logout{\n\t\tc,\n\t}\n\tlogout.Register(router)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\n\tasp \"golang.org/x/exp/aspectgo/aspect\"\n)\n\n\ntype ExampleAspect struct {\n}\n\n\nfunc (a *ExampleAspect) Pointcut() asp.Pointcut {\n\tpkg := regexp.QuoteMeta(\"golang.org/x/exp/aspectgo/example/hello2\")\n\ts := pkg + \".*\"\n\treturn asp.NewCallPointcutFromRegexp(s)\n}\n\n\nfunc (a *ExampleAspect) Advice(ctx asp.Context) []interface{} {\n\targs := ctx.Args()\n\tfmt.Println(\"BEFORE hello\")\n\tres := ctx.Call(args)\n\tfmt.Println(\"AFTER hello\")\n\treturn res\n}\n\n\ntype FmtPrintlnAspect struct {\n}\n\nfunc (a *FmtPrintlnAspect) Pointcut() asp.Pointcut {\n\ts := regexp.QuoteMeta(\"fmt.Println\")\n\treturn asp.NewCallPointcutFromRegexp(s)\n}\n\n\n\nfunc (a *FmtPrintlnAspect) Advice(ctx asp.Context) []interface{} ", "output": "{\n\targs := ctx.Args()\n\tfmt.Fprintf(os.Stderr, \"directing to stderr: %s\\n\", args...)\n\treturn []interface{}{0, nil}\n}"} {"input": "package astar\n\nimport (\n\t\"os\"\n\t\"image\"\n)\n\nimport _ \"image/png\"\n\nfunc openImage(filename string) (image.Image) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer f.Close()\n\timg, _, _ := image.Decode(f)\n\treturn img\n}\n\nfunc parseImage(img image.Image) MapData {\n\tmax := uint32(65536-1) \n\n\tbounds := img.Bounds()\n\tmap_data := NewMapData(bounds.Max.X, bounds.Max.Y)\n\tfor y := bounds.Min.Y; y < bounds.Max.Y; y++ {\n\t\tfor x := bounds.Min.X; x < bounds.Max.X; x++ {\n\t\t\tr, g, b, a := img.At(x, y).RGBA()\n\n\t\t\tif(r == max && g == max && b == max && a == max) {\n\t\t\t\tmap_data[x][bounds.Max.Y-1-y] = LAND\n\t\t\t} else {\n\t\t\t\tmap_data[x][bounds.Max.Y-1-y] = WALL\n\t\t\t}\n\t\t}\n\t}\n\treturn map_data\n}\n\n\n\nfunc GetMapFromImage(filename string) MapData ", "output": "{\n\timg := openImage(filename)\n\tif(img == nil) {\n\t\treturn nil\n\t}\n\treturn parseImage(img)\n}"} {"input": "package hcsshim\n\nimport (\n\t\"time\"\n\n\t\"github.com/Sirupsen/logrus\"\n)\n\n\n\nfunc waitForNotification(callbackNumber uintptr, expectedNotification hcsNotification, timeout *time.Duration) error {\n\tcallbackMapLock.RLock()\n\tchannels := callbackMap[callbackNumber].channels\n\tcallbackMapLock.RUnlock()\n\n\texpectedChannel := channels[expectedNotification]\n\tif expectedChannel == nil {\n\t\tlogrus.Errorf(\"unknown notification type in waitForNotification %x\", expectedNotification)\n\t\treturn ErrInvalidNotificationType\n\t}\n\n\tvar c <-chan time.Time\n\tif timeout != nil {\n\t\ttimer := time.NewTimer(*timeout)\n\t\tc = timer.C\n\t\tdefer timer.Stop()\n\t}\n\n\tselect {\n\tcase err, ok := <-expectedChannel:\n\t\tif !ok {\n\t\t\treturn ErrHandleClose\n\t\t}\n\t\treturn err\n\tcase err, ok := <-channels[hcsNotificationSystemExited]:\n\t\tif !ok {\n\t\t\treturn ErrHandleClose\n\t\t}\n\t\tif channels[hcsNotificationSystemExited] == expectedChannel {\n\t\t\treturn err\n\t\t}\n\t\treturn ErrUnexpectedContainerExit\n\tcase _, ok := <-channels[hcsNotificationServiceDisconnect]:\n\t\tif !ok {\n\t\t\treturn ErrHandleClose\n\t\t}\n\t\treturn ErrUnexpectedProcessAbort\n\tcase <-c:\n\t\treturn ErrTimeout\n\t}\n}\n\nfunc processAsyncHcsResult(err error, resultp *uint16, callbackNumber uintptr, expectedNotification hcsNotification, timeout *time.Duration) error ", "output": "{\n\terr = processHcsResult(err, resultp)\n\tif IsPending(err) {\n\t\treturn waitForNotification(callbackNumber, expectedNotification, timeout)\n\t}\n\n\treturn err\n}"} {"input": "package api_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/tidepool-org/platform/test\"\n)\n\n\n\nfunc TestSuite(t *testing.T) ", "output": "{\n\ttest.Test(t)\n}"} {"input": "package config\n\n\ntype UserOptions struct {\n\tRememberMeDays int `json:\"remember-me-days\" yaml:\"remember-me-days\" envconfig:\"REMEMBER_ME_DAYS\"`\n\tPasswordNoReuseMonths int `json:\"password-no-reuse-months\" yaml:\"password-no-reuse-months\" envconfig:\"PASSWORD_NO_REUSE_MONTHS\"`\n}\n\n\n\n\n\nfunc (o *UserOptions) VerifyAndPrepare() error { return nil }\n\nfunc NewUserOptions() *UserOptions ", "output": "{\n\treturn &UserOptions{\n\t\tRememberMeDays: 45,\n\t\tPasswordNoReuseMonths: 0,\n\t}\n}"} {"input": "package proto\n\nimport (\n\t\"fmt\"\n\t\"net\"\n)\n\n\nfunc FromNetAddr(addr net.Addr) *Addr {\n\treturn &Addr{\n\t\tNetwork: addr.Network(),\n\t\tAddress: addr.String(),\n\t}\n}\n\n\nfunc (a Addr) NetAddr() (net.Addr, error) {\n\tswitch a.Network {\n\tcase \"tcp\", \"tcp4\", \"tcp6\":\n\t\treturn net.ResolveTCPAddr(a.Network, a.Address)\n\tcase \"udp\", \"udp4\", \"udp6\":\n\t\treturn net.ResolveUDPAddr(a.Network, a.Address)\n\tcase \"unix\", \"unixgram\", \"unixpacket\":\n\t\treturn net.ResolveUnixAddr(a.Network, a.Address)\n\t}\n\treturn nil, fmt.Errorf(\"network %s not supported\", a.Network)\n}\n\n\n\n\n\nfunc (m *GossipRequest) GetUser() string ", "output": "{\n\treturn \"node\"\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\n\t\"go-common/app/job/openplatform/article/conf\"\n\t\"go-common/app/job/openplatform/article/http\"\n\t\"go-common/app/job/openplatform/article/service\"\n\t\"go-common/library/log\"\n\t\"go-common/library/net/trace\"\n)\n\nfunc main() {\n\tflag.Parse()\n\tinitConf()\n\tinitLog()\n\tdefer log.Close()\n\tlog.Info(\"article-job start\")\n\tsrv := service.New(conf.Conf)\n\thttp.Init(conf.Conf, srv)\n\tinitSignal(srv)\n}\n\nfunc initConf() {\n\tif err := conf.Init(); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\n\nfunc initSignal(srv *service.Service) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)\n\tfor {\n\t\ts := <-c\n\t\tlog.Info(\"article-job get a signal: %s\", s.String())\n\t\tswitch s {\n\t\tcase syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:\n\t\t\tif err := srv.Close(); err != nil {\n\t\t\t\tlog.Error(\"srv close consumer error(%+v)\", err)\n\t\t\t}\n\t\t\treturn\n\t\tcase syscall.SIGHUP:\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc initLog() ", "output": "{\n\tlog.Init(conf.Conf.Xlog)\n\ttrace.Init(conf.Conf.Tracer)\n\tdefer trace.Close()\n}"} {"input": "package bunyan\n\nimport \"os\"\n\n\n\ntype Sink interface {\n\tWrite(record Record) error\n}\n\ntype funcSink struct {\n\twrite func(record Record) error\n}\n\nfunc (sink *funcSink) Write(record Record) error {\n\treturn sink.write(record)\n}\n\n\n\nfunc SinkFunc(write func(record Record) error) Sink {\n\treturn &funcSink{write}\n}\n\n\n\nfunc NilSink() Sink {\n\treturn SinkFunc(func(record Record) error {\n\t\treturn nil \n\t})\n}\n\nfunc InfoSink(target Sink, info Info) Sink {\n\treturn SinkFunc(func(record Record) error {\n\t\trecord.SetIfNot(info.Key(), info.Value())\n\t\treturn target.Write(record)\n\t})\n}\n\n\n\n\n\nfunc FileSink(path string) Sink {\n\tconst flags = os.O_CREATE | os.O_APPEND | os.O_WRONLY\n\tfile, e := os.OpenFile(path, flags, 0666)\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\n\treturn NewJsonSink(file)\n}\n\nfunc StdoutSink() Sink ", "output": "{\n\treturn NewJsonSink(os.Stdout)\n}"} {"input": "package thrift\n\nimport (\n\t\"net\"\n)\n\n\ntype socketConn struct {\n\tnet.Conn\n\n\tbuffer [1]byte\n}\n\nvar _ net.Conn = (*socketConn)(nil)\n\n\n\n\n\n\nfunc wrapSocketConn(conn net.Conn) *socketConn {\n\tif sc, ok := conn.(*socketConn); ok {\n\t\treturn sc\n\t}\n\n\treturn &socketConn{\n\t\tConn: conn,\n\t}\n}\n\n\n\n\n\n\n\n\nfunc (sc *socketConn) isValid() bool {\n\treturn sc != nil && sc.Conn != nil\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (sc *socketConn) IsOpen() bool {\n\tif !sc.isValid() {\n\t\treturn false\n\t}\n\treturn sc.checkConn() == nil\n}\n\n\n\n\n\n\n\n\n\n\nfunc (sc *socketConn) Read(p []byte) (n int, err error) {\n\tif len(p) == 0 {\n\t\treturn 0, sc.read0()\n\t}\n\n\treturn sc.Conn.Read(p)\n}\n\nfunc createSocketConnFromReturn(conn net.Conn, err error) (*socketConn, error) ", "output": "{\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &socketConn{\n\t\tConn: conn,\n\t}, nil\n}"} {"input": "package elements\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestRegistryAddAlias(t *testing.T) {\n\tr := NewRegistry()\n\tc := NewComponent(\"cloud\", \"foo\", \"bar\")\n\n\tr.Add(c)\n\tc1 := Get(r, \"bar\")\n\tassert.Equal(t, c, c1)\n\n\tc2 := Get(r, \"foo\")\n\tassert.Nil(t, c2)\n}\n\nfunc TestErrors(t *testing.T) {\n\tr := NewRegistry()\n\tc := NewComponent(\"cloud\", \"\", \"\")\n\n\terr := r.Add(nil)\n\tassert.Equal(t, errors.New(\"Nil given\"), err)\n\n\terr = r.Add(c)\n\tassert.Equal(t, errors.New(\"Neither alias nor identifier set\"), err)\n\n\tc1 := NewComponent(\"cloud\", \"foo\", \"bar\")\n\terr = r.Add(c1)\n\tassert.Equal(t, nil, err)\n\n\terr = r.Add(c1)\n\tassert.Equal(t, errors.New(\"Alias bar already exists\"), err)\n\n\tc2 := NewComponent(\"cloud\", \"foo\", \"\")\n\terr = r.Add(c2)\n\tassert.Equal(t, nil, err)\n\n\terr = r.Add(c2)\n\tassert.Equal(t, errors.New(\"Identifier foo already exists\"), err)\n}\n\nfunc TestRegistryAddId(t *testing.T) ", "output": "{\n\tr := NewRegistry()\n\tc := NewComponent(\"cloud\", \"foo\", \"\")\n\n\tr.Add(c)\n\tc1 := Get(r, \"foo\")\n\tassert.Equal(t, c, c1)\n}"} {"input": "package sqlite3\n\nimport \"C\"\n\ntype ErrNo int\n\ntype Error struct {\n\tCode ErrNo \n\terr string \n}\n\n\nvar (\n\tErrError error = ErrNo(1) \n\tErrInternal error = ErrNo(2) \n\tErrPerm error = ErrNo(3) \n\tErrAbort error = ErrNo(4) \n\tErrBusy error = ErrNo(5) \n\tErrLocked error = ErrNo(6) \n\tErrNomem error = ErrNo(7) \n\tErrReadonly error = ErrNo(8) \n\tErrInterrupt error = ErrNo(9) \n\tErrIoErr error = ErrNo(10) \n\tErrCorrupt error = ErrNo(11) \n\tErrNotFound error = ErrNo(12) \n\tErrFull error = ErrNo(13) \n\tErrCantOpen error = ErrNo(14) \n\tErrProtocol error = ErrNo(15) \n\tErrEmpty error = ErrNo(16) \n\tErrSchema error = ErrNo(17) \n\tErrTooBig error = ErrNo(18) \n\tErrConstraint error = ErrNo(19) \n\tErrMismatch error = ErrNo(20) \n\tErrMisuse error = ErrNo(21) \n\tErrNoLFS error = ErrNo(22) \n\tErrAuth error = ErrNo(23) \n\tErrFormat error = ErrNo(24) \n\tErrRange error = ErrNo(25) \n\tErrNotADB error = ErrNo(26) \n\tErrNotice error = ErrNo(27) \n\tErrWarning error = ErrNo(28) \n)\n\n\n\nfunc (err Error) Error() string {\n\tif err.err != \"\" {\n\t\treturn err.err\n\t}\n\treturn errorString(err)\n}\n\nfunc (err ErrNo) Error() string ", "output": "{\n\treturn Error{Code: err}.Error()\n}"} {"input": "package css\n\nfunc checkSubArraySum(nums []int, k int) bool {\n\treturn bruteForce(nums, k)\n}\n\n\nfunc bruteForce(nums []int, k int) bool {\n\tn := len(nums)\n\tif n < 2 {\n\t\treturn false\n\t}\n\tvar sum int\n\tfor i := range nums {\n\t\tsum = 0\n\t\tfor j := i; j < n; j++ {\n\t\t\tsum += nums[j]\n\t\t\tif sum == k || (k != 0 && sum%k == 0) {\n\t\t\t\tif j > i {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\nfunc preSumHash(nums []int, k int) bool ", "output": "{\n\tn := len(nums)\n\tif n < 2 {\n\t\treturn false\n\t}\n\thash := make(map[int]int, n)\n\thash[0] = -1\n\tvar sum int\n\tfor i := range nums {\n\t\tsum += nums[i]\n\t\tif k != 0 {\n\t\t\tsum %= k\n\t\t}\n\t\tif v, exists := hash[sum]; exists {\n\t\t\tif i-v > 1 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t} else {\n\t\t\thash[sum] = i\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package machinelearningservices\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" machinelearningservices/2021-07-01\"\n}"} {"input": "package iso20022\n\n\ntype ActionMessage3 struct {\n\n\tDestination *UserInterface3Code `xml:\"Dstn\"`\n\n\tFormat *OutputFormat1Code `xml:\"Frmt,omitempty\"`\n\n\tContent *Max20000Text `xml:\"Cntt\"`\n}\n\n\n\nfunc (a *ActionMessage3) SetFormat(value string) {\n\ta.Format = (*OutputFormat1Code)(&value)\n}\n\nfunc (a *ActionMessage3) SetContent(value string) {\n\ta.Content = (*Max20000Text)(&value)\n}\n\nfunc (a *ActionMessage3) SetDestination(value string) ", "output": "{\n\ta.Destination = (*UserInterface3Code)(&value)\n}"} {"input": "package testing\n\nimport \"k8s.io/kubernetes/pkg/util/iptables\"\n\n\ntype fake struct{}\n\nfunc NewFake() *fake {\n\treturn &fake{}\n}\n\nfunc (*fake) EnsureChain(table iptables.Table, chain iptables.Chain) (bool, error) {\n\treturn true, nil\n}\n\nfunc (*fake) FlushChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) DeleteChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) EnsureRule(position iptables.RulePosition, table iptables.Table, chain iptables.Chain, args ...string) (bool, error) {\n\treturn true, nil\n}\n\nfunc (*fake) DeleteRule(table iptables.Table, chain iptables.Chain, args ...string) error {\n\treturn nil\n}\n\nfunc (*fake) IsIpv6() bool {\n\treturn false\n}\n\nfunc (*fake) Save(table iptables.Table) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\nfunc (*fake) SaveAll() ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\nfunc (*fake) Restore(table iptables.Table, data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\n\n\nfunc (*fake) AddReloadFunc(reloadFunc func()) {}\n\nfunc (*fake) Destroy() {}\n\nvar _ = iptables.Interface(&fake{})\n\nfunc (*fake) RestoreAll(data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error ", "output": "{\n\treturn nil\n}"} {"input": "package data\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\ntype Data struct {\n\tKey string\n\tValue interface{}\n\tTimestamp time.Time\n}\n\n\n\n\nfunc (d *Data) IsLater(other *Data) bool {\n\treturn d.Timestamp.After(other.Timestamp)\n}\n\n\nfunc (d *Data) String() string {\n\treturn fmt.Sprintf(\"%s/%v\", d.Key, d.Value)\n}\n\n\n\n\n\nfunc New(key string, value interface{}) *Data ", "output": "{\n\treturn &Data{key, value, time.Now()}\n}"} {"input": "package opts\n\n\ntype CreateOption func(*CreateConfig)\n\n\n\ntype CreateConfig struct {\n\tOptions map[string]string\n\tLabels map[string]string\n\tReference string\n}\n\n\n\nfunc WithCreateLabels(labels map[string]string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Labels = labels\n\t}\n}\n\n\n\nfunc WithCreateOptions(opts map[string]string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Options = opts\n\t}\n}\n\n\n\n\n\n\n\n\ntype GetConfig struct {\n\tDriver string\n\tReference string\n\tResolveStatus bool\n}\n\n\ntype GetOption func(*GetConfig)\n\n\n\n\n\nfunc WithGetDriver(name string) GetOption {\n\treturn func(o *GetConfig) {\n\t\to.Driver = name\n\t}\n}\n\n\n\nfunc WithGetReference(ref string) GetOption {\n\treturn func(o *GetConfig) {\n\t\to.Reference = ref\n\t}\n}\n\n\n\nfunc WithGetResolveStatus(cfg *GetConfig) {\n\tcfg.ResolveStatus = true\n}\n\n\ntype RemoveConfig struct {\n\tPurgeOnError bool\n}\n\n\ntype RemoveOption func(*RemoveConfig)\n\n\n\n\nfunc WithPurgeOnError(b bool) RemoveOption {\n\treturn func(o *RemoveConfig) {\n\t\to.PurgeOnError = b\n\t}\n}\n\nfunc WithCreateReference(ref string) CreateOption ", "output": "{\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Reference = ref\n\t}\n}"} {"input": "package main \n\nimport (\n\t\"testing\" \n)\n\nfunc Benchmark_numberOfWaysToMake2Pounds(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tnumberOfWaysToMake2Pounds()\n\t}\n}\n\nfunc Benchmark_numberOfWaysToMakeX1(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tnumberOfWaysToMakeX1(200)\n\t}\n}\n\n\n\nfunc Benchmark_numberOfWaysToMakeX2(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tnumberOfWaysToMakeX2(200)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\n\tasp \"golang.org/x/exp/aspectgo/aspect\"\n)\n\n\ntype ExampleAspect struct {\n}\n\n\n\n\n\nfunc (a *ExampleAspect) Advice(ctx asp.Context) []interface{} {\n\targs := ctx.Args()\n\tfmt.Println(\"BEFORE hello\")\n\tres := ctx.Call(args)\n\tfmt.Println(\"AFTER hello\")\n\treturn res\n}\n\n\ntype FmtPrintlnAspect struct {\n}\n\nfunc (a *FmtPrintlnAspect) Pointcut() asp.Pointcut {\n\ts := regexp.QuoteMeta(\"fmt.Println\")\n\treturn asp.NewCallPointcutFromRegexp(s)\n}\n\nfunc (a *FmtPrintlnAspect) Advice(ctx asp.Context) []interface{} {\n\targs := ctx.Args()\n\tfmt.Fprintf(os.Stderr, \"directing to stderr: %s\\n\", args...)\n\treturn []interface{}{0, nil}\n}\n\nfunc (a *ExampleAspect) Pointcut() asp.Pointcut ", "output": "{\n\tpkg := regexp.QuoteMeta(\"golang.org/x/exp/aspectgo/example/hello2\")\n\ts := pkg + \".*\"\n\treturn asp.NewCallPointcutFromRegexp(s)\n}"} {"input": "package lmath\n\n\n\nfunc smallestRangeI(A []int, K int) int ", "output": "{\n\tminV, maxV := A[0], A[0]\n\tfor _, v := range A {\n\t\tif v < minV {\n\t\t\tminV = v\n\t\t} else if v > maxV {\n\t\t\tmaxV = v\n\t\t}\n\t}\n\tif res := (maxV - K) - (minV + K); res < 0 {\n\t\treturn 0\n\t} else {\n\t\treturn res\n\t}\n}"} {"input": "package config\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestDefaultHoardConfig(t *testing.T) {\n\tassertHoardConfigSerialisation(t,\n\t\tfunc(conf *HoardConfig) string {\n\t\t\treturn conf.TOMLString()\n\t\t},\n\t\tHoardConfigFromTOMLString,\n\t\tDefaultHoardConfig)\n\tassertHoardConfigSerialisation(t,\n\t\tfunc(conf *HoardConfig) string {\n\t\t\treturn conf.JSONString()\n\t\t},\n\t\tHoardConfigFromJSONString,\n\t\tDefaultHoardConfig)\n}\n\n\n\nfunc assertHoardConfigSerialisation(t *testing.T,\n\tserialise func(*HoardConfig) string,\n\tdeserialise func(string) (*HoardConfig, error),\n\thoardConfig *HoardConfig) ", "output": "{\n\n\thoardConfigRoundTrip, err := deserialise(serialise(hoardConfig))\n\tassert.NoError(t, err)\n\thoardConfigString := serialise(hoardConfig)\n\tassert.NotEmpty(t, hoardConfigString)\n\tassert.Equal(t, hoardConfigString, serialise(hoardConfigRoundTrip))\n}"} {"input": "package fsm\n\nimport (\n\t\"log\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/boltdb/bolt\"\n\t\"github.com/docker/engine-api/client\"\n\t\"golang.org/x/net/context\"\n)\n\nfunc Watch(period int, states chan map[string]string) {\n\tlog.Println(\"Watcher was started...\")\n\tcli, err := client.NewEnvClient()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor {\n\t\tids := getIds(\"my.db\")\n\t\tif len(ids) == 0 {\n\t\t\tlog.Println(\"No containers for watching.\")\n\t\t\ttime.Sleep(time.Second * 3)\n\t\t\tcontinue\n\t\t}\n\t\tfor _, id := range ids {\n\t\t\tres, err := cli.ContainerInspect(context.Background(), id)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstates <- map[string]string{res.Name[1:]: res.State.Status}\n\t\t\tlog.Printf(`Container \"%s\" with id \"%s\" is in status \"%s\"`, res.Name, id, res.State.Status)\n\t\t}\n\t\ttime.Sleep(time.Second * 3)\n\t}\n}\n\n\n\nfunc getIds(path string) []string ", "output": "{\n\tcontainers := []string{}\n\tdb, err := bolt.Open(path, 0600, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\tbname := []byte(\"Northshore\")\n\tkey := []byte(\"containers\")\n\n\terr = db.View(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket(bname)\n\t\tif bucket == nil {\n\t\t\tlog.Printf(\"Bucket %s not found\", bname)\n\t\t\treturn nil\n\t\t}\n\n\t\tk := bucket.Get(key)\n\t\tstr := string(k[:])\n\t\tcontainers = strings.Split(str, \",\")\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn containers\n}"} {"input": "package logmon\n\nimport (\n\t\"context\"\n\n\t\"github.com/hashicorp/nomad/client/logmon/proto\"\n)\n\ntype logmonClient struct {\n\tclient proto.LogMonClient\n}\n\nfunc (c *logmonClient) Start(cfg *LogConfig) error {\n\treq := &proto.StartRequest{\n\t\tLogDir: cfg.LogDir,\n\t\tStdoutFileName: cfg.StdoutLogFile,\n\t\tStderrFileName: cfg.StderrLogFile,\n\t\tMaxFiles: uint32(cfg.MaxFiles),\n\t\tMaxFileSizeMb: uint32(cfg.MaxFileSizeMB),\n\t\tStdoutFifo: cfg.StdoutFifo,\n\t\tStderrFifo: cfg.StderrFifo,\n\t}\n\t_, err := c.client.Start(context.Background(), req)\n\treturn err\n}\n\n\n\nfunc (c *logmonClient) Stop() error ", "output": "{\n\treq := &proto.StopRequest{}\n\t_, err := c.client.Stop(context.Background(), req)\n\treturn err\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/converter\"\n\t\"strings\"\n)\n\n\ntype BatchStopServersOption struct {\n\tServers []ServerId `json:\"servers\"`\n\tType *BatchStopServersOptionType `json:\"type,omitempty\"`\n}\n\nfunc (o BatchStopServersOption) String() string {\n\tdata, _ := json.Marshal(o)\n\treturn strings.Join([]string{\"BatchStopServersOption\", string(data)}, \" \")\n}\n\ntype BatchStopServersOptionType struct {\n\tvalue string\n}\n\ntype BatchStopServersOptionTypeEnum struct {\n\tSOFT BatchStopServersOptionType\n\tHARD BatchStopServersOptionType\n}\n\n\n\nfunc (c BatchStopServersOptionType) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(c.value)\n}\n\nfunc (c *BatchStopServersOptionType) UnmarshalJSON(b []byte) error {\n\tmyConverter := converter.StringConverterFactory(\"string\")\n\tif myConverter != nil {\n\t\tval, err := myConverter.CovertStringToInterface(strings.Trim(string(b[:]), \"\\\"\"))\n\t\tif err == nil {\n\t\t\tc.value = val.(string)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t} else {\n\t\treturn errors.New(\"convert enum data to string error\")\n\t}\n}\n\nfunc GetBatchStopServersOptionTypeEnum() BatchStopServersOptionTypeEnum ", "output": "{\n\treturn BatchStopServersOptionTypeEnum{\n\t\tSOFT: BatchStopServersOptionType{\n\t\t\tvalue: \"SOFT\",\n\t\t},\n\t\tHARD: BatchStopServersOptionType{\n\t\t\tvalue: \"HARD\",\n\t\t},\n\t}\n}"} {"input": "package error\n\nimport (\n\t\"strconv\"\n)\n\n\n\ntype StructuralError string\n\nfunc (s StructuralError) String() string {\n\treturn \"OpenPGP data invalid: \" + string(s)\n}\n\n\n\ntype UnsupportedError string\n\nfunc (s UnsupportedError) String() string {\n\treturn \"OpenPGP feature unsupported: \" + string(s)\n}\n\n\n\ntype InvalidArgumentError string\n\nfunc (i InvalidArgumentError) String() string {\n\treturn \"OpenPGP argument invalid: \" + string(i)\n}\n\n\n\ntype SignatureError string\n\n\n\ntype keyIncorrect int\n\nfunc (ki keyIncorrect) String() string {\n\treturn \"the given key was incorrect\"\n}\n\nvar KeyIncorrectError = keyIncorrect(0)\n\ntype unknownIssuer int\n\nfunc (unknownIssuer) String() string {\n\treturn \"signature make by unknown entity\"\n}\n\nvar UnknownIssuerError = unknownIssuer(0)\n\ntype UnknownPacketTypeError uint8\n\nfunc (upte UnknownPacketTypeError) String() string {\n\treturn \"unknown OpenPGP packet type: \" + strconv.Itoa(int(upte))\n}\n\nfunc (b SignatureError) String() string ", "output": "{\n\treturn \"OpenPGP signature invalid: \" + string(b)\n}"} {"input": "package osv\n\nimport (\n\t\"time\"\n\n\t\"github.com/intelsdi-x/snap/control/plugin\"\n\t\"github.com/intelsdi-x/snap/core\"\n)\n\n\n\nfunc getCPUMetricTypes() ([]plugin.MetricType, error) {\n\tvar mts []plugin.MetricType\n\tfor _, metricType := range cpuMetrics {\n\t\tmts = append(mts, plugin.MetricType{Namespace_: core.NewNamespace(Vendor, Name, \"cpu\", metricType)})\n\t}\n\treturn mts, nil\n}\n\nfunc getCPUTime(swagURL string) (uint64, error) {\n\tpath := \"trace/count\"\n\tresponse, err := osvRestGet(swagURL, path)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tcounters, err := osvRestUnmarshall(response)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn counters.TimeMs, nil\n}\n\nfunc cpuStat(ns core.Namespace, swagURL string) (*plugin.MetricType, error) ", "output": "{\n\tmetric, err := getCPUTime(swagURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &plugin.MetricType{\n\t\tNamespace_: ns,\n\t\tData_: metric,\n\t\tTimestamp_: time.Now(),\n\t}, nil\n}"} {"input": "package vault\n\nimport \"time\"\n\ntype dynamicSystemView struct {\n\tcore *Core\n\tmountEntry *MountEntry\n}\n\nfunc (d dynamicSystemView) DefaultLeaseTTL() time.Duration {\n\tdef, _ := d.fetchTTLs()\n\treturn def\n}\n\n\n\n\n\nfunc (d dynamicSystemView) fetchTTLs() (def, max time.Duration) {\n\tdef = d.core.defaultLeaseTTL\n\tmax = d.core.maxLeaseTTL\n\n\tif d.mountEntry.Config.DefaultLeaseTTL != 0 {\n\t\tdef = d.mountEntry.Config.DefaultLeaseTTL\n\t}\n\tif d.mountEntry.Config.MaxLeaseTTL != 0 {\n\t\tmax = d.mountEntry.Config.MaxLeaseTTL\n\t}\n\n\treturn\n}\n\nfunc (d dynamicSystemView) MaxLeaseTTL() time.Duration ", "output": "{\n\t_, max := d.fetchTTLs()\n\treturn max\n}"} {"input": "package signal\n\nimport (\n\t\"github.com/idealeak/goserver/core\"\n)\n\nvar Config = Configuration{}\n\ntype Configuration struct {\n\tSupportSignal bool\n}\n\nfunc (c *Configuration) Name() string {\n\treturn \"signal\"\n}\n\nfunc (c *Configuration) Init() error {\n\tif c.SupportSignal {\n\t\tgo SignalHandlerModule.ProcessSignal()\n\t}\n\treturn nil\n}\n\nfunc (c *Configuration) Close() error {\n\treturn nil\n}\n\n\n\nfunc init() ", "output": "{\n\tcore.RegistePackage(&Config)\n}"} {"input": "package instructions\n\nimport \"github.com/zxh0/jvm.go/jvmgo/jvm/rtda\"\n\n\ntype astore struct{ Index8Instruction }\n\nfunc (self *astore) Execute(frame *rtda.Frame) {\n\t_astore(frame, uint(self.index))\n}\n\ntype astore_0 struct{ NoOperandsInstruction }\n\nfunc (self *astore_0) Execute(frame *rtda.Frame) {\n\t_astore(frame, 0)\n}\n\ntype astore_1 struct{ NoOperandsInstruction }\n\nfunc (self *astore_1) Execute(frame *rtda.Frame) {\n\t_astore(frame, 1)\n}\n\ntype astore_2 struct{ NoOperandsInstruction }\n\nfunc (self *astore_2) Execute(frame *rtda.Frame) {\n\t_astore(frame, 2)\n}\n\ntype astore_3 struct{ NoOperandsInstruction }\n\n\n\nfunc _astore(frame *rtda.Frame, index uint) {\n\tref := frame.OperandStack().PopRef()\n\tframe.LocalVars().SetRef(index, ref)\n}\n\nfunc (self *astore_3) Execute(frame *rtda.Frame) ", "output": "{\n\t_astore(frame, 3)\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"os\"\n \"io/ioutil\"\n \"strings\"\n \"sort\"\n \"bytes\"\n)\n\n\n\ntype Letter struct {\n Name string\n Count int\n}\n\ntype ByCount []Letter\n\nfunc (a ByCount) Len() int { return len(a) }\nfunc (a ByCount) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a ByCount) Less(i, j int) bool { return a[i].Count > a[j].Count }\n\nfunc main() {\n directions := strings.Split(ReadFile(\"input.txt\"), \"\\n\")\n\n var col_letters bytes.Buffer\n var answer bytes.Buffer\n\n for x := 0; x < len(directions[0]); x++ {\n \n col_letters.Reset()\n\n \n for y := 0; y < len(directions) - 1; y++ {\n col_letters.WriteByte(directions[y][x])\n }\n\n var letter_counts []Letter\n \n found := make(map[string]bool)\n for _, letter := range strings.Split(col_letters.String(), \"\") {\n if found[letter] {\n continue\n }\n found[letter] = true\n letter_counts = append(letter_counts, Letter{Name: letter, Count: strings.Count(col_letters.String(), letter)})\n \t}\n\n \n sort.Sort(ByCount(letter_counts))\n \n answer.WriteString(letter_counts[0].Name)\n }\n fmt.Println(answer.String())\n}\n\nfunc ReadFile(filename string) string ", "output": "{\n data, err := ioutil.ReadFile(filename)\n\n if err != nil {\n fmt.Fprintf(os.Stderr, \"Error: %v\\n\", err)\n return \"\"\n }\n\n return string(data)\n}"} {"input": "package policy\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"fmt\"\n)\n\nconst (\n\tmajor = \"7\"\n\tminor = \"0\"\n\tpatch = \"1\"\n\ttag = \"-beta\"\n\tsemVerFormat = \"%s.%s.%s%s\"\n\tuserAgentFormat = \"Azure-SDK-for-Go/%s arm-%s/%s\"\n)\n\n\nfunc UserAgent() string {\n\treturn fmt.Sprintf(userAgentFormat, Version(), \"policy\", \"2016-04-01\")\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn fmt.Sprintf(semVerFormat, major, minor, patch, tag)\n}"} {"input": "package fuse\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\ntype MountConfig struct {\n\tOpContext context.Context\n\n\tFSName string\n\n\tReadOnly bool\n\n\tErrorLogger *log.Logger\n\n\tDebugLogger *log.Logger\n\n\tDisableWritebackCaching bool\n\n\tEnableVnodeCaching bool\n\n\tOptions map[string]string\n}\n\n\n\nfunc (c *MountConfig) toMap() (opts map[string]string) {\n\tisDarwin := runtime.GOOS == \"darwin\"\n\topts = make(map[string]string)\n\n\topts[\"default_permissions\"] = \"\"\n\n\tfsname := c.FSName\n\tif runtime.GOOS == \"linux\" && fsname == \"\" {\n\t\tfsname = \"some_fuse_file_system\"\n\t}\n\n\tif fsname != \"\" {\n\t\topts[\"fsname\"] = fsname\n\t}\n\n\tif c.ReadOnly {\n\t\topts[\"ro\"] = \"\"\n\t}\n\n\tif isDarwin && !c.EnableVnodeCaching {\n\t\topts[\"novncache\"] = \"\"\n\t}\n\n\tif isDarwin {\n\t\topts[\"noappledouble\"] = \"\"\n\t}\n\n\tfor k, v := range c.Options {\n\t\topts[k] = v\n\t}\n\n\treturn\n}\n\nfunc escapeOptionsKey(s string) (res string) {\n\tres = s\n\tres = strings.Replace(res, `\\`, `\\\\`, -1)\n\tres = strings.Replace(res, `,`, `\\,`, -1)\n\treturn\n}\n\n\n\n\nfunc (c *MountConfig) toOptionsString() string ", "output": "{\n\tvar components []string\n\tfor k, v := range c.toMap() {\n\t\tk = escapeOptionsKey(k)\n\n\t\tcomponent := k\n\t\tif v != \"\" {\n\t\t\tcomponent = fmt.Sprintf(\"%s=%s\", k, v)\n\t\t}\n\n\t\tcomponents = append(components, component)\n\t}\n\n\treturn strings.Join(components, \",\")\n}"} {"input": "package fileutil\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\ntype unixLock struct {\n\tf *os.File\n}\n\n\n\nfunc (l *unixLock) set(lock bool) error {\n\tflock := syscall.Flock_t{\n\t\tType: syscall.F_UNLCK,\n\t\tStart: 0,\n\t\tLen: 0,\n\t\tWhence: 1,\n\t}\n\tif lock {\n\t\tflock.Type = syscall.F_WRLCK\n\t}\n\treturn syscall.FcntlFlock(l.f.Fd(), syscall.F_SETLK, &flock)\n}\n\nfunc newLock(fileName string) (Releaser, error) {\n\tf, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tl := &unixLock{f}\n\terr = l.set(true)\n\tif err != nil {\n\t\tf.Close()\n\t\treturn nil, err\n\t}\n\treturn l, nil\n}\n\nfunc (l *unixLock) Release() error ", "output": "{\n\tif err := l.set(false); err != nil {\n\t\treturn err\n\t}\n\treturn l.f.Close()\n}"} {"input": "package html_test\n\nimport (\n\t\"fmt\"\n\t\"html\"\n)\n\n\n\nfunc ExampleUnescapeString() {\n\tconst s = `"Fran & Freddie's Diner" <tasty@example.com>`\n\tfmt.Println(html.UnescapeString(s))\n}\n\nfunc ExampleEscapeString() ", "output": "{\n\tconst s = `\"Fran & Freddie's Diner\" `\n\tfmt.Println(html.EscapeString(s))\n}"} {"input": "package gce\n\nimport (\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\ntype GCEAPITarget struct {\n\tCloud *GCECloud\n}\n\nvar _ fi.Target = &GCEAPITarget{}\n\nfunc NewGCEAPITarget(cloud *GCECloud) *GCEAPITarget {\n\treturn &GCEAPITarget{\n\t\tCloud: cloud,\n\t}\n}\n\n\n\nfunc (t *GCEAPITarget) Finish(taskMap map[string]fi.Task) error ", "output": "{\n\treturn nil\n}"} {"input": "package v1beta1\n\nimport (\n\tv1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\twatch \"k8s.io/apimachinery/pkg/watch\"\n\trest \"k8s.io/client-go/rest\"\n\tv1beta1 \"k8s.io/metrics/pkg/apis/metrics/v1beta1\"\n\tscheme \"k8s.io/metrics/pkg/client/clientset_generated/clientset/scheme\"\n)\n\n\n\ntype NodeMetricsesGetter interface {\n\tNodeMetricses() NodeMetricsInterface\n}\n\n\ntype NodeMetricsInterface interface {\n\tGet(name string, options v1.GetOptions) (*v1beta1.NodeMetrics, error)\n\tList(opts v1.ListOptions) (*v1beta1.NodeMetricsList, error)\n\tWatch(opts v1.ListOptions) (watch.Interface, error)\n\tNodeMetricsExpansion\n}\n\n\ntype nodeMetricses struct {\n\tclient rest.Interface\n}\n\n\nfunc newNodeMetricses(c *MetricsV1beta1Client) *nodeMetricses {\n\treturn &nodeMetricses{\n\t\tclient: c.RESTClient(),\n\t}\n}\n\n\n\n\n\nfunc (c *nodeMetricses) List(opts v1.ListOptions) (result *v1beta1.NodeMetricsList, err error) {\n\tresult = &v1beta1.NodeMetricsList{}\n\terr = c.client.Get().\n\t\tResource(\"nodes\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}\n\n\nfunc (c *nodeMetricses) Watch(opts v1.ListOptions) (watch.Interface, error) {\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"nodes\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tWatch()\n}\n\nfunc (c *nodeMetricses) Get(name string, options v1.GetOptions) (result *v1beta1.NodeMetrics, err error) ", "output": "{\n\tresult = &v1beta1.NodeMetrics{}\n\terr = c.client.Get().\n\t\tResource(\"nodes\").\n\t\tName(name).\n\t\tVersionedParams(&options, scheme.ParameterCodec).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}"} {"input": "package samples\n\n\n\nfunc init() ", "output": "{\n\n\tsampleDataCustomOperation[2] = `{\n \"data\": \"466f6f626172\",\n \"fee\": {\n \"amount\": 164678,\n \"asset_id\": \"1.3.0\"\n },\n \"id\": 16,\n \"payer\": \"1.2.30127\",\n \"required_auths\": [\n \"1.2.30127\"\n ]\n}`\n\n}"} {"input": "package main\n\n\nimport \"C\"\nimport \"./windows\"\n\n\n\nfunc CgoDLLImportsMain() {\n\tC.getthread()\n\twindows.GetThread()\n\tprintln(\"OK\")\n}\n\nfunc init() ", "output": "{\n\tregister(\"CgoDLLImportsMain\", CgoDLLImportsMain)\n}"} {"input": "package pending\n\nimport (\n\t\"time\"\n\n\t\"github.com/bulletind/khabar/config\"\n\t\"github.com/bulletind/khabar/db\"\n\t\"github.com/bulletind/khabar/utils\"\n)\n\n\n\nfunc Throttled(pending_item *db.PendingItem) bool ", "output": "{\n\tvar query utils.M = make(utils.M)\n\tlatency := config.Settings.Khabar.Throttling * int64(time.Minute/time.Millisecond)\n\n\tquery[\"org\"] = pending_item.Organization\n\tquery[\"app_name\"] = pending_item.AppName\n\tquery[\"topic\"] = pending_item.Topic\n\tquery[\"user\"] = pending_item.User\n\tquery[\"created_by\"] = pending_item.CreatedBy\n\tquery[\"created_on\"] = utils.M{\"$gt\": utils.EpochNow() - latency}\n\tquery[\"entity\"] = pending_item.Entity\n\n\tcount := db.Conn.Count(db.SentCollection, query)\n\n\treturn count > 0\n}"} {"input": "package initializer\n\nimport (\n\t\"k8s.io/apiserver/pkg/admission\"\n\t\"k8s.io/apiserver/pkg/authorization/authorizer\"\n\t\"k8s.io/client-go/informers\"\n\t\"k8s.io/client-go/kubernetes\"\n)\n\ntype pluginInitializer struct {\n\texternalClient kubernetes.Interface\n\texternalInformers informers.SharedInformerFactory\n\tauthorizer authorizer.Authorizer\n\tserverIdentifyingClientCert []byte\n\tserverIdentifyingClientKey []byte\n}\n\n\n\nfunc New(extClientset kubernetes.Interface, extInformers informers.SharedInformerFactory, authz authorizer.Authorizer, serverIdentifyingClientCert, serverIdentifyingClientKey []byte) (pluginInitializer, error) {\n\treturn pluginInitializer{\n\t\texternalClient: extClientset,\n\t\texternalInformers: extInformers,\n\t\tauthorizer: authz,\n\t\tserverIdentifyingClientCert: serverIdentifyingClientCert,\n\t\tserverIdentifyingClientKey: serverIdentifyingClientKey,\n\t}, nil\n}\n\n\n\n\n\nvar _ admission.PluginInitializer = pluginInitializer{}\n\nfunc (i pluginInitializer) Initialize(plugin admission.Interface) ", "output": "{\n\tif wants, ok := plugin.(WantsExternalKubeClientSet); ok {\n\t\twants.SetExternalKubeClientSet(i.externalClient)\n\t}\n\n\tif wants, ok := plugin.(WantsExternalKubeInformerFactory); ok {\n\t\twants.SetExternalKubeInformerFactory(i.externalInformers)\n\t}\n\n\tif wants, ok := plugin.(WantsAuthorizer); ok {\n\t\twants.SetAuthorizer(i.authorizer)\n\t}\n\n\tif wants, ok := plugin.(WantsClientCert); ok {\n\t\twants.SetClientCert(i.serverIdentifyingClientCert, i.serverIdentifyingClientKey)\n\t}\n}"} {"input": "package docker\n\nimport (\n\tcomposeConfig \"github.com/docker/libcompose/config\"\n\t\"github.com/docker/libcompose/docker\"\n\t\"github.com/docker/libcompose/project\"\n\t\"github.com/rancher/os/util\"\n)\n\ntype ServiceFactory struct {\n\tContext *docker.Context\n\tDeps map[string][]string\n}\n\n\n\nfunc (s *ServiceFactory) Create(project *project.Project, name string, serviceConfig *composeConfig.ServiceConfig) (project.Service, error) ", "output": "{\n\tif after := serviceConfig.Labels[\"io.rancher.os.after\"]; after != \"\" {\n\t\tfor _, dep := range util.TrimSplit(after, \",\") {\n\t\t\ts.Deps[name] = append(s.Deps[name], dep)\n\t\t}\n\t}\n\tif before := serviceConfig.Labels[\"io.rancher.os.before\"]; before != \"\" {\n\t\tfor _, dep := range util.TrimSplit(before, \",\") {\n\t\t\ts.Deps[dep] = append(s.Deps[dep], name)\n\t\t}\n\t}\n\n\treturn NewService(s, name, serviceConfig, s.Context, project), nil\n}"} {"input": "package openstack\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gophercloud/gophercloud\"\n\ttokens2 \"github.com/gophercloud/gophercloud/openstack/identity/v2/tokens\"\n\ttokens3 \"github.com/gophercloud/gophercloud/openstack/identity/v3/tokens\"\n)\n\n\n\ntype ErrEndpointNotFound struct{ gophercloud.BaseError }\n\nfunc (e ErrEndpointNotFound) Error() string {\n\treturn \"No suitable endpoint could be found in the service catalog.\"\n}\n\n\n\ntype ErrInvalidAvailabilityProvided struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrInvalidAvailabilityProvided) Error() string {\n\treturn fmt.Sprintf(\"Unexpected availability in endpoint query: %s\", e.Value)\n}\n\n\n\ntype ErrMultipleMatchingEndpointsV2 struct {\n\tgophercloud.BaseError\n\tEndpoints []tokens2.Endpoint\n}\n\nfunc (e ErrMultipleMatchingEndpointsV2) Error() string {\n\treturn fmt.Sprintf(\"Discovered %d matching endpoints: %#v\", len(e.Endpoints), e.Endpoints)\n}\n\n\n\ntype ErrMultipleMatchingEndpointsV3 struct {\n\tgophercloud.BaseError\n\tEndpoints []tokens3.Endpoint\n}\n\nfunc (e ErrMultipleMatchingEndpointsV3) Error() string {\n\treturn fmt.Sprintf(\"Discovered %d matching endpoints: %#v\", len(e.Endpoints), e.Endpoints)\n}\n\n\n\ntype ErrNoAuthURL struct{ gophercloud.ErrInvalidInput }\n\n\n\n\n\ntype ErrNoUsername struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoUsername) Error() string {\n\treturn \"Environment variable OS_USERNAME needs to be set.\"\n}\n\n\n\ntype ErrNoPassword struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoPassword) Error() string {\n\treturn \"Environment variable OS_PASSWORD needs to be set.\"\n}\n\nfunc (e ErrNoAuthURL) Error() string ", "output": "{\n\treturn \"Environment variable OS_AUTH_URL needs to be set.\"\n}"} {"input": "package iso20022\n\n\ntype FundSettlementParameters3 struct {\n\n\tSettlementDate *ISODate `xml:\"SttlmDt,omitempty\"`\n\n\tSettlementPlace *PartyIdentification2Choice `xml:\"SttlmPlc\"`\n\n\tSafekeepingPlace *PartyIdentification2Choice `xml:\"SfkpgPlc,omitempty\"`\n\n\tSecuritiesSettlementSystemIdentification *Max35Text `xml:\"SctiesSttlmSysId,omitempty\"`\n\n\tReceivingSideDetails *ReceivingPartiesAndAccount3 `xml:\"RcvgSdDtls,omitempty\"`\n\n\tDeliveringSideDetails *DeliveringPartiesAndAccount3 `xml:\"DlvrgSdDtls\"`\n}\n\nfunc (f *FundSettlementParameters3) SetSettlementDate(value string) {\n\tf.SettlementDate = (*ISODate)(&value)\n}\n\n\n\nfunc (f *FundSettlementParameters3) AddSafekeepingPlace() *PartyIdentification2Choice {\n\tf.SafekeepingPlace = new(PartyIdentification2Choice)\n\treturn f.SafekeepingPlace\n}\n\nfunc (f *FundSettlementParameters3) SetSecuritiesSettlementSystemIdentification(value string) {\n\tf.SecuritiesSettlementSystemIdentification = (*Max35Text)(&value)\n}\n\nfunc (f *FundSettlementParameters3) AddReceivingSideDetails() *ReceivingPartiesAndAccount3 {\n\tf.ReceivingSideDetails = new(ReceivingPartiesAndAccount3)\n\treturn f.ReceivingSideDetails\n}\n\nfunc (f *FundSettlementParameters3) AddDeliveringSideDetails() *DeliveringPartiesAndAccount3 {\n\tf.DeliveringSideDetails = new(DeliveringPartiesAndAccount3)\n\treturn f.DeliveringSideDetails\n}\n\nfunc (f *FundSettlementParameters3) AddSettlementPlace() *PartyIdentification2Choice ", "output": "{\n\tf.SettlementPlace = new(PartyIdentification2Choice)\n\treturn f.SettlementPlace\n}"} {"input": "package fakes\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/concourse/atc/db\"\n\t\"github.com/concourse/atc/lostandfound\"\n\t\"github.com/pivotal-golang/lager\"\n)\n\ntype FakeRunnerDB struct {\n\tLeaseCacheInvalidationStub func(logger lager.Logger, interval time.Duration) (db.Lease, bool, error)\n\tleaseCacheInvalidationMutex sync.RWMutex\n\tleaseCacheInvalidationArgsForCall []struct {\n\t\tlogger lager.Logger\n\t\tinterval time.Duration\n\t}\n\tleaseCacheInvalidationReturns struct {\n\t\tresult1 db.Lease\n\t\tresult2 bool\n\t\tresult3 error\n\t}\n}\n\n\n\nfunc (fake *FakeRunnerDB) LeaseCacheInvalidationCallCount() int {\n\tfake.leaseCacheInvalidationMutex.RLock()\n\tdefer fake.leaseCacheInvalidationMutex.RUnlock()\n\treturn len(fake.leaseCacheInvalidationArgsForCall)\n}\n\nfunc (fake *FakeRunnerDB) LeaseCacheInvalidationArgsForCall(i int) (lager.Logger, time.Duration) {\n\tfake.leaseCacheInvalidationMutex.RLock()\n\tdefer fake.leaseCacheInvalidationMutex.RUnlock()\n\treturn fake.leaseCacheInvalidationArgsForCall[i].logger, fake.leaseCacheInvalidationArgsForCall[i].interval\n}\n\nfunc (fake *FakeRunnerDB) LeaseCacheInvalidationReturns(result1 db.Lease, result2 bool, result3 error) {\n\tfake.LeaseCacheInvalidationStub = nil\n\tfake.leaseCacheInvalidationReturns = struct {\n\t\tresult1 db.Lease\n\t\tresult2 bool\n\t\tresult3 error\n\t}{result1, result2, result3}\n}\n\nvar _ lostandfound.RunnerDB = new(FakeRunnerDB)\n\nfunc (fake *FakeRunnerDB) LeaseCacheInvalidation(logger lager.Logger, interval time.Duration) (db.Lease, bool, error) ", "output": "{\n\tfake.leaseCacheInvalidationMutex.Lock()\n\tfake.leaseCacheInvalidationArgsForCall = append(fake.leaseCacheInvalidationArgsForCall, struct {\n\t\tlogger lager.Logger\n\t\tinterval time.Duration\n\t}{logger, interval})\n\tfake.leaseCacheInvalidationMutex.Unlock()\n\tif fake.LeaseCacheInvalidationStub != nil {\n\t\treturn fake.LeaseCacheInvalidationStub(logger, interval)\n\t} else {\n\t\treturn fake.leaseCacheInvalidationReturns.result1, fake.leaseCacheInvalidationReturns.result2, fake.leaseCacheInvalidationReturns.result3\n\t}\n}"} {"input": "package drum\n\nimport \"fmt\"\n\n\n\ntype Pattern struct {\n\tversion Version\n\ttempo Tempo\n\ttracks Tracks\n}\n\nfunc (p Pattern) String() string {\n\treturn fmt.Sprintf(\"%s\\n%s\\n%s\", p.version.String(), p.tempo.String(), p.tracks.String())\n}\n\n\ntype Version string\n\nfunc (v Version) String() string {\n\treturn fmt.Sprintf(\"Saved with HW Version: %s\", string(v))\n}\n\n\ntype Tempo float64\n\nfunc (t Tempo) String() string {\n\treturn fmt.Sprintf(\"Tempo: %.3g\", t)\n}\n\n\ntype Tracks []Track\n\nfunc (t Tracks) String() string {\n\tpretty := \"\"\n\tfor _, track := range t {\n\t\tpretty = fmt.Sprintf(\"%s%s\\n\", pretty, track.String())\n\t}\n\treturn pretty\n}\n\n\ntype Track struct {\n\tID int\n\tName string\n\tSteps Steps\n}\n\n\n\n\ntype Steps struct {\n\tBars [4]Bar\n}\n\nfunc (s Steps) String() string {\n\tpretty := \"|\"\n\tfor _, bar := range s.Bars {\n\t\tpretty = pretty + bar.String() + \"|\"\n\t}\n\treturn pretty\n}\n\n\ntype Bar [4]Note\n\nfunc (bar Bar) String() string {\n\tpretty := \"\"\n\tfor _, note := range bar {\n\t\tpretty = pretty + note.String()\n\t}\n\treturn pretty\n}\n\n\ntype Note bool\n\nfunc (n Note) String() string {\n\tif n {\n\t\treturn \"x\"\n\t}\n\treturn \"-\"\n}\n\nfunc (t Track) String() string ", "output": "{\n\treturn fmt.Sprintf(\"(%d) %s\\t%s\", t.ID, t.Name, t.Steps.String())\n}"} {"input": "package migrator\n\nimport (\n\t\"github.com/cgrates/cgrates/engine\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc (m *Migrator) migrateCurrentTPratingplans() (err error) {\n\ttpids, err := m.storDBIn.StorDB().GetTpIds(utils.TBLTPRatingPlans)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, tpid := range tpids {\n\t\tids, err := m.storDBIn.StorDB().GetTpTableIds(tpid, utils.TBLTPRatingPlans, utils.TPDistinctIds{\"tag\"}, map[string]string{}, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(ids) != 0 {\n\t\t\tfor _, id := range ids {\n\t\t\t\tratingPlan, err := m.storDBIn.StorDB().GetTPRatingPlans(tpid, id, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif ratingPlan != nil {\n\t\t\t\t\tif m.dryRun != true {\n\t\t\t\t\t\tif err := m.storDBOut.StorDB().SetTPRatingPlans(ratingPlan); err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor _, ratPln := range ratingPlan {\n\t\t\t\t\t\t\tif err := m.storDBIn.StorDB().RemTpData(utils.TBLTPRatingPlans, ratPln.TPid, map[string]string{\"tag\": ratPln.ID}); err != nil {\n\t\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tm.stats[utils.TpRatingPlans] += 1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\n\n\nfunc (m *Migrator) migrateTPratingplans() (err error) ", "output": "{\n\tvar vrs engine.Versions\n\tcurrent := engine.CurrentStorDBVersions()\n\tif vrs, err = m.getVersions(utils.TpRatingPlans); err != nil {\n\t\treturn\n\t}\n\tswitch vrs[utils.TpRatingPlans] {\n\tcase current[utils.TpRatingPlans]:\n\t\tif m.sameStorDB {\n\t\t\tbreak\n\t\t}\n\t\tif err := m.migrateCurrentTPratingplans(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn m.ensureIndexesStorDB(utils.TBLTPRatingPlans)\n}"} {"input": "package crypto\n\nimport (\n\t\"errors\"\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"encoding/pem\"\n)\n\nfunc LoadRSAPrivateKey(key []byte) (*rsa.PrivateKey, error) {\n\tparsed_key, err := LoadPrivateKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar rsa_private_key *rsa.PrivateKey\n\tvar ok bool = false\n\trsa_private_key, ok = parsed_key.(*rsa.PrivateKey)\n\tif !ok {\n\t\treturn nil, errors.New(\"invalid RSA private key.\")\n\t}\n\n\treturn rsa_private_key, nil\n}\n\nfunc LoadRSAPublicKey(key []byte) (*rsa.PublicKey, error) {\n\tparsed_key, err := LoadPublicKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar rsa_public_key *rsa.PublicKey\n\tvar ok bool = false\n\trsa_public_key, ok = parsed_key.(*rsa.PublicKey)\n\tif !ok {\n\t\treturn nil, errors.New(\"invalid RSA public key.\")\n\t}\n\n\treturn rsa_public_key, nil\n}\n\n\n\nfunc CreateRSAPublicKeyPEM(pubkey *rsa.PublicKey) ([]byte, error) {\n\tder, err := x509.MarshalPKIXPublicKey(pubkey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata := pem.EncodeToMemory(\n\t\t&pem.Block{\n\t\t\tType: \"RSA PUBLIC KEY\",\n\t\t\tBytes: der,\n\t\t},\n\t)\n\n\treturn data, nil\n}\n\nfunc CreateRSAPrivateKeyPEM(prvkey *rsa.PrivateKey) ([]byte, error) ", "output": "{\n\tder := x509.MarshalPKCS1PrivateKey(prvkey)\n\tdata := pem.EncodeToMemory(\n\t\t&pem.Block{\n\t\t\tType: \"RSA PRIVATE KEY\",\n\t\t\tBytes: der,\n\t\t},\n\t)\n\n\treturn data, nil\n}"} {"input": "package fib\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestFib(t *testing.T) ", "output": "{\n\tvar a []string\n\n\tfor v := range Fib(10) {\n\t\ta = append(a, strconv.Itoa(v))\n\t}\n\n\tactual := strings.Join(a, \", \")\n\tif actual != \"0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55\" {\n\t\tt.Errorf(\"error: %v\", actual)\n\t}\n}"} {"input": "package moss\n\nimport (\n\t\"github.com/couchbase/moss\"\n\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\ntype Batch struct {\n\tstore *Store\n\tmerge *store.EmulatedMerge\n\tbatch moss.Batch\n\tbuf []byte \n\tbufUsed int\n}\n\nfunc (b *Batch) Set(key, val []byte) {\n\tvar err error\n\tif b.buf != nil {\n\t\tb.bufUsed += len(key) + len(val)\n\t\terr = b.batch.AllocSet(key, val)\n\t} else {\n\t\terr = b.batch.Set(key, val)\n\t}\n\n\tif err != nil {\n\t\tb.store.Logf(\"bleve moss batch.Set err: %v\", err)\n\t}\n}\n\n\n\nfunc (b *Batch) Merge(key, val []byte) {\n\tif b.buf != nil {\n\t\tb.bufUsed += len(key) + len(val)\n\t}\n\tb.merge.Merge(key, val)\n}\n\nfunc (b *Batch) Reset() {\n\terr := b.Close()\n\tif err != nil {\n\t\tb.store.Logf(\"bleve moss batch.Close err: %v\", err)\n\t\treturn\n\t}\n\n\tbatch, err := b.store.ms.NewBatch(0, 0)\n\tif err == nil {\n\t\tb.batch = batch\n\t\tb.merge = store.NewEmulatedMerge(b.store.mo)\n\t\tb.buf = nil\n\t\tb.bufUsed = 0\n\t}\n}\n\nfunc (b *Batch) Close() error {\n\tb.merge = nil\n\terr := b.batch.Close()\n\tb.batch = nil\n\treturn err\n}\n\nfunc (b *Batch) Delete(key []byte) ", "output": "{\n\tvar err error\n\tif b.buf != nil {\n\t\tb.bufUsed += len(key)\n\t\terr = b.batch.AllocDel(key)\n\t} else {\n\t\terr = b.batch.Del(key)\n\t}\n\n\tif err != nil {\n\t\tb.store.Logf(\"bleve moss batch.Delete err: %v\", err)\n\t}\n}"} {"input": "package testing\n\nimport (\n\t\"time\"\n\n\t\"github.com/zinic/protobus/bus\"\n\t\"github.com/zinic/protobus/concurrent\"\n)\n\nfunc NewInjector(event bus.Event, interval time.Duration) (injector bus.Source) {\n\treturn &InjectorSource {\n\t\tevent: event,\n\t\trunning: concurrent.NewReferenceLocker(false),\n\t\tinterval: interval,\n\t}\n}\n\ntype InjectorSource struct {\n\tevent bus.Event\n\trunning concurrent.ReferenceLocker\n\tinterval time.Duration\n}\n\n\n\nfunc (injector *InjectorSource) Stop() (err error) {\n\tinjector.running.Set(false)\n\treturn\n}\n\nfunc (injector *InjectorSource) Start(outgoing chan<- bus.Event, actx bus.ActorContext) (err error) ", "output": "{\n\tinjector.running.Set(true)\n\n\tvar elapsedNanos int64 = 0\n\tfor injector.running.Get().(bool) {\n\t\tthen := time.Now()\n\n\t\tif elapsedNanos >= injector.interval.Nanoseconds() {\n\t\t\telapsedNanos = 0\n\t\t\toutgoing <- injector.event\n\t\t}\n\n\t\ttime.Sleep(1 * time.Millisecond)\n\t\telapsedNanos += time.Now().Sub(then).Nanoseconds()\n\t}\n\n\treturn\n}"} {"input": "package handlers\n\nimport (\n\t\"net/http\"\n\n\t\"code.cloudfoundry.org/bbs\"\n\t\"code.cloudfoundry.org/bbs/models\"\n\t\"code.cloudfoundry.org/lager\"\n)\n\ntype StopAppHandler struct {\n\tbbsClient bbs.Client\n\tlogger lager.Logger\n}\n\n\n\nfunc (h *StopAppHandler) StopApp(resp http.ResponseWriter, req *http.Request) {\n\tprocessGuid := req.FormValue(\":process_guid\")\n\n\tlogger := h.logger.Session(\"stop-app\", lager.Data{\n\t\t\"process-guid\": processGuid,\n\t\t\"method\": req.Method,\n\t\t\"request\": req.URL.String(),\n\t})\n\n\tif processGuid == \"\" {\n\t\tlogger.Error(\"missing-process-guid\", missingParameterErr)\n\t\tresp.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlogger.Info(\"serving\")\n\tdefer logger.Info(\"complete\")\n\n\tlogger.Debug(\"removing-desired-lrp\")\n\terr := h.bbsClient.RemoveDesiredLRP(logger, processGuid)\n\tif err != nil {\n\t\tlogger.Error(\"failed-to-remove-desired-lrp\", err)\n\n\t\tbbsError := models.ConvertError(err)\n\t\tif bbsError.Type == models.Error_ResourceNotFound {\n\t\t\tresp.WriteHeader(http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\n\t\tresp.WriteHeader(http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\tlogger.Debug(\"removed-desired-lrp\")\n\n\tresp.WriteHeader(http.StatusAccepted)\n}\n\nfunc NewStopAppHandler(logger lager.Logger, bbsClient bbs.Client) *StopAppHandler ", "output": "{\n\treturn &StopAppHandler{\n\t\tlogger: logger,\n\t\tbbsClient: bbsClient,\n\t}\n}"} {"input": "package dynamo\n\nimport (\n\t\"errors\"\n\n\t\"golang.org/x/crypto/acme/autocert\"\n)\n\n\ntype Provider struct {\n\tclient *client\n}\n\n\nfunc NewProvider() *Provider {\n\treturn new(Provider)\n}\n\n\nfunc (p *Provider) Name() string {\n\treturn \"dynamodb\"\n}\n\n\nfunc (p *Provider) Configure(config map[string]interface{}) (err error) {\n\tconst prefix = \"unable to configure DynamoDB provider\"\n\tif config == nil {\n\t\treturn errors.New(prefix + \", no configuration provided\")\n\t}\n\n\tregion := get(config, \"region\", \"\")\n\tif region == \"\" {\n\t\treturn errors.New(prefix + \", no AWS Region was specified\")\n\t}\n\n\ttable := get(config, \"table\", \"\")\n\tif table == \"\" {\n\t\treturn errors.New(prefix + \", no Table Name was specified\")\n\t}\n\n\tkeyColumn := get(config, \"keyColumn\", \"key\")\n\tvalColumn := get(config, \"valueColumn\", \"value\")\n\n\tif p.client, err = newClient(region, table, keyColumn, valColumn); err == nil {\n\t\tif _, err := p.client.Get(\"testkey\"); err == nil && err == errKeyNotFound {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn err\n}\n\n\nfunc (p *Provider) GetSecret(secretName string) (string, bool) {\n\tif p.client != nil {\n\t\tif value, err := p.client.Get(secretName); err == nil {\n\t\t\treturn value, true\n\t\t}\n\t}\n\n\treturn \"\", false\n}\n\n\n\n\n\nfunc get(config map[string]interface{}, key, defaultValue string) string {\n\tif v, ok := config[key]; ok {\n\t\tif s, ok := v.(string); ok {\n\t\t\treturn s\n\t\t}\n\t}\n\treturn defaultValue\n}\n\nfunc (p *Provider) GetCache() (autocert.Cache, bool) ", "output": "{\n\tif p.client != nil {\n\t\treturn newCache(p.client), true\n\t}\n\n\treturn nil, false\n}"} {"input": "package admin\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\n\t\"github.com/heketi/heketi/pkg/glusterfs/api\"\n)\n\n\n\nfunc ResetStateOnSignal(s *ServerState, sig ...os.Signal) ", "output": "{\n\tsignalch := make(chan os.Signal, 1)\n\tsignal.Notify(signalch, sig...)\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-signalch:\n\t\t\t\ts.Set(api.AdminStateNormal)\n\t\t\t}\n\t\t}\n\t}()\n}"} {"input": "package iso20022\n\n\ntype OriginalItem4 struct {\n\n\tOriginalItemIdentification *Max35Text `xml:\"OrgnlItmId\"`\n\n\tOriginalEndToEndIdentification *Max35Text `xml:\"OrgnlEndToEndId,omitempty\"`\n\n\tAmount *ActiveOrHistoricCurrencyAndAmount `xml:\"Amt\"`\n\n\tExpectedValueDate *ISODate `xml:\"XpctdValDt,omitempty\"`\n\n\tOriginalItemReference *OriginalItemReference3 `xml:\"OrgnlItmRef,omitempty\"`\n}\n\nfunc (o *OriginalItem4) SetOriginalItemIdentification(value string) {\n\to.OriginalItemIdentification = (*Max35Text)(&value)\n}\n\nfunc (o *OriginalItem4) SetOriginalEndToEndIdentification(value string) {\n\to.OriginalEndToEndIdentification = (*Max35Text)(&value)\n}\n\nfunc (o *OriginalItem4) SetAmount(value, currency string) {\n\to.Amount = NewActiveOrHistoricCurrencyAndAmount(value, currency)\n}\n\n\n\nfunc (o *OriginalItem4) AddOriginalItemReference() *OriginalItemReference3 {\n\to.OriginalItemReference = new(OriginalItemReference3)\n\treturn o.OriginalItemReference\n}\n\nfunc (o *OriginalItem4) SetExpectedValueDate(value string) ", "output": "{\n\to.ExpectedValueDate = (*ISODate)(&value)\n}"} {"input": "package server\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n)\n\nconst (\n\tChatReqTypeSetNickname = 101 + iota\n\tChatReqTypeGetNickname\n\tChatReqTypeListRooms\n\tChatReqTypeJoin\n\tChatReqTypeListNames\n\tChatReqTypeHide\n\tChatReqTypeUnhide\n\tChatReqTypeMsg\n\tChatReqTypeLeave\n)\n\n\ntype ChatRequest struct {\n\tWho *Chatter `json:\"-\"` \n\tRoomName string `json:\"roomName\"` \n\tReqType int `json:\"reqType\"` \n\tContent string `json:\"content\"` \n}\n\n\nfunc ChatRequestNew(c *Chatter, room string, reqt int, cont string) (*ChatRequest, error) {\n\tif reqt < ChatReqTypeSetNickname || reqt > ChatReqTypeLeave {\n\t\treturn nil, errors.New(\"Request Type is out of range.\")\n\t}\n\treturn &ChatRequest{\n\t\tWho: c,\n\t\tRoomName: room,\n\t\tReqType: reqt,\n\t\tContent: cont,\n\t}, nil\n}\n\n\n\n\n\nfunc (r *ChatRequest) String() string ", "output": "{\n\tb, _ := json.Marshal(r)\n\treturn string(b)\n}"} {"input": "package measurers\n\nimport \"syscall\"\n\ntype DiskSpaceMeasurer struct {\n\tpath string\n}\n\nfunc NewDiskSpaceMeasurer(path string) *DiskSpaceMeasurer {\n\treturn &DiskSpaceMeasurer{path: path}\n}\n\n\n\nfunc (m *DiskSpaceMeasurer) Measure() (float64, error) ", "output": "{\n\tvar res syscall.Statfs_t\n\tif err := syscall.Statfs(m.path, &res); err != nil {\n\t\treturn 0, err\n\t}\n\treturn float64(res.Blocks-res.Bavail) * float64(res.Bsize), nil\n}"} {"input": "package events\n\nimport (\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/gravitational/teleport/lib/session\"\n)\n\n\n\ntype DiscardAuditLog struct {\n}\n\nfunc (d *DiscardAuditLog) Close() error {\n\treturn nil\n}\n\nfunc (d *DiscardAuditLog) EmitAuditEvent(eventType string, fields EventFields) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionChunk(namespace string, sid session.ID, reader io.Reader) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionSlice(SessionSlice) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\nfunc (d *DiscardAuditLog) GetSessionEvents(namespace string, sid session.ID, after int) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchEvents(fromUTC, toUTC time.Time, query string) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchSessionEvents(fromUTC time.Time, toUTC time.Time) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\n\n\n\n\ntype discardSessionLogger struct {\n}\n\nfunc (d *discardSessionLogger) LogEvent(fields EventFields) {\n\treturn\n}\n\nfunc (d *discardSessionLogger) Close() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) Finalize() error {\n\treturn nil\n}\n\n\n\nfunc (d *discardSessionLogger) WriteChunk(chunk *SessionChunk) (written int, err error) ", "output": "{\n\treturn 0, nil\n}"} {"input": "package input\n\nimport (\n\t\"encoding/xml\"\n\t\"os\"\n)\n\ntype _summary struct {\n\tDeps _deps `xml:\"dependencies\"`\n}\n\ntype _deps struct {\n\tDependencies []Dependency `xml:\"dependency\"`\n}\n\n\ntype Dependency struct {\n\tGroupID string `xml:\"groupId\"`\n\tArtifactID string `xml:\"artifactId\"`\n\tVersion string `xml:\"version\"`\n\tLicenses Licenses `xml:\"licenses\"`\n}\n\n\ntype Licenses struct {\n\tLicenses []License `xml:\"license\"`\n}\n\n\ntype License struct {\n\tName string `xml:\"name\"`\n\tURL string `xml:\"url\"`\n\tDistribution string `xml:\"distribution\"`\n}\n\n\n\n\nfunc ReadLicenses(uri string) ([]Dependency, error) ", "output": "{\n\tfile, err := os.Open(uri)\n\n\tdefer file.Close()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar xmlSummary _summary\n\tif err := xml.NewDecoder(file).Decode(&xmlSummary); err != nil {\n\t\treturn nil, err\n\t}\n\treturn xmlSummary.Deps.Dependencies, nil\n}"} {"input": "package document\n\ntype IndexingOptions int\n\nconst (\n\tIndexField IndexingOptions = 1 << iota\n\tStoreField\n\tIncludeTermVectors\n)\n\nfunc (o IndexingOptions) IsIndexed() bool {\n\treturn o&IndexField != 0\n}\n\nfunc (o IndexingOptions) IsStored() bool {\n\treturn o&StoreField != 0\n}\n\nfunc (o IndexingOptions) IncludeTermVectors() bool {\n\treturn o&IncludeTermVectors != 0\n}\n\n\n\nfunc (o IndexingOptions) String() string ", "output": "{\n\trv := \"\"\n\tif o.IsIndexed() {\n\t\trv += \"INDEXED\"\n\t}\n\tif o.IsStored() {\n\t\tif rv != \"\" {\n\t\t\trv += \", \"\n\t\t}\n\t\trv += \"STORE\"\n\t}\n\tif o.IncludeTermVectors() {\n\t\tif rv != \"\" {\n\t\t\trv += \", \"\n\t\t}\n\t\trv += \"TV\"\n\t}\n\treturn rv\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/cihub/seelog\"\n)\n\n\nconst Succeed = \"\\u2713\"\n\n\nconst Failed = \"\\u2717\"\n\nfunc init() {\n\tseelogConfig := \"conf/seelog.xml.test\"\n\tlogger, err := seelog.LoggerFromConfigAsFile(seelogConfig)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"FOO Error creating Logger from seelog file: %s\", seelogConfig)\n\t\tseelog.Error(err)\n\t}\n\tdefer seelog.Flush()\n\tseelog.ReplaceLogger(logger)\n}\n\n\nfunc Context(t *testing.T, msg string, args ...interface{}) {\n\tt.Log(fmt.Sprintf(msg, args...))\n}\n\n\nfunc Fatal(t *testing.T, msg string, args ...interface{}) {\n\tm := fmt.Sprintf(msg, args...)\n\tt.Fatal(fmt.Sprintf(\"\\t %-80s\", m), Failed)\n}\n\n\nfunc Error(t *testing.T, msg string, args ...interface{}) {\n\tm := fmt.Sprintf(msg, args...)\n\tt.Error(fmt.Sprintf(\"\\t %-80s\", m), Failed)\n}\n\n\n\n\nfunc Success(t *testing.T, msg string, args ...interface{}) ", "output": "{\n\tm := fmt.Sprintf(msg, args...)\n\tt.Log(fmt.Sprintf(\"\\t %-80s\", m), Succeed)\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nvar Version string\nvar BuildDate string\nvar GitRevision string\n\n\n\n\nfunc NewVersionCommand() *cobra.Command ", "output": "{\n\treturn &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Prints the plugin version\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tout := cmd.OutOrStdout()\n\t\t\tfmt.Fprintf(out, \"Version: %s\\n\", Version)\n\t\t\tfmt.Fprintf(out, \"Build Date: %s\\n\", BuildDate)\n\t\t\tfmt.Fprintf(out, \"Git Revision: %s\\n\", GitRevision)\n\t\t\treturn nil\n\t\t},\n\t}\n}"} {"input": "package flatmap\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\nfunc Expand(m map[string]string, key string) interface{} {\n\tif v, ok := m[key]; ok {\n\t\tif v == \"true\" {\n\t\t\treturn true\n\t\t} else if v == \"false\" {\n\t\t\treturn false\n\t\t}\n\n\t\treturn v\n\t}\n\n\tif _, ok := m[key+\".#\"]; ok {\n\t\treturn expandArray(m, key)\n\t}\n\n\tprefix := key + \".\"\n\tfor k, _ := range m {\n\t\tif strings.HasPrefix(k, prefix) {\n\t\t\treturn expandMap(m, prefix)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc expandMap(m map[string]string, prefix string) map[string]interface{} {\n\tresult := make(map[string]interface{})\n\tfor k, _ := range m {\n\t\tif !strings.HasPrefix(k, prefix) {\n\t\t\tcontinue\n\t\t}\n\n\t\tkey := k[len(prefix):]\n\t\tidx := strings.Index(key, \".\")\n\t\tif idx != -1 {\n\t\t\tkey = key[:idx]\n\t\t}\n\t\tif _, ok := result[key]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tresult[key] = Expand(m, k[:len(prefix)+len(key)])\n\t}\n\n\treturn result\n}\n\nfunc expandArray(m map[string]string, prefix string) []interface{} ", "output": "{\n\tnum, err := strconv.ParseInt(m[prefix+\".#\"], 0, 0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tresult := make([]interface{}, num)\n\tfor i := 0; i < int(num); i++ {\n\t\tresult[i] = Expand(m, fmt.Sprintf(\"%s.%d\", prefix, i))\n\t}\n\n\treturn result\n}"} {"input": "package roles\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar TopLevelRoles = map[string]struct{}{\n\t\"root\": {},\n\t\"targets\": {},\n\t\"snapshot\": {},\n\t\"timestamp\": {},\n}\n\nfunc IsTopLevelRole(name string) bool {\n\t_, ok := TopLevelRoles[name]\n\treturn ok\n}\n\nfunc IsDelegatedTargetsRole(name string) bool {\n\treturn !IsTopLevelRole(name)\n}\n\n\n\nfunc IsDelegatedTargetsManifest(name string) bool {\n\treturn !IsTopLevelManifest(name)\n}\n\nfunc IsVersionedManifest(name string) bool {\n\tparts := strings.Split(name, \".\")\n\tif len(parts) < 3 {\n\t\treturn false\n\t}\n\n\t_, err := strconv.Atoi(parts[0])\n\treturn err == nil\n}\n\nfunc IsTopLevelManifest(name string) bool ", "output": "{\n\treturn IsTopLevelRole(strings.TrimSuffix(name, \".json\"))\n}"} {"input": "package main\n\nimport \"fmt\"\n\ntype Config struct {\n\tUsers `json:\"users,omitempty\" mapstructure:\",\"`\n\tUsersFile string `json:\"usersFile,omitempty\"`\n\tRealm string `json:\"realm,omitempty\"`\n\tRemoveHeader bool `json:\"removeHeader,omitempty\"`\n\tHeaderField string `json:\"headerField,omitempty\" export:\"true\"`\n}\n\n\ntype Users []string\n\n\n\nfunc main() {\n\tc := CreateConfig()\n\tfmt.Println(c)\n}\n\nfunc CreateConfig() *Config ", "output": "{\n\treturn &Config{}\n}"} {"input": "package gengen\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\n\t\"github.com/raphael/goa/goagen/codegen\"\n\t\"github.com/raphael/goa/goagen/meta\"\n)\n\nvar (\n\tGenPkgPath string\n\n\tGenPkgName string\n)\n\n\n\ntype Command struct {\n\t*codegen.BaseCommand\n}\n\n\nfunc NewCommand() *Command {\n\tbase := codegen.NewBaseCommand(\"gen\", \"Invoke third party generator\")\n\treturn &Command{BaseCommand: base}\n}\n\n\nfunc (c *Command) RegisterFlags(r codegen.FlagRegistry) {\n\tr.Flag(\"pkg-path\", \"Go package path to generator package. The package must implement the Generate global function.\").Required().StringVar(&GenPkgPath)\n\tr.Flag(\"pkg-name\", \"Go package name of generator package. Defaults to name of inner most directory in package path.\").StringVar(&GenPkgName)\n}\n\n\n\n\nfunc (c *Command) Run() ([]string, error) ", "output": "{\n\tif GenPkgName == \"\" {\n\t\tGenPkgName = filepath.ToSlash(filepath.Base(GenPkgPath))\n\t}\n\tgen := meta.NewGenerator(\n\t\tfmt.Sprintf(\"%s.Generate\", GenPkgName),\n\t\t[]*codegen.ImportSpec{codegen.SimpleImport(GenPkgPath)},\n\t\tnil,\n\t)\n\treturn gen.Generate()\n}"} {"input": "package iso20022\n\n\ntype DeliveryReturn4Choice struct {\n\n\tCode *DeliveryReturn1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification47 `xml:\"Prtry\"`\n}\n\nfunc (d *DeliveryReturn4Choice) SetCode(value string) {\n\td.Code = (*DeliveryReturn1Code)(&value)\n}\n\n\n\nfunc (d *DeliveryReturn4Choice) AddProprietary() *GenericIdentification47 ", "output": "{\n\td.Proprietary = new(GenericIdentification47)\n\treturn d.Proprietary\n}"} {"input": "package airac\n\nimport (\n\t\"math\"\n\t\"testing\"\n\n\t\"github.com/jwkohnen/airac/proto\"\n)\n\n\n\nfunc TestProtoOverflow(t *testing.T) {\n\twant := AIRAC(0)\n\tp := proto.AiracMessage{Airac19010110: math.MaxUint16 + 1}\n\tgot := FromProto(p)\n\tif got != want {\n\t\tt.Errorf(\"Want %s, got %s\", want, got)\n\t}\n}\n\nfunc TestProto(t *testing.T) ", "output": "{\n\tfor want := AIRAC(0); want < FromStringMust(\"9213\"); want++ {\n\t\tp := want.Proto()\n\t\tgot := FromProto(p)\n\t\tif want != got {\n\t\t\tt.Errorf(\"Want %v, got %x\", want, got)\n\t\t}\n\t}\n}"} {"input": "package nl\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\ntype RtMsg struct {\n\tsyscall.RtMsg\n}\n\nfunc NewRtMsg() *RtMsg {\n\treturn &RtMsg{\n\t\tRtMsg: syscall.RtMsg{\n\t\t\tTable: syscall.RT_TABLE_MAIN,\n\t\t\tScope: syscall.RT_SCOPE_UNIVERSE,\n\t\t\tProtocol: syscall.RTPROT_BOOT,\n\t\t\tType: syscall.RTN_UNICAST,\n\t\t},\n\t}\n}\n\nfunc NewRtDelMsg() *RtMsg {\n\treturn &RtMsg{\n\t\tRtMsg: syscall.RtMsg{\n\t\t\tTable: syscall.RT_TABLE_MAIN,\n\t\t\tScope: syscall.RT_SCOPE_NOWHERE,\n\t\t},\n\t}\n}\n\nfunc (msg *RtMsg) Len() int {\n\treturn syscall.SizeofRtMsg\n}\n\nfunc DeserializeRtMsg(b []byte) *RtMsg {\n\treturn (*RtMsg)(unsafe.Pointer(&b[0:syscall.SizeofRtMsg][0]))\n}\n\nfunc (msg *RtMsg) Serialize() []byte {\n\treturn (*(*[syscall.SizeofRtMsg]byte)(unsafe.Pointer(msg)))[:]\n}\n\ntype RtNexthop struct {\n\tsyscall.RtNexthop\n}\n\n\n\nfunc (msg *RtNexthop) Serialize() []byte {\n\treturn (*(*[syscall.SizeofRtNexthop]byte)(unsafe.Pointer(msg)))[:]\n}\n\nfunc DeserializeRtNexthop(b []byte) *RtNexthop ", "output": "{\n\treturn (*RtNexthop)(unsafe.Pointer(&b[0:syscall.SizeofRtNexthop][0]))\n}"} {"input": "package linux\n\nimport (\n\t\"testing\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestGetAdapters(t *testing.T) {\n\n\tlog.SetLevel(log.DebugLevel)\n\n\tlist, err := GetAdapters()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassert.NotEmpty(t, list)\n}\n\n\n\nfunc TestGetAdapterNotFound(t *testing.T) {\n\t_, err := GetAdapter(\"hci999\")\n\tif err == nil {\n\t\tt.Fatal(\"adapter should not exists\")\n\t}\n}\n\nfunc TestUp(t *testing.T) {\n\terr := Up(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDown(t *testing.T) {\n\terr := Down(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestReset(t *testing.T) {\n\terr := Reset(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestGetAdapter(t *testing.T) ", "output": "{\n\tlog.SetLevel(log.DebugLevel)\n\t_, err := GetAdapter(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package externalversions\n\nimport (\n\t\"fmt\"\n\n\tv1 \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1\"\n\tv1beta1 \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1\"\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tcache \"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}\n\n\nfunc (f *genericInformer) Lister() cache.GenericLister {\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}\n\n\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) ", "output": "{\n\tswitch resource {\n\tcase v1.SchemeGroupVersion.WithResource(\"customresourcedefinitions\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Apiextensions().V1().CustomResourceDefinitions().Informer()}, nil\n\n\tcase v1beta1.SchemeGroupVersion.WithResource(\"customresourcedefinitions\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Apiextensions().V1beta1().CustomResourceDefinitions().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}"} {"input": "package plain\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t. \"github.com/SimonRichardson/wishful-route/route\"\n\t. \"github.com/SimonRichardson/wishful/useful\"\n\t. \"github.com/SimonRichardson/wishful/wishful\"\n)\n\nfunc NewPlainResult(statusCode int, body string) Result {\n\treturn NewResult(body, statusCode, NewHeaders(map[string]string{\n\t\t\"Content-Length\": fmt.Sprintf(\"%d\", len(body)),\n\t\t\"Content-Type\": \"text/plain\",\n\t}))\n}\n\nfunc Ok(body string) Promise {\n\treturn NewPromise(func(resolve func(x AnyVal) AnyVal) AnyVal {\n\t\treturn resolve(NewPlainResult(http.StatusOK, body))\n\t})\n}\n\nfunc NotFound(body string) Promise {\n\treturn NewPromise(func(resolve func(x AnyVal) AnyVal) AnyVal {\n\t\treturn resolve(NewPlainResult(http.StatusNotFound, body))\n\t})\n}\n\nfunc InternalServerError(body string) Promise {\n\treturn NewPromise(func(resolve func(x AnyVal) AnyVal) AnyVal {\n\t\treturn resolve(NewPlainResult(http.StatusInternalServerError, body))\n\t})\n}\n\n\n\nfunc Redirect(url string) Promise ", "output": "{\n\treturn NewPromise(func(resolve func(x AnyVal) AnyVal) AnyVal {\n\t\treturn resolve(NewResult(\"\", http.StatusFound, NewHeaders(map[string]string{\n\t\t\t\"Location\": url,\n\t\t})))\n\t})\n}"} {"input": "package iso20022\n\n\ntype PartyIdentification45Choice struct {\n\n\tAnyBIC *AnyBICIdentifier `xml:\"AnyBIC\"`\n\n\tProprietaryIdentification *GenericIdentification19 `xml:\"PrtryId\"`\n\n\tNameAndAddress *NameAndAddress5 `xml:\"NmAndAdr\"`\n}\n\n\n\nfunc (p *PartyIdentification45Choice) AddProprietaryIdentification() *GenericIdentification19 {\n\tp.ProprietaryIdentification = new(GenericIdentification19)\n\treturn p.ProprietaryIdentification\n}\n\nfunc (p *PartyIdentification45Choice) AddNameAndAddress() *NameAndAddress5 {\n\tp.NameAndAddress = new(NameAndAddress5)\n\treturn p.NameAndAddress\n}\n\nfunc (p *PartyIdentification45Choice) SetAnyBIC(value string) ", "output": "{\n\tp.AnyBIC = (*AnyBICIdentifier)(&value)\n}"} {"input": "package content\nimport (\n\t\"go2o/src/core/domain/interface/content\"\n\t\"time\"\n)\n\nvar _ content.IPage = new(Page)\ntype Page struct{\n\t_contentRep content.IContentRep\n\t_partnerId int\n\t_value *content.ValuePage\n}\n\nfunc NewPage(partnerId int, rep content.IContentRep,v *content.ValuePage) content.IPage {\n\treturn &Page{\n\t\t_contentRep: rep,\n\t\t_partnerId: partnerId,\n\t\t_value:v,\n\t}\n}\n\n\n\nfunc (this *Page) GetDomainId() int{\n\treturn this._value.Id\n}\n\n\nfunc (this *Page) GetValue()*content.ValuePage{\n\treturn this._value\n}\n\n\n\n\n\nfunc (this *Page) Save()(int,error){\n\tthis._value.UpdateTime = time.Now().Unix()\n\treturn this._contentRep.SavePage(this._partnerId,this._value)\n}\n\nfunc (this *Page) SetValue(v *content.ValuePage)error", "output": "{\n\tv.Id = this.GetDomainId()\n\tthis._value = v\n\treturn nil\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestHashPassword(t *testing.T) {\n\tfmt.Println(HashAndSalt(\"123456\", \"245accec-3c12-4642-967f-e476cef558c0\"))\n}\n\nfunc TestIsBlank(t *testing.T) ", "output": "{\n\tif !IsBlank(\"\") {\n\t\tt.FailNow()\n\t}\n\n\tif !IsBlank(`\n\t`) {\n\t\tt.FailNow()\n\t}\n\n}"} {"input": "package main\n\nimport \"sort\"\n\ntype Node struct {\n\tLeft *Node\n\tRight *Node\n\tParent *Node\n\tValue uint\n\tFactor int\n}\n\nfunc GetHuffmanTree(arr []uint) *Node {\n\tm := make(map[uint]int)\n\tfor _, v := range arr {\n\t\tm[v]++\n\t}\n\tvar nodes []*Node\n\tfor k, v := range m {\n\t\tnodes = append(nodes, &Node{Value: k, Factor: v})\n\t}\n\tfor len(nodes) > 1 {\n\t\tsort.Slice(nodes, func(i, j int) bool {\n\t\t\treturn nodes[i].Factor < nodes[j].Factor\n\t\t})\n\t\tnewNode := &Node{Left: nodes[0], Right: nodes[1], Factor: nodes[0].Factor + nodes[1].Factor}\n\t\tnodes[0].Parent, nodes[1].Parent = newNode, newNode\n\t\tnodes = append(nodes[2:], newNode)\n\t}\n\tif len(nodes) == 1 {\n\t\treturn nodes[0]\n\t}\n\treturn nil\n}\n\nfunc GetHuffmanTableMap(root *Node) map[uint]string {\n\ttable := make(map[uint]string)\n\tscan(root, \"\", &table)\n\treturn table\n}\n\n\n\nfunc scan(root *Node, prefix string, table *map[uint]string) ", "output": "{\n\tif root.Left == nil || root.Right == nil {\n\t\t(*table)[root.Value] = prefix\n\t}\n\tif root.Left != nil {\n\t\tscan(root.Left, prefix + \"0\", table)\n\t}\n\tif root.Right != nil {\n\t\tscan(root.Right, prefix + \"1\", table)\n\t}\n}"} {"input": "package scrapers\n\nimport (\n\t\"golang.org/x/net/html\"\n\t\"golang.org/x/net/html/atom\"\n\t\"io\"\n)\n\n\ntype Parser struct {\n\treader io.Reader\n\tlinks []string\n}\n\n\nfunc NewParser(reader io.Reader) *Parser {\n\treturn &Parser{\n\t\treader: reader,\n\t\tlinks: make([]string, 0),\n\t}\n}\n\n\nfunc (p *Parser) Parse() error {\n\ttokenizer := html.NewTokenizer(p.reader)\n\n\tfor {\n\t\ttokenType := tokenizer.Next()\n\n\t\tswitch tokenType {\n\t\tcase html.ErrorToken:\n\t\t\terr := tokenizer.Err()\n\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\treturn err\n\n\t\tcase html.StartTagToken:\n\t\t\ttoken := tokenizer.Token()\n\n\t\t\tif token.DataAtom == atom.A {\n\t\t\t\tfor _, attribute := range token.Attr {\n\t\t\t\t\tif attribute.Key == \"href\" {\n\t\t\t\t\t\tlink := attribute.Val\n\n\t\t\t\t\t\tp.links = append(p.links, link)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n\nfunc (p *Parser) Links() []string ", "output": "{\n\treturn p.links\n}"} {"input": "package main\n\ntype TopicMessage struct {\n source *Client\n text string\n}\n\nfunc NewTopicMessage(source *Client, text string) *TopicMessage {\n return &TopicMessage{source, text}\n}\n\nfunc (this *TopicMessage) Source() *Client {\n return this.source\n}\n\n\n\nfunc (this *TopicMessage) Text() string ", "output": "{\n return this.text\n}"} {"input": "package archive\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/docker/docker/pkg/system\"\n)\n\n\n\nfunc collectFileInfo(sourceDir string) (*FileInfo, error) {\n\troot := newRootFileInfo()\n\n\terr := filepath.Walk(sourceDir, func(path string, f os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trelPath, err := filepath.Rel(sourceDir, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trelPath = filepath.Join(string(os.PathSeparator), relPath)\n\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\tif strings.HasPrefix(relPath, `\\\\`) {\n\t\t\t\trelPath = relPath[1:]\n\t\t\t}\n\t\t}\n\n\t\tif relPath == string(os.PathSeparator) {\n\t\t\treturn nil\n\t\t}\n\n\t\tparent := root.LookUp(filepath.Dir(relPath))\n\t\tif parent == nil {\n\t\t\treturn fmt.Errorf(\"collectFileInfo: Unexpectedly no parent for %s\", relPath)\n\t\t}\n\n\t\tinfo := &FileInfo{\n\t\t\tname: filepath.Base(relPath),\n\t\t\tchildren: make(map[string]*FileInfo),\n\t\t\tparent: parent,\n\t\t}\n\n\t\ts, err := system.Lstat(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tinfo.stat = s\n\n\t\tinfo.capability, _ = system.Lgetxattr(path, \"security.capability\")\n\n\t\tparent.children[info.name] = info\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn root, nil\n}\n\nfunc collectFileInfoForChanges(oldDir, newDir string) (*FileInfo, *FileInfo, error) ", "output": "{\n\tvar (\n\t\toldRoot, newRoot *FileInfo\n\t\terr1, err2 error\n\t\terrs = make(chan error, 2)\n\t)\n\tgo func() {\n\t\toldRoot, err1 = collectFileInfo(oldDir)\n\t\terrs <- err1\n\t}()\n\tgo func() {\n\t\tnewRoot, err2 = collectFileInfo(newDir)\n\t\terrs <- err2\n\t}()\n\n\tfor i := 0; i < 2; i++ {\n\t\tif err := <-errs; err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\treturn oldRoot, newRoot, nil\n}"} {"input": "package awstesting\n\nimport (\n\t\"github.com/golib/aws/service\"\n\t\"github.com/golib/aws/service/client\"\n\t\"github.com/golib/aws/service/client/metadata\"\n\t\"github.com/golib/aws/service/defaults\"\n)\n\n\n\n\nfunc NewClient(cfgs ...*service.Config) *client.Client ", "output": "{\n\tinfo := metadata.ClientInfo{\n\t\tEndpoint: \"http://endpoint\",\n\t\tSigningName: \"\",\n\t}\n\tdef := defaults.Get()\n\tdef.Config.MergeIn(cfgs...)\n\n\treturn client.New(*def.Config, info, def.Handlers)\n}"} {"input": "package app\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/jaegertracing/jaeger/pkg/config\"\n)\n\nfunc TestCollectorOptionsWithFlags_CheckHostPort(t *testing.T) {\n\tc := &CollectorOptions{}\n\tv, command := config.Viperize(AddFlags)\n\tcommand.ParseFlags([]string{\n\t\t\"--collector.http-server.host-port=5678\",\n\t\t\"--collector.grpc-server.host-port=1234\",\n\t\t\"--collector.zipkin.host-port=3456\",\n\t})\n\tc.InitFromViper(v)\n\n\tassert.Equal(t, \":5678\", c.CollectorHTTPHostPort)\n\tassert.Equal(t, \":1234\", c.CollectorGRPCHostPort)\n\tassert.Equal(t, \":3456\", c.CollectorZipkinHTTPHostPort)\n}\n\n\n\nfunc TestCollectorOptionsWithFlags_CheckFullHostPort(t *testing.T) ", "output": "{\n\tc := &CollectorOptions{}\n\tv, command := config.Viperize(AddFlags)\n\tcommand.ParseFlags([]string{\n\t\t\"--collector.http-server.host-port=:5678\",\n\t\t\"--collector.grpc-server.host-port=127.0.0.1:1234\",\n\t\t\"--collector.zipkin.host-port=0.0.0.0:3456\",\n\t})\n\tc.InitFromViper(v)\n\n\tassert.Equal(t, \":5678\", c.CollectorHTTPHostPort)\n\tassert.Equal(t, \"127.0.0.1:1234\", c.CollectorGRPCHostPort)\n\tassert.Equal(t, \"0.0.0.0:3456\", c.CollectorZipkinHTTPHostPort)\n}"} {"input": "package AuditTime\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t_ \"github.com/reactivego/rx\"\n)\n\n\n\nfunc Example_auditTimeBursts() {\n\tconst ms = time.Millisecond\n\n\tburst20ms := func(i int) ObservableInt {\n\t\treturn IntervalInt(5 * ms).Take(4).MapInt(func(j int) int {\n\t\t\treturn i*100 + j\n\t\t})\n\t}\n\n\tfmt.Println(\"-1-\")\n\n\tIntervalInt(25 * ms).Take(4).MergeMapInt(burst20ms).AuditTime(21 * ms).Println()\n\n\tfmt.Println(\"-2-\")\n\n\tIntervalInt(50 * ms).Take(4).MergeMapInt(burst20ms).AuditTime(14 * ms).Println()\n}\n\nfunc Example_auditTime() ", "output": "{\n\tconst ms = time.Millisecond\n\n\tInterval(1 * ms).AuditTime(10 * ms).Take(5).Println()\n}"} {"input": "package vision_test\n\nimport (\n\t\"context\"\n\n\tvision \"cloud.google.com/go/vision/apiv1\"\n\tvisionpb \"google.golang.org/genproto/googleapis/cloud/vision/v1\"\n)\n\nfunc ExampleNewImageAnnotatorClient() {\n\tctx := context.Background()\n\tc, err := vision.NewImageAnnotatorClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\nfunc ExampleImageAnnotatorClient_BatchAnnotateImages() {\n\tctx := context.Background()\n\tc, err := vision.NewImageAnnotatorClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &visionpb.BatchAnnotateImagesRequest{\n\t}\n\tresp, err := c.BatchAnnotateImages(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleImageAnnotatorClient_BatchAnnotateFiles() {\n\tctx := context.Background()\n\tc, err := vision.NewImageAnnotatorClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &visionpb.BatchAnnotateFilesRequest{\n\t}\n\tresp, err := c.BatchAnnotateFiles(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\n\n\nfunc ExampleImageAnnotatorClient_AsyncBatchAnnotateFiles() {\n\tctx := context.Background()\n\tc, err := vision.NewImageAnnotatorClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &visionpb.AsyncBatchAnnotateFilesRequest{\n\t}\n\top, err := c.AsyncBatchAnnotateFiles(ctx, req)\n\tif err != nil {\n\t}\n\n\tresp, err := op.Wait(ctx)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleImageAnnotatorClient_AsyncBatchAnnotateImages() ", "output": "{\n\tctx := context.Background()\n\tc, err := vision.NewImageAnnotatorClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &visionpb.AsyncBatchAnnotateImagesRequest{\n\t}\n\top, err := c.AsyncBatchAnnotateImages(ctx, req)\n\tif err != nil {\n\t}\n\n\tresp, err := op.Wait(ctx)\n\tif err != nil {\n\t}\n\t_ = resp\n}"} {"input": "package apis\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/go-ozzo/ozzo-routing\"\n\t\"github.com/go-ozzo/ozzo-routing/content\"\n\t\"github.com/Zhanat87/go/app\"\n\t\"github.com/Zhanat87/go/testdata\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype apiTestCase struct {\n\ttag string\n\tmethod string\n\turl string\n\tbody string\n\tstatus int\n\tresponse string\n}\n\nvar router *routing.Router\n\nfunc init() {\n\tlogger := logrus.New()\n\tlogger.Level = logrus.PanicLevel\n\n\trouter = routing.New()\n\n\trouter.Use(\n\t\tapp.Init(logger),\n\t\tcontent.TypeNegotiator(content.JSON),\n\t\tapp.Transactional(testdata.DB),\n\t)\n}\n\nfunc testAPI(method, URL, body string) *httptest.ResponseRecorder {\n\treq, _ := http.NewRequest(method, URL, bytes.NewBufferString(body))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tres := httptest.NewRecorder()\n\trouter.ServeHTTP(res, req)\n\treturn res\n}\n\n\n\nfunc runAPITests(t *testing.T, tests []apiTestCase) ", "output": "{\n\tfor _, test := range tests {\n\t\tres := testAPI(test.method, test.url, test.body)\n\t\tassert.Equal(t, test.status, res.Code, test.tag + \", \" + res.Body.String())\n\t\tif test.response != \"\" {\n\t\t\tassert.JSONEq(t, test.response, res.Body.String(), test.tag)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/codegangsta/martini-contrib/render\"\n\t\"github.com/luan/godo/godo\"\n\t\"net/http\"\n)\n\ntype ProjectsController struct{}\n\n\n\nfunc (c *ProjectsController) Create(req *http.Request, r render.Render) {\n\n\tp := godo.NewProject(req.FormValue(\"name\"))\n\tgodo.NewProjectManager().Add(&p)\n\n\tr.Redirect(\"/projects\", 301)\n}\n\nfunc (c *ProjectsController) List(r render.Render) ", "output": "{\n\tprojects, _ := godo.NewProjectManager().FindAllWithTasks()\n\n\tr.HTML(200, \"projects\", projects)\n}"} {"input": "package protocol\n\nimport (\n\t\"encoding/binary\"\n\t\"io\"\n)\n\n\n\ntype Floor struct {\n\tProtocolIdentifier []byte\n\tAddressData []byte\n}\n\n\nfunc (f Floor) WriteTo(w io.Writer) (n int64, err error) {\n\tbuf := make([]byte, f.EncodedLength())\n\tf.Marshal(buf)\n\tn32, err := w.Write(buf)\n\treturn int64(n32), err\n}\n\n\n\n\n\n\nfunc (f Floor) EncodedLength() int {\n\treturn 4 + len(f.ProtocolIdentifier) + len(f.AddressData)\n}\n\nfunc copyWithLength(from []byte, to []byte) {\n\tbinary.LittleEndian.PutUint16(to[0:2], uint16(len(from)))\n\tcopy(to[2:], from)\n}\n\nfunc (f Floor) Marshal(p []byte) ", "output": "{\n\tcopyWithLength(f.ProtocolIdentifier, p) \n\tp = p[2+len(f.ProtocolIdentifier):]\n\tcopyWithLength(f.AddressData, p) \n}"} {"input": "package pprofextension \n\nimport (\n\t\"go.opentelemetry.io/collector/config\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n)\n\n\n\ntype Config struct {\n\tconfig.ExtensionSettings `mapstructure:\",squash\"` \n\n\tTCPAddr confignet.TCPAddr `mapstructure:\",squash\"`\n\n\tBlockProfileFraction int `mapstructure:\"block_profile_fraction\"`\n\n\tMutexProfileFraction int `mapstructure:\"mutex_profile_fraction\"`\n\n\tSaveToFile string `mapstructure:\"save_to_file\"`\n}\n\nvar _ config.Extension = (*Config)(nil)\n\n\n\n\nfunc (cfg *Config) Validate() error ", "output": "{\n\treturn nil\n}"} {"input": "package eventlistener\n\nimport (\n\t\"testing\"\n\t\"github.com/docker/docker/api/types\"\n\t\"golang.org/x/net/context\"\n\t\"fmt\"\n\t\"time\"\n\t\"github.com/docker/docker/api/types/events\"\n)\n\n\nfunc TestEventListener(t *testing.T) {\n\n\tconst labelToMonitor = \"tugbot-test\"\n\ttsk := make(chan string, 10)\n\n\tRegister(dockerClientMock{}, labelToMonitor, tsk)\n\tselect {\n\tcase res := <-tsk:\n\t\tfmt.Println(\"we recieved the die container id via the tasks chan: \", res)\n\tcase <-time.After(time.Second * 5):\n\t\tt.Error(\"we did not recieved the die container id on the tasks chan after 5 sec!\")\n\t}\n}\n\ntype dockerClientMock struct {}\n\nfunc (d dockerClientMock) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) {\n\teventsChan := make(chan events.Message, 10)\n\terrChan := make(chan error, 10)\n\tevent := events.Message{ Type: \"container\", Action: \"die\", }\n\teventsChan <- event\n\treturn eventsChan, errChan\n}\nfunc (d dockerClientMock) Info(ctx context.Context) (types.Info, error) {\n\tpanic(\"This function not suppose to be called\")\n}\nfunc (d dockerClientMock) RegistryLogin(ctx context.Context, auth types.AuthConfig) (types.AuthResponse, error) {\n\tpanic(\"This function not suppose to be called\")\n}\n\nfunc (d dockerClientMock) DiskUsage(ctx context.Context) (types.DiskUsage, error) {\n\tpanic(\"This function not suppose to be called\")\n}\n\n\n\nfunc (d dockerClientMock) Ping(ctx context.Context) (bool, error) ", "output": "{\n\tpanic(\"This function not suppose to be called\")\n}"} {"input": "package gtk\n\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (v *FileChooserButton) GetFocusOnClick() bool {\n\treturn gobool(C.gtk_file_chooser_button_get_focus_on_click(v.native()))\n}\n\n\nfunc (v *FileChooserButton) SetFocusOnClick(grabFocus bool) {\n\tC.gtk_file_chooser_button_set_focus_on_click(v.native(), gbool(grabFocus))\n}\n\n\n\n\n\n\n\nfunc (v *Button) SetFocusOnClick(focusOnClick bool) {\n\tC.gtk_button_set_focus_on_click(v.native(), gbool(focusOnClick))\n}\n\n\n\n\nfunc (v *TextIter) BeginsTag(v1 *TextTag) bool {\n\treturn gobool(C.gtk_text_iter_begins_tag(v.native(), v1.native()))\n}\n\n\n\n\nfunc (v *Window) ParseGeometry(geometry string) bool {\n\tcstr := C.CString(geometry)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_window_parse_geometry(v.native(), (*C.gchar)(cstr))\n\treturn gobool(c)\n}\n\n\nfunc (v *Window) ResizeToGeometry(width, height int) {\n\tC.gtk_window_resize_to_geometry(v.native(), C.gint(width), C.gint(height))\n}\n\n\nfunc (v *Window) SetDefaultGeometry(width, height int) {\n\tC.gtk_window_set_default_geometry(v.native(), C.gint(width),\n\t\tC.gint(height))\n}\n\nfunc (v *Button) GetFocusOnClick() bool ", "output": "{\n\tc := C.gtk_button_get_focus_on_click(v.native())\n\treturn gobool(c)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/opencontainers/runtime-spec/specs-go\"\n\t\"github.com/urfave/cli\"\n)\n\n\n\n\n\n\nfunc setupSpec(context *cli.Context) (*specs.Spec, error) {\n\tbundle := context.String(\"bundle\")\n\tif bundle != \"\" {\n\t\tif err := os.Chdir(bundle); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tspec, err := loadSpec(specConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnotifySocket := os.Getenv(\"NOTIFY_SOCKET\")\n\tif notifySocket != \"\" {\n\t\tsetupSdNotify(spec, notifySocket)\n\t}\n\tif os.Geteuid() != 0 {\n\t\treturn nil, fmt.Errorf(\"runc should be run as root\")\n\t}\n\treturn spec, nil\n}\n\nfunc fatal(err error) ", "output": "{\n\tlogrus.Error(err)\n\tfmt.Fprintln(os.Stderr, err)\n\tos.Exit(1)\n}"} {"input": "package connect\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestCatalogCommand_noTabs(t *testing.T) ", "output": "{\n\tt.Parallel()\n\tif strings.ContainsRune(New().Help(), '\\t') {\n\t\tt.Fatal(\"help has tabs\")\n\t}\n}"} {"input": "package spnego\n\nimport (\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/apcera/gssapi\"\n)\n\n\n\nfunc AddSPNEGONegotiate(h http.Header, name string, token *gssapi.Buffer) {\n\tif name == \"\" {\n\t\treturn\n\t}\n\n\tv := \"Negotiate\"\n\tif token.Length() != 0 {\n\t\tdata := token.Bytes()\n\t\tv = v + \" \" + base64.StdEncoding.EncodeToString(data)\n\t}\n\th.Set(name, v)\n}\n\n\n\n\n\nfunc CheckSPNEGONegotiate(lib *gssapi.Lib, h http.Header, name string) (present bool, token *gssapi.Buffer) ", "output": "{\n\tvar err error\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlib.Debug(fmt.Sprintf(\"CheckSPNEGONegotiate: %v\", err))\n\t\t}\n\t}()\n\n\tv := h.Get(name)\n\tif len(v) == 0 || !strings.HasPrefix(v, \"Negotiate\") {\n\t\treturn false, nil\n\t}\n\n\tpresent = true\n\ttbytes, err := base64.StdEncoding.DecodeString(strings.TrimSpace(v[len(\"Negotiate\"):]))\n\tif err != nil {\n\t\treturn false, nil\n\t}\n\n\tif len(tbytes) > 0 {\n\t\ttoken, err = lib.MakeBufferBytes(tbytes)\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\treturn present, token\n}"} {"input": "package commands\n\nimport (\n \"github.com/spf13/cobra\"\n \"github.com/YusukeKomatsu/honoka\"\n \"github.com/davecgh/go-spew/spew\"\n)\n\nvar (\n listCmd = &cobra.Command{\n Use: \"list\",\n Short: \"Retrive cache index list\",\n Long: \"Retrive cache index list (not include cache data). If you get cache, use get method\",\n Run: listCommand,\n }\n)\n\nfunc listCommand(cmd *cobra.Command, args []string) {\n cli, err := honoka.New()\n if err != nil {\n Exit(err)\n }\n\n list, err := cli.List()\n if err != nil {\n Exit(err)\n }\n spew.Dump(list);\n}\n\n\n\nfunc init() ", "output": "{\n RootCmd.AddCommand(listCmd)\n}"} {"input": "package x509_test\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t. \"github.com/hyperledger/fabric-ca/lib/client/credential/x509\"\n\t\"github.com/hyperledger/fabric-ca/util\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestNewSignerError(t *testing.T) {\n\t_, err := NewSigner(nil, []byte{})\n\tassert.Error(t, err, \"NewSigner should return an error if cert byte array is empty\")\n}\n\n\n\nfunc TestNewSigner(t *testing.T) ", "output": "{\n\tcertBytes, err := util.ReadFile(filepath.Join(testDataDir, \"ec256-1-cert.pem\"))\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to read the cert: %s\", err.Error())\n\t}\n\tsigner, err := NewSigner(nil, certBytes)\n\tassert.NoError(t, err, \"NewSigner should not return an error if cert bytes are valid\")\n\n\tassert.NotNil(t, signer.GetX509Cert())\n\tassert.Nil(t, signer.Key())\n\tassert.NotEmpty(t, signer.GetName())\n\t_, err = signer.Attributes()\n\tassert.NoError(t, err)\n}"} {"input": "package lint\n\nimport (\n\t\"go/token\"\n)\n\n\ntype DisabledInterval struct {\n\tFrom token.Position\n\tTo token.Position\n\tRuleName string\n}\n\n\ntype Rule interface {\n\tName() string\n\tApply(*File, Arguments) []Failure\n}\n\n\ntype AbstractRule struct {\n\tFailures []Failure\n}\n\n\n\n\nfunc ToFailurePosition(start token.Pos, end token.Pos, file *File) FailurePosition ", "output": "{\n\treturn FailurePosition{\n\t\tStart: file.ToPosition(start),\n\t\tEnd: file.ToPosition(end),\n\t}\n}"} {"input": "package aws\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/aws/aws-sdk-go/service/outposts\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/v2/terraform\"\n)\n\n\n\nfunc testAccCheckOutpostsSitesAttributes(dataSourceName string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[dataSourceName]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", dataSourceName)\n\t\t}\n\n\t\tif v := rs.Primary.Attributes[\"ids.#\"]; v == \"0\" {\n\t\t\treturn fmt.Errorf(\"expected at least one ids result, got none\")\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccPreCheckAWSOutpostsSites(t *testing.T) {\n\tconn := testAccProvider.Meta().(*AWSClient).outpostsconn\n\n\tinput := &outposts.ListSitesInput{}\n\n\toutput, err := conn.ListSites(input)\n\n\tif testAccPreCheckSkipError(err) {\n\t\tt.Skipf(\"skipping acceptance testing: %s\", err)\n\t}\n\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected PreCheck error: %s\", err)\n\t}\n\n\tif output == nil || len(output.Sites) == 0 {\n\t\tt.Skip(\"skipping since no Sites Outpost found\")\n\t}\n}\n\nfunc testAccAWSOutpostsSitesDataSourceConfig() string {\n\treturn `\ndata \"aws_outposts_sites\" \"test\" {}\n`\n}\n\nfunc TestAccAWSOutpostsSitesDataSource_basic(t *testing.T) ", "output": "{\n\tdataSourceName := \"data.aws_outposts_sites.test\"\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsSites(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: nil,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSOutpostsSitesDataSourceConfig(),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckOutpostsSitesAttributes(dataSourceName),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}"} {"input": "package storage\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) BaseClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package packets\n\nimport (\n\t\"fmt\"\n\t\"github.com/google/uuid\"\n\t\"io\"\n)\n\n\n\ntype PubcompPacket struct {\n\tFixedHeader\n\tMessageID uint16\n\tuuid uuid.UUID\n}\n\nfunc (pc *PubcompPacket) String() string {\n\tstr := fmt.Sprintf(\"%s\\n\", pc.FixedHeader)\n\tstr += fmt.Sprintf(\"MessageID: %d\", pc.MessageID)\n\treturn str\n}\n\n\n\nfunc (pc *PubcompPacket) Unpack(b io.Reader) {\n\tpc.MessageID = decodeUint16(b)\n}\n\nfunc (pc *PubcompPacket) Details() Details {\n\treturn Details{Qos: pc.Qos, MessageID: pc.MessageID}\n}\n\nfunc (pc *PubcompPacket) UUID() uuid.UUID {\n\treturn pc.uuid\n}\n\nfunc (pc *PubcompPacket) Write(w io.Writer) error ", "output": "{\n\tvar err error\n\tpc.FixedHeader.RemainingLength = 2\n\tpacket := pc.FixedHeader.pack()\n\tpacket.Write(encodeUint16(pc.MessageID))\n\t_, err = packet.WriteTo(w)\n\n\treturn err\n}"} {"input": "package thrift\n\nimport \"io\"\n\ntype RichTransport struct {\n\tTTransport\n}\n\n\nfunc NewTRichTransport(trans TTransport) *RichTransport {\n\treturn &RichTransport{trans}\n}\n\nfunc (r *RichTransport) ReadByte() (c byte, err error) {\n\treturn readByte(r.TTransport)\n}\n\nfunc (r *RichTransport) WriteByte(c byte) error {\n\treturn writeByte(r.TTransport, c)\n}\n\nfunc (r *RichTransport) WriteString(s string) (n int, err error) {\n\treturn r.Write([]byte(s))\n}\n\n\n\nfunc readByte(r io.Reader) (c byte, err error) {\n\tv := [1]byte{0}\n\tn, err := r.Read(v[0:1])\n\tif n > 0 && (err == nil || err == io.EOF) {\n\t\treturn v[0], nil\n\t}\n\tif n > 0 && err != nil {\n\t\treturn v[0], err\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn v[0], nil\n}\n\nfunc writeByte(w io.Writer, c byte) error {\n\tv := [1]byte{c}\n\t_, err := w.Write(v[0:1])\n\treturn err\n}\n\nfunc (r *RichTransport) RemainingBytes() (num_bytes uint64) ", "output": "{\n\treturn r.TTransport.RemainingBytes()\n}"} {"input": "package mock\n\nimport (\n\t\"time\"\n)\n\ntype Clock struct {\n\tAdded []uint\n\tRemoved []chan time.Time\n\tEta float64\n}\n\nfunc NewClock() *Clock {\n\tm := &Clock{\n\t\tAdded: []uint{},\n\t\tRemoved: []chan time.Time{},\n\t}\n\treturn m\n}\n\nfunc (m *Clock) Add(c chan time.Time, t uint, sync bool) {\n\tm.Added = append(m.Added, t)\n}\n\nfunc (m *Clock) Remove(c chan time.Time) {\n\tm.Removed = append(m.Removed, c)\n}\n\n\n\nfunc (m *Clock) ETA(c chan time.Time) float64 ", "output": "{\n\treturn m.Eta\n}"} {"input": "package sacloud\n\n\ntype ENoteClass string\n\nvar (\n\tNoteClassShell = ENoteClass(\"shell\")\n\tNoteClassYAMLCloudConfig = ENoteClass(\"yaml_cloud_config\")\n)\n\n\nvar ENoteClasses = []ENoteClass{NoteClassShell, NoteClassYAMLCloudConfig}\n\n\ntype propNoteClass struct {\n\tClass ENoteClass `json:\",omitempty\"` \n}\n\n\nfunc (p *propNoteClass) GetClass() ENoteClass {\n\treturn p.Class\n}\n\n\nfunc (p *propNoteClass) SetClass(c ENoteClass) {\n\tp.Class = c\n}\n\n\n\n\n\nfunc (p *propNoteClass) SetClassByStr(c string) {\n\tp.Class = ENoteClass(c)\n}\n\nfunc (p *propNoteClass) GetClassStr() string ", "output": "{\n\treturn string(p.Class)\n}"} {"input": "package underscore\n\nfunc Select(source, predicate interface{}) interface{} {\n\treturn filter(source, predicate, true)\n}\n\nfunc SelectBy(source interface{}, properties map[string]interface{}) interface{} {\n\treturn Select(source, func (value, _ interface{}) bool {\n\t\treturn IsMatch(value, properties)\n\t})\n}\n\n\n\n\nfunc (this *Query) SelectBy(properties map[string]interface{}) Queryer {\n\tthis.source = SelectBy(this.source, properties)\n\treturn this\n}\n\nfunc (this *Query) Select(predicate interface{}) Queryer ", "output": "{\n\tthis.source = Select(this.source, predicate)\n\treturn this\n}"} {"input": "package configparser\n\nimport (\n\t\"github.com/bigkevmcd/go-configparser/chainmap\"\n\n\t\"strings\"\n)\n\nfunc (p *ConfigParser) getInterpolated(section, option string, c *chainmap.ChainMap) (string, error) {\n\tval, err := p.Get(section, option)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn p.interpolate(val, c), nil\n}\n\n\n\n\n\nfunc (p *ConfigParser) GetInterpolated(section, option string) (string, error) {\n\to, err := p.Items(section)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tc := chainmap.New(chainmap.Dict(p.Defaults()), chainmap.Dict(o))\n\treturn p.getInterpolated(section, option, c)\n}\n\n\n\n\n\n\n\nfunc (p *ConfigParser) GetInterpolatedWithVars(section, option string, v Dict) (string, error) {\n\to, err := p.Items(section)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tc := chainmap.New(chainmap.Dict(p.Defaults()), chainmap.Dict(o), chainmap.Dict(v))\n\treturn p.getInterpolated(section, option, c)\n\n}\n\n\n\n\nfunc (p *ConfigParser) interpolate(value string, options *chainmap.ChainMap) string {\n\n\tfor i := 0; i < maxInterpolationDepth; i++ {\n\t\tif strings.Contains(value, \"%(\") {\n\t\t\tvalue = interpolater.ReplaceAllStringFunc(value, func(m string) string {\n\t\t\t\tmatch := interpolater.FindAllStringSubmatch(m, 1)[0][1]\n\t\t\t\treplacement := options.Get(match)\n\t\t\t\treturn replacement\n\t\t\t})\n\t\t}\n\t}\n\treturn value\n}\n\n\n\n\nfunc (p *ConfigParser) ItemsWithDefaultsInterpolated(section string) (Dict, error) ", "output": "{\n\ts, err := p.ItemsWithDefaults(section)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range s {\n\t\tv, err = p.GetInterpolated(section, k)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts[k] = v\n\t}\n\treturn s, nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\t. \"github.com/CodyGuo/win\"\n)\n\nvar (\n\trt *gin.Engine\n\trootPrefix string\n)\n\nfunc main() {\n\trt = gin.Default()\n\trouter(rt)\n\n\tgo rt.Run(\":8945\")\n\n\tc := make(chan os.Signal, 1)\n\n\tsignal.Notify(c, os.Interrupt, os.Kill, syscall.SIGTERM)\n\t<-c\n\n\n\tos.Exit(0)\n}\n\n\nfunc router(r *gin.Engine) {\n\tg := &r.RouterGroup\n\tif rootPrefix != \"\" {\n\t\tg = r.Group(rootPrefix)\n\t}\n\n\t{\n\t\tg.GET(\"/\", func(c *gin.Context) { c.String(200, \"ok\") })\n\t\tg.GET(\"/ShutDown\", ShutDown)\n\t}\n}\n\n\n\nfunc getPrivileges() {\n\tvar hToken HANDLE\n\tvar tkp TOKEN_PRIVILEGES\n\n\tOpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken)\n\tLookupPrivilegeValueA(nil, StringToBytePtr(SE_SHUTDOWN_NAME), &tkp.Privileges[0].Luid)\n\ttkp.PrivilegeCount = 1\n\ttkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED\n\tAdjustTokenPrivileges(hToken, false, &tkp, 0, nil, nil)\n}\n\nfunc ShutDown(c *gin.Context) ", "output": "{\n\tgetPrivileges()\n\tExitWindowsEx(EWX_SHUTDOWN, 0)\n}"} {"input": "package main\n\nimport (\n \"os\"\n \"os/exec\"\n \"log\"\n)\n\n\n\nfunc mvim(files []string) {\n for i := 0 ; i < len(files) ; i++ {\n cmd := exec.Command(\"mvim\", files[i])\n err := cmd.Run()\n if err != nil {\n log.Fatal(err)\n }\n }\n}\n\nfunc vim(files []string) ", "output": "{\n for i := 0 ; i < len(files) ; i++ {\n cmd := exec.Command(\"vim\", files[i])\n cmd.Stdin = os.Stdin\n cmd.Stdout = os.Stdout\n cmd.Stderr = os.Stderr\n err := cmd.Run()\n if err != nil {\n log.Fatal(err)\n }\n if i != len(files) - 1 {\n check_if_continue()\n }\n }\n}"} {"input": "package ecs\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestModifyHaVipAttribute(t *testing.T) ", "output": "{\n\tvar req ModifyHaVipAttributeRequest\n\treq.Init()\n\treq.SetFormat(\"JSON\")\n\treq.SetRegionId(\"cn-shenzhen\")\n\tvar accessId = \"Ie65kUInu5GeAsma\"\n\tvar accessSecret = \"8cCqoxdYU9zKUihwXFXiN1HEACBDwB\"\n\tresp, err := ModifyHaVipAttribute(&req, accessId, accessSecret)\n\tif err != nil {\n\t\tt.Errorf(\"Error: %s\", err.Error())\n\t}\n\tfmt.Printf(\"Success: %v\\n\", resp)\n}"} {"input": "package filehash\n\nimport (\n\t\"crypto/sha1\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/cloudfoundry/gofileutils/fileutils\"\n)\n\ntype Hash []byte\n\nfunc Zero() Hash {\n\treturn Hash(make([]byte, sha1.Size))\n}\n\n\n\n\nfunc (k Hash) String() string {\n\treturn fmt.Sprintf(\"%x\", string(k))\n}\n\nfunc StringToHash(s string) Hash {\n\tvar sh string\n\tif _, err := fmt.Sscanf(s, \"%x\", &sh); err != nil {\n\t\tpanic(err)\n\t}\n\treturn Hash(sh)\n}\n\nfunc (h1 Hash) Combine(h2 Hash) {\n\tif len(h1) != len(h2) {\n\t\tpanic(\"Invalid hash length\")\n\t}\n\tfor i, b := range h1 {\n\t\th1[i] = b ^ h2[i]\n\t}\n}\n\nfunc (h1 Hash) Remove(h2 Hash) {\n\th1.Combine(h2)\n}\n\nfunc New(filePath string) Hash ", "output": "{\n\tfileInfo, err := os.Lstat(filePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif fileInfo.IsDir() {\n\t\tpanic(\"cannot compute hash of directory\")\n\t} else {\n\t\thash := sha1.New()\n\t\terr = fileutils.CopyPathToWriter(filePath, hash)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn Hash(hash.Sum(nil))\n\t}\n}"} {"input": "package sqlbuilder\n\ntype Dialect interface {\n\tEscapeCharacter() rune\n\tInsertReturningClause() string\n\tKind() string\n\tName() *string\n}\n\ntype genericDialect struct {\n\tescapeChar rune\n\treturningClause string\n\tkind string\n\tname *string\n}\n\nfunc (db *genericDialect) EscapeCharacter() rune {\n\treturn db.escapeChar\n}\n\nfunc (db *genericDialect) InsertReturningClause() string {\n\treturn db.returningClause\n}\n\nfunc (db *genericDialect) Kind() string {\n\treturn db.kind\n}\n\nfunc (db *genericDialect) Name() *string {\n\treturn db.name\n}\n\nfunc NewMySQLDialect(dbName *string) Dialect {\n\treturn &genericDialect{\n\t\tescapeChar: '`',\n\t\tkind: \"mysql\",\n\t\tname: dbName,\n\t}\n}\n\n\n\nfunc NewSQLiteDialect() Dialect {\n\tdefaultName := \"main\"\n\treturn &genericDialect{\n\t\tescapeChar: '\"',\n\t\tkind: \"sqlite\",\n\t\tname: &defaultName,\n\t}\n}\n\nfunc NewPostgresDialect(dbName *string) Dialect ", "output": "{\n\treturn &genericDialect{\n\t\tescapeChar: '\"',\n\t\treturningClause: \" RETURNING *\",\n\t\tkind: \"postgres\",\n\t\tname: dbName,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"encoding/hex\"\n\t\"log\"\n\t\"os\"\n\t\"time\"\n)\n\n\nfunc FakeBluetooth() {\n\tlog.Println(\"[FAKEBLUETOOTH] Sending fake data from 'testdata' to the indicator parser... (waiting 5 seconds)\")\n\tf, err := os.Open(\"testdata\")\n\tif err != nil {\n\t\tlog.Println(\"[FAKEBLUETOOTH] error opening file= \", err)\n\t\tos.Exit(1)\n\t}\n\tr := bufio.NewReader(f)\n\ts, e := readln(r)\n\ttime.Sleep(5 * time.Second)\n\tfor e == nil {\n\t\tlog.Println(\"[FAKEBLUETOOTH] Sending data: \", s)\n\t\th, _ := hex.DecodeString(s)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[FAKEBLUETOOTH] error decoding line: %+v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tgo decodeData(h)\n\t\ttime.Sleep(200 * time.Millisecond)\n\t\ts, e = readln(r)\n\t}\n\ttime.Sleep(1 * time.Second)\n\tlog.Println(\"[FAKEBLUETOOTH] Finished sending fake data from 'testdata' to the indicator parser. Waiting in an infinite loop now.\")\n\tselect {}\n}\n\n\n\nfunc readln(r *bufio.Reader) (string, error) ", "output": "{\n\tvar (\n\t\tisPrefix = true\n\t\terr error\n\t\tline, ln []byte\n\t)\n\tfor isPrefix && err == nil {\n\t\tline, isPrefix, err = r.ReadLine()\n\t\tln = append(ln, line...)\n\t}\n\treturn string(ln), err\n}"} {"input": "package store\n\nimport \"strings\"\n\n\ntype ByPathLen []string\n\nfunc (s ByPathLen) Len() int { return len(s) }\n\nfunc (s ByPathLen) Less(i, j int) bool {\n\treturn strings.Count(s[i], \"/\") < strings.Count(s[j], \"/\")\n}\n\n\n\n\ntype ByLen []string\n\n\nfunc (s ByLen) Len() int { return len(s) }\n\n\nfunc (s ByLen) Less(i, j int) bool { return len(s[i]) > len(s[j]) }\n\n\nfunc (s ByLen) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s ByPathLen) Swap(i, j int) ", "output": "{\n\ts[i], s[j] = s[j], s[i]\n}"} {"input": "package networker_test\n\nimport (\n\tstdtesting \"testing\"\n\n\t\"github.com/juju/juju/testing\"\n)\n\n\n\nfunc TestAll(t *stdtesting.T) ", "output": "{\n\ttesting.MgoTestPackage(t)\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n)\n\nfunc main() {\n\n\tif len(os.Args) == 1 {\n\t\tfmt.Println(\"Please provide either a file path or a number input\")\n\n\t} else {\n\n\t\tinput := os.Args[1]\n\t\tfile, err := os.Open(input)\n\n\t\tif check(err) == false {\n\t\t\tdefer file.Close()\n\n\t\t\treader := bufio.NewReader(file)\n\t\t\tscanner := bufio.NewScanner(reader)\n\n\t\t\tfor scanner.Scan() {\n\t\t\t\tvalue := scanner.Text()\n\t\t\t\tif value == \"#\" {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tvalue = cleanString(value)\n\n\t\t\t\tnum := stringToInt(value)\n\t\t\t\tif num <= 15 {\n\t\t\t\t\tfmt.Println(factorial(num))\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else if check(err) == true {\n\t\t\tintInput := stringToInt(input)\n\n\t\t\toutput := factorial(intInput)\n\t\t\tfmt.Println(output)\n\n\t\t}\n\n\t}\n\n}\n\nfunc factorial(number int64) (factor int64) {\n\tfactor = 1\n\n\tif number == 1 {\n\t\treturn\n\t} else {\n\n\t\tvar counter int64 = 1\n\n\t\tfor i := counter; i <= number; i++ {\n\t\t\tfactor = factor * i\n\t\t}\n\t\treturn\n\t}\n\n\treturn\n}\n\n\n\nfunc check(e error) bool {\n\tif e != nil {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc cleanString(value string) (result string) {\n\n\tr := regexp.MustCompile(`\\d+`)\n\tmatches := r.FindAllString(value, -1)\n\n\tfor _, value := range matches {\n\t\tresult += value\n\t}\n\n\treturn\n}\n\nfunc stringToInt(input string) int64 ", "output": "{\n\tresult, _ := strconv.ParseInt(input, 10, 0)\n\treturn result\n}"} {"input": "package gitbot\n\nimport \"fmt\"\n\n\ntype PullRequest struct {\n\tHead *Head `json:\"head\"`\n\tBase *Head `json:\"base\"`\n\tLinks *Links `json:\"_links\"`\n\tUser *User `json:\"user\"`\n\tMergedBy *User `json:\"merged_by\"`\n\tURL string `json:\"url\"`\n\tHTMLURL string `json:\"html_url\"`\n\tDiffURL string `json:\"diff_url\"`\n\tPatchURL string `json:\"patch_url\"`\n\tIssueURL string `json:\"issue_url\"`\n\tCommitsURL string `json:\"commits_url\"`\n\tReviewCommentsURL string `json:\"review_comments_url\"`\n\tReviewCommentURL string `json:\"review_comment_url\"`\n\tCommentsURL string `json:\"comments_url\"`\n\tStatusesURL string `json:\"statuses_url\"`\n\tNumber int `json:\"number\"`\n\tState string `json:\"state\"`\n\tTitle string `json:\"title\"`\n\tBody string `json:\"body\"`\n\tMergeCommitSha string `json:\"merge_commit_sha\"`\n\tMerged bool `json:\"merged\"`\n\tMergeable bool `json:\"mergeable\"`\n\tComments int `json:\"comments\"`\n\tCommits int `json:\"commits\"`\n\tAdditions int `json:\"additions\"`\n\tDeletions int `json:\"deletions\"`\n\tChangedFiles int `json:\"changed_files\"`\n}\n\n\n\nfunc (s PullRequest) String() string ", "output": "{\n\treturn fmt.Sprintf(\"#%v %s (%s)\", s.Number, s.Title, s.HTMLURL)\n}"} {"input": "package driverskeleton\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"periph.io/x/periph\"\n\t\"periph.io/x/periph/conn/i2c/i2ctest\"\n)\n\nfunc TestDriverSkeleton(t *testing.T) {\n\tbus := i2ctest.Playback{\n\t\tOps: []i2ctest.IO{\n\t\t\t{Addr: 42, W: []byte(\"in\"), R: []byte(\"IN\")},\n\t\t\t{Addr: 42, W: []byte(\"what\"), R: []byte(\"Hello world!\")},\n\t\t},\n\t\tDontPanic: true,\n\t}\n\tdev, err := New(&bus)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif data := dev.Read(); data != \"Hello world!\" {\n\t\tt.Fatal(data)\n\t}\n\n\tif data := dev.Read(); !strings.HasPrefix(data, \"i2ctest: unexpected Tx()\") {\n\t\tt.Fatal(data)\n\t}\n}\n\n\n\nfunc TestDriverSkeleton_init_failed(t *testing.T) {\n\tbus := i2ctest.Playback{\n\t\tOps: []i2ctest.IO{\n\t\t\t{Addr: 42, W: []byte(\"in\"), R: []byte(\"xx\")},\n\t\t},\n\t}\n\tif dev, err := New(&bus); dev != nil || err == nil {\n\t\tt.Fatal(\"New should have failed\")\n\t}\n}\n\nfunc TestInit(t *testing.T) {\n\tif state, err := periph.Init(); err != nil {\n\t\tt.Fatal(state, err)\n\t}\n}\n\nfunc TestDriverSkeleton_empty(t *testing.T) ", "output": "{\n\tif dev, err := New(&i2ctest.Playback{DontPanic: true}); dev != nil || err == nil {\n\t\tt.Fatal(\"Tx should have failed\")\n\t}\n}"} {"input": "package routers\n\nimport (\n\t\"github.com/astaxie/beego\"\n\t\"github.com/sy/bomer/controllers\"\n)\n\n\n\nfunc init() ", "output": "{\n\tbeego.Router(\"/\", &controllers.IndexController{})\n\tbeego.Router(\"/dashboard\", &controllers.DashboardController{})\n\tbeego.Router(\"/import\", &controllers.ImportController{})\n\tbeego.Router(\"/analyse\", &controllers.AnalyseController{})\n}"} {"input": "package xjsonbase\n\nimport (\n\t\"fmt\"\n\tmsg \"github.com/Centimitr/xmessage\"\n\t\"io/ioutil\"\n)\n\nfunc (j *JSONBase) Load(c *msg.Ctx) {\n\tfilename := c.Method\n\tdata, err := ioutil.ReadFile(filename + \".json\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tc.Data = string(data)\n}\n\n\n\nfunc (j *JSONBase) Save(c *msg.Ctx) ", "output": "{\n\tfilename := c.Method\n\terr := ioutil.WriteFile(filename+\".json\", []byte(c.Data), 0777)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}"} {"input": "package module\n\nimport (\n\t\"fmt\"\n\t\"github.com/davidscholberg/irkbot/lib/configure\"\n\t\"github.com/davidscholberg/irkbot/lib/message\"\n)\n\nfunc helpQuit() []string {\n\ts := \"quit - ragequit IRC (requires owner privilege)\"\n\treturn []string{s}\n}\n\n\n\nfunc quit(cfg *configure.Config, in *message.InboundMsg, actions *actions) ", "output": "{\n\tif in.Event.Nick != cfg.Admin.Owner {\n\t\tactions.say(fmt.Sprintf(\"%s: %s\", in.Event.Nick, cfg.Admin.DenyMessage))\n\t\treturn\n\t}\n\tactions.quit()\n}"} {"input": "package context\n\nimport (\n\t\"io\"\n\t\"net/http\"\n)\n\n\ntype Context struct {\n\tParams Params\n\n\tValues Values\n\n\treq *http.Request\n}\n\n\n\n\n\nfunc (c *Context) Request() *http.Request {\n\treturn c.req\n}\n\n\n\n\n\n\n\n\ntype wrapper struct {\n\tbody io.ReadCloser \n\tcontext *Context\n}\n\nfunc wrap(r *http.Request) *wrapper {\n\tw := wrapper{ body: r.Body }\n\tr.Body = &w\n\treturn &w\n}\n\nfunc (w *wrapper) Read(p []byte) (n int, err error) {\n\treturn w.body.Read(p)\n}\n\nfunc (w *wrapper) Close() error {\n\treturn w.body.Close()\n}\n\n\n\n\ntype Params map[string]string\n\n\n\nfunc (p Params) Get(key string) string {\n\tif p == nil {\n\t\treturn \"\"\n\t}\n\treturn p[key]\n}\n\n\nfunc (p Params) Set(key, value string) {\n\tp[key] = value\n}\n\n\nfunc (p Params) Del(key string) {\n\tdelete(p, key)\n}\n\n\n\n\ntype Values map[interface{}]interface{}\n\n\n\nfunc (v Values) Get(key interface{}) interface{} {\n\tif v == nil {\n\t\treturn nil\n\t}\n\n\treturn v[key]\n}\n\n\n\n\nfunc (v Values) GetStr(key interface{}) interface{} {\n\tif v == nil { return \"\" }\n\tval := v.Get(key)\n\tif val == nil { return \"\" }\n\n\tstr, ok := val.(string)\n\tif !ok { return \"\" }\n\treturn str\n}\n\n\nfunc (v Values) Set(key, value interface{}) {\n\tv[key] = value\n}\n\n\nfunc (v Values) Del(key interface{}) {\n\tdelete(v, key)\n}\n\nfunc Get(r *http.Request) *Context ", "output": "{\n\n\tif v, ok := r.Body.(*wrapper); ok {\n\t\treturn v.context\n\t}\n\n\tc := Context{ }\n\tc.Params = make(Params)\n\tc.Values = make(Values)\n\tc.req = r\n\n\twrapper := wrap(r)\n\twrapper.context = &c\n\treturn &c\n}"} {"input": "package nginx\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"text/template\"\n\n\t\"github.com/golang/glog\"\n\n\t\"github.com/fatih/structs\"\n\t\"github.com/ghodss/yaml\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\tclient \"k8s.io/kubernetes/pkg/client/unversioned\"\n\t\"k8s.io/kubernetes/pkg/util/flowcontrol\"\n\n\t\"k8s.io/contrib/ingress/controllers/nginx/nginx/config\"\n)\n\n\ntype Manager struct {\n\tConfigFile string\n\n\tdefCfg config.Configuration\n\n\tdefResolver string\n\n\tsslDHParam string\n\n\treloadRateLimiter flowcontrol.RateLimiter\n\n\ttemplate *template.Template\n\n\treloadLock *sync.Mutex\n}\n\n\n\n\nfunc (nginx *Manager) createCertsDir(base string) {\n\tif err := os.Mkdir(base, os.ModeDir); err != nil {\n\t\tif os.IsExist(err) {\n\t\t\tglog.Infof(\"%v already exists\", err)\n\t\t\treturn\n\t\t}\n\t\tglog.Fatalf(\"Couldn't create directory %v: %v\", base, err)\n\t}\n}\n\n\n\nfunc ConfigMapAsString() string {\n\tcfg := &api.ConfigMap{}\n\tcfg.Name = \"custom-name\"\n\tcfg.Namespace = \"a-valid-namespace\"\n\tcfg.Data = make(map[string]string)\n\n\tdata := structs.Map(config.NewDefault())\n\tfor k, v := range data {\n\t\tcfg.Data[k] = fmt.Sprintf(\"%v\", v)\n\t}\n\n\tout, err := yaml.Marshal(cfg)\n\tif err != nil {\n\t\tglog.Warningf(\"Unexpected error creating default configuration: %v\", err)\n\t\treturn \"\"\n\t}\n\n\treturn string(out)\n}\n\nfunc NewManager(kubeClient *client.Client) *Manager ", "output": "{\n\tngx := &Manager{\n\t\tConfigFile: \"/etc/nginx/nginx.conf\",\n\t\tdefCfg: config.NewDefault(),\n\t\tdefResolver: strings.Join(getDNSServers(), \" \"),\n\t\treloadLock: &sync.Mutex{},\n\t\treloadRateLimiter: flowcontrol.NewTokenBucketRateLimiter(0.1, 1),\n\t}\n\n\tngx.createCertsDir(config.SSLDirectory)\n\n\tngx.sslDHParam = ngx.SearchDHParamFile(config.SSLDirectory)\n\n\tif err := ngx.loadTemplate(); err != nil {\n\t\tglog.Fatalf(\"invalid NGINX template: %v\", err)\n\t}\n\n\treturn ngx\n}"} {"input": "package classReader\n\nimport \"math\"\n\ntype ConstantIntegerInfo struct {\n\tval int32\n}\n\nfunc (self *ConstantIntegerInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint32()\n\tself.val = int32(bytes)\n}\n\nfunc (self *ConstantIntegerInfo) Value() int32 {\n\treturn self.val\n}\n\ntype ConstantFloatInfo struct {\n\tval float32\n}\n\nfunc (self *ConstantFloatInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint32()\n\tself.val = math.Float32frombits(bytes)\n}\n\n\n\ntype ConstantLongInfo struct {\n\tval int64\n}\n\nfunc (self *ConstantLongInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint64()\n\tself.val = int64(bytes)\n}\n\nfunc (self *ConstantLongInfo) Value() int64 {\n\treturn self.val\n}\n\ntype ConstantDoubleInfo struct {\n\tval float64\n}\n\nfunc (self *ConstantDoubleInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint64()\n\tself.val = math.Float64frombits(bytes)\n}\n\nfunc (self *ConstantDoubleInfo) Value() float64 {\n\treturn self.val\n}\n\nfunc (self *ConstantFloatInfo) Value() float32 ", "output": "{\n\treturn self.val\n}"} {"input": "package twt\n\nimport (\n\t\"github.com/ChimeraCoder/anaconda\"\n\n\tgolhashmap \"github.com/abhishekkr/gol/golhashmap\"\n)\n\n\n\nfunc GetAPI(creds golhashmap.HashMap) *anaconda.TwitterApi ", "output": "{\n\tanaconda.SetConsumerKey(creds[\"api-key\"])\n\tanaconda.SetConsumerSecret(creds[\"api-secret\"])\n\treturn anaconda.NewTwitterApi(creds[\"access-token\"], creds[\"access-token-secret\"])\n}"} {"input": "package maidenhead\n\nimport (\n\t\"math\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestParseLocator(t *testing.T) {\n\tvar locTests = map[string]Point{\n\t\t\"JN88RT\": Point{48.791667, 17.416667},\n\t\t\"JN89HF\": Point{49.208333, 16.583333},\n\t\t\"JN58TD\": Point{48.125000, 11.583333},\n\t\t\"GF15VC\": Point{-34.916667, -56.250000},\n\t\t\"FM18LW\": Point{38.916667, -77.083333},\n\t\t\"RE78IR\": Point{-41.291667, 174.666667},\n\t\t\"PM45lm\": Point{35.5, 128.916667},\n\t}\n\n\tfor loc, p := range locTests {\n\t\tpoint, err := ParseLocator(loc)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s parsing error: %s\", loc, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tl, err := point.GridSquare()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s: %v to GridSquare(): %s\", loc, point, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !strings.EqualFold(l, loc) {\n\t\t\tt.Errorf(\"%s: parsed to %v produces %s\\n\", loc, point, l)\n\t\t}\n\n\t\tif !(almostEqual(p.Latitude, point.Latitude) && almostEqual(p.Longitude, point.Longitude)) {\n\t\t\tt.Errorf(\"%s: at %s, expeted %s\", loc, point, p)\n\t\t}\n\t}\n}\n\n\n\nfunc almostEqual(a, b float64) bool ", "output": "{\n\treturn math.Abs(a-b) < 1e-06\n}"} {"input": "package actor\n\nimport (\n\t\"time\"\n)\n\n\ntype RestartStatistics struct {\n\tfailureTimes []time.Time\n}\n\n\nfunc NewRestartStatistics() *RestartStatistics {\n\treturn &RestartStatistics{[]time.Time{}}\n}\n\n\nfunc (rs *RestartStatistics) FailureCount() int {\n\treturn len(rs.failureTimes)\n}\n\n\n\n\n\nfunc (rs *RestartStatistics) Reset() {\n\trs.failureTimes = []time.Time{}\n}\n\n\nfunc (rs *RestartStatistics) NumberOfFailures(withinDuration time.Duration) int {\n\tif withinDuration == 0 {\n\t\treturn len(rs.failureTimes)\n\t}\n\n\tnum := 0\n\tcurrTime := time.Now()\n\tfor _, t := range rs.failureTimes {\n\t\tif currTime.Sub(t) < withinDuration {\n\t\t\tnum++\n\t\t}\n\t}\n\treturn num\n}\n\nfunc (rs *RestartStatistics) Fail() ", "output": "{\n\trs.failureTimes = append(rs.failureTimes, time.Now())\n}"} {"input": "package cache\n\nimport (\n\tkapi \"k8s.io/kubernetes/pkg/api\"\n\tkapierrors \"k8s.io/kubernetes/pkg/api/errors\"\n\t\"k8s.io/kubernetes/pkg/controller/framework\"\n\n\toapi \"github.com/openshift/origin/pkg/api\"\n\tauthorizationapi \"github.com/openshift/origin/pkg/authorization/api\"\n\tclusterpolicyregistry \"github.com/openshift/origin/pkg/authorization/registry/clusterpolicy\"\n\t\"github.com/openshift/origin/pkg/client\"\n)\n\ntype InformerToClusterPolicyLister struct {\n\tframework.SharedIndexInformer\n}\n\n\nfunc (i *InformerToClusterPolicyLister) LastSyncResourceVersion() string {\n\treturn i.SharedIndexInformer.LastSyncResourceVersion()\n}\n\nfunc (i *InformerToClusterPolicyLister) ClusterPolicies() client.ClusterPolicyLister {\n\treturn i\n}\n\nfunc (i *InformerToClusterPolicyLister) List(options kapi.ListOptions) (*authorizationapi.ClusterPolicyList, error) {\n\tclusterPolicyList := &authorizationapi.ClusterPolicyList{}\n\treturnedList := i.GetIndexer().List()\n\tmatcher := clusterpolicyregistry.Matcher(oapi.ListOptionsToSelectors(&options))\n\tfor i := range returnedList {\n\t\tclusterPolicy := returnedList[i].(*authorizationapi.ClusterPolicy)\n\t\tif matches, err := matcher.Matches(clusterPolicy); err == nil && matches {\n\t\t\tclusterPolicyList.Items = append(clusterPolicyList.Items, *clusterPolicy)\n\t\t}\n\t}\n\treturn clusterPolicyList, nil\n}\n\n\n\nfunc (i *InformerToClusterPolicyLister) Get(name string) (*authorizationapi.ClusterPolicy, error) ", "output": "{\n\tkeyObj := &authorizationapi.ClusterPolicy{ObjectMeta: kapi.ObjectMeta{Name: name}}\n\tkey, _ := framework.DeletionHandlingMetaNamespaceKeyFunc(keyObj)\n\n\titem, exists, getErr := i.GetIndexer().GetByKey(key)\n\tif getErr != nil {\n\t\treturn nil, getErr\n\t}\n\tif !exists {\n\t\texistsErr := kapierrors.NewNotFound(authorizationapi.Resource(\"clusterpolicy\"), name)\n\t\treturn nil, existsErr\n\t}\n\treturn item.(*authorizationapi.ClusterPolicy), nil\n}"} {"input": "package upside_down\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/blevesearch/bleve/index\"\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\ntype UpsideDownCouchFieldDict struct {\n\tindexReader *IndexReader\n\titerator store.KVIterator\n\tendKey []byte\n\tfield uint16\n}\n\n\n\nfunc (r *UpsideDownCouchFieldDict) Next() (*index.DictEntry, error) {\n\tkey, val, valid := r.iterator.Current()\n\tif !valid {\n\t\treturn nil, nil\n\t}\n\n\tif bytes.Compare(key, r.endKey) > 0 {\n\t\treturn nil, nil\n\t}\n\n\tcurrRow, err := NewDictionaryRowKV(key, val)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unexpected error parsing dictionary row kv: %v\", err)\n\t}\n\trv := index.DictEntry{\n\t\tTerm: string(currRow.term),\n\t\tCount: currRow.count,\n\t}\n\tr.iterator.Next()\n\treturn &rv, nil\n\n}\n\nfunc (r *UpsideDownCouchFieldDict) Close() error {\n\treturn r.iterator.Close()\n}\n\nfunc incrementBytes(in []byte) []byte {\n\trv := make([]byte, len(in))\n\tcopy(rv, in)\n\tfor i := len(rv) - 1; i >= 0; i-- {\n\t\trv[i] = rv[i] + 1\n\t\tif rv[i] != 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn rv\n}\n\nfunc newUpsideDownCouchFieldDict(indexReader *IndexReader, field uint16, startTerm, endTerm []byte) (*UpsideDownCouchFieldDict, error) ", "output": "{\n\n\tstartKey := NewDictionaryRow(startTerm, field, 0).Key()\n\tif endTerm == nil {\n\t\tendTerm = []byte{ByteSeparator}\n\t}\n\tendKey := NewDictionaryRow(endTerm, field, 0).Key()\n\n\tit := indexReader.kvreader.Iterator(startKey)\n\n\treturn &UpsideDownCouchFieldDict{\n\t\tindexReader: indexReader,\n\t\titerator: it,\n\t\tfield: field,\n\t\tendKey: endKey,\n\t}, nil\n\n}"} {"input": "package rest\n\nimport (\n\t\"time\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\ntype TimerMiddleware struct{}\n\n\n\n\nfunc (mw *TimerMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc ", "output": "{\n\treturn func(ctx context.Context, w ResponseWriter, r *Request) {\n\n\t\tstart := time.Now()\n\t\tenv := EnvFromContext(ctx)\n\t\tenv[\"START_TIME\"] = &start\n\n\t\th(ctx, w, r)\n\n\t\tend := time.Now()\n\t\telapsed := end.Sub(start)\n\t\tenv[\"ELAPSED_TIME\"] = &elapsed\n\t}\n}"} {"input": "package repomodel\n\nimport (\n\t\"github.com/kopia/kopia/repo/content\"\n\t\"github.com/kopia/kopia/repo/manifest\"\n)\n\n\ntype RepositorySession struct {\n\tOpenRepo *OpenRepository\n\n\tWrittenContents ContentSet\n\tWrittenManifests ManifestSet\n}\n\n\nfunc (s *RepositorySession) WriteContent(cid content.ID) {\n\ts.WrittenContents.Add(cid)\n}\n\n\nfunc (s *RepositorySession) WriteManifest(mid manifest.ID) {\n\ts.WrittenManifests.Add(mid)\n}\n\n\n\n\n\n\nfunc (s *RepositorySession) Flush(wc *ContentSet, wm *ManifestSet) {\n\ts.OpenRepo.mu.Lock()\n\tdefer s.OpenRepo.mu.Unlock()\n\n\ts.OpenRepo.Contents.Add(wc.ids...)\n\ts.OpenRepo.Manifests.Add(wm.ids...)\n\n\ts.OpenRepo.RepoData.Contents.Add(wc.ids...)\n\ts.OpenRepo.RepoData.Manifests.Add(wm.ids...)\n\n\ts.WrittenContents.RemoveAll(wc.ids...)\n\ts.WrittenManifests.RemoveAll(wm.ids...)\n}\n\nfunc (s *RepositorySession) Refresh() ", "output": "{\n\ts.OpenRepo.Refresh()\n}"} {"input": "package lock\n\nimport (\n\t\"os\"\n)\n\ntype LockedFile interface {\n\tFile() *os.File\n\tExclusive() bool\n\tClose() error\n}\n\ntype DefaultLockedFile struct {\n\tf *os.File\n\texclusive bool\n}\n\nfunc OpenExclusive(path string, flag int, perm os.FileMode) (LockedFile, error) {\n\treturn open(path, flag, perm, true)\n}\n\n\n\nfunc (e *DefaultLockedFile) File() *os.File {\n\treturn e.f\n}\n\nfunc (e *DefaultLockedFile) Exclusive() bool {\n\treturn e.exclusive\n}\n\nfunc (e *DefaultLockedFile) Close() error {\n\terr := e.unlock()\n\terr2 := e.f.Close()\n\tif err2 != nil && err == nil {\n\t\terr = err2\n\t}\n\treturn err\n}\n\nfunc OpenShared(path string, flag int, perm os.FileMode) (LockedFile, error) ", "output": "{\n\treturn open(path, flag, perm, false)\n}"} {"input": "package tcp\n\nimport (\n\t\"flag\"\n\t\"net\"\n\t\"os\"\n\t\"bufio\"\n\t\"time\"\n\t\"log\"\n)\n\nfunc DefaultServer() {\n\n\tvar address = flag.String(\"address\", \":6789\", \"server address host:port\")\n\tflag.Parse()\n\n\tlistener, err := net.Listen(\"tcp4\", *address)\n\tif err != nil {\n\t\tlog.Println(\"Error listening:\", err)\n\t\tos.Exit(1)\n\t}\n\n\tdefer listener.Close()\n\n\tlog.Println(\"Listening on \" + *address)\n\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error accepting: \", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tlog.Printf(\"Received message %s -> %s \\n\", conn.RemoteAddr(), conn.LocalAddr())\n\t\tgo readFromClient(conn)\n\t}\n}\n\nfunc writeToClient(conn net.Conn) {\n\tdefer conn.Close()\n\tfor {\n\t\t_, err := conn.Write([]byte(\"hello client.\\r\\n\"))\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error to send message because of \", err.Error())\n\t\t\treturn\n\t\t}\n\t\tlog.Println(\"sent hello to client.\")\n\t\ttime.Sleep(time.Second)\n\t}\n\n}\n\nfunc readFromClient(conn net.Conn) ", "output": "{\n\treader := bufio.NewReader(conn)\n\tfor {\n\t\tlog.Println(\"receiving...\")\n\t\tline, isPrefix, err := reader.ReadLine()\n\t\tif err != nil {\n\t\t\tlog.Print(\"Error to read message because of \", err)\n\t\t\treturn\n\t\t} else {\n\t\t\tlog.Println(\"receive:\", string(line))\n\t\t\tlog.Println(\"isPrefix:\", isPrefix)\n\t\t}\n\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\n\t\"github.com/containerd/containerd/containers\"\n\t\"github.com/containerd/containerd/oci\"\n\tspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n)\n\nconst newLine = \"\\r\\n\"\n\n\n\nfunc withProcessArgs(args ...string) oci.SpecOpts {\n\treturn oci.WithProcessArgs(append([]string{\"cmd\", \"/c\"}, args...)...)\n}\n\nfunc withCat() oci.SpecOpts {\n\treturn oci.WithProcessArgs(\"cmd\", \"/c\", \"more\")\n}\n\nfunc withTrue() oci.SpecOpts {\n\treturn oci.WithProcessArgs(\"cmd\", \"/c\")\n}\n\nfunc withExecExitStatus(s *specs.Process, es int) {\n\ts.Args = []string{\"cmd\", \"/c\", \"exit\", strconv.Itoa(es)}\n}\n\nfunc withExecArgs(s *specs.Process, args ...string) {\n\ts.Args = append([]string{\"cmd\", \"/c\"}, args...)\n}\n\nfunc withExitStatus(es int) oci.SpecOpts ", "output": "{\n\treturn func(_ context.Context, _ oci.Client, _ *containers.Container, s *specs.Spec) error {\n\t\ts.Process.Args = []string{\"cmd\", \"/c\", \"exit\", strconv.Itoa(es)}\n\t\treturn nil\n\t}\n}"} {"input": "package config\n\nimport \"github.com/corestoreio/csfw/utils\"\n\n\n\ntype ScopePerm uint64\n\n\nvar ScopePermAll = ScopePerm(1<':\n\t\t\treturn false\n\t\tcase '\\032':\n\t\t\treturn false\n\t\tdefault:\n\t\t\tif !unicode.IsPrint(t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package tty\n\nimport (\n\t\"fmt\"\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/fortytw2/clarent/util\"\n\t\"os\"\n\t\"os/exec\"\n)\n\n\n\n\n\nfunc Getty(args []string) {\n\tapp := cli.NewApp()\n\tcli.AppHelpTemplate = util.AppletHelpTemplate\n\tapp.Name = \"getty\"\n\tapp.Usage = \"getty [/dev/tty*] [command to run]\"\n\tapp.Action = getty\n\n\tapp.Run(args)\n}\n\n\n\nfunc getty(c *cli.Context) ", "output": "{\n\n\tif len(c.Args()) < 2 {\n\t\tcli.ShowAppHelp(c)\n\t}\n\n\ttty, err := os.OpenFile(c.Args().Get(0), os.O_RDWR, 0)\n\tif err != nil {\n\t\tfmt.Println(\"unable to obtain tty device, try running as root\")\n\t}\n\n\tos.Stdout = tty\n\tos.Stderr = tty\n\tos.Stdin = tty\n\n\thostname, _ := os.Hostname()\n\n\tfmt.Println(\"Welcome to \", hostname, \"running at \", c.Args().Get(0))\n\tcmd := exec.Command(c.Args().Get(1))\n\tcmd.Stdin = tty\n\tcmd.Stdout = tty\n\tcmd.Stderr = tty\n\tcmd.Run()\n\n}"} {"input": "package meli\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nvar (\n\tclient = Client{\n\t\tClientID: 907054494590799,\n\t\tClientSecret: \"x7qFo8AudrLHEsDWm96Kwfu1xbYTiWbW\",\n\t}\n\n\tcode = \"your code\"\n\tredirectUrl = \"redirect url\"\n)\n\n\nfunc TestGetAuthUrl(t *testing.T) {\n\tresult, _ := client.GetAuthUrl(\"\", AuthUrls[\"MLB\"])\n\n\texpected := \"https://auth.mercadolivre.com.br/authorization?client_id=907054494590799&redirect_uri=&response_type=code\"\n\tif reflect.DeepEqual(expected, result) == false {\n\t\tt.Error(fmt.Sprintf(\"Expected: %s - Got: %s\", expected, result))\n\t}\n}\n\n\n\n\n\nfunc TestRefreshAccessToken(t *testing.T) {\n\terr := client.RefreshAccessToken()\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestAuthorize(t *testing.T) ", "output": "{\n\terr := client.Authorize(code, redirectUrl)\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}"} {"input": "package livereload\n\nimport (\n\t\"bytes\"\n\t\"sync\"\n\n\t\"github.com/gorilla/websocket\"\n)\n\ntype connection struct {\n\tws *websocket.Conn\n\n\tsend chan []byte\n\n\tcloser sync.Once\n}\n\nfunc (c *connection) close() {\n\tc.closer.Do(func() {\n\t\tclose(c.send)\n\t})\n}\n\nfunc (c *connection) reader() {\n\tfor {\n\t\t_, message, err := c.ws.ReadMessage()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif bytes.Contains(message, []byte(`\"command\":\"hello\"`)) {\n\t\t\tc.send <- []byte(`{\n\t\t\t\t\"command\": \"hello\",\n\t\t\t\t\"protocols\": [ \"http:livereload.com/protocols/official-7\" ],\n\t\t\t\t\"serverName\": \"Hugo\"\n\t\t\t}`)\n\t\t}\n\t}\n\tc.ws.Close()\n}\n\n\n\nfunc (c *connection) writer() ", "output": "{\n\tfor message := range c.send {\n\t\terr := c.ws.WriteMessage(websocket.TextMessage, message)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tc.ws.Close()\n}"} {"input": "package isatty\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestCygwinPipeName(t *testing.T) {\n\tif IsCygwinTerminal(os.Stdout.Fd()) {\n\t\tt.Fatal(\"should be false always\")\n\t}\n}\n\nfunc TestTerminal(t *testing.T) ", "output": "{\n\tIsTerminal(os.Stdout.Fd())\n}"} {"input": "package vml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/urn/schemas_microsoft_com/vml\"\n)\n\n\n\nfunc TestRoundrectMarshalUnmarshal(t *testing.T) {\n\tv := vml.NewRoundrect()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := vml.NewRoundrect()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestRoundrectConstructor(t *testing.T) ", "output": "{\n\tv := vml.NewRoundrect()\n\tif v == nil {\n\t\tt.Errorf(\"vml.NewRoundrect must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed vml.Roundrect should validate: %s\", err)\n\t}\n}"} {"input": "package library\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/vapi/library\"\n\t\"github.com/vmware/govmomi/vapi/rest\"\n)\n\ntype rm struct {\n\t*flags.ClientFlag\n\tforce bool\n}\n\nfunc init() {\n\tcli.Register(\"library.rm\", &rm{})\n}\n\nfunc (cmd *rm) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.ClientFlag, ctx = flags.NewClientFlag(ctx)\n\tcmd.ClientFlag.Register(ctx, f)\n}\n\nfunc (cmd *rm) Usage() string {\n\treturn \"NAME\"\n}\n\n\n\nfunc (cmd *rm) Run(ctx context.Context, f *flag.FlagSet) error {\n\treturn cmd.WithRestClient(ctx, func(c *rest.Client) error {\n\t\tm := library.NewManager(c)\n\t\tres, err := flags.ContentLibraryResult(ctx, c, \"\", f.Arg(0))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch t := res.GetResult().(type) {\n\t\tcase library.Library:\n\t\t\treturn m.DeleteLibrary(ctx, &t)\n\t\tcase library.Item:\n\t\t\treturn m.DeleteLibraryItem(ctx, &t)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"%q is a %T\", f.Arg(0), t)\n\t\t}\n\t})\n}\n\nfunc (cmd *rm) Description() string ", "output": "{\n\treturn `Delete library or item NAME.\n\nExamples:\n govc library.rm /library_name\n govc library.rm library_id # Use library id if multiple libraries have the same name\n govc library.rm /library_name/item_name`\n}"} {"input": "package file\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\n\n\ntype darwinExFileInfo struct {\n\tos.FileInfo\n\tfid FID\n\tpath string\n}\n\n\n\nfunc timespecToTime(ts syscall.Timespec) time.Time {\n\treturn time.Unix(int64(ts.Sec), int64(ts.Nsec))\n}\n\n\nfunc (fi *darwinExFileInfo) CTime() time.Time {\n\treturn timespecToTime(fi.Sys().(*syscall.Stat_t).Ctimespec)\n}\n\n\n\n\n\nfunc (fi *darwinExFileInfo) FID() FID {\n\treturn fi.fid\n}\n\n\nfunc (fi *darwinExFileInfo) Path() string {\n\treturn fi.path\n}\n\n\nfunc systemExFileInfo(fi os.FileInfo, path string) *darwinExFileInfo {\n\tfid := FID{\n\t\tIDLow: fi.Sys().(*syscall.Stat_t).Ino,\n\t}\n\tabsolute, _ := filepath.Abs(path)\n\treturn &darwinExFileInfo{\n\t\tFileInfo: fi,\n\t\tfid: fid,\n\t\tpath: filepath.Clean(absolute),\n\t}\n}\n\nfunc (fi *darwinExFileInfo) ATime() time.Time ", "output": "{\n\treturn timespecToTime(fi.Sys().(*syscall.Stat_t).Atimespec)\n}"} {"input": "package u\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync/atomic\"\n)\n\n\ntype FileWalkEntry struct {\n\tDir string\n\tFileInfo os.FileInfo\n}\n\n\n\n\n\ntype FileWalk struct {\n\tstartDir string\n\tFilesChan chan *FileWalkEntry\n\taskedToStop int32\n}\n\n\nfunc (ft *FileWalk) Stop() {\n\tatomic.StoreInt32(&ft.askedToStop, 1)\n\tfor range ft.FilesChan {\n\t}\n}\n\nfunc fileWalkWorker(ft *FileWalk) {\n\ttoVisit := []string{ft.startDir}\n\tdefer close(ft.FilesChan)\n\n\tfor len(toVisit) > 0 {\n\t\tshouldStop := atomic.LoadInt32(&ft.askedToStop)\n\t\tif shouldStop > 0 {\n\t\t\treturn\n\t\t}\n\t\tdir := toVisit[0]\n\t\ttoVisit = StringsRemoveFirst(toVisit)\n\n\t\tfiles, err := ioutil.ReadDir(dir)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, fi := range files {\n\t\t\tpath := filepath.Join(dir, fi.Name())\n\t\t\tmode := fi.Mode()\n\t\t\tif mode.IsDir() {\n\t\t\t\ttoVisit = append(toVisit, path)\n\t\t\t} else if mode.IsRegular() {\n\t\t\t\tfte := &FileWalkEntry{\n\t\t\t\t\tDir: dir,\n\t\t\t\t\tFileInfo: fi,\n\t\t\t\t}\n\t\t\t\tft.FilesChan <- fte\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nfunc StartFileWalk(startDir string) *FileWalk {\n\tch := make(chan *FileWalkEntry, 1024*64)\n\tft := &FileWalk{\n\t\tstartDir: startDir,\n\t\tFilesChan: ch,\n\t}\n\tgo fileWalkWorker(ft)\n\treturn ft\n}\n\nfunc (e *FileWalkEntry) Path() string ", "output": "{\n\treturn filepath.Join(e.Dir, e.FileInfo.Name())\n}"} {"input": "package lib\n\nfunc cacheHintRegistryList() string {\n\treturn \"catalog:\"\n}\n\n\n\nfunc cacheHintTagDetails(repository string) string {\n\treturn \"pull:\" + repository\n}\n\nfunc cacheHintTagList(repository string) string ", "output": "{\n\treturn \"pull:\" + repository\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc foo(x int) bool {\n\treturn x == x \n}\n\nfunc isNaN(x float32) bool {\n\treturn x != x \n}\n\nfunc main() {\n\tfoo(42)\n}\n\nconst mode = \"Debug\"\n\nfunc log(msg string) {\n\tif mode == \"Debug\" {\n\t\tfmt.Println(msg)\n\t}\n}\n\nfunc bar() {\n\tif ptrsize == 8 { \n\t\tfmt.Println()\n\t}\n}\n\nfunc bump(x *int) {\n\t*x++\n}\n\nfunc baz() bool {\n\tvar x = 0\n\tbump(&x)\n\treturn x == 0\n}\n\ntype counter int\n\n\n\nfunc (x counter) bimp() {\n\tx++\n}\n\nfunc baz2() bool {\n\tvar x counter\n\tx.bump()\n\treturn x == 0 \n}\n\nfunc baz3() bool {\n\tvar y counter\n\ty.bimp()\n\treturn y == 0 \n}\n\nfunc (x *counter) bump() ", "output": "{\n\t*x++\n}"} {"input": "package client\n\nimport (\n\t\"errors\"\n\t\"github.com/manythumbed/gegenstand/packets\"\n\t\"github.com/manythumbed/gegenstand/protocol\"\n\t\"io\"\n\t\"net\"\n)\n\ntype Message interface {\n}\n\ntype MessageHandler interface {\n\tHandle(message Message)\n}\n\ntype Connection interface {\n\tConnect() error\n\tDisconnect() error\n\tUnsubscribe(topics ...string) error\n\tSubscribe(handler MessageHandler, topics ...protocol.Subscription) error\n\tPublish(topic string, qos protocol.Qos, retained bool, payload []byte) error\n}\n\ntype dummy struct {\n\tconnected bool\n\tconn net.Conn\n}\n\n\n\nfunc (d *dummy) Disconnect() error {\n\tif !d.connected {\n\t\treturn errors.New(\"Not connected\")\n\t}\n\n\terr := disconnect(d.conn)\n\terr = d.conn.Close()\n\n\td.connected = false\n\treturn err\n}\n\nfunc disconnect(w io.Writer) error {\n\t_, err := w.Write(packets.WriteDisconnect())\n\n\treturn err\n}\n\nfunc (d *dummy) Connect() error ", "output": "{\n\tif d.connected {\n\t\treturn errors.New(\"Already connected\")\n\t}\n\n\n\n\td.connected = true\n\treturn nil\n}"} {"input": "package containerd\n\nimport (\n\t\"testing\"\n\n\tspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n)\n\nfunc TestGenerateSpec(t *testing.T) {\n\ts, err := GenerateSpec()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif s == nil {\n\t\tt.Fatal(\"GenerateSpec() returns a nil spec\")\n\t}\n\n\tdefaults := defaltCaps()\n\tfor _, cl := range [][]string{\n\t\ts.Process.Capabilities.Ambient,\n\t\ts.Process.Capabilities.Bounding,\n\t\ts.Process.Capabilities.Permitted,\n\t\ts.Process.Capabilities.Inheritable,\n\t\ts.Process.Capabilities.Effective,\n\t} {\n\t\tfor i := 0; i < len(defaults); i++ {\n\t\t\tif cl[i] != defaults[i] {\n\t\t\t\tt.Errorf(\"cap at %d does not match set %q != %q\", i, defaults[i], cl[i])\n\t\t\t}\n\t\t}\n\t}\n\n\tdefaultNS := defaultNamespaces()\n\tfor i, ns := range s.Linux.Namespaces {\n\t\tif defaultNS[i] != ns {\n\t\t\tt.Errorf(\"ns at %d does not match set %q != %q\", i, defaultNS[i], ns)\n\t\t}\n\t}\n\n\tif s.Process.Terminal {\n\t\tt.Error(\"terminal set on default process\")\n\t}\n}\n\nfunc TestSpecWithTTY(t *testing.T) {\n\ts, err := GenerateSpec(WithTTY)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !s.Process.Terminal {\n\t\tt.Error(\"terminal net set WithTTY()\")\n\t}\n\tv := s.Process.Env[len(s.Process.Env)-1]\n\tif v != \"TERM=xterm\" {\n\t\tt.Errorf(\"xterm not set in env for TTY\")\n\t}\n}\n\n\n\nfunc TestWithLinuxNamespace(t *testing.T) ", "output": "{\n\treplacedNS := specs.LinuxNamespace{Type: specs.NetworkNamespace, Path: \"/var/run/netns/test\"}\n\ts, err := GenerateSpec(WithLinuxNamespace(replacedNS))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdefaultNS := defaultNamespaces()\n\tfound := false\n\tfor i, ns := range s.Linux.Namespaces {\n\t\tif ns == replacedNS && !found {\n\t\t\tfound = true\n\t\t\tcontinue\n\t\t}\n\t\tif defaultNS[i] != ns {\n\t\t\tt.Errorf(\"ns at %d does not match set %q != %q\", i, defaultNS[i], ns)\n\t\t}\n\t}\n}"} {"input": "package iso20022\n\n\ntype CardPaymentEnvironment37 struct {\n\n\tAcquirer *Acquirer4 `xml:\"Acqrr\"`\n\n\tMerchantIdentification *GenericIdentification53 `xml:\"MrchntId,omitempty\"`\n\n\tPOIIdentification *GenericIdentification53 `xml:\"POIId,omitempty\"`\n\n\tPOIComponent []*PointOfInteractionComponent5 `xml:\"POICmpnt,omitempty\"`\n}\n\nfunc (c *CardPaymentEnvironment37) AddAcquirer() *Acquirer4 {\n\tc.Acquirer = new(Acquirer4)\n\treturn c.Acquirer\n}\n\nfunc (c *CardPaymentEnvironment37) AddMerchantIdentification() *GenericIdentification53 {\n\tc.MerchantIdentification = new(GenericIdentification53)\n\treturn c.MerchantIdentification\n}\n\n\n\nfunc (c *CardPaymentEnvironment37) AddPOIComponent() *PointOfInteractionComponent5 {\n\tnewValue := new(PointOfInteractionComponent5)\n\tc.POIComponent = append(c.POIComponent, newValue)\n\treturn newValue\n}\n\nfunc (c *CardPaymentEnvironment37) AddPOIIdentification() *GenericIdentification53 ", "output": "{\n\tc.POIIdentification = new(GenericIdentification53)\n\treturn c.POIIdentification\n}"} {"input": "package parentlocator\n\n\n\ntype ParseError struct {\n\tLocatorField string\n\terr error\n}\n\n\n\nfunc (e *ParseError) Error() string {\n\treturn \"Parse parent locator field\" + \" '\" + e.LocatorField + \"' failed: \" + e.err.Error()\n}\n\n\n\n\n\n\n\n\n\nfunc NewParseError(locatorField string, err error) error {\n\treturn &ParseError{\n\t\tLocatorField: locatorField,\n\t\terr: err,\n\t}\n}\n\nfunc (e *ParseError) GetInnerErr() error ", "output": "{\n\treturn e.err\n}"} {"input": "package trueskill\n\nimport (\n\t\"errors\"\n\t\"math\"\n)\n\nconst (\n\tDefMu = 25.0\n\n\tDefSig = DefMu / 3\n\n\tDefBeta = DefSig / 2\n\n\tDefTau = DefSig / 100\n)\n\n\ntype Game struct {\n\tbeta float64\n\ttau float64\n\tpDraw float64\n}\n\n\nfunc NewDefaultGame() Game {\n\treturn NewGame(DefBeta, DefTau, 0)\n}\n\n\n\n\n\n\n\n\n\nfunc NewGame(beta, tau, pDraw float64) Game {\n\treturn Game{\n\t\tbeta: beta,\n\t\ttau: tau,\n\t\tpDraw: pDraw,\n\t}\n}\n\n\n\n\n\n\n\nfunc (g *Game) CalcMatchQuality(teams []Team) (result float64, err error) {\n\tif len(teams) > 2 {\n\t\terr = errors.New(\"CalcMatchQuality does not support more than 2 teams yet.\")\n\t\treturn\n\t}\n\n\tnPlayers := float64(teams[0].Size() + teams[1].Size())\n\n\tt1Mean := teams[0].GetMu()\n\tt1Var := teams[0].GetVar()\n\tt2Mean := teams[1].GetMu()\n\tt2Var := teams[1].GetVar()\n\n\tsqrt := math.Sqrt(\n\t\t(nPlayers * g.beta * g.beta) /\n\t\t\t(nPlayers*g.beta*g.beta + t1Var + t2Var))\n\n\texp := math.Exp(\n\t\t-1 * (t1Mean - t2Mean) * (t1Mean - t2Mean) /\n\t\t\t(2 * (nPlayers*g.beta*g.beta + t1Var + t2Var)))\n\n\tresult = sqrt * exp\n\treturn\n}\n\nfunc (g *Game) CalcNewRatings(teams []Team, ranks []int) (t []Team, err error) ", "output": "{\n\treturn\n}"} {"input": "package leveldb\n\nimport (\n\t\"testing\"\n\n\t\"camlistore.org/third_party/github.com/syndtr/goleveldb/leveldb/testutil\"\n)\n\n\n\nfunc TestLevelDB(t *testing.T) ", "output": "{\n\ttestutil.RunSuite(t, \"LevelDB Suite\")\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"k8s.io/client-go/kubernetes/typed/batch/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeBatchV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeBatchV1beta1) CronJobs(namespace string) v1beta1.CronJobInterface {\n\treturn &FakeCronJobs{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeBatchV1beta1) RESTClient() rest.Interface ", "output": "{\n\tvar ret *rest.RESTClient\n\treturn ret\n}"} {"input": "package daemon\n\nimport (\n\t\"path/filepath\"\n\n\t\"github.com/pkg/errors\"\n\n\t\"github.com/mutagen-io/mutagen/pkg/filesystem\"\n)\n\nconst (\n\tlockName = \"daemon.lock\"\n\tendpointName = \"daemon.sock\"\n)\n\n\n\n\n\n\n\nfunc lockPath() (string, error) {\n\treturn subpath(lockName)\n}\n\n\n\nfunc EndpointPath() (string, error) {\n\treturn subpath(endpointName)\n}\n\nfunc subpath(name string) (string, error) ", "output": "{\n\tdaemonRoot, err := filesystem.Mutagen(true, filesystem.MutagenDaemonDirectoryName)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to compute daemon directory\")\n\t}\n\n\treturn filepath.Join(daemonRoot, name), nil\n}"} {"input": "package factor\n\nimport (\n\t\"github.com/jesand/stats\"\n\t\"github.com/jesand/stats/dist\"\n\t\"github.com/jesand/stats/variable\"\n)\n\n\n\n\ntype Factor interface {\n\n\tAdjacent() []variable.RandomVariable\n\n\tScore() float64\n}\n\n\n\n\nfunc NewDistFactor(vars []variable.RandomVariable, distr dist.Dist) *DistFactor {\n\treturn &DistFactor{\n\t\tVars: vars,\n\t\tDist: distr,\n\t}\n}\n\n\ntype DistFactor struct {\n\tVars []variable.RandomVariable\n\tDist dist.Dist\n}\n\n\nfunc (factor DistFactor) Adjacent() []variable.RandomVariable {\n\treturn factor.Vars\n}\n\n\n\n\n\nfunc NewConstFactor(vars []variable.RandomVariable, value float64) *ConstFactor {\n\treturn &ConstFactor{\n\t\tVars: vars,\n\t\tValue: value,\n\t}\n}\n\n\ntype ConstFactor struct {\n\tVars []variable.RandomVariable\n\tValue float64\n}\n\n\nfunc (factor ConstFactor) Adjacent() []variable.RandomVariable {\n\treturn factor.Vars\n}\n\n\nfunc (factor ConstFactor) Score() float64 {\n\treturn factor.Value\n}\n\nfunc (factor DistFactor) Score() float64 ", "output": "{\n\tvar (\n\t\tnumVars = factor.Dist.NumVars()\n\t\tnumParams = factor.Dist.NumParams()\n\t)\n\tif len(factor.Vars) != numVars+numParams {\n\t\tpanic(stats.ErrfFactorVarNum(numVars, numParams, len(factor.Vars)))\n\t}\n\tvar (\n\t\tvars = make([]float64, numVars)\n\t\tparams = make([]float64, numParams)\n\t)\n\tfor i, rv := range factor.Vars {\n\t\tif i < len(vars) {\n\t\t\tvars[i] = rv.Val()\n\t\t} else {\n\t\t\tparams[i-len(vars)] = rv.Val()\n\t\t}\n\t}\n\treturn factor.Dist.Score(vars, params)\n}"} {"input": "package kubernikusctl\n\nimport (\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/sapcc/kubernikus/pkg/cmd/kubernikusctl/common\"\n\t\"github.com/sapcc/kubernikus/pkg/cmd/kubernikusctl/delete\"\n)\n\nfunc deleteRun(c *cobra.Command, args []string) {\n\tc.Help()\n}\n\n\n\nfunc NewDeleteCommand() *cobra.Command ", "output": "{\n\to := delete.DeleteOptions{\n\t\tOpenstack: common.NewOpenstackClient(),\n\t}\n\n\tc := &cobra.Command{\n\t\tUse: \"delete [object]\",\n\t\tShort: \"Deletes an object\",\n\t\tPersistentPreRun: o.PersistentPreRun,\n\t\tRun: deleteRun,\n\t}\n\to.BindFlags(c.PersistentFlags())\n\tc.AddCommand(o.NewClusterCommand())\n\treturn c\n}"} {"input": "package command\n\nimport (\n \"fmt\"\n)\n\n\n\n\nfunc CommandRemove(options map[string]string, rest []string, cwd string) ", "output": "{\n fmt.Println(options)\n}"} {"input": "package firewallsso\n\nimport (\n\t\"testing\"\n\n\t\"github.com/inverse-inc/go-radius/rfc2865\"\n\t\"github.com/inverse-inc/go-radius/rfc2866\"\n)\n\nfunc TestFortiGateStartRadiusPacket(t *testing.T) {\n\tf := FortiGate{Password: \"secret\"}\n\n\tp := f.startRadiusPacket(ctx, sampleInfo, 86400)\n\n\tif rfc2866.AcctStatusType_Get(p) != 1 {\n\t\tt.Errorf(\"Incorrect Acct-Status-Type in SSO packet.\")\n\t}\n\n\tif rfc2865.FramedIPAddress_Get(p).String() != sampleInfo[\"ip\"] {\n\t\tt.Errorf(\"Incorrect Framed-IP-Address in SSO packet.\")\n\t}\n\n\tif string(rfc2865.UserName_Get(p)) != sampleInfo[\"username\"] {\n\t\tt.Errorf(\"Incorrect User-Name in SSO packet.\")\n\t}\n\n\tif string(rfc2865.CallingStationID_Get(p)) != sampleInfo[\"mac\"] {\n\t\tt.Errorf(\"Incorrect Calling-Station-Id in SSO packet.\")\n\t}\n}\n\n\n\nfunc TestFortiGateStopRadiusPacket(t *testing.T) ", "output": "{\n\tf := FortiGate{Password: \"secret\"}\n\n\tp := f.stopRadiusPacket(ctx, sampleInfo)\n\n\tif rfc2866.AcctStatusType_Get(p) != 2 {\n\t\tt.Errorf(\"Incorrect Acct-Status-Type in SSO packet.\")\n\t}\n\n\tif rfc2865.FramedIPAddress_Get(p).String() != sampleInfo[\"ip\"] {\n\t\tt.Errorf(\"Incorrect Framed-IP-Address in SSO packet.\")\n\t}\n\n\tif string(rfc2865.UserName_Get(p)) != sampleInfo[\"username\"] {\n\t\tt.Errorf(\"Incorrect User-Name in SSO packet.\")\n\t}\n\n\tif string(rfc2865.CallingStationID_Get(p)) != sampleInfo[\"mac\"] {\n\t\tt.Errorf(\"Incorrect Calling-Station-Id in SSO packet.\")\n\t}\n}"} {"input": "package config\n\nimport (\n\t\"encoding/xml\"\n)\n\ntype defXMLReader struct {\n\topts ReaderOptions\n}\n\n\nfunc NewXMLReader(opts ...ReaderOptionFunc) Reader {\n\tr := &defXMLReader{}\n\tfor _, o := range opts {\n\t\to(&r.opts)\n\t}\n\treturn r\n}\n\n\n\nfunc (*defXMLReader) Dump(v interface{}) ([]byte, error) {\n\treturn xml.Marshal(v)\n}\n\nfunc (*defXMLReader) ParseData(data []byte, model interface{}) error {\n\treturn ParseXMLConfig(data, model)\n}\n\n\nfunc ReadXMLFile(name string) ([]byte, error) {\n\tdata, _, err := filesRepo.Read(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}\n\n\nfunc ParseXMLConfig(data []byte, model interface{}) error {\n\treturn xml.Unmarshal(data, model)\n}\n\nfunc (p *defXMLReader) Read(model interface{}) error ", "output": "{\n\tdata, err := ReadXMLFile(p.opts.filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ParseXMLConfig(data, model)\n}"} {"input": "package driver\n\nimport \"os/exec\"\n\n\nvar supportedDrivers = []string{\n\tVirtualBox,\n}\n\n\n\nfunc VBoxManagePath() string ", "output": "{\n\tcmd := \"VBoxManage\"\n\tif path, err := exec.LookPath(cmd); err == nil {\n\t\treturn path\n\t}\n\treturn cmd\n}"} {"input": "package popcount\n\n\nvar pc [256]byte\n\nfunc init() {\n\tfor i := range pc {\n\t\tpc[i] = pc[i/2] + byte(i&1)\n\t}\n}\n\n\n\n\nfunc PopCount2(x uint64) int {\n\tvar sum byte\n\tfor i := uint(0); i < 8; i++ {\n\t\tsum += pc[byte(x>>(i*8))]\n\t}\n\treturn int(sum)\n}\n\nfunc PopCount(x uint64) int ", "output": "{\n\treturn int(pc[byte(x>>(0*8))] +\n\t\tpc[byte(x>>(1*8))] +\n\t\tpc[byte(x>>(2*8))] +\n\t\tpc[byte(x>>(3*8))] +\n\t\tpc[byte(x>>(4*8))] +\n\t\tpc[byte(x>>(5*8))] +\n\t\tpc[byte(x>>(6*8))] +\n\t\tpc[byte(x>>(7*8))])\n}"} {"input": "package sync \n\nimport (\n\t\"github.com/cenkalti/backoff\"\n\t\"github.com/sirupsen/logrus\"\n)\n\ntype deferredChange struct {\n\tmarshaledChange *[]byte\n\tpeerPublicKey [32]byte\n\tlastAttempted uint64\n\tdone bool\n}\n\nfunc (s *Sync) handleDeferredChanges() {\n\tfor {\n\t\tc := <-*s.deferredChangeChan\n\t\tif !c.done {\n\t\t\top := func() error {\n\t\t\t\ts.Logger.WithFields(logrus.Fields{\"package\": \"sync\"}).Debug(\"Retrying change propogation\")\n\t\t\t\te := s.notifyPeer(*s.findPeerFromKey(c.peerPublicKey), c.marshaledChange, true)\n\t\t\t\treturn e\n\t\t\t}\n\t\t\tgo backoff.Retry(op, backoff.NewExponentialBackOff())\n\t\t\tc.done = true\n\t\t}\n\t}\n}\n\n\n\nfunc (s *Sync) findPeerFromKey(key [32]byte) *Peer ", "output": "{\n\tfor _, p := range *s.Peers {\n\t\tif *p.publicKey == key {\n\t\t\treturn &p\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package global\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/propagation\"\n)\n\n\n\n\ntype textMapPropagator struct {\n\tmtx sync.Mutex\n\tonce sync.Once\n\tdelegate propagation.TextMapPropagator\n\tnoop propagation.TextMapPropagator\n}\n\n\n\nvar _ propagation.TextMapPropagator = (*textMapPropagator)(nil)\n\n\n\n\n\n\nfunc (p *textMapPropagator) SetDelegate(delegate propagation.TextMapPropagator) {\n\tif delegate == nil {\n\t\treturn\n\t}\n\n\tp.mtx.Lock()\n\tp.once.Do(func() { p.delegate = delegate })\n\tp.mtx.Unlock()\n}\n\n\n\n\nfunc (p *textMapPropagator) effectiveDelegate() propagation.TextMapPropagator {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tif p.delegate != nil {\n\t\treturn p.delegate\n\t}\n\treturn p.noop\n}\n\n\nfunc (p *textMapPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) {\n\tp.effectiveDelegate().Inject(ctx, carrier)\n}\n\n\nfunc (p *textMapPropagator) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context {\n\treturn p.effectiveDelegate().Extract(ctx, carrier)\n}\n\n\nfunc (p *textMapPropagator) Fields() []string {\n\treturn p.effectiveDelegate().Fields()\n}\n\nfunc newTextMapPropagator() *textMapPropagator ", "output": "{\n\treturn &textMapPropagator{\n\t\tnoop: propagation.NewCompositeTextMapPropagator(),\n\t}\n}"} {"input": "package balanced\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n)\n\ntype Customer struct {\n\tAddress *Address `json:\"address,omitempty\"`\n\tBusinessName string `json:\"business_name,omitempty\"`\n\tCreatedAt time.Time `json:\"created_at,omitempty\"`\n\tDobMonth int `json:\"dob_month,omitempty\"`\n\tDobYear int `json:\"dob_year,omitempty\"`\n\tEin string `json:\"ein,omitempty\"`\n\tEmail string `json:\"email,omitempty\"`\n\tID string `json:\"id,omitempty\"`\n\tMeta map[string]interface{} `json:\"meta,omitempty\"`\n\tName string `json:\"name,omitempty\"`\n\tPhone string `json:\"phone,omitempty\"`\n\tSSNLast4 string `json:\"ssn_last4,omitempty\"`\n\tMerchantStatus string `json:\"merchant_status,omitempty\"`\n}\n\ntype customerResponse struct {\n\tCustomers []*Customer `json:\"customers\"`\n}\n\nfunc (c *Customer) path() string {\n\treturn \"/customers\"\n}\n\nfunc (c *Customer) getID() string {\n\treturn c.ID\n}\n\nfunc (c *Customer) getOwnerPath() string {\n\treturn \"\"\n}\n\n\n\nfunc (c *Customer) canDelete() bool {\n\treturn true\n}\n\nfunc (c *Customer) IsVerified() bool {\n\treturn c.MerchantStatus == \"underwritten\"\n}\n\nfunc (c *Customer) singleResponse(data []byte) ", "output": "{\n\tparsedResponse := new(customerResponse)\n\tjson.Unmarshal(data, &parsedResponse)\n\t*c = *parsedResponse.Customers[0]\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\n\t\"mvdan.cc/fdroidcl/fdroid\"\n)\n\nvar cmdDownload = &Command{\n\tUsageLine: \"download \",\n\tShort: \"Download an app\",\n}\n\nfunc init() {\n\tcmdDownload.Run = runDownload\n}\n\nfunc runDownload(args []string) error {\n\tif len(args) < 1 {\n\t\treturn fmt.Errorf(\"no package names given\")\n\t}\n\tapps, err := findApps(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdevice, _ := maybeOneDevice()\n\tfor _, app := range apps {\n\t\tapk := app.SuggestedApk(device)\n\t\tif apk == nil {\n\t\t\treturn fmt.Errorf(\"no suggested APK found for %s\", app.PackageName)\n\t\t}\n\t\tpath, err := downloadApk(apk)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"APK available in %s\\n\", path)\n\t}\n\treturn nil\n}\n\n\n\nfunc apkPath(apkname string) string {\n\tapksDir := subdir(mustCache(), \"apks\")\n\treturn filepath.Join(apksDir, apkname)\n}\n\nfunc downloadApk(apk *fdroid.Apk) (string, error) ", "output": "{\n\turl := apk.URL()\n\tpath := apkPath(apk.ApkName)\n\tif err := downloadEtag(url, path, apk.Hash); err == errNotModified {\n\t} else if err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not download %s: %v\", apk.AppID, err)\n\t}\n\treturn path, nil\n}"} {"input": "package datacatalog\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteCustomPropertyRequest struct {\n\n\tCatalogId *string `mandatory:\"true\" contributesTo:\"path\" name:\"catalogId\"`\n\n\tNamespaceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"namespaceId\"`\n\n\tCustomPropertyKey *string `mandatory:\"true\" contributesTo:\"path\" name:\"customPropertyKey\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteCustomPropertyRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request DeleteCustomPropertyRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request DeleteCustomPropertyRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteCustomPropertyResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteCustomPropertyResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteCustomPropertyResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteCustomPropertyRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package controller\n\nimport \"fmt\"\nimport \"html/template\"\nimport \"net/http\"\nimport . \"model\"\n\n\n\nfunc Deploy(response http.ResponseWriter, request *http.Request) ", "output": "{\n\tliumiaocn := Person{Id: 1001, Name: \"liumiaocn\", Country: \"China\"}\n\n\ttmpl, err := template.ParseFiles(\"./view/deploy.html\")\n\tif err != nil {\n\t\tfmt.Println(\"Error happened..\")\n\t}\n\ttmpl.Execute(response, liumiaocn)\n}"} {"input": "package calendar\n\nimport (\n\t\"time\"\n)\n\nvar (\n\tentries = make(map[int]Entry)\n\tindex int\n)\n\ntype Entry struct {\n\tID int\n\tTitle string\n\tStarts time.Time\n\tFinishes time.Time\n}\n\nfunc (e Entry) Duration() time.Duration {\n\treturn e.Finishes.Sub(e.Starts)\n}\n\nfunc Lookup(id int) (Entry, bool) {\n\te, isPresent := entries[id]\n\treturn e, isPresent\n}\n\nfunc Add(e Entry) Entry {\n\tindex++\n\te.ID = index\n\tUpdate(e)\n\treturn e\n}\n\nfunc Update(e Entry) {\n\tentries[e.ID] = e\n}\n\nfunc Remove(id int) {\n\tdelete(entries, id)\n}\n\n\n\nfunc All() []Entry {\n\tall := []Entry{}\n\tfor _, e := range entries {\n\t\tall = append(all, e)\n\t}\n\treturn all\n}\n\nfunc Count() int ", "output": "{\n\treturn len(entries)\n}"} {"input": "package core\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tclientset \"k8s.io/client-go/kubernetes\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/quota\"\n\t\"k8s.io/kubernetes/pkg/quota/generic\"\n)\n\n\n\n\nfunc NewSecretEvaluator(kubeClient clientset.Interface) quota.Evaluator ", "output": "{\n\treturn &generic.ObjectCountEvaluator{\n\t\tAllowCreateOnUpdate: false,\n\t\tInternalGroupKind: api.Kind(\"Secret\"),\n\t\tResourceName: api.ResourceSecrets,\n\t\tListFuncByNamespace: func(namespace string, options metav1.ListOptions) ([]runtime.Object, error) {\n\t\t\titemList, err := kubeClient.Core().Secrets(namespace).List(options)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresults := make([]runtime.Object, 0, len(itemList.Items))\n\t\t\tfor i := range itemList.Items {\n\t\t\t\tresults = append(results, &itemList.Items[i])\n\t\t\t}\n\t\t\treturn results, nil\n\t\t},\n\t}\n}"} {"input": "package http\n\nimport \"github.com/viant/endly\"\n\n\n\nfunc init() ", "output": "{\n\tendly.Registry.Register(func() endly.Service {\n\t\treturn New()\n\t})\n}"} {"input": "package testhelpers\n\nimport \"github.com/go-kit/kit/metrics\"\n\n\ntype CollectingCounter struct {\n\tCounterValue float64\n\tLastLabelValues []string\n}\n\n\nfunc (c *CollectingCounter) With(labelValues ...string) metrics.Counter {\n\tc.LastLabelValues = labelValues\n\treturn c\n}\n\n\nfunc (c *CollectingCounter) Add(delta float64) {\n\tc.CounterValue += delta\n}\n\n\ntype CollectingGauge struct {\n\tGaugeValue float64\n\tLastLabelValues []string\n}\n\n\nfunc (g *CollectingGauge) With(labelValues ...string) metrics.Gauge {\n\tg.LastLabelValues = labelValues\n\treturn g\n}\n\n\n\n\n\nfunc (g *CollectingGauge) Add(delta float64) {\n\tg.GaugeValue = delta\n}\n\n\ntype CollectingHealthCheckMetrics struct {\n\tGauge *CollectingGauge\n}\n\n\nfunc (m *CollectingHealthCheckMetrics) BackendServerUpGauge() metrics.Gauge {\n\treturn m.Gauge\n}\n\n\nfunc NewCollectingHealthCheckMetrics() *CollectingHealthCheckMetrics {\n\treturn &CollectingHealthCheckMetrics{&CollectingGauge{}}\n}\n\nfunc (g *CollectingGauge) Set(value float64) ", "output": "{\n\tg.GaugeValue = value\n}"} {"input": "package app\n\nimport (\n\t\"time\"\n\n\tgenericcontrollermanager \"k8s.io/kubernetes/cmd/controller-manager/app\"\n)\n\n\ntype ExtraConfig struct {\n\tNodeStatusUpdateFrequency time.Duration\n}\n\n\ntype Config struct {\n\tGeneric genericcontrollermanager.Config\n\tExtra ExtraConfig\n}\n\ntype completedConfig struct {\n\tGeneric genericcontrollermanager.CompletedConfig\n\tExtra *ExtraConfig\n}\n\n\ntype CompletedConfig struct {\n\t*completedConfig\n}\n\n\n\n\nfunc (c *Config) Complete() *CompletedConfig ", "output": "{\n\tcc := completedConfig{\n\t\tc.Generic.Complete(),\n\t\t&c.Extra,\n\t}\n\n\treturn &CompletedConfig{&cc}\n}"} {"input": "package main\n\nimport \"testing\"\n\n\n\nfunc Test_swap_LT(t *testing.T) {\n\tx := 10\n\ty := 100\n\n\tswapIfgt(&x, &y)\n\n\tif y != 100 || x != 10 {\n\t\tt.Error(\"Cannot swap\")\n\t}\n}\n\nfunc Test_swap_GT(t *testing.T) ", "output": "{\n\tx := 100\n\ty := 10\n\n\tswapIfgt(&x, &y)\n\n\tif y != 100 || x != 10 {\n\t\tt.Error(\"Did not swap\")\n\t}\n}"} {"input": "package iso20022\n\n\ntype CashAccountType2Choice struct {\n\n\tCode *ExternalCashAccountType1Code `xml:\"Cd\"`\n\n\tProprietary *Max35Text `xml:\"Prtry\"`\n}\n\n\n\nfunc (c *CashAccountType2Choice) SetProprietary(value string) {\n\tc.Proprietary = (*Max35Text)(&value)\n}\n\nfunc (c *CashAccountType2Choice) SetCode(value string) ", "output": "{\n\tc.Code = (*ExternalCashAccountType1Code)(&value)\n}"} {"input": "package http_test\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"testing\"\n\n\thttpFetcher \"github.com/wanelo/image-server/fetcher/http\"\n\n\t. \"github.com/wanelo/image-server/test\"\n)\n\nfunc TestUniqueFetcher(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"image/jpeg\")\n\t\tfmt.Fprintln(w, `there is some content`)\n\t}))\n\tdefer ts.Close()\n\n\tf := &httpFetcher.Fetcher{}\n\n\tdefer os.Remove(\"valid\")\n\terr := f.Fetch(ts.URL, \"valid\")\n\n\tOk(t, err)\n}\n\n\n\nfunc TestURLEscaping(t *testing.T) {\n\tpath := \"//hell[o]/(x)//two%20words/boo.jpg?something=fo(o)\"\n\texpectedPath := \"/hell[o]/(x)//two%20words/boo.jpg?something=fo(o)\"\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.RequestURI != expectedPath {\n\t\t\tt.Fail()\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"image/jpeg\")\n\t\tfmt.Fprintln(w, `there is some content`)\n\t}))\n\tdefer ts.Close()\n\n\tf := &httpFetcher.Fetcher{}\n\tdefer os.Remove(\"valid\")\n\terr := f.Fetch(ts.URL+path, \"valid\")\n\n\tOk(t, err)\n}\n\nfunc TestUniqueFetcherOnEmptyFiles(t *testing.T) ", "output": "{\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"image/jpeg\")\n\t\tfmt.Fprintf(w, ``)\n\t}))\n\tdefer ts.Close()\n\n\tf := &httpFetcher.Fetcher{}\n\n\tdefer os.Remove(\"blank.jpg\")\n\terr := f.Fetch(ts.URL, \"blank.jpg\")\n\n\tEquals(t, \"File is empty\", fmt.Sprintf(\"%s\", err))\n}"} {"input": "package queue\n\nimport \"context\"\n\n\ntype Client struct {\n\tContent []byte\n\terr error\n}\n\n\nfunc (c *Client) Push(ctx context.Context, content []byte) error {\n\tif c.err != nil {\n\t\treturn c.err\n\t}\n\tc.Content = content\n\treturn nil\n}\n\n\n\n\n\nfunc ClientError(err error) func(*Client) {\n\treturn func(c *Client) {\n\t\tc.err = err\n\t}\n}\n\nfunc NewClient(options ...func(*Client)) *Client ", "output": "{\n\tc := &Client{}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\treturn c\n}"} {"input": "package ast\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/gobuffalo/plush/token\"\n)\n\ntype InfixExpression struct {\n\tToken token.Token\n\tLeft Expression\n\tOperator string\n\tRight Expression\n}\n\nfunc (oe *InfixExpression) expressionNode() {\n}\n\n\n\nfunc (oe *InfixExpression) String() string {\n\tvar out bytes.Buffer\n\n\tout.WriteString(\"(\")\n\tif oe.Left != nil {\n\t\tout.WriteString(oe.Left.String())\n\t}\n\tout.WriteString(\" \" + oe.Operator + \" \")\n\tout.WriteString(oe.Right.String())\n\tout.WriteString(\")\")\n\n\treturn out.String()\n}\n\nfunc (oe *InfixExpression) TokenLiteral() string ", "output": "{\n\treturn oe.Token.Literal\n}"} {"input": "package EGESPLOIT\n\n\nimport \"net/http\"\n\n\n\n\nfunc Dos(Target string) ", "output": "{\n\n var Count int = 0;\n\tvar ReqCount int = 1000;\n\n \tfor {\n \tCount++\n \tResponse, err := http.Get(Target);\n \tif err != nil {\n \t\tbreak;\n \t}\n \tResponse.Body.Close();\n \tif Count < ReqCount {\n \t\tgo Dos(Target)\n \t}else{\n \t\tbreak;\n \t} \n \t}\n}"} {"input": "package validator\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\nfunc IsNull(str string) bool {\n\treturn len(str) == 0\n}\n\nfunc IsWord(str string, params ...int) bool {\n\tif IsNull(str) {\n\t\treturn false\n\t}\n\treturn rxWord.MatchString(str)\n}\n\nfunc IsTime(str string, format string) bool {\n\t_, err := time.Parse(format, str)\n\treturn err == nil\n}\n\n\n\nfunc IsEmpty(str string) bool {\n\treturn len(strings.TrimSpace(str)) == 0\n}\n\nfunc IsRequestURI(rawurl string) bool {\n\t_, err := url.ParseRequestURI(rawurl)\n\treturn err == nil\n}\n\nfunc IsURI(str string) bool {\n\trelation := false\n\tfor idx, val := range str {\n\t\tif val == '.' {\n\t\t\trelation = true\n\t\t\tcontinue\n\t\t}\n\t\tif val == '/' || val == '\\\\' {\n\t\t\tif idx < len(str)-1 {\n\t\t\t\tif str[idx+1] == '.' {\n\t\t\t\t\trelation = true\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif relation && (val != '/' && val != '\\\\') {\n\t\t\treturn false\n\t\t}\n\t\treturn IsRequestURI(str[idx:])\n\t}\n\treturn false\n}\n\nfunc IsMobilePhone(str string) bool {\n\tif IsEmpty(str) {\n\t\treturn false\n\t}\n\treturn rxMobolePhone.MatchString(str)\n}\n\nfunc IsDate(str string, format ...string) bool ", "output": "{\n\n\tif len(format) == 0 {\n\n\t\tif len(strings.Split(str, \"/\")) > 1 {\n\t\t\treturn IsTime(str, \"2006/01/02\")\n\t\t}\n\n\t\tif len(strings.Split(str, \"-\")) > 1 {\n\t\t\treturn IsTime(str, \"2006-01-02\")\n\t\t}\n\n\t\treturn false\n\t}\n\n\treturn IsTime(str, format[0])\n}"} {"input": "package wire\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\n\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc (w *fixedWriter) Bytes() []byte ", "output": "{\n\treturn w.b\n}"} {"input": "package wraps\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-on/wrap\"\n)\n\n\n\ntype Catcher interface {\n\tCatch(recovered interface{}, w http.ResponseWriter, r *http.Request)\n}\n\n\ntype CatchFunc func(recovered interface{}, w http.ResponseWriter, r *http.Request)\n\n\nfunc (c CatchFunc) Catch(recovered interface{}, w http.ResponseWriter, r *http.Request) {\n\tc(recovered, w, r)\n}\n\n\n\n\nfunc (c CatchFunc) ServeHTTPNext(next http.Handler, wr http.ResponseWriter, req *http.Request) {\n\tchecked := wrap.NewPeek(wr, func(ck *wrap.Peek) bool {\n\t\tck.FlushHeaders()\n\t\tck.FlushCode()\n\t\treturn true\n\t})\n\n\tdefer func() {\n\t\tif p := recover(); p != nil {\n\t\t\tc(p, wr, req)\n\t\t} else {\n\t\t\tchecked.FlushMissing()\n\t\t}\n\t}()\n\n\tnext.ServeHTTP(checked, req)\n}\n\n\n\n\n\nfunc Catch(c Catcher) wrap.Wrapper {\n\treturn CatchFunc(c.Catch)\n}\n\nfunc (c CatchFunc) Wrap(next http.Handler) http.Handler ", "output": "{\n\treturn wrap.NextHandler(c).Wrap(next)\n}"} {"input": "package ks\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nfunc ReadBytesFromFile(filename string) ([]byte, error) {\n\tfin, err := os.Open(filename)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ioutil.ReadAll(fin)\n}\n\n\n\nfunc ListFiles(folder string) []string {\n\n\tvar res []string\n\n\tfilepath.Walk(fmt.Sprintf(folder),\n\t\tfunc(path string, info os.FileInfo, err error) error {\n\n\t\t\tif info != nil && !info.IsDir() {\n\t\t\t\tres = append(res, info.Name())\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\treturn res\n}\n\nfunc FileExists(filename string) bool {\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc ReadLines(r io.Reader) []string ", "output": "{\n\n\tbr := bufio.NewReader(r)\n\tvar res []string\n\n\tfor {\n\t\ts, _, err := br.ReadLine()\n\n\t\tif err != nil {\n\t\t\treturn res\n\t\t}\n\n\t\tres = append(res, string(s))\n\n\t}\n\n}"} {"input": "package listener\n\nimport (\n\t\"fmt\"\n)\n\nconst (\n\tDefaultGrpcPort = 18847\n\tDefaultHttpHealthCheckPort = 8080\n)\n\ntype Config struct {\n\tDebug bool\n\tGrpcPort int\n\tInsecureGrpcPort int\n\tHealthPort int\n\tTlsCertFile string\n\tTlsKeyFile string\n\tClientID string\n\tClientSecret string\n\tAuthDiscovery string\n\tRedisAddr string\n\tRedisPassword string\n\tRedisSentinel bool\n\tRedisMasterName string\n\tRedisDB int\n\tPubSubURL string\n\tInstanceName string\n\tNatsClusterID string\n}\n\n\nfunc (c *Config) GetHealthPortString() string {\n\treturn fmt.Sprintf(\":%d\", c.HealthPort)\n}\nfunc NewConfig() *Config {\n\treturn &Config{\n\t\tGrpcPort: DefaultGrpcPort,\n\t\tHealthPort: DefaultHttpHealthCheckPort,\n\t\tRedisAddr: \"127.0.0.1:6379\",\n\t\tRedisPassword: \"\",\n\t\tRedisDB: 0,\n\t\tInsecureGrpcPort: 0,\n\t\tRedisMasterName: \"mymaster\",\n\t\tNatsClusterID: \"otsimo\",\n\t\tInstanceName: \"listener\",\n\t}\n}\n\nfunc (c *Config) GetGrpcPortString() string ", "output": "{\n\treturn fmt.Sprintf(\":%d\", c.GrpcPort)\n}"} {"input": "package render\n\n\ntype Data map[string]interface{}\n\n\n\n\n\nfunc (d *Data) Set(key string, data interface{}) {\n\tif *d == nil {\n\t\tdata := Data(map[string]interface{}{})\n\t\t*d = data\n\t}\n\t(*d)[key] = data\n}\n\n\nfunc (d *Data) Del(key string) {\n\tif *d == nil {\n\t\treturn\n\t}\n\tdelete(*d, key)\n}\n\n\nfunc (d *Data) Get(key string) interface{} {\n\tif *d == nil {\n\t\treturn nil\n\t}\n\tdata, ok := (*d)[key]\n\tif ok == false {\n\t\treturn nil\n\t}\n\treturn data\n}\n\n\nfunc (d *Data) Merge(data *Data) {\n\tif *d == nil {\n\t\tdata := Data(map[string]interface{}{})\n\t\t*d = data\n\t}\n\tif data == nil || *data == nil {\n\t\treturn\n\t}\n\tfor k, v := range *data {\n\t\td.Set(k, v)\n\t}\n}\n\nfunc NewData() *Data ", "output": "{\n\treturn &Data{}\n}"} {"input": "package distribute\n\nimport (\n \"net/rpc\"\n \"net/http\"\n \"fmt\"\n)\n\ntype Worker struct {\n addr string\n addUrlChannel chan bool\n}\n\nfunc initWorker(addr string) *Worker{\n w := &Worker{}\n w.addr = addr\n w.addUrlChannel = make(chan bool)\n return w\n}\n\nfunc RunWorker(mAddr, wAddr string) {\n fmt.Println(\"=======RunWorker Begin=======\")\n w := initWorker(wAddr)\n \n register(mAddr, w.addr)\n fmt.Println(\"=======RunWorker End=======\")\n \n \n \n \n \n \n \n}\n\nfunc register(mAddr, wAddr string) {\n args := &RegisterArgs{}\n args.Worker = wAddr\n var reply RegisterReply\n call(mAddr, \"Master.Register\", args, &reply)\n}\n\n\n\nfunc startRpcWorker(w *Worker) {\n \n rpc.Register(w)\n rpc.HandleHTTP()\n err := http.ListenAndServe(w.addr, nil)\n fmt.Println(\"RegistrationServer: accept error\", err)\n \n \n \n \n \n \n}\n\nfunc (w *Worker) Dojob(args *DojobArgs, res *DojobReply) error ", "output": "{\n fmt.Println(\"DoJob: JobType \", args.JobType)\n switch args.JobType {\n case \"Crawl\":\n \n \n \n }\n return nil\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nfunc NashPath() (string, error) {\n\tnashpath := os.Getenv(\"NASHPATH\")\n\tif nashpath != \"\" {\n\t\treturn nashpath, nil\n\t}\n\th, err := home()\n\treturn filepath.Join(h, \"nash\"), err\n}\n\nfunc NashRoot() (string, error) {\n\tnashroot, ok := os.LookupEnv(\"NASHROOT\")\n\tif ok {\n\t\treturn nashroot, nil\n\t}\n\n\th, err := home()\n\treturn filepath.Join(h, \"nashroot\"), err\n}\n\n\n\nfunc home() (string, error) ", "output": "{\n\thomedir, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif homedir == \"\" {\n\t\treturn \"\", errors.New(\"invalid empty home dir\")\n\t}\n\treturn homedir, nil\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/converter\"\n\t\"strings\"\n)\n\n\ntype CreateScalingTagsRequestBody struct {\n\tTags *[]TagsSingleValue `json:\"tags,omitempty\"`\n\tAction *CreateScalingTagsRequestBodyAction `json:\"action,omitempty\"`\n}\n\nfunc (o CreateScalingTagsRequestBody) String() string {\n\tdata, _ := json.Marshal(o)\n\treturn strings.Join([]string{\"CreateScalingTagsRequestBody\", string(data)}, \" \")\n}\n\ntype CreateScalingTagsRequestBodyAction struct {\n\tvalue string\n}\n\ntype CreateScalingTagsRequestBodyActionEnum struct {\n\tCREATE CreateScalingTagsRequestBodyAction\n}\n\nfunc GetCreateScalingTagsRequestBodyActionEnum() CreateScalingTagsRequestBodyActionEnum {\n\treturn CreateScalingTagsRequestBodyActionEnum{\n\t\tCREATE: CreateScalingTagsRequestBodyAction{\n\t\t\tvalue: \"create\",\n\t\t},\n\t}\n}\n\nfunc (c CreateScalingTagsRequestBodyAction) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(c.value)\n}\n\n\n\nfunc (c *CreateScalingTagsRequestBodyAction) UnmarshalJSON(b []byte) error ", "output": "{\n\tmyConverter := converter.StringConverterFactory(\"string\")\n\tif myConverter != nil {\n\t\tval, err := myConverter.CovertStringToInterface(strings.Trim(string(b[:]), \"\\\"\"))\n\t\tif err == nil {\n\t\t\tc.value = val.(string)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t} else {\n\t\treturn errors.New(\"convert enum data to string error\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\t\"fmt\"\n)\n\n\n\nfunc TestSecond(t *testing.T) {\n\tresult := solveSecond([]int{\n\t\t0,\n\t\t3,\n\t\t0,\n\t\t1,\n\t\t-3,\n\t})\n\n\tcheckResult(t, result, 10)\n}\n\nfunc checkResult(t *testing.T, actualResult int, requiredResult int) {\n\tt.Helper()\n\n\tif actualResult != requiredResult {\n\t\tt.Error(fmt.Printf(\"steps count must be %+v, but: %+v\", requiredResult, actualResult))\n\t}\n}\n\nfunc TestFirst(t *testing.T) ", "output": "{\n\tresult := solveFirst([]int{\n\t\t0,\n\t\t3,\n\t\t0,\n\t\t1,\n\t\t-3,\n\t})\n\n\tcheckResult(t, result, 5)\n}"} {"input": "package kvm2\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\n\t\"github.com/docker/machine/libmachine/drivers\"\n\tcfg \"k8s.io/minikube/pkg/minikube/config\"\n\t\"k8s.io/minikube/pkg/minikube/constants\"\n\t\"k8s.io/minikube/pkg/minikube/registry\"\n)\n\nfunc init() {\n\tregistry.Register(registry.DriverDef{\n\t\tName: \"kvm2\",\n\t\tBuiltin: false,\n\t\tConfigCreator: createKVM2Host,\n\t})\n}\n\n\n\ntype kvmDriver struct {\n\t*drivers.BaseDriver\n\n\tMemory int\n\tDiskSize int\n\tCPU int\n\tNetwork string\n\tPrivateNetwork string\n\tISO string\n\tBoot2DockerURL string\n\tDiskPath string\n\tGPU bool\n}\n\n\n\nfunc createKVM2Host(config cfg.MachineConfig) interface{} ", "output": "{\n\treturn &kvmDriver{\n\t\tBaseDriver: &drivers.BaseDriver{\n\t\t\tMachineName: cfg.GetMachineName(),\n\t\t\tStorePath: constants.GetMinipath(),\n\t\t\tSSHUser: \"docker\",\n\t\t},\n\t\tMemory: config.Memory,\n\t\tCPU: config.CPUs,\n\t\tNetwork: config.KvmNetwork,\n\t\tPrivateNetwork: \"minikube-net\",\n\t\tBoot2DockerURL: config.Downloader.GetISOFileURI(config.MinikubeISO),\n\t\tDiskSize: config.DiskSize,\n\t\tDiskPath: filepath.Join(constants.GetMinipath(), \"machines\", cfg.GetMachineName(), fmt.Sprintf(\"%s.rawdisk\", cfg.GetMachineName())),\n\t\tISO: filepath.Join(constants.GetMinipath(), \"machines\", cfg.GetMachineName(), \"boot2docker.iso\"),\n\t\tGPU: config.GPU,\n\t}\n}"} {"input": "package loggo\n\nvar (\n\tdefaultContext = newDefaultContxt()\n)\n\nfunc newDefaultContxt() *Context {\n\tctx := NewContext(WARNING)\n\tctx.AddWriter(DefaultWriterName, defaultWriter())\n\treturn ctx\n}\n\n\nfunc DefaultContext() *Context {\n\treturn defaultContext\n}\n\n\n\n\n\nfunc LoggerInfo() string {\n\treturn defaultContext.Config().String()\n}\n\n\n\n\n\n\n\n\n\nfunc ResetLogging() {\n\tdefaultContext.ResetLoggerLevels()\n\tdefaultContext.ResetWriters()\n}\n\n\nfunc ResetWriters() {\n\tdefaultContext.ResetWriters()\n}\n\n\n\n\nfunc ReplaceDefaultWriter(writer Writer) (Writer, error) {\n\treturn defaultContext.ReplaceWriter(DefaultWriterName, writer)\n}\n\n\n\n\nfunc RegisterWriter(name string, writer Writer) error {\n\treturn defaultContext.AddWriter(name, writer)\n}\n\n\n\nfunc RemoveWriter(name string) (Writer, error) {\n\treturn defaultContext.RemoveWriter(name)\n}\n\n\n\n\n\n\n\n\n\n\nfunc ConfigureLoggers(specification string) error {\n\tconfig, err := ParseConfigString(specification)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefaultContext.ApplyConfig(config)\n\treturn nil\n}\n\nfunc GetLogger(name string, size ...int) Logger ", "output": "{\n\treturn defaultContext.GetLogger(name, size...)\n}"} {"input": "package debugtools\n\nimport (\n\t\"github.com/oakmound/oak/v3/render\"\n\t\"golang.org/x/sync/syncmap\"\n)\n\nvar (\n\tdebugMap syncmap.Map\n)\n\n\n\nfunc SetDebugRenderable(rName string, r render.Renderable) {\n\tdebugMap.Store(rName, r)\n}\n\n\n\nfunc GetDebugRenderable(rName string) (render.Renderable, bool) {\n\tr, ok := debugMap.Load(rName)\n\tif r == nil {\n\t\treturn nil, false\n\t}\n\treturn r.(render.Renderable), ok\n}\n\n\n\n\n\nfunc EnumerateDebugRenderableKeys() []string ", "output": "{\n\tkeys := []string{}\n\tdebugMap.Range(func(k, v interface{}) bool {\n\t\tkey, ok := k.(string)\n\t\tif ok {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t\treturn true\n\t})\n\treturn keys\n}"} {"input": "package target\n\nimport (\n\t\"os\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Glob(dst string, globs ...string) (bool, error) {\n\tstat, err := os.Stat(os.ExpandEnv(dst))\n\tif os.IsNotExist(err) {\n\t\treturn true, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn GlobNewer(stat.ModTime(), globs...)\n}\n\n\n\n\n\n\n\nfunc Dir(dst string, sources ...string) (bool, error) {\n\tdst = os.ExpandEnv(dst)\n\tstat, err := os.Stat(dst)\n\tif os.IsNotExist(err) {\n\t\treturn true, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdestTime := stat.ModTime()\n\tif stat.IsDir() {\n\t\tdestTime, err = NewestModTime(dst)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\treturn DirNewer(destTime, sources...)\n}\n\nfunc Path(dst string, sources ...string) (bool, error) ", "output": "{\n\tstat, err := os.Stat(os.ExpandEnv(dst))\n\tif os.IsNotExist(err) {\n\t\treturn true, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn PathNewer(stat.ModTime(), sources...)\n}"} {"input": "package main\n\nvar counter uint\nvar shift uint\n\n\n\nfunc Send(a, b chan uint) int {\n\tvar i int;\n\nLOOP:\n\tfor {\n\t\tselect {\n\t\tcase a <- GetValue():\n\t\t\ti++;\n\t\t\ta = nil;\n\t\tcase b <- GetValue():\n\t\t\ti++;\n\t\t\tb = nil;\n\t\tdefault:\n\t\t\tbreak LOOP;\n\t\t}\n\t\tshift++;\n\t}\n\treturn i;\n}\n\nfunc main() {\n\ta := make(chan uint, 1);\n\tb := make(chan uint, 1);\n\tif v := Send(a, b); v != 2 {\n\t\tpanicln(\"Send returned\", v, \"!= 2\");\n\t}\n\tif av, bv := <- a, <- b; av | bv != 3 {\n\t\tpanicln(\"bad values\", av, bv);\n\t}\n\tif v := Send(a, nil); v != 1 {\n\t\tpanicln(\"Send returned\", v, \"!= 1\");\n\t}\n\tif counter != 10 {\n\t\tpanicln(\"counter is\", counter, \"!= 10\");\n\t}\n}\n\nfunc GetValue() uint ", "output": "{\n\tcounter++;\n\treturn 1 << shift\n}"} {"input": "package master\n\nimport ()\n\n\n\ntype frame struct {\n\tjob *job\n\tslaveName string\n\tframe int\n\tdata []byte\n\tprogress byte\n\tcompleted bool\n}\n\n\n\nfunc NewFrame(job *job, fr int) *frame {\n\treturn &frame{\n\t\tjob: job,\n\t\tslaveName: \"\",\n\t\tframe: fr,\n\t\tdata: nil,\n\t\tprogress: 0,\n\t\tcompleted: false,\n\t}\n}\n\n\n\nfunc (f *frame) Job() *job {\n\treturn f.job\n}\n\nfunc (f *frame) SlaveName() string {\n\treturn f.slaveName\n}\n\nfunc (f *frame) Frame() int {\n\treturn f.frame\n}\n\nfunc (f *frame) AlignedFrame() int {\n\treturn f.frame + f.Job().Start()\n}\n\nfunc (f *frame) Data() []byte {\n\treturn f.data\n}\n\nfunc (f *frame) Progress() byte {\n\treturn f.progress\n}\n\nfunc (f *frame) Completed() bool {\n\treturn f.completed\n}\n\n\n\n\n\nfunc (f *frame) SetSlaveName(slaveName string) {\n\tf.slaveName = slaveName\n}\n\nfunc (f *frame) SetData(data []byte) {\n\tf.data = data\n}\n\nfunc (f *frame) SetProgress(progress byte) {\n\tf.progress = progress\n}\n\nfunc (f *frame) SetCompleted(completed bool) {\n\tf.completed = completed\n\tif completed {\n\t\tf.SetProgress(100)\n\t}\n}\n\n\n\nfunc (f *frame) Reset() {\n\tf.SetSlaveName(\"\")\n\tf.SetData(nil)\n\tf.SetProgress(0)\n\tf.SetCompleted(false)\n}\n\nfunc (f *frame) File() []byte ", "output": "{\n\treturn f.Job().File()\n}"} {"input": "package trackerserver\n\nimport (\n\t\"time\"\n\n\t\"github.com/uber-go/tally\"\n\n\t\"github.com/uber/kraken/tracker/originstore\"\n\t\"github.com/uber/kraken/tracker/peerhandoutpolicy\"\n\t\"github.com/uber/kraken/tracker/peerstore\"\n)\n\n\n\n\nfunc Fixture() *Server ", "output": "{\n\tpolicy := peerhandoutpolicy.DefaultPriorityPolicyFixture()\n\tconfig := Config{\n\t\tAnnounceInterval: 250 * time.Millisecond,\n\t}\n\treturn New(\n\t\tconfig, tally.NoopScope, policy,\n\t\tpeerstore.NewTestStore(), originstore.NewNoopStore(), nil)\n}"} {"input": "package xml\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/xml\"\n\t\"github.com/graniticio/granitic/v2/ws\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestUnmarshalling(t *testing.T) {\n\n\tr := new(http.Request)\n\tsr := strings.NewReader(\"1\")\n\n\trc := ioutil.NopCloser(sr)\n\n\tr.Body = rc\n\n\tum := new(Unmarshaller)\n\n\twsr := new(ws.Request)\n\twsr.RequestBody = new(target)\n\n\tum.Unmarshall(context.Background(), r, wsr)\n\n\ttar := wsr.RequestBody.(*target)\n\n\tif tar.A != 1 {\n\t\tt.Fail()\n\t}\n\n}\n\ntype target struct {\n\tXMLName xml.Name `xml:\"content\"`\n\tA int64 `xml:\"a\"`\n}\n\ntype resWriter struct {\n\tsw bytes.Buffer\n}\n\nfunc (rw *resWriter) Header() http.Header {\n\treturn nil\n}\n\nfunc (rw *resWriter) Write(b []byte) (int, error) {\n\treturn rw.sw.Write(b)\n}\n\nfunc (rw *resWriter) WriteHeader(statusCode int) {\n\n}\n\nfunc TestMarshallAndWrite(t *testing.T) ", "output": "{\n\n\tmw := new(MarshalingWriter)\n\trw := new(resWriter)\n\n\tmw.MarshalAndWrite(target{A: 1}, rw)\n\n\tif rw.sw.String() != \"1\" {\n\t\tt.Fail()\n\t}\n\n}"} {"input": "package systray\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\nfunc nativeLoop() {\n\tC.nativeLoop()\n}\n\n\n\n\n\n\nfunc SetIcon(iconBytes []byte) {\n\tcstr := (*C.char)(unsafe.Pointer(&iconBytes[0]))\n\tC.setIcon(cstr, (C.int)(len(iconBytes)))\n}\n\n\nfunc SetTitle(title string) {\n\tC.setTitle(C.CString(title))\n}\n\n\n\nfunc SetTooltip(tooltip string) {\n\tC.setTooltip(C.CString(tooltip))\n}\n\nfunc addOrUpdateMenuItem(item *MenuItem) {\n\tvar disabled C.short = 0\n\tif item.disabled {\n\t\tdisabled = 1\n\t}\n\tvar checked C.short = 0\n\tif item.checked {\n\t\tchecked = 1\n\t}\n\tC.add_or_update_menu_item(\n\n\t\tC.int(item.id),\n\t\tC.CString(item.title),\n\t\tC.CString(item.tooltip),\n\t\tdisabled,\n\t\tchecked,\n\t)\n}\n\n\nfunc systray_ready() {\n\tsystrayReady()\n}\n\n\nfunc systray_menu_item_selected(cId C.int) {\n\tsystrayMenuItemSelected(int32(cId))\n}\n\nfunc quit() ", "output": "{\n\tC.quit()\n}"} {"input": "package relay\n\nimport \"go.uber.org/zap\"\n\n\ntype Option func(options *options) error\n\ntype options struct {\n\tbufferSize int\n\tlog *zap.Logger\n}\n\nfunc newOptions() *options {\n\treturn &options{\n\t\tbufferSize: 32 * 1024,\n\t\tlog: zap.NewNop(),\n\t}\n}\n\n\n\n\n\n\n\nfunc WithLogger(log *zap.Logger) Option ", "output": "{\n\treturn func(options *options) error {\n\t\toptions.log = log\n\t\treturn nil\n\t}\n}"} {"input": "package vterrors\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"golang.org/x/net/context\"\n\n\tvtrpcpb \"github.com/youtube/vitess/go/vt/proto/vtrpc\"\n)\n\n\n\nfunc TestCode(t *testing.T) {\n\ttestcases := []struct {\n\t\tin error\n\t\twant vtrpcpb.Code\n\t}{{\n\t\tin: nil,\n\t\twant: vtrpcpb.Code_OK,\n\t}, {\n\t\tin: errors.New(\"generic\"),\n\t\twant: vtrpcpb.Code_UNKNOWN,\n\t}, {\n\t\tin: New(vtrpcpb.Code_CANCELED, \"generic\"),\n\t\twant: vtrpcpb.Code_CANCELED,\n\t}, {\n\t\tin: context.Canceled,\n\t\twant: vtrpcpb.Code_CANCELED,\n\t}, {\n\t\tin: context.DeadlineExceeded,\n\t\twant: vtrpcpb.Code_DEADLINE_EXCEEDED,\n\t}}\n\tfor _, tcase := range testcases {\n\t\tif got := Code(tcase.in); got != tcase.want {\n\t\t\tt.Errorf(\"Code(%v): %v, want %v\", tcase.in, got, tcase.want)\n\t\t}\n\t}\n}\n\nfunc TestCreation(t *testing.T) ", "output": "{\n\ttestcases := []struct {\n\t\tin, want vtrpcpb.Code\n\t}{{\n\t\tin: vtrpcpb.Code_CANCELED,\n\t\twant: vtrpcpb.Code_CANCELED,\n\t}, {\n\t\tin: vtrpcpb.Code_UNKNOWN,\n\t\twant: vtrpcpb.Code_UNKNOWN,\n\t}}\n\tfor _, tcase := range testcases {\n\t\tif got := Code(New(tcase.in, \"\")); got != tcase.want {\n\t\t\tt.Errorf(\"Code(New(%v)): %v, want %v\", tcase.in, got, tcase.want)\n\t\t}\n\t\tif got := Code(Errorf(tcase.in, \"\")); got != tcase.want {\n\t\t\tt.Errorf(\"Code(Errorf(%v)): %v, want %v\", tcase.in, got, tcase.want)\n\t\t}\n\t}\n}"} {"input": "package db\n\nimport (\n\t\"database/sql\"\n\t_ \"github.com/go-sql-driver/mysql\" \n)\n\nfunc NewDB(drivername, driversourcename string) *DB {\n\treturn &DB{\n\t\tDriverName: drivername,\n\t\tDriverSourceName: driversourcename,\n\t}\n}\n\ntype DB struct {\n\tDriverName string\n\tDriverSourceName string\n\tDataBase *sql.DB\n}\n\n\nfunc (this *DB) Open() (err error) {\n\tthis.DataBase, err = sql.Open(this.DriverName, this.DriverSourceName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\nfunc (this *DB) Close() {\n\tthis.DataBase.Close()\n}\n\n\n\n\n\n\n\nfunc (this *DB) QueryData(sql string, args ...interface{}) *sql.Row {\n\treturn this.DataBase.QueryRow(sql, args...)\n\n}\n\nfunc (this *DB) InsertData(sql string, args ...interface{}) error ", "output": "{\n\tstmt, err := this.DataBase.Prepare(sql)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\t_, err = stmt.Exec(args...)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"github.com/Shopify/toxiproxy/stream\"\n\t\"github.com/Shopify/toxiproxy/toxics\"\n)\n\ntype HttpResponseToxic struct {\n\tHttpBody string `json:\"body\"`\n\tHttpStatusCode int `json:\"code\"`\n\tHttpStatusText string `json:\"status\"`\n}\n\nfunc (t *HttpResponseToxic) ModifyResponse(resp *http.Response) {\n\tif t.HttpBody != \"\" {\n\t\tresp.Body = ioutil.NopCloser(bytes.NewBufferString(t.HttpBody))\n\t\tresp.ContentLength = int64(len(t.HttpBody))\n\t}\n\tif t.HttpStatusCode > 0 {\n\t\tresp.StatusCode = t.HttpStatusCode\n\t}\n\tif t.HttpStatusText != \"\" {\n\t\tresp.Status = t.HttpStatusText\n\t}\n}\n\n\n\nfunc init() {\n\ttoxics.Register(\"response\", new(HttpResponseToxic))\n}\n\nfunc (t *HttpResponseToxic) Pipe(stub *toxics.ToxicStub) ", "output": "{\n\tbuffer := bytes.NewBuffer(make([]byte, 0, 32*1024))\n\twriter := stream.NewChanWriter(stub.Output)\n\treader := stream.NewChanReader(stub.Input)\n\treader.SetInterrupt(stub.Interrupt)\n\tfor {\n\t\ttee := io.TeeReader(reader, buffer)\n\t\tresp, err := http.ReadResponse(bufio.NewReader(tee), nil)\n\t\tif err == stream.ErrInterrupted {\n\t\t\tbuffer.WriteTo(writer)\n\t\t\treturn\n\t\t} else if err == io.EOF {\n\t\t\tstub.Close()\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tbuffer.WriteTo(writer)\n\t\t} else {\n\t\t\tt.ModifyResponse(resp)\n\t\t\tresp.Write(writer)\n\t\t}\n\t\tbuffer.Reset()\n\t}\n}"} {"input": "package iso20022\n\n\ntype RejectionReason24Choice struct {\n\n\tCode *RejectionReason31Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification30 `xml:\"Prtry\"`\n}\n\n\n\nfunc (r *RejectionReason24Choice) AddProprietary() *GenericIdentification30 {\n\tr.Proprietary = new(GenericIdentification30)\n\treturn r.Proprietary\n}\n\nfunc (r *RejectionReason24Choice) SetCode(value string) ", "output": "{\n\tr.Code = (*RejectionReason31Code)(&value)\n}"} {"input": "package module\n\nimport (\n\t\"encoding/gob\"\n\t\"fmt\"\n\t\"github.com/glennyonemitsu/reicon/system/activity\"\n\t\"net\"\n\t\"os\"\n)\n\ntype Module struct {\n\tName string\n\tActivities []*activity.Activity\n\tServerSocket *net.UnixConn\n\tSocketAddr *net.UnixAddr\n\tListener *net.UnixListener\n}\n\nfunc (m *Module) Run() {\n\tsocket_path := os.Getenv(\"REICON_SYSTEM_SOCKET\")\n\tm.SocketAddr = new(net.UnixAddr)\n\tm.SocketAddr.Name = \"unix\"\n\tm.SocketAddr.Net = socket_path\n\tm.Listener, _ = net.ListenUnix(\"unix\", m.SocketAddr)\n\tm.ListenSocket()\n\n}\n\nfunc (m *Module) ListenSocket() {\n\tfor {\n\t\tconn, err := m.Listener.AcceptUnix()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tgo m.handleUnixConnection(conn)\n\t}\n}\n\nfunc (m *Module) handleUnixConnection(conn *net.UnixConn) {\n\tvar msg string\n\tenc := gob.NewEncoder(conn)\n\tdec := gob.NewDecoder(conn)\n\tdec.Decode(&msg)\n\tenc.Encode(fmt.Sprintf(\"your message was: %s\", msg))\n}\n\nfunc (m *Module) Shutdown() {\n\tm.ServerSocket.Close()\n}\n\n\n\nfunc Create(name string) *Module {\n\tm := new(Module)\n\tm.Name = name\n\treturn m\n}\n\nfunc (m *Module) RegisterActivity(name string) *activity.Activity ", "output": "{\n\ta := new(activity.Activity)\n\ta.Name = name\n\tm.Activities = append(m.Activities, a)\n\treturn a\n}"} {"input": "package leet_25\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\ntype dequeue struct {\n\tbuff []*ListNode\n}\n\nfunc (q *dequeue) lpop() *ListNode {\n\tif 0 == len(q.buff) {\n\t\treturn nil\n\t}\n\tp := q.buff[0]\n\tq.buff = q.buff[1:]\n\treturn p\n}\n\nfunc (q *dequeue) rpop() *ListNode {\n\tif 0 == len(q.buff) {\n\t\treturn nil\n\t}\n\tlast := len(q.buff) - 1\n\tp := q.buff[last]\n\tq.buff = q.buff[:last]\n\treturn p\n}\n\nfunc (q *dequeue) rpush(p *ListNode) {\n\tq.buff = append(q.buff, p)\n}\n\nfunc (q *dequeue) clear() {\n\tq.buff = buff[:0]\n}\n\nvar buff []*ListNode\n\n\n\nfunc reverseKGroup(head *ListNode, k int) *ListNode ", "output": "{\n\tif head == nil {\n\t\treturn nil\n\t}\n\tif k <= 1 {\n\t\treturn head\n\t}\n\tbuff = make([]*ListNode, 0, k)\n\tqueue := &dequeue{buff: buff}\n\tcount := 0\n\tcur := head\n\tfor cur != nil {\n\t\tcount++\n\t\tqueue.rpush(cur)\n\t\tif count == k {\n\t\t\tcount = 0\n\t\t\tfor {\n\t\t\t\tl := queue.lpop()\n\t\t\t\tr := queue.rpop()\n\t\t\t\tif l == nil || r == nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tl.Val, r.Val = r.Val, l.Val\n\t\t\t}\n\t\t\tqueue.clear()\n\t\t}\n\t\tcur = cur.Next\n\t}\n\treturn head\n}"} {"input": "package exchange\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\ntype ValidPeriod struct {\n\tdate time.Time\n\texpires time.Time\n}\n\n\n\nfunc NewValidPeriod(date, expires time.Time) ValidPeriod {\n\treturn ValidPeriod{date, expires}\n}\n\n\n\nfunc NewValidPeriodWithLifetime(date time.Time, lifetime time.Duration) ValidPeriod {\n\treturn ValidPeriod{date, date.Add(lifetime)}\n}\n\n\nfunc (vp ValidPeriod) Date() time.Time {\n\treturn vp.date\n}\n\n\nfunc (vp ValidPeriod) Expires() time.Time {\n\treturn vp.expires\n}\n\n\nfunc (vp ValidPeriod) Lifetime() time.Duration {\n\treturn vp.expires.Sub(vp.date)\n}\n\n\n\n\nfunc (vp ValidPeriod) Contains(t time.Time) bool {\n\treturn !t.Before(vp.date) && !t.After(vp.expires)\n}\n\n\n\n\nfunc (vp ValidPeriod) String() string ", "output": "{\n\treturn fmt.Sprintf(\"[%s] to [%s]\", vp.date, vp.expires)\n}"} {"input": "package of13\n\nimport (\n\t\"github.com/superkkt/cherry/cherryd/openflow\"\n)\n\n\n\nfunc NewEchoReply(xid uint32) openflow.EchoReply {\n\treturn &openflow.BaseEcho{\n\t\tMessage: openflow.NewMessage(openflow.OF13_VERSION, OFPT_ECHO_REPLY, xid),\n\t}\n}\n\nfunc NewEchoRequest(xid uint32) openflow.EchoRequest ", "output": "{\n\treturn &openflow.BaseEcho{\n\t\tMessage: openflow.NewMessage(openflow.OF13_VERSION, OFPT_ECHO_REQUEST, xid),\n\t}\n}"} {"input": "package opentracing \n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/otel/bridge/opentracing/migration\"\n\t\"go.opentelemetry.io/otel/trace\"\n)\n\ntype WrapperTracerProvider struct {\n\twTracer *WrapperTracer\n}\n\nvar _ trace.TracerProvider = (*WrapperTracerProvider)(nil)\n\n\nfunc (p *WrapperTracerProvider) Tracer(_ string, _ ...trace.TracerOption) trace.Tracer {\n\treturn p.wTracer\n}\n\n\n\nfunc NewWrappedTracerProvider(bridge *BridgeTracer, tracer trace.Tracer) *WrapperTracerProvider {\n\treturn &WrapperTracerProvider{\n\t\twTracer: NewWrapperTracer(bridge, tracer),\n\t}\n}\n\n\n\n\n\n\n\n\n\ntype WrapperTracer struct {\n\tbridge *BridgeTracer\n\ttracer trace.Tracer\n}\n\nvar _ trace.Tracer = &WrapperTracer{}\nvar _ migration.DeferredContextSetupTracerExtension = &WrapperTracer{}\n\n\n\n\nfunc NewWrapperTracer(bridge *BridgeTracer, tracer trace.Tracer) *WrapperTracer {\n\treturn &WrapperTracer{\n\t\tbridge: bridge,\n\t\ttracer: tracer,\n\t}\n}\n\nfunc (t *WrapperTracer) otelTracer() trace.Tracer {\n\treturn t.tracer\n}\n\n\n\n\nfunc (t *WrapperTracer) Start(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) {\n\tctx, span := t.otelTracer().Start(ctx, name, opts...)\n\tif spanWithExtension, ok := span.(migration.OverrideTracerSpanExtension); ok {\n\t\tspanWithExtension.OverrideTracer(t)\n\t}\n\tif !migration.SkipContextSetup(ctx) {\n\t\tctx = t.bridge.ContextWithBridgeSpan(ctx, span)\n\t}\n\treturn ctx, span\n}\n\n\n\n\n\n\n\nfunc (t *WrapperTracer) DeferredContextSetupHook(ctx context.Context, span trace.Span) context.Context ", "output": "{\n\tif tracerWithExtension, ok := t.otelTracer().(migration.DeferredContextSetupTracerExtension); ok {\n\t\tctx = tracerWithExtension.DeferredContextSetupHook(ctx, span)\n\t}\n\tctx = trace.ContextWithSpan(ctx, span)\n\treturn ctx\n}"} {"input": "package digits\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\n\nfunc testServer() (*http.Client, *http.ServeMux, *httptest.Server) {\n\tmux := http.NewServeMux()\n\tserver := httptest.NewServer(mux)\n\ttransport := &RewriteTransport{&http.Transport{\n\t\tProxy: func(req *http.Request) (*url.URL, error) {\n\t\t\treturn url.Parse(server.URL)\n\t\t},\n\t}}\n\tclient := &http.Client{Transport: transport}\n\treturn client, mux, server\n}\n\n\n\ntype RewriteTransport struct {\n\tTransport http.RoundTripper\n}\n\n\n\nfunc (t *RewriteTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq.URL.Scheme = \"http\"\n\tif t.Transport == nil {\n\t\treturn http.DefaultTransport.RoundTrip(req)\n\t}\n\treturn t.Transport.RoundTrip(req)\n}\n\n\n\n\n\nfunc assertQuery(t *testing.T, expected map[string]string, req *http.Request) {\n\tqueryValues := req.URL.Query()\n\texpectedValues := url.Values{}\n\tfor key, value := range expected {\n\t\texpectedValues.Add(key, value)\n\t}\n\tassert.Equal(t, expectedValues, queryValues)\n}\n\nfunc assertMethod(t *testing.T, expectedMethod string, req *http.Request) ", "output": "{\n\tassert.Equal(t, expectedMethod, req.Method)\n}"} {"input": "package timer\n\nimport (\n\t\"time\"\n)\n\ntype typeAction int\n\nconst (\n\tCLOSE typeAction = iota\n\tRESET\n\tFORCE\n)\n\n\n\ntype Timer struct {\n\tinterval time.Duration\n\tmsg, resp chan typeAction\n}\n\n\n\n\nfunc NewTimer(interval time.Duration) *Timer {\n\treturn &Timer{\n\t\tinterval: interval,\n\t\tmsg: make(chan typeAction, 1),\n\t\tresp: make(chan typeAction, 1),\n\t}\n}\n\n\n\n\n\n\n\n\nfunc (self *Timer) SetInterval(ns time.Duration) {\n\tself.interval = ns\n\tself.msg <- RESET\n}\n\n\n\nfunc (self *Timer) Trigger() {\n\tself.msg <- FORCE\n}\n\n\nfunc (self *Timer) TriggerAfter(ns time.Duration) {\n\tgo func() {\n\t\t<-time.After(ns)\n\t\tself.Trigger()\n\t}()\n}\n\n\n\n\nfunc (self *Timer) Close() {\n\tself.msg <- CLOSE\n\t<-self.resp\n}\n\nfunc (self *Timer) Next() bool ", "output": "{\n\tfor {\n\t\tvar ch <-chan time.Time\n\t\tif self.interval <= 0 {\n\t\t\tch = nil\n\t\t} else {\n\t\t\tch = time.After(self.interval)\n\t\t}\n\t\tselect {\n\t\tcase action := <-self.msg:\n\t\t\tswitch action {\n\t\t\tcase CLOSE:\n\t\t\t\tself.resp <- CLOSE\n\t\t\t\treturn false\n\t\t\tcase FORCE:\n\t\t\t\treturn true\n\t\t\t}\n\t\tcase <-ch:\n\t\t\treturn true\n\t\t}\n\t}\n\tpanic(\"unreachable\")\n}"} {"input": "package httpapi\n\nimport (\n\t\"github.com/labstack/echo\"\n\t\"github.com/labstack/echo/engine/standard\"\n\t\"github.com/labstack/echo/middleware\"\n\t\"net/http\"\n)\n\nvar (\n\tReloadChan chan bool\n)\n\ntype HttpError struct {\n\tCode int `json:\"code\"`\n\tMessage string `json:\"message\"`\n}\n\nfunc RunApiServer(addr string, reload chan bool) {\n\tReloadChan = reload\n\n\te := echo.New()\n\te.Pre(middleware.AddTrailingSlash())\n\n\te.GET(\"/\", func(c echo.Context) error {\n\t\treturn c.JSON(http.StatusOK, map[string]string{\"name\": \"Gydro Api Gateway\", \"version\": \"0.1.0\"})\n\t})\n\n\tApiController(e)\n\tConsumerController(e)\n\n\te.Run(standard.New(addr))\n}\n\n\n\nfunc NewHttpError(c echo.Context, code int, msg string) (err error) ", "output": "{\n\thttperr := &HttpError{Code: code, Message: msg}\n\treturn c.JSON(code, httperr)\n}"} {"input": "package crypto\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\n\t. \"github.com/tendermint/go-common\"\n\t\"golang.org/x/crypto/openpgp/armor\"\n)\n\n\n\nfunc DecodeArmor(armorStr string) (blockType string, headers map[string]string, data []byte, err error) {\n\tbuf := bytes.NewBufferString(armorStr)\n\tblock, err := armor.Decode(buf)\n\tif err != nil {\n\t\treturn \"\", nil, nil, err\n\t}\n\tdata, err = ioutil.ReadAll(block.Body)\n\tif err != nil {\n\t\treturn \"\", nil, nil, err\n\t}\n\treturn block.Type, block.Header, data, nil\n}\n\nfunc EncodeArmor(blockType string, headers map[string]string, data []byte) string ", "output": "{\n\tbuf := new(bytes.Buffer)\n\tw, err := armor.Encode(buf, blockType, headers)\n\tif err != nil {\n\t\tPanicSanity(\"Error encoding ascii armor: \" + err.Error())\n\t}\n\t_, err = w.Write(data)\n\tif err != nil {\n\t\tPanicSanity(\"Error encoding ascii armor: \" + err.Error())\n\t}\n\terr = w.Close()\n\tif err != nil {\n\t\tPanicSanity(\"Error encoding ascii armor: \" + err.Error())\n\t}\n\treturn string(buf.Bytes())\n}"} {"input": "package docker\n\nimport \"github.com/noxiouz/stout/isolate\"\n\n\n\nfunc init() ", "output": "{\n\tisolate.RegisterBox(\"docker\", NewBox)\n}"} {"input": "package log\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n)\n\nvar (\n\tinternalLog *logMux\n\tdebugMode bool\n)\n\n\nfunc init() {\n\tinternalLog = NewMux()\n\tinternalLog.Add(NewSyslogSink())\n\tinternalLog.Add(NewColourisedTerminalSink())\n}\n\n\ntype Sink interface {\n\tInfo(message string)\n\tWarning(message string)\n\tError(message string)\n\tDebug(message string)\n}\n\n\n\nfunc Info(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Info(fileMessage, v...)\n}\n\nfunc Warning(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Warning(fileMessage, v...)\n}\n\n\n\nfunc Debug(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Debug(fileMessage, v...)\n}\n\n\nfunc DebugMode(status bool) {\n\tinternalLog.DebugMode(status)\n\tdebugMode = status\n}\n\nfunc Errorf(message string, v ...interface{}) ", "output": "{\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Error(fileMessage, v...)\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/engine\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdGetAttributes{\n\t\tname: \"attributes\",\n\t\trpcMethod: utils.APIerSv1GetAttributeProfile,\n\t\trpcParams: &utils.TenantID{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetAttributes struct {\n\tname string\n\trpcMethod string\n\trpcParams *utils.TenantID\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetAttributes) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdGetAttributes) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdGetAttributes) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &utils.TenantID{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetAttributes) PostprocessRpcParams() error {\n\treturn nil\n}\n\n\n\nfunc (self *CmdGetAttributes) RpcResult() interface{} ", "output": "{\n\tvar atr engine.AttributeProfile\n\treturn &atr\n}"} {"input": "package main\n\nimport (\n\t\"api/handlers\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"runtime\"\n\t\"time\"\n)\n\n\n\nfunc main() {\n\tfmt.Println(\"Server is start at \", time.Now().String(), \" , on port 8080\")\n\thttp.HandleFunc(\"/useage\", handlers.Useage)\n\thttp.HandleFunc(\"/v1/\", handlers.API_V1)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc init() ", "output": "{\n\truntime.GOMAXPROCS(runtime.NumCPU())\n}"} {"input": "package secret\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nconst targetTestVersion = 1\n\nvar tests = []struct {\n\tcode uint\n\th []string\n}{\n\t{1, []string{\"wink\"}},\n\t{2, []string{\"double blink\"}},\n\t{4, []string{\"close your eyes\"}},\n\t{8, []string{\"jump\"}},\n\t{3, []string{\"wink\", \"double blink\"}},\n\t{19, []string{\"double blink\", \"wink\"}},\n\t{31, []string{\"jump\", \"close your eyes\", \"double blink\", \"wink\"}},\n\t{0, nil},\n\t{32, nil},\n\t{33, []string{\"wink\"}},\n}\n\nfunc TestHandshake(t *testing.T) {\n\tif testVersion != targetTestVersion {\n\t\tt.Fatalf(\"Found testVersion = %v, want %v\", testVersion, targetTestVersion)\n\t}\n\tfor _, test := range tests {\n\t\th := Handshake(test.code)\n\t\tif len(h) == 0 && len(test.h) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif !reflect.DeepEqual(h, test.h) {\n\t\t\tt.Fatalf(\"Handshake(%d) = %q, want %q.\", test.code, h, test.h)\n\t\t}\n\t}\n}\n\n\n\nfunc BenchmarkHandshake(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tHandshake(31)\n\t}\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\ntype ResourceData struct {\n\n\tData *Resource `json:\"data\"`\n}\n\n\nfunc (m *ResourceData) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\nfunc (m *ResourceData) validateData(formats strfmt.Registry) error ", "output": "{\n\n\tif err := validate.Required(\"data\", \"body\", m.Data); err != nil {\n\t\treturn err\n\t}\n\n\tif m.Data != nil {\n\n\t\tif err := m.Data.Validate(formats); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package seccomp\n\nimport (\n\tseccomp_compiler \"github.com/snapcore/snapd/sandbox/seccomp\"\n)\n\n\n\n\n\nfunc MockTemplate(fakeTemplate []byte) (restore func()) {\n\torig := defaultTemplate\n\torigBarePrivDropSyscalls := barePrivDropSyscalls\n\tdefaultTemplate = fakeTemplate\n\tbarePrivDropSyscalls = \"\"\n\treturn func() {\n\t\tdefaultTemplate = orig\n\t\tbarePrivDropSyscalls = origBarePrivDropSyscalls\n\t}\n}\n\nfunc MockKernelFeatures(f func() []string) (resture func()) {\n\told := kernelFeatures\n\tkernelFeatures = f\n\treturn func() {\n\t\tkernelFeatures = old\n\t}\n}\n\nfunc MockRequiresSocketcall(f func(string) bool) (restore func()) {\n\told := requiresSocketcall\n\trequiresSocketcall = f\n\treturn func() {\n\t\trequiresSocketcall = old\n\t}\n}\n\nfunc MockDpkgKernelArchitecture(f func() string) (restore func()) {\n\told := dpkgKernelArchitecture\n\tdpkgKernelArchitecture = f\n\treturn func() {\n\t\tdpkgKernelArchitecture = old\n\t}\n}\n\n\n\nfunc MockReleaseInfoVersionId(s string) (restore func()) {\n\told := releaseInfoVersionId\n\treleaseInfoVersionId = s\n\treturn func() {\n\t\treleaseInfoVersionId = old\n\t}\n}\n\nfunc MockSeccompCompilerLookup(f func(string) (string, error)) (restore func()) {\n\told := seccompCompilerLookup\n\tseccompCompilerLookup = f\n\treturn func() {\n\t\tseccompCompilerLookup = old\n\t}\n}\n\nfunc (b *Backend) VersionInfo() seccomp_compiler.VersionInfo {\n\treturn b.versionInfo\n}\n\nvar (\n\tRequiresSocketcall = requiresSocketcall\n\n\tGlobalProfileLE = globalProfileLE\n\tGlobalProfileBE = globalProfileBE\n\tIsBigEndian = isBigEndian\n)\n\nfunc MockReleaseInfoId(s string) (restore func()) ", "output": "{\n\told := releaseInfoId\n\treleaseInfoId = s\n\treturn func() {\n\t\treleaseInfoId = old\n\t}\n}"} {"input": "package main\n\nimport (\n\tcontext2 \"context\"\n)\n\n\n\n\n\nfunc inject(contextContext context2.Context, arg struct{}) (context, error) ", "output": "{\n\tmainContext, err := provide(contextContext)\n\tif err != nil {\n\t\treturn context{}, err\n\t}\n\treturn mainContext, nil\n}"} {"input": "package armmanagedservices\n\nconst (\n\tmoduleName = \"armmanagedservices\"\n\tmoduleVersion = \"v0.2.1\"\n)\n\n\ntype MultiFactorAuthProvider string\n\nconst (\n\tMultiFactorAuthProviderAzure MultiFactorAuthProvider = \"Azure\"\n\tMultiFactorAuthProviderNone MultiFactorAuthProvider = \"None\"\n)\n\n\n\n\n\nfunc (c MultiFactorAuthProvider) ToPtr() *MultiFactorAuthProvider {\n\treturn &c\n}\n\n\ntype ProvisioningState string\n\nconst (\n\tProvisioningStateAccepted ProvisioningState = \"Accepted\"\n\tProvisioningStateCanceled ProvisioningState = \"Canceled\"\n\tProvisioningStateCreated ProvisioningState = \"Created\"\n\tProvisioningStateCreating ProvisioningState = \"Creating\"\n\tProvisioningStateDeleted ProvisioningState = \"Deleted\"\n\tProvisioningStateDeleting ProvisioningState = \"Deleting\"\n\tProvisioningStateFailed ProvisioningState = \"Failed\"\n\tProvisioningStateNotSpecified ProvisioningState = \"NotSpecified\"\n\tProvisioningStateReady ProvisioningState = \"Ready\"\n\tProvisioningStateRunning ProvisioningState = \"Running\"\n\tProvisioningStateSucceeded ProvisioningState = \"Succeeded\"\n\tProvisioningStateUpdating ProvisioningState = \"Updating\"\n)\n\n\nfunc PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateAccepted,\n\t\tProvisioningStateCanceled,\n\t\tProvisioningStateCreated,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleted,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateNotSpecified,\n\t\tProvisioningStateReady,\n\t\tProvisioningStateRunning,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateUpdating,\n\t}\n}\n\n\nfunc (c ProvisioningState) ToPtr() *ProvisioningState {\n\treturn &c\n}\n\nfunc PossibleMultiFactorAuthProviderValues() []MultiFactorAuthProvider ", "output": "{\n\treturn []MultiFactorAuthProvider{\n\t\tMultiFactorAuthProviderAzure,\n\t\tMultiFactorAuthProviderNone,\n\t}\n}"} {"input": "package vm\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc newStack() *stack {\n\treturn &stack{}\n}\n\ntype stack struct {\n\tdata []*big.Int\n\tptr int\n}\n\n\n\nfunc (st *stack) pop() (ret *big.Int) {\n\tst.ptr--\n\tret = st.data[st.ptr]\n\treturn\n}\n\nfunc (st *stack) len() int {\n\treturn st.ptr\n}\n\nfunc (st *stack) swap(n int) {\n\tst.data[st.len()-n], st.data[st.len()-1] = st.data[st.len()-1], st.data[st.len()-n]\n}\n\nfunc (st *stack) dup(n int) {\n\tst.push(st.data[st.len()-n])\n}\n\nfunc (st *stack) peek() *big.Int {\n\treturn st.data[st.len()-1]\n}\n\nfunc (st *stack) require(n int) error {\n\tif st.len() < n {\n\t\treturn fmt.Errorf(\"stack underflow (%d <=> %d)\", len(st.data), n)\n\t}\n\treturn nil\n}\n\nfunc (st *stack) Print() {\n\tfmt.Println(\"### stack ###\")\n\tif len(st.data) > 0 {\n\t\tfor i, val := range st.data {\n\t\t\tfmt.Printf(\"%-3d %v\\n\", i, val)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"-- empty --\")\n\t}\n\tfmt.Println(\"#############\")\n}\n\nfunc (st *stack) push(d *big.Int) ", "output": "{\n\tstackItem := new(big.Int).Set(d)\n\tif len(st.data) > st.ptr {\n\t\tst.data[st.ptr] = stackItem\n\t} else {\n\t\tst.data = append(st.data, stackItem)\n\t}\n\tst.ptr++\n}"} {"input": "package error\n\nimport (\n\t\"strconv\"\n)\n\n\n\ntype StructuralError string\n\nfunc (s StructuralError) String() string {\n\treturn \"OpenPGP data invalid: \" + string(s)\n}\n\n\n\ntype UnsupportedError string\n\nfunc (s UnsupportedError) String() string {\n\treturn \"OpenPGP feature unsupported: \" + string(s)\n}\n\n\n\ntype InvalidArgumentError string\n\n\n\n\n\ntype SignatureError string\n\nfunc (b SignatureError) String() string {\n\treturn \"OpenPGP signature invalid: \" + string(b)\n}\n\ntype keyIncorrect int\n\nfunc (ki keyIncorrect) String() string {\n\treturn \"the given key was incorrect\"\n}\n\nvar KeyIncorrectError = keyIncorrect(0)\n\ntype unknownIssuer int\n\nfunc (unknownIssuer) String() string {\n\treturn \"signature make by unknown entity\"\n}\n\nvar UnknownIssuerError = unknownIssuer(0)\n\ntype UnknownPacketTypeError uint8\n\nfunc (upte UnknownPacketTypeError) String() string {\n\treturn \"unknown OpenPGP packet type: \" + strconv.Itoa(int(upte))\n}\n\nfunc (i InvalidArgumentError) String() string ", "output": "{\n\treturn \"OpenPGP argument invalid: \" + string(i)\n}"} {"input": "package io_usage\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"github.com/gollector/gollector/logger\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\tgm \"github.com/gollector/gollector_metrics\"\n)\n\nvar ioUsage = &gm.IOUsage{}\n\n\n\n\n\nfunc Detect() []string {\n\tout, err := ioutil.ReadFile(gm.DISKSTATS_FILE)\n\tvar collector []string\n\n\tif err != nil {\n\t\tfmt.Println(\"during detection, got error:\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlines := strings.Split(string(out), \"\\n\")\n\tre, _ := regexp.Compile(\"[ \\t]+\")\n\n\tfor _, line := range lines {\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tparts := re.Split(line, -1)\n\t\tparts = parts[1:]\n\n\t\tdevice_type_parsed, err := strconv.ParseUint(parts[gm.LINE_ID], 10, 64)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"during detection, got error:\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tif device_type_parsed > 7 {\n\t\t\tcollector = append(collector, parts[gm.LINE_DEVICE])\n\t\t}\n\t}\n\n\treturn collector\n}\n\nfunc GetMetric(params interface{}, log *logger.Logger) interface{} ", "output": "{\n\tresults, err := ioUsage.Metric(params.(string))\n\n\tif err != nil {\n\t\tlog.Log(\"crit\", err.Error())\n\t\treturn nil\n\t}\n\n\treturn results\n}"} {"input": "package s3storage\n\nimport (\n\t\"testing\"\n\n\t\"github.com/AdRoll/goamz/aws\"\n\t\"github.com/AdRoll/goamz/s3\"\n\t\"github.com/AdRoll/goamz/s3/s3test\"\n\t\"github.com/facebookgo/ensure\"\n)\n\n\ntype MockS3 struct {\n\tauth aws.Auth\n\tregion aws.Region\n\tsrv *s3test.Server\n\tconfig *s3test.Config\n}\n\n\nfunc (s *MockS3) Start(t *testing.T) {\n\tsrv, err := s3test.NewServer(s.config)\n\tensure.Nil(t, err)\n\tensure.NotNil(t, srv)\n\n\ts.srv = srv\n\ts.region = aws.Region{\n\t\tName: \"faux-region-1\",\n\t\tS3Endpoint: srv.URL(),\n\t\tS3LocationConstraint: true, \n\t}\n}\n\n\nfunc (s *MockS3) Stop() {\n\ts.srv.Quit()\n}\n\n\n\n\n\nfunc NewStorageWithMockS3(s *MockS3) (*S3Storage, error) {\n\treturn NewS3Storage(s.region, s.auth, \"testbucket\", \"test\", s3.Private)\n}\n\nfunc NewMockS3(t *testing.T) *MockS3 ", "output": "{\n\tm := MockS3{}\n\tm.Start(t)\n\treturn &m\n}"} {"input": "package linebot\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n\t\"net/http\"\n)\n\n\ntype BasicResponse struct {\n}\n\ntype errorResponseDetail struct {\n\tMessage string `json:\"message\"`\n\tProperty string `json:\"property\"`\n}\n\n\ntype ErrorResponse struct {\n\tMessage string `json:\"message\"`\n\tDetails []errorResponseDetail `json:\"details\"`\n}\n\n\ntype UserProfileResponse struct {\n\tUserID string `json:\"userId\"`\n\tDisplayName string `json:\"displayName\"`\n\tPictureURL string `json:\"pictureUrl\"`\n\tStatusMessage string `json:\"statusMessage\"`\n}\n\n\ntype MessageContentResponse struct {\n\tContent io.ReadCloser\n\tContentLength int64\n\tContentType string\n}\n\n\n\nfunc decodeToBasicResponse(res *http.Response) (*BasicResponse, error) {\n\tif err := checkResponse(res); err != nil {\n\t\treturn nil, err\n\t}\n\tdecoder := json.NewDecoder(res.Body)\n\tresult := BasicResponse{}\n\tif err := decoder.Decode(&result); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}\n\nfunc decodeToUserProfileResponse(res *http.Response) (*UserProfileResponse, error) {\n\tif err := checkResponse(res); err != nil {\n\t\treturn nil, err\n\t}\n\tdecoder := json.NewDecoder(res.Body)\n\tresult := UserProfileResponse{}\n\tif err := decoder.Decode(&result); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}\n\nfunc decodeToMessageContentResponse(res *http.Response) (*MessageContentResponse, error) {\n\tif err := checkResponse(res); err != nil {\n\t\treturn nil, err\n\t}\n\tresult := MessageContentResponse{\n\t\tContent: res.Body,\n\t\tContentType: res.Header.Get(\"Content-Type\"),\n\t\tContentLength: res.ContentLength,\n\t}\n\treturn &result, nil\n}\n\nfunc checkResponse(res *http.Response) error ", "output": "{\n\tif res.StatusCode != http.StatusOK {\n\t\tdecoder := json.NewDecoder(res.Body)\n\t\tresult := ErrorResponse{}\n\t\tif err := decoder.Decode(&result); err != nil {\n\t\t\treturn &APIError{\n\t\t\t\tCode: res.StatusCode,\n\t\t\t}\n\t\t}\n\t\treturn &APIError{\n\t\t\tCode: res.StatusCode,\n\t\t\tResponse: &result,\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package data\n\nimport (\n \"github.com/twitchyliquid64/CNC/registry/syscomponents\"\n)\n\nvar trackerObj DatabaseComponent\n\ntype DatabaseComponent struct{\n err error\n}\n\nfunc (d *DatabaseComponent)Name() string{\n return \"Database\"\n}\nfunc (d *DatabaseComponent)IconStr() string{\n return \"list\"\n}\n\nfunc (d *DatabaseComponent)IsDisabled()bool{\n return false\n}\nfunc (d *DatabaseComponent)IsFault()bool{\n return d.err != nil\n}\nfunc (d *DatabaseComponent)Error()string{\n if d.err == nil{\n return \"\"\n }\n return d.err.Error()\n}\nfunc (d *DatabaseComponent)SetError(e error){\n d.err = e\n}\n\nfunc trackingSetup(){\n trackerObj = DatabaseComponent{}\n syscomponents.Register(&trackerObj)\n}\n\nfunc tracking_notifyFault(err error){\n syscomponents.SetError(trackerObj.Name(), err)\n}\n\nfunc (d *DatabaseComponent)IsNominal()bool", "output": "{\n return d.err == nil\n}"} {"input": "package badactor\n\nimport \"time\"\n\ntype jail struct {\n\trule *Rule\n\treleaseBy time.Time\n\tstart time.Time\n}\n\n\n\nfunc newJail(r *Rule, sen time.Duration) *jail ", "output": "{\n\treturn &jail{\n\t\trule: r,\n\t\treleaseBy: time.Now().Add(sen),\n\t\tstart: time.Now(),\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"os\"\n\n\t\"k8s.io/klog/v2\"\n)\n\n\n\nfunc MakeTempDirOrDie(prefix string, baseDir string) string ", "output": "{\n\tif baseDir == \"\" {\n\t\tbaseDir = \"/tmp\"\n\t}\n\ttempDir, err := os.MkdirTemp(baseDir, prefix)\n\tif err != nil {\n\t\tklog.Fatalf(\"Can't make a temp rootdir: %v\", err)\n\t}\n\treturn tempDir\n}"} {"input": "package chunkstore\n\nimport (\n\t\"errors\"\n\n\t. \"github.com/huin/chunkymonkey/types\"\n)\n\n\n\n\n\ntype MultiStore struct {\n\treadStores []IChunkStore\n\twriteStore IChunkStore\n}\n\nfunc NewMultiStore(readStores []IChunkStore, writeStore IChunkStore) *MultiStore {\n\ts := &MultiStore{\n\t\treadStores: readStores,\n\t\twriteStore: writeStore,\n\t}\n\n\treturn s\n}\n\nfunc (s *MultiStore) ReadChunk(chunkLoc ChunkXz) (reader IChunkReader, err error) {\n\tfor _, store := range s.readStores {\n\t\tresult := <-store.ReadChunk(chunkLoc)\n\n\t\tif result.Err == nil {\n\t\t\treturn result.Reader, result.Err\n\t\t} else {\n\t\t\tif _, ok := result.Err.(NoSuchChunkError); ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, result.Err\n\t\t}\n\t}\n\n\treturn nil, NoSuchChunkError(false)\n}\n\nfunc (s *MultiStore) SupportsWrite() bool {\n\treturn s.writeStore != nil && s.writeStore.SupportsWrite()\n}\n\n\n\nfunc (s *MultiStore) WriteChunk(writer IChunkWriter) error {\n\tif s.writeStore == nil {\n\t\treturn errors.New(\"writes not supported\")\n\t}\n\ts.writeStore.WriteChunk(writer)\n\treturn nil\n}\n\nfunc (s *MultiStore) Writer() IChunkWriter ", "output": "{\n\tif s.writeStore != nil {\n\t\treturn s.writeStore.Writer()\n\t}\n\treturn nil\n}"} {"input": "package contentutil\n\nimport (\n\t\"context\"\n\n\t\"github.com/containerd/containerd/content\"\n\t\"github.com/containerd/containerd/errdefs\"\n\t\"github.com/containerd/containerd/remotes\"\n\t\"github.com/pkg/errors\"\n)\n\nfunc FromPusher(p remotes.Pusher) content.Ingester {\n\treturn &pushingIngester{\n\t\tp: p,\n\t}\n}\n\ntype pushingIngester struct {\n\tp remotes.Pusher\n}\n\n\nfunc (i *pushingIngester) Writer(ctx context.Context, opts ...content.WriterOpt) (content.Writer, error) {\n\tvar wOpts content.WriterOpts\n\tfor _, opt := range opts {\n\t\tif err := opt(&wOpts); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif wOpts.Ref == \"\" {\n\t\treturn nil, errors.Wrap(errdefs.ErrInvalidArgument, \"ref must not be empty\")\n\t}\n\tcontentWriter, err := i.p.Push(ctx, wOpts.Desc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &writer{\n\t\tWriter: contentWriter,\n\t\tcontentWriterRef: wOpts.Ref,\n\t}, nil\n}\n\ntype writer struct {\n\tcontent.Writer \n\tcontentWriterRef string \n}\n\n\n\nfunc (w *writer) Status() (content.Status, error) ", "output": "{\n\tst, err := w.Writer.Status()\n\tif err != nil {\n\t\treturn st, err\n\t}\n\tif w.contentWriterRef != \"\" {\n\t\tst.Ref = w.contentWriterRef\n\t}\n\treturn st, nil\n}"} {"input": "package rz\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc BenchmarkMain(b *testing.B) {\n\tvar resource int = 0\n\tvar syncpoint = NewSyncPoint(func(arg1 int) (arg2 int) {\n\t\treturn resource + arg1\n\t})\n\tgo func() {\n\t\tfor {\n\t\t\tb.StartTimer()\n\t\t\tsyncpoint.Send(func(arg2 int) { arg2 = 0 }, 1000)\n\t\t\tb.StopTimer()\n\t\t}\n\t}()\n\tb.ResetTimer()\n\tfor resource < b.N {\n\t\tsyncpoint.Accept()\n\t\tresource++\n\t}\n}\n\nfunc BenchmarkMain_nofunc(b *testing.B) {\n\tvar resource int = 0\n\tvar syncpoint = NewSyncPoint(nil)\n\tgo func() {\n\t\tfor {\n\t\t\tb.StartTimer()\n\t\t\tsyncpoint.Send(nil)\n\t\t\tb.StopTimer()\n\t\t}\n\t}()\n\tb.ResetTimer()\n\tfor resource < b.N {\n\t\tsyncpoint.Accept()\n\t\tresource++\n\t}\n}\n\nfunc ExampleSyncPoint() ", "output": "{\n\tvar resource int = 0\n\tvar syncpoint = NewSyncPoint(func(arg1 int) (arg2 int) {\n\t\targ2 = resource + arg1\n\t\treturn\n\t})\n\tgo func() {\n\t\tfor {\n\t\t\tsyncpoint.Send(func(arg2 int) {\n\t\t\t\tfmt.Println(arg2)\n\t\t\t},\n\t\t\t\t 1000)\n\t\t}\n\t}()\n\tfor resource < 10 {\n\t\tsyncpoint.Accept()\n\t\tresource++\n\t\ttime.Sleep(10 * time.Microsecond)\n\t}\n\n}"} {"input": "package streaming\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteStreamPoolRequest struct {\n\n\tStreamPoolId *string `mandatory:\"true\" contributesTo:\"path\" name:\"streamPoolId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request DeleteStreamPoolRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request DeleteStreamPoolRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request DeleteStreamPoolRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteStreamPoolResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteStreamPoolResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteStreamPoolResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteStreamPoolRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package termios\n\nimport (\n\t\"fmt\"\n\t\"syscall\"\n\t\"unsafe\"\n)\n\nfunc ptsname(fd uintptr) (string, error) {\n\tvar n uintptr\n\terr := ioctl(fd, syscall.TIOCGPTN, uintptr(unsafe.Pointer(&n)))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"/dev/pts/%d\", n), nil\n}\n\nfunc grantpt(fd uintptr) error {\n\tvar n uintptr\n\treturn ioctl(fd, syscall.TIOCGPTN, uintptr(unsafe.Pointer(&n)))\n}\n\n\n\nfunc unlockpt(fd uintptr) error ", "output": "{\n\tvar n uintptr\n\treturn ioctl(fd, syscall.TIOCSPTLCK, uintptr(unsafe.Pointer(&n)))\n}"} {"input": "package parser\n\nimport \"bytes\"\n\n\ntype DropBehavior int\n\n\nconst (\n\tDropDefault DropBehavior = iota\n\tDropRestrict\n\tDropCascade\n)\n\nvar dropBehaviorName = [...]string{\n\tDropDefault: \"\",\n\tDropRestrict: \"RESTRICT\",\n\tDropCascade: \"CASCADE\",\n}\n\n\n\n\ntype DropDatabase struct {\n\tName Name\n\tIfExists bool\n}\n\n\nfunc (node *DropDatabase) Format(buf *bytes.Buffer, f FmtFlags) {\n\tbuf.WriteString(\"DROP DATABASE \")\n\tif node.IfExists {\n\t\tbuf.WriteString(\"IF EXISTS \")\n\t}\n\tFormatNode(buf, f, node.Name)\n}\n\n\ntype DropIndex struct {\n\tIndexList TableNameWithIndexList\n\tIfExists bool\n\tDropBehavior DropBehavior\n}\n\n\nfunc (node *DropIndex) Format(buf *bytes.Buffer, f FmtFlags) {\n\tbuf.WriteString(\"DROP INDEX \")\n\tif node.IfExists {\n\t\tbuf.WriteString(\"IF EXISTS \")\n\t}\n\tFormatNode(buf, f, node.IndexList)\n\tif node.DropBehavior != DropDefault {\n\t\tbuf.WriteByte(' ')\n\t\tbuf.WriteString(node.DropBehavior.String())\n\t}\n}\n\n\ntype DropTable struct {\n\tNames QualifiedNames\n\tIfExists bool\n\tDropBehavior DropBehavior\n}\n\n\nfunc (node *DropTable) Format(buf *bytes.Buffer, f FmtFlags) {\n\tbuf.WriteString(\"DROP TABLE \")\n\tif node.IfExists {\n\t\tbuf.WriteString(\"IF EXISTS \")\n\t}\n\tFormatNode(buf, f, node.Names)\n\tif node.DropBehavior != DropDefault {\n\t\tbuf.WriteByte(' ')\n\t\tbuf.WriteString(node.DropBehavior.String())\n\t}\n}\n\nfunc (d DropBehavior) String() string ", "output": "{\n\treturn dropBehaviorName[d]\n}"} {"input": "package daemon\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetMapNameOKCode int = 200\n\n\ntype GetMapNameOK struct {\n\n\tPayload *models.BPFMap `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetMapNameOK() *GetMapNameOK {\n\n\treturn &GetMapNameOK{}\n}\n\n\nfunc (o *GetMapNameOK) WithPayload(payload *models.BPFMap) *GetMapNameOK {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *GetMapNameOK) SetPayload(payload *models.BPFMap) {\n\to.Payload = payload\n}\n\n\nfunc (o *GetMapNameOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\n\nconst GetMapNameNotFoundCode int = 404\n\n\ntype GetMapNameNotFound struct {\n}\n\n\nfunc NewGetMapNameNotFound() *GetMapNameNotFound {\n\n\treturn &GetMapNameNotFound{}\n}\n\n\n\n\nfunc (o *GetMapNameNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}"} {"input": "package glfw2\n\nimport (\n\tgl \"github.com/tHinqa/outside-opengl\"\n\t\"testing\"\n)\n\nvar mode VidMode\n\nfunc TestInit(t *testing.T) {\n\tif Init() {\n\t\tGetDesktopMode(&mode)\n\t\tvar major, minor, rev int\n\t\tGetGLVersion(&major, &minor, &rev)\n\t\tt.Logf(\"GLFW Version: %v.%v.%v\", major, minor, rev)\n\t\tt.Logf(\"%+v\", mode)\n\t\tif OpenWindow(mode.Width/2, mode.Height/2,\n\t\t\tmode.RedBits, mode.GreenBits, mode.BlueBits,\n\t\t\t0, 0, 0, Window) {\n\t\t\tSetWindowTitle(\"Go GLFW 2\")\n\t\t\tSetWindowPos(mode.Width/2-mode.Width/4, mode.Height/2-mode.Height/4)\n\t\t\tgl.Clear(gl.ColorBufferBit)\n\t\t\tSwapBuffers()\n\t\t\tSleep(2.5) \n\t\t\tt.Logf(\"Elapsed (including 2.5s sleep): %fs\", GetTime())\n\t\t\tGetTime() \n\t\t\ts := GetTime()\n\t\t\tt.Logf(\"GetTime() call duration: ~%dns\", int((GetTime()-s)*1e9))\n\t\t} else {\n\t\t\tt.Fatal(\"OpenWindow: Failed to Open Window\")\n\t\t}\n\t\tTerminate()\n\t} else {\n\t\tt.Fatal(\"Init: Failed to initialize GLFW\")\n\t}\n}\n\n\n\n\nfunc TestMode(t *testing.T) ", "output": "{\n\tconst MAX_NUM_MODES = 400\n\tvar (\n\t\tdtmode VidMode\n\t\tmodes [MAX_NUM_MODES]VidMode\n\t)\n\n\tif !Init() {\n\t\tt.Fail()\n\t}\n\n\tGetDesktopMode(&dtmode)\n\tt.Logf(\"Desktop mode: %d x %d x %d\\n\",\n\t\tdtmode.Width, dtmode.Height, dtmode.RedBits+\n\t\t\tdtmode.GreenBits+dtmode.BlueBits)\n\tmodecount := GetVideoModes(&modes[0], MAX_NUM_MODES)\n\tt.Log(\"Available modes:\")\n\tfor i := 0; i < modecount; i++ {\n\t\tt.Logf(\"%3d: %d x %d x %d\\n\", i,\n\t\t\tmodes[i].Width, modes[i].Height, modes[i].RedBits+\n\t\t\t\tmodes[i].GreenBits+modes[i].BlueBits)\n\t}\n\tTerminate()\n}"} {"input": "package gospell\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\ntype Match struct {\n\tWord []rune\n\tDistance int\n\tWeight int\n}\n\ntype Matches []Match\n\nfunc (m1 Match) Equal(m2 Match) bool {\n\treturn string(m1.Word) == string(m2.Word) &&\n\t\tm1.Distance == m2.Distance && m1.Weight == m2.Weight\n}\n\nfunc (m Match) String() string {\n\treturn fmt.Sprintf(\"{%v %d %d}\", string(m.Word), m.Distance, m.Weight)\n}\n\nfunc (s Matches) Len() int { return len(s) }\n\n\n\nfunc (s Matches) Strings() []string {\n\tstrings := make([]string, len(s))\n\tsort.Sort(ByDistance{s})\n\tfor i, r := range s {\n\t\tstrings[i] = string(r.Word)\n\t}\n\n\treturn strings\n}\n\ntype ByDistance struct {\n\tMatches\n}\n\nfunc (s ByDistance) Less(i, j int) bool {\n\td1 := s.Matches[i].Distance\n\td2 := s.Matches[j].Distance\n\tif d1 == d2 {\n\t\treturn string(s.Matches[i].Word) < string(s.Matches[j].Word)\n\t}\n\treturn d1 < d2\n}\n\nfunc (m *Match) update(r rune, distance, weight int) Match {\n\tm2 := Match{}\n\tif r != 0 {\n\t\tm2.Word = []rune{r}\n\t\tm2.Word = append(m2.Word, m.Word...)\n\t} else {\n\t\tm2.Word = m.Word[:]\n\t}\n\tm2.Distance = m.Distance + distance\n\tm2.Weight = m.Weight + weight\n\treturn m2\n}\n\nfunc (s Matches) Swap(i, j int) ", "output": "{ s[i], s[j] = s[j], s[i] }"} {"input": "package iso20022\n\n\ntype PendingCancellationStatusReason6 struct {\n\n\tReasonCode *PendingCancellationReason4Choice `xml:\"RsnCd\"`\n\n\tAdditionalReasonInformation *RestrictedFINXMax210Text `xml:\"AddtlRsnInf,omitempty\"`\n}\n\n\n\nfunc (p *PendingCancellationStatusReason6) SetAdditionalReasonInformation(value string) {\n\tp.AdditionalReasonInformation = (*RestrictedFINXMax210Text)(&value)\n}\n\nfunc (p *PendingCancellationStatusReason6) AddReasonCode() *PendingCancellationReason4Choice ", "output": "{\n\tp.ReasonCode = new(PendingCancellationReason4Choice)\n\treturn p.ReasonCode\n}"} {"input": "package handlers\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/play-with-docker/play-with-docker/config\"\n\t\"github.com/play-with-docker/play-with-docker/services\"\n)\n\ntype NewSessionResponse struct {\n\tSessionId string `json:\"session_id\"`\n\tHostname string `json:\"hostname\"`\n}\n\n\n\nfunc NewSession(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\treq.ParseForm()\n\tif !services.IsHuman(req, rw) {\n\t\trw.WriteHeader(http.StatusForbidden)\n\t\treturn\n\t}\n\n\treqDur := req.Form.Get(\"session-duration\")\n\n\tduration := services.GetDuration(reqDur)\n\ts, err := services.NewSession(duration)\n\tif err != nil {\n\t\tlog.Println(err)\n\t} else {\n\n\t\thostname := fmt.Sprintf(\"%s.%s\", config.PWDCName, req.Host)\n\t\tif req.Header.Get(\"X-Requested-With\") == \"XMLHttpRequest\" {\n\t\t\tresp := NewSessionResponse{SessionId: s.Id, Hostname: hostname}\n\t\t\trw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tjson.NewEncoder(rw).Encode(resp)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(rw, req, fmt.Sprintf(\"http://%s/p/%s\", hostname, s.Id), http.StatusFound)\n\t}\n}"} {"input": "package swagger\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n)\n\n\n\n\n\nfunc NewSwaggerUI(swaggerPath string) http.Handler ", "output": "{\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.URL.Path == swaggerPath ||\n\t\t\t(r.URL.Path == swaggerPath+\"/\" && r.URL.Query().Get(\"url\") == \"\") {\n\t\t\thttp.Redirect(w, r, swaggerPath+\"/?url=swagger.json\", http.StatusFound)\n\t\t\treturn\n\t\t}\n\n\t\tif strings.Index(r.URL.Path, swaggerPath) == 0 {\n\t\t\thttp.StripPrefix(swaggerPath+\"/\", http.FileServer(assetFS())).ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t})\n}"} {"input": "package policy\n\nimport \"github.com/cilium/cilium/pkg/labels\"\n\n\n\n\nfunc JoinPath(a, b string) string ", "output": "{\n\treturn a + labels.PathDelimiter + b\n}"} {"input": "package fileutils\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"os\"\n)\n\n\n\nfunc fileToByteslice(filename string) []byte ", "output": "{\n\n\tfile, err := os.Open(filename)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfinfo, err := file.Stat()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsize_of_slice := finfo.Size()\n\n\tbyteSlice := make([]byte, size_of_slice)\n\n\t_, err = io.ReadFull(file, byteSlice)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn byteSlice\n\n}"} {"input": "package json\n\nimport \"fmt\"\n\ntype Serializer struct {\n\tdumper *Dumper\n\tparser *Parser\n}\n\n\n\nfunc (serializer *Serializer) Dump(m *map[interface{}]interface{}) string {\n\treturn serializer.dumper.Dump(m)\n}\n\nfunc (serializer *Serializer) Parse(s string) map[interface{}]interface{} {\n\treturn serializer.parser.Parse(s)\n}\n\nfunc (serializer *Serializer) String() string ", "output": "{\n\treturn fmt.Sprintf(\"\")\n}"} {"input": "package events\n\nimport (\n\t\"fmt\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/klog\"\n)\n\ntype LoggingEventRecorder struct {\n\tcomponent string\n}\n\n\nfunc NewLoggingEventRecorder(component string) Recorder {\n\treturn &LoggingEventRecorder{component: component}\n}\n\n\n\nfunc (r *LoggingEventRecorder) ForComponent(component string) Recorder {\n\tnewRecorder := *r\n\tnewRecorder.component = component\n\treturn &newRecorder\n}\n\nfunc (r *LoggingEventRecorder) WithComponentSuffix(suffix string) Recorder {\n\treturn r.ForComponent(fmt.Sprintf(\"%s-%s\", r.ComponentName(), suffix))\n}\n\nfunc (r *LoggingEventRecorder) Event(reason, message string) {\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeNormal, reason, message)\n\tklog.Info(event.String())\n}\n\nfunc (r *LoggingEventRecorder) Eventf(reason, messageFmt string, args ...interface{}) {\n\tr.Event(reason, fmt.Sprintf(messageFmt, args...))\n}\n\nfunc (r *LoggingEventRecorder) Warning(reason, message string) {\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeWarning, reason, message)\n\tklog.Warning(event.String())\n}\n\nfunc (r *LoggingEventRecorder) Warningf(reason, messageFmt string, args ...interface{}) {\n\tr.Warning(reason, fmt.Sprintf(messageFmt, args...))\n}\n\nfunc (r *LoggingEventRecorder) ComponentName() string ", "output": "{\n\treturn r.component\n}"} {"input": "package mgorm\n\nimport (\n\t\"labix.org/v2/mgo/bson\"\n)\n\ntype IEmbeddedModel interface {\n\tIErrorHandler\n\tIValidator\n\tIEvent\n}\n\ntype IModel interface {\n\tIEmbeddedModel\n\tIsNew() bool\n\tGetId() bson.ObjectId\n\tAfterFind()\n\tBeforeSave() error\n\tAfterSave()\n\tCollectionName() string\n}\n\ntype EmbeddedModel struct {\n\tErrorHandler `bson:\",inline\" json:\"-\"`\n\tEvent `bson:\",inline\" json:\"-\"`\n}\n\nfunc (self *EmbeddedModel) Validate() bool {\n\tself.ClearErrors()\n\n\terr := self.Emit(\"BeforeValidate\")\n\tif nil != err {\n\t\tself.AddError(err.Error())\n\t\treturn false\n\t}\n\n\treturn true\n}\n\ntype Model struct {\n\tEmbeddedModel `bson:\",inline\" json:\"-\"`\n\tId bson.ObjectId `bson:\"_id\" json:\"id\"`\n\tisOld bool\n\tcollectionName string\n}\n\nfunc (self *Model) AfterFind() {\n\tself.Emit(\"AfterFind\")\n\tself.isOld = true\n}\n\n\n\nfunc (self *Model) AfterSave() {\n\tself.Emit(\"AfterSave\")\n\tself.isOld = true\n}\n\nfunc (self *Model) GetId() bson.ObjectId {\n\treturn self.Id\n}\n\nfunc (self *Model) IsNew() bool {\n\treturn !self.isOld\n}\n\nfunc (self *Model) BeforeSave() error ", "output": "{\n\tif self.IsNew() {\n\t\tself.Id = bson.NewObjectId()\n\t}\n\n\treturn self.Emit(\"BeforeSave\")\n}"} {"input": "package linebot\n\nimport (\n\t\"context\"\n\n\t\"github.com/line/line-bot-sdk-go/linebot\"\n\t\"github.com/utahta/momoclo-channel/config\"\n\t\"google.golang.org/appengine/urlfetch\"\n)\n\ntype (\n\tClient interface {\n\t\tReplyText(context.Context, string, string) error\n\t\tReplyImage(context.Context, string, string, string) error\n\t}\n\n\tclient struct {\n\t}\n)\n\n\n\n\n\nfunc (c *client) ReplyText(ctx context.Context, replyToken, text string) error {\n\tbot, err := c.fromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttextMessage := linebot.NewTextMessage(text)\n\tif _, err := bot.ReplyMessage(replyToken, textMessage).Do(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\nfunc (c *client) ReplyImage(ctx context.Context, replyToken, originalContentURL, previewImageURL string) error {\n\tbot, err := c.fromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\timageMessage := linebot.NewImageMessage(originalContentURL, previewImageURL)\n\tif _, err := bot.ReplyMessage(replyToken, imageMessage).Do(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *client) fromContext(ctx context.Context) (*linebot.Client, error) {\n\treturn linebot.New(\n\t\tconfig.C().LineBot.ChannelSecret,\n\t\tconfig.C().LineBot.ChannelToken,\n\t\tlinebot.WithHTTPClient(urlfetch.Client(ctx)),\n\t)\n}\n\nfunc New() Client ", "output": "{\n\treturn &client{}\n}"} {"input": "package iso20022\n\n\ntype PartyIdentification45Choice struct {\n\n\tAnyBIC *AnyBICIdentifier `xml:\"AnyBIC\"`\n\n\tProprietaryIdentification *GenericIdentification19 `xml:\"PrtryId\"`\n\n\tNameAndAddress *NameAndAddress5 `xml:\"NmAndAdr\"`\n}\n\nfunc (p *PartyIdentification45Choice) SetAnyBIC(value string) {\n\tp.AnyBIC = (*AnyBICIdentifier)(&value)\n}\n\n\n\nfunc (p *PartyIdentification45Choice) AddNameAndAddress() *NameAndAddress5 {\n\tp.NameAndAddress = new(NameAndAddress5)\n\treturn p.NameAndAddress\n}\n\nfunc (p *PartyIdentification45Choice) AddProprietaryIdentification() *GenericIdentification19 ", "output": "{\n\tp.ProprietaryIdentification = new(GenericIdentification19)\n\treturn p.ProprietaryIdentification\n}"} {"input": "package backingstore\n\nimport (\n\t\"github.com/gostor/gotgt/pkg/api\"\n\t\"github.com/gostor/gotgt/pkg/scsi\"\n)\n\nfunc init() {\n\tscsi.RegisterBackingStore(\"null\", newNull)\n}\n\ntype NullBackingStore struct {\n\tscsi.BaseBackingStore\n}\n\nfunc newNull() (api.BackingStore, error) {\n\treturn &NullBackingStore{\n\t\tBaseBackingStore: scsi.BaseBackingStore{\n\t\t\tName: \"null\",\n\t\t\tDataSize: 0,\n\t\t\tOflagsSupported: 0,\n\t\t},\n\t}, nil\n}\n\nfunc (bs *NullBackingStore) Open(dev *api.SCSILu, path string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Close(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Init(dev *api.SCSILu, Opts string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Exit(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Size(dev *api.SCSILu) uint64 {\n\treturn 0\n}\n\nfunc (bs *NullBackingStore) Read(offset, tl int64) ([]byte, error) {\n\treturn nil, nil\n}\n\n\n\nfunc (bs *NullBackingStore) DataSync(offset, tl int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataAdvise(offset, length int64, advise uint32) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Unmap([]api.UnmapBlockDescriptor) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Write(wbuf []byte, offset int64) error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"time\"\n)\n\n\nvar TopicCache = make([]*Topic, 0, 16)\n\ntype Topic struct {\n\tId int `json:\"id\"`\n\tTitle string `json:\"title\"`\n\tContent string `json:\"content\"`\n\tCreatedAt time.Time `json:\"created_at\"`\n}\n\n\n\nfunc (t *Topic) Create() error {\n\tt.Id = len(TopicCache) + 1\n\tt.CreatedAt = time.Now()\n\tTopicCache = append(TopicCache, t)\n\treturn nil\n}\n\nfunc (t *Topic) Update() error {\n\tif err := checkIndex(t.Id); err != nil {\n\t\treturn err\n\t}\n\tTopicCache[t.Id-1] = t\n\treturn nil\n}\n\n\nfunc (t *Topic) Delete() error {\n\tif err := checkIndex(t.Id); err != nil {\n\t\treturn err\n\t}\n\tTopicCache[t.Id-1] = nil\n\treturn nil\n}\n\nfunc checkIndex(id int) error {\n\tif id > 0 && len(TopicCache) <= id-1 {\n\t\treturn errors.New(\"The topic is not exists!\")\n\t}\n\n\treturn nil\n}\n\nfunc FindTopic(id int) (*Topic, error) ", "output": "{\n\tif err := checkIndex(id); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn TopicCache[id-1], nil\n}"} {"input": "package gumble\n\nimport (\n\t\"github.com/unascribed/gumble/gumble/MumbleProto\"\n)\n\n\ntype RegisteredUser struct {\n\tUserID uint32\n\tName string\n\n\tchanged bool\n\tderegister bool\n}\n\n\nfunc (ru *RegisteredUser) SetName(name string) {\n\tru.Name = name\n\tru.changed = true\n}\n\n\nfunc (ru *RegisteredUser) Deregister() {\n\tru.deregister = true\n}\n\n\n\nfunc (ru *RegisteredUser) Register() {\n\tru.deregister = false\n}\n\n\nfunc (ru *RegisteredUser) ACLUser() *ACLUser {\n\treturn &ACLUser{\n\t\tUserID: ru.UserID,\n\t\tName: ru.Name,\n\t}\n}\n\n\n\n\n\ntype RegisteredUsers []*RegisteredUser\n\n\n\nfunc (pm RegisteredUsers) writeMessage(client *Client) error ", "output": "{\n\tpacket := MumbleProto.UserList{}\n\n\tfor _, user := range pm {\n\t\tif user.deregister || user.changed {\n\t\t\tuserListUser := &MumbleProto.UserList_User{\n\t\t\t\tUserId: &user.UserID,\n\t\t\t}\n\t\t\tif !user.deregister {\n\t\t\t\tuserListUser.Name = &user.Name\n\t\t\t}\n\t\t\tpacket.Users = append(packet.Users, userListUser)\n\t\t}\n\t}\n\n\tif len(packet.Users) <= 0 {\n\t\treturn nil\n\t}\n\tproto := protoMessage{&packet}\n\treturn proto.writeMessage(client)\n}"} {"input": "package term \n\nimport \"io\"\n\ntype Db []Term\n\nfunc NewDb(args []Term) Db {\n\treturn Db(args)\n}\n\nfunc (s Db) Format(w io.Writer, style Style) {\n\tisRoot := style.IsRoot\n\tstyle.IsRoot = false \n\n\tprevName := \"#\" \n\tfor _, t := range s {\n\t\tif isRoot {\n\t\t\tname := Name(t)\n\t\t\tif prevName != \"#\" && prevName != name {\n\t\t\t\tio.WriteString(w, \"\\n\")\n\t\t\t}\n\t\t\tprevName = name\n\t\t}\n\n\t\tstyle.WriteIndent(w)\n\t\tt.Format(w, style)\n\t}\n}\n\n\ntype Query struct {\n\tdb Db\n\tname string\n\tarity int\n}\n\n\n\n\n\n\n\n\nfunc (q *Query) Run() *Cursor {\n\treturn &Cursor{\n\t\tq: q,\n\t\ti: 0,\n\t}\n}\n\n\ntype Cursor struct {\n\tq *Query\n\ti int\n}\n\nfunc (c *Cursor) Next() (Term, bool) {\n\tfor ; c.i < len(c.q.db); c.i++ {\n\t\tcandidate := c.q.db[c.i]\n\t\tif Arity(candidate) == c.q.arity && Name(candidate) == c.q.name {\n\t\t\tc.i++\n\t\t\treturn candidate, c.i < len(c.q.db)\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc (db Db) NewQuery(t Term) *Query ", "output": "{\n\treturn &Query{\n\t\tdb: db,\n\t\tname: Name(t),\n\t\tarity: Arity(t),\n\t}\n}"} {"input": "package main\n\n\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\nconst semanticAlphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-\"\n\n\n\nconst (\n\tappMajor uint = 0\n\tappMinor uint = 1\n\tappPatch uint = 0\n\n\tappPreRelease = \"alpha\"\n)\n\n\n\n\nvar appBuild string\n\n\n\n\n\n\n\n\n\nfunc normalizeVerString(str string) string {\n\tvar result bytes.Buffer\n\tfor _, r := range str {\n\t\tif strings.ContainsRune(semanticAlphabet, r) {\n\t\t\tresult.WriteRune(r)\n\t\t}\n\t}\n\treturn result.String()\n}\n\nfunc version() string ", "output": "{\n\tversion := fmt.Sprintf(\"%d.%d.%d\", appMajor, appMinor, appPatch)\n\n\tpreRelease := normalizeVerString(appPreRelease)\n\tif preRelease != \"\" {\n\t\tversion = fmt.Sprintf(\"%s-%s\", version, preRelease)\n\t}\n\n\tbuild := normalizeVerString(appBuild)\n\tif build != \"\" {\n\t\tversion = fmt.Sprintf(\"%s+%s\", version, build)\n\t}\n\n\treturn version\n}"} {"input": "package handlers\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/cloudfoundry-incubator/executor\"\n\t\"github.com/pivotal-golang/lager\"\n)\n\ntype CancelTaskHandler struct {\n\tlogger lager.Logger\n\texecutorClient executor.Client\n}\n\n\n\nfunc (h CancelTaskHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ttaskGuid := r.FormValue(\":task_guid\")\n\n\tlogger := h.logger.Session(\"cancel-task\", lager.Data{\n\t\t\"instance-guid\": taskGuid,\n\t})\n\n\tw.WriteHeader(http.StatusAccepted)\n\n\tgo func() {\n\t\tlogger.Info(\"deleting-container\")\n\t\terr := h.executorClient.DeleteContainer(taskGuid)\n\t\tif err == executor.ErrContainerNotFound {\n\t\t\tlogger.Info(\"container-not-found\")\n\t\t\treturn\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlogger.Error(\"failed-deleting-container\", err)\n\t\t\treturn\n\t\t}\n\n\t\tlogger.Info(\"succeeded-deleting-container\")\n\t}()\n}\n\nfunc NewCancelTaskHandler(logger lager.Logger, executorClient executor.Client) *CancelTaskHandler ", "output": "{\n\treturn &CancelTaskHandler{\n\t\tlogger: logger,\n\t\texecutorClient: executorClient,\n\t}\n}"} {"input": "package css\n\ntype Id string\n\nfunc (id Id) Selector() string {\n\treturn \"#\" + string(id)\n}\n\n\n\nfunc (id Id) Style(properties ...Property) RuleSet {\n\treturn For(id).Set(properties...)\n}\n\nfunc (id Id) WithPseudoClass(pseudoClass PseudoClass) SelectorWithPseudoClass ", "output": "{\n\treturn SelectorWithPseudoClass{Element: id, PseudoClass: pseudoClass}\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\n\t\"gopkg.in/stretchr/testify.v1/mock\"\n)\n\ntype Printer interface {\n\tHelp()\n\tVersion()\n\tMessage(msg string)\n\tError(err error)\n\tCommands()\n}\n\ntype TextPrinter struct {\n\tversion string\n}\n\nfunc NewTextPrinter(version string) *TextPrinter {\n\treturn &TextPrinter{version}\n}\n\nfunc (p *TextPrinter) Help() {\n\thelpText := `Name:\n\tfiz - a file wizard\n\nVersion:\n\t` + p.version + `\n\nUsage:\n\tfiz \n\n`\n\tp.Message(helpText)\n\tp.Commands()\n}\n\nfunc (p *TextPrinter) Version() {\n\tfmt.Println(\"fiz\", p.version)\n}\n\nfunc (p *TextPrinter) Message(msg string) {\n\tfmt.Print(msg)\n}\n\nfunc (p *TextPrinter) Error(err error) {\n\tfmt.Println(\"Error: \", err)\n}\n\nfunc (p *TextPrinter) Commands() {\n\tp.Message(COMMANDS_MSG)\n}\n\n\ntype MockPrinter struct {\n\tmock.Mock\n}\n\n\n\nfunc (m *MockPrinter) Help() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Version() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Message(msg string) {\n\tm.Called(msg)\n}\n\nfunc (m *MockPrinter) Error(err error) {\n\tm.Called(err)\n}\n\nfunc (m *MockPrinter) Commands() {\n\tm.Called()\n}\n\nfunc NewMockPrinter() *MockPrinter ", "output": "{\n\treturn &MockPrinter{}\n}"} {"input": "package wiringpi\n\n\n\n\n\n\n\n\n\n\n\nimport \"C\"\nimport (\n\t\"sync\"\n\n\t\"github.com/yroffin/jarvis-go-ext/logger\"\n)\n\n\ntype WiringPiDriver struct {\n}\n\nvar instance *WiringPiDriver\nvar once sync.Once\n\n\nfunc GetInstance() *WiringPiDriver {\n\tonce.Do(func() {\n\t\tinstance = new(WiringPiDriver)\n\t\tinstance.init()\n\t})\n\treturn instance\n}\n\n\nfunc (wiringPi *WiringPiDriver) init() int {\n\tvar res = int(C.wiringPiSetupInit())\n\tlogger.Default.Info(\"WiringPiDriver\", logger.Fields{\n\t\t\"Init\": \"on\",\n\t})\n\treturn res\n}\n\n\nfunc PinMode(pin int, value int) {\n\tC.pinMode(C.int(pin), C.int(value))\n}\n\n\nfunc DigitalWrite(pin int, value int) {\n\tC.digitalWrite(C.int(pin), C.int(value))\n}\n\n\nfunc DelayMicroseconds(delay uint) {\n\tC.delayMicroseconds(C.uint(delay))\n}\n\n\n\n\nfunc Delay(delay uint) ", "output": "{\n\tC.delay(C.uint(delay))\n}"} {"input": "package jaeger\n\nimport \"github.com/containous/traefik/old/log\"\n\n\ntype jaegerLogger struct{}\n\nfunc (l *jaegerLogger) Error(msg string) {\n\tlog.Errorf(\"Tracing jaeger error: %s\", msg)\n}\n\n\n\n\nfunc (l *jaegerLogger) Infof(msg string, args ...interface{}) ", "output": "{\n\tlog.Debugf(msg, args...)\n}"} {"input": "package models\n\nimport (\n\t\"koding/db/mongodb/modelhelper\"\n\t\"net\"\n\t\"socialapi/config\"\n\t\"socialapi/request\"\n\n\t\"github.com/koding/logging\"\n)\n\n\ntype Client struct {\n\tAccount *Account\n\n\tIP net.IP\n\n\tSessionID string\n}\n\n\ntype Context struct {\n\tGroupName string\n\tClient *Client\n\tlog logging.Logger\n}\n\n\nfunc NewContext(log logging.Logger) *Context {\n\treturn &Context{\n\t\tlog: log,\n\t}\n}\n\n\nfunc (c *Context) OverrideQuery(q *request.Query) *request.Query {\n\tq.GroupName = c.GroupName\n\tif c.IsLoggedIn() {\n\t\tq.AccountId = c.Client.Account.Id\n\t} else {\n\t\tq.AccountId = 0\n\t}\n\n\treturn q\n}\n\n\nfunc (c *Context) IsLoggedIn() bool {\n\tif c.Client == nil {\n\t\treturn false\n\t}\n\n\tif c.Client.Account == nil {\n\t\treturn false\n\t}\n\n\tif c.Client.Account.Id == 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\n\n\n\n\n\n\n\nfunc (c *Context) CanManage() error {\n\tif !c.IsLoggedIn() {\n\t\treturn ErrNotLoggedIn\n\t}\n\n\tcanManage, err := modelhelper.CanManage(c.Client.Account.Nick, c.GroupName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !canManage {\n\t\treturn ErrCannotManageGroup\n\t}\n\n\treturn nil\n}\n\n\nfunc (c *Context) MustGetLogger() logging.Logger {\n\tif c.log == nil {\n\t\tpanic(ErrLoggerNotExist)\n\t}\n\n\treturn c.log\n}\n\nfunc (c *Context) IsAdmin() bool ", "output": "{\n\tif !c.IsLoggedIn() {\n\t\treturn false\n\t}\n\n\tsuperAdmins := config.MustGet().DummyAdmins\n\treturn IsIn(c.Client.Account.Nick, superAdmins...)\n}"} {"input": "package groph\n\nimport \"fmt\"\n\ntype Edge struct {\n\tData `json:\"data, omitempty\"`\n\tPointsTo *Vertex `json:\"PointsTo, omitempty\"`\n\tFrom *Vertex `json:\"From, omitempty\"`\n\tWeight float64 `json:\"weight, omitempty\"`\n}\n\nfunc (e *Edge) Points(v *Vertex) bool {\n\treturn e.PointsTo == v\n}\n\n\n\nfunc (e *Edge) String() string ", "output": "{\n\treturn fmt.Sprintf(\"\\nEDGE ID: '%s'\\nData: '%v'\\nPointsTo ID: '%s'\\nPointsTo Data: '%v'\\nFrom ID: '%s'\\nFrom Data: '%v'\\nWeight: '%f'\\n\",\n\t\te.GetID(), e.GetData(), e.PointsTo.GetID(), e.PointsTo.GetData(), e.From.GetID(), e.From.GetData(), e.Weight)\n}"} {"input": "package app\n\nimport (\n\t\"os\"\n\t\"strings\"\n)\n\ntype Environment struct {\n\tEnv string\n\tPort string\n}\n\nfunc (this *App) defaultEnv() Environment {\n\treturn Environment{\n\t\tEnv: \"development\",\n\t\tPort: \"5000\",\n\t}\n}\n\n\n\nfunc envMap() map[string]string ", "output": "{\n\tenviron := os.Environ()\n\tenv := make(map[string]string)\n\n\tfor _, v := range environ {\n\t\tpair := strings.SplitN(v, \"=\", 2)\n\t\tenv[pair[0]] = pair[1]\n\t}\n\n\treturn env\n}"} {"input": "package remote\n\nimport (\n\t\"github.com/AsynkronIT/protoactor-go/actor\"\n)\n\ntype process struct {\n\tpid *actor.PID\n\tremote *Remote\n}\n\n\n\nfunc (ref *process) SendUserMessage(pid *actor.PID, message interface{}) {\n\theader, msg, sender := actor.UnwrapEnvelope(message)\n\tref.remote.SendMessage(pid, header, msg, sender, -1)\n}\n\nfunc (ref *process) SendSystemMessage(pid *actor.PID, message interface{}) {\n\n\tswitch msg := message.(type) {\n\tcase *actor.Watch:\n\t\trw := &remoteWatch{\n\t\t\tWatcher: msg.Watcher,\n\t\t\tWatchee: pid,\n\t\t}\n\t\tref.remote.edpManager.remoteWatch(rw)\n\tcase *actor.Unwatch:\n\t\truw := &remoteUnwatch{\n\t\t\tWatcher: msg.Watcher,\n\t\t\tWatchee: pid,\n\t\t}\n\t\tref.remote.edpManager.remoteUnwatch(ruw)\n\tdefault:\n\t\tref.remote.SendMessage(pid, nil, message, nil, -1)\n\t}\n}\n\nfunc (ref *process) Stop(pid *actor.PID) {\n\tref.SendSystemMessage(pid, stopMessage)\n}\n\nfunc newProcess(pid *actor.PID, r *Remote) actor.Process ", "output": "{\n\treturn &process{\n\t\tpid: pid,\n\t\tremote: r,\n\t}\n}"} {"input": "package tradier\n\n\n\ntype AccountService service\n\n\n\nfunc (s *AccountService) accountRequest(uri string) (*Account, *Response, error) ", "output": "{\n\treq, err := s.client.NewRequest(\"GET\", uri, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\ta := &Account{}\n\n\tresp, err := s.client.Do(req, a)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn a, resp, nil\n}"} {"input": "package sortedmap\n\nimport (\n\t\"testing\"\n\n\t\"github.com/umpc/go-sortedmap/asc\"\n)\n\n\n\nfunc batchInsertRecords(b *testing.B, n int) {\n\trecords := randRecords(n)\n\tsm := New(0, asc.Time)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsm.BatchInsert(records)\n\n\t\tb.StopTimer()\n\t\trecords = randRecords(n)\n\t\tsm = New(0, asc.Time)\n\t\tb.StartTimer()\n\t}\n}\n\nfunc BenchmarkInsert1Record(b *testing.B) {\n\tinsertRecord(b)\n}\n\nfunc BenchmarkBatchInsert10Records(b *testing.B) {\n\tbatchInsertRecords(b, 10)\n}\n\nfunc BenchmarkBatchInsert100Records(b *testing.B) {\n\tbatchInsertRecords(b, 100)\n}\n\nfunc BenchmarkBatchInsert1000Records(b *testing.B) {\n\tbatchInsertRecords(b, 1000)\n}\n\nfunc BenchmarkBatchInsert10000Records(b *testing.B) {\n\tbatchInsertRecords(b, 10000)\n}\n\nfunc insertRecord(b *testing.B) ", "output": "{\n\trecords := randRecords(1)\n\tsm := New(0, asc.Time)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsm.Insert(records[0].Key, records[0].Val)\n\n\t\tb.StopTimer()\n\t\trecords = randRecords(1)\n\t\tsm = New(0, asc.Time)\n\t\tb.StartTimer()\n\t}\n}"} {"input": "package cov\n\nimport \"fmt\"\n\n\ntype Package struct {\n\tName string `json:\"name\"`\n\tPath string `json:\"path\"`\n\tCoverage float64 `json:\"coverage\"`\n\tLOC int `json:\"loc\"`\n\tFunctions []*Function `json:\"-\"`\n}\n\n\n\n\n\nfunc (p *Package) Accumulate(p2 *Package) error ", "output": "{\n\tif p.Name != p2.Name {\n\t\treturn fmt.Errorf(\"Names do not match: %q != %q\", p.Name, p2.Name)\n\t}\n\tif p.Coverage != p2.Coverage {\n\t\tp.Coverage = p2.Coverage\n\t}\n\tif p.Path != p2.Path {\n\t\tp.Path = p2.Path\n\t}\n\tif len(p.Functions) != len(p2.Functions) {\n\t\treturn fmt.Errorf(\"Function counts do not match: %d != %d\", len(p.Functions), len(p2.Functions))\n\t}\n\tfor i, f := range p.Functions {\n\t\terr := f.Accumulate(p2.Functions[i])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package controller_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/almighty/almighty-core/app/test\"\n\t\"github.com/almighty/almighty-core/controller\"\n\t\"github.com/almighty/almighty-core/gormapplication\"\n\t\"github.com/almighty/almighty-core/gormtestsupport\"\n\t\"github.com/almighty/almighty-core/resource\"\n\t\"github.com/goadesign/goa\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"github.com/stretchr/testify/suite\"\n)\n\ntype TestFiltersREST struct {\n\tgormtestsupport.DBTestSuite\n\tdb *gormapplication.GormDB\n\tclean func()\n}\n\n\n\nfunc (rest *TestFiltersREST) TestListFiltersOK() {\n\tsvc := goa.New(\"filterService\")\n\tctrl := controller.NewFilterController(svc, rest.Configuration)\n\tres, filters := test.ListFilterOK(rest.T(), svc.Context, svc, ctrl, nil)\n\tassert.Equal(rest.T(), 5, len(filters.Data))\n\tassertResponseHeaders(rest.T(), res)\n}\n\nfunc TestRunFiltersREST(t *testing.T) ", "output": "{\n\tresource.Require(t, resource.Database)\n\tpwd, err := os.Getwd()\n\trequire.Nil(t, err)\n\tsuite.Run(t, &TestFiltersREST{DBTestSuite: gormtestsupport.NewDBTestSuite(pwd + \"/../config.yaml\")})\n}"} {"input": "package statictemplate\n\nimport (\n\t\"io\"\n)\n\ntype constantWriterTo string\n\n\n\nfunc (c constantWriterTo) WriteTo(w io.Writer) (int64, error) ", "output": "{\n\tn, err := io.WriteString(w, string(c))\n\treturn int64(n), err\n}"} {"input": "package assert\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc Float32Equals(t *testing.T, actual float32, expected float32) {\n\tif actual != expected {\n\t\tt.Fatalf(\"%#v != %#v\", actual, expected)\n\t}\n}\n\nfunc StringEquals(t *testing.T, actual string, expected string) {\n\tif actual != expected {\n\t\tt.Fatalf(\"%#v != %#v\", actual, expected)\n\t}\n}\n\nfunc IntListEquals(t *testing.T, actualList []int, expectedList []int) {\n\tIntEquals(t, len(actualList), len(expectedList))\n\tfor i, expected := range expectedList {\n\t\tIntEquals(t, actualList[i], expected)\n\t}\n}\n\nfunc IntListListEquals(t *testing.T, actualList [][]int, expectedList [][]int) {\n\tif len(actualList) != len(expectedList) {\n\t\tt.Fatalf(\"%#v != %#v\", actualList, expectedList)\n\t}\n\tfor i, expected := range expectedList {\n\t\tIntListEquals(t, actualList[i], expected)\n\t}\n}\n\nfunc IntEquals(t *testing.T, actual int, expected int) ", "output": "{\n\tif actual != expected {\n\t\tt.Fatalf(\"%#v != %#v\", actual, expected)\n\t}\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/mexisme/go-config/settings\"\n)\n\n\nfunc AddConfigItems(configKeys []string) {\n\tsettings.AddConfigItems(configKeys)\n}\n\n\nfunc AddConfigItemsWithPFlags(configKeys []string) error {\n\treturn settings.AddConfigItemsWithPFlags(configKeys)\n}\n\n\nfunc ApplyWith(key string, f func(interface{})) {\n\tsettings.ApplyWith(key, f)\n}\n\n\nfunc Get(key string) interface{} {\n\treturn settings.Get(key)\n}\n\n\nfunc GetBool(key string) bool {\n\treturn settings.GetBool(key)\n}\n\n\nfunc GetFloat64(key string) float64 {\n\treturn settings.GetFloat64(key)\n}\n\n\nfunc GetInt(key string) int {\n\treturn settings.GetInt(key)\n}\n\n\nfunc GetString(key string) string {\n\treturn settings.GetString(key)\n}\n\n\nfunc GetStringMap(key string) map[string]interface{} {\n\treturn settings.GetStringMap(key)\n}\n\n\nfunc GetStringMapString(key string) map[string]string {\n\treturn settings.GetStringMapString(key)\n}\n\n\nfunc GetStringSlice(key string) []string {\n\treturn settings.GetStringSlice(key)\n}\n\n\nfunc GetTime(key string) time.Time {\n\treturn settings.GetTime(key)\n}\n\n\n\n\n\nfunc IsSet(key string) bool {\n\treturn settings.IsSet(key)\n}\n\n\nfunc AllSettings() map[string]interface{} {\n\treturn settings.AllSettings()\n}\n\nfunc GetDuration(key string) time.Duration ", "output": "{\n\treturn settings.GetDuration(key)\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n\ntype ParamResponse struct {\n\tVersion string `json:\"version\"`\n\tResponse []Parameter `json:\"response\"`\n}\n\n\ntype Parameter struct {\n\tName string `json:\"name\"`\n\tConfigFile string `json:\"configFile\"`\n\tValue string `json:\"Value\"`\n\tLastUpdated string `json:\"lastUpdated\"`\n}\n\n\n\n\nfunc (to *Session) Parameters(profileName string) ([]Parameter, error) ", "output": "{\n\turl := fmt.Sprintf(\"/api/1.2/parameters/profile/%s.json\", profileName)\n\tresp, err := to.request(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar data ParamResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&data); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data.Response, nil\n}"} {"input": "package terraform\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hashicorp/hcl2/hcl\"\n\t\"github.com/hashicorp/terraform/addrs\"\n\t\"github.com/zclconf/go-cty/cty\"\n)\n\n\n\n\ntype EvalLocal struct {\n\tAddr addrs.LocalValue\n\tExpr hcl.Expression\n}\n\n\n\n\n\n\ntype EvalDeleteLocal struct {\n\tAddr addrs.LocalValue\n}\n\nfunc (n *EvalDeleteLocal) Eval(ctx EvalContext) (interface{}, error) {\n\tstate := ctx.State()\n\tif state == nil {\n\t\treturn nil, nil\n\t}\n\n\tstate.RemoveLocalValue(n.Addr.Absolute(ctx.Path()))\n\treturn nil, nil\n}\n\nfunc (n *EvalLocal) Eval(ctx EvalContext) (interface{}, error) ", "output": "{\n\tval, diags := ctx.EvaluateExpr(n.Expr, cty.DynamicPseudoType, nil)\n\tif diags.HasErrors() {\n\t\treturn nil, diags.Err()\n\t}\n\n\tstate := ctx.State()\n\tif state == nil {\n\t\treturn nil, fmt.Errorf(\"cannot write local value to nil state\")\n\t}\n\n\tstate.SetLocalValue(n.Addr.Absolute(ctx.Path()), val)\n\n\treturn nil, nil\n}"} {"input": "package jpsplus\n\nimport (\n\t\"container/heap\"\n)\n\ntype PriorityQueue struct {\n\tpos int\n\tnode map[int]*Node\n}\n\nfunc newPriorityQueue() *PriorityQueue {\n\tp := new(PriorityQueue)\n\tp.node = make(map[int]*Node)\n\treturn p\n}\n\nfunc (p *PriorityQueue) Len() int {\n\treturn len(p.node)\n}\n\nfunc (p *PriorityQueue) Less(i, j int) bool {\n\treturn p.node[i].finalCost < p.node[j].finalCost\n}\n\nfunc (p *PriorityQueue) Swap(i, j int) {\n\tp.node[i], p.node[j] = p.node[j], p.node[i]\n\tp.node[i].heapIndex = i\n\tp.node[j].heapIndex = j\n}\n\nfunc (p *PriorityQueue) Push(x interface{}) {\n\titem, ok := x.(*Node)\n\tif ok {\n\t\titem.heapIndex = p.pos\n\t\tp.node[p.pos] = item\n\t\tp.pos++\n\t}\n}\n\n\n\nfunc (p *PriorityQueue) PushNode(n *Node) {\n\theap.Push(p, n)\n}\n\nfunc (p *PriorityQueue) PopNode() *Node {\n\treturn heap.Pop(p).(*Node)\n}\n\nfunc (p *PriorityQueue) RemoveNode(n *Node) {\n\theap.Remove(p, n.heapIndex)\n}\n\nfunc (p *PriorityQueue) Pop() interface{} ", "output": "{\n\tp.pos--\n\titem := p.node[p.pos]\n\tdelete(p.node, p.pos)\n\treturn item\n}"} {"input": "package main\n\ntype Element interface {\n}\n\ntype Vector struct {\n\tnelem int;\n\telem []Element;\n}\n\nfunc New() *Vector {\n\tv := new(Vector);\n\tv.nelem = 0;\n\tv.elem = make([]Element, 10);\n\treturn v;\n}\n\nfunc (v *Vector) At(i int) Element {\n\treturn v.elem[i];\n}\n\n\n\nfunc main() {\n\ttype I struct { val int; };\n\ti0 := new(I); i0.val = 0;\n\ti1 := new(I); i1.val = 11;\n\ti2 := new(I); i2.val = 222;\n\ti3 := new(I); i3.val = 3333;\n\ti4 := new(I); i4.val = 44444;\n\tv := New();\n\tprint(\"hi\\n\");\n\tv.Insert(i4);\n\tv.Insert(i3);\n\tv.Insert(i2);\n\tv.Insert(i1);\n\tv.Insert(i0);\n\tfor i := 0; i < v.nelem; i++ {\n\t\tvar x *I;\n\t\tx = v.At(i).(*I);\n\t\tprint(i, \" \", x.val, \"\\n\"); \n\t}\n\tfor i := 0; i < v.nelem; i++ {\n\t\tprint(i, \" \", v.At(i).(*I).val, \"\\n\");\n\t}\n}\n\nfunc (v *Vector) Insert(e Element) ", "output": "{\n\tv.elem[v.nelem] = e;\n\tv.nelem++;\n}"} {"input": "package leet_61\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\n\n\nfunc rotateRight(head *ListNode, k int) *ListNode ", "output": "{\n\tif head == nil || k == 0 {\n\t\treturn head\n\t}\n\tcur := head\n\tcount := 1\n\tfor cur.Next != nil {\n\t\tcur = cur.Next\n\t\tcount++\n\t}\n\tcur.Next = head\n\tk %= count\n\tcur = head\n\tlength := count - k\n\tfor i := 1; i < length; i++ {\n\t\tcur = cur.Next\n\t}\n\tans := cur.Next\n\tcur.Next = nil\n\treturn ans\n}"} {"input": "package test\n\nimport \"io\"\n\n\ntype PlainReader struct {\n\tr io.Reader\n}\n\n\nfunc NewPlainReader(r io.Reader) *PlainReader {\n\treturn &PlainReader{r}\n}\n\n\n\n\n\n\n\ntype ErrorReader struct {\n\tn int\n}\n\n\nfunc NewErrorReader(n int) *ErrorReader {\n\treturn &ErrorReader{n}\n}\n\n\nfunc (r *ErrorReader) Read(b []byte) (n int, err error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tif r.n == 0 {\n\t\treturn 0, ErrPlain\n\t}\n\tr.n--\n\tb[0] = '.'\n\treturn 1, nil\n}\n\n\n\n\ntype InfiniteReader struct{}\n\n\nfunc NewInfiniteReader() *InfiniteReader {\n\treturn &InfiniteReader{}\n}\n\n\nfunc (r *InfiniteReader) Read(b []byte) (n int, err error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tb[0] = '.'\n\treturn 1, nil\n}\n\n\n\n\ntype EmptyReader struct {\n}\n\n\nfunc NewEmptyReader() *EmptyReader {\n\treturn &EmptyReader{}\n}\n\n\nfunc (r *EmptyReader) Read(b []byte) (n int, err error) {\n\treturn 0, io.EOF\n}\n\nfunc (r *PlainReader) Read(p []byte) (int, error) ", "output": "{\n\treturn r.r.Read(p)\n}"} {"input": "package term\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc IsANSI(f *os.File) bool {\n\treturn IsTerminal(f)\n}\n\n\nfunc IsTerminal(f *os.File) bool {\n\tcmd := exec.Command(\"test\", \"-t\", \"0\")\n\tcmd.Stdin = f\n\treturn cmd.Run() == nil\n}\n\nfunc MakeRaw(f *os.File) error {\n\treturn stty(f, \"-icanon\", \"-echo\").Run()\n}\n\nfunc Restore(f *os.File) error {\n\treturn stty(f, \"icanon\", \"echo\").Run()\n}\n\n\n\nfunc Lines() (int, error) {\n\tcols, err := tput(\"lines\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}\n\n\n\nfunc stty(f *os.File, args ...string) *exec.Cmd {\n\tc := exec.Command(\"stty\", args...)\n\tc.Stdin = f\n\treturn c\n}\n\nfunc tput(what string) (string, error) {\n\tc := exec.Command(\"tput\", what)\n\tc.Stderr = os.Stderr\n\tout, err := c.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.TrimSpace(string(out)), nil\n}\n\nfunc Cols() (int, error) ", "output": "{\n\tcols, err := tput(\"cols\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}"} {"input": "package app\n\ntype Page interface {\n\tGetTemplate() string\n\tSetSessionData(u User)\n}\n\ntype PageWeb struct {\n\tTitrePage string\n\tTemplate string\n\tSessIdUser int64\n\tSessNameUser string\n\tSessIsLogged bool\n}\n\n\n\nfunc (p *PageWeb) SetSessionData(u User) {\n\tif u.Id != 0 && u.Prenom != \"\" {\n\t\tp.SessIdUser = u.Id\n\t\tp.SessIsLogged = true\n\t\tp.SessNameUser = u.Prenom\n\n\t} else {\n\t\tp.SessIdUser = 0\n\t\tp.SessIsLogged = false\n\t\tp.SessNameUser = \"\"\n\t}\n}\n\nfunc (p *PageWeb) GetTemplate() string ", "output": "{\n\treturn p.Template\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc leapYear(year int) bool {\n\tswitch {\n\tcase year%4 != 0:\n\t\treturn false\n\tcase year%400 == 0:\n\t\treturn true\n\tdefault:\n\t\treturn year%100 != 0\n\t}\n}\n\nfunc huluculuYear(year int) bool { return year%15 == 0 }\n\n\n\nfunc main() {\n\tin, _ := os.Open(\"10070.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"10070.out\")\n\tdefer out.Close()\n\n\tvar year int\n\tfor first := true; ; {\n\t\tif _, err := fmt.Fscanf(in, \"%d\", &year); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif first {\n\t\t\tfirst = false\n\t\t} else {\n\t\t\tfmt.Fprintln(out)\n\t\t}\n\t\tif leap, huluculu, bulukulu := leapYear(year), huluculuYear(year), bulukuluYear(year); !leap && !huluculu && !bulukulu {\n\t\t\tfmt.Fprintln(out, \"This is an ordinary year.\")\n\t\t} else {\n\t\t\tif leap {\n\t\t\t\tfmt.Fprintln(out, \"This is leap year.\")\n\t\t\t}\n\t\t\tif huluculu {\n\t\t\t\tfmt.Fprintln(out, \"This is huluculu festival year.\")\n\t\t\t}\n\t\t\tif bulukulu {\n\t\t\t\tfmt.Fprintln(out, \"This is bulukulu festival year.\")\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc bulukuluYear(year int) bool ", "output": "{ return leapYear(year) && year%55 == 0 }"} {"input": "package server\n\nimport (\n\t\"fmt\"\n\t\"github.com/centurylinkcloud/clc-go-cli/base\"\n)\n\ntype Server struct {\n\tServerId string\n\tServerName string\n}\n\n\n\nfunc (s *Server) InferID(cn base.Connection) error {\n\tif s.ServerName == \"\" {\n\t\treturn nil\n\t}\n\n\tID, err := IDByName(cn, s.ServerName)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.ServerId = ID\n\treturn nil\n}\n\nfunc (s *Server) GetNames(cn base.Connection, property string) ([]string, error) {\n\tif property != \"ServerName\" {\n\t\treturn nil, nil\n\t}\n\n\treturn GetNames(cn, \"all\")\n}\n\nfunc (s *Server) Validate() error ", "output": "{\n\tif (s.ServerId == \"\") == (s.ServerName == \"\") {\n\t\treturn fmt.Errorf(\"Exactly one of the server-id and server-name must be set.\")\n\t}\n\treturn nil\n}"} {"input": "package templates\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewGetTemplatesLibraryParams() *GetTemplatesLibraryParams {\n\n\treturn &GetTemplatesLibraryParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\n\n\n\ntype GetTemplatesLibraryParams struct {\n\ttimeout time.Duration\n}\n\n\nfunc (o *GetTemplatesLibraryParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewGetTemplatesLibraryParamsWithTimeout(timeout time.Duration) *GetTemplatesLibraryParams ", "output": "{\n\n\treturn &GetTemplatesLibraryParams{\n\n\t\ttimeout: timeout,\n\t}\n}"} {"input": "package elastic\n\n\n\n\n\n\n\n\n\ntype MissingAggregation struct {\n\tfield string\n\tsubAggregations map[string]Aggregation\n\tmeta map[string]interface{}\n}\n\nfunc NewMissingAggregation() *MissingAggregation {\n\treturn &MissingAggregation{\n\t\tsubAggregations: make(map[string]Aggregation),\n\t}\n}\n\nfunc (a *MissingAggregation) Field(field string) *MissingAggregation {\n\ta.field = field\n\treturn a\n}\n\nfunc (a *MissingAggregation) SubAggregation(name string, subAggregation Aggregation) *MissingAggregation {\n\ta.subAggregations[name] = subAggregation\n\treturn a\n}\n\n\nfunc (a *MissingAggregation) Meta(metaData map[string]interface{}) *MissingAggregation {\n\ta.meta = metaData\n\treturn a\n}\n\n\n\nfunc (a *MissingAggregation) Source() (interface{}, error) ", "output": "{\n\n\tsource := make(map[string]interface{})\n\topts := make(map[string]interface{})\n\tsource[\"missing\"] = opts\n\n\tif a.field != \"\" {\n\t\topts[\"field\"] = a.field\n\t}\n\n\tif len(a.subAggregations) > 0 {\n\t\taggsMap := make(map[string]interface{})\n\t\tsource[\"aggregations\"] = aggsMap\n\t\tfor name, aggregate := range a.subAggregations {\n\t\t\tsrc, err := aggregate.Source()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\taggsMap[name] = src\n\t\t}\n\t}\n\n\tif len(a.meta) > 0 {\n\t\tsource[\"meta\"] = a.meta\n\t}\n\n\treturn source, nil\n}"} {"input": "package logs\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestLog(t *testing.T) {\n\tlog := New(\"a simple log\")\n\tt.Log(log)\n}\n\n\n\nfunc TestNewf(t *testing.T) {\n\tlog := Newf(\"hello %q\", \"world\")\n\tt.Log(log)\n}\n\ntype goStringer struct{}\n\nfunc (s goStringer) GoString() string {\n\treturn \"go stringer !\"\n}\n\nfunc BenchmarkNew(b *testing.B) {\n\tfor n := 0; n < b.N; n++ {\n\t\tNew(\"a log with tags\").\n\t\t\tTag(\"string\", \"hello world\").\n\t\t\tTag(\"int8\", int8(8)).\n\t\t\tTag(\"int16\", int16(16)).\n\t\t\tTag(\"int32\", int32(32)).\n\t\t\tTag(\"int64\", int64(64))\n\t}\n}\n\nfunc BenchmarkString(b *testing.B) {\n\tvar s string\n\n\tfor n := 0; n < b.N; n++ {\n\t\ts = New(\"a log with tags\").\n\t\t\tTag(\"string\", \"hello world\").\n\t\t\tTag(\"int8\", int8(8)).\n\t\t\tTag(\"int16\", int16(16)).\n\t\t\tTag(\"int32\", int32(32)).\n\t\t\tTag(\"int64\", int64(64)).\n\t\t\tString()\n\t}\n\n\tb.Log(s)\n}\n\nfunc TestLogWithTags(t *testing.T) ", "output": "{\n\tlog := New(\"an log with tags\").\n\t\tTag(\"string\", \"hello world\").\n\t\tTag(\"go-stringer\", goStringer{}).\n\t\tTag(\"duration\", time.Duration(3600000000)).\n\t\tTag(\"int\", 42).\n\t\tTag(\"int8\", int8(8)).\n\t\tTag(\"int16\", int16(16)).\n\t\tTag(\"int32\", int32(32)).\n\t\tTag(\"int64\", int64(64)).\n\t\tTag(\"uint\", uint(42)).\n\t\tTag(\"uint8\", uint8(8)).\n\t\tTag(\"uint16\", uint16(16)).\n\t\tTag(\"uint32\", uint32(32)).\n\t\tTag(\"uint64\", uint64(64)).\n\t\tTag(\"float32\", float32(32.42)).\n\t\tTag(\"float64\", float64(64.42)).\n\t\tTag(\"slice\", []string{\"hello\", \"world\"})\n\tt.Log(\"\\n\", log)\n}"} {"input": "package geoip_test\n\nimport (\n\t\"github.com/corestoreio/pkg/net/geoip\"\n\t\"github.com/corestoreio/pkg/store\"\n\t\"github.com/corestoreio/pkg/store/scope\"\n)\n\ntype storeFinderMock struct{}\n\nfunc (storeFinderMock) DefaultStoreID(runMode scope.TypeID) (websiteID, storeID uint32, err error) {\n\treturn\n}\n\n\n\n\nvar (\n\t_ geoip.StoreFinder = (*storeFinderMock)(nil)\n\t_ store.Finder = (*storeFinderMock)(nil)\n)\n\nfunc (storeFinderMock) StoreIDbyCode(runMode scope.TypeID, storeCode string) (websiteID, storeID uint32, err error) ", "output": "{\n\treturn\n}"} {"input": "package server\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"os/signal\"\n\n\t\"k8s.io/klog/v2\"\n)\n\nvar onlyOneSignalHandler = make(chan struct{})\nvar shutdownHandler chan os.Signal\n\n\n\n\n\n\n\n\n\n\n\nfunc SetupSignalContext(exitOnSecondSignal bool) context.Context {\n\tclose(onlyOneSignalHandler) \n\n\tshutdownHandler = make(chan os.Signal, 2)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tsignal.Notify(shutdownHandler, shutdownSignals...)\n\tgo func() {\n\t\t<-shutdownHandler\n\t\tcancel()\n\t\tif exitOnSecondSignal {\n\t\t\t<-shutdownHandler\n\t\t\tos.Exit(1)\n\t\t} else {\n\t\t\tfor {\n\t\t\t\t<-shutdownHandler\n\t\t\t\tklog.Infof(\"Termination signal has been received already. Ignoring signal.\")\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn ctx\n}\n\n\n\nfunc RequestShutdown() bool {\n\tif shutdownHandler != nil {\n\t\tselect {\n\t\tcase shutdownHandler <- shutdownSignals[0]:\n\t\t\treturn true\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc SetupSignalHandler(exitOnSecondSignal bool) <-chan struct{} ", "output": "{\n\treturn SetupSignalContext(exitOnSecondSignal).Done()\n}"} {"input": "package v1\n\nimport (\n\t\"github.com/rancher/norman/lifecycle\"\n\t\"github.com/rancher/norman/resource\"\n\tv1 \"k8s.io/api/apps/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\ntype StatefulSetLifecycle interface {\n\tCreate(obj *v1.StatefulSet) (runtime.Object, error)\n\tRemove(obj *v1.StatefulSet) (runtime.Object, error)\n\tUpdated(obj *v1.StatefulSet) (runtime.Object, error)\n}\n\ntype statefulSetLifecycleAdapter struct {\n\tlifecycle StatefulSetLifecycle\n}\n\nfunc (w *statefulSetLifecycleAdapter) HasCreate() bool {\n\to, ok := w.lifecycle.(lifecycle.ObjectLifecycleCondition)\n\treturn !ok || o.HasCreate()\n}\n\nfunc (w *statefulSetLifecycleAdapter) HasFinalize() bool {\n\to, ok := w.lifecycle.(lifecycle.ObjectLifecycleCondition)\n\treturn !ok || o.HasFinalize()\n}\n\nfunc (w *statefulSetLifecycleAdapter) Create(obj runtime.Object) (runtime.Object, error) {\n\to, err := w.lifecycle.Create(obj.(*v1.StatefulSet))\n\tif o == nil {\n\t\treturn nil, err\n\t}\n\treturn o, err\n}\n\nfunc (w *statefulSetLifecycleAdapter) Finalize(obj runtime.Object) (runtime.Object, error) {\n\to, err := w.lifecycle.Remove(obj.(*v1.StatefulSet))\n\tif o == nil {\n\t\treturn nil, err\n\t}\n\treturn o, err\n}\n\nfunc (w *statefulSetLifecycleAdapter) Updated(obj runtime.Object) (runtime.Object, error) {\n\to, err := w.lifecycle.Updated(obj.(*v1.StatefulSet))\n\tif o == nil {\n\t\treturn nil, err\n\t}\n\treturn o, err\n}\n\n\n\nfunc NewStatefulSetLifecycleAdapter(name string, clusterScoped bool, client StatefulSetInterface, l StatefulSetLifecycle) StatefulSetHandlerFunc ", "output": "{\n\tif clusterScoped {\n\t\tresource.PutClusterScoped(StatefulSetGroupVersionResource)\n\t}\n\tadapter := &statefulSetLifecycleAdapter{lifecycle: l}\n\tsyncFn := lifecycle.NewObjectLifecycleAdapter(name, clusterScoped, adapter, client.ObjectClient())\n\treturn func(key string, obj *v1.StatefulSet) (runtime.Object, error) {\n\t\tnewObj, err := syncFn(key, obj)\n\t\tif o, ok := newObj.(runtime.Object); ok {\n\t\t\treturn o, err\n\t\t}\n\t\treturn nil, err\n\t}\n}"} {"input": "package do\n\nimport \"strings\"\n\n\n\nfunc SafeClusterName(clusterName string) string ", "output": "{\n\tsafeClusterName := strings.Replace(clusterName, \".\", \"-\", -1)\n\treturn safeClusterName\n}"} {"input": "package proxy\n\nimport (\n\t\"store\"\n\t\"utils\"\n)\n\nconst (\n\tEFFICIENT_POOL_KEY = \"EfficientPoolKey\"\n)\n\nvar (\n\tefficientPool = InitEfficientPool()\n)\n\ntype EfficientPool struct {\n\tBasePool\n\tStorage store.SetStringStorer\n}\n\n\n\nfunc (pool *EfficientPool) Add(proxy string) {\n\tpool.Storage.Add(EFFICIENT_POOL_KEY, proxy)\n}\n\nfunc (pool *EfficientPool) Remove(proxy string) {\n\tpool.Storage.Remove(EFFICIENT_POOL_KEY, proxy)\n}\n\nfunc Rand() (ok bool, proxy string) {\n\treturn efficientPool.Storage.Rand(EFFICIENT_POOL_KEY)\n}\n\nfunc Feedback(proxy string, ok bool, time int) {\n\tstablePool.Add(proxy, utils.EscapeToTime(ok, time))\n\n\tif !ok {\n\t\tefficientPool.Remove(proxy)\n\t}\n}\n\nfunc InitEfficientPool() *EfficientPool ", "output": "{\n\treturn &EfficientPool{BasePool: *InitBasePool(), Storage: store.RedisSet{}}\n}"} {"input": "package app\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\ntype collect struct{\n\turl string\n\tcontroller func(w http.ResponseWriter, r *http.Request) bool\n}\n\nfunc render(w http.ResponseWriter, r *http.Request){\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\troutes := Routes()\n\turl := r.URL.Path\n\tfor _, element := range routes{\n\t\tif url == element.url {\n\t\t\telement.controller(w, r)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Fprintf(w, \"

Error 404

\")\n}\n\n\n\nfunc Server(port int, host string){\n\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc( \"/\" , func(w http.ResponseWriter, r *http.Request){\n\t\trender(w, r)\n\t})\n\tmux.HandleFunc( \"/api/\" , func(w http.ResponseWriter, r *http.Request){\n\t\tapi(w, r)\n\t})\n\n\tprintln( fmt.Sprintf(\"Starting exodo server on port %d\", port))\n http.ListenAndServe(fmt.Sprintf(\"%s:%d\",host, port), mux)\n}\n\nfunc api(w http.ResponseWriter, r *http.Request)", "output": "{\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\troutes := Routes()\n\turl := r.URL.Path\n\tfor _, element := range routes{\n\t\tif url == element.url {\n\t\t\telement.controller(w, r)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Fprintf(w, \"{\\\"error\\\":true}\")\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realIAMInstanceProfile IAMInstanceProfile\n\n\nfunc (o *IAMInstanceProfile) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realIAMInstanceProfile\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = IAMInstanceProfile(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &IAMInstanceProfile{}\n\n\nfunc (o *IAMInstanceProfile) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\nvar _ fi.HasName = &IAMInstanceProfile{}\n\n\n\n\n\nfunc (o *IAMInstanceProfile) SetName(name string) {\n\to.Name = &name\n}\n\n\nfunc (o *IAMInstanceProfile) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *IAMInstanceProfile) GetName() *string ", "output": "{\n\treturn o.Name\n}"} {"input": "package networkcontainers\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com/Azure/azure-container-networking/cns\"\n\t\"github.com/Azure/azure-container-networking/log\"\n)\n\n\ntype NetworkContainers struct {\n\tlogpath string\n}\n\nfunc interfaceExists(iFaceName string) (bool, error) {\n\t_, err := net.InterfaceByName(iFaceName)\n\n\tif err != nil {\n\t\terrMsg := fmt.Sprintf(\"[Azure CNS] Unable to get interface by name %v, %v\", iFaceName, err)\n\t\tlog.Printf(errMsg)\n\t\treturn false, errors.New(errMsg)\n\t}\n\n\treturn true, nil\n}\n\n\nfunc (cn *NetworkContainers) Create(createNetworkContainerRequest cns.CreateNetworkContainerRequest) error {\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Create called\")\n\terr := createOrUpdateInterface(createNetworkContainerRequest)\n\tif err == nil {\n\t\terr = setWeakHostOnInterface(createNetworkContainerRequest.PrimaryInterfaceIdentifier)\n\t}\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Create finished.\")\n\treturn err\n}\n\n\nfunc (cn *NetworkContainers) Update(createNetworkContainerRequest cns.CreateNetworkContainerRequest) error {\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Update called\")\n\terr := createOrUpdateInterface(createNetworkContainerRequest)\n\tif err == nil {\n\t\terr = setWeakHostOnInterface(createNetworkContainerRequest.PrimaryInterfaceIdentifier)\n\t}\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Update finished.\")\n\treturn err\n}\n\n\n\n\nfunc (cn *NetworkContainers) Delete(networkContainerID string) error ", "output": "{\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Delete called\")\n\terr := deleteInterface(networkContainerID)\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Delete finished.\")\n\treturn err\n}"} {"input": "package v1\n\n\n\ntype PodAffinityApplyConfiguration struct {\n\tRequiredDuringSchedulingIgnoredDuringExecution []PodAffinityTermApplyConfiguration `json:\"requiredDuringSchedulingIgnoredDuringExecution,omitempty\"`\n\tPreferredDuringSchedulingIgnoredDuringExecution []WeightedPodAffinityTermApplyConfiguration `json:\"preferredDuringSchedulingIgnoredDuringExecution,omitempty\"`\n}\n\n\n\nfunc PodAffinity() *PodAffinityApplyConfiguration {\n\treturn &PodAffinityApplyConfiguration{}\n}\n\n\n\n\nfunc (b *PodAffinityApplyConfiguration) WithRequiredDuringSchedulingIgnoredDuringExecution(values ...*PodAffinityTermApplyConfiguration) *PodAffinityApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRequiredDuringSchedulingIgnoredDuringExecution\")\n\t\t}\n\t\tb.RequiredDuringSchedulingIgnoredDuringExecution = append(b.RequiredDuringSchedulingIgnoredDuringExecution, *values[i])\n\t}\n\treturn b\n}\n\n\n\n\n\n\nfunc (b *PodAffinityApplyConfiguration) WithPreferredDuringSchedulingIgnoredDuringExecution(values ...*WeightedPodAffinityTermApplyConfiguration) *PodAffinityApplyConfiguration ", "output": "{\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPreferredDuringSchedulingIgnoredDuringExecution\")\n\t\t}\n\t\tb.PreferredDuringSchedulingIgnoredDuringExecution = append(b.PreferredDuringSchedulingIgnoredDuringExecution, *values[i])\n\t}\n\treturn b\n}"} {"input": "package geom\n\nimport \"math\"\n\n\ntype Vertex struct {\n\tX, Y float64\n}\n\n\ntype Vertices []Vertex\n\n\nfunc (l Vertices) Convert() (data []float32) {\n\n\tdata = make([]float32, len(l)*2)\n\tfor i, v := range l {\n\t\tindex := i * 2\n\t\tdata[index] = float32(v.X)\n\t\tdata[index+1] = float32(v.Y)\n\t}\n\treturn\n}\n\n\nfunc (c Vertex) SideOfLine(a Vertex, b Vertex) int {\n\n\tcross := float64((b.X-a.X)*(c.Y-a.Y) - (b.Y-a.Y)*(c.X-a.X))\n\n\tif cross == 0 {\n\t\treturn 0\n\t}\n\tif math.Signbit(cross) {\n\t\treturn 1\n\t}\n\treturn -1\n\n}\n\n\ntype Lexographically []Vertex\n\n\nfunc (a Lexographically) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a Lexographically) Less(i, j int) bool {\n\tif a[i].X == a[j].X {\n\t\treturn a[i].Y < a[j].Y\n\t}\n\treturn a[i].X < a[j].X\n}\n\nfunc (a Lexographically) Len() int ", "output": "{ return len(a) }"} {"input": "package app\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"strings\"\n\t\"github.com/h2object/h2object/httpext\"\n)\n\n\n\nfunc do_authentic(ctx *context, ctrl *ext.Controller) bool {\n\tr := ctrl.Request\n\trequired := false\n\tswitch r.MethodToLower() {\n\tcase \"get\":\n\t\tswitch r.Suffix() {\n\t\tcase \"page\":\n\t\t\tfallthrough\n\t\tcase \"click\":\n\t\t\tfallthrough\t\n\t\tcase \"system\":\n\t\t\trequired = true\n\t\t}\n\n\t\tif r.URI() == \"/stats\" {\n\t\t\trequired = true\t\n\t\t}\n\tcase \"put\":\n\t\trequired = true\n\t\tif ctx.storage_full() {\n\t\t\tctrl.JsonError(http.StatusForbidden, errors.New(\"application storage reach max limit.\"))\n\t\t\treturn true\n\t\t}\n\tcase \"delete\":\n\t\trequired = true\n\t}\n\n\ttoken := r.Param(\"token\")\n\tif token == \"\" {\n\t\tauthorization := r.Header.Get(\"Authorization\")\n\t\tif strings.HasPrefix(authorization, \"H2OBJECT \") {\n\t\t\ttoken = authorization[len(\"H2OBJECT \"):]\n\t\t}\n\t}\n\tif required {\n\t\tif token != ctx.signature {\n\t\t\tctrl.JsonError(http.StatusUnauthorized, errors.New(\"require administrator right\"))\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc acl_filter(ctx *context, c *ext.Controller, filters []filter) ", "output": "{\n\tif done := do_authentic(ctx, c); done {\n\t\tctx.Info(\"request (%s) (%s) done by acl\", c.Request.MethodToLower(), c.Request.URI())\n\t\treturn\n\t}\n\n\tfilters[0](ctx, c, filters[1:])\n}"} {"input": "package url\n\nimport (\n\t\"github.com/dpb587/metalink\"\n\t\"github.com/dpb587/metalink/file\"\n)\n\ntype MultiLoader struct {\n\tloaders []Loader\n}\n\nvar _ Loader = &MultiLoader{}\n\nfunc NewMultiLoader(loaders ...Loader) *MultiLoader {\n\treturn &MultiLoader{\n\t\tloaders: loaders,\n\t}\n}\n\n\n\nfunc (l *MultiLoader) LoadURL(source metalink.URL) (file.Reference, error) {\n\tfor _, loader := range l.loaders {\n\t\tif !loader.SupportsURL(source) {\n\t\t\tcontinue\n\t\t}\n\n\t\tref, err := loader.LoadURL(source)\n\t\tif err == UnsupportedURLError {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn ref, err\n\t}\n\n\treturn nil, UnsupportedURLError\n}\n\nfunc (l *MultiLoader) Add(add Loader) {\n\tl.loaders = append(l.loaders, add)\n}\n\nfunc (l *MultiLoader) SupportsURL(source metalink.URL) bool ", "output": "{\n\tfor _, loader := range l.loaders {\n\t\tif loader.SupportsURL(source) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package metrics\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestNothing(t *testing.T) ", "output": "{\n\tt.Log(\"success!\")\n}"} {"input": "package rpc\n\nimport pb \"github.com/anycable/anycable-go/protos\"\n\n\ntype ClientHelper interface {\n\tReady() error\n\tClose()\n}\n\n\ntype Dialer = func(c *Config) (pb.RPCClient, ClientHelper, error)\n\n\ntype Config struct {\n\tHost string\n\tConcurrency int\n\tEnableTLS bool\n\tMaxRecvSize int\n\tMaxSendSize int\n\tDialFun Dialer\n}\n\n\n\n\nfunc NewConfig() Config ", "output": "{\n\treturn Config{Concurrency: 28, EnableTLS: false}\n}"} {"input": "package main\n\n\n\nvar signalTests = []testCase{\n\t{\n\t\tName: \"signal.0\",\n\t\tIn: `package main\n\nimport (\n\t_ \"a\"\n\t\"os/signal\"\n\t_ \"z\"\n)\n\ntype T1 signal.UnixSignal\ntype T2 signal.Signal\n\nfunc f() {\n\t_ = signal.SIGHUP\n\t_ = signal.Incoming\n}\n`,\n\t\tOut: `package main\n\nimport (\n\t_ \"a\"\n\t\"os\"\n\t\"os/signal\"\n\t_ \"z\"\n)\n\ntype T1 os.UnixSignal\ntype T2 os.Signal\n\nfunc f() {\n\t_ = os.SIGHUP\n\t_ = signal.Incoming\n}\n`,\n\t},\n\t{\n\t\tName: \"signal.1\",\n\t\tIn: `package main\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n)\n\nfunc f() {\n\tvar _ os.Error\n\t_ = signal.SIGHUP\n}\n`,\n\t\tOut: `package main\n\nimport \"os\"\n\n\nfunc f() {\n\tvar _ os.Error\n\t_ = os.SIGHUP\n}\n`,\n\t},\n\t{\n\t\tName: \"signal.2\",\n\t\tIn: `package main\n\nimport \"os\"\nimport \"os/signal\"\n\nfunc f() {\n\tvar _ os.Error\n\t_ = signal.SIGHUP\n}\n`,\n\t\tOut: `package main\n\nimport \"os\"\n\n\nfunc f() {\n\tvar _ os.Error\n\t_ = os.SIGHUP\n}\n`,\n\t},\n}\n\nfunc init() ", "output": "{\n\taddTestCases(signalTests)\n}"} {"input": "package informers\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/docker/compose-on-kubernetes/api/compose/v1alpha3\"\n\t\"github.com/docker/compose-on-kubernetes/api/compose/v1beta2\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\n\n\n\nfunc (f *genericInformer) Lister() cache.GenericLister {\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {\n\tswitch resource {\n\tcase v1beta2.SchemeGroupVersion.WithResource(\"stacks\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Compose().V1beta2().Stacks().Informer()}, nil\n\tcase v1alpha3.SchemeGroupVersion.WithResource(\"stacks\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Compose().V1alpha3().Stacks().Informer()}, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer ", "output": "{\n\treturn f.informer\n}"} {"input": "package issue15722\n\ntype T int\ntype P *T\n\nfunc (T) t() {}\n\n\n\nfunc _(p P) ", "output": "{\n\tP.t(p) \n}"} {"input": "package iso20022\n\n\ntype AcceptorCancellationAdvice3 struct {\n\n\tEnvironment *CardPaymentEnvironment24 `xml:\"Envt\"`\n\n\tContext *CardPaymentContext2 `xml:\"Cntxt,omitempty\"`\n\n\tTransaction *CardPaymentTransaction28 `xml:\"Tx\"`\n}\n\nfunc (a *AcceptorCancellationAdvice3) AddEnvironment() *CardPaymentEnvironment24 {\n\ta.Environment = new(CardPaymentEnvironment24)\n\treturn a.Environment\n}\n\n\n\nfunc (a *AcceptorCancellationAdvice3) AddTransaction() *CardPaymentTransaction28 {\n\ta.Transaction = new(CardPaymentTransaction28)\n\treturn a.Transaction\n}\n\nfunc (a *AcceptorCancellationAdvice3) AddContext() *CardPaymentContext2 ", "output": "{\n\ta.Context = new(CardPaymentContext2)\n\treturn a.Context\n}"} {"input": "package testhelpers\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\nfunc Intp(i int) *int {\n\treturn &i\n}\n\n\n\n\n\nfunc MustParseURL(rawURL string) *url.URL {\n\tu, err := url.Parse(rawURL)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to parse URL '%s': %s\", rawURL, err))\n\t}\n\treturn u\n}\n\nfunc MustNewRequest(method, urlStr string, body io.Reader) *http.Request ", "output": "{\n\trequest, err := http.NewRequest(method, urlStr, body)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to create HTTP %s Request for '%s': %s\", method, urlStr, err))\n\t}\n\treturn request\n}"} {"input": "package http\n\nimport (\n\t\"github.com/asim/go-micro/v3/registry\"\n\t\"github.com/asim/go-micro/v3/server\"\n)\n\ntype httpHandler struct {\n\topts server.HandlerOptions\n\teps []*registry.Endpoint\n\thd interface{}\n}\n\nfunc (h *httpHandler) Name() string {\n\treturn \"handler\"\n}\n\nfunc (h *httpHandler) Handler() interface{} {\n\treturn h.hd\n}\n\n\n\nfunc (h *httpHandler) Options() server.HandlerOptions {\n\treturn h.opts\n}\n\nfunc (h *httpHandler) Endpoints() []*registry.Endpoint ", "output": "{\n\treturn h.eps\n}"} {"input": "package core\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/splicers/elastigo/api\"\n)\n\n\n\n\n\ntype MoreLikeThisQuery struct {\n\tMoreLikeThis MLT `json:\"more_like_this\"`\n}\n\ntype MLT struct {\n\tFields []string `json:\"fields\"`\n\tLikeText string `json:\"like_text\"`\n\tPercentTermsToMatch float32 `json:\"percent_terms_to_match\"`\n\tMinTermFrequency int `json:\"min_term_freq\"`\n\tMaxQueryTerms int `json:\"max_query_terms\"`\n\tStopWords []string `json:\"stop_words\"`\n\tMinDocFrequency int `json:\"min_doc_freq\"`\n\tMaxDocFrequency int `json:\"max_doc_freq\"`\n\tMinWordLength int `json:\"min_word_len\"`\n\tMaxWordLength int `json:\"max_word_len\"`\n\tBoostTerms int `json:\"boost_terms\"`\n\tBoost float32 `json:\"boost\"`\n\tAnalyzer string `json:\"analyzer\"`\n}\n\nfunc MoreLikeThis(index string, _type string, id string, args map[string]interface{}, query MoreLikeThisQuery) (api.BaseResponse, error) ", "output": "{\n\tvar url string\n\tvar retval api.BaseResponse\n\turl = fmt.Sprintf(\"/%s/%s/%s/_mlt\", index, _type, id)\n\tbody, err := api.DoCommand(\"GET\", url, args, query)\n\tif err != nil {\n\t\treturn retval, err\n\t}\n\tif err == nil {\n\t\tjsonErr := json.Unmarshal(body, &retval)\n\t\tif jsonErr != nil {\n\t\t\treturn retval, jsonErr\n\t\t}\n\t}\n\treturn retval, err\n}"} {"input": "package iso20022\n\n\ntype FundSettlementParameters3 struct {\n\n\tSettlementDate *ISODate `xml:\"SttlmDt,omitempty\"`\n\n\tSettlementPlace *PartyIdentification2Choice `xml:\"SttlmPlc\"`\n\n\tSafekeepingPlace *PartyIdentification2Choice `xml:\"SfkpgPlc,omitempty\"`\n\n\tSecuritiesSettlementSystemIdentification *Max35Text `xml:\"SctiesSttlmSysId,omitempty\"`\n\n\tReceivingSideDetails *ReceivingPartiesAndAccount3 `xml:\"RcvgSdDtls,omitempty\"`\n\n\tDeliveringSideDetails *DeliveringPartiesAndAccount3 `xml:\"DlvrgSdDtls\"`\n}\n\nfunc (f *FundSettlementParameters3) SetSettlementDate(value string) {\n\tf.SettlementDate = (*ISODate)(&value)\n}\n\nfunc (f *FundSettlementParameters3) AddSettlementPlace() *PartyIdentification2Choice {\n\tf.SettlementPlace = new(PartyIdentification2Choice)\n\treturn f.SettlementPlace\n}\n\n\n\nfunc (f *FundSettlementParameters3) SetSecuritiesSettlementSystemIdentification(value string) {\n\tf.SecuritiesSettlementSystemIdentification = (*Max35Text)(&value)\n}\n\nfunc (f *FundSettlementParameters3) AddReceivingSideDetails() *ReceivingPartiesAndAccount3 {\n\tf.ReceivingSideDetails = new(ReceivingPartiesAndAccount3)\n\treturn f.ReceivingSideDetails\n}\n\nfunc (f *FundSettlementParameters3) AddDeliveringSideDetails() *DeliveringPartiesAndAccount3 {\n\tf.DeliveringSideDetails = new(DeliveringPartiesAndAccount3)\n\treturn f.DeliveringSideDetails\n}\n\nfunc (f *FundSettlementParameters3) AddSafekeepingPlace() *PartyIdentification2Choice ", "output": "{\n\tf.SafekeepingPlace = new(PartyIdentification2Choice)\n\treturn f.SafekeepingPlace\n}"} {"input": "package openpgp\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\ntype recordingHash struct {\n\tbuf *bytes.Buffer\n}\n\nfunc (r recordingHash) Write(b []byte) (n int, err error) {\n\treturn r.buf.Write(b)\n}\n\nfunc (r recordingHash) Sum(in []byte) []byte {\n\treturn append(in, r.buf.Bytes()...)\n}\n\nfunc (r recordingHash) Reset() {\n\tpanic(\"shouldn't be called\")\n}\n\nfunc (r recordingHash) Size() int {\n\tpanic(\"shouldn't be called\")\n}\n\n\n\nfunc testCanonicalText(t *testing.T, input, expected string) {\n\tr := recordingHash{bytes.NewBuffer(nil)}\n\tc := NewCanonicalTextHash(r)\n\tc.Write([]byte(input))\n\tresult := c.Sum(nil)\n\tif expected != string(result) {\n\t\tt.Errorf(\"input: %x got: %x want: %x\", input, result, expected)\n\t}\n}\n\nfunc TestCanonicalText(t *testing.T) {\n\ttestCanonicalText(t, \"foo\\n\", \"foo\\r\\n\")\n\ttestCanonicalText(t, \"foo\", \"foo\")\n\ttestCanonicalText(t, \"foo\\r\\n\", \"foo\\r\\n\")\n\ttestCanonicalText(t, \"foo\\r\\nbar\", \"foo\\r\\nbar\")\n\ttestCanonicalText(t, \"foo\\r\\nbar\\n\\n\", \"foo\\r\\nbar\\r\\n\\r\\n\")\n}\n\nfunc (r recordingHash) BlockSize() int ", "output": "{\n\tpanic(\"shouldn't be called\")\n}"} {"input": "package config\n\nimport (\n\t\"github.com/griesbacher/nagflux/data\"\n\t\"sync\"\n)\n\n\ntype PauseMap map[data.Target]bool\n\n\nvar pauseNagflux = PauseMap{}\n\nvar objMutex = &sync.Mutex{}\n\n\nfunc IsAnyTargetOnPause() bool {\n\tobjMutex.Lock()\n\tresult := false\n\tfor _, v := range pauseNagflux {\n\t\tif v {\n\t\t\tresult = true\n\t\t\tbreak\n\t\t}\n\t}\n\tobjMutex.Unlock()\n\treturn result\n}\n\n\n\nfunc StoreValue(target data.Target, value bool) ", "output": "{\n\tobjMutex.Lock()\n\tpauseNagflux[target] = value\n\tobjMutex.Unlock()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/mailgun/log\"\n\t\"github.com/mailgun/pong/config\"\n\t\"github.com/mailgun/pong/model\"\n\t\"os\"\n\t\"os/signal\"\n)\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"pong\"\n\tapp.Usage = \"Command line tool that generates endpoints with different behavior for testing purposes\"\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{Name: \"c, config\", Usage: \"Yaml file with endpoint specifications\"},\n\t}\n\tapp.Action = startService\n\tapp.Run(os.Args)\n}\n\n\n\nfunc startService(c *cli.Context) ", "output": "{\n\tservers, logConfig, err := config.ParseConfig(c.String(\"config\"))\n\tif err != nil {\n\t\tfmt.Println(\"Failed to load config file '%s' err:\", c.String(\"config\"), err)\n\t\treturn\n\t}\n\tlog.Init(logConfig)\n\tfor _, s := range servers {\n\t\tgo model.StartServer(s)\n\t}\n\tinChan := make(chan os.Signal, 1)\n\tsignal.Notify(inChan, os.Interrupt, os.Kill)\n\tlog.Infof(\"Got signal %s, exiting now\", <-inChan)\n}"} {"input": "package operator\n\nimport (\n\t\"time\"\n\n\t\"go-common/library/log\"\n\txtime \"go-common/library/time\"\n)\n\ntype Reddot struct {\n\tStartTime xtime.Time `json:\"start_time,omitempty\"`\n\tEndTime xtime.Time `json:\"end_time,omitempty\"`\n}\n\n\nfunc (r *Reddot) ReddotChange(startStr, endStr string) {\n\tif startStr != \"\" && endStr != \"\" {\n\t\tr.StartTime = timeStrToInt(startStr)\n\t\tr.EndTime = timeStrToInt(endStr)\n\t}\n}\n\n\n\n\nfunc timeStrToInt(timeStr string) (timeInt xtime.Time) ", "output": "{\n\tvar err error\n\ttimeLayout := \"2006-01-02 15:04:05\"\n\tloc, _ := time.LoadLocation(\"Local\")\n\ttheTime, _ := time.ParseInLocation(timeLayout, timeStr, loc)\n\tif err = timeInt.Scan(theTime); err != nil {\n\t\tlog.Error(\"timeInt.Scan error(%v)\", err)\n\t}\n\treturn\n}"} {"input": "package i3ipc\n\nimport (\n\t\"encoding/json\"\n)\n\n\n\ntype I3Node struct {\n\tID int64\n\tName string\n\tType string\n\tBorder string\n\tCurrentBorderWidth int32 `json:\"current_border_width\"`\n\tLayout string\n\tOrientation string\n\tPercent float64\n\tRect Rect\n\tWindowRect Rect\n\tDecoRect Rect `json:\"deco_rect\"`\n\tGeometry Rect\n\tWindow int32\n\tUrgent bool\n\tFocused bool\n\tFloating_Nodes []I3Node\n\tNodes []I3Node\n\tParent *I3Node\n\n\tWindow_Properties struct {\n\t\tTitle string\n\t\tInstance string\n\t\tClass string\n\t}\n\tSticky bool\n\tFloating string\n\tLast_Split_Layout string\n\tFullscreen_Mode int32\n\tScratchpad_State string\n\tWorkspace_Layout string\n}\n\n\n\n\n\nfunc (socket *IPCSocket) GetTree() (root I3Node, err error) {\n\tjsonReply, err := socket.Raw(I3GetTree, \"\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer setParent(&root, nil)\n\n\terr = json.Unmarshal(jsonReply, &root)\n\tif err == nil {\n\t\treturn\n\t}\n\tif _, ok := err.(*json.UnmarshalTypeError); ok {\n\t\terr = nil\n\t}\n\treturn\n}\n\nfunc setParent(node, parent *I3Node) ", "output": "{\n\n\tnode.Parent = parent\n\n\tfor i := range node.Nodes {\n\t\tsetParent(&node.Nodes[i], node)\n\t}\n\tfor i := range node.Floating_Nodes {\n\t\tsetParent(&node.Floating_Nodes[i], node)\n\t}\n}"} {"input": "package main\n\nimport (\n \"gopkg.in/macaron.v1\"\n \"github.com/go-macaron/binding\"\n\n \"github.com/katuyo/symbol-exchange/controller\"\n \"github.com/katuyo/symbol-exchange/models/req\"\n)\n\n\n\nfunc configRoutes(m *macaron.Macaron)", "output": "{\n\n m.Get(\"/\", func() string {\n\treturn \"Hello world!\"\n });\n\n orderController := new (controller.OrderController);\n m.Post(\"/trade.do\", binding.Bind(req.Order{}), orderController.Exchange);\n m.Post(\"/cancel_order.do\", binding.Bind(req.Withdraw{}), orderController.Cancel);\n\n m.Post(\"/order.exchange\", binding.Bind(req.Order{}), orderController.Exchange);\n m.Post(\"/order.withdraw\", binding.Bind(req.Withdraw{}), orderController.Cancel);\n}"} {"input": "package dbconnpool\n\nimport (\n\t\"github.com/youtube/vitess/go/mysql\"\n\t\"github.com/youtube/vitess/go/stats\"\n)\n\n\ntype PooledDBConnection struct {\n\t*DBConnection\n\tpool *ConnectionPool\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc DBConnectionCreator(info *mysql.ConnectionParams, mysqlStats *stats.Timings) CreateConnectionFunc {\n\treturn func(pool *ConnectionPool) (PoolConnection, error) {\n\t\tc, err := NewDBConnection(info, mysqlStats)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &PooledDBConnection{c, pool}, nil\n\t}\n}\n\nfunc (pc *PooledDBConnection) Recycle() ", "output": "{\n\tif pc.IsClosed() {\n\t\tpc.pool.Put(nil)\n\t} else {\n\t\tpc.pool.Put(pc)\n\t}\n}"} {"input": "package fields\n\nimport (\n\t\"regexp\"\n\t\"time\"\n)\n\nfunc UseDefaultKeyIfCustomKeyIsEmpty(defaultKey, customKey string) string {\n\tif \"\" != customKey {\n\t\treturn customKey\n\t}\n\treturn defaultKey\n}\n\nfunc ExecFuncIfErrIsNotNil(err error, fn func()) (b bool) {\n\tif nil != err {\n\t\tfn()\n\t\tb = true\n\t}\n\treturn\n}\n\nfunc getMessageFromError(err error) string {\n\tif nil == err {\n\t\treturn \"\"\n\t}\n\treturn err.Error()\n}\n\nfunc getPatternFromRegExp(re *regexp.Regexp) string {\n\tif nil == re {\n\t\treturn \"\"\n\t}\n\treturn re.String()\n}\n\n\n\nfunc addSuffix(name string, suffix *string) string {\n\tif nil != suffix {\n\t\treturn name + \"-\" + *suffix\n\t}\n\treturn name\n}\n\nfunc _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) (*time.Location, int) {\n\tif nil == locationByString || \"\" == *locationByString {\n\t\treturn defaultLoc, 1\n\t}\n\n\tif loc, err := time.LoadLocation(*locationByString); nil == err {\n\t\treturn loc, 2\n\t}\n\n\treturn defaultLoc, 0\n}\n\n\nfunc useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) *time.Location {\n\tloc, _ := _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc, locationByString)\n\treturn loc\n}\n\nfunc execFnIfNotNil(fn func()) ", "output": "{\n\tif nil != fn {\n\t\tfn()\n\t}\n}"} {"input": "package main\n\nimport(\n \"fmt\"\n \"strconv\"\n)\n\n\n\n\n\nfunc main() {\n var no_of_process int\n\tfmt.Scan(&no_of_process)\n\tburst_time := []int{}\n\tfor i := 0; i < no_of_process; i++ {\n\t\tvar x int\n\t\tfmt.Scan(&x)\n\t\tburst_time = append(burst_time, x)\n\t}\n\tsolve(no_of_process, burst_time)\n}\n\nfunc solve(no_of_process int, burst_time []int) ", "output": "{\n var wait_time []int\n var turnaround_time []int\n wait_time = append(wait_time, 0) \n \n for i := 1; i <= no_of_process; i++ {\n wait_time = append(wait_time, wait_time[i - 1] + burst_time[i - 1])\n }\n for i := 0; i < no_of_process; i++ {\n turnaround_time = append(turnaround_time, burst_time[i] + wait_time[i])\n }\n for i := 0; i < no_of_process ; i++ {\n fmt.Println(\"Process \" + strconv.Itoa(i + 1) + \" --> (B.T) : \" + strconv.Itoa(burst_time[i]) + \n \" (W.T.) : \" + strconv.Itoa(wait_time[i]) + \" (T.A.T) : \" + strconv.Itoa(turnaround_time[i]))\n }\n}"} {"input": "package utils\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"reflect\"\n\t\"testing\"\n\n\tfv1 \"github.com/fission/fission/pkg/apis/core/v1\"\n)\n\n\n\nfunc TestGetChecksum(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tsrc io.Reader\n\t\twant *fv1.Checksum\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname: \"string case\",\n\t\t\tsrc: bytes.NewReader([]byte(\"foobar hello world\")),\n\t\t\twant: &fv1.Checksum{\n\t\t\t\tType: \"sha256\",\n\t\t\t\tSum: \"99936be1902361c29745aef68bd818f5f08246fc695e2d6e4cc474daf79fed32\",\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"empty reader\",\n\t\t\tsrc: nil,\n\t\t\twant: nil,\n\t\t\twantErr: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot, err := GetChecksum(tt.src)\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"GetChecksum() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(got, tt.want) {\n\t\t\t\tt.Errorf(\"GetChecksum() got = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestIsURL(t *testing.T) ", "output": "{\n\ttests := []struct {\n\t\tname string\n\t\turl string\n\t\twant bool\n\t}{\n\t\t{\"http\", \"http://example.com\", true},\n\t\t{\"https\", \"https://example.com\", true},\n\t\t{\"file\", \"file://example.com\", false},\n\t\t{\"filename\", \"foobar.zip\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := IsURL(tt.url); got != tt.want {\n\t\t\t\tt.Errorf(\"IsURL() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main () {\n\tcounts := make(map[string]int)\n\tfiles := os.Args[1:]\n\n\tif len(files) == 0 {\n\t\tcountLines(os.Stdin, counts)\n\t} else {\n\t\tfor _, arg := range files {\n\t\t\tf, err := os.Open(arg)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"dup2: %v\\n\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcountLines(f, counts)\n\t\t\tf.Close()\n\t\t}\n\t}\n\n\tfor line, n := range counts {\n\t\tif n > 1 {\n\t\t\tfmt.Printf(\"%d\\t%s\\n\", n, line)\n\t\t}\n\t}\n}\n\n\n\nfunc countLines(f *os.File, counts map[string]int) ", "output": "{\n\tinput := bufio.NewScanner(f)\n\tfor input.Scan() {\n\t\tcounts[input.Text()]++\n\t}\n}"} {"input": "package icinga\n\nimport \"strconv\"\n\n\n\nconst _State_name = \"OKWarningCriticalUnknown\"\n\nvar _State_index = [...]uint8{0, 2, 9, 17, 24}\n\nfunc (i State) String() string {\n\tif i < 0 || i >= State(len(_State_index)-1) {\n\t\treturn \"State(\" + strconv.FormatInt(int64(i), 10) + \")\"\n\t}\n\treturn _State_name[_State_index[i]:_State_index[i+1]]\n}\n\nfunc _() ", "output": "{\n\tvar x [1]struct{}\n\t_ = x[OK-0]\n\t_ = x[Warning-1]\n\t_ = x[Critical-2]\n\t_ = x[Unknown-3]\n}"} {"input": "package hijackhelpers\n\nimport (\n\t\"strings\"\n\n\t\"github.com/concourse/atc\"\n)\n\ntype ContainerSorter []atc.Container\n\n\n\nfunc (sorter ContainerSorter) Swap(i, j int) {\n\tsorter[i], sorter[j] = sorter[j], sorter[i]\n}\n\nfunc (sorter ContainerSorter) Less(i, j int) bool {\n\tswitch {\n\tcase sorter[i].BuildID < sorter[j].BuildID:\n\t\treturn true\n\tcase sorter[i].BuildID > sorter[j].BuildID:\n\t\treturn false\n\tcase strings.Compare(sorter[i].ResourceName, sorter[j].ResourceName) == -1:\n\t\treturn true\n\tcase strings.Compare(sorter[i].ResourceName, sorter[j].ResourceName) == 1:\n\t\treturn false\n\tcase strings.Compare(sorter[i].StepName, sorter[j].StepName) == -1:\n\t\treturn true\n\tcase strings.Compare(sorter[i].StepName, sorter[j].StepName) == 1:\n\t\treturn false\n\tcase strings.Compare(sorter[i].Type, sorter[j].Type) == -1:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc (sorter ContainerSorter) Len() int ", "output": "{\n\treturn len(sorter)\n}"} {"input": "package objc\n\nimport \"testing\"\n\nfunc TestIvarGetName(t *testing.T) {\n\tclassName := \"ClassWithIvar\"\n\tclass := Objc_allocateClassPair(nil, className, 0)\n\tivarName := \"ivar\"\n\n\tClass_addIvar(class, ivarName, 4, 0, \"i\")\n\tivar := Class_getInstanceVariable(class, ivarName)\n\n\tif name := Ivar_getName(ivar); name != ivarName {\n\t\tt.Errorf(\"name should be %s: %s\", ivarName, ivar)\n\t}\n}\n\n\n\nfunc TestIvarGetTypeEncoding(t *testing.T) ", "output": "{\n\tclassName := \"ClassWithIvarForEncodingTest\"\n\tivarName := \"ivar\"\n\ttypeEncoding := \"i\"\n\tclass := Objc_allocateClassPair(nil, className, 0)\n\n\tClass_addIvar(class, ivarName, 4, 0, typeEncoding)\n\tivar := Class_getInstanceVariable(class, ivarName)\n\n\tif encoding := Ivar_getTypeEncoding(ivar); encoding != typeEncoding {\n\t\tt.Errorf(\"encoding should be %s: %s\", typeEncoding, encoding)\n\t}\n}"} {"input": "package node\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\n\nfunc (n *Node) String() string ", "output": "{\n\ts := fmt.Sprintf(` \\n\"\n\t}\n\treturn s + \">\\n\" + t + \" \\n\"\n}"} {"input": "package validator\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\nfunc IsNull(str string) bool {\n\treturn len(str) == 0\n}\n\nfunc IsWord(str string, params ...int) bool {\n\tif IsNull(str) {\n\t\treturn false\n\t}\n\treturn rxWord.MatchString(str)\n}\n\nfunc IsTime(str string, format string) bool {\n\t_, err := time.Parse(format, str)\n\treturn err == nil\n}\n\nfunc IsDate(str string, format ...string) bool {\n\n\tif len(format) == 0 {\n\n\t\tif len(strings.Split(str, \"/\")) > 1 {\n\t\t\treturn IsTime(str, \"2006/01/02\")\n\t\t}\n\n\t\tif len(strings.Split(str, \"-\")) > 1 {\n\t\t\treturn IsTime(str, \"2006-01-02\")\n\t\t}\n\n\t\treturn false\n\t}\n\n\treturn IsTime(str, format[0])\n}\n\nfunc IsEmpty(str string) bool {\n\treturn len(strings.TrimSpace(str)) == 0\n}\n\nfunc IsRequestURI(rawurl string) bool {\n\t_, err := url.ParseRequestURI(rawurl)\n\treturn err == nil\n}\n\nfunc IsURI(str string) bool {\n\trelation := false\n\tfor idx, val := range str {\n\t\tif val == '.' {\n\t\t\trelation = true\n\t\t\tcontinue\n\t\t}\n\t\tif val == '/' || val == '\\\\' {\n\t\t\tif idx < len(str)-1 {\n\t\t\t\tif str[idx+1] == '.' {\n\t\t\t\t\trelation = true\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif relation && (val != '/' && val != '\\\\') {\n\t\t\treturn false\n\t\t}\n\t\treturn IsRequestURI(str[idx:])\n\t}\n\treturn false\n}\n\n\n\nfunc IsMobilePhone(str string) bool ", "output": "{\n\tif IsEmpty(str) {\n\t\treturn false\n\t}\n\treturn rxMobolePhone.MatchString(str)\n}"} {"input": "package structs\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"testing\"\n)\n\nfunc TestUnmarshal(t *testing.T) {\n\tin := map[string]string{\n\t\t\"string\": \"a string\",\n\t\t\"integer\": \"-1234\",\n\t\t\"uinteger\": \"1234\",\n\t\t\"bool\": \"true\",\n\t\t\"float\": \"1.234\",\n\t}\n\tvar out struct {\n\t\tString string `cfg:\"string\"`\n\t\tInteger int `cfg:\"integer\"`\n\t\tUinteger uint `cfg:\"uinteger\"`\n\t\tBool bool `cfg:\"bool\"`\n\t\tFloat float64 `cfg:\"float\"`\n\t}\n\n\terr := Unmarshal(in, &out)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif out.String != \"a string\" {\n\t\tt.Errorf(\"unexpected string: %v\", out.String)\n\t}\n\tif out.Integer != -1234 {\n\t\tt.Errorf(\"unexpected integer: %v\", out.Integer)\n\t}\n\tif out.Uinteger != 1234 {\n\t\tt.Errorf(\"unexpected uinteger: %v\", out.Uinteger)\n\t}\n\tif out.Bool != true {\n\t\tt.Errorf(\"unexpected bool: %v\", out.Bool)\n\t}\n\tif math.Abs(out.Float-1.234) > 0.001 {\n\t\tt.Errorf(\"unexpected float: %v\", out.Float)\n\t}\n}\n\n\n\nfunc TestUnmarshalInvalidInt(t *testing.T) {\n\tin := map[string]string{\n\t\t\"integer\": \"abc\",\n\t}\n\tvar out struct {\n\t\tInteger int `cfg:\"integer\"`\n\t}\n\terr := Unmarshal(in, &out)\n\tif err == nil {\n\t\tt.Fatal(\"error expected\")\n\t}\n}\n\nfunc ExampleUnmarshal() ", "output": "{\n\tin := map[string]string{\n\t\t\"name\": \"Foo Bar\",\n\t\t\"age\": \"54\",\n\t\t\"married\": \"true\",\n\t\t\"height\": \"1.75\",\n\t}\n\tvar out struct {\n\t\tName string `cfg:\"name\"`\n\t\tAge int `cfg:\"age\"`\n\t\tMarried bool `cfg:\"married\"`\n\t\tHeight float64 `cfg:\"height\"`\n\t}\n\terr := Unmarshal(in, &out)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"%+v\\n\", out)\n}"} {"input": "package crate\n\n\n\ntype CrateErr struct {\n\tCode int\n\tMessage string\n}\n\n\n\n\nfunc (e *CrateErr) Error() string ", "output": "{\n\treturn e.Message\n}"} {"input": "package storage\n\nimport (\n\t\"context\"\n)\n\n\n\n\nfunc NewTransactionOrDie(ctx context.Context, store Store, params ...TransactionParams) Transaction {\n\ttxn, err := store.NewTransaction(ctx, params...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn txn\n}\n\n\n\n\nfunc ReadOne(ctx context.Context, store Store, path Path) (interface{}, error) {\n\ttxn, err := store.NewTransaction(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer store.Abort(ctx, txn)\n\n\treturn store.Read(ctx, txn, path)\n}\n\n\n\n\n\n\n\n\n\n\nfunc Txn(ctx context.Context, store Store, params TransactionParams, f func(Transaction) error) error {\n\n\ttxn, err := store.NewTransaction(ctx, params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := f(txn); err != nil {\n\t\tstore.Abort(ctx, txn)\n\t\treturn err\n\t}\n\n\treturn store.Commit(ctx, txn)\n}\n\nfunc WriteOne(ctx context.Context, store Store, op PatchOp, path Path, value interface{}) error ", "output": "{\n\ttxn, err := store.NewTransaction(ctx, WriteParams)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := store.Write(ctx, txn, op, path, value); err != nil {\n\t\tstore.Abort(ctx, txn)\n\t\treturn err\n\t}\n\n\treturn store.Commit(ctx, txn)\n}"} {"input": "package cluster\n\nimport (\n\t\"github.com/hashicorp/nomad/api\"\n\t\"github.com/jippi/hashi-ui/backend/structs\"\n)\n\nconst (\n\tReconsileSummaries = \"NOMAD_RECONCILE_SYSTEM\"\n)\n\ntype reconsileSummaries struct {\n\taction structs.Action\n\tclient *api.Client\n}\n\nfunc NewReconsileSummaries(action structs.Action, client *api.Client) *reconsileSummaries {\n\treturn &reconsileSummaries{\n\t\taction: action,\n\t\tclient: client,\n\t}\n}\n\n\n\nfunc (w *reconsileSummaries) Key() string {\n\treturn \"/system/reconsile_summaries\"\n}\n\nfunc (w *reconsileSummaries) IsMutable() bool {\n\treturn true\n}\n\nfunc (w *reconsileSummaries) BackendType() string {\n\treturn \"nomad\"\n}\n\nfunc (w *reconsileSummaries) Do() (structs.Response, error) ", "output": "{\n\terr := w.client.System().ReconcileSummaries()\n\tif err != nil {\n\t\treturn structs.NewErrorResponse(err)\n\t}\n\n\treturn structs.NewSuccessResponse(\"Successfully reconsiled summaries\")\n}"} {"input": "package main\n\nimport \"fmt\"\n\ntype QU struct {\n\tid []int\n}\n\nfunc (q *QU) Init(size int) {\n\tfor i := 0; i < size; i++ {\n\t\tq.id = append(q.id, i)\n\t}\n}\n\n\n\nfunc (q *QU) Union(a int, b int) {\n\ti := q.Root(a)\n\tj := q.Root(b)\n\tq.id[i] = j\n}\n\nfunc (q *QU) Connected(a int, b int) bool {\n\treturn q.Root(a) == q.Root(b)\n}\n\nfunc main() {\n\tqu := QU{}\n\tqu.Init(10)\n\tfmt.Printf(\"Array initialized. %v\", qu.id)\n\tqu.Union(3, 4)\n\tqu.Union(4, 8)\n\tfmt.Printf(\"\\n\\n%v is Connected to %v %v\", 3, 8, qu.Connected(3, 8))\n}\n\nfunc (q *QU) Root(i int) int ", "output": "{\n\tfor i != q.id[i] {\n\t\ti = q.id[i]\n\t}\n\treturn i\n}"} {"input": "package sw\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\n\t\"github.com/hyperledger/fabric/core/crypto/bccsp\"\n\t\"github.com/hyperledger/fabric/core/crypto/primitives\"\n)\n\ntype rsaPrivateKey struct {\n\tk *rsa.PrivateKey\n}\n\n\n\nfunc (k *rsaPrivateKey) Bytes() (raw []byte, err error) {\n\treturn\n}\n\n\nfunc (k *rsaPrivateKey) SKI() (ski []byte) {\n\traw := x509.MarshalPKCS1PrivateKey(k.k)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\nfunc (k *rsaPrivateKey) Symmetric() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPrivateKey) Private() bool {\n\treturn true\n}\n\n\n\nfunc (k *rsaPrivateKey) PublicKey() (bccsp.Key, error) {\n\treturn &rsaPublicKey{&k.k.PublicKey}, nil\n}\n\ntype rsaPublicKey struct {\n\tk *rsa.PublicKey\n}\n\n\n\nfunc (k *rsaPublicKey) Bytes() (raw []byte, err error) {\n\traw, err = x509.MarshalPKIXPublicKey(k.k)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed marshalling key [%s]\", err)\n\t}\n\treturn\n}\n\n\n\n\n\n\nfunc (k *rsaPublicKey) Symmetric() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) Private() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) PublicKey() (bccsp.Key, error) {\n\treturn k, nil\n}\n\nfunc (k *rsaPublicKey) SKI() (ski []byte) ", "output": "{\n\traw, _ := primitives.PublicKeyToPEM(k.k, nil)\n\n\treturn primitives.Hash(raw)\n}"} {"input": "package lb\n\nimport (\n\t\"database/sql\"\n\t\"testing\"\n\n\t_ \"github.com/lib/pq\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestDBPortAllocator_Get(t *testing.T) {\n\tdb := newDB(t)\n\ta := &DBPortAllocator{\n\t\tdb: db,\n\t}\n\n\tport, err := a.Get()\n\tassert.NoError(t, err)\n\tassert.NotEqual(t, 0, port)\n\n\terr = a.Put(port)\n\tassert.NoError(t, err)\n}\n\n\n\nfunc newDB(t testing.TB) *sql.DB ", "output": "{\n\tdb, err := sql.Open(\"postgres\", \"postgres://localhost/empire?sslmode=disable\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn db\n}"} {"input": "package epi\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\n\n\n\nfunc TestGoParity(t *testing.T) {\n\tassert.Equal(t, 0, parity(3))\n\tassert.Equal(t, 1, parity(1))\n}\n\nfunc parity(n uint64) int ", "output": "{\n\tcount := 0\n\tfor i := 0; i < 64; i++ {\n\t\tif (n & (1 << uint64(i))) > 0 {\n\t\t\tcount++\n\t\t}\n\t}\n\tif count%2 == 0 {\n\t\treturn 0\n\t}\n\treturn 1\n}"} {"input": "package processors\n\nimport (\n\t\"context\"\n\n\t\"github.com/cloudevents/sdk-go/v2/event\"\n)\n\n\n\n\n\ntype Interface interface {\n\tProcess(ctx context.Context, e *event.Event) error\n\tNext() Interface\n}\n\n\ntype ChainableProcessor interface {\n\tInterface\n\n\tWithNext(ChainableProcessor) ChainableProcessor\n}\n\n\n\n\ntype BaseProcessor struct {\n\tn ChainableProcessor\n}\n\n\n\n\nfunc (p *BaseProcessor) Next() Interface {\n\tif p.n == nil {\n\t\treturn noop\n\t}\n\treturn p.n\n}\n\n\nfunc (p *BaseProcessor) WithNext(n ChainableProcessor) ChainableProcessor {\n\tp.n = n\n\treturn p.n\n}\n\n\n\n\nvar noop = &noOpProcessor{}\n\ntype noOpProcessor struct{}\n\nfunc (p noOpProcessor) Process(_ context.Context, _ *event.Event) error {\n\treturn nil\n}\n\n\n\nfunc (p noOpProcessor) Next() Interface {\n\treturn nil\n}\n\nfunc ChainProcessors(first ChainableProcessor, rest ...ChainableProcessor) Interface ", "output": "{\n\tnext := first\n\tfor _, p := range rest {\n\t\tnext = next.WithNext(p)\n\t}\n\treturn first\n}"} {"input": "package checkers\n\nimport (\n\t\"errors\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/jkomoros/boardgame\"\n\t\"github.com/jkomoros/boardgame/base\"\n\t\"github.com/jkomoros/boardgame/moves\"\n)\n\n\n\n\ntype gameDelegate struct {\n\tbase.GameDelegate\n}\n\nvar memoizedDelegateName string\n\nfunc (g *gameDelegate) Name() string {\n\n\n\tif memoizedDelegateName == \"\" {\n\t\tpkgPath := reflect.ValueOf(g).Elem().Type().PkgPath()\n\t\tpathPieces := strings.Split(pkgPath, \"/\")\n\t\tmemoizedDelegateName = pathPieces[len(pathPieces)-1]\n\t}\n\treturn memoizedDelegateName\n}\n\n\n\nfunc (g *gameDelegate) GameStateConstructor() boardgame.ConfigurableSubState {\n\treturn new(gameState)\n}\n\nfunc (g *gameDelegate) PlayerStateConstructor(index boardgame.PlayerIndex) boardgame.ConfigurableSubState {\n\treturn new(playerState)\n}\n\nfunc (g *gameDelegate) DistributeComponentToStarterStack(state boardgame.ImmutableState, c boardgame.Component) (boardgame.ImmutableStack, error) {\n\n\treturn nil, errors.New(\"Not yet implemented\")\n\n}\n\n\n\nfunc NewDelegate() boardgame.GameDelegate {\n\treturn &gameDelegate{}\n}\n\nfunc (g *gameDelegate) ConfigureMoves() []boardgame.MoveConfig ", "output": "{\n\n\tauto := moves.NewAutoConfigurer(g)\n\n\treturn moves.Combine(\n\n\t\tmoves.Add(\n\t\t\tauto.MustConfig(new(moves.NoOp),\n\t\t\t\tmoves.WithMoveName(\"Example No Op Move\"),\n\t\t\t\tmoves.WithHelpText(\"This move is an example that is always legal and does nothing. It exists to show how to return moves and make sure 'go test' works from the beginning, but you should remove it.\"),\n\t\t\t),\n\t\t),\n\t)\n\n}"} {"input": "package main\n\nimport (\n\t\"github.com/ginuerzh/gosocks5\"\n\t\"github.com/gorilla/websocket\"\n\t\"log\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype WSConn struct {\n\t*websocket.Conn\n\trb []byte\n}\n\n\n\nfunc (conn *WSConn) Read(b []byte) (n int, err error) {\n\tif len(conn.rb) == 0 {\n\t\t_, conn.rb, err = conn.ReadMessage()\n\t}\n\tn = copy(b, conn.rb)\n\tconn.rb = conn.rb[n:]\n\n\n\treturn\n}\n\nfunc (conn *WSConn) Write(b []byte) (n int, err error) {\n\terr = conn.WriteMessage(websocket.BinaryMessage, b)\n\tn = len(b)\n\n\treturn\n}\n\nfunc (conn *WSConn) SetDeadline(t time.Time) error {\n\tif err := conn.SetReadDeadline(t); err != nil {\n\t\treturn err\n\t}\n\treturn conn.SetWriteDeadline(t)\n}\n\ntype WSServer struct {\n\tAddr string\n}\n\nvar upgrader = websocket.Upgrader{\n\tReadBufferSize: 8192,\n\tWriteBufferSize: 8192,\n\tCheckOrigin: func(r *http.Request) bool { return true },\n}\n\nfunc (s *WSServer) handle(w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tc := gosocks5.ServerConn(NewWSConn(conn), serverConfig)\n\tsocks5Handle(c)\n}\n\nfunc (s *WSServer) ListenAndServe() error {\n\thttp.HandleFunc(\"/\", s.handle)\n\treturn http.ListenAndServe(s.Addr, nil)\n}\n\nfunc NewWSConn(conn *websocket.Conn) *WSConn ", "output": "{\n\tc := &WSConn{\n\t\tConn: conn,\n\t}\n\n\treturn c\n}"} {"input": "package directory\n\nimport (\n\t\"github.com/corestoreio/csfw/config\"\n\t\"github.com/corestoreio/csfw/config/model\"\n\t\"github.com/corestoreio/csfw/store/scope\"\n\t\"github.com/juju/errgo\"\n\t\"golang.org/x/text/currency\"\n)\n\n\ntype ConfigCurrency struct {\n\tmodel.Str\n}\n\n\nfunc NewConfigCurrency(path string, opts ...model.Option) ConfigCurrency {\n\treturn ConfigCurrency{\n\t\tStr: model.NewStr(path, opts...),\n\t}\n}\n\n\n\n\n\nfunc (p ConfigCurrency) Write(w config.Writer, v Currency, s scope.Scope, id int64) error {\n\treturn p.Str.Write(w, v.String(), s, id)\n}\n\nfunc (p ConfigCurrency) Get(sg config.ScopedGetter) (Currency, error) ", "output": "{\n\tcur := p.Str.Get(sg)\n\tu, err := currency.ParseISO(cur)\n\tif err != nil {\n\t\treturn Currency{}, errgo.Mask(err)\n\t}\n\treturn Currency{Unit: u}, nil\n}"} {"input": "package probe_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/minio/mc/pkg/probe\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype MySuite struct{}\n\nvar _ = Suite(&MySuite{})\n\nfunc testDummy0() *probe.Error {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\treturn probe.NewError(e)\n}\n\nfunc testDummy1() *probe.Error {\n\treturn testDummy0().Trace(\"DummyTag1\")\n}\n\n\n\nfunc (s *MySuite) TestProbe(c *C) {\n\tprobe.Init() \n\tprobe.SetAppInfo(\"Commit-ID\", \"7390cc957239\")\n\tes := testDummy2().Trace(\"TopOfStack\")\n\tc.Assert(es, Not(Equals), nil)\n\n\tnewES := es.Trace()\n\tc.Assert(newES, Not(Equals), nil)\n}\n\nfunc (s *MySuite) TestWrappedError(c *C) {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\tes := probe.NewError(e) \n\te = probe.WrapError(es) \n\t_, ok := probe.UnwrapError(e)\n\tc.Assert(ok, Equals, true)\n}\n\nfunc testDummy2() *probe.Error ", "output": "{\n\treturn testDummy1().Trace(\"DummyTag2\")\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/astaxie/beego\"\n\t\"github.com/RayFantasyStudio/blog/models\"\n\t\"fmt\"\n)\n\nvar owner string\n\nfunc init() {\n\towner = beego.AppConfig.String(\"owner\")\n}\n\nfunc initHeaderFooterData(c *beego.Controller, title string) (user *models.User, err error) {\n\tc.Data[\"Owner\"] = owner\n\n\tc.Data[\"Title\"] = title\n\n\tif token := c.Ctx.GetCookie(\"token\"); len(token) != 0 {\n\t\tif user, err = models.GetUserByToken(token); err != nil {\n\t\t\tbeego.Error(err)\n\t\t} else {\n\t\t\tc.Data[\"IsLogin\"] = true\n\t\t\tc.Data[\"User\"] = user\n\t\t\tvar avatar_path string\n\t\t\tavatar_path, err = models.GetUserAvatar(int64(user.Id))\n\t\t\tc.Data[\"avatar_path\"] = avatar_path\n\t\t\tbeego.Info(avatar_path)\n\t\t}\n\t}\n\n\tflash := beego.ReadFromRequest(c)\n\tif n, ok := flash.Data[\"notice\"]; ok {\n\t\tc.Data[\"Message\"] = n\n\t}\n\treturn\n}\n\n\n\nfunc NewNoticeFlash(c *beego.Controller, msg string, args ...interface{}) ", "output": "{\n\tvar data string\n\tif len(args) == 0 {\n\t\tdata = msg\n\t} else {\n\t\tdata = fmt.Sprintf(msg, args...)\n\t}\n\tflash := beego.NewFlash()\n\tflash.Notice(data)\n\tflash.Store(c)\n}"} {"input": "package protolog \n\nimport (\n\t\"os\"\n\n\t\"go.pedge.io/dlog\"\n\t\"go.pedge.io/protolog\"\n)\n\nfunc init() {\n\tdlog.SetLogger(NewLogger(protolog.NewStandardLogger(protolog.NewFileFlusher(os.Stderr))))\n}\n\ntype logger struct {\n\tprotolog.Logger\n}\n\n\nfunc NewLogger(l protolog.Logger) dlog.Logger {\n\treturn &logger{l}\n}\n\nfunc (l *logger) Debug(args ...interface{}) {\n\tl.Debugln(args...)\n}\n\nfunc (l *logger) Info(args ...interface{}) {\n\tl.Infoln(args...)\n}\n\nfunc (l *logger) Warn(args ...interface{}) {\n\tl.Warnln(args...)\n}\n\nfunc (l *logger) Error(args ...interface{}) {\n\tl.Errorln(args...)\n}\n\nfunc (l *logger) Fatal(args ...interface{}) {\n\tl.Fatalln(args...)\n}\n\n\n\nfunc (l *logger) Print(args ...interface{}) {\n\tl.Println(args...)\n}\n\nfunc (l *logger) Panic(args ...interface{}) ", "output": "{\n\tl.Panicln(args...)\n}"} {"input": "package e2e\n\nimport (\n\t\"testing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\n\n\n\nfunc Test(t *testing.T) ", "output": "{ TestingT(t) }"} {"input": "package util\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestGetSortedKeys(t *testing.T) {\n\tmapKeyValue := make(map[string]int)\n\tmapKeyValue[\"blue\"] = 10\n\tmapKeyValue[\"apple\"] = 15\n\tmapKeyValue[\"red\"] = 12\n\tmapKeyValue[\"123\"] = 22\n\tmapKeyValue[\"a\"] = 33\n\tmapKeyValue[\"\"] = 30\n\tassert.Equal(t, []string{\"\", \"123\", \"a\", \"apple\", \"blue\", \"red\"}, GetSortedKeys(mapKeyValue))\n}\n\n\n\nfunc TestGetValuesBySortedKeys(t *testing.T) ", "output": "{\n\ttype name struct {\n\t\tfName string\n\t\tlName string\n\t}\n\tmapKeyValue := make(map[string]*name)\n\tmapKeyValue[\"2\"] = &name{\"Two\", \"two\"}\n\tmapKeyValue[\"3\"] = &name{\"Three\", \"three\"}\n\tmapKeyValue[\"5\"] = &name{\"Five\", \"five\"}\n\tmapKeyValue[\"\"] = &name{\"None\", \"none\"}\n\n\tsortedRes := []*name{}\n\tGetValuesBySortedKeys(&mapKeyValue, &sortedRes)\n\tassert.Equal(\n\t\tt,\n\t\t[]*name{&name{\"None\", \"none\"}, &name{\"Two\", \"two\"}, &name{\"Three\", \"three\"}, &name{\"Five\", \"five\"}},\n\t\tsortedRes,\n\t)\n}"} {"input": "package api\n\nimport \"testing\"\n\nfunc assertQueryMeta(t *testing.T, qm *QueryMeta) {\n\tif qm.LastIndex == 0 {\n\t\tt.Fatalf(\"bad index: %d\", qm.LastIndex)\n\t}\n\tif !qm.KnownLeader {\n\t\tt.Fatalf(\"expected known leader, got none\")\n\t}\n}\n\nfunc assertWriteMeta(t *testing.T, wm *WriteMeta) {\n\tif wm.LastIndex == 0 {\n\t\tt.Fatalf(\"bad index: %d\", wm.LastIndex)\n\t}\n}\n\n\n\nfunc testPeriodicJob() *Job {\n\tjob := testJob().AddPeriodicConfig(&PeriodicConfig{\n\t\tEnabled: true,\n\t\tSpec: \"*/30 * * * *\",\n\t\tSpecType: \"cron\",\n\t})\n\treturn job\n}\n\nfunc testJob() *Job ", "output": "{\n\ttask := NewTask(\"task1\", \"exec\").\n\t\tSetConfig(\"command\", \"/bin/sleep\").\n\t\tRequire(&Resources{\n\t\t\tCPU: 100,\n\t\t\tMemoryMB: 256,\n\t\t\tIOPS: 10,\n\t\t}).\n\t\tSetLogConfig(&LogConfig{\n\t\t\tMaxFiles: 1,\n\t\t\tMaxFileSizeMB: 2,\n\t\t})\n\n\tgroup := NewTaskGroup(\"group1\", 1).\n\t\tAddTask(task).\n\t\tRequireDisk(&EphemeralDisk{\n\t\t\tSizeMB: 25,\n\t\t})\n\n\tjob := NewBatchJob(\"job1\", \"redis\", \"region1\", 1).\n\t\tAddDatacenter(\"dc1\").\n\t\tAddTaskGroup(group)\n\n\treturn job\n}"} {"input": "package transactions\n\nimport \"github.com/joshheinrichs/httperr\"\n\nfunc AddAdmin(requesterID, userID string) httperr.Error {\n\treturn ErrNotImplemented\n}\n\n\n\nfunc RemoveAdmin(requesterID, userID string) httperr.Error {\n\treturn ErrNotImplemented\n}\n\nfunc IsAdmin(userID string) (bool, httperr.Error) ", "output": "{\n\treturn false, ErrNotImplemented\n}"} {"input": "package model\n\nimport (\n\t\"go-common/app/service/main/archive/model/archive\"\n)\n\n\ntype ArcToView struct {\n\t*archive.Archive3\n\tPage *archive.Page3 `json:\"page,omitempty\"`\n\tCount int `json:\"count\"`\n\tCid int64 `json:\"cid\"`\n\tProgress int64 `json:\"progress\"`\n\tAddTime int64 `json:\"add_at\"`\n}\n\n\ntype WebArcToView struct {\n\t*archive.View3\n\tBangumiInfo *Bangumi `json:\"bangumi,omitempty\"`\n\tCid int64 `json:\"cid\"`\n\tProgress int64 `json:\"progress\"`\n\tAddTime int64 `json:\"add_at\"`\n}\n\n\ntype ToView struct {\n\tAid int64 `json:\"aid,omitempty\"`\n\tUnix int64 `json:\"now,omitempty\"`\n}\n\n\ntype ToViews []*ToView\n\n\nfunc (h ToViews) Less(i, j int) bool { return h[i].Unix > h[j].Unix }\nfunc (h ToViews) Swap(i, j int) { h[i], h[j] = h[j], h[i] }\n\nfunc (h ToViews) Len() int ", "output": "{ return len(h) }"} {"input": "package models\n\n\n\n\nimport (\n\t\"github.com/go-swagger/go-swagger/errors\"\n\t\"github.com/go-swagger/go-swagger/strfmt\"\n\t\"github.com/go-swagger/go-swagger/swag\"\n)\n\n\ntype TopicPageableResult struct {\n\n\tContent []Topic `json:\"content,omitempty\"`\n\n\tFirst bool `json:\"first,omitempty\"`\n\n\tLast bool `json:\"last,omitempty\"`\n\n\tNumber int32 `json:\"number,omitempty\"`\n\n\tNumberOfElements int32 `json:\"numberOfElements,omitempty\"`\n\n\tServerTime int64 `json:\"serverTime,omitempty\"`\n\n\tSize int32 `json:\"size,omitempty\"`\n\n\tTotalElements int32 `json:\"totalElements,omitempty\"`\n\n\tTotalPages int32 `json:\"totalPages,omitempty\"`\n}\n\n\n\n\nfunc (m *TopicPageableResult) validateContent(formats strfmt.Registry) error {\n\n\tif swag.IsZero(m.Content) { \n\t\treturn nil\n\t}\n\n\tfor i := 0; i < len(m.Content); i++ {\n\n\t\tif err := m.Content[i].Validate(formats); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nfunc (m *TopicPageableResult) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateContent(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package concurrency\n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\n\nfunc PlusOne(ctx context.Context, in <-chan int) <-chan int {\n\tout := make(chan int)\n\tgo func() {\n\t\tdefer close(out)\n\t\tfor num := range in {\n\t\t\tselect {\n\t\t\tcase out <- num + 1:\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn out\n}\n\ntype IntPipe func(context.Context, <-chan int) <-chan int\n\nfunc Chain(ps ...IntPipe) IntPipe {\n\treturn func(ctx context.Context, in <-chan int) <-chan int {\n\t\tc := in\n\t\tfor _, p := range ps {\n\t\t\tc = p(ctx, c)\n\t\t}\n\t\treturn c\n\t}\n}\n\nvar PlusTwo = Chain(PlusOne, PlusOne)\n\nfunc FanIn(ins ...<-chan int) <-chan int {\n\tout := make(chan int)\n\tvar wg sync.WaitGroup\n\twg.Add(len(ins))\n\tfor _, in := range ins {\n\t\tgo func(in <-chan int) {\n\t\t\tdefer wg.Done()\n\t\t\tfor num := range in {\n\t\t\t\tout <- num\n\t\t\t}\n\t\t}(in)\n\t}\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(out)\n\t}()\n\treturn out\n}\n\nfunc Distribute(p IntPipe, n int) IntPipe {\n\treturn func(ctx context.Context, in <-chan int) <-chan int {\n\t\tcs := make([]<-chan int, n)\n\t\tfor i := 0; i < n; i++ {\n\t\t\tcs[i] = p(ctx, in)\n\t\t}\n\t\treturn FanIn(cs...)\n\t}\n}\n\n\n\nfunc FanIn3(in1, in2, in3 <-chan int) <-chan int ", "output": "{\n\tout := make(chan int)\n\topenCnt := 3\n\tcloseChan := func(c *<-chan int) bool {\n\t\t*c = nil\n\t\topenCnt--\n\t\treturn openCnt == 0\n\t}\n\tgo func() {\n\t\tdefer close(out)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase n, ok := <-in1:\n\t\t\t\tif ok {\n\t\t\t\t\tout <- n\n\t\t\t\t} else if closeChan(&in1) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase n, ok := <-in2:\n\t\t\t\tif ok {\n\t\t\t\t\tout <- n\n\t\t\t\t} else if closeChan(&in2) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase n, ok := <-in3:\n\t\t\t\tif ok {\n\t\t\t\t\tout <- n\n\t\t\t\t} else if closeChan(&in3) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn out\n\n}"} {"input": "package request\n\nimport (\n\t\"time\"\n\n\t\"github.com/YakLabs/kube-cloudwatch-node-metrics/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/YakLabs/kube-cloudwatch-node-metrics/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr\"\n)\n\n\n\n\ntype Retryer interface {\n\tRetryRules(*Request) time.Duration\n\tShouldRetry(*Request) bool\n\tMaxRetries() int\n}\n\n\n\nfunc WithRetryer(cfg *aws.Config, retryer Retryer) *aws.Config {\n\tcfg.Retryer = retryer\n\treturn cfg\n}\n\n\n\nvar retryableCodes = map[string]struct{}{\n\t\"RequestError\": {},\n\t\"RequestTimeout\": {},\n\t\"ProvisionedThroughputExceededException\": {},\n\t\"Throttling\": {},\n\t\"ThrottlingException\": {},\n\t\"RequestLimitExceeded\": {},\n\t\"RequestThrottled\": {},\n\t\"LimitExceededException\": {}, \n\t\"TooManyRequestsException\": {}, \n}\n\n\n\n\nvar credsExpiredCodes = map[string]struct{}{\n\t\"ExpiredToken\": {},\n\t\"ExpiredTokenException\": {},\n\t\"RequestExpired\": {}, \n}\n\nfunc isCodeRetryable(code string) bool {\n\tif _, ok := retryableCodes[code]; ok {\n\t\treturn true\n\t}\n\n\treturn isCodeExpiredCreds(code)\n}\n\nfunc isCodeExpiredCreds(code string) bool {\n\t_, ok := credsExpiredCodes[code]\n\treturn ok\n}\n\n\n\n\n\n\n\nfunc (r *Request) IsErrorExpired() bool {\n\tif r.Error != nil {\n\t\tif err, ok := r.Error.(awserr.Error); ok {\n\t\t\treturn isCodeExpiredCreds(err.Code())\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (r *Request) IsErrorRetryable() bool ", "output": "{\n\tif r.Error != nil {\n\t\tif err, ok := r.Error.(awserr.Error); ok {\n\t\t\treturn isCodeRetryable(err.Code())\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package poly1305\n\n\n\n\n\n\nfunc Sum(out *[TagSize]byte, msg []byte, key *[32]byte) ", "output": "{\n\th := newMAC(key)\n\th.Write(msg)\n\th.Sum(out)\n}"} {"input": "package overcurrent\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\ntype (\n\tNoopBreaker struct{}\n\n\tNoopCollector struct{}\n)\n\nvar defaultCollector = NewNoopCollector()\n\n\nfunc NewNoopBreaker() CircuitBreaker {\n\treturn &NoopBreaker{}\n}\n\nfunc (b *NoopBreaker) Trip() {}\nfunc (b *NoopBreaker) Reset() {}\nfunc (b *NoopBreaker) ShouldTry() bool { return true }\nfunc (b *NoopBreaker) MarkResult(err error) bool { return true }\nfunc (b *NoopBreaker) Call(f BreakerFunc) error { return f(context.Background()) }\nfunc (b *NoopBreaker) CallAsync(f BreakerFunc) <-chan error { return nil }\n\n\n\n\nfunc (c *NoopCollector) ReportNew(BreakerConfig) {}\nfunc (c *NoopCollector) ReportCount(EventType) {}\nfunc (c *NoopCollector) ReportDuration(EventType, time.Duration) {}\nfunc (c *NoopCollector) ReportState(CircuitState) {}\n\nfunc NewNoopCollector() MetricCollector ", "output": "{\n\treturn &NoopCollector{}\n}"} {"input": "package versioned\n\nimport (\n\toauthv1 \"github.com/openshift/client-go/oauth/clientset/versioned/typed/oauth/v1\"\n\tdiscovery \"k8s.io/client-go/discovery\"\n\trest \"k8s.io/client-go/rest\"\n\tflowcontrol \"k8s.io/client-go/util/flowcontrol\"\n)\n\ntype Interface interface {\n\tDiscovery() discovery.DiscoveryInterface\n\tOauthV1() oauthv1.OauthV1Interface\n}\n\n\n\ntype Clientset struct {\n\t*discovery.DiscoveryClient\n\toauthV1 *oauthv1.OauthV1Client\n}\n\n\nfunc (c *Clientset) OauthV1() oauthv1.OauthV1Interface {\n\treturn c.oauthV1\n}\n\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.DiscoveryClient\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *Clientset {\n\tvar cs Clientset\n\tcs.oauthV1 = oauthv1.NewForConfigOrDie(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)\n\treturn &cs\n}\n\n\nfunc New(c rest.Interface) *Clientset {\n\tvar cs Clientset\n\tcs.oauthV1 = oauthv1.New(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClient(c)\n\treturn &cs\n}\n\nfunc NewForConfig(c *rest.Config) (*Clientset, error) ", "output": "{\n\tconfigShallowCopy := *c\n\tif configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {\n\t\tconfigShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)\n\t}\n\tvar cs Clientset\n\tvar err error\n\tcs.oauthV1, err = oauthv1.NewForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &cs, nil\n}"} {"input": "package addrs\n\nimport \"fmt\"\n\n\n\n\n\n\n\n\n\n\n\ntype ResourceInstancePhase struct {\n\treferenceable\n\tResourceInstance ResourceInstance\n\tPhase ResourceInstancePhaseType\n}\n\nvar _ Referenceable = ResourceInstancePhase{}\n\n\n\n\nfunc (r ResourceInstance) Phase(rpt ResourceInstancePhaseType) ResourceInstancePhase {\n\treturn ResourceInstancePhase{\n\t\tResourceInstance: r,\n\t\tPhase: rpt,\n\t}\n}\n\n\n\n\n\nfunc (rp ResourceInstancePhase) String() string {\n\treturn fmt.Sprintf(\"%s#%s\", rp.ResourceInstance, rp.Phase)\n}\n\n\ntype ResourceInstancePhaseType string\n\nconst (\n\tResourceInstancePhaseDestroy ResourceInstancePhaseType = \"destroy\"\n\n\tResourceInstancePhaseDestroyCBD ResourceInstancePhaseType = \"destroy-cbd\"\n)\n\nfunc (rpt ResourceInstancePhaseType) String() string {\n\treturn string(rpt)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype ResourcePhase struct {\n\treferenceable\n\tResource Resource\n\tPhase ResourceInstancePhaseType\n}\n\nvar _ Referenceable = ResourcePhase{}\n\n\n\n\nfunc (r Resource) Phase(rpt ResourceInstancePhaseType) ResourcePhase {\n\treturn ResourcePhase{\n\t\tResource: r,\n\t\tPhase: rpt,\n\t}\n}\n\nfunc (rp ResourcePhase) String() string {\n\treturn fmt.Sprintf(\"%s#%s\", rp.Resource, rp.Phase)\n}\n\nfunc (rp ResourceInstancePhase) ContainingResource() ResourcePhase ", "output": "{\n\treturn rp.ResourceInstance.Resource.Phase(rp.Phase)\n}"} {"input": "package protolog \n\nimport (\n\t\"os\"\n\n\t\"go.pedge.io/dlog\"\n\t\"go.pedge.io/protolog\"\n)\n\nfunc init() {\n\tdlog.SetLogger(NewLogger(protolog.NewStandardLogger(protolog.NewFileFlusher(os.Stderr))))\n}\n\ntype logger struct {\n\tprotolog.Logger\n}\n\n\nfunc NewLogger(l protolog.Logger) dlog.Logger {\n\treturn &logger{l}\n}\n\n\n\nfunc (l *logger) Info(args ...interface{}) {\n\tl.Infoln(args...)\n}\n\nfunc (l *logger) Warn(args ...interface{}) {\n\tl.Warnln(args...)\n}\n\nfunc (l *logger) Error(args ...interface{}) {\n\tl.Errorln(args...)\n}\n\nfunc (l *logger) Fatal(args ...interface{}) {\n\tl.Fatalln(args...)\n}\n\nfunc (l *logger) Panic(args ...interface{}) {\n\tl.Panicln(args...)\n}\n\nfunc (l *logger) Print(args ...interface{}) {\n\tl.Println(args...)\n}\n\nfunc (l *logger) Debug(args ...interface{}) ", "output": "{\n\tl.Debugln(args...)\n}"} {"input": "package message\n\nimport \"github.com/cloustone/sentel/pkg/config\"\n\ntype Producer interface {\n\tSendMessage(msg Message) error\n\tSendMessages(msgs []Message) error\n\tClose()\n}\n\nfunc NewProducer(c config.Config, clientID string, sync bool) (Producer, error) {\n\treturn newKafkaProducer(c, clientID, sync)\n}\n\nfunc PostMessage(c config.Config, msg Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", false); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessage(msg)\n\t}\n\treturn\n}\n\n\n\nfunc SendMessage(c config.Config, msg Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", true); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessage(msg)\n\t}\n\treturn\n}\n\nfunc SendMessages(c config.Config, msgs []Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", true); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessages(msgs)\n\t}\n\treturn\n}\n\nfunc PostMessages(c config.Config, msgs []Message) (err error) ", "output": "{\n\tif producer, err := NewProducer(c, \"\", false); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessages(msgs)\n\t}\n\treturn\n}"} {"input": "package authentication\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/piot/hasty-protocol/user\"\n)\n\n\ntype Info struct {\n\tuserID user.ID\n}\n\n\n\n\n\nfunc (in Info) UserID() user.ID {\n\treturn in.userID\n}\n\n\nfunc (in Info) String() string {\n\treturn fmt.Sprintf(\"[authentication ID:%s ]\", in.userID)\n}\n\nfunc NewInfo(userID user.ID) Info ", "output": "{\n\treturn Info{userID: userID}\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSOpsWorksApp_Source struct {\n\n\tPassword string `json:\"Password,omitempty\"`\n\n\tRevision string `json:\"Revision,omitempty\"`\n\n\tSshKey string `json:\"SshKey,omitempty\"`\n\n\tType string `json:\"Type,omitempty\"`\n\n\tUrl string `json:\"Url,omitempty\"`\n\n\tUsername string `json:\"Username,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\n\n\n\n\nfunc (r *AWSOpsWorksApp_Source) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSOpsWorksApp_Source) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::OpsWorks::App.Source\"\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n)\n\ntype BuiltInClass struct {\n\tname Instance\n\tsupers []Class\n\tslots []Instance\n}\n\nfunc NewBuiltInClass(name string, super Class, slots ...string) Class {\n\tslotNames := []Instance{}\n\tfor _, slot := range slots {\n\t\tslotNames = append(slotNames, NewSymbol(slot))\n\t}\n\treturn BuiltInClass{NewSymbol(name), []Class{super}, slotNames}\n}\n\nfunc (p BuiltInClass) Supers() []Class {\n\treturn p.supers\n}\n\nfunc (p BuiltInClass) Slots() []Instance {\n\treturn p.slots\n}\n\nfunc (p BuiltInClass) Initform(arg Instance) (v Instance, ok bool) {\n\treturn nil, false\n}\n\nfunc (p BuiltInClass) Initarg(arg Instance) (v Instance, ok bool) {\n\treturn arg, true\n}\n\n\n\nfunc (p BuiltInClass) String() string {\n\treturn fmt.Sprint(p.name)\n}\n\nfunc (BuiltInClass) Class() Class ", "output": "{\n\treturn BuiltInClassClass\n}"} {"input": "package iso20022\n\n\ntype PlainCardData4 struct {\n\n\tPAN *Min8Max28NumericText `xml:\"PAN\"`\n\n\tCardSequenceNumber *Min2Max3NumericText `xml:\"CardSeqNb,omitempty\"`\n\n\tEffectiveDate *Max10Text `xml:\"FctvDt,omitempty\"`\n\n\tExpiryDate *Max10Text `xml:\"XpryDt\"`\n\n\tServiceCode *Exact3NumericText `xml:\"SvcCd,omitempty\"`\n\n\tTrackData []*TrackData1 `xml:\"TrckData,omitempty\"`\n\n\tCardSecurityCode *CardSecurityInformation1 `xml:\"CardSctyCd,omitempty\"`\n}\n\nfunc (p *PlainCardData4) SetPAN(value string) {\n\tp.PAN = (*Min8Max28NumericText)(&value)\n}\n\nfunc (p *PlainCardData4) SetCardSequenceNumber(value string) {\n\tp.CardSequenceNumber = (*Min2Max3NumericText)(&value)\n}\n\nfunc (p *PlainCardData4) SetEffectiveDate(value string) {\n\tp.EffectiveDate = (*Max10Text)(&value)\n}\n\nfunc (p *PlainCardData4) SetExpiryDate(value string) {\n\tp.ExpiryDate = (*Max10Text)(&value)\n}\n\n\n\nfunc (p *PlainCardData4) AddTrackData() *TrackData1 {\n\tnewValue := new(TrackData1)\n\tp.TrackData = append(p.TrackData, newValue)\n\treturn newValue\n}\n\nfunc (p *PlainCardData4) AddCardSecurityCode() *CardSecurityInformation1 {\n\tp.CardSecurityCode = new(CardSecurityInformation1)\n\treturn p.CardSecurityCode\n}\n\nfunc (p *PlainCardData4) SetServiceCode(value string) ", "output": "{\n\tp.ServiceCode = (*Exact3NumericText)(&value)\n}"} {"input": "package mongo\n\nimport (\n\t\"context\"\n\n\t\"github.com/cuigh/swirl/dao\"\n\t\"go.mongodb.org/mongo-driver/bson\"\n)\n\nconst Setting = \"setting\"\n\nfunc (d *Dao) SettingGetAll(ctx context.Context) (settings []*dao.Setting, err error) {\n\tsettings = []*dao.Setting{}\n\terr = d.fetch(ctx, Setting, bson.M{}, &settings)\n\treturn\n}\n\nfunc (d *Dao) SettingGet(ctx context.Context, id string) (setting *dao.Setting, err error) {\n\tsetting = &dao.Setting{}\n\tfound, err := d.find(ctx, Setting, id, setting)\n\tif !found {\n\t\treturn nil, err\n\t}\n\treturn\n}\n\n\n\nfunc (d *Dao) SettingUpdate(ctx context.Context, setting *dao.Setting) (err error) ", "output": "{\n\tupdate := bson.M{\n\t\t\"$set\": bson.M{\n\t\t\t\"options\": setting.Options,\n\t\t\t\"updated_at\": setting.UpdatedAt,\n\t\t\t\"updated_by\": setting.UpdatedBy,\n\t\t},\n\t}\n\treturn d.upsert(ctx, Setting, setting.ID, update)\n}"} {"input": "package goopenzwave\n\n\n\n\n\nimport \"C\"\nimport (\n\t\"fmt\"\n)\n\nvar (\n\tstarted bool\n\tnotificationHandler NotificationHandler\n)\n\n\n\ntype NotificationHandler func(notification *Notification)\n\n\n\n\n\nfunc Start(handler NotificationHandler) error {\n\tif started {\n\t\treturn fmt.Errorf(\"already started\")\n\t}\n\n\terr := createManager()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create manager: %s\", err)\n\t}\n\n\terr = startNotifications()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnotificationHandler = handler\n\n\treturn nil\n}\n\n\n\n\n\nfunc Stop() error ", "output": "{\n\tif started {\n\t\treturn fmt.Errorf(\"already started\")\n\t}\n\n\terr := stopNotifications()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdestroyManager()\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/lxc/lxd/lxd/cluster\"\n\t\"github.com/lxc/lxd/lxd/db\"\n\t\"github.com/lxc/lxd/lxd/node\"\n\t\"github.com/lxc/lxd/lxd/state\"\n\t\"github.com/lxc/lxd/shared\"\n)\n\n\n\nfunc daemonConfigSetProxy(d *Daemon, config *cluster.Config) {\n\td.proxy = shared.ProxyFromConfig(\n\t\tconfig.ProxyHTTPS(),\n\t\tconfig.ProxyHTTP(),\n\t\tconfig.ProxyIgnoreHosts(),\n\t)\n\n\timageStreamCacheLock.Lock()\n\tfor k := range imageStreamCache {\n\t\tdelete(imageStreamCache, k)\n\t}\n\timageStreamCacheLock.Unlock()\n}\n\nfunc daemonConfigRender(state *state.State) (map[string]interface{}, error) ", "output": "{\n\tconfig := map[string]interface{}{}\n\n\terr := state.Cluster.Transaction(func(tx *db.ClusterTx) error {\n\t\tclusterConfig, err := cluster.ConfigLoad(tx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor key, value := range clusterConfig.Dump() {\n\t\t\tconfig[key] = value\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = state.Node.Transaction(func(tx *db.NodeTx) error {\n\t\tnodeConfig, err := node.ConfigLoad(tx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor key, value := range nodeConfig.Dump() {\n\t\t\tconfig[key] = value\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn config, nil\n}"} {"input": "package wiringpi\n\n\n\n\n\n\n\n\n\n\n\nimport \"C\"\nimport (\n\t\"sync\"\n\n\t\"github.com/yroffin/jarvis-go-ext/logger\"\n)\n\n\ntype WiringPiDriver struct {\n}\n\nvar instance *WiringPiDriver\nvar once sync.Once\n\n\n\n\n\nfunc (wiringPi *WiringPiDriver) init() int {\n\tvar res = int(C.wiringPiSetupInit())\n\tlogger.Default.Info(\"WiringPiDriver\", logger.Fields{\n\t\t\"Init\": \"on\",\n\t})\n\treturn res\n}\n\n\nfunc PinMode(pin int, value int) {\n\tC.pinMode(C.int(pin), C.int(value))\n}\n\n\nfunc DigitalWrite(pin int, value int) {\n\tC.digitalWrite(C.int(pin), C.int(value))\n}\n\n\nfunc DelayMicroseconds(delay uint) {\n\tC.delayMicroseconds(C.uint(delay))\n}\n\n\nfunc Delay(delay uint) {\n\tC.delay(C.uint(delay))\n}\n\nfunc GetInstance() *WiringPiDriver ", "output": "{\n\tonce.Do(func() {\n\t\tinstance = new(WiringPiDriver)\n\t\tinstance.init()\n\t})\n\treturn instance\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSGlueCrawler_Schedule struct {\n\n\tScheduleExpression string `json:\"ScheduleExpression,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSGlueCrawler_Schedule) AWSCloudFormationType() string {\n\treturn \"AWS::Glue::Crawler.Schedule\"\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetDeletionPolicy(policy policies.DeletionPolicy) ", "output": "{\n\tr._deletionPolicy = policy\n}"} {"input": "package core \n\nimport (\n\t\"sync\"\n\n\t\"barista.run/bar\"\n\tl \"barista.run/logging\"\n\t\"barista.run/sink\"\n)\n\n\n\ntype ModuleSet struct {\n\tmodules []*Module\n\tupdateCh chan int\n\toutputs []bar.Segments\n\toutputsMu sync.RWMutex\n}\n\n\n\n\n\n\nfunc (m *ModuleSet) Stream() <-chan int {\n\tfor i, mod := range m.modules {\n\t\tgo mod.Stream(m.sinkFn(i))\n\t}\n\treturn m.updateCh\n}\n\nfunc (m *ModuleSet) sinkFn(idx int) bar.Sink {\n\treturn sink.Func(func(out bar.Segments) {\n\t\tl.Fine(\"%s new output from %s\",\n\t\t\tl.ID(m), l.ID(m.modules[idx].original))\n\t\tm.outputsMu.Lock()\n\t\tm.outputs[idx] = out\n\t\tm.outputsMu.Unlock()\n\t\tm.updateCh <- idx\n\t})\n}\n\n\nfunc (m *ModuleSet) Len() int {\n\treturn len(m.modules)\n}\n\n\n\nfunc (m *ModuleSet) LastOutput(idx int) bar.Segments {\n\tm.outputsMu.RLock()\n\tdefer m.outputsMu.RUnlock()\n\treturn m.outputs[idx]\n}\n\n\n\n\nfunc (m *ModuleSet) LastOutputs() []bar.Segments {\n\tm.outputsMu.RLock()\n\tdefer m.outputsMu.RUnlock()\n\tcp := make([]bar.Segments, len(m.outputs))\n\tcopy(cp, m.outputs)\n\treturn cp\n}\n\nfunc NewModuleSet(modules []bar.Module) *ModuleSet ", "output": "{\n\tset := &ModuleSet{\n\t\tmodules: make([]*Module, len(modules)),\n\t\toutputs: make([]bar.Segments, len(modules)),\n\t\tupdateCh: make(chan int),\n\t}\n\tfor i, m := range modules {\n\t\tl.Fine(\"%s added as %s[%d]\", l.ID(m), l.ID(set), i)\n\t\tset.modules[i] = NewModule(m)\n\t}\n\treturn set\n}"} {"input": "package logging\n\nimport (\n\t\"time\"\n\n\t\"github.com/urandom/readeef/content\"\n\t\"github.com/urandom/readeef/content/repo\"\n\t\"github.com/urandom/readeef/log\"\n)\n\ntype tagRepo struct {\n\trepo.Tag\n\n\tlog log.Log\n}\n\n\n\nfunc (r tagRepo) ForUser(user content.User) ([]content.Tag, error) {\n\tstart := time.Now()\n\n\ttags, err := r.Tag.ForUser(user)\n\n\tr.log.Infof(\"repo.Tag.ForUser took %s\", time.Now().Sub(start))\n\n\treturn tags, err\n}\n\nfunc (r tagRepo) ForFeed(feed content.Feed, user content.User) ([]content.Tag, error) {\n\tstart := time.Now()\n\n\ttags, err := r.Tag.ForFeed(feed, user)\n\n\tr.log.Infof(\"repo.Tag.ForFeed took %s\", time.Now().Sub(start))\n\n\treturn tags, err\n}\n\nfunc (r tagRepo) FeedIDs(tag content.Tag, user content.User) ([]content.FeedID, error) {\n\tstart := time.Now()\n\n\tids, err := r.Tag.FeedIDs(tag, user)\n\n\tr.log.Infof(\"repo.Tag.FeedIDs took %s\", time.Now().Sub(start))\n\n\treturn ids, err\n}\n\nfunc (r tagRepo) Get(id content.TagID, user content.User) (content.Tag, error) ", "output": "{\n\tstart := time.Now()\n\n\ttag, err := r.Tag.Get(id, user)\n\n\tr.log.Infof(\"repo.Tag.Get took %s\", time.Now().Sub(start))\n\n\treturn tag, err\n}"} {"input": "package bunyan\n\nimport \"fmt\"\n\n\ntype Logger struct {\n\tsink Sink\n\trecord Record\n}\n\n\nfunc NewLogger(target Sink) *Logger {\n\treturn &Logger{target, NewRecord()}\n}\n\n\n\nfunc (l *Logger) Write(record Record) error {\n\trecord.TemplateMerge(l.record)\n\treturn l.sink.Write(record)\n}\n\n\n\nfunc (l *Logger) Include(info Info) Log {\n\treturn NewLogger(InfoSink(l, info))\n}\n\n\n\n\n\n\n\nfunc (l *Logger) Recordf(key, value string, args ...interface{}) Log {\n\treturn l.Record(key, fmt.Sprintf(value, args...))\n}\n\n\n\nfunc (l *Logger) Child() Log {\n\treturn NewLogger(l)\n}\n\nfunc (l *Logger) Tracef(msg string, args ...interface{}) { l.send(TRACE, msg, args...) }\nfunc (l *Logger) Debugf(msg string, args ...interface{}) { l.send(DEBUG, msg, args...) }\nfunc (l *Logger) Infof(msg string, args ...interface{}) { l.send(INFO, msg, args...) }\nfunc (l *Logger) Warnf(msg string, args ...interface{}) { l.send(WARN, msg, args...) }\nfunc (l *Logger) Errorf(msg string, args ...interface{}) { l.send(ERROR, msg, args...) }\nfunc (l *Logger) Fatalf(msg string, args ...interface{}) { l.send(FATAL, msg, args...) }\n\nfunc (l *Logger) send(level Level, msg string, args ...interface{}) {\n\trecord := NewRecord()\n\trecord.SetMessagef(level, msg, args...)\n\te := l.Write(record)\n\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc (l *Logger) Record(key string, value interface{}) Log ", "output": "{\n\tbuilder := NewLogger(l)\n\tbuilder.record[key] = value\n\treturn builder\n}"} {"input": "package apihelper\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\n\t\"github.com/mediocregopher/mediocre-api/common\"\n\t\"github.com/mediocregopher/mediocre-api/pickyjson\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Prepare(\n\tw http.ResponseWriter, r *http.Request, params interface{},\n\tbodySizeLimit int64,\n) bool {\n\tr.Body = http.MaxBytesReader(w, r.Body, bodySizeLimit)\n\tif params != nil {\n\t\tif err := json.NewDecoder(r.Body).Decode(params); err != nil {\n\t\t\thttp.Error(w, err.Error(), 400)\n\t\t\treturn false\n\t\t}\n\t\tif err := pickyjson.CheckRequired(params); err != nil {\n\t\t\tcommon.HTTPError(w, r, err)\n\t\t\treturn false\n\t\t}\n\t\tif err := pickyjson.CheckRequired(¶ms); err != nil {\n\t\t\tcommon.HTTPError(w, r, err)\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n\n\nfunc JSONSuccess(w io.Writer, i interface{}) {\n\tjson.NewEncoder(w).Encode(i)\n\tfmt.Fprintf(w, \"\\n\")\n}\n\nfunc ErrUnlessMethod(\n\tw http.ResponseWriter, r *http.Request, methods ...string,\n) bool ", "output": "{\n\tfor i := range methods {\n\t\tif r.Method == methods[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\thttp.Error(w, \"invalid method\", 400)\n\treturn false\n}"} {"input": "package srpc\n\nimport (\n\t\"crypto/tls\"\n\n\t\"github.com/Symantec/Dominator/lib/connpool\"\n)\n\nfunc newClientResource(network, address string) *ClientResource {\n\tclientResource := &ClientResource{\n\t\tnetwork: network,\n\t\taddress: address,\n\t}\n\tclientResource.privateClientResource.clientResource = clientResource\n\trp := connpool.GetResourcePool()\n\tclientResource.resource = rp.Create(&clientResource.privateClientResource)\n\treturn clientResource\n}\n\nfunc (cr *ClientResource) getHTTP(tlsConfig *tls.Config,\n\tcancelChannel <-chan struct{}, dialer connpool.Dialer) (*Client, error) {\n\tcr.privateClientResource.tlsConfig = tlsConfig\n\tcr.privateClientResource.dialer = dialer\n\tif err := cr.resource.Get(cancelChannel); err != nil {\n\t\treturn nil, err\n\t}\n\tcr.inUse = true\n\tclientMetricsMutex.Lock()\n\tnumInUseClientConnections++\n\tclientMetricsMutex.Unlock()\n\treturn cr.client, nil\n}\n\nfunc (client *Client) put() {\n\tclient.resource.resource.Put()\n\tif client.resource.inUse {\n\t\tclientMetricsMutex.Lock()\n\t\tnumInUseClientConnections--\n\t\tclientMetricsMutex.Unlock()\n\t\tclient.resource.inUse = false\n\t}\n}\n\nfunc (pcr *privateClientResource) Allocate() error {\n\tcr := pcr.clientResource\n\tclient, err := dialHTTP(cr.network, cr.address, pcr.tlsConfig, pcr.dialer)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcr.client = client\n\tclient.resource = cr\n\treturn nil\n}\n\n\n\nfunc (pcr *privateClientResource) Release() error ", "output": "{\n\tcr := pcr.clientResource\n\terr := cr.client.conn.Close()\n\tcr.client = nil\n\treturn err\n}"} {"input": "package logutil\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/coreos/pkg/capnslog\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n)\n\nvar DefaultLogLevel = \"info\"\n\n\n\n\n\n\nfunc ConvertToCapnslogLogLevel(lvl string) capnslog.LogLevel {\n\tswitch lvl {\n\tcase \"debug\":\n\t\treturn capnslog.DEBUG\n\tcase \"info\":\n\t\treturn capnslog.INFO\n\tcase \"warn\":\n\t\treturn capnslog.WARNING\n\tcase \"error\":\n\t\treturn capnslog.ERROR\n\tcase \"dpanic\":\n\t\treturn capnslog.CRITICAL\n\tcase \"panic\":\n\t\treturn capnslog.CRITICAL\n\tcase \"fatal\":\n\t\treturn capnslog.CRITICAL\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unknown level %q\", lvl))\n\t}\n}\n\nfunc ConvertToZapLevel(lvl string) zapcore.Level ", "output": "{\n\tswitch lvl {\n\tcase \"debug\":\n\t\treturn zap.DebugLevel\n\tcase \"info\":\n\t\treturn zap.InfoLevel\n\tcase \"warn\":\n\t\treturn zap.WarnLevel\n\tcase \"error\":\n\t\treturn zap.ErrorLevel\n\tcase \"dpanic\":\n\t\treturn zap.DPanicLevel\n\tcase \"panic\":\n\t\treturn zap.PanicLevel\n\tcase \"fatal\":\n\t\treturn zap.FatalLevel\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unknown level %q\", lvl))\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/hyperhq/hyperd/engine\"\n\t\"github.com/hyperhq/runv/hypervisor/types\"\n)\n\nfunc (cli *Client) CreatePod(spec interface{}) (string, int, error) {\n\tbody, statusCode, err := readBody(cli.call(\"POST\", \"/pod/create\", spec, nil))\n\tif err != nil {\n\t\treturn \"\", statusCode, err\n\t}\n\tif statusCode != http.StatusCreated && statusCode != http.StatusOK {\n\t\treturn \"\", statusCode, err\n\t}\n\n\tout := engine.NewOutput()\n\tremoteInfo, err := out.AddEnv()\n\tif err != nil {\n\t\treturn \"\", statusCode, err\n\t}\n\n\tif _, err := out.Write(body); err != nil {\n\t\treturn \"\", statusCode, fmt.Errorf(\"Error reading remote info: %s\", err)\n\t}\n\tout.Close()\n\terrCode := remoteInfo.GetInt(\"Code\")\n\tif errCode == types.E_OK {\n\t} else {\n\t\tif errCode != types.E_BAD_REQUEST &&\n\t\t\terrCode != types.E_FAILED {\n\t\t\treturn \"\", statusCode, fmt.Errorf(\"Error code is %d\", errCode)\n\t\t} else {\n\t\t\treturn \"\", statusCode, fmt.Errorf(\"Cause is %s\", remoteInfo.Get(\"Cause\"))\n\t\t}\n\t}\n\treturn remoteInfo.Get(\"ID\"), statusCode, nil\n}\n\n\n\nfunc (cli *Client) CreateContainer(podID string, spec interface{}) (string, int, error) ", "output": "{\n\tv := url.Values{}\n\tv.Set(\"podId\", podID)\n\tbody, statusCode, err := readBody(cli.call(\"POST\", \"/container/create?\"+v.Encode(), spec, nil))\n\tif err != nil {\n\t\treturn \"\", statusCode, err\n\t}\n\tif statusCode != http.StatusCreated && statusCode != http.StatusOK {\n\t\treturn \"\", statusCode, err\n\t}\n\n\tout := engine.NewOutput()\n\tremoteInfo, err := out.AddEnv()\n\tif err != nil {\n\t\treturn \"\", statusCode, err\n\t}\n\n\tif _, err := out.Write(body); err != nil {\n\t\treturn \"\", statusCode, fmt.Errorf(\"Error reading remote info: %s\", err)\n\t}\n\tout.Close()\n\n\treturn remoteInfo.Get(\"ID\"), statusCode, nil\n}"} {"input": "package db\n\nimport \"testing\"\n\nfunc TestObjectToJSON(t *testing.T) {\n\tv := &SurveyVar{\n\t\tName: \"test\",\n\t\tTitle: \"Test\",\n\t}\n\ts := ObjectToJSON(v)\n\tif s == nil || *s != \"{\\\"name\\\":\\\"test\\\",\\\"title\\\":\\\"Test\\\",\\\"required\\\":false,\\\"type\\\":\\\"\\\",\\\"description\\\":\\\"\\\"}\" {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestObjectToJSON2(t *testing.T) {\n\tvar v *SurveyVar = nil\n\ts := ObjectToJSON(v)\n\tif s != nil {\n\t\tt.Fail()\n\t}\n}\n\n\n\nfunc TestObjectToJSON3(t *testing.T) ", "output": "{\n\tv := SurveyVar{\n\t\tName: \"test\",\n\t\tTitle: \"Test\",\n\t}\n\ts := ObjectToJSON(v)\n\tif s == nil || *s != \"{\\\"name\\\":\\\"test\\\",\\\"title\\\":\\\"Test\\\",\\\"required\\\":false,\\\"type\\\":\\\"\\\",\\\"description\\\":\\\"\\\"}\" {\n\t\tt.Fail()\n\t}\n}"} {"input": "package segment\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/checkr/flagr/swagger_gen/models\"\n)\n\n\nconst DeleteSegmentOKCode int = 200\n\n\ntype DeleteSegmentOK struct {\n}\n\n\nfunc NewDeleteSegmentOK() *DeleteSegmentOK {\n\n\treturn &DeleteSegmentOK{}\n}\n\n\nfunc (o *DeleteSegmentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(200)\n}\n\n\ntype DeleteSegmentDefault struct {\n\t_statusCode int\n\n\tPayload *models.Error `json:\"body,omitempty\"`\n}\n\n\n\n\n\nfunc (o *DeleteSegmentDefault) WithStatusCode(code int) *DeleteSegmentDefault {\n\to._statusCode = code\n\treturn o\n}\n\n\nfunc (o *DeleteSegmentDefault) SetStatusCode(code int) {\n\to._statusCode = code\n}\n\n\nfunc (o *DeleteSegmentDefault) WithPayload(payload *models.Error) *DeleteSegmentDefault {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *DeleteSegmentDefault) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}\n\n\nfunc (o *DeleteSegmentDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(o._statusCode)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\nfunc NewDeleteSegmentDefault(code int) *DeleteSegmentDefault ", "output": "{\n\tif code <= 0 {\n\t\tcode = 500\n\t}\n\n\treturn &DeleteSegmentDefault{\n\t\t_statusCode: code,\n\t}\n}"} {"input": "package argparse\n\n\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\ntype ArgumentParser struct {\n\tStdout io.Writer\n\n\tStderr io.Writer\n\n\tMessages Messages\n\n\tHelpSwitches []string\n\n\tRoot *Command\n\n\tfinalized bool\n}\n\n\n\n\n\nfunc (self *ArgumentParser) Add(arg *Argument) {\n\tself.Root.Add(arg)\n}\n\n\nfunc (self *ArgumentParser) New(c *Command) *Command {\n\treturn self.Root.New(c)\n}\n\n\n\n\nfunc (self *ArgumentParser) Parse() {\n\tresults := self.parseArgv(os.Args[1:])\n\n\tcmd := results.triggeredCommand\n\n\tif results.helpRequested {\n\t\thelpString := self.helpString(cmd, results.ancestorCommands)\n\t\tfmt.Fprintln(self.Stdout, helpString)\n\t\tos.Exit(0)\n\t} else if results.parseError != nil {\n\t\tfmt.Fprintln(self.Stderr, results.parseError.Error())\n\t\tos.Exit(1)\n\t}\n\n\tif cmd.Function != nil {\n\t\terr := cmd.Function(cmd, cmd.Values)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(self.Stderr, err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}\n\n\n\n\n\n\nfunc (self *ArgumentParser) ParseAndExit() {\n\tself.Parse()\n\tos.Exit(0)\n}\n\nfunc (self *ArgumentParser) parseArgv(argv []string) *parseResults {\n\tparser := parserState{}\n\tresults := parser.runParser(self, argv)\n\treturn results\n}\n\nfunc New(cmd *Command) *ArgumentParser ", "output": "{\n\tap := &ArgumentParser{\n\t\tStdout: os.Stdout,\n\t\tStderr: os.Stderr,\n\t\tMessages: DefaultMessages_en,\n\t\tHelpSwitches: []string{\"-h\", \"--help\"},\n\t\tRoot: cmd,\n\t}\n\tcmd.init(nil, ap)\n\tif cmd.Name == \"\" {\n\t\tcmd.Name = os.Args[0]\n\t}\n\treturn ap\n}"} {"input": "package run_model\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype APIPipelineRuntime struct {\n\n\tPipelineManifest string `json:\"pipeline_manifest,omitempty\"`\n\n\tWorkflowManifest string `json:\"workflow_manifest,omitempty\"`\n}\n\n\nfunc (m *APIPipelineRuntime) Validate(formats strfmt.Registry) error {\n\treturn nil\n}\n\n\n\n\n\nfunc (m *APIPipelineRuntime) UnmarshalBinary(b []byte) error {\n\tvar res APIPipelineRuntime\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *APIPipelineRuntime) MarshalBinary() ([]byte, error) ", "output": "{\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}"} {"input": "package internal\n\nimport (\n\t\"bufio\"\n\t\"compress/gzip\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc NewBufferedSectionReader(ra io.ReaderAt, off, n int64) io.Reader {\n\tbuf := n\n\tif ps := int64(os.Getpagesize()); n > ps {\n\t\tbuf = ps\n\t}\n\n\treturn bufio.NewReaderSize(io.NewSectionReader(ra, off, n), int(buf))\n}\n\n\n\ntype DiscardZeroes struct{}\n\n\n\n\nfunc ReadAllCompressed(file string) ([]byte, error) {\n\tfh, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer fh.Close()\n\n\tgz, err := gzip.NewReader(fh)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer gz.Close()\n\n\treturn io.ReadAll(gz)\n}\n\nfunc (DiscardZeroes) Write(p []byte) (int, error) ", "output": "{\n\tfor _, b := range p {\n\t\tif b != 0 {\n\t\t\treturn 0, errors.New(\"encountered non-zero byte\")\n\t\t}\n\t}\n\treturn len(p), nil\n}"} {"input": "package boom\n\nimport (\n\t\"github.com/efritz/glock\"\n)\n\ntype TaskConfig func(*taskConfig)\n\ntype taskConfig struct {\n\tclock glock.Clock\n}\n\n\n\nfunc (tc *taskConfig) ApplyConfigs(configs []TaskConfig) {\n\tfor _, f := range configs {\n\t\tf(tc)\n\t}\n}\n\nfunc WithClock(clock glock.Clock) TaskConfig {\n\treturn func(cfg *taskConfig) {\n\t\tcfg.clock = clock\n\t}\n}\n\nfunc newTaskConfig() *taskConfig ", "output": "{\n\treturn &taskConfig{\n\t\tclock: glock.NewRealClock(),\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/banerwai/gommon/crypto\"\n\t\"github.com/banerwai/micros/query/auth/service\"\n\t\"gopkg.in/mgo.v2/bson\"\n)\n\ntype inmemService struct {\n}\n\nfunc newInmemService() service.AuthService {\n\treturn &inmemService{}\n}\n\nfunc (ims *inmemService) Ping() (r string) {\n\tr = \"pong\"\n\treturn\n}\n\n\n\nfunc (ims *inmemService) Login(email string, pwd string) (r string) ", "output": "{\n\tvar _bsonM bson.M\n\terr := UsersCollection.Find(bson.M{\"email\": email}).One(&_bsonM)\n\n\tif err != nil {\n\t\treturn \"error:\" + err.Error()\n\t}\n\n\t_active := _bsonM[\"actived\"].(bool)\n\tif !_active {\n\t\treturn \"error: user email need active\"\n\t}\n\n\t_pwd := _bsonM[\"pwd\"].(string)\n\n\t_is := crypto.CompareHash([]byte(_pwd), pwd)\n\tif !_is {\n\t\treturn \"error: compare false\"\n\t}\n\n\t_data, _err := bson.Marshal(_bsonM)\n\tif _err != nil {\n\t\treturn \"error: bson.Marshal error\"\n\t}\n\n\tr = string(_data)\n\treturn\n}"} {"input": "package iso20022\n\n\ntype AmountAndDirection55 struct {\n\n\tAmount *RestrictedFINActiveOrHistoricCurrencyAndAmount `xml:\"Amt\"`\n\n\tCreditDebitIndicator *CreditDebitCode `xml:\"CdtDbtInd,omitempty\"`\n\n\tOriginalCurrencyAndOrderedAmount *RestrictedFINActiveOrHistoricCurrencyAndAmount `xml:\"OrgnlCcyAndOrdrdAmt,omitempty\"`\n\n\tForeignExchangeDetails *ForeignExchangeTerms23 `xml:\"FXDtls,omitempty\"`\n}\n\nfunc (a *AmountAndDirection55) SetAmount(value, currency string) {\n\ta.Amount = NewRestrictedFINActiveOrHistoricCurrencyAndAmount(value, currency)\n}\n\n\n\nfunc (a *AmountAndDirection55) SetOriginalCurrencyAndOrderedAmount(value, currency string) {\n\ta.OriginalCurrencyAndOrderedAmount = NewRestrictedFINActiveOrHistoricCurrencyAndAmount(value, currency)\n}\n\nfunc (a *AmountAndDirection55) AddForeignExchangeDetails() *ForeignExchangeTerms23 {\n\ta.ForeignExchangeDetails = new(ForeignExchangeTerms23)\n\treturn a.ForeignExchangeDetails\n}\n\nfunc (a *AmountAndDirection55) SetCreditDebitIndicator(value string) ", "output": "{\n\ta.CreditDebitIndicator = (*CreditDebitCode)(&value)\n}"} {"input": "package futures\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\ntype Completer <-chan interface{}\n\n\n\n\n\n\n\ntype Future struct {\n\ttriggered bool \n\titem interface{}\n\terr error\n\tlock sync.Mutex\n\twg sync.WaitGroup\n}\n\n\n\nfunc (f *Future) GetResult() (interface{}, error) {\n\tf.lock.Lock()\n\tif f.triggered {\n\t\tf.lock.Unlock()\n\t\treturn f.item, f.err\n\t}\n\tf.lock.Unlock()\n\n\tf.wg.Wait()\n\treturn f.item, f.err\n}\n\nfunc (f *Future) setItem(item interface{}, err error) {\n\tf.lock.Lock()\n\tf.triggered = true\n\tf.item = item\n\tf.err = err\n\tf.lock.Unlock()\n\tf.wg.Done()\n}\n\n\n\n\n\n\n\nfunc New(completer Completer, timeout time.Duration) *Future {\n\tf := &Future{}\n\tf.wg.Add(1)\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo listenForResult(f, completer, timeout, &wg)\n\twg.Wait()\n\treturn f\n}\n\nfunc listenForResult(f *Future, ch Completer, timeout time.Duration, wg *sync.WaitGroup) ", "output": "{\n\twg.Done()\n\tselect {\n\tcase item := <-ch:\n\t\tf.setItem(item, nil)\n\tcase <-time.After(timeout):\n\t\tf.setItem(nil, fmt.Errorf(`Timeout after %f seconds.`, timeout.Seconds()))\n\t}\n}"} {"input": "package iso20022\n\n\ntype CorporateActionOption1FormatChoice struct {\n\n\tCode *CorporateActionOptionType1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification13 `xml:\"Prtry\"`\n}\n\n\n\nfunc (c *CorporateActionOption1FormatChoice) AddProprietary() *GenericIdentification13 {\n\tc.Proprietary = new(GenericIdentification13)\n\treturn c.Proprietary\n}\n\nfunc (c *CorporateActionOption1FormatChoice) SetCode(value string) ", "output": "{\n\tc.Code = (*CorporateActionOptionType1Code)(&value)\n}"} {"input": "package builder\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\n\tvelerov1api \"github.com/vmware-tanzu/velero/pkg/apis/velero/v1\"\n)\n\n\ntype PodVolumeBackupBuilder struct {\n\tobject *velerov1api.PodVolumeBackup\n}\n\n\nfunc ForPodVolumeBackup(ns, name string) *PodVolumeBackupBuilder {\n\treturn &PodVolumeBackupBuilder{\n\t\tobject: &velerov1api.PodVolumeBackup{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tAPIVersion: velerov1api.SchemeGroupVersion.String(),\n\t\t\t\tKind: \"PodVolumeBackup\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: name,\n\t\t\t},\n\t\t},\n\t}\n}\n\n\nfunc (b *PodVolumeBackupBuilder) Result() *velerov1api.PodVolumeBackup {\n\treturn b.object\n}\n\n\nfunc (b *PodVolumeBackupBuilder) ObjectMeta(opts ...ObjectMetaOpt) *PodVolumeBackupBuilder {\n\tfor _, opt := range opts {\n\t\topt(b.object)\n\t}\n\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) Phase(phase velerov1api.PodVolumeBackupPhase) *PodVolumeBackupBuilder {\n\tb.object.Status.Phase = phase\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) SnapshotID(snapshotID string) *PodVolumeBackupBuilder {\n\tb.object.Status.SnapshotID = snapshotID\n\treturn b\n}\n\n\n\n\n\nfunc (b *PodVolumeBackupBuilder) Volume(volume string) *PodVolumeBackupBuilder {\n\tb.object.Spec.Volume = volume\n\treturn b\n}\n\nfunc (b *PodVolumeBackupBuilder) PodName(name string) *PodVolumeBackupBuilder ", "output": "{\n\tb.object.Spec.Pod.Name = name\n\treturn b\n}"} {"input": "package data_table\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/julienschmidt/httprouter\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\nfunc DataStoreHandler(tableStore TableStore) func(http.ResponseWriter, *http.Request, httprouter.Params) {\n\treturn func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\t\trequest := newSearchRequest(r, ps)\n\t\tresult := tableStore.QueryData(request)\n\t\tjsonBytes, _ := json.Marshal(result)\n\t\tfmt.Fprint(w, string(jsonBytes))\n\t}\n}\n\nfunc TreePostFormValues(values url.Values) map[string]interface{} {\n\tres := make(map[string]interface{})\n\tvar currValue map[string]interface{}\n\tfor rawKey, value := range values {\n\t\tif vs := value; len(vs) > 0 {\n\t\t\tcurrValue = res\n\t\t\tkeyPath := ParseKey(rawKey)\n\t\t\tlastIndex := len(keyPath) - 1\n\t\t\tfor index, key := range keyPath {\n\t\t\t\tif index == lastIndex {\n\t\t\t\t\tcurrValue[key] = vs[0]\n\t\t\t\t} else {\n\t\t\t\t\tif _, ok := currValue[key]; !ok {\n\t\t\t\t\t\tcurrValue[key] = make(map[string]interface{})\n\t\t\t\t\t}\n\t\t\t\t\tcurrValue = currValue[key].(map[string]interface{})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\treturn res\n}\n\n\n\nfunc ParseKey(key string) []string ", "output": "{\n\tres := make([]string, 0)\n\tvar currKey bytes.Buffer\n\n\tfor _, char := range key {\n\t\tif char == '[' || char == ']' {\n\t\t\tif currKey.Len() > 0 {\n\t\t\t\tres = append(res, currKey.String())\n\t\t\t\tcurrKey.Reset()\n\t\t\t}\n\t\t} else {\n\t\t\tcurrKey.WriteRune(char)\n\t\t}\n\t}\n\n\tif currKey.Len() > 0 {\n\t\tres = append(res, currKey.String())\n\t}\n\n\treturn res\n}"} {"input": "package models\n\nimport \"fmt\"\n\ntype TaskManager struct {\n\ttasks []*Task\n\tlastID int64\n}\n\nfunc NewTaskManager() *TaskManager {\n\treturn &TaskManager{}\n}\n\nfunc (m *TaskManager) Tasks() []*Task {\n\treturn m.tasks\n}\n\nfunc (m *TaskManager) Add(task *Task) error {\n\tif task.Id == 0 {\n\t\tm.lastID++\n\t\ttask.Id = m.lastID\n\t\tm.tasks = append(m.tasks, task.clone())\n\t\treturn nil\n\t}\n\n\t_, found := m.Find(task.Id)\n\tif found {\n\t\tm.tasks[task.Id-1] = task\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"unknown task\")\n}\n\n\n\nfunc (m *TaskManager) Find(id int64) (*Task, bool) ", "output": "{\n\tfor _, t := range m.tasks {\n\t\tif t.Id == id {\n\t\t\treturn t, true\n\t\t}\n\t}\n\treturn nil, false\n}"} {"input": "package launchdarkly\n\nimport (\n\t\"errors\"\n\t\"os\"\n\n\t\"github.com/GoogleCloudPlatform/terraformer/terraformutils\"\n)\n\ntype LaunchDarklyProvider struct { \n\tterraformutils.Provider\n\tapiKey string\n}\n\nconst (\n\tbasePath = \"https:app.launchdarkly.com/api/v2\"\n\tversion = \"0.0.1\"\n\tAPIVersion = \"20191212\"\n)\n\n\n\nfunc (p *LaunchDarklyProvider) GetName() string {\n\treturn \"launchdarkly\"\n}\n\nfunc (p *LaunchDarklyProvider) GetProviderData(arg ...string) map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"provider\": map[string]interface{}{\n\t\t\t\"launchdarkly\": map[string]interface{}{\n\t\t\t\t\"api_key\": p.apiKey,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (LaunchDarklyProvider) GetResourceConnections() map[string]map[string][]string {\n\treturn map[string]map[string][]string{}\n}\n\nfunc (p *LaunchDarklyProvider) GetSupportedService() map[string]terraformutils.ServiceGenerator {\n\treturn map[string]terraformutils.ServiceGenerator{\n\t\t\"project\": &ProjectGenerator{},\n\t}\n}\n\nfunc (p *LaunchDarklyProvider) InitService(serviceName string, verbose bool) error {\n\tvar isSupported bool\n\tif _, isSupported = p.GetSupportedService()[serviceName]; !isSupported {\n\t\treturn errors.New(\"launchdarkly: \" + serviceName + \" not supported service\")\n\t}\n\tp.Service = p.GetSupportedService()[serviceName]\n\tp.Service.SetName(serviceName)\n\tp.Service.SetVerbose(verbose)\n\tp.Service.SetProviderName(p.GetName())\n\tp.Service.SetArgs(map[string]interface{}{\n\t\t\"api_key\": p.apiKey,\n\t})\n\treturn nil\n}\n\nfunc (p *LaunchDarklyProvider) Init(args []string) error ", "output": "{\n\tif os.Getenv(\"LAUNCHDARKLY_ACCESS_TOKEN\") == \"\" {\n\t\treturn errors.New(\"set LAUNCHDARKLY_ACCESS_TOKEN env var\")\n\t}\n\tp.apiKey = os.Getenv(\"LAUNCHDARKLY_ACCESS_TOKEN\")\n\n\treturn nil\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/docker/infrakit/pkg/types\"\n)\n\ntype errBadDependency types.Dependency\n\nfunc (e errBadDependency) Error() string {\n\treturn fmt.Sprintf(\"unresolved dependency: class=%s name=%s\", types.Dependency(e).Class, types.Dependency(e).Name)\n}\n\ntype errCircularDependency []*types.Spec\n\nfunc (e errCircularDependency) Error() string {\n\tdeps := []*types.Spec(e)\n\tlist := fmt.Sprintf(\"%s/%s\", deps[0].Class, deps[0].Metadata.Name)\n\tfor _, dep := range deps[1:] {\n\t\tlist = list + fmt.Sprintf(\"=> %s/%s\", dep.Class, dep.Metadata.Name)\n\t}\n\treturn fmt.Sprintf(\"circular dependency: %s\", list)\n}\n\ntype errNotFound struct {\n\tclass string\n\tname string\n}\n\n\n\nfunc (e errNotFound) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"not found %s/%s\", e.class, e.name)\n}"} {"input": "package planbuilder\n\nimport (\n\t\"github.com/ngaut/arena\"\n\t\"github.com/cloud-all/cloudsql/sqlparser\"\n)\n\ntype DDLPlan struct {\n\tAction string\n\tTableName string\n\tNewName string\n}\n\nfunc DDLParse(sql string, alloc arena.ArenaAllocator) (plan *DDLPlan) {\n\tstatement, err := sqlparser.Parse(sql, alloc)\n\tif err != nil {\n\t\treturn &DDLPlan{Action: \"\"}\n\t}\n\tstmt, ok := statement.(*sqlparser.DDL)\n\tif !ok {\n\t\treturn &DDLPlan{Action: \"\"}\n\t}\n\treturn &DDLPlan{\n\t\tAction: stmt.Action,\n\t\tTableName: string(stmt.Table),\n\t\tNewName: string(stmt.NewName),\n\t}\n}\n\n\n\nfunc analyzeDDL(ddl *sqlparser.DDL, getTable TableGetter) *ExecPlan ", "output": "{\n\tplan := &ExecPlan{PlanId: PLAN_DDL}\n\ttableName := string(ddl.Table)\n\tif tableName != \"\" {\n\t\ttableInfo, ok := getTable(tableName)\n\t\tif ok {\n\t\t\tplan.TableName = tableInfo.Name\n\t\t}\n\t}\n\treturn plan\n}"} {"input": "package mocktikv\n\nimport (\n\t\"github.com/pingcap/pd/pd-client\"\n\t\"github.com/pkg/errors\"\n)\n\n\n\n\nfunc NewTiKVAndPDClient(cluster *Cluster, mvccStore MVCCStore, path string) (*RPCClient, pd.Client, error) ", "output": "{\n\tif cluster == nil {\n\t\tcluster = NewCluster()\n\t\tBootstrapWithSingleStore(cluster)\n\t}\n\n\tif mvccStore == nil {\n\t\tvar err error\n\t\tmvccStore, err = NewMVCCLevelDB(path)\n\t\tif err != nil {\n\t\t\treturn nil, nil, errors.Trace(err)\n\t\t}\n\t}\n\n\treturn NewRPCClient(cluster, mvccStore), NewPDClient(cluster), nil\n}"} {"input": "package muxer\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\tdebug \"github.com/micro/micro/v3/service/debug/handler\"\n\t\"github.com/micro/micro/v3/service/proxy\"\n\t\"github.com/micro/micro/v3/service/server\"\n\t\"github.com/micro/micro/v3/service/server/mucp\"\n)\n\n\ntype Server struct {\n\tName string\n\tProxy proxy.Proxy\n\tHandler Handler\n}\n\ntype Handler interface {\n\tproxy.Proxy\n\tNewHandler(interface{}, ...server.HandlerOption) server.Handler\n\tHandle(server.Handler) error\n}\n\nvar (\n\tonce sync.Once\n)\n\nfunc (s *Server) ProcessMessage(ctx context.Context, msg server.Message) error {\n\tif msg.Topic() == s.Name {\n\t\treturn s.Handler.ProcessMessage(ctx, msg)\n\t}\n\treturn s.Proxy.ProcessMessage(ctx, msg)\n}\n\n\n\nfunc New(name string, p proxy.Proxy) *Server {\n\tr := mucp.DefaultRouter\n\n\tonce.Do(func() {\n\t\tr.Handle(\n\t\t\tr.NewHandler(\n\t\t\t\tdebug.NewHandler(),\n\t\t\t\tserver.InternalHandler(true),\n\t\t\t),\n\t\t)\n\t})\n\n\treturn &Server{\n\t\tName: name,\n\t\tProxy: p,\n\t\tHandler: r,\n\t}\n}\n\nfunc (s *Server) ServeRequest(ctx context.Context, req server.Request, rsp server.Response) error ", "output": "{\n\tif req.Service() == s.Name {\n\t\treturn s.Handler.ServeRequest(ctx, req, rsp)\n\t}\n\treturn s.Proxy.ServeRequest(ctx, req, rsp)\n}"} {"input": "package keys\n\nimport \"context\"\n\n\ntype keySetType int\n\n\nconst keySet = keySetType(0)\n\n\nfunc Get(ctx context.Context) []interface{} {\n\tseen := map[interface{}]bool{}\n\tresult := make([]interface{}, 0, 10)\n\tfor link, _ := ctx.Value(keySet).(*Link); link != nil; link = link.Next {\n\t\tif !seen[link.Value] {\n\t\t\tseen[link.Value] = true\n\t\t\tresult = append(result, link.Value)\n\t\t}\n\t}\n\treturn result\n}\n\n\n\n\n\n\nfunc Clone(ctx context.Context, from context.Context) context.Context {\n\tfor _, key := range Get(from) {\n\t\tctx = WithValue(ctx, key, from.Value(key))\n\t}\n\treturn ctx\n}\n\nfunc WithValue(ctx context.Context, key interface{}, value interface{}) context.Context ", "output": "{\n\told, _ := ctx.Value(keySet).(*Link)\n\tctx = context.WithValue(ctx, key, value)\n\treturn context.WithValue(ctx, keySet, &Link{Value: key, Next: old})\n}"} {"input": "package routing\n\nimport \"net/http\"\n\n\nfunc Method(method string, handler http.Handler) Matcher {\n\treturn func(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\t\tif req.Method == method {\n\t\t\thandler.ServeHTTP(resp, req)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}\n\n\nfunc GET(handler http.Handler) Matcher {\n\treturn Method(\"GET\", handler)\n}\n\n\nfunc GETFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn GET(http.HandlerFunc(handler))\n}\n\n\nfunc POST(handler http.Handler) Matcher {\n\treturn Method(\"POST\", handler)\n}\n\n\nfunc POSTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn POST(http.HandlerFunc(handler))\n}\n\n\nfunc PUT(handler http.Handler) Matcher {\n\treturn Method(\"PUT\", handler)\n}\n\n\nfunc PUTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PUT(http.HandlerFunc(handler))\n}\n\n\n\n\n\nfunc PATCHFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PATCH(http.HandlerFunc(handler))\n}\n\n\nfunc DELETE(handler http.Handler) Matcher {\n\treturn Method(\"DELETE\", handler)\n}\n\n\nfunc DELETEFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn DELETE(http.HandlerFunc(handler))\n}\n\n\n\nfunc MethodNotAllowed(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\tresp.WriteHeader(405)\n\treturn true\n}\n\nfunc PATCH(handler http.Handler) Matcher ", "output": "{\n\treturn Method(\"PATCH\", handler)\n}"} {"input": "package project\n\nimport (\n\t\"javaPlugin/pkg/db\"\n\t\"testing\"\n\t\"encoding/json\"\n)\n\ntype parseNameCase struct {\n\tstr string\n\texp []string\n}\n\nfunc (testcase parseNameCase) CheckResult(result []string) bool {\n\tif len(result) != len(testcase.exp) {\n\t\treturn false\n\t}\n\tfor index, str := range result {\n\t\tif str != testcase.exp[index] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\nfunc Test_parseName(t *testing.T) ", "output": "{\n\tdb.InitVar(\"10.6.82.199:3306\", \"yzadmin\", \"fxm\", \"fxm@YiZhen\", \"mysql\")\n\terr := db.Init()\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\ttt, err := db.DbClient.Engine().DBMetas()\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\tfor _,value:=range tt{\n\t\tb,err:=json.Marshal(value.Columns())\n\t\tif err!=nil{\n\t\t\tt.Error(err.Error())\n\t\t}else{\n\t\t\tt.Log(string(b))\n\t\t}\n\t}\n\n\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\n\nfunc NashRoot() (string, error) {\n\tnashroot, ok := os.LookupEnv(\"NASHROOT\")\n\tif ok {\n\t\treturn nashroot, nil\n\t}\n\n\th, err := home()\n\treturn filepath.Join(h, \"nashroot\"), err\n}\n\nfunc home() (string, error) {\n\thomedir, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif homedir == \"\" {\n\t\treturn \"\", errors.New(\"invalid empty home dir\")\n\t}\n\treturn homedir, nil\n}\n\nfunc NashPath() (string, error) ", "output": "{\n\tnashpath := os.Getenv(\"NASHPATH\")\n\tif nashpath != \"\" {\n\t\treturn nashpath, nil\n\t}\n\th, err := home()\n\treturn filepath.Join(h, \"nash\"), err\n}"} {"input": "package isatty\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestTerminal(t *testing.T) {\n\tIsTerminal(os.Stdout.Fd())\n}\n\n\n\nfunc TestCygwinPipeName(t *testing.T) ", "output": "{\n\tif IsCygwinTerminal(os.Stdout.Fd()) {\n\t\tt.Fatal(\"should be false always\")\n\t}\n}"} {"input": "package errors\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/GoogleContainerTools/skaffold/proto/v1\"\n)\n\ntype Error interface {\n\tError() string\n\tStatusCode() proto.StatusCode\n\tSuggestions() []*proto.Suggestion\n\tUnwrap() error\n}\n\ntype ErrDef struct {\n\terr error\n\tae *proto.ActionableErr\n}\n\nvar _ error = (*ErrDef)(nil)\n\nfunc (e *ErrDef) Error() string {\n\tif s := concatSuggestions(e.Suggestions()); s != \"\" {\n\t\treturn fmt.Sprintf(\"%s. %s\", e.ae.Message, concatSuggestions(e.Suggestions()))\n\t}\n\treturn e.ae.Message\n}\n\nfunc (e *ErrDef) Unwrap() error {\n\treturn e.err\n}\n\nfunc (e *ErrDef) StatusCode() proto.StatusCode {\n\treturn e.ae.ErrCode\n}\n\n\n\n\nfunc NewError(err error, ae *proto.ActionableErr) *ErrDef {\n\treturn &ErrDef{\n\t\terr: err,\n\t\tae: ae,\n\t}\n}\n\n\nfunc NewErrorWithStatusCode(ae *proto.ActionableErr) *ErrDef {\n\treturn &ErrDef{\n\t\tae: ae,\n\t}\n}\n\nfunc IsSkaffoldErr(err error) bool {\n\tif _, ok := err.(Error); ok {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (e *ErrDef) Suggestions() []*proto.Suggestion ", "output": "{\n\treturn e.ae.Suggestions\n}"} {"input": "package registry\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/blevesearch/bleve/analysis\"\n)\n\nfunc RegisterTokenizer(name string, constructor TokenizerConstructor) {\n\t_, exists := tokenizers[name]\n\tif exists {\n\t\tpanic(fmt.Errorf(\"attempted to register duplicate tokenizer named '%s'\", name))\n\t}\n\ttokenizers[name] = constructor\n}\n\ntype TokenizerConstructor func(config map[string]interface{}, cache *Cache) (analysis.Tokenizer, error)\ntype TokenizerRegistry map[string]TokenizerConstructor\ntype TokenizerCache map[string]analysis.Tokenizer\n\nfunc (c TokenizerCache) TokenizerNamed(name string, cache *Cache) (analysis.Tokenizer, error) {\n\ttokenizer, cached := c[name]\n\tif cached {\n\t\treturn tokenizer, nil\n\t}\n\ttokenizerConstructor, registered := tokenizers[name]\n\tif !registered {\n\t\treturn nil, fmt.Errorf(\"no tokenizer with name or type '%s' registered\", name)\n\t}\n\ttokenizer, err := tokenizerConstructor(nil, cache)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error building tokenizer '%s': %v\", name, err)\n\t}\n\tc[name] = tokenizer\n\treturn tokenizer, nil\n}\n\n\n\nfunc TokenizerTypesAndInstances() ([]string, []string) {\n\temptyConfig := map[string]interface{}{}\n\temptyCache := NewCache()\n\ttypes := make([]string, 0)\n\tinstances := make([]string, 0)\n\tfor name, cons := range tokenizers {\n\t\t_, err := cons(emptyConfig, emptyCache)\n\t\tif err == nil {\n\t\t\tinstances = append(instances, name)\n\t\t} else {\n\t\t\ttypes = append(types, name)\n\t\t}\n\t}\n\treturn types, instances\n}\n\nfunc (c TokenizerCache) DefineTokenizer(name string, typ string, config map[string]interface{}, cache *Cache) (analysis.Tokenizer, error) ", "output": "{\n\t_, cached := c[name]\n\tif cached {\n\t\treturn nil, fmt.Errorf(\"tokenizer named '%s' already defined\", name)\n\t}\n\ttokenizerConstructor, registered := tokenizers[typ]\n\tif !registered {\n\t\treturn nil, fmt.Errorf(\"no tokenizer type '%s' registered\", typ)\n\t}\n\ttokenizer, err := tokenizerConstructor(config, cache)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error building tokenizer '%s': %v\", name, err)\n\t}\n\tc[name] = tokenizer\n\treturn tokenizer, nil\n}"} {"input": "package v1alpha1\n\nimport (\n\truntime \"k8s.io/apimachinery/pkg/runtime\"\n)\n\nvar _ runtime.NestedObjectDecoder = &AdmissionConfiguration{}\n\n\n\nfunc (c *AdmissionConfiguration) DecodeNestedObjects(d runtime.Decoder) error {\n\tfor k, v := range c.Plugins {\n\t\tdecodeNestedRawExtensionOrUnknown(d, &v.Configuration)\n\t\tc.Plugins[k] = v\n\t}\n\treturn nil\n}\n\nvar _ runtime.NestedObjectEncoder = &AdmissionConfiguration{}\n\n\n\nfunc (c *AdmissionConfiguration) EncodeNestedObjects(e runtime.Encoder) error {\n\tfor k, v := range c.Plugins {\n\t\tif err := encodeNestedRawExtension(e, &v.Configuration); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.Plugins[k] = v\n\t}\n\treturn nil\n}\n\nfunc decodeNestedRawExtensionOrUnknown(d runtime.Decoder, ext *runtime.RawExtension) {\n\tif ext.Raw == nil || ext.Object != nil {\n\t\treturn\n\t}\n\tobj, gvk, err := d.Decode(ext.Raw, nil, nil)\n\tif err != nil {\n\t\tunk := &runtime.Unknown{Raw: ext.Raw}\n\t\tif runtime.IsNotRegisteredError(err) {\n\t\t\tif _, gvk, err := d.Decode(ext.Raw, nil, unk); err == nil {\n\t\t\t\tunk.APIVersion = gvk.GroupVersion().String()\n\t\t\t\tunk.Kind = gvk.Kind\n\t\t\t\text.Object = unk\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif gvk != nil {\n\t\t\tunk.APIVersion = gvk.GroupVersion().String()\n\t\t\tunk.Kind = gvk.Kind\n\t\t}\n\t\tobj = unk\n\t}\n\text.Object = obj\n}\n\n\n\nfunc encodeNestedRawExtension(e runtime.Encoder, ext *runtime.RawExtension) error ", "output": "{\n\tif ext.Raw != nil || ext.Object == nil {\n\t\treturn nil\n\t}\n\tdata, err := runtime.Encode(e, ext.Object)\n\tif err != nil {\n\t\treturn err\n\t}\n\text.Raw = data\n\treturn nil\n}"} {"input": "package go1\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nvar (\n\tgobbytes []byte\n\tgobdata *JSONResponse\n)\n\n\n\n\nfunc gobResponse(r *JSONResponse) *JSONResponse {\n\treturn &JSONResponse{gobNode(r.Tree), r.Username}\n}\n\nfunc gobNode(n *JSONNode) *JSONNode {\n\tn1 := new(JSONNode)\n\t*n1 = *n\n\tif len(n1.Kids) == 0 {\n\t\tn1.Kids = nil\n\t} else {\n\t\tfor i, k := range n1.Kids {\n\t\t\tn1.Kids[i] = gobNode(k)\n\t\t}\n\t}\n\treturn n1\n}\n\nfunc gobdec() {\n\tif gobbytes == nil {\n\t\tpanic(\"gobdata not initialized\")\n\t}\n\tvar r JSONResponse\n\tif err := gob.NewDecoder(bytes.NewBuffer(gobbytes)).Decode(&r); err != nil {\n\t\tpanic(err)\n\t}\n\t_ = r\n}\n\nfunc gobenc() {\n\tif err := gob.NewEncoder(ioutil.Discard).Encode(&gobdata); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc BenchmarkGobDecode(b *testing.B) {\n\tb.SetBytes(int64(len(gobbytes)))\n\tfor i := 0; i < b.N; i++ {\n\t\tgobdec()\n\t}\n}\n\nfunc BenchmarkGobEncode(b *testing.B) {\n\tb.SetBytes(int64(len(gobbytes)))\n\tfor i := 0; i < b.N; i++ {\n\t\tgobenc()\n\t}\n}\n\nfunc init() ", "output": "{\n\tgobdata = gobResponse(&jsondata)\n\n\tvar buf bytes.Buffer\n\tif err := gob.NewEncoder(&buf).Encode(gobdata); err != nil {\n\t\tpanic(err)\n\t}\n\tgobbytes = buf.Bytes()\n\n\tvar r JSONResponse\n\tif err := gob.NewDecoder(bytes.NewBuffer(gobbytes)).Decode(&r); err != nil {\n\t\tpanic(err)\n\t}\n\tif !reflect.DeepEqual(gobdata, &r) {\n\t\tlog.Printf(\"%v\\n%v\", jsondata, r)\n\t\tb, _ := json.Marshal(&jsondata)\n\t\tbr, _ := json.Marshal(&r)\n\t\tlog.Printf(\"%s\\n%s\\n\", b, br)\n\t\tpanic(\"gob: encode+decode lost data\")\n\t}\n}"} {"input": "package azurerm\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/acctest\"\n\t\"github.com/hashicorp/terraform/helper/resource\"\n)\n\nfunc TestAccAzureRMNetworkWatcher_importBasic(t *testing.T) {\n\trInt := acctest.RandInt()\n\tresourceName := \"azurerm_network_watcher.test\"\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testCheckAzureRMNetworkWatcherDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAzureRMNetworkWatcher_basic(rInt, testLocation()),\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName: resourceName,\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\n\n\nfunc TestAccAzureRMNetworkWatcher_importComplete(t *testing.T) ", "output": "{\n\trInt := acctest.RandInt()\n\tresourceName := \"azurerm_network_watcher.test\"\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testCheckAzureRMNetworkWatcherDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAzureRMNetworkWatcher_complete(rInt, testLocation()),\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName: resourceName,\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}"} {"input": "package elasticsearch\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/luopengift/gohttp\"\n)\n\nconst (\n\tenter = '\\n'\n)\n\ntype Meta struct {\n\tIndex string `json:\"_index\"`\n\tType string `json:\"_type\"`\n\tId string `json:\"_id,omitempty\"`\n}\n\nfunc NewMeta(_index, _type, _id string) *Meta {\n\treturn &Meta{_index, _type, _id}\n}\n\ntype Bulk struct {\n\tIndex *Meta `json:\"index,omitempty\"`\n\tUpdate *Meta `json:\"update,omitempty\"`\n\tSource []byte `json:\"-\"`\n}\n\nfunc NewBulkIndex(_index, _type, _id string, source []byte) *Bulk {\n\treturn &Bulk{\n\t\tIndex: NewMeta(_index, _type, _id),\n\t\tSource: source,\n\t}\n}\nfunc NewBulkUpdate(_index, _type, _id string, source []byte) *Bulk {\n\treturn &Bulk{\n\t\tUpdate: NewMeta(_index, _type, _id),\n\t\tSource: source,\n\t}\n}\n\n\nfunc (b *Bulk) Bytes() ([]byte, error) {\n\tp, err := json.Marshal(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp = append(p, enter)\n\tp = append(p, b.Source...)\n\tp = append(p, enter)\n\treturn p, nil\n}\n\n\n\nfunc Send(addr string, p []byte) error ", "output": "{\n\tresp, err := gohttp.NewClient().URLString(\"http://\"+addr).Path(\"/_bulk\").Header(\"Accept\", \"application/json\").Body(p).Post()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.Code() != 200 {\n\t\treturn fmt.Errorf(resp.String())\n\t}\n\treturn nil\n\n}"} {"input": "package app\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/jaegertracing/jaeger/pkg/config\"\n)\n\n\n\nfunc TestCollectorOptionsWithFlags_CheckFullHostPort(t *testing.T) {\n\tc := &CollectorOptions{}\n\tv, command := config.Viperize(AddFlags)\n\tcommand.ParseFlags([]string{\n\t\t\"--collector.http-server.host-port=:5678\",\n\t\t\"--collector.grpc-server.host-port=127.0.0.1:1234\",\n\t\t\"--collector.zipkin.host-port=0.0.0.0:3456\",\n\t})\n\tc.InitFromViper(v)\n\n\tassert.Equal(t, \":5678\", c.CollectorHTTPHostPort)\n\tassert.Equal(t, \"127.0.0.1:1234\", c.CollectorGRPCHostPort)\n\tassert.Equal(t, \"0.0.0.0:3456\", c.CollectorZipkinHTTPHostPort)\n}\n\nfunc TestCollectorOptionsWithFlags_CheckHostPort(t *testing.T) ", "output": "{\n\tc := &CollectorOptions{}\n\tv, command := config.Viperize(AddFlags)\n\tcommand.ParseFlags([]string{\n\t\t\"--collector.http-server.host-port=5678\",\n\t\t\"--collector.grpc-server.host-port=1234\",\n\t\t\"--collector.zipkin.host-port=3456\",\n\t})\n\tc.InitFromViper(v)\n\n\tassert.Equal(t, \":5678\", c.CollectorHTTPHostPort)\n\tassert.Equal(t, \":1234\", c.CollectorGRPCHostPort)\n\tassert.Equal(t, \":3456\", c.CollectorZipkinHTTPHostPort)\n}"} {"input": "package cluster\n\nimport (\n\t\"net\"\n\n\t\"github.com/hashicorp/memberlist\"\n)\n\ntype Node struct {\n\tAddr string\n}\n\ntype Discovery interface {\n\tDiscover(addr ...string) (RemoteCluster, error)\n}\n\ntype RemoteCluster interface {\n\tMembers() []Node\n\tJoin(cb func(ip string) (net.Addr, error)) (Cluster, error)\n}\n\ntype Cluster interface {\n\tSelf() Node\n\tMembers() []Node\n\tLeave() error\n}\n\ntype gossipDiscovery struct {\n}\n\nfunc (gd *gossipDiscovery) Discover(addrs ...string) (RemoteCluster, error) {\n\tcfg := memberlist.DefaultLANConfig()\n\tlist, err := memberlist.Create(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = list.Join(addrs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &gossipCluster{list: list}, nil\n}\n\ntype gossipCluster struct {\n\tlist *memberlist.Memberlist\n}\n\n\n\nfunc (gd *gossipCluster) Join(cb func(ip string) (net.Addr, error)) (Cluster, error) {\n\taddr, err := cb(gd.list.LocalNode().Addr.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_ = addr\n\n\treturn nil, nil\n}\n\nfunc (gd *gossipCluster) Members() []Node ", "output": "{\n\n\n\n\treturn nil\n}"} {"input": "package library\n\nimport (\n\t\"strings\"\n\n\t\"github.com/facette/facette/pkg/config\"\n)\n\n\ntype Collection struct {\n\tItem\n\tEntries []*CollectionEntry `json:\"entries\"`\n\tParent *Collection `json:\"-\"`\n\tParentID string `json:\"parent\"`\n\tOptions map[string]interface{} `json:\"options\"`\n\tChildren []*Collection `json:\"-\"`\n}\n\n\ntype CollectionEntry struct {\n\tID string `json:\"id\"`\n\tOptions map[string]interface{} `json:\"options\"`\n}\n\n\n\n\nfunc (library *Library) FilterCollection(collection *Collection, filter string) *Collection ", "output": "{\n\tcollectionTemp := &Collection{}\n\t*collectionTemp = *collection\n\tcollectionTemp.Entries = nil\n\n\trefreshInterval, _ := config.GetInt(collectionTemp.Options, \"refresh_interval\", false)\n\n\tfor _, entry := range collection.Entries {\n\t\tif refreshInterval > 0 {\n\t\t\tif _, err := config.GetInt(entry.Options, \"refresh_interval\", true); err != nil {\n\t\t\t\tentry.Options[\"refresh_interval\"] = refreshInterval\n\t\t\t}\n\t\t}\n\n\t\tif enabled, err := config.GetBool(entry.Options, \"enabled\", false); err != nil || !enabled {\n\t\t\tcontinue\n\t\t} else if filter != \"\" {\n\t\t\tif title, err := config.GetString(entry.Options, \"title\", false); err != nil ||\n\t\t\t\t!strings.Contains(strings.ToLower(title), strings.ToLower(filter)) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tcollectionTemp.Entries = append(collectionTemp.Entries, entry)\n\t}\n\n\treturn collectionTemp\n}"} {"input": "package bolt\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc setUp(t *testing.T) (*Driver, func()) {\n\ttmpFile, err := ioutil.TempFile(\"\", \"\")\n\trequire.NoError(t, err, \"tmp file\")\n\n\tfilename := tmpFile.Name()\n\tdriver := &Driver{}\n\terr = driver.Open(filename)\n\trequire.NoError(t, err, \"open driver\")\n\n\treturn driver, func() {\n\t\tdriver.Close()\n\t\tos.Remove(filename)\n\t}\n}\n\n\n\nfunc TestPaperRepository(t *testing.T) ", "output": "{\n\tdriver, tearDown := setUp(t)\n\tdefer tearDown()\n\n\trepo := NewPaperRepository(driver)\n\n\tid, err := repo.Get(1, \"source 1\", \"ref 1\")\n\trequire.NoError(t, err, \"get non inserted u1 s1 r1\")\n\tassert.Equal(t, 0, id, \"get non inserted u1 s1 r1 - id\")\n\n\terr = repo.Save(1, 10, \"source 1\", \"ref 1\")\n\trequire.NoError(t, err, \"insert u1 p10 s1 r1\")\n\n\tid, err = repo.Get(1, \"source 1\", \"ref 1\")\n\trequire.NoError(t, err, \"get u1 s1 r1\")\n\tassert.Equal(t, 10, id, \"get u1 s1 r1 - id\")\n}"} {"input": "package backoff\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\n\ntype BackOffContext interface {\n\tBackOff\n\tContext() context.Context\n}\n\ntype backOffContext struct {\n\tBackOff\n\tctx context.Context\n}\n\n\n\n\nfunc WithContext(b BackOff, ctx context.Context) BackOffContext {\n\tif ctx == nil {\n\t\tpanic(\"nil context\")\n\t}\n\n\tif b, ok := b.(*backOffContext); ok {\n\t\treturn &backOffContext{\n\t\t\tBackOff: b.BackOff,\n\t\t\tctx: ctx,\n\t\t}\n\t}\n\n\treturn &backOffContext{\n\t\tBackOff: b,\n\t\tctx: ctx,\n\t}\n}\n\nfunc ensureContext(b BackOff) BackOffContext {\n\tif cb, ok := b.(BackOffContext); ok {\n\t\treturn cb\n\t}\n\treturn WithContext(b, context.Background())\n}\n\n\n\nfunc (b *backOffContext) NextBackOff() time.Duration {\n\tselect {\n\tcase <-b.ctx.Done():\n\t\treturn Stop\n\tdefault:\n\t}\n\tnext := b.BackOff.NextBackOff()\n\tif deadline, ok := b.ctx.Deadline(); ok && deadline.Sub(time.Now()) < next {\n\t\treturn Stop\n\t}\n\treturn next\n}\n\nfunc (b *backOffContext) Context() context.Context ", "output": "{\n\treturn b.ctx\n}"} {"input": "package service\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetServiceIDOKCode int = 200\n\n\ntype GetServiceIDOK struct {\n\n\tPayload *models.Service `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetServiceIDOK() *GetServiceIDOK {\n\n\treturn &GetServiceIDOK{}\n}\n\n\nfunc (o *GetServiceIDOK) WithPayload(payload *models.Service) *GetServiceIDOK {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *GetServiceIDOK) SetPayload(payload *models.Service) {\n\to.Payload = payload\n}\n\n\nfunc (o *GetServiceIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\n\nconst GetServiceIDNotFoundCode int = 404\n\n\ntype GetServiceIDNotFound struct {\n}\n\n\nfunc NewGetServiceIDNotFound() *GetServiceIDNotFound {\n\n\treturn &GetServiceIDNotFound{}\n}\n\n\n\n\nfunc (o *GetServiceIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}"} {"input": "package clock\n\nimport \"time\"\n\n\nvar Work Clock\n\nfunc init() {\n\tWork = New()\n}\n\n\n\n\nfunc Since(t time.Time) time.Duration {\n\treturn Work.Now().Sub(t)\n}\n\n\n\nfunc Sleep(d time.Duration) {\n\tWork.Sleep(d)\n}\n\n\n\nfunc After(d time.Duration) <-chan time.Time {\n\treturn Work.After(d)\n}\n\n\n\nfunc Tick(d time.Duration) <-chan time.Time {\n\treturn Work.Tick(d)\n}\n\n\n\n\n\nfunc Ticker(d time.Duration) *time.Ticker {\n\treturn Work.Ticker(d)\n}\n\n\ntype Clock interface {\n\n\tNow() time.Time\n\n\tSleep(d time.Duration)\n\n\tAfter(d time.Duration) <-chan time.Time\n\n\tTick(d time.Duration) <-chan time.Time\n\n\tTicker(d time.Duration) *time.Ticker\n\n}\n\n\ntype Mock interface {\n\tClock\n\n\n\tSet(t time.Time) Mock\n\n\tAdd(d time.Duration) Mock\n\n\tFreeze() Mock\n\n\tIsFrozen() bool\n\n\tUnfreeze() Mock\n\n\tClose()\n}\n\nfunc Now() time.Time ", "output": "{\n\treturn Work.Now()\n}"} {"input": "package main\n\nimport (\n\t\"github.com/tabone/websocket\"\n\t\"log\"\n\t\"net/http\"\n)\n\nvar m *manager\n\nfunc main() {\n\tm = &manager{\n\t\tusers: make(map[int]*websocket.Socket),\n\t}\n\thttp.HandleFunc(\"/ws\", wsHandler)\n\thttp.Handle(\"/\", http.FileServer(http.Dir(\"public/\")))\n\n\tlog.Println(\"listening on localhost:8080.\")\n\thttp.ListenAndServe(\"localhost:8080\", nil)\n}\n\n\n\nfunc wsHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tlog.Println(\"new connection\")\n\n\tq := &websocket.Request{\n\t\tCheckOrigin: func(r *http.Request) bool {\n\t\t\treturn true\n\t\t},\n\t}\n\n\ts, err := q.Upgrade(w, r)\n\n\tif err != nil {\n\t\tlog.Println(\"upgrade failed:\", err)\n\t}\n\n\tm.addSocket(s)\n}"} {"input": "package routetemplate\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\nvar routeTemplates []RouteTemplate\n\nfunc Add(template string) (err error) {\n\trouteTemplate, _ := Parse(template)\n\trouteTemplates = append(routeTemplates, routeTemplate)\n\treturn nil\n}\n\n\n\nfunc GetMatchTemplate(url string) (routeTemplateMatch RouteTemplateMatch, err error) {\n\n\trouteTemplateMatch = RouteTemplateMatch{}\n\tfor _, value := range routeTemplates {\n\t\twasMatched, _ := IsMatch(url, value)\n\t\tif wasMatched {\n\n\t\t\trouteTemplateMatch, _ = BindVariables(url, value)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn routeTemplateMatch, nil\n}\n\nfunc GetMatchedTemplate(url string) (template string, err error) {\n\ttemplate = \"\"\n\n\tfor _, value := range routeTemplates {\n\n\t\twasMatched, _ := IsMatch(url, value)\n\t\tif wasMatched {\n\t\t\ttemplate = value.TemplatePath\n\t\t\tbreak\n\t\t}\n\t}\n\treturn template, nil\n}\n\nfunc AddRoute(name string, method string, urlTemplate string, handler interface{}) {\n\tfmt.Printf(\"%q\\n\", handler)\n\tvar x reflect.Value\n\tif fv, ok := handler.(reflect.Value); ok {\n\t\tx = fv\n\t} else {\n\t\tx = reflect.ValueOf(handler)\n\t}\n\n\targs := make([]reflect.Value, 0, 0)\n\tx.Call(args)\n\tfmt.Printf(\"%q\\n\", x)\n}\n\nfunc GetAllTemplates() (templates []RouteTemplate, err error) {\n\treturn routeTemplates, nil\n}\n\nfunc ClearAllTemplates() (err error) {\n\trouteTemplates = make([]RouteTemplate, 0)\n\treturn nil\n}\n\nfunc GetMatchedTemplateString(url string) (template string, err error) ", "output": "{\n\ttemplate = \"\"\n\n\tfor _, value := range routeTemplates {\n\n\t\twasMatched, _ := IsMatch(url, value)\n\t\tif wasMatched {\n\t\t\ttemplate = value.TemplatePath\n\t\t\tbreak\n\t\t}\n\t}\n\treturn template, nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/arduino/arduino-create-agent/updater\"\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/kardianos/osext\"\n)\n\n\n\nfunc updateHandler(c *gin.Context) ", "output": "{\n\n\tpath, err := osext.Executable()\n\n\tif err != nil {\n\t\tc.JSON(500, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\tvar up = &updater.Updater{\n\t\tCurrentVersion: version,\n\t\tAPIURL: *updateUrl,\n\t\tBinURL: *updateUrl,\n\t\tDiffURL: \"\",\n\t\tDir: \"update/\",\n\t\tCmdName: *appName,\n\t}\n\n\terr = up.BackgroundRun()\n\n\tif err != nil {\n\t\tc.JSON(500, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\tpath = updater.TempPath(path)\n\n\tc.JSON(200, gin.H{\"success\": \"Please wait a moment while the agent reboots itself\"})\n\tSystray.Update(path)\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\ntype StorageState struct {\n\tHistoryState HistoryDB `json:\"history,omitempty\"`\n\tTrafficHistoryState map[int]*FlowSummary `json:\"traffichistory,omitempty\"`\n}\n\nfunc save(fp string) bool {\n\tHistory.RLock()\n\tTrafficHistory.RLock()\n\tdefer History.RUnlock()\n\tdefer TrafficHistory.RUnlock()\n\tss := StorageState{History.m, TrafficHistory.h}\n\treturn saveToFile(ss, fp)\n}\n\nfunc load(fp string) (StorageState, error) {\n\tf, err := os.Open(fp)\n\tif err != nil {\n\t\treturn StorageState{}, err\n\t}\n\tdefer f.Close()\n\n\tbbuf, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn StorageState{}, errors.New(\"Error: cannot load from file, failed read\")\n\t}\n\n\tss := StorageState{}\n\terr = json.Unmarshal(bbuf, &ss)\n\tif err != nil {\n\t\treturn StorageState{}, errors.New(\"Error on loading state from json\")\n\t}\n\tfmt.Println(\"Loaded state from disk\", fp)\n\treturn ss, nil\n}\n\n\n\nfunc saveToFile(ss StorageState, fp string) bool ", "output": "{\n\tb, err := json.Marshal(ss)\n\tif err != nil {\n\t\tfmt.Println(\"Error on dumping state to json:\", err)\n\t\treturn false\n\t}\n\n\tf, err := os.Create(fp)\n\tif err != nil {\n\t\tfmt.Println(\"Error on opening file\", fp, \":\", err)\n\t\treturn false\n\t}\n\tdefer f.Close()\n\n\tw := bufio.NewWriter(f)\n\tn, err := w.Write(b)\n\tif err != nil {\n\t\tfmt.Println(\"Error on writing file\", fp, \":\", err)\n\t\treturn false\n\t}\n\n\tw.Flush()\n\tfmt.Println(\"Wrote history to file in\", n, \"bytes\")\n\treturn true\n}"} {"input": "package frames\n\nimport \"testing\"\n\nfunc TestApicBasicOutput(t *testing.T) {\n\tx := NewFrame(\"APIC\", \"Attached picture\", Version3).(*APIC)\n\tif x.GetName() != \"APIC\" {\n\t\tt.Error(\"Invalid name from APIC frame\")\n\t}\n\n\tif x.GetExplain() != \"Attached picture\" {\n\t\tt.Error(\"Invalid APIC GetExplain() response\")\n\t}\n\n\tx.Name = \"BOB\"\n\tif x.GetName() != \"BOB\" {\n\t\tt.Error(\"Invalid APIC Name setting\")\n\t}\n}\n\nfunc TestApicProcess(t *testing.T) {\n\tx := NewFrame(\"APIC\", \"\", Version3).(*APIC)\n\tb := []byte(\"\\x00image/jpeg\\x00\\x03Something\\x00\\x01\\x02\\x00\")\n\n\tx.ProcessData(len(b), b)\n\texpected := 3\n\tfound := x.GetLength()\n\tif found != expected {\n\t\tt.Errorf(\"Got [%d], Expected [%d]\", found, expected)\n\t}\n}\n\n\n\nfunc TestApicInvalidPicType(t *testing.T) {\n\tx := NewFrame(\"APIC\", \"\", Version3).(*APIC)\n\tb := []byte(\"\\x00image/png\\x00\\x22Hello\\x00\\x01\\x02\\x03\")\n\n\tx.ProcessData(len(b), b)\n\texpected := \"Image (image/png, Other, 3b) Hello\\n\"\n\tfound := x.DisplayContent()\n\tif found != expected {\n\t\tt.Errorf(\"Got [%s], Expected [%s]\", found, expected)\n\t}\n}\n\nfunc TestApicProcessUtf16(t *testing.T) ", "output": "{\n\tx := NewFrame(\"APIC\", \"\", Version3).(*APIC)\n\tb := []byte(\"\\x01image/png\\x00\\x02\" +\n\t\t\"\\xfe\\xff\\x00B\\x00o\\x00b\\x00 \\x00i\\x00s\\x00 \\x00G\\x00r\\x00e\\x00a\\x00t\\x00\\x00\" +\n\t\t\"\\x01\\x02\\x03\")\n\n\tx.ProcessData(len(b), b)\n\texpected := \"Image (image/png, Other file icon, 3b) Bob is Great\\n\"\n\tfound := x.DisplayContent()\n\tif found != expected {\n\t\tt.Errorf(\"Got [%s], Expected [%s]\", found, expected)\n\t}\n}"} {"input": "package auth\n\nimport (\n\t\"golang.org/x/crypto/bcrypt\"\n\n\t\"github.com/nats-io/gnatsd/server\"\n)\n\n\ntype MultiUser struct {\n\tusers map[string]string\n}\n\n\nfunc NewMultiUser(users []server.User) *MultiUser {\n\tm := &MultiUser{users: make(map[string]string)}\n\tfor _, u := range users {\n\t\tm.users[u.Username] = u.Password\n\t}\n\treturn m\n}\n\n\n\n\nfunc (m *MultiUser) Check(c server.ClientAuth) bool ", "output": "{\n\topts := c.GetOpts()\n\tpass, ok := m.users[opts.Username]\n\tif !ok {\n\t\treturn false\n\t}\n\tif isBcrypt(pass) {\n\t\tif err := bcrypt.CompareHashAndPassword([]byte(pass), []byte(opts.Password)); err != nil {\n\t\t\treturn false\n\t\t}\n\t} else if pass != opts.Password {\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package types\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\nfunc HstoreScanner(typ reflect.Type) ScannerFunc {\n\tif typ.Key() == stringType && typ.Elem() == stringType {\n\t\treturn scanMapStringStringValue\n\t}\n\treturn func(v reflect.Value, rd Reader, n int) error {\n\t\treturn fmt.Errorf(\"pg.Hstore(unsupported %s)\", v.Type())\n\t}\n}\n\nfunc scanMapStringStringValue(v reflect.Value, rd Reader, n int) error {\n\tm, err := scanMapStringString(rd, n)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tv.Set(reflect.ValueOf(m))\n\treturn nil\n}\n\n\n\nfunc scanMapStringString(rd Reader, n int) (map[string]string, error) ", "output": "{\n\tif n == -1 {\n\t\treturn nil, nil\n\t}\n\n\tp := newHstoreParser(rd)\n\tm := make(map[string]string)\n\tfor {\n\t\tkey, err := p.NextKey()\n\t\tif err != nil {\n\t\t\tif err == errEndOfHstore {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalue, err := p.NextValue()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tm[string(key)] = string(value)\n\t}\n\treturn m, nil\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/nanobox-io/nanobox-server/util\"\n)\n\n\n\nfunc (api *API) LockCount(rw http.ResponseWriter, req *http.Request) {\n\tfmt.Fprintf(rw, \"%d\", util.LockCount())\n}\n\n\n\nfunc (api *API) Lock(rw http.ResponseWriter, req *http.Request) {\n\tutil.Lock()\n\tdefer util.Unlock()\n\n\tcNotify := rw.(http.CloseNotifier)\n\t<-cNotify.CloseNotify()\n}\n\nfunc (api *API) Suspend(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\tif util.LockCount() <= 0 {\n\t\treturn\n\t}\n\n\twriteBody(map[string]string{\"error\": fmt.Sprintf(\"Current lock count: %d\", util.LockCount())}, rw, http.StatusNotAcceptable)\n}"} {"input": "package pry\n\nimport (\n\t\"go/ast\"\n\t\"go/types\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\ntype JSImporter struct {\n\tpackages map[string]*types.Package\n\tDir map[string]*ast.Package\n}\n\n\n\nfunc (i *JSImporter) Import(path string) (*types.Package, error) ", "output": "{\n\tp, ok := i.packages[path]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"package %q not found\", path)\n\t}\n\treturn p, nil\n}"} {"input": "package main_test\n\nimport (\n\t\"testing\"\n\n\tmain \"github.com/influxdb/influxdb/cmd/influx\"\n)\n\nfunc TestParseCommand_CommandsExist(t *testing.T) {\n\tt.Parallel()\n\tc := main.CommandLine{}\n\ttests := []struct {\n\t\tcmd string\n\t}{\n\t\t{cmd: \"gopher\"},\n\t\t{cmd: \"connect\"},\n\t\t{cmd: \"help\"},\n\t\t{cmd: \"pretty\"},\n\t\t{cmd: \"use\"},\n\t\t{cmd: \"\"}, \n\t}\n\tfor _, test := range tests {\n\t\tif !c.ParseCommand(test.cmd) {\n\t\t\tt.Fatalf(`Command failed for %q.`, test.cmd)\n\t\t}\n\t}\n}\n\nfunc TestParseCommand_TogglePretty(t *testing.T) {\n\tt.Parallel()\n\tc := main.CommandLine{}\n\tif c.Pretty {\n\t\tt.Fatalf(`Pretty should be false.`)\n\t}\n\tc.ParseCommand(\"pretty\")\n\tif !c.Pretty {\n\t\tt.Fatalf(`Pretty should be true.`)\n\t}\n\tc.ParseCommand(\"pretty\")\n\tif c.Pretty {\n\t\tt.Fatalf(`Pretty should be false.`)\n\t}\n}\n\n\n\nfunc TestParseCommand_Use(t *testing.T) {\n\tt.Parallel()\n\tc := main.CommandLine{}\n\ttests := []struct {\n\t\tcmd string\n\t}{\n\t\t{cmd: \"use db\"},\n\t\t{cmd: \" use db\"},\n\t\t{cmd: \"use db \"},\n\t\t{cmd: \"Use db\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tif !c.ParseCommand(test.cmd) {\n\t\t\tt.Fatalf(`Command \"use\" failed for %q.`, test.cmd)\n\t\t}\n\t}\n}\n\nfunc TestParseCommand_Exit(t *testing.T) ", "output": "{\n\tt.Parallel()\n\tc := main.CommandLine{}\n\ttests := []struct {\n\t\tcmd string\n\t}{\n\t\t{cmd: \"exit\"},\n\t\t{cmd: \" exit\"},\n\t\t{cmd: \"exit \"},\n\t\t{cmd: \"Exit \"},\n\t}\n\n\tfor _, test := range tests {\n\t\tif c.ParseCommand(test.cmd) {\n\t\t\tt.Fatalf(`Command \"exit\" failed for %q.`, test.cmd)\n\t\t}\n\t}\n}"} {"input": "package anime\n\nimport (\n\t\"fmt\"\n\n\t\"bitbucket.org/ikeikeikeike/antenna/ormapper\"\n\t\"github.com/jinzhu/gorm\"\n)\n\n\n\nfunc PictureCountMoreThanZero(db *gorm.DB) *gorm.DB {\n\treturn db.Where(\"anime.pictures_count > ?\", 0)\n}\n\nfunc FilterNameKana(words []string) func(db *gorm.DB) *gorm.DB {\n\treturn func(db *gorm.DB) *gorm.DB {\n\t\tfor _, word := range words {\n\t\t\tif word != \"\" {\n\t\t\t\tw := fmt.Sprintf(\"%%%s%%\", word)\n\t\t\t\tdb = db.Where(\"anime.name like ? OR anime.kana like ?\", w, w)\n\t\t\t}\n\t\t}\n\t\treturn db\n\t}\n}\n\n\n\nfunc FilterPrefixLines(line string) func(db *gorm.DB) *gorm.DB ", "output": "{\n\treturn func(db *gorm.DB) *gorm.DB {\n\t\tif line != \"\" {\n\t\t\tin, ok := ormapper.PrefixLines[line]\n\t\t\tif ok {\n\t\t\t\tdb = db.Where(\"anime.gyou in (?)\", in)\n\t\t\t}\n\t\t}\n\t\treturn db\n\t}\n}"} {"input": "package glacier\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/rdwilliamson/aws\"\n)\n\n\ntype Connection struct {\n\tClient *http.Client\n\n\tSignature *aws.Signature\n}\n\nfunc (c *Connection) client() *http.Client {\n\tif c.Client == nil {\n\t\treturn http.DefaultClient\n\t}\n\treturn c.Client\n}\n\n\nfunc (c *Connection) vault(vault string) string {\n\treturn \"https://\" + c.Signature.Region.Glacier + \"/-/vaults/\" + vault\n}\n\n\nfunc (c *Connection) policy(policy string) string {\n\treturn \"https://\" + c.Signature.Region.Glacier + \"/-/policies/\" + policy\n}\n\n\n\nfunc NewConnection(secret, access string, r *aws.Region) *Connection {\n\treturn &Connection{\n\t\tSignature: aws.NewSignature(secret, access, r, \"glacier\"),\n\t}\n}\n\n\n\n\nfunc toHex(x []byte) string {\n\treturn fmt.Sprintf(\"%x\", x)\n}\n\n\n\ntype parameters url.Values\n\n\n\n\n\n\n\nfunc (p parameters) encode() string {\n\tif encoded := url.Values(p).Encode(); encoded != \"\" {\n\t\treturn \"?\" + encoded\n\t}\n\treturn \"\"\n}\n\nfunc (p parameters) add(key, value string) ", "output": "{\n\turl.Values(p).Add(key, value)\n}"} {"input": "package core\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype BootVolumeSourceDetails interface {\n}\n\ntype bootvolumesourcedetails struct {\n\tJsonData []byte\n\tType string `json:\"type\"`\n}\n\n\nfunc (m *bootvolumesourcedetails) UnmarshalJSON(data []byte) error {\n\tm.JsonData = data\n\ttype Unmarshalerbootvolumesourcedetails bootvolumesourcedetails\n\ts := struct {\n\t\tModel Unmarshalerbootvolumesourcedetails\n\t}{}\n\terr := json.Unmarshal(data, &s.Model)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Type = s.Model.Type\n\n\treturn err\n}\n\n\nfunc (m *bootvolumesourcedetails) UnmarshalPolymorphicJSON(data []byte) (interface{}, error) {\n\n\tif data == nil || string(data) == \"null\" {\n\t\treturn nil, nil\n\t}\n\n\tvar err error\n\tswitch m.Type {\n\tcase \"bootVolumeBackup\":\n\t\tmm := BootVolumeSourceFromBootVolumeBackupDetails{}\n\t\terr = json.Unmarshal(data, &mm)\n\t\treturn mm, err\n\tcase \"bootVolume\":\n\t\tmm := BootVolumeSourceFromBootVolumeDetails{}\n\t\terr = json.Unmarshal(data, &mm)\n\t\treturn mm, err\n\tcase \"bootVolumeReplica\":\n\t\tmm := BootVolumeSourceFromBootVolumeReplicaDetails{}\n\t\terr = json.Unmarshal(data, &mm)\n\t\treturn mm, err\n\tdefault:\n\t\treturn *m, nil\n\t}\n}\n\n\n\nfunc (m bootvolumesourcedetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package token\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n)\n\n\nfunc PrettyPrintTree(w io.Writer, root Token) {\n\tprettyPrintTreeRek(w, root, 0)\n}\n\nfunc prettyPrintTreeRek(w io.Writer, tok Token, level int) {\n\t_, _ = fmt.Fprintf(w, \"%s(%p)%#v %d Permutations\\n\", strings.Repeat(\"\\t\", level), tok, tok, tok.Permutations())\n\n\tswitch t := tok.(type) {\n\tcase ForwardToken:\n\t\tif v := t.Get(); v != nil {\n\t\t\tprettyPrintTreeRek(w, v, level+1)\n\t\t}\n\tcase ListToken:\n\t\tfor i := 0; i < t.Len(); i++ {\n\t\t\tc, _ := t.Get(i)\n\n\t\t\tprettyPrintTreeRek(w, c, level+1)\n\t\t}\n\t}\n}\n\n\n\n\nfunc prettyPrintInternalTreeRek(w io.Writer, tok Token, level int) {\n\t_, _ = fmt.Fprintf(w, \"%s(%p)%#v\\n\", strings.Repeat(\"\\t\", level), tok, tok)\n\n\tswitch t := tok.(type) {\n\tcase ForwardToken:\n\t\tif v := t.InternalGet(); v != nil {\n\t\t\tprettyPrintInternalTreeRek(w, v, level+1)\n\t\t}\n\tcase ListToken:\n\t\tfor i := 0; i < t.InternalLen(); i++ {\n\t\t\tc, _ := t.InternalGet(i)\n\n\t\t\tprettyPrintInternalTreeRek(w, c, level+1)\n\t\t}\n\t}\n}\n\nfunc PrettyPrintInternalTree(w io.Writer, root Token) ", "output": "{\n\tprettyPrintInternalTreeRek(w, root, 0)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"sync\"\n)\n\nvar mu sync.Mutex\nvar count int\n\nfunc main() {\n\thttp.HandleFunc(\"/\", handler)\n\thttp.HandleFunc(\"/count\", counter)\n\tlog.Fatal(http.ListenAndServe(\"localhost:8000\", nil))\n}\n\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\tmu.Lock()\n\tcount++\n\tmu.Unlock()\n\tfmt.Fprintf(w, \"URL.Path = %q\\n\", r.URL.Path)\n\tfmt.Fprintf(w, \"%s %s %s\\n\", r.Method, r.URL, r.Proto)\n\tfor k, v := range r.Header {\n\t\tfmt.Fprintf(w, \"Header[%q] = %q\\n\", k, v)\n\t}\n\tfmt.Fprintf(w, \"Host = %q\\n\", r.Host)\n\tfmt.Fprintf(w, \"RemoteAddr = %q\\n\", r.RemoteAddr)\n\tif err := r.ParseForm(); err != nil {\n\t\tlog.Print(err)\n\t}\n\tfor k, v := range r.Form {\n\t\tfmt.Fprintf(w, \"Form[%q] = %q\\n\", k, v)\n\t}\n}\n\n\n\n\nfunc counter(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tmu.Lock()\n\tfmt.Fprintf(w, \"Count %d\\n\", count)\n\tmu.Unlock()\n}"} {"input": "package v2\n\nimport (\n\t\"os\"\n\n\t\"code.cloudfoundry.org/cli/cf/cmd\"\n\t\"code.cloudfoundry.org/cli/command\"\n\t\"code.cloudfoundry.org/cli/command/flag\"\n)\n\ntype SSHEnabledCommand struct {\n\tRequiredArgs flag.AppName `positional-args:\"yes\"`\n\tusage interface{} `usage:\"CF_NAME ssh-enabled APP_NAME\"`\n\trelatedCommands interface{} `related_commands:\"enable-ssh, space-ssh-allowed, ssh\"`\n}\n\nfunc (_ SSHEnabledCommand) Setup(config command.Config, ui command.UI) error {\n\treturn nil\n}\n\n\n\nfunc (_ SSHEnabledCommand) Execute(args []string) error ", "output": "{\n\tcmd.Main(os.Getenv(\"CF_TRACE\"), os.Args)\n\treturn nil\n}"} {"input": "package aes\n\nimport (\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\n\t\"github.com/golang/glog\"\n)\n\ntype aesInfo struct {\n\tkeyLen int\n\tivLen int\n}\n\nvar info = map[string]aesInfo{\n\t\"aes-128-cfb\": aesInfo{keyLen: 16, ivLen: 16},\n\t\"aes-192-cfb\": aesInfo{keyLen: 24, ivLen: 16},\n\t\"aes-256-cfb\": aesInfo{keyLen: 32, ivLen: 16},\n}\n\n\ntype AES struct {\n\tName string\n}\n\n\nfunc NewAES(aesType string) (*AES, error) {\n\talg := &AES{\n\t\tName: aesType,\n\t}\n\treturn alg, nil\n}\n\n\n\n\n\nfunc (a *AES) GetIVLen() int {\n\tv, ok := info[a.Name]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\treturn v.ivLen\n}\n\nfunc (a *AES) GetKeyLen() int {\n\tv, ok := info[a.Name]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\treturn v.keyLen\n}\n\nfunc (a *AES) NewStream(key, iv []byte, encrypt bool) (cipher.Stream, error) ", "output": "{\n\tglog.V(5).Infoln(\"New Aes Stream\")\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif encrypt {\n\t\treturn cipher.NewCFBEncrypter(block, iv), nil\n\t}\n\treturn cipher.NewCFBDecrypter(block, iv), nil\n}"} {"input": "package network\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype basicProcessor struct {\n\tenvChan chan Message\n}\n\nfunc (bp *basicProcessor) Process(from Address, msg Message) {\n\tbp.envChan <- msg\n}\n\ntype basicMessage struct {\n\tValue int\n}\n\nfunc TestBlockingDispatcher(t *testing.T) {\n\n\tdispatcher := NewBlockingDispatcher()\n\tprocessor := &basicProcessor{make(chan Message, 1)}\n\taddr := NewLocalAddress(\"blou\")\n\terr := dispatcher.Dispatch(addr, &basicMessage{10})\n\n\tif err == nil {\n\t\tt.Error(\"Dispatcher should have returned an error\")\n\t}\n\n\tdispatcher.RegisterProcessor(processor, basicMessage{})\n\tdispatcher.Dispatch(addr, &basicMessage{10})\n\n\tselect {\n\tcase m := <-processor.envChan:\n\t\tmsg, ok := m.(*basicMessage)\n\t\tassert.True(t, ok)\n\t\tassert.Equal(t, msg.Value, 10)\n\tdefault:\n\t\tt.Error(\"No message received\")\n\t}\n\n\tvar found bool\n\tdispatcher.RegisterProcessorFunc(basicMessage{}, func(from Address, msg Message) {\n\t\tfound = true\n\t})\n\tdispatcher.Dispatch(addr, basicMessage{10})\n\n\tif !found {\n\t\tt.Error(\"ProcessorFunc should have set to true\")\n\t}\n}\n\n\n\nfunc TestDefaultProcessor(t *testing.T) {\n\tvar okCh = make(chan bool, 1)\n\tpr := defaultProcessor{func(from Address, msg Message) {\n\t\tokCh <- true\n\t}}\n\n\tpr.Process(NewLocalAddress(\"blou\"), &basicMessage{})\n\tselect {\n\tcase <-okCh:\n\tdefault:\n\t\tt.Error(\"no ack received...\")\n\t}\n}\n\nfunc TestRoutineDispatcher(t *testing.T) ", "output": "{\n\n\tdispatcher := NewRoutineDispatcher()\n\tif dispatcher == nil {\n\t\tt.Fatal(\"nil dispatcher\")\n\t}\n\tprocessor := &basicProcessor{make(chan Message, 1)}\n\n\taddr := NewLocalAddress(\"blou\")\n\terr := dispatcher.Dispatch(addr, basicMessage{10})\n\n\tif err == nil {\n\t\tt.Error(\"Dispatcher should have returned an error\")\n\t}\n\n\tdispatcher.RegisterProcessor(processor, &basicMessage{})\n\tdispatcher.Dispatch(addr, basicMessage{10})\n\n\tselect {\n\tcase m := <-processor.envChan:\n\t\tmsg, ok := m.(basicMessage)\n\t\tassert.True(t, ok)\n\t\tassert.Equal(t, msg.Value, 10)\n\tcase <-time.After(100 * time.Millisecond):\n\t\tt.Error(\"No message received\")\n\n\t}\n}"} {"input": "package things\n\n\n\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\tgolangswaggerpaths \"path\"\n\t\"strings\"\n\n\t\"github.com/go-openapi/strfmt\"\n)\n\n\ntype ThingsReferencesUpdateURL struct {\n\tID strfmt.UUID\n\tPropertyName string\n\n\t_basePath string\n\t_ struct{}\n}\n\n\n\n\nfunc (o *ThingsReferencesUpdateURL) WithBasePath(bp string) *ThingsReferencesUpdateURL {\n\to.SetBasePath(bp)\n\treturn o\n}\n\n\n\n\nfunc (o *ThingsReferencesUpdateURL) SetBasePath(bp string) {\n\to._basePath = bp\n}\n\n\n\n\n\nfunc (o *ThingsReferencesUpdateURL) Must(u *url.URL, err error) *url.URL {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif u == nil {\n\t\tpanic(\"url can't be nil\")\n\t}\n\treturn u\n}\n\n\nfunc (o *ThingsReferencesUpdateURL) String() string {\n\treturn o.Must(o.Build()).String()\n}\n\n\nfunc (o *ThingsReferencesUpdateURL) BuildFull(scheme, host string) (*url.URL, error) {\n\tif scheme == \"\" {\n\t\treturn nil, errors.New(\"scheme is required for a full url on ThingsReferencesUpdateURL\")\n\t}\n\tif host == \"\" {\n\t\treturn nil, errors.New(\"host is required for a full url on ThingsReferencesUpdateURL\")\n\t}\n\n\tbase, err := o.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbase.Scheme = scheme\n\tbase.Host = host\n\treturn base, nil\n}\n\n\nfunc (o *ThingsReferencesUpdateURL) StringFull(scheme, host string) string {\n\treturn o.Must(o.BuildFull(scheme, host)).String()\n}\n\nfunc (o *ThingsReferencesUpdateURL) Build() (*url.URL, error) ", "output": "{\n\tvar _result url.URL\n\n\tvar _path = \"/things/{id}/references/{propertyName}\"\n\n\tid := o.ID.String()\n\tif id != \"\" {\n\t\t_path = strings.Replace(_path, \"{id}\", id, -1)\n\t} else {\n\t\treturn nil, errors.New(\"id is required on ThingsReferencesUpdateURL\")\n\t}\n\n\tpropertyName := o.PropertyName\n\tif propertyName != \"\" {\n\t\t_path = strings.Replace(_path, \"{propertyName}\", propertyName, -1)\n\t} else {\n\t\treturn nil, errors.New(\"propertyName is required on ThingsReferencesUpdateURL\")\n\t}\n\n\t_basePath := o._basePath\n\tif _basePath == \"\" {\n\t\t_basePath = \"/v1\"\n\t}\n\t_result.Path = golangswaggerpaths.Join(_basePath, _path)\n\n\treturn &_result, nil\n}"} {"input": "package api\n\nimport (\n\t\"debug/gosym\"\n\t\"github.com/derekparker/delve/proc\"\n)\n\n\nfunc ConvertBreakpoint(bp *proc.Breakpoint) *Breakpoint {\n\treturn &Breakpoint{\n\t\tID: bp.ID,\n\t\tFunctionName: bp.FunctionName,\n\t\tFile: bp.File,\n\t\tLine: bp.Line,\n\t\tAddr: bp.Addr,\n\t}\n}\n\n\nfunc ConvertThread(th *proc.Thread) *Thread {\n\tvar (\n\t\tfunction *Function\n\t\tfile string\n\t\tline int\n\t\tpc uint64\n\t)\n\n\tloc, err := th.Location()\n\tif err == nil {\n\t\tpc = loc.PC\n\t\tfile = loc.File\n\t\tline = loc.Line\n\t\tfunction = ConvertFunction(loc.Fn)\n\t}\n\n\treturn &Thread{\n\t\tID: th.Id,\n\t\tPC: pc,\n\t\tFile: file,\n\t\tLine: line,\n\t\tFunction: function,\n\t}\n}\n\n\nfunc ConvertVar(v *proc.Variable) Variable {\n\treturn Variable{\n\t\tName: v.Name,\n\t\tValue: v.Value,\n\t\tType: v.Type,\n\t}\n}\n\nfunc ConvertFunction(fn *gosym.Func) *Function {\n\tif fn == nil {\n\t\treturn nil\n\t}\n\n\treturn &Function{\n\t\tName: fn.Name,\n\t\tType: fn.Type,\n\t\tValue: fn.Value,\n\t\tGoType: fn.GoType,\n\t}\n}\n\n\n\n\nfunc ConvertLocation(loc proc.Location) Location {\n\treturn Location{\n\t\tPC: loc.PC,\n\t\tFile: loc.File,\n\t\tLine: loc.Line,\n\t\tFunction: ConvertFunction(loc.Fn),\n\t}\n}\n\nfunc ConvertGoroutine(g *proc.G) *Goroutine ", "output": "{\n\treturn &Goroutine{\n\t\tID: g.Id,\n\t\tPC: g.PC,\n\t\tFile: g.File,\n\t\tLine: g.Line,\n\t\tFunction: ConvertFunction(g.Func),\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"errors\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/bitly/go-simplejson\"\n)\n\n\n\nfunc RequestUnparsedResponse(url string, header http.Header) (\n\tresponse *http.Response, err error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed building request for \" +\n\t\t\turl + \": \" + err.Error())\n\t}\n\treq.Header = header\n\n\thttpclient := &http.Client{}\n\tif response, err = httpclient.Do(req); err != nil {\n\t\treturn nil, errors.New(\"request failed for \" +\n\t\t\turl + \": \" + err.Error())\n\t}\n\treturn\n}\n\nfunc Request(req *http.Request) (*simplejson.Json, error) ", "output": "{\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tresp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != 200 {\n\t\tlog.Printf(\"got response code %d - %s\", resp.StatusCode, body)\n\t\treturn nil, errors.New(\"api request returned non 200 status code\")\n\t}\n\tdata, err := simplejson.NewJson(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}"} {"input": "package obj\n\n\n\nconst (\n\tLOG = 5\n)\n\nfunc mkfwd(sym *LSym) {\n\tvar dwn [LOG]int32\n\tvar cnt [LOG]int32\n\tvar lst [LOG]*Prog\n\n\tfor i := 0; i < LOG; i++ {\n\t\tif i == 0 {\n\t\t\tcnt[i] = 1\n\t\t} else {\n\t\t\tcnt[i] = LOG * cnt[i-1]\n\t\t}\n\t\tdwn[i] = 1\n\t\tlst[i] = nil\n\t}\n\n\ti := 0\n\tfor p := sym.Func.Text; p != nil && p.Link != nil; p = p.Link {\n\t\ti--\n\t\tif i < 0 {\n\t\t\ti = LOG - 1\n\t\t}\n\t\tp.Forwd = nil\n\t\tdwn[i]--\n\t\tif dwn[i] <= 0 {\n\t\t\tdwn[i] = cnt[i]\n\t\t\tif lst[i] != nil {\n\t\t\t\tlst[i].Forwd = p\n\t\t\t}\n\t\t\tlst[i] = p\n\t\t}\n\t}\n}\n\n\n\nfunc Appendp(q *Prog, newprog ProgAlloc) *Prog ", "output": "{\n\tp := newprog()\n\tp.Link = q.Link\n\tq.Link = p\n\tp.Pos = q.Pos\n\treturn p\n}"} {"input": "package gull\n\nimport \"fmt\"\n\ntype ConfigLeaf struct {\n\tPath string\n\tValue string\n}\n\ntype ConfigLeaves struct {\n\tEntries []ConfigLeaf\n}\n\n\n\nfunc (c *ConfigLeaves) GetValue(path string) (string, error) {\n\tfor _, leaf := range c.Entries {\n\t\tif leaf.Path == path {\n\t\t\treturn leaf.Value, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"No value found at path [%v]\", path)\n}\n\nfunc NewConfigLeaves() (*ConfigLeaves, error) ", "output": "{\n\treturn &ConfigLeaves{\n\t\tEntries: []ConfigLeaf{},\n\t}, nil\n}"} {"input": "package users\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime/middleware\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\n\n\n\n\n\n\ntype DeleteUserByIDParams struct {\n\n\tHTTPRequest *http.Request `json:\"-\"`\n\n\tUserID string\n}\n\n\n\nfunc (o *DeleteUserByIDParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {\n\tvar res []error\n\to.HTTPRequest = r\n\n\trUserID, rhkUserID, _ := route.Params.GetOK(\"userID\")\n\tif err := o.bindUserID(rUserID, rhkUserID, route.Formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (o *DeleteUserByIDParams) bindUserID(rawData []string, hasKey bool, formats strfmt.Registry) error {\n\tvar raw string\n\tif len(rawData) > 0 {\n\t\traw = rawData[len(rawData)-1]\n\t}\n\n\to.UserID = raw\n\n\treturn nil\n}\n\nfunc NewDeleteUserByIDParams() DeleteUserByIDParams ", "output": "{\n\tvar ()\n\treturn DeleteUserByIDParams{}\n}"} {"input": "package store\n\nimport \"strings\"\n\n\ntype ByPathLen []string\n\nfunc (s ByPathLen) Len() int { return len(s) }\n\n\n\nfunc (s ByPathLen) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\n\ntype ByLen []string\n\n\nfunc (s ByLen) Len() int { return len(s) }\n\n\nfunc (s ByLen) Less(i, j int) bool { return len(s[i]) > len(s[j]) }\n\n\nfunc (s ByLen) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s ByPathLen) Less(i, j int) bool ", "output": "{\n\treturn strings.Count(s[i], \"/\") < strings.Count(s[j], \"/\")\n}"} {"input": "package handlers\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/doubledutch/dd-vote/api/auth\"\n\t\"github.com/jinzhu/gorm\"\n\n\t\"github.com/doubledutch/dd-vote/api/models/resp\"\n\t\"github.com/doubledutch/dd-vote/api/models/table\"\n\t\"github.com/gin-gonic/gin\"\n)\n\n\ntype CommentHandler struct {\n\tdb *gorm.DB\n}\n\n\n\n\n\nfunc (handler CommentHandler) CreateComment(c *gin.Context) {\n\tpostUUID := c.Param(\"puuid\")\n\tvar post table.Post\n\tif err := handler.db.Where(\"uuid = ?\", postUUID).First(&post).Error; err != nil {\n\t\tc.JSON(http.StatusNotFound, resp.APIResponse{IsError: true, Message: \"Question does not exist\"})\n\t\treturn\n\t}\n\n\tvar comment table.Comment\n\tc.Bind(&comment)\n\tif !comment.IsValidForCreate() {\n\t\tc.JSON(http.StatusBadRequest, resp.APIResponse{IsError: true, Message: \"Invalid data\"})\n\t\treturn\n\t}\n\tcomment.PostID = post.ID\n\tcomment.UserID = auth.GetUserIDFromCookie(c)\n\n\tif err := handler.db.Create(&comment).Error; err != nil {\n\t\tc.JSON(http.StatusInternalServerError, resp.APIResponse{IsError: true, Message: \"Unknown error\"})\n\t\treturn\n\t}\n\n\thandler.db.Preload(\"User\").Find(&comment)\n\n\tc.JSON(http.StatusCreated, resp.APIResponse{IsError: false, Value: comment})\n}\n\nfunc NewCommentHandler(db *gorm.DB) *CommentHandler ", "output": "{\n\treturn &CommentHandler{db: db}\n}"} {"input": "package app\n\n\n\n\nimport \"C\"\nimport (\n\t\"runtime\"\n\t\"sync\"\n\n\t\"grate/backend/mobile/event\"\n\t\"grate/backend/mobile/geom\"\n\t\"grate/backend/mobile/gl\"\n)\n\nvar cb Callbacks\n\nfunc run(callbacks Callbacks) {\n\truntime.LockOSThread()\n\tcb = callbacks\n\tC.runApp()\n}\n\n\n\n\nvar events struct {\n\tsync.Mutex\n\tpending []event.Touch\n}\n\nfunc sendTouch(ty event.TouchType, x, y float32) {\n\tevents.Lock()\n\tevents.pending = append(events.pending, event.Touch{\n\t\tType: ty,\n\t\tLoc: geom.Point{\n\t\t\tX: geom.Pt(float32(x)/ geom.PixelsPerPt),\n\t\t\tY: geom.Pt(float32(y)/ geom.PixelsPerPt),\n\t\t},\n\t})\n\tevents.Unlock()\n}\n\n\nfunc onTouchStart(x, y float32) { sendTouch(event.TouchStart, x, y) }\n\n\nfunc onTouchMove(x, y float32) { sendTouch(event.TouchMove, x, y) }\n\n\nfunc onTouchEnd(x, y float32) { sendTouch(event.TouchEnd, x, y) }\n\nvar started bool\n\n\nfunc onDraw() {\n\tif !started {\n\t\tcb.Start()\n\t\tstarted = true\n\t}\n\n\tevents.Lock()\n\tpending := events.pending\n\tevents.pending = nil\n\tevents.Unlock()\n\n\tfor _, e := range pending {\n\t\tif cb.Touch != nil {\n\t\t\tcb.Touch(e)\n\t\t}\n\t}\n\tif cb.Draw != nil {\n\t\tcb.Draw()\n\t}\n}\n\nfunc onResize(w, h int) ", "output": "{\n\tgeom.PixelsPerPt = 72\n\tgeom.Width = geom.Pt(float32(w)/ geom.PixelsPerPt)\n\tgeom.Height = geom.Pt(float32(h)/ geom.PixelsPerPt)\n\tgl.Viewport(0, 0, w, h);\n}"} {"input": "package main\n \nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n \nfunc main() {\n \n slice := generateSlice(20)\n fmt.Println(\"\\n--- Unsorted --- \\n\\n\", slice)\n quicksort(slice)\n fmt.Println(\"\\n--- Sorted ---\\n\\n\", slice, \"\\n\")\n}\n \n\n\n \nfunc quicksort(a []int) []int {\n if len(a) < 2 {\n return a\n }\n \n left, right := 0, len(a)-1\n \n pivot := rand.Int() % len(a)\n \n a[pivot], a[right] = a[right], a[pivot]\n \n for i, _ := range a {\n if a[i] < a[right] {\n a[left], a[i] = a[i], a[left]\n left++\n }\n }\n \n a[left], a[right] = a[right], a[left]\n \n quicksort(a[:left])\n quicksort(a[left+1:])\n \n return a\n}\n\nfunc generateSlice(size int) []int ", "output": "{\n \n slice := make([]int, size, size)\n rand.Seed(time.Now().UnixNano())\n for i := 0; i < size; i++ {\n slice[i] = rand.Intn(999) - rand.Intn(999)\n }\n return slice\n}"} {"input": "package dchan\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype SimpleReq struct {\n\tHeader Header\n\tBody io.ReadCloser\n}\n\ntype Header []header\n\nfunc (h Header) get(k string) int {\n\tfor idx := range h {\n\t\tif strings.EqualFold(h[idx].Name, k) {\n\t\t\treturn idx\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (h Header) Get(k string) string {\n\tidx := h.get(k)\n\tif idx < 0 {\n\t\treturn \"\"\n\t}\n\treturn h[idx].Values[0]\n}\n\n\n\ntype header struct {\n\tName string\n\tValues []string\n}\n\nfunc NewSimpleReq(r *bufio.Reader) (*SimpleReq, error) {\n\tsr := &SimpleReq{\n\t\tHeader: make(Header, 0, 16),\n\t}\n\n\tfor {\n\t\tline, err := r.ReadSlice('\\n')\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(line) == 2 {\n\t\t\tbreak\n\t\t}\n\n\t\tif idx := bytes.Index(line, []byte(\":\")); idx > 0 {\n\t\t\tsr.Header.Add(string(line[:idx]), string(bytes.TrimSpace(line[idx+1:])))\n\t\t}\n\t}\n\n\tcl := sr.Header.Get(\"Content-Length\")\n\tif n, _ := strconv.Atoi(cl); n > 0 {\n\t\tsr.Body = ioutil.NopCloser(io.LimitReader(r, int64(n)))\n\t} else {\n\t\tsr.Body = ioutil.NopCloser(r)\n\t}\n\treturn sr, nil\n}\n\nfunc (h *Header) Add(k string, v string) ", "output": "{\n\tidx := h.get(k)\n\tif idx < 0 {\n\t\t*h = append(*h, header{k, []string{v}})\n\t} else {\n\t\t(*h)[idx].Values = append((*h)[idx].Values, v)\n\t}\n}"} {"input": "package yarn_client\n\nimport (\n\t\"github.com/hortonworks/gohadoop/hadoop_yarn\"\n)\n\ntype AMNMClient struct {\n\tclient hadoop_yarn.ContainerManagementProtocolService\n}\n\n\n\nfunc (c *AMNMClient) StartContainer(container *hadoop_yarn.ContainerProto, containerLaunchContext *hadoop_yarn.ContainerLaunchContextProto) error {\n\trequest := hadoop_yarn.StartContainersRequestProto{StartContainerRequest: []*hadoop_yarn.StartContainerRequestProto{&hadoop_yarn.StartContainerRequestProto{ContainerLaunchContext: containerLaunchContext, Container: container, ContainerToken: container.GetContainerToken()}}}\n\tresponse := hadoop_yarn.StartContainersResponseProto{}\n\treturn c.client.StartContainers(&request, &response)\n}\n\nfunc CreateAMNMClient(host string, port int) (*AMNMClient, error) ", "output": "{\n\tc, err := hadoop_yarn.DialContainerManagementProtocolService(host, port)\n\treturn &AMNMClient{client: c}, err\n}"} {"input": "package ble\n\nimport (\n\t\"testing\"\n\n\t\"gobot.io/x/gobot/gobottest\"\n)\n\nfunc initTestBLESerialPort() *SerialPort {\n\treturn NewSerialPort(\"TEST123\", \"123\", \"456\")\n}\n\n\n\nfunc TestBLESerialPort(t *testing.T) ", "output": "{\n\td := initTestBLESerialPort()\n\tgobottest.Assert(t, d.Address(), \"TEST123\")\n}"} {"input": "package labelindex_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"github.com/onsi/ginkgo/reporters\"\n\n\t\"github.com/projectcalico/calico/libcalico-go/lib/testutils\"\n)\n\nfunc init() {\n\ttestutils.HookLogrusForGinkgo()\n}\n\n\n\nfunc TestLabels(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tjunitReporter := reporters.NewJUnitReporter(\"../report/labels_suite.xml\")\n\tRunSpecsWithDefaultAndCustomReporters(t, \"Labels Suite\", []Reporter{junitReporter})\n}"} {"input": "package dml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/dml\"\n)\n\n\n\nfunc TestEG_LineJoinPropertiesMarshalUnmarshal(t *testing.T) {\n\tv := dml.NewEG_LineJoinProperties()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := dml.NewEG_LineJoinProperties()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestEG_LineJoinPropertiesConstructor(t *testing.T) ", "output": "{\n\tv := dml.NewEG_LineJoinProperties()\n\tif v == nil {\n\t\tt.Errorf(\"dml.NewEG_LineJoinProperties must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed dml.EG_LineJoinProperties should validate: %s\", err)\n\t}\n}"} {"input": "package fabenc\n\nimport (\n\t\"io\"\n\n\t\"go.uber.org/zap/buffer\"\n\t\"go.uber.org/zap/zapcore\"\n)\n\n\n\ntype FormatEncoder struct {\n\tzapcore.Encoder\n\tformatters []Formatter\n\tpool buffer.Pool\n\tconsoleEncoder zapcore.Encoder\n}\n\n\ntype Formatter interface {\n\tFormat(w io.Writer, entry zapcore.Entry, fields []zapcore.Field)\n}\n\nfunc NewFormatEncoder(formatters ...Formatter) *FormatEncoder {\n\treturn &FormatEncoder{\n\t\tEncoder: zapcore.NewConsoleEncoder(zapcore.EncoderConfig{LineEnding: \"\\n\"}),\n\t\tformatters: formatters,\n\t\tpool: buffer.NewPool(),\n\t}\n}\n\n\n\n\n\n\n\nfunc (f *FormatEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {\n\tline := f.pool.Get()\n\tfor _, f := range f.formatters {\n\t\tf.Format(line, entry, fields)\n\t}\n\n\tencodedFields, err := f.Encoder.EncodeEntry(entry, fields)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif line.Len() > 0 && encodedFields.Len() != 1 {\n\t\tline.AppendString(\" \")\n\t}\n\tline.AppendString(encodedFields.String())\n\tencodedFields.Free()\n\n\treturn line, nil\n}\n\nfunc (f *FormatEncoder) Clone() zapcore.Encoder ", "output": "{\n\treturn &FormatEncoder{\n\t\tEncoder: f.Encoder.Clone(),\n\t\tformatters: f.formatters,\n\t\tpool: f.pool,\n\t}\n}"} {"input": "package error\n\nimport \"google.golang.org/grpc/codes\"\n\n\ntype ErrType int\n\nconst (\n\tCANotReady ErrType = iota\n\tCSRError\n\tTTLError\n\tCertGenError\n)\n\n\ntype Error struct {\n\tt ErrType\n\terr error\n}\n\n\nfunc (e Error) Error() string {\n\treturn e.err.Error()\n}\n\n\n\n\n\nfunc (e Error) HTTPErrorCode() codes.Code {\n\tswitch e.t {\n\tcase CANotReady:\n\t\treturn codes.Internal\n\tcase CertGenError:\n\t\treturn codes.Internal\n\tcase CSRError:\n\t\treturn codes.InvalidArgument\n\tcase TTLError:\n\t\treturn codes.InvalidArgument\n\t}\n\treturn codes.Internal\n}\n\n\nfunc NewError(t ErrType, err error) *Error {\n\treturn &Error{\n\t\tt: t,\n\t\terr: err,\n\t}\n}\n\nfunc (e Error) ErrorType() string ", "output": "{\n\tswitch e.t {\n\tcase CANotReady:\n\t\treturn \"CA_NOT_READY\"\n\tcase CSRError:\n\t\treturn \"CSR_ERROR\"\n\tcase TTLError:\n\t\treturn \"TTL_ERROR\"\n\tcase CertGenError:\n\t\treturn \"CERT_GEN_ERROR\"\n\t}\n\treturn \"UNKNOWN\"\n}"} {"input": "package main\n\nimport (\n\t\"net\"\n\t\"os\"\n\t\"fmt\"\n)\n\n\n\nfunc main() {\n\n\tif len(os.Args) != 2 {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s host:port\\n\", os.Args[0])\n\t\tos.Exit(1)\n\t}\n\n\tservice := os.Args[1]\n\tfmt.Printf(\"Is Port Open? %v\\n\", IsPortOpen(\"tcp4\", service))\n\n\n}\n\nfunc IsPortOpen(connectionType, addr string) bool ", "output": "{\n\n\ttcpAddr, err := net.ResolveTCPAddr(connectionType, addr)\n\tif err == nil {\n\t\t_, err = net.DialTCP(connectionType, nil, tcpAddr)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t} else {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package openstacktasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realFloatingIP FloatingIP\n\n\nfunc (o *FloatingIP) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realFloatingIP\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = FloatingIP(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &FloatingIP{}\n\n\nfunc (o *FloatingIP) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\n\nfunc (o *FloatingIP) SetLifecycle(lifecycle fi.Lifecycle) {\n\to.Lifecycle = &lifecycle\n}\n\nvar _ fi.HasName = &FloatingIP{}\n\n\n\n\n\nfunc (o *FloatingIP) SetName(name string) {\n\to.Name = &name\n}\n\n\nfunc (o *FloatingIP) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *FloatingIP) GetName() *string ", "output": "{\n\treturn o.Name\n}"} {"input": "package command\n\nimport (\n\t\"flag\"\n\n\t\"fmt\"\n\n\tapi \"github.com/elodina/stack-deploy/framework\"\n)\n\ntype AddUserCommand struct{}\n\nfunc (auc *AddUserCommand) Run(args []string) int {\n\tvar (\n\t\tflags = flag.NewFlagSet(\"adduser\", flag.ExitOnError)\n\t\tapiUrl = flags.String(\"api\", \"\", \"Stack-deploy server address.\")\n\t\tname = flags.String(\"name\", \"\", \"New user name\")\n\t\tadmin = flags.Bool(\"admin\", false, \"Create admin\")\n\t)\n\tflags.Parse(args)\n\n\tstackDeployApi, err := resolveApi(*apiUrl)\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tclient := api.NewClient(stackDeployApi)\n\n\trole := \"regular\"\n\tif *admin {\n\t\trole = \"admin\"\n\t}\n\tkey, err := client.CreateUser(&api.CreateUserRequest{\n\t\tName: *name,\n\t\tRole: role,\n\t})\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tfmt.Printf(\"User added. Key: %s\\n\", key)\n\treturn 0\n}\n\nfunc (auc *AddUserCommand) Help() string {\n\treturn \"\"\n}\n\n\n\nfunc (auc *AddUserCommand) Synopsis() string ", "output": "{\n\treturn \"Add new user\"\n}"} {"input": "package termdash\n\nimport (\n\t\"github.com/ohsu-comp-bio/funnel/cmd/termdash/compact\"\n\t\"github.com/ohsu-comp-bio/funnel/tes\"\n)\n\ntype TaskWidget struct {\n\tTask *tes.Task\n\tWidgets *compact.Compact\n\tdisplay bool\n}\n\n\n\nfunc NewTaskWidget(t *tes.Task) *TaskWidget ", "output": "{\n\twidgets := compact.NewCompact(t)\n\treturn &TaskWidget{\n\t\tTask: t,\n\t\tWidgets: widgets,\n\t\tdisplay: true,\n\t}\n}"} {"input": "package reports\n\nimport (\n\t\"time\"\n\n\t\"github.com/rafaeljusto/druns/core/db\"\n)\n\ntype Service struct {\n\tsqler db.SQLer\n}\n\nfunc NewService(sqler db.SQLer) Service {\n\treturn Service{sqler}\n}\n\n\n\nfunc (s Service) IncomingPerGroup(month time.Time, classValue float64) ([]Incoming, error) ", "output": "{\n\tdao := newDAO(s.sqler)\n\treturn dao.incomingPerGroup(month, classValue)\n}"} {"input": "package aes\n\nimport (\n\t\"crypto/cipher\"\n)\n\ntype code int\n\n\nconst (\n\taes128 code = 18\n\taes192 = 19\n\taes256 = 20\n)\n\ntype aesCipherAsm struct {\n\tfunction code \n\tkey []byte \n\tstorage [256]byte \n}\n\n\n\n\nfunc hasAsm() bool\n\n\n\n\n\nfunc cryptBlocks(c code, key, dst, src *byte, length int)\n\nvar useAsm = hasAsm()\n\n\n\nfunc (c *aesCipherAsm) BlockSize() int { return BlockSize }\n\nfunc (c *aesCipherAsm) Encrypt(dst, src []byte) {\n\tif len(src) < BlockSize {\n\t\tpanic(\"crypto/aes: input not full block\")\n\t}\n\tif len(dst) < BlockSize {\n\t\tpanic(\"crypto/aes: output not full block\")\n\t}\n\tcryptBlocks(c.function, &c.key[0], &dst[0], &src[0], BlockSize)\n}\n\nfunc (c *aesCipherAsm) Decrypt(dst, src []byte) {\n\tif len(src) < BlockSize {\n\t\tpanic(\"crypto/aes: input not full block\")\n\t}\n\tif len(dst) < BlockSize {\n\t\tpanic(\"crypto/aes: output not full block\")\n\t}\n\tcryptBlocks(c.function+128, &c.key[0], &dst[0], &src[0], BlockSize)\n}\n\n\n\nfunc expandKey(key []byte, enc, dec []uint32) {\n\texpandKeyGo(key, enc, dec)\n}\n\nfunc newCipher(key []byte) (cipher.Block, error) ", "output": "{\n\tif !useAsm {\n\t\treturn newCipherGeneric(key)\n\t}\n\n\tvar function code\n\tswitch len(key) {\n\tcase 128 / 8:\n\t\tfunction = aes128\n\tcase 192 / 8:\n\t\tfunction = aes192\n\tcase 256 / 8:\n\t\tfunction = aes256\n\tdefault:\n\t\treturn nil, KeySizeError(len(key))\n\t}\n\n\tvar c aesCipherAsm\n\tc.function = function\n\tc.key = c.storage[:len(key)]\n\tcopy(c.key, key)\n\treturn &c, nil\n}"} {"input": "package gtk\n\n\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n\n\t\"github.com/untoldwind/amintk/gdk\"\n)\n\n\ntype Image struct {\n\tWidget\n}\n\n\nfunc ImageNew() *Image {\n\tc := C.gtk_image_new()\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\nfunc (v *Image) native() *C.GtkImage {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn (*C.GtkImage)(v.Native())\n}\n\n\nfunc ImageNewFromIconName(iconName string, size IconSize) *Image {\n\tcstr := C.CString(iconName)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_image_new_from_icon_name((*C.gchar)(cstr),\n\t\tC.GtkIconSize(size))\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\n\n\n\nfunc wrapImage(p unsafe.Pointer) *Image {\n\tif widget := wrapWidget(p); widget != nil {\n\t\treturn &Image{Widget: *widget}\n\t}\n\treturn nil\n}\n\n\nfunc (v *Image) Clear() {\n\tC.gtk_image_clear(v.native())\n}\n\n\nfunc (v *Image) SetFromPixbuf(pixbuf *gdk.Pixbuf) {\n\tpbptr := (*C.GdkPixbuf)(pixbuf.Native())\n\tC.gtk_image_set_from_pixbuf(v.native(), pbptr)\n}\n\nfunc ImageNewFromPixbuf(pixbuf *gdk.Pixbuf) *Image ", "output": "{\n\tptr := (*C.GdkPixbuf)(pixbuf.Native())\n\tc := C.gtk_image_new_from_pixbuf(ptr)\n\treturn wrapImage(unsafe.Pointer(c))\n}"} {"input": "package console\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"syscall\"\n\n\t\"github.com/dotcloud/docker/pkg/label\"\n\t\"github.com/dotcloud/docker/pkg/system\"\n)\n\n\nfunc Setup(rootfs, consolePath, mountLabel string) error {\n\toldMask := system.Umask(0000)\n\tdefer system.Umask(oldMask)\n\n\tif err := os.Chmod(consolePath, 0600); err != nil {\n\t\treturn err\n\t}\n\tif err := os.Chown(consolePath, 0, 0); err != nil {\n\t\treturn err\n\t}\n\tif err := label.SetFileLabel(consolePath, mountLabel); err != nil {\n\t\treturn fmt.Errorf(\"set file label %s %s\", consolePath, err)\n\t}\n\n\tdest := filepath.Join(rootfs, \"dev/console\")\n\n\tf, err := os.Create(dest)\n\tif err != nil && !os.IsExist(err) {\n\t\treturn fmt.Errorf(\"create %s %s\", dest, err)\n\t}\n\tif f != nil {\n\t\tf.Close()\n\t}\n\n\tif err := system.Mount(consolePath, dest, \"bind\", syscall.MS_BIND, \"\"); err != nil {\n\t\treturn fmt.Errorf(\"bind %s to %s %s\", consolePath, dest, err)\n\t}\n\treturn nil\n}\n\n\n\nfunc OpenAndDup(consolePath string) error ", "output": "{\n\tslave, err := system.OpenTerminal(consolePath, syscall.O_RDWR)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"open terminal %s\", err)\n\t}\n\tif err := system.Dup2(slave.Fd(), 0); err != nil {\n\t\treturn err\n\t}\n\tif err := system.Dup2(slave.Fd(), 1); err != nil {\n\t\treturn err\n\t}\n\treturn system.Dup2(slave.Fd(), 2)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc Newton(x float64) float64 {\n\tif x == 0 {\n\t\treturn 0\n\t}\n\tz := 1.0\n\tfor i := 0; i < int(x); i++ {\n\t\tz = z - ((math.Pow(z, 2) - x) / (2 * z))\n\t}\n\treturn z\n}\n\n\n\nfunc main() {\n\ttimes := 16\n\tdelta := float64(0.000001)\n\tfor i := 0; i < times; i++ {\n\t\tsquareroot := SquareRoot(float64(i))\n\t\tnewton := Newton(float64(i))\n\t\tfmt.Println(i, \"squared:\")\n\t\tfmt.Println(\" SquareRoot:\", squareroot)\n\t\tfmt.Println(\" Newton :\", newton)\n\t\tdiff := math.Abs(squareroot - newton)\n\t\tif diff == 0.0 {\n\t\t\tfmt.Println(\" Difference: 0.0\")\n\t\t} else if diff < delta {\n\t\t\tfmt.Println(\" Difference: 0.0 [\", diff, \"< DELTA of\", delta, \"]\")\n\t\t} else {\n\t\t\tfmt.Println(\" Difference:\", diff)\n\t\t}\n\t}\n}\n\nfunc SquareRoot(x float64) float64 ", "output": "{\n\treturn math.Sqrt(x)\n}"} {"input": "package iso20022\n\n\ntype SubAccount2 struct {\n\n\tIdentification *Max35Text `xml:\"Id\"`\n}\n\n\n\nfunc (s *SubAccount2) SetIdentification(value string) ", "output": "{\n\ts.Identification = (*Max35Text)(&value)\n}"} {"input": "package render\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gogo/protobuf/proto\"\n\t\"github.com/pkg/errors\"\n)\n\nvar pbContentType = []string{\"application/x-protobuf\"}\n\n\n\n\n\nfunc (r PB) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, pbContentType)\n}\n\nfunc writePB(w http.ResponseWriter, obj PB) (err error) {\n\tvar pbBytes []byte\n\twriteContentType(w, pbContentType)\n\n\tif pbBytes, err = proto.Marshal(&obj); err != nil {\n\t\terr = errors.WithStack(err)\n\t\treturn\n\t}\n\n\tif _, err = w.Write(pbBytes); err != nil {\n\t\terr = errors.WithStack(err)\n\t}\n\treturn\n}\n\nfunc (r PB) Render(w http.ResponseWriter) error ", "output": "{\n\tif r.TTL <= 0 {\n\t\tr.TTL = 1\n\t}\n\treturn writePB(w, r)\n}"} {"input": "package migration\n\nimport \"time\"\n\n\ntype IssueContext interface {\n\tLocalID() int64\n\tForeignID() int64\n}\n\n\ntype BasicIssueContext int64\n\n\nfunc (c BasicIssueContext) LocalID() int64 {\n\treturn int64(c)\n}\n\n\n\n\n\ntype Issue struct {\n\tNumber int64 `json:\"number\"`\n\tPosterID int64 `yaml:\"poster_id\" json:\"poster_id\"`\n\tPosterName string `yaml:\"poster_name\" json:\"poster_name\"`\n\tPosterEmail string `yaml:\"poster_email\" json:\"poster_email\"`\n\tTitle string `json:\"title\"`\n\tContent string `json:\"content\"`\n\tRef string `json:\"ref\"`\n\tMilestone string `json:\"milestone\"`\n\tState string `json:\"state\"` \n\tIsLocked bool `yaml:\"is_locked\" json:\"is_locked\"`\n\tCreated time.Time `json:\"created\"`\n\tUpdated time.Time `json:\"updated\"`\n\tClosed *time.Time `json:\"closed\"`\n\tLabels []*Label `json:\"labels\"`\n\tReactions []*Reaction `json:\"reactions\"`\n\tAssignees []string `json:\"assignees\"`\n\tContext IssueContext `yaml:\"-\"`\n}\n\n\nfunc (i *Issue) GetExternalName() string { return i.PosterName }\n\n\nfunc (i *Issue) GetExternalID() int64 { return i.PosterID }\n\nfunc (c BasicIssueContext) ForeignID() int64 ", "output": "{\n\treturn int64(c)\n}"} {"input": "package v1\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n\n\t\"go-common/library/net/rpc/warden\"\n)\n\n\nconst AppID = \"passport.service.auth\"\n\n\n\n\nfunc NewClient(cfg *warden.ClientConfig, opts ...grpc.DialOption) (AuthClient, error) ", "output": "{\n\tclient := warden.NewClient(cfg, opts...)\n\tconn, err := client.Dial(context.Background(), \"discovery://default/\"+AppID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewAuthClient(conn), nil\n}"} {"input": "package iso20022\n\n\ntype CorporateActionRate21 struct {\n\n\tAdditionalQuantityForSubscribedResultantSecurities *RatioFormat3Choice `xml:\"AddtlQtyForSbcbdRsltntScties,omitempty\"`\n\n\tAdditionalQuantityForExistingSecurities *RatioFormat3Choice `xml:\"AddtlQtyForExstgScties,omitempty\"`\n\n\tNewToOld *RatioFormat4Choice `xml:\"NewToOd,omitempty\"`\n}\n\nfunc (c *CorporateActionRate21) AddAdditionalQuantityForSubscribedResultantSecurities() *RatioFormat3Choice {\n\tc.AdditionalQuantityForSubscribedResultantSecurities = new(RatioFormat3Choice)\n\treturn c.AdditionalQuantityForSubscribedResultantSecurities\n}\n\n\n\nfunc (c *CorporateActionRate21) AddNewToOld() *RatioFormat4Choice {\n\tc.NewToOld = new(RatioFormat4Choice)\n\treturn c.NewToOld\n}\n\nfunc (c *CorporateActionRate21) AddAdditionalQuantityForExistingSecurities() *RatioFormat3Choice ", "output": "{\n\tc.AdditionalQuantityForExistingSecurities = new(RatioFormat3Choice)\n\treturn c.AdditionalQuantityForExistingSecurities\n}"} {"input": "package register\n\nimport (\n\t\"github.com/plimble/validator\"\n)\n\n\n\nfunc validateRegister(form *RegisterForm) validator.Validator ", "output": "{\n\tv := validator.New()\n\n\tv.RequiredString(form.Username, ErrUsernameRequired)\n\tv.RequiredString(form.Password, ErrPasswordRequired)\n\tv.RequiredString(form.Name, ErrNameRequired)\n\tv.RequiredString(form.Email, ErrEmailRequired)\n\tv.Email(form.Email, ErrEmailInvalid)\n\n\treturn v\n}"} {"input": "package settings\n\nimport (\n\t\"testing\"\n\n\t\"github.com/admpub/nging/v4/application/dbschema\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/webx-top/echo\"\n)\n\nvar expect = `{\n \"base\": {\n \"debug\": \"test\"\n }\n}`\n\n\n\nfunc TestConfigDefaultsAsStore(t *testing.T) ", "output": "{\n\tactual := echo.Dump(configAsStore(map[string]map[string]*dbschema.NgingConfig{\n\t\t`base`: {\n\t\t\t`debug`: {\n\t\t\t\tKey: `debug`,\n\t\t\t\tLabel: `调试模式`,\n\t\t\t\tDescription: ``,\n\t\t\t\tValue: `test`,\n\t\t\t\tGroup: `base`,\n\t\t\t\tType: `text`,\n\t\t\t\tSort: 0,\n\t\t\t\tDisabled: `N`,\n\t\t\t},\n\t\t},\n\t}), false)\n\tassert.Equal(t, expect, actual)\n}"} {"input": "package wire\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\n\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max)\n\tif buf != nil {\n\t\tcopy(b, buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc (w *fixedWriter) Bytes() []byte ", "output": "{\n\treturn w.b\n}"} {"input": "package errors\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype MultiError struct {\n\tErrors []error\n}\n\n\n\nfunc (errs MultiError) Error() string {\n\terrorMessages := []string{}\n\tfor _, err := range errs.Errors {\n\t\tif err != nil {\n\t\t\terrorMessages = append(errorMessages, err.Error())\n\t\t}\n\t}\n\n\treturn fmt.Sprintf(\"Hit multiple errors:\\n%s\", strings.Join(errorMessages, \"\\n\"))\n}\n\nfunc NewMultiError(errs ...error) error ", "output": "{\n\tnilsRemoved := make([]error, 0, len(errs))\n\tfor _, item := range errs {\n\t\tif item != nil {\n\t\t\tnilsRemoved = append(nilsRemoved, item)\n\t\t}\n\t}\n\n\tif len(nilsRemoved) == 0 {\n\t\treturn nil\n\t}\n\n\treturn MultiError{Errors: nilsRemoved}\n}"} {"input": "package appfilesfakes\n\nimport (\n\t\"sync\"\n\n\t\"code.cloudfoundry.org/cli/cf/api/appfiles\"\n)\n\ntype FakeAppFilesRepository struct {\n\tListFilesStub func(appGUID string, instance int, path string) (files string, apiErr error)\n\tlistFilesMutex sync.RWMutex\n\tlistFilesArgsForCall []struct {\n\t\tappGUID string\n\t\tinstance int\n\t\tpath string\n\t}\n\tlistFilesReturns struct {\n\t\tresult1 string\n\t\tresult2 error\n\t}\n}\n\nfunc (fake *FakeAppFilesRepository) ListFiles(appGUID string, instance int, path string) (files string, apiErr error) {\n\tfake.listFilesMutex.Lock()\n\tfake.listFilesArgsForCall = append(fake.listFilesArgsForCall, struct {\n\t\tappGUID string\n\t\tinstance int\n\t\tpath string\n\t}{appGUID, instance, path})\n\tfake.listFilesMutex.Unlock()\n\tif fake.ListFilesStub != nil {\n\t\treturn fake.ListFilesStub(appGUID, instance, path)\n\t} else {\n\t\treturn fake.listFilesReturns.result1, fake.listFilesReturns.result2\n\t}\n}\n\nfunc (fake *FakeAppFilesRepository) ListFilesCallCount() int {\n\tfake.listFilesMutex.RLock()\n\tdefer fake.listFilesMutex.RUnlock()\n\treturn len(fake.listFilesArgsForCall)\n}\n\nfunc (fake *FakeAppFilesRepository) ListFilesArgsForCall(i int) (string, int, string) {\n\tfake.listFilesMutex.RLock()\n\tdefer fake.listFilesMutex.RUnlock()\n\treturn fake.listFilesArgsForCall[i].appGUID, fake.listFilesArgsForCall[i].instance, fake.listFilesArgsForCall[i].path\n}\n\n\n\nvar _ appfiles.Repository = new(FakeAppFilesRepository)\n\nfunc (fake *FakeAppFilesRepository) ListFilesReturns(result1 string, result2 error) ", "output": "{\n\tfake.ListFilesStub = nil\n\tfake.listFilesReturns = struct {\n\t\tresult1 string\n\t\tresult2 error\n\t}{result1, result2}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/aarzilli/iching\"\n\t\"os\"\n\t\"strconv\"\n)\n\n\n\nfunc main() {\n\tif len(os.Args) != 2 {\n\t\tfmt.Fprintf(os.Stderr, \"Wrong number of arguments.\\n\")\n\t\tusage()\n\t}\n\n\ts := os.Args[1]\n\n\tvar n uint64\n\tvar err error\n\n\tch := ([]rune(s))[0]\n\tif ch >= 0x4dc0 && ch <= 0x4dff {\n\t\tn, err = iching.Ichingtoi(s)\n\t} else {\n\t\tn, err = strconv.ParseUint(s, 0, 64)\n\t}\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Wrong argument: %v\\n\", err)\n\t\tusage()\n\t}\n\n\tfmt.Printf(\"decimal = %d\\n\", n)\n\n\toct := fmt.Sprintf(\"%o\", n)\n\n\tfmt.Printf(\"octal =\")\n\tstart := 0\n\tif len(oct)%2 != 0 {\n\t\tfmt.Printf(\" 0%c\", oct[0])\n\t\tstart = 1\n\t}\n\tfor i := start; i < len(oct); i += 2 {\n\t\tfmt.Printf(\" %c%c\", oct[i], oct[i+1])\n\t}\n\tfmt.Printf(\"\\n\")\n\n\tich := iching.Itoiching(n)\n\n\tfmt.Printf(\"iching =\")\n\tfor _, ch := range []rune(ich) {\n\t\tfmt.Printf(\" %c\", ch)\n\t}\n\tfmt.Printf(\"\\n\")\n}\n\nfunc usage() ", "output": "{\n\tfmt.Fprintf(os.Stderr, \"Usage: ichingtest |||\\n\")\n\tos.Exit(1)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"github.com/codahale/grump\"\n)\n\n\n\nfunc verify(pubKeyFilename, inFilename, sigFilename string, quiet bool) ", "output": "{\n\tpubKey, err := ioutil.ReadFile(pubKeyFilename)\n\tif err != nil {\n\t\tdie(err)\n\t}\n\n\tsig, err := ioutil.ReadFile(sigFilename)\n\tif err != nil {\n\t\tdie(err)\n\t}\n\n\tin, err := os.Open(inFilename)\n\tif err != nil {\n\t\tdie(err)\n\t}\n\tdefer in.Close()\n\n\terr = grump.Verify(pubKey, sig, in)\n\tif err != nil {\n\t\tif quiet {\n\t\t\tos.Exit(-1)\n\t\t}\n\t\tdie(err)\n\t} else {\n\t\tif !quiet {\n\t\t\tfmt.Fprintln(os.Stderr, \"good signature\")\n\t\t}\n\t}\n}"} {"input": "package neurgo\n\nimport (\n\t\"bufio\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc WriteStringToFile(value string, filepath string) error {\n\toutputFile, outputError := os.OpenFile(filepath,\n\t\tos.O_WRONLY|os.O_CREATE,\n\t\t0666)\n\tif outputError != nil {\n\t\treturn outputError\n\t}\n\tdefer outputFile.Close()\n\toutputWriter := bufio.NewWriter(outputFile)\n\toutputWriter.WriteString(value)\n\toutputWriter.Flush()\n\treturn nil\n}\n\n\n\nfunc JsonString(v interface{}) string ", "output": "{\n\tjson, err := json.Marshal(v)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn err.Error()\n\t}\n\treturn fmt.Sprintf(\"%s\", json)\n}"} {"input": "package resources\n\nimport \"github.com/starkandwayne/cf-cli/cf/models\"\n\ntype RouteResource struct {\n\tResource\n\tEntity RouteEntity\n}\n\ntype RouteEntity struct {\n\tHost string\n\tDomain DomainResource\n\tSpace SpaceResource\n\tApps []ApplicationResource\n}\n\n\nfunc (resource RouteResource) ToModel() (route models.Route) {\n\troute.Host = resource.Entity.Host\n\troute.Guid = resource.Metadata.Guid\n\troute.Domain = resource.Entity.Domain.ToFields()\n\troute.Space = resource.Entity.Space.ToFields()\n\tfor _, appResource := range resource.Entity.Apps {\n\t\troute.Apps = append(route.Apps, appResource.ToFields())\n\t}\n\treturn\n}\n\nfunc (resource RouteResource) ToFields() (fields models.Route) ", "output": "{\n\tfields.Guid = resource.Metadata.Guid\n\tfields.Host = resource.Entity.Host\n\treturn\n}"} {"input": "package commands\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/layeh/gumble/gumble\"\n\t\"github.com/matthieugrieger/mumbledj/interfaces\"\n\t\"github.com/spf13/viper\"\n)\n\n\n\ntype SkipPlaylistCommand struct{}\n\n\nfunc (c *SkipPlaylistCommand) Aliases() []string {\n\treturn viper.GetStringSlice(\"commands.skipplaylist.aliases\")\n}\n\n\nfunc (c *SkipPlaylistCommand) Description() string {\n\treturn viper.GetString(\"commands.skipplaylist.description\")\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (c *SkipPlaylistCommand) Execute(user *gumble.User, args ...string) (string, bool, error) {\n\tvar (\n\t\tcurrentTrack interfaces.Track\n\t\terr error\n\t)\n\n\tif currentTrack, err = DJ.Queue.CurrentTrack(); err != nil {\n\t\treturn \"\", true, errors.New(viper.GetString(\"commands.common_messages.no_tracks_error\"))\n\t}\n\n\tif playlist := currentTrack.GetPlaylist(); playlist == nil {\n\t\treturn \"\", true, errors.New(viper.GetString(\"commands.skipplaylist.messages.no_playlist_error\"))\n\t}\n\tif currentTrack.GetPlaylist().GetSubmitter() == user.Name {\n\t\tDJ.Queue.SkipPlaylist()\n\t\treturn fmt.Sprintf(viper.GetString(\"commands.skipplaylist.messages.submitter_voted\"), user.Name), false, nil\n\t}\n\tif err := DJ.Skips.AddPlaylistSkip(user); err != nil {\n\t\treturn \"\", true, errors.New(viper.GetString(\"commands.skipplaylist.messages.already_voted_error\"))\n\t}\n\n\treturn fmt.Sprintf(viper.GetString(\"commands.skipplaylist.messages.voted\"), user.Name), false, nil\n}\n\nfunc (c *SkipPlaylistCommand) IsAdminCommand() bool ", "output": "{\n\treturn viper.GetBool(\"commands.skipplaylist.is_admin\")\n}"} {"input": "package main\n\nfunc main() {\n\tx := \"Hello World\"\n\tch := make(chan string)\n\tf(ch)\n\tsink(x)\n\tx = source()\n\tch <- x\n}\n\nfunc f(ch chan string) {\n\tgo func() {\n\t\ty := <-ch\n\t\tsink(y)\n\t}()\n}\n\nfunc sink(s string) {\n}\n\n\n\nfunc source() string ", "output": "{\n\treturn \"secret\"\n}"} {"input": "package limiter\n\ntype SimpleLimiter chan struct{}\n\nfunc (l SimpleLimiter) Enter() { l <- struct{}{} }\nfunc (l SimpleLimiter) Leave() { <-l }\n\n\n\nfunc NewSimpleLimiter(l int) SimpleLimiter ", "output": "{\n\treturn make(chan struct{}, l)\n}"} {"input": "package openpgp\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\ntype recordingHash struct {\n\tbuf *bytes.Buffer\n}\n\nfunc (r recordingHash) Write(b []byte) (n int, err error) {\n\treturn r.buf.Write(b)\n}\n\nfunc (r recordingHash) Sum(in []byte) []byte {\n\treturn append(in, r.buf.Bytes()...)\n}\n\nfunc (r recordingHash) Reset() {\n\tpanic(\"shouldn't be called\")\n}\n\nfunc (r recordingHash) Size() int {\n\tpanic(\"shouldn't be called\")\n}\n\nfunc (r recordingHash) BlockSize() int {\n\tpanic(\"shouldn't be called\")\n}\n\nfunc testCanonicalText(t *testing.T, input, expected string) {\n\tr := recordingHash{bytes.NewBuffer(nil)}\n\tc := NewCanonicalTextHash(r)\n\tc.Write([]byte(input))\n\tresult := c.Sum(nil)\n\tif expected != string(result) {\n\t\tt.Errorf(\"input: %x got: %x want: %x\", input, result, expected)\n\t}\n}\n\n\n\nfunc TestCanonicalText(t *testing.T) ", "output": "{\n\ttestCanonicalText(t, \"foo\\n\", \"foo\\r\\n\")\n\ttestCanonicalText(t, \"foo\", \"foo\")\n\ttestCanonicalText(t, \"foo\\r\\n\", \"foo\\r\\n\")\n\ttestCanonicalText(t, \"foo\\r\\nbar\", \"foo\\r\\nbar\")\n\ttestCanonicalText(t, \"foo\\r\\nbar\\n\\n\", \"foo\\r\\nbar\\r\\n\\r\\n\")\n}"} {"input": "package wkb\n\nimport (\n\t\"encoding/binary\"\n\t\"github.com/foobaz/geom\"\n\t\"io\"\n)\n\nfunc multiPointReader(r io.Reader, byteOrder binary.ByteOrder, dimension int) (geom.T, error) {\n\tvar numPoints uint32\n\tif err := binary.Read(r, byteOrder, &numPoints); err != nil {\n\t\treturn nil, err\n\t}\n\tpoints := make([]geom.Point, numPoints)\n\tfor i := range points {\n\t\tif g, err := Read(r); err == nil {\n\t\t\tvar ok bool\n\t\t\tpoints[i], ok = g.(geom.Point)\n\t\t\tif !ok {\n\t\t\t\treturn nil, &UnexpectedGeometryError{g}\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn geom.MultiPoint(points), nil\n}\n\n\n\nfunc writeMultiPoint(w io.Writer, byteOrder binary.ByteOrder, axes uint32, multiPoint geom.MultiPoint) error ", "output": "{\n\tif err := binary.Write(w, byteOrder, uint32(len(multiPoint))); err != nil {\n\t\treturn err\n\t}\n\tfor _, point := range multiPoint {\n\t\tif err := Write(w, byteOrder, axes, point); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package util\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/atnet/gof\"\n\t\"github.com/atnet/gof/crypto\"\n\t\"github.com/atnet/gof/web\"\n\t\"strconv\"\n)\n\nconst offset string = \"%$^&@#\"\n\nfunc chkStorage(sto gof.Storage) {\n\tif sto == nil {\n\t\tpanic(errors.New(\"[ Api] - api token storage is null !\"))\n\t}\n}\n\n\nfunc GetMemberApiTokenKey(memberId int) string {\n\treturn fmt.Sprintf(\"api:member:token:%d\", memberId)\n}\n\n\nfunc SetMemberApiToken(sto gof.Storage, memberId int, pwd string) string {\n\tchkStorage(sto)\n\tcyp := crypto.NewUnixCrypto(pwd+offset, offset)\n\tvar token string = string(cyp.Encode())\n\tvar key string = GetMemberApiTokenKey(memberId)\n\n\tsto.Set(key, token) \n\tsto.Set(key+\"base\", pwd) \n\n\treturn token\n}\n\n\nfunc GetMemberApiToken(sto gof.Storage, memberId int) (string, string) {\n\tchkStorage(sto)\n\n\tvar key = GetMemberApiTokenKey(memberId)\n\tvar srcToken, tokenBase string\n\n\tsrcToken, _ = sto.GetString(key)\n\ttokenBase, _ = sto.GetString(key + \"base\")\n\treturn srcToken, tokenBase\n}\n\n\nfunc CompareMemberApiToken(sto gof.Storage, memberId int, token string) bool {\n\n\tif len(token) == 0 {\n\t\treturn false\n\t}\n\n\tsrcToken, tokenBase := GetMemberApiToken(sto, memberId)\n\tif len(srcToken) == 0 || len(tokenBase) == 0 {\n\t\treturn false\n\t}\n\treturn srcToken == token\n}\n\n\n\n\nfunc MemberHttpSessionConnect(ctx *web.Context) (ok bool, memberId int) ", "output": "{\n\tif param := ctx.Request.URL.Query().Get(\"member_id\"); len(param) != 0 {\n\t\tmemberId, _ = strconv.Atoi(param)\n\n\t\tvar token string = ctx.Request.URL.Query().Get(\"token\")\n\t\tif CompareMemberApiToken(ctx.App.Storage(), memberId, token) {\n\t\t\tctx.Session().Set(\"client_member_id\", memberId)\n\t\t\tctx.Session().Save()\n\t\t\treturn true, memberId\n\t\t}\n\t} else {\n\t\tif v := ctx.Session().Get(\"client_member_id\"); v != nil {\n\t\t\tmemberId = v.(int)\n\t\t\treturn true, memberId\n\t\t}\n\t}\n\n\n\treturn false, memberId\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\n\tasp \"golang.org/x/exp/aspectgo/aspect\"\n)\n\n\ntype ExampleAspect struct {\n}\n\n\nfunc (a *ExampleAspect) Pointcut() asp.Pointcut {\n\tpkg := regexp.QuoteMeta(\"golang.org/x/exp/aspectgo/example/hello2\")\n\ts := pkg + \".*\"\n\treturn asp.NewCallPointcutFromRegexp(s)\n}\n\n\n\n\n\ntype FmtPrintlnAspect struct {\n}\n\nfunc (a *FmtPrintlnAspect) Pointcut() asp.Pointcut {\n\ts := regexp.QuoteMeta(\"fmt.Println\")\n\treturn asp.NewCallPointcutFromRegexp(s)\n}\n\nfunc (a *FmtPrintlnAspect) Advice(ctx asp.Context) []interface{} {\n\targs := ctx.Args()\n\tfmt.Fprintf(os.Stderr, \"directing to stderr: %s\\n\", args...)\n\treturn []interface{}{0, nil}\n}\n\nfunc (a *ExampleAspect) Advice(ctx asp.Context) []interface{} ", "output": "{\n\targs := ctx.Args()\n\tfmt.Println(\"BEFORE hello\")\n\tres := ctx.Call(args)\n\tfmt.Println(\"AFTER hello\")\n\treturn res\n}"} {"input": "package nats\n\nimport (\n\t\"github.com/apcera/nats\"\n\t\"github.com/plimble/kuja/broker\"\n)\n\ntype natsBroker struct {\n\turl string\n\tconn *nats.Conn\n}\n\nfunc NewBroker(url string) *natsBroker {\n\treturn &natsBroker{\n\t\turl: url,\n\t}\n}\n\nfunc (n *natsBroker) Connect() error {\n\tvar err error\n\tn.conn, err = nats.Connect(n.url)\n\n\treturn err\n}\n\nfunc (n *natsBroker) Close() {\n\tn.conn.Close()\n}\n\n\n\nfunc (n *natsBroker) Subscribe(topic, queue, appId string, size int, h broker.Handler) {\n\tfor i := 0; i < size; i++ {\n\t\tn.conn.QueueSubscribe(topic, queue, func(msg *nats.Msg) {\n\t\t\tbrokerMsg := &broker.Message{}\n\t\t\tbrokerMsg.Unmarshal(msg.Data)\n\t\t\tretryCount, err := h(msg.Subject, brokerMsg)\n\t\t\tif err != nil {\n\t\t\t\tfor i := 0; i < retryCount; i++ {\n\t\t\t\t\tbrokerMsg.Retry++\n\t\t\t\t\t_, err := h(topic, brokerMsg)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc (n *natsBroker) Publish(topic string, msg *broker.Message) error ", "output": "{\n\tdata, err := msg.Marshal()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn n.conn.Publish(topic, data)\n}"} {"input": "package statsd\n\nimport (\n\t\"github.com/golang/glog\"\n)\n\ntype dummyStatsdClientImpl struct {\n\tmessages []string\n}\n\nfunc (client *dummyStatsdClientImpl) open() error {\n\tglog.V(2).Infof(\"dummy statsd client open() called, doing nothing\")\n\treturn nil\n}\n\nfunc (client *dummyStatsdClientImpl) close() error {\n\tglog.V(2).Infof(\"dummy statsd client close() called, doing nothing\")\n\treturn nil\n}\n\n\n\nfunc (client *dummyStatsdClientImpl) send(messages []string) error ", "output": "{\n\tclient.messages = messages\n\treturn nil\n}"} {"input": "package todoist\n\nimport \"fmt\"\n\ntype IntBool bool\n\n\n\nfunc (i IntBool) MarshalJSON() ([]byte, error) {\n\tif i {\n\t\treturn []byte(\"1\"), nil\n\t} else {\n\t\treturn []byte(\"0\"), nil\n\t}\n}\n\nfunc (i *IntBool) UnmarshalJSON(b []byte) (err error) {\n\tswitch string(b) {\n\tcase \"1\":\n\t\t*i = true\n\tcase \"0\":\n\t\t*i = false\n\tdefault:\n\t\treturn fmt.Errorf(\"Could not unmarshal into intbool: %s\", string(b))\n\t}\n\treturn nil\n}\n\ntype ColorStringer interface {\n\tString() string\n\tColorString() string\n}\n\ntype NoColorString struct {\n\ts string\n}\n\nfunc NewNoColorString(s string) NoColorString {\n\treturn NoColorString{s}\n}\n\nfunc (n NoColorString) String() string {\n\treturn n.s\n}\n\nfunc (n NoColorString) ColorString() string {\n\treturn n.s\n}\n\nfunc (i IntBool) Bool() bool ", "output": "{\n\tif i {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/rakyll/statik/fs\"\n\n\t_ \"github.com/reviewdog/reviewdog/doghouse/appengine/statik\"\n)\n\nvar tmplFiles http.FileSystem\n\n\n\nfunc parseTemplatesFiles(filenames ...string) (*template.Template, error) {\n\tvar t *template.Template\n\tfor _, filename := range filenames {\n\t\tif t == nil {\n\t\t\tt = template.New(filename)\n\t\t}\n\t\ttext, err := fs.ReadFile(tmplFiles, filename)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tt, err = t.Parse(string(text))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn t, nil\n}\n\nvar (\n\ttopTmpl *template.Template\n\tghTopTmpl *template.Template\n\tghRepoTmpl *template.Template\n)\n\nfunc initTemplates() {\n\tvar err error\n\ttmplFiles, err = fs.New()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttopTmpl = mustParseTemplatesFiles(\n\t\t\"/base.html\",\n\t\t\"/index.html\",\n\t)\n\n\tghTopTmpl = mustParseTemplatesFiles(\n\t\t\"/gh/base.html\",\n\t\t\"/gh/header.html\",\n\t\t\"/gh/top.html\",\n\t)\n\n\tghRepoTmpl = mustParseTemplatesFiles(\n\t\t\"/gh/base.html\",\n\t\t\"/gh/header.html\",\n\t\t\"/gh/repo.html\",\n\t)\n}\n\nfunc mustParseTemplatesFiles(filenames ...string) *template.Template ", "output": "{\n\tt, err := parseTemplatesFiles(filenames...)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn t\n}"} {"input": "package iso20022\n\n\ntype PartyIdentification45Choice struct {\n\n\tAnyBIC *AnyBICIdentifier `xml:\"AnyBIC\"`\n\n\tProprietaryIdentification *GenericIdentification19 `xml:\"PrtryId\"`\n\n\tNameAndAddress *NameAndAddress5 `xml:\"NmAndAdr\"`\n}\n\nfunc (p *PartyIdentification45Choice) SetAnyBIC(value string) {\n\tp.AnyBIC = (*AnyBICIdentifier)(&value)\n}\n\nfunc (p *PartyIdentification45Choice) AddProprietaryIdentification() *GenericIdentification19 {\n\tp.ProprietaryIdentification = new(GenericIdentification19)\n\treturn p.ProprietaryIdentification\n}\n\n\n\nfunc (p *PartyIdentification45Choice) AddNameAndAddress() *NameAndAddress5 ", "output": "{\n\tp.NameAndAddress = new(NameAndAddress5)\n\treturn p.NameAndAddress\n}"} {"input": "package gonum\n\nimport \"gonum.org/v1/gonum/lapack\"\n\n\n\n\ntype Implementation struct{}\n\nvar _ lapack.Float64 = Implementation{}\n\n\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc abs(a int) int {\n\tif a < 0 {\n\t\treturn -a\n\t}\n\treturn a\n}\n\nconst (\n\tdlamchE = 1.0 / (1 << 53)\n\n\tdlamchB = 2\n\n\tdlamchP = dlamchB * dlamchE\n\n\tdlamchS = 1.0 / (1 << 256) / (1 << 256) / (1 << 256) / (1 << 254)\n)\n\nfunc min(a, b int) int ", "output": "{\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}"} {"input": "package nogo\n\n\ntype Permission int\n\n\ntype Principal interface {\n\tGetId() string\n\tGetSid() string\n\tGetRoleNames() []string\n}\n\n\ntype Role interface {\n\tGetName() string\n\tIsAdmin() bool\n\tHasPermission(permission Permission) (bool, error)\n}\n\n\nfunc NewRole(name string, mask Permission) Role {\n\treturn &defaultRole{RoleName: name, PermissionMask: mask, Admin: false}\n}\n\n\n\n\ntype defaultRole struct {\n\tRoleName string `db:\"role_name\"`\n\tPermissionMask Permission `db:\"permission_mask\"`\n\tAdmin bool `db:\"is_admin\"`\n}\n\nfunc (this *defaultRole) GetName() string {\n\treturn this.RoleName\n}\n\nfunc (this *defaultRole) IsAdmin() bool {\n\treturn this.Admin\n}\n\nfunc (this *defaultRole) HasPermission(permission Permission) (bool, error) {\n\tval := (this.PermissionMask&permission != 0)\n\treturn val, nil\n}\n\nfunc NewAdminRole(name string, mask Permission) Role ", "output": "{\n\treturn &defaultRole{RoleName: name, PermissionMask: mask, Admin: true}\n}"} {"input": "package pathmgr\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\n\n\n\n\n\n\n\n\n\ntype SyncPaths struct {\n\tvalue atomic.Value\n\tmutex sync.Mutex\n}\n\n\n\ntype SyncPathsData struct {\n\tAPS AppPathSet\n\tModifyTime time.Time\n\tRefreshTime time.Time\n}\n\n\n\n\n\n\n\n\n\n\nfunc (sp *SyncPaths) update(newAPS AppPathSet) {\n\tsp.mutex.Lock()\n\tdefer sp.mutex.Unlock()\n\tvalue := sp.value.Load().(*SyncPathsData)\n\tvalue.RefreshTime = time.Now()\n\ttoAdd := setSubtract(newAPS, value.APS)\n\ttoRemove := setSubtract(value.APS, newAPS)\n\tif len(toAdd) > 0 || len(toRemove) > 0 {\n\t\tvalue.ModifyTime = value.RefreshTime\n\t}\n\tvalue.APS = newAPS\n\tsp.value.Store(value)\n}\n\n\nfunc (sp *SyncPaths) Load() *SyncPathsData {\n\treturn sp.value.Load().(*SyncPathsData)\n}\n\nfunc setSubtract(x, y AppPathSet) AppPathSet {\n\tresult := make(AppPathSet)\n\tfor _, ap := range x {\n\t\tif _, ok := y[ap.Key()]; !ok {\n\t\t\tresult.Add(ap.Entry)\n\t\t}\n\t}\n\treturn result\n}\n\nfunc NewSyncPaths() *SyncPaths ", "output": "{\n\tsp := &SyncPaths{}\n\tnow := time.Now()\n\tsp.value.Store(\n\t\t&SyncPathsData{\n\t\t\tAPS: make(AppPathSet),\n\t\t\tModifyTime: now,\n\t\t\tRefreshTime: now,\n\t\t},\n\t)\n\treturn sp\n}"} {"input": "package io\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc Info(args ...interface{}) {\n\tfmt.Print(\"\\033[1m-----> \")\n\targs = append(args, \"\\033[0m\")\n\tfmt.Println(args...)\n}\n\nfunc Infof(format string, args ...interface{}) {\n\tfmt.Print(\"\\033[1m-----> \")\n\tfmt.Printf(format+\"\\033[0m\", args...)\n}\n\nfunc Print(args ...interface{}) {\n\tfmt.Print(\" \")\n\tfmt.Println(args...)\n}\n\n\n\nfunc Warnf(format string, args ...interface{}) {\n\tfmt.Print(\" ! \")\n\tfmt.Printf(format, args...)\n}\n\nfunc Error(args ...interface{}) {\n\tfmt.Print(\" ! \")\n\tfmt.Println(args...)\n\tos.Exit(1)\n}\n\nfunc Printf(format string, args ...interface{}) ", "output": "{\n\tfmt.Print(\" \")\n\tfmt.Printf(format, args...)\n}"} {"input": "package libcontainer\n\nimport (\n \"fmt\"\n \"os\"\n \"strings\"\n\n \"github.com/syndtr/gocapability/capability\"\n)\n\nconst allCapabilityTypes = capability.CAPS | capability.BOUNDS\n\nvar capabilityMap map[string]capability.Cap\n\n\n\nfunc newCapWhitelist(caps []string) (*whitelist, error) {\n l := []capability.Cap{}\n for _, c := range caps {\n v, ok := capabilityMap[c]\n if !ok {\n return nil, fmt.Errorf(\"unknown capability %q\", c)\n }\n l = append(l, v)\n }\n pid, err := capability.NewPid(os.Getpid())\n if err != nil {\n return nil, err\n }\n return &whitelist{\n keep: l,\n pid: pid,\n }, nil\n}\n\ntype whitelist struct {\n pid capability.Capabilities\n keep []capability.Cap\n}\n\n\nfunc (w *whitelist) dropBoundingSet() error {\n w.pid.Clear(capability.BOUNDS)\n w.pid.Set(capability.BOUNDS, w.keep...)\n return w.pid.Apply(capability.BOUNDS)\n}\n\n\nfunc (w *whitelist) drop() error {\n w.pid.Clear(allCapabilityTypes)\n w.pid.Set(allCapabilityTypes, w.keep...)\n return w.pid.Apply(allCapabilityTypes)\n}\n\nfunc init() ", "output": "{\n capabilityMap = make(map[string]capability.Cap)\n last := capability.CAP_LAST_CAP\n \n if last == capability.Cap(63) {\n last = capability.CAP_BLOCK_SUSPEND\n }\n for _, cap := range capability.List() {\n if cap > last {\n continue\n }\n capKey := fmt.Sprintf(\"CAP_%s\", strings.ToUpper(cap.String()))\n capabilityMap[capKey] = cap\n }\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\n\t\"gopkg.in/stretchr/testify.v1/mock\"\n)\n\ntype Printer interface {\n\tHelp()\n\tVersion()\n\tMessage(msg string)\n\tError(err error)\n\tCommands()\n}\n\ntype TextPrinter struct {\n\tversion string\n}\n\nfunc NewTextPrinter(version string) *TextPrinter {\n\treturn &TextPrinter{version}\n}\n\nfunc (p *TextPrinter) Help() {\n\thelpText := `Name:\n\tfiz - a file wizard\n\nVersion:\n\t` + p.version + `\n\nUsage:\n\tfiz \n\n`\n\tp.Message(helpText)\n\tp.Commands()\n}\n\nfunc (p *TextPrinter) Version() {\n\tfmt.Println(\"fiz\", p.version)\n}\n\nfunc (p *TextPrinter) Message(msg string) {\n\tfmt.Print(msg)\n}\n\nfunc (p *TextPrinter) Error(err error) {\n\tfmt.Println(\"Error: \", err)\n}\n\nfunc (p *TextPrinter) Commands() {\n\tp.Message(COMMANDS_MSG)\n}\n\n\ntype MockPrinter struct {\n\tmock.Mock\n}\n\nfunc NewMockPrinter() *MockPrinter {\n\treturn &MockPrinter{}\n}\n\nfunc (m *MockPrinter) Help() {\n\tm.Called()\n}\n\n\n\nfunc (m *MockPrinter) Message(msg string) {\n\tm.Called(msg)\n}\n\nfunc (m *MockPrinter) Error(err error) {\n\tm.Called(err)\n}\n\nfunc (m *MockPrinter) Commands() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Version() ", "output": "{\n\tm.Called()\n}"} {"input": "package guard\n\nimport (\n\t\"time\"\n\n\t\"gopkg.in/workanator/go-floc.v2\"\n\t\"gopkg.in/workanator/go-floc.v2/errors\"\n)\n\n\ntype TimeoutTrigger func(ctx floc.Context, ctrl floc.Control, id interface{})\n\n\n\n\nfunc Timeout(when WhenTimeoutFunc, id interface{}, job floc.Job) floc.Job {\n\treturn OnTimeout(when, id, job, nil)\n}\n\n\n\n\n\n\n\nfunc OnTimeout(when WhenTimeoutFunc, id interface{}, job floc.Job, timeoutTrigger TimeoutTrigger) floc.Job ", "output": "{\n\treturn func(ctx floc.Context, ctrl floc.Control) error {\n\t\tdone := make(chan error)\n\t\tdefer close(done)\n\n\t\ttimer := time.NewTimer(when(ctx, id))\n\t\tdefer timer.Stop()\n\n\t\tgo func() {\n\t\t\tvar err error\n\t\t\tdefer func() { done <- err }()\n\t\t\terr = job(ctx, ctrl)\n\t\t}()\n\n\t\tselect {\n\t\tcase <-ctx.Done():\n\n\t\tcase err := <-done:\n\t\t\treturn err\n\n\t\tcase <-timer.C:\n\t\t\tif timeoutTrigger != nil {\n\t\t\t\ttimeoutTrigger(ctx, ctrl, id)\n\t\t\t} else {\n\t\t\t\tctrl.Fail(id, errors.NewErrTimeout(id, time.Now().UTC()))\n\t\t\t}\n\t\t}\n\n\t\treturn <-done\n\t}\n}"} {"input": "package pool\n\nimport \"sync/atomic\"\n\n\ntype WorkUnit interface {\n\n\tWait()\n\n\tValue() interface{}\n\n\tError() error\n\n\tCancel()\n\n\tIsCancelled() bool\n}\n\nvar _ WorkUnit = new(workUnit)\n\n\ntype workUnit struct {\n\tvalue interface{}\n\terr error\n\tdone chan struct{}\n\tfn WorkFunc\n\tcancelled atomic.Value\n\tcancelling atomic.Value\n\twriting atomic.Value\n}\n\n\n\n\nfunc (wu *workUnit) cancelWithError(err error) {\n\n\twu.cancelling.Store(struct{}{})\n\n\tif wu.writing.Load() == nil && wu.cancelled.Load() == nil {\n\t\twu.cancelled.Store(struct{}{})\n\t\twu.err = err\n\t\tclose(wu.done)\n\t}\n}\n\n\nfunc (wu *workUnit) Wait() {\n\t<-wu.done\n}\n\n\nfunc (wu *workUnit) Value() interface{} {\n\treturn wu.value\n}\n\n\nfunc (wu *workUnit) Error() error {\n\treturn wu.err\n}\n\n\n\n\nfunc (wu *workUnit) IsCancelled() bool {\n\twu.writing.Store(struct{}{}) \n\treturn wu.cancelled.Load() != nil\n}\n\nfunc (wu *workUnit) Cancel() ", "output": "{\n\twu.cancelWithError(&ErrCancelled{s: errCancelled})\n}"} {"input": "package network\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/\" + version.Number + \" network/2019-08-01\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/spf13/viper\"\n)\n\ntype writeStdout struct {\n}\n\n\n\n\n\nfunc NewWriteStdout(cfg *viper.Viper) (interface{}, error) {\n\treturn &writeStdout{}, nil\n}\n\nfunc (s *writeStdout) Write(dirname, filename, content, contentType, contentEncoding string,\n\tmetadata map[string]*string) error ", "output": "{\n\tfmt.Printf(\"--- %s/%s ---\\n\", dirname, filename)\n\tfmt.Printf(\"%s\\n\", content)\n\treturn nil\n}"} {"input": "package api\n\ntype FormatsResponse struct {\n\tFormats []string `json:\"formats\"`\n}\n\nfunc (a *API) getFormats(ctx *context) {\n\tctx.Success(FormatsResponse{Formats: a.c.formats.Keys()})\n}\n\ntype LeechTypesResponse struct {\n\tLeechTypes []string `json:\"leech_types\"`\n}\n\nfunc (a *API) getLeechTypes(ctx *context) {\n\tctx.Success(LeechTypesResponse{LeechTypes: a.c.leechTypes.Keys()})\n}\n\ntype MediaResponse struct {\n\tMedia []string `json:\"media\"`\n}\n\nfunc (a *API) getMedia(ctx *context) {\n\tctx.Success(MediaResponse{Media: a.c.media.Keys()})\n}\n\ntype ReleaseGroupTypesResponse struct {\n\tReleaseGroupTypes []string `json:\"release_group_types\"`\n}\n\nfunc (a *API) getReleaseGroupTypes(ctx *context) {\n\tctx.Success(ReleaseGroupTypesResponse{ReleaseGroupTypes: a.c.releaseGroupTypes.Keys()})\n}\n\ntype ReleasePropertiesResponse struct {\n\tReleaseProperties []string `json:\"release_properties\"`\n}\n\nfunc (a *API) getReleaseProperties(ctx *context) {\n\tctx.Success(ReleasePropertiesResponse{ReleaseProperties: a.c.releaseProperties.Keys()})\n}\n\ntype ReleaseRolesResponse struct {\n\tReleaseRoles []string `json:\"release_roles\"`\n}\n\n\n\ntype PrivilegesResponse struct {\n\tPrivileges []string `json:\"privileges\"`\n}\n\nfunc (a *API) getPrivileges(ctx *context) {\n\tctx.Success(PrivilegesResponse{Privileges: a.c.privileges.Keys()})\n}\n\nfunc (a *API) getReleaseRoles(ctx *context) ", "output": "{\n\tctx.Success(ReleaseRolesResponse{ReleaseRoles: a.c.releaseRoles.Keys()})\n}"} {"input": "package godo\n\nimport(\n\t\"github.com/jmoiron/modl\"\n\t\"database/sql\"\n\t_ \"github.com/mattn/go-sqlite3\"\n\t\"log\"\n)\n\nvar Dbmap *modl.DbMap\n\nfunc InitDb(dbname string) *modl.DbMap {\n\tdb, err := sql.Open(\"sqlite3\", \"/tmp/\"+dbname)\n\tCheckErr(err, \"sql.Open failed\")\n\n\tdbmap := modl.NewDbMap(db, modl.SqliteDialect{})\n\n\tdbmap.AddTableWithName(Task{}, \"tasks\").SetKeys(true, \"ID\")\n\tdbmap.AddTableWithName(Project{}, \"projects\").SetKeys(true, \"ID\")\n\tDbmap = dbmap\n\n\terr = dbmap.CreateTablesIfNotExists()\n\tCheckErr(err, \"Create tables failed\")\n\n\treturn dbmap\n}\n\nfunc CheckErr(err error, msg string) {\n\tif err != nil {\n\t\tlog.Fatalln(msg, err)\n\t}\n}\n\n\n\nfunc ResetDatabase() ", "output": "{\n\tDbmap.TruncateTables()\n}"} {"input": "package test\n\nimport (\n\tcryptoTest \"github.com/tidepool-org/platform/crypto/test\"\n\timageStoreStructured \"github.com/tidepool-org/platform/image/store/structured\"\n\timageTest \"github.com/tidepool-org/platform/image/test\"\n\t\"github.com/tidepool-org/platform/pointer\"\n\t\"github.com/tidepool-org/platform/test\"\n)\n\nfunc RandomUpdate() *imageStoreStructured.Update {\n\tdatum := imageStoreStructured.NewUpdate()\n\tdatum.Metadata = imageTest.RandomMetadata()\n\tdatum.ContentID = pointer.FromString(imageTest.RandomContentID())\n\tdatum.ContentIntent = pointer.FromString(imageTest.RandomContentIntent())\n\tdatum.ContentAttributes = RandomContentAttributes()\n\tdatum.RenditionsID = nil\n\tdatum.Rendition = nil\n\treturn datum\n}\n\n\n\nfunc RandomContentAttributes() *imageStoreStructured.ContentAttributes ", "output": "{\n\tdatum := imageStoreStructured.NewContentAttributes()\n\tdatum.DigestMD5 = pointer.FromString(cryptoTest.RandomBase64EncodedMD5Hash())\n\tdatum.MediaType = pointer.FromString(imageTest.RandomMediaType())\n\tdatum.Width = pointer.FromInt(imageTest.RandomWidth())\n\tdatum.Height = pointer.FromInt(imageTest.RandomHeight())\n\tdatum.Size = pointer.FromInt(test.RandomIntFromRange(1, 100*1024*1024))\n\treturn datum\n}"} {"input": "package postgres\n\nimport \"github.com/shijuvar/gokit/examples/http-app/pkg/domain\"\n\n\ntype ProductStore struct {\n\tStore DataStore\n}\n\n\n\n\n\nfunc (productStore ProductStore) Create(product domain.Product) (domain.Product, error) ", "output": "{\n\treturn domain.Product{}, nil\n}"} {"input": "package autostart\n\nimport (\n\t\"flag\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/vim25/types\"\n)\n\ntype add struct {\n\t*AutostartFlag\n}\n\nfunc init() {\n\tcli.Register(\"host.autostart.add\", &add{})\n}\n\n\n\nfunc (cmd *add) Process(ctx context.Context) error {\n\tif err := cmd.AutostartFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (cmd *add) Usage() string {\n\treturn \"VM...\"\n}\n\nfunc (cmd *add) Run(ctx context.Context, f *flag.FlagSet) error {\n\tvar powerInfo = types.AutoStartPowerInfo{\n\t\tStartAction: \"powerOn\",\n\t\tStartDelay: -1,\n\t\tStartOrder: -1,\n\t\tStopAction: \"systemDefault\",\n\t\tStopDelay: -1,\n\t\tWaitForHeartbeat: types.AutoStartWaitHeartbeatSettingSystemDefault,\n\t}\n\n\treturn cmd.ReconfigureVMs(f.Args(), powerInfo)\n}\n\nfunc (cmd *add) Register(ctx context.Context, f *flag.FlagSet) ", "output": "{\n\tcmd.AutostartFlag, ctx = newAutostartFlag(ctx)\n\tcmd.AutostartFlag.Register(ctx, f)\n}"} {"input": "package datadog\n\nimport (\n\tcc \"github.com/grokify/commonchat\"\n\n\t\"github.com/grokify/chathooks/pkg/config\"\n\t\"github.com/grokify/chathooks/pkg/handlers\"\n\t\"github.com/grokify/chathooks/pkg/util\"\n)\n\n\n\nfunc ExampleMessage(cfg config.Configuration, data util.ExampleData) (cc.Message, error) ", "output": "{\n\tbytes, err := data.ExampleMessageBytes(HandlerKey, \"formatted1\")\n\tif err != nil {\n\t\treturn cc.Message{}, err\n\t}\n\treturn Normalize(cfg, handlers.HandlerRequest{Body: bytes})\n}"} {"input": "package gospec\n\nimport (\n\t\"fmt\"\n\tfilepath \"path\"\n\t\"runtime\"\n)\n\ntype Location struct {\n\tname string\n\tfile string\n\tline int\n}\n\nfunc currentLocation() *Location {\n\treturn newLocation(1)\n}\n\nfunc callerLocation() *Location {\n\treturn newLocation(2)\n}\n\nfunc newLocation(n int) *Location {\n\tif pc, _, _, ok := runtime.Caller(n + 1); ok {\n\t\treturn locationForPC(pc)\n\t}\n\treturn nil\n}\n\nfunc locationForPC(pc uintptr) *Location {\n\tpc = pcOfWhereCallWasMade(pc)\n\tf := runtime.FuncForPC(pc)\n\tname := f.Name()\n\tfile, line := f.FileLine(pc)\n\treturn &Location{name, file, line}\n}\n\n\n\n\n\n\n\n\nfunc pcOfWhereCallWasMade(pcOfWhereCallReturnsTo uintptr) uintptr {\n\treturn pcOfWhereCallReturnsTo - 1\n}\n\nfunc (this *Location) Name() string { return this.name }\nfunc (this *Location) File() string { return this.file }\nfunc (this *Location) FileName() string { return filename(this.file) }\nfunc (this *Location) Line() int { return this.line }\n\nfunc filename(path string) string {\n\t_, file := filepath.Split(path)\n\treturn file\n}\n\nfunc (this *Location) equals(that *Location) bool {\n\treturn this.name == that.name &&\n\t\tthis.file == that.file &&\n\t\tthis.line == that.line\n}\n\n\n\nfunc (this *Location) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%v:%v\", this.FileName(), this.Line())\n}"} {"input": "package sum\n\nimport (\n\t\"github.com/catorpilor/leetcode/utils\"\n)\n\n\n\nfunc helper(node *utils.TreeNode, val int) int {\n\tif node == nil {\n\t\treturn val\n\t}\n\tval = val*10 + node.Val\n\tif node.Left == nil && node.Right == nil {\n\t\treturn val\n\t}\n\tleftSum, rightSum := 0, 0\n\tif node.Left != nil {\n\t\tleftSum = helper(node.Left, val)\n\t}\n\tif node.Right != nil {\n\t\trightSum = helper(node.Right, val)\n\t}\n\treturn leftSum + rightSum\n}\n\nfunc SumNumbers(root *utils.TreeNode) int ", "output": "{\n\treturn helper(root, 0)\n}"} {"input": "package git\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/Originate/git-town/src/command\"\n\t\"github.com/Originate/git-town/src/util\"\n)\n\n\n\nfunc EnsureDoesNotHaveConflicts() {\n\tutil.Ensure(!HasConflicts(), \"You must resolve the conflicts before continuing\")\n}\n\n\n\n\n\n\nvar rootDirectory string\n\n\n\nfunc GetRootDirectory() string {\n\tif rootDirectory == \"\" {\n\t\trootDirectory = command.MustRun(\"git\", \"rev-parse\", \"--show-toplevel\").OutputSanitized()\n\t}\n\treturn rootDirectory\n}\n\n\nfunc HasConflicts() bool {\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"Unmerged paths\")\n}\n\n\nfunc HasOpenChanges() bool {\n\treturn command.MustRun(\"git\", \"status\", \"--porcelain\").OutputSanitized() != \"\"\n}\n\n\n\nfunc HasShippableChanges(branchName string) bool {\n\treturn command.MustRun(\"git\", \"diff\", Config().GetMainBranch()+\"..\"+branchName).OutputSanitized() != \"\"\n}\n\n\n\nfunc IsMergeInProgress() bool {\n\t_, err := os.Stat(fmt.Sprintf(\"%s/.git/MERGE_HEAD\", GetRootDirectory()))\n\treturn err == nil\n}\n\n\n\nfunc IsRebaseInProgress() bool {\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"rebase in progress\")\n}\n\nfunc EnsureDoesNotHaveOpenChanges(message string) ", "output": "{\n\tutil.Ensure(!HasOpenChanges(), \"You have uncommitted changes. \"+message)\n}"} {"input": "package httpmux\n\nimport \"net/http\"\n\n\ntype ConfigOption interface {\n\tSet(c *Config)\n}\n\n\ntype ConfigOptionFunc func(c *Config)\n\n\nfunc (f ConfigOptionFunc) Set(c *Config) { f(c) }\n\n\nfunc WithPrefix(prefix string) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Prefix = prefix })\n}\n\n\nfunc WithMiddleware(mw ...Middleware) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Middleware = mw })\n}\n\n\n\n\n\nfunc WithRedirectTrailingSlash(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectTrailingSlash = v })\n}\n\n\nfunc WithRedirectFixedPath(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectFixedPath = v })\n}\n\n\nfunc WithHandleMethodNotAllowed(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.HandleMethodNotAllowed = v })\n}\n\n\nfunc WithNotFound(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.NotFound = f })\n}\n\n\nfunc WithMethodNotAllowed(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.MethodNotAllowed = f })\n}\n\n\nfunc WithPanicHandler(f func(http.ResponseWriter, *http.Request, interface{})) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.PanicHandler = f })\n}\n\nfunc WithMiddlewareFunc(mw ...MiddlewareFunc) ConfigOption ", "output": "{\n\treturn ConfigOptionFunc(func(c *Config) { c.UseFunc(mw...) })\n}"} {"input": "package github\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/hashicorp/vault/api\"\n)\n\ntype CLIHandler struct{}\n\n\n\nfunc (h *CLIHandler) Help() string {\n\thelp := `\nThe GitHub credential provider allows you to authenticate with GitHub.\nTo use it, specify the \"token\" parameter. The value should be a personal access\ntoken for your GitHub account. You can generate a personal access token on your\naccount settings page on GitHub.\n\n Example: vault auth -method=github token=\n\nKey/Value Pairs:\n\n mount=github The mountpoint for the GitHub credential provider.\n Defaults to \"github\"\n\n token= The GitHub personal access token for authentication.\n\t`\n\n\treturn strings.TrimSpace(help)\n}\n\nfunc (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, error) ", "output": "{\n\tmount, ok := m[\"mount\"]\n\tif !ok {\n\t\tmount = \"github\"\n\t}\n\n\ttoken, ok := m[\"token\"]\n\tif !ok {\n\t\tif token = os.Getenv(\"VAULT_AUTH_GITHUB_TOKEN\"); token == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"GitHub token should be provided either as 'value' for 'token' key,\\nor via an env var VAULT_AUTH_GITHUB_TOKEN\")\n\t\t}\n\t}\n\n\tpath := fmt.Sprintf(\"auth/%s/login\", mount)\n\tsecret, err := c.Logical().Write(path, map[string]interface{}{\n\t\t\"token\": token,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif secret == nil {\n\t\treturn nil, fmt.Errorf(\"empty response from credential provider\")\n\t}\n\n\treturn secret, nil\n}"} {"input": "package unversioned\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/testapi\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\ntype HTTPClientFunc func(*http.Request) (*http.Response, error)\n\nfunc (f HTTPClientFunc) Do(req *http.Request) (*http.Response, error) {\n\treturn f(req)\n}\n\n\ntype FakeRESTClient struct {\n\tClient HTTPClient\n\tCodec runtime.Codec\n\tReq *http.Request\n\tResp *http.Response\n\tErr error\n}\n\n\n\nfunc (c *FakeRESTClient) Put() *Request {\n\treturn NewRequest(c, \"PUT\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Patch(_ api.PatchType) *Request {\n\treturn NewRequest(c, \"PATCH\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Post() *Request {\n\treturn NewRequest(c, \"POST\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Delete() *Request {\n\treturn NewRequest(c, \"DELETE\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Do(req *http.Request) (*http.Response, error) {\n\tc.Req = req\n\tif c.Client != HTTPClient(nil) {\n\t\treturn c.Client.Do(req)\n\t}\n\treturn c.Resp, c.Err\n}\n\nfunc (c *FakeRESTClient) Get() *Request ", "output": "{\n\treturn NewRequest(c, \"GET\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}"} {"input": "package alert\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/opsgenie/opsgenie-go-sdk-v2/client\"\n\t\"github.com/pkg/errors\"\n)\n\ntype DeleteAttachmentRequest struct {\n\tclient.BaseRequest\n\tIdentifierType AlertIdentifier\n\tIdentifierValue string\n\tAttachmentId string\n\tUser string\n}\n\nfunc (r *DeleteAttachmentRequest) Validate() error {\n\tif r.AttachmentId == \"\" {\n\t\treturn errors.New(\"AttachmentId can not be empty\")\n\t}\n\n\tif r.IdentifierValue == \"\" {\n\t\treturn errors.New(\"Identifier can not be empty\")\n\t}\n\treturn nil\n}\n\n\n\nfunc (r *DeleteAttachmentRequest) Method() string {\n\treturn http.MethodDelete\n}\n\nfunc (r *DeleteAttachmentRequest) RequestParams() map[string]string {\n\n\tparams := make(map[string]string)\n\n\tif r.IdentifierType == ALIAS {\n\t\tparams[\"alertIdentifierType\"] = \"alias\"\n\n\t} else if r.IdentifierType == TINYID {\n\t\tparams[\"alertIdentifierType\"] = \"tiny\"\n\n\t} else {\n\t\tparams[\"alertIdentifierType\"] = \"id\"\n\n\t}\n\n\tif r.User != \"\" {\n\t\tparams[\"user\"] = r.User\n\t}\n\n\treturn params\n}\n\nfunc (r *DeleteAttachmentRequest) ResourcePath() string ", "output": "{\n\n\treturn \"/v2/alerts/\" + r.IdentifierValue + \"/attachments/\" + r.AttachmentId\n}"} {"input": "package supervisor_test\n\nimport (\n\t\"go-common/library/net/http/blademaster\"\n\t\"go-common/library/net/http/blademaster/middleware/supervisor\"\n\t\"time\"\n)\n\n\n\n\n\n\n\nfunc Example() ", "output": "{\n\tnow := time.Now()\n\tend := now.Add(time.Hour * 1)\n\tspv := supervisor.New(&supervisor.Config{\n\t\tOn: true,\n\t\tBegin: now,\n\t\tEnd: end,\n\t})\n\n\tengine := blademaster.Default()\n\tengine.Use(spv)\n\tengine.GET(\"/ping\", func(c *blademaster.Context) {\n\t\tc.String(200, \"%s\", \"pong\")\n\t})\n\tengine.Run(\":18080\")\n}"} {"input": "package openstack\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gophercloud/gophercloud\"\n\ttokens2 \"github.com/gophercloud/gophercloud/openstack/identity/v2/tokens\"\n\ttokens3 \"github.com/gophercloud/gophercloud/openstack/identity/v3/tokens\"\n)\n\n\n\ntype ErrEndpointNotFound struct{ gophercloud.BaseError }\n\nfunc (e ErrEndpointNotFound) Error() string {\n\treturn \"No suitable endpoint could be found in the service catalog.\"\n}\n\n\n\ntype ErrInvalidAvailabilityProvided struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrInvalidAvailabilityProvided) Error() string {\n\treturn fmt.Sprintf(\"Unexpected availability in endpoint query: %s\", e.Value)\n}\n\n\n\ntype ErrMultipleMatchingEndpointsV2 struct {\n\tgophercloud.BaseError\n\tEndpoints []tokens2.Endpoint\n}\n\nfunc (e ErrMultipleMatchingEndpointsV2) Error() string {\n\treturn fmt.Sprintf(\"Discovered %d matching endpoints: %#v\", len(e.Endpoints), e.Endpoints)\n}\n\n\n\ntype ErrMultipleMatchingEndpointsV3 struct {\n\tgophercloud.BaseError\n\tEndpoints []tokens3.Endpoint\n}\n\nfunc (e ErrMultipleMatchingEndpointsV3) Error() string {\n\treturn fmt.Sprintf(\"Discovered %d matching endpoints: %#v\", len(e.Endpoints), e.Endpoints)\n}\n\n\n\ntype ErrNoAuthURL struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoAuthURL) Error() string {\n\treturn \"Environment variable OS_AUTH_URL needs to be set.\"\n}\n\n\n\ntype ErrNoUsername struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoUsername) Error() string {\n\treturn \"Environment variable OS_USERNAME needs to be set.\"\n}\n\n\n\ntype ErrNoPassword struct{ gophercloud.ErrInvalidInput }\n\n\n\nfunc (e ErrNoPassword) Error() string ", "output": "{\n\treturn \"Environment variable OS_PASSWORD needs to be set.\"\n}"} {"input": "package loads\n\nimport \"jvmgo/ch09/instructions/base\"\nimport \"jvmgo/ch09/rtda\"\n\n\ntype ILOAD struct{ base.Index8Instruction }\n\nfunc (self *ILOAD) Execute(frame *rtda.Frame) {\n\t_iload(frame, self.Index)\n}\n\ntype ILOAD_0 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_0) Execute(frame *rtda.Frame) {\n\t_iload(frame, 0)\n}\n\ntype ILOAD_1 struct{ base.NoOperandsInstruction }\n\n\n\ntype ILOAD_2 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_2) Execute(frame *rtda.Frame) {\n\t_iload(frame, 2)\n}\n\ntype ILOAD_3 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_3) Execute(frame *rtda.Frame) {\n\t_iload(frame, 3)\n}\n\nfunc _iload(frame *rtda.Frame, index uint) {\n\tval := frame.LocalVars().GetInt(index)\n\tframe.OperandStack().PushInt(val)\n}\n\nfunc (self *ILOAD_1) Execute(frame *rtda.Frame) ", "output": "{\n\t_iload(frame, 1)\n}"} {"input": "package utils\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n\n\t\"github.com/astaxie/beego\"\n)\n\nvar testRandNum int\nvar testRandString string\n\n\n\n\n\nfunc GetRandNum(n int) int {\n\tif IsTest() {\n\t\treturn testRandNum\n\t}\n\n\trand.Seed(time.Now().UnixNano())\n\n\treturn rand.Intn(n)\n}\n\n\nfunc SetTestRandString(s string) {\n\tif !IsTest() {\n\t\treturn\n\t}\n\n\ttestRandString = s\n}\n\n\nfunc GetRandString(n int) string {\n\tif IsTest() {\n\t\treturn testRandString\n\t}\n\n\trs2Letters := beego.AppConfig.String(\"randKey\")\n\n\tb := make([]byte, n)\n\tfor i := range b {\n\t\tb[i] = rs2Letters[rand.Intn(len(rs2Letters))]\n\t}\n\n\treturn string(b)\n}\n\nfunc SetTestRandNum(n int) ", "output": "{\n\tif !IsTest() {\n\t\treturn\n\t}\n\n\ttestRandNum = n\n}"} {"input": "package testing_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\n\n\n\n\n\nfunc TestMain(m *testing.M) ", "output": "{\n\tos.Exit(m.Run())\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n)\n\nvar (\n\tlogger *log.Logger\n\tlog_filename string\n\tlog_mutex sync.Mutex\n)\n\n\n\nfunc new_logger(w io.Writer) *log.Logger {\n\n\treturn log.New(w, \"\", log.Ldate|log.Ltime|log.LUTC)\n}\n\nfunc log_printf(format string, a ...interface{}) {\n\n\t_, err := os.Stat(log_filename)\n\tif err != nil && os.IsNotExist(err) {\n\t\tlog_mutex.Lock()\n\n\t\t_, err := os.Stat(log_filename)\n\t\tif err != nil && os.IsNotExist(err) {\n\t\t\tnew_log_file, err := os.Create(log_filename)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"error creating new log file\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tlogger = new_logger(new_log_file)\n\t\t}\n\n\t\tlog_mutex.Unlock()\n\t}\n\n\tlogger.Printf(format, a...)\n\n\tif strings.Compare(config_get(\"stdout\"), \"true\") == 0 {\n\t\tfmt.Printf(format, a...)\n\t}\n}\n\nfunc log_init(filename string) ", "output": "{\n\n\tlog_filename = filename\n\n\tvar log_file *os.File = nil\n\n\t_, err := os.Stat(log_filename)\n\tif os.IsNotExist(err) {\n\t\tlog_file, err = os.Create(log_filename)\n\t\terr = nil\n\t} else if err != nil {\n\t\tfmt.Printf(\"unknown error checking log file %s\\n\", log_filename)\n\t\tfmt.Printf(\"%v\\n\", err)\n\t\tos.Exit(1)\n\t} else {\n\t\tlog_file, err = os.OpenFile(log_filename,\n\t\t\tos.O_APPEND|os.O_WRONLY,\n\t\t\t0644)\n\t}\n\n\tif err != nil {\n\t\tfmt.Printf(\"error opening log file %s\\n\", log_filename)\n\t\tfmt.Printf(\"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlogger = new_logger(log_file)\n}"} {"input": "package runtime\n\nimport (\n\t\"encoding/gob\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\nvar (\n\tgoatsSettings *GoatsSettings\n)\n\nfunc NewGoatsSettings() *GoatsSettings {\n\treturn &GoatsSettings{}\n}\n\n\n\nfunc DecodeRpcRequestOrFail(input io.Reader, settings *TemplateSettings, args interface{}) {\n\tdecoder := gob.NewDecoder(input)\n\terr := decoder.Decode(settings)\n\tif err == nil {\n\t\terr = decoder.Decode(args)\n\t}\n\tif err != nil {\n\t\tfmt.Fprint(os.Stderr, err)\n\t\tos.Exit(2)\n\t}\n}\n\nfunc InitGoats(settings *GoatsSettings) ", "output": "{\n\tif settings == nil {\n\t\tgoatsSettings = NewGoatsSettings()\n\t} else {\n\t\tgoatsSettings = settings\n\t}\n}"} {"input": "package metricsaccountant_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestMetricsAccountant(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Metricsaccountant Suite\")\n}"} {"input": "package iso20022\n\n\ntype Tax13 struct {\n\n\tType *TaxType9Code `xml:\"Tp\"`\n\n\tOtherTaxType *Max35Text `xml:\"OthrTaxTp\"`\n\n\tAmount *CurrencyAndAmount `xml:\"Amt\"`\n\n\tRate *PercentageRate `xml:\"Rate\"`\n}\n\nfunc (t *Tax13) SetType(value string) {\n\tt.Type = (*TaxType9Code)(&value)\n}\n\n\n\nfunc (t *Tax13) SetAmount(value, currency string) {\n\tt.Amount = NewCurrencyAndAmount(value, currency)\n}\n\nfunc (t *Tax13) SetRate(value string) {\n\tt.Rate = (*PercentageRate)(&value)\n}\n\nfunc (t *Tax13) SetOtherTaxType(value string) ", "output": "{\n\tt.OtherTaxType = (*Max35Text)(&value)\n}"} {"input": "package lib\n\n\nimport \"C\"\n\nfunc CheckIsSupported(check int) bool {\n\treturn C.lzma_check_is_supported(C.lzma_check(check)) != 0\n}\n\nfunc CheckSize(check int) int {\n\treturn int(C.lzma_check_size(C.lzma_check(check)))\n}\n\nfunc CRC32(buf []byte, crc uint32) uint32 {\n\tptr, size := CSlicePtrLen(buf)\n\treturn uint32(C.lzma_crc32(ptr, size, C.uint32_t(crc)))\n}\n\nfunc CRC64(buf []byte, crc uint64) uint64 {\n\tptr, size := CSlicePtrLen(buf)\n\treturn uint64(C.lzma_crc64(ptr, size, C.uint64_t(crc)))\n}\n\n\n\nfunc (z *Stream) GetCheck() int ", "output": "{\n\treturn int(C.lzma_get_check(z.C()))\n}"} {"input": "package integration\n\nimport (\n\t\"k8s.io/minikube/test/integration/util\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestClusterSSH(t *testing.T) ", "output": "{\n\tminikubeRunner := util.MinikubeRunner{BinaryPath: *binaryPath, T: t}\n\tminikubeRunner.EnsureRunning()\n\n\texpectedStr := \"hello\"\n\tsshCmdOutput := minikubeRunner.RunCommand(\"ssh echo \"+expectedStr, true)\n\tif !strings.Contains(sshCmdOutput, expectedStr) {\n\t\tt.Fatalf(\"ExpectedStr sshCmdOutput to be: %s. Output was: %s\", expectedStr, sshCmdOutput)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/wikiwi/kube-volume-freezer/pkg/client\"\n\t\"github.com/wikiwi/kube-volume-freezer/pkg/util/validation\"\n)\n\ntype listCommand struct {\n}\n\n\n\nfunc init() {\n\tparser.AddCommand(\"list\",\n\t\t\"List Pod Volumes\",\n\t\t\"List Pod Volumes\",\n\t\tnew(listCommand))\n}\n\nfunc (cmd *listCommand) Execute(args []string) error ", "output": "{\n\tif len(args) < 1 {\n\t\treturn fmt.Errorf(\"Error: Please specify Pod and Volume.\")\n\t}\n\tif len(args) > 1 {\n\t\treturn fmt.Errorf(\"Error: Unexpected argument %s\", args[1:])\n\t}\n\n\tpodName := args[0]\n\n\tif issues := validation.ValidateQualitfiedName(podName); len(issues) > 0 {\n\t\treturn fmt.Errorf(\"Error: Invalid Pod Name %s\", issues)\n\t}\n\n\toptions := &client.Options{Token: globalOptions.Token}\n\tclient, err := client.New(globalOptions.Address, options)\n\tif err != nil {\n\t\treturn err\n\t}\n\tls, err := client.Volumes().List(globalOptions.Namespace, podName)\n\tfor _, item := range ls.Items {\n\t\tfmt.Println(item)\n\t}\n\treturn err\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\n\n\n\n\ntype MsgMemPool struct{}\n\n\n\n\n\n\n\nfunc (msg *MsgMemPool) BtcEncode(w io.Writer, pver uint32) error {\n\tif pver < BIP0035Version {\n\t\tstr := fmt.Sprintf(\"mempool message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgMemPool.BtcEncode\", str)\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (msg *MsgMemPool) Command() string {\n\treturn CmdMemPool\n}\n\n\n\nfunc (msg *MsgMemPool) MaxPayloadLength(pver uint32) uint32 {\n\treturn 0\n}\n\n\n\nfunc NewMsgMemPool() *MsgMemPool {\n\treturn &MsgMemPool{}\n}\n\nfunc (msg *MsgMemPool) BtcDecode(r io.Reader, pver uint32) error ", "output": "{\n\tif pver < BIP0035Version {\n\t\tstr := fmt.Sprintf(\"mempool message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgMemPool.BtcDecode\", str)\n\t}\n\n\treturn nil\n}"} {"input": "package swag\n\nimport (\n\t\"sort\"\n\t\"sync\"\n)\n\n\n\ntype indexOfInitialisms struct {\n\tgetMutex *sync.Mutex\n\tindex map[string]bool\n}\n\nfunc newIndexOfInitialisms() *indexOfInitialisms {\n\treturn &indexOfInitialisms{\n\t\tgetMutex: new(sync.Mutex),\n\t\tindex: make(map[string]bool, 50),\n\t}\n}\n\nfunc (m *indexOfInitialisms) load(initial map[string]bool) *indexOfInitialisms {\n\tm.getMutex.Lock()\n\tdefer m.getMutex.Unlock()\n\tfor k, v := range initial {\n\t\tm.index[k] = v\n\t}\n\treturn m\n}\n\nfunc (m *indexOfInitialisms) isInitialism(key string) bool {\n\tm.getMutex.Lock()\n\tdefer m.getMutex.Unlock()\n\t_, ok := m.index[key]\n\treturn ok\n}\n\n\n\nfunc (m *indexOfInitialisms) sorted() (result []string) {\n\tm.getMutex.Lock()\n\tdefer m.getMutex.Unlock()\n\tfor k := range m.index {\n\t\tresult = append(result, k)\n\t}\n\tsort.Sort(sort.Reverse(byLength(result)))\n\treturn\n}\n\nfunc (m *indexOfInitialisms) add(key string) *indexOfInitialisms ", "output": "{\n\tm.getMutex.Lock()\n\tdefer m.getMutex.Unlock()\n\tm.index[key] = true\n\treturn m\n}"} {"input": "package migrations\n\nimport (\n\t\"xorm.io/xorm\"\n)\n\n\n\nfunc purgeInvalidDependenciesComments(x *xorm.Engine) error ", "output": "{\n\t_, err := x.Exec(\"DELETE FROM comment WHERE dependent_issue_id != 0 AND dependent_issue_id NOT IN (SELECT id FROM issue)\")\n\treturn err\n}"} {"input": "package main\n\nimport (\n\t\"time\"\n\n\t\"github.com/PalmStoneGames/polymer\"\n)\n\nfunc init() {\n\tpolymer.Register(\"tick-timer\", &Timer{})\n}\n\ntype Timer struct {\n\t*polymer.Proto\n\n\tTime time.Time `polymer:\"bind\"`\n}\n\n\n\nfunc (t *Timer) ComputeTime() string {\n\treturn t.Time.String()\n}\n\nfunc main() {}\n\nfunc (t *Timer) Created() ", "output": "{\n\tgo func() {\n\t\tfor {\n\t\t\tt.Time = time.Now()\n\n\t\t\tt.Notify(\"time\")\n\n\t\t\ttime.Sleep(time.Millisecond * 100)\n\t\t}\n\t}()\n}"} {"input": "package handlers\n\nimport (\n\t\"github.com/THUNDERGROOVE/SDETool2/log\"\n\t\"html/template\"\n\t\"path/filepath\"\n)\n\nvar Templates map[string]*template.Template\n\nfunc init() {\n\tif Templates == nil {\n\t\tTemplates = make(map[string]*template.Template)\n\t}\n}\n\n\n\nfunc LoadTemplates() ", "output": "{\n\tTemplates = make(map[string]*template.Template)\n\n\tglob := []string{\"template/index.tmpl\", \"template/login.tmpl\",\n\t\t\"template/fit.tmpl\", \"template/newfit.tmpl\",\n\t\t\"template/error.tmpl\", \"template/usermanage.tmpl\",\n\t\t\"template/fits.tmpl\"}\n\tincludes := []string{\"template/base.tmpl\"}\n\tfor _, v := range glob {\n\t\tvar err error\n\t\tlog.Info(\"Attempting to load template\", v, \"with index of\", filepath.Base(v))\n\t\tfiles := append(includes, v)\n\t\tTemplates[filepath.Base(v)] = template.Must(template.ParseFiles(files...))\n\t\tif err != nil {\n\t\t\tlog.LogError(err.Error())\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n)\n\nfunc main() {\n\ttests := []int{234, 4421}\n\n\tfor _, test := range tests {\n\t\tlog.Printf(\"subtractProductAndSum(%d) = %d\\n\", test, subtractProductAndSum(test))\n\t}\n}\n\nfunc subtractProductAndSum(n int) int {\n\tnDigits := getDecimalDigits(n)\n \n\n \n \n\n \n \n\n\treturn (getProduct(nDigits) - getTotal(nDigits))\n}\n\nfunc getDecimalDigits(n int) []int {\n\tres := []int{}\n\n\trem := n % 10\n\tn = n / 10\n\tres = append(res, rem)\n\n\tfor n > 0 {\n\t\trem = n % 10\n\t\tn = n / 10\n\n\t\tres = append(res, rem)\n\t}\n\n\treturn res\n}\n\nfunc getTotal(nums []int) int {\n\tvar tot int\n\n\tfor _, n := range nums {\n\t\ttot += n\n\t}\n\n\treturn tot\n}\n\n\n\nfunc getProduct(nums []int) int ", "output": "{\n\tvar prod int\n\n if len(nums) > 0 {\n prod = 1\n }\n\n\tfor _, n := range nums {\n\t\tprod *= n\n\t}\n\n\treturn prod\n}"} {"input": "package helpers\n\nimport (\n\t\"fmt\"\n\t\"os/user\"\n\t\"os\"\n\t\"runtime\"\n\t\"time\"\n\t\"log\"\n\t\"github.com/joho/godotenv\"\n)\n\nfunc CurrentUser() *user.User {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tSendErrorEmail(\"golang balu\", fmt.Sprintf(\"failed get current user: %s\", err))\n\t\tpanic(err)\n\t}\n\treturn usr\n}\n\nfunc IsDocker() bool {\n\treturn os.Getenv(\"HOME\") == \"/root\"\n}\n\nfunc MonitorRuntime() {\n\tlog.Println(\"Number of CPUs:\", runtime.NumCPU())\n\tm := &runtime.MemStats{}\n\tfor {\n\t\tr := runtime.NumGoroutine()\n\t\tlog.Println(\"Number of goroutines\", r)\n\t\truntime.ReadMemStats(m)\n\t\tlog.Println(\"Allocated memory\", m.Alloc)\n\t\ttime.Sleep(10 * time.Second)\n\t}\n}\n\n\n\nfunc LoadEnvFile() ", "output": "{\n\terr := godotenv.Load()\n\tif err != nil {\n\t\tpanic(\"Error loading .env file\" + err.Error())\n\t}\n}"} {"input": "package memo\n\nimport (\n\t\"encoding/binary\"\n\t\"reflect\"\n\n\t. \"github.com/pingcap/check\"\n\t\"github.com/pingcap/tidb/expression\"\n\tplannercore \"github.com/pingcap/tidb/planner/core\"\n)\n\nfunc (s *testMemoSuite) TestNewGroupExpr(c *C) {\n\tp := &plannercore.LogicalLimit{}\n\texpr := NewGroupExpr(p)\n\tc.Assert(expr.ExprNode, Equals, p)\n\tc.Assert(expr.Children, IsNil)\n\tc.Assert(expr.Explored, IsFalse)\n}\n\n\n\nfunc (s *testMemoSuite) TestGroupExprFingerprint(c *C) ", "output": "{\n\tp := &plannercore.LogicalLimit{Count: 3}\n\texpr := NewGroupExpr(p)\n\tchildGroup := NewGroupWithSchema(nil, expression.NewSchema())\n\texpr.SetChildren(childGroup)\n\tplanHash := p.HashCode()\n\tbuffer := make([]byte, 10+len(planHash))\n\tbinary.BigEndian.PutUint16(buffer, 1)\n\tbinary.BigEndian.PutUint64(buffer[2:], uint64(reflect.ValueOf(childGroup).Pointer()))\n\tcopy(buffer[10:], planHash)\n\tc.Assert(expr.FingerPrint(), Equals, string(buffer))\n}"} {"input": "package shoauth\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\ntype expectedSuccessHandler struct{}\n\nfunc (s *expectedSuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}\n\ntype expectedFailureHandler struct{}\n\nfunc (s *expectedFailureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}\n\ntype unexpectedSuccessHandler struct {\n\tt *testing.T\n}\n\nfunc (s *unexpectedSuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.t.Errorf(\"Request should have failed, but succeeded instead!\")\n}\n\ntype unexpectedFailureHandler struct {\n\tt *testing.T\n}\n\n\n\ntype testPersistence struct {\n\texists bool\n\tcreate error\n\tsession bool\n}\n\nfunc (t *testPersistence) InstallationExists(shopID string) bool {\n\treturn t.exists\n}\n\nfunc (t *testPersistence) CreateInstallation(shopID string, accessToken string) error {\n\treturn t.create\n}\n\nfunc TestAlreadyInstalled(t *testing.T) {\n\tp := testPersistence{\n\t\texists: true,\n\t\tcreate: errors.New(\"Installation already exists!\"),\n\t\tsession: false,\n\t}\n\thandler := NewShopifyOauthHandler(&unexpectedSuccessHandler{t: t}, &expectedFailureHandler{}, &p)\n\ttestServer := httptest.NewServer(handler)\n\tdefer testServer.Close()\n\thttp.Get(testServer.URL + \"/install\")\n}\n\nfunc (s *unexpectedFailureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\ts.t.Errorf(\"Request should have succeeded, but failed instead!\")\n}"} {"input": "package keytransform\n\nimport ds \"github.com/ipfs/go-datastore\"\n\n\ntype Pair struct {\n\tConvert KeyMapping\n\tInvert KeyMapping\n}\n\n\n\nfunc (t *Pair) InvertKey(k ds.Key) ds.Key {\n\treturn t.Invert(k)\n}\n\nvar _ KeyTransform = (*Pair)(nil)\n\n\n\n\n\n\ntype PrefixTransform struct {\n\tPrefix ds.Key\n}\n\n\nfunc (p PrefixTransform) ConvertKey(k ds.Key) ds.Key {\n\treturn p.Prefix.Child(k)\n}\n\n\nfunc (p PrefixTransform) InvertKey(k ds.Key) ds.Key {\n\tif p.Prefix.String() == \"/\" {\n\t\treturn k\n\t}\n\n\tif !p.Prefix.IsAncestorOf(k) {\n\t\tpanic(\"expected prefix not found\")\n\t}\n\n\ts := k.String()[len(p.Prefix.String()):]\n\treturn ds.RawKey(s)\n}\n\nvar _ KeyTransform = (*PrefixTransform)(nil)\n\nfunc (t *Pair) ConvertKey(k ds.Key) ds.Key ", "output": "{\n\treturn t.Convert(k)\n}"} {"input": "package macos\n\n\n\nimport (\n\t\"os\"\n\n\t\"github.com/martinlindhe/formats/parse\"\n)\n\n\nfunc CodeDirectory(c *parse.Checker) (*parse.ParsedLayout, error) {\n\n\tif !isCodeDirectory(c.Header) {\n\t\treturn nil, nil\n\t}\n\treturn parseCodeDirectory(c.File, c.ParsedLayout)\n}\n\n\n\nfunc parseCodeDirectory(file *os.File, pl parse.ParsedLayout) (*parse.ParsedLayout, error) {\n\n\n\tpos := int64(0)\n\tpl.FileKind = parse.MacOSResource\n\tpl.Layout = []parse.Layout{{\n\t\tOffset: pos,\n\t\tLength: 4, \n\t\tInfo: \"header\",\n\t\tType: parse.Group,\n\t\tChilds: []parse.Layout{\n\t\t\t{Offset: pos, Length: 4, Info: \"magic\", Type: parse.ASCII},\n\t\t}}}\n\n\treturn &pl, nil\n}\n\nfunc isCodeDirectory(b []byte) bool ", "output": "{\n\n\tif b[0] != 0xfa || b[1] != 0xde || b[2] != 0x0c || (b[3] != 0x01 && b[3] != 0x02) {\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package diskio\n\ntype diskInfoCache struct{}\n\n\n\nfunc (d *DiskIO) diskInfo(devName string) (map[string]string, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package vkutil\n\nimport (\n\t\"strconv\"\n\t\"time\"\n)\n\n\ntype EpochTime time.Time\n\n\nfunc (t EpochTime) MarshalJSON() ([]byte, error) {\n\treturn []byte(strconv.FormatInt(time.Time(t).Unix(), 10)), nil\n}\n\n\nfunc (t *EpochTime) UnmarshalJSON(s []byte) error {\n\tvar err error\n\tvar q int64\n\tif q, err = strconv.ParseInt(string(s), 10, 64); err != nil {\n\t\treturn err\n\t}\n\t*(*time.Time)(t) = time.Unix(q, 0)\n\treturn err\n}\n\n\n\nfunc (t EpochTime) ToTime() time.Time ", "output": "{\n\treturn time.Time(t)\n}"} {"input": "package revc\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc Test_dna(t *testing.T) ", "output": "{\n\tvar cases = []struct {\n\t\tfpath string\n\t\trevcS string\n\t}{\n\t\t{\n\t\t\t\"../input/revc/test_input_01.txt\",\n\t\t\t\"ACCGGGTTTT\",\n\t\t},\n\t}\n\tfor _, c := range cases {\n\t\trevcS, err := revc(c.fpath)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Error retriving counts: %v\", err)\n\t\t}\n\t\tif strings.ToUpper(revcS) != c.revcS {\n\t\t\tt.Errorf(\"revc sequence does not match:\\nwant:\\n%v\\n\\ngot:\\n%v\\n\\n\", c.revcS, strings.ToUpper(revcS))\n\t\t}\n\t}\n}"} {"input": "package swt\n\nimport \"github.com/timob/javabind\"\n\ntype EventsTraverseEventInterface interface {\n\tEventsKeyEventInterface\n}\n\ntype EventsTraverseEvent struct {\n\tEventsKeyEvent\n}\n\n\nfunc NewEventsTraverseEvent(a WidgetsEventInterface) (*EventsTraverseEvent) {\n\tconv_a := javabind.NewGoToJavaCallable()\n\tif err := conv_a.Convert(a); err != nil {\n\t\tpanic(err)\n\t}\n\n\tobj, err := javabind.GetEnv().NewObject(\"org/eclipse/swt/events/TraverseEvent\", conv_a.Value().Cast(\"org/eclipse/swt/widgets/Event\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tconv_a.CleanUp()\n\tx := &EventsTraverseEvent{}\n\tx.Callable = &javabind.Callable{obj}\n\treturn x\n}\n\n\nfunc (jbobject *EventsTraverseEvent) ToString() string {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"toString\", \"java/lang/String\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tretconv := javabind.NewJavaToGoString()\n\tdst := new(string)\n\tretconv.Dest(dst)\n\tif err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {\n\t\tpanic(err)\n\t}\n\tretconv.CleanUp()\n\treturn *dst\n}\n\n\n\nfunc (jbobject *EventsTraverseEvent) SetFieldDetail(val int) {\n\terr := jbobject.SetField(javabind.GetEnv(), \"detail\", val)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n}\n\nfunc (jbobject *EventsTraverseEvent) Detail() int ", "output": "{\n\tjret, err := jbobject.GetField(javabind.GetEnv(), \"detail\", javabind.Int)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn jret.(int)\n}"} {"input": "package elasticorm_test\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"testing\"\n)\n\nvar elasticSearchURL = determinElasticsearchURL()\n\n\n\n\nfunc assert(tb testing.TB, condition bool, msg string, v ...interface{}) {\n\tif !condition {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\033[31m%s:%d: \"+msg+\"\\033[39m\\n\\n\", append([]interface{}{filepath.Base(file), line}, v...)...)\n\t\ttb.FailNow()\n\t}\n}\n\n\nfunc ok(tb testing.TB, err error) {\n\tif err != nil {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\033[31m%s:%d: unexpected error: %s\\033[39m\\n\\n\", filepath.Base(file), line, err.Error())\n\t\ttb.FailNow()\n\t}\n}\n\n\nfunc equals(tb testing.TB, exp, act interface{}) {\n\tif !reflect.DeepEqual(exp, act) {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\033[31m%s:%d:\\n\\n\\texp: %#v\\n\\n\\tgot: %#v\\033[39m\\n\\n\", filepath.Base(file), line, exp, act)\n\t\ttb.FailNow()\n\t}\n}\n\nfunc determinElasticsearchURL() string ", "output": "{\n\tURL := os.Getenv(\"EDS_ES_URL\")\n\tif URL == `` {\n\t\tURL = `http://localhost:9200`\n\t}\n\treturn URL\n}"} {"input": "package ewma\n\nimport (\n\t\"time\"\n)\n\ntype EwmaRate struct {\n\tEwma\n}\n\n\nconst nanosec = float64(1000000000)\n\n\n\n\nfunc NewEwmaRate(halfLife time.Duration) *EwmaRate {\n\treturn (&EwmaRate{}).Init(halfLife)\n}\n\n\n\n\n\n\n\n\n\nfunc (r *EwmaRate) UpdateNow() float64 {\n\treturn r.Update(time.Now())\n}\n\n\n\n\nfunc (r *EwmaRate) Update(now time.Time) float64 {\n\ttimeDelta := now.Sub(r.lastTimestamp)\n\treturn r.Ewma.Update(nanosec/float64(timeDelta.Nanoseconds()), now)\n}\n\n\n\n\nfunc (r *EwmaRate) CurrentNow() float64 {\n\treturn r.Current(time.Now())\n}\n\n\nfunc (r *EwmaRate) Current(now time.Time) float64 {\n\tif r.lastTimestamp.IsZero() || r.lastTimestamp == now || now.Before(r.lastTimestamp) {\n\t\treturn r.Ewma.Current\n\t}\n\n\ttimeDelta := now.Sub(r.lastTimestamp)\n\n\treturn r.count(0, timeDelta)\n}\n\nfunc (r *EwmaRate) Init(halfLife time.Duration) *EwmaRate ", "output": "{\n\tr.Ewma.Init(halfLife)\n\treturn r\n}"} {"input": "package bitbucket\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/javiermanzano/goth\"\n)\n\n\ntype Session struct {\n\tAuthURL string\n\tAccessToken string\n\tRefreshToken string\n\tExpiresAt time.Time\n}\n\n\nfunc (s Session) GetAuthURL() (string, error) {\n\tif s.AuthURL == \"\" {\n\t\treturn \"\", errors.New(goth.NoAuthUrlErrorMessage)\n\t}\n\treturn s.AuthURL, nil\n}\n\n\nfunc (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {\n\tp := provider.(*Provider)\n\ttoken, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get(\"code\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !token.Valid() {\n\t\treturn \"\", errors.New(\"Invalid token received from provider\")\n\t}\n\n\ts.AccessToken = token.AccessToken\n\ts.RefreshToken = token.RefreshToken\n\ts.ExpiresAt = token.Expiry\n\treturn token.AccessToken, err\n}\n\n\n\n\n\nfunc (p *Provider) UnmarshalSession(data string) (goth.Session, error) {\n\tsess := &Session{}\n\terr := json.NewDecoder(strings.NewReader(data)).Decode(sess)\n\treturn sess, err\n}\n\nfunc (s Session) String() string {\n\treturn s.Marshal()\n}\n\nfunc (s Session) Marshal() string ", "output": "{\n\tb, _ := json.Marshal(s)\n\treturn string(b)\n}"} {"input": "package goutils\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strings\"\n)\n\nvar letters = []rune(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\")\n\n\n\nfunc StrFormat(format string, kv map[string]interface{}) string {\n\tfor key, val := range kv {\n\t\tkey = \"{\" + key + \"}\"\n\t\tformat = strings.Replace(format, key, fmt.Sprintf(\"%v\", val), -1)\n\t}\n\treturn format\n}\n\nfunc RandNString(n int) string ", "output": "{\n\tb := make([]rune, n)\n\tfor i := range b {\n\t\tb[i] = letters[rand.Intn(len(letters))]\n\t}\n\treturn string(b)\n}"} {"input": "package extends\n\ntype CEO interface {\n\tManager\n\tdeleteManager()\n\tIsCEO()\n}\n\ntype ceo struct {\n\tManager\n}\n\nfunc (p *ceo) deleteManager() {\n\tDeleteDirectorManager(p.Manager)\n}\n\nfunc (p *ceo) IsCEO() {}\n\ntype overwrittenMethodsOnManager struct {\n\tp Manager\n}\n\nfunc NewCEO(name string) CEO {\n\tom := &overwrittenMethodsOnManager{}\n\tp := NewDirectorManager(om, name)\n\tom.p = p\n\n\treturn &ceo{Manager: p}\n}\n\n\n\nfunc (p *ceo) GetPosition() string {\n\treturn \"CEO\"\n}\n\nfunc DeleteCEO(p CEO) ", "output": "{\n\tp.deleteManager()\n}"} {"input": "package yaml\n\nimport (\n\t\"github.com/pinpt/dialect/pkg\"\n\t\"github.com/pinpt/dialect/pkg/types\"\n)\n\ntype YAMLExaminer struct {\n}\n\nfunc (e *YAMLExaminer) Examine(language string, filename string, line *types.DialectLine) error {\n\tpkg.SingleSymbolProcessor(\"#\", line)\n\treturn nil\n}\n\nfunc (e *YAMLExaminer) NewExaminer() types.DialectExaminer {\n\tex := new(YAMLExaminer)\n\treturn ex\n}\n\n\n\nfunc init() ", "output": "{\n\ttypes.RegisterExaminer(\"YAML\", &YAMLExaminer{})\n}"} {"input": "package storage\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n)\n\n\n\nfunc TestSetBinlogPosition(t *testing.T) ", "output": "{\n\tdir, err := ioutil.TempDir(\"\", \"example\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tfile := filepath.Join(dir, \"temp.db\")\n\n\tstore := &BoltDBStore{}\n\tstore.Open(file)\n\n\tstore.SetBinlogPosition(&BinlogInformation{File: \"binlog001.log\", Position: 1234567890})\n\tbinlogInfo, err := store.GetBinlogPosition()\n\tif err != nil || binlogInfo.File != \"binlog001.log\" || binlogInfo.Position != 1234567890 {\n\t\tt.Error(\"failed\")\n\t}\n}"} {"input": "package vpki\n\nimport (\n\t\"crypto/tls\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype certCache struct {\n\tm map[string]*tls.Certificate\n\tmut *sync.RWMutex\n\tcrt Certifier\n\tttl time.Duration\n}\n\n\n\nfunc (cc *certCache) add(name string) (*tls.Certificate, error) {\n\tcrt, err := cc.crt.Cert(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcc.mut.Lock()\n\tcc.m[name] = crt\n\tcc.mut.Unlock()\n\treturn crt, nil\n}\n\nfunc (cc *certCache) get(name string) (*tls.Certificate, error) {\n\tlkr := cc.mut.RLocker()\n\tlkr.Lock()\n\n\tif c, ok := cc.m[name]; ok {\n\t\tn := time.Now()\n\t\tif n.After(c.Leaf.NotBefore) && n.Before(c.Leaf.NotAfter) {\n\t\t\tlkr.Unlock()\n\t\t\treturn c, nil\n\t\t}\n\t}\n\tlkr.Unlock()\n\n\treturn cc.add(name)\n}\n\nfunc newCertCache(crt Certifier) *certCache ", "output": "{\n\treturn &certCache{\n\t\tm: map[string]*tls.Certificate{},\n\t\tmut: &sync.RWMutex{},\n\t\tcrt: crt,\n\t\tttl: DefaultTTL,\n\t}\n}"} {"input": "package cmd\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/ghodss/yaml\"\n\t\"github.com/spf13/cobra\"\n)\n\n\nfunc NameFromCommandArgs(cmd *cobra.Command, args []string, noNameRequired bool) (string, error) {\n\tif len(args) == 0 {\n\n\t\treturn \"\", getErrorForNoName(noNameRequired)\n\t}\n\treturn args[0], nil\n}\n\nfunc getErrorForNoName(noNameRequired bool) error {\n\tif noNameRequired {\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"NAME is required\")\n}\n\n\n\nfunc PrintOutput(format string, object interface{}) error {\n\tvar msg string\n\ttmpCluster := object\n\tif format == \"yaml\" {\n\t\ty, err := yaml.Marshal(tmpCluster)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmsg += string(y)\n\t\tfmt.Printf(msg)\n\t} else if format == \"json\" {\n\t\ty, err := json.Marshal(tmpCluster)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpmsg, err := prettyprint(y)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmsg += string(pmsg)\n\t\tfmt.Printf(msg)\n\t}\n\treturn nil\n}\n\nfunc prettyprint(b []byte) ([]byte, error) ", "output": "{\n\tvar out bytes.Buffer\n\terr := json.Indent(&out, b, \"\", \" \")\n\treturn out.Bytes(), err\n}"} {"input": "package cache\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"time\"\n)\n\ntype Cache struct {\n\tmemoryCache map[string][]byte\n\trefreshTime int\n}\n\nfunc NewCache(t int) *Cache {\n\treturn &Cache{\n\t\tmemoryCache: make(map[string][]byte),\n\t\trefreshTime: t,\n\t}\n}\n\n\n\nfunc (c *Cache) GetCache(name string) ([]byte, error) {\n\tif dat, ok := c.memoryCache[name]; ok {\n\t\treturn dat, nil\n\t}\n\n\tf, err := os.Stat(\"/tmp/\" + name)\n\tif os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\n\tif time.Since(f.ModTime()).Minutes() > float64(c.refreshTime) {\n\t\treturn nil, fmt.Errorf(\"[GetCache] %s\", \"cache invalidate\")\n\t}\n\n\tdat, err := ioutil.ReadFile(\"/tmp/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dat, nil\n}\n\nfunc (c *Cache) SetCache(name string, data []byte) error ", "output": "{\n\terr := ioutil.WriteFile(\"/tmp/\"+name, data, 0644)\n\tif err == nil {\n\t\tc.memoryCache[name] = data\n\t}\n\treturn err\n}"} {"input": "package config\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/dnephin/configtf\"\n\tpth \"github.com/dnephin/configtf/path\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype ComposeConfig struct {\n\tFiles []string\n\tProject string `config:\"required\"`\n\tStopGrace int\n\tDependent\n\tAnnotations\n}\n\n\nfunc (c *ComposeConfig) StopGraceString() string {\n\treturn strconv.Itoa(c.StopGrace)\n}\n\n\nfunc (c *ComposeConfig) Validate(path pth.Path, config *Config) *pth.Error {\n\treturn nil\n}\n\nfunc (c *ComposeConfig) String() string {\n\treturn fmt.Sprintf(\"Run Compose project %q from: %v\",\n\t\tc.Project, strings.Join(c.Files, \", \"))\n}\n\n\n\n\nfunc composeFromConfig(name string, values map[string]interface{}) (Resource, error) {\n\tcompose := &ComposeConfig{Project: \"{unique}\", StopGrace: 5}\n\treturn compose, configtf.Transform(name, values, compose)\n}\n\nfunc init() {\n\tRegisterResource(\"compose\", composeFromConfig)\n}\n\nfunc (c *ComposeConfig) Resolve(resolver Resolver) (Resource, error) ", "output": "{\n\tconf := *c\n\tvar err error\n\tconf.Files, err = resolver.ResolveSlice(c.Files)\n\tif err != nil {\n\t\treturn &conf, err\n\t}\n\tconf.Project, err = resolver.Resolve(c.Project)\n\treturn &conf, err\n}"} {"input": "package throttled\n\n\ntype WaitGroup struct {\n\tthrottle int\n\tcompleted chan bool\n\toutstanding int\n}\n\n\n\n\n\nfunc (w *WaitGroup) PeekThrottled() bool {\n\treturn w.outstanding+1 > w.throttle\n}\n\n\n\nfunc (w *WaitGroup) Add() {\n\tw.outstanding++\n\tif w.outstanding > w.throttle {\n\t\tselect {\n\t\tcase <-w.completed:\n\t\t\tw.outstanding--\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\nfunc (w *WaitGroup) Done() {\n\tw.completed <- true\n}\n\n\nfunc (w *WaitGroup) Wait() {\n\tif w.outstanding == 0 {\n\t\treturn\n\t}\n\tfor w.outstanding > 0 {\n\t\tselect {\n\t\tcase <-w.completed:\n\t\t\tw.outstanding--\n\t\t}\n\t}\n}\n\nfunc NewWaitGroup(throttle int) *WaitGroup ", "output": "{\n\treturn &WaitGroup{\n\t\toutstanding: 0,\n\t\tthrottle: throttle,\n\t\tcompleted: make(chan bool, throttle),\n\t}\n}"} {"input": "package linux\n\nimport (\n\t\"testing\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestGetAdapters(t *testing.T) {\n\n\tlog.SetLevel(log.DebugLevel)\n\n\tlist, err := GetAdapters()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassert.NotEmpty(t, list)\n}\n\nfunc TestGetAdapter(t *testing.T) {\n\tlog.SetLevel(log.DebugLevel)\n\t_, err := GetAdapter(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestGetAdapterNotFound(t *testing.T) {\n\t_, err := GetAdapter(\"hci999\")\n\tif err == nil {\n\t\tt.Fatal(\"adapter should not exists\")\n\t}\n}\n\n\n\nfunc TestDown(t *testing.T) {\n\terr := Down(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestReset(t *testing.T) {\n\terr := Reset(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestUp(t *testing.T) ", "output": "{\n\terr := Up(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package html_test\n\nimport (\n\t\"fmt\"\n\t\"html\"\n)\n\nfunc ExampleEscapeString() {\n\tconst s = `\"Fran & Freddie's Diner\" `\n\tfmt.Println(html.EscapeString(s))\n}\n\n\n\nfunc ExampleUnescapeString() ", "output": "{\n\tconst s = `"Fran & Freddie's Diner" <tasty@example.com>`\n\tfmt.Println(html.UnescapeString(s))\n}"} {"input": "package internalversion\n\nimport (\n\tapi \"k8s.io/kubernetes/pkg/api\"\n\tregistered \"k8s.io/kubernetes/pkg/apimachinery/registered\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n)\n\ntype QuotaInterface interface {\n\tRESTClient() restclient.Interface\n\tClusterResourceQuotasGetter\n}\n\n\ntype QuotaClient struct {\n\trestClient restclient.Interface\n}\n\nfunc (c *QuotaClient) ClusterResourceQuotas() ClusterResourceQuotaInterface {\n\treturn newClusterResourceQuotas(c)\n}\n\n\nfunc NewForConfig(c *restclient.Config) (*QuotaClient, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := restclient.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &QuotaClient{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *restclient.Config) *QuotaClient {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c restclient.Interface) *QuotaClient {\n\treturn &QuotaClient{c}\n}\n\n\n\n\n\nfunc (c *QuotaClient) RESTClient() restclient.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc setConfigDefaults(config *restclient.Config) error ", "output": "{\n\tg, err := registered.Group(\"quota.openshift.io\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.APIPath = \"/apis\"\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = restclient.DefaultKubernetesUserAgent()\n\t}\n\tif config.GroupVersion == nil || config.GroupVersion.Group != g.GroupVersion.Group {\n\t\tcopyGroupVersion := g.GroupVersion\n\t\tconfig.GroupVersion = ©GroupVersion\n\t}\n\tconfig.NegotiatedSerializer = api.Codecs\n\n\tif config.QPS == 0 {\n\t\tconfig.QPS = 5\n\t}\n\tif config.Burst == 0 {\n\t\tconfig.Burst = 10\n\t}\n\treturn nil\n}"} {"input": "package widgets\n\nimport (\n)\n\ntype WidgetCore struct {\n x, y float32\n width, height float32\n}\n\n\n\nfunc (wc *WidgetCore) SetPosition(x, y float32) {\n wc.x = x\n wc.y = y\n}\n\nfunc (wc *WidgetCore) Size()(width, height float32) {\n return wc.width, wc.height\n}\n\ntype Widget interface {\n Position()(x, y float32)\n SetPosition(x, y float32)\n Size()(width, height float32)\n\n Dispose()\n Render()\n OnKey(modifier, key int) bool\n OnMouseClickDown() bool\n OnMouseClickUp() bool\n}\n\nfunc (wc *WidgetCore) Position()(x, y float32) ", "output": "{\n return wc.x, wc.y\n}"} {"input": "package master\n\nimport ()\n\n\n\ntype frame struct {\n\tjob *job\n\tslaveName string\n\tframe int\n\tdata []byte\n\tprogress byte\n\tcompleted bool\n}\n\n\n\nfunc NewFrame(job *job, fr int) *frame {\n\treturn &frame{\n\t\tjob: job,\n\t\tslaveName: \"\",\n\t\tframe: fr,\n\t\tdata: nil,\n\t\tprogress: 0,\n\t\tcompleted: false,\n\t}\n}\n\n\n\nfunc (f *frame) Job() *job {\n\treturn f.job\n}\n\nfunc (f *frame) SlaveName() string {\n\treturn f.slaveName\n}\n\nfunc (f *frame) Frame() int {\n\treturn f.frame\n}\n\n\n\nfunc (f *frame) Data() []byte {\n\treturn f.data\n}\n\nfunc (f *frame) Progress() byte {\n\treturn f.progress\n}\n\nfunc (f *frame) Completed() bool {\n\treturn f.completed\n}\n\nfunc (f *frame) File() []byte {\n\treturn f.Job().File()\n}\n\n\n\nfunc (f *frame) SetSlaveName(slaveName string) {\n\tf.slaveName = slaveName\n}\n\nfunc (f *frame) SetData(data []byte) {\n\tf.data = data\n}\n\nfunc (f *frame) SetProgress(progress byte) {\n\tf.progress = progress\n}\n\nfunc (f *frame) SetCompleted(completed bool) {\n\tf.completed = completed\n\tif completed {\n\t\tf.SetProgress(100)\n\t}\n}\n\n\n\nfunc (f *frame) Reset() {\n\tf.SetSlaveName(\"\")\n\tf.SetData(nil)\n\tf.SetProgress(0)\n\tf.SetCompleted(false)\n}\n\nfunc (f *frame) AlignedFrame() int ", "output": "{\n\treturn f.frame + f.Job().Start()\n}"} {"input": "package gtka\n\nimport (\n\t\"github.com/gotk3/gotk3/gtk\"\n\t\"github.com/coyim/gotk3adapter/gliba\"\n\t\"github.com/coyim/gotk3adapter/gtki\"\n)\n\ntype application struct {\n\t*gliba.Application\n\tinternal *gtk.Application\n}\n\nfunc wrapApplicationSimple(v *gtk.Application) *application {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn &application{gliba.WrapApplicationSimple(&v.Application), v}\n}\n\n\n\nfunc unwrapApplication(v gtki.Application) *gtk.Application {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*application).internal\n}\n\nfunc (v *application) GetActiveWindow() gtki.Window {\n\tret := wrapWindowSimple(v.internal.GetActiveWindow())\n\tif ret == nil {\n\t\treturn nil\n\t}\n\treturn ret\n}\n\nfunc wrapApplication(v *gtk.Application, e error) (*application, error) ", "output": "{\n\treturn wrapApplicationSimple(v), e\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t_ \"net/http/pprof\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n)\n\n\n\nfunc main() {\n\tvar err error\n\tif err = InitGlobalConfig(); err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tif err = InitLog(); err != nil {\n\t\tfmt.Println(\"InitLog \", err)\n\t\treturn\n\t}\n\tgo func() {\n\t\tfmt.Printf(\"start metric interface %s\\n\", GlobalConfig.MetricBind)\n\t\tfmt.Printf(\"%s\\n\", http.ListenAndServe(GlobalConfig.MetricBind, nil))\n\t}()\n\tif err = InitMysqlConnPool(); err != nil {\n\t\tfmt.Println(\"init mysql error: \", err.Error())\n\t\treturn\n\t}\n\tif err = InitCFC(); err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tlg.Info(\"start cfc on %s \", GlobalConfig.TCPBind)\n\tgo updatHostStatus()\n\tif GlobalConfig.EnableCleanupExpiredMetric {\n\t\tgo cleanupExpiredMetrics()\n\t}\n\tselect {}\n}\n\nfunc init() ", "output": "{\n\tos.Chdir(filepath.Dir(os.Args[0]))\n\tos.Mkdir(\"logs\", 0755)\n\truntime.GOMAXPROCS(runtime.NumCPU())\n}"} {"input": "package types\n\nimport \"fmt\"\n\ntype IntegerValue struct {\n\tValue int64\n}\n\nfunc (v *IntegerValue) ToString() string {\n\treturn fmt.Sprint(v.Value)\n}\n\nfunc (v *IntegerValue) GetType() string {\n\treturn \"integer\"\n}\n\nfunc (v *IntegerValue) IsValue() bool {\n\treturn true\n}\n\nfunc (v *IntegerValue) ConvertTo(t string) (ValueType, error) {\n\treturn nil, fmt.Errorf(\"cannot convert integer to %s: does not implement yet\", t)\n}\n\nfunc (v *IntegerValue) EqualTo(t ValueType) bool {\n\tif v2, ok := t.(*IntegerValue); ok {\n\t\tif v2.Value == v.Value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc NewIntegerValue(v int64) *IntegerValue ", "output": "{\n\treturn &IntegerValue{Value: v}\n}"} {"input": "package monator\n\nimport (\n \"time\"\n \"bytes\"\n \"encoding/json\"\n)\n\ntype CheckDuration time.Duration\n\nfunc (d CheckDuration) Hours() float64 {\n return time.Duration(d).Hours()\n}\n\nfunc (d CheckDuration) Minutes() float64 {\n return time.Duration(d).Minutes()\n}\n\n\n\nfunc (d CheckDuration) Seconds() float64 {\n return time.Duration(d).Seconds()\n}\n\nfunc (d CheckDuration) Milliseconds() int64 {\n return time.Duration(d).Nanoseconds() / int64(time.Millisecond)\n}\n\nfunc (d CheckDuration) String() string {\n \n rounded := ((time.Duration(d)).Nanoseconds() / int64(time.Millisecond)) * int64(time.Millisecond)\n return time.Duration(rounded).String()\n}\n\n\nfunc (d *CheckDuration) UnmarshalJSON(data []byte) error {\n b := bytes.NewBuffer(data)\n dec := json.NewDecoder(b)\n\n var s string\n\n if err := dec.Decode(&s); err != nil {\n return err\n }\n if duration, err := time.ParseDuration(s); err != nil {\n return err\n } else {\n *d = CheckDuration(duration)\n }\n\n return nil\n}\n\nfunc (d CheckDuration) Nanoseconds() int64 ", "output": "{\n return time.Duration(d).Nanoseconds()\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/appleboy/gin-jwt\"\n\t\"github.com/gin-gonic/gin\"\n)\n\n\n\nfunc main() {\n\tport := os.Getenv(\"PORT\")\n\tr := gin.New()\n\tr.Use(gin.Logger())\n\tr.Use(gin.Recovery())\n\n\tif port == \"\" {\n\t\tport = \"8000\"\n\t}\n\n\tauthMiddleware := &jwt.GinJWTMiddleware{\n\t\tRealm: \"test zone\",\n\t\tKey: []byte(\"secret key\"),\n\t\tTimeout: time.Hour,\n\t\tMaxRefresh: time.Hour,\n\t\tAuthenticator: func(userId string, password string, c *gin.Context) (string, bool) {\n\t\t\tif (userId == \"admin\" && password == \"admin\") || (userId == \"test\" && password == \"test\") {\n\t\t\t\treturn userId, true\n\t\t\t}\n\n\t\t\treturn userId, false\n\t\t},\n\t\tAuthorizator: func(userId string, c *gin.Context) bool {\n\t\t\tif userId == \"admin\" {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\treturn false\n\t\t},\n\t\tUnauthorized: func(c *gin.Context, code int, message string) {\n\t\t\tc.JSON(code, gin.H{\n\t\t\t\t\"code\": code,\n\t\t\t\t\"message\": message,\n\t\t\t})\n\t\t},\n\t\tTokenLookup: \"header:Authorization\",\n\n\t\tTokenHeadName: \"Bearer\",\n\n\t\tTimeFunc: time.Now,\n\t}\n\n\tr.POST(\"/login\", authMiddleware.LoginHandler)\n\n\tauth := r.Group(\"/auth\")\n\tauth.Use(authMiddleware.MiddlewareFunc())\n\t{\n\t\tauth.GET(\"/hello\", helloHandler)\n\t\tauth.GET(\"/refresh_token\", authMiddleware.RefreshHandler)\n\t}\n\n\thttp.ListenAndServe(\":\"+port, r)\n}\n\nfunc helloHandler(c *gin.Context) ", "output": "{\n\tc.JSON(200, gin.H{\n\t\t\"text\": \"Hello World.\",\n\t})\n}"} {"input": "package fake_cmdpreparer\n\nimport (\n\t\"os/exec\"\n\t\"sync\"\n\n\t\"code.cloudfoundry.org/garden\"\n\t\"code.cloudfoundry.org/garden-linux/container_daemon\"\n)\n\ntype FakeCmdPreparer struct {\n\tPrepareCmdStub func(garden.ProcessSpec) (*exec.Cmd, error)\n\tprepareCmdMutex sync.RWMutex\n\tprepareCmdArgsForCall []struct {\n\t\targ1 garden.ProcessSpec\n\t}\n\tprepareCmdReturns struct {\n\t\tresult1 *exec.Cmd\n\t\tresult2 error\n\t}\n}\n\n\n\nfunc (fake *FakeCmdPreparer) PrepareCmdCallCount() int {\n\tfake.prepareCmdMutex.RLock()\n\tdefer fake.prepareCmdMutex.RUnlock()\n\treturn len(fake.prepareCmdArgsForCall)\n}\n\nfunc (fake *FakeCmdPreparer) PrepareCmdArgsForCall(i int) garden.ProcessSpec {\n\tfake.prepareCmdMutex.RLock()\n\tdefer fake.prepareCmdMutex.RUnlock()\n\treturn fake.prepareCmdArgsForCall[i].arg1\n}\n\nfunc (fake *FakeCmdPreparer) PrepareCmdReturns(result1 *exec.Cmd, result2 error) {\n\tfake.PrepareCmdStub = nil\n\tfake.prepareCmdReturns = struct {\n\t\tresult1 *exec.Cmd\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nvar _ container_daemon.CmdPreparer = new(FakeCmdPreparer)\n\nfunc (fake *FakeCmdPreparer) PrepareCmd(arg1 garden.ProcessSpec) (*exec.Cmd, error) ", "output": "{\n\tfake.prepareCmdMutex.Lock()\n\tfake.prepareCmdArgsForCall = append(fake.prepareCmdArgsForCall, struct {\n\t\targ1 garden.ProcessSpec\n\t}{arg1})\n\tfake.prepareCmdMutex.Unlock()\n\tif fake.PrepareCmdStub != nil {\n\t\treturn fake.PrepareCmdStub(arg1)\n\t} else {\n\t\treturn fake.prepareCmdReturns.result1, fake.prepareCmdReturns.result2\n\t}\n}"} {"input": "package action\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n)\n\ntype aclInfo struct {\n\t*config\n}\n\nfunc AclInfoAction() Action {\n\treturn &aclInfo{\n\t\tconfig: &gConfig,\n\t}\n}\n\n\n\nfunc (a aclInfo) Run(args []string) error {\n\tif len(args) != 1 {\n\t\treturn fmt.Errorf(\"An ACL id must be specified\")\n\t}\n\tid := args[0]\n\n\tclient, err := a.newACL()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tqueryOpts := a.queryOptions()\n\tacl, _, err := client.Info(id, queryOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn a.Output(acl)\n}\n\nfunc (a *aclInfo) CommandFlags() *flag.FlagSet ", "output": "{\n\treturn a.newFlagSet(FLAG_OUTPUT, FLAG_CONSISTENCY, FLAG_BLOCKING)\n}"} {"input": "package host\n\nimport (\n\t\"unsafe\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\nfunc fstatat(fd int, name string, flags int) (unix.Stat_t, error) ", "output": "{\n\tvar stat unix.Stat_t\n\tnamePtr, err := unix.BytePtrFromString(name)\n\tif err != nil {\n\t\treturn stat, err\n\t}\n\t_, _, errno := unix.Syscall6(\n\t\tunix.SYS_NEWFSTATAT,\n\t\tuintptr(fd),\n\t\tuintptr(unsafe.Pointer(namePtr)),\n\t\tuintptr(unsafe.Pointer(&stat)),\n\t\tuintptr(flags),\n\t\t0, 0)\n\tif errno != 0 {\n\t\treturn stat, errno\n\t}\n\treturn stat, nil\n}"} {"input": "package common\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"io\"\n\t\"math/rand\"\n\t\"os\"\n)\n\nfunc GetFileInfo(path string) (*LocalFileInfo, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer file.Close()\n\n\ts, err := file.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf := &LocalFileInfo{}\n\tf.Size = s.Size()\n\tf.Name = s.Name()\n\tf.Path = path\n\n\th := md5.New()\n\t_, err = io.Copy(h, file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf.Md5 = fmt.Sprintf(\"%X\", h.Sum(nil))\n\n\treturn f, nil\n}\n\n\n\nfunc RandString(n int) string ", "output": "{\n\tvar letters = []byte(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n\tb := make([]byte, n)\n\tfor i := range b {\n\t\tb[i] = letters[rand.Intn(len(letters))]\n\t}\n\treturn string(b)\n}"} {"input": "package core\n\nimport (\n\tabci \"github.com/tendermint/abci/types\"\n\tdata \"github.com/tendermint/go-wire/data\"\n\tctypes \"github.com/tendermint/tendermint/rpc/core/types\"\n)\n\n\n\nfunc ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuery, error) {\n\tresQuery, err := proxyAppQuery.QuerySync(abci.RequestQuery{\n\t\tPath: path,\n\t\tData: data,\n\t\tProve: prove,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogger.Info(\"ABCIQuery\", \"path\", path, \"data\", data, \"result\", resQuery)\n\treturn &ctypes.ResultABCIQuery{\n\t\tresQuery.Result(),\n\t}, nil\n}\n\n\n\nfunc ABCIInfo() (*ctypes.ResultABCIInfo, error) ", "output": "{\n\tresInfo, err := proxyAppQuery.InfoSync()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ctypes.ResultABCIInfo{resInfo}, nil\n}"} {"input": "package parsex\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype ParsexError struct {\n\tPos int\n\tMessage string\n}\n\n\n\ntype ParsexState interface {\n\tNext(pred func(int, interface{}) (interface{}, error)) (x interface{}, err error)\n\tPos() int\n\tSeekTo(int)\n\tTrap(message string, args ...interface{}) error\n}\n\ntype StateInMemory struct {\n\tbuffer []interface{}\n\tpos int\n}\n\nfunc NewStateInMemory(buffer []interface{}) *StateInMemory {\n\treturn &StateInMemory{buffer, 0}\n}\n\nfunc (this *StateInMemory) Next(pred func(int, interface{}) (interface{}, error)) (x interface{}, err error) {\n\tbuffer := (*this).buffer\n\tif (*this).pos < len(buffer) {\n\t\tx := buffer[(*this).pos]\n\t\toutput, err := pred((*this).pos, x)\n\t\tif err == nil {\n\t\t\t(*this).pos++\n\t\t\treturn output, nil\n\t\t} else {\n\t\t\treturn x, err\n\t\t}\n\t} else {\n\t\treturn nil, io.EOF\n\t}\n}\n\nfunc (this *StateInMemory) Pos() int {\n\treturn (*this).pos\n}\n\nfunc (this *StateInMemory) SeekTo(pos int) {\n\tend := len((*this).buffer)\n\tif pos < 0 || pos > end {\n\t\tmessage := fmt.Sprintf(\"%d out range [0, %d]\", pos, end)\n\t\tpanic(errors.New(message))\n\t}\n\t(*this).pos = pos\n}\n\nfunc (this *StateInMemory) Trap(message string, args ...interface{}) error {\n\treturn ParsexError{(*this).pos,\n\t\tfmt.Sprintf(message, args...)}\n}\n\nfunc (err ParsexError) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"pos %d :\\n%s\",\n\t\terr.Pos, err.Message)\n}"} {"input": "package thrift\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\n\t\"github.com/uber/tchannel/golang/typed\"\n)\n\n\n\n\n\nfunc readHeaders(r io.Reader) (map[string]string, error) {\n\tbs, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuffer := typed.NewReadBuffer(bs)\n\tnumHeaders := buffer.ReadUint16()\n\tif numHeaders == 0 {\n\t\treturn nil, buffer.Err()\n\t}\n\n\theaders := make(map[string]string)\n\tfor i := 0; i < int(numHeaders) && buffer.Err() == nil; i++ {\n\t\tk := buffer.ReadLen16String()\n\t\tv := buffer.ReadLen16String()\n\t\theaders[k] = v\n\t}\n\treturn headers, buffer.Err()\n}\n\nfunc writeHeaders(w io.Writer, headers map[string]string) error ", "output": "{\n\tsize := 2\n\tfor k, v := range headers {\n\t\tsize += 4 \n\t\tsize += len(k) + len(v)\n\t}\n\n\tbuf := make([]byte, size)\n\twriteBuffer := typed.NewWriteBuffer(buf)\n\twriteBuffer.WriteUint16(uint16(len(headers)))\n\tfor k, v := range headers {\n\t\twriteBuffer.WriteLen16String(k)\n\t\twriteBuffer.WriteLen16String(v)\n\t}\n\n\tif err := writeBuffer.Err(); err != nil {\n\t\treturn err\n\t}\n\n\tif writeBuffer.BytesWritten() != size {\n\t\treturn fmt.Errorf(\"writeHeaders size calculation wrong, expected to write %v bytes, only wrote %v bytes\",\n\t\t\tsize, writeBuffer.BytesWritten())\n\t}\n\n\t_, err := writeBuffer.FlushTo(w)\n\treturn err\n}"} {"input": "package ec2query\n\n\n\nimport (\n\t\"net/url\"\n\n\trequest \"github.com/aws/aws-sdk-go-v2/aws\"\n\t\"github.com/aws/aws-sdk-go-v2/aws/awserr\"\n\t\"github.com/aws/aws-sdk-go-v2/private/protocol/query/queryutil\"\n)\n\n\nvar BuildHandler = request.NamedHandler{Name: \"awssdk.ec2query.Build\", Fn: Build}\n\n\n\n\nfunc Build(r *request.Request) ", "output": "{\n\tbody := url.Values{\n\t\t\"Action\": {r.Operation.Name},\n\t\t\"Version\": {r.Metadata.APIVersion},\n\t}\n\tif err := queryutil.Parse(body, r.Params, true); err != nil {\n\t\tr.Error = awserr.New(\"SerializationError\", \"failed encoding EC2 Query request\", err)\n\t}\n\n\tif r.ExpireTime == 0 {\n\t\tr.HTTPRequest.Method = \"POST\"\n\t\tr.HTTPRequest.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded; charset=utf-8\")\n\t\tr.SetBufferBody([]byte(body.Encode()))\n\t} else { \n\t\tr.HTTPRequest.Method = \"GET\"\n\t\tr.HTTPRequest.URL.RawQuery = body.Encode()\n\t}\n}"} {"input": "package middleware\n\nimport \"github.com/gin-gonic/gin\"\nimport \"github.com/helderfarias/ges/api/util\"\n\n\n\nfunc CertifiedConfig(certs *util.Certified) gin.HandlerFunc ", "output": "{\n\treturn func(c *gin.Context) {\n\t\tc.Set(\"certs\", certs)\n\t\tc.Next()\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"os/signal\"\n\n\t\"k8s.io/klog/v2\"\n)\n\nvar onlyOneSignalHandler = make(chan struct{})\nvar shutdownHandler chan os.Signal\n\n\n\n\n\n\nfunc SetupSignalHandler(exitOnSecondSignal bool) <-chan struct{} {\n\treturn SetupSignalContext(exitOnSecondSignal).Done()\n}\n\n\n\n\nfunc SetupSignalContext(exitOnSecondSignal bool) context.Context {\n\tclose(onlyOneSignalHandler) \n\n\tshutdownHandler = make(chan os.Signal, 2)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tsignal.Notify(shutdownHandler, shutdownSignals...)\n\tgo func() {\n\t\t<-shutdownHandler\n\t\tcancel()\n\t\tif exitOnSecondSignal {\n\t\t\t<-shutdownHandler\n\t\t\tos.Exit(1)\n\t\t} else {\n\t\t\tfor {\n\t\t\t\t<-shutdownHandler\n\t\t\t\tklog.Infof(\"Termination signal has been received already. Ignoring signal.\")\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn ctx\n}\n\n\n\n\n\nfunc RequestShutdown() bool ", "output": "{\n\tif shutdownHandler != nil {\n\t\tselect {\n\t\tcase shutdownHandler <- shutdownSignals[0]:\n\t\t\treturn true\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSDynamoDBTable_TimeToLiveSpecification struct {\n\n\tAttributeName string `json:\"AttributeName,omitempty\"`\n\n\tEnabled bool `json:\"Enabled\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) AWSCloudFormationType() string {\n\treturn \"AWS::DynamoDB::Table.TimeToLiveSpecification\"\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\n\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetDependsOn(dependencies []string) ", "output": "{\n\tr._dependsOn = dependencies\n}"} {"input": "package v1\n\nimport (\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\trest \"k8s.io/client-go/rest\"\n\tv1 \"k8s.io/code-generator/_examples/crd/apis/example/v1\"\n\t\"k8s.io/code-generator/_examples/crd/clientset/versioned/scheme\"\n)\n\ntype ExampleV1Interface interface {\n\tRESTClient() rest.Interface\n\tTestTypesGetter\n}\n\n\ntype ExampleV1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *ExampleV1Client) TestTypes(namespace string) TestTypeInterface {\n\treturn newTestTypes(c, namespace)\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *ExampleV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *ExampleV1Client {\n\treturn &ExampleV1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *ExampleV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfig(c *rest.Config) (*ExampleV1Client, error) ", "output": "{\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ExampleV1Client{client}, nil\n}"} {"input": "package state\n\nimport (\n\t\"strconv\"\n\t. \"bugnuts/maps\"\n\t. \"bugnuts/torus\"\n\t. \"bugnuts/util\"\n)\n\nfunc (s *State) FoodLocations() (l []Location) {\n\tfor loc := range s.Food {\n\t\tl = append(l, Location(loc))\n\t}\n\n\treturn l\n}\n\n\n\nfunc (s *State) EnemyHillLocations(player int) (l []Location) {\n\tfor loc, hill := range s.Hills {\n\t\tif hill.Player != player && hill.Killed == 0 {\n\t\t\tl = append(l, Location(loc))\n\t\t}\n\t}\n\n\treturn l\n}\n\nfunc (s *State) ValidStep(loc Location) bool {\n\ti := s.Map.Grid[loc]\n\n\treturn i != WATER && i != BLOCK && i != OCCUPIED && i != FOOD && i != MY_ANT && i != MY_HILLANT\n}\n\nfunc (s *State) Stepable(loc Location) bool {\n\ti := s.Map.Grid[loc]\n\n\treturn i != WATER && i != BLOCK && i != FOOD\n}\n\nfunc (m *Metrics) DumpSeen() string {\n\tmax := Max(m.Seen)\n\tstr := \"\"\n\n\tfor r := 0; r < m.Rows; r++ {\n\t\tfor c := 0; c < m.Cols; c++ {\n\t\t\tstr += strconv.Itoa(m.Seen[r*m.Cols+c] * 10 / (max + 1))\n\t\t}\n\t\tstr += \"\\n\"\n\t}\n\n\treturn str\n}\n\nfunc (s *State) HillLocations(player int) (l []Location) ", "output": "{\n\tfor loc, hill := range s.Hills {\n\t\tif hill.Player == player && hill.Killed == 0 {\n\t\t\tl = append(l, Location(loc))\n\t\t}\n\t}\n\n\treturn l\n}"} {"input": "package v3\n\nimport (\n\tv3 \"github.com/projectcalico/api/pkg/apis/projectcalico/v3\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype BGPPeerLister interface {\n\tList(selector labels.Selector) (ret []*v3.BGPPeer, err error)\n\tGet(name string) (*v3.BGPPeer, error)\n\tBGPPeerListerExpansion\n}\n\n\ntype bGPPeerLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewBGPPeerLister(indexer cache.Indexer) BGPPeerLister {\n\treturn &bGPPeerLister{indexer: indexer}\n}\n\n\n\n\n\nfunc (s *bGPPeerLister) Get(name string) (*v3.BGPPeer, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v3.Resource(\"bgppeer\"), name)\n\t}\n\treturn obj.(*v3.BGPPeer), nil\n}\n\nfunc (s *bGPPeerLister) List(selector labels.Selector) (ret []*v3.BGPPeer, err error) ", "output": "{\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v3.BGPPeer))\n\t})\n\treturn ret, err\n}"} {"input": "package auth\n\nimport (\n\t\"errors\"\n\t\"sync\"\n)\n\ntype Users struct {\n\tsync.RWMutex\n\n\tList []*User\n\n\tlastID int64\n}\n\nfunc (u *Users) Get(id int64) (*User, error) {\n\tu.RLock()\n\tdefer u.RUnlock()\n\n\tfor _, user := range u.List {\n\t\tif user.ID == id {\n\t\t\treturn user, nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"User not found\")\n}\n\nfunc (u *Users) Create(user *User) {\n\tu.Lock()\n\tdefer u.Unlock()\n\n\tu.lastID++\n\tuser.ID = u.lastID\n\n\tu.List = append(u.List, user)\n}\n\nfunc (r *Users) Remove(id int64) {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\tfor key, item := range r.List {\n\t\tif item.ID == id {\n\n\t\t\tcopy(r.List[key:], r.List[key+1:])\n\t\t\tr.List[len(r.List)-1] = nil\n\t\t\tr.List = r.List[:len(r.List)-1]\n\n\t\t}\n\t}\n}\n\n\n\nfunc (r *Users) Flush() ", "output": "{\n\tr.Lock()\n\tdefer r.Unlock()\n\n\tr.List = []*User{}\n}"} {"input": "package uaa\n\nimport (\n\t\"sort\"\n\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n)\n\ntype Prompt struct {\n\tKey string \n\tType string \n\tLabel string \n}\n\ntype PromptAnswer struct {\n\tKey string \n\tValue string\n}\n\nfunc (p Prompt) IsPassword() bool { return p.Type == \"password\" }\n\ntype PromptsResp struct {\n\tPrompts map[string][]string \n}\n\nfunc (u UAAImpl) Prompts() ([]Prompt, error) {\n\tresp, err := u.client.Prompts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar prompts []Prompt\n\n\tfor key, pair := range resp.Prompts {\n\t\tprompts = append(prompts, Prompt{\n\t\t\tKey: key,\n\t\t\tType: pair[0],\n\t\t\tLabel: pair[1],\n\t\t})\n\t}\n\n\tsort.Sort(PromptSorting(prompts))\n\n\treturn prompts, nil\n}\n\nfunc (c Client) Prompts() (PromptsResp, error) {\n\tvar resp PromptsResp\n\n\terr := c.clientRequest.Get(\"/login\", &resp)\n\tif err != nil {\n\t\treturn resp, bosherr.WrapError(err, \"Requesting UAA prompts\")\n\t}\n\n\treturn resp, nil\n}\n\ntype PromptSorting []Prompt\n\n\nfunc (s PromptSorting) Less(i, j int) bool { return s[i].Type > s[j].Type }\nfunc (s PromptSorting) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s PromptSorting) Len() int ", "output": "{ return len(s) }"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/kataras/iris\"\n)\n\nfunc main() {\n\tapp := iris.New()\n\n\tapp.Get(\"/\", func(ctx iris.Context) {\n\t\tctx.HTML(\"

Hello, try to refresh the page after ~10 secs

\")\n\t})\n\n\tapp.Logger().Info(\"Wait 10 seconds and check your terminal again\")\n\tgo func() {\n\t\t<-time.After(10 * time.Second)\n\t\ttimeout := 5 * time.Second\n\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\tdefer cancel()\n\t\tapp.Shutdown(ctx)\n\t}()\n\n\n\tapp.Run(iris.Addr(\":8080\", configureHost), iris.WithoutServerError(iris.ErrServerClosed))\n\n}\n\n\n\nfunc configureHost(su *iris.Supervisor) ", "output": "{\n\tsu.RegisterOnShutdown(func() {\n\t\tprintln(\"server is closed\")\n\t})\n}"} {"input": "package rpc\n\nimport (\n\t\"github.com/mitchellh/packer/packer\"\n\t\"log\"\n\t\"net/rpc\"\n)\n\n\n\ntype hook struct {\n\tclient *rpc.Client\n\tmux *muxBroker\n}\n\n\n\ntype HookServer struct {\n\thook packer.Hook\n\tmux *muxBroker\n}\n\ntype HookRunArgs struct {\n\tName string\n\tData interface{}\n\tStreamId uint32\n}\n\nfunc (h *hook) Run(name string, ui packer.Ui, comm packer.Communicator, data interface{}) error {\n\tnextId := h.mux.NextId()\n\tserver := newServerWithMux(h.mux, nextId)\n\tserver.RegisterCommunicator(comm)\n\tserver.RegisterUi(ui)\n\tgo server.Serve()\n\n\targs := HookRunArgs{\n\t\tName: name,\n\t\tData: data,\n\t\tStreamId: nextId,\n\t}\n\n\treturn h.client.Call(\"Hook.Run\", &args, new(interface{}))\n}\n\nfunc (h *hook) Cancel() {\n\terr := h.client.Call(\"Hook.Cancel\", new(interface{}), new(interface{}))\n\tif err != nil {\n\t\tlog.Printf(\"Hook.Cancel error: %s\", err)\n\t}\n}\n\n\n\nfunc (h *HookServer) Cancel(args *interface{}, reply *interface{}) error {\n\th.hook.Cancel()\n\treturn nil\n}\n\nfunc (h *HookServer) Run(args *HookRunArgs, reply *interface{}) error ", "output": "{\n\tclient, err := newClientWithMux(h.mux, args.StreamId)\n\tif err != nil {\n\t\treturn NewBasicError(err)\n\t}\n\tdefer client.Close()\n\n\tif err := h.hook.Run(args.Name, client.Ui(), client.Communicator(), args.Data); err != nil {\n\t\treturn NewBasicError(err)\n\t}\n\n\t*reply = nil\n\treturn nil\n}"} {"input": "package minus\n\nimport (\n \"RETIA/unit\"\n \"RETIA/messages\"\n)\n\n\n\n\n\nfunc Eval(statement *unit.MinusStatement) *unit.Relation {\n if statement != nil {\n relation := new(unit.Relation)\n\n relation.Tname = statement.Lrelation.Tname\n\n for _, l_tuple := range statement.Lrelation.Tuples {\n present := false\n\n for _, r_tuple := range statement.Rrelation.Tuples {\n if l_tuple.Hash == r_tuple.Hash {\n present = true\n break\n }\n }\n\n if !present {\n relation.Tuples = append(relation.Tuples, l_tuple)\n }\n }\n\n return relation\n } else {\n return nil\n }\n}\n\n\nfunc relationsTypeMatches(lrelation, rrelation *unit.Relation) bool {\n if lrelation.Tname == rrelation.Tname {\n return true\n } else {\n messages.TypesMismatch()\n return true\n }\n}\n\nfunc Create(lrelation, rrelation *unit.Relation) *unit.MinusStatement ", "output": "{\n if lrelation != nil && rrelation != nil && relationsTypeMatches(lrelation, rrelation) {\n statement := new(unit.MinusStatement)\n\n statement.Lrelation = lrelation\n statement.Rrelation = rrelation\n\n return statement\n } else {\n return nil\n }\n}"} {"input": "package nl\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\ntype RtMsg struct {\n\tsyscall.RtMsg\n}\n\nfunc NewRtMsg() *RtMsg {\n\treturn &RtMsg{\n\t\tRtMsg: syscall.RtMsg{\n\t\t\tTable: syscall.RT_TABLE_MAIN,\n\t\t\tScope: syscall.RT_SCOPE_UNIVERSE,\n\t\t\tProtocol: syscall.RTPROT_BOOT,\n\t\t\tType: syscall.RTN_UNICAST,\n\t\t},\n\t}\n}\n\n\n\nfunc (msg *RtMsg) Len() int {\n\treturn syscall.SizeofRtMsg\n}\n\nfunc DeserializeRtMsg(b []byte) *RtMsg {\n\treturn (*RtMsg)(unsafe.Pointer(&b[0:syscall.SizeofRtMsg][0]))\n}\n\nfunc (msg *RtMsg) Serialize() []byte {\n\treturn (*(*[syscall.SizeofRtMsg]byte)(unsafe.Pointer(msg)))[:]\n}\n\ntype RtNexthop struct {\n\tsyscall.RtNexthop\n}\n\nfunc DeserializeRtNexthop(b []byte) *RtNexthop {\n\treturn (*RtNexthop)(unsafe.Pointer(&b[0:syscall.SizeofRtNexthop][0]))\n}\n\nfunc (msg *RtNexthop) Serialize() []byte {\n\treturn (*(*[syscall.SizeofRtNexthop]byte)(unsafe.Pointer(msg)))[:]\n}\n\nfunc NewRtDelMsg() *RtMsg ", "output": "{\n\treturn &RtMsg{\n\t\tRtMsg: syscall.RtMsg{\n\t\t\tTable: syscall.RT_TABLE_MAIN,\n\t\t\tScope: syscall.RT_SCOPE_NOWHERE,\n\t\t},\n\t}\n}"} {"input": "package sliceset\n\nimport (\n\t\"sort\"\n\n\t\"github.com/xtgo/set\"\n)\n\ntype Set []int\n\nfunc (s Set) Len() int { return len(s) }\nfunc (s Set) Less(i, j int) bool { return s[i] < s[j] }\nfunc (s Set) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s Set) Copy() Set { return append(Set(nil), s...) }\n\nfunc (s Set) Union(t Set) Set { return s.Do(set.Union, t) }\nfunc (s Set) Inter(t Set) Set { return s.Do(set.Inter, t) }\nfunc (s Set) Diff(t Set) Set { return s.Do(set.Diff, t) }\nfunc (s Set) SymDiff(t Set) Set { return s.Do(set.SymDiff, t) }\nfunc (s Set) IsSub(t Set) bool { return s.DoBool(set.IsSub, t) }\nfunc (s Set) IsSuper(t Set) bool { return s.DoBool(set.IsSuper, t) }\nfunc (s Set) IsInter(t Set) bool { return s.DoBool(set.IsInter, t) }\nfunc (s Set) IsEqual(t Set) bool { return s.DoBool(set.IsEqual, t) }\n\nfunc (s Set) Uniq() Set {\n\tn := set.Uniq(s)\n\treturn s[:n]\n}\n\nfunc (s Set) Do(op set.Op, t Set) Set {\n\tdata := append(s, t...)\n\tn := op(data, len(s))\n\treturn data[:n]\n}\n\ntype BoolOp func(sort.Interface, int) bool\n\n\n\nfunc (s Set) DoBool(op BoolOp, t Set) bool ", "output": "{\n\tdata := append(s, t...)\n\treturn op(data, len(s))\n}"} {"input": "package api\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n)\n\nfunc handleInternalServerError(w http.ResponseWriter) {\n\thttp.Error(w, http.StatusText(http.StatusInternalServerError),\n\t\thttp.StatusInternalServerError)\n}\n\nfunc handleUnauthorized(w http.ResponseWriter) {\n\thttp.Error(w, http.StatusText(http.StatusUnauthorized),\n\t\thttp.StatusUnauthorized)\n}\n\n\n\n\nfunc writeJSON(w http.ResponseWriter, v interface{}) error ", "output": "{\n\tb, err := json.Marshal(v)\n\tif err != nil {\n\t\thandleInternalServerError(w)\n\t\treturn err\n\t}\n\n\tif _, err = w.Write(b); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package networkcontainers\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com/Azure/azure-container-networking/cns\"\n\t\"github.com/Azure/azure-container-networking/log\"\n)\n\n\ntype NetworkContainers struct {\n\tlogpath string\n}\n\n\n\n\nfunc (cn *NetworkContainers) Create(createNetworkContainerRequest cns.CreateNetworkContainerRequest) error {\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Create called\")\n\terr := createOrUpdateInterface(createNetworkContainerRequest)\n\tif err == nil {\n\t\terr = setWeakHostOnInterface(createNetworkContainerRequest.PrimaryInterfaceIdentifier)\n\t}\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Create finished.\")\n\treturn err\n}\n\n\nfunc (cn *NetworkContainers) Update(createNetworkContainerRequest cns.CreateNetworkContainerRequest) error {\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Update called\")\n\terr := createOrUpdateInterface(createNetworkContainerRequest)\n\tif err == nil {\n\t\terr = setWeakHostOnInterface(createNetworkContainerRequest.PrimaryInterfaceIdentifier)\n\t}\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Update finished.\")\n\treturn err\n}\n\n\nfunc (cn *NetworkContainers) Delete(networkContainerID string) error {\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Delete called\")\n\terr := deleteInterface(networkContainerID)\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Delete finished.\")\n\treturn err\n}\n\nfunc interfaceExists(iFaceName string) (bool, error) ", "output": "{\n\t_, err := net.InterfaceByName(iFaceName)\n\n\tif err != nil {\n\t\terrMsg := fmt.Sprintf(\"[Azure CNS] Unable to get interface by name %v, %v\", iFaceName, err)\n\t\tlog.Printf(errMsg)\n\t\treturn false, errors.New(errMsg)\n\t}\n\n\treturn true, nil\n}"} {"input": "package cmd\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n)\n\n\n\nfunc TestEvalBinding(t *testing.T) ", "output": "{\n\tout := new(bytes.Buffer)\n\tif err := evalBinding(out, \"../testdata/triggerbinding.yaml\", \"../testdata/http.txt\"); err != nil {\n\t\tt.Fatalf(\"evalBinding: %v\", err)\n\t}\n\n\twant := `[\n {\n \"name\": \"bar\",\n \"value\": \"tacocat\"\n },\n {\n \"name\": \"foo\",\n \"value\": \"body\"\n }\n]\n`\n\tif diff := cmp.Diff(want, out.String()); diff != \"\" {\n\t\tt.Errorf(\"-want +got: %s\", diff)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype Page struct {\n\tTitle string\n\tBody []byte\n}\n\nfunc (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}\n\n\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/view/\"):]\n\tp, _ := loadPage(title)\n\tfmt.Fprintf(w, \"

%s

%s
\", p.Title, p.Body)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/view/\", viewHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc loadPage(title string) (*Page, error) ", "output": "{\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Page{Title: title, Body: body}, nil\n}"} {"input": "package sarama\n\n\ntype ApiVersionsRequest struct{}\n\nfunc (a *ApiVersionsRequest) encode(pe packetEncoder) error {\n\treturn nil\n}\n\nfunc (a *ApiVersionsRequest) decode(pd packetDecoder, version int16) (err error) {\n\treturn nil\n}\n\nfunc (a *ApiVersionsRequest) key() int16 {\n\treturn 18\n}\n\nfunc (a *ApiVersionsRequest) version() int16 {\n\treturn 0\n}\n\n\n\nfunc (a *ApiVersionsRequest) requiredVersion() KafkaVersion {\n\treturn V0_10_0_0\n}\n\nfunc (a *ApiVersionsRequest) headerVersion() int16 ", "output": "{\n\treturn 1\n}"} {"input": "package togglr\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"reflect\"\n)\n\ntype jsonConfigSource struct {\n\tjsonData map[string]interface{}\n}\n\n\n\nfunc (source jsonConfigSource) GetConfig(name string, tag reflect.StructTag) (interface{}, bool) {\n\tkey := tag.Get(\"json\")\n\tif key == \"\" {\n\t\tkey = name\n\t}\n\tval, ok := source.jsonData[key]\n\n\treturn val, ok\n}\n\nfunc NewJsonConfigSource(path string) ConfigSource ", "output": "{\n\tfile, _ := ioutil.ReadFile(path)\n\tjsonData := make(map[string]interface{})\n\tjson.Unmarshal(file, &jsonData)\n\treturn jsonConfigSource{jsonData}\n}"} {"input": "package sample\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n)\n\ntype sampleState struct {\n\trate uint64\n\tseed int64\n\tsampleCount uint64\n\ttrueCount uint64\n\trnd *rand.Rand\n}\n\n\ntype Sampler interface {\n\tSample() bool\n\tSampleFrom(probe uint64) bool\n\tState\n}\n\n\ntype State interface {\n\tReset()\n\tString() string\n\tRate() uint64\n\tCalls() uint64\n\tCount() uint64\n}\n\nfunc (state *sampleState) Rate() uint64 {\n\tif state != nil {\n\t\treturn state.rate\n\t}\n\treturn 0\n}\n\nfunc (state *sampleState) Calls() uint64 {\n\tif state != nil {\n\t\treturn state.sampleCount\n\t}\n\treturn 0\n}\n\n\n\nfunc (state *sampleState) Reset() {\n\tstate.rnd.Seed(state.seed)\n\tstate.sampleCount = 0\n\tstate.trueCount = 0\n}\n\nfunc (state *sampleState) String() string {\n\ttype X *sampleState\n\tx := X(state)\n\treturn fmt.Sprintf(\"%+v\", x)\n}\n\n\nfunc Deviation(state State) (deviation float64) {\n\tif state != nil && state.Count() > 0 {\n\t\tdeviation = 1.0 - 1.0/float64(state.Rate())*(float64(state.Calls())/float64(state.Count()))\n\t} else {\n\t\tdeviation = 1.0\n\t}\n\n\treturn\n}\n\n\nfunc Stats(state State) string {\n\tif state != nil {\n\t\treturn fmt.Sprintf(\"Rate: %d, SampleCount: %d, TrueCount: %d, Deviation: %.4f%%\", state.Rate(), state.Calls(), state.Count(), Deviation(state)*100.0)\n\t}\n\treturn \"No state provided\"\n}\n\nfunc (state *sampleState) Count() uint64 ", "output": "{\n\tif state != nil {\n\t\treturn state.trueCount\n\t}\n\treturn 0\n}"} {"input": "package objects\n\nimport \"strings\"\n\nconst (\n\tPREFIX_FADERDATATYPE = \"application/fader.datatypes.\"\n\n\tInvalidObject ObjectType = \"\"\n\tBlobObject ObjectType = \"blob\"\n\tUserObject ObjectType = \"user\"\n)\n\n\n\ntype ObjectType string\n\nfunc (t ObjectType) String() string {\n\treturn string(t)\n}\n\nfunc (t ObjectType) Bytes() []byte {\n\treturn []byte(t.String())\n}\n\n\n\ntype ContentType string\n\nvar (\n\tTUnknown ContentType = \"application/fader.dt.unknown\"\n\tTString ContentType = \"application/fader.dt.string\"\n\tTNumber ContentType = \"application/fader.dt.number\"\n\tTBool ContentType = \"application/fader.dt.bool\"\n\tTArray ContentType = \"application/fader.dt.array\"\n\tTMap ContentType = \"application/fader.dt.map\"\n\tTCustom ContentType = \"application/fader.dt.custom.\"\n)\n\nfunc TypeFrom(v interface{}) (t ContentType) {\n\tswitch v.(type) {\n\tcase float32, float64, int, int32, int64:\n\t\treturn TNumber\n\tcase string:\n\t\treturn TString\n\tcase bool:\n\t\treturn TBool\n\tcase []interface{}:\n\t\treturn TArray\n\tcase map[string]interface{}:\n\t\treturn TMap\n\t}\n\n\treturn TUnknown\n}\n\nfunc (t ContentType) String() string {\n\treturn string(t)\n}\n\nfunc (t ContentType) Valid() bool {\n\treturn strings.HasPrefix(t.String(), PREFIX_FADERDATATYPE)\n}\n\n\n\nfunc (t ContentType) Equal(v ContentType) bool ", "output": "{\n\treturn t == v\n}"} {"input": "package gorequest\n\nimport (\n \"time\"\n \"net/http\"\n)\n\n\n\n\n\n\n\nfunc (s *SuperAgent) Timeout(timeout time.Duration) *SuperAgent {\n s.safeModifyHttpClient()\n s.Client.Timeout = timeout\n return s\n}\n\nfunc (s *SuperAgent) safeModifyHttpClient() ", "output": "{\n if !s.isClone {\n return\n }\n oldClient := s.Client\n s.Client = &http.Client{}\n s.Client.Jar = oldClient.Jar\n s.Client.Transport = oldClient.Transport\n s.Client.Timeout = oldClient.Timeout\n s.Client.CheckRedirect = oldClient.CheckRedirect\n}"} {"input": "package objectstorage\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype ListMultipartUploadsRequest struct {\n\n\tNamespaceName *string `mandatory:\"true\" contributesTo:\"path\" name:\"namespaceName\"`\n\n\tBucketName *string `mandatory:\"true\" contributesTo:\"path\" name:\"bucketName\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tOpcClientRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-client-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request ListMultipartUploadsRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request ListMultipartUploadsRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListMultipartUploadsResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []MultipartUpload `presentIn:\"body\"`\n\n\tOpcClientRequestId *string `presentIn:\"header\" name:\"opc-client-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n}\n\nfunc (response ListMultipartUploadsResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListMultipartUploadsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListMultipartUploadsRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package common\n\nimport (\n\t\"io/ioutil\"\n\n\t\"github.com/hyperledger/fabric/cmd/common/comm\"\n\t\"github.com/hyperledger/fabric/cmd/common/signer\"\n\t\"github.com/pkg/errors\"\n\tyaml \"gopkg.in/yaml.v2\"\n)\n\n\ntype Config struct {\n\tVersion int\n\tTLSConfig comm.Config\n\tSignerConfig signer.Config\n}\n\n\nfunc ConfigFromFile(file string) (Config, error) {\n\tconfigData, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn Config{}, errors.WithStack(err)\n\t}\n\tconfig := Config{}\n\n\tif err := yaml.Unmarshal([]byte(configData), &config); err != nil {\n\t\treturn Config{}, errors.Errorf(\"error unmarshaling YAML file %s: %s\", file, err)\n\t}\n\n\treturn config, validateConfig(config)\n}\n\n\nfunc (c Config) ToFile(file string) error {\n\tif err := validateConfig(c); err != nil {\n\t\treturn errors.Wrap(err, \"config isn't valid\")\n\t}\n\tb, _ := yaml.Marshal(c)\n\tif err := ioutil.WriteFile(file, b, 0o600); err != nil {\n\t\treturn errors.Errorf(\"failed writing file %s: %v\", file, err)\n\t}\n\treturn nil\n}\n\n\n\nfunc validateConfig(conf Config) error ", "output": "{\n\tnonEmptyStrings := []string{\n\t\tconf.SignerConfig.MSPID,\n\t\tconf.SignerConfig.IdentityPath,\n\t\tconf.SignerConfig.KeyPath,\n\t}\n\n\tfor _, s := range nonEmptyStrings {\n\t\tif s == \"\" {\n\t\t\treturn errors.New(\"empty string that is mandatory\")\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package splitter\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/libgit2/git2go\"\n)\n\n\ntype Result struct {\n\tmu sync.RWMutex\n\ttraversed int\n\tcreated int\n\thead *git.Oid\n\tduration time.Duration\n}\n\n\nfunc NewResult(duration time.Duration, traversed, created int) *Result {\n\treturn &Result{\n\t\tduration: duration,\n\t\ttraversed: traversed,\n\t\tcreated: created,\n\t}\n}\n\n\nfunc (r *Result) Traversed() int {\n\tr.mu.RLock()\n\tdefer r.mu.RUnlock()\n\treturn r.traversed\n}\n\n\nfunc (r *Result) Created() int {\n\tr.mu.RLock()\n\tdefer r.mu.RUnlock()\n\treturn r.created\n}\n\n\nfunc (r *Result) Duration(precision time.Duration) time.Duration {\n\tr.mu.RLock()\n\tdefer r.mu.RUnlock()\n\treturn roundDuration(r.duration, precision)\n}\n\n\nfunc (r *Result) Head() *git.Oid {\n\tr.mu.RLock()\n\tdefer r.mu.RUnlock()\n\treturn r.head\n}\n\nfunc (r *Result) moveHead(oid *git.Oid) {\n\tr.mu.Lock()\n\tr.head = oid\n\tr.mu.Unlock()\n}\n\nfunc (r *Result) incCreated() {\n\tr.mu.Lock()\n\tr.created++\n\tr.mu.Unlock()\n}\n\nfunc (r *Result) incTraversed() {\n\tr.mu.Lock()\n\tr.traversed++\n\tr.mu.Unlock()\n}\n\nfunc (r *Result) end(start time.Time) {\n\tr.mu.Lock()\n\tr.duration = time.Since(start)\n\tr.mu.Unlock()\n}\n\n\n\n\nfunc roundDuration(d, r time.Duration) time.Duration ", "output": "{\n\tif r <= 0 {\n\t\treturn d\n\t}\n\tneg := d < 0\n\tif neg {\n\t\td = -d\n\t}\n\tif m := d % r; m+m < r {\n\t\td = d - m\n\t} else {\n\t\td = d + r - m\n\t}\n\tif neg {\n\t\treturn -d\n\t}\n\treturn d\n}"} {"input": "package roles\n\nimport (\n\t\"testing\"\n\n\t\"github.com/rackspace/gophercloud/pagination\"\n\tth \"github.com/rackspace/gophercloud/testhelper\"\n\t\"github.com/rackspace/gophercloud/testhelper/client\"\n)\n\nfunc TestRole(t *testing.T) {\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\n\tMockListRoleResponse(t)\n\n\tcount := 0\n\n\terr := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) {\n\t\tcount++\n\t\tactual, err := ExtractRoles(page)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to extract users: %v\", err)\n\t\t\treturn false, err\n\t\t}\n\n\t\texpected := []Role{\n\t\t\tRole{\n\t\t\t\tID: \"123\",\n\t\t\t\tName: \"compute:admin\",\n\t\t\t\tDescription: \"Nova Administrator\",\n\t\t\t},\n\t\t}\n\n\t\tth.CheckDeepEquals(t, expected, actual)\n\n\t\treturn true, nil\n\t})\n\n\tth.AssertNoErr(t, err)\n\tth.AssertEquals(t, 1, count)\n}\n\n\n\nfunc TestDeleteUserRole(t *testing.T) {\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\n\tMockDeleteUserRoleResponse(t)\n\n\terr := DeleteUserRole(client.ServiceClient(), \"{tenant_id}\", \"{user_id}\", \"{role_id}\").ExtractErr()\n\n\tth.AssertNoErr(t, err)\n}\n\nfunc TestAddUserRole(t *testing.T) ", "output": "{\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\n\tMockAddUserRoleResponse(t)\n\n\terr := AddUserRole(client.ServiceClient(), \"{tenant_id}\", \"{user_id}\", \"{role_id}\").ExtractErr()\n\n\tth.AssertNoErr(t, err)\n}"} {"input": "package main\n\nimport (\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/rakyll/statik/fs\"\n\n\t_ \"github.com/reviewdog/reviewdog/doghouse/appengine/statik\"\n)\n\nvar tmplFiles http.FileSystem\n\nfunc mustParseTemplatesFiles(filenames ...string) *template.Template {\n\tt, err := parseTemplatesFiles(filenames...)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn t\n}\n\n\n\nvar (\n\ttopTmpl *template.Template\n\tghTopTmpl *template.Template\n\tghRepoTmpl *template.Template\n)\n\nfunc initTemplates() {\n\tvar err error\n\ttmplFiles, err = fs.New()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttopTmpl = mustParseTemplatesFiles(\n\t\t\"/base.html\",\n\t\t\"/index.html\",\n\t)\n\n\tghTopTmpl = mustParseTemplatesFiles(\n\t\t\"/gh/base.html\",\n\t\t\"/gh/header.html\",\n\t\t\"/gh/top.html\",\n\t)\n\n\tghRepoTmpl = mustParseTemplatesFiles(\n\t\t\"/gh/base.html\",\n\t\t\"/gh/header.html\",\n\t\t\"/gh/repo.html\",\n\t)\n}\n\nfunc parseTemplatesFiles(filenames ...string) (*template.Template, error) ", "output": "{\n\tvar t *template.Template\n\tfor _, filename := range filenames {\n\t\tif t == nil {\n\t\t\tt = template.New(filename)\n\t\t}\n\t\ttext, err := fs.ReadFile(tmplFiles, filename)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tt, err = t.Parse(string(text))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn t, nil\n}"} {"input": "package tsmt\n\nimport (\n\t\"encoding/xml\"\n\n\t\"github.com/fgrid/iso20022\"\n)\n\ntype Document05500101 struct {\n\tXMLName xml.Name `xml:\"urn:iso:std:iso:20022:tech:xsd:tsmt.055.001.01 Document\"`\n\tMessage *PartyEventAdviceV01 `xml:\"PtyEvtAdvc\"`\n}\n\nfunc (d *Document05500101) AddMessage() *PartyEventAdviceV01 {\n\td.Message = new(PartyEventAdviceV01)\n\treturn d.Message\n}\n\n\n\n\n\ntype PartyEventAdviceV01 struct {\n\n\tHeader *iso20022.BusinessLetter1 `xml:\"Hdr\"`\n\n\tEventNotice []*iso20022.EventDescription1 `xml:\"EvtNtce\"`\n\n\tEventCount *iso20022.Max15NumericText `xml:\"EvtCnt,omitempty\"`\n\n\tAttachedMessage []*iso20022.EncapsulatedBusinessMessage1 `xml:\"AttchdMsg,omitempty\"`\n}\n\nfunc (p *PartyEventAdviceV01) AddHeader() *iso20022.BusinessLetter1 {\n\tp.Header = new(iso20022.BusinessLetter1)\n\treturn p.Header\n}\n\nfunc (p *PartyEventAdviceV01) AddEventNotice() *iso20022.EventDescription1 {\n\tnewValue := new(iso20022.EventDescription1)\n\tp.EventNotice = append(p.EventNotice, newValue)\n\treturn newValue\n}\n\nfunc (p *PartyEventAdviceV01) SetEventCount(value string) {\n\tp.EventCount = (*iso20022.Max15NumericText)(&value)\n}\n\n\n\nfunc (p *PartyEventAdviceV01) AddAttachedMessage() *iso20022.EncapsulatedBusinessMessage1 ", "output": "{\n\tnewValue := new(iso20022.EncapsulatedBusinessMessage1)\n\tp.AttachedMessage = append(p.AttachedMessage, newValue)\n\treturn newValue\n}"} {"input": "package runtime\n\nimport (\n\t\"strings\"\n\n\t\"github.com/Shopify/go-lua\"\n\t\"github.com/fsouza/go-dockerclient\"\n\t\"github.com/involucro/involucro/auth\"\n\t\"github.com/involucro/involucro/ilog\"\n)\n\ntype pushStepBuilderState struct {\n\tpushStep\n\tupper fm\n\tregisterStep func(Step)\n}\n\ntype pushStep struct {\n\tdocker.PushImageOptions\n}\n\nfunc newPushSubBuilder(upper fm, register func(Step)) lua.Function {\n\tpsbs := pushStepBuilderState{\n\t\tupper: upper,\n\t\tregisterStep: register,\n\t}\n\treturn psbs.push\n}\n\n\n\nfunc (s pushStep) Take(i *Runtime) error {\n\tac, foundAuthentication, err := auth.ForServer(serverOfRepo(s.PushImageOptions.Name))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := i.client.PushImage(s.PushImageOptions, ac); err != nil {\n\t\tif !foundAuthentication {\n\t\t\tilog.Warn.Logf(\"Pull may have failed due to missing authentication information in ~/.involucro\")\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (s pushStep) ShowStartInfo() {\n\tlogTask.Logf(\"Push image [%s:%s]\", s.Name, s.Tag)\n}\n\nfunc serverOfRepo(name string) string {\n\tparts := strings.Split(name, \"/\")\n\tif len(parts) < 3 {\n\t\treturn \"\"\n\t}\n\treturn strings.Join(parts[:len(parts)-2], \"/\")\n}\n\nfunc (psbs pushStepBuilderState) push(l *lua.State) int ", "output": "{\n\topts := &psbs.PushImageOptions\n\topts.Name = lua.CheckString(l, 1)\n\tif l.Top() >= 2 {\n\t\topts.Tag = lua.CheckString(l, 2)\n\t} else {\n\t\topts.Name, _, opts.Tag = repoNameAndTagFrom(opts.Name)\n\t}\n\tpsbs.registerStep(psbs.pushStep)\n\n\treturn tableWith(l, psbs.upper)\n}"} {"input": "package fields\n\nimport (\n\t\"regexp\"\n\t\"time\"\n)\n\nfunc UseDefaultKeyIfCustomKeyIsEmpty(defaultKey, customKey string) string {\n\tif \"\" != customKey {\n\t\treturn customKey\n\t}\n\treturn defaultKey\n}\n\nfunc ExecFuncIfErrIsNotNil(err error, fn func()) (b bool) {\n\tif nil != err {\n\t\tfn()\n\t\tb = true\n\t}\n\treturn\n}\n\nfunc getMessageFromError(err error) string {\n\tif nil == err {\n\t\treturn \"\"\n\t}\n\treturn err.Error()\n}\n\n\n\nfunc execFnIfNotNil(fn func()) {\n\tif nil != fn {\n\t\tfn()\n\t}\n}\n\nfunc addSuffix(name string, suffix *string) string {\n\tif nil != suffix {\n\t\treturn name + \"-\" + *suffix\n\t}\n\treturn name\n}\n\nfunc _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) (*time.Location, int) {\n\tif nil == locationByString || \"\" == *locationByString {\n\t\treturn defaultLoc, 1\n\t}\n\n\tif loc, err := time.LoadLocation(*locationByString); nil == err {\n\t\treturn loc, 2\n\t}\n\n\treturn defaultLoc, 0\n}\n\n\nfunc useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) *time.Location {\n\tloc, _ := _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc, locationByString)\n\treturn loc\n}\n\nfunc getPatternFromRegExp(re *regexp.Regexp) string ", "output": "{\n\tif nil == re {\n\t\treturn \"\"\n\t}\n\treturn re.String()\n}"} {"input": "package resourcemanager\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteTemplateRequest struct {\n\n\tTemplateId *string `mandatory:\"true\" contributesTo:\"path\" name:\"templateId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteTemplateRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteTemplateRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request DeleteTemplateRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype DeleteTemplateResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteTemplateResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteTemplateResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteTemplateRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package upload\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"go.skia.org/infra/perf/go/ingest/format\"\n)\n\n\n\n\n\n\n\nfunc ObjectPath(benchData *format.BenchData, gcsPath string, now time.Time, b []byte) string {\n\thash := fmt.Sprintf(\"%x\", md5.Sum(b))\n\tkeyparts := []string{}\n\tif benchData.Key != nil {\n\t\tfor k, v := range benchData.Key {\n\t\t\tkeyparts = append(keyparts, k, v)\n\t\t}\n\t}\n\tfilename := fmt.Sprintf(\"%s_%s_%s.json\", benchData.Hash, strings.Join(keyparts, \"_\"), hash)\n\treturn path.Join(gcsPath, now.Format(\"2006/01/02/15/\"), filename)\n}\n\n\n\n\n\n\n\n\n\nfunc LogPath(gcsPath string, now time.Time, b []byte) string ", "output": "{\n\thash := fmt.Sprintf(\"%x\", md5.Sum(b))\n\tfilename := fmt.Sprintf(\"%s.json\", hash)\n\treturn path.Join(gcsPath, now.Format(\"2006/01/02/15/\"), filename)\n}"} {"input": "package secret\n\nconst (\n\tAdminserverUser = \"harbor-adminserver\"\n\tJobserviceUser = \"harbor-jobservice\"\n\tUIUser = \"harbor-ui\"\n)\n\n\ntype Store struct {\n\tsecrets map[string]string\n}\n\n\nfunc NewStore(secrets map[string]string) *Store {\n\treturn &Store{\n\t\tsecrets: secrets,\n\t}\n}\n\n\nfunc (s *Store) IsValid(secret string) bool {\n\treturn len(s.GetUsername(secret)) != 0\n}\n\n\n\n\nfunc (s *Store) GetUsername(secret string) string ", "output": "{\n\treturn s.secrets[secret]\n}"} {"input": "package util\n\nimport (\n\t\"sort\"\n\n\t\"github.com/prometheus/common/model\"\n\t\"github.com/weaveworks/cortex/pkg/prom1/storage/metric\"\n)\n\n\n\ntype SampleStreamIterator struct {\n\tss *model.SampleStream\n}\n\n\nfunc NewSampleStreamIterator(ss *model.SampleStream) SampleStreamIterator {\n\treturn SampleStreamIterator{ss: ss}\n}\n\n\nfunc (it SampleStreamIterator) Metric() metric.Metric {\n\treturn metric.Metric{Metric: it.ss.Metric}\n}\n\n\n\n\n\nfunc (it SampleStreamIterator) RangeValues(in metric.Interval) []model.SamplePair {\n\tn := len(it.ss.Values)\n\tstart := sort.Search(n, func(i int) bool {\n\t\treturn !it.ss.Values[i].Timestamp.Before(in.OldestInclusive)\n\t})\n\tend := sort.Search(n, func(i int) bool {\n\t\treturn it.ss.Values[i].Timestamp.After(in.NewestInclusive)\n\t})\n\n\tif start == n {\n\t\treturn nil\n\t}\n\n\treturn it.ss.Values[start:end]\n}\n\n\nfunc (it SampleStreamIterator) Close() {}\n\nfunc (it SampleStreamIterator) ValueAtOrBeforeTime(ts model.Time) model.SamplePair ", "output": "{\n\ti := sort.Search(len(it.ss.Values), func(n int) bool {\n\t\treturn it.ss.Values[n].Timestamp.After(ts)\n\t})\n\tif i == 0 {\n\t\treturn model.SamplePair{Timestamp: model.Earliest}\n\t}\n\treturn it.ss.Values[i-1]\n}"} {"input": "package service\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"gopkg.in/gin-gonic/gin.v0\"\n\t\"gopkg.in/jmoiron/sqlx.v0\"\n\t_ \"gopkg.in/lib/pq.v0\"\n\t_ \"gopkg.in/mattn/go-sqlite3.v0\"\n)\n\ntype Config struct {\n\tServiceHost string `yaml:\"host,flow\"`\n\tDbDriver string `yaml:\"driver,flow\"`\n\tDbSource string `yaml:\"datasource,flow\"`\n\tKeyFile string\n}\n\ntype AuthService struct{}\n\nfunc (s *AuthService) GetHttpHandler(conf Config) (http.Handler, error) {\n\tdbh, err := GetDBHandler(conf)\n\tif err != nil {\n\t\treturn gin.New(), err\n\t}\n\n\tkeyData, err := ioutil.ReadFile(conf.KeyFile)\n\tif err != nil {\n\t\treturn gin.New(), err\n\t}\n\n\tresource := &AuthResource{dbh, keyData}\n\tr := gin.Default()\n\tauth := r.Group(\"/auth\")\n\tauth.POST(\"/login\", resource.CreateSession)\n\tauth.POST(\"/signup\", resource.CreateUser)\n\treturn r, nil\n}\n\n\n\nfunc GetDBHandler(conf Config) (*sqlx.DB, error) ", "output": "{\n\tdbh, err := sqlx.Connect(conf.DbDriver, conf.DbSource)\n\treturn dbh, err\n}"} {"input": "package endpoint\n\nimport (\n\t\"fmt\"\n)\n\nconst (\n\t_PlaceholderCreationEncryptionPropertyName_0 = \"unspecifiedinherit\"\n\t_PlaceholderCreationEncryptionPropertyName_1 = \"off\"\n)\n\nvar (\n\t_PlaceholderCreationEncryptionPropertyIndex_0 = [...]uint8{0, 11, 18}\n\t_PlaceholderCreationEncryptionPropertyIndex_1 = [...]uint8{0, 3}\n)\n\nfunc (i PlaceholderCreationEncryptionProperty) String() string {\n\tswitch {\n\tcase 1 <= i && i <= 2:\n\t\ti -= 1\n\t\treturn _PlaceholderCreationEncryptionPropertyName_0[_PlaceholderCreationEncryptionPropertyIndex_0[i]:_PlaceholderCreationEncryptionPropertyIndex_0[i+1]]\n\tcase i == 4:\n\t\treturn _PlaceholderCreationEncryptionPropertyName_1\n\tdefault:\n\t\treturn fmt.Sprintf(\"PlaceholderCreationEncryptionProperty(%d)\", i)\n\t}\n}\n\nvar _PlaceholderCreationEncryptionPropertyValues = []PlaceholderCreationEncryptionProperty{1, 2, 4}\n\nvar _PlaceholderCreationEncryptionPropertyNameToValueMap = map[string]PlaceholderCreationEncryptionProperty{\n\t_PlaceholderCreationEncryptionPropertyName_0[0:11]: 1,\n\t_PlaceholderCreationEncryptionPropertyName_0[11:18]: 2,\n\t_PlaceholderCreationEncryptionPropertyName_1[0:3]: 4,\n}\n\n\n\n\n\n\nfunc PlaceholderCreationEncryptionPropertyValues() []PlaceholderCreationEncryptionProperty {\n\treturn _PlaceholderCreationEncryptionPropertyValues\n}\n\n\nfunc (i PlaceholderCreationEncryptionProperty) IsAPlaceholderCreationEncryptionProperty() bool {\n\tfor _, v := range _PlaceholderCreationEncryptionPropertyValues {\n\t\tif i == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc PlaceholderCreationEncryptionPropertyString(s string) (PlaceholderCreationEncryptionProperty, error) ", "output": "{\n\tif val, ok := _PlaceholderCreationEncryptionPropertyNameToValueMap[s]; ok {\n\t\treturn val, nil\n\t}\n\treturn 0, fmt.Errorf(\"%s does not belong to PlaceholderCreationEncryptionProperty values\", s)\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"os\"\n \"path/filepath\"\n\n \"github.com/aws/aws-sdk-go/aws\"\n \"github.com/aws/aws-sdk-go/aws/awserr\"\n \"github.com/aws/aws-sdk-go/aws/session\"\n \"github.com/aws/aws-sdk-go/service/ec2\"\n)\n\n\n\n\n\nfunc main() {\n if len(os.Args) != 2 {\n exitErrorf(\"Security Group ID required\\nUsage: %s group_id\",\n filepath.Base(os.Args[0]))\n }\n groupID := os.Args[1]\n\n \n \n sess, err := session.NewSession(&aws.Config{\n Region: aws.String(\"us-west-2\")},\n )\n\n \n svc := ec2.New(sess)\n\n \n _, err = svc.DeleteSecurityGroup(&ec2.DeleteSecurityGroupInput{\n GroupId: aws.String(groupID),\n })\n if err != nil {\n if aerr, ok := err.(awserr.Error); ok {\n switch aerr.Code() {\n case \"InvalidGroupId.Malformed\":\n fallthrough\n case \"InvalidGroup.NotFound\":\n exitErrorf(\"%s.\", aerr.Message())\n }\n }\n exitErrorf(\"Unable to get descriptions for security groups, %v.\", err)\n }\n\n fmt.Printf(\"Successfully delete security group %q.\\n\", groupID)\n}\n\n\n\nfunc exitErrorf(msg string, args ...interface{}) ", "output": "{\n fmt.Fprintf(os.Stderr, msg+\"\\n\", args...)\n os.Exit(1)\n}"} {"input": "package main\n\nimport \"github.com/astaxie/beego/orm\"\n\ntype User struct {\n\tId int\n\tName string\n}\n\ntype Profile struct {\n\tId int\n\tAge int16\n}\n\n\n\nfunc init() ", "output": "{\n\torm.RegisterModel(new(User))\n}"} {"input": "package format\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\n\ntype Unsigned32 uint32\n\n\n\nfunc (n Unsigned32) Serialize() []byte {\n\tb := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(b, uint32(n))\n\treturn b\n}\n\nfunc (n Unsigned32) Len() int {\n\treturn 4\n}\n\nfunc (n Unsigned32) Padding() int {\n\treturn 0\n}\n\nfunc (n Unsigned32) Format() FormatId {\n\treturn Unsigned32Format\n}\n\nfunc (n Unsigned32) String() string {\n\treturn fmt.Sprintf(\"Unsigned32{%d}\", n)\n}\n\nfunc DecodeUnsigned32(b []byte) (Format, error) ", "output": "{\n\treturn Unsigned32(binary.BigEndian.Uint32(b)), nil\n}"} {"input": "package boom\n\nimport (\n\t\"github.com/efritz/glock\"\n)\n\ntype TaskConfig func(*taskConfig)\n\ntype taskConfig struct {\n\tclock glock.Clock\n}\n\nfunc newTaskConfig() *taskConfig {\n\treturn &taskConfig{\n\t\tclock: glock.NewRealClock(),\n\t}\n}\n\nfunc (tc *taskConfig) ApplyConfigs(configs []TaskConfig) {\n\tfor _, f := range configs {\n\t\tf(tc)\n\t}\n}\n\n\n\nfunc WithClock(clock glock.Clock) TaskConfig ", "output": "{\n\treturn func(cfg *taskConfig) {\n\t\tcfg.clock = clock\n\t}\n}"} {"input": "package listener\n\nimport (\n\t\"fmt\"\n)\n\nconst (\n\tDefaultGrpcPort = 18847\n\tDefaultHttpHealthCheckPort = 8080\n)\n\ntype Config struct {\n\tDebug bool\n\tGrpcPort int\n\tInsecureGrpcPort int\n\tHealthPort int\n\tTlsCertFile string\n\tTlsKeyFile string\n\tClientID string\n\tClientSecret string\n\tAuthDiscovery string\n\tRedisAddr string\n\tRedisPassword string\n\tRedisSentinel bool\n\tRedisMasterName string\n\tRedisDB int\n\tPubSubURL string\n\tInstanceName string\n\tNatsClusterID string\n}\n\nfunc (c *Config) GetGrpcPortString() string {\n\treturn fmt.Sprintf(\":%d\", c.GrpcPort)\n}\nfunc (c *Config) GetHealthPortString() string {\n\treturn fmt.Sprintf(\":%d\", c.HealthPort)\n}\n\n\nfunc NewConfig() *Config ", "output": "{\n\treturn &Config{\n\t\tGrpcPort: DefaultGrpcPort,\n\t\tHealthPort: DefaultHttpHealthCheckPort,\n\t\tRedisAddr: \"127.0.0.1:6379\",\n\t\tRedisPassword: \"\",\n\t\tRedisDB: 0,\n\t\tInsecureGrpcPort: 0,\n\t\tRedisMasterName: \"mymaster\",\n\t\tNatsClusterID: \"otsimo\",\n\t\tInstanceName: \"listener\",\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\nimport \"io/ioutil\"\nimport \"io\"\n\nimport \"net/http\"\n\ntype Response struct {\n\tBody io.ReadCloser\n}\n\n\n\nfunc main() {\n\tfmt.Println(\"hello world\")\n\n\tsendHttpGet(\"http:www.cnet.com\")\n}\n\nfunc askMeMyName() string {\n\tvar givenName string\n\tfmt.Println(\"What is your name?\")\n\tfmt.Scanf(\"%s\", &givenName)\n\n\treturn givenName\n}\n\nfunc sendHttpGet(url string) {\n\tresponse, err := http.Get(url)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif response.StatusCode == 200 {\n\t\tbody := Response{response.Body}\n\n\t\tfmt.Printf(\"%s\", body)\n\t} else {\n\t\tfmt.Printf(\"The Status code is %s\", response.StatusCode)\n\t}\n}\n\nfunc (resp Response) String() string ", "output": "{\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\n\treturn string(body)\n}"} {"input": "package main\n\nimport(\n\t\"io/ioutil\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\t\"fmt\"\n)\n\ntype route struct{\n\tto int32\n\tcost int32\n}\n\ntype node struct {\n\tneighbours []route\n}\n\nfunc readPlaces()([]node, int){\n\tbytes, err := ioutil.ReadFile(\"agraph\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlines := strings.Split(string(bytes),\"\\n\")\n\tnumNodes, err := strconv.Atoi(lines[0])\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\tlines = lines[1:]\n\tnodes := make([]node, numNodes)\n\tfor i := range nodes{\n\t\tnodes[i].neighbours = make([]route, 0, numNodes/2)\n\t}\n\tfor _,ln := range lines{\n\t\tnums := strings.Split(ln,\" \")\n\t\tif len(nums) < 3{\n\t\t\tbreak\n\t\t}\n\t\tnode, err1 := strconv.Atoi(nums[0])\n\t\tneighbour, err2 := strconv.Atoi(nums[1])\n\t\tcost, err3 := strconv.Atoi(nums[2])\n\t\tif err1 != nil || err2 != nil || err3 != nil{\n\t\t\tpanic(\"Error: encountered a line that wasn't three integers\")\n\t\t}\n\t\tnodes[node].neighbours = append(nodes[node].neighbours, route{to:int32(neighbour), cost:int32(cost)})\n\t}\n return nodes, numNodes\n}\n\n\n\nfunc main(){\n\tnodes, nNodes := readPlaces()\n\tvisited := make([]bool, nNodes)\n\tstart := time.Now()\n\tlen := getLongestPath(nodes, 0, visited)\n\tduration := time.Now().Sub(start).Nanoseconds() / 1000000\n\tfmt.Printf(\"%v LANGUAGE GCCGo %v\\n\", len, duration)\n\n}\n\nfunc getLongestPath(nodes []node, nodeID int32, visited []bool) int32", "output": "{\n\tvisited[nodeID] = true\n\tvar max int32\n\tfor _, neighbour := range nodes[nodeID].neighbours{\n\t\tif !visited[neighbour.to]{\n\t\t\tdist := neighbour.cost + getLongestPath(nodes, neighbour.to, visited)\n\t\t\tif dist > max{\n\t\t\t\tmax = dist\n\t\t\t}\n\t\t}\n\t}\n\tvisited[nodeID] = false\n\treturn max\n}"} {"input": "package iso20022\n\n\ntype BasicCollateralValuation1Details struct {\n\n\tValuationHaircut *PercentageRate `xml:\"ValtnHrcut\"`\n\n\tHaircutSource *PartyIdentification15 `xml:\"HrcutSrc,omitempty\"`\n}\n\nfunc (b *BasicCollateralValuation1Details) SetValuationHaircut(value string) {\n\tb.ValuationHaircut = (*PercentageRate)(&value)\n}\n\n\n\nfunc (b *BasicCollateralValuation1Details) AddHaircutSource() *PartyIdentification15 ", "output": "{\n\tb.HaircutSource = new(PartyIdentification15)\n\treturn b.HaircutSource\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestMain(m *testing.M) ", "output": "{\n\tr := m.Run()\n\tos.Exit(r)\n}"} {"input": "package utils\n\ntype Set map[string]bool\n\nfunc (self Set) Contains(key string) bool {\n\t_, found := self[key]\n\treturn found\n}\n\nfunc (self Set) Insert(key string) {\n\tself[key] = true\n}\n\n\n\nfunc (self Set) Size() int {\n\treturn len(self)\n}\n\nfunc (self Set) Remove(key string) ", "output": "{\n\tdelete(self, key)\n}"} {"input": "package rpkt\n\nimport (\n\t\"github.com/scionproto/scion/go/lib/addr\"\n\t\"github.com/scionproto/scion/go/lib/common\"\n\t\"github.com/scionproto/scion/go/lib/ctrl/path_mgmt\"\n\t\"github.com/scionproto/scion/go/lib/scmp\"\n)\n\ntype RevTokenCallbackArgs struct {\n\tRevInfo *path_mgmt.RevInfo\n\tAddrs []addr.HostSVC\n}\n\n\n\n\n\nfunc (rp *RtrPkt) parseSCMPPayload() (HookResult, common.Payload, error) ", "output": "{\n\thdr := rp.l4.(*scmp.Hdr)\n\tpld, err := scmp.PldFromRaw(rp.Raw[rp.idxs.pld:],\n\t\tscmp.ClassType{Class: hdr.Class, Type: hdr.Type})\n\tif err != nil {\n\t\treturn HookError, nil, err\n\t}\n\treturn HookFinish, pld, nil\n}"} {"input": "package build\n\n\n\nfunc init() ", "output": "{\n\tDuplicates[56787] = 54724\n}"} {"input": "package functools\n\n\nfunc All(bools ...bool) bool {\n\tfor _, b := range bools {\n\t\tif !b {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc Any(bools ...bool) bool {\n\tfor _, b := range bools {\n\t\tif b {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\nfunc None(bools ...bool) bool ", "output": "{\n\tfor _, b := range bools {\n\t\tif b {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package labelindex_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"github.com/onsi/ginkgo/reporters\"\n\n\t\"github.com/projectcalico/calico/libcalico-go/lib/testutils\"\n)\n\n\n\nfunc TestLabels(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tjunitReporter := reporters.NewJUnitReporter(\"../report/labels_suite.xml\")\n\tRunSpecsWithDefaultAndCustomReporters(t, \"Labels Suite\", []Reporter{junitReporter})\n}\n\nfunc init() ", "output": "{\n\ttestutils.HookLogrusForGinkgo()\n}"} {"input": "package dockertools\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\tdocker \"github.com/fsouza/go-dockerclient\"\n\tkubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\"\n\tkubetypes \"k8s.io/kubernetes/pkg/kubelet/types\"\n)\n\n\n\n\nfunc mapStatus(status string) kubecontainer.ContainerStatus {\n\tswitch {\n\tcase strings.HasPrefix(status, \"Up\"):\n\t\treturn kubecontainer.ContainerStatusRunning\n\tcase strings.HasPrefix(status, \"Exited\"):\n\t\treturn kubecontainer.ContainerStatusExited\n\tdefault:\n\t\treturn kubecontainer.ContainerStatusUnknown\n\t}\n}\n\n\n\n\n\nfunc toRuntimeImage(image *docker.APIImages) (*kubecontainer.Image, error) {\n\tif image == nil {\n\t\treturn nil, fmt.Errorf(\"unable to convert a nil pointer to a runtime image\")\n\t}\n\n\treturn &kubecontainer.Image{\n\t\tID: image.ID,\n\t\tTags: image.RepoTags,\n\t\tSize: image.VirtualSize,\n\t}, nil\n}\n\nfunc toRuntimeContainer(c *docker.APIContainers) (*kubecontainer.Container, error) ", "output": "{\n\tif c == nil {\n\t\treturn nil, fmt.Errorf(\"unable to convert a nil pointer to a runtime container\")\n\t}\n\n\tdockerName, hash, err := getDockerContainerNameInfo(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &kubecontainer.Container{\n\t\tID: kubetypes.DockerID(c.ID).ContainerID(),\n\t\tName: dockerName.ContainerName,\n\t\tImage: c.Image,\n\t\tHash: hash,\n\t\tCreated: c.Created,\n\t\tStatus: mapStatus(c.Status),\n\t}, nil\n}"} {"input": "package tests\n\nimport (\n log \"github.com/janekolszak/revfluent\"\n \"github.com/revel/revel/testing\"\n)\n\ntype AppTest struct {\n testing.TestSuite\n}\n\n\n\nfunc (t *AppTest) TestDebug() {\n data := map[string]string{\"message\": \"Debug\"}\n log.Debug(data)\n}\n\nfunc (t *AppTest) TestInfo() {\n data := map[string]string{\"message\": \"Info\"}\n log.Info(data)\n}\n\nfunc (t *AppTest) TestLog() {\n data := map[string]string{\"message\": \"Log\"}\n log.Log(\"tag\", data)\n}\n\nfunc (t *AppTest) TestLogger() {\n data := map[string]string{\"message\": \"Logger\"}\n log.Logger.Post(\"tag\", data)\n}\n\nfunc (t *AppTest) TestError() ", "output": "{\n data := map[string]string{\"message\": \"Error\"}\n log.Error(data)\n}"} {"input": "package popcount1_test\n\nimport (\n \"testing\"\n\n \"ch02/popcount\"\n \"ch02/popcount1\"\n)\n\nfunc BenchmarkPopCount(b *testing.B) {\n for i := 0; i < b.N; i++ {\n popcount.PopCount(0x1234567890ABCDEF)\n }\n}\n\n\n\nfunc BenchmarkPopCount1(b *testing.B) ", "output": "{\n for i := 0; i < b.N; i++ {\n popcount1.PopCount(0x1234567890ABCDEF)\n }\n}"} {"input": "package insights\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + version.Number + \" insights/2015-05-01\"\n}"} {"input": "package cloudfoundry_test\n\nimport (\n\t\"github.com/javiermanzano/goth\"\n\t\"github.com/javiermanzano/goth/providers/cloudfoundry\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc Test_New(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\tp := provider()\n\n\ta.Equal(p.ClientKey, os.Getenv(\"UAA_CLIENT_ID\"))\n\ta.Equal(p.Secret, os.Getenv(\"UAA_CLIENT_SECRET\"))\n\ta.Equal(p.CallbackURL, \"/foo\")\n}\n\nfunc Test_Implements_Provider(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\ta.Implements((*goth.Provider)(nil), provider())\n}\n\n\n\nfunc Test_SessionFromJSON(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\n\tp := provider()\n\tsession, err := p.UnmarshalSession(`{\"AuthURL\":\"https://cf.example.com/oauth/authorize\",\"AccessToken\":\"1234567890\"}`)\n\ta.NoError(err)\n\n\ts := session.(*cloudfoundry.Session)\n\ta.Equal(s.AuthURL, \"https://cf.example.com/oauth/authorize\")\n\ta.Equal(s.AccessToken, \"1234567890\")\n}\n\nfunc provider() *cloudfoundry.Provider {\n\treturn cloudfoundry.New(\"https://cf.example.com/\", os.Getenv(\"UAA_CLIENT_ID\"), os.Getenv(\"UAA_CLIENT_SECRET\"), \"/foo\")\n}\n\nfunc Test_BeginAuth(t *testing.T) ", "output": "{\n\tt.Parallel()\n\ta := assert.New(t)\n\tp := provider()\n\tsession, err := p.BeginAuth(\"test_state\")\n\ts := session.(*cloudfoundry.Session)\n\ta.NoError(err)\n\ta.Contains(s.AuthURL, \"https://cf.example.com/oauth/authorize\")\n}"} {"input": "package entity\n\nimport (\n\t\"context\"\n\n\t\"github.com/utahta/momoclo-channel/dao\"\n)\n\ntype (\n\tReminderRepository interface {\n\t\tFindAll(context.Context) ([]*Reminder, error)\n\t\tSave(context.Context, *Reminder) error\n\t}\n\n\treminderRepository struct {\n\t\tdao.PersistenceHandler\n\t}\n)\n\n\nfunc NewReminderRepository(h dao.PersistenceHandler) ReminderRepository {\n\treturn &reminderRepository{h}\n}\n\n\n\n\n\nfunc (repo *reminderRepository) Save(ctx context.Context, item *Reminder) error {\n\treturn repo.Put(ctx, item)\n}\n\nfunc (repo *reminderRepository) FindAll(ctx context.Context) ([]*Reminder, error) ", "output": "{\n\tkind := repo.Kind(ctx, &Reminder{})\n\tq := repo.NewQuery(kind).Filter(\"Enabled =\", true)\n\n\tvar dst []*Reminder\n\treturn dst, repo.GetAll(ctx, q, &dst)\n}"} {"input": "package gcetpmsigner\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/google/go-tpm/tpm2\"\n)\n\nvar tpmPath = \"/dev/tpm0\"\n\n\n\nfunc openTPM() (io.ReadWriteCloser, error) ", "output": "{\n\trw, err := tpm2.OpenTPM(tpmPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"tpm2.OpenTPM(%q): %w\", tpmPath, err)\n\t}\n\treturn rw, nil\n}"} {"input": "package logger\n\nimport \"context\"\n\ntype loggerKeyType struct{}\n\nvar loggerKey = loggerKeyType{}\n\n\nfunc NewContext(ctx context.Context, logger KayveeLogger) context.Context {\n\treturn context.WithValue(ctx, loggerKey, logger)\n}\n\n\n\n\n\n\n\n\nfunc FromContext(ctx context.Context) KayveeLogger ", "output": "{\n\tlogger := ctx.Value(loggerKey)\n\tif lggr, ok := logger.(KayveeLogger); ok {\n\t\treturn lggr\n\t}\n\treturn New(\"\")\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/apier/v1\"\n\t\"github.com/cgrates/cgrates/engine\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdGetDataCost{\n\t\tname: \"datacost\",\n\t\trpcMethod: \"ApierV1.GetDataCost\",\n\t\tclientArgs: []string{\"Direction\", \"Category\", \"Tenant\", \"Account\", \"Subject\", \"StartTime\", \"Usage\"},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetDataCost struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrGetDataCost\n\tclientArgs []string\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetDataCost) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdGetDataCost) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\n\n\nfunc (self *CmdGetDataCost) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetDataCost) RpcResult() interface{} {\n\treturn &engine.DataCost{}\n}\n\nfunc (self *CmdGetDataCost) ClientArgs() []string {\n\treturn self.clientArgs\n}\n\nfunc (self *CmdGetDataCost) RpcParams() interface{} ", "output": "{\n\tif self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrGetDataCost{Direction: utils.OUT}\n\t}\n\treturn self.rpcParams\n}"} {"input": "package treemap\n\nimport (\n\t\"github.com/emirpasic/gods/containers\"\n\trbt \"github.com/emirpasic/gods/trees/redblacktree\"\n)\n\nfunc assertIteratorImplementation() {\n\tvar _ containers.ReverseIteratorWithKey = (*Iterator)(nil)\n}\n\n\ntype Iterator struct {\n\titerator rbt.Iterator\n}\n\n\n\n\n\n\n\n\nfunc (iterator *Iterator) Next() bool {\n\treturn iterator.iterator.Next()\n}\n\n\n\n\nfunc (iterator *Iterator) Prev() bool {\n\treturn iterator.iterator.Prev()\n}\n\n\n\nfunc (iterator *Iterator) Value() interface{} {\n\treturn iterator.iterator.Value()\n}\n\n\n\nfunc (iterator *Iterator) Key() interface{} {\n\treturn iterator.iterator.Key()\n}\n\n\n\nfunc (iterator *Iterator) Begin() {\n\titerator.iterator.Begin()\n}\n\n\n\nfunc (iterator *Iterator) End() {\n\titerator.iterator.End()\n}\n\n\n\n\nfunc (iterator *Iterator) First() bool {\n\treturn iterator.iterator.First()\n}\n\n\n\n\nfunc (iterator *Iterator) Last() bool {\n\treturn iterator.iterator.Last()\n}\n\nfunc (m *Map) Iterator() Iterator ", "output": "{\n\treturn Iterator{iterator: m.tree.Iterator()}\n}"} {"input": "package netlink\n\nimport (\n\t\"fmt\"\n\t\"net\"\n)\n\n\ntype Rule struct {\n\tPriority int\n\tFamily int\n\tTable int\n\tMark int\n\tMask int\n\tTunID uint\n\tGoto int\n\tSrc *net.IPNet\n\tDst *net.IPNet\n\tFlow int\n\tIifName string\n\tOifName string\n\tSuppressIfgroup int\n\tSuppressPrefixlen int\n}\n\nfunc (r Rule) String() string {\n\treturn fmt.Sprintf(\"ip rule %d: from %s table %d\", r.Priority, r.Src, r.Table)\n}\n\n\n\n\nfunc NewRule() *Rule ", "output": "{\n\treturn &Rule{\n\t\tSuppressIfgroup: -1,\n\t\tSuppressPrefixlen: -1,\n\t\tPriority: -1,\n\t\tMark: -1,\n\t\tMask: -1,\n\t\tGoto: -1,\n\t\tFlow: -1,\n\t}\n}"} {"input": "package wire_test\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\n\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc newFixedWriter(max int) io.Writer ", "output": "{\n\tb := make([]byte, max, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}"} {"input": "package changes\n\nimport \"github.com/m3db/m3metrics/rules/view\"\n\n\ntype MappingRuleChange struct {\n\tOp Op `json:\"op\"`\n\tRuleID *string `json:\"ruleID,omitempty\"`\n\tRuleData *view.MappingRule `json:\"ruleData,omitempty\"`\n}\n\ntype mappingRuleChangesByOpAscNameAscIDAsc []MappingRuleChange\n\nfunc (a mappingRuleChangesByOpAscNameAscIDAsc) Len() int { return len(a) }\n\nfunc (a mappingRuleChangesByOpAscNameAscIDAsc) Less(i, j int) bool {\n\tif a[i].Op < a[j].Op {\n\t\treturn true\n\t}\n\tif a[i].Op > a[j].Op {\n\t\treturn false\n\t}\n\tif a[i].RuleData != nil && a[j].RuleData != nil {\n\t\treturn a[i].RuleData.Name < a[j].RuleData.Name\n\t}\n\tif a[i].RuleID != nil && a[j].RuleID != nil {\n\t\treturn *a[i].RuleID < *a[j].RuleID\n\t}\n\treturn false\n}\n\nfunc (a mappingRuleChangesByOpAscNameAscIDAsc) Swap(i, j int) ", "output": "{ a[i], a[j] = a[j], a[i] }"} {"input": "package cborl\n\ntype stateStack struct {\n\tstack []state \n\tstack0 [64]state\n\tcurrent state\n}\n\ntype lengthStack struct {\n\tstack []int64\n\tstack0 [32]int64\n\tcurrent int64\n}\n\nfunc (s *stateStack) init(s0 state) {\n\ts.current = s0\n\ts.stack = s.stack0[:0]\n}\n\n\n\nfunc (s *stateStack) pop() {\n\tif len(s.stack) == 0 {\n\t\ts.current = state{stFail, stStart}\n\t} else {\n\t\tlast := len(s.stack) - 1\n\t\ts.current = s.stack[last]\n\t\ts.stack = s.stack[:last]\n\t}\n}\n\nfunc (s *lengthStack) init() {\n\ts.stack = s.stack0[:0]\n}\n\nfunc (s *lengthStack) push(l int64) {\n\ts.stack = append(s.stack, s.current)\n\ts.current = l\n}\n\nfunc (s *lengthStack) pop() int64 {\n\tif len(s.stack) == 0 {\n\t\ts.current = -1\n\t\treturn -1\n\t} else {\n\t\tlast := len(s.stack) - 1\n\t\told := s.current\n\t\ts.current = s.stack[last]\n\t\ts.stack = s.stack[:last]\n\t\treturn old\n\t}\n}\n\nfunc (s *stateStack) push(next state) ", "output": "{\n\tif s.current.major != stFail {\n\t\ts.stack = append(s.stack, s.current)\n\t}\n\ts.current = next\n}"} {"input": "package after\n\nimport (\n\t\"strconv\"\n)\n\ntype order struct {\n\tpid productId\n\tcid customerId\n}\n\ntype productId struct {\n\tid int64\n}\n\n\n\ntype customerId struct {\n\tid int64\n}\n\n\n\ntype orderId struct {\n\tid int64\n}\n\n\n\n\n\nfunc CreateOrder(pid int64, cid int64) order {\n\treturn order{\n\t\tpid: productId{pid}, cid: customerId{cid},\n\t}\n}\n\nfunc (o order) Submit() (orderId, error) {\n\n\treturn orderId{int64(3252345234)}, nil\n}\n\nfunc (oid orderId) String() string ", "output": "{\n\treturn strconv.FormatInt(oid.id, 10)\n}"} {"input": "package model\n\ntype HealthStatus int\n\nconst (\n\tHealthOK HealthStatus = iota\n\tHealthWarning\n\tHealthError\n\tHealthUnknown\n)\n\ntype StatusDetails struct {\n\tOverallStatus HealthStatus `json:\"overall\"`\n\tSummaryMessages []StatusSummary `json:\"summary\"`\n\tMonitors []MonitorSummary `json:\"monitors\"`\n\tOSDs OSDSummary `json:\"osd\"`\n\tPGs PGSummary `json:\"pg\"`\n\tUsage UsageSummary `json:\"usage\"`\n}\n\ntype StatusSummary struct {\n\tStatus HealthStatus `json:\"status\"`\n\tMessage string `json:\"message\"`\n}\n\ntype MonitorSummary struct {\n\tName string `json:\"name\"`\n\tAddress string `json:\"address\"`\n\tInQuorum bool `json:\"inQuorum\"`\n\tStatus HealthStatus `json:\"status\"`\n}\n\ntype OSDSummary struct {\n\tTotal int `json:\"total\"`\n\tNumberIn int `json:\"numIn\"`\n\tNumberUp int `json:\"numUp\"`\n\tFull bool `json:\"full\"`\n\tNearFull bool `json:\"nearFull\"`\n}\n\ntype PGSummary struct {\n\tTotal int `json:\"total\"`\n\tStateCounts map[string]int `json:\"stateCount\"`\n}\n\ntype UsageSummary struct {\n\tDataBytes uint64 `json:\"data\"`\n\tUsedBytes uint64 `json:\"used\"`\n\tAvailableBytes uint64 `json:\"available\"`\n\tTotalBytes uint64 `json:\"total\"`\n}\n\n\n\nfunc HealthStatusToString(hs HealthStatus) string ", "output": "{\n\tswitch hs {\n\tcase HealthOK:\n\t\treturn \"OK\"\n\tcase HealthWarning:\n\t\treturn \"WARNING\"\n\tcase HealthError:\n\t\treturn \"ERROR\"\n\tdefault:\n\t\treturn \"UNKNOWN\"\n\t}\n}"} {"input": "package terraform\n\nimport \"net/http\"\n\n\ntype Release struct {\n\tHome string\n\tVersion string\n\tHTTPclient *http.Client\n\tHTTPResponse *http.Response\n}\n\ntype Path string\n\nconst (\n\tPathTerraform Path = \"https://releases.hashicorp.com/terraform/%s/terraform_%s_%s_%s.zip\"\n\tPathTerraformIndex Path = \"https://releases.hashicorp.com/terraform/\"\n\tPathBin Path = \"/.tfversion/bin/\"\n\tPathTmp Path = \"/.tfversion/tmp/\"\n)\n\n\n\nfunc (f Path) toString() string ", "output": "{\n\treturn string(f)\n}"} {"input": "package flags\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\ntype Traffic struct {\n\tRevisionsPercentages []string\n\tRevisionsTags []string\n\tUntagRevisions []string\n}\n\nfunc (t *Traffic) Add(cmd *cobra.Command) {\n\tcmd.Flags().StringSliceVar(&t.RevisionsPercentages,\n\t\t\"traffic\",\n\t\tnil,\n\t\t\"Set traffic distribution (format: --traffic revisionRef=percent) where revisionRef can be a revision or a tag or '@latest' string \"+\n\t\t\t\"representing latest ready revision. This flag can be given multiple times with percent summing up to 100%.\")\n\n\tcmd.Flags().StringSliceVar(&t.RevisionsTags,\n\t\t\"tag\",\n\t\tnil,\n\t\t\"Set tag (format: --tag revisionRef=tagName) where revisionRef can be a revision or '@latest' string representing latest ready revision. \"+\n\t\t\t\"This flag can be specified multiple times.\")\n\n\tcmd.Flags().StringSliceVar(&t.UntagRevisions,\n\t\t\"untag\",\n\t\tnil,\n\t\t\"Untag revision (format: --untag tagName). This flag can be specified multiple times.\")\n}\n\nfunc (t *Traffic) PercentagesChanged(cmd *cobra.Command) bool {\n\treturn cmd.Flags().Changed(\"traffic\")\n}\n\n\n\nfunc (t *Traffic) Changed(cmd *cobra.Command) bool {\n\treturn t.PercentagesChanged(cmd) || t.TagsChanged(cmd)\n}\n\nfunc (t *Traffic) TagsChanged(cmd *cobra.Command) bool ", "output": "{\n\treturn cmd.Flags().Changed(\"tag\") || cmd.Flags().Changed(\"untag\")\n}"} {"input": "package ifacetest\n\nimport (\n\t\"github.com/snapcore/snapd/interfaces\"\n\t\"github.com/snapcore/snapd/snap\"\n)\n\n\ntype Specification struct {\n\tSnippets []string\n}\n\n\nfunc (spec *Specification) AddSnippet(snippet string) {\n\tspec.Snippets = append(spec.Snippets, snippet)\n}\n\n\n\n\nfunc (spec *Specification) AddConnectedPlug(iface interfaces.Interface, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error {\n\ttype definer interface {\n\t\tTestConnectedPlug(spec *Specification, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestConnectedPlug(spec, plug, slot)\n\t}\n\treturn nil\n}\n\n\nfunc (spec *Specification) AddConnectedSlot(iface interfaces.Interface, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error {\n\ttype definer interface {\n\t\tTestConnectedSlot(spec *Specification, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestConnectedSlot(spec, plug, slot)\n\t}\n\treturn nil\n}\n\n\nfunc (spec *Specification) AddPermanentPlug(iface interfaces.Interface, plug *snap.PlugInfo) error {\n\ttype definer interface {\n\t\tTestPermanentPlug(spec *Specification, plug *snap.PlugInfo) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestPermanentPlug(spec, plug)\n\t}\n\treturn nil\n}\n\n\n\n\nfunc (spec *Specification) AddPermanentSlot(iface interfaces.Interface, slot *snap.SlotInfo) error ", "output": "{\n\ttype definer interface {\n\t\tTestPermanentSlot(spec *Specification, slot *snap.SlotInfo) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestPermanentSlot(spec, slot)\n\t}\n\treturn nil\n}"} {"input": "package iff\n\nimport (\n\t\"encoding/binary\"\n\t\"io\"\n)\n\ntype Writer struct {\n\tio.Writer\n}\n\ntype writeCallback func(w io.Writer)\n\nfunc NewWriter(w io.Writer, fileType []byte, fileSize uint32) *Writer {\n\tw.Write([]byte(\"FORM\"))\n\tbinary.Write(w, binary.BigEndian, fileSize)\n\tw.Write(fileType)\n\n\treturn &Writer{w}\n}\n\n\n\nfunc (w *Writer) WriteChunk(chunkID []byte, chunkSize uint32, cb writeCallback) (err error) ", "output": "{\n\t_, err = w.Write(chunkID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = binary.Write(w, binary.BigEndian, chunkSize)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcb(w)\n\n\treturn\n}"} {"input": "package schedule\n\nimport (\n\t\"testing\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\nfunc TestFIFOSchedule(t *testing.T) ", "output": "{\n\ts := NewFIFOScheduler()\n\tdefer s.Stop()\n\n\tnext := 0\n\tjobCreator := func(i int) Job {\n\t\treturn func(ctx context.Context) {\n\t\t\tif next != i {\n\t\t\t\tt.Fatalf(\"job#%d: got %d, want %d\", i, next, i)\n\t\t\t}\n\t\t\tnext = i + 1\n\t\t}\n\t}\n\n\tvar jobs []Job\n\tfor i := 0; i < 100; i++ {\n\t\tjobs = append(jobs, jobCreator(i))\n\t}\n\n\tfor _, j := range jobs {\n\t\ts.Schedule(j)\n\t}\n\n\ts.WaitFinish(100)\n\tif s.Scheduled() != 100 {\n\t\tt.Errorf(\"scheduled = %d, want %d\", s.Scheduled(), 100)\n\t}\n}"} {"input": "package model\n\n\n\ntype ResourceAssignment struct {\n\t*Record\n}\n\n\n\n\nfunc (ra *ResourceAssignment) MappedPartitions() []string {\n\treturn nil\n}\n\n\n\nfunc (ra *ResourceAssignment) ReplicaMap(partition string) map[string]string {\n\treturn nil\n}\n\nfunc (ra *ResourceAssignment) Resource() string ", "output": "{\n\treturn ra.ID\n}"} {"input": "package uhost\n\nimport (\n\t\"github.com/ucloud/ucloud-sdk-go/ucloud/request\"\n\t\"github.com/ucloud/ucloud-sdk-go/ucloud/response\"\n)\n\n\ntype ModifyUHostInstanceNameRequest struct {\n\trequest.CommonBase\n\n\n\n\n\tUHostId *string `required:\"true\"`\n\n\tName *string `required:\"false\"`\n}\n\n\ntype ModifyUHostInstanceNameResponse struct {\n\tresponse.CommonBase\n\n\tUhostId string\n}\n\n\n\n\n\nfunc (c *UHostClient) ModifyUHostInstanceName(req *ModifyUHostInstanceNameRequest) (*ModifyUHostInstanceNameResponse, error) {\n\tvar err error\n\tvar res ModifyUHostInstanceNameResponse\n\n\terr = c.Client.InvokeAction(\"ModifyUHostInstanceName\", req, &res)\n\tif err != nil {\n\t\treturn &res, err\n\t}\n\n\treturn &res, nil\n}\n\nfunc (c *UHostClient) NewModifyUHostInstanceNameRequest() *ModifyUHostInstanceNameRequest ", "output": "{\n\treq := &ModifyUHostInstanceNameRequest{}\n\n\tc.Client.SetupRequest(req)\n\n\treq.SetRetryable(true)\n\treturn req\n}"} {"input": "package jsonfile\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestInvalidJSONFile(t *testing.T) {\n\tprovider := New(\"./invalid\")\n\t_, err := provider.Hosts()\n\tassert.Error(t, err, \"open /invalid: no such file or directory\", \"should fail to open file\")\n}\n\nfunc TestMalformedJSONFile(t *testing.T) {\n\tprovider := New(\"../test/invalidhosts.json\")\n\t_, err := provider.Hosts()\n\tassert.Error(t, err, \"invalid character 'T' looking for beginning of value\", \"should fail to unmarhsal JSON\")\n}\n\n\n\nfunc TestNiceJSONFile(t *testing.T) ", "output": "{\n\tcontent := []byte(\"[\\\"127.0.0.1:3000\\\", \\\"127.0.0.1:3042\\\"]\")\n\n\ttmpfile, err := ioutil.TempFile(\"\", \"jsonfiletest\")\n\tassert.NoError(t, err, \"failed to create a temp file\")\n\tdefer os.Remove(tmpfile.Name())\n\n\t_, err = tmpfile.Write(content)\n\tassert.NoError(t, err, \"failed to write contents to the temp file\")\n\n\terr = tmpfile.Close()\n\tassert.NoError(t, err, \"failed to write contents to the temp file\")\n\n\tprovider := New(tmpfile.Name())\n\tres, err := provider.Hosts()\n\tassert.NoError(t, err, \"hosts call failed\")\n\tassert.Equal(t, []string{\"127.0.0.1:3000\", \"127.0.0.1:3042\"}, res)\n}"} {"input": "package account\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/v10.0.2-beta arm-account/2016-11-01\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn \"v10.0.2-beta\"\n}"} {"input": "package sender\n\nimport (\n\t\"github.com/open-falcon/transfer/g\"\n\tcpool \"github.com/open-falcon/transfer/sender/conn_pool\"\n\tnset \"github.com/toolkits/container/set\"\n)\n\nfunc initConnPools() {\n\tcfg := g.Config()\n\n\tjudgeInstances := nset.NewStringSet()\n\tfor _, instance := range cfg.Judge.Cluster {\n\t\tjudgeInstances.Add(instance)\n\t}\n\tJudgeConnPools = cpool.CreateSafeRpcConnPools(cfg.Judge.MaxConns, cfg.Judge.MaxIdle,\n\t\tcfg.Judge.ConnTimeout, cfg.Judge.CallTimeout, judgeInstances.ToSlice())\n\n\tif cfg.Tsdb.Enabled {\n\t\tTsdbConnPoolHelper = cpool.NewTsdbConnPoolHelper(cfg.Tsdb.Address, cfg.Tsdb.MaxConns, cfg.Tsdb.MaxIdle, cfg.Tsdb.ConnTimeout, cfg.Tsdb.CallTimeout)\n\t}\n\n\tgraphInstances := nset.NewSafeSet()\n\tfor _, nitem := range cfg.Graph.ClusterList {\n\t\tfor _, addr := range nitem.Addrs {\n\t\t\tgraphInstances.Add(addr)\n\t\t}\n\t}\n\tGraphConnPools = cpool.CreateSafeRpcConnPools(cfg.Graph.MaxConns, cfg.Graph.MaxIdle,\n\t\tcfg.Graph.ConnTimeout, cfg.Graph.CallTimeout, graphInstances.ToSlice())\n\n}\n\n\n\nfunc DestroyConnPools() ", "output": "{\n\tJudgeConnPools.Destroy()\n\tGraphConnPools.Destroy()\n\tTsdbConnPoolHelper.Destroy()\n}"} {"input": "package triegen\n\n\n\nimport \"io\"\n\n\n\n\n\ntype Compacter interface {\n\tSize(v []uint64) (sz int, ok bool)\n\n\tStore(v []uint64) uint32\n\n\tPrint(w io.Writer) error\n\n\tHandler() string\n}\n\n\n\ntype simpleCompacter builder\n\nfunc (b *simpleCompacter) Size([]uint64) (sz int, ok bool) {\n\treturn blockSize * b.ValueSize, true\n}\n\nfunc (b *simpleCompacter) Store(v []uint64) uint32 {\n\th := uint32(len(b.ValueBlocks) - blockOffset)\n\tb.ValueBlocks = append(b.ValueBlocks, v)\n\treturn h\n}\n\n\n\nfunc (b *simpleCompacter) Handler() string {\n\tpanic(\"Handler should be special-cased for this Compacter\")\n}\n\nfunc (b *simpleCompacter) Print(io.Writer) error ", "output": "{\n\treturn nil\n}"} {"input": "package iso20022\n\n\ntype Statement8 struct {\n\n\tReference *Max35Text `xml:\"Ref\"`\n\n\tStatementPeriod *DatePeriodDetails `xml:\"StmtPrd\"`\n\n\tCreationDateTime *DateAndDateTimeChoice `xml:\"CreDtTm,omitempty\"`\n\n\tFrequency *EventFrequency1Code `xml:\"Frqcy,omitempty\"`\n\n\tUpdateType *StatementUpdateTypeCode `xml:\"UpdTp\"`\n\n\tActivityIndicator *YesNoIndicator `xml:\"ActvtyInd\"`\n\n\tReportNumber *Max5NumericText `xml:\"RptNb,omitempty\"`\n}\n\nfunc (s *Statement8) SetReference(value string) {\n\ts.Reference = (*Max35Text)(&value)\n}\n\nfunc (s *Statement8) AddStatementPeriod() *DatePeriodDetails {\n\ts.StatementPeriod = new(DatePeriodDetails)\n\treturn s.StatementPeriod\n}\n\n\n\nfunc (s *Statement8) SetFrequency(value string) {\n\ts.Frequency = (*EventFrequency1Code)(&value)\n}\n\nfunc (s *Statement8) SetUpdateType(value string) {\n\ts.UpdateType = (*StatementUpdateTypeCode)(&value)\n}\n\nfunc (s *Statement8) SetActivityIndicator(value string) {\n\ts.ActivityIndicator = (*YesNoIndicator)(&value)\n}\n\nfunc (s *Statement8) SetReportNumber(value string) {\n\ts.ReportNumber = (*Max5NumericText)(&value)\n}\n\nfunc (s *Statement8) AddCreationDateTime() *DateAndDateTimeChoice ", "output": "{\n\ts.CreationDateTime = new(DateAndDateTimeChoice)\n\treturn s.CreationDateTime\n}"} {"input": "package commands\n\nimport \"github.com/spf13/cobra\"\n\n\n\ntype Command struct {\n\t*cobra.Command\n\n\tDocCategories []string\n\n\tfmtCols []string\n\n\tchildCommands []*Command\n\tIsIndex bool\n}\n\n\nfunc (c *Command) AddCommand(commands ...*Command) {\n\tc.childCommands = append(c.childCommands, commands...)\n\tfor _, cmd := range commands {\n\t\tc.Command.AddCommand(cmd.Command)\n\t}\n}\n\n\n\n\nfunc (c *Command) ChildCommands() []*Command ", "output": "{\n\treturn c.childCommands\n}"} {"input": "package verboten\n\nimport (\n\t\"github.com/reiver/gogen-optiontype/driver\"\n\t\"github.com/reiver/gogen-optiontype/drivers/shared\"\n)\n\n\n\n\nfunc init() ", "output": "{\n\tconst typeName = \"string\"\n\tconst fileName = \"gen_type_gostring_test.go\"\n\n\trenderer := gendriver.DefaultRenderer{\n\t\tFileName: fileName,\n\t\tFileTmpl: shared.TypeGoStringStringTestTmpl,\n\t}\n\n\n\tif err := gendriver.Registry.Register(typeName, true, renderer); nil != err {\n\t\tpanic(err)\n\t}\n}"} {"input": "package render\n\n\ntype Data map[string]interface{}\n\n\nfunc NewData() *Data {\n\treturn &Data{}\n}\n\n\nfunc (d *Data) Set(key string, data interface{}) {\n\tif *d == nil {\n\t\tdata := Data(map[string]interface{}{})\n\t\t*d = data\n\t}\n\t(*d)[key] = data\n}\n\n\nfunc (d *Data) Del(key string) {\n\tif *d == nil {\n\t\treturn\n\t}\n\tdelete(*d, key)\n}\n\n\n\n\n\nfunc (d *Data) Merge(data *Data) {\n\tif *d == nil {\n\t\tdata := Data(map[string]interface{}{})\n\t\t*d = data\n\t}\n\tif data == nil || *data == nil {\n\t\treturn\n\t}\n\tfor k, v := range *data {\n\t\td.Set(k, v)\n\t}\n}\n\nfunc (d *Data) Get(key string) interface{} ", "output": "{\n\tif *d == nil {\n\t\treturn nil\n\t}\n\tdata, ok := (*d)[key]\n\tif ok == false {\n\t\treturn nil\n\t}\n\treturn data\n}"} {"input": "package db\n\nimport (\n\t\"gopkg.in/mgo.v2\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Session struct {\n\tS *mgo.Session\n\tDb *mgo.Database\n\tC *mgo.Collection\n}\n\n\ntype MongoClient struct {\n\tHosts string\n\tDatabase string\n\tCollection string\n\tSession\n}\n\nfunc (m *MongoClient) Connect() error {\n\tdailinfo := &mgo.DialInfo{\n\t\tAddrs: strings.Split(m.Hosts, \",\"),\n\t\tTimeout: 5 * time.Second,\n\t\tDatabase: m.Database,\n\t}\n\tsession, err := mgo.DialWithInfo(dailinfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.S = session\n\tm.S.SetMode(mgo.Monotonic, true)\n\treturn nil\n}\n\nfunc (m *MongoClient) DB() {\n\tdb := m.Session.S.DB(m.Database)\n\tm.Session.Db = db\n}\n\nfunc (m *MongoClient) C() {\n\tc := m.Session.Db.C(m.Collection)\n\tm.Session.C = c\n}\n\n\n\nfunc (m *MongoClient) GetCollection() *mgo.Collection {\n\treturn m.Session.C\n}\n\nfunc (m *MongoClient) Close() ", "output": "{\n\tif m.S != nil {\n\t\tm.S.LogoutAll()\n\t\tm.S.Close()\n\t}\n}"} {"input": "package leetcode\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc Test_hammingDistance(t *testing.T) ", "output": "{\n\tn := hammingDistance(1, 4)\n\tif n != 2 {\n\t\tt.Error(n, 2)\n\t}\n}"} {"input": "package testhelpers\n\nimport \"github.com/go-kit/kit/metrics\"\n\n\ntype CollectingCounter struct {\n\tCounterValue float64\n\tLastLabelValues []string\n}\n\n\n\n\n\nfunc (c *CollectingCounter) Add(delta float64) {\n\tc.CounterValue += delta\n}\n\n\ntype CollectingGauge struct {\n\tGaugeValue float64\n\tLastLabelValues []string\n}\n\n\nfunc (g *CollectingGauge) With(labelValues ...string) metrics.Gauge {\n\tg.LastLabelValues = labelValues\n\treturn g\n}\n\n\nfunc (g *CollectingGauge) Set(value float64) {\n\tg.GaugeValue = value\n}\n\n\nfunc (g *CollectingGauge) Add(delta float64) {\n\tg.GaugeValue = delta\n}\n\n\ntype CollectingHealthCheckMetrics struct {\n\tGauge *CollectingGauge\n}\n\n\nfunc (m *CollectingHealthCheckMetrics) BackendServerUpGauge() metrics.Gauge {\n\treturn m.Gauge\n}\n\n\nfunc NewCollectingHealthCheckMetrics() *CollectingHealthCheckMetrics {\n\treturn &CollectingHealthCheckMetrics{&CollectingGauge{}}\n}\n\nfunc (c *CollectingCounter) With(labelValues ...string) metrics.Counter ", "output": "{\n\tc.LastLabelValues = labelValues\n\treturn c\n}"} {"input": "package output\n\nimport \"reflect\"\n\n\ntype S3Grantee struct {\n\tID string `json:\"id\"`\n\tType string `json:\"type\"`\n\tPermissions string `json:\"permissions\"`\n}\n\n\ntype S3 struct {\n\tProviderType string `json:\"_type\"`\n\tDatacenterName string `json:\"datacenter_name,omitempty\"`\n\tDatacenterRegion string `json:\"datacenter_region\"`\n\tAccessKeyID string `json:\"aws_access_key_id\"`\n\tSecretAccessKey string `json:\"aws_secret_access_key\"`\n\tName string `json:\"name\"`\n\tACL string `json:\"acl\"`\n\tBucketLocation string `json:\"bucket_location\"`\n\tBucketURI string `json:\"bucket_uri\"`\n\tGrantees []S3Grantee `json:\"grantees,omitempty\"`\n\tTags map[string]string `json:\"tags\"`\n\tService string `json:\"service\"`\n\tStatus string `json:\"status\"`\n\tExists bool\n}\n\n\nfunc (s *S3) HasChanged(os *S3) bool {\n\tif s.ACL != os.ACL {\n\t\treturn true\n\t}\n\n\tif len(s.Grantees) < 1 && len(os.Grantees) < 1 {\n\t\treturn false\n\t}\n\n\treturn !reflect.DeepEqual(s.Grantees, os.Grantees)\n}\n\n\nfunc (s S3) GetTags() map[string]string {\n\treturn s.Tags\n}\n\n\n\n\n\nfunc (s S3) ComponentName() string {\n\treturn s.Name\n}\n\nfunc (s S3) ProviderID() string ", "output": "{\n\treturn s.Name\n}"} {"input": "package stats_test\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t. \"v2ray.com/core/app/stats\"\n\t\"v2ray.com/core/common\"\n\t\"v2ray.com/core/features/stats\"\n)\n\n\n\nfunc TestStatsCounter(t *testing.T) {\n\traw, err := common.CreateObject(context.Background(), &Config{})\n\tcommon.Must(err)\n\n\tm := raw.(stats.Manager)\n\tc, err := m.RegisterCounter(\"test.counter\")\n\tcommon.Must(err)\n\n\tif v := c.Add(1); v != 1 {\n\t\tt.Fatal(\"unpexcted Add(1) return: \", v, \", wanted \", 1)\n\t}\n\n\tif v := c.Set(0); v != 1 {\n\t\tt.Fatal(\"unexpected Set(0) return: \", v, \", wanted \", 1)\n\t}\n\n\tif v := c.Value(); v != 0 {\n\t\tt.Fatal(\"unexpected Value() return: \", v, \", wanted \", 0)\n\t}\n}\n\nfunc TestInternface(t *testing.T) ", "output": "{\n\t_ = (stats.Manager)(new(Manager))\n}"} {"input": "package ethash\n\nimport (\n\t\"encoding/json\"\n\t\"math/big\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/xenioplatform/go-xenio/common/math\"\n\t\"github.com/xenioplatform/go-xenio/core/types\"\n\t\"github.com/xenioplatform/go-xenio/params\"\n)\n\ntype diffTest struct {\n\tParentTimestamp uint64\n\tParentDifficulty *big.Int\n\tCurrentTimestamp uint64\n\tCurrentBlocknumber *big.Int\n\tCurrentDifficulty *big.Int\n}\n\n\n\nfunc TestCalcDifficulty(t *testing.T) {\n\tfile, err := os.Open(filepath.Join(\"..\", \"..\", \"tests\", \"testdata\", \"BasicTests\", \"difficulty.json\"))\n\tif err != nil {\n\t\tt.Skip(err)\n\t}\n\tdefer file.Close()\n\n\ttests := make(map[string]diffTest)\n\terr = json.NewDecoder(file).Decode(&tests)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tconfig := ¶ms.ChainConfig{HomesteadBlock: big.NewInt(1150000)}\n\tfor name, test := range tests {\n\t\tnumber := new(big.Int).Sub(test.CurrentBlocknumber, big.NewInt(1))\n\t\tdiff := CalcDifficulty(config, test.CurrentTimestamp, &types.Header{\n\t\t\tNumber: number,\n\t\t\tTime: new(big.Int).SetUint64(test.ParentTimestamp),\n\t\t\tDifficulty: test.ParentDifficulty,\n\t\t})\n\t\tif diff.Cmp(test.CurrentDifficulty) != 0 {\n\t\t\tt.Error(name, \"failed. Expected\", test.CurrentDifficulty, \"and calculated\", diff)\n\t\t}\n\t}\n}\n\nfunc (d *diffTest) UnmarshalJSON(b []byte) (err error) ", "output": "{\n\tvar ext struct {\n\t\tParentTimestamp string\n\t\tParentDifficulty string\n\t\tCurrentTimestamp string\n\t\tCurrentBlocknumber string\n\t\tCurrentDifficulty string\n\t}\n\tif err := json.Unmarshal(b, &ext); err != nil {\n\t\treturn err\n\t}\n\n\td.ParentTimestamp = math.MustParseUint64(ext.ParentTimestamp)\n\td.ParentDifficulty = math.MustParseBig256(ext.ParentDifficulty)\n\td.CurrentTimestamp = math.MustParseUint64(ext.CurrentTimestamp)\n\td.CurrentBlocknumber = math.MustParseBig256(ext.CurrentBlocknumber)\n\td.CurrentDifficulty = math.MustParseBig256(ext.CurrentDifficulty)\n\n\treturn nil\n}"} {"input": "package vm\n\nimport (\n\t\"github.com/expanse-org/go-expanse/common\"\n\t\"github.com/expanse-org/go-expanse/common/math\"\n\t\"github.com/holiman/uint256\"\n)\n\n\n\nfunc calcMemSize64(off, l *uint256.Int) (uint64, bool) {\n\tif !l.IsUint64() {\n\t\treturn 0, true\n\t}\n\treturn calcMemSize64WithUint(off, l.Uint64())\n}\n\n\n\n\nfunc calcMemSize64WithUint(off *uint256.Int, length64 uint64) (uint64, bool) {\n\tif length64 == 0 {\n\t\treturn 0, false\n\t}\n\toffset64, overflow := off.Uint64WithOverflow()\n\tif overflow {\n\t\treturn 0, true\n\t}\n\tval := offset64 + length64\n\treturn val, val < offset64\n}\n\n\n\nfunc getData(data []byte, start uint64, size uint64) []byte {\n\tlength := uint64(len(data))\n\tif start > length {\n\t\tstart = length\n\t}\n\tend := start + size\n\tif end > length {\n\t\tend = length\n\t}\n\treturn common.RightPadBytes(data[start:end], int(size))\n}\n\n\n\n\nfunc allZero(b []byte) bool {\n\tfor _, byte := range b {\n\t\tif byte != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc toWordSize(size uint64) uint64 ", "output": "{\n\tif size > math.MaxUint64-31 {\n\t\treturn math.MaxUint64/32 + 1\n\t}\n\n\treturn (size + 31) / 32\n}"} {"input": "package framework\n\ntype HorizontalAlignment int\n\nconst (\n\tAlignLeft HorizontalAlignment = iota\n\tAlignCenter\n\tAlignRight\n)\n\nfunc (a HorizontalAlignment) AlignLeft() bool { return a == AlignLeft }\nfunc (a HorizontalAlignment) AlignCenter() bool { return a == AlignCenter }\n\n\ntype VerticalAlignment int\n\nconst (\n\tAlignTop VerticalAlignment = iota\n\tAlignMiddle\n\tAlignBottom\n)\n\nfunc (a VerticalAlignment) AlignTop() bool { return a == AlignTop }\nfunc (a VerticalAlignment) AlignMiddle() bool { return a == AlignMiddle }\nfunc (a VerticalAlignment) AlignBottom() bool { return a == AlignBottom }\n\nfunc (a HorizontalAlignment) AlignRight() bool ", "output": "{ return a == AlignRight }"} {"input": "package http\n\nimport (\n\t\"go-common/app/admin/main/tv/model\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\nfunc mangoList(c *bm.Context) {\n\tc.JSON(tvSrv.MangoList(c))\n}\n\n\n\nfunc mangoEdit(c *bm.Context) {\n\tparam := new(model.ReqMangoEdit)\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(nil, tvSrv.MangoEdit(c, param))\n}\n\nfunc mangoDel(c *bm.Context) {\n\tparam := new(struct {\n\t\tID int64 `form:\"id\" validate:\"required,min=1,gt=0\"`\n\t})\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(nil, tvSrv.MangoDel(c, param.ID))\n}\n\nfunc mangoPub(c *bm.Context) {\n\tparam := new(struct {\n\t\tIDs []int64 `form:\"ids,split\" validate:\"required,min=1,dive,gt=0\"`\n\t})\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(nil, tvSrv.MangoPub(c, param.IDs))\n}\n\nfunc mangoAdd(c *bm.Context) ", "output": "{\n\tparam := new(struct {\n\t\tIDs []int64 `form:\"rids,split\" validate:\"required,min=1,dive,gt=0\"`\n\t\tRType int `form:\"rtype\" validate:\"required,min=1,max=2\"` \n\t})\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(tvSrv.MangoAdd(c, param.RType, param.IDs))\n}"} {"input": "package db\n\nimport (\n\t\"gopkg.in/mgo.v2\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Session struct {\n\tS *mgo.Session\n\tDb *mgo.Database\n\tC *mgo.Collection\n}\n\n\ntype MongoClient struct {\n\tHosts string\n\tDatabase string\n\tCollection string\n\tSession\n}\n\n\n\nfunc (m *MongoClient) DB() {\n\tdb := m.Session.S.DB(m.Database)\n\tm.Session.Db = db\n}\n\nfunc (m *MongoClient) C() {\n\tc := m.Session.Db.C(m.Collection)\n\tm.Session.C = c\n}\n\nfunc (m *MongoClient) Close() {\n\tif m.S != nil {\n\t\tm.S.LogoutAll()\n\t\tm.S.Close()\n\t}\n}\n\nfunc (m *MongoClient) GetCollection() *mgo.Collection {\n\treturn m.Session.C\n}\n\nfunc (m *MongoClient) Connect() error ", "output": "{\n\tdailinfo := &mgo.DialInfo{\n\t\tAddrs: strings.Split(m.Hosts, \",\"),\n\t\tTimeout: 5 * time.Second,\n\t\tDatabase: m.Database,\n\t}\n\tsession, err := mgo.DialWithInfo(dailinfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.S = session\n\tm.S.SetMode(mgo.Monotonic, true)\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/ChuckHa/grout\"\n\t\"net/http\"\n)\n\ntype Blog struct {\n}\n\nfunc (b *Blog) PostById(id string) string {\n\treturn \"a blog post\"\n}\n\n\n\nfunc blogsHandler(w http.ResponseWriter, r *http.Request, data map[string]string) {\n\ttheBlog := BlogByName(data[\"name\"])\n\tpost := theBlog.PostById(data[\"othername\"])\n\tfmt.Fprintf(w, post)\n}\n\nfunc main() {\n\tmux := grout.NewRouteMux()\n\tmux.Route(`/blogs/(?P[a-z][a-z_-]+[a-z])/(?P[0-9]+)`, blogsHandler)\n\tfmt.Println(\"Listening on port 8080\")\n\thttp.ListenAndServe(\":8080\", mux)\n}\n\nfunc BlogByName(name string) *Blog ", "output": "{\n\treturn &Blog{}\n}"} {"input": "package client\n\nimport (\n\t\"strings\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\n\n\nfunc CheckDuplicates(models []Model) error ", "output": "{\n\tresMap := make(map[ModelType]map[string][]string)\n\n\tfor _, r := range models {\n\t\tresType := r.Type()\n\t\tname := r.Meta().Name\n\n\t\tif resMap[resType] == nil {\n\t\t\tresMap[resType] = make(map[string][]string)\n\t\t}\n\t\tif resMap[resType][name] == nil {\n\t\t\tresMap[resType][name] = []string{}\n\t\t}\n\t\tresMap[resType][name] = append(resMap[resType][name], r.File())\n\t}\n\n\tfor resType, names := range resMap {\n\t\tfor name, files := range names {\n\t\t\tif len(files) > 1 {\n\t\t\t\treturn errors.Errorf(\"duplicate %s definitions for %s:\\n- %s\", resType, name, strings.Join(files, \"\\n- \"))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package database\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/base64\"\n\n\t\"github.com/garyburd/redigo/redis\"\n\n\t\"bosun.org/slog\"\n)\n\ntype ConfigDataAccess interface {\n\tSaveTempConfig(text string) (hash string, err error)\n\tGetTempConfig(hash string) (text string, err error)\n}\n\nfunc (d *dataAccess) Configs() ConfigDataAccess {\n\treturn d\n}\n\nconst configLifetime = 60 * 24 * 14 \n\n\n\nfunc (d *dataAccess) GetTempConfig(hash string) (string, error) {\n\tconn := d.Get()\n\tdefer conn.Close()\n\n\tkey := \"tempConfig:\" + hash\n\tdat, err := redis.String(conn.Do(\"GET\", key))\n\tif err != nil {\n\t\treturn \"\", slog.Wrap(err)\n\t}\n\t_, err = conn.Do(\"EXPIRE\", key, configLifetime)\n\treturn dat, slog.Wrap(err)\n}\n\nfunc (d *dataAccess) SaveTempConfig(text string) (string, error) ", "output": "{\n\tconn := d.Get()\n\tdefer conn.Close()\n\n\tsig := md5.Sum([]byte(text))\n\tb64 := base64.StdEncoding.EncodeToString(sig[0:8])\n\tif d.isRedis {\n\t\t_, err := conn.Do(\"SET\", \"tempConfig:\"+b64, text, \"EX\", configLifetime)\n\t\treturn b64, slog.Wrap(err)\n\t}\n\t_, err := conn.Do(\"SETEX\", \"tempConfig:\"+b64, configLifetime, text)\n\treturn b64, slog.Wrap(err)\n}"} {"input": "package iso20022\n\n\ntype Statement8 struct {\n\n\tReference *Max35Text `xml:\"Ref\"`\n\n\tStatementPeriod *DatePeriodDetails `xml:\"StmtPrd\"`\n\n\tCreationDateTime *DateAndDateTimeChoice `xml:\"CreDtTm,omitempty\"`\n\n\tFrequency *EventFrequency1Code `xml:\"Frqcy,omitempty\"`\n\n\tUpdateType *StatementUpdateTypeCode `xml:\"UpdTp\"`\n\n\tActivityIndicator *YesNoIndicator `xml:\"ActvtyInd\"`\n\n\tReportNumber *Max5NumericText `xml:\"RptNb,omitempty\"`\n}\n\n\n\nfunc (s *Statement8) AddStatementPeriod() *DatePeriodDetails {\n\ts.StatementPeriod = new(DatePeriodDetails)\n\treturn s.StatementPeriod\n}\n\nfunc (s *Statement8) AddCreationDateTime() *DateAndDateTimeChoice {\n\ts.CreationDateTime = new(DateAndDateTimeChoice)\n\treturn s.CreationDateTime\n}\n\nfunc (s *Statement8) SetFrequency(value string) {\n\ts.Frequency = (*EventFrequency1Code)(&value)\n}\n\nfunc (s *Statement8) SetUpdateType(value string) {\n\ts.UpdateType = (*StatementUpdateTypeCode)(&value)\n}\n\nfunc (s *Statement8) SetActivityIndicator(value string) {\n\ts.ActivityIndicator = (*YesNoIndicator)(&value)\n}\n\nfunc (s *Statement8) SetReportNumber(value string) {\n\ts.ReportNumber = (*Max5NumericText)(&value)\n}\n\nfunc (s *Statement8) SetReference(value string) ", "output": "{\n\ts.Reference = (*Max35Text)(&value)\n}"} {"input": "package characteristic\n\nimport (\n\t\"github.com/brutella/hc/model\"\n)\n\ntype HeatingCoolingMode struct {\n\t*ByteCharacteristic\n}\n\n\n\nfunc NewCurrentHeatingCoolingMode(current model.HeatCoolModeType) *HeatingCoolingMode {\n\treturn NewHeatingCoolingMode(current, CharTypeHeatingCoolingModeCurrent, PermsRead())\n}\n\nfunc NewTargetHeatingCoolingMode(current model.HeatCoolModeType) *HeatingCoolingMode {\n\treturn NewHeatingCoolingMode(current, CharTypeHeatingCoolingModeTarget, PermsAll())\n}\n\nfunc (c *HeatingCoolingMode) SetHeatingCoolingMode(mode model.HeatCoolModeType) {\n\tc.SetByte(byte(mode))\n}\n\nfunc (c *HeatingCoolingMode) HeatingCoolingMode() model.HeatCoolModeType {\n\treturn model.HeatCoolModeType(c.Byte())\n}\n\nfunc NewHeatingCoolingMode(current model.HeatCoolModeType, charType CharType, permissions []string) *HeatingCoolingMode ", "output": "{\n\tc := HeatingCoolingMode{NewByteCharacteristic(byte(current), permissions)}\n\tc.Type = charType\n\n\treturn &c\n}"} {"input": "package utils\n\nimport (\n \"unsafe\"\n \"reflect\"\n)\n\n\nfunc ByteString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}\n\n\n\n\n\nfunc BytePointer(b []byte) unsafe.Pointer {\n\tp := (*reflect.SliceHeader)(unsafe.Pointer(&b))\n\treturn unsafe.Pointer(p.Data)\n}\n\nfunc StringPointer(s string) unsafe.Pointer ", "output": "{\n\tp := (*reflect.StringHeader)(unsafe.Pointer(&s))\n\treturn unsafe.Pointer(p.Data)\n}"} {"input": "package budget\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteBudgetRequest struct {\n\n\tBudgetId *string `mandatory:\"true\" contributesTo:\"path\" name:\"budgetId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteBudgetRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteBudgetRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request DeleteBudgetRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteBudgetResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteBudgetResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteBudgetResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteBudgetRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package service\n\nimport (\n\tgofig \"github.com/akutz/gofig/types\"\n\n\t\"github.com/thecodeteam/rexray/libstorage/api/registry\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/server/handlers\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/server/httputils\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/types\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/utils/schema\"\n)\n\nfunc init() {\n\tregistry.RegisterRouter(&router{})\n}\n\ntype router struct {\n\troutes []types.Route\n}\n\nfunc (r *router) Name() string {\n\treturn \"service-router\"\n}\n\nfunc (r *router) Init(config gofig.Config) {\n\tr.initRoutes()\n}\n\n\n\n\nfunc (r *router) initRoutes() {\n\n\tr.routes = []types.Route{\n\n\t\thttputils.NewGetRoute(\n\t\t\t\"services\",\n\t\t\t\"/services\",\n\t\t\tr.servicesList,\n\t\t\thandlers.NewAuthAllSvcsHandler(),\n\t\t\thandlers.NewSchemaValidator(nil, schema.ServiceInfoMapSchema, nil)),\n\n\t\thttputils.NewGetRoute(\n\t\t\t\"serviceInspect\",\n\t\t\t\"/services/{service}\",\n\t\t\tr.serviceInspect,\n\t\t\thandlers.NewServiceValidator(),\n\t\t\thandlers.NewAuthSvcHandler(),\n\t\t\thandlers.NewSchemaValidator(nil, schema.ServiceInfoSchema, nil)),\n\t}\n}\n\nfunc (r *router) Routes() []types.Route ", "output": "{\n\treturn r.routes\n}"} {"input": "package command\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/hashicorp/serf/serf\"\n\t\"github.com/mitchellh/cli\"\n)\n\n\ntype VersionCommand struct {\n\tRevision string\n\tVersion string\n\tVersionPrerelease string\n\tUi cli.Ui\n}\n\nfunc (c *VersionCommand) Help() string {\n\treturn \"\"\n}\n\n\n\nfunc (c *VersionCommand) Synopsis() string {\n\treturn \"Prints the Serf version\"\n}\n\nfunc (c *VersionCommand) Run(_ []string) int ", "output": "{\n\tvar versionString bytes.Buffer\n\tfmt.Fprintf(&versionString, \"Serf v%s\", c.Version)\n\tif c.VersionPrerelease != \"\" {\n\t\tfmt.Fprintf(&versionString, \".%s\", c.VersionPrerelease)\n\n\t\tif c.Revision != \"\" {\n\t\t\tfmt.Fprintf(&versionString, \" (%s)\", c.Revision)\n\t\t}\n\t}\n\n\tc.Ui.Output(versionString.String())\n\tc.Ui.Output(fmt.Sprintf(\"Agent Protocol: %d (Understands back to: %d)\",\n\t\tserf.ProtocolVersionMax, serf.ProtocolVersionMin))\n\treturn 0\n}"} {"input": "package authboss\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\n\ntype DefaultLogger log.Logger\n\n\n\n\n\nfunc (d *DefaultLogger) Write(b []byte) (int, error) {\n\t((*log.Logger)(d)).Printf(\"%s\", b)\n\treturn len(b), nil\n}\n\nfunc NewDefaultLogger() *DefaultLogger ", "output": "{\n\treturn ((*DefaultLogger)(log.New(os.Stdout, \"\", log.LstdFlags)))\n}"} {"input": "package turtle\n\nimport (\n\t\"strings\"\n)\n\ntype DataSet struct {\n\ttriplecount int\n\tnscount int\n\tNamespaces map[string]string\n\tTriples []Triple\n}\n\nfunc newDataSet() *DataSet {\n\treturn &DataSet{\n\t\ttriplecount: 0,\n\t\tnscount: 0,\n\t\tNamespaces: make(map[string]string),\n\t\tTriples: []Triple{},\n\t}\n}\n\n\n\nfunc (d *DataSet) AddTripleURIs(subject, predicate, object URI) {\n\td.triplecount += 1\n\td.Triples = append(d.Triples, Triple{subject, predicate, object})\n}\n\nfunc (d *DataSet) addNamespace(prefix, namespace string) {\n\td.nscount += 1\n\tnamespace = strings.TrimRight(namespace, \"#\")\n\td.Namespaces[prefix] = namespace\n}\n\nfunc (d *DataSet) NumTriples() int {\n\treturn d.triplecount\n}\n\nfunc (d *DataSet) NumNamespaces() int {\n\treturn d.nscount\n}\n\nfunc (d *DataSet) AddTripleStrings(subject, predicate, object string) ", "output": "{\n\td.triplecount += 1\n\td.Triples = append(d.Triples, MakeTriple(subject, predicate, object))\n}"} {"input": "package printer\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/resoursea/api\"\n)\n\n\n\nfunc router(r api.Router, lvl int) {\n\tfmt.Printf(\"%sRoute: %s\\n\", strings.Repeat(\"\t\", lvl), r)\n\n\tfor _, m := range r.Methods() {\n\t\thandler(m, lvl)\n\t}\n\n\tfor _, c := range r.Children() {\n\t\tif r.IsSlice() {\n\t\t\trouter(c, lvl)\n\t\t} else {\n\t\t\trouter(c, lvl+1)\n\t\t}\n\t}\n}\n\nfunc handler(m api.Method, lvl int) {\n\tfmt.Printf(\"%s- Method: %s\\n\", strings.Repeat(\"\t\", lvl), m)\n}\n\nfunc Router(rt api.Router) ", "output": "{\n\tfmt.Println(\"\\n--- PRINT ROUTER ---\\n\")\n\trouter(rt, 0)\n\tfmt.Println(\"\\n--- END PRINT ---\\n\")\n}"} {"input": "package vkutil\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n)\n\n\n\n\nfunc NewCountOffsetParams(count int, offsets ...int) url.Values ", "output": "{\n\tif count == 0 {\n\t\tcount = 1\n\t}\n\tparam := url.Values{\n\t\t\"count\": {fmt.Sprint(count)},\n\t}\n\tif len(offsets) > 0 && offsets[0] != 0 {\n\t\tparam.Set(\"offset\", fmt.Sprint(offsets[0]))\n\t}\n\treturn param\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\n\t\"github.com/codeskyblue/go-sh\"\n)\n\n\n\nfunc KillCmd(cmd *exec.Cmd, signal string) (err error) {\n\tvar pid, pgid int\n\tif cmd.Process != nil {\n\t\tpid = cmd.Process.Pid\n\t\tsess := sh.NewSession()\n\t\tif *verbose {\n\t\t\tsess.ShowCMD = true\n\t\t}\n\t\tc := sess.Command(\"/bin/ps\", \"-o\", \"pgid\", \"-p\", strconv.Itoa(pid)).Command(\"sed\", \"-n\", \"2,$p\")\n\t\tvar out []byte\n\t\tout, err = c.Output()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t_, err = fmt.Sscanf(string(out), \"%d\", &pgid)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\treturn sess.Command(\"/bin/ps\", \"-eo\", \"pid,pgid\").Command(\"awk\", fmt.Sprintf(`$2==%d {system(\"/bin/kill -%s \"$1)}`, pgid, signal)).Run()\n\t}\n\treturn\n}\n\nfunc StartCmd(name string, args ...string) *exec.Cmd ", "output": "{\n\tc := exec.Command(name, args...)\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stdout\n\tc.Stdin = os.Stdin\n\n\treturn c\n}"} {"input": "package balanced\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n)\n\ntype Customer struct {\n\tAddress *Address `json:\"address,omitempty\"`\n\tBusinessName string `json:\"business_name,omitempty\"`\n\tCreatedAt time.Time `json:\"created_at,omitempty\"`\n\tDobMonth int `json:\"dob_month,omitempty\"`\n\tDobYear int `json:\"dob_year,omitempty\"`\n\tEin string `json:\"ein,omitempty\"`\n\tEmail string `json:\"email,omitempty\"`\n\tID string `json:\"id,omitempty\"`\n\tMeta map[string]interface{} `json:\"meta,omitempty\"`\n\tName string `json:\"name,omitempty\"`\n\tPhone string `json:\"phone,omitempty\"`\n\tSSNLast4 string `json:\"ssn_last4,omitempty\"`\n\tMerchantStatus string `json:\"merchant_status,omitempty\"`\n}\n\ntype customerResponse struct {\n\tCustomers []*Customer `json:\"customers\"`\n}\n\nfunc (c *Customer) path() string {\n\treturn \"/customers\"\n}\n\nfunc (c *Customer) getID() string {\n\treturn c.ID\n}\n\nfunc (c *Customer) getOwnerPath() string {\n\treturn \"\"\n}\n\nfunc (c *Customer) singleResponse(data []byte) {\n\tparsedResponse := new(customerResponse)\n\tjson.Unmarshal(data, &parsedResponse)\n\t*c = *parsedResponse.Customers[0]\n}\n\nfunc (c *Customer) canDelete() bool {\n\treturn true\n}\n\n\n\nfunc (c *Customer) IsVerified() bool ", "output": "{\n\treturn c.MerchantStatus == \"underwritten\"\n}"} {"input": "package sync\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t. \"github.com/franela/goblin\"\n)\n\n\n\nfunc TestOnce(t *testing.T) ", "output": "{\n\tg := Goblin(t)\n\tg.Describe(\"#Once\", func() {\n\t\tg.It(\"should return nil only once for one id\", func() {\n\t\t\tvar id = \"1\"\n\t\t\tg.Assert(Once(id) == nil).IsTrue()\n\t\t\tg.Assert(Once(id) == nil).IsFalse()\n\t\t\tg.Assert(Once(id) == nil).IsFalse()\n\t\t\tg.Assert(Once(id) == nil).IsFalse()\n\t\t})\n\t\tg.It(\"should return nil again after ttl reached\", func() {\n\t\t\tvar id = \"2\"\n\t\t\tttl = time.Millisecond * 500\n\t\t\tg.Assert(Once(id) == nil).IsTrue()\n\t\t\tg.Assert(Once(id) == nil).IsFalse()\n\t\t\tg.Assert(Once(id) == nil).IsFalse()\n\n\t\t\ttime.Sleep(time.Second)\n\t\t\tg.Assert(Once(id) == nil).IsTrue()\n\t\t})\n\t})\n}"} {"input": "package api\n\nimport (\n\t\"io\"\n\n\t\"github.com/dghubble/sling\"\n)\n\n\n\nconst SdkDebugKey = \"SdkDebug\"\n\n\ntype Client struct {\n\tsling.Doer\n\t*sling.Sling\n}\n\ntype ApiKeyClientOption func(*ApiKeyClientOptions)\ntype ApiKeyClientOptions struct {\n\tInsecureSkipVerify bool\n\n\tInsecureUsePlaintext bool\n\n\tEnableRoot bool\n\n\tProduct string\n\n\tDebugWriter io.Writer\n}\n\nvar DefaultApiKeyClientOptions = ApiKeyClientOptions{\n\tInsecureSkipVerify: false,\n\tInsecureUsePlaintext: false,\n\tEnableRoot: false,\n}\n\n\n\nvar InsecureNoSSLVerification ApiKeyClientOption\n\n\n\nvar InsecureUsePlaintext ApiKeyClientOption\n\n\nvar EnableRoot ApiKeyClientOption\n\n\nfunc UserAgent(product string) ApiKeyClientOption {\n\treturn func(o *ApiKeyClientOptions) {\n\t\to.Product = product\n\t}\n}\n\n\n\nfunc DebugLogRequests(w io.Writer) ApiKeyClientOption {\n\treturn func(o *ApiKeyClientOptions) {\n\t\to.DebugWriter = w\n\t}\n}\n\n\n\nfunc init() ", "output": "{\n\tInsecureNoSSLVerification = func(o *ApiKeyClientOptions) {\n\t\to.InsecureSkipVerify = true\n\t}\n\n\tInsecureUsePlaintext = func(o *ApiKeyClientOptions) {\n\t\to.InsecureUsePlaintext = true\n\t}\n\n\tEnableRoot = func(o *ApiKeyClientOptions) {\n\t\to.EnableRoot = true\n\t}\n}"} {"input": "package nat\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n\n\t\"github.com/cilium/cilium/pkg/byteorder\"\n\t\"github.com/cilium/cilium/pkg/tuple\"\n\t\"github.com/cilium/cilium/pkg/types\"\n)\n\n\n\n\ntype NatEntry4 struct {\n\tCreated uint64 `align:\"created\"`\n\tHostLocal uint64 `align:\"host_local\"`\n\tPad1 uint64 `align:\"pad1\"`\n\tPad2 uint64 `align:\"pad2\"`\n\tAddr types.IPv4 `align:\"to_saddr\"`\n\tPort uint16 `align:\"to_sport\"`\n}\n\n\nconst SizeofNatEntry4 = int(unsafe.Sizeof(NatEntry4{}))\n\n\nfunc (n *NatEntry4) GetValuePtr() unsafe.Pointer { return unsafe.Pointer(n) }\n\n\n\n\n\nfunc (n *NatEntry4) Dump(key NatKey, start uint64) string {\n\tvar which string\n\n\tif key.GetFlags()&tuple.TUPLE_F_IN != 0 {\n\t\twhich = \"DST\"\n\t} else {\n\t\twhich = \"SRC\"\n\t}\n\treturn fmt.Sprintf(\"XLATE_%s %s:%d Created=%s HostLocal=%d\\n\",\n\t\twhich,\n\t\tn.Addr,\n\t\tn.Port,\n\t\tNatDumpCreated(start, n.Created),\n\t\tn.HostLocal)\n}\n\n\nfunc (n *NatEntry4) ToHost() NatEntry {\n\tx := *n\n\tx.Port = byteorder.NetworkToHost16(n.Port)\n\treturn &x\n}\n\nfunc (n *NatEntry4) String() string ", "output": "{\n\treturn fmt.Sprintf(\"Addr=%s Port=%d Created=%d HostLocal=%d\\n\",\n\t\tn.Addr,\n\t\tn.Port,\n\t\tn.Created,\n\t\tn.HostLocal)\n}"} {"input": "package downloader\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/WhaleCoinOrg/WhaleCoin/core/types\"\n)\n\n\ntype peerDropFn func(id string)\n\n\ntype dataPack interface {\n\tPeerId() string\n\tItems() int\n\tStats() string\n}\n\n\ntype headerPack struct {\n\tpeerId string\n\theaders []*types.Header\n}\n\nfunc (p *headerPack) PeerId() string { return p.peerId }\nfunc (p *headerPack) Items() int { return len(p.headers) }\n\n\n\ntype bodyPack struct {\n\tpeerId string\n\ttransactions [][]*types.Transaction\n\tuncles [][]*types.Header\n}\n\nfunc (p *bodyPack) PeerId() string { return p.peerId }\nfunc (p *bodyPack) Items() int {\n\tif len(p.transactions) <= len(p.uncles) {\n\t\treturn len(p.transactions)\n\t}\n\treturn len(p.uncles)\n}\nfunc (p *bodyPack) Stats() string { return fmt.Sprintf(\"%d:%d\", len(p.transactions), len(p.uncles)) }\n\n\ntype receiptPack struct {\n\tpeerId string\n\treceipts [][]*types.Receipt\n}\n\nfunc (p *receiptPack) PeerId() string { return p.peerId }\nfunc (p *receiptPack) Items() int { return len(p.receipts) }\nfunc (p *receiptPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.receipts)) }\n\n\ntype statePack struct {\n\tpeerId string\n\tstates [][]byte\n}\n\nfunc (p *statePack) PeerId() string { return p.peerId }\nfunc (p *statePack) Items() int { return len(p.states) }\nfunc (p *statePack) Stats() string { return fmt.Sprintf(\"%d\", len(p.states)) }\n\nfunc (p *headerPack) Stats() string ", "output": "{ return fmt.Sprintf(\"%d\", len(p.headers)) }"} {"input": "package event\n\nimport (\n\t\"github.com/hyperledger/fabric-protos-go/gateway\"\n\t\"github.com/hyperledger/fabric-protos-go/peer\"\n\t\"github.com/hyperledger/fabric/common/ledger\"\n)\n\ntype ChaincodeEventsIterator struct {\n\tblockIter *BlockIterator\n}\n\nfunc NewChaincodeEventsIterator(iterator ledger.ResultsIterator) *ChaincodeEventsIterator {\n\treturn &ChaincodeEventsIterator{\n\t\tblockIter: NewBlockIterator(iterator),\n\t}\n}\n\nfunc (iter *ChaincodeEventsIterator) Next() (*gateway.ChaincodeEventsResponse, error) {\n\tfor {\n\t\tresult, err := iter.nextBlock()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(result.Events) > 0 {\n\t\t\treturn result, nil\n\t\t}\n\t}\n}\n\n\n\nfunc chaincodeEventsFromBlock(block *Block) ([]*peer.ChaincodeEvent, error) {\n\ttransactions, err := block.Transactions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar results []*peer.ChaincodeEvent\n\n\tfor _, transaction := range transactions {\n\t\tif !transaction.Valid() {\n\t\t\tcontinue\n\t\t}\n\n\t\tevents, err := transaction.ChaincodeEvents()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, event := range events {\n\t\t\tresults = append(results, event.ProtoMessage())\n\t\t}\n\t}\n\n\treturn results, nil\n}\n\nfunc (iter *ChaincodeEventsIterator) Close() {\n\titer.blockIter.Close()\n}\n\nfunc (iter *ChaincodeEventsIterator) nextBlock() (*gateway.ChaincodeEventsResponse, error) ", "output": "{\n\tblock, err := iter.blockIter.Next()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tevents, err := chaincodeEventsFromBlock(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := &gateway.ChaincodeEventsResponse{\n\t\tBlockNumber: block.Number(),\n\t\tEvents: events,\n\t}\n\treturn result, nil\n}"} {"input": "package gspt\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"encoding/binary\"\n\t\"encoding/hex\"\n\n\t\"crypto/md5\"\n\t\"os/exec\"\n)\n\n\n\nfunc TestSetProcTitle(t *testing.T) {\n\tif HaveSetProcTitle == HaveNone {\n\t\tt.SkipNow()\n\t}\n\n\ttitle := randomMD5()\n\n\tSetProcTitle(title)\n\n\tout, err := exec.Command(\"/bin/ps\", \"ax\").Output()\n\tif err != nil {\n\t\tt.SkipNow()\n\t} else if !strings.Contains(string(out), title) {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestSetProcTitleFast(t *testing.T) {\n\tif HaveSetProcTitleFast == HaveNone {\n\t\tt.SkipNow()\n\t}\n\n\ttitle := randomMD5()\n\n\tSetProcTitleFast(title)\n\n\tout, err := exec.Command(\"/bin/ps\", \"ax\").Output()\n\tif err != nil {\n\t\tt.SkipNow()\n\t} else if !strings.Contains(string(out), title) {\n\t\tt.FailNow()\n\t}\n}\n\nfunc randomMD5() string ", "output": "{\n\tstr := md5.New()\n\trandom := new(bytes.Buffer)\n\n\tbinary.Write(random, binary.LittleEndian, time.Now().UTC().UnixNano())\n\n\tstr.Write(random.Bytes())\n\n\treturn hex.EncodeToString(str.Sum(nil))\n}"} {"input": "package lib_gc_metrics_endpoint\n\nimport(\n\t\"expvar\"\n\t\"net/http\"\n\t\"net\"\n)\n\nvar (\n\tDummy dummy\n)\n\ntype dummy struct{}\n\n\n\nfunc Start(_net,host,port string) error{\n\tsock, err := net.Listen(_net, host+\":\"+port)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\n\t\thttp.Serve(sock, nil)\n\t}()\n\treturn nil\n}\n\nfunc init()", "output": "{\n\tz:=expvar.NewString(\"METRICS\")\n\tz.Set(\"OK\")\n}"} {"input": "package utils\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nfunc ToJson(data interface{}) string {\n\tb, err := json.Marshal(data)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\treturn string(b)\n}\n\nfunc GetHostIp() string {\n\tip := \"127.0.0.1\"\n\n\taddrs, _ := net.InterfaceAddrs()\n\tfor _, a := range addrs {\n\t\tipnet := net.ParseIP(a.String())\n\t\tif ipnet == nil {\n\t\t\tipnet, _, _ = net.ParseCIDR(a.String())\n\t\t}\n\t\tif ipnet != nil && !ipnet.IsLoopback() && !ipnet.IsUnspecified() {\n\t\t\tif ipnet.To4() != nil {\n\t\t\t\tip = ipnet.String()\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ip\n}\n\n\n\nfunc IsIgnoreRequest(url string, contentType string, statusCode int) bool ", "output": "{\n\tif statusCode != 200 {\n\t\treturn true\n\t}\n\tif !strings.Contains(contentType, \"text\") && !strings.Contains(contentType, \"application\") {\n\t\treturn true\n\t}\n\n\tswitch {\n\tcase strings.Contains(contentType, \"text/css\"):\n\t\tfallthrough\n\tcase strings.Contains(contentType, \"text/javascript\"):\n\t\treturn true\n\tdefault:\n\t\tbreak\n\t}\n\tidx := strings.Index(url, \"?\")\n\tif idx >= 0 {\n\t\turl = url[:idx]\n\t}\n\text := strings.ToLower(filepath.Ext(url))\n\treturn ext == \".js\" || ext == \".css\" ||\n\t\text == \".jpg\" || ext == \".jpeg\" || ext == \".gif\" || ext == \".png\" ||\n\t\text == \".bmp\" || ext == \".ico\" || ext == \".woff\" || ext == \".font\" ||\n\t\text == \".ttf\" || ext == \".svg\" || ext == \".pdf\" || ext == \".txt\"\n}"} {"input": "package s2\n\n\nvar (\n\t_ Shape = (*PointVector)(nil)\n)\n\n\n\n\n\n\n\n\ntype PointVector []Point\n\n\nfunc (p *PointVector) Edge(i int) Edge { return Edge{(*p)[i], (*p)[i]} }\nfunc (p *PointVector) ReferencePoint() ReferencePoint { return OriginReferencePoint(false) }\nfunc (p *PointVector) NumChains() int { return len(*p) }\nfunc (p *PointVector) Chain(i int) Chain { return Chain{i, 1} }\nfunc (p *PointVector) ChainEdge(i, j int) Edge { return Edge{(*p)[i], (*p)[j]} }\nfunc (p *PointVector) ChainPosition(e int) ChainPosition { return ChainPosition{e, 0} }\nfunc (p *PointVector) Dimension() int { return 0 }\nfunc (p *PointVector) IsEmpty() bool { return defaultShapeIsEmpty(p) }\nfunc (p *PointVector) IsFull() bool { return defaultShapeIsFull(p) }\nfunc (p *PointVector) typeTag() typeTag { return typeTagPointVector }\nfunc (p *PointVector) privateInterface() {}\n\nfunc (p *PointVector) NumEdges() int ", "output": "{ return len(*p) }"} {"input": "package main\n\nimport (\n\t\"time\"\n\n\t\"golang.org/x/text/language\"\n)\n\n\n\nconst (\n\tcashShift = 3\n\troundMask = 0x7\n\n\tnonTenderBit = 0x8000\n)\n\n\n\n\ntype currencyInfo byte\n\n\n\n\ntype roundingType struct {\n\tscale, increment uint8\n}\n\n\n\nvar roundings = [...]roundingType{\n\t{2, 1}, \n\t{0, 1},\n\t{1, 1},\n\t{3, 1},\n\t{4, 1},\n\t{2, 5}, \n\t{2, 50},\n}\n\n\n\nfunc regionToCode(r language.Region) uint16 {\n\tif s := r.String(); len(s) == 2 {\n\t\treturn uint16(s[0])<<8 | uint16(s[1])\n\t}\n\treturn 0\n}\n\nfunc toDate(t time.Time) uint32 {\n\ty := t.Year()\n\tif y == 1 {\n\t\treturn 0\n\t}\n\tdate := uint32(y) << 4\n\tdate |= uint32(t.Month())\n\tdate <<= 5\n\tdate |= uint32(t.Day())\n\treturn date\n}\n\n\n\nfunc fromDate(date uint32) time.Time ", "output": "{\n\treturn time.Date(int(date>>9), time.Month((date>>5)&0xf), int(date&0x1f), 0, 0, 0, 0, time.UTC)\n}"} {"input": "package timeconv\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestNow(t *testing.T) {\n\tnow := time.Now()\n\tts := Now()\n\tvar drift int64 = 5\n\tif ts.Seconds < int64(now.Second())-drift {\n\t\tt.Errorf(\"Unexpected time drift: %d\", ts.Seconds)\n\t}\n}\n\n\n\nfunc TestTime(t *testing.T) {\n\tnowts := Now()\n\tnow := Time(nowts)\n\n\tif now.Unix() != nowts.Seconds {\n\t\tt.Errorf(\"Unexpected time drift %d\", now.Unix())\n\t}\n}\n\nfunc TestFormat(t *testing.T) {\n\tnow := time.Now()\n\tnowts := Timestamp(now)\n\n\tif now.Format(time.ANSIC) != Format(nowts, time.ANSIC) {\n\t\tt.Error(\"Format mismatch\")\n\t}\n}\n\nfunc TestTimestamp(t *testing.T) ", "output": "{\n\tnow := time.Now()\n\tts := Timestamp(now)\n\n\tif now.Unix() != ts.Seconds {\n\t\tt.Errorf(\"Unexpected time drift: %d to %d\", now.Second(), ts.Seconds)\n\t}\n\n\tif now.Nanosecond() != int(ts.Nanos) {\n\t\tt.Errorf(\"Unexpected nano drift: %d to %d\", now.Nanosecond(), ts.Nanos)\n\t}\n}"} {"input": "package modules\n\nimport(\n\n\t\"golangapi/tools\"\n\n\t\"gopkg.in/mgo.v2/bson\"\n)\n\nconst versionrulecname = \"versionrule\"\n\ntype VersionRule struct{}\n\n\n\nfunc (v *VersionRule) GetRuleByFilter (filters map[string]interface{}) (result bson.M, err error)", "output": "{\n\tdata, err := (&tools.MongoHelper{}).GetFieldByFilter(versionrulecname, filters)\n\terr = bson.Unmarshal(data, &result)\n\treturn result, err\n}"} {"input": "package logical\n\ntype HTTPCodedError interface {\n\tError() string\n\tCode() int\n}\n\nfunc CodedError(status int, msg string) HTTPCodedError {\n\treturn &codedError{\n\t\tStatus: status,\n\t\tMessage: msg,\n\t}\n}\n\ntype codedError struct {\n\tStatus int\n\tMessage string\n}\n\nfunc (e *codedError) Error() string {\n\treturn e.Message\n}\n\nfunc (e *codedError) Code() int {\n\treturn e.Status\n}\n\n\n\ntype StatusBadRequest struct {\n\tErr string\n}\n\n\n\n\n\n\n\n\ntype ReplicationCodedError struct {\n\tMsg string\n\tCode int\n}\n\nfunc (r *ReplicationCodedError) Error() string {\n\treturn r.Msg\n}\n\nfunc (s *StatusBadRequest) Error() string ", "output": "{\n\treturn s.Err\n}"} {"input": "package logger\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\tlog \"github.com/cihub/seelog\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestGetLogFileLocationReturnsOverriddenPath(t *testing.T) {\n\tpath := \"/tmp/foo\"\n\tos.Setenv(envLogFilePath, path)\n\tdefer os.Unsetenv(envLogFilePath)\n\n\tassert.Equal(t, path, GetLogFileLocation(\"/tmp/bar\"))\n}\n\nfunc TestGetLogFileLocationReturnsDefaultPath(t *testing.T) {\n\tpath := \"/tmp/foo\"\n\tassert.Equal(t, path, GetLogFileLocation(path))\n}\n\nfunc TestLogLevelReturnsOverriddenLevel(t *testing.T) {\n\tos.Setenv(envLogLevel, \"DEBUG\")\n\tdefer os.Unsetenv(envLogLevel)\n\n\tvar expectedLogLevel log.LogLevel\n\texpectedLogLevel = log.DebugLvl\n\tassert.Equal(t, expectedLogLevel.String(), getLogLevel())\n}\n\n\n\nfunc TestLogLevelReturnsDefaultLevelWhenEnvSetToInvalidValue(t *testing.T) {\n\tos.Setenv(envLogLevel, \"DEBUGGER\")\n\tdefer os.Unsetenv(envLogLevel)\n\n\tvar expectedLogLevel log.LogLevel\n\texpectedLogLevel = log.InfoLvl\n\tassert.Equal(t, expectedLogLevel.String(), getLogLevel())\n}\n\nfunc TestLogLevelReturnsDefaultLevelWhenEnvNotSet(t *testing.T) ", "output": "{\n\tvar expectedLogLevel log.LogLevel\n\texpectedLogLevel = log.InfoLvl\n\tassert.Equal(t, expectedLogLevel.String(), getLogLevel())\n}"} {"input": "package os\n\n\n\n\nfunc Hostname() (name string, err Error) ", "output": "{\n\tf, err := Open(\"#c/sysname\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\n\tvar buf [128]byte\n\tn, err := f.Read(buf[:len(buf)-1])\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif n > 0 {\n\t\tbuf[n] = 0\n\t}\n\treturn string(buf[0:n]), nil\n}"} {"input": "package oauth\n\nimport (\n\t\"net/http/httptest\"\n\n\t\"golang.org/x/oauth2\"\n)\n\n\n\n\nfunc NewTestProvider(s *httptest.Server) *Provider ", "output": "{\n\treturn &Provider{\n\t\t&oauth2.Config{\n\t\t\tClientID: \"TEST\",\n\t\t\tClientSecret: \"SECRET\",\n\t\t\tEndpoint: oauth2.Endpoint{\n\t\t\t\tAuthURL: s.URL,\n\t\t\t\tTokenURL: s.URL,\n\t\t\t},\n\t\t},\n\t\tfunc(t *oauth2.Token) (*UserInfo, error) {\n\t\t\treturn &UserInfo{\n\t\t\t\tID: t.AccessToken,\n\t\t\t\tEmail: t.AccessToken,\n\t\t\t}, nil\n\t\t},\n\t}\n}"} {"input": "package info_fakes\n\nimport (\n\t\"sync\"\n\n\t\"github.com/cloudfoundry-incubator/diego-ssh/cf-plugin/models/info\"\n)\n\ntype FakeInfoFactory struct {\n\tGetStub func() (info.Info, error)\n\tgetMutex sync.RWMutex\n\tgetArgsForCall []struct{}\n\tgetReturns struct {\n\t\tresult1 info.Info\n\t\tresult2 error\n\t}\n}\n\nfunc (fake *FakeInfoFactory) Get() (info.Info, error) {\n\tfake.getMutex.Lock()\n\tfake.getArgsForCall = append(fake.getArgsForCall, struct{}{})\n\tfake.getMutex.Unlock()\n\tif fake.GetStub != nil {\n\t\treturn fake.GetStub()\n\t} else {\n\t\treturn fake.getReturns.result1, fake.getReturns.result2\n\t}\n}\n\n\n\nfunc (fake *FakeInfoFactory) GetReturns(result1 info.Info, result2 error) {\n\tfake.GetStub = nil\n\tfake.getReturns = struct {\n\t\tresult1 info.Info\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nvar _ info.InfoFactory = new(FakeInfoFactory)\n\nfunc (fake *FakeInfoFactory) GetCallCount() int ", "output": "{\n\tfake.getMutex.RLock()\n\tdefer fake.getMutex.RUnlock()\n\treturn len(fake.getArgsForCall)\n}"} {"input": "package client\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest/adal\"\n\t\"github.com/Azure/go-autorest/autorest/azure\"\n)\n\n\ntype msiOAuthTokenProvider struct {\n\tenv azure.Environment\n}\n\n\n\nfunc (tp *msiOAuthTokenProvider) getServicePrincipalToken() (*adal.ServicePrincipalToken, error) {\n\treturn tp.getServicePrincipalTokenWithResource(tp.env.ResourceManagerEndpoint)\n}\n\nfunc (tp *msiOAuthTokenProvider) getServicePrincipalTokenWithResource(resource string) (*adal.ServicePrincipalToken, error) {\n\treturn adal.NewServicePrincipalTokenFromMSI(\"http://169.254.169.254/metadata/identity/oauth2/token\", resource)\n}\n\nfunc NewMSIOAuthTokenProvider(env azure.Environment) oAuthTokenProvider ", "output": "{\n\treturn &msiOAuthTokenProvider{env}\n}"} {"input": "package all\n\nimport (\n\t\"github.com/juju/collections/set\"\n\t\"github.com/juju/errors\"\n)\n\ntype component interface {\n\tregisterForServer() error\n\tregisterForClient() error\n}\n\nvar components = []component{\n\t&payloads{},\n\t&resources{},\n}\n\n\n\nfunc RegisterForServer() error {\n\tfor _, c := range components {\n\t\tif err := c.registerForServer(); err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\n\n\nvar registered = map[string]set.Strings{}\n\n\n\n\n\nfunc markRegistered(component, part string) bool {\n\tparts, ok := registered[component]\n\tif !ok {\n\t\tparts = set.NewStrings()\n\t\tregistered[component] = parts\n\t}\n\tif parts.Contains(part) {\n\t\treturn false\n\t}\n\tparts.Add(part)\n\treturn true\n}\n\nfunc RegisterForClient() error ", "output": "{\n\tfor _, c := range components {\n\t\tif err := c.registerForClient(); err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package addrs\n\nimport \"fmt\"\n\n\n\n\n\n\n\n\n\n\n\ntype ResourceInstancePhase struct {\n\treferenceable\n\tResourceInstance ResourceInstance\n\tPhase ResourceInstancePhaseType\n}\n\nvar _ Referenceable = ResourceInstancePhase{}\n\n\n\n\nfunc (r ResourceInstance) Phase(rpt ResourceInstancePhaseType) ResourceInstancePhase {\n\treturn ResourceInstancePhase{\n\t\tResourceInstance: r,\n\t\tPhase: rpt,\n\t}\n}\n\n\n\nfunc (rp ResourceInstancePhase) ContainingResource() ResourcePhase {\n\treturn rp.ResourceInstance.Resource.Phase(rp.Phase)\n}\n\nfunc (rp ResourceInstancePhase) String() string {\n\treturn fmt.Sprintf(\"%s#%s\", rp.ResourceInstance, rp.Phase)\n}\n\n\ntype ResourceInstancePhaseType string\n\nconst (\n\tResourceInstancePhaseDestroy ResourceInstancePhaseType = \"destroy\"\n\n\tResourceInstancePhaseDestroyCBD ResourceInstancePhaseType = \"destroy-cbd\"\n)\n\nfunc (rpt ResourceInstancePhaseType) String() string {\n\treturn string(rpt)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype ResourcePhase struct {\n\treferenceable\n\tResource Resource\n\tPhase ResourceInstancePhaseType\n}\n\nvar _ Referenceable = ResourcePhase{}\n\n\n\n\n\n\nfunc (rp ResourcePhase) String() string {\n\treturn fmt.Sprintf(\"%s#%s\", rp.Resource, rp.Phase)\n}\n\nfunc (r Resource) Phase(rpt ResourceInstancePhaseType) ResourcePhase ", "output": "{\n\treturn ResourcePhase{\n\t\tResource: r,\n\t\tPhase: rpt,\n\t}\n}"} {"input": "package events\n\nimport (\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/gravitational/teleport/lib/session\"\n)\n\n\n\ntype DiscardAuditLog struct {\n}\n\nfunc (d *DiscardAuditLog) Close() error {\n\treturn nil\n}\n\nfunc (d *DiscardAuditLog) EmitAuditEvent(eventType string, fields EventFields) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionChunk(namespace string, sid session.ID, reader io.Reader) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionSlice(SessionSlice) error {\n\treturn nil\n}\n\nfunc (d *DiscardAuditLog) GetSessionEvents(namespace string, sid session.ID, after int) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchEvents(fromUTC, toUTC time.Time, query string) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchSessionEvents(fromUTC time.Time, toUTC time.Time) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\n\n\n\n\ntype discardSessionLogger struct {\n}\n\nfunc (d *discardSessionLogger) LogEvent(fields EventFields) {\n\treturn\n}\n\nfunc (d *discardSessionLogger) Close() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) Finalize() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) WriteChunk(chunk *SessionChunk) (written int, err error) {\n\treturn 0, nil\n}\n\nfunc (d *DiscardAuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) ", "output": "{\n\treturn make([]byte, 0), nil\n}"} {"input": "package fwd\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"path\"\n)\n\n\n\n\n\n\n\nfunc Abs(absURL string, errHandler func(*http.Request, error)) http.Handler {\n\tparsedURL, err := url.Parse(absURL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdoProxy(parsedURL, w, r, errHandler)\n\t})\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc doProxy(\n\tu *url.URL, w http.ResponseWriter, r *http.Request,\n\terrHandler func(*http.Request, error),\n) {\n\tr.URL = u\n\tresp, err := http.DefaultClient.Do(r)\n\tif err != nil {\n\t\tif errHandler != nil {\n\t\t\terrHandler(r, err)\n\t\t}\n\t\thttp.Error(w, \"unexpected server-side error\", 500)\n\t}\n\tdefer resp.Body.Close()\n\n\tfor header, vals := range resp.Header {\n\t\tw.Header()[header] = append(w.Header()[header], vals...)\n\t}\n\n\tw.WriteHeader(resp.StatusCode)\n\tio.Copy(w, resp.Body)\n}\n\nfunc Rel(\n\taddr, relPath string, errHandler func(*http.Request, error),\n) http.Handler ", "output": "{\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tabsURL := addr + path.Join(relPath, r.URL.Path)\n\t\tparsedURL, err := url.Parse(absURL)\n\t\tif err != nil {\n\t\t\terrHandler(r, err)\n\t\t}\n\t\tparsedURL.RawQuery = r.URL.RawQuery\n\n\t\tdoProxy(parsedURL, w, r, errHandler)\n\t})\n}"} {"input": "package sql\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/cockroachdb/cockroach/pkg/roachpb\"\n\t\"github.com/cockroachdb/cockroach/pkg/sql/parser\"\n\t\"github.com/cockroachdb/cockroach/pkg/sql/sqlbase\"\n)\n\n\n\n\ntype delayedNode struct {\n\tname string\n\tcolumns sqlbase.ResultColumns\n\tconstructor nodeConstructor\n\tplan planNode\n}\n\ntype nodeConstructor func(context.Context, *planner) (planNode, error)\n\nfunc (d *delayedNode) Close(ctx context.Context) {\n\tif d.plan != nil {\n\t\td.plan.Close(ctx)\n\t\td.plan = nil\n\t}\n}\n\nfunc (d *delayedNode) Columns() sqlbase.ResultColumns { return d.columns }\nfunc (d *delayedNode) Ordering() orderingInfo { return orderingInfo{} }\nfunc (d *delayedNode) MarkDebug(_ explainMode) {}\nfunc (d *delayedNode) Start(ctx context.Context) error { return d.plan.Start(ctx) }\nfunc (d *delayedNode) Next(ctx context.Context) (bool, error) { return d.plan.Next(ctx) }\n\nfunc (d *delayedNode) DebugValues() debugValues { return d.plan.DebugValues() }\nfunc (d *delayedNode) Spans(ctx context.Context) (_, _ roachpb.Spans, _ error) {\n\treturn d.plan.Spans(ctx)\n}\n\nfunc (d *delayedNode) Values() parser.Datums ", "output": "{ return d.plan.Values() }"} {"input": "package document\n\ntype IndexingOptions int\n\nconst (\n\tIndexField IndexingOptions = 1 << iota\n\tStoreField\n\tIncludeTermVectors\n)\n\n\n\nfunc (o IndexingOptions) IsStored() bool {\n\treturn o&StoreField != 0\n}\n\nfunc (o IndexingOptions) IncludeTermVectors() bool {\n\treturn o&IncludeTermVectors != 0\n}\n\nfunc (o IndexingOptions) String() string {\n\trv := \"\"\n\tif o.IsIndexed() {\n\t\trv += \"INDEXED\"\n\t}\n\tif o.IsStored() {\n\t\tif rv != \"\" {\n\t\t\trv += \", \"\n\t\t}\n\t\trv += \"STORE\"\n\t}\n\tif o.IncludeTermVectors() {\n\t\tif rv != \"\" {\n\t\t\trv += \", \"\n\t\t}\n\t\trv += \"TV\"\n\t}\n\treturn rv\n}\n\nfunc (o IndexingOptions) IsIndexed() bool ", "output": "{\n\treturn o&IndexField != 0\n}"} {"input": "package structs\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nconst (\n\tDefaultUnpriviledgedUser = \"nobody\"\n\n\tCheckBufSize = 4 * 1024\n)\n\n\ntype WaitResult struct {\n\tExitCode int\n\tSignal int\n\tErr error\n}\n\nfunc NewWaitResult(code, signal int, err error) *WaitResult {\n\treturn &WaitResult{\n\t\tExitCode: code,\n\t\tSignal: signal,\n\t\tErr: err,\n\t}\n}\n\n\n\nfunc (r *WaitResult) String() string {\n\treturn fmt.Sprintf(\"Wait returned exit code %v, signal %v, and error %v\",\n\t\tr.ExitCode, r.Signal, r.Err)\n}\n\n\n\ntype RecoverableError struct {\n\tErr error\n\tRecoverable bool\n}\n\n\n\nfunc NewRecoverableError(e error, recoverable bool) *RecoverableError {\n\treturn &RecoverableError{\n\t\tErr: e,\n\t\tRecoverable: recoverable,\n\t}\n}\n\nfunc (r *RecoverableError) Error() string {\n\treturn r.Err.Error()\n}\n\n\ntype CheckResult struct {\n\n\tExitCode int\n\n\tOutput string\n\n\tTimestamp time.Time\n\n\tDuration time.Duration\n\n\tErr error\n}\n\nfunc (r *WaitResult) Successful() bool ", "output": "{\n\treturn r.ExitCode == 0 && r.Signal == 0 && r.Err == nil\n}"} {"input": "package chipmunk\n\nimport (\n\t\"github.com/Dethrail/chipmunk/transform\"\n\t\"github.com/Dethrail/chipmunk/vect\"\n\t\"math\"\n)\n\nconst (\n\tRadianConst = math.Pi / 180\n\tDegreeConst = 180 / math.Pi\n)\n\ntype Group int\ntype Layer int\n\ntype Shape struct {\n\tDefaultHash\n\tShapeClass\n\n\tBody *Body\n\n\tBB AABB\n\n\tIsSensor bool\n\n\te vect.Float\n\tu vect.Float\n\tSurface_v vect.Vect\n\n\tUserData interface{}\n\n\tGroup Group\n\tLayer Layer\n\n\tspace *Space\n\n\tvelocityIndexed bool\n}\n\nfunc newShape() *Shape {\n\treturn &Shape{velocityIndexed: true, e: 0.5, u: 0.5, Layer: -1}\n\n}\n\nfunc (shape *Shape) Velocity() (vect.Vect, bool) {\n\treturn shape.Body.v, shape.velocityIndexed\n}\n\nfunc (shape *Shape) SetFriction(friction vect.Float) {\n\tshape.u = friction\n}\n\nfunc (shape *Shape) SetElasticity(e vect.Float) {\n\tshape.e = e\n}\n\nfunc (shape *Shape) Shape() *Shape {\n\treturn shape\n}\n\n\n\nfunc (shape *Shape) Clone() *Shape {\n\tclone := *shape\n\tcc := &clone\n\tcc.space = nil\n\tcc.DefaultHash.Reset()\n\tcc.Body = nil\n\tcc.ShapeClass = cc.ShapeClass.Clone(cc)\n\treturn cc\n}\n\nfunc (shape *Shape) Update() {\n\tshape.BB = shape.ShapeClass.update(transform.NewTransform(shape.Body.p, shape.Body.a))\n}\n\nfunc (shape *Shape) AABB() AABB ", "output": "{\n\treturn shape.BB\n}"} {"input": "package types\n\nimport (\n\t\"bytes\"\n\t\"database/sql\"\n\t\"encoding/json\"\n)\n\n\ntype NullBool struct {\n\tsql.NullBool\n}\n\n\n\n\n\nfunc (n *NullBool) UnmarshalJSON(b []byte) error {\n\tif bytes.Equal(b, []byte(\"null\")) {\n\t\tn.Bool = false\n\t\tn.Valid = false\n\t\treturn nil\n\t}\n\tvar x interface{}\n\tvar err error\n\tjson.Unmarshal(b, &x)\n\tswitch x.(type) {\n\tcase bool:\n\t\terr = json.Unmarshal(b, &n.Bool)\n\tcase map[string]interface{}:\n\t\terr = json.Unmarshal(b, &n.NullBool)\n\t}\n\tn.Valid = true\n\treturn err\n}\n\nfunc (n *NullBool) MarshalJSON() ([]byte, error) ", "output": "{\n\tif !n.Valid {\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn json.Marshal(n.Bool)\n}"} {"input": "package example\n\nimport (\n\t\"net/http\"\n\n\t\"gopkg.in/gin-gonic/gin.v1\"\n)\n\nfunc ginHelloHandler(c *gin.Context) {\n\tc.String(http.StatusOK, \"Hello World\")\n}\n\n\n\n\nfunc GinEngine() *gin.Engine ", "output": "{\n\tgin.SetMode(gin.TestMode)\n\tr := gin.New()\n\n\tr.GET(\"/\", ginHelloHandler)\n\n\treturn r\n}"} {"input": "package containerinstance\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" containerinstance/2021-03-01\"\n}"} {"input": "package proxy\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n)\n\ntype Response interface {\n\tStatus() int\n\tHeader() http.Header\n\tBody() []byte\n}\n\ntype WriterRecorder struct {\n\thttp.ResponseWriter\n\tstatus int\n\tbody bytes.Buffer\n}\n\nfunc (w *WriterRecorder) WriteHeader(status int) {\n\tw.ResponseWriter.WriteHeader(status)\n\tw.status = status\n}\n\nfunc (w *WriterRecorder) Write(body []byte) (n int, err error) {\n\tif n, err := w.body.Write(body); err != nil {\n\t\treturn n, err\n\t}\n\n\treturn w.ResponseWriter.Write(body)\n}\n\nfunc (w *WriterRecorder) Body() []byte {\n\treturn w.body.Bytes()\n}\n\n\n\nfunc (w *WriterRecorder) Status() int ", "output": "{\n\tif w.status == 0 {\n\t\treturn 200\n\t}\n\treturn w.status\n}"} {"input": "package args\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\n\t\"github.com/spf13/pflag\"\n\tcodegenutil \"k8s.io/code-generator/pkg/util\"\n\t\"k8s.io/gengo/args\"\n)\n\n\ntype CustomArgs struct {\n\tVersionedClientSetPackage string\n\tInternalClientSetPackage string\n\tListersPackage string\n\tSingleDirectory bool\n}\n\n\n\n\n\nfunc (ca *CustomArgs) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(&ca.InternalClientSetPackage, \"internal-clientset-package\", ca.InternalClientSetPackage, \"the full package name for the internal clientset to use\")\n\tfs.StringVar(&ca.VersionedClientSetPackage, \"versioned-clientset-package\", ca.VersionedClientSetPackage, \"the full package name for the versioned clientset to use\")\n\tfs.StringVar(&ca.ListersPackage, \"listers-package\", ca.ListersPackage, \"the full package name for the listers to use\")\n\tfs.BoolVar(&ca.SingleDirectory, \"single-directory\", ca.SingleDirectory, \"if true, omit the intermediate \\\"internalversion\\\" and \\\"externalversions\\\" subdirectories\")\n}\n\n\nfunc Validate(genericArgs *args.GeneratorArgs) error {\n\tcustomArgs := genericArgs.CustomArgs.(*CustomArgs)\n\n\tif len(genericArgs.OutputPackagePath) == 0 {\n\t\treturn fmt.Errorf(\"output package cannot be empty\")\n\t}\n\tif len(customArgs.VersionedClientSetPackage) == 0 {\n\t\treturn fmt.Errorf(\"versioned clientset package cannot be empty\")\n\t}\n\tif len(customArgs.ListersPackage) == 0 {\n\t\treturn fmt.Errorf(\"listers package cannot be empty\")\n\t}\n\n\treturn nil\n}\n\nfunc NewDefaults() (*args.GeneratorArgs, *CustomArgs) ", "output": "{\n\tgenericArgs := args.Default().WithoutDefaultFlagParsing()\n\tcustomArgs := &CustomArgs{\n\t\tSingleDirectory: false,\n\t}\n\tgenericArgs.CustomArgs = customArgs\n\n\tif pkg := codegenutil.CurrentPackage(); len(pkg) != 0 {\n\t\tgenericArgs.OutputPackagePath = path.Join(pkg, \"pkg/client/informers\")\n\t\tcustomArgs.VersionedClientSetPackage = path.Join(pkg, \"pkg/client/clientset/versioned\")\n\t\tcustomArgs.InternalClientSetPackage = path.Join(pkg, \"pkg/client/clientset/internalversion\")\n\t\tcustomArgs.ListersPackage = path.Join(pkg, \"pkg/client/listers\")\n\t}\n\n\treturn genericArgs, customArgs\n}"} {"input": "package proc\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n)\n\ntype StdioConn struct {\n\tio.ReadCloser\n\tio.WriteCloser\n\twaitErr chan error\n}\n\n\n\n\nfunc StartStdioProcess(path string, stderr io.Writer, args ...string) (*StdioConn, error) {\n\tvar (\n\t\terr error\n\t\tcmd = exec.Command(path, args...)\n\t\tconn StdioConn\n\t)\n\n\tconn.ReadCloser, err = cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn.WriteCloser, err = cmd.StdinPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn.waitErr = make(chan error)\n\n\tif stderr == nil {\n\t\tstderr, err := cmd.StderrPipe()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tgo func() {\n\t\t\ts := bufio.NewScanner(stderr)\n\t\t\tfor s.Scan() {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"stdioproc err:\", s.Text())\n\t\t\t}\n\t\t\tif err := s.Err(); err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"stdioproc failed:\", err)\n\t\t\t}\n\t\t}()\n\t} else {\n\t\tcmd.Stderr = stderr\n\t}\n\n\tif err = cmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tgo func() {\n\t\tconn.waitErr <- cmd.Wait()\n\t}()\n\n\treturn &conn, nil\n}\n\nfunc (s StdioConn) Close() error ", "output": "{\n\tif err := s.ReadCloser.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := s.WriteCloser.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn <-s.waitErr\n}"} {"input": "package logutils\n\nimport (\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype MockLog struct {\n\tmock.Mock\n}\n\nfunc NewMockLog() *MockLog {\n\treturn &MockLog{}\n}\n\nfunc (m *MockLog) Fatalf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Panicf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\n\n\nfunc (m *MockLog) Warnf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Infof(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Child(name string) Log {\n\tm.Called(name)\n\treturn m\n}\n\nfunc (m *MockLog) SetLevel(level LogLevel) {\n\tm.Called(level)\n}\n\nfunc (m *MockLog) Errorf(format string, args ...interface{}) ", "output": "{\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}"} {"input": "package containerregistry\n\nimport (\n\t\"github.com/sacloud/libsacloud/v2/helper/validate\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\ntype DeleteRequest struct {\n\tID types.ID `request:\"-\" validate:\"required\"`\n\n\tFailIfNotFound bool `request:\"-\"`\n}\n\n\n\nfunc (req *DeleteRequest) Validate() error ", "output": "{\n\treturn validate.Struct(req)\n}"} {"input": "package custom_commands\n\nimport (\n\t\"github.com/jmoiron/sqlx\"\n\t\"github.com/sgt-kabukiman/kabukibot/bot\"\n)\n\ntype pluginStruct struct {\n\tdb *sqlx.DB\n}\n\nfunc NewPlugin() *pluginStruct {\n\treturn &pluginStruct{}\n}\n\n\n\nfunc (self *pluginStruct) Setup(bot *bot.Kabukibot) {\n\tself.db = bot.Database()\n}\n\nfunc (self *pluginStruct) CreateWorker(channel bot.Channel) bot.PluginWorker {\n\treturn &worker{\n\t\tchannel: channel,\n\t\tacl: channel.ACL(),\n\t\tdb: self.db,\n\t}\n}\n\nfunc (self *pluginStruct) Name() string ", "output": "{\n\treturn \"custom_commands\"\n}"} {"input": "package transpose\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestTranspose(t *testing.T) {\n\tfor _, test := range testCases {\n\t\tactual := Transpose(test.input)\n\t\tif !reflect.DeepEqual(actual, test.expected) {\n\t\t\tif len(actual) == 0 || len(test.expected) == 0 {\n\t\t\t\tt.Fatalf(\"\\n\\tTranspose(%q): %s\\n\\n\\tExpected: %q\\n\\tGot: %q\",\n\t\t\t\t\ttest.input, test.description, test.expected, actual)\n\t\t\t}\n\t\t\tmin := min(len(test.expected), len(actual))\n\t\t\tfor i := 0; i < min; i++ {\n\t\t\t\tif test.expected[i] != actual[i] {\n\t\t\t\t\tt.Fatalf(\"\\n\\tTranspose(%q): %s\\n\\n\\tExpected: %q\\n\\tGot: %q\\n\\n\\tRow %d Expected: %q Got: %q\",\n\t\t\t\t\t\ttest.input, test.description, test.expected, actual, i, test.expected[i], actual[i])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n\n\nfunc BenchmarkTranspose(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, test := range testCases {\n\t\t\tTranspose(test.input)\n\t\t}\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n)\n\n\n\n\ntype CreateIpSecTunnelEncryptionDomainDetails struct {\n\n\tOracleTrafficSelector []string `mandatory:\"false\" json:\"oracleTrafficSelector\"`\n\n\tCpeTrafficSelector []string `mandatory:\"false\" json:\"cpeTrafficSelector\"`\n}\n\n\n\nfunc (m CreateIpSecTunnelEncryptionDomainDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package string_byte_array_converter\n\nimport (\n\t\"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/blevesearch/bleve/analysis\"\n\t\"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/blevesearch/bleve/registry\"\n)\n\ntype StringByteArrayConverter struct{}\n\nfunc NewStringByteArrayConverter() *StringByteArrayConverter {\n\treturn &StringByteArrayConverter{}\n}\n\n\n\nfunc Constructor(config map[string]interface{}, cache *registry.Cache) (analysis.ByteArrayConverter, error) {\n\treturn NewStringByteArrayConverter(), nil\n}\n\nfunc init() {\n\tregistry.RegisterByteArrayConverter(\"string\", Constructor)\n}\n\nfunc (c *StringByteArrayConverter) Convert(in []byte) (interface{}, error) ", "output": "{\n\treturn string(in), nil\n}"} {"input": "package plugins\n\nimport (\n\t\"fmt\"\n\t\"k8s.io/api/core/v1\"\n)\n\nconst (\n\tCinderDriverName = \"cinder.csi.openstack.org\"\n\tCinderInTreePluginName = \"kubernetes.io/cinder\"\n)\n\nvar _ InTreePlugin = (*osCinderCSITranslator)(nil)\n\n\ntype osCinderCSITranslator struct{}\n\n\nfunc NewOpenStackCinderCSITranslator() InTreePlugin {\n\treturn &osCinderCSITranslator{}\n}\n\n\n\nfunc (t *osCinderCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.Cinder == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or Cinder not defined on pv\")\n\t}\n\n\tcinderSource := pv.Spec.Cinder\n\n\tcsiSource := &v1.CSIPersistentVolumeSource{\n\t\tDriver: CinderDriverName,\n\t\tVolumeHandle: cinderSource.VolumeID,\n\t\tReadOnly: cinderSource.ReadOnly,\n\t\tFSType: cinderSource.FSType,\n\t\tVolumeAttributes: map[string]string{},\n\t}\n\n\tpv.Spec.Cinder = nil\n\tpv.Spec.CSI = csiSource\n\treturn pv, nil\n}\n\n\n\n\n\n\n\n\nfunc (t *osCinderCSITranslator) CanSupport(pv *v1.PersistentVolume) bool {\n\treturn pv != nil && pv.Spec.Cinder != nil\n}\n\n\nfunc (t *osCinderCSITranslator) GetInTreePluginName() string {\n\treturn CinderInTreePluginName\n}\n\nfunc (t *osCinderCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) ", "output": "{\n\tif pv == nil || pv.Spec.CSI == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or CSI source not defined on pv\")\n\t}\n\n\tcsiSource := pv.Spec.CSI\n\n\tcinderSource := &v1.CinderPersistentVolumeSource{\n\t\tVolumeID: csiSource.VolumeHandle,\n\t\tFSType: csiSource.FSType,\n\t\tReadOnly: csiSource.ReadOnly,\n\t}\n\n\tpv.Spec.CSI = nil\n\tpv.Spec.Cinder = cinderSource\n\treturn pv, nil\n}"} {"input": "package kmz\n\nimport (\n\t\"bytes\"\n\t\"log\"\n\n\t\"github.com/twpayne/go-kml\"\n)\n\n\n\nfunc ExampleNewKMZ() ", "output": "{\n\tkmz := NewKMZ(\n\t\tkml.Placemark(\n\t\t\tkml.Name(\"Simple placemark\"),\n\t\t\tkml.Description(\"Attached to the ground. Intelligently places itself at the height of the underlying terrain.\"),\n\t\t\tkml.Point(\n\t\t\t\tkml.Coordinates(kml.Coordinate{Lon: -122.0822035425683, Lat: 37.42228990140251}),\n\t\t\t),\n\t\t),\n\t)\n\tw := &bytes.Buffer{}\n\tif err := kmz.WriteIndent(w, \"\", \"\\t\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"testing\"\n)\n\nvar artifacts = []struct {\n\tin string\n\tout string\n}{\n\t{\"fixtures/virtualbox-ovf.json\", \"packer_virtualbox-ovf_virtualbox.vhd\"},\n\t{\"fixtures/virtualbox-ova.json\", \"packer_virtualbox-ova_virtualbox.vhd\"},\n}\n\n\n\n\nfunc TestIntegration(t *testing.T) {\n\tif err := os.Chdir(\"test\"); err != nil {\n\t\tt.Error(err)\n\t}\n\tfor _, tt := range artifacts {\n\t\tcmd := exec.Command(\"packer\", \"build\", \"--force\", tt.in)\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t\terr := cmd.Run()\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif _, err := os.Stat(tt.out); os.IsNotExist(err) {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n}\n\nfunc init() ", "output": "{\n\tcmd := exec.Command(\"packer\", \"build\", \"--force\", \"fixtures/virtualbox-iso.json\")\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"input": "package testutil\n\nimport (\n\t\"testing\"\n\n\tci \"gx/ipfs/QmP1DfoUjiWH2ZBo1PBH6FupdBucbDepx3HpWmEY6JMUpY/go-libp2p-crypto\"\n\tma \"gx/ipfs/QmcyqRMCAXVtYPS4DiBrA7sezL9rRGfW8Ctx7cywL4TXJj/go-multiaddr\"\n\tpeer \"gx/ipfs/QmdS9KpbDyPrieswibZhkod1oXqRwZJrUPzxCofAMWpFGq/go-libp2p-peer\"\n)\n\ntype Identity interface {\n\tAddress() ma.Multiaddr\n\tID() peer.ID\n\tPrivateKey() ci.PrivKey\n\tPublicKey() ci.PubKey\n}\n\n\n\nfunc RandIdentity() (Identity, error) {\n\tp, err := RandPeerNetParams()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &identity{*p}, nil\n}\n\nfunc RandIdentityOrFatal(t *testing.T) Identity {\n\tp, err := RandPeerNetParams()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn &identity{*p}\n}\n\n\ntype identity struct {\n\tPeerNetParams\n}\n\n\n\nfunc (p *identity) Address() ma.Multiaddr {\n\treturn p.Addr\n}\n\nfunc (p *identity) PrivateKey() ci.PrivKey {\n\treturn p.PrivKey\n}\n\nfunc (p *identity) PublicKey() ci.PubKey {\n\treturn p.PubKey\n}\n\nfunc (p *identity) ID() peer.ID ", "output": "{\n\treturn p.PeerNetParams.ID\n}"} {"input": "package framework\n\nimport \"github.com/onsi/gomega\"\n\n\nfunc ExpectEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.Equal(extra), explain...)\n}\n\n\nfunc ExpectNotEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).NotTo(gomega.Equal(extra), explain...)\n}\n\n\nfunc ExpectError(err error, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, err).To(gomega.HaveOccurred(), explain...)\n}\n\n\nfunc ExpectNoError(err error, explain ...interface{}) {\n\tExpectNoErrorWithOffset(1, err, explain...)\n}\n\n\n\nfunc ExpectNoErrorWithOffset(offset int, err error, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1+offset, err).NotTo(gomega.HaveOccurred(), explain...)\n}\n\n\nfunc ExpectConsistOf(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.ConsistOf(extra), explain...)\n}\n\n\n\n\n\nfunc ExpectEmpty(actual interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.BeEmpty(), explain...)\n}\n\nfunc ExpectHaveKey(actual interface{}, key interface{}, explain ...interface{}) ", "output": "{\n\tgomega.ExpectWithOffset(1, actual).To(gomega.HaveKey(key), explain...)\n}"} {"input": "package splitquery\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/youtube/vitess/go/vt/sqlparser\"\n\t\"github.com/youtube/vitess/go/vt/vttablet/tabletserver/querytypes\"\n\t\"github.com/youtube/vitess/go/vt/vttablet/tabletserver/schema\"\n)\n\nfunc Example() {\n\tschema := map[string]*schema.Table{}\n\tsplitParams, err := NewSplitParamsGivenSplitCount(\n\t\tquerytypes.BoundQuery{\n\t\t\tSql: \"SELECT * FROM table WHERE id > :id\",\n\t\t\tBindVariables: map[string]interface{}{\"id\": int64(5)},\n\t\t},\n\t\t[]sqlparser.ColIdent{\n\t\t\tsqlparser.NewColIdent(\"id\"),\n\t\t\tsqlparser.NewColIdent(\"user_id\"),\n\t\t}, \n\t\t1000, \n\t\tschema)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"NewSplitParamsGivenSplitCount failed with: %v\", err))\n\t}\n\n\talgorithm, err := NewFullScanAlgorithm(splitParams, getSQLExecuter())\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"NewFullScanAlgorithm failed with: %v\", err))\n\t}\n\n\tsplitter := NewSplitter(splitParams, algorithm)\n\n\tqueryParts, err := splitter.Split()\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"splitter.Split() failed with: %v\", err))\n\t}\n\tfmt.Println(queryParts)\n}\n\n\n\nfunc getSQLExecuter() SQLExecuter ", "output": "{\n\treturn nil\n}"} {"input": "package handlers\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/dgrijalva/jwt-go\"\n\t\"github.com/beacloudgenius/k8s/app/user\"\n\t\"golang.org/x/crypto/bcrypt\"\n)\n\ntype LoginResponse struct {\n\tToken string `json:\"token\"`\n}\n\ntype loginHandler struct {\n\tsecret string\n\tusers user.Users\n}\n\nfunc (h *loginHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tusername, password, ok := r.BasicAuth()\n\tif !ok {\n\t\thttp.Error(w, \"authorization failed\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tuser, ok := h.users[username]\n\tif !ok {\n\t\thttp.Error(w, \"authorization failed\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\terr := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password))\n\tif err != nil {\n\t\thttp.Error(w, \"authorization failed\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\ttoken := jwt.New(jwt.SigningMethodHS256)\n\ttoken.Claims[\"exp\"] = time.Now().Add(time.Hour * 72).Unix()\n\ttoken.Claims[\"iss\"] = \"auth.service\"\n\ttoken.Claims[\"iat\"] = time.Now().Unix()\n\ttoken.Claims[\"email\"] = user.Email\n\ttoken.Claims[\"sub\"] = user.Username\n\n\ttokenString, err := token.SignedString([]byte(h.secret))\n\tif err != nil {\n\t\thttp.Error(w, \"authorization failed\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tresponse := LoginResponse{\n\t\tToken: tokenString,\n\t}\n\tjson.NewEncoder(w).Encode(response)\n}\n\n\n\nfunc LoginHandler(secret string, users user.Users) http.Handler ", "output": "{\n\treturn &loginHandler{\n\t\tsecret: secret,\n\t\tusers: users,\n\t}\n}"} {"input": "package ratelimiter\n\nimport \"time\"\n\nvar domainLimitMap = make(map[string]*Limiter)\n\n\ntype Limiter struct {\n\tnextChan chan bool\n\tapiLimit time.Duration\n}\n\n\n\n\nfunc (limiter *Limiter) next() {\n\tgo func(l *Limiter) {\n\t\tticker := time.NewTimer(l.apiLimit)\n\t\t<-ticker.C\n\t\tticker.Stop()\n\t\tl.nextChan <- true\n\t}(limiter)\n}\n\n\nfunc (limiter *Limiter) Wait() {\n\t<-limiter.nextChan\n\tlimiter.next()\n}\n\nfunc New(domain string, apiLimit time.Duration) *Limiter ", "output": "{\n\tif _, ok := domainLimitMap[domain]; !ok {\n\t\tdomainLimitMap[domain] = &Limiter{\n\t\t\tnextChan: make(chan bool),\n\t\t\tapiLimit: apiLimit,\n\t\t}\n\t\tdomainLimitMap[domain].next()\n\t}\n\treturn domainLimitMap[domain]\n}"} {"input": "package driver\n\nimport \"database/sql/driver\"\n\nvar _ driver.Tx = tx{}\n\ntype tx struct {\n\tconn *conn\n}\n\nfunc (t tx) Commit() error {\n\t_, err := t.conn.Exec(\"COMMIT TRANSACTION\", nil)\n\treturn err\n}\n\n\n\nfunc (t tx) Rollback() error ", "output": "{\n\t_, err := t.conn.Exec(\"ROLLBACK TRANSACTION\", nil)\n\treturn err\n}"} {"input": "package operator\n\nimport (\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/openshift/library-go/pkg/controller/controllercmd\"\n\t\"github.com/openshift/service-serving-cert-signer/pkg/operator\"\n\t\"github.com/openshift/service-serving-cert-signer/pkg/version\"\n)\n\n\n\nfunc NewOperator() *cobra.Command ", "output": "{\n\tcmd := controllercmd.\n\t\tNewControllerCommandConfig(\"openshift-service-cert-signer-operator\", version.Get(), operator.RunOperator).\n\t\tNewCommand()\n\tcmd.Use = \"operator\"\n\tcmd.Short = \"Start the Service Cert Signer Operator\"\n\n\treturn cmd\n}"} {"input": "package api\n\n\ntype OptionKey string\n\nconst (\n\tOptName = OptionKey(\"Name\")\n\tOptVolumeID = OptionKey(\"VolumeID\")\n\tOptLabel = OptionKey(\"Label\")\n\tOptConfigLabel = OptionKey(\"ConfigLabel\")\n)\n\n\n\n\n\n\n\n\ntype GraphDriverChanges struct {\n\tPath string \n\tKind int\n}\n\n\ntype VolumeCreateRequest struct {\n\tLocator VolumeLocator `json:\"locator\"`\n\tSource *Source `json:\"source,omitempty\"`\n\tSpec *VolumeSpec `json:\"spec,omitempty\"`\n}\n\n\ntype VolumeCreateResponse struct {\n\tID VolumeID `json:\"id\"`\n\tVolumeResponse\n}\n\n\ntype VolumeActionParam int\n\nconst (\n\tParamIgnore VolumeActionParam = iota\n\tParamOff\n\tParamOn\n)\n\n\ntype VolumeStateAction struct {\n\tAttach VolumeActionParam `json:\"attach\"`\n\tMount VolumeActionParam `json:\"mount\"`\n\tMountPath string `json:\"mount_path\"`\n\tDevicePath string `json:\"device_path\"`\n}\n\ntype VolumeSetRequest struct {\n\tLocator *VolumeLocator `json:\"locator,omitempty\"`\n\tSpec *VolumeSpec `json:\"spec,omitempty\"`\n\tAction *VolumeStateAction `json:\"action,omitempty\"`\n}\n\n\ntype VolumeSetResponse struct {\n\tVolume\n\tVolumeResponse\n}\n\n\ntype VolumeResponse struct {\n\tError string `json:\"error\"`\n}\n\n\ntype SnapCreateRequest struct {\n\tID VolumeID `json:\"id\"`\n\tLocator VolumeLocator `json:\"locator\"`\n\tReadonly bool `json:\"readonly\"`\n}\n\n\ntype SnapCreateResponse struct {\n\tVolumeCreateResponse\n}\n\n\n\n\nfunc ResponseStatusNew(err error) VolumeResponse ", "output": "{\n\tif err == nil {\n\t\treturn VolumeResponse{}\n\t}\n\treturn VolumeResponse{Error: err.Error()}\n}"} {"input": "package servicelabel\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/namsral/flag\"\n\n\t\"go.ligato.io/cn-infra/v2/infra\"\n\t\"go.ligato.io/cn-infra/v2/logging/logrus\"\n)\n\nvar microserviceLabelFlag string\n\nfunc init() {\n\tflag.StringVar(µserviceLabelFlag, \"microservice-label\", \"vpp1\", fmt.Sprintf(\"microservice label; also set via '%v' env variable.\", MicroserviceLabelEnvVar))\n}\n\n\ntype Plugin struct {\n\tinfra.PluginName\n\tMicroserviceLabel string\n}\n\n\nfunc (p *Plugin) Init() error {\n\tif p.MicroserviceLabel == \"\" {\n\t\tp.MicroserviceLabel = microserviceLabelFlag\n\t}\n\tlogrus.DefaultLogger().Debugf(\"Microservice label is set to %v\", p.MicroserviceLabel)\n\treturn nil\n}\n\n\nfunc (p *Plugin) Close() error {\n\treturn nil\n}\n\n\n\nfunc (p *Plugin) GetAgentLabel() string {\n\treturn p.MicroserviceLabel\n}\n\n\n\n\n\n\n\nfunc (p *Plugin) GetDifferentAgentPrefix(microserviceLabel string) string {\n\treturn GetDifferentAgentPrefix(microserviceLabel)\n}\n\n\n\nfunc (p *Plugin) GetAllAgentsPrefix() string {\n\treturn GetAllAgentsPrefix()\n}\n\nfunc (p *Plugin) GetAgentPrefix() string ", "output": "{\n\treturn agentPrefix + p.MicroserviceLabel + \"/\"\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com/onsi/gomega/format\"\n)\n\ntype BeElementOfMatcher struct {\n\tElements []interface{}\n}\n\n\n\nfunc (matcher *BeElementOfMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"to be an element of\", presentable(matcher.Elements))\n}\n\nfunc (matcher *BeElementOfMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"not to be an element of\", presentable(matcher.Elements))\n}\n\nfunc (matcher *BeElementOfMatcher) Match(actual interface{}) (success bool, err error) ", "output": "{\n\tif reflect.TypeOf(actual) == nil {\n\t\treturn false, fmt.Errorf(\"BeElement matcher expects actual to be typed\")\n\t}\n\n\tvar lastError error\n\tfor _, m := range flatten(matcher.Elements) {\n\t\tmatcher := &EqualMatcher{Expected: m}\n\t\tsuccess, err := matcher.Match(actual)\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\tcontinue\n\t\t}\n\t\tif success {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, lastError\n}"} {"input": "package datastore\n\nimport (\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/01org/ciao/openstack/image\"\n)\n\n\ntype State string\n\nconst (\n\tCreated State = \"created\"\n\n\tSaving State = \"saving\"\n\n\tActive State = \"active\"\n\n\tKilled State = \"killed\"\n)\n\n\nfunc (state State) Status() image.Status {\n\tswitch state {\n\tcase Created:\n\t\treturn image.Queued\n\tcase Saving:\n\t\treturn image.Saving\n\tcase Active:\n\t\treturn image.Active\n\tcase Killed:\n\t\treturn image.Killed\n\t}\n\n\treturn image.Active\n}\n\n\n\n\n\ntype Type string\n\nconst (\n\tRaw Type = \"raw\"\n\n\tQCow Type = \"qcow2\"\n\n\tISO Type = \"iso\"\n)\n\n\ntype Image struct {\n\tID string\n\tState State\n\tTenantID string\n\tName string\n\tCreateTime time.Time\n\tType Type\n\tSize uint64\n}\n\n\ntype DataStore interface {\n\tInit(RawDataStore, MetaDataStore) error\n\tCreateImage(Image) error\n\tGetAllImages() ([]Image, error)\n\tGetImage(string) (Image, error)\n\tUpdateImage(Image) error\n\tDeleteImage(string) error\n\tUploadImage(string, io.Reader) error\n}\n\n\n\ntype MetaDataStore interface {\n\tWrite(Image) error\n\tDelete(ID string) error\n\tGet(ID string) (Image, error)\n\tGetAll() ([]Image, error)\n}\n\n\n\ntype RawDataStore interface {\n\tWrite(ID string, body io.Reader) error\n\tDelete(ID string) error\n\tGetImageSize(ID string) (uint64, error)\n}\n\nfunc (i Image) Visibility() image.Visibility ", "output": "{\n\tif i.TenantID == \"\" {\n\t\treturn image.Public\n\t}\n\treturn image.Private\n}"} {"input": "package downloader\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"launchpad.net/juju-core/log\"\n\t\"launchpad.net/tomb\"\n\t\"net/http\"\n\t\"os\"\n)\n\n\ntype Status struct {\n\tFile *os.File\n\tErr error\n}\n\n\ntype Download struct {\n\ttomb tomb.Tomb\n\tdone chan Status\n}\n\n\n\nfunc New(url, dir string) *Download {\n\td := &Download{\n\t\tdone: make(chan Status),\n\t}\n\tgo d.run(url, dir)\n\treturn d\n}\n\n\nfunc (d *Download) Stop() {\n\td.tomb.Kill(nil)\n\td.tomb.Wait()\n}\n\n\n\n\nfunc (d *Download) Done() <-chan Status {\n\treturn d.done\n}\n\nfunc (d *Download) run(url, dir string) {\n\tdefer d.tomb.Done()\n\tfile, err := download(url, dir)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"cannot download %q: %v\", url, err)\n\t}\n\tstatus := Status{\n\t\tFile: file,\n\t\tErr: err,\n\t}\n\tselect {\n\tcase d.done <- status:\n\tcase <-d.tomb.Dying():\n\t\tcleanTempFile(status.File)\n\t}\n}\n\n\n\nfunc cleanTempFile(f *os.File) {\n\tif f != nil {\n\t\tf.Close()\n\t\tif err := os.Remove(f.Name()); err != nil {\n\t\t\tlog.Printf(\"downloader: cannot remove temp file %q: %v\", f.Name(), err)\n\t\t}\n\t}\n}\n\nfunc download(url, dir string) (file *os.File, err error) ", "output": "{\n\tif dir == \"\" {\n\t\tdir = os.TempDir()\n\t}\n\ttempFile, err := ioutil.TempFile(dir, \"inprogress-\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tcleanTempFile(tempFile)\n\t\t}\n\t}()\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"bad http response: %v\", resp.Status)\n\t}\n\t_, err = io.Copy(tempFile, resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err := tempFile.Seek(0, 0); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tempFile, nil\n}"} {"input": "package main\n\n\n\nfunc if_stmts() ", "output": "{\n\tvar x string\n\tif x = x; true {\n\t\tprint((x+1)/5)\n\t} else {\n\t\treturn\n\t}\n}"} {"input": "package store\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\n\t\"gopkg.in/oauth2.v3\"\n)\n\nfunc NewClientStore() *ClientStore {\n\treturn &ClientStore{\n\t\tdata: make(map[string]oauth2.ClientInfo),\n\t}\n}\n\n\ntype ClientStore struct {\n\tsync.RWMutex\n\tdata map[string]oauth2.ClientInfo\n}\n\n\n\n\n\nfunc (cs *ClientStore) Set(id string, cli oauth2.ClientInfo) (err error) {\n\tcs.Lock()\n\tdefer cs.Unlock()\n\tcs.data[id] = cli\n\treturn\n}\n\nfunc (cs *ClientStore) GetByID(id string) (cli oauth2.ClientInfo, err error) ", "output": "{\n\tcs.RLock()\n\tdefer cs.RUnlock()\n\tif c, ok := cs.data[id]; ok {\n\t\tcli = c\n\t\treturn\n\t}\n\terr = errors.New(\"not found\")\n\treturn\n}"} {"input": "package console\n\nimport (\n\t\"os\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\nimport \"C\"\n\nconst (\n\tcmdTcGet = unix.TCGETS\n\tcmdTcSet = unix.TCSETS\n)\n\n\n\n\n\n\nfunc unlockpt(f *os.File) error {\n\tif _, err := C.grantpt(C.int(f.Fd())); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc ptsname(f *os.File) (string, error) ", "output": "{\n\tptspath, err := C.ptsname(C.int(f.Fd()))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn C.GoString(ptspath), nil\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListLocalPeeringGatewaysRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tVcnId *string `mandatory:\"false\" contributesTo:\"query\" name:\"vcnId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListLocalPeeringGatewaysRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListLocalPeeringGatewaysRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\n\n\n\nfunc (request ListLocalPeeringGatewaysRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListLocalPeeringGatewaysResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []LocalPeeringGateway `presentIn:\"body\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ListLocalPeeringGatewaysResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListLocalPeeringGatewaysResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListLocalPeeringGatewaysRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package musicserver\n\nimport (\n\t\"net/http\"\n\t\"time\"\n)\n\n\n\nfunc adminLoginHandler(w http.ResponseWriter, req *http.Request) {\n\tif req.Method != http.MethodPost {\n\t\ttl.Render(w, \"admin_login\", nil)\n\t\treturn\n\t}\n\n\tip := getIPFromRequest(req)\n\tpwd := req.PostFormValue(\"admin_pwd\")\n\tif ad.ValidPassword(pwd) {\n\t\tad.StartSession(ip)\n\t\thttp.Redirect(w, req, url(\"/admin\"), http.StatusSeeOther)\n\t\treturn\n\t} else {\n\t\ttl.Render(w, \"admin_bad_login\", nil)\n\t\treturn\n\t}\n}\n\nfunc adminLogoutHandler(w http.ResponseWriter, req *http.Request) {\n\tip := getIPFromRequest(req)\n\tad.EndSession(ip)\n\thttp.Redirect(w, req, url(\"/\"), http.StatusSeeOther)\n}\n\nfunc adminRemoveHandler(w http.ResponseWriter, req *http.Request) {\n\tip := getIPFromRequest(req)\n\tif req.Method == http.MethodPost && ad.ValidSession(ip) {\n\t\tremUUID := req.PostFormValue(\"video_id\")\n\t\tpl.RemoveVideo(remUUID)\n\t}\n\thttp.Redirect(w, req, url(\"/admin\"), http.StatusSeeOther)\n}\n\nfunc adminKillVideoHandler(w http.ResponseWriter, req *http.Request) {\n\tip := getIPFromRequest(req)\n\tif !ad.ValidSession(ip) {\n\t\thttp.Redirect(w, req, url(\"/admin/login\"), http.StatusFound)\n\t\treturn\n\t}\n\n\tvd.End()\n\ttime.Sleep(500 * time.Millisecond)\n\n\thttp.Redirect(w, req, url(\"/admin\"), http.StatusFound)\n}\n\nfunc adminHandler(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tip := getIPFromRequest(req)\n\n\tif ad.ValidSession(ip) {\n\t\ttl.Render(w, \"admin\", newPlaylistInfo(ip))\n\t} else {\n\t\thttp.Redirect(w, req, url(\"/admin/login\"), http.StatusFound)\n\t}\n}"} {"input": "package executedconditionals\n\n\n\nfunc b() string {\n\treturn \"B\"\n}\n\nfunc c() string {\n\treturn \"C\"\n}\n\nfunc wrapper(condition bool) {\n\ta(condition)\n\tb()\n\tc()\n}\n\nfunc a(condition bool) string ", "output": "{\n\tif condition {\n\t\treturn \"A\"\n\t}\n\treturn \"A\"\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfmt.Println(Hello())\n}\n\n\nfunc Hello() string {\n\treturn \"Hello \" + user()\n}\n\n\n\n\nfunc user() string ", "output": "{\n\tuser := os.Getenv(\"USER\")\n\tif user == \"\" {\n\t\tuser = os.Getenv(\"USERNAME\")\n\t}\n\tif user == \"\" {\n\t\tuser = \"stranger\"\n\t}\n\treturn user\n}"} {"input": "package edit_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestEdit(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Edit Suite\")\n}"} {"input": "package openweathermap\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\n\nvar StationDataParameters = []string{\n\t\"wind_dir\", \n\t\"wind_speed\", \n\t\"wind_gust\", \n\t\"temp\", \n\t\"humidity\", \n\t\"pressure\", \n\t\"rain_1h\", \n\t\"rain_24h\", \n\t\"rain_today\", \n\t\"snow\", \n\t\"lum\", \n\t\"lat\", \n\t\"long\", \n\t\"alt\", \n\t\"radiation\", \n\t\"dewpoint\", \n\t\"uv\", \n\t\"name\", \n}\n\n\n\n\n\n\n\n\nfunc ConvertToURLValues(data map[string]string) string {\n\tv := url.Values{}\n\n\tfor key, val := range data {\n\t\tv.Set(key, val)\n\t}\n\n\treturn v.Encode()\n}\n\n\n\nfunc SendStationData(data url.Values) {\n\tresp, err := http.PostForm(dataPostURL, data)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tfmt.Println(resp.Body)\n}\n\nfunc ValidateStationDataParameter(param string) bool ", "output": "{\n\tfor _, p := range StationDataParameters {\n\t\tif param == p {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package runtime\n\nimport \"unsafe\"\n\n\n\n\n\n\nfunc atomicload(ptr *uint32) uint32 {\n\tnop()\n\treturn *ptr\n}\n\n\nfunc atomicloadp(ptr unsafe.Pointer) unsafe.Pointer {\n\tnop()\n\treturn *(*unsafe.Pointer)(ptr)\n}\n\n\nfunc xadd64(ptr *uint64, delta int64) uint64 {\n\tfor {\n\t\told := *ptr\n\t\tif cas64(ptr, old, old+uint64(delta)) {\n\t\t\treturn old + uint64(delta)\n\t\t}\n\t}\n}\n\n\n\n\n\nfunc xadd(ptr *uint32, delta int32) uint32\n\n\nfunc xchg(ptr *uint32, new uint32) uint32\n\n\nfunc xchgp1(ptr unsafe.Pointer, new unsafe.Pointer) unsafe.Pointer\n\n\nfunc xchguintptr(ptr *uintptr, new uintptr) uintptr\n\n\nfunc atomicload64(ptr *uint64) uint64\n\n\nfunc atomicor8(ptr *uint8, val uint8)\n\n\nfunc cas64(ptr *uint64, old, new uint64) bool\n\n\nfunc atomicstore(ptr *uint32, val uint32)\n\n\nfunc atomicstore64(ptr *uint64, val uint64)\n\n\nfunc atomicstorep1(ptr unsafe.Pointer, val unsafe.Pointer)\n\nfunc xchg64(ptr *uint64, new uint64) uint64 ", "output": "{\n\tfor {\n\t\told := *ptr\n\t\tif cas64(ptr, old, new) {\n\t\t\treturn old\n\t\t}\n\t}\n}"} {"input": "package http\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/Cepave/open-falcon-backend/modules/transfer/g\"\n\tlog \"github.com/sirupsen/logrus\"\n\t\"net/http\"\n\t_ \"net/http/pprof\"\n)\n\ntype Dto struct {\n\tMsg string `json:\"msg\"`\n\tData interface{} `json:\"data\"`\n}\n\nfunc Start() {\n\tgo startHttpServer()\n}\nfunc startHttpServer() {\n\tif !g.Config().Http.Enabled {\n\t\treturn\n\t}\n\n\taddr := g.Config().Http.Listen\n\tif addr == \"\" {\n\t\treturn\n\t}\n\n\tconfigCommonRoutes()\n\tconfigProcHttpRoutes()\n\tconfigDebugHttpRoutes()\n\tconfigApiHttpRoutes()\n\n\ts := &http.Server{\n\t\tAddr: addr,\n\t\tMaxHeaderBytes: 1 << 30,\n\t}\n\n\tlog.Println(\"http.startHttpServer ok, listening\", addr)\n\tlog.Fatalln(s.ListenAndServe())\n}\n\nfunc RenderJson(w http.ResponseWriter, v interface{}) {\n\tbs, err := json.Marshal(v)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.Write(bs)\n}\n\n\n\nfunc RenderMsgJson(w http.ResponseWriter, msg string) {\n\tRenderJson(w, map[string]string{\"msg\": msg})\n}\n\nfunc AutoRender(w http.ResponseWriter, data interface{}, err error) {\n\tif err != nil {\n\t\tRenderMsgJson(w, err.Error())\n\t\treturn\n\t}\n\tRenderDataJson(w, data)\n}\n\nfunc RenderDataJson(w http.ResponseWriter, data interface{}) ", "output": "{\n\tRenderJson(w, Dto{Msg: \"success\", Data: data})\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype DeleteVolumeBackupPolicyRequest struct {\n\n\tPolicyId *string `mandatory:\"true\" contributesTo:\"path\" name:\"policyId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteVolumeBackupPolicyRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request DeleteVolumeBackupPolicyRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteVolumeBackupPolicyResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteVolumeBackupPolicyResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteVolumeBackupPolicyResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteVolumeBackupPolicyRequest) HTTPRequest(method, path string) (http.Request, error) ", "output": "{\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}"} {"input": "package log\n\nimport (\n\t\"sync\"\n\n\t\"github.com/asim/go-micro/v3/util/ring\"\n\t\"github.com/google/uuid\"\n)\n\n\ntype osLog struct {\n\tformat FormatFunc\n\tonce sync.Once\n\n\tsync.RWMutex\n\tbuffer *ring.Buffer\n\tsubs map[string]*osStream\n}\n\ntype osStream struct {\n\tstream chan Record\n}\n\n\nfunc (o *osLog) Read(...ReadOption) ([]Record, error) {\n\tvar records []Record\n\n\tfor _, v := range o.buffer.Get(100) {\n\t\trecords = append(records, v.Value.(Record))\n\t}\n\n\treturn records, nil\n}\n\n\nfunc (o *osLog) Write(r Record) error {\n\to.buffer.Put(r)\n\treturn nil\n}\n\n\nfunc (o *osLog) Stream() (Stream, error) {\n\to.Lock()\n\tdefer o.Unlock()\n\n\tst := &osStream{\n\t\tstream: make(chan Record, 128),\n\t}\n\n\to.subs[uuid.New().String()] = st\n\n\treturn st, nil\n}\n\nfunc (o *osStream) Chan() <-chan Record {\n\treturn o.stream\n}\n\n\n\nfunc NewLog(opts ...Option) Log {\n\toptions := Options{\n\t\tFormat: DefaultFormat,\n\t}\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\tl := &osLog{\n\t\tformat: options.Format,\n\t\tbuffer: ring.New(1024),\n\t\tsubs: make(map[string]*osStream),\n\t}\n\n\treturn l\n}\n\nfunc (o *osStream) Stop() error ", "output": "{\n\treturn nil\n}"} {"input": "package tika\n\nimport (\n\t\"github.com/c2h5oh/datasize\"\n\t\"time\"\n)\n\n\ntype Config struct {\n\tTikaExtractorURL string \n\tRequestTimeout time.Duration \n\tMaxFileSize datasize.ByteSize \n}\n\n\n\n\nfunc DefaultConfig() *Config ", "output": "{\n\treturn &Config{\n\t\tTikaExtractorURL: \"http://localhost:8081\",\n\t\tRequestTimeout: 300 * time.Duration(time.Second),\n\t\tMaxFileSize: 4 * 1024 * 1024 * 1024, \n\t}\n}"} {"input": "package osv\n\nimport (\n\t\"time\"\n\n\t\"github.com/intelsdi-x/snap/control/plugin\"\n\t\"github.com/intelsdi-x/snap/core\"\n)\n\nfunc cpuStat(ns core.Namespace, swagURL string) (*plugin.MetricType, error) {\n\tmetric, err := getCPUTime(swagURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &plugin.MetricType{\n\t\tNamespace_: ns,\n\t\tData_: metric,\n\t\tTimestamp_: time.Now(),\n\t}, nil\n}\n\n\n\nfunc getCPUTime(swagURL string) (uint64, error) {\n\tpath := \"trace/count\"\n\tresponse, err := osvRestGet(swagURL, path)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tcounters, err := osvRestUnmarshall(response)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn counters.TimeMs, nil\n}\n\nfunc getCPUMetricTypes() ([]plugin.MetricType, error) ", "output": "{\n\tvar mts []plugin.MetricType\n\tfor _, metricType := range cpuMetrics {\n\t\tmts = append(mts, plugin.MetricType{Namespace_: core.NewNamespace(Vendor, Name, \"cpu\", metricType)})\n\t}\n\treturn mts, nil\n}"} {"input": "package main\n\nimport (\n\t\"html/template\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype Page struct {\n\tTitle string\n\tBody []byte\n}\n\nfunc (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}\n\nfunc loadPage(title string) (*Page, error) {\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Page{Title: title, Body: body}, nil\n}\n\nfunc editHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/edit/\"):]\n\tp, err := loadPage(title)\n\tif err != nil {\n\t\tp = &Page{Title: title}\n\t}\n\trenderTemplate(w, \"edit\", p)\n}\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/view/\"):]\n\tp, _ := loadPage(title)\n\trenderTemplate(w, \"view\", p)\n}\n\nfunc saveHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/save/\"):]\n\tbody := r.FormValue(\"body\")\n\tp := &Page{Title: title, Body: []byte(body)}\n\tp.save()\n\thttp.Redirect(w, r, \"/view/\"+title, http.StatusFound)\n}\n\n\n\nfunc main() {\n\thttp.HandleFunc(\"/view/\", viewHandler)\n\thttp.HandleFunc(\"/edit/\", editHandler)\n\thttp.HandleFunc(\"/save/\", saveHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc renderTemplate(w http.ResponseWriter, tmpl string, p *Page) ", "output": "{\n\tt, _ := template.ParseFiles(tmpl + \".html\")\n\tt.Execute(w, p)\n}"} {"input": "package cabf_br\n\n\n\nimport (\n\t\"testing\"\n\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/test\"\n)\n\n\n\nfunc TestCertPolicyOvNoCountryOrLocal(t *testing.T) {\n\tinputPath := \"orgValNoProvinceOrLocal.pem\"\n\texpected := lint.Error\n\tout := test.TestLint(\"e_cert_policy_ov_requires_province_or_locality\", inputPath)\n\tif out.Status != expected {\n\t\tt.Errorf(\"%s: expected %s, got %s\", inputPath, expected, out.Status)\n\t}\n}\n\nfunc TestCertPolicyOvHasCountryOrLocal(t *testing.T) ", "output": "{\n\tinputPath := \"orgValGoodAllFields.pem\"\n\texpected := lint.Pass\n\tout := test.TestLint(\"e_cert_policy_ov_requires_province_or_locality\", inputPath)\n\tif out.Status != expected {\n\t\tt.Errorf(\"%s: expected %s, got %s\", inputPath, expected, out.Status)\n\t}\n}"} {"input": "package api\n\n\ntype UserInfo interface {\n\tGetName() string\n\tGetUID() string\n\tGetScope() string\n\tGetExtra() map[string]string\n}\n\n\n\ntype UserIdentityInfo interface {\n\tGetUserName() string\n\tGetProviderName() string\n\tGetExtra() map[string]string\n}\n\n\ntype UserIdentityMapper interface {\n\tUserFor(identityInfo UserIdentityInfo) (UserInfo, error)\n}\n\ntype Client interface {\n\tGetId() string\n\tGetSecret() string\n\tGetRedirectUri() string\n\tGetUserData() interface{}\n}\n\ntype Grant struct {\n\tClient Client\n\tScope string\n\tExpiration int64\n\tRedirectURI string\n}\n\ntype DefaultUserInfo struct {\n\tName string\n\tUID string\n\tScope string\n\tExtra map[string]string\n}\n\nfunc (i *DefaultUserInfo) GetName() string {\n\treturn i.Name\n}\n\n\n\nfunc (i *DefaultUserInfo) GetScope() string {\n\treturn i.Scope\n}\n\nfunc (i *DefaultUserInfo) GetExtra() map[string]string {\n\treturn i.Extra\n}\n\ntype DefaultUserIdentityInfo struct {\n\tUserName string\n\tProviderName string\n\tExtra map[string]string\n}\n\n\nfunc NewDefaultUserIdentityInfo(username string) DefaultUserIdentityInfo {\n\treturn DefaultUserIdentityInfo{\n\t\tUserName: username,\n\t\tExtra: make(map[string]string),\n\t}\n}\n\nfunc (i *DefaultUserIdentityInfo) GetUserName() string {\n\treturn i.UserName\n}\n\nfunc (i *DefaultUserIdentityInfo) GetProviderName() string {\n\treturn i.ProviderName\n}\n\nfunc (i *DefaultUserIdentityInfo) GetExtra() map[string]string {\n\treturn i.Extra\n}\n\nfunc (i *DefaultUserInfo) GetUID() string ", "output": "{\n\treturn i.UID\n}"} {"input": "package main\n\nvar y int = 1\n\n\nfunc switch_stmts() ", "output": "{\n\tswitch {\n\tcase y < 0: print(\"string\" + 3)\n\tcase y > 0: print(4+1)\n\tdefault: \"zero\"\n\t}\n}"} {"input": "package daemon\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/docker/docker/api/types/swarm\"\n\t\"gotest.tools/assert\"\n)\n\n\ntype ConfigConstructor func(*swarm.Config)\n\n\nfunc (d *Daemon) CreateConfig(t testing.TB, configSpec swarm.ConfigSpec) string {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tscr, err := cli.ConfigCreate(context.Background(), configSpec)\n\tassert.NilError(t, err)\n\treturn scr.ID\n}\n\n\n\n\n\nfunc (d *Daemon) GetConfig(t testing.TB, id string) *swarm.Config {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tconfig, _, err := cli.ConfigInspectWithRaw(context.Background(), id)\n\tassert.NilError(t, err)\n\treturn &config\n}\n\n\nfunc (d *Daemon) DeleteConfig(t testing.TB, id string) {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\terr := cli.ConfigRemove(context.Background(), id)\n\tassert.NilError(t, err)\n}\n\n\n\nfunc (d *Daemon) UpdateConfig(t testing.TB, id string, f ...ConfigConstructor) {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tconfig := d.GetConfig(t, id)\n\tfor _, fn := range f {\n\t\tfn(config)\n\t}\n\n\terr := cli.ConfigUpdate(context.Background(), config.ID, config.Version, config.Spec)\n\tassert.NilError(t, err)\n}\n\nfunc (d *Daemon) ListConfigs(t testing.TB) []swarm.Config ", "output": "{\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tconfigs, err := cli.ConfigList(context.Background(), types.ConfigListOptions{})\n\tassert.NilError(t, err)\n\treturn configs\n}"} {"input": "package schema\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc dataSourceResourceShimAdjustSchema(schema map[string]*Schema) {\n\tfor _, s := range schema {\n\t\tif s.Required || s.Optional {\n\t\t\ts.ForceNew = true\n\t\t}\n\n\t\tif s.Elem != nil {\n\t\t\tif r, ok := s.Elem.(*Resource); ok {\n\t\t\t\tdataSourceResourceShimAdjustSchema(r.Schema)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc DataSourceResourceShim(name string, dataSource *Resource) *Resource ", "output": "{\n\tdataSourceResourceShimAdjustSchema(dataSource.Schema)\n\n\tdataSource.Create = CreateFunc(dataSource.Read)\n\tdataSource.Delete = func(d *ResourceData, meta interface{}) error {\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\tdataSource.Update = nil \n\n\tdataSource.DeprecationMessage = fmt.Sprintf(\n\t\t\"using %s as a resource is deprecated; consider using the data source instead\",\n\t\tname,\n\t)\n\n\treturn dataSource\n}"} {"input": "package virtcontainers\n\nimport \"fmt\"\n\ntype bridgeType string\n\nconst (\n\tpciBridge bridgeType = \"pci\"\n\tpcieBridge = \"pcie\"\n)\n\nconst pciBridgeMaxCapacity = 30\n\n\ntype Bridge struct {\n\tAddress map[uint32]string\n\n\tType bridgeType\n\n\tID string\n}\n\n\n\nfunc (b *Bridge) addDevice(ID string) (uint32, error) {\n\tvar addr uint32\n\n\tfor i := uint32(1); i <= pciBridgeMaxCapacity; i++ {\n\t\tif _, ok := b.Address[i]; !ok {\n\t\t\taddr = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif addr == 0 {\n\t\treturn 0, fmt.Errorf(\"Unable to hot plug device on bridge: there are not empty slots\")\n\t}\n\n\tb.Address[addr] = ID\n\treturn addr, nil\n}\n\n\n\n\n\nfunc (b *Bridge) removeDevice(ID string) error ", "output": "{\n\tfor addr, devID := range b.Address {\n\t\tif devID == ID {\n\t\t\tdelete(b.Address, addr)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"Unable to hot unplug device %s: not present on bridge\", ID)\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc max(vals ...int) (result int, ok bool) {\n\tif len(vals) == 0 {\n\t\treturn\n\t}\n\tok = true\n\n\tresult = vals[0]\n\tfor _, val := range vals[1:] {\n\t\tif result < val {\n\t\t\tresult = val\n\t\t}\n\t}\n\treturn\n}\n\nfunc main() {\n\tfmt.Println(min(5, 6, 2, 4, 1, 0))\n\tfmt.Println(min(5, 6, 2, 4, 1, 0))\n}\n\nfunc min(vals ...int) (result int, ok bool) ", "output": "{\n\tif len(vals) == 0 {\n\t\treturn\n\t}\n\tok = true\n\n\tresult = vals[0]\n\tfor _, val := range vals[1:] {\n\t\tif result > val {\n\t\t\tresult = val\n\t\t}\n\t}\n\treturn\n}"} {"input": "package workshop\n\nimport (\n\t\"math\"\n)\n\n\ntype Shape interface {\n\tarea()\n\tcircumference()\n\tvolume()\n}\n\n\ntype Circle struct {\n\tradius float64\n\tPI float64\n}\n\nfunc (circle *Circle) area() float64 {\n\treturn circle.PI * math.Pow(circle.radius, 2)\n}\n\nfunc (circle *Circle) circumference() float64 {\n\treturn 2 * circle.PI * circle.radius\n}\n\n\ntype Square struct {\n\tside float64\n}\n\nfunc (square *Square) area() float64 {\n\treturn math.Pow(square.side, 2)\n}\n\ntype Sphere struct {\n\tPI float64\n\tradius float64\n}\n\nfunc (sphere *Sphere) volume() float64 {\n\treturn (4 / 3) * sphere.PI * math.Pow(sphere.radius, 3)\n}\n\n\ntype Cube struct {\n\tside float64\n}\n\n\n\nfunc (square *Square) volume() float64 {\n\treturn math.Pow(square.side, 3)\n}\n\n\ntype Rectangle struct {\n\theight int\n\twidth int\n}\n\nfunc (rectangle *Rectangle) area() int {\n\treturn rectangle.height * rectangle.width\n}\n\nfunc interfaces() {\n\tcircle := Circle{radius: 5.5, PI: math.Pi}\n\tareaOfCircle := circle.area()\n\n\tassert(areaOfCircle == 55)\n\tassert(circle.circumference() == 88)\n\n\tvar square = Square{5}\n\tassert(square.area() == 36)\n\n\tcube := new(Cube)\n\tassert(cube.volume() == 8)\n\n\tvar rectangle = Rectangle{width: 4, height: 5}\n\tassert(rectangle.area() == 2)\n}\n\nfunc (cube *Cube) volume() float64 ", "output": "{\n\treturn math.Pow(cube.side, 3)\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\ntype LagTestData struct {\n\tOcrData hostData `json:\"ocrData\"`\n\tTestStartTimestamp int64 `json:\"testStartTimestamp\"`\n\tCameraStartupDelay int64 `json:\"cameraStartupDelay\"`\n\tKeyPressTimestamp []int64 `json:\"keyPressTimestamp\"`\n\tExpectedLag []int64 `json:\"expectedLag\"`\n}\n\n\n\nfunc TestCalculateLag(t *testing.T) ", "output": "{\n\tfile, err := ioutil.ReadFile(\"calculateLag_test_data.json\")\n\tif err != nil {\n\t\tt.Fatal(\"Unable to read ocr-data.json:\", err)\n\t}\n\tvar lagTestData LagTestData\n\terr = json.Unmarshal([]byte(file), &lagTestData)\n\n\tif err != nil {\n\t\tt.Fatal(\"Unable to read ocr-data.json:\", err)\n\t}\n\n\tlagResultCalculated := calculateLag(lagTestData.OcrData, lagTestData.TestStartTimestamp, lagTestData.KeyPressTimestamp, lagTestData.CameraStartupDelay)\n\n\tfor i := 0; i < 10; i++ {\n\t\tif lagTestData.ExpectedLag[i] != lagResultCalculated[i] {\n\t\t\tt.Errorf(\"Lag result incorrect, got: %d, want: %d\", lagResultCalculated[i], lagTestData.ExpectedLag[i])\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\n\nconst target int = 200 \nvar coins = []int{1, 2, 5, 10, 20, 50, 100, 200} \n\n\n\n\n\n\n\nfunc dynamic() {\n\tways := make([]int, target+1)\n\tways[0] = 1 \n\n\tfor _, v := range coins {\n\t\tfor x := v; x <= (target); x++ {\n\t\t\tways[x] += ways[x-v]\n\t\t}\n\t}\n\tfmt.Println(ways[target])\n}\n\nfunc main() {\n\tfmt.Println(\"Recursion Way:\", recursion(target, coins, len(coins)))\n\tfmt.Print(\"Dynamic Way : \")\n\tdynamic()\n\n}\n\nfunc recursion(aTarget int, aCoins []int, size int) int ", "output": "{\n\n\tif aTarget < 0 {\n\t\treturn 0\n\t}\n\tif aTarget == 0 {\n\t\treturn 1\n\t}\n\tif size == 1 {\n\t\treturn 1\n\t}\n\treturn recursion(aTarget, aCoins, size-1) + recursion(aTarget-aCoins[size-1], aCoins, size)\n\n}"} {"input": "package tchannelthrift\n\nimport (\n\tstdctx \"context\"\n\t\"time\"\n\n\t\"github.com/m3db/m3/src/x/context\"\n\n\tapachethrift \"github.com/apache/thrift/lib/go/thrift\"\n\t\"github.com/uber/tchannel-go\"\n\t\"github.com/uber/tchannel-go/thrift\"\n)\n\nconst (\n\tcontextKey = \"m3dbcontext\"\n)\n\n\nfunc RegisterServer(channel *tchannel.Channel, service thrift.TChanServer, contextPool context.Pool) {\n\tserver := thrift.NewServer(channel)\n\tserver.Register(service, thrift.OptPostResponse(postResponseFn))\n\tserver.SetContextFn(func(ctx stdctx.Context, method string, headers map[string]string) thrift.Context {\n\t\txCtx := contextPool.Get()\n\t\txCtx.SetGoContext(ctx)\n\t\tctxWithValue := stdctx.WithValue(ctx, contextKey, xCtx) \n\t\treturn thrift.WithHeaders(ctxWithValue, headers)\n\t})\n}\n\n\nfunc NewContext(timeout time.Duration) (thrift.Context, stdctx.CancelFunc) {\n\ttctx, cancel := thrift.NewContext(timeout)\n\txCtx := context.NewWithGoContext(tctx)\n\tctxWithValue := stdctx.WithValue(tctx, contextKey, xCtx) \n\treturn thrift.WithHeaders(ctxWithValue, nil), cancel\n}\n\n\nfunc Context(ctx thrift.Context) context.Context {\n\treturn ctx.Value(contextKey).(context.Context)\n}\n\n\n\nfunc postResponseFn(ctx stdctx.Context, method string, response apachethrift.TStruct) ", "output": "{\n\tvalue := ctx.Value(contextKey)\n\tinner := value.(context.Context)\n\tinner.Close()\n}"} {"input": "package wire\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\n\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc newFixedWriter(max int) io.Writer ", "output": "{\n\tb := make([]byte, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}"} {"input": "package serial\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n)\n\n\ntype OverwriteableFile interface {\n\tio.Reader\n\tio.Writer\n\tio.Seeker\n\tTruncate(size int64) error\n}\n\n\ntype Serializer interface {\n\tDecodeAll(file io.ReadSeeker, outData interface{}) error\n\tEncodeAndOverwrite(file OverwriteableFile, outData interface{}) error\n}\n\ntype Serial struct{}\n\nfunc (s *Serial) DecodeAll(file io.ReadSeeker, outData interface{}) error {\n\t_, err := file.Seek(0, io.SeekStart)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = json.NewDecoder(file).Decode(outData)\n\tif err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc (s *Serial) EncodeAndOverwrite(file OverwriteableFile, outData interface{}) error ", "output": "{\n\t_, err := file.Seek(0, io.SeekStart)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = file.Truncate(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.NewEncoder(file).Encode(outData)\n}"} {"input": "package wire_test\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\n\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) ", "output": "{\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}"} {"input": "package errors\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n)\n\n\ntype HTTPError struct {\n\tStatusCode int\n\terror\n}\n\n\nfunc (e *HTTPError) Error() string {\n\treturn e.error.Error()\n}\n\n\n\n\nfunc NewMethodNotAllowed(method string) *HTTPError {\n\treturn &HTTPError{http.StatusMethodNotAllowed, errors.New(`Method is not allowed:\"` + method + `\"`)}\n}\n\n\nfunc NewBadRequest(err error) *HTTPError {\n\treturn &HTTPError{http.StatusBadRequest, err}\n}\n\n\n\n\n\n\n\nfunc NewBadRequestMissingParameter(s string) *HTTPError {\n\treturn NewBadRequestString(`Missing parameter \"` + s + `\"`)\n}\n\n\n\nfunc NewBadRequestUnwantedParameter(s string) *HTTPError {\n\treturn NewBadRequestString(`Unwanted parameter \"` + s + `\"`)\n}\n\nfunc NewBadRequestString(s string) *HTTPError ", "output": "{\n\treturn NewBadRequest(errors.New(s))\n}"} {"input": "package command\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/mitchellh/cli\"\n\t\"github.com/sgeb/go-acd\"\n)\n\ntype VersionCommand struct {\n\tAppName string\n\tRevision string\n\tVersion string\n\tVersionPrerelease string\n\tUi cli.Ui\n}\n\n\n\nfunc (c *VersionCommand) Run(_ []string) int {\n\tvar versionString bytes.Buffer\n\n\tfmt.Fprintf(&versionString, \"%s v%s\", c.AppName, c.Version)\n\tif c.VersionPrerelease != \"\" {\n\t\tfmt.Fprintf(&versionString, \"-%s\", c.VersionPrerelease)\n\n\t\tif c.Revision != \"\" {\n\t\t\tfmt.Fprintf(&versionString, \" (%s)\", c.Revision)\n\t\t}\n\t}\n\n\tfmt.Fprintln(&versionString, \"\")\n\tfmt.Fprintf(&versionString, \"using go-acd v%s\", acd.LibraryVersion)\n\n\tc.Ui.Output(versionString.String())\n\treturn 0\n\n}\n\nfunc (c *VersionCommand) Synopsis() string {\n\treturn fmt.Sprintf(\"Prints the %s version\", c.AppName)\n}\n\nfunc (c *VersionCommand) Help() string ", "output": "{\n\treturn \"\"\n}"} {"input": "package xmpp\n\nimport (\n\t\"encoding/xml\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/rmmmmpl/tcp_testserver\"\n)\n\nconst (\n\ttestUser = \"milton.waddams\"\n\ttestPassword = \"secret\"\n\ttestResource = \"basement\"\n\ttestHost = \"localhost\"\n\ttestPort = \"5552\"\n\ttestJID = JID(testUser + \"@\" + testHost + \"/\" + testResource)\n)\n\nvar s *tcp_testserver.Server\nvar c *Client\n\nfunc serverErrHandler(t *testing.T) chan<- bool {\n\tch := make(chan bool)\n\tgo func() {\n\t\tselect {\n\t\tcase err := <-s.ErrCh:\n\t\t\tt.Fatal(err)\n\t\tcase <-ch:\n\t\t\treturn\n\t\t}\n\t}()\n\treturn ch\n}\n\n\n\nfunc printErr(t *testing.T, shouldBe, is interface{}) {\n\tt.Log(\"Should be:\", shouldBe)\n\tt.Fatal(\"Is:\", is)\n}\n\nfunc presenceRequestHandler(t *testing.T, conn net.Conn) {\n\tvar p Presence\n\tif err := xml.NewDecoder(conn).Decode(&p); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tvar retP Presence\n\tretP.SetID(p.ID())\n\tretP.SetFrom(p.To())\n\tretP.SetTo(p.From())\n\tretP.SetType(Result)\n\n\tif err := xml.NewEncoder(conn).Encode(&retP); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestMain(m *testing.M) ", "output": "{\n\tvar err error\n\ts, err = tcp_testserver.NewServer(testHost + \":\" + testPort)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tos.Exit(-1)\n\t}\n\n\tr := m.Run()\n\n\tif c != nil {\n\t\tc.Close()\n\t}\n\ts.Close()\n\tos.Exit(r)\n}"} {"input": "package log\n\n\nfunc (me *Logging) Prefix() string {\n\treturn me.prefix\n}\n\n\nfunc (me *Logging) SetPrefix(value string) {\n\tme.prefix = value\n\tif me.console != nil {\n\t\tme.console.SetPrefix(me.prefix)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPrefix(me.prefix)\n\t}\n}\n\n\nfunc (me *Logging) Priority() int {\n\treturn me.priority\n}\n\n\nfunc (me *Logging) SetPriority(value int) {\n\tme.setPriority = true\n\tme.priority = value\n\tif me.console != nil {\n\t\tme.console.SetPriority(me.priority)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPriority(me.priority)\n\t}\n}\n\n\nfunc (me *Logging) Layouts() int {\n\treturn me.layouts\n}\n\n\nfunc (me *Logging) SetLayouts(value int) {\n\tme.setLayouts = true\n\tme.layouts = value\n\tif me.console != nil {\n\t\tme.console.SetLayouts(me.layouts)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetLayouts(me.layouts)\n\t}\n}\n\n\nfunc (me *Logging) Outputs() int {\n\treturn me.outputs\n}\n\n\n\n\nfunc (me *Logging) SetOutputs(value int) ", "output": "{\n\tme.setOutputs = true\n\tme.outputs = value\n}"} {"input": "package omniscient\n\nimport (\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestHealth(t *testing.T) {\n\tvar mu sync.Mutex\n\thealthStatus := true\n\tcheck := func() bool {\n\t\tmu.Lock()\n\t\tdefer mu.Unlock()\n\t\treturn healthStatus\n\t}\n\n\tupdateCheckInterval := func(h *Health) error {\n\t\th.checkInterval = 1 * time.Millisecond\n\t\treturn nil\n\t}\n\n\th, err := NewHealth(\n\t\tHealthCheckOption(check),\n\t\tupdateCheckInterval)\n\tassert.NoError(t, err)\n\n\th.Start()\n\tdefer h.Stop()\n\n\tassert.True(t, h.IsOK(), \"health check status\")\n\n\tmu.Lock()\n\thealthStatus = false\n\tmu.Unlock()\n\n\t<-h.statusUpdated\n\tassert.False(t, h.IsOK(), \"health check status\")\n}\n\n\n\nfunc TestHealthCannotStopIfNotStarted(t *testing.T) {\n\tupdateCheckInterval := func(h *Health) error {\n\t\th.checkInterval = 1 * time.Millisecond\n\t\treturn nil\n\t}\n\n\th, err := NewHealth(updateCheckInterval)\n\tassert.NoError(t, err)\n\n\terr = h.Stop()\n\tassert.Error(t, err)\n}\n\nfunc TestHealthCannotStartIfStarted(t *testing.T) ", "output": "{\n\tupdateCheckInterval := func(h *Health) error {\n\t\th.checkInterval = 1 * time.Millisecond\n\t\treturn nil\n\t}\n\n\th, err := NewHealth(updateCheckInterval)\n\tassert.NoError(t, err)\n\n\terr = h.Start()\n\tassert.NoError(t, err)\n\n\t<-h.stateChange\n\n\terr = h.Start()\n\tassert.Error(t, err)\n}"} {"input": "package builder\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\n\tvelerov1api \"github.com/vmware-tanzu/velero/pkg/apis/velero/v1\"\n)\n\n\ntype PodVolumeBackupBuilder struct {\n\tobject *velerov1api.PodVolumeBackup\n}\n\n\nfunc ForPodVolumeBackup(ns, name string) *PodVolumeBackupBuilder {\n\treturn &PodVolumeBackupBuilder{\n\t\tobject: &velerov1api.PodVolumeBackup{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tAPIVersion: velerov1api.SchemeGroupVersion.String(),\n\t\t\t\tKind: \"PodVolumeBackup\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: name,\n\t\t\t},\n\t\t},\n\t}\n}\n\n\nfunc (b *PodVolumeBackupBuilder) Result() *velerov1api.PodVolumeBackup {\n\treturn b.object\n}\n\n\nfunc (b *PodVolumeBackupBuilder) ObjectMeta(opts ...ObjectMetaOpt) *PodVolumeBackupBuilder {\n\tfor _, opt := range opts {\n\t\topt(b.object)\n\t}\n\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) Phase(phase velerov1api.PodVolumeBackupPhase) *PodVolumeBackupBuilder {\n\tb.object.Status.Phase = phase\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) SnapshotID(snapshotID string) *PodVolumeBackupBuilder {\n\tb.object.Status.SnapshotID = snapshotID\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) PodName(name string) *PodVolumeBackupBuilder {\n\tb.object.Spec.Pod.Name = name\n\treturn b\n}\n\n\n\n\nfunc (b *PodVolumeBackupBuilder) Volume(volume string) *PodVolumeBackupBuilder ", "output": "{\n\tb.object.Spec.Volume = volume\n\treturn b\n}"} {"input": "package buildinfo\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t. \"src.elv.sh/pkg/prog/progtest\"\n)\n\n\n\nfunc TestProgram(t *testing.T) ", "output": "{\n\tTest(t, &Program{},\n\t\tThatElvish(\"-version\").WritesStdout(Value.Version+\"\\n\"),\n\t\tThatElvish(\"-version\", \"-json\").WritesStdout(mustToJSON(Value.Version)+\"\\n\"),\n\n\t\tThatElvish(\"-buildinfo\").WritesStdout(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Version: %v\\nGo version: %v\\nReproducible build: %v\\n\",\n\t\t\t\tValue.Version, Value.GoVersion, Value.Reproducible)),\n\t\tThatElvish(\"-buildinfo\", \"-json\").WritesStdout(mustToJSON(Value)+\"\\n\"),\n\n\t\tThatElvish().ExitsWith(2).WritesStderr(\"internal error: no suitable subprogram\\n\"),\n\t)\n}"} {"input": "package handlers\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\t\"github.com/xoriath/alexandria-go/fetch\"\n\t\"github.com/xoriath/alexandria-go/index\"\n\t\"github.com/xoriath/alexandria-go/types\"\n)\n\n\ntype ReloadBook struct {\n\tbooks *types.Books\n\tindex string\n}\n\n\n\n\nfunc (rb *ReloadBook) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ttempBooks, err := fetch.MainIndex(rb.index)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t} else {\n\t\trb.books = tempBooks\n\t\tjson.NewEncoder(w).Encode(rb.books)\n\t}\n}\n\n\ntype ReloadKeyword struct {\n\tbooks *types.Books\n\tstore *index.Store\n\tf1Pattern string\n}\n\n\nfunc NewReloadKeywordHandler(books *types.Books, store *index.Store, f1Pattern string) *ReloadKeyword {\n\treturn &ReloadKeyword{books: books, store: store, f1Pattern: f1Pattern}\n}\n\nfunc (rk *ReloadKeyword) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\trk.store = fetch.F1Indexes(rk.books, rk.store)\n\n\tstat := rk.store.GetStatistics()\n\tjson.NewEncoder(w).Encode(stat)\n}\n\nfunc NewReloadBookHandler(books *types.Books, index string) *ReloadBook ", "output": "{\n\treturn &ReloadBook{books: books, index: index}\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/bitly/nsq/util\"\n)\n\ntype NSQAdmin struct {\n\toptions *nsqadminOptions\n\thttpAddr *net.TCPAddr\n\thttpListener net.Listener\n\twaitGroup util.WaitGroupWrapper\n\tnotifications chan *AdminAction\n}\n\n\n\nfunc (n *NSQAdmin) handleAdminActions() {\n\tfor action := range n.notifications {\n\t\tcontent, err := json.Marshal(action)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error serializing admin action! %s\", err)\n\t\t}\n\t\thttpclient := &http.Client{Transport: util.NewDeadlineTransport(10 * time.Second)}\n\t\tlog.Printf(\"Posting notification to %s\", *notificationHTTPEndpoint)\n\t\t_, err = httpclient.Post(*notificationHTTPEndpoint, \"application/json\", bytes.NewBuffer(content))\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error posting notification: %s\", err)\n\t\t}\n\t}\n}\n\nfunc (n *NSQAdmin) Main() {\n\thttpListener, err := net.Listen(\"tcp\", n.httpAddr.String())\n\tif err != nil {\n\t\tlog.Fatalf(\"FATAL: listen (%s) failed - %s\", n.httpAddr, err.Error())\n\t}\n\tn.httpListener = httpListener\n\thttpServer := NewHTTPServer(&Context{n})\n\tn.waitGroup.Wrap(func() { util.HTTPServer(n.httpListener, httpServer) })\n\tn.waitGroup.Wrap(func() { n.handleAdminActions() })\n}\n\nfunc (n *NSQAdmin) Exit() {\n\tn.httpListener.Close()\n\tclose(n.notifications)\n\tn.waitGroup.Wait()\n}\n\nfunc NewNSQAdmin(options *nsqadminOptions) *NSQAdmin ", "output": "{\n\tif len(options.NSQDHTTPAddresses) == 0 && len(options.NSQLookupdHTTPAddresses) == 0 {\n\t\tlog.Fatalf(\"--nsqd-http-address or --lookupd-http-address required.\")\n\t}\n\n\tif len(options.NSQDHTTPAddresses) != 0 && len(options.NSQLookupdHTTPAddresses) != 0 {\n\t\tlog.Fatalf(\"use --nsqd-http-address or --lookupd-http-address not both\")\n\t}\n\n\thttpAddr, err := net.ResolveTCPAddr(\"tcp\", options.HTTPAddress)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn &NSQAdmin{\n\t\toptions: options,\n\t\thttpAddr: httpAddr,\n\t\tnotifications: make(chan *AdminAction),\n\t}\n}"} {"input": "package anydata_test\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/pbnjay/anydata\"\n)\n\n\n\n\nfunc Example_usage() ", "output": "{\n\n\ttaxNames := \"ftp://ftp.ncbi.nih.gov/pub/taxonomy/taxdump.tar.gz#names.dmp\"\n\tftch, err := anydata.GetFetcher(taxNames)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = ftch.Fetch(taxNames)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\trdr, err := ftch.GetReader()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tscanner := bufio.NewScanner(rdr)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif strings.Contains(line, \"scientific name\") {\n\t\t\tfmt.Println(line)\n\t\t}\n\t}\n}"} {"input": "package clang\n\n\n\n\nimport \"C\"\n\n\ntype Version struct {\n\tc C.CXVersion\n}\n\n\n\n\n\nfunc (v Version) Minor() int {\n\treturn int(v.c.Minor)\n}\n\n\nfunc (v Version) Subminor() int {\n\treturn int(v.c.Subminor)\n}\n\nfunc (v Version) Major() int ", "output": "{\n\treturn int(v.c.Major)\n}"} {"input": "package iso20022\n\n\ntype GrossDividendRateFormat21Choice struct {\n\n\tAmount *ActiveCurrencyAnd13DecimalAmount `xml:\"Amt\"`\n\n\tAmountAndRateStatus *AmountAndRateStatus1 `xml:\"AmtAndRateSts\"`\n\n\tRateTypeAndAmountAndRateStatus *RateTypeAndAmountAndStatus22 `xml:\"RateTpAndAmtAndRateSts\"`\n}\n\n\n\nfunc (g *GrossDividendRateFormat21Choice) AddAmountAndRateStatus() *AmountAndRateStatus1 {\n\tg.AmountAndRateStatus = new(AmountAndRateStatus1)\n\treturn g.AmountAndRateStatus\n}\n\nfunc (g *GrossDividendRateFormat21Choice) AddRateTypeAndAmountAndRateStatus() *RateTypeAndAmountAndStatus22 {\n\tg.RateTypeAndAmountAndRateStatus = new(RateTypeAndAmountAndStatus22)\n\treturn g.RateTypeAndAmountAndRateStatus\n}\n\nfunc (g *GrossDividendRateFormat21Choice) SetAmount(value, currency string) ", "output": "{\n\tg.Amount = NewActiveCurrencyAnd13DecimalAmount(value, currency)\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\ntype CreateEnvironmentRequest struct {\n\n\tInstanceGroup *InstanceGroup `json:\"instanceGroup\"`\n\n\tName *string `json:\"name\"`\n\n\tTaskDefinition *string `json:\"taskDefinition\"`\n}\n\n\nfunc (m *CreateEnvironmentRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateInstanceGroup(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTaskDefinition(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (m *CreateEnvironmentRequest) validateInstanceGroup(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"instanceGroup\", \"body\", m.InstanceGroup); err != nil {\n\t\treturn err\n\t}\n\n\tif m.InstanceGroup != nil {\n\n\t\tif err := m.InstanceGroup.Validate(formats); err != nil {\n\t\t\tif ve, ok := err.(*errors.Validation); ok {\n\t\t\t\treturn ve.ValidateName(\"instanceGroup\")\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (m *CreateEnvironmentRequest) validateTaskDefinition(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"taskDefinition\", \"body\", m.TaskDefinition); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *CreateEnvironmentRequest) validateName(formats strfmt.Registry) error ", "output": "{\n\n\tif err := validate.Required(\"name\", \"body\", m.Name); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validate.Pattern(\"name\", \"body\", string(*m.Name), `^[a-zA-Z0-9-_]{1,30}$`); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "\n\n\nfunc fetch(target string) (*JSONIP, error) {\n\tresp, err := http.Get(target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar ip *JSONIP\n\terr = json.NewDecoder(resp.Body).Decode(&ip)\n\treturn ip, err\n}\n\nfunc IPv6() (*JSONIP, error) ", "output": "{\n\treturn fetch(ipv6Endpoint)\n}"} {"input": "package server\n\nimport (\n\t\"github.com/Ray-GuanhuiLiang/GoGuidGenerator/common\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n\t\"log\"\n\t\"net\"\n)\n\ntype GrpcServer struct {\n\tgenerator common.Generator\n\tserv *grpc.Server\n\texit chan int\n}\n\nfunc NewGrpcServer(generator common.Generator) *GrpcServer {\n\te := make(chan int)\n\tserv := grpc.NewServer()\n\ts := &GrpcServer{generator, serv, e}\n\tRegisterGuidServer(serv, s)\n\treturn s\n}\n\nfunc (this *GrpcServer) Start() error {\n\tlistener, err := net.Listen(\"tcp\", \":5588\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn err\n\t}\n\tgo this.serv.Serve(listener)\n\treturn nil\n}\n\nfunc (this *GrpcServer) Wait() {\n\t<-this.exit\n}\n\n\n\nfunc (this *GrpcServer) GetGuid(context.Context, *Req) (*Resp, error) ", "output": "{\n\tid, err := this.generator.Generate()\n\tvar (\n\t\tr Resp\n\t\tcode int32\n\t\tguid uint64\n\t)\n\tif err != nil {\n\t\tcode = 1\n\t\tguid = 0\n\t} else {\n\t\tcode = 0\n\t\tguid = id\n\t}\n\tr.Code = &code\n\tr.Guid = &guid\n\treturn &r, err\n}"} {"input": "package system\n\nimport (\n\t\"github.com/juju/cmd\"\n\t\"github.com/juju/errors\"\n\t\"launchpad.net/gnuflag\"\n\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/cmd/envcmd\"\n)\n\nfunc newListBlocksCommand() cmd.Command {\n\treturn envcmd.WrapSystem(&listBlocksCommand{})\n}\n\n\ntype listBlocksCommand struct {\n\tenvcmd.SysCommandBase\n\tout cmd.Output\n\tapi listBlocksAPI\n\tapierr error\n}\n\nvar listBlocksDoc = `List all blocks for environments within the specified system`\n\n\n\ntype listBlocksAPI interface {\n\tClose() error\n\tListBlockedEnvironments() ([]params.EnvironmentBlockInfo, error)\n}\n\n\n\n\n\nfunc (c *listBlocksCommand) SetFlags(f *gnuflag.FlagSet) {\n\tc.out.AddFlags(f, \"tabular\", map[string]cmd.Formatter{\n\t\t\"yaml\": cmd.FormatYaml,\n\t\t\"json\": cmd.FormatJson,\n\t\t\"tabular\": formatTabularBlockedEnvironments,\n\t})\n}\n\nfunc (c *listBlocksCommand) getAPI() (listBlocksAPI, error) {\n\tif c.api != nil {\n\t\treturn c.api, c.apierr\n\t}\n\treturn c.NewSystemManagerAPIClient()\n}\n\n\nfunc (c *listBlocksCommand) Run(ctx *cmd.Context) error {\n\tapi, err := c.getAPI()\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"cannot connect to the API\")\n\t}\n\tdefer api.Close()\n\n\tenvs, err := api.ListBlockedEnvironments()\n\tif err != nil {\n\t\tlogger.Errorf(\"Unable to list blocked environments: %s\", err)\n\t\treturn err\n\t}\n\treturn c.out.Write(ctx, envs)\n}\n\nfunc (c *listBlocksCommand) Info() *cmd.Info ", "output": "{\n\treturn &cmd.Info{\n\t\tName: \"list-blocks\",\n\t\tPurpose: \"list all blocks within the system\",\n\t\tDoc: listBlocksDoc,\n\t}\n}"} {"input": "package MySQLProtocol\n\ntype Packet_SSLRequest struct {\n\tPacket\n\n\tcapability uint32\n\tmax_packet_size uint32\n\tusername string\n\tcharacter_set uint8\n}\n\nfunc (packet Packet_SSLRequest) GetPacketSize(context Context) (size uint64) {\n\tsize += 4\n\tsize += 4\n\tsize += 1\n\tsize += 23\n\treturn size\n}\n\nfunc (packet Packet_SSLRequest) ToPacket(context Context) (data []byte) {\n\tsize := packet.GetPacketSize(context)\n\n\tdata = make([]byte, 0, size+4)\n\n\tdata = append(data, BuildFixedLengthInteger3(uint32(size))...)\n\tdata = append(data, BuildFixedLengthInteger1(packet.sequence_id)...)\n\n\tdata = append(data, BuildFixedLengthInteger4(packet.capability)...)\n\tdata = append(data, BuildFixedLengthInteger4(packet.max_packet_size)...)\n\tdata = append(data, BuildFixedLengthInteger1(packet.character_set)...)\n\tdata = append(data, BuildFixedLengthString(\"\", 23)...)\n\n\treturn data\n}\n\n\n\nfunc (packet *Packet_SSLRequest) FromPacket(context Context, data Proto) ", "output": "{\n\tdata.GetFixedLengthInteger3()\n\tpacket.sequence_id = data.GetFixedLengthInteger1()\n\n\tpacket.capability = data.GetFixedLengthInteger4()\n\tpacket.max_packet_size = data.GetFixedLengthInteger4()\n\tpacket.character_set = data.GetFixedLengthInteger1()\n\tdata.GetFixedLengthString(23)\n}"} {"input": "package egoscale\n\nimport \"fmt\"\n\n\nfunc (ListAntiAffinityGroups) Response() interface{} {\n\treturn new(ListAntiAffinityGroupsResponse)\n}\n\n\nfunc (ls *ListAntiAffinityGroups) ListRequest() (ListCommand, error) {\n\tif ls == nil {\n\t\treturn nil, fmt.Errorf(\"%T cannot be nil\", ls)\n\t}\n\treturn ls, nil\n}\n\n\n\n\n\nfunc (ls *ListAntiAffinityGroups) SetPageSize(pageSize int) {\n\tls.PageSize = pageSize\n}\n\n\nfunc (ListAntiAffinityGroups) Each(resp interface{}, callback IterateItemFunc) {\n\titems, ok := resp.(*ListAntiAffinityGroupsResponse)\n\tif !ok {\n\t\tcallback(nil, fmt.Errorf(\"wrong type, ListAntiAffinityGroupsResponse was expected, got %T\", resp))\n\t\treturn\n\t}\n\n\tfor i := range items.AntiAffinityGroup {\n\t\tif !callback(&items.AntiAffinityGroup[i], nil) {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (ls *ListAntiAffinityGroups) SetPage(page int) ", "output": "{\n\tls.Page = page\n}"} {"input": "package backoff\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\n\ntype BackOffContext interface {\n\tBackOff\n\tContext() context.Context\n}\n\ntype backOffContext struct {\n\tBackOff\n\tctx context.Context\n}\n\n\n\n\n\n\nfunc ensureContext(b BackOff) BackOffContext {\n\tif cb, ok := b.(BackOffContext); ok {\n\t\treturn cb\n\t}\n\treturn WithContext(b, context.Background())\n}\n\nfunc (b *backOffContext) Context() context.Context {\n\treturn b.ctx\n}\n\nfunc (b *backOffContext) NextBackOff() time.Duration {\n\tselect {\n\tcase <-b.ctx.Done():\n\t\treturn Stop\n\tdefault:\n\t}\n\tnext := b.BackOff.NextBackOff()\n\tif deadline, ok := b.ctx.Deadline(); ok && deadline.Sub(time.Now()) < next {\n\t\treturn Stop\n\t}\n\treturn next\n}\n\nfunc WithContext(b BackOff, ctx context.Context) BackOffContext ", "output": "{\n\tif ctx == nil {\n\t\tpanic(\"nil context\")\n\t}\n\n\tif b, ok := b.(*backOffContext); ok {\n\t\treturn &backOffContext{\n\t\t\tBackOff: b.BackOff,\n\t\t\tctx: ctx,\n\t\t}\n\t}\n\n\treturn &backOffContext{\n\t\tBackOff: b,\n\t\tctx: ctx,\n\t}\n}"} {"input": "package egl\n\n\nimport \"C\"\nimport \"unsafe\"\n\ntype (\n\tEnum uint32\n\tConfig uintptr\n\tContext uintptr\n\tDisplay uintptr\n\tSurface uintptr\n\tClientBuffer uintptr\n\tNativeDisplayType unsafe.Pointer\n\tNativeWindowType unsafe.Pointer\n\tNativePixmapType unsafe.Pointer\n)\n\nfunc goBoolean(n C.EGLBoolean) bool {\n\treturn n == 1\n}\n\n\nfunc eglBoolean(n bool) C.EGLBoolean ", "output": "{\n\tvar b int\n\tif n == true {\n\t\tb = 1\n\t}\n\treturn C.EGLBoolean(b)\n}"} {"input": "package listener\n\nimport (\n\t\"fmt\"\n)\n\nconst (\n\tDefaultGrpcPort = 18847\n\tDefaultHttpHealthCheckPort = 8080\n)\n\ntype Config struct {\n\tDebug bool\n\tGrpcPort int\n\tInsecureGrpcPort int\n\tHealthPort int\n\tTlsCertFile string\n\tTlsKeyFile string\n\tClientID string\n\tClientSecret string\n\tAuthDiscovery string\n\tRedisAddr string\n\tRedisPassword string\n\tRedisSentinel bool\n\tRedisMasterName string\n\tRedisDB int\n\tPubSubURL string\n\tInstanceName string\n\tNatsClusterID string\n}\n\nfunc (c *Config) GetGrpcPortString() string {\n\treturn fmt.Sprintf(\":%d\", c.GrpcPort)\n}\n\nfunc NewConfig() *Config {\n\treturn &Config{\n\t\tGrpcPort: DefaultGrpcPort,\n\t\tHealthPort: DefaultHttpHealthCheckPort,\n\t\tRedisAddr: \"127.0.0.1:6379\",\n\t\tRedisPassword: \"\",\n\t\tRedisDB: 0,\n\t\tInsecureGrpcPort: 0,\n\t\tRedisMasterName: \"mymaster\",\n\t\tNatsClusterID: \"otsimo\",\n\t\tInstanceName: \"listener\",\n\t}\n}\n\nfunc (c *Config) GetHealthPortString() string ", "output": "{\n\treturn fmt.Sprintf(\":%d\", c.HealthPort)\n}"} {"input": "package pqueue\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc Test_AdjustHeap(t *testing.T) ", "output": "{\n\tlist := []Node{Node{0, 0}, Node{1, 1}, Node{2, 2}, Node{3, 3}, Node{4, 1}, Node{6, 6}}\n\n\tadjustHeap(list, 1, len(list)-1)\n\tassert.Equal(t, 6, list[1].value)\n}"} {"input": "package data\n\nimport (\n \"github.com/twitchyliquid64/CNC/registry/syscomponents\"\n)\n\nvar trackerObj DatabaseComponent\n\ntype DatabaseComponent struct{\n err error\n}\n\nfunc (d *DatabaseComponent)Name() string{\n return \"Database\"\n}\n\nfunc (d *DatabaseComponent)IsNominal()bool{\n return d.err == nil\n}\nfunc (d *DatabaseComponent)IsDisabled()bool{\n return false\n}\nfunc (d *DatabaseComponent)IsFault()bool{\n return d.err != nil\n}\nfunc (d *DatabaseComponent)Error()string{\n if d.err == nil{\n return \"\"\n }\n return d.err.Error()\n}\nfunc (d *DatabaseComponent)SetError(e error){\n d.err = e\n}\n\nfunc trackingSetup(){\n trackerObj = DatabaseComponent{}\n syscomponents.Register(&trackerObj)\n}\n\nfunc tracking_notifyFault(err error){\n syscomponents.SetError(trackerObj.Name(), err)\n}\n\nfunc (d *DatabaseComponent)IconStr() string", "output": "{\n return \"list\"\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\t\"github.com/gorilla/mux\"\n)\n\n\n\nfunc initData(resp http.ResponseWriter, req *http.Request) {\n\n\tinsert()\n}\n\nfunc getData(resp http.ResponseWriter, req *http.Request) {\n\n\tname, _ := mux.Vars(req)[\"name\"]\n\tdata := callDb(name)\n\n\tif data.Name == \"\" {\n\t\tresp.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tval, _ := json.Marshal(data)\n\tresp.Write(val)\n}\n\nfunc Configure(router *mux.Router) ", "output": "{\n\n\trouter.HandleFunc(\"/init\", initData).Methods(\"GET\")\n\trouter.HandleFunc(\"/test/{name}\", getData).Methods(\"GET\")\n}"} {"input": "package bigcache\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n\n\nfunc isPowerOfTwo(number int) bool {\n\treturn (number & (number - 1)) == 0\n}\n\nfunc convertMBToBytes(value int) int ", "output": "{\n\treturn value * 1024 * 1024\n}"} {"input": "package condition_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/ngurajeka/go-querybuilder/v2/condition\"\n)\n\n\n\nfunc TestAdvancedCondition(t *testing.T) {\n\tvar (\n\t\tc condition.Condition\n\t\texpected, result string\n\t)\n\n\tc = condition.New(\n\t\t\"username\",\n\t\tcondition.IN,\n\t\tcondition.AND,\n\t\t[]string{\"ady\", \"ngurajeka\"},\n\t)\n\texpected = \"username IN ( 'ady', 'ngurajeka' )\"\n\tresult = c.String(false)\n\tif result != expected {\n\t\tt.Errorf(\"invalid operation result, got %s\\n\", result)\n\t}\n\n\tc = condition.New(\n\t\t\"id\",\n\t\tcondition.IN,\n\t\tcondition.AND,\n\t\t[]int{10, 11},\n\t)\n\texpected = \"id IN ( 10, 11 )\"\n\tresult = c.String(false)\n\tif result != expected {\n\t\tt.Errorf(\"invalid operation result, got %s\\n\", result)\n\t}\n\n\tc = condition.Default(\"id\", []int{10, 11})\n\tresult = c.String(false)\n\tif result != expected {\n\t\tt.Errorf(\"invalid operation result, got %s\\n\", result)\n\t}\n}\n\nfunc TestNilValue(t *testing.T) {\n\tvar (\n\t\tc condition.Condition\n\t\texpected, result string\n\t)\n\n\tc = condition.Nil(\"last_name\")\n\texpected = \"last_name IS NULL\"\n\tresult = c.String(false)\n\tif result != expected {\n\t\tt.Errorf(\"invalid operation result, got %s\\n\", result)\n\t}\n\n\tc = condition.Default(\"last_name\", nil)\n\tif result != expected {\n\t\tt.Errorf(\"invalid operation result, got %s\\n\", result)\n\t}\n}\n\nfunc TestSimpleCondition(t *testing.T) ", "output": "{\n\tvar (\n\t\tc condition.Condition\n\t\texpected, result string\n\t)\n\tc = condition.Default(\"username\", \"ngurajeka\")\n\texpected = \"username = 'ngurajeka'\"\n\n\tresult = c.String(false)\n\tif result != expected {\n\t\tt.Errorf(\"invalid operation result, got %s\\n\", result)\n\t}\n\n\tc = condition.Default(\"id\", 10)\n\texpected = \"id = 10\"\n\n\tresult = c.String(false)\n\tif result != expected {\n\t\tt.Errorf(\"invalid operation result, got %s\\n\", result)\n\t}\n}"} {"input": "package sql\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/cockroachdb/cockroach/pkg/roachpb\"\n\t\"github.com/cockroachdb/cockroach/pkg/sql/parser\"\n\t\"github.com/cockroachdb/cockroach/pkg/sql/sqlbase\"\n)\n\n\n\n\ntype delayedNode struct {\n\tname string\n\tcolumns sqlbase.ResultColumns\n\tconstructor nodeConstructor\n\tplan planNode\n}\n\ntype nodeConstructor func(context.Context, *planner) (planNode, error)\n\nfunc (d *delayedNode) Close(ctx context.Context) {\n\tif d.plan != nil {\n\t\td.plan.Close(ctx)\n\t\td.plan = nil\n\t}\n}\n\nfunc (d *delayedNode) Columns() sqlbase.ResultColumns { return d.columns }\nfunc (d *delayedNode) Ordering() orderingInfo { return orderingInfo{} }\nfunc (d *delayedNode) MarkDebug(_ explainMode) {}\nfunc (d *delayedNode) Start(ctx context.Context) error { return d.plan.Start(ctx) }\nfunc (d *delayedNode) Next(ctx context.Context) (bool, error) { return d.plan.Next(ctx) }\nfunc (d *delayedNode) Values() parser.Datums { return d.plan.Values() }\n\nfunc (d *delayedNode) Spans(ctx context.Context) (_, _ roachpb.Spans, _ error) {\n\treturn d.plan.Spans(ctx)\n}\n\nfunc (d *delayedNode) DebugValues() debugValues ", "output": "{ return d.plan.DebugValues() }"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\n\t\"errors\"\n\n\t\"github.com/kubernetes-sigs/service-catalog/pkg/svcat/service-catalog\"\n\t\"github.com/spf13/pflag\"\n)\n\n\n\ntype HasScopedFlags interface {\n\tApplyScopedFlags(flags *pflag.FlagSet) error\n}\n\n\nvar _ HasScopedFlags = NewScoped()\n\n\n\ntype Scoped struct {\n\tallowAll bool\n\trawScope string\n\tScope servicecatalog.Scope\n}\n\n\n\n\n\n\nfunc (c *Scoped) AddScopedFlags(flags *pflag.FlagSet, allowAll bool) {\n\tc.allowAll = allowAll\n\tif allowAll {\n\t\tflags.StringVar(&c.rawScope, \"scope\", servicecatalog.AllScope, \"Limit the command to a particular scope: cluster, namespace or all\")\n\t} else {\n\t\tflags.StringVar(&c.rawScope, \"scope\", servicecatalog.NamespaceScope, \"Limit the command to a particular scope: cluster or namespace\")\n\t}\n}\n\n\n\nfunc (c *Scoped) ApplyScopedFlags(flags *pflag.FlagSet) error {\n\tswitch c.rawScope {\n\tcase servicecatalog.AllScope:\n\t\tif !c.allowAll {\n\t\t\treturn errors.New(\"invalid --scope (all), allowed values are: cluster, namespace\")\n\t\t}\n\t\tc.Scope = servicecatalog.Scope(c.rawScope)\n\t\treturn nil\n\tcase servicecatalog.ClusterScope, servicecatalog.NamespaceScope:\n\t\tc.Scope = servicecatalog.Scope(c.rawScope)\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid --scope (%s), allowed values are: all, cluster, namespace\", c.rawScope)\n\t}\n}\n\nfunc NewScoped() *Scoped ", "output": "{\n\treturn &Scoped{}\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/ulricqin/beego-blog/g\"\n\t\"github.com/ulricqin/beego-blog/models/blog\"\n\t\"github.com/ulricqin/beego-blog/models/catalog\"\n)\n\ntype MainController struct {\n\tBaseController\n}\n\nfunc (this *MainController) Get() {\n\tthis.Data[\"Catalogs\"] = catalog.All()\n\tthis.Data[\"PageTitle\"] = \"首页\"\n\tthis.Layout = \"layout/default.html\"\n\tthis.TplName = \"index.html\"\n}\n\n\n\nfunc (this *MainController) ListByCatalog() {\n\tcata := this.Ctx.Input.Param(\":ident\")\n\tif cata == \"\" {\n\t\tthis.Ctx.WriteString(\"catalog ident is blank\")\n\t\treturn\n\t}\n\n\tlimit := this.GetIntWithDefault(\"limit\", 10)\n\n\tc := catalog.OneByIdent(cata)\n\tif c == nil {\n\t\tthis.Ctx.WriteString(\"catalog:\" + cata + \" not found\")\n\t\treturn\n\t}\n\n\tids := blog.Ids(c.Id)\n\tpager := this.SetPaginator(limit, int64(len(ids)))\n\tblogs := blog.ByCatalog(c.Id, pager.Offset(), limit)\n\n\tthis.Data[\"Catalog\"] = c\n\tthis.Data[\"Blogs\"] = blogs\n\tthis.Data[\"PageTitle\"] = c.Name\n\n\tthis.Layout = \"layout/default.html\"\n\tthis.TplName = \"article/by_catalog.html\"\n}\n\nfunc (this *MainController) Read() ", "output": "{\n\tident := this.GetString(\":ident\")\n\tb := blog.OneByIdent(ident)\n\tif b == nil {\n\t\tthis.Ctx.WriteString(\"no such article\")\n\t\treturn\n\t}\n\n\tb.Views = b.Views + 1\n\tblog.Update(b, \"\")\n\n\tthis.Data[\"Blog\"] = b\n\tthis.Data[\"Content\"] = g.RenderMarkdown(blog.ReadBlogContent(b).Content)\n\tthis.Data[\"PageTitle\"] = b.Title\n\tthis.Data[\"Catalog\"] = catalog.OneById(b.CatalogId)\n\tthis.Layout = \"layout/default.html\"\n\tthis.TplName = \"article/read.html\"\n}"} {"input": "package jsonbuilder\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n)\n\nfunc MarshalIntArray(inta []int) []byte {\n\tbuffer := new(bytes.Buffer)\n\te := gob.NewEncoder(buffer)\n\terr := e.Encode(inta)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to marshal \", err)\n\t}\n\treturn buffer.Bytes()\n}\n\n\n\nfunc ReadData(r io.Reader, intf interface{}) error {\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(data, &intf)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc WriteData(w io.Writer, intf interface{}) error {\n\tb, err := json.Marshal(intf)\n\tfmt.Println(len(b), string(b))\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\n\ti, err := w.Write(b)\n\tif i != len(b) || err != nil {\n\t\tfmt.Println(\"Nothing to write\", i, err)\n\t}\n\treturn err\n}\n\nfunc UnmarshalIntArray(ba []byte) []int ", "output": "{\n\tbuffer := bytes.NewBuffer(ba)\n\tvar inta = new([]int)\n\td := gob.NewDecoder(buffer)\n\terr := d.Decode(&inta)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to unmarshal \", ba, err)\n\t}\n\treturn *inta\n}"} {"input": "package dexcom\n\nimport (\n\t\"math\"\n)\n\n\n\nfunc marshalUint16(n uint16) []byte {\n\treturn []byte{byte(n & 0xFF), byte(n >> 8)}\n}\n\n\nfunc marshalInt16(n int16) []byte {\n\treturn marshalUint16(uint16(n))\n}\n\nfunc marshalUint32(n uint32) []byte {\n\treturn append(marshalUint16(uint16(n&0xFFFF)), marshalUint16(uint16(n>>16))...)\n}\n\n\n\nfunc unmarshalUint16(v []byte) uint16 {\n\treturn uint16(v[0]) | uint16(v[1])<<8\n}\n\n\nfunc unmarshalInt16(v []byte) int16 {\n\treturn int16(unmarshalUint16(v))\n}\n\nfunc unmarshalUint32(v []byte) uint32 {\n\treturn uint32(unmarshalUint16(v[0:2])) | uint32(unmarshalUint16(v[2:4]))<<16\n}\n\nfunc unmarshalInt32(v []byte) int32 {\n\treturn int32(unmarshalUint32(v))\n}\n\nfunc unmarshalUint64(v []byte) uint64 {\n\treturn uint64(unmarshalUint32(v[0:4])) | uint64(unmarshalUint32(v[4:8]))<<32\n}\n\nfunc unmarshalFloat64(v []byte) float64 {\n\treturn math.Float64frombits(unmarshalUint64(v))\n}\n\nfunc marshalInt32(n int32) []byte ", "output": "{\n\treturn marshalUint32(uint32(n))\n}"} {"input": "package msgpack\n\nimport (\n\t\"strings\"\n)\n\n\n\ntype tagOptions string\n\n\n\nfunc parseTag(tag string) (string, tagOptions) {\n\tif idx := strings.Index(tag, \",\"); idx != -1 {\n\t\treturn tag[:idx], tagOptions(tag[idx+1:])\n\t}\n\treturn tag, tagOptions(\"\")\n}\n\n\n\n\n\n\nfunc (o tagOptions) Contains(optionName string) bool ", "output": "{\n\tif len(o) == 0 {\n\t\treturn false\n\t}\n\ts := string(o)\n\tfor s != \"\" {\n\t\tvar next string\n\t\ti := strings.IndexRune(s, ',')\n\t\tif i >= 0 {\n\t\t\ts, next = s[:i], s[i+1:]\n\t\t}\n\t\tif s == optionName {\n\t\t\treturn true\n\t\t}\n\t\ts = next\n\t}\n\treturn false\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/apier/v1\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\n\n\n\ntype CmdRemoveBalance struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrAddBalance\n\t*CommandExecuter\n}\n\nfunc (self *CmdRemoveBalance) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdRemoveBalance) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdRemoveBalance) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrAddBalance{BalanceType: utils.MONETARY, Overwrite: false}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdRemoveBalance) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdRemoveBalance) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc init() ", "output": "{\n\tc := &CmdRemoveBalance{\n\t\tname: \"balance_remove\",\n\t\trpcMethod: \"ApierV1.RemoveBalances\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}"} {"input": "package gh9\n\n\n\nfunc x() string ", "output": "{\n\ts := f(`\nfoo`)\n\treturn s\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/jackytck/projecteuler/tools\"\n)\n\nfunc isAbundant(n int) bool {\n\treturn tools.SumDivisors(n) > n\n}\n\n\n\nfunc solve() int {\n\tvar sum int\n\tab := make([]bool, 28124)\n\tfor i := 12; i <= 28123; i++ {\n\t\tab[i] = isAbundant(i)\n\t}\n\tfor i := 1; i <= 28123; i++ {\n\t\tif !isSumOfTwoAbundant(i, ab) {\n\t\t\tsum += i\n\t\t}\n\t}\n\treturn sum\n}\n\nfunc main() {\n\tfmt.Println(solve())\n}\n\nfunc isSumOfTwoAbundant(n int, a []bool) bool ", "output": "{\n\tvar ret bool\n\tfor i := 1; i < n; i++ {\n\t\tif a[i] && a[n-i] {\n\t\t\tret = true\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ret\n}"} {"input": "package common\n\nimport (\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/instance\"\n\t\"github.com/juju/juju/state\"\n\t\"github.com/juju/names\"\n)\n\n\n\ntype InstanceIdGetter struct {\n\tst state.EntityFinder\n\tgetCanRead GetAuthFunc\n}\n\n\n\n\n\n\nfunc (ig *InstanceIdGetter) getInstanceId(tag names.Tag) (instance.Id, error) {\n\tentity0, err := ig.st.FindEntity(tag)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tentity, ok := entity0.(state.InstanceIdGetter)\n\tif !ok {\n\t\treturn \"\", NotSupportedError(tag, \"instance id\")\n\t}\n\treturn entity.InstanceId()\n}\n\n\n\nfunc (ig *InstanceIdGetter) InstanceId(args params.Entities) (params.StringResults, error) {\n\tresult := params.StringResults{\n\t\tResults: make([]params.StringResult, len(args.Entities)),\n\t}\n\tcanRead, err := ig.getCanRead()\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tfor i, entity := range args.Entities {\n\t\ttag, err := names.ParseTag(entity.Tag)\n\t\tif err != nil {\n\t\t\tresult.Results[i].Error = ServerError(ErrPerm)\n\t\t\tcontinue\n\t\t}\n\t\terr = ErrPerm\n\t\tif canRead(tag) {\n\t\t\tvar instanceId instance.Id\n\t\t\tinstanceId, err = ig.getInstanceId(tag)\n\t\t\tif err == nil {\n\t\t\t\tresult.Results[i].Result = string(instanceId)\n\t\t\t}\n\t\t}\n\t\tresult.Results[i].Error = ServerError(err)\n\t}\n\treturn result, nil\n}\n\nfunc NewInstanceIdGetter(st state.EntityFinder, getCanRead GetAuthFunc) *InstanceIdGetter ", "output": "{\n\treturn &InstanceIdGetter{\n\t\tst: st,\n\t\tgetCanRead: getCanRead,\n\t}\n}"} {"input": "package naming\n\nimport (\n\t\"github.com/snapcore/snapd/snapdenv\"\n)\n\nvar (\n\tprodWellKnownSnapIDs = map[string]string{\n\t\t\"core\": \"99T7MUlRhtI3U0QFgl5mXXESAiSwt776\",\n\t\t\"snapd\": \"PMrrV4ml8uWuEUDBT8dSGnKUYbevVhc4\",\n\t\t\"core18\": \"CSO04Jhav2yK0uz97cr0ipQRyqg0qQL6\",\n\t\t\"core20\": \"DLqre5XGLbDqg9jPtiAhRRjDuPVa5X1q\",\n\t}\n\n\tstagingWellKnownSnapIDs = map[string]string{\n\t\t\"core\": \"xMNMpEm0COPZy7jq9YRwWVLCD9q5peow\",\n\t\t\"snapd\": \"Z44rtQD1v4r1LXGPCDZAJO3AOw1EDGqy\",\n\t\t\"core18\": \"NhSvwckvNdvgdiVGlsO1vYmi3FPdTZ9U\",\n\t\t\"core20\": \"\",\n\t}\n)\n\nvar wellKnownSnapIDs = prodWellKnownSnapIDs\n\nfunc init() {\n\tif snapdenv.UseStagingStore() {\n\t\twellKnownSnapIDs = stagingWellKnownSnapIDs\n\t}\n}\n\n\n\n\n\nfunc UseStagingIDs(staging bool) (restore func()) {\n\told := wellKnownSnapIDs\n\tif staging {\n\t\twellKnownSnapIDs = stagingWellKnownSnapIDs\n\t} else {\n\t\twellKnownSnapIDs = prodWellKnownSnapIDs\n\t}\n\treturn func() {\n\t\twellKnownSnapIDs = old\n\t}\n}\n\nfunc WellKnownSnapID(snapName string) string ", "output": "{\n\treturn wellKnownSnapIDs[snapName]\n}"} {"input": "package vespa\n\nimport \"fmt\"\n\n\nvar PublicSystem = System{\n\tName: \"public\",\n\tURL: \"https://api-ctl.vespa-cloud.com:4443\",\n\tConsoleURL: \"https://console.vespa-cloud.com\",\n\tDefaultZone: ZoneID{Environment: \"dev\", Region: \"aws-us-east-1c\"},\n}\n\n\nvar PublicCDSystem = System{\n\tName: \"publiccd\",\n\tURL: \"https://api-ctl.cd.vespa-cloud.com:4443\",\n\tConsoleURL: \"https://console.cd.vespa-cloud.com\",\n\tDefaultZone: ZoneID{Environment: \"dev\", Region: \"aws-us-east-1c\"},\n}\n\n\nvar MainSystem = System{\n\tName: \"main\",\n\tURL: \"https://api.vespa.ouryahoo.com:4443\",\n\tConsoleURL: \"https://console.vespa.ouryahoo.com\",\n\tDefaultZone: ZoneID{Environment: \"dev\", Region: \"us-east-1\"},\n\tAthenzDomain: \"vespa.vespa\",\n}\n\n\nvar CDSystem = System{\n\tName: \"cd\",\n\tURL: \"https://api-cd.vespa.ouryahoo.com:4443\",\n\tConsoleURL: \"https://console-cd.vespa.ouryahoo.com\",\n\tDefaultZone: ZoneID{Environment: \"dev\", Region: \"cd-us-west-1\"},\n\tAthenzDomain: \"vespa.vespa.cd\",\n}\n\n\ntype System struct {\n\tName string\n\tURL string\n\tConsoleURL string\n\tDefaultZone ZoneID\n\tAthenzDomain string\n}\n\n\nfunc (s *System) IsPublic() bool { return s.Name == PublicSystem.Name || s.Name == PublicCDSystem.Name }\n\n\n\n\nfunc GetSystem(name string) (System, error) ", "output": "{\n\tswitch name {\n\tcase \"cd\":\n\t\treturn CDSystem, nil\n\tcase \"main\":\n\t\treturn MainSystem, nil\n\tcase \"public\":\n\t\treturn PublicSystem, nil\n\tcase \"publiccd\":\n\t\treturn PublicCDSystem, nil\n\t}\n\treturn System{}, fmt.Errorf(\"invalid system: %s\", name)\n}"} {"input": "package utils\n\nimport (\n \"unsafe\"\n \"reflect\"\n)\n\n\n\n\n\nfunc StringPointer(s string) unsafe.Pointer {\n\tp := (*reflect.StringHeader)(unsafe.Pointer(&s))\n\treturn unsafe.Pointer(p.Data)\n}\n\n\nfunc BytePointer(b []byte) unsafe.Pointer {\n\tp := (*reflect.SliceHeader)(unsafe.Pointer(&b))\n\treturn unsafe.Pointer(p.Data)\n}\n\nfunc ByteString(b []byte) string ", "output": "{\n\treturn *(*string)(unsafe.Pointer(&b))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/jackytck/projecteuler/tools\"\n)\n\n\n\nfunc check(p string, log []string) bool {\n\tfor _, s := range log {\n\t\tif !match(p, s) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc solve(path string) string {\n\tlogs, err := tools.ReadFile(path)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\texist := make(map[string]bool)\n\tvar unique []string\n\tfor _, v := range logs {\n\t\tif !exist[v] {\n\t\t\tunique = append(unique, v)\n\t\t\texist[v] = true\n\t\t}\n\t}\n\n\tfor p := range tools.Perms([]int{0, 1, 2, 3, 6, 7, 8, 9}) {\n\t\tpsw := tools.JoinIntsString(p...)\n\t\tif check(psw, unique) {\n\t\t\treturn psw\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\nfunc main() {\n\tfmt.Println(solve(\"./p079_keylog.txt\"))\n}\n\nfunc match(p, s string) bool ", "output": "{\n\tm := make(map[rune]bool)\n\tfor _, r := range s {\n\t\tm[r] = true\n\t}\n\tvar e string\n\tfor _, r := range p {\n\t\tif m[r] {\n\t\t\te += string(r)\n\t\t}\n\t}\n\treturn e == s\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net\"\n\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/host\", hostFinder)\n\thttp.HandleFunc(\"/ip\", sourceIp)\n\thttp.HandleFunc(\"/date\", GetJosnTime)\n\tfmt.Println(\"Listening on 0.0.0.0:8000\")\n\terr := http.ListenAndServe(\"0.0.0.0:8000\", nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}\n\nfunc hostFinder(rw http.ResponseWriter, req *http.Request) {\n\thostPort := req.Host\n\thost, port, _ := net.SplitHostPort(hostPort)\n\tio.WriteString(rw, \"\")\n\tio.WriteString(rw, \"Host Name : \"+host+\"
\")\n\tio.WriteString(rw, \"Port Number : \"+port)\n\tio.WriteString(rw, \"
\")\n\tio.WriteString(rw, req.RemoteAddr)\n\tio.WriteString(rw, \"\")\n\n}\n\n\nfunc GetJosnTime(rw http.ResponseWriter, req *http.Request) {\n\trw.Header().Set(\"Content-type\", \"application/json\")\n\trw.Header().Add(\"Content-type\", \"charset=utf-8\")\n\tresponse, _ := http.Get(\"http://date.jsontest.com/\")\n\tdefer response.Body.Close()\n\n\tdata, _ := ioutil.ReadAll(response.Body)\n\tio.WriteString(rw, string(data))\n\n}\n\nfunc sourceIp(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\thost, _, _ := net.SplitHostPort(req.RemoteAddr)\n\tio.WriteString(rw, \"

Your Ip address : \"+host)\n}"} {"input": "package logrus\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"runtime\"\n)\n\n\nfunc (logger *Logger) Writer() *io.PipeWriter {\n\treturn logger.WriterLevel(InfoLevel)\n}\n\n\n\n\n\n\nfunc (logger *Logger) WriterLevel(level Level) *io.PipeWriter {\n\treturn NewEntry(logger).WriterLevel(level)\n}\n\nfunc (entry *Entry) Writer() *io.PipeWriter {\n\treturn entry.WriterLevel(InfoLevel)\n}\n\nfunc (entry *Entry) WriterLevel(level Level) *io.PipeWriter {\n\treader, writer := io.Pipe()\n\n\tvar printFunc func(args ...interface{})\n\n\tswitch level {\n\tcase TraceLevel:\n\t\tprintFunc = entry.Trace\n\tcase DebugLevel:\n\t\tprintFunc = entry.Debug\n\tcase InfoLevel:\n\t\tprintFunc = entry.Info\n\tcase WarnLevel:\n\t\tprintFunc = entry.Warn\n\tcase ErrorLevel:\n\t\tprintFunc = entry.Error\n\tcase FatalLevel:\n\t\tprintFunc = entry.Fatal\n\tcase PanicLevel:\n\t\tprintFunc = entry.Panic\n\tdefault:\n\t\tprintFunc = entry.Print\n\t}\n\n\tgo entry.writerScanner(reader, printFunc)\n\truntime.SetFinalizer(writer, writerFinalizer)\n\n\treturn writer\n}\n\nfunc (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {\n\tscanner := bufio.NewScanner(reader)\n\tfor scanner.Scan() {\n\t\tprintFunc(scanner.Text())\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tentry.Errorf(\"Error while reading from Writer: %s\", err)\n\t}\n\treader.Close()\n}\n\n\n\nfunc writerFinalizer(writer *io.PipeWriter) ", "output": "{\n\twriter.Close()\n}"} {"input": "package commands\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/pivotal-cf/jhanda\"\n\t\"github.com/pivotal-cf/om/api\"\n)\n\ntype InstallationLog struct {\n\tservice installationLogService\n\tlogger logger\n\tOptions struct {\n\t\tId int `long:\"id\" required:\"true\" description:\"id of the installation to retrieve logs for\"`\n\t}\n}\n\n\ntype installationLogService interface {\n\tGetInstallationLogs(id int) (api.InstallationsServiceOutput, error)\n}\n\nfunc NewInstallationLog(service installationLogService, logger logger) InstallationLog {\n\treturn InstallationLog{\n\t\tservice: service,\n\t\tlogger: logger,\n\t}\n}\n\n\n\nfunc (i InstallationLog) Usage() jhanda.Usage {\n\treturn jhanda.Usage{\n\t\tDescription: \"This authenticated command retrieves the logs for a given installation.\",\n\t\tShortDescription: \"output installation logs\",\n\t\tFlags: i.Options,\n\t}\n}\n\nfunc (i InstallationLog) Execute(args []string) error ", "output": "{\n\tif _, err := jhanda.Parse(&i.Options, args); err != nil {\n\t\treturn fmt.Errorf(\"could not parse installation-log flags: %s\", err)\n\t}\n\n\toutput, err := i.service.GetInstallationLogs(i.Options.Id)\n\tif err != nil {\n\t\treturn err\n\t}\n\ti.logger.Print(output.Logs)\n\treturn nil\n}"} {"input": "package service\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"golang.org/x/sys/windows/svc\"\n\t\"golang.org/x/sys/windows/svc/debug\"\n\n\t\"github.com/elastic/beats/libbeat/logp\"\n)\n\ntype beatService struct{}\n\n\n\n\n\n\n\n\n\n\nfunc ProcessWindowsControlEvents(stopCallback func()) {\n\tisInteractive, err := svc.IsAnInteractiveSession()\n\tif err != nil {\n\t\tlogp.Err(\"IsAnInteractiveSession: %v\", err)\n\t\treturn\n\t}\n\tlogp.Debug(\"service\", \"Windows is interactive: %v\", isInteractive)\n\n\trun := svc.Run\n\tif isInteractive {\n\t\trun = debug.Run\n\t}\n\terr = run(os.Args[0], &beatService{})\n\tif err != nil {\n\t\tlogp.Err(\"Error: %v\", err)\n\t} else {\n\t\tstopCallback()\n\t}\n}\n\nfunc (m *beatService) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) ", "output": "{\n\tconst cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown\n\tchanges <- svc.Status{State: svc.StartPending}\n\tchanges <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}\n\nloop:\n\tfor c := range r {\n\t\tswitch c.Cmd {\n\t\tcase svc.Interrogate:\n\t\t\tchanges <- c.CurrentStatus\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\tchanges <- c.CurrentStatus\n\t\tcase svc.Stop, svc.Shutdown:\n\t\t\tbreak loop\n\t\tdefault:\n\t\t\tlogp.Err(\"Unexpected control request: $%d. Ignored.\", c)\n\t\t}\n\t}\n\tchanges <- svc.Status{State: svc.StopPending}\n\treturn\n}"} {"input": "package bds\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype MetricThresholdRule struct {\n\n\tDurationInMinutes *int `mandatory:\"true\" json:\"durationInMinutes\"`\n\n\tOperator MetricThresholdRuleOperatorEnum `mandatory:\"true\" json:\"operator\"`\n\n\tValue *int `mandatory:\"true\" json:\"value\"`\n}\n\n\n\n\ntype MetricThresholdRuleOperatorEnum string\n\n\nconst (\n\tMetricThresholdRuleOperatorGt MetricThresholdRuleOperatorEnum = \"GT\"\n\tMetricThresholdRuleOperatorLt MetricThresholdRuleOperatorEnum = \"LT\"\n)\n\nvar mappingMetricThresholdRuleOperator = map[string]MetricThresholdRuleOperatorEnum{\n\t\"GT\": MetricThresholdRuleOperatorGt,\n\t\"LT\": MetricThresholdRuleOperatorLt,\n}\n\n\nfunc GetMetricThresholdRuleOperatorEnumValues() []MetricThresholdRuleOperatorEnum {\n\tvalues := make([]MetricThresholdRuleOperatorEnum, 0)\n\tfor _, v := range mappingMetricThresholdRuleOperator {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}\n\nfunc (m MetricThresholdRule) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package pointer\n\nimport \"time\"\n\nfunc DefaultBool(value *bool, defaultValue bool) *bool {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultDuration(value *time.Duration, defaultValue time.Duration) *time.Duration {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultFloat64(value *float64, defaultValue float64) *float64 {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultInt(value *int, defaultValue int) *int {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultString(value *string, defaultValue string) *string {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\n\n\nfunc DefaultTime(value *time.Time, defaultValue time.Time) *time.Time {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultStringArray(value *[]string, defaultValue []string) *[]string ", "output": "{\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}"} {"input": "package kingpin\n\nimport (\n\t\"github.com/nicksnyder/go-i18n/i18n\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestI18N_fr(t *testing.T) ", "output": "{\n\tf, err := i18n.Tfunc(\"fr\")\n\trequire.NoError(t, err)\n\trequire.Equal(t,\n\t\t\"Afficher l'aide contextuelle.\",\n\t\tf(\"Show context-sensitive help.\"),\n\t)\n}"} {"input": "package plugins\n\nimport (\n\t\"fmt\"\n\t\"github.com/mattn/go-xmpp\"\n\t\"github.com/yetist/xmppbot/robot\"\n\t\"strings\"\n)\n\ntype Example struct {\n\tName string\n\tOption map[string]bool\n\tbot *robot.Bot\n}\n\nfunc NewExample(name string, opt map[string]interface{}) *Example {\n\treturn &Example{\n\t\tName: name,\n\t\tOption: map[string]bool{},\n\t}\n}\n\nfunc (m *Example) GetName() string {\n\treturn m.Name\n}\n\nfunc (m *Example) GetSummary() string {\n\treturn \"示例模块\"\n}\n\nfunc (m *Example) Help() string {\n\tmsg := []string{\n\t\tm.GetSummary() + \": 回显消息.\",\n\t}\n\treturn strings.Join(msg, \"\\n\")\n}\n\n\n\nfunc (m *Example) CheckEnv() bool {\n\treturn true\n}\n\nfunc (m *Example) Start(bot *robot.Bot) {\n\tfmt.Printf(\"[%s] Starting...\\n\", m.GetName())\n\tm.bot = bot\n}\n\nfunc (m *Example) Stop() {\n\tfmt.Printf(\"[%s] Stop\\n\", m.GetName())\n}\n\nfunc (m *Example) Restart() {\n}\n\nfunc (m *Example) Chat(msg xmpp.Chat) {\n\tif len(msg.Text) == 0 || !msg.Stamp.IsZero() {\n\t\treturn\n\t}\n\tm.bot.ReplyAuto(msg, msg.Text)\n}\n\nfunc (m *Example) Presence(pres xmpp.Presence) {\n}\n\nfunc (m *Example) GetOptions() map[string]string {\n\topts := map[string]string{}\n\treturn opts\n}\n\nfunc (m *Example) SetOption(key, val string) {\n}\n\nfunc (m *Example) Description() string ", "output": "{\n\tmsg := []string{m.Help(),\n\t\t\"当有好友或群聊消息时将自动回复原内容。\",\n\t\t\"本模块可配置属性:\",\n\t}\n\treturn strings.Join(msg, \"\\n\")\n}"} {"input": "package ddd\n\n\n\nfunc Sum(args ...int) int ", "output": "{\n\ts := 0\n\tfor _, v := range args {\n\t\ts += v\n\t}\n\treturn s\n}"} {"input": "package all\n\nimport \"github.com/catorpilor/leetcode/utils\"\n\nfunc allElements(root1, root2 *utils.TreeNode) []int {\n\treturn useMorris(root1, root2)\n}\n\n\n\n\nfunc useMorris(root1, root2 *utils.TreeNode) []int ", "output": "{\n\tu1, u2 := utils.InorderTraversal(root1), utils.InorderTraversal(root2)\n\tn1, n2 := len(u1), len(u2)\n\tans := make([]int, 0, n1+n2)\n\tvar i, j int\n\tfor i != n1 && j != n2 {\n\t\tif u1[i] <= u2[j] {\n\t\t\tans = append(ans, u1[i])\n\t\t\ti++\n\t\t} else {\n\t\t\tans = append(ans, u2[j])\n\t\t\tj++\n\t\t}\n\t}\n\tif i != n1 {\n\t\tans = append(ans, u1[i:]...)\n\t}\n\tif j != n2 {\n\t\tans = append(ans, u2[j:]...)\n\t}\n\treturn ans\n}"} {"input": "package tbin\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\n\n\nfunc TestTBinMarshalGenericEncode(test *testing.T) ", "output": "{\n\tvar line interface{}\n\ttdata, err := ioutil.ReadFile(\"../testdata/test.tbin\")\n\terr = Unmarshal(tdata, &line)\n\tif err != nil {\n\t\ttest.Errorf(\"Cannot unmarshal test.tbin: %v\", err)\n\t}\n\terr = Unmarshal(tdata, &line)\n\tif err != nil {\n\t\ttest.Errorf(\"Cannot unmarshal test.tbin: %v\", err)\n\t}\n\ttdata2, err := Marshal(line)\n\tif err != nil {\n\t\ttest.Errorf(\"Cannot marshal generic data:, %v\", err)\n\t} else {\n\t\tfmt.Println(\"tbin (generic) is\", len(tdata2), \"bytes long\")\n\t\tioutil.WriteFile(\"../target/test_generic.tbin\", tdata2, 0644)\n\t}\n}"} {"input": "package internal \n\nimport (\n\t\"strings\"\n)\n\nconst (\n\tWatchState = 1 << iota\n\tMultiState\n\tSubscribeState\n\tMonitorState\n)\n\ntype CommandInfo struct {\n\tSet, Clear int\n}\n\nvar commandInfos = map[string]CommandInfo{\n\t\"WATCH\": {Set: WatchState},\n\t\"UNWATCH\": {Clear: WatchState},\n\t\"MULTI\": {Set: MultiState},\n\t\"EXEC\": {Clear: WatchState | MultiState},\n\t\"DISCARD\": {Clear: WatchState | MultiState},\n\t\"PSUBSCRIBE\": {Set: SubscribeState},\n\t\"SUBSCRIBE\": {Set: SubscribeState},\n\t\"MONITOR\": {Set: MonitorState},\n}\n\nfunc init() {\n\tfor n, ci := range commandInfos {\n\t\tcommandInfos[strings.ToLower(n)] = ci\n\t}\n}\n\n\n\nfunc LookupCommandInfo(commandName string) CommandInfo ", "output": "{\n\tif ci, ok := commandInfos[commandName]; ok {\n\t\treturn ci\n\t}\n\treturn commandInfos[strings.ToUpper(commandName)]\n}"} {"input": "package views\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\tui \"github.com/jroimartin/gocui\"\n)\n\nvar (\n\thelpWidth = 49\n\thelpHeight = 15\n\ttpl = `%s C-x means Control x`\n)\n\ntype help struct {\n\tname string\n\tcoords coords\n\tbody []byte\n}\n\nfunc newHelp(w, h int) *help {\n\treturn &help{\n\t\tname: \"help\",\n\t}\n}\n\n\n\nfunc (h *help) show(g *ui.Gui, v *ui.View, keys []key) error {\n\tv.Editable = false\n\tif h.body == nil {\n\t\th.body = h.getBody(keys)\n\t}\n\n\tvar err error\n\n\tcoords := getHelpCoords(g)\n\n\tv, err = g.SetView(\"help\", coords.x1, coords.y1, coords.x2, coords.y2)\n\tif err != ui.ErrUnknownView {\n\t\treturn err\n\t}\n\n\tv.Title = h.name\n\n\tv.Write([]byte(h.body))\n\t_, err = g.SetCurrentView(\"help\")\n\treturn err\n}\n\nfunc (h *help) hide(g *ui.Gui, v *ui.View) error {\n\tv.Clear()\n\treturn g.DeleteView(h.name)\n}\n\nfunc (h *help) getBody(keys []key) []byte {\n\tout := &bytes.Buffer{}\n\tfor _, key := range keys {\n\t\th := key.help\n\t\tif h.key != \"\" {\n\t\t\tfmt.Fprintf(out, fmt.Sprintf(\"%s %s\\n\", c3(h.key), c1(fmt.Sprintf(fmt.Sprintf(\"%%%ds\", helpWidth-len(h.key)-4), h.body))))\n\t\t}\n\t}\n\treturn []byte(fmt.Sprintf(tpl, out.String()))\n}\n\nfunc getHelpCoords(g *ui.Gui) coords ", "output": "{\n\tmaxX, maxY := g.Size()\n\tx1 := maxX/2 - helpWidth/2\n\tx2 := maxX/2 + helpWidth/2\n\ty1 := maxY/2 - helpHeight/2\n\ty2 := maxY/2 + helpHeight/2 + helpHeight%2\n\treturn coords{x1: x1, y1: y1, x2: x2, y2: y2}\n}"} {"input": "package restinspectorhandler\n\nimport (\n\tlog \"github.com/cihub/seelog\"\n\t. \"github.com/osrg/earthquake/earthquake/entity\"\n\t. \"github.com/osrg/earthquake/earthquake/inspectorhandler/restinspectorhandler/queue\"\n\t. \"github.com/osrg/earthquake/earthquake/signal\"\n)\n\nfunc registerNewEntity(entityID string) (*TransitionEntity, *ActionQueue, error) {\n\tlog.Debugf(\"Registering entity: %s\", entityID)\n\tentity := TransitionEntity{\n\t\tID: entityID,\n\t\tActionFromMain: make(chan Action),\n\t\tEventToMain: make(chan Event),\n\t}\n\tif err := RegisterTransitionEntity(&entity); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tqueue, err := RegisterNewQueue(entityID)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tpropagateActionFromMain(&entity, queue)\n\t\t}\n\t}()\n\tlog.Debugf(\"Registered entity: %s\", entityID)\n\treturn &entity, queue, nil\n}\n\nfunc sendEventToMain(entity *TransitionEntity, event Event) {\n\tlog.Debugf(\"Handler[%s]->Main: sending an event %s\", entity.ID, event)\n\tsentToEntityCh := make(chan bool)\n\tsentToMainCh := make(chan bool)\n\tgo func() {\n\t\tentity.EventToMain <- event\n\t\tsentToEntityCh <- true\n\t}()\n\tgo func() {\n\t\tmainReadyEntityCh <- entity\n\t\tsentToMainCh <- true\n\t}()\n\t<-sentToEntityCh\n\t<-sentToMainCh\n\tlog.Debugf(\"Handler[%s]->Main: sent event %s\", entity.ID, event)\n}\n\n\n\nfunc propagateActionFromMain(entity *TransitionEntity, queue *ActionQueue) ", "output": "{\n\tlog.Debugf(\"Handler[%s]<-Main: receiving an action\", entity.ID)\n\taction := <-entity.ActionFromMain\n\tlog.Debugf(\"Handler[%s]<-Main: received an action %s\", entity.ID, action)\n\tqueue.Put(action)\n}"} {"input": "package resourceapply\n\nimport (\n\t\"testing\"\n\n\t\"github.com/openshift/library-go/pkg/operator/events\"\n\t\"k8s.io/client-go/kubernetes/fake\"\n\n\t\"github.com/davecgh/go-spew/spew\"\n)\n\n\n\nfunc TestApplyDirectlyUnhandledType(t *testing.T) {\n\tfakeClient := fake.NewSimpleClientset()\n\tcontent := func(name string) ([]byte, error) {\n\t\treturn []byte(`apiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n name: sample-claim\n labels:\n openshift.io/run-level: \"1\"\n`), nil\n\t}\n\trecorder := events.NewInMemoryRecorder(\"\")\n\tret := ApplyDirectly(fakeClient, recorder, content, \"pvc\")\n\tif ret[0].Error == nil {\n\t\tt.Fatal(\"missing expected error\")\n\t} else if ret[0].Error.Error() != \"unhandled type *v1.PersistentVolumeClaim\" {\n\t\tt.Fatal(ret[0].Error)\n\t}\n}\n\nfunc TestApplyDirectly(t *testing.T) ", "output": "{\n\trequiredObj, gvk, err := genericCodec.Decode([]byte(`apiVersion: v1\nkind: Namespace\nmetadata:\n name: openshift-apiserver\n labels:\n openshift.io/run-level: \"1\"\n`), nil, nil)\n\tt.Log(spew.Sdump(requiredObj))\n\tt.Log(spew.Sdump(gvk))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package fields\n\nimport (\n\t\"regexp\"\n\t\"time\"\n)\n\n\n\nfunc ExecFuncIfErrIsNotNil(err error, fn func()) (b bool) {\n\tif nil != err {\n\t\tfn()\n\t\tb = true\n\t}\n\treturn\n}\n\nfunc getMessageFromError(err error) string {\n\tif nil == err {\n\t\treturn \"\"\n\t}\n\treturn err.Error()\n}\n\nfunc getPatternFromRegExp(re *regexp.Regexp) string {\n\tif nil == re {\n\t\treturn \"\"\n\t}\n\treturn re.String()\n}\n\nfunc execFnIfNotNil(fn func()) {\n\tif nil != fn {\n\t\tfn()\n\t}\n}\n\nfunc addSuffix(name string, suffix *string) string {\n\tif nil != suffix {\n\t\treturn name + \"-\" + *suffix\n\t}\n\treturn name\n}\n\nfunc _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) (*time.Location, int) {\n\tif nil == locationByString || \"\" == *locationByString {\n\t\treturn defaultLoc, 1\n\t}\n\n\tif loc, err := time.LoadLocation(*locationByString); nil == err {\n\t\treturn loc, 2\n\t}\n\n\treturn defaultLoc, 0\n}\n\n\nfunc useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) *time.Location {\n\tloc, _ := _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc, locationByString)\n\treturn loc\n}\n\nfunc UseDefaultKeyIfCustomKeyIsEmpty(defaultKey, customKey string) string ", "output": "{\n\tif \"\" != customKey {\n\t\treturn customKey\n\t}\n\treturn defaultKey\n}"} {"input": "package runewidth\n\nimport (\n\t\"testing\"\n\t\"unicode/utf8\"\n)\n\nvar benchSink int\n\nfunc benchTable(b *testing.B, tbl table) int {\n\tn := 0\n\tfor i := 0; i < b.N; i++ {\n\t\tfor r := rune(0); r <= utf8.MaxRune; r++ {\n\t\t\tif inTable(r, tbl) {\n\t\t\t\tn++\n\t\t\t}\n\t\t}\n\t}\n\treturn n\n}\n\nfunc BenchmarkTablePrivate(b *testing.B) {\n\tbenchSink = benchTable(b, private)\n}\nfunc BenchmarkTableNonprint(b *testing.B) {\n\tbenchSink = benchTable(b, nonprint)\n}\nfunc BenchmarkTableCombining(b *testing.B) {\n\tbenchSink = benchTable(b, combining)\n}\n\nfunc BenchmarkTableAmbiguous(b *testing.B) {\n\tbenchSink = benchTable(b, ambiguous)\n}\nfunc BenchmarkTableEmoji(b *testing.B) {\n\tbenchSink = benchTable(b, emoji)\n}\nfunc BenchmarkTableNotassigned(b *testing.B) {\n\tbenchSink = benchTable(b, notassigned)\n}\nfunc BenchmarkTableNeutral(b *testing.B) {\n\tbenchSink = benchTable(b, neutral)\n}\n\nfunc BenchmarkTableDoublewidth(b *testing.B) ", "output": "{\n\tbenchSink = benchTable(b, doublewidth)\n}"} {"input": "package monator\n\nimport (\n \"time\"\n \"bytes\"\n \"encoding/json\"\n)\n\ntype CheckDuration time.Duration\n\nfunc (d CheckDuration) Hours() float64 {\n return time.Duration(d).Hours()\n}\n\nfunc (d CheckDuration) Minutes() float64 {\n return time.Duration(d).Minutes()\n}\n\nfunc (d CheckDuration) Nanoseconds() int64 {\n return time.Duration(d).Nanoseconds()\n}\n\nfunc (d CheckDuration) Seconds() float64 {\n return time.Duration(d).Seconds()\n}\n\n\n\nfunc (d CheckDuration) String() string {\n \n rounded := ((time.Duration(d)).Nanoseconds() / int64(time.Millisecond)) * int64(time.Millisecond)\n return time.Duration(rounded).String()\n}\n\n\nfunc (d *CheckDuration) UnmarshalJSON(data []byte) error {\n b := bytes.NewBuffer(data)\n dec := json.NewDecoder(b)\n\n var s string\n\n if err := dec.Decode(&s); err != nil {\n return err\n }\n if duration, err := time.ParseDuration(s); err != nil {\n return err\n } else {\n *d = CheckDuration(duration)\n }\n\n return nil\n}\n\nfunc (d CheckDuration) Milliseconds() int64 ", "output": "{\n return time.Duration(d).Nanoseconds() / int64(time.Millisecond)\n}"} {"input": "package autositespeed\n\nimport (\n\t\"log\"\n\n\t\"gopkg.in/natefinch/lumberjack.v2\"\n)\n\ntype LogOptions struct {\n\tEnabled bool\n\tFilePath string\n\tMaxSize int\n\tMaxBackups int\n\tMaxAge int\n}\n\n\n\ntype logWriter struct {\n}\n\nfunc (lw *logWriter) Write(p []byte) (n int, err error) {\n\tlog.Println(string(p))\n\n\treturn len(p), nil\n}\n\nfunc initLogging(options *LogOptions) ", "output": "{\n\tlog.SetOutput(&lumberjack.Logger{\n\t\tFilename: options.FilePath,\n\t\tMaxSize: options.MaxSize,\n\t\tMaxAge: options.MaxAge,\n\t\tMaxBackups: options.MaxBackups,\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc digitSum(n int) int {\n\tsum := 0\n\tfor n > 0 {\n\t\tsum += n % 10\n\t\tn /= 10\n\t}\n\treturn sum\n}\n\n\n\nfunc primeFactorize(n int) []int {\n\tvar p []int\n\tfor i := 2; i <= n; i++ {\n\t\tfor isPrime(i) {\n\t\t\tfor n%i == 0 {\n\t\t\t\tp = append(p, i)\n\t\t\t\tn /= i\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\treturn p\n}\n\nfunc main() {\n\tin, _ := os.Open(\"10042.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"10042.out\")\n\tdefer out.Close()\n\n\tvar n, num int\n\tfor fmt.Fscanf(in, \"%d\", &n); n > 0; n-- {\n\t\tfor fmt.Fscanf(in, \"%d\", &num); ; num++ {\n\t\t\tsum1 := digitSum(num)\n\t\t\tsum2 := 0\n\t\t\tfor _, v := range primeFactorize(num) {\n\t\t\t\tsum2 += digitSum(v)\n\t\t\t}\n\t\t\tif sum1 == sum2 {\n\t\t\t\tfmt.Fprintln(out, num)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc isPrime(n int) bool ", "output": "{\n\tif n%2 == 0 {\n\t\treturn n == 2\n\t}\n\tfor i := 3; i*i <= n; i += 2 {\n\t\tif n%i == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package cache\n\nimport (\n\t\"context\"\n\n\t\"github.com/go-kit/log\"\n\t\"github.com/go-kit/log/level\"\n\n\tutil_log \"github.com/grafana/loki/pkg/util/log\"\n)\n\n\ntype RedisCache struct {\n\tname string\n\tredis *RedisClient\n\tlogger log.Logger\n}\n\n\nfunc NewRedisCache(name string, redisClient *RedisClient, logger log.Logger) *RedisCache {\n\tutil_log.WarnExperimentalUse(\"Redis cache\", logger)\n\tcache := &RedisCache{\n\t\tname: name,\n\t\tredis: redisClient,\n\t\tlogger: logger,\n\t}\n\tif err := cache.redis.Ping(context.Background()); err != nil {\n\t\tlevel.Error(logger).Log(\"msg\", \"error connecting to redis\", \"name\", name, \"err\", err)\n\t}\n\treturn cache\n}\n\n\nfunc (c *RedisCache) Fetch(ctx context.Context, keys []string) (found []string, bufs [][]byte, missed []string, err error) {\n\tdata, err := c.redis.MGet(ctx, keys)\n\tif err != nil {\n\t\tlevel.Error(c.logger).Log(\"msg\", \"failed to get from redis\", \"name\", c.name, \"err\", err)\n\t\tmissed = make([]string, len(keys))\n\t\tcopy(missed, keys)\n\t\treturn\n\t}\n\tfor i, key := range keys {\n\t\tif data[i] != nil {\n\t\t\tfound = append(found, key)\n\t\t\tbufs = append(bufs, data[i])\n\t\t} else {\n\t\t\tmissed = append(missed, key)\n\t\t}\n\t}\n\treturn\n}\n\n\n\n\n\nfunc (c *RedisCache) Stop() {\n\t_ = c.redis.Close()\n}\n\nfunc (c *RedisCache) Store(ctx context.Context, keys []string, bufs [][]byte) error ", "output": "{\n\terr := c.redis.MSet(ctx, keys, bufs)\n\tif err != nil {\n\t\tlevel.Error(c.logger).Log(\"msg\", \"failed to put to redis\", \"name\", c.name, \"err\", err)\n\t}\n\treturn err\n}"} {"input": "package engine\n\nimport (\n\t\"github.com/nicholaskh/pushd/engine/storage\"\n)\n\n\nfunc history(channel string, ts int64) (result []interface{}, err error) {\n\tresult = storage.MsgCache.GetRange(channel, ts)\n\n\treturn\n}\n\n\n\n\nfunc fullHistory(channel string, ts int64) (result []interface{}, err error) ", "output": "{\n\tresult, err = storage.FetchHistory(channel, ts)\n\n\treturn\n}"} {"input": "package goparser\n\nimport (\n\t\"strings\"\n)\n\nfunc isExceptedStatement(name string, prefixs, suffixs, fullnames []string) bool {\n\tname = strings.ToLower(name)\n\tfor _, prefix := range prefixs {\n\t\tif strings.HasPrefix(name, prefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tfor _, suffix := range suffixs {\n\t\tif strings.HasSuffix(name, suffix) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, fullname := range fullnames {\n\t\tif name == fullname {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc isInsertStatement(name string) bool {\n\treturn isExceptedStatement(name, []string{\n\t\t\"insert\",\n\t\t\"upsert\",\n\t\t\"add\",\n\t\t\"create\",\n\t}, nil, nil)\n}\n\n\nfunc isDeleteStatement(name string) bool {\n\treturn isExceptedStatement(name, []string{\n\t\t\"delete\",\n\t\t\"remove\",\n\t\t\"clear\",\n\t}, nil, nil)\n}\nfunc isSelectStatement(name string) bool {\n\treturn isExceptedStatement(name, []string{\n\t\t\"select\",\n\t\t\"find\",\n\t\t\"get\",\n\t\t\"query\",\n\t\t\"list\",\n\t\t\"count\",\n\t\t\"read\",\n\t\t\"statby\",\n\t\t\"statsby\",\n\t}, []string{\"count\"}, []string{\"id\", \"all\", \"names\", \"titles\"})\n}\n\nfunc isUpdateStatement(name string) bool ", "output": "{\n\treturn isExceptedStatement(name, []string{\n\t\t\"set\",\n\t\t\"update\",\n\t}, nil, nil)\n}"} {"input": "package model\n\nimport (\n\t\"github.com/evolsnow/samaritan/common/caches\"\n\t\"github.com/evolsnow/samaritan/common/dbms\"\n\t\"time\"\n)\n\nvar cache *caches.SimpleCache\n\n\n\nfunc beforeTest() {\n\tcache = caches.NewCache()\n\tu := &User{\n\t\tSamId: \"evol\",\n\t\tAlias: \"evol\",\n\t\tName: \"张三\",\n\t\tPhone: \"13212341234\",\n\t\tPassword: \"oldpwd\",\n\t\tEmail: \"gsc1215225@gmail.com\",\n\t}\n\tu.Save()\n\tdbms.CreateSearchIndex(u.Id, \"gsc1215225@gmail.com\", \"mail\")\n\tcache.Set(\"gsc1215225@gmail.com:code\", \"123456\", time.Minute*5)\n\n\tt := &Todo{\n\t\tOwnerId: u.Id,\n\t\tStartTime: time.Now().Unix(),\n\t\tDesc: \"desc here\",\n\t}\n\tt.Save()\n\tcache.Set(\"delete_test_todo_pid\", t.Pid, time.Minute*5)\n}\n\nfunc init() ", "output": "{\n\tdbms.Pool = dbms.NewPool(\"127.0.0.1:6379\", \"\", \"2\")\n\tdbms.CachePool = dbms.NewPool(\"127.0.0.1:6379\", \"\", \"9\")\n\tc := dbms.Pool.Get()\n\tdefer c.Close()\n\tc.Do(\"FLUSHDB\")\n\tcc := dbms.CachePool.Get()\n\tdefer cc.Close()\n\tcc.Do(\"FLUSHDB\")\n\tbeforeTest()\n}"} {"input": "package rule\n\nimport (\n\t\"go/ast\"\n\n\t\"github.com/mgechev/revive/lint\"\n)\n\n\ntype NestedStructs struct{}\n\n\nfunc (r *NestedStructs) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {\n\tvar failures []lint.Failure\n\n\tif len(arguments) > 0 {\n\t\tpanic(r.Name() + \" doesn't take any arguments\")\n\t}\n\n\twalker := &lintNestedStructs{\n\t\tfileAST: file.AST,\n\t\tonFailure: func(failure lint.Failure) {\n\t\t\tfailures = append(failures, failure)\n\t\t},\n\t}\n\n\tast.Walk(walker, file.AST)\n\n\treturn failures\n}\n\n\n\n\ntype lintNestedStructs struct {\n\tfileAST *ast.File\n\tonFailure func(lint.Failure)\n}\n\nfunc (l *lintNestedStructs) Visit(n ast.Node) ast.Visitor {\n\tswitch v := n.(type) {\n\tcase *ast.FuncDecl:\n\t\tif v.Body != nil {\n\t\t\tast.Walk(l, v.Body)\n\t\t}\n\t\treturn nil\n\tcase *ast.Field:\n\t\tif _, ok := v.Type.(*ast.StructType); ok {\n\t\t\tl.onFailure(lint.Failure{\n\t\t\t\tFailure: \"no nested structs are allowed\",\n\t\t\t\tCategory: \"style\",\n\t\t\t\tNode: v,\n\t\t\t\tConfidence: 1,\n\t\t\t})\n\t\t\tbreak\n\t\t}\n\t}\n\treturn l\n}\n\nfunc (r *NestedStructs) Name() string ", "output": "{\n\treturn \"nested-structs\"\n}"} {"input": "package stores\n\nimport \"jvmgo/ch06/instructions/base\"\nimport \"jvmgo/ch06/rtda\"\n\n\ntype ISTORE struct{ base.Index8Instruction }\n\n\n\ntype ISTORE_0 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_0) Execute(frame *rtda.Frame) {\n\t_istore(frame, 0)\n}\n\ntype ISTORE_1 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_1) Execute(frame *rtda.Frame) {\n\t_istore(frame, 1)\n}\n\ntype ISTORE_2 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_2) Execute(frame *rtda.Frame) {\n\t_istore(frame, 2)\n}\n\ntype ISTORE_3 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_3) Execute(frame *rtda.Frame) {\n\t_istore(frame, 3)\n}\n\nfunc _istore(frame *rtda.Frame, index uint) {\n\tval := frame.OperandStack().PopInt()\n\tframe.LocalVars().SetInt(index, val)\n}\n\nfunc (self *ISTORE) Execute(frame *rtda.Frame) ", "output": "{\n\t_istore(frame, uint(self.Index))\n}"} {"input": "package role\n\nimport (\n\t\"github.com/watermint/toolbox/domain/dropbox/api/dbx_auth\"\n\t\"github.com/watermint/toolbox/domain/dropbox/api/dbx_conn\"\n\t\"github.com/watermint/toolbox/domain/dropbox/model/mo_user\"\n\t\"github.com/watermint/toolbox/domain/dropbox/service/sv_adminrole\"\n\t\"github.com/watermint/toolbox/domain/dropbox/service/sv_member\"\n\t\"github.com/watermint/toolbox/infra/control/app_control\"\n\t\"github.com/watermint/toolbox/infra/recipe/rc_exec\"\n\t\"github.com/watermint/toolbox/infra/recipe/rc_recipe\"\n)\n\ntype Clear struct {\n\tPeer dbx_conn.ConnScopedTeam\n\tEmail string\n}\n\nfunc (z *Clear) Preset() {\n\tz.Peer.SetScopes(\n\t\tdbx_auth.ScopeMembersRead,\n\t\tdbx_auth.ScopeMembersWrite,\n\t)\n}\n\nfunc (z *Clear) Exec(c app_control.Control) error {\n\tmember, err := sv_member.New(z.Peer.Context()).ResolveByEmail(z.Email)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = sv_adminrole.New(z.Peer.Context()).UpdateRole(mo_user.NewUserSelectorByTeamMemberId(member.TeamMemberId), []string{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (z *Clear) Test(c app_control.Control) error ", "output": "{\n\treturn rc_exec.ExecMock(c, &Clear{}, func(r rc_recipe.Recipe) {\n\t\tm := r.(*Clear)\n\t\tm.Email = \"jo@example.com\"\n\t})\n}"} {"input": "package iso20022\n\n\ntype AcquirerProtocolParameters5 struct {\n\n\tFinancialCapture *FinancialCapture1Code `xml:\"FinCaptr\"`\n\n\tBatchTransfer *ExchangeConfiguration4 `xml:\"BtchTrf,omitempty\"`\n\n\tCompletionExchange *ExchangeConfiguration5 `xml:\"CmpltnXchg,omitempty\"`\n\n\tCancellationExchange *CancellationProcess1Code `xml:\"CxlXchg,omitempty\"`\n}\n\nfunc (a *AcquirerProtocolParameters5) SetFinancialCapture(value string) {\n\ta.FinancialCapture = (*FinancialCapture1Code)(&value)\n}\n\n\n\nfunc (a *AcquirerProtocolParameters5) AddCompletionExchange() *ExchangeConfiguration5 {\n\ta.CompletionExchange = new(ExchangeConfiguration5)\n\treturn a.CompletionExchange\n}\n\nfunc (a *AcquirerProtocolParameters5) SetCancellationExchange(value string) {\n\ta.CancellationExchange = (*CancellationProcess1Code)(&value)\n}\n\nfunc (a *AcquirerProtocolParameters5) AddBatchTransfer() *ExchangeConfiguration4 ", "output": "{\n\ta.BatchTransfer = new(ExchangeConfiguration4)\n\treturn a.BatchTransfer\n}"} {"input": "package model\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestSubmitTest(t *testing.T) {\n\ttestResp := Response{\n\t\tReqUrl: testSrv.URL + \"?k1=v1&k2=v2\",\n\t\tStatus: \"200 OK\",\n\t\tTest: \"k1=v1&k2=v2 k3=v3&k4=v4\",\n\t\tReqBody: \"k3=v3&k4=v4\",\n\t}\n\n\tresp, err := SubmitModel.Submit(testData0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tt.Logf(\"%#v\", resp)\n\tif !reflect.DeepEqual(testResp, resp) {\n\t\tt.Fatal(\"response not equal!\")\n\t}\n}\n\n\n\nfunc TestSubmitBenckmark(t *testing.T) ", "output": "{\n\ttestData1 := testData0\n\ttestData1.Bm = Bm{\n\t\tSwitch: true,\n\t\tN: 10,\n\t\tC: 1,\n\t}\n\n\tresp, err := SubmitModel.Submit(testData1)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tt.Log(resp.Bm)\n\tif resp.Bm == \"\" {\n\t\tt.Fatal(\"no benchmark data?\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/zerobotlabs/nestor-cli/Godeps/_workspace/src/github.com/jpillora/archive\"\n)\n\nconst LARGE_FILE = \"/Users/jpillora/file.mp4\"\n\nfunc main() {\n\tif _, err := os.Stat(LARGE_FILE); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\thttp.HandleFunc(\"/\", handle)\n\tlog.Fatal(http.ListenAndServe(\":3000\", nil))\n}\n\n\n\nfunc handle(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tw.Header().Set(\"Content-Type\", \"application/zip\")\n\tw.WriteHeader(200)\n\ta := archive.NewZipWriter(w)\n\tf, _ := os.Open(LARGE_FILE)\n\tlog.Println(\"sending...\")\n\tt0 := time.Now()\n\ta.AddFile(\"file.bin\", f)\n\ta.Close()\n\tlog.Printf(\"sent in %s\", time.Now().Sub(t0))\n\n}"} {"input": "package version\n\n\n\n\nfunc init() ", "output": "{\n\tbuildTags = append(buildTags, \"seccomp\")\n}"} {"input": "package circonusgometrics\n\nimport (\n\t\"sync\"\n\n\t\"github.com/circonus-labs/circonusllhist\"\n)\n\n\ntype Histogram struct {\n\tname string\n\thist *circonusllhist.Histogram\n\trw sync.RWMutex\n}\n\n\nfunc (m *CirconusMetrics) Timing(metric string, val float64) {\n\tm.SetHistogramValue(metric, val)\n}\n\n\nfunc (m *CirconusMetrics) RecordValue(metric string, val float64) {\n\tm.SetHistogramValue(metric, val)\n}\n\n\nfunc (m *CirconusMetrics) SetHistogramValue(metric string, val float64) {\n\tm.NewHistogram(metric)\n\n\tm.histograms[metric].rw.Lock()\n\tdefer m.histograms[metric].rw.Unlock()\n\n\tm.histograms[metric].hist.RecordValue(val)\n}\n\n\nfunc (m *CirconusMetrics) RemoveHistogram(metric string) {\n\tm.hm.Lock()\n\tdefer m.hm.Unlock()\n\tdelete(m.histograms, metric)\n}\n\n\n\n\n\nfunc (h *Histogram) Name() string {\n\treturn h.name\n}\n\n\nfunc (h *Histogram) RecordValue(v float64) {\n\th.rw.Lock()\n\tdefer h.rw.Unlock()\n\n\th.hist.RecordValue(v)\n}\n\nfunc (m *CirconusMetrics) NewHistogram(metric string) *Histogram ", "output": "{\n\tm.hm.Lock()\n\tdefer m.hm.Unlock()\n\n\tif hist, ok := m.histograms[metric]; ok {\n\t\treturn hist\n\t}\n\n\thist := &Histogram{\n\t\tname: metric,\n\t\thist: circonusllhist.New(),\n\t}\n\n\tm.histograms[metric] = hist\n\n\treturn hist\n}"} {"input": "package archive\n\nimport (\n\t\"archive/tar\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/docker/docker/pkg/longpath\"\n)\n\n\n\nfunc fixVolumePathPrefix(srcPath string) string {\n\treturn longpath.AddPrefix(srcPath)\n}\n\n\n\nfunc getWalkRoot(srcPath string, include string) string {\n\treturn filepath.Join(srcPath, include)\n}\n\n\n\n\nfunc CanonicalTarNameForPath(p string) (string, error) {\n\tif strings.Contains(p, \"/\") {\n\t\treturn \"\", fmt.Errorf(\"Windows path contains forward slash: %s\", p)\n\t}\n\treturn strings.Replace(p, string(os.PathSeparator), \"/\", -1), nil\n\n}\n\n\n\nfunc chmodTarEntry(perm os.FileMode) os.FileMode {\n\tperm &= 0755\n\tperm |= 0111\n\n\treturn perm\n}\n\nfunc setHeaderForSpecialDevice(hdr *tar.Header, ta *tarAppender, name string, stat interface{}) (nlink uint32, inode uint64, err error) {\n\treturn\n}\n\n\n\nfunc handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error {\n\treturn nil\n}\n\n\n\nfunc getFileUIDGID(stat interface{}) (int, int, error) {\n\treturn 0, 0, nil\n}\n\nfunc handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error ", "output": "{\n\treturn nil\n}"} {"input": "package pvm\n\nimport (\n\t\"fmt\"\n\t\"github.com/mitchellh/multistep\"\n\tparallelscommon \"github.com/mitchellh/packer/builder/parallels/common\"\n\t\"github.com/mitchellh/packer/packer\"\n)\n\n\ntype StepImport struct {\n\tName string\n\tSourcePath string\n\tvmName string\n}\n\nfunc (s *StepImport) Run(state multistep.StateBag) multistep.StepAction {\n\tdriver := state.Get(\"driver\").(parallelscommon.Driver)\n\tui := state.Get(\"ui\").(packer.Ui)\n\tconfig := state.Get(\"config\").(*Config)\n\n\tui.Say(fmt.Sprintf(\"Importing VM: %s\", s.SourcePath))\n\tif err := driver.Import(s.Name, s.SourcePath, config.OutputDir, config.ReassignMac); err != nil {\n\t\terr := fmt.Errorf(\"Error importing VM: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\ts.vmName = s.Name\n\tstate.Put(\"vmName\", s.Name)\n\treturn multistep.ActionContinue\n}\n\n\n\nfunc (s *StepImport) Cleanup(state multistep.StateBag) ", "output": "{\n\n\tif s.vmName == \"\" {\n\t\treturn\n\t}\n\n\tdriver := state.Get(\"driver\").(parallelscommon.Driver)\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\tui.Say(\"Unregistering virtual machine...\")\n\tif err := driver.Prlctl(\"unregister\", s.vmName); err != nil {\n\t\tui.Error(fmt.Sprintf(\"Error unregistering virtual machine: %s\", err))\n\t}\n}"} {"input": "package luhn\n\nimport \"testing\"\n\nvar validTests = []struct {\n\tn string\n\tok bool\n}{\n\t{\"738\", false},\n\t{\"8739567\", true},\n\t{\"1111\", false},\n\t{\"8763\", true},\n\t{\" \", false},\n\t{\"\", false},\n\t{\"2323 2005 7766 3554\", true},\n}\n\nvar addTests = []struct{ raw, luhn string }{\n\t{\"123\", \"1230\"},\n\t{\"873956\", \"8739567\"},\n\t{\"837263756\", \"8372637564\"},\n\t{\"2323 2005 7766 355\", \"2323 2005 7766 3554\"},\n}\n\nfunc TestValid(t *testing.T) {\n\tfor _, test := range validTests {\n\t\tif ok := Valid(test.n); ok != test.ok {\n\t\t\tt.Fatalf(\"Valid(%s) = %t, want %t.\", test.n, ok, test.ok)\n\t\t}\n\t}\n}\n\nfunc TestAddCheck(t *testing.T) {\n\tfor _, test := range addTests {\n\t\tif luhn := AddCheck(test.raw); luhn != test.luhn {\n\t\t\tt.Fatalf(\"AddCheck(%s) = %s, want %s.\", test.raw, luhn, test.luhn)\n\t\t}\n\t}\n}\n\nfunc BenchmarkValid(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tValid(\"2323 2005 7766 3554\")\n\t}\n}\n\n\n\nfunc BenchmarkAddCheck(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tAddCheck(\"2323 2005 7766 355\")\n\t}\n}"} {"input": "package networking\n\nimport (\n\t\"github.com/hashicorp/nomad/e2e/e2eutil\"\n\t\"github.com/hashicorp/nomad/e2e/framework\"\n)\n\n\n\nfunc init() ", "output": "{\n\tframework.AddSuites(&framework.TestSuite{\n\t\tComponent: \"Networking\",\n\t\tCanRunLocal: true,\n\t\tCases: []framework.TestCase{e2eutil.NewE2EJob(\"networking/inputs/basic.nomad\")},\n\t})\n}"} {"input": "package postgresql\n\nimport (\n\t\"encoding/binary\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strconv\"\n)\n\n\n\nfunc (p *Manager) GetSystemdID() (string, error) ", "output": "{\n\tpgControl, err := os.Open(filepath.Join(p.dataDir, \"global\", \"pg_control\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar systemID uint64\n\terr = binary.Read(pgControl, binary.LittleEndian, &systemID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strconv.FormatUint(systemID, 10), nil\n}"} {"input": "package libcontainer\n\nimport (\n \"fmt\"\n \"os\"\n \"strings\"\n\n \"github.com/syndtr/gocapability/capability\"\n)\n\nconst allCapabilityTypes = capability.CAPS | capability.BOUNDS\n\nvar capabilityMap map[string]capability.Cap\n\nfunc init() {\n capabilityMap = make(map[string]capability.Cap)\n last := capability.CAP_LAST_CAP\n \n if last == capability.Cap(63) {\n last = capability.CAP_BLOCK_SUSPEND\n }\n for _, cap := range capability.List() {\n if cap > last {\n continue\n }\n capKey := fmt.Sprintf(\"CAP_%s\", strings.ToUpper(cap.String()))\n capabilityMap[capKey] = cap\n }\n}\n\n\n\ntype whitelist struct {\n pid capability.Capabilities\n keep []capability.Cap\n}\n\n\nfunc (w *whitelist) dropBoundingSet() error {\n w.pid.Clear(capability.BOUNDS)\n w.pid.Set(capability.BOUNDS, w.keep...)\n return w.pid.Apply(capability.BOUNDS)\n}\n\n\nfunc (w *whitelist) drop() error {\n w.pid.Clear(allCapabilityTypes)\n w.pid.Set(allCapabilityTypes, w.keep...)\n return w.pid.Apply(allCapabilityTypes)\n}\n\nfunc newCapWhitelist(caps []string) (*whitelist, error) ", "output": "{\n l := []capability.Cap{}\n for _, c := range caps {\n v, ok := capabilityMap[c]\n if !ok {\n return nil, fmt.Errorf(\"unknown capability %q\", c)\n }\n l = append(l, v)\n }\n pid, err := capability.NewPid(os.Getpid())\n if err != nil {\n return nil, err\n }\n return &whitelist{\n keep: l,\n pid: pid,\n }, nil\n}"} {"input": "package v1\n\nimport (\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\n\n\nfunc SetDefaults_Job(obj *Job) {\n\tif obj.Spec.Completions == nil && obj.Spec.Parallelism == nil {\n\t\tobj.Spec.Completions = new(int32)\n\t\t*obj.Spec.Completions = 1\n\t\tobj.Spec.Parallelism = new(int32)\n\t\t*obj.Spec.Parallelism = 1\n\t}\n\tif obj.Spec.Parallelism == nil {\n\t\tobj.Spec.Parallelism = new(int32)\n\t\t*obj.Spec.Parallelism = 1\n\t}\n}\n\nfunc addDefaultingFuncs(scheme *runtime.Scheme) ", "output": "{\n\tscheme.AddDefaultingFuncs(\n\t\tSetDefaults_Job,\n\t)\n}"} {"input": "package main\n\nimport (\n\t\"../nsq\"\n\t\"../util\"\n\t\"log\"\n\t\"net\"\n)\n\ntype TcpProtocol struct {\n\tutil.TcpHandler\n\tprotocols map[int32]nsq.Protocol\n}\n\n\n\nfunc (p *TcpProtocol) Handle(clientConn net.Conn) ", "output": "{\n\tlog.Printf(\"TCP: new client(%s)\", clientConn.RemoteAddr())\n\n\tprotocolMagic, err := nsq.ReadMagic(clientConn)\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: failed to read protocol version - %s\", err.Error())\n\t\treturn\n\t}\n\n\tlog.Printf(\"CLIENT(%s): desired protocol %d\", clientConn.RemoteAddr(), protocolMagic)\n\n\tprot, ok := p.protocols[protocolMagic]\n\tif !ok {\n\t\tnsq.SendFramedResponse(clientConn, nsq.FrameTypeError, []byte(\"E_BAD_PROTOCOL\"))\n\t\tlog.Printf(\"ERROR: client(%s) bad protocol version %d\", clientConn.RemoteAddr(), protocolMagic)\n\t\treturn\n\t}\n\n\terr = prot.IOLoop(clientConn)\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: client(%s) - %s\", clientConn.RemoteAddr(), err.Error())\n\t\treturn\n\t}\n}"} {"input": "package insulin\n\nimport (\n\t\"math\"\n\n\t\"github.com/tidepool-org/platform/data\"\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tConcentrationUnitsUnitsPerML = \"Units/mL\"\n\tConcentrationValueUnitsPerMLMaximum = 10000.0\n\tConcentrationValueUnitsPerMLMinimum = 0.0\n)\n\nfunc ConcentrationUnits() []string {\n\treturn []string{\n\t\tConcentrationUnitsUnitsPerML,\n\t}\n}\n\ntype Concentration struct {\n\tUnits *string `json:\"units,omitempty\" bson:\"units,omitempty\"`\n\tValue *float64 `json:\"value,omitempty\" bson:\"value,omitempty\"`\n}\n\nfunc ParseConcentration(parser structure.ObjectParser) *Concentration {\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewConcentration()\n\tparser.Parse(datum)\n\treturn datum\n}\n\nfunc NewConcentration() *Concentration {\n\treturn &Concentration{}\n}\n\nfunc (c *Concentration) Parse(parser structure.ObjectParser) {\n\tc.Units = parser.String(\"units\")\n\tc.Value = parser.Float64(\"value\")\n}\n\n\n\nfunc (c *Concentration) Normalize(normalizer data.Normalizer) {}\n\nfunc ConcentrationValueRangeForUnits(units *string) (float64, float64) {\n\tif units != nil {\n\t\tswitch *units {\n\t\tcase ConcentrationUnitsUnitsPerML:\n\t\t\treturn ConcentrationValueUnitsPerMLMinimum, ConcentrationValueUnitsPerMLMaximum\n\t\t}\n\t}\n\treturn -math.MaxFloat64, math.MaxFloat64\n}\n\nfunc (c *Concentration) Validate(validator structure.Validator) ", "output": "{\n\tvalidator.String(\"units\", c.Units).Exists().OneOf(ConcentrationUnits()...)\n\tvalidator.Float64(\"value\", c.Value).Exists().InRange(ConcentrationValueRangeForUnits(c.Units))\n}"} {"input": "package cl\n\n\nimport \"C\"\n\n\n\nfunc CLCreateCommandQueue(context CL_context,\n\tdevice CL_device_id,\n\tproperties CL_command_queue_properties,\n\terrcode_ret *CL_int) CL_command_queue ", "output": "{\n\tvar c_errcode_ret C.cl_int\n\tvar c_command_queue C.cl_command_queue\n\n\tc_command_queue = C.clCreateCommandQueue(context.cl_context,\n\t\tdevice.cl_device_id,\n\t\tC.cl_command_queue_properties(properties),\n\t\t&c_errcode_ret)\n\n\tif errcode_ret != nil {\n\t\t*errcode_ret = CL_int(c_errcode_ret)\n\t}\n\n\treturn CL_command_queue{c_command_queue}\n}"} {"input": "package xmodule\n\nimport (\n\t\"fmt\"\n\tmsg \"github.com/Centimitr/xmessage\"\n)\n\ntype Comment struct{}\n\nfunc (m Comment) GetIndexComments(ctx *msg.Ctx) {\n\tfmt.Println(\"C\")\n}\n\nfunc init() {\n\tvar m Comment\n\tmsg.LoadModule(m)\n}\n\nfunc (m Comment) GetMessages(ctx *msg.Ctx) ", "output": "{\n\tfmt.Println(\"M\")\n}"} {"input": "package iso20022\n\n\ntype ReportStatusAndReason1 struct {\n\n\tRelatedReference *Max35Text `xml:\"RltdRef\"`\n\n\tStatus *Status2Code `xml:\"Sts\"`\n\n\tRejected []*RejectedStatusReason9Choice `xml:\"Rjctd\"`\n}\n\nfunc (r *ReportStatusAndReason1) SetRelatedReference(value string) {\n\tr.RelatedReference = (*Max35Text)(&value)\n}\n\nfunc (r *ReportStatusAndReason1) SetStatus(value string) {\n\tr.Status = (*Status2Code)(&value)\n}\n\n\n\nfunc (r *ReportStatusAndReason1) AddRejected() *RejectedStatusReason9Choice ", "output": "{\n\tnewValue := new(RejectedStatusReason9Choice)\n\tr.Rejected = append(r.Rejected, newValue)\n\treturn newValue\n}"} {"input": "package client\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\nfunc TestTemplates(t *testing.T) {\n\tname := \"foo\"\n\tversion := \"123\"\n\ttyp := \"service\"\n\tnamespace := \"default\"\n\n\ts := NewService(name, version, typ, namespace)\n\tbs := new(bytes.Buffer)\n\tif err := renderTemplate(templates[\"service\"], bs, s); err != nil {\n\t\tt.Errorf(\"Failed to render kubernetes service: %v\", err)\n\t}\n\n\td := NewDeployment(name, version, typ, namespace)\n\tbd := new(bytes.Buffer)\n\tif err := renderTemplate(templates[\"deployment\"], bd, d); err != nil {\n\t\tt.Errorf(\"Failed to render kubernetes deployment: %v\", err)\n\t}\n}\n\n\n\nfunc TestFormatName(t *testing.T) ", "output": "{\n\ttestCases := []struct {\n\t\tname string\n\t\texpect string\n\t}{\n\t\t{\"foobar\", \"foobar\"},\n\t\t{\"foo-bar\", \"foo-bar\"},\n\t\t{\"foo.bar\", \"foo-bar\"},\n\t\t{\"Foo.Bar\", \"foo-bar\"},\n\t\t{\"go.micro.foo.bar\", \"go-micro-foo-bar\"},\n\t}\n\n\tfor _, test := range testCases {\n\t\tv := Format(test.name)\n\t\tif v != test.expect {\n\t\t\tt.Fatalf(\"Expected name %s for %s got: %s\", test.expect, test.name, v)\n\t\t}\n\t}\n}"} {"input": "package docconv\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\n\t\"github.com/nuveo/GoOse\"\n)\n\n\n\n\nfunc ConvertURL(input io.Reader, readability bool) (string, map[string]string, error) ", "output": "{\n\tmeta := make(map[string]string)\n\n\tbuf := new(bytes.Buffer)\n\t_, err := buf.ReadFrom(input)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tg := goose.New()\n\tarticle, err := g.ExtractFromURL(buf.String())\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tmeta[\"title\"] = article.Title\n\tmeta[\"description\"] = article.MetaDescription\n\tmeta[\"image\"] = article.TopImage\n\n\treturn article.CleanedText, meta, nil\n}"} {"input": "package polymorphichelpers\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tapi \"k8s.io/kubernetes/pkg/apis/core\"\n\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n)\n\nfunc portsForObject(object runtime.Object) ([]string, error) {\n\tswitch t := object.(type) {\n\tcase *api.ReplicationController:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\tcase *api.Pod:\n\t\treturn getPorts(t.Spec), nil\n\tcase *api.Service:\n\t\treturn getServicePorts(t.Spec), nil\n\tcase *extensions.Deployment:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\tcase *extensions.ReplicaSet:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"cannot extract ports from %T\", object)\n\t}\n}\n\n\n\n\nfunc getServicePorts(spec api.ServiceSpec) []string {\n\tresult := []string{}\n\tfor _, servicePort := range spec.Ports {\n\t\tresult = append(result, strconv.Itoa(int(servicePort.Port)))\n\t}\n\treturn result\n}\n\nfunc getPorts(spec api.PodSpec) []string ", "output": "{\n\tresult := []string{}\n\tfor _, container := range spec.Containers {\n\t\tfor _, port := range container.Ports {\n\t\t\tresult = append(result, strconv.Itoa(int(port.ContainerPort)))\n\t\t}\n\t}\n\treturn result\n}"} {"input": "package golbStoreIpsum\n\nimport (\n\t\"github.com/cryptix/golbStore\"\n)\n\nfunc (b IpsumBlog) Latest(n int, withText bool) ([]*golbStore.Entry, error) {\n\treturn nil, nil\n}\n\nfunc (b IpsumBlog) Get(id string) (*golbStore.Entry, error) {\n\te, found := b.store[id]\n\tif !found {\n\t\treturn nil, golbStore.ErrEntryNotFound\n\t}\n\n\treturn e, nil\n}\n\nfunc (b IpsumBlog) Delete(id string) error {\n\treturn nil\n}\n\n\n\nfunc (b IpsumBlog) Save(e *golbStore.Entry) error ", "output": "{\n\tb.store[e.ID] = e\n\n\treturn nil\n}"} {"input": "package namespaces\n\nimport (\n\t\"github.com/containerd/containerd/metadata\"\n\t\"github.com/pkg/errors\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n)\n\n\n\nfunc rewriteGRPCError(err error) error {\n\tif err == nil {\n\t\treturn err\n\t}\n\n\tswitch grpc.Code(errors.Cause(err)) {\n\tcase codes.AlreadyExists:\n\t\treturn metadata.ErrExists\n\tcase codes.NotFound:\n\t\treturn metadata.ErrNotFound\n\t}\n\n\treturn err\n}\n\nfunc mapGRPCError(err error, id string) error ", "output": "{\n\tswitch {\n\tcase metadata.IsNotFound(err):\n\t\treturn grpc.Errorf(codes.NotFound, \"namespace %v not found\", id)\n\tcase metadata.IsExists(err):\n\t\treturn grpc.Errorf(codes.AlreadyExists, \"namespace %v already exists\", id)\n\tcase metadata.IsNotEmpty(err):\n\t\treturn grpc.Errorf(codes.FailedPrecondition, \"namespace %v must be empty\", id)\n\t}\n\n\treturn err\n}"} {"input": "package task_handler\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/cloudfoundry-incubator/bbs/models\"\n\t\"github.com/cloudfoundry-incubator/receptor/handlers\"\n\t\"github.com/cloudfoundry-incubator/runtime-schema/routes\"\n\t\"github.com/pivotal-golang/lager\"\n\t\"github.com/tedsuo/rata\"\n)\n\n\n\nfunc New(enqueue chan<- *models.Task, logger lager.Logger) http.Handler ", "output": "{\n\ttaskHandler := NewHandler(enqueue, logger)\n\n\tactions := rata.Handlers{\n\t\troutes.CompleteTasks: taskHandler,\n\t}\n\n\thandler, err := rata.NewRouter(routes.CompleteTasksRoutes, actions)\n\tif err != nil {\n\t\tpanic(\"unable to create router: \" + err.Error())\n\t}\n\n\thandler = handlers.LogWrap(handler, logger)\n\n\treturn handler\n}"} {"input": "package heap\n\nimport (\n\t\"sync\"\n)\n\ntype Monitor struct {\n\towner interface{} \n\townerLock sync.Locker\n\tlock sync.Locker\n\tentryCount int\n\tcond *sync.Cond\n}\n\nfunc newMonitor() *Monitor {\n\tm := &Monitor{}\n\tm.ownerLock = &sync.Mutex{}\n\tm.lock = &sync.Mutex{}\n\tm.cond = sync.NewCond(m.lock)\n\treturn m\n}\n\nfunc (monitor *Monitor) Enter(thread interface{}) {\n\tmonitor.ownerLock.Lock()\n\tif monitor.owner == thread {\n\t\tmonitor.entryCount++\n\t\tmonitor.ownerLock.Unlock()\n\t\treturn\n\t} else {\n\t\tmonitor.ownerLock.Unlock()\n\t}\n\n\tmonitor.lock.Lock()\n\n\tmonitor.ownerLock.Lock()\n\tmonitor.owner = thread\n\tmonitor.entryCount = 1\n\tmonitor.ownerLock.Unlock()\n}\n\nfunc (monitor *Monitor) Exit(thread interface{}) {\n\tmonitor.ownerLock.Lock()\n\tvar _unlock bool\n\tif monitor.owner == thread {\n\t\tmonitor.entryCount--\n\t\tif monitor.entryCount == 0 {\n\t\t\tmonitor.owner = nil\n\t\t\t_unlock = true\n\t\t}\n\t}\n\tmonitor.ownerLock.Unlock()\n\n\tif _unlock {\n\t\tmonitor.lock.Unlock()\n\t}\n}\n\n\n\nfunc (monitor *Monitor) Wait() {\n\tmonitor.ownerLock.Lock()\n\toldEntryCount := monitor.entryCount\n\toldOwner := monitor.owner\n\tmonitor.entryCount = 0\n\tmonitor.owner = nil\n\tmonitor.ownerLock.Unlock()\n\n\tmonitor.cond.Wait()\n\n\tmonitor.ownerLock.Lock()\n\tmonitor.entryCount = oldEntryCount\n\tmonitor.owner = oldOwner\n\tmonitor.ownerLock.Unlock()\n}\n\nfunc (monitor *Monitor) NotifyAll() {\n\tmonitor.cond.Broadcast()\n}\n\nfunc (monitor *Monitor) HasOwner(thread interface{}) bool ", "output": "{\n\tmonitor.ownerLock.Lock()\n\tisOwner := monitor.owner == thread\n\tmonitor.ownerLock.Unlock()\n\n\treturn isOwner\n}"} {"input": "package opensimplex\n\nimport (\n\t\"compress/gzip\"\n\t\"encoding/json\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n)\n\nfunc loadSamples() <-chan []float64 {\n\tc := make(chan []float64)\n\tgo func() {\n\t\tf, err := os.Open(path.Join(\"test_files\", \"samples.json.gz\"))\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tdefer f.Close()\n\n\t\tgz, err := gzip.NewReader(f)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\n\t\tdec := json.NewDecoder(gz)\n\t\tfor {\n\t\t\tvar sample []float64\n\t\t\tif err := dec.Decode(&sample); err == io.EOF {\n\t\t\t\tbreak\n\t\t\t} else if err != nil {\n\t\t\t\tpanic(err.Error())\n\t\t\t} else {\n\t\t\t\tc <- sample\n\t\t\t}\n\t\t}\n\t\tclose(c)\n\t}()\n\n\treturn c\n}\n\n\n\nfunc TestSamplesMatch(t *testing.T) ", "output": "{\n\tsamples := loadSamples()\n\tn := New(0)\n\n\tfor s := range samples {\n\t\tvar expected, actual float64\n\t\tswitch len(s) {\n\t\tcase 3:\n\t\t\texpected = s[2]\n\t\t\tactual = n.Eval2(s[0], s[1])\n\t\tcase 4:\n\t\t\texpected = s[3]\n\t\t\tactual = n.Eval3(s[0], s[1], s[2])\n\t\tcase 5:\n\t\t\texpected = s[4]\n\t\t\tactual = n.Eval4(s[0], s[1], s[2], s[3])\n\t\tdefault:\n\t\t\tt.Fatalf(\"Unexpected size sample: %d\", len(s))\n\t\t}\n\n\t\tif expected != actual {\n\t\t\tt.Fatalf(\"Expected %v, got %v for %dD sample at %v\",\n\t\t\t\texpected, actual, len(s)-1, s[:len(s)-1])\n\t\t}\n\t}\n}"} {"input": "package tparse_test\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/shivam07a/tparse\"\n)\n\nfunc ExampleDict_UnMarshal() {\n\ttomlStr := `[Linus Torvalds]\n Found = Linux, git\n\n [Guido Van Rossum]\n Found = Python, Gerrit\n\n [Larry Wall]\n Found = Perl`\n\tvar dict *tparse.Dict = tparse.NewDict()\n\terr := dict.Parse(tomlStr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tif err := d.UnMarshal(os.Stdout); err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}\n\nfunc ExampleDict_Parse() {\n\ttomlStr := `[Linus Torvalds]\n Found = Linux, git\n\n [Guido Van Rossum]\n Found = Python, Gerrit\n\n [Larry Wall]\n Found = Perl`\n\tvar dict *tparse.Dict = tparse.NewDict()\n\terr := dict.Parse(tomlStr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n\nfunc ExampleDict_Find() {\n\ttomlStr := `[Linus Torvalds]\n Found = Linux, git\n\n [Guido Van Rossum]\n Found = Python, Gerrit\n\n [Larry Wall]\n Found = Perl`\n\tvar dict *tparse.Dict = tparse.NewDict()\n\terr := dict.Parse(tomlStr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\te, err := dict.Find(\"Linus Torvalds\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tfmt.Println(e)\n}\n\n\n\nfunc ExampleEntries_Find() ", "output": "{\n\ttomlStr := `[Linus Torvalds]\n Found = Linux, git\n\n [Guido Van Rossum]\n Found = Python, Gerrit\n\n [Larry Wall]\n Found = Perl`\n\tvar dict *tparse.Dict = tparse.NewDict()\n\terr := dict.Parse(tomlStr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\te, err := dict.Find(\"Linus Torvalds\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tfound, err := e.Find(\"Found\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tfmt.Println(found)\n\n}"} {"input": "package command\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"google.golang.org/grpc\"\n\n\t\"github.com/itslab-kyushu/simple-kvs/kvs\"\n\t\"github.com/itslab-kyushu/sss/cfg\"\n\t\"github.com/urfave/cli\"\n)\n\ntype getOpt struct {\n\tConfig *cfg.Config\n\tName string\n\tOutputFile string\n\tLog io.Writer\n}\n\n\n\n\nfunc cmdGet(opt *getOpt) (err error) {\n\n\tif opt.Config.NServers() == 0 {\n\t\treturn fmt.Errorf(\"No server information is given.\")\n\t}\n\n\tfmt.Fprintln(opt.Log, \"Downloading a file\")\n\tserver := opt.Config.Servers[0]\n\n\tconn, err := grpc.Dial(\n\t\tfmt.Sprintf(\"%s:%d\", server.Address, server.Port),\n\t\tgrpc.WithInsecure(),\n\t\tgrpc.WithCompressor(grpc.NewGZIPCompressor()),\n\t\tgrpc.WithDecompressor(grpc.NewGZIPDecompressor()),\n\t)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tclient := kvs.NewKvsClient(conn)\n\tvalue, err := client.Get(context.Background(), &kvs.Key{\n\t\tName: opt.Name,\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ioutil.WriteFile(opt.OutputFile, value.Value, 0644)\n\n}\n\nfunc CmdGet(c *cli.Context) (err error) ", "output": "{\n\n\tif c.NArg() != 1 {\n\t\treturn cli.ShowSubcommandHelp(c)\n\t}\n\n\tconf, err := cfg.ReadConfig(c.String(\"config\"))\n\tif err != nil {\n\t\treturn\n\t}\n\n\toutput := c.String(\"output\")\n\tif output == \"\" {\n\t\toutput = c.Args().First()\n\t}\n\n\tvar log io.Writer\n\tif c.GlobalBool(\"quiet\") {\n\t\tlog = ioutil.Discard\n\t} else {\n\t\tlog = os.Stderr\n\t}\n\n\treturn cmdGet(&getOpt{\n\t\tConfig: conf,\n\t\tName: c.Args().First(),\n\t\tOutputFile: output,\n\t\tLog: log,\n\t})\n\n}"} {"input": "package utils\n\nimport (\n\t\"net\"\n\t\"fmt\"\n\t\"strings\"\n\t\"errors\"\n)\n\ntype Local int\n\n\n\nfunc (this *Local) GetIps() []string {\n\tresult := []string{}\n\tinterfaces,err := net.Interfaces()\n\tCheckError(err)\n\tfor _,inter :=range interfaces {\n\t\tip,err := inter.Addrs()\n\t\tCheckError(err)\n\t\tfor _,x := range ip {\n\t\t\tresult = append(result,x.String())\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (this *Local) GiveOneIp() (string,error) {\n\trs := this.GetIps()\n\tfor _,data := range rs {\n\t\tif strings.Contains(data,\"24\") {\n\t\t\treturn strings.Split(data,\"/\")[0],nil\n\t\t}\n\t}\n\treturn \"\",errors.New(\"没有255.255.255.0网段的IP设置\")\n}\n\nfunc (this *Local) GetMac() ", "output": "{\n\tinterfaces,err := net.Interfaces()\n\tCheckError(err)\n\tfor _,inter :=range interfaces {\n\t\tmac := inter.HardwareAddr\n\t\tname := inter.Name\n\t\tfmt.Printf(\"MAC=%s NAME=%s \\n\",mac,name)\n\t}\n}"} {"input": "package application\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/garyburd/redigo/redis\"\n)\n\ntype RedisDataStore struct {\n\tHost string\n\tPassword string\n\tpool *redis.Pool\n}\n\n\n\nfunc (s *RedisDataStore) Initialize() error {\n\terr := s.checkConnection()\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.pool = &redis.Pool{\n\t\tMaxIdle: 5,\n\t\tMaxActive: 5,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.Dial(\"tcp\", s.Host)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t_, err = c.Do(\"AUTH\", s.Password)\n\t\t\tif err != nil {\n\t\t\t\tc.Close()\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, nil\n\t\t},\n\t}\n\treturn nil\n}\n\nfunc (s *RedisDataStore) Get(key string) ([]byte, error) {\n\tc := s.pool.Get()\n\tdefer c.Close()\n\n\tval, err := c.Do(\"GET\", key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbytes, ok := val.([]byte)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unable to type-assert response of type %T to []byte\", val)\n\t}\n\treturn bytes, nil\n}\n\nfunc (s *RedisDataStore) Set(key string, val []byte) error {\n\tc := s.pool.Get()\n\tdefer c.Close()\n\n\t_, err := c.Do(\"SET\", key, val)\n\treturn err\n}\n\nfunc (s *RedisDataStore) checkConnection() error ", "output": "{\n\tc, err := redis.Dial(\"tcp\", s.Host)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = c.Do(\"AUTH\", s.Password)\n\tif err != nil {\n\t\tc.Close()\n\t\treturn err\n\t}\n\tc.Close()\n\treturn nil\n}"} {"input": "package sw\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\n\t\"github.com/hyperledger/fabric/core/crypto/bccsp\"\n\t\"github.com/hyperledger/fabric/core/crypto/primitives\"\n)\n\ntype rsaPrivateKey struct {\n\tk *rsa.PrivateKey\n}\n\n\n\nfunc (k *rsaPrivateKey) Bytes() (raw []byte, err error) {\n\treturn\n}\n\n\nfunc (k *rsaPrivateKey) SKI() (ski []byte) {\n\traw := x509.MarshalPKCS1PrivateKey(k.k)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\nfunc (k *rsaPrivateKey) Symmetric() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPrivateKey) Private() bool {\n\treturn true\n}\n\n\n\nfunc (k *rsaPrivateKey) PublicKey() (bccsp.Key, error) {\n\treturn &rsaPublicKey{&k.k.PublicKey}, nil\n}\n\ntype rsaPublicKey struct {\n\tk *rsa.PublicKey\n}\n\n\n\n\n\n\nfunc (k *rsaPublicKey) SKI() (ski []byte) {\n\traw, _ := primitives.PublicKeyToPEM(k.k, nil)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\nfunc (k *rsaPublicKey) Symmetric() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) Private() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) PublicKey() (bccsp.Key, error) {\n\treturn k, nil\n}\n\nfunc (k *rsaPublicKey) Bytes() (raw []byte, err error) ", "output": "{\n\traw, err = x509.MarshalPKIXPublicKey(k.k)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed marshalling key [%s]\", err)\n\t}\n\treturn\n}"} {"input": "package tracepkts\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n)\n\nconst (\n\tATOM_N = 0\n\tATOM_E = 1\n)\n\ntype AtomFmt1ETMv4 struct {\n\t*GenericTracePacketv4\n\ttaken bool\n}\n\nfunc DecodeAtomFmt1(header byte, reader *bufio.Reader) TracePacket {\n\tpkt := AtomFmt1ETMv4{}\n\n\tif header&0x1 == ATOM_N {\n\t\tpkt.taken = false\n\t} else {\n\t\tpkt.taken = true\n\t}\n\n\treturn pkt\n}\n\n\n\nfunc (pkt AtomFmt1ETMv4) String() string ", "output": "{\n\ttaken := \"Taken\"\n\tif pkt.taken == false {\n\t\ttaken = \"Not Taken\"\n\t}\n\treturn fmt.Sprintf(\"Atom Format 1 Branch %s\", taken)\n}"} {"input": "package cobra\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\nfunc TestCompleteNoDesCmdInFishScript(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse: \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun: emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, false))\n\toutput := buf.String()\n\n\tcheck(t, output, ShellCompNoDescRequestCmd)\n}\n\nfunc TestCompleteCmdInFishScript(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse: \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun: emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, true))\n\toutput := buf.String()\n\n\tcheck(t, output, ShellCompRequestCmd)\n\tcheckOmit(t, output, ShellCompNoDescRequestCmd)\n}\n\n\n\nfunc TestProgWithColon(t *testing.T) {\n\trootCmd := &Command{Use: \"root:colon\", Args: NoArgs, Run: emptyRun}\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, false))\n\toutput := buf.String()\n\n\tcheck(t, output, \"__root_colon_perform_completion\")\n\tcheckOmit(t, output, \"__root:colon_perform_completion\")\n\n\tcheck(t, output, \"-c root:colon\")\n\tcheckOmit(t, output, \"-c root_colon\")\n}\n\nfunc TestProgWithDash(t *testing.T) ", "output": "{\n\trootCmd := &Command{Use: \"root-dash\", Args: NoArgs, Run: emptyRun}\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, false))\n\toutput := buf.String()\n\n\tcheck(t, output, \"__root_dash_perform_completion\")\n\tcheckOmit(t, output, \"__root-dash_perform_completion\")\n\n\tcheck(t, output, \"-c root-dash\")\n\tcheckOmit(t, output, \"-c root_dash\")\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSECSTaskDefinition_DockerVolumeConfiguration struct {\n\n\tAutoprovision bool `json:\"Autoprovision,omitempty\"`\n\n\tDriver string `json:\"Driver,omitempty\"`\n\n\tDriverOpts map[string]string `json:\"DriverOpts,omitempty\"`\n\n\tLabels map[string]string `json:\"Labels,omitempty\"`\n\n\tScope string `json:\"Scope,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) AWSCloudFormationType() string {\n\treturn \"AWS::ECS::TaskDefinition.DockerVolumeConfiguration\"\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\n\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetMetadata(metadata map[string]interface{}) ", "output": "{\n\tr._metadata = metadata\n}"} {"input": "package logs\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\ntype connWriter struct {\n\tlg *logWriter\n\tinnerWriter io.WriteCloser\n\tReconnectOnMsg bool `json:\"reconnectOnMsg\"`\n\tReconnect bool `json:\"reconnect\"`\n\tNet string `json:\"net\"`\n\tAddr string `json:\"addr\"`\n\tLevel int `json:\"level\"`\n}\n\n\nfunc NewConn() Logger {\n\tconn := new(connWriter)\n\tconn.Level = LevelTrace\n\treturn conn\n}\n\n\n\nfunc (c *connWriter) Init(jsonConfig string) error {\n\treturn json.Unmarshal([]byte(jsonConfig), c)\n}\n\n\n\nfunc (c *connWriter) WriteMsg(when time.Time, msg string, level int) error {\n\tif level > c.Level {\n\t\treturn nil\n\t}\n\tif c.needToConnectOnMsg() {\n\t\terr := c.connect()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif c.ReconnectOnMsg {\n\t\tdefer c.innerWriter.Close()\n\t}\n\n\tc.lg.println(when, msg)\n\treturn nil\n}\n\n\nfunc (c *connWriter) Flush() {\n\n}\n\n\nfunc (c *connWriter) Destroy() {\n\tif c.innerWriter != nil {\n\t\tc.innerWriter.Close()\n\t}\n}\n\n\n\nfunc (c *connWriter) needToConnectOnMsg() bool {\n\tif c.Reconnect {\n\t\tc.Reconnect = false\n\t\treturn true\n\t}\n\n\tif c.innerWriter == nil {\n\t\treturn true\n\t}\n\n\treturn c.ReconnectOnMsg\n}\n\nfunc init() {\n\tRegister(AdapterConn, NewConn)\n}\n\nfunc (c *connWriter) connect() error ", "output": "{\n\tif c.innerWriter != nil {\n\t\tc.innerWriter.Close()\n\t\tc.innerWriter = nil\n\t}\n\n\tconn, err := net.Dial(c.Net, c.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif tcpConn, ok := conn.(*net.TCPConn); ok {\n\t\ttcpConn.SetKeepAlive(true)\n\t}\n\n\tc.innerWriter = conn\n\tc.lg = newLogWriter(conn)\n\treturn nil\n}"} {"input": "package packer\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"golang.org/x/sync/errgroup\"\n)\n\n\n\nfunc TestProgressTracking_open_close(t *testing.T) {\n\tvar bar *uiProgressBar\n\n\ttracker := bar.TrackProgress(\"1,\", 1, 42, ioutil.NopCloser(nil))\n\ttracker.Close()\n\n\ttracker = bar.TrackProgress(\"2,\", 1, 42, ioutil.NopCloser(nil))\n\ttracker.Close()\n}\n\nfunc TestProgressTracking_multi_open_close(t *testing.T) {\n\tvar bar *uiProgressBar\n\tg := errgroup.Group{}\n\n\tfor i := 0; i < 100; i++ {\n\t\tg.Go(func() error {\n\t\t\ttracker := bar.TrackProgress(\"file,\", 1, 42, ioutil.NopCloser(nil))\n\t\t\treturn tracker.Close()\n\t\t})\n\t}\n\tif err := g.Wait(); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\n\nfunc TestProgressTracking_races(t *testing.T) ", "output": "{\n\tvar bar *uiProgressBar\n\tg := errgroup.Group{}\n\n\tfor i := 0; i < 100; i++ {\n\t\tg.Go(func() error {\n\t\t\ttxt := []byte(\"foobarbaz dolores\")\n\t\t\tb := bytes.NewReader(txt)\n\t\t\ttracker := bar.TrackProgress(\"file,\", 1, 42, ioutil.NopCloser(b))\n\n\t\t\tfor i := 0; i < 42; i++ {\n\t\t\t\ttracker.Read([]byte(\"i\"))\n\t\t\t}\n\t\t\treturn tracker.Close()\n\t\t})\n\t}\n\n\tif err := g.Wait(); err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package config\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\n\t\"github.com/hauke96/sigolo\"\n)\n\n\n\n\n\n\ntype ConfigLoader struct {\n\ttopicConfig *TopicConfig\n\tserverConfig *ServerConfig\n}\n\n\n\n\n\n\n\nfunc (cl *ConfigLoader) LoadConfig(filename string) {\n\tdata, err := ioutil.ReadFile(filename)\n\n\tif err != nil {\n\t\tsigolo.Error(\"Error reading \" + filename)\n\t\tsigolo.Error(\"\\n\\nAhhh, *urg*, I'm sorry but there was a really bad error inside of me. Above the stack trace is a message marked with [FATAL], you'll find some information there.\\nIf not, feel free to contact my maker via:\\n\\n goms@hauke-stieler.de\\n\\nI hope my death .. . eh ... crash is only an exception and will be fixed soon ... my power ... leaves me ... good bye ... x.x\")\n\t\tsigolo.Fatal(err.Error())\n\t}\n\n\tcl.serverConfig = &ServerConfig{}\n\tjson.Unmarshal(data, cl.serverConfig)\n\n\tcl.loadTopics(cl.serverConfig.TopicLocation)\n}\n\n\nfunc (cl *ConfigLoader) GetConfig() Config {\n\treturn Config{\n\t\tTopicConfig: *cl.topicConfig,\n\t\tServerConfig: *cl.serverConfig,\n\t}\n}\n\nfunc (cl *ConfigLoader) loadTopics(filename string) ", "output": "{\n\tdata, err := ioutil.ReadFile(filename)\n\n\tif err != nil {\n\t\tsigolo.Error(\"Error reading \" + filename)\n\t\tsigolo.Error(\"\\n\\nAhhh, *urg*, I'm sorry but there was a really bad error inside of me. Above the stack trace is a message marked with [FATAL], you'll find some information there.\\nIf not, feel free to contact my maker via:\\n\\n goms@hauke-stieler.de\\n\\nI hope my death .. . eh ... crash is only an exception and will be fixed soon ... my power ... leaves me ... good bye ... x.x\")\n\t\tsigolo.Error(err.Error())\n\t}\n\n\tcl.topicConfig = &TopicConfig{}\n\tjson.Unmarshal(data, cl.topicConfig)\n}"} {"input": "package gce\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"google.golang.org/cloud/compute/metadata\"\n)\n\ntype AuthToken struct {\n\tAccessToken string `json:\"access_token\"`\n\n\tExpiresIn int `json:\"expires_in\"`\n\n\tTokenType string `json:\"token_type\"`\n}\n\n\nfunc VerifyAuthScope(expectedScope string) error {\n\tscopes, err := metadata.Get(\"instance/service-accounts/default/scopes\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, scope := range strings.Fields(scopes) {\n\t\tif scope == expectedScope {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"Current instance does not have the expected scope (%q). Actual scopes: %v\", expectedScope, scopes)\n}\n\n\n\n\nfunc GetAuthToken() (AuthToken, error) ", "output": "{\n\trawToken, err := metadata.Get(\"instance/service-accounts/default/token\")\n\tif err != nil {\n\t\treturn AuthToken{}, err\n\t}\n\n\tvar token AuthToken\n\terr = json.Unmarshal([]byte(rawToken), &token)\n\tif err != nil {\n\t\treturn AuthToken{}, fmt.Errorf(\"failed to unmarshal service account token with output %q: %v\", rawToken, err)\n\t}\n\n\treturn token, err\n}"} {"input": "package gospell\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\ntype Match struct {\n\tWord []rune\n\tDistance int\n\tWeight int\n}\n\ntype Matches []Match\n\nfunc (m1 Match) Equal(m2 Match) bool {\n\treturn string(m1.Word) == string(m2.Word) &&\n\t\tm1.Distance == m2.Distance && m1.Weight == m2.Weight\n}\n\nfunc (m Match) String() string {\n\treturn fmt.Sprintf(\"{%v %d %d}\", string(m.Word), m.Distance, m.Weight)\n}\n\n\nfunc (s Matches) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\n\nfunc (s Matches) Strings() []string {\n\tstrings := make([]string, len(s))\n\tsort.Sort(ByDistance{s})\n\tfor i, r := range s {\n\t\tstrings[i] = string(r.Word)\n\t}\n\n\treturn strings\n}\n\ntype ByDistance struct {\n\tMatches\n}\n\nfunc (s ByDistance) Less(i, j int) bool {\n\td1 := s.Matches[i].Distance\n\td2 := s.Matches[j].Distance\n\tif d1 == d2 {\n\t\treturn string(s.Matches[i].Word) < string(s.Matches[j].Word)\n\t}\n\treturn d1 < d2\n}\n\nfunc (m *Match) update(r rune, distance, weight int) Match {\n\tm2 := Match{}\n\tif r != 0 {\n\t\tm2.Word = []rune{r}\n\t\tm2.Word = append(m2.Word, m.Word...)\n\t} else {\n\t\tm2.Word = m.Word[:]\n\t}\n\tm2.Distance = m.Distance + distance\n\tm2.Weight = m.Weight + weight\n\treturn m2\n}\n\nfunc (s Matches) Len() int ", "output": "{ return len(s) }"} {"input": "package main\n\ntype OffState struct {\n\tstatusLed Output\n}\n\nfunc NewOffState(statusLed Output) State {\n\ts := OffState{statusLed: statusLed}\n\treturn &s\n}\n\nfunc (s *OffState) Enter(m StateMachine) {\n\ts.statusLed.Low()\n}\n\nfunc (s *OffState) Event(m StateMachine, pin uint, value uint) {\n\tif pin == GPIO_SWITCH_PIN && value == GPIO_SWITCH_ON {\n\t\tm.Transit(STATE_WAITING)\n\t}\n}\n\nfunc (s *OffState) Leave(m StateMachine) {}\n\n\n\nfunc (s *OffState) String() string ", "output": "{\n\treturn \"Off\"\n}"} {"input": "package Filter\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/reactivego/scheduler\"\n\t\"github.com/reactivego/subscriber\"\n)\n\n\n\n\ntype Scheduler = scheduler.Scheduler\n\n\n\n\n\n\ntype Subscriber = subscriber.Subscriber\n\n\n\n\n\n\n\n\n\ntype IntObserver func(next int, err error, done bool)\n\n\n\n\n\ntype ObservableInt func(IntObserver, Scheduler, Subscriber)\n\n\n\n\nfunc FromInt(slice ...int) ObservableInt {\n\tobservable := func(observe IntObserver, scheduler Scheduler, subscriber Subscriber) {\n\t\ti := 0\n\t\trunner := scheduler.ScheduleRecursive(func(self func()) {\n\t\t\tif subscriber.Subscribed() {\n\t\t\t\tif i < len(slice) {\n\t\t\t\t\tobserve(slice[i], nil, false)\n\t\t\t\t\tif subscriber.Subscribed() {\n\t\t\t\t\t\ti++\n\t\t\t\t\t\tself()\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tvar zero int\n\t\t\t\t\tobserve(zero, nil, true)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\tsubscriber.OnUnsubscribe(runner.Cancel)\n\t}\n\treturn observable\n}\n\n\n\n\nfunc (o ObservableInt) Filter(predicate func(next int) bool) ObservableInt {\n\tobservable := func(observe IntObserver, subscribeOn Scheduler, subscriber Subscriber) {\n\t\tobserver := func(next int, err error, done bool) {\n\t\t\tif done || predicate(next) {\n\t\t\t\tobserve(next, err, done)\n\t\t\t}\n\t\t}\n\t\to(observer, subscribeOn, subscriber)\n\t}\n\treturn observable\n}\n\n\n\n\n\n\n\n\n\nfunc (o ObservableInt) Println(a ...interface{}) error ", "output": "{\n\tsubscriber := subscriber.New()\n\tscheduler := scheduler.MakeTrampoline()\n\tobserver := func(next int, err error, done bool) {\n\t\tif !done {\n\t\t\tfmt.Println(append(a, next)...)\n\t\t} else {\n\t\t\tsubscriber.Done(err)\n\t\t}\n\t}\n\tsubscriber.OnWait(scheduler.Wait)\n\to(observer, scheduler, subscriber)\n\treturn subscriber.Wait()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst version = 74\n\nvar cmdVersion = &Command{\n\tName: \"version\",\n\tShort: \"show version info\",\n\tLong: `\n\nDisplays the version of godep as well as the target OS, architecture and go runtime version.\n`,\n\tRun: runVersion,\n}\n\nfunc versionString() string {\n\treturn fmt.Sprintf(\"godep v%d (%s/%s/%s)\", version, runtime.GOOS, runtime.GOARCH, runtime.Version())\n}\n\nfunc runVersion(cmd *Command, args []string) {\n\tfmt.Printf(\"%s\\n\", versionString())\n}\n\n\n\n\n\n\nfunc isSameOrNewer(base, check string) bool {\n\tif base == check {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(check, \"devel-\") {\n\t\treturn true\n\t}\n\tbp := strings.FieldsFunc(base, GoVersionFields)\n\tcp := strings.FieldsFunc(check, GoVersionFields)\n\tif len(bp) < 2 || len(cp) < 2 {\n\t\tlog.Fatalf(\"Error comparing %s to %s\\n\", base, check)\n\t}\n\tif bp[0] == cp[0] { \n\t\tbm, err := strconv.Atoi(bp[1])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tcm, err := strconv.Atoi(cp[1])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn cm >= bm\n\t}\n\treturn false\n}\n\nfunc GoVersionFields(c rune) bool ", "output": "{\n\treturn c == 'g' || c == 'o' || c == '.'\n}"} {"input": "package ipwrapper\n\nimport (\n\t\"net\"\n\n\t\"github.com/containernetworking/cni/pkg/ip\"\n\t\"github.com/vishvananda/netlink\"\n)\n\ntype IP interface {\n\tAddDefaultRoute(gw net.IP, dev netlink.Link) error\n}\n\ntype ipRoute struct {\n}\n\nfunc NewIP() IP {\n\treturn &ipRoute{}\n}\n\n\n\nfunc (*ipRoute) AddDefaultRoute(gw net.IP, dev netlink.Link) error ", "output": "{\n\treturn ip.AddDefaultRoute(gw, dev)\n}"} {"input": "package vitess\n\nimport (\n\t\"encoding/binary\"\n\t\"encoding/hex\"\n\t\"math\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestVitessHash(t *testing.T) {\n\tt.Parallel()\n\n\thashed, err := HashUint64(30375298039)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"031265661E5F1133\", toHex(hashed))\n\n\thashed, err = HashUint64(1123)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"031B565D41BDF8CA\", toHex(hashed))\n\n\thashed, err = HashUint64(30573721600)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"1EFD6439F2050FFD\", toHex(hashed))\n\n\thashed, err = HashUint64(116)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"1E1788FF0FDE093C\", toHex(hashed))\n\n\thashed, err = HashUint64(math.MaxUint64)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"355550B2150E2451\", toHex(hashed))\n}\n\n\n\nfunc toHex(value uint64) string ", "output": "{\n\tvar keybytes [8]byte\n\tbinary.BigEndian.PutUint64(keybytes[:], value)\n\treturn strings.ToUpper(hex.EncodeToString(keybytes[:]))\n}"} {"input": "package shutdown\n\nimport (\n\t\"log\"\n\t\"os/exec\"\n\t\"strconv\"\n)\n\nfunc abort() {\n\trun(\"/a\")\n}\n\nfunc start(sec int) {\n\trun(\"/s\", \"/t\", strconv.Itoa(sec))\n}\n\n\n\n\nfunc run(args ...string) ", "output": "{\n\tcmd := exec.Command(\"shutdown\", args...)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Println(\"error: \" + err.Error())\n\t}\n}"} {"input": "package routing\n\nimport \"net/http\"\n\n\nfunc Method(method string, handler http.Handler) Matcher {\n\treturn func(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\t\tif req.Method == method {\n\t\t\thandler.ServeHTTP(resp, req)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}\n\n\nfunc GET(handler http.Handler) Matcher {\n\treturn Method(\"GET\", handler)\n}\n\n\nfunc GETFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn GET(http.HandlerFunc(handler))\n}\n\n\nfunc POST(handler http.Handler) Matcher {\n\treturn Method(\"POST\", handler)\n}\n\n\nfunc POSTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn POST(http.HandlerFunc(handler))\n}\n\n\n\n\n\nfunc PUTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PUT(http.HandlerFunc(handler))\n}\n\n\nfunc PATCH(handler http.Handler) Matcher {\n\treturn Method(\"PATCH\", handler)\n}\n\n\nfunc PATCHFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PATCH(http.HandlerFunc(handler))\n}\n\n\nfunc DELETE(handler http.Handler) Matcher {\n\treturn Method(\"DELETE\", handler)\n}\n\n\nfunc DELETEFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn DELETE(http.HandlerFunc(handler))\n}\n\n\n\nfunc MethodNotAllowed(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\tresp.WriteHeader(405)\n\treturn true\n}\n\nfunc PUT(handler http.Handler) Matcher ", "output": "{\n\treturn Method(\"PUT\", handler)\n}"} {"input": "package sqltrace\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\nfunc boolToInt64(f bool) int64 {\n\tif f {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\ntype sqlTrace struct {\n\ton int64 \n\n\t*log.Logger\n}\n\nfunc newSQLTrace() *sqlTrace {\n\treturn &sqlTrace{\n\t\tLogger: log.New(os.Stdout, \"hdb \", log.Ldate|log.Ltime|log.Lshortfile),\n\t}\n}\nfunc (t *sqlTrace) On() bool { return atomic.LoadInt64(&t.on) != 0 }\nfunc (t *sqlTrace) SetOn(on bool) { atomic.StoreInt64(&t.on, boolToInt64(on)) }\n\ntype flagValue struct {\n\tt *sqlTrace\n}\n\nfunc (v flagValue) IsBoolFlag() bool { return true }\n\nfunc (v flagValue) String() string {\n\tif v.t == nil {\n\t\treturn \"\"\n\t}\n\treturn strconv.FormatBool(v.t.On())\n}\n\nfunc (v flagValue) Set(s string) error {\n\tf, err := strconv.ParseBool(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.t.SetOn(f)\n\treturn nil\n}\n\nvar tracer = newSQLTrace()\n\nfunc init() {\n\tflag.Var(&flagValue{t: tracer}, \"hdb.sqlTrace\", \"enabling hdb sql trace\")\n}\n\n\nfunc On() bool { return tracer.On() }\n\n\n\n\n\nfunc Trace(v ...interface{}) { tracer.Print(v...) }\n\n\nfunc Tracef(format string, v ...interface{}) { tracer.Printf(format, v...) }\n\n\nfunc Traceln(v ...interface{}) { tracer.Println(v...) }\n\nfunc SetOn(on bool) ", "output": "{ tracer.SetOn(on) }"} {"input": "package models\n\nimport (\n\t\"fmt\"\n\n\t\"google.golang.org/protobuf/reflect/protoreflect\"\n\t\"google.golang.org/protobuf/types/known/fieldmaskpb\"\n)\n\n\n\n\n\n\n\nfunc ExpandMask(m protoreflect.ProtoMessage, mask *fieldmaskpb.FieldMask) *fieldmaskpb.FieldMask {\n\tif mask == nil || len(mask.GetPaths()) == 0 {\n\t\treturn populatedFields(m)\n\t} else if len(mask.GetPaths()) == 1 && mask.Paths[0] == \"*\" {\n\t\treturn allFields(m)\n\t}\n\n\tmask.Normalize()\n\treturn mask\n}\n\nfunc populatedFields(m protoreflect.ProtoMessage) *fieldmaskpb.FieldMask {\n\tmask, _ := fieldmaskpb.New(m)\n\n\tm.ProtoReflect().Range(func(field protoreflect.FieldDescriptor, _ protoreflect.Value) bool {\n\t\t_ = mask.Append(m, string(field.Name()))\n\t\treturn true \n\t})\n\n\treturn mask\n}\n\nfunc allFields(m protoreflect.ProtoMessage) *fieldmaskpb.FieldMask {\n\tmask, _ := fieldmaskpb.New(m)\n\n\tfields := m.ProtoReflect().Descriptor().Fields()\n\tfor i := 0; i < fields.Len(); i++ {\n\t\t_ = mask.Append(m, string(fields.Get(i).Name()))\n\t}\n\n\treturn mask\n}\n\nfunc ValidateMask(message protoreflect.ProtoMessage, mask *fieldmaskpb.FieldMask) error ", "output": "{\n\tif mask == nil {\n\t\treturn nil\n\t}\n\n\tif len(mask.GetPaths()) == 1 && mask.Paths[0] == \"*\" {\n\t\treturn nil\n\t}\n\n\tunknowns := make([]string, 0)\n\tfor _, field := range mask.GetPaths() {\n\t\tif _, err := fieldmaskpb.New(message, field); err != nil {\n\t\t\tunknowns = append(unknowns, field)\n\t\t}\n\t}\n\n\tif len(unknowns) > 0 {\n\t\treturn fmt.Errorf(\"unrecognized fields %v\", unknowns)\n\t}\n\n\treturn nil\n}"} {"input": "package utils\n\nimport (\n\t\"sync\"\n)\n\ntype BeeMap struct {\n\tlock *sync.RWMutex\n\tbm map[interface{}]interface{}\n}\n\n\nfunc NewBeeMap() *BeeMap {\n\treturn &BeeMap{\n\t\tlock: new(sync.RWMutex),\n\t\tbm: make(map[interface{}]interface{}),\n\t}\n}\n\n\nfunc (m *BeeMap) Get(k interface{}) interface{} {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\tif val, ok := m.bm[k]; ok {\n\t\treturn val\n\t}\n\treturn nil\n}\n\n\n\nfunc (m *BeeMap) Set(k interface{}, v interface{}) bool {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tif val, ok := m.bm[k]; !ok {\n\t\tm.bm[k] = v\n\t} else if val != v {\n\t\tm.bm[k] = v\n\t} else {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\nfunc (m *BeeMap) Check(k interface{}) bool {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\tif _, ok := m.bm[k]; !ok {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc (m *BeeMap) Items() map[interface{}]interface{} {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\treturn m.bm\n}\n\nfunc (m *BeeMap) Delete(k interface{}) ", "output": "{\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tdelete(m.bm, k)\n}"} {"input": "package server\n\nimport (\n\t\"strings\"\n\n\tot \"github.com/opentracing/opentracing-go\"\n\tzipkinot \"github.com/openzipkin-contrib/zipkin-go-opentracing\"\n\tzipkin \"github.com/openzipkin/zipkin-go\"\n\tzipkinhttp \"github.com/openzipkin/zipkin-go/reporter/http\"\n)\n\nfunc initTracing(tracingType, tracingEP string) (ot.Tracer, error) {\n\tif tracingEP == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tswitch strings.ToLower(tracingType) {\n\tdefault:\n\t\treturn nil, newTracingTypeError(tracingType)\n\n\tcase \"zipkin\":\n\t\treturn setupZipkin(tracingEP)\n\t}\n}\n\n\n\nfunc setupZipkin(tracingEP string) (ot.Tracer, error) ", "output": "{\n\treporter := zipkinhttp.NewReporter(tracingEP)\n\trecorder, err := zipkin.NewEndpoint(\"PDP\", \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttracer, err := zipkin.NewTracer(\n\t\treporter,\n\t\tzipkin.WithLocalEndpoint(recorder),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn zipkinot.Wrap(tracer), nil\n}"} {"input": "package tweetharvest\n\nimport (\n\t\"time\"\n\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/appengine/datastore\"\n\t\"google.golang.org/appengine/log\"\n)\n\nconst tweetKey string = \"Tweets\"\nconst tweetKeyID string = \"default_tweetstore\"\n\n\n\nfunc GetAllNewTweets(since time.Time, c context.Context) LinkTweets {\n\tlog.Infof(c, \"Getting all tweets newer than: %v\", since)\n\tq := datastore.NewQuery(linkTweetKind).Ancestor(getTweetKey(c)).Filter(\"CreatedTime >\", since)\n\tout := make(LinkTweets, 0, 15)\n\tq.GetAll(c, &out)\n\treturn out\n}\n\n\n\n\nfunc getTweetKey(c context.Context) *datastore.Key {\n\treturn datastore.NewKey(c, tweetKey, tweetKeyID, 0, nil)\n}\n\n\nfunc LinkTweetFromDatastore(tweetID int64, c context.Context) *LinkTweet {\n\tq := datastore.NewQuery(linkTweetKind).\n\t\tFilter(\"TweetID =\", tweetID).\n\t\tLimit(1)\n\n\titerator := q.Run(c)\n\tlinkTweet := &LinkTweet{}\n\t_, err := iterator.Next(linkTweet)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn linkTweet\n}\n\nfunc getNewestTweet(c context.Context) time.Time ", "output": "{\n\tvar latest LinkTweet\n\n\tq := datastore.NewQuery(linkTweetKind).Order(\"-CreatedTime\").Project(\"CreatedTime\").Limit(1)\n\tq.GetAll(c, latest)\n\ti := q.Run(c)\n\ti.Next(&latest)\n\ttime, _ := latest.CreatedAtTime()\n\treturn time\n}"} {"input": "package pump\n\nimport (\n\t\"math\"\n\n\t\"github.com/tidepool-org/platform/data\"\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tBolusAmountMaximumUnitsUnits = \"Units\"\n\tBolusAmountMaximumValueUnitsMaximum = 100.0\n\tBolusAmountMaximumValueUnitsMinimum = 0.0\n)\n\nfunc BolusAmountMaximumUnits() []string {\n\treturn []string{\n\t\tBolusAmountMaximumUnitsUnits,\n\t}\n}\n\ntype BolusAmountMaximum struct {\n\tUnits *string `json:\"units,omitempty\" bson:\"units,omitempty\"`\n\tValue *float64 `json:\"value,omitempty\" bson:\"value,omitempty\"`\n}\n\n\n\nfunc NewBolusAmountMaximum() *BolusAmountMaximum {\n\treturn &BolusAmountMaximum{}\n}\n\nfunc (b *BolusAmountMaximum) Parse(parser structure.ObjectParser) {\n\tb.Units = parser.String(\"units\")\n\tb.Value = parser.Float64(\"value\")\n}\n\nfunc (b *BolusAmountMaximum) Validate(validator structure.Validator) {\n\tvalidator.String(\"units\", b.Units).Exists().OneOf(BolusAmountMaximumUnits()...)\n\tvalidator.Float64(\"value\", b.Value).Exists().InRange(BolusAmountMaximumValueRangeForUnits(b.Units))\n}\n\nfunc (b *BolusAmountMaximum) Normalize(normalizer data.Normalizer) {}\n\nfunc BolusAmountMaximumValueRangeForUnits(units *string) (float64, float64) {\n\tif units != nil {\n\t\tswitch *units {\n\t\tcase BolusAmountMaximumUnitsUnits:\n\t\t\treturn BolusAmountMaximumValueUnitsMinimum, BolusAmountMaximumValueUnitsMaximum\n\t\t}\n\t}\n\treturn -math.MaxFloat64, math.MaxFloat64\n}\n\nfunc ParseBolusAmountMaximum(parser structure.ObjectParser) *BolusAmountMaximum ", "output": "{\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewBolusAmountMaximum()\n\tparser.Parse(datum)\n\treturn datum\n}"} {"input": "package fs\n\nimport (\n\t\"github.com/opencontainers/runc/libcontainer/cgroups\"\n\t\"github.com/opencontainers/runc/libcontainer/cgroups/fscommon\"\n\t\"github.com/opencontainers/runc/libcontainer/configs\"\n)\n\ntype NetPrioGroup struct {\n}\n\n\n\nfunc (s *NetPrioGroup) Apply(path string, d *cgroupData) error {\n\treturn join(path, d.pid)\n}\n\nfunc (s *NetPrioGroup) Set(path string, r *configs.Resources) error {\n\tfor _, prioMap := range r.NetPrioIfpriomap {\n\t\tif err := fscommon.WriteFile(path, \"net_prio.ifpriomap\", prioMap.CgroupString()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (s *NetPrioGroup) GetStats(path string, stats *cgroups.Stats) error {\n\treturn nil\n}\n\nfunc (s *NetPrioGroup) Name() string ", "output": "{\n\treturn \"net_prio\"\n}"} {"input": "package swagger\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n)\n\nfunc (prop *ModelProperty) setDescription(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"description\"); tag != \"\" {\n\t\tprop.Description = tag\n\t}\n}\n\nfunc (prop *ModelProperty) setDefaultValue(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"default\"); tag != \"\" {\n\t\tprop.DefaultValue = Special(tag)\n\t}\n}\n\nfunc (prop *ModelProperty) setEnumValues(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"enum\"); tag != \"\" {\n\t\tprop.Enum = strings.Split(tag, \"|\")\n\t}\n}\n\nfunc (prop *ModelProperty) setMaximum(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"maximum\"); tag != \"\" {\n\t\tprop.Maximum = tag\n\t}\n}\n\nfunc (prop *ModelProperty) setMinimum(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"minimum\"); tag != \"\" {\n\t\tprop.Minimum = tag\n\t}\n}\n\nfunc (prop *ModelProperty) setUniqueItems(field reflect.StructField) {\n\ttag := field.Tag.Get(\"unique\")\n\tswitch tag {\n\tcase \"true\":\n\t\tv := true\n\t\tprop.UniqueItems = &v\n\tcase \"false\":\n\t\tv := false\n\t\tprop.UniqueItems = &v\n\t}\n}\n\n\n\nfunc (prop *ModelProperty) setPropertyMetadata(field reflect.StructField) ", "output": "{\n\tprop.setDescription(field)\n\tprop.setEnumValues(field)\n\tprop.setMinimum(field)\n\tprop.setMaximum(field)\n\tprop.setUniqueItems(field)\n\tprop.setDefaultValue(field)\n}"} {"input": "package iso20022\n\n\ntype HoldIndicator2 struct {\n\n\tIndicator *YesNoIndicator `xml:\"Ind\"`\n\n\tReason []*RegistrationReason1 `xml:\"Rsn,omitempty\"`\n}\n\nfunc (h *HoldIndicator2) SetIndicator(value string) {\n\th.Indicator = (*YesNoIndicator)(&value)\n}\n\n\n\nfunc (h *HoldIndicator2) AddReason() *RegistrationReason1 ", "output": "{\n\tnewValue := new(RegistrationReason1)\n\th.Reason = append(h.Reason, newValue)\n\treturn newValue\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path\"\n)\n\nvar pkgloc string\nvar apiFile string\nvar ctxFile string\n\n\n\nfunc generateAPIFile(gss []*GoSignature) {\n\tf, err := os.Create(apiFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\n\tf.WriteString(header)\n\tgenerateAPI(f, gss)\n}\n\nfunc generateContextFile(gss []*GoSignature) {\n\tg, err := os.Create(ctxFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer g.Close()\n\tg.WriteString(header)\n\tgenerateContextAPI(g, gss)\n}\n\nfunc main() {\n\tsigs := Parse()\n\n\tvar gss []*GoSignature\n\tsigs = filterCSigs(sigs)\n\tfor _, sig := range sigs {\n\t\tgs := sig.GoSig()\n\t\tgss = append(gss, gs)\n\t}\n\n\tgenerateAPIFile(gss)\n\tgenerateContextFile(gss)\n\n\tvar err error\n\tfilename := apiFile\n\tcmd := exec.Command(\"goimports\", \"-w\", filename)\n\tif err = cmd.Run(); err != nil {\n\t\tlog.Fatalf(\"Go imports failed with %v for %q\", err, filename)\n\t}\n\n\tfilename = ctxFile\n\tcmd = exec.Command(\"goimports\", \"-w\", filename)\n\tif err = cmd.Run(); err != nil {\n\t\tlog.Fatalf(\"Go imports failed with %v for %q\", err, filename)\n\t}\n}\n\nfunc init() ", "output": "{\n\tgopath := os.Getenv(\"GOPATH\")\n\tpkgloc = path.Join(gopath, \"src/gorgonia.org/cu\")\n\tapiFile = path.Join(pkgloc, \"api.go\")\n\tctxFile = path.Join(pkgloc, \"ctx_api.go\")\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetServiceRequest struct {\n\n\tServiceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"serviceId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetServiceRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request GetServiceRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\n\n\n\nfunc (request GetServiceRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetServiceResponse struct {\n\n\tRawResponse *http.Response\n\n\tService `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetServiceResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetServiceResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetServiceRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package main\n\nimport \"math\"\n\n\nfunc hsin(theta float64) float64 {\n\treturn math.Pow(math.Sin(theta/2), 2)\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Distance(lat1, lon1, lat2, lon2 float64) float64 ", "output": "{\n\tvar la1, lo1, la2, lo2, r float64\n\tla1 = lat1 * math.Pi / 180\n\tlo1 = lon1 * math.Pi / 180\n\tla2 = lat2 * math.Pi / 180\n\tlo2 = lon2 * math.Pi / 180\n\n\tr = 6378100 \n\n\th := hsin(la2-la1) + math.Cos(la1)*math.Cos(la2)*hsin(lo2-lo1)\n\n\treturn 2 * r * math.Asin(math.Sqrt(h))\n}"} {"input": "package iso20022\n\n\ntype ApplicationParameters4 struct {\n\n\tApplicationIdentification *Max35Text `xml:\"ApplId\"`\n\n\tVersion *Max256Text `xml:\"Vrsn\"`\n\n\tParameters []*Max100KBinary `xml:\"Params,omitempty\"`\n\n\tEncryptedParameters *ContentInformationType10 `xml:\"NcrptdParams,omitempty\"`\n}\n\nfunc (a *ApplicationParameters4) SetApplicationIdentification(value string) {\n\ta.ApplicationIdentification = (*Max35Text)(&value)\n}\n\nfunc (a *ApplicationParameters4) SetVersion(value string) {\n\ta.Version = (*Max256Text)(&value)\n}\n\n\n\nfunc (a *ApplicationParameters4) AddEncryptedParameters() *ContentInformationType10 {\n\ta.EncryptedParameters = new(ContentInformationType10)\n\treturn a.EncryptedParameters\n}\n\nfunc (a *ApplicationParameters4) AddParameters(value string) ", "output": "{\n\ta.Parameters = append(a.Parameters, (*Max100KBinary)(&value))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\tprimes \"github.com/whatever/math/primes\"\n\t_ \"math\"\n\t\"sort\"\n)\n\n\n\nfunc SortedString(s string) string {\n\n\tintArray := make([]int, len(s))\n\n\tfor i, letter := range s {\n\t\tintArray[i] = int(letter)\n\t}\n\n\tsort.Ints(intArray)\n\n\tnewString := \"\"\n\n\tfor _, digit := range intArray {\n\t\tnewString += fmt.Sprintf(\"%s\", string(digit))\n\t}\n\n\treturn newString\n}\n\nfunc IsPermutation(lhs, rhs int) bool {\n\treturn SortedString(fmt.Sprintf(\"%d\", lhs)) == SortedString(fmt.Sprintf(\"%d\", rhs))\n}\n\nfunc main() {\n\tlimit := 1000000\n\ts := primes.NewNaiveSieve(limit)\n\thits := make(map[int]float64)\n\n\tminIndex := 200000000\n\tminValue := float64(limit + 1)\n\n\tfor i := 2; i <= limit; i++ {\n\t\tif i%(limit/100) == 0 {\n\t\t\tfmt.Println(i)\n\t\t}\n\n\t\ttotient := s.Totient(i)\n\t\tt := float64(i) / float64(totient)\n\t\thits[i] = t\n\n\t\tif !IsPermutation(totient, i) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif t < minValue {\n\t\t\tminValue = t\n\t\t\tminIndex = i\n\t\t\tfmt.Println(minIndex, minValue, i, totient)\n\t\t}\n\t}\n\n\tfmt.Println(minIndex, minValue)\n}\n\nfunc Factorial(n int) int ", "output": "{\n\tresult := 1\n\tfor n > 0 {\n\t\tresult *= n\n\t\tn--\n\t}\n\treturn result\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nconst (\n\tFilePermission = 0644\n\n\tDirPermission = 0755\n)\n\n\n\n\n\nfunc ValidatePath(path string) (string, error) {\n\tpath, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = dirExists(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = dirExists(path, \"posts\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = dirExists(path, \"static\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = dirExists(path, \"templates\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdeploy := filepath.Join(path, \"deploy\")\n\terr = os.RemoveAll(deploy)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = os.MkdirAll(filepath.Join(deploy, \"posts\"), DirPermission)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn path, os.MkdirAll(filepath.Join(deploy, \"tags\"), DirPermission)\n}\n\n\n\n\n\nfunc dirExists(paths ...string) error ", "output": "{\n\tpath := strings.Join(paths, string(filepath.Separator))\n\n\tstat, err := os.Lstat(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !stat.IsDir() {\n\t\treturn newError(\"Path is not a directory.\")\n\t}\n\n\treturn nil\n}"} {"input": "package server\n\nimport (\n\tpb \"go-common/app/service/main/resource/api/v1\"\n\t\"go-common/app/service/main/resource/service\"\n\t\"go-common/library/net/rpc/warden\"\n)\n\n\n\n\nfunc New(c *warden.ServerConfig, svr *service.Service) *warden.Server ", "output": "{\n\tws := warden.NewServer(c)\n\tpb.RegisterResourceServer(ws.Server(), svr)\n\tws, err := ws.Start()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ws\n}"} {"input": "package profile\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\n\t\"github.com/sirupsen/logrus\"\n\n\t\"github.com/supergiant/control/pkg/storage\"\n)\n\nconst DefaultKubeProfilePreifx = \"/supergiant/profile\"\n\ntype Service struct {\n\tprefix string\n\tkubeProfileStorage storage.Interface\n}\n\nfunc NewService(prefix string, s storage.Interface) *Service {\n\treturn &Service{\n\t\tprefix: prefix,\n\t\tkubeProfileStorage: s,\n\t}\n}\n\nfunc (s *Service) Get(ctx context.Context, profileId string) (*Profile, error) {\n\tlogrus.Debugf(\"get cloud profile by id %s\", profileId)\n\tprofileData, err := s.kubeProfileStorage.Get(ctx, s.prefix, profileId)\n\tprofile := &Profile{}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = json.Unmarshal(profileData, profile)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn profile, nil\n}\n\nfunc (s *Service) Create(ctx context.Context, profile *Profile) error {\n\tprofileData, err := json.Marshal(profile)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.kubeProfileStorage.Put(ctx, s.prefix, profile.ID, profileData)\n}\n\n\n\nfunc (s *Service) GetAll(ctx context.Context) ([]Profile, error) ", "output": "{\n\tvar (\n\t\tprofiles []Profile\n\t\tprofile Profile\n\t)\n\n\tprofilesData, err := s.kubeProfileStorage.GetAll(ctx, s.prefix)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, profileData := range profilesData {\n\t\terr = json.Unmarshal(profileData, &profile)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tprofiles = append(profiles, profile)\n\t}\n\n\treturn profiles, nil\n}"} {"input": "package scene\n\nimport \"github.com/thinkofdeath/steven/ui\"\n\n\ntype Type struct {\n\tvisible bool\n\n\tdrawables []ui.Drawable\n\thidding bool\n}\n\n\nfunc New(visible bool) *Type {\n\treturn &Type{\n\t\tvisible: visible,\n\t}\n}\n\n\nfunc (t *Type) Show() {\n\tif t.visible {\n\t\treturn\n\t}\n\tt.visible = true\n\tfor _, d := range t.drawables {\n\t\tui.AddDrawable(d)\n\t}\n}\n\n\n\n\n\nfunc (t *Type) AddDrawable(d ui.Drawable) {\n\tt.drawables = append(t.drawables, d)\n\tif t.visible {\n\t\tui.AddDrawable(d)\n\t}\n\td.SetRemoveHook(t.removeHook)\n}\n\nfunc (t *Type) removeHook(d ui.Drawable) {\n\tif t.hidding {\n\t\treturn\n\t}\n\tfor i, dd := range t.drawables {\n\t\tif dd == d {\n\t\t\tt.drawables = append(t.drawables[:i], t.drawables[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n\n}\n\n\nfunc (t *Type) IsVisible() bool {\n\treturn t.visible\n}\n\nfunc (t *Type) Hide() ", "output": "{\n\tif !t.visible {\n\t\treturn\n\t}\n\tt.visible = false\n\tt.hidding = true\n\tfor _, d := range t.drawables {\n\t\tui.Remove(d)\n\t}\n\tt.hidding = false\n}"} {"input": "package dynaml\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cloudfoundry-incubator/spiff/yaml\"\n)\n\ntype BooleanExpr struct {\n\tValue bool\n}\n\n\n\nfunc (e BooleanExpr) String() string {\n\treturn fmt.Sprintf(\"%v\", e.Value)\n}\n\nfunc (e BooleanExpr) Evaluate(Binding) (yaml.Node, bool) ", "output": "{\n\treturn node(e.Value), true\n}"} {"input": "package main\n\nimport (\n\t\"github.com/apaxa-go/helper/unicodeh\"\n\t\"github.com/apaxa-go/helper/unicodeh/rangetableh\"\n\t\"golang.org/x/text/unicode/norm\"\n\t\"log\"\n\t\"unicode\"\n)\n\n\n\n\n\nfunc main() {\n\ttmpNormPairs := make(map[rune]rune) \n\tfor iter := rangetableh.Start(unicodeh.BidiPairedBracketTypeOpen); !iter.End(); iter.Next() {\n\t\topenBracket := iter.Value()\n\t\tcloseBracket := unicodeh.BidiPairedBracket[openBracket]\n\t\ttmpNormPairs[normRune(openBracket)] = normRune(closeBracket)\n\t}\n\n\ttmpNormClose := make(map[rune]rune) \n\tfor iter := rangetableh.Start(unicodeh.BidiPairedBracketTypeClose); !iter.End(); iter.Next() {\n\t\ttmpNormClose[normRune(iter.Value())] = iter.Value()\n\t}\n\n\tnormOpen := make(map[rune]rune) \n\tnormClose := make(map[rune]rune) \n\tfor r := rune(0); r <= unicode.MaxRune; r++ {\n\t\tnormR := normRune(r)\n\t\tif pair, ok := tmpNormPairs[normR]; ok {\n\t\t\tnormOpen[r] = pair\n\t\t}\n\t\tif _, ok := tmpNormClose[normR]; ok {\n\t\t\tnormClose[r] = normR\n\t\t}\n\t}\n\n\tlog.Println(\"Open => norm close: \", normOpen)\n\tlog.Println(\"Close => norm close:\", normClose)\n}\n\nfunc normRune(r rune) rune ", "output": "{\n\ttmp := []rune(norm.NFC.String(string(r)))\n\tif len(tmp) != 1 {\n\t\treturn -1\n\t}\n\treturn tmp[0]\n}"} {"input": "package data\n\nimport (\n\t\"crypto/tls\"\n\t\"io\"\n\t\"io/ioutil\"\n)\n\n\ntype Config struct {\n\tInLog io.Writer\n\tOutLog io.Writer\n\tLog io.Writer\n\tCreateCallback FormCallback\n\tArchive bool\n\tSkipTLS bool\n\tTLSConfig *tls.Config\n\tSkipSRVLookup bool\n}\n\n\n\n\nfunc (c *Config) GetLog() io.Writer ", "output": "{\n\tif c.Log == nil {\n\t\treturn ioutil.Discard\n\t}\n\n\treturn c.Log\n}"} {"input": "package customer\n\nimport (\n\t\"testing\"\n\n\tassert \"github.com/stretchr/testify/require\"\n\tstripe \"github.com/stripe/stripe-go\"\n\t_ \"github.com/stripe/stripe-go/testing\"\n)\n\nfunc TestCustomerDel(t *testing.T) {\n\tcustomer, err := Del(\"cus_123\", nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerGet(t *testing.T) {\n\tcustomer, err := Get(\"cus_123\", nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\n\n\nfunc TestCustomerNew(t *testing.T) {\n\tcustomer, err := New(&stripe.CustomerParams{\n\t\tEmail: stripe.String(\"foo@example.com\"),\n\t\tShipping: &stripe.CustomerShippingDetailsParams{\n\t\t\tAddress: &stripe.AddressParams{\n\t\t\t\tLine1: stripe.String(\"line1\"),\n\t\t\t\tCity: stripe.String(\"city\"),\n\t\t\t},\n\t\t\tName: stripe.String(\"name\"),\n\t\t},\n\t})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerNew_NilParams(t *testing.T) {\n\tcustomer, err := New(nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerUpdate(t *testing.T) {\n\tcustomer, err := Update(\"cus_123\", &stripe.CustomerParams{\n\t\tEmail: stripe.String(\"foo@example.com\"),\n\t})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerList(t *testing.T) ", "output": "{\n\ti := List(&stripe.CustomerListParams{})\n\n\tassert.True(t, i.Next())\n\tassert.Nil(t, i.Err())\n\tassert.NotNil(t, i.Customer())\n}"} {"input": "package assert\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/alecthomas/colour\"\n\t\"github.com/alecthomas/repr\"\n\t\"github.com/sergi/go-diff/diffmatchpatch\"\n)\n\n\n\nfunc DiffValuesDefault(a, b interface{}) string {\n\tdiff := diffmatchpatch.New()\n\tat := repr.String(a)\n\tbt := repr.String(b)\n\tdiffs := diff.DiffMain(at, bt, true)\n\tw := bytes.NewBuffer(nil)\n\tfor _, d := range diffs {\n\t\tswitch d.Type {\n\t\tcase diffmatchpatch.DiffEqual:\n\t\t\tif len(d.Text) <= 40 {\n\t\t\t\tw.WriteString(d.Text)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(w, \"%s...%s\", d.Text[:15], d.Text[len(d.Text)-15:])\n\t\t\t}\n\t\tcase diffmatchpatch.DiffDelete:\n\t\t\tfmt.Fprintf(w, \"-{{%s}}\", d.Text)\n\t\tcase diffmatchpatch.DiffInsert:\n\t\t\tfmt.Fprintf(w, \"+{{%s}}\", d.Text)\n\t\t}\n\t}\n\treturn w.String()\n}\n\nfunc DiffValues(a, b interface{}) string ", "output": "{\n\tprinter := colour.String()\n\tdiff := diffmatchpatch.New()\n\tat := repr.String(a, repr.OmitEmpty())\n\tbt := repr.String(b, repr.OmitEmpty())\n\tdiffs := diff.DiffMain(at, bt, true)\n\tfor _, d := range diffs {\n\t\tswitch d.Type {\n\t\tcase diffmatchpatch.DiffEqual:\n\t\t\tif len(d.Text) <= 40 {\n\t\t\t\tprinter.Print(d.Text)\n\t\t\t} else {\n\t\t\t\tprinter.Printf(\"%s^B...^R%s\", d.Text[:15], d.Text[len(d.Text)-15:])\n\t\t\t}\n\t\tcase diffmatchpatch.DiffDelete:\n\t\t\tprinter.Printf(\"^9%s^R\", d.Text)\n\t\tcase diffmatchpatch.DiffInsert:\n\t\t\tprinter.Printf(\"^a%s^R\", d.Text)\n\t\t}\n\t}\n\treturn printer.String()\n}"} {"input": "package user\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n\ntype RangeList []*Range\n\n\nfunc ParseRangeList(str string) (*RangeList, error) {\n\trl := RangeList{}\n\tif len(str) == 0 {\n\t\treturn &rl, nil\n\t}\n\tparts := strings.Split(str, \",\")\n\tfor _, p := range parts {\n\t\tr, err := ParseRange(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trl = append(rl, r)\n\t}\n\treturn &rl, nil\n}\n\n\nfunc (l *RangeList) Empty() bool {\n\tif len(*l) == 0 {\n\t\treturn true\n\t}\n\tfor _, r := range *l {\n\t\tif !r.Empty() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (l *RangeList) Contains(uid int) bool {\n\tfor _, r := range *l {\n\t\tif r.Contains(uid) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\n\nfunc (l *RangeList) Set(value string) error {\n\tnewRangeList, err := ParseRangeList(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*l = *newRangeList\n\treturn nil\n}\n\n\nfunc (l *RangeList) String() string {\n\trangeStrings := []string{}\n\tfor _, r := range *l {\n\t\trangeStrings = append(rangeStrings, r.String())\n\t}\n\treturn strings.Join(rangeStrings, \",\")\n}\n\n\n\nfunc IsUserAllowed(user string, allowed *RangeList) bool {\n\tuid, err := strconv.Atoi(user)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn allowed.Contains(uid)\n}\n\nfunc (l *RangeList) Type() string ", "output": "{\n\treturn \"user.RangeList\"\n}"} {"input": "package orchestrator\n\nimport (\n\t\"encoding/json\"\n)\n\ntype Message struct {\n\tID int\n\tState int\n}\n\n\ntype Error struct {\n\tCode int `json:\"code\"`\n\tMessage string `json:\"message\"`\n}\n\n\n\nfunc (e *Error) Error() string ", "output": "{\n\to, _ := json.Marshal(e)\n\treturn string(o)\n}"} {"input": "package e2e\n\nimport (\n\t\"testing\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/onsi/ginkgo\"\n\t\"github.com/onsi/ginkgo/config\"\n\t\"github.com/onsi/gomega\"\n\t_ \"k8s.io/client-go/plugin/pkg/client/auth\"\n\n\t\"github.com/jetstack-experimental/cert-manager/pkg/logs\"\n\t\"github.com/jetstack-experimental/cert-manager/test/e2e/framework\"\n)\n\n\n\n\n\nfunc RunE2ETests(t *testing.T) ", "output": "{\n\tlogs.InitLogs()\n\tdefer logs.FlushLogs()\n\n\tgomega.RegisterFailHandler(ginkgo.Fail)\n\tif config.GinkgoConfig.FocusString == \"\" && config.GinkgoConfig.SkipString == \"\" {\n\t\tconfig.GinkgoConfig.SkipString = `\\[Flaky\\]|\\[Feature:.+\\]`\n\t}\n\n\tglog.Infof(\"Starting e2e run %q on Ginkgo node %d\", framework.RunId, config.GinkgoConfig.ParallelNode)\n\tginkgo.RunSpecs(t, \"cert-manager e2e suite\")\n}"} {"input": "package network\n\nimport (\n\tspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n)\n\nfunc NewNoneProvider() Provider {\n\treturn &none{}\n}\n\ntype none struct {\n}\n\nfunc (h *none) New() (Namespace, error) {\n\treturn &noneNS{}, nil\n}\n\ntype noneNS struct {\n}\n\nfunc (h *noneNS) Set(s *specs.Spec) {\n}\n\n\n\nfunc (h *noneNS) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar s *bufio.Scanner\n\n\n\nfunc getLength(l string) int {\n\tvar n int\n\tfmt.Sscanf(l, \"%b\", &n)\n\treturn n\n}\n\nfunc solve(out io.Writer, header string) {\n\tkeyMap := buildKey(header)\n\tvar l int\n\tvar line, code string\n\ts.Scan()\n\tfor line = s.Text(); line != \"000\"; {\n\t\tl, line = getLength(line[:3]), line[3:]\n\t\tfor {\n\t\t\tcode, line = line[:l], line[l:]\n\t\t\tif len(line) < l {\n\t\t\t\ts.Scan()\n\t\t\t\tline += s.Text()\n\t\t\t}\n\t\t\tif strings.Count(code, \"1\") == l {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfmt.Fprintf(out, \"%c\", keyMap[code])\n\t\t}\n\t}\n\tfmt.Fprintln(out)\n}\n\nfunc main() {\n\tin, _ := os.Open(\"213.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"213.out\")\n\tdefer out.Close()\n\n\ts = bufio.NewScanner(in)\n\ts.Split(bufio.ScanLines)\n\n\tvar line string\n\tfor s.Scan() {\n\t\tif line = s.Text(); line == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tsolve(out, line)\n\t}\n}\n\nfunc buildKey(header string) map[string]byte ", "output": "{\n\tkeyMap := make(map[string]byte)\n\tvar key int64\n\tdigit := uint(1)\n\tfor i := range header {\n\t\tif key == (2<<(digit-1) - 1) {\n\t\t\tkey = 0\n\t\t\tdigit++\n\t\t}\n\t\tbinary := strconv.FormatInt(key, 2)\n\t\tbinary = strings.Repeat(\"0\", int(digit)-len(binary)) + binary\n\t\tkeyMap[binary] = header[i]\n\t\tkey++\n\t}\n\treturn keyMap\n}"} {"input": "package aliasdirectlink\n\n\ntype Request struct {\n\tOrderID string `json:\"orderId\"`\n\tAmount string `json:\",\"`\n\tAlias string `json:\"alias\"`\n}\n\n\nfunc (r *Request) isValid() error {\n\tif \"\" == r.Alias {\n\t\treturn nil\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc NewRequest() *Request ", "output": "{\n\treturn &Request{}\n}"} {"input": "package calendar\n\nimport (\n\t\"time\"\n)\n\nvar (\n\tentries = make(map[int]Entry)\n\tindex int\n)\n\ntype Entry struct {\n\tID int\n\tTitle string\n\tStarts time.Time\n\tFinishes time.Time\n}\n\nfunc (e Entry) Duration() time.Duration {\n\treturn e.Finishes.Sub(e.Starts)\n}\n\n\n\nfunc Add(e Entry) Entry {\n\tindex++\n\te.ID = index\n\tUpdate(e)\n\treturn e\n}\n\nfunc Update(e Entry) {\n\tentries[e.ID] = e\n}\n\nfunc Remove(id int) {\n\tdelete(entries, id)\n}\n\nfunc Count() int {\n\treturn len(entries)\n}\n\nfunc All() []Entry {\n\tall := []Entry{}\n\tfor _, e := range entries {\n\t\tall = append(all, e)\n\t}\n\treturn all\n}\n\nfunc Lookup(id int) (Entry, bool) ", "output": "{\n\te, isPresent := entries[id]\n\treturn e, isPresent\n}"} {"input": "package sortedmap\n\nimport \"sort\"\n\n\n\nfunc (sm *SortedMap) boundsIdxSearch(lowerBound, upperBound interface{}) []int {\n\tsmLen := len(sm.sorted)\n\tif smLen == 0 {\n\t\treturn nil\n\t}\n\n\tif lowerBound != nil && upperBound != nil {\n\t\tif sm.lessFn(upperBound, lowerBound) {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tlowerBoundIdx := 0\n\tif lowerBound != nil {\n\t\tlowerBoundIdx = sm.setBoundIdx(lowerBound)\n\n\t\tif lowerBoundIdx == smLen {\n\t\t\tlowerBoundIdx--\n\t\t}\n\t\tif lowerBoundIdx >= 0 && sm.lessFn(sm.idx[sm.sorted[lowerBoundIdx]], lowerBound) {\n\t\t\tlowerBoundIdx++\n\t\t}\n\t}\n\n\tupperBoundIdx := smLen - 1\n\tif upperBound != nil {\n\t\tupperBoundIdx = sm.setBoundIdx(upperBound)\n\t\tif upperBoundIdx == smLen {\n\t\t\tupperBoundIdx--\n\t\t}\n\t\tif upperBoundIdx >= 0 && sm.lessFn(upperBound, sm.idx[sm.sorted[upperBoundIdx]]) {\n\t\t\tupperBoundIdx--\n\t\t}\n\t}\n\n\tif lowerBoundIdx > upperBoundIdx {\n\t\treturn nil\n\t}\n\n\treturn []int{\n\t\tlowerBoundIdx,\n\t\tupperBoundIdx,\n\t}\n}\n\nfunc (sm *SortedMap) setBoundIdx(boundVal interface{}) int ", "output": "{\n\treturn sort.Search(len(sm.sorted), func(i int) bool {\n\t\treturn sm.lessFn(boundVal, sm.idx[sm.sorted[i]])\n\t})\n}"} {"input": "package iso20022\n\n\ntype DirectDebitTransaction7 struct {\n\n\tMandateRelatedInformation *MandateRelatedInformation8 `xml:\"MndtRltdInf,omitempty\"`\n\n\tCreditorSchemeIdentification *PartyIdentification43 `xml:\"CdtrSchmeId,omitempty\"`\n\n\tPreNotificationIdentification *Max35Text `xml:\"PreNtfctnId,omitempty\"`\n\n\tPreNotificationDate *ISODate `xml:\"PreNtfctnDt,omitempty\"`\n}\n\n\n\nfunc (d *DirectDebitTransaction7) AddCreditorSchemeIdentification() *PartyIdentification43 {\n\td.CreditorSchemeIdentification = new(PartyIdentification43)\n\treturn d.CreditorSchemeIdentification\n}\n\nfunc (d *DirectDebitTransaction7) SetPreNotificationIdentification(value string) {\n\td.PreNotificationIdentification = (*Max35Text)(&value)\n}\n\nfunc (d *DirectDebitTransaction7) SetPreNotificationDate(value string) {\n\td.PreNotificationDate = (*ISODate)(&value)\n}\n\nfunc (d *DirectDebitTransaction7) AddMandateRelatedInformation() *MandateRelatedInformation8 ", "output": "{\n\td.MandateRelatedInformation = new(MandateRelatedInformation8)\n\treturn d.MandateRelatedInformation\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/docker/docker/api/types/filters\"\n)\n\n\n\nfunc printImages(images []types.ImageSummary) {\n\tsuseImages := make([]types.ImageSummary, 0, len(images))\n\tcache := getCacheFile()\n\tcounter := 0\n\n\tfor _, img := range images {\n\t\tselect {\n\t\tcase <-killChannel:\n\t\t\treturn\n\t\tdefault:\n\t\t\tfmt.Printf(\"Inspecting image %d/%d\\r\", (counter + 1), len(images))\n\t\t\tif cache.isSUSE(img.ID) {\n\t\t\t\tsuseImages = append(suseImages, img)\n\t\t\t}\n\t\t}\n\t\tcounter++\n\t}\n\tformatAndPrint(suseImages)\n\tcache.flush()\n}\n\n\nfunc imagesCmd(ctx *cli.Context) {\n\tclient := getDockerClient()\n\n\tif ctx.GlobalBool(\"force\") {\n\t\tcd := getCacheFile()\n\t\tcd.reset()\n\t}\n\n\tif imgs, err := client.ImageList(context.Background(), types.ImageListOptions{}); err != nil {\n\t\tlogAndFatalf(\"Cannot proceed safely: %v.\", err)\n\t} else {\n\t\tprintImages(imgs)\n\t\texitWithCode(0)\n\t}\n}\n\n\n\n\n\nfunc checkImageExists(repo, tag string) (bool, error) ", "output": "{\n\tclient := getDockerClient()\n\n\timages, err := client.ImageList(context.Background(), types.ImageListOptions{\n\t\tAll: false,\n\t\tFilters: filters.NewArgs(filters.Arg(\"reference\", repo)),\n\t})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(images) == 0 {\n\t\treturn false, nil\n\t}\n\n\tref := fmt.Sprintf(\"%s:%s\", repo, tag)\n\tfor _, image := range images {\n\t\tfor _, t := range image.RepoTags {\n\t\t\tif ref == t {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn false, nil\n}"} {"input": "package validation\n\nimport (\n\t\"strings\"\n\n\t\"github.com/rantuttl/cloudops/apimachinery/pkg/util/validation\"\n\t\"github.com/rantuttl/cloudops/apimachinery/pkg/util/validation/field\"\n)\n\nconst IsNegativeErrorMsg string = `must be greater than or equal to 0`\n\n\n\n\n\n\ntype ValidateNameFunc func(name string, prefix bool) []string\n\n\nfunc NameIsDNSSubdomain(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1123Subdomain(name)\n}\n\n\nfunc NameIsDNSLabel(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1123Label(name)\n}\n\n\nfunc NameIsDNS1035Label(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1035Label(name)\n}\n\n\n\n\nvar ValidateNamespaceName = NameIsDNSLabel\n\n\n\n\nvar ValidateServiceAccountName = NameIsDNSSubdomain\n\n\n\n\n\n\nfunc ValidateNonnegativeField(value int64, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif value < 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, value, IsNegativeErrorMsg))\n\t}\n\treturn allErrs\n}\n\nfunc maskTrailingDash(name string) string ", "output": "{\n\tif strings.HasSuffix(name, \"-\") {\n\t\treturn name[:len(name)-2] + \"a\"\n\t}\n\treturn name\n}"} {"input": "package node\n\nimport (\n\t\"errors\"\n\t\"os\"\n\n\tlog \"github.com/cihub/seelog\"\n)\n\n\ntype OptionsDirectory struct {\n\tData string\n\tStorage string\n\tKeystore string\n\tConfig string\n\tRuntime string\n}\n\n\nfunc (options *OptionsDirectory) Check() error {\n\n\tif options.Config != \"\" {\n\t\terr := ensureDirExists(options.Config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr := ensureOrCreateDir(options.Runtime)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ensureOrCreateDir(options.Storage)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ensureOrCreateDir(options.Data)\n}\n\n\n\nfunc ensureDirExists(dir string) error {\n\tfileStat, err := os.Stat(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isDir := fileStat.IsDir(); !isDir {\n\t\treturn errors.New(\"directory expected\")\n\t}\n\treturn nil\n}\n\nfunc ensureOrCreateDir(dir string) error ", "output": "{\n\terr := ensureDirExists(dir)\n\tif os.IsNotExist(err) {\n\t\tlog.Info(\"[Directory config checker] \", \"Directory: \", dir, \" does not exit. Creating new one\")\n\t\treturn os.MkdirAll(dir, 0700)\n\t}\n\treturn err\n}"} {"input": "package sockjs\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\ntype Config struct {\n\tSockjsURL string\n\n\tWebsocket bool\n\n\tResponseLimit int\n\n\tJsessionid bool\n\n\tJsessionidFunc func(http.ResponseWriter, *http.Request)\n\n\tVerifyAddr bool\n\n\tHeartbeatDelay time.Duration\n\n\tDisconnectDelay time.Duration\n\n\tHeaders []string\n\n\tLogger *log.Logger\n\n\tiframePage []byte\n\tiframeHash string\n}\n\n\n\n\nfunc NewConfig() (c Config) ", "output": "{\n\tc.SockjsURL = \"https://cdn.sockjs.org/sockjs-0.3.4.min.js\"\n\tc.Websocket = true\n\tc.ResponseLimit = 128 * 1024\n\tc.VerifyAddr = true\n\tc.HeartbeatDelay = time.Duration(25) * time.Second\n\tc.DisconnectDelay = time.Duration(5) * time.Second\n\tc.Headers = []string{\"referer\", \"x-client-ip\", \"x-forwarded-for\",\n\t\t\"x-cluster-client-ip\", \"via\", \"x-real-ip\", \"host\"}\n\tc.Logger = log.New(os.Stdout, \"sockjs: \", log.LstdFlags)\n\tc.iframePage = []byte(fmt.Sprintf(iframePageFormat, c.SockjsURL))\n\thash := md5.New()\n\thash.Write(c.iframePage)\n\tc.iframeHash = fmt.Sprintf(\"%x\", hash.Sum(nil))\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/unrolled/render\"\n)\n\n\nvar Render *render.Render\n\n\nfunc init() {\n\tRender = render.New(render.Options{\n\t\tIndentJSON: true,\n\t})\n}\n\nfunc index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Welcome to the home page!\")\n}\n\nfunc apiHandler(w http.ResponseWriter, r *http.Request) {\n\tRender.JSON(w, http.StatusOK, \"Welcome to the api hander page!\")\n}\n\nfunc apiKeyHandler(w http.ResponseWriter, r *http.Request) {\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the api Key hander page! %s\", id)\n}\n\nfunc apiKeyDetailsHandler(w http.ResponseWriter, r *http.Request) {\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the api Key Details hander page! %s\", id)\n}\n\n\n\nfunc notFound(w http.ResponseWriter, r *http.Request) {\n\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n}\n\nfunc webKeyHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the web Key hander page! %s\", id)\n}"} {"input": "package drum\n\nimport \"fmt\"\n\n\n\ntype Pattern struct {\n\tversion Version\n\ttempo Tempo\n\ttracks Tracks\n}\n\nfunc (p Pattern) String() string {\n\treturn fmt.Sprintf(\"%s\\n%s\\n%s\", p.version.String(), p.tempo.String(), p.tracks.String())\n}\n\n\ntype Version string\n\nfunc (v Version) String() string {\n\treturn fmt.Sprintf(\"Saved with HW Version: %s\", string(v))\n}\n\n\ntype Tempo float64\n\nfunc (t Tempo) String() string {\n\treturn fmt.Sprintf(\"Tempo: %.3g\", t)\n}\n\n\ntype Tracks []Track\n\nfunc (t Tracks) String() string {\n\tpretty := \"\"\n\tfor _, track := range t {\n\t\tpretty = fmt.Sprintf(\"%s%s\\n\", pretty, track.String())\n\t}\n\treturn pretty\n}\n\n\ntype Track struct {\n\tID int\n\tName string\n\tSteps Steps\n}\n\nfunc (t Track) String() string {\n\treturn fmt.Sprintf(\"(%d) %s\\t%s\", t.ID, t.Name, t.Steps.String())\n}\n\n\ntype Steps struct {\n\tBars [4]Bar\n}\n\nfunc (s Steps) String() string {\n\tpretty := \"|\"\n\tfor _, bar := range s.Bars {\n\t\tpretty = pretty + bar.String() + \"|\"\n\t}\n\treturn pretty\n}\n\n\ntype Bar [4]Note\n\nfunc (bar Bar) String() string {\n\tpretty := \"\"\n\tfor _, note := range bar {\n\t\tpretty = pretty + note.String()\n\t}\n\treturn pretty\n}\n\n\ntype Note bool\n\n\n\nfunc (n Note) String() string ", "output": "{\n\tif n {\n\t\treturn \"x\"\n\t}\n\treturn \"-\"\n}"} {"input": "package gitea\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"reflect\"\n)\n\n\ntype AccessToken struct {\n\tID int64 `json:\"id\"`\n\tName string `json:\"name\"`\n\tToken string `json:\"sha1\"`\n\tTokenLastEight string `json:\"token_last_eight\"`\n}\n\n\ntype ListAccessTokensOptions struct {\n\tListOptions\n}\n\n\nfunc (c *Client) ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, *Response, error) {\n\tif len(c.username) == 0 {\n\t\treturn nil, nil, fmt.Errorf(\"\\\"username\\\" not set: only BasicAuth allowed\")\n\t}\n\topts.setDefaults()\n\ttokens := make([]*AccessToken, 0, opts.PageSize)\n\tresp, err := c.getParsedResponse(\"GET\", fmt.Sprintf(\"/users/%s/tokens?%s\", c.username, opts.getURLQuery().Encode()), jsonHeader, nil, &tokens)\n\treturn tokens, resp, err\n}\n\n\ntype CreateAccessTokenOption struct {\n\tName string `json:\"name\"`\n}\n\n\nfunc (c *Client) CreateAccessToken(opt CreateAccessTokenOption) (*AccessToken, *Response, error) {\n\tif len(c.username) == 0 {\n\t\treturn nil, nil, fmt.Errorf(\"\\\"username\\\" not set: only BasicAuth allowed\")\n\t}\n\tbody, err := json.Marshal(&opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tt := new(AccessToken)\n\tresp, err := c.getParsedResponse(\"POST\", fmt.Sprintf(\"/users/%s/tokens\", c.username), jsonHeader, bytes.NewReader(body), t)\n\treturn t, resp, err\n}\n\n\n\n\nfunc (c *Client) DeleteAccessToken(value interface{}) (*Response, error) ", "output": "{\n\tif len(c.username) == 0 {\n\t\treturn nil, fmt.Errorf(\"\\\"username\\\" not set: only BasicAuth allowed\")\n\t}\n\n\tvar token = \"\"\n\n\tswitch reflect.ValueOf(value).Kind() {\n\tcase reflect.Int64:\n\t\ttoken = fmt.Sprintf(\"%d\", value.(int64))\n\tcase reflect.String:\n\t\tif err := c.CheckServerVersionConstraint(\">= 1.13.0\"); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttoken = value.(string)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"only string and int64 supported\")\n\t}\n\n\t_, resp, err := c.getResponse(\"DELETE\", fmt.Sprintf(\"/users/%s/tokens/%s\", c.username, token), jsonHeader, nil)\n\treturn resp, err\n}"} {"input": "package category\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/vapi/tags\"\n)\n\ntype ls struct {\n\t*flags.ClientFlag\n\t*flags.OutputFlag\n}\n\nfunc init() {\n\tcli.Register(\"tags.category.ls\", &ls{})\n}\n\nfunc (cmd *ls) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.ClientFlag, ctx = flags.NewClientFlag(ctx)\n\tcmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)\n\tcmd.ClientFlag.Register(ctx, f)\n\tcmd.OutputFlag.Register(ctx, f)\n}\n\nfunc (cmd *ls) Process(ctx context.Context) error {\n\tif err := cmd.ClientFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn cmd.OutputFlag.Process(ctx)\n}\n\nfunc (cmd *ls) Description() string {\n\treturn `List all categories.\n\nExamples:\n govc tags.category.ls\n govc tags.category.ls -json | jq .`\n}\n\ntype lsResult []tags.Category\n\n\n\nfunc (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {\n\tc, err := cmd.RestClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tl, err := tags.NewManager(c).GetCategories(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn cmd.WriteResult(lsResult(l))\n}\n\nfunc (r lsResult) Write(w io.Writer) error ", "output": "{\n\tfor _, c := range r {\n\t\tfmt.Fprintln(w, c.Name)\n\t}\n\treturn nil\n}"} {"input": "package merkledag\n\nimport (\n\t\"context\"\n\n\tcid \"gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid\"\n\tipld \"gx/ipfs/QmR7TcHkR9nxkUorfi8XMTAMLUK7GiP64TWWBzY3aacc1o/go-ipld-format\"\n)\n\n\ntype ErrorService struct {\n\tErr error\n}\n\nvar _ ipld.DAGService = (*ErrorService)(nil)\n\n\nfunc (cs *ErrorService) Add(ctx context.Context, nd ipld.Node) error {\n\treturn cs.Err\n}\n\n\nfunc (cs *ErrorService) AddMany(ctx context.Context, nds []ipld.Node) error {\n\treturn cs.Err\n}\n\n\nfunc (cs *ErrorService) Get(ctx context.Context, c cid.Cid) (ipld.Node, error) {\n\treturn nil, cs.Err\n}\n\n\nfunc (cs *ErrorService) GetMany(ctx context.Context, cids []cid.Cid) <-chan *ipld.NodeOption {\n\tch := make(chan *ipld.NodeOption)\n\tclose(ch)\n\treturn ch\n}\n\n\n\n\n\nfunc (cs *ErrorService) RemoveMany(ctx context.Context, cids []cid.Cid) error {\n\treturn cs.Err\n}\n\nfunc (cs *ErrorService) Remove(ctx context.Context, c cid.Cid) error ", "output": "{\n\treturn cs.Err\n}"} {"input": "package v1\n\nimport (\n\tapi \"k8s.io/kubernetes/pkg/api\"\n\tregistered \"k8s.io/kubernetes/pkg/apimachinery/registered\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n\tserializer \"k8s.io/kubernetes/pkg/runtime/serializer\"\n)\n\ntype BatchInterface interface {\n\tGetRESTClient() *restclient.RESTClient\n\tJobsGetter\n}\n\n\ntype BatchClient struct {\n\t*restclient.RESTClient\n}\n\nfunc (c *BatchClient) Jobs(namespace string) JobInterface {\n\treturn newJobs(c, namespace)\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *restclient.Config) *BatchClient {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c *restclient.RESTClient) *BatchClient {\n\treturn &BatchClient{c}\n}\n\nfunc setConfigDefaults(config *restclient.Config) error {\n\tg, err := registered.Group(\"batch\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.APIPath = \"/apis\"\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = restclient.DefaultKubernetesUserAgent()\n\t}\n\tcopyGroupVersion := g.GroupVersion\n\tconfig.GroupVersion = ©GroupVersion\n\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: api.Codecs}\n\n\tif config.QPS == 0 {\n\t\tconfig.QPS = 5\n\t}\n\tif config.Burst == 0 {\n\t\tconfig.Burst = 10\n\t}\n\treturn nil\n}\n\n\n\nfunc (c *BatchClient) GetRESTClient() *restclient.RESTClient {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.RESTClient\n}\n\nfunc NewForConfig(c *restclient.Config) (*BatchClient, error) ", "output": "{\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := restclient.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BatchClient{client}, nil\n}"} {"input": "package metha\n\nimport (\n\t\"encoding/base64\"\n\t\"io/ioutil\"\n\t\"strings\"\n)\n\n\ntype Repository struct {\n\tBaseURL string\n}\n\n\nfunc (r Repository) Formats() ([]MetadataFormat, error) {\n\tvar formats []MetadataFormat\n\tvar token string\n\tfor {\n\t\treq := Request{BaseURL: r.BaseURL, Verb: \"ListMetadataFormats\", ResumptionToken: token}\n\t\tresp, err := Do(&req)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tformats = append(formats, resp.ListMetadataFormats.MetadataFormat...)\n\t\tif !resp.HasResumptionToken() {\n\t\t\tbreak\n\t\t}\n\t\ttoken = resp.GetResumptionToken()\n\t}\n\treturn formats, nil\n}\n\n\nfunc (r Repository) Sets() ([]Set, error) {\n\tvar sets []Set\n\tvar token string\n\tfor {\n\t\treq := Request{BaseURL: r.BaseURL, Verb: \"ListSets\", ResumptionToken: token}\n\t\tresp, err := Do(&req)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsets = append(sets, resp.ListSets.Set...)\n\t\tif !resp.HasResumptionToken() {\n\t\t\tbreak\n\t\t}\n\t\ttoken = resp.GetResumptionToken()\n\t}\n\treturn sets, nil\n}\n\n\n\n\n\nfunc FindRepositoriesByString(s string) (urls []string, err error) ", "output": "{\n\tfiles, err := ioutil.ReadDir(BaseDir)\n\tif err != nil {\n\t\treturn urls, err\n\t}\n\tfor _, file := range files {\n\t\tb, err := base64.RawURLEncoding.DecodeString(file.Name())\n\t\tif err != nil {\n\t\t\treturn urls, err\n\t\t}\n\t\tparts := strings.SplitN(string(b), \"#\", 3)\n\t\tif len(parts) < 3 {\n\t\t\tcontinue\n\t\t}\n\t\tbaseURL := parts[2]\n\t\tif strings.Contains(baseURL, s) {\n\t\t\turls = append(urls, baseURL)\n\t\t}\n\t}\n\treturn urls, nil\n}"} {"input": "package segment\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/checkr/flagr/swagger_gen/models\"\n)\n\n\nconst DeleteSegmentOKCode int = 200\n\n\ntype DeleteSegmentOK struct {\n}\n\n\nfunc NewDeleteSegmentOK() *DeleteSegmentOK {\n\n\treturn &DeleteSegmentOK{}\n}\n\n\nfunc (o *DeleteSegmentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(200)\n}\n\n\ntype DeleteSegmentDefault struct {\n\t_statusCode int\n\n\tPayload *models.Error `json:\"body,omitempty\"`\n}\n\n\nfunc NewDeleteSegmentDefault(code int) *DeleteSegmentDefault {\n\tif code <= 0 {\n\t\tcode = 500\n\t}\n\n\treturn &DeleteSegmentDefault{\n\t\t_statusCode: code,\n\t}\n}\n\n\nfunc (o *DeleteSegmentDefault) WithStatusCode(code int) *DeleteSegmentDefault {\n\to._statusCode = code\n\treturn o\n}\n\n\n\n\n\nfunc (o *DeleteSegmentDefault) WithPayload(payload *models.Error) *DeleteSegmentDefault {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *DeleteSegmentDefault) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}\n\n\nfunc (o *DeleteSegmentDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(o._statusCode)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\nfunc (o *DeleteSegmentDefault) SetStatusCode(code int) ", "output": "{\n\to._statusCode = code\n}"} {"input": "package grpclog \n\nimport \"os\"\n\nvar logger = newLoggerV2()\n\n\nfunc V(l int) bool {\n\treturn logger.V(l)\n}\n\n\nfunc Info(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\nfunc Infof(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\nfunc Infoln(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\n\nfunc Warning(args ...interface{}) {\n\tlogger.Warning(args...)\n}\n\n\n\n\n\nfunc Warningln(args ...interface{}) {\n\tlogger.Warningln(args...)\n}\n\n\nfunc Error(args ...interface{}) {\n\tlogger.Error(args...)\n}\n\n\nfunc Errorf(format string, args ...interface{}) {\n\tlogger.Errorf(format, args...)\n}\n\n\nfunc Errorln(args ...interface{}) {\n\tlogger.Errorln(args...)\n}\n\n\n\nfunc Fatal(args ...interface{}) {\n\tlogger.Fatal(args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalf(format string, args ...interface{}) {\n\tlogger.Fatalf(format, args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalln(args ...interface{}) {\n\tlogger.Fatalln(args...)\n\tos.Exit(1)\n}\n\n\n\n\nfunc Print(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\n\n\nfunc Printf(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\n\n\nfunc Println(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\nfunc Warningf(format string, args ...interface{}) ", "output": "{\n\tlogger.Warningf(format, args...)\n}"} {"input": "package csv\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n\n\t\"gopkg.in/Clever/optimus.v3\"\n)\n\n\n\n\nfunc New(out io.Writer) optimus.Sink ", "output": "{\n\treturn func(source optimus.Table) error {\n\t\tdefer source.Stop()\n\t\tfor row := range source.Rows() {\n\t\t\tobj, err := json.Marshal(row)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tobj = append(obj, byte('\\n'))\n\t\t\tif _, err := out.Write(obj); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif source.Err() != nil {\n\t\t\treturn source.Err()\n\t\t}\n\t\treturn nil\n\t}\n}"} {"input": "package iso20022\n\n\ntype PaymentInstrument21Choice struct {\n\n\tCreditTransferDetails *CreditTransfer8 `xml:\"CdtTrfDtls\"`\n\n\tChequeDetails *Cheque9 `xml:\"ChqDtls\"`\n\n\tBankersDraftDetails *Cheque9 `xml:\"BkrsDrftDtls\"`\n\n\tCashAccountDetails *InvestmentAccount60 `xml:\"CshAcctDtls\"`\n}\n\nfunc (p *PaymentInstrument21Choice) AddCreditTransferDetails() *CreditTransfer8 {\n\tp.CreditTransferDetails = new(CreditTransfer8)\n\treturn p.CreditTransferDetails\n}\n\nfunc (p *PaymentInstrument21Choice) AddChequeDetails() *Cheque9 {\n\tp.ChequeDetails = new(Cheque9)\n\treturn p.ChequeDetails\n}\n\n\n\nfunc (p *PaymentInstrument21Choice) AddCashAccountDetails() *InvestmentAccount60 {\n\tp.CashAccountDetails = new(InvestmentAccount60)\n\treturn p.CashAccountDetails\n}\n\nfunc (p *PaymentInstrument21Choice) AddBankersDraftDetails() *Cheque9 ", "output": "{\n\tp.BankersDraftDetails = new(Cheque9)\n\treturn p.BankersDraftDetails\n}"} {"input": "package handlers\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/openshift/origin/pkg/auth/api\"\n)\n\ntype AuthenticationHandler interface {\n\tAuthenticationNeeded(w http.ResponseWriter, req *http.Request)\n\tAuthenticationError(err error, w http.ResponseWriter, req *http.Request)\n}\n\ntype AuthenticationSuccessHandler interface {\n\tAuthenticationSucceeded(user api.UserInfo, state string, w http.ResponseWriter, req *http.Request) error\n}\n\ntype AuthenticationErrorHandler interface {\n\tAuthenticationError(err error, w http.ResponseWriter, req *http.Request)\n}\n\ntype GrantChecker interface {\n\tHasAuthorizedClient(client api.Client, user api.UserInfo, grant *api.Grant) (bool, error)\n}\n\ntype GrantHandler interface {\n\tGrantNeeded(client api.Client, user api.UserInfo, grant *api.Grant, w http.ResponseWriter, req *http.Request)\n\tGrantError(err error, w http.ResponseWriter, req *http.Request)\n}\n\n\n\ntype AuthenticationSuccessHandlers []AuthenticationSuccessHandler\n\n\n\nfunc (all AuthenticationSuccessHandlers) AuthenticationSucceeded(user api.UserInfo, state string, w http.ResponseWriter, req *http.Request) error ", "output": "{\n\tfor _, h := range all {\n\t\tif err := h.AuthenticationSucceeded(user, state, w, req); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package kubernetes\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/weaveworks/scope/report\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/unversioned\"\n\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n\t\"k8s.io/kubernetes/pkg/labels\"\n)\n\n\nconst (\n\tUpdatedReplicas = \"kubernetes_updated_replicas\"\n\tAvailableReplicas = \"kubernetes_available_replicas\"\n\tUnavailableReplicas = \"kubernetes_unavailable_replicas\"\n\tStrategy = \"kubernetes_strategy\"\n)\n\n\ntype Deployment interface {\n\tMeta\n\tSelector() labels.Selector\n\tGetNode(probeID string) report.Node\n}\n\ntype deployment struct {\n\t*extensions.Deployment\n\tMeta\n\tNode *api.Node\n}\n\n\n\n\nfunc (d *deployment) Selector() labels.Selector {\n\tselector, err := unversioned.LabelSelectorAsSelector(d.Spec.Selector)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn selector\n}\n\nfunc (d *deployment) GetNode(probeID string) report.Node {\n\treturn d.MetaNode(report.MakeDeploymentNodeID(d.UID())).WithLatests(map[string]string{\n\t\tObservedGeneration: fmt.Sprint(d.Status.ObservedGeneration),\n\t\tDesiredReplicas: fmt.Sprint(d.Spec.Replicas),\n\t\tReplicas: fmt.Sprint(d.Status.Replicas),\n\t\tUpdatedReplicas: fmt.Sprint(d.Status.UpdatedReplicas),\n\t\tAvailableReplicas: fmt.Sprint(d.Status.AvailableReplicas),\n\t\tUnavailableReplicas: fmt.Sprint(d.Status.UnavailableReplicas),\n\t\tStrategy: string(d.Spec.Strategy.Type),\n\t\treport.ControlProbeID: probeID,\n\t}).WithLatestActiveControls(ScaleUp, ScaleDown)\n}\n\nfunc NewDeployment(d *extensions.Deployment) Deployment ", "output": "{\n\treturn &deployment{Deployment: d, Meta: meta{d.ObjectMeta}}\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc main() {\n\tsc := bufio.NewScanner(os.Stdin)\n\tsc.Split(bufio.ScanWords)\n\tn := nextInt(sc)\n\ta := nextInt(sc)\n\tb := nextInt(sc)\n\n\tanswer := 0\n\tfor i := 1; i <= n; i++ {\n\t\tsum := 0\n\t\tfor _, s := range fmt.Sprintf(\"%d\", i) {\n\t\t\tx, _ := strconv.Atoi(string(s))\n\t\t\tsum = sum + x\n\t\t}\n\t\tif a <= sum && sum <= b {\n\t\t\tanswer = answer + i\n\t\t}\n\t}\n\n\tfmt.Println(answer)\n}\n\n\n\n\n\nfunc nextNumber(sc *bufio.Scanner) float64 {\n\tsc.Scan()\n\tf, err := strconv.ParseFloat(sc.Text(), 32)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}\n\nfunc nextInt(sc *bufio.Scanner) int {\n\tsc.Scan()\n\tn, err := strconv.Atoi(sc.Text())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn n\n}\n\nfunc printArray(xs []int) {\n\tfmt.Println(strings.Trim(fmt.Sprint(xs), \"[]\"))\n}\n\nfunc debugPrintf(format string, a ...interface{}) {\n\tfmt.Fprintf(os.Stderr, format, a...)\n}\n\nfunc nextString(sc *bufio.Scanner) string ", "output": "{\n\tsc.Scan()\n\treturn sc.Text()\n}"} {"input": "package result\n\ntype Classic struct {\n\tid int\n\tfitness float64\n\terr error\n\tstop bool\n}\n\nfunc New(id int, fitness float64, err error, stop bool) Classic {\n\treturn Classic{id, fitness, err, stop}\n}\n\n\nfunc (r Classic) ID() int { return r.id }\n\n\nfunc (r Classic) Fitness() float64 { return r.fitness }\n\n\n\n\n\nfunc (r Classic) Stop() bool { return r.stop }\n\nfunc (r Classic) Err() error ", "output": "{ return r.err }"} {"input": "package messages\n\nimport (\n\t\"bytes\"\n\t\"message-delivery-system/src/utils\"\n)\n\n\ntype ListResponse struct {\n\tList []uint64\n\tReceiver uint64\n}\n\n\nfunc NewListResponse(data []byte) ListResponse {\n\tbuf := bytes.NewReader(data)\n\tlist, _ := utils.ByteArrayToUint64List(buf, data)\n\treturn ListResponse{List:list}\n}\n\n\nfunc (l ListResponse) GetMessageType() MessageType {\n\treturn ListResponseMessage\n}\n\n\nfunc (l ListResponse) GetData() []byte {\n\tbuf := new(bytes.Buffer)\n\tdata, _ := utils.Uint64ListToByteArray(buf, l.List)\n\treturn data\n}\n\n\n\n\nfunc (l ListResponse) GetReceiverIds() []uint64 ", "output": "{\n\tvar receivers []uint64\n\treturn append(receivers, l.Receiver)\n}"} {"input": "package core\n\nimport (\n\t\"net\";\n\t\"os\";\n\t\"log\";\n)\n\ntype acceptFunc\tfunc(net.Conn)\ntype errorFunc\tfunc(os.Error)\n\n\ntype listenConn struct {\n\tlisten\tnet.Listener;\n\taccept\tacceptFunc;\n\terror\terrorFunc;\n}\n\nfunc newListenConn(listen net.Listener, accept acceptFunc, error errorFunc) *listenConn {\n\tl := &listenConn{listen, accept, error};\n\tgo l.run();\n\treturn l;\n}\n\nfunc (l *listenConn) run() {\n\tlog.Stderrf(\"listening on %s\\n\", l.listen.Addr());\n\tfor {\n\t\tconn, err := l.listen.Accept();\n\t\tif err != nil {\n\t\t\tlog.Stderrf(\"accept failed: %s\\n\", err);\n\t\t\tl.listen.Close();\n\t\t\tif l.error != nil {\n\t\t\t\tl.error(err);\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tl.accept(conn);\n\t}\n}\n\n\n\nfunc (l *listenConn) Addr() net.Addr ", "output": "{\n\treturn l.listen.Addr()\n}"} {"input": "package pathmgr\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\n\n\n\n\n\n\n\n\n\ntype SyncPaths struct {\n\tvalue atomic.Value\n\tmutex sync.Mutex\n}\n\n\n\ntype SyncPathsData struct {\n\tAPS AppPathSet\n\tModifyTime time.Time\n\tRefreshTime time.Time\n}\n\n\n\nfunc NewSyncPaths() *SyncPaths {\n\tsp := &SyncPaths{}\n\tnow := time.Now()\n\tsp.value.Store(\n\t\t&SyncPathsData{\n\t\t\tAPS: make(AppPathSet),\n\t\t\tModifyTime: now,\n\t\t\tRefreshTime: now,\n\t\t},\n\t)\n\treturn sp\n}\n\n\n\n\n\n\nfunc (sp *SyncPaths) update(newAPS AppPathSet) {\n\tsp.mutex.Lock()\n\tdefer sp.mutex.Unlock()\n\tvalue := sp.value.Load().(*SyncPathsData)\n\tvalue.RefreshTime = time.Now()\n\ttoAdd := setSubtract(newAPS, value.APS)\n\ttoRemove := setSubtract(value.APS, newAPS)\n\tif len(toAdd) > 0 || len(toRemove) > 0 {\n\t\tvalue.ModifyTime = value.RefreshTime\n\t}\n\tvalue.APS = newAPS\n\tsp.value.Store(value)\n}\n\n\nfunc (sp *SyncPaths) Load() *SyncPathsData {\n\treturn sp.value.Load().(*SyncPathsData)\n}\n\n\n\nfunc setSubtract(x, y AppPathSet) AppPathSet ", "output": "{\n\tresult := make(AppPathSet)\n\tfor _, ap := range x {\n\t\tif _, ok := y[ap.Key()]; !ok {\n\t\t\tresult.Add(ap.Entry)\n\t\t}\n\t}\n\treturn result\n}"} {"input": "package lemon\n\nimport (\n\t\"errors\"\n\t\"testing\"\n)\n\n\n\ntype errOption struct {\n\terr error\n}\n\nfunc (o errOption) apply(e *Engine) error {\n\treturn o.err\n}\n\nfunc OptionWithError(runtime *TestRuntime) {\n\n\texpected := errors.New(\"cannot update engine with foobar\")\n\toption := errOption{\n\t\terr: expected,\n\t}\n\n\tengine, err := New(runtime.Context(), option)\n\n\tif err == nil {\n\t\truntime.Error(\"An error was expected\")\n\t}\n\n\tif err != expected {\n\t\truntime.Error(\"Unexpected error: %s\", err)\n\t}\n\n\tif engine != nil {\n\t\truntime.Error(\"Engine should be undefined\")\n\t}\n\n\truntime.Log(\"We received expected error: %s.\", err)\n\n}\n\nfunc TestOption(t *testing.T) ", "output": "{\n\ttests := map[string]TestHandler{\n\t\t\"WithError\": OptionWithError,\n\t}\n\n\tfor name, handler := range tests {\n\t\tt.Run(name, Setup(handler))\n\t}\n}"} {"input": "package suite_init\n\ntype SuiteData struct {\n\t*StubsData\n\t*SynchronizedSuiteCallbacksData\n\t*WerfBinaryData\n\t*ProjectNameData\n\t*K8sDockerRegistryData\n\t*TmpDirData\n\t*ContainerRegistryPerImplementationData\n}\n\nfunc (data *SuiteData) SetupStubs(setupData *StubsData) bool {\n\tdata.StubsData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupSynchronizedSuiteCallbacks(setupData *SynchronizedSuiteCallbacksData) bool {\n\tdata.SynchronizedSuiteCallbacksData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupWerfBinary(setupData *WerfBinaryData) bool {\n\tdata.WerfBinaryData = setupData\n\treturn true\n}\n\n\n\nfunc (data *SuiteData) SetupK8sDockerRegistry(setupData *K8sDockerRegistryData) bool {\n\tdata.K8sDockerRegistryData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupTmp(setupData *TmpDirData) bool {\n\tdata.TmpDirData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupContainerRegistryPerImplementation(setupData *ContainerRegistryPerImplementationData) bool {\n\tdata.ContainerRegistryPerImplementationData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupProjectName(setupData *ProjectNameData) bool ", "output": "{\n\tdata.ProjectNameData = setupData\n\treturn true\n}"} {"input": "package in\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/blevesearch/bleve/analysis\"\n\t\"github.com/blevesearch/bleve/registry\"\n)\n\nconst NormalizeName = \"normalize_in\"\n\ntype IndicNormalizeFilter struct {\n}\n\nfunc NewIndicNormalizeFilter() *IndicNormalizeFilter {\n\treturn &IndicNormalizeFilter{}\n}\n\nfunc (s *IndicNormalizeFilter) Filter(input analysis.TokenStream) analysis.TokenStream {\n\tfor _, token := range input {\n\t\trunes := bytes.Runes(token.Term)\n\t\trunes = normalize(runes)\n\t\ttoken.Term = analysis.BuildTermFromRunes(runes)\n\t}\n\treturn input\n}\n\n\n\nfunc init() {\n\tregistry.RegisterTokenFilter(NormalizeName, NormalizerFilterConstructor)\n}\n\nfunc NormalizerFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) ", "output": "{\n\treturn NewIndicNormalizeFilter(), nil\n}"} {"input": "package httpgrpc\n\nimport (\n\t\"fmt\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/golang/protobuf/ptypes\"\n\t\"github.com/golang/protobuf/ptypes/any\"\n\tspb \"google.golang.org/genproto/googleapis/rpc/status\"\n\t\"google.golang.org/grpc/status\"\n)\n\n\n\n\nfunc Errorf(code int, tmpl string, args ...interface{}) error {\n\treturn ErrorFromHTTPResponse(&HTTPResponse{\n\t\tCode: int32(code),\n\t\tBody: []byte(fmt.Sprintf(tmpl, args...)),\n\t})\n}\n\n\nfunc ErrorFromHTTPResponse(resp *HTTPResponse) error {\n\ta, err := ptypes.MarshalAny(resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn status.ErrorProto(&spb.Status{\n\t\tCode: resp.Code,\n\t\tMessage: string(resp.Body),\n\t\tDetails: []*any.Any{a},\n\t})\n}\n\n\n\n\nfunc HTTPResponseFromError(err error) (*HTTPResponse, bool) ", "output": "{\n\ts, ok := status.FromError(err)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tstatus := s.Proto()\n\tif len(status.Details) != 1 {\n\t\treturn nil, false\n\t}\n\n\tvar resp HTTPResponse\n\tif err := ptypes.UnmarshalAny(status.Details[0], &resp); err != nil {\n\t\tlog.Errorf(\"Got error containing non-response: %v\", err)\n\t\treturn nil, false\n\t}\n\n\treturn &resp, true\n}"} {"input": "package common\n\nimport \"math/big\"\n\ntype _N_ [_S_]byte\n\nfunc BytesTo_N_(b []byte) _N_ {\n\tvar h _N_\n\th.SetBytes(b)\n\treturn h\n}\nfunc StringTo_N_(s string) _N_ { return BytesTo_N_([]byte(s)) }\nfunc BigTo_N_(b *big.Int) _N_ { return BytesTo_N_(b.Bytes()) }\nfunc HexTo_N_(s string) _N_ { return BytesTo_N_(FromHex(s)) }\n\n\n\n\nfunc (h _N_) Str() string { return string(h[:]) }\nfunc (h _N_) Bytes() []byte { return h[:] }\nfunc (h _N_) Big() *big.Int { return Bytes2Big(h[:]) }\nfunc (h _N_) Hex() string { return \"0x\" + Bytes2Hex(h[:]) }\n\n\nfunc (h *_N_) SetBytes(b []byte) {\n\tif len(b) > len(h) {\n\t\tb = b[len(b)-_S_:]\n\t}\n\n\tfor i := len(b) - 1; i >= 0; i-- {\n\t\th[_S_-len(b)+i] = b[i]\n\t}\n}\n\n\n\n\n\nfunc (h *_N_) Set(other _N_) {\n\tfor i, v := range other {\n\t\th[i] = v\n\t}\n}\n\nfunc (h *_N_) SetString(s string) ", "output": "{ h.SetBytes([]byte(s)) }"} {"input": "package kcl\n\nimport \"fmt\"\n\ntype message struct {\n\tAction string `json:\"action\"`\n\tShardID *string `json:\"shardId,omitempty\"`\n\tRecords []*Record `json:\"records,omitempty\"`\n\tCheckpoint *string `json:\"checkpoint,omitempty\"`\n\tError *string `json:\"error,omitempty\"`\n\tReason *string `json:\"reason,omitempty\"`\n}\n\ntype messageHandler struct {\n\tih *ioHandler\n\trp RecordProcessor\n\tcp *CheckPointer\n}\n\n\n\nfunc (mh *messageHandler) doAction() error ", "output": "{\n\n\tmsg, err := mh.ih.receiveMessage()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch msg.Action {\n\tcase \"initialize\":\n\t\terr = mh.rp.Initialize(*msg.ShardID)\n\tcase \"processRecords\":\n\t\terr = mh.rp.ProcessRecords(msg.Records, mh.cp)\n\tcase \"shutdown\":\n\t\tif msg.Reason == nil || *msg.Reason == \"ZOMBIE\" {\n\t\t\tmh.cp.checkPointAllowed = false\n\t\t}\n\t\terr = mh.rp.Shutdown(*msg.Reason, mh.cp)\n\tdefault:\n\t\terr = fmt.Errorf(\"invalid action: %s\", msg.Action)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn mh.ih.sendStatus(msg.Action)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/aarondl/dbm/config\"\n)\n\n\n\nfunc trackdb(args []string) {\n\tengine, err := NewEngine(config.Current)\n\tif err != nil {\n\t\texitLn(\"Error getting handle to db:\", err)\n\t}\n\ttrackdbHelper(args, engine)\n}\n\nfunc trackdbHelper(args []string, engine SqlEngine) {\n\tif err := engine.Open(); err != nil {\n\t\texitLn(\"Error opening to db:\", err)\n\t}\n\tdefer engine.Close()\n\tif err := engine.CreateMigrationsTable(); err != nil {\n\t\texitLn(\"Error creating migrations table:\", err)\n\t}\n}\n\nfunc dropDatabase(args []string) {\n\tengine, err := NewEngine(config.Current)\n\tif err != nil {\n\t\texitLn(\"Error getting handle to db:\", err)\n\t}\n\tif err = engine.DropDB(); err != nil {\n\t\texitLn(\"Error dropping db:\", err)\n\t}\n}\n\nfunc createDatabase(args []string) ", "output": "{\n\tengine, err := NewEngine(config.Current)\n\tif err != nil {\n\t\texitLn(\"Error getting handle to db:\", err)\n\t}\n\tif err = engine.CreateDB(); err != nil {\n\t\texitLn(\"Error creating db:\", err)\n\t}\n\ttrackdbHelper(args, engine)\n}"} {"input": "package paypal\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nconst format = \"2006-01-02T15:04:05Z\"\n\n\ntype Filter struct {\n\tfields []fmt.Stringer\n}\n\n\n\n\ntype TextField struct {\n\tname string\n\tIs string\n}\n\nfunc (d TextField) String() string {\n\treturn fmt.Sprintf(\"%s=%s\", d.name, d.Is)\n}\n\n\ntype TimeField struct {\n\tname string\n\tIs time.Time\n}\n\n\nfunc (d TimeField) String() string {\n\treturn fmt.Sprintf(\"%s=%s\", d.name, d.Is.UTC().Format(format))\n}\n\n\nfunc (s *Filter) AddTextField(field string) *TextField {\n\tf := &TextField{name: field}\n\ts.fields = append(s.fields, f)\n\treturn f\n}\n\n\nfunc (s *Filter) AddTimeField(field string) *TimeField {\n\tf := &TimeField{name: field}\n\ts.fields = append(s.fields, f)\n\treturn f\n}\n\nfunc (s *Filter) String() string ", "output": "{\n\tvar filter string\n\tfor i, f := range s.fields {\n\t\tif i == 0 {\n\t\t\tfilter = \"?\" + f.String()\n\t\t} else {\n\t\t\tfilter = filter + \"&\" + f.String()\n\t\t}\n\t}\n\n\treturn filter\n}"} {"input": "package gftest\n\nimport (\n \"errors\"\n \"reflect\"\n \"encoding/json\"\n)\n\nfunc (req *Request) Debug(msg string) { req.t.Log(req.FullPath() + \": %v\", msg) }\n\nfunc (req *Request) NewError(msg string) error {\n\n\terr := errors.New(req.FullPath() + \": \" + msg)\n\treturn err\n}\n\nfunc (req *Request) Error(e error) { req.t.Log(e.Error()) }\n\n\n\nfunc (req *Request) DebugJSON(i interface{}) {\n\tb, err := json.Marshal(i); if err != nil { req.Error(err); return }\n\treq.Debug(string(b))\n}\n\nfunc (req *Request) Reflect(e interface{}) ", "output": "{\n\tmsg := \"REFLECT VALUE IS NIL\"\n\tif e != nil {\n\t\tmsg = \"REFLECT VALUE IS \"+reflect.TypeOf(e).String()\n\t}\n\treq.NewError(msg)\n}"} {"input": "package instructions\n\nimport \"github.com/zxh0/jvm.go/jvmgo/jvm/rtda\"\n\n\ntype astore struct{ Index8Instruction }\n\nfunc (self *astore) Execute(frame *rtda.Frame) {\n\t_astore(frame, uint(self.index))\n}\n\ntype astore_0 struct{ NoOperandsInstruction }\n\nfunc (self *astore_0) Execute(frame *rtda.Frame) {\n\t_astore(frame, 0)\n}\n\ntype astore_1 struct{ NoOperandsInstruction }\n\nfunc (self *astore_1) Execute(frame *rtda.Frame) {\n\t_astore(frame, 1)\n}\n\ntype astore_2 struct{ NoOperandsInstruction }\n\n\n\ntype astore_3 struct{ NoOperandsInstruction }\n\nfunc (self *astore_3) Execute(frame *rtda.Frame) {\n\t_astore(frame, 3)\n}\n\nfunc _astore(frame *rtda.Frame, index uint) {\n\tref := frame.OperandStack().PopRef()\n\tframe.LocalVars().SetRef(index, ref)\n}\n\nfunc (self *astore_2) Execute(frame *rtda.Frame) ", "output": "{\n\t_astore(frame, 2)\n}"} {"input": "package osutil\n\nimport (\n\t\"syscall\"\n\t\"time\"\n)\n\n\n\nfunc timeToTimeval32(t time.Time) *syscall.Timeval {\n\treturn &syscall.Timeval{\n\t\tSec: int32(t.Unix()),\n\t\tUsec: int32(t.Nanosecond() / 1000),\n\t}\n}\n\nfunc init() ", "output": "{\n\ttimeToTimeval = timeToTimeval32\n}"} {"input": "package homedir\n\nimport (\n\t\"errors\"\n\t\"os\"\n)\n\n\n\n\nfunc dir() (string, error) ", "output": "{\n\tdrive := os.Getenv(\"HOMEDRIVE\")\n\tpath := os.Getenv(\"HOMEPATH\")\n\thome := drive + path\n\tif drive == \"\" || path == \"\" {\n\t\thome = os.Getenv(\"USERPROFILE\")\n\t}\n\tif home == \"\" {\n\t\treturn \"\", errors.New(\"HOMEDRIVE, HOMEPATH, and USERPROFILE are blank\")\n\t}\n\n\treturn home, nil\n}"} {"input": "package git\n\nimport \"testing\"\n\n\n\nfunc TestTreeEntryById(t *testing.T) ", "output": "{\n\trepo := createTestRepo(t)\n\tdefer cleanupTestRepo(t, repo)\n\n\t_, treeID := seedTestRepo(t, repo)\n\n\ttree, err := repo.LookupTree(treeID)\n\tcheckFatal(t, err)\n\n\tid, err := NewOid(\"257cc5642cb1a054f08cc83f2d943e56fd3ebe99\")\n\tcheckFatal(t, err)\n\n\tentry := tree.EntryById(id)\n\n\tif entry == nil {\n\t\tt.Fatalf(\"entry id %v was not found\", id)\n\t}\n}"} {"input": "package config\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"text/template\"\n)\n\nvar (\n\tglbEnvs map[string]string\n)\n\nfunc init() {\n\tglbEnvs = make(map[string]string)\n\tenvs := os.Environ()\n\tfor _, env := range envs {\n\t\tkv := strings.Split(env, \"=\")\n\t\tif len(kv) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tglbEnvs[kv[0]] = kv[1]\n\t}\n}\n\ntype Values struct {\n\tEnvs map[string]string \n}\n\nfunc GetValues() *Values {\n\treturn &Values{\n\t\tEnvs: glbEnvs,\n\t}\n}\n\nfunc RenderContent(in []byte) (out []byte, err error) {\n\ttmpl, errRet := template.New(\"frp\").Parse(string(in))\n\tif errRet != nil {\n\t\terr = errRet\n\t\treturn\n\t}\n\n\tbuffer := bytes.NewBufferString(\"\")\n\tv := GetValues()\n\terr = tmpl.Execute(buffer, v)\n\tif err != nil {\n\t\treturn\n\t}\n\tout = buffer.Bytes()\n\treturn\n}\n\n\n\nfunc GetRenderedConfFromFile(path string) (out []byte, err error) ", "output": "{\n\tvar b []byte\n\tb, err = ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tout, err = RenderContent(b)\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"testing\"\n)\n\nvar artifacts = []struct {\n\tin string\n\tout string\n}{\n\t{\"fixtures/virtualbox-ovf.json\", \"packer_virtualbox-ovf_virtualbox.vhd\"},\n\t{\"fixtures/virtualbox-ova.json\", \"packer_virtualbox-ova_virtualbox.vhd\"},\n}\n\n\nfunc init() {\n\tcmd := exec.Command(\"packer\", \"build\", \"--force\", \"fixtures/virtualbox-iso.json\")\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\n\nfunc TestIntegration(t *testing.T) ", "output": "{\n\tif err := os.Chdir(\"test\"); err != nil {\n\t\tt.Error(err)\n\t}\n\tfor _, tt := range artifacts {\n\t\tcmd := exec.Command(\"packer\", \"build\", \"--force\", tt.in)\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t\terr := cmd.Run()\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif _, err := os.Stat(tt.out); os.IsNotExist(err) {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\n\n\nfunc TestFormatName(t *testing.T) {\n\ttestCases := []struct {\n\t\tname string\n\t\texpect string\n\t}{\n\t\t{\"foobar\", \"foobar\"},\n\t\t{\"foo-bar\", \"foo-bar\"},\n\t\t{\"foo.bar\", \"foo-bar\"},\n\t\t{\"Foo.Bar\", \"foo-bar\"},\n\t\t{\"go.micro.foo.bar\", \"go-micro-foo-bar\"},\n\t}\n\n\tfor _, test := range testCases {\n\t\tv := Format(test.name)\n\t\tif v != test.expect {\n\t\t\tt.Fatalf(\"Expected name %s for %s got: %s\", test.expect, test.name, v)\n\t\t}\n\t}\n}\n\nfunc TestTemplates(t *testing.T) ", "output": "{\n\tname := \"foo\"\n\tversion := \"123\"\n\ttyp := \"service\"\n\tnamespace := \"default\"\n\n\ts := NewService(name, version, typ, namespace)\n\tbs := new(bytes.Buffer)\n\tif err := renderTemplate(templates[\"service\"], bs, s); err != nil {\n\t\tt.Errorf(\"Failed to render kubernetes service: %v\", err)\n\t}\n\n\td := NewDeployment(name, version, typ, namespace)\n\tbd := new(bytes.Buffer)\n\tif err := renderTemplate(templates[\"deployment\"], bd, d); err != nil {\n\t\tt.Errorf(\"Failed to render kubernetes deployment: %v\", err)\n\t}\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n)\n\n\n\n\nfunc MakeName(name, version string) string {\n\treturn fmt.Sprintf(\"%s/v%s/%s/%s\", name, version, runtime.GOOS, runtime.Version())\n}\n\nfunc FileExist(filePath string) bool {\n\t_, err := os.Stat(filePath)\n\tif err != nil && os.IsNotExist(err) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\n\nfunc AbsolutePath(Datadir string, filename string) string ", "output": "{\n\tif filepath.IsAbs(filename) {\n\t\treturn filename\n\t}\n\treturn filepath.Join(Datadir, filename)\n}"} {"input": "package helpers\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n)\n\n\n\nfunc ReadFixtureBytes(name string) []byte {\n\tpath := GetFixturePath(name)\n\tcontents, err := ioutil.ReadFile(path)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn contents\n}\n\nfunc ReadFixtureString(name string) string {\n\treturn string(ReadFixtureBytes(name))\n}\n\nfunc GetFixturePath(name string) string ", "output": "{\n\t_, filename, _, _ := runtime.Caller(0)\n\n\tfixturePath := path.Join(path.Dir(filename), \"..\", \"fixtures\", name)\n\n\t_, err := os.Stat(fixturePath)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn fixturePath\n}"} {"input": "package stripe\n\nimport \"encoding/json\"\n\n\n\ntype PackageDimensions struct {\n\tHeight float64 `json:\"height\"`\n\tLength float64 `json:\"length\"`\n\tWidth float64 `json:\"width\"`\n\tWeight float64 `json:\"weight\"`\n}\n\n\n\n\n\ntype ProductParams struct {\n\tParams\n\tID string\n\tActive *bool\n\tName string\n\tCaption string\n\tDesc string\n\tAttrs []string\n\tImages []string\n\tURL string\n\tShippable *bool\n\tPackageDimensions *PackageDimensions\n}\n\n\n\ntype Product struct {\n\tID string `json:\"id\"`\n\tCreated int64 `json:\"created\"`\n\tUpdated int64 `json:\"updated\"`\n\tLive bool `json:\"livemode\"`\n\tActive bool `json:\"active\"`\n\tName string `json:\"name\"`\n\tCaption string `json:\"caption\"`\n\tDesc string `json:\"description\"`\n\tAttrs []string `json:\"attributes\"`\n\tShippable bool `json:\"shippable\"`\n\tPackageDimensions *PackageDimensions `json:\"package_dimensions\"`\n\tImages []string `json:\"images\"`\n\tMeta map[string]string `json:\"metadata\"`\n\tURL string `json:\"url\"`\n\tSkus *SKUList `json:\"skus\"`\n}\n\n\n\n\ntype ProductListParams struct {\n\tListParams\n\tActive *bool\n\tIDs []string\n\tShippable *bool\n\tURL string\n}\n\n\n\n\n\n\nfunc (p *Product) UnmarshalJSON(data []byte) error ", "output": "{\n\ttype product Product\n\tvar pr product\n\terr := json.Unmarshal(data, &pr)\n\tif err == nil {\n\t\t*p = Product(pr)\n\t} else {\n\t\tp.ID = string(data[1 : len(data)-1])\n\t}\n\n\treturn nil\n}"} {"input": "package logutil\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/coreos/pkg/capnslog\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n)\n\nvar DefaultLogLevel = \"info\"\n\n\nfunc ConvertToZapLevel(lvl string) zapcore.Level {\n\tswitch lvl {\n\tcase \"debug\":\n\t\treturn zap.DebugLevel\n\tcase \"info\":\n\t\treturn zap.InfoLevel\n\tcase \"warn\":\n\t\treturn zap.WarnLevel\n\tcase \"error\":\n\t\treturn zap.ErrorLevel\n\tcase \"dpanic\":\n\t\treturn zap.DPanicLevel\n\tcase \"panic\":\n\t\treturn zap.PanicLevel\n\tcase \"fatal\":\n\t\treturn zap.FatalLevel\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unknown level %q\", lvl))\n\t}\n}\n\n\n\n\n\nfunc ConvertToCapnslogLogLevel(lvl string) capnslog.LogLevel ", "output": "{\n\tswitch lvl {\n\tcase \"debug\":\n\t\treturn capnslog.DEBUG\n\tcase \"info\":\n\t\treturn capnslog.INFO\n\tcase \"warn\":\n\t\treturn capnslog.WARNING\n\tcase \"error\":\n\t\treturn capnslog.ERROR\n\tcase \"dpanic\":\n\t\treturn capnslog.CRITICAL\n\tcase \"panic\":\n\t\treturn capnslog.CRITICAL\n\tcase \"fatal\":\n\t\treturn capnslog.CRITICAL\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unknown level %q\", lvl))\n\t}\n}"} {"input": "package sql\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cockroachdb/cockroach/sql/parser\"\n)\n\n\n\n\ntype valuesNode struct {\n\tcolumns []string\n\trows []parser.DTuple\n\tnextRow int \n}\n\nfunc (n *valuesNode) Columns() []string {\n\treturn n.columns\n}\n\nfunc (n *valuesNode) Values() parser.DTuple {\n\treturn n.rows[n.nextRow-1]\n}\n\nfunc (n *valuesNode) Next() bool {\n\tif n.nextRow >= len(n.rows) {\n\t\treturn false\n\t}\n\tn.nextRow++\n\treturn true\n}\n\nfunc (*valuesNode) Err() error {\n\treturn nil\n}\n\nfunc (p *planner) Values(n parser.Values) (planNode, error) ", "output": "{\n\tv := &valuesNode{\n\t\trows: make([]parser.DTuple, 0, len(n)),\n\t}\n\tfor _, tuple := range n {\n\t\tdata, err := parser.EvalExpr(tuple, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvals, ok := data.(parser.DTuple)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"expected a tuple, but found %T\", data)\n\t\t}\n\t\tv.rows = append(v.rows, vals)\n\t}\n\treturn v, nil\n}"} {"input": "package fake\n\nimport (\n\tclientset \"github.com/openshift/client-go/oauth/clientset/versioned\"\n\toauthv1 \"github.com/openshift/client-go/oauth/clientset/versioned/typed/oauth/v1\"\n\tfakeoauthv1 \"github.com/openshift/client-go/oauth/clientset/versioned/typed/oauth/v1/fake\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/watch\"\n\t\"k8s.io/client-go/discovery\"\n\tfakediscovery \"k8s.io/client-go/discovery/fake\"\n\t\"k8s.io/client-go/testing\"\n)\n\n\n\n\n\n\n\n\n\n\ntype Clientset struct {\n\ttesting.Fake\n\tdiscovery *fakediscovery.FakeDiscovery\n}\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\treturn c.discovery\n}\n\nvar _ clientset.Interface = &Clientset{}\n\n\nfunc (c *Clientset) OauthV1() oauthv1.OauthV1Interface {\n\treturn &fakeoauthv1.FakeOauthV1{Fake: &c.Fake}\n}\n\n\nfunc (c *Clientset) Oauth() oauthv1.OauthV1Interface {\n\treturn &fakeoauthv1.FakeOauthV1{Fake: &c.Fake}\n}\n\nfunc NewSimpleClientset(objects ...runtime.Object) *Clientset ", "output": "{\n\to := testing.NewObjectTracker(scheme, codecs.UniversalDecoder())\n\tfor _, obj := range objects {\n\t\tif err := o.Add(obj); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tfakePtr := testing.Fake{}\n\tfakePtr.AddReactor(\"*\", \"*\", testing.ObjectReaction(o))\n\tfakePtr.AddWatchReactor(\"*\", testing.DefaultWatchReactor(watch.NewFake(), nil))\n\n\treturn &Clientset{fakePtr, &fakediscovery.FakeDiscovery{Fake: &fakePtr}}\n}"} {"input": "package parser\n\nimport (\n\t\"monkey/ast\"\n\t\"monkey/token\"\n)\n\nfunc (p *Parser) parseStringLiteralExpression() ast.Expression {\n\treturn &ast.StringLiteral{Token: p.curToken, Value: p.curToken.Literal}\n}\n\n\n\nfunc (p *Parser) parseInterpolatedString() ast.Expression ", "output": "{\n\tis := &ast.InterpolatedString{Token: p.curToken, Value: p.curToken.Literal, ExprMap: make(map[byte]ast.Expression)}\n\n\tkey := \"0\"[0]\n\tfor {\n\t\tif p.curTokenIs(token.LBRACE) {\n\t\t\tp.nextToken()\n\t\t\texpr := p.parseExpression(LOWEST)\n\t\t\tis.ExprMap[key] = expr\n\t\t\tkey++\n\t\t}\n\t\tp.nextInterpToken()\n\t\tif p.curTokenIs(token.ISTRING) {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn is\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\n\n\n\ntype ClusterMeshStatus struct {\n\n\tClusters []*RemoteCluster `json:\"clusters\"`\n\n\tNumGlobalServices int64 `json:\"num-global-services,omitempty\"`\n}\n\n\nfunc (m *ClusterMeshStatus) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateClusters(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (m *ClusterMeshStatus) validateClusters(formats strfmt.Registry) error {\n\n\tif swag.IsZero(m.Clusters) { \n\t\treturn nil\n\t}\n\n\tfor i := 0; i < len(m.Clusters); i++ {\n\t\tif swag.IsZero(m.Clusters[i]) { \n\t\t\tcontinue\n\t\t}\n\n\t\tif m.Clusters[i] != nil {\n\t\t\tif err := m.Clusters[i].Validate(formats); err != nil {\n\t\t\t\tif ve, ok := err.(*errors.Validation); ok {\n\t\t\t\t\treturn ve.ValidateName(\"clusters\" + \".\" + strconv.Itoa(i))\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\n\nfunc (m *ClusterMeshStatus) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\n\n\nfunc (m *ClusterMeshStatus) UnmarshalBinary(b []byte) error ", "output": "{\n\tvar res ClusterMeshStatus\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}"} {"input": "package request\n\nimport (\n\t\"CitySourcedAPI/data\"\n\t\"CitySourcedAPI/logs\"\n\t\"CitySourcedAPI/response\"\n\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\n\n\ntype CreateReportComment struct {\n\tRequest\n\tProcessor\n\tReportID string `xml:\"ReportId\" json:\"ReportId\"`\n\treportID int64\n\tComment string `xml:\"Comment\" json:\"Comment\"`\n}\n\nfunc (st *CreateReportComment) Validate(start time.Time) string {\n\tvar v validate\n\tst.start = start\n\tst.reportID = v.int(\"ReportID\", st.ReportID)\n\treturn v.errmsg\n}\n\n\n\nfunc (st CreateReportComment) String() string {\n\tls := new(logs.LogString)\n\tls.AddS(\"CreateReportComment\\n\")\n\tls.AddS(st.Request.String())\n\tls.AddF(\"ID %s/%d\\n\", st.ReportID, st.reportID)\n\tls.AddF(\"Comment: %v\\n\", st.Comment)\n\treturn ls.Box(90)\n}\n\nfunc (st *CreateReportComment) Run() (string, error) ", "output": "{\n\terr := data.NewComment(st.reportID, data.CustomTime{time.Now()}, st.Comment)\n\tif err != nil {\n\t\treturn response.StatusMsg(fmt.Sprintf(\"CreateReportComment failed: %q\", err), st.start), nil\n\t}\n\treturn response.StatusMsg(\"Comment created.\", st.start), nil\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\n\t\"code.gitea.io/gitea/models/db\"\n\t\"code.gitea.io/gitea/modules/log\"\n\t\"code.gitea.io/gitea/modules/setting\"\n\n\t\"github.com/urfave/cli\"\n)\n\n\nvar CmdConvert = cli.Command{\n\tName: \"convert\",\n\tUsage: \"Convert the database\",\n\tDescription: \"A command to convert an existing MySQL database from utf8 to utf8mb4\",\n\tAction: runConvert,\n}\n\n\n\nfunc runConvert(ctx *cli.Context) error ", "output": "{\n\tstdCtx, cancel := installSignals()\n\tdefer cancel()\n\n\tif err := initDB(stdCtx); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Info(\"AppPath: %s\", setting.AppPath)\n\tlog.Info(\"AppWorkPath: %s\", setting.AppWorkPath)\n\tlog.Info(\"Custom path: %s\", setting.CustomPath)\n\tlog.Info(\"Log path: %s\", setting.LogRootPath)\n\tlog.Info(\"Configuration file: %s\", setting.CustomConf)\n\n\tif !setting.Database.UseMySQL {\n\t\tfmt.Println(\"This command can only be used with a MySQL database\")\n\t\treturn nil\n\t}\n\n\tif err := db.ConvertUtf8ToUtf8mb4(); err != nil {\n\t\tlog.Fatal(\"Failed to convert database from utf8 to utf8mb4: %v\", err)\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Converted successfully, please confirm your database's character set is now utf8mb4\")\n\n\treturn nil\n}"} {"input": "package builtin\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/madlambda/nash/errors\"\n\t\"github.com/madlambda/nash/sh\"\n)\n\ntype (\n\tformatFn struct {\n\t\tfmt string\n\t\targs []interface{}\n\t}\n)\n\nfunc newFormat() *formatFn {\n\treturn &formatFn{}\n}\n\n\n\nfunc (f *formatFn) Run(in io.Reader, out io.Writer, err io.Writer) ([]sh.Obj, error) {\n\treturn []sh.Obj{sh.NewStrObj(fmt.Sprintf(f.fmt, f.args...))}, nil\n}\n\nfunc (f *formatFn) SetArgs(args []sh.Obj) error {\n\tif len(args) == 0 {\n\t\treturn errors.NewError(\"format expects at least 1 argument\")\n\t}\n\n\tf.fmt = args[0].String()\n\tf.args = nil\n\n\tfor _, arg := range args[1:] {\n\t\tf.args = append(f.args, arg.String())\n\t}\n\n\treturn nil\n}\n\nfunc (f *formatFn) ArgNames() []sh.FnArg ", "output": "{\n\treturn []sh.FnArg{\n\t\tsh.NewFnArg(\"fmt\", false),\n\t\tsh.NewFnArg(\"arg...\", true),\n\t}\n}"} {"input": "package circular\n\nimport (\n\t\"errors\"\n)\n\n\ntype Buffer struct {\n\tsize int \n\tn int \n\tdata []byte \n\twrite, read int \n}\n\n\nfunc NewBuffer(size int) *Buffer {\n\n\treturn &Buffer{\n\t\tsize: size,\n\t\tdata: make([]byte, size),\n\t}\n}\n\n\nfunc (b *Buffer) ReadByte() (byte, error) {\n\tif b.n == 0 {\n\t\treturn 0, errors.New(\"no bytes read\")\n\t}\n\td := b.data[b.read]\n\tb.read = (b.read + 1) % b.size\n\tb.n--\n\treturn d, nil\n}\n\n\nfunc (b *Buffer) WriteByte(c byte) error {\n\tif b.write == b.read && b.n > 0 {\n\t\treturn errors.New(\"buffer is full\")\n\t}\n\tb.Overwrite(c)\n\treturn nil\n}\n\n\nfunc (b *Buffer) Overwrite(c byte) {\n\tif b.read == b.write && b.n > 0 {\n\t\tb.read = (b.read + 1) % b.size\n\t\tb.n--\n\t}\n\tb.data[b.write] = c\n\tb.write = (b.write + 1) % b.size\n\tb.n++\n}\n\n\n\n\nfunc (b *Buffer) Reset() ", "output": "{\n\t*b = Buffer{\n\t\tsize: b.size,\n\t\tdata: make([]byte, b.size),\n\t}\n}"} {"input": "package remotestate\n\nimport (\n\t\"context\"\n\n\t\"github.com/r3labs/terraform/backend\"\n\t\"github.com/r3labs/terraform/helper/schema\"\n\t\"github.com/r3labs/terraform/state\"\n\t\"github.com/r3labs/terraform/state/remote\"\n\t\"github.com/r3labs/terraform/terraform\"\n)\n\n\n\n\n\n\ntype Backend struct {\n\t*schema.Backend\n\n\tConfigureFunc func(ctx context.Context) (remote.Client, error)\n\n\tclient remote.Client\n}\n\n\n\nfunc (b *Backend) States() ([]string, error) {\n\treturn nil, backend.ErrNamedStatesNotSupported\n}\n\nfunc (b *Backend) DeleteState(name string) error {\n\treturn backend.ErrNamedStatesNotSupported\n}\n\nfunc (b *Backend) State(name string) (state.State, error) {\n\tif b.client == nil {\n\t\tpanic(\"nil remote client\")\n\t}\n\n\tif name != backend.DefaultStateName {\n\t\treturn nil, backend.ErrNamedStatesNotSupported\n\t}\n\n\ts := &remote.State{Client: b.client}\n\treturn s, nil\n}\n\nfunc (b *Backend) Configure(rc *terraform.ResourceConfig) error ", "output": "{\n\tb.Backend.ConfigureFunc = func(ctx context.Context) error {\n\t\tc, err := b.ConfigureFunc(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tb.client = c\n\t\treturn nil\n\t}\n\n\treturn b.Backend.Configure(rc)\n}"} {"input": "package readline\n\nimport \"io\"\n\ntype Instance struct {\n\tt *Terminal\n\to *Operation\n}\n\ntype Config struct {\n\tPrompt string\n\tHistoryFile string\n}\n\nfunc NewEx(cfg *Config) (*Instance, error) {\n\tt, err := NewTerminal(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trl := t.Readline()\n\treturn &Instance{\n\t\tt: t,\n\t\to: rl,\n\t}, nil\n}\n\nfunc New(prompt string) (*Instance, error) {\n\treturn NewEx(&Config{Prompt: prompt})\n}\n\nfunc (i *Instance) Stdout() io.Writer {\n\treturn i.o.Stdout()\n}\n\nfunc (i *Instance) Stderr() io.Writer {\n\treturn i.o.Stderr()\n}\n\nfunc (i *Instance) Readline() (string, error) {\n\treturn i.o.String()\n}\n\n\n\nfunc (i *Instance) Close() error {\n\tif err := i.t.Close(); err != nil {\n\t\treturn err\n\t}\n\ti.o.Close()\n\treturn nil\n}\n\nfunc (i *Instance) ReadSlice() ([]byte, error) ", "output": "{\n\treturn i.o.Slice()\n}"} {"input": "package viewmodel\n\nimport \"github.com/airlingo/airlingo/model\"\n\ntype Settings struct {\n\tCurrentUser *model.User\n\tName string\n\tTranslationLanguage *model.Language\n\tTranslationLanguages []*model.Language\n}\n\nfunc NewSettings(currentUser *model.User, name string, translationLanguageID *string, translationLanguages []*model.Language) *Settings {\n\tsettings := &Settings{\n\t\tCurrentUser: currentUser,\n\t\tName: name,\n\t\tTranslationLanguages: translationLanguages,\n\t}\n\n\tif translationLanguageID != nil {\n\t\tfor _, language := range translationLanguages {\n\t\t\tif language.ID == *translationLanguageID {\n\t\t\t\tsettings.TranslationLanguage = language\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn settings\n}\n\n\n\nfunc (c *Settings) GetTranslationLanguageID() string ", "output": "{\n\tif c.TranslationLanguage == nil {\n\t\treturn \"\"\n\t}\n\n\treturn c.TranslationLanguage.ID\n}"} {"input": "package billing\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/billing/mgmt/2017-04-24-preview/billing\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype ManagementClient = original.ManagementClient\ntype InvoicesClient = original.InvoicesClient\ntype DownloadURL = original.DownloadURL\ntype ErrorDetails = original.ErrorDetails\ntype ErrorResponse = original.ErrorResponse\ntype Invoice = original.Invoice\ntype InvoiceProperties = original.InvoiceProperties\ntype InvoicesListResult = original.InvoicesListResult\ntype Operation = original.Operation\ntype OperationDisplay = original.OperationDisplay\ntype OperationListResult = original.OperationListResult\ntype Period = original.Period\ntype PeriodProperties = original.PeriodProperties\ntype PeriodsListResult = original.PeriodsListResult\ntype Resource = original.Resource\ntype OperationsClient = original.OperationsClient\ntype PeriodsClient = original.PeriodsClient\n\nfunc NewOperationsClient(subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClient(subscriptionID)\n}\nfunc NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewPeriodsClient(subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClient(subscriptionID)\n}\nfunc NewPeriodsClientWithBaseURI(baseURI string, subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\nfunc New(subscriptionID string) ManagementClient {\n\treturn original.New(subscriptionID)\n}\n\nfunc NewInvoicesClient(subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClient(subscriptionID)\n}\nfunc NewInvoicesClientWithBaseURI(baseURI string, subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClientWithBaseURI(baseURI, subscriptionID)\n}\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient ", "output": "{\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}"} {"input": "package event\n\n\ntype Newchannel struct {\n\tPrivilege []string\n\tChannel string `AMI:\"Channel\"`\n\tChannelState string `AMI:\"Channelstate\"`\n\tChannelStateDesc string `AMI:\"Channelstatedesc\"`\n\tCallerIDNum string `AMI:\"Calleridnum\"`\n\tCallerIDName string `AMI:\"Calleridname\"`\n\tAccountCode string `AMI:\"Accountcode\"`\n\tUniqueID string `AMI:\"Uniqueid\"`\n\tContext string `AMI:\"Context\"`\n\tExtension string `AMI:\"Exten\"`\n}\n\n\n\nfunc init() ", "output": "{\n\teventTrap[\"Newchannel\"] = Newchannel{}\n}"} {"input": "package test_helpers\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\tdatatypes \"github.com/maximilien/softlayer-go/data_types\"\n)\n\ntype MockProductPackageService struct{}\n\nfunc (mock *MockProductPackageService) GetName() string {\n\treturn \"Mock_Product_Package_Service\"\n}\n\nfunc (mock *MockProductPackageService) GetItemsByType(packageType string) ([]datatypes.SoftLayer_Product_Item, error) {\n\tresponse, _ := ReadJsonTestFixtures(\"services\", \"SoftLayer_Product_Package_getItemsByType_virtual_server.json\")\n\n\tproductItems := []datatypes.SoftLayer_Product_Item{}\n\tjson.Unmarshal(response, &productItems)\n\n\treturn productItems, nil\n}\n\nfunc (mock *MockProductPackageService) GetItemPrices(packageId int) ([]datatypes.SoftLayer_Product_Item_Price, error) {\n\treturn []datatypes.SoftLayer_Product_Item_Price{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetItemPricesBySize(packageId int, size int) ([]datatypes.SoftLayer_Product_Item_Price, error) {\n\treturn []datatypes.SoftLayer_Product_Item_Price{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetItems(packageId int) ([]datatypes.SoftLayer_Product_Item, error) {\n\treturn []datatypes.SoftLayer_Product_Item{}, errors.New(\"Not supported\")\n}\n\n\n\nfunc (mock *MockProductPackageService) GetOnePackageByType(packageType string) (datatypes.Softlayer_Product_Package, error) {\n\treturn datatypes.Softlayer_Product_Package{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetPackagesByType(packageType string) ([]datatypes.Softlayer_Product_Package, error) ", "output": "{\n\treturn []datatypes.Softlayer_Product_Package{}, errors.New(\"Not supported\")\n}"} {"input": "package readline\n\nimport \"io\"\n\ntype Instance struct {\n\tt *Terminal\n\to *Operation\n}\n\ntype Config struct {\n\tPrompt string\n\tHistoryFile string\n}\n\n\n\nfunc New(prompt string) (*Instance, error) {\n\treturn NewEx(&Config{Prompt: prompt})\n}\n\nfunc (i *Instance) Stdout() io.Writer {\n\treturn i.o.Stdout()\n}\n\nfunc (i *Instance) Stderr() io.Writer {\n\treturn i.o.Stderr()\n}\n\nfunc (i *Instance) Readline() (string, error) {\n\treturn i.o.String()\n}\n\nfunc (i *Instance) ReadSlice() ([]byte, error) {\n\treturn i.o.Slice()\n}\n\nfunc (i *Instance) Close() error {\n\tif err := i.t.Close(); err != nil {\n\t\treturn err\n\t}\n\ti.o.Close()\n\treturn nil\n}\n\nfunc NewEx(cfg *Config) (*Instance, error) ", "output": "{\n\tt, err := NewTerminal(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trl := t.Readline()\n\treturn &Instance{\n\t\tt: t,\n\t\to: rl,\n\t}, nil\n}"} {"input": "package awsdeployer_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestAWSDeployer(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"awsdeployer\")\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime/middleware\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewDownloadImageParams() DownloadImageParams {\n\tvar ()\n\treturn DownloadImageParams{}\n}\n\n\n\n\n\ntype DownloadImageParams struct {\n\n\tHTTPRequest *http.Request\n\n\tImageID string\n}\n\n\n\n\n\nfunc (o *DownloadImageParams) bindImageID(rawData []string, hasKey bool, formats strfmt.Registry) error {\n\tvar raw string\n\tif len(rawData) > 0 {\n\t\traw = rawData[len(rawData)-1]\n\t}\n\n\to.ImageID = raw\n\n\treturn nil\n}\n\nfunc (o *DownloadImageParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error ", "output": "{\n\tvar res []error\n\to.HTTPRequest = r\n\n\trImageID, rhkImageID, _ := route.Params.GetOK(\"imageId\")\n\tif err := o.bindImageID(rImageID, rhkImageID, route.Formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetCrossConnectRequest struct {\n\n\tCrossConnectId *string `mandatory:\"true\" contributesTo:\"path\" name:\"crossConnectId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request GetCrossConnectRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request GetCrossConnectRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetCrossConnectRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetCrossConnectResponse struct {\n\n\tRawResponse *http.Response\n\n\tCrossConnect `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetCrossConnectResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetCrossConnectResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetCrossConnectRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package prime\n\nimport \"math\"\n\n\n\n\nfunc isPrime(candidate int) bool {\n\tfor i := 2; i <= int(math.Sqrt(float64(candidate))); i++ {\n\t\tif candidate%i == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn candidate > 1\n}\n\nfunc Nth(n int) (int, bool) ", "output": "{\n\tif n < 1 {\n\t\treturn 0, false\n\t}\n\n\tfoundPrimes := 0\n\tcandidate := 1\n\n\tfor foundPrimes < n {\n\t\tcandidate++\n\t\tif isPrime(candidate) {\n\t\t\tfoundPrimes++\n\t\t}\n\t}\n\n\treturn candidate, true\n}"} {"input": "package mock_driver\n\nimport (\n\tnet \"net\"\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n)\n\n\ntype MockNetworkAPIs struct {\n\tctrl *gomock.Controller\n\trecorder *MockNetworkAPIsMockRecorder\n}\n\n\ntype MockNetworkAPIsMockRecorder struct {\n\tmock *MockNetworkAPIs\n}\n\n\nfunc NewMockNetworkAPIs(ctrl *gomock.Controller) *MockNetworkAPIs {\n\tmock := &MockNetworkAPIs{ctrl: ctrl}\n\tmock.recorder = &MockNetworkAPIsMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockNetworkAPIs) EXPECT() *MockNetworkAPIsMockRecorder {\n\treturn m.recorder\n}\n\n\nfunc (m *MockNetworkAPIs) SetupNS(arg0, arg1, arg2 string, arg3 *net.IPNet, arg4 int, arg5 []string, arg6 bool) error {\n\tret := m.ctrl.Call(m, \"SetupNS\", arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}\n\n\nfunc (mr *MockNetworkAPIsMockRecorder) SetupNS(arg0, arg1, arg2, arg3, arg4, arg5, arg6 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SetupNS\", reflect.TypeOf((*MockNetworkAPIs)(nil).SetupNS), arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n}\n\n\n\n\n\nfunc (mr *MockNetworkAPIsMockRecorder) TeardownNS(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"TeardownNS\", reflect.TypeOf((*MockNetworkAPIs)(nil).TeardownNS), arg0, arg1)\n}\n\nfunc (m *MockNetworkAPIs) TeardownNS(arg0 *net.IPNet, arg1 int) error ", "output": "{\n\tret := m.ctrl.Call(m, \"TeardownNS\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}"} {"input": "package web\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/gravitational/teleport/lib/httplib\"\n\n\t\"github.com/gravitational/roundtrip\"\n\t\"github.com/gravitational/trace\"\n)\n\nfunc newInsecureClient() *http.Client {\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t}\n}\n\nfunc newClientWithPool(pool *x509.CertPool) *http.Client {\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{RootCAs: pool},\n\t\t},\n\t}\n}\n\nfunc newWebClient(url string, opts ...roundtrip.ClientParam) (*webClient, error) {\n\tclt, err := roundtrip.NewClient(url, APIVersion, opts...)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn &webClient{clt}, nil\n}\n\n\n\ntype webClient struct {\n\t*roundtrip.Client\n}\n\nfunc (w *webClient) PostJSON(\n\tendpoint string, val interface{}) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.PostJSON(endpoint, val))\n}\n\nfunc (w *webClient) PutJSON(\n\tendpoint string, val interface{}) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.PutJSON(endpoint, val))\n}\n\nfunc (w *webClient) Get(endpoint string, val url.Values) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.Get(endpoint, val))\n}\n\n\n\nfunc (w *webClient) Delete(endpoint string) (*roundtrip.Response, error) ", "output": "{\n\treturn httplib.ConvertResponse(w.Client.Delete(endpoint))\n}"} {"input": "package xenserver\n\nimport (\n\t\"time\"\n\n\t\"github.com/hashicorp/terraform/helper/schema\"\n)\n\n\n\nfunc dataSourceXenServerPifsRead(d *schema.ResourceData, meta interface{}) error {\n\tc := meta.(*Connection)\n\n\tpifUUIDs := make([]string, 0)\n\n\tif pifs, err := c.client.PIF.GetAllRecords(c.session); err == nil {\n\t\tfor _, pif := range pifs {\n\t\t\tpifUUIDs = append(pifUUIDs, pif.UUID)\n\t\t}\n\t}\n\n\td.SetId(time.Now().UTC().String())\n\td.Set(\"uuids\", pifUUIDs)\n\n\treturn nil\n}\n\nfunc dataSourceXenServerPifs() *schema.Resource ", "output": "{\n\treturn &schema.Resource{\n\t\tRead: dataSourceXenServerPifsRead,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"uuids\": &schema.Schema{\n\t\t\t\tType: schema.TypeList,\n\t\t\t\tComputed: true,\n\t\t\t\tElem: &schema.Schema{Type: schema.TypeString},\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package format\n\nimport (\n\t\"github.com/kitwalker12/fotomat/vips\"\n)\n\n\ntype Metadata struct {\n\tWidth int\n\tHeight int\n\tFormat Format\n\tOrientation Orientation\n\tHasAlpha bool\n}\n\n\nfunc MetadataBytes(blob []byte) (Metadata, error) {\n\tformat := DetectFormat(blob)\n\tif format == Unknown {\n\t\treturn Metadata{}, ErrUnknownFormat\n\t}\n\n\treturn format.MetadataBytes(blob)\n}\n\n\nfunc (format Format) MetadataBytes(blob []byte) (Metadata, error) {\n\timage, err := format.LoadBytes(blob)\n\tif err != nil {\n\t\treturn Metadata{}, ErrUnknownFormat\n\t}\n\n\tdefer image.Close()\n\n\treturn metadataImageFormat(image, format), nil\n}\n\n\nfunc (format Format) MetadataFile(filename string) (Metadata, error) {\n\timage, err := format.LoadFile(filename)\n\tif err != nil {\n\t\treturn Metadata{}, err\n\t}\n\n\tdefer image.Close()\n\n\treturn metadataImageFormat(image, format), nil\n}\n\nfunc metadataImageFormat(image *vips.Image, format Format) Metadata {\n\tm := MetadataImage(image)\n\tm.Format = format\n\treturn m\n}\n\n\n\n\nfunc MetadataImage(image *vips.Image) Metadata ", "output": "{\n\to := DetectOrientation(image)\n\tw, h := o.Dimensions(image.Xsize(), image.Ysize())\n\tif w <= 0 || h <= 0 {\n\t\tpanic(\"Invalid image dimensions.\")\n\t}\n\treturn Metadata{Width: w, Height: h, Orientation: o, HasAlpha: image.HasAlpha()}\n}"} {"input": "package utils\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Config struct {\n\tApiToken string\n\tDebug int\n}\n\nfunc LoadConfig(filename string, conf *Config) error {\n\n\tvalid := map[string]int{\n\t\t\"debug\": 1,\n\t\t\"api_token\": 1,\n\t}\n\n\tbuf := bytes.NewBuffer(nil)\n\tf, err := os.Open(filename) \n\tif err != nil {\n\t\treturn errors.New(\"Invalid or missing config!\")\n\t}\n\n\tio.Copy(buf, f) \n\tf.Close()\n\ts := string(buf.Bytes())\n\n\tfor _, l := range strings.Split(strings.Trim(s, \" \"), \"\\n\") {\n\t\tif l == \"\" || string(l[0]) == \"#\" {\n\t\t\tcontinue\n\t\t}\n\t\tparts := strings.SplitN(strings.Trim(l, \" \"), \"=\", 2)\n\t\tif _, ok := valid[parts[0]]; ok {\n\t\t\tif parts[0] == \"debug\" {\n\t\t\t\tv, _ := strconv.Atoi(parts[1])\n\t\t\t\tif v < 0 || v > 1 {\n\t\t\t\t\tfmt.Println(DateStampAsString(), \"Config ERROR: debug can only be 0 or 1\")\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t\tconf.Debug = v\n\t\t\t} else if parts[0] == \"api_token\" {\n\t\t\t\tconf.ApiToken = parts[1]\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc YmdToString() string {\n\tt := time.Now()\n\ty, m, d := t.Date()\n\treturn strconv.Itoa(y) + fmt.Sprintf(\"%02d\", m) + fmt.Sprintf(\"%02d\", d)\n}\n\n\nfunc DateStampAsString() string ", "output": "{\n\tt := time.Now()\n\treturn \"[\" + YmdToString() + \" \" + fmt.Sprintf(\"%02d\", t.Hour()) + \":\" + fmt.Sprintf(\"%02d\", t.Minute()) + \":\" + fmt.Sprintf(\"%02d\", t.Second()) + \"]\"\n}"} {"input": "package query\n\n\n\nfunc hideManagementTraffic(conditional string) string {\n\treturn conditional\n}\n\nfunc excludeManagementNet(conditional string) string ", "output": "{\n\treturn conditional\n}"} {"input": "package protocol\n\n\ntype Perspective int\n\n\nconst (\n\tPerspectiveServer Perspective = 1\n\tPerspectiveClient Perspective = 2\n)\n\n\n\nfunc (p Perspective) String() string ", "output": "{\n\tswitch p {\n\tcase PerspectiveServer:\n\t\treturn \"Server\"\n\tcase PerspectiveClient:\n\t\treturn \"Client\"\n\tdefault:\n\t\treturn \"invalid perspective\"\n\t}\n}"} {"input": "package service\n\nimport (\n\tgofig \"github.com/akutz/gofig/types\"\n\n\t\"github.com/thecodeteam/rexray/libstorage/api/registry\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/server/handlers\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/server/httputils\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/types\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/utils/schema\"\n)\n\nfunc init() {\n\tregistry.RegisterRouter(&router{})\n}\n\ntype router struct {\n\troutes []types.Route\n}\n\nfunc (r *router) Name() string {\n\treturn \"service-router\"\n}\n\nfunc (r *router) Init(config gofig.Config) {\n\tr.initRoutes()\n}\n\n\nfunc (r *router) Routes() []types.Route {\n\treturn r.routes\n}\n\n\n\nfunc (r *router) initRoutes() ", "output": "{\n\n\tr.routes = []types.Route{\n\n\t\thttputils.NewGetRoute(\n\t\t\t\"services\",\n\t\t\t\"/services\",\n\t\t\tr.servicesList,\n\t\t\thandlers.NewAuthAllSvcsHandler(),\n\t\t\thandlers.NewSchemaValidator(nil, schema.ServiceInfoMapSchema, nil)),\n\n\t\thttputils.NewGetRoute(\n\t\t\t\"serviceInspect\",\n\t\t\t\"/services/{service}\",\n\t\t\tr.serviceInspect,\n\t\t\thandlers.NewServiceValidator(),\n\t\t\thandlers.NewAuthSvcHandler(),\n\t\t\thandlers.NewSchemaValidator(nil, schema.ServiceInfoSchema, nil)),\n\t}\n}"} {"input": "package apimgr\n\nimport \"reflect\"\n\nfunc newSorter(manager *Manager) *sorter {\n\tapis := []Definition{}\n\tfor _, api := range manager.apiMethodPatternMap {\n\t\tapis = append(apis, api)\n\t}\n\treturn &sorter{\n\t\tManager: manager,\n\t\tapis: apis,\n\t}\n}\n\ntype sorter struct {\n\t*Manager\n\n\tapis []Definition\n}\n\nfunc (t sorter) Len() int {\n\treturn len(t.apis)\n}\n\nfunc (t sorter) Swap(i int, j int) {\n\tt.apis[i], t.apis[j] = t.apis[j], t.apis[i]\n}\n\n\n\nfunc (t sorter) getSortKey(api Definition) string {\n\tpkgpath := getPackagePath(reflect.ValueOf(api.Request))\n\tkey := pkgpath + \" \" + t.GetMethodPatternKey(t.Manager, api)\n\treturn key\n}\n\nfunc (t sorter) Less(i int, j int) bool ", "output": "{\n\tki := t.getSortKey(t.apis[i])\n\tkj := t.getSortKey(t.apis[j])\n\treturn ki < kj\n}"} {"input": "package parse\n\n\nimport (\n\t\"strings\"\n)\n\nfunc indent(s string, character string, size int) string {\n\tindent := strings.Repeat(character, size)\n\tlines := strings.Split(s, newLine)\n\tfor k, v := range lines {\n\t\tif len(v) > 0 {\n\t\t\tlines[k] = indent + v\n\t\t}\n\t}\n\treturn strings.Join(lines, newLine)\n}\n\n\n\nfunc EqualSlicesFoldPrefix(a, prefix []string) bool {\n\tl, lprefix := len(a), len(prefix)\n\tswitch {\n\tcase lprefix == 0:\n\t\treturn true\n\tcase l < lprefix:\n\t\treturn false\n\tcase l > lprefix:\n\t\treturn EqualSlicesFold(a[:lprefix], prefix)\n\tdefault:\n\t\treturn EqualSlicesFold(a, prefix)\n\t}\n}\n\n\n\n\n\n\n\nfunc EqualSlicesFold(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor k := range a {\n\t\tif !strings.EqualFold(a[k], b[k]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\nfunc EqualSlicesFoldSome(a []string, b ...[]string) bool {\n\tif len(a) == 0 && len(b) == 0 {\n\t\treturn true\n\t}\n\n\tfor k := range b {\n\t\tif EqualSlicesFold(a, b[k]) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc EqualSlicesFoldSuffix(a, suffix []string) bool ", "output": "{\n\tl, lsuffix := len(a), len(suffix)\n\tswitch {\n\tcase lsuffix == 0:\n\t\treturn true\n\tcase l < lsuffix:\n\t\treturn false\n\tcase l > lsuffix:\n\t\treturn EqualSlicesFold(a[l-lsuffix:], suffix)\n\tdefault:\n\t\treturn EqualSlicesFold(a, suffix)\n\t}\n}"} {"input": "package kms\n\nimport (\n\t\"encoding/base64\"\n\t\"fmt\"\n\n\t\"github.com/VirgilSecurity/virgil-sdk-go/v6/crypto/wrapper/phe\"\n\t\"github.com/urfave/cli/v2\"\n\n\t\"github.com/VirgilSecurity/virgil-cli/utils\"\n)\n\n\n\n\nfunc KMSPrivateKey() *cli.Command {\n\treturn &cli.Command{\n\t\tName: \"client-private\",\n\t\tAliases: []string{\"pk\"},\n\t\tUsage: \"Generate a new KMS Client Private key\",\n\t\tAction: func(context *cli.Context) error {\n\t\t\terr := printKMSPrivateKey()\n\t\t\tif err != nil {\n\t\t\t\treturn utils.CliExit(err)\n\t\t\t}\n\t\t\treturn err\n\t\t},\n\t}\n}\n\n\n\nfunc printKMSPrivateKey() error {\n\tkey, err := GenerateKMSPrivateKey()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(base64.StdEncoding.EncodeToString(key))\n\treturn nil\n}\n\nfunc GenerateKMSPrivateKey() ([]byte, error) ", "output": "{\n\tkmsClient := phe.NewUokmsClient()\n\tif err := kmsClient.SetupDefaults(); err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\treturn kmsClient.GenerateClientPrivateKey()\n}"} {"input": "package stringutil\n\nimport (\n\t\"fmt\"\n\t\"github.com/golang/example/stringutil\"\n\t\"testing\"\n)\n\nfunc TestReverse(t *testing.T) {\n\tfor _, c := range []struct {\n\t\tin, want string\n\t}{\n\t\t{\"Hello, world\", \"dlrow ,olleH\"},\n\t\t{\"Hello, 世界\", \"界世 ,olleH\"},\n\t\t{\"\", \"\"},\n\t} {\n\t\tgot := Reverse(c.in)\n\t\tif got != c.want {\n\t\t\tt.Errorf(\"Reverse(%q) == %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}\n\n\n\nfunc ExampleReverse() ", "output": "{\n\tr := stringutil.Reverse(\"Hello, world\")\n\tfmt.Println(r)\n\n\tr = stringutil.Reverse(\"Hello, 世界\")\n\tfmt.Println(r)\n\n}"} {"input": "package main\n\nimport \"reflect\"\n\n\n\n\n\n\nvar a, b int\n\n\n\nfunc chanreflect2() {\n\tch := make(chan *int, 0)\n\tch <- &b\n\tcrv := reflect.ValueOf(ch)\n\tr, _ := crv.Recv()\n\tprint(r.Interface()) \n\tprint(r.Interface().(*int)) \n}\n\nfunc main() {\n\tchanreflect1()\n\tchanreflect2()\n}\n\nfunc chanreflect1() ", "output": "{\n\tch := make(chan *int, 0)\n\tcrv := reflect.ValueOf(ch)\n\tcrv.Send(reflect.ValueOf(&a))\n\tprint(crv.Interface()) \n\tprint(crv.Interface().(chan *int)) \n\tprint(<-ch) \n}"} {"input": "package scaffold\n\ntype MockPlatform struct {\n\tRoute *Route\n}\n\n\n\nfunc NewMockPlatform() *MockPlatform {\n\treturn &MockPlatform{}\n}\n\nfunc (m *MockPlatform) Routes(r *Router) ", "output": "{\n\tm.Route = &r.route\n}"} {"input": "package client_test\n\nimport (\n\t\"github.com/jdextraze/go-gesclient/client\"\n\t\"testing\"\n)\n\nfunc TestWrongExpectedVersion_Error(t *testing.T) {\n\tif client.WrongExpectedVersion.Error() != \"Wrong expected version\" {\n\t\tt.FailNow()\n\t}\n}\n\n\n\nfunc TestInvalidTransaction_Error(t *testing.T) {\n\tif client.InvalidTransaction.Error() != \"Invalid transaction\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestAccessDenied_Error(t *testing.T) {\n\tif client.AccessDenied.Error() != \"Access denied\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestAuthenticationError_Error(t *testing.T) {\n\tif client.AuthenticationError.Error() != \"Authentication error\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestBadRequest_Error(t *testing.T) {\n\tif client.BadRequest.Error() != \"Bad request\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestServerError_Error(t *testing.T) {\n\terr := client.NewServerError(\"\")\n\tif err.Error() != \"Unexpected error on server: \" {\n\t\tt.FailNow()\n\t}\n\n\terr = client.NewServerError(\"test\")\n\tif err.Error() != \"Unexpected error on server: test\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestNotModified_Error(t *testing.T) {\n\terr := client.NewNotModified(\"test\")\n\tif err.Error() != \"Stream not modified: test\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestStreamDeleted_Error(t *testing.T) ", "output": "{\n\tif client.StreamDeleted.Error() != \"Stream deleted\" {\n\t\tt.FailNow()\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n)\n\n\n\n\n\n\n\nconst (\n\twriteExec = 1 << iota\n\twriteSkipSame\n)\n\n\nfunc ReadFile(file string) string {\n\tdata, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tlog.Fatalf(\"ReadFile: %v\", err)\n\t}\n\treturn string(data)\n}\n\n\n\n\n\n\n\n\nfunc CopyFile(dst, src string, flag int) {\n\tWriteFile(ReadFile(src), dst, flag)\n}\n\nfunc WriteFile(b, file string, flag int) ", "output": "{\n\tnew := []byte(b)\n\tif flag&writeSkipSame != 0 {\n\t\told, err := ioutil.ReadFile(file)\n\t\tif err == nil && bytes.Equal(old, new) {\n\t\t\treturn\n\t\t}\n\t}\n\tmode := os.FileMode(0666)\n\tif flag&writeExec != 0 {\n\t\tmode = 0777\n\t}\n\terr := ioutil.WriteFile(file, new, mode)\n\tif err != nil {\n\t\tlog.Fatalf(\"WriteFile: %v\", err)\n\t}\n}"} {"input": "package cloudinfo\n\nimport (\n\t\"k8s.io/klog/v2\"\n\n\tinfo \"github.com/google/cadvisor/info/v1\"\n)\n\ntype CloudInfo interface {\n\tGetCloudProvider() info.CloudProvider\n\tGetInstanceType() info.InstanceType\n\tGetInstanceID() info.InstanceID\n}\n\n\ntype CloudProvider interface {\n\tIsActiveProvider() bool\n\tGetInstanceType() info.InstanceType\n\tGetInstanceID() info.InstanceID\n}\n\nvar providers = map[info.CloudProvider]CloudProvider{}\n\n\n\n\ntype realCloudInfo struct {\n\tcloudProvider info.CloudProvider\n\tinstanceType info.InstanceType\n\tinstanceID info.InstanceID\n}\n\nfunc NewRealCloudInfo() CloudInfo {\n\tfor name, provider := range providers {\n\t\tif provider.IsActiveProvider() {\n\t\t\treturn &realCloudInfo{\n\t\t\t\tcloudProvider: name,\n\t\t\t\tinstanceType: provider.GetInstanceType(),\n\t\t\t\tinstanceID: provider.GetInstanceID(),\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &realCloudInfo{\n\t\tcloudProvider: info.UnknownProvider,\n\t\tinstanceType: info.UnknownInstance,\n\t\tinstanceID: info.UnNamedInstance,\n\t}\n}\n\nfunc (i *realCloudInfo) GetCloudProvider() info.CloudProvider {\n\treturn i.cloudProvider\n}\n\nfunc (i *realCloudInfo) GetInstanceType() info.InstanceType {\n\treturn i.instanceType\n}\n\nfunc (i *realCloudInfo) GetInstanceID() info.InstanceID {\n\treturn i.instanceID\n}\n\nfunc RegisterCloudProvider(name info.CloudProvider, provider CloudProvider) ", "output": "{\n\tif _, alreadyRegistered := providers[name]; alreadyRegistered {\n\t\tklog.Warningf(\"Duplicate registration of CloudProvider %s\", name)\n\t}\n\tproviders[name] = provider\n}"} {"input": "package cases\n\nimport \"gx/ipfs/QmVcxhXDbXjNoAdmYBWbY1eU67kQ8eZUHjG4mAYZUtZZu3/go-text/transform\"\n\ntype caseFolder struct{ transform.NopResetter }\n\n\nfunc (t *caseFolder) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {\n\tc := context{dst: dst, src: src, atEOF: atEOF}\n\tfor c.next() {\n\t\tfoldFull(&c)\n\t\tc.checkpoint()\n\t}\n\treturn c.ret()\n}\n\n\n\nfunc makeFold(o options) transform.SpanningTransformer {\n\treturn &caseFolder{}\n}\n\nfunc (t *caseFolder) Span(src []byte, atEOF bool) (n int, err error) ", "output": "{\n\tc := context{src: src, atEOF: atEOF}\n\tfor c.next() && isFoldFull(&c) {\n\t\tc.checkpoint()\n\t}\n\treturn c.retSpan()\n}"} {"input": "package g\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/toolkits/file\"\n)\n\n\n\nfunc RrdFileName(baseDir string, md5 string, dsType string, step int) string {\n\treturn baseDir + \"/\" + md5[0:2] + \"/\" +\n\t\tmd5 + \"_\" + dsType + \"_\" + strconv.Itoa(step) + \".rrd\"\n}\n\n\nfunc IsRrdFileExist(filename string) bool {\n\treturn file.IsExist(filename)\n}\n\n\nfunc FormRrdCacheKey(md5 string, dsType string, step int) string {\n\treturn md5 + \"_\" + dsType + \"_\" + strconv.Itoa(step)\n}\n\n\n\nfunc IsValidString(str string) bool {\n\n\tr := []rune(str)\n\n\tfor _, t := range r {\n\t\tswitch t {\n\t\tcase '\\r':\n\t\t\treturn false\n\t\tcase '\\n':\n\t\t\treturn false\n\t\tcase '\\'':\n\t\t\treturn false\n\t\tcase '\"':\n\t\t\treturn false\n\t\tcase '>':\n\t\t\treturn false\n\t\tcase '\\032':\n\t\t\treturn false\n\t\tdefault:\n\t\t\tif !unicode.IsPrint(t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\nfunc SplitRrdCacheKey(ckey string) (md5 string, dsType string, step int, err error) ", "output": "{\n\tckey_slice := strings.Split(ckey, \"_\")\n\tif len(ckey_slice) != 3 {\n\t\terr = fmt.Errorf(\"bad rrd cache key: %s\", ckey)\n\t\treturn\n\t}\n\n\tmd5 = ckey_slice[0]\n\tdsType = ckey_slice[1]\n\tstepInt64, err := strconv.ParseInt(ckey_slice[2], 10, 32)\n\tif err != nil {\n\t\treturn\n\t}\n\tstep = int(stepInt64)\n\n\terr = nil\n\treturn\n}"} {"input": "package osutil_test\n\nimport (\n\t\"crypto\"\n\t\"crypto/sha512\"\n\t\"io/ioutil\"\n\t\"path/filepath\"\n\n\t. \"gopkg.in/check.v1\"\n\n\t\"github.com/snapcore/snapd/osutil\"\n)\n\ntype FileDigestSuite struct{}\n\nvar _ = Suite(&FileDigestSuite{})\n\n\n\nfunc (ts *FileDigestSuite) TestFileDigest(c *C) ", "output": "{\n\texData := []byte(\"hashmeplease\")\n\n\ttempdir := c.MkDir()\n\tfn := filepath.Join(tempdir, \"ex.file\")\n\terr := ioutil.WriteFile(fn, exData, 0644)\n\tc.Assert(err, IsNil)\n\n\tdigest, size, err := osutil.FileDigest(fn, crypto.SHA512)\n\tc.Assert(err, IsNil)\n\tc.Check(size, Equals, uint64(len(exData)))\n\th512 := sha512.Sum512(exData)\n\tc.Check(digest, DeepEquals, h512[:])\n}"} {"input": "package mountinfo\n\nimport \"strings\"\n\n\n\n\n\n\n\n\n\n\n\ntype FilterFunc func(*Info) (skip, stop bool)\n\n\n\n\n\n\n\n\n\n\n\nfunc SingleEntryFilter(mp string) FilterFunc {\n\treturn func(m *Info) (bool, bool) {\n\t\tif m.Mountpoint == mp {\n\t\t\treturn false, true \n\t\t}\n\t\treturn true, false \n\t}\n}\n\n\n\n\n\n\nfunc ParentsFilter(path string) FilterFunc {\n\treturn func(m *Info) (bool, bool) {\n\t\tskip := !strings.HasPrefix(path, m.Mountpoint)\n\t\treturn skip, false\n\t}\n}\n\n\nfunc FSTypeFilter(fstype ...string) FilterFunc {\n\treturn func(m *Info) (bool, bool) {\n\t\tfor _, t := range fstype {\n\t\t\tif m.FSType == t {\n\t\t\t\treturn false, false \n\t\t\t}\n\t\t}\n\t\treturn true, false \n\t}\n}\n\nfunc PrefixFilter(prefix string) FilterFunc ", "output": "{\n\treturn func(m *Info) (bool, bool) {\n\t\tskip := !strings.HasPrefix(m.Mountpoint+\"/\", prefix+\"/\")\n\t\treturn skip, false\n\t}\n}"} {"input": "package handlers\n\nimport (\n\t\"github.com/bbiskup/edify-web/defs\"\n\t\"github.com/gorilla/mux\"\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n)\n\nvar compositeDataElemSpecTemplates *template.Template\n\nfunc init() {\n\tfuncMap := template.FuncMap{\n\t\t\"DataElemSpecURL\": DataElemSpecURL,\n\t}\n\tt := template.New(\"layout.html\").Funcs(funcMap)\n\tcompositeDataElemSpecTemplates = template.Must(t.ParseFiles(\n\t\tdefs.TemplatePaths(\"layout.html\", \"navbar.html\", \"compositedataelemspec.html\")...,\n\t))\n}\n\n\n\nfunc CompositeDataElemSpec(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tvars := mux.Vars(r)\n\tdataElemSpecID := vars[\"id\"]\n\n\tdata := map[string]interface{}{\n\t\t\"dataElemSpec\": defs.SpecParser.CompositeDataElemSpecs[dataElemSpecID],\n\t}\n\n\terr := compositeDataElemSpecTemplates.ExecuteTemplate(w, \"layout\", data)\n\tif err != nil {\n\t\tlog.Printf(\"Error executing template: %s\", err)\n\t}\n}"} {"input": "package gate\n\nimport (\n\t\"github.com/lonng/nano/component\"\n\t\"github.com/lonng/nano/examples/cluster/protocol\"\n\t\"github.com/lonng/nano/session\"\n\t\"github.com/pingcap/errors\"\n)\n\ntype BindService struct {\n\tcomponent.Base\n\tnextGateUid int64\n}\n\nfunc newBindService() *BindService {\n\treturn &BindService{}\n}\n\ntype (\n\tLoginRequest struct {\n\t\tNickname string `json:\"nickname\"`\n\t}\n\tLoginResponse struct {\n\t\tCode int `json:\"code\"`\n\t}\n)\n\n\n\nfunc (bs *BindService) BindChatServer(s *session.Session, msg []byte) error {\n\treturn errors.Errorf(\"not implement\")\n}\n\nfunc (bs *BindService) Login(s *session.Session, msg *LoginRequest) error ", "output": "{\n\tbs.nextGateUid++\n\tuid := bs.nextGateUid\n\trequest := &protocol.NewUserRequest{\n\t\tNickname: msg.Nickname,\n\t\tGateUid: uid,\n\t}\n\tif err := s.RPC(\"TopicService.NewUser\", request); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\treturn s.Response(&LoginResponse{})\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n)\n\nfunc main() {\n \n methods()\n interfaces()\n typeAssertions()\n}\n\n\nfunc methods() {\n fmt.Println(\"Methods\")\n fmt.Println(\"=======\")\n\n swedishChef := Person{\n Phrase: \"Bork bork bork!\",\n }\n\n fmt.Printf(\"swedishChef says '%s'\\n\", swedishChef.Speak())\n\n myFloat := MyFloat(16.0)\n myFloat.Square()\n\n fmt.Printf(\"myFloat -> value = %f, squared = %f\\n\", myFloat, myFloat.Square())\n\n fmt.Println()\n}\n\n\n\nfunc typeAssertions() {\n fmt.Println(\"Type assertions\")\n fmt.Println(\"===============\")\n\n var i interface{} = \"All types match the empty interface\"\n\n \n f, ok := i.(float64)\n fmt.Printf(\"Type assertion results for float64 -> f = %f, ok = %t\\n\", f, ok)\n s, ok := i.(string)\n fmt.Printf(\"Type assertion results for string -> s = %s, ok = %t\\n\", s, ok)\n \n \n\n \n switch i.(type) {\n case int:\n fmt.Println(\"It's an int\")\n case string:\n fmt.Println(\"It's a string\")\n default:\n fmt.Println(\"Hell if I know\")\n }\n fmt.Println()\n}\n\nfunc interfaces() ", "output": "{\n fmt.Println(\"Interfaces\")\n fmt.Println(\"==========\")\n\n person := Person{\n Phrase: \"Hello\",\n Thought: \"Cogito ergo sum\",\n }\n \n \n dog := Dog{}\n\n var sentient Sentient\n \n sentient = person\n fmt.Printf(\"sentient says '%s' and thinks '%s'\\n\", sentient.Speak(), sentient.Reason())\n \n \n\n var speaker Speaker\n \n speaker = sentient\n fmt.Printf(\"sentient speaker says '%s'\\n\", speaker.Speak())\n speaker = dog\n fmt.Printf(\"non-sentient speaker says '%s'\\n\", speaker.Speak())\n speaker.Speak()\n\n fmt.Println()\n}"} {"input": "package catalog\n\nimport (\n\t\"github.com/hashicorp/nomad/helper/testlog\"\n\t\"github.com/hashicorp/nomad/nomad/structs/config\"\n\t\"github.com/hashicorp/nomad/plugins/shared/loader\"\n\t\"github.com/mitchellh/go-testing-interface\"\n)\n\n\n\n\n\nfunc TestPluginLoaderWithOptions(t testing.T,\n\tpluginDir string,\n\toptions map[string]string,\n\tconfigs []*config.PluginConfig) loader.PluginCatalog {\n\n\tlogger := testlog.HCLogger(t)\n\n\tcatalog := Catalog()\n\n\tinternal := make(map[loader.PluginID]*loader.InternalPluginConfig, len(catalog))\n\n\tfor id, reg := range catalog {\n\t\tif reg.Config == nil {\n\t\t\tlogger.Warn(\"skipping loading internal plugin because it is missing its configuration\", \"plugin\", id)\n\t\t\tcontinue\n\t\t}\n\n\t\tpluginConfig := reg.Config.Config\n\t\tif reg.ConfigLoader != nil {\n\t\t\tpc, err := reg.ConfigLoader(options)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"failed to retrieve config for internal plugin %v: %v\", id, err)\n\t\t\t}\n\n\t\t\tpluginConfig = pc\n\t\t}\n\n\t\tinternal[id] = &loader.InternalPluginConfig{\n\t\t\tFactory: reg.Config.Factory,\n\t\t\tConfig: pluginConfig,\n\t\t}\n\t}\n\n\tconfig := &loader.PluginLoaderConfig{\n\t\tLogger: logger,\n\t\tPluginDir: \"\",\n\t\tConfigs: configs,\n\t\tInternalPlugins: internal,\n\t}\n\tl, err := loader.NewPluginLoader(config)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create plugin loader: %v\", err)\n\t}\n\n\treturn l\n}\n\nfunc TestPluginLoader(t testing.T) loader.PluginCatalog ", "output": "{\n\treturn TestPluginLoaderWithOptions(t, \"\", nil, nil)\n}"} {"input": "package logs\n\nimport (\n\t\"io\"\n)\n\ntype stdoutWriter struct {\n\twriter io.Writer\n}\n\ntype stderrorWriter struct {\n\twriter io.Writer\n}\ntype stdbothWriter struct {\n\twriter io.Writer\n}\n\nfunc (w stdoutWriter) Write(message []byte) (n int, err error) {\n\tn, err = w.writer.Write(append([]byte(\"01 \"), message...))\n\treturn n - 3, err\n}\n\n\n\nfunc (w stdbothWriter) Write(message []byte) (n int, err error) {\n\tn, err = w.writer.Write(append([]byte(\"00 \"), message...))\n\treturn n - 3, err\n}\n\nfunc (w stderrorWriter) Write(message []byte) (n int, err error) ", "output": "{\n\tn, err = w.writer.Write(append([]byte(\"02 \"), message...))\n\treturn n - 3, err\n}"} {"input": "package remove_duplicates_from_sorted_array\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestRemoveDuplicates(t *testing.T) ", "output": "{\n\tnums := []int{1, 2, 3, 3, 5, 7, 7, 7, 11, 15}\n\tfmt.Println(removeDuplicates(nums), nums)\n\n\tnums = []int{1, 1, 2}\n\tfmt.Println(removeDuplicates(nums), nums)\n\n\tnums = []int{1}\n\tfmt.Println(removeDuplicates(nums), nums)\n\n\tnums = []int{}\n\tfmt.Println(removeDuplicates(nums), nums)\n}"} {"input": "package route\n\nimport \"github.com/berkaroad/saashard/sqlparser\"\n\n\n\nfunc (r *Router) buildKillQuery(statement *sqlparser.KillQuery) (*normalPlan, error) {\n\tschemaConfig := r.Schemas[r.SchemaName]\n\tplan := new(normalPlan)\n\n\tplan.nodeNames = []string{schemaConfig.Nodes[0]}\n\tplan.onSlave = true && !r.InTrans\n\tplan.anyNode = true\n\tplan.Statement = statement\n\treturn plan, nil\n}\n\nfunc (r *Router) buildKillConnection(statement *sqlparser.KillConnection) (*normalPlan, error) ", "output": "{\n\tschemaConfig := r.Schemas[r.SchemaName]\n\tplan := new(normalPlan)\n\n\tplan.nodeNames = []string{schemaConfig.Nodes[0]}\n\tplan.onSlave = true && !r.InTrans\n\tplan.anyNode = true\n\tplan.Statement = statement\n\treturn plan, nil\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\n\t\"github.com/ToQoz/gopwt\"\n\t\"github.com/ToQoz/gopwt/assert\"\n\n\t\"testing\"\n)\n\ntype myint int\n\nconst two myint = 2\n\n\n\nfunc TestFoo(t *testing.T) {\n\ta := myint(6)\n\tassert.OK(t, a == 3*two)\n}\n\nfunc TestMain(m *testing.M) ", "output": "{\n\tflag.Parse()\n\tgopwt.Empower()\n\tos.Exit(m.Run())\n}"} {"input": "package test\n\nimport (\n\t\"github.com/stellar/go/support/db\"\n\t\"github.com/stellar/horizon/ledger\"\n)\n\n\nfunc (t *T) CoreRepo() *db.Repo {\n\treturn &db.Repo{\n\t\tDB: t.CoreDB,\n\t\tCtx: t.Ctx,\n\t}\n}\n\n\n\nfunc (t *T) Finish() {\n\tRestoreLogger()\n\tledger.SetState(ledger.State{})\n\n\tif t.LogBuffer.Len() > 0 {\n\t\tt.T.Log(\"\\n\" + t.LogBuffer.String())\n\t}\n}\n\n\n\n\n\nfunc (t *T) Scenario(name string) *T {\n\tLoadScenario(name)\n\tt.UpdateLedgerState()\n\treturn t\n}\n\n\nfunc (t *T) ScenarioWithoutHorizon(name string) *T {\n\tLoadScenarioWithoutHorizon(name)\n\tt.UpdateLedgerState()\n\treturn t\n}\n\n\nfunc (t *T) UpdateLedgerState() {\n\tvar next ledger.State\n\n\terr := t.CoreRepo().GetRaw(&next, `\n\t\tSELECT\n\t\t\tCOALESCE(MIN(ledgerseq), 0) as core_elder,\n\t\t\tCOALESCE(MAX(ledgerseq), 0) as core_latest\n\t\tFROM ledgerheaders\n\t`)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = t.HorizonRepo().GetRaw(&next, `\n\t\t\tSELECT\n\t\t\t\tCOALESCE(MIN(sequence), 0) as history_elder,\n\t\t\t\tCOALESCE(MAX(sequence), 0) as history_latest\n\t\t\tFROM history_ledgers\n\t\t`)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tledger.SetState(next)\n\treturn\n}\n\nfunc (t *T) HorizonRepo() *db.Repo ", "output": "{\n\treturn &db.Repo{\n\t\tDB: t.HorizonDB,\n\t\tCtx: t.Ctx,\n\t}\n}"} {"input": "package remote\n\nimport (\n\t\"errors\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\n\n\ntype outputInterceptor struct {\n\tredirectFile *os.File\n\tintercepting bool\n}\n\nfunc (interceptor *outputInterceptor) StartInterceptingOutput() error {\n\tif interceptor.intercepting {\n\t\treturn errors.New(\"Already intercepting output!\")\n\t}\n\tinterceptor.intercepting = true\n\n\tvar err error\n\n\tinterceptor.redirectFile, err = ioutil.TempFile(\"\", \"ginkgo-output\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsyscallDup(int(interceptor.redirectFile.Fd()), 1)\n\tsyscallDup(int(interceptor.redirectFile.Fd()), 2)\n\n\treturn nil\n}\n\nfunc (interceptor *outputInterceptor) StopInterceptingAndReturnOutput() (string, error) {\n\tif !interceptor.intercepting {\n\t\treturn \"\", errors.New(\"Not intercepting output!\")\n\t}\n\n\tinterceptor.redirectFile.Close()\n\toutput, err := ioutil.ReadFile(interceptor.redirectFile.Name())\n\tos.Remove(interceptor.redirectFile.Name())\n\n\tinterceptor.intercepting = false\n\n\treturn string(output), err\n}\n\nfunc NewOutputInterceptor() OutputInterceptor ", "output": "{\n\treturn &outputInterceptor{}\n}"} {"input": "package test\n\nimport \"io\"\n\n\ntype PlainReader struct {\n\tr io.Reader\n}\n\n\nfunc NewPlainReader(r io.Reader) *PlainReader {\n\treturn &PlainReader{r}\n}\n\n\nfunc (r *PlainReader) Read(p []byte) (int, error) {\n\treturn r.r.Read(p)\n}\n\n\n\n\ntype ErrorReader struct {\n\tn int\n}\n\n\nfunc NewErrorReader(n int) *ErrorReader {\n\treturn &ErrorReader{n}\n}\n\n\nfunc (r *ErrorReader) Read(b []byte) (n int, err error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tif r.n == 0 {\n\t\treturn 0, ErrPlain\n\t}\n\tr.n--\n\tb[0] = '.'\n\treturn 1, nil\n}\n\n\n\n\ntype InfiniteReader struct{}\n\n\n\n\n\nfunc (r *InfiniteReader) Read(b []byte) (n int, err error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tb[0] = '.'\n\treturn 1, nil\n}\n\n\n\n\ntype EmptyReader struct {\n}\n\n\nfunc NewEmptyReader() *EmptyReader {\n\treturn &EmptyReader{}\n}\n\n\nfunc (r *EmptyReader) Read(b []byte) (n int, err error) {\n\treturn 0, io.EOF\n}\n\nfunc NewInfiniteReader() *InfiniteReader ", "output": "{\n\treturn &InfiniteReader{}\n}"} {"input": "package ast\n\nimport \"github.com/orktes/orlang/scanner\"\n\ntype UnaryExpression struct {\n\tExpression\n\tOperator scanner.Token\n\tPostfix bool\n}\n\nfunc (u *UnaryExpression) StartPos() Position {\n\tif u.Postfix {\n\t\treturn u.Expression.StartPos()\n\t}\n\treturn StartPositionFromToken(u.Operator)\n}\n\n\n\nfunc (_ *UnaryExpression) exprNode() {}\n\nfunc (u *UnaryExpression) EndPos() Position ", "output": "{\n\tif u.Postfix {\n\t\treturn EndPositionFromToken(u.Operator)\n\t}\n\treturn u.Expression.EndPos()\n}"} {"input": "package toolbox_test\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/viant/toolbox\"\n)\n\nfunc TestEncoderFactory(t *testing.T) {\n\tbuffer := new(bytes.Buffer)\n\tassert.NotNil(t, toolbox.NewJSONEncoderFactory().Create(buffer))\n}\n\nfunc TestMarshalEncoderFactory(t *testing.T) {\n\tbuffer := new(bytes.Buffer)\n\tencoder := toolbox.NewMarshalerEncoderFactory().Create(buffer)\n\tfoo := &Foo200{\"abc\"}\n\terr := encoder.Encode(foo)\n\tassert.Nil(t, err)\n\tassert.Equal(t, \"abc\", string(buffer.Bytes()))\n\terr = encoder.Encode(&Foo201{})\n\tassert.NotNil(t, err)\n}\n\ntype Foo200 struct {\n\tAttr string\n}\n\n\n\ntype Foo201 struct {\n\tAttr string\n}\n\nfunc (m *Foo200) Marshal() ([]byte, error) ", "output": "{\n\treturn []byte(m.Attr), nil\n}"} {"input": "package co\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\n\t\"github.com/pkg/errors\"\n\n\t\"github.com/ynqa/wego/pkg/corpus/cooccurrence/encode\"\n)\n\ntype CountType = string\n\nconst (\n\tIncrement CountType = \"inc\"\n\tProximity CountType = \"prox\"\n)\n\nfunc invalidCountTypeError(typ CountType) error {\n\treturn fmt.Errorf(\"invalid relation type: %s not in %s|%s\", typ, Increment, Proximity)\n}\n\ntype Cooccurrence struct {\n\ttyp CountType\n\n\tma map[uint64]float64\n}\n\nfunc New(typ CountType) (*Cooccurrence, error) {\n\tif typ != Increment && typ != Proximity {\n\t\treturn nil, invalidCountTypeError(typ)\n\t}\n\treturn &Cooccurrence{\n\t\ttyp: typ,\n\n\t\tma: make(map[uint64]float64),\n\t}, nil\n}\n\nfunc (c *Cooccurrence) EncodedMatrix() map[uint64]float64 {\n\treturn c.ma\n}\n\n\n\nfunc (c *Cooccurrence) Add(left, right int) error ", "output": "{\n\tenc := encode.EncodeBigram(uint64(left), uint64(right))\n\tvar val float64\n\tswitch c.typ {\n\tcase Increment:\n\t\tval = 1\n\tcase Proximity:\n\t\tdiv := left - right\n\t\tif div == 0 {\n\t\t\treturn errors.Errorf(\"Divide by zero on counting co-occurrence\")\n\t\t}\n\t\tval = 1. / math.Abs(float64(div))\n\tdefault:\n\t\treturn invalidCountTypeError(c.typ)\n\t}\n\tc.ma[enc] += val\n\treturn nil\n}"} {"input": "package xmlkey\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/xml\"\n\t\"math/big\"\n)\n\ntype (\n\tkeyXML struct {\n\t\tXMLName xml.Name `xml:\"RSAKeyValue\"`\n\t\tpublicKeyXML\n\t\tprivateKeyXML\n\t}\n\n\tpublicKeyXML struct {\n\t\tModulus, Exponent *bigInt\n\t}\n\tprivateKeyXML struct {\n\t\tP, Q, DP, DQ, D, InverseQ *bigInt\n\t}\n\n\tbigInt struct{ *big.Int }\n)\n\nfunc (k keyXML) HasPublicKey() bool {\n\treturn allNotEmpty(k.Exponent, k.Modulus)\n}\n\n\n\nfunc allNotEmpty(bis ...*bigInt) bool {\n\tfor _, bi := range bis {\n\t\tif bi == nil || bi.IsEmpty() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (bi *bigInt) UnmarshalText(text []byte) error {\n\tbs := make([]byte, base64.StdEncoding.DecodedLen(len(text)))\n\tif _, err := base64.StdEncoding.Decode(bs, text); err != nil {\n\t\treturn err\n\t}\n\tif bi.Int == nil {\n\t\tbi.Int = new(big.Int)\n\t}\n\tbi.Int.SetBytes(bytes.TrimRight(bs, \"\\x00\"))\n\treturn nil\n}\n\nfunc (bi *bigInt) MarshalText() ([]byte, error) {\n\ttext := make([]byte, base64.StdEncoding.EncodedLen(len(bi.Bytes())))\n\tbase64.StdEncoding.Encode(text, bi.Bytes())\n\treturn text, nil\n}\n\nfunc (bi bigInt) BigInt() *big.Int {\n\treturn bi.Int\n}\n\nfunc (bi bigInt) Integer() int {\n\treturn int(bi.Int64())\n}\n\nfunc (bi bigInt) IsEmpty() bool {\n\treturn bi.Int == nil\n}\n\nfunc (k keyXML) HasPrivateKey() bool ", "output": "{\n\treturn allNotEmpty(k.D, k.DP, k.DQ, k.InverseQ, k.P, k.Q)\n}"} {"input": "package state\n\nimport (\n\t\"context\"\n)\n\ntype envKey struct{}\n\n\n\nfunc ContextWith(ctx context.Context, s Store) context.Context {\n\treturn context.WithValue(ctx, envKey{}, s)\n}\n\n\n\n\nfunc FromContext(ctx context.Context) Store {\n\tif e, ok := ctx.Value(envKey{}).(Store); ok {\n\t\treturn e\n\t}\n\tpanic(\"no Store found in context\")\n}\n\n\ntype fail interface {\n\tError(args ...interface{})\n}\n\n\n\n\n\nfunc GetOrFail(ctx context.Context, t fail, key string, value interface{}) {\n\tstate := FromContext(ctx)\n\tif err := state.Get(ctx, key, value); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\n\nfunc SetOrFail(ctx context.Context, t fail, key string, value interface{}) {\n\tstate := FromContext(ctx)\n\tif err := state.Set(ctx, key, value); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc GetStringOrFail(ctx context.Context, t fail, key string) string ", "output": "{\n\tvalue := \"\"\n\tstate := FromContext(ctx)\n\tif err := state.Get(ctx, key, &value); err != nil {\n\t\tt.Error(err)\n\t}\n\treturn value\n}"} {"input": "package common\n\nimport (\n\t\"io/ioutil\"\n\n\t\"github.com/hyperledger/fabric/cmd/common/comm\"\n\t\"github.com/hyperledger/fabric/cmd/common/signer\"\n\t\"github.com/pkg/errors\"\n\tyaml \"gopkg.in/yaml.v2\"\n)\n\n\ntype Config struct {\n\tVersion int\n\tTLSConfig comm.Config\n\tSignerConfig signer.Config\n}\n\n\nfunc ConfigFromFile(file string) (Config, error) {\n\tconfigData, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn Config{}, errors.WithStack(err)\n\t}\n\tconfig := Config{}\n\n\tif err := yaml.Unmarshal([]byte(configData), &config); err != nil {\n\t\treturn Config{}, errors.Errorf(\"error unmarshaling YAML file %s: %s\", file, err)\n\t}\n\n\treturn config, validateConfig(config)\n}\n\n\n\n\nfunc validateConfig(conf Config) error {\n\tnonEmptyStrings := []string{\n\t\tconf.SignerConfig.MSPID,\n\t\tconf.SignerConfig.IdentityPath,\n\t\tconf.SignerConfig.KeyPath,\n\t}\n\n\tfor _, s := range nonEmptyStrings {\n\t\tif s == \"\" {\n\t\t\treturn errors.New(\"empty string that is mandatory\")\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (c Config) ToFile(file string) error ", "output": "{\n\tif err := validateConfig(c); err != nil {\n\t\treturn errors.Wrap(err, \"config isn't valid\")\n\t}\n\tb, _ := yaml.Marshal(c)\n\tif err := ioutil.WriteFile(file, b, 0o600); err != nil {\n\t\treturn errors.Errorf(\"failed writing file %s: %v\", file, err)\n\t}\n\treturn nil\n}"} {"input": "package sqlite\n\nimport (\n\t\"testing\"\n\n\t\"github.com/anmil/quicknote/test\"\n)\n\nvar tableNames = []string{\n\t\"books\",\n\t\"note_book_tag\",\n\t\"note_tag\",\n\t\"notes\",\n\t\"sqlite_sequence\",\n\t\"tags\",\n}\n\n\n\nfunc closeDatabase(db *Database, t *testing.T) {\n\tif err := db.Close(); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestCreateDatabaseSQLite(t *testing.T) {\n\tdb := openDatabase(t)\n\tdefer closeDatabase(db, t)\n\n\tif tables, err := db.GetTableNames(); err != nil {\n\t\tt.Fatal(err)\n\t} else if !test.StringSliceEq(tables, tableNames) {\n\t\tt.Fatal(\"Database either has extra or is missing tables\")\n\t}\n}\n\nfunc openDatabase(t *testing.T) *Database ", "output": "{\n\tdb, err := NewDatabase(\"file::memory:?cache=shared\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treturn db\n}"} {"input": "package imageutil\n\nimport (\n \"bytes\"\n \"encoding/hex\"\n \"crypto/sha256\"\n \"testing\"\n)\n\nfunc TestReadRgbaPng(t *testing.T) {\n goldImageHash :=\n \"d333fb91aa05709483df2d00f62e3caa91db0be1b30ff72e8e829f3264cb30b9\"\n\n image, err := ReadRgbaPng(\"test_data/fruits.png\")\n if err != nil {\n t.Fatal(err)\n }\n\n if image.Rect.Min.X != 0 || image.Rect.Max.X != 512 ||\n image.Rect.Min.Y != 0 || image.Rect.Max.Y != 512 {\n t.Errorf(\"Incorrect image rectangle: %v\\n\", image.Rect)\n }\n\n hash := sha256.Sum256(image.Pix)\n imageHash := hex.EncodeToString(hash[:])\n if imageHash != goldImageHash {\n t.Error(\"Pixel data hash mismatch. Got :\", imageHash)\n }\n}\n\n\n\nfunc TestRgbaToPng(t *testing.T) ", "output": "{\n image, err := ReadRgbaPng(\"test_data/fruits.png\")\n if err != nil {\n t.Fatal(err)\n }\n\n err = RgbaToPng(image.Pix, image.Bounds().Dx(), image.Bounds().Dy(),\n \"test_tmp/fruits_RgbaToPng.png\")\n if err != nil {\n t.Fatal(err)\n }\n\n recodedImage, err := ReadRgbaPng(\"test_tmp/fruits_RgbaToPng.png\")\n if err != nil {\n t.Fatal(err)\n }\n if !bytes.Equal(image.Pix, recodedImage.Pix) {\n t.Error(\"Pixel data mismatch\")\n }\n}"} {"input": "package adt\n\ntype Stack struct {\n\ttop *Element\n\tsize int\n}\n \ntype Element struct {\n\tvalue interface{} \n\tnext *Element\n}\n\n\nfunc NewStack() *Stack {\n\treturn new(Stack)\n\n}\n\n\n\n\n\nfunc (s *Stack) IsEmpty() bool {\n\treturn s.Len()==0\n}\n\n\nfunc (s *Stack) Push(value interface{}) {\n\ts.top = &Element{value, s.top}\n\ts.size++\n}\n \n\n\nfunc (s *Stack) Pop() (value interface{}) {\n\tif s.size > 0 {\n\t\tvalue, s.top = s.top.value, s.top.next\n\t\ts.size--\n\t\treturn\n\t}\n\treturn nil\n}\n\nfunc (s *Stack) Len() int ", "output": "{\n\treturn s.size\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CopyVolumeGroupBackupRequest struct {\n\n\tVolumeGroupBackupId *string `mandatory:\"true\" contributesTo:\"path\" name:\"volumeGroupBackupId\"`\n\n\tCopyVolumeGroupBackupDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CopyVolumeGroupBackupRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CopyVolumeGroupBackupRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CopyVolumeGroupBackupRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype CopyVolumeGroupBackupResponse struct {\n\n\tRawResponse *http.Response\n\n\tVolumeGroupBackup `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CopyVolumeGroupBackupResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CopyVolumeGroupBackupResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CopyVolumeGroupBackupRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package mpd\n\nimport (\n\t\"errors\"\n\t\"testing\"\n)\n\n\n\nfunc TestAckError(t *testing.T) ", "output": "{\n\tfor _, tt := range []struct {\n\t\tcmdErr error\n\t\tackErr error\n\t}{\n\t\t{cmdErr: &CommandError{ID: 1}, ackErr: ErrNotList},\n\t\t{cmdErr: &CommandError{ID: 50}, ackErr: ErrNoExist},\n\t} {\n\t\tif !errors.Is(tt.cmdErr, tt.ackErr) {\n\t\t\tt.Errorf(\"%+v != %+v\", tt.cmdErr, tt.ackErr)\n\t\t}\n\t}\n}"} {"input": "package travel\n\nimport (\n\t\"os\"\n\n\t\"github.com/akerl/speculate/v2/creds\"\n)\n\nfunc clearEnvironment() error {\n\tfor varName := range creds.Translations[\"envvar\"] {\n\t\tlogger.InfoMsgf(\"Unsetting env var: %s\", varName)\n\t\terr := os.Unsetenv(varName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc stringInSlice(list []string, key string) bool {\n\tfor _, item := range list {\n\t\tif item == key {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc sliceUnion(a []string, b []string) []string {\n\tvar res []string\n\tfor _, item := range a {\n\t\tif stringInSlice(b, item) {\n\t\t\tres = append(res, item)\n\t\t}\n\t}\n\treturn res\n}\n\ntype attrFunc func(Path) string\n\n\n\nfunc filterPathsByAttribute(paths []Path, match string, af attrFunc) []Path {\n\tfilteredPaths := []Path{}\n\tfor _, item := range paths {\n\t\tif af(item) == match {\n\t\t\tfilteredPaths = append(filteredPaths, item)\n\t\t}\n\t}\n\treturn filteredPaths\n}\n\nfunc uniquePathAttributes(paths []Path, af attrFunc) []string ", "output": "{\n\ttmpMap := map[string]bool{}\n\tfor _, item := range paths {\n\t\tattr := af(item)\n\t\ttmpMap[attr] = true\n\t}\n\ttmpList := []string{}\n\tfor item := range tmpMap {\n\t\ttmpList = append(tmpList, item)\n\t}\n\treturn tmpList\n}"} {"input": "package closer\n\nimport (\n\t\"sync\"\n)\n\ntype Closer struct {\n\tIsClosedChan chan struct{}\n\n\tf func()\n\tmutex sync.Mutex\n}\n\n\n\nfunc New(f func()) *Closer {\n\treturn &Closer{\n\t\tIsClosedChan: make(chan struct{}),\n\t\tf: f,\n\t}\n}\n\n\n\n\n\nfunc (c *Closer) IsClosed() bool {\n\tselect {\n\tcase <-c.IsClosedChan:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc (c *Closer) Close() ", "output": "{\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tif c.IsClosed() {\n\t\treturn\n\t}\n\n\tclose(c.IsClosedChan)\n\n\tc.f()\n}"} {"input": "package login_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestLogin(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Login Suite\")\n}"} {"input": "package identity\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype DeleteUserRequest struct {\n\n\tUserId *string `mandatory:\"true\" contributesTo:\"path\" name:\"userId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteUserRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteUserRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\n\n\n\ntype DeleteUserResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteUserResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteUserResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteUserRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package models\n\nimport (\n\t\"fmt\"\n\n\t\"google.golang.org/protobuf/reflect/protoreflect\"\n\t\"google.golang.org/protobuf/types/known/fieldmaskpb\"\n)\n\n\nfunc ValidateMask(message protoreflect.ProtoMessage, mask *fieldmaskpb.FieldMask) error {\n\tif mask == nil {\n\t\treturn nil\n\t}\n\n\tif len(mask.GetPaths()) == 1 && mask.Paths[0] == \"*\" {\n\t\treturn nil\n\t}\n\n\tunknowns := make([]string, 0)\n\tfor _, field := range mask.GetPaths() {\n\t\tif _, err := fieldmaskpb.New(message, field); err != nil {\n\t\t\tunknowns = append(unknowns, field)\n\t\t}\n\t}\n\n\tif len(unknowns) > 0 {\n\t\treturn fmt.Errorf(\"unrecognized fields %v\", unknowns)\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc ExpandMask(m protoreflect.ProtoMessage, mask *fieldmaskpb.FieldMask) *fieldmaskpb.FieldMask {\n\tif mask == nil || len(mask.GetPaths()) == 0 {\n\t\treturn populatedFields(m)\n\t} else if len(mask.GetPaths()) == 1 && mask.Paths[0] == \"*\" {\n\t\treturn allFields(m)\n\t}\n\n\tmask.Normalize()\n\treturn mask\n}\n\n\n\nfunc allFields(m protoreflect.ProtoMessage) *fieldmaskpb.FieldMask {\n\tmask, _ := fieldmaskpb.New(m)\n\n\tfields := m.ProtoReflect().Descriptor().Fields()\n\tfor i := 0; i < fields.Len(); i++ {\n\t\t_ = mask.Append(m, string(fields.Get(i).Name()))\n\t}\n\n\treturn mask\n}\n\nfunc populatedFields(m protoreflect.ProtoMessage) *fieldmaskpb.FieldMask ", "output": "{\n\tmask, _ := fieldmaskpb.New(m)\n\n\tm.ProtoReflect().Range(func(field protoreflect.FieldDescriptor, _ protoreflect.Value) bool {\n\t\t_ = mask.Append(m, string(field.Name()))\n\t\treturn true \n\t})\n\n\treturn mask\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"time\"\n \"log\"\n \n\n \"gomud/connections\"\n \n \n zmq \"github.com/pebbe/zmq4\"\n)\n\nconst noFlags = 0\n\nfunc main() {\n server, err := connections.CreateServer()\n defer server.Close()\n if err == nil {\n waitForPlayersOn(server)\n } else {\n log.Fatal(err)\n }\n}\n\n\n\nfunc waitForPlayersOn(server *zmq.Socket) ", "output": "{\n \n for {\n \n msg, _ := server.Recv(noFlags)\n fmt.Println(\"Received \", msg)\n\n \n time.Sleep(time.Second)\n\n \n reply := \"World\"\n server.Send(reply, noFlags)\n }\n}"} {"input": "package client\n\n\n\n\nimport (\n\t\"github.com/go-openapi/runtime\"\n\thttptransport \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/jkawamoto/roadie/cloud/azure/subscriptions/client/subscriptions\"\n\t\"github.com/jkawamoto/roadie/cloud/azure/subscriptions/client/tenants\"\n)\n\n\nvar Default = NewHTTPClient(nil)\n\n\nfunc NewHTTPClient(formats strfmt.Registry) *SubscriptionClient {\n\tif formats == nil {\n\t\tformats = strfmt.Default\n\t}\n\ttransport := httptransport.New(\"management.azure.com\", \"/\", []string{\"https\"})\n\treturn New(transport, formats)\n}\n\n\nfunc New(transport runtime.ClientTransport, formats strfmt.Registry) *SubscriptionClient {\n\tcli := new(SubscriptionClient)\n\tcli.Transport = transport\n\n\tcli.Subscriptions = subscriptions.New(transport, formats)\n\n\tcli.Tenants = tenants.New(transport, formats)\n\n\treturn cli\n}\n\n\ntype SubscriptionClient struct {\n\tSubscriptions *subscriptions.Client\n\n\tTenants *tenants.Client\n\n\tTransport runtime.ClientTransport\n}\n\n\n\n\nfunc (c *SubscriptionClient) SetTransport(transport runtime.ClientTransport) ", "output": "{\n\tc.Transport = transport\n\n\tc.Subscriptions.SetTransport(transport)\n\n\tc.Tenants.SetTransport(transport)\n\n}"} {"input": "package dockershim\n\nimport (\n\t\"context\"\n\n\truntimeapi \"k8s.io/cri-api/pkg/apis/runtime/v1alpha2\"\n)\n\n\n\n\n\nfunc (ds *dockerService) ListContainerStats(ctx context.Context, r *runtimeapi.ListContainerStatsRequest) (*runtimeapi.ListContainerStatsResponse, error) {\n\tcontainerStatsFilter := r.GetFilter()\n\tfilter := &runtimeapi.ContainerFilter{}\n\n\tif containerStatsFilter != nil {\n\t\tfilter.Id = containerStatsFilter.Id\n\t\tfilter.PodSandboxId = containerStatsFilter.PodSandboxId\n\t\tfilter.LabelSelector = containerStatsFilter.LabelSelector\n\t}\n\n\tlistResp, err := ds.ListContainers(ctx, &runtimeapi.ListContainersRequest{Filter: filter})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar stats []*runtimeapi.ContainerStats\n\tfor _, container := range listResp.Containers {\n\t\tcontainerStats, err := ds.getContainerStats(container.Id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif containerStats != nil {\n\t\t\tstats = append(stats, containerStats)\n\t\t}\n\t}\n\n\treturn &runtimeapi.ListContainerStatsResponse{Stats: stats}, nil\n}\n\nfunc (ds *dockerService) ContainerStats(_ context.Context, r *runtimeapi.ContainerStatsRequest) (*runtimeapi.ContainerStatsResponse, error) ", "output": "{\n\tstats, err := ds.getContainerStats(r.ContainerId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &runtimeapi.ContainerStatsResponse{Stats: stats}, nil\n}"} {"input": "package collector\n\nimport (\n\t\"fullerite/metric\"\n\t\"math/rand\"\n)\n\n\ntype Test struct {\n\tinterval int\n\tchannel chan metric.Metric\n}\n\n\nfunc NewTest() *Test {\n\tt := new(Test)\n\tt.channel = make(chan metric.Metric)\n\treturn t\n}\n\n\nfunc (t Test) Collect() {\n\tmetric := metric.New(\"TestMetric\")\n\tmetric.Value = rand.Float64()\n\tmetric.AddDimension(\"testing\", \"yes\")\n\tt.Channel() <- metric\n}\n\n\n\n\n\nfunc (t Test) Interval() int {\n\treturn t.interval\n}\n\n\n\nfunc (t Test) Channel() chan metric.Metric {\n\treturn t.channel\n}\n\n\nfunc (t Test) String() string {\n\treturn t.Name() + \"Collector\"\n}\n\n\nfunc (t *Test) SetInterval(interval int) {\n\tt.interval = interval\n}\n\nfunc (t Test) Name() string ", "output": "{\n\treturn \"Test\"\n}"} {"input": "package osc\n\nimport (\n\t\"encoding/base64\"\n\t\"regexp\"\n)\n\n\n\nfunc base64Encode(data []byte) string {\n\tif isBase64Encoded(data) {\n\t\treturn string(data)\n\t}\n\treturn base64.StdEncoding.EncodeToString(data)\n}\n\nfunc isBase64Encoded(data []byte) bool {\n\t_, err := base64.StdEncoding.DecodeString(string(data))\n\treturn err == nil\n}\n\n\n\nfunc looksLikeJsonString(s interface{}) bool ", "output": "{\n\treturn regexp.MustCompile(`^\\s*{`).MatchString(s.(string))\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSDynamoDBTable_TimeToLiveSpecification struct {\n\n\tAttributeName string `json:\"AttributeName,omitempty\"`\n\n\tEnabled bool `json:\"Enabled\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) AWSCloudFormationType() string {\n\treturn \"AWS::DynamoDB::Table.TimeToLiveSpecification\"\n}\n\n\n\n\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) DependsOn() []string ", "output": "{\n\treturn r._dependsOn\n}"} {"input": "package influxdb\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/url\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/fractalplatform/fractal/metrics\"\n\tclient \"github.com/influxdata/influxdb1-client\"\n)\n\nconst (\n\tdburl = \"http://localhost:8086\"\n\ttestdb = \"testmetrics\"\n\tusername = \"\"\n\tpassword = \"\"\n\tnamespace = \"test/\"\n\tprefix = \"test\"\n\ttable = namespace + prefix + \".timer\"\n)\n\nfunc TestWrite(t *testing.T) {\n\tgo InfluxDBWithTags(metrics.DefaultRegistry, 1*time.Second, dburl, testdb, \"\", \"\", namespace, make(map[string]string))\n\ttm := metrics.NewRegisteredTimer(prefix, nil)\n\tfor i := 0; i < 5; i++ {\n\t\ttm.Update(100 * time.Second)\n\t}\n\ttime.Sleep(time.Duration(10) * time.Second)\n}\n\n\n\nfunc TestQuery(t *testing.T) ", "output": "{\n\thost, err := url.Parse(dburl)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcon, err := client.NewClient(client.Config{URL: *host})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tq := client.Query{\n\t\tCommand: fmt.Sprintf(`select * from \"%s\"`, table),\n\t\tDatabase: testdb,\n\t}\n\tif response, err := con.Query(q); err == nil && response.Error() == nil {\n\t\tlog.Println(response.Results)\n\t}\n}"} {"input": "package chart\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\ntype CT_Thickness struct {\n\tValAttr ST_Thickness\n}\n\nfunc NewCT_Thickness() *CT_Thickness {\n\tret := &CT_Thickness{}\n\treturn ret\n}\n\n\n\nfunc (m *CT_Thickness) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"val\" {\n\t\t\tparsed, err := ParseUnionST_Thickness(attr.Value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.ValAttr = parsed\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_Thickness: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (m *CT_Thickness) Validate() error {\n\treturn m.ValidateWithPath(\"CT_Thickness\")\n}\n\n\nfunc (m *CT_Thickness) ValidateWithPath(path string) error {\n\tif err := m.ValAttr.ValidateWithPath(path + \"/ValAttr\"); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (m *CT_Thickness) MarshalXML(e *xml.Encoder, start xml.StartElement) error ", "output": "{\n\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"val\"},\n\t\tValue: fmt.Sprintf(\"%v\", m.ValAttr)})\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}"} {"input": "package v1\n\n\n\ntype EnvVarApplyConfiguration struct {\n\tName *string `json:\"name,omitempty\"`\n\tValue *string `json:\"value,omitempty\"`\n\tValueFrom *EnvVarSourceApplyConfiguration `json:\"valueFrom,omitempty\"`\n}\n\n\n\nfunc EnvVar() *EnvVarApplyConfiguration {\n\treturn &EnvVarApplyConfiguration{}\n}\n\n\n\n\n\n\n\n\n\nfunc (b *EnvVarApplyConfiguration) WithValue(value string) *EnvVarApplyConfiguration {\n\tb.Value = &value\n\treturn b\n}\n\n\n\n\nfunc (b *EnvVarApplyConfiguration) WithValueFrom(value *EnvVarSourceApplyConfiguration) *EnvVarApplyConfiguration {\n\tb.ValueFrom = value\n\treturn b\n}\n\nfunc (b *EnvVarApplyConfiguration) WithName(value string) *EnvVarApplyConfiguration ", "output": "{\n\tb.Name = &value\n\treturn b\n}"} {"input": "package HeatersController\n\nimport (\n\t\"errors\"\n\n\t\"github.com/stianeikeland/go-rpio\"\n)\n\nvar heaters [3]rpio.Pin\n\nfunc init() {\n\trpio.Open()\n\n\theaters[0] = rpio.Pin(26)\n\theaters[1] = rpio.Pin(20)\n\theaters[2] = rpio.Pin(21)\n\n\theaters[0].Output()\n\theaters[1].Output()\n\theaters[2].Output()\n\n\theaters[0].High()\n\theaters[1].High()\n\theaters[2].High()\n}\n\n\nfunc SetNumberOfWorkingHeaters(num int) error {\n\tif num == 0 {\n\t\theaters[0].High()\n\t\theaters[1].High()\n\t\theaters[2].High()\n\t} else if num == 1 {\n\t\theaters[0].Low()\n\t\theaters[1].High()\n\t\theaters[2].High()\n\t} else if num == 2 {\n\t\theaters[0].Low()\n\t\theaters[1].Low()\n\t\theaters[2].High()\n\t} else if num == 3 {\n\t\theaters[0].Low()\n\t\theaters[1].Low()\n\t\theaters[2].Low()\n\t} else {\n\t\treturn errors.New(\"The num argument should be between 0 and 3 inclusive\")\n\t}\n\n\treturn nil\n}\n\n\nfunc TurnOn(heaterID int) {\n\theaters[heaterID-1].Low()\n}\n\n\n\n\n\nfunc GetNumberOfWorkingHeaters() int {\n\tresult := 0\n\tif heaters[0].Read() == rpio.Low {\n\t\tresult++\n\t}\n\n\tif heaters[1].Read() == rpio.Low {\n\t\tresult++\n\t}\n\n\tif heaters[2].Read() == rpio.Low {\n\t\tresult++\n\t}\n\n\treturn result\n}\n\nfunc TurnOff(heaterID int) ", "output": "{\n\theaters[heaterID-1].High()\n}"} {"input": "package bunyan\n\nimport \"fmt\"\n\n\ntype Logger struct {\n\tsink Sink\n\trecord Record\n}\n\n\nfunc NewLogger(target Sink) *Logger {\n\treturn &Logger{target, NewRecord()}\n}\n\n\n\nfunc (l *Logger) Write(record Record) error {\n\trecord.TemplateMerge(l.record)\n\treturn l.sink.Write(record)\n}\n\n\n\nfunc (l *Logger) Include(info Info) Log {\n\treturn NewLogger(InfoSink(l, info))\n}\n\n\n\nfunc (l *Logger) Record(key string, value interface{}) Log {\n\tbuilder := NewLogger(l)\n\tbuilder.record[key] = value\n\treturn builder\n}\n\n\n\nfunc (l *Logger) Recordf(key, value string, args ...interface{}) Log {\n\treturn l.Record(key, fmt.Sprintf(value, args...))\n}\n\n\n\n\n\nfunc (l *Logger) Tracef(msg string, args ...interface{}) { l.send(TRACE, msg, args...) }\nfunc (l *Logger) Debugf(msg string, args ...interface{}) { l.send(DEBUG, msg, args...) }\nfunc (l *Logger) Infof(msg string, args ...interface{}) { l.send(INFO, msg, args...) }\nfunc (l *Logger) Warnf(msg string, args ...interface{}) { l.send(WARN, msg, args...) }\nfunc (l *Logger) Errorf(msg string, args ...interface{}) { l.send(ERROR, msg, args...) }\nfunc (l *Logger) Fatalf(msg string, args ...interface{}) { l.send(FATAL, msg, args...) }\n\nfunc (l *Logger) send(level Level, msg string, args ...interface{}) {\n\trecord := NewRecord()\n\trecord.SetMessagef(level, msg, args...)\n\te := l.Write(record)\n\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc (l *Logger) Child() Log ", "output": "{\n\treturn NewLogger(l)\n}"} {"input": "package client\n\nimport \"net\"\n\ntype Request struct {\n\tConn net.Conn\n\tPassword string\n\tNetworkName string\n}\n\ntype Server struct {\n\tAddr string\n\n\tlistener net.Listener\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (s *Server) Close() error {\n\tif s.listener == nil {\n\t\treturn nil\n\t}\n\n\treturn s.listener.Close()\n}\n\nfunc (s *Server) Listen() (chan *Request, error) ", "output": "{\n\tlistener, err := net.Listen(\"tcp\", s.Addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout := make(chan *Request)\n\ts.listener = listener\n\treturn out, nil\n}"} {"input": "package unix\n\nimport \"syscall\"\n\nfunc setTimespec(sec, nsec int64) Timespec {\n\treturn Timespec{Sec: int32(sec), Nsec: int32(nsec)}\n}\n\nfunc setTimeval(sec, usec int64) Timeval {\n\treturn Timeval{Sec: int32(sec), Usec: int32(usec)}\n}\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint32(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\n\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\nfunc (msghdr *Msghdr) SetIovlen(length int) {\n\tmsghdr.Iovlen = int32(length)\n}\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\nfunc Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)\n\nfunc (iov *Iovec) SetLen(length int) ", "output": "{\n\tiov.Len = uint32(length)\n}"} {"input": "package buffer\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\n\t\"player/logger\"\n\n\t\"github.com/djherbis/buffer\"\n\t\"github.com/op/go-libspotify/spotify\"\n)\n\n\ntype Spotify struct {\n\tfile *os.File \n\tbuffer buffer.Buffer \n\tbuffered int \n\tsession *spotify.Session \n\twg sync.WaitGroup\n\tcloseC chan bool\n}\n\n\nfunc (s *Spotify) Read(b []byte) (int, error) {\n\tif s.buffer == nil {\n\t\treturn 0, io.ErrShortBuffer\n\t}\n\tif s.buffered < 64*1024 {\n\t\treturn 0, io.ErrShortBuffer\n\t}\n\tif s.buffer.Len() == 0 {\n\t\treturn 0, io.EOF\n\t}\n\treturn s.buffer.Read(b)\n}\n\nfunc (s *Spotify) Close() error {\n\tlogger.Debug(\"close spotify buffer\")\n\tdefer logger.Debug(\"closed spotify buffer\")\n\tclose(s.closeC)\n\ts.wg.Wait()\n\treturn nil\n}\n\n\nfunc (s *Spotify) WriteAudio(f spotify.AudioFormat, raw []byte) int {\n\tselect {\n\tcase <-s.closeC:\n\t\treturn 0\n\tdefault:\n\t\ti, err := s.buffer.Write(raw)\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Error(\"error writting audio\")\n\t\t}\n\t\ts.buffered += i\n\t\treturn i\n\t}\n}\n\n\n\nfunc SpotifyBuffer(session *spotify.Session) *Spotify {\n\treturn &Spotify{\n\t\tsession: session,\n\t\tcloseC: make(chan bool),\n\t}\n}\n\nfunc (s *Spotify) Buffer(track *spotify.Track) error ", "output": "{\n\ts.wg.Add(1)\n\tdefer s.wg.Done()\n\tlogger.Debug(\"start spotify buffer\")\n\tdefer logger.Debug(\"exit spotify buffer\")\n\tbuf := buffer.NewPartition(buffer.NewMemPool(128 * 1024))\n\ts.buffer = buf\n\tplayer := s.session.Player()\n\tif err := player.Prefetch(track); err != nil {\n\t\treturn err\n\t}\n\tif err := player.Load(track); err != nil {\n\t\treturn err\n\t}\n\tplayer.Play()\n\tdefer player.Unload() \n\tselect {\n\tcase <-s.session.EndOfTrackUpdates():\n\t\tlogger.Debug(\"end of track updates\")\n\t\treturn nil\n\tcase <-s.closeC:\n\t\treturn nil\n\t}\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSGameLiftBuild_S3Location struct {\n\n\tBucket string `json:\"Bucket,omitempty\"`\n\n\tKey string `json:\"Key,omitempty\"`\n\n\tRoleArn string `json:\"RoleArn,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSGameLiftBuild_S3Location) AWSCloudFormationType() string {\n\treturn \"AWS::GameLift::Build.S3Location\"\n}\n\n\n\n\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSGameLiftBuild_S3Location) DependsOn() []string ", "output": "{\n\treturn r._dependsOn\n}"} {"input": "package main\nimport \"fmt\"\nimport \"termbox-go\"\n\ntype PanelDeathScreen struct { }\n\nfunc (p *PanelDeathScreen) ProcessInput(g *Game, ch rune, key termbox.Key) *InputResult {\n result := &InputResult {\n Exit: false,\n TicksToPass: 0, \n }\n\n switch ch {\n \n case 'Q', 'q': \n result.Exit = true\n \n default:\n return nil\n }\n \n return result\n}\n\n\n\nfunc (p *PanelDeathScreen) Display(g *Game, r *ConsoleRange) ", "output": "{\n white := termbox.ColorWhite | termbox.AttrBold\n grey := termbox.ColorWhite\n black := termbox.ColorBlack\n \n fd := NewFlowDocument(78, 23)\n fd.AddParagraph(\"You have been destroyed\", grey, black)\n fd.AddParagraph(\" \", grey, black)\n fd.AddParagraph(fmt.Sprintf(\"You destroyed %d ships before heading off to Spacey Jones Locker.\", g.kills), grey, black)\n fd.Write(r, 1,1)\n \n r.Com(\"[Q]\", \" Quit\", 1, 23, black, white)\n \n \n}"} {"input": "package logger\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\tlog \"github.com/cihub/seelog\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestGetLogFileLocationReturnsDefaultPath(t *testing.T) {\n\tpath := \"/tmp/foo\"\n\tassert.Equal(t, path, GetLogFileLocation(path))\n}\n\nfunc TestLogLevelReturnsOverriddenLevel(t *testing.T) {\n\tos.Setenv(envLogLevel, \"DEBUG\")\n\tdefer os.Unsetenv(envLogLevel)\n\n\tvar expectedLogLevel log.LogLevel\n\texpectedLogLevel = log.DebugLvl\n\tassert.Equal(t, expectedLogLevel.String(), getLogLevel())\n}\n\nfunc TestLogLevelReturnsDefaultLevelWhenEnvNotSet(t *testing.T) {\n\tvar expectedLogLevel log.LogLevel\n\texpectedLogLevel = log.InfoLvl\n\tassert.Equal(t, expectedLogLevel.String(), getLogLevel())\n}\n\nfunc TestLogLevelReturnsDefaultLevelWhenEnvSetToInvalidValue(t *testing.T) {\n\tos.Setenv(envLogLevel, \"DEBUGGER\")\n\tdefer os.Unsetenv(envLogLevel)\n\n\tvar expectedLogLevel log.LogLevel\n\texpectedLogLevel = log.InfoLvl\n\tassert.Equal(t, expectedLogLevel.String(), getLogLevel())\n}\n\nfunc TestGetLogFileLocationReturnsOverriddenPath(t *testing.T) ", "output": "{\n\tpath := \"/tmp/foo\"\n\tos.Setenv(envLogFilePath, path)\n\tdefer os.Unsetenv(envLogFilePath)\n\n\tassert.Equal(t, path, GetLogFileLocation(\"/tmp/bar\"))\n}"} {"input": "package utils\n\nimport \"fmt\"\n\nfunc ExampleStringSet_Add() {\n\tset := NewStringSet()\n\tset.Add(\"a\")\n\tset.Add(\"b\")\n\n\tfmt.Println(set)\n\tset.Add(\"a\")\n\tfmt.Println(set)\n\n}\n\nfunc ExampleNewStringSet() {\n\ta := NewStringSet()\n\ta.Add(\"a\")\n\ta.Add(\"b\")\n\n\tb := NewStringSet(\"b\", \"a\")\n\n\tfmt.Println(a.Equals(b))\n\n}\n\nfunc ExampleNewStringSetFromStringMapKeys() {\n\tm := map[string]string{\n\t\t\"a\": \"some a value\",\n\t\t\"b\": \"some b value\",\n\t}\n\n\tset := NewStringSetFromStringMapKeys(m)\n\tfmt.Println(set)\n\n}\n\n\n\nfunc ExampleStringSet_IsEmpty() {\n\ta := NewStringSet()\n\n\tfmt.Println(a.IsEmpty())\n\ta.Add(\"a\")\n\tfmt.Println(a.IsEmpty())\n\n}\n\nfunc ExampleStringSet_Equals() {\n\ta := NewStringSet(\"a\", \"b\")\n\tb := NewStringSet(\"a\", \"b\", \"c\")\n\tfmt.Println(a.Equals(b))\n\n\ta.Add(\"c\")\n\tfmt.Println(a.Equals(b))\n\n}\n\nfunc ExampleStringSet_Contains() {\n\ta := NewStringSet(\"a\", \"b\")\n\tfmt.Println(a.Contains(\"z\"))\n\tfmt.Println(a.Contains(\"a\"))\n\n}\n\nfunc ExampleStringSet_Minus() {\n\ta := NewStringSet(\"a\", \"b\")\n\tb := NewStringSet(\"b\", \"c\")\n\tdelta := a.Minus(b)\n\n\tfmt.Println(delta)\n}\n\nfunc ExampleStringSet_ToSlice() ", "output": "{\n\ta := NewStringSet()\n\ta.Add(\"z\")\n\ta.Add(\"b\")\n\n\tfmt.Println(a.ToSlice())\n\n}"} {"input": "package models\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\n\nconst (\n\tIncomeStatusPending = \"Pending\"\n\tIncomeStatusCharged = \"Charged\"\n\tIncomeStatusChargeback = \"Chargeback\"\n)\n\n\nconst (\n\tIncomeTypeReward = 0\n\tIncomeTypeSuperrewards = 2\n\tIncomeTypeClixwall = 3\n\tIncomeTypePtcwall = 4\n\tIncomeTypePersonaly = 5\n\tIncomeTypeKiwiwall = 7\n\tIncomeTypeAdscendMedia = 8\n\tIncomeTypeAdgateMedia = 9\n\tIncomeTypeOffertoro = 10\n)\n\nvar incomeTypes = map[int64]string{\n\tIncomeTypeReward: \"reward\",\n\tIncomeTypeSuperrewards: \"superrewards\",\n\tIncomeTypeClixwall: \"clixwall\",\n\tIncomeTypePtcwall: \"ptcwall\",\n\tIncomeTypePersonaly: \"personaly\",\n\tIncomeTypeKiwiwall: \"kiwiwall\",\n\tIncomeTypeAdscendMedia: \"adscend media\",\n\tIncomeTypeAdgateMedia: \"adgate media\",\n\tIncomeTypeOffertoro: \"offertoro\",\n}\n\n\ntype Income struct {\n\tID int64 `db:\"id\"`\n\tUserID int64 `db:\"user_id\"`\n\tRefererID int64 `db:\"referer_id\"`\n\tType int64 `db:\"type\"`\n\tIncome float64 `db:\"income\"`\n\tRefererIncome float64 `db:\"referer_income\"`\n\tCreatedAt time.Time `db:\"created_at\"`\n\tStatus string `db:\"status\"`\n}\n\n\n\n\nfunc (i Income) MarshalJSON() ([]byte, error) ", "output": "{\n\tt, ok := incomeTypes[i.Type]\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"Invalid income type %v\", i.Type))\n\t}\n\n\tif i.Type != IncomeTypeReward {\n\t\tt = fmt.Sprintf(\"%s.%s\", t, i.Status)\n\t}\n\n\treturn json.Marshal(map[string]interface{}{\n\t\t\"type\": t,\n\t\t\"income\": i.Income,\n\t\t\"referer_income\": i.RefererIncome,\n\t\t\"created_at\": i.CreatedAt,\n\t})\n}"} {"input": "package fixtures_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/gomega\"\n\n\t\"istio.io/istio/galley/pkg/config/testing/data\"\n\t\"istio.io/istio/galley/pkg/config/testing/fixtures\"\n\t\"istio.io/istio/pkg/config/event\"\n\t\"istio.io/istio/pkg/config/resource\"\n)\n\nfunc TestNoVersions(t *testing.T) {\n\tg := NewGomegaWithT(t)\n\n\tevents := []event.Event{data.Event1Col1AddItem1}\n\tg.Expect(events[0].Resource.Metadata.Version).NotTo(Equal(resource.Version(\"\")))\n\tevents = fixtures.NoVersions(events)\n\tg.Expect(events[0].Resource.Metadata.Version).To(Equal(resource.Version(\"\")))\n}\n\nfunc TestNoFullSync(t *testing.T) {\n\tg := NewGomegaWithT(t)\n\n\tevents := []event.Event{data.Event1Col1AddItem1, data.Event1Col1Synced, data.Event2Col1AddItem2}\n\tevents = fixtures.NoFullSync(events)\n\n\texpected := []event.Event{data.Event1Col1AddItem1, data.Event2Col1AddItem2}\n\tg.Expect(events).To(Equal(expected))\n}\n\nfunc TestSort(t *testing.T) {\n\tg := NewGomegaWithT(t)\n\n\tevents := []event.Event{data.Event2Col1AddItem2, data.Event1Col1Synced, data.Event1Col1AddItem1}\n\tevents = fixtures.Sort(events)\n\n\texpected := []event.Event{data.Event1Col1AddItem1, data.Event2Col1AddItem2, data.Event1Col1Synced}\n\tg.Expect(events).To(Equal(expected))\n}\n\n\n\nfunc TestChain(t *testing.T) ", "output": "{\n\tg := NewGomegaWithT(t)\n\n\tevents := []event.Event{data.Event2Col1AddItem2, data.Event1Col1Synced, data.Event1Col1AddItem1}\n\tfn := fixtures.Chain(fixtures.Sort, fixtures.NoFullSync, fixtures.NoVersions)\n\tevents = fn(events)\n\n\texpected := []event.Event{\n\t\tdata.Event1Col1AddItem1.Clone(),\n\t\tdata.Event2Col1AddItem2.Clone(),\n\t}\n\texpected[0].Resource.Metadata.Version = resource.Version(\"\")\n\texpected[1].Resource.Metadata.Version = resource.Version(\"\")\n\n\tg.Expect(events).To(Equal(expected))\n}"} {"input": "package config\n\nimport (\n\t\"encoding/json\"\n\t\"path\"\n\n\t\"github.com/golang/glog\"\n)\n\n\nfunc Store(client ETCDInterface, cfg Config) error {\n\tbuf, err := json.Marshal(cfg)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to marshal global config: %v\", err)\n\t\treturn err\n\t}\n\tif _, err := client.Set(\"/goship/config\", string(buf), 0); err != nil {\n\t\tglog.Errorf(\"Failed to store global config: %v\", err)\n\t\treturn err\n\t}\n\tfor _, p := range cfg.Projects {\n\t\tif err := storeProject(client, p, \"/goship\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\nfunc storeEnvironment(client ETCDInterface, env Environment, dir string) error {\n\tbuf, err := json.Marshal(env)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to marshal environment config of %s: %v\", env.Name, err)\n\t\treturn err\n\t}\n\tif _, err := client.Set(path.Join(dir, env.Name), string(buf), 0); err != nil {\n\t\tglog.Errorf(\"Failed to store environment config of %s: %v\", env.Name, err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc storeProject(client ETCDInterface, p Project, base string) error ", "output": "{\n\tbuf, err := json.Marshal(p)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to marshal project config of %s: %v\", p.Name, err)\n\t\treturn err\n\t}\n\tdir := path.Join(base, \"projects\", p.Name)\n\tif _, err := client.Set(path.Join(dir, \"config\"), string(buf), 0); err != nil {\n\t\tglog.Errorf(\"Failed to store project config of %s: %v\", p.Name, err)\n\t\treturn err\n\t}\n\tfor _, env := range p.Environments {\n\t\tif err := storeEnvironment(client, env, path.Join(dir, \"environments\")); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package utils\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com/golang/glog\"\n)\n\n\n\nfunc Forever(method func() error) error {\n\tgo func() {\n\t\tfor {\n\t\t\tif err := method(); err != nil {\n\t\t\t\tglog.Errorf(\"Method failed to execute, error: %s, restarting now\", err)\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc Attempt(method func() (interface {}, error), attempts, interval int) (interface {},error) ", "output": "{\n\tfor i := 0; i < attempts; i++ {\n\t\tresult, err := method()\n\t\tif err != nil {\n\t\t\ttime.Sleep(interval * time.Second)\n\t\t} else {\n\t\t\treturn result, nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"Failed to implement the method\")\n}"} {"input": "package client\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\n\t\"github.com/containerd/containerd/containers\"\n\t\"github.com/containerd/containerd/oci\"\n\tspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n)\n\nconst newLine = \"\\r\\n\"\n\nfunc withExitStatus(es int) oci.SpecOpts {\n\treturn func(_ context.Context, _ oci.Client, _ *containers.Container, s *specs.Spec) error {\n\t\ts.Process.Args = []string{\"cmd\", \"/c\", \"exit\", strconv.Itoa(es)}\n\t\treturn nil\n\t}\n}\n\nfunc withProcessArgs(args ...string) oci.SpecOpts {\n\treturn oci.WithProcessArgs(append([]string{\"cmd\", \"/c\"}, args...)...)\n}\n\n\n\nfunc withTrue() oci.SpecOpts {\n\treturn oci.WithProcessArgs(\"cmd\", \"/c\")\n}\n\nfunc withExecExitStatus(s *specs.Process, es int) {\n\ts.Args = []string{\"cmd\", \"/c\", \"exit\", strconv.Itoa(es)}\n}\n\nfunc withExecArgs(s *specs.Process, args ...string) {\n\ts.Args = append([]string{\"cmd\", \"/c\"}, args...)\n}\n\nfunc withCat() oci.SpecOpts ", "output": "{\n\treturn oci.WithProcessArgs(\"cmd\", \"/c\", \"more\")\n}"} {"input": "package design\n\n\n\n\n\n\n\nimport (\n\t\"fmt\"\n)\n\ntype PhoneBrand interface {\n\tSetSoft(s Soft)\n\tRun()\n}\ntype Soft interface {\n\tRun()\n}\ntype Nokia struct {\n\ts Soft\n}\n\nfunc (n *Nokia) SetSoft(s Soft) {\n\tn.s = s\n}\n\n\ntype Game struct {\n}\n\nfunc (g Game) Run() {\n\tfmt.Println(\"手机游戏\")\n}\n\nfunc (n Nokia) Run() ", "output": "{\n\tfmt.Println(\"nokia\")\n\tn.s.Run()\n}"} {"input": "package validation\n\nimport (\n\t\"k8s.io/apimachinery/pkg/util/validation/field\"\n\t\"k8s.io/kubernetes/pkg/api\"\n)\n\n\nconst MountOptionAnnotation = \"volume.beta.kubernetes.io/mount-options\"\n\n\n\n\n\nfunc checkMountOption(pv *api.PersistentVolume) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif pv.Spec.GCEPersistentDisk != nil ||\n\t\tpv.Spec.AWSElasticBlockStore != nil ||\n\t\tpv.Spec.Glusterfs != nil ||\n\t\tpv.Spec.NFS != nil ||\n\t\tpv.Spec.RBD != nil ||\n\t\tpv.Spec.Quobyte != nil ||\n\t\tpv.Spec.ISCSI != nil ||\n\t\tpv.Spec.Cinder != nil ||\n\t\tpv.Spec.CephFS != nil ||\n\t\tpv.Spec.AzureFile != nil ||\n\t\tpv.Spec.VsphereVolume != nil ||\n\t\tpv.Spec.AzureDisk != nil ||\n\t\tpv.Spec.PhotonPersistentDisk != nil {\n\t\treturn allErrs\n\t}\n\tif _, ok := pv.Annotations[MountOptionAnnotation]; ok {\n\t\tmetaField := field.NewPath(\"metadata\")\n\t\tallErrs = append(allErrs, field.Forbidden(metaField.Child(\"annotations\", MountOptionAnnotation), \"may not specify mount options for this volume type\"))\n\t}\n\treturn allErrs\n}\n\nfunc ValidatePersistentVolume(pv *api.PersistentVolume) field.ErrorList ", "output": "{\n\treturn checkMountOption(pv)\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\n\tv1beta1 \"kubevirt.io/client-go/generated/containerized-data-importer/clientset/versioned/typed/core/v1beta1\"\n)\n\ntype FakeCdiV1beta1 struct {\n\t*testing.Fake\n}\n\n\n\nfunc (c *FakeCdiV1beta1) CDIConfigs() v1beta1.CDIConfigInterface {\n\treturn &FakeCDIConfigs{c}\n}\n\nfunc (c *FakeCdiV1beta1) DataImportCrons(namespace string) v1beta1.DataImportCronInterface {\n\treturn &FakeDataImportCrons{c, namespace}\n}\n\nfunc (c *FakeCdiV1beta1) DataSources(namespace string) v1beta1.DataSourceInterface {\n\treturn &FakeDataSources{c, namespace}\n}\n\nfunc (c *FakeCdiV1beta1) DataVolumes(namespace string) v1beta1.DataVolumeInterface {\n\treturn &FakeDataVolumes{c, namespace}\n}\n\nfunc (c *FakeCdiV1beta1) ObjectTransfers() v1beta1.ObjectTransferInterface {\n\treturn &FakeObjectTransfers{c}\n}\n\nfunc (c *FakeCdiV1beta1) StorageProfiles() v1beta1.StorageProfileInterface {\n\treturn &FakeStorageProfiles{c}\n}\n\n\n\nfunc (c *FakeCdiV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeCdiV1beta1) CDIs() v1beta1.CDIInterface ", "output": "{\n\treturn &FakeCDIs{c}\n}"} {"input": "package delete\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\n\n\n\n\nfunc NewDeleteFilesFileidentifierParamsWithTimeout(timeout time.Duration) *DeleteFilesFileidentifierParams {\n\tvar ()\n\treturn &DeleteFilesFileidentifierParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype DeleteFilesFileidentifierParams struct {\n\n\tFileidentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *DeleteFilesFileidentifierParams) WithFileidentifier(fileidentifier string) *DeleteFilesFileidentifierParams {\n\to.Fileidentifier = fileidentifier\n\treturn o\n}\n\n\nfunc (o *DeleteFilesFileidentifierParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"fileidentifier\", o.Fileidentifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewDeleteFilesFileidentifierParams() *DeleteFilesFileidentifierParams ", "output": "{\n\tvar ()\n\treturn &DeleteFilesFileidentifierParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}"} {"input": "package subtitles\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestDownloadFromTheSubDb(t *testing.T) {\n\tfileName := createZeroedTempFile(1024 * 1024 * 4)\n\tdefer os.Remove(fileName)\n\n\tf, err := os.Open(fileName)\n\tassert.Equal(t, nil, err)\n\n\thash, err := SubDbHashFromFile(f)\n\tassert.Equal(t, nil, err)\n\tassert.Equal(t, \"0dfbe8aa4c20b52e1b8bf3cb6cbdf193\", hash)\n\n\tfinder := NewSubFinder(f, fileName, \"en\")\n\n\ttext, err := finder.TheSubDb(\"sandbox.thesubdb.com\")\n\tassert.Equal(t, nil, err)\n\tassert.True(t, len(text) > 1000)\n}\n\n\n\nfunc TestSubDbHashFromFile(t *testing.T) {\n\n\tsubDbConformTest(t, \"conformance-files/thesubdb/dexter.mp4\", \"ffd8d4aa68033dc03d1c8ef373b9028c\")\n\n\tsubDbConformTest(t, \"conformance-files/thesubdb/justified.mp4\", \"edc1981d6459c6111fe36205b4aff6c2\")\n}\n\nfunc subDbConformTest(t *testing.T, fileName string, expectedHash string) ", "output": "{\n\tif !exists(fileName) {\n\t\tfmt.Println(\"ERROR thesubdb.com conformance tests missing, run ./hash-conformance-deps if you want to run these tests\")\n\t\treturn\n\t}\n\n\tf, err := os.Open(fileName)\n\tassert.Equal(t, nil, err)\n\n\thash, err := SubDbHashFromFile(f)\n\tassert.Equal(t, nil, err)\n\tassert.Equal(t, expectedHash, hash)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n)\n\nconst (\n\tdefaultRecurse = false\n\tdefaultCommand = \"\"\n\tdefaultVerbose = false\n)\n\ntype WatcherSettings struct {\n\tPath string\n\tRecurse bool\n\n\tCommand string\n\n\tVerbose bool\n}\n\nvar Settings WatcherSettings = WatcherSettings{}\n\n\n\nfunc init() ", "output": "{\n\n\tdefaultPath, err := os.Getwd()\n\tif err != nil {\n\t\tdefaultPath = \".\"\n\t}\n\n\tflag.StringVar(&Settings.Path, \"path\", defaultPath, \"The file or directory to watch\")\n\n\tflag.BoolVar(&Settings.Recurse, \"recurse\", defaultRecurse, \"A flag indicating whether to recurse or not\")\n\n\tflag.StringVar(&Settings.Command, \"command\", defaultCommand, \"A command that will be executed every time something changed\")\n\n\tflag.BoolVar(&Settings.Verbose, \"verbose\", defaultVerbose, \"A flag for enabling verbose output\")\n}"} {"input": "package sysfs\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n)\n\nfunc TestGetRaplZones(t *testing.T) {\n\tfs, err := NewFS(sysTestFixtures)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tzones, err := GetRaplZones(fs)\n\tif err != nil || zones == nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestNoRaplFiles(t *testing.T) {\n\tfs, err := NewFS(filepath.Join(sysTestFixtures, \"class\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tzones, err := GetRaplZones(fs)\n\tif err == nil || zones != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\n\nfunc TestNewRaplValues(t *testing.T) ", "output": "{\n\tfs, err := NewFS(sysTestFixtures)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tzones, err := GetRaplZones(fs)\n\tif err != nil || zones == nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif len(zones) != 3 {\n\t\tt.Fatal(\"wrong number of RAPL values\")\n\t}\n\tmicrojoules, err := zones[0].GetEnergyMicrojoules()\n\tif err != nil {\n\t\tt.Fatal(\"couldn't read microjoules\")\n\t}\n\tif microjoules != 240422366267 {\n\t\tt.Fatal(\"wrong microjoule number\")\n\t}\n\tif zones[2].Index != 10 {\n\t\tt.Fatal(\"wrong index number\")\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"debug/gosym\"\n\t\"github.com/derekparker/delve/proc\"\n)\n\n\n\n\n\nfunc ConvertThread(th *proc.Thread) *Thread {\n\tvar (\n\t\tfunction *Function\n\t\tfile string\n\t\tline int\n\t\tpc uint64\n\t)\n\n\tloc, err := th.Location()\n\tif err == nil {\n\t\tpc = loc.PC\n\t\tfile = loc.File\n\t\tline = loc.Line\n\t\tfunction = ConvertFunction(loc.Fn)\n\t}\n\n\treturn &Thread{\n\t\tID: th.Id,\n\t\tPC: pc,\n\t\tFile: file,\n\t\tLine: line,\n\t\tFunction: function,\n\t}\n}\n\n\nfunc ConvertVar(v *proc.Variable) Variable {\n\treturn Variable{\n\t\tName: v.Name,\n\t\tValue: v.Value,\n\t\tType: v.Type,\n\t}\n}\n\nfunc ConvertFunction(fn *gosym.Func) *Function {\n\tif fn == nil {\n\t\treturn nil\n\t}\n\n\treturn &Function{\n\t\tName: fn.Name,\n\t\tType: fn.Type,\n\t\tValue: fn.Value,\n\t\tGoType: fn.GoType,\n\t}\n}\n\n\nfunc ConvertGoroutine(g *proc.G) *Goroutine {\n\treturn &Goroutine{\n\t\tID: g.Id,\n\t\tPC: g.PC,\n\t\tFile: g.File,\n\t\tLine: g.Line,\n\t\tFunction: ConvertFunction(g.Func),\n\t}\n}\n\nfunc ConvertLocation(loc proc.Location) Location {\n\treturn Location{\n\t\tPC: loc.PC,\n\t\tFile: loc.File,\n\t\tLine: loc.Line,\n\t\tFunction: ConvertFunction(loc.Fn),\n\t}\n}\n\nfunc ConvertBreakpoint(bp *proc.Breakpoint) *Breakpoint ", "output": "{\n\treturn &Breakpoint{\n\t\tID: bp.ID,\n\t\tFunctionName: bp.FunctionName,\n\t\tFile: bp.File,\n\t\tLine: bp.Line,\n\t\tAddr: bp.Addr,\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/url\"\n)\n\ntype PageToken struct {\n\tLimit uint16\n\tPage uint16\n}\n\nfunc DefaultPageToken(limit uint16) PageToken {\n\treturn PageToken{Limit: limit, Page: 1}\n}\n\nfunc (tok PageToken) Next() PageToken {\n\treturn PageToken{Limit: tok.Limit, Page: tok.Page + 1}\n}\n\nfunc (tok PageToken) Encode() string {\n\tbuf := bytes.Buffer{}\n\tbinary.Write(&buf, binary.LittleEndian, tok)\n\treturn base64.URLEncoding.EncodeToString(buf.Bytes())\n}\n\nfunc decodePageToken(value string) (*PageToken, error) {\n\tdec, err := base64.URLEncoding.DecodeString(value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdb := bytes.NewBuffer(dec)\n\n\tvar tok PageToken\n\terr = binary.Read(db, binary.LittleEndian, &tok)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &tok, nil\n}\n\nfunc findNextPageToken(u *url.URL, limit uint16) (*PageToken, error) {\n\tvalues := u.Query()[\"nextPageToken\"]\n\n\tif len(values) > 1 {\n\t\treturn nil, errors.New(\"too many values for page token\")\n\t}\n\n\tif len(values) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tval := values[0]\n\ttok, err := decodePageToken(val)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = validatePageToken(tok, limit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tok, nil\n}\n\n\n\nfunc validatePageToken(tok *PageToken, limit uint16) error ", "output": "{\n\tif tok.Limit != limit {\n\t\treturn fmt.Errorf(\"token limit must be %d\", limit)\n\t}\n\n\tif tok.Page == 0 {\n\t\treturn errors.New(\"token page must be greater than zero\")\n\t}\n\n\treturn nil\n}"} {"input": "package service\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/syncloud/redirect/model\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype ActionsDbStub struct {\n\taction *model.Action\n}\n\nfunc (db *ActionsDbStub) GetAction(_ int64, _ uint64) (*model.Action, error) {\n\treturn db.action, nil\n}\nfunc (db *ActionsDbStub) GetActionByToken(_ string, _ uint64) (*model.Action, error) {\n\treturn db.action, nil\n}\n\nfunc (db *ActionsDbStub) InsertAction(action *model.Action) error {\n\tdb.action = action\n\treturn nil\n}\n\nfunc (db *ActionsDbStub) UpdateAction(action *model.Action) error {\n\tif db.action != nil {\n\t\tdb.action = action\n\t}\n\treturn nil\n}\n\nfunc (db *ActionsDbStub) DeleteActions(_ int64) error {\n\tdb.action = nil\n\treturn nil\n}\n\n\n\nfunc TestUpsert(t *testing.T) {\n\n\tdb := &ActionsDbStub{nil}\n\tactions := NewActions(db)\n\n\tuser := &model.User{Id: 1, Email: \"test@example.com\", PasswordHash: \"pass\", Active: true, UpdateToken: \"token\", Timestamp: time.Now()}\n\taction, err := actions.UpsertActivateAction(user.Id)\n\n\tassert.Nil(t, err)\n\tassert.NotNil(t, action)\n\tassert.NotNil(t, db.action)\n}\n\nfunc (db *ActionsDbStub) DeleteAction(actionId uint64) error ", "output": "{\n\tdb.action = nil\n\treturn nil\n}"} {"input": "package turtle\n\nimport (\n\t\"strings\"\n)\n\ntype DataSet struct {\n\ttriplecount int\n\tnscount int\n\tNamespaces map[string]string\n\tTriples []Triple\n}\n\nfunc newDataSet() *DataSet {\n\treturn &DataSet{\n\t\ttriplecount: 0,\n\t\tnscount: 0,\n\t\tNamespaces: make(map[string]string),\n\t\tTriples: []Triple{},\n\t}\n}\n\nfunc (d *DataSet) AddTripleStrings(subject, predicate, object string) {\n\td.triplecount += 1\n\td.Triples = append(d.Triples, MakeTriple(subject, predicate, object))\n}\n\nfunc (d *DataSet) AddTripleURIs(subject, predicate, object URI) {\n\td.triplecount += 1\n\td.Triples = append(d.Triples, Triple{subject, predicate, object})\n}\n\nfunc (d *DataSet) addNamespace(prefix, namespace string) {\n\td.nscount += 1\n\tnamespace = strings.TrimRight(namespace, \"#\")\n\td.Namespaces[prefix] = namespace\n}\n\nfunc (d *DataSet) NumTriples() int {\n\treturn d.triplecount\n}\n\n\n\nfunc (d *DataSet) NumNamespaces() int ", "output": "{\n\treturn d.nscount\n}"} {"input": "package tsdb\n\nimport \"sync\"\n\ntype _Cached struct {\n\tsync.RWMutex \n\tindexer map[uint64]int \n\tringbuffer []*DBValue \n\theader int \n\ttail int \n}\n\nfunc newCached(cachedsize int) *_Cached {\n\treturn &_Cached{\n\t\tindexer: make(map[uint64]int),\n\t\tringbuffer: make([]*DBValue, cachedsize),\n\t}\n}\n\n\n\nfunc (cached *_Cached) Update(val *DBValue) {\n\tcached.Lock()\n\tdefer cached.Unlock()\n\n\told := cached.ringbuffer[cached.tail]\n\n\tif old != nil {\n\t\tdelete(cached.indexer, old.ID)\n\t}\n\n\tcached.ringbuffer[cached.tail] = val\n\tcached.indexer[val.ID] = cached.tail\n\n\tcached.tail++\n\n\tif cached.tail == len(cached.ringbuffer) {\n\t\tcached.tail = 0\n\t}\n\n\tif cached.tail == cached.header {\n\t\tcached.header++\n\n\t\tif cached.header == len(cached.ringbuffer) {\n\t\t\tcached.header = 0\n\t\t}\n\t}\n}\n\nfunc (cached *_Cached) Get(id uint64) (*DBValue, bool) ", "output": "{\n\tcached.RLock()\n\tdefer cached.RUnlock()\n\n\tif indexer, ok := cached.indexer[id]; ok {\n\t\treturn cached.ringbuffer[indexer], true\n\t}\n\n\treturn nil, false\n}"} {"input": "package expr\n\nimport (\n\t\"github.com/grafana/metrictank/api/models\"\n)\n\ntype FuncUnique struct {\n\tin []GraphiteFunc\n}\n\nfunc NewUnique() GraphiteFunc {\n\treturn &FuncUnique{}\n}\n\nfunc (s *FuncUnique) Signature() ([]Arg, []Arg) {\n\treturn []Arg{\n\t\tArgSeriesLists{val: &s.in}}, []Arg{ArgSeriesList{}}\n}\n\n\n\nfunc (s *FuncUnique) Exec(dataMap DataMap) ([]models.Series, error) {\n\tseries, _, err := consumeFuncs(dataMap, s.in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tseenNames := make(map[string]bool)\n\tvar uniqueSeries []models.Series\n\tfor _, serie := range series {\n\t\tif _, ok := seenNames[serie.Target]; !ok {\n\t\t\tseenNames[serie.Target] = true\n\t\t\tuniqueSeries = append(uniqueSeries, serie)\n\t\t}\n\t}\n\treturn uniqueSeries, nil\n}\n\nfunc (s *FuncUnique) Context(context Context) Context ", "output": "{\n\treturn context\n}"} {"input": "package images\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"upload-demo/config\"\n\t\"upload-demo/httpd/route\"\n\t\"upload-demo/log\"\n\n\t\"github.com/gorilla/mux\"\n)\n\n\n\nfunc download(w http.ResponseWriter, r *http.Request, v route.Vars) {\n\tfile, err := config.FileRepo.OneById(v.FileId(\"imageId\"))\n\tlog.PanicIf(err)\n\tdefer file.Close()\n\n\tcontentDisposition := fmt.Sprintf(\"attachment; filename=%q\", file.Name())\n\n\tw.Header().Set(\"Content-Disposition\", contentDisposition)\n\tw.Header().Set(\"Content-Type\", file.ContentType())\n\tio.Copy(w, file)\n}\n\nfunc Download(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tdownload(w, r, route.Vars(mux.Vars(r)))\n}"} {"input": "package audioplayer\n\nimport (\n \"govkmedia/dialogboxes\"\n \"govkmedia/requestwrapper\"\n \"strconv\"\n \"time\"\n)\n\nfunc (e *Engine) StartPlay() {\n mwroot:=e.mainWindow.Root()\n playerobj:=mwroot.ObjectByName(\"mplayer\")\n curplaying:=e.playlist[e.currentPlaying]\n playerobj.Set(\"source\",curplaying.Url)\n time.Sleep(time.Second) \n context:=e.qmlEngine.Context()\n context.SetVar(\"vkartist\",curplaying.Artist)\n context.SetVar(\"vktitle\",curplaying.Title)\n context.SetVar(\"vkduration\",curplaying.Duration)\n e.LoadLyrics()\n playerobj.Call(\"resetProgress\")\n playerobj.Call(\"play\")\n}\n\nfunc (e *Engine) LoadLyrics() {\n curplaying:=e.playlist[e.currentPlaying]\n if curplaying.LyricsId==0 { return }\n ra:=requestwrapper.RequestAccesser{Token: e.accessToken}\n parms:=map[string]string{\"lyrics_id\":strconv.FormatFloat(curplaying.LyricsId,'f',-1,64)}\n resp,err:=ra.MakeRequest(\"audio.getLyrics\",parms)\n if err!=nil {\n dialogboxes.ShowErrorDialog(err.Error())\n return\n }\n lyricsfield:=e.mainWindow.Root().ObjectByName(\"lyrics\")\n lyrics:=resp[\"response\"].(map[string]interface{})[\"text\"].(string)\n lyricsfield.Set(\"text\",lyrics)\n}\n\nfunc (e *Engine) Next() {\n if e.currentPlaying+1==len(e.playlist) { return }\n e.currentPlaying++\n e.StartPlay()\n}\n\n\n\nfunc (e *Engine) Prev() ", "output": "{\n if e.currentPlaying==0 { return }\n e.currentPlaying--\n e.StartPlay()\n}"} {"input": "package utils\n\nimport (\n\t\"net\"\n)\n\ntype Clienter struct {\n\tclient net.Conn\n\tisAlive bool\n}\n\n\n\nfunc (c *Clienter) Connect(proxy_server string) bool ", "output": "{\n\tif c.isAlive {\n\t\treturn true\n\t} else {\n\t\tvar err error\n\t\tc.client, err = net.Dial(\"tcp\", proxy_server)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tdefer c.client.Close()\n\t\tc.isAlive = true\n\t}\n\treturn c.isAlive\n}"} {"input": "package python\n\n\nimport \"C\"\nimport \"unsafe\"\n\n\n\nfunc PyImportImport(modulePtr unsafe.Pointer) unsafe.Pointer {\n\tptr := (*C.PyObject)(modulePtr)\n\tret := PyImport_Import(ptr)\n\treturn unsafe.Pointer(ret)\n}\n\nfunc PyUnicodeFromString(s string) unsafe.Pointer ", "output": "{\n\tcstr := C.CString(s)\n\tret := PyUnicode_FromString(cstr)\n\treturn unsafe.Pointer(ret)\n}"} {"input": "package geddit\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\ntype Submission struct {\n\tAuthor string `json:\"author\"`\n\tTitle string `json:\"title\"`\n\tURL string `json:\"url\"`\n\tDomain string `json:\"domain\"`\n\tSubreddit string `json:\"subreddit\"`\n\tSubredditID string `json:\"subreddit_id\"`\n\tFullID string `json:\"name\"`\n\tID string `json:\"id\"`\n\tPermalink string `json:\"permalink\"`\n\tSelftext string `json:\"selftext\"`\n\tThumbnailURL string `json:\"thumbnail\"`\n\tDateCreated float64 `json:\"created_utc\"`\n\tNumComments int `json:\"num_comments\"`\n\tScore int `json:\"score\"`\n\tUps int `json:\"ups\"`\n\tDowns int `json:\"downs\"`\n\tIsNSFW bool `json:\"over_18\"`\n\tIsSelf bool `json:\"is_self\"`\n\tWasClicked bool `json:\"clicked\"`\n\tIsSaved bool `json:\"saved\"`\n\tBannedBy *string `json:\"banned_by\"`\n}\n\nfunc (h Submission) voteID() string { return h.FullID }\nfunc (h Submission) deleteID() string { return h.FullID }\nfunc (h Submission) replyID() string { return h.FullID }\n\n\n\n\n\nfunc (h *Submission) String() string {\n\tplural := \"\"\n\tif h.NumComments != 1 {\n\t\tplural = \"s\"\n\t}\n\tcomments := fmt.Sprintf(\"%d comment%s\", h.NumComments, plural)\n\treturn fmt.Sprintf(\"%d - %s (%s)\", h.Score, h.Title, comments)\n}\n\nfunc (h *Submission) FullPermalink() string ", "output": "{\n\treturn \"https://reddit.com\" + h.Permalink\n}"} {"input": "package variant\n\nimport (\n\t\"github.com/go-ole/com/errors\"\n\t\"github.com/go-ole/com/types\"\n)\n\n\n\nfunc VariantClear(v *types.Variant) error {\n\treturn errors.NotImplementedError\n}\n\nfunc VariantChangeType(source *types.Variant, flags uint16, vt types.VariantType) *types.Variant {\n\treturn source\n}\n\nfunc VariantChangeTypeEx(source *types.Variant, locale uint32, flags uint16, vt types.VariantType) *types.Variant {\n\treturn source\n}\n\nfunc VariantCopy(source *types.Variant) *types.Variant {\n\treturn source\n}\n\nfunc VariantCopyIndirect(source *types.Variant) *types.Variant {\n\treturn source\n}\n\nfunc VariantInit(v *types.Variant) error ", "output": "{\n\treturn errors.NotImplementedError\n}"} {"input": "package sacloud\n\n\ntype propInterfaceDriver struct {\n\tInterfaceDriver EInterfaceDriver `json:\",omitempty\"` \n}\n\n\nfunc (p *propInterfaceDriver) SetInterfaceDriver(v EInterfaceDriver) {\n\tp.InterfaceDriver = v\n}\n\n\nfunc (p *propInterfaceDriver) GetInterfaceDriver() EInterfaceDriver {\n\treturn p.InterfaceDriver\n}\n\n\n\n\n\nfunc (p *propInterfaceDriver) GetInterfaceDriverString() string {\n\treturn string(p.InterfaceDriver)\n}\n\nfunc (p *propInterfaceDriver) SetInterfaceDriverByString(v string) ", "output": "{\n\tp.InterfaceDriver = EInterfaceDriver(v)\n}"} {"input": "package user\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n\ntype RangeList []*Range\n\n\n\n\n\nfunc (l *RangeList) Empty() bool {\n\tif len(*l) == 0 {\n\t\treturn true\n\t}\n\tfor _, r := range *l {\n\t\tif !r.Empty() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (l *RangeList) Contains(uid int) bool {\n\tfor _, r := range *l {\n\t\tif r.Contains(uid) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (l *RangeList) Type() string {\n\treturn \"user.RangeList\"\n}\n\n\nfunc (l *RangeList) Set(value string) error {\n\tnewRangeList, err := ParseRangeList(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*l = *newRangeList\n\treturn nil\n}\n\n\nfunc (l *RangeList) String() string {\n\trangeStrings := []string{}\n\tfor _, r := range *l {\n\t\trangeStrings = append(rangeStrings, r.String())\n\t}\n\treturn strings.Join(rangeStrings, \",\")\n}\n\n\n\nfunc IsUserAllowed(user string, allowed *RangeList) bool {\n\tuid, err := strconv.Atoi(user)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn allowed.Contains(uid)\n}\n\nfunc ParseRangeList(str string) (*RangeList, error) ", "output": "{\n\trl := RangeList{}\n\tif len(str) == 0 {\n\t\treturn &rl, nil\n\t}\n\tparts := strings.Split(str, \",\")\n\tfor _, p := range parts {\n\t\tr, err := ParseRange(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trl = append(rl, r)\n\t}\n\treturn &rl, nil\n}"} {"input": "package features\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" features/2021-07-01\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package iso20022\n\n\ntype CardPaymentTransaction42 struct {\n\n\tSaleReferenceIdentification *Max35Text `xml:\"SaleRefId,omitempty\"`\n\n\tTransactionIdentification *TransactionIdentifier1 `xml:\"TxId\"`\n\n\tRecipientTransactionIdentification *Max35Text `xml:\"RcptTxId,omitempty\"`\n\n\tReconciliationIdentification *Max35Text `xml:\"RcncltnId,omitempty\"`\n\n\tInterchangeData *Max140Text `xml:\"IntrchngData,omitempty\"`\n\n\tTransactionDetails *CardPaymentTransactionDetails22 `xml:\"TxDtls\"`\n}\n\nfunc (c *CardPaymentTransaction42) SetSaleReferenceIdentification(value string) {\n\tc.SaleReferenceIdentification = (*Max35Text)(&value)\n}\n\nfunc (c *CardPaymentTransaction42) AddTransactionIdentification() *TransactionIdentifier1 {\n\tc.TransactionIdentification = new(TransactionIdentifier1)\n\treturn c.TransactionIdentification\n}\n\nfunc (c *CardPaymentTransaction42) SetRecipientTransactionIdentification(value string) {\n\tc.RecipientTransactionIdentification = (*Max35Text)(&value)\n}\n\nfunc (c *CardPaymentTransaction42) SetReconciliationIdentification(value string) {\n\tc.ReconciliationIdentification = (*Max35Text)(&value)\n}\n\n\n\nfunc (c *CardPaymentTransaction42) AddTransactionDetails() *CardPaymentTransactionDetails22 {\n\tc.TransactionDetails = new(CardPaymentTransactionDetails22)\n\treturn c.TransactionDetails\n}\n\nfunc (c *CardPaymentTransaction42) SetInterchangeData(value string) ", "output": "{\n\tc.InterchangeData = (*Max140Text)(&value)\n}"} {"input": "package etcd2\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/coreos/etcd/client\"\n\t\"golang.org/x/net/context\"\n)\n\n\ntype Etcd2Connect struct {\n\tetcd2 client.Client\n}\n\n\nfunc NewEtcd2Connect(etcd2EndPoint string) (*Etcd2Connect, error) {\n\tc, err := client.New(client.Config{\n\t\tEndpoints: []string{fmt.Sprintf(\"http://%s\", etcd2EndPoint)},\n\t\tTransport: client.DefaultTransport,\n\t\tHeaderTimeoutPerRequest: time.Second,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Etcd2Connect{etcd2: c}, nil\n}\n\n\n\n\n\nfunc (e *Etcd2Connect) Make(data map[string]string) error {\n\tkapi := client.NewKeysAPI(e.etcd2)\n\topts := &client.SetOptions{PrevExist: client.PrevNoExist}\n\tfor k, v := range data {\n\t\tif _, err := kapi.Set(context.Background(), k, v, opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (e *Etcd2Connect) Get(data map[string]string) (map[string]string, error) {\n\tkapi := client.NewKeysAPI(e.etcd2)\n\tresult := make(map[string]string)\n\tfor k := range data {\n\t\tresp, err := kapi.Get(context.Background(), k, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult[k] = resp.Node.Value\n\t}\n\treturn result, nil\n}\n\nfunc (e *Etcd2Connect) Set(data map[string]string) error ", "output": "{\n\tkapi := client.NewKeysAPI(e.etcd2)\n\tfor k, v := range data {\n\t\tif _, err := kapi.Set(context.Background(), k, v, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package errors \n\nimport (\n\t\"strconv\"\n)\n\n\n\ntype StructuralError string\n\nfunc (s StructuralError) Error() string {\n\treturn \"openpgp: invalid data: \" + string(s)\n}\n\n\n\ntype UnsupportedError string\n\nfunc (s UnsupportedError) Error() string {\n\treturn \"openpgp: unsupported feature: \" + string(s)\n}\n\n\n\ntype InvalidArgumentError string\n\n\n\n\n\ntype SignatureError string\n\nfunc (b SignatureError) Error() string {\n\treturn \"openpgp: invalid signature: \" + string(b)\n}\n\ntype keyIncorrectError int\n\nfunc (ki keyIncorrectError) Error() string {\n\treturn \"openpgp: incorrect key\"\n}\n\nvar ErrKeyIncorrect error = keyIncorrectError(0)\n\ntype unknownIssuerError int\n\nfunc (unknownIssuerError) Error() string {\n\treturn \"openpgp: signature made by unknown entity\"\n}\n\nvar ErrUnknownIssuer error = unknownIssuerError(0)\n\ntype keyRevokedError int\n\nfunc (keyRevokedError) Error() string {\n\treturn \"openpgp: signature made by revoked key\"\n}\n\nvar ErrKeyRevoked error = keyRevokedError(0)\n\ntype UnknownPacketTypeError uint8\n\nfunc (upte UnknownPacketTypeError) Error() string {\n\treturn \"openpgp: unknown packet type: \" + strconv.Itoa(int(upte))\n}\n\nfunc (i InvalidArgumentError) Error() string ", "output": "{\n\treturn \"openpgp: invalid argument: \" + string(i)\n}"} {"input": "package web\n\nfunc SetBaseUrl(baseUrl string) {\n\tclient.setBaseUrl(baseUrl)\n}\n\nfunc SetKey(key string) {\n\tclient.setKey(key)\n}\n\n\n\nfunc SetNodeId(nodeId int) ", "output": "{\n\tclient.setNodeId(nodeId)\n}"} {"input": "package mocks\n\nimport (\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n\tremotecommand \"k8s.io/client-go/tools/remotecommand\"\n)\n\n\ntype MockExecutor struct {\n\tctrl *gomock.Controller\n\trecorder *MockExecutorMockRecorder\n}\n\n\ntype MockExecutorMockRecorder struct {\n\tmock *MockExecutor\n}\n\n\nfunc NewMockExecutor(ctrl *gomock.Controller) *MockExecutor {\n\tmock := &MockExecutor{ctrl: ctrl}\n\tmock.recorder = &MockExecutorMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockExecutor) EXPECT() *MockExecutorMockRecorder {\n\treturn m.recorder\n}\n\n\n\n\n\nfunc (mr *MockExecutorMockRecorder) Stream(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Stream\", reflect.TypeOf((*MockExecutor)(nil).Stream), arg0)\n}\n\nfunc (m *MockExecutor) Stream(arg0 remotecommand.StreamOptions) error ", "output": "{\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Stream\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}"} {"input": "package model\n\n\ntype Weight struct {\n\ttime int\n\trequirements map[*Reward]int\n}\n\n\nfunc (weight *Weight) Time() int {\n\treturn weight.time\n}\n\n\nfunc (weight *Weight) Requirements() map[*Reward]int {\n\treturn weight.requirements\n}\n\n\n\n\n\nfunc CreateWeight(time int) *Weight {\n\tweight := new(Weight)\n\tweight.time = time\n\tweight.requirements = make(map[*Reward]int)\n\treturn weight\n}\n\n\ntype ByTime []*Weight\n\n\nfunc (a ByTime) Len() int {\n\treturn len(a)\n}\n\n\nfunc (a ByTime) Swap(i, j int) {\n\ta[i], a[j] = a[j], a[i]\n}\n\n\nfunc (a ByTime) Less(i, j int) bool {\n\treturn a[i].Time() < a[j].Time()\n}\n\nfunc (weight *Weight) AddRequirement(reward *Reward, quantity int) ", "output": "{\n\tweight.requirements[reward] = quantity\n}"} {"input": "package scheduler\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n\nconst (\n\tdefaultWorkManagerQueueSize uint = 25\n\tdefaultWorkManagerPoolSize uint = 4\n)\n\n\n\n\n\ntype Config struct {\n\tWorkManagerQueueSize uint `json:\"work_manager_queue_size\"yaml:\"work_manager_queue_size\"`\n\tWorkManagerPoolSize uint `json:\"work_manager_pool_size\"yaml:\"work_manager_pool_size\"`\n}\n\nconst (\n\tCONFIG_CONSTRAINTS = `\n\t\t\t\"scheduler\": {\n\t\t\t\t\"type\": [\"object\", \"null\"],\n\t\t\t\t\"properties\" : {\n\t\t\t\t\t\"work_manager_queue_size\" : {\n\t\t\t\t\t\t\"type\": \"integer\",\n\t\t\t\t\t\t\"minimum\": 1\n\t\t\t\t\t},\n\t\t\t\t\t\"work_manager_pool_size\" : {\n\t\t\t\t\t\t\"type\": \"integer\",\n\t\t\t\t\t\t\"minimum\": 1\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t\"additionalProperties\": false\n\t\t\t}\n\t`\n)\n\n\n\n\n\n\nfunc (c *Config) UnmarshalJSON(data []byte) error {\n\tt := make(map[string]json.RawMessage)\n\tif err := json.Unmarshal(data, &t); err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range t {\n\t\tswitch k {\n\t\tcase \"work_manager_queue_size\":\n\t\t\tif err := json.Unmarshal(v, &(c.WorkManagerQueueSize)); err != nil {\n\t\t\t\treturn fmt.Errorf(\"%v (while parsing 'scheduler::work_manager_queue_size')\", err)\n\t\t\t}\n\t\tcase \"work_manager_pool_size\":\n\t\t\tif err := json.Unmarshal(v, &(c.WorkManagerPoolSize)); err != nil {\n\t\t\t\treturn fmt.Errorf(\"%v (while parsing 'scheduler::work_manager_pool_size')\", err)\n\t\t\t}\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"Unrecognized key '%v' in global config file while parsing 'scheduler'\", k)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GetDefaultConfig() *Config ", "output": "{\n\treturn &Config{\n\t\tWorkManagerQueueSize: defaultWorkManagerQueueSize,\n\t\tWorkManagerPoolSize: defaultWorkManagerPoolSize,\n\t}\n}"} {"input": "package app\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/client-go/informers\"\n\t\"k8s.io/client-go/rest\"\n)\n\n\n\nfunc newInformerFactory(clientConfig *rest.Config) (informers.SharedInformerFactory, error) ", "output": "{\n\treturn nil, fmt.Errorf(\"unsupported in this build\")\n}"} {"input": "package chshare\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\n\ntype Logger struct {\n\tprefix string\n\tlogger *log.Logger\n\tInfo, Debug bool\n}\n\nfunc NewLogger(prefix string) *Logger {\n\treturn NewLoggerFlag(prefix, log.Ldate|log.Ltime)\n}\n\nfunc NewLoggerFlag(prefix string, flag int) *Logger {\n\tl := &Logger{\n\t\tprefix: prefix,\n\t\tlogger: log.New(os.Stdout, \"\", flag),\n\t\tInfo: false,\n\t\tDebug: false,\n\t}\n\treturn l\n}\n\nfunc (l *Logger) Infof(f string, args ...interface{}) {\n\tif l.Info {\n\t\tl.logger.Printf(l.prefix+\": \"+f, args...)\n\t}\n}\n\nfunc (l *Logger) Debugf(f string, args ...interface{}) {\n\tif l.Debug {\n\t\tl.logger.Printf(l.prefix+\": \"+f, args...)\n\t}\n}\n\nfunc (l *Logger) Errorf(f string, args ...interface{}) error {\n\treturn fmt.Errorf(l.prefix+\": \"+f, args...)\n}\n\n\n\nfunc (l *Logger) Prefix() string {\n\treturn l.prefix\n}\n\nfunc (l *Logger) Fork(prefix string, args ...interface{}) *Logger ", "output": "{\n\targs = append([]interface{}{l.prefix}, args...)\n\tll := NewLogger(fmt.Sprintf(\"%s: \"+prefix, args...))\n\tll.Info = l.Info\n\tll.Debug = l.Debug\n\treturn ll\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n)\n\ntype I interface {\n\tM()\n}\n\nfunc main() {\n\tvar x I\n\tswitch x.(type) {\n\tcase string: \n\t\tprintln(\"FAIL\")\n\t}\n\n\n\tvar r io.Reader\n\n\t_, _ = r.(io.Writer)\n\n\tswitch r.(type) {\n\tcase io.Writer:\n\t}\n\n\tswitch _ := r.(type) { \n\t}\n}\n\n\n\nfunc noninterface() ", "output": "{\n\tvar i int\n\tswitch i.(type) { \n\tcase string:\n\tcase int:\n\t}\n\n\ttype S struct {\n\t\tname string\n\t}\n\tvar s S\n\tswitch s.(type) { \n\t}\n}"} {"input": "package main\n\n\n\nfunc sanitizeUrlGood(redir string) string ", "output": "{\n\tif len(redir) > 1 && redir[0] == '/' && redir[1] != '/' && redir[1] != '\\\\' {\n\t\treturn redir\n\t}\n\treturn \"/\"\n}"} {"input": "package test\n\nimport \"io\"\n\n\ntype PlainReader struct {\n\tr io.Reader\n}\n\n\nfunc NewPlainReader(r io.Reader) *PlainReader {\n\treturn &PlainReader{r}\n}\n\n\nfunc (r *PlainReader) Read(p []byte) (int, error) {\n\treturn r.r.Read(p)\n}\n\n\n\n\ntype ErrorReader struct {\n\tn int\n}\n\n\nfunc NewErrorReader(n int) *ErrorReader {\n\treturn &ErrorReader{n}\n}\n\n\nfunc (r *ErrorReader) Read(b []byte) (n int, err error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tif r.n == 0 {\n\t\treturn 0, ErrPlain\n\t}\n\tr.n--\n\tb[0] = '.'\n\treturn 1, nil\n}\n\n\n\n\ntype InfiniteReader struct{}\n\n\nfunc NewInfiniteReader() *InfiniteReader {\n\treturn &InfiniteReader{}\n}\n\n\n\n\n\n\n\ntype EmptyReader struct {\n}\n\n\nfunc NewEmptyReader() *EmptyReader {\n\treturn &EmptyReader{}\n}\n\n\nfunc (r *EmptyReader) Read(b []byte) (n int, err error) {\n\treturn 0, io.EOF\n}\n\nfunc (r *InfiniteReader) Read(b []byte) (n int, err error) ", "output": "{\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tb[0] = '.'\n\treturn 1, nil\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification struct {\n\n\tPredefinedScalingMetricType string `json:\"PredefinedScalingMetricType,omitempty\"`\n\n\tResourceLabel string `json:\"ResourceLabel,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) AWSCloudFormationType() string {\n\treturn \"AWS::AutoScalingPlans::ScalingPlan.PredefinedScalingMetricSpecification\"\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\n\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) Metadata() map[string]interface{} ", "output": "{\n\treturn r._metadata\n}"} {"input": "package database\n\nimport (\n\t\"labix.org/v2/mgo\"\n\t\"labix.org/v2/mgo/bson\"\n\t\"github.com/DewaldV/crucible/config\"\n)\n\ntype MgoConnection struct {\n\tDatabase string\n\tCollection string\n}\n\nfunc (conn *MgoConnection) FindOne(m bson.M, d interface{}) {\n\tExecuteWithCollection(conn.Database, conn.Collection, func(c *mgo.Collection) error { return c.Find(m).One(d) })\n}\n\nfunc (conn *MgoConnection) FindAll(m bson.M, d interface{}) {\n\tExecuteWithCollection(conn.Database, conn.Collection, func(c *mgo.Collection) error { return c.Find(m).All(d) })\n}\n\n\nfunc (conn *MgoConnection) Insert(d interface{}) {\n\tExecuteWithCollection(conn.Database, conn.Collection, func(c *mgo.Collection) error { return c.Insert(d) })\n}\n\n\n\nfunc ExecuteWithCollection(database, collection string, f func(*mgo.Collection) error) error {\n\tsession := GetSession(\"Default\")\n\tdefer session.Close()\n\n\tsession.SetMode(mgo.Monotonic, true)\n\n\tc := session.DB(database).C(collection)\n\n\treturn f(c)\n}\n\nvar sessionPool map[string]*mgo.Session\n\nfunc LoadSessions(dataSourceConfig map[string]*config.DataSourceConfiguration) {\n\tsessionPool = make(map[string]*mgo.Session)\n\tfor key, source := range dataSourceConfig {\n\t\ts, _ := mgo.Dial(source.ServerName)\n\t\tsessionPool[key] = s\n\t}\n}\n\n\n\nfunc GetSession(dataSource string) *mgo.Session ", "output": "{\n\ts := sessionPool[dataSource]\n\treturn s.Clone()\n}"} {"input": "package packr\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/gobuffalo/envy\"\n\t\"github.com/gobuffalo/packr/v2/plog\"\n)\n\nfunc construct(name string, path string) *Box {\n\treturn &Box{\n\t\tPath:\t\tpath,\n\t\tName:\t\tname,\n\t\tResolutionDir:\tresolutionDir(path),\n\t\tresolvers:\tresolversMap{},\n\t\tdirs:\t\tdirsMap{},\n\t}\n}\n\nfunc resolutionDirTestFilename(filename, og string) (string, bool) {\n\tng := filepath.Join(filepath.Dir(filename), og)\n\n\tcov := filepath.Join(\"_test\", \"_obj_test\")\n\tng = strings.Replace(ng, string(filepath.Separator)+cov, \"\", 1)\n\n\tif resolutionDirExists(ng, og) {\n\t\treturn ng, true\n\t}\n\n\tng = filepath.Join(envy.GoPath(), \"src\", ng)\n\tif resolutionDirExists(ng, og) {\n\t\treturn ng, true\n\t}\n\n\treturn og, false\n}\n\n\n\nfunc resolutionDir(og string) string {\n\tng, _ := filepath.Abs(og)\n\n\tif resolutionDirExists(ng, og) {\n\t\treturn ng\n\t}\n\n\t_, filename, _, _ := runtime.Caller(3)\n\tng, ok := resolutionDirTestFilename(filename, og)\n\tif ok {\n\t\treturn ng\n\t}\n\n\t_, filename, _, _ = runtime.Caller(4)\n\tng, ok = resolutionDirTestFilename(filename, og)\n\tif ok {\n\t\treturn ng\n\t}\n\n\treturn og\n}\n\nfunc resolutionDirExists(s, og string) bool ", "output": "{\n\t_, err := os.Stat(s)\n\tif err != nil {\n\t\treturn false\n\t}\n\tplog.Debug(\"packr\", \"resolutionDir\", \"original\", og, \"resolved\", s)\n\treturn true\n}"} {"input": "package greq\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n\n\nfunc String(res *http.Response, err error) (string, error) {\n\tbody, err := Bytes(res, err)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}\n\nfunc JSON(res *http.Response, err error, ptr interface{}) error {\n\tbody, err := Bytes(res, err)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(body, ptr)\n}\n\nfunc Bytes(res *http.Response, err error) ([]byte, error) ", "output": "{\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn body, nil\n}"} {"input": "package runtime\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/heroku/instruments\"\n)\n\n\n\nfunc ExamplePauses() {\n\tpauses := NewPauses(512)\n\tgo func() {\n\t\tfor {\n\t\t\tpauses.Update()\n\t\t\ttime.Sleep(time.Minute)\n\t\t}\n\t}()\n\tperc95 := instruments.Quantile(pauses.Snapshot(), 0.95)\n\tfmt.Println(perc95)\n}\n\nfunc TestPauses(t *testing.T) ", "output": "{\n\tp := NewPauses(1024)\n\n\tp.Update()\n\tp.Snapshot()\n\n\truntime.GC()\n\tp.Update()\n\tif count := len(p.Snapshot()); count != 1 {\n\t\tt.Fatalf(\"captured %d gc runs, expect 1\", count)\n\t}\n\n\truntime.GC()\n\truntime.GC()\n\tp.Update()\n\tif count := len(p.Snapshot()); count != 2 {\n\t\tt.Fatalf(\"captured %d gc runs, expected 2\", count)\n\t}\n\n\tfor i := 0; i < 257; i++ {\n\t\truntime.GC()\n\t}\n\tp.Update()\n\tif count := len(p.Snapshot()); count != 256 {\n\t\tt.Fatalf(\"captured %d gc runs, expected 256\", count)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n)\n\ntype Configuration struct {\n\tHost string\n\tPort int\n\tPeriod int\n\tMetricsHost string\n\tMetricsPort int\n\tMetricsPrefix string\n}\n\n\n\nfunc config() Configuration ", "output": "{\n\thostPtr := flag.String(\"host\", \"127.0.0.1\", \"Squid server host\")\n\tportPtr := flag.Int(\"port\", 3128, \"Squid server http port\")\n\tperiodPtr := flag.Int(\"period\", 60, \"Period of status page polling in seconds\")\n\tmetricsHostPtr := flag.String(\"metrics-host\", \"127.0.0.1\", \"Ip address of the Graphite collector host\")\n\tmetricsPortPtr := flag.Int(\"metrics-port\", 2003, \"Port of the Graphite collector host\")\n\tmetricsPrefixPtr := flag.String(\"metrics-prefix\", \"server.squid\", \"Prefix to prepend metrics names\")\n\n\tflag.Parse()\n\n\treturn Configuration{Host: *hostPtr, Port: *portPtr, Period: *periodPtr, MetricsHost: *metricsHostPtr, MetricsPort: *metricsPortPtr, MetricsPrefix: *metricsPrefixPtr}\n}"} {"input": "package googlecompute\n\nimport (\n\t\"github.com/mitchellh/packer/packer\"\n\t\"testing\"\n)\n\n\n\nfunc TestArtifact_impl(t *testing.T) ", "output": "{\n\tvar _ packer.Artifact = new(Artifact)\n}"} {"input": "package graphite\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n)\n\nfunc createFindMetricsTestServer() *httptest.Server {\n\treturn httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, `[\n\t\t\t{\"text\": \"one\", \"expandable\": 1, \"leaf\": 0, \"id\": \"cluster.one\", \"allowChildren\": 1},\n\t\t\t{\"text\": \"two\", \"expandable\": 1, \"leaf\": 0, \"id\": \"cluster.two\", \"allowChildren\": 1}]`)\n\t}))\n}\n\n\n\nfunc createExpandMetricsTestServer() *httptest.Server {\n\treturn httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, \"{\\\"results\\\": [\\\"cluster.one\\\", \\\"cluster.two\\\"]}\")\n\t}))\n}\n\nfunc ExampleClient_ExpandMetrics() {\n\tts := createExpandMetricsTestServer()\n\tdefer ts.Close()\n\n\tclient, _ := NewFromString(ts.URL)\n\tres, _ := client.ExpandMetrics(\n\t\tExpandMetricRequest{\n\t\t\tQuery: \"cluster.*\",\n\t\t},\n\t)\n\tfmt.Printf(\"%+v\", res)\n}\n\nfunc ExampleClient_FindMetrics() ", "output": "{\n\tts := createFindMetricsTestServer()\n\tdefer ts.Close()\n\n\tclient, _ := NewFromString(ts.URL)\n\tres, _ := client.FindMetrics(\n\t\tFindMetricRequest{\n\t\t\tQuery: \"cluster.*\",\n\t\t},\n\t)\n\tfmt.Printf(\"%+v\", res)\n\n}"} {"input": "package main\n\nimport (\n\t\"regexp\"\n\t\"testing\"\n)\n\nfunc Test_GcSuiteRePass(t *testing.T) {\n\tfind_suite := regexp.MustCompile(gc_endRE).FindStringSubmatch\n\ttokens := find_suite(\"PASS: mmath_test.go:16: MySuite.TestAdd\t0.000s\")\n\n\tfor i, expected := range []string{\"PASS\", \"MySuite\", \"TestAdd\", \"0.000\"} {\n\t\tcheckExpected(t, expected, tokens[i+1])\n\t}\n}\n\nfunc Test_GcSuiteReFail(t *testing.T) {\n\tfind_suite := regexp.MustCompile(gc_endRE).FindStringSubmatch\n\ttokens := find_suite(\"FAIL: mmath_test.go:35: MySuite.TestDiv\")\n\n\tfor i, expected := range []string{\"FAIL\", \"MySuite\", \"TestDiv\", \"\"} {\n\t\tcheckExpected(t, expected, tokens[i+1])\n\t}\n}\n\n\n\nfunc checkExpected(t *testing.T, expected string, actual string) {\n\tif actual != expected {\n\t\tt.Fatalf(\"Expected %s but was %s\\n\", expected, actual)\n\t}\n}\n\nfunc Test_GcSuiteReSkip(t *testing.T) ", "output": "{\n\tfind_suite := regexp.MustCompile(gc_endRE).FindStringSubmatch\n\ttokens := find_suite(\"SKIP: mmath_test.go:35: MySuite.TestMul (not implemented)\")\n\n\tfor i, expected := range []string{\"SKIP\", \"MySuite\", \"TestMul\", \"\"} {\n\t\tcheckExpected(t, expected, tokens[i+1])\n\t}\n}"} {"input": "package finspacedata\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/awstesting/unit\"\n)\n\n\n\nfunc TestClientContentType(t *testing.T) ", "output": "{\n\tsess := unit.Session.Copy()\n\n\tserver := httptest.NewServer(http.HandlerFunc(\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\tcontentType := r.Header.Get(\"Content-Type\")\n\t\t\tif e, a := contentType, \"application/x-amz-json-1.1\"; !strings.EqualFold(e, a) {\n\t\t\t\tt.Errorf(\"expect %v content-type, got %v\", e, a)\n\t\t\t}\n\t\t},\n\t))\n\tdefer server.Close()\n\n\tclient := New(sess, &aws.Config{Endpoint: &server.URL})\n\t_, err := client.GetWorkingLocation(&GetWorkingLocationInput{\n\t\tLocationType: aws.String(\"INGESTION\"),\n\t})\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n}"} {"input": "package runtime\n\nimport (\n\t\"github.com/dotcloud/docker/runtime/graphdriver\"\n)\n\n\n\nfunc migrateIfAufs(driver graphdriver.Driver, root string) error ", "output": "{\n\treturn nil\n}"} {"input": "package service\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"log\"\n)\n\n\ntype Service struct {\n\tURL string\n\tDNSName string\n\tSecure bool\n\tForceTLS bool\n\tEncodedCert string\n\tEncodedKey string\n\tparsedCert tls.Certificate\n}\n\n\nfunc (s Service) Certificate() tls.Certificate {\n\treturn s.parsedCert\n}\n\n\n\n\n\nfunc NewService(name string, port int, dnsName string, secure bool, forceTLS bool, encodedCert string, encodedKey string) Service {\n\turl := fmt.Sprintf(\"%s:%d\", name, port)\n\treturn Service{\n\t\tURL: url,\n\t\tDNSName: dnsName,\n\t\tSecure: secure,\n\t\tForceTLS: forceTLS,\n\t\tEncodedCert: encodedCert,\n\t\tEncodedKey: encodedKey,\n\t}\n}\n\nfunc (s *Service) ParseCertificate() bool ", "output": "{\n\tif !s.Secure {\n\t\treturn false\n\t}\n\n\tparsedCert, err := tls.X509KeyPair([]byte(s.EncodedCert), []byte(s.EncodedKey))\n\tif err != nil {\n\t\tlog.Printf(\"Failed to parse certificate for %s\", s.DNSName)\n\t\treturn false\n\t}\n\n\ts.parsedCert = parsedCert\n\treturn true\n}"} {"input": "package hilbert\n\ntype mockRectangle struct {\n\txlow, ylow, xhigh, yhigh int32\n}\n\nfunc (mr *mockRectangle) LowerLeft() (int32, int32) {\n\treturn mr.xlow, mr.ylow\n}\n\n\n\nfunc newMockRectangle(xlow, ylow, xhigh, yhigh int32) *mockRectangle {\n\treturn &mockRectangle{\n\t\txlow: xlow,\n\t\tylow: ylow,\n\t\txhigh: xhigh,\n\t\tyhigh: yhigh,\n\t}\n}\n\nfunc (mr *mockRectangle) UpperRight() (int32, int32) ", "output": "{\n\treturn mr.xhigh, mr.yhigh\n}"} {"input": "package http\n\nimport (\n\t\"fmt\"\n\t\"github.com/denniscollective/dragonfly.go/dragonfly\"\n\t\"github.com/gorilla/handlers\"\n\t\"github.com/gorilla/mux\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc StartServer() error {\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"/favicon.ico\", hollar)\n\tr.HandleFunc(\"/{b64JobString}\", serveFile)\n\n\terr := http.ListenAndServe(\":2345\", handle(r))\n\treturn err\n}\n\ntype benchmarkHandler struct {\n\thandler http.Handler\n}\n\nfunc (h benchmarkHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tt := time.Now()\n\th.handler.ServeHTTP(w, req)\n\tfmt.Println(time.Now().Sub(t))\n}\n\nfunc handle(h http.Handler) http.Handler {\n\n\treturn benchmarkHandler{handlers.CombinedLoggingHandler(os.Stdout, h)}\n\n}\n\nfunc hollar(response http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"hollar\")\n}\n\n\n\nfunc serveFile(response http.ResponseWriter, request *http.Request) ", "output": "{\n\tresponse.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\tvars := mux.Vars(request)\n\tjobStr := vars[\"b64JobString\"]\n\tfile, err := dragonfly.ImageFor(jobStr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tdata, _ := ioutil.ReadAll(file)\n\tresponse.Write(data)\n}"} {"input": "package grpcproxy\n\nimport (\n\t\"context\"\n\n\t\"github.com/coreos/etcd/clientv3\"\n\t\"github.com/coreos/etcd/etcdserver/api/v3lock/v3lockpb\"\n)\n\ntype lockProxy struct {\n\tclient *clientv3.Client\n}\n\n\n\nfunc (lp *lockProxy) Lock(ctx context.Context, req *v3lockpb.LockRequest) (*v3lockpb.LockResponse, error) {\n\treturn v3lockpb.NewLockClient(lp.client.ActiveConnection()).Lock(ctx, req)\n}\n\nfunc (lp *lockProxy) Unlock(ctx context.Context, req *v3lockpb.UnlockRequest) (*v3lockpb.UnlockResponse, error) {\n\treturn v3lockpb.NewLockClient(lp.client.ActiveConnection()).Unlock(ctx, req)\n}\n\nfunc NewLockProxy(client *clientv3.Client) v3lockpb.LockServer ", "output": "{\n\treturn &lockProxy{client: client}\n}"} {"input": "package validation\n\nimport (\n\t\"strings\"\n\n\t\"github.com/rantuttl/cloudops/apimachinery/pkg/util/validation\"\n\t\"github.com/rantuttl/cloudops/apimachinery/pkg/util/validation/field\"\n)\n\nconst IsNegativeErrorMsg string = `must be greater than or equal to 0`\n\n\n\n\n\n\ntype ValidateNameFunc func(name string, prefix bool) []string\n\n\n\n\n\nfunc NameIsDNSLabel(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1123Label(name)\n}\n\n\nfunc NameIsDNS1035Label(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1035Label(name)\n}\n\n\n\n\nvar ValidateNamespaceName = NameIsDNSLabel\n\n\n\n\nvar ValidateServiceAccountName = NameIsDNSSubdomain\n\n\n\nfunc maskTrailingDash(name string) string {\n\tif strings.HasSuffix(name, \"-\") {\n\t\treturn name[:len(name)-2] + \"a\"\n\t}\n\treturn name\n}\n\n\nfunc ValidateNonnegativeField(value int64, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif value < 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, value, IsNegativeErrorMsg))\n\t}\n\treturn allErrs\n}\n\nfunc NameIsDNSSubdomain(name string, prefix bool) []string ", "output": "{\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1123Subdomain(name)\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc main() {\n\tsc := bufio.NewScanner(os.Stdin)\n\tsc.Split(bufio.ScanWords)\n\tn := nextInt(sc)\n\ta := nextInt(sc)\n\tb := nextInt(sc)\n\n\tanswer := 0\n\tfor i := 1; i <= n; i++ {\n\t\tsum := 0\n\t\tfor _, s := range fmt.Sprintf(\"%d\", i) {\n\t\t\tx, _ := strconv.Atoi(string(s))\n\t\t\tsum = sum + x\n\t\t}\n\t\tif a <= sum && sum <= b {\n\t\t\tanswer = answer + i\n\t\t}\n\t}\n\n\tfmt.Println(answer)\n}\n\n\n\nfunc nextString(sc *bufio.Scanner) string {\n\tsc.Scan()\n\treturn sc.Text()\n}\n\n\n\nfunc nextInt(sc *bufio.Scanner) int {\n\tsc.Scan()\n\tn, err := strconv.Atoi(sc.Text())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn n\n}\n\nfunc printArray(xs []int) {\n\tfmt.Println(strings.Trim(fmt.Sprint(xs), \"[]\"))\n}\n\nfunc debugPrintf(format string, a ...interface{}) {\n\tfmt.Fprintf(os.Stderr, format, a...)\n}\n\nfunc nextNumber(sc *bufio.Scanner) float64 ", "output": "{\n\tsc.Scan()\n\tf, err := strconv.ParseFloat(sc.Text(), 32)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}"} {"input": "package save\n\nimport (\n\t\"github.com/madhusudhancs/redis/cache\"\n\t\"github.com/madhusudhancs/redis/cmd\"\n\t\"github.com/madhusudhancs/redis/config\"\n\t\"github.com/madhusudhancs/redis/utils/log\"\n)\n\nconst (\n\tCmdName = \"SAVE\"\n)\n\nfunc init() {\n\tif err := cmd.Register(CmdName, Run); err != nil {\n\t\tlog.Errorf(\"SaveCmd: failed to register command. err: %v\", err)\n\t}\n}\n\n\n\nfunc Run(options []string, c *cache.Cache) ([]byte, bool) ", "output": "{\n\tif _, err := c.Save(config.DBFileName); err != nil {\n\t\tlog.Errorf(\"SaveCmd: err: %v\", err)\n\t\treturn cmd.GetErrMsg(err), false\n\t}\n\n\treturn cmd.GetSimpleString(\"OK\"), false\n}"} {"input": "package docker\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/megamsys/vertice/provision/docker\"\n\t\"strings\"\n\t\"text/tabwriter\"\n\n\t\"github.com/megamsys/libgo/cmd\"\n)\n\ntype Bridges map[string]DockerBridge\n\ntype DockerBridge struct {\n\tName string\n\tNetwork string\n\tGateway string\n}\n\n\n\nfunc NewBridgeConfig() *Bridges {\n\tbr := make(Bridges)\n\treturn &br\n}\n\nfunc (c Bridges) ConvertToMap() map[string]string {\n\tvar x map[string]string\n\tfor _, v := range c {\n\t\tx = v.toMap()\n\t}\n\treturn x\n}\n\nfunc (c DockerBridge) toMap() map[string]string {\n\tm := make(map[string]string)\n\tm[docker.BRIDGE_NAME] = c.Name\n\tm[docker.BRIDGE_NETWORK] = c.Network\n\tm[docker.BRIDGE_GATEWAY] = c.Gateway\n\n\treturn m\n}\n\nfunc (c Bridges) String() string {\n\tbs := make([]string, len(c))\n\tfor _, v := range c {\n\t\tbs = append(bs, v.String(), \"\\n\")\n\t}\n\n\tw := new(tabwriter.Writer)\n\tvar b bytes.Buffer\n\tw.Init(&b, 0, 8, 0, '\\t', 0)\n\tb.Write([]byte(cmd.Colorfy(\"Config:\", \"white\", \"\", \"bold\") + \"\\t\" +\n\t\tcmd.Colorfy(\"bridges\", \"green\", \"\", \"\") + \"\\n\"))\n\tb.Write([]byte(strings.Join(bs, \"\\n\")))\n\tfmt.Fprintln(w)\n\tw.Flush()\n\treturn strings.TrimSpace(b.String())\n\n}\n\nfunc (d DockerBridge) String() string ", "output": "{\n\tw := new(tabwriter.Writer)\n\tvar b bytes.Buffer\n\tw.Init(&b, 1, 8, 0, '\\t', 0)\n\tb.Write([]byte(cmd.Colorfy(\"Bridge\", \"white\", \"\", \"\") + \"\\t\" +\n\t\tcmd.Colorfy(d.Name, \"blue\", \"\", \"\") + \"\\n\"))\n\tb.Write([]byte(\"network\" + \"\\t\" + d.Network + \"\\n\"))\n\tb.Write([]byte(\"gateway\" + \"\\t\" + d.Gateway + \"\\n\"))\n\tb.Write([]byte(\"---\\n\"))\n\tfmt.Fprintln(w)\n\tw.Flush()\n\treturn strings.TrimSpace(b.String())\n}"} {"input": "package assert\n\nimport (\n\t\"testing\"\n)\n\nfunc IntEquals(t *testing.T, actual int, expected int) {\n\tif actual != expected {\n\t\tt.Fatalf(\"%#v != %#v\", actual, expected)\n\t}\n}\n\nfunc Float32Equals(t *testing.T, actual float32, expected float32) {\n\tif actual != expected {\n\t\tt.Fatalf(\"%#v != %#v\", actual, expected)\n\t}\n}\n\nfunc StringEquals(t *testing.T, actual string, expected string) {\n\tif actual != expected {\n\t\tt.Fatalf(\"%#v != %#v\", actual, expected)\n\t}\n}\n\n\n\nfunc IntListListEquals(t *testing.T, actualList [][]int, expectedList [][]int) {\n\tif len(actualList) != len(expectedList) {\n\t\tt.Fatalf(\"%#v != %#v\", actualList, expectedList)\n\t}\n\tfor i, expected := range expectedList {\n\t\tIntListEquals(t, actualList[i], expected)\n\t}\n}\n\nfunc IntListEquals(t *testing.T, actualList []int, expectedList []int) ", "output": "{\n\tIntEquals(t, len(actualList), len(expectedList))\n\tfor i, expected := range expectedList {\n\t\tIntEquals(t, actualList[i], expected)\n\t}\n}"} {"input": "package api\n\nimport (\n\t. \"atlantis/manager/rpc/types\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\n\n\nfunc Usage(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tauth := ManagerAuthArg{r.FormValue(\"User\"), \"\", r.FormValue(\"Secret\")}\n\targ := ManagerUsageArg{ManagerAuthArg: auth}\n\tvar reply ManagerUsageReply\n\terr := manager.Usage(arg, &reply)\n\tfmt.Fprintf(w, \"%s\", Output(map[string]interface{}{\"Usage\": reply.Usage}, err))\n}"} {"input": "package syslocale\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\n\nconst maxlen = 85\n\n\n\nfunc getLocaleName() (string, error) ", "output": "{\n\tif name := getEnvLang(); len(name) > 0 {\n\t\treturn name, nil\n\t}\n\n\tk32, err := syscall.LoadDLL(\"kernel32.dll\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer k32.Release()\n\n\tf, err := k32.FindProc(\"GetUserDefaultLocaleName\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tbuf := make([]uint16, maxlen)\n\tr1, _, err := f.Call(uintptr(unsafe.Pointer(&buf[0])), uintptr(maxlen))\n\tif uint32(r1) == 0 {\n\t\treturn \"\", err\n\t}\n\n\treturn syscall.UTF16ToString(buf), nil\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/boltdb/bolt\"\n)\n\nfunc writeNBytes(bdb *bolt.DB, k []byte, N int) error {\n\tbuf := make([]byte, N)\n\treturn bdb.Update(func(tx *bolt.Tx) error {\n\t\tbucket, err := tx.CreateBucketIfNotExists([]byte(\"predicate\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn bucket.Put(k, buf)\n\t})\n}\n\n\n\nfunc main() {\n\tdb, err := bolt.Open(\"bolt.db\", 0600, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\tk := []byte(\"key\")\n\tN := 512\n\tif err := writeNBytes(db, k, N); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(readValue(db, k))\n}\n\nfunc readValue(bdb *bolt.DB, k []byte) (N int) ", "output": "{\n\tbdb.View(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(\"predicate\"))\n\t\tif bucket == nil {\n\t\t\treturn errors.New(\"Bucket not found\")\n\t\t}\n\t\tval := bucket.Get(k)\n\t\tm := make([]byte, len(val))\n\t\tcopy(m, val)\n\t\tN = len(m)\n\t\treturn nil\n\t})\n\treturn\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc foo(x int) bool {\n\treturn x == x \n}\n\nfunc isNaN(x float32) bool {\n\treturn x != x \n}\n\nfunc main() {\n\tfoo(42)\n}\n\nconst mode = \"Debug\"\n\nfunc log(msg string) {\n\tif mode == \"Debug\" {\n\t\tfmt.Println(msg)\n\t}\n}\n\n\n\nfunc bump(x *int) {\n\t*x++\n}\n\nfunc baz() bool {\n\tvar x = 0\n\tbump(&x)\n\treturn x == 0\n}\n\ntype counter int\n\nfunc (x *counter) bump() {\n\t*x++\n}\n\nfunc (x counter) bimp() {\n\tx++\n}\n\nfunc baz2() bool {\n\tvar x counter\n\tx.bump()\n\treturn x == 0 \n}\n\nfunc baz3() bool {\n\tvar y counter\n\ty.bimp()\n\treturn y == 0 \n}\n\nfunc bar() ", "output": "{\n\tif ptrsize == 8 { \n\t\tfmt.Println()\n\t}\n}"} {"input": "package treemap\n\nimport (\n\t\"github.com/emirpasic/gods/containers\"\n\trbt \"github.com/emirpasic/gods/trees/redblacktree\"\n)\n\nfunc assertIteratorImplementation() {\n\tvar _ containers.ReverseIteratorWithKey = (*Iterator)(nil)\n}\n\n\ntype Iterator struct {\n\titerator rbt.Iterator\n}\n\n\nfunc (m *Map) Iterator() Iterator {\n\treturn Iterator{iterator: m.tree.Iterator()}\n}\n\n\n\n\n\nfunc (iterator *Iterator) Next() bool {\n\treturn iterator.iterator.Next()\n}\n\n\n\n\nfunc (iterator *Iterator) Prev() bool {\n\treturn iterator.iterator.Prev()\n}\n\n\n\nfunc (iterator *Iterator) Value() interface{} {\n\treturn iterator.iterator.Value()\n}\n\n\n\nfunc (iterator *Iterator) Key() interface{} {\n\treturn iterator.iterator.Key()\n}\n\n\n\nfunc (iterator *Iterator) Begin() {\n\titerator.iterator.Begin()\n}\n\n\n\nfunc (iterator *Iterator) End() {\n\titerator.iterator.End()\n}\n\n\n\n\nfunc (iterator *Iterator) First() bool {\n\treturn iterator.iterator.First()\n}\n\n\n\n\n\n\nfunc (iterator *Iterator) Last() bool ", "output": "{\n\treturn iterator.iterator.Last()\n}"} {"input": "package libDao\n\nvar (\n\tstorage Storage\n)\n\n\ntype DefaultDao struct {\n}\n\n\nfunc InitDao(sc *StorageConfig, s Storage) (err error) {\n\tif sc == nil {\n\t\terr = ErrStorageConfigIllegal\n\t\treturn\n\t}\n\tif s == nil {\n\t\tdefaultStorage := new(DefaultStorage)\n\t\tstorage = defaultStorage\n\t} else {\n\t\tstorage = s\n\t}\n\tif sc.OpenCache {\n\t\tif err = storage.InitCache(sc.CacheAddr, sc.CacheKeyPrefix); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif sc.OpenPersistence {\n\t\tif err = storage.InitPersistence(sc.PersistenceAddr, sc.PersistenceDbName); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\n\nfunc (this *DefaultDao) Get(key string, value interface{}) (err error) {\n\terr = storage.Get(key, value)\n\treturn\n}\n\n\nfunc (this *DefaultDao) Put(key string, value interface{}) (err error) {\n\terr = storage.Put(key, value)\n\treturn\n}\n\n\n\n\nfunc (this *DefaultDao) Del(key string, value interface{}) (err error) ", "output": "{\n\terr = storage.Del(key, value)\n\treturn\n}"} {"input": "package permutation\n\n\nimport \"C\"\n\nimport (\n\t\"github.com/dtromb/gogsl\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\n\n\nfunc (p *GslPermutation) Slice_() interface{} {\n\tbaseType := gogsl.GOGSL_SIZE_T_TYPE\n\tsliceType := reflect.SliceOf(baseType)\n\tsize := p.Len()\n\thdr := &reflect.SliceHeader{Len: size, Cap: size, Data: uintptr(C.get_permutation_data((*C.gsl_permutation)(unsafe.Pointer(p.Ptr()))))}\n\treturn reflect.NewAt(sliceType, unsafe.Pointer(hdr)).Elem().Interface()\n}\n\nfunc (p *GslPermutation) Len() int ", "output": "{\n\treturn int(C.get_permutation_size((*C.gsl_permutation)(unsafe.Pointer(p.Ptr()))))\n}"} {"input": "package j_group\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"koding/remoteapi/models\"\n)\n\n\ntype JGroupEachReader struct {\n\tformats strfmt.Registry\n}\n\n\n\n\n\nfunc NewJGroupEachOK() *JGroupEachOK {\n\treturn &JGroupEachOK{}\n}\n\n\ntype JGroupEachOK struct {\n\tPayload *models.DefaultResponse\n}\n\nfunc (o *JGroupEachOK) Error() string {\n\treturn fmt.Sprintf(\"[POST /remote.api/JGroup.each][%d] jGroupEachOK %+v\", 200, o.Payload)\n}\n\nfunc (o *JGroupEachOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\to.Payload = new(models.DefaultResponse)\n\n\tif err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc NewJGroupEachUnauthorized() *JGroupEachUnauthorized {\n\treturn &JGroupEachUnauthorized{}\n}\n\n\ntype JGroupEachUnauthorized struct {\n\tPayload *models.UnauthorizedRequest\n}\n\nfunc (o *JGroupEachUnauthorized) Error() string {\n\treturn fmt.Sprintf(\"[POST /remote.api/JGroup.each][%d] jGroupEachUnauthorized %+v\", 401, o.Payload)\n}\n\nfunc (o *JGroupEachUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\to.Payload = new(models.UnauthorizedRequest)\n\n\tif err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (o *JGroupEachReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) ", "output": "{\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewJGroupEachOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 401:\n\t\tresult := NewJGroupEachUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"golang.org/x/net/http2\"\n\n\t\"github.com/summerwind/h2spec/config\"\n\t\"github.com/summerwind/h2spec/spec\"\n)\n\n\n\nfunc GoAway() *spec.ClientTestGroup ", "output": "{\n\ttg := NewTestGroup(\"6.8\", \"GOAWAY\")\n\n\ttg.AddTestCase(&spec.ClientTestCase{\n\t\tDesc: \"Sends a GOAWAY frame with a stream identifier other than 0x0\",\n\t\tRequirement: \"The endpoint MUST treat this as a connection error of type PROTOCOL_ERROR.\",\n\t\tRun: func(c *config.Config, conn *spec.Conn) error {\n\t\t\terr := conn.Handshake()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tconn.Send([]byte(\"\\x00\\x00\\x08\\x07\\x00\\x00\\x00\\x00\\x01\"))\n\t\t\tconn.Send([]byte(\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"))\n\n\t\t\treturn spec.VerifyConnectionError(conn, http2.ErrCodeProtocol)\n\t\t},\n\t})\n\n\treturn tg\n}"} {"input": "package builder\n\nimport (\n\t\"arduino.cc/builder/constants\"\n\t\"arduino.cc/builder/i18n\"\n\t\"arduino.cc/builder/types\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype AddBuildBoardPropertyIfMissing struct{}\n\n\n\nfunc (s *AddBuildBoardPropertyIfMissing) Run(context map[string]interface{}) error ", "output": "{\n\tpackages := context[constants.CTX_HARDWARE].(map[string]*types.Package)\n\tlogger := context[constants.CTX_LOGGER].(i18n.Logger)\n\n\tfor _, aPackage := range packages {\n\t\tfor _, platform := range aPackage.Platforms {\n\t\t\tfor _, board := range platform.Boards {\n\t\t\t\tif board.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD] == constants.EMPTY_STRING {\n\t\t\t\t\tboard.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD] = strings.ToUpper(platform.PlatformId + \"_\" + board.BoardId)\n\t\t\t\t\tlogger.Fprintln(os.Stderr, constants.MSG_MISSING_BUILD_BOARD, aPackage.PackageId, platform.PlatformId, board.BoardId, board.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "\n\nfunc change(amount int, coins []int) int ", "output": "{\n dp := make([]int, amount+1)\n \n \n \n dp[0] = 1\n \n for _, coin := range coins {\n for i := 0; i <= amount; i++ {\n if i >= coin {\n dp[i] += dp[i-coin]\n }\n }\n }\n return dp[amount]\n}"} {"input": "package pusher\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"strings\"\n)\n\n\n\nfunc hmacBytes(toSign, secret []byte) []byte {\n\t_authSignature := hmac.New(sha256.New, secret)\n\t_authSignature.Write(toSign)\n\treturn _authSignature.Sum(nil)\n}\n\nfunc createAuthString(key, secret, stringToSign string) string {\n\tauthSignature := hmacSignature(stringToSign, secret)\n\treturn strings.Join([]string{key, authSignature}, \":\")\n}\n\nfunc hmacSignature(toSign, secret string) string ", "output": "{\n\treturn hex.EncodeToString(hmacBytes([]byte(toSign), []byte(secret)))\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n\twatchlist \"github.com/macarrie/flemzerd/watchlists\"\n\t\"github.com/macarrie/flemzerd/watchlists/impl/trakt\"\n)\n\nfunc performTraktAuth(c *gin.Context) {\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\tt := w.(*trakt.TraktWatchlist)\n\tif err := t.IsAuthenticated(); err == nil {\n\t\tc.AbortWithStatus(http.StatusNoContent)\n\t\treturn\n\t}\n\n\tgo t.Auth()\n\tc.JSON(http.StatusOK, gin.H{})\n\treturn\n}\n\nfunc getTraktAuthErrors(c *gin.Context) {\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tt := w.(*trakt.TraktWatchlist)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, t.GetAuthErrors())\n}\n\nfunc getTraktToken(c *gin.Context) {\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tt := w.(*trakt.TraktWatchlist)\n\tc.JSON(http.StatusOK, t.Token)\n}\n\n\n\nfunc getTraktDeviceCode(c *gin.Context) ", "output": "{\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\tt := w.(*trakt.TraktWatchlist)\n\tc.JSON(http.StatusOK, t.DeviceCode)\n\treturn\n}"} {"input": "package circular\n\nimport (\n\t\"errors\"\n)\n\n\ntype Buffer struct {\n\tsize int \n\tn int \n\tdata []byte \n\twrite, read int \n}\n\n\nfunc NewBuffer(size int) *Buffer {\n\n\treturn &Buffer{\n\t\tsize: size,\n\t\tdata: make([]byte, size),\n\t}\n}\n\n\nfunc (b *Buffer) ReadByte() (byte, error) {\n\tif b.n == 0 {\n\t\treturn 0, errors.New(\"no bytes read\")\n\t}\n\td := b.data[b.read]\n\tb.read = (b.read + 1) % b.size\n\tb.n--\n\treturn d, nil\n}\n\n\nfunc (b *Buffer) WriteByte(c byte) error {\n\tif b.write == b.read && b.n > 0 {\n\t\treturn errors.New(\"buffer is full\")\n\t}\n\tb.Overwrite(c)\n\treturn nil\n}\n\n\n\n\n\nfunc (b *Buffer) Reset() {\n\t*b = Buffer{\n\t\tsize: b.size,\n\t\tdata: make([]byte, b.size),\n\t}\n}\n\nfunc (b *Buffer) Overwrite(c byte) ", "output": "{\n\tif b.read == b.write && b.n > 0 {\n\t\tb.read = (b.read + 1) % b.size\n\t\tb.n--\n\t}\n\tb.data[b.write] = c\n\tb.write = (b.write + 1) % b.size\n\tb.n++\n}"} {"input": "package check\n\n\ntype GoFmt struct {\n\tDir string\n\tFilenames []string\n}\n\n\nfunc (g GoFmt) Name() string {\n\treturn \"gofmt\"\n}\n\n\n\n\n\nfunc (g GoFmt) Percentage() (float64, []FileSummary, error) {\n\treturn GoTool(g.Dir, g.Filenames, []string{\"gofmt\", \"-s\", \"-l\"})\n}\n\n\nfunc (g GoFmt) Description() string {\n\treturn `Gofmt formats Go programs. We run gofmt -s on your code, where -s is for the \"simplify\" command`\n}\n\nfunc (g GoFmt) Weight() float64 ", "output": "{\n\treturn .35\n}"} {"input": "package cm\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/kubernetes/pkg/kubelet/dockershim/libdocker\"\n)\n\ntype unsupportedContainerManager struct {\n}\n\n\nfunc NewContainerManager(_ string, _ libdocker.Interface) ContainerManager {\n\treturn &unsupportedContainerManager{}\n}\n\n\n\nfunc (m *unsupportedContainerManager) Start() error ", "output": "{\n\treturn fmt.Errorf(\"Container Manager is unsupported in this build\")\n}"} {"input": "package api\n\ntype FormatsResponse struct {\n\tFormats []string `json:\"formats\"`\n}\n\nfunc (a *API) getFormats(ctx *context) {\n\tctx.Success(FormatsResponse{Formats: a.c.formats.Keys()})\n}\n\ntype LeechTypesResponse struct {\n\tLeechTypes []string `json:\"leech_types\"`\n}\n\nfunc (a *API) getLeechTypes(ctx *context) {\n\tctx.Success(LeechTypesResponse{LeechTypes: a.c.leechTypes.Keys()})\n}\n\ntype MediaResponse struct {\n\tMedia []string `json:\"media\"`\n}\n\n\n\ntype ReleaseGroupTypesResponse struct {\n\tReleaseGroupTypes []string `json:\"release_group_types\"`\n}\n\nfunc (a *API) getReleaseGroupTypes(ctx *context) {\n\tctx.Success(ReleaseGroupTypesResponse{ReleaseGroupTypes: a.c.releaseGroupTypes.Keys()})\n}\n\ntype ReleasePropertiesResponse struct {\n\tReleaseProperties []string `json:\"release_properties\"`\n}\n\nfunc (a *API) getReleaseProperties(ctx *context) {\n\tctx.Success(ReleasePropertiesResponse{ReleaseProperties: a.c.releaseProperties.Keys()})\n}\n\ntype ReleaseRolesResponse struct {\n\tReleaseRoles []string `json:\"release_roles\"`\n}\n\nfunc (a *API) getReleaseRoles(ctx *context) {\n\tctx.Success(ReleaseRolesResponse{ReleaseRoles: a.c.releaseRoles.Keys()})\n}\n\ntype PrivilegesResponse struct {\n\tPrivileges []string `json:\"privileges\"`\n}\n\nfunc (a *API) getPrivileges(ctx *context) {\n\tctx.Success(PrivilegesResponse{Privileges: a.c.privileges.Keys()})\n}\n\nfunc (a *API) getMedia(ctx *context) ", "output": "{\n\tctx.Success(MediaResponse{Media: a.c.media.Keys()})\n}"} {"input": "package command\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"github.com/jpartogi/dosboxgo/console\"\n\t\"github.com/jpartogi/dosboxgo/filesystem\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype Processor struct {\n\tInvoker Invoker\n\tDrive filesystem.Drive\n\tOutputter console.Outputter\n}\n\n\n\nfunc (p *Processor) ProcessInput() {\n\tp.Outputter.Println(\"DOSBox, Scrum.org, Professional Scrum Developer Training\")\n\tp.Outputter.Println(\"Copyright (c) Joshua Partogi. All rights reserved.\")\n\n\tline := \"\"\n\treader := bufio.NewReader(os.Stdin)\n\n\tfor strings.ToLower(line) != \"exit\" {\n\t\tp.Outputter.NewLine()\n\t\tfmt.Print(\"C:\\\\>\")\n\n\t\ttext, _ := reader.ReadString('\\n')\n\t\tline = strings.TrimSpace(text)\n\n\t\tp.Invoker.ExecuteCommand(line)\n\t}\n}\n\nfunc NewProc(Invoker Invoker, Drive filesystem.Drive, Outputter console.Outputter) Processor ", "output": "{\n\treturn Processor{Invoker, Drive, Outputter}\n}"} {"input": "package wml\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\ntype CT_MailMergeDocType struct {\n\tValAttr ST_MailMergeDocType\n}\n\nfunc NewCT_MailMergeDocType() *CT_MailMergeDocType {\n\tret := &CT_MailMergeDocType{}\n\tret.ValAttr = ST_MailMergeDocType(1)\n\treturn ret\n}\n\n\n\nfunc (m *CT_MailMergeDocType) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tm.ValAttr = ST_MailMergeDocType(1)\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"val\" {\n\t\t\tm.ValAttr.UnmarshalXMLAttr(attr)\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_MailMergeDocType: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (m *CT_MailMergeDocType) Validate() error {\n\treturn m.ValidateWithPath(\"CT_MailMergeDocType\")\n}\n\n\nfunc (m *CT_MailMergeDocType) ValidateWithPath(path string) error {\n\tif m.ValAttr == ST_MailMergeDocTypeUnset {\n\t\treturn fmt.Errorf(\"%s/ValAttr is a mandatory field\", path)\n\t}\n\tif err := m.ValAttr.ValidateWithPath(path + \"/ValAttr\"); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (m *CT_MailMergeDocType) MarshalXML(e *xml.Encoder, start xml.StartElement) error ", "output": "{\n\tattr, err := m.ValAttr.MarshalXMLAttr(xml.Name{Local: \"w:val\"})\n\tif err != nil {\n\t\treturn err\n\t}\n\tstart.Attr = append(start.Attr, attr)\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}"} {"input": "package main_test\n\nimport (\n\t\"testing\"\n\n\tmain \"github.com/influxdb/influxdb/cmd/influx\"\n)\n\nfunc TestParseCommand_CommandsExist(t *testing.T) {\n\tt.Parallel()\n\tc := main.CommandLine{}\n\ttests := []struct {\n\t\tcmd string\n\t}{\n\t\t{cmd: \"gopher\"},\n\t\t{cmd: \"connect\"},\n\t\t{cmd: \"help\"},\n\t\t{cmd: \"pretty\"},\n\t\t{cmd: \"use\"},\n\t\t{cmd: \"\"}, \n\t}\n\tfor _, test := range tests {\n\t\tif !c.ParseCommand(test.cmd) {\n\t\t\tt.Fatalf(`Command failed for %q.`, test.cmd)\n\t\t}\n\t}\n}\n\nfunc TestParseCommand_TogglePretty(t *testing.T) {\n\tt.Parallel()\n\tc := main.CommandLine{}\n\tif c.Pretty {\n\t\tt.Fatalf(`Pretty should be false.`)\n\t}\n\tc.ParseCommand(\"pretty\")\n\tif !c.Pretty {\n\t\tt.Fatalf(`Pretty should be true.`)\n\t}\n\tc.ParseCommand(\"pretty\")\n\tif c.Pretty {\n\t\tt.Fatalf(`Pretty should be false.`)\n\t}\n}\n\nfunc TestParseCommand_Exit(t *testing.T) {\n\tt.Parallel()\n\tc := main.CommandLine{}\n\ttests := []struct {\n\t\tcmd string\n\t}{\n\t\t{cmd: \"exit\"},\n\t\t{cmd: \" exit\"},\n\t\t{cmd: \"exit \"},\n\t\t{cmd: \"Exit \"},\n\t}\n\n\tfor _, test := range tests {\n\t\tif c.ParseCommand(test.cmd) {\n\t\t\tt.Fatalf(`Command \"exit\" failed for %q.`, test.cmd)\n\t\t}\n\t}\n}\n\n\n\nfunc TestParseCommand_Use(t *testing.T) ", "output": "{\n\tt.Parallel()\n\tc := main.CommandLine{}\n\ttests := []struct {\n\t\tcmd string\n\t}{\n\t\t{cmd: \"use db\"},\n\t\t{cmd: \" use db\"},\n\t\t{cmd: \"use db \"},\n\t\t{cmd: \"Use db\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tif !c.ParseCommand(test.cmd) {\n\t\t\tt.Fatalf(`Command \"use\" failed for %q.`, test.cmd)\n\t\t}\n\t}\n}"} {"input": "package common\n\nimport (\n\t\"testing\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\n\nfunc Test_Pad_PKCS7(t *testing.T) ", "output": "{\n\tinput := []byte(\"YELLOW SUBMARINE\")\n\n\treceived := Pad_PKCS7(input, 4)\n\texpected := []byte(\"YELLOW SUBMARINE\\x04\\x04\\x04\\x04\")\n\n\tassert.Equal(t, expected, received)\n}"} {"input": "package ShortMessagingService\n\nimport \"fmt\"\n\n\ntype Message interface {\n\tSend(phone string, message string) (map[string]bool, error)\n}\n\nvar channels = make(map[string]ShortMessagingService)\n\n\ntype ShortMessagingService interface {\n\tParse(filename string) (Message, error)\n}\n\n\n\nfunc NewShortMessagingService(channel, filename string) (Message, error) {\n\tif service, ok := channels[channel]; ok {\n\t\treturn service.Parse(filename)\n\t}\n\treturn nil, fmt.Errorf(\"unknown sms channel: %q\", channel)\n}\n\n\n\n\nfunc Register(name string, sms ShortMessagingService) ", "output": "{\n\tif sms == nil {\n\t\tpanic(\"[SMS]: Register channel is nil\")\n\t}\n\tif _, ok := channels[name]; ok {\n\t\tpanic(\"[SMS]: Register called teice for channel \" + name)\n\t}\n\tchannels[name] = sms\n}"} {"input": "package test\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/pilosa/pilosa\"\n)\n\n\nfunc NewCluster(n int) *pilosa.Cluster {\n\tc := pilosa.NewCluster()\n\tc.ReplicaN = 1\n\tc.Hasher = NewModHasher()\n\n\tfor i := 0; i < n; i++ {\n\t\tc.Nodes = append(c.Nodes, &pilosa.Node{\n\t\t\tScheme: \"http\",\n\t\t\tHost: fmt.Sprintf(\"host%d\", i),\n\t\t})\n\t}\n\n\treturn c\n}\n\n\ntype ModHasher struct{}\n\n\nfunc NewModHasher() *ModHasher { return &ModHasher{} }\n\nfunc (*ModHasher) Hash(key uint64, n int) int { return int(key) % n }\n\n\ntype ConstHasher struct {\n\ti int\n}\n\n\n\n\nfunc (h *ConstHasher) Hash(key uint64, n int) int { return h.i }\n\nfunc NewConstHasher(i int) *ConstHasher ", "output": "{ return &ConstHasher{i: i} }"} {"input": "package vmware\n\nimport (\n\t\"fmt\"\n\t\"github.com/mitchellh/multistep\"\n\t\"github.com/mitchellh/packer/packer\"\n\t\"time\"\n)\n\n\n\n\n\n\n\n\n\n\n\ntype stepRun struct {\n\tbootTime time.Time\n\tvmxPath string\n}\n\n\n\nfunc (s *stepRun) Cleanup(state map[string]interface{}) {\n\tdriver := state[\"driver\"].(Driver)\n\tui := state[\"ui\"].(packer.Ui)\n\n\tif s.vmxPath != \"\" {\n\t\tsinceBootTime := time.Since(s.bootTime)\n\t\twaitBootTime := 5 * time.Second\n\t\tif sinceBootTime < waitBootTime {\n\t\t\tsleepTime := waitBootTime - sinceBootTime\n\t\t\tui.Say(fmt.Sprintf(\"Waiting %s to give VMware time to clean up...\", sleepTime.String()))\n\t\t\ttime.Sleep(sleepTime)\n\t\t}\n\n\t\trunning, _ := driver.IsRunning(s.vmxPath)\n\t\tif running {\n\t\t\tui.Say(\"Stopping virtual machine...\")\n\t\t\tif err := driver.Stop(s.vmxPath); err != nil {\n\t\t\t\tui.Error(fmt.Sprintf(\"Error stopping VM: %s\", err))\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (s *stepRun) Run(state map[string]interface{}) multistep.StepAction ", "output": "{\n\tconfig := state[\"config\"].(*config)\n\tdriver := state[\"driver\"].(Driver)\n\tui := state[\"ui\"].(packer.Ui)\n\tvmxPath := state[\"vmx_path\"].(string)\n\n\ts.bootTime = time.Now()\n\ts.vmxPath = vmxPath\n\n\tui.Say(\"Starting virtual machine...\")\n\tif err := driver.Start(vmxPath); err != nil {\n\t\terr := fmt.Errorf(\"Error starting VM: %s\", err)\n\t\tstate[\"error\"] = err\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\tif int64(config.BootWait) > 0 {\n\t\tui.Say(fmt.Sprintf(\"Waiting %s for boot...\", config.BootWait.String()))\n\t\ttime.Sleep(config.BootWait)\n\t}\n\n\treturn multistep.ActionContinue\n}"} {"input": "package TeleGogo\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n)\n\nfunc responseToError(response *http.Response) error {\n\treturn responseToTgError(response)\n}\n\nfunc responseToTgError(response *http.Response) TelegramError {\n\tdefer response.Body.Close()\n\ttgErr := telegramError{}\n\tjson.NewDecoder(response.Body).Decode(&tgErr)\n\treturn tgErr\n}\n\nfunc errToTelegramErr(err error) TelegramError {\n\treturn telegramError{OK: false, ErrorCode: 0, Description: err.Error()}\n}\n\ntype telegramError struct {\n\tOK bool `json:\"ok\"`\n\tErrorCode int `json:\"error_code\"`\n\tDescription string `json:\"description\"`\n}\n\nfunc (t telegramError) IsOK() bool {\n\treturn t.OK\n}\n\n\n\nfunc (t telegramError) Error() string {\n\treturn t.Description\n}\n\n\ntype TelegramError interface {\n\tIsOK() bool\n\tErrCode() int\n\tError() string\n}\n\nfunc (t telegramError) ErrCode() int ", "output": "{\n\treturn t.ErrorCode\n}"} {"input": "package loaders\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\n\t\"github.com/ftcjeff/ConfigurationProcessor/logger\"\n\t\"github.com/ftcjeff/ConfigurationProcessor/types\"\n)\n\n\n\nfunc ElementLoader(id int, fileName string, channel chan types.ElementChannel) ", "output": "{\n\tdefer logger.Trace(logger.Enter())\n\n\traw, err := ioutil.ReadFile(fileName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar e types.ElementDataType\n\terr = json.Unmarshal(raw, &e)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar ec types.ElementChannel\n\tec.Id = id\n\tec.Element = e\n\n\tchannel <- ec\n}"} {"input": "package alert\n\nimport (\n\t. \"aliyun-openapi-go-sdk/core\"\n)\n\ntype GetContactGroupRequest struct {\n\tRoaRequest\n\tProjectName string\n\tGroupName string\n}\n\nfunc (r *GetContactGroupRequest) SetProjectName(value string) {\n\tr.ProjectName = value\n\tr.PathParams.Set(\"ProjectName\", value)\n}\nfunc (r *GetContactGroupRequest) GetProjectName() string {\n\treturn r.ProjectName\n}\nfunc (r *GetContactGroupRequest) SetGroupName(value string) {\n\tr.GroupName = value\n\tr.PathParams.Set(\"GroupName\", value)\n}\nfunc (r *GetContactGroupRequest) GetGroupName() string {\n\treturn r.GroupName\n}\n\nfunc (r *GetContactGroupRequest) Init() {\n\tr.RoaRequest.Init()\n\tr.PathPattern = \"/projects/ProjectName/groups/GroupName\"\n\tr.SetMethod(\"GET\")\n\tr.SetProtocol(\"HTTP\")\n\tr.SetProduct(Product)\n}\n\ntype GetContactGroupResponse struct {\n\tcode string `xml:\"code\" json:\"code\"`\n\tmessage string `xml:\"message\" json:\"message\"`\n\tsuccess string `xml:\"success\" json:\"success\"`\n\ttraceId string `xml:\"traceId\" json:\"traceId\"`\n\tresult string `xml:\"result\" json:\"result\"`\n}\n\n\n\nfunc GetContactGroup(req *GetContactGroupRequest, accessId, accessSecret string) (*GetContactGroupResponse, error) ", "output": "{\n\tvar pResponse GetContactGroupResponse\n\tbody, err := ApiHttpRequest(accessId, accessSecret, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tApiUnmarshalResponse(req.GetFormat(), body, &pResponse)\n\treturn &pResponse, err\n}"} {"input": "package sw\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\n\t\"github.com/hyperledger/fabric/core/crypto/bccsp\"\n\t\"github.com/hyperledger/fabric/core/crypto/primitives\"\n)\n\ntype rsaPrivateKey struct {\n\tk *rsa.PrivateKey\n}\n\n\n\nfunc (k *rsaPrivateKey) Bytes() (raw []byte, err error) {\n\treturn\n}\n\n\nfunc (k *rsaPrivateKey) SKI() (ski []byte) {\n\traw := x509.MarshalPKCS1PrivateKey(k.k)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\n\n\n\n\nfunc (k *rsaPrivateKey) Private() bool {\n\treturn true\n}\n\n\n\nfunc (k *rsaPrivateKey) PublicKey() (bccsp.Key, error) {\n\treturn &rsaPublicKey{&k.k.PublicKey}, nil\n}\n\ntype rsaPublicKey struct {\n\tk *rsa.PublicKey\n}\n\n\n\nfunc (k *rsaPublicKey) Bytes() (raw []byte, err error) {\n\traw, err = x509.MarshalPKIXPublicKey(k.k)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed marshalling key [%s]\", err)\n\t}\n\treturn\n}\n\n\nfunc (k *rsaPublicKey) SKI() (ski []byte) {\n\traw, _ := primitives.PublicKeyToPEM(k.k, nil)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\nfunc (k *rsaPublicKey) Symmetric() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) Private() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) PublicKey() (bccsp.Key, error) {\n\treturn k, nil\n}\n\nfunc (k *rsaPrivateKey) Symmetric() bool ", "output": "{\n\treturn false\n}"} {"input": "package unix\n\nimport \"syscall\"\n\nfunc setTimespec(sec, nsec int64) Timespec {\n\treturn Timespec{Sec: int32(sec), Nsec: int32(nsec)}\n}\n\n\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint32(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint32(length)\n}\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\nfunc (msghdr *Msghdr) SetIovlen(length int) {\n\tmsghdr.Iovlen = int32(length)\n}\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\nfunc Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)\n\nfunc setTimeval(sec, usec int64) Timeval ", "output": "{\n\treturn Timeval{Sec: int32(sec), Usec: int32(usec)}\n}"} {"input": "package v1\n\nimport (\n\tv1 \"github.com/openshift/api/console/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype ConsoleYAMLSampleLister interface {\n\tList(selector labels.Selector) (ret []*v1.ConsoleYAMLSample, err error)\n\tGet(name string) (*v1.ConsoleYAMLSample, error)\n\tConsoleYAMLSampleListerExpansion\n}\n\n\ntype consoleYAMLSampleLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewConsoleYAMLSampleLister(indexer cache.Indexer) ConsoleYAMLSampleLister {\n\treturn &consoleYAMLSampleLister{indexer: indexer}\n}\n\n\nfunc (s *consoleYAMLSampleLister) List(selector labels.Selector) (ret []*v1.ConsoleYAMLSample, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ConsoleYAMLSample))\n\t})\n\treturn ret, err\n}\n\n\n\n\nfunc (s *consoleYAMLSampleLister) Get(name string) (*v1.ConsoleYAMLSample, error) ", "output": "{\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"consoleyamlsample\"), name)\n\t}\n\treturn obj.(*v1.ConsoleYAMLSample), nil\n}"} {"input": "package slackhook_test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"testing\"\n\n\t. \"github.com/lytics/slackhook\"\n)\n\ntype fakeposter struct {\n\tbody []byte\n}\n\nfunc (p *fakeposter) Post(_, _ string, body io.Reader) (*http.Response, error) {\n\tp.body, _ = ioutil.ReadAll(body)\n\treturn &http.Response{Body: ioutil.NopCloser(bytes.NewBuffer(nil)), StatusCode: 200}, nil\n}\n\nfunc TestSimple(t *testing.T) {\n\ttxt := \"test\"\n\ts := New(\"\")\n\tfake := &fakeposter{}\n\ts.HTTPClient = fake\n\tif err := s.Simple(txt); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tmsg := Message{}\n\tif err := json.Unmarshal(fake.body, &msg); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif msg.Text != txt {\n\t\tt.Errorf(\"Expected text=%q but found %q\", txt, msg.Text)\n\t}\n\tif msg.Channel != \"\" {\n\t\tt.Errorf(\"Expected channel to be empty but found %q\", msg.Channel)\n\t}\n\tif msg.UserName != \"\" {\n\t\tt.Errorf(\"Expected username to be empty but found %q\", msg.UserName)\n\t}\n\tif msg.IconURL != \"\" {\n\t\tt.Errorf(\"Expected icon_url to be empty but found %q\", msg.IconURL)\n\t}\n\tif msg.IconEmoji != \"\" {\n\t\tt.Errorf(\"Expected icon_emoji to be empty but found %q\", msg.IconEmoji)\n\t}\n}\n\n\n\nfunc TestAttachment(t *testing.T) ", "output": "{\n\ts := New(\"\")\n\tfake := &fakeposter{}\n\ts.HTTPClient = fake\n\n\tmsg := &Message{Text: \"Hello Slack!\"}\n\tmsg.AddAttachment(&Attachment{\n\t\tColor: \"danger\",\n\t})\n\tif err := s.Send(msg); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tm := &Message{}\n\tif err := json.Unmarshal(fake.body, m); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif len(m.Attachments) != 1 {\n\t\tt.Errorf(\"Expected to have exactly 1 attachment but found %d\", len(m.Attachments))\n\t}\n\n\tif m.Attachments[0].Color != \"danger\" {\n\t\tt.Errorf(\"Expected attachment to have color 'danger' but found '%d'\", m.Attachments[0].Color)\n\t}\n}"} {"input": "package texas\n\ntype SeatResultList []*SeatResult\n\ntype SeatResult struct {\n\tm_seat *SeatPlayer\n\tpot_idx int\n\tcard_type int\n\tcard_list CardDataList\n}\n\n\n\nfunc (this *SeatResult) Trace() {\n\tprintln(\"玩家:\", this.m_seat.m_seat_id, POKER_TYPE_STR[this.card_type], TraceBigCards(this.card_list))\n}\n\n\nfunc (this SeatResultList) Len() int {\n\treturn len(this)\n}\n\n\nfunc (this SeatResultList) Less(i, j int) bool {\n\treturn this[i].card_type > this[j].card_type\n}\n\nfunc (this SeatResultList) Swap(i, j int) {\n\ttemp := this[i]\n\tthis[i] = this[j]\n\tthis[j] = temp\n}\n\nfunc NewSeatResult(seat *SeatPlayer, cards []int16) *SeatResult ", "output": "{\n\tthis := new(SeatResult)\n\tthis.m_seat = seat\n\tthis.pot_idx = seat.m_pot_point\n\tthis.card_type, this.card_list = CardTypeOfTexas(cards)\n\treturn this\n}"} {"input": "package types\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v1\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc newLocalDevicesObj() *LocalDevices {\n\treturn &LocalDevices{\n\t\tDriver: \"vfs\",\n\t\tDeviceMap: map[string]string{\n\t\t\t\"vfs-000\": \"/dev/xvda\",\n\t\t\t\"vfs-001\": \"/dev/xvdb\",\n\t\t\t\"vfs-002\": \"/dev/xvdc\",\n\t\t},\n\t}\n}\n\nvar expectedLD1String = \"vfs=vfs-000::/dev/xvda,vfs-001::/dev/xvdb,vfs-002::/dev/xvdc\"\n\nfunc TestLocalDevicesMarshalText(t *testing.T) {\n\n\tld1 := newLocalDevicesObj()\n\tassert.Equal(t, expectedLD1String, ld1.String())\n\tt.Logf(\"localDevices=%s\", ld1)\n\n\tld2 := &LocalDevices{}\n\tassert.NoError(t, ld2.UnmarshalText([]byte(ld1.String())))\n\tassert.EqualValues(t, ld1, ld2)\n}\n\n\n\nfunc TestLocalDevicesMarshalJSON(t *testing.T) {\n\n\tld1 := newLocalDevicesObj()\n\n\tbuf, err := ld1.MarshalJSON()\n\tassert.NoError(t, err)\n\tt.Logf(\"localDevices=%s\", string(buf))\n\n\tld2 := &LocalDevices{}\n\tassert.NoError(t, ld2.UnmarshalJSON(buf))\n\n\tassert.EqualValues(t, ld1, ld2)\n}\n\nfunc TestLocalDevicesMarshalToYAML(t *testing.T) {\n\tout, err := yaml.Marshal(newLocalDevicesObj())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfmt.Println(string(out))\n}\n\nfunc TestLocalDevicesUnmarshalText(t *testing.T) ", "output": "{\n\n\tld1 := &LocalDevices{}\n\terr := ld1.UnmarshalText([]byte(\"scaleio=\"))\n\tassert.NoError(t, err)\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\tfmt.Println(\"vim-go\")\n}\n\nfunc removeDuplicates(nums []int) int ", "output": "{\n\tif len(nums) == 0 {\n\t\treturn 0\n\t}\n\n\tpos := 0\n\tfor i := 1; i < len(nums); i++ {\n\t\tif nums[i] != nums[pos] {\n\t\t\tpos++\n\t\t\tnums[pos] = nums[i]\n\t\t}\n\t}\n\n\treturn pos + 1\n}"} {"input": "package entrapped\n\nimport (\n\t\"github.com/SKatiyar/entrapped/Godeps/_workspace/src/github.com/julienschmidt/httprouter\"\n\t\"net/http\"\n)\n\nconst (\n\tsize int = 7\n\tnumBombs int = 10\n\tlifes int = 5\n\tnumBonusLifes int = 2\n)\n\nfunc Start(addr string) {\n\tif len(addr) == 0 {\n\t\taddr = \":7000\"\n\t}\n\n\tgo ch.run()\n\n\trouter := httprouter.New()\n\n\trouter.GET(\"/\", home)\n\trouter.ServeFiles(\"/statics/*filepath\", http.Dir(\"client/dist/statics\"))\n\n\trouter.GET(\"/players/:id\", addPlayer)\n\n\tlistenErr := http.ListenAndServe(addr, router)\n\tif listenErr != nil {\n\t\tlogger.Println(listenErr)\n\t\treturn\n\t}\n}\n\nfunc addPlayer(rw http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tid := params.ByName(\"id\")\n\n\tws, wsErr := upgrader.Upgrade(rw, req, nil)\n\tif wsErr != nil {\n\t\tlogger.Println(wsErr)\n\t\treturn\n\t}\n\n\ttrap := makeTrap(size, numBombs, numBonusLifes, lifes)\n\n\tch.add(&trooper{id, trap, ws, make(chan []byte, 512)})\n}\n\n\n\nfunc home(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) ", "output": "{\n\trw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\thttp.ServeFile(rw, req, \"client/dist/index.html\")\n}"} {"input": "package request\n\nimport (\n \"bytes\"\n \"encoding/json\"\n \"io/ioutil\"\n)\n\n\ntype Handlers struct {\n RequestHandler func(*Request, *interface{}) error\n ResponseHandler func(*Request, *interface{}) error\n}\n\n\nfunc RequestHandler(request *Request, input *interface{}) error {\n jsonstr, err := json.Marshal(&input)\n request.HTTPRequest.Body = ioutil.NopCloser(bytes.NewBuffer(jsonstr))\n return err\n}\n\n\nfunc ResponseHandler(request *Request, output *interface{}) error {\n return json.Unmarshal(request.Body, &output)\n}\n\n\n\n\n\nfunc ListResponseHandler(request *Request, output *interface{}) error ", "output": "{\n var objmap map[string]*json.RawMessage\n err := json.Unmarshal(request.Body, &objmap)\n if err != nil {\n return err\n }\n return json.Unmarshal(*objmap[\"results\"], &output)\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n)\n\ntype BuiltInClass struct {\n\tname Instance\n\tsupers []Class\n\tslots []Instance\n}\n\n\n\nfunc (p BuiltInClass) Supers() []Class {\n\treturn p.supers\n}\n\nfunc (p BuiltInClass) Slots() []Instance {\n\treturn p.slots\n}\n\nfunc (p BuiltInClass) Initform(arg Instance) (v Instance, ok bool) {\n\treturn nil, false\n}\n\nfunc (p BuiltInClass) Initarg(arg Instance) (v Instance, ok bool) {\n\treturn arg, true\n}\n\nfunc (BuiltInClass) Class() Class {\n\treturn BuiltInClassClass\n}\n\nfunc (p BuiltInClass) String() string {\n\treturn fmt.Sprint(p.name)\n}\n\nfunc NewBuiltInClass(name string, super Class, slots ...string) Class ", "output": "{\n\tslotNames := []Instance{}\n\tfor _, slot := range slots {\n\t\tslotNames = append(slotNames, NewSymbol(slot))\n\t}\n\treturn BuiltInClass{NewSymbol(name), []Class{super}, slotNames}\n}"} {"input": "package logger\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"gopkg.in/clever/kayvee-go.v2\"\n)\n\n\ntype M map[string]interface{}\n\n\n\n\n\nfunc Trace(title string, data M) {\n\tlogWithLevel(title, kayvee.Trace, data)\n}\n\n\nfunc Warning(title string, data M) {\n\tlogWithLevel(title, kayvee.Warning, data)\n}\n\n\nfunc Critical(title string, data M) {\n\tlogWithLevel(title, kayvee.Critical, data)\n}\n\n\nfunc Error(title string, err error) {\n\tlogWithLevel(title, kayvee.Error, M{\"error\": fmt.Sprint(err)})\n}\n\n\nfunc ErrorDetailed(title string, err error, extras M) {\n\textras[\"error\"] = fmt.Sprint(err)\n\tlogWithLevel(title, kayvee.Error, extras)\n}\n\nfunc logWithLevel(title string, level kayvee.LogLevel, data M) {\n\tformatted := kayvee.FormatLog(\"moredis\", level, title, data)\n\tlog.Println(formatted)\n}\n\nfunc Info(title string, data M) ", "output": "{\n\tlogWithLevel(title, kayvee.Info, data)\n}"} {"input": "package operations\n\n\n\n\n\nfunc mountItem(method, path string, handler interface{}) {}\n\nfunc ServeAPI(host, basePath string, schemes []string) (err error) ", "output": "{\n\tmountItem(\"GET\", basePath+\"/pets\", nil)\n\n\tmountItem(\"PUT\", basePath+\"/pets/{id}\", nil)\n\n\tmountItem(\"GET\", basePath+\"/events\", nil)\n\n\treturn\n}"} {"input": "package incoming\n\nimport (\n\t\"github.com/pkg/errors\"\n)\n\ntype ignorableErr struct {\n\terror\n}\n\nfunc (e ignorableErr) Ignorable() bool {\n\treturn true\n}\n\nfunc wrapIgnorable(err error) error {\n\treturn ignorableErr{error: err}\n}\n\n\n\nfunc (m *RuleMap) Set(name string, r *Rule) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tif m.rules == nil {\n\t\tm.rules = make(map[string]*Rule)\n\t}\n\n\tm.rules[name] = r\n}\n\nfunc (r Rule) Disabled() bool {\n\treturn false\n}\n\nfunc (r Rule) AggregationWindow() int64 {\n\treturn 300\n}\n\nfunc (m *RuleMap) Get(name string) (*Rule, error) ", "output": "{\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tif m.rules == nil {\n\t\treturn nil, wrapIgnorable(errors.New(\"rule not found: '\" + name + \"'\"))\n\t}\n\n\tr, ok := m.rules[name]\n\tif !ok {\n\t\treturn nil, wrapIgnorable(errors.New(\"rule not found: '\" + name + \"'\"))\n\t}\n\treturn r, nil\n}"} {"input": "package travis\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nvar (\n\tintegrationClient *Client\n\tintegrationToken string\n\tintegrationUrl string = TRAVIS_API_DEFAULT_URL\n\tintegrationRepo string = \"Ableton/go-travis\"\n)\n\n\n\nfunc init() ", "output": "{\n\turl := os.Getenv(\"TRAVIS_API_URL\")\n\tif url != \"\" {\n\t\tintegrationUrl = url\n\t}\n\n\tintegrationToken := os.Getenv(\"TRAVIS_API_AUTH_TOKEN\")\n\tif integrationToken == \"\" {\n\t\tfmt.Println(\n\t\t\t\"TRAVIS_API_AUTH_TOKEN environment variable not set. \",\n\t\t\t\"Unable to authenticate the integration tests client. \",\n\t\t\t\"Some tests won't run!\",\n\t\t)\n\t}\n\n\tintegrationClient = NewClient(integrationUrl, integrationToken)\n}"} {"input": "package jpsplus\n\nimport (\n\t\"container/heap\"\n)\n\ntype PriorityQueue struct {\n\tpos int\n\tnode map[int]*Node\n}\n\nfunc newPriorityQueue() *PriorityQueue {\n\tp := new(PriorityQueue)\n\tp.node = make(map[int]*Node)\n\treturn p\n}\n\nfunc (p *PriorityQueue) Len() int {\n\treturn len(p.node)\n}\n\n\n\nfunc (p *PriorityQueue) Swap(i, j int) {\n\tp.node[i], p.node[j] = p.node[j], p.node[i]\n\tp.node[i].heapIndex = i\n\tp.node[j].heapIndex = j\n}\n\nfunc (p *PriorityQueue) Push(x interface{}) {\n\titem, ok := x.(*Node)\n\tif ok {\n\t\titem.heapIndex = p.pos\n\t\tp.node[p.pos] = item\n\t\tp.pos++\n\t}\n}\n\nfunc (p *PriorityQueue) Pop() interface{} {\n\tp.pos--\n\titem := p.node[p.pos]\n\tdelete(p.node, p.pos)\n\treturn item\n}\n\nfunc (p *PriorityQueue) PushNode(n *Node) {\n\theap.Push(p, n)\n}\n\nfunc (p *PriorityQueue) PopNode() *Node {\n\treturn heap.Pop(p).(*Node)\n}\n\nfunc (p *PriorityQueue) RemoveNode(n *Node) {\n\theap.Remove(p, n.heapIndex)\n}\n\nfunc (p *PriorityQueue) Less(i, j int) bool ", "output": "{\n\treturn p.node[i].finalCost < p.node[j].finalCost\n}"} {"input": "package rpc\n\nimport (\n\t\"cgl.tideland.biz/asserts\"\n\t\"github.com/mitchellh/packer/packer\"\n\t\"net/rpc\"\n\t\"testing\"\n)\n\ntype testHook struct {\n\trunCalled bool\n\trunUi packer.Ui\n}\n\nfunc (h *testHook) Run(name string, ui packer.Ui, comm packer.Communicator, data interface{}) error {\n\th.runCalled = true\n\treturn nil\n}\n\n\n\nfunc TestHook_Implements(t *testing.T) {\n\tassert := asserts.NewTestingAsserts(t, true)\n\n\tvar r packer.Hook\n\th := &hook{nil}\n\n\tassert.Implementor(h, &r, \"should be a Hook\")\n}\n\nfunc TestHookRPC(t *testing.T) ", "output": "{\n\tassert := asserts.NewTestingAsserts(t, true)\n\n\th := new(testHook)\n\n\tserver := rpc.NewServer()\n\tRegisterHook(server, h)\n\taddress := serveSingleConn(server)\n\n\tclient, err := rpc.Dial(\"tcp\", address)\n\tassert.Nil(err, \"should be able to connect\")\n\n\thClient := Hook(client)\n\n\tui := &testUi{}\n\thClient.Run(\"foo\", ui, nil, 42)\n\tassert.True(h.runCalled, \"run should be called\")\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\nvar cliParamsTcs = []struct {\n\tparams []string\n\tresultIsError bool\n}{\n\t{[]string{\"FOO=BAR\", \"BAZ=BLAH\"}, false},\n\t{[]string{\"FOO=BAR\", \"BAZ\"}, true},\n}\n\nfunc TestValidateCliParameters(t *testing.T) {\n\tfor _, tc := range cliParamsTcs {\n\t\terr := validateCliParameters(tc.params)\n\t\tif (err != nil) != tc.resultIsError {\n\t\t\tt.Fatalf(\"Expected '%v' got '%v' for '%v'\", tc.resultIsError, err, tc.params)\n\t\t}\n\t}\n}\n\nvar cliExistsTcs = []struct {\n\tcmd string\n\tresultIsError bool\n}{\n\t{\"ls\", false},\n\t{\"no-way-this-exists\", true},\n}\n\n\n\nvar templateExistsTcs = []struct {\n\tfile string\n\tcreateTmpFile bool\n\tresultIsError bool\n}{\n\t{\"\", true, false},\n\t{\"/no-way-this-exists\", false, true},\n}\n\nfunc TestValidateTemplateExists(t *testing.T) {\n\tfor _, tc := range templateExistsTcs {\n\t\tif tc.createTmpFile {\n\t\t\tf, err := ioutil.TempFile(\"\", \"cfn-clone-test\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Unable to create temp file for testing ValidateTemplateExists\")\n\t\t\t}\n\n\t\t\tdefer f.Close()\n\t\t\ttc.file = f.Name()\n\t\t}\n\n\t\terr := validateTemplateExists(tc.file)\n\t\tif (err != nil) != tc.resultIsError {\n\t\t\tt.Fatalf(\"Expected '%v' got '%v' for '%v'\", tc.resultIsError, err, tc.file)\n\t\t}\n\t}\n}\n\nfunc TestValidateCliExists(t *testing.T) ", "output": "{\n\tfor _, tc := range cliExistsTcs {\n\t\terr := validateCliExists(tc.cmd)\n\t\tif (err != nil) != tc.resultIsError {\n\t\t\tt.Fatalf(\"Expected '%v' got '%v' for '%v'\", tc.resultIsError, err, tc.cmd)\n\t\t}\n\t}\n}"} {"input": "package bosh\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/cloudfoundry/bosh-bootloader/storage\"\n)\n\ntype ConfigUpdater struct {\n\tboshCLIProvider boshCLIProvider\n\tboshCLI AuthenticatedCLIRunner\n}\n\ntype boshCLIProvider interface {\n\tAuthenticatedCLI(jumpbox storage.Jumpbox, stderr io.Writer, directorAddress, directorUsername, directorPassword, directorCACert string) (AuthenticatedCLIRunner, error)\n}\n\nfunc NewConfigUpdater(boshCLIProvider boshCLIProvider) ConfigUpdater {\n\treturn ConfigUpdater{boshCLIProvider: boshCLIProvider}\n}\n\nfunc (c ConfigUpdater) InitializeAuthenticatedCLI(state storage.State) (AuthenticatedCLIRunner, error) {\n\tboshCLI, err := c.boshCLIProvider.AuthenticatedCLI(\n\t\tstate.Jumpbox,\n\t\tos.Stderr,\n\t\tstate.BOSH.DirectorAddress,\n\t\tstate.BOSH.DirectorUsername,\n\t\tstate.BOSH.DirectorPassword,\n\t\tstate.BOSH.DirectorSSLCA,\n\t)\n\n\tif err != nil {\n\t\treturn AuthenticatedCLI{}, fmt.Errorf(\"failed to create bosh cli: %s\", err)\n\t}\n\n\treturn boshCLI, nil\n}\n\n\n\nfunc (c ConfigUpdater) UpdateRuntimeConfig(boshCLI AuthenticatedCLIRunner, filepath string, opsFilepaths []string, name string) error {\n\targs := []string{\"update-runtime-config\", filepath}\n\tfor _, opsFilepath := range opsFilepaths {\n\t\targs = append(args, \"--ops-file\", opsFilepath)\n\t}\n\targs = append(args, \"--name\", name)\n\n\treturn boshCLI.Run(nil, \"\", args)\n}\n\nfunc (c ConfigUpdater) UpdateCloudConfig(boshCLI AuthenticatedCLIRunner, filepath string, opsFilepaths []string, varsFilepath string) error ", "output": "{\n\targs := []string{\"update-cloud-config\", filepath}\n\tfor _, opsFilepath := range opsFilepaths {\n\t\targs = append(args, \"--ops-file\", opsFilepath)\n\t}\n\targs = append(args, \"--vars-file\", varsFilepath)\n\n\treturn boshCLI.Run(nil, \"\", args)\n}"} {"input": "package test\n\nimport \"io\"\n\n\ntype PlainReader struct {\n\tr io.Reader\n}\n\n\nfunc NewPlainReader(r io.Reader) *PlainReader {\n\treturn &PlainReader{r}\n}\n\n\nfunc (r *PlainReader) Read(p []byte) (int, error) {\n\treturn r.r.Read(p)\n}\n\n\n\n\ntype ErrorReader struct {\n\tn int\n}\n\n\nfunc NewErrorReader(n int) *ErrorReader {\n\treturn &ErrorReader{n}\n}\n\n\nfunc (r *ErrorReader) Read(b []byte) (n int, err error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tif r.n == 0 {\n\t\treturn 0, ErrPlain\n\t}\n\tr.n--\n\tb[0] = '.'\n\treturn 1, nil\n}\n\n\n\n\ntype InfiniteReader struct{}\n\n\nfunc NewInfiniteReader() *InfiniteReader {\n\treturn &InfiniteReader{}\n}\n\n\nfunc (r *InfiniteReader) Read(b []byte) (n int, err error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tb[0] = '.'\n\treturn 1, nil\n}\n\n\n\n\ntype EmptyReader struct {\n}\n\n\n\n\n\nfunc (r *EmptyReader) Read(b []byte) (n int, err error) {\n\treturn 0, io.EOF\n}\n\nfunc NewEmptyReader() *EmptyReader ", "output": "{\n\treturn &EmptyReader{}\n}"} {"input": "package serialconsole\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/serialconsole/mgmt/2018-05-01/serialconsole\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype BaseClient = original.BaseClient\ntype ConsoleClient = original.ConsoleClient\ntype DeploymentValidateResult = original.DeploymentValidateResult\ntype GetDisabledResult = original.GetDisabledResult\ntype GetResult = original.GetResult\ntype ListClient = original.ListClient\ntype ListConsoleClient = original.ListConsoleClient\ntype Operations = original.Operations\ntype SetDisabledResult = original.SetDisabledResult\n\nfunc New(subscriptionID string) BaseClient {\n\treturn original.New(subscriptionID)\n}\nfunc NewConsoleClient(subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClient(subscriptionID)\n}\nfunc NewConsoleClientWithBaseURI(baseURI string, subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewListClient(subscriptionID string) ListClient {\n\treturn original.NewListClient(subscriptionID)\n}\nfunc NewListClientWithBaseURI(baseURI string, subscriptionID string) ListClient {\n\treturn original.NewListClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewListConsoleClient(subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClient(subscriptionID)\n}\nfunc NewListConsoleClientWithBaseURI(baseURI string, subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\n\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient ", "output": "{\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}"} {"input": "package extended\n\nimport \"jvmgo/ch06/instructions/base\"\nimport \"jvmgo/ch06/rtda\"\n\n\ntype IFNULL struct{ base.BranchInstruction }\n\n\n\n\ntype IFNONNULL struct{ base.BranchInstruction }\n\nfunc (self *IFNONNULL) Execute(frame *rtda.Frame) {\n\tref := frame.OperandStack().PopRef()\n\tif ref != nil {\n\t\tbase.Branch(frame, self.Offset)\n\t}\n}\n\nfunc (self *IFNULL) Execute(frame *rtda.Frame) ", "output": "{\n\tref := frame.OperandStack().PopRef()\n\tif ref == nil {\n\t\tbase.Branch(frame, self.Offset)\n\t}\n}"} {"input": "package ultradns\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/Ensighten/udnssdk\"\n)\n\n\ntype Config struct {\n\tUsername string\n\tPassword string\n\tBaseURL string\n}\n\n\n\n\nfunc (c *Config) Client() (*udnssdk.Client, error) ", "output": "{\n\tclient, err := udnssdk.NewClient(c.Username, c.Password, c.BaseURL)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error setting up client: %s\", err)\n\t}\n\n\tlog.Printf(\"[INFO] UltraDNS Client configured for user: %s\", c.Username)\n\n\treturn client, nil\n}"} {"input": "package model\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/utils\"\n\n\t\"errors\"\n\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/converter\"\n\n\t\"strings\"\n)\n\n\ntype PrePaidServerSchedulerHints struct {\n\n\tGroup *string `json:\"group,omitempty\"`\n\n\tTenancy *PrePaidServerSchedulerHintsTenancy `json:\"tenancy,omitempty\"`\n\n\tDedicatedHostId *string `json:\"dedicated_host_id,omitempty\"`\n}\n\nfunc (o PrePaidServerSchedulerHints) String() string {\n\tdata, err := utils.Marshal(o)\n\tif err != nil {\n\t\treturn \"PrePaidServerSchedulerHints struct{}\"\n\t}\n\n\treturn strings.Join([]string{\"PrePaidServerSchedulerHints\", string(data)}, \" \")\n}\n\ntype PrePaidServerSchedulerHintsTenancy struct {\n\tvalue string\n}\n\ntype PrePaidServerSchedulerHintsTenancyEnum struct {\n\tSHARED PrePaidServerSchedulerHintsTenancy\n\tDEDICATED PrePaidServerSchedulerHintsTenancy\n}\n\nfunc GetPrePaidServerSchedulerHintsTenancyEnum() PrePaidServerSchedulerHintsTenancyEnum {\n\treturn PrePaidServerSchedulerHintsTenancyEnum{\n\t\tSHARED: PrePaidServerSchedulerHintsTenancy{\n\t\t\tvalue: \"shared\",\n\t\t},\n\t\tDEDICATED: PrePaidServerSchedulerHintsTenancy{\n\t\t\tvalue: \"dedicated\",\n\t\t},\n\t}\n}\n\nfunc (c PrePaidServerSchedulerHintsTenancy) MarshalJSON() ([]byte, error) {\n\treturn utils.Marshal(c.value)\n}\n\n\n\nfunc (c *PrePaidServerSchedulerHintsTenancy) UnmarshalJSON(b []byte) error ", "output": "{\n\tmyConverter := converter.StringConverterFactory(\"string\")\n\tif myConverter != nil {\n\t\tval, err := myConverter.CovertStringToInterface(strings.Trim(string(b[:]), \"\\\"\"))\n\t\tif err == nil {\n\t\t\tc.value = val.(string)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t} else {\n\t\treturn errors.New(\"convert enum data to string error\")\n\t}\n}"} {"input": "package goblueboxapi\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"testing\"\n)\n\nconst (\n\tcustomerID = \"customer_id\"\n\tapiKey = \"api_key\"\n)\n\nvar (\n\tmux *http.ServeMux\n\tclient *Client\n\tserver *httptest.Server\n)\n\n\n\nfunc teardown() {\n\tserver.Close()\n}\n\nfunc testMethod(t *testing.T, r *http.Request, want string) {\n\tif want != r.Method {\n\t\tt.Errorf(\"Request method = %v, want %v\", r.Method, want)\n\t}\n}\n\nfunc setup() ", "output": "{\n\tmux = http.NewServeMux()\n\tserver = httptest.NewServer(mux)\n\n\tclient = NewClient(customerID, apiKey)\n\tclient.BaseURL, _ = url.Parse(server.URL)\n}"} {"input": "package subscriptions\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/status-im/status-go/rpc\"\n)\n\ntype ethFilter struct {\n\tid string\n\trpcClient *rpc.Client\n}\n\nfunc installEthFilter(rpcClient *rpc.Client, method string, args []interface{}) (*ethFilter, error) {\n\n\tif err := validateEthMethod(method); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result string\n\n\terr := rpcClient.Call(&result, rpcClient.UpstreamChainID, method, args...)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilter := ðFilter{\n\t\tid: result,\n\t\trpcClient: rpcClient,\n\t}\n\n\treturn filter, nil\n\n}\n\nfunc (ef *ethFilter) getID() string {\n\treturn ef.id\n}\n\n\n\nfunc (ef *ethFilter) uninstall() error {\n\treturn ef.rpcClient.Call(nil, ef.rpcClient.UpstreamChainID, \"eth_uninstallFilter\", ef.getID())\n}\n\nfunc validateEthMethod(method string) error {\n\tfor _, allowedMethod := range []string{\n\t\t\"eth_newFilter\",\n\t\t\"eth_newBlockFilter\",\n\t\t\"eth_newPendingTransactionFilter\",\n\t} {\n\t\tif method == allowedMethod {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"unexpected filter method: %s\", method)\n}\n\nfunc (ef *ethFilter) getChanges() ([]interface{}, error) ", "output": "{\n\tvar result []interface{}\n\n\terr := ef.rpcClient.Call(&result, ef.rpcClient.UpstreamChainID, \"eth_getFilterChanges\", ef.getID())\n\n\treturn result, err\n}"} {"input": "package license\n\nimport (\n\t\"context\"\n\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n)\n\n\n\nfunc (s *Service) FindWithContext(ctx context.Context, req *FindRequest) ([]*sacloud.License, error) {\n\tif err := req.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams, err := req.ToRequestParameter()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := sacloud.NewLicenseOp(s.caller)\n\tfound, err := client.Find(ctx, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn found.Licenses, nil\n}\n\nfunc (s *Service) Find(req *FindRequest) ([]*sacloud.License, error) ", "output": "{\n\treturn s.FindWithContext(context.Background(), req)\n}"} {"input": "package ui\n\nfunc About() string {\n\treturn \"go-ui 0.1.1 \"\n}\n\nfunc Version() string {\n\treturn \"go-ui 0.1.1\"\n}\n\nfunc Main(fn func()) int {\n\tfnAppMain = fn\n\treturn theApp.AppMain()\n}\n\nfunc Run() int {\n\treturn theApp.Run()\n}\n\nfunc Exit(code int) {\n\ttheApp.Exit(code)\n}\n\n\n\nfunc App() *app {\n\treturn &theApp\n}\n\nfunc CloseAllWindows() ", "output": "{\n\ttheApp.CloseAllWindows()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"labix.org/v2/mgo\"\n)\n\n\n\n\n\ntype MgoConsistencyMode int\n\n\n\nfunc (mcm *MgoConsistencyMode) String() string {\n\tswitch MgoConsistencyMode(*mcm) {\n\tcase MgoConsistencyMode(mgo.Strong):\n\t\treturn \"STRONG\"\n\tcase MgoConsistencyMode(mgo.Monotonic):\n\t\treturn \"MONOTONIC\"\n\tcase MgoConsistencyMode(mgo.Eventual):\n\t\treturn \"EVENTUAL\"\n\t}\n\treturn \"INVALID\"\n}\n\nfunc (mcm *MgoConsistencyMode) Apply(s *mgo.Session) {\n\tswitch MgoConsistencyMode(*mcm) {\n\tcase MgoConsistencyMode(mgo.Strong):\n\t\ts.SetMode(mgo.Strong, true)\n\tcase MgoConsistencyMode(mgo.Monotonic):\n\t\ts.SetMode(mgo.Monotonic, true)\n\tcase MgoConsistencyMode(mgo.Eventual):\n\t\ts.SetMode(mgo.Eventual, true)\n\t}\n}\n\nfunc (mcm *MgoConsistencyMode) MarshalGoptions(val string) error ", "output": "{\n\tswitch strings.ToUpper(val) {\n\tcase \"STRONG\":\n\t\t*mcm = MgoConsistencyMode(mgo.Strong)\n\tcase \"MONOTONIC\":\n\t\t*mcm = MgoConsistencyMode(mgo.Monotonic)\n\tcase \"EVENTUAL\":\n\t\t*mcm = MgoConsistencyMode(mgo.Eventual)\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown consistency type \\\"%s\\\"\", val)\n\t}\n\treturn nil\n}"} {"input": "package logs\n\nimport (\n\t\"io\"\n\n\t\"github.com/cloudfoundry/dropsonde/log_sender\"\n\t\"github.com/cloudfoundry/sonde-go/events\"\n)\n\ntype LogSender interface {\n\tSendAppLog(appID, message, sourceType, sourceInstance string) error\n\tSendAppErrorLog(appID, message, sourceType, sourceInstance string) error\n\tScanLogStream(appID, sourceType, sourceInstance string, reader io.Reader)\n\tScanErrorLogStream(appID, sourceType, sourceInstance string, reader io.Reader)\n\tLogMessage(msg []byte, msgType events.LogMessage_MessageType) log_sender.LogChainer\n}\n\nvar logSender LogSender\n\n\n\nfunc Initialize(ls LogSender) {\n\tlogSender = ls\n}\n\n\n\n\nfunc SendAppLog(appID, message, sourceType, sourceInstance string) error {\n\tif logSender == nil {\n\t\treturn nil\n\t}\n\treturn logSender.SendAppLog(appID, message, sourceType, sourceInstance)\n}\n\n\n\n\n\n\n\n\nfunc ScanLogStream(appID, sourceType, sourceInstance string, reader io.Reader) {\n\tif logSender == nil {\n\t\treturn\n\t}\n\tlogSender.ScanLogStream(appID, sourceType, sourceInstance, reader)\n}\n\n\n\nfunc ScanErrorLogStream(appID, sourceType, sourceInstance string, reader io.Reader) {\n\tif logSender == nil {\n\t\treturn\n\t}\n\tlogSender.ScanErrorLogStream(appID, sourceType, sourceInstance, reader)\n}\n\n\n\nfunc LogMessage(msg []byte, msgType events.LogMessage_MessageType) log_sender.LogChainer {\n\treturn logSender.LogMessage(msg, msgType)\n}\n\nfunc SendAppErrorLog(appID, message, sourceType, sourceInstance string) error ", "output": "{\n\tif logSender == nil {\n\t\treturn nil\n\t}\n\treturn logSender.SendAppErrorLog(appID, message, sourceType, sourceInstance)\n}"} {"input": "package main\nimport (\n\t\"net/http\"\n\tmv \"github.com/delicb/mezvaro\"\n\t\"log\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc LoggingMiddleware(c *mv.Context) {\n\tlog.Println(\"Simluate real logging here\")\n\tc.Next()\n}\n\n\n\nfunc PubliclyAvailable(c *mv.Context) {\n\tc.Response.Write([]byte(\"This page is available for all users.\"))\n}\n\nfunc PrivatelyAvailable(c *mv.Context) {\n\tc.Response.Write([]byte(\"This page is only for authorized users.\"))\n}\n\nfunc main() {\n\tm := mv.New(mv.HandlerFunc(LoggingMiddleware)) \n\tauthOnly := m.Fork(mv.HandlerFunc(AuthMiddleware))\n\thttp.Handle(\"/public\", m.HF(PubliclyAvailable))\n\thttp.Handle(\"/auth\", authOnly.HF(PrivatelyAvailable))\n\thttp.ListenAndServe(\":8000\", nil)\n}\n\nfunc AuthMiddleware(c *mv.Context) ", "output": "{\n\tlog.Println(\"Simulate user authentication.\")\n\trand.Seed(time.Now().Unix())\n\tif rand.Int() % 2 == 0 {\n\t\tc.Response.Write([]byte(\"User authenticated.\\n\"))\n\t\tc.Next()\n\t} else {\n\t\tc.Response.WriteHeader(http.StatusUnauthorized)\n\t\tc.Response.Write([]byte(\"Use not authenticated.\\n\"))\n\t\tc.Abort()\n\t}\n}"} {"input": "package syswrap\n\nimport (\n\t\"os\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\nvar fileCount uint64\n\n\n\nvar maxFileCount uint64 = 500000\nvar fileMu sync.RWMutex\n\nfunc SetMaxFileCount(max uint64) {\n\tfileMu.Lock()\n\tmaxFileCount = max\n\tfileMu.Unlock()\n}\n\n\n\n\n\n\n\n\n\nfunc CloseFile(f *os.File) error {\n\tatomic.AddUint64(&fileCount, ^uint64(0)) \n\treturn f.Close()\n}\n\nfunc OpenFile(name string, flag int, perm os.FileMode) (file *os.File, mustClose bool, err error) ", "output": "{\n\tfile, err = os.OpenFile(name, flag, perm)\n\tfileMu.RLock()\n\tdefer fileMu.RUnlock()\n\tif newCount := atomic.AddUint64(&fileCount, 1); newCount > maxFileCount {\n\t\tmustClose = true\n\t}\n\treturn file, mustClose, err\n}"} {"input": "package fake\n\nimport (\n\tclientset \"github.com/openshift/origin/pkg/image/generated/clientset\"\n\timagev1 \"github.com/openshift/origin/pkg/image/generated/clientset/typed/image/v1\"\n\tfakeimagev1 \"github.com/openshift/origin/pkg/image/generated/clientset/typed/image/v1/fake\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/watch\"\n\t\"k8s.io/client-go/discovery\"\n\tfakediscovery \"k8s.io/client-go/discovery/fake\"\n\t\"k8s.io/client-go/testing\"\n)\n\n\n\n\n\n\n\n\n\n\ntype Clientset struct {\n\ttesting.Fake\n}\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\treturn &fakediscovery.FakeDiscovery{Fake: &c.Fake}\n}\n\nvar _ clientset.Interface = &Clientset{}\n\n\nfunc (c *Clientset) ImageV1() imagev1.ImageV1Interface {\n\treturn &fakeimagev1.FakeImageV1{Fake: &c.Fake}\n}\n\n\nfunc (c *Clientset) Image() imagev1.ImageV1Interface {\n\treturn &fakeimagev1.FakeImageV1{Fake: &c.Fake}\n}\n\nfunc NewSimpleClientset(objects ...runtime.Object) *Clientset ", "output": "{\n\to := testing.NewObjectTracker(registry, scheme, codecs.UniversalDecoder())\n\tfor _, obj := range objects {\n\t\tif err := o.Add(obj); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tfakePtr := testing.Fake{}\n\tfakePtr.AddReactor(\"*\", \"*\", testing.ObjectReaction(o, registry.RESTMapper()))\n\n\tfakePtr.AddWatchReactor(\"*\", testing.DefaultWatchReactor(watch.NewFake(), nil))\n\n\treturn &Clientset{fakePtr}\n}"} {"input": "package bot\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"log\"\n)\n\n\ntype Config struct {\n\tAdmin string `json:\"admin\"`\n\tNotifiers map[string][]string `json:\"notifiers\"`\n\tDebug bool `json:\"debug\"`\n}\n\n\n\n\nfunc (cfg *Config) fromJSON(filename string) error {\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = json.Unmarshal(file, &cfg); err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Loaded config.\")\n\treturn nil\n}\n\nfunc (cfg *Config) toJSON(filename string) error {\n\tjsonBytes, err := json.MarshalIndent(cfg, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = ioutil.WriteFile(filename, jsonBytes, 0600); err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Saved config.\")\n\treturn nil\n}\n\nfunc NewConfig() *Config ", "output": "{\n\tcfg := &Config{\n\t\tNotifiers: make(map[string][]string),\n\t}\n\treturn cfg\n}"} {"input": "package flog\n\nimport \"github.com/Sirupsen/logrus\"\n\ntype Parameter interface {\n\tConvert() map[string]interface{}\n}\n\ntype Fields struct {\n\tEvent string\n\tError error\n}\n\n\n\ntype Details map[string]interface{}\n\nfunc (d Details) Convert() map[string]interface{} {\n\treturn d\n}\n\ntype DebugFields map[string]interface{}\n\nfunc (d DebugFields) Convert() map[string]interface{} {\n\treturn map[string]interface{}{}\n}\n\nfunc transform(params []Parameter) logrus.Fields {\n\tlogrusFields := logrus.Fields{}\n\n\tfor _, p := range params {\n\t\tfieldMap := p.Convert()\n\n\t\tfor k, v := range fieldMap {\n\t\t\tlogrusFields[k] = v\n\t\t}\n\t}\n\n\treturn logrusFields\n}\n\nfunc Debug(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Debug(msg)\n}\n\nfunc Info(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Info(msg)\n}\n\nfunc Warn(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Warning(msg)\n}\n\nfunc Error(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Error(msg)\n}\n\nfunc Fatal(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Fatal(msg)\n}\n\nfunc Panic(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Panic(msg)\n}\n\nfunc (f Fields) Convert() map[string]interface{} ", "output": "{\n\tfields := map[string]interface{}{}\n\n\tif f.Event != \"\" {\n\t\tfields[\"event\"] = f.Event\n\t}\n\n\tif f.Error != nil {\n\t\tfields[\"error\"] = f.Error\n\t}\n\n\treturn fields\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n\n\tctypes \"github.com/tendermint/tendermint/rpc/core/types\"\n\t\"github.com/tendermint/tendermint/types\"\n\t. \"github.com/tendermint/tmlibs/common\"\n)\n\n\n\n\n\n\n\n\nfunc Block(height int) (*ctypes.ResultBlock, error) {\n\tif height == 0 {\n\t\treturn nil, fmt.Errorf(\"Height must be greater than 0\")\n\t}\n\tif height > blockStore.Height() {\n\t\treturn nil, fmt.Errorf(\"Height must be less than the current blockchain height\")\n\t}\n\n\tblockMeta := blockStore.LoadBlockMeta(height)\n\tblock := blockStore.LoadBlock(height)\n\treturn &ctypes.ResultBlock{blockMeta, block}, nil\n}\n\n\n\nfunc Commit(height int) (*ctypes.ResultCommit, error) {\n\tif height == 0 {\n\t\treturn nil, fmt.Errorf(\"Height must be greater than 0\")\n\t}\n\tstoreHeight := blockStore.Height()\n\tif height > storeHeight {\n\t\treturn nil, fmt.Errorf(\"Height must be less than or equal to the current blockchain height\")\n\t}\n\n\theader := blockStore.LoadBlockMeta(height).Header\n\n\tif height == storeHeight {\n\t\tcommit := blockStore.LoadSeenCommit(height)\n\t\treturn &ctypes.ResultCommit{header, commit, false}, nil\n\t}\n\n\tcommit := blockStore.LoadBlockCommit(height)\n\treturn &ctypes.ResultCommit{header, commit, true}, nil\n}\n\nfunc BlockchainInfo(minHeight, maxHeight int) (*ctypes.ResultBlockchainInfo, error) ", "output": "{\n\tif maxHeight == 0 {\n\t\tmaxHeight = blockStore.Height()\n\t} else {\n\t\tmaxHeight = MinInt(blockStore.Height(), maxHeight)\n\t}\n\tif minHeight == 0 {\n\t\tminHeight = MaxInt(1, maxHeight-20)\n\t} else {\n\t\tminHeight = MaxInt(minHeight, maxHeight-20)\n\t}\n\n\tlogger.Debug(\"BlockchainInfoHandler\", \"maxHeight\", maxHeight, \"minHeight\", minHeight)\n\n\tblockMetas := []*types.BlockMeta{}\n\tfor height := maxHeight; height >= minHeight; height-- {\n\t\tblockMeta := blockStore.LoadBlockMeta(height)\n\t\tblockMetas = append(blockMetas, blockMeta)\n\t}\n\n\treturn &ctypes.ResultBlockchainInfo{blockStore.Height(), blockMetas}, nil\n}"} {"input": "package taskbytime\n\n\ntype taskData struct {\n\tstartNum\tint\n\tmaxNum\t\tint\n\tinterval\tint\n\tisRepeat\tbool\n}\n\n\nvar taskDatas = make(map[int]taskData)\n\n\n\n\n\nfunc SetData(taskId int, t taskData) ", "output": "{\n\ttaskDatas[taskId] = t\n}"} {"input": "package utils\n\nimport \"fmt\"\n\n\n\n\n\n\n\n\ntype SafeGoroutineTester struct{}\n\n\nfunc (s *SafeGoroutineTester) Errorf(format string, args ...interface{}) {\n\tfmt.Printf(format, args...)\n\tpanic(\"MOCK TEST ERROR\")\n}\n\n\n\n\nfunc (s *SafeGoroutineTester) Fatalf(format string, args ...interface{}) ", "output": "{\n\tfmt.Printf(format+\"\\n\", args...)\n\tpanic(\"MOCK TEST FATAL FAILURE\")\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/TykTechnologies/tyk/apidef\"\n)\n\n\ntype TransformMethod struct {\n\t*BaseMiddleware\n}\n\n\n\nfunc (t *TransformMethod) IsEnabledForSpec() bool {\n\tfor _, version := range t.Spec.VersionData.Versions {\n\t\tif len(version.ExtendedPaths.MethodTransforms) > 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (t *TransformMethod) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {\n\t_, versionPaths, _, _ := t.Spec.Version(r)\n\tfound, meta := t.Spec.CheckSpecMatchesStatus(r, versionPaths, MethodTransformed)\n\tif !found {\n\t\treturn nil, 200\n\t}\n\tmmeta := meta.(*apidef.MethodTransformMeta)\n\tswitch strings.ToUpper(mmeta.ToMethod) {\n\tcase \"GET\":\n\t\tr.Method = \"GET\"\n\tcase \"POST\":\n\t\tr.Method = \"POST\"\n\tcase \"PUT\":\n\t\tr.Method = \"PUT\"\n\tcase \"DELETE\":\n\t\tr.Method = \"DELETE\"\n\tcase \"OPTIONS\":\n\t\tr.Method = \"OPTIONS\"\n\tcase \"PATCH\":\n\t\tr.Method = \"PATCH\"\n\tdefault:\n\t\treturn errors.New(\"Method not allowed\"), 405\n\t}\n\treturn nil, 200\n}\n\nfunc (t *TransformMethod) Name() string ", "output": "{\n\treturn \"TransformMethod\"\n}"} {"input": "package pdf417\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\n\t\"github.com/boombuler/barcode\"\n\t\"github.com/boombuler/barcode/utils\"\n)\n\ntype pdfBarcode struct {\n\tdata string\n\twidth int\n\tcode *utils.BitList\n}\n\nfunc (c *pdfBarcode) Metadata() barcode.Metadata {\n\treturn barcode.Metadata{barcode.TypePDF, 2}\n}\n\nfunc (c *pdfBarcode) Content() string {\n\treturn c.data\n}\n\n\n\nfunc (c *pdfBarcode) Bounds() image.Rectangle {\n\theight := c.code.Len() / c.width\n\n\treturn image.Rect(0, 0, c.width, height*moduleHeight)\n}\n\nfunc (c *pdfBarcode) At(x, y int) color.Color {\n\tif c.code.GetBit((y/moduleHeight)*c.width + x) {\n\t\treturn color.Black\n\t}\n\treturn color.White\n}\n\nfunc (c *pdfBarcode) ColorModel() color.Model ", "output": "{\n\treturn color.Gray16Model\n}"} {"input": "package context\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\n\tjujuos \"github.com/juju/utils/os\"\n)\n\n\n\nfunc OSDependentEnvVars(paths Paths) []string {\n\tswitch jujuos.HostOS() {\n\tcase jujuos.Windows:\n\t\treturn windowsEnv(paths)\n\tcase jujuos.Ubuntu:\n\t\treturn ubuntuEnv(paths)\n\tcase jujuos.CentOS:\n\t\treturn centosEnv(paths)\n\t}\n\treturn nil\n}\n\nfunc appendPath(paths Paths) []string {\n\treturn []string{\n\t\t\"PATH=\" + paths.GetToolsDir() + \":\" + os.Getenv(\"PATH\"),\n\t}\n}\n\nfunc ubuntuEnv(paths Paths) []string {\n\tpath := appendPath(paths)\n\tenv := []string{\n\t\t\"APT_LISTCHANGES_FRONTEND=none\",\n\t\t\"DEBIAN_FRONTEND=noninteractive\",\n\t}\n\tenv = append(env, path...)\n\treturn env\n}\n\nfunc centosEnv(paths Paths) []string {\n\treturn appendPath(paths)\n}\n\n\n\n\n\n\n\nfunc windowsEnv(paths Paths) []string ", "output": "{\n\tcharmDir := paths.GetCharmDir()\n\tcharmModules := filepath.Join(charmDir, \"lib\", \"Modules\")\n\treturn []string{\n\t\t\"Path=\" + paths.GetToolsDir() + \";\" + os.Getenv(\"Path\"),\n\t\t\"PSModulePath=\" + os.Getenv(\"PSModulePath\") + \";\" + charmModules,\n\t}\n}"} {"input": "package memory\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/protobuf/types/known/emptypb\"\n\n\t\"go.chromium.org/luci/gce/api/projects/v1\"\n)\n\n\nvar _ projects.ProjectsServer = &Projects{}\n\n\ntype Projects struct {\n\tcfg sync.Map\n}\n\n\n\n\n\nfunc (srv *Projects) Ensure(c context.Context, req *projects.EnsureRequest) (*projects.Config, error) {\n\tsrv.cfg.Store(req.GetId(), req.GetProject())\n\treturn req.GetProject(), nil\n}\n\n\nfunc (srv *Projects) Get(c context.Context, req *projects.GetRequest) (*projects.Config, error) {\n\tcfg, ok := srv.cfg.Load(req.GetId())\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.NotFound, \"no project found with ID %q\", req.GetId())\n\t}\n\treturn cfg.(*projects.Config), nil\n}\n\n\nfunc (srv *Projects) List(c context.Context, req *projects.ListRequest) (*projects.ListResponse, error) {\n\trsp := &projects.ListResponse{}\n\tif req.GetPageToken() != \"\" {\n\t\treturn rsp, nil\n\t}\n\tsrv.cfg.Range(func(_, val interface{}) bool {\n\t\trsp.Projects = append(rsp.Projects, val.(*projects.Config))\n\t\treturn true\n\t})\n\treturn rsp, nil\n}\n\nfunc (srv *Projects) Delete(c context.Context, req *projects.DeleteRequest) (*emptypb.Empty, error) ", "output": "{\n\tsrv.cfg.Delete(req.GetId())\n\treturn &emptypb.Empty{}, nil\n}"} {"input": "package ioctl\n\nimport \"golang.org/x/sys/unix\"\n\nconst (\n\ttypeBits = 8\n\tnumberBits = 8\n\tsizeBits = 14\n\tdirectionBits = 2\n\n\ttypeMask = (1 << typeBits) - 1\n\tnumberMask = (1 << numberBits) - 1\n\tsizeMask = (1 << sizeBits) - 1\n\tdirectionMask = (1 << directionBits) - 1\n\n\tdirectionNone = 0\n\tdirectionWrite = 1\n\tdirectionRead = 2\n\n\tnumberShift = 0\n\ttypeShift = numberShift + numberBits\n\tsizeShift = typeShift + typeBits\n\tdirectionShift = sizeShift + sizeBits\n)\n\nfunc ioc(dir, t, nr, size uintptr) uintptr {\n\treturn (dir << directionShift) | (t << typeShift) | (nr << numberShift) | (size << sizeShift)\n}\n\n\n\n\n\nfunc IoR(t, nr, size uintptr) uintptr {\n\treturn ioc(directionRead, t, nr, size)\n}\n\n\nfunc IoW(t, nr, size uintptr) uintptr {\n\treturn ioc(directionWrite, t, nr, size)\n}\n\n\nfunc IoRW(t, nr, size uintptr) uintptr {\n\treturn ioc(directionRead|directionWrite, t, nr, size)\n}\n\n\nfunc Ioctl(fd, op, arg uintptr) error {\n\t_, _, ep := unix.Syscall(unix.SYS_IOCTL, fd, op, arg)\n\tif ep != 0 {\n\t\treturn ep\n\t}\n\treturn nil\n}\n\nfunc Io(t, nr uintptr) uintptr ", "output": "{\n\treturn ioc(directionNone, t, nr, 0)\n}"} {"input": "package cache\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc TestCacheRefreshUpTypeAsync(t *testing.T) {\n\tconvey.Convey(\"RefreshUpTypeAsync\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\ttm = time.Now()\n\t\t)\n\t\tctx.Convey(\"When everything goes positive\", func(ctx convey.C) {\n\t\t\tRefreshUpTypeAsync(tm)\n\t\t\tctx.Convey(\"No return values\", func(ctx convey.C) {\n\t\t\t})\n\t\t})\n\t})\n}\n\n\n\nfunc TestCacheGetTidName(t *testing.T) {\n\tconvey.Convey(\"GetTidName\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\ttids = int64(0)\n\t\t)\n\t\tctx.Convey(\"When everything goes positive\", func(ctx convey.C) {\n\t\t\ttpNames := GetTidName(tids)\n\t\t\tctx.Convey(\"Then tpNames should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(tpNames, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestCacheRefreshUpType(t *testing.T) ", "output": "{\n\tconvey.Convey(\"RefreshUpType\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\ttm = time.Now()\n\t\t)\n\t\tctx.Convey(\"When everything goes positive\", func(ctx convey.C) {\n\t\t\tRefreshUpType(tm)\n\t\t\tctx.Convey(\"No return values\", func(ctx convey.C) {\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package remotecache\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/bradfitz/gomemcache/memcache\"\n\t\"github.com/grafana/grafana/pkg/setting\"\n)\n\nconst memcachedCacheType = \"memcached\"\n\ntype memcachedStorage struct {\n\tc *memcache.Client\n}\n\nfunc newMemcachedStorage(opts *setting.RemoteCacheOptions) *memcachedStorage {\n\treturn &memcachedStorage{\n\t\tc: memcache.New(opts.ConnStr),\n\t}\n}\n\nfunc newItem(sid string, data []byte, expire int32) *memcache.Item {\n\treturn &memcache.Item{\n\t\tKey: sid,\n\t\tValue: data,\n\t\tExpiration: expire,\n\t}\n}\n\n\n\n\n\nfunc (s *memcachedStorage) Get(ctx context.Context, key string) (interface{}, error) {\n\tmemcachedItem, err := s.c.Get(key)\n\tif err != nil && err.Error() == \"memcache: cache miss\" {\n\t\treturn nil, ErrCacheItemNotFound\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titem := &cachedItem{}\n\n\terr = decodeGob(memcachedItem.Value, item)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn item.Val, nil\n}\n\n\nfunc (s *memcachedStorage) Delete(ctx context.Context, key string) error {\n\treturn s.c.Delete(key)\n}\n\nfunc (s *memcachedStorage) Set(ctx context.Context, key string, val interface{}, expires time.Duration) error ", "output": "{\n\titem := &cachedItem{Val: val}\n\tbytes, err := encodeGob(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar expiresInSeconds int64\n\tif expires != 0 {\n\t\texpiresInSeconds = int64(expires) / int64(time.Second)\n\t}\n\n\tmemcachedItem := newItem(key, bytes, int32(expiresInSeconds))\n\treturn s.c.Set(memcachedItem)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n\t\"runtime\"\n\n\t\"github.com/fatih/color\"\n\t\"github.com/ssddanbrown/haste/engine\"\n\t\"github.com/ssddanbrown/haste/options\"\n\t\"github.com/ssddanbrown/haste/server\"\n)\n\nfunc main() {\n\n\topts := options.NewOptions()\n\terr := opts.ParseCommandFlags()\n\topts.LoadFileResolver()\n\tcheck(err)\n\n\tmanager := engine.NewManager(opts)\n\n\tmanager.BuildAll()\n\n\tif opts.Watch {\n\t\tstartWatcher(manager, opts)\n\t}\n\n}\n\nfunc startWatcher(m *engine.Manager, opts *options.Options) {\n\tser := server.NewServer(m, opts)\n\tser.AddWatchedFolder(opts.RootPath)\n\n\tcolor.Green(fmt.Sprintf(\"Server started at http://localhost:%d\", opts.ServerPort))\n\n\terr := ser.Listen()\n\tcheck(err)\n}\n\nfunc openWebPage(url string) error {\n\tvar err error\n\n\tswitch runtime.GOOS {\n\tcase \"linux\":\n\t\tfmt.Println(url)\n\t\terr = exec.Command(\"xdg-open\", url).Run()\n\tcase \"windows\", \"darwin\":\n\t\terr = exec.Command(\"rundll32\", \"url.dll,FileProtocolHandler\", url).Run()\n\tdefault:\n\t\terr = fmt.Errorf(\"unsupported platform\")\n\t}\n\treturn err\n}\n\n\n\nfunc check(err error) ", "output": "{\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package kata\n\nimport \"strings\"\n\n\n\nfunc DNAtoRNA(dna string) string ", "output": "{\n return strings.Replace(dna, \"T\", \"U\", -1)\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\tfor i := 0; i < 3; i++ {\n\t\tfp(&[3]int{i, i * i, i * i * i})\n\t}\n}\n\nfunc fp(a *[3]int) ", "output": "{ fmt.Println(a) }"} {"input": "package glacier\n\nimport (\n\t\"encoding/hex\"\n\t\"reflect\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/awsutil\"\n)\n\nvar (\n\tdefaultAccountID = \"-\"\n)\n\nfunc init() {\n\tinitRequest = func(r *aws.Request) {\n\t\tr.Handlers.Validate.PushFront(addAccountID)\n\t\tr.Handlers.Validate.PushFront(copyParams) \n\t\tr.Handlers.Build.PushBack(addChecksum)\n\t\tr.Handlers.Build.PushBack(addAPIVersion)\n\t}\n}\n\nfunc copyParams(r *aws.Request) {\n\tr.Params = awsutil.CopyOf(r.Params)\n}\n\n\n\nfunc addChecksum(r *aws.Request) {\n\tif r.Body == nil {\n\t\treturn\n\t}\n\n\th := ComputeHashes(r.Body)\n\n\tif r.HTTPRequest.Header.Get(\"X-Amz-Content-Sha256\") == \"\" {\n\t\thstr := hex.EncodeToString(h.LinearHash)\n\t\tr.HTTPRequest.Header.Set(\"X-Amz-Content-Sha256\", hstr)\n\t}\n\tif r.HTTPRequest.Header.Get(\"X-Amz-Sha256-Tree-Hash\") == \"\" {\n\t\thstr := hex.EncodeToString(h.TreeHash)\n\t\tr.HTTPRequest.Header.Set(\"X-Amz-Sha256-Tree-Hash\", hstr)\n\t}\n}\n\nfunc addAPIVersion(r *aws.Request) {\n\tr.HTTPRequest.Header.Set(\"X-Amz-Glacier-Version\", r.Service.APIVersion)\n}\n\nfunc addAccountID(r *aws.Request) ", "output": "{\n\tif !r.ParamsFilled() {\n\t\treturn\n\t}\n\n\tv := reflect.Indirect(reflect.ValueOf(r.Params))\n\tif f := v.FieldByName(\"AccountID\"); f.IsNil() {\n\t\tf.Set(reflect.ValueOf(&defaultAccountID))\n\t}\n}"} {"input": "package models\n\nimport \"fmt\"\n\ntype TaskManager struct {\n\ttasks []*Task\n\tlastID int64\n}\n\n\n\nfunc (m *TaskManager) Tasks() []*Task {\n\treturn m.tasks\n}\n\nfunc (m *TaskManager) Add(task *Task) error {\n\tif task.Id == 0 {\n\t\tm.lastID++\n\t\ttask.Id = m.lastID\n\t\tm.tasks = append(m.tasks, task.clone())\n\t\treturn nil\n\t}\n\n\t_, found := m.Find(task.Id)\n\tif found {\n\t\tm.tasks[task.Id-1] = task\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"unknown task\")\n}\n\nfunc (m *TaskManager) Find(id int64) (*Task, bool) {\n\tfor _, t := range m.tasks {\n\t\tif t.Id == id {\n\t\t\treturn t, true\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc NewTaskManager() *TaskManager ", "output": "{\n\treturn &TaskManager{}\n}"} {"input": "package utils\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\tirc \"gopkg.in/irc.v3\"\n)\n\n\n\ntype TestClientServer struct {\n\tclient *bytes.Buffer\n\tserver *bytes.Buffer\n}\n\n\nfunc NewTestClientServer() *TestClientServer {\n\treturn &TestClientServer{\n\t\tclient: &bytes.Buffer{},\n\t\tserver: &bytes.Buffer{},\n\t}\n}\n\n\nfunc (cs *TestClientServer) Read(p []byte) (int, error) {\n\treturn cs.server.Read(p)\n}\n\n\nfunc (cs *TestClientServer) Write(p []byte) (int, error) {\n\treturn cs.client.Write(p)\n}\n\n\n\nfunc (cs *TestClientServer) SendServerLines(lines []string) {\n\tw := irc.NewWriter(cs.server)\n\n\tfor _, line := range lines {\n\t\tw.WriteMessage(irc.MustParseMessage(line))\n\t}\n}\n\n\n\n\n\n\n\nfunc (cs *TestClientServer) Reset() {\n\tcs.client.Reset()\n\tcs.server.Reset()\n}\n\nfunc (cs *TestClientServer) CheckLines(t *testing.T, expected []string) bool ", "output": "{\n\tok := true\n\n\tlines := strings.Split(cs.client.String(), \"\\r\\n\")\n\n\tvar line, clientLine string\n\tfor len(expected) > 0 && len(lines) > 0 {\n\t\tline, expected = expected[0], expected[1:]\n\t\tclientLine, lines = lines[0], lines[1:]\n\n\t\tok = ok && assert.Equal(t, line, clientLine)\n\t}\n\n\tok = ok && assert.Equal(t, 0, len(expected), \"Not enough lines: %s\", strings.Join(expected, \", \"))\n\tok = ok && assert.Equal(t, 0, len(lines), \"Extra non-empty lines: %s\", strings.Join(lines, \", \"))\n\n\treturn ok\n}"} {"input": "package logs\n\nconst (\n\tErrorLevel = iota\n\tWarnLevel\n\tInfoLevel\n\tDebugLevel\n)\n\ntype Level uint32\n\nfunc (l Level) EQ(lv Level) bool {\n\tif l == lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc (l Level) LT(lv Level) bool {\n\tif l < lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) GTE(lv Level) bool {\n\tif l >= lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) GT(lv Level) bool {\n\tif l > lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) Color() int {\n\tvar levelColor int\n\tswitch l {\n\tcase DebugLevel:\n\t\tlevelColor = 32\n\tcase InfoLevel:\n\t\tlevelColor = 36\n\tcase WarnLevel:\n\t\tlevelColor = 33\n\tcase ErrorLevel:\n\t\tlevelColor = 31\n\tdefault:\n\t\tlevelColor = 0\n\t}\n\treturn levelColor\n}\n\nfunc (l Level) String() string {\n\tswitch l {\n\tcase DebugLevel:\n\t\treturn \"DEBU\"\n\tcase InfoLevel:\n\t\treturn \"INFO\"\n\tcase WarnLevel:\n\t\treturn \"WARN\"\n\tcase ErrorLevel:\n\t\treturn \"ERRO\"\n\t}\n\treturn \" \"\n}\n\nfunc (l Level) LTE(lv Level) bool ", "output": "{\n\tif l <= lv {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package trace\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\nfunc TestNew(t *testing.T) {\n\tvar buf bytes.Buffer\n\ttracer := New(&buf)\n\tif tracer == nil {\n\t\tt.Error(\"Return from New should not be nil\")\n\t} else {\n\t\ttracer.Trace(\"Hello trace package.\")\n\t\tif buf.String() != \"Hello trace package.\\n\" {\n\t\t\tt.Errorf(\"Trace should not write '%s'.\", buf.String())\n\t\t}\n\t}\n}\n\n\n\nfunc TestOff(t *testing.T) ", "output": "{\n\ttracer := Off()\n\ttracer.Trace(\"do something\")\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\ntype SCmd struct {\n\tm_chanStringCmd chan string\n\tm_chanWaitCmdComplete chan bool\n\tm_bHadStop bool\n\tm_funcDoCmd func(string)\n\tm_mutex sync.Mutex\n}\n\nfunc NewSCmd(funcDoCmd func(string)) *SCmd {\n\tif funcDoCmd == nil {\n\t\treturn nil\n\t}\n\n\tvar pSCmd = &SCmd{\n\t\tm_bHadStop: false,\n\t\tm_chanStringCmd: make(chan string, 0),\n\t\tm_chanWaitCmdComplete: make(chan bool, 0),\n\t\tm_funcDoCmd: funcDoCmd,\n\t}\n\tgo pSCmd.mainWorker()\n\treturn pSCmd\n}\n\nfunc (this *SCmd) Cmd(strCmd string) {\n\tfmt.Println(\"Cmd\", strCmd)\n\n\tif this.m_bHadStop {\n\t\tfmt.Println(\"had stop\")\n\t\treturn\n\t}\n\n\tthis.m_chanStringCmd <- strCmd\n}\n\nfunc (this *SCmd) Quit() {\n\tclose(this.m_chanStringCmd)\n}\n\n\n\nfunc (this *SCmd) mainWorker() ", "output": "{\n\tfor strCmd := range this.m_chanStringCmd {\n\t\tthis.m_funcDoCmd(strCmd)\n\t}\n}"} {"input": "package base\n\nimport (\n\t\"github.com/johnwilson/bytengine\"\n)\n\n\nfunc ServerListDb(cmd bytengine.Command, user *bytengine.User, eng *bytengine.Engine) (interface{}, error) {\n\tfilter := \".\"\n\tval, ok := cmd.Options[\"regex\"]\n\tif ok {\n\t\tfilter = val.(string)\n\t}\n\treturn eng.FileSystem.ListDatabase(filter)\n}\n\n\nfunc ServerNewDb(cmd bytengine.Command, user *bytengine.User, eng *bytengine.Engine) (interface{}, error) {\n\tdb := cmd.Args[\"database\"].(string)\n\tif err := eng.FileSystem.CreateDatabase(db); err != nil {\n\t\treturn nil, err\n\t}\n\treturn true, nil\n}\n\n\nfunc ServerInit(cmd bytengine.Command, user *bytengine.User, eng *bytengine.Engine) (interface{}, error) {\n\treturn eng.FileSystem.ClearAll()\n}\n\n\nfunc ServerDropDb(cmd bytengine.Command, user *bytengine.User, eng *bytengine.Engine) (interface{}, error) {\n\tdb := cmd.Args[\"database\"].(string)\n\tif err := eng.FileSystem.DropDatabase(db); err != nil {\n\t\treturn nil, err\n\t}\n\treturn true, nil\n}\n\n\n\nfunc init() ", "output": "{\n\tbytengine.RegisterCommandHandler(\"server.listdb\", ServerListDb)\n\tbytengine.RegisterCommandHandler(\"server.newdb\", ServerNewDb)\n\tbytengine.RegisterCommandHandler(\"server.init\", ServerInit)\n\tbytengine.RegisterCommandHandler(\"server.dropdb\", ServerDropDb)\n}"} {"input": "package toJson\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc WriteToJson(w http.ResponseWriter, obj interface{}) error {\n\treturn WriteToJsonWithCode(w, obj, http.StatusOK)\n}\n\n\n\nfunc WriteToJsonNotWrapped(w http.ResponseWriter, obj interface{}) error {\n\treturn WriteToJsonNotWrappedWithCode(w, obj, http.StatusOK)\n}\n\nfunc WriteToJsonNotWrappedWithCode(w http.ResponseWriter, obj interface{}, code int) error {\n\to, err := ToJson(obj)\n\tif err != nil {\n\t\twriteError(err)\n\t\treturn err\n\t}\n\n\treturn WriteJson(w, &o, code)\n}\n\nfunc WriteJson(w http.ResponseWriter, obj interface{}, code int) error {\n\tmarshalled, err := json.MarshalIndent(obj, \"\", \" \")\n\tif err != nil {\n\t\twriteError(err)\n\t\treturn err\n\t}\n\n\tdata := []byte(fmt.Sprintf(\"%s\\n\", marshalled))\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.Header().Set(\"Content-Length\", fmt.Sprint(len(data)))\n\tw.WriteHeader(code)\n\tw.Write(data)\n\n\treturn nil\n}\n\nfunc WriteToJsonWithCode(w http.ResponseWriter, obj interface{}, code int) error ", "output": "{\n\to, err := ToJson(obj)\n\tif err != nil {\n\t\twriteError(err)\n\t\treturn err\n\t}\n\n\twrapped := map[string]interface{}{\"result\": o}\n\n\treturn WriteJson(w, &wrapped, code)\n}"} {"input": "package connmgr\n\nimport \"github.com/abcsuite/abclog\"\n\n\n\n\nvar log abclog.Logger\n\n\n\n\n\n\nfunc DisableLog() {\n\tlog = abclog.Disabled\n}\n\n\n\n\nfunc UseLogger(logger abclog.Logger) {\n\tlog = logger\n}\n\nfunc init() ", "output": "{\n\tDisableLog()\n}"} {"input": "package databasemanagement\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ResetDatabaseParametersRequest struct {\n\n\tManagedDatabaseId *string `mandatory:\"true\" contributesTo:\"path\" name:\"managedDatabaseId\"`\n\n\tResetDatabaseParametersDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ResetDatabaseParametersRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request ResetDatabaseParametersRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ResetDatabaseParametersRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ResetDatabaseParametersResponse struct {\n\n\tRawResponse *http.Response\n\n\tUpdateDatabaseParametersResult `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ResetDatabaseParametersResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ResetDatabaseParametersResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ResetDatabaseParametersRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package live_data\n\nimport (\n\t\"context\"\n\n\t\"go-common/app/interface/live/app-interface/conf\"\n)\n\n\ntype Dao struct {\n\tc *conf.Config\n}\n\n\nfunc New(c *conf.Config) (dao *Dao) {\n\tdao = &Dao{\n\t\tc: c,\n\t}\n\treturn\n}\n\n\n\n\n\nfunc (d *Dao) Ping(c context.Context) error {\n\treturn nil\n}\n\nfunc (d *Dao) Close() ", "output": "{\n\treturn\n}"} {"input": "package module\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/config\"\n\t\"github.com/hashicorp/terraform/svchost/disco\"\n)\n\n\n\nconst fixtureDir = \"./test-fixtures\"\n\nfunc tempDir(t *testing.T) string {\n\tt.Helper()\n\tdir, err := ioutil.TempDir(\"\", \"tf\")\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\tif err := os.RemoveAll(dir); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\treturn dir\n}\n\nfunc testConfig(t *testing.T, n string) *config.Config {\n\tt.Helper()\n\tc, err := config.LoadDir(filepath.Join(fixtureDir, n))\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\treturn c\n}\n\nfunc testStorage(t *testing.T, d *disco.Disco) *Storage {\n\tt.Helper()\n\treturn NewStorage(tempDir(t), d)\n}\n\nfunc init() ", "output": "{\n\tif os.Getenv(\"TF_LOG\") == \"\" {\n\t\tlog.SetOutput(ioutil.Discard)\n\t}\n}"} {"input": "package amber\n\nimport (\n\t\"errors\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/kotfalya/amber/utils\"\n)\n\ntype DB struct {\n\tconfig *Config\n\tname string\n\trootPage *Page\n\treq chan *Req\n\tstop chan struct{}\n}\n\nfunc NewDB(name string, config *Config) *DB {\n\tdb := &DB{\n\t\tconfig: config,\n\t\tname: name,\n\t\trootPage: createRootPage(),\n\t\treq: make(chan *Req, 10),\n\t\tstop: make(chan struct{}),\n\t}\n\tgo db.start()\n\n\treturn db\n}\n\n\n\nfunc (db *DB) load(keyName string, level int) (Key, error) {\n\tkey, err := db.rootPage.load(keyName)\n\tif err != nil {\n\t\treturn nil, errors.New(ErrUndefinedKey)\n\t}\n\treturn key, nil\n}\n\nfunc (db *DB) add(keyName string, key Key, level int) (err error) {\n\terr = db.rootPage.add(keyName, key)\n\n\treturn\n}\n\nfunc DBHandle(db *DB, req *Req) {\n\n}\n\nfunc (db *DB) start() ", "output": "{\n\tsem := utils.NewSemaphore(10)\n\tfor {\n\t\tselect {\n\t\tcase req := <-db.req:\n\t\t\treq.master = db.name\n\t\t\tsem.Acquire()\n\t\t\tgo func(req *Req) {\n\t\t\t\tdefer sem.Release()\n\t\t\t\tswitch req.handler {\n\t\t\t\tcase RequestDBHandler:\n\t\t\t\t\tDBHandle(db, req)\n\t\t\t\tcase RequestKeyHandler:\n\t\t\t\t\tKeyHandler(db, req)\n\t\t\t\tcase RequestNetHandler:\n\t\t\t\t\tNetHandler(db, req)\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(errors.New(ErrInvalidReqHandler))\n\t\t\t\t}\n\n\t\t\t}(req)\n\n\t\tcase <-db.stop:\n\t\t\tglog.V(1).Infoln(\"db:stop\")\n\t\t\treturn\n\t\t}\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/yeo/betterdev.link/baja/dts\"\n\n\t\"github.com/labstack/echo\"\n)\n\n\n\n\nfunc (s *Server) Activity(c echo.Context) error ", "output": "{\n\tuser := c.Param(\"email\")\n\n\tactivity := dts.ActivityService{s.db}\n\tuserHistory := activity.LoadUser(user)\n\n\tc.Response().Header().Set(echo.HeaderContentType, \"application/json\")\n\n\treturn c.JSON(http.StatusOK, userHistory)\n}"} {"input": "package circonusgometrics\n\nimport (\n\t\"sync\"\n\n\t\"github.com/circonus-labs/circonusllhist\"\n)\n\n\ntype Histogram struct {\n\tname string\n\thist *circonusllhist.Histogram\n\trw sync.RWMutex\n}\n\n\nfunc (m *CirconusMetrics) Timing(metric string, val float64) {\n\tm.SetHistogramValue(metric, val)\n}\n\n\n\n\n\nfunc (m *CirconusMetrics) SetHistogramValue(metric string, val float64) {\n\tm.NewHistogram(metric)\n\n\tm.histograms[metric].rw.Lock()\n\tdefer m.histograms[metric].rw.Unlock()\n\n\tm.histograms[metric].hist.RecordValue(val)\n}\n\n\nfunc (m *CirconusMetrics) RemoveHistogram(metric string) {\n\tm.hm.Lock()\n\tdefer m.hm.Unlock()\n\tdelete(m.histograms, metric)\n}\n\n\nfunc (m *CirconusMetrics) NewHistogram(metric string) *Histogram {\n\tm.hm.Lock()\n\tdefer m.hm.Unlock()\n\n\tif hist, ok := m.histograms[metric]; ok {\n\t\treturn hist\n\t}\n\n\thist := &Histogram{\n\t\tname: metric,\n\t\thist: circonusllhist.New(),\n\t}\n\n\tm.histograms[metric] = hist\n\n\treturn hist\n}\n\n\nfunc (h *Histogram) Name() string {\n\treturn h.name\n}\n\n\nfunc (h *Histogram) RecordValue(v float64) {\n\th.rw.Lock()\n\tdefer h.rw.Unlock()\n\n\th.hist.RecordValue(v)\n}\n\nfunc (m *CirconusMetrics) RecordValue(metric string, val float64) ", "output": "{\n\tm.SetHistogramValue(metric, val)\n}"} {"input": "package logger\n\n\n\ntype options struct {\n\tvalues map[string][]OptionItem\n}\n\n\ntype Option struct {\n\tApply func(op *options)\n}\n\n\nfunc BackendOption(name string, level string, settings map[string]interface{}) Option {\n\treturn Option{func(op *options) {\n\t\tvals := make([]OptionItem, 0)\n\t\tvals = append(vals, OptionItem{\"level\", level})\n\n\t\tif len(settings) > 0 {\n\t\t\tfor k, v := range settings {\n\t\t\t\tvals = append(vals, OptionItem{k, v})\n\t\t\t}\n\t\t}\n\n\t\top.values[name] = vals\n\t}}\n}\n\n\n\n\n\nfunc GetterOption(name string, settings map[string]interface{}) Option {\n\treturn Option{func(op *options) {\n\t\tvals := make([]OptionItem, 0)\n\t\tif len(settings) > 0 {\n\t\t\tfor k, v := range settings {\n\t\t\t\tvals = append(vals, OptionItem{k, v})\n\t\t\t}\n\t\t}\n\n\t\top.values[name] = vals\n\t}}\n}\n\n\ntype OptionItem struct {\n\tfield string\n\tval interface{}\n}\n\n\nfunc (o *OptionItem) Field() string {\n\treturn o.field\n}\n\n\nfunc (o *OptionItem) Int() int {\n\tif o.val == nil {\n\t\treturn 0\n\t}\n\n\treturn o.val.(int)\n}\n\n\nfunc (o *OptionItem) String() string {\n\tif o.val == nil {\n\t\treturn \"\"\n\t}\n\n\treturn o.val.(string)\n}\n\n\nfunc (o *OptionItem) Raw() interface{} {\n\treturn o.val\n}\n\nfunc SweeperOption(name string, duration int, settings map[string]interface{}) Option ", "output": "{\n\treturn Option{func(op *options) {\n\t\tvals := make([]OptionItem, 0)\n\t\tvals = append(vals, OptionItem{\"duration\", duration})\n\n\t\tif len(settings) > 0 {\n\t\t\tfor k, v := range settings {\n\t\t\t\tvals = append(vals, OptionItem{k, v})\n\t\t\t}\n\t\t}\n\n\t\top.values[name] = vals\n\t}}\n}"} {"input": "package plusone\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc TestPlusOne(t *testing.T) ", "output": "{\n\tcases := []struct {\n\t\tname string\n\t\tinputs []int\n\t\texpect []int\n\t}{\n\t\t{\"1 digit is zero\", []int{0}, []int{1}},\n\t\t{\"1 digit is 9\", []int{9}, []int{1, 0}},\n\t\t{\"2 normal digits\", []int{2, 3}, []int{2, 4}},\n\t}\n\tfor _, c := range cases {\n\t\tt.Run(c.name, func(t *testing.T) {\n\t\t\tret := PlusOne(c.inputs)\n\t\t\tif !reflect.DeepEqual(ret, c.expect) {\n\t\t\t\tt.Fatalf(\"expected %v, but got %v, with inputs %v\",\n\t\t\t\t\tc.expect, ret, c.inputs)\n\t\t\t}\n\t\t})\n\t}\n\tt.Log(\"passed\")\n}"} {"input": "package readpass\n\n\n\n\nimport (\n\t\"log\"\n\t\"os\"\n\n\t\"golang.org/x/crypto/ssh/terminal\"\n)\n\n\n\n\n\nvar PasswordPrompt func(prompt string) (password string, err error) = DefaultPasswordPrompt\n\n\n\nvar PasswordPromptBytes func(prompt string) (password []byte, err error) = DefaultPasswordPromptBytes\n\n\n\nfunc DefaultPasswordPrompt(prompt string) (password string, err error) {\n\tstate, err := terminal.MakeRaw(0)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer terminal.Restore(0, state)\n\tterm := terminal.NewTerminal(os.Stdout, \">\")\n\tpassword, err = term.ReadPassword(prompt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}\n\n\n\nfunc DefaultPasswordPromptBytes(prompt string) (password []byte, err error) {\n\tpasswordString, err := PasswordPrompt(prompt)\n\tif err == nil {\n\t\tpassword = []byte(passwordString)\n\t}\n\treturn\n}\n\nfunc SSHPasswordPrompt(prompt string) (password string, err error) ", "output": "{\n\tstate, err := terminal.MakeRaw(0)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer terminal.Restore(0, state)\n\tterm := terminal.NewTerminal(os.Stdout, \">\")\n\tpassword, err = term.ReadPassword(prompt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}"} {"input": "package container\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/martin-helmich/distcrond/domain\"\n)\n\ntype JobContainer struct {\n\tjobs []domain.Job\n\tjobsByName map[string]*domain.Job\n}\n\nfunc NewJobContainer(initialCapacity int) *JobContainer {\n\tcontainer := new(JobContainer)\n\tcontainer.jobs = make([]domain.Job, 0, initialCapacity)\n\tcontainer.jobsByName = make(map[string]*domain.Job)\n\treturn container\n}\n\nfunc (c *JobContainer) AddJob(job domain.Job) {\n\tc.jobs = append(c.jobs, job)\n\tc.jobsByName[job.Name] = &c.jobs[len(c.jobs)-1]\n}\n\nfunc (c *JobContainer) Count() int {\n\treturn len(c.jobs)\n}\n\n\n\nfunc (c *JobContainer) Get(i int) *domain.Job {\n\treturn &c.jobs[i]\n}\n\nfunc (c *JobContainer) JobByName(n string) (*domain.Job, error) {\n\tif job, ok := c.jobsByName[n]; !ok {\n\t\treturn nil, errors.New(fmt.Sprintf(\"No job with name '%s' is known\", n))\n\t} else {\n\t\treturn job, nil\n\t}\n}\n\nfunc (c *JobContainer) All() []domain.Job ", "output": "{\n\treturn c.jobs\n}"} {"input": "package scheduler\n\nimport (\n\t\"github.com/cnaize/kubernetes/pkg/api\"\n)\n\n\ntype FitPredicate func(pod api.Pod, existingPods []api.Pod, node string) (bool, error)\n\n\ntype HostPriority struct {\n\thost string\n\tscore int\n}\n\ntype HostPriorityList []HostPriority\n\n\n\nfunc (h HostPriorityList) Less(i, j int) bool {\n\tif h[i].score == h[j].score {\n\t\treturn h[i].host < h[j].host\n\t}\n\treturn h[i].score < h[j].score\n}\n\nfunc (h HostPriorityList) Swap(i, j int) {\n\th[i], h[j] = h[j], h[i]\n}\n\ntype PriorityFunction func(pod api.Pod, podLister PodLister, minionLister MinionLister) (HostPriorityList, error)\n\ntype PriorityConfig struct {\n\tFunction PriorityFunction\n\tWeight int\n}\n\nfunc (h HostPriorityList) Len() int ", "output": "{\n\treturn len(h)\n}"} {"input": "package callinfo\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\n\t\"github.com/youtube/vitess/go/rpcwrap/proto\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\nfunc RPCWrapCallInfo(ctx context.Context) context.Context {\n\tremoteAddr, _ := proto.RemoteAddr(ctx)\n\tusername, _ := proto.Username(ctx)\n\treturn NewContext(ctx, &rpcWrapCallInfoImpl{\n\t\tremoteAddr: remoteAddr,\n\t\tusername: username,\n\t})\n}\n\ntype rpcWrapCallInfoImpl struct {\n\tremoteAddr, username string\n}\n\nfunc (rwci *rpcWrapCallInfoImpl) RemoteAddr() string {\n\treturn rwci.remoteAddr\n}\n\nfunc (rwci *rpcWrapCallInfoImpl) Username() string {\n\treturn rwci.username\n}\n\n\n\nfunc (rwci *rpcWrapCallInfoImpl) HTML() template.HTML {\n\treturn template.HTML(\"RemoteAddr: \" + rwci.remoteAddr + \"
\\n\" + \"Username: \" + rwci.username + \"
\\n\")\n}\n\nfunc (rwci *rpcWrapCallInfoImpl) Text() string ", "output": "{\n\treturn fmt.Sprintf(\"%s@%s\", rwci.username, rwci.remoteAddr)\n}"} {"input": "package jaegerthrifthttpexporter\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/model/pdata\"\n)\n\nconst testHTTPAddress = \"http:a.example.com:123/at/some/path\"\n\n\n\nfunc TestNew(t *testing.T) ", "output": "{\n\tconfig := Config{\n\t\tExporterSettings: config.NewExporterSettings(config.NewComponentID(typeStr)),\n\t\tHTTPClientSettings: confighttp.HTTPClientSettings{\n\t\t\tEndpoint: testHTTPAddress,\n\t\t\tHeaders: map[string]string{\"test\": \"test\"},\n\t\t\tTimeout: 10 * time.Nanosecond,\n\t\t},\n\t}\n\n\tgot, err := newTracesExporter(&config, componenttest.NewNopExporterCreateSettings())\n\tassert.NoError(t, err)\n\trequire.NotNil(t, got)\n\n\terr = got.ConsumeTraces(context.Background(), pdata.NewTraces())\n\tassert.NoError(t, err)\n}"} {"input": "package k1\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t\"github.com/songgao/water\"\n)\n\n\n\nfunc initTun(tun string, ipNet *net.IPNet, mtu int) error {\n\tip := ipNet.IP\n\tmaskIP := net.IP(ipNet.Mask)\n\tsargs := fmt.Sprintf(\"%s %s %s mtu %d netmask %s up\", tun, ip.String(), ip.String(), mtu, maskIP.String())\n\tif err := execCommand(\"ifconfig\", sargs); err != nil {\n\t\treturn err\n\t}\n\treturn addRoute(tun, ipNet)\n}\n\nfunc addRoute(tun string, subnet *net.IPNet) error {\n\tip := subnet.IP\n\tmaskIP := net.IP(subnet.Mask)\n\tsargs := fmt.Sprintf(\"-n add -net %s -netmask %s -interface %s\", ip.String(), maskIP.String(), tun)\n\treturn execCommand(\"route\", sargs)\n}\n\nfunc createTun(ip net.IP, mask net.IPMask) (*water.Interface, error) {\n\tifce, err := water.New(water.Config{\n\t\tDeviceType: water.TUN,\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger.Infof(\"create %s\", ifce.Name())\n\n\tipNet := &net.IPNet{\n\t\tIP: ip,\n\t\tMask: mask,\n\t}\n\n\tif err := initTun(ifce.Name(), ipNet, MTU); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ifce, nil\n}\n\n\nfunc fixTunIP(ip net.IP) net.IP {\n\treturn net.IPv4zero\n}\n\nfunc execCommand(name, sargs string) error ", "output": "{\n\targs := strings.Split(sargs, \" \")\n\tcmd := exec.Command(name, args...)\n\tlogger.Infof(\"exec command: %s %s\", name, sargs)\n\treturn cmd.Run()\n}"} {"input": "package ram\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestGetAccountAlias(t *testing.T) ", "output": "{\n\tvar req GetAccountAliasRequest\n\treq.Init()\n\treq.SetFormat(\"JSON\")\n\treq.SetRegionId(\"cn-shenzhen\")\n\tvar accessId = \"Ie65kUInu5GeAsma\"\n\tvar accessSecret = \"8cCqoxdYU9zKUihwXFXiN1HEACBDwB\"\n\tresp, err := GetAccountAlias(&req, accessId, accessSecret)\n\tif err != nil {\n\t\tt.Errorf(\"Error: %s\", err.Error())\n\t}\n\tfmt.Printf(\"Success: %v\\n\", resp)\n}"} {"input": "package foursum\n\nimport \"sort\"\n\nfunc fourSum(nums []int, target int) [][]int {\n\tif l := len(nums); l >= 4 {\n\t\tsort.Ints(nums) \n\n\t\tr := make([][]int, 0, l)\n\t\tfor i := 0; i < l-3; i++ {\n\t\t\tif i == 0 || nums[i] != nums[i-1] { \n\t\t\t\tthreeSum(&r, nums[i+1:], nums[i], target-nums[i])\n\t\t\t}\n\t\t}\n\t\treturn r\n\t}\n\treturn [][]int{}\n}\n\n\n\nfunc threeSum(r *[][]int, nums []int, base, target int) ", "output": "{\n\tfor i, l := 0, len(nums); i < l-2; i++ { \n\t\tif i == 0 || nums[i] != nums[i-1] { \n\t\t\tfor n, j, k := nums[i], i+1, l-1; j < k; {\n\t\t\t\tif sum := n + nums[j] + nums[k]; sum == target {\n\t\t\t\t\t*r = append(*r, []int{base, n, nums[j], nums[k]}) \n\t\t\t\t\tfor k--; k > j && nums[k] == nums[k+1]; k-- { \n\t\t\t\t\t}\n\t\t\t\t\tfor j++; j < k && nums[j] == nums[j-1]; j++ { \n\t\t\t\t\t}\n\t\t\t\t} else if sum > target {\n\t\t\t\t\tk-- \n\t\t\t\t} else {\n\t\t\t\t\tj++ \n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package packets\n\nimport (\n\t\"io\"\n)\n\ntype WillMsgReqMessage struct {\n\tHeader\n}\n\nfunc (wm *WillMsgReqMessage) MessageType() byte {\n\treturn WILLMSGREQ\n}\n\n\n\nfunc (wm *WillMsgReqMessage) Unpack(b io.Reader) {\n\n}\n\nfunc (wm *WillMsgReqMessage) Write(w io.Writer) error ", "output": "{\n\tpacket := wm.Header.pack()\n\tpacket.WriteByte(wm.Header.MessageType)\n\t_, err := packet.WriteTo(w)\n\n\treturn err\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSAmazonMQConfiguration_TagsEntry struct {\n\n\tKey string `json:\"Key,omitempty\"`\n\n\tValue string `json:\"Value,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) AWSCloudFormationType() string {\n\treturn \"AWS::AmazonMQ::Configuration.TagsEntry\"\n}\n\n\n\n\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) DependsOn() []string ", "output": "{\n\treturn r._dependsOn\n}"} {"input": "package data\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\n\ntype Art struct {\n\tID int\n\tFileSize int64 `db:\"file_size\"`\n\tFileName string `db:\"file_name\"`\n\tLastModified int64 `db:\"last_modified\"`\n}\n\n\nfunc (a *Art) Delete() error {\n\treturn DB.DeleteArt(a)\n}\n\n\n\n\n\nfunc (a *Art) Save() error {\n\treturn DB.SaveArt(a)\n}\n\n\nfunc (a Art) Stream() (io.ReadSeeker, error) {\n\treturn os.Open(a.FileName)\n}\n\nfunc (a *Art) Load() error ", "output": "{\n\treturn DB.LoadArt(a)\n}"} {"input": "package test\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/rook/rook/pkg/daemon/ceph/client\"\n)\n\n\n\nfunc MonInQuorumResponseFromMons(mons map[string]*client.MonInfo) string {\n\tresp := client.MonStatusResponse{Quorum: []int{}}\n\ti := 0\n\tfor name := range mons {\n\t\tresp.MonMap.Mons = append(resp.MonMap.Mons, client.MonMapEntry{\n\t\t\tName: name,\n\t\t\tRank: i,\n\t\t\tAddress: fmt.Sprintf(\"1.2.3.%d\", i),\n\t\t})\n\t\tresp.Quorum = append(resp.Quorum, i)\n\t\ti++\n\t}\n\tserialized, _ := json.Marshal(resp)\n\treturn string(serialized)\n}\n\nfunc MonInQuorumResponseMany(count int) string {\n\tresp := client.MonStatusResponse{Quorum: []int{0}}\n\tresp.MonMap.Mons = []client.MonMapEntry{}\n\tfor i := 0; i <= count; i++ {\n\t\tresp.MonMap.Mons = append(resp.MonMap.Mons, client.MonMapEntry{\n\t\t\tName: fmt.Sprintf(\"rook-ceph-mon%d\", i),\n\t\t\tRank: 0,\n\t\t\tAddress: fmt.Sprintf(\"1.2.3.%d\", i),\n\t\t})\n\t}\n\tserialized, _ := json.Marshal(resp)\n\treturn string(serialized)\n}\n\nfunc MonInQuorumResponse() string ", "output": "{\n\tresp := client.MonStatusResponse{Quorum: []int{0}}\n\tresp.MonMap.Mons = []client.MonMapEntry{\n\t\t{\n\t\t\tName: \"a\",\n\t\t\tRank: 0,\n\t\t\tAddress: \"1.2.3.1\",\n\t\t},\n\t}\n\tserialized, _ := json.Marshal(resp)\n\treturn string(serialized)\n}"} {"input": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"time\"\n)\n\ntype TLSConnection struct {\n\thost string\n\tcertPool *x509.CertPool\n\tconn *tls.Conn\n}\n\nfunc NewTLSConnection(host string) (*TLSConnection, error) {\n\tc := &TLSConnection{}\n\tc.host = host\n\tc.getCerts()\n\terr := c.Connect()\n\treturn c, err\n}\n\nfunc (c *TLSConnection) Connect() (err error) {\n\tc.conn, err = tls.Dial(\"tcp\", c.host, &tls.Config{\n\t\tRootCAs: c.certPool,\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\tc.conn.SetWriteDeadline(time.Time{})\n\treturn\n}\n\nfunc (c *TLSConnection) WriteString(s string) (n int, err error) {\n\treturn io.WriteString(c.conn, s)\n}\n\nfunc (c *TLSConnection) Write(p []byte) (n int, err error) {\n\treturn c.conn.Write(p)\n}\n\n\n\nfunc (c *TLSConnection) getCerts() {\n\tc.certPool = x509.NewCertPool()\n\tcert, err := ioutil.ReadFile(certsPemFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif !c.certPool.AppendCertsFromPEM(cert) {\n\t\tlog.Fatal(\"Failed parsing root certificate\")\n\t}\n}\n\nfunc (c *TLSConnection) Close() error ", "output": "{\n\treturn c.conn.Close()\n}"} {"input": "package stree\n\n\n\ntype serial struct {\n\tstree\n}\n\n\nfunc NewSerial() Tree {\n\tt := new(serial)\n\tt.Clear()\n\treturn t\n}\n\nfunc (t *serial) BuildTree() {\n\tpanic(\"BuildTree() not supported for serial data structure\")\n}\n\n\n\nfunc (t *serial) Tree2Array() []SegmentOverlap {\n\tpanic(\"Tree2Array() not supported for serial data structure\")\n}\n\n\nfunc (t *serial) Query(from, to int) []Interval {\n\tresult := make([]Interval, 0, 10)\n\tfor _, intrvl := range t.base {\n\t\tif !intrvl.Segment.Disjoint(from, to) {\n\t\t\tresult = append(result, intrvl)\n\t\t}\n\t}\n\treturn result\n}\n\n\nfunc (t *serial) QueryArray(from, to []int) []Interval {\n\tresult := make([]Interval, 0, 10)\n\tfor i, fromvalue := range from {\n\t\tresult = append(result, t.Query(fromvalue, to[i])...)\n\t}\n\treturn result\n}\n\nfunc (t *serial) Print() ", "output": "{\n\tpanic(\"Print() not supported for serial data structure\")\n}"} {"input": "package antlr\n\nimport \"fmt\"\n\ntype TraceListener struct {\n\tparser *BaseParser\n}\n\nfunc NewTraceListener(parser *BaseParser) *TraceListener {\n\ttl := new(TraceListener)\n\ttl.parser = parser\n\treturn tl\n}\n\nfunc (t *TraceListener) VisitErrorNode(_ ErrorNode) {\n}\n\nfunc (t *TraceListener) EnterEveryRule(ctx ParserRuleContext) {\n\tfmt.Println(\"enter \" + t.parser.GetRuleNames()[ctx.GetRuleIndex()] + \", LT(1)=\" + t.parser.input.LT(1).GetText())\n}\n\n\n\nfunc (t *TraceListener) ExitEveryRule(ctx ParserRuleContext) {\n\tfmt.Println(\"exit \" + t.parser.GetRuleNames()[ctx.GetRuleIndex()] + \", LT(1)=\" + t.parser.input.LT(1).GetText())\n}\n\nfunc (t *TraceListener) VisitTerminal(node TerminalNode) ", "output": "{\n\tfmt.Println(\"consume \" + fmt.Sprint(node.GetSymbol()) + \" rule \" + t.parser.GetRuleNames()[t.parser.ctx.GetRuleIndex()])\n}"} {"input": "package gota\n\n\ntype RSI struct {\n\temaUp EMA\n\temaDown EMA\n\tlastV float64\n}\n\n\nfunc NewRSI(inTimePeriod int, warmType WarmupType) *RSI {\n\tema := NewEMA(inTimePeriod+1, warmType)\n\tema.alpha = float64(1) / float64(inTimePeriod)\n\treturn &RSI{\n\t\temaUp: *ema,\n\t\temaDown: *ema,\n\t}\n}\n\n\nfunc (rsi RSI) WarmCount() int {\n\treturn rsi.emaUp.WarmCount()\n}\n\n\nfunc (rsi RSI) Warmed() bool {\n\treturn rsi.emaUp.Warmed()\n}\n\n\nfunc (rsi RSI) Last() float64 {\n\treturn 100 - (100 / (1 + rsi.emaUp.Last()/rsi.emaDown.Last()))\n}\n\n\n\n\nfunc (rsi *RSI) Add(v float64) float64 ", "output": "{\n\tvar up float64\n\tvar down float64\n\tif v > rsi.lastV {\n\t\tup = v - rsi.lastV\n\t} else if v < rsi.lastV {\n\t\tdown = rsi.lastV - v\n\t}\n\trsi.emaUp.Add(up)\n\trsi.emaDown.Add(down)\n\trsi.lastV = v\n\treturn rsi.Last()\n}"} {"input": "package delegatednetwork\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) BaseClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient ", "output": "{\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package main\n\nimport \"strings\"\n\nvar x = make([]byte, 10)\n\nfunc main() {\n\ttest1()\n\ttest2()\n\ttest3()\n\ttest4()\n\ttest5()\n\ttest6()\n\ttest7()\n}\n\nfunc mustRecover(s string) {\n\tv := recover()\n\tif v == nil {\n\t\tpanic(\"expected panic\")\n\t}\n\tif e := v.(error).Error(); strings.Index(e, s) < 0 {\n\t\tpanic(\"want: \" + s + \"; have: \" + e)\n\t}\n}\n\n\n\nfunc test2() {\n\tdefer mustRecover(\"slice\")\n\tprintln(x[5:15])\n}\n\nfunc test3() {\n\tdefer mustRecover(\"slice\")\n\tvar lo = 11\n\tvar hi = 9\n\tprintln(x[lo:hi])\n}\n\nfunc test4() {\n\tdefer mustRecover(\"interface\")\n\tvar x interface{} = 1\n\tprintln(x.(float32))\n}\n\ntype T struct {\n\ta, b int\n\tc []int\n}\n\nfunc test5() {\n\tdefer mustRecover(\"uncomparable\")\n\tvar x T\n\tvar z interface{} = x\n\tprintln(z != z)\n}\n\nfunc test6() {\n\tdefer mustRecover(\"unhashable\")\n\tvar x T\n\tvar z interface{} = x\n\tm := make(map[interface{}]int)\n\tm[z] = 1\n}\n\nfunc test7() {\n\tdefer mustRecover(\"divide by zero\")\n\tvar x, y int\n\tprintln(x / y)\n}\n\nfunc test1() ", "output": "{\n\tdefer mustRecover(\"index\")\n\tprintln(x[123])\n}"} {"input": "package queue\n\nimport (\n\t\"fmt\"\n\t\"github.com/apache/servicecomb-service-center/pkg/log\"\n\t\"golang.org/x/net/context\"\n)\n\ntype UniQueue struct {\n\tqueue chan interface{}\n}\n\nfunc (uq *UniQueue) Get(ctx context.Context) interface{} {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil\n\tcase item := <-uq.queue:\n\t\treturn item\n\t}\n}\n\n\n\nfunc (uq *UniQueue) Put(value interface{}) (e error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.LogPanic(r)\n\n\t\t\te = fmt.Errorf(\"%v\", r)\n\t\t}\n\t}()\n\n\tselect {\n\tcase _, ok := <-uq.queue:\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"channel is closed\")\n\t\t}\n\tdefault:\n\t}\n\n\tselect {\n\tcase uq.queue <- value:\n\tdefault:\n\t}\n\treturn\n}\n\nfunc (uq *UniQueue) Close() {\n\tselect {\n\tcase _, ok := <-uq.queue:\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\tdefault:\n\t}\n\tclose(uq.queue)\n}\n\nfunc NewUniQueue() (uq *UniQueue) {\n\treturn &UniQueue{\n\t\tqueue: make(chan interface{}, 1),\n\t}\n}\n\nfunc (uq *UniQueue) Chan() <-chan interface{} ", "output": "{\n\treturn uq.queue\n}"} {"input": "package app\n\nimport (\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/urfave/cli\"\n)\n\n\nfunc GenerateCommandsHelp(cmds []cli.Command) string {\n\tcommandsUsage := make([]string, 0, len(cmds))\n\tfor _, cmd := range cmds {\n\t\tcommandsUsage = append(commandsUsage, GenerateSubcommandsUsage(cmd, \"\")...)\n\t}\n\n\tsort.Strings(commandsUsage)\n\n\treturn \" \" + strings.Join(commandsUsage, \"\\r\\n \")\n}\n\n\n\n\nfunc GenerateSubcommandsUsage(cmd cli.Command, prefix string) (commandsUsage []string) ", "output": "{\n\tif cmd.Subcommands == nil || len(cmd.Subcommands) == 0 {\n\t\tfullName := prefix + cmd.Name\n\n\t\treturn []string{fullName + \": \" + cmd.Usage}\n\t}\n\tcommandsUsage = make([]string, 0, len(cmd.Subcommands))\n\tfor _, subcmd := range cmd.Subcommands {\n\t\tcommandsUsage = append(commandsUsage, GenerateSubcommandsUsage(subcmd, prefix+cmd.Name+\" \")...)\n\t}\n\treturn\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc merge(a, b, d []int) {\n i, j, k := 0, 0, 0\n na, nb := len(a), len(b)\n for i < na && j < nb {\n if a[i] < b[j] {\n d[k] = a[i]\n i++\n } else {\n d[k] = b[j]\n j++;\n }\n k++;\n }\n for i < na {\n d[k] = a[i]\n k++\n i++\n }\n for j < nb {\n d[k] = b[j]\n k++\n j++\n }\n}\n\nfunc merge_sort1(a, b []int) {\n n := len(a)\n if n == 1 {\n b[0] = a[0]\n return\n }\n merge_sort1(a[:n/2], b[:n/2])\n merge_sort1(a[n/2:], b[n/2:])\n merge(b[:n/2], b[n/2:], a)\n copy(b,a)\n}\n\n\n\nfunc main() {\n a := []int{3,4,178,642,85,3,45,78,5,976,34,51,65,761,414,1,87,612,53,14,550}\n merge_sort(a)\n fmt.Println(a)\n}\n\nfunc merge_sort(a []int) ", "output": "{\n n := len(a)\n if n <= 1 {\n return\n }\n b := make([]int, n)\n merge_sort1(a[:n/2], b[:n/2])\n merge_sort1(a[n/2:], b[n/2:])\n merge(b[:n/2], b[n/2:], a)\n}"} {"input": "package thirdpartyresourcedata\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"k8s.io/kubernetes/pkg/api/unversioned\"\n\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n)\n\nfunc ExtractGroupVersionKind(list *extensions.ThirdPartyResourceList) ([]unversioned.GroupVersion, []unversioned.GroupVersionKind, error) {\n\tgvs := []unversioned.GroupVersion{}\n\tgvks := []unversioned.GroupVersionKind{}\n\tfor ix := range list.Items {\n\t\trsrc := &list.Items[ix]\n\t\tkind, group, err := ExtractApiGroupAndKind(rsrc)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tfor _, version := range rsrc.Versions {\n\t\t\tgv := unversioned.GroupVersion{Group: group, Version: version.Name}\n\t\t\tgvs = append(gvs, gv)\n\t\t\tgvks = append(gvks, unversioned.GroupVersionKind{Group: group, Version: version.Name, Kind: kind})\n\t\t}\n\t}\n\treturn gvs, gvks, nil\n}\n\n\n\nfunc ExtractApiGroupAndKind(rsrc *extensions.ThirdPartyResource) (kind string, group string, err error) {\n\tparts := strings.Split(rsrc.Name, \".\")\n\tif len(parts) < 3 {\n\t\treturn \"\", \"\", fmt.Errorf(\"unexpectedly short resource name: %s, expected at least ..\", rsrc.Name)\n\t}\n\treturn convertToCamelCase(parts[0]), strings.Join(parts[1:], \".\"), nil\n}\n\nfunc convertToCamelCase(input string) string ", "output": "{\n\tresult := \"\"\n\ttoUpper := true\n\tfor ix := range input {\n\t\tchar := input[ix]\n\t\tif toUpper {\n\t\t\tresult = result + string([]byte{(char - 32)})\n\t\t\ttoUpper = false\n\t\t} else if char == '-' {\n\t\t\ttoUpper = true\n\t\t} else {\n\t\t\tresult = result + string([]byte{char})\n\t\t}\n\t}\n\treturn result\n}"} {"input": "package main\n\nimport (\n\t\"github.com/kr/pretty\"\n\t\"testing\"\n)\n\n\n\nfunc TestReadYAMLConf(t *testing.T) {\n\tpath := \"./examples/basic\"\n\n\tfiles, err := ReadFiles(path)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif len(files) <= 0 {\n\t\tt.Error(\"files len must be > 0\")\n\t}\n\n\tfor _, f := range files {\n\t\tif f.Base == \"_.yaml\" {\n\t\t\tif len(f.Meta) <= 0 {\n\t\t\t\tt.Errorf(\"%s could not read\", f.Path)\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nfunc TestReadFiles(t *testing.T) ", "output": "{\n\n\tpath := \"./examples/basic\"\n\tfiles, err := ReadFiles(path)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif len(files) <= 0 {\n\t\tt.Error(\"files len must be > 0\")\n\t}\n\n\tt.Logf(\"%# v\", pretty.Formatter(files))\n}"} {"input": "package certificates\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gophercloud/gophercloud\"\n)\n\n\n\ntype CreateOptsBuilder interface {\n\tToCertificateCreateMap() (map[string]interface{}, error)\n}\n\n\ntype CreateOpts struct {\n\tClusterUUID string `json:\"cluster_uuid,omitempty\" xor:\"BayUUID\"`\n\tBayUUID string `json:\"bay_uuid,omitempty\" xor:\"ClusterUUID\"`\n\tCSR string `json:\"csr\" required:\"true\"`\n}\n\n\n\n\n\nfunc Get(client *gophercloud.ServiceClient, clusterID string) (r GetResult) {\n\turl := getURL(client, clusterID)\n\n\t_, r.Err = client.Get(url, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{200},\n\t})\n\n\treturn\n}\n\n\nfunc Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToCertificateCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\n\tvar result *http.Response\n\tresult, r.Err = client.Post(createURL(client), b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{201},\n\t})\n\n\tif r.Err == nil {\n\t\tr.Header = result.Header\n\t}\n\n\treturn\n}\n\n\nfunc Update(client *gophercloud.ServiceClient, clusterID string) (r UpdateResult) {\n\t_, r.Err = client.Patch(updateURL(client, clusterID), nil, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{202},\n\t})\n\n\treturn\n}\n\nfunc (opts CreateOpts) ToCertificateCreateMap() (map[string]interface{}, error) ", "output": "{\n\treturn gophercloud.BuildRequestBody(opts, \"\")\n}"} {"input": "package util\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestOnlyNumbers(t *testing.T) ", "output": "{\n\tphone := \"(604)555-1212\"\n\tphonenum := \"6045551212\"\n\tv := OnlyNumbers(phone)\n\tif v != phonenum {\n\t\tt.Error(\n\t\t\t\"For\", phone,\n\t\t\t\"expected\", phonenum,\n\t\t\t\"got\", v,\n\t\t)\n\t}\n}"} {"input": "package test_utils\n\nimport (\n\t\"fmt\"\n\t\"simplejsondb/dbio\"\n)\n\n\n\ntype InMemoryDataFile struct {\n\tBlocks [][]byte\n\tCloseFunc func() error\n\tReadBlockFunc func(uint16, []byte) error\n\tWriteBlockFunc func(uint16, []byte) error\n}\n\nfunc NewFakeDataFile(blocksCount int) *InMemoryDataFile {\n\tblocks := [][]byte{}\n\tfor i := 0; i < blocksCount; i++ {\n\t\tblocks = append(blocks, make([]byte, dbio.DATABLOCK_SIZE))\n\t}\n\treturn NewFakeDataFileWithBlocks(blocks)\n}\n\n\n\nfunc (df *InMemoryDataFile) Close() error {\n\treturn df.CloseFunc()\n}\nfunc (df *InMemoryDataFile) ReadBlock(id uint16, data []byte) error {\n\treturn df.ReadBlockFunc(id, data)\n}\nfunc (df *InMemoryDataFile) WriteBlock(id uint16, data []byte) error {\n\treturn df.WriteBlockFunc(id, data)\n}\n\nfunc NewFakeDataFileWithBlocks(blocks [][]byte) *InMemoryDataFile ", "output": "{\n\treturn &InMemoryDataFile{\n\t\tBlocks: blocks,\n\t\tCloseFunc: func() error {\n\t\t\treturn nil \n\t\t},\n\t\tWriteBlockFunc: func(id uint16, data []byte) error {\n\t\t\tblock := blocks[id]\n\t\t\tfor i := range block {\n\t\t\t\tblock[i] = data[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tReadBlockFunc: func(id uint16, data []byte) error {\n\t\t\tif id < 0 || id >= uint16(len(blocks)) {\n\t\t\t\treturn fmt.Errorf(\"Invalid datablock requested: %d\", id)\n\t\t\t}\n\t\t\tblock := blocks[id]\n\t\t\tfor i := 0; i < len(block); i++ {\n\t\t\t\tdata[i] = block[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n}"} {"input": "package elements_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/purl.org/dc/elements\"\n)\n\nfunc TestSimpleLiteralConstructor(t *testing.T) {\n\tv := elements.NewSimpleLiteral()\n\tif v == nil {\n\t\tt.Errorf(\"elements.NewSimpleLiteral must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed elements.SimpleLiteral should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestSimpleLiteralMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := elements.NewSimpleLiteral()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := elements.NewSimpleLiteral()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package zipkin\n\nimport (\n\t\"github.com/jaegertracing/jaeger/thrift-gen/zipkincore\"\n)\n\n\nfunc IsServerCore(anno string) bool {\n\treturn anno == zipkincore.SERVER_SEND || anno == zipkincore.SERVER_RECV\n}\n\n\nfunc IsClientCore(anno string) bool {\n\treturn anno == zipkincore.CLIENT_SEND || anno == zipkincore.CLIENT_RECV\n}\n\n\n\n\n\nfunc FindServiceName(span *zipkincore.Span) string {\n\tfor _, anno := range span.Annotations {\n\t\tendpoint := anno.GetHost()\n\t\tif endpoint == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif IsCore(anno.Value) && endpoint.GetServiceName() != \"\" {\n\t\t\treturn endpoint.GetServiceName()\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc IsCore(anno string) bool ", "output": "{\n\treturn IsServerCore(anno) || IsClientCore(anno)\n}"} {"input": "package stop\n\nimport (\n\t\"github.com/seehuhn/classification/data\"\n)\n\n\n\n\n\ntype Function func(data.Histogram) bool\n\n\n\n\n\n\n\n\n\n\nfunc IfPure(hist data.Histogram) bool {\n\tk := 0\n\tfor _, ni := range hist {\n\t\tif ni > 0 {\n\t\t\tk++\n\t\t\tif k > 1 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\nfunc IfPureOrAtMost(n float64) Function {\n\treturn func(hist data.Histogram) bool {\n\t\ttotal := 0.0\n\t\tk := 0\n\t\tfor _, ni := range hist {\n\t\t\ttotal += ni\n\t\t\tif ni > 0 {\n\t\t\t\tk++\n\t\t\t}\n\t\t\tif k > 1 && total > n {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n}\n\nfunc IfAtMost(n float64) Function ", "output": "{\n\treturn func(hist data.Histogram) bool {\n\t\treturn hist.Sum() <= n\n\t}\n}"} {"input": "package network\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/docker/docker/api/types/filters\"\n\t\"github.com/docker/docker/cli\"\n\t\"github.com/docker/docker/cli/command\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype pruneOptions struct {\n\tforce bool\n}\n\n\n\n\nconst warning = `WARNING! This will remove all networks not used by at least one container.\nAre you sure you want to continue?`\n\nfunc runPrune(dockerCli *command.DockerCli, opts pruneOptions) (output string, err error) {\n\tif !opts.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) {\n\t\treturn\n\t}\n\n\treport, err := dockerCli.Client().NetworksPrune(context.Background(), filters.Args{})\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(report.NetworksDeleted) > 0 {\n\t\toutput = \"Deleted Networks:\\n\"\n\t\tfor _, id := range report.NetworksDeleted {\n\t\t\toutput += id + \"\\n\"\n\t\t}\n\t}\n\n\treturn\n}\n\n\n\nfunc RunPrune(dockerCli *command.DockerCli) (uint64, string, error) {\n\toutput, err := runPrune(dockerCli, pruneOptions{force: true})\n\treturn 0, output, err\n}\n\nfunc NewPruneCommand(dockerCli *command.DockerCli) *cobra.Command ", "output": "{\n\tvar opts pruneOptions\n\n\tcmd := &cobra.Command{\n\t\tUse: \"prune [OPTIONS]\",\n\t\tShort: \"Remove all unused networks\",\n\t\tArgs: cli.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\toutput, err := runPrune(dockerCli, opts)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif output != \"\" {\n\t\t\t\tfmt.Fprintln(dockerCli.Out(), output)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tTags: map[string]string{\"version\": \"1.25\"},\n\t}\n\n\tflags := cmd.Flags()\n\tflags.BoolVarP(&opts.force, \"force\", \"f\", false, \"Do not prompt for confirmation\")\n\n\treturn cmd\n}"} {"input": "package plugin\n\nimport \"strings\"\n\n\ntype YandexShare struct{}\n\n\nfunc (p *YandexShare) Defaults() map[string]string {\n\treturn map[string]string{\"services\": \"facebook,twitter,gplus\", \"size\": \"m\", \"lang\": \"en\"}\n}\n\n\n\n\nfunc (p *YandexShare) SetUp(settings map[string]string) (map[string]string, error) ", "output": "{\n\tif val, ok := settings[\"services\"]; ok {\n\t\tsettings[\"services\"] = strings.Replace(val, \" \", \",\", -1)\n\t}\n\n\treturn mergeSettings(settings, p.Defaults()), nil\n}"} {"input": "package b\n\nimport \"a\"\n\nvar N n\n\ntype n struct{}\n\nfunc (r n) M1() int { return a.G1 }\nfunc (r n) M2() int { return a.G2 }\nfunc (r n) M3() int { return a.G3 }\nfunc (r n) M4() int { return a.G4 }\nfunc (r n) M5() int { return a.G5 }\nfunc (r n) M6() int { return a.G6 }\nfunc (r n) M7() int { return a.G7 }\nfunc (r n) M8() int { return a.G8 }\nfunc (r n) M9() int { return a.G9 }\n\n\nfunc (r n) M10() int ", "output": "{ return a.G10 }"} {"input": "package armsql_test\n\nimport (\n\t\"context\"\n\t\"log\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azcore/to\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/sql/armsql\"\n)\n\n\n\n\n\nfunc ExampleDataMaskingPoliciesClient_Get() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armsql.NewDataMaskingPoliciesClient(\"\", cred, nil)\n\tres, err := client.Get(ctx,\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Response result: %#v\\n\", res.DataMaskingPoliciesClientGetResult)\n}\n\nfunc ExampleDataMaskingPoliciesClient_CreateOrUpdate() ", "output": "{\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armsql.NewDataMaskingPoliciesClient(\"\", cred, nil)\n\tres, err := client.CreateOrUpdate(ctx,\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\tarmsql.DataMaskingPolicy{\n\t\t\tProperties: &armsql.DataMaskingPolicyProperties{\n\t\t\t\tDataMaskingState: armsql.DataMaskingStateEnabled.ToPtr(),\n\t\t\t\tExemptPrincipals: to.StringPtr(\"\"),\n\t\t\t},\n\t\t},\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Response result: %#v\\n\", res.DataMaskingPoliciesClientCreateOrUpdateResult)\n}"} {"input": "package sarama\n\n\ntype ApiVersionsRequest struct{}\n\nfunc (a *ApiVersionsRequest) encode(pe packetEncoder) error {\n\treturn nil\n}\n\nfunc (a *ApiVersionsRequest) decode(pd packetDecoder, version int16) (err error) {\n\treturn nil\n}\n\nfunc (a *ApiVersionsRequest) key() int16 {\n\treturn 18\n}\n\n\n\nfunc (a *ApiVersionsRequest) headerVersion() int16 {\n\treturn 1\n}\n\nfunc (a *ApiVersionsRequest) requiredVersion() KafkaVersion {\n\treturn V0_10_0_0\n}\n\nfunc (a *ApiVersionsRequest) version() int16 ", "output": "{\n\treturn 0\n}"} {"input": "package windows\n\nimport (\n\t\"github.com/docker/docker/daemon/execdriver\"\n\t\"github.com/docker/engine-api/types/container\"\n)\n\ntype info struct {\n\tID string\n\tdriver *Driver\n\tisolation container.IsolationLevel\n}\n\n\nfunc (d *Driver) Info(id string) execdriver.Info {\n\treturn &info{\n\t\tID: id,\n\t\tdriver: d,\n\t\tisolation: DefaultIsolation,\n\t}\n}\n\n\n\nfunc (i *info) IsRunning() bool ", "output": "{\n\tvar running bool\n\trunning = true \n\treturn running\n}"} {"input": "package collector\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n\n\nfunc Bufferapp() Platform ", "output": "{\n\treturn Platform{\n\t\tenabled: true,\n\t\tname: \"buffer\",\n\t\tstatsURL: \"https://api.bufferapp.com/1/links/shares.json?url=%s\",\n\t\tparseWith: func(r *http.Response) (Stat, error) {\n\t\t\tbody, error := ioutil.ReadAll(r.Body)\n\t\t\tif error != nil {\n\t\t\t\treturn Stat{}, error\n\t\t\t}\n\n\t\t\tvar jsonBlob map[string]interface{}\n\t\t\tif err := json.Unmarshal(body, &jsonBlob); err != nil {\n\t\t\t\treturn Stat{}, err\n\t\t\t}\n\n\t\t\treturn Stat{\n\t\t\t\tdata: map[string]interface{}{\"count\": jsonBlob[\"shares\"]},\n\t\t\t}, nil\n\t\t},\n\t}\n}"} {"input": "package internal\n\nvar _ TerminateFile = &terminateFile{}\n\ntype terminateFile struct {\n\tname string\n\tpath string\n}\n\n\n\n\nfunc (t *terminateFile) Name() string {\n\treturn t.name\n}\n\n\nfunc (t *terminateFile) Path() string {\n\treturn t.path\n}\n\nfunc newTerminateFile(name string, path string) TerminateFile ", "output": "{\n\treturn &terminateFile{\n\t\tname: name,\n\t\tpath: path,\n\t}\n}"} {"input": "package gtk\n\n\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n\n\t\"github.com/untoldwind/amintk/gdk\"\n)\n\n\ntype Image struct {\n\tWidget\n}\n\n\nfunc ImageNew() *Image {\n\tc := C.gtk_image_new()\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\nfunc (v *Image) native() *C.GtkImage {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn (*C.GtkImage)(v.Native())\n}\n\n\nfunc ImageNewFromIconName(iconName string, size IconSize) *Image {\n\tcstr := C.CString(iconName)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_image_new_from_icon_name((*C.gchar)(cstr),\n\t\tC.GtkIconSize(size))\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\n\nfunc ImageNewFromPixbuf(pixbuf *gdk.Pixbuf) *Image {\n\tptr := (*C.GdkPixbuf)(pixbuf.Native())\n\tc := C.gtk_image_new_from_pixbuf(ptr)\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\nfunc wrapImage(p unsafe.Pointer) *Image {\n\tif widget := wrapWidget(p); widget != nil {\n\t\treturn &Image{Widget: *widget}\n\t}\n\treturn nil\n}\n\n\nfunc (v *Image) Clear() {\n\tC.gtk_image_clear(v.native())\n}\n\n\n\n\nfunc (v *Image) SetFromPixbuf(pixbuf *gdk.Pixbuf) ", "output": "{\n\tpbptr := (*C.GdkPixbuf)(pixbuf.Native())\n\tC.gtk_image_set_from_pixbuf(v.native(), pbptr)\n}"} {"input": "package channel\n\nimport (\n\t\"code.google.com/p/go.net/websocket\"\n)\n\ntype connection struct {\n\tws *websocket.Conn\n\n\tsend chan string\n}\n\n\n\nfunc (c *connection) writer() {\n\tfor message := range c.send {\n\t\terr := websocket.Message.Send(c.ws, message)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tc.ws.Close()\n}\n\nfunc (c *connection) reader() ", "output": "{\n\tfor {\n\t\tvar message string\n\t\terr := websocket.Message.Receive(c.ws, &message)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tc.ws.Close()\n}"} {"input": "package vfs\n\nimport (\n\t\"path\"\n\n\tgofig \"github.com/akutz/gofig/types\"\n\n\t\"github.com/codedellemc/rexray/libstorage/api/context\"\n\t\"github.com/codedellemc/rexray/libstorage/api/registry\"\n\t\"github.com/codedellemc/rexray/libstorage/api/types\"\n)\n\nconst (\n\tName = \"vfs\"\n)\n\n\n\n\nfunc RootDir(config gofig.Config) string {\n\treturn config.GetString(\"vfs.root\")\n}\n\n\nfunc DeviceFilePath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"dev\")\n}\n\n\nfunc VolumesDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"vol\")\n}\n\n\nfunc SnapshotsDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"snap\")\n}\n\nfunc init() ", "output": "{\n\tregistry.RegisterConfigReg(\n\t\t\"VFS\",\n\t\tfunc(ctx types.Context, r gofig.ConfigRegistration) {\n\t\t\tvfsRoot := path.Join(context.MustPathConfig(ctx).Lib, \"vfs\")\n\t\t\tr.Key(\n\t\t\t\tgofig.String,\n\t\t\t\t\"\",\n\t\t\t\tvfsRoot,\n\t\t\t\t\"\",\n\t\t\t\t\"vfs.root\")\n\t\t})\n}"} {"input": "package commands\n\nimport \"github.com/spf13/cobra\"\n\n\n\ntype Command struct {\n\t*cobra.Command\n\n\tDocCategories []string\n\n\tfmtCols []string\n\n\tchildCommands []*Command\n\tIsIndex bool\n}\n\n\n\n\n\nfunc (c *Command) ChildCommands() []*Command {\n\treturn c.childCommands\n}\n\nfunc (c *Command) AddCommand(commands ...*Command) ", "output": "{\n\tc.childCommands = append(c.childCommands, commands...)\n\tfor _, cmd := range commands {\n\t\tc.Command.AddCommand(cmd.Command)\n\t}\n}"} {"input": "package byte_tree\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/kentik/patricia\"\n)\n\n\n\n\nfunc (t *TreeV6) newNode(address patricia.IPv6Address, prefixLength uint) uint {\n\tavailCount := len(t.availableIndexes)\n\tif availCount > 0 {\n\t\tindex := t.availableIndexes[availCount-1]\n\t\tt.availableIndexes = t.availableIndexes[:availCount-1]\n\t\tt.nodes[index] = treeNodeV6{prefixLeft: address.Left, prefixRight: address.Right, prefixLength: prefixLength}\n\t\treturn index\n\t}\n\n\tt.nodes = append(t.nodes, treeNodeV6{prefixLeft: address.Left, prefixRight: address.Right, prefixLength: prefixLength})\n\treturn uint(len(t.nodes) - 1)\n}\n\n\n\nfunc (t *TreeV6) print() ", "output": "{\n\tbuf := make([]byte, 0)\n\tfor i := range t.nodes {\n\t\tbuf = buf[:0]\n\t\tfmt.Printf(\"%d: \\tleft: %d, right: %d, prefix: %032b %032b (%d), tags: (%d): %v\\n\", i, int(t.nodes[i].Left), int(t.nodes[i].Right), int(t.nodes[i].prefixLeft), int(t.nodes[i].prefixRight), int(t.nodes[i].prefixLength), t.nodes[i].TagCount, t.tagsForNode(buf, uint(i), nil))\n\t}\n}"} {"input": "package handlers\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/cloudfoundry-incubator/executor\"\n\t\"github.com/pivotal-golang/lager\"\n)\n\ntype CancelTaskHandler struct {\n\tlogger lager.Logger\n\texecutorClient executor.Client\n}\n\nfunc NewCancelTaskHandler(logger lager.Logger, executorClient executor.Client) *CancelTaskHandler {\n\treturn &CancelTaskHandler{\n\t\tlogger: logger,\n\t\texecutorClient: executorClient,\n\t}\n}\n\n\n\nfunc (h CancelTaskHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\ttaskGuid := r.FormValue(\":task_guid\")\n\n\tlogger := h.logger.Session(\"cancel-task\", lager.Data{\n\t\t\"instance-guid\": taskGuid,\n\t})\n\n\tw.WriteHeader(http.StatusAccepted)\n\n\tgo func() {\n\t\tlogger.Info(\"deleting-container\")\n\t\terr := h.executorClient.DeleteContainer(taskGuid)\n\t\tif err == executor.ErrContainerNotFound {\n\t\t\tlogger.Info(\"container-not-found\")\n\t\t\treturn\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlogger.Error(\"failed-deleting-container\", err)\n\t\t\treturn\n\t\t}\n\n\t\tlogger.Info(\"succeeded-deleting-container\")\n\t}()\n}"} {"input": "package parser\n\nimport (\n\t\"github.com/dop251/goja/ast\"\n)\n\ntype _scope struct {\n\touter *_scope\n\tallowIn bool\n\tinIteration bool\n\tinSwitch bool\n\tinFunction bool\n\tdeclarationList []ast.Declaration\n\n\tlabels []string\n}\n\n\n\nfunc (self *_parser) closeScope() {\n\tself.scope = self.scope.outer\n}\n\nfunc (self *_scope) declare(declaration ast.Declaration) {\n\tself.declarationList = append(self.declarationList, declaration)\n}\n\nfunc (self *_scope) hasLabel(name string) bool {\n\tfor _, label := range self.labels {\n\t\tif label == name {\n\t\t\treturn true\n\t\t}\n\t}\n\tif self.outer != nil && !self.inFunction {\n\t\treturn self.outer.hasLabel(name)\n\t}\n\treturn false\n}\n\nfunc (self *_parser) openScope() ", "output": "{\n\tself.scope = &_scope{\n\t\touter: self.scope,\n\t\tallowIn: true,\n\t}\n}"} {"input": "package chat\n\nimport (\n\t\"code.google.com/p/go.net/websocket\"\n\t\"log\"\n\t\"net/http\"\n)\n\ntype Server struct {\n\tclients []*Client\n\taddClient chan *Client\n\tremoveClient chan *Client\n\tsendAll chan *Message\n\tmessages []*Message\n}\n\n\n\n\n\nfunc (this *Server) Messages() []*Message {\n\tmsgs := make([]*Message, len(this.messages))\n\tcopy(msgs, this.messages)\n\treturn msgs\n}\n\n\nfunc (this *Server) Handler() http.Handler {\n\tgo func() {\n\t\tlog.Println(\"Listening server...\")\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase c := <-this.addClient:\n\t\t\t\tlog.Println(\"Added new client\")\n\t\t\t\tthis.clients = append(this.clients, c)\n\t\t\t\tfor _, msg := range this.messages {\n\t\t\t\t\tc.message <- msg\n\t\t\t\t}\n\t\t\t\tlog.Println(\"Now\", len(this.clients), \"clients connected.\")\n\n\t\t\tcase c := <-this.removeClient:\n\t\t\t\tlog.Println(\"Remove client\")\n\t\t\t\tfor i := range this.clients {\n\t\t\t\t\tif this.clients[i] == c {\n\t\t\t\t\t\tthis.clients = append(this.clients[:i], this.clients[i+1:]...)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tcase msg := <-this.sendAll:\n\t\t\t\tlog.Println(\"Send all:\", msg)\n\t\t\t\tthis.messages = append(this.messages, msg)\n\t\t\t\tfor _, c := range this.clients {\n\t\t\t\t\tc.message <- msg\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tonConnected := func(ws *websocket.Conn) {\n\t\tdefer ws.Close()\n\t\tclient := NewClient(ws, this)\n\t\tthis.addClient <- client\n\t\tclient.Listen()\n\t}\n\n\tlog.Println(\"Created handler\")\n\treturn websocket.Handler(onConnected)\n}\n\nfunc NewServer() *Server ", "output": "{\n\tclients := make([]*Client, 0)\n\taddClient := make(chan *Client)\n\tremoveClient := make(chan *Client)\n\tsendAll := make(chan *Message)\n\tmessages := make([]*Message, 0)\n\n\treturn &Server{clients, addClient, removeClient, sendAll, messages}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\n\n\nfunc associate(s string) string {\n\tif s == \"\" {\n\t\treturn s\n\t}\n\treturn s + \"2\" + s\n}\n\nfunc solve(s string) string {\n\tswitch {\n\tcase strings.Contains(s, \"0\"):\n\t\treturn \"\"\n\tcase s[0] == '3':\n\t\treturn associate(solve(s[1:]))\n\tcase len(s) > 1 && s[0] == '2':\n\t\treturn produce(s)\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\nfunc main() {\n\tin, _ := os.Open(\"743.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"743.out\")\n\tdefer out.Close()\n\n\tvar n int64\n\tfor {\n\t\tif fmt.Fscanf(in, \"%d\", &n); n == 0 {\n\t\t\tbreak\n\t\t}\n\t\tif s := solve(fmt.Sprint(n)); s != \"\" {\n\t\t\tfmt.Fprintln(out, s)\n\t\t} else {\n\t\t\tfmt.Fprintln(out, \"NOT ACCEPTABLE\")\n\t\t}\n\t}\n}\n\nfunc produce(s string) string ", "output": "{\n\tif s == \"2\" {\n\t\treturn s\n\t}\n\treturn s[1:]\n}"} {"input": "package mgorm\n\nimport (\n\t\"labix.org/v2/mgo/bson\"\n)\n\ntype IEmbeddedModel interface {\n\tIErrorHandler\n\tIValidator\n\tIEvent\n}\n\ntype IModel interface {\n\tIEmbeddedModel\n\tIsNew() bool\n\tGetId() bson.ObjectId\n\tAfterFind()\n\tBeforeSave() error\n\tAfterSave()\n\tCollectionName() string\n}\n\ntype EmbeddedModel struct {\n\tErrorHandler `bson:\",inline\" json:\"-\"`\n\tEvent `bson:\",inline\" json:\"-\"`\n}\n\nfunc (self *EmbeddedModel) Validate() bool {\n\tself.ClearErrors()\n\n\terr := self.Emit(\"BeforeValidate\")\n\tif nil != err {\n\t\tself.AddError(err.Error())\n\t\treturn false\n\t}\n\n\treturn true\n}\n\ntype Model struct {\n\tEmbeddedModel `bson:\",inline\" json:\"-\"`\n\tId bson.ObjectId `bson:\"_id\" json:\"id\"`\n\tisOld bool\n\tcollectionName string\n}\n\nfunc (self *Model) AfterFind() {\n\tself.Emit(\"AfterFind\")\n\tself.isOld = true\n}\n\nfunc (self *Model) BeforeSave() error {\n\tif self.IsNew() {\n\t\tself.Id = bson.NewObjectId()\n\t}\n\n\treturn self.Emit(\"BeforeSave\")\n}\n\n\n\nfunc (self *Model) GetId() bson.ObjectId {\n\treturn self.Id\n}\n\nfunc (self *Model) IsNew() bool {\n\treturn !self.isOld\n}\n\nfunc (self *Model) AfterSave() ", "output": "{\n\tself.Emit(\"AfterSave\")\n\tself.isOld = true\n}"} {"input": "package organization\n\nimport (\n\t\"cf/api\"\n\t\"cf/configuration\"\n\t\"cf/models\"\n\t\"cf/requirements\"\n\t\"cf/terminal\"\n\t\"github.com/codegangsta/cli\"\n)\n\ntype ListOrgs struct {\n\tui terminal.UI\n\tconfig configuration.Reader\n\torgRepo api.OrganizationRepository\n}\n\n\n\nfunc (cmd ListOrgs) GetRequirements(reqFactory requirements.Factory, c *cli.Context) (reqs []requirements.Requirement, err error) {\n\treqs = []requirements.Requirement{\n\t\treqFactory.NewLoginRequirement(),\n\t}\n\treturn\n}\n\nfunc (cmd ListOrgs) Run(c *cli.Context) {\n\tcmd.ui.Say(\"Getting orgs as %s...\\n\", terminal.EntityNameColor(cmd.config.Username()))\n\n\tnoOrgs := true\n\ttable := cmd.ui.Table([]string{\"name\"})\n\n\tapiStatus := cmd.orgRepo.ListOrgs(func(org models.Organization) bool {\n\t\ttable.Print([][]string{{org.Name}})\n\t\tnoOrgs = false\n\t\treturn true\n\t})\n\n\tif apiStatus.IsNotSuccessful() {\n\t\tcmd.ui.Failed(\"Failed fetching orgs.\\n%s\", apiStatus.Message)\n\t\treturn\n\t}\n\n\tif noOrgs {\n\t\tcmd.ui.Say(\"No orgs found\")\n\t}\n}\n\nfunc NewListOrgs(ui terminal.UI, config configuration.Reader, orgRepo api.OrganizationRepository) (cmd ListOrgs) ", "output": "{\n\tcmd.ui = ui\n\tcmd.config = config\n\tcmd.orgRepo = orgRepo\n\treturn\n}"} {"input": "package common\n\nimport (\n\t\"bytes\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n)\n\n\ntype Endpoint struct {\n\tHost string `json:\"host\"`\n\n\tPorts []ServicePort `json:\"ports\"`\n}\n\n\nfunc GetExternalEndpoints(service *api.Service) []Endpoint {\n\tvar externalEndpoints []Endpoint\n\tif service.Spec.Type == api.ServiceTypeLoadBalancer {\n\t\tfor _, ingress := range service.Status.LoadBalancer.Ingress {\n\t\t\texternalEndpoints = append(externalEndpoints, getExternalEndpoint(ingress, service.Spec.Ports))\n\t\t}\n\t}\n\n\tfor _, ip := range service.Spec.ExternalIPs {\n\t\texternalEndpoints = append(externalEndpoints, Endpoint{\n\t\t\tHost: ip,\n\t\t\tPorts: GetServicePorts(service.Spec.Ports),\n\t\t})\n\t}\n\n\treturn externalEndpoints\n}\n\n\n\nfunc GetInternalEndpoint(serviceName, namespace string, ports []api.ServicePort) Endpoint {\n\tname := serviceName\n\n\tif namespace != api.NamespaceDefault && len(namespace) > 0 && len(serviceName) > 0 {\n\t\tbufferName := bytes.NewBufferString(name)\n\t\tbufferName.WriteString(\".\")\n\t\tbufferName.WriteString(namespace)\n\t\tname = bufferName.String()\n\t}\n\n\treturn Endpoint{\n\t\tHost: name,\n\t\tPorts: GetServicePorts(ports),\n\t}\n}\n\n\nfunc getExternalEndpoint(ingress api.LoadBalancerIngress, ports []api.ServicePort) Endpoint {\n\tvar host string\n\tif ingress.Hostname != \"\" {\n\t\thost = ingress.Hostname\n\t} else {\n\t\thost = ingress.IP\n\t}\n\treturn Endpoint{\n\t\tHost: host,\n\t\tPorts: GetServicePorts(ports),\n\t}\n}\n\n\n\n\nfunc GetNodeByName(nodes []api.Node, nodeName string) *api.Node ", "output": "{\n\tfor _, node := range nodes {\n\t\tif node.ObjectMeta.Name == nodeName {\n\t\t\treturn &node\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype Message struct {\n\tExpire int64 `json:\"-\"`\n\tMsg string `json:\"msg\"`\n\tMsgID int64 `json:\"mid\"`\n\tGroupID int `json:\"gid\"`\n}\n\n\n\n\nfunc (m *Message) Bytes() ([]byte, error) ", "output": "{\n\tbyteJson, err := json.Marshal(m)\n\tif err != nil {\n\t\tLog.Error(\"json.Marshal(%v) error(%v)\", m, err)\n\t\treturn nil, err\n\t}\n\n\treturn byteJson, nil\n}"} {"input": "package wire\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\n\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max)\n\tif buf != nil {\n\t\tcopy(b, buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) ", "output": "{\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}"} {"input": "package cloudformation\n\n\n\ntype AWSOpsWorksLayer_LifecycleEventConfiguration struct {\n\n\tShutdownEventConfiguration *AWSOpsWorksLayer_ShutdownEventConfiguration `json:\"ShutdownEventConfiguration,omitempty\"`\n}\n\n\n\n\nfunc (r *AWSOpsWorksLayer_LifecycleEventConfiguration) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::OpsWorks::Layer.LifecycleEventConfiguration\"\n}"} {"input": "package eventhub\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) BaseClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient ", "output": "{\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package suite_init\n\ntype SuiteData struct {\n\t*StubsData\n\t*SynchronizedSuiteCallbacksData\n\t*WerfBinaryData\n\t*ProjectNameData\n\t*K8sDockerRegistryData\n\t*TmpDirData\n\t*ContainerRegistryPerImplementationData\n}\n\nfunc (data *SuiteData) SetupStubs(setupData *StubsData) bool {\n\tdata.StubsData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupSynchronizedSuiteCallbacks(setupData *SynchronizedSuiteCallbacksData) bool {\n\tdata.SynchronizedSuiteCallbacksData = setupData\n\treturn true\n}\n\n\n\nfunc (data *SuiteData) SetupProjectName(setupData *ProjectNameData) bool {\n\tdata.ProjectNameData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupK8sDockerRegistry(setupData *K8sDockerRegistryData) bool {\n\tdata.K8sDockerRegistryData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupTmp(setupData *TmpDirData) bool {\n\tdata.TmpDirData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupContainerRegistryPerImplementation(setupData *ContainerRegistryPerImplementationData) bool {\n\tdata.ContainerRegistryPerImplementationData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupWerfBinary(setupData *WerfBinaryData) bool ", "output": "{\n\tdata.WerfBinaryData = setupData\n\treturn true\n}"} {"input": "package client_test\n\nimport (\n\t\"github.com/jdextraze/go-gesclient/client\"\n\t\"testing\"\n)\n\n\n\nfunc TestStreamDeleted_Error(t *testing.T) {\n\tif client.StreamDeleted.Error() != \"Stream deleted\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestInvalidTransaction_Error(t *testing.T) {\n\tif client.InvalidTransaction.Error() != \"Invalid transaction\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestAccessDenied_Error(t *testing.T) {\n\tif client.AccessDenied.Error() != \"Access denied\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestAuthenticationError_Error(t *testing.T) {\n\tif client.AuthenticationError.Error() != \"Authentication error\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestBadRequest_Error(t *testing.T) {\n\tif client.BadRequest.Error() != \"Bad request\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestServerError_Error(t *testing.T) {\n\terr := client.NewServerError(\"\")\n\tif err.Error() != \"Unexpected error on server: \" {\n\t\tt.FailNow()\n\t}\n\n\terr = client.NewServerError(\"test\")\n\tif err.Error() != \"Unexpected error on server: test\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestNotModified_Error(t *testing.T) {\n\terr := client.NewNotModified(\"test\")\n\tif err.Error() != \"Stream not modified: test\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestWrongExpectedVersion_Error(t *testing.T) ", "output": "{\n\tif client.WrongExpectedVersion.Error() != \"Wrong expected version\" {\n\t\tt.FailNow()\n\t}\n}"} {"input": "package openssl\n\n\nimport \"C\"\n\nimport (\n\t\"errors\"\n\t\"runtime\"\n\t\"unsafe\"\n)\n\ntype DH struct {\n\tdh *C.struct_dh_st\n}\n\n\n\nfunc LoadDHParametersFromPEM(pem_block []byte) (*DH, error) {\n\tif len(pem_block) == 0 {\n\t\treturn nil, errors.New(\"empty pem block\")\n\t}\n\tbio := C.BIO_new_mem_buf(unsafe.Pointer(&pem_block[0]),\n\t\tC.int(len(pem_block)))\n\tif bio == nil {\n\t\treturn nil, errors.New(\"failed creating bio\")\n\t}\n\tdefer C.BIO_free(bio)\n\n\tparams := C.PEM_read_bio_DHparams(bio, nil, nil, nil)\n\tif params == nil {\n\t\treturn nil, errors.New(\"failed reading dh parameters\")\n\t}\n\tdhparams := &DH{dh: params}\n\truntime.SetFinalizer(dhparams, func(dhparams *DH) {\n\t\tC.DH_free(dhparams.dh)\n\t})\n\treturn dhparams, nil\n}\n\n\n\n\n\nfunc (c *Ctx) SetDHParameters(dh *DH) error ", "output": "{\n\truntime.LockOSThread()\n\tdefer runtime.UnlockOSThread()\n\n\tif int(C.X_SSL_CTX_set_tmp_dh(c.ctx, dh.dh)) != 1 {\n\t\treturn errorFromErrorQueue()\n\t}\n\treturn nil\n}"} {"input": "package user\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n\ntype RangeList []*Range\n\n\nfunc ParseRangeList(str string) (*RangeList, error) {\n\trl := RangeList{}\n\tif len(str) == 0 {\n\t\treturn &rl, nil\n\t}\n\tparts := strings.Split(str, \",\")\n\tfor _, p := range parts {\n\t\tr, err := ParseRange(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trl = append(rl, r)\n\t}\n\treturn &rl, nil\n}\n\n\nfunc (l *RangeList) Empty() bool {\n\tif len(*l) == 0 {\n\t\treturn true\n\t}\n\tfor _, r := range *l {\n\t\tif !r.Empty() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (l *RangeList) Contains(uid int) bool {\n\tfor _, r := range *l {\n\t\tif r.Contains(uid) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (l *RangeList) Type() string {\n\treturn \"user.RangeList\"\n}\n\n\nfunc (l *RangeList) Set(value string) error {\n\tnewRangeList, err := ParseRangeList(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*l = *newRangeList\n\treturn nil\n}\n\n\n\n\n\n\nfunc IsUserAllowed(user string, allowed *RangeList) bool {\n\tuid, err := strconv.Atoi(user)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn allowed.Contains(uid)\n}\n\nfunc (l *RangeList) String() string ", "output": "{\n\trangeStrings := []string{}\n\tfor _, r := range *l {\n\t\trangeStrings = append(rangeStrings, r.String())\n\t}\n\treturn strings.Join(rangeStrings, \",\")\n}"} {"input": "package safepackets\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\n\t\"github.com/mark-rushakoff/go_tftpd/packets\"\n)\n\ntype SafeError struct {\n\tCode packets.ErrorCode\n\tMessage string\n}\n\n\n\nfunc NewAccessViolationError(message string) *SafeError {\n\treturn &SafeError{\n\t\tCode: packets.AccessViolation,\n\t\tMessage: message,\n\t}\n}\n\nfunc NewAncientAckError() *SafeError {\n\treturn &SafeError{\n\t\tCode: packets.Undefined,\n\t\tMessage: \"Received unexpectedly old Ack\",\n\t}\n}\n\nfunc (e *SafeError) Equals(other *SafeError) bool {\n\treturn e.Code == other.Code && e.Message == other.Message\n}\n\nfunc (e *SafeError) Bytes() []byte {\n\tbuf := &bytes.Buffer{}\n\tbinary.Write(buf, binary.BigEndian, packets.ErrorOpcode)\n\tbinary.Write(buf, binary.BigEndian, e.Code)\n\tbuf.WriteString(e.Message)\n\tbuf.WriteByte(0)\n\treturn buf.Bytes()\n}\n\nfunc NewFileNotFoundError() *SafeError ", "output": "{\n\treturn &SafeError{\n\t\tCode: packets.FileNotFound,\n\t\tMessage: \"File not found\",\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/user\"\n\t\"strconv\"\n)\n\nfunc CreateVcapDirs(paths []string, userName string, groupName string) error {\n\terr := mkdir(paths)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = chown(paths, userName, groupName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc mkdir(paths []string) error {\n\tfor _, path := range paths {\n\t\terr := os.MkdirAll(path, os.ModePerm)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Make directory failed: %s\\n\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc chown(paths []string, userName string, groupName string) error {\n\tuserId, err := GetUserId(userName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgroupId, err := getGroupId(groupName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, path := range paths {\n\t\terr := os.Chown(path, userId, groupId)\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Chown failed: %s\\n\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc getGroupId(groupName string) (int, error) {\n\tg, err := user.LookupGroup(groupName)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to obtain GID: %s\\n\", err)\n\t\treturn -1, err\n\t}\n\n\tgroupId, _ := strconv.Atoi(g.Gid)\n\n\treturn groupId, nil\n}\n\nfunc GetUserId(userName string) (int, error) ", "output": "{\n\tu, err := user.Lookup(userName)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to obtain UID: %s\\n\", err)\n\t\treturn -1, err\n\t}\n\n\tuserId, _ := strconv.Atoi(u.Uid)\n\n\treturn userId, nil\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n)\n\nfunc Client(hostPort string) {\n\tlog.Println(\"falcon-client connecting to %s\\n\", hostPort)\n\n\taddress, err := net.ResolveTCPAddr(\"tcp\", hostPort)\n\thandleError(err)\n\n\tconn, err := net.DialTCP(\"tcp\", nil, address)\n\thandleError(err)\n\n\tmessage := \"hello world\"\n\trequest := []byte(fmt.Sprintf(\"request: %s\\n\", message))\n\tconn.Write(request)\n\n\tvar buf [512]byte\n\n\tn, err := conn.Read(buf[0:])\n\thandleError(err)\n\n\tresponse := buf[0:n]\n\tlog.Println(string(response))\n\n\tconn.Write(response[0:])\n}\n\n\n\nfunc handleError(err error) ", "output": "{\n\tif err != nil {\n\t\tlog.Println(\"error while bootstrapping. abort. %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n}"} {"input": "package alertsv2\n\nimport \"net/url\"\n\ntype DeleteAlertRequest struct {\n\t*Identifier\n\tUser string\n\tSource string\n\tApiKey string\n}\n\n\n\nfunc (r *DeleteAlertRequest) GenerateUrl() (string, url.Values, error) {\n\tpath, params, err := r.Identifier.GenerateUrl()\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tif r.User != \"\" {\n\t\tparams.Add(\"user\", r.User)\n\t}\n\n\tif r.Source != \"\" {\n\t\tparams.Add(\"source\", r.Source)\n\t}\n\n\treturn path, params, err\n}\n\nfunc (r *DeleteAlertRequest) GetApiKey() string ", "output": "{\n\treturn r.ApiKey\n}"} {"input": "package node\n\nimport (\n\t\"os\"\n\n\t\"github.com/cilium/cilium/pkg/logging/logfields\"\n)\n\nvar (\n\tnodeName = \"localhost\"\n)\n\n\n\n\n\n\n\nfunc SetName(name string) {\n\tnodeName = name\n}\n\n\n\n\n\n\nfunc init() {\n\tif h, err := os.Hostname(); err != nil {\n\t\tlog.WithError(err).Warn(\"Unable to retrieve local hostname\")\n\t} else {\n\t\tlog.WithField(logfields.NodeName, h).Debug(\"os.Hostname() returned\")\n\t\tnodeName = h\n\t}\n}\n\nfunc GetName() string ", "output": "{\n\treturn nodeName\n}"} {"input": "package vsphere\n\nimport (\n\t\"github.com/juju/juju/environs\"\n\t\"github.com/juju/juju/storage/provider/registry\"\n)\n\nconst (\n\tproviderType = \"vsphere\"\n)\n\n\n\nfunc init() ", "output": "{\n\tenvirons.RegisterProvider(providerType, providerInstance)\n\tregistry.RegisterEnvironStorageProviders(providerType)\n}"} {"input": "package kubemark\n\nimport (\n\t\"time\"\n\n\tproxyapp \"k8s.io/kubernetes/cmd/kube-proxy/app\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/client/record\"\n\tclient \"k8s.io/kubernetes/pkg/client/unversioned\"\n\tproxyconfig \"k8s.io/kubernetes/pkg/proxy/config\"\n\t\"k8s.io/kubernetes/pkg/types\"\n\tutiliptables \"k8s.io/kubernetes/pkg/util/iptables\"\n\n\t\"github.com/golang/glog\"\n)\n\ntype HollowProxy struct {\n\tProxyServer *proxyapp.ProxyServer\n}\n\ntype FakeProxyHandler struct{}\n\nfunc (*FakeProxyHandler) OnServiceUpdate(services []api.Service) {}\nfunc (*FakeProxyHandler) OnEndpointsUpdate(endpoints []api.Endpoints) {}\n\ntype FakeProxier struct{}\n\nfunc (*FakeProxier) OnServiceUpdate(services []api.Service) {}\nfunc (*FakeProxier) Sync() {}\nfunc (*FakeProxier) SyncLoop() {\n\tselect {}\n}\n\n\n\nfunc (hp *HollowProxy) Run() {\n\tif err := hp.ProxyServer.Run(make([]string, 0)); err != nil {\n\t\tglog.Fatalf(\"Error while running proxy: %v\\n\", err)\n\t}\n}\n\nfunc NewHollowProxyOrDie(\n\tnodeName string,\n\tclient *client.Client,\n\tendpointsConfig *proxyconfig.EndpointsConfig,\n\tserviceConfig *proxyconfig.ServiceConfig,\n\tiptInterface utiliptables.Interface,\n\tbroadcaster record.EventBroadcaster,\n\trecorder record.EventRecorder,\n) *HollowProxy ", "output": "{\n\tconfig := proxyapp.NewProxyConfig()\n\tconfig.OOMScoreAdj = 0\n\tconfig.ResourceContainer = \"\"\n\tconfig.NodeRef = &api.ObjectReference{\n\t\tKind: \"Node\",\n\t\tName: nodeName,\n\t\tUID: types.UID(nodeName),\n\t\tNamespace: \"\",\n\t}\n\tproxyconfig.NewSourceAPI(\n\t\tclient,\n\t\t30*time.Second,\n\t\tserviceConfig.Channel(\"api\"),\n\t\tendpointsConfig.Channel(\"api\"),\n\t)\n\n\thollowProxy, err := proxyapp.NewProxyServer(client, config, iptInterface, &FakeProxier{}, broadcaster, recorder, nil)\n\tif err != nil {\n\t\tglog.Fatalf(\"Error while creating ProxyServer: %v\\n\", err)\n\t}\n\treturn &HollowProxy{\n\t\tProxyServer: hollowProxy,\n\t}\n}"} {"input": "package github\n\nimport (\n\t\"sync\"\n\n\t\"k8s.io/kubernetes/pkg/util/sets\"\n)\n\n\ntype StatusChange struct {\n\theads map[int]string \n\tpullRequests map[string]sets.Int \n\tchanged sets.String \n\tmutex sync.Mutex\n}\n\n\nfunc NewStatusChange() *StatusChange {\n\treturn &StatusChange{\n\t\theads: map[int]string{},\n\t\tpullRequests: map[string]sets.Int{},\n\t\tchanged: sets.NewString(),\n\t}\n}\n\n\nfunc (s *StatusChange) UpdatePullRequestHead(pullRequestID int, newHead string) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tif oldHead, has := s.heads[pullRequestID]; has {\n\t\tdelete(s.pullRequests, oldHead)\n\t}\n\ts.heads[pullRequestID] = newHead\n\tif _, has := s.pullRequests[newHead]; !has {\n\t\ts.pullRequests[newHead] = sets.NewInt()\n\t}\n\ts.pullRequests[newHead].Insert(pullRequestID)\n}\n\n\n\n\n\nfunc (s *StatusChange) PopChangedPullRequests() []int {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tchangedPullRequests := sets.NewInt()\n\tfor _, commit := range s.changed.List() {\n\t\tif pullRequests, has := s.pullRequests[commit]; has {\n\t\t\tchangedPullRequests = changedPullRequests.Union(pullRequests)\n\t\t}\n\t}\n\ts.changed = sets.NewString()\n\n\treturn changedPullRequests.List()\n}\n\nfunc (s *StatusChange) CommitStatusChanged(commit string) ", "output": "{\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\ts.changed.Insert(commit)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Cpu struct {\n\tSeconds time.Duration \n}\n\nfunc newCpu(p Packet) (Action, error) {\n\tc := Cpu{}\n\n\tif p.Cmd != \"cpu\" {\n\t\treturn c, fmt.Errorf(\"wrong command for type MemUp\")\n\t}\n\n\ti, err := strconv.Atoi(p.Arg)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\n\tif i < 1 {\n\t\treturn c, fmt.Errorf(\"cpu seconds argument must be greater than 0\")\n\t}\n\n\tc.Seconds = time.Duration(i) * time.Second\n\n\treturn c, nil\n}\n\nfunc fact(n int) int {\n\tif n == 0 {\n\t\treturn 1\n\t}\n\treturn n * fact(n-1)\n}\n\n\n\nfunc (c Cpu) act(dng *danger) error ", "output": "{\n\n\tncpus := runtime.GOMAXPROCS(-1)\n\tngos := 4 * ncpus\n\n\tdone := make(chan struct{})\n\tdefer close(done)\n\n\tburner := func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tfor j := 0; j < 100000; j++ {\n\t\t\t\t\tfor i := range []int{1, 2, 3, 4, 5, 6, 7, 8} {\n\t\t\t\t\t\tfact(i)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := 0; i < ngos; i++ {\n\t\tgo burner()\n\t}\n\n\ttime.Sleep(c.Seconds)\n\treturn nil\n}"} {"input": "package runtime_test\n\nimport (\n\t\"runtime\"\n\t\"sync\"\n\t\"testing\"\n)\n\ntype response struct {\n}\n\ntype myError struct {\n}\n\nfunc (myError) Error() string { return \"\" }\n\n\n\nfunc TestChanSendSelectBarrier(t *testing.T) {\n\ttestChanSendBarrier(true)\n}\n\nfunc TestChanSendBarrier(t *testing.T) {\n\ttestChanSendBarrier(false)\n}\n\nfunc testChanSendBarrier(useSelect bool) {\n\tvar wg sync.WaitGroup\n\tvar globalMu sync.Mutex\n\touter := 100\n\tinner := 100000\n\tif testing.Short() {\n\t\touter = 10\n\t\tinner = 1000\n\t}\n\tfor i := 0; i < outer; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tvar garbage []byte\n\t\t\tfor j := 0; j < inner; j++ {\n\t\t\t\t_, err := doRequest(useSelect)\n\t\t\t\t_, ok := err.(myError)\n\t\t\t\tif !ok {\n\t\t\t\t\tpanic(1)\n\t\t\t\t}\n\t\t\t\tgarbage = make([]byte, 1<<10)\n\t\t\t}\n\t\t\tglobalMu.Lock()\n\t\t\tglobal = garbage\n\t\t\tglobalMu.Unlock()\n\t\t}()\n\t}\n\twg.Wait()\n}\n\nfunc doRequest(useSelect bool) (*response, error) ", "output": "{\n\ttype async struct {\n\t\tresp *response\n\t\terr error\n\t}\n\tch := make(chan *async, 0)\n\tdone := make(chan struct{}, 0)\n\n\tif useSelect {\n\t\tgo func() {\n\t\t\tselect {\n\t\t\tcase ch <- &async{resp: nil, err: myError{}}:\n\t\t\tcase <-done:\n\t\t\t}\n\t\t}()\n\t} else {\n\t\tgo func() {\n\t\t\tch <- &async{resp: nil, err: myError{}}\n\t\t}()\n\t}\n\n\tr := <-ch\n\truntime.Gosched()\n\treturn r.resp, r.err\n}"} {"input": "package blanket_emulator\n\nimport (\n\t\"fmt\"\n)\n\ntype Event interface {\n\tHash() uint64\n\tInspect() string\n}\n\ntype ReturnEvent uint64\ntype ReadEvent uint64\ntype WriteEvent struct {\n\tAddr uint64\n\tValue uint64\n}\ntype SyscallEvent uint64\ntype InvalidInstructionEvent uint64\n\n\n\nfunc (s WriteEvent) Hash() uint64 {\n\treturn WriteEventHash(s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Hash() uint64 {\n\treturn SysEventHash(uint64(s))\n}\n\nfunc (s ReturnEvent) Hash() uint64 {\n\treturn ReturnEventHash(uint64(s))\n}\n\nfunc (s InvalidInstructionEvent) Hash() uint64 {\n\treturn InvalidInstructionEventHash(uint64(s))\n}\n\nfunc (addr ReadEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Read([%x])\", addr)\n}\n\nfunc (addr ReturnEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Return([%x])\", addr)\n}\n\nfunc (s WriteEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Write([%x]=%x)\", s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Sys(%x)\", s)\n}\n\nfunc (s InvalidInstructionEvent) Inspect() string {\n\treturn fmt.Sprintf(\"InvalidOpcode([%x])\", s)\n}\n\nfunc (addr ReadEvent) Hash() uint64 ", "output": "{\n\treturn ReadEventHash(uint64(addr))\n}"} {"input": "package core\n\nimport (\n\t. \"github.com/smartystreets/goconvey/convey\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestValidateSymbol(t *testing.T) {\n\tConvey(\"Given a node name validation function\", t, func() {\n\t\tcases := []struct {\n\t\t\ttitle string\n\t\t\tname string\n\t\t\tsuccess bool\n\t\t}{\n\t\t\t{\"an empty string\", \"\", false},\n\t\t\t{\"one alphabet name\", \"a\", true},\n\t\t\t{\"one digit name\", \"0\", false},\n\t\t\t{\"one underscore name\", \"_\", false},\n\t\t\t{\"a name starting from a digit\", \"0test\", false},\n\t\t\t{\"a name starting from an underscore\", \"_test\", false},\n\t\t\t{\"a name only containing alphabet\", \"test\", true},\n\t\t\t{\"a name containing alphabet-digit\", \"t1e2s3t4\", true},\n\t\t\t{\"a name containing alphabet-digit-underscore\", \"t1e2_s3t4\", true},\n\t\t\t{\"a name containing an invalid letter\", \"da-me\", false},\n\t\t\t{\"a name has maximum length\", strings.Repeat(\"a\", 127), true},\n\t\t\t{\"a name longer than the maximum length\", strings.Repeat(\"a\", 128), false},\n\t\t\t{\"a reserved word\", \"UNTIL\", false},\n\t\t\t{\"a reserved word with different capitalization\", \"vaLIdaTE\", false},\n\t\t}\n\n\t\tfor _, c := range cases {\n\t\t\tc := c\n\n\t\t\tConvey(\"When validating \"+c.title, func() {\n\t\t\t\tif c.success {\n\t\t\t\t\tConvey(\"Then it should succeed\", func() {\n\t\t\t\t\t\tSo(ValidateSymbol(c.name), ShouldBeNil)\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tConvey(\"Then it should fail\", func() {\n\t\t\t\t\t\tSo(ValidateSymbol(c.name), ShouldNotBeNil)\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})\n}\n\n\n\nfunc TestValidateCapacity(t *testing.T) ", "output": "{\n\tConvey(\"Given validateCapacity function\", t, func() {\n\t\tConvey(\"When passing a valid value to it\", func() {\n\t\t\tConvey(\"Then it should accept 0\", func() {\n\t\t\t\tSo(validateCapacity(0), ShouldBeNil)\n\t\t\t})\n\n\t\t\tConvey(\"Then it should accept a maximum value\", func() {\n\t\t\t\tSo(validateCapacity(MaxCapacity), ShouldBeNil)\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"When passing a too large value\", func() {\n\t\t\tConvey(\"Then it should fail\", func() {\n\t\t\t\tSo(validateCapacity(MaxCapacity+1), ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"When passing a negative value\", func() {\n\t\t\tConvey(\"Then it should fail\", func() {\n\t\t\t\tSo(validateCapacity(-1), ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package spool_test\n\nimport (\n\t\"io\"\n\t\"net\"\n\n\t\"github.com/juju/errors\"\n)\n\n\n\nfunc dial(socketPath string) (io.ReadCloser, error) ", "output": "{\n\tconn, err := net.Dial(\"unix\", socketPath)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treturn conn, nil\n}"} {"input": "package menu\n\nimport \"fmt\"\n\ntype MenuFunc func()\n\n\ntype MenuEntry struct {\n\tMenuText string\n\tMenuSelector int\n\tMenuFunction MenuFunc\n\tStopRunning bool\n}\n\n\nfunc (entry MenuEntry) PrintEntry() {\n\tfmt.Printf(\"%d - %v\\n\", entry.MenuSelector, entry.MenuText)\n}\n\n\n\n\nfunc (entry MenuEntry) IsSelected(selector int) bool ", "output": "{\n\treturn entry.MenuSelector == selector\n}"} {"input": "package golang\n\nimport (\n\t\"bldy.build/build/executor\"\n\t\"bldy.build/build/label\"\n)\n\ntype Go struct {\n\tname string `group:\"name\"`\n\tdependencies []label.Label `group:\"deps\"`\n}\n\nfunc (g *Go) Name() string {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Dependencies() []label.Label {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Outputs() []string {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Hash() []byte {\n\tpanic(\"not implemented\")\n}\n\n\n\nfunc (g *Go) Build(*executor.Executor) error ", "output": "{\n\tpanic(\"not implemented\")\n}"} {"input": "package opts\n\n\ntype CreateOption func(*CreateConfig)\n\n\n\ntype CreateConfig struct {\n\tOptions map[string]string\n\tLabels map[string]string\n\tReference string\n}\n\n\n\nfunc WithCreateLabels(labels map[string]string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Labels = labels\n\t}\n}\n\n\n\n\n\n\n\n\nfunc WithCreateReference(ref string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Reference = ref\n\t}\n}\n\n\n\ntype GetConfig struct {\n\tDriver string\n\tReference string\n\tResolveStatus bool\n}\n\n\ntype GetOption func(*GetConfig)\n\n\n\n\n\nfunc WithGetDriver(name string) GetOption {\n\treturn func(o *GetConfig) {\n\t\to.Driver = name\n\t}\n}\n\n\n\nfunc WithGetReference(ref string) GetOption {\n\treturn func(o *GetConfig) {\n\t\to.Reference = ref\n\t}\n}\n\n\n\nfunc WithGetResolveStatus(cfg *GetConfig) {\n\tcfg.ResolveStatus = true\n}\n\n\ntype RemoveConfig struct {\n\tPurgeOnError bool\n}\n\n\ntype RemoveOption func(*RemoveConfig)\n\n\n\n\nfunc WithPurgeOnError(b bool) RemoveOption {\n\treturn func(o *RemoveConfig) {\n\t\to.PurgeOnError = b\n\t}\n}\n\nfunc WithCreateOptions(opts map[string]string) CreateOption ", "output": "{\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Options = opts\n\t}\n}"} {"input": "package fake_command_runner_matchers\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n\n\t\"github.com/cloudfoundry/gunk/command_runner/fake_command_runner\"\n)\n\nfunc HaveKilled(spec fake_command_runner.CommandSpec) *HaveKilledMatcher {\n\treturn &HaveKilledMatcher{Spec: spec}\n}\n\ntype HaveKilledMatcher struct {\n\tSpec fake_command_runner.CommandSpec\n\tkilled []*exec.Cmd\n}\n\nfunc (m *HaveKilledMatcher) Match(actual interface{}) (bool, error) {\n\trunner, ok := actual.(*fake_command_runner.FakeCommandRunner)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"Not a fake command runner: %#v.\", actual)\n\t}\n\n\tm.killed = runner.KilledCommands()\n\n\tmatched := false\n\tfor _, cmd := range m.killed {\n\t\tif m.Spec.Matches(cmd) {\n\t\t\tmatched = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif matched {\n\t\treturn true, nil\n\t} else {\n\t\treturn false, nil\n\t}\n}\n\nfunc (m *HaveKilledMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn fmt.Sprintf(\"Expected to kill:%s\\n\\nActually killed:%s\", prettySpec(m.Spec), prettyCommands(m.killed))\n}\n\n\n\nfunc (m *HaveKilledMatcher) NegatedFailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn fmt.Sprintf(\"Expected to not kill the following commands:%s\", prettySpec(m.Spec))\n}"} {"input": "package utils\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/mitchellh/go-homedir\"\n\t\"github.com/spf13/viper\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n)\n\nconst (\n\tKEY_ORG_ID string = \"orgId\"\n\tKEY_TOKEN string = \"authToken\"\n\tKEY_URI string = \"uri\"\n\tKEY_DEBUG string = \"debug_mode\"\n\tKEY_FORMAT string = \"format\"\n\tCONFIG_FILE_NAME string = \".anypoint-cli\"\n)\n\n\n\nfunc WriteConfig() ", "output": "{\n\tDebug(func() {\n\t\tmaps := viper.AllSettings()\n\t\tfmt.Printf(\"All settings %s\\n\", maps)\n\t})\n\n\tfileName := viper.ConfigFileUsed()\n\n\tif fileName == \"\" {\n\t\thome, err := homedir.Dir()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif home[len(home)-1] != os.PathSeparator {\n\t\t\thome += string(os.PathSeparator)\n\t\t}\n\n\t\tfileName = home + CONFIG_FILE_NAME + \".json\"\n\t}\n\n\tsettings := viper.AllSettings()\n\tdelete(settings, KEY_DEBUG)\n\n\tfileContent, err := json.MarshalIndent(settings, \" \", \"\\t\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while saving configuration file %s : %s\", fileName, err)\n\t}\n\n\tioutil.WriteFile(fileName, fileContent, 755)\n\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n\t\"runtime\"\n\n\t\"github.com/fatih/color\"\n\t\"github.com/ssddanbrown/haste/engine\"\n\t\"github.com/ssddanbrown/haste/options\"\n\t\"github.com/ssddanbrown/haste/server\"\n)\n\nfunc main() {\n\n\topts := options.NewOptions()\n\terr := opts.ParseCommandFlags()\n\topts.LoadFileResolver()\n\tcheck(err)\n\n\tmanager := engine.NewManager(opts)\n\n\tmanager.BuildAll()\n\n\tif opts.Watch {\n\t\tstartWatcher(manager, opts)\n\t}\n\n}\n\nfunc startWatcher(m *engine.Manager, opts *options.Options) {\n\tser := server.NewServer(m, opts)\n\tser.AddWatchedFolder(opts.RootPath)\n\n\tcolor.Green(fmt.Sprintf(\"Server started at http://localhost:%d\", opts.ServerPort))\n\n\terr := ser.Listen()\n\tcheck(err)\n}\n\n\n\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc openWebPage(url string) error ", "output": "{\n\tvar err error\n\n\tswitch runtime.GOOS {\n\tcase \"linux\":\n\t\tfmt.Println(url)\n\t\terr = exec.Command(\"xdg-open\", url).Run()\n\tcase \"windows\", \"darwin\":\n\t\terr = exec.Command(\"rundll32\", \"url.dll,FileProtocolHandler\", url).Run()\n\tdefault:\n\t\terr = fmt.Errorf(\"unsupported platform\")\n\t}\n\treturn err\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/ant0ine/go-json-rest/rest\"\n\n\t\"github.com/pdxjohnny/s/api\"\n\t\"github.com/pdxjohnny/s/variables\"\n)\n\n\n\n\n\nfunc PostAccount(w rest.ResponseWriter, r *rest.Request) {\n\tvar recvDoc map[string]interface{}\n\tid := r.PathParam(\"id\")\n\terr := r.DecodeJsonPayload(&recvDoc)\n\tif err != nil {\n\t\trest.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdoc, err := api.SaveAccount(variables.ServiceDBURL, r.Env[\"JWT_RAW\"].(string), id, recvDoc)\n\tif err != nil {\n\t\trest.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tif doc == nil {\n\t\tw.(http.ResponseWriter).Write(variables.BlankResponse)\n\t\treturn\n\t}\n\tw.WriteJson(doc)\n}\n\nfunc GetAccount(w rest.ResponseWriter, r *rest.Request) ", "output": "{\n\tid := r.PathParam(\"id\")\n\tdoc, err := api.GetAccount(variables.ServiceDBURL, r.Env[\"JWT_RAW\"].(string), id)\n\tif err != nil {\n\t\trest.Error(w, err.Error(), http.StatusNotFound)\n\t\treturn\n\t}\n\tif doc == nil {\n\t\tw.(http.ResponseWriter).Write(variables.BlankResponse)\n\t\treturn\n\t}\n\tw.WriteJson(doc)\n}"} {"input": "package main\n\nimport \"fmt\"\nimport \"sort\"\n\ntype ByLength []string\n\nfunc (s ByLength) Len() int {\n return len(s)\n}\n\nfunc (s ByLength) Swap(i, j int) {\n s[i], s[j] = s[j], s[i]\n}\n\n\n\nfunc main() {\n fruits := []string{\"peach\", \"banana\", \"kiwi\"}\n sort.Sort(ByLength(fruits))\n fmt.Println(fruits)\n}\n\nfunc (s ByLength) Less(i, j int) bool ", "output": "{\n return len(s[i]) < len(s[j])\n}"} {"input": "package action\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n)\n\ntype kvRead struct {\n\trecurse bool\n\n\t*config\n}\n\n\n\nfunc (k *kvRead) CommandFlags() *flag.FlagSet {\n\tf := k.newFlagSet(FLAG_DATACENTER, FLAG_KVOUTPUT, FLAG_CONSISTENCY, FLAG_BLOCKING)\n\n\tf.BoolVar(&k.recurse, \"recurse\", false, \"Perform a recursive read\")\n\n\treturn f\n}\n\nfunc (k *kvRead) Run(args []string) error {\n\tif len(args) != 1 {\n\t\treturn fmt.Errorf(\"A single key path must be specified\")\n\t}\n\tpath := args[0]\n\n\tclient, err := k.newKv()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tqueryOpts := k.queryOptions()\n\n\tif k.recurse {\n\t\tkvlist, _, err := client.List(path, queryOpts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif kvlist == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn k.OutputKv(kvlist)\n\t} else {\n\t\tkv, _, err := client.Get(path, queryOpts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif kv == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn k.OutputKv(kv)\n\t}\n}\n\nfunc KvReadAction() Action ", "output": "{\n\treturn &kvRead{\n\t\tconfig: &gConfig,\n\t}\n}"} {"input": "package driver\n\nimport \"database/sql/driver\"\n\nvar _ driver.Result = result{}\n\n\n\ntype result struct {\n\tlastInsertID int64\n\trowsAffected int64\n}\n\nfunc (r result) LastInsertId() (int64, error) {\n\treturn r.lastInsertID, nil\n}\n\n\n\nfunc (r result) RowsAffected() (int64, error) ", "output": "{\n\treturn r.rowsAffected, nil\n}"} {"input": "package http\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc isCtl(c rune) bool { return c <= 31 || c == 127 }\n\nfunc isSeparator(c rune) bool {\n\tswitch c {\n\tcase '(', ')', '<', '>', '@', ',', ';', ':', '\\\\', '\"', '/', '[', ']', '?', '=', '{', '}', ' ', '\\t':\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc TestIsToken(t *testing.T) {\n\tfor i := 0; i <= 130; i++ {\n\t\tr := rune(i)\n\t\texpected := isChar(r) && !isCtl(r) && !isSeparator(r)\n\t\tif isToken(r) != expected {\n\t\t\tt.Errorf(\"isToken(0x%x) = %v\", r, !expected)\n\t\t}\n\t}\n}\n\nfunc isChar(c rune) bool ", "output": "{ return c <= 127 }"} {"input": "package rtcp\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\n\ntype RapidResynchronizationRequest struct {\n\tSenderSSRC uint32\n\n\tMediaSSRC uint32\n}\n\nconst (\n\trrrLength = 2\n\trrrHeaderLength = ssrcLength * 2\n\trrrMediaOffset = 4\n)\n\n\n\n\n\nfunc (p *RapidResynchronizationRequest) Unmarshal(rawPacket []byte) error {\n\n\tif len(rawPacket) < (headerLength + (ssrcLength * 2)) {\n\t\treturn errPacketTooShort\n\t}\n\n\tvar h Header\n\tif err := h.Unmarshal(rawPacket); err != nil {\n\t\treturn err\n\t}\n\n\tif h.Type != TypeTransportSpecificFeedback || h.Count != FormatRRR {\n\t\treturn errWrongType\n\t}\n\n\tp.SenderSSRC = binary.BigEndian.Uint32(rawPacket[headerLength:])\n\tp.MediaSSRC = binary.BigEndian.Uint32(rawPacket[headerLength+ssrcLength:])\n\treturn nil\n}\n\nfunc (p *RapidResynchronizationRequest) len() int {\n\treturn headerLength + rrrHeaderLength\n}\n\n\nfunc (p *RapidResynchronizationRequest) Header() Header {\n\treturn Header{\n\t\tCount: FormatRRR,\n\t\tType: TypeTransportSpecificFeedback,\n\t\tLength: rrrLength,\n\t}\n}\n\n\nfunc (p *RapidResynchronizationRequest) DestinationSSRC() []uint32 {\n\treturn []uint32{p.MediaSSRC}\n}\n\nfunc (p *RapidResynchronizationRequest) String() string {\n\treturn fmt.Sprintf(\"RapidResynchronizationRequest %x %x\", p.SenderSSRC, p.MediaSSRC)\n}\n\nfunc (p RapidResynchronizationRequest) Marshal() ([]byte, error) ", "output": "{\n\trawPacket := make([]byte, p.len())\n\tpacketBody := rawPacket[headerLength:]\n\n\tbinary.BigEndian.PutUint32(packetBody, p.SenderSSRC)\n\tbinary.BigEndian.PutUint32(packetBody[rrrMediaOffset:], p.MediaSSRC)\n\n\thData, err := p.Header().Marshal()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcopy(rawPacket, hData)\n\n\treturn rawPacket, nil\n}"} {"input": "package jobs\n\nimport (\n\t\"sync\"\n\n\tl4g \"github.com/alecthomas/log4go\"\n\tejobs \"github.com/mattermost/platform/einterfaces/jobs\"\n\t\"github.com/mattermost/platform/model\"\n\t\"github.com/mattermost/platform/store\"\n\t\"github.com/mattermost/platform/utils\"\n)\n\ntype Jobs struct {\n\tstartOnce sync.Once\n\n\tDataRetention model.Job\n\n\tlistenerId string\n}\n\nfunc InitJobs(s store.Store) *Jobs {\n\tjobs := &Jobs{\n\t}\n\n\tif dataRetentionInterface := ejobs.GetDataRetentionInterface(); dataRetentionInterface != nil {\n\t\tjobs.DataRetention = dataRetentionInterface.MakeJob(s)\n\t}\n\n\treturn jobs\n}\n\nfunc (jobs *Jobs) Start() *Jobs {\n\tl4g.Info(\"Starting jobs\")\n\n\tjobs.startOnce.Do(func() {\n\t\tif jobs.DataRetention != nil && *utils.Cfg.DataRetentionSettings.Enable {\n\t\t\tgo jobs.DataRetention.Run()\n\t\t}\n\n\t})\n\n\tjobs.listenerId = utils.AddConfigListener(jobs.handleConfigChange)\n\n\treturn jobs\n}\n\n\n\nfunc (jobs *Jobs) Stop() *Jobs {\n\tutils.RemoveConfigListener(jobs.listenerId)\n\n\tif jobs.DataRetention != nil && *utils.Cfg.DataRetentionSettings.Enable {\n\t\tjobs.DataRetention.Stop()\n\t}\n\n\tl4g.Info(\"Stopped jobs\")\n\n\treturn jobs\n}\n\nfunc (jobs *Jobs) handleConfigChange(oldConfig *model.Config, newConfig *model.Config) ", "output": "{\n\tif jobs.DataRetention != nil {\n\t\tif !*oldConfig.DataRetentionSettings.Enable && *newConfig.DataRetentionSettings.Enable {\n\t\t\tgo jobs.DataRetention.Run()\n\t\t} else if *oldConfig.DataRetentionSettings.Enable && !*newConfig.DataRetentionSettings.Enable {\n\t\t\tjobs.DataRetention.Stop()\n\t\t}\n\t}\n}"} {"input": "package airplane_mode\n\nfunc getRadioModule(key RadioType) BaseRadioModule {\n\tvar module BaseRadioModule\n\tswitch key {\n\tcase BluetoothRadioType:\n\t\tmodule = &BluetoothRadio{GeneralRadioModule{typ: BluetoothRadioType, name: \"bluetooth\"}}\n\tcase WlanRadioType:\n\t\tmodule = &WlanRadio{GeneralRadioModule{typ: WlanRadioType, name: \"wlan\"}}\n\tcase AllRadioType:\n\t\tmodule = &AllRadio{GeneralRadioModule{typ: AllRadioType, name: \"all\"}}\n\tdefault:\n\t\tpanic(\"radio type not exist\")\n\t}\n\treturn module\n}\n\ntype GeneralRadioModule struct {\n\ttyp RadioType\n\tname string\n}\n\nfunc (Op *GeneralRadioModule) Type() RadioType {\n\treturn Op.typ\n}\n\nfunc (Op *GeneralRadioModule) Module() string {\n\treturn Op.name\n}\n\n\n\nfunc (Op *GeneralRadioModule) Block() error {\n\treturn rfkillAction(Op.typ, BlockRadioAction)\n}\n\nfunc (Op *GeneralRadioModule) Unblock() error {\n\treturn rfkillAction(Op.typ, UnblockRadioAction)\n}\n\nfunc (Op *GeneralRadioModule) IsBlocked() bool {\n\tstate, err := rfkillState(Op.typ)\n\tif err != nil {\n\t\tlogger.Warningf(\"check rfkill blocked state failed, err: %v\", err)\n\t\tstate.blocked = false\n\t}\n\treturn state.blocked\n}\n\n\ntype BluetoothRadio struct {\n\tGeneralRadioModule\n}\n\n\ntype WlanRadio struct {\n\tGeneralRadioModule\n}\n\n\ntype AllRadio struct {\n\tGeneralRadioModule\n}\n\nfunc (Op *GeneralRadioModule) Len() int ", "output": "{\n\tstate, err := rfkillState(Op.typ)\n\tif err != nil {\n\t\tlogger.Warningf(\"check rfkill blocked state failed, err: %v\", err)\n\t\tstate.count = 0\n\t}\n\treturn state.count\n}"} {"input": "package bunyan\n\nimport \"fmt\"\n\n\ntype Logger struct {\n\tsink Sink\n\trecord Record\n}\n\n\nfunc NewLogger(target Sink) *Logger {\n\treturn &Logger{target, NewRecord()}\n}\n\n\n\nfunc (l *Logger) Write(record Record) error {\n\trecord.TemplateMerge(l.record)\n\treturn l.sink.Write(record)\n}\n\n\n\nfunc (l *Logger) Include(info Info) Log {\n\treturn NewLogger(InfoSink(l, info))\n}\n\n\n\nfunc (l *Logger) Record(key string, value interface{}) Log {\n\tbuilder := NewLogger(l)\n\tbuilder.record[key] = value\n\treturn builder\n}\n\n\n\nfunc (l *Logger) Recordf(key, value string, args ...interface{}) Log {\n\treturn l.Record(key, fmt.Sprintf(value, args...))\n}\n\n\n\nfunc (l *Logger) Child() Log {\n\treturn NewLogger(l)\n}\n\nfunc (l *Logger) Tracef(msg string, args ...interface{}) { l.send(TRACE, msg, args...) }\nfunc (l *Logger) Debugf(msg string, args ...interface{}) { l.send(DEBUG, msg, args...) }\n\nfunc (l *Logger) Warnf(msg string, args ...interface{}) { l.send(WARN, msg, args...) }\nfunc (l *Logger) Errorf(msg string, args ...interface{}) { l.send(ERROR, msg, args...) }\nfunc (l *Logger) Fatalf(msg string, args ...interface{}) { l.send(FATAL, msg, args...) }\n\nfunc (l *Logger) send(level Level, msg string, args ...interface{}) {\n\trecord := NewRecord()\n\trecord.SetMessagef(level, msg, args...)\n\te := l.Write(record)\n\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc (l *Logger) Infof(msg string, args ...interface{}) ", "output": "{ l.send(INFO, msg, args...) }"} {"input": "package cronsun\n\nimport (\n\t\"encoding/hex\"\n\n\t\"github.com/rogpeppe/fastuuid\"\n)\n\nvar generator *fastuuid.Generator\n\nfunc initID() (err error) {\n\tgenerator, err = fastuuid.NewGenerator()\n\treturn\n}\n\n\n\nfunc NextID() string ", "output": "{\n\tid := generator.Next()\n\treturn hex.EncodeToString(id[:])\n}"} {"input": "package testutil\n\nimport (\n\t\"fmt\"\n\n\t\"gopkg.in/check.v1\"\n)\n\ntype intChecker struct {\n\t*check.CheckerInfo\n\trel string\n}\n\n\n\n\n\n\n\nvar IntLessThan = &intChecker{CheckerInfo: &check.CheckerInfo{Name: \"IntLessThan\", Params: []string{\"a\", \"b\"}}, rel: \"<\"}\n\n\n\n\n\nvar IntLessEqual = &intChecker{CheckerInfo: &check.CheckerInfo{Name: \"IntLessEqual\", Params: []string{\"a\", \"b\"}}, rel: \"<=\"}\n\n\n\n\n\nvar IntEqual = &intChecker{CheckerInfo: &check.CheckerInfo{Name: \"IntEqual\", Params: []string{\"a\", \"b\"}}, rel: \"==\"}\n\n\n\n\n\nvar IntNotEqual = &intChecker{CheckerInfo: &check.CheckerInfo{Name: \"IntNotEqual\", Params: []string{\"a\", \"b\"}}, rel: \"!=\"}\n\n\n\n\n\nvar IntGreaterThan = &intChecker{CheckerInfo: &check.CheckerInfo{Name: \"IntGreaterThan\", Params: []string{\"a\", \"b\"}}, rel: \">\"}\n\n\n\n\n\nvar IntGreaterEqual = &intChecker{CheckerInfo: &check.CheckerInfo{Name: \"IntGreaterEqual\", Params: []string{\"a\", \"b\"}}, rel: \">=\"}\n\nfunc (checker *intChecker) Check(params []interface{}, names []string) (result bool, error string) ", "output": "{\n\ta, ok := params[0].(int)\n\tif !ok {\n\t\treturn false, \"left-hand-side argument must be an int\"\n\t}\n\tb, ok := params[1].(int)\n\tif !ok {\n\t\treturn false, \"right-hand-side argument must be an int\"\n\t}\n\tswitch checker.rel {\n\tcase \"<\":\n\t\tresult = a < b\n\tcase \"<=\":\n\t\tresult = a <= b\n\tcase \"==\":\n\t\tresult = a == b\n\tcase \"!=\":\n\t\tresult = a != b\n\tcase \">\":\n\t\tresult = a > b\n\tcase \">=\":\n\t\tresult = a >= b\n\tdefault:\n\t\treturn false, fmt.Sprintf(\"unexpected relation %q\", checker.rel)\n\t}\n\tif !result {\n\t\terror = fmt.Sprintf(\"relation %d %s %d is not true\", a, checker.rel, b)\n\t}\n\treturn result, error\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype DrgAttachmentInfo struct {\n\n\tId *string `mandatory:\"true\" json:\"id\"`\n}\n\n\n\nfunc (m DrgAttachmentInfo) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package utils\n\nimport \"time\"\n\nconst (\n\tDateFormat = \"yyyy-MM-dd hh:mm:ss\"\n\tTimeLayout = \"2006-01-02 15:04:05\"\n\tDateLayout = \"2006-01-02\"\n)\n\n\n\nfunc Date() string {\n\treturn time.Now().Format(\"2006-01-02\")\n}\n\nfunc Now() string ", "output": "{\n\treturn time.Now().Format(\"2006-01-02 15:04:05\")\n}"} {"input": "package speech_test\n\nimport (\n\t\"io\"\n\n\t\"cloud.google.com/go/speech/apiv1beta1\"\n\t\"github.com/golang/protobuf/ptypes\"\n\t\"golang.org/x/net/context\"\n\tspeechpb \"google.golang.org/genproto/googleapis/cloud/speech/v1beta1\"\n)\n\nfunc ExampleNewClient() {\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\nfunc ExampleClient_SyncRecognize() {\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &speechpb.SyncRecognizeRequest{\n\t}\n\tresp, err := c.SyncRecognize(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleClient_AsyncRecognize() {\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &speechpb.AsyncRecognizeRequest{\n\t}\n\top, err := c.AsyncRecognize(ctx, req)\n\tif err != nil {\n\t}\n\n\tvar resp ptypes.DynamicAny \n\tif err := op.Wait(ctx, &resp); err != nil {\n\t}\n}\n\n\n\nfunc StreamingRecognize() ", "output": "{\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\tstream, err := c.StreamingRecognize(ctx)\n\tif err != nil {\n\t}\n\tgo func() {\n\t\treqs := []*speechpb.StreamingRecognizeRequest{\n\t\t}\n\t\tfor _, req := range reqs {\n\t\t\tif err := stream.Send(req); err != nil {\n\t\t\t}\n\t\t}\n\t\tstream.CloseSend()\n\t}()\n\tfor {\n\t\tresp, err := stream.Recv()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}"} {"input": "package mock_driver\n\nimport (\n\tnet \"net\"\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n)\n\n\ntype MockNetworkAPIs struct {\n\tctrl *gomock.Controller\n\trecorder *MockNetworkAPIsMockRecorder\n}\n\n\ntype MockNetworkAPIsMockRecorder struct {\n\tmock *MockNetworkAPIs\n}\n\n\nfunc NewMockNetworkAPIs(ctrl *gomock.Controller) *MockNetworkAPIs {\n\tmock := &MockNetworkAPIs{ctrl: ctrl}\n\tmock.recorder = &MockNetworkAPIsMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockNetworkAPIs) EXPECT() *MockNetworkAPIsMockRecorder {\n\treturn m.recorder\n}\n\n\n\n\n\nfunc (mr *MockNetworkAPIsMockRecorder) SetupNS(arg0, arg1, arg2, arg3, arg4, arg5, arg6 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SetupNS\", reflect.TypeOf((*MockNetworkAPIs)(nil).SetupNS), arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n}\n\n\nfunc (m *MockNetworkAPIs) TeardownNS(arg0 *net.IPNet, arg1 int) error {\n\tret := m.ctrl.Call(m, \"TeardownNS\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}\n\n\nfunc (mr *MockNetworkAPIsMockRecorder) TeardownNS(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"TeardownNS\", reflect.TypeOf((*MockNetworkAPIs)(nil).TeardownNS), arg0, arg1)\n}\n\nfunc (m *MockNetworkAPIs) SetupNS(arg0, arg1, arg2 string, arg3 *net.IPNet, arg4 int, arg5 []string, arg6 bool) error ", "output": "{\n\tret := m.ctrl.Call(m, \"SetupNS\", arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}"} {"input": "package dax\n\n\ntype Grapher interface {\n\tGetParent() Grapher\n\tAddChild(child Grapher)\n\tGetChildren() []Grapher\n}\n\ntype nodeStack struct {\n\tnodes []Grapher\n}\n\nfunc (s *nodeStack) Init() {\n\ts.nodes = make([]Grapher, 0, 16)\n}\n\nfunc (s *nodeStack) Empty() bool {\n\treturn len(s.nodes) == 0\n}\n\nfunc (s *nodeStack) Push(n Grapher) {\n\ts.nodes = append(s.nodes, n)\n}\n\nfunc (s *nodeStack) Pop() Grapher {\n\ti := len(s.nodes) - 1\n\tn := s.nodes[i]\n\ts.nodes[i] = nil\n\ts.nodes = s.nodes[:i]\n\treturn n\n}\n\ntype SceneGraph struct {\n\tNode\n}\n\nfunc NewSceneGraph() *SceneGraph {\n\tsg := new(SceneGraph)\n\tsg.Init()\n\treturn sg\n}\n\nfunc (sg *SceneGraph) Init() {\n\tsg.Node.Init()\n}\n\n\n\nfunc (sg *SceneGraph) Update(time float64) {\n\tsg.updateWorldTransform()\n}\n\n\nfunc (sg *SceneGraph) Traverse() <-chan Grapher {\n\tch := make(chan Grapher)\n\n\tgo func() {\n\t\tvar stack nodeStack\n\n\t\tstack.Init()\n\t\tstack.Push(sg)\n\n\t\tfor !stack.Empty() {\n\t\t\tn := stack.Pop()\n\t\t\tch <- n\n\t\t\tchildren := n.GetChildren()\n\t\t\tfor i := len(children) - 1; i >= 0; i-- {\n\t\t\t\tstack.Push(children[i])\n\t\t\t}\n\t\t}\n\t\tclose(ch)\n\t}()\n\n\treturn ch\n}\n\nfunc (sg *SceneGraph) Draw(fb Framebuffer) {\n\tfb.render().drawSceneGraph(fb, sg)\n}\n\nfunc (sg *SceneGraph) updateWorldTransform() ", "output": "{\n\tsg.Node.updateWorldTransform(false)\n}"} {"input": "package netutil\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype ConnWrapper struct {\n\tio.Reader\n\tio.Writer\n\tUnderlyingConn net.Conn\n\tReadCloser io.Closer\n\tWriteCloser io.Closer\n}\n\nvar _ net.Conn = new(ConnWrapper)\n\nfunc (c *ConnWrapper) Close() error {\n\tvar multiErr MultiError\n\tif c.ReadCloser != nil {\n\t\tmultiErr.RecordError(c.ReadCloser.Close())\n\t}\n\tif c.WriteCloser != nil {\n\t\tmultiErr.RecordError(c.WriteCloser.Close())\n\t}\n\tmultiErr.RecordError(c.UnderlyingConn.Close())\n\treturn multiErr.ToError()\n}\n\nfunc (c *ConnWrapper) LocalAddr() net.Addr { return c.UnderlyingConn.LocalAddr() }\nfunc (c *ConnWrapper) RemoteAddr() net.Addr { return c.UnderlyingConn.RemoteAddr() }\nfunc (c *ConnWrapper) SetDeadline(t time.Time) error { return c.UnderlyingConn.SetDeadline(t) }\nfunc (c *ConnWrapper) SetReadDeadline(t time.Time) error { return c.UnderlyingConn.SetReadDeadline(t) }\n\n\nfunc (c *ConnWrapper) SetWriteDeadline(t time.Time) error ", "output": "{ return c.UnderlyingConn.SetWriteDeadline(t) }"} {"input": "package msgpack_test\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/danjac/podbaby/api/Godeps/_workspace/src/gopkg.in/vmihailenco/msgpack.v2\"\n)\n\ntype customStruct struct {\n\tS string\n\tN int\n}\n\nvar (\n\t_ msgpack.CustomEncoder = &customStruct{}\n\t_ msgpack.CustomDecoder = &customStruct{}\n)\n\n\n\nfunc (s *customStruct) DecodeMsgpack(dec *msgpack.Decoder) error {\n\treturn dec.Decode(&s.S, &s.N)\n}\n\nfunc ExampleCustomEncoder() {\n\tb, err := msgpack.Marshal(&customStruct{S: \"hello\", N: 42})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar v customStruct\n\terr = msgpack.Unmarshal(b, &v)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"%#v\", v)\n}\n\nfunc (s *customStruct) EncodeMsgpack(enc *msgpack.Encoder) error ", "output": "{\n\treturn enc.Encode(s.S, s.N)\n}"} {"input": "package error\n\nimport \"google.golang.org/grpc/codes\"\n\n\ntype ErrType int\n\nconst (\n\tCANotReady ErrType = iota\n\tCSRError\n\tTTLError\n\tCertGenError\n)\n\n\ntype Error struct {\n\tt ErrType\n\terr error\n}\n\n\nfunc (e Error) Error() string {\n\treturn e.err.Error()\n}\n\n\nfunc (e Error) ErrorType() string {\n\tswitch e.t {\n\tcase CANotReady:\n\t\treturn \"CA_NOT_READY\"\n\tcase CSRError:\n\t\treturn \"CSR_ERROR\"\n\tcase TTLError:\n\t\treturn \"TTL_ERROR\"\n\tcase CertGenError:\n\t\treturn \"CERT_GEN_ERROR\"\n\t}\n\treturn \"UNKNOWN\"\n}\n\n\n\n\n\nfunc NewError(t ErrType, err error) *Error {\n\treturn &Error{\n\t\tt: t,\n\t\terr: err,\n\t}\n}\n\nfunc (e Error) HTTPErrorCode() codes.Code ", "output": "{\n\tswitch e.t {\n\tcase CANotReady:\n\t\treturn codes.Internal\n\tcase CertGenError:\n\t\treturn codes.Internal\n\tcase CSRError:\n\t\treturn codes.InvalidArgument\n\tcase TTLError:\n\t\treturn codes.InvalidArgument\n\t}\n\treturn codes.Internal\n}"} {"input": "package internalversion\n\nimport (\n\tauthorization \"github.com/openshift/origin/pkg/authorization/apis/authorization\"\n\trest \"k8s.io/client-go/rest\"\n)\n\n\n\ntype SubjectRulesReviewsGetter interface {\n\tSubjectRulesReviews(namespace string) SubjectRulesReviewInterface\n}\n\n\ntype SubjectRulesReviewInterface interface {\n\tCreate(*authorization.SubjectRulesReview) (*authorization.SubjectRulesReview, error)\n\tSubjectRulesReviewExpansion\n}\n\n\ntype subjectRulesReviews struct {\n\tclient rest.Interface\n\tns string\n}\n\n\nfunc newSubjectRulesReviews(c *AuthorizationClient, namespace string) *subjectRulesReviews {\n\treturn &subjectRulesReviews{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}\n\n\n\n\nfunc (c *subjectRulesReviews) Create(subjectRulesReview *authorization.SubjectRulesReview) (result *authorization.SubjectRulesReview, err error) ", "output": "{\n\tresult = &authorization.SubjectRulesReview{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"subjectrulesreviews\").\n\t\tBody(subjectRulesReview).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}"} {"input": "package dao\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net/url\"\n\n\t\"go-common/library/log\"\n)\n\nconst (\n\t_codeFigureNotFound = 55001\n\t_figureInfoURL = \"/x/internal/figure/info\"\n)\n\n\n\n\nfunc (d *Dao) FigureInfo(c context.Context, mid int64) (score int32, err error) {\n\tvar (\n\t\tres = &struct {\n\t\t\tCode int `json:\"code\"`\n\t\t\tData *struct {\n\t\t\t\tPercentage int32 `json:\"percentage\"`\n\t\t\t} `json:\"data\"`\n\t\t}{}\n\t\tparams = url.Values{}\n\t\turi = d.figureInfoURI()\n\t)\n\tparams.Set(\"mid\", fmt.Sprint(mid))\n\tif err = d.httpClient.Get(c, uri, \"\", params, &res); err != nil {\n\t\tlog.Error(\"d.httpClient.Get(%s,%v,%d)\", uri, params, err)\n\t\treturn\n\t}\n\tif res.Code != 0 && res.Code != _codeFigureNotFound {\n\t\terr = fmt.Errorf(\"code != 0 && code !=%d\", _codeFigureNotFound)\n\t\tlog.Error(\"d.httpClient.Get(%s,%v,%v,%d)\", uri, params, err, res.Code)\n\t\treturn\n\t}\n\tif res != nil && res.Data != nil {\n\t\tscore = res.Data.Percentage\n\t}\n\treturn\n}\n\nfunc (d *Dao) figureInfoURI() string ", "output": "{\n\treturn d.conf.Host.API + _figureInfoURL\n}"} {"input": "package gologger\n\nimport (\n \"fmt\"\n)\n\ntype appender2Console struct {\n}\n\nfunc (self *appender2Console) init() error {\n return nil\n}\n\n\n\nfunc (self *appender2Console) handle(msg *logMsg) error {\n fmt.Printf(\"%s\\n\", msg.info)\n return nil\n}\n\nfunc (self *appender2Console) setNext(n logHandler) {\n return\n}\n\nfunc (self *appender2Console) close() ", "output": "{\n return\n}"} {"input": "package data\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"testing\"\n)\n\nfunc TestBytesInt32Convert(t *testing.T) {\n\tvar i32 int32\n\ti32 = 11\n\tt.Log(i32)\n\tbs := Int32ToBytes(i32)\n\tt.Log(bs)\n\tt.Log(len(bs))\n\tt.Log(cap(bs))\n\tbuff := bytes.NewBuffer(bs)\n\tt.Log(buff.Bytes())\n\tinew := BytesToInt32(bs)\n\tt.Log(inew)\n\tif i32 == inew {\n\t\tt.Log(i32 == inew)\n\t} else {\n\t\tt.Fail()\n\t}\n}\n\n\n\nfunc TestMsg(t *testing.T) ", "output": "{\n\tmsg := new(Message)\n\tjson.Unmarshal([]byte(`{\n\t\"msg_type\": \"msg_type\",\n\t\"msg\": \"msg\",\n\t\"from_user_id\": \"from_user_id\",\n\t\"to_user_id\": \"to_user_id\",\n\t\"from_conn_id\": \"from_conn_id\",\n\t\"to_conn_id\": \"to_conn_id\"\n}`), msg)\n\tt.Log(msg)\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/spf13/cobra\"\n\t\"go.etcd.io/etcd/etcdutl/v3/etcdutl\"\n\t\"go.etcd.io/etcd/pkg/v3/cobrautl\"\n)\n\nvar (\n\tdefragDataDir string\n)\n\n\n\n\nfunc defragCommandFunc(cmd *cobra.Command, args []string) {\n\tif len(defragDataDir) > 0 {\n\t\tfmt.Fprintf(os.Stderr, \"Use `etcdutl defrag` instead. The --data-dir is going to be decomissioned in v3.6.\\n\\n\")\n\t\terr := etcdutl.DefragData(defragDataDir)\n\t\tif err != nil {\n\t\t\tcobrautl.ExitWithError(cobrautl.ExitError, err)\n\t\t}\n\t}\n\n\tfailures := 0\n\tc := mustClientFromCmd(cmd)\n\tfor _, ep := range endpointsFromCluster(cmd) {\n\t\tctx, cancel := commandCtx(cmd)\n\t\tstart := time.Now()\n\t\t_, err := c.Defragment(ctx, ep)\n\t\td := time.Now().Sub(start)\n\t\tcancel()\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Failed to defragment etcd member[%s]. took %s. (%v)\\n\", ep, d.String(), err)\n\t\t\tfailures++\n\t\t} else {\n\t\t\tfmt.Printf(\"Finished defragmenting etcd member[%s]. took %s\\n\", ep, d.String())\n\t\t}\n\t}\n\n\tif failures != 0 {\n\t\tos.Exit(cobrautl.ExitError)\n\t}\n}\n\nfunc NewDefragCommand() *cobra.Command ", "output": "{\n\tcmd := &cobra.Command{\n\t\tUse: \"defrag\",\n\t\tShort: \"Defragments the storage of the etcd members with given endpoints\",\n\t\tRun: defragCommandFunc,\n\t}\n\tcmd.PersistentFlags().BoolVar(&epClusterEndpoints, \"cluster\", false, \"use all endpoints from the cluster member list\")\n\tcmd.Flags().StringVar(&defragDataDir, \"data-dir\", \"\", \"Optional. If present, defragments a data directory not in use by etcd.\")\n\tcmd.MarkFlagDirname(\"data-dir\")\n\treturn cmd\n}"} {"input": "package Filter\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/reactivego/scheduler\"\n\t\"github.com/reactivego/subscriber\"\n)\n\n\n\n\ntype Scheduler = scheduler.Scheduler\n\n\n\n\n\n\ntype Subscriber = subscriber.Subscriber\n\n\n\n\n\n\n\n\n\ntype IntObserver func(next int, err error, done bool)\n\n\n\n\n\ntype ObservableInt func(IntObserver, Scheduler, Subscriber)\n\n\n\n\n\n\n\n\n\nfunc (o ObservableInt) Filter(predicate func(next int) bool) ObservableInt {\n\tobservable := func(observe IntObserver, subscribeOn Scheduler, subscriber Subscriber) {\n\t\tobserver := func(next int, err error, done bool) {\n\t\t\tif done || predicate(next) {\n\t\t\t\tobserve(next, err, done)\n\t\t\t}\n\t\t}\n\t\to(observer, subscribeOn, subscriber)\n\t}\n\treturn observable\n}\n\n\n\n\n\n\n\nfunc (o ObservableInt) Println(a ...interface{}) error {\n\tsubscriber := subscriber.New()\n\tscheduler := scheduler.MakeTrampoline()\n\tobserver := func(next int, err error, done bool) {\n\t\tif !done {\n\t\t\tfmt.Println(append(a, next)...)\n\t\t} else {\n\t\t\tsubscriber.Done(err)\n\t\t}\n\t}\n\tsubscriber.OnWait(scheduler.Wait)\n\to(observer, scheduler, subscriber)\n\treturn subscriber.Wait()\n}\n\nfunc FromInt(slice ...int) ObservableInt ", "output": "{\n\tobservable := func(observe IntObserver, scheduler Scheduler, subscriber Subscriber) {\n\t\ti := 0\n\t\trunner := scheduler.ScheduleRecursive(func(self func()) {\n\t\t\tif subscriber.Subscribed() {\n\t\t\t\tif i < len(slice) {\n\t\t\t\t\tobserve(slice[i], nil, false)\n\t\t\t\t\tif subscriber.Subscribed() {\n\t\t\t\t\t\ti++\n\t\t\t\t\t\tself()\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tvar zero int\n\t\t\t\t\tobserve(zero, nil, true)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\tsubscriber.OnUnsubscribe(runner.Cancel)\n\t}\n\treturn observable\n}"} {"input": "package clock\n\nimport \"time\"\n\n\nvar Work Clock\n\nfunc init() {\n\tWork = New()\n}\n\n\nfunc Now() time.Time {\n\treturn Work.Now()\n}\n\nfunc Since(t time.Time) time.Duration {\n\treturn Work.Now().Sub(t)\n}\n\n\n\nfunc Sleep(d time.Duration) {\n\tWork.Sleep(d)\n}\n\n\n\nfunc After(d time.Duration) <-chan time.Time {\n\treturn Work.After(d)\n}\n\n\n\nfunc Tick(d time.Duration) <-chan time.Time {\n\treturn Work.Tick(d)\n}\n\n\n\n\n\n\n\n\ntype Clock interface {\n\n\tNow() time.Time\n\n\tSleep(d time.Duration)\n\n\tAfter(d time.Duration) <-chan time.Time\n\n\tTick(d time.Duration) <-chan time.Time\n\n\tTicker(d time.Duration) *time.Ticker\n\n}\n\n\ntype Mock interface {\n\tClock\n\n\n\tSet(t time.Time) Mock\n\n\tAdd(d time.Duration) Mock\n\n\tFreeze() Mock\n\n\tIsFrozen() bool\n\n\tUnfreeze() Mock\n\n\tClose()\n}\n\nfunc Ticker(d time.Duration) *time.Ticker ", "output": "{\n\treturn Work.Ticker(d)\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\nfunc direntIno(buf []byte) (uint64, bool) {\n\treturn readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino))\n}\n\n\n\nfunc direntNamlen(buf []byte) (uint64, bool) {\n\treturn readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen))\n}\n\nfunc direntReclen(buf []byte) (uint64, bool) ", "output": "{\n\treturn readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))\n}"} {"input": "package server\n\nimport (\n\t\"strings\"\n\n\tot \"github.com/opentracing/opentracing-go\"\n\tzipkinot \"github.com/openzipkin-contrib/zipkin-go-opentracing\"\n\tzipkin \"github.com/openzipkin/zipkin-go\"\n\tzipkinhttp \"github.com/openzipkin/zipkin-go/reporter/http\"\n)\n\n\n\nfunc setupZipkin(tracingEP string) (ot.Tracer, error) {\n\treporter := zipkinhttp.NewReporter(tracingEP)\n\trecorder, err := zipkin.NewEndpoint(\"PDP\", \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttracer, err := zipkin.NewTracer(\n\t\treporter,\n\t\tzipkin.WithLocalEndpoint(recorder),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn zipkinot.Wrap(tracer), nil\n}\n\nfunc initTracing(tracingType, tracingEP string) (ot.Tracer, error) ", "output": "{\n\tif tracingEP == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tswitch strings.ToLower(tracingType) {\n\tdefault:\n\t\treturn nil, newTracingTypeError(tracingType)\n\n\tcase \"zipkin\":\n\t\treturn setupZipkin(tracingEP)\n\t}\n}"} {"input": "package main\n\ntype Move struct {\n\tSrc Point\n\tDest Point\n}\n\nvar EmptyMove = Move{Point{0, 0}, Point{0, 0}}\n\n\n\nfunc (m Move) String() string {\n\treturn m.Src.String() + \">\" + m.Dest.String()\n}\n\nfunc (m Move) Valid(table Table) bool {\n\tfor x := m.Src.X; x <= m.Dest.X; x++ {\n\t\tfor y := m.Src.Y; y <= m.Dest.Y; y++ {\n\t\t\tcell := table[y][x]\n\t\t\tswitch cell {\n\t\t\tcase HOLLOW, LAND:\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (m Move) Apply(t Table) {\n\tdist := m.Src.DistanceTo(m.Dest) + 1\n\tdist /= 2\n\n\tif m.Src.X == m.Dest.X {\n\t\tfor i := 0; i < dist; i++ {\n\t\t\tt.SwapY(m.Src.X, m.Src.Y+i, m.Dest.Y-i)\n\t\t}\n\n\t} else if m.Src.Y == m.Dest.Y {\n\t\tfor i := 0; i < dist; i++ {\n\t\t\tt.SwapX(m.Src.Y, m.Src.X+i, m.Dest.X-i)\n\t\t}\n\n\t} else {\n\t\tpanic(\"Diagonal move is not supported!\")\n\t}\n\n\n\n\tfor t.Resolve() > 0 {\n\t}\n}\n\nfunc NewMove(src Point, dest Point) Move ", "output": "{\n\ts, d := src, dest\n\tif s.X > d.X {\n\t\ts.X, d.X = d.X, s.X\n\t}\n\tif s.Y > d.Y {\n\t\ts.Y, d.Y = d.Y, s.Y\n\t}\n\n\treturn Move{src, dest}\n}"} {"input": "package names\n\nimport \"knative.dev/pkg/kmeta\"\n\n\n\n\n\nfunc ImageCache(rev kmeta.Accessor) string {\n\treturn kmeta.ChildName(rev.GetName(), \"-cache\")\n}\n\n\nfunc PA(rev kmeta.Accessor) string {\n\treturn rev.GetName()\n}\n\nfunc Deployment(rev kmeta.Accessor) string ", "output": "{\n\treturn kmeta.ChildName(rev.GetName(), \"-deployment\")\n}"} {"input": "package iterkernel\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc (receiver *Kernel) KernelScan(fn func(interface{})(bool,error), dest ...interface{}) error ", "output": "{\n\tif nil == receiver {\n\t\treturn errNilReceiver\n\t}\n\n\n\tif expected, actual := 1, len(dest); expected != actual {\n\t\treturn fmt.Errorf(\"iter: expected %d destination arguments in Scan, not %d\", expected, actual)\n\t}\n\n\tdest0 := dest[0]\n\n\tif err := receiver.KernelDecode(fn, dest0); nil != err {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package db\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"time\"\n\n\t\"github.com/boltdb/bolt\"\n\n\t\"github.com/michaelorr/goodall/pkg/metrics\"\n)\n\nfunc Open(path string) (*bolt.DB, error) {\n\treturn bolt.Open(path, 0600, &bolt.Options{Timeout: 1 * time.Second})\n}\n\nfunc Init(conn *bolt.DB) error {\n\tfor bucket, _ := range metrics.BucketMap {\n\t\terr := conn.Update(func(tx *bolt.Tx) error {\n\t\t\t_, err := tx.CreateBucketIfNotExists([]byte(bucket))\n\t\t\treturn err\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\nfunc Btof(b []byte) (float64, error) {\n\tvar f float64\n\tbuf := bytes.NewReader(b)\n\terr := binary.Read(buf, binary.BigEndian, &f)\n\tif err != nil {\n\t\treturn f, err\n\t}\n\treturn f, nil\n}\n\nfunc Ftob(f float64) ([]byte, error) ", "output": "{\n\tbuf := new(bytes.Buffer)\n\terr := binary.Write(buf, binary.BigEndian, f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}"} {"input": "package Plugin\n\nimport \"github.com/MPjct/GoMP/MySQLProtocol\"\n\ntype Plugin_interface interface {\n\tinit(context MySQLProtocol.Context)\n\tread_handshake(context MySQLProtocol.Context)\n\tsend_handshake(context MySQLProtocol.Context)\n\tread_auth(context MySQLProtocol.Context)\n\tsend_auth(context MySQLProtocol.Context)\n\tread_auth_result(context MySQLProtocol.Context)\n\tsend_auth_result(context MySQLProtocol.Context)\n\tread_query(context MySQLProtocol.Context)\n\tsend_query(context MySQLProtocol.Context)\n\tread_query_result(context MySQLProtocol.Context)\n\tsend_query_result(context MySQLProtocol.Context)\n\tcleanup(context MySQLProtocol.Context)\n}\n\ntype Plugin struct {\n}\n\nfunc (plugin *Plugin) init(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\n\n\nfunc (plugin *Plugin) read_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) cleanup(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth_result(context MySQLProtocol.Context) ", "output": "{\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"os\"\n)\n\n\n\nfunc main() {\n\tvar x1, y1, x2, y2 int\n\tdata, err := os.Open(os.Args[1])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer data.Close()\n\tscanner := bufio.NewScanner(data)\n\tfor scanner.Scan() {\n\t\tfmt.Sscanf(scanner.Text(), \"(%d, %d) (%d, %d)\", &x1, &y1, &x2, &y2)\n\t\tx, y := x1-x2, y1-y2\n\t\tfmt.Println(sqrt(x*x + y*y))\n\t}\n}\n\nfunc sqrt(a int) int ", "output": "{\n\treturn int(math.Sqrt(float64(a)))\n}"} {"input": "package cabf_br\n\n\n\nimport (\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/util\"\n)\n\ntype CertPolicyOVRequiresProvinceOrLocal struct{}\n\n\n\n\n\nfunc (l *CertPolicyOVRequiresProvinceOrLocal) Initialize() error {\n\treturn nil\n}\n\nfunc (l *CertPolicyOVRequiresProvinceOrLocal) CheckApplies(cert *x509.Certificate) bool {\n\treturn util.IsSubscriberCert(cert) && util.SliceContainsOID(cert.PolicyIdentifiers, util.BROrganizationValidatedOID)\n}\n\nfunc (l *CertPolicyOVRequiresProvinceOrLocal) Execute(cert *x509.Certificate) *lint.LintResult {\n\tvar out lint.LintResult\n\tif util.TypeInName(&cert.Subject, util.LocalityNameOID) || util.TypeInName(&cert.Subject, util.StateOrProvinceNameOID) {\n\t\tout.Status = lint.Pass\n\t} else {\n\t\tout.Status = lint.Error\n\t}\n\treturn &out\n}\n\nfunc init() ", "output": "{\n\tlint.RegisterLint(&lint.Lint{\n\t\tName: \"e_cert_policy_ov_requires_province_or_locality\",\n\t\tDescription: \"If certificate policy 2.23.140.1.2.2 is included, localityName or stateOrProvinceName MUST be included in subject\",\n\t\tCitation: \"BRs: 7.1.6.4\",\n\t\tSource: lint.CABFBaselineRequirements,\n\t\tEffectiveDate: util.CABEffectiveDate,\n\t\tLint: &CertPolicyOVRequiresProvinceOrLocal{},\n\t})\n}"} {"input": "package client\n\nimport (\n\tuserapi \"github.com/projectatomic/atomic-enterprise/pkg/user/api\"\n)\n\n\ntype UserIdentityMappingsInterface interface {\n\tUserIdentityMappings() UserIdentityMappingInterface\n}\n\n\ntype UserIdentityMappingInterface interface {\n\tGet(string) (*userapi.UserIdentityMapping, error)\n\tCreate(*userapi.UserIdentityMapping) (*userapi.UserIdentityMapping, error)\n\tUpdate(*userapi.UserIdentityMapping) (*userapi.UserIdentityMapping, error)\n\tDelete(string) error\n}\n\n\ntype userIdentityMappings struct {\n\tr *Client\n}\n\n\nfunc newUserIdentityMappings(c *Client) *userIdentityMappings {\n\treturn &userIdentityMappings{\n\t\tr: c,\n\t}\n}\n\n\nfunc (c *userIdentityMappings) Get(name string) (result *userapi.UserIdentityMapping, err error) {\n\tresult = &userapi.UserIdentityMapping{}\n\terr = c.r.Get().Resource(\"userIdentityMappings\").Name(name).Do().Into(result)\n\treturn\n}\n\n\nfunc (c *userIdentityMappings) Create(mapping *userapi.UserIdentityMapping) (result *userapi.UserIdentityMapping, err error) {\n\tresult = &userapi.UserIdentityMapping{}\n\terr = c.r.Post().Resource(\"userIdentityMappings\").Body(mapping).Do().Into(result)\n\treturn\n}\n\n\nfunc (c *userIdentityMappings) Update(mapping *userapi.UserIdentityMapping) (result *userapi.UserIdentityMapping, err error) {\n\tresult = &userapi.UserIdentityMapping{}\n\terr = c.r.Put().Resource(\"userIdentityMappings\").Name(mapping.Name).Body(mapping).Do().Into(result)\n\treturn\n}\n\n\n\n\nfunc (c *userIdentityMappings) Delete(name string) (err error) ", "output": "{\n\terr = c.r.Delete().Resource(\"userIdentityMappings\").Name(name).Do().Error()\n\treturn\n}"} {"input": "package framework\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"k8s.io/kubernetes/pkg/kubelet/remote\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\nvar (\n\tuuidLock sync.Mutex\n\n\tlastUUID uuid.UUID\n)\n\n\nfunc LoadCRIClient() (*InternalAPIClient, error) {\n\trService, err := remote.NewRemoteRuntimeService(TestContext.RuntimeServiceAddr, TestContext.RuntimeServiceTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tiService, err := remote.NewRemoteImageService(TestContext.ImageServiceAddr, TestContext.ImageServiceTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &InternalAPIClient{\n\t\tCRIRuntimeClient: rService,\n\t\tCRIImageClient: iService,\n\t}, nil\n}\n\nfunc nowStamp() string {\n\treturn time.Now().Format(time.StampMilli)\n}\n\nfunc log(level string, format string, args ...interface{}) {\n\tfmt.Fprintf(GinkgoWriter, nowStamp()+\": \"+level+\": \"+format+\"\\n\", args...)\n}\n\n\nfunc Logf(format string, args ...interface{}) {\n\tlog(\"INFO\", format, args...)\n}\n\n\nfunc Failf(format string, args ...interface{}) {\n\tmsg := fmt.Sprintf(format, args...)\n\tlog(\"INFO\", msg)\n\tFail(nowStamp()+\": \"+msg, 1)\n}\n\n\nfunc ExpectNoError(err error, explain ...interface{}) {\n\tif err != nil {\n\t\tLogf(\"Unexpected error occurred: %v\", err)\n\t}\n\tExpectWithOffset(1, err).NotTo(HaveOccurred(), explain...)\n}\n\n\n\n\nfunc NewUUID() string ", "output": "{\n\tuuidLock.Lock()\n\tdefer uuidLock.Unlock()\n\tresult := uuid.NewUUID()\n\tfor uuid.Equal(lastUUID, result) == true {\n\t\tresult = uuid.NewUUID()\n\t}\n\tlastUUID = result\n\treturn result.String()\n}"} {"input": "package graph\n\ntype vertexDistance struct {\n\tvertex string\n\tdistance float64\n}\n\n\n\n\ntype vertexDistanceHeap []vertexDistance\n\nfunc (h vertexDistanceHeap) Len() int { return len(h) }\n \nfunc (h vertexDistanceHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }\n\nfunc (h *vertexDistanceHeap) Push(x interface{}) {\n\t*h = append(*h, x.(vertexDistance))\n}\n\nfunc (h *vertexDistanceHeap) Pop() interface{} {\n\theapSize := len(*h)\n\tlastVertex := (*h)[heapSize-1]\n\t*h = (*h)[0 : heapSize-1]\n\treturn lastVertex\n}\n\nfunc (h *vertexDistanceHeap) updateDistance(vtx string, val float64) {\n\tfor i := 0; i < len(*h); i++ {\n\t\tif (*h)[i].vertex == vtx {\n\t\t\t(*h)[i].distance = val\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (h vertexDistanceHeap) Less(i, j int) bool ", "output": "{ return h[i].distance < h[j].distance }"} {"input": "package builtin\n\nconst bluetoothControlSummary = `allows managing the kernel bluetooth stack`\n\nconst bluetoothControlBaseDeclarationSlots = `\n bluetooth-control:\n allow-installation:\n slot-snap-type:\n - core\n deny-auto-connection: true\n`\n\nconst bluetoothControlConnectedPlugAppArmor = `\n# Description: Allow managing the kernel side Bluetooth stack. Reserved\n# because this gives privileged access to the system.\n\n network bluetooth,\n # For crypto functionality the kernel offers\n network alg,\n\n capability net_admin,\n\n # File accesses\n /sys/bus/usb/drivers/btusb/ r,\n /sys/bus/usb/drivers/btusb/** r,\n /sys/class/bluetooth/ r,\n /sys/devices/**/bluetooth/ rw,\n /sys/devices/**/bluetooth/** rw,\n\n # Requires CONFIG_BT_VHCI to be loaded\n /dev/vhci rw,\n`\n\nconst bluetoothControlConnectedPlugSecComp = `\n# Description: Allow managing the kernel side Bluetooth stack. Reserved\n# because this gives privileged access to the system.\nbind\n`\n\nconst bluetoothControlConnectedPlugUDev = `SUBSYSTEM==\"bluetooth\", TAG+=\"###CONNECTED_SECURITY_TAGS###\"`\n\n\n\nfunc init() ", "output": "{\n\tregisterIface(&commonInterface{\n\t\tname: \"bluetooth-control\",\n\t\tsummary: bluetoothControlSummary,\n\t\timplicitOnCore: true,\n\t\timplicitOnClassic: true,\n\t\tbaseDeclarationSlots: bluetoothControlBaseDeclarationSlots,\n\t\tconnectedPlugAppArmor: bluetoothControlConnectedPlugAppArmor,\n\t\tconnectedPlugSecComp: bluetoothControlConnectedPlugSecComp,\n\t\tconnectedPlugUDev: bluetoothControlConnectedPlugUDev,\n\t\treservedForOS: true,\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\nfunc TestDiscovery(t *testing.T) {\n\tdiscoveryStr := \"redis://root@127.0.0.1:6379/dragonfly/master\"\n\tdiscovery := new(Discovery)\n\terr := discovery.parse(discoveryStr)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestAdvertise(t *testing.T) {\n\tadvertiseStr := \"127.0.0.1\"\n\tadvertise := new(Advertise)\n\terr := advertise.parse(advertiseStr)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\n\n\nfunc TestServer(t *testing.T) ", "output": "{\n\tsm := new(ServerManage)\n\tdiscoveryStr := \"redis://root@127.0.0.1:6379/dragonfly/master\"\n\tdiscovery := new(Discovery)\n\tdiscovery.parse(discoveryStr)\n\tadvertiseStr := \"127.0.0.1\"\n\tadvertise := new(Advertise)\n\tadvertise.parse(advertiseStr)\n\tserver, err := discovery.init()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tsm.server = server\n\tsm.quit = make(chan bool)\n\tsm.clear = make(chan bool)\n\tsm.run(advertise)\n\tsm.stop()\n}"} {"input": "package cpf\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\nfunc Valid(digits string) (bool, error) {\n\treturn valid(digits)\n}\n\nfunc sanitize(data string) string {\n\tdata = strings.Replace(data, \".\", \"\", -1)\n\tdata = strings.Replace(data, \"-\", \"\", -1)\n\treturn data\n}\n\nfunc valid(data string) (bool, error) {\n\tdata = sanitize(data)\n\n\tif len(data) != 11 {\n\t\treturn false, errors.New(\"Invalid length\")\n\t}\n\n\tif strings.Contains(blacklist, data) || !check(data) {\n\t\treturn false, errors.New(\"Invalid value\")\n\t}\n\n\treturn true, nil\n}\n\nconst blacklist = `00000000000\n11111111111\n22222222222\n33333333333\n44444444444\n55555555555\n66666666666\n77777777777\n88888888888\n99999999999\n12345678909`\n\n\n\nfunc verify(data []int, n int) int {\n\tvar total int\n\n\tfor i := 0; i < n; i++ {\n\t\ttotal += data[i] * (n + 1 - i)\n\t}\n\n\ttotal = total % 11\n\tif total < 2 {\n\t\treturn 0\n\t}\n\treturn 11 - total\n}\n\nfunc check(data string) bool {\n\treturn checkEach(data, 9) && checkEach(data, 10)\n}\n\nfunc checkEach(data string, n int) bool {\n\tfinal := verify(stringToIntSlice(data), n)\n\n\tx, err := strconv.Atoi(string(data[n]))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn final == x\n}\n\nfunc stringToIntSlice(data string) (res []int) ", "output": "{\n\tfor _, d := range data {\n\t\tx, err := strconv.Atoi(string(d))\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, x)\n\t}\n\treturn\n}"} {"input": "package flag\n\nimport (\n\t\"flag\"\n\t\"github.com/mono83/cfg\"\n\t\"github.com/mono83/cfg/reflect\"\n\t\"os\"\n\t\"sync\"\n)\n\ntype flagSource struct {\n\tset *flag.FlagSet\n\targs []string\n\tm sync.Mutex\n\n\tvalues map[string]interface{}\n}\n\n\nfunc NewFlagSource() cfg.Configurer {\n\treturn NewCustomFlagSource(flag.CommandLine, os.Args[1:])\n}\n\n\n\nfunc NewCustomFlagSource(source *flag.FlagSet, args []string) cfg.Configurer {\n\treturn &flagSource{set: source, args: args}\n}\n\nfunc (f *flagSource) Validate() error {\n\treturn f.load()\n}\n\n\n\nfunc (f *flagSource) Has(key string) bool {\n\tif f.values == nil {\n\t\terr := f.load()\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t_, ok := f.values[key]\n\treturn ok\n}\n\nfunc (f *flagSource) UnmarshalKey(key string, target interface{}) error {\n\tif f.values == nil {\n\t\terr := f.load()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tv, ok := f.values[key]\n\tif !ok {\n\t\treturn cfg.ErrKeyMissing{Key: key}\n\t}\n\n\treturn reflect.CopyHelper(key, v, target)\n}\n\nfunc (f *flagSource) KeyFunc(key string) func(interface{}) error {\n\treturn cfg.ExtractUnmarshalFunc(f, key)\n}\n\nfunc (f *flagSource) load() error ", "output": "{\n\tf.m.Lock()\n\tdefer f.m.Unlock()\n\n\tif !f.set.Parsed() {\n\t\terr := f.set.Parse(f.args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tf.values = map[string]interface{}{}\n\n\tf.set.Visit(func(fl *flag.Flag) {\n\t\tv, ok := fl.Value.(flag.Getter)\n\t\tif ok {\n\t\t\tf.values[fl.Name] = v.Get()\n\t\t}\n\t})\n\n\treturn nil\n}"} {"input": "package queue\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Node struct {\n\tvalue interface{}\n\tnext *Node\n}\n\nfunc NewNode(value interface{}) *Node {\n\tnode := new(Node)\n\tnode.value = value\n\n\treturn node\n}\n\ntype Queue struct {\n\thead *Node\n\ttail *Node\n}\n\nfunc NewQueue(args ...interface{}) *Queue {\n\tlist := new(Queue)\n\n\tfor _, v := range args {\n\t\tlist.Enqueue(v)\n\t}\n\n\treturn list\n}\n\n\n\nfunc (q *Queue) Enqueue(value interface{}) {\n\tnewTail := NewNode(value)\n\n\tif q.head == nil {\n\t\tq.head = newTail\n\t\tq.tail = q.head\n\t} else {\n\t\tq.tail.next = newTail\n\t\tq.tail = newTail\n\t}\n}\n\nfunc (q *Queue) Dequeue() (value interface{}, ok bool) {\n\n\tif q.head == nil {\n\t\treturn 0, false\n\t} else {\n\t\tnode := q.head\n\t\tq.head = node.next\n\t\treturn node.value, true\n\t}\n}\n\nfunc (q *Queue) Peek() (value interface{}, ok bool) {\n\tif q.head == nil {\n\t\treturn 0, false\n\t} else {\n\t\treturn q.head.value, true\n\t}\n}\n\nfunc (q *Queue) Empty() bool {\n\tif q.head == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\nfunc (q *Queue) String() string ", "output": "{\n\tnode := q.head\n\n\tvar values []string\n\n\tif node == nil {\n\t\treturn \"[]\"\n\t}\n\n\tfor node.next != nil {\n\t\tvalues = append(values, fmt.Sprintf(\"%v\", node.value))\n\n\t\tnode = node.next\n\t}\n\tvalues = append(values, fmt.Sprintf(\"%v\", node.value))\n\n\treturn fmt.Sprintf(\"[%s]\", strings.Join(values, \", \"))\n}"} {"input": "package nagiosplugin\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestCheck(t *testing.T) {\n\trand.Seed(time.Now().UTC().UnixNano())\n\tc := NewCheck()\n\texpected := \"CRITICAL: 200000 terrifying space monkeys in the engineroom | space_monkeys=200000c;10000;100000;0;4294967296\"\n\tnSpaceMonkeys := float64(200000)\n\tmaxSpaceMonkeys := float64(1 << 32)\n\tc.AddPerfDatum(\"space_monkeys\", \"c\", nSpaceMonkeys, 0, maxSpaceMonkeys, 10000, 100000)\n\tc.AddResult(CRITICAL, fmt.Sprintf(\"%v terrifying space monkeys in the engineroom\", nSpaceMonkeys))\n\tc.AddResult(WARNING, fmt.Sprintf(\"%v slightly annoying space monkeys in the engineroom\", nSpaceMonkeys))\n\tresult := c.String()\n\tif expected != result {\n\t\tt.Errorf(\"Expected check output %v, got check output %v\", expected, result)\n\t}\n}\n\nfunc TestDefaultStatusPolicy(t *testing.T) {\n\tc := NewCheck()\n\tc.AddResult(WARNING, \"Isolated-frame flux emission outside threshold\")\n\tc.AddResult(UNKNOWN, \"No response from betaform amplifier\")\n\n\texpected := \"UNKNOWN\"\n\tactual := strings.SplitN(c.String(), \":\", 2)[0]\n\tif actual != expected {\n\t\tt.Errorf(\"Expected %v status, got %v\", expected, actual)\n\t}\n}\n\n\n\nfunc TestOUWCStatusPolicy(t *testing.T) ", "output": "{\n\tc := NewCheckWithOptions(CheckOptions{\n\t\tStatusPolicy: NewOUWCStatusPolicy(),\n\t})\n\tc.AddResult(WARNING, \"Isolated-frame flux emission outside threshold\")\n\tc.AddResult(UNKNOWN, \"No response from betaform amplifier\")\n\n\texpected := \"WARNING\"\n\tactual := strings.SplitN(c.String(), \":\", 2)[0]\n\tif actual != expected {\n\t\tt.Errorf(\"Expected %v status, got %v\", expected, actual)\n\t}\n}"} {"input": "package mobileengagement\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype ManagementClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {\n\treturn ManagementClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) ManagementClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/cobra/doc\"\n\n\tcli \"github.com/lxc/lxd/shared/cmd\"\n\t\"github.com/lxc/lxd/shared/i18n\"\n)\n\ntype cmdManpage struct {\n\tglobal *cmdGlobal\n}\n\nfunc (c *cmdManpage) Command() *cobra.Command {\n\tcmd := &cobra.Command{}\n\tcmd.Use = i18n.G(\"manpage \")\n\tcmd.Short = i18n.G(\"Generate manpages for all commands\")\n\tcmd.Long = cli.FormatSection(i18n.G(\"Description\"), i18n.G(\n\t\t`Generate manpages for all commands`))\n\tcmd.Hidden = true\n\n\tcmd.RunE = c.Run\n\n\treturn cmd\n}\n\n\n\nfunc (c *cmdManpage) Run(cmd *cobra.Command, args []string) error ", "output": "{\n\texit, err := c.global.CheckArgs(cmd, args, 1, 1)\n\tif exit {\n\t\treturn err\n\t}\n\n\theader := &doc.GenManHeader{\n\t\tTitle: i18n.G(\"LXD - Command line client\"),\n\t\tSection: \"1\",\n\t}\n\n\topts := doc.GenManTreeOptions{\n\t\tHeader: header,\n\t\tPath: args[0],\n\t\tCommandSeparator: \".\",\n\t}\n\n\tdoc.GenManTreeFromOpts(c.global.cmd, opts)\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/robfig/cron\"\n)\n\ntype Sync struct{}\n\nfunc (s *Sync) Help() string {\n\treturn \"glr sync Help\"\n}\n\nfunc (s *Sync) Run(args []string) int {\n\t_, err := SyncRepository()\n\n\tif err != nil {\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n\nfunc (s *Sync) Synopsis() string {\n\treturn \"Synchronize local git repository with remote at once\"\n}\n\n\ntype status struct {\n\tc *cron.Cron\n\trepositories []string\n\tschedules []string\n}\n\nvar sharedStatus *status = newStatus()\n\n\n\n\nfunc GetStatus() *status {\n\treturn sharedStatus\n}\n\ntype StatusStart struct{}\n\nfunc (s *StatusStart) Help() string {\n\treturn \"glr status start Help\"\n}\n\nfunc (s *StatusStart) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.AddFunc(\"@hourly\", func() {\n\t\tSyncRepository()\n\t})\n\tfmt.Println(\"set job schedule\")\n\tstatus.c.Start()\n\n\treturn 0\n}\n\nfunc (s *StatusStart) Synopsis() string {\n\treturn \"Synchronize local git repository with remote\"\n}\n\ntype StatusStop struct{}\n\nfunc (s *StatusStop) Help() string {\n\treturn \"glr status stop Help\"\n}\n\nfunc (s *StatusStop) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.Stop()\n\tfmt.Println(\"stop job scheduler\")\n\n\treturn 0\n}\n\nfunc (s *StatusStop) Synopsis() string {\n\treturn \"Stop cron scheduler\"\n}\n\nfunc newStatus() *status ", "output": "{\n\treturn &status{\n\t\tc: cron.New(),\n\t}\n}"} {"input": "package syncutil\n\nimport (\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\ntype TimedMutex struct {\n\tmu *Mutex \n\tlockedAt time.Time \n\tisLocked int32 \n\n\tcb TimingFn\n}\n\n\n\n\ntype TimingFn func(heldFor time.Duration)\n\n\n\n\nfunc ThresholdLogger(\n\tctx context.Context,\n\twarnDuration time.Duration,\n\tprintf func(context.Context, string, ...interface{}),\n\trecord TimingFn,\n) TimingFn {\n\treturn func(heldFor time.Duration) {\n\t\trecord(heldFor)\n\t\tif heldFor > warnDuration {\n\t\t\tpc, _, _, ok := runtime.Caller(2)\n\t\t\tfun := \"?\"\n\t\t\tif ok {\n\t\t\t\tif f := runtime.FuncForPC(pc); f != nil {\n\t\t\t\t\tfun = f.Name()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprintf(\n\t\t\t\tctx, \"mutex held by %s for %s (>%s):\\n%s\",\n\t\t\t\tfun, heldFor, warnDuration, debug.Stack(),\n\t\t\t)\n\t\t}\n\t}\n}\n\n\n\n\n\nfunc MakeTimedMutex(cb TimingFn) TimedMutex {\n\treturn TimedMutex{\n\t\tcb: cb,\n\t\tmu: &Mutex{},\n\t}\n}\n\n\nfunc (tm *TimedMutex) Lock() {\n\ttm.mu.Lock()\n\tatomic.StoreInt32(&tm.isLocked, 1)\n\ttm.lockedAt = time.Now()\n}\n\n\nfunc (tm *TimedMutex) Unlock() {\n\tlockedAt := tm.lockedAt\n\tatomic.StoreInt32(&tm.isLocked, 0)\n\ttm.mu.Unlock()\n\tif tm.cb != nil {\n\t\ttm.cb(time.Since(lockedAt))\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (tm *TimedMutex) AssertHeld() ", "output": "{\n\tisLocked := atomic.LoadInt32(&tm.isLocked)\n\tif isLocked == 0 {\n\t\tpanic(\"mutex is not locked\")\n\t}\n}"} {"input": "package testutil\n\nimport (\n\t\"testing\"\n\n\t\"github.com/tendermint/abci/server\"\n\twire \"github.com/tendermint/go-wire\"\n\t\"github.com/tendermint/merkleeyes/app\"\n\teyes \"github.com/tendermint/merkleeyes/client\"\n\t. \"github.com/tendermint/tmlibs/common\"\n)\n\n\n\n\n\nfunc MakeTxKV() ([]byte, []byte, []byte) {\n\tk := []byte(RandStr(8))\n\tv := []byte(RandStr(8))\n\treturn k, v, makeSet(k, v)\n}\n\n\n\nfunc makeSet(key, value []byte) []byte {\n\ttx := make([]byte, 1+wire.ByteSliceSize(key)+wire.ByteSliceSize(value))\n\tbuf := tx\n\tbuf[0] = app.TxTypeSet \n\tbuf = buf[1:]\n\tn, err := wire.PutByteSlice(buf, key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tbuf = buf[n:]\n\tn, err = wire.PutByteSlice(buf, value)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn tx\n}\n\nfunc CreateEyes(t *testing.T) (svr Service, cli *eyes.Client) ", "output": "{\n\taddr := \"unix://eyes.sock\"\n\n\tmApp := app.NewMerkleEyesApp(\"\", 0)\n\tsvr, err := server.NewServer(addr, \"socket\", mApp)\n\tif err != nil {\n\t\t(err.Error())\n\t\treturn\n\t}\n\n\tcli, err = eyes.NewClient(addr)\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t\treturn\n\t}\n\n\treturn svr, cli\n}"} {"input": "package vrfrontend\n\nimport (\n\t\"errors\"\n\n\t\"github.com/mjibson/go-dsp/fft\"\n\t\"github.com/mjibson/go-dsp/window\"\n)\n\n\n\nfunc ApplyWindow(signal []float64, window []float64) ([]float64, error) ", "output": "{\n\tret := make([]float64, len(signal))\n\tif len(signal) != len(window) {\n\t\treturn ret, errors.New(\"signal size is not equal to window\")\n\t}\n\n\tfor i, w := range window {\n\t\tret[i] = signal[i] * w\n\t}\n\treturn ret, nil\n}"} {"input": "package vm\n\nimport (\n\t\"math/big\"\n\n\t\"github.com/ariseid/ariseid-core/common\"\n)\n\n\n\n\ntype destinations map[common.Hash][]byte\n\n\nfunc (d destinations) has(codehash common.Hash, code []byte, dest *big.Int) bool {\n\tudest := dest.Uint64()\n\tif dest.BitLen() >= 63 || udest >= uint64(len(code)) {\n\t\treturn false\n\t}\n\n\tm, analysed := d[codehash]\n\tif !analysed {\n\t\tm = jumpdests(code)\n\t\td[codehash] = m\n\t}\n\treturn (m[udest/8] & (1 << (udest % 8))) != 0\n}\n\n\n\n\n\nfunc jumpdests(code []byte) []byte ", "output": "{\n\tm := make([]byte, len(code)/8+1)\n\tfor pc := uint64(0); pc < uint64(len(code)); pc++ {\n\t\top := OpCode(code[pc])\n\t\tif op == JUMPDEST {\n\t\t\tm[pc/8] |= 1 << (pc % 8)\n\t\t} else if op >= PUSH1 && op <= PUSH32 {\n\t\t\ta := uint64(op) - uint64(PUSH1) + 1\n\t\t\tpc += a\n\t\t}\n\t}\n\treturn m\n}"} {"input": "package autostart\n\nimport (\n\t\"flag\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/vim25/types\"\n)\n\ntype add struct {\n\t*AutostartFlag\n}\n\nfunc init() {\n\tcli.Register(\"host.autostart.add\", &add{})\n}\n\nfunc (cmd *add) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.AutostartFlag, ctx = newAutostartFlag(ctx)\n\tcmd.AutostartFlag.Register(ctx, f)\n}\n\n\n\nfunc (cmd *add) Usage() string {\n\treturn \"VM...\"\n}\n\nfunc (cmd *add) Run(ctx context.Context, f *flag.FlagSet) error {\n\tvar powerInfo = types.AutoStartPowerInfo{\n\t\tStartAction: \"powerOn\",\n\t\tStartDelay: -1,\n\t\tStartOrder: -1,\n\t\tStopAction: \"systemDefault\",\n\t\tStopDelay: -1,\n\t\tWaitForHeartbeat: types.AutoStartWaitHeartbeatSettingSystemDefault,\n\t}\n\n\treturn cmd.ReconfigureVMs(f.Args(), powerInfo)\n}\n\nfunc (cmd *add) Process(ctx context.Context) error ", "output": "{\n\tif err := cmd.AutostartFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package uaa\n\nimport (\n\t\"sort\"\n\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n)\n\ntype Prompt struct {\n\tKey string \n\tType string \n\tLabel string \n}\n\ntype PromptAnswer struct {\n\tKey string \n\tValue string\n}\n\nfunc (p Prompt) IsPassword() bool { return p.Type == \"password\" }\n\ntype PromptsResp struct {\n\tPrompts map[string][]string \n}\n\nfunc (u UAAImpl) Prompts() ([]Prompt, error) {\n\tresp, err := u.client.Prompts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar prompts []Prompt\n\n\tfor key, pair := range resp.Prompts {\n\t\tprompts = append(prompts, Prompt{\n\t\t\tKey: key,\n\t\t\tType: pair[0],\n\t\t\tLabel: pair[1],\n\t\t})\n\t}\n\n\tsort.Sort(PromptSorting(prompts))\n\n\treturn prompts, nil\n}\n\n\n\ntype PromptSorting []Prompt\n\nfunc (s PromptSorting) Len() int { return len(s) }\nfunc (s PromptSorting) Less(i, j int) bool { return s[i].Type > s[j].Type }\nfunc (s PromptSorting) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (c Client) Prompts() (PromptsResp, error) ", "output": "{\n\tvar resp PromptsResp\n\n\terr := c.clientRequest.Get(\"/login\", &resp)\n\tif err != nil {\n\t\treturn resp, bosherr.WrapError(err, \"Requesting UAA prompts\")\n\t}\n\n\treturn resp, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"thezombie.net/libgojira\"\n)\n\nfunc init() {\n\tparser.AddCommand(\"rank\",\n\t\t\"Rank Jira stories\",\n\t\t\"The rank command allows a user to modify story ranks\",\n\t\t&rankCommand)\n\n}\n\n\ntype RankCommand struct {\n}\n\nfunc (rc *RankCommand) Usage() string {\n\treturn \"gojira rank TASK-1 TASK-2 TASK-3 TASK-4\"\n}\n\nvar rankCommand RankCommand\n\n\n\nfunc (rc *RankCommand) Execute(args []string) error ", "output": "{\n\tif len(args) < 3 {\n\t\treturn fmt.Errorf(\"Need at least 3 arguments. Usage: %s\", rc.Usage)\n\t}\n\ttarget := args[len(args)-1]\n\tbefore_or_after := strings.ToLower(args[len(args)-2])\n\ttasks := args[:len(args)-2]\n\n\tif before_or_after != \"before\" && before_or_after != \"after\" {\n\t\treturn fmt.Errorf(\"second last parameter needs to be 'before' or 'after'\")\n\t}\n\n\tfmt.Println(\"target\", target)\n\tjc := libgojira.NewJiraClient(options)\n\terr := jc.ChangeRank(tasks, before_or_after, target)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package datastructures\n\n\ntype Comparable interface {\n\tCompare(Comparable) int\n}\n\n\ntype Comparables []Comparable\n\n\nfunc (cs Comparables) Len() int {\n\treturn len(cs)\n}\n\n\nfunc (cs Comparables) Less(i, j int) bool {\n\tif cs[i].Compare(cs[j]) < 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\n\n\n\nfunc (cs Comparables) Swap(i, j int) {\n\tcs[i], cs[j] = cs[j], cs[i]\n}\n\n\ntype IntComparable int\n\n\nfunc (ic IntComparable) Compare(i Comparable) int {\n\tother, ok := i.(IntComparable)\n\n\tif !ok {\n\t\tpanic(\"param should be an intComparable\")\n\t}\n\n\tif int(ic) == int(other) {\n\t\treturn 0\n\t} else if int(ic) < int(other) {\n\t\treturn -1\n\t} else {\n\t\treturn 1\n\t}\n}\n\nfunc (cs *Comparables) Shift() Comparable ", "output": "{\n\tif len(*cs) == 0 {\n\t\treturn nil\n\t}\n\n\tf := (*cs)[0]\n\t*cs = (*cs)[1:]\n\treturn f\n}"} {"input": "package logrus\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\nvar loggerFields = Fields{\n\t\"foo\": \"bar\",\n\t\"baz\": \"qux\",\n\t\"one\": \"two\",\n\t\"three\": \"four\",\n}\n\nfunc BenchmarkDummyLogger(b *testing.B) {\n\tnullf, err := os.OpenFile(\"/dev/null\", os.O_WRONLY, 0666)\n\tif err != nil {\n\t\tb.Fatalf(\"%v\", err)\n\t}\n\tdefer nullf.Close()\n\tdoLoggerBenchmark(b, nullf, &TextFormatter{DisableColors: true}, smallFields)\n}\n\nfunc BenchmarkDummyLoggerNoLock(b *testing.B) {\n\tnullf, err := os.OpenFile(\"/dev/null\", os.O_WRONLY|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tb.Fatalf(\"%v\", err)\n\t}\n\tdefer nullf.Close()\n\tdoLoggerBenchmarkNoLock(b, nullf, &TextFormatter{DisableColors: true}, smallFields)\n}\n\nfunc doLoggerBenchmark(b *testing.B, out *os.File, formatter Formatter, fields Fields) {\n\tlogger := Logger{\n\t\tOut: out,\n\t\tLevel: InfoLevel,\n\t\tFormatter: formatter,\n\t}\n\tentry := logger.WithFields(fields)\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tentry.Info(\"aaa\")\n\t\t}\n\t})\n}\n\n\n\nfunc doLoggerBenchmarkNoLock(b *testing.B, out *os.File, formatter Formatter, fields Fields) ", "output": "{\n\tlogger := Logger{\n\t\tOut: out,\n\t\tLevel: InfoLevel,\n\t\tFormatter: formatter,\n\t}\n\tlogger.SetNoLock()\n\tentry := logger.WithFields(fields)\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tentry.Info(\"aaa\")\n\t\t}\n\t})\n}"} {"input": "package version\n\nimport (\n\tapi \"github.com/containerd/containerd/api/services/version\"\n\t\"github.com/containerd/containerd/plugin\"\n\tctrdversion \"github.com/containerd/containerd/version\"\n\tempty \"github.com/golang/protobuf/ptypes/empty\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\nvar _ api.VersionServer = &Service{}\n\nfunc init() {\n\tplugin.Register(\"version-grpc\", &plugin.Registration{\n\t\tType: plugin.GRPCPlugin,\n\t\tInit: New,\n\t})\n}\n\nfunc New(ic *plugin.InitContext) (interface{}, error) {\n\treturn &Service{}, nil\n}\n\ntype Service struct {\n}\n\nfunc (s *Service) Register(server *grpc.Server) error {\n\tapi.RegisterVersionServer(server, s)\n\treturn nil\n}\n\n\n\nfunc (s *Service) Version(ctx context.Context, _ *empty.Empty) (*api.VersionResponse, error) ", "output": "{\n\treturn &api.VersionResponse{\n\t\tVersion: ctrdversion.Version,\n\t\tRevision: ctrdversion.Revision,\n\t}, nil\n}"} {"input": "package render\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gogo/protobuf/proto\"\n\t\"github.com/pkg/errors\"\n)\n\nvar pbContentType = []string{\"application/x-protobuf\"}\n\n\nfunc (r PB) Render(w http.ResponseWriter) error {\n\tif r.TTL <= 0 {\n\t\tr.TTL = 1\n\t}\n\treturn writePB(w, r)\n}\n\n\nfunc (r PB) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, pbContentType)\n}\n\n\n\nfunc writePB(w http.ResponseWriter, obj PB) (err error) ", "output": "{\n\tvar pbBytes []byte\n\twriteContentType(w, pbContentType)\n\n\tif pbBytes, err = proto.Marshal(&obj); err != nil {\n\t\terr = errors.WithStack(err)\n\t\treturn\n\t}\n\n\tif _, err = w.Write(pbBytes); err != nil {\n\t\terr = errors.WithStack(err)\n\t}\n\treturn\n}"} {"input": "package machine\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestStorage_create (t *testing.T) ", "output": "{\n\t_, err := NewStorage(\"tests.db\", true)\n\tif err != nil {\n\t\tt.Failed()\n\t}\n\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSOpsWorksApp_Source struct {\n\n\tPassword string `json:\"Password,omitempty\"`\n\n\tRevision string `json:\"Revision,omitempty\"`\n\n\tSshKey string `json:\"SshKey,omitempty\"`\n\n\tType string `json:\"Type,omitempty\"`\n\n\tUrl string `json:\"Url,omitempty\"`\n\n\tUsername string `json:\"Username,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSOpsWorksApp_Source) AWSCloudFormationType() string {\n\treturn \"AWS::OpsWorks::App.Source\"\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\n\n\n\n\nfunc (r *AWSOpsWorksApp_Source) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSOpsWorksApp_Source) SetDependsOn(dependencies []string) ", "output": "{\n\tr._dependsOn = dependencies\n}"} {"input": "package cmd\n\nimport \"testing\"\n\n\n\nfunc TestGetInterfaceIPv4s(t *testing.T) ", "output": "{\n\tipv4s, err := getInterfaceIPv4s()\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error %s\", err)\n\t}\n\tfor _, ip := range ipv4s {\n\t\tif ip.To4() == nil {\n\t\t\tt.Fatalf(\"Unexpected expecting only IPv4 addresses only %s\", ip)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"os/exec\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n\nfunc getPing(c *gin.Context) {\n\tc.String(200, \"pong\")\n}\n\nfunc addRouteWithArg(name string, cmd string, router *gin.RouterGroup) {\n\tlog.Printf(\"Configuring route %v with command %s and argument\\n\", name, cmd)\n\tpath := name + \"/:arg\"\n\trouter.GET(path, func(c *gin.Context) {\n\t\targ := c.Params.ByName(\"arg\")\n\t\tif cmdOut, err := exec.Command(cmd, arg).Output(); err == nil {\n\t\t\tc.JSON(http.StatusOK, gin.H{\"status\": \"ok\", \"cmd\": string(cmd), \"argument\": string(arg), \"stdout\": string(cmdOut)})\n\t\t}\n\t})\n}\n\n\n\nfunc addRouteWithoutArg(name string, cmd string, router *gin.RouterGroup) ", "output": "{\n\tlog.Printf(\"Configuring route %s with command: %s\\n\", name, cmd)\n\trouter.GET(name, func(c *gin.Context) {\n\t\tif cmdOut, err := exec.Command(cmd).Output(); err == nil {\n\t\t\tc.JSON(http.StatusOK, gin.H{\"status\": \"ok\", \"cmd\": string(cmd), \"stdout\": string(cmdOut)})\n\t\t}\n\t})\n}"} {"input": "package v1beta1\n\nimport (\n\tfmt \"fmt\"\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\tapi \"k8s.io/kubernetes/pkg/api\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n)\n\ntype StorageV1beta1Interface interface {\n\tRESTClient() restclient.Interface\n\tStorageClassesGetter\n}\n\n\ntype StorageV1beta1Client struct {\n\trestClient restclient.Interface\n}\n\nfunc (c *StorageV1beta1Client) StorageClasses() StorageClassInterface {\n\treturn newStorageClasses(c)\n}\n\n\nfunc NewForConfig(c *restclient.Config) (*StorageV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := restclient.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &StorageV1beta1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *restclient.Config) *StorageV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c restclient.Interface) *StorageV1beta1Client {\n\treturn &StorageV1beta1Client{c}\n}\n\n\n\n\n\nfunc (c *StorageV1beta1Client) RESTClient() restclient.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc setConfigDefaults(config *restclient.Config) error ", "output": "{\n\tgv, err := schema.ParseGroupVersion(\"storage.k8s.io/v1beta1\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !api.Registry.IsEnabledVersion(gv) {\n\t\treturn fmt.Errorf(\"storage.k8s.io/v1beta1 is not enabled\")\n\t}\n\tconfig.APIPath = \"/apis\"\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = restclient.DefaultKubernetesUserAgent()\n\t}\n\tcopyGroupVersion := gv\n\tconfig.GroupVersion = ©GroupVersion\n\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: api.Codecs}\n\n\treturn nil\n}"} {"input": "package auth\n\nimport (\n\t\"sync\"\n\n\t\"github.com/google/martian/session\"\n)\n\nconst key = \"auth.Context\"\n\n\ntype Context struct {\n\tmu sync.RWMutex\n\tid string\n\terr error\n}\n\n\nfunc FromContext(ctx *session.Context) *Context {\n\tif v, ok := ctx.GetSession().Get(key); ok {\n\t\treturn v.(*Context)\n\t}\n\n\tactx := &Context{}\n\tctx.GetSession().Set(key, actx)\n\n\treturn actx\n}\n\n\nfunc (ctx *Context) ID() string {\n\tctx.mu.RLock()\n\tctx.mu.RUnlock()\n\n\treturn ctx.id\n}\n\n\nfunc (ctx *Context) SetID(id string) {\n\tctx.mu.Lock()\n\tctx.mu.Unlock()\n\n\tctx.err = nil\n\n\tif id == \"\" {\n\t\treturn\n\t}\n\n\tctx.id = id\n}\n\n\n\n\n\nfunc (ctx *Context) Error() error {\n\tctx.mu.RLock()\n\tdefer ctx.mu.RUnlock()\n\n\treturn ctx.err\n}\n\nfunc (ctx *Context) SetError(err error) ", "output": "{\n\tctx.mu.Lock()\n\tdefer ctx.mu.Unlock()\n\n\tctx.id = \"\"\n\tctx.err = err\n}"} {"input": "package jobs\n\nimport (\n\t\"github.com/simplemvc/gocorelib/cron\"\n\t\"github.com/simplemvc/gocorelib/revel\"\n\t\"strings\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype Func func()\n\nfunc (r Func) Run() { r() }\n\nfunc Schedule(spec string, job cron.Job) {\n\tif strings.HasPrefix(spec, \"cron.\") {\n\t\tconfSpec, found := revel.Config.String(spec)\n\t\tif !found {\n\t\t\tpanic(\"Cron spec not found: \" + spec)\n\t\t}\n\t\tspec = confSpec\n\t}\n\tMainCron.Schedule(cron.Parse(spec), New(job))\n}\n\n\n\n\nfunc Every(duration time.Duration, job cron.Job) {\n\tMainCron.Schedule(cron.Every(duration), New(job))\n}\n\n\n\n\n\nfunc In(duration time.Duration, job cron.Job) {\n\tgo func() {\n\t\ttime.Sleep(duration)\n\t\tNew(job).Run()\n\t}()\n}\n\nfunc Now(job cron.Job) ", "output": "{\n\tgo New(job).Run()\n}"} {"input": "package world\n\nimport \"fmt\"\n\ntype Zone struct {\n\tId string\n\tRooms map[string]*Room\n\tName string\n}\n\n\n\nfunc (z Zone) String() string ", "output": "{\n\treturn fmt.Sprintf(\"(Zone %s: '%s')\", z.Id, z.Name)\n}"} {"input": "package text\n\nimport \"fmt\"\n\nconst (\n\tredCode = \"\\x1b[31m\"\n\tgreenCode = \"\\x1b[32m\"\n\tyellowCode = \"\\x1b[33m\"\n\tblueCode = \"\\x1b[34m\"\n\tmagentaCode = \"\\x1b[35m\"\n\tCyanCode = \"\\x1b[36m\"\n\tboldCode = \"\\x1b[1m\"\n\n\tResetCode = \"\\x1b[0m\"\n)\n\n\nvar UseColor = true\n\nfunc stylize(startCode, in string) string {\n\tif UseColor {\n\t\treturn startCode + in + ResetCode\n\t}\n\n\treturn in\n}\n\nfunc Red(in string) string {\n\treturn stylize(redCode, in)\n}\n\nfunc Green(in string) string {\n\treturn stylize(greenCode, in)\n}\n\n\n\nfunc Cyan(in string) string {\n\treturn stylize(CyanCode, in)\n}\n\nfunc Magenta(in string) string {\n\treturn stylize(magentaCode, in)\n}\n\nfunc Blue(in string) string {\n\treturn stylize(blueCode, in)\n}\n\nfunc Bold(in string) string {\n\treturn stylize(boldCode, in)\n}\n\n\n\nfunc ColorHash(name string) (output string) {\n\tif !UseColor {\n\t\treturn name\n\t}\n\n\tvar hash uint = 5381\n\n\tfor i := 0; i < len(name); i++ {\n\t\thash = uint(name[i]) + ((hash << 5) + (hash))\n\t}\n\n\treturn fmt.Sprintf(\"\\x1b[%dm%s\\x1b[0m\", hash%6+31, name)\n}\n\nfunc yellow(in string) string ", "output": "{\n\treturn stylize(yellowCode, in)\n}"} {"input": "package dodo\n\n\nfunc NewPropertyIndex() *propertyIndex {\n\n\treturn &propertyIndex{\n\t\tpropertyIndexMap: map[string]map[string]int{},\n\t}\n}\n\ntype propertyIndex struct {\n\tpropertyIndexMap map[string]map[string]int\n}\n\nfunc (p *propertyIndex) index(container, property string) *int {\n\n\tindexMap, exists := p.propertyIndexMap[container]\n\tif !exists {\n\t\treturn nil\n\t}\n\n\tindex, exists := indexMap[property]\n\tif !exists {\n\t\treturn nil\n\t}\n\n\treturn &index\n}\n\n\n\nfunc (p *propertyIndex) incrementIndex(container, property string) *int ", "output": "{\n\n\tindexMap, exists := p.propertyIndexMap[container]\n\tif !exists {\n\t\tindexMap = map[string]int{}\n\t\tp.propertyIndexMap[container] = indexMap\n\t}\n\n\tindex, exists := indexMap[property]\n\tif !exists {\n\t\tindex = 0\n\t\tindexMap[property] = index\n\t} else {\n\t\tindex++\n\t\tindexMap[property] = index\n\t}\n\n\treturn &index\n}"} {"input": "package tracking\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n)\n\ntype trackCargoRequest struct {\n\tID string\n}\n\ntype trackCargoResponse struct {\n\tCargo *Cargo `json:\"cargo,omitempty\"`\n\tErr error `json:\"error,omitempty\"`\n}\n\nfunc (r trackCargoResponse) error() error { return r.Err }\n\n\n\nfunc makeTrackCargoEndpoint(ts Service) endpoint.Endpoint ", "output": "{\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\treq := request.(trackCargoRequest)\n\t\tc, err := ts.Track(req.ID)\n\t\treturn trackCargoResponse{Cargo: &c, Err: err}, nil\n\t}\n}"} {"input": "package rediscmd\n\n\n\nfunc Bytes(s string) []byte {\n\treturn []byte(s)\n}\n\nfunc String(b []byte) string ", "output": "{\n\treturn string(b)\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n\n\nfunc handlePing(c *gin.Context) ", "output": "{\n\tc.JSON(http.StatusOK, gin.H{\"hello\": \"world!\", \"goto\": \"https://github.com/treeder/functions\"})\n}"} {"input": "package echo\n\ntype (\n\tGroup struct {\n\t\techo Echo\n\t}\n)\n\nfunc (g *Group) Use(m ...Middleware) {\n\tfor _, h := range m {\n\t\tg.echo.middleware = append(g.echo.middleware, wrapMiddleware(h))\n\t}\n}\n\nfunc (g *Group) Connect(path string, h Handler) {\n\tg.echo.Connect(path, h)\n}\n\n\n\nfunc (g *Group) Get(path string, h Handler) {\n\tg.echo.Get(path, h)\n}\n\nfunc (g *Group) Head(path string, h Handler) {\n\tg.echo.Head(path, h)\n}\n\nfunc (g *Group) Options(path string, h Handler) {\n\tg.echo.Options(path, h)\n}\n\nfunc (g *Group) Patch(path string, h Handler) {\n\tg.echo.Patch(path, h)\n}\n\nfunc (g *Group) Post(path string, h Handler) {\n\tg.echo.Post(path, h)\n}\n\nfunc (g *Group) Put(path string, h Handler) {\n\tg.echo.Put(path, h)\n}\n\nfunc (g *Group) Trace(path string, h Handler) {\n\tg.echo.Trace(path, h)\n}\n\nfunc (g *Group) WebSocket(path string, h HandlerFunc) {\n\tg.echo.WebSocket(path, h)\n}\n\nfunc (g *Group) Static(path, root string) {\n\tg.echo.Static(path, root)\n}\n\nfunc (g *Group) ServeDir(path, root string) {\n\tg.echo.ServeDir(path, root)\n}\n\nfunc (g *Group) ServeFile(path, file string) {\n\tg.echo.ServeFile(path, file)\n}\n\nfunc (g *Group) Group(prefix string, m ...Middleware) *Group {\n\treturn g.echo.Group(prefix, m...)\n}\n\nfunc (g *Group) Delete(path string, h Handler) ", "output": "{\n\tg.echo.Delete(path, h)\n}"} {"input": "package parsing\n\nimport (\n\t\"testing\"\n)\n\n\n\n\nfunc TestParseIntOrDefault(t *testing.T) {\n\tout := ParseIntOrDefault(\"4\", 0)\n\tif out != 4 {\n\t\tt.Errorf(\"Unexpected output from ParseIntOrDefault: %s\", out)\n\t}\n\tout = ParseIntOrDefault(\"\", 5)\n\tif out != 5 {\n\t\tt.Errorf(\"Unexpected output from ParseIntOrDefault default: %s\", out)\n\t}\n}\n\nfunc TestParseYesOrNo(t *testing.T) {\n\tif !ParseYesOrNo(\"YES\") {\n\t\tt.Errorf(\"ParseYesOrNo returned false when it should return true\")\n\t}\n\tif !ParseYesOrNo(\"yes\") {\n\t\tt.Errorf(\"ParseYesOrNo returned false when it should return true\")\n\t}\n}\n\nfunc TestConcatIfNotEmpty(t *testing.T) ", "output": "{\n\tx := \"Hello World\"\n\toutput := ConcatIfNotEmpty(\" \", \"Hello\", \"\", \"World\")\n\tif x != output {\n\t\tt.Errorf(\"Unexpected output from ConcatIfNotEmpty: %s\", output)\n\t}\n}"} {"input": "package printer\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/resoursea/api\"\n)\n\nfunc Router(rt api.Router) {\n\tfmt.Println(\"\\n--- PRINT ROUTER ---\\n\")\n\trouter(rt, 0)\n\tfmt.Println(\"\\n--- END PRINT ---\\n\")\n}\n\nfunc router(r api.Router, lvl int) {\n\tfmt.Printf(\"%sRoute: %s\\n\", strings.Repeat(\"\t\", lvl), r)\n\n\tfor _, m := range r.Methods() {\n\t\thandler(m, lvl)\n\t}\n\n\tfor _, c := range r.Children() {\n\t\tif r.IsSlice() {\n\t\t\trouter(c, lvl)\n\t\t} else {\n\t\t\trouter(c, lvl+1)\n\t\t}\n\t}\n}\n\n\n\nfunc handler(m api.Method, lvl int) ", "output": "{\n\tfmt.Printf(\"%s- Method: %s\\n\", strings.Repeat(\"\t\", lvl), m)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/gorilla/schema\"\n\t\"github.com/jordic/k8s/cloudsqlip/Godeps/_workspace/src/github.com/emicklei/go-restful\"\n\t\"io\"\n\t\"net/http\"\n)\n\n\n\n\n\n\n\ntype Profile struct {\n\tName string\n\tAge int\n}\n\nvar decoder *schema.Decoder\n\nfunc main() {\n\tdecoder = schema.NewDecoder()\n\tws := new(restful.WebService)\n\tws.Route(ws.POST(\"/profiles\").Consumes(\"application/x-www-form-urlencoded\").To(postAdddress))\n\tws.Route(ws.GET(\"/profiles\").To(addresssForm))\n\trestful.Add(ws)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\n\n\nfunc addresssForm(req *restful.Request, resp *restful.Response) {\n\tio.WriteString(resp.ResponseWriter,\n\t\t`\n\t\t\n\t\t

Enter Profile

\n\t\t
\n\t\t \n\t\t\t\n\t\t\t\n\t\t \n\t\t\t\n\t\t
\n\t\t\n\t\t`)\n}\n\nfunc postAdddress(req *restful.Request, resp *restful.Response) ", "output": "{\n\terr := req.Request.ParseForm()\n\tif err != nil {\n\t\tresp.WriteErrorString(http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tp := new(Profile)\n\terr = decoder.Decode(p, req.Request.PostForm)\n\tif err != nil {\n\t\tresp.WriteErrorString(http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tio.WriteString(resp.ResponseWriter, fmt.Sprintf(\"Name=%s, Age=%d\", p.Name, p.Age))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cloudfoundry/cli/plugin\"\n)\n\ntype TestWithPush struct {\n}\n\nfunc (c *TestWithPush) Run(cliConnection plugin.CliConnection, args []string) {\n\tif args[0] == \"push\" {\n\t\tthePushCmd()\n\t}\n}\n\n\n\nfunc thePushCmd() {\n\tfmt.Println(\"You called push in test_with_push\")\n}\n\nfunc main() {\n\tplugin.Start(new(TestWithPush))\n}\n\nfunc (c *TestWithPush) GetMetadata() plugin.PluginMetadata ", "output": "{\n\treturn plugin.PluginMetadata{\n\t\tName: \"TestWithPush\",\n\t\tCommands: []plugin.Command{\n\t\t\t{\n\t\t\t\tName: \"push\",\n\t\t\t\tHelpText: \"push text for test_with_push\",\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package profile\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\n\t\"github.com/sirupsen/logrus\"\n\n\t\"github.com/supergiant/control/pkg/storage\"\n)\n\nconst DefaultKubeProfilePreifx = \"/supergiant/profile\"\n\ntype Service struct {\n\tprefix string\n\tkubeProfileStorage storage.Interface\n}\n\n\n\nfunc (s *Service) Get(ctx context.Context, profileId string) (*Profile, error) {\n\tlogrus.Debugf(\"get cloud profile by id %s\", profileId)\n\tprofileData, err := s.kubeProfileStorage.Get(ctx, s.prefix, profileId)\n\tprofile := &Profile{}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = json.Unmarshal(profileData, profile)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn profile, nil\n}\n\nfunc (s *Service) Create(ctx context.Context, profile *Profile) error {\n\tprofileData, err := json.Marshal(profile)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.kubeProfileStorage.Put(ctx, s.prefix, profile.ID, profileData)\n}\n\nfunc (s *Service) GetAll(ctx context.Context) ([]Profile, error) {\n\tvar (\n\t\tprofiles []Profile\n\t\tprofile Profile\n\t)\n\n\tprofilesData, err := s.kubeProfileStorage.GetAll(ctx, s.prefix)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, profileData := range profilesData {\n\t\terr = json.Unmarshal(profileData, &profile)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tprofiles = append(profiles, profile)\n\t}\n\n\treturn profiles, nil\n}\n\nfunc NewService(prefix string, s storage.Interface) *Service ", "output": "{\n\treturn &Service{\n\t\tprefix: prefix,\n\t\tkubeProfileStorage: s,\n\t}\n}"} {"input": "package size\n\nimport (\n\t\"math\"\n\t\"time\"\n)\n\n\n\n\n\n\nfunc Rate(numBytes int64, dur time.Duration) (bytesPerSecond int64) {\n\treturn numBytes / int64(dur/time.Second)\n}\n\n\n\nfunc Duration(numBytes, bytesPerSecond int64) time.Duration {\n\tr := time.Duration(bytesPerSecond)\n\ts := time.Duration(numBytes)\n\tif s > math.MaxInt64/time.Second {\n\t\treturn s / r * time.Second\n\t}\n\treturn s * time.Second / r\n}\n\nfunc Size(bytesPerSecond int64, dur time.Duration) (numBytes int64) ", "output": "{\n\treturn bytesPerSecond * int64(dur/time.Second)\n}"} {"input": "package proxyprotocol\n\nimport (\n\t\"net\"\n)\n\ntype listener struct {\n\traw net.Listener\n}\n\nfunc Listen(raw net.Listener) net.Listener {\n\treturn &listener{raw}\n}\n\nfunc (l *listener) Accept() (c net.Conn, err error) {\n\traw, err := l.raw.Accept()\n\tif err == nil {\n\t\tc = &conn{\n\t\t\traw: raw,\n\t\t}\n\t}\n\treturn\n}\n\n\n\nfunc (l *listener) Addr() net.Addr {\n\treturn l.raw.Addr()\n}\n\nfunc (l *listener) Close() error ", "output": "{\n\treturn l.raw.Close()\n}"} {"input": "package leet_20\n\ntype Stack []byte\n\nfunc (s *Stack) Pop() byte {\n\tc := s.Top()\n\tlength := len(*s)\n\tif length <= 1 {\n\t\t*s = nil\n\t} else {\n\t\t*s = (*s)[:length-1]\n\t}\n\treturn c\n}\n\nfunc (s *Stack) Empty() bool {\n\treturn nil == s || *s == nil || len(*s) == 0\n}\n\nfunc (s *Stack) Push(x byte) {\n\t*s = append(*s, x)\n}\n\nfunc (s *Stack) Top() byte {\n\tlength := len(*s)\n\tif 0 == length {\n\t\treturn 0\n\t}\n\treturn (*s)[length-1]\n}\n\nfunc (s *Stack) String() string {\n\treturn string(*s)\n}\n\n\n\nfunc isValid(s string) bool {\n\tarr := []byte(s)\n\tstack := new(Stack)\n\tfor _, c := range arr {\n\t\tswitch c {\n\t\tcase '[', '{', '(':\n\t\t\tstack.Push(c)\n\t\t\tcontinue\n\t\t}\n\t\ttop := stack.Top()\n\t\tif match(top, c) {\n\t\t\tstack.Pop()\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn stack.Empty()\n}\n\nfunc match(a, b byte) bool ", "output": "{\n\tif a == '[' && b == ']' {\n\t\treturn true\n\t}\n\tif a == '(' && b == ')' {\n\t\treturn true\n\t}\n\tif a == '{' && b == '}' {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package mock\n\nimport (\n\t\"context\"\n\n\t\"github.com/pingcap/tidb/kv\"\n)\n\n\n\ntype Client struct {\n\tkv.RequestTypeSupportedChecker\n\tMockResponse kv.Response\n}\n\n\n\n\nfunc (c *Client) Send(ctx context.Context, req *kv.Request, kv interface{}, option *kv.ClientSendOption) kv.Response ", "output": "{\n\treturn c.MockResponse\n}"} {"input": "package api\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\n\n\n\n\n\n\n\n\nfunc (a *API) Attach(filename string) {\n\ta.path = filepath.Dir(filename)\n\tf, err := os.Open(filename)\n\tdefer f.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjson.NewDecoder(f).Decode(a)\n}\n\n\n\nfunc (a *API) AttachString(str string) {\n\tjson.Unmarshal([]byte(str), a)\n\n\tif !a.initialized {\n\t\ta.Setup()\n\t}\n}\n\n\nfunc (a *API) Setup() {\n\ta.unrecognizedNames = map[string]string{}\n\ta.writeShapeNames()\n\ta.resolveReferences()\n\ta.fixStutterNames()\n\ta.renameExportable()\n\ta.renameToplevelShapes()\n\ta.updateTopLevelShapeReferences()\n\ta.createInputOutputShapes()\n\ta.customizationPasses()\n\n\tif !a.NoRemoveUnusedShapes {\n\t\ta.removeUnusedShapes()\n\t}\n\n\tif len(a.unrecognizedNames) > 0 {\n\t\tmsg := []string{\n\t\t\t\"Unrecognized inflections for the following export names:\",\n\t\t\t\"(Add these to inflections.csv with any inflections added after the ':')\",\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"%s\\n%s\\n\\n\", msg[0], msg[1])\n\t\tfor n, m := range a.unrecognizedNames {\n\t\t\tif n == m {\n\t\t\t\tm = \"\"\n\t\t\t}\n\t\t\tfmt.Fprintf(os.Stderr, \"%s:%s\\n\", n, m)\n\t\t}\n\t\tos.Stderr.WriteString(\"\\n\\n\")\n\t\tpanic(\"Found unrecognized exported names in API \" + a.PackageName())\n\t}\n\n\ta.initialized = true\n}\n\nfunc Load(api, docs, paginators, waiters string) *API ", "output": "{\n\ta := API{}\n\ta.Attach(api)\n\ta.Attach(docs)\n\ta.Attach(paginators)\n\ta.Attach(waiters)\n\ta.Setup()\n\treturn &a\n}"} {"input": "package libkb\n\nimport (\n\tkeybase1 \"github.com/keybase/client/go/protocol/keybase1\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\nfunc NormalizeSocialAssertion(ctx AssertionContext, s string) (keybase1.SocialAssertion, bool) {\n\turl, err := ParseAssertionURL(ctx, s, true)\n\tif err != nil || !url.IsRemote() {\n\t\treturn keybase1.SocialAssertion{}, false\n\t}\n\treturn keybase1.SocialAssertion{\n\t\tUser: url.GetValue(),\n\t\tService: keybase1.SocialAssertionService(url.GetKey()),\n\t}, true\n}\n\nfunc IsSocialAssertion(ctx AssertionContext, s string) bool ", "output": "{\n\t_, ok := NormalizeSocialAssertion(ctx, s)\n\treturn ok\n}"} {"input": "package circonusgometrics\n\nimport (\n\t\"sync\"\n\n\t\"github.com/circonus-labs/circonusllhist\"\n)\n\n\ntype Histogram struct {\n\tname string\n\thist *circonusllhist.Histogram\n\trw sync.RWMutex\n}\n\n\nfunc (m *CirconusMetrics) Timing(metric string, val float64) {\n\tm.SetHistogramValue(metric, val)\n}\n\n\nfunc (m *CirconusMetrics) RecordValue(metric string, val float64) {\n\tm.SetHistogramValue(metric, val)\n}\n\n\nfunc (m *CirconusMetrics) SetHistogramValue(metric string, val float64) {\n\tm.NewHistogram(metric)\n\n\tm.histograms[metric].rw.Lock()\n\tdefer m.histograms[metric].rw.Unlock()\n\n\tm.histograms[metric].hist.RecordValue(val)\n}\n\n\nfunc (m *CirconusMetrics) RemoveHistogram(metric string) {\n\tm.hm.Lock()\n\tdefer m.hm.Unlock()\n\tdelete(m.histograms, metric)\n}\n\n\nfunc (m *CirconusMetrics) NewHistogram(metric string) *Histogram {\n\tm.hm.Lock()\n\tdefer m.hm.Unlock()\n\n\tif hist, ok := m.histograms[metric]; ok {\n\t\treturn hist\n\t}\n\n\thist := &Histogram{\n\t\tname: metric,\n\t\thist: circonusllhist.New(),\n\t}\n\n\tm.histograms[metric] = hist\n\n\treturn hist\n}\n\n\n\n\n\nfunc (h *Histogram) RecordValue(v float64) {\n\th.rw.Lock()\n\tdefer h.rw.Unlock()\n\n\th.hist.RecordValue(v)\n}\n\nfunc (h *Histogram) Name() string ", "output": "{\n\treturn h.name\n}"} {"input": "package match\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\n\n\nfunc IsNil(t *testing.T, value interface{}) *Matcher {\n\treturn Match(t, value).IsNil()\n}\n\n\nfunc IsNotNil(t *testing.T, value interface{}) *Matcher {\n\treturn Match(t, value).IsNotNil()\n}\n\n\nfunc Equals(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).Equals(other)\n}\n\n\nfunc NotEquals(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).NotEquals(other)\n}\n\n\nfunc LessThan(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).LessThan(other)\n}\n\n\nfunc GreaterThan(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).GreaterThan(other)\n}\n\n\nfunc Contains(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).Contains(other)\n}\n\n\nfunc Matches(t *testing.T, value interface{}, pattern string) *Matcher {\n\treturn Match(t, value).Matches(pattern)\n}\n\n\nfunc KindOf(t *testing.T, value interface{}, kind reflect.Kind) *Matcher {\n\treturn Match(t, value).KindOf(kind)\n}\n\nfunc Match(t *testing.T, value interface{}) *Matcher ", "output": "{\n\treturn &Matcher{\n\t\tt: t,\n\t\tvalue: value,\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\nfunc InfoHashToMagnet(ih string, name string, trackers ...string) (str string) ", "output": "{\n\tstr = fmt.Sprintf(\"magnet:?xt=urn:btih:%s\", ih)\n\tif len(name) > 0 {\n\t\tstr += fmt.Sprintf(\"&dn=%s\", name)\n\t}\n\tfor idx := range trackers {\n\t\tstr += fmt.Sprintf(\"&tr=%s\", trackers[idx])\n\t}\n\treturn\n}"} {"input": "package fs\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nconst (\n\tWindowsTempPrefix = \"~syncthing~\"\n\tUnixTempPrefix = \".syncthing.\"\n)\n\nvar TempPrefix string\n\n\n\n\nconst maxFilenameLength = 160 - len(UnixTempPrefix) - len(\".tmp\")\n\nfunc init() {\n\tif runtime.GOOS == \"windows\" {\n\t\tTempPrefix = WindowsTempPrefix\n\t} else {\n\t\tTempPrefix = UnixTempPrefix\n\t}\n}\n\n\n\n\n\n\nfunc TempName(name string) string {\n\ttdir := filepath.Dir(name)\n\ttbase := filepath.Base(name)\n\tif len(tbase) > maxFilenameLength {\n\t\thash := md5.New()\n\t\thash.Write([]byte(name))\n\t\ttbase = fmt.Sprintf(\"%x\", hash.Sum(nil))\n\t}\n\ttname := fmt.Sprintf(\"%s%s.tmp\", TempPrefix, tbase)\n\treturn filepath.Join(tdir, tname)\n}\n\nfunc IsTemporary(name string) bool ", "output": "{\n\tname = filepath.Base(name)\n\tif strings.HasPrefix(name, WindowsTempPrefix) ||\n\t\tstrings.HasPrefix(name, UnixTempPrefix) {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package bc\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n)\n\ntype Bc interface {\n\tExec(string) error\n\tQuit()\n}\n\ntype bc struct {\n\tcmd *exec.Cmd\n\tstdin io.WriteCloser\n\tstdout io.ReadCloser\n}\n\n\n\n\nvar inputSuffix = []byte(\"\\n\\\"\\x04\\\"\\n\")\n\nfunc (bc *bc) Exec(code string) error {\n\tbc.stdin.Write([]byte(code))\n\tbc.stdin.Write(inputSuffix)\n\tfor {\n\t\tb, err := readByte(bc.stdout)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif b == 0x04 {\n\t\t\tbreak\n\t\t}\n\t\tos.Stdout.Write([]byte{b})\n\t}\n\treturn nil\n}\n\nfunc readByte(r io.Reader) (byte, error) {\n\tvar buf [1]byte\n\t_, err := r.Read(buf[:])\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn buf[0], nil\n}\n\nfunc (bc *bc) Quit() {\n\tbc.stdin.Close()\n\tbc.cmd.Wait()\n\tbc.stdout.Close()\n}\n\nfunc Start() Bc ", "output": "{\n\tcmd := exec.Command(\"bc\")\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcmd.Stderr = os.Stderr\n\tcmd.Start()\n\treturn &bc{cmd, stdin, stdout}\n}"} {"input": "package lexer\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc EqualSentences(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n\n\nfunc TestLexer(t *testing.T) {\n\ts := strings.NewReader(`foo bar; spaces \"and quotes\"; \"es\\\"ca\\\\p e\"`)\n\tz := New(s)\n\n\tAssertNextSentence(z, t, []string{\"foo\", \"bar\"})\n\tAssertNextSentence(z, t, []string{\"spaces\", \"and quotes\"})\n\tAssertNextSentence(z, t, []string{`es\"ca\\p e`})\n}\n\nfunc TestSplit(t *testing.T) {\n\tss, err := Split(\"foo bar baz\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif len(ss) != 1 {\n\t\tt.Errorf(\"bad result: %s\", ss)\n\t}\n\tif !EqualSentences(ss[0], []string{\"foo\", \"bar\", \"baz\"}) {\n\t\tt.Errorf(\"bad result: %s\", ss)\n\t}\n}\n\nfunc AssertNextSentence(l *Lexer, t *testing.T, a []string) ", "output": "{\n\tb, _ := l.NextSentence()\n\n\tif !EqualSentences(a, b) {\n\t\tt.Errorf(\"bad sentence: '%s' VS '%s'\", a, b)\n\t}\n}"} {"input": "package app\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc TestAppPgcCont(t *testing.T) {\n\tvar (\n\t\tc = context.Background()\n\t\tid = int(0)\n\t\tlimit = int(10)\n\t)\n\tconvey.Convey(\"PgcCont\", t, func(ctx convey.C) {\n\t\tres, err := d.PgcCont(c, id, limit)\n\t\tctx.Convey(\"Then err should be nil.res should not be nil.\", func(ctx convey.C) {\n\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\tctx.So(res, convey.ShouldNotBeNil)\n\t\t})\n\t})\n}\n\n\n\nfunc TestAppPgcContCount(t *testing.T) ", "output": "{\n\tvar (\n\t\tc = context.Background()\n\t)\n\tconvey.Convey(\"PgcContCount\", t, func(ctx convey.C) {\n\t\tupCnt, err := d.PgcContCount(c)\n\t\tctx.Convey(\"Then err should be nil.upCnt should not be nil.\", func(ctx convey.C) {\n\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\tctx.So(upCnt, convey.ShouldNotBeNil)\n\t\t})\n\t})\n}"} {"input": "package types\n\nimport (\n\t\"encoding/json\"\n)\n\n\n\n\ntype FilteredString struct {\n\tIsSet bool\n\tValue string\n}\n\n\nfunc (n *FilteredString) ParseValue(val string) {\n\tif val == \"\" {\n\t\tn.IsSet = false\n\t\tn.Value = \"\"\n\t\treturn\n\t}\n\n\tn.IsSet = true\n\n\tswitch val {\n\tcase \"null\", \"default\":\n\t\tn.Value = \"\"\n\tdefault:\n\t\tn.Value = val\n\t}\n}\n\nfunc (n *FilteredString) UnmarshalJSON(rawJSON []byte) error {\n\tvar value *string\n\terr := json.Unmarshal(rawJSON, &value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif value != nil {\n\t\tn.Value = *value\n\t\tn.IsSet = true\n\t\treturn nil\n\t}\n\n\tn.Value = \"\"\n\tn.IsSet = false\n\treturn nil\n}\n\n\n\nfunc (n FilteredString) MarshalJSON() ([]byte, error) ", "output": "{\n\tif n.IsSet {\n\t\treturn json.Marshal(n.Value)\n\t}\n\n\treturn json.Marshal(nil)\n}"} {"input": "package eventual\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/getlantern/testify/assert\"\n)\n\nconst (\n\tconcurrency = 200\n)\n\nfunc TestSingle(t *testing.T) {\n\tv := NewValue()\n\tgo func() {\n\t\ttime.Sleep(20 * time.Millisecond)\n\t\tv.Set(\"hi\")\n\t}()\n\n\tr, ok := v.Get(10 * time.Millisecond)\n\tassert.False(t, ok, \"Get with short timeout should have timed out\")\n\n\tr, ok = v.Get(20 * time.Millisecond)\n\tassert.True(t, ok, \"Get with longer timeout should have succeed\")\n\tassert.Equal(t, \"hi\", r, \"Wrong result\")\n}\n\nfunc BenchmarkGet(b *testing.B) {\n\tv := NewValue()\n\tgo func() {\n\t\ttime.Sleep(20 * time.Millisecond)\n\t\tv.Set(\"hi\")\n\t}()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tv.Get(20 * time.Millisecond)\n\t}\n}\n\n\n\nfunc TestConcurrent(t *testing.T) ", "output": "{\n\tv := NewValue()\n\n\tvar sets int32 = 0\n\n\tgo func() {\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(1)\n\t\tfor i := 0; i < concurrency; i++ {\n\t\t\tgo func() {\n\t\t\t\twg.Wait()\n\t\t\t\tv.Set(\"hi\")\n\t\t\t\tatomic.AddInt32(&sets, 1)\n\t\t\t}()\n\t\t}\n\t\twg.Done()\n\t}()\n\n\ttime.Sleep(50 * time.Millisecond)\n\tr, ok := v.Get(20 * time.Millisecond)\n\tassert.True(t, ok, \"Get should have succeed\")\n\tassert.Equal(t, \"hi\", r, \"Wrong result\")\n\tassert.Equal(t, concurrency, atomic.LoadInt32(&sets), \"Wrong number of successful Sets\")\n}"} {"input": "package tokens\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/client\"\n\t\"github.com/golang/glog\"\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/openshift/origin/pkg/auth/server/tokenrequest\"\n\tosclientcmd \"github.com/openshift/origin/pkg/cmd/util/clientcmd\"\n)\n\nconst (\n\tTokenRecommendedCommandName = \"tokens\"\n\tTOKEN_FILE_PARAM = \"token-file\"\n)\n\n\n\nfunc getFlagString(cmd *cobra.Command, flag string) string {\n\tf := cmd.Flags().Lookup(flag)\n\tif f == nil {\n\t\tglog.Fatalf(\"Flag accessed but not defined for command %s: %s\", cmd.Name(), flag)\n\t}\n\treturn f.Value.String()\n}\n\nfunc getRequestTokenURL(clientCfg *client.Config) string {\n\treturn clientCfg.Host + path.Join(\"/oauth\", tokenrequest.RequestTokenEndpoint)\n}\n\nfunc NewCmdTokens(name, fullName string, f *osclientcmd.Factory, out io.Writer) *cobra.Command ", "output": "{\n\tcmds := &cobra.Command{\n\t\tUse: name,\n\t\tShort: \"Manage authentication tokens\",\n\t\tLong: `Manage authentication tokens`,\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tc.SetOutput(os.Stdout)\n\t\t\tc.Help()\n\t\t},\n\t}\n\n\tcmds.AddCommand(NewCmdValidateToken(f))\n\tcmds.AddCommand(NewCmdRequestToken(f))\n\n\treturn cmds\n}"} {"input": "package tests\n\n\n\nimport (\n\t\"testing\"\n)\n\n\n\n\n\n\n\n\n\nfunc TestInboxIsOrderedCollection(t *testing.T) {\n\tdesc := `\nServer: Fetching the inbox\n Try retrieving the actor's inbox of an actor.\n\n inbox is an OrderedCollection\n`\n\tt.Skip(desc)\n}\n\n\n\n\nfunc TestInboxFilteringBasedOnPermissions(t *testing.T) {\n\tdesc := `\nServer: Fetching the inbox\n Try retrieving the actor's inbox of an actor.\n\n Server filters inbox content according to the requester's permission\n`\n\tt.Skip(desc)\n}\n\nfunc TestInboxGETRequest(t *testing.T) ", "output": "{\n\tdesc := `\nServer: Fetching the inbox\n Try retrieving the actor's inbox of an actor.\n\n Server responds to GET request at inbox URL\n`\n\tt.Skip(desc)\n}"} {"input": "package state\n\nimport (\n\t\"net/url\"\n\n\t\"gopkg.in/juju/charm.v3\"\n)\n\n\ntype charmDoc struct {\n\tURL *charm.URL `bson:\"_id\"`\n\tMeta *charm.Meta\n\tConfig *charm.Config\n\tActions *charm.Actions\n\tBundleURL *url.URL\n\tBundleSha256 string\n\tPendingUpload bool\n\tPlaceholder bool\n}\n\n\ntype Charm struct {\n\tst *State\n\tdoc charmDoc\n}\n\n\n\nfunc (c *Charm) String() string {\n\treturn c.doc.URL.String()\n}\n\n\nfunc (c *Charm) URL() *charm.URL {\n\tclone := *c.doc.URL\n\treturn &clone\n}\n\n\n\nfunc (c *Charm) Revision() int {\n\treturn c.doc.URL.Revision\n}\n\n\nfunc (c *Charm) Meta() *charm.Meta {\n\treturn c.doc.Meta\n}\n\n\nfunc (c *Charm) Config() *charm.Config {\n\treturn c.doc.Config\n}\n\n\nfunc (c *Charm) Actions() *charm.Actions {\n\treturn c.doc.Actions\n}\n\n\n\nfunc (c *Charm) BundleURL() *url.URL {\n\treturn c.doc.BundleURL\n}\n\n\nfunc (c *Charm) BundleSha256() string {\n\treturn c.doc.BundleSha256\n}\n\n\n\nfunc (c *Charm) IsUploaded() bool {\n\treturn !c.doc.PendingUpload\n}\n\n\n\nfunc (c *Charm) IsPlaceholder() bool {\n\treturn c.doc.Placeholder\n}\n\nfunc newCharm(st *State, cdoc *charmDoc) (*Charm, error) ", "output": "{\n\treturn &Charm{st: st, doc: *cdoc}, nil\n}"} {"input": "package validation\n\nimport (\n\t\"strings\"\n\n\t\"github.com/rantuttl/cloudops/apimachinery/pkg/util/validation\"\n\t\"github.com/rantuttl/cloudops/apimachinery/pkg/util/validation/field\"\n)\n\nconst IsNegativeErrorMsg string = `must be greater than or equal to 0`\n\n\n\n\n\n\ntype ValidateNameFunc func(name string, prefix bool) []string\n\n\nfunc NameIsDNSSubdomain(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1123Subdomain(name)\n}\n\n\nfunc NameIsDNSLabel(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1123Label(name)\n}\n\n\nfunc NameIsDNS1035Label(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1035Label(name)\n}\n\n\n\n\nvar ValidateNamespaceName = NameIsDNSLabel\n\n\n\n\nvar ValidateServiceAccountName = NameIsDNSSubdomain\n\n\n\nfunc maskTrailingDash(name string) string {\n\tif strings.HasSuffix(name, \"-\") {\n\t\treturn name[:len(name)-2] + \"a\"\n\t}\n\treturn name\n}\n\n\n\n\nfunc ValidateNonnegativeField(value int64, fldPath *field.Path) field.ErrorList ", "output": "{\n\tallErrs := field.ErrorList{}\n\tif value < 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, value, IsNegativeErrorMsg))\n\t}\n\treturn allErrs\n}"} {"input": "package model\n\nimport (\n\t\"time\"\n\n\t\"gopkg.in/mgo.v2\"\n)\n\ntype Relation struct {\n\tUids [2]string `bson:\"uids\"`\n\tApproved [2]bool `bson:\"approved\"`\n\tSource string `bson:\"source\"`\n\tDate time.Time `bson:\"date\"`\n}\n\n\n\ntype RelationModel struct {\n\t*BaseModel\n}\n\nfunc NewRelationModel(mdb *Mdb) *RelationModel {\n\treturn &RelationModel{NewBaseModel(mdb, User{})}\n}\n\nfunc (r *RelationModel) Add() {\n\n}\n\nfunc (r Relation) Index() []mgo.Index ", "output": "{\n\treturn []mgo.Index{\n\t\t{Key: []string{\"uids\"}, Unique: true},\n\t}\n}"} {"input": "package euler4\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strconv\"\n\n\t\"github.com/andrew-field/maths\"\n)\n\n\n\n\n\nfunc MaximumPathSumTwo() int {\n\tabsPath, err := filepath.Abs(\"p067_triangle.txt\")\n\tcheck(err)\n\tf, err := os.Open(absPath)\n\tcheck(err)\n\tdefer f.Close()\n\n\treader := bufio.NewReader(f) \n\n\tnumbers := make([]int, 0)\n\n\tnumber := make([]byte, 2)\n\tfor {\n\t\t_, err = reader.Read(number)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tcheck(err)\n\t\tvalue, err := strconv.Atoi(string(number))\n\t\tcheck(err)\n\t\tnumbers = append(numbers, value)\n\t}\n\n\tpyramidTree := maths.CreatePyramidTree(numbers...)\n\n\treturn maths.MaxPath(pyramidTree)\n}\n\nfunc check(e error) ", "output": "{\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}"} {"input": "package ui\n\nimport (\n\t\"github.com/Bredgren/geo\"\n\t\"github.com/hajimehoshi/ebiten\"\n)\n\n\n\n\ntype VerticalContainer struct {\n\tElements []WeightedDrawer\n\tWt float64\n}\n\n\nfunc (v *VerticalContainer) Draw(dst *ebiten.Image, bounds geo.Rect) {\n\ttotalWeight := 0.0\n\tfor _, e := range v.Elements {\n\t\ttotalWeight += e.Weight()\n\t}\n\theights := make([]float64, len(v.Elements))\n\tfor i, e := range v.Elements {\n\t\theights[i] = e.Weight() / totalWeight * bounds.H\n\t}\n\tsubBounds := bounds\n\tfor i, h := range heights {\n\t\tsubBounds.H = h\n\t\tv.Elements[i].Draw(dst, subBounds)\n\t\tsubBounds.Y += h\n\t}\n}\n\n\nfunc (v *VerticalContainer) Weight() float64 {\n\treturn v.Wt\n}\n\n\n\n\ntype HorizontalContainer struct {\n\tElements []WeightedDrawer\n\tWt float64\n}\n\n\n\n\n\nfunc (h *HorizontalContainer) Weight() float64 {\n\treturn h.Wt\n}\n\nfunc (h *HorizontalContainer) Draw(dst *ebiten.Image, bounds geo.Rect) ", "output": "{\n\ttotalWeight := 0.0\n\tfor _, e := range h.Elements {\n\t\ttotalWeight += e.Weight()\n\t}\n\twidths := make([]float64, len(h.Elements))\n\tfor i, e := range h.Elements {\n\t\twidths[i] = e.Weight() / totalWeight * bounds.W\n\t}\n\tsubBounds := bounds\n\tfor i, w := range widths {\n\t\tsubBounds.W = w\n\t\th.Elements[i].Draw(dst, subBounds)\n\t\tsubBounds.X += w\n\t}\n}"} {"input": "package logrus\n\nimport (\n\t\"io\"\n\t\"sync\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/golang/protobuf/proto\"\n\n\t\"go.pedge.io/protolog\"\n)\n\nvar (\n\tglobalPusherOptions = PusherOptions{}\n\tglobalLoggerOptions = protolog.LoggerOptions{}\n\tglobalLock = &sync.Mutex{}\n)\n\n\ntype PusherOptions struct {\n\tOut io.Writer\n\tHooks []logrus.Hook\n\tFormatter logrus.Formatter\n\tEnableID bool\n\tDisableContexts bool\n\tUnmarshalFunc func([]byte, proto.Message) error\n}\n\n\nfunc NewPusher(options PusherOptions) protolog.Pusher {\n\treturn newPusher(options)\n}\n\n\nfunc SetPusherOptions(options PusherOptions) {\n\tglobalLock.Lock()\n\tdefer globalLock.Unlock()\n\tglobalPusherOptions = options\n\tregister()\n}\n\n\n\n\n\nfunc Register() {\n\tglobalLock.Lock()\n\tdefer globalLock.Unlock()\n\tregister()\n}\n\nfunc register() {\n\tprotolog.SetLogger(protolog.NewLogger(NewPusher(globalPusherOptions), globalLoggerOptions))\n}\n\nfunc SetLoggerOptions(options protolog.LoggerOptions) ", "output": "{\n\tglobalLock.Lock()\n\tdefer globalLock.Unlock()\n\tglobalLoggerOptions = options\n\tregister()\n}"} {"input": "package random\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/google/uuid\"\n)\n\nconst (\n\tmaxNameLength = 63\n)\n\ntype Interface interface {\n\tName() (string, error)\n}\n\ntype impl struct {\n\tsslCertificateNamePrefix string\n}\n\n\n\n\nfunc (r impl) Name() (string, error) {\n\tif uid, err := uuid.NewRandom(); err != nil {\n\t\treturn \"\", err\n\t} else {\n\t\tgeneratedName := fmt.Sprintf(\"%s%s\", r.sslCertificateNamePrefix, uid.String())\n\t\tmaxLength := maxNameLength\n\t\tif len(generatedName) < maxLength {\n\t\t\tmaxLength = len(generatedName)\n\t\t}\n\n\t\treturn generatedName[:maxLength], nil\n\t}\n}\n\nfunc New(sslCertificateNamePrefix string) Interface ", "output": "{\n\treturn impl{sslCertificateNamePrefix: sslCertificateNamePrefix}\n}"} {"input": "package global\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/propagation\"\n)\n\n\n\n\ntype textMapPropagator struct {\n\tmtx sync.Mutex\n\tonce sync.Once\n\tdelegate propagation.TextMapPropagator\n\tnoop propagation.TextMapPropagator\n}\n\n\n\nvar _ propagation.TextMapPropagator = (*textMapPropagator)(nil)\n\nfunc newTextMapPropagator() *textMapPropagator {\n\treturn &textMapPropagator{\n\t\tnoop: propagation.NewCompositeTextMapPropagator(),\n\t}\n}\n\n\n\n\nfunc (p *textMapPropagator) SetDelegate(delegate propagation.TextMapPropagator) {\n\tif delegate == nil {\n\t\treturn\n\t}\n\n\tp.mtx.Lock()\n\tp.once.Do(func() { p.delegate = delegate })\n\tp.mtx.Unlock()\n}\n\n\n\n\n\n\n\nfunc (p *textMapPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) {\n\tp.effectiveDelegate().Inject(ctx, carrier)\n}\n\n\nfunc (p *textMapPropagator) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context {\n\treturn p.effectiveDelegate().Extract(ctx, carrier)\n}\n\n\nfunc (p *textMapPropagator) Fields() []string {\n\treturn p.effectiveDelegate().Fields()\n}\n\nfunc (p *textMapPropagator) effectiveDelegate() propagation.TextMapPropagator ", "output": "{\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tif p.delegate != nil {\n\t\treturn p.delegate\n\t}\n\treturn p.noop\n}"} {"input": "package utter_test\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/kortschak/utter\"\n)\n\ntype Flag int\n\nconst (\n\tflagOne Flag = iota\n\tflagTwo\n)\n\nvar flagStrings = map[Flag]string{\n\tflagOne: \"flagOne\",\n\tflagTwo: \"flagTwo\",\n}\n\nfunc (f Flag) String() string {\n\tif s, ok := flagStrings[f]; ok {\n\t\treturn s\n\t}\n\treturn fmt.Sprintf(\"Unknown flag (%d)\", int(f))\n}\n\ntype Bar struct {\n\tflag Flag\n\tdata uintptr\n}\n\ntype Foo struct {\n\tunexportedField Bar\n\tExportedField map[interface{}]interface{}\n}\n\n\n\n\n\nfunc ExampleConfigState() {\n\tscs := utter.ConfigState{Indent: \"\\t\"}\n\n\tv := map[string]int{\"one\": 1}\n\tscs.Dump(v)\n\n}\n\n\n\nfunc ExampleConfigState_Dump() {\n\n\tscs := utter.ConfigState{Indent: \"\\t\"}\n\tscs2 := utter.ConfigState{Indent: \" \"}\n\n\tbar := Bar{Flag(flagTwo), uintptr(0)}\n\ts1 := Foo{bar, map[interface{}]interface{}{\"one\": true}}\n\n\tscs.Dump(s1)\n\tscs2.Dump(s1)\n\n}\n\nfunc ExampleDump() ", "output": "{\n\n\tbar := Bar{Flag(flagTwo), uintptr(0)}\n\ts1 := Foo{bar, map[interface{}]interface{}{\"one\": true}}\n\tf := Flag(5)\n\tb := []byte{\n\t\t0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,\n\t\t0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,\n\t\t0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,\n\t\t0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,\n\t\t0x31, 0x32,\n\t}\n\n\tutter.Dump([]interface{}{s1, f, b})\n\n}"} {"input": "package midi\n\nimport \"fmt\"\n\ntype Track struct {\n\tevents []Event\n}\n\nfunc (t *Track) Events() []Event {\n\treturn t.events\n}\n\n\n\nfunc NewTrack(e []Event) *Track {\n\treturn &Track{e}\n}\n\nfunc (t *Track) String() string ", "output": "{\n\treturn fmt.Sprintf(\n\t\t\"Track [Events=%v]\",\n\t\tt.Events())\n}"} {"input": "package persist\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n)\n\n\ntype Database struct {\n\tuser string\n\tpassword string\n\tdatabase string\n\thost string\n}\n\n\n\n\n\nfunc (db Database) TestConnection() error {\n\tcon, err := db.getConnection()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer con.Close()\n\n\terr = con.Ping()\n\treturn err\n}\n\nfunc (db Database) getConnection() (*sql.DB, error) {\n\tcon, err := sql.Open(\"mysql\", fmt.Sprintf(\"%v:%v@tcp(%v:3306)/%v?parseTime=true\", db.user, db.password, db.host, db.database))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn con, nil\n}\n\n\nfunc (db Database) GetConnectionString() string {\n\treturn fmt.Sprintf(\"Data Source=%s;Database=%s;User ID=%s;Password=%s;Old Guids=true;\", db.host, db.database, db.user, db.password)\n}\n\nfunc NewDatabase(username string, password string, database string, host string) Database ", "output": "{\n\treturn Database{username, password, database, host}\n}"} {"input": "package client \n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/docker/docker/errdefs\"\n\t\"gotest.tools/assert\"\n\tis \"gotest.tools/assert/cmp\"\n)\n\nfunc TestSecretRemoveUnsupported(t *testing.T) {\n\tclient := &Client{\n\t\tversion: \"1.24\",\n\t\tclient: &http.Client{},\n\t}\n\terr := client.SecretRemove(context.Background(), \"secret_id\")\n\tassert.Check(t, is.Error(err, `\"secret remove\" requires API version 1.25, but the Docker daemon API version is 1.24`))\n}\n\nfunc TestSecretRemoveError(t *testing.T) {\n\tclient := &Client{\n\t\tversion: \"1.25\",\n\t\tclient: newMockClient(errorMock(http.StatusInternalServerError, \"Server error\")),\n\t}\n\n\terr := client.SecretRemove(context.Background(), \"secret_id\")\n\tif !errdefs.IsSystem(err) {\n\t\tt.Fatalf(\"expected a Server Error, got %[1]T: %[1]v\", err)\n\t}\n}\n\n\n\nfunc TestSecretRemove(t *testing.T) ", "output": "{\n\texpectedURL := \"/v1.25/secrets/secret_id\"\n\n\tclient := &Client{\n\t\tversion: \"1.25\",\n\t\tclient: newMockClient(func(req *http.Request) (*http.Response, error) {\n\t\t\tif !strings.HasPrefix(req.URL.Path, expectedURL) {\n\t\t\t\treturn nil, fmt.Errorf(\"Expected URL '%s', got '%s'\", expectedURL, req.URL)\n\t\t\t}\n\t\t\tif req.Method != http.MethodDelete {\n\t\t\t\treturn nil, fmt.Errorf(\"expected DELETE method, got %s\", req.Method)\n\t\t\t}\n\t\t\treturn &http.Response{\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tBody: ioutil.NopCloser(bytes.NewReader([]byte(\"body\"))),\n\t\t\t}, nil\n\t\t}),\n\t}\n\n\terr := client.SecretRemove(context.Background(), \"secret_id\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package v1beta3\n\nimport (\n\t\"testing\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/conversion\"\n)\n\nfunc TestAPItoV1Beta3VolumeSourceConversion(t *testing.T) {\n\tc := conversion.NewConverter()\n\tc.Debug = t\n\n\tif err := c.RegisterConversionFunc(convert_api_VolumeSource_To_v1beta3_VolumeSource); err != nil {\n\t\tt.Fatalf(\"unexpected error %v\", err)\n\t}\n\n\tin := api.VolumeSource{\n\t\tDownwardAPI: &api.DownwardAPIVolumeSource{\n\t\t\tItems: []api.DownwardAPIVolumeFile{\n\t\t\t\t{\n\t\t\t\t\tPath: \"./test/api-to-v1beta3/conversion\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tout := VolumeSource{}\n\n\tif err := c.Convert(&in, &out, 0, nil); err != nil {\n\t\tt.Fatalf(\"unexpected error %v\", err)\n\t}\n\tif e, a := in.DownwardAPI.Items[0].Path, out.Metadata.Items[0].Name; e != a {\n\t\tt.Errorf(\"expected %v, got %v\", e, a)\n\t}\n}\n\n\n\nfunc TestV1Beta3toAPIVolumeSourceConversion(t *testing.T) ", "output": "{\n\tc := conversion.NewConverter()\n\tc.Debug = t\n\n\tif err := c.RegisterConversionFunc(convert_v1beta3_VolumeSource_To_api_VolumeSource); err != nil {\n\t\tt.Fatalf(\"unexpected error %v\", err)\n\t}\n\n\tin := VolumeSource{\n\t\tMetadata: &MetadataVolumeSource{\n\t\t\tItems: []MetadataFile{\n\t\t\t\t{\n\t\t\t\t\tName: \"./test/v1beta3-to-api/conversion\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tout := api.VolumeSource{}\n\n\tif err := c.Convert(&in, &out, 0, nil); err != nil {\n\t\tt.Fatalf(\"unexpected error %v\", err)\n\t}\n\tif e, a := in.Metadata.Items[0].Name, out.DownwardAPI.Items[0].Path; e != a {\n\t\tt.Errorf(\"expected %v, got %v\", e, a)\n\t}\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSGameLiftBuild_S3Location struct {\n\n\tBucket string `json:\"Bucket,omitempty\"`\n\n\tKey string `json:\"Key,omitempty\"`\n\n\tRoleArn string `json:\"RoleArn,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSGameLiftBuild_S3Location) AWSCloudFormationType() string {\n\treturn \"AWS::GameLift::Build.S3Location\"\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetDeletionPolicy(policy policies.DeletionPolicy) ", "output": "{\n\tr._deletionPolicy = policy\n}"} {"input": "package wml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/wml\"\n)\n\nfunc TestCT_PConstructor(t *testing.T) {\n\tv := wml.NewCT_P()\n\tif v == nil {\n\t\tt.Errorf(\"wml.NewCT_P must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed wml.CT_P should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestCT_PMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := wml.NewCT_P()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := wml.NewCT_P()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package stateful\n\nimport \"sync\"\n\n\n\n\ntype ScopePool interface {\n\tGet() *Scope\n\tPut(scope *Scope)\n\n\tReferenceVariables() []string\n}\n\ntype scopePool struct {\n\treferenceVariables []string\n\tpool sync.Pool\n}\n\n\nfunc NewScopePool(referenceVariables []string) ScopePool {\n\tscopePool := &scopePool{\n\t\treferenceVariables: referenceVariables,\n\t}\n\n\tscopePool.pool = sync.Pool{\n\t\tNew: func() interface{} {\n\t\t\tscope := NewScope()\n\t\t\tfor _, refVariable := range scopePool.referenceVariables {\n\t\t\t\tscope.Set(refVariable, empty)\n\t\t\t}\n\n\t\t\treturn scope\n\t\t},\n\t}\n\n\treturn scopePool\n}\n\nfunc (s *scopePool) ReferenceVariables() []string {\n\treturn s.referenceVariables\n}\n\n\n\n\n\n\nfunc (s *scopePool) Put(scope *Scope) {\n\tscope.Reset()\n\ts.pool.Put(scope)\n}\n\nfunc (s *scopePool) Get() *Scope ", "output": "{\n\treturn s.pool.Get().(*Scope)\n}"} {"input": "package iso20022\n\n\ntype MatchingDenied1Choice struct {\n\n\tCode *MatchingProcess1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification20 `xml:\"Prtry\"`\n}\n\nfunc (m *MatchingDenied1Choice) SetCode(value string) {\n\tm.Code = (*MatchingProcess1Code)(&value)\n}\n\n\n\nfunc (m *MatchingDenied1Choice) AddProprietary() *GenericIdentification20 ", "output": "{\n\tm.Proprietary = new(GenericIdentification20)\n\treturn m.Proprietary\n}"} {"input": "package authentication\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/piot/hasty-protocol/user\"\n)\n\n\ntype Info struct {\n\tuserID user.ID\n}\n\n\nfunc NewInfo(userID user.ID) Info {\n\treturn Info{userID: userID}\n}\n\n\nfunc (in Info) UserID() user.ID {\n\treturn in.userID\n}\n\n\n\n\nfunc (in Info) String() string ", "output": "{\n\treturn fmt.Sprintf(\"[authentication ID:%s ]\", in.userID)\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/mitchellh/packer/template/interpolate\"\n)\n\ntype FloppyConfig struct {\n\tFloppyFiles []string `mapstructure:\"floppy_files\"`\n}\n\n\n\nfunc (c *FloppyConfig) Prepare(ctx *interpolate.Context) []error ", "output": "{\n\tvar errs []error\n\n\tif c.FloppyFiles == nil {\n\t\tc.FloppyFiles = make([]string, 0)\n\t}\n\n\tfor _, path := range c.FloppyFiles {\n\t\tif _, err := os.Stat(path); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"Bad Floppy disk file '%s': %s\", path, err))\n\t\t}\n\t}\n\n\treturn errs\n}"} {"input": "package iso20022\n\n\ntype PlainCardData4 struct {\n\n\tPAN *Min8Max28NumericText `xml:\"PAN\"`\n\n\tCardSequenceNumber *Min2Max3NumericText `xml:\"CardSeqNb,omitempty\"`\n\n\tEffectiveDate *Max10Text `xml:\"FctvDt,omitempty\"`\n\n\tExpiryDate *Max10Text `xml:\"XpryDt\"`\n\n\tServiceCode *Exact3NumericText `xml:\"SvcCd,omitempty\"`\n\n\tTrackData []*TrackData1 `xml:\"TrckData,omitempty\"`\n\n\tCardSecurityCode *CardSecurityInformation1 `xml:\"CardSctyCd,omitempty\"`\n}\n\n\n\nfunc (p *PlainCardData4) SetCardSequenceNumber(value string) {\n\tp.CardSequenceNumber = (*Min2Max3NumericText)(&value)\n}\n\nfunc (p *PlainCardData4) SetEffectiveDate(value string) {\n\tp.EffectiveDate = (*Max10Text)(&value)\n}\n\nfunc (p *PlainCardData4) SetExpiryDate(value string) {\n\tp.ExpiryDate = (*Max10Text)(&value)\n}\n\nfunc (p *PlainCardData4) SetServiceCode(value string) {\n\tp.ServiceCode = (*Exact3NumericText)(&value)\n}\n\nfunc (p *PlainCardData4) AddTrackData() *TrackData1 {\n\tnewValue := new(TrackData1)\n\tp.TrackData = append(p.TrackData, newValue)\n\treturn newValue\n}\n\nfunc (p *PlainCardData4) AddCardSecurityCode() *CardSecurityInformation1 {\n\tp.CardSecurityCode = new(CardSecurityInformation1)\n\treturn p.CardSecurityCode\n}\n\nfunc (p *PlainCardData4) SetPAN(value string) ", "output": "{\n\tp.PAN = (*Min8Max28NumericText)(&value)\n}"} {"input": "package gemini\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/thrasher-corp/gocryptotrader/exchanges/request\"\n\t\"golang.org/x/time/rate\"\n)\n\nconst (\n\tgeminiRateInterval = time.Minute\n\tgeminiAuthRate = 600\n\tgeminiUnauthRate = 120\n)\n\n\ntype RateLimit struct {\n\tAuth *rate.Limiter\n\tUnAuth *rate.Limiter\n}\n\n\nfunc (r *RateLimit) Limit(ctx context.Context, f request.EndpointLimit) error {\n\tif f == request.Auth {\n\t\treturn r.Auth.Wait(ctx)\n\t}\n\treturn r.UnAuth.Wait(ctx)\n}\n\n\n\n\nfunc SetRateLimit() *RateLimit ", "output": "{\n\treturn &RateLimit{\n\t\tAuth: request.NewRateLimit(geminiRateInterval, geminiAuthRate),\n\t\tUnAuth: request.NewRateLimit(geminiRateInterval, geminiUnauthRate),\n\t}\n}"} {"input": "package imagestreamtag\n\nimport (\n\tkapi \"github.com/GoogleCloudPlatform/kubernetes/pkg/api\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/api/rest\"\n\t\"github.com/projectatomic/atomic-enterprise/pkg/image/api\"\n)\n\n\ntype Registry interface {\n\tGetImageStreamTag(ctx kapi.Context, nameAndTag string) (*api.ImageStreamTag, error)\n\tDeleteImageStreamTag(ctx kapi.Context, nameAndTag string) (*kapi.Status, error)\n}\n\n\ntype Storage interface {\n\trest.Deleter\n\trest.Getter\n}\n\n\ntype storage struct {\n\tStorage\n}\n\n\n\nfunc NewRegistry(s Storage) Registry {\n\treturn &storage{s}\n}\n\nfunc (s *storage) GetImageStreamTag(ctx kapi.Context, nameAndTag string) (*api.ImageStreamTag, error) {\n\tobj, err := s.Get(ctx, nameAndTag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*api.ImageStreamTag), nil\n}\n\n\n\nfunc (s *storage) DeleteImageStreamTag(ctx kapi.Context, nameAndTag string) (*kapi.Status, error) ", "output": "{\n\tobj, err := s.Delete(ctx, nameAndTag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*kapi.Status), err\n}"} {"input": "package inigo\n\nimport (\n\t\"errors\"\n)\n\n\n\n\n\nfunc (config *Config) GetAllSections() []string {\n\tvar res []string\n\n\tfor key, _ := range config.config {\n\t\tres = append(res, key)\n\t}\n\n\treturn res\n}\n\n\nfunc (config *Config) GetAllKeys() map[string][]string {\n\tvar res map[string][]string = make(map[string][]string)\n\n\tfor section, data := range config.config {\n\t\tfor key, _ := range data.data {\n\t\t\tres[section] = append(res[section], key)\n\t\t}\n\t}\n\n\treturn res\n}\n\n\nfunc (config *Config) GetValue(section, key string) (string, error) {\n\tvar processing bool = true\n\tvar currentSection string = section\n\tvar res string\n\n\tfor processing && len(currentSection) > 0 {\n\t\tres = config.config[currentSection].data[key]\n\n\t\tif len(res) > 0 {\n\t\t\tprocessing = false\n\t\t\tbreak\n\t\t} else {\n\t\t\tcurrentSection = config.config[currentSection].inheritSection\n\t\t}\n\t}\n\n\tif len(res) == 0 {\n\t\treturn res, errors.New(\"Has no key\")\n\t}\n\n\treturn res, nil\n}\n\nfunc (config *Config) GetConfigFilename() string ", "output": "{\n\treturn config.filename\n}"} {"input": "package token\n\nimport (\n\t\"github.com/dgrijalva/jwt-go\"\n)\n\nconst (\n\tSignerAlgorithm = \"HS256\"\n)\n\ntype SecretFunc func(*Token) (string, error)\n\ntype Token struct {\n\tType string\n\tValue string\n}\n\nfunc New(t, v string) *Token {\n\treturn &Token{Type: t, Value: v}\n}\n\n\n\n\n\nfunc (t *Token) SignWithExp(secret string, expiration int64) (string, error) {\n\ttoken := jwt.New(jwt.SigningMethodHS256)\n\tclaims := token.Claims.(jwt.MapClaims)\n\n\tclaims[\"type\"] = t.Type\n\tclaims[\"value\"] = t.Value\n\tif expiration > 0 {\n\t\tclaims[\"exp\"] = float64(expiration)\n\t}\n\n\treturn token.SignedString([]byte(secret))\n}\n\nfunc ParseToken(tokenStr string, secretFn SecretFunc) (*Token, error) ", "output": "{\n\ttoken := &Token{}\n\tparsedToken, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {\n\n\t\tif t.Method.Alg() != SignerAlgorithm {\n\t\t\treturn nil, jwt.ErrSignatureInvalid\n\t\t}\n\n\t\tclaims := t.Claims.(jwt.MapClaims)\n\t\ttypev, ok := claims[\"type\"]\n\t\tif !ok {\n\t\t\treturn nil, jwt.ValidationError{}\n\t\t}\n\n\t\tval, ok := claims[\"value\"]\n\t\tif !ok {\n\t\t\treturn nil, jwt.ValidationError{}\n\t\t}\n\n\t\ttoken.Type = typev.(string)\n\t\ttoken.Value = val.(string)\n\n\t\tsecret, err := secretFn(token)\n\t\treturn []byte(secret), err\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t} else if !parsedToken.Valid {\n\t\treturn nil, jwt.ValidationError{}\n\t}\n\n\treturn token, nil\n}"} {"input": "package vm\n\nimport (\n\t\"github.com/rancher/wrangler/pkg/generic\"\n\t\"k8s.io/client-go/rest\"\n)\n\ntype Factory struct {\n\t*generic.Factory\n}\n\nfunc NewFactoryFromConfigOrDie(config *rest.Config) *Factory {\n\tf, err := NewFactoryFromConfig(config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}\n\nfunc NewFactoryFromConfig(config *rest.Config) (*Factory, error) {\n\treturn NewFactoryFromConfigWithOptions(config, nil)\n}\n\nfunc NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (*Factory, error) {\n\treturn NewFactoryFromConfigWithOptions(config, &FactoryOptions{\n\t\tNamespace: namespace,\n\t})\n}\n\ntype FactoryOptions = generic.FactoryOptions\n\nfunc NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) {\n\tf, err := generic.NewFactoryFromConfigWithOptions(config, opts)\n\treturn &Factory{\n\t\tFactory: f,\n\t}, err\n}\n\n\n\nfunc (c *Factory) Vm() Interface ", "output": "{\n\treturn New(c.ControllerFactory())\n}"} {"input": "package cancel\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/coredns/coredns/plugin\"\n\t\"github.com/coredns/coredns/plugin/pkg/dnstest\"\n\t\"github.com/coredns/coredns/plugin/test\"\n\n\t\"github.com/miekg/dns\"\n)\n\ntype sleepPlugin struct{}\n\nfunc (s sleepPlugin) Name() string { return \"sleep\" }\n\nfunc (s sleepPlugin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {\n\ti := 0\n\tm := new(dns.Msg)\n\tm.SetReply(r)\n\tfor {\n\t\tif plugin.Done(ctx) {\n\t\t\tm.Rcode = dns.RcodeBadTime \n\t\t\tw.WriteMsg(m)\n\t\t\treturn 0, nil\n\t\t}\n\t\ttime.Sleep(20 * time.Millisecond)\n\t\ti++\n\t\tif i > 2 {\n\t\t\tm.Rcode = dns.RcodeServerFailure\n\t\t\tw.WriteMsg(m)\n\t\t\treturn 0, nil\n\t\t}\n\t}\n\treturn 0, nil\n}\n\n\n\nfunc TestCancel(t *testing.T) ", "output": "{\n\tca := Cancel{Next: sleepPlugin{}, timeout: 20 * time.Millisecond}\n\tctx := context.Background()\n\n\tw := dnstest.NewRecorder(&test.ResponseWriter{})\n\tm := new(dns.Msg)\n\tm.SetQuestion(\"aaa.example.com.\", dns.TypeTXT)\n\n\tca.ServeDNS(ctx, w, m)\n\tif w.Rcode != dns.RcodeBadTime {\n\t\tt.Error(\"Expected ServeDNS to be canceled by context\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"os\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"github.com/go-xorm/xorm\"\n)\n\n\ntype Account struct {\n\tId int64\n\tName string `xorm:\"unique\"`\n\tBalance float64\n\tVersion int `xorm:\"version\"` \n}\n\n\nfunc (a *Account) BeforeInsert() {\n\tlog.Printf(\"before insert: %s\", a.Name)\n}\n\n\nfunc (a *Account) AfterInsert() {\n\tlog.Printf(\"after insert: %s\", a.Name)\n}\n\n\nvar x *xorm.Engine\n\nfunc init() {\n\tvar err error\n\tx, err = xorm.NewEngine(\"mysql\", \"root:password@tcp(10.10.0.122)/test?charset=utf8&parseTime=True&loc=Local\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to create engine: %v\\n\", err)\n\t}\n\n\tif err = x.Sync(new(Account)); err != nil {\n\t\tlog.Fatalf(\"Fail to sync database: %v\\n\", err)\n\t}\n\n\tf, err := os.Create(\"sql.log\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to create log file: %v\\n\", err)\n\t\treturn\n\t}\n\tx.SetLogger(xorm.NewSimpleLogger(f))\n\tx.ShowSQL()\n\n\tcacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)\n\tx.SetDefaultCacher(cacher)\n}\n\n\nfunc newAccount(name string, balance float64) error {\n\t_, err := x.Insert(&Account{Name: name, Balance: balance})\n\treturn err\n}\n\n\nfunc getAccountCount() (int64, error) {\n\treturn x.Count(new(Account))\n}\n\n\n\n\nfunc getAccount(id int64) (*Account, error) ", "output": "{\n\ta := &Account{}\n\thas, err := x.ID(id).Get(a)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if !has {\n\t\treturn nil, errors.New(\"Account does not exist\")\n\t}\n\treturn a, nil\n}"} {"input": "package parser\n\nimport (\n\t\"fmt\"\n)\n\ntype OKPacket struct {\n\tAffectedRows *UintV\n\tInsertID *UintV\n\tStatus uint16\n\tWarningCount uint16\n\tMessage string\n}\n\n\n\nfunc NewOKPacket(b []byte) (*OKPacket, error) ", "output": "{\n\tvar (\n\t\tpkt = &OKPacket{}\n\t\tbuf = &decbuf{buf: b}\n\t)\n\tif b[0] != 0x00 {\n\t\treturn nil, fmt.Errorf(\"OK packet must start with 0x00: %02x\", b[0])\n\t}\n\tpkt.AffectedRows, _ = buf.ReadUintV()\n\tpkt.InsertID, _ = buf.ReadUintV()\n\tpkt.Status, _ = buf.ReadUint16()\n\tpkt.WarningCount, _ = buf.ReadUint16()\n\tif buf.err != nil {\n\t\treturn nil, buf.err\n\t}\n\treturn pkt, nil\n}"} {"input": "package fda\n\n\n\ntype FoodService struct {\n\tclient *Client\n}\n\n\n\n\n\n\nfunc (s *FoodService) EnforcementCount(search, count string, data interface{}, limit int) (*Meta, error) {\n\tmeta, err := s.client.count(\"/food/enforcement\", search, count, limit, &data)\n\treturn meta, err\n}\n\nfunc (s *FoodService) EnforcementSearch(search string, limit, skip int) ([]EnforcementReport, *Meta, error) ", "output": "{\n\tdata := []EnforcementReport{}\n\n\tmeta, err := s.client.search(\"/food/enforcement\", search, limit, skip, &data)\n\treturn data, meta, err\n}"} {"input": "package stats\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestSum(t *testing.T) {\n\tfor _, c := range []struct {\n\t\tin []float64\n\t\tout float64\n\t}{\n\t\t{[]float64{1, 2, 3}, 6},\n\t\t{[]float64{1.0, 1.1, 1.2, 2.2}, 5.5},\n\t\t{[]float64{1, -1, 2, -3}, -1},\n\t} {\n\t\tgot, err := Sum(c.in)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Returned an error\")\n\t\t}\n\t\tif !reflect.DeepEqual(c.out, got) {\n\t\t\tt.Errorf(\"Sum(%.1f) => %.1f != %.1f\", c.in, got, c.out)\n\t\t}\n\t}\n\t_, err := Sum([]float64{})\n\tif err == nil {\n\t\tt.Errorf(\"Empty slice should have returned an error\")\n\t}\n}\n\n\n\nfunc BenchmarkSumLargeFloatSlice(b *testing.B) {\n\tlf := makeFloatSlice(100000)\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tSum(lf)\n\t}\n}\n\nfunc BenchmarkSumSmallFloatSlice(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tSum(makeFloatSlice(5))\n\t}\n}"} {"input": "package config\n\n\ntype UserOptions struct {\n\tRememberMeDays int `json:\"remember-me-days\" yaml:\"remember-me-days\" envconfig:\"REMEMBER_ME_DAYS\"`\n\tPasswordNoReuseMonths int `json:\"password-no-reuse-months\" yaml:\"password-no-reuse-months\" envconfig:\"PASSWORD_NO_REUSE_MONTHS\"`\n}\n\n\nfunc NewUserOptions() *UserOptions {\n\treturn &UserOptions{\n\t\tRememberMeDays: 45,\n\t\tPasswordNoReuseMonths: 0,\n\t}\n}\n\n\n\n\nfunc (o *UserOptions) VerifyAndPrepare() error ", "output": "{ return nil }"} {"input": "package probe_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/minio/minio/pkg/probe\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype MySuite struct{}\n\nvar _ = Suite(&MySuite{})\n\nfunc testDummy0() *probe.Error {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\treturn probe.NewError(e)\n}\n\nfunc testDummy1() *probe.Error {\n\treturn testDummy0().Trace(\"DummyTag1\")\n}\n\nfunc testDummy2() *probe.Error {\n\treturn testDummy1().Trace(\"DummyTag2\")\n}\n\n\n\nfunc (s *MySuite) TestWrappedError(c *C) {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\tes := probe.NewError(e) \n\te = probe.WrapError(es) \n\t_, ok := probe.UnwrapError(e)\n\tc.Assert(ok, Equals, true)\n}\n\nfunc (s *MySuite) TestProbe(c *C) ", "output": "{\n\tes := testDummy2().Trace(\"TopOfStack\")\n\tc.Assert(es, Not(Equals), nil)\n\n\tnewES := es.Trace()\n\tc.Assert(newES, Not(Equals), nil)\n}"} {"input": "package helper\n\nimport (\n\t\"github.com/sascha-andres/devenv\"\n)\n\n\n\nfunc GetProcess(e *devenv.EnvironmentConfiguration) devenv.EnvironmentExternalProcessConfiguration ", "output": "{\n\treturn e.ProcessConfiguration\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/labstack/echo\"\n)\n\n\n\n\nfunc MakeControllers(e *echo.Echo) ", "output": "{\n\te.GET(\"/api\", homeController)\n}"} {"input": "package apimgr\n\nimport \"reflect\"\n\n\n\ntype sorter struct {\n\t*Manager\n\n\tapis []Definition\n}\n\nfunc (t sorter) Len() int {\n\treturn len(t.apis)\n}\n\nfunc (t sorter) Swap(i int, j int) {\n\tt.apis[i], t.apis[j] = t.apis[j], t.apis[i]\n}\n\nfunc (t sorter) Less(i int, j int) bool {\n\tki := t.getSortKey(t.apis[i])\n\tkj := t.getSortKey(t.apis[j])\n\treturn ki < kj\n}\n\nfunc (t sorter) getSortKey(api Definition) string {\n\tpkgpath := getPackagePath(reflect.ValueOf(api.Request))\n\tkey := pkgpath + \" \" + t.GetMethodPatternKey(t.Manager, api)\n\treturn key\n}\n\nfunc newSorter(manager *Manager) *sorter ", "output": "{\n\tapis := []Definition{}\n\tfor _, api := range manager.apiMethodPatternMap {\n\t\tapis = append(apis, api)\n\t}\n\treturn &sorter{\n\t\tManager: manager,\n\t\tapis: apis,\n\t}\n}"} {"input": "package node\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Node struct {\n\tPriority uint\n\tLoad interface{}\n}\n\nfunc (n Node) String() string {\n\treturn fmt.Sprintf(\"{ Priority : %d, Load : %+v}\", n.Priority, n.Load)\n}\n\n\nfunc NewEmptyNode() Node {\n\treturn Node{}\n}\n\n\n\n\nfunc New(load interface{}, priority uint) *Node ", "output": "{\n\treturn &Node{Load: load, Priority: priority}\n}"} {"input": "package nom\n\nimport (\n\t\"encoding/gob\"\n\t\"fmt\"\n)\n\n\nconst (\n\tPortFlood UID = \"Ports.PortBcast\"\n\tPortAll UID = \"Ports.PortAll\"\n)\n\n\ntype PacketIn struct {\n\tNode UID\n\tInPort UID\n\tBufferID PacketBufferID\n\tPacket Packet\n}\n\nfunc (in PacketIn) String() string {\n\treturn fmt.Sprintf(\"packet in on switch %s port %s\", in.Node, in.InPort)\n}\n\n\ntype PacketOut struct {\n\tNode UID\n\tInPort UID\n\tBufferID PacketBufferID\n\tPacket Packet\n\tActions []Action\n}\n\n\ntype Packet []byte\n\n\n\n\n\nfunc (p Packet) SrcMAC() MACAddr {\n\treturn MACAddr{p[6], p[7], p[8], p[9], p[10], p[11]}\n}\n\n\n\n\ntype PacketBufferID uint32\n\nfunc init() {\n\tgob.Register(Packet{})\n\tgob.Register(PacketBufferID(0))\n\tgob.Register(PacketIn{})\n\tgob.Register(PacketOut{})\n}\n\nfunc (p Packet) DstMAC() MACAddr ", "output": "{\n\treturn MACAddr{p[0], p[1], p[2], p[3], p[4], p[5]}\n}"} {"input": "package gorouter\n\nimport \"net/http\"\n\ntype WSHandler interface {\n\tServeWS(Request) Response\n}\n\ntype HandleBind interface {\n\thttp.Handler\n\tWSHandler\n}\n\ntype WSHandlerFunc func(Request) Response\n\n\n\nfunc (f WSHandlerFunc) ServeWS(r Request) Response ", "output": "{\n\treturn f(r)\n}"} {"input": "package cborl\n\ntype stateStack struct {\n\tstack []state \n\tstack0 [64]state\n\tcurrent state\n}\n\ntype lengthStack struct {\n\tstack []int64\n\tstack0 [32]int64\n\tcurrent int64\n}\n\nfunc (s *stateStack) init(s0 state) {\n\ts.current = s0\n\ts.stack = s.stack0[:0]\n}\n\nfunc (s *stateStack) push(next state) {\n\tif s.current.major != stFail {\n\t\ts.stack = append(s.stack, s.current)\n\t}\n\ts.current = next\n}\n\nfunc (s *stateStack) pop() {\n\tif len(s.stack) == 0 {\n\t\ts.current = state{stFail, stStart}\n\t} else {\n\t\tlast := len(s.stack) - 1\n\t\ts.current = s.stack[last]\n\t\ts.stack = s.stack[:last]\n\t}\n}\n\nfunc (s *lengthStack) init() {\n\ts.stack = s.stack0[:0]\n}\n\n\n\nfunc (s *lengthStack) pop() int64 {\n\tif len(s.stack) == 0 {\n\t\ts.current = -1\n\t\treturn -1\n\t} else {\n\t\tlast := len(s.stack) - 1\n\t\told := s.current\n\t\ts.current = s.stack[last]\n\t\ts.stack = s.stack[:last]\n\t\treturn old\n\t}\n}\n\nfunc (s *lengthStack) push(l int64) ", "output": "{\n\ts.stack = append(s.stack, s.current)\n\ts.current = l\n}"} {"input": "package influxdbclient\n\nimport \"github.com/influxdata/influxdb1-client/v2\"\nimport \"time\"\nimport \"encoding/json\"\n\n\n\n\n\ntype DataSet struct {\n\tName string\n\tTimeStamps []time.Time\n\tTags map[string]string\n\tDatas map[string][]float64\n}\n\n\nfunc NewDataSet(length int, fields []string) *DataSet {\n\tds := DataSet{TimeStamps: make([]time.Time, length), Datas: make(map[string][]float64)}\n\n\tfor _, fieldname := range fields {\n\t\tds.Datas[fieldname] = make([]float64, length)\n\t}\n\treturn &ds\n}\n\n\n\n\nfunc ConvertToDataSet(res []client.Result) (dsets []*DataSet) ", "output": "{\n\tif len(res[0].Series) == 0 {\n\t\treturn\n\t}\n\n\tfor _, serie := range res[0].Series {\n\t\tds := NewDataSet(len(serie.Values), serie.Columns[1:])\n\n\t\tds.Name = serie.Name\n\t\tds.Tags = serie.Tags\n\t\tfor i, row := range serie.Values {\n\n\t\t\tt, _ := time.Parse(time.RFC3339, row[0].(string))\n\n\t\t\tds.TimeStamps[i] = t\n\n\t\t\tfor j, field := range row {\n\t\t\t\tif j == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tfieldname := serie.Columns[j]\n\t\t\t\tif field != nil {\n\t\t\t\t\tval, _ := field.(json.Number).Float64()\n\t\t\t\t\tds.Datas[fieldname][i] = val\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdsets = append(dsets, ds)\n\t}\n\treturn\n}"} {"input": "package client\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\n\t\"github.com/containerd/containerd/containers\"\n\t\"github.com/containerd/containerd/oci\"\n\tspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n)\n\nconst newLine = \"\\r\\n\"\n\nfunc withExitStatus(es int) oci.SpecOpts {\n\treturn func(_ context.Context, _ oci.Client, _ *containers.Container, s *specs.Spec) error {\n\t\ts.Process.Args = []string{\"cmd\", \"/c\", \"exit\", strconv.Itoa(es)}\n\t\treturn nil\n\t}\n}\n\nfunc withProcessArgs(args ...string) oci.SpecOpts {\n\treturn oci.WithProcessArgs(append([]string{\"cmd\", \"/c\"}, args...)...)\n}\n\nfunc withCat() oci.SpecOpts {\n\treturn oci.WithProcessArgs(\"cmd\", \"/c\", \"more\")\n}\n\n\n\nfunc withExecExitStatus(s *specs.Process, es int) {\n\ts.Args = []string{\"cmd\", \"/c\", \"exit\", strconv.Itoa(es)}\n}\n\nfunc withExecArgs(s *specs.Process, args ...string) {\n\ts.Args = append([]string{\"cmd\", \"/c\"}, args...)\n}\n\nfunc withTrue() oci.SpecOpts ", "output": "{\n\treturn oci.WithProcessArgs(\"cmd\", \"/c\")\n}"} {"input": "package unversioned\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/testapi\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\ntype HTTPClientFunc func(*http.Request) (*http.Response, error)\n\nfunc (f HTTPClientFunc) Do(req *http.Request) (*http.Response, error) {\n\treturn f(req)\n}\n\n\ntype FakeRESTClient struct {\n\tClient HTTPClient\n\tCodec runtime.Codec\n\tReq *http.Request\n\tResp *http.Response\n\tErr error\n}\n\nfunc (c *FakeRESTClient) Get() *Request {\n\treturn NewRequest(c, \"GET\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Put() *Request {\n\treturn NewRequest(c, \"PUT\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Patch(_ api.PatchType) *Request {\n\treturn NewRequest(c, \"PATCH\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Post() *Request {\n\treturn NewRequest(c, \"POST\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\n\n\nfunc (c *FakeRESTClient) Do(req *http.Request) (*http.Response, error) {\n\tc.Req = req\n\tif c.Client != HTTPClient(nil) {\n\t\treturn c.Client.Do(req)\n\t}\n\treturn c.Resp, c.Err\n}\n\nfunc (c *FakeRESTClient) Delete() *Request ", "output": "{\n\treturn NewRequest(c, \"DELETE\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realInternetGateway InternetGateway\n\n\nfunc (o *InternetGateway) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realInternetGateway\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = InternetGateway(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &InternetGateway{}\n\n\n\n\n\nfunc (o *InternetGateway) SetLifecycle(lifecycle fi.Lifecycle) {\n\to.Lifecycle = &lifecycle\n}\n\nvar _ fi.HasName = &InternetGateway{}\n\n\nfunc (o *InternetGateway) GetName() *string {\n\treturn o.Name\n}\n\n\nfunc (o *InternetGateway) SetName(name string) {\n\to.Name = &name\n}\n\n\nfunc (o *InternetGateway) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *InternetGateway) GetLifecycle() *fi.Lifecycle ", "output": "{\n\treturn o.Lifecycle\n}"} {"input": "package metrics\n\n\n\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\tgolangswaggerpaths \"path\"\n)\n\n\ntype GetMetricsURL struct {\n\t_basePath string\n}\n\n\n\n\nfunc (o *GetMetricsURL) WithBasePath(bp string) *GetMetricsURL {\n\to.SetBasePath(bp)\n\treturn o\n}\n\n\n\n\nfunc (o *GetMetricsURL) SetBasePath(bp string) {\n\to._basePath = bp\n}\n\n\nfunc (o *GetMetricsURL) Build() (*url.URL, error) {\n\tvar result url.URL\n\n\tvar _path = \"/metrics/\"\n\n\t_basePath := o._basePath\n\tif _basePath == \"\" {\n\t\t_basePath = \"/v1\"\n\t}\n\tresult.Path = golangswaggerpaths.Join(_basePath, _path)\n\n\treturn &result, nil\n}\n\n\n\n\n\nfunc (o *GetMetricsURL) String() string {\n\treturn o.Must(o.Build()).String()\n}\n\n\nfunc (o *GetMetricsURL) BuildFull(scheme, host string) (*url.URL, error) {\n\tif scheme == \"\" {\n\t\treturn nil, errors.New(\"scheme is required for a full url on GetMetricsURL\")\n\t}\n\tif host == \"\" {\n\t\treturn nil, errors.New(\"host is required for a full url on GetMetricsURL\")\n\t}\n\n\tbase, err := o.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbase.Scheme = scheme\n\tbase.Host = host\n\treturn base, nil\n}\n\n\nfunc (o *GetMetricsURL) StringFull(scheme, host string) string {\n\treturn o.Must(o.BuildFull(scheme, host)).String()\n}\n\nfunc (o *GetMetricsURL) Must(u *url.URL, err error) *url.URL ", "output": "{\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif u == nil {\n\t\tpanic(\"url can't be nil\")\n\t}\n\treturn u\n}"} {"input": "package api\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/resource\"\n)\n\n\nfunc (self ResourceName) String() string {\n\treturn string(self)\n}\n\n\n\n\n\nfunc (self *ResourceList) Memory() *resource.Quantity {\n\tif val, ok := (*self)[ResourceMemory]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{}\n}\n\nfunc (self *ResourceList) Pods() *resource.Quantity {\n\tif val, ok := (*self)[ResourcePods]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{}\n}\n\nfunc GetContainerStatus(statuses []ContainerStatus, name string) (ContainerStatus, bool) {\n\tfor i := range statuses {\n\t\tif statuses[i].Name == name {\n\t\t\treturn statuses[i], true\n\t\t}\n\t}\n\treturn ContainerStatus{}, false\n}\n\nfunc GetExistingContainerStatus(statuses []ContainerStatus, name string) ContainerStatus {\n\tfor i := range statuses {\n\t\tif statuses[i].Name == name {\n\t\t\treturn statuses[i]\n\t\t}\n\t}\n\treturn ContainerStatus{}\n}\n\n\nfunc IsPodReady(pod *Pod) bool {\n\tfor _, c := range pod.Status.Conditions {\n\t\tif c.Type == PodReady && c.Status == ConditionTrue {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (self *ResourceList) Cpu() *resource.Quantity ", "output": "{\n\tif val, ok := (*self)[ResourceCPU]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{}\n}"} {"input": "package common\n\n\n\nimport (\n\t\"github.com/mitchellh/multistep\"\n\t\"github.com/mitchellh/packer/packer\"\n\t\"log\"\n\t\"os\"\n\t\"time\"\n)\n\ntype StepPrepareOutputDir struct {\n\tForce bool\n\tPath string\n}\n\n\n\nfunc (self *StepPrepareOutputDir) Cleanup(state multistep.StateBag) {\n\t_, cancelled := state.GetOk(multistep.StateCancelled)\n\t_, halted := state.GetOk(multistep.StateHalted)\n\n\tif cancelled || halted {\n\t\tui := state.Get(\"ui\").(packer.Ui)\n\n\t\tui.Say(\"Deleting output directory...\")\n\t\tfor i := 0; i < 5; i++ {\n\t\t\terr := os.RemoveAll(self.Path)\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tlog.Printf(\"Error removing output dir: %s\", err)\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t}\n\t}\n}\n\nfunc (self *StepPrepareOutputDir) Run(state multistep.StateBag) multistep.StepAction ", "output": "{\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\tif _, err := os.Stat(self.Path); err == nil && self.Force {\n\t\tui.Say(\"Deleting previous output directory...\")\n\t\tos.RemoveAll(self.Path)\n\t}\n\n\tif err := os.MkdirAll(self.Path, 0755); err != nil {\n\t\tstate.Put(\"error\", err)\n\t\treturn multistep.ActionHalt\n\t}\n\n\treturn multistep.ActionContinue\n}"} {"input": "package persistence\n\n\ntype Database struct {\n\tConnstring string\n}\n\n\n\nfunc OpenDatabase(connstring string) *Database ", "output": "{\n\treturn &Database{Connstring: connstring}\n}"} {"input": "package client\n\n\n\n\nimport (\n\t\"github.com/go-openapi/runtime\"\n\thttptransport \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/jkawamoto/roadie/cloud/azure/subscriptions/client/subscriptions\"\n\t\"github.com/jkawamoto/roadie/cloud/azure/subscriptions/client/tenants\"\n)\n\n\nvar Default = NewHTTPClient(nil)\n\n\nfunc NewHTTPClient(formats strfmt.Registry) *SubscriptionClient {\n\tif formats == nil {\n\t\tformats = strfmt.Default\n\t}\n\ttransport := httptransport.New(\"management.azure.com\", \"/\", []string{\"https\"})\n\treturn New(transport, formats)\n}\n\n\n\n\n\ntype SubscriptionClient struct {\n\tSubscriptions *subscriptions.Client\n\n\tTenants *tenants.Client\n\n\tTransport runtime.ClientTransport\n}\n\n\nfunc (c *SubscriptionClient) SetTransport(transport runtime.ClientTransport) {\n\tc.Transport = transport\n\n\tc.Subscriptions.SetTransport(transport)\n\n\tc.Tenants.SetTransport(transport)\n\n}\n\nfunc New(transport runtime.ClientTransport, formats strfmt.Registry) *SubscriptionClient ", "output": "{\n\tcli := new(SubscriptionClient)\n\tcli.Transport = transport\n\n\tcli.Subscriptions = subscriptions.New(transport, formats)\n\n\tcli.Tenants = tenants.New(transport, formats)\n\n\treturn cli\n}"} {"input": "package sorting\n\nimport (\n\t. \"gopkg.in/check.v1\"\n)\n\nvar _ = Suite(&MySuite{})\n\n\n\nfunc (s *MySuite) BenchmarkNumberOfDiscIntersections(c *C) {\n\tfor i := 0; i < c.N; i++ {\n\t\tNumberOfDiscIntersections([]int{1, 5, 2, 1, 4, 0})\n\t}\n}\n\nfunc (s *MySuite) TestNumberOfDiscIntersections(c *C) ", "output": "{\n\tc.Assert(NumberOfDiscIntersections([]int{1, 5, 2, 1, 4, 0}), Equals, 11)\n}"} {"input": "package pgjson\n\nimport (\n\t\"io\"\n)\n\nvar provider Provider = StdProvider{}\n\nfunc SetProvider(p Provider) {\n\tprovider = p\n}\n\ntype Provider interface {\n\tMarshal(v interface{}) ([]byte, error)\n\tUnmarshal(data []byte, v interface{}) error\n\tNewEncoder(w io.Writer) Encoder\n\tNewDecoder(r io.Reader) Decoder\n}\n\ntype Decoder interface {\n\tDecode(v interface{}) error\n\tUseNumber()\n}\n\ntype Encoder interface {\n\tEncode(v interface{}) error\n}\n\nfunc Marshal(v interface{}) ([]byte, error) {\n\treturn provider.Marshal(v)\n}\n\nfunc Unmarshal(data []byte, v interface{}) error {\n\treturn provider.Unmarshal(data, v)\n}\n\n\n\nfunc NewDecoder(r io.Reader) Decoder {\n\treturn provider.NewDecoder(r)\n}\n\nfunc NewEncoder(w io.Writer) Encoder ", "output": "{\n\treturn provider.NewEncoder(w)\n}"} {"input": "package assertstate\n\nimport (\n\t\"github.com/snapcore/snapd/asserts\"\n\t\"github.com/snapcore/snapd/logger\"\n\t\"github.com/snapcore/snapd/overlord/auth\"\n\t\"github.com/snapcore/snapd/overlord/snapstate\"\n\t\"github.com/snapcore/snapd/overlord/state\"\n)\n\n\nfunc userFromUserID(st *state.State, userID int) (*auth.UserState, error) {\n\tif userID == 0 {\n\t\treturn nil, nil\n\t}\n\treturn auth.User(st, userID)\n}\n\n\n\nfunc doFetch(s *state.State, userID int, deviceCtx snapstate.DeviceContext, fetching func(asserts.Fetcher) error) error ", "output": "{\n\n\tdb := cachedDB(s)\n\n\tunsupported := func(ref *asserts.Ref, unsupportedErr error) error {\n\t\tif _, err := ref.Resolve(db.Find); err != nil {\n\t\t\treturn unsupportedErr\n\t\t}\n\t\tlogger.Noticef(\"Cannot update assertion %v: %v\", ref, unsupportedErr)\n\t\treturn nil\n\t}\n\n\tb := asserts.NewBatch(unsupported)\n\n\tuser, err := userFromUserID(s, userID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsto := snapstate.Store(s, deviceCtx)\n\n\tretrieve := func(ref *asserts.Ref) (asserts.Assertion, error) {\n\t\treturn sto.Assertion(ref.Type, ref.PrimaryKey, user)\n\t}\n\n\ts.Unlock()\n\terr = b.Fetch(db, retrieve, fetching)\n\ts.Lock()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn b.CommitTo(db, nil)\n}"} {"input": "package lnwire\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\ntype NeighborAckMessage struct {\n\tRoutingMessageBase\n}\n\nfunc (msg *NeighborAckMessage) String() string {\n\treturn fmt.Sprintf(\"NeighborAckMessage{%v %v}\", msg.SenderID, msg.ReceiverID)\n}\n\n\n\nfunc (msg *NeighborAckMessage) Encode(w io.Writer, pver uint32) error{\n\treturn nil\n}\n\nfunc (msg *NeighborAckMessage) Decode(r io.Reader, pver uint32) error{\n\treturn nil\n}\n\nfunc (msg *NeighborAckMessage) MaxPayloadLength(uint32) uint32{\n\treturn 0\n}\n\nfunc (msg *NeighborAckMessage) Validate() error{\n\treturn nil\n}\n\nvar _ Message = (*NeighborAckMessage)(nil)\n\nfunc (msg *NeighborAckMessage) Command() uint32", "output": "{\n\treturn CmdNeighborAckMessage\n}"} {"input": "package sshConfig\n\n\nfunc ValidAddressFamilyAnswers() []string {\n\treturn []string{\"\", \"any\", \"inet\", \"inet6\"}\n}\n\n\n\n\nfunc ValidYesOrNo() []string {\n\treturn []string{\"\", \"yes\", \"no\"}\n}\n\n\n\n\n\nfunc ValidStringArgs(possibilities []string, received string) bool ", "output": "{\n\tfor _, possible := range possibilities {\n\t\tif possible == received {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package sdk\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\nfunc init() {\n\tNowTime = time.Now\n\tSleep = time.Sleep\n\tSleepWithContext = sleepWithContext\n}\n\n\n\nvar NowTime func() time.Time\n\n\n\nvar Sleep func(time.Duration)\n\n\n\n\n\n\nvar SleepWithContext func(context.Context, time.Duration) error\n\n\n\n\nfunc sleepWithContext(ctx context.Context, dur time.Duration) error {\n\tt := time.NewTimer(dur)\n\tdefer t.Stop()\n\n\tselect {\n\tcase <-t.C:\n\t\tbreak\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc noOpSleep(time.Duration) {}\n\n\n\nfunc TestingUseNopSleep() func() {\n\tSleepWithContext = noOpSleepWithContext\n\tSleep = noOpSleep\n\n\treturn func() {\n\t\tSleepWithContext = sleepWithContext\n\t\tSleep = time.Sleep\n\t}\n}\n\n\n\nfunc TestingUseReferenceTime(referenceTime time.Time) func() {\n\tNowTime = func() time.Time {\n\t\treturn referenceTime\n\t}\n\treturn func() {\n\t\tNowTime = time.Now\n\t}\n}\n\nfunc noOpSleepWithContext(context.Context, time.Duration) error ", "output": "{\n\treturn nil\n}"} {"input": "package datasource\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/golang/glog\"\n\tcadvisorClient \"github.com/google/cadvisor/client\"\n\tcadvisor \"github.com/google/cadvisor/info/v1\"\n\t\"k8s.io/heapster/sources/api\"\n)\n\ntype cadvisorSource struct{}\n\nfunc (self *cadvisorSource) parseStat(containerInfo *cadvisor.ContainerInfo) *api.Container {\n\tcontainer := &api.Container{\n\t\tName: containerInfo.Name,\n\t\tSpec: containerInfo.Spec,\n\t\tStats: sampleContainerStats(containerInfo.Stats),\n\t}\n\tif len(containerInfo.Aliases) > 0 {\n\t\tcontainer.Name = containerInfo.Aliases[0]\n\t}\n\n\treturn container\n}\n\nfunc (self *cadvisorSource) getAllContainers(client *cadvisorClient.Client, start, end time.Time) (subcontainers []*api.Container, root *api.Container, err error) {\n\tallContainers, err := client.SubcontainersInfo(\"/\",\n\t\t&cadvisor.ContainerInfoRequest{Start: start, End: end})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfor _, containerInfo := range allContainers {\n\t\tcontainer := self.parseStat(&containerInfo)\n\t\tif containerInfo.Name == \"/\" {\n\t\t\troot = container\n\t\t} else {\n\t\t\tsubcontainers = append(subcontainers, container)\n\t\t}\n\t}\n\n\treturn subcontainers, root, nil\n}\n\n\n\nfunc (self *cadvisorSource) GetAllContainers(host Host, start, end time.Time) (subcontainers []*api.Container, root *api.Container, err error) ", "output": "{\n\turl := fmt.Sprintf(\"http:%s:%d/\", host.IP, host.Port)\n\tclient, err := cadvisorClient.NewClient(url)\n\tif err != nil {\n\t\treturn\n\t}\n\tsubcontainers, root, err = self.getAllContainers(client, start, end)\n\tif err != nil {\n\t\tglog.Errorf(\"failed to get stats from cadvisor %q - %v\\n\", url, err)\n\t}\n\treturn\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/labstack/echo\"\n)\n\n\ntype Error struct {\n\tMessage string `json:\"message\"`\n}\n\n\nfunc OK(c echo.Context, payload interface{}) error {\n\treturn c.JSON(http.StatusOK, payload)\n}\n\n\nfunc Created(c echo.Context, payload interface{}) error {\n\treturn c.JSON(http.StatusCreated, payload)\n}\n\n\nfunc NoContent(c echo.Context) error {\n\treturn c.NoContent(http.StatusNoContent)\n}\n\n\nfunc BadRequest(c echo.Context, msg string) error {\n\treturn c.JSON(http.StatusBadRequest, Error{msg})\n}\n\n\n\n\n\nfunc Conflict(c echo.Context, msg string) error {\n\treturn c.JSON(http.StatusConflict, Error{msg})\n}\n\n\nfunc Invalid(c echo.Context, msg string) error {\n\treturn c.JSON(422, Error{msg})\n}\n\n\n\nfunc InternalServerError(c echo.Context, err error) error {\n\tlog.WithFields(log.Fields{\n\t\t\"request_id\": RequestID(c),\n\t}).Error(err)\n\n\treturn c.JSON(http.StatusInternalServerError, Error{\"Oops! Something went wrong\"})\n}\n\nfunc NotFound(c echo.Context) error ", "output": "{\n\treturn c.JSON(http.StatusNotFound, Error{\"Resource not found\"})\n}"} {"input": "package factory\n\nimport (\n\tcontext \"context\"\n\n\texternalversions \"knative.dev/eventing-kafka/pkg/client/informers/externalversions\"\n\tclient \"knative.dev/eventing-kafka/pkg/client/injection/client\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Default.RegisterInformerFactory(withInformerFactory)\n}\n\n\ntype Key struct{}\n\nfunc withInformerFactory(ctx context.Context) context.Context {\n\tc := client.Get(ctx)\n\topts := make([]externalversions.SharedInformerOption, 0, 1)\n\tif injection.HasNamespaceScope(ctx) {\n\t\topts = append(opts, externalversions.WithNamespace(injection.GetNamespaceScope(ctx)))\n\t}\n\treturn context.WithValue(ctx, Key{},\n\t\texternalversions.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...))\n}\n\n\n\n\nfunc Get(ctx context.Context) externalversions.SharedInformerFactory ", "output": "{\n\tuntyped := ctx.Value(Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch knative.dev/eventing-kafka/pkg/client/informers/externalversions.SharedInformerFactory from context.\")\n\t}\n\treturn untyped.(externalversions.SharedInformerFactory)\n}"} {"input": "package errors\n\nimport (\n\t\"sync\"\n)\n\n\n\n\n\n\n\n\n\ntype LazyMultiError interface {\n\tAssign(int, error) bool\n\n\tGetOne(int) error\n\n\tGet() error\n}\n\ntype lazyMultiError struct {\n\tsync.Mutex\n\n\tsize int\n\tme MultiError\n}\n\n\nfunc NewLazyMultiError(size int) LazyMultiError {\n\treturn &lazyMultiError{size: size}\n}\n\nfunc (e *lazyMultiError) Assign(i int, err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\te.Lock()\n\tdefer e.Unlock()\n\tif e.me == nil {\n\t\te.me = make(MultiError, e.size)\n\t}\n\te.me[i] = err\n\treturn true\n}\n\nfunc (e *lazyMultiError) GetOne(i int) error {\n\te.Lock()\n\tdefer e.Unlock()\n\tif e.me == nil {\n\t\treturn nil\n\t}\n\treturn e.me[i]\n}\n\n\n\nfunc (e *lazyMultiError) Get() error ", "output": "{\n\te.Lock()\n\tdefer e.Unlock()\n\tif e.me == nil {\n\t\treturn nil\n\t}\n\treturn e.me\n}"} {"input": "package resourcemanager\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteTemplateRequest struct {\n\n\tTemplateId *string `mandatory:\"true\" contributesTo:\"path\" name:\"templateId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteTemplateRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteTemplateRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request DeleteTemplateRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteTemplateResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteTemplateResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteTemplateResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteTemplateRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package zip_test\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/klauspost/compress/flate\"\n\t\"github.com/klauspost/compress/zip\"\n)\n\n\n\nfunc ExampleReader() {\n\tr, err := zip.OpenReader(\"testdata/readme.zip\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer r.Close()\n\n\tfor _, f := range r.File {\n\t\tfmt.Printf(\"Contents of %s:\\n\", f.Name)\n\t\trc, err := f.Open()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t_, err = io.CopyN(os.Stdout, rc, 68)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\trc.Close()\n\t\tfmt.Println()\n\t}\n}\n\nfunc ExampleWriter_RegisterCompressor() {\n\n\tbuf := new(bytes.Buffer)\n\n\tw := zip.NewWriter(buf)\n\n\tvar fw *flate.Writer\n\n\tw.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {\n\t\tvar err error\n\t\tif fw == nil {\n\t\t\tfw, err = flate.NewWriter(out, flate.BestCompression)\n\t\t} else {\n\t\t\tfw.Reset(out)\n\t\t}\n\t\treturn fw, err\n\t})\n\n}\n\nfunc ExampleWriter() ", "output": "{\n\tbuf := new(bytes.Buffer)\n\n\tw := zip.NewWriter(buf)\n\n\tvar files = []struct {\n\t\tName, Body string\n\t}{\n\t\t{\"readme.txt\", \"This archive contains some text files.\"},\n\t\t{\"gopher.txt\", \"Gopher names:\\nGeorge\\nGeoffrey\\nGonzo\"},\n\t\t{\"todo.txt\", \"Get animal handling licence.\\nWrite more examples.\"},\n\t}\n\tfor _, file := range files {\n\t\tf, err := w.Create(file.Name)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t_, err = f.Write([]byte(file.Body))\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\terr := w.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n)\n\ntype limitedReader struct {\n\tsub io.Reader\n\tremaining int64\n}\n\n\n\nfunc (self *limitedReader) Close() error {\n\treturn nil\n}\n\nfunc (self *limitedReader) Read(p []byte) (int, error) ", "output": "{\n\n\tif self.remaining <= 0 {\n\t\treturn 0, io.EOF\n\t}\n\n\tvar n int\n\tvar err error\n\n\tif int64(len(p)) > self.remaining {\n\t\tl := int(self.remaining)\n\t\tbuf := make([]byte, l, l)\n\t\tn, err = self.sub.Read(buf)\n\t\tif err == nil {\n\t\t\tcopy(p, buf)\n\t\t}\n\t} else {\n\t\tn, err = self.sub.Read(p)\n\t}\n\n\tif err == io.EOF && self.remaining > 0 {\n\t\terr = ErrRangeNotSatisfiable\n\t} else if err == nil {\n\t\tself.remaining = self.remaining - int64(n)\n\t}\n\treturn n, err\n}"} {"input": "package errors2\n\nimport (\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tlvldbug = iota\n\tlvlinfo\n\tlvlerr\n\tlvlcrit\n)\n\ntype logMessage struct {\n\ttime time.Time\n\tlevel int\n\tmessage string\n}\n\ntype Logger struct {\n\tmessages []*logMessage\n\tTimer Timer\n}\n\nfunc (l *Logger) Debug(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvldbug, message: message})\n}\n\nfunc (l *Logger) Info(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvlinfo, message: message})\n}\n\n\n\nfunc (l *Logger) Critical(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvlcrit, message: message})\n}\n\nvar lock = &sync.Mutex{}\n\nfunc (l *Logger) log(message *logMessage) {\n\tlock.Lock()\n\tl.messages = append(l.messages, message)\n\tlock.Unlock()\n}\n\nfunc (l *Logger) Error(message string) ", "output": "{\n\tl.log(&logMessage{time: time.Now(), level: lvlerr, message: message})\n}"} {"input": "package flatmap\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\nfunc Expand(m map[string]string, key string) interface{} {\n\tif v, ok := m[key]; ok {\n\t\tif v == \"true\" {\n\t\t\treturn true\n\t\t} else if v == \"false\" {\n\t\t\treturn false\n\t\t}\n\n\t\treturn v\n\t}\n\n\tif _, ok := m[key+\".#\"]; ok {\n\t\treturn expandArray(m, key)\n\t}\n\n\tprefix := key + \".\"\n\tfor k, _ := range m {\n\t\tif strings.HasPrefix(k, prefix) {\n\t\t\treturn expandMap(m, prefix)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc expandArray(m map[string]string, prefix string) []interface{} {\n\tnum, err := strconv.ParseInt(m[prefix+\".#\"], 0, 0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tresult := make([]interface{}, num)\n\tfor i := 0; i < int(num); i++ {\n\t\tresult[i] = Expand(m, fmt.Sprintf(\"%s.%d\", prefix, i))\n\t}\n\n\treturn result\n}\n\n\n\nfunc expandMap(m map[string]string, prefix string) map[string]interface{} ", "output": "{\n\tresult := make(map[string]interface{})\n\tfor k, _ := range m {\n\t\tif !strings.HasPrefix(k, prefix) {\n\t\t\tcontinue\n\t\t}\n\n\t\tkey := k[len(prefix):]\n\t\tidx := strings.Index(key, \".\")\n\t\tif idx != -1 {\n\t\t\tkey = key[:idx]\n\t\t}\n\t\tif _, ok := result[key]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tresult[key] = Expand(m, k[:len(prefix)+len(key)])\n\t}\n\n\treturn result\n}"} {"input": "package registry\n\nimport (\n \"github.com/twitchyliquid64/CNC/plugin/exec\"\n)\n\n\nvar dispatchMethod func(string, interface{})bool = nil\nvar deregisterPluginMethod func (plugin *exec.Plugin) = nil\n\nfunc SetupDispatchMethod(in func(string, interface{})bool) {\n dispatchMethod = in\n}\n\n\n\nfunc DeregisterPluginMethod(plugin *exec.Plugin){\n if deregisterPluginMethod == nil{\n panic(\"deregisterPluginMethod == nil\")\n }\n deregisterPluginMethod(plugin)\n}\n\nfunc DispatchEvent(typ string, data interface{})bool{\n if dispatchMethod != nil {\n return dispatchMethod(typ, data)\n }\n return false\n}\n\nfunc SetupDeregisterMethod(in func (plugin *exec.Plugin))", "output": "{\n deregisterPluginMethod = in\n}"} {"input": "package cluster\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\nfunc addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}\n\nfunc SetDefaults_InstanceGroup(obj *InstanceGroup) {\n\tif obj.Spec.ProvisionPolicy == \"\" {\n\t\tobj.Spec.ProvisionPolicy = InstanceGroupProvisionDynamicOnly\n\t}\n}\n\nfunc SetDefaults_Instance(obj *Instance) {\n\tif obj.Spec.ReclaimPolicy == \"\" {\n\t\tobj.Spec.ReclaimPolicy = InstanceReclaimDelete\n\t}\n\n\tif obj.Status.Phase == \"\" {\n\t\tobj.Status.Phase = InstancePending\n\t}\n}\n\nfunc SetDefaults_Network(obj *Network) {\n\tif obj.Status.Phase == \"\" {\n\t\tobj.Status.Phase = NetworkPending\n\t}\n}\n\n\n\nfunc SetDefaults_ReservedInstance(obj *ReservedInstance) ", "output": "{\n\tif obj.Status.Phase == \"\" {\n\t\tobj.Status.Phase = ReservedInstanceAvailable\n\t}\n}"} {"input": "package cmd\n\n\nimport (\n\t\"fmt\"\n\t\"github.com/madhusudhancs/redis/cache\"\n\t\"strings\"\n)\n\nvar (\n\tcommands map[string]RunFunc\n)\n\nfunc init() {\n\tcommands = make(map[string]RunFunc)\n}\n\n\ntype Command struct {\n\tName string\n\tOptions []string\n}\n\n\nfunc NewCommand(req string) (Command, error) {\n\tfields := strings.Fields(req)\n\n\tif len(fields) == 0 {\n\t\treturn Command{}, fmt.Errorf(\"Invalid command\")\n\t}\n\n\tcommand := Command{}\n\tcommand.Name = strings.ToUpper(fields[0])\n\tcommand.Options = fields[1:]\n\n\tfor i, option := range command.Options {\n\t\tcommand.Options[i] = strings.Replace(option, `\"`, \"\", -1)\n\t}\n\n\treturn command, nil\n}\n\ntype RunFunc func(options []string, cache *cache.Cache) ([]byte, bool)\n\n\n\n\n\nfunc ExecuteCmd(cmd Command, cache *cache.Cache) ([]byte, bool) {\n\trunFunc, ok := commands[cmd.Name]\n\tif !ok {\n\t\treturn GetErrMsg(fmt.Sprintf(\"ERR unknown command '%s'\", cmd.Name)), false\n\t}\n\n\treturn runFunc(cmd.Options, cache)\n}\n\nfunc Register(cmdName string, runFunc RunFunc) error ", "output": "{\n\tif _, ok := commands[cmdName]; ok {\n\t\treturn fmt.Errorf(\"command with name %s already registered\", cmdName)\n\t}\n\n\tcommands[cmdName] = runFunc\n\treturn nil\n}"} {"input": "package nginx\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc TestGeoLite2DBExists(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tsetup func()\n\t\twant bool\n\t\twantFiles []string\n\t}{\n\t\t{\n\t\t\tname: \"empty\",\n\t\t\twantFiles: []string{},\n\t\t},\n\t\t{\n\t\t\tname: \"existing files\",\n\t\t\tsetup: func() {\n\t\t\t\tMaxmindEditionIDs = \"GeoLite2-City,GeoLite2-ASN\"\n\t\t\t\tfileExists = func(string) bool {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t},\n\t\t\twant: true,\n\t\t\twantFiles: []string{\"GeoLite2-City.mmdb\", \"GeoLite2-ASN.mmdb\"},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresetForTesting()\n\t\t\tconfig := &MaxmindEditionFiles\n\n\t\t\tif tt.setup != nil {\n\t\t\t\ttt.setup()\n\t\t\t}\n\t\t\tif got := GeoLite2DBExists(); got != tt.want {\n\t\t\t\tt.Errorf(\"GeoLite2DBExists() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(MaxmindEditionFiles, tt.wantFiles) {\n\t\t\t\tt.Errorf(\"nginx.MaxmindEditionFiles = %v, want %v\", MaxmindEditionFiles, tt.wantFiles)\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(*config, tt.wantFiles) {\n\t\t\t\tt.Errorf(\"config.MaxmindEditionFiles = %v, want %v\", *config, tt.wantFiles)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc resetForTesting() ", "output": "{\n\tfileExists = _fileExists\n\tMaxmindLicenseKey = \"\"\n\tMaxmindEditionIDs = \"\"\n\tMaxmindEditionFiles = []string{}\n\tMaxmindMirror = \"\"\n}"} {"input": "package httpRender\n\nimport \"net/http\"\n\n\n\nfunc (t *renderImpl) Redirect(status int, location string) ", "output": "{\n\tif !t.expectWritten(false) {\n\t\treturn\n\t}\n\tt.written = true\n\n\tif !t.expectStatus(0) {\n\t\treturn\n\t}\n\tt.status = status\n\n\thttp.Redirect(t.w, t.req, location, status)\n}"} {"input": "package windows\n\nimport (\n\t\"github.com/docker/libnetwork/driverapi\"\n\t\"github.com/docker/libnetwork/types\"\n)\n\nconst networkType = \"windows\"\n\n\n\ntype driver struct{}\n\n\nfunc Init(dc driverapi.DriverCallback) error {\n\tc := driverapi.Capability{\n\t\tScope: driverapi.LocalScope,\n\t}\n\treturn dc.RegisterDriver(networkType, &driver{}, c)\n}\n\nfunc (d *driver) Config(option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) DeleteNetwork(nid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) DeleteEndpoint(nid, eid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {\n\treturn make(map[string]interface{}, 0), nil\n}\n\n\nfunc (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {\n\treturn nil\n}\n\n\nfunc (d *driver) Leave(nid, eid types.UUID) error {\n\treturn nil\n}\n\n\n\nfunc (d *driver) Type() string ", "output": "{\n\treturn networkType\n}"} {"input": "package module\n\nimport (\n\t\"fmt\"\n\t\"github.com/davidscholberg/irkbot/lib/configure\"\n\t\"github.com/davidscholberg/irkbot/lib/message\"\n)\n\n\n\nfunc quit(cfg *configure.Config, in *message.InboundMsg, actions *actions) {\n\tif in.Event.Nick != cfg.Admin.Owner {\n\t\tactions.say(fmt.Sprintf(\"%s: %s\", in.Event.Nick, cfg.Admin.DenyMessage))\n\t\treturn\n\t}\n\tactions.quit()\n}\n\nfunc helpQuit() []string ", "output": "{\n\ts := \"quit - ragequit IRC (requires owner privilege)\"\n\treturn []string{s}\n}"} {"input": "package cache\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\n\n\n\n\n\n\n\n\ntype Cache interface {\n\tGet(key string) interface{}\n\tGetMulti(keys []string) []interface{}\n\tPut(key string, val interface{}, timeout time.Duration) error\n\tDelete(key string) error\n\tIncr(key string) error\n\tDecr(key string) error\n\tIsExist(key string) bool\n\tClearAll() error\n\tStartAndGC(config string) error\n}\n\n\ntype Instance func() Cache\n\nvar adapters = make(map[string]Instance)\n\n\n\n\n\n\n\n\n\nfunc NewCache(adapterName, config string) (adapter Cache, err error) {\n\tinstanceFunc, ok := adapters[adapterName]\n\tif !ok {\n\t\terr = fmt.Errorf(\"cache: unknown adapter name %q (forgot to import?)\", adapterName)\n\t\treturn\n\t}\n\tadapter = instanceFunc()\n\terr = adapter.StartAndGC(config)\n\tif err != nil {\n\t\tadapter = nil\n\t}\n\treturn\n}\n\nfunc Register(name string, adapter Instance) ", "output": "{\n\tif adapter == nil {\n\t\tpanic(\"cache: Register adapter is nil\")\n\t}\n\tif _, ok := adapters[name]; ok {\n\t\tpanic(\"cache: Register called twice for adapter \" + name)\n\t}\n\tadapters[name] = adapter\n}"} {"input": "package gtk\n\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (v *FileChooserButton) GetFocusOnClick() bool {\n\treturn gobool(C.gtk_file_chooser_button_get_focus_on_click(v.native()))\n}\n\n\nfunc (v *FileChooserButton) SetFocusOnClick(grabFocus bool) {\n\tC.gtk_file_chooser_button_set_focus_on_click(v.native(), gbool(grabFocus))\n}\n\n\n\n\nfunc (v *Button) GetFocusOnClick() bool {\n\tc := C.gtk_button_get_focus_on_click(v.native())\n\treturn gobool(c)\n}\n\n\nfunc (v *Button) SetFocusOnClick(focusOnClick bool) {\n\tC.gtk_button_set_focus_on_click(v.native(), gbool(focusOnClick))\n}\n\n\n\n\nfunc (v *TextIter) BeginsTag(v1 *TextTag) bool {\n\treturn gobool(C.gtk_text_iter_begins_tag(v.native(), v1.native()))\n}\n\n\n\n\nfunc (v *Window) ParseGeometry(geometry string) bool {\n\tcstr := C.CString(geometry)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_window_parse_geometry(v.native(), (*C.gchar)(cstr))\n\treturn gobool(c)\n}\n\n\n\n\n\nfunc (v *Window) SetDefaultGeometry(width, height int) {\n\tC.gtk_window_set_default_geometry(v.native(), C.gint(width),\n\t\tC.gint(height))\n}\n\nfunc (v *Window) ResizeToGeometry(width, height int) ", "output": "{\n\tC.gtk_window_resize_to_geometry(v.native(), C.gint(width), C.gint(height))\n}"} {"input": "package main\n\nimport (\n\t\"os/exec\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\n\n\nfunc openURL(url string) error ", "output": "{\n\tswitch runtime.GOOS {\n\tcase \"darwin\":\n\t\treturn exec.Command(\"open\", url).Run()\n\n\tdefault:\n\t\tcmd := exec.Command(\"xdg-open\", url)\n\t\tcmd.SysProcAttr = &syscall.SysProcAttr{\n\t\t\tSetpgid: true,\n\t\t}\n\t\treturn cmd.Run()\n\t}\n}"} {"input": "package readline\n\nimport \"io\"\n\ntype Instance struct {\n\tt *Terminal\n\to *Operation\n}\n\ntype Config struct {\n\tPrompt string\n\tHistoryFile string\n}\n\nfunc NewEx(cfg *Config) (*Instance, error) {\n\tt, err := NewTerminal(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trl := t.Readline()\n\treturn &Instance{\n\t\tt: t,\n\t\to: rl,\n\t}, nil\n}\n\nfunc New(prompt string) (*Instance, error) {\n\treturn NewEx(&Config{Prompt: prompt})\n}\n\nfunc (i *Instance) Stdout() io.Writer {\n\treturn i.o.Stdout()\n}\n\nfunc (i *Instance) Stderr() io.Writer {\n\treturn i.o.Stderr()\n}\n\n\n\nfunc (i *Instance) ReadSlice() ([]byte, error) {\n\treturn i.o.Slice()\n}\n\nfunc (i *Instance) Close() error {\n\tif err := i.t.Close(); err != nil {\n\t\treturn err\n\t}\n\ti.o.Close()\n\treturn nil\n}\n\nfunc (i *Instance) Readline() (string, error) ", "output": "{\n\treturn i.o.String()\n}"} {"input": "package analytics\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\t\"testing\"\n\t\"time\"\n\n\tadaptertest \"istio.io/istio/mixer/pkg/adapter/test\"\n)\n\nfunc TestLegacySelect(t *testing.T) {\n\n\tenv := adaptertest.NewEnv(t)\n\n\topts := Options{\n\t\tLegacyEndpoint: true,\n\t\tBufferPath: \"\",\n\t\tStagingFileLimit: 10,\n\t\tBaseURL: &url.URL{},\n\t\tKey: \"key\",\n\t\tSecret: \"secret\",\n\t\tClient: http.DefaultClient,\n\t\tnow: time.Now,\n\t}\n\n\tm, err := NewManager(env, opts)\n\tm.Close()\n\tif err != nil {\n\t\tt.Fatalf(\"newManager: %s\", err)\n\t}\n\n\tif _, ok := m.(*legacyAnalytics); !ok {\n\t\tt.Errorf(\"want an *legacyAnalytics type, got: %#v\", m)\n\t}\n}\n\nfunc TestStandardSelect(t *testing.T) {\n\n\tenv := adaptertest.NewEnv(t)\n\n\topts := Options{\n\t\tBufferPath: \"/tmp/apigee-ax/buffer/\",\n\t\tStagingFileLimit: 10,\n\t\tBaseURL: &url.URL{},\n\t\tKey: \"key\",\n\t\tSecret: \"secret\",\n\t\tClient: http.DefaultClient,\n\t\tnow: time.Now,\n\t\tCollectionInterval: time.Minute,\n\t}\n\n\tm, err := NewManager(env, opts)\n\tif err != nil {\n\t\tt.Fatalf(\"newManager: %s\", err)\n\t}\n\tm.Close()\n\n\tif _, ok := m.(*manager); !ok {\n\t\tt.Errorf(\"want an *manager type, got: %#v\", m)\n\t}\n}\n\n\n\nfunc TestStandardBadOptions(t *testing.T) ", "output": "{\n\n\tenv := adaptertest.NewEnv(t)\n\n\topts := Options{\n\t\tBufferPath: \"/tmp/apigee-ax/buffer/\",\n\t\tStagingFileLimit: 0,\n\t\tBaseURL: &url.URL{},\n\t\tKey: \"\",\n\t\tSecret: \"\",\n\t\tClient: http.DefaultClient,\n\t\tnow: time.Now,\n\t}\n\n\twant := \"all analytics options are required\"\n\tm, err := NewManager(env, opts)\n\tif err == nil || err.Error() != want {\n\t\tt.Errorf(\"want: %s, got: %s\", want, err)\n\t}\n\tif m != nil {\n\t\tt.Errorf(\"should not get manager\")\n\t\tm.Close()\n\t}\n}"} {"input": "package host\n\n\n\nfunc charsToString(ca [65]int8) string ", "output": "{\n\ts := make([]byte, len(ca))\n\tvar lens int\n\tfor ; lens < len(ca); lens++ {\n\t\tif ca[lens] == 0 {\n\t\t\tbreak\n\t\t}\n\t\ts[lens] = uint8(ca[lens])\n\t}\n\treturn string(s[0:lens])\n}"} {"input": "package graph\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gonum/graph\"\n\t\"github.com/gonum/graph/concrete\"\n\t\"github.com/gonum/graph/encoding/dot\"\n)\n\ntype Node struct {\n\tId int\n\tUniqueName string\n\tLabelName string\n\tColor string\n}\n\n\n\n\nfunc (n Node) DOTAttributes() []dot.Attribute {\n\tcolor := n.Color\n\tif len(color) == 0 {\n\t\tcolor = \"black\"\n\t}\n\n\treturn []dot.Attribute{\n\t\t{Key: \"label\", Value: fmt.Sprintf(\"%q\", n.LabelName)},\n\t\t{Key: \"color\", Value: color},\n\t}\n}\n\nfunc NewMutableDirectedGraph(g *concrete.DirectedGraph) *MutableDirectedGraph {\n\treturn &MutableDirectedGraph{\n\t\tDirectedGraph: concrete.NewDirectedGraph(),\n\t\tnodesByName: make(map[string]graph.Node),\n\t}\n}\n\ntype MutableDirectedGraph struct {\n\t*concrete.DirectedGraph\n\n\tnodesByName map[string]graph.Node\n}\n\nfunc (g *MutableDirectedGraph) AddNode(n *Node) error {\n\tif _, exists := g.nodesByName[n.UniqueName]; exists {\n\t\treturn fmt.Errorf(\"node .UniqueName collision: %s\", n.UniqueName)\n\t}\n\n\tg.nodesByName[n.UniqueName] = n\n\tg.DirectedGraph.AddNode(n)\n\treturn nil\n}\n\nfunc (g *MutableDirectedGraph) NodeByName(name string) (graph.Node, bool) {\n\tn, exists := g.nodesByName[name]\n\treturn n, exists && g.DirectedGraph.Has(n)\n}\n\nfunc (n Node) ID() int ", "output": "{\n\treturn n.Id\n}"} {"input": "package x509\n\nimport (\n\t\"encoding/pem\"\n)\n\n\ntype CertPool struct {\n\tbySubjectKeyId map[string][]int\n\tbyName map[string][]int\n\tcerts []*Certificate\n}\n\n\nfunc NewCertPool() *CertPool {\n\treturn &CertPool{\n\t\tmake(map[string][]int),\n\t\tmake(map[string][]int),\n\t\tnil,\n\t}\n}\n\n\n\n\n\n\n\nfunc (s *CertPool) AddCert(cert *Certificate) {\n\tif cert == nil {\n\t\tpanic(\"adding nil Certificate to CertPool\")\n\t}\n\n\tfor _, c := range s.certs {\n\t\tif c.Equal(cert) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tn := len(s.certs)\n\ts.certs = append(s.certs, cert)\n\n\tif len(cert.SubjectKeyId) > 0 {\n\t\tkeyId := string(cert.SubjectKeyId)\n\t\ts.bySubjectKeyId[keyId] = append(s.bySubjectKeyId[keyId], n)\n\t}\n\tname := string(cert.RawSubject)\n\ts.byName[name] = append(s.byName[name], n)\n}\n\n\n\n\n\n\n\nfunc (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool) {\n\tfor len(pemCerts) > 0 {\n\t\tvar block *pem.Block\n\t\tblock, pemCerts = pem.Decode(pemCerts)\n\t\tif block == nil {\n\t\t\tbreak\n\t\t}\n\t\tif block.Type != \"CERTIFICATE\" || len(block.Headers) != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tcert, err := ParseCertificate(block.Bytes)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\ts.AddCert(cert)\n\t\tok = true\n\t}\n\n\treturn\n}\n\nfunc (s *CertPool) findVerifiedParents(cert *Certificate) (parents []int) ", "output": "{\n\tif s == nil {\n\t\treturn\n\t}\n\tvar candidates []int\n\n\tif len(cert.AuthorityKeyId) > 0 {\n\t\tcandidates = s.bySubjectKeyId[string(cert.AuthorityKeyId)]\n\t}\n\tif len(candidates) == 0 {\n\t\tcandidates = s.byName[string(cert.RawIssuer)]\n\t}\n\n\tfor _, c := range candidates {\n\t\tif cert.CheckSignatureFrom(s.certs[c]) == nil {\n\t\t\tparents = append(parents, c)\n\t\t}\n\t}\n\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n)\n\ntype Player struct {\n\tlog *os.File\n\tlogTime time.Time\n\tdecoder *json.Decoder\n\tdir string\n\toffset time.Duration\n}\n\nfunc NewPlayer(dir string) *Player {\n\tvar p Player\n\tp.dir = dir\n\treturn &p\n}\n\nfunc (p *Player) Reset() error {\n\tn := p.Then()\n\tp.logTime = logTime(n)\n\tfilename := logFileName(n)\n\tif p.log != nil {\n\t\tp.log.Close()\n\t}\n\tlog.Printf(\"Playing file %s\\n\", filename)\n\tvar err error\n\tp.log, err = os.Open(filepath.Join(p.dir, filename))\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.decoder = json.NewDecoder(p.log)\n\treturn nil\n}\n\n\nfunc (p *Player) Playback(t time.Time) error {\n\tlog.Printf(\"Playing back starting at %s\\n\", t)\n\tp.offset = time.Now().Sub(t)\n\terr := p.Reset()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor {\n\t\tvar m Msg\n\t\terr := p.decoder.Decode(&m)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\td := m.Timestamp.Time.Sub(p.Then())\n\t\tdebugf(\"difference is %f seconds\", d.Seconds())\n\t\tif d > 0 {\n\t\t\ttime.Sleep(d)\n\t\t}\n\t\tm.Print()\n\t}\n}\n\nfunc (p *Player) Then() time.Time {\n\treturn time.Now().Add(-p.offset)\n}\n\n\n\nfunc (p *Player) Close() error ", "output": "{\n\tp.decoder = nil\n\treturn p.log.Close()\n}"} {"input": "package ibmmq\n\n\n\n\nimport \"C\"\n\n\ntype MQCBD struct {\n\tCallbackType int32\n\tOptions int32\n\tCallbackArea interface{}\n\tCallbackFunction MQCB_FUNCTION\n\tCallbackName string\n\tMaxMsgLength int32\n}\n\n\nfunc NewMQCBD() *MQCBD {\n\tcbd := new(MQCBD)\n\tcbd.CallbackType = C.MQCBT_MESSAGE_CONSUMER\n\tcbd.Options = C.MQCBDO_NONE\n\tcbd.CallbackArea = nil\n\tcbd.CallbackFunction = nil\n\tcbd.CallbackName = \"\"\n\tcbd.MaxMsgLength = C.MQCBD_FULL_MSG_LENGTH\n\n\treturn cbd\n}\n\n\n\nfunc copyCBDfromC(mqcbd *C.MQCBD, gocbd *MQCBD) {\n\treturn\n}\n\nfunc copyCBDtoC(mqcbd *C.MQCBD, gocbd *MQCBD) ", "output": "{\n\n\tsetMQIString((*C.char)(&mqcbd.StrucId[0]), \"CBD \", 4)\n\tmqcbd.Version = C.MQCBD_VERSION_1\n\n\tmqcbd.CallbackType = C.MQLONG(gocbd.CallbackType)\n\tmqcbd.Options = C.MQLONG(gocbd.Options) | C.MQCBDO_FAIL_IF_QUIESCING\n\tmqcbd.CallbackArea = (C.MQPTR)(C.NULL)\n\n\tsetMQIString((*C.char)(&mqcbd.CallbackName[0]), gocbd.CallbackName, 128) \n\n\tmqcbd.MaxMsgLength = C.MQLONG(gocbd.MaxMsgLength)\n\n\treturn\n}"} {"input": "package websocket\n\ntype data struct {\n\tIndex int\n\tBody []byte\n\tError error\n}\n\nfunc makeHeader(index int) (header [4]byte) {\n\theader[0] = byte(index >> 24 & 0xff)\n\theader[1] = byte(index >> 16 & 0xff)\n\theader[2] = byte(index >> 8 & 0xff)\n\theader[3] = byte(index & 0xff)\n\treturn\n}\n\n\n\nfunc parseHeader(header []byte) (index int, ok bool) ", "output": "{\n\tindex = int(header[0])<<24 | int(header[1])<<16 | int(header[2])<<8 | int(header[3])\n\tif ok = (header[0]&0x80 == 0); !ok {\n\t\tindex &= 0x7fffffff\n\t}\n\treturn\n}"} {"input": "package migrations\n\nimport (\n\t\"database/sql\"\n\n\t\"github.com/pressly/goose\"\n)\n\n\n\nfunc up00002(tx *sql.Tx) error {\n\t_, err := tx.Exec(`CREATE TABLE IF NOT EXISTS users (email text)`)\n\treturn err\n}\n\nfunc down00002(tx *sql.Tx) error {\n\t_, err := tx.Exec(`DROP TABLE users`)\n\treturn err\n}\n\nfunc init() ", "output": "{\n\tgoose.AddMigration(up00002, down00002)\n}"} {"input": "package time\n\nimport (\n\t\"time\"\n)\n\nconst (\n\tDateTimeLayout = \"2006-01-02 15:04:05\"\n)\n\n\nfunc DateTimeFormat(t time.Time) string {\n\treturn t.Format(DateTimeLayout)\n}\n\n\n\n\n\nfunc MustParseDateTimeFormat(v string) time.Time {\n\tt, _ := ParseDateTimeFormat(v)\n\treturn t\n}\n\nfunc ParseDateTimeFormat(v string) (time.Time, error) ", "output": "{\n\treturn time.Parse(DateTimeLayout, v)\n}"} {"input": "package rtcp\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\n\ntype RapidResynchronizationRequest struct {\n\tSenderSSRC uint32\n\n\tMediaSSRC uint32\n}\n\nconst (\n\trrrLength = 2\n\trrrHeaderLength = ssrcLength * 2\n\trrrMediaOffset = 4\n)\n\n\nfunc (p RapidResynchronizationRequest) Marshal() ([]byte, error) {\n\trawPacket := make([]byte, p.len())\n\tpacketBody := rawPacket[headerLength:]\n\n\tbinary.BigEndian.PutUint32(packetBody, p.SenderSSRC)\n\tbinary.BigEndian.PutUint32(packetBody[rrrMediaOffset:], p.MediaSSRC)\n\n\thData, err := p.Header().Marshal()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcopy(rawPacket, hData)\n\n\treturn rawPacket, nil\n}\n\n\n\n\nfunc (p *RapidResynchronizationRequest) len() int {\n\treturn headerLength + rrrHeaderLength\n}\n\n\nfunc (p *RapidResynchronizationRequest) Header() Header {\n\treturn Header{\n\t\tCount: FormatRRR,\n\t\tType: TypeTransportSpecificFeedback,\n\t\tLength: rrrLength,\n\t}\n}\n\n\nfunc (p *RapidResynchronizationRequest) DestinationSSRC() []uint32 {\n\treturn []uint32{p.MediaSSRC}\n}\n\nfunc (p *RapidResynchronizationRequest) String() string {\n\treturn fmt.Sprintf(\"RapidResynchronizationRequest %x %x\", p.SenderSSRC, p.MediaSSRC)\n}\n\nfunc (p *RapidResynchronizationRequest) Unmarshal(rawPacket []byte) error ", "output": "{\n\n\tif len(rawPacket) < (headerLength + (ssrcLength * 2)) {\n\t\treturn errPacketTooShort\n\t}\n\n\tvar h Header\n\tif err := h.Unmarshal(rawPacket); err != nil {\n\t\treturn err\n\t}\n\n\tif h.Type != TypeTransportSpecificFeedback || h.Count != FormatRRR {\n\t\treturn errWrongType\n\t}\n\n\tp.SenderSSRC = binary.BigEndian.Uint32(rawPacket[headerLength:])\n\tp.MediaSSRC = binary.BigEndian.Uint32(rawPacket[headerLength+ssrcLength:])\n\treturn nil\n}"} {"input": "package AutoMPI\n\nimport (\n\t\"time\"\n)\n\n\ntype WorkerLocation struct {\n\tGUID string\n\tCreationTimeStamp time.Time\n\tModifiedTimeStamp time.Time\n\tparentNodeGUID string\n}\n\n\n\n\nfunc CreateWorkerLocation(GUID string, parentNodeGUID string) *WorkerLocation ", "output": "{\n\tlocation := new(WorkerLocation)\n\tlocation.GUID = GUID\n\tlocation.CreationTimeStamp = time.Now()\n\tlocation.ModifiedTimeStamp = time.Now()\n\tlocation.parentNodeGUID = parentNodeGUID\n\treturn location\n}"} {"input": "package genny\n\nimport (\n\t\"github.com/markbates/safe\"\n\t\"github.com/pkg/errors\"\n)\n\ntype TransformerFn func(File) (File, error)\n\ntype Transformer struct {\n\tExt string\n\tStripExt bool\n\tfn TransformerFn\n}\n\n\n\nfunc NewTransformer(ext string, fn TransformerFn) Transformer {\n\treturn Transformer{\n\t\tExt: ext,\n\t\tfn: fn,\n\t}\n}\n\nfunc (t Transformer) Transform(f File) (File, error) ", "output": "{\n\tif !HasExt(f, t.Ext) {\n\t\treturn f, nil\n\t}\n\tif t.fn == nil {\n\t\treturn f, nil\n\t}\n\terr := safe.RunE(func() error {\n\t\tvar e error\n\t\tf, e = t.fn(f)\n\t\tif e != nil {\n\t\t\treturn errors.WithStack(e)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn f, errors.WithStack(err)\n\t}\n\tif t.StripExt {\n\t\treturn StripExt(f, t.Ext), nil\n\t}\n\treturn f, nil\n}"} {"input": "package xeth\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/ethereum/go-ethereum/common\"\n)\n\n\n\ntype whisperFilter struct {\n\tid int \n\tref *Whisper \n\n\tcache []WhisperMessage \n\tskip map[common.Hash]struct{} \n\tupdate time.Time \n\n\tlock sync.RWMutex \n}\n\n\nfunc newWhisperFilter(id int, ref *Whisper) *whisperFilter {\n\treturn &whisperFilter{\n\t\tid: id,\n\t\tref: ref,\n\n\t\tupdate: time.Now(),\n\t\tskip: make(map[common.Hash]struct{}),\n\t}\n}\n\n\n\n\n\n\nfunc (w *whisperFilter) insert(messages ...WhisperMessage) {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tfor _, message := range messages {\n\t\tif _, ok := w.skip[message.ref.Hash]; !ok {\n\t\t\tw.cache = append(w.cache, messages...)\n\t\t}\n\t}\n}\n\n\nfunc (w *whisperFilter) retrieve() (messages []WhisperMessage) {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tmessages, w.cache = w.cache, nil\n\tw.update = time.Now()\n\n\treturn\n}\n\n\n\nfunc (w *whisperFilter) activity() time.Time {\n\tw.lock.RLock()\n\tdefer w.lock.RUnlock()\n\n\treturn w.update\n}\n\nfunc (w *whisperFilter) messages() []WhisperMessage ", "output": "{\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tw.cache = nil\n\tw.update = time.Now()\n\n\tw.skip = make(map[common.Hash]struct{})\n\tmessages := w.ref.Messages(w.id)\n\tfor _, message := range messages {\n\t\tw.skip[message.ref.Hash] = struct{}{}\n\t}\n\treturn messages\n}"} {"input": "package htpasswd\n\nimport (\n\t\"crypto/sha1\"\n\t\"crypto/subtle\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype sshaPassword struct {\n\thashed []byte\n\tsalt []byte\n}\n\n\nfunc AcceptSsha(src string) (EncodedPasswd, error) {\n\tif !strings.HasPrefix(src, \"{SSHA}\") {\n\t\treturn nil, nil\n\t}\n\n\tb64 := strings.TrimPrefix(src, \"{SSHA}\")\n\thashed, err := base64.StdEncoding.DecodeString(b64)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Malformed ssha(%s): %s\", src, err.Error())\n\t}\n\n\tif len(hashed) < sha1.Size {\n\t\treturn nil, fmt.Errorf(\"Malformed ssha(%s): wrong length\", src)\n\t}\n\n\thash := hashed[:sha1.Size]\n\tsalt := hashed[sha1.Size:]\n\treturn &sshaPassword{hash, salt}, nil\n}\n\n\nfunc RejectSsha(src string) (EncodedPasswd, error) {\n\tif !strings.HasPrefix(src, \"{SSHA}\") {\n\t\treturn nil, nil\n\t}\n\treturn nil, fmt.Errorf(\"ssha passwords are not accepted: %s\", src)\n}\n\n\n\nfunc (s *sshaPassword) MatchesPassword(password string) bool ", "output": "{\n\tsha := append([]byte(password), s.salt[:]...)\n\thash := sha1.Sum(sha)\n\treturn subtle.ConstantTimeCompare(hash[:], s.hashed) == 1\n}"} {"input": "package fakes\n\nimport (\n\t\"net\"\n\t\"sync\"\n\n\t\"github.com/cloudfoundry-incubator/diego-ssh/cf-plugin/cmd\"\n)\n\ntype FakeListenerFactory struct {\n\tListenStub func(network, address string) (net.Listener, error)\n\tlistenMutex sync.RWMutex\n\tlistenArgsForCall []struct {\n\t\tnetwork string\n\t\taddress string\n\t}\n\tlistenReturns struct {\n\t\tresult1 net.Listener\n\t\tresult2 error\n\t}\n}\n\nfunc (fake *FakeListenerFactory) Listen(network string, address string) (net.Listener, error) {\n\tfake.listenMutex.Lock()\n\tfake.listenArgsForCall = append(fake.listenArgsForCall, struct {\n\t\tnetwork string\n\t\taddress string\n\t}{network, address})\n\tfake.listenMutex.Unlock()\n\tif fake.ListenStub != nil {\n\t\treturn fake.ListenStub(network, address)\n\t} else {\n\t\treturn fake.listenReturns.result1, fake.listenReturns.result2\n\t}\n}\n\nfunc (fake *FakeListenerFactory) ListenCallCount() int {\n\tfake.listenMutex.RLock()\n\tdefer fake.listenMutex.RUnlock()\n\treturn len(fake.listenArgsForCall)\n}\n\n\n\nfunc (fake *FakeListenerFactory) ListenReturns(result1 net.Listener, result2 error) {\n\tfake.ListenStub = nil\n\tfake.listenReturns = struct {\n\t\tresult1 net.Listener\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nvar _ cmd.ListenerFactory = new(FakeListenerFactory)\n\nfunc (fake *FakeListenerFactory) ListenArgsForCall(i int) (string, string) ", "output": "{\n\tfake.listenMutex.RLock()\n\tdefer fake.listenMutex.RUnlock()\n\treturn fake.listenArgsForCall[i].network, fake.listenArgsForCall[i].address\n}"} {"input": "package main\n\nimport \"github.com/augustoroman/serial_lcd\"\n\ntype FakeLcd struct{}\n\nfunc (f FakeLcd) SetBG(r, g, b uint8) error { return nil }\n\nfunc (f FakeLcd) SetBrightness(b uint8) error { return nil }\nfunc (f FakeLcd) SetContrast(c uint8) error { return nil }\nfunc (f FakeLcd) SetAutoscroll(On bool) error { return nil }\nfunc (f FakeLcd) SetSize(cols, rows uint8) error { return nil }\nfunc (f FakeLcd) Clear() error { return nil }\nfunc (f FakeLcd) Home() error { return nil }\nfunc (f FakeLcd) MoveTo(col, row uint8) error { return nil }\nfunc (f FakeLcd) MoveForward() error { return nil }\nfunc (f FakeLcd) MoveBack() error { return nil }\nfunc (f FakeLcd) Write(b []byte) (int, error) { return len(b), nil }\n\nfunc (f FakeLcd) CreateCustomChar(spot uint8, c serial_lcd.Char) error { return nil }\n\nfunc (f FakeLcd) SetOn(On bool) error ", "output": "{ return nil }"} {"input": "package fs\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nconst (\n\tWindowsTempPrefix = \"~syncthing~\"\n\tUnixTempPrefix = \".syncthing.\"\n)\n\nvar TempPrefix string\n\n\n\n\nconst maxFilenameLength = 160 - len(UnixTempPrefix) - len(\".tmp\")\n\nfunc init() {\n\tif runtime.GOOS == \"windows\" {\n\t\tTempPrefix = WindowsTempPrefix\n\t} else {\n\t\tTempPrefix = UnixTempPrefix\n\t}\n}\n\n\n\n\nfunc IsTemporary(name string) bool {\n\tname = filepath.Base(name)\n\tif strings.HasPrefix(name, WindowsTempPrefix) ||\n\t\tstrings.HasPrefix(name, UnixTempPrefix) {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc TempName(name string) string ", "output": "{\n\ttdir := filepath.Dir(name)\n\ttbase := filepath.Base(name)\n\tif len(tbase) > maxFilenameLength {\n\t\thash := md5.New()\n\t\thash.Write([]byte(name))\n\t\ttbase = fmt.Sprintf(\"%x\", hash.Sum(nil))\n\t}\n\ttname := fmt.Sprintf(\"%s%s.tmp\", TempPrefix, tbase)\n\treturn filepath.Join(tdir, tname)\n}"} {"input": "package topology\n\nimport (\n\t\"github.com/skydive-project/skydive/graffiti/getter\"\n\t\"strings\"\n)\n\nfunc (obj *NextHop) GetFieldBool(key string) (bool, error) {\n\treturn false, getter.ErrFieldNotFound\n}\n\nfunc (obj *NextHop) GetFieldInt64(key string) (int64, error) {\n\tswitch key {\n\tcase \"Priority\":\n\t\treturn int64(obj.Priority), nil\n\tcase \"IfIndex\":\n\t\treturn int64(obj.IfIndex), nil\n\t}\n\treturn 0, getter.ErrFieldNotFound\n}\n\nfunc (obj *NextHop) GetFieldString(key string) (string, error) {\n\tswitch key {\n\tcase \"IP\":\n\t\treturn obj.IP.String(), nil\n\tcase \"MAC\":\n\t\treturn string(obj.MAC), nil\n\t}\n\treturn \"\", getter.ErrFieldNotFound\n}\n\n\n\nfunc (obj *NextHop) MatchBool(key string, predicate getter.BoolPredicate) bool {\n\treturn false\n}\n\nfunc (obj *NextHop) MatchInt64(key string, predicate getter.Int64Predicate) bool {\n\tif b, err := obj.GetFieldInt64(key); err == nil {\n\t\treturn predicate(b)\n\t}\n\treturn false\n}\n\nfunc (obj *NextHop) MatchString(key string, predicate getter.StringPredicate) bool {\n\tif b, err := obj.GetFieldString(key); err == nil {\n\t\treturn predicate(b)\n\t}\n\treturn false\n}\n\nfunc (obj *NextHop) GetField(key string) (interface{}, error) {\n\tif s, err := obj.GetFieldString(key); err == nil {\n\t\treturn s, nil\n\t}\n\n\tif i, err := obj.GetFieldInt64(key); err == nil {\n\t\treturn i, nil\n\t}\n\treturn nil, getter.ErrFieldNotFound\n}\n\nfunc init() {\n\tstrings.Index(\"\", \".\")\n}\n\nfunc (obj *NextHop) GetFieldKeys() []string ", "output": "{\n\treturn []string{\n\t\t\"Priority\",\n\t\t\"IP\",\n\t\t\"MAC\",\n\t\t\"IfIndex\",\n\t}\n}"} {"input": "package github\n\nimport (\n\t\"github.com/hashicorp/terraform/helper/schema\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\n\nfunc Provider() terraform.ResourceProvider {\n\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"token\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"GITHUB_TOKEN\", nil),\n\t\t\t\tDescription: descriptions[\"token\"],\n\t\t\t},\n\t\t\t\"organization\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"GITHUB_ORGANIZATION\", nil),\n\t\t\t\tDescription: descriptions[\"organization\"],\n\t\t\t},\n\t\t},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"github_team\": resourceGithubTeam(),\n\t\t\t\"github_team_membership\": resourceGithubTeamMembership(),\n\t\t\t\"github_team_repository\": resourceGithubTeamRepository(),\n\t\t\t\"github_membership\": resourceGithubMembership(),\n\t\t},\n\n\t\tConfigureFunc: providerConfigure,\n\t}\n}\n\nvar descriptions map[string]string\n\n\n\nfunc providerConfigure(d *schema.ResourceData) (interface{}, error) {\n\tconfig := Config{\n\t\tToken: d.Get(\"token\").(string),\n\t\tOrganization: d.Get(\"organization\").(string),\n\t}\n\n\treturn config.Client()\n}\n\nfunc init() ", "output": "{\n\tdescriptions = map[string]string{\n\t\t\"token\": \"The OAuth token used to connect to GitHub.\",\n\n\t\t\"organization\": \"The GitHub organization name to manage.\",\n\t}\n}"} {"input": "package context\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/docker/cli/cli/config\"\n\t\"github.com/docker/cli/cli/config/configfile\"\n\t\"github.com/docker/cli/cli/context/store\"\n\t\"gotest.tools/assert\"\n)\n\nfunc TestUse(t *testing.T) {\n\tconfigDir, err := ioutil.TempDir(\"\", t.Name()+\"config\")\n\tassert.NilError(t, err)\n\tdefer os.RemoveAll(configDir)\n\tconfigFilePath := filepath.Join(configDir, \"config.json\")\n\ttestCfg := configfile.New(configFilePath)\n\tcli, cleanup := makeFakeCli(t, withCliConfig(testCfg))\n\tdefer cleanup()\n\terr = RunCreate(cli, &CreateOptions{\n\t\tName: \"test\",\n\t\tDocker: map[string]string{},\n\t})\n\tassert.NilError(t, err)\n\tassert.NilError(t, newUseCommand(cli).RunE(nil, []string{\"test\"}))\n\treloadedConfig, err := config.Load(configDir)\n\tassert.NilError(t, err)\n\tassert.Equal(t, \"test\", reloadedConfig.CurrentContext)\n\n\tcli.OutBuffer().Reset()\n\tcli.ErrBuffer().Reset()\n\tassert.NilError(t, newUseCommand(cli).RunE(nil, []string{\"default\"}))\n\treloadedConfig, err = config.Load(configDir)\n\tassert.NilError(t, err)\n\tassert.Equal(t, \"\", reloadedConfig.CurrentContext)\n\tassert.Equal(t, \"default\\n\", cli.OutBuffer().String())\n\tassert.Equal(t, \"Current context is now \\\"default\\\"\\n\", cli.ErrBuffer().String())\n}\n\n\n\nfunc TestUseNoExist(t *testing.T) ", "output": "{\n\tcli, cleanup := makeFakeCli(t)\n\tdefer cleanup()\n\terr := newUseCommand(cli).RunE(nil, []string{\"test\"})\n\tassert.Check(t, store.IsErrContextDoesNotExist(err))\n}"} {"input": "package model\n\n\ntype Sample struct {\n\tMetric Metric\n\tValue SampleValue\n\tTimestamp Timestamp\n}\n\n\n\n\n\ntype Samples []*Sample\n\nfunc (s Samples) Len() int {\n\treturn len(s)\n}\n\n\nfunc (s Samples) Less(i, j int) bool {\n\tswitch {\n\tcase s[i].Metric.Before(s[j].Metric):\n\t\treturn true\n\tcase s[j].Metric.Before(s[i].Metric):\n\t\treturn false\n\tcase s[i].Timestamp.Before(s[j].Timestamp):\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc (s Samples) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\n\nfunc (s Samples) Equal(o Samples) bool {\n\tif len(s) != len(o) {\n\t\treturn false\n\t}\n\n\tfor i, sample := range s {\n\t\tif !sample.Equal(o[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (s *Sample) Equal(o *Sample) bool ", "output": "{\n\tif s == o {\n\t\treturn true\n\t}\n\n\tif !s.Metric.Equal(o.Metric) {\n\t\treturn false\n\t}\n\tif !s.Timestamp.Equal(o.Timestamp) {\n\t\treturn false\n\t}\n\tif !s.Value.Equal(o.Value) {\n\t\treturn false\n\t}\n\n\treturn true\n}"} {"input": "package web\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/gravitational/teleport/lib/httplib\"\n\n\t\"github.com/gravitational/roundtrip\"\n\t\"github.com/gravitational/trace\"\n)\n\nfunc newInsecureClient() *http.Client {\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t}\n}\n\n\n\nfunc newWebClient(url string, opts ...roundtrip.ClientParam) (*webClient, error) {\n\tclt, err := roundtrip.NewClient(url, APIVersion, opts...)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn &webClient{clt}, nil\n}\n\n\n\ntype webClient struct {\n\t*roundtrip.Client\n}\n\nfunc (w *webClient) PostJSON(\n\tendpoint string, val interface{}) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.PostJSON(endpoint, val))\n}\n\nfunc (w *webClient) PutJSON(\n\tendpoint string, val interface{}) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.PutJSON(endpoint, val))\n}\n\nfunc (w *webClient) Get(endpoint string, val url.Values) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.Get(endpoint, val))\n}\n\nfunc (w *webClient) Delete(endpoint string) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.Delete(endpoint))\n}\n\nfunc newClientWithPool(pool *x509.CertPool) *http.Client ", "output": "{\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{RootCAs: pool},\n\t\t},\n\t}\n}"} {"input": "package html\n\nimport (\n\t\"golang.org/x/net/html/atom\"\n)\n\n\nfunc (node *Node) FindByAtom(atoms ...atom.Atom) (nodes []*Node) {\n\tnodes = make([]*Node, 1)\n\tnodes[0] = node\n\tfor _, a := range atoms {\n\t\tchildren := make([]*Node, 0)\n\t\tfor _, n := range nodes {\n\t\t\tfor _, c := range n.ElementChildren() {\n\t\t\t\tif c.DataAtom == a {\n\t\t\t\t\tchildren = append(children, c)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tnodes = children\n\t}\n\treturn\n}\n\n\nfunc (node *Node) NextByAtom(atom atom.Atom) *Node {\n\tfor node = node.NextElement(); node != nil; node = node.NextElement() {\n\t\tif node.DataAtom == atom {\n\t\t\treturn node\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\nfunc (node *Node) PrevByAtom(atom atom.Atom) *Node ", "output": "{\n\tfor node = node.PrevElement(); node != nil; node = node.PrevElement() {\n\t\tif node.DataAtom == atom {\n\t\t\treturn node\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package photon\n\nimport (\n\t\"github.com/emc-advanced-dev/unik/pkg/providers\"\n)\n\n\n\nfunc (p *PhotonProvider) GetConfig() providers.ProviderConfig ", "output": "{\n\treturn providers.ProviderConfig{\n\t\tUsePartitionTables: true,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc main() {\n\tfor i := 0; i < 10; i++ {\n\t\tgo f(i)\n\t}\n\tvar input string\n\tfmt.Scanln(&input)\n}\n\nfunc f(n int) ", "output": "{\n\tfor i := 0; i < 10; i++ {\n\t\tfmt.Println(n, \":\", i)\n\t}\n}"} {"input": "package Util\nimport \"crypto/rand\"\n\n\nconst alphanum = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n\n\nfunc RandString(n int) string ", "output": "{\n\n var bytes = make([]byte, n)\n rand.Read(bytes)\n for i, b := range bytes {\n bytes[i] = alphanum[b % byte(len(alphanum))]\n }\n return string(bytes)\n}"} {"input": "package auto\n\nimport (\n\t\"sync\"\n\n\t\"github.com/miekg/coredns/middleware/file\"\n)\n\n\n\ntype Zones struct {\n\tZ map[string]*file.Zone \n\tnames []string \n\n\torigins []string \n\n\tsync.RWMutex\n}\n\n\nfunc (z *Zones) Names() []string {\n\tz.RLock()\n\tn := z.names\n\tz.RUnlock()\n\treturn n\n}\n\n\nfunc (z *Zones) Origins() []string {\n\treturn z.origins\n}\n\n\nfunc (z *Zones) Zones(name string) *file.Zone {\n\tz.RLock()\n\tzo := z.Z[name]\n\tz.RUnlock()\n\treturn zo\n}\n\n\n\nfunc (z *Zones) Add(zo *file.Zone, name string) {\n\tz.Lock()\n\n\tif z.Z == nil {\n\t\tz.Z = make(map[string]*file.Zone)\n\t}\n\n\tz.Z[name] = zo\n\tz.names = append(z.names, name)\n\tzo.Reload()\n\n\tz.Unlock()\n}\n\n\n\n\nfunc (z *Zones) Remove(name string) ", "output": "{\n\tz.Lock()\n\n\tif zo, ok := z.Z[name]; ok && !zo.NoReload {\n\t\tzo.ReloadShutdown <- true\n\t}\n\n\tdelete(z.Z, name)\n\n\tz.names = []string{}\n\tfor n := range z.Z {\n\t\tz.names = append(z.names, n)\n\t}\n\n\tz.Unlock()\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n\n\nfunc root(w http.ResponseWriter, req *http.Request) {\n\tpath := req.URL.Path\n\tswitch {\n\tcase strings.HasPrefix(path, \"/hello/\"):\n\t\thelloWorld(w, req)\n\tdefault:\n\t\thttp.Error(w, \"Not Found\", http.StatusNotFound)\n\t}\n}\n\nfunc main() {\n\tport := \"1234\"\n\thttp.HandleFunc(\"/\", root)\n\tlog.Fatal(http.ListenAndServe(\":\"+port, nil))\n}\n\nfunc helloWorld(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tpath := req.URL.Path\n\tname := strings.Title(strings.TrimPrefix(path, \"/hello/\"))\n\tif len(name) < 1 {\n\t\thttp.Error(w, \"Not Found\", http.StatusNotFound)\n\t\treturn\n\t}\n\tio.WriteString(w, \"Hello, \"+name+\"!\\n\")\n}"} {"input": "package fake\n\nimport (\n\tclientset \"github.com/openshift/origin/pkg/image/generated/clientset\"\n\timagev1 \"github.com/openshift/origin/pkg/image/generated/clientset/typed/image/v1\"\n\tfakeimagev1 \"github.com/openshift/origin/pkg/image/generated/clientset/typed/image/v1/fake\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/watch\"\n\t\"k8s.io/client-go/discovery\"\n\tfakediscovery \"k8s.io/client-go/discovery/fake\"\n\t\"k8s.io/client-go/testing\"\n)\n\n\n\n\n\nfunc NewSimpleClientset(objects ...runtime.Object) *Clientset {\n\to := testing.NewObjectTracker(registry, scheme, codecs.UniversalDecoder())\n\tfor _, obj := range objects {\n\t\tif err := o.Add(obj); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tfakePtr := testing.Fake{}\n\tfakePtr.AddReactor(\"*\", \"*\", testing.ObjectReaction(o, registry.RESTMapper()))\n\n\tfakePtr.AddWatchReactor(\"*\", testing.DefaultWatchReactor(watch.NewFake(), nil))\n\n\treturn &Clientset{fakePtr}\n}\n\n\n\n\ntype Clientset struct {\n\ttesting.Fake\n}\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\treturn &fakediscovery.FakeDiscovery{Fake: &c.Fake}\n}\n\nvar _ clientset.Interface = &Clientset{}\n\n\nfunc (c *Clientset) ImageV1() imagev1.ImageV1Interface {\n\treturn &fakeimagev1.FakeImageV1{Fake: &c.Fake}\n}\n\n\n\n\nfunc (c *Clientset) Image() imagev1.ImageV1Interface ", "output": "{\n\treturn &fakeimagev1.FakeImageV1{Fake: &c.Fake}\n}"} {"input": "package loader_test\n\n\n\nfunc init() ", "output": "{\n\tgo16 = true\n}"} {"input": "package web\n\nimport (\n\t\"net/http\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype StatusHandler struct {\n\tmu sync.Mutex\n\n\tBuildInfo map[string]string\n\tConfig string\n\tFlags map[string]string\n\tBirth time.Time\n}\n\nfunc (h *StatusHandler) UpdateConfig(c string) {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\th.Config = c\n}\n\n\n\nfunc (h *StatusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\texecuteTemplate(w, \"status\", h)\n}"} {"input": "package vfs\n\nimport (\n\t\"path\"\n\n\tgofig \"github.com/akutz/gofig/types\"\n\n\t\"github.com/codedellemc/rexray/libstorage/api/context\"\n\t\"github.com/codedellemc/rexray/libstorage/api/registry\"\n\t\"github.com/codedellemc/rexray/libstorage/api/types\"\n)\n\nconst (\n\tName = \"vfs\"\n)\n\nfunc init() {\n\tregistry.RegisterConfigReg(\n\t\t\"VFS\",\n\t\tfunc(ctx types.Context, r gofig.ConfigRegistration) {\n\t\t\tvfsRoot := path.Join(context.MustPathConfig(ctx).Lib, \"vfs\")\n\t\t\tr.Key(\n\t\t\t\tgofig.String,\n\t\t\t\t\"\",\n\t\t\t\tvfsRoot,\n\t\t\t\t\"\",\n\t\t\t\t\"vfs.root\")\n\t\t})\n}\n\n\nfunc RootDir(config gofig.Config) string {\n\treturn config.GetString(\"vfs.root\")\n}\n\n\nfunc DeviceFilePath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"dev\")\n}\n\n\n\n\n\nfunc SnapshotsDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"snap\")\n}\n\nfunc VolumesDirPath(config gofig.Config) string ", "output": "{\n\treturn path.Join(RootDir(config), \"vol\")\n}"} {"input": "package gokeepasslib\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"io\"\n)\n\n\nvar BaseSignature = [...]byte{0x03, 0xd9, 0xa2, 0x9a}\n\n\nvar SecondarySignature = [...]byte{0x67, 0xfb, 0x4b, 0xb5}\n\n\nconst MajorVersion = 3\n\n\nconst MinorVersion = 1\n\n\nvar DefaultSig = FileSignature{BaseSignature, SecondarySignature, MinorVersion, MajorVersion}\n\ntype ErrInvalidSignature struct {\n\tName string\n\tIs interface{}\n\tShouldbe interface{}\n}\n\nfunc (e ErrInvalidSignature) Error() string {\n\treturn fmt.Sprintf(\"gokeepasslib: invalid signature. %s is %x. Should be %x\", e.Name, e.Is, e.Shouldbe)\n}\n\n\n\n\n\ntype FileSignature struct {\n\tBaseSignature [4]byte\n\tSecondarySignature [4]byte\n\tMinorVersion uint16\n\tMajorVersion uint16\n}\n\n\nfunc (s FileSignature) Validate() error {\n\tif s.BaseSignature != BaseSignature {\n\t\treturn ErrInvalidSignature{\"Base Signature\", s.BaseSignature, BaseSignature}\n\t}\n\tif s.SecondarySignature != SecondarySignature {\n\t\treturn ErrInvalidSignature{\"Secondary Signature\", s.SecondarySignature, SecondarySignature}\n\t}\n\tif s.MinorVersion != MinorVersion {\n\t\treturn ErrInvalidSignature{\"Minor Version\", s.MinorVersion, MinorVersion}\n\t}\n\tif s.MajorVersion != MajorVersion {\n\t\treturn ErrInvalidSignature{\"Major Version\", s.MajorVersion, MajorVersion}\n\t}\n\treturn nil\n}\nfunc (s *FileSignature) ReadFrom(r io.Reader) error {\n\tif err := binary.Read(r, binary.LittleEndian, s); err != nil {\n\t\treturn err\n\t}\n\treturn s.Validate()\n}\n\nfunc (s FileSignature) WriteTo(w io.Writer) error {\n\treturn binary.Write(w, binary.LittleEndian, s)\n}\n\nfunc (s FileSignature) String() string ", "output": "{\n\treturn fmt.Sprintf(\"Base: %x, Secondary: %x, Format Version: %d.%d\",\n\t\ts.BaseSignature,\n\t\ts.SecondarySignature,\n\t\ts.MajorVersion,\n\t\ts.MinorVersion,\n\t)\n}"} {"input": "package stats\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/kubernetes/pkg/volume\"\n)\n\ntype fakeLogMetrics struct {\n\tfakeStats map[string]*volume.Metrics\n}\n\nfunc NewFakeLogMetricsService(stats map[string]*volume.Metrics) LogMetricsService {\n\treturn &fakeLogMetrics{fakeStats: stats}\n}\n\n\n\ntype fakeMetricsDu struct {\n\tfakeStats *volume.Metrics\n}\n\nfunc NewFakeMetricsDu(path string, stats *volume.Metrics) volume.MetricsProvider {\n\treturn &fakeMetricsDu{fakeStats: stats}\n}\n\nfunc (f *fakeMetricsDu) GetMetrics() (*volume.Metrics, error) {\n\tif f.fakeStats == nil {\n\t\treturn nil, fmt.Errorf(\"no stats provided\")\n\t}\n\treturn f.fakeStats, nil\n}\n\nfunc (l *fakeLogMetrics) createLogMetricsProvider(path string) volume.MetricsProvider ", "output": "{\n\treturn NewFakeMetricsDu(path, l.fakeStats[path])\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\ntype Item struct {\n\n\tCompleted bool `json:\"completed,omitempty\"`\n\n\tDescription *string `json:\"description\"`\n\n\tID int64 `json:\"id,omitempty\"`\n}\n\n\n\n\nfunc (m *Item) validateDescription(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"description\", \"body\", m.Description); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validate.MinLength(\"description\", \"body\", string(*m.Description), 1); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *Item) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateDescription(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package muxer\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\tdebug \"github.com/micro/micro/v3/service/debug/handler\"\n\t\"github.com/micro/micro/v3/service/proxy\"\n\t\"github.com/micro/micro/v3/service/server\"\n\t\"github.com/micro/micro/v3/service/server/mucp\"\n)\n\n\ntype Server struct {\n\tName string\n\tProxy proxy.Proxy\n\tHandler Handler\n}\n\ntype Handler interface {\n\tproxy.Proxy\n\tNewHandler(interface{}, ...server.HandlerOption) server.Handler\n\tHandle(server.Handler) error\n}\n\nvar (\n\tonce sync.Once\n)\n\n\n\nfunc (s *Server) ServeRequest(ctx context.Context, req server.Request, rsp server.Response) error {\n\tif req.Service() == s.Name {\n\t\treturn s.Handler.ServeRequest(ctx, req, rsp)\n\t}\n\treturn s.Proxy.ServeRequest(ctx, req, rsp)\n}\n\nfunc New(name string, p proxy.Proxy) *Server {\n\tr := mucp.DefaultRouter\n\n\tonce.Do(func() {\n\t\tr.Handle(\n\t\t\tr.NewHandler(\n\t\t\t\tdebug.NewHandler(),\n\t\t\t\tserver.InternalHandler(true),\n\t\t\t),\n\t\t)\n\t})\n\n\treturn &Server{\n\t\tName: name,\n\t\tProxy: p,\n\t\tHandler: r,\n\t}\n}\n\nfunc (s *Server) ProcessMessage(ctx context.Context, msg server.Message) error ", "output": "{\n\tif msg.Topic() == s.Name {\n\t\treturn s.Handler.ProcessMessage(ctx, msg)\n\t}\n\treturn s.Proxy.ProcessMessage(ctx, msg)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\nvar (\n\tnames = []string{\n\t\t\"Pepe\",\n\t\t\"Gozalo\",\n\t\t\"Juan\",\n\t\t\"Carolina\",\n\t}\n\tlastNames = []string{\n\t\t\"Escobar\",\n\t\t\"Sierra\",\n\t\t\"Velez\",\n\t\t\"Mejia\",\n\t}\n\tusernames = []string{\n\t\t\"pep66\",\n\t\t\"jsi3rra\",\n\t\t\"jvlez8\",\n\t\t\"caro27\",\n\t}\n\temails = []string{\n\t\t\"pepe27@gmail.com\",\n\t\t\"gozalosierra@gmail.com\",\n\t\t\"juanv@gmail.com\",\n\t\t\"carolina@gmail.com\",\n\t}\n\tpasswords = []string{\n\t\t\"qwerty\",\n\t\t\"123456\",\n\t\t\"AeIoU!@\",\n\t\t\"S3CUR3P455W0RD!\\\"#$%&/()=\",\n\t}\n)\n\n\ntype User struct {\n\tUsername string\n\tEmail string\n\tLastName string\n\tName string\n\tPasswordHash string\n}\n\nfunc makeUsers() []User {\n\tusers := []User{}\n\tfor i := 0; i < 10; i++ {\n\t\tu := User{\n\t\t\tUsername: usernames[i%4],\n\t\t\tEmail: emails[i%4],\n\t\t\tLastName: lastNames[i%4],\n\t\t\tName: names[i%4],\n\t\t\tPasswordHash: passwords[i%4],\n\t\t}\n\t\tusers = append(users, u)\n\t}\n\treturn users\n}\n\n\n\n\n\nfunc main() {\n\tparallelLoop()\n}\n\nfunc parallelLoop() ", "output": "{\n\tusers := makeUsers()\n\tvar wg sync.WaitGroup\n\tfor _, u := range users {\n\t\twg.Add(1)\n\t\tgo func(u User) {\n\t\t\tfmt.Printf(\"%s: (%s)\\n\", u.Email, u.Username)\n\t\t\twg.Done()\n\t\t}(u)\n\t}\n\twg.Wait()\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/mysza/go-service-template/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert\"\n\t\"os\"\n)\n\n\n\nfunc convertPackage(args []string, additionalArgs []string) {\n\tif len(args) != 1 {\n\t\tprintln(fmt.Sprintf(\"usage: ginkgo convert /path/to/your/package\"))\n\t\tos.Exit(1)\n\t}\n\n\tdefer func() {\n\t\terr := recover()\n\t\tif err != nil {\n\t\t\tswitch err := err.(type) {\n\t\t\tcase error:\n\t\t\t\tprintln(err.Error())\n\t\t\tcase string:\n\t\t\t\tprintln(err)\n\t\t\tdefault:\n\t\t\t\tprintln(fmt.Sprintf(\"unexpected error: %#v\", err))\n\t\t\t}\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\tconvert.RewritePackage(args[0])\n}\n\nfunc BuildConvertCommand() *Command ", "output": "{\n\treturn &Command{\n\t\tName: \"convert\",\n\t\tFlagSet: flag.NewFlagSet(\"convert\", flag.ExitOnError),\n\t\tUsageCommand: \"ginkgo convert /path/to/package\",\n\t\tUsage: []string{\n\t\t\t\"Convert the package at the passed in path from an XUnit-style test to a Ginkgo-style test\",\n\t\t},\n\t\tCommand: convertPackage,\n\t}\n}"} {"input": "package counting_test\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/facebookgo/counting\"\n)\n\n\n\nfunc TestWriter(t *testing.T) ", "output": "{\n\tconst payload = \"hello world\"\n\tbuf := bytes.NewBuffer(nil)\n\tcountingW := counting.NewWriter(buf)\n\tfmt.Fprint(countingW, payload)\n\tif countingW.Count() != len(payload) {\n\t\tt.Fatalf(\"did not get expected count\")\n\t}\n\tif buf.String() != payload {\n\t\tt.Fatalf(\"did not get expected payload: %s\", buf.String())\n\t}\n}"} {"input": "package externalversions\n\nimport (\n\t\"fmt\"\n\n\tv1 \"github.com/openshift/api/network/v1\"\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tcache \"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\n\n\n\nfunc (f *genericInformer) Lister() cache.GenericLister {\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {\n\tswitch resource {\n\tcase v1.SchemeGroupVersion.WithResource(\"clusternetworks\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Network().V1().ClusterNetworks().Informer()}, nil\n\tcase v1.SchemeGroupVersion.WithResource(\"egressnetworkpolicies\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Network().V1().EgressNetworkPolicies().Informer()}, nil\n\tcase v1.SchemeGroupVersion.WithResource(\"hostsubnets\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Network().V1().HostSubnets().Informer()}, nil\n\tcase v1.SchemeGroupVersion.WithResource(\"netnamespaces\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Network().V1().NetNamespaces().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer ", "output": "{\n\treturn f.informer\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestBats(t *testing.T) {\n\tif r := bats(22, 2, 2, []string{\"9\", \"11\"}); r != 3 {\n\t\tt.Errorf(\"failed: bats 22 2 2 9 11 is 3, got %d\",\n\t\t\tr)\n\t}\n\tif r := bats(835, 125, 1, []string{\"113\"}); r != 5 {\n\t\tt.Errorf(\"failed: bats 835 125 1 113 is 5, got %d\",\n\t\t\tr)\n\t}\n\tif r := bats(47, 5, 0, []string{}); r != 8 {\n\t\tt.Errorf(\"failed: bats 475 5 0 is 8, got %d\",\n\t\t\tr)\n\t}\n}\n\n\n\nfunc bats(l, d, n int, s []string) (c int) ", "output": "{\n\tvar t int\n\ttx := 6 - d\n\tfor i := 6; i <= l-6; i += d {\n\t\tif i > tx-d {\n\t\t\ti = tx\n\t\t\tif t == n {\n\t\t\t\ttx = l - 6 + d\n\t\t\t} else {\n\t\t\t\tfmt.Sscanf(s[t], \"%d\", &tx)\n\t\t\t\tt++\n\t\t\t}\n\t\t} else {\n\t\t\tc++\n\t\t}\n\t}\n\treturn c\n}"} {"input": "package ioctl\n\nimport \"golang.org/x/sys/unix\"\n\nconst (\n\ttypeBits = 8\n\tnumberBits = 8\n\tsizeBits = 14\n\tdirectionBits = 2\n\n\ttypeMask = (1 << typeBits) - 1\n\tnumberMask = (1 << numberBits) - 1\n\tsizeMask = (1 << sizeBits) - 1\n\tdirectionMask = (1 << directionBits) - 1\n\n\tdirectionNone = 0\n\tdirectionWrite = 1\n\tdirectionRead = 2\n\n\tnumberShift = 0\n\ttypeShift = numberShift + numberBits\n\tsizeShift = typeShift + typeBits\n\tdirectionShift = sizeShift + sizeBits\n)\n\nfunc ioc(dir, t, nr, size uintptr) uintptr {\n\treturn (dir << directionShift) | (t << typeShift) | (nr << numberShift) | (size << sizeShift)\n}\n\n\nfunc Io(t, nr uintptr) uintptr {\n\treturn ioc(directionNone, t, nr, 0)\n}\n\n\n\n\n\nfunc IoW(t, nr, size uintptr) uintptr {\n\treturn ioc(directionWrite, t, nr, size)\n}\n\n\nfunc IoRW(t, nr, size uintptr) uintptr {\n\treturn ioc(directionRead|directionWrite, t, nr, size)\n}\n\n\nfunc Ioctl(fd, op, arg uintptr) error {\n\t_, _, ep := unix.Syscall(unix.SYS_IOCTL, fd, op, arg)\n\tif ep != 0 {\n\t\treturn ep\n\t}\n\treturn nil\n}\n\nfunc IoR(t, nr, size uintptr) uintptr ", "output": "{\n\treturn ioc(directionRead, t, nr, size)\n}"} {"input": "package veneur\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/hashicorp/consul/api\"\n)\n\n\n\ntype Consul struct {\n\tConsulHealth *api.Health\n}\n\n\nfunc NewConsul(config *api.Config) (*Consul, error) {\n\tconsulClient, err := api.NewClient(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Consul{\n\t\tConsulHealth: consulClient.Health(),\n\t}, nil\n}\n\n\n\n\n\nfunc (c *Consul) GetDestinationsForService(serviceName string) ([]string, error) ", "output": "{\n\tserviceEntries, _, err := c.ConsulHealth.Service(serviceName, \"\", true, &api.QueryOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnumHosts := len(serviceEntries)\n\tif numHosts < 1 {\n\t\treturn nil, errors.New(\"Received no hosts from Consul\")\n\t}\n\thosts := make([]string, numHosts)\n\tfor index, se := range serviceEntries {\n\t\thosts[index] = fmt.Sprintf(\"%s:%d\", se.Node.Address, se.Service.Port)\n\t}\n\n\treturn hosts, nil\n}"} {"input": "package state\n\nimport (\n\t\"net/url\"\n\n\t\"gopkg.in/juju/charm.v3\"\n)\n\n\ntype charmDoc struct {\n\tURL *charm.URL `bson:\"_id\"`\n\tMeta *charm.Meta\n\tConfig *charm.Config\n\tActions *charm.Actions\n\tBundleURL *url.URL\n\tBundleSha256 string\n\tPendingUpload bool\n\tPlaceholder bool\n}\n\n\ntype Charm struct {\n\tst *State\n\tdoc charmDoc\n}\n\nfunc newCharm(st *State, cdoc *charmDoc) (*Charm, error) {\n\treturn &Charm{st: st, doc: *cdoc}, nil\n}\n\nfunc (c *Charm) String() string {\n\treturn c.doc.URL.String()\n}\n\n\nfunc (c *Charm) URL() *charm.URL {\n\tclone := *c.doc.URL\n\treturn &clone\n}\n\n\n\n\n\n\nfunc (c *Charm) Meta() *charm.Meta {\n\treturn c.doc.Meta\n}\n\n\nfunc (c *Charm) Config() *charm.Config {\n\treturn c.doc.Config\n}\n\n\nfunc (c *Charm) Actions() *charm.Actions {\n\treturn c.doc.Actions\n}\n\n\n\nfunc (c *Charm) BundleURL() *url.URL {\n\treturn c.doc.BundleURL\n}\n\n\nfunc (c *Charm) BundleSha256() string {\n\treturn c.doc.BundleSha256\n}\n\n\n\nfunc (c *Charm) IsUploaded() bool {\n\treturn !c.doc.PendingUpload\n}\n\n\n\nfunc (c *Charm) IsPlaceholder() bool {\n\treturn c.doc.Placeholder\n}\n\nfunc (c *Charm) Revision() int ", "output": "{\n\treturn c.doc.URL.Revision\n}"} {"input": "package tokencmd\n\nimport \"io\"\n\nfunc SSPIEnabled() bool {\n\treturn false\n}\n\n\n\nfunc NewSSPINegotiator(string, string, string, io.Reader) Negotiator ", "output": "{\n\treturn newUnsupportedNegotiator(\"SSPI\")\n}"} {"input": "package main\n\nimport \"testing\"\n\nvar args []string = []string{\"main_test\", \"a\", \"b\", \"c\", \"d\", \"f\"}\n\n\n\nfunc BenchmarkEchoFast(b *testing.B) {\n for i := 0; i < b.N; i++ {\n echoFast(args)\n }\n}\n\nfunc BenchmarkEchoSlow(b *testing.B) ", "output": "{\n for i := 0; i < b.N; i++ {\n echoSlow(args)\n }\n}"} {"input": "package ovs\n\nimport (\n\t\"net\"\n\n\t\"github.com/vishvananda/netlink\"\n)\n\ntype bridgeInterface struct {\n\tLink netlink.Link\n\tgatewayIPv4 net.IP\n}\n\n\n\n\nfunc newInterface(config *networkConfiguration) *bridgeInterface {\n\ti := &bridgeInterface{}\n\n\tif config.BridgeName == \"\" {\n\t\tconfig.BridgeName = DefaultOvsBridgeName\n\t}\n\n\ti.Link, _ = netlink.LinkByName(config.BridgeName)\n\treturn i\n}\n\n\n\n\nfunc (i *bridgeInterface) exists() bool ", "output": "{\n\treturn i.Link != nil\n}"} {"input": "package test\n\nimport (\n\t\"beam.apache.org/learning/katas/core_transforms/partition/partition/pkg/task\"\n\t\"github.com/apache/beam/sdks/go/pkg/beam\"\n\t\"github.com/apache/beam/sdks/go/pkg/beam/testing/passert\"\n\t\"github.com/apache/beam/sdks/go/pkg/beam/testing/ptest\"\n\t\"testing\"\n)\n\n\n\nfunc TestApplyTransform(t *testing.T) ", "output": "{\n\tp, s := beam.NewPipelineWithRoot()\n\ttests := []struct {\n\t\tinput beam.PCollection\n\t\twant [][]interface{}\n\t}{\n\t\t{\n\t\t\tinput: beam.Create(s, 1, 2, 3, 4, 5, 100, 110, 150, 250),\n\t\t\twant: [][]interface{}{\n\t\t\t\t{110, 150, 250},\n\t\t\t\t{1, 2, 3, 4, 5, 100},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tgot := task.ApplyTransform(s, tt.input)\n\t\tpassert.Equals(s, got[0], tt.want[0]...)\n\t\tpassert.Equals(s, got[1], tt.want[1]...)\n\t\tif err := ptest.Run(p); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n}"} {"input": "package uuid_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/socialpoint-labs/bsk/uuid\"\n)\n\n\n\nfunc TestTimeOrderedUuid(t *testing.T) ", "output": "{\n\tuu := uuid.New()\n\tif len(uu) != 36 {\n\t\tt.Fatalf(\"bad UUID size: %s. Must be 36 and is %d\", uu, len(uu))\n\t}\n}"} {"input": "package depsync\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n)\n\n\n\ntype syncNowResponse struct{}\ntype syncNowRequest struct{}\n\nfunc MakeSyncNowEndpoint(s Service) endpoint.Endpoint {\n\treturn func(ctx context.Context, _ interface{}) (interface{}, error) {\n\t\ts.SyncNow(ctx)\n\t\treturn syncNowResponse{}, nil\n\t}\n}\n\nfunc decodeEmptyRequest(ctx context.Context, r *http.Request) (interface{}, error) {\n\treturn nil, nil\n}\n\nfunc encodeEmptyResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {\n\treturn nil\n}\n\nfunc decodeEmptyResponse(ctx context.Context, r *http.Response) (interface{}, error) {\n\treturn nil, nil\n}\n\nfunc (e Endpoints) SyncNow(ctx context.Context) error {\n\t_, err := e.SyncNowEndpoint(ctx, nil)\n\treturn err\n}\n\nfunc (s *DEPSyncService) SyncNow(_ context.Context) error ", "output": "{\n\ts.syncer.SyncNow()\n\treturn nil\n}"} {"input": "package resource\n\nimport (\n\t\"github.com/gbl08ma/sqalx\"\n\t\"github.com/yarf-framework/yarf\"\n)\n\n\ntype AuthTest struct {\n\tresource\n}\n\n\nfunc (r *AuthTest) WithNode(node sqalx.Node) *AuthTest {\n\tr.node = node\n\treturn r\n}\n\n\nfunc (r *AuthTest) WithHashKey(key []byte) *AuthTest {\n\tr.hashKey = key\n\treturn r\n}\n\n\n\n\nfunc (r *AuthTest) Get(c *yarf.Context) error ", "output": "{\n\tpair, err := r.AuthenticateClient(c)\n\tif err != nil {\n\t\tRenderUnauthorized(c)\n\t\treturn nil\n\t}\n\n\tRenderData(c, struct {\n\t\tResult string `msgpack:\"result\" json:\"result\"`\n\t\tKey string `msgpack:\"key\" json:\"key\"`\n\t}{\n\t\tResult: \"ok\",\n\t\tKey: pair.Key,\n\t}, \"no-cache, no-store, must-revalidate\")\n\treturn nil\n}"} {"input": "package server\n\nimport (\n\t\"github.com/coreos/doozerd/consensus\"\n\t\"github.com/coreos/doozerd/store\"\n\t\"log\"\n\t\"net\"\n\t\"syscall\"\n)\n\n\n\nfunc ListenAndServe(l net.Listener, canWrite chan bool, st *store.Store, p consensus.Proposer, rwsk, rosk string, self string) {\n\tvar w bool\n\tfor {\n\t\tc, err := l.Accept()\n\t\tif err != nil {\n\t\t\tif err == syscall.EINVAL {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif e, ok := err.(*net.OpError); ok && e.Err == syscall.EINVAL {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tselect {\n\t\tcase w = <-canWrite:\n\t\t\tcanWrite = nil\n\t\tdefault:\n\t\t}\n\n\t\tgo serve(c, st, p, w, rwsk, rosk, self)\n\t}\n}\n\n\n\nfunc serve(nc net.Conn, st *store.Store, p consensus.Proposer, w bool, rwsk, rosk string, self string) ", "output": "{\n\tc := &conn{\n\t\tc: nc,\n\t\taddr: nc.RemoteAddr().String(),\n\t\tst: st,\n\t\tp: p,\n\t\tcanWrite: w,\n\t\trwsk: rwsk,\n\t\trosk: rosk,\n\t\tself: self,\n\t}\n\n\tc.grant(\"\") \n\n\n\tc.serve()\n\tnc.Close()\n}"} {"input": "package repo\n\nimport (\n\t\"github.com/OpenBazaar/openbazaar-go/pb\"\n\t\"github.com/golang/protobuf/proto\"\n\t\"math/big\"\n)\n\n\n\n\n\nfunc ToV5Refund(refund *pb.Refund) *pb.Refund ", "output": "{\n\tnewRefund := proto.Clone(refund).(*pb.Refund)\n\n\tif refund.RefundTransaction.Value != 0 && refund.RefundTransaction.BigValue == \"\" {\n\t\tnewRefund.RefundTransaction.BigValue = big.NewInt(int64(refund.RefundTransaction.Value)).String()\n\t\tnewRefund.RefundTransaction.Value = 0\n\t}\n\treturn newRefund\n}"} {"input": "package sc\n\n\ntype ControlRate struct{}\n\n\n\n\n\nfunc (s ControlRate) Rate(rate int8) Input ", "output": "{\n\tif rate != IR {\n\t\tpanic(\"ControlRate only supports IR\")\n\t}\n\treturn NewInput(\"ControlRate\", rate, 0, 1)\n}"} {"input": "package ons\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestOnsConsumerGetConnection(t *testing.T) ", "output": "{\n\tvar req OnsConsumerGetConnectionRequest\n\treq.Init()\n\treq.SetFormat(\"JSON\")\n\treq.SetRegionId(\"cn-shenzhen\")\n\tvar accessId = \"Ie65kUInu5GeAsma\"\n\tvar accessSecret = \"8cCqoxdYU9zKUihwXFXiN1HEACBDwB\"\n\tresp, err := OnsConsumerGetConnection(&req, accessId, accessSecret)\n\tif err != nil {\n\t\tt.Errorf(\"Error: %s\", err.Error())\n\t}\n\tfmt.Printf(\"Success: %v\\n\", resp)\n}"} {"input": "package chroma\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestCoalesce(t *testing.T) ", "output": "{\n\tlexer := Coalesce(mustNewLexer(t, nil, Rules{ \n\t\t\"root\": []Rule{\n\t\t\t{`[!@#$%^&*()]`, Punctuation, nil},\n\t\t},\n\t}))\n\tactual, err := Tokenise(lexer, nil, \"!@#$\")\n\tassert.NoError(t, err)\n\texpected := []Token{{Punctuation, \"!@#$\"}}\n\tassert.Equal(t, expected, actual)\n}"} {"input": "package compiler\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/okcoin/go-okcoin/core/asm\"\n)\n\n\n\nfunc Compile(fn string, src []byte, debug bool) (string, error) ", "output": "{\n\tcompiler := asm.NewCompiler(debug)\n\tcompiler.Feed(asm.Lex(fn, src, debug))\n\n\tbin, compileErrors := compiler.Compile()\n\tif len(compileErrors) > 0 {\n\t\tfor _, err := range compileErrors {\n\t\t\tfmt.Printf(\"%s:%v\\n\", fn, err)\n\t\t}\n\t\treturn \"\", errors.New(\"compiling failed\")\n\t}\n\treturn bin, nil\n}"} {"input": "package stdres\n\nimport \"fmt\"\n\nvar colorDisabled bool\n\nfunc DisableColor() {\n\tcolorDisabled = true\n}\n\nfunc EnableColor() {\n\tcolorDisabled = false\n}\n\ntype Result uint\n\n\nconst (\n\treset = \"\\033[00m\"\n\tblack = \"\\033[30m\"\n\tred = \"\\033[31m\"\n\tgreen = \"\\033[32m\"\n\tyellow = \"\\033[33m\"\n\tblue = \"\\033[34m\"\n\tmagenta = \"\\033[35m\"\n\tcyan = \"\\033[36m\"\n\twhite = \"\\033[37m\"\n)\n\nconst (\n\tUNKNOWN Result = iota\n\tPENDING\n\tFAILURE\n\tSUCCESS\n\tINFO\n\tPLAIN\n)\n\ntype Buffer struct {\n\tbuffer []*Record\n}\n\n\ntype Record struct {\n\tResult\n\tMessage string\n}\n\nfunc (out *Record) String() string {\n\treturn string(out.Message)\n}\n\n\n\n\n\nfunc (outBuffer *Buffer) printer(message string) *Record {\n\tif outBuffer.buffer == nil {\n\t\toutBuffer.buffer = make([]*Record, 0, 500)\n\t}\n\n\tout := &Record{UNKNOWN, message}\n\toutBuffer.buffer = append(outBuffer.buffer, out)\n\n\treturn out\n}\n\n\n\n\nfunc (outBuffer *Buffer) Print(message string) *Record {\n\treturn outBuffer.printer(message)\n}\n\n\n\n\nfunc (outBuffer *Buffer) Println(message string) *Record {\n\treturn outBuffer.printer(message + \"\\n\")\n}\n\n\n\n\nfunc (outBuffer *Buffer) Printf(format string, a ...interface{}) *Record {\n\tmessage := fmt.Sprintf(format, a...)\n\treturn outBuffer.printer(message)\n}\n\nfunc (outBuffer *Buffer) Flush() ", "output": "{\n\ttoFlush := outBuffer.buffer\n\toutBuffer.buffer = make([]*Record, 0, 500)\n\n\tif colorDisabled {\n\t\tfor _, out := range toFlush {\n\t\t\tmessage := out.String()\n\t\t\tfmt.Print(message)\n\t\t}\n\n\t\treturn\n\t}\n\n\tfor _, record := range toFlush {\n\t\tvar color string\n\n\t\tswitch record.Result {\n\t\tcase UNKNOWN:\n\t\t\tcolor = cyan\n\t\tcase PENDING:\n\t\t\tcolor = yellow\n\t\tcase SUCCESS:\n\t\t\tcolor = green\n\t\tcase FAILURE:\n\t\t\tcolor = red\n\t\tcase INFO:\n\t\t\tcolor = blue\n\t\tcase PLAIN:\n\t\t\tcolor = white\n\t\t}\n\n\t\tfmt.Print(color, record.String(), reset)\n\t}\n}"} {"input": "package iso20022\n\n\ntype Acquirer8 struct {\n\n\tIdentification *Max35Text `xml:\"Id\"`\n\n\tApplicationVersion *Max35Text `xml:\"ApplVrsn,omitempty\"`\n}\n\nfunc (a *Acquirer8) SetIdentification(value string) {\n\ta.Identification = (*Max35Text)(&value)\n}\n\n\n\nfunc (a *Acquirer8) SetApplicationVersion(value string) ", "output": "{\n\ta.ApplicationVersion = (*Max35Text)(&value)\n}"} {"input": "package google\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype SpannerOperationWaiter struct {\n\tConfig *Config\n\tUserAgent string\n\tProject string\n\tCommonOperationWaiter\n}\n\nfunc (w *SpannerOperationWaiter) QueryOp() (interface{}, error) {\n\tif w == nil {\n\t\treturn nil, fmt.Errorf(\"Cannot query operation, it's unset or nil.\")\n\t}\n\turl := fmt.Sprintf(\"%s%s\", w.Config.SpannerBasePath, w.CommonOperationWaiter.Op.Name)\n\n\treturn sendRequest(w.Config, \"GET\", w.Project, url, w.UserAgent, nil)\n}\n\nfunc createSpannerWaiter(config *Config, op map[string]interface{}, project, activity, userAgent string) (*SpannerOperationWaiter, error) {\n\tw := &SpannerOperationWaiter{\n\t\tConfig: config,\n\t\tUserAgent: userAgent,\n\t\tProject: project,\n\t}\n\tif err := w.CommonOperationWaiter.SetOp(op); err != nil {\n\t\treturn nil, err\n\t}\n\treturn w, nil\n}\n\n\nfunc spannerOperationWaitTimeWithResponse(config *Config, op map[string]interface{}, response *map[string]interface{}, project, activity, userAgent string, timeout time.Duration) error {\n\tw, err := createSpannerWaiter(config, op, project, activity, userAgent)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := OperationWait(w, activity, timeout, config.PollInterval); err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal([]byte(w.CommonOperationWaiter.Op.Response), response)\n}\n\n\n\nfunc spannerOperationWaitTime(config *Config, op map[string]interface{}, project, activity, userAgent string, timeout time.Duration) error ", "output": "{\n\tif val, ok := op[\"name\"]; !ok || val == \"\" {\n\t\treturn nil\n\t}\n\tw, err := createSpannerWaiter(config, op, project, activity, userAgent)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn OperationWait(w, activity, timeout, config.PollInterval)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/spf13/cobra\"\n\n\t_ \"github.com/lxc/lxd/lxd/include\"\n)\n\n\nimport \"C\"\n\ntype cmdForksyscall struct {\n\tglobal *cmdGlobal\n}\n\n\n\nfunc (c *cmdForksyscall) Run(cmd *cobra.Command, args []string) error {\n\treturn fmt.Errorf(\"This command should have been intercepted in cgo\")\n}\n\nfunc (c *cmdForksyscall) Command() *cobra.Command ", "output": "{\n\tcmd := &cobra.Command{}\n\tcmd.Use = \"forksyscall [...]\"\n\tcmd.Short = \"Perform syscall operations\"\n\tcmd.Long = `Description:\n Perform syscall operations\n\n This set of internal commands is used for all seccomp-based container syscall\n operations.\n`\n\tcmd.RunE = c.Run\n\tcmd.Hidden = true\n\n\treturn cmd\n}"} {"input": "package integration\n\nimport (\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/containous/traefik/integration/try\"\n\t\"github.com/go-check/check\"\n\tchecker \"github.com/vdemeester/shakers\"\n)\n\n\ntype ErrorPagesSuite struct {\n\tBaseSuite\n\tErrorPageIP string\n\tBackendIP string\n}\n\nfunc (s *ErrorPagesSuite) SetUpSuite(c *check.C) {\n\ts.createComposeProject(c, \"error_pages\")\n\ts.composeProject.Start(c)\n\n\ts.ErrorPageIP = s.composeProject.Container(c, \"nginx2\").NetworkSettings.IPAddress\n\ts.BackendIP = s.composeProject.Container(c, \"nginx1\").NetworkSettings.IPAddress\n}\n\n\n\nfunc (s *ErrorPagesSuite) TestErrorPage(c *check.C) {\n\n\tfile := s.adaptFile(c, \"fixtures/error_pages/error.toml\", struct {\n\t\tServer1 string\n\t\tServer2 string\n\t}{s.BackendIP, s.ErrorPageIP})\n\tdefer os.Remove(file)\n\n\tcmd, display := s.traefikCmd(withConfigFile(file))\n\tdefer display(c)\n\terr := cmd.Start()\n\tc.Assert(err, checker.IsNil)\n\tdefer cmd.Process.Kill()\n\n\tfrontendReq, err := http.NewRequest(http.MethodGet, \"http://127.0.0.1:8080\", nil)\n\tc.Assert(err, checker.IsNil)\n\tfrontendReq.Host = \"test.local\"\n\n\terr = try.Request(frontendReq, 2*time.Second, try.BodyContains(\"An error occurred.\"))\n\tc.Assert(err, checker.IsNil)\n}\n\nfunc (s *ErrorPagesSuite) TestSimpleConfiguration(c *check.C) ", "output": "{\n\n\tfile := s.adaptFile(c, \"fixtures/error_pages/simple.toml\", struct {\n\t\tServer1 string\n\t\tServer2 string\n\t}{s.BackendIP, s.ErrorPageIP})\n\tdefer os.Remove(file)\n\n\tcmd, display := s.traefikCmd(withConfigFile(file))\n\tdefer display(c)\n\terr := cmd.Start()\n\tc.Assert(err, checker.IsNil)\n\tdefer cmd.Process.Kill()\n\n\tfrontendReq, err := http.NewRequest(http.MethodGet, \"http://127.0.0.1:8080\", nil)\n\tc.Assert(err, checker.IsNil)\n\tfrontendReq.Host = \"test.local\"\n\n\terr = try.Request(frontendReq, 2*time.Second, try.BodyContains(\"nginx\"))\n\tc.Assert(err, checker.IsNil)\n}"} {"input": "package bds\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype MetricThresholdRule struct {\n\n\tDurationInMinutes *int `mandatory:\"true\" json:\"durationInMinutes\"`\n\n\tOperator MetricThresholdRuleOperatorEnum `mandatory:\"true\" json:\"operator\"`\n\n\tValue *int `mandatory:\"true\" json:\"value\"`\n}\n\nfunc (m MetricThresholdRule) String() string {\n\treturn common.PointerString(m)\n}\n\n\ntype MetricThresholdRuleOperatorEnum string\n\n\nconst (\n\tMetricThresholdRuleOperatorGt MetricThresholdRuleOperatorEnum = \"GT\"\n\tMetricThresholdRuleOperatorLt MetricThresholdRuleOperatorEnum = \"LT\"\n)\n\nvar mappingMetricThresholdRuleOperator = map[string]MetricThresholdRuleOperatorEnum{\n\t\"GT\": MetricThresholdRuleOperatorGt,\n\t\"LT\": MetricThresholdRuleOperatorLt,\n}\n\n\n\n\nfunc GetMetricThresholdRuleOperatorEnumValues() []MetricThresholdRuleOperatorEnum ", "output": "{\n\tvalues := make([]MetricThresholdRuleOperatorEnum, 0)\n\tfor _, v := range mappingMetricThresholdRuleOperator {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package channelling\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"log\"\n\n\t\"github.com/strukturag/spreed-webrtc/go/buffercache\"\n)\n\ntype IncomingDecoder interface {\n\tDecodeIncoming(buffercache.Buffer) (*DataIncoming, error)\n}\n\ntype OutgoingEncoder interface {\n\tEncodeOutgoing(*DataOutgoing) (buffercache.Buffer, error)\n}\n\ntype Codec interface {\n\tNewBuffer() buffercache.Buffer\n\tIncomingDecoder\n\tOutgoingEncoder\n}\n\ntype incomingCodec struct {\n\tbuffers buffercache.BufferCache\n\tincomingLimit int\n}\n\nfunc NewCodec(incomingLimit int) Codec {\n\treturn &incomingCodec{buffercache.NewBufferCache(1024, bytes.MinRead), incomingLimit}\n}\n\nfunc (codec incomingCodec) NewBuffer() buffercache.Buffer {\n\treturn codec.buffers.New()\n}\n\nfunc (codec incomingCodec) DecodeIncoming(b buffercache.Buffer) (*DataIncoming, error) {\n\tlength := b.GetBuffer().Len()\n\tif length > codec.incomingLimit {\n\t\treturn nil, errors.New(\"Incoming message size limit exceeded\")\n\t}\n\tincoming := &DataIncoming{}\n\treturn incoming, json.Unmarshal(b.Bytes(), incoming)\n}\n\n\n\nfunc (codec incomingCodec) EncodeOutgoing(outgoing *DataOutgoing) (buffercache.Buffer, error) ", "output": "{\n\tb := codec.NewBuffer()\n\tif err := json.NewEncoder(b).Encode(outgoing); err != nil {\n\t\tlog.Println(\"Error while encoding JSON\", err)\n\t\tb.Decref()\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gorilla/mux\"\n\t\"net/http\"\n)\n\n\n\nfunc NewRouter() *mux.Router ", "output": "{\n\n\trouter := mux.NewRouter().StrictSlash(true)\n\tfor _, route := range routes {\n\t\tvar handler http.Handler\n\n\t\thandler = route.HandlerFunc\n\t\thandler = Logger(handler, route.Name)\n\n\t\trouter.\n\t\t\tMethods(route.Method).\n\t\t\tPath(route.Pattern).\n\t\t\tName(route.Name).\n\t\t\tHandler(handler)\n\n\t}\n\n\treturn router\n\n}"} {"input": "package wikipedia\n\nimport (\n\t\"log\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestQueryRU(t *testing.T) {\n\tapi := NewApi()\n\tquery := \"лопата\"\n\tres, err := api.Query(RU, query)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tassert.Equal(t, query, res.Query)\n\tassert.NotEmpty(t, res.Items)\n\tfor _, it := range res.Items {\n\t\tlog.Printf(\"Item %s:\\n%s (%s)\\n\\n\", it.Text, it.Description, it.URL)\n\t}\n}\n\n\n\nfunc TestQueryEN(t *testing.T) ", "output": "{\n\tapi := NewApi()\n\tquery := \"shovel\"\n\tres, err := api.Query(EN, query)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tassert.Equal(t, query, res.Query)\n\tassert.NotEmpty(t, res.Items)\n\tfor _, it := range res.Items {\n\t\tlog.Printf(\"Item %s:\\n%s (%s)\\n\\n\", it.Text, it.Description, it.URL)\n\t}\n}"} {"input": "package context\n\nimport (\n\t\"context\"\n)\n\n\ntype subscriptionKey struct{}\n\n\n\n\n\nfunc GetSubscriptionKey(ctx context.Context) (string, error) {\n\tuntyped := ctx.Value(subscriptionKey{})\n\tif untyped == nil {\n\t\treturn \"\", ErrSubscriptionKeyNotPresent\n\t}\n\treturn untyped.(string), nil\n}\n\nfunc WithSubscriptionKey(ctx context.Context, key string) context.Context ", "output": "{\n\treturn context.WithValue(ctx, subscriptionKey{}, key)\n}"} {"input": "package writer\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\nconst (\n\tdefaultFlexibleWriterSize = 64\n)\n\ntype FlexibleWriter struct {\n\t*bytes.Buffer\n\twriter io.Writer\n}\n\nfunc NewFlexibleWriter(writer io.Writer) *FlexibleWriter {\n\tw := &FlexibleWriter{}\n\tw.writer = writer\n\tbuf := make([]byte, 0, defaultFlexibleWriterSize)\n\tw.Buffer = bytes.NewBuffer(buf)\n\treturn w\n}\n\n\n\nfunc (this *FlexibleWriter) Buffered() int {\n\treturn this.Len()\n}\n\nfunc (this *FlexibleWriter) Flush() (err error) ", "output": "{\n\t_, err = this.Buffer.WriteTo(this.writer)\n\n\treturn\n}"} {"input": "package gull\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype Up struct {\n\tEnvironment string\n\tSourceDirectory string\n\tMigrateTarget MigrationTarget\n\tMigrations *Migrations\n}\n\nfunc NewUp(source string, target MigrationTarget) *Up {\n\treturn &Up{\n\t\tEnvironment: target.GetEnvironment(),\n\t\tMigrateTarget: target,\n\t\tSourceDirectory: source,\n\t\tMigrations: NewMigrations(),\n\t}\n}\n\n\n\nfunc (u *Up) Ingest() error {\n\treturn filepath.Walk(u.SourceDirectory, u.IngestFile)\n}\n\nfunc (u *Up) IngestFile(path string, f os.FileInfo, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !f.IsDir() {\n\t\tmigration, err := NewMigrationFromGullFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = u.Migrations.Add(migration)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (u *Up) Migrate() error ", "output": "{\n\terr := u.Ingest()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif u.MigrateTarget.IsPerformingFullMigration() {\n\t\tu.MigrateTarget.GetLogger().Info(\"Deleting configuration for [%v]/[%v]\", u.MigrateTarget.GetApplication(), u.MigrateTarget.GetEnvironment())\n\t\t_ = u.MigrateTarget.DeleteEnvironment()\n\t}\n\treturn u.Migrations.Apply(u.MigrateTarget)\n}"} {"input": "package matcher\n\nimport \"errors\"\n\ntype IntComparator struct{}\n\nfunc (s *IntComparator) Valid(data interface{}) error {\n\tif _, ok := data.(int); !ok {\n\t\treturn errors.New(\"Invalid argument\")\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (s *IntComparator) LessThan(a, b interface{}) bool {\n\treturn a.(int) < b.(int)\n}\n\nfunc (s *IntComparator) EqualTo(a, b interface{}) bool {\n\treturn a.(int) == b.(int)\n}\n\nfunc (s *IntComparator) NotEqualTo(a, b interface{}) bool {\n\treturn a.(int) != b.(int)\n}\n\nfunc (s *IntComparator) GreaterThan(a, b interface{}) bool ", "output": "{\n\treturn a.(int) > b.(int)\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"k8s.io/client-go/kubernetes/typed/extensions/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeExtensionsV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeExtensionsV1beta1) DaemonSets(namespace string) v1beta1.DaemonSetInterface {\n\treturn &FakeDaemonSets{c, namespace}\n}\n\n\n\nfunc (c *FakeExtensionsV1beta1) Ingresses(namespace string) v1beta1.IngressInterface {\n\treturn &FakeIngresses{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) PodSecurityPolicies() v1beta1.PodSecurityPolicyInterface {\n\treturn &FakePodSecurityPolicies{c}\n}\n\nfunc (c *FakeExtensionsV1beta1) ReplicaSets(namespace string) v1beta1.ReplicaSetInterface {\n\treturn &FakeReplicaSets{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) Scales(namespace string) v1beta1.ScaleInterface {\n\treturn &FakeScales{c, namespace}\n}\n\n\n\nfunc (c *FakeExtensionsV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeExtensionsV1beta1) Deployments(namespace string) v1beta1.DeploymentInterface ", "output": "{\n\treturn &FakeDeployments{c, namespace}\n}"} {"input": "package util\n\nimport (\n\t\"github.com/go-kit/kit/log\"\n\t\"net/http\"\n\t\"path\"\n\t\"strings\"\n)\n\ntype catchAllFileHandler struct {\n\tFS http.FileSystem\n\tInnerHandler http.Handler\n\tserveInstead string\n\tLogger log.Logger\n}\n\nfunc CatchAllFileServer(\n\troot http.FileSystem,\n\tserveInstead string,\n\tlogger log.Logger,\n) http.Handler {\n\treturn &catchAllFileHandler{\n\t\tFS: root,\n\t\tInnerHandler: http.FileServer(root),\n\t\tserveInstead: serveInstead,\n\t\tLogger: logger,\n\t}\n}\n\nfunc (f *catchAllFileHandler) ServeFallback(w http.ResponseWriter, r *http.Request) {\n\tfile, err := f.FS.Open(f.serveInstead)\n\tif err != nil {\n\t\tf.Logger.Log(\n\t\t\t\"action\", \"serve-fallback\",\n\t\t\t\"result\", false,\n\t\t\t\"message\", err,\n\t\t)\n\t}\n\n\td, err := file.Stat()\n\tif err != nil {\n\t\tf.Logger.Log(\n\t\t\t\"action\", \"serve-fallback\",\n\t\t\t\"result\", false,\n\t\t\t\"message\", err,\n\t\t)\n\t}\n\n\thttp.ServeContent(w, r, f.serveInstead, d.ModTime(), file)\n}\n\n\n\nfunc (f *catchAllFileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tif !strings.HasPrefix(r.URL.Path, \"/\") {\n\t\tr.URL.Path = \"/\" + r.URL.Path\n\t}\n\n\tfindPath := path.Clean(r.URL.Path)\n\tfile, err := f.FS.Open(findPath)\n\tif err != nil {\n\t\tf.ServeFallback(w, r)\n\t\treturn\n\t}\n\n\tif _, err := file.Stat(); err != nil {\n\t\tf.ServeFallback(w, r)\n\t\treturn\n\t}\n\n\tf.InnerHandler.ServeHTTP(w, r)\n}"} {"input": "package noops\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/spf13/viper\"\n)\n\nconst configPrefix = \"CORE_NOOPS\"\n\n\n\nfunc loadConfig() (config *viper.Viper) ", "output": "{\n\tconfig = viper.New()\n\n\tconfig.SetEnvPrefix(configPrefix)\n\tconfig.AutomaticEnv()\n\treplacer := strings.NewReplacer(\".\", \"_\")\n\tconfig.SetEnvKeyReplacer(replacer)\n\n\tconfig.SetConfigName(\"config\")\n\tconfig.AddConfigPath(\"./\")\n\tconfig.AddConfigPath(\"../consensus/noops/\")\n\tgopath := os.Getenv(\"GOPATH\")\n\tfor _, p := range filepath.SplitList(gopath) {\n\t\tpath := filepath.Join(p, \"src/github.com/TarantulaTechnology/fabric/consensus/noops\")\n\t\tconfig.AddConfigPath(path)\n\t}\n\terr := config.ReadInConfig()\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Error reading %s plugin config: %s\", configPrefix, err))\n\t}\n\treturn config\n}"} {"input": "package modules\n\nimport (\n\t\"github.com/NiZiL/i3line/core\"\n\t\"time\"\n)\n\ntype DateModule struct {\n\tFormat string\n}\n\nfunc (m DateModule) GenBlock() i3line.Block {\n\treturn i3line.NewDefaultBlock(time.Now().Format(m.Format))\n}\n\n\n\nfunc (m DateModule) OnClick(e i3line.Event) bool ", "output": "{\n\treturn false\n}"} {"input": "package helloplugin\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cafxx/pluggo\"\n)\n\nfunc init() {\n\tpluggo.Register(\"hello\", func() interface{} {\n\t\treturn &hello{}\n\t})\n}\n\ntype hello struct {\n}\n\n\n\nfunc (*hello) Say() ", "output": "{\n\tfmt.Println(\"Hello pluggo\")\n}"} {"input": "package types\n\n\n\n\nimport (\n\t\"github.com/jcmturner/gofork/encoding/asn1\"\n)\n\n\n\n\nfunc NewKrbFlags() asn1.BitString {\n\tf := asn1.BitString{}\n\tf.Bytes = make([]byte, 4)\n\tf.BitLength = len(f.Bytes) * 8\n\treturn f\n}\n\n\nfunc SetFlags(f *asn1.BitString, j []int) {\n\tfor _, i := range j {\n\t\tSetFlag(f, i)\n\t}\n}\n\n\n\n\n\nfunc UnsetFlags(f *asn1.BitString, j []int) {\n\tfor _, i := range j {\n\t\tUnsetFlag(f, i)\n\t}\n}\n\n\nfunc UnsetFlag(f *asn1.BitString, i int) {\n\tfor l := len(f.Bytes); l < 4; l++ {\n\t\t(*f).Bytes = append((*f).Bytes, byte(0))\n\t\t(*f).BitLength = len((*f).Bytes) * 8\n\t}\n\tb := i / 8\n\tp := uint(7 - (i - 8*b))\n\t(*f).Bytes[b] = (*f).Bytes[b] &^ (1 << p)\n}\n\n\nfunc IsFlagSet(f *asn1.BitString, i int) bool {\n\tb := i / 8\n\tp := uint(7 - (i - 8*b))\n\tif (*f).Bytes[b]&(1< 7 {\n\t\thops = 7\n\t}\n\n\treturn ControlField2(hops&7) << 4\n}\n\nfunc (ctrl2 ControlField2) Hops() uint8 ", "output": "{\n\treturn uint8(ctrl2>>7) & 7\n}"} {"input": "package Utils\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestBinary(t *testing.T) {\n\tmergeBuf := MergeBinary([]byte(\"i am first words\"), []byte(\"i am second words\"))\n\n\tsplitBuf := SplitBinary(mergeBuf)\n\n\tfor _, v := range splitBuf {\n\t\tfmt.Println(string(v))\n\t}\n}\n\n\n\nfunc TestGzip(t *testing.T) ", "output": "{\n\tmergeBuf := MergeBinary([]byte(\"i am first words\"), []byte(\"i am second words\"))\n\n\tgzip, err := FastGZipMsg(mergeBuf, true)\n\tif err != nil {\n\t\tt.Fail()\n\t\treturn\n\t}\n\n\tunzip, err := FastUnGZipMsg(gzip, true)\n\tif err != nil {\n\t\tt.Fail()\n\t\treturn\n\t}\n\n\tsplitBuf := SplitBinary(unzip)\n\n\tfor _, v := range splitBuf {\n\t\tfmt.Println(string(v))\n\t}\n}"} {"input": "package language\n\nimport (\n\t\"database/sql\"\n\t\"time\"\n\t\"xrguide/db/query\"\n)\n\ntype Language struct {\n\tId int64\n\tName string\n}\n\nvar (\n\tlangIdCache = make(map[int64]*Language)\n\tlangNameCache = make(map[string]*Language)\n\tsetCache = make(chan *Language)\n\tgetIdCache = make(chan map[int64]*Language)\n\tgetNameCache = make(chan map[string]*Language)\n)\n\nfunc init() {\n\tgo func() {\n\t\tselect {\n\t\tcase l := <-setCache:\n\t\t\tlangIdCache[l.Id] = l\n\t\t\tlangNameCache[l.Name] = l\n\n\t\tcase getIdCache <- langIdCache:\n\n\t\tcase getNameCache <- langNameCache:\n\t\t}\n\t}()\n}\n\nfunc LanguageById(db *sql.DB, id int64) (*Language, error) {\n\tvar lang *Language\n\tto := time.After(50 * time.Millisecond)\n\tselect {\n\tcase cache := <-getIdCache:\n\t\tlang, ok := cache[id]\n\t\tif ok {\n\t\t\treturn lang, nil\n\t\t}\n\tcase <-to:\n\t}\n\tlang = new(Language)\n\tq := query.SelectLanguage + \" WHERE id = ?\"\n\trow := db.QueryRow(q, id)\n\terr := row.Scan(&lang.Id, &lang.Name)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tto = time.After(50 * time.Millisecond)\n\tselect {\n\tcase setCache <- lang:\n\tcase <-to:\n\t}\n\treturn lang, nil\n}\n\n\n\nfunc LanguageByName(db *sql.DB, name string) (*Language, error) ", "output": "{\n\tvar lang *Language\n\tto := time.After(50 * time.Millisecond)\n\tselect {\n\tcase cache := <-getNameCache:\n\t\tlang, ok := cache[name]\n\t\tif ok {\n\t\t\treturn lang, nil\n\t\t}\n\tcase <-to:\n\t}\n\tlang = new(Language)\n\tq := query.SelectLanguage + \" WHERE name = ?\"\n\trow := db.QueryRow(q, name)\n\terr := row.Scan(&lang.Id, &lang.Name)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tto = time.After(50 * time.Millisecond)\n\tselect {\n\tcase setCache <- lang:\n\tcase <-to:\n\t}\n\treturn lang, nil\n\n}"} {"input": "package models\n\nimport (\n\t\"openpitrix.io/openpitrix/pkg/logger\"\n\t\"openpitrix.io/openpitrix/pkg/util/jsonutil\"\n)\n\ntype Volume struct {\n\tVolumeId string\n\tNodeId string\n\tInstanceId string\n\tDevice string\n\tMountPoint string\n\tMountOptions string\n\tFileSystem string\n\tName string\n\tSize int\n\tStatus string\n\tTransitionStatus string\n\tZone string\n\tRuntimeId string\n\tTargetJobId string \n\tTimeout int `json:\"timeout\"`\n}\n\n\n\nfunc NewVolume(data string) (*Volume, error) ", "output": "{\n\tvolume := &Volume{}\n\terr := jsonutil.Decode([]byte(data), volume)\n\tif err != nil {\n\t\tlogger.Error(nil, \"Decode [%s] into volume failed: %+v\", data, err)\n\t}\n\treturn volume, err\n}"} {"input": "package sql\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/cockroachdb/cockroach/pkg/roachpb\"\n\t\"github.com/cockroachdb/cockroach/pkg/sql/parser\"\n\t\"github.com/cockroachdb/cockroach/pkg/sql/sqlbase\"\n)\n\n\n\n\ntype delayedNode struct {\n\tname string\n\tcolumns sqlbase.ResultColumns\n\tconstructor nodeConstructor\n\tplan planNode\n}\n\ntype nodeConstructor func(context.Context, *planner) (planNode, error)\n\nfunc (d *delayedNode) Close(ctx context.Context) {\n\tif d.plan != nil {\n\t\td.plan.Close(ctx)\n\t\td.plan = nil\n\t}\n}\n\n\nfunc (d *delayedNode) Ordering() orderingInfo { return orderingInfo{} }\nfunc (d *delayedNode) MarkDebug(_ explainMode) {}\nfunc (d *delayedNode) Start(ctx context.Context) error { return d.plan.Start(ctx) }\nfunc (d *delayedNode) Next(ctx context.Context) (bool, error) { return d.plan.Next(ctx) }\nfunc (d *delayedNode) Values() parser.Datums { return d.plan.Values() }\nfunc (d *delayedNode) DebugValues() debugValues { return d.plan.DebugValues() }\nfunc (d *delayedNode) Spans(ctx context.Context) (_, _ roachpb.Spans, _ error) {\n\treturn d.plan.Spans(ctx)\n}\n\nfunc (d *delayedNode) Columns() sqlbase.ResultColumns ", "output": "{ return d.columns }"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/robfig/cron\"\n)\n\ntype Sync struct{}\n\nfunc (s *Sync) Help() string {\n\treturn \"glr sync Help\"\n}\n\nfunc (s *Sync) Run(args []string) int {\n\t_, err := SyncRepository()\n\n\tif err != nil {\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n\nfunc (s *Sync) Synopsis() string {\n\treturn \"Synchronize local git repository with remote at once\"\n}\n\n\ntype status struct {\n\tc *cron.Cron\n\trepositories []string\n\tschedules []string\n}\n\nvar sharedStatus *status = newStatus()\n\nfunc newStatus() *status {\n\treturn &status{\n\t\tc: cron.New(),\n\t}\n}\n\n\nfunc GetStatus() *status {\n\treturn sharedStatus\n}\n\ntype StatusStart struct{}\n\nfunc (s *StatusStart) Help() string {\n\treturn \"glr status start Help\"\n}\n\nfunc (s *StatusStart) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.AddFunc(\"@hourly\", func() {\n\t\tSyncRepository()\n\t})\n\tfmt.Println(\"set job schedule\")\n\tstatus.c.Start()\n\n\treturn 0\n}\n\nfunc (s *StatusStart) Synopsis() string {\n\treturn \"Synchronize local git repository with remote\"\n}\n\ntype StatusStop struct{}\n\nfunc (s *StatusStop) Help() string {\n\treturn \"glr status stop Help\"\n}\n\nfunc (s *StatusStop) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.Stop()\n\tfmt.Println(\"stop job scheduler\")\n\n\treturn 0\n}\n\n\n\nfunc (s *StatusStop) Synopsis() string ", "output": "{\n\treturn \"Stop cron scheduler\"\n}"} {"input": "package errors\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n)\n\n\ntype HTTPError struct {\n\tStatusCode int\n\terror\n}\n\n\nfunc (e *HTTPError) Error() string {\n\treturn e.error.Error()\n}\n\n\n\n\nfunc NewMethodNotAllowed(method string) *HTTPError {\n\treturn &HTTPError{http.StatusMethodNotAllowed, errors.New(`Method is not allowed:\"` + method + `\"`)}\n}\n\n\n\n\n\n\nfunc NewBadRequestString(s string) *HTTPError {\n\treturn NewBadRequest(errors.New(s))\n}\n\n\n\nfunc NewBadRequestMissingParameter(s string) *HTTPError {\n\treturn NewBadRequestString(`Missing parameter \"` + s + `\"`)\n}\n\n\n\nfunc NewBadRequestUnwantedParameter(s string) *HTTPError {\n\treturn NewBadRequestString(`Unwanted parameter \"` + s + `\"`)\n}\n\nfunc NewBadRequest(err error) *HTTPError ", "output": "{\n\treturn &HTTPError{http.StatusBadRequest, err}\n}"} {"input": "package azurerm\n\nimport (\n\t\"testing\"\n\n\t\"fmt\"\n\n\t\"github.com/hashicorp/terraform/helper/acctest\"\n\t\"github.com/hashicorp/terraform/helper/resource\"\n)\n\n\n\nfunc TestAccAzureRMEventHub_importBasic(t *testing.T) ", "output": "{\n\tresourceName := \"azurerm_eventhub.test\"\n\n\tri := acctest.RandInt()\n\tconfig := fmt.Sprintf(testAccAzureRMEventHub_basic, ri, ri, ri)\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testCheckAzureRMEventHubDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: config,\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tResourceName: resourceName,\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}"} {"input": "package utils\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\tirc \"gopkg.in/irc.v3\"\n)\n\n\n\ntype TestClientServer struct {\n\tclient *bytes.Buffer\n\tserver *bytes.Buffer\n}\n\n\n\n\n\nfunc (cs *TestClientServer) Read(p []byte) (int, error) {\n\treturn cs.server.Read(p)\n}\n\n\nfunc (cs *TestClientServer) Write(p []byte) (int, error) {\n\treturn cs.client.Write(p)\n}\n\n\n\nfunc (cs *TestClientServer) SendServerLines(lines []string) {\n\tw := irc.NewWriter(cs.server)\n\n\tfor _, line := range lines {\n\t\tw.WriteMessage(irc.MustParseMessage(line))\n\t}\n}\n\n\n\n\nfunc (cs *TestClientServer) CheckLines(t *testing.T, expected []string) bool {\n\tok := true\n\n\tlines := strings.Split(cs.client.String(), \"\\r\\n\")\n\n\tvar line, clientLine string\n\tfor len(expected) > 0 && len(lines) > 0 {\n\t\tline, expected = expected[0], expected[1:]\n\t\tclientLine, lines = lines[0], lines[1:]\n\n\t\tok = ok && assert.Equal(t, line, clientLine)\n\t}\n\n\tok = ok && assert.Equal(t, 0, len(expected), \"Not enough lines: %s\", strings.Join(expected, \", \"))\n\tok = ok && assert.Equal(t, 0, len(lines), \"Extra non-empty lines: %s\", strings.Join(lines, \", \"))\n\n\treturn ok\n}\n\n\nfunc (cs *TestClientServer) Reset() {\n\tcs.client.Reset()\n\tcs.server.Reset()\n}\n\nfunc NewTestClientServer() *TestClientServer ", "output": "{\n\treturn &TestClientServer{\n\t\tclient: &bytes.Buffer{},\n\t\tserver: &bytes.Buffer{},\n\t}\n}"} {"input": "package bits\n\nimport (\n\t\"path/filepath\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"k8s.io/kubeadm/kinder/pkg/extract\"\n)\n\n\n\ntype binaryBits struct {\n\tsrc string\n\tbinaryName string\n}\n\nvar _ Installer = &binaryBits{}\n\n\nfunc NewBinaryBits(src, binaryName string) Installer {\n\treturn &binaryBits{\n\t\tsrc: src,\n\t\tbinaryName: binaryName,\n\t}\n}\n\n\n\n\n\nfunc (b *binaryBits) Install(c *BuildContext) error {\n\tsrc := filepath.Join(c.ContainerBitsPath(), b.binaryName)\n\n\tdest := filepath.Join(\"/usr\", \"bin\", b.binaryName)\n\n\tif err := c.RunInContainer(\"cp\", src, dest); err != nil {\n\t\tlog.Errorf(\"Image alter Failed! %v\", err)\n\t\treturn err\n\t}\n\n\tif err := c.RunInContainer(\"chown\", \"-R\", \"root:root\", dest); err != nil {\n\t\tlog.Errorf(\"Image alter failed! %v\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (b *binaryBits) Prepare(c *BuildContext) (map[string]string, error) ", "output": "{\n\te := extract.NewExtractor(\n\t\tb.src, c.HostBitsPath(),\n\t\textract.OnlyKubeadm(b.binaryName == \"kubeadm\"),\n\t\textract.OnlyKubelet(b.binaryName == \"kubelet\"),\n\t)\n\n\treturn e.Extract()\n}"} {"input": "package v3public\n\nimport (\n\t\"github.com/rancher/norman/lifecycle\"\n\t\"github.com/rancher/norman/resource\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\ntype AuthProviderLifecycle interface {\n\tCreate(obj *AuthProvider) (runtime.Object, error)\n\tRemove(obj *AuthProvider) (runtime.Object, error)\n\tUpdated(obj *AuthProvider) (runtime.Object, error)\n}\n\ntype authProviderLifecycleAdapter struct {\n\tlifecycle AuthProviderLifecycle\n}\n\nfunc (w *authProviderLifecycleAdapter) HasCreate() bool {\n\to, ok := w.lifecycle.(lifecycle.ObjectLifecycleCondition)\n\treturn !ok || o.HasCreate()\n}\n\nfunc (w *authProviderLifecycleAdapter) HasFinalize() bool {\n\to, ok := w.lifecycle.(lifecycle.ObjectLifecycleCondition)\n\treturn !ok || o.HasFinalize()\n}\n\nfunc (w *authProviderLifecycleAdapter) Create(obj runtime.Object) (runtime.Object, error) {\n\to, err := w.lifecycle.Create(obj.(*AuthProvider))\n\tif o == nil {\n\t\treturn nil, err\n\t}\n\treturn o, err\n}\n\nfunc (w *authProviderLifecycleAdapter) Finalize(obj runtime.Object) (runtime.Object, error) {\n\to, err := w.lifecycle.Remove(obj.(*AuthProvider))\n\tif o == nil {\n\t\treturn nil, err\n\t}\n\treturn o, err\n}\n\nfunc (w *authProviderLifecycleAdapter) Updated(obj runtime.Object) (runtime.Object, error) {\n\to, err := w.lifecycle.Updated(obj.(*AuthProvider))\n\tif o == nil {\n\t\treturn nil, err\n\t}\n\treturn o, err\n}\n\n\n\nfunc NewAuthProviderLifecycleAdapter(name string, clusterScoped bool, client AuthProviderInterface, l AuthProviderLifecycle) AuthProviderHandlerFunc ", "output": "{\n\tif clusterScoped {\n\t\tresource.PutClusterScoped(AuthProviderGroupVersionResource)\n\t}\n\tadapter := &authProviderLifecycleAdapter{lifecycle: l}\n\tsyncFn := lifecycle.NewObjectLifecycleAdapter(name, clusterScoped, adapter, client.ObjectClient())\n\treturn func(key string, obj *AuthProvider) (runtime.Object, error) {\n\t\tnewObj, err := syncFn(key, obj)\n\t\tif o, ok := newObj.(runtime.Object); ok {\n\t\t\treturn o, err\n\t\t}\n\t\treturn nil, err\n\t}\n}"} {"input": "package tsm1\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/influxdata/influxdb/influxql\"\n)\n\n\n\nfunc newLimitIterator(input influxql.Iterator, opt influxql.IteratorOptions) influxql.Iterator ", "output": "{\n\tswitch input := input.(type) {\n\tcase influxql.FloatIterator:\n\t\treturn newFloatLimitIterator(input, opt)\n\tcase influxql.IntegerIterator:\n\t\treturn newIntegerLimitIterator(input, opt)\n\tcase influxql.StringIterator:\n\t\treturn newStringLimitIterator(input, opt)\n\tcase influxql.BooleanIterator:\n\t\treturn newBooleanLimitIterator(input, opt)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unsupported limit iterator type: %T\", input))\n\t}\n}"} {"input": "package math\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\ntype CT_Integer2 struct {\n\tValAttr int64\n}\n\nfunc NewCT_Integer2() *CT_Integer2 {\n\tret := &CT_Integer2{}\n\tret.ValAttr = -2\n\treturn ret\n}\n\nfunc (m *CT_Integer2) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"m:val\"},\n\t\tValue: fmt.Sprintf(\"%v\", m.ValAttr)})\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}\n\nfunc (m *CT_Integer2) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tm.ValAttr = -2\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"val\" {\n\t\t\tparsed, err := strconv.ParseInt(attr.Value, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.ValAttr = parsed\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_Integer2: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (m *CT_Integer2) Validate() error {\n\treturn m.ValidateWithPath(\"CT_Integer2\")\n}\n\n\n\n\nfunc (m *CT_Integer2) ValidateWithPath(path string) error ", "output": "{\n\tif m.ValAttr < -2 {\n\t\treturn fmt.Errorf(\"%s/m.ValAttr must be >= -2 (have %v)\", path, m.ValAttr)\n\t}\n\tif m.ValAttr > 2 {\n\t\treturn fmt.Errorf(\"%s/m.ValAttr must be <= 2 (have %v)\", path, m.ValAttr)\n\t}\n\treturn nil\n}"} {"input": "package persist\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n)\n\n\ntype Database struct {\n\tuser string\n\tpassword string\n\tdatabase string\n\thost string\n}\n\n\nfunc NewDatabase(username string, password string, database string, host string) Database {\n\treturn Database{username, password, database, host}\n}\n\n\n\n\nfunc (db Database) getConnection() (*sql.DB, error) {\n\tcon, err := sql.Open(\"mysql\", fmt.Sprintf(\"%v:%v@tcp(%v:3306)/%v?parseTime=true\", db.user, db.password, db.host, db.database))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn con, nil\n}\n\n\nfunc (db Database) GetConnectionString() string {\n\treturn fmt.Sprintf(\"Data Source=%s;Database=%s;User ID=%s;Password=%s;Old Guids=true;\", db.host, db.database, db.user, db.password)\n}\n\nfunc (db Database) TestConnection() error ", "output": "{\n\tcon, err := db.getConnection()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer con.Close()\n\n\terr = con.Ping()\n\treturn err\n}"} {"input": "package utils\n\nimport \"fmt\"\n\nfunc ExampleStringSet_Add() {\n\tset := NewStringSet()\n\tset.Add(\"a\")\n\tset.Add(\"b\")\n\n\tfmt.Println(set)\n\tset.Add(\"a\")\n\tfmt.Println(set)\n\n}\n\nfunc ExampleNewStringSet() {\n\ta := NewStringSet()\n\ta.Add(\"a\")\n\ta.Add(\"b\")\n\n\tb := NewStringSet(\"b\", \"a\")\n\n\tfmt.Println(a.Equals(b))\n\n}\n\nfunc ExampleNewStringSetFromStringMapKeys() {\n\tm := map[string]string{\n\t\t\"a\": \"some a value\",\n\t\t\"b\": \"some b value\",\n\t}\n\n\tset := NewStringSetFromStringMapKeys(m)\n\tfmt.Println(set)\n\n}\n\nfunc ExampleStringSet_ToSlice() {\n\ta := NewStringSet()\n\ta.Add(\"z\")\n\ta.Add(\"b\")\n\n\tfmt.Println(a.ToSlice())\n\n}\n\nfunc ExampleStringSet_IsEmpty() {\n\ta := NewStringSet()\n\n\tfmt.Println(a.IsEmpty())\n\ta.Add(\"a\")\n\tfmt.Println(a.IsEmpty())\n\n}\n\n\n\nfunc ExampleStringSet_Contains() {\n\ta := NewStringSet(\"a\", \"b\")\n\tfmt.Println(a.Contains(\"z\"))\n\tfmt.Println(a.Contains(\"a\"))\n\n}\n\nfunc ExampleStringSet_Minus() {\n\ta := NewStringSet(\"a\", \"b\")\n\tb := NewStringSet(\"b\", \"c\")\n\tdelta := a.Minus(b)\n\n\tfmt.Println(delta)\n}\n\nfunc ExampleStringSet_Equals() ", "output": "{\n\ta := NewStringSet(\"a\", \"b\")\n\tb := NewStringSet(\"a\", \"b\", \"c\")\n\tfmt.Println(a.Equals(b))\n\n\ta.Add(\"c\")\n\tfmt.Println(a.Equals(b))\n\n}"} {"input": "package plugin\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestExtrSocketInfo(t *testing.T) ", "output": "{\n\targs := []string{\"receptord\", \"unix\", \"/tmp/test.sock\"}\n\t_, _, err := extrSocketInfo(args[:1])\n\tif err == nil {\n\t\tt.Fatal(\"Expected error\")\n\t}\n\tnet, laddr, err := extrSocketInfo(args)\n\tif err != nil {\n\t\tt.Fatal(\"No error expected\")\n\t}\n\tif net != \"unix\" || laddr != \"/tmp/test.sock\" {\n\t\tt.Fatal(\"Wrong parsed arguments\")\n\t}\n\n}"} {"input": "package query\n\nfunc excludeManagementNet(conditional string) string {\n\treturn conditional\n}\n\n\n\nfunc hideManagementTraffic(conditional string) string ", "output": "{\n\treturn conditional\n}"} {"input": "package logging\n\n\ntype DefaultFormatter struct {\n}\n\n\nfunc (f *DefaultFormatter) GetPrefix(lvl level) string {\n\treturn \"\"\n}\n\n\nfunc (f *DefaultFormatter) GetSuffix(lvl level) string {\n\treturn \"\"\n}\n\n\n\n\nfunc (f *DefaultFormatter) Format(lvl level, v ...interface{}) []interface{} ", "output": "{\n\treturn append([]interface{}{header()}, v...)\n}"} {"input": "package controller\n\nimport (\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n\ntype Controller struct {\n\te *gin.Engine\n}\n\n\n\n\n\nfunc (c *Controller) SetupRouters() {\n\tc.e.GET(\"/ping2\", c.ping)\n\n}\n\n\nfunc (p *Controller) ping(ctx *gin.Context) {\n\tctx.String(200, \"pong pong\")\n}\n\nfunc New( e *gin.Engine) *Controller ", "output": "{\n\n\treturn &Controller{\n\t\te: e,\n\t}\n\n}"} {"input": "package auto\n\nimport (\n\t\"sync\"\n\n\t\"github.com/miekg/coredns/middleware/file\"\n)\n\n\n\ntype Zones struct {\n\tZ map[string]*file.Zone \n\tnames []string \n\n\torigins []string \n\n\tsync.RWMutex\n}\n\n\nfunc (z *Zones) Names() []string {\n\tz.RLock()\n\tn := z.names\n\tz.RUnlock()\n\treturn n\n}\n\n\nfunc (z *Zones) Origins() []string {\n\treturn z.origins\n}\n\n\nfunc (z *Zones) Zones(name string) *file.Zone {\n\tz.RLock()\n\tzo := z.Z[name]\n\tz.RUnlock()\n\treturn zo\n}\n\n\n\n\n\n\nfunc (z *Zones) Remove(name string) {\n\tz.Lock()\n\n\tif zo, ok := z.Z[name]; ok && !zo.NoReload {\n\t\tzo.ReloadShutdown <- true\n\t}\n\n\tdelete(z.Z, name)\n\n\tz.names = []string{}\n\tfor n := range z.Z {\n\t\tz.names = append(z.names, n)\n\t}\n\n\tz.Unlock()\n}\n\nfunc (z *Zones) Add(zo *file.Zone, name string) ", "output": "{\n\tz.Lock()\n\n\tif z.Z == nil {\n\t\tz.Z = make(map[string]*file.Zone)\n\t}\n\n\tz.Z[name] = zo\n\tz.names = append(z.names, name)\n\tzo.Reload()\n\n\tz.Unlock()\n}"} {"input": "package errors\n\nimport \"reflect\"\n\n\n\n\nfunc unwrap(err error) error {\n\tu, ok := err.(interface {\n\t\tUnwrap() error\n\t})\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn u.Unwrap()\n}\n\nfunc Is(err, target error) bool ", "output": "{\n\tif target == nil {\n\t\treturn err == target\n\t}\n\n\tisComparable := reflect.TypeOf(target).Comparable()\n\tfor {\n\t\tif isComparable && err == target {\n\t\t\treturn true\n\t\t}\n\t\tif x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) {\n\t\t\treturn true\n\t\t}\n\t\tif err = unwrap(err); err == nil {\n\t\t\treturn false\n\t\t}\n\t}\n}"} {"input": "package instagram\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"net/url\"\n\n\t\"github.com/laicosly/goth\"\n\t\"golang.org/x/oauth2\"\n)\n\n\ntype Session struct {\n\tAuthURL string\n\tAccessToken string\n\tState string\n\tParams url.Values\n}\n\n\n\n\n\nfunc (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {\n\tp := provider.(*Provider)\n\ttoken, err := p.config.Exchange(oauth2.NoContext, params.Get(\"code\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ts.AccessToken = token.AccessToken\n\treturn token.AccessToken, err\n}\n\n\nfunc (s Session) Marshal() string {\n\tb, _ := json.Marshal(s)\n\treturn string(b)\n}\n\nfunc (s Session) String() string {\n\treturn s.Marshal()\n}\n\nfunc (s Session) GetAuthURL() (string, error) ", "output": "{\n\tif s.AuthURL == \"\" {\n\t\treturn \"\", errors.New(\"an AuthURL has not be set\")\n\t}\n\treturn s.AuthURL, nil\n}"} {"input": "package iso20022\n\n\ntype AcceptorCancellationAdvice3 struct {\n\n\tEnvironment *CardPaymentEnvironment24 `xml:\"Envt\"`\n\n\tContext *CardPaymentContext2 `xml:\"Cntxt,omitempty\"`\n\n\tTransaction *CardPaymentTransaction28 `xml:\"Tx\"`\n}\n\n\n\nfunc (a *AcceptorCancellationAdvice3) AddContext() *CardPaymentContext2 {\n\ta.Context = new(CardPaymentContext2)\n\treturn a.Context\n}\n\nfunc (a *AcceptorCancellationAdvice3) AddTransaction() *CardPaymentTransaction28 {\n\ta.Transaction = new(CardPaymentTransaction28)\n\treturn a.Transaction\n}\n\nfunc (a *AcceptorCancellationAdvice3) AddEnvironment() *CardPaymentEnvironment24 ", "output": "{\n\ta.Environment = new(CardPaymentEnvironment24)\n\treturn a.Environment\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc filter(in chan int, prime int) chan int {\n\tout := make(chan int)\n\tgo func() {\n\t\tfor {\n\t\t\tif i := <-in; i%prime != 0 {\n\t\t\t\tout <- i\n\t\t\t}\n\t\t}\n\t}()\n\treturn out\n}\n\nfunc sieve() chan int {\n\tout := make(chan int)\n\tgo func() {\n\t\tch := generate()\n\t\tfor {\n\t\t\tprime := <-ch\n\t\t\tch = filter(ch, prime)\n\t\t\tout <- prime\n\t\t}\n\t}()\n\treturn out\n}\n\nfunc main() {\n\tprimes := sieve()\n\tfor {\n\t\tfmt.Println(<-primes)\n\t}\n}\n\nfunc generate() chan int ", "output": "{\n\tch := make(chan int)\n\tgo func() {\n\t\tfor i := 2; ; i++ {\n\t\t\tch <- i\n\t\t}\n\t}()\n\treturn ch\n}"} {"input": "package cover\n\nimport (\n\t\"flag\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc ParseAndStripTestFlags() {\n\tflag.Parse()\n\n\tvar runtimeArgs []string\n\tfor _, arg := range os.Args {\n\t\tif strings.HasPrefix(arg, \"-test.\") ||\n\t\t\tstrings.HasPrefix(arg, \"-httptest.\") {\n\t\t\tcontinue\n\t\t}\n\t\truntimeArgs = append(runtimeArgs, arg)\n\t}\n\tos.Args = runtimeArgs\n}\n\ntype dummyTestDeps func(pat, str string) (bool, error)\n\nfunc (d dummyTestDeps) MatchString(pat, str string) (bool, error) { return false, nil }\nfunc (d dummyTestDeps) StartCPUProfile(io.Writer) error { return nil }\nfunc (d dummyTestDeps) StopCPUProfile() {}\nfunc (f dummyTestDeps) StartTestLog(w io.Writer) {}\n\nfunc (d dummyTestDeps) WriteHeapProfile(io.Writer) error { return nil }\nfunc (d dummyTestDeps) WriteProfileTo(string, io.Writer, int) error { return nil }\nfunc (f dummyTestDeps) ImportPath() string { return \"\" }\n\n\n\n\n\nfunc FlushProfiles() {\n\toldstdout := os.Stdout\n\toldstderr := os.Stderr\n\tos.Stdout, _ = os.Open(os.DevNull)\n\tos.Stderr, _ = os.Open(os.DevNull)\n\n\ttests := []testing.InternalTest{}\n\tbenchmarks := []testing.InternalBenchmark{}\n\texamples := []testing.InternalExample{}\n\tvar f dummyTestDeps\n\tdummyM := testing.MainStart(f, tests, benchmarks, examples)\n\tdummyM.Run()\n\n\tos.Stdout = oldstdout\n\tos.Stderr = oldstderr\n}\n\nfunc (f dummyTestDeps) StopTestLog() error ", "output": "{ return nil }"} {"input": "package authy\n\nimport (\n\t\"github.com/tg123/sshpiper/sshpiperd/challenger\"\n)\n\nfunc (authyClient) GetName() string {\n\treturn \"authy\"\n}\n\nfunc (a *authyClient) GetOpts() interface{} {\n\treturn &a.Config\n}\n\n\n\nfunc init() {\n\tchallenger.Register(\"authy\", &authyClient{})\n}\n\nfunc (a *authyClient) GetHandler() challenger.Handler ", "output": "{\n\treturn a.challenge\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n)\n\n\ntype Tree struct {\n\tLeft *Tree\n\tValue int\n\tRight *Tree\n}\n\n\n\n\n\n\n\nfunc Walker(t *Tree) <-chan int {\n\tch := make(chan int)\n\tgo func() {\n\t\tWalk(t, ch)\n\t\tclose(ch)\n\t}()\n\treturn ch\n}\n\n\n\n\nfunc Compare(t1, t2 *Tree) bool {\n\tc1, c2 := Walker(t1), Walker(t2)\n\tfor {\n\t\tv1, ok1 := <-c1\n\t\tv2, ok2 := <-c2\n\t\tif !ok1 || !ok2 {\n\t\t\treturn ok1 == ok2\n\t\t}\n\t\tif v1 != v2 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc New(n, k int) *Tree {\n\tvar t *Tree\n\tfor _, v := range rand.Perm(n) {\n\t\tt = insert(t, (1+v)*k)\n\t}\n\treturn t\n}\n\nfunc insert(t *Tree, v int) *Tree {\n\tif t == nil {\n\t\treturn &Tree{nil, v, nil}\n\t}\n\tif v < t.Value {\n\t\tt.Left = insert(t.Left, v)\n\t\treturn t\n\t}\n\tt.Right = insert(t.Right, v)\n\treturn t\n}\n\nfunc main() {\n\tt1 := New(100, 1)\n\tfmt.Println(Compare(t1, New(100, 1)), \"Same Contents\")\n\tfmt.Println(Compare(t1, New(99, 1)), \"Differing Sizes\")\n\tfmt.Println(Compare(t1, New(100, 2)), \"Differing Values\")\n\tfmt.Println(Compare(t1, New(101, 2)), \"Dissimilar\")\n}\n\nfunc Walk(t *Tree, ch chan int) ", "output": "{\n\tif t == nil {\n\t\treturn\n\t}\n\tWalk(t.Left, ch)\n\tch <- t.Value\n\tWalk(t.Right, ch)\n}"} {"input": "package captcha\n\nimport (\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\nfunc BenchmarkNewAudio(b *testing.B) {\n\tb.StopTimer()\n\td := RandomDigits(DefaultLen)\n\tid := randomId()\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tNewAudio(id, d, \"\")\n\t}\n}\n\n\n\nfunc BenchmarkAudioWriteTo(b *testing.B) ", "output": "{\n\tb.StopTimer()\n\td := RandomDigits(DefaultLen)\n\tid := randomId()\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\ta := NewAudio(id, d, \"\")\n\t\tn, _ := a.WriteTo(ioutil.Discard)\n\t\tb.SetBytes(n)\n\t}\n}"} {"input": "package master\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\n\tauth \"github.com/abbot/go-http-auth\"\n\t\"github.com/h2oai/steam/master/az\"\n)\n\ntype DefaultAz struct {\n\tdirectory az.Directory\n}\n\nfunc NewDefaultAz(directory az.Directory) *DefaultAz {\n\treturn &DefaultAz{directory}\n}\n\nfunc (a *DefaultAz) Authenticate(username string) string {\n\tpz, err := a.directory.Lookup(username)\n\tif err != nil {\n\t\tlog.Printf(\"User %s read failed: %s\\n\", username, err)\n\t\treturn \"\"\n\t}\n\n\tif pz == nil {\n\t\tlog.Printf(\"User %s does not exist\\n\", username)\n\t\treturn \"\"\n\t}\n\treturn pz.Password()\n}\n\n\n\nfunc serveNoop(w http.ResponseWriter, r *http.Request) {}\nfunc authNoop(user, realm string) string { return \"\" }\n\nfunc (a *DefaultAz) Identify(r *http.Request) (az.Principal, error) ", "output": "{\n\tusername := r.Header.Get(auth.AuthUsernameHeader)\n\tpz, err := a.directory.Lookup(username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif pz == nil {\n\t\treturn nil, fmt.Errorf(\"User %s does not exist\\n\", username)\n\t}\n\n\treturn pz, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/directorz/mailfull-go\"\n\t\"github.com/directorz/mailfull-go/cmd\"\n)\n\n\ntype CmdDomainDel struct {\n\tcmd.Meta\n}\n\n\n\n\n\nfunc (c *CmdDomainDel) Help() string {\n\ttxt := fmt.Sprintf(`\nUsage:\n %s %s [-n] domain\n\nDescription:\n %s\n\nRequired Args:\n domain\n The domain name that you want to delete.\n\nOptional Args:\n -n\n Don't update databases.\n`,\n\t\tc.CmdName, c.SubCmdName,\n\t\tc.Synopsis())\n\n\treturn txt[1:]\n}\n\n\nfunc (c *CmdDomainDel) Run(args []string) int {\n\tnoCommit, err := noCommitFlag(&args)\n\tif err != nil {\n\t\tfmt.Fprintf(c.UI.ErrorWriter, \"%v\\n\", c.Help())\n\t\treturn 1\n\t}\n\n\tif len(args) != 1 {\n\t\tfmt.Fprintf(c.UI.ErrorWriter, \"%v\\n\", c.Help())\n\t\treturn 1\n\t}\n\n\tdomainName := args[0]\n\n\trepo, err := mailfull.OpenRepository(\".\")\n\tif err != nil {\n\t\tc.Meta.Errorf(\"%v\\n\", err)\n\t\treturn 1\n\t}\n\n\tif err := repo.DomainRemove(domainName); err != nil {\n\t\tc.Meta.Errorf(\"%v\\n\", err)\n\t\treturn 1\n\t}\n\n\tif noCommit {\n\t\treturn 0\n\t}\n\tif err = repo.GenerateDatabases(); err != nil {\n\t\tc.Meta.Errorf(\"%v\\n\", err)\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n\nfunc (c *CmdDomainDel) Synopsis() string ", "output": "{\n\treturn \"Delete and backup a domain.\"\n}"} {"input": "package synapse\n\nimport (\n\t\"fmt\"\n)\n\n\n\ntype Handler interface {\n\n\tServeCall(req Request, res ResponseWriter)\n}\n\n\n\ntype Status int\n\n\n\n\n\n\nconst (\n\tStatusInvalid Status = iota \n\tStatusOK \n\tStatusNotFound \n\tStatusCondition \n\tStatusBadRequest \n\tStatusNotAuthed \n\tStatusServerError \n\tStatusOther \n)\n\n\n\n\n\ntype ResponseError struct {\n\tCode Status\n\tExpl string\n}\n\n\nfunc (e *ResponseError) Error() string {\n\treturn fmt.Sprintf(\"synapse: response error (%s): %s\", e.Code, e.Expl)\n}\n\n\n\n\nfunc (s Status) String() string ", "output": "{\n\tswitch s {\n\tcase StatusOK:\n\t\treturn \"OK\"\n\tcase StatusNotFound:\n\t\treturn \"not found\"\n\tcase StatusCondition:\n\t\treturn \"precondition failed\"\n\tcase StatusBadRequest:\n\t\treturn \"bad request\"\n\tcase StatusNotAuthed:\n\t\treturn \"not authorized\"\n\tcase StatusServerError:\n\t\treturn \"server error\"\n\tcase StatusOther:\n\t\treturn \"other\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"Status(%d)\", s)\n\t}\n}"} {"input": "package config\n\nimport (\n\t\"k8s.io/perf-tests/clusterloader2/api\"\n)\n\n\ntype ClusterLoaderConfig struct {\n\tClusterConfig ClusterConfig\n\tReportDir string\n\tEnableExecService bool\n\tTestScenario api.TestScenario\n\tPrometheusConfig PrometheusConfig\n}\n\n\ntype ClusterConfig struct {\n\tKubeConfigPath string\n\tNodes int\n\tProvider string\n\tEtcdInsecurePort int\n\tMasterIPs []string\n\tMasterInternalIPs []string\n\tMasterName string\n\tKubemarkRootKubeConfigPath string\n}\n\n\ntype PrometheusConfig struct {\n\tEnableServer bool\n\tTearDownServer bool\n\tScrapeEtcd bool\n\tScrapeNodeExporter bool\n\tScrapeKubelets bool\n\tScrapeKubeProxy bool\n}\n\n\n\n\n\n\n\nfunc (c *ClusterConfig) GetMasterInternalIp() string {\n\tif len(c.MasterInternalIPs) > 0 {\n\t\treturn c.MasterInternalIPs[0]\n\t}\n\treturn \"\"\n}\n\nfunc (c *ClusterConfig) GetMasterIp() string ", "output": "{\n\tif len(c.MasterIPs) > 0 {\n\t\treturn c.MasterIPs[0]\n\t}\n\treturn \"\"\n}"} {"input": "package htpasswd\n\nimport (\n\t\"crypto/sha1\"\n\t\"crypto/subtle\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype sshaPassword struct {\n\thashed []byte\n\tsalt []byte\n}\n\n\n\n\n\nfunc RejectSsha(src string) (EncodedPasswd, error) {\n\tif !strings.HasPrefix(src, \"{SSHA}\") {\n\t\treturn nil, nil\n\t}\n\treturn nil, fmt.Errorf(\"ssha passwords are not accepted: %s\", src)\n}\n\nfunc (s *sshaPassword) MatchesPassword(password string) bool {\n\tsha := append([]byte(password), s.salt[:]...)\n\thash := sha1.Sum(sha)\n\treturn subtle.ConstantTimeCompare(hash[:], s.hashed) == 1\n}\n\nfunc AcceptSsha(src string) (EncodedPasswd, error) ", "output": "{\n\tif !strings.HasPrefix(src, \"{SSHA}\") {\n\t\treturn nil, nil\n\t}\n\n\tb64 := strings.TrimPrefix(src, \"{SSHA}\")\n\thashed, err := base64.StdEncoding.DecodeString(b64)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Malformed ssha(%s): %s\", src, err.Error())\n\t}\n\n\tif len(hashed) < sha1.Size {\n\t\treturn nil, fmt.Errorf(\"Malformed ssha(%s): wrong length\", src)\n\t}\n\n\thash := hashed[:sha1.Size]\n\tsalt := hashed[sha1.Size:]\n\treturn &sshaPassword{hash, salt}, nil\n}"} {"input": "package pipeline\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/influxdata/influxdb/influxql\"\n)\n\nconst (\n\tdefaultFlattenDelimiter = \".\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype FlattenNode struct {\n\tchainnode `json:\"-\"`\n\n\tDimensions []string `tick:\"On\" json:\"on\"`\n\n\tDelimiter string `json:\"delimiter\"`\n\n\tTolerance time.Duration `json:\"tolerance\"`\n\n\tDropOriginalFieldNameFlag bool `tick:\"DropOriginalFieldName\" json:\"dropOriginalFieldName\"`\n}\n\nfunc newFlattenNode(e EdgeType) *FlattenNode {\n\tf := &FlattenNode{\n\t\tchainnode: newBasicChainNode(\"flatten\", e, e),\n\t\tDelimiter: defaultFlattenDelimiter,\n\t}\n\treturn f\n}\n\n\nfunc (n *FlattenNode) MarshalJSON() ([]byte, error) {\n\ttype Alias FlattenNode\n\tvar raw = &struct {\n\t\tTypeOf\n\t\t*Alias\n\t\tTolerance string `json:\"tolerance\"`\n\t}{\n\t\tTypeOf: TypeOf{\n\t\t\tType: \"flatten\",\n\t\t\tID: n.ID(),\n\t\t},\n\t\tAlias: (*Alias)(n),\n\t\tTolerance: influxql.FormatDuration(n.Tolerance),\n\t}\n\treturn json.Marshal(raw)\n}\n\n\n\n\n\n\nfunc (f *FlattenNode) On(dims ...string) *FlattenNode {\n\tf.Dimensions = dims\n\treturn f\n}\n\n\n\n\nfunc (f *FlattenNode) DropOriginalFieldName(drop ...bool) *FlattenNode {\n\tif len(drop) == 1 {\n\t\tf.DropOriginalFieldNameFlag = drop[0]\n\t} else {\n\t\tf.DropOriginalFieldNameFlag = true\n\t}\n\treturn f\n}\n\nfunc (n *FlattenNode) UnmarshalJSON(data []byte) error ", "output": "{\n\ttype Alias FlattenNode\n\tvar raw = &struct {\n\t\tTypeOf\n\t\t*Alias\n\t\tTolerance string `json:\"tolerance\"`\n\t}{\n\t\tAlias: (*Alias)(n),\n\t}\n\terr := json.Unmarshal(data, raw)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif raw.Type != \"flatten\" {\n\t\treturn fmt.Errorf(\"error unmarshaling node %d of type %s as FlattenNode\", raw.ID, raw.Type)\n\t}\n\tn.Tolerance, err = influxql.ParseDuration(raw.Tolerance)\n\tif err != nil {\n\t\treturn err\n\t}\n\tn.setID(raw.ID)\n\treturn nil\n}"} {"input": "package pointer\n\nimport \"time\"\n\nfunc DefaultBool(value *bool, defaultValue bool) *bool {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultDuration(value *time.Duration, defaultValue time.Duration) *time.Duration {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultFloat64(value *float64, defaultValue float64) *float64 {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultInt(value *int, defaultValue int) *int {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\n\n\nfunc DefaultStringArray(value *[]string, defaultValue []string) *[]string {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultTime(value *time.Time, defaultValue time.Time) *time.Time {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultString(value *string, defaultValue string) *string ", "output": "{\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}"} {"input": "package storage\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\n\t\"gopkg.in/mgo.v2\"\n)\n\nvar pointerMap = map[string][2048]byte{}\n\nfunc Open(addr, dbname string) (storage *Storage, err error) {\n\tsessionLock.RLock()\n\tif sessions[addr] == nil {\n\t\tsessionLock.RUnlock()\n\t\tsessionLock.Lock()\n\t\tif sessions[addr] == nil {\n\t\t\tsessions[addr], err = open(addr)\n\t\t}\n\t\tsessionLock.Unlock()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tsessionLock.RUnlock()\n\t}\n\tcloned := sessions[addr].Clone()\n\tpointerAddr := fmt.Sprintf(\"%p\", cloned)\n\tbuf := pointerMap[pointerAddr]\n\truntime.Stack(buf[:], false)\n\tpointerMap[pointerAddr] = buf\n\truntime.SetFinalizer(cloned, sessionFinalizer)\n\tstorage = &Storage{\n\t\tsession: cloned,\n\t\tdbname: dbname,\n\t}\n\treturn\n}\n\n\n\nfunc sessionFinalizer(session *mgo.Session) ", "output": "{\n\tptr := fmt.Sprintf(\"%p\", session)\n\tdefer func() {\n\t\trecover()\n\t\tdelete(pointerMap, ptr)\n\t}()\n\tsession.DB(\"tsuru\").C(\"mycoll\").Find(nil).Count()\n\tbuf := pointerMap[ptr]\n\tfmt.Printf(\"\\n********** LEAK **********\\n%s\\n********** ENDLEAK **********\\n\", string(buf[:]))\n\tsession.Close()\n}"} {"input": "package common\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/hashicorp/packer/helper/multistep\"\n\t\"github.com/hashicorp/packer/packer\"\n)\n\n\n\ntype StepSuppressMessages struct{}\n\n\n\nfunc (StepSuppressMessages) Cleanup(multistep.StateBag) {}\n\nfunc (StepSuppressMessages) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction ", "output": "{\n\tdriver := state.Get(\"driver\").(Driver)\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\tlog.Println(\"Suppressing annoying messages in VirtualBox\")\n\tif err := driver.SuppressMessages(); err != nil {\n\t\terr := fmt.Errorf(\"Error configuring VirtualBox to suppress messages: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\treturn multistep.ActionContinue\n}"} {"input": "package lsp\n\nimport \"fmt\"\n\n\nconst (\n\tDefaultEpochLimit = 5\n\tDefaultEpochMillis = 2000\n\tDefaultWindowSize = 1\n)\n\n\ntype Params struct {\n\tEpochLimit int\n\n\tEpochMillis int\n\n\tWindowSize int\n}\n\n\n\n\n\n\n\n\nfunc (p *Params) String() string {\n\treturn fmt.Sprintf(\"[EpochLimit: %d, EpochMillis: %d, WindowSize: %d]\",\n\t\tp.EpochLimit, p.EpochMillis, p.WindowSize)\n}\n\nfunc NewParams() *Params ", "output": "{\n\treturn &Params{\n\t\tEpochLimit: DefaultEpochLimit,\n\t\tEpochMillis: DefaultEpochMillis,\n\t\tWindowSize: DefaultWindowSize,\n\t}\n}"} {"input": "package amber\n\nimport (\n\t\"errors\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/kotfalya/amber/utils\"\n)\n\ntype DB struct {\n\tconfig *Config\n\tname string\n\trootPage *Page\n\treq chan *Req\n\tstop chan struct{}\n}\n\n\n\nfunc (db *DB) start() {\n\tsem := utils.NewSemaphore(10)\n\tfor {\n\t\tselect {\n\t\tcase req := <-db.req:\n\t\t\treq.master = db.name\n\t\t\tsem.Acquire()\n\t\t\tgo func(req *Req) {\n\t\t\t\tdefer sem.Release()\n\t\t\t\tswitch req.handler {\n\t\t\t\tcase RequestDBHandler:\n\t\t\t\t\tDBHandle(db, req)\n\t\t\t\tcase RequestKeyHandler:\n\t\t\t\t\tKeyHandler(db, req)\n\t\t\t\tcase RequestNetHandler:\n\t\t\t\t\tNetHandler(db, req)\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(errors.New(ErrInvalidReqHandler))\n\t\t\t\t}\n\n\t\t\t}(req)\n\n\t\tcase <-db.stop:\n\t\t\tglog.V(1).Infoln(\"db:stop\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (db *DB) load(keyName string, level int) (Key, error) {\n\tkey, err := db.rootPage.load(keyName)\n\tif err != nil {\n\t\treturn nil, errors.New(ErrUndefinedKey)\n\t}\n\treturn key, nil\n}\n\nfunc (db *DB) add(keyName string, key Key, level int) (err error) {\n\terr = db.rootPage.add(keyName, key)\n\n\treturn\n}\n\nfunc DBHandle(db *DB, req *Req) {\n\n}\n\nfunc NewDB(name string, config *Config) *DB ", "output": "{\n\tdb := &DB{\n\t\tconfig: config,\n\t\tname: name,\n\t\trootPage: createRootPage(),\n\t\treq: make(chan *Req, 10),\n\t\tstop: make(chan struct{}),\n\t}\n\tgo db.start()\n\n\treturn db\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", mainHandle)\n\tif err := http.ListenAndServe(\":8080\", nil); err != nil {\n\t\tlog.Fatal(\"Listen and serve:\", err)\n\t}\n}\n\n\ntype reply struct {\n\tLanguage string `json:\"language\"`\n\tOs string `json:\"software\"`\n\tIP string `json:\"ipaddress\"`\n}\n\n\nfunc mainHandle(w http.ResponseWriter, r *http.Request) {\n\theader := r.Header\n\th := fmt.Sprintf(\"%v\", header)\n\taddr := r.RemoteAddr\n\n\tos := parseOs(h)\n\tl := parseLang(h)\n\tip := parseIP(addr)\n\n\treply := reply{Language: l, Os: os, IP: ip}\n\n\tout, err := json.MarshalIndent(reply, \"\", \" \")\n\tif err != nil {\n\t\tfmt.Println(\"Cannot produce json\", err)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"%s\\n\", out)\n}\n\n\n\n\n\n\nfunc parseIP(addr string) string {\n\tip := strings.Split(addr, \":\")[0]\n\treturn ip\n}\n\n\nfunc parseLang(h string) string {\n\ttag := strings.Index(h, \"Accept-Language:\")\n\tstart := strings.Index(h[tag:], \"[\")\n\tstart += tag + 1\n\n\tend := strings.Index(h[start:], \"]\")\n\tend += start\n\n\tl := h[start:end]\n\n\treturn strings.Split(l, \";\")[0]\n}\n\n\n\n\nfunc parseOs(h string) string ", "output": "{\n\ttag := strings.Index(h, \"User-Agent\")\n\tstart := strings.Index(h[tag:], \"(\")\n\tstart += tag + 1 \n\n\tend := strings.Index(h[start:], \")\")\n\tend += start\n\n\treturn h[start:end]\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/rpc\"\n)\n\n\nfunc defaultHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"

Hello %s!

\", r.URL.Path[1:])\n}\n\ntype Args struct {\n\tA, B int\n}\n\n\ntype Arith int\n\n\n\n\nfunc (t *Arith) Add(args *Args, reply *int) error {\n\t*reply = args.A + args.B\n\treturn nil\n}\n\nfunc main() {\n\tarith := new(Arith)\n\terr := rpc.Register(arith)\n\tif err != nil {\n\t\tlog.Fatal(\"Service Error: %s\", err)\n\t}\n\trpc.HandleHTTP()\n\n\tl, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", 57439))\n\n\tif err != nil {\n\t\tlog.Fatal(\"TCP Error: %s\", err)\n\t}\n\tlog.Println(\"ok\")\n\thttp.Serve(l, nil)\n}\n\nfunc (t *Arith) Multiply(args *Args, reply *int) error ", "output": "{\n\t*reply = args.A * args.B\n\treturn nil\n}"} {"input": "package token\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n)\n\n\nfunc PrettyPrintTree(w io.Writer, root Token) {\n\tprettyPrintTreeRek(w, root, 0)\n}\n\nfunc prettyPrintTreeRek(w io.Writer, tok Token, level int) {\n\t_, _ = fmt.Fprintf(w, \"%s(%p)%#v %d Permutations\\n\", strings.Repeat(\"\\t\", level), tok, tok, tok.Permutations())\n\n\tswitch t := tok.(type) {\n\tcase ForwardToken:\n\t\tif v := t.Get(); v != nil {\n\t\t\tprettyPrintTreeRek(w, v, level+1)\n\t\t}\n\tcase ListToken:\n\t\tfor i := 0; i < t.Len(); i++ {\n\t\t\tc, _ := t.Get(i)\n\n\t\t\tprettyPrintTreeRek(w, c, level+1)\n\t\t}\n\t}\n}\n\n\nfunc PrettyPrintInternalTree(w io.Writer, root Token) {\n\tprettyPrintInternalTreeRek(w, root, 0)\n}\n\n\n\nfunc prettyPrintInternalTreeRek(w io.Writer, tok Token, level int) ", "output": "{\n\t_, _ = fmt.Fprintf(w, \"%s(%p)%#v\\n\", strings.Repeat(\"\\t\", level), tok, tok)\n\n\tswitch t := tok.(type) {\n\tcase ForwardToken:\n\t\tif v := t.InternalGet(); v != nil {\n\t\t\tprettyPrintInternalTreeRek(w, v, level+1)\n\t\t}\n\tcase ListToken:\n\t\tfor i := 0; i < t.InternalLen(); i++ {\n\t\t\tc, _ := t.InternalGet(i)\n\n\t\t\tprettyPrintInternalTreeRek(w, c, level+1)\n\t\t}\n\t}\n}"} {"input": "package arrayUtility\n\n\n\nfunc Contain(needle string, haystack []string) bool {\n\tfor _, v := range haystack {\n\t\tif v == needle {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc RemoveDuplicatesUnordered(elements []string) []string ", "output": "{\n\tencountered := map[string]bool{}\n\n\tfor v := range elements {\n\t\tencountered[elements[v]] = true\n\t}\n\n\tresult := []string{}\n\tfor key := range encountered {\n\t\tresult = append(result, key)\n\t}\n\treturn result\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\trest \"github.com/Kissaki/rest2go\"\n\t\"log\"\n\t\"net/http\"\n)\n\nvar wdmap = map[string]string{\n\t\"Mo\": \"Monday\",\n\t\"Tu\": \"Tuesday\",\n\t\"We\": \"Wednesday\",\n\t\"Th\": \"Thursday\",\n\t\"Fr\": \"Friday\",\n\t\"Sa\": \"Saturday\",\n\t\"Su\": \"Sunday\",\n}\n\ntype Weekdays struct {\n\twd map[string]string\n}\n\nfunc (wd *Weekdays) Index(resp http.ResponseWriter) {\n\tfor i, v := range wd.wd {\n\t\tfmt.Fprintf(resp, \"%s: %s
\\n\", i, v)\n\t}\n}\n\n\nfunc main() {\n\tlog.Println(\"Starting Server\")\n\taddress := \"127.0.0.1:3000\"\n\n\tvar wd = new(Weekdays)\n\twd.wd = wdmap\n\trest.Resource(\"/wd/\", wd)\n\n\tif err := http.ListenAndServe(address, nil); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc (wd *Weekdays) Find(resp http.ResponseWriter, id string) ", "output": "{\n\tif full, ok := wd.wd[id]; ok {\n\t\tfmt.Fprintf(resp, full)\n\t}\n}"} {"input": "package v20170701\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n)\n\n\n\nfunc TestAgentPoolProfile(t *testing.T) {\n\tAgentPoolProfileText := \"{\\\"count\\\" : 0}\"\n\tap := &AgentPoolProfile{}\n\tif e := json.Unmarshal([]byte(AgentPoolProfileText), ap); e != nil {\n\t\tt.Fatalf(\"unexpectedly detected unmarshal failure for AgentPoolProfile, %+v\", e)\n\t}\n\n\tif ap.Count != 1 {\n\t\tt.Fatalf(\"unexpectedly detected AgentPoolProfile.Count != 1 after unmarshal\")\n\t}\n\n\tif ap.OSType != Linux {\n\t\tt.Fatalf(\"unexpectedly detected AgentPoolProfile.OSType != Linux after unmarshal\")\n\t}\n}\n\nfunc TestMasterProfile(t *testing.T) ", "output": "{\n\tMasterProfileText := \"{\\\"count\\\" : 0}\"\n\tmp := &MasterProfile{}\n\tif e := json.Unmarshal([]byte(MasterProfileText), mp); e != nil {\n\t\tt.Fatalf(\"unexpectedly detected unmarshal failure for MasterProfile, %+v\", e)\n\t}\n\n\tif mp.Count != 1 {\n\t\tt.Fatalf(\"unexpectedly detected MasterProfile.Count != 1 after unmarshal\")\n\t}\n\n\tif mp.FirstConsecutiveStaticIP != \"10.240.255.5\" {\n\t\tt.Fatalf(\"unexpectedly detected MasterProfile.FirstConsecutiveStaticIP != 10.240.255.5 after unmarshal\")\n\t}\n}"} {"input": "package brdgme\n\n\ntype CommandResponse struct {\n\tLogs []Log\n\tCanUndo bool\n\tRemaining string\n}\n\ntype Status struct {\n\tActive *StatusActive `json:\",omitempty\"`\n\tFinished *StatusFinished `json:\",omitempty\"`\n}\n\ntype StatusActive struct {\n\tWhoseTurn []int `json:\"whose_turn\"`\n\tEliminated []int `json:\"eliminated\"`\n}\n\nfunc (sa StatusActive) ToStatus() Status {\n\treturn Status{\n\t\tActive: &sa,\n\t}\n}\n\ntype StatusFinished struct {\n\tPlacings []int `json:\"placings\"`\n\tStats []interface{} `json:\"stats\"`\n}\n\n\n\n\ntype Gamer interface {\n\tNew(players int) ([]Log, error)\n\tPubState() interface{}\n\tPlayerState(player int) interface{}\n\tCommand(\n\t\tplayer int,\n\t\tinput string,\n\t\tplayers []string,\n\t) (CommandResponse, error)\n\tStatus() Status\n\tCommandSpec(player int) *Spec\n\tPlayerCount() int\n\tPlayerCounts() []int\n\tPubRender() string\n\tPlayerRender(player int) string\n\tPoints() []float32\n}\n\nfunc (sf StatusFinished) ToStatus() Status ", "output": "{\n\treturn Status{\n\t\tFinished: &sf,\n\t}\n}"} {"input": "package iso20022\n\n\n\ntype RestrictedFINActiveOrHistoricCurrencyAnd13DecimalAmount struct {\n\tValue string `xml:\",chardata\"`\n\tCurrency string `xml:\"Ccy,attr\"`\n}\n\n\n\nfunc NewRestrictedFINActiveOrHistoricCurrencyAnd13DecimalAmount(value, currency string) *RestrictedFINActiveOrHistoricCurrencyAnd13DecimalAmount ", "output": "{\n\treturn &RestrictedFINActiveOrHistoricCurrencyAnd13DecimalAmount{Value: value, Currency: currency}\n}"} {"input": "package v1\n\n\n\ntype EnvVarApplyConfiguration struct {\n\tName *string `json:\"name,omitempty\"`\n\tValue *string `json:\"value,omitempty\"`\n\tValueFrom *EnvVarSourceApplyConfiguration `json:\"valueFrom,omitempty\"`\n}\n\n\n\nfunc EnvVar() *EnvVarApplyConfiguration {\n\treturn &EnvVarApplyConfiguration{}\n}\n\n\n\n\nfunc (b *EnvVarApplyConfiguration) WithName(value string) *EnvVarApplyConfiguration {\n\tb.Name = &value\n\treturn b\n}\n\n\n\n\n\n\n\n\n\nfunc (b *EnvVarApplyConfiguration) WithValueFrom(value *EnvVarSourceApplyConfiguration) *EnvVarApplyConfiguration {\n\tb.ValueFrom = value\n\treturn b\n}\n\nfunc (b *EnvVarApplyConfiguration) WithValue(value string) *EnvVarApplyConfiguration ", "output": "{\n\tb.Value = &value\n\treturn b\n}"} {"input": "package cork\n\nimport (\n\t\"math\"\n)\n\n\n\n\n\nfunc (w *Writer) EncodeCorker(v Corker) {\n\tenc, err := v.MarshalCORK()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsze := len(enc)\n\tswitch {\n\tcase sze <= fixedExt:\n\t\tw.writeOne(cFixExt + byte(sze))\n\tcase sze <= math.MaxUint8:\n\t\tw.writeOne(cExt8)\n\t\tw.writeLen8(uint8(sze))\n\tcase sze <= math.MaxUint16:\n\t\tw.writeOne(cExt16)\n\t\tw.writeLen16(uint16(sze))\n\tcase sze <= math.MaxUint32:\n\t\tw.writeOne(cExt32)\n\t\tw.writeLen32(uint32(sze))\n\tcase sze <= math.MaxInt64:\n\t\tw.writeOne(cExt64)\n\t\tw.writeLen64(uint64(sze))\n\t}\n\tw.writeOne(v.ExtendCORK())\n\tw.writeMany(enc)\n}\n\nfunc (w *Writer) EncodeSelfer(v Selfer) ", "output": "{\n\tw.writeOne(cSlf)\n\tw.writeOne(v.ExtendCORK())\n\tv.MarshalCORK(w)\n}"} {"input": "package iso20022\n\n\ntype SecuritiesCertificate5 struct {\n\n\tNumber *RestrictedFINXMax30Text `xml:\"Nb\"`\n\n\tIssuer *Max4AlphaNumericText `xml:\"Issr,omitempty\"`\n\n\tSchemeName *Max4AlphaNumericText `xml:\"SchmeNm,omitempty\"`\n}\n\n\n\nfunc (s *SecuritiesCertificate5) SetIssuer(value string) {\n\ts.Issuer = (*Max4AlphaNumericText)(&value)\n}\n\nfunc (s *SecuritiesCertificate5) SetSchemeName(value string) {\n\ts.SchemeName = (*Max4AlphaNumericText)(&value)\n}\n\nfunc (s *SecuritiesCertificate5) SetNumber(value string) ", "output": "{\n\ts.Number = (*RestrictedFINXMax30Text)(&value)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"appengine\"\n\t\"appengine/datastore\"\n)\n\n\n\ntype regexStats struct {\n\tExprLength int `datastore:\",noindex\"`\n\tTextLength int `datastore:\",noindex\"`\n\tRanAt time.Time `datastore:\",noindex\"`\n\tDuration time.Duration `datastore:\",noindex\"`\n}\n\nfunc recordStats(ctx appengine.Context, expr string, text string, duration time.Duration) {\n\tdefer func() {\n\t\tif rec := recover(); rec != nil {\n\t\t\tstack := make([]byte, 32768)\n\t\t\truntime.Stack(stack, false)\n\t\t\tctx.Errorf(\"Recovered from panic: %v -- %s\", rec, stack)\n\t\t}\n\t}()\n\tstats := ®exStats{\n\t\tExprLength: len(expr),\n\t\tTextLength: len(text),\n\t\tRanAt: time.Now(),\n\t\tDuration: duration,\n\t}\n\t_, err := datastore.Put(ctx, datastore.NewIncompleteKey(ctx, \"regex_stats\", nil), stats)\n\tif err != nil {\n\t\tctx.Errorf(\"Error writing stats: %v\", err)\n\t}\n\n}\n\nfunc EvalRegex(ctx appengine.Context, input *MatchInput) (*MatchResultResponse, error) ", "output": "{\n\tstartRegex := time.Now()\n\n\tr, err := regexp.Compile(input.Expr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Invalid RegExp: %s -- %v\", input.Expr, err)\n\t}\n\n\tmatches := r.FindAllStringSubmatch(input.Text, input.NumMatches)\n\tresult := &MatchResultResponse{}\n\tif len(matches) > 0 {\n\t\tresult.Matches = matches\n\t\tresult.GroupsName = r.SubexpNames()[1:]\n\t}\n\n\tgo recordStats(ctx, input.Expr, input.Text, time.Since(startRegex))\n\n\treturn result, nil\n}"} {"input": "package common\n\nimport \"math/big\"\n\ntype _N_ [_S_]byte\n\nfunc BytesTo_N_(b []byte) _N_ {\n\tvar h _N_\n\th.SetBytes(b)\n\treturn h\n}\nfunc StringTo_N_(s string) _N_ { return BytesTo_N_([]byte(s)) }\nfunc BigTo_N_(b *big.Int) _N_ { return BytesTo_N_(b.Bytes()) }\nfunc HexTo_N_(s string) _N_ { return BytesTo_N_(FromHex(s)) }\n\n\n\n\nfunc (h _N_) Str() string { return string(h[:]) }\nfunc (h _N_) Bytes() []byte { return h[:] }\nfunc (h _N_) Big() *big.Int { return Bytes2Big(h[:]) }\n\n\n\nfunc (h *_N_) SetBytes(b []byte) {\n\tif len(b) > len(h) {\n\t\tb = b[len(b)-_S_:]\n\t}\n\n\tfor i := len(b) - 1; i >= 0; i-- {\n\t\th[_S_-len(b)+i] = b[i]\n\t}\n}\n\n\nfunc (h *_N_) SetString(s string) { h.SetBytes([]byte(s)) }\n\n\nfunc (h *_N_) Set(other _N_) {\n\tfor i, v := range other {\n\t\th[i] = v\n\t}\n}\n\nfunc (h _N_) Hex() string ", "output": "{ return \"0x\" + Bytes2Hex(h[:]) }"} {"input": "package core\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\n\n\nfunc PodContainerKey(namespace, podName, containerName string) string {\n\treturn fmt.Sprintf(\"namespace:%s/pod:%s/container:%s\", namespace, podName, containerName)\n}\n\nfunc PodKey(namespace, podName string) string {\n\treturn fmt.Sprintf(\"namespace:%s/pod:%s\", namespace, podName)\n}\n\nfunc NamespaceKey(namespace string) string {\n\treturn fmt.Sprintf(\"namespace:%s\", namespace)\n}\n\nfunc NodeKey(node string) string {\n\treturn fmt.Sprintf(\"node:%s\", node)\n}\n\nfunc NodeContainerKey(node, container string) string {\n\treturn fmt.Sprintf(\"node:%s/container:%s\", node, container)\n}\n\n\n\nfunc ClusterKey() string ", "output": "{\n\treturn \"cluster\"\n}"} {"input": "package stats\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc BenchmarkSumSmallFloatSlice(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tSum(makeFloatSlice(5))\n\t}\n}\n\nfunc BenchmarkSumLargeFloatSlice(b *testing.B) {\n\tlf := makeFloatSlice(100000)\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tSum(lf)\n\t}\n}\n\nfunc TestSum(t *testing.T) ", "output": "{\n\tfor _, c := range []struct {\n\t\tin []float64\n\t\tout float64\n\t}{\n\t\t{[]float64{1, 2, 3}, 6},\n\t\t{[]float64{1.0, 1.1, 1.2, 2.2}, 5.5},\n\t\t{[]float64{1, -1, 2, -3}, -1},\n\t} {\n\t\tgot, err := Sum(c.in)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Returned an error\")\n\t\t}\n\t\tif !reflect.DeepEqual(c.out, got) {\n\t\t\tt.Errorf(\"Sum(%.1f) => %.1f != %.1f\", c.in, got, c.out)\n\t\t}\n\t}\n\t_, err := Sum([]float64{})\n\tif err == nil {\n\t\tt.Errorf(\"Empty slice should have returned an error\")\n\t}\n}"} {"input": "package credential\n\nimport (\n\t\"pharmer.dev/cloud/apis\"\n\tv1 \"pharmer.dev/cloud/apis/cloud/v1\"\n\n\t\"github.com/spf13/pflag\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\ntype Linode struct {\n\tCommonSpec\n\n\ttoken string\n}\n\nfunc (c Linode) APIToken() string { return get(c.Data, LinodeAPIToken, c.token) }\n\nfunc (c *Linode) LoadFromEnv() {\n\tc.CommonSpec.LoadFromEnv(c.Format())\n}\n\nfunc (c Linode) IsValid() (bool, error) {\n\treturn c.CommonSpec.IsValid(c.Format())\n}\n\nfunc (c *Linode) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(&c.token, apis.Linode+\".\"+LinodeAPIToken, c.token, \"Linode api token\")\n}\n\nfunc (_ Linode) RequiredFlags() []string {\n\treturn []string{apis.Linode + \".\" + LinodeAPIToken}\n}\n\n\n\nfunc (_ Linode) Format() v1.CredentialFormat ", "output": "{\n\treturn v1.CredentialFormat{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: apis.Linode,\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tapis.KeyClusterCredential: \"\",\n\t\t\t\tapis.KeyDNSCredential: \"\",\n\t\t\t},\n\t\t},\n\t\tSpec: v1.CredentialFormatSpec{\n\t\t\tProvider: apis.Linode,\n\t\t\tDisplayFormat: \"field\",\n\t\t\tFields: []v1.CredentialField{\n\t\t\t\t{\n\t\t\t\t\tEnvconfig: \"LINODE_TOKEN\",\n\t\t\t\t\tForm: \"linode_token\",\n\t\t\t\t\tJSON: LinodeAPIToken,\n\t\t\t\t\tLabel: \"Token\",\n\t\t\t\t\tInput: \"password\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package cvss\n\nimport \"testing\"\n\n\nfunc TestCalculateBaseScore(t *testing.T) {\n\tcvssString := `AV:N/AC:L/Au:N/C:N/I:N/A:C`\n\tscore, err := CalculateBaseScore(cvssString, 3)\n\tif err == nil {\n\t\tt.Error(\"Version 3 should not be supported yet\")\n\t}\n\tscore, err = CalculateBaseScore(cvssString, 2)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif score != 7.8 {\n\t\tt.Errorf(\"Expected 7.8 BaseScore, got %f\", score)\n\t}\n\n}\n\nfunc TestBaseParse(t *testing.T) ", "output": "{\n\tm := BaseMetric{AccessVector: 1, AccessComplexity: 0.71, Authentication: 0.704, Confidentiality: 0.0, Integrity: 0.0, Avaliability: 0.66}\n\tcvssString := `AV:N/AC:L/Au:N/C:N/I:N/A:C`\n\n\tmetric, err := ParseBaseMetric(cvssString)\n\tif err != nil {\n\t\tt.Errorf(\"Could not parse %s: %s\", cvssString, err)\n\t}\n\tif metric != m {\n\t\tt.Errorf(\"Could not parse %s: Expected %+v, got %+v\", cvssString, m, metric)\n\t}\n}"} {"input": "package common\n\nimport (\n\t\"github.com/golang/protobuf/proto\"\n\t\"github.com/hyperledger/fabric/core/util\"\n)\n\n\n\nfunc (b *BlockData) Hash() []byte {\n\tdata, err := proto.Marshal(b) \n\tif err != nil {\n\t\tpanic(\"This should never fail and is generally irrecoverable\")\n\t}\n\n\treturn util.ComputeCryptoHash(data)\n}\n\nfunc (b *BlockHeader) Hash() []byte ", "output": "{\n\tdata, err := proto.Marshal(b) \n\tif err != nil {\n\t\tpanic(\"This should never fail and is generally irrecoverable\")\n\t}\n\n\treturn util.ComputeCryptoHash(data)\n}"} {"input": "package factory\n\nimport (\n\t\"encoding/hex\"\n\n\t\"github.com/hyperledger/fabric/bccsp\"\n\t\"github.com/hyperledger/fabric/bccsp/pkcs11\"\n\t\"github.com/hyperledger/fabric/bccsp/sw\"\n\t\"github.com/pkg/errors\"\n)\n\nconst (\n\tPKCS11BasedFactoryName = \"PKCS11\"\n)\n\n\ntype PKCS11Factory struct{}\n\n\nfunc (f *PKCS11Factory) Name() string {\n\treturn PKCS11BasedFactoryName\n}\n\n\n\n\nfunc skiMapper(p11Opts pkcs11.PKCS11Opts) func([]byte) []byte {\n\tkeyMap := map[string]string{}\n\tfor _, k := range p11Opts.KeyIDs {\n\t\tkeyMap[k.SKI] = k.ID\n\t}\n\n\treturn func(ski []byte) []byte {\n\t\tkeyID := hex.EncodeToString(ski)\n\t\tif id, ok := keyMap[keyID]; ok {\n\t\t\treturn []byte(id)\n\t\t}\n\t\tif p11Opts.AltID != \"\" {\n\t\t\treturn []byte(p11Opts.AltID)\n\t\t}\n\t\treturn ski\n\t}\n}\n\nfunc (f *PKCS11Factory) Get(config *FactoryOpts) (bccsp.BCCSP, error) ", "output": "{\n\tif config == nil || config.PKCS11 == nil {\n\t\treturn nil, errors.New(\"Invalid config. It must not be nil.\")\n\t}\n\n\tp11Opts := *config.PKCS11\n\tks := sw.NewDummyKeyStore()\n\tmapper := skiMapper(p11Opts)\n\n\treturn pkcs11.New(p11Opts, ks, pkcs11.WithKeyMapper(mapper))\n}"} {"input": "package utils\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n\n\t\"github.com/astaxie/beego\"\n)\n\nvar testRandNum int\nvar testRandString string\n\n\nfunc SetTestRandNum(n int) {\n\tif !IsTest() {\n\t\treturn\n\t}\n\n\ttestRandNum = n\n}\n\n\nfunc GetRandNum(n int) int {\n\tif IsTest() {\n\t\treturn testRandNum\n\t}\n\n\trand.Seed(time.Now().UnixNano())\n\n\treturn rand.Intn(n)\n}\n\n\nfunc SetTestRandString(s string) {\n\tif !IsTest() {\n\t\treturn\n\t}\n\n\ttestRandString = s\n}\n\n\n\n\nfunc GetRandString(n int) string ", "output": "{\n\tif IsTest() {\n\t\treturn testRandString\n\t}\n\n\trs2Letters := beego.AppConfig.String(\"randKey\")\n\n\tb := make([]byte, n)\n\tfor i := range b {\n\t\tb[i] = rs2Letters[rand.Intn(len(rs2Letters))]\n\t}\n\n\treturn string(b)\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype CreateBootVolumeRequest struct {\n\n\tCreateBootVolumeDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateBootVolumeRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateBootVolumeRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request CreateBootVolumeRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateBootVolumeResponse struct {\n\n\tRawResponse *http.Response\n\n\tBootVolume `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateBootVolumeResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response CreateBootVolumeResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package mungerutil\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\ntype testLTG struct {\n\tnumber int\n\tlabel string\n\ttime time.Time\n}\n\nfunc (t *testLTG) Number() int { return t.number }\n\n\nfunc TestFirstLabelCache(t *testing.T) {\n\ttimeA := time.Now()\n\ttimeB := timeA.Add(time.Minute)\n\ttable := []struct {\n\t\tobj testLTG\n\t\texpect time.Time\n\t}{\n\t\t{testLTG{1, \"lgtm\", timeA}, timeA},\n\n\t\t{testLTG{2, \"blah\", timeA}, time.Time{}},\n\n\t\t{testLTG{1, \"lgtm\", timeB}, timeA},\n\n\t\t{testLTG{2, \"lgtm\", timeB}, timeB},\n\t}\n\n\tcache := NewLabelTimeCache(\"lgtm\")\n\tfor i, tt := range table {\n\t\tgot, ok := cache.FirstLabelTime(&tt.obj)\n\t\tif e := (tt.expect != time.Time{}); e != ok {\n\t\t\tt.Errorf(\"%v: Expected %v, got %v\", i, e, ok)\n\t\t\tcontinue\n\t\t}\n\t\tif got != tt.expect {\n\t\t\tt.Errorf(\"%v: Expected %v, got %v\", i, tt.expect, got)\n\t\t}\n\t}\n}\n\nfunc (t *testLTG) FirstLabelTime(label string) *time.Time ", "output": "{\n\tif label == t.label {\n\t\treturn &t.time\n\t}\n\treturn nil\n}"} {"input": "package mediaconvert\n\nimport (\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/client\"\n\t\"github.com/aws/aws-sdk-go/aws/client/metadata\"\n\t\"github.com/aws/aws-sdk-go/aws/request\"\n\t\"github.com/aws/aws-sdk-go/aws/signer/v4\"\n\t\"github.com/aws/aws-sdk-go/private/protocol/restjson\"\n)\n\n\n\n\n\n\n\ntype MediaConvert struct {\n\t*client.Client\n}\n\n\nvar initClient func(*client.Client)\n\n\nvar initRequest func(*request.Request)\n\n\nconst (\n\tServiceName = \"mediaconvert\" \n\tEndpointsID = ServiceName \n\tServiceID = \"MediaConvert\" \n)\n\n\n\n\n\n\n\n\n\n\n\nfunc New(p client.ConfigProvider, cfgs ...*aws.Config) *MediaConvert {\n\tc := p.ClientConfig(EndpointsID, cfgs...)\n\tif c.SigningNameDerived || len(c.SigningName) == 0 {\n\t\tc.SigningName = \"mediaconvert\"\n\t}\n\treturn newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName)\n}\n\n\n\n\n\n\nfunc (c *MediaConvert) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\tif initRequest != nil {\n\t\tinitRequest(req)\n\t}\n\n\treturn req\n}\n\nfunc newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *MediaConvert ", "output": "{\n\tsvc := &MediaConvert{\n\t\tClient: client.New(\n\t\t\tcfg,\n\t\t\tmetadata.ClientInfo{\n\t\t\t\tServiceName: ServiceName,\n\t\t\t\tServiceID: ServiceID,\n\t\t\t\tSigningName: signingName,\n\t\t\t\tSigningRegion: signingRegion,\n\t\t\t\tEndpoint: endpoint,\n\t\t\t\tAPIVersion: \"2017-08-29\",\n\t\t\t\tJSONVersion: \"1.1\",\n\t\t\t},\n\t\t\thandlers,\n\t\t),\n\t}\n\n\tsvc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)\n\tsvc.Handlers.Build.PushBackNamed(restjson.BuildHandler)\n\tsvc.Handlers.Unmarshal.PushBackNamed(restjson.UnmarshalHandler)\n\tsvc.Handlers.UnmarshalMeta.PushBackNamed(restjson.UnmarshalMetaHandler)\n\tsvc.Handlers.UnmarshalError.PushBackNamed(restjson.UnmarshalErrorHandler)\n\n\tif initClient != nil {\n\t\tinitClient(svc.Client)\n\t}\n\n\treturn svc\n}"} {"input": "package core\n\nimport (\n\t\"database/sql\"\n\t\"strconv\"\n)\n\n\ntype Migration struct {\n\tIdentifier int64\n\tName string\n\tUp func(tx *Tx)\n\tDown func(tx *Tx)\n}\n\n\nfunc (m *Migration) GetID() string {\n\treturn strconv.FormatInt(m.Identifier, 10)\n}\n\n\n\n\n\n\ntype ByIdentifier []Migration\n\nfunc (a ByIdentifier) Len() int { return len(a) }\nfunc (a ByIdentifier) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a ByIdentifier) Less(i, j int) bool { return a[i].Identifier < a[j].Identifier }\n\nfunc (m *Migration) Pending(db *sql.DB) bool ", "output": "{\n\trows, _ := db.Query(\"Select * from \" + MigrationsTable + \" WHERE identifier =\" + m.GetID())\n\tdefer rows.Close()\n\tcount := 0\n\n\tfor rows.Next() {\n\t\tcount++\n\t}\n\n\treturn count == 0\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/engine\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\n\n\n\ntype CmdGetAttributes struct {\n\tname string\n\trpcMethod string\n\trpcParams *utils.TenantID\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetAttributes) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdGetAttributes) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdGetAttributes) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &utils.TenantID{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetAttributes) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetAttributes) RpcResult() interface{} {\n\tvar atr engine.AttributeProfile\n\treturn &atr\n}\n\nfunc init() ", "output": "{\n\tc := &CmdGetAttributes{\n\t\tname: \"attributes\",\n\t\trpcMethod: utils.APIerSv1GetAttributeProfile,\n\t\trpcParams: &utils.TenantID{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}"} {"input": "package v1beta3\n\nimport (\n\t\"testing\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/conversion\"\n)\n\n\n\nfunc TestV1Beta3toAPIVolumeSourceConversion(t *testing.T) {\n\tc := conversion.NewConverter()\n\tc.Debug = t\n\n\tif err := c.RegisterConversionFunc(convert_v1beta3_VolumeSource_To_api_VolumeSource); err != nil {\n\t\tt.Fatalf(\"unexpected error %v\", err)\n\t}\n\n\tin := VolumeSource{\n\t\tMetadata: &MetadataVolumeSource{\n\t\t\tItems: []MetadataFile{\n\t\t\t\t{\n\t\t\t\t\tName: \"./test/v1beta3-to-api/conversion\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tout := api.VolumeSource{}\n\n\tif err := c.Convert(&in, &out, 0, nil); err != nil {\n\t\tt.Fatalf(\"unexpected error %v\", err)\n\t}\n\tif e, a := in.Metadata.Items[0].Name, out.DownwardAPI.Items[0].Path; e != a {\n\t\tt.Errorf(\"expected %v, got %v\", e, a)\n\t}\n}\n\nfunc TestAPItoV1Beta3VolumeSourceConversion(t *testing.T) ", "output": "{\n\tc := conversion.NewConverter()\n\tc.Debug = t\n\n\tif err := c.RegisterConversionFunc(convert_api_VolumeSource_To_v1beta3_VolumeSource); err != nil {\n\t\tt.Fatalf(\"unexpected error %v\", err)\n\t}\n\n\tin := api.VolumeSource{\n\t\tDownwardAPI: &api.DownwardAPIVolumeSource{\n\t\t\tItems: []api.DownwardAPIVolumeFile{\n\t\t\t\t{\n\t\t\t\t\tPath: \"./test/api-to-v1beta3/conversion\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tout := VolumeSource{}\n\n\tif err := c.Convert(&in, &out, 0, nil); err != nil {\n\t\tt.Fatalf(\"unexpected error %v\", err)\n\t}\n\tif e, a := in.DownwardAPI.Items[0].Path, out.Metadata.Items[0].Name; e != a {\n\t\tt.Errorf(\"expected %v, got %v\", e, a)\n\t}\n}"} {"input": "package arm\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/mitchellh/multistep\"\n\t\"github.com/mitchellh/packer/builder/azure/common/constants\"\n\t\"github.com/mitchellh/packer/packer\"\n)\n\ntype StepPowerOffCompute struct {\n\tclient *AzureClient\n\tpowerOff func(resourceGroupName string, computeName string) error\n\tsay func(message string)\n\terror func(e error)\n}\n\nfunc NewStepPowerOffCompute(client *AzureClient, ui packer.Ui) *StepPowerOffCompute {\n\tvar step = &StepPowerOffCompute{\n\t\tclient: client,\n\t\tsay: func(message string) { ui.Say(message) },\n\t\terror: func(e error) { ui.Error(e.Error()) },\n\t}\n\n\tstep.powerOff = step.powerOffCompute\n\treturn step\n}\n\n\n\nfunc (s *StepPowerOffCompute) Run(state multistep.StateBag) multistep.StepAction {\n\ts.say(\"Powering off machine ...\")\n\n\tvar resourceGroupName = state.Get(constants.ArmResourceGroupName).(string)\n\tvar computeName = state.Get(constants.ArmComputeName).(string)\n\n\ts.say(fmt.Sprintf(\" -> ResourceGroupName : '%s'\", resourceGroupName))\n\ts.say(fmt.Sprintf(\" -> ComputeName : '%s'\", computeName))\n\n\terr := s.powerOff(resourceGroupName, computeName)\n\tif err != nil {\n\t\tstate.Put(constants.Error, err)\n\t\ts.error(err)\n\n\t\treturn multistep.ActionHalt\n\t}\n\n\treturn multistep.ActionContinue\n}\n\nfunc (*StepPowerOffCompute) Cleanup(multistep.StateBag) {\n}\n\nfunc (s *StepPowerOffCompute) powerOffCompute(resourceGroupName string, computeName string) error ", "output": "{\n\tres, err := s.client.PowerOff(resourceGroupName, computeName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.client.VirtualMachinesClient.PollAsNeeded(res.Response)\n\treturn nil\n}"} {"input": "package crypto\n\nimport (\n\t\"crypto\"\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/sha256\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\nfunc Sign(key *rsa.PrivateKey, message []byte) ([]byte, error) {\n\thashed := sha256.Sum256(message)\n\tsignature, err := rsa.SignPKCS1v15(\n\t\trand.Reader, key, crypto.SHA256, hashed[:],\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to sign message: \")\n\t}\n\treturn signature, nil\n}\n\n\n\nfunc Verify(key *rsa.PublicKey, signature, message []byte) error {\n\thashed := sha256.Sum256(message)\n\terr := rsa.VerifyPKCS1v15(key, crypto.SHA256, hashed[:], signature)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to verify message: \")\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc DecryptRSA(key *rsa.PrivateKey, ciphertext []byte) ([]byte, error) {\n\tsession, err := rsa.DecryptPKCS1v15(rand.Reader, key, ciphertext)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to decrypt ciphertext: \")\n\t}\n\treturn session, nil\n}\n\nfunc EncryptRSA(key *rsa.PublicKey, plaintext []byte) ([]byte, error) ", "output": "{\n\tciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, key, plaintext)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to encrypt plaintext: \")\n\t}\n\treturn ciphertext, nil\n}"} {"input": "package lineargo\n\n\nimport \"C\"\nimport \"unsafe\"\n\n\n\nfunc mapCInt(in []int) []C.int {\n\tout := make([]C.int, len(in), len(in))\n\tfor i, val := range in {\n\t\tout[i] = C.int(val)\n\t}\n\treturn out\n}\n\n\nfunc doubleToFloats(in *C.double, size int) []float64 {\n\tdefer C.free(unsafe.Pointer(in))\n\toutD := (*[1 << 30]C.double)(unsafe.Pointer(in))[:size:size]\n\tout := make([]float64, size, size)\n\tfor i := 0; i < size; i++ {\n\t\tout[i] = float64(outD[i])\n\t}\n\n\treturn out\n}\n\nfunc mapCDouble(in []float64) []C.double ", "output": "{\n\tout := make([]C.double, len(in), len(in))\n\tfor i, val := range in {\n\t\tout[i] = C.double(val)\n\t}\n\treturn out\n}"} {"input": "package avs\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) BaseClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient ", "output": "{\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package keymanager\n\nimport (\n\t\"launchpad.net/juju-core/state/api\"\n\t\"launchpad.net/juju-core/state/api/params\"\n\t\"launchpad.net/juju-core/utils/ssh\"\n)\n\n\ntype Client struct {\n\tst *api.State\n}\n\n\nfunc NewClient(st *api.State) *Client {\n\treturn &Client{st}\n}\n\n\nfunc (c *Client) Close() error {\n\treturn c.st.Close()\n}\n\n\nfunc (c *Client) ListKeys(mode ssh.ListMode, users ...string) ([]params.StringsResult, error) {\n\tp := params.ListSSHKeys{Mode: mode}\n\tp.Entities.Entities = make([]params.Entity, len(users))\n\tfor i, userName := range users {\n\t\tp.Entities.Entities[i] = params.Entity{Tag: userName}\n\t}\n\tresults := new(params.StringsResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"ListKeys\", p, results)\n\treturn results.Results, err\n}\n\n\nfunc (c *Client) AddKeys(user string, keys ...string) ([]params.ErrorResult, error) {\n\tp := params.ModifyUserSSHKeys{User: user, Keys: keys}\n\tresults := new(params.ErrorResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"AddKeys\", p, results)\n\treturn results.Results, err\n}\n\n\nfunc (c *Client) DeleteKeys(user string, keys ...string) ([]params.ErrorResult, error) {\n\tp := params.ModifyUserSSHKeys{User: user, Keys: keys}\n\tresults := new(params.ErrorResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"DeleteKeys\", p, results)\n\treturn results.Results, err\n}\n\n\n\n\nfunc (c *Client) ImportKeys(user string, keyIds ...string) ([]params.ErrorResult, error) ", "output": "{\n\tp := params.ModifyUserSSHKeys{User: user, Keys: keyIds}\n\tresults := new(params.ErrorResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"ImportKeys\", p, results)\n\treturn results.Results, err\n}"} {"input": "package space\n\n\ntype Planet string\n\nconst secondsInEarthYear = 31557600\n\nvar orbitalPeriods = map[Planet]float64{\n\t\"Mercury\": 0.2408467,\n\t\"Venus\": 0.61519726,\n\t\"Earth\": 1,\n\t\"Mars\": 1.8808158,\n\t\"Jupiter\": 11.862615,\n\t\"Saturn\": 29.447498,\n\t\"Uranus\": 84.016846,\n\t\"Neptune\": 164.79132,\n}\n\n\nfunc Age(ageInSeconds float64, planet Planet) float64 {\n\treturn ageOnEarth(ageInSeconds) / orbitalPeriods[planet]\n}\n\n\n\n\nfunc ageOnEarth(ageInSeconds float64) float64 ", "output": "{\n\treturn ageInSeconds / secondsInEarthYear\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"testing\"\n)\n\ntype inspector struct {\n\terr error\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc TestGetMinImageSize(t *testing.T) {\n\tin := &inspector{}\n\tvar wg sync.WaitGroup\n\twg.Add(10)\n\tfor i := 0; i < 10; i++ {\n\t\tgo func() {\n\t\t\tsize, err := getMinImageSize(in, \"\")\n\t\t\tif err != nil || size != 10 {\n\t\t\t\tt.Errorf(\"Unexpected return value from getMinImageSize\")\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n\n\tin.err = fmt.Errorf(\"Can't read image\")\n\tsize, err := getMinImageSize(in, \"\")\n\tif err != nil || size != 10 {\n\t\tt.Errorf(\"Unexpected return value from getMinImageSize\")\n\t}\n\n\t_, err = getMinImageSize(in, \"/new/path\")\n\tif err == nil {\n\t\tt.Errorf(\"Error expected from getMinImageSize\")\n\t}\n\n}\n\nfunc (i *inspector) imageInfo(imagePath string) (int, error) ", "output": "{\n\tif i.err != nil {\n\t\treturn 0, i.err\n\t}\n\treturn 10, nil\n}"} {"input": "package mesh\n\nimport (\n\t\"time\"\n)\n\n\n\ntype tokenBucket struct {\n\tcapacity int64 \n\ttokenInterval time.Duration \n\trefillDuration time.Duration \n\tearliestUnspentToken time.Time\n}\n\n\n\nfunc newTokenBucket(capacity int64, tokenInterval time.Duration) *tokenBucket {\n\ttb := tokenBucket{\n\t\tcapacity: capacity,\n\t\ttokenInterval: tokenInterval,\n\t\trefillDuration: tokenInterval * time.Duration(capacity)}\n\n\ttb.earliestUnspentToken = tb.capacityToken()\n\n\treturn &tb\n}\n\n\n\nfunc (tb *tokenBucket) wait() {\n\ttime.Sleep(time.Until(tb.earliestUnspentToken))\n\n\tcapacityToken := tb.capacityToken()\n\tif tb.earliestUnspentToken.Before(capacityToken) {\n\t\ttb.earliestUnspentToken = capacityToken\n\t}\n\n\ttb.earliestUnspentToken = tb.earliestUnspentToken.Add(tb.tokenInterval)\n}\n\n\n\n\nfunc (tb *tokenBucket) capacityToken() time.Time ", "output": "{\n\treturn time.Now().Add(-tb.refillDuration).Truncate(tb.tokenInterval)\n}"} {"input": "package server\n\nimport (\n\t\"sync/atomic\"\n\n\t\"github.com/berkaroad/saashard/admin\"\n\t\"github.com/berkaroad/saashard/config\"\n\t\"github.com/berkaroad/saashard/proxy\"\n)\n\nconst (\n\tOffline = iota\n\tOnline\n\tUnknown\n)\n\n\ntype Server struct {\n\tcfg *config.Config\n\n\tstatusIndex int32\n\tstatus [2]int32\n\trunning bool\n\n\tproxy *proxy.Server\n\tadmin *admin.Server\n}\n\n\nfunc NewServer(cfg *config.Config) (*Server, error) {\n\tvar err error\n\ts := new(Server)\n\ts.cfg = cfg\n\n\tatomic.StoreInt32(&s.statusIndex, 0)\n\ts.status[s.statusIndex] = Online\n\n\ts.proxy, err = proxy.NewServer(cfg)\n\ts.admin, err = admin.NewServer(cfg)\n\treturn s, err\n}\n\n\nfunc (s *Server) Run() {\n\ts.running = true\n\n\tgo s.proxy.Run()\n\n\ts.admin.Run()\n}\n\n\n\n\n\nfunc (s *Server) Close() {\n\ts.running = false\n\ts.proxy.Close()\n\ts.admin.Close()\n}\n\nfunc (s *Server) Status() string ", "output": "{\n\tvar status string\n\tswitch s.status[s.statusIndex] {\n\tcase Online:\n\t\tstatus = \"online\"\n\tcase Offline:\n\t\tstatus = \"offline\"\n\tcase Unknown:\n\t\tstatus = \"unknown\"\n\tdefault:\n\t\tstatus = \"unknown\"\n\t}\n\treturn status\n}"} {"input": "package main\n\nimport (\n\t\"github.com/douglaswth/rsrdp/win32\"\n)\n\n\n\nfunc deleteCredential(credential string) error ", "output": "{\n\terr := win32.CredDelete(credential, win32.CRED_TYPE_GENERIC, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package cachestore\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\ntype CacheStore struct {\n\tstores map[string]*KVStore\n\tmutex sync.RWMutex\n}\n\n\n\nfunc (c *CacheStore) GetStore(svcName string) *KVStore {\n\tc.mutex.RLock()\n\tkvstore := c.stores[svcName]\n\tc.mutex.RUnlock()\n\n\treturn kvstore\n}\n\n\n\nfunc (c *CacheStore) CreateStore(svcName string) *KVStore {\n\tkvstore := NewKVStore()\n\tc.mutex.Lock()\n\tc.stores[svcName] = kvstore\n\tc.mutex.Unlock()\n\n\treturn kvstore\n}\n\n\nfunc (c *CacheStore) DeleteStore(svcName string) {\n\tc.mutex.Lock()\n\tdelete(c.stores, svcName)\n\tc.mutex.Unlock()\n}\n\n\nfunc (c *CacheStore) SetCache(svcName string, key string, value interface{}) {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore == nil {\n\t\tsvcStore = c.CreateStore(svcName)\n\t}\n\n\tsvcStore.Set(key, value)\n}\n\n\n\nfunc (c *CacheStore) GetCache(svcName string, key string) interface{} {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore == nil {\n\t\treturn nil\n\t}\n\treturn svcStore.Get(key)\n}\n\n\nfunc (c *CacheStore) DeleteCache(svcName string, key string) {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore != nil {\n\t\tsvcStore.Delete(key)\n\t}\n}\n\n\nfunc (c *CacheStore) MarshalJSON() ([]byte, error) {\n\tc.mutex.RLock()\n\tbytes, err := json.Marshal(&c.stores)\n\tc.mutex.RUnlock()\n\treturn bytes, err\n}\n\n\n\n\nfunc NewCacheStore() *CacheStore ", "output": "{\n\treturn &CacheStore{map[string]*KVStore{}, sync.RWMutex{}}\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSIoTAnalyticsPipeline_Channel struct {\n\n\tChannelName string `json:\"ChannelName,omitempty\"`\n\n\tName string `json:\"Name,omitempty\"`\n\n\tNext string `json:\"Next,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) AWSCloudFormationType() string {\n\treturn \"AWS::IoTAnalytics::Pipeline.Channel\"\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\n\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) SetMetadata(metadata map[string]interface{}) ", "output": "{\n\tr._metadata = metadata\n}"} {"input": "package dt\n\nimport (\n\t\"strings\"\n\n\t\"github.com/dchest/stemmer/porter2\"\n)\n\n\n\ntype Keywords struct {\n\tDict map[string]KeywordFn\n}\n\n\n\n\ntype KeywordHandler struct {\n\tFn KeywordFn\n\tTrigger *StructuredInput\n}\n\n\n\n\ntype KeywordFn func(in *Msg) (response string)\n\n\n\n\nfunc (k *Keywords) handle(m *Msg) string ", "output": "{\n\tif k == nil {\n\t\treturn \"\"\n\t}\n\tfor _, intent := range m.StructuredInput.Intents {\n\t\tfn, ok := k.Dict[\"I_\"+intent]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn fn(m)\n\t}\n\n\teng := porter2.Stemmer\n\tfor _, cmd := range m.StructuredInput.Commands {\n\t\tcmd = strings.ToLower(eng.Stem(cmd))\n\t\tfor _, obj := range m.StructuredInput.Objects {\n\t\t\tobj = strings.ToLower(eng.Stem(obj))\n\t\t\tfn, ok := k.Dict[\"CO_\"+cmd+\"_\"+obj]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn fn(m)\n\t\t}\n\t}\n\treturn \"\"\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\n\n\nfunc Info(format string, params ...interface{}) {\n\tPrint(\"Info: \" + format, params...)\n}\n\nfunc Error(err error) {\n\tPrint(\"Error: %s\", err)\n}\n\nfunc Fatal(err error) {\n\tPrint(\"Fatal: %s\", err)\n\tos.Exit(1)\n}\n\nfunc main() {\n\tvar config Config\n\tvar err error\n\tif config, err = LoadConfig(); err != nil {\n\t\tFatal(err)\n\t}\n\n\tif err = config.Verify(); err != nil {\n\t\tFatal(err)\n\t}\n\n\tvar svcmon ServiceMonitor\n\tif svcmon, err = NewServiceMonitor(&config); err != nil {\n\t\tFatal(err)\n\t}\n\n\tcleanup := func() {\n\t\tsvcmon.Close()\n\t}\n\n\tdefer cleanup()\n\tsigchan := make(chan os.Signal, 1)\n\tsignal.Notify(sigchan, syscall.SIGINT)\n\tsignal.Notify(sigchan, syscall.SIGTERM)\n\tquit := make(chan bool)\n\n\tgo func() {\n\t\t<-sigchan\n\t\tcleanup()\n\t\tquit <- true\n\t}()\n\n\tgo func() {\n\t\tif err = svcmon.Run(); err != nil {\n\t\t\tFatal(err)\n\t\t}\n\t\tquit <- true\n\t}()\n\n\t<-quit\n}\n\nfunc Print(format string, params ...interface{}) ", "output": "{\n\tfmt.Fprintf(os.Stderr, format+\"\\n\", params...)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/takama/daemon\"\n)\n\n\ntype Service struct {\n\tdaemon.Daemon\n}\n\nfunc (service *Service) Start() (string, error) {\n\n\n\tgo URLScanner(results, control, urls)\n\treturn \"\", nil\n}\n\n\n\nfunc (service *Service) Status() (string, error) {\n\treturn \"\", nil\n}\n\nfunc (service *Service) Update() (string, error) {\n\treturn \"\", nil\n}\n\nfunc (service *Service) Stop() (string, error) ", "output": "{\n\n\tcontrol <- FULLSTOP\n\treturn \"\", nil\n}"} {"input": "package memory\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/square/quotaservice/buckets\"\n\t\"github.com/square/quotaservice/config\"\n)\n\nvar factory = NewBucketFactory()\n\nfunc TestMain(m *testing.M) {\n\tsetUp()\n\tr := m.Run()\n\tos.Exit(r)\n}\n\nfunc setUp() {\n\tfactory.Init(config.NewDefaultServiceConfig())\n}\n\nfunc TestTokenAcquisition(t *testing.T) {\n\tbucket := factory.NewBucket(\"memory\", \"memory\", config.NewDefaultBucketConfig(\"\"), false)\n\tbuckets.TestTokenAcquisition(t, bucket)\n}\n\n\n\nfunc TestGC(t *testing.T) ", "output": "{\n\tbuckets.TestGC(t, factory, \"memory\")\n}"} {"input": "package challenge25\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"github.com/stripedpajamas/cryptopals/set3/challenge18\"\n)\n\nvar globalPlaintext []byte\n\n\n\nfunc TestEncryptSecretWithCTR(t *testing.T) {\n\tenc := EncryptSecretWithCTR(globalPlaintext)\n\tdec := challenge18.CTR(enc, globalKey, globalNonce)\n\n\tif !bytes.Equal(dec, globalPlaintext) {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestEdit(t *testing.T) {\n\tinput := []byte(\"HELLO POTATO FACE\")\n\tkey := []byte(\"YELLOW SUBMARINE\")\n\tnonce := []byte{0, 0, 0, 0, 0, 0, 0, 0}\n\tenc := challenge18.CTR(input, key, nonce)\n\tedited := Edit(enc, key, nonce, []byte(\"TOMATO\"), 6)\n\tdec := challenge18.CTR(edited, key, nonce)\n\n\tif string(dec) != \"HELLO TOMATO FACE\" {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestEditAPI(t *testing.T) {\n\tinput := []byte(\"HELLO POTATO FACE\")\n\tenc := challenge18.CTR(input, globalKey, globalNonce)\n\tedited := EditAPI(enc, []byte(\"TOMATO\"), 6)\n\tdec := challenge18.CTR(edited, globalKey, globalNonce)\n\n\tif string(dec) != \"HELLO TOMATO FACE\" {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestRecoverPTFromAPI(t *testing.T) {\n\tenc := EncryptSecretWithCTR(globalPlaintext)\n\trecovered := RecoverPTFromAPI(enc)\n\tif !bytes.Equal(recovered, globalPlaintext) {\n\t\tt.Fail()\n\t}\n}\n\nfunc init() ", "output": "{\n\tvar err error\n\tglobalPlaintext, err = ioutil.ReadFile(\"25_decoded.txt\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package controller\n\nimport (\n\t\"fmt\"\n\t\"github.com/Nainterceptor/MiniProject-Ping/config\"\n\t\"github.com/emicklei/go-restful\"\n\t\"net/http\"\n\t\"os\"\n\t\"path\"\n)\n\n\n\nfunc ServeStatic(req *restful.Request, resp *restful.Response) ", "output": "{\n\tactual := path.Join(config.StaticPath, req.PathParameter(\"subpath\"))\n\tif _, err := os.Stat(actual); os.IsNotExist(err) {\n\t\tactual = path.Join(config.StaticPath, \"index.html\")\n\t}\n\tfmt.Printf(\"serving %s ... (from %s)\\n\", actual, req.PathParameter(\"subpath\"))\n\thttp.ServeFile(\n\t\tresp.ResponseWriter,\n\t\treq.Request,\n\t\tactual)\n}"} {"input": "package goparsify\n\nimport (\n\t\"strconv\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\n\ntype State struct {\n\tInput string\n\tPos int\n\tCut int\n\tError Error\n\tWS VoidParser\n}\n\n\n\nfunc ASCIIWhitespace(s *State) {\n\tfor s.Pos < len(s.Input) {\n\t\tswitch s.Input[s.Pos] {\n\t\tcase '\\t', '\\n', '\\v', '\\f', '\\r', ' ':\n\t\t\ts.Pos++\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\n\n\n\nfunc NoWhitespace(s *State) {\n\n}\n\n\nfunc NewState(input string) *State {\n\treturn &State{\n\t\tInput: input,\n\t\tWS: UnicodeWhitespace,\n\t}\n}\n\n\nfunc (s *State) Advance(i int) {\n\ts.Pos += i\n}\n\n\nfunc (s *State) Get() string {\n\tif s.Pos > len(s.Input) {\n\t\treturn \"\"\n\t}\n\treturn s.Input[s.Pos:]\n}\n\n\nfunc (s *State) Preview(x int) string {\n\tif s.Pos >= len(s.Input) {\n\t\treturn \"\"\n\t}\n\n\tquoted := strconv.Quote(s.Get())\n\tquoted = quoted[1 : len(quoted)-1]\n\tif len(quoted) >= x {\n\t\treturn quoted[0:x]\n\t}\n\n\treturn quoted\n}\n\n\nfunc (s *State) ErrorHere(expected string) {\n\ts.Error.pos = s.Pos\n\ts.Error.expected = expected\n}\n\n\n\nfunc (s *State) Recover() {\n\ts.Error.expected = \"\"\n}\n\n\nfunc (s *State) Errored() bool {\n\treturn s.Error.expected != \"\"\n}\n\nfunc UnicodeWhitespace(s *State) ", "output": "{\n\tfor s.Pos < len(s.Input) {\n\t\tr, w := utf8.DecodeRuneInString(s.Get())\n\t\tif !unicode.IsSpace(r) {\n\t\t\treturn\n\t\t}\n\t\ts.Pos += w\n\t}\n}"} {"input": "package test\n\nimport (\n\t\"app/models\"\n\t\"app/services\"\n\t\"github.com/andboson/carbon\"\n\t. \"github.com/smartystreets/goconvey/convey\"\n\t\"testing\"\n)\n\n\n\n\nfunc AddMockDataModel(name string) {\n\tservices.DB.Where(\"name = ?\", name).Delete(models.Model{})\n\tmodel := models.Model{\n\t\tName: name,\n\t\tDate: carbon.Now().SubDays(2).Time,\n\t}\n\tservices.DB.Create(&model)\n}\n\nfunc TestGetModel(t *testing.T) ", "output": "{\n\tAddMockDataModel(\"tst\")\n\n\tvar model = &models.Model{}\n\tmodel = model.GetByName(\"tst\")\n\tConvey(\"Subject: Test Find Model in DB \\n\", t, func() {\n\n\t\tConvey(\"The Result Name must be equal `tst`\", func() {\n\t\t\tSo(model.Name, ShouldEqual, \"tst\")\n\t\t})\n\n\t\tConvey(\"The Result Updated At must be equal \"+carbon.Now().SubDays(2).ToDateTimeString(), func() {\n\t\t\tSo(model.Date.Day(), ShouldEqual, carbon.Now().SubDays(2).Day())\n\t\t})\n\n\t})\n}"} {"input": "package ast\n\n\ntype AsmLabelAttr struct {\n\tAddr Address\n\tPos Position\n\tInherited bool\n\tFunctionName string\n\tChildNodes []Node\n\tIsLiteralLabel bool\n}\n\nfunc parseAsmLabelAttr(line string) *AsmLabelAttr {\n\tgroups := groupsFromRegex(\n\t\t`<(?P.*)>\n\t\t(?P Inherited)?\n\t\t \"(?P.+)\"\n\t\t(?P IsLiteralLabel)?`,\n\t\tline,\n\t)\n\n\treturn &AsmLabelAttr{\n\t\tAddr: ParseAddress(groups[\"address\"]),\n\t\tPos: NewPositionFromString(groups[\"position\"]),\n\t\tInherited: len(groups[\"inherited\"]) > 0,\n\t\tFunctionName: groups[\"function\"],\n\t\tChildNodes: []Node{},\n\t\tIsLiteralLabel: len(groups[\"literal\"]) > 0,\n\t}\n}\n\n\n\nfunc (n *AsmLabelAttr) AddChild(node Node) {\n\tn.ChildNodes = append(n.ChildNodes, node)\n}\n\n\n\n\n\n\n\nfunc (n *AsmLabelAttr) Children() []Node {\n\treturn n.ChildNodes\n}\n\n\nfunc (n *AsmLabelAttr) Position() Position {\n\treturn n.Pos\n}\n\nfunc (n *AsmLabelAttr) Address() Address ", "output": "{\n\treturn n.Addr\n}"} {"input": "package opcodes\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/PMoneda/hub/lang\"\n)\n\n\n\ntype Print struct {\n\tOp interface{}\n}\n\n\n\n\n\nfunc (opcode Print) Execute() {\n\tfmt.Println(\"Execute Print\")\n}\n\nfunc (opcode Print) ToString() string ", "output": "{\n\tswitch v := opcode.Op.(type) {\n\tcase lang.Pointer:\n\t\treturn \"print $\" + v.ToString()\n\tcase lang.Number:\n\t\treturn \"print #\" + v.ToString()\n\tcase string:\n\t\treturn \"print \" + v\n\tdefault:\n\t\treturn \"print\"\n\t}\n}"} {"input": "package setup\n\nimport (\n\t\"github.com/mholt/caddy/middleware\"\n\t\"github.com/mholt/caddy/middleware/inner\"\n)\n\n\nfunc Internal(c *Controller) (middleware.Middleware, error) {\n\tpaths, err := internalParse(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn func(next middleware.Handler) middleware.Handler {\n\t\treturn inner.Internal{Next: next, Paths: paths}\n\t}, nil\n}\n\n\n\nfunc internalParse(c *Controller) ([]string, error) ", "output": "{\n\tvar paths []string\n\n\tfor c.Next() {\n\t\tif !c.NextArg() {\n\t\t\treturn paths, c.ArgErr()\n\t\t}\n\t\tpaths = append(paths, c.Val())\n\t}\n\n\treturn paths, nil\n}"} {"input": "package image\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestGetMaxAge(t *testing.T) ", "output": "{\n\ts := &resumableSession{}\n\ttests := []struct {\n\t\tvalue string\n\t\tmaxAge int\n\t}{\n\t\t{\n\t\t\tvalue: \"max-age=10\",\n\t\t\tmaxAge: 10,\n\t\t},\n\t\t{\n\t\t\tvalue: \"no-cache\",\n\t\t\tmaxAge: 0,\n\t\t},\n\t\t{\n\t\t\tvalue: \"no-store\",\n\t\t\tmaxAge: 0,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tgot := s.getMaxAge(tt.value)\n\t\tif tt.maxAge != got {\n\t\t\tt.Errorf(\"expected max-age of %d from %q, got %d\", tt.maxAge, tt.value, got)\n\t\t}\n\t}\n}"} {"input": "package mocks\n\nimport (\n\tcli \"github.com/stackanetes/kubernetes-entrypoint/client\"\n\tv1batch \"k8s.io/client-go/1.5/kubernetes/typed/batch/v1\"\n\tv1core \"k8s.io/client-go/1.5/kubernetes/typed/core/v1\"\n\tv1beta1extensions \"k8s.io/client-go/1.5/kubernetes/typed/extensions/v1beta1\"\n)\n\ntype Client struct {\n\tv1core.PodInterface\n\tv1core.ServiceInterface\n\tv1beta1extensions.DaemonSetInterface\n\tv1core.EndpointsInterface\n\tv1batch.JobInterface\n}\n\nfunc (c Client) Pods(namespace string) v1core.PodInterface {\n\treturn c.PodInterface\n}\n\nfunc (c Client) Services(namespace string) v1core.ServiceInterface {\n\treturn c.ServiceInterface\n}\n\nfunc (c Client) DaemonSets(namespace string) v1beta1extensions.DaemonSetInterface {\n\treturn c.DaemonSetInterface\n}\n\nfunc (c Client) Endpoints(namespace string) v1core.EndpointsInterface {\n\treturn c.EndpointsInterface\n}\n\n\nfunc NewClient() cli.ClientInterface {\n\treturn Client{\n\t\tNewPClient(),\n\t\tNewSClient(),\n\t\tNewDSClient(),\n\t\tNewEClient(),\n\t\tNewJClient(),\n\t}\n}\n\nfunc (c Client) Jobs(namespace string) v1batch.JobInterface ", "output": "{\n\treturn c.JobInterface\n}"} {"input": "package logutils\n\nimport (\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype MockLog struct {\n\tmock.Mock\n}\n\nfunc NewMockLog() *MockLog {\n\treturn &MockLog{}\n}\n\nfunc (m *MockLog) Fatalf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Panicf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Errorf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Warnf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\n\n\nfunc (m *MockLog) Child(name string) Log {\n\tm.Called(name)\n\treturn m\n}\n\nfunc (m *MockLog) SetLevel(level LogLevel) {\n\tm.Called(level)\n}\n\nfunc (m *MockLog) Infof(format string, args ...interface{}) ", "output": "{\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-chi/chi\"\n)\n\ntype todosResource struct{}\n\n\nfunc (rs todosResource) Routes() chi.Router {\n\tr := chi.NewRouter()\n\n\tr.Get(\"/\", rs.List) \n\tr.Post(\"/\", rs.Create) \n\tr.Put(\"/\", rs.Delete)\n\n\tr.Route(\"/{id}\", func(r chi.Router) {\n\t\tr.Get(\"/\", rs.Get) \n\t\tr.Put(\"/\", rs.Update) \n\t\tr.Delete(\"/\", rs.Delete) \n\t\tr.Get(\"/sync\", rs.Sync)\n\t})\n\n\treturn r\n}\n\nfunc (rs todosResource) List(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todos list of stuff..\"))\n}\n\nfunc (rs todosResource) Create(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todos create\"))\n}\n\nfunc (rs todosResource) Get(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo get\"))\n}\n\nfunc (rs todosResource) Update(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo update\"))\n}\n\n\n\nfunc (rs todosResource) Sync(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo sync\"))\n}\n\nfunc (rs todosResource) Delete(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tw.Write([]byte(\"todo delete\"))\n}"} {"input": "package integration\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/m3db/m3cluster/kv\"\n\n\t\"github.com/golang/protobuf/proto\"\n\t\"github.com/stretchr/testify/require\"\n)\n\ntype conditionFn func() bool\n\nfunc waitUntil(fn conditionFn, timeout time.Duration) bool {\n\tdeadline := time.Now().Add(timeout)\n\tfor time.Now().Before(deadline) {\n\t\tif fn() {\n\t\t\treturn true\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n\treturn false\n}\n\n\n\nfunc updateStore(t *testing.T, store kv.Store, key string, proto proto.Message) ", "output": "{\n\t_, err := store.Set(key, proto)\n\trequire.NoError(t, err)\n}"} {"input": "package awspublicip\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/dan-v/awslambdaproxy/pkg/server/publicip\"\n\t\"io/ioutil\"\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst (\n\tDefaultHTTPTimeout = time.Second * 10\n\tAWSProviderURL = \"http://checkip.amazonaws.com/\"\n)\n\ntype PublicIPClient struct {\n\tproviderURL string\n\thttpClient *http.Client\n}\n\n\n\nfunc (p *PublicIPClient) GetIP() (string, error) {\n\tresp, err := p.httpClient.Get(p.providerURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"http request to get ip address from %v failed: %w\", p.providerURL, err)\n\t}\n\tdefer resp.Body.Close()\n\n\tbuf, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"reading response body from %v failed: %w\", p.providerURL, err)\n\t}\n\n\tip := string(bytes.TrimSpace(buf))\n\tif net.ParseIP(ip) == nil {\n\t\treturn \"\", fmt.Errorf(\"unable to parse ip %v: %w\",\n\t\t\tpublicip.ErrInvalidIPAddress, publicip.ErrInvalidIPAddress)\n\t}\n\treturn ip, nil\n}\n\nfunc (p *PublicIPClient) ProviderURL() string {\n\treturn p.providerURL\n}\n\nfunc New() *PublicIPClient ", "output": "{\n\treturn &PublicIPClient{\n\t\tproviderURL: AWSProviderURL,\n\t\thttpClient: &http.Client{\n\t\t\tTimeout: DefaultHTTPTimeout,\n\t\t},\n\t}\n}"} {"input": "package iso20022\n\n\ntype DeadlineCode4Choice struct {\n\n\tCode *CorporateActionDeadline1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification47 `xml:\"Prtry\"`\n}\n\nfunc (d *DeadlineCode4Choice) SetCode(value string) {\n\td.Code = (*CorporateActionDeadline1Code)(&value)\n}\n\n\n\nfunc (d *DeadlineCode4Choice) AddProprietary() *GenericIdentification47 ", "output": "{\n\td.Proprietary = new(GenericIdentification47)\n\treturn d.Proprietary\n}"} {"input": "package tests\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/coreos/init/tests/coreos-install/register\"\n\t\"github.com/coreos/init/tests/coreos-install/util\"\n\n\t_ \"github.com/coreos/init/tests/coreos-install/registry\"\n)\n\nvar flagBinaryPath string\n\nfunc init() {\n\tflag.StringVar(&flagBinaryPath, \"coreos-install\", \"coreos-install\", \"path to coreos-install binary\")\n}\n\nfunc TestMain(m *testing.M) {\n\tflag.Parse()\n\tos.Exit(m.Run())\n}\n\n\n\nfunc TestCoreosInstall(t *testing.T) ", "output": "{\n\tlocalImagePath := util.FetchLocalImage(t)\n\tdefer os.RemoveAll(localImagePath)\n\n\tserver := util.HTTPServer{\n\t\tFileDir: localImagePath,\n\t}\n\taddr := server.Start(t)\n\n\tctx := register.Context{\n\t\tBinaryPath: flagBinaryPath,\n\t\tLocalImagePath: filepath.Join(localImagePath, \"coreos_production_image.bin.bz2\"),\n\t\tLocalAddress: addr,\n\t}\n\n\tnetworkUnit := util.CreateNetworkUnit(t)\n\tif networkUnit != \"\" {\n\t\tdefer os.RemoveAll(networkUnit)\n\t}\n\n\tfor _, test := range register.Tests {\n\t\tt.Run(test.Name, func(t *testing.T) {\n\t\t\ttest.Ctx = ctx\n\t\t\ttest.Run(t)\n\t\t})\n\t}\n}"} {"input": "package json\n\nimport (\n\t\"encoding/json\"\n)\n\nvar nullValue = []byte(\"null\")\n\n\ntype JsonString string\n\n\n\n\ntype RawJsonForm string\n\nfunc (s RawJsonForm) MarshalJSON() ([]byte, error) {\n\treturn []byte(s), nil\n}\n\nfunc (s JsonString) MarshalJSON() ([]byte, error) ", "output": "{\n\tif s == \"\" {\n\t\treturn nullValue, nil\n\t}\n\n\treturn json.Marshal(string(s))\n}"} {"input": "package resources\n\nimport \"github.com/starkandwayne/cf-cli/cf/models\"\n\ntype RouteResource struct {\n\tResource\n\tEntity RouteEntity\n}\n\ntype RouteEntity struct {\n\tHost string\n\tDomain DomainResource\n\tSpace SpaceResource\n\tApps []ApplicationResource\n}\n\nfunc (resource RouteResource) ToFields() (fields models.Route) {\n\tfields.Guid = resource.Metadata.Guid\n\tfields.Host = resource.Entity.Host\n\treturn\n}\n\n\nfunc (resource RouteResource) ToModel() (route models.Route) ", "output": "{\n\troute.Host = resource.Entity.Host\n\troute.Guid = resource.Metadata.Guid\n\troute.Domain = resource.Entity.Domain.ToFields()\n\troute.Space = resource.Entity.Space.ToFields()\n\tfor _, appResource := range resource.Entity.Apps {\n\t\troute.Apps = append(route.Apps, appResource.ToFields())\n\t}\n\treturn\n}"} {"input": "package comm\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestQueryType_String(t *testing.T) {\n\tassert.Equal(t, \"REQUEST\", Request.String())\n\tassert.Equal(t, \"RESPONSE\", Response.String())\n}\n\nfunc TestOutcome_String(t *testing.T) {\n\tassert.Equal(t, \"SUCCESS\", Success.String())\n\tassert.Equal(t, \"ERROR\", Error.String())\n}\n\n\n\nfunc TestMetrics_Record(t *testing.T) ", "output": "{\n\tm := newScalarMetrics()\n\n\tm.Record()\n\tassert.NotEmpty(t, m.Earliest)\n\tassert.Equal(t, m.Earliest, m.Latest)\n\tassert.Equal(t, uint64(1), m.Count)\n\n\tm.Record()\n\tassert.True(t, m.Earliest.Before(m.Latest))\n\tassert.Equal(t, uint64(2), m.Count)\n}"} {"input": "package bot\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/graffic/wanon/telegram\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\n\ntype ConfService struct {\n\tbytes []byte\n}\n\n\n\n\n\n\nfunc (service *ConfService) Get(in interface{}) error {\n\treturn yaml.Unmarshal(service.bytes, in)\n}\n\nfunc createAPI(conf *ConfService) (telegram.API, error) {\n\tvar apiConf telegram.Configuration\n\tconf.Get(&apiConf)\n\tapi := telegram.NewAPI(&http.Client{Timeout: time.Second * 15}, apiConf)\n\tresult, err := api.GetMe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Info(\"%s online\", result.Username)\n\n\treturn api, nil\n}\n\nfunc LoadConf(fileName string) (*ConfService, error) ", "output": "{\n\tconf := new(ConfService)\n\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\tconf.bytes, err = ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\treturn conf, nil\n}"} {"input": "package util\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\n\n\nfunc Fdatasync(file *os.File) error ", "output": "{\n\treturn syscall.Fdatasync(int(file.Fd()))\n}"} {"input": "package master\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\n\tkubeadmapi \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm\"\n\tkubeadmutil \"k8s.io/kubernetes/cmd/kubeadm/app/util\"\n\tclientcmdapi \"k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api\"\n\tcertutil \"k8s.io/kubernetes/pkg/util/cert\"\n)\n\n\n\nfunc CreateCertsAndConfigForClients(cfg kubeadmapi.API, clientNames []string, caKey *rsa.PrivateKey, caCert *x509.Certificate) (map[string]*clientcmdapi.Config, error) ", "output": "{\n\n\tbasicClientConfig := kubeadmutil.CreateBasicClientConfig(\n\t\t\"kubernetes\",\n\t\tfmt.Sprintf(\"https://%s:%d\", cfg.AdvertiseAddresses[0], cfg.Port),\n\t\tcertutil.EncodeCertPEM(caCert),\n\t)\n\n\tconfigs := map[string]*clientcmdapi.Config{}\n\n\tfor _, client := range clientNames {\n\t\tkey, cert, err := newClientKeyAndCert(caCert, caKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failure while creating %s client certificate - [%v]\", client, err)\n\t\t}\n\t\tconfig := kubeadmutil.MakeClientConfigWithCerts(\n\t\t\tbasicClientConfig,\n\t\t\t\"kubernetes\",\n\t\t\tclient,\n\t\t\tcertutil.EncodePrivateKeyPEM(key),\n\t\t\tcertutil.EncodeCertPEM(cert),\n\t\t)\n\t\tconfigs[client] = config\n\t}\n\n\treturn configs, nil\n}"} {"input": "package tsdb\n\nimport \"sync\"\n\ntype _Cached struct {\n\tsync.RWMutex \n\tindexer map[uint64]int \n\tringbuffer []*DBValue \n\theader int \n\ttail int \n}\n\nfunc newCached(cachedsize int) *_Cached {\n\treturn &_Cached{\n\t\tindexer: make(map[uint64]int),\n\t\tringbuffer: make([]*DBValue, cachedsize),\n\t}\n}\n\nfunc (cached *_Cached) Get(id uint64) (*DBValue, bool) {\n\tcached.RLock()\n\tdefer cached.RUnlock()\n\n\tif indexer, ok := cached.indexer[id]; ok {\n\t\treturn cached.ringbuffer[indexer], true\n\t}\n\n\treturn nil, false\n}\n\n\n\nfunc (cached *_Cached) Update(val *DBValue) ", "output": "{\n\tcached.Lock()\n\tdefer cached.Unlock()\n\n\told := cached.ringbuffer[cached.tail]\n\n\tif old != nil {\n\t\tdelete(cached.indexer, old.ID)\n\t}\n\n\tcached.ringbuffer[cached.tail] = val\n\tcached.indexer[val.ID] = cached.tail\n\n\tcached.tail++\n\n\tif cached.tail == len(cached.ringbuffer) {\n\t\tcached.tail = 0\n\t}\n\n\tif cached.tail == cached.header {\n\t\tcached.header++\n\n\t\tif cached.header == len(cached.ringbuffer) {\n\t\t\tcached.header = 0\n\t\t}\n\t}\n}"} {"input": "package etw\n\nimport (\n\t\"github.com/Microsoft/go-winio/pkg/guid\"\n)\n\n\n\n\nfunc NewProviderWithID(name string, id guid.GUID, callback EnableCallback) (provider *Provider, err error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package wraps\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-on/wrap\"\n)\n\n\n\ntype Catcher interface {\n\tCatch(recovered interface{}, w http.ResponseWriter, r *http.Request)\n}\n\n\ntype CatchFunc func(recovered interface{}, w http.ResponseWriter, r *http.Request)\n\n\nfunc (c CatchFunc) Catch(recovered interface{}, w http.ResponseWriter, r *http.Request) {\n\tc(recovered, w, r)\n}\n\n\n\n\n\n\n\nfunc (c CatchFunc) Wrap(next http.Handler) http.Handler {\n\treturn wrap.NextHandler(c).Wrap(next)\n}\n\n\nfunc Catch(c Catcher) wrap.Wrapper {\n\treturn CatchFunc(c.Catch)\n}\n\nfunc (c CatchFunc) ServeHTTPNext(next http.Handler, wr http.ResponseWriter, req *http.Request) ", "output": "{\n\tchecked := wrap.NewPeek(wr, func(ck *wrap.Peek) bool {\n\t\tck.FlushHeaders()\n\t\tck.FlushCode()\n\t\treturn true\n\t})\n\n\tdefer func() {\n\t\tif p := recover(); p != nil {\n\t\t\tc(p, wr, req)\n\t\t} else {\n\t\t\tchecked.FlushMissing()\n\t\t}\n\t}()\n\n\tnext.ServeHTTP(checked, req)\n}"} {"input": "package tests\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n)\n\n\n\nfunc TestWrongRLPTransactions(t *testing.T) {\n\terr := RunTransactionTests(filepath.Join(transactionTestDir, \"ttWrongRLPTransaction.json\"), TransSkipTests)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc Test10MBtx(t *testing.T) {\n\terr := RunTransactionTests(filepath.Join(transactionTestDir, \"tt10mbDataField.json\"), TransSkipTests)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestTransactions(t *testing.T) ", "output": "{\n\terr := RunTransactionTests(filepath.Join(transactionTestDir, \"ttTransactionTest.json\"), TransSkipTests)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package logrus\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"runtime\"\n)\n\n\nfunc (logger *Logger) Writer() *io.PipeWriter {\n\treturn logger.WriterLevel(InfoLevel)\n}\n\n\n\n\n\n\nfunc (logger *Logger) WriterLevel(level Level) *io.PipeWriter {\n\treturn NewEntry(logger).WriterLevel(level)\n}\n\nfunc (entry *Entry) Writer() *io.PipeWriter {\n\treturn entry.WriterLevel(InfoLevel)\n}\n\nfunc (entry *Entry) WriterLevel(level Level) *io.PipeWriter {\n\treader, writer := io.Pipe()\n\n\tvar printFunc func(args ...interface{})\n\n\tswitch level {\n\tcase TraceLevel:\n\t\tprintFunc = entry.Trace\n\tcase DebugLevel:\n\t\tprintFunc = entry.Debug\n\tcase InfoLevel:\n\t\tprintFunc = entry.Info\n\tcase WarnLevel:\n\t\tprintFunc = entry.Warn\n\tcase ErrorLevel:\n\t\tprintFunc = entry.Error\n\tcase FatalLevel:\n\t\tprintFunc = entry.Fatal\n\tcase PanicLevel:\n\t\tprintFunc = entry.Panic\n\tdefault:\n\t\tprintFunc = entry.Print\n\t}\n\n\tgo entry.writerScanner(reader, printFunc)\n\truntime.SetFinalizer(writer, writerFinalizer)\n\n\treturn writer\n}\n\n\n\nfunc writerFinalizer(writer *io.PipeWriter) {\n\twriter.Close()\n}\n\nfunc (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) ", "output": "{\n\tscanner := bufio.NewScanner(reader)\n\tfor scanner.Scan() {\n\t\tprintFunc(scanner.Text())\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tentry.Errorf(\"Error while reading from Writer: %s\", err)\n\t}\n\treader.Close()\n}"} {"input": "package whisperv6\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/energicryptocurrency/energi/common/hexutil\"\n)\n\nvar _ = (*messageOverride)(nil)\n\n\n\n\n\nfunc (m *Message) UnmarshalJSON(input []byte) error {\n\ttype Message struct {\n\t\tSig *hexutil.Bytes `json:\"sig,omitempty\"`\n\t\tTTL *uint32 `json:\"ttl\"`\n\t\tTimestamp *uint32 `json:\"timestamp\"`\n\t\tTopic *TopicType `json:\"topic\"`\n\t\tPayload *hexutil.Bytes `json:\"payload\"`\n\t\tPadding *hexutil.Bytes `json:\"padding\"`\n\t\tPoW *float64 `json:\"pow\"`\n\t\tHash *hexutil.Bytes `json:\"hash\"`\n\t\tDst *hexutil.Bytes `json:\"recipientPublicKey,omitempty\"`\n\t}\n\tvar dec Message\n\tif err := json.Unmarshal(input, &dec); err != nil {\n\t\treturn err\n\t}\n\tif dec.Sig != nil {\n\t\tm.Sig = *dec.Sig\n\t}\n\tif dec.TTL != nil {\n\t\tm.TTL = *dec.TTL\n\t}\n\tif dec.Timestamp != nil {\n\t\tm.Timestamp = *dec.Timestamp\n\t}\n\tif dec.Topic != nil {\n\t\tm.Topic = *dec.Topic\n\t}\n\tif dec.Payload != nil {\n\t\tm.Payload = *dec.Payload\n\t}\n\tif dec.Padding != nil {\n\t\tm.Padding = *dec.Padding\n\t}\n\tif dec.PoW != nil {\n\t\tm.PoW = *dec.PoW\n\t}\n\tif dec.Hash != nil {\n\t\tm.Hash = *dec.Hash\n\t}\n\tif dec.Dst != nil {\n\t\tm.Dst = *dec.Dst\n\t}\n\treturn nil\n}\n\nfunc (m Message) MarshalJSON() ([]byte, error) ", "output": "{\n\ttype Message struct {\n\t\tSig hexutil.Bytes `json:\"sig,omitempty\"`\n\t\tTTL uint32 `json:\"ttl\"`\n\t\tTimestamp uint32 `json:\"timestamp\"`\n\t\tTopic TopicType `json:\"topic\"`\n\t\tPayload hexutil.Bytes `json:\"payload\"`\n\t\tPadding hexutil.Bytes `json:\"padding\"`\n\t\tPoW float64 `json:\"pow\"`\n\t\tHash hexutil.Bytes `json:\"hash\"`\n\t\tDst hexutil.Bytes `json:\"recipientPublicKey,omitempty\"`\n\t}\n\tvar enc Message\n\tenc.Sig = m.Sig\n\tenc.TTL = m.TTL\n\tenc.Timestamp = m.Timestamp\n\tenc.Topic = m.Topic\n\tenc.Payload = m.Payload\n\tenc.Padding = m.Padding\n\tenc.PoW = m.PoW\n\tenc.Hash = m.Hash\n\tenc.Dst = m.Dst\n\treturn json.Marshal(&enc)\n}"} {"input": "package protobuf\n\nimport \"github.com/m3db/m3x/pool\"\n\nconst (\n\tdefaultInitBufferSize = 2880\n\n\tdefaultMaxUnaggregatedMessageSize = 50 * 1024 * 1024\n)\n\n\ntype UnaggregatedOptions interface {\n\tSetBytesPool(value pool.BytesPool) UnaggregatedOptions\n\n\tBytesPool() pool.BytesPool\n\n\tSetInitBufferSize(value int) UnaggregatedOptions\n\n\tInitBufferSize() int\n\n\tSetMaxMessageSize(value int) UnaggregatedOptions\n\n\tMaxMessageSize() int\n}\n\ntype unaggregatedOptions struct {\n\tbytesPool pool.BytesPool\n\tinitBufferSize int\n\tmaxMessageSize int\n}\n\n\nfunc NewUnaggregatedOptions() UnaggregatedOptions {\n\tp := pool.NewBytesPool(nil, nil)\n\tp.Init()\n\treturn &unaggregatedOptions{\n\t\tbytesPool: p,\n\t\tinitBufferSize: defaultInitBufferSize,\n\t\tmaxMessageSize: defaultMaxUnaggregatedMessageSize,\n\t}\n}\n\nfunc (o *unaggregatedOptions) SetBytesPool(value pool.BytesPool) UnaggregatedOptions {\n\topts := *o\n\topts.bytesPool = value\n\treturn &opts\n}\n\nfunc (o *unaggregatedOptions) BytesPool() pool.BytesPool {\n\treturn o.bytesPool\n}\n\n\n\nfunc (o *unaggregatedOptions) InitBufferSize() int {\n\treturn o.initBufferSize\n}\n\nfunc (o *unaggregatedOptions) SetMaxMessageSize(value int) UnaggregatedOptions {\n\topts := *o\n\topts.maxMessageSize = value\n\treturn &opts\n}\n\nfunc (o *unaggregatedOptions) MaxMessageSize() int {\n\treturn o.maxMessageSize\n}\n\nfunc (o *unaggregatedOptions) SetInitBufferSize(value int) UnaggregatedOptions ", "output": "{\n\topts := *o\n\topts.initBufferSize = value\n\treturn &opts\n}"} {"input": "package events\n\nimport (\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/gravitational/teleport/lib/session\"\n)\n\n\n\ntype DiscardAuditLog struct {\n}\n\nfunc (d *DiscardAuditLog) Close() error {\n\treturn nil\n}\n\nfunc (d *DiscardAuditLog) EmitAuditEvent(eventType string, fields EventFields) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionChunk(namespace string, sid session.ID, reader io.Reader) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionSlice(SessionSlice) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\nfunc (d *DiscardAuditLog) GetSessionEvents(namespace string, sid session.ID, after int) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchEvents(fromUTC, toUTC time.Time, query string) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchSessionEvents(fromUTC time.Time, toUTC time.Time) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\n\n\n\n\ntype discardSessionLogger struct {\n}\n\nfunc (d *discardSessionLogger) LogEvent(fields EventFields) {\n\treturn\n}\n\nfunc (d *discardSessionLogger) Close() error {\n\treturn nil\n}\n\n\n\nfunc (d *discardSessionLogger) WriteChunk(chunk *SessionChunk) (written int, err error) {\n\treturn 0, nil\n}\n\nfunc (d *discardSessionLogger) Finalize() error ", "output": "{\n\treturn nil\n}"} {"input": "package math\n\nimport \"jvmgo/ch06/instructions/base\"\nimport \"jvmgo/ch06/rtda\"\n\n\ntype IXOR struct{ base.NoOperandsInstruction }\n\n\n\n\ntype LXOR struct{ base.NoOperandsInstruction }\n\nfunc (self *LXOR) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tv1 := stack.PopLong()\n\tv2 := stack.PopLong()\n\tresult := v1 ^ v2\n\tstack.PushLong(result)\n}\n\nfunc (self *IXOR) Execute(frame *rtda.Frame) ", "output": "{\n\tstack := frame.OperandStack()\n\tv1 := stack.PopInt()\n\tv2 := stack.PopInt()\n\tresult := v1 ^ v2\n\tstack.PushInt(result)\n}"} {"input": "package v1\n\nimport context \"context\"\n\nimport proto \"github.com/golang/protobuf/proto\"\nimport \"go-common/library/net/rpc/liverpc\"\n\nvar _ proto.Message \n\n\n\n\n\n\ntype AdminSilent interface {\n\tGetShieldRule(context.Context, *AdminSilentGetShieldRuleReq) (*AdminSilentGetShieldRuleResp, error)\n}\n\n\n\n\n\ntype adminSilentRpcClient struct {\n\tclient *liverpc.Client\n}\n\n\n\n\n\nfunc (c *adminSilentRpcClient) GetShieldRule(ctx context.Context, in *AdminSilentGetShieldRuleReq) (*AdminSilentGetShieldRuleResp, error) {\n\tout := new(AdminSilentGetShieldRuleResp)\n\terr := doRpcRequest(ctx, c.client, 1, \"AdminSilent.get_shield_rule\", in, out)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}\n\n\n\n\n\nfunc doRpcRequest(ctx context.Context, client *liverpc.Client, version int, method string, in, out proto.Message) (err error) {\n\terr = client.Call(ctx, version, method, in, out)\n\treturn\n}\n\nfunc NewAdminSilentRpcClient(client *liverpc.Client) AdminSilent ", "output": "{\n\treturn &adminSilentRpcClient{\n\t\tclient: client,\n\t}\n}"} {"input": "package metha\n\nimport (\n\t\"encoding/base64\"\n\t\"io/ioutil\"\n\t\"strings\"\n)\n\n\ntype Repository struct {\n\tBaseURL string\n}\n\n\nfunc (r Repository) Formats() ([]MetadataFormat, error) {\n\tvar formats []MetadataFormat\n\tvar token string\n\tfor {\n\t\treq := Request{BaseURL: r.BaseURL, Verb: \"ListMetadataFormats\", ResumptionToken: token}\n\t\tresp, err := Do(&req)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tformats = append(formats, resp.ListMetadataFormats.MetadataFormat...)\n\t\tif !resp.HasResumptionToken() {\n\t\t\tbreak\n\t\t}\n\t\ttoken = resp.GetResumptionToken()\n\t}\n\treturn formats, nil\n}\n\n\n\n\n\n\nfunc FindRepositoriesByString(s string) (urls []string, err error) {\n\tfiles, err := ioutil.ReadDir(BaseDir)\n\tif err != nil {\n\t\treturn urls, err\n\t}\n\tfor _, file := range files {\n\t\tb, err := base64.RawURLEncoding.DecodeString(file.Name())\n\t\tif err != nil {\n\t\t\treturn urls, err\n\t\t}\n\t\tparts := strings.SplitN(string(b), \"#\", 3)\n\t\tif len(parts) < 3 {\n\t\t\tcontinue\n\t\t}\n\t\tbaseURL := parts[2]\n\t\tif strings.Contains(baseURL, s) {\n\t\t\turls = append(urls, baseURL)\n\t\t}\n\t}\n\treturn urls, nil\n}\n\nfunc (r Repository) Sets() ([]Set, error) ", "output": "{\n\tvar sets []Set\n\tvar token string\n\tfor {\n\t\treq := Request{BaseURL: r.BaseURL, Verb: \"ListSets\", ResumptionToken: token}\n\t\tresp, err := Do(&req)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsets = append(sets, resp.ListSets.Set...)\n\t\tif !resp.HasResumptionToken() {\n\t\t\tbreak\n\t\t}\n\t\ttoken = resp.GetResumptionToken()\n\t}\n\treturn sets, nil\n}"} {"input": "package MySQLProtocol\n\nimport \"testing\"\nimport \"github.com/stretchr/testify/assert\"\n\nvar COM_STMT_FETCH_test_packets = []struct {\n\tpacket Proto\n\tcontext Context\n}{\n\t{packet: Proto{data: StringToPacket(`\n09 00 00 00 1c 00 00 00 00 00 00 00 00\n`)}, context: Context{}},\n}\n\nfunc Test_Packet_COM_STMT_FETCH(t *testing.T) {\n\tvar pkt Packet_COM_STMT_FETCH\n\tfor _, value := range COM_STMT_FETCH_test_packets {\n\t\tpkt = Packet_COM_STMT_FETCH{}\n\t\tpkt.FromPacket(value.context, value.packet)\n\t\tassert.Equal(t, pkt.ToPacket(value.context), value.packet.data, \"\")\n\t}\n}\n\n\n\nfunc Benchmark_Packet_COM_STMT_FETCH_GetPacketSize(b *testing.B) {\n\tcontext := COM_STMT_FETCH_test_packets[0].context\n\tpkt := Packet_COM_STMT_FETCH{}\n\tpkt.FromPacket(context, COM_STMT_FETCH_test_packets[0].packet)\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt.GetPacketSize(context)\n\t}\n}\n\nfunc Benchmark_Packet_COM_STMT_FETCH_ToPacket(b *testing.B) {\n\tcontext := COM_STMT_FETCH_test_packets[0].context\n\tpkt := Packet_COM_STMT_FETCH{}\n\tpkt.FromPacket(context, COM_STMT_FETCH_test_packets[0].packet)\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt.ToPacket(context)\n\t}\n}\n\nfunc Benchmark_Packet_COM_STMT_FETCH_FromPacket(b *testing.B) ", "output": "{\n\tcontext := COM_STMT_FETCH_test_packets[0].context\n\tpacket := COM_STMT_FETCH_test_packets[0].packet\n\tpkt := Packet_COM_STMT_FETCH{}\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tpacket.offset = 0\n\t\tpkt.FromPacket(context, packet)\n\t}\n}"} {"input": "package dnssec\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/coredns/coredns/plugin/test\"\n\t\"github.com/coredns/coredns/request\"\n\n\t\"github.com/miekg/dns\"\n)\n\nconst server = \"dns//.\"\n\n\nfunc TestBlackLiesBitmapNameError(t *testing.T) {\n\td, rm1, rm2 := newDnssec(t, []string{\"example.org.\"})\n\tdefer rm1()\n\tdefer rm2()\n\n\tm := testTLSAMsg()\n\tm.Rcode = dns.RcodeNameError \n\tstate := request.Request{Req: m, Zone: \"example.org.\"}\n\tm = d.Sign(state, time.Now().UTC(), server)\n\n\tvar nsec *dns.NSEC\n\tfor _, r := range m.Ns {\n\t\tif r.Header().Rrtype == dns.TypeNSEC {\n\t\t\tnsec = r.(*dns.NSEC)\n\t\t}\n\t}\n\tfor _, b := range nsec.TypeBitMap {\n\t\tif uint16(b) == dns.TypeTLSA {\n\t\t\tt.Errorf(\"Type TLSA should not be present in the type bitmap: %v\", nsec.TypeBitMap)\n\t\t}\n\t}\n}\n\nfunc testTLSAMsg() *dns.Msg {\n\treturn &dns.Msg{MsgHdr: dns.MsgHdr{Rcode: dns.RcodeSuccess},\n\t\tQuestion: []dns.Question{{Name: \"25._tcp.example.org.\", Qclass: dns.ClassINET, Qtype: dns.TypeTLSA}},\n\t\tNs: []dns.RR{test.SOA(\"example.org.\t1800\tIN\tSOA\tlinode.example.org. miek.example.org. 1461471181 14400 3600 604800 14400\")},\n\t}\n}\n\nfunc TestBlackLiesBitmapNoData(t *testing.T) ", "output": "{\n\td, rm1, rm2 := newDnssec(t, []string{\"example.org.\"})\n\tdefer rm1()\n\tdefer rm2()\n\n\tm := testTLSAMsg()\n\tstate := request.Request{Req: m, Zone: \"example.org.\"}\n\tm = d.Sign(state, time.Now().UTC(), server)\n\n\tvar nsec *dns.NSEC\n\tfor _, r := range m.Ns {\n\t\tif r.Header().Rrtype == dns.TypeNSEC {\n\t\t\tnsec = r.(*dns.NSEC)\n\t\t}\n\t}\n\tfor _, b := range nsec.TypeBitMap {\n\t\tif uint16(b) == dns.TypeTLSA {\n\t\t\tt.Errorf(\"Type TLSA should not be present in the type bitmap: %v\", nsec.TypeBitMap)\n\t\t}\n\t}\n}"} {"input": "package gtimer\n\n\nfunc (h *priorityQueueHeap) Len() int {\n\treturn len(h.array)\n}\n\n\n\n\n\n\nfunc (h *priorityQueueHeap) Swap(i, j int) {\n\tif len(h.array) == 0 {\n\t\treturn\n\t}\n\th.array[i], h.array[j] = h.array[j], h.array[i]\n}\n\n\nfunc (h *priorityQueueHeap) Push(x interface{}) {\n\th.array = append(h.array, x.(priorityQueueItem))\n}\n\n\nfunc (h *priorityQueueHeap) Pop() interface{} {\n\tlength := len(h.array)\n\tif length == 0 {\n\t\treturn nil\n\t}\n\titem := h.array[length-1]\n\th.array = h.array[0 : length-1]\n\treturn item\n}\n\nfunc (h *priorityQueueHeap) Less(i, j int) bool ", "output": "{\n\treturn h.array[i].priority < h.array[j].priority\n}"} {"input": "package vm\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc newStack() *stack {\n\treturn &stack{}\n}\n\ntype stack struct {\n\tdata []*big.Int\n\tptr int\n}\n\nfunc (st *stack) push(d *big.Int) {\n\tstackItem := new(big.Int).Set(d)\n\tif len(st.data) > st.ptr {\n\t\tst.data[st.ptr] = stackItem\n\t} else {\n\t\tst.data = append(st.data, stackItem)\n\t}\n\tst.ptr++\n}\n\nfunc (st *stack) pop() (ret *big.Int) {\n\tst.ptr--\n\tret = st.data[st.ptr]\n\treturn\n}\n\nfunc (st *stack) len() int {\n\treturn st.ptr\n}\n\nfunc (st *stack) swap(n int) {\n\tst.data[st.len()-n], st.data[st.len()-1] = st.data[st.len()-1], st.data[st.len()-n]\n}\n\n\n\nfunc (st *stack) peek() *big.Int {\n\treturn st.data[st.len()-1]\n}\n\nfunc (st *stack) require(n int) error {\n\tif st.len() < n {\n\t\treturn fmt.Errorf(\"stack underflow (%d <=> %d)\", len(st.data), n)\n\t}\n\treturn nil\n}\n\nfunc (st *stack) Print() {\n\tfmt.Println(\"### stack ###\")\n\tif len(st.data) > 0 {\n\t\tfor i, val := range st.data {\n\t\t\tfmt.Printf(\"%-3d %v\\n\", i, val)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"-- empty --\")\n\t}\n\tfmt.Println(\"#############\")\n}\n\nfunc (st *stack) dup(n int) ", "output": "{\n\tst.push(st.data[st.len()-n])\n}"} {"input": "package do\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\n\n\n\n\n\nfunc WaitForErrorChannels(ctx Context, channels ...<-chan error) (err error) {\n\tcases := make([]reflect.SelectCase, len(channels)+1)\n\tctxDoneCaseIndex := len(channels)\n\tfor i, ch := range channels {\n\t\tcases[i] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ch)}\n\t}\n\tif ctx != nil {\n\t\tcases[ctxDoneCaseIndex] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ctx.Done())}\n\t}\n\n\tremaining := len(channels)\n\tfor remaining > 0 {\n\t\ti, value, ok := reflect.Select(cases)\n\n\t\tif i == ctxDoneCaseIndex {\n\t\t\treturn ctx.Err()\n\n\t\t} else if !value.IsNil() {\n\t\t\treturn value.Interface().(error)\n\n\t\t} else if !ok {\n\t\t\treturn fmt.Errorf(\"WaitForErrorChannels attempted read from closed channel #%d\", i)\n\t\t}\n\n\t\tcases[i].Chan = reflect.ValueOf(nil)\n\t\tremaining--\n\t}\n\treturn nil\n}\n\n\n\nfunc CheckChan(channel chan interface{}) (didRead bool, item interface{}) {\n\treturn nonBlockingChannelRead(channel)\n}\n\n\n\nfunc CheckErrChan(errChan chan error) (didRead bool, err error) {\n\tdidRead, val := nonBlockingChannelRead(errChan)\n\treturn didRead, val.(error)\n}\n\n\n\n\n\nfunc nonBlockingChannelRead(channel interface{}) (didRead bool, item interface{}) {\n\trCase := reflect.SelectCase{\n\t\tChan: reflect.ValueOf(channel),\n\t\tDir: reflect.SelectRecv,\n\t}\n\t_, value, didRead := reflect.Select([]reflect.SelectCase{rCase})\n\treturn didRead, value.Interface()\n}\n\nfunc CheckStructChan(channel chan struct{}) (didRead bool) ", "output": "{\n\tdidRead, _ = nonBlockingChannelRead(channel)\n\treturn didRead\n}"} {"input": "package igdman\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n\t\"regexp\"\n\t\"time\"\n)\n\nvar (\n\tsearchRegex *regexp.Regexp\n)\n\nfunc init() {\n\tvar err error\n\tsearchRegex, err = regexp.Compile(\".*default\\\\s+([0-9]{1,3}\\\\.[0-9]{1,3}\\\\.[0-9,]{1,3}\\\\.[0-9,]{1,3})\\\\.*\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to compile searchRegex: %s\", err)\n\t}\n}\n\n\n\nfunc defaultGatewayIp() (string, error) ", "output": "{\n\tlog.Trace(\"Calling netstat\")\n\tcmd := exec.Command(\"netstat\", \"-f\", \"inet\", \"-rn\")\n\tout, err := execTimeout(10*time.Second, cmd)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to call netstat: %s\\n%s\", err, out)\n\t}\n\tlog.Tracef(\"Netstat output\\n------------\\n%s\\n\\n\", out)\n\n\tsubmatches := searchRegex.FindSubmatch(out)\n\tif len(submatches) < 2 {\n\t\treturn \"\", fmt.Errorf(\"Unable to find default gateway in netstat output: \\n%s\", out)\n\t}\n\n\treturn string(submatches[1]), nil\n}"} {"input": "package goxpath\n\nimport (\n\txml \"encoding/xml\"\n)\n\ntype FuncOpts func(*Opts)\n\nfunc MustParse(_ string) XPathExec {\n\treturn XPathExec{}\n}\n\ntype Opts struct {\n\tNS map[string]string\n\tFuncs map[xml.Name]interface{}\n\tVars map[string]interface{}\n}\n\nfunc Parse(_ string) (XPathExec, error) {\n\treturn XPathExec{}, nil\n}\n\nfunc ParseExec(_ string, _ interface{}, _ ...FuncOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\ntype XPathExec struct{}\n\nfunc (_ XPathExec) Exec(_ interface{}, _ ...FuncOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\nfunc (_ XPathExec) ExecBool(_ interface{}, _ ...FuncOpts) (bool, error) {\n\treturn false, nil\n}\n\nfunc (_ XPathExec) ExecNode(_ interface{}, _ ...FuncOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\nfunc (_ XPathExec) ExecNum(_ interface{}, _ ...FuncOpts) (float64, error) {\n\treturn 0, nil\n}\n\n\n\nfunc (_ XPathExec) MustExec(_ interface{}, _ ...FuncOpts) interface{} ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\n\nfunc main() {\n f := fibonacci()\n for i := 0; i < 10; i++ {\n fmt.Println(f())\n }\n}\n\nfunc fibonacci() func() int ", "output": "{\n old_fib :=-1\n fib := 1\n\n return func() int {\n fib, old_fib = fib + old_fib, fib\n return fib\n }\n}"} {"input": "package facebook\n\n\ntype Error struct {\n\tMessage string\n\tType string\n\tCode int\n\tErrorSubcode int \n}\n\n\n\n\nfunc (e *Error) Error() string ", "output": "{\n\treturn e.Message\n}"} {"input": "package windows\n\nimport (\n\t\"github.com/docker/libnetwork/driverapi\"\n\t\"github.com/docker/libnetwork/types\"\n)\n\nconst networkType = \"windows\"\n\n\n\ntype driver struct{}\n\n\nfunc Init(dc driverapi.DriverCallback) error {\n\tc := driverapi.Capability{\n\t\tScope: driverapi.LocalScope,\n\t}\n\treturn dc.RegisterDriver(networkType, &driver{}, c)\n}\n\nfunc (d *driver) Config(option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) DeleteNetwork(nid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) DeleteEndpoint(nid, eid types.UUID) error {\n\treturn nil\n}\n\n\n\n\nfunc (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {\n\treturn nil\n}\n\n\nfunc (d *driver) Leave(nid, eid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) Type() string {\n\treturn networkType\n}\n\nfunc (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) ", "output": "{\n\treturn make(map[string]interface{}, 0), nil\n}"} {"input": "package testutils\n\n\ntype BlockingRW struct{ nilChan chan struct{} }\n\n\n\nfunc (rw *BlockingRW) Write(p []byte) (n int, err error) {\n\t<-rw.nilChan\n\treturn\n}\n\n\ntype NoopRW struct{}\n\nfunc (rw *NoopRW) Read(p []byte) (n int, err error) {\n\treturn len(p), nil\n}\n\nfunc (rw *NoopRW) Write(p []byte) (n int, err error) {\n\treturn len(p), nil\n}\n\nfunc (rw *BlockingRW) Read(p []byte) (n int, err error) ", "output": "{\n\t<-rw.nilChan\n\treturn\n}"} {"input": "package sc\n\n\n\n\n\n\n\n\n\ntype Gendy3 struct {\n\tAmpDist Input\n\n\tDurDist Input\n\n\tADParam Input\n\n\tDDParam Input\n\n\tFreq Input\n\n\tAmpScale Input\n\n\tDurScale Input\n\n\tInitCPs Input\n\n\tKNum Input\n}\n\n\n\n\n\nfunc (g Gendy3) Rate(rate int8) Input {\n\tCheckRate(rate)\n\t(&g).defaults()\n\treturn NewInput(\"Gendy3\", rate, 0, 1, g.AmpDist, g.DurDist, g.ADParam, g.DDParam, g.Freq, g.AmpScale, g.DurScale, g.InitCPs, g.KNum)\n}\n\nfunc (g *Gendy3) defaults() ", "output": "{\n\tif g.AmpDist == nil {\n\t\tg.AmpDist = DistCauchy\n\t}\n\tif g.DurDist == nil {\n\t\tg.DurDist = DistCauchy\n\t}\n\tif g.ADParam == nil {\n\t\tg.ADParam = C(1)\n\t}\n\tif g.DDParam == nil {\n\t\tg.DDParam = C(1)\n\t}\n\tif g.Freq == nil {\n\t\tg.Freq = C(440)\n\t}\n\tif g.AmpScale == nil {\n\t\tg.AmpScale = C(0.5)\n\t}\n\tif g.DurScale == nil {\n\t\tg.DurScale = C(0.5)\n\t}\n\tif g.InitCPs == nil {\n\t\tg.InitCPs = C(12)\n\t}\n\tif g.KNum == nil {\n\t\tg.KNum = C(12)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gabriel-comeau/tbuikit\"\n\t\"github.com/nsf/termbox-go\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc doDisconnect(uiElement, event interface{}) {\n\tdisconnect()\n}\n\n\nfunc chatEnterHandler(uiElement, event interface{}) {\n\twidget, ok := uiElement.(*tbuikit.TextInputWidget)\n\tif ok {\n\t\tnetChatChan <- widget.GetBuffer().ReturnAndClear() + \"\\n\"\n\t}\n}\n\n\n\n\n\n\nfunc calculateTopTitleBar() (x1, x2, y1, y2 int) {\n\tw := tbuikit.GetTermboxWidth()\n\tx1 = 1\n\tx2 = w - 1\n\ty1 = 1\n\ty2 = TITLE_BAR_HEIGHT\n\treturn\n}\n\n\nfunc calculateChatBufferRect() (x1, x2, y1, y2 int) {\n\tw, h := termbox.Size()\n\tx1 = 1\n\tx2 = w - 1\n\ty1 = (h / 2) + (h / 4)\n\ty2 = h - 2\n\treturn\n}\n\n\nfunc calculateMessageBufferRect() (x1, x2, y1, y2 int) {\n\tw, h := termbox.Size()\n\tx1 = 1\n\tx2 = w - (w / 4)\n\ty1 = TITLE_BAR_HEIGHT + 1\n\ty2 = (h / 2) + (h / 4) - 1\n\treturn\n}\n\n\nfunc calculateWhoRect() (x1, x2, y1, y2 int) {\n\tw, h := termbox.Size()\n\tx1 = w - (w / 4) + 1\n\tx2 = w - 1\n\ty1 = TITLE_BAR_HEIGHT + 6\n\ty2 = (h / 2) + (h / 4) - 1\n\treturn\n}\n\n\n\n\nfunc calculateWhoLabelRect() (x1, x2, y1, y2 int) ", "output": "{\n\tw := tbuikit.GetTermboxWidth()\n\tx1 = w - (w / 4) + 1\n\tx2 = w - 1\n\ty1 = TITLE_BAR_HEIGHT + 1\n\ty2 = TITLE_BAR_HEIGHT + 5\n\treturn\n}"} {"input": "package log\n\nimport (\n\t\"github.com/fcavani/e\"\n)\n\ntype StoreFake struct{}\n\n\n\nfunc (s StoreFake) Tx(write bool, f func(tx Transaction) error) error {\n\treturn e.New(\"store not implemented\")\n}\n\nfunc (s StoreFake) SupportTx() bool ", "output": "{\n\treturn false\n}"} {"input": "package hash\n\nimport \"unsafe\"\n\nconst DJBInit uint32 = 5381\n\nfunc DJBCombine(acc, h uint32) uint32 {\n\treturn mul33(acc) + h\n}\n\nfunc DJB(hs ...uint32) uint32 {\n\tacc := DJBInit\n\tfor _, h := range hs {\n\t\tacc = DJBCombine(acc, h)\n\t}\n\treturn acc\n}\n\nfunc UInt32(u uint32) uint32 {\n\treturn u\n}\n\nfunc UInt64(u uint64) uint32 {\n\treturn mul33(uint32(u>>32)) + uint32(u&0xffffffff)\n}\n\nfunc Pointer(p unsafe.Pointer) uint32 {\n\tswitch unsafe.Sizeof(p) {\n\tcase 4:\n\t\treturn UInt32(uint32(uintptr(p)))\n\tcase 8:\n\t\treturn UInt64(uint64(uintptr(p)))\n\tdefault:\n\t\tpanic(\"unhandled pointer size\")\n\t}\n}\n\nfunc UIntPtr(p uintptr) uint32 {\n\tswitch unsafe.Sizeof(p) {\n\tcase 4:\n\t\treturn UInt32(uint32(p))\n\tcase 8:\n\t\treturn UInt64(uint64(p))\n\tdefault:\n\t\tpanic(\"unhandled pointer size\")\n\t}\n}\n\nfunc String(s string) uint32 {\n\th := DJBInit\n\tfor i := 0; i < len(s); i++ {\n\t\th = DJBCombine(h, uint32(s[i]))\n\t}\n\treturn h\n}\n\n\n\nfunc mul33(u uint32) uint32 ", "output": "{\n\treturn u<<5 + u\n}"} {"input": "package containers\n\nimport (\n\t\"github.com/nanobox-io/golang-docker-client\"\n\n\t\"github.com/nanobox-io/nanobox/util/dhcp\"\n)\n\n\n\n\n\nfunc BridgeName() string {\n\treturn \"nanobox_bridge\"\n}\n\n\nfunc reserveIP() string {\n\tip, _ := dhcp.ReserveLocal()\n\treturn ip.String()\n}\n\nfunc BridgeConfig() docker.ContainerConfig ", "output": "{\n\treturn docker.ContainerConfig{\n\t\tName: BridgeName(),\n\t\tImage: \"nanobox/bridge\",\n\t\tNetwork: \"virt\",\n\t\tIP: reserveIP(),\n\t\tRestartPolicy: \"always\",\n\t\tPorts: []string{\"1194:1194/udp\"},\n\t}\n}"} {"input": "package routing\n\nimport \"net/http\"\n\n\nfunc Method(method string, handler http.Handler) Matcher {\n\treturn func(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\t\tif req.Method == method {\n\t\t\thandler.ServeHTTP(resp, req)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}\n\n\n\n\n\nfunc GETFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn GET(http.HandlerFunc(handler))\n}\n\n\nfunc POST(handler http.Handler) Matcher {\n\treturn Method(\"POST\", handler)\n}\n\n\nfunc POSTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn POST(http.HandlerFunc(handler))\n}\n\n\nfunc PUT(handler http.Handler) Matcher {\n\treturn Method(\"PUT\", handler)\n}\n\n\nfunc PUTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PUT(http.HandlerFunc(handler))\n}\n\n\nfunc PATCH(handler http.Handler) Matcher {\n\treturn Method(\"PATCH\", handler)\n}\n\n\nfunc PATCHFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PATCH(http.HandlerFunc(handler))\n}\n\n\nfunc DELETE(handler http.Handler) Matcher {\n\treturn Method(\"DELETE\", handler)\n}\n\n\nfunc DELETEFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn DELETE(http.HandlerFunc(handler))\n}\n\n\n\nfunc MethodNotAllowed(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\tresp.WriteHeader(405)\n\treturn true\n}\n\nfunc GET(handler http.Handler) Matcher ", "output": "{\n\treturn Method(\"GET\", handler)\n}"} {"input": "package test\n\nimport \"time\"\n\n\n\n\n\nfunc WaitFor(condition func() bool, maxWait, checkInterval time.Duration) bool ", "output": "{\n\tt0 := time.Now()\n\ttmax := t0.Add(maxWait)\n\tfor time.Now().Before(tmax) {\n\t\tif condition() {\n\t\t\treturn true\n\t\t}\n\t\ttime.Sleep(checkInterval)\n\t}\n\treturn false\n}"} {"input": "package user\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/juju/cmd\"\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/names\"\n\t\"launchpad.net/gnuflag\"\n\n\t\"github.com/juju/juju/cmd/envcmd\"\n)\n\nconst userCredentialsDoc = `\nWrites out the current user and credentials to a file that can be used\nwith 'juju system login' to allow the user to access the same environments\nas the same user from another machine.\n\nExamples:\n\n $ juju user credentials --output staging.creds\n\n # copy the staging.creds file to another machine\n\n $ juju system login staging --server staging.creds --keep-password\n\n\nSee Also:\n juju system login\n`\n\nfunc newCredentialsCommand() cmd.Command {\n\treturn envcmd.WrapSystem(&credentialsCommand{})\n}\n\n\ntype credentialsCommand struct {\n\tUserCommandBase\n\tOutPath string\n}\n\n\nfunc (c *credentialsCommand) Info() *cmd.Info {\n\treturn &cmd.Info{\n\t\tName: \"credentials\",\n\t\tPurpose: \"save the credentials and server details to a file\",\n\t\tDoc: userCredentialsDoc,\n\t}\n}\n\n\nfunc (c *credentialsCommand) SetFlags(f *gnuflag.FlagSet) {\n\tf.StringVar(&c.OutPath, \"o\", \"\", \"specifies the path of the generated file\")\n\tf.StringVar(&c.OutPath, \"output\", \"\", \"\")\n}\n\n\n\n\nfunc (c *credentialsCommand) Run(ctx *cmd.Context) error ", "output": "{\n\tcreds, err := c.ConnectionCredentials()\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfilename := c.OutPath\n\tif filename == \"\" {\n\t\tname := names.NewUserTag(creds.User).Name()\n\t\tfilename = fmt.Sprintf(\"%s.server\", name)\n\t}\n\treturn writeServerFile(c, ctx, creds.User, creds.Password, filename)\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\n\t\"github.com/BurntSushi/toml\"\n)\n\n\ntype ServerConfig struct {\n\tPOP pop\n\tIMAP imapClient\n\tDB db\n\tHTTP httpClient\n}\n\ntype pop struct {\n\tPort int\n\tTLS bool\n\tCert string\n\tKey string\n}\n\ntype imapClient struct {\n\tServer string\n\tPort int\n\tAddressFmt string `toml:\"address_fmt\"`\n\tFolder string\n}\n\ntype db struct {\n\tType string\n\tDBname string\n\tUser string\n\tPass string\n\tHost string\n\tPort int\n}\n\ntype httpClient struct {\n\tPort int\n}\n\n\n\n\n\nfunc ReadServerConfig(path string) (*ServerConfig, error) {\n\tvar config = ServerConfig{}\n\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = toml.Unmarshal(data, &config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n}\n\nfunc MustReadServerConfig(path string) *ServerConfig ", "output": "{\n\tconfig, err := ReadServerConfig(path)\n\tif err != nil {\n\t\tpanic(\"unable to read config: \" + err.Error())\n\t}\n\treturn config\n}"} {"input": "package errors\n\nimport (\n\t\"sync\"\n)\n\n\n\n\n\n\n\n\n\ntype LazyMultiError interface {\n\tAssign(int, error) bool\n\n\tGetOne(int) error\n\n\tGet() error\n}\n\ntype lazyMultiError struct {\n\tsync.Mutex\n\n\tsize int\n\tme MultiError\n}\n\n\nfunc NewLazyMultiError(size int) LazyMultiError {\n\treturn &lazyMultiError{size: size}\n}\n\n\n\nfunc (e *lazyMultiError) GetOne(i int) error {\n\te.Lock()\n\tdefer e.Unlock()\n\tif e.me == nil {\n\t\treturn nil\n\t}\n\treturn e.me[i]\n}\n\nfunc (e *lazyMultiError) Get() error {\n\te.Lock()\n\tdefer e.Unlock()\n\tif e.me == nil {\n\t\treturn nil\n\t}\n\treturn e.me\n}\n\nfunc (e *lazyMultiError) Assign(i int, err error) bool ", "output": "{\n\tif err == nil {\n\t\treturn false\n\t}\n\te.Lock()\n\tdefer e.Unlock()\n\tif e.me == nil {\n\t\te.me = make(MultiError, e.size)\n\t}\n\te.me[i] = err\n\treturn true\n}"} {"input": "package apmcontrolplane\n\n\ntype LifecycleStatesEnum string\n\n\nconst (\n\tLifecycleStatesCreating LifecycleStatesEnum = \"CREATING\"\n\tLifecycleStatesUpdating LifecycleStatesEnum = \"UPDATING\"\n\tLifecycleStatesActive LifecycleStatesEnum = \"ACTIVE\"\n\tLifecycleStatesDeleting LifecycleStatesEnum = \"DELETING\"\n\tLifecycleStatesFailed LifecycleStatesEnum = \"FAILED\"\n)\n\nvar mappingLifecycleStates = map[string]LifecycleStatesEnum{\n\t\"CREATING\": LifecycleStatesCreating,\n\t\"UPDATING\": LifecycleStatesUpdating,\n\t\"ACTIVE\": LifecycleStatesActive,\n\t\"DELETING\": LifecycleStatesDeleting,\n\t\"FAILED\": LifecycleStatesFailed,\n}\n\n\n\n\nfunc GetLifecycleStatesEnumValues() []LifecycleStatesEnum ", "output": "{\n\tvalues := make([]LifecycleStatesEnum, 0)\n\tfor _, v := range mappingLifecycleStates {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package mmf\n\nimport (\n\t\"os\"\n\t\"unsafe\"\n\n\tsyscall \"golang.org/x/sys/unix\"\n)\n\n\ntype MappedFile struct {\n\tdata []byte\n\toff int\n\tfile *os.File\n}\n\n\n\nfunc (mf *MappedFile) munmap() error {\n\tif data := mf.data; data != nil {\n\t\tmf.data = nil\n\t\tif err := syscall.Munmap(data); err != nil {\n\t\t\treturn os.NewSyscallError(\"Munmap\", err)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (mf *MappedFile) sync(async bool) error {\n\tvar flags uintptr\n\tif async {\n\t\tflags = syscall.MS_ASYNC\n\t} else {\n\t\tflags = syscall.MS_SYNC\n\t}\n\t_, _, errno := syscall.Syscall(syscall.SYS_MSYNC, uintptr(unsafe.Pointer(&mf.data[0])), uintptr(len(mf.data)), flags)\n\tif errno != 0 {\n\t\treturn os.NewSyscallError(\"Msync\", errno)\n\t}\n\treturn nil\n}\n\nfunc (mf *MappedFile) mmap(size int) error ", "output": "{\n\tvar err error\n\tmf.data, err = syscall.Mmap(int(mf.file.Fd()), 0, size, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED)\n\tif err != nil {\n\t\treturn os.NewSyscallError(\"Mmap\", err)\n\t}\n\treturn nil\n}"} {"input": "package heap\n\nimport (\n\t\"github.com/zxh0/jvm.go/classfile\"\n)\n\ntype ClassMember struct {\n\tclassfile.AccessFlags\n\tName string\n\tDescriptor string\n\tSignature string\n\tAnnotationData []byte \n\tClass *Class\n}\n\n\n\nfunc (m *ClassMember) copyMemberData(cf *classfile.ClassFile, cfMember classfile.MemberInfo) ", "output": "{\n\tm.AccessFlags = classfile.AccessFlags(cfMember.AccessFlags)\n\tm.Name = cf.GetUTF8(cfMember.NameIndex)\n\tm.Descriptor = cf.GetUTF8(cfMember.DescriptorIndex)\n\tm.Signature = cf.GetUTF8(cfMember.GetSignatureIndex())\n\tm.AnnotationData = cfMember.GetRuntimeVisibleAnnotationsAttributeData()\n}"} {"input": "package bsu\n\nimport (\n\t\"crypto/tls\"\n\t\"net/http\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/packer/builder/osc/common\"\n\tbuilderT \"github.com/hashicorp/packer/helper/builder/testing\"\n\t\"github.com/outscale/osc-go/oapi\"\n)\n\n\n\nfunc testAccPreCheck(t *testing.T) {\n}\n\nfunc testOAPIConn() (*oapi.Client, error) {\n\taccess := &common.AccessConfig{RawRegion: \"us-east-1\"}\n\tclientConfig, err := access.Config()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tskipClient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t}\n\n\treturn oapi.NewClient(clientConfig, skipClient), nil\n}\n\nconst testBuilderAccBasic = `\n{\n\t\"builders\": [{\n\t\t\"type\": \"test\",\n\t\t\"region\": \"eu-west-2\",\n\t\t\"vm_type\": \"t2.micro\",\n\t\t\"source_omi\": \"ami-65efcc11\",\n\t\t\"ssh_username\": \"outscale\",\n\t\t\"omi_name\": \"packer-test {{timestamp}}\"\n\t}]\n}\n`\n\nfunc TestBuilderAcc_basic(t *testing.T) ", "output": "{\n\tbuilderT.Test(t, builderT.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tBuilder: &Builder{},\n\t\tTemplate: testBuilderAccBasic,\n\t\tSkipArtifactTeardown: true,\n\t})\n}"} {"input": "package ctl\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n)\n\n\n\nfunc pullImages(images ...string) error ", "output": "{\n\tfor _, image := range images {\n\t\tfmt.Println(\"* pulling\", image, \"image\")\n\t\tif err := exec.Command(\"/usr/bin/docker\", \"pull\", image).Run(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package iso20022\n\n\ntype CorporateActionRate21 struct {\n\n\tAdditionalQuantityForSubscribedResultantSecurities *RatioFormat3Choice `xml:\"AddtlQtyForSbcbdRsltntScties,omitempty\"`\n\n\tAdditionalQuantityForExistingSecurities *RatioFormat3Choice `xml:\"AddtlQtyForExstgScties,omitempty\"`\n\n\tNewToOld *RatioFormat4Choice `xml:\"NewToOd,omitempty\"`\n}\n\nfunc (c *CorporateActionRate21) AddAdditionalQuantityForSubscribedResultantSecurities() *RatioFormat3Choice {\n\tc.AdditionalQuantityForSubscribedResultantSecurities = new(RatioFormat3Choice)\n\treturn c.AdditionalQuantityForSubscribedResultantSecurities\n}\n\nfunc (c *CorporateActionRate21) AddAdditionalQuantityForExistingSecurities() *RatioFormat3Choice {\n\tc.AdditionalQuantityForExistingSecurities = new(RatioFormat3Choice)\n\treturn c.AdditionalQuantityForExistingSecurities\n}\n\n\n\nfunc (c *CorporateActionRate21) AddNewToOld() *RatioFormat4Choice ", "output": "{\n\tc.NewToOld = new(RatioFormat4Choice)\n\treturn c.NewToOld\n}"} {"input": "package daemon\n\nimport (\n\t\"github.com/docker/docker/daemon/graphdriver\"\n\t\"github.com/docker/docker/daemon/graphdriver/aufs\"\n\t\"github.com/docker/docker/graph\"\n\t\"github.com/docker/docker/pkg/log\"\n)\n\n\n\n\n\nfunc migrateIfAufs(driver graphdriver.Driver, root string) error ", "output": "{\n\tif ad, ok := driver.(*aufs.Driver); ok {\n\t\tlog.Debugf(\"Migrating existing containers\")\n\t\tif err := ad.Migrate(root, graph.SetupInitLayer); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package fabric\n\n\n\n\nfunc containsVirtual(s []Virtual, i Virtual) bool {\n\tfor _, v := range s {\n\t\tif i.ID() == v.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc ContainsNode(l NodeList, n Node) bool {\n\tfor _, v := range l {\n\t\tif v.ID() == n.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc ContainsEdge(l EdgeList, e Edge) bool {\n\tfor _, v := range l {\n\t\tif v.ID() == e.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc contains(s []DGNode, i DGNode) bool ", "output": "{\n\tfor _, v := range s {\n\t\tif i.ID() == v.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/af83/edwig/core\"\n\t\"github.com/af83/edwig/logger\"\n\t\"github.com/af83/edwig/siri\"\n)\n\ntype SIRIStopDiscoveryRequestHandler struct {\n\txmlRequest *siri.XMLStopPointsDiscoveryRequest\n}\n\n\n\nfunc (handler *SIRIStopDiscoveryRequestHandler) ConnectorType() string {\n\treturn core.SIRI_STOP_POINTS_DISCOVERY_REQUEST_BROADCASTER\n}\n\nfunc (handler *SIRIStopDiscoveryRequestHandler) Respond(connector core.Connector, rw http.ResponseWriter) {\n\tlogger.Log.Debugf(\"StopDiscovery %s\\n\", handler.xmlRequest.MessageIdentifier())\n\n\ttmp := connector.(*core.SIRIStopPointsDiscoveryRequestBroadcaster)\n\tresponse, _ := tmp.StopAreas(handler.xmlRequest)\n\txmlResponse, err := response.BuildXML()\n\tif err != nil {\n\t\tsiriError(\"InternalServiceError\", fmt.Sprintf(\"Internal Error: %v\", err), rw)\n\t\treturn\n\t}\n\n\tsoapEnvelope := siri.NewSOAPEnvelopeBuffer()\n\tsoapEnvelope.WriteXML(xmlResponse)\n\n\t_, err = soapEnvelope.WriteTo(rw)\n\tif err != nil {\n\t\tsiriError(\"InternalServiceError\", fmt.Sprintf(\"Internal Error: %v\", err), rw)\n\t\treturn\n\t}\n}\n\nfunc (handler *SIRIStopDiscoveryRequestHandler) RequestorRef() string ", "output": "{\n\treturn handler.xmlRequest.RequestorRef()\n}"} {"input": "package proto_test\n\nimport (\n\t\"testing\"\n\n\tpb \"./testdata\"\n\t\"github.com/golang/protobuf/proto\"\n)\n\n\n\nfunc TestGetExtensionsWithMissingExtensions(t *testing.T) ", "output": "{\n\tmsg := &pb.MyMessage{}\n\text1 := &pb.Ext{}\n\tif err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil {\n\t\tt.Fatalf(\"Could not set ext1: %s\", ext1)\n\t}\n\texts, err := proto.GetExtensions(msg, []*proto.ExtensionDesc{\n\t\tpb.E_Ext_More,\n\t\tpb.E_Ext_Text,\n\t})\n\tif err != nil {\n\t\tt.Fatalf(\"GetExtensions() failed: %s\", err)\n\t}\n\tif exts[0] != ext1 {\n\t\tt.Errorf(\"ext1 not in returned extensions: %T %v\", exts[0], exts[0])\n\t}\n\tif exts[1] != nil {\n\t\tt.Errorf(\"ext2 in returned extensions: %T %v\", exts[1], exts[1])\n\t}\n}"} {"input": "package glw\n\nimport \"golang.org/x/mobile/gl\"\n\ntype A2fv gl.Attrib\n\nfunc (a A2fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A2fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A2fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 2, gl.FLOAT, false, 0, 0)\n}\n\ntype A3fv gl.Attrib\n\nfunc (a A3fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A3fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A3fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 3, gl.FLOAT, false, 0, 0)\n}\n\ntype A4fv gl.Attrib\n\n\nfunc (a A4fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A4fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 4, gl.FLOAT, false, 0, 0)\n}\n\nfunc (a A4fv) Enable() ", "output": "{ ctx.EnableVertexAttribArray(gl.Attrib(a)) }"} {"input": "package bloom\n\nimport \"math/bits\"\n\n\n\nfunc popcount(x uint64) uint64 ", "output": "{ return uint64(bits.OnesCount64(x)) }"} {"input": "package util\n\nimport \"testing\"\n\nfunc TestToCharsAscii(t *testing.T) {\n\tchars := ToChars([]byte(\"foobar\"))\n\tif !chars.inBytes || chars.ToString() != \"foobar\" || !chars.inBytes {\n\t\tt.Error()\n\t}\n}\n\n\n\nfunc TestCharsToString(t *testing.T) {\n\ttext := \"\\tabc한글 \"\n\tchars := ToChars([]byte(text))\n\tif chars.ToString() != text {\n\t\tt.Error()\n\t}\n}\n\nfunc TestTrimLength(t *testing.T) {\n\tcheck := func(str string, exp uint16) {\n\t\tchars := ToChars([]byte(str))\n\t\ttrimmed := chars.TrimLength()\n\t\tif trimmed != exp {\n\t\t\tt.Errorf(\"Invalid TrimLength result for '%s': %d (expected %d)\",\n\t\t\t\tstr, trimmed, exp)\n\t\t}\n\t}\n\tcheck(\"hello\", 5)\n\tcheck(\"hello \", 5)\n\tcheck(\"hello \", 5)\n\tcheck(\" hello\", 5)\n\tcheck(\" hello\", 5)\n\tcheck(\" hello \", 5)\n\tcheck(\" hello \", 5)\n\tcheck(\"h o\", 5)\n\tcheck(\" h o \", 5)\n\tcheck(\" \", 0)\n}\n\nfunc TestCharsLength(t *testing.T) ", "output": "{\n\tchars := ToChars([]byte(\"\\tabc한글 \"))\n\tif chars.inBytes || chars.Length() != 8 || chars.TrimLength() != 5 {\n\t\tt.Error()\n\t}\n}"} {"input": "package billing\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/billing/mgmt/2017-04-24-preview/billing\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype ManagementClient = original.ManagementClient\ntype InvoicesClient = original.InvoicesClient\ntype DownloadURL = original.DownloadURL\ntype ErrorDetails = original.ErrorDetails\ntype ErrorResponse = original.ErrorResponse\ntype Invoice = original.Invoice\ntype InvoiceProperties = original.InvoiceProperties\ntype InvoicesListResult = original.InvoicesListResult\ntype Operation = original.Operation\ntype OperationDisplay = original.OperationDisplay\ntype OperationListResult = original.OperationListResult\ntype Period = original.Period\ntype PeriodProperties = original.PeriodProperties\ntype PeriodsListResult = original.PeriodsListResult\ntype Resource = original.Resource\ntype OperationsClient = original.OperationsClient\ntype PeriodsClient = original.PeriodsClient\n\nfunc NewOperationsClient(subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClient(subscriptionID)\n}\nfunc NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewPeriodsClient(subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClient(subscriptionID)\n}\nfunc NewPeriodsClientWithBaseURI(baseURI string, subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\nfunc New(subscriptionID string) ManagementClient {\n\treturn original.New(subscriptionID)\n}\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewInvoicesClient(subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClient(subscriptionID)\n}\n\n\nfunc NewInvoicesClientWithBaseURI(baseURI string, subscriptionID string) InvoicesClient ", "output": "{\n\treturn original.NewInvoicesClientWithBaseURI(baseURI, subscriptionID)\n}"} {"input": "package float64_tree\n\nimport (\n\t\"math/bits\"\n\n\t\"github.com/kentik/patricia\"\n)\n\nconst _leftmost32Bit = uint32(1 << 31)\n\ntype treeNodeV4 struct {\n\tLeft uint \n\tRight uint \n\tprefix uint32\n\tprefixLength uint\n\tTagCount int\n}\n\n\nfunc (n *treeNodeV4) MatchCount(address patricia.IPv4Address) uint {\n\tvar length uint\n\tif address.Length > n.prefixLength {\n\t\tlength = n.prefixLength\n\t} else {\n\t\tlength = address.Length\n\t}\n\n\tmatches := uint(bits.LeadingZeros32(n.prefix ^ address.Address))\n\tif matches > length {\n\t\treturn length\n\t}\n\treturn matches\n}\n\n\n\n\n\nfunc (n *treeNodeV4) IsLeftBitSet() bool {\n\treturn n.prefix >= _leftmost32Bit\n}\n\n\nfunc (n *treeNodeV4) MergeFromNodes(left *treeNodeV4, right *treeNodeV4) {\n\tn.prefix, n.prefixLength = patricia.MergePrefixes32(left.prefix, left.prefixLength, right.prefix, right.prefixLength)\n}\n\nfunc (n *treeNodeV4) ShiftPrefix(shiftCount uint) ", "output": "{\n\tn.prefix <<= shiftCount\n\tn.prefixLength -= shiftCount\n}"} {"input": "package util\n\nimport (\n\tutilfeature \"k8s.io/apiserver/pkg/util/feature\"\n\t\"k8s.io/kubernetes/pkg/apis/storage\"\n\t\"k8s.io/kubernetes/pkg/features\"\n)\n\n\n\n\nfunc DropDisabledAlphaFields(class *storage.StorageClass) ", "output": "{\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.VolumeScheduling) {\n\t\tclass.VolumeBindingMode = nil\n\t}\n}"} {"input": "package service\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"net/http\"\n)\n\n\ntype StandardErrorRespModel struct {\n\tErrorMessage string `json:\"error\"`\n}\n\n\n\n\n\nfunc RespondWith(w http.ResponseWriter, httpStatusCode int, respModel interface{}) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(httpStatusCode)\n\tif err := json.NewEncoder(w).Encode(&respModel); err != nil {\n\t\tlog.Println(\" [!] Exception: RespondWith: Error: \", err)\n\t}\n}\n\n\n\n\n\nfunc RespondWithSuccessOK(w http.ResponseWriter, respModel interface{}) {\n\tRespondWith(w, http.StatusOK, respModel)\n}\n\n\n\n\n\n\n\n\nfunc RespondWithNotFoundError(w http.ResponseWriter, errMsg string) {\n\tRespondWithError(w, http.StatusNotFound, errMsg)\n}\n\n\nfunc RespondWithError(w http.ResponseWriter, httpErrCode int, errMsg string) {\n\tresp := StandardErrorRespModel{\n\t\tErrorMessage: errMsg,\n\t}\n\tRespondWithErrorJSON(w, httpErrCode, resp)\n}\n\n\nfunc RespondWithErrorJSON(w http.ResponseWriter, httpErrCode int, respModel interface{}) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(httpErrCode)\n\tif err := json.NewEncoder(w).Encode(&respModel); err != nil {\n\t\tlog.Println(\" [!] Exception: RespondWithErrorJSON: Error: \", err)\n\t}\n}\n\nfunc RespondWithBadRequestError(w http.ResponseWriter, errMsg string) ", "output": "{\n\tRespondWithError(w, http.StatusBadRequest, errMsg)\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\n\ntype Response struct {\n\tBody string `json:\",omitempty\"`\n\tError string `json:\",omitempty\"`\n}\n\n\nfunc (r Response) String() string {\n\tb, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Print(\"Bad marshalling:\", err)\n\t\treturn \"\"\n\t}\n\n\treturn string(b)\n}\n\n\n\n\n\nfunc logHttpAccess(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tipPrint(r, \"request\")\n\t\thandler.ServeHTTP(w, r)\n\t})\n}\n\n\nfunc sendResponseToClient(w http.ResponseWriter, body string, err string) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfmt.Fprint(w, Response{body, err})\n}\n\nfunc ipPrint(r *http.Request, v ...interface{}) ", "output": "{\n\ts := fmt.Sprintf(\"%s %s %s: \", r.RemoteAddr, r.Method, r.URL)\n\tb := make([]interface{}, 0, len(v)+1)\n\tb = append(b, s)\n\tb = append(b, v...)\n\tlog.Print(b...)\n}"} {"input": "package util\n\ntype Bool struct {\n\tb bool\n}\n\n\n\nvar True = &Bool{true}\nvar False = &Bool{false}\n\nfunc BoolFor(val bool) *Bool {\n\tif val {\n\t\treturn True\n\t}\n\treturn False\n}\n\nfunc (b *Bool) Value() bool ", "output": "{\n\treturn b.b\n}"} {"input": "package parlib\n\nimport (\n\t\"errors\"\n)\n\n\nfunc Cstrlen(str []byte) int {\n var i int = 0\n for (str[i] != 0) { i++ }\n return i\n}\n\n\n\n\nfunc StringByteSlice(s string) []byte {\n\ta, err := ByteSliceFromString(s)\n\tif err != nil {\n\t\tpanic(\"syscall: string with NUL passed to StringByteSlice\")\n\t}\n\treturn a\n}\n\n\n\n\nfunc ByteSliceFromString(s string) ([]byte, error) {\n\tfor i := 0; i < len(s); i++ {\n\t\tif s[i] == 0 {\n\t\t\treturn nil, errors.New(\"String contains a NULL byte.\")\n\t\t}\n\t}\n\ta := make([]byte, len(s)+1)\n\tcopy(a, s)\n\treturn a, nil\n}\n\n\n\n\nfunc StringBytePtr(s string) *byte { return &StringByteSlice(s)[0] }\n\n\n\n\n\n\n\n\n\nfunc StringSlicePtr(ss []string) []*byte {\n bb := make([]*byte, len(ss)+1)\n for i := 0; i < len(ss); i++ {\n bb[i] = StringBytePtr(ss[i])\n }\n bb[len(ss)] = nil\n return bb\n}\n\n\n\n\nfunc SlicePtrFromStrings(ss []string) ([]*byte, error) {\n var err error\n bb := make([]*byte, len(ss)+1)\n for i := 0; i < len(ss); i++ {\n bb[i], err = BytePtrFromString(ss[i])\n if err != nil {\n return nil, err\n }\n }\n bb[len(ss)] = nil\n return bb, nil\n}\n\nfunc BytePtrFromString(s string) (*byte, error) ", "output": "{\n\ta, err := ByteSliceFromString(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &a[0], nil\n}"} {"input": "package builder\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\n\tvelerov1api \"github.com/vmware-tanzu/velero/pkg/apis/velero/v1\"\n)\n\n\ntype PodVolumeBackupBuilder struct {\n\tobject *velerov1api.PodVolumeBackup\n}\n\n\nfunc ForPodVolumeBackup(ns, name string) *PodVolumeBackupBuilder {\n\treturn &PodVolumeBackupBuilder{\n\t\tobject: &velerov1api.PodVolumeBackup{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tAPIVersion: velerov1api.SchemeGroupVersion.String(),\n\t\t\t\tKind: \"PodVolumeBackup\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: name,\n\t\t\t},\n\t\t},\n\t}\n}\n\n\nfunc (b *PodVolumeBackupBuilder) Result() *velerov1api.PodVolumeBackup {\n\treturn b.object\n}\n\n\nfunc (b *PodVolumeBackupBuilder) ObjectMeta(opts ...ObjectMetaOpt) *PodVolumeBackupBuilder {\n\tfor _, opt := range opts {\n\t\topt(b.object)\n\t}\n\n\treturn b\n}\n\n\n\n\n\nfunc (b *PodVolumeBackupBuilder) SnapshotID(snapshotID string) *PodVolumeBackupBuilder {\n\tb.object.Status.SnapshotID = snapshotID\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) PodName(name string) *PodVolumeBackupBuilder {\n\tb.object.Spec.Pod.Name = name\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) Volume(volume string) *PodVolumeBackupBuilder {\n\tb.object.Spec.Volume = volume\n\treturn b\n}\n\nfunc (b *PodVolumeBackupBuilder) Phase(phase velerov1api.PodVolumeBackupPhase) *PodVolumeBackupBuilder ", "output": "{\n\tb.object.Status.Phase = phase\n\treturn b\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"sync\"\n\n\t\"github.com/jacobsa/util/password\"\n)\n\nvar gPassword string\nvar gPasswordOnce sync.Once\n\n\nconst passwordEnvVar = \"COMEBACK_PASSWORD\"\n\nfunc initPassword() {\n\tvar ok bool\n\tif gPassword, ok = os.LookupEnv(passwordEnvVar); ok {\n\t\treturn\n\t}\n\n\tgPassword = password.ReadPassword(\"Enter crypto password: \")\n\tif len(gPassword) == 0 {\n\t\tlog.Fatalln(\"You must enter a password.\")\n\t}\n}\n\n\n\nfunc getPassword() string ", "output": "{\n\tgPasswordOnce.Do(initPassword)\n\treturn gPassword\n}"} {"input": "package log\n\nimport \"gopkg.in/inconshreveable/log15.v2\"\n\nvar (\n\tLogger log15.Logger\n)\n\nfunc init() {\n\tLogger = log15.New()\n\tLogger.SetHandler(log15.DiscardHandler())\n}\n\n\n\nfunc Interactive() {\n\tLogger.SetHandler(log15.MultiHandler(\n\t\tlog15.LvlFilterHandler(\n\t\t\tlog15.LvlError,\n\t\t\tlog15.StderrHandler)))\n}\n\n\nfunc Debug(msg string, ctx ...interface{}) { Logger.Debug(msg, ctx...) }\nfunc Info(msg string, ctx ...interface{}) { Logger.Info(msg, ctx...) }\nfunc Warn(msg string, ctx ...interface{}) { Logger.Warn(msg, ctx...) }\nfunc Error(msg string, ctx ...interface{}) { Logger.Error(msg, ctx...) }\n\n\nfunc Crit(msg string, ctx ...interface{}) ", "output": "{ Logger.Crit(msg, ctx...) }"} {"input": "package main\n\nfunc evalRPN(tokens []string) int {\n\tstack := []int{}\n\tfor _, t := range tokens {\n\t\tif !strings.Contains(\"*+/-\", t) {\n\t\t\tx, _ := strconv.Atoi(t)\n\t\t\tstack = append(stack, x)\n\t\t} else {\n\t\t\ta := stack[len(stack)-2]\n\t\t\tb := stack[len(stack)-1]\n\t\t\tstack = stack[:len(stack)-2]\n\t\t\tstack = append(stack, eval(a, b, t))\n\t\t}\n\t}\n\treturn stack[0]\n}\n\n\n\nfunc eval(a int, b int, sym string) int ", "output": "{\n\tswitch sym {\n\tcase \"+\":\n\t\treturn a + b\n\tcase \"*\":\n\t\treturn a * b\n\tcase \"/\":\n\t\treturn a / b\n\tcase \"-\":\n\t\treturn a - b\n\t}\n\treturn 0\n}"} {"input": "package mysql\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\n\n\n\n\ntype GTID interface {\n\tString() string\n\n\tFlavor() string\n\n\tSourceServer() interface{}\n\n\tSequenceNumber() interface{}\n\n\tSequenceDomain() interface{}\n\n\tGTIDSet() GTIDSet\n}\n\n\nvar gtidParsers = make(map[string]func(string) (GTID, error))\n\n\nfunc ParseGTID(flavor, value string) (GTID, error) {\n\tparser := gtidParsers[flavor]\n\tif parser == nil {\n\t\treturn nil, fmt.Errorf(\"parse error: unknown GTID flavor %#v\", flavor)\n\t}\n\treturn parser(value)\n}\n\n\nfunc MustParseGTID(flavor, value string) GTID {\n\tgtid, err := ParseGTID(flavor, value)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn gtid\n}\n\n\n\n\n\n\n\n\nfunc DecodeGTID(s string) (GTID, error) {\n\tif s == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tparts := strings.SplitN(s, \"/\", 2)\n\tif len(parts) != 2 {\n\t\treturn ParseGTID(\"\", s)\n\t}\n\treturn ParseGTID(parts[0], parts[1])\n}\n\n\nfunc MustDecodeGTID(s string) GTID {\n\tgtid, err := DecodeGTID(s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn gtid\n}\n\nfunc EncodeGTID(gtid GTID) string ", "output": "{\n\tif gtid == nil {\n\t\treturn \"\"\n\t}\n\n\treturn fmt.Sprintf(\"%s/%s\", gtid.Flavor(), gtid.String())\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n)\n\ntype limitedReader struct {\n\tsub io.Reader\n\tremaining int64\n}\n\nfunc (self *limitedReader) Read(p []byte) (int, error) {\n\n\tif self.remaining <= 0 {\n\t\treturn 0, io.EOF\n\t}\n\n\tvar n int\n\tvar err error\n\n\tif int64(len(p)) > self.remaining {\n\t\tl := int(self.remaining)\n\t\tbuf := make([]byte, l, l)\n\t\tn, err = self.sub.Read(buf)\n\t\tif err == nil {\n\t\t\tcopy(p, buf)\n\t\t}\n\t} else {\n\t\tn, err = self.sub.Read(p)\n\t}\n\n\tif err == io.EOF && self.remaining > 0 {\n\t\terr = ErrRangeNotSatisfiable\n\t} else if err == nil {\n\t\tself.remaining = self.remaining - int64(n)\n\t}\n\treturn n, err\n}\n\n\n\nfunc (self *limitedReader) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package gce\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"google.golang.org/cloud/compute/metadata\"\n)\n\ntype AuthToken struct {\n\tAccessToken string `json:\"access_token\"`\n\n\tExpiresIn int `json:\"expires_in\"`\n\n\tTokenType string `json:\"token_type\"`\n}\n\n\n\n\n\nfunc GetAuthToken() (AuthToken, error) {\n\trawToken, err := metadata.Get(\"instance/service-accounts/default/token\")\n\tif err != nil {\n\t\treturn AuthToken{}, err\n\t}\n\n\tvar token AuthToken\n\terr = json.Unmarshal([]byte(rawToken), &token)\n\tif err != nil {\n\t\treturn AuthToken{}, fmt.Errorf(\"failed to unmarshal service account token with output %q: %v\", rawToken, err)\n\t}\n\n\treturn token, err\n}\n\nfunc VerifyAuthScope(expectedScope string) error ", "output": "{\n\tscopes, err := metadata.Get(\"instance/service-accounts/default/scopes\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, scope := range strings.Fields(scopes) {\n\t\tif scope == expectedScope {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"Current instance does not have the expected scope (%q). Actual scopes: %v\", expectedScope, scopes)\n}"} {"input": "package s0035\n\n\n\n\n\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com/peterstace/project-euler/number\"\n)\n\nfunc Solution() interface{} {\n\treturn Parameterised(1000000)\n}\n\n\n\n\nfunc Parameterised(n int) int ", "output": "{\n\n\tisPrime := number.PrimeSieve(n)\n\tcount := 0\n\n\tfor c := range isPrime {\n\t\tif !isPrime[c] {\n\t\t\tcontinue\n\t\t}\n\n\t\tp := fmt.Sprintf(\"%d\", c)\n\t\tcircular := true\n\t\tfor i := 1; i < len(p); i++ {\n\t\t\tp = p[1:] + p[0:1]\n\t\t\trotated, err := strconv.Atoi(p)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tif !isPrime[rotated] {\n\t\t\t\tcircular = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif circular {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}"} {"input": "package wifi\n\nimport (\n\t\"time\"\n\n\t\"github.com/bettercap/bettercap/network\"\n)\n\n\n\nfunc (mod *WiFiModule) channelHopper() {\n\tmod.reads.Add(1)\n\tdefer mod.reads.Done()\n\n\tmod.Info(\"channel hopper started.\")\n\n\tfor mod.Running() {\n\t\tdelay := mod.hopPeriod\n\t\tif len(mod.frequencies) > 14 {\n\t\t\tdelay = delay * 2\n\t\t}\n\n\t\tfrequencies := mod.frequencies\n\n\tloopCurrentChannels:\n\t\tfor _, frequency := range frequencies {\n\t\t\tchannel := network.Dot11Freq2Chan(frequency)\n\t\t\tif mod.stickChan != 0 {\n\t\t\t\tchannel = mod.stickChan\n\t\t\t}\n\n\t\t\tmod.Debug(\"hopping on channel %d\", channel)\n\n\t\t\tmod.chanLock.Lock()\n\t\t\tif err := network.SetInterfaceChannel(mod.iface.Name(), channel); err != nil {\n\t\t\t\tmod.Warning(\"error while hopping to channel %d: %s\", channel, err)\n\t\t\t}\n\t\t\tmod.chanLock.Unlock()\n\n\t\t\tselect {\n\t\t\tcase _ = <-mod.hopChanges:\n\t\t\t\tmod.Debug(\"hop changed\")\n\t\t\t\tbreak loopCurrentChannels\n\t\t\tcase <-time.After(delay):\n\t\t\t\tif !mod.Running() {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (mod *WiFiModule) onChannel(channel int, cb func()) ", "output": "{\n\tmod.chanLock.Lock()\n\tdefer mod.chanLock.Unlock()\n\n\tprev := mod.stickChan\n\tmod.stickChan = channel\n\n\tif err := network.SetInterfaceChannel(mod.iface.Name(), channel); err != nil {\n\t\tmod.Warning(\"error while hopping to channel %d: %s\", channel, err)\n\t} else {\n\t\tmod.Debug(\"hopped on channel %d\", channel)\n\t}\n\n\tcb()\n\n\tmod.stickChan = prev\n}"} {"input": "package datascience\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype UpdateModelRequest struct {\n\n\tModelId *string `mandatory:\"true\" contributesTo:\"path\" name:\"modelId\"`\n\n\tUpdateModelDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateModelRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request UpdateModelRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request UpdateModelRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateModelResponse struct {\n\n\tRawResponse *http.Response\n\n\tModel `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateModelResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateModelResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateModelRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package authy\n\nimport (\n\t\"github.com/tg123/sshpiper/sshpiperd/challenger\"\n)\n\nfunc (authyClient) GetName() string {\n\treturn \"authy\"\n}\n\nfunc (a *authyClient) GetOpts() interface{} {\n\treturn &a.Config\n}\n\nfunc (a *authyClient) GetHandler() challenger.Handler {\n\treturn a.challenge\n}\n\n\n\nfunc init() ", "output": "{\n\tchallenger.Register(\"authy\", &authyClient{})\n}"} {"input": "package ewma\n\nimport (\n\t\"time\"\n)\n\ntype EwmaRate struct {\n\tEwma\n}\n\n\nconst nanosec = float64(1000000000)\n\n\n\n\nfunc NewEwmaRate(halfLife time.Duration) *EwmaRate {\n\treturn (&EwmaRate{}).Init(halfLife)\n}\n\n\n\n\nfunc (r *EwmaRate) Init(halfLife time.Duration) *EwmaRate {\n\tr.Ewma.Init(halfLife)\n\treturn r\n}\n\n\n\n\nfunc (r *EwmaRate) UpdateNow() float64 {\n\treturn r.Update(time.Now())\n}\n\n\n\n\n\n\n\n\n\nfunc (r *EwmaRate) CurrentNow() float64 {\n\treturn r.Current(time.Now())\n}\n\n\nfunc (r *EwmaRate) Current(now time.Time) float64 {\n\tif r.lastTimestamp.IsZero() || r.lastTimestamp == now || now.Before(r.lastTimestamp) {\n\t\treturn r.Ewma.Current\n\t}\n\n\ttimeDelta := now.Sub(r.lastTimestamp)\n\n\treturn r.count(0, timeDelta)\n}\n\nfunc (r *EwmaRate) Update(now time.Time) float64 ", "output": "{\n\ttimeDelta := now.Sub(r.lastTimestamp)\n\treturn r.Ewma.Update(nanosec/float64(timeDelta.Nanoseconds()), now)\n}"} {"input": "package float64_tree\n\nimport (\n\t\"math/bits\"\n\n\t\"github.com/kentik/patricia\"\n)\n\nconst _leftmost32Bit = uint32(1 << 31)\n\ntype treeNodeV4 struct {\n\tLeft uint \n\tRight uint \n\tprefix uint32\n\tprefixLength uint\n\tTagCount int\n}\n\n\nfunc (n *treeNodeV4) MatchCount(address patricia.IPv4Address) uint {\n\tvar length uint\n\tif address.Length > n.prefixLength {\n\t\tlength = n.prefixLength\n\t} else {\n\t\tlength = address.Length\n\t}\n\n\tmatches := uint(bits.LeadingZeros32(n.prefix ^ address.Address))\n\tif matches > length {\n\t\treturn length\n\t}\n\treturn matches\n}\n\n\nfunc (n *treeNodeV4) ShiftPrefix(shiftCount uint) {\n\tn.prefix <<= shiftCount\n\tn.prefixLength -= shiftCount\n}\n\n\nfunc (n *treeNodeV4) IsLeftBitSet() bool {\n\treturn n.prefix >= _leftmost32Bit\n}\n\n\n\n\nfunc (n *treeNodeV4) MergeFromNodes(left *treeNodeV4, right *treeNodeV4) ", "output": "{\n\tn.prefix, n.prefixLength = patricia.MergePrefixes32(left.prefix, left.prefixLength, right.prefix, right.prefixLength)\n}"} {"input": "package terminal\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"golang.org/x/crypto/ssh/terminal\"\n)\n\n\n\nfunc GetSize() (w, h int) {\n\tw, h, err := terminal.GetSize(int(os.Stdout.Fd()))\n\tif err != nil {\n\t\tw, h = 80, 25\n\t}\n\treturn w, h\n}\n\n\n\n\n\n\n\nfunc ReadPassword(fd int) ([]byte, error) {\n\treturn terminal.ReadPassword(fd)\n}\n\n\nfunc WriteTerminalTitle(title string) {\n\tfmt.Printf(ChangeTitle + title + BEL)\n}\n\nfunc IsTerminal(fd int) bool ", "output": "{\n\treturn terminal.IsTerminal(fd)\n}"} {"input": "package util\n\ntype Progress struct {\n\terrs chan error\n\tdone chan struct{}\n}\n\nfunc NewProgress(total int) *Progress {\n\tp := &Progress{make(chan error), make(chan struct{})}\n\tgo func() {\n\t\tcompleted := 0\n\t\terrorCount := 0\n\t\tfor err := range p.errs {\n\t\t\tif err == nil {\n\t\t\t\tcompleted += 1\n\t\t\t} else {\n\t\t\t\terrorCount += 1\n\t\t\t\tif FlagQuiet {\n\t\t\t\t\tWarnf(\"%s\", err)\n\t\t\t\t} else {\n\t\t\t\t\tWarnf(\"\\r%s \\n\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tratio := 100.0 * (float64(completed) / float64(total))\n\t\t\tVerbosef(\"\\r%d of %d jobs complete (%0.2f%% done, %d errors)\",\n\t\t\t\tcompleted, total, ratio, errorCount)\n\t\t}\n\t\tVerbosef(\"\\n\")\n\t\tp.done <- struct{}{}\n\t}()\n\treturn p\n}\n\n\n\nfunc (p *Progress) Close() {\n\tif p == nil {\n\t\treturn\n\t}\n\tclose(p.errs)\n\t<-p.done\n}\n\nfunc (p *Progress) JobDone(err error) ", "output": "{\n\tif p == nil {\n\t\treturn\n\t}\n\tp.errs <- err\n}"} {"input": "package gpio\n\n\ntype Mode byte\n\nconst (\n\tIn Mode = 0 \n\tOut Mode = out \n\tAlt Mode = alt \n\tAltIn Mode = altIn \n\tAna Mode = ana \n)\n\n\ntype Driver byte\n\nconst (\n\tPushPull Driver = 0\n\tOpenDrain Driver = openDrain\n)\n\n\n\n\n\ntype Speed int8\n\nconst (\n\tVeryLow Speed = veryLow \n\tLow Speed = low \n\tMedium Speed = 0 \n\tHigh Speed = high \n\tVeryHigh Speed = veryHigh \n)\n\n\ntype Pull byte\n\nconst (\n\tNoPull Pull = 0 \n\tPullUp Pull = pullUp \n\tPullDown Pull = pullDown \n)\n\n\ntype Config struct {\n\tMode Mode \n\tDriver Driver \n\tSpeed Speed \n\tPull Pull \n}\n\n\nfunc (p *Port) SetupPin(index int, cfg *Config) {\n\tsetup(p, index, cfg)\n}\n\n\n\n\n\n\nfunc (p *Port) Lock(pins Pins) {\n\tpins1 := uint32(pins) | 0x10000\n\tp.lckr.Store(pins1)\n\tp.lckr.Store(uint32(pins))\n\tp.lckr.Store(pins1)\n\tp.lckr.Load()\n\tp.lckr.Load()\n}\n\nfunc (p *Port) Setup(pins Pins, cfg *Config) ", "output": "{\n\tfor n := 0; n < 16; n++ {\n\t\tif pins&(1< 0 {\n\t\tsum += n % 10\n\t\tn /= 10\n\t}\n\treturn sum\n}\n\nfunc isPrime(n int) bool {\n\tif n%2 == 0 {\n\t\treturn n == 2\n\t}\n\tfor i := 3; i*i <= n; i += 2 {\n\t\tif n%i == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\nfunc main() {\n\tin, _ := os.Open(\"10042.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"10042.out\")\n\tdefer out.Close()\n\n\tvar n, num int\n\tfor fmt.Fscanf(in, \"%d\", &n); n > 0; n-- {\n\t\tfor fmt.Fscanf(in, \"%d\", &num); ; num++ {\n\t\t\tsum1 := digitSum(num)\n\t\t\tsum2 := 0\n\t\t\tfor _, v := range primeFactorize(num) {\n\t\t\t\tsum2 += digitSum(v)\n\t\t\t}\n\t\t\tif sum1 == sum2 {\n\t\t\t\tfmt.Fprintln(out, num)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc primeFactorize(n int) []int ", "output": "{\n\tvar p []int\n\tfor i := 2; i <= n; i++ {\n\t\tfor isPrime(i) {\n\t\t\tfor n%i == 0 {\n\t\t\t\tp = append(p, i)\n\t\t\t\tn /= i\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\treturn p\n}"} {"input": "package x11\n\nimport (\n\t\"C\"\n\t\"unsafe\"\n\n\t\"github.com/richardwilkes/toolbox/xmath/geom\"\n\t\"github.com/richardwilkes/ui/keys\"\n)\n\ntype CrossingEvent C.XCrossingEvent\n\n\n\nfunc (evt *CrossingEvent) Where() geom.Point {\n\treturn geom.Point{X: float64(evt.x), Y: float64(evt.y)}\n}\n\nfunc (evt *CrossingEvent) Modifiers() keys.Modifiers {\n\treturn Modifiers(evt.state)\n}\n\nfunc (evt *CrossingEvent) ToEvent() *Event {\n\treturn (*Event)(unsafe.Pointer(evt))\n}\n\nfunc (evt *CrossingEvent) Window() Window ", "output": "{\n\treturn Window(evt.window)\n}"} {"input": "package simple\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/spencergibb/go-nuvem/loadbalancer\"\n\t\"github.com/spencergibb/go-nuvem/loadbalancer/rule\"\n\t\"github.com/spencergibb/go-nuvem/loadbalancer/serverlist\"\n\t\"github.com/spf13/viper\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\"\n)\n\nfunc TestFactory(t *testing.T) {\n\tviper.SetConfigType(\"yaml\")\n\tyaml := []byte(`\nnuvem.loadbalancer.test.serverlist.static.servers:\n- localhost:8080\n- 127.0.0.1:9080\n`)\n\terr := viper.ReadConfig(bytes.NewBuffer(yaml))\n\tviper.SetDefault(\"nuvem.loadbalancer.test.factory\", FactoryKey)\n\n\tif err != nil { \n\t\tpanic(fmt.Errorf(\"Fatal error config file: %s \\n\", err))\n\t}\n\n\tlb := loadbalancer.Create(\"test\")\n\tassertLoadBalancer(t, lb)\n}\n\n\n\nfunc assertLoadBalancer(t *testing.T, lb loadbalancer.LoadBalancer) {\n\trequire.NotNil(t, lb, \"lb was nil\")\n\n\tserver := lb.Choose()\n\tassert.NotNil(t, server, \"server was nil\")\n}\n\nfunc TestBuilder(t *testing.T) ", "output": "{\n\tprintln(\"\\nTestBuilder\")\n\tlb := NewBuilder().\n\t\tNamespace(\"test\").\n\t\tServerList(serverlist.NewStaticBuilder(\"test\").Servers(\"10.0.0.1:80\").Build()).\n\t\tRule(rule.NewRandomRule()).\n\t\tBuild()\n\n\tassertLoadBalancer(t, lb)\n}"} {"input": "package expression\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/pingcap/tidb/config\"\n\t\"github.com/pingcap/tidb/testkit/testmain\"\n\t\"github.com/pingcap/tidb/util/mock\"\n\t\"github.com/pingcap/tidb/util/testbridge\"\n\t\"github.com/pingcap/tidb/util/timeutil\"\n\t\"github.com/stretchr/testify/require\"\n\t\"github.com/tikv/client-go/v2/tikv\"\n\t\"go.uber.org/goleak\"\n)\n\n\n\nfunc createContext(t *testing.T) *mock.Context {\n\tctx := mock.NewContext()\n\tctx.GetSessionVars().StmtCtx.TimeZone = time.Local\n\tsc := ctx.GetSessionVars().StmtCtx\n\tsc.TruncateAsWarning = true\n\trequire.NoError(t, ctx.GetSessionVars().SetSystemVar(\"max_allowed_packet\", \"67108864\"))\n\tctx.GetSessionVars().PlanColumnID = 0\n\treturn ctx\n}\n\nfunc TestMain(m *testing.M) ", "output": "{\n\ttestbridge.WorkaroundGoCheckFlags()\n\ttestmain.ShortCircuitForBench(m)\n\n\tconfig.UpdateGlobal(func(conf *config.Config) {\n\t\tconf.TiKVClient.AsyncCommit.SafeWindow = 0\n\t\tconf.TiKVClient.AsyncCommit.AllowedClockDrift = 0\n\t\tconf.Experimental.AllowsExpressionIndex = true\n\t})\n\ttikv.EnableFailpoints()\n\n\ttimeutil.SetSystemTZ(\"system\")\n\n\topts := []goleak.Option{\n\t\tgoleak.IgnoreTopFunction(\"go.etcd.io/etcd/pkg/logutil.(*MergeLogger).outputLoop\"),\n\t\tgoleak.IgnoreTopFunction(\"go.opencensus.io/stats/view.(*worker).start\"),\n\t\tgoleak.IgnoreTopFunction(\"github.com/pingcap/tidb/table/tables.mockRemoteService\"),\n\t}\n\n\tgoleak.VerifyTestMain(m, opts...)\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/utils\"\n\nfunc init() {\n\tc := &ImportTpFromFolder{\n\t\tname: \"import_tp_from_folder\",\n\t\trpcMethod: utils.APIerSv1ImportTariffPlanFromFolder,\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype ImportTpFromFolder struct {\n\tname string\n\trpcMethod string\n\trpcParams *utils.AttrImportTPFromFolder\n\trpcResult string\n\t*CommandExecuter\n}\n\nfunc (self *ImportTpFromFolder) Name() string {\n\treturn self.name\n}\n\nfunc (self *ImportTpFromFolder) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *ImportTpFromFolder) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &utils.AttrImportTPFromFolder{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *ImportTpFromFolder) PostprocessRpcParams() error {\n\treturn nil\n}\n\n\n\nfunc (self *ImportTpFromFolder) RpcResult() interface{} ", "output": "{\n\tvar s string\n\treturn &s\n}"} {"input": "package goopenzwave\n\n\n\n\n\nimport \"C\"\nimport (\n\t\"fmt\"\n)\n\nvar (\n\tstarted bool\n\tnotificationHandler NotificationHandler\n)\n\n\n\ntype NotificationHandler func(notification *Notification)\n\n\n\n\n\n\n\n\n\nfunc Stop() error {\n\tif started {\n\t\treturn fmt.Errorf(\"already started\")\n\t}\n\n\terr := stopNotifications()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdestroyManager()\n\n\treturn nil\n}\n\nfunc Start(handler NotificationHandler) error ", "output": "{\n\tif started {\n\t\treturn fmt.Errorf(\"already started\")\n\t}\n\n\terr := createManager()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create manager: %s\", err)\n\t}\n\n\terr = startNotifications()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnotificationHandler = handler\n\n\treturn nil\n}"} {"input": "package keymutex\n\nimport (\n\t\"hash/fnv\"\n\t\"runtime\"\n\t\"sync\"\n)\n\n\n\n\n\n\nfunc NewHashed(n int) KeyMutex {\n\tif n <= 0 {\n\t\tn = runtime.NumCPU()\n\t}\n\treturn &hashedKeyMutex{\n\t\tmutexes: make([]sync.Mutex, n),\n\t}\n}\n\ntype hashedKeyMutex struct {\n\tmutexes []sync.Mutex\n}\n\n\n\n\n\nfunc (km *hashedKeyMutex) UnlockKey(id string) error {\n\tkm.mutexes[km.hash(id)%len(km.mutexes)].Unlock()\n\treturn nil\n}\n\nfunc (km *hashedKeyMutex) hash(id string) int {\n\th := fnv.New32a()\n\th.Write([]byte(id))\n\treturn int(h.Sum32())\n}\n\nfunc (km *hashedKeyMutex) LockKey(id string) ", "output": "{\n\tkm.mutexes[km.hash(id)%len(km.mutexes)].Lock()\n}"} {"input": "package check\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestCheckErrorForExit(t *testing.T) ", "output": "{\n\tErrorForExit(\"name\", nil)\n\tassert.True(t, true)\n}"} {"input": "package service\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"testing\"\n\n\t\"go-common/library/ecode\"\n)\n\nfunc TestService_Oauth(t *testing.T) {\n\tonce.Do(startService)\n\tak := \"4de8aecfafc7f91cb650d6371efb1b63\"\n\texpectMid := int64(110000139)\n\tif res, err := s.Oauth(context.TODO(), s.appMap[_gameAppKey], ak, \"\"); err != nil {\n\t\tt.Errorf(\"s.Oauth() error(%v)\", err)\n\t\tt.FailNow()\n\t} else if res == nil || res.Mid != expectMid {\n\t\tt.Errorf(\"res is not correct, expected res with mid %d but got %v\", expectMid, res)\n\t\tt.FailNow()\n\t} else {\n\t\tstr, _ := json.Marshal(res)\n\t\tt.Logf(\"res: %s\", str)\n\t}\n}\n\n\n\nfunc TestService_Oauth_Expires(t *testing.T) ", "output": "{\n\tonce.Do(startService)\n\tak := \"c1e220e12fd4c89a0c5449b9f8c7b062\"\n\tif _, err := s.Oauth(context.TODO(), s.appMap[_gameAppKey], ak, \"\"); err != ecode.AccessTokenExpires {\n\t\tt.Errorf(\"res is not correct, expected error %v, but got %v\", ecode.AccessTokenExpires, err)\n\t\tt.FailNow()\n\t}\n}"} {"input": "package ibmmq\n\n\n\n\nimport \"C\"\n\n\ntype MQCBD struct {\n\tCallbackType int32\n\tOptions int32\n\tCallbackArea interface{}\n\tCallbackFunction MQCB_FUNCTION\n\tCallbackName string\n\tMaxMsgLength int32\n}\n\n\n\n\nfunc copyCBDtoC(mqcbd *C.MQCBD, gocbd *MQCBD) {\n\n\tsetMQIString((*C.char)(&mqcbd.StrucId[0]), \"CBD \", 4)\n\tmqcbd.Version = C.MQCBD_VERSION_1\n\n\tmqcbd.CallbackType = C.MQLONG(gocbd.CallbackType)\n\tmqcbd.Options = C.MQLONG(gocbd.Options) | C.MQCBDO_FAIL_IF_QUIESCING\n\tmqcbd.CallbackArea = (C.MQPTR)(C.NULL)\n\n\tsetMQIString((*C.char)(&mqcbd.CallbackName[0]), gocbd.CallbackName, 128) \n\n\tmqcbd.MaxMsgLength = C.MQLONG(gocbd.MaxMsgLength)\n\n\treturn\n}\n\nfunc copyCBDfromC(mqcbd *C.MQCBD, gocbd *MQCBD) {\n\treturn\n}\n\nfunc NewMQCBD() *MQCBD ", "output": "{\n\tcbd := new(MQCBD)\n\tcbd.CallbackType = C.MQCBT_MESSAGE_CONSUMER\n\tcbd.Options = C.MQCBDO_NONE\n\tcbd.CallbackArea = nil\n\tcbd.CallbackFunction = nil\n\tcbd.CallbackName = \"\"\n\tcbd.MaxMsgLength = C.MQCBD_FULL_MSG_LENGTH\n\n\treturn cbd\n}"} {"input": "package k8sclient\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\t\"hash/fnv\"\n\t\"math/rand\"\n\t\"sync\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/google/uuid\"\n)\n\nvar (\n\tseedOnce sync.Once\n\tuuidMutex sync.Mutex\n)\n\nfunc GenerateUUID(seed string) string {\n\tvar stringUUID string\n\tuuidMutex.Lock()\n\tuuid.SetRand(rand.New(rand.NewSource(int64(hash(seed)))))\n\tstringUUID = uuid.New().String()\n\tuuidMutex.Unlock()\n\treturn stringUUID\n}\n\n\nfunc getBytes(value interface{}) []byte {\n\tvar byteBuffer bytes.Buffer\n\tgobEncoder := gob.NewEncoder(&byteBuffer)\n\tif err := gobEncoder.Encode(value); err != nil {\n\t\tglog.Fatalln(\"Failed to encode value\")\n\t\treturn nil\n\t}\n\treturn byteBuffer.Bytes()\n}\n\nfunc hash(valueOne interface{}) uint64 {\n\tnewHash := fnv.New64()\n\tnewHash.Write(getBytes(valueOne))\n\treturn newHash.Sum64()\n}\n\n\n\nfunc HashCombine(valueOne, valueTwo interface{}) uint64 ", "output": "{\n\tnewHash := fnv.New64()\n\tvalueOneBytes := getBytes(valueOne)\n\tvalueTwoBytes := getBytes(valueTwo)\n\tnewHash.Write(append(valueOneBytes, valueTwoBytes...))\n\treturn newHash.Sum64()\n}"} {"input": "package backoff\n\nimport (\n\t\"math\"\n\t\"time\"\n\n\t\"github.com/quan-xie/tuba/util/xtime\"\n)\n\n\ntype Backoff interface {\n\tNext(retry int) time.Duration\n}\n\ntype constantBackoff struct {\n\tbackoffInterval xtime.Duration\n}\n\n\n\n\n\nfunc (cb *constantBackoff) Next(retry int) time.Duration {\n\tif retry <= 0 {\n\t\treturn 0 * time.Millisecond\n\t}\n\n\treturn time.Duration(cb.backoffInterval) * 1 << uint(retry)\n}\n\ntype exponentialBackoff struct {\n\texponentFactor float64\n\tinitialTimeout float64\n\tmaxTimeout float64\n}\n\n\nfunc NewExponentialBackoff(initialTimeout, maxTimeout time.Duration, exponentFactor float64) Backoff {\n\treturn &exponentialBackoff{\n\t\texponentFactor: exponentFactor,\n\t\tinitialTimeout: float64(initialTimeout / time.Millisecond),\n\t\tmaxTimeout: float64(maxTimeout / time.Millisecond),\n\t}\n}\n\n\nfunc (eb *exponentialBackoff) Next(retry int) time.Duration {\n\tif retry <= 0 {\n\t\treturn 0 * time.Millisecond\n\t}\n\n\treturn time.Duration(math.Min(eb.initialTimeout+math.Pow(eb.exponentFactor, float64(retry)), eb.maxTimeout)) * time.Millisecond\n}\n\nfunc NewConstantBackoff(backoffInterval xtime.Duration) Backoff ", "output": "{\n\treturn &constantBackoff{backoffInterval: backoffInterval}\n}"} {"input": "package waiter\n\nimport (\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/service/neptune\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource\"\n)\n\nconst (\n\tEventSubscriptionStatusNotFound = \"NotFound\"\n\n\tEventSubscriptionStatusUnknown = \"Unknown\"\n)\n\n\n\n\nfunc EventSubscriptionStatus(conn *neptune.Neptune, subscriptionName string) resource.StateRefreshFunc ", "output": "{\n\treturn func() (interface{}, string, error) {\n\t\tinput := &neptune.DescribeEventSubscriptionsInput{\n\t\t\tSubscriptionName: aws.String(subscriptionName),\n\t\t}\n\n\t\toutput, err := conn.DescribeEventSubscriptions(input)\n\n\t\tif err != nil {\n\t\t\treturn nil, EventSubscriptionStatusUnknown, err\n\t\t}\n\n\t\tif len(output.EventSubscriptionsList) == 0 {\n\t\t\treturn nil, EventSubscriptionStatusNotFound, nil\n\t\t}\n\n\t\treturn output.EventSubscriptionsList[0], aws.StringValue(output.EventSubscriptionsList[0].Status), nil\n\t}\n}"} {"input": "package gtk\n\n\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n\n\t\"github.com/untoldwind/amintk/gdk\"\n)\n\n\ntype Image struct {\n\tWidget\n}\n\n\nfunc ImageNew() *Image {\n\tc := C.gtk_image_new()\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\n\n\n\nfunc ImageNewFromIconName(iconName string, size IconSize) *Image {\n\tcstr := C.CString(iconName)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_image_new_from_icon_name((*C.gchar)(cstr),\n\t\tC.GtkIconSize(size))\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\n\nfunc ImageNewFromPixbuf(pixbuf *gdk.Pixbuf) *Image {\n\tptr := (*C.GdkPixbuf)(pixbuf.Native())\n\tc := C.gtk_image_new_from_pixbuf(ptr)\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\nfunc wrapImage(p unsafe.Pointer) *Image {\n\tif widget := wrapWidget(p); widget != nil {\n\t\treturn &Image{Widget: *widget}\n\t}\n\treturn nil\n}\n\n\nfunc (v *Image) Clear() {\n\tC.gtk_image_clear(v.native())\n}\n\n\nfunc (v *Image) SetFromPixbuf(pixbuf *gdk.Pixbuf) {\n\tpbptr := (*C.GdkPixbuf)(pixbuf.Native())\n\tC.gtk_image_set_from_pixbuf(v.native(), pbptr)\n}\n\nfunc (v *Image) native() *C.GtkImage ", "output": "{\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn (*C.GtkImage)(v.Native())\n}"} {"input": "package aes\n\nimport (\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\n\t\"github.com/golang/glog\"\n)\n\ntype aesInfo struct {\n\tkeyLen int\n\tivLen int\n}\n\nvar info = map[string]aesInfo{\n\t\"aes-128-cfb\": aesInfo{keyLen: 16, ivLen: 16},\n\t\"aes-192-cfb\": aesInfo{keyLen: 24, ivLen: 16},\n\t\"aes-256-cfb\": aesInfo{keyLen: 32, ivLen: 16},\n}\n\n\ntype AES struct {\n\tName string\n}\n\n\n\n\n\nfunc (a *AES) NewStream(key, iv []byte, encrypt bool) (cipher.Stream, error) {\n\tglog.V(5).Infoln(\"New Aes Stream\")\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif encrypt {\n\t\treturn cipher.NewCFBEncrypter(block, iv), nil\n\t}\n\treturn cipher.NewCFBDecrypter(block, iv), nil\n}\n\n\nfunc (a *AES) GetIVLen() int {\n\tv, ok := info[a.Name]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\treturn v.ivLen\n}\n\nfunc (a *AES) GetKeyLen() int {\n\tv, ok := info[a.Name]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\treturn v.keyLen\n}\n\nfunc NewAES(aesType string) (*AES, error) ", "output": "{\n\talg := &AES{\n\t\tName: aesType,\n\t}\n\treturn alg, nil\n}"} {"input": "package object\n\ntype Error string\n\nfunc (e Error) First() Value {\n\treturn e\n}\n\nfunc (e Error) Rest() Value {\n\treturn e\n}\n\nfunc (e Error) Type() Type {\n\treturn ERROR\n}\n\n\n\nfunc (e Error) String() string ", "output": "{\n\treturn string(\"\")\n}"} {"input": "package trace\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\n\n\nfunc TestOff(t *testing.T) {\n\ttracer := Off()\n\ttracer.Trace(\"do something\")\n}\n\nfunc TestNew(t *testing.T) ", "output": "{\n\tvar buf bytes.Buffer\n\ttracer := New(&buf)\n\tif tracer == nil {\n\t\tt.Error(\"Return from New should not be nil\")\n\t} else {\n\t\ttracer.Trace(\"Hello trace package.\")\n\t\tif buf.String() != \"Hello trace package.\\n\" {\n\t\t\tt.Errorf(\"Trace should not write '%s'.\", buf.String())\n\t\t}\n\t}\n}"} {"input": "package cronjob\n\nimport (\n\tcontext \"context\"\n\n\tv1beta1 \"k8s.io/client-go/informers/batch/v1beta1\"\n\tfactory \"knative.dev/pkg/client/injection/kube/informers/factory\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\n\n\n\ntype Key struct{}\n\nfunc withInformer(ctx context.Context) (context.Context, controller.Informer) {\n\tf := factory.Get(ctx)\n\tinf := f.Batch().V1beta1().CronJobs()\n\treturn context.WithValue(ctx, Key{}, inf), inf.Informer()\n}\n\n\nfunc Get(ctx context.Context) v1beta1.CronJobInformer {\n\tuntyped := ctx.Value(Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch k8s.io/client-go/informers/batch/v1beta1.CronJobInformer from context.\")\n\t}\n\treturn untyped.(v1beta1.CronJobInformer)\n}\n\nfunc init() ", "output": "{\n\tinjection.Default.RegisterInformer(withInformer)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"golang.org/x/net/html\"\n\t\"io\"\n\t\"strings\"\n)\n\n\nconst htmldata = `\n\n\nPage Title\n\n\n\n

This is a Heading1

\n

This is a paragraph.

\n\n

This is a Heading2

\n\n\n
`\n\nfunc main() {\n\n\thtmlReader := strings.NewReader(htmldata)\n\tallText := html2rawtext(htmlReader)\n\n\tfmt.Println(allText)\n\n}\n\nfunc html2rawtext(htmlReader io.Reader) string {\n\n\tz := html.NewTokenizer(htmlReader)\n\n\talltext := func(z *html.Tokenizer) []string {\n\t\tvar alltext []string\n\t\tfor {\n\n\t\t\ttt := z.Next()\n\n\t\t\tif tt == html.ErrorToken {\n\t\t\t\treturn alltext\n\t\t\t}\n\t\t\tif tt == html.TextToken {\n\t\t\t\tt := z.Token()\n\n\t\t\t\talltext = append(alltext, t.Data)\n\n\t\t\t}\n\t\t}\n\t}(z)\n\n\treturn cleanNonPrintChar(strings.Join(alltext, \" \"))\n}\n\n\n\nfunc cleanNonPrintChar(text string) string ", "output": "{\n\n\tclean := make([]rune, 0, len(text))\n\tvar prev rune\n\tfor _, t := range text {\n\t\tif t < 32 { \n\t\t\tt = 32\n\t\t}\n\t\tif !(t == 32 && prev == 32) {\n\t\t\tclean = append(clean, t)\n\t\t\tprev = t\n\t\t}\n\t}\n\n\treturn string(clean)\n\n}"} {"input": "package controller\n\nimport (\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n\ntype Controller struct {\n\te *gin.Engine\n}\n\n\nfunc New( e *gin.Engine) *Controller {\n\n\treturn &Controller{\n\t\te: e,\n\t}\n\n}\n\n\n\n\n\nfunc (p *Controller) ping(ctx *gin.Context) {\n\tctx.String(200, \"pong pong\")\n}\n\nfunc (c *Controller) SetupRouters() ", "output": "{\n\tc.e.GET(\"/ping2\", c.ping)\n\n}"} {"input": "package mqcontrollers\n\nimport (\n\t\"github.com/byrnedo/apibase/natsio\"\n\tr \"github.com/byrnedo/apibase/routes\"\n\t\"github.com/nats-io/nats\"\n)\n\ntype HealthcheckController struct {\n\troutes []*r.NatsRoute\n\tnatsCon *natsio.Nats\n}\n\n\n\nfunc NewHealthcheckController(nc *natsio.Nats) (hc *HealthcheckController) {\n\thc = &HealthcheckController{}\n\thc.natsCon = nc\n\thc.routes = []*r.NatsRoute{\n\t\tr.NewNatsRoute(\"user.healthcheck\", hc.Healthcheck),\n\t}\n\treturn\n}\n\nfunc (c *HealthcheckController) Healthcheck(m *nats.Msg) {\n}\n\nfunc (c *HealthcheckController) GetRoutes() []*r.NatsRoute ", "output": "{\n\treturn c.routes\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/ovh/cds/cli\"\n\t\"github.com/ovh/cds/sdk\"\n)\n\nvar projectFavoriteCmd = cli.Command{\n\tName: \"favorite\",\n\tAliases: []string{\"favorites\"},\n\tShort: \"Add or delete a CDS project to your personal bookmarks\",\n\tCtx: []cli.Arg{\n\t\t{Name: _ProjectKey},\n\t},\n}\n\n\n\nfunc projectFavoriteRun(c cli.Values) error ", "output": "{\n\tparams := sdk.FavoriteParams{\n\t\tType: \"project\",\n\t\tProjectKey: c.GetString(_ProjectKey),\n\t}\n\n\tres, err := client.UpdateFavorite(context.Background(), params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif proj, ok := res.(sdk.Project); ok {\n\t\tif proj.Favorite {\n\t\t\tfmt.Printf(\"Bookmarks added for project %s\\n\", proj.Name)\n\t\t} else {\n\t\t\tfmt.Printf(\"Bookmarks deleted for project %s\\n\", proj.Name)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Bookmarks updated\")\n\t}\n\n\treturn nil\n}"} {"input": "package rubber\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"go.uber.org/zap\"\n)\n\nconst (\n\tConfigWeightedBackend = \"weighted\"\n\n\tConfigSimpleBackend = \"simple\"\n)\n\nfunc compare(name, constant string) bool {\n\treturn strings.ToLower(name) == strings.ToLower(constant)\n}\n\nfunc makeBackend(log *zap.Logger, settings Settings) (Backend, error) {\n\tif compare(settings.Type, ConfigWeightedBackend) {\n\t\tlog.Debug(\"Using weighted backend\")\n\t\treturn CreateWeightedBackend(settings, log)\n\t}\n\tif compare(settings.Type, ConfigSimpleBackend) || compare(settings.Type, \"\") {\n\t\tlog.Debug(\"Using simple backend\")\n\t\tnodes := []string{settings.Preferred}\n\t\tnodes = append(nodes, settings.Nodes...)\n\t\treturn &singleServerBackend{\n\t\t\tlog: log,\n\t\t\tnodes: nodes,\n\t\t\ttimeout: settings.Timeout * time.Second,\n\n\t\t\tclient: &http.Client{\n\t\t\t\tTimeout: settings.Timeout * time.Second,\n\t\t\t},\n\t\t}, nil\n\t}\n\treturn nil, errors.New(\"Unknown backend\")\n}\n\n\n\n\n\nfunc New(log *zap.Logger, settings Settings) (*Elastic, error) {\n\tbackend, err := makeBackend(log, settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn Create(backend), nil\n}\n\nfunc Create(backend Backend) *Elastic ", "output": "{\n\treturn &Elastic{Backend: backend}\n}"} {"input": "package internalversion\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\tapi \"k8s.io/kubernetes/pkg/api\"\n)\n\ntype TestgroupInterface interface {\n\tRESTClient() rest.Interface\n\tTestTypesGetter\n}\n\n\ntype TestgroupClient struct {\n\trestClient rest.Interface\n}\n\nfunc (c *TestgroupClient) TestTypes(namespace string) TestTypeInterface {\n\treturn newTestTypes(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*TestgroupClient, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TestgroupClient{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *TestgroupClient {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *TestgroupClient {\n\treturn &TestgroupClient{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tg, err := api.Registry.Group(\"testgroup.k8s.io\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.APIPath = \"/apis\"\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\tif config.GroupVersion == nil || config.GroupVersion.Group != g.GroupVersion.Group {\n\t\tcopyGroupVersion := g.GroupVersion\n\t\tconfig.GroupVersion = ©GroupVersion\n\t}\n\tconfig.NegotiatedSerializer = api.Codecs\n\n\tif config.QPS == 0 {\n\t\tconfig.QPS = 5\n\t}\n\tif config.Burst == 0 {\n\t\tconfig.Burst = 10\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (c *TestgroupClient) RESTClient() rest.Interface ", "output": "{\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}"} {"input": "package main\n\nimport \"testing\"\n\nfunc Test_container_key(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tlabels []string\n\t\texpect string\n\t}{\n\t\t{\n\t\t\tname: \"foo\",\n\t\t\tlabels: []string{},\n\t\t\texpect: \"foo{}\",\n\t\t}, {\n\t\t\tname: \"foo\",\n\t\t\tlabels: []string{\"value\"},\n\t\t\texpect: \"foo{value}\",\n\t\t}, {\n\t\t\tname: \"foo\",\n\t\t\tlabels: []string{\"value\", \"color\"},\n\t\t\texpect: \"foo{color,value}\",\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tkey := containerKey(c.name, c.labels)\n\t\tif key != c.expect {\n\t\t\tt.Errorf(\"expected container key %s, got %s\", c.expect, key)\n\t\t}\n\t}\n}\n\n\n\nfunc Test_container_fetch_gauge(t *testing.T) {\n\tcontainer := NewGaugeContainer(\"marathon\")\n\t_, new := container.Fetch(\"foo\", \"\")\n\n\tif !new {\n\t\tt.Fatal(\"expected a new gauge\")\n\t}\n\tif len(container.gauges) != 1 {\n\t\tt.Fatalf(\"expected a gauge, got %d gauges\", len(container.gauges))\n\t}\n\n\t_, new = container.Fetch(\"foo\", \"\")\n\tif new {\n\t\tt.Fatal(\"expected an existing gauge\")\n\t}\n\tif len(container.gauges) != 1 {\n\t\tt.Fatalf(\"expected same gauge as before, go %d gauges\", len(container.gauges))\n\t}\n}\n\nfunc Test_container_fetch_counter(t *testing.T) ", "output": "{\n\tcontainer := NewCounterContainer(\"marathon\")\n\t_, new := container.Fetch(\"foo\", \"\")\n\n\tif !new {\n\t\tt.Fatal(\"expected a new counter\")\n\t}\n\tif len(container.counters) != 1 {\n\t\tt.Fatalf(\"expected a counter, got %d counters\", len(container.counters))\n\t}\n\n\t_, new = container.Fetch(\"foo\", \"\")\n\tif new {\n\t\tt.Fatal(\"expected an existing counter\")\n\t}\n\tif len(container.counters) != 1 {\n\t\tt.Fatalf(\"expected same counter as before, go %d counters\", len(container.counters))\n\t}\n}"} {"input": "package gospec\n\nimport (\n\t\"fmt\"\n\tfilepath \"path\"\n\t\"runtime\"\n)\n\ntype Location struct {\n\tname string\n\tfile string\n\tline int\n}\n\n\n\nfunc callerLocation() *Location {\n\treturn newLocation(2)\n}\n\nfunc newLocation(n int) *Location {\n\tif pc, _, _, ok := runtime.Caller(n + 1); ok {\n\t\treturn locationForPC(pc)\n\t}\n\treturn nil\n}\n\nfunc locationForPC(pc uintptr) *Location {\n\tpc = pcOfWhereCallWasMade(pc)\n\tf := runtime.FuncForPC(pc)\n\tname := f.Name()\n\tfile, line := f.FileLine(pc)\n\treturn &Location{name, file, line}\n}\n\n\n\n\n\n\n\n\nfunc pcOfWhereCallWasMade(pcOfWhereCallReturnsTo uintptr) uintptr {\n\treturn pcOfWhereCallReturnsTo - 1\n}\n\nfunc (this *Location) Name() string { return this.name }\nfunc (this *Location) File() string { return this.file }\nfunc (this *Location) FileName() string { return filename(this.file) }\nfunc (this *Location) Line() int { return this.line }\n\nfunc filename(path string) string {\n\t_, file := filepath.Split(path)\n\treturn file\n}\n\nfunc (this *Location) equals(that *Location) bool {\n\treturn this.name == that.name &&\n\t\tthis.file == that.file &&\n\t\tthis.line == that.line\n}\n\nfunc (this *Location) String() string {\n\treturn fmt.Sprintf(\"%v:%v\", this.FileName(), this.Line())\n}\n\nfunc currentLocation() *Location ", "output": "{\n\treturn newLocation(1)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSGameLiftBuild_S3Location struct {\n\n\tBucket string `json:\"Bucket,omitempty\"`\n\n\tKey string `json:\"Key,omitempty\"`\n\n\tRoleArn string `json:\"RoleArn,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\n\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSGameLiftBuild_S3Location) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::GameLift::Build.S3Location\"\n}"} {"input": "package util\n\nimport (\n \"github.com/twitchyliquid64/CNC/logging\"\n \"github.com/robertkrimen/otto\"\n)\n\n\n\nfunc GetFunc(argument otto.Value, vm *otto.Otto) otto.Value ", "output": "{\n if (argument.IsFunction()) {\n return argument;\n }\n\n mname := argument.String()\n logging.Warning(\"plugin-builtin\", \"Using a string to name parameters is now deprecated. Please use callbacks directly: \" + mname)\n\n method, err := vm.Get(mname)\n if (err != nil){\n logging.Error(\"plugin-builtin\", \"Error getting function \\\"\" + mname + \"\\\": \")\n }\n\n return method;\n}"} {"input": "package adapterManager\n\nimport (\n\t\"istio.io/mixer/pkg/adapter\"\n\t\"istio.io/mixer/pkg/pool\"\n)\n\ntype env struct {\n\tlogger adapter.Logger\n\tgp *pool.GoroutinePool\n}\n\nfunc newEnv(aspect string, gp *pool.GoroutinePool) adapter.Env {\n\treturn env{\n\t\tlogger: newLogger(aspect),\n\t\tgp: gp,\n\t}\n}\n\nfunc (e env) Logger() adapter.Logger {\n\treturn e.logger\n}\n\nfunc (e env) ScheduleWork(fn adapter.WorkFunc) {\n\te.gp.ScheduleWork(func() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\t_ = e.Logger().Errorf(\"Adapter worker failed: %v\", r)\n\n\t\t\t}\n\t\t}()\n\n\t\tfn()\n\t})\n}\n\n\n\nfunc (e env) ScheduleDaemon(fn adapter.DaemonFunc) ", "output": "{\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\t_ = e.Logger().Errorf(\"Adapter daemon failed: %v\", r)\n\n\t\t\t}\n\t\t}()\n\n\t\tfn()\n\t}()\n}"} {"input": "package schemareplication\n\nimport (\n\tcontext \"context\"\n\n\tv1beta1 \"github.com/rabbitmq/messaging-topology-operator/pkg/generated/informers/externalversions/rabbitmq.com/v1beta1\"\n\tfactory \"knative.dev/eventing-rabbitmq/pkg/client/injection/rabbitmq.com/informers/factory\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\n\n\n\ntype Key struct{}\n\nfunc withInformer(ctx context.Context) (context.Context, controller.Informer) {\n\tf := factory.Get(ctx)\n\tinf := f.Rabbitmq().V1beta1().SchemaReplications()\n\treturn context.WithValue(ctx, Key{}, inf), inf.Informer()\n}\n\n\nfunc Get(ctx context.Context) v1beta1.SchemaReplicationInformer {\n\tuntyped := ctx.Value(Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch github.com/rabbitmq/messaging-topology-operator/pkg/generated/informers/externalversions/rabbitmq.com/v1beta1.SchemaReplicationInformer from context.\")\n\t}\n\treturn untyped.(v1beta1.SchemaReplicationInformer)\n}\n\nfunc init() ", "output": "{\n\tinjection.Default.RegisterInformer(withInformer)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification struct {\n\n\tPredefinedScalingMetricType string `json:\"PredefinedScalingMetricType,omitempty\"`\n\n\tResourceLabel string `json:\"ResourceLabel,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) AWSCloudFormationType() string {\n\treturn \"AWS::AutoScalingPlans::ScalingPlan.PredefinedScalingMetricSpecification\"\n}\n\n\n\n\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) DependsOn() []string ", "output": "{\n\treturn r._dependsOn\n}"} {"input": "package leetcode\n\nconst MAX_INT32 = 1<<31 - 1\nconst MIN_INT32 = -1 << 31\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\nfunc maxInt(a, b int) int {\n\tif a < b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}\n\n\n\nfunc absInt(num int) int {\n\tif num > 0 {\n\t\treturn num\n\t} else {\n\t\treturn -num\n\t}\n}\n\nfunc qsortInt(nums []int) []int {\n\tif len(nums) <= 1 {\n\t\treturn nums\n\t}\n\n\thead, tail := 0, len(nums)-1\n\tidx, mid := 1, nums[0]\n\tfor head < tail {\n\t\tif nums[idx] > mid {\n\t\t\tnums[idx], nums[tail] = nums[tail], nums[idx]\n\t\t\ttail--\n\t\t} else {\n\t\t\tnums[idx], nums[head] = nums[head], nums[idx]\n\t\t\thead++\n\t\t\tidx++\n\t\t}\n\t}\n\tnums[head] = mid\n\tqsortInt(nums[:head])\n\tqsortInt(nums[head+1:])\n\treturn nums\n}\n\ntype Stack struct {\n\tdata []rune\n}\n\nfunc (s *Stack) push(data rune) {\n\ts.data = append(s.data, data)\n}\n\nfunc (s *Stack) pop() rune {\n\tif len(s.data) == 0 {\n\t\treturn 0\n\t}\n\tret := s.data[len(s.data)-1]\n\ts.data = s.data[:len(s.data)-1]\n\treturn ret\n}\n\nfunc (s Stack) empty() bool {\n\treturn len(s.data) == 0\n}\n\nfunc minInt(a, b int) int ", "output": "{\n\tif a > b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}"} {"input": "package persistentvolume\n\nimport (\n\tutilfeature \"k8s.io/apiserver/pkg/util/feature\"\n\tapi \"k8s.io/kubernetes/pkg/apis/core\"\n\t\"k8s.io/kubernetes/pkg/features\"\n)\n\n\n\n\n\nfunc DropDisabledAlphaFields(pvSpec *api.PersistentVolumeSpec) ", "output": "{\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.BlockVolume) {\n\t\tpvSpec.VolumeMode = nil\n\t}\n}"} {"input": "package uaa\n\nimport (\n\t\"sort\"\n\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n)\n\ntype Prompt struct {\n\tKey string \n\tType string \n\tLabel string \n}\n\ntype PromptAnswer struct {\n\tKey string \n\tValue string\n}\n\n\n\ntype PromptsResp struct {\n\tPrompts map[string][]string \n}\n\nfunc (u UAAImpl) Prompts() ([]Prompt, error) {\n\tresp, err := u.client.Prompts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar prompts []Prompt\n\n\tfor key, pair := range resp.Prompts {\n\t\tprompts = append(prompts, Prompt{\n\t\t\tKey: key,\n\t\t\tType: pair[0],\n\t\t\tLabel: pair[1],\n\t\t})\n\t}\n\n\tsort.Sort(PromptSorting(prompts))\n\n\treturn prompts, nil\n}\n\nfunc (c Client) Prompts() (PromptsResp, error) {\n\tvar resp PromptsResp\n\n\terr := c.clientRequest.Get(\"/login\", &resp)\n\tif err != nil {\n\t\treturn resp, bosherr.WrapError(err, \"Requesting UAA prompts\")\n\t}\n\n\treturn resp, nil\n}\n\ntype PromptSorting []Prompt\n\nfunc (s PromptSorting) Len() int { return len(s) }\nfunc (s PromptSorting) Less(i, j int) bool { return s[i].Type > s[j].Type }\nfunc (s PromptSorting) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (p Prompt) IsPassword() bool ", "output": "{ return p.Type == \"password\" }"} {"input": "package iso20022\n\n\ntype StatisticsByPredefinedTimePeriods2 struct {\n\n\tHighestPriceValue12Months *PriceValue5 `xml:\"HghstPricVal12Mnths,omitempty\"`\n\n\tLowestPriceValue12Months *PriceValue5 `xml:\"LwstPricVal12Mnths,omitempty\"`\n\n\tOneYearPriceChange *PriceValueChange1 `xml:\"OneYrPricChng,omitempty\"`\n\n\tThreeYearPriceChange *PriceValueChange1 `xml:\"ThreeYrPricChng,omitempty\"`\n\n\tFiveYearPriceChange *PriceValueChange1 `xml:\"FiveYrPricChng,omitempty\"`\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddHighestPriceValue12Months() *PriceValue5 {\n\ts.HighestPriceValue12Months = new(PriceValue5)\n\treturn s.HighestPriceValue12Months\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddLowestPriceValue12Months() *PriceValue5 {\n\ts.LowestPriceValue12Months = new(PriceValue5)\n\treturn s.LowestPriceValue12Months\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddOneYearPriceChange() *PriceValueChange1 {\n\ts.OneYearPriceChange = new(PriceValueChange1)\n\treturn s.OneYearPriceChange\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddThreeYearPriceChange() *PriceValueChange1 {\n\ts.ThreeYearPriceChange = new(PriceValueChange1)\n\treturn s.ThreeYearPriceChange\n}\n\n\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddFiveYearPriceChange() *PriceValueChange1 ", "output": "{\n\ts.FiveYearPriceChange = new(PriceValueChange1)\n\treturn s.FiveYearPriceChange\n}"} {"input": "package memory\n\nimport (\n\t\"fmt\"\n)\n\n\ntype RAM struct {\n\tdata []byte\n\twindow []byte\n\taddrOffset uint16\n}\n\n\nfunc NewRAM(data []byte, addrOffset uint16) *RAM {\n\n\tr := RAM{data: data, addrOffset: addrOffset}\n\tr.SetWindow(0)\n\n\treturn &r\n}\n\n\n\nfunc (r *RAM) SetWindow(offset uint32) error {\n\n\tif uint32(len(r.data)) <= offset {\n\t\treturn fmt.Errorf(\"window offset out of range (%d)\", offset)\n\t}\n\n\tr.window = r.data[offset:]\n\n\treturn nil\n}\n\n\n\n\n\nfunc (r *RAM) Write(addr uint16, data byte) error {\n\n\tif r.addrOffset > addr {\n\t\treturn WriteOutOfRangeError(addr)\n\t}\n\n\tphysicalAddr := addr - r.addrOffset\n\n\tif uint(len(r.window)) <= uint(physicalAddr) {\n\t\treturn WriteOutOfRangeError(addr)\n\t}\n\n\tr.window[physicalAddr] = data\n\n\treturn nil\n}\n\nfunc (r *RAM) Read(addr uint16) (byte, error) ", "output": "{\n\n\tif r.addrOffset > addr {\n\t\treturn 0, ReadOutOfRangeError(addr)\n\t}\n\n\tphysicalAddr := addr - r.addrOffset\n\n\tif uint(len(r.window)) <= uint(physicalAddr) {\n\t\treturn 0, ReadOutOfRangeError(addr)\n\t}\n\n\treturn r.window[physicalAddr], nil\n}"} {"input": "package gonion\n\nimport (\n\t\"net/http\"\n)\n\n\n\ntype MiddlewareOptions struct {\n\tcomposer *Composer\n\trouteFilter func(*RouteModel) bool\n}\n\n\n\nfunc (mo *MiddlewareOptions) ChainLink(ctor func(http.Handler) http.Handler) {\n\tmo.composer.addMiddleware(ChainLink(ctor), mo.routeFilter)\n}\n\nfunc wrap(handler http.Handler) ChainLink {\n\treturn ChainLink(func(inner http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {\n\t\t\thandler.ServeHTTP(rw, r)\n\t\t\tinner.ServeHTTP(rw, r)\n\t\t})\n\t})\n}\n\n\nfunc (mo *MiddlewareOptions) Handler(handler http.Handler) {\n\tmo.composer.addMiddleware(wrap(handler), mo.routeFilter)\n}\n\n\n\n\n\nfunc (mo *MiddlewareOptions) Func(handler func(http.ResponseWriter, *http.Request)) ", "output": "{\n\tmo.Handler(http.HandlerFunc(handler))\n}"} {"input": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"strings\"\n)\n\ntype marshalerForTest struct {\n\tX string\n}\n\n\n\nfunc decode(str string) string {\n\tif len(str) == 0 {\n\t\treturn \"\"\n\t}\n\tb64 := base64.NewDecoder(base64.StdEncoding, strings.NewReader(str))\n\tbs := make([]byte, len(str))\n\tif n, err := b64.Read(bs); err != nil {\n\t\tpanic(err)\n\t} else {\n\t\tbs = bs[:n]\n\t}\n\treturn string(bs)\n}\n\nfunc (m marshalerForTest) MarshalJSON() ([]byte, error) {\n\treturn []byte(`\"MANUAL__` + encode(m.X) + `\"`), nil\n}\n\nfunc (m *marshalerForTest) UnmarshalJSON(text []byte) error {\n\tm.X = decode(strings.TrimPrefix(strings.Trim(string(text), `\"`), \"MANUAL__\"))\n\treturn nil\n}\n\nvar _ json.Marshaler = marshalerForTest{}\nvar _ json.Unmarshaler = &marshalerForTest{}\n\ntype typeForTest struct {\n\tS string\n\tM marshalerForTest\n\tI int8\n}\n\nfunc encode(str string) string ", "output": "{\n\tbuf := bytes.Buffer{}\n\tb64 := base64.NewEncoder(base64.StdEncoding, &buf)\n\tif _, err := b64.Write([]byte(str)); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := b64.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn buf.String()\n}"} {"input": "package servo_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n\t\"github.com/fgrosse/servo\"\n\t\"fmt\"\n)\n\nfunc TestServo(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Servo Test Suite\")\n}\n\ntype TestBundle struct {}\n\nfunc (b *TestBundle) Boot(kernel *servo.Kernel) {\n\tkernel.RegisterType(\"test_bundle.my_type\", NewService)\n}\n\ntype SomeService struct {}\n\nfunc NewRecursiveService(*SomeService) *SomeService {\n\treturn &SomeService{}\n}\n\nfunc NewService() *SomeService {\n\treturn &SomeService{}\n}\n\nfunc NewServiceWithParam(param interface{}) *SomeService {\n\tpanic(param)\n\treturn &SomeService{}\n}\n\n\ntype ServerMock struct {\n\tRunHasBeenCalled bool\n\tReturnError bool\n\n\tParameter1, Parameter2 string\n}\n\nfunc NewServerMockWithParams(param1, param2 string) *ServerMock {\n\tExpect(param1).To(Equal(\"foo\"), `NewServerMockWithParams should always be called with the values \"foo\" and \"bar\"`)\n\tExpect(param2).To(Equal(\"bar\"), `NewServerMockWithParams should always be called with the values \"foo\" and \"bar\"`)\n\n\treturn &ServerMock{\n\t\tParameter1: param1,\n\t\tParameter2: param2,\n\t}\n}\n\n\n\nfunc (s *ServerMock) Run() error ", "output": "{\n\ts.RunHasBeenCalled = true\n\tif s.ReturnError {\n\t\treturn fmt.Errorf(\"ServerMock was told to return an error!\")\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\ntype TopicMessage struct {\n source *Client\n text string\n}\n\n\n\nfunc (this *TopicMessage) Source() *Client {\n return this.source\n}\n\nfunc (this *TopicMessage) Text() string {\n return this.text\n}\n\nfunc NewTopicMessage(source *Client, text string) *TopicMessage ", "output": "{\n return &TopicMessage{source, text}\n}"} {"input": "package packr\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\nvar gil = &sync.Mutex{}\nvar data = map[string]map[string][]byte{}\n\n\nfunc PackBytes(box string, name string, bb []byte) {\n\tgil.Lock()\n\tdefer gil.Unlock()\n\tif _, ok := data[box]; !ok {\n\t\tdata[box] = map[string][]byte{}\n\t}\n\tdata[box][name] = bb\n}\n\n\n\n\nfunc PackJSONBytes(box string, name string, jbb string) error ", "output": "{\n\tbb := []byte{}\n\terr := json.Unmarshal([]byte(jbb), &bb)\n\tif err != nil {\n\t\treturn err\n\t}\n\tPackBytes(box, name, bb)\n\treturn nil\n}"} {"input": "package builder\n\nimport (\n\t\"sync\"\n\n\t\"github.com/rikvdh/ci/lib/config\"\n)\n\ntype jobCounter struct {\n\tmu sync.RWMutex\n\tjobCounter uint\n\tjobLimit uint\n\teventCh chan uint\n}\n\nfunc newJobCounter() *jobCounter {\n\treturn &jobCounter{\n\t\tjobCounter: 0,\n\t\tjobLimit: config.Get().ConcurrentBuilds,\n\t\teventCh: make(chan uint),\n\t}\n}\n\nfunc (j *jobCounter) Increment() {\n\tj.mu.Lock()\n\tj.jobCounter++\n\tj.mu.Unlock()\n\tj.publishEvent()\n}\n\nfunc (j *jobCounter) Decrement() {\n\tj.mu.Lock()\n\tj.jobCounter--\n\tj.mu.Unlock()\n\tj.publishEvent()\n}\n\n\n\nfunc (j *jobCounter) publishEvent() {\n\tj.mu.RLock()\n\tj.eventCh <- j.jobCounter\n\tj.mu.RUnlock()\n}\n\nfunc (j *jobCounter) GetEventChannel() <-chan uint {\n\tj.mu.RLock()\n\tdefer j.mu.RUnlock()\n\treturn j.eventCh\n}\n\nfunc (j *jobCounter) CanStartJob() bool ", "output": "{\n\tj.mu.RLock()\n\tdefer j.mu.RUnlock()\n\treturn (j.jobCounter < j.jobLimit)\n}"} {"input": "package util\n\nimport \"os/exec\"\n\n\n\ntype binRunner func(string, ...string) ([]byte, error)\n\n\n\nfunc defaultBinRunner(bin string, args ...string) ([]byte, error) {\n\treturn exec.Command(bin, args...).CombinedOutput()\n}\n\n\n\ntype Permissions struct {\n\tbinRunner binRunner\n}\n\n\n\nfunc NewPermissions() *Permissions {\n\treturn &Permissions{\n\t\tbinRunner: defaultBinRunner,\n\t}\n}\n\n\n\n\n\n\nfunc (p *Permissions) IsAdmin() (bool, error) ", "output": "{\n\treturn p.isAdmin()\n}"} {"input": "package net\n\nimport (\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\ntype Endpoint interface {\n\tHostName() string\n\tPort() int\n}\n\ntype defaultEndpoint struct {\n\thostname string\n\tport int\n}\n\nfunc (e defaultEndpoint) HostName() string {\n\treturn e.hostname\n}\nfunc (e defaultEndpoint) Port() int {\n\treturn e.port\n}\n\nfunc NewEndpoint(hostname string, port int) Endpoint {\n\treturn defaultEndpoint{hostname, port}\n}\n\n\n\nfunc FromUrl(u url.URL) Endpoint ", "output": "{\n\tparts := strings.Split(u.Host, \":\")\n\tif len(parts) != 2 {\n\t\treturn nil\n\t}\n\tport, _ := strconv.Atoi(parts[1])\n\treturn NewEndpoint(parts[0], port)\n}"} {"input": "package netutil\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype ConnWrapper struct {\n\tio.Reader\n\tio.Writer\n\tUnderlyingConn net.Conn\n\tReadCloser io.Closer\n\tWriteCloser io.Closer\n}\n\nvar _ net.Conn = new(ConnWrapper)\n\nfunc (c *ConnWrapper) Close() error {\n\tvar multiErr MultiError\n\tif c.ReadCloser != nil {\n\t\tmultiErr.RecordError(c.ReadCloser.Close())\n\t}\n\tif c.WriteCloser != nil {\n\t\tmultiErr.RecordError(c.WriteCloser.Close())\n\t}\n\tmultiErr.RecordError(c.UnderlyingConn.Close())\n\treturn multiErr.ToError()\n}\n\nfunc (c *ConnWrapper) LocalAddr() net.Addr { return c.UnderlyingConn.LocalAddr() }\nfunc (c *ConnWrapper) RemoteAddr() net.Addr { return c.UnderlyingConn.RemoteAddr() }\nfunc (c *ConnWrapper) SetDeadline(t time.Time) error { return c.UnderlyingConn.SetDeadline(t) }\n\nfunc (c *ConnWrapper) SetWriteDeadline(t time.Time) error { return c.UnderlyingConn.SetWriteDeadline(t) }\n\nfunc (c *ConnWrapper) SetReadDeadline(t time.Time) error ", "output": "{ return c.UnderlyingConn.SetReadDeadline(t) }"} {"input": "package rng\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\n\ntype CauchyGenerator struct {\n\tuniform *UniformGenerator\n}\n\n\n\n\nfunc NewCauchyGenerator(seed int64) *CauchyGenerator {\n\turng := NewUniformGenerator(seed)\n\treturn &CauchyGenerator{urng}\n}\n\n\nfunc (crng CauchyGenerator) Cauchy(x0, gamma float64) float64 {\n\tif !(gamma > 0.0) {\n\t\tpanic(fmt.Sprintf(\"Invalid parameter gamma: %.2f\", gamma))\n\t}\n\treturn crng.cauchy(x0, gamma)\n}\n\n\n\n\nfunc (crng CauchyGenerator) cauchy(x0, gamma float64) float64 {\n\treturn x0 + gamma*math.Tan(math.Pi*(crng.uniform.Float64()-0.5))\n}\n\nfunc (crng CauchyGenerator) StandardCauchy() float64 ", "output": "{\n\treturn crng.cauchy(0.0, 1.0)\n}"} {"input": "package google\n\nimport (\n\t\"github.com/hashicorp/vault/logical\"\n\t\"github.com/hashicorp/vault/logical/framework\"\n)\n\nconst BackendName = \"google\"\n\n\nfunc Factory(conf *logical.BackendConfig) (logical.Backend, error) {\n\tb := Backend()\n\t_, err := b.Setup(conf)\n\tif err != nil {\n\t\treturn b, err\n\t}\n\treturn b, nil\n}\n\nconst googleBackendHelp = `\nThe Google credential provider allows you to authenticate with Google. You must own a registered google application.\n`+ writeConfigPathHelp + `\nThen, proceed to generate a personal access token by browsing to a google url.\n` + readCodeUrlPathHelp + `\n\n Example: vault auth -method=` + BackendName + ` ` + googleAuthCodeParameterName + `=\n\n the user's google domain will be matched against the domain you configured for the backend, e.g. example.com (or empty string for none)\n\nKey/Value Pairs:\n\n mount=` + BackendName + ` The mountpoint for the Google credential provider.\n Defaults to \"` + BackendName + `\"\n\n ` + googleAuthCodeParameterName + `= The Google access code for authentication.\n`\n\nconst usersToPoliciesMapPath = \"users\"\n\n\n\n\ntype backend struct {\n\t*framework.Backend\n\n\tMap *framework.PolicyMap\n}\n\nfunc Backend() *backend ", "output": "{\n\tvar b backend\n\tb.Map = &framework.PolicyMap{\n\t\tPathMap: framework.PathMap{\n\t\t\tName: usersToPoliciesMapPath,\n\t\t},\n\t}\n\tb.Backend = &framework.Backend{\n\t\tHelp: googleBackendHelp,\n\n\t\tPathsSpecial: &logical.Paths{\n\t\t\tUnauthenticated: []string{\n\t\t\t\tloginPath,\n\t\t\t\tcodeURLPath,\n\t\t\t},\n\t\t},\n\n\t\tPaths: append([]*framework.Path{\n\t\t\tpathConfig(&b),\n\t\t\tpathLogin(&b),\n\t\t\tpathCodeURL(&b),\n\t\t}, b.Map.Paths()...),\n\n\t\tAuthRenew: b.pathLoginRenew,\n\t}\n\n\treturn &b\n}"} {"input": "package http\n\nimport (\n\t\"net/http\"\n\t\"reflect\"\n)\n\n\ntype JSONErrorBuilder interface {\n\tBuild() JSONError\n\n\tCustomError(code int, errorType, msg string) JSONErrorBuilder\n\n\tFromError(e error) JSONErrorBuilder\n\n\tMessage(string) JSONErrorBuilder\n\n\tStatus(int) JSONErrorBuilder\n\n\tURL(string) JSONErrorBuilder\n}\n\ntype jsonErrorBuilder struct {\n\tinstance JSONError\n}\n\n\n\nfunc NewJSONError() JSONErrorBuilder {\n\treturn &jsonErrorBuilder{JSONError{\n\t\tStatus: http.StatusInternalServerError,\n\t}}\n}\n\nfunc (b *jsonErrorBuilder) Build() JSONError {\n\treturn b.instance\n}\n\nfunc (b *jsonErrorBuilder) CustomError(\n\tcode int,\n\terrorType,\n\tmsg string,\n) JSONErrorBuilder {\n\tb.instance.Code = code\n\tb.instance.Type = errorType\n\tb.instance.Message = msg\n\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) FromError(e error) JSONErrorBuilder {\n\terrType := reflect.TypeOf(e)\n\tvar typeName string\n\tif errType.Kind() == reflect.Ptr {\n\t\ttypeName = errType.Elem().Name()\n\t} else {\n\t\ttypeName = errType.Name()\n\t}\n\n\tb.instance.Type = typeName\n\tb.instance.Message = e.Error()\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) Message(msg string) JSONErrorBuilder {\n\tb.instance.Message = msg\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) Status(status int) JSONErrorBuilder {\n\tb.instance.Status = status\n\treturn b\n}\n\n\n\nvar _ JSONErrorBuilder = (*jsonErrorBuilder)(nil)\n\nfunc (b *jsonErrorBuilder) URL(url string) JSONErrorBuilder ", "output": "{\n\tb.instance.MoreInfo = url\n\treturn b\n}"} {"input": "package cloudsigma\n\nconst (\n\tEndpointBurstUsage = \"burstusage\"\n)\n\n\ntype BurstUsage struct {\n\tArgs *Args\n}\n\n\nfunc NewBurstUsage() *BurstUsage {\n\to := BurstUsage{}\n\to.Args = NewArgs()\n\to.Args.Resource = EndpointBurstUsage\n\treturn &o\n}\n\n\n\n\nfunc (o *BurstUsage) NewList() *Args ", "output": "{\n\to.Args.Verb = \"GET\"\n\to.Args.RequiresAuth = true\n\treturn o.Args\n}"} {"input": "package db\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"time\"\n\n\t\"github.com/boltdb/bolt\"\n\n\t\"github.com/michaelorr/goodall/pkg/metrics\"\n)\n\n\n\nfunc Init(conn *bolt.DB) error {\n\tfor bucket, _ := range metrics.BucketMap {\n\t\terr := conn.Update(func(tx *bolt.Tx) error {\n\t\t\t_, err := tx.CreateBucketIfNotExists([]byte(bucket))\n\t\t\treturn err\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc Ftob(f float64) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\terr := binary.Write(buf, binary.BigEndian, f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}\n\nfunc Btof(b []byte) (float64, error) {\n\tvar f float64\n\tbuf := bytes.NewReader(b)\n\terr := binary.Read(buf, binary.BigEndian, &f)\n\tif err != nil {\n\t\treturn f, err\n\t}\n\treturn f, nil\n}\n\nfunc Open(path string) (*bolt.DB, error) ", "output": "{\n\treturn bolt.Open(path, 0600, &bolt.Options{Timeout: 1 * time.Second})\n}"} {"input": "package jwt\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype Token struct {\n\tExpiryDate int64\n\tRawToken string\n}\n\n\n\nconst expirationSkew = 30\n\n\nfunc (t *Token) Expired() bool {\n\treturn time.Now().Unix()+expirationSkew > t.ExpiryDate\n}\n\n\n\nfunc (t *Token) GetAuthenticationHeaderValue() string {\n\treturn fmt.Sprintf(\"Bearer %s\", t.RawToken)\n}\n\n\n\n\n\ntype tokenPayload struct {\n\tExpirationTime int64 `json:\"exp\"`\n}\n\n\n\n\n\nfunc New(token string) (Token, error) {\n\tif len(token) == 0 {\n\t\treturn Token{}, errors.New(\"no token given, a token should be set\")\n\t}\n\n\ttokenParts := strings.Split(token, \".\")\n\tif len(tokenParts) != 3 {\n\t\treturn Token{}, fmt.Errorf(\"invalid token '%s' given, token should exist at least of 3 parts\", token)\n\t}\n\n\tjsonBody, err := base64.RawStdEncoding.DecodeString(tokenParts[1])\n\tif err != nil {\n\t\treturn Token{}, errors.New(\"could not decode token, invalid base64\")\n\t}\n\n\tvar tokenRequest tokenPayload\n\terr = json.Unmarshal(jsonBody, &tokenRequest)\n\tif err != nil {\n\t\treturn Token{}, errors.New(\"could not read token body, invalid json\")\n\t}\n\n\treturn Token{\n\t\tRawToken: token,\n\t\tExpiryDate: tokenRequest.ExpirationTime,\n\t}, nil\n}\n\nfunc (t *Token) String() string ", "output": "{\n\treturn t.RawToken\n}"} {"input": "package generator\n\nimport (\n\t\"go/ast\"\n\t\"go/token\"\n)\n\nfunc makeBasicLit(kind token.Token, value string) *ast.BasicLit {\n\treturn &ast.BasicLit{Kind: kind, Value: value}\n}\n\nfunc makeVector(typ ast.Expr, elements []ast.Expr) *ast.CompositeLit {\n\treturn makeCompositeLit(&ast.ArrayType{Elt: typ}, elements)\n}\n\n\n\nfunc makeCompositeLit(typ ast.Expr, elements []ast.Expr) *ast.CompositeLit ", "output": "{\n\treturn &ast.CompositeLit{\n\t\tType: typ,\n\t\tElts: elements,\n\t}\n}"} {"input": "package fakes\n\nimport (\n\t\"net\"\n\t\"sync\"\n\n\t\"github.com/cloudfoundry-incubator/diego-ssh/cf-plugin/cmd\"\n)\n\ntype FakeListenerFactory struct {\n\tListenStub func(network, address string) (net.Listener, error)\n\tlistenMutex sync.RWMutex\n\tlistenArgsForCall []struct {\n\t\tnetwork string\n\t\taddress string\n\t}\n\tlistenReturns struct {\n\t\tresult1 net.Listener\n\t\tresult2 error\n\t}\n}\n\n\n\nfunc (fake *FakeListenerFactory) ListenCallCount() int {\n\tfake.listenMutex.RLock()\n\tdefer fake.listenMutex.RUnlock()\n\treturn len(fake.listenArgsForCall)\n}\n\nfunc (fake *FakeListenerFactory) ListenArgsForCall(i int) (string, string) {\n\tfake.listenMutex.RLock()\n\tdefer fake.listenMutex.RUnlock()\n\treturn fake.listenArgsForCall[i].network, fake.listenArgsForCall[i].address\n}\n\nfunc (fake *FakeListenerFactory) ListenReturns(result1 net.Listener, result2 error) {\n\tfake.ListenStub = nil\n\tfake.listenReturns = struct {\n\t\tresult1 net.Listener\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nvar _ cmd.ListenerFactory = new(FakeListenerFactory)\n\nfunc (fake *FakeListenerFactory) Listen(network string, address string) (net.Listener, error) ", "output": "{\n\tfake.listenMutex.Lock()\n\tfake.listenArgsForCall = append(fake.listenArgsForCall, struct {\n\t\tnetwork string\n\t\taddress string\n\t}{network, address})\n\tfake.listenMutex.Unlock()\n\tif fake.ListenStub != nil {\n\t\treturn fake.ListenStub(network, address)\n\t} else {\n\t\treturn fake.listenReturns.result1, fake.listenReturns.result2\n\t}\n}"} {"input": "package sqlmock\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\nvar mock = &sqlmock{}\n\nfunc ExampleNewErrorResult() {\n\tdb, mock, _ := New()\n\tresult := NewErrorResult(fmt.Errorf(\"some error\"))\n\tmock.ExpectExec(\"^INSERT (.+)\").WillReturnResult(result)\n\tres, _ := db.Exec(\"INSERT something\")\n\t_, err := res.LastInsertId()\n\tfmt.Println(err)\n}\n\n\n\nfunc TestShouldReturnValidSqlDriverResult(t *testing.T) {\n\tresult := NewResult(1, 2)\n\tid, err := result.LastInsertId()\n\tif 1 != id {\n\t\tt.Errorf(\"Expected last insert id to be 1, but got: %d\", id)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"expected no error, but got: %s\", err)\n\t}\n\taffected, err := result.RowsAffected()\n\tif 2 != affected {\n\t\tt.Errorf(\"Expected affected rows to be 2, but got: %d\", affected)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"expected no error, but got: %s\", err)\n\t}\n}\n\nfunc TestShouldReturnErroeSqlDriverResult(t *testing.T) {\n\tresult := NewErrorResult(fmt.Errorf(\"some error\"))\n\t_, err := result.LastInsertId()\n\tif err == nil {\n\t\tt.Error(\"expected error, but got none\")\n\t}\n\t_, err = result.RowsAffected()\n\tif err == nil {\n\t\tt.Error(\"expected error, but got none\")\n\t}\n}\n\nfunc ExampleNewResult() ", "output": "{\n\tvar lastInsertID, affected int64\n\tresult := NewResult(lastInsertID, affected)\n\tmock.ExpectExec(\"^INSERT (.+)\").WillReturnResult(result)\n\tfmt.Println(mock.ExpectationsWereMet())\n}"} {"input": "package classfile\n\n\ntype ConstantStringInfo struct {\n\tcp ConstantPool\n\tstringIndex uint16\n}\n\n\nfunc (self *ConstantStringInfo) String() string {\n\treturn self.cp.getUtf8(self.stringIndex)\n}\nfunc (self *ConstantStringInfo) toString() string {\n\treturn \"String\"\n}\n\nfunc (self *ConstantStringInfo) readInfo(reader *ClassReader) ", "output": "{\n\tself.stringIndex = reader.readUint16()\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\n\n\nfunc setTimeval(sec, usec int64) Timeval {\n\treturn Timeval{Sec: sec, Usec: usec}\n}\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint64(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint64(length)\n}\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\nfunc setTimespec(sec, nsec int64) Timespec ", "output": "{\n\treturn Timespec{Sec: sec, Nsec: nsec}\n}"} {"input": "package main\n\nimport \"strings\"\n\nvar x = make([]byte, 10)\n\nfunc main() {\n\ttest1()\n\ttest2()\n\ttest3()\n\ttest4()\n\ttest5()\n\ttest6()\n\ttest7()\n}\n\nfunc mustRecover(s string) {\n\tv := recover()\n\tif v == nil {\n\t\tpanic(\"expected panic\")\n\t}\n\tif e := v.(error).Error(); strings.Index(e, s) < 0 {\n\t\tpanic(\"want: \" + s + \"; have: \" + e)\n\t}\n}\n\nfunc test1() {\n\tdefer mustRecover(\"index\")\n\tprintln(x[123])\n}\n\nfunc test2() {\n\tdefer mustRecover(\"slice\")\n\tprintln(x[5:15])\n}\n\nfunc test3() {\n\tdefer mustRecover(\"slice\")\n\tvar lo = 11\n\tvar hi = 9\n\tprintln(x[lo:hi])\n}\n\nfunc test4() {\n\tdefer mustRecover(\"interface\")\n\tvar x interface{} = 1\n\tprintln(x.(float32))\n}\n\ntype T struct {\n\ta, b int\n\tc []int\n}\n\n\n\nfunc test6() {\n\tdefer mustRecover(\"unhashable\")\n\tvar x T\n\tvar z interface{} = x\n\tm := make(map[interface{}]int)\n\tm[z] = 1\n}\n\nfunc test7() {\n\tdefer mustRecover(\"divide by zero\")\n\tvar x, y int\n\tprintln(x / y)\n}\n\nfunc test5() ", "output": "{\n\tdefer mustRecover(\"uncomparable\")\n\tvar x T\n\tvar z interface{} = x\n\tprintln(z != z)\n}"} {"input": "package linode\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/resource\"\n)\n\nfunc TestAccDataSourceLinodeImage(t *testing.T) {\n\tt.Parallel()\n\n\timageID := \"linode/debian8\"\n\tresourceName := \"data.linode_image.foobar\"\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testDataSourceLinodeImage(imageID),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\tresource.TestCheckResourceAttr(resourceName, \"id\", imageID),\n\t\t\t\t\tresource.TestCheckResourceAttr(resourceName, \"label\", \"Debian 8\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(resourceName, \"description\", \"\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(resourceName, \"is_public\", \"true\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(resourceName, \"type\", \"manual\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(resourceName, \"size\", \"1300\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(resourceName, \"vendor\", \"Debian\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\n\n\nfunc testDataSourceLinodeImage(imageID string) string ", "output": "{\n\treturn fmt.Sprintf(`\ndata \"linode_image\" \"foobar\" {\n\tid = \"%s\"\n}`, imageID)\n}"} {"input": "package algorithm\n\nimport (\n\t\"github.com/concourse/concourse/atc/db\"\n)\n\ntype NameToIDMap map[string]int\n\ntype relatedInputConfigs struct {\n\tpassedJobs map[int]bool\n\tinputConfigs db.InputConfigs\n}\n\n\n\nfunc groupInputsConfigsByPassedJobs(passedInputConfigs db.InputConfigs) []relatedInputConfigs {\n\tgroupedPassedInputConfigs := []relatedInputConfigs{}\n\tfor _, inputConfig := range passedInputConfigs {\n\t\tvar index int\n\t\tvar found bool\n\n\t\tfor passedJob := range inputConfig.Passed {\n\t\t\tfor groupIndex, group := range groupedPassedInputConfigs {\n\t\t\t\tif group.passedJobs[passedJob] {\n\t\t\t\t\tfound = true\n\t\t\t\t\tindex = groupIndex\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif found {\n\t\t\tgroupedPassedInputConfigs[index].inputConfigs = append(groupedPassedInputConfigs[index].inputConfigs, inputConfig)\n\n\t\t\tfor inputPassedJob := range inputConfig.Passed {\n\t\t\t\tif !groupedPassedInputConfigs[index].passedJobs[inputPassedJob] {\n\t\t\t\t\tgroupedPassedInputConfigs[index].passedJobs[inputPassedJob] = true\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tpassedJobs := map[int]bool{}\n\t\t\tfor jobID := range inputConfig.Passed {\n\t\t\t\tpassedJobs[jobID] = true\n\t\t\t}\n\n\t\t\tgroupedPassedInputConfigs = append(groupedPassedInputConfigs, relatedInputConfigs{\n\t\t\t\tpassedJobs: passedJobs,\n\t\t\t\tinputConfigs: db.InputConfigs{inputConfig},\n\t\t\t})\n\t\t}\n\t}\n\n\treturn groupedPassedInputConfigs\n}\n\nfunc constructResolvers(\n\tversions db.VersionsDB,\n\tinputs db.InputConfigs,\n) ([]Resolver, error) ", "output": "{\n\tresolvers := []Resolver{}\n\tinputConfigsWithPassed := db.InputConfigs{}\n\tfor _, input := range inputs {\n\t\tif len(input.Passed) == 0 {\n\t\t\tif input.PinnedVersion != nil {\n\t\t\t\tresolvers = append(resolvers, NewPinnedResolver(versions, input))\n\t\t\t} else {\n\t\t\t\tresolvers = append(resolvers, NewIndividualResolver(versions, input))\n\t\t\t}\n\t\t} else {\n\t\t\tinputConfigsWithPassed = append(inputConfigsWithPassed, input)\n\t\t}\n\t}\n\n\tgroupedInputConfigs := groupInputsConfigsByPassedJobs(inputConfigsWithPassed)\n\n\tfor _, group := range groupedInputConfigs {\n\t\tresolvers = append(resolvers, NewGroupResolver(versions, group.inputConfigs))\n\t}\n\n\treturn resolvers, nil\n}"} {"input": "package consul\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/abronan/valkeyrie/store\"\n\t\"github.com/abronan/valkeyrie/store/consul\"\n\t\"github.com/containous/traefik/old/provider\"\n\t\"github.com/containous/traefik/old/provider/kv\"\n\t\"github.com/containous/traefik/old/types\"\n\t\"github.com/containous/traefik/safe\"\n)\n\nvar _ provider.Provider = (*Provider)(nil)\n\n\ntype Provider struct {\n\tkv.Provider `mapstructure:\",squash\" export:\"true\"`\n}\n\n\nfunc (p *Provider) Init(constraints types.Constraints) error {\n\terr := p.Provider.Init(constraints)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstore, err := p.CreateStore()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to Connect to KV store: %v\", err)\n\t}\n\n\tp.SetKVClient(store)\n\treturn nil\n}\n\n\n\nfunc (p *Provider) Provide(configurationChan chan<- types.ConfigMessage, pool *safe.Pool) error {\n\treturn p.Provider.Provide(configurationChan, pool)\n}\n\n\n\n\nfunc (p *Provider) CreateStore() (store.Store, error) ", "output": "{\n\tp.SetStoreType(store.CONSUL)\n\tconsul.Register()\n\treturn p.Provider.CreateStore()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\ntype BuildCommand struct {\n\tType string `short:\"t\" long:\"type\" description:\"Type of environment.\"`\n\tVersion string `short:\"v\" long:\"version\" description:\"Version of environment type.\"`\n\tImage string `short:\"i\" long:\"image\" description:\"Image to use for creating environment.\"`\n\tForcePull bool `long:\"force-pull\" description:\"Force pulling base image.\"`\n}\n\nvar buildCommand BuildCommand\n\nfunc (ccommand *BuildCommand) toBuildOpts(sc SystemClient) BuildOpts {\n\treturn BuildOpts{\n\t\tImage: ImageOpts{\n\t\t\tType: ccommand.Type,\n\t\t\tVersion: ccommand.Version,\n\t\t\tImage: ccommand.Image,\n\t\t},\n\t\tForcePull: ccommand.ForcePull,\n\t\tUsername: sc.Username(),\n\t\tUID: sc.UID(),\n\t\tGID: sc.GID(),\n\t}\n}\n\n\n\nfunc init() {\n\t_, err := parser.AddCommand(\"build\",\n\t\t\"Build an image.\",\n\t\t\"\",\n\t\t&buildCommand)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n\nfunc (x *BuildCommand) Execute(args []string) error ", "output": "{\n\tdc, err := NewDockerClient(globalOptions.toConnectOpts())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsc, err := NewSystemClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\timage, err := BuildImage(dc, buildCommand.toBuildOpts(sc), os.Stdout)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Built image: \", image)\n\n\treturn nil\n}"} {"input": "package catalogs\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewGetNodesIdentifierCatalogsParams() *GetNodesIdentifierCatalogsParams {\n\tvar ()\n\treturn &GetNodesIdentifierCatalogsParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\n\n\n\ntype GetNodesIdentifierCatalogsParams struct {\n\n\tIdentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *GetNodesIdentifierCatalogsParams) WithIdentifier(identifier string) *GetNodesIdentifierCatalogsParams {\n\to.Identifier = identifier\n\treturn o\n}\n\n\nfunc (o *GetNodesIdentifierCatalogsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"identifier\", o.Identifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewGetNodesIdentifierCatalogsParamsWithTimeout(timeout time.Duration) *GetNodesIdentifierCatalogsParams ", "output": "{\n\tvar ()\n\treturn &GetNodesIdentifierCatalogsParams{\n\n\t\ttimeout: timeout,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"compress/gzip\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\nfunc main() {\n\tfpath := \"test.tar.gz\"\n\tif err := toGzip(\"Hello World!\", fpath); err != nil {\n\t\tpanic(err)\n\t}\n\tif tb, err := toBytes(fpath); err != nil {\n\t\tpanic(err)\n\t} else {\n\t\tfmt.Println(fpath, \":\", string(tb))\n\t}\n\tos.Remove(fpath)\n}\n\n\n\n\nfunc toBytes(fpath string) ([]byte, error) {\n\tf, err := os.OpenFile(fpath, os.O_RDONLY, 0444)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tfz, err := gzip.NewReader(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer fz.Close()\n\n\ts, err := ioutil.ReadAll(fz)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s, nil\n}\n\nfunc toGzip(txt, fpath string) error ", "output": "{\n\tf, err := os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0777)\n\tif err != nil {\n\t\tf, err = os.Create(fpath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tdefer f.Close()\n\tgw := gzip.NewWriter(f)\n\tif _, err := gw.Write([]byte(txt)); err != nil {\n\t\treturn err\n\t}\n\tgw.Close()\n\tgw.Flush()\n\treturn nil\n}"} {"input": "package metric\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\ntype (\n\tCollectFnOpts struct {\n\t\tMethod string\n\t\tStart time.Time\n\t\tErr error\n\t\tAdditionalProps map[string]interface{}\n\t}\n\n\tCounterFn func(vec *prometheus.CounterVec, o CollectFnOpts)\n\n\tHistogramFn func(vec *prometheus.HistogramVec, o CollectFnOpts)\n\n\tVecOpts struct {\n\t\tName string\n\t\tHelp string\n\t\tLabelNames []string\n\n\t\tCounterFn CounterFn\n\t\tHistogramFn HistogramFn\n\t}\n)\n\ntype metricOpts struct {\n\tnamespace string\n\tservice string\n\tserviceSuffix string\n\tcounterMetrics map[string]VecOpts\n\thistogramMetrics map[string]VecOpts\n}\n\nfunc (o metricOpts) serviceName() string {\n\tif o.serviceSuffix != \"\" {\n\t\treturn fmt.Sprintf(\"%s_%s\", o.service, o.serviceSuffix)\n\t}\n\treturn o.service\n}\n\n\ntype ClientOptFn func(*metricOpts)\n\n\n\n\n\nfunc WithSuffix(suffix string) ClientOptFn {\n\treturn func(opts *metricOpts) {\n\t\topts.serviceSuffix = suffix\n\t}\n}\n\nfunc ApplyMetricOpts(opts ...ClientOptFn) *metricOpts {\n\to := metricOpts{}\n\tfor _, opt := range opts {\n\t\topt(&o)\n\t}\n\treturn &o\n}\n\nfunc (o *metricOpts) ApplySuffix(prefix string) string {\n\tif o.serviceSuffix != \"\" {\n\t\treturn fmt.Sprintf(\"%s_%s\", prefix, o.serviceSuffix)\n\t}\n\treturn prefix\n}\n\nfunc WithVec(opts VecOpts) ClientOptFn ", "output": "{\n\treturn func(o *metricOpts) {\n\t\tif opts.CounterFn != nil {\n\t\t\tif o.counterMetrics == nil {\n\t\t\t\to.counterMetrics = make(map[string]VecOpts)\n\t\t\t}\n\t\t\to.counterMetrics[opts.Name] = opts\n\t\t}\n\t}\n}"} {"input": "package project\n\nimport (\n\t\"testing\"\n)\n\nfunc TestTrimSpaceAndNonPrintable_unicode(t *testing.T) {\n\tt.Parallel()\n\n\textraChars := \"state\\uFEFF\"\n\twant := \"state\"\n\tgot := TrimSpaceAndNonPrintable(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}\n\nfunc TestTrimSpaceAndNonPrintable_space(t *testing.T) {\n\tt.Parallel()\n\n\textraChars := \" state \\r\\t\"\n\twant := \"state\"\n\tgot := TrimSpaceAndNonPrintable(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}\n\n\n\nfunc TestTrimSpace_space(t *testing.T) {\n\tt.Parallel()\n\n\textraChars := \" state \\r\\t\"\n\twant := \"state\"\n\tgot := TrimSpace(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}\n\nfunc TestTrimSpace_unicode(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\textraChars := \"state\\uFEFF\"\n\twant := \"state\"\n\tgot := TrimSpace(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}"} {"input": "package validation\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\nfunc ExampleErrIfNotOSBName() {\n\tfmt.Println(\"Good is nil:\", ErrIfNotOSBName(\"google-storage\", \"my-field\") == nil)\n\tfmt.Println(\"Bad:\", ErrIfNotOSBName(\"google storage\", \"my-field\"))\n\n}\n\nfunc ExampleErrIfNotJSONSchemaType() {\n\tfmt.Println(\"Good is nil:\", ErrIfNotJSONSchemaType(\"string\", \"my-field\") == nil)\n\tfmt.Println(\"Bad:\", ErrIfNotJSONSchemaType(\"str\", \"my-field\"))\n\n}\n\n\n\nfunc ExampleErrIfNotTerraformIdentifier() {\n\tfmt.Println(\"Good is nil:\", ErrIfNotTerraformIdentifier(\"good_id\", \"my-field\") == nil)\n\tfmt.Println(\"Bad:\", ErrIfNotTerraformIdentifier(\"bad id\", \"my-field\"))\n\n}\n\nfunc ExampleErrIfNotJSON() {\n\tfmt.Println(\"Good is nil:\", ErrIfNotJSON(json.RawMessage(\"{}\"), \"my-field\") == nil)\n\tfmt.Println(\"Bad:\", ErrIfNotJSON(json.RawMessage(\"\"), \"my-field\"))\n\n}\n\nfunc ExampleErrIfNotHCL() ", "output": "{\n\tfmt.Println(\"Good HCL is nil:\", ErrIfNotHCL(`provider \"google\" {\n\t\tcredentials = \"${file(\"account.json\")}\"\n\t\tproject = \"my-project-id\"\n\t\tregion = \"us-central1\"\n\t}`, \"my-field\") == nil)\n\n\tfmt.Println(\"Good JSON is nil:\", ErrIfNotHCL(`{\"a\":42, \"s\":\"foo\"}`, \"my-field\") == nil)\n\n\tfmt.Println(\"Bad:\", ErrIfNotHCL(\"google storage\", \"my-field\"))\n\n}"} {"input": "package parse\n\n\nimport (\n\t\"strings\"\n)\n\n\n\n\n\nfunc EqualSlicesFoldPrefix(a, prefix []string) bool {\n\tl, lprefix := len(a), len(prefix)\n\tswitch {\n\tcase lprefix == 0:\n\t\treturn true\n\tcase l < lprefix:\n\t\treturn false\n\tcase l > lprefix:\n\t\treturn EqualSlicesFold(a[:lprefix], prefix)\n\tdefault:\n\t\treturn EqualSlicesFold(a, prefix)\n\t}\n}\n\n\n\nfunc EqualSlicesFoldSuffix(a, suffix []string) bool {\n\tl, lsuffix := len(a), len(suffix)\n\tswitch {\n\tcase lsuffix == 0:\n\t\treturn true\n\tcase l < lsuffix:\n\t\treturn false\n\tcase l > lsuffix:\n\t\treturn EqualSlicesFold(a[l-lsuffix:], suffix)\n\tdefault:\n\t\treturn EqualSlicesFold(a, suffix)\n\t}\n}\n\n\n\nfunc EqualSlicesFold(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor k := range a {\n\t\tif !strings.EqualFold(a[k], b[k]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\nfunc EqualSlicesFoldSome(a []string, b ...[]string) bool {\n\tif len(a) == 0 && len(b) == 0 {\n\t\treturn true\n\t}\n\n\tfor k := range b {\n\t\tif EqualSlicesFold(a, b[k]) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc indent(s string, character string, size int) string ", "output": "{\n\tindent := strings.Repeat(character, size)\n\tlines := strings.Split(s, newLine)\n\tfor k, v := range lines {\n\t\tif len(v) > 0 {\n\t\t\tlines[k] = indent + v\n\t\t}\n\t}\n\treturn strings.Join(lines, newLine)\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realIAMInstanceProfile IAMInstanceProfile\n\n\nfunc (o *IAMInstanceProfile) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realIAMInstanceProfile\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = IAMInstanceProfile(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &IAMInstanceProfile{}\n\n\nfunc (o *IAMInstanceProfile) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\nvar _ fi.HasName = &IAMInstanceProfile{}\n\n\nfunc (o *IAMInstanceProfile) GetName() *string {\n\treturn o.Name\n}\n\n\n\n\n\nfunc (o *IAMInstanceProfile) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *IAMInstanceProfile) SetName(name string) ", "output": "{\n\to.Name = &name\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1beta1 \"k8s.io/metrics/pkg/client/clientset_generated/clientset/typed/metrics/v1beta1\"\n)\n\ntype FakeMetricsV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeMetricsV1beta1) NodeMetricses() v1beta1.NodeMetricsInterface {\n\treturn &FakeNodeMetricses{c}\n}\n\n\n\n\n\nfunc (c *FakeMetricsV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeMetricsV1beta1) PodMetricses(namespace string) v1beta1.PodMetricsInterface ", "output": "{\n\treturn &FakePodMetricses{c, namespace}\n}"} {"input": "package machinelearningservices\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) BaseClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package slack_incoming_webhooks\n\ntype Field struct {\n\tTitle string `json:\"title,omitempty\"`\n\tValue string `json:\"value,omitempty\"`\n\tShort bool `json:\"short,omitempty\"`\n}\n\n\n\nfunc (f Field) IsEmpty() bool ", "output": "{\n\treturn f.Title == \"\" &&\n\t\tf.Value == \"\" &&\n\t\t!f.Short\n}"} {"input": "package handlers\n\nimport (\n\t\"net/http\"\n\t\"appengine/user\"\n\t\"appengine\"\n\t\"appengine/datastore\"\n\t\"text/template\"\n\t\"time\"\n\n\t\"model\"\n\t\"model/booth\"\n\t\"util\"\n)\n\n\nfunc HandleBooths(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\thandleGetAllBooths(w, r)\n\t\tbreak;\n\tcase \"POST\":\n\t\thandleCreateBooth(w, r)\n\t\tbreak;\n\tdefault:\n\t\thttp.Error(w, \"\", http.StatusMethodNotAllowed)\n\t}\n}\n\n\n\n\n\nfunc handleCreateBooth(w http.ResponseWriter, r *http.Request) {\n\tc := appengine.NewContext(r)\n\tu := user.Current(c)\n\n\tutil.RedirectIfNotLoggedIn(w, r)\n\n\tb := model.Booth{\n\t\tAuthor: u.String(),\n\t\tDate: time.Now(),\n\t\tName: r.FormValue(\"name\"),\n\t}\n\n\tkey := datastore.NewIncompleteKey(c, \"Booth\", booth.Key(c))\n\t_, err := datastore.Put(c, key, &b)\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thttp.Redirect(w, r, \"/\", http.StatusCreated)\n}\n\nfunc handleGetAllBooths(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tc := appengine.NewContext(r)\n\n\tutil.RedirectIfNotLoggedIn(w, r)\n\n\tq := datastore.NewQuery(\"Booth\").Ancestor(booth.Key(c)).Order(\"-Date\").Limit(10)\n\tbooths := make([]model.Booth, 10)\n\n\tif _, err := q.GetAll(c, &booths); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tboothsTemplate, _ := template.ParseFiles(\"./templates/booths/index.html\")\n\n\tif err := boothsTemplate.Execute(w, booths); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}"} {"input": "package b\n\nimport \"a\"\n\nvar N n\n\ntype n struct{}\n\nfunc (r n) M1() int { return a.G1 }\nfunc (r n) M2() int { return a.G2 }\nfunc (r n) M3() int { return a.G3 }\nfunc (r n) M4() int { return a.G4 }\nfunc (r n) M5() int { return a.G5 }\nfunc (r n) M6() int { return a.G6 }\n\nfunc (r n) M8() int { return a.G8 }\nfunc (r n) M9() int { return a.G9 }\nfunc (r n) M10() int { return a.G10 }\n\nfunc (r n) M7() int ", "output": "{ return a.G7 }"} {"input": "package immortal\n\nimport (\n\t\"os/exec\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestWatchPidGetpidKill(t *testing.T) {\n\td := &Daemon{}\n\tch := make(chan error, 1)\n\tcmd := exec.Command(\"sleep\", \"100\")\n\tcmd.Start()\n\tpid := cmd.Process.Pid\n\tgo func() {\n\t\td.WatchPid(pid, ch)\n\t\tch <- cmd.Wait()\n\t}()\n\n\tselect {\n\tcase err := <-ch:\n\t\tif err != nil {\n\t\t\tif err.Error() != \"EXIT\" {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\tcase <-time.After(1 * time.Millisecond):\n\t\tif err := cmd.Process.Kill(); err != nil {\n\t\t\tt.Errorf(\"failed to kill: %s\", err)\n\t\t}\n\t}\n}\n\nfunc TestWatchPidGetpid(t *testing.T) ", "output": "{\n\tch := make(chan error, 1)\n\td := &Daemon{}\n\tcmd := exec.Command(\"go\", \"version\")\n\tcmd.Start()\n\tpid := cmd.Process.Pid\n\tgo func() {\n\t\td.WatchPid(pid, ch)\n\t\tch <- cmd.Wait()\n\t}()\n\tselect {\n\tcase <-time.After(time.Millisecond):\n\t\tsyscall.Kill(pid, syscall.SIGTERM)\n\tcase err := <-ch:\n\t\tif err != nil {\n\t\t\tif err.Error() != \"EXIT\" {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package kubernetes\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/api/apps/v1beta1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\n\t\"github.com/weaveworks/scope/report\"\n)\n\n\ntype StatefulSet interface {\n\tMeta\n\tSelector() (labels.Selector, error)\n\tGetNode(probeID string) report.Node\n}\n\ntype statefulSet struct {\n\t*v1beta1.StatefulSet\n\tMeta\n}\n\n\nfunc NewStatefulSet(s *v1beta1.StatefulSet) StatefulSet {\n\treturn &statefulSet{\n\t\tStatefulSet: s,\n\t\tMeta: meta{s.ObjectMeta},\n\t}\n}\n\n\n\nfunc (s *statefulSet) GetNode(probeID string) report.Node {\n\tdesiredReplicas := 1\n\tif s.Spec.Replicas != nil {\n\t\tdesiredReplicas = int(*s.Spec.Replicas)\n\t}\n\tlatests := map[string]string{\n\t\tNodeType: \"StatefulSet\",\n\t\tDesiredReplicas: fmt.Sprint(desiredReplicas),\n\t\tReplicas: fmt.Sprint(s.Status.Replicas),\n\t\treport.ControlProbeID: probeID,\n\t}\n\tif s.Status.ObservedGeneration != nil {\n\t\tlatests[ObservedGeneration] = fmt.Sprint(*s.Status.ObservedGeneration)\n\t}\n\treturn s.MetaNode(report.MakeStatefulSetNodeID(s.UID())).WithLatests(latests)\n}\n\nfunc (s *statefulSet) Selector() (labels.Selector, error) ", "output": "{\n\tselector, err := metav1.LabelSelectorAsSelector(s.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn selector, nil\n}"} {"input": "package core\n\nimport (\n\t\"github.com/google/blueprint\"\n)\n\ntype generateBinary struct {\n\tgenerateLibrary\n}\n\n\nvar _ generateLibraryInterface = (*generateBinary)(nil)\nvar _ singleOutputModule = (*generateBinary)(nil)\nvar _ splittable = (*generateBinary)(nil)\nvar _ blueprint.Module = (*generateBinary)(nil)\n\nfunc (m *generateBinary) generateInouts(ctx blueprint.ModuleContext, g generatorBackend) []inout {\n\treturn generateLibraryInouts(m, ctx, g, m.Properties.Headers)\n}\n\n\n\nfunc (m *generateBinary) libExtension() string {\n\treturn \"\"\n}\n\n\n\n\n\n\n\nfunc (m *generateBinary) GenerateBuildActions(ctx blueprint.ModuleContext) {\n\tif isEnabled(m) {\n\t\tg := getBackend(ctx)\n\t\tg.genBinaryActions(m, ctx)\n\t}\n}\n\n\n\nfunc genBinaryFactory(config *bobConfig) (blueprint.Module, []interface{}) {\n\tmodule := &generateBinary{}\n\tmodule.generateCommon.init(&config.Properties, GenerateProps{})\n\n\treturn module, []interface{}{\n\t\t&module.SimpleName.Properties,\n\t\t&module.generateCommon.Properties,\n\t\t&module.Properties,\n\t}\n}\n\nfunc (m *generateBinary) outputFileName() string ", "output": "{\n\treturn m.altName() + m.libExtension()\n}"} {"input": "package n3\n\nimport \"testing\"\n\nfunc getTestObject() N3 {\n\tn := N3{\n\t\tPrefix: \"http://purl.org/dc/elements/1.1/\",\n\t\tPrefixNS: \"dc\",\n\t\tURI: \"http://en.wikipedia.org/wiki/Tony_Benn\",\n\t\tItems: []N3Element{\n\t\t\tN3Element{\n\t\t\t\tKey: \"title\",\n\t\t\t\tValue: \"Tony Benn\",\n\t\t\t},\n\t\t\tN3Element{\n\t\t\t\tKey: \"publisher\",\n\t\t\t\tValue: \"Wikipedia\",\n\t\t\t},\n\t\t},\n\t}\n\treturn n\n}\n\n\n\nfunc TestWriteN3(t *testing.T) {\n\tn := getTestObject()\n\tn.WriteN3()\n\treturn\n}\n\nfunc TestN3(t *testing.T) ", "output": "{\n\tn := getTestObject()\n\tn.Print()\n\treturn\n}"} {"input": "package goZKP\n\nimport (\n\t\"errors\"\n\t\"math/big\"\n)\n\n\ntype ZZ struct {\n\tg *big.Int\n\tmodulo *big.Int\n}\n\nfunc (z *ZZ) Bytes() []byte {\n\treturn z.g.Bytes()\n}\n\nfunc (z *ZZ) Mul(x *ZZ) (*ZZ, error) {\n\tif x.modulo.Cmp(z.modulo) != 0 {\n\t\treturn nil, errors.New(\"Unmatched modulo in ZZ multiplication.\")\n\t}\n\tz.g.Mul(z.g, x.g)\n\tz.g.Mod(z.g, z.modulo)\n\treturn z, nil\n}\n\nfunc (z *ZZ) Exp(x *big.Int) *ZZ {\n\tz.g.Exp(z.g, x, z.modulo)\n\treturn z\n}\n\n\n\nfunc (z *ZZ) Inverse() *ZZ ", "output": "{\n\tz.g.ModInverse(z.g, z.modulo)\n\treturn z\n}"} {"input": "package ar\n\nimport (\n\t\"database/sql\"\n\t\"time\"\n)\n\ntype Executer struct {\n\tdb *sql.DB\n\tlogger *Logger\n}\n\n\n\nfunc (e *Executer) log(t time.Time, sql string, args ...interface{}) {\n\te.logger.Print(time.Now().Sub(t), sql, args)\n}\n\nfunc (e *Executer) Exec(q string, b ...interface{}) (sql.Result, error) ", "output": "{\n\tdefer e.log(time.Now(), q, b...)\n\treturn e.db.Exec(q, b...)\n}"} {"input": "package main\n\nimport \"fmt\"\n\nvar GoogleAccountID = \"32984782374\"\n\nfunc main() {\n}\n\n\n\nfunc getLikeCount() ", "output": "{\n\tfmt.Print(\"Your Google Account ID: \", GoogleAccountID)\n}"} {"input": "package htesting\n\nimport (\n\t\"path/filepath\"\n\n\t\"github.com/gohugoio/hugo/cache/filecache\"\n\t\"github.com/gohugoio/hugo/config\"\n\t\"github.com/gohugoio/hugo/helpers\"\n\t\"github.com/gohugoio/hugo/hugofs\"\n\t\"github.com/gohugoio/hugo/media\"\n\t\"github.com/gohugoio/hugo/output\"\n\t\"github.com/gohugoio/hugo/resources\"\n\t\"github.com/spf13/afero\"\n)\n\n\n\nfunc NewResourceTransformer(filename, content string) (resources.ResourceTransformer, error) {\n\tspec, err := NewTestResourceSpec()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewResourceTransformerForSpec(spec, filename, content)\n}\n\nfunc NewResourceTransformerForSpec(spec *resources.Spec, filename, content string) (resources.ResourceTransformer, error) {\n\tfilename = filepath.FromSlash(filename)\n\n\tfs := spec.Fs.Source\n\tif err := afero.WriteFile(fs, filename, []byte(content), 0777); err != nil {\n\t\treturn nil, err\n\t}\n\n\tr, err := spec.New(resources.ResourceSourceDescriptor{Fs: fs, SourceFilename: filename})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.(resources.ResourceTransformer), nil\n}\n\nfunc NewTestResourceSpec() (*resources.Spec, error) ", "output": "{\n\tcfg := config.New()\n\tcfg.Set(\"baseURL\", \"https:example.org\")\n\tcfg.Set(\"publishDir\", \"public\")\n\n\timagingCfg := map[string]interface{}{\n\t\t\"resampleFilter\": \"linear\",\n\t\t\"quality\": 68,\n\t\t\"anchor\": \"left\",\n\t}\n\n\tcfg.Set(\"imaging\", imagingCfg)\n\n\tfs := hugofs.NewFrom(hugofs.NewBaseFileDecorator(afero.NewMemMapFs()), cfg)\n\n\ts, err := helpers.NewPathSpec(fs, cfg, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilecaches, err := filecache.NewCaches(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tspec, err := resources.NewSpec(s, filecaches, nil, nil, nil, nil, output.DefaultFormats, media.DefaultTypes)\n\treturn spec, err\n}"} {"input": "package lbacktracking\n\nimport \"sort\"\n\n\n\nfunc permuteUnique(nums []int) [][]int ", "output": "{\n\tsort.Ints(nums)\n\tres := [][]int{}\n\n\tvar helper func(nums []int, start int, res *[][]int)\n\thelper = func(nums []int, start int, res *[][]int) {\n\t\tif len(nums)-1 == start {\n\t\t\t*res = append(*res, append([]int{}, nums...))\n\t\t}\n\t\tfor i := start; i < len(nums); i++ {\n\t\t\tif i != start && nums[i] == nums[start] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnums[i], nums[start] = nums[start], nums[i]\n\t\t\thelper(append([]int{}, nums...), start+1, res)\n\t\t}\n\t}\n\n\thelper(nums, 0, &res)\n\treturn res\n}"} {"input": "package main\n\nimport (\n\t\"GoVM/chapter6-obj/heap\"\n\t\"GoVM/chapter4-rtdt\"\n\t\"GoVM/chapter2-class/classpath\"\n\t\"GoVM/chapter5-instructions/base\"\n\t\"GoVM/chapter5-instructions\"\n\t\"strings\"\n\t\"fmt\"\n)\n\ntype JVM struct {\n\tcmd *Cmd\n\tclassLoader *heap.ClassLoader\n\tmainThread *chapter4_rtdt.Thread\n}\n\nfunc newJVM(cmd *Cmd) *JVM {\n\tcp := classpath.Parse(cmd.XjreOption, cmd.cpOption)\n\tclassLoader := heap.NewClassLoader(cp, cmd.verboseClassFlag)\n\treturn &JVM{\n\t\tcmd: cmd,\n\t\tclassLoader: classLoader,\n\t\tmainThread: chapter4_rtdt.NewThread(),\n\t}\n}\n\nfunc (self *JVM) start() {\n\tself.initVM()\n\tself.execMain()\n}\n\nfunc (self *JVM) initVM() {\n\tvmClass := self.classLoader.LoadClass(\"sun/misc/VM\")\n\tbase.InitClass(self.mainThread, vmClass)\n\tchapter5_instructions.Interpret(self.mainThread, self.cmd.verboseInstFlag)\n}\n\n\n\nfunc (self *JVM) createArgsArray() *heap.Object {\n\tstringClass := self.classLoader.LoadClass(\"java/lang/String\")\n\targsLen := uint(len(self.cmd.args))\n\targsArr := stringClass.ArrayClass().NewArray(argsLen)\n\tjArgs := argsArr.Refs()\n\tfor i, arg := range self.cmd.args {\n\t\tjArgs[i] = heap.JString(self.classLoader, arg)\n\t}\n\treturn argsArr\n}\n\nfunc (self *JVM) execMain() ", "output": "{\n\tclassName := strings.Replace(self.cmd.class, \".\", \"/\", -1)\n\tmainClass := self.classLoader.LoadClass(className)\n\tmainMethd := mainClass.GetMainMethod()\n\tif mainMethd == nil {\n\t\tfmt.Printf(\"Main method not found in class %s \\n\", self.cmd.class)\n\t\treturn\n\t}\n\n\targsArr := self.createArgsArray()\n\tframe := self.mainThread.NewFrame(mainMethd)\n\tframe.LocalVars().SetRef(0, argsArr)\n\tself.mainThread.PushFrame(frame)\n\tchapter5_instructions.Interpret(self.mainThread, self.cmd.verboseInstFlag)\n}"} {"input": "package certs\n\n\n\n\nfunc UseTLS(certificateFile, privateKeyFile *string) bool ", "output": "{\n\treturn *certificateFile != \"\" && *privateKeyFile != \"\"\n}"} {"input": "package datascience\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype UpdateModelRequest struct {\n\n\tModelId *string `mandatory:\"true\" contributesTo:\"path\" name:\"modelId\"`\n\n\tUpdateModelDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateModelRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request UpdateModelRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request UpdateModelRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateModelResponse struct {\n\n\tRawResponse *http.Response\n\n\tModel `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateModelResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateModelResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateModelRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package fixtures\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/atlassian/gostatsd\"\n)\n\ntype MetricOpt func(m *gostatsd.Metric)\n\n\n\nfunc MakeMetric(opts ...MetricOpt) *gostatsd.Metric {\n\tm := &gostatsd.Metric{\n\t\tType: gostatsd.COUNTER,\n\t\tName: \"name\",\n\t\tRate: 1,\n\t\tTags: gostatsd.Tags{\n\t\t\t\"foo:bar\",\n\t\t\t\"host:baz\",\n\t\t},\n\t\tSource: \"baz\",\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}\n\nfunc Name(n string) MetricOpt {\n\treturn func(m *gostatsd.Metric) {\n\t\tm.Name = n\n\t}\n}\n\nfunc AddTag(t ...string) MetricOpt {\n\treturn func(m *gostatsd.Metric) {\n\t\tm.Tags = append(m.Tags, t...)\n\t}\n}\n\nfunc DropSource(m *gostatsd.Metric) {\n\tm.Source = gostatsd.UnknownSource\n}\n\n\n\n\n\nfunc SortCompare(ms []*gostatsd.Metric) func(i, j int) bool {\n\treturn func(i, j int) bool {\n\t\tif ms[i].Name == ms[j].Name {\n\t\t\tif len(ms[i].Tags) == len(ms[j].Tags) { \n\t\t\t\tif ms[i].Type == gostatsd.SET {\n\t\t\t\t\treturn ms[i].StringValue < ms[j].StringValue\n\t\t\t\t} else {\n\t\t\t\t\treturn ms[i].Value < ms[j].Value\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn len(ms[i].Tags) < len(ms[j].Tags)\n\t\t}\n\t\treturn ms[i].Name < ms[j].Name\n\t}\n}\n\nfunc DropTag(t string) MetricOpt ", "output": "{\n\treturn func(m *gostatsd.Metric) {\n\t\tnext := 0\n\t\tfound := false\n\t\tfor _, tag := range m.Tags {\n\t\t\tif t == tag {\n\t\t\t\tfound = true\n\t\t\t\tm.Tags[next] = tag\n\t\t\t\tnext++\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tpanic(fmt.Sprintf(\"failed to find tag %s while building metric\", t))\n\t\t}\n\t\tm.Tags = m.Tags[:next]\n\t}\n}"} {"input": "package leet_572\n\ntype TreeNode struct {\n\tVal int\n\tLeft *TreeNode\n\tRight *TreeNode\n}\n\n\n\nfunc visit(s *TreeNode, t *TreeNode) bool {\n\tif s == nil && t == nil {\n\t\treturn true\n\t}\n\tif s == nil || t == nil {\n\t\treturn false\n\t}\n\tif s.Val != t.Val {\n\t\treturn false\n\t}\n\treturn visit(s.Left, t.Left) && visit(s.Right, t.Right)\n}\n\nfunc isSubtree(s *TreeNode, t *TreeNode) bool ", "output": "{\n\tif s == nil || t == nil {\n\t\treturn false\n\t}\n\n\treturn visit(s, t) || isSubtree(s.Left, t) || isSubtree(s.Right, t)\n}"} {"input": "package iso20022\n\n\ntype TotalFeesAndTaxes40 struct {\n\n\tTotalOverheadApplied *ActiveCurrencyAndAmount `xml:\"TtlOvrhdApld,omitempty\"`\n\n\tTotalFees *ActiveCurrencyAndAmount `xml:\"TtlFees,omitempty\"`\n\n\tTotalTaxes *ActiveCurrencyAndAmount `xml:\"TtlTaxs,omitempty\"`\n\n\tCommercialAgreementReference *Max35Text `xml:\"ComrclAgrmtRef,omitempty\"`\n\n\tIndividualFee []*Fee2 `xml:\"IndvFee,omitempty\"`\n\n\tIndividualTax []*Tax31 `xml:\"IndvTax,omitempty\"`\n}\n\n\n\nfunc (t *TotalFeesAndTaxes40) SetTotalFees(value, currency string) {\n\tt.TotalFees = NewActiveCurrencyAndAmount(value, currency)\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalTaxes(value, currency string) {\n\tt.TotalTaxes = NewActiveCurrencyAndAmount(value, currency)\n}\n\nfunc (t *TotalFeesAndTaxes40) SetCommercialAgreementReference(value string) {\n\tt.CommercialAgreementReference = (*Max35Text)(&value)\n}\n\nfunc (t *TotalFeesAndTaxes40) AddIndividualFee() *Fee2 {\n\tnewValue := new(Fee2)\n\tt.IndividualFee = append(t.IndividualFee, newValue)\n\treturn newValue\n}\n\nfunc (t *TotalFeesAndTaxes40) AddIndividualTax() *Tax31 {\n\tnewValue := new(Tax31)\n\tt.IndividualTax = append(t.IndividualTax, newValue)\n\treturn newValue\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalOverheadApplied(value, currency string) ", "output": "{\n\tt.TotalOverheadApplied = NewActiveCurrencyAndAmount(value, currency)\n}"} {"input": "package cover\n\nimport (\n\t\"flag\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\n\n\ntype dummyTestDeps func(pat, str string) (bool, error)\n\nfunc (d dummyTestDeps) MatchString(pat, str string) (bool, error) { return false, nil }\nfunc (d dummyTestDeps) StartCPUProfile(io.Writer) error { return nil }\nfunc (d dummyTestDeps) StopCPUProfile() {}\nfunc (f dummyTestDeps) StartTestLog(w io.Writer) {}\nfunc (f dummyTestDeps) StopTestLog() error { return nil }\nfunc (d dummyTestDeps) WriteHeapProfile(io.Writer) error { return nil }\nfunc (d dummyTestDeps) WriteProfileTo(string, io.Writer, int) error { return nil }\nfunc (f dummyTestDeps) ImportPath() string { return \"\" }\n\n\n\n\n\nfunc FlushProfiles() {\n\toldstdout := os.Stdout\n\toldstderr := os.Stderr\n\tos.Stdout, _ = os.Open(os.DevNull)\n\tos.Stderr, _ = os.Open(os.DevNull)\n\n\ttests := []testing.InternalTest{}\n\tbenchmarks := []testing.InternalBenchmark{}\n\texamples := []testing.InternalExample{}\n\tvar f dummyTestDeps\n\tdummyM := testing.MainStart(f, tests, benchmarks, examples)\n\tdummyM.Run()\n\n\tos.Stdout = oldstdout\n\tos.Stderr = oldstderr\n}\n\nfunc ParseAndStripTestFlags() ", "output": "{\n\tflag.Parse()\n\n\tvar runtimeArgs []string\n\tfor _, arg := range os.Args {\n\t\tif strings.HasPrefix(arg, \"-test.\") ||\n\t\t\tstrings.HasPrefix(arg, \"-httptest.\") {\n\t\t\tcontinue\n\t\t}\n\t\truntimeArgs = append(runtimeArgs, arg)\n\t}\n\tos.Args = runtimeArgs\n}"} {"input": "package x11\n\nimport (\n\t\"C\"\n\t\"unsafe\"\n\n\t\"github.com/richardwilkes/toolbox/xmath/geom\"\n\t\"github.com/richardwilkes/ui/keys\"\n)\n\ntype CrossingEvent C.XCrossingEvent\n\nfunc (evt *CrossingEvent) Window() Window {\n\treturn Window(evt.window)\n}\n\nfunc (evt *CrossingEvent) Where() geom.Point {\n\treturn geom.Point{X: float64(evt.x), Y: float64(evt.y)}\n}\n\n\n\nfunc (evt *CrossingEvent) ToEvent() *Event {\n\treturn (*Event)(unsafe.Pointer(evt))\n}\n\nfunc (evt *CrossingEvent) Modifiers() keys.Modifiers ", "output": "{\n\treturn Modifiers(evt.state)\n}"} {"input": "package errors2\n\nimport (\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tlvldbug = iota\n\tlvlinfo\n\tlvlerr\n\tlvlcrit\n)\n\ntype logMessage struct {\n\ttime time.Time\n\tlevel int\n\tmessage string\n}\n\ntype Logger struct {\n\tmessages []*logMessage\n\tTimer Timer\n}\n\n\n\nfunc (l *Logger) Info(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvlinfo, message: message})\n}\n\nfunc (l *Logger) Error(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvlerr, message: message})\n}\n\nfunc (l *Logger) Critical(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvlcrit, message: message})\n}\n\nvar lock = &sync.Mutex{}\n\nfunc (l *Logger) log(message *logMessage) {\n\tlock.Lock()\n\tl.messages = append(l.messages, message)\n\tlock.Unlock()\n}\n\nfunc (l *Logger) Debug(message string) ", "output": "{\n\tl.log(&logMessage{time: time.Now(), level: lvldbug, message: message})\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\n\n\ntype PatchDetails struct {\n\n\tAction PatchDetailsActionEnum `mandatory:\"false\" json:\"action,omitempty\"`\n\n\tPatchId *string `mandatory:\"false\" json:\"patchId\"`\n}\n\nfunc (m PatchDetails) String() string {\n\treturn common.PointerString(m)\n}\n\n\ntype PatchDetailsActionEnum string\n\n\nconst (\n\tPatchDetailsActionApply PatchDetailsActionEnum = \"APPLY\"\n\tPatchDetailsActionPrecheck PatchDetailsActionEnum = \"PRECHECK\"\n)\n\nvar mappingPatchDetailsAction = map[string]PatchDetailsActionEnum{\n\t\"APPLY\": PatchDetailsActionApply,\n\t\"PRECHECK\": PatchDetailsActionPrecheck,\n}\n\n\n\n\nfunc GetPatchDetailsActionEnumValues() []PatchDetailsActionEnum ", "output": "{\n\tvalues := make([]PatchDetailsActionEnum, 0)\n\tfor _, v := range mappingPatchDetailsAction {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package archive\n\nimport (\n\t\"io\"\n\n\t\"github.com/sacloud/libsacloud/v2/helper/validate\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\ntype UploadRequest struct {\n\tZone string `request:\"-\" validate:\"required\"`\n\tID types.ID `request:\"-\" validate:\"required\"`\n\n\tPath string `validate:\"omitempty,file\"`\n\tReader io.Reader\n}\n\n\n\nfunc (req *UploadRequest) Validate() error ", "output": "{\n\treturn validate.Struct(req)\n}"} {"input": "package model\n\nimport (\n\t\"fmt\"\n\tnative_time \"time\"\n)\n\n\n\n\n\n\n\n\ntype Timestamp int64\n\nconst (\n\tMinimumTick = native_time.Second\n\tsecond = int64(native_time.Second / MinimumTick)\n)\n\n\n\n\n\nfunc (t Timestamp) Before(o Timestamp) bool {\n\treturn t < o\n}\n\n\nfunc (t Timestamp) After(o Timestamp) bool {\n\treturn t > o\n}\n\n\nfunc (t Timestamp) Add(d native_time.Duration) Timestamp {\n\treturn t + Timestamp(d/MinimumTick)\n}\n\n\nfunc (t Timestamp) Sub(o Timestamp) native_time.Duration {\n\treturn native_time.Duration(t-o) * MinimumTick\n}\n\n\nfunc (t Timestamp) Time() native_time.Time {\n\treturn native_time.Unix(int64(t)/second, (int64(t) % second))\n}\n\n\n\nfunc (t Timestamp) Unix() int64 {\n\treturn int64(t) / second\n}\n\n\nfunc (t Timestamp) String() string {\n\treturn fmt.Sprint(int64(t))\n}\n\n\nfunc Now() Timestamp {\n\treturn TimestampFromTime(native_time.Now())\n}\n\n\nfunc TimestampFromTime(t native_time.Time) Timestamp {\n\treturn TimestampFromUnix(t.Unix())\n}\n\n\nfunc TimestampFromUnix(t int64) Timestamp {\n\treturn Timestamp(t * second)\n}\n\nfunc (t Timestamp) Equal(o Timestamp) bool ", "output": "{\n\treturn t == o\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/client-go/informers\"\n\tclientset \"k8s.io/client-go/kubernetes\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/quota\"\n\t\"k8s.io/kubernetes/pkg/quota/generic\"\n)\n\n\n\n\n\n\nfunc NewConfigMapEvaluator(kubeClient clientset.Interface, f informers.SharedInformerFactory) quota.Evaluator {\n\tlistFuncByNamespace := listConfigMapsByNamespaceFuncUsingClient(kubeClient)\n\tif f != nil {\n\t\tlistFuncByNamespace = generic.ListResourceUsingInformerFunc(f, v1.SchemeGroupVersion.WithResource(\"configmaps\"))\n\t}\n\treturn &generic.ObjectCountEvaluator{\n\t\tAllowCreateOnUpdate: false,\n\t\tInternalGroupKind: api.Kind(\"ConfigMap\"),\n\t\tResourceName: api.ResourceConfigMaps,\n\t\tListFuncByNamespace: listFuncByNamespace,\n\t}\n}\n\nfunc listConfigMapsByNamespaceFuncUsingClient(kubeClient clientset.Interface) generic.ListFuncByNamespace ", "output": "{\n\treturn func(namespace string, options metav1.ListOptions) ([]runtime.Object, error) {\n\t\titemList, err := kubeClient.CoreV1().ConfigMaps(namespace).List(options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresults := make([]runtime.Object, 0, len(itemList.Items))\n\t\tfor i := range itemList.Items {\n\t\t\tresults = append(results, &itemList.Items[i])\n\t\t}\n\t\treturn results, nil\n\t}\n}"} {"input": "package sqlite3\n\nimport \"C\"\n\ntype ErrNo int\n\ntype Error struct {\n\tCode ErrNo \n\terr string \n}\n\n\nvar (\n\tErrError error = ErrNo(1) \n\tErrInternal error = ErrNo(2) \n\tErrPerm error = ErrNo(3) \n\tErrAbort error = ErrNo(4) \n\tErrBusy error = ErrNo(5) \n\tErrLocked error = ErrNo(6) \n\tErrNomem error = ErrNo(7) \n\tErrReadonly error = ErrNo(8) \n\tErrInterrupt error = ErrNo(9) \n\tErrIoErr error = ErrNo(10) \n\tErrCorrupt error = ErrNo(11) \n\tErrNotFound error = ErrNo(12) \n\tErrFull error = ErrNo(13) \n\tErrCantOpen error = ErrNo(14) \n\tErrProtocol error = ErrNo(15) \n\tErrEmpty error = ErrNo(16) \n\tErrSchema error = ErrNo(17) \n\tErrTooBig error = ErrNo(18) \n\tErrConstraint error = ErrNo(19) \n\tErrMismatch error = ErrNo(20) \n\tErrMisuse error = ErrNo(21) \n\tErrNoLFS error = ErrNo(22) \n\tErrAuth error = ErrNo(23) \n\tErrFormat error = ErrNo(24) \n\tErrRange error = ErrNo(25) \n\tErrNotADB error = ErrNo(26) \n\tErrNotice error = ErrNo(27) \n\tErrWarning error = ErrNo(28) \n)\n\nfunc (err ErrNo) Error() string {\n\treturn Error{Code: err}.Error()\n}\n\n\n\nfunc (err Error) Error() string ", "output": "{\n\tif err.err != \"\" {\n\t\treturn err.err\n\t}\n\treturn errorString(err)\n}"} {"input": "package model\n\nimport \"time\"\n\ntype FlashMessage struct {\n\tID string\n\tValue string\n\tExpiredAt time.Time\n}\n\n\n\nfunc (fm *FlashMessage) IsExpired(now time.Time) bool {\n\tif fm.ExpiredAt.IsZero() {\n\t\treturn false\n\t}\n\treturn fm.ExpiredAt.Before(now)\n}\n\nfunc (*FlashMessage) TableName() string ", "output": "{\n\treturn \"flash_message\"\n}"} {"input": "package log\n\nimport (\n\t\"testing\"\n)\n\ntype testLogger struct {\n\tkeyvals []interface{}\n}\n\nfunc (tl *testLogger) Log(keyvals ...interface{}) error {\n\ttl.keyvals = keyvals\n\treturn nil\n}\n\ntype testSink struct {\n\tkeyvals []interface{}\n}\n\n\n\nfunc TestLogger_Log(t *testing.T) {\n\ttl := &testLogger{}\n\tl := NewLogger(tl, nil)\n\n\tl.Log(\"message\", \"value\")\n\tif len(tl.keyvals) != 2 {\n\t\tt.Errorf(\"Expected log message with 2 values, got %v\", len(tl.keyvals))\n\t}\n\n\tm1 := tl.keyvals[0]\n\tm2 := tl.keyvals[1]\n\tif m1.(string) != \"message\" || m2.(string) != \"value\" {\n\t\tt.Errorf(\"Expected [message, value] but got %s\", tl.keyvals)\n\t}\n}\n\nfunc TestLogger_Event(t *testing.T) {\n\tts := &testSink{}\n\ttl := &testLogger{}\n\tl := NewLogger(tl, []EventSink{ts})\n\n\tl.Event(\"important_event\", \"act_on_me\")\n\tif len(ts.keyvals) != 2 {\n\t\tt.Errorf(\"Expected to recieve event with 2 values, got %v\", len(ts.keyvals))\n\t}\n\n\tm1 := ts.keyvals[0]\n\tm2 := ts.keyvals[1]\n\tif m1.(string) != \"important_event\" || m2.(string) != \"act_on_me\" {\n\t\tt.Errorf(\"Expected [important_event, act_on_me] but got %s\", ts.keyvals)\n\t}\n}\n\nfunc (ts *testSink) Receive(keyvals ...interface{}) error ", "output": "{\n\tts.keyvals = keyvals\n\treturn nil\n}"} {"input": "package delete\n\nimport (\n\t\"os\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/spf13/cobra\"\n\n\t\"k8s.io/test-infra/kind/pkg/cluster\"\n)\n\ntype flags struct {\n\tName string\n}\n\n\nfunc NewCommand() *cobra.Command {\n\tflags := &flags{}\n\tcmd := &cobra.Command{\n\t\tUse: \"delete\",\n\t\tShort: \"Deletes a cluster\",\n\t\tLong: \"Deletes a Kubernetes cluster\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\trun(flags, cmd, args)\n\t\t},\n\t}\n\tcmd.Flags().StringVar(&flags.Name, \"name\", \"\", \"the cluster name\")\n\treturn cmd\n}\n\n\n\nfunc run(flags *flags, cmd *cobra.Command, args []string) ", "output": "{\n\tconfig := cluster.NewConfig(flags.Name)\n\tctx := cluster.NewContext(config)\n\terr := ctx.Delete()\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to delete cluster: %v\", err)\n\t\tos.Exit(-1)\n\t}\n}"} {"input": "package os\n\nimport (\n\t\"syscall\"\n)\n\n\n\nfunc (f *File) Stat() (FileInfo, error) {\n\tif f == nil {\n\t\treturn nil, ErrInvalid\n\t}\n\tvar fs fileStat\n\terr := f.pfd.Fstat(&fs.sys)\n\tif err != nil {\n\t\treturn nil, &PathError{\"stat\", f.name, err}\n\t}\n\tfillFileStatFromSys(&fs, f.name)\n\treturn &fs, nil\n}\n\n\n\n\n\n\n\n\n\nfunc Lstat(name string) (FileInfo, error) {\n\tvar fs fileStat\n\terr := syscall.Lstat(name, &fs.sys)\n\tif err != nil {\n\t\treturn nil, &PathError{\"lstat\", name, err}\n\t}\n\tfillFileStatFromSys(&fs, name)\n\treturn &fs, nil\n}\n\nfunc Stat(name string) (FileInfo, error) ", "output": "{\n\tvar fs fileStat\n\terr := syscall.Stat(name, &fs.sys)\n\tif err != nil {\n\t\treturn nil, &PathError{\"stat\", name, err}\n\t}\n\tfillFileStatFromSys(&fs, name)\n\treturn &fs, nil\n}"} {"input": "package tracing\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/gotgo/fw/logging\"\n)\n\ntype Receiver struct {\n\tReceiverName string\n\tWriter TraceMessageWriter\n\tLog logging.Logger `inject:\"\"`\n}\n\n\n\nfunc (ft *Receiver) Receive(m *TraceMessage) {\n\tif bytes, err := json.MarshalIndent(m, \"\", \"\\t\"); err != nil {\n\t\tft.Log.MarshalFail(\"trace receive\", m, err)\n\t} else if _, err := ft.Writer.Write(bytes); err != nil {\n\t\tft.Log.Error(\"failed to write to receiver\", err)\n\t}\n}\n\nfunc (ft *Receiver) Close() {\n\tif err := ft.Writer.Close(); err != nil {\n\t\tft.Log.Error(\"failed to close trace writer\", err)\n\t}\n}\n\nfunc (ft *Receiver) Name() string ", "output": "{\n\treturn ft.ReceiverName\n}"} {"input": "package disjointset\n\nimport ()\n\ntype QuickUnion struct {\n\tdisjointset\n}\n\nfunc NewQuickUnion(N int) *QuickUnion {\n\tthis := &QuickUnion{}\n\tthis.UnionFind = this\n\tthis.Init(N)\n\treturn this\n}\n\n\n\nfunc (this *QuickUnion) Union(p, q int) {\n\tpRoot := this.Find(p)\n\tqRoot := this.Find(q)\n\n\tif pRoot == qRoot {\n\t\treturn\n\t}\n\n\tthis.id[pRoot] = qRoot\n\n\tthis.count--\n}\n\nfunc (this *QuickUnion) Find(p int) int ", "output": "{\n\tfor p != this.id[p] {\n\t\tp = this.id[p]\n\t}\n\treturn p\n}"} {"input": "package nobody\n\nimport (\n\t\"context\"\n\n\tvoucher \"github.com/grafeas/voucher/v2\"\n\t\"github.com/grafeas/voucher/v2/docker\"\n)\n\n\n\ntype check struct {\n\tauth voucher.Auth\n}\n\n\n\nfunc (n *check) SetAuth(auth voucher.Auth) {\n\tn.auth = auth\n}\n\n\n\nfunc (n *check) Check(ctx context.Context, i voucher.ImageData) (bool, error) {\n\tif nil == n.auth {\n\t\treturn false, voucher.ErrNoAuth\n\t}\n\n\tclient, err := n.auth.ToClient(ctx, i)\n\tif nil != err {\n\t\treturn false, err\n\t}\n\n\timageConfig, err := docker.RequestImageConfig(client, i)\n\n\tif nil != err {\n\t\treturn false, err\n\t}\n\n\treturn !imageConfig.RunsAsRoot(), nil\n}\n\n\n\nfunc init() ", "output": "{\n\tvoucher.RegisterCheckFactory(\"nobody\", func() voucher.Check {\n\t\treturn new(check)\n\t})\n}"} {"input": "package violetear\n\nimport (\n\t\"net/http\"\n\t\"time\"\n)\n\n\ntype ResponseWriter struct {\n\thttp.ResponseWriter\n\trequestID string\n\tsize, status int\n\tstart time.Time\n}\n\n\nfunc NewResponseWriter(w http.ResponseWriter, rid string) *ResponseWriter {\n\treturn &ResponseWriter{\n\t\tResponseWriter: w,\n\t\trequestID: rid,\n\t\tstart: time.Now(),\n\t\tstatus: http.StatusOK,\n\t}\n}\n\n\nfunc (w *ResponseWriter) Status() int {\n\treturn w.status\n}\n\n\nfunc (w *ResponseWriter) Size() int {\n\treturn w.size\n}\n\n\n\n\n\nfunc (w *ResponseWriter) RequestID() string {\n\treturn w.requestID\n}\n\n\n\nfunc (w *ResponseWriter) Write(data []byte) (int, error) {\n\tsize, err := w.ResponseWriter.Write(data)\n\tw.size += size\n\treturn size, err\n}\n\n\n\nfunc (w *ResponseWriter) WriteHeader(statusCode int) {\n\tw.status = statusCode\n\tw.ResponseWriter.WriteHeader(statusCode)\n}\n\nfunc (w *ResponseWriter) RequestTime() string ", "output": "{\n\treturn time.Since(w.start).String()\n}"} {"input": "package zk\n\nimport (\n\t\"atlantis/router/config\"\n)\n\ntype ZkPool struct {\n\tName string\n\tInternal bool\n\tConfig config.PoolConfig\n}\n\n\n\nfunc (z ZkPool) Pool(hosts map[string]config.Host) config.Pool {\n\treturn config.Pool{\n\t\tName: z.Name,\n\t\tInternal: z.Internal,\n\t\tHosts: hosts,\n\t\tConfig: z.Config,\n\t}\n}\n\nfunc ToZkPool(p config.Pool) (ZkPool, map[string]config.Host) ", "output": "{\n\tzkPool := ZkPool{\n\t\tName: p.Name,\n\t\tInternal: p.Internal,\n\t\tConfig: p.Config,\n\t}\n\n\treturn zkPool, p.Hosts\n}"} {"input": "package http\n\nimport (\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/IBM-Bluemix/bluemix-cli-sdk/bluemix/terminal\"\n\t\"github.com/IBM-Bluemix/bluemix-cli-sdk/bluemix/trace\"\n)\n\n\n\n\n\ntype TraceLoggingTransport struct {\n\trt http.RoundTripper\n}\n\n\n\n\nfunc NewTraceLoggingTransport(rt http.RoundTripper) *TraceLoggingTransport {\n\tif rt == nil {\n\t\treturn &TraceLoggingTransport{\n\t\t\trt: http.DefaultTransport,\n\t\t}\n\t}\n\treturn &TraceLoggingTransport{\n\t\trt: rt,\n\t}\n}\n\nfunc (r *TraceLoggingTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {\n\tstart := time.Now()\n\tr.dumpRequest(req, start)\n\tresp, err = r.rt.RoundTrip(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tr.dumpResponse(resp, start)\n\treturn\n}\n\n\n\nfunc (r *TraceLoggingTransport) dumpResponse(res *http.Response, start time.Time) {\n\tend := time.Now()\n\n\tdumpedResponse, err := httputil.DumpResponse(res, true)\n\tif err != nil {\n\t\ttrace.Logger.Printf(\"An error occurred while dumping response:\\n%v\\n\", err)\n\t\treturn\n\t}\n\n\ttrace.Logger.Printf(\"\\n%s [%s] %s %.0fms\\n%s\\n\",\n\t\tterminal.HeaderColor(\"RESPONSE:\"),\n\t\tend.Format(time.RFC3339),\n\t\tterminal.HeaderColor(\"Elapsed:\"),\n\t\tend.Sub(start).Seconds()*1000,\n\t\ttrace.Sanitize(string(dumpedResponse)))\n}\n\nfunc (r *TraceLoggingTransport) dumpRequest(req *http.Request, start time.Time) ", "output": "{\n\tshouldDisplayBody := !strings.Contains(req.Header.Get(\"Content-Type\"), \"multipart/form-data\")\n\n\tdumpedRequest, err := httputil.DumpRequest(req, shouldDisplayBody)\n\tif err != nil {\n\t\ttrace.Logger.Printf(\"An error occurred while dumping request:\\n%v\\n\", err)\n\t\treturn\n\t}\n\n\ttrace.Logger.Printf(\"\\n%s [%s]\\n%s\\n\",\n\t\tterminal.HeaderColor(\"REQUEST:\"),\n\t\tstart.Format(time.RFC3339),\n\t\ttrace.Sanitize(string(dumpedRequest)))\n\n\tif !shouldDisplayBody {\n\t\ttrace.Logger.Println(\"[MULTIPART/FORM-DATA CONTENT HIDDEN]\")\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"github.com/ying32/govcl/vcl/api/memorydll\"\n\t\"github.com/ying32/govcl/vcl/win\"\n)\n\n\n\nfunc getLibType(lib *memorydll.LazyDLL) int32 {\n\tproc := lib.NewProc(\"DGetLibType\")\n\tr, _, _ := proc.Call()\n\treturn int32(r)\n}\n\n\nfunc GetLibVcl() *memorydll.LazyDLL {\n\treturn libvcl\n}\n\n\nfunc FeeMemoryDLL() {\n\tif libvcl != nil {\n\t\tlibvcl.Close()\n\t\tlibvcl = nil\n\t}\n}\n\nfunc closeLib() {\n\tFeeMemoryDLL()\n}\n\nfunc loadUILib() *memorydll.LazyDLL ", "output": "{\n\tdllBytes, ok := win.ResourceToBytes(win.GetSelfModuleHandle(), \"GOVCLLIB\", win.RT_RCDATA)\n\tif !ok {\n\t\tpanic(\"\\\"GOVCLLIB\\\" resource does not exist.\")\n\t\treturn nil\n\t}\n\tlib := memorydll.NewMemoryDLL(dllBytes)\n\tif lib.Load() != nil {\n\t\tpanic(\"Unable to load dll, unknown reason.\")\n\t\treturn nil\n\t}\n\tif getLibType(lib) != 1 {\n\t\tpanic(\"The VCL library is no longer supported. If necessary, please use the last code that supports VCL version: https:github.com/ying32/govcl/tree/last-vcl-support.\")\n\t}\n\treturn lib\n}"} {"input": "package machinery_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/RichardKnop/machinery/v2\"\n)\n\nfunc TestRedactURL(t *testing.T) {\n\tt.Parallel()\n\n\tbroker := \"amqp://guest:guest@localhost:5672\"\n\tredactedURL := machinery.RedactURL(broker)\n\tassert.Equal(t, \"amqp://localhost:5672\", redactedURL)\n}\n\nfunc TestPreConsumeHandler(t *testing.T) {\n\tt.Parallel()\n\tworker := &machinery.Worker{}\n\n\tworker.SetPreConsumeHandler(SamplePreConsumeHandler)\n\tassert.True(t, worker.PreConsumeHandler())\n}\n\n\n\nfunc SamplePreConsumeHandler(w *machinery.Worker) bool ", "output": "{\n\treturn true\n}"} {"input": "package main\n\nimport (\n\t\"math\"\n\t\"math/rand\"\n)\n\n\nfunc chunkStrings(x []string, numChunks int) [][]string {\n\tvar result [][]string\n\tif numChunks > len(x) {\n\t\tnumChunks = len(x)\n\t}\n\ti := 0\n\tfor len(result) < numChunks {\n\t\tchunkSize := int(math.Floor(float64(len(x)-i) / float64(numChunks-len(result))))\n\t\tub := i + chunkSize\n\t\tresult = append(result, x[i:ub])\n\t\ti += chunkSize\n\t}\n\treturn result\n}\n\n\n\n\nfunc shuffleStrings(x []string, seed int64) ", "output": "{\n\tr := rand.New(rand.NewSource(seed))\n\tfor i := range x {\n\t\tj := r.Intn(i + 1)\n\t\tx[i], x[j] = x[j], x[i]\n\t}\n}"} {"input": "package auth\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/fragmenta/auth\"\n\t\"github.com/fragmenta/router\"\n\n\t\"github.com/fragmenta/fragmenta-app/src/users\"\n)\n\n\n\n\n\nfunc CurrentUser(context router.Context) *users.User {\n\n\tif context.Get(\"current_user\") != nil {\n\t\treturn context.Get(\"current_user\").(*users.User)\n\t}\n\n\tuser := &users.User{}\n\n\tsession, err := auth.Session(context.Writer(), context.Request())\n\tif err != nil {\n\t\tcontext.Logf(\"#error problem retrieving session\")\n\t\treturn user\n\t}\n\n\tvar id int64\n\tval := session.Get(auth.SessionUserKey)\n\tif len(val) > 0 {\n\t\tid, err = strconv.ParseInt(val, 10, 64)\n\t\tif err != nil {\n\t\t\tcontext.Logf(\"#error Error decoding session user key:%s\\n\", err)\n\t\t\treturn user\n\t\t}\n\t}\n\n\tif id != 0 {\n\t\tu, err := users.Find(id)\n\t\tif err != nil {\n\t\t\tcontext.Logf(\"#info User not found from session id:%d\\n\", id)\n\t\t\treturn user\n\t\t}\n\t\tuser = u\n\t}\n\n\treturn user\n}\n\nfunc CurrentUserFilter(context router.Context) error ", "output": "{\n\tu := CurrentUser(context)\n\tcontext.Set(\"current_user\", u)\n\treturn nil\n}"} {"input": "package dodo\n\n\nfunc NewPropertyIndex() *propertyIndex {\n\n\treturn &propertyIndex{\n\t\tpropertyIndexMap: map[string]map[string]int{},\n\t}\n}\n\ntype propertyIndex struct {\n\tpropertyIndexMap map[string]map[string]int\n}\n\n\n\nfunc (p *propertyIndex) incrementIndex(container, property string) *int {\n\n\tindexMap, exists := p.propertyIndexMap[container]\n\tif !exists {\n\t\tindexMap = map[string]int{}\n\t\tp.propertyIndexMap[container] = indexMap\n\t}\n\n\tindex, exists := indexMap[property]\n\tif !exists {\n\t\tindex = 0\n\t\tindexMap[property] = index\n\t} else {\n\t\tindex++\n\t\tindexMap[property] = index\n\t}\n\n\treturn &index\n}\n\nfunc (p *propertyIndex) index(container, property string) *int ", "output": "{\n\n\tindexMap, exists := p.propertyIndexMap[container]\n\tif !exists {\n\t\treturn nil\n\t}\n\n\tindex, exists := indexMap[property]\n\tif !exists {\n\t\treturn nil\n\t}\n\n\treturn &index\n}"} {"input": "package imagemetadata\n\n\n\n\nfunc SetSigningPublicKey(key string) string ", "output": "{\n\toldKey := simplestreamsImagesPublicKey\n\tsimplestreamsImagesPublicKey = key\n\treturn oldKey\n}"} {"input": "package errors \n\nimport (\n\t\"strconv\"\n)\n\n\n\ntype StructuralError string\n\n\n\n\n\ntype UnsupportedError string\n\nfunc (s UnsupportedError) Error() string {\n\treturn \"openpgp: unsupported feature: \" + string(s)\n}\n\n\n\ntype InvalidArgumentError string\n\nfunc (i InvalidArgumentError) Error() string {\n\treturn \"openpgp: invalid argument: \" + string(i)\n}\n\n\n\ntype SignatureError string\n\nfunc (b SignatureError) Error() string {\n\treturn \"openpgp: invalid signature: \" + string(b)\n}\n\ntype keyIncorrectError int\n\nfunc (ki keyIncorrectError) Error() string {\n\treturn \"openpgp: incorrect key\"\n}\n\nvar ErrKeyIncorrect error = keyIncorrectError(0)\n\ntype unknownIssuerError int\n\nfunc (unknownIssuerError) Error() string {\n\treturn \"openpgp: signature made by unknown entity\"\n}\n\nvar ErrUnknownIssuer error = unknownIssuerError(0)\n\ntype keyRevokedError int\n\nfunc (keyRevokedError) Error() string {\n\treturn \"openpgp: signature made by revoked key\"\n}\n\nvar ErrKeyRevoked error = keyRevokedError(0)\n\ntype UnknownPacketTypeError uint8\n\nfunc (upte UnknownPacketTypeError) Error() string {\n\treturn \"openpgp: unknown packet type: \" + strconv.Itoa(int(upte))\n}\n\nfunc (s StructuralError) Error() string ", "output": "{\n\treturn \"openpgp: invalid data: \" + string(s)\n}"} {"input": "package envelope_extensions\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\n\t\"github.com/cloudfoundry/sonde-go/events\"\n)\n\nconst SystemAppId = \"system\"\n\ntype hasAppId interface {\n\tGetApplicationId() *events.UUID\n}\n\nfunc GetAppId(envelope *events.Envelope) string {\n\tif envelope.GetEventType() == events.Envelope_LogMessage {\n\t\treturn envelope.GetLogMessage().GetAppId()\n\t}\n\n\tif envelope.GetEventType() == events.Envelope_ContainerMetric {\n\t\treturn envelope.GetContainerMetric().GetApplicationId()\n\t}\n\n\tvar event hasAppId\n\tswitch envelope.GetEventType() {\n\tcase events.Envelope_HttpStart:\n\t\tevent = envelope.GetHttpStart()\n\tcase events.Envelope_HttpStop:\n\t\tevent = envelope.GetHttpStop()\n\tcase events.Envelope_HttpStartStop:\n\t\tevent = envelope.GetHttpStartStop()\n\tdefault:\n\t\treturn SystemAppId\n\t}\n\n\tuuid := event.GetApplicationId()\n\tif uuid != nil {\n\t\treturn formatUUID(uuid)\n\t}\n\treturn SystemAppId\n}\n\n\n\nfunc formatUUID(uuid *events.UUID) string ", "output": "{\n\tvar uuidBytes [16]byte\n\tbinary.LittleEndian.PutUint64(uuidBytes[:8], uuid.GetLow())\n\tbinary.LittleEndian.PutUint64(uuidBytes[8:], uuid.GetHigh())\n\treturn fmt.Sprintf(\"%x-%x-%x-%x-%x\", uuidBytes[0:4], uuidBytes[4:6], uuidBytes[6:8], uuidBytes[8:10], uuidBytes[10:])\n}"} {"input": "package main\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\n\n\nfunc runRolesCmd(cmd *cobra.Command, args []string) {\n\n}\n\nfunc getRolesCmd() *cobra.Command ", "output": "{\n\treturn &cobra.Command{\n\t\tUse: \"roles\",\n\t\tShort: \"Resets all settings\",\n\t\tLong: ``,\n\t\tPreRun: initConfigFiles,\n\t\tRun: runRolesCmd,\n\t}\n}"} {"input": "package endpoints_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\n\n\n\n\nfunc TestEndpoints_ClusterUpdateAddressIsCovered(t *testing.T) {\n\tendpoints, config, cleanup := newEndpoints(t)\n\tdefer cleanup()\n\n\tconfig.NetworkAddress = \"[::]:12345\"\n\tconfig.ClusterAddress = \"\"\n\trequire.NoError(t, endpoints.Up(config))\n\n\trequire.NoError(t, endpoints.ClusterUpdateAddress(\"127.0.0.1:12345\"))\n\n\tassert.NoError(t, httpGetOverTLSSocket(endpoints.NetworkAddressAndCert()))\n}\n\nfunc TestEndpoints_ClusterCreateTCPSocket(t *testing.T) ", "output": "{\n\tendpoints, config, cleanup := newEndpoints(t)\n\tdefer cleanup()\n\n\tconfig.NetworkAddress = \"127.0.0.1:12345\"\n\tconfig.ClusterAddress = \"127.0.0.1:54321\"\n\trequire.NoError(t, endpoints.Up(config))\n\n\tassert.NoError(t, httpGetOverTLSSocket(endpoints.NetworkAddressAndCert()))\n\tassert.NoError(t, httpGetOverTLSSocket(endpoints.ClusterAddressAndCert()))\n}"} {"input": "package nes\n\nimport \"log\"\n\ntype Mapper2 struct {\n\t*Cartridge\n\tprgBank1 int\n\tprgBank2 int\n}\n\n\n\nfunc (m *Mapper2) Step() {\n}\n\nfunc (m *Mapper2) Read(address uint16) byte {\n\tswitch {\n\tcase address < 0x2000:\n\t\treturn m.CHR[address]\n\tcase address >= 0xC000:\n\t\tindex := m.prgBank2*0x4000 + int(address-0xC000)\n\t\treturn m.PRG[index]\n\tcase address >= 0x8000:\n\t\tindex := m.prgBank1*0x4000 + int(address-0x8000)\n\t\treturn m.PRG[index]\n\tcase address >= 0x6000:\n\t\tindex := int(address) - 0x6000\n\t\treturn m.SRAM[index]\n\tdefault:\n\t\tlog.Fatalf(\"unhandled mapper2 read at address: 0x%04X\", address)\n\t}\n\treturn 0\n}\n\nfunc (m *Mapper2) Write(address uint16, value byte) {\n\tswitch {\n\tcase address < 0x2000:\n\t\tm.CHR[address] = value\n\tcase address >= 0x8000:\n\t\tm.prgBank1 = int(value)\n\tcase address >= 0x6000:\n\t\tindex := int(address) - 0x6000\n\t\tm.SRAM[index] = value\n\tdefault:\n\t\tlog.Fatalf(\"unhandled mapper2 write at address: 0x%04X\", address)\n\t}\n}\n\nfunc NewMapper2(cartridge *Cartridge) Mapper ", "output": "{\n\tprgBanks := len(cartridge.PRG) / 0x4000\n\tprgBank1 := 0\n\tprgBank2 := prgBanks - 1\n\treturn &Mapper2{cartridge, prgBank1, prgBank2}\n}"} {"input": "package jms\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype UpdateFleetAgentConfigurationRequest struct {\n\n\tFleetId *string `mandatory:\"true\" contributesTo:\"path\" name:\"fleetId\"`\n\n\tUpdateFleetAgentConfigurationDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateFleetAgentConfigurationRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request UpdateFleetAgentConfigurationRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request UpdateFleetAgentConfigurationRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request UpdateFleetAgentConfigurationRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateFleetAgentConfigurationResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateFleetAgentConfigurationResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response UpdateFleetAgentConfigurationResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package goparser\n\nimport (\n\t\"go/ast\"\n\t\"testing\"\n)\n\nfunc testCmtAgainstExpt(t *testing.T, text, expected string) {\n\tcmt := ast.Comment{\n\t\tText: text,\n\t}\n\n\tresult := CmtToStr(&cmt)\n\n\tif expected != result {\n\t\tt.Errorf(\"Result doesn't match expectation\")\n\t\tt.Errorf(\"Expected:\\n%s\", expected)\n\t\tt.Errorf(\"Get:\\n%s\", result)\n\t}\n}\n\n\nfunc TestCmtToStr1(t *testing.T) {\n\ttestCmtAgainstExpt(t,\n\t\t\"//\\n\"+\n\t\t\t\" // testing line 1\\n\"+\n\t\t\t\"//testing line 2\\n\"+\n\t\t\t\"// testing line 3\",\n\t\t\"testing line 1\\n\"+\n\t\t\t\"testing line 2\\n\"+\n\t\t\t\"testing line 3\\n\")\n}\n\n\n\n\n\nfunc TestCmtToStr3(t *testing.T) {\n\ttestCmtAgainstExpt(t,\n\t\t\"/*\\n\"+\n\t\t\t\" testing line 1\\n\"+\n\t\t\t\" testing line 2\\n\"+\n\t\t\t\" testing line 3\\n\"+\n\t\t\t\"*/\",\n\t\t\" testing line 1\\n\"+\n\t\t\t\" testing line 2\\n\"+\n\t\t\t\" testing line 3\\n\")\n}\n\nfunc TestCmtToStr2(t *testing.T) ", "output": "{\n\ttestCmtAgainstExpt(t,\n\t\t\"/**\\n\"+\n\t\t\t\" * testing line 1\\n\"+\n\t\t\t\"* testing line 2\\n\"+\n\t\t\t\" * testing line 3\\n\"+\n\t\t\t\" */\",\n\t\t\" testing line 1\\n\"+\n\t\t\t\" testing line 2\\n\"+\n\t\t\t\" testing line 3\\n\")\n}"} {"input": "package leet_20\n\ntype Stack []byte\n\nfunc (s *Stack) Pop() byte {\n\tc := s.Top()\n\tlength := len(*s)\n\tif length <= 1 {\n\t\t*s = nil\n\t} else {\n\t\t*s = (*s)[:length-1]\n\t}\n\treturn c\n}\n\n\n\nfunc (s *Stack) Push(x byte) {\n\t*s = append(*s, x)\n}\n\nfunc (s *Stack) Top() byte {\n\tlength := len(*s)\n\tif 0 == length {\n\t\treturn 0\n\t}\n\treturn (*s)[length-1]\n}\n\nfunc (s *Stack) String() string {\n\treturn string(*s)\n}\n\nfunc match(a, b byte) bool {\n\tif a == '[' && b == ']' {\n\t\treturn true\n\t}\n\tif a == '(' && b == ')' {\n\t\treturn true\n\t}\n\tif a == '{' && b == '}' {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc isValid(s string) bool {\n\tarr := []byte(s)\n\tstack := new(Stack)\n\tfor _, c := range arr {\n\t\tswitch c {\n\t\tcase '[', '{', '(':\n\t\t\tstack.Push(c)\n\t\t\tcontinue\n\t\t}\n\t\ttop := stack.Top()\n\t\tif match(top, c) {\n\t\t\tstack.Pop()\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn stack.Empty()\n}\n\nfunc (s *Stack) Empty() bool ", "output": "{\n\treturn nil == s || *s == nil || len(*s) == 0\n}"} {"input": "package head\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/arapov/pile/lib/flight\"\n\n\t\"github.com/blue-jay/core/router\"\n)\n\nvar (\n\turi = \"/roster\"\n)\n\n\nfunc Load() {\n\trouter.Get(uri+\"/head\", IndexHead)\n\trouter.Get(uri+\"/all\", IndexAll)\n}\n\n\n\n\n\nfunc IndexAll(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\tv := c.View.New(\"head/index\")\n\tv.Vars[\"name\"] = \"Everyone in organization\"\n\tv.Vars[\"suffix\"] = \"all\"\n\tv.Render(w, r)\n}\n\nfunc IndexHead(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tc := flight.Context(w, r)\n\n\tv := c.View.New(\"head/index\")\n\tv.Vars[\"name\"] = \"TC-UA-Steward\"\n\tv.Vars[\"suffix\"] = \"heads\"\n\tv.Render(w, r)\n}"} {"input": "package bunny\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype Bunny interface {\n\tHealthy() bool\n}\n\ntype HttpBunny struct {\n\turl string\n}\n\ntype BunnyStatus struct {\n\tName string `json:\"name\"`\n\tStatus string `json:\"status\"`\n\tProcessTime int `json:\"timeToEvaluate\"`\n}\n\nfunc NewBunny(url string) (bunny HttpBunny) {\n\tbunny.url = url\n\treturn\n}\n\n\n\n\nfunc(bunny HttpBunny) Update() (bunnyStatus BunnyStatus) ", "output": "{\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\n\tres, err := client.Get(bunny.url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tbunnyStatus.Status = \"ERROR\"\n\t}\n\tbody, err := ioutil.ReadAll(res.Body)\n\tres.Body.Close()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tbunnyStatus.Status = \"ERROR\"\n\t}else{\n\t\tjson.Unmarshal(body, &bunnyStatus)\n\t}\n\treturn\n}"} {"input": "package nanomsg\n\n\nimport \"C\"\n\nimport (\n\t\"time\"\n)\n\nconst (\n\tSURVEYOR = Protocol(C.NN_SURVEYOR)\n\tRESPONDENT = Protocol(C.NN_RESPONDENT)\n)\n\ntype SurveyorSocket struct {\n\t*Socket\n}\n\n\n\n\n\n\nfunc NewSurveyorSocket() (*SurveyorSocket, error) {\n\tsocket, err := NewSocket(AF_SP, SURVEYOR)\n\treturn &SurveyorSocket{socket}, err\n}\n\n\nfunc (s *SurveyorSocket) Deadline() (time.Duration, error) {\n\treturn s.Socket.SockOptDuration(C.NN_SURVEYOR, C.NN_SURVEYOR_DEADLINE, time.Millisecond)\n}\n\n\n\n\nfunc (s *SurveyorSocket) SetDeadline(deadline time.Duration) error {\n\treturn s.Socket.SetSockOptDuration(C.NN_SURVEYOR, C.NN_SURVEYOR_DEADLINE, time.Millisecond, deadline)\n}\n\ntype RespondentSocket struct {\n\t*Socket\n}\n\n\n\n\n\n\nfunc NewRespondentSocket() (*RespondentSocket, error) ", "output": "{\n\tsocket, err := NewSocket(AF_SP, RESPONDENT)\n\treturn &RespondentSocket{socket}, err\n}"} {"input": "package util\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os/exec\"\n\t\"regexp\"\n\t\"strings\"\n\t\"syscall\"\n)\n\n\n\n\n\nfunc ExecCommandOutput(cmd string, args []string) (string, int, error) {\n\tLogDebug.Print(\"ExecCommandOutput called with \", cmd, args)\n\tc := exec.Command(cmd, args...)\n\tvar b bytes.Buffer\n\tc.Stdout = &b\n\tc.Stderr = &b\n\n\tif err := c.Start(); err != nil {\n\t\treturn \"\", 999, err\n\t}\n\n\n\terr := c.Wait()\n\tout := string(b.Bytes())\n\n\tfor _, line := range strings.Split(out, \"\\n\") {\n\t\tLogDebug.Print(\"out :\", line)\n\t}\n\n\tif err != nil {\n\t\tif badnews, ok := err.(*exec.ExitError); ok {\n\t\t\tif status, ok := badnews.Sys().(syscall.WaitStatus); ok {\n\t\t\t\treturn out, status.ExitStatus(), fmt.Errorf(\"rc=%d\", status.ExitStatus())\n\t\t\t}\n\t\t} else {\n\t\t\treturn out, 888, fmt.Errorf(\"unknown error\")\n\t\t}\n\t}\n\n\treturn out, 0, nil\n}\n\n\n\n\nfunc FindStringSubmatchMap(s string, r *regexp.Regexp) map[string]string ", "output": "{\n\tcaptures := make(map[string]string)\n\tmatch := r.FindStringSubmatch(s)\n\tif match == nil {\n\t\treturn captures\n\t}\n\tfor i, name := range r.SubexpNames() {\n\t\tif i != 0 {\n\t\t\tcaptures[name] = match[i]\n\t\t}\n\t}\n\treturn captures\n}"} {"input": "package playground \n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst baseURL = \"https://play.golang.org\"\n\nfunc init() {\n\thttp.HandleFunc(\"/compile\", bounce)\n\thttp.HandleFunc(\"/share\", bounce)\n}\n\nfunc bounce(w http.ResponseWriter, r *http.Request) {\n\tb := new(bytes.Buffer)\n\tif err := passThru(b, r); err != nil {\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treport(r, err)\n\t\treturn\n\t}\n\tio.Copy(w, b)\n}\n\nfunc passThru(w io.Writer, req *http.Request) error {\n\tif req.URL.Path == \"/share\" && !allowShare(req) {\n\t\treturn errors.New(\"Forbidden\")\n\t}\n\tdefer req.Body.Close()\n\turl := baseURL + req.URL.Path\n\tctx, cancel := context.WithTimeout(contextFunc(req), 60*time.Second)\n\tdefer cancel()\n\tr, err := post(ctx, url, req.Header.Get(\"Content-type\"), req.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"making POST request: %v\", err)\n\t}\n\tdefer r.Body.Close()\n\tif _, err := io.Copy(w, r.Body); err != nil {\n\t\treturn fmt.Errorf(\"copying response Body: %v\", err)\n\t}\n\treturn nil\n}\n\nvar onAppengine = false \n\n\n\nfunc allowShare(r *http.Request) bool ", "output": "{\n\tif !onAppengine {\n\t\treturn true\n\t}\n\tswitch r.Header.Get(\"X-AppEngine-Country\") {\n\tcase \"\", \"ZZ\", \"CN\":\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package main\n\nimport \"github.com/augustoroman/serial_lcd\"\n\ntype FakeLcd struct{}\n\nfunc (f FakeLcd) SetBG(r, g, b uint8) error { return nil }\nfunc (f FakeLcd) SetOn(On bool) error { return nil }\nfunc (f FakeLcd) SetBrightness(b uint8) error { return nil }\nfunc (f FakeLcd) SetContrast(c uint8) error { return nil }\nfunc (f FakeLcd) SetAutoscroll(On bool) error { return nil }\nfunc (f FakeLcd) SetSize(cols, rows uint8) error { return nil }\nfunc (f FakeLcd) Clear() error { return nil }\nfunc (f FakeLcd) Home() error { return nil }\n\nfunc (f FakeLcd) MoveForward() error { return nil }\nfunc (f FakeLcd) MoveBack() error { return nil }\nfunc (f FakeLcd) Write(b []byte) (int, error) { return len(b), nil }\n\nfunc (f FakeLcd) CreateCustomChar(spot uint8, c serial_lcd.Char) error { return nil }\n\nfunc (f FakeLcd) MoveTo(col, row uint8) error ", "output": "{ return nil }"} {"input": "package core\n\nimport \"os\"\nimport \"fmt\"\n\nvar f *os.File\nvar watchdog = true\n\nfunc StartDog() {\n\treturn\n\twatchdog = false\n\treturn\n\tvar err error\n\tf, err = os.Create(\"/dev/watchdog\")\n\tif err != nil {\n\t\tfmt.Println(\"Watchdog Error:\", err)\n\t\tos.Exit(1)\n\t}\n\t_, err = f.WriteString(\"X\")\n\tif err != nil {\n\t\tfmt.Println(\"StartDog Write Error:\", err)\n\t\tos.Exit(1)\n\t}\n}\n\n\n\nfunc PetDog(){\n\treturn\n\tif watchdog {\n\t\tvar err error\n\t\t_, err = f.WriteString(\"X\")\n\t\tif err != nil {\n\t\t\tfmt.Println(\"PetDog Write Error:\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}\n\nfunc StopDog() ", "output": "{\n\treturn\n\tif watchdog {\n\t\twatchdog = false\n\t\tf.Close()\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype UpdateInternetGatewayRequest struct {\n\n\tIgId *string `mandatory:\"true\" contributesTo:\"path\" name:\"igId\"`\n\n\tUpdateInternetGatewayDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateInternetGatewayRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request UpdateInternetGatewayRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request UpdateInternetGatewayRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateInternetGatewayResponse struct {\n\n\tRawResponse *http.Response\n\n\tInternetGateway `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateInternetGatewayResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response UpdateInternetGatewayResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package feed\n\nimport (\n\t\"go-common/app/interface/main/app-card/model/card/rank\"\n\t\"go-common/app/interface/main/app-feed/model\"\n)\n\n\n\nfunc (s *Service) RankCard(plat int8) (ranks []*rank.Rank, aids []int64) ", "output": "{\n\tvar limit int\n\tif !model.IsIPad(plat) {\n\t\tlimit = 3\n\t} else {\n\t\tlimit = 4\n\t}\n\tranks = make([]*rank.Rank, 0, limit)\n\taids = make([]int64, 0, limit)\n\tfor _, rank := range s.rankCache {\n\t\tranks = append(ranks, rank)\n\t\taids = append(aids, rank.Aid)\n\t\tif len(ranks) == limit {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn\n}"} {"input": "package checkers\n\nimport (\n\t\"errors\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/jkomoros/boardgame\"\n\t\"github.com/jkomoros/boardgame/base\"\n\t\"github.com/jkomoros/boardgame/moves\"\n)\n\n\n\n\ntype gameDelegate struct {\n\tbase.GameDelegate\n}\n\nvar memoizedDelegateName string\n\n\n\nfunc (g *gameDelegate) ConfigureMoves() []boardgame.MoveConfig {\n\n\tauto := moves.NewAutoConfigurer(g)\n\n\treturn moves.Combine(\n\n\t\tmoves.Add(\n\t\t\tauto.MustConfig(new(moves.NoOp),\n\t\t\t\tmoves.WithMoveName(\"Example No Op Move\"),\n\t\t\t\tmoves.WithHelpText(\"This move is an example that is always legal and does nothing. It exists to show how to return moves and make sure 'go test' works from the beginning, but you should remove it.\"),\n\t\t\t),\n\t\t),\n\t)\n\n}\n\nfunc (g *gameDelegate) GameStateConstructor() boardgame.ConfigurableSubState {\n\treturn new(gameState)\n}\n\nfunc (g *gameDelegate) PlayerStateConstructor(index boardgame.PlayerIndex) boardgame.ConfigurableSubState {\n\treturn new(playerState)\n}\n\nfunc (g *gameDelegate) DistributeComponentToStarterStack(state boardgame.ImmutableState, c boardgame.Component) (boardgame.ImmutableStack, error) {\n\n\treturn nil, errors.New(\"Not yet implemented\")\n\n}\n\n\n\nfunc NewDelegate() boardgame.GameDelegate {\n\treturn &gameDelegate{}\n}\n\nfunc (g *gameDelegate) Name() string ", "output": "{\n\n\n\tif memoizedDelegateName == \"\" {\n\t\tpkgPath := reflect.ValueOf(g).Elem().Type().PkgPath()\n\t\tpathPieces := strings.Split(pkgPath, \"/\")\n\t\tmemoizedDelegateName = pathPieces[len(pathPieces)-1]\n\t}\n\treturn memoizedDelegateName\n}"} {"input": "package tc\n\n\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype CRStates struct {\n\tCaches map[CacheName]IsAvailable `json:\"caches\"`\n\tDeliveryService map[DeliveryServiceName]CRStatesDeliveryService `json:\"deliveryServices\"`\n}\n\n\ntype CRStatesDeliveryService struct {\n\tDisabledLocations []CacheGroupName `json:\"disabledLocations\"`\n\tIsAvailable bool `json:\"isAvailable\"`\n}\n\n\ntype IsAvailable struct {\n\tIsAvailable bool `json:\"isAvailable\"`\n}\n\n\n\n\n\nfunc (a CRStates) Copy() CRStates {\n\tb := NewCRStates()\n\tfor k, v := range a.Caches {\n\t\tb.Caches[k] = v\n\t}\n\tfor k, v := range a.DeliveryService {\n\t\tb.DeliveryService[k] = v\n\t}\n\treturn b\n}\n\n\nfunc (a CRStates) CopyDeliveryServices() map[DeliveryServiceName]CRStatesDeliveryService {\n\tb := map[DeliveryServiceName]CRStatesDeliveryService{}\n\tfor k, v := range a.DeliveryService {\n\t\tb[k] = v\n\t}\n\treturn b\n}\n\n\nfunc (a CRStates) CopyCaches() map[CacheName]IsAvailable {\n\tb := map[CacheName]IsAvailable{}\n\tfor k, v := range a.Caches {\n\t\tb[k] = v\n\t}\n\treturn b\n}\n\n\nfunc CRStatesMarshall(states CRStates) ([]byte, error) {\n\treturn json.Marshal(states)\n}\n\n\nfunc CRStatesUnMarshall(body []byte) (CRStates, error) {\n\tvar crStates CRStates\n\terr := json.Unmarshal(body, &crStates)\n\treturn crStates, err\n}\n\nfunc NewCRStates() CRStates ", "output": "{\n\treturn CRStates{\n\t\tCaches: map[CacheName]IsAvailable{},\n\t\tDeliveryService: map[DeliveryServiceName]CRStatesDeliveryService{},\n\t}\n}"} {"input": "package naivecheap\n\nimport \"github.com/ffloyd/evergrid-go/global/types\"\n\ntype byPriceAsc []types.WorkerInfo\n\n\n\nfunc (sw byPriceAsc) Swap(i, j int) {\n\tsw[i], sw[j] = sw[j], sw[i]\n}\n\nfunc (sw byPriceAsc) Less(i, j int) bool {\n\treturn sw[i].PricePerTick < sw[j].PricePerTick \n}\n\ntype byQueueAsc []types.WorkerInfo\n\nfunc (sw byQueueAsc) Len() int {\n\treturn len(sw)\n}\n\nfunc (sw byQueueAsc) Swap(i, j int) {\n\tsw[i], sw[j] = sw[j], sw[i]\n}\n\nfunc (sw byQueueAsc) Less(i, j int) bool {\n\treturn sw[i].QueueLength < sw[j].QueueLength \n}\n\nfunc (sw byPriceAsc) Len() int ", "output": "{\n\treturn len(sw)\n}"} {"input": "package client\n\nimport (\n\tuserapi \"github.com/projectatomic/atomic-enterprise/pkg/user/api\"\n)\n\n\ntype UserIdentityMappingsInterface interface {\n\tUserIdentityMappings() UserIdentityMappingInterface\n}\n\n\ntype UserIdentityMappingInterface interface {\n\tGet(string) (*userapi.UserIdentityMapping, error)\n\tCreate(*userapi.UserIdentityMapping) (*userapi.UserIdentityMapping, error)\n\tUpdate(*userapi.UserIdentityMapping) (*userapi.UserIdentityMapping, error)\n\tDelete(string) error\n}\n\n\ntype userIdentityMappings struct {\n\tr *Client\n}\n\n\nfunc newUserIdentityMappings(c *Client) *userIdentityMappings {\n\treturn &userIdentityMappings{\n\t\tr: c,\n\t}\n}\n\n\nfunc (c *userIdentityMappings) Get(name string) (result *userapi.UserIdentityMapping, err error) {\n\tresult = &userapi.UserIdentityMapping{}\n\terr = c.r.Get().Resource(\"userIdentityMappings\").Name(name).Do().Into(result)\n\treturn\n}\n\n\nfunc (c *userIdentityMappings) Create(mapping *userapi.UserIdentityMapping) (result *userapi.UserIdentityMapping, err error) {\n\tresult = &userapi.UserIdentityMapping{}\n\terr = c.r.Post().Resource(\"userIdentityMappings\").Body(mapping).Do().Into(result)\n\treturn\n}\n\n\n\n\n\nfunc (c *userIdentityMappings) Delete(name string) (err error) {\n\terr = c.r.Delete().Resource(\"userIdentityMappings\").Name(name).Do().Error()\n\treturn\n}\n\nfunc (c *userIdentityMappings) Update(mapping *userapi.UserIdentityMapping) (result *userapi.UserIdentityMapping, err error) ", "output": "{\n\tresult = &userapi.UserIdentityMapping{}\n\terr = c.r.Put().Resource(\"userIdentityMappings\").Name(mapping.Name).Body(mapping).Do().Into(result)\n\treturn\n}"} {"input": "package msgpack_test\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/danjac/podbaby/api/Godeps/_workspace/src/gopkg.in/vmihailenco/msgpack.v2\"\n)\n\ntype customStruct struct {\n\tS string\n\tN int\n}\n\nvar (\n\t_ msgpack.CustomEncoder = &customStruct{}\n\t_ msgpack.CustomDecoder = &customStruct{}\n)\n\nfunc (s *customStruct) EncodeMsgpack(enc *msgpack.Encoder) error {\n\treturn enc.Encode(s.S, s.N)\n}\n\n\n\nfunc ExampleCustomEncoder() {\n\tb, err := msgpack.Marshal(&customStruct{S: \"hello\", N: 42})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar v customStruct\n\terr = msgpack.Unmarshal(b, &v)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"%#v\", v)\n}\n\nfunc (s *customStruct) DecodeMsgpack(dec *msgpack.Decoder) error ", "output": "{\n\treturn dec.Decode(&s.S, &s.N)\n}"} {"input": "package events\n\nimport (\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/gravitational/teleport/lib/session\"\n)\n\n\n\ntype DiscardAuditLog struct {\n}\n\nfunc (d *DiscardAuditLog) Close() error {\n\treturn nil\n}\n\nfunc (d *DiscardAuditLog) EmitAuditEvent(eventType string, fields EventFields) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionChunk(namespace string, sid session.ID, reader io.Reader) error {\n\treturn nil\n}\n\nfunc (d *DiscardAuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\nfunc (d *DiscardAuditLog) GetSessionEvents(namespace string, sid session.ID, after int) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchEvents(fromUTC, toUTC time.Time, query string) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchSessionEvents(fromUTC time.Time, toUTC time.Time) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\n\n\n\n\ntype discardSessionLogger struct {\n}\n\nfunc (d *discardSessionLogger) LogEvent(fields EventFields) {\n\treturn\n}\n\nfunc (d *discardSessionLogger) Close() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) Finalize() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) WriteChunk(chunk *SessionChunk) (written int, err error) {\n\treturn 0, nil\n}\n\nfunc (d *DiscardAuditLog) PostSessionSlice(SessionSlice) error ", "output": "{\n\treturn nil\n}"} {"input": "package gumble\n\nimport (\n\t\"strconv\"\n\n\t\"layeh.com/gumble/gumble/MumbleProto\"\n)\n\n\ntype RejectType int\n\n\nconst (\n\tRejectNone RejectType = RejectType(MumbleProto.Reject_None)\n\tRejectVersion RejectType = RejectType(MumbleProto.Reject_WrongVersion)\n\tRejectUserName RejectType = RejectType(MumbleProto.Reject_InvalidUsername)\n\tRejectUserCredentials RejectType = RejectType(MumbleProto.Reject_WrongUserPW)\n\tRejectServerPassword RejectType = RejectType(MumbleProto.Reject_WrongServerPW)\n\tRejectUsernameInUse RejectType = RejectType(MumbleProto.Reject_UsernameInUse)\n\tRejectServerFull RejectType = RejectType(MumbleProto.Reject_ServerFull)\n\tRejectNoCertificate RejectType = RejectType(MumbleProto.Reject_NoCertificate)\n\tRejectAuthenticatorFail RejectType = RejectType(MumbleProto.Reject_AuthenticatorFail)\n)\n\n\n\ntype RejectError struct {\n\tType RejectType\n\tReason string\n}\n\n\n\n\nfunc (e RejectError) Error() string ", "output": "{\n\tvar msg string\n\tswitch e.Type {\n\tcase RejectNone:\n\t\tmsg = \"none\"\n\tcase RejectVersion:\n\t\tmsg = \"wrong client version\"\n\tcase RejectUserName:\n\t\tmsg = \"invalid username\"\n\tcase RejectUserCredentials:\n\t\tmsg = \"incorrect user credentials\"\n\tcase RejectServerPassword:\n\t\tmsg = \"incorrect server password\"\n\tcase RejectUsernameInUse:\n\t\tmsg = \"username in use\"\n\tcase RejectServerFull:\n\t\tmsg = \"server full\"\n\tcase RejectNoCertificate:\n\t\tmsg = \"no certificate\"\n\tcase RejectAuthenticatorFail:\n\t\tmsg = \"authenticator fail\"\n\tdefault:\n\t\tmsg = \"unknown type \" + strconv.Itoa(int(e.Type))\n\t}\n\tif e.Reason != \"\" {\n\t\tmsg += \": \" + e.Reason\n\t}\n\treturn msg\n}"} {"input": "package v1beta1\n\nimport (\n\t\"context\"\n\n\t\"knative.dev/pkg/apis\"\n\t\"knative.dev/pkg/kmp\"\n)\n\nfunc (et *EventType) Validate(ctx context.Context) *apis.FieldError {\n\treturn et.Spec.Validate(ctx).ViaField(\"spec\")\n}\n\n\n\nfunc (et *EventType) CheckImmutableFields(ctx context.Context, original *EventType) *apis.FieldError {\n\tif original == nil {\n\t\treturn nil\n\t}\n\n\tif diff, err := kmp.ShortDiff(original.Spec, et.Spec); err != nil {\n\t\treturn &apis.FieldError{\n\t\t\tMessage: \"Failed to diff EventType\",\n\t\t\tPaths: []string{\"spec\"},\n\t\t\tDetails: err.Error(),\n\t\t}\n\t} else if diff != \"\" {\n\t\treturn &apis.FieldError{\n\t\t\tMessage: \"Immutable fields changed (-old +new)\",\n\t\t\tPaths: []string{\"spec\"},\n\t\t\tDetails: diff,\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (ets *EventTypeSpec) Validate(ctx context.Context) *apis.FieldError ", "output": "{\n\tvar errs *apis.FieldError\n\tif ets.Type == \"\" {\n\t\tfe := apis.ErrMissingField(\"type\")\n\t\terrs = errs.Also(fe)\n\t}\n\treturn errs\n}"} {"input": "package fake_filter_provider\n\nimport (\n\t\"sync\"\n\n\t\"code.cloudfoundry.org/garden-linux/network\"\n\t\"code.cloudfoundry.org/garden-linux/resource_pool\"\n)\n\ntype FakeFilterProvider struct {\n\tProvideFilterStub func(containerId string) network.Filter\n\tprovideFilterMutex sync.RWMutex\n\tprovideFilterArgsForCall []struct {\n\t\tcontainerId string\n\t}\n\tprovideFilterReturns struct {\n\t\tresult1 network.Filter\n\t}\n}\n\nfunc (fake *FakeFilterProvider) ProvideFilter(containerId string) network.Filter {\n\tfake.provideFilterMutex.Lock()\n\tfake.provideFilterArgsForCall = append(fake.provideFilterArgsForCall, struct {\n\t\tcontainerId string\n\t}{containerId})\n\tfake.provideFilterMutex.Unlock()\n\tif fake.ProvideFilterStub != nil {\n\t\treturn fake.ProvideFilterStub(containerId)\n\t} else {\n\t\treturn fake.provideFilterReturns.result1\n\t}\n}\n\nfunc (fake *FakeFilterProvider) ProvideFilterCallCount() int {\n\tfake.provideFilterMutex.RLock()\n\tdefer fake.provideFilterMutex.RUnlock()\n\treturn len(fake.provideFilterArgsForCall)\n}\n\nfunc (fake *FakeFilterProvider) ProvideFilterArgsForCall(i int) string {\n\tfake.provideFilterMutex.RLock()\n\tdefer fake.provideFilterMutex.RUnlock()\n\treturn fake.provideFilterArgsForCall[i].containerId\n}\n\n\n\nvar _ resource_pool.FilterProvider = new(FakeFilterProvider)\n\nfunc (fake *FakeFilterProvider) ProvideFilterReturns(result1 network.Filter) ", "output": "{\n\tfake.ProvideFilterStub = nil\n\tfake.provideFilterReturns = struct {\n\t\tresult1 network.Filter\n\t}{result1}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n)\n\nvar quit = make(chan int)\n\n\n\nfunc main() {\n\n\tgo loop()\n\tgo loop()\n\n\tfor i := 0; i < 2; i++ {\n\t\t<-quit\n\t}\n\n\tfmt.Println()\n}\n\nfunc loop() ", "output": "{\n\tfor i := 0; i < 10; i++ {\n\t\truntime.Gosched() \n\t\tfmt.Printf(\"%d \", i)\n\t}\n\tquit <- 0\n}"} {"input": "package node\n\nimport (\n\t\"errors\"\n\t\"os\"\n\n\tlog \"github.com/cihub/seelog\"\n)\n\n\ntype OptionsDirectory struct {\n\tData string\n\tStorage string\n\tKeystore string\n\tConfig string\n\tRuntime string\n}\n\n\nfunc (options *OptionsDirectory) Check() error {\n\n\tif options.Config != \"\" {\n\t\terr := ensureDirExists(options.Config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr := ensureOrCreateDir(options.Runtime)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ensureOrCreateDir(options.Storage)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ensureOrCreateDir(options.Data)\n}\n\nfunc ensureOrCreateDir(dir string) error {\n\terr := ensureDirExists(dir)\n\tif os.IsNotExist(err) {\n\t\tlog.Info(\"[Directory config checker] \", \"Directory: \", dir, \" does not exit. Creating new one\")\n\t\treturn os.MkdirAll(dir, 0700)\n\t}\n\treturn err\n}\n\n\n\nfunc ensureDirExists(dir string) error ", "output": "{\n\tfileStat, err := os.Stat(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isDir := fileStat.IsDir(); !isDir {\n\t\treturn errors.New(\"directory expected\")\n\t}\n\treturn nil\n}"} {"input": "package models\n\nimport (\n\t\"net\"\n\t\"time\"\n\n\t\"github.com/golang-jwt/jwt/v4\"\n\t\"github.com/google/uuid\"\n)\n\n\nfunc NewIdentityVerification(jti uuid.UUID, username, action string, ip net.IP) (verification IdentityVerification) {\n\treturn IdentityVerification{\n\t\tJTI: jti,\n\t\tIssuedAt: time.Now(),\n\t\tExpiresAt: time.Now().Add(5 * time.Minute),\n\t\tAction: action,\n\t\tUsername: username,\n\t\tIssuedIP: NewIP(ip),\n\t}\n}\n\n\ntype IdentityVerification struct {\n\tID int `db:\"id\"`\n\tJTI uuid.UUID `db:\"jti\"`\n\tIssuedAt time.Time `db:\"iat\"`\n\tIssuedIP IP `db:\"issued_ip\"`\n\tExpiresAt time.Time `db:\"exp\"`\n\tAction string `db:\"action\"`\n\tUsername string `db:\"username\"`\n\tConsumed *time.Time `db:\"consumed\"`\n\tConsumedIP NullIP `db:\"consumed_ip\"`\n}\n\n\n\n\n\n\ntype IdentityVerificationClaim struct {\n\tjwt.RegisteredClaims\n\n\tAction string `json:\"action\"`\n\tUsername string `json:\"username\"`\n}\n\n\nfunc (v IdentityVerificationClaim) ToIdentityVerification() (verification *IdentityVerification, err error) {\n\tjti, err := uuid.Parse(v.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &IdentityVerification{\n\t\tJTI: jti,\n\t\tUsername: v.Username,\n\t\tAction: v.Action,\n\t\tExpiresAt: v.ExpiresAt.Time,\n\t}, nil\n}\n\nfunc (v IdentityVerification) ToIdentityVerificationClaim() (claim *IdentityVerificationClaim) ", "output": "{\n\treturn &IdentityVerificationClaim{\n\t\tRegisteredClaims: jwt.RegisteredClaims{\n\t\t\tID: v.JTI.String(),\n\t\t\tIssuer: \"Authelia\",\n\t\t\tIssuedAt: jwt.NewNumericDate(v.IssuedAt),\n\t\t\tExpiresAt: jwt.NewNumericDate(v.ExpiresAt),\n\t\t},\n\t\tAction: v.Action,\n\t\tUsername: v.Username,\n\t}\n}"} {"input": "package cli\n\nimport (\n\t\"os\"\n\t\"fmt\"\n)\n\n\ntype Cmd interface {\n\tKey() string\n\tDescription() string\n\tExecute(args []string) error\n\tPrintUsage()\n}\n\n\n\ntype CmdHandler interface {\n\tRegisterCmd(Cmd)\n\tHandle()\n\tHandleCmd(key string, args []string)\n\tPrintUsage()\n}\n\n\nfunc NewCmdHandler() CmdHandler {\n\th := initCmdHandler()\n\th.RegisterCmd(NewBuildCmd())\n\treturn h\n}\n\nfunc initCmdHandler() *cmdHandler {\n\th := new(cmdHandler)\n\th.cmds = make(map[string]Cmd)\n\treturn h\n}\n\ntype cmdHandler struct {\n\tcmds map[string]Cmd\n}\n\nfunc (h *cmdHandler) RegisterCmd(cmd Cmd) {\n\tkey := cmd.Key()\n\th.cmds[key] = cmd\n}\n\nfunc (h *cmdHandler) Handle() {\n\targs := os.Args\n\tif args == nil || len(args) < 2 {\n\t\th.handleUsageError(\"Insufficient arguments\")\n\t\treturn\n\t} \n\tkey := args[1]\n\tcmdArgs := args[2:]\n\th.HandleCmd(key, cmdArgs)\n}\n\nfunc (h *cmdHandler) PrintUsage() {\n}\n\nfunc (h *cmdHandler) HandleCmd(key string, args []string) {\n\tcmd := h.cmds[key]\n\tif cmd == nil {\n\t\th.handleUsageError(\"Unrecognized command: \" + key)\n\t\treturn\n\t}\n\terr := cmd.Execute(args)\n\tif err != nil {\n\t\th.handleError(err)\n\t}\n}\n\n\nfunc (h *cmdHandler) handleUsageError(message string) {\n\tfmt.Println(message)\n\th.PrintUsage()\n}\n\n\n\n\nfunc (h *cmdHandler) handleError(err error) ", "output": "{\n\tfmt.Println(err)\n}"} {"input": "package target\n\nimport (\n\t\"os\"\n)\n\n\n\n\n\n\n\nfunc Path(dst string, sources ...string) (bool, error) {\n\tstat, err := os.Stat(os.ExpandEnv(dst))\n\tif os.IsNotExist(err) {\n\t\treturn true, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn PathNewer(stat.ModTime(), sources...)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Dir(dst string, sources ...string) (bool, error) {\n\tdst = os.ExpandEnv(dst)\n\tstat, err := os.Stat(dst)\n\tif os.IsNotExist(err) {\n\t\treturn true, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdestTime := stat.ModTime()\n\tif stat.IsDir() {\n\t\tdestTime, err = NewestModTime(dst)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\treturn DirNewer(destTime, sources...)\n}\n\nfunc Glob(dst string, globs ...string) (bool, error) ", "output": "{\n\tstat, err := os.Stat(os.ExpandEnv(dst))\n\tif os.IsNotExist(err) {\n\t\treturn true, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn GlobNewer(stat.ModTime(), globs...)\n}"} {"input": "package componenttest \n\nimport (\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/trace\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n)\n\n\n\n\nfunc NewNopTelemetrySettings() component.TelemetrySettings ", "output": "{\n\treturn component.TelemetrySettings{\n\t\tLogger: zap.NewNop(),\n\t\tTracerProvider: trace.NewNoopTracerProvider(),\n\t\tMeterProvider: metric.NewNoopMeterProvider(),\n\t\tMetricsLevel: configtelemetry.LevelNone,\n\t}\n}"} {"input": "package box\n\nimport (\n\t\"golang.org/x/crypto/curve25519\"\n\t\"golang.org/x/crypto/nacl/secretbox\"\n\t\"golang.org/x/crypto/salsa20/salsa\"\n\t\"io\"\n)\n\n\nconst Overhead = secretbox.Overhead\n\n\n\nfunc GenerateKey(rand io.Reader) (publicKey, privateKey *[32]byte, err error) {\n\tpublicKey = new([32]byte)\n\tprivateKey = new([32]byte)\n\t_, err = io.ReadFull(rand, privateKey[:])\n\tif err != nil {\n\t\tpublicKey = nil\n\t\tprivateKey = nil\n\t\treturn\n\t}\n\n\tcurve25519.ScalarBaseMult(publicKey, privateKey)\n\treturn\n}\n\nvar zeros [16]byte\n\n\n\n\n\n\n\n\n\n\nfunc Seal(out, message []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) []byte {\n\tvar sharedKey [32]byte\n\tPrecompute(&sharedKey, peersPublicKey, privateKey)\n\treturn secretbox.Seal(out, message, nonce, &sharedKey)\n}\n\n\n\nfunc SealAfterPrecomputation(out, message []byte, nonce *[24]byte, sharedKey *[32]byte) []byte {\n\treturn secretbox.Seal(out, message, nonce, sharedKey)\n}\n\n\n\n\nfunc Open(out, box []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) ([]byte, bool) {\n\tvar sharedKey [32]byte\n\tPrecompute(&sharedKey, peersPublicKey, privateKey)\n\treturn secretbox.Open(out, box, nonce, &sharedKey)\n}\n\n\n\nfunc OpenAfterPrecomputation(out, box []byte, nonce *[24]byte, sharedKey *[32]byte) ([]byte, bool) {\n\treturn secretbox.Open(out, box, nonce, sharedKey)\n}\n\nfunc Precompute(sharedKey, peersPublicKey, privateKey *[32]byte) ", "output": "{\n\tcurve25519.ScalarMult(sharedKey, privateKey, peersPublicKey)\n\tsalsa.HSalsa20(sharedKey, &zeros, sharedKey, &salsa.Sigma)\n}"} {"input": "package tunnel\n\nimport (\n \"container/list\"\n \"time\"\n)\n\ntype recyclerItem struct {\n when time.Time\n buf []byte\n}\n\ntype recycler struct {\n q *list.List\n takeChan, giveChan chan []byte\n}\n\nfunc NewRecycler(size uint32) *recycler {\n r := &recycler{\n q: new(list.List),\n takeChan: make(chan []byte),\n giveChan: make(chan []byte),\n }\n go r.cycle(size)\n return r\n}\n\nfunc (r *recycler) cycle(size uint32) {\n for {\n if r.q.Len() == 0 {\n \n r.q.PushFront(recyclerItem{when: time.Now(), buf: make([]byte, size)})\n }\n i := r.q.Front()\n timeout := time.NewTimer(time.Minute)\n select {\n case b:= <-r.giveChan:\n timeout.Stop()\n r.q.PushFront(recyclerItem{when: time.Now(), buf: b})\n case r.takeChan <- i.Value.(recyclerItem).buf:\n timeout.Stop()\n r.q.Remove(i)\n case <-timeout.C:\n i := r.q.Front()\n for i != nil {\n n := i.Next()\n if time.Since(i.Value.(recyclerItem).when) > time.Minute {\n r.q.Remove(i)\n i.Value = nil\n }\n i = n\n }\n }\n }\n}\n\n\n\nfunc (r *recycler) give(b []byte) {\n r.giveChan <- b\n}\n\nfunc (r *recycler) take() []byte ", "output": "{\n return <-r.takeChan\n}"} {"input": "package entities\n\nconst (\n\tActionMove = iota + 1\n\n\tActionAttack\n\n\tActionCastSpell\n\n\tActionGather\n\n\tActionLoot\n\n\tActionConsume\n)\n\n\n\n\n\n\n\n\n\n\n\ntype Action interface {\n\tSetTarget(Entity)\n\tSetSelf(Entity)\n\n\tGetTypeAction() uint8\n\tGetSelf() Entity\n\tGetTarget() Entity\n\n\tPlay() error\n}\n\n\ntype SimpleAction struct {\n\tself Entity\n\ttarget Entity\n\ttypeAction uint8\n}\n\n\nfunc (action *SimpleAction) GetTypeAction() uint8 {\n\treturn action.GetTypeAction()\n}\n\n\nfunc (action *SimpleAction) SetTarget(target Entity) {\n\taction.target = target\n}\n\n\n\n\n\nfunc (action *SimpleAction) SetSelf(self Entity) {\n\taction.self = self\n}\n\n\nfunc (action *SimpleAction) GetSelf() Entity {\n\treturn action.self\n}\n\n\nfunc (action *SimpleAction) Play() error {\n\treturn nil\n}\n\nfunc (action *SimpleAction) GetTarget() Entity ", "output": "{\n\treturn action.target\n}"} {"input": "package vspk\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"github.com/nuagenetworks/go-bambou/bambou\"\n\t\"strings\"\n)\n\nvar (\n\turlpostfix string\n)\n\n\nfunc NewSession(username, password, organization, url string) (*bambou.Session, *Me) {\n\n\troot := NewMe()\n\turl += urlpostfix\n\n\tsession := bambou.NewSession(username, password, organization, url, root)\n\n\treturn session, root\n}\n\n\nfunc NewX509Session(cert *tls.Certificate, url string) (*bambou.Session, *Me) {\n\n\troot := NewMe()\n\turl += urlpostfix\n\n\tsession := bambou.NewX509Session(cert, url, root)\n\n\treturn session, root\n}\n\n\n\nfunc init() ", "output": "{\n\n\turlpostfix = \"/\" + SDKAPIPrefix + \"/v\" + strings.Replace(fmt.Sprintf(\"%.1v\", SDKAPIVersion), \".\", \"_\", 100)\n}"} {"input": "package route\n\nimport \"unsafe\"\n\nvar (\n\tnativeEndian binaryByteOrder\n\tkernelAlign int\n\trtmVersion byte\n\twireFormats map[int]*wireFormat\n)\n\nfunc init() {\n\ti := uint32(1)\n\tb := (*[4]byte)(unsafe.Pointer(&i))\n\tif b[0] == 1 {\n\t\tnativeEndian = littleEndian\n\t} else {\n\t\tnativeEndian = bigEndian\n\t}\n\trtmVersion = sysRTM_VERSION\n\tkernelAlign, wireFormats = probeRoutingStack()\n}\n\n\n\ntype wireFormat struct {\n\textOff int \n\tbodyOff int \n\tparse func(RIBType, []byte) (Message, error)\n}\n\nfunc roundup(l int) int ", "output": "{\n\tif l == 0 {\n\t\treturn kernelAlign\n\t}\n\treturn (l + kernelAlign - 1) &^ (kernelAlign - 1)\n}"} {"input": "package gogetvers\n\nimport (\n\t\"os\"\n)\n\n\nfunc IsFile(path string) bool {\n\tif len(path) == 0 {\n\t\treturn false\n\t}\n\tfinfo, err := os.Stat(path)\n\treturn err == nil && !finfo.IsDir()\n\n}\n\n\n\n\n\nfunc Mkdir(path string, perm os.FileMode) error {\n\treturn os.MkdirAll(path, perm)\n}\n\nfunc IsDir(path string) bool ", "output": "{\n\tif len(path) == 0 {\n\t\treturn false\n\t}\n\tfinfo, err := os.Stat(path)\n\treturn err == nil && finfo.IsDir()\n}"} {"input": "package perfcounters\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\ntype CountPerTimeInterval32 struct {\n\tlastCount int32\n\tlastTime *time.Time\n\tcurrentCount int32\n\tmu sync.Mutex\n}\n\nfunc NewCountPerTimeInterval32() *CountPerTimeInterval32 {\n\n\treturn &CountPerTimeInterval32{\n\t\tlastTime: nil,\n\t\tlastCount: 0,\n\t\tcurrentCount: 0,\n\t}\n}\n\nfunc (self *CountPerTimeInterval32) Increment() {\n\tself.Add(1)\n}\n\nfunc (self *CountPerTimeInterval32) Add(value int32) {\n\tself.mu.Lock()\n\tdefer self.mu.Unlock()\n\n\tself.currentCount += value\n\n\tif self.lastTime == nil {\n\t\tnow := time.Now()\n\t\tself.lastTime = &now\n\t}\n}\n\nfunc (self *CountPerTimeInterval32) CalculatedValue() float64 {\n\tself.mu.Lock()\n\tdefer self.mu.Unlock()\n\n\tcurrentTime := time.Now()\n\n\tif self.lastTime == nil {\n\t\tself.lastTime = ¤tTime\n\t\treturn 0\n\t}\n\n\tlastTime := *self.lastTime\n\tlastCount := self.lastCount\n\tcurrentCount := self.currentCount\n\n\tcalculatedValue := float64(int64(currentCount-lastCount) / (currentTime.Sub(lastTime).Nanoseconds() / 1e6))\n\n\tself.lastTime = ¤tTime\n\tself.lastCount = currentCount\n\n\treturn calculatedValue\n}\n\n\n\nfunc (self *CountPerTimeInterval32) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%.3f\", self.CalculatedValue())\n}"} {"input": "package gtreap\n\nimport (\n\t\"math/rand\"\n\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\n\n\nfunc (w *Writer) Get(k []byte) (v []byte, err error) {\n\tw.s.m.Lock()\n\tt := w.s.t\n\tw.s.m.Unlock()\n\n\titm := t.Get(&Item{k: k})\n\tif itm != nil {\n\t\treturn itm.(*Item).v, nil\n\t}\n\treturn nil, nil\n}\n\nfunc (w *Writer) Iterator(k []byte) store.KVIterator {\n\tw.s.m.Lock()\n\tt := w.s.t\n\tw.s.m.Unlock()\n\n\treturn newIterator(t).restart(&Item{k: k})\n}\n\nfunc (w *Writer) Close() error {\n\tw.s.availableWriters <- true\n\tw.s = nil\n\n\treturn nil\n}\n\nfunc (w *Writer) Set(k, v []byte) (err error) {\n\tw.s.m.Lock()\n\tw.s.t = w.s.t.Upsert(&Item{k: k, v: v}, rand.Int())\n\tw.s.m.Unlock()\n\n\treturn nil\n}\n\nfunc (w *Writer) Delete(k []byte) (err error) {\n\tw.s.m.Lock()\n\tw.s.t = w.s.t.Delete(&Item{k: k})\n\tw.s.m.Unlock()\n\n\treturn nil\n}\n\nfunc (w *Writer) NewBatch() store.KVBatch {\n\treturn store.NewEmulatedBatch(w, w.s.mo)\n}\n\nfunc (w *Writer) BytesSafeAfterClose() bool ", "output": "{\n\treturn false\n}"} {"input": "package pool\n\nimport (\n\t\"testing\"\n\n\t\"github.com/m3db/m3x/checked\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestCheckedObjectPool(t *testing.T) {\n\ttype obj struct {\n\t\tchecked.RefCount\n\t\tx int\n\t}\n\n\topts := NewObjectPoolOptions().SetSize(1)\n\n\tp := NewCheckedObjectPool(opts)\n\tp.Init(func() checked.ReadWriteRef {\n\t\treturn &obj{}\n\t})\n\n\tassert.Equal(t, 1, checkedObjectPoolLen(p))\n\n\to := p.Get().(*obj)\n\tassert.Equal(t, 0, checkedObjectPoolLen(p))\n\n\to.IncRef()\n\to.IncWrites()\n\to.x = 3\n\to.DecWrites()\n\to.DecRef()\n\to.Finalize()\n\n\tassert.Equal(t, 1, checkedObjectPoolLen(p))\n\n\to = p.Get().(*obj)\n\tassert.Equal(t, 0, checkedObjectPoolLen(p))\n\n\to.IncRef()\n\to.IncReads()\n\tassert.Equal(t, 3, o.x)\n}\n\n\n\nfunc checkedObjectPoolLen(p CheckedObjectPool) int {\n\treturn len(p.(*checkedObjectPool).pool.(*objectPool).values)\n}\n\nfunc TestCheckedObjectPoolNoOptions(t *testing.T) ", "output": "{\n\tp := NewCheckedObjectPool(nil)\n\tassert.NotNil(t, p)\n}"} {"input": "package pathfs\n\nimport (\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/hanwen/go-fuse/fuse\"\n)\n\n\n\nconst _UTIME_NOW = ((1 << 30) - 1)\nconst _UTIME_OMIT = ((1 << 30) - 2)\n\n\n\n\n\n\nfunc timeToTimeval(t *time.Time) syscall.Timeval {\n\tvar tv syscall.Timeval\n\ttv.Usec = int32(t.Nanosecond() / 1000)\n\ttv.Sec = t.Unix()\n\treturn tv\n}\n\n\n\nfunc (fs *loopbackFileSystem) Utimens(path string, a *time.Time, m *time.Time, context *fuse.Context) fuse.Status {\n\ttv := make([]syscall.Timeval, 2)\n\tif a == nil {\n\t\ttv[0].Usec = _UTIME_OMIT\n\t} else {\n\t\ttv[0] = timeToTimeval(a)\n\t}\n\n\tif m == nil {\n\t\ttv[1].Usec = _UTIME_OMIT\n\t} else {\n\t\ttv[1] = timeToTimeval(m)\n\t}\n\n\terr := syscall.Utimes(fs.GetPath(path), tv)\n\treturn fuse.ToStatus(err)\n}\n\nfunc (fs *loopbackFileSystem) StatFs(name string) *fuse.StatfsOut ", "output": "{\n\ts := syscall.Statfs_t{}\n\terr := syscall.Statfs(fs.GetPath(name), &s)\n\tif err == nil {\n\t\treturn &fuse.StatfsOut{\n\t\t\tBlocks: s.Blocks,\n\t\t\tBfree: s.Bfree,\n\t\t\tBavail: s.Bavail,\n\t\t\tFiles: s.Files,\n\t\t\tFfree: s.Ffree,\n\t\t\tBsize: uint32(s.Iosize), \n\t\t\tFrsize: s.Bsize, \n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package refmt\n\nimport (\n\t\"github.com/polydawn/refmt/obj\"\n\t\"github.com/polydawn/refmt/obj/atlas\"\n\t\"github.com/polydawn/refmt/shared\"\n)\n\nfunc Clone(src, dst interface{}) error {\n\treturn CloneAtlased(src, dst, atlas.MustBuild())\n}\nfunc MustClone(src, dst interface{}) {\n\tif err := Clone(src, dst); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc CloneAtlased(src, dst interface{}, atl atlas.Atlas) error {\n\treturn NewCloner(atl).Clone(src, dst)\n}\n\n\ntype Cloner interface {\n\tClone(src, dst interface{}) error\n}\n\nfunc NewCloner(atl atlas.Atlas) Cloner {\n\tx := &cloner{\n\t\tmarshaller: obj.NewMarshaller(atl),\n\t\tunmarshaller: obj.NewUnmarshaller(atl),\n\t}\n\tx.pump = shared.TokenPump{x.marshaller, x.unmarshaller}\n\treturn x\n}\n\ntype cloner struct {\n\tmarshaller *obj.Marshaller\n\tunmarshaller *obj.Unmarshaller\n\tpump shared.TokenPump\n}\n\nfunc (c cloner) Clone(src, dst interface{}) error {\n\tc.marshaller.Bind(src)\n\tc.unmarshaller.Bind(dst)\n\treturn c.pump.Run()\n}\n\nfunc MustCloneAtlased(src, dst interface{}, atl atlas.Atlas) ", "output": "{\n\tif err := CloneAtlased(src, dst, atl); err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package v1alpha1\n\nimport (\n\truntime \"k8s.io/apimachinery/pkg/runtime\"\n)\n\nvar _ runtime.NestedObjectDecoder = &AdmissionConfiguration{}\n\n\n\nfunc (c *AdmissionConfiguration) DecodeNestedObjects(d runtime.Decoder) error {\n\tfor k, v := range c.Plugins {\n\t\tdecodeNestedRawExtensionOrUnknown(d, &v.Configuration)\n\t\tc.Plugins[k] = v\n\t}\n\treturn nil\n}\n\nvar _ runtime.NestedObjectEncoder = &AdmissionConfiguration{}\n\n\n\nfunc (c *AdmissionConfiguration) EncodeNestedObjects(e runtime.Encoder) error {\n\tfor k, v := range c.Plugins {\n\t\tif err := encodeNestedRawExtension(e, &v.Configuration); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.Plugins[k] = v\n\t}\n\treturn nil\n}\n\n\n\nfunc encodeNestedRawExtension(e runtime.Encoder, ext *runtime.RawExtension) error {\n\tif ext.Raw != nil || ext.Object == nil {\n\t\treturn nil\n\t}\n\tdata, err := runtime.Encode(e, ext.Object)\n\tif err != nil {\n\t\treturn err\n\t}\n\text.Raw = data\n\treturn nil\n}\n\nfunc decodeNestedRawExtensionOrUnknown(d runtime.Decoder, ext *runtime.RawExtension) ", "output": "{\n\tif ext.Raw == nil || ext.Object != nil {\n\t\treturn\n\t}\n\tobj, gvk, err := d.Decode(ext.Raw, nil, nil)\n\tif err != nil {\n\t\tunk := &runtime.Unknown{Raw: ext.Raw}\n\t\tif runtime.IsNotRegisteredError(err) {\n\t\t\tif _, gvk, err := d.Decode(ext.Raw, nil, unk); err == nil {\n\t\t\t\tunk.APIVersion = gvk.GroupVersion().String()\n\t\t\t\tunk.Kind = gvk.Kind\n\t\t\t\text.Object = unk\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif gvk != nil {\n\t\t\tunk.APIVersion = gvk.GroupVersion().String()\n\t\t\tunk.Kind = gvk.Kind\n\t\t}\n\t\tobj = unk\n\t}\n\text.Object = obj\n}"} {"input": "package entity\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestDate_MoreThan(t *testing.T) {\n\ttype args struct {\n\t\tdate Date\n\t}\n\ttests := []struct {\n\t\tname string\n\t\tdate Date\n\t\targs args\n\t\twant bool\n\t}{\n\t\t{\"month: 2 > 3\", Date{2000, 2, 29, 1, 1}, args{Date{2000, 3, 1, 20, 1}}, false},\n\t\t{\"minute: 1 > 1\", Date{2000, 2, 29, 1, 1}, args{Date{2000, 2, 29, 1, 1}}, false},\n\t\t{\"vaild: 1 > 0\", Date{2000, 2, 28, 1, 1}, args{Date{2000, 2, 28, 1, 0}}, true},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := tt.date.MoreThan(tt.args.date); got != tt.want {\n\t\t\t\tt.Errorf(\"Date.MoreThan() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestIsValid(t *testing.T) ", "output": "{\n\ttype args struct {\n\t\tdate Date\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant bool\n\t}{\n\t\t{\"leap year\", args{Date{2000, 2, 29, 1, 1}}, true},\n\t\t{\"leap year\", args{Date{2004, 2, 29, 1, 1}}, true},\n\t\t{\"not leap year\", args{Date{1500, 2, 29, 1, 1}}, false},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := IsValid(tt.args.date); got != tt.want {\n\t\t\t\tt.Errorf(\"IsValid() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}"} {"input": "package runtime_test\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/jumbucks/go-jumbucksee/common\"\n\t\"github.com/jumbucks/go-jumbucksee/core/vm/runtime\"\n)\n\n\n\nfunc ExampleExecute() ", "output": "{\n\tret, _, err := runtime.Execute(common.Hex2Bytes(\"6060604052600a8060106000396000f360606040526008565b00\"), nil, nil)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(ret)\n}"} {"input": "package tensor2go\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestVectorBasics(t *testing.T) ", "output": "{\n\n\tv1 := NewVector(3)\n\n\tif v1.Size() != 3 {\n\t\tt.Errorf(\"Vectorsize is %d, expected 3\", v1.Size())\n\t}\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateDbHomeRequest struct {\n\n\tCreateDbHomeWithDbSystemIdDetails CreateDbHomeBase `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateDbHomeRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateDbHomeRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CreateDbHomeRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CreateDbHomeRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateDbHomeResponse struct {\n\n\tRawResponse *http.Response\n\n\tDbHome `presentIn:\"body\"`\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateDbHomeResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response CreateDbHomeResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package events\n\nimport (\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/gravitational/teleport/lib/session\"\n)\n\n\n\ntype DiscardAuditLog struct {\n}\n\nfunc (d *DiscardAuditLog) Close() error {\n\treturn nil\n}\n\nfunc (d *DiscardAuditLog) EmitAuditEvent(eventType string, fields EventFields) error {\n\treturn nil\n}\n\nfunc (d *DiscardAuditLog) PostSessionSlice(SessionSlice) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\nfunc (d *DiscardAuditLog) GetSessionEvents(namespace string, sid session.ID, after int) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchEvents(fromUTC, toUTC time.Time, query string) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchSessionEvents(fromUTC time.Time, toUTC time.Time) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\n\n\n\n\ntype discardSessionLogger struct {\n}\n\nfunc (d *discardSessionLogger) LogEvent(fields EventFields) {\n\treturn\n}\n\nfunc (d *discardSessionLogger) Close() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) Finalize() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) WriteChunk(chunk *SessionChunk) (written int, err error) {\n\treturn 0, nil\n}\n\nfunc (d *DiscardAuditLog) PostSessionChunk(namespace string, sid session.ID, reader io.Reader) error ", "output": "{\n\treturn nil\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetVolumeKmsKeyRequest struct {\n\n\tVolumeId *string `mandatory:\"true\" contributesTo:\"path\" name:\"volumeId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request GetVolumeKmsKeyRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request GetVolumeKmsKeyRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetVolumeKmsKeyRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetVolumeKmsKeyResponse struct {\n\n\tRawResponse *http.Response\n\n\tVolumeKmsKey `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetVolumeKmsKeyResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetVolumeKmsKeyResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetVolumeKmsKeyRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package handlers\n\nimport (\n\t\"net/http\"\n\t\"appengine/user\"\n\t\"appengine\"\n\t\"appengine/datastore\"\n\t\"text/template\"\n\t\"time\"\n\n\t\"model\"\n\t\"model/booth\"\n\t\"util\"\n)\n\n\nfunc HandleBooths(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\thandleGetAllBooths(w, r)\n\t\tbreak;\n\tcase \"POST\":\n\t\thandleCreateBooth(w, r)\n\t\tbreak;\n\tdefault:\n\t\thttp.Error(w, \"\", http.StatusMethodNotAllowed)\n\t}\n}\n\n\nfunc handleGetAllBooths(w http.ResponseWriter, r *http.Request) {\n\tc := appengine.NewContext(r)\n\n\tutil.RedirectIfNotLoggedIn(w, r)\n\n\tq := datastore.NewQuery(\"Booth\").Ancestor(booth.Key(c)).Order(\"-Date\").Limit(10)\n\tbooths := make([]model.Booth, 10)\n\n\tif _, err := q.GetAll(c, &booths); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tboothsTemplate, _ := template.ParseFiles(\"./templates/booths/index.html\")\n\n\tif err := boothsTemplate.Execute(w, booths); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\n\n\n\nfunc handleCreateBooth(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tc := appengine.NewContext(r)\n\tu := user.Current(c)\n\n\tutil.RedirectIfNotLoggedIn(w, r)\n\n\tb := model.Booth{\n\t\tAuthor: u.String(),\n\t\tDate: time.Now(),\n\t\tName: r.FormValue(\"name\"),\n\t}\n\n\tkey := datastore.NewIncompleteKey(c, \"Booth\", booth.Key(c))\n\t_, err := datastore.Put(c, key, &b)\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thttp.Redirect(w, r, \"/\", http.StatusCreated)\n}"} {"input": "package atom\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\ntype Truncater interface {\n\tTruncate(int64) error\n}\n\n\ntype File interface {\n\tio.Reader\n\tio.Writer\n\tio.Seeker\n\tio.Closer\n\n\tTruncater\n}\n\n\n\n\ntype file struct {\n\tto string\n\ttmp *os.File\n\tdirty bool\n}\n\nfunc (f *file) Read(p []byte) (int, error) {\n\treturn f.tmp.Read(p)\n}\n\nfunc (f *file) Write(p []byte) (int, error) {\n\tn, err := f.tmp.Write(p)\n\tif err != nil {\n\t\tf.dirty = true\n\t}\n\n\treturn n, err\n}\n\nfunc (f *file) Seek(offset int64, whence int) (int64, error) {\n\treturn f.tmp.Seek(offset, whence)\n}\n\nfunc (f *file) Truncate(n int64) error {\n\treturn f.tmp.Truncate(n)\n}\n\nfunc (f *file) Close() error {\n\tif err := f.tmp.Close(); err != nil {\n\t\treturn err\n\t}\n\n\tif f.dirty {\n\t\treturn nil\n\t}\n\n\treturn os.Rename(f.tmp.Name(), f.to)\n}\n\nfunc Open(name string) (File, error) ", "output": "{\n\ttmp, err := ioutil.TempFile(filepath.Dir(name), \".jump\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err := os.Stat(name); !os.IsNotExist(err) {\n\t\tfile, err := os.OpenFile(name, os.O_RDWR, 0644)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer file.Close()\n\n\t\t_, err = io.Copy(tmp, file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t_, err = tmp.Seek(0, 0)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &file{to: name, tmp: tmp}, nil\n}"} {"input": "package bno055\n\ntype AxisConfig struct {\n\tX byte\n\tY byte\n\tZ byte\n\tSignX byte\n\tSignY byte\n\tSignZ byte\n}\n\nfunc newAxisConfig(mapConfig, signConfig byte) *AxisConfig {\n\taxisConfig := &AxisConfig{\n\t\tX: mapConfig & 0x03,\n\t\tY: (mapConfig >> 2) & 0x03,\n\t\tZ: (mapConfig >> 4) & 0x03,\n\t\tSignX: (signConfig >> 2) & 0x01,\n\t\tSignY: (signConfig >> 1) & 0x01,\n\t\tSignZ: signConfig & 0x01,\n\t}\n\n\treturn axisConfig\n}\n\n\n\nfunc (c *AxisConfig) Signs() byte {\n\tvar signs byte\n\n\tsigns |= (c.SignX & 0x01) << 2\n\tsigns |= (c.SignY & 0x01) << 1\n\tsigns |= c.SignZ & 0x01\n\n\treturn signs\n}\n\nfunc (c *AxisConfig) Mappings() byte ", "output": "{\n\tvar mappings byte\n\n\tmappings |= (c.Z & 0x03) << 4\n\tmappings |= (c.Y & 0x03) << 2\n\tmappings |= c.X & 0x03\n\n\treturn mappings\n}"} {"input": "package slack\n\nimport (\n\t\"github.com/nlopes/slack\"\n\t\"github.com/pkg/errors\"\n)\n\n\ntype Client struct {\n\tapi *slack.Client\n}\n\n\nfunc NewClient(token string) *Client {\n\treturn &Client{\n\t\tapi: slack.New(token),\n\t}\n}\n\n\nfunc (c *Client) GetChannelID(channel string) (string, error) {\n\tchs, err := c.api.GetChannels(true)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to list Slack channels\")\n\t}\n\n\tfor _, ch := range chs {\n\t\tif ch.Name == channel {\n\t\t\treturn ch.ID, nil\n\t\t}\n\t}\n\n\treturn \"\", errors.Errorf(\"channel %s is not found\", channel)\n}\n\n\n\n\nfunc (c *Client) PostMessageWithAttachment(channelID, color, title, text string, fields []*AttachmentField) error ", "output": "{\n\tattachmentFields := []slack.AttachmentField{}\n\n\tfor _, field := range fields {\n\t\tattachmentFields = append(attachmentFields, slack.AttachmentField{\n\t\t\tTitle: field.Title,\n\t\t\tValue: field.Value,\n\t\t\tShort: true,\n\t\t})\n\t}\n\n\tparams := slack.PostMessageParameters{\n\t\tAttachments: []slack.Attachment{\n\t\t\tslack.Attachment{\n\t\t\t\tTitle: title,\n\t\t\t\tText: text,\n\t\t\t\tColor: color,\n\t\t\t\tFields: attachmentFields,\n\t\t\t},\n\t\t},\n\t}\n\n\t_, _, err := c.api.PostMessage(channelID, \"\", params)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to post message to Slack\")\n\t}\n\n\treturn nil\n}"} {"input": "package lib\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc benchmarkReduceToDiff(modulesCount, deltaCount int, b *testing.B) {\n\tclean()\n\tdefer clean()\n\n\trepo := NewTestRepoForBench(b, \".tmp/repo\")\n\n\tfor i := 0; i < modulesCount; i++ {\n\t\terr := repo.InitModule(fmt.Sprintf(\"app-%v\", i))\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"%v\", err)\n\t\t}\n\t}\n\n\terr := repo.Commit(\"first\")\n\tif err != nil {\n\t\tb.Fatalf(\"%v\", err)\n\t}\n\n\tc1 := repo.LastCommit\n\n\tfor i := 0; i < deltaCount; i++ {\n\t\terr = repo.WriteContent(fmt.Sprintf(\"content/file-%v\", i), \"sample content\")\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"%v\", err)\n\t\t}\n\t}\n\n\trepo.Commit(\"second\")\n\tc2 := repo.LastCommit\n\n\tworld := NewBenchmarkWorld(b, \".tmp/repo\")\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, err = world.System.ManifestByDiff(c1.String(), c2.String())\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"%v\", err)\n\t\t}\n\n\t}\n\n\tb.StopTimer()\n}\nfunc BenchmarkReduceToDiff10(b *testing.B) {\n\tbenchmarkReduceToDiff(10, 10, b)\n}\n\n\n\nfunc BenchmarkReduceToDiff1000(b *testing.B) {\n\tbenchmarkReduceToDiff(1000, 1000, b)\n}\n\nfunc BenchmarkReduceToDiff10000(b *testing.B) {\n\tbenchmarkReduceToDiff(10000, 10000, b)\n}\n\nfunc BenchmarkReduceToDiff100(b *testing.B) ", "output": "{\n\tbenchmarkReduceToDiff(100, 100, b)\n}"} {"input": "package unibyte\n\nimport \"unicode\"\n\n\nfunc IsLower(b byte) bool {\n\treturn b >= 'a' && b <= 'z'\n}\n\n\nfunc IsUpper(b byte) bool {\n\treturn b >= 'A' && b <= 'Z'\n}\n\n\nfunc IsLetter(b byte) bool {\n\treturn IsLower(b) || IsUpper(b)\n}\n\n\nfunc IsSpaceQuote(b byte) bool {\n\treturn IsSpace(b) || b == '\"' || b == '\\''\n}\n\n\nfunc IsSpace(b byte) bool {\n\treturn unicode.IsSpace(rune(b))\n}\n\n\n\n\n\nfunc ToUpper(b byte) byte {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn b\n}\n\n\nfunc ToLowerString(b byte) string {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn string(b)\n}\n\n\nfunc ToUpperString(b byte) string {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn string(b)\n}\n\nfunc ToLower(b byte) byte ", "output": "{\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn b\n}"} {"input": "package validator\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\nfunc IsNull(str string) bool {\n\treturn len(str) == 0\n}\n\nfunc IsWord(str string, params ...int) bool {\n\tif IsNull(str) {\n\t\treturn false\n\t}\n\treturn rxWord.MatchString(str)\n}\n\nfunc IsTime(str string, format string) bool {\n\t_, err := time.Parse(format, str)\n\treturn err == nil\n}\n\nfunc IsDate(str string, format ...string) bool {\n\n\tif len(format) == 0 {\n\n\t\tif len(strings.Split(str, \"/\")) > 1 {\n\t\t\treturn IsTime(str, \"2006/01/02\")\n\t\t}\n\n\t\tif len(strings.Split(str, \"-\")) > 1 {\n\t\t\treturn IsTime(str, \"2006-01-02\")\n\t\t}\n\n\t\treturn false\n\t}\n\n\treturn IsTime(str, format[0])\n}\n\nfunc IsEmpty(str string) bool {\n\treturn len(strings.TrimSpace(str)) == 0\n}\n\nfunc IsRequestURI(rawurl string) bool {\n\t_, err := url.ParseRequestURI(rawurl)\n\treturn err == nil\n}\n\n\n\nfunc IsMobilePhone(str string) bool {\n\tif IsEmpty(str) {\n\t\treturn false\n\t}\n\treturn rxMobolePhone.MatchString(str)\n}\n\nfunc IsURI(str string) bool ", "output": "{\n\trelation := false\n\tfor idx, val := range str {\n\t\tif val == '.' {\n\t\t\trelation = true\n\t\t\tcontinue\n\t\t}\n\t\tif val == '/' || val == '\\\\' {\n\t\t\tif idx < len(str)-1 {\n\t\t\t\tif str[idx+1] == '.' {\n\t\t\t\t\trelation = true\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif relation && (val != '/' && val != '\\\\') {\n\t\t\treturn false\n\t\t}\n\t\treturn IsRequestURI(str[idx:])\n\t}\n\treturn false\n}"} {"input": "package gobot\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"gobot.io/x/gobot/gobottest\"\n)\n\n\n\nfunc TestEventerDeleteEvent(t *testing.T) {\n\te := NewEventer()\n\te.AddEvent(\"test1\")\n\te.DeleteEvent(\"test1\")\n\n\tif _, ok := e.Events()[\"test1\"]; ok {\n\t\tt.Errorf(\"Could not add delete event from list of Event names\")\n\t}\n}\n\nfunc TestEventerOn(t *testing.T) {\n\te := NewEventer()\n\te.AddEvent(\"test\")\n\n\tsem := make(chan bool)\n\te.On(\"test\", func(data interface{}) {\n\t\tsem <- true\n\t})\n\n\tgo func() {\n\t\te.Publish(\"test\", true)\n\t}()\n\n\tselect {\n\tcase <-sem:\n\tcase <-time.After(10 * time.Millisecond):\n\t\tt.Errorf(\"On was not called\")\n\t}\n}\n\nfunc TestEventerOnce(t *testing.T) {\n\te := NewEventer()\n\te.AddEvent(\"test\")\n\n\tsem := make(chan bool)\n\te.Once(\"test\", func(data interface{}) {\n\t\tsem <- true\n\t})\n\n\tgo func() {\n\t\te.Publish(\"test\", true)\n\t}()\n\n\tselect {\n\tcase <-sem:\n\tcase <-time.After(10 * time.Millisecond):\n\t\tt.Errorf(\"Once was not called\")\n\t}\n\n\tgo func() {\n\t\te.Publish(\"test\", true)\n\t}()\n\n\tselect {\n\tcase <-sem:\n\t\tt.Errorf(\"Once was called twice\")\n\tcase <-time.After(10 * time.Millisecond):\n\t}\n}\n\nfunc TestEventerAddEvent(t *testing.T) ", "output": "{\n\te := NewEventer()\n\te.AddEvent(\"test\")\n\n\tif _, ok := e.Events()[\"test\"]; !ok {\n\t\tt.Errorf(\"Could not add event to list of Event names\")\n\t}\n\tgobottest.Assert(t, e.Event(\"test\"), \"test\")\n}"} {"input": "package controller\n\nimport (\n\t\"fmt\"\n)\n\ntype AdminParams struct {\n\tName *string\n\tInviteId *string\n\tInviteKey *string\n\tConfirmDelete *string\n}\n\nfunc NewAdminParams() *AdminParams {\n\treturn new(AdminParams)\n}\n\nfunc (params *AdminParams) ValidateName(required bool) error {\n\tif required && *params.Name == \"\" {\n\t\treturn fmt.Errorf(\"name cannot be empty\")\n\t}\n\treturn nil\n}\n\n\nfunc (params *AdminParams) ValidateInviteKey(required bool) error { return nil }\n\nfunc (params *AdminParams) ValidateInviteId(required bool) error ", "output": "{ return nil }"} {"input": "package hashing_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/vlad-doru/experimento/backend/utils/hashing\"\n\t\"github.com/vlad-doru/experimento/backend/utils/test\"\n)\n\nfunc TestHashFloat(t *testing.T) {\n\tseed := hashing.Hash(\"experimento\")\n\ttest.SetSeed(1) \n\tfor i := 0; i < 100000; i++ {\n\t\tid := test.RandString(6, 10)\n\t\tf := hashing.HashFloat(id, seed)\n\t\tassert.True(t, (f >= 0) && (f < 1),\n\t\t\t\"Invariant violation of the hash function for id %s: %v\", id, f)\n\t}\n}\n\n\n\nfunc BenchmarkHashFloat(b *testing.B) {\n\tseed := hashing.Hash(\"experimento\")\n\tfor i := 0; i < b.N; i++ {\n\t\thashing.HashFloat(\"hashing_id\", seed)\n\t}\n}\n\nfunc BenchmarkHash(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\thashing.Hash(\"experimento\")\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"reflect\"\n\t\"runtime\"\n)\n\n\n\n\nfunc GetFuncName(i interface{}) string ", "output": "{\n\treturn runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()\n}"} {"input": "package fischer\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\tgenericregistry \"k8s.io/apiserver/pkg/registry/generic/registry\"\n\t\"k8s.io/sample-apiserver/pkg/apis/wardle\"\n\t\"k8s.io/sample-apiserver/pkg/registry\"\n)\n\n\n\n\nfunc NewREST(scheme *runtime.Scheme, optsGetter generic.RESTOptionsGetter) (*registry.REST, error) ", "output": "{\n\tstrategy := NewStrategy(scheme)\n\n\tstore := &genericregistry.Store{\n\t\tCopier: scheme,\n\t\tNewFunc: func() runtime.Object { return &wardle.Fischer{} },\n\t\tNewListFunc: func() runtime.Object { return &wardle.FischerList{} },\n\t\tPredicateFunc: MatchFischer,\n\t\tDefaultQualifiedResource: wardle.Resource(\"fischers\"),\n\n\t\tCreateStrategy: strategy,\n\t\tUpdateStrategy: strategy,\n\t\tDeleteStrategy: strategy,\n\t}\n\toptions := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ®istry.REST{store}, nil\n}"} {"input": "package builtin\n\nconst pppSummary = `allows operating as the ppp service`\n\nconst pppBaseDeclarationSlots = `\n ppp:\n allow-installation:\n slot-snap-type:\n - core\n deny-auto-connection: true\n`\n\nconst pppConnectedPlugAppArmor = `\n# Description: Allow operating ppp daemon. This gives privileged access to the\n# ppp daemon.\n\n# Needed for modem connections using PPP\n/usr/sbin/pppd ix,\n/etc/ppp/** rwix,\n/dev/ppp rw,\n/dev/tty[^0-9]* rw,\n/run/lock/*tty[^0-9]* rw,\n/run/ppp* rw,\n/var/run/ppp* rw,\n/var/log/ppp* rw,\n/bin/run-parts ix,\n@{PROC}/@{pid}/loginuid r,\ncapability setgid,\ncapability setuid,\n`\n\n\n\n\nvar pppConnectedPlugKmod = []string{\n\t\"ppp_generic\",\n}\n\nvar pppConnectedPlugUDev = []string{\n\t`KERNEL==\"ppp\"`,\n\t`KERNEL==\"tty[a-zA-Z]*[0-9]*\"`,\n}\n\n\n\nfunc init() ", "output": "{\n\tregisterIface(&commonInterface{\n\t\tname: \"ppp\",\n\t\tsummary: pppSummary,\n\t\timplicitOnCore: true,\n\t\timplicitOnClassic: true,\n\t\tbaseDeclarationSlots: pppBaseDeclarationSlots,\n\t\tconnectedPlugAppArmor: pppConnectedPlugAppArmor,\n\t\tconnectedPlugKModModules: pppConnectedPlugKmod,\n\t\tconnectedPlugUDev: pppConnectedPlugUDev,\n\t\treservedForOS: true,\n\t})\n}"} {"input": "package problem0188\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\nvar tcs = []struct {\n\tk int\n prices []int\n\tans int\n}{\n\n\n\n}\n\n\n\nfunc Benchmark_maxProfit(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, tc := range tcs {\n\t\t\tmaxProfit(tc.k, tc.prices)\n\t\t}\n\t}\n}\n\nfunc Test_maxProfit(t *testing.T) ", "output": "{\n\ta := assert.New(t)\n\n\tfor _, tc := range tcs {\n\t\ta.Equal(tc.ans, maxProfit(tc.k, tc.prices), \"输入:%v\", tc)\n\t}\n}"} {"input": "package env\n\nimport (\n\t\"os\"\n\t\"strconv\"\n)\n\nfunc GetEnvAsStringOrFallback(key, defaultValue string) string {\n\tif v := os.Getenv(key); v != \"\" {\n\t\treturn v\n\t}\n\treturn defaultValue\n}\n\n\n\nfunc GetEnvAsFloat64OrFallback(key string, defaultValue float64) (float64, error) {\n\tif v := os.Getenv(key); v != \"\" {\n\t\tvalue, err := strconv.ParseFloat(v, 64)\n\t\tif err != nil {\n\t\t\treturn defaultValue, err\n\t\t}\n\t\treturn value, nil\n\t}\n\treturn defaultValue, nil\n}\n\nfunc GetEnvAsIntOrFallback(key string, defaultValue int) (int, error) ", "output": "{\n\tif v := os.Getenv(key); v != \"\" {\n\t\tvalue, err := strconv.Atoi(v)\n\t\tif err != nil {\n\t\t\treturn defaultValue, err\n\t\t}\n\t\treturn value, nil\n\t}\n\treturn defaultValue, nil\n}"} {"input": "package client\n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\n\n\nfunc WrapperUnaryClient(interceptors ...grpc.UnaryClientInterceptor) grpc.UnaryClientInterceptor {\n\treturn func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {\n\t\th := wrap(invoker, interceptors...)\n\t\treturn h(ctx, method, req, reply, cc, opts...)\n\t}\n}\n\n\n\n\nfunc wrap(ui grpc.UnaryInvoker, interceptors ...grpc.UnaryClientInterceptor) grpc.UnaryInvoker ", "output": "{\n\tfor _, i := range interceptors {\n\t\th := func(current grpc.UnaryClientInterceptor, next grpc.UnaryInvoker) grpc.UnaryInvoker {\n\t\t\treturn func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, opts ...grpc.CallOption) error {\n\t\t\t\treturn current(ctx, method, req, reply, cc, next, opts...)\n\t\t\t}\n\t\t}\n\t\tui = h(i, ui)\n\t}\n\treturn ui\n}"} {"input": "package goku\n\nimport (\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype TestReader struct{}\n\nfunc (self TestReader) Read() ([]Message, error) {\n\ttime.Sleep(10 * time.Millisecond)\n\treturn []Message{\"Hello\"}, nil\n}\n\ntype TestWriter struct {\n\tmsgs []Message\n}\n\nfunc (self *TestWriter) Write(msgs []Message) error {\n\tfor _, msg := range msgs {\n\t\tself.msgs = append(self.msgs, msg)\n\t}\n\treturn nil\n}\n\n\n\nfunc TestNewQueueSetsupWriter(t *testing.T) {\n\tt.Parallel()\n\n\twriter := &TestWriter{}\n\tq := NewQueue(nil, writer)\n\n\tq.Receiver() <- \"Hello\"\n\tq.Receiver() <- \"World\"\n\n\truntime.Gosched()\n\n\tif count := len(writer.msgs); count != 2 {\n\t\tt.Errorf(\"messages written == %d, want 2\", count)\n\t}\n}\n\nfunc TestNewQueueSetupReader(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\tq := NewQueue(&TestReader{}, nil)\n\n\tselect {\n\tcase <-q.Sender():\n\t\tbreak\n\tcase <-time.After(100 * time.Millisecond):\n\t\tt.Fatal(\"Timeout expired\")\n\t}\n}"} {"input": "package gocleanup\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\nvar cleanupFuncs []func()\nvar capturingSignals bool\n\n\n\n\n\n\n\n\n\nfunc Cleanup() {\n\tfor _, f := range cleanupFuncs {\n\t\tf()\n\t}\n\tcleanupFuncs = []func(){}\n}\n\n\nfunc Exit(status int) {\n\tCleanup()\n\tos.Exit(status)\n}\n\nfunc Register(f func()) ", "output": "{\n\tcleanupFuncs = append(cleanupFuncs, f)\n\tif !capturingSignals {\n\t\tcapturingSignals = true\n\t\tgo func() {\n\t\t\tc := make(chan os.Signal, 1)\n\t\t\tsignal.Notify(c, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM)\n\n\t\t\t<-c\n\t\t\tExit(1)\n\t\t}()\n\t}\n}"} {"input": "package swt\n\nimport \"github.com/timob/javabind\"\nimport \"unsafe\"\n\n\n\nimport \"C\"\n\nfunc go_callback_EventsSegmentListenerNative_GetSegments(env unsafe.Pointer, obj uintptr, arg_0 uintptr) {\n rObj := &javabind.Callable{javabind.WrapJObject(obj, \"org/eclipse/swt/events/SegmentListenerNative\", false)}\n hash, err := rObj.CallMethod(javabind.GetEnv(), \"hashCode\", javabind.Int)\n if err != nil {\n panic(err)\n }\n\n i := EventsSegmentListenerNativeMap[hash.(int)]\n \tretcon_a := javabind.NewJavaToGoCallable()\n\tdst_a := &javabind.Callable{}\n\tretcon_a.Dest(dst_a)\n\tif err := retcon_a.Convert(javabind.WrapJObject(arg_0, \"org/eclipse/swt/events/SegmentEvent\", false)); err != nil {\n\t\tpanic(err)\n\t}\n\targ_a := &EventsSegmentEvent{}\n\targ_a.Callable = dst_a\ni.GetSegments(arg_a)\n}\n\nvar EventsSegmentListenerNativeMap = make(map[int]EventsSegmentListenerInterface)\n\ntype EventsSegmentListenerNative struct {\n\t*javabind.Callable\n\tEventsSegmentListenerInterface\n}\n\n\n\n\n func init() {\n javabind.OnJVMStart(func() {\n javabind.GetEnv().RegisterNative(\"org/eclipse/swt/events/SegmentListenerNative\", \"getSegments\", javabind.Void, []interface{}{\"org/eclipse/swt/events/SegmentEvent\"}, C.go_callback_EventsSegmentListenerNative_GetSegments)\n\n })\n }\n\nfunc NewEventsSegmentListenerNative(implementation EventsSegmentListenerInterface) *EventsSegmentListenerNative ", "output": "{\n\n\tobj, err := javabind.GetEnv().NewObject(\"org/eclipse/swt/events/SegmentListenerNative\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tx := &EventsSegmentListenerNative{}\n\tx.Callable = &javabind.Callable{obj}\n\n hash, err := x.Callable.CallMethod(javabind.GetEnv(), \"hashCode\", javabind.Int)\n if err != nil {\n panic(err)\n }\n EventsSegmentListenerNativeMap[hash.(int)] = implementation\n\treturn x\n}"} {"input": "package custom_commands\n\nimport (\n\t\"github.com/jmoiron/sqlx\"\n\t\"github.com/sgt-kabukiman/kabukibot/bot\"\n)\n\ntype pluginStruct struct {\n\tdb *sqlx.DB\n}\n\n\n\nfunc (self *pluginStruct) Name() string {\n\treturn \"custom_commands\"\n}\n\nfunc (self *pluginStruct) Setup(bot *bot.Kabukibot) {\n\tself.db = bot.Database()\n}\n\nfunc (self *pluginStruct) CreateWorker(channel bot.Channel) bot.PluginWorker {\n\treturn &worker{\n\t\tchannel: channel,\n\t\tacl: channel.ACL(),\n\t\tdb: self.db,\n\t}\n}\n\nfunc NewPlugin() *pluginStruct ", "output": "{\n\treturn &pluginStruct{}\n}"} {"input": "package dax\n\n\ntype Grapher interface {\n\tGetParent() Grapher\n\tAddChild(child Grapher)\n\tGetChildren() []Grapher\n}\n\ntype nodeStack struct {\n\tnodes []Grapher\n}\n\nfunc (s *nodeStack) Init() {\n\ts.nodes = make([]Grapher, 0, 16)\n}\n\nfunc (s *nodeStack) Empty() bool {\n\treturn len(s.nodes) == 0\n}\n\nfunc (s *nodeStack) Push(n Grapher) {\n\ts.nodes = append(s.nodes, n)\n}\n\nfunc (s *nodeStack) Pop() Grapher {\n\ti := len(s.nodes) - 1\n\tn := s.nodes[i]\n\ts.nodes[i] = nil\n\ts.nodes = s.nodes[:i]\n\treturn n\n}\n\ntype SceneGraph struct {\n\tNode\n}\n\nfunc NewSceneGraph() *SceneGraph {\n\tsg := new(SceneGraph)\n\tsg.Init()\n\treturn sg\n}\n\nfunc (sg *SceneGraph) Init() {\n\tsg.Node.Init()\n}\n\nfunc (sg *SceneGraph) updateWorldTransform() {\n\tsg.Node.updateWorldTransform(false)\n}\n\nfunc (sg *SceneGraph) Update(time float64) {\n\tsg.updateWorldTransform()\n}\n\n\n\n\nfunc (sg *SceneGraph) Draw(fb Framebuffer) {\n\tfb.render().drawSceneGraph(fb, sg)\n}\n\nfunc (sg *SceneGraph) Traverse() <-chan Grapher ", "output": "{\n\tch := make(chan Grapher)\n\n\tgo func() {\n\t\tvar stack nodeStack\n\n\t\tstack.Init()\n\t\tstack.Push(sg)\n\n\t\tfor !stack.Empty() {\n\t\t\tn := stack.Pop()\n\t\t\tch <- n\n\t\t\tchildren := n.GetChildren()\n\t\t\tfor i := len(children) - 1; i >= 0; i-- {\n\t\t\t\tstack.Push(children[i])\n\t\t\t}\n\t\t}\n\t\tclose(ch)\n\t}()\n\n\treturn ch\n}"} {"input": "package builtin\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/madlambda/nash/errors\"\n\t\"github.com/madlambda/nash/sh\"\n)\n\ntype (\n\tformatFn struct {\n\t\tfmt string\n\t\targs []interface{}\n\t}\n)\n\nfunc newFormat() *formatFn {\n\treturn &formatFn{}\n}\n\nfunc (f *formatFn) ArgNames() []sh.FnArg {\n\treturn []sh.FnArg{\n\t\tsh.NewFnArg(\"fmt\", false),\n\t\tsh.NewFnArg(\"arg...\", true),\n\t}\n}\n\n\n\nfunc (f *formatFn) SetArgs(args []sh.Obj) error {\n\tif len(args) == 0 {\n\t\treturn errors.NewError(\"format expects at least 1 argument\")\n\t}\n\n\tf.fmt = args[0].String()\n\tf.args = nil\n\n\tfor _, arg := range args[1:] {\n\t\tf.args = append(f.args, arg.String())\n\t}\n\n\treturn nil\n}\n\nfunc (f *formatFn) Run(in io.Reader, out io.Writer, err io.Writer) ([]sh.Obj, error) ", "output": "{\n\treturn []sh.Obj{sh.NewStrObj(fmt.Sprintf(f.fmt, f.args...))}, nil\n}"} {"input": "package minion\n\nimport (\n\t\"testing\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/fields\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/labels\"\n)\n\n\n\nfunc TestMatchNode(t *testing.T) ", "output": "{\n\ttestFieldMap := map[bool][]fields.Set{\n\t\ttrue: {\n\t\t\t{\"metadata.name\": \"foo\"},\n\t\t},\n\t\tfalse: {\n\t\t\t{\"foo\": \"bar\"},\n\t\t},\n\t}\n\n\tfor expectedResult, fieldSet := range testFieldMap {\n\t\tfor _, field := range fieldSet {\n\t\t\tm := MatchNode(labels.Everything(), field.AsSelector())\n\t\t\t_, matchesSingle := m.MatchesSingle()\n\t\t\tif e, a := expectedResult, matchesSingle; e != a {\n\t\t\t\tt.Errorf(\"%+v: expected %v, got %v\", e, a)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package binlogplayer\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"vitess.io/vitess/go/sqltypes\"\n)\n\ntype fakeDBClient struct {\n}\n\n\n\nfunc NewFakeDBClient() DBClient {\n\treturn &fakeDBClient{}\n}\n\nfunc (dc *fakeDBClient) DBName() string {\n\treturn \"db\"\n}\n\nfunc (dc *fakeDBClient) Connect() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Begin() error {\n\treturn nil\n}\n\n\n\nfunc (dc *fakeDBClient) Rollback() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Close() {\n}\n\nfunc (dc *fakeDBClient) ExecuteFetch(query string, maxrows int) (qr *sqltypes.Result, err error) {\n\tquery = strings.ToLower(query)\n\tswitch {\n\tcase strings.HasPrefix(query, \"insert\"):\n\t\treturn &sqltypes.Result{InsertID: 1}, nil\n\tcase strings.HasPrefix(query, \"update\"):\n\t\treturn &sqltypes.Result{RowsAffected: 1}, nil\n\tcase strings.HasPrefix(query, \"delete\"):\n\t\treturn &sqltypes.Result{RowsAffected: 1}, nil\n\tcase strings.HasPrefix(query, \"select\"):\n\t\tif strings.Contains(query, \"where\") {\n\t\t\treturn sqltypes.MakeTestResult(\n\t\t\t\tsqltypes.MakeTestFields(\n\t\t\t\t\t\"id|state|source\",\n\t\t\t\t\t\"int64|varchar|varchar\",\n\t\t\t\t),\n\t\t\t\t`1|Running|keyspace:\"ks\" shard:\"0\" key_range: `,\n\t\t\t), nil\n\t\t}\n\t\treturn &sqltypes.Result{}, nil\n\tcase strings.HasPrefix(query, \"use\"):\n\t\treturn &sqltypes.Result{}, nil\n\t}\n\treturn nil, fmt.Errorf(\"unexpected: %v\", query)\n}\n\nfunc (dc *fakeDBClient) Commit() error ", "output": "{\n\treturn nil\n}"} {"input": "package byteorder\n\nimport (\n\t\"encoding/binary\"\n\t\"net\"\n\t\"testing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\n\n\n\ntype ByteorderSuite struct{}\n\nvar _ = Suite(&ByteorderSuite{})\n\nfunc (b *ByteorderSuite) TestNativeIsInitialized(c *C) {\n\tc.Assert(Native, NotNil)\n}\n\nfunc (b *ByteorderSuite) TestHostToNetwork(c *C) {\n\tswitch Native {\n\tcase binary.LittleEndian:\n\t\tc.Assert(HostToNetwork16(0xAABB), Equals, uint16(0xBBAA))\n\t\tc.Assert(HostToNetwork32(0xAABBCCDD), Equals, uint32(0xDDCCBBAA))\n\tcase binary.BigEndian:\n\t\tc.Assert(HostToNetwork16(0xAABB), Equals, uint16(0xAABB))\n\t\tc.Assert(HostToNetwork32(0xAABBCCDD), Equals, uint32(0xAABBCCDD))\n\t}\n}\n\nfunc (b *ByteorderSuite) TestNetIPv4ToHost32(c *C) {\n\tswitch Native {\n\tcase binary.LittleEndian:\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.129.91\")), Equals, uint32(0x5b810b0a))\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.138.214\")), Equals, uint32(0xd68a0b0a))\n\tcase binary.BigEndian:\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.129.91\")), Equals, uint32(0x0a0b815b))\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.138.214\")), Equals, uint32(0x0a0b8ad6))\n\t}\n}\n\nfunc Test(t *testing.T) ", "output": "{\n\tTestingT(t)\n}"} {"input": "package testclient\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\tclientgotesting \"k8s.io/client-go/testing\"\n\n\tuserapi \"github.com/openshift/origin/pkg/user/apis/user\"\n)\n\n\n\ntype FakeIdentities struct {\n\tFake *Fake\n}\n\nvar identitiesResource = schema.GroupVersionResource{Group: \"\", Version: \"\", Resource: \"identities\"}\n\nfunc (c *FakeIdentities) Get(name string, options metav1.GetOptions) (*userapi.Identity, error) {\n\tobj, err := c.Fake.Invokes(clientgotesting.NewRootGetAction(identitiesResource, name), &userapi.Identity{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*userapi.Identity), err\n}\n\n\n\nfunc (c *FakeIdentities) Create(inObj *userapi.Identity) (*userapi.Identity, error) {\n\tobj, err := c.Fake.Invokes(clientgotesting.NewRootCreateAction(identitiesResource, inObj), inObj)\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*userapi.Identity), err\n}\n\nfunc (c *FakeIdentities) Update(inObj *userapi.Identity) (*userapi.Identity, error) {\n\tobj, err := c.Fake.Invokes(clientgotesting.NewRootUpdateAction(identitiesResource, inObj), inObj)\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*userapi.Identity), err\n}\n\nfunc (c *FakeIdentities) Delete(name string) error {\n\t_, err := c.Fake.Invokes(clientgotesting.NewRootDeleteAction(identitiesResource, name), nil)\n\treturn err\n}\n\nfunc (c *FakeIdentities) List(opts metav1.ListOptions) (*userapi.IdentityList, error) ", "output": "{\n\tobj, err := c.Fake.Invokes(clientgotesting.NewRootListAction(identitiesResource, opts), &userapi.IdentityList{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*userapi.IdentityList), err\n}"} {"input": "package butteredscones\n\nimport (\n\t\"time\"\n)\n\n\n\ntype Spooler struct {\n\tIn chan *FileData\n\tOut chan []*FileData\n\n\tsize int\n\ttimeout time.Duration\n}\n\nconst (\n\tspoolOutBuffer = 4\n)\n\n\n\n\n\nfunc (s *Spooler) Spool() {\n\ttimer := time.NewTimer(s.timeout)\n\tcurrentChunk := make([]*FileData, 0, s.size)\n\tfor {\n\t\tselect {\n\t\tcase fileData, ok := <-s.In:\n\t\t\tif ok {\n\t\t\t\tcurrentChunk = append(currentChunk, fileData)\n\t\t\t\tif len(currentChunk) >= s.size {\n\t\t\t\t\ts.Out <- currentChunk\n\t\t\t\t\tcurrentChunk = make([]*FileData, 0, s.size)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-timer.C:\n\t\t\tif len(currentChunk) > 0 {\n\t\t\t\tselect {\n\t\t\t\tcase s.Out <- currentChunk:\n\t\t\t\t\tcurrentChunk = make([]*FileData, 0, s.size)\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttimer.Reset(s.timeout)\n\t}\n}\n\nfunc NewSpooler(size int, timeout time.Duration) *Spooler ", "output": "{\n\treturn &Spooler{\n\t\tIn: make(chan *FileData, size*spoolOutBuffer),\n\t\tOut: make(chan []*FileData, spoolOutBuffer),\n\t\tsize: size,\n\t\ttimeout: timeout,\n\t}\n}"} {"input": "package gridq\n\ntype byColRow []*WriteResponse\n\nfunc (p byColRow) Len() int { return len(p) }\nfunc (p byColRow) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byColRow) Less(i, j int) bool {\n\tif p[i].Col < p[j].Col {\n\t\treturn true\n\t} else if p[i].Col > p[j].Col {\n\t\treturn false\n\t} else {\n\t\treturn p[i].Row < p[j].Row\n\t}\n}\n\ntype byRowTimestamp []*ReadResponse\n\nfunc (p byRowTimestamp) Len() int { return len(p) }\n\nfunc (p byRowTimestamp) Less(i, j int) bool {\n\tif p[i].Row < p[j].Row {\n\t\treturn true\n\t} else if p[i].Row > p[j].Row {\n\t\treturn false\n\t} else {\n\t\treturn p[i].State.Timestamp > p[j].State.Timestamp\n\t}\n}\n\ntype byTimestamp []*ReadResponse\n\nfunc (p byTimestamp) Len() int { return len(p) }\nfunc (p byTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byTimestamp) Less(i, j int) bool { return p[i].State.Timestamp < p[j].State.Timestamp }\n\nfunc (p byRowTimestamp) Swap(i, j int) ", "output": "{ p[i], p[j] = p[j], p[i] }"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\n\t\"github.com/codeskyblue/go-sh\"\n)\n\nfunc StartCmd(name string, args ...string) *exec.Cmd {\n\tc := exec.Command(name, args...)\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stdout\n\tc.Stdin = os.Stdin\n\n\treturn c\n}\n\n\n\nfunc KillCmd(cmd *exec.Cmd, signal string) (err error) ", "output": "{\n\tvar pid, pgid int\n\tif cmd.Process != nil {\n\t\tpid = cmd.Process.Pid\n\t\tsess := sh.NewSession()\n\t\tif *verbose {\n\t\t\tsess.ShowCMD = true\n\t\t}\n\t\tc := sess.Command(\"/bin/ps\", \"-o\", \"pgid\", \"-p\", strconv.Itoa(pid)).Command(\"sed\", \"-n\", \"2,$p\")\n\t\tvar out []byte\n\t\tout, err = c.Output()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t_, err = fmt.Sscanf(string(out), \"%d\", &pgid)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\treturn sess.Command(\"/bin/ps\", \"-eo\", \"pid,pgid\").Command(\"awk\", fmt.Sprintf(`$2==%d {system(\"/bin/kill -%s \"$1)}`, pgid, signal)).Run()\n\t}\n\treturn\n}"} {"input": "package record\n\nimport (\n\t\"sync\"\n\n\t\"github.com/gollector/gollector/logger\"\n)\n\nvar recorded_metrics map[string]interface{}\n\nvar rwmutex sync.RWMutex\n\n\n\nfunc RecordMetric(name string, value interface{}, log *logger.Logger) {\n\trwmutex.Lock()\n\tif recorded_metrics == nil {\n\t\trecorded_metrics = make(map[string]interface{})\n\t}\n\trecorded_metrics[name] = value\n\trwmutex.Unlock()\n}\n\nfunc GetMetric(params interface{}, log *logger.Logger) interface{} ", "output": "{\n\tendpoint := params.(string)\n\n\trwmutex.RLock()\n\tresult := recorded_metrics[endpoint]\n\trwmutex.RUnlock()\n\n\treturn result\n}"} {"input": "package main\n\ntype Human struct {\n\tname string\n\tage int\n\tphone string\n}\n\ntype Student struct {\n\tHuman\n\tschool string\n\tloan float32\n}\n\ntype Employee struct {\n\tHuman\n\tcompany string\n\tmoney float32\n}\n\n\ntype Men interface {\n\tSayHi()\n\tSing(lyrics string)\n\tGuzzle(beerStein string)\n}\n\ntype YoungChap interface {\n\tSayHi()\n\tSing(lyrics string)\n\tBorrowMoney(amount float32)\n}\n\ntype ElderlyGent interface {\n\tSayHi()\n\tSing(song string)\n\tSpendSalary(amount float32)\n}\n\n\n\nfunc (h *Human) Sing(lyrics string) {\n\tfmt.Println(\"La la, la la la, la la la la...\", lyrics)\n}\n\nfunc (h *Human) Guzzle(beerStein string) {\n\tfmt.Println(\"Guzzle Guzzle Guzzle...\", beerStein)\n}\n\n\nfunc (e *Employee) SayHi() {\n\tfmt.Printf(\"Hi, I am %s, I work at %s. Call me on %s\\n\", e.name, e.company, e.phone)\n}\n\nfunc (s *Student) BorrowMoney(amount float32) {\n\ts.loan += amount\n}\n\nfunc (e *Employee) SpendSalary(amount float32) {\n\te.money -= e.amount\n}\n\nfunc (h *Human) SayHi() ", "output": "{\n\tfmt.Printf(\"Hi, I am %s you can call me on %s\\n\", h.name, h.phone)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc middlewareFirst(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"MiddlewareFirst - Before Handler\")\n\t\tnext.ServeHTTP(w, r)\n\t\tlog.Println(\"MiddlewareFirst- After Handler\")\n\t})\n}\n\nfunc middlewareSecond(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"MiddlewareSecond - Before Handler\")\n\t\tif r.URL.Path == \"/message\" {\n\t\t\tif r.URL.Query().Get(\"password\") == \"pass123\" {\n\t\t\t\tlog.Println(\"Authorized to the system\")\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t} else {\n\t\t\t\tlog.Println(\"Failed to authorize to the system\")\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t}\n\t\tlog.Println(\"MiddlewareSecond - After Handler\")\n\t})\n}\n\nfunc index(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Executing index handler\")\n\tfmt.Fprintf(w, \"Welcome!\")\n}\n\n\n\nfunc iconHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.ServeFile(w, r, \"./favicon.ico\")\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/favicon.ico\", iconHandler)\n\n\thttp.Handle(\"/\", middlewareFirst(middlewareSecond(http.HandlerFunc(index))))\n\thttp.Handle(\"/message\", middlewareFirst(middlewareSecond(http.HandlerFunc(message))))\n\n\tserver := &http.Server{\n\t\tAddr: \":8080\",\n\t}\n\tlog.Println(\"Listening...\")\n\tserver.ListenAndServe()\n}\n\nfunc message(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tlog.Println(\"Excuting message Handler\")\n\tfmt.Fprintf(w, \"HTTP Middleware is awesome\")\n}"} {"input": "package yaml\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"lib/oht/core/locales\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\n\n\n\n\ntype Backend struct {\n\tfiles []string\n}\n\nfunc loadTranslationsFromYaml(locale string, value interface{}, scopes []string) (translations []*i18n.Translation) {\n\tswitch v := value.(type) {\n\tcase yaml.MapSlice:\n\t\tfor _, s := range v {\n\t\t\tresults := loadTranslationsFromYaml(locale, s.Value, append(scopes, fmt.Sprintf(\"%v\", s.Key)))\n\t\t\ttranslations = append(translations, results...)\n\t\t}\n\tdefault:\n\t\tvar translation = &i18n.Translation{\n\t\t\tLocale: locale,\n\t\t\tKey: strings.Join(scopes, \".\"),\n\t\t\tValue: fmt.Sprintf(\"%v\", v),\n\t\t}\n\t\ttranslations = append(translations, translation)\n\t}\n\treturn\n}\n\n\nfunc (backend *Backend) LoadTranslations() (translations []*i18n.Translation) {\n\tfor _, file := range backend.files {\n\t\tif content, err := ioutil.ReadFile(file); err == nil {\n\t\t\tvar slice yaml.MapSlice\n\t\t\tif err := yaml.Unmarshal(content, &slice); err == nil {\n\t\t\t\tfor _, item := range slice {\n\t\t\t\t\ttranslations = append(translations, loadTranslationsFromYaml(item.Key.(string) , item.Value, []string{})...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn translations\n}\n\n\nfunc (backend *Backend) SaveTranslation(t *i18n.Translation) error {\n\treturn errors.New(\"not implemented\")\n}\n\n\nfunc (backend *Backend) DeleteTranslation(t *i18n.Translation) error {\n\treturn errors.New(\"not implemented\")\n}\n\nfunc New(paths ...string) i18n.Backend ", "output": "{\n\tbackend := &Backend{}\n\tfor _, p := range paths {\n\t\tif file, err := os.Open(p); err == nil {\n\t\t\tdefer file.Close()\n\t\t\tif fileInfo, err := file.Stat(); err == nil {\n\t\t\t\tif fileInfo.IsDir() {\n\t\t\t\t\tyamlFiles, _ := filepath.Glob(path.Join(p, \"*.yaml\"))\n\t\t\t\t\tbackend.files = append(backend.files, yamlFiles...)\n\t\t\t\t\tymlFiles, _ := filepath.Glob(path.Join(p, \"*.yml\"))\n\t\t\t\t\tbackend.files = append(backend.files, ymlFiles...)\n\t\t\t\t} else if fileInfo.Mode().IsRegular() {\n\t\t\t\t\tbackend.files = append(backend.files, p)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn backend\n}"} {"input": "package depsync\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n)\n\nfunc (s *DEPSyncService) SyncNow(_ context.Context) error {\n\ts.syncer.SyncNow()\n\treturn nil\n}\n\ntype syncNowResponse struct{}\ntype syncNowRequest struct{}\n\nfunc MakeSyncNowEndpoint(s Service) endpoint.Endpoint {\n\treturn func(ctx context.Context, _ interface{}) (interface{}, error) {\n\t\ts.SyncNow(ctx)\n\t\treturn syncNowResponse{}, nil\n\t}\n}\n\nfunc decodeEmptyRequest(ctx context.Context, r *http.Request) (interface{}, error) {\n\treturn nil, nil\n}\n\nfunc encodeEmptyResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {\n\treturn nil\n}\n\nfunc decodeEmptyResponse(ctx context.Context, r *http.Response) (interface{}, error) {\n\treturn nil, nil\n}\n\n\n\nfunc (e Endpoints) SyncNow(ctx context.Context) error ", "output": "{\n\t_, err := e.SyncNowEndpoint(ctx, nil)\n\treturn err\n}"} {"input": "package proxy\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/AaronO/gogo-proxy\"\n)\n\n\n\nfunc TestRandomEmpty(t *testing.T) {\n\tbalancer := proxy.Random()\n\n\tif _, err := balancer(nil); err == nil {\n\t\tt.Fatalf(\"Random should fail when given no hosts\")\n\t}\n}\n\nfunc TestRoundrobin(t *testing.T) {\n\tbalancer := proxy.Roundrobin(\"1\", \"2\", \"3\")\n\n\thosts := []string{}\n\n\tfor i := 0; i < 7; i++ {\n\t\thost, err := balancer(nil)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\thosts = append(hosts, host)\n\t}\n\n\tequal := reflect.DeepEqual(\n\t\thosts,\n\t\t[]string{\"1\", \"2\", \"3\", \"1\", \"2\", \"3\", \"1\"},\n\t)\n\n\tif !equal {\n\t\tt.Fatalf(\"Roundrobin did not generate expected hosts\")\n\t}\n}\n\nfunc TestRoundrobinEmpty(t *testing.T) ", "output": "{\n\tbalancer := proxy.Roundrobin()\n\n\tif _, err := balancer(nil); err == nil {\n\t\tt.Fatalf(\"Roundrobin should fail when given no hosts\")\n\t}\n}"} {"input": "package render\n\n\ntype Data map[string]interface{}\n\n\nfunc NewData() *Data {\n\treturn &Data{}\n}\n\n\nfunc (d *Data) Set(key string, data interface{}) {\n\tif *d == nil {\n\t\tdata := Data(map[string]interface{}{})\n\t\t*d = data\n\t}\n\t(*d)[key] = data\n}\n\n\nfunc (d *Data) Del(key string) {\n\tif *d == nil {\n\t\treturn\n\t}\n\tdelete(*d, key)\n}\n\n\nfunc (d *Data) Get(key string) interface{} {\n\tif *d == nil {\n\t\treturn nil\n\t}\n\tdata, ok := (*d)[key]\n\tif ok == false {\n\t\treturn nil\n\t}\n\treturn data\n}\n\n\n\n\nfunc (d *Data) Merge(data *Data) ", "output": "{\n\tif *d == nil {\n\t\tdata := Data(map[string]interface{}{})\n\t\t*d = data\n\t}\n\tif data == nil || *data == nil {\n\t\treturn\n\t}\n\tfor k, v := range *data {\n\t\td.Set(k, v)\n\t}\n}"} {"input": "package main\n\ntype instanceGroupManagers struct {\n\tbasicGCPResource\n}\n\nfunc (b instanceGroupManagers) ifNeedZone(zoneInParameters bool) bool {\n\treturn true\n}\n\n\nfunc (b instanceGroupManagers) ifNeedRegion() bool {\n\treturn false\n}\n\nfunc (b instanceGroupManagers) ifIDWithZone(zoneInParameters bool) bool ", "output": "{\n\treturn false\n}"} {"input": "package location\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype (\n\tlocation struct {\n\t\tscheme string\n\t\thost string\n\t\tbase string\n\t\theaders Headers\n\t}\n)\n\nfunc newLocation(config Config) *location {\n\treturn &location{\n\t\tscheme: config.Scheme,\n\t\thost: config.Host,\n\t\tbase: config.Base,\n\t\theaders: config.Headers,\n\t}\n}\n\nfunc (l *location) applyToContext(c *gin.Context) {\n\tvalue := new(url.URL)\n\tvalue.Scheme = l.resolveScheme(c.Request)\n\tvalue.Host = l.resolveHost(c.Request)\n\tvalue.Path = l.base\n\tc.Set(key, value)\n}\n\n\n\nfunc (l *location) resolveHost(r *http.Request) (host string) {\n\tswitch {\n\tcase r.Header.Get(l.headers.Host) != \"\":\n\t\treturn r.Header.Get(l.headers.Host)\n\tcase r.Header.Get(\"X-Host\") != \"\":\n\t\treturn r.Header.Get(\"X-Host\")\n\tcase r.Host != \"\":\n\t\treturn r.Host\n\tcase r.URL.Host != \"\":\n\t\treturn r.URL.Host\n\tdefault:\n\t\treturn l.host\n\t}\n}\n\nfunc (l *location) resolveScheme(r *http.Request) string ", "output": "{\n\tswitch {\n\tcase r.Header.Get(l.headers.Scheme) == \"https\":\n\t\treturn \"https\"\n\tcase r.URL.Scheme == \"https\":\n\t\treturn \"https\"\n\tcase r.TLS != nil:\n\t\treturn \"https\"\n\tcase strings.HasPrefix(r.Proto, \"HTTPS\"):\n\t\treturn \"https\"\n\tdefault:\n\t\treturn l.scheme\n\t}\n}"} {"input": "package net\n\nimport \"net\"\nimport \"golang.org/x/net/context\"\n\n\ntype Dialer interface {\n\tDial(net, addr string, ctx context.Context) (net.Conn, error)\n}\n\n\ntype DialerFunc func(net, addr string, ctx context.Context) (net.Conn, error)\n\nfunc (df DialerFunc) Dial(net, addr string, ctx context.Context) (net.Conn, error) {\n\treturn df(net, addr, ctx)\n}\n\n\ntype netDialer struct{}\n\n\n\n\nvar NetDialer netDialer\n\n\nvar DefaultDialer = NetDialer\n\nfunc (netDialer) Dial(n, addr string, ctx context.Context) (net.Conn, error) ", "output": "{\n\tdeadline, _ := ctx.Deadline()\n\n\td := net.Dialer{\n\t\tDeadline: deadline,\n\t}\n\treturn d.Dial(n, addr)\n}"} {"input": "package collaboration\n\nimport \"sync\"\n\nfunc NewMemoryStorage() *memoryStorage {\n\treturn &memoryStorage{\n\t\tusers: make(map[string]*Option),\n\t}\n}\n\n\ntype memoryStorage struct {\n\tusers map[string]*Option\n\tsync.Mutex\n}\n\n\n\nfunc (m *memoryStorage) GetAll() (map[string]*Option, error) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\treturn m.users, nil\n}\n\nfunc (m *memoryStorage) Set(username string, value *Option) error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tm.users[username] = value\n\treturn nil\n}\n\nfunc (m *memoryStorage) Delete(username string) error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tdelete(m.users, username)\n\treturn nil\n}\n\nfunc (m *memoryStorage) Close() error {\n\treturn nil\n}\n\nfunc (m *memoryStorage) Get(username string) (*Option, error) ", "output": "{\n\tm.Lock()\n\tdefer m.Unlock()\n\n\toption, ok := m.users[username]\n\tif !ok {\n\t\treturn nil, ErrUserNotFound\n\t}\n\n\treturn option, nil\n}"} {"input": "package message\n\nimport \"github.com/cloustone/sentel/pkg/config\"\n\ntype Producer interface {\n\tSendMessage(msg Message) error\n\tSendMessages(msgs []Message) error\n\tClose()\n}\n\nfunc NewProducer(c config.Config, clientID string, sync bool) (Producer, error) {\n\treturn newKafkaProducer(c, clientID, sync)\n}\n\n\n\nfunc PostMessages(c config.Config, msgs []Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", false); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessages(msgs)\n\t}\n\treturn\n}\n\nfunc SendMessage(c config.Config, msg Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", true); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessage(msg)\n\t}\n\treturn\n}\n\nfunc SendMessages(c config.Config, msgs []Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", true); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessages(msgs)\n\t}\n\treturn\n}\n\nfunc PostMessage(c config.Config, msg Message) (err error) ", "output": "{\n\tif producer, err := NewProducer(c, \"\", false); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessage(msg)\n\t}\n\treturn\n}"} {"input": "package parlib\n\nimport (\n\t\"errors\"\n)\n\n\nfunc Cstrlen(str []byte) int {\n var i int = 0\n for (str[i] != 0) { i++ }\n return i\n}\n\n\n\n\nfunc StringByteSlice(s string) []byte {\n\ta, err := ByteSliceFromString(s)\n\tif err != nil {\n\t\tpanic(\"syscall: string with NUL passed to StringByteSlice\")\n\t}\n\treturn a\n}\n\n\n\n\nfunc ByteSliceFromString(s string) ([]byte, error) {\n\tfor i := 0; i < len(s); i++ {\n\t\tif s[i] == 0 {\n\t\t\treturn nil, errors.New(\"String contains a NULL byte.\")\n\t\t}\n\t}\n\ta := make([]byte, len(s)+1)\n\tcopy(a, s)\n\treturn a, nil\n}\n\n\n\n\nfunc StringBytePtr(s string) *byte { return &StringByteSlice(s)[0] }\n\n\n\n\nfunc BytePtrFromString(s string) (*byte, error) {\n\ta, err := ByteSliceFromString(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &a[0], nil\n}\n\n\n\n\n\n\n\n\n\nfunc SlicePtrFromStrings(ss []string) ([]*byte, error) {\n var err error\n bb := make([]*byte, len(ss)+1)\n for i := 0; i < len(ss); i++ {\n bb[i], err = BytePtrFromString(ss[i])\n if err != nil {\n return nil, err\n }\n }\n bb[len(ss)] = nil\n return bb, nil\n}\n\nfunc StringSlicePtr(ss []string) []*byte ", "output": "{\n bb := make([]*byte, len(ss)+1)\n for i := 0; i < len(ss); i++ {\n bb[i] = StringBytePtr(ss[i])\n }\n bb[len(ss)] = nil\n return bb\n}"} {"input": "package stats\n\nimport (\n\t\"time\"\n\n\t\"sync\"\n\n\t\"github.com/paulbellamy/ratecounter\"\n)\n\nvar lock = sync.RWMutex{}\n\ntype stat struct {\n\treadReq *ratecounter.RateCounter\n\twriteReq *ratecounter.RateCounter\n}\n\nfunc newStat() stat {\n\treturn stat{\n\t\treadReq: ratecounter.NewRateCounter(time.Hour),\n\t\twriteReq: ratecounter.NewRateCounter(time.Hour),\n\t}\n}\n\ntype namespaceStatMap map[string]stat\n\nvar golbalNamespaceStat namespaceStatMap\n\nfunc init() {\n\tgolbalNamespaceStat = namespaceStatMap{}\n}\n\n\nfunc AddNamespace(label string) {\n\t_, ok := golbalNamespaceStat[label]\n\tif ok {\n\t\treturn\n\t}\n\n\tgolbalNamespaceStat[label] = newStat()\n\treturn\n}\n\n\nfunc IncrRead(label string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tstat, ok := golbalNamespaceStat[label]\n\tif !ok {\n\t\tAddNamespace(label)\n\t\tstat = golbalNamespaceStat[label]\n\t}\n\n\tstat.readReq.Incr(1)\n}\n\n\nfunc IncrWrite(label string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tstat, ok := golbalNamespaceStat[label]\n\tif !ok {\n\t\tAddNamespace(label)\n\t\tstat = golbalNamespaceStat[label]\n\t}\n\n\tstat.writeReq.Incr(1)\n}\n\n\n\n\nfunc Rate(label string) (read, write int64) ", "output": "{\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\tstat, ok := golbalNamespaceStat[label]\n\tif !ok {\n\t\tAddNamespace(label)\n\t\tstat = golbalNamespaceStat[label]\n\t}\n\n\treturn stat.readReq.Rate(), stat.writeReq.Rate()\n}"} {"input": "package schema\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc DataSourceResourceShim(name string, dataSource *Resource) *Resource {\n\tdataSourceResourceShimAdjustSchema(dataSource.Schema)\n\n\tdataSource.Create = CreateFunc(dataSource.Read)\n\tdataSource.Delete = func(d *ResourceData, meta interface{}) error {\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\tdataSource.Update = nil \n\n\tdataSource.DeprecationMessage = fmt.Sprintf(\n\t\t\"using %s as a resource is deprecated; consider using the data source instead\",\n\t\tname,\n\t)\n\n\treturn dataSource\n}\n\n\n\nfunc dataSourceResourceShimAdjustSchema(schema map[string]*Schema) ", "output": "{\n\tfor _, s := range schema {\n\t\tif s.Required || s.Optional {\n\t\t\ts.ForceNew = true\n\t\t}\n\n\t\tif s.Elem != nil {\n\t\t\tif r, ok := s.Elem.(*Resource); ok {\n\t\t\t\tdataSourceResourceShimAdjustSchema(r.Schema)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package model\n\n\ntype Sample struct {\n\tMetric Metric\n\tValue SampleValue\n\tTimestamp Timestamp\n}\n\n\nfunc (s *Sample) Equal(o *Sample) bool {\n\tif s == o {\n\t\treturn true\n\t}\n\n\tif !s.Metric.Equal(o.Metric) {\n\t\treturn false\n\t}\n\tif !s.Timestamp.Equal(o.Timestamp) {\n\t\treturn false\n\t}\n\tif !s.Value.Equal(o.Value) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\ntype Samples []*Sample\n\n\n\n\nfunc (s Samples) Less(i, j int) bool {\n\tswitch {\n\tcase s[i].Metric.Before(s[j].Metric):\n\t\treturn true\n\tcase s[j].Metric.Before(s[i].Metric):\n\t\treturn false\n\tcase s[i].Timestamp.Before(s[j].Timestamp):\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc (s Samples) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\n\nfunc (s Samples) Equal(o Samples) bool {\n\tif len(s) != len(o) {\n\t\treturn false\n\t}\n\n\tfor i, sample := range s {\n\t\tif !sample.Equal(o[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (s Samples) Len() int ", "output": "{\n\treturn len(s)\n}"} {"input": "package goparsify\n\nimport (\n\t\"strconv\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\n\ntype State struct {\n\tInput string\n\tPos int\n\tCut int\n\tError Error\n\tWS VoidParser\n}\n\n\n\nfunc ASCIIWhitespace(s *State) {\n\tfor s.Pos < len(s.Input) {\n\t\tswitch s.Input[s.Pos] {\n\t\tcase '\\t', '\\n', '\\v', '\\f', '\\r', ' ':\n\t\t\ts.Pos++\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\nfunc UnicodeWhitespace(s *State) {\n\tfor s.Pos < len(s.Input) {\n\t\tr, w := utf8.DecodeRuneInString(s.Get())\n\t\tif !unicode.IsSpace(r) {\n\t\t\treturn\n\t\t}\n\t\ts.Pos += w\n\t}\n}\n\n\nfunc NoWhitespace(s *State) {\n\n}\n\n\nfunc NewState(input string) *State {\n\treturn &State{\n\t\tInput: input,\n\t\tWS: UnicodeWhitespace,\n\t}\n}\n\n\nfunc (s *State) Advance(i int) {\n\ts.Pos += i\n}\n\n\n\n\n\nfunc (s *State) Preview(x int) string {\n\tif s.Pos >= len(s.Input) {\n\t\treturn \"\"\n\t}\n\n\tquoted := strconv.Quote(s.Get())\n\tquoted = quoted[1 : len(quoted)-1]\n\tif len(quoted) >= x {\n\t\treturn quoted[0:x]\n\t}\n\n\treturn quoted\n}\n\n\nfunc (s *State) ErrorHere(expected string) {\n\ts.Error.pos = s.Pos\n\ts.Error.expected = expected\n}\n\n\n\nfunc (s *State) Recover() {\n\ts.Error.expected = \"\"\n}\n\n\nfunc (s *State) Errored() bool {\n\treturn s.Error.expected != \"\"\n}\n\nfunc (s *State) Get() string ", "output": "{\n\tif s.Pos > len(s.Input) {\n\t\treturn \"\"\n\t}\n\treturn s.Input[s.Pos:]\n}"} {"input": "package reflect\n\nimport (\n\t\"unsafe\"\n)\n\n\n\ntype makeFuncImpl struct {\n\tcode uintptr\n\tstack *bitVector \n\ttyp *funcType\n\tfn func([]Value) []Value\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc makeFuncStub()\n\ntype methodValue struct {\n\tfn uintptr\n\tstack *bitVector \n\tmethod int\n\trcvr Value\n}\n\n\n\n\n\n\n\n\nfunc makeMethodValue(op string, v Value) Value {\n\tif v.flag&flagMethod == 0 {\n\t\tpanic(\"reflect: internal error: invalid use of makeMethodValue\")\n\t}\n\n\tfl := v.flag & (flagRO | flagAddr | flagIndir)\n\tfl |= flag(v.typ.Kind())\n\trcvr := Value{v.typ, v.ptr, fl}\n\n\tfuncType := v.Type().(*rtype)\n\n\tdummy := methodValueCall\n\tcode := **(**uintptr)(unsafe.Pointer(&dummy))\n\n\t_, _, _, stack, _ := funcLayout(funcType, nil)\n\n\tfv := &methodValue{\n\t\tfn: code,\n\t\tstack: stack,\n\t\tmethod: int(v.flag) >> flagMethodShift,\n\t\trcvr: rcvr,\n\t}\n\n\tmethodReceiver(op, fv.rcvr, fv.method)\n\n\treturn Value{funcType, unsafe.Pointer(fv), v.flag&flagRO | flag(Func)}\n}\n\n\n\n\n\n\nfunc methodValueCall()\n\nfunc MakeFunc(typ Type, fn func(args []Value) (results []Value)) Value ", "output": "{\n\tif typ.Kind() != Func {\n\t\tpanic(\"reflect: call of MakeFunc with non-Func type\")\n\t}\n\n\tt := typ.common()\n\tftyp := (*funcType)(unsafe.Pointer(t))\n\n\tdummy := makeFuncStub\n\tcode := **(**uintptr)(unsafe.Pointer(&dummy))\n\n\t_, _, _, stack, _ := funcLayout(t, nil)\n\n\timpl := &makeFuncImpl{code: code, stack: stack, typ: ftyp, fn: fn}\n\n\treturn Value{t, unsafe.Pointer(impl), flag(Func)}\n}"} {"input": "package uber\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\tistioconfig \"istio.io/api/istio/config/v1\"\n\n\t\"istio.io/mixer/pkg/aspectsupport\"\n\t\"istio.io/mixer/pkg/attribute\"\n\t\"istio.io/mixer/pkg/expr\"\n)\n\ntype (\n\tfakereg struct {\n\t\tRegistryQuerier\n\t}\n\n\tfakemgr struct {\n\t\tkind string\n\t\taspectsupport.Manager\n\t}\n\n\tfakebag struct {\n\t\tattribute.Bag\n\t}\n\n\tfakeevaluator struct {\n\t\texpr.Evaluator\n\t}\n)\n\nfunc (m *fakemgr) Kind() string {\n\treturn m.kind\n}\n\n\n\nfunc TestManager(t *testing.T) ", "output": "{\n\tr := &fakereg{}\n\tmgrs := []aspectsupport.Manager{&fakemgr{kind: \"k1\"}, &fakemgr{kind: \"k2\"}}\n\tm := NewManager(r, mgrs)\n\tcfg := &aspectsupport.CombinedConfig{\n\t\tAspect: &istioconfig.Aspect{},\n\t\tAdapter: &istioconfig.Adapter{},\n\t}\n\tattrs := &fakebag{}\n\tmapper := &fakeevaluator{}\n\tif _, err := m.Execute(cfg, attrs, mapper); err != nil {\n\t\tif !strings.Contains(err.Error(), \"could not find aspect manager\") {\n\t\t\tt.Error(\"excute errored out: \", err)\n\t\t}\n\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"net\"\n\t\"log\"\n\t\"unicode/utf16\"\n\t\"fmt\"\n)\n\nconst BOM = '\\ufffe'\n\n\n\nfunc readShorts(conn net.Conn) []uint16 {\n\tvar buf [512] byte\n\n\tn, err := conn.Read(buf[0:2])\n\n\tfor true {\n\t\tm, err := conn.Read(buf[n:])\n\t\tif m == 0 || err != nil {\n\t\t\tbreak\n\t\t}\n\t\tn += m\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar shorts []uint16\n\n\tshorts = make([]uint16, n/2)\n\n\tif buf[0] == 0xff && buf[1] == 0xfe {\n\t\tfor i := 2; i < n; i += 2 {\n\t\t\tshorts[i/2] = uint16(buf[i])<<8 + uint16(buf[i+1])\n\t\t}\n\t} else if buf[1] == 0xfe && buf[0] == 0xff {\n\t\tfor i := 2; i < n; i += 2 {\n\t\t\tshorts[i/2] = uint16(buf[i+1])<<8 + uint16(buf[i])\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Unknown order\")\n\t}\n\n\treturn shorts\n\n}\n\nfunc Utf16Client(server string) ", "output": "{\n\n\tconn, err := net.Dial(\"tcp\", server)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tshorts := readShorts(conn)\n\tints := utf16.Decode(shorts)\n\tstr := string(ints)\n\n\tfmt.Println(str)\n\n}"} {"input": "package flydb\n\nimport (\n \"fmt\"\n)\n\nfunc NewArrayNode(v []interface{}) (*ArrayNode, error) {\n node := &ArrayNode {\n }\n\n if err := node.SetRaw(v); err != nil {\n return nil, err\n }\n\n return node, nil\n}\n\n\ntype ArrayNode struct {\n data []*Node\n}\n\n\n\nfunc (this *ArrayNode) GetRaw() interface{} {\n result := make([]interface{}, len(this.data))\n for i, v := range this.data {\n result[i] = v.GetRaw()\n }\n\n return result\n}\n\nfunc (this *ArrayNode) Append(data interface{}) error {\n node, err := CreateNode(data)\n if err != nil {\n return err\n }\n\n this.data = append(this.data, node)\n return nil\n}\n\nfunc (this *ArrayNode) Get(i int) (*Node, error) {\n if i < 0 || i >= len(this.data) {\n return nil, fmt.Errorf(\"key out of range: %d\", i)\n }\n\n return this.data[i], nil\n}\n\nfunc (this *ArrayNode) Set(i int, data interface{}) error {\n if i < 0 || i >= len(this.data) {\n return fmt.Errorf(\"key out of range: %d\", i)\n }\n\n node, err := CreateNode(data)\n if err != nil {\n return err\n }\n\n this.data[i] = node\n return nil\n}\n\nfunc (this *ArrayNode) Delete(key int) {\n if key < 0 || key >= len(this.data) {\n return\n }\n\n this.data = append(this.data[0:key], this.data[key+1:]...)\n}\n\nfunc (this *ArrayNode) Length() int {\n return len(this.data)\n}\n\nfunc (this *ArrayNode) SetRaw(raw interface{}) (error) ", "output": "{\n rawArray, ok := raw.([]interface{})\n if !ok {\n return fmt.Errorf(\"raw data is not an array\")\n }\n data := make([]*Node, len(rawArray))\n for k, v := range rawArray {\n node, err := CreateNode(v)\n if err != nil {\n return err\n }\n\n data[k] = node\n }\n\n this.data = data\n return nil\n}"} {"input": "package graph\n\ntype vertexDistance struct {\n\tvertex string\n\tdistance float64\n}\n\n\n\n\ntype vertexDistanceHeap []vertexDistance\n\nfunc (h vertexDistanceHeap) Len() int { return len(h) }\nfunc (h vertexDistanceHeap) Less(i, j int) bool { return h[i].distance < h[j].distance } \nfunc (h vertexDistanceHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }\n\nfunc (h *vertexDistanceHeap) Push(x interface{}) {\n\t*h = append(*h, x.(vertexDistance))\n}\n\nfunc (h *vertexDistanceHeap) Pop() interface{} {\n\theapSize := len(*h)\n\tlastVertex := (*h)[heapSize-1]\n\t*h = (*h)[0 : heapSize-1]\n\treturn lastVertex\n}\n\n\n\nfunc (h *vertexDistanceHeap) updateDistance(vtx string, val float64) ", "output": "{\n\tfor i := 0; i < len(*h); i++ {\n\t\tif (*h)[i].vertex == vtx {\n\t\t\t(*h)[i].distance = val\n\t\t\tbreak\n\t\t}\n\t}\n}"} {"input": "package mockhttputil\n\nimport (\n\tgomock \"github.com/golang/mock/gomock\"\n\thttp \"net/http\"\n\treflect \"reflect\"\n)\n\n\ntype MockRoundTripper struct {\n\tctrl *gomock.Controller\n\trecorder *MockRoundTripperMockRecorder\n}\n\n\ntype MockRoundTripperMockRecorder struct {\n\tmock *MockRoundTripper\n}\n\n\nfunc NewMockRoundTripper(ctrl *gomock.Controller) *MockRoundTripper {\n\tmock := &MockRoundTripper{ctrl: ctrl}\n\tmock.recorder = &MockRoundTripperMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockRoundTripper) EXPECT() *MockRoundTripperMockRecorder {\n\treturn m.recorder\n}\n\n\nfunc (m *MockRoundTripper) RoundTrip(arg0 *http.Request) (*http.Response, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RoundTrip\", arg0)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}\n\n\n\n\nfunc (mr *MockRoundTripperMockRecorder) RoundTrip(arg0 interface{}) *gomock.Call ", "output": "{\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"RoundTrip\", reflect.TypeOf((*MockRoundTripper)(nil).RoundTrip), arg0)\n}"} {"input": "package libcontainer\n\nimport (\n \"fmt\"\n \"os\"\n \"strings\"\n\n \"github.com/syndtr/gocapability/capability\"\n)\n\nconst allCapabilityTypes = capability.CAPS | capability.BOUNDS\n\nvar capabilityMap map[string]capability.Cap\n\nfunc init() {\n capabilityMap = make(map[string]capability.Cap)\n last := capability.CAP_LAST_CAP\n \n if last == capability.Cap(63) {\n last = capability.CAP_BLOCK_SUSPEND\n }\n for _, cap := range capability.List() {\n if cap > last {\n continue\n }\n capKey := fmt.Sprintf(\"CAP_%s\", strings.ToUpper(cap.String()))\n capabilityMap[capKey] = cap\n }\n}\n\nfunc newCapWhitelist(caps []string) (*whitelist, error) {\n l := []capability.Cap{}\n for _, c := range caps {\n v, ok := capabilityMap[c]\n if !ok {\n return nil, fmt.Errorf(\"unknown capability %q\", c)\n }\n l = append(l, v)\n }\n pid, err := capability.NewPid(os.Getpid())\n if err != nil {\n return nil, err\n }\n return &whitelist{\n keep: l,\n pid: pid,\n }, nil\n}\n\ntype whitelist struct {\n pid capability.Capabilities\n keep []capability.Cap\n}\n\n\n\n\n\nfunc (w *whitelist) drop() error {\n w.pid.Clear(allCapabilityTypes)\n w.pid.Set(allCapabilityTypes, w.keep...)\n return w.pid.Apply(allCapabilityTypes)\n}\n\nfunc (w *whitelist) dropBoundingSet() error ", "output": "{\n w.pid.Clear(capability.BOUNDS)\n w.pid.Set(capability.BOUNDS, w.keep...)\n return w.pid.Apply(capability.BOUNDS)\n}"} {"input": "package handlers\n\nimport (\n\t\"github.com/dmonay/okra/common\"\n\t\"github.com/gin-gonic/gin\"\n\t\"gopkg.in/mgo.v2/bson\"\n)\n\n\n\nfunc (dw *DoWorkResource) UpdateMission(c *gin.Context) ", "output": "{\n\n\torg := c.Params.ByName(\"organization\")\n\tvar reqBody common.MissionJson\n\n\tc.Bind(&reqBody)\n\n\tmission := reqBody.Mission\n\ttreeId := bson.ObjectIdHex(reqBody.TreeId)\n\n\tcolQuerier := bson.M{\"_id\": treeId}\n\tsetMission := bson.M{\"$set\": bson.M{\"mission\": mission}}\n\terr := dw.mongo.C(org).Update(colQuerier, setMission)\n\tif err != nil {\n\t\tCheckErr(err, \"Mongo failed to update mission\", c)\n\t\treturn\n\t}\n\n\tc.JSON(201, SuccessMsg{mission})\n}"} {"input": "package main\n\ntype Session struct {\n\tseq int32\n\tservers map[int32]int32 \n}\n\n\nfunc NewSession(server int) *Session {\n\ts := new(Session)\n\ts.servers = make(map[int32]int32, server)\n\ts.seq = 0\n\treturn s\n}\n\nfunc (s *Session) nextSeq() int32 {\n\ts.seq++\n\treturn s.seq\n}\n\n\n\n\nfunc (s *Session) Servers() (seqs []int32, servers []int32) {\n\tvar (\n\t\ti = len(s.servers)\n\t\tseq, server int32\n\t)\n\tseqs = make([]int32, i)\n\tservers = make([]int32, i)\n\tfor seq, server = range s.servers {\n\t\ti--\n\t\tseqs[i] = seq\n\t\tservers[i] = server\n\t}\n\treturn\n}\n\n\nfunc (s *Session) Del(seq int32) bool {\n\tdelete(s.servers, seq)\n\treturn (len(s.servers) == 0)\n}\n\nfunc (s *Session) Size() int {\n\treturn len(s.servers)\n}\n\nfunc (s *Session) Put(server int32) (seq int32) ", "output": "{\n\tseq = s.nextSeq()\n\ts.servers[seq] = server\n\treturn\n}"} {"input": "package client\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\nfunc TestVolumeRemove(t *testing.T) {\n\texpectedURL := \"/volumes/volume_id\"\n\n\tclient := &Client{\n\t\ttransport: newMockClient(nil, func(req *http.Request) (*http.Response, error) {\n\t\t\tif !strings.HasPrefix(req.URL.Path, expectedURL) {\n\t\t\t\treturn nil, fmt.Errorf(\"Expected URL '%s', got '%s'\", expectedURL, req.URL)\n\t\t\t}\n\t\t\tif req.Method != \"DELETE\" {\n\t\t\t\treturn nil, fmt.Errorf(\"expected DELETE method, got %s\", req.Method)\n\t\t\t}\n\t\t\treturn &http.Response{\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tBody: ioutil.NopCloser(bytes.NewReader([]byte(\"body\"))),\n\t\t\t}, nil\n\t\t}),\n\t}\n\n\terr := client.VolumeRemove(context.Background(), \"volume_id\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestVolumeRemoveError(t *testing.T) ", "output": "{\n\tclient := &Client{\n\t\ttransport: newMockClient(nil, errorMock(http.StatusInternalServerError, \"Server error\")),\n\t}\n\n\terr := client.VolumeRemove(context.Background(), \"volume_id\")\n\tif err == nil || err.Error() != \"Error response from daemon: Server error\" {\n\t\tt.Fatalf(\"expected a Server Error, got %v\", err)\n\t}\n}"} {"input": "package gtk\n\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (v *FileChooserButton) GetFocusOnClick() bool {\n\treturn gobool(C.gtk_file_chooser_button_get_focus_on_click(v.native()))\n}\n\n\nfunc (v *FileChooserButton) SetFocusOnClick(grabFocus bool) {\n\tC.gtk_file_chooser_button_set_focus_on_click(v.native(), gbool(grabFocus))\n}\n\n\n\n\nfunc (v *Button) GetFocusOnClick() bool {\n\tc := C.gtk_button_get_focus_on_click(v.native())\n\treturn gobool(c)\n}\n\n\nfunc (v *Button) SetFocusOnClick(focusOnClick bool) {\n\tC.gtk_button_set_focus_on_click(v.native(), gbool(focusOnClick))\n}\n\n\n\n\n\n\n\n\n\nfunc (v *Window) ParseGeometry(geometry string) bool {\n\tcstr := C.CString(geometry)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_window_parse_geometry(v.native(), (*C.gchar)(cstr))\n\treturn gobool(c)\n}\n\n\nfunc (v *Window) ResizeToGeometry(width, height int) {\n\tC.gtk_window_resize_to_geometry(v.native(), C.gint(width), C.gint(height))\n}\n\n\nfunc (v *Window) SetDefaultGeometry(width, height int) {\n\tC.gtk_window_set_default_geometry(v.native(), C.gint(width),\n\t\tC.gint(height))\n}\n\nfunc (v *TextIter) BeginsTag(v1 *TextTag) bool ", "output": "{\n\treturn gobool(C.gtk_text_iter_begins_tag(v.native(), v1.native()))\n}"} {"input": "package serial\n\nimport (\n\t\"flag\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"golang.org/x/net/context\"\n)\n\ntype connect struct {\n\t*flags.VirtualMachineFlag\n\n\tdevice string\n\tclient bool\n}\n\n\n\nfunc (cmd *connect) Register(f *flag.FlagSet) {\n\tf.StringVar(&cmd.device, \"device\", \"\", \"serial port device name\")\n\tf.BoolVar(&cmd.client, \"client\", false, \"Use client direction\")\n}\n\nfunc (cmd *connect) Process() error { return nil }\n\nfunc (cmd *connect) Run(f *flag.FlagSet) error {\n\tvm, err := cmd.VirtualMachine()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif vm == nil {\n\t\treturn flag.ErrHelp\n\t}\n\n\tdevices, err := vm.Device(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td, err := devices.FindSerialPort(cmd.device)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn vm.EditDevice(context.TODO(), devices.ConnectSerialPort(d, f.Arg(0), cmd.client))\n}\n\nfunc init() ", "output": "{\n\tcli.Register(\"device.serial.connect\", &connect{})\n}"} {"input": "package testutil\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\ntype Context struct {\n\tName string `yaml:\"name,omitempty\"`\n\tContext struct {\n\t\tNamespace string `yaml:\"namespace,omitempty\"`\n\t} `yaml:\"context,omitempty\"`\n}\n\nfunc Ctx(name string) *Context { return &Context{Name: name} }\nfunc (c *Context) Ns(ns string) *Context { c.Context.Namespace = ns; return c }\n\ntype Kubeconfig map[string]interface{}\n\nfunc KC() *Kubeconfig {\n\treturn &Kubeconfig{\n\t\t\"apiVersion\": \"v1\",\n\t\t\"kind\": \"Config\"}\n}\n\n\nfunc (k *Kubeconfig) WithCurrentCtx(s string) *Kubeconfig { (*k)[\"current-context\"] = s; return k }\nfunc (k *Kubeconfig) WithCtxs(c ...*Context) *Kubeconfig { (*k)[\"contexts\"] = c; return k }\n\nfunc (k *Kubeconfig) ToYAML(t *testing.T) string {\n\tt.Helper()\n\tvar v strings.Builder\n\tif err := yaml.NewEncoder(&v).Encode(*k); err != nil {\n\t\tt.Fatalf(\"failed to encode mock kubeconfig: %v\", err)\n\t}\n\treturn v.String()\n}\n\nfunc (k *Kubeconfig) Set(key string, v interface{}) *Kubeconfig ", "output": "{ (*k)[key] = v; return k }"} {"input": "package daemon\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/docker/docker/api/types/swarm\"\n\t\"gotest.tools/assert\"\n)\n\n\ntype ConfigConstructor func(*swarm.Config)\n\n\n\n\n\nfunc (d *Daemon) ListConfigs(t testing.TB) []swarm.Config {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tconfigs, err := cli.ConfigList(context.Background(), types.ConfigListOptions{})\n\tassert.NilError(t, err)\n\treturn configs\n}\n\n\nfunc (d *Daemon) GetConfig(t testing.TB, id string) *swarm.Config {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tconfig, _, err := cli.ConfigInspectWithRaw(context.Background(), id)\n\tassert.NilError(t, err)\n\treturn &config\n}\n\n\nfunc (d *Daemon) DeleteConfig(t testing.TB, id string) {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\terr := cli.ConfigRemove(context.Background(), id)\n\tassert.NilError(t, err)\n}\n\n\n\nfunc (d *Daemon) UpdateConfig(t testing.TB, id string, f ...ConfigConstructor) {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tconfig := d.GetConfig(t, id)\n\tfor _, fn := range f {\n\t\tfn(config)\n\t}\n\n\terr := cli.ConfigUpdate(context.Background(), config.ID, config.Version, config.Spec)\n\tassert.NilError(t, err)\n}\n\nfunc (d *Daemon) CreateConfig(t testing.TB, configSpec swarm.ConfigSpec) string ", "output": "{\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tscr, err := cli.ConfigCreate(context.Background(), configSpec)\n\tassert.NilError(t, err)\n\treturn scr.ID\n}"} {"input": "package sha256\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"runtime\"\n\n\t\"github.com/klauspost/cpuid/v2\"\n)\n\n\n\nfunc hasArmSha2() bool ", "output": "{\n\tif cpuid.CPU.Has(cpuid.SHA2) {\n\t\treturn true\n\t}\n\tif runtime.GOARCH != \"arm64\" || runtime.GOOS != \"linux\" {\n\t\treturn false\n\t}\n\n\tconst procCPUInfo = \"/proc/cpuinfo\"\n\n\tconst sha256Feature = \"sha2\"\n\n\tcpuInfo, err := ioutil.ReadFile(procCPUInfo)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn bytes.Contains(cpuInfo, []byte(sha256Feature))\n\n}"} {"input": "package cluster\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\nfunc addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}\n\nfunc SetDefaults_InstanceGroup(obj *InstanceGroup) {\n\tif obj.Spec.ProvisionPolicy == \"\" {\n\t\tobj.Spec.ProvisionPolicy = InstanceGroupProvisionDynamicOnly\n\t}\n}\n\nfunc SetDefaults_Instance(obj *Instance) {\n\tif obj.Spec.ReclaimPolicy == \"\" {\n\t\tobj.Spec.ReclaimPolicy = InstanceReclaimDelete\n\t}\n\n\tif obj.Status.Phase == \"\" {\n\t\tobj.Status.Phase = InstancePending\n\t}\n}\n\n\n\nfunc SetDefaults_ReservedInstance(obj *ReservedInstance) {\n\tif obj.Status.Phase == \"\" {\n\t\tobj.Status.Phase = ReservedInstanceAvailable\n\t}\n}\n\nfunc SetDefaults_Network(obj *Network) ", "output": "{\n\tif obj.Status.Phase == \"\" {\n\t\tobj.Status.Phase = NetworkPending\n\t}\n}"} {"input": "package partner\n\nimport (\n\t\"github.com/jrsix/gof/web\"\n\t\"github.com/jrsix/gof/web/mvc\"\n\t\"go2o/src/core/domain/interface/partner\"\n\t\"go2o/src/core/service/dps\"\n\t\"net/url\"\n)\n\n\nfunc redirect(ctx *web.Context) {\n\tr, w := ctx.Request, ctx.Response\n\tw.Write([]byte(\"\"))\n}\n\nvar _ mvc.Filter = new(baseC)\n\ntype baseC struct {\n}\n\nfunc (this *baseC) Requesting(ctx *web.Context) bool {\n\tif b, _ := chkLogin(ctx); !b {\n\t\tredirect(ctx)\n\t\treturn false\n\t}\n\treturn true\n}\nfunc (this *baseC) RequestEnd(ctx *web.Context) {\n}\n\n\nfunc (this *baseC) GetPartnerId(ctx *web.Context) int {\n\tv := ctx.Session().Get(\"partner_id\")\n\tif v == nil {\n\t\tthis.Requesting(ctx)\n\t\treturn -1\n\t}\n\treturn v.(int)\n}\n\nfunc (this *baseC) GetPartner(ctx *web.Context) (*partner.ValuePartner, error) {\n\treturn dps.PartnerService.GetPartner(this.GetPartnerId(ctx))\n}\n\n\nfunc (this *baseC) ErrorOutput(ctx *web.Context, err string) {\n\tctx.Response.Write([]byte(\"{error:\\\"\" + err + \"\\\"}\"))\n}\n\nfunc chkLogin(ctx *web.Context) (b bool, partnerId int) ", "output": "{\n\tv := ctx.Session().Get(\"partner_id\")\n\tif v == nil {\n\t\treturn false, -1\n\t}\n\treturn true, v.(int)\n}"} {"input": "package collector\n\nimport (\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\ntype conntrackCollector struct {\n\tcurrent *prometheus.Desc\n\tlimit *prometheus.Desc\n}\n\n\n\n\n\nfunc NewConntrackCollector() (Collector, error) {\n\treturn &conntrackCollector{\n\t\tcurrent: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(Namespace, \"\", \"nf_conntrack_entries\"),\n\t\t\t\"Number of currently allocated flow entries for connection tracking.\",\n\t\t\tnil, nil,\n\t\t),\n\t\tlimit: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(Namespace, \"\", \"nf_conntrack_entries_limit\"),\n\t\t\t\"Maximum size of connection tracking table.\",\n\t\t\tnil, nil,\n\t\t),\n\t}, nil\n}\n\nfunc (c *conntrackCollector) Update(ch chan<- prometheus.Metric) (err error) {\n\tvalue, err := readUintFromFile(procFilePath(\"sys/net/netfilter/nf_conntrack_count\"))\n\tif err != nil {\n\t\treturn nil\n\t}\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.current, prometheus.GaugeValue, float64(value))\n\n\tvalue, err = readUintFromFile(procFilePath(\"sys/net/netfilter/nf_conntrack_max\"))\n\tif err != nil {\n\t\treturn nil\n\t}\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.limit, prometheus.GaugeValue, float64(value))\n\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tFactories[\"conntrack\"] = NewConntrackCollector\n}"} {"input": "package cloudstorage\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n)\n\ntype MockStorage struct {\n\tPutRequest *http.Request\n\tGetURL *url.URL\n\tOriginallySigned bool\n\tListObjectsResponse *ListObjectsResponse\n}\n\nvar _ Storage = &MockStorage{}\n\nfunc (s *MockStorage) PresignPutObject(name string, accessType AccessType, header http.Header) (*http.Request, error) {\n\treturn s.PutRequest, nil\n}\n\nfunc (s *MockStorage) PresignGetObject(name string) (*url.URL, error) {\n\treturn s.GetURL, nil\n}\n\nfunc (s *MockStorage) PresignHeadObject(name string) (*url.URL, error) {\n\treturn s.GetURL, nil\n}\n\nfunc (s *MockStorage) RewriteGetURL(u *url.URL, name string) (*url.URL, bool, error) {\n\treturn s.GetURL, s.OriginallySigned, nil\n}\n\n\n\nfunc (s *MockStorage) DeleteObject(name string) error {\n\treturn nil\n}\n\nfunc (s *MockStorage) AccessType(header http.Header) AccessType {\n\treturn AccessTypeDefault\n}\n\nfunc (s *MockStorage) StandardToProprietary(header http.Header) http.Header {\n\treturn header\n}\n\nfunc (s *MockStorage) ProprietaryToStandard(header http.Header) http.Header {\n\treturn header\n}\n\nfunc (s *MockStorage) ListObjects(r *ListObjectsRequest) (*ListObjectsResponse, error) ", "output": "{\n\treturn s.ListObjectsResponse, nil\n}"} {"input": "package protolog \n\nimport (\n\t\"os\"\n\n\t\"go.pedge.io/dlog\"\n\t\"go.pedge.io/protolog\"\n)\n\nfunc init() {\n\tdlog.SetLogger(NewLogger(protolog.NewStandardLogger(protolog.NewFileFlusher(os.Stderr))))\n}\n\ntype logger struct {\n\tprotolog.Logger\n}\n\n\nfunc NewLogger(l protolog.Logger) dlog.Logger {\n\treturn &logger{l}\n}\n\nfunc (l *logger) Debug(args ...interface{}) {\n\tl.Debugln(args...)\n}\n\n\n\nfunc (l *logger) Warn(args ...interface{}) {\n\tl.Warnln(args...)\n}\n\nfunc (l *logger) Error(args ...interface{}) {\n\tl.Errorln(args...)\n}\n\nfunc (l *logger) Fatal(args ...interface{}) {\n\tl.Fatalln(args...)\n}\n\nfunc (l *logger) Panic(args ...interface{}) {\n\tl.Panicln(args...)\n}\n\nfunc (l *logger) Print(args ...interface{}) {\n\tl.Println(args...)\n}\n\nfunc (l *logger) Info(args ...interface{}) ", "output": "{\n\tl.Infoln(args...)\n}"} {"input": "package additional\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\nfunc Test_NewArtboard_1(t *testing.T) {\n\tdata, err := ioutil.ReadFile(\"./testdata/artb_1\")\n\trequire.NoError(t, err)\n\tartboard, err := NewArtboard(data)\n\trequire.NoError(t, err)\n\tassert.Equal(t, &Artboard{\n\t\tText: \"iPhone 6\\x00\",\n\t\tType: 1,\n\t\tColor: &ArtboardColor{\n\t\t\tRed: 255,\n\t\t\tGreen: 255,\n\t\t\tBlue: 255,\n\t\t},\n\t\tRect: &ArtboardRect{\n\t\t\tTop: 0,\n\t\t\tLeft: 750,\n\t\t\tBottom: 1334,\n\t\t\tRight: 1500,\n\t\t},\n\t}, artboard)\n}\n\n\n\nfunc Test_NewArtboard_2(t *testing.T) ", "output": "{\n\tdata, err := ioutil.ReadFile(\"./testdata/artb_2\")\n\trequire.NoError(t, err)\n\tartboard, err := NewArtboard(data)\n\trequire.NoError(t, err)\n\tassert.Equal(t, &Artboard{\n\t\tText: \"\\x00\",\n\t\tType: 1,\n\t\tColor: &ArtboardColor{\n\t\t\tRed: 255,\n\t\t\tGreen: 255,\n\t\t\tBlue: 255,\n\t\t},\n\t\tRect: &ArtboardRect{\n\t\t\tTop: 0,\n\t\t\tLeft: 1570,\n\t\t\tBottom: 1068,\n\t\t\tRight: 2627,\n\t\t},\n\t}, artboard)\n}"} {"input": "package controller \n\nimport (\n\t\"net/url\"\n\t\"testing\"\n\n\t\"github.com/docker/infrakit/pkg/spi/stack\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\nfunc fakeLeader(v bool) func() stack.Leadership {\n\treturn func() stack.Leadership { return fakeLeaderT(v) }\n}\n\ntype fakeLeaderT bool\n\nfunc (f fakeLeaderT) IsLeader() (bool, error) {\n\treturn bool(f), nil\n}\n\n\n\nfunc TestSingleton(t *testing.T) {\n\n\tcall1 := make(chan int, 1)\n\tsingleton1 := Singleton(fake(call1), fakeLeader(true))\n\n\t_, err := singleton1.Describe(nil)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, <-call1)\n\n\tcall2 := make(chan int, 1)\n\tsingleton2 := Singleton(fake(call2), fakeLeader(false))\n\n\t_, err = singleton2.Describe(nil)\n\trequire.Error(t, err)\n\trequire.Equal(t, \"not a leader\", err.Error())\n\n\tclose(call1)\n\tclose(call2)\n}\n\nfunc (f fakeLeaderT) LeaderLocation() (*url.URL, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package togglr\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"reflect\"\n)\n\ntype jsonConfigSource struct {\n\tjsonData map[string]interface{}\n}\n\nfunc NewJsonConfigSource(path string) ConfigSource {\n\tfile, _ := ioutil.ReadFile(path)\n\tjsonData := make(map[string]interface{})\n\tjson.Unmarshal(file, &jsonData)\n\treturn jsonConfigSource{jsonData}\n}\n\n\n\nfunc (source jsonConfigSource) GetConfig(name string, tag reflect.StructTag) (interface{}, bool) ", "output": "{\n\tkey := tag.Get(\"json\")\n\tif key == \"\" {\n\t\tkey = name\n\t}\n\tval, ok := source.jsonData[key]\n\n\treturn val, ok\n}"} {"input": "package codebuild_test\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/awserr\"\n\t\"github.com/aws/aws-sdk-go/aws/request\"\n\t\"github.com/aws/aws-sdk-go/awstesting/integration\"\n\t\"github.com/aws/aws-sdk-go/service/codebuild\"\n)\n\nvar _ aws.Config\nvar _ awserr.Error\nvar _ request.Request\n\n\n\nfunc TestInteg_00_ListBuilds(t *testing.T) ", "output": "{\n\tctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancelFn()\n\n\tsess := integration.SessionWithDefaultRegion(\"us-west-2\")\n\tsvc := codebuild.New(sess)\n\tparams := &codebuild.ListBuildsInput{}\n\t_, err := svc.ListBuildsWithContext(ctx, params, func(r *request.Request) {\n\t\tr.Handlers.Validate.RemoveByName(\"core.ValidateParametersHandler\")\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"expect no error, got %v\", err)\n\t}\n}"} {"input": "package main\n\nfunc main() {\n\tpoison()\n\ttest()\n}\n\n\nfunc poison() {\n\tvar large [256]uintptr\n\tfor i := range large {\n\t\tlarge[i] = 1\n\t}\n\tuse(large[:])\n}\n\n\nfunc test() {\n\ta := 2\n\tx := &a\n\tif x != compare(&x) {\n\t\tpanic(\"not possible\")\n\t}\n}\n\n\n\n\n\nfunc grow() {\n\tvar large [1 << 16]uintptr\n\tuse(large[:])\n}\n\n\nfunc use(_ []uintptr) { }\n\nfunc compare(x **int) *int ", "output": "{\n\tvar y *int\n\tif x == &y {\n\t\tpanic(\"not possible\")\n\t}\n\tgrow()\n\tif x == &y {\n\t\tpanic(\"not possible\")\n\t}\n\treturn *x\n}"} {"input": "package v2\n\nimport (\n\t\"os\"\n\n\t\"code.cloudfoundry.org/cli/cf/cmd\"\n\t\"code.cloudfoundry.org/cli/commands\"\n\t\"code.cloudfoundry.org/cli/commands/flags\"\n)\n\ntype DeleteSecurityGroupCommand struct {\n\tRequiredArgs flags.SecurityGroup `positional-args:\"yes\"`\n\tForce bool `short:\"f\" description:\"Force deletion without confirmation\"`\n\tusage interface{} `usage:\"CF_NAME delete-security-group SECURITY_GROUP [-f]\"`\n\trelatedCommands interface{} `related_commands:\"security-groups\"`\n}\n\n\n\nfunc (_ DeleteSecurityGroupCommand) Execute(args []string) error {\n\tcmd.Main(os.Getenv(\"CF_TRACE\"), os.Args)\n\treturn nil\n}\n\nfunc (_ DeleteSecurityGroupCommand) Setup(config commands.Config, ui commands.UI) error ", "output": "{\n\treturn nil\n}"} {"input": "package out\n\nimport \"math\"\n\n\ntype Point struct {\n\tVid int \n\tIpId int \n\tX []float64 \n\tDist float64 \n\tVals map[string][]float64 \n}\n\n\ntype Points []*Point\n\n\nfunc (o Points) Len() int {\n\treturn len(o)\n}\n\n\nfunc (o Points) Swap(i, j int) {\n\to[i], o[j] = o[j], o[i]\n}\n\n\nfunc (o Points) Less(i, j int) bool {\n\treturn o[i].Dist < o[j].Dist\n}\n\n\n\nfunc get_ip_point(ipid int, A []float64) *Point {\n\tip := Ipoints[ipid]\n\tif ip != nil {\n\t\tvar dist float64\n\t\tif A != nil {\n\t\t\tdist = dist_point_point(ip.X, A)\n\t\t}\n\t\treturn &Point{-1, ipid, ip.X, dist, make(map[string][]float64)}\n\t}\n\treturn nil\n}\n\n\nfunc dist_point_point(a, b []float64) float64 {\n\tif len(a) == 2 {\n\t\treturn math.Sqrt((a[0]-b[0])*(a[0]-b[0]) + (a[1]-b[1])*(a[1]-b[1]))\n\t}\n\treturn math.Sqrt((a[0]-b[0])*(a[0]-b[0]) + (a[1]-b[1])*(a[1]-b[1]) + (a[2]-b[2])*(a[2]-b[2]))\n}\n\nfunc get_nod_point(vid int, A []float64) *Point ", "output": "{\n\tnod := Dom.Vid2node[vid]\n\tif nod != nil {\n\t\tvar dist float64\n\t\tif A != nil {\n\t\t\tdist = dist_point_point(nod.Vert.C, A)\n\t\t}\n\t\treturn &Point{vid, -1, nod.Vert.C, dist, make(map[string][]float64)}\n\t}\n\treturn nil\n}"} {"input": "package v1\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/unversioned\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\nconst GroupName = \"\"\n\n\nvar SchemeGroupVersion = unversioned.GroupVersion{Group: GroupName, Version: \"v1\"}\n\n\n\n\nfunc addKnownTypes(scheme *runtime.Scheme) {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t&Project{},\n\t\t&ProjectList{},\n\t\t&ProjectRequest{},\n\t)\n}\n\nfunc (obj *ProjectRequest) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta }\nfunc (obj *Project) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta }\nfunc (obj *ProjectList) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta }\n\nfunc AddToScheme(scheme *runtime.Scheme) ", "output": "{\n\taddKnownTypes(scheme)\n\taddConversionFuncs(scheme)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSEMRCluster_HadoopJarStepConfig struct {\n\n\tArgs []string `json:\"Args,omitempty\"`\n\n\tJar string `json:\"Jar,omitempty\"`\n\n\tMainClass string `json:\"MainClass,omitempty\"`\n\n\tStepProperties []AWSEMRCluster_KeyValue `json:\"StepProperties,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) AWSCloudFormationType() string {\n\treturn \"AWS::EMR::Cluster.HadoopJarStepConfig\"\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetDeletionPolicy(policy policies.DeletionPolicy) ", "output": "{\n\tr._deletionPolicy = policy\n}"} {"input": "package config\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestConfig(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Config Suite\")\n}"} {"input": "package extra\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\nfunc SetNamingStrategy(translate func(string) string) {\n\tjsoniter.RegisterExtension(&namingStrategyExtension{jsoniter.DummyExtension{}, translate})\n}\n\ntype namingStrategyExtension struct {\n\tjsoniter.DummyExtension\n\ttranslate func(string) string\n}\n\nfunc (extension *namingStrategyExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) {\n\tfor _, binding := range structDescriptor.Fields {\n\t\tif unicode.IsLower(rune(binding.Field.Name()[0])) || binding.Field.Name()[0] == '_'{\n\t\t\tcontinue\n\t\t}\n\t\ttag, hastag := binding.Field.Tag().Lookup(\"json\")\n\t\tif hastag {\n\t\t\ttagParts := strings.Split(tag, \",\")\n\t\t\tif tagParts[0] == \"-\" {\n\t\t\t\tcontinue \n\t\t\t}\n\t\t\tif tagParts[0] != \"\" {\n\t\t\t\tcontinue \n\t\t\t}\n\t\t}\n\t\tbinding.ToNames = []string{extension.translate(binding.Field.Name())}\n\t\tbinding.FromNames = []string{extension.translate(binding.Field.Name())}\n\t}\n}\n\n\n\n\nfunc LowerCaseWithUnderscores(name string) string ", "output": "{\n\tnewName := []rune{}\n\tfor i, c := range name {\n\t\tif i == 0 {\n\t\t\tnewName = append(newName, unicode.ToLower(c))\n\t\t} else {\n\t\t\tif unicode.IsUpper(c) {\n\t\t\t\tnewName = append(newName, '_')\n\t\t\t\tnewName = append(newName, unicode.ToLower(c))\n\t\t\t} else {\n\t\t\t\tnewName = append(newName, c)\n\t\t\t}\n\t\t}\n\t}\n\treturn string(newName)\n}"} {"input": "package runewidth\n\nimport (\n\t\"testing\"\n\t\"unicode/utf8\"\n)\n\nvar benchSink int\n\nfunc benchTable(b *testing.B, tbl table) int {\n\tn := 0\n\tfor i := 0; i < b.N; i++ {\n\t\tfor r := rune(0); r <= utf8.MaxRune; r++ {\n\t\t\tif inTable(r, tbl) {\n\t\t\t\tn++\n\t\t\t}\n\t\t}\n\t}\n\treturn n\n}\n\n\nfunc BenchmarkTableNonprint(b *testing.B) {\n\tbenchSink = benchTable(b, nonprint)\n}\nfunc BenchmarkTableCombining(b *testing.B) {\n\tbenchSink = benchTable(b, combining)\n}\nfunc BenchmarkTableDoublewidth(b *testing.B) {\n\tbenchSink = benchTable(b, doublewidth)\n}\nfunc BenchmarkTableAmbiguous(b *testing.B) {\n\tbenchSink = benchTable(b, ambiguous)\n}\nfunc BenchmarkTableEmoji(b *testing.B) {\n\tbenchSink = benchTable(b, emoji)\n}\nfunc BenchmarkTableNotassigned(b *testing.B) {\n\tbenchSink = benchTable(b, notassigned)\n}\nfunc BenchmarkTableNeutral(b *testing.B) {\n\tbenchSink = benchTable(b, neutral)\n}\n\nfunc BenchmarkTablePrivate(b *testing.B) ", "output": "{\n\tbenchSink = benchTable(b, private)\n}"} {"input": "package env\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestEnvGet(t *testing.T) {\n\tgopath := Get(\"GOPATH\", \"\")\n\tif gopath != os.Getenv(\"GOPATH\") {\n\t\tt.Error(\"expected GOPATH not empty.\")\n\t}\n\n\tnoExistVar := Get(\"NOEXISTVAR\", \"foo\")\n\tif noExistVar != \"foo\" {\n\t\tt.Errorf(\"expected NOEXISTVAR to equal foo, got %s.\", noExistVar)\n\t}\n}\n\n\n\nfunc TestEnvSet(t *testing.T) {\n\tSet(\"MYVAR\", \"foo\")\n\tmyVar := Get(\"MYVAR\", \"bar\")\n\tif myVar != \"foo\" {\n\t\tt.Errorf(\"expected MYVAR to equal foo, got %s.\", myVar)\n\t}\n}\n\nfunc TestEnvMustSet(t *testing.T) {\n\terr := MustSet(\"FOO\", \"bar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tfooVar := os.Getenv(\"FOO\")\n\tif fooVar != \"bar\" {\n\t\tt.Errorf(\"expected FOO variable to equal bar, got %s.\", fooVar)\n\t}\n}\n\nfunc TestEnvGetAll(t *testing.T) {\n\tenvMap := GetAll()\n\tif len(envMap) == 0 {\n\t\tt.Error(\"expected environment not empty.\")\n\t}\n}\n\nfunc TestEnvMustGet(t *testing.T) ", "output": "{\n\tgopath, err := MustGet(\"GOPATH\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif gopath != os.Getenv(\"GOPATH\") {\n\t\tt.Errorf(\"expected GOPATH to be the same, got %s.\", gopath)\n\t}\n\n\t_, err = MustGet(\"NOEXISTVAR\")\n\tif err == nil {\n\t\tt.Error(\"expected error to be non-nil\")\n\t}\n}"} {"input": "package jobs\n\nimport (\n\t\"github.com/simplemvc/gocorelib/cron\"\n\t\"github.com/simplemvc/gocorelib/revel\"\n\t\"strings\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype Func func()\n\n\n\nfunc Schedule(spec string, job cron.Job) {\n\tif strings.HasPrefix(spec, \"cron.\") {\n\t\tconfSpec, found := revel.Config.String(spec)\n\t\tif !found {\n\t\t\tpanic(\"Cron spec not found: \" + spec)\n\t\t}\n\t\tspec = confSpec\n\t}\n\tMainCron.Schedule(cron.Parse(spec), New(job))\n}\n\n\n\n\nfunc Every(duration time.Duration, job cron.Job) {\n\tMainCron.Schedule(cron.Every(duration), New(job))\n}\n\n\nfunc Now(job cron.Job) {\n\tgo New(job).Run()\n}\n\n\nfunc In(duration time.Duration, job cron.Job) {\n\tgo func() {\n\t\ttime.Sleep(duration)\n\t\tNew(job).Run()\n\t}()\n}\n\nfunc (r Func) Run() ", "output": "{ r() }"} {"input": "package chacha20poly1305\n\nfunc (c *chacha20poly1305) seal(dst, nonce, plaintext, additionalData []byte) []byte {\n\treturn c.sealGeneric(dst, nonce, plaintext, additionalData)\n}\n\n\n\nfunc (c *chacha20poly1305) open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) ", "output": "{\n\treturn c.openGeneric(dst, nonce, ciphertext, additionalData)\n}"} {"input": "package route\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"path\"\n\t\"strings\"\n)\n\n\nvar match matcher = prefixMatcher\n\n\ntype matcher func(uri string, r *Route) bool\n\n\n\n\n\nfunc globMatcher(uri string, r *Route) bool {\n\tvar hasMatch, err = path.Match(r.Path, uri)\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] Glob matching error %s for path %s route %s\", err, uri, r.Path)\n\t\treturn false\n\t}\n\treturn hasMatch\n}\n\n\nfunc SetMatcher(s string) error {\n\tswitch s {\n\tcase \"prefix\":\n\t\tmatch = prefixMatcher\n\tcase \"glob\":\n\t\tmatch = globMatcher\n\tdefault:\n\t\treturn fmt.Errorf(\"route: invalid matcher: %s\", s)\n\t}\n\treturn nil\n}\n\nfunc prefixMatcher(uri string, r *Route) bool ", "output": "{\n\treturn strings.HasPrefix(uri, r.Path)\n}"} {"input": "package testclient\n\nimport (\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/fields\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/labels\"\n\n\tauthorizationapi \"github.com/openshift/origin/pkg/authorization/api\"\n)\n\n\n\ntype FakeClusterRoles struct {\n\tFake *Fake\n}\n\nfunc (c *FakeClusterRoles) List(label labels.Selector, field fields.Selector) (*authorizationapi.ClusterRoleList, error) {\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"list-clusterRoles\"}, &authorizationapi.ClusterRoleList{})\n\treturn obj.(*authorizationapi.ClusterRoleList), err\n}\n\nfunc (c *FakeClusterRoles) Get(name string) (*authorizationapi.ClusterRole, error) {\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"get-clusterRole\"}, &authorizationapi.ClusterRole{})\n\treturn obj.(*authorizationapi.ClusterRole), err\n}\n\n\n\nfunc (c *FakeClusterRoles) Update(role *authorizationapi.ClusterRole) (*authorizationapi.ClusterRole, error) {\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"update-clusterRole\"}, &authorizationapi.ClusterRole{})\n\treturn obj.(*authorizationapi.ClusterRole), err\n}\n\nfunc (c *FakeClusterRoles) Delete(name string) error {\n\tc.Fake.Actions = append(c.Fake.Actions, FakeAction{Action: \"delete-clusterRole\", Value: name})\n\treturn nil\n}\n\nfunc (c *FakeClusterRoles) Create(role *authorizationapi.ClusterRole) (*authorizationapi.ClusterRole, error) ", "output": "{\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"create-clusterRole\", Value: role}, &authorizationapi.ClusterRole{})\n\treturn obj.(*authorizationapi.ClusterRole), err\n}"} {"input": "package clean\n\nimport (\n\t\"flag\"\n\t\"os\"\n\n\t\"github.com/tueftler/doget/command\"\n\t\"github.com/tueftler/doget/config\"\n\t\"github.com/tueftler/doget/dockerfile\"\n)\n\n\ntype CleanCommand struct {\n\tcommand.Command\n\tflags *flag.FlagSet\n}\n\n\n\n\n\nfunc (c *CleanCommand) Run(parser *dockerfile.Parser, args []string) error {\n\ttarget := config.Vendordir\n\tif _, err := os.Stat(target); nil == err {\n\t\treturn os.RemoveAll(target)\n\t}\n\n\treturn nil\n}\n\nfunc NewCommand(name string) *CleanCommand ", "output": "{\n\treturn &CleanCommand{flags: flag.NewFlagSet(name, flag.ExitOnError)}\n}"} {"input": "package rpc\n\nimport (\n\t\"testing\"\n\n\t\"github.com/cockroachdb/cockroach/util\"\n\t\"github.com/cockroachdb/cockroach/util/leaktest\"\n)\n\nfunc checkUpdateMatches(t *testing.T, network, oldAddrString, newAddrString, expAddrString string) {\n\toldAddr := util.MakeUnresolvedAddr(network, oldAddrString)\n\tnewAddr := util.MakeUnresolvedAddr(network, newAddrString)\n\texpAddr := util.MakeUnresolvedAddr(network, expAddrString)\n\n\tretAddr, err := updatedAddr(oldAddr, newAddr)\n\tif err != nil {\n\t\tt.Fatalf(\"updatedAddr failed on %v, %v: %v\", oldAddr, newAddr, err)\n\t}\n\n\tif retAddr.String() != expAddrString {\n\t\tt.Fatalf(\"updatedAddr(%v, %v) was %s; expected %s\", oldAddr, newAddr, retAddr, expAddr)\n\t}\n}\n\nfunc checkUpdateFails(t *testing.T, network, oldAddrString, newAddrString string) {\n\toldAddr := util.MakeUnresolvedAddr(network, oldAddrString)\n\tnewAddr := util.MakeUnresolvedAddr(network, newAddrString)\n\n\tretAddr, err := updatedAddr(oldAddr, newAddr)\n\tif err == nil {\n\t\tt.Fatalf(\"updatedAddr(%v, %v) should have failed; instead returned %v\", oldAddr, newAddr, retAddr)\n\t}\n}\n\n\n\nfunc TestUpdatedAddr(t *testing.T) ", "output": "{\n\tdefer leaktest.AfterTest(t)\n\tfor _, network := range []string{\"tcp\", \"tcp4\", \"tcp6\"} {\n\t\tcheckUpdateMatches(t, network, \"localhost:0\", \"127.0.0.1:1234\", \"localhost:1234\")\n\t\tcheckUpdateMatches(t, network, \"localhost:1234\", \"127.0.0.1:1234\", \"localhost:1234\")\n\t\tcheckUpdateMatches(t, network, \"localhost:1234\", \"127.0.0.1:1235\", \"localhost:1235\")\n\t}\n\n\tcheckUpdateMatches(t, \"unix\", \"address\", \"address\", \"address\")\n\tcheckUpdateFails(t, \"unix\", \"address\", \"anotheraddress\")\n}"} {"input": "package migrations\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/go-xorm/xorm\"\n)\n\n\n\nfunc addUserOpenIDShow(x *xorm.Engine) error ", "output": "{\n\tif err := x.Sync2(new(UserOpenID)); err != nil {\n\t\treturn fmt.Errorf(\"Sync2: %v\", err)\n\t}\n\treturn nil\n}"} {"input": "package jwt\n\n\n\n\n\n\n\n\nfunc ValidAudience(a, b interface{}) bool {\n\ts1, ok := a.(string)\n\tif ok {\n\t\tif s2, ok := b.(string); ok {\n\t\t\treturn s1 == s2\n\t\t}\n\t\ta2, ok := b.([]string)\n\t\treturn ok && verifyPrincipals([]string{s1}, a2)\n\t}\n\n\ta1, ok := a.([]string)\n\tif !ok {\n\t\treturn false\n\t}\n\tif a2, ok := b.([]string); ok {\n\t\treturn verifyPrincipals(a1, a2)\n\t}\n\ts2, ok := b.(string)\n\treturn ok && len(a1) == 1 && a1[0] == s2\n}\n\nfunc verifyPrincipals(pcpls, auds []string) bool ", "output": "{\n\n\tfound := -1\n\tfor i, p := range pcpls {\n\t\tfor _, v := range auds {\n\t\t\tif p == v {\n\t\t\t\tfound++\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif found != i {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package process\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc toHash(input []byte) string {\n\thasher := sha256.New()\n\thasher.Write(input)\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}\n\nfunc getRandomData() []byte {\n\tsize := 64\n\trb := make([]byte, size)\n\t_, _ = rand.Read(rb)\n\treturn rb\n}\n\nfunc RandomHash() string {\n\treturn toHash(getRandomData())\n}\n\n\ntype Token struct {\n\tHash string\n}\n\nvar ProcessToken *Token = NewToken()\n\nfunc NewToken() *Token {\n\treturn &Token{\n\t\tHash: RandomHash(),\n\t}\n}\n\n\n\nfunc PrettyUniqueToken() string ", "output": "{\n\treturn fmt.Sprintf(\"%d:%s\", time.Now().UnixNano(), NewToken().Hash)\n}"} {"input": "package docker\n\nimport (\n\t\"os/exec\"\n)\n\nfunc IsExistsNetwork(network string) (bool, error) {\n\treturn isExists(\"network\", network)\n}\n\nfunc Network(args []string) (*exec.Cmd, error) {\n\targs = append([]string{\"network\"}, args...)\n\treturn docker(args)\n}\n\n\n\nfunc NetworkCreate(network string) error ", "output": "{\n\targs := []string{\"create\", network}\n\tcmd, err := Network(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd.Stderr = nil\n\terr = cmd.Run()\n\treturn err\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/cihub/seelog\"\n)\n\n\nconst Succeed = \"\\u2713\"\n\n\nconst Failed = \"\\u2717\"\n\n\n\n\nfunc Context(t *testing.T, msg string, args ...interface{}) {\n\tt.Log(fmt.Sprintf(msg, args...))\n}\n\n\nfunc Fatal(t *testing.T, msg string, args ...interface{}) {\n\tm := fmt.Sprintf(msg, args...)\n\tt.Fatal(fmt.Sprintf(\"\\t %-80s\", m), Failed)\n}\n\n\nfunc Error(t *testing.T, msg string, args ...interface{}) {\n\tm := fmt.Sprintf(msg, args...)\n\tt.Error(fmt.Sprintf(\"\\t %-80s\", m), Failed)\n}\n\n\nfunc Success(t *testing.T, msg string, args ...interface{}) {\n\tm := fmt.Sprintf(msg, args...)\n\tt.Log(fmt.Sprintf(\"\\t %-80s\", m), Succeed)\n}\n\nfunc init() ", "output": "{\n\tseelogConfig := \"conf/seelog.xml.test\"\n\tlogger, err := seelog.LoggerFromConfigAsFile(seelogConfig)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"FOO Error creating Logger from seelog file: %s\", seelogConfig)\n\t\tseelog.Error(err)\n\t}\n\tdefer seelog.Flush()\n\tseelog.ReplaceLogger(logger)\n}"} {"input": "package types\n\nimport \"fmt\"\n\ntype KeywordValue struct {\n\tValue string\n}\n\nfunc (v *KeywordValue) ToString() string {\n\treturn fmt.Sprint(v.Value)\n}\n\nfunc (v *KeywordValue) GetType() string {\n\treturn \"keyword\"\n}\n\nfunc (v *KeywordValue) IsValue() bool {\n\treturn false\n}\n\n\n\nfunc (v *KeywordValue) EqualTo(t ValueType) bool {\n\tif v2, ok := t.(*KeywordValue); ok {\n\t\tif v2.Value == v.Value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc NewKeywordValue(v string) *KeywordValue {\n\treturn &KeywordValue{Value: v}\n}\n\nfunc (v *KeywordValue) ConvertTo(t string) (ValueType, error) ", "output": "{\n\treturn nil, fmt.Errorf(\"cannot convert keyword to %s: does not implement yet\", t)\n}"} {"input": "package nsqlookup\n\nimport \"bufio\"\n\ntype Ping struct {\n}\n\n\n\nfunc (c Ping) Write(w *bufio.Writer) (err error) {\n\t_, err = w.WriteString(\"PING\\n\")\n\treturn\n}\n\nfunc readPing(args ...string) (cmd Ping, err error) {\n\treturn\n}\n\nfunc (c Ping) Name() string ", "output": "{\n\treturn \"PING\"\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"net/http\"\n\n\tmiddleware \"github.com/go-openapi/runtime/middleware\"\n)\n\n\ntype DecommissionSiteHandlerFunc func(DecommissionSiteParams) middleware.Responder\n\n\nfunc (fn DecommissionSiteHandlerFunc) Handle(params DecommissionSiteParams) middleware.Responder {\n\treturn fn(params)\n}\n\n\ntype DecommissionSiteHandler interface {\n\tHandle(DecommissionSiteParams) middleware.Responder\n}\n\n\nfunc NewDecommissionSite(ctx *middleware.Context, handler DecommissionSiteHandler) *DecommissionSite {\n\treturn &DecommissionSite{Context: ctx, Handler: handler}\n}\n\n\ntype DecommissionSite struct {\n\tContext *middleware.Context\n\tHandler DecommissionSiteHandler\n}\n\n\n\nfunc (o *DecommissionSite) ServeHTTP(rw http.ResponseWriter, r *http.Request) ", "output": "{\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\tr = rCtx\n\t}\n\tvar Params = NewDecommissionSiteParams()\n\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params) \n\n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}"} {"input": "package dis\n\n\n\nfunc findValidMax(count []int, valid []int, idx int) int {\n\tcurMax, pos := 0, -1\n\tfor i := range count {\n\t\tif count[i] > curMax && idx >= valid[i] {\n\t\t\tcurMax = count[i]\n\t\t\tpos = i\n\t\t}\n\t}\n\treturn pos\n}\n\nfunc Rearrange(s string, k int) string ", "output": "{\n\thm := make([]int, 26)\n\tvalid := make([]int, 26)\n\tvar id, maxF, numOfMaxF int\n\tfor _, c := range s {\n\t\tid = int(c - 'a')\n\t\thm[id]++\n\t\tif hm[id] > maxF {\n\t\t\tmaxF, numOfMaxF = hm[id], 1\n\t\t} else if hm[id] == maxF {\n\t\t\tnumOfMaxF++\n\t\t}\n\t}\n\tif (maxF-1)*k+numOfMaxF > len(s) {\n\t\treturn \"\"\n\t}\n\tret := make([]byte, len(s))\n\tvar pos int\n\tfor i := range s {\n\t\tpos = findValidMax(hm, valid, i)\n\t\thm[pos]--\n\t\tvalid[pos] = i + k\n\t\tret[i] = byte(pos) + 'a'\n\t}\n\treturn string(ret)\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"github.com/obieq/goar/db/couchbase/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n\t\"time\"\n)\n\ntype BeTemporallyMatcher struct {\n\tComparator string\n\tCompareTo time.Time\n\tThreshold []time.Duration\n}\n\nfunc (matcher *BeTemporallyMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, fmt.Sprintf(\"to be %s\", matcher.Comparator), matcher.CompareTo)\n}\n\nfunc (matcher *BeTemporallyMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, fmt.Sprintf(\"not to be %s\", matcher.Comparator), matcher.CompareTo)\n}\n\nfunc (matcher *BeTemporallyMatcher) Match(actual interface{}) (bool, error) {\n\tisTime := func(t interface{}) bool {\n\t\t_, ok := t.(time.Time)\n\t\treturn ok\n\t}\n\n\tif !isTime(actual) {\n\t\treturn false, fmt.Errorf(\"Expected a time.Time. Got:\\n%s\", format.Object(actual, 1))\n\t}\n\n\tswitch matcher.Comparator {\n\tcase \"==\", \"~\", \">\", \">=\", \"<\", \"<=\":\n\tdefault:\n\t\treturn false, fmt.Errorf(\"Unknown comparator: %s\", matcher.Comparator)\n\t}\n\n\tvar threshold = time.Millisecond\n\tif len(matcher.Threshold) == 1 {\n\t\tthreshold = matcher.Threshold[0]\n\t}\n\n\treturn matcher.matchTimes(actual.(time.Time), matcher.CompareTo, threshold), nil\n}\n\n\n\nfunc (matcher *BeTemporallyMatcher) matchTimes(actual, compareTo time.Time, threshold time.Duration) (success bool) ", "output": "{\n\tswitch matcher.Comparator {\n\tcase \"==\":\n\t\treturn actual.Equal(compareTo)\n\tcase \"~\":\n\t\tdiff := actual.Sub(compareTo)\n\t\treturn -threshold <= diff && diff <= threshold\n\tcase \">\":\n\t\treturn actual.After(compareTo)\n\tcase \">=\":\n\t\treturn !actual.Before(compareTo)\n\tcase \"<\":\n\t\treturn actual.Before(compareTo)\n\tcase \"<=\":\n\t\treturn !actual.After(compareTo)\n\t}\n\treturn false\n}"} {"input": "package daemon\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"os/user\"\n)\n\n\nconst (\n\trootPrivileges = \"You must have root user privileges. Possibly using 'sudo' command should help\"\n\tsuccess = \"\\t\\t\\t\\t\\t[ \\033[32mOK\\033[0m ]\" \n\tfailed = \"\\t\\t\\t\\t\\t[\\033[31mFAILED\\033[0m]\" \n)\n\nfunc IsExecutable(path string) (bool, error) {\n\tin, err := os.Open(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer in.Close()\n\n\tstat, err := in.Stat()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif stat.Mode()&0111 != 0 {\n\t\treturn true, nil\n\t} else {\n\t\treturn false, nil\n\t}\n}\n\n\nfunc executablePath(name string) (string, error) {\n\tif path, err := exec.LookPath(name); err == nil {\n\t\t_, err := os.Stat(path)\n\t\tif os.IsNotExist(err) {\n\t\t\treturn execPath()\n\t\t}\n\t\treturn path, nil\n\t}\n\treturn execPath()\n}\n\n\n\n\nfunc checkPrivileges() bool ", "output": "{\n\n\tif user, err := user.Current(); err == nil && user.Gid == \"0\" {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package learn\n\nimport (\n\t\"fmt\"\n)\n\ntype List struct {\n\tData interface{}\n\tNextnode *List\n}\n\nfunc myPrint(t interface{}) {\n\tfmt.Println(t)\n}\n\n\nfunc (l *List) ListLength() int {\n\tvar i int = 0\n\tn := l\n\tfor n.Nextnode != nil {\n\t\ti++\n\t\tn = n.Nextnode\n\t}\n\treturn i + 1\n}\n\n\n\n\n\nfunc (l *List) ListInsert(i int, ele interface{}) bool {\n\tvar s List \n\tif i < 0 || i > l.ListLength() {\n\t\treturn false\n\t}\n\ts.Data = ele\n\tp := l\n\tj := 1\n\tfor j < i && p != nil {\n\t\tj++\n\t\tp = p.Nextnode\n\t}\n\tif p != nil && j <= i {\n\t\ts.Nextnode = p.Nextnode\n\t\tp.Nextnode = &s\n\t} else {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\nfunc (l *List) ListDelete(i int) bool {\n\tp := l\n\tj := 1\n\tfor j < i && p != nil {\n\t\tj++\n\t\tp = p.Nextnode\n\t}\n\tif p == nil || j > i {\n\t\treturn false\n\t}\n\tp.Nextnode = p.Nextnode.Nextnode\n\treturn true\n}\n\n\nfunc (l *List) ListAll() (all string) {\n\tp := l\n\tfor p != nil {\n\t\tall += fmt.Sprintf(\"%v+\", p.Data)\n\t\tp = p.Nextnode\n\t}\n\treturn all\n}\n\nfunc (l *List) GetEle(i int) (ele interface{}) ", "output": "{\n\tif i < 0 || i > l.ListLength() {\n\t\treturn nil\n\t}\n\tcur := l\n\tj := 1\n\tfor cur.Nextnode != nil {\n\t\tif j == i {\n\t\t\treturn cur.Data\n\t\t}\n\t\tj++\n\t\tcur = cur.Nextnode\n\n\t}\n\tif cur != nil && j == i {\n\t\treturn cur.Data\n\t}\n\treturn nil\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realVPCDHCPOptionsAssociation VPCDHCPOptionsAssociation\n\n\n\n\nvar _ fi.HasName = &VPCDHCPOptionsAssociation{}\n\n\nfunc (o *VPCDHCPOptionsAssociation) GetName() *string {\n\treturn o.Name\n}\n\n\nfunc (o *VPCDHCPOptionsAssociation) SetName(name string) {\n\to.Name = &name\n}\n\n\nfunc (o *VPCDHCPOptionsAssociation) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *VPCDHCPOptionsAssociation) UnmarshalJSON(data []byte) error ", "output": "{\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realVPCDHCPOptionsAssociation\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = VPCDHCPOptionsAssociation(r)\n\treturn nil\n}"} {"input": "package metadata\n\nimport \"testing\"\n\nfunc TestGetLanguage(t *testing.T) {\n\tfor _, l := range AllowedLanguages {\n\t\tif g, ok := GetLanguage(l.Name); !ok {\n\t\t\tt.Errorf(\"language defined but not found: %s\", l.Name)\n\t\t} else if g != l {\n\t\t\tt.Errorf(\"found wrong language, expected %v, found %v\", l, g)\n\t\t}\n\t}\n}\n\nfunc TestNoLanguage(t *testing.T) {\n\tlangs := [...]string{\"foobar language\"}\n\tfor _, l := range langs {\n\t\tif _, exist := GetLanguage(l); exist {\n\t\t\tt.Errorf(\"language found but should not exist: %s\", l)\n\t\t}\n\t}\n}\n\n\n\nfunc TestGetLanguageFromExt(t *testing.T) {\n\tfor _, l := range AllowedLanguages {\n\t\tif g, ok := GetLanguageFromExt(l.Ext); !ok {\n\t\t\tt.Errorf(\"cannot look up extension: %s\", l.Ext)\n\t\t} else if l != g {\n\t\t\tt.Errorf(\"language different from definition: %s\", l.Name)\n\t\t}\n\t}\n}\n\nfunc TestNoLanguageFromExt(t *testing.T) {\n\tlangs := [...]string{\"foo\", \"bar\"}\n\tfor _, l := range langs {\n\t\tif _, exist := GetLanguageFromExt(l); exist {\n\t\t\tt.Errorf(\"language found but should not exist: %s\", l)\n\t\t}\n\t}\n}\n\nfunc TestRequiredLanguages(t *testing.T) ", "output": "{\n\tfor _, l := range RequiredLanguages {\n\t\tif !l.Required {\n\t\t\tt.Errorf(\"language is required but not marked required: %s\", l.Name)\n\t\t}\n\t\tif g, ok := GetLanguage(l.Name); !ok {\n\t\t\tt.Errorf(\"language required but not defined: %s\", l.Name)\n\t\t} else if l != g {\n\t\t\tt.Errorf(\"required language different from the definition: %s\", l.Name)\n\t\t}\n\t}\n\n\tfor _, l := range AllowedLanguages {\n\t\tfound := false\n\t\tfor _, r := range RequiredLanguages {\n\t\t\tif l.Name == r.Name {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif l.Required && !found {\n\t\t\tt.Errorf(\"language marked required but not in RequiredLanguages: %s\", l.Name)\n\t\t}\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"net\"\n\t\"strconv\"\n)\n\nconst (\n\tAddrTypeIP = byte(0x01)\n\tAddrTypeDomain = byte(0x03)\n)\n\ntype VAddress struct {\n\tType byte\n\tIP net.IP\n\tDomain string\n\tPort uint16\n}\n\nfunc IPAddress(ip []byte, port uint16) VAddress {\n\treturn VAddress{\n\t\tAddrTypeIP,\n\t\tnet.IP(ip),\n\t\t\"\",\n\t\tport}\n}\n\nfunc DomainAddress(domain string, port uint16) VAddress {\n\treturn VAddress{\n\t\tAddrTypeDomain,\n\t\tnil,\n\t\tdomain,\n\t\tport}\n}\n\nfunc (addr VAddress) IsIPv4() bool {\n\treturn addr.Type == AddrTypeIP && len(addr.IP) == net.IPv4len\n}\n\nfunc (addr VAddress) IsIPv6() bool {\n\treturn addr.Type == AddrTypeIP && len(addr.IP) == net.IPv6len\n}\n\n\n\nfunc (addr VAddress) String() string {\n\tvar host string\n\tswitch addr.Type {\n\tcase AddrTypeIP:\n\t\thost = addr.IP.String()\n\t\tif len(addr.IP) == net.IPv6len {\n\t\t\thost = \"[\" + host + \"]\"\n\t\t}\n\n\tcase AddrTypeDomain:\n\t\thost = addr.Domain\n\tdefault:\n\t\tpanic(\"Unknown Address Type \" + strconv.Itoa(int(addr.Type)))\n\t}\n\treturn host + \":\" + strconv.Itoa(int(addr.Port))\n}\n\nfunc (addr VAddress) IsDomain() bool ", "output": "{\n\treturn addr.Type == AddrTypeDomain\n}"} {"input": "package resources\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"mime\"\n\t\"net/http\"\n\n\tcharmresource \"github.com/juju/charm/v9/resource\"\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/names/v4\"\n\n\t\"github.com/juju/juju/resource\"\n)\n\n\ntype UploadRequest struct {\n\tApplication string\n\n\tName string\n\n\tFilename string\n\n\tSize int64\n\n\tFingerprint charmresource.Fingerprint\n\n\tPendingID string\n\n\tContent io.ReadSeeker\n}\n\n\n\n\nfunc setFilename(filename string, req *http.Request) {\n\tfilename = mime.BEncoding.Encode(\"utf-8\", filename)\n\n\tdisp := mime.FormatMediaType(\n\t\tMediaTypeFormData,\n\t\tmap[string]string{FilenameParamForContentDispositionHeader: filename},\n\t)\n\n\treq.Header.Set(HeaderContentDisposition, disp)\n}\n\n\n\n\n\n\n\n\n\nconst FilenameParamForContentDispositionHeader = \"filename\"\n\n\nfunc (ur UploadRequest) HTTPRequest() (*http.Request, error) {\n\turlStr := NewEndpointPath(ur.Application, ur.Name)\n\n\treq, err := http.NewRequest(http.MethodPut, urlStr, ur.Content)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treq.Header.Set(HeaderContentType, ContentTypeRaw)\n\treq.Header.Set(HeaderContentSha384, ur.Fingerprint.String())\n\treq.Header.Set(HeaderContentLength, fmt.Sprint(ur.Size))\n\tsetFilename(ur.Filename, req)\n\n\treq.ContentLength = ur.Size\n\n\tif ur.PendingID != \"\" {\n\t\tquery := req.URL.Query()\n\t\tquery.Set(QueryParamPendingID, ur.PendingID)\n\t\treq.URL.RawQuery = query.Encode()\n\t}\n\n\treturn req, nil\n}\n\nfunc NewUploadRequest(application, name, filename string, r io.ReadSeeker) (UploadRequest, error) ", "output": "{\n\tif !names.IsValidApplication(application) {\n\t\treturn UploadRequest{}, errors.Errorf(\"invalid application %q\", application)\n\t}\n\n\tcontent, err := resource.GenerateContent(r)\n\tif err != nil {\n\t\treturn UploadRequest{}, errors.Trace(err)\n\t}\n\n\tur := UploadRequest{\n\t\tApplication: application,\n\t\tName: name,\n\t\tFilename: filename,\n\t\tSize: content.Size,\n\t\tFingerprint: content.Fingerprint,\n\t\tContent: r,\n\t}\n\treturn ur, nil\n}"} {"input": "package dao\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestDaoassetRelationField(t *testing.T) {\n\tconvey.Convey(\"assetRelationField\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\toid = int64(0)\n\t\t\totype = \"\"\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\tp1 := assetRelationField(oid, otype)\n\t\t\tctx.Convey(\"Then p1 should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(p1, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestDaoDelCacheAssetRelationState(t *testing.T) {\n\tconvey.Convey(\"DelCacheAssetRelationState\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t\toid = int64(0)\n\t\t\totype = \"\"\n\t\t\tmid = int64(0)\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\terr := d.DelCacheAssetRelationState(c, oid, otype, mid)\n\t\t\tctx.Convey(\"Then err should be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestDaoassetRelationKey(t *testing.T) ", "output": "{\n\tconvey.Convey(\"assetRelationKey\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tmid = int64(0)\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\tp1 := assetRelationKey(mid)\n\t\t\tctx.Convey(\"Then p1 should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(p1, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package elastic\n\n\n\n\n\ntype GeoPolygonQuery struct {\n\tname string\n\tpoints []*GeoPoint\n\tqueryName string\n}\n\n\nfunc NewGeoPolygonQuery(name string) *GeoPolygonQuery {\n\treturn &GeoPolygonQuery{\n\t\tname: name,\n\t\tpoints: make([]*GeoPoint, 0),\n\t}\n}\n\n\nfunc (q *GeoPolygonQuery) AddPoint(lat, lon float64) *GeoPolygonQuery {\n\tq.points = append(q.points, GeoPointFromLatLon(lat, lon))\n\treturn q\n}\n\n\n\n\nfunc (q *GeoPolygonQuery) QueryName(queryName string) *GeoPolygonQuery {\n\tq.queryName = queryName\n\treturn q\n}\n\n\nfunc (q *GeoPolygonQuery) Source() (interface{}, error) {\n\tsource := make(map[string]interface{})\n\n\tparams := make(map[string]interface{})\n\tsource[\"geo_polygon\"] = params\n\n\tpolygon := make(map[string]interface{})\n\tparams[q.name] = polygon\n\n\tpoints := make([]interface{}, 0)\n\tfor _, point := range q.points {\n\t\tpoints = append(points, point.Source())\n\t}\n\tpolygon[\"points\"] = points\n\n\tif q.queryName != \"\" {\n\t\tparams[\"_name\"] = q.queryName\n\t}\n\n\treturn source, nil\n}\n\nfunc (q *GeoPolygonQuery) AddGeoPoint(point *GeoPoint) *GeoPolygonQuery ", "output": "{\n\tq.points = append(q.points, point)\n\treturn q\n}"} {"input": "package services\n\nimport (\n\t\"github.com/astaxie/beego/orm\"\n\t\"github.com/scmo/apayment-backend/models\"\n)\n\nfunc CreateControlPoint(cp *models.ControlPoint) error {\n\to := orm.NewOrm()\n\t_, err := o.Insert(cp)\n\treturn err\n}\n\nfunc GetAllControlPoints() []*models.ControlPoint {\n\to := orm.NewOrm()\n\tvar controlPoints []*models.ControlPoint\n\to.QueryTable(new(models.ControlPoint)).All(&controlPoints)\n\treturn controlPoints\n}\n\n\n\nfunc CountControlPoints() (int64, error) ", "output": "{\n\to := orm.NewOrm()\n\tcnt, err := o.QueryTable(new(models.ControlPoint)).Count() \n\treturn cnt, err\n}"} {"input": "package render\n\nimport (\n\t\"runtime\"\n\t\"sync\"\n)\n\nvar (\n\trender_funcs chan func()\n\tpurge chan bool\n\tinit_once sync.Once\n)\n\nfunc init() {\n\trender_funcs = make(chan func(), 1000)\n\tpurge = make(chan bool)\n}\n\n\nfunc Queue(f func()) {\n\trender_funcs <- f\n}\n\n\n\n\nfunc Init() {\n\tinit_once.Do(func() {\n\t\tgo func() {\n\t\t\truntime.LockOSThread()\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase f := <-render_funcs:\n\t\t\t\t\tf()\n\t\t\t\tcase <-purge:\n\t\t\t\t\tfor {\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase f := <-render_funcs:\n\t\t\t\t\t\t\tf()\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tgoto purged\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tpurged:\n\t\t\t\t\tpurge <- true\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t})\n}\n\nfunc Purge() ", "output": "{\n\tpurge <- true\n\t<-purge\n}"} {"input": "package main\n\nimport \"testing\"\n\nfunc TestNewSliceStack(t *testing.T) {\n\tstack := NewStack()\n\n\tif len(stack) != 0 {\n\t\tt.Error(`Expected length of stack to be 0, got`, len(stack))\n\t}\n}\n\nfunc TestSliceStackPush(t *testing.T) {\n\tstack := NewStack()\n\tstack.Push(1111)\n\tstack.Push(2345)\n\n\tif stack[0] != 1111 {\n\t\tt.Error(`Expected the first item to be 1111, got`, stack[0])\n\t}\n}\n\nfunc TestSliceStackPeek(t *testing.T) {\n\tstack := NewStack()\n\tstack.Push(1234)\n\tstack.Push(2345)\n\tvalue, _ := stack.Peek()\n\n\tif value != 2345 {\n\t\tt.Error(`Expected peeked value to be 2345, got`, value)\n\t}\n}\n\nfunc TestSliceStackPop(t *testing.T) {\n\tstack := NewStack()\n\tstack.Push(1234)\n\tstack.Push(2345)\n\tvalue, _ := stack.Pop()\n\n\tif value != 2345 {\n\t\tt.Error(`Expected peeked value to be 2345, got`, value)\n\t}\n}\n\nfunc BenchmarkSliceStackPush(b *testing.B) {\n\tb.StopTimer()\n\tstack := NewStack()\n\n\tb.StartTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tstack.Push(n)\n\t}\n}\n\n\n\nfunc BenchmarkSliceStackPop(b *testing.B) {\n\tb.StopTimer()\n\tstack := make(Stack, b.N, b.N)\n\tfor n := 0; n < b.N; n++ {\n\t\tstack[n] = n\n\t}\n\n\tb.StartTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tstack.Pop()\n\t}\n}\n\nfunc BenchmarkSliceStackPeek(b *testing.B) ", "output": "{\n\tb.StopTimer()\n\tstack := make(Stack, b.N, b.N)\n\n\tb.StartTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tstack.Peek()\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"github.com/gorilla/pat\"\n)\n\n\n\nfunc main() {\n\tmux := pat.New()\n\n\tmux.Get(\"/hello\", http.HandlerFunc(hello))\n\tmux.Add(\"GET\", \"/\", http.FileServer(http.Dir(\"./public\")))\n\n\thttp.Handle(\"/\", mux)\n\n\tport := os.Getenv(\"PORT\")\n\n\tlog.Println(\"Listening on Port: \" + port)\n\tlog.Fatalln(http.ListenAndServe(\":\"+port, nil))\n}\n\nfunc hello(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tfmt.Fprintf(w, \"Hello World\")\n}"} {"input": "package awsping\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n)\n\n\ntype RequestType int\n\nconst (\n\tRequestTypeHTTP RequestType = iota\n\tRequestTypeTCP\n)\n\n\ntype Requester interface {\n\tDo(ua, url string, reqType RequestType) (time.Duration, error)\n}\n\n\ntype AWSHTTPRequester interface {\n\tDo(req *http.Request) (*http.Response, error)\n}\n\n\ntype AWSTCPRequester interface {\n\tDial(network, address string) (net.Conn, error)\n}\n\n\ntype AWSRequest struct {\n\thttpClient AWSHTTPRequester\n\ttcpClient AWSTCPRequester\n}\n\n\nfunc NewAWSRequest() *AWSRequest {\n\treturn &AWSRequest{\n\t\thttpClient: &http.Client{},\n\t\ttcpClient: &net.Dialer{},\n\t}\n}\n\n\nfunc (r *AWSRequest) DoHTTP(ua, url string) (time.Duration, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treq.Header.Set(\"User-Agent\", ua)\n\n\tstart := time.Now()\n\tresp, err := r.httpClient.Do(req)\n\tlatency := time.Since(start)\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn latency, nil\n}\n\n\nfunc (r *AWSRequest) DoTCP(_, addr string) (time.Duration, error) {\n\tstart := time.Now()\n\tconn, err := r.tcpClient.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tl := time.Since(start)\n\tdefer conn.Close()\n\n\treturn l, nil\n}\n\n\n\n\nfunc (r *AWSRequest) Do(ua, url string, reqType RequestType) (time.Duration, error) ", "output": "{\n\tif reqType == RequestTypeHTTP {\n\t\treturn r.DoHTTP(ua, url)\n\t}\n\treturn r.DoTCP(ua, url)\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype UpdateInternetGatewayRequest struct {\n\n\tIgId *string `mandatory:\"true\" contributesTo:\"path\" name:\"igId\"`\n\n\tUpdateInternetGatewayDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request UpdateInternetGatewayRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request UpdateInternetGatewayRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateInternetGatewayResponse struct {\n\n\tRawResponse *http.Response\n\n\tInternetGateway `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateInternetGatewayResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateInternetGatewayResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateInternetGatewayRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package cache\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/go-spatial/cobra\"\n)\n\nfunc setupMinMaxZoomFlags(cmd *cobra.Command, min, max uint) {\n\tcmd.Flags().UintVarP(&minZoom, \"min-zoom\", \"\", min, \"min zoom to seed cache from\")\n\tcmd.Flags().UintVarP(&maxZoom, \"max-zoom\", \"\", max, \"max zoom to seed cache to\")\n}\n\nfunc IsMinMaxZoomExplicit(cmd *cobra.Command) bool {\n\treturn !(cmd.Flag(\"min-zoom\").Changed || cmd.Flag(\"max-zoom\").Changed)\n}\n\nfunc minMaxZoomValidate(cmd *cobra.Command, args []string) (err error) {\n\tzooms, err = sliceFromRange(minZoom, maxZoom)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid zoom range, %v\", err)\n\t}\n\treturn nil\n}\n\n\n\nfunc tileNameFormatValidate(cmd *cobra.Command, args []string) (err error) {\n\tformat, err = NewFormat(tileListFormat)\n\treturn err\n}\n\nfunc setupTileNameFormat(cmd *cobra.Command) ", "output": "{\n\tcmd.Flags().StringVarP(&tileListFormat, \"format\", \"\", \"/zxy\", \"4 character string where the first character is a non-numeric delimiter followed by 'z', 'x' and 'y' defining the coordinate order\")\n}"} {"input": "package jsonutil\n\nimport (\n\t\"github.com/buger/jsonparser\"\n\t\"strconv\"\n)\n\nfunc GetString(data []byte, keys ...string) (string, error) {\n\treturn jsonparser.GetString(data, keys...)\n}\n\nfunc MustGetString(data []byte, keys ...string) string {\n\ts, err := GetString(data, keys...)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s\n}\n\nfunc GetFloat(data []byte, keys ...string) (float64, error) {\n\treturn jsonparser.GetFloat(data, keys...)\n}\n\nfunc MustGetFloat(data []byte, keys ...string) float64 {\n\tf, err := GetFloat(data, keys...)\n\tif err != nil {\n\t\treturn 0.0\n\t}\n\treturn f\n}\n\nfunc GetInt(data []byte, keys ...string) (int64, error) {\n\treturn jsonparser.GetInt(data, keys...)\n}\n\nfunc MustGetInt(data []byte, keys ...string) int64 {\n\ti, err := GetInt(data, keys...)\n\tif err != nil {\n\t\tif s := MustGetString(data, keys...); len(s) == 0 {\n\t\t\treturn 0\n\t\t} else if i, err = strconv.ParseInt(s, 10, 64); err != nil {\n\t\t\treturn 0\n\t\t}\n\t}\n\treturn i\n}\n\nfunc GetBoolean(data []byte, keys ...string) (bool, error) {\n\treturn jsonparser.GetBoolean(data, keys...)\n}\n\n\n\nfunc MustGetBoolean(data []byte, keys ...string) bool ", "output": "{\n\tb, err := GetBoolean(data, keys...)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn b\n}"} {"input": "package metrics\n\nimport \"github.com/mackerelio/mackerel-agent/mackerel\"\n\n\ntype Values map[string]float64\n\n\nfunc (vs *Values) Merge(other Values) {\n\tfor k, v := range (map[string]float64)(other) {\n\t\t(*vs)[k] = v\n\t}\n}\n\n\ntype ValuesCustomIdentifier struct {\n\tValues Values\n\tCustomIdentifier *string\n}\n\n\n\n\n\ntype Generator interface {\n\tGenerate() (Values, error)\n}\n\n\ntype PluginGenerator interface {\n\tGenerate() (Values, error)\n\tPrepareGraphDefs() ([]mackerel.CreateGraphDefsPayload, error)\n\tCustomIdentifier() *string\n}\n\nfunc MergeValuesCustomIdentifiers(values []ValuesCustomIdentifier, newValue ValuesCustomIdentifier) []ValuesCustomIdentifier ", "output": "{\n\tfor _, value := range values {\n\t\tif value.CustomIdentifier == newValue.CustomIdentifier ||\n\t\t\t(value.CustomIdentifier != nil && newValue.CustomIdentifier != nil &&\n\t\t\t\t*value.CustomIdentifier == *newValue.CustomIdentifier) {\n\t\t\tvalue.Values.Merge(newValue.Values)\n\t\t\treturn values\n\t\t}\n\t}\n\treturn append(values, newValue)\n}"} {"input": "package person_test\n\n\n\nimport (\n\t\"fmt\"\n\n\t\"chitin.io/chitin/examples/maker/fields\"\n)\n\n\n\nfunc Example() ", "output": "{\n\tm := person.NewPersonV2Maker()\n\tm.SetAge(15)\n\tm.SetSiblings(3)\n\tm.SetName(\"Jane\")\n\tbuf := m.Bytes()\n\tfmt.Printf(\"%q\\n\", buf)\n\n}"} {"input": "package v3\n\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\ttranslate \"cloud.google.com/go/translate/apiv3\"\n\ttranslatepb \"google.golang.org/genproto/googleapis/cloud/translate/v3\"\n)\n\n\n\n\nfunc detectLanguage(w io.Writer, projectID string, text string) error ", "output": "{\n\n\tctx := context.Background()\n\tclient, err := translate.NewTranslationClient(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NewTranslationClient: %v\", err)\n\t}\n\tdefer client.Close()\n\n\treq := &translatepb.DetectLanguageRequest{\n\t\tParent: fmt.Sprintf(\"projects/%s/locations/global\", projectID),\n\t\tMimeType: \"text/plain\", \n\t\tSource: &translatepb.DetectLanguageRequest_Content{\n\t\t\tContent: text,\n\t\t},\n\t}\n\n\tresp, err := client.DetectLanguage(ctx, req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"DetectLanguage: %v\", err)\n\t}\n\n\tfor _, language := range resp.GetLanguages() {\n\t\tfmt.Fprintf(w, \"Language code: %v\\n\", language.GetLanguageCode())\n\t\tfmt.Fprintf(w, \"Confidence: %v\\n\", language.GetConfidence())\n\t}\n\n\treturn nil\n}"} {"input": "package handler\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"net/http\"\n\t\"text/template\"\n\t\"time\"\n)\n\n\ntype AppHandler func(http.ResponseWriter, *http.Request) (int, error)\n\n\ntype AppConfig struct {\n\tServerTime int64 `json:\"serverTime\"`\n}\n\nconst (\n\tConfigTemplateName string = \"appConfig\"\n\tConfigTemplate string = \"var appConfig_DO_NOT_USE_DIRECTLY = {{.}}\"\n)\n\n\nfunc (fn AppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif _, err := fn(w, r); err != nil {\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError),\n\t\t\thttp.StatusInternalServerError)\n\t}\n}\n\nfunc getAppConfigJSON() string {\n\tlog.Printf(\"Getting application global configuration\")\n\n\tconfig := &AppConfig{\n\t\tServerTime: time.Now().UTC().UnixNano() / 1e6,\n\t}\n\n\tjson, _ := json.Marshal(config)\n\tlog.Printf(\"Application configuration %s\", json)\n\treturn string(json)\n}\n\n\n\nfunc ConfigHandler(w http.ResponseWriter, r *http.Request) (int, error) ", "output": "{\n\ttemplate, err := template.New(ConfigTemplateName).Parse(ConfigTemplate)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn http.StatusInternalServerError, err\n\t}\n\treturn http.StatusOK, template.Execute(w, getAppConfigJSON())\n}"} {"input": "package types\n\nimport (\n\t\"math\"\n)\n\n\n\n\n\n\n\nfunc getMaxFloat(flen int, decimal int) float64 {\n\tintPartLen := flen - decimal\n\tf := math.Pow10(intPartLen)\n\tf -= math.Pow10(-decimal)\n\treturn f\n}\n\nfunc truncateFloat(f float64, decimal int) float64 {\n\tpow := math.Pow10(decimal)\n\tt := (f - math.Floor(f)) * pow\n\n\tround := RoundFloat(t)\n\n\tf = math.Floor(f) + round/pow\n\treturn f\n}\n\n\n\nfunc TruncateFloat(f float64, flen int, decimal int) (float64, error) {\n\tif math.IsNaN(f) {\n\t\treturn 0, nil\n\t}\n\n\tmaxF := getMaxFloat(flen, decimal)\n\n\tif !math.IsInf(f, 0) {\n\t\tf = truncateFloat(f, decimal)\n\t}\n\n\tif f > maxF {\n\t\tf = maxF\n\t} else if f < -maxF {\n\t\tf = -maxF\n\t}\n\n\treturn f, nil\n}\n\nfunc RoundFloat(val float64) float64 ", "output": "{\n\tv, frac := math.Modf(val)\n\tif val >= 0.0 {\n\t\tif frac > 0.5 || (frac == 0.5 && uint64(v)%2 != 0) {\n\t\t\tv += 1.0\n\t\t}\n\t} else {\n\t\tif frac < -0.5 || (frac == -0.5 && uint64(v)%2 != 0) {\n\t\t\tv -= 1.0\n\t\t}\n\t}\n\n\treturn v\n}"} {"input": "package graph\n\nimport (\n\t\"github.com/filwisher/algo/set\"\n)\n\ntype Graph struct {\n\tEdges map[int] *set.Set\n}\n\nfunc NewGraph() Graph {\n\treturn Graph{\n\t\tEdges: make(map[int] *set.Set),\n\t}\n}\n\nfunc (g *Graph) addSingleEdge(u, v int) {\n\tif _, ok := g.Edges[u]; !ok {\n\t\tg.Edges[u] = set.NewSet()\n\t}\n\tg.Edges[u].Add(v)\n}\n\n\n\nfunc (g *Graph) Adjacent(u int) <-chan int {\n\tch := make(chan int)\n\tgo func() {\n\t\tif set, ok := g.Edges[u]; ok {\n\t\t\tfor e := range set.Each() {\n\t\t\t\tch <- e.(int)\n\t\t\t}\t\n\t\t\tclose(ch)\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc (g *Graph) AddEdge(u, v int) ", "output": "{\n\tg.addSingleEdge(u, v)\n\tg.addSingleEdge(v, u)\n}"} {"input": "package uidgid\n\nimport (\n\t\"os/exec\"\n\t\"syscall\"\n)\n\ntype uidGidMapper struct {\n\tuids []syscall.SysProcIDMap\n\tgids []syscall.SysProcIDMap\n}\n\nfunc NewPrivilegedMapper() Mapper {\n\tmaxID := min(MustGetMaxValidUID(), MustGetMaxValidGID())\n\n\treturn uidGidMapper{\n\t\tuids: []syscall.SysProcIDMap{\n\t\t\t{ContainerID: maxID, HostID: 0, Size: 1},\n\t\t\t{ContainerID: 1, HostID: 1, Size: maxID - 1},\n\t\t},\n\t\tgids: []syscall.SysProcIDMap{\n\t\t\t{ContainerID: maxID, HostID: 0, Size: 1},\n\t\t\t{ContainerID: 1, HostID: 1, Size: maxID - 1},\n\t\t},\n\t}\n}\n\n\n\nfunc (m uidGidMapper) Apply(cmd *exec.Cmd) {\n\tcmd.SysProcAttr.Credential = &syscall.Credential{\n\t\tUid: uint32(m.uids[0].ContainerID),\n\t\tGid: uint32(m.gids[0].ContainerID),\n\t}\n\n\tcmd.SysProcAttr.UidMappings = m.uids\n\tcmd.SysProcAttr.GidMappings = m.gids\n}\n\nfunc findMapping(idMap []syscall.SysProcIDMap, fromID int) int {\n\tfor _, id := range idMap {\n\t\tif id.Size != 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif id.ContainerID == fromID {\n\t\t\treturn id.HostID\n\t\t}\n\t}\n\n\treturn fromID\n}\n\nfunc (m uidGidMapper) Map(fromUid int, fromGid int) (int, int) {\n\treturn findMapping(m.uids, fromUid), findMapping(m.gids, fromGid)\n}\n\nfunc NewUnprivilegedMapper() Mapper ", "output": "{\n\tmaxID := min(MustGetMaxValidUID(), MustGetMaxValidGID())\n\n\treturn uidGidMapper{\n\t\tuids: []syscall.SysProcIDMap{\n\t\t\t{ContainerID: 0, HostID: maxID, Size: 1},\n\t\t\t{ContainerID: 1, HostID: 1, Size: maxID - 1},\n\t\t},\n\t\tgids: []syscall.SysProcIDMap{\n\t\t\t{ContainerID: 0, HostID: maxID, Size: 1},\n\t\t\t{ContainerID: 1, HostID: 1, Size: maxID - 1},\n\t\t},\n\t}\n}"} {"input": "package workshop\n\nimport (\n\t\"math\"\n)\n\n\ntype Shape interface {\n\tarea()\n\tcircumference()\n\tvolume()\n}\n\n\ntype Circle struct {\n\tradius float64\n\tPI float64\n}\n\nfunc (circle *Circle) area() float64 {\n\treturn circle.PI * math.Pow(circle.radius, 2)\n}\n\nfunc (circle *Circle) circumference() float64 {\n\treturn 2 * circle.PI * circle.radius\n}\n\n\ntype Square struct {\n\tside float64\n}\n\nfunc (square *Square) area() float64 {\n\treturn math.Pow(square.side, 2)\n}\n\ntype Sphere struct {\n\tPI float64\n\tradius float64\n}\n\nfunc (sphere *Sphere) volume() float64 {\n\treturn (4 / 3) * sphere.PI * math.Pow(sphere.radius, 3)\n}\n\n\ntype Cube struct {\n\tside float64\n}\n\nfunc (cube *Cube) volume() float64 {\n\treturn math.Pow(cube.side, 3)\n}\n\nfunc (square *Square) volume() float64 {\n\treturn math.Pow(square.side, 3)\n}\n\n\ntype Rectangle struct {\n\theight int\n\twidth int\n}\n\nfunc (rectangle *Rectangle) area() int {\n\treturn rectangle.height * rectangle.width\n}\n\n\n\nfunc interfaces() ", "output": "{\n\tcircle := Circle{radius: 5.5, PI: math.Pi}\n\tareaOfCircle := circle.area()\n\n\tassert(areaOfCircle == 55)\n\tassert(circle.circumference() == 88)\n\n\tvar square = Square{5}\n\tassert(square.area() == 36)\n\n\tcube := new(Cube)\n\tassert(cube.volume() == 8)\n\n\tvar rectangle = Rectangle{width: 4, height: 5}\n\tassert(rectangle.area() == 2)\n}"} {"input": "package runtime\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype response struct {\n}\n\n\nfunc (r response) Message() string {\n\treturn \"the message\"\n}\nfunc (r response) GetHeader(_ string) string {\n\treturn \"the header\"\n}\nfunc (r response) GetHeaders(_ string) []string {\n\treturn []string{\"the headers\", \"the headers2\"}\n}\nfunc (r response) Body() io.ReadCloser {\n\treturn ioutil.NopCloser(bytes.NewBufferString(\"the content\"))\n}\n\nfunc TestResponseReaderFunc(t *testing.T) {\n\tvar actual struct {\n\t\tHeader, Message, Body string\n\t\tCode int\n\t}\n\treader := ClientResponseReaderFunc(func(r ClientResponse, _ Consumer) (interface{}, error) {\n\t\tb, _ := ioutil.ReadAll(r.Body())\n\t\tactual.Body = string(b)\n\t\tactual.Code = r.Code()\n\t\tactual.Message = r.Message()\n\t\tactual.Header = r.GetHeader(\"blah\")\n\t\treturn actual, nil\n\t})\n\t_, _ = reader.ReadResponse(response{}, nil)\n\tassert.Equal(t, \"the content\", actual.Body)\n\tassert.Equal(t, \"the message\", actual.Message)\n\tassert.Equal(t, \"the header\", actual.Header)\n\tassert.Equal(t, 490, actual.Code)\n}\n\nfunc (r response) Code() int ", "output": "{\n\treturn 490\n}"} {"input": "package goleveldb\n\nimport (\n\tstore \"github.com/blevesearch/upsidedown_store_api\"\n\t\"github.com/syndtr/goleveldb/leveldb\"\n)\n\ntype Batch struct {\n\tstore *Store\n\tmerge *store.EmulatedMerge\n\tbatch *leveldb.Batch\n}\n\n\n\nfunc (b *Batch) Delete(key []byte) {\n\tb.batch.Delete(key)\n}\n\nfunc (b *Batch) Merge(key, val []byte) {\n\tb.merge.Merge(key, val)\n}\n\nfunc (b *Batch) Reset() {\n\tb.batch.Reset()\n\tb.merge = store.NewEmulatedMerge(b.store.mo)\n}\n\nfunc (b *Batch) Close() error {\n\tb.batch.Reset()\n\tb.batch = nil\n\tb.merge = nil\n\treturn nil\n}\n\nfunc (b *Batch) Set(key, val []byte) ", "output": "{\n\tb.batch.Put(key, val)\n}"} {"input": "package daemon\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\tbgp \"github.com/gopher-net/gopher-net/third-party/github.com/gobgp/packet\"\n)\n\nfunc NewRibEntry() RibEntry {\n\trib := RibEntry{\n\t\tNextHop: nil,\n\t\tNetworkSegment: 0,\n\t\tDestIpPrefix: nil,\n\t\tLength: 0,\n\t\tGateway: nil,\n\t}\n\treturn rib\n}\n\n\ntype RibEntry struct {\n\tNextHop net.IP\n\tNetworkSegment int\n\tDestIpPrefix net.IP\n\tLength int\n\tGateway net.IP\n\tInterface net.IP\n\tMetric int\n}\n\n\ntype RoutingTable struct {\n\tRib []RibEntry\n}\n\n\nfunc (r *RoutingTable) Add(entry *RibEntry) {\n\tr.Rib = append(r.Rib, *entry)\n}\n\n\n\n\nfunc Ipv4PrefixConcat(p *bgp.NLRInfo) string {\n\treturn fmt.Sprintf(\"%v/%v\", p.Prefix.String(), p.Length)\n}\n\nfunc (r *RoutingTable) Print() string ", "output": "{\n\tresult := fmt.Sprintf(\"%+v\\n\", r.Rib)\n\treturn result\n}"} {"input": "package networkd\n\nimport (\n\t\"github.com/coreos/ignition/tests/register\"\n\t\"github.com/coreos/ignition/tests/types\"\n)\n\n\n\nfunc CreateNetworkdUnit() types.Test {\n\tname := \"Create a networkd unit\"\n\tin := types.GetBaseDisk()\n\tout := types.GetBaseDisk()\n\tconfig := `{\n\t\t\"ignition\": { \"version\": \"2.1.0\" },\n\t\t\"networkd\": {\n\t\t\t\"units\": [{\n\t\t\t\t\"name\": \"static.network\",\n\t\t\t\t\"contents\": \"[Match]\\nName=enp2s0\\n\\n[Network]\\nAddress=192.168.0.15/24\\nGateway=192.168.0.1\\n\"\n\t\t\t}]\n\t\t}\n\t}`\n\tout[0].Partitions.AddFiles(\"ROOT\", []types.File{\n\t\t{\n\t\t\tNode: types.Node{\n\t\t\t\tName: \"static.network\",\n\t\t\t\tDirectory: \"etc/systemd/network\",\n\t\t\t},\n\t\t\tContents: \"[Match]\\nName=enp2s0\\n\\n[Network]\\nAddress=192.168.0.15/24\\nGateway=192.168.0.1\\n\",\n\t\t},\n\t})\n\n\treturn types.Test{\n\t\tName: name,\n\t\tIn: in,\n\t\tOut: out,\n\t\tConfig: config,\n\t}\n}\n\nfunc init() ", "output": "{\n\tregister.Register(register.PositiveTest, CreateNetworkdUnit())\n}"} {"input": "package node\n\nimport (\n\t\"bytes\"\n\n\t\"golang.org/x/net/html\"\n)\n\n\n\n\n\n\nfunc Children(n *html.Node, filter func(*html.Node) bool) []*html.Node {\n\tnodes := make([]*html.Node, 0)\n\n\tif filter == nil {\n\t\tfilter = func(*html.Node) bool { return true }\n\t}\n\n\tfor c := n.FirstChild; c != nil; c = c.NextSibling {\n\t\tif !filter(c) {\n\t\t\tcontinue\n\t\t}\n\t\tnodes = append(nodes, c)\n\n\t}\n\treturn nodes\n}\n\n\nfunc JoinData(n ...*html.Node) string {\n\tvar buf bytes.Buffer\n\tfor _, m := range n {\n\t\tbuf.WriteString(m.Data)\n\t}\n\treturn buf.String()\n}\n\nfunc Attr(n *html.Node, key string) (string, bool) ", "output": "{\n\tfor _, a := range n.Attr {\n\t\tif a.Key == key {\n\t\t\treturn a.Val, true\n\t\t}\n\t}\n\treturn \"\", false\n}"} {"input": "package meli\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nvar (\n\tclient = Client{\n\t\tClientID: 907054494590799,\n\t\tClientSecret: \"x7qFo8AudrLHEsDWm96Kwfu1xbYTiWbW\",\n\t}\n\n\tcode = \"your code\"\n\tredirectUrl = \"redirect url\"\n)\n\n\nfunc TestGetAuthUrl(t *testing.T) {\n\tresult, _ := client.GetAuthUrl(\"\", AuthUrls[\"MLB\"])\n\n\texpected := \"https://auth.mercadolivre.com.br/authorization?client_id=907054494590799&redirect_uri=&response_type=code\"\n\tif reflect.DeepEqual(expected, result) == false {\n\t\tt.Error(fmt.Sprintf(\"Expected: %s - Got: %s\", expected, result))\n\t}\n}\n\n\nfunc TestAuthorize(t *testing.T) {\n\terr := client.Authorize(code, redirectUrl)\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\n\n\n\nfunc TestRefreshAccessToken(t *testing.T) ", "output": "{\n\terr := client.RefreshAccessToken()\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}"} {"input": "package goredis\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestPipelining(t *testing.T) ", "output": "{\n\tp, err := r.Pipelining()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tdefer p.Close()\n\tn := 3\n\tfor i := 0; i < n; i++ {\n\t\tif err := p.Command(\"PING\"); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n\trps, err := p.ReceiveAll()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif len(rps) != n {\n\t\tt.Fail()\n\t}\n\tif s, err := rps[1].StatusValue(); err != nil {\n\t\tt.Error(err)\n\t} else if s != \"PONG\" {\n\t\tt.Fail()\n\t}\n}"} {"input": "package log5go\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype jsonFormatter struct {\n\ttimeFormat string\n\tlines bool\n}\n\ntype jsonLog struct {\n\tTime string `json:\"time\"`\n\tLevel string `json:\"level\"`\n\tPrefix string `json:\"prefix,omitempty\"`\n\tLine string `json:\"line,omitempty\"`\n\tMsg string `json:\"msg\"`\n\tData map[string]interface{} `json:\"data,omitempty\"`\n}\n\nfunc (f *jsonFormatter) Format(tstamp time.Time, level LogLevel, prefix, caller string, line uint, msg string, data Data, out *[]byte) {\n\toutput := jsonLog{\n\t\tTime: tstamp.Format(f.timeFormat),\n\t\tLevel: GetLogLevelString(level),\n\t\tPrefix: prefix,\n\t\tLine: f.formatLine(caller, line),\n\t\tMsg: msg,\n\t\tData: data,\n\t}\n\n\tserialized, err := json.Marshal(output)\n\tif err == nil {\n\t\t*out = append(*out, serialized...)\n\t}\n}\n\nfunc (f *jsonFormatter) SetTimeFormat(timeFormat string) {\n\tf.timeFormat = timeFormat\n}\n\n\n\nfunc (f *jsonFormatter) formatLine(caller string, line uint) string {\n\tif !f.lines || caller == \"\" {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%s:%d\", caller, line)\n}\n\nfunc (f *jsonFormatter) SetLines(lines bool) ", "output": "{\n\tf.lines = lines\n}"} {"input": "package expression\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/juju/errors\"\n\t\"github.com/pingcap/tidb/context\"\n)\n\nvar (\n\t_ Expression = (*Position)(nil)\n)\n\n\n\n\ntype Position struct {\n\tN int\n\tName string\n}\n\n\nfunc (p *Position) Clone() Expression {\n\tnewP := *p\n\treturn &newP\n}\n\n\nfunc (p *Position) IsStatic() bool {\n\treturn false\n}\n\n\n\n\n\nfunc (p *Position) Eval(ctx context.Context, args map[interface{}]interface{}) (v interface{}, err error) {\n\tf, ok := args[ExprEvalPositionFunc]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"no eval position function\")\n\t}\n\tgot, ok := f.(func(int) (interface{}, error))\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"invalid eval position function format\")\n\t}\n\n\treturn got(p.N)\n}\n\n\nfunc (p *Position) Accept(v Visitor) (Expression, error) {\n\treturn v.VisitPosition(p)\n}\n\nfunc (p *Position) String() string ", "output": "{\n\tif len(p.Name) > 0 {\n\t\treturn p.Name\n\t}\n\treturn fmt.Sprintf(\"%d\", p.N)\n}"} {"input": "package zk\n\nimport \"github.com/go-kit/kit/log\"\n\n\ntype Registrar struct {\n\tclient Client\n\tservice Service\n\tlogger log.Logger\n}\n\n\n\ntype Service struct {\n\tPath string \n\tName string \n\tData []byte \n\tnode string \n}\n\n\n\nfunc NewRegistrar(client Client, service Service, logger log.Logger) *Registrar {\n\treturn &Registrar{\n\t\tclient: client,\n\t\tservice: service,\n\t\tlogger: log.NewContext(logger).With(\n\t\t\t\"service\", service.Name,\n\t\t\t\"path\", service.Path,\n\t\t\t\"data\", string(service.Data),\n\t\t),\n\t}\n}\n\n\n\n\n\nfunc (r *Registrar) Deregister() {\n\tif err := r.client.Deregister(&r.service); err != nil {\n\t\tr.logger.Log(\"err\", err)\n\t} else {\n\t\tr.logger.Log(\"action\", \"deregister\")\n\t}\n}\n\nfunc (r *Registrar) Register() ", "output": "{\n\tif err := r.client.Register(&r.service); err != nil {\n\t\tr.logger.Log(\"err\", err)\n\t} else {\n\t\tr.logger.Log(\"action\", \"register\")\n\t}\n}"} {"input": "package app\n\nimport (\n\t\"time\"\n\n\t\"github.com/urfave/cli\"\n)\n\ntype innerContext interface {\n\tArgs() cli.Args\n\tBool(name string) bool\n\tBoolT(name string) bool\n\tDuration(name string) time.Duration\n\tFlagNames() (names []string)\n\tFloat64(name string) float64\n\tGeneric(name string) interface{}\n\tGlobalBool(name string) bool\n\tGlobalBoolT(name string) bool\n\tGlobalDuration(name string) time.Duration\n\tGlobalFlagNames() (names []string)\n\tGlobalFloat64(name string) float64\n\tGlobalGeneric(name string) interface{}\n\tGlobalInt(name string) int\n\tGlobalInt64(name string) int64\n\tGlobalInt64Slice(name string) []int64\n\tGlobalIntSlice(name string) []int\n\tGlobalIsSet(name string) bool\n\tGlobalSet(name, value string) error\n\tGlobalString(name string) string\n\tGlobalStringSlice(name string) []string\n\tGlobalUint(name string) uint\n\tGlobalUint64(name string) uint64\n\tInt(name string) int\n\tInt64(name string) int64\n\tInt64Slice(name string) []int64\n\tIntSlice(name string) []int\n\tIsSet(name string) bool\n\tNArg() int\n\tNumFlags() int\n\tParent() *cli.Context\n\tSet(name, value string) error\n\tString(name string) string\n\tStringSlice(name string) []string\n\tUint(name string) uint\n\tUint64(name string) uint64\n\n\tApp() *cli.App\n\tCommand() cli.Command\n}\n\n\ntype CliContextWrapper struct {\n\t*cli.Context\n}\n\n\n\n\n\nfunc (ctx CliContextWrapper) Command() cli.Command {\n\treturn ctx.Context.Command\n}\n\nfunc (ctx CliContextWrapper) App() *cli.App ", "output": "{\n\treturn ctx.Context.App\n}"} {"input": "package gl\n\nimport (\n\t\"fmt\"\n\t\"github.com/tmacychen/UFG/framework\"\n\n\t\"github.com/goxjs/glfw\"\n)\n\nfunc translateMouseButton(button glfw.MouseButton) framework.MouseButton {\n\tswitch button {\n\tcase glfw.MouseButtonLeft:\n\t\treturn framework.MouseButtonLeft\n\tcase glfw.MouseButtonMiddle:\n\t\treturn framework.MouseButtonMiddle\n\tcase glfw.MouseButtonRight:\n\t\treturn framework.MouseButtonRight\n\tdefault:\n\t\tpanic(fmt.Errorf(\"Unknown mouse button %v\", button))\n\t}\n}\n\n\n\nfunc getMouseState(w *glfw.Window) framework.MouseState ", "output": "{\n\tvar s framework.MouseState\n\tfor _, button := range []glfw.MouseButton{glfw.MouseButtonLeft, glfw.MouseButtonMiddle, glfw.MouseButtonRight} {\n\t\tif w.GetMouseButton(button) == glfw.Press {\n\t\t\ts |= 1 << uint(translateMouseButton(button))\n\t\t}\n\t}\n\treturn s\n}"} {"input": "package iso20022\n\n\ntype HoldIndicator2 struct {\n\n\tIndicator *YesNoIndicator `xml:\"Ind\"`\n\n\tReason []*RegistrationReason1 `xml:\"Rsn,omitempty\"`\n}\n\n\n\nfunc (h *HoldIndicator2) AddReason() *RegistrationReason1 {\n\tnewValue := new(RegistrationReason1)\n\th.Reason = append(h.Reason, newValue)\n\treturn newValue\n}\n\nfunc (h *HoldIndicator2) SetIndicator(value string) ", "output": "{\n\th.Indicator = (*YesNoIndicator)(&value)\n}"} {"input": "package bolthold\n\nimport (\n\t\"reflect\"\n\n\t\"github.com/boltdb/bolt\"\n)\n\n\n\nfunc (s *Store) Delete(key, dataType interface{}) error {\n\treturn s.Bolt().Update(func(tx *bolt.Tx) error {\n\t\treturn s.TxDelete(tx, key, dataType)\n\t})\n}\n\n\n\n\n\nfunc (s *Store) DeleteMatching(dataType interface{}, query *Query) error {\n\treturn s.Bolt().Update(func(tx *bolt.Tx) error {\n\t\treturn s.TxDeleteMatching(tx, dataType, query)\n\t})\n}\n\n\nfunc (s *Store) TxDeleteMatching(tx *bolt.Tx, dataType interface{}, query *Query) error {\n\treturn deleteQuery(tx, dataType, query)\n}\n\nfunc (s *Store) TxDelete(tx *bolt.Tx, key, dataType interface{}) error ", "output": "{\n\tif !tx.Writable() {\n\t\treturn bolt.ErrTxNotWritable\n\t}\n\n\tstorer := newStorer(dataType)\n\tgk, err := encode(key)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb := tx.Bucket([]byte(storer.Type()))\n\tif b == nil {\n\t\treturn ErrNotFound\n\t}\n\n\tvalue := reflect.New(reflect.TypeOf(dataType)).Interface()\n\n\tbVal := b.Get(gk)\n\n\terr = decode(bVal, value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = b.Delete(gk)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = indexDelete(storer, tx, gk, value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package logrus_papertrail\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/botemout/consul-alerts/Godeps/_workspace/src/github.com/Sirupsen/logrus\"\n)\n\nconst (\n\tformat = \"Jan 2 15:04:05\"\n)\n\n\ntype PapertrailHook struct {\n\tHost string\n\tPort int\n\tAppName string\n\tUDPConn net.Conn\n}\n\n\n\n\n\nfunc (hook *PapertrailHook) Fire(entry *logrus.Entry) error {\n\tdate := time.Now().Format(format)\n\tmsg, _ := entry.String()\n\tpayload := fmt.Sprintf(\"<22> %s %s: %s\", date, hook.AppName, msg)\n\n\tbytesWritten, err := hook.UDPConn.Write([]byte(payload))\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to send log line to Papertrail via UDP. Wrote %d bytes before error: %v\", bytesWritten, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc (hook *PapertrailHook) Levels() []logrus.Level {\n\treturn []logrus.Level{\n\t\tlogrus.PanicLevel,\n\t\tlogrus.FatalLevel,\n\t\tlogrus.ErrorLevel,\n\t\tlogrus.WarnLevel,\n\t\tlogrus.InfoLevel,\n\t\tlogrus.DebugLevel,\n\t}\n}\n\nfunc NewPapertrailHook(host string, port int, appName string) (*PapertrailHook, error) ", "output": "{\n\tconn, err := net.Dial(\"udp\", fmt.Sprintf(\"%s:%d\", host, port))\n\treturn &PapertrailHook{host, port, appName, conn}, err\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSIoTAnalyticsPipeline_Channel struct {\n\n\tChannelName string `json:\"ChannelName,omitempty\"`\n\n\tName string `json:\"Name,omitempty\"`\n\n\tNext string `json:\"Next,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) AWSCloudFormationType() string {\n\treturn \"AWS::IoTAnalytics::Pipeline.Channel\"\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\n\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) SetDependsOn(dependencies []string) ", "output": "{\n\tr._dependsOn = dependencies\n}"} {"input": "package weighted\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/AsynkronIT/protoactor-go/cluster\"\n)\n\ntype WeightedMemberStatusValue struct {\n\tWeight int\n}\n\nfunc (sv *WeightedMemberStatusValue) IsSame(val cluster.MemberStatusValue) bool {\n\tif val == nil {\n\t\treturn false\n\t}\n\tif v, ok := val.(*WeightedMemberStatusValue); ok {\n\t\treturn sv.Weight == v.Weight\n\t}\n\treturn false\n}\n\ntype WeightedMemberStatusValueSerializer struct{}\n\n\n\nfunc (s *WeightedMemberStatusValueSerializer) FromValueBytes(val []byte) cluster.MemberStatusValue {\n\tweight, _ := strconv.Atoi(string(val))\n\treturn &WeightedMemberStatusValue{Weight: weight}\n}\n\nfunc (s *WeightedMemberStatusValueSerializer) ToValueBytes(val cluster.MemberStatusValue) []byte ", "output": "{\n\tdVal, _ := val.(*WeightedMemberStatusValue)\n\treturn []byte(strconv.Itoa(dVal.Weight))\n}"} {"input": "package desk\n\nimport (\n \"github.com/stianeikeland/go-rpio\"\n)\n\ntype Direction uint8\n\nvar (\n upPin rpio.Pin\n downPin rpio.Pin\n)\n\nconst (\n Down Direction = iota\n Up\n)\n\nfunc Move(dir Direction) {\n Stop()\n if (dir == Up) {\n upPin.High()\n } else {\n downPin.High()\n }\n}\n\n\n\nfunc Init(up int, down int) (err error) {\n err = rpio.Open()\n\n if (err != nil) {\n return\n }\n\n upPin = rpio.Pin(up)\n upPin.Output()\n upPin.Low()\n\n downPin = rpio.Pin(down)\n downPin.Output()\n downPin.Low()\n\n return nil\n}\n\nfunc Close() {\n rpio.Close()\n}\n\nfunc Stop() ", "output": "{\n upPin.Low()\n downPin.Low()\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(Solve([]int{9, 2, 3, 2, 3}))\n}\n\n\n\nfunc Solve(data []int) int ", "output": "{\n\tx := 0\n\tfor _, a := range data {\n\t\tx ^= a\n\t}\n\treturn x\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\n\nfunc (cli *Client) RegistryLogin(ctx context.Context, auth types.AuthConfig) (types.AuthResponse, error) ", "output": "{\n\tresp, err := cli.post(ctx, \"/auth\", url.Values{}, auth, nil)\n\n\tif resp.statusCode == http.StatusUnauthorized {\n\t\treturn types.AuthResponse{}, unauthorizedError{err}\n\t}\n\tif err != nil {\n\t\treturn types.AuthResponse{}, err\n\t}\n\n\tvar response types.AuthResponse\n\terr = json.NewDecoder(resp.body).Decode(&response)\n\tensureReaderClosed(resp)\n\treturn response, err\n}"} {"input": "package logger\n\n\n\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"strings\"\n)\n\ntype (\n\tLog struct {\n\t\tlogger *log.Logger\n\t\tpositiveList map[string]bool\n\t\tprintAll bool\n\t\tcolor string\n\t}\n)\n\n\nfunc New(w io.Writer, color string, packages string) *Log {\n\tl := &Log{\n\t\tcolor: color,\n\t\tlogger: log.New(w, \"\", log.Ldate|log.Lmicroseconds),\n\t\tpositiveList: make(map[string]bool),\n\t\tprintAll: false,\n\t}\n\n\tpositives := strings.Split(packages, \",\")\n\tfor _, positive := range positives {\n\t\tif positive == \"*\" {\n\t\t\tl.printAll = true\n\t\t} else {\n\t\t\tl.positiveList[positive] = true\n\t\t}\n\t}\n\n\treturn l\n}\n\n\n\n\n\nfunc (l *Log) Logger(pkg string) *log.Logger {\n\t_, print := l.positiveList[pkg]\n\tif print || l.printAll {\n\t\treturn log.New(l, Purple+pkg+\" \"+l.color, 0)\n\t}\n\n\treturn log.New(ioutil.Discard, \"\", 0)\n}\n\n\nfunc (l *Log) Printf(pkg string, format string, args ...interface{}) {\n\tl.logger.Printf(Purple+pkg+Reset+\" \"+format+\"\\n\", args...)\n}\n\n\nfunc (l *Log) Write(p []byte) (n int, err error) {\n\tstr := strings.TrimSpace(string(p))\n\n\tl.logger.Printf(\"%s\"+Reset+\"\\n\", str)\n\n\treturn len(p), nil\n}\n\nfunc (l *Log) Log(pkg string, format string, args ...interface{}) ", "output": "{\n\t_, print := l.positiveList[pkg]\n\tif print || l.printAll {\n\t\tl.Printf(pkg, l.color+format+Reset, args...)\n\t}\n}"} {"input": "package jsons\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\n\ntype FileReader struct {\n\tfilename string\n\tf io.WriteCloser\n\tr *Reader\n}\n\n\n\n\n\n\n\nfunc (fr *FileReader) Open() error {\n\tf, err := os.Open(fr.filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfr.f = f\n\tfr.r = NewReader(f)\n\treturn nil\n}\n\n\nfunc (fr *FileReader) Close() error {\n\treturn fr.f.Close()\n}\n\n\n\nfunc (fr *FileReader) Next(v interface{}) error {\n\treturn fr.r.Next(v)\n}\n\nfunc NewFileReader(filename string) *FileReader ", "output": "{\n\treturn &FileReader{filename: filename}\n}"} {"input": "package crdt\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/mediocregopher/radix.v2/redis\"\n\t\"log\"\n)\n\nvar redisPort int\nvar zset string\nvar client *redis.Client\nvar err error\n\nfunc Add(value int, elemName string) string {\n\tresp := client.Cmd(fmt.Sprintf(\"ZADD\"), zset, value, elemName)\n\tif resp.Err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Command failed: %s\\n\", resp.Err))\n\t} else {\n\t\tfmt.Printf(\"%s\\n\", resp.String())\n\t}\n\treturn resp.String()\n}\n\nfunc Remove(value int, elemName string) string {\n\tresp := client.Cmd(fmt.Sprintf(\"ZREM\"), zset, value, elemName)\n\tif resp.Err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Command failed: %s\\n\", resp.Err))\n\t} else {\n\t\tfmt.Printf(\"%s\\n\", resp.String())\n\t}\n\treturn resp.String()\n}\n\n\n\nfunc checkInput() {\n\tif redisPort == 0 {\n\t\tlog.Fatal(\"Please specify the port at which the redis server is running using --port option.\")\n\t} else if zset == \"\" {\n\t\tlog.Fatal(\"Please specify the name of the ZSET to store using the --zset option.\")\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tcheckInput()\n}\n\nfunc PrintAll(minValue int, maxValue int, constraints string) string ", "output": "{\n\tresp := client.Cmd(fmt.Sprintf(\"ZRANGE\"), zset, minValue, maxValue, constraints)\n\tif resp.Err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Command failed: %s\\n\", resp.Err))\n\t} else {\n\t\tfmt.Printf(\"%s\\n\", resp.String())\n\t}\n\n\treturn resp.String()\n}"} {"input": "package label\n\n\n\n\nfunc InitLabels(mcsdir string, options []string) (string, string, error) {\n\treturn \"\", \"\", nil\n}\n\nfunc FormatMountLabel(src string, mountLabel string) string {\n\treturn src\n}\n\nfunc SetProcessLabel(processLabel string) error {\n\treturn nil\n}\n\nfunc SetFileLabel(path string, fileLabel string) error {\n\treturn nil\n}\n\nfunc SetFileCreateLabel(fileLabel string) error {\n\treturn nil\n}\n\nfunc Relabel(path string, fileLabel string, relabel string) error {\n\treturn nil\n}\n\n\n\nfunc Init() {\n}\n\nfunc ReserveLabel(label string) error {\n\treturn nil\n}\n\nfunc UnreserveLabel(label string) error {\n\treturn nil\n}\n\n\n\nfunc DupSecOpt(src string) []string {\n\treturn nil\n}\n\n\n\nfunc DisableSecOpt() []string {\n\treturn nil\n}\n\nfunc GetPidLabel(pid int) (string, error) ", "output": "{\n\treturn \"\", nil\n}"} {"input": "package windex\n\nimport (\n\t\"time\"\n)\n\ntype Windex struct {\n\tlogfile *LogFile\n\twatcher *Watcher\n\tindexer Indexer\n\tLogData chan []byte\n\tExit chan bool\n}\n\n\n\nfunc (windex *Windex) Watch() {\n\tfor {\n\t\ttime.Sleep(50 * time.Millisecond)\n\t\twindex.watcher.Watch(windex.logfile.Filename)\n\t}\n}\n\nfunc (windex *Windex) Index() {\n\tfor {\n\t\tparsed_log_data, _ := windex.indexer.Parse(windex.LogData)\n\t\twindex.indexer.Flush(parsed_log_data)\n\t}\n}\n\nfunc (windex *Windex) Filename() (filename string) {\n\treturn windex.logfile.Filename\n}\n\nfunc (windex *Windex) startwatchloop() {\n\tfor {\n\t\tselect {\n\t\tcase ev := <-windex.watcher.Watcher.Event:\n\t\t\tif ev != nil && ev.IsModify() && ev.Name == windex.logfile.Filename {\n\t\t\t\twindex.logfile.Flush(windex.LogData)\n\t\t\t}\n\t\tcase err := <-windex.watcher.Watcher.Error:\n\t\t\tif err != nil {\n\t\t\t\twindex.Exit <- true\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nfunc New(filename string, custom_indexer ...Indexer) (windex *Windex, err error) ", "output": "{\n\tlogfile, err := NewLogFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twatcher, err := NewWatcher()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar indexer Indexer\n\n\tif len(custom_indexer) == 0 {\n\t\tindexer = NewStdoutIndexer()\n\t} else {\n\t\tindexer = custom_indexer[0]\n\t}\n\n\texit := make(chan bool)\n\tlog_data := make(chan []byte, 5)\n\n\twindex = &Windex{\n\t\tlogfile: logfile,\n\t\twatcher: watcher,\n\t\tindexer: indexer,\n\t\tExit: exit,\n\t\tLogData: log_data,\n\t}\n\n\tgo windex.startwatchloop()\n\n\treturn windex, nil\n}"} {"input": "package wicore\n\nimport \"fmt\"\n\nconst _BorderType_name = \"BorderNoneBorderSingleBorderDouble\"\n\nvar _BorderType_index = [...]uint8{0, 10, 22, 34}\n\nfunc (i BorderType) String() string {\n\tif i < 0 || i+1 >= BorderType(len(_BorderType_index)) {\n\t\treturn fmt.Sprintf(\"BorderType(%d)\", i)\n\t}\n\treturn _BorderType_name[_BorderType_index[i]:_BorderType_index[i+1]]\n}\n\nconst _CommandCategory_name = \"UnknownCategoryWindowCategoryCommandsCategoryEditorCategoryDebugCategory\"\n\nvar _CommandCategory_index = [...]uint8{0, 15, 29, 45, 59, 72}\n\nfunc (i CommandCategory) String() string {\n\tif i < 0 || i+1 >= CommandCategory(len(_CommandCategory_index)) {\n\t\treturn fmt.Sprintf(\"CommandCategory(%d)\", i)\n\t}\n\treturn _CommandCategory_name[_CommandCategory_index[i]:_CommandCategory_index[i+1]]\n}\n\nconst _DockingType_name = \"DockingUnknownDockingFillDockingFloatingDockingLeftDockingRightDockingTopDockingBottom\"\n\nvar _DockingType_index = [...]uint8{0, 14, 25, 40, 51, 63, 73, 86}\n\nfunc (i DockingType) String() string {\n\tif i < 0 || i+1 >= DockingType(len(_DockingType_index)) {\n\t\treturn fmt.Sprintf(\"DockingType(%d)\", i)\n\t}\n\treturn _DockingType_name[_DockingType_index[i]:_DockingType_index[i+1]]\n}\n\nconst _KeyboardMode_name = \"NormalInsertAllMode\"\n\nvar _KeyboardMode_index = [...]uint8{0, 6, 12, 19}\n\n\n\nfunc (i KeyboardMode) String() string ", "output": "{\n\ti -= 1\n\tif i < 0 || i+1 >= KeyboardMode(len(_KeyboardMode_index)) {\n\t\treturn fmt.Sprintf(\"KeyboardMode(%d)\", i+1)\n\t}\n\treturn _KeyboardMode_name[_KeyboardMode_index[i]:_KeyboardMode_index[i+1]]\n}"} {"input": "package main\n\nimport \"fmt\"\n\ntype Test struct {\n Num int\n}\n\n\n\nfunc main() {\n stu := Test{}\n\n change(stu)\n\n fmt.Println(stu.Num)\n}\n\nfunc change(t Test) ", "output": "{\n t.Num = 3\n}"} {"input": "package coproto\n\nimport \"sync\"\n\n\n\n\n\ntype Client struct {\n\tmutex sync.Mutex\n\tgroup *ClientGroup\n}\n\n\n\n\nfunc (c *Client) Close() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tif c.group == nil {\n\t\treturn \n\t}\n\tc.group.remove(c)\n}\n\n\n\n\nfunc (c *Client) Group() *ClientGroup ", "output": "{\n\treturn c.group\n}"} {"input": "package figure\n\nimport (\n \"fmt\"\n \"log\"\n \"net/http\"\n \"strconv\"\n \"strings\"\n)\n\nconst signature = \"flf2\"\nconst reverseFlag = \"1\"\nvar charDelimiters = [3]string{\"@\", \"#\", \"$\"}\nvar hardblanksBlacklist = [2]byte{'a', '2'}\n\nfunc getFile(name string) (file http.File) {\n filePath := fmt.Sprintf(\"%s.flf\", name)\n file, err := AssetFS().Open(filePath)\n if err != nil {\n log.Fatalf(\"invalid font name:%s.\",err)\n }\n return file\n}\n\nfunc getHeight(metadata string) int {\n datum := strings.Fields(metadata)[1]\n height, _ := strconv.Atoi(datum)\n return height\n}\n\n\n\nfunc getHardblank(metadata string) byte {\n datum := strings.Fields(metadata)[0]\n hardblank := datum[len(datum)-1]\n if hardblank == hardblanksBlacklist[0] || hardblank == hardblanksBlacklist[1] {\n return ' '\n } else {\n return hardblank\n }\n}\n\nfunc getReverse(metadata string) bool {\n data := strings.Fields(metadata)\n return len(data) > 6 && data[6] == reverseFlag\n}\n\nfunc lastCharLine(text string, height int) bool {\n endOfLine, length := \" \", 2\n if height == 1 && len(text) > 0 {\n length = 1\n }\n if len(text) >= length {\n endOfLine = text[len(text)-length:]\n }\n return endOfLine == strings.Repeat(charDelimiters[0], length) ||\n endOfLine == strings.Repeat(charDelimiters[1], length) ||\n endOfLine == strings.Repeat(charDelimiters[2], length)\n}\n\nfunc getBaseline(metadata string) int ", "output": "{\n datum := strings.Fields(metadata)[2]\n baseline, _ := strconv.Atoi(datum)\n return baseline\n}"} {"input": "package xml2json\n\nimport (\n\t\"strings\"\n)\n\n\ntype Node struct {\n\tChildren map[string]Nodes\n\tData string\n\tChildrenAlwaysAsArray bool\n}\n\n\ntype Nodes []*Node\n\n\nfunc (n *Node) AddChild(s string, c *Node) {\n\tif n.Children == nil {\n\t\tn.Children = map[string]Nodes{}\n\t}\n\n\tn.Children[s] = append(n.Children[s], c)\n}\n\n\nfunc (n *Node) IsComplex() bool {\n\treturn len(n.Children) > 0\n}\n\n\n\n\nfunc (n *Node) GetChild(path string) *Node ", "output": "{\n\tresult := n\n\tnames := strings.Split(path, \".\")\n\tfor _, name := range names {\n\t\tchildren, exists := result.Children[name]\n\t\tif !exists {\n\t\t\treturn nil\n\t\t}\n\t\tif len(children) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tresult = children[0]\n\t}\n\treturn result\n}"} {"input": "package packagestest\n\nimport (\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n\n\nfunc proxyDirToURL(dir string) string ", "output": "{\n\tpath := filepath.ToSlash(dir)\n\tif !strings.HasPrefix(path, \"/\") {\n\t\tpath = \"/\" + path\n\t}\n\treturn \"file://\" + path\n}"} {"input": "package manifestparser\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype Locator struct {\n\tFilesToCheckFor []string\n}\n\nfunc NewLocator() *Locator {\n\treturn &Locator{\n\t\tFilesToCheckFor: []string{\n\t\t\t\"manifest.yml\",\n\t\t\t\"manifest.yaml\",\n\t\t},\n\t}\n}\n\nfunc (loc Locator) Path(filepathOrDirectory string) (string, bool, error) {\n\tinfo, err := os.Stat(filepathOrDirectory)\n\tif os.IsNotExist(err) {\n\t\treturn \"\", false, nil\n\t} else if err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tresolvedFilepathOrDirectory, err := filepath.EvalSymlinks(filepathOrDirectory)\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tif info.IsDir() {\n\t\treturn loc.handleDir(resolvedFilepathOrDirectory)\n\t}\n\n\treturn loc.handleFilepath(resolvedFilepathOrDirectory)\n}\n\nfunc (loc Locator) handleDir(dir string) (string, bool, error) {\n\tfor _, filename := range loc.FilesToCheckFor {\n\t\tfullPath := filepath.Join(dir, filename)\n\t\tif _, err := os.Stat(fullPath); err == nil {\n\t\t\treturn fullPath, true, nil\n\t\t} else if !os.IsNotExist(err) {\n\t\t\treturn \"\", false, err\n\t\t}\n\t}\n\n\treturn \"\", false, nil\n}\n\n\n\nfunc (Locator) handleFilepath(filepath string) (string, bool, error) ", "output": "{\n\treturn filepath, true, nil\n}"} {"input": "package watch\n\n\n\ntype FilterFunc func(in Event) (out Event, keep bool)\n\n\n\n\n\n\n\n\n\n\nfunc Filter(w Interface, f FilterFunc) Interface {\n\tfw := &filteredWatch{\n\t\tincoming: w,\n\t\tresult: make(chan Event),\n\t\tf: f,\n\t}\n\tgo fw.loop()\n\treturn fw\n}\n\ntype filteredWatch struct {\n\tincoming Interface\n\tresult chan Event\n\tf FilterFunc\n}\n\n\nfunc (fw *filteredWatch) ResultChan() <-chan Event {\n\treturn fw.result\n}\n\n\nfunc (fw *filteredWatch) Stop() {\n\tfw.incoming.Stop()\n}\n\n\n\n\nfunc (fw *filteredWatch) loop() ", "output": "{\n\tdefer close(fw.result)\n\tfor {\n\t\tevent, ok := <-fw.incoming.ResultChan()\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tfiltered, keep := fw.f(event)\n\t\tif keep {\n\t\t\tfw.result <- filtered\n\t\t}\n\t}\n}"} {"input": "package project\n\nimport (\n\t\"testing\"\n)\n\nfunc TestTrimSpaceAndNonPrintable_unicode(t *testing.T) {\n\tt.Parallel()\n\n\textraChars := \"state\\uFEFF\"\n\twant := \"state\"\n\tgot := TrimSpaceAndNonPrintable(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}\n\n\n\nfunc TestTrimSpace_unicode(t *testing.T) {\n\tt.Parallel()\n\n\textraChars := \"state\\uFEFF\"\n\twant := \"state\"\n\tgot := TrimSpace(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}\n\nfunc TestTrimSpace_space(t *testing.T) {\n\tt.Parallel()\n\n\textraChars := \" state \\r\\t\"\n\twant := \"state\"\n\tgot := TrimSpace(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}\n\nfunc TestTrimSpaceAndNonPrintable_space(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\textraChars := \" state \\r\\t\"\n\twant := \"state\"\n\tgot := TrimSpaceAndNonPrintable(extraChars)\n\n\tif want != got {\n\t\tt.Fatalf(\"wrong trim, want: %q got: %q\", want, got)\n\t}\n}"} {"input": "package model\n\ntype Interface interface {\n\tVisitString(name string, resume func())\n\tVisitInt(name string, resume func())\n\tVisitFloat(name string, resume func())\n\tVisitBool(name string, resume func())\n\tVisitPtr(name string, resume func())\n\tVisitBytes(name string, resume func())\n\tVisitSlice(name string, resume func())\n\tVisitStruct(name string, fields []Field, resume func())\n\tVisitStructField(field Field, resume func())\n\tVisitMap(name string, resume func())\n\tVisitCustom(name string, resume func())\n\tVisitReference(name string, resume func())\n}\n\ntype Visitor struct{}\n\nfunc (self *Visitor) VisitString(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitInt(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitFloat(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBool(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitPtr(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBytes(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitSlice(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\n\n\nfunc (self *Visitor) VisitMap(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitCustom(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitReference(name string, resume func()) {\n\tresume()\n}\n\ntype EmbeddedStructVisitor struct {\n\tInterface\n}\n\nfunc (self *EmbeddedStructVisitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStructField(field Field, resume func()) ", "output": "{\n\tresume()\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gorilla/mux\"\n)\n\n\n\nfunc CreateRouter(routes Routes) *mux.Router ", "output": "{\n\trouter := mux.NewRouter().StrictSlash(true)\n\tfor _, route := range routes {\n\t\tvar handler http.Handler\n\t\thandler = route.HandlerFunc\n\t\thandler = Logger(handler, route.Name)\n\n\t\trouter.\n\t\t\tMethods(route.Method).\n\t\t\tPath(route.Pattern).\n\t\t\tName(route.Name).\n\t\t\tHandler(handler)\n\t}\n\treturn router\n}"} {"input": "package request\n\nimport (\n\t\"CitySourcedAPI/data\"\n\t\"CitySourcedAPI/logs\"\n\t\"CitySourcedAPI/response\"\n\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\n\n\ntype CreateReportComment struct {\n\tRequest\n\tProcessor\n\tReportID string `xml:\"ReportId\" json:\"ReportId\"`\n\treportID int64\n\tComment string `xml:\"Comment\" json:\"Comment\"`\n}\n\nfunc (st *CreateReportComment) Validate(start time.Time) string {\n\tvar v validate\n\tst.start = start\n\tst.reportID = v.int(\"ReportID\", st.ReportID)\n\treturn v.errmsg\n}\n\nfunc (st *CreateReportComment) Run() (string, error) {\n\terr := data.NewComment(st.reportID, data.CustomTime{time.Now()}, st.Comment)\n\tif err != nil {\n\t\treturn response.StatusMsg(fmt.Sprintf(\"CreateReportComment failed: %q\", err), st.start), nil\n\t}\n\treturn response.StatusMsg(\"Comment created.\", st.start), nil\n}\n\n\n\nfunc (st CreateReportComment) String() string ", "output": "{\n\tls := new(logs.LogString)\n\tls.AddS(\"CreateReportComment\\n\")\n\tls.AddS(st.Request.String())\n\tls.AddF(\"ID %s/%d\\n\", st.ReportID, st.reportID)\n\tls.AddF(\"Comment: %v\\n\", st.Comment)\n\treturn ls.Box(90)\n}"} {"input": "package incoming\n\nimport (\n\t\"github.com/pkg/errors\"\n)\n\ntype ignorableErr struct {\n\terror\n}\n\nfunc (e ignorableErr) Ignorable() bool {\n\treturn true\n}\n\nfunc wrapIgnorable(err error) error {\n\treturn ignorableErr{error: err}\n}\n\nfunc (m *RuleMap) Get(name string) (*Rule, error) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tif m.rules == nil {\n\t\treturn nil, wrapIgnorable(errors.New(\"rule not found: '\" + name + \"'\"))\n\t}\n\n\tr, ok := m.rules[name]\n\tif !ok {\n\t\treturn nil, wrapIgnorable(errors.New(\"rule not found: '\" + name + \"'\"))\n\t}\n\treturn r, nil\n}\n\nfunc (m *RuleMap) Set(name string, r *Rule) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tif m.rules == nil {\n\t\tm.rules = make(map[string]*Rule)\n\t}\n\n\tm.rules[name] = r\n}\n\nfunc (r Rule) Disabled() bool {\n\treturn false\n}\n\n\n\nfunc (r Rule) AggregationWindow() int64 ", "output": "{\n\treturn 300\n}"} {"input": "package role\n\nimport (\n\t\"github.com/watermint/toolbox/domain/dropbox/api/dbx_auth\"\n\t\"github.com/watermint/toolbox/domain/dropbox/api/dbx_conn\"\n\t\"github.com/watermint/toolbox/domain/dropbox/model/mo_user\"\n\t\"github.com/watermint/toolbox/domain/dropbox/service/sv_adminrole\"\n\t\"github.com/watermint/toolbox/domain/dropbox/service/sv_member\"\n\t\"github.com/watermint/toolbox/infra/control/app_control\"\n\t\"github.com/watermint/toolbox/infra/recipe/rc_exec\"\n\t\"github.com/watermint/toolbox/infra/recipe/rc_recipe\"\n)\n\ntype Clear struct {\n\tPeer dbx_conn.ConnScopedTeam\n\tEmail string\n}\n\n\n\nfunc (z *Clear) Exec(c app_control.Control) error {\n\tmember, err := sv_member.New(z.Peer.Context()).ResolveByEmail(z.Email)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = sv_adminrole.New(z.Peer.Context()).UpdateRole(mo_user.NewUserSelectorByTeamMemberId(member.TeamMemberId), []string{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (z *Clear) Test(c app_control.Control) error {\n\treturn rc_exec.ExecMock(c, &Clear{}, func(r rc_recipe.Recipe) {\n\t\tm := r.(*Clear)\n\t\tm.Email = \"jo@example.com\"\n\t})\n}\n\nfunc (z *Clear) Preset() ", "output": "{\n\tz.Peer.SetScopes(\n\t\tdbx_auth.ScopeMembersRead,\n\t\tdbx_auth.ScopeMembersWrite,\n\t)\n}"} {"input": "package commands\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestPersianizeNumbers(t *testing.T) ", "output": "{\n\ttype data struct {\n\t\tTestName string\n\t\tNormalString string\n\t\tPersianString string\n\t}\n\n\ttests := []data{\n\t\t{\"Alphanumeric\", \"سلام جهان 12\", \"سلام جهان ۱۲\"},\n\t\t{\"Numeric\", \"0123456789\", \"۰۱۲۳۴۵۶۷۸۹\"},\n\t\t{\"RepititiveAlphanumeric\", \"11 foo 153 بار\", \"۱۱ foo ۱۵۳ بار\"},\n\t}\n\n\tfor i, test := range tests {\n\t\toutput := persianizeNumbers(test.NormalString)\n\t\tif output != test.PersianString {\n\t\t\tt.Errorf(\"Test #%d %s: expected %q, got %q\", i, test.TestName, test.PersianString, output)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/trasa/watchmud-message\"\n)\n\nfunc (c *Client) handleSayResponse(resp *message.SayResponse) {\n\tif resp.Success {\n\t\tUIPrintf(\"You say '%s'\\n\", resp.Value)\n\t} else {\n\t\tif resp.GetResultCode() == \"NOT_IN_A_ROOM\" {\n\t\t\tUIPrintln(\"You yell into the darkness.\")\n\t\t} else {\n\t\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t\t}\n\t}\n}\n\nfunc (c *Client) handleSayNotification(note *message.SayNotification) {\n\tif note.Success {\n\t\tUIPrintf(\"%s says '%s'.\\n\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellNotification(note *message.TellNotification) {\n\tif note.GetSuccess() {\n\t\tUIPrintf(\"%s tells you '%s'.\\n\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellResponse(resp *message.TellResponse) {\n\tif resp.GetSuccess() {\n\t\tUIPrintln(\"sent.\")\n\t} else if resp.GetResultCode() == \"TO_PLAYER_NOT_FOUND\" {\n\t\tUIPrintln(\"Nobody here by that name.\")\n\t} else {\n\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t}\n}\n\n\n\nfunc (c *Client) handleTellAllNotification(note *message.TellAllNotification) {\n\tif note.GetSuccess() {\n\t\tUIPrintf(\"tell_all %s> %s\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellAllResponse(resp *message.TellAllResponse) ", "output": "{\n\tif resp.GetSuccess() {\n\t\tUIPrintln(\"sent.\")\n\t} else {\n\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t}\n}"} {"input": "package rfc3164\n\nimport (\n\t\"time\"\n)\n\n\ntype YearOperator interface {\n\tApply() int\n}\n\n\ntype YearOperation struct {\n\tOperator YearOperator\n}\n\n\n\n\n\ntype CurrentYear struct{}\n\n\nfunc (CurrentYear) Apply() int {\n\treturn time.Now().Year()\n}\n\n\ntype Year struct {\n\tYYYY int\n}\n\n\nfunc (y Year) Apply() int {\n\treturn y.YYYY\n}\n\nfunc (y YearOperation) Operate() int ", "output": "{\n\treturn y.Operator.Apply()\n}"} {"input": "package elasticsearch\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/elastic/beats/libbeat/outputs/outil\"\n)\n\nconst ElasticsearchDefaultHost = \"localhost\"\nconst ElasticsearchDefaultPort = \"9200\"\n\nfunc GetEsPort() string {\n\tport := os.Getenv(\"ES_PORT\")\n\n\tif len(port) == 0 {\n\t\tport = ElasticsearchDefaultPort\n\t}\n\treturn port\n}\n\n\nfunc GetEsHost() string {\n\n\thost := os.Getenv(\"ES_HOST\")\n\n\tif len(host) == 0 {\n\t\thost = ElasticsearchDefaultHost\n\t}\n\n\treturn host\n}\n\n\n\nfunc newTestClientAuth(url, user, pass string) *Client {\n\tclient, err := NewClient(ClientSettings{\n\t\tURL: url,\n\t\tIndex: outil.MakeSelector(),\n\t\tUsername: user,\n\t\tPassword: pass,\n\t\tTimeout: 60 * time.Second,\n\t\tCompressionLevel: 3,\n\t}, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\nfunc GetTestingElasticsearch() *Client ", "output": "{\n\tvar address = \"http://\" + GetEsHost() + \":\" + GetEsPort()\n\tusername := os.Getenv(\"ES_USER\")\n\tpass := os.Getenv(\"ES_PASS\")\n\tclient := newTestClientAuth(address, username, pass)\n\n\tclient.Connect(3 * time.Second)\n\treturn client\n}"} {"input": "package local\n\nimport (\n\t\"github.com/coreos/go-omaha/omaha\"\n)\n\n\n\ntype OmahaWrapper struct {\n\t*omaha.TrivialServer\n}\n\n\n\nfunc (o OmahaWrapper) Destroy() ", "output": "{\n\tif err := o.TrivialServer.Destroy(); err != nil {\n\t\tplog.Errorf(\"Error destroying omaha server: %v\", err)\n\t}\n}"} {"input": "package util\n\nimport \"time\"\n\ntype WriteThrottler struct {\n\tcompactionBytePerSecond int64\n\tlastSizeCounter int64\n\tlastSizeCheckTime time.Time\n}\n\nfunc NewWriteThrottler(bytesPerSecond int64) *WriteThrottler {\n\treturn &WriteThrottler{\n\t\tcompactionBytePerSecond: bytesPerSecond,\n\t\tlastSizeCheckTime: time.Now(),\n\t}\n}\n\n\n\nfunc (wt *WriteThrottler) MaybeSlowdown(delta int64) ", "output": "{\n\tif wt.compactionBytePerSecond > 0 {\n\t\twt.lastSizeCounter += delta\n\t\tnow := time.Now()\n\t\telapsedDuration := now.Sub(wt.lastSizeCheckTime)\n\t\tif elapsedDuration > 100*time.Millisecond {\n\t\t\toverLimitBytes := wt.lastSizeCounter - wt.compactionBytePerSecond/10\n\t\t\tif overLimitBytes > 0 {\n\t\t\t\toverRatio := float64(overLimitBytes) / float64(wt.compactionBytePerSecond)\n\t\t\t\tsleepTime := time.Duration(overRatio*1000) * time.Millisecond\n\t\t\t\ttime.Sleep(sleepTime)\n\t\t\t}\n\t\t\twt.lastSizeCounter, wt.lastSizeCheckTime = 0, time.Now()\n\t\t}\n\t}\n}"} {"input": "package expression\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/juju/errors\"\n\t\"github.com/pingcap/tidb/context\"\n)\n\nvar (\n\t_ Expression = (*Position)(nil)\n)\n\n\n\n\ntype Position struct {\n\tN int\n\tName string\n}\n\n\nfunc (p *Position) Clone() Expression {\n\tnewP := *p\n\treturn &newP\n}\n\n\n\n\n\nfunc (p *Position) String() string {\n\tif len(p.Name) > 0 {\n\t\treturn p.Name\n\t}\n\treturn fmt.Sprintf(\"%d\", p.N)\n}\n\n\nfunc (p *Position) Eval(ctx context.Context, args map[interface{}]interface{}) (v interface{}, err error) {\n\tf, ok := args[ExprEvalPositionFunc]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"no eval position function\")\n\t}\n\tgot, ok := f.(func(int) (interface{}, error))\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"invalid eval position function format\")\n\t}\n\n\treturn got(p.N)\n}\n\n\nfunc (p *Position) Accept(v Visitor) (Expression, error) {\n\treturn v.VisitPosition(p)\n}\n\nfunc (p *Position) IsStatic() bool ", "output": "{\n\treturn false\n}"} {"input": "package master\n\nimport ()\n\n\n\ntype frame struct {\n\tjob *job\n\tslaveName string\n\tframe int\n\tdata []byte\n\tprogress byte\n\tcompleted bool\n}\n\n\n\nfunc NewFrame(job *job, fr int) *frame {\n\treturn &frame{\n\t\tjob: job,\n\t\tslaveName: \"\",\n\t\tframe: fr,\n\t\tdata: nil,\n\t\tprogress: 0,\n\t\tcompleted: false,\n\t}\n}\n\n\n\nfunc (f *frame) Job() *job {\n\treturn f.job\n}\n\nfunc (f *frame) SlaveName() string {\n\treturn f.slaveName\n}\n\nfunc (f *frame) Frame() int {\n\treturn f.frame\n}\n\nfunc (f *frame) AlignedFrame() int {\n\treturn f.frame + f.Job().Start()\n}\n\nfunc (f *frame) Data() []byte {\n\treturn f.data\n}\n\nfunc (f *frame) Progress() byte {\n\treturn f.progress\n}\n\nfunc (f *frame) Completed() bool {\n\treturn f.completed\n}\n\nfunc (f *frame) File() []byte {\n\treturn f.Job().File()\n}\n\n\n\nfunc (f *frame) SetSlaveName(slaveName string) {\n\tf.slaveName = slaveName\n}\n\nfunc (f *frame) SetData(data []byte) {\n\tf.data = data\n}\n\nfunc (f *frame) SetProgress(progress byte) {\n\tf.progress = progress\n}\n\nfunc (f *frame) SetCompleted(completed bool) {\n\tf.completed = completed\n\tif completed {\n\t\tf.SetProgress(100)\n\t}\n}\n\n\n\n\n\nfunc (f *frame) Reset() ", "output": "{\n\tf.SetSlaveName(\"\")\n\tf.SetData(nil)\n\tf.SetProgress(0)\n\tf.SetCompleted(false)\n}"} {"input": "package pmgo\n\nimport mgo \"gopkg.in/mgo.v2\"\n\ntype IterManager interface {\n\tAll(result interface{}) error\n\tClose() error\n\tDone() bool\n\tErr() error\n\tFor(result interface{}, f func() error) (err error)\n\tNext(result interface{}) bool\n\tTimeout() bool\n}\n\ntype Iter struct {\n\titer *mgo.Iter\n}\n\nfunc NewIter(iter *mgo.Iter) IterManager {\n\treturn &Iter{iter}\n}\n\nfunc (i *Iter) All(result interface{}) error {\n\treturn i.iter.All(result)\n}\n\nfunc (i *Iter) Close() error {\n\treturn i.iter.Close()\n}\n\nfunc (i *Iter) Done() bool {\n\treturn i.iter.Done()\n}\n\nfunc (i *Iter) Err() error {\n\treturn i.iter.Err()\n}\n\nfunc (i *Iter) For(result interface{}, f func() error) (err error) {\n\treturn i.iter.For(result, f)\n}\n\n\n\nfunc (i *Iter) Timeout() bool {\n\treturn i.iter.Timeout()\n}\n\nfunc (i *Iter) Next(result interface{}) bool ", "output": "{\n\treturn i.iter.Next(result)\n}"} {"input": "package archive\n\nimport (\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com/containers/storage/pkg/system\"\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\nfunc (info *FileInfo) isDir() bool {\n\treturn info.parent == nil || info.stat.Mode()&unix.S_IFDIR != 0\n}\n\nfunc getIno(fi os.FileInfo) uint64 {\n\treturn fi.Sys().(*syscall.Stat_t).Ino\n}\n\nfunc hasHardlinks(fi os.FileInfo) bool {\n\treturn fi.Sys().(*syscall.Stat_t).Nlink > 1\n}\n\nfunc statDifferent(oldStat *system.StatT, newStat *system.StatT) bool ", "output": "{\n\tif oldStat.Mode() != newStat.Mode() ||\n\t\toldStat.UID() != newStat.UID() ||\n\t\toldStat.GID() != newStat.GID() ||\n\t\toldStat.Rdev() != newStat.Rdev() ||\n\t\t(oldStat.Mode()&unix.S_IFDIR != unix.S_IFDIR &&\n\t\t\t(!sameFsTimeSpec(oldStat.Mtim(), newStat.Mtim()) || (oldStat.Size() != newStat.Size()))) {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package minicon\n\nimport \"container/ring\"\n\n\n\n\ntype History struct {\n\tr *ring.Ring\n}\n\n\n\n\ntype HistoryMarker *ring.Ring\n\n\n\n\nfunc NewHistory(capacity int) *History {\n\treturn &History{ring.New(capacity)}\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (hs *History) Back() (string, bool) {\n\treturn hs._update(hs.r.Prev())\n}\n\n\n\n\n\nfunc (hs *History) Forward() (string, bool) {\n\treturn hs._update(hs.r.Next())\n}\n\n\n\n\nfunc (hs *History) Mark() HistoryMarker {\n\treturn hs.r\n}\n\n\n\n\nfunc (hs *History) Restore(mark HistoryMarker) {\n\tif mark != nil {\n\t\ths.r = mark\n\t}\n}\n\n\n\n\nfunc (hs *History) _update(r *ring.Ring) (ret string, okay bool) {\n\tif s, ok := r.Value.(string); ok && s != \"\" {\n\t\ths.r = r\n\t\tret, okay = s, ok\n\t}\n\treturn ret, okay\n}\n\nfunc (hs *History) Add(s string, mark HistoryMarker) HistoryMarker ", "output": "{\n\ths.Restore(mark)\n\tif s != \"\" && hs.r.Value != s {\n\t\ths.r.Value = s\n\t\ths.r = hs.r.Next()\n\t}\n\treturn nil\n}"} {"input": "package types\n\nimport (\n\t\"database/sql/driver\"\n\t\"encoding/json\"\n\t\"errors\"\n)\n\n\n\n\ntype JSON json.RawMessage\n\n\nfunc (j JSON) String() string {\n\treturn string(j)\n}\n\n\nfunc (j JSON) Unmarshal(dest interface{}) error {\n\treturn json.Unmarshal(j, dest)\n}\n\n\nfunc (j *JSON) Marshal(obj interface{}) error {\n\tres, err := json.Marshal(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*j = res\n\treturn nil\n}\n\n\n\n\n\nfunc (j JSON) MarshalJSON() ([]byte, error) {\n\treturn j, nil\n}\n\n\n\nfunc (j JSON) Value() (driver.Value, error) {\n\tvar r json.RawMessage\n\tif err := j.Unmarshal(&r); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn []byte(r), nil\n}\n\n\nfunc (j *JSON) Scan(src interface{}) error {\n\tvar source []byte\n\n\tswitch src.(type) {\n\tcase string:\n\t\tsource = []byte(src.(string))\n\tcase []byte:\n\t\tsource = src.([]byte)\n\tdefault:\n\t\treturn errors.New(\"incompatible type for json\")\n\t}\n\n\t*j = JSON(append((*j)[0:0], source...))\n\n\treturn nil\n}\n\nfunc (j *JSON) UnmarshalJSON(data []byte) error ", "output": "{\n\tif j == nil {\n\t\treturn errors.New(\"json: unmarshal json on nil pointer to json\")\n\t}\n\n\t*j = append((*j)[0:0], data...)\n\treturn nil\n}"} {"input": "package app\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"k8s.io/kubernetes/pkg/apis/batch\"\n\t\"k8s.io/kubernetes/pkg/client/clientset_generated/clientset\"\n\t\"k8s.io/kubernetes/pkg/controller/cronjob\"\n\t\"k8s.io/kubernetes/pkg/controller/job\"\n)\n\n\n\nfunc startCronJobController(ctx ControllerContext) (bool, error) {\n\tif !ctx.AvailableResources[schema.GroupVersionResource{Group: \"batch\", Version: \"v2alpha1\", Resource: \"cronjobs\"}] {\n\t\treturn false, nil\n\t}\n\tcronjobConfig := ctx.ClientBuilder.ConfigOrDie(\"cronjob-controller\")\n\tcronjobConfig.ContentConfig.GroupVersion = &schema.GroupVersion{Group: batch.GroupName, Version: \"v2alpha1\"}\n\tgo cronjob.NewCronJobController(\n\t\tclientset.NewForConfigOrDie(cronjobConfig),\n\t).Run(ctx.Stop)\n\treturn true, nil\n}\n\nfunc startJobController(ctx ControllerContext) (bool, error) ", "output": "{\n\tif !ctx.AvailableResources[schema.GroupVersionResource{Group: \"batch\", Version: \"v1\", Resource: \"jobs\"}] {\n\t\treturn false, nil\n\t}\n\tgo job.NewJobController(\n\t\tctx.NewInformerFactory.Core().V1().Pods(),\n\t\tctx.NewInformerFactory.Batch().V1().Jobs(),\n\t\tctx.ClientBuilder.ClientOrDie(\"job-controller\"),\n\t).Run(int(ctx.Options.ConcurrentJobSyncs), ctx.Stop)\n\treturn true, nil\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime/pprof\"\n)\n\nconst (\n\tusage = `Usage: %s [OPTION...]\ncontrol program for coffee roasting\n\nOptions:\n`\n)\n\nvar (\n\tmemProfile string\n\tcpuProfile string\n)\n\n\n\n\n\nfunc startProfiling() {\n\tvar err error\n\tif memProfile != \"\" {\n\t\truntime.MemProfileRate = 1\n\t}\n\tif cpuProfile != \"\" {\n\t\tvar f *os.File\n\t\tif f, err = os.Create(cpuProfile); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tpprof.StartCPUProfile(f)\n\t}\n}\n\nfunc stopProfiling() {\n\tif memProfile != \"\" {\n\t\truntime.GC()\n\t\tf, err := os.Create(memProfile)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tpprof.WriteHeapProfile(f)\n\t\tf.Close()\n\t}\n\tif cpuProfile != \"\" {\n\t\tpprof.StopCPUProfile()\n\t\tcpuProfile = \"\"\n\t}\n}\n\nfunc main() {\n\tstartProfiling()\n\tdefer stopProfiling()\n\n}\n\nfunc init() ", "output": "{\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, usage, os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\n\tflag.StringVar(&memProfile, \"memprofile\", \"\",\n\t\t\"write memory profile to this file\")\n\tflag.StringVar(&cpuProfile, \"cpuprofile\", \"\",\n\t\t\"write cpu profile to this file\")\n\n\tflag.Parse()\n}"} {"input": "package ifacetest\n\nimport (\n\t\"github.com/snapcore/snapd/interfaces\"\n\t\"github.com/snapcore/snapd/snap\"\n)\n\n\ntype Specification struct {\n\tSnippets []string\n}\n\n\n\n\n\n\n\nfunc (spec *Specification) AddConnectedPlug(iface interfaces.Interface, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error {\n\ttype definer interface {\n\t\tTestConnectedPlug(spec *Specification, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestConnectedPlug(spec, plug, slot)\n\t}\n\treturn nil\n}\n\n\nfunc (spec *Specification) AddConnectedSlot(iface interfaces.Interface, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error {\n\ttype definer interface {\n\t\tTestConnectedSlot(spec *Specification, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestConnectedSlot(spec, plug, slot)\n\t}\n\treturn nil\n}\n\n\nfunc (spec *Specification) AddPermanentPlug(iface interfaces.Interface, plug *snap.PlugInfo) error {\n\ttype definer interface {\n\t\tTestPermanentPlug(spec *Specification, plug *snap.PlugInfo) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestPermanentPlug(spec, plug)\n\t}\n\treturn nil\n}\n\n\nfunc (spec *Specification) AddPermanentSlot(iface interfaces.Interface, slot *snap.SlotInfo) error {\n\ttype definer interface {\n\t\tTestPermanentSlot(spec *Specification, slot *snap.SlotInfo) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestPermanentSlot(spec, slot)\n\t}\n\treturn nil\n}\n\nfunc (spec *Specification) AddSnippet(snippet string) ", "output": "{\n\tspec.Snippets = append(spec.Snippets, snippet)\n}"} {"input": "package cloudapi_test\n\nimport (\n\tgc \"launchpad.net/gocheck\"\n\n\t\"github.com/joyent/gosdc/cloudapi\"\n)\n\nfunc (s *LocalTests) TestListNetworks(c *gc.C) {\n\tnets, err := s.testClient.ListNetworks()\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(nets, gc.NotNil)\n}\n\n\n\nfunc (s *LocalTests) TestGetNetwork(c *gc.C) ", "output": "{\n\tnet, err := s.testClient.GetNetwork(localNetworkID)\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(net, gc.NotNil)\n\tc.Assert(net, gc.DeepEquals, &cloudapi.Network{\n\t\tId: localNetworkID,\n\t\tName: \"Test-Joyent-Public\",\n\t\tPublic: true,\n\t\tDescription: \"\",\n\t})\n}"} {"input": "package oglematchers\n\n\n\n\n\n\n\n\n\ntype Matcher interface {\n\tMatches(candidate interface{}) error\n\n\tDescription() string\n}\n\n\n\n\n\n\n\n\n\n\n\ntype FatalError struct {\n\terrorText string\n}\n\n\n\n\nfunc (e *FatalError) Error() string {\n\treturn e.errorText\n}\n\nfunc NewFatalError(s string) *FatalError ", "output": "{\n\treturn &FatalError{s}\n}"} {"input": "package getmodules\n\nimport (\n\t\"path\"\n\n\tgetter \"github.com/hashicorp/go-getter\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc SplitPackageSubdir(given string) (packageAddr, subDir string) {\n\tpackageAddr, subDir = getter.SourceDirSubdir(given)\n\tif subDir != \"\" {\n\t\tsubDir = path.Clean(subDir)\n\t}\n\treturn packageAddr, subDir\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ExpandSubdirGlobs(instDir string, subDir string) (string, error) ", "output": "{\n\treturn getter.SubdirGlob(instDir, subDir)\n}"} {"input": "package missinggo\n\nimport \"io\"\n\ntype StatWriter struct {\n\tWritten int64\n\tw io.Writer\n}\n\nfunc (me *StatWriter) Write(b []byte) (n int, err error) {\n\tn, err = me.w.Write(b)\n\tme.Written += int64(n)\n\treturn\n}\n\n\n\nvar ZeroReader zeroReader\n\ntype zeroReader struct{}\n\nfunc (me zeroReader) Read(b []byte) (n int, err error) {\n\tfor i := range b {\n\t\tb[i] = 0\n\t}\n\tn = len(b)\n\treturn\n}\n\nfunc NewStatWriter(w io.Writer) *StatWriter ", "output": "{\n\treturn &StatWriter{w: w}\n}"} {"input": "package callinfo\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\n\t\"github.com/youtube/vitess/go/rpcwrap/proto\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\nfunc RPCWrapCallInfo(ctx context.Context) context.Context {\n\tremoteAddr, _ := proto.RemoteAddr(ctx)\n\tusername, _ := proto.Username(ctx)\n\treturn NewContext(ctx, &rpcWrapCallInfoImpl{\n\t\tremoteAddr: remoteAddr,\n\t\tusername: username,\n\t})\n}\n\ntype rpcWrapCallInfoImpl struct {\n\tremoteAddr, username string\n}\n\nfunc (rwci *rpcWrapCallInfoImpl) RemoteAddr() string {\n\treturn rwci.remoteAddr\n}\n\n\n\nfunc (rwci *rpcWrapCallInfoImpl) Text() string {\n\treturn fmt.Sprintf(\"%s@%s\", rwci.username, rwci.remoteAddr)\n}\n\nfunc (rwci *rpcWrapCallInfoImpl) HTML() template.HTML {\n\treturn template.HTML(\"RemoteAddr: \" + rwci.remoteAddr + \"
\\n\" + \"Username: \" + rwci.username + \"
\\n\")\n}\n\nfunc (rwci *rpcWrapCallInfoImpl) Username() string ", "output": "{\n\treturn rwci.username\n}"} {"input": "package cloudfoundry_test\n\nimport (\n\t\"github.com/javiermanzano/goth\"\n\t\"github.com/javiermanzano/goth/providers/cloudfoundry\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc Test_New(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\tp := provider()\n\n\ta.Equal(p.ClientKey, os.Getenv(\"UAA_CLIENT_ID\"))\n\ta.Equal(p.Secret, os.Getenv(\"UAA_CLIENT_SECRET\"))\n\ta.Equal(p.CallbackURL, \"/foo\")\n}\n\n\n\nfunc Test_BeginAuth(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\tp := provider()\n\tsession, err := p.BeginAuth(\"test_state\")\n\ts := session.(*cloudfoundry.Session)\n\ta.NoError(err)\n\ta.Contains(s.AuthURL, \"https://cf.example.com/oauth/authorize\")\n}\n\nfunc Test_SessionFromJSON(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\n\tp := provider()\n\tsession, err := p.UnmarshalSession(`{\"AuthURL\":\"https://cf.example.com/oauth/authorize\",\"AccessToken\":\"1234567890\"}`)\n\ta.NoError(err)\n\n\ts := session.(*cloudfoundry.Session)\n\ta.Equal(s.AuthURL, \"https://cf.example.com/oauth/authorize\")\n\ta.Equal(s.AccessToken, \"1234567890\")\n}\n\nfunc provider() *cloudfoundry.Provider {\n\treturn cloudfoundry.New(\"https://cf.example.com/\", os.Getenv(\"UAA_CLIENT_ID\"), os.Getenv(\"UAA_CLIENT_SECRET\"), \"/foo\")\n}\n\nfunc Test_Implements_Provider(t *testing.T) ", "output": "{\n\tt.Parallel()\n\ta := assert.New(t)\n\ta.Implements((*goth.Provider)(nil), provider())\n}"} {"input": "package file\n\nimport (\n\t\"testing\"\n\n\t\"github.com/aykevl/dtsync/tree\"\n)\n\n\n\n\nfunc TestFilesystem(t *testing.T) ", "output": "{\n\troot1, err := NewTestRoot()\n\tif err != nil {\n\t\tt.Fatal(\"could not create root1:\", err)\n\t}\n\tdefer func() {\n\t\t_, err := root1.Remove(&tree.FileInfoStruct{})\n\t\tif err != nil {\n\t\t\tt.Fatal(\"could not remove root1 after use:\", err)\n\t\t}\n\t}()\n\n\troot2, err := NewTestRoot()\n\tif err != nil {\n\t\tt.Fatal(\"could not create root2:\", err)\n\t}\n\tdefer func() {\n\t\t_, err := root2.Remove(&tree.FileInfoStruct{})\n\t\tif err != nil {\n\t\t\tt.Fatal(\"could not remove root2 after use:\", err)\n\t\t}\n\t}()\n\n\tt.Log(\"root1:\", root1.path)\n\tt.Log(\"root2:\", root2.path)\n\n\ttree.TreeTest(t, root1, root2)\n}"} {"input": "package logical\n\ntype HTTPCodedError interface {\n\tError() string\n\tCode() int\n}\n\nfunc CodedError(status int, msg string) HTTPCodedError {\n\treturn &codedError{\n\t\tStatus: status,\n\t\tMessage: msg,\n\t}\n}\n\ntype codedError struct {\n\tStatus int\n\tMessage string\n}\n\n\n\nfunc (e *codedError) Code() int {\n\treturn e.Status\n}\n\n\n\ntype StatusBadRequest struct {\n\tErr string\n}\n\n\nfunc (s *StatusBadRequest) Error() string {\n\treturn s.Err\n}\n\n\n\n\n\ntype ReplicationCodedError struct {\n\tMsg string\n\tCode int\n}\n\nfunc (r *ReplicationCodedError) Error() string {\n\treturn r.Msg\n}\n\nfunc (e *codedError) Error() string ", "output": "{\n\treturn e.Message\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"net/url\"\n\n\t\"github.com/docker/engine-api/types\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\nfunc (cli *Client) ImageRemove(ctx context.Context, imageID string, options types.ImageRemoveOptions) ([]types.ImageDelete, error) ", "output": "{\n\tquery := url.Values{}\n\n\tif options.Force {\n\t\tquery.Set(\"force\", \"1\")\n\t}\n\tif !options.PruneChildren {\n\t\tquery.Set(\"noprune\", \"1\")\n\t}\n\n\tresp, err := cli.delete(ctx, \"/images/\"+imageID, query, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar dels []types.ImageDelete\n\terr = json.NewDecoder(resp.body).Decode(&dels)\n\tensureReaderClosed(resp)\n\treturn dels, err\n}"} {"input": "package graphdb\n\n\n\n\nfunc NewSqliteConn(root string) (*Database, error) ", "output": "{\n\tpanic(\"Not implemented\")\n}"} {"input": "package evoli\n\nimport \"math/rand\"\n\ntype crosserMock struct {\n}\n\nfunc (c crosserMock) Cross(parent1, parent2 Individual) (child1, child2 Individual, err error) {\n\tw := 0.1 + 0.8*rand.Float64()\n\treturn NewIndividual(w*parent1.Fitness() + (1-w)*parent2.Fitness()),\n\t\tNewIndividual((1-w)*parent1.Fitness() + w*parent2.Fitness()),\n\t\tnil\n}\n\ntype evaluaterMock struct {\n}\n\n\n\ntype mutaterMock struct {\n}\n\nfunc (m mutaterMock) Mutate(individual Individual, p float64) (Individual, error) {\n\treturn individual, nil\n}\n\ntype positionerMock struct {\n}\n\nfunc (p positionerMock) Position(indiv, pBest, gBest Individual, c1, c2 float64) (Individual, error) {\n\treturn NewIndividual((indiv.Fitness() + pBest.Fitness() + gBest.Fitness()) / 3), nil\n}\n\nfunc (e evaluaterMock) Evaluate(individual Individual) (Fitness float64, err error) ", "output": "{\n\treturn individual.Fitness(), nil\n}"} {"input": "package checks\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tADD int = 1\n\tREMOVE int = 2\n)\n\n\nfunc handleTransition(ipAddress string, live bool) {\n\tif Gm.Clustered && Gm.Members.NumMembers() > 1 {\n\t\terr := NotifyIPState(ipAddress, live, false)\n\t\tif err != nil {\n\t\t\tlog.Errorln(\"Error Updating state: \", ipAddress, err)\n\t\t}\n\t} else {\n\t\tif Gm.MinAgreement > 0 {\n\t\t\tlog.Debugln(\"Running in single mode, BUT need agreement from peers in cluster mode\")\n\t\t} else {\n\t\t\tlog.Debugln(\"Running in single mode, updating DNS\")\n\t\t\tif live == true {\n\t\t\t\terr := updateDNSRec(ipAddress, Gm.DryRun, ADD)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorln(\"Error Adding IP: \", ipAddress, err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr := updateDNSRec(ipAddress, Gm.DryRun, REMOVE)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorln(\"Error Removing IP: \", ipAddress, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\nfunc updateDNSRec(ipAddress string, dryRun bool, op int) error ", "output": "{\n\tvar err error\n\n\tif Gm.Clustered {\n\t\tlog.Debugln(\"Acquiring distributed lock\")\n\t\tif err = Gm.Dmutex.Lock(); err != nil {\n\t\t\treturn errors.New(\"Error acquiring distributed lock: \" + err.Error())\n\t\t} else {\n\t\t\tlog.Debugln(\"Acquired distributed lock: \", time.Now())\n\t\t}\n\t}\n\n\tif op == ADD {\n\t\terr = Master.DNS.AddIP(ipAddress, dryRun)\n\t} else if op == REMOVE {\n\t\terr = Master.DNS.RemoveIP(ipAddress, dryRun)\n\t}\n\n\tif Gm.Clustered {\n\t\tlog.Debugln(\"Releasing distributed lock\")\n\t\tif errUnlock := Gm.Dmutex.UnLock(); errUnlock != nil {\n\t\t\tlog.Errorln(errUnlock)\n\t\t} else {\n\t\t\tlog.Debugln(\"Released distributed lock: \", time.Now())\n\t\t}\n\t}\n\treturn err\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\tosexec \"os/exec\"\n\t\"path/filepath\"\n)\n\n\nfunc exec(args ...string) error {\n\tcmd := osexec.Command(args[0], args[1:]...)\n\tout, err := cmd.CombinedOutput()\n\tswitch err := err.(type) {\n\tcase nil:\n\t\treturn nil\n\tcase *osexec.ExitError:\n\t\treturn fmt.Errorf(\"failed to run %q:\\n%v\", args, string(out))\n\tdefault:\n\t\treturn err\n\t}\n}\n\n\nfunc execVerbose(args ...string) error {\n\tcmd := osexec.Command(args[0], args[1:]...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}\n\n\nfunc execCompose(dir string, args ...string) error {\n\treturn exec(append(\n\t\t[]string{\"docker-compose\", \"--ansi=never\", \"-f\", filepath.Join(dir, \"docker-compose.yml\")},\n\t\targs...)...)\n}\n\n\nfunc execComposeVerbose(dir string, args ...string) error {\n\treturn execVerbose(append(\n\t\t[]string{\"docker-compose\", \"--ansi=never\", \"-f\", filepath.Join(dir, \"docker-compose.yml\")},\n\t\targs...)...)\n}\n\n\n\n\nfunc execDocker(args ...string) error ", "output": "{\n\treturn exec(append([]string{\"docker\"}, args...)...)\n}"} {"input": "package chart\n\nimport (\n\t\"baliance.com/gooxml\"\n\t\"baliance.com/gooxml/drawing\"\n\t\"baliance.com/gooxml/schema/soo/dml\"\n\tcrt \"baliance.com/gooxml/schema/soo/dml/chart\"\n)\n\n\ntype SurfaceChart struct {\n\tchartBase\n\tx *crt.CT_SurfaceChart\n}\n\n\nfunc (c SurfaceChart) X() *crt.CT_SurfaceChart {\n\treturn c.x\n}\n\nfunc (c SurfaceChart) InitializeDefaults() {\n\tc.x.Wireframe = crt.NewCT_Boolean()\n\tc.x.Wireframe.ValAttr = gooxml.Bool(false)\n\n\tc.x.BandFmts = crt.NewCT_BandFmts()\n\tfor i := 0; i < 15; i++ {\n\t\tbfmt := crt.NewCT_BandFmt()\n\t\tbfmt.Idx.ValAttr = uint32(i)\n\t\tbfmt.SpPr = dml.NewCT_ShapeProperties()\n\n\t\tsp := drawing.MakeShapeProperties(bfmt.SpPr)\n\t\tsp.SetSolidFill(c.nextColor(i))\n\t\tc.x.BandFmts.BandFmt = append(c.x.BandFmts.BandFmt, bfmt)\n\t}\n}\n\n\nfunc (c SurfaceChart) AddSeries() SurfaceChartSeries {\n\tcolor := c.nextColor(len(c.x.Ser))\n\tser := crt.NewCT_SurfaceSer()\n\tc.x.Ser = append(c.x.Ser, ser)\n\tser.Idx.ValAttr = uint32(len(c.x.Ser) - 1)\n\tser.Order.ValAttr = uint32(len(c.x.Ser) - 1)\n\n\tls := SurfaceChartSeries{ser}\n\tls.InitializeDefaults()\n\tls.Properties().LineProperties().SetSolidFill(color)\n\treturn ls\n}\n\n\n\n\nfunc (c SurfaceChart) AddAxis(axis Axis) ", "output": "{\n\taxisID := crt.NewCT_UnsignedInt()\n\taxisID.ValAttr = axis.AxisID()\n\tc.x.AxId = append(c.x.AxId, axisID)\n}"} {"input": "package object\n\ntype Error string\n\nfunc (e Error) First() Value {\n\treturn e\n}\n\n\n\nfunc (e Error) Type() Type {\n\treturn ERROR\n}\n\nfunc (e Error) String() string {\n\treturn string(\"\")\n}\n\nfunc (e Error) Rest() Value ", "output": "{\n\treturn e\n}"} {"input": "package gtk\n\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (v *FileChooserButton) GetFocusOnClick() bool {\n\treturn gobool(C.gtk_file_chooser_button_get_focus_on_click(v.native()))\n}\n\n\nfunc (v *FileChooserButton) SetFocusOnClick(grabFocus bool) {\n\tC.gtk_file_chooser_button_set_focus_on_click(v.native(), gbool(grabFocus))\n}\n\n\n\n\nfunc (v *Button) GetFocusOnClick() bool {\n\tc := C.gtk_button_get_focus_on_click(v.native())\n\treturn gobool(c)\n}\n\n\nfunc (v *Button) SetFocusOnClick(focusOnClick bool) {\n\tC.gtk_button_set_focus_on_click(v.native(), gbool(focusOnClick))\n}\n\n\n\n\nfunc (v *TextIter) BeginsTag(v1 *TextTag) bool {\n\treturn gobool(C.gtk_text_iter_begins_tag(v.native(), v1.native()))\n}\n\n\n\n\n\n\n\nfunc (v *Window) ResizeToGeometry(width, height int) {\n\tC.gtk_window_resize_to_geometry(v.native(), C.gint(width), C.gint(height))\n}\n\n\nfunc (v *Window) SetDefaultGeometry(width, height int) {\n\tC.gtk_window_set_default_geometry(v.native(), C.gint(width),\n\t\tC.gint(height))\n}\n\nfunc (v *Window) ParseGeometry(geometry string) bool ", "output": "{\n\tcstr := C.CString(geometry)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_window_parse_geometry(v.native(), (*C.gchar)(cstr))\n\treturn gobool(c)\n}"} {"input": "package nanomsg\n\n\nimport \"C\"\n\nimport (\n\t\"time\"\n)\n\nconst (\n\tSURVEYOR = Protocol(C.NN_SURVEYOR)\n\tRESPONDENT = Protocol(C.NN_RESPONDENT)\n)\n\ntype SurveyorSocket struct {\n\t*Socket\n}\n\n\n\n\n\n\nfunc NewSurveyorSocket() (*SurveyorSocket, error) {\n\tsocket, err := NewSocket(AF_SP, SURVEYOR)\n\treturn &SurveyorSocket{socket}, err\n}\n\n\n\n\n\n\n\nfunc (s *SurveyorSocket) SetDeadline(deadline time.Duration) error {\n\treturn s.Socket.SetSockOptDuration(C.NN_SURVEYOR, C.NN_SURVEYOR_DEADLINE, time.Millisecond, deadline)\n}\n\ntype RespondentSocket struct {\n\t*Socket\n}\n\n\n\n\nfunc NewRespondentSocket() (*RespondentSocket, error) {\n\tsocket, err := NewSocket(AF_SP, RESPONDENT)\n\treturn &RespondentSocket{socket}, err\n}\n\nfunc (s *SurveyorSocket) Deadline() (time.Duration, error) ", "output": "{\n\treturn s.Socket.SockOptDuration(C.NN_SURVEYOR, C.NN_SURVEYOR_DEADLINE, time.Millisecond)\n}"} {"input": "package hdiutil\n\nimport \"os/exec\"\n\n\ntype formatFlag interface {\n\tformatFlag() []string\n}\n\ntype convertFormot int\n\nconst (\n\tConvertUDRW convertFormot = 1 << iota\n\tConvertUDRO\n\tConvertUDCO\n\tConvertUDZO\n\tConvertULFO\n\tConvertUDBZ\n\tConvertUDTO\n\tConvertUDSP\n\tConvertUDSB\n\tConvertUFBI\n\tConvertUDRo\n\tConvertUDCo\n\tConvertRdWr\n\tConvertRdxx\n\tConvertROCo\n\tConvertRken\n\tConvertDC42\n)\n\n\ntype convertFlag interface {\n\tconvertFlag() []string\n}\n\n\ntype ConvertAlign int\n\n\n\ntype convertPmap bool\n\nfunc (c convertPmap) convertFlag() []string { return boolFlag(\"pmap\", bool(c)) }\n\n\n\n\n\n\ntype ConvertSegmentSize string\n\nfunc (c ConvertSegmentSize) convertFlag() []string { return stringFlag(\"segmentSize\", string(c)) }\n\n\n\n\ntype ConvertTasks int\n\nfunc (c ConvertTasks) convertFlag() []string { return intFlag(\"tasks\", int(c)) }\n\nconst (\n\tConvertPmap convertPmap = true\n)\n\n\nfunc Convert(image string, format formatFlag, outfile string, flags ...convertFlag) error {\n\tcmd := exec.Command(hdiutilPath, \"convert\", image)\n\tcmd.Args = append(cmd.Args, format.formatFlag()...)\n\tcmd.Args = append(cmd.Args, outfile)\n\tif len(flags) > 0 {\n\t\tfor _, flag := range flags {\n\t\t\tcmd.Args = append(cmd.Args, flag.convertFlag()...)\n\t\t}\n\t}\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c ConvertAlign) convertFlag() []string ", "output": "{ return intFlag(\"align\", int(c)) }"} {"input": "package main\n\nimport \"time\"\n\n\nfunc DeleteEmptyString(slice []string) []string {\n\tvar localSlice []string\n\tfor _, str := range slice {\n\t\tif str != \"\" {\n\t\t\tlocalSlice = append(localSlice, str)\n\t\t}\n\t}\n\treturn localSlice\n}\n\n\n\n\nfunc DroneSleep(seconds int) ", "output": "{\n\tlog.Debugf(\"sleeping for %d seconds\", seconds)\n\ttime.Sleep(time.Duration(seconds) * time.Second)\n}"} {"input": "package parser\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestValidPodFromSentinelConfig(t *testing.T) {\n\t_, err := ParseSentinelConfig(\"sentinel.conf\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n}\n\nfunc TestBadDirectives(t *testing.T) {\n\tsconf, err := ParseSentinelConfig(\"sentinel.conf\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n\tif len(sconf.BadDirectives) == 0 {\n\t\tt.Error(fmt.Errorf(\"Should have had bad directives, had none.\"))\n\t\tt.Fail()\n\t}\n}\n\nfunc TestGetPod(t *testing.T) {\n\tsconf, err := ParseSentinelConfig(\"sentinel.conf\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n\tpod, err := sconf.GetPod(\"pod1\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n\tif pod.Name != \"pod1\" {\n\t\tt.Error(fmt.Errorf(\"retreived pod is not named 'pod1'\"))\n\t\tt.Fail()\n\t}\n}\n\nfunc TestPodKnownSentinels(t *testing.T) {\n\tsconf, err := ParseSentinelConfig(\"sentinel.conf\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n\tpod, err := sconf.GetPod(\"pod1\")\n\tif len(pod.KnownSentinels) != 2 {\n\t\tt.Error(fmt.Errorf(\"Mismatched KnownSentinels. Expected 2, got %d\", len(pod.KnownSentinels)))\n\t\tfmt.Printf(\"pod: %+v\\n\", pod)\n\t\tt.Fail()\n\t}\n}\n\nfunc TestPodKnownSlaves(t *testing.T) ", "output": "{\n\tsconf, err := ParseSentinelConfig(\"sentinel.conf\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n\tpod, err := sconf.GetPod(\"pod1\")\n\tif len(pod.KnownSlaves) != 2 {\n\t\tt.Error(fmt.Errorf(\"Mismatched KnownSlaves. Expected 2, got %d\", len(pod.KnownSlaves)))\n\t\tt.Fail()\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"html/template\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype Page struct {\n\tTitle string\n\tBody []byte\n}\n\nfunc (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}\n\nfunc loadPage(title string) (*Page, error) {\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Page{Title: title, Body: body}, nil\n}\n\n\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/view/\"):]\n\tp, _ := loadPage(title)\n\trenderTemplate(w, \"view\", p)\n}\n\nfunc saveHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/save/\"):]\n\tbody := r.FormValue(\"body\")\n\tp := &Page{Title: title, Body: []byte(body)}\n\tp.save()\n\thttp.Redirect(w, r, \"/view/\"+title, http.StatusFound)\n}\n\nfunc renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {\n\tt, _ := template.ParseFiles(tmpl + \".html\")\n\tt.Execute(w, p)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/view/\", viewHandler)\n\thttp.HandleFunc(\"/edit/\", editHandler)\n\thttp.HandleFunc(\"/save/\", saveHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc editHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\ttitle := r.URL.Path[len(\"/edit/\"):]\n\tp, err := loadPage(title)\n\tif err != nil {\n\t\tp = &Page{Title: title}\n\t}\n\trenderTemplate(w, \"edit\", p)\n}"} {"input": "package model\n\ntype RepoSecret struct {\n\tID int64 `json:\"id\" meddler:\"secret_id,pk\"`\n\n\tRepoID int64 `json:\"-\" meddler:\"secret_repo_id\"`\n\n\tName string `json:\"name\" meddler:\"secret_name\"`\n\n\tValue string `json:\"value\" meddler:\"secret_value\"`\n\n\tImages []string `json:\"image,omitempty\" meddler:\"secret_images,json\"`\n\n\tEvents []string `json:\"event,omitempty\" meddler:\"secret_events,json\"`\n\n\tSkipVerify bool `json:\"skip_verify\" meddler:\"secret_skip_verify\"`\n\n\tConceal bool `json:\"conceal\" meddler:\"secret_conceal\"`\n}\n\n\nfunc (s *RepoSecret) Secret() *Secret {\n\treturn &Secret{\n\t\tName: s.Name,\n\t\tValue: s.Value,\n\t\tImages: s.Images,\n\t\tEvents: s.Events,\n\t\tSkipVerify: s.SkipVerify,\n\t\tConceal: s.Conceal,\n\t}\n}\n\n\n\n\n\nfunc (s *RepoSecret) Validate() error {\n\treturn nil\n}\n\nfunc (s *RepoSecret) Clone() *RepoSecret ", "output": "{\n\treturn &RepoSecret{\n\t\tID: s.ID,\n\t\tName: s.Name,\n\t\tImages: s.Images,\n\t\tEvents: s.Events,\n\t\tSkipVerify: s.SkipVerify,\n\t\tConceal: s.Conceal,\n\t}\n}"} {"input": "package cm\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/kubernetes/pkg/kubelet/dockershim/libdocker\"\n)\n\ntype unsupportedContainerManager struct {\n}\n\n\n\n\nfunc (m *unsupportedContainerManager) Start() error {\n\treturn fmt.Errorf(\"Container Manager is unsupported in this build\")\n}\n\nfunc NewContainerManager(_ string, _ libdocker.Interface) ContainerManager ", "output": "{\n\treturn &unsupportedContainerManager{}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\n\t\"golang.org/x/net/websocket\"\n)\n\nconst channelBufSize = 100\n\nvar maxID int = 0\n\ntype Client struct {\n\tid int\n\tws *websocket.Conn\n\tserver *Server\n\tch chan *Message\n\tdoneCh chan bool\n}\n\nfunc NewClient(ws *websocket.Conn, server *Server) *Client {\n\tif ws == nil {\n\t\tpanic(\"ws cannot be nil\")\n\t}\n\n\tif server == nil {\n\t\tpanic(\"server cannot be nil\")\n\t}\n\n\tmaxID++\n\tch := make(chan *Message, channelBufSize)\n\tdoneCh := make(chan bool)\n\n\treturn &Client{maxID, ws, server, ch, doneCh}\n}\n\nfunc (c *Client) Conn() *websocket.Conn {\n\treturn c.ws\n}\n\nfunc (c *Client) Write(msg *Message) {\n\tselect {\n\tcase c.ch <- msg:\n\tdefault:\n\t\tc.server.Del(c)\n\t\terr := fmt.Errorf(\"client %d is disconnected.\", c.id)\n\t\tc.server.Err(err)\n\t}\n}\n\nfunc (c *Client) Done() {\n\tc.doneCh <- true\n}\n\nfunc (c *Client) Listen() {\n\tgo c.listenWrite()\n\tc.listenRead()\n}\n\nfunc (c *Client) listenWrite() {\n\tlog.Println(\"Listening write to client\")\n\tfor {\n\t\tselect {\n\t\tcase msg := <-c.ch:\n\t\t\tlog.Println(\"Send: \", msg)\n\t\t\twebsocket.JSON.Send(c.ws, msg)\n\n\t\tcase <-c.doneCh:\n\t\t\tc.server.Del(c)\n\t\t\tc.doneCh <- true\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\nfunc (c *Client) listenRead() ", "output": "{\n\tlog.Println(\"Listening read from client\")\n\tfor {\n\t\tselect {\n\t\tcase <-c.doneCh:\n\t\t\tc.server.Del(c)\n\t\t\tc.doneCh <- true\n\t\t\treturn\n\n\t\tdefault:\n\t\t\tvar msg Message\n\t\t\terr := websocket.JSON.Receive(c.ws, &msg)\n\t\t\tif err == io.EOF {\n\t\t\t\tc.doneCh <- true\n\t\t\t} else if err != nil {\n\t\t\t\tc.server.Err(err)\n\t\t\t} else {\n\t\t\t\tc.server.SendAll(&msg)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package relay\n\nimport (\n\t\"encoding/gob\"\n\t\"encoding/json\"\n\t\"io\"\n)\n\n\n\n\ntype Serializer interface {\n\tContentType() string\n\tRelayEncode(io.Writer, interface{}) error\n\tRelayDecode(io.Reader, interface{}) error\n}\n\n\ntype GOBSerializer struct{}\n\nfunc (*GOBSerializer) ContentType() string {\n\treturn \"binary/gob\"\n}\nfunc (*GOBSerializer) RelayEncode(w io.Writer, e interface{}) error {\n\tenc := gob.NewEncoder(w)\n\treturn enc.Encode(e)\n}\n\n\n\ntype JSONSerializer struct{}\n\nfunc (*JSONSerializer) ContentType() string {\n\treturn \"text/json\"\n}\n\nfunc (*JSONSerializer) RelayEncode(w io.Writer, e interface{}) error {\n\tenc := json.NewEncoder(w)\n\treturn enc.Encode(e)\n}\n\nfunc (*JSONSerializer) RelayDecode(r io.Reader, o interface{}) error {\n\tdec := json.NewDecoder(r)\n\treturn dec.Decode(o)\n}\n\nfunc (*GOBSerializer) RelayDecode(r io.Reader, o interface{}) error ", "output": "{\n\tdec := gob.NewDecoder(r)\n\treturn dec.Decode(o)\n}"} {"input": "package iso20022\n\n\ntype Tax13 struct {\n\n\tType *TaxType9Code `xml:\"Tp\"`\n\n\tOtherTaxType *Max35Text `xml:\"OthrTaxTp\"`\n\n\tAmount *CurrencyAndAmount `xml:\"Amt\"`\n\n\tRate *PercentageRate `xml:\"Rate\"`\n}\n\nfunc (t *Tax13) SetType(value string) {\n\tt.Type = (*TaxType9Code)(&value)\n}\n\nfunc (t *Tax13) SetOtherTaxType(value string) {\n\tt.OtherTaxType = (*Max35Text)(&value)\n}\n\n\n\nfunc (t *Tax13) SetRate(value string) {\n\tt.Rate = (*PercentageRate)(&value)\n}\n\nfunc (t *Tax13) SetAmount(value, currency string) ", "output": "{\n\tt.Amount = NewCurrencyAndAmount(value, currency)\n}"} {"input": "package thrift\n\nimport \"context\"\n\ntype TClient interface {\n\tCall(ctx context.Context, method string, args, result TStruct) error\n}\n\n\n\nfunc (p *TStandardClient) Call(ctx context.Context, method string, args, result TStruct) error ", "output": "{\n\treturn p.call(method, args, result)\n}"} {"input": "package rule\n\nimport (\n\t\"go/ast\"\n\n\t\"github.com/mgechev/revive/lint\"\n)\n\n\ntype NestedStructs struct{}\n\n\nfunc (r *NestedStructs) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {\n\tvar failures []lint.Failure\n\n\tif len(arguments) > 0 {\n\t\tpanic(r.Name() + \" doesn't take any arguments\")\n\t}\n\n\twalker := &lintNestedStructs{\n\t\tfileAST: file.AST,\n\t\tonFailure: func(failure lint.Failure) {\n\t\t\tfailures = append(failures, failure)\n\t\t},\n\t}\n\n\tast.Walk(walker, file.AST)\n\n\treturn failures\n}\n\n\nfunc (r *NestedStructs) Name() string {\n\treturn \"nested-structs\"\n}\n\ntype lintNestedStructs struct {\n\tfileAST *ast.File\n\tonFailure func(lint.Failure)\n}\n\n\n\nfunc (l *lintNestedStructs) Visit(n ast.Node) ast.Visitor ", "output": "{\n\tswitch v := n.(type) {\n\tcase *ast.FuncDecl:\n\t\tif v.Body != nil {\n\t\t\tast.Walk(l, v.Body)\n\t\t}\n\t\treturn nil\n\tcase *ast.Field:\n\t\tif _, ok := v.Type.(*ast.StructType); ok {\n\t\t\tl.onFailure(lint.Failure{\n\t\t\t\tFailure: \"no nested structs are allowed\",\n\t\t\t\tCategory: \"style\",\n\t\t\t\tNode: v,\n\t\t\t\tConfidence: 1,\n\t\t\t})\n\t\t\tbreak\n\t\t}\n\t}\n\treturn l\n}"} {"input": "package errors\n\nimport (\n\t\"errors\"\n)\n\nconst callStackDepth = 10\n\ntype DetailError interface {\n\terror\n\tErrCoder\n\tCallStacker\n\tGetRoot() error\n}\n\n\nfunc NewErr(errmsg string) error {\n\treturn errors.New(errmsg)\n}\n\n\n\nfunc RootErr(err error) error {\n\tif err, ok := err.(DetailError); ok {\n\t\treturn err.GetRoot()\n\t}\n\treturn err\n}\n\nfunc NewDetailErr(err error,errcode ErrCode,errmsg string) DetailError", "output": "{\n\tif err == nil {return nil}\n\n\tdnaerr, ok := err.(dnaError)\n\tif !ok {\n\t\tdnaerr.root = err\n\t\tdnaerr.errmsg = err.Error()\n\t\tdnaerr.callstack = getCallStack(0, callStackDepth)\n\t\tdnaerr.code = errcode\n\n\t}\n\tif errmsg != \"\" {\n\t\tdnaerr.errmsg = errmsg + \": \" + dnaerr.errmsg\n\t}\n\n\n\treturn dnaerr\n}"} {"input": "package imagick\n\n\nimport \"C\"\nimport (\n\t\"runtime\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\nvar (\n\tinitOnce sync.Once\n\tterminateOnce *sync.Once\n\n\tcanTerminate = make(chan struct{}, 1)\n\n\tenvSemaphore = make(chan struct{}, 1)\n\n\tmagickWandCounter int64\n\tdrawingWandCounter int64\n\tpixelIteratorCounter int64\n\tpixelWandCounter int64\n)\n\n\nfunc Initialize() {\n\tenvSemaphore <- struct{}{}\n\tdefer func() {\n\t\t<-envSemaphore\n\t}()\n\n\tinitOnce.Do(func() {\n\t\tC.MagickWandGenesis()\n\t\tterminateOnce = &sync.Once{}\n\t\tsetCanTerminate()\n\t})\n}\n\n\n\n\n\n\n\nfunc terminate() {\n\t<-canTerminate\n\tC.MagickWandTerminus()\n\tinitOnce = sync.Once{}\n}\n\n\nfunc setCanTerminate() {\n\tif isImageMagickCleaned() {\n\t\tselect {\n\t\tcase canTerminate <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n}\n\n\nfunc unsetCanTerminate() {\n\tselect {\n\tcase <-canTerminate:\n\tdefault:\n\t}\n}\n\n\nfunc isImageMagickCleaned() bool {\n\tif atomic.LoadInt64(&magickWandCounter) != 0 || atomic.LoadInt64(&drawingWandCounter) != 0 || atomic.LoadInt64(&pixelIteratorCounter) != 0 || atomic.LoadInt64(&pixelWandCounter) != 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc Terminate() ", "output": "{\n\tenvSemaphore <- struct{}{}\n\tdefer func() {\n\t\t<-envSemaphore\n\t}()\n\n\tif terminateOnce != nil {\n\t\tterminateOnce.Do(func() {\n\t\t\truntime.GC()\n\t\t\tterminate()\n\t\t})\n\t}\n}"} {"input": "package debug\n\nimport \"github.com/jsimonetti/ldapserv/ldap\"\n\n\n\nfunc (d *DebugBackend) Bind(w ldap.ResponseWriter, m *ldap.Message) ", "output": "{\n\tr := m.GetBindRequest()\n\tdump(r)\n\tres := ldap.NewBindResponse(ldap.LDAPResultUnwillingToPerform)\n\tw.Write(res)\n}"} {"input": "package http\n\nimport (\n\t\"testing\"\n)\n\nfunc isChar(c rune) bool { return c <= 127 }\n\nfunc isCtl(c rune) bool { return c <= 31 || c == 127 }\n\nfunc isSeparator(c rune) bool {\n\tswitch c {\n\tcase '(', ')', '<', '>', '@', ',', ';', ':', '\\\\', '\"', '/', '[', ']', '?', '=', '{', '}', ' ', '\\t':\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc TestIsToken(t *testing.T) ", "output": "{\n\tfor i := 0; i <= 130; i++ {\n\t\tr := rune(i)\n\t\texpected := isChar(r) && !isCtl(r) && !isSeparator(r)\n\t\tif isToken(r) != expected {\n\t\t\tt.Errorf(\"isToken(0x%x) = %v\", r, !expected)\n\t\t}\n\t}\n}"} {"input": "package tmpl\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\t\"net/http\"\n)\n\n\ntype Page struct {\n\tTitle string\n\tBackLink string\n}\n\n\ntype Template struct {\n\ttemplates map[string]*template.Template\n\ttemplateData map[string]map[string]interface{}\n\ttemplateFilepath string\n}\n\n\nfunc New(templateFilepath string) *Template {\n\treturn &Template{\n\t\ttemplateFilepath: templateFilepath,\n\t\ttemplates: make(map[string]*template.Template),\n\t\ttemplateData: make(map[string]map[string]interface{}),\n\t}\n}\n\n\n\n\n\n\nfunc (self *Template) AddDataToTemplate(template, data_id string, data interface{}) error {\n\t_, ok := self.templateData[template]\n\tif !ok {\n\t\treturn fmt.Errorf(\"There is no template named '%s' registered.\", template)\n\t}\n\n\tself.templateData[template][data_id] = data\n\n\treturn nil\n}\n\n\n\n\n\nfunc (self *Template) RenderPage(w http.ResponseWriter, tmpl string, p *Page) {\n\tself.AddDataToTemplate(tmpl, \"Page\", p)\n\n\terr := self.templates[tmpl].Execute(w, self.templateData[tmpl])\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\nfunc (self *Template) AddTemplate(name string, templates ...string) ", "output": "{\n\tif len(templates) > 0 {\n\t\tfor i := 0; i < len(templates); i++ {\n\t\t\ttemplates[i] = self.templateFilepath + \"templates/\" + templates[i] + \".tpl\"\n\t\t}\n\t\tself.templates[name] = template.Must(template.ParseFiles(templates...))\n\t}\n\n\tself.templateData[name] = make(map[string]interface{})\n}"} {"input": "package internalversion\n\nimport (\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n)\n\n\n\ntype SubjectAccessReviewsGetter interface {\n\tSubjectAccessReviews() SubjectAccessReviewInterface\n}\n\n\ntype SubjectAccessReviewInterface interface {\n\tSubjectAccessReviewExpansion\n}\n\n\ntype subjectAccessReviews struct {\n\tclient restclient.Interface\n}\n\n\n\n\nfunc newSubjectAccessReviews(c *AuthorizationClient) *subjectAccessReviews ", "output": "{\n\treturn &subjectAccessReviews{\n\t\tclient: c.RESTClient(),\n\t}\n}"} {"input": "package util\n\nimport \"time\"\n\ntype WriteThrottler struct {\n\tcompactionBytePerSecond int64\n\tlastSizeCounter int64\n\tlastSizeCheckTime time.Time\n}\n\n\n\nfunc (wt *WriteThrottler) MaybeSlowdown(delta int64) {\n\tif wt.compactionBytePerSecond > 0 {\n\t\twt.lastSizeCounter += delta\n\t\tnow := time.Now()\n\t\telapsedDuration := now.Sub(wt.lastSizeCheckTime)\n\t\tif elapsedDuration > 100*time.Millisecond {\n\t\t\toverLimitBytes := wt.lastSizeCounter - wt.compactionBytePerSecond/10\n\t\t\tif overLimitBytes > 0 {\n\t\t\t\toverRatio := float64(overLimitBytes) / float64(wt.compactionBytePerSecond)\n\t\t\t\tsleepTime := time.Duration(overRatio*1000) * time.Millisecond\n\t\t\t\ttime.Sleep(sleepTime)\n\t\t\t}\n\t\t\twt.lastSizeCounter, wt.lastSizeCheckTime = 0, time.Now()\n\t\t}\n\t}\n}\n\nfunc NewWriteThrottler(bytesPerSecond int64) *WriteThrottler ", "output": "{\n\treturn &WriteThrottler{\n\t\tcompactionBytePerSecond: bytesPerSecond,\n\t\tlastSizeCheckTime: time.Now(),\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"text/template\"\n)\n\n\n\nfunc writeTemplateToFile(path string, t *template.Template, data interface{}) (string, error) {\n\tf, e := os.Create(path)\n\tif e != nil {\n\t\treturn \"\", e\n\t}\n\tdefer f.Close()\n\n\te = t.Execute(f, data)\n\tif e != nil {\n\t\treturn \"\", e\n\t}\n\n\treturn f.Name(), nil\n}\n\n\n\nfunc copyFile(dst, src string) (int64, error) ", "output": "{\n\tsf, err := os.Open(src)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer sf.Close()\n\n\tdf, err := os.Create(dst)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer df.Close()\n\n\treturn io.Copy(df, sf)\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/Bluek404/gohtml/example/tpl\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", hello)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\n\n\nfunc hello(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tw.Write(tpl.Index(r.URL.Path[1:]))\n}"} {"input": "package git\n\nimport (\n\t\"sync\"\n\n\t\"github.com/mholt/caddy/middleware/git/gitos\"\n)\n\n\n\ntype repoService struct {\n\trepo *Repo\n\tticker gitos.Ticker \n\thalt chan struct{} \n}\n\n\nfunc Start(repo *Repo) {\n\tservice := &repoService{\n\t\trepo,\n\t\tgos.NewTicker(repo.Interval),\n\t\tmake(chan struct{}),\n\t}\n\tgo func(s *repoService) {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-s.ticker.C():\n\t\t\t\terr := repo.Pull()\n\t\t\t\tif err != nil {\n\t\t\t\t\tLogger().Println(err)\n\t\t\t\t}\n\t\t\tcase <-s.halt:\n\t\t\t\ts.ticker.Stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(service)\n\n\tServices.add(service)\n}\n\n\ntype services struct {\n\tservices []*repoService\n\tsync.Mutex\n}\n\n\nfunc (s *services) add(r *repoService) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.services = append(s.services, r)\n}\n\n\n\n\n\n\n\nfunc (s *services) Stop(repoURL string, limit int) ", "output": "{\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tfor i, j := 0, 0; i < len(s.services) && ((limit >= 0 && j < limit) || limit < 0); i++ {\n\t\tservice := s.services[i]\n\t\tif service.repo.URL == repoURL {\n\t\t\tservice.halt <- struct{}{}\n\t\t\ts.services[i] = nil\n\t\t\tj++\n\t\t}\n\t}\n\n\tservices := s.services[:0]\n\tfor _, s := range s.services {\n\t\tif s != nil {\n\t\t\tservices = append(services, s)\n\t\t}\n\t}\n\ts.services = services\n}"} {"input": "package client\n\nimport (\n\t\"errors\"\n\t\"net\"\n)\n\n\n\nfunc newDirectQuicConn(c *Client, network, address string) (net.Conn, error) ", "output": "{\n\treturn nil, errors.New(\"quic unsupported\")\n}"} {"input": "package server\n\nimport (\n\t\"github.com/coreos/doozerd/consensus\"\n\t\"github.com/coreos/doozerd/store\"\n\t\"log\"\n\t\"net\"\n\t\"syscall\"\n)\n\n\n\n\n\nfunc serve(nc net.Conn, st *store.Store, p consensus.Proposer, w bool, rwsk, rosk string, self string) {\n\tc := &conn{\n\t\tc: nc,\n\t\taddr: nc.RemoteAddr().String(),\n\t\tst: st,\n\t\tp: p,\n\t\tcanWrite: w,\n\t\trwsk: rwsk,\n\t\trosk: rosk,\n\t\tself: self,\n\t}\n\n\tc.grant(\"\") \n\n\n\tc.serve()\n\tnc.Close()\n}\n\nfunc ListenAndServe(l net.Listener, canWrite chan bool, st *store.Store, p consensus.Proposer, rwsk, rosk string, self string) ", "output": "{\n\tvar w bool\n\tfor {\n\t\tc, err := l.Accept()\n\t\tif err != nil {\n\t\t\tif err == syscall.EINVAL {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif e, ok := err.(*net.OpError); ok && e.Err == syscall.EINVAL {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tselect {\n\t\tcase w = <-canWrite:\n\t\t\tcanWrite = nil\n\t\tdefault:\n\t\t}\n\n\t\tgo serve(c, st, p, w, rwsk, rosk, self)\n\t}\n}"} {"input": "package chug_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestChug(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Chug Suite\")\n}"} {"input": "package header\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n\n\nfunc NoCache(c *gin.Context) {\n\tc.Header(\"Cache-Control\", \"no-cache, no-store, max-age=0, must-revalidate, value\")\n\tc.Header(\"Expires\", \"Thu, 01 Jan 1970 00:00:00 GMT\")\n\tc.Header(\"Last-Modified\", time.Now().UTC().Format(http.TimeFormat))\n\tc.Next()\n}\n\n\n\n\nfunc Options(c *gin.Context) {\n\tif c.Request.Method != \"OPTIONS\" {\n\t\tc.Next()\n\t} else {\n\t\tc.Header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tc.Header(\"Access-Control-Allow-Methods\", \"GET,POST,PUT,PATCH,DELETE,OPTIONS\")\n\t\tc.Header(\"Access-Control-Allow-Headers\", \"authorization, origin, content-type, accept\")\n\t\tc.Header(\"Allow\", \"HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS\")\n\t\tc.Header(\"Content-Type\", \"application/json\")\n\t\tc.AbortWithStatus(200)\n\t}\n}\n\n\n\n\n\nfunc Secure(c *gin.Context) ", "output": "{\n\tc.Header(\"Access-Control-Allow-Origin\", \"*\")\n\tc.Header(\"X-Frame-Options\", \"DENY\")\n\tc.Header(\"X-Content-Type-Options\", \"nosniff\")\n\tc.Header(\"X-XSS-Protection\", \"1; mode=block\")\n\tif c.Request.TLS != nil {\n\t\tc.Header(\"Strict-Transport-Security\", \"max-age=31536000\")\n\t}\n}"} {"input": "package eppgo\n\nimport \"fmt\"\n\nconst (\n\tErrorCodeRegisteringWrongType ErrorCode = iota\n\n\tErrorCodeUnknownElement\n)\n\n\ntype ErrorCode int\n\n\nfunc (e ErrorCode) String() string {\n\tswitch e {\n\tcase ErrorCodeRegisteringWrongType:\n\t\treturn \"registering wrong type\"\n\tcase ErrorCodeUnknownElement:\n\t\treturn \"unknown element found in the XML\"\n\t}\n\n\treturn \"\"\n}\n\n\n\ntype Error struct {\n\tCode ErrorCode\n\tReference string\n}\n\n\n\n\nfunc (e Error) Error() string ", "output": "{\n\tif e.Reference != \"\" {\n\t\treturn fmt.Sprintf(\"[eppgo] %s : %s\", e.Code, e.Reference)\n\t}\n\n\treturn fmt.Sprintf(\"[eppgo] %s\", e.Code)\n}"} {"input": "package gorever\n\nimport (\n\t\"fmt\"\n\t\"github.com/inconshreveable/go-update\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype Updater struct {\n\tnewVersion bool\n\tch chan bool\n}\n\n\n\nfunc (u *Updater) HasNewVersion() bool {\n\treturn u.newVersion\n}\n\nfunc (u *Updater) Update() error {\n\tu.newVersion = false\n\turl := \"http://localhost:8078/gorever-poc\" \n\treturn u.doUpdate(url)\n}\n\nfunc (u *Updater) doUpdate(url string) error {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\terr = update.Apply(resp.Body, update.Options{})\n\tif err != nil {\n\t\tif rerr := update.RollbackError(err); rerr != nil {\n\t\t\treturn fmt.Errorf(\"Failed to rollback from bad update: %v\", rerr)\n\t\t}\n\t}\n\treturn err\n}\n\nfunc NewUpdater(ch chan bool) (*Updater, error) ", "output": "{\n\tu := &Updater{\n\t\tnewVersion: true,\n\t\tch: ch,\n\t}\n\n\tgo func(updater *Updater) {\n\t\ttime.Sleep(6*time.Second)\n\t\tupdater.ch <- true\n\t}(u)\n\n\treturn u, nil\n}"} {"input": "package string_byte_array_converter\n\nimport (\n\t\"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/blevesearch/bleve/analysis\"\n\t\"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/blevesearch/bleve/registry\"\n)\n\ntype StringByteArrayConverter struct{}\n\nfunc NewStringByteArrayConverter() *StringByteArrayConverter {\n\treturn &StringByteArrayConverter{}\n}\n\nfunc (c *StringByteArrayConverter) Convert(in []byte) (interface{}, error) {\n\treturn string(in), nil\n}\n\nfunc Constructor(config map[string]interface{}, cache *registry.Cache) (analysis.ByteArrayConverter, error) {\n\treturn NewStringByteArrayConverter(), nil\n}\n\n\n\nfunc init() ", "output": "{\n\tregistry.RegisterByteArrayConverter(\"string\", Constructor)\n}"} {"input": "package main\n\nimport (\n \"os\"\n \"math\"\n \"errors\"\n \"fmt\"\n \"database/sql\"\n _ \"github.com/mattn/go-sqlite3\"\n)\n\n\ntype Location struct {\n lat float64\n long float64\n}\n\n\nfunc handleErrors(err error) {\n if err != nil {\n panic(err)\n }\n}\n\n\nfunc degreesToRadians(degrees float64) float64 {\n for degrees >= 360.0 {\n degrees -= 360\n }\n\n return degrees * (math.Pi / 180)\n}\n\n\n\n\n\n\nfunc getLocationFromPostcode(postcode string) Location {\n db, err := sql.Open(\"sqlite3\", \"./postcode.sl3\")\n handleErrors(err)\n defer db.Close()\n\n var location Location\n rows, err := db.Query(fmt.Sprintf(\"select lat, long from postcode where code='%s' limit 1\", postcode))\n rows.Next()\n handleErrors(rows.Scan(&location.lat, &location.long))\n\n return location\n}\n\n\nfunc distanceBetweenPostcodes(postcode0, postcode1 string) float64 {\n loc0 := getLocationFromPostcode(postcode0)\n loc1 := getLocationFromPostcode(postcode1)\n\n return haversineDistance(loc0, loc1)\n}\n\nfunc main() {\n if len(os.Args) != 3 {\n handleErrors(errors.New(\"Program takes two arguments, the two postcodes.\"))\n }\n\n postcode0 := os.Args[1]\n postcode1 := os.Args[2]\n\n distance := distanceBetweenPostcodes(postcode0, postcode1)\n distance_in_miles := distance / 1.609344\n\n fmt.Printf(\"The distance between postcodes %s and %s is %f km (%f mi).\", postcode0, postcode1, distance, distance_in_miles)\n}\n\nfunc haversineDistance(loc0 Location, loc1 Location) float64 ", "output": "{\n lat0 := degreesToRadians(loc0.lat)\n lat1 := degreesToRadians(loc1.lat)\n delta_lat := degreesToRadians(loc1.lat - loc0.lat)\n delta_long := degreesToRadians(loc1.long - loc0.long)\n r := 6365.079 \n\n return 2.0 * r * math.Asin(math.Sqrt(math.Pow(delta_lat / 2.0, 2.0) + math.Cos(lat1) * math.Cos(lat0) * math.Pow(delta_long / 2.0, 2.0)))\n}"} {"input": "package runtime\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype response struct {\n}\n\nfunc (r response) Code() int {\n\treturn 490\n}\nfunc (r response) Message() string {\n\treturn \"the message\"\n}\nfunc (r response) GetHeader(_ string) string {\n\treturn \"the header\"\n}\nfunc (r response) GetHeaders(_ string) []string {\n\treturn []string{\"the headers\", \"the headers2\"}\n}\n\n\nfunc TestResponseReaderFunc(t *testing.T) {\n\tvar actual struct {\n\t\tHeader, Message, Body string\n\t\tCode int\n\t}\n\treader := ClientResponseReaderFunc(func(r ClientResponse, _ Consumer) (interface{}, error) {\n\t\tb, _ := ioutil.ReadAll(r.Body())\n\t\tactual.Body = string(b)\n\t\tactual.Code = r.Code()\n\t\tactual.Message = r.Message()\n\t\tactual.Header = r.GetHeader(\"blah\")\n\t\treturn actual, nil\n\t})\n\t_, _ = reader.ReadResponse(response{}, nil)\n\tassert.Equal(t, \"the content\", actual.Body)\n\tassert.Equal(t, \"the message\", actual.Message)\n\tassert.Equal(t, \"the header\", actual.Header)\n\tassert.Equal(t, 490, actual.Code)\n}\n\nfunc (r response) Body() io.ReadCloser ", "output": "{\n\treturn ioutil.NopCloser(bytes.NewBufferString(\"the content\"))\n}"} {"input": "package fake\n\nimport (\n\tv1 \"github.com/gravitational/workshop/crd/controller/pkg/generated/clientset/versioned/typed/nginxcontroller/v1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeTrainingV1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeTrainingV1) Nginxes(namespace string) v1.NginxInterface {\n\treturn &FakeNginxes{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeTrainingV1) RESTClient() rest.Interface ", "output": "{\n\tvar ret *rest.RESTClient\n\treturn ret\n}"} {"input": "package resources\n\nimport (\n\t\"sort\"\n\n\t\"encoding/json\"\n\n\t\"github.com/mitchellh/mapstructure\"\n)\n\n\ntype AWSServerlessApplication_Location struct {\n\tString *string\n\n\tApplicationLocation *AWSServerlessApplication_ApplicationLocation\n}\n\n\n\nfunc (r AWSServerlessApplication_Location) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(r.value())\n}\n\n\nfunc (r *AWSServerlessApplication_Location) UnmarshalJSON(b []byte) error {\n\n\tvar typecheck interface{}\n\tif err := json.Unmarshal(b, &typecheck); err != nil {\n\t\treturn err\n\t}\n\n\tswitch val := typecheck.(type) {\n\n\tcase string:\n\t\tr.String = &val\n\n\tcase map[string]interface{}:\n\n\t\tmapstructure.Decode(val, &r.ApplicationLocation)\n\n\tcase []interface{}:\n\n\t}\n\n\treturn nil\n}\n\nfunc (r AWSServerlessApplication_Location) value() interface{} ", "output": "{\n\n\tif r.String != nil {\n\t\treturn r.String\n\t}\n\n\tret := []interface{}{}\n\n\tif r.ApplicationLocation != nil {\n\t\tret = append(ret, *r.ApplicationLocation)\n\t}\n\n\tsort.Sort(byJSONLength(ret))\n\tif len(ret) > 0 {\n\t\treturn ret[0]\n\t}\n\n\treturn nil\n\n}"} {"input": "package assertutil\n\n\n\ntype Checker struct {\n\tIsNil func(obtained interface{})\n\tFailNow func()\n}\n\n\nfunc NewChecker(failNow func()) *Checker {\n\treturn &Checker{\n\t\tFailNow: failNow,\n\t}\n}\n\n\n\n\nfunc (c *Checker) AssertNil(obtained interface{}) {\n\tif c.IsNil == nil {\n\t\tc.failNow()\n\t\treturn\n\t}\n\tc.IsNil(obtained)\n}\n\nfunc (c *Checker) failNow() ", "output": "{\n\tc.FailNow()\n}"} {"input": "package common\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/hashicorp/packer-plugin-sdk/multistep\"\n\tpackersdk \"github.com/hashicorp/packer-plugin-sdk/packer\"\n)\n\ntype StepRebootVm struct {\n}\n\n\n\nfunc (s *StepRebootVm) Cleanup(state multistep.StateBag) {\n}\n\nfunc (s *StepRebootVm) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction ", "output": "{\n\tdriver := state.Get(\"driver\").(Driver)\n\tui := state.Get(\"ui\").(packersdk.Ui)\n\n\terrorMsg := \"Error rebooting vm: %s\"\n\tvmName := state.Get(\"vmName\").(string)\n\n\tui.Say(\"Rebooting vm...\")\n\n\terr := driver.RestartVirtualMachine(vmName)\n\tif err != nil {\n\t\terr := fmt.Errorf(errorMsg, err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\tui.Say(\"Waiting the VM to complete rebooting (2 minutes)...\")\n\n\tsleepTime := time.Minute * 2\n\ttime.Sleep(sleepTime)\n\n\treturn multistep.ActionContinue\n}"} {"input": "package databus\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\n\t\"go-common/app/interface/main/app-show/conf\"\n\t\"go-common/library/log\"\n\t\"go-common/library/queue/databus\"\n)\n\n\ntype Dao struct {\n\tdataBus *databus.Databus\n}\n\n\n\nfunc (d *Dao) Pub(ctx context.Context, buvid, gt string, id, mid int64) (err error) {\n\tkey := strconv.FormatInt(mid, 10)\n\tmsg := struct {\n\t\tBuvid string `json:\"buvid\"`\n\t\tGoto string `json:\"goto\"`\n\t\tID int64 `json:\"id\"`\n\t\tMid int64 `json:\"mid\"`\n\t}{Buvid: buvid, Goto: gt, ID: id, Mid: mid}\n\tif err = d.dataBus.Send(ctx, key, msg); err != nil {\n\t\tlog.Error(\"d.dataBus.Pub(%s,%v) error (%v)\", key, msg, err)\n\t}\n\treturn\n}\n\nfunc New(c *conf.Config) (d *Dao) ", "output": "{\n\td = &Dao{\n\t\tdataBus: databus.New(c.DislikeDataBus),\n\t}\n\treturn\n}"} {"input": "package util\n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"testing\"\n)\n\n\n\nfunc TestKeepAliveLease(t *testing.T) {\n\t_, err := KeepAliveLease(context.Background(), \"\", \"\", \"\", -1)\n\tif err == nil {\n\t\tt.Fatalf(\"KeepAliveLease -1 failed\")\n\t}\n\n\t_, err = KeepAliveLease(context.Background(), \"\", \"\", \"\", 0)\n\tif err != nil {\n\t\tt.Fatalf(\"KeepAliveLease failed\")\n\t}\n}\n\nfunc TestHeartbeatUtil(t *testing.T) ", "output": "{\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tt.Fatalf(\"TestHeartbeatUtil failed\")\n\t\t}\n\t}()\n\tHeartbeatUtil(context.Background(), \"\", \"\", \"\")\n}"} {"input": "package protolog \n\nimport (\n\t\"os\"\n\n\t\"go.pedge.io/dlog\"\n\t\"go.pedge.io/protolog\"\n)\n\n\n\ntype logger struct {\n\tprotolog.Logger\n}\n\n\nfunc NewLogger(l protolog.Logger) dlog.Logger {\n\treturn &logger{l}\n}\n\nfunc (l *logger) Debug(args ...interface{}) {\n\tl.Debugln(args...)\n}\n\nfunc (l *logger) Info(args ...interface{}) {\n\tl.Infoln(args...)\n}\n\nfunc (l *logger) Warn(args ...interface{}) {\n\tl.Warnln(args...)\n}\n\nfunc (l *logger) Error(args ...interface{}) {\n\tl.Errorln(args...)\n}\n\nfunc (l *logger) Fatal(args ...interface{}) {\n\tl.Fatalln(args...)\n}\n\nfunc (l *logger) Panic(args ...interface{}) {\n\tl.Panicln(args...)\n}\n\nfunc (l *logger) Print(args ...interface{}) {\n\tl.Println(args...)\n}\n\nfunc init() ", "output": "{\n\tdlog.SetLogger(NewLogger(protolog.NewStandardLogger(protolog.NewFileFlusher(os.Stderr))))\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"net/http\"\n)\n\n\n\nfunc GetAllStats(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"statistics go here\"})\n}\n\nfunc GetAllImages(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"all images go here\"})\n}\n\nfunc GetImage(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"one image goes here\"})\n}\n\nfunc CreateImage(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"ID of the image we created goes here\"})\n}\n\nfunc UpdateImage(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"ID of the image we updated goes here\"})\n}\n\nfunc PingHandler(c *gin.Context) ", "output": "{\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"PONG!\"})\n}"} {"input": "package closure\n\nimport (\n\t\"fmt\"\n)\n\nfunc wrapper() func() int {\n\tx := 0\n\n\tincrement := func() int {\n\t\tx++ \n\t\treturn x\n\t}\n\treturn increment\n}\n\nfunc bye() {\n\tfmt.Println(\"good bye\")\n}\n\n\n\nfunc IncrementTest() ", "output": "{\n\tdefer bye() \n\tincrementer := wrapper()\n\tfmt.Println(incrementer())\n\tfmt.Println(incrementer())\n}"} {"input": "package allocdir\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\thclog \"github.com/hashicorp/go-hclog\"\n\ttesting \"github.com/mitchellh/go-testing-interface\"\n)\n\n\n\n\n\nfunc TestAllocDir(t testing.T, l hclog.Logger, prefix, id string) (*AllocDir, func()) ", "output": "{\n\tdir, err := ioutil.TempDir(\"\", prefix)\n\tif err != nil {\n\t\tt.Fatalf(\"Couldn't create temp dir: %v\", err)\n\t}\n\n\tallocDir := NewAllocDir(l, dir, id)\n\n\tcleanup := func() {\n\t\tif err := os.RemoveAll(dir); err != nil {\n\t\t\tt.Logf(\"error cleaning up alloc dir %q: %v\", prefix, err)\n\t\t}\n\n\t\tif err := allocDir.Destroy(); err != nil {\n\t\t\tt.Logf(\"error cleaning up alloc dir %q: %v\", prefix, err)\n\t\t}\n\t}\n\n\tif err := allocDir.Build(); err != nil {\n\t\tcleanup()\n\t\tt.Fatalf(\"error building alloc dir %q: %v\", prefix, err)\n\t}\n\n\treturn allocDir, cleanup\n}"} {"input": "package password\n\n\nvar _ PasswordGenerator = (*mockGenerator)(nil)\n\ntype mockGenerator struct {\n\tresult string\n\terr error\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (g *mockGenerator) Generate(int, int, int, bool, bool) (string, error) {\n\tif g.err != nil {\n\t\treturn \"\", g.err\n\t}\n\treturn g.result, nil\n}\n\n\nfunc (g *mockGenerator) MustGenerate(int, int, int, bool, bool) string {\n\tif g.err != nil {\n\t\tpanic(g.err)\n\t}\n\treturn g.result\n}\n\nfunc NewMockGenerator(result string, err error) *mockGenerator ", "output": "{\n\treturn &mockGenerator{\n\t\tresult: result,\n\t\terr: err,\n\t}\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/apier/v1\"\n\t\"github.com/cgrates/cgrates/engine\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdGetDataCost{\n\t\tname: \"datacost\",\n\t\trpcMethod: \"ApierV1.GetDataCost\",\n\t\tclientArgs: []string{\"Direction\", \"Category\", \"Tenant\", \"Account\", \"Subject\", \"StartTime\", \"Usage\"},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetDataCost struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrGetDataCost\n\tclientArgs []string\n\t*CommandExecuter\n}\n\n\n\nfunc (self *CmdGetDataCost) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdGetDataCost) RpcParams() interface{} {\n\tif self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrGetDataCost{Direction: utils.OUT}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetDataCost) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetDataCost) RpcResult() interface{} {\n\treturn &engine.DataCost{}\n}\n\nfunc (self *CmdGetDataCost) ClientArgs() []string {\n\treturn self.clientArgs\n}\n\nfunc (self *CmdGetDataCost) Name() string ", "output": "{\n\treturn self.name\n}"} {"input": "package service\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"go-common/app/service/main/assist/conf\"\n\t\"go-common/app/service/main/assist/dao/account\"\n\t\"go-common/app/service/main/assist/dao/assist\"\n\t\"go-common/app/service/main/assist/dao/message\"\n\t\"go-common/library/log\"\n\t\"go-common/library/queue/databus\"\n)\n\n\ntype Service struct {\n\tc *conf.Config\n\tass *assist.Dao\n\tacc *account.Dao\n\tmsg *message.Dao\n\trelationSub *databus.Databus\n\tcacheChan chan func()\n\twg sync.WaitGroup\n}\n\n\nfunc New(c *conf.Config) *Service {\n\ts := &Service{\n\t\tc: c,\n\t\tass: assist.New(c),\n\t\tacc: account.New(c),\n\t\tmsg: message.New(c),\n\t\tcacheChan: make(chan func(), 1024),\n\t\trelationSub: databus.New(c.RelationSub),\n\t}\n\ts.wg.Add(1)\n\tgo s.relationConsumer()\n\ts.wg.Add(1)\n\tgo s.cacheproc()\n\treturn s\n}\n\n\n\n\n\nfunc (s *Service) asyncCache(f func()) {\n\tselect {\n\tcase s.cacheChan <- f:\n\tdefault:\n\t\tlog.Warn(\"assist cacheproc chan full\")\n\t}\n}\n\n\nfunc (s *Service) cacheproc() {\n\tfor {\n\t\tf := <-s.cacheChan\n\t\tf()\n\t}\n}\n\n\nfunc (s *Service) Close() {\n\ts.relationSub.Close()\n\ts.wg.Wait()\n}\n\nfunc (s *Service) Ping(c context.Context) (err error) ", "output": "{\n\tif err = s.ass.Ping(c); err != nil {\n\t\tlog.Error(\"s.ass.Dao.Ping err(%v)\", err)\n\t}\n\treturn\n}"} {"input": "package libproxy\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\ntype UnixProxy struct {\n\tlistener net.Listener\n\tfrontendAddr net.Addr\n\tbackendAddr *net.UnixAddr\n}\n\n\nfunc NewUnixProxy(listener net.Listener, backendAddr *net.UnixAddr) (*UnixProxy, error) {\n\tlog.Printf(\"NewUnixProxy from %s -> %s\\n\", listener.Addr().String(), backendAddr.String())\n\treturn &UnixProxy{\n\t\tlistener: listener,\n\t\tfrontendAddr: listener.Addr(),\n\t\tbackendAddr: backendAddr,\n\t}, nil\n}\n\n\n\n\n\nfunc (proxy *UnixProxy) Run() {\n\tquit := make(chan struct{})\n\tdefer close(quit)\n\tfor {\n\t\tclient, err := proxy.listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Stopping proxy on unix/%v for unix/%v (%s)\", proxy.frontendAddr, proxy.backendAddr, err)\n\t\t\treturn\n\t\t}\n\t\tgo HandleUnixConnection(client.(Conn), proxy.backendAddr, quit)\n\t}\n}\n\n\nfunc (proxy *UnixProxy) Close() { proxy.listener.Close() }\n\n\nfunc (proxy *UnixProxy) FrontendAddr() net.Addr { return proxy.frontendAddr }\n\n\nfunc (proxy *UnixProxy) BackendAddr() net.Addr { return proxy.backendAddr }\n\nfunc HandleUnixConnection(client Conn, backendAddr *net.UnixAddr, quit <-chan struct{}) error ", "output": "{\n\tstart := time.Now()\n\tfor {\n\t\tbackend, err := net.DialUnix(\"unix\", nil, backendAddr)\n\t\tif err != nil {\n\t\t\tif errIsConnectionRefused(err) {\n\t\t\t\tif time.Since(start) > 120*time.Second {\n\t\t\t\t\tlog.Errorf(\"failed to connect to %s after 120s. The server appears to be down.\", backendAddr.String())\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlog.Infof(\"%s appears to not be started yet: will retry in 5s\", backendAddr.String())\n\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"can't forward traffic to backend unix/%v: %s\", backendAddr, err)\n\t\t}\n\t\treturn ProxyStream(client, backend, quit)\n\t}\n}"} {"input": "package overview\n\nimport (\n\t\"appengine\"\n\n\th \"github.com/czertbytes/pocket/pkg/http\"\n\tt \"github.com/czertbytes/pocket/pkg/types\"\n)\n\ntype Notificator struct {\n\tAppEngineContext appengine.Context\n\tRequestContext *h.RequestContext\n}\n\nfunc NewNotificator(RequestContext *h.RequestContext) *Notificator {\n\treturn &Notificator{\n\t\tAppEngineContext: RequestContext.AppEngineContext,\n\t\tRequestContext: RequestContext,\n\t}\n}\n\n\n\nfunc (self *Notificator) Update(overview *t.Overview) error {\n\treturn nil\n}\n\nfunc (self *Notificator) CreatePayment(payment *t.Payment) error {\n\treturn nil\n}\n\nfunc (self *Notificator) CreateParticipant(participant *t.User) error {\n\treturn nil\n}\n\nfunc (self *Notificator) Create(overview *t.Overview) error ", "output": "{\n\treturn nil\n}"} {"input": "package circonusgometrics\n\nimport (\n\t\"sync\"\n\n\t\"github.com/circonus-labs/circonusllhist\"\n)\n\n\ntype Histogram struct {\n\tname string\n\thist *circonusllhist.Histogram\n\trw sync.RWMutex\n}\n\n\nfunc (m *CirconusMetrics) Timing(metric string, val float64) {\n\tm.SetHistogramValue(metric, val)\n}\n\n\nfunc (m *CirconusMetrics) RecordValue(metric string, val float64) {\n\tm.SetHistogramValue(metric, val)\n}\n\n\n\n\n\nfunc (m *CirconusMetrics) RemoveHistogram(metric string) {\n\tm.hm.Lock()\n\tdefer m.hm.Unlock()\n\tdelete(m.histograms, metric)\n}\n\n\nfunc (m *CirconusMetrics) NewHistogram(metric string) *Histogram {\n\tm.hm.Lock()\n\tdefer m.hm.Unlock()\n\n\tif hist, ok := m.histograms[metric]; ok {\n\t\treturn hist\n\t}\n\n\thist := &Histogram{\n\t\tname: metric,\n\t\thist: circonusllhist.New(),\n\t}\n\n\tm.histograms[metric] = hist\n\n\treturn hist\n}\n\n\nfunc (h *Histogram) Name() string {\n\treturn h.name\n}\n\n\nfunc (h *Histogram) RecordValue(v float64) {\n\th.rw.Lock()\n\tdefer h.rw.Unlock()\n\n\th.hist.RecordValue(v)\n}\n\nfunc (m *CirconusMetrics) SetHistogramValue(metric string, val float64) ", "output": "{\n\tm.NewHistogram(metric)\n\n\tm.histograms[metric].rw.Lock()\n\tdefer m.histograms[metric].rw.Unlock()\n\n\tm.histograms[metric].hist.RecordValue(val)\n}"} {"input": "package fifo\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\n\n\n\nfunc CreateAndRead(path string) (func() (io.ReadCloser, error), error) {\n\tif err := mkfifo(path, 0600); err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating fifo %v: %v\", path, err)\n\t}\n\n\treturn func() (io.ReadCloser, error) {\n\t\treturn OpenReader(path)\n\t}, nil\n}\n\nfunc OpenReader(path string) (io.ReadCloser, error) {\n\treturn os.OpenFile(path, unix.O_RDONLY, os.ModeNamedPipe)\n}\n\n\nfunc OpenWriter(path string) (io.WriteCloser, error) {\n\treturn os.OpenFile(path, unix.O_WRONLY, os.ModeNamedPipe)\n}\n\n\nfunc Remove(path string) error {\n\treturn os.Remove(path)\n}\n\nfunc IsClosedErr(err error) bool {\n\terr2, ok := err.(*os.PathError)\n\tif ok {\n\t\treturn err2.Err == os.ErrClosed\n\t}\n\treturn false\n}\n\n\n\nfunc mkfifo(path string, mode uint32) (err error) ", "output": "{\n\treturn unix.Mkfifo(path, mode)\n}"} {"input": "package matn\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\ter \"../error\"\n)\n\n\n\nfunc TestTextIndexSet(t *testing.T) ", "output": "{\n\ttype args struct {\n\t\treq *TextIndexSetReq\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twantErr *er.Error\n\t}{\n\t\t{\n\t\t\tname: \"test1\",\n\t\t\targs: args{\n\t\t\t\treq: &TextIndexSetReq{\n\t\t\t\t\tText: \"test is best\",\n\t\t\t\t},\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif gotErr := TextIndexSet(tt.args.req); !reflect.DeepEqual(gotErr, tt.wantErr) {\n\t\t\t\tt.Errorf(\"TextIndexSet() = %v, want %v\", gotErr, tt.wantErr)\n\t\t\t}\n\t\t})\n\t}\n}"} {"input": "package main\n\nimport \"github.com/gin-gonic/gin\"\n\nfunc setupStatic(router *gin.Engine) {\n router.Static(\"/css\", STATIC_DIR + \"css\")\n router.Static(\"/js\", STATIC_DIR + \"js\")\n router.LoadHTMLGlob(STATIC_DIR + \"tpl/*.tpl\")\n}\n\n\n\nfunc main() {\n cache := NewSiteUsersCache()\n\n router := gin.Default()\n setupStatic(router)\n setupPages(router, cache)\n\n router.Run(\":8080\")\n}\n\nfunc setupPages(router *gin.Engine, cache *SiteUsersCache) ", "output": "{\n router.GET(\"/life\", GetRenderLifeGamePage)\n router.GET(\"/form\", GetRenderFormPage)\n router.POST(\"/form_ajax\", func(ctx *gin.Context) {\n PostRenderFormPage(ctx, cache)\n })\n router.GET(\"/calc\", GetRenderCalcPage)\n router.POST(\"/calc_ajax\", func(ctx *gin.Context) {\n PostRenderCalcPage(ctx, cache)\n })\n}"} {"input": "package cron\n\nimport (\n\t\"time\"\n\n\tuser_model \"code.gitea.io/gitea/models/user\"\n\n\t\"github.com/unknwon/i18n\"\n)\n\n\ntype Config interface {\n\tIsEnabled() bool\n\tDoRunAtStart() bool\n\tGetSchedule() string\n\tFormatMessage(name, status string, doer *user_model.User, args ...interface{}) string\n\tDoNoticeOnSuccess() bool\n}\n\n\ntype BaseConfig struct {\n\tEnabled bool\n\tRunAtStart bool\n\tSchedule string\n\tNoSuccessNotice bool\n}\n\n\ntype OlderThanConfig struct {\n\tBaseConfig\n\tOlderThan time.Duration\n}\n\n\ntype UpdateExistingConfig struct {\n\tBaseConfig\n\tUpdateExisting bool\n}\n\n\ntype CleanupHookTaskConfig struct {\n\tBaseConfig\n\tCleanupType string\n\tOlderThan time.Duration\n\tNumberToKeep int\n}\n\n\nfunc (b *BaseConfig) GetSchedule() string {\n\treturn b.Schedule\n}\n\n\nfunc (b *BaseConfig) IsEnabled() bool {\n\treturn b.Enabled\n}\n\n\nfunc (b *BaseConfig) DoRunAtStart() bool {\n\treturn b.RunAtStart\n}\n\n\nfunc (b *BaseConfig) DoNoticeOnSuccess() bool {\n\treturn !b.NoSuccessNotice\n}\n\n\n\n\nfunc (b *BaseConfig) FormatMessage(name, status string, doer *user_model.User, args ...interface{}) string ", "output": "{\n\trealArgs := make([]interface{}, 0, len(args)+2)\n\trealArgs = append(realArgs, i18n.Tr(\"en-US\", \"admin.dashboard.\"+name))\n\tif doer == nil {\n\t\trealArgs = append(realArgs, \"(Cron)\")\n\t} else {\n\t\trealArgs = append(realArgs, doer.Name)\n\t}\n\tif len(args) > 0 {\n\t\trealArgs = append(realArgs, args...)\n\t}\n\tif doer == nil || (doer.ID == -1 && doer.Name == \"(Cron)\") {\n\t\treturn i18n.Tr(\"en-US\", \"admin.dashboard.cron.\"+status, realArgs...)\n\t}\n\treturn i18n.Tr(\"en-US\", \"admin.dashboard.task.\"+status, realArgs...)\n}"} {"input": "package trace\n\nimport (\n\t\"github.com/golang/groupcache/lru\"\n)\n\n\n\ntype lruMap struct {\n\tcacheKeys map[lru.Key]bool\n\tcache *lru.Cache\n\tdroppedCount int\n}\n\nfunc newLruMap(size int) *lruMap {\n\tlm := &lruMap{\n\t\tcacheKeys: make(map[lru.Key]bool),\n\t\tcache: lru.New(size),\n\t\tdroppedCount: 0,\n\t}\n\tlm.cache.OnEvicted = func(key lru.Key, value interface{}) {\n\t\tdelete(lm.cacheKeys, key)\n\t\tlm.droppedCount++\n\t}\n\treturn lm\n}\n\n\n\nfunc (lm lruMap) keys() []interface{} {\n\tkeys := []interface{}{}\n\tfor k := range lm.cacheKeys {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}\n\nfunc (lm *lruMap) add(key, value interface{}) {\n\tlm.cacheKeys[lru.Key(key)] = true\n\tlm.cache.Add(lru.Key(key), value)\n}\n\nfunc (lm *lruMap) get(key interface{}) (interface{}, bool) {\n\treturn lm.cache.Get(key)\n}\n\nfunc (lm lruMap) len() int ", "output": "{\n\treturn lm.cache.Len()\n}"} {"input": "package fake_filter_provider\n\nimport (\n\t\"sync\"\n\n\t\"code.cloudfoundry.org/garden-linux/network\"\n\t\"code.cloudfoundry.org/garden-linux/resource_pool\"\n)\n\ntype FakeFilterProvider struct {\n\tProvideFilterStub func(containerId string) network.Filter\n\tprovideFilterMutex sync.RWMutex\n\tprovideFilterArgsForCall []struct {\n\t\tcontainerId string\n\t}\n\tprovideFilterReturns struct {\n\t\tresult1 network.Filter\n\t}\n}\n\nfunc (fake *FakeFilterProvider) ProvideFilter(containerId string) network.Filter {\n\tfake.provideFilterMutex.Lock()\n\tfake.provideFilterArgsForCall = append(fake.provideFilterArgsForCall, struct {\n\t\tcontainerId string\n\t}{containerId})\n\tfake.provideFilterMutex.Unlock()\n\tif fake.ProvideFilterStub != nil {\n\t\treturn fake.ProvideFilterStub(containerId)\n\t} else {\n\t\treturn fake.provideFilterReturns.result1\n\t}\n}\n\n\n\nfunc (fake *FakeFilterProvider) ProvideFilterArgsForCall(i int) string {\n\tfake.provideFilterMutex.RLock()\n\tdefer fake.provideFilterMutex.RUnlock()\n\treturn fake.provideFilterArgsForCall[i].containerId\n}\n\nfunc (fake *FakeFilterProvider) ProvideFilterReturns(result1 network.Filter) {\n\tfake.ProvideFilterStub = nil\n\tfake.provideFilterReturns = struct {\n\t\tresult1 network.Filter\n\t}{result1}\n}\n\nvar _ resource_pool.FilterProvider = new(FakeFilterProvider)\n\nfunc (fake *FakeFilterProvider) ProvideFilterCallCount() int ", "output": "{\n\tfake.provideFilterMutex.RLock()\n\tdefer fake.provideFilterMutex.RUnlock()\n\treturn len(fake.provideFilterArgsForCall)\n}"} {"input": "package data\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\n\ntype Art struct {\n\tID int\n\tFileSize int64 `db:\"file_size\"`\n\tFileName string `db:\"file_name\"`\n\tLastModified int64 `db:\"last_modified\"`\n}\n\n\nfunc (a *Art) Delete() error {\n\treturn DB.DeleteArt(a)\n}\n\n\nfunc (a *Art) Load() error {\n\treturn DB.LoadArt(a)\n}\n\n\n\n\n\nfunc (a Art) Stream() (io.ReadSeeker, error) {\n\treturn os.Open(a.FileName)\n}\n\nfunc (a *Art) Save() error ", "output": "{\n\treturn DB.SaveArt(a)\n}"} {"input": "package engine\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestJobOK(t *testing.T) {\n\teng := New()\n\teng.Register(\"return_ok\", func(job *Job) error { return nil })\n\terr := eng.Job(\"return_ok\").Run()\n\tif err != nil {\n\t\tt.Fatalf(\"Expected: err=%v\\nReceived: err=%v\", nil, err)\n\t}\n}\n\nfunc TestJobErr(t *testing.T) {\n\teng := New()\n\teng.Register(\"return_err\", func(job *Job) error { return errors.New(\"return_err\") })\n\terr := eng.Job(\"return_err\").Run()\n\tif err == nil {\n\t\tt.Fatalf(\"When a job returns error, Run() should return an error\")\n\t}\n}\n\n\n\nfunc TestJobStdoutString(t *testing.T) ", "output": "{\n\teng := New()\n\teng.Register(\"say_something_in_stdout\", func(job *Job) error {\n\t\tjob.Printf(\"Hello world\\n\")\n\t\treturn nil\n\t})\n\n\tjob := eng.Job(\"say_something_in_stdout\")\n\tvar outputBuffer = bytes.NewBuffer(nil)\n\tjob.Stdout.Add(outputBuffer)\n\tif err := job.Run(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfmt.Println(outputBuffer)\n\tvar output = Tail(outputBuffer, 1)\n\tif expectedOutput := \"Hello world\"; output != expectedOutput {\n\t\tt.Fatalf(\"Stdout last line:\\nExpected: %v\\nReceived: %v\", expectedOutput, output)\n\t}\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype OpenpitrixRepoEvent struct {\n\n\tCreateTime strfmt.DateTime `json:\"create_time,omitempty\"`\n\n\tOwner string `json:\"owner,omitempty\"`\n\n\tOwnerPath string `json:\"owner_path,omitempty\"`\n\n\tRepoEventID string `json:\"repo_event_id,omitempty\"`\n\n\tRepoID string `json:\"repo_id,omitempty\"`\n\n\tResult string `json:\"result,omitempty\"`\n\n\tStatus string `json:\"status,omitempty\"`\n\n\tStatusTime strfmt.DateTime `json:\"status_time,omitempty\"`\n}\n\n\nfunc (m *OpenpitrixRepoEvent) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (m *OpenpitrixRepoEvent) UnmarshalBinary(b []byte) error {\n\tvar res OpenpitrixRepoEvent\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *OpenpitrixRepoEvent) MarshalBinary() ([]byte, error) ", "output": "{\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}"} {"input": "package localcommand\n\nimport (\n\t\"syscall\"\n\t\"time\"\n)\n\ntype Option func(*LocalCommand)\n\n\n\nfunc WithCloseTimeout(timeout time.Duration) Option {\n\treturn func(lcmd *LocalCommand) {\n\t\tlcmd.closeTimeout = timeout\n\t}\n}\n\nfunc WithCloseSignal(signal syscall.Signal) Option ", "output": "{\n\treturn func(lcmd *LocalCommand) {\n\t\tlcmd.closeSignal = signal\n\t}\n}"} {"input": "package leetcode\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc Test_countAndSay(t *testing.T) ", "output": "{\n\ts4 := countAndSay(4)\n\tif s4 != \"1211\" {\n\t\tt.Error(s4, \"1211\")\n\t}\n\n\ts5 := countAndSay(5)\n\tif s5 != \"111221\" {\n\t\tt.Error(s5, \"111221\")\n\t}\n\n\ts8 := countAndSay(8)\n\tif s8 != \"1113213211\" {\n\t\tt.Error(s8, \"1113213211\")\n\t}\n}"} {"input": "package bunyan\n\nimport \"os\"\n\n\n\ntype Sink interface {\n\tWrite(record Record) error\n}\n\ntype funcSink struct {\n\twrite func(record Record) error\n}\n\nfunc (sink *funcSink) Write(record Record) error {\n\treturn sink.write(record)\n}\n\n\n\nfunc SinkFunc(write func(record Record) error) Sink {\n\treturn &funcSink{write}\n}\n\n\n\nfunc NilSink() Sink {\n\treturn SinkFunc(func(record Record) error {\n\t\treturn nil \n\t})\n}\n\nfunc InfoSink(target Sink, info Info) Sink {\n\treturn SinkFunc(func(record Record) error {\n\t\trecord.SetIfNot(info.Key(), info.Value())\n\t\treturn target.Write(record)\n\t})\n}\n\n\nfunc StdoutSink() Sink {\n\treturn NewJsonSink(os.Stdout)\n}\n\n\n\n\nfunc FileSink(path string) Sink ", "output": "{\n\tconst flags = os.O_CREATE | os.O_APPEND | os.O_WRONLY\n\tfile, e := os.OpenFile(path, flags, 0666)\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\n\treturn NewJsonSink(file)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSSecretsManagerRotationSchedule_RotationRules struct {\n\n\tAutomaticallyAfterDays int `json:\"AutomaticallyAfterDays,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) AWSCloudFormationType() string {\n\treturn \"AWS::SecretsManager::RotationSchedule.RotationRules\"\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\n\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) SetDependsOn(dependencies []string) ", "output": "{\n\tr._dependsOn = dependencies\n}"} {"input": "package fakes\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org/route-registrar/commandrunner\"\n\t\"code.cloudfoundry.org/route-registrar/healthchecker\"\n)\n\ntype FakeHealthChecker struct {\n\tCheckStub func(runner commandrunner.Runner, scriptPath string, timeout time.Duration) (bool, error)\n\tcheckMutex sync.RWMutex\n\tcheckArgsForCall []struct {\n\t\trunner commandrunner.Runner\n\t\tscriptPath string\n\t\ttimeout time.Duration\n\t}\n\tcheckReturns struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}\n}\n\nfunc (fake *FakeHealthChecker) Check(runner commandrunner.Runner, scriptPath string, timeout time.Duration) (bool, error) {\n\tfake.checkMutex.Lock()\n\tfake.checkArgsForCall = append(fake.checkArgsForCall, struct {\n\t\trunner commandrunner.Runner\n\t\tscriptPath string\n\t\ttimeout time.Duration\n\t}{runner, scriptPath, timeout})\n\tfake.checkMutex.Unlock()\n\tif fake.CheckStub != nil {\n\t\treturn fake.CheckStub(runner, scriptPath, timeout)\n\t} else {\n\t\treturn fake.checkReturns.result1, fake.checkReturns.result2\n\t}\n}\n\n\n\nfunc (fake *FakeHealthChecker) CheckArgsForCall(i int) (commandrunner.Runner, string, time.Duration) {\n\tfake.checkMutex.RLock()\n\tdefer fake.checkMutex.RUnlock()\n\treturn fake.checkArgsForCall[i].runner, fake.checkArgsForCall[i].scriptPath, fake.checkArgsForCall[i].timeout\n}\n\nfunc (fake *FakeHealthChecker) CheckReturns(result1 bool, result2 error) {\n\tfake.CheckStub = nil\n\tfake.checkReturns = struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nvar _ healthchecker.HealthChecker = new(FakeHealthChecker)\n\nfunc (fake *FakeHealthChecker) CheckCallCount() int ", "output": "{\n\tfake.checkMutex.RLock()\n\tdefer fake.checkMutex.RUnlock()\n\treturn len(fake.checkArgsForCall)\n}"} {"input": "package config\n\nimport \"testing\"\n\nconst (\n\ttestCollectionsJSON = `[{\"type\":\"array\", \"key\":\"key1\", \"prompt\":\"prompt\", \"properties\":[{\"key\":\"key\", \"type\":\"alnum\", \"min\":1, \"max\":22}]}]`\n\ttestCollectionJSON = `{\"type\":\"map\", \"key\":\"key1\", \"prompt\":\"prompt\",\"properties\":[{\"key\":\"key\", \"type\":\"alnum\", \"min\":1, \"max\":22}]}`\n)\n\n\n\nfunc TestCollection(t *testing.T) {\n\tt.Parallel()\n\tc, err := NewCollection([]byte(testCollectionJSON))\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tif c.Type != \"map\" {\n\t\tt.Errorf(\"incorrect Type value parsing (expected map and take %s)\", c.Type)\n\t\treturn\n\t}\n\tif len(c.Properties) != 1 {\n\t\tt.Errorf(\"properties array should contains 1 element (and it have %d)\", len(c.Properties))\n\t\treturn\n\t}\n}\n\nfunc TestCollections(t *testing.T) ", "output": "{\n\tt.Parallel()\n\tc, err := NewCollections([]byte(testCollectionsJSON))\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tif len(c) != 1 {\n\t\tt.Errorf(\"modules array should contains 1 element (and it have %d)\", len(c))\n\t\treturn\n\t}\n\tif c[0].Type != \"array\" {\n\t\tt.Errorf(\"wrong Type value (expected array and take %s)\", c[0].Type)\n\t\treturn\n\t}\n\tif len(c[0].Properties) != 1 {\n\t\tt.Errorf(\"properties array should contains 1 element (and it have %d)\", len(c[0].Properties))\n\t\treturn\n\t}\n}"} {"input": "package markdown\n\nimport (\n\t\"bufio\"\n\t\"io\"\n)\n\ntype writer interface {\n\tWrite([]byte) (int, error)\n\tWriteByte(byte) error\n\tWriteString(string) (int, error)\n\tFlush() error\n}\n\ntype monadicWriter struct {\n\twriter\n\terr error\n}\n\n\n\nfunc (w *monadicWriter) Write(p []byte) (n int, err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\tn, err = w.writer.Write(p)\n\tw.err = err\n\treturn\n}\n\nfunc (w *monadicWriter) WriteByte(b byte) (err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\terr = w.writer.WriteByte(b)\n\tw.err = err\n\treturn\n}\n\nfunc (w *monadicWriter) WriteString(s string) (n int, err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\tn, err = w.writer.WriteString(s)\n\tw.err = err\n\treturn\n}\n\nfunc (w *monadicWriter) Flush() (err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\terr = w.writer.Flush()\n\tw.err = err\n\treturn\n}\n\nfunc newMonadicWriter(w io.Writer) *monadicWriter ", "output": "{\n\tif w, ok := w.(writer); ok {\n\t\treturn &monadicWriter{writer: w}\n\t}\n\treturn &monadicWriter{writer: bufio.NewWriter(w)}\n}"} {"input": "package provider\n\nimport (\n\t\"time\"\n\t\"fmt\"\n\t\"reflect\"\n)\n\n\ntype Error struct {\n\tValue error\n}\n\n\ntype Result struct {\n\tValue interface{}\n}\n\n\ntype Provider interface {\n\tInitialise(host string, params map[string][]string) (error)\n\tSet(name string, data interface{}, expiry time.Duration) (error)\n\tGet(name string) (*Result)\n}\n\n\n\nfunc (i *Result) String() (string, error) {\n\n\tval := i.Value\n\tswitch val := val.(type) {\n\tcase string:\n\t\treturn val, nil\n\tcase []byte:\n\t\treturn string(val), nil\n\tcase nil:\n\t\treturn \"\", nil\n\tcase Error:\n\t\treturn \"\", val.Value\n\t}\n\treturn \"\", fmt.Errorf(\"cache::provider: unable to convert %v to string\", reflect.TypeOf(val))\n}\n\n\n\n\n\nfunc (i *Result) Bytes() ([]byte, error) ", "output": "{\n\n\tval := i.Value\n\tswitch val := val.(type) {\n\tcase string:\n\t\treturn []byte(val), nil\n\tcase []byte:\n\t\treturn val, nil\n\tcase Error:\n\t\treturn nil, val.Value\n\t}\n\treturn nil, fmt.Errorf(\"cache::provider: unable to convert %v to []byte\", reflect.TypeOf(val))\n}"} {"input": "package ratecounter\n\nimport \"time\"\n\n\n\ntype RateCounter struct {\n\tcounter Counter\n\tinterval time.Duration\n}\n\n\nfunc NewRateCounter(intrvl time.Duration) *RateCounter {\n\treturn &RateCounter{\n\t\tinterval: intrvl,\n\t}\n}\n\n\nfunc (r *RateCounter) Incr(val int64) {\n\tr.counter.Incr(val)\n\tgo r.scheduleDecrement(val)\n}\n\nfunc (r *RateCounter) scheduleDecrement(amount int64) {\n\ttime.Sleep(r.interval)\n\tr.counter.Incr(-1 * amount)\n}\n\n\n\n\nfunc (r *RateCounter) Rate() int64 ", "output": "{\n\treturn r.counter.Value()\n}"} {"input": "package blend_test\n\nimport (\n\t\"image/color\"\n\t\"testing\"\n\n\t\"github.com/tv42/quobar/blend\"\n)\n\nvar (\n\twhite = color.RGBA{R: 255, G: 255, B: 255, A: 255}\n\tgreen = color.RGBA{R: 0, G: 255, B: 0, A: 255}\n\tyellow = color.RGBA{R: 255, G: 255, B: 0, A: 255}\n\tred = color.RGBA{R: 255, G: 0, B: 0, A: 255}\n)\n\nvar trafficLights = []blend.Threshold{\n\t{\n\t\tMax: 1024,\n\t\tColor: white,\n\t},\n\t{\n\t\tMax: 768,\n\t\tColor: green,\n\t},\n\t{\n\t\tMax: 512,\n\t\tColor: yellow,\n\t},\n\t{\n\t\tMax: 256,\n\t\tColor: red,\n\t},\n}\n\n\n\nfunc TestPickColorEmpty(t *testing.T) {\n\tif g, e := blend.PickColor(nil, 42), color.Black; g != e {\n\t\tt.Errorf(\"wrong color for empty slice: %v != %v\", g, e)\n\t}\n}\n\nfunc TestPickColorKnown(t *testing.T) ", "output": "{\n\tfor idx, test := range []struct {\n\t\tinput uint64\n\t\texpect color.Color\n\t}{\n\t\t{9000, white},\n\t\t{100, red},\n\t\t{0, red},\n\t\t{1024, white},\n\t\t{768, green},\n\t\t{512, yellow},\n\t\t{256, red},\n\t} {\n\t\tif g, e := blend.PickColor(trafficLights, test.input), color.RGBA64Model.Convert(test.expect); g != e {\n\t\t\tt.Errorf(\"#%d: value %d wrong color: %v != %v\", idx, test.input, g, e)\n\t\t}\n\t}\n}"} {"input": "package syscall\n\nfunc setTimespec(sec, nsec int64) Timespec {\n\treturn Timespec{Sec: sec, Nsec: nsec}\n}\n\n\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint64(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint64(length)\n}\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\n\nconst RTM_LOCK = 0x8\n\n\n\nconst SYS___SYSCTL = SYS_SYSCTL\n\nfunc setTimeval(sec, usec int64) Timeval ", "output": "{\n\treturn Timeval{Sec: sec, Usec: usec}\n}"} {"input": "package virtualterm_test\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/lmorg/murex/test/count\"\n\t\"github.com/lmorg/murex/utils/ansi\"\n\t\"github.com/lmorg/murex/utils/virtualterm\"\n)\n\nfunc TestWriteSgrFgRedExportHtml(t *testing.T) {\n\tcount.Tests(t, 1)\n\n\tterm := virtualterm.NewTerminal(120, 1)\n\ttest := fmt.Sprintf(\"Normal%sBold%sRed%sReset\", ansi.Bold, ansi.FgRed, ansi.Reset)\n\texp1 := `NormalBoldRedReset \n`\n\texp2 := `NormalBoldRedReset \n`\n\n\tterm.Write([]rune(test))\n\tact := strings.TrimSpace(term.ExportHtml())\n\n\tif exp1 != act && exp2 != act {\n\t\tt.Error(\"Expected output does not match actual output\")\n\t\tt.Logf(\" Expected: '%s'\", exp1)\n\t\tt.Logf(\" Actual: '%s'\", act)\n\t\tt.Logf(\" exp bytes: %v\", []byte(exp1))\n\t\tt.Logf(\" act bytes: %v\", []byte(act))\n\t}\n}\n\n\n\nfunc TestWriteSgrFgColoursExportHtml(t *testing.T) ", "output": "{\n\tcount.Tests(t, 1)\n\n\tterm := virtualterm.NewTerminal(120, 1)\n\ttest := fmt.Sprintf(\"%sRed%sGreen%sBlue\", ansi.FgRed, ansi.FgGreen, ansi.FgBlue)\n\texp := `RedGreenBlue \n`\n\n\tterm.Write([]rune(test))\n\tact := strings.TrimSpace(term.ExportHtml())\n\n\tif exp != act {\n\t\tt.Error(\"Expected output does not match actual output\")\n\t\tt.Logf(\" Expected: '%s'\", exp)\n\t\tt.Logf(\" Actual: '%s'\", act)\n\t\tt.Logf(\" exp bytes: %v\", []byte(exp))\n\t\tt.Logf(\" act bytes: %v\", []byte(act))\n\t}\n}"} {"input": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"io/ioutil\"\n \"os\"\n)\n\n\n\nfunc main() {\n\n \n \n d1 := []byte(\"hello\\ngo\\n\")\n err := ioutil.WriteFile(\"/tmp/dat1\", d1, 0644)\n check(err)\n\n \n f, err := os.Create(\"/tmp/dat2\")\n check(err)\n\n \n \n defer f.Close()\n\n \n d2 := []byte{115, 111, 109, 101, 10}\n n2, err := f.Write(d2)\n check(err)\n fmt.Printf(\"wrote %d bytes\\n\", n2)\n\n \n n3, err := f.WriteString(\"writes\\n\")\n fmt.Printf(\"wrote %d bytes\\n\", n3)\n\n \n f.Sync()\n\n \n \n w := bufio.NewWriter(f)\n n4, err := w.WriteString(\"buffered\\n\")\n fmt.Printf(\"wrote %d bytes\\n\", n4)\n\n \n \n w.Flush()\n\n}\n\nfunc check(e error) ", "output": "{\n if e != nil {\n panic(e)\n }\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"html/template\"\n \"io/ioutil\"\n \"net/http\"\n \"os\"\n)\n\ntype Page struct {\n\tTitle string\n\tBody []byte\n}\n\nfunc (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}\n\n\n\nfunc renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {\n t, _ := template.ParseFiles(tmpl + \".html\")\n t.Execute(w, p)\n}\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n title := r.URL.Path[len(\"/view/\"):]\n p, err := loadPage(title)\n if err != nil {\n http.Redirect(w, r, \"/edit/\" + title, http.StatusFound)\n return\n }\n renderTemplate(w, \"view\", p)\n}\n\nfunc editHandler(w http.ResponseWriter, r *http.Request) {\n title := r.URL.Path[len(\"/edit/\"):]\n p, err := loadPage(title)\n if err != nil {\n p = &Page{Title: title}\n }\n renderTemplate(w, \"edit\", p)\n}\n\nfunc main() {\n http.HandleFunc(\"/view/\", viewHandler)\n http.HandleFunc(\"/edit/\", editHandler)\n \n fmt.Println(\"starting http service ...\")\n http.ListenAndServe(os.Getenv(\"IP\") + \":\" + os.Getenv(\"PORT\"), nil)\n}\n\nfunc loadPage(title string) (*Page, error) ", "output": "{\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Page{Title: title, Body: body}, nil\n}"} {"input": "package main\n\nimport \"fmt\"\nimport \"sort\"\n\ntype ByLength []string\n\nfunc (s ByLength) Len() int {\n return len(s)\n}\n\n\n\nfunc (s ByLength) Less(i, j int) bool {\n return len(s[i]) < len(s[j])\n}\n\nfunc main() {\n fruits := []string{\"peach\", \"banana\", \"kiwi\"}\n sort.Sort(ByLength(fruits))\n fmt.Println(fruits)\n}\n\nfunc (s ByLength) Swap(i, j int) ", "output": "{\n s[i], s[j] = s[j], s[i]\n}"} {"input": "package caaa\n\nimport (\n\t\"encoding/xml\"\n\n\t\"github.com/fgrid/iso20022\"\n)\n\ntype Document01600102 struct {\n\tXMLName xml.Name `xml:\"urn:iso:std:iso:20022:tech:xsd:caaa.016.001.02 Document\"`\n\tMessage *AcceptorCurrencyConversionRequestV02 `xml:\"AccptrCcyConvsReq\"`\n}\n\n\n\n\n\ntype AcceptorCurrencyConversionRequestV02 struct {\n\n\tHeader *iso20022.Header10 `xml:\"Hdr\"`\n\n\tCurrencyConversionRequest *iso20022.AcceptorCurrencyConversionRequest2 `xml:\"CcyConvsReq\"`\n\n\tSecurityTrailer *iso20022.ContentInformationType11 `xml:\"SctyTrlr\"`\n}\n\nfunc (a *AcceptorCurrencyConversionRequestV02) AddHeader() *iso20022.Header10 {\n\ta.Header = new(iso20022.Header10)\n\treturn a.Header\n}\n\nfunc (a *AcceptorCurrencyConversionRequestV02) AddCurrencyConversionRequest() *iso20022.AcceptorCurrencyConversionRequest2 {\n\ta.CurrencyConversionRequest = new(iso20022.AcceptorCurrencyConversionRequest2)\n\treturn a.CurrencyConversionRequest\n}\n\nfunc (a *AcceptorCurrencyConversionRequestV02) AddSecurityTrailer() *iso20022.ContentInformationType11 {\n\ta.SecurityTrailer = new(iso20022.ContentInformationType11)\n\treturn a.SecurityTrailer\n}\n\nfunc (d *Document01600102) AddMessage() *AcceptorCurrencyConversionRequestV02 ", "output": "{\n\td.Message = new(AcceptorCurrencyConversionRequestV02)\n\treturn d.Message\n}"} {"input": "package driver\n\nimport \"database/sql/driver\"\n\nvar _ driver.Result = result{}\n\n\n\ntype result struct {\n\tlastInsertID int64\n\trowsAffected int64\n}\n\n\n\nfunc (r result) RowsAffected() (int64, error) {\n\treturn r.rowsAffected, nil\n}\n\nfunc (r result) LastInsertId() (int64, error) ", "output": "{\n\treturn r.lastInsertID, nil\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/aws/aws-lambda-go/events\"\n\t\"github.com/aws/aws-lambda-go/lambda\"\n)\n\n\n\nfunc main() {\n\tlambda.Start(handler)\n}\n\nfunc handler(ctx context.Context, sqsEvent events.SQSEvent) error ", "output": "{\n\tfor _, message := range sqsEvent.Records {\n\t\tfmt.Printf(\"The message %s for event source %s = %s \\n\", message.MessageId, message.EventSource, message.Body)\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\t\"github.com/gorilla/mux\"\n)\n\nfunc Configure(router *mux.Router) {\n\n\trouter.HandleFunc(\"/init\", initData).Methods(\"GET\")\n\trouter.HandleFunc(\"/test/{name}\", getData).Methods(\"GET\")\n}\n\n\n\nfunc getData(resp http.ResponseWriter, req *http.Request) {\n\n\tname, _ := mux.Vars(req)[\"name\"]\n\tdata := callDb(name)\n\n\tif data.Name == \"\" {\n\t\tresp.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tval, _ := json.Marshal(data)\n\tresp.Write(val)\n}\n\nfunc initData(resp http.ResponseWriter, req *http.Request) ", "output": "{\n\n\tinsert()\n}"} {"input": "package blanket_emulator\n\nimport (\n\t\"fmt\"\n)\n\ntype Event interface {\n\tHash() uint64\n\tInspect() string\n}\n\ntype ReturnEvent uint64\ntype ReadEvent uint64\ntype WriteEvent struct {\n\tAddr uint64\n\tValue uint64\n}\ntype SyscallEvent uint64\ntype InvalidInstructionEvent uint64\n\nfunc (addr ReadEvent) Hash() uint64 {\n\treturn ReadEventHash(uint64(addr))\n}\n\nfunc (s WriteEvent) Hash() uint64 {\n\treturn WriteEventHash(s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Hash() uint64 {\n\treturn SysEventHash(uint64(s))\n}\n\nfunc (s ReturnEvent) Hash() uint64 {\n\treturn ReturnEventHash(uint64(s))\n}\n\nfunc (s InvalidInstructionEvent) Hash() uint64 {\n\treturn InvalidInstructionEventHash(uint64(s))\n}\n\nfunc (addr ReadEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Read([%x])\", addr)\n}\n\n\n\nfunc (s WriteEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Write([%x]=%x)\", s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Sys(%x)\", s)\n}\n\nfunc (s InvalidInstructionEvent) Inspect() string {\n\treturn fmt.Sprintf(\"InvalidOpcode([%x])\", s)\n}\n\nfunc (addr ReturnEvent) Inspect() string ", "output": "{\n\treturn fmt.Sprintf(\"Return([%x])\", addr)\n}"} {"input": "package Plugin\n\nimport \"github.com/MPjct/GoMP/MySQLProtocol\"\n\ntype Plugin_interface interface {\n\tinit(context MySQLProtocol.Context)\n\tread_handshake(context MySQLProtocol.Context)\n\tsend_handshake(context MySQLProtocol.Context)\n\tread_auth(context MySQLProtocol.Context)\n\tsend_auth(context MySQLProtocol.Context)\n\tread_auth_result(context MySQLProtocol.Context)\n\tsend_auth_result(context MySQLProtocol.Context)\n\tread_query(context MySQLProtocol.Context)\n\tsend_query(context MySQLProtocol.Context)\n\tread_query_result(context MySQLProtocol.Context)\n\tsend_query_result(context MySQLProtocol.Context)\n\tcleanup(context MySQLProtocol.Context)\n}\n\ntype Plugin struct {\n}\n\n\n\nfunc (plugin *Plugin) read_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) cleanup(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) init(context MySQLProtocol.Context) ", "output": "{\n\treturn\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/hyperledger/fabric/common/channelconfig\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n)\n\n\ntype Orderer struct {\n\tConsensusTypeVal string\n\tBatchSizeVal *ab.BatchSize\n\tBatchTimeoutVal time.Duration\n\tKafkaBrokersVal []string\n\tMaxChannelsCountVal uint64\n\tOrganizationsVal map[string]channelconfig.Org\n\tCapabilitiesVal channelconfig.OrdererCapabilities\n}\n\n\nfunc (scm *Orderer) ConsensusType() string {\n\treturn scm.ConsensusTypeVal\n}\n\n\nfunc (scm *Orderer) BatchSize() *ab.BatchSize {\n\treturn scm.BatchSizeVal\n}\n\n\nfunc (scm *Orderer) BatchTimeout() time.Duration {\n\treturn scm.BatchTimeoutVal\n}\n\n\n\n\n\nfunc (scm *Orderer) MaxChannelsCount() uint64 {\n\treturn scm.MaxChannelsCountVal\n}\n\n\nfunc (scm *Orderer) Organizations() map[string]channelconfig.Org {\n\treturn scm.OrganizationsVal\n}\n\n\nfunc (scm *Orderer) Capabilities() channelconfig.OrdererCapabilities {\n\treturn scm.CapabilitiesVal\n}\n\n\ntype OrdererCapabilities struct {\n\tSupportedErr error\n\n\tSetChannelModPolicyDuringCreateVal bool\n\n\tResubmissionVal bool\n}\n\n\nfunc (oc *OrdererCapabilities) Supported() error {\n\treturn oc.SupportedErr\n}\n\n\nfunc (oc *OrdererCapabilities) SetChannelModPolicyDuringCreate() bool {\n\treturn oc.SetChannelModPolicyDuringCreateVal\n}\n\n\nfunc (oc *OrdererCapabilities) Resubmission() bool {\n\treturn oc.ResubmissionVal\n}\n\nfunc (scm *Orderer) KafkaBrokers() []string ", "output": "{\n\treturn scm.KafkaBrokersVal\n}"} {"input": "package data\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/credentials\"\n\t\"github.com/aws/aws-sdk-go/aws/session\"\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/guregu/dynamo\"\n\t\"github.com/spf13/viper\"\n)\n\n\ntype DynamoDB struct {\n\tdb *dynamo.DB\n}\n\n\n\n\nfunc (d *DynamoDB) FindByHash(hash string) (*Avatar, error) {\n\tvar avatar Avatar\n\n\tif err := d.getTable().Get(\"Hash\", hash).One(&avatar); err != nil {\n\t\treturn nil, fmt.Errorf(\"Cannot find avatar with hash %s\", hash)\n\t}\n\n\treturn &avatar, nil\n}\n\nfunc (d *DynamoDB) Save(a *Avatar) error {\n\n\tif err := d.getTable().Put(a).Run(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *DynamoDB) Migrate() error {\n\treturn nil\n}\n\nfunc (d *DynamoDB) getTable() dynamo.Table {\n\treturn d.db.Table(viper.GetString(\"TableName\"))\n}\n\nfunc (d *DynamoDB) Connect() error ", "output": "{\n\tvar awsConfig *aws.Config\n\tif viper.GetString(\"DynamoEndpoint\") == \"\" {\n\t\tawsConfig = &aws.Config{}\n\t} else {\n\t\tmyTrue := true\n\t\tawsConfig = &aws.Config{\n\t\t\tEndpoint: aws.String(viper.GetString(\"DynamoEndpoint\")),\n\t\t\tCredentials: credentials.NewStaticCredentials(\"foo\", \"foo\", \"foo\"),\n\t\t\tDisableSSL: &myTrue,\n\t\t}\n\t}\n\tawsConfig.WithRegion(viper.GetString(\"DynamoRegion\"))\n\tif gin.Mode() == gin.DebugMode {\n\t\tawsConfig.WithLogLevel(aws.LogDebugWithHTTPBody)\n\t}\n\n\td.db = dynamo.New(session.Must(session.NewSession()), awsConfig)\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\t\"text/template\"\n)\n\nvar htmlTemplate = `\n\n\n \n \n Pinentry\n \n \n
\n\t\t\t\n\t\t\t\n\t\t
\n \n\n`\n\ntype password struct {\n\tPassword string\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/\", pinentry)\n\thttp.ListenAndServe(\":8001\", nil)\n}\n\nfunc pinentry(w http.ResponseWriter, r *http.Request) {\n\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tt, _ := template.New(\"html\").Parse(htmlTemplate)\n\t\tt.Execute(w, nil)\n\tcase \"POST\":\n\t\thandlePost(w, r)\n\t}\n}\n\n\n\nfunc handlePost(w http.ResponseWriter, r *http.Request) ", "output": "{\n\n\tif r.PostFormValue(\"password\") != \"\" {\n\t\tfmt.Println(r.PostFormValue(\"password\"))\n\t\tw.Write([]byte(\"password was submitted\"))\n\t\tos.Exit(0)\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tdefer r.Body.Close()\n\tvar t password\n\terr := decoder.Decode(&t)\n\tif err != nil {\n\t\tw.Write([]byte(\"{'error':'cannot parse json'}\"))\n\t\treturn\n\t}\n\n\tw.Write([]byte(\"{'message':'password was submitted'}\"))\n\tfmt.Println(t.Password)\n\n\tos.Exit(0)\n}"} {"input": "package service\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetServiceIDOKCode int = 200\n\n\ntype GetServiceIDOK struct {\n\n\tPayload *models.Service `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetServiceIDOK() *GetServiceIDOK {\n\n\treturn &GetServiceIDOK{}\n}\n\n\nfunc (o *GetServiceIDOK) WithPayload(payload *models.Service) *GetServiceIDOK {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *GetServiceIDOK) SetPayload(payload *models.Service) {\n\to.Payload = payload\n}\n\n\nfunc (o *GetServiceIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\n\nconst GetServiceIDNotFoundCode int = 404\n\n\ntype GetServiceIDNotFound struct {\n}\n\n\n\n\n\nfunc (o *GetServiceIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc NewGetServiceIDNotFound() *GetServiceIDNotFound ", "output": "{\n\n\treturn &GetServiceIDNotFound{}\n}"} {"input": "package controllers\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/lessos/lessgo/httpsrv\"\n\t\"github.com/lessos/lessids/idclient\"\n\n\t\"../../../config\"\n)\n\ntype Pod struct {\n\t*httpsrv.Controller\n}\n\n\n\nfunc (c Pod) IndexAction() ", "output": "{\n\n\tc.Data[\"version\"] = config.Config.Version\n\n\tif !idclient.SessionIsLogin(c.Session) {\n\t\tc.Redirect(idclient.AuthServiceUrl(\n\t\t\tconfig.Config.InstanceID,\n\t\t\tfmt.Sprintf(\"%s%s/auth/cb\", c.Request.Host, config.HttpSrvBasePath(\"\")),\n\t\t\tc.Request.RawAbsUrl()))\n\t\treturn\n\t}\n\n\tc.Data[\"pandora_endpoint\"] = config.Config.PandoraEndpoint\n\tc.Data[\"l9r_pod_active\"] = c.Params.Get(\"pod_id\")\n\n\tc.Render(\"index/index.tpl\")\n}"} {"input": "package s3\n\nimport (\n\t\"github.com/djbarber/ipfs-hack/Godeps/_workspace/src/github.com/crowdmob/goamz/aws\"\n)\n\nvar originalStrategy = attempts\n\nfunc SetAttemptStrategy(s *aws.AttemptStrategy) {\n\tif s == nil {\n\t\tattempts = originalStrategy\n\t} else {\n\t\tattempts = *s\n\t}\n}\n\nfunc Sign(auth aws.Auth, method, path string, params, headers map[string][]string) {\n\tsign(auth, method, path, params, headers)\n}\n\nfunc SetListPartsMax(n int) {\n\tlistPartsMax = n\n}\n\n\n\nfunc SetListMultiMax(n int) ", "output": "{\n\tlistMultiMax = n\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\n\t\"github.com/uber/jaeger-client-go/thrift-gen/agent\"\n\t\"github.com/uber/jaeger-client-go/thrift-gen/zipkincore\"\n\n\t\"github.com/apache/thrift/lib/go/thrift\"\n)\n\n\nconst UDPPacketMaxLength = 65000\n\n\ntype AgentClientUDP struct {\n\tagent.Agent\n\tio.Closer\n\n\tconnUDP *net.UDPConn\n\tclient *agent.AgentClient\n\tmaxPacketSize int \n\tthriftBuffer *thrift.TMemoryBuffer \n}\n\n\n\n\n\nfunc (a *AgentClientUDP) EmitZipkinBatch(spans []*zipkincore.Span) error {\n\ta.thriftBuffer.Reset()\n\ta.client.SeqId = 0 \n\tif err := a.client.EmitZipkinBatch(spans); err != nil {\n\t\treturn err\n\t}\n\tif a.thriftBuffer.Len() > a.maxPacketSize {\n\t\treturn fmt.Errorf(\"Data does not fit within one UDP packet; size %d, max %d, spans %d\",\n\t\t\ta.thriftBuffer.Len(), a.maxPacketSize, len(spans))\n\t}\n\t_, err := a.connUDP.Write(a.thriftBuffer.Bytes())\n\treturn err\n}\n\n\nfunc (a *AgentClientUDP) Close() error {\n\treturn a.connUDP.Close()\n}\n\nfunc NewAgentClientUDP(hostPort string, maxPacketSize int) (*AgentClientUDP, error) ", "output": "{\n\tif maxPacketSize == 0 {\n\t\tmaxPacketSize = UDPPacketMaxLength\n\t}\n\n\tthriftBuffer := thrift.NewTMemoryBufferLen(maxPacketSize)\n\tprotocolFactory := thrift.NewTCompactProtocolFactory()\n\tclient := agent.NewAgentClientFactory(thriftBuffer, protocolFactory)\n\n\tdestAddr, err := net.ResolveUDPAddr(\"udp\", hostPort)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconnUDP, err := net.DialUDP(destAddr.Network(), nil, destAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := connUDP.SetWriteBuffer(maxPacketSize); err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientUDP := &AgentClientUDP{\n\t\tconnUDP: connUDP,\n\t\tclient: client,\n\t\tmaxPacketSize: maxPacketSize,\n\t\tthriftBuffer: thriftBuffer}\n\treturn clientUDP, nil\n}"} {"input": "package regex_test\n\nimport (\n\t\"fmt\"\n\t\"simonwaldherr.de/go/golibs/regex\"\n)\n\n\n\nfunc ExampleReplaceAllString() ", "output": "{\n\tfmt.Print(regex.ReplaceAllString(\"FooBaR LoReM IpSuM\", \"[a-z]\", \"\"))\n\n}"} {"input": "package credentials\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype FakeProvider struct {\n\tError error\n\tCredentials *Credentials\n}\n\nfunc (p *FakeProvider) GetCredentials() (*Credentials, error) {\n\tif p.Credentials != nil {\n\t\treturn p.Credentials, nil\n\t}\n\n\tif p.Error != nil {\n\t\treturn nil, p.Error\n\t}\n\n\tpanic(\"Specify either Credentials or Error\")\n}\n\n\n\nfunc TestFakeProviderAssignable(t *testing.T) ", "output": "{\n\tvar provider interface{}\n\tprovider = &FakeProvider{}\n\n\t_, ok := provider.(Provider)\n\tassert.True(t, ok, \"\")\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/djthorpe/gopi/v3\"\n\n\t_ \"github.com/djthorpe/gopi/v3/pkg/dev/chromecast\"\n\t_ \"github.com/djthorpe/gopi/v3/pkg/event\"\n\t_ \"github.com/djthorpe/gopi/v3/pkg/log\"\n\t_ \"github.com/djthorpe/gopi/v3/pkg/mdns\"\n)\n\n\n\n\ntype app struct {\n\tgopi.Unit\n\tgopi.Logger\n\tgopi.CastManager\n\tgopi.Publisher\n}\n\n\n\n\n\n\nfunc (this *app) Run(ctx context.Context) error ", "output": "{\n\tthis.Require(this.Logger, this.CastManager)\n\n\tctx2, cancel := context.WithTimeout(ctx, time.Second)\n\tdefer cancel()\n\tif devices, err := this.Devices(ctx2); err != nil {\n\t\treturn err\n\t} else {\n\t\tfmt.Println(devices)\n\t}\n\n\tch := this.Subscribe()\n\tdefer this.Unsubscribe(ch)\n\n\tfmt.Println(\"Press CTRL+C to end\")\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase evt := <-ch:\n\t\t\tif evt, ok := evt.(gopi.CastEvent); ok {\n\t\t\t\tfmt.Println(evt)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package keepalive_test\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"istio.io/istio/pkg/keepalive\"\n)\n\n\n\n\n\n\nfunc TestSetConnectionAgeCommandlineOptions(t *testing.T) {\n\tko := keepalive.DefaultOption()\n\tcmd := &cobra.Command{}\n\tko.AttachCobraFlags(cmd)\n\n\tbuf := new(bytes.Buffer)\n\tcmd.SetOutput(buf)\n\tsec := 1 * time.Second\n\tcmd.SetArgs([]string{\n\t\tfmt.Sprintf(\"--keepaliveMaxServerConnectionAge=%v\", sec),\n\t})\n\n\tif err := cmd.Execute(); err != nil {\n\t\tt.Errorf(\"%s %s\", t.Name(), err.Error())\n\t}\n\tif ko.MaxServerConnectionAge != sec {\n\t\tt.Errorf(\"%s maximum connection age %v\", t.Name(), ko.MaxServerConnectionAge)\n\t}\n}\n\nfunc TestAgeDefaultsToInfinite(t *testing.T) ", "output": "{\n\tko := keepalive.DefaultOption()\n\n\tif ko.MaxServerConnectionAge != keepalive.Infinity {\n\t\tt.Errorf(\"%s maximum connection age %v\", t.Name(), ko.MaxServerConnectionAge)\n\t}\n}"} {"input": "package main\n\nimport \"strings\"\n\nvar x = make([]byte, 10)\n\nfunc main() {\n\ttest1()\n\ttest2()\n\ttest3()\n\ttest4()\n\ttest5()\n\ttest6()\n\ttest7()\n}\n\nfunc mustRecover(s string) {\n\tv := recover()\n\tif v == nil {\n\t\tpanic(\"expected panic\")\n\t}\n\tif e := v.(error).Error(); strings.Index(e, s) < 0 {\n\t\tpanic(\"want: \" + s + \"; have: \" + e)\n\t}\n}\n\nfunc test1() {\n\tdefer mustRecover(\"index\")\n\tprintln(x[123])\n}\n\n\n\nfunc test3() {\n\tdefer mustRecover(\"slice\")\n\tvar lo = 11\n\tvar hi = 9\n\tprintln(x[lo:hi])\n}\n\nfunc test4() {\n\tdefer mustRecover(\"interface\")\n\tvar x interface{} = 1\n\tprintln(x.(float32))\n}\n\ntype T struct {\n\ta, b int\n\tc []int\n}\n\nfunc test5() {\n\tdefer mustRecover(\"uncomparable\")\n\tvar x T\n\tvar z interface{} = x\n\tprintln(z != z)\n}\n\nfunc test6() {\n\tdefer mustRecover(\"unhashable\")\n\tvar x T\n\tvar z interface{} = x\n\tm := make(map[interface{}]int)\n\tm[z] = 1\n}\n\nfunc test7() {\n\tdefer mustRecover(\"divide by zero\")\n\tvar x, y int\n\tprintln(x / y)\n}\n\nfunc test2() ", "output": "{\n\tdefer mustRecover(\"slice\")\n\tprintln(x[5:15])\n}"} {"input": "package utils\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n\n\nfunc CheckConnection() bool ", "output": "{\n\tsuccess := \"Success\" +\n\t\t\"Success\"\n\n\tres, err := http.Get(\"http://www.apple.com/library/test/success.html\")\n\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tdefer res.Body.Close()\n\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn string(body) == success\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/xiegeo/thuder\"\n\t\"gopkg.in/natefinch/lumberjack.v2\"\n)\n\n\n\n\nfunc logger(hc *thuder.HostConfig) io.Writer ", "output": "{\n\tlogger := &lumberjack.Logger{\n\t\tFilename: filepath.Join(hc.UniqueDirectory(), \"log\"),\n\t\tMaxSize: 1,\n\t\tMaxBackups: 2,\n\t}\n\treturn io.MultiWriter(os.Stdout, logger)\n}"} {"input": "package util\n\nconst (\n\tDefaultPerPage = 20\n)\n\n\n\nfunc (p *Pagination) SimplePage() (from int64, to int64) {\n\tif p.CurPage == 0 || p.PerPage == 0 {\n\t\tp.CurPage, p.PerPage = 1, DefaultPerPage\n\t}\n\tfrom = (p.CurPage-1)*p.PerPage + 1\n\tto = from + p.PerPage - 1\n\treturn\n}\n\n\n\n\n\n\nfunc (p *Pagination) VagueOffsetLimit() (offset int64, limit int64) {\n\tfrom, to := p.SimplePage()\n\tif to == 0 || from == 0 {\n\t\treturn 0, 0\n\t}\n\treturn from - 1, to - from + 1\n}\n\n\nfunc (p *Pagination) OffsetLimit(total int64) (offset int64, limit int64) {\n\tfrom, to := p.Page(total)\n\tif to == 0 || from == 0 {\n\t\treturn 0, 0\n\t}\n\treturn from - 1, to - from + 1\n}\n\n\ntype Pagination struct {\n\tCurPage int64\n\tPerPage int64\n}\n\nfunc (p *Pagination) Page(total int64) (from int64, to int64) ", "output": "{\n\tif p.CurPage == 0 {\n\t\tp.CurPage = 1\n\t}\n\tif p.PerPage == 0 {\n\t\tp.PerPage = DefaultPerPage\n\t}\n\n\tif total == 0 || total < p.PerPage*(p.CurPage-1) {\n\t\treturn\n\t}\n\tif total <= p.PerPage {\n\t\treturn 1, total\n\t}\n\tfrom = (p.CurPage-1)*p.PerPage + 1\n\tif (total - from + 1) < p.PerPage {\n\t\treturn from, total\n\t}\n\treturn from, from + p.PerPage - 1\n}"} {"input": "package datastore\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype JSONMessage interface {\n\tBytes() json.RawMessage\n\tVersion() map[string]int\n}\n\n\nfunc NewJSONMessage(data []byte, version map[string]int) JSONMessage {\n\treturn &jsonMessage{data, version}\n}\n\ntype jsonMessage struct {\n\tdata json.RawMessage\n\tvEntity map[string]int\n}\n\nfunc (m *jsonMessage) Bytes() json.RawMessage {\n\treturn m.data\n}\n\nfunc (m *jsonMessage) Version() map[string]int {\n\treturn m.vEntity\n}\n\n\n\n\n\nfunc (m *jsonMessage) UnmarshalJSON(data []byte) error {\n\treturn m.data.UnmarshalJSON(data)\n}\n\nfunc (m *jsonMessage) MarshalJSON() ([]byte, error) ", "output": "{\n\treturn m.data.MarshalJSON()\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"k8s.io/client-go/kubernetes/typed/extensions/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeExtensionsV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeExtensionsV1beta1) DaemonSets(namespace string) v1beta1.DaemonSetInterface {\n\treturn &FakeDaemonSets{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) Deployments(namespace string) v1beta1.DeploymentInterface {\n\treturn &FakeDeployments{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) Ingresses(namespace string) v1beta1.IngressInterface {\n\treturn &FakeIngresses{c, namespace}\n}\n\n\n\nfunc (c *FakeExtensionsV1beta1) ReplicaSets(namespace string) v1beta1.ReplicaSetInterface {\n\treturn &FakeReplicaSets{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) Scales(namespace string) v1beta1.ScaleInterface {\n\treturn &FakeScales{c, namespace}\n}\n\n\n\nfunc (c *FakeExtensionsV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeExtensionsV1beta1) PodSecurityPolicies() v1beta1.PodSecurityPolicyInterface ", "output": "{\n\treturn &FakePodSecurityPolicies{c}\n}"} {"input": "package photo\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"github.com/nebulaim/telegramd/baselib/base\"\n\t\"github.com/nebulaim/telegramd/baselib/mysql_client\"\n\t\"github.com/nebulaim/telegramd/service/document/biz/dal/dao/mysql_dao\"\n\t\"github.com/nebulaim/telegramd/service/idgen/client\"\n)\n\ntype photosDAO struct {\n\t*mysql_dao.PhotoDatasDAO\n\tidgen.UUIDGen\n}\n\ntype PhotoModel struct {\n\tdao *photosDAO\n}\n\n\n\nfunc NewPhotoModel(serverId int32, dbName, redisName string) *PhotoModel ", "output": "{\n\tm := &PhotoModel{dao: &photosDAO{}}\n\tdb := mysql_client.GetMysqlClient(dbName)\n\tif db == nil {\n\t\tglog.Fatal(\"not found db: \", dbName)\n\t}\n\n\tm.dao.PhotoDatasDAO = mysql_dao.NewPhotoDatasDAO(db)\n\n\tvar err error\n\tm.dao.UUIDGen, err = idgen.NewUUIDGen(\"snowflake\", base.Int32ToString(serverId))\n\tif err != nil {\n\t\tglog.Fatal(\"uuidgen init error: \", err)\n\t}\n\treturn m\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype MyFloat float64\n\n\n\nfunc main() {\n\tf := MyFloat(-math.Sqrt2)\n\tfmt.Println(f.Abs())\n}\n\nfunc (f MyFloat) Abs() float64 ", "output": "{\n\tif f < 0 {\n\t\treturn float64(-f)\n\t}\n\treturn float64(f)\n}"} {"input": "package store\n\nimport (\n\t\"github.com/snapcore/snapd/testutil\"\n\n\t\"gopkg.in/retry.v1\"\n)\n\n\n\n\nfunc (cm *CacheManager) CacheDir() string {\n\treturn cm.cacheDir\n}\n\nfunc MockDefaultRetryStrategy(t *testutil.BaseTest, strategy retry.Strategy) ", "output": "{\n\toriginalDefaultRetryStrategy := defaultRetryStrategy\n\tdefaultRetryStrategy = strategy\n\tt.AddCleanup(func() {\n\t\tdefaultRetryStrategy = originalDefaultRetryStrategy\n\t})\n}"} {"input": "package accessor_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestAccessor(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Accessor Suite\")\n}"} {"input": "package testbackend\n\nimport (\n\t\"context\"\n\n\t\"github.com/stripe/veneur/v14/ssf\"\n\t\"github.com/stripe/veneur/v14/trace\"\n)\n\n\n\ntype SendErrorSource func(*ssf.SSFSpan) error\n\n\n\ntype BackendOption func(*Backend)\n\n\n\nfunc SendErrors(src SendErrorSource) BackendOption {\n\treturn func(be *Backend) {\n\t\tbe.errorSrc = src\n\t}\n}\n\n\n\ntype Backend struct {\n\tch chan<- *ssf.SSFSpan\n\terrorSrc SendErrorSource\n}\n\n\nfunc (be *Backend) Close() error {\n\treturn nil\n}\n\n\n\n\n\n\nfunc NewBackend(ch chan<- *ssf.SSFSpan, opts ...BackendOption) trace.ClientBackend {\n\tbe := &Backend{ch: ch}\n\tfor _, opt := range opts {\n\t\topt(be)\n\t}\n\treturn be\n}\n\nfunc (be *Backend) SendSync(ctx context.Context, span *ssf.SSFSpan) error ", "output": "{\n\tif be.errorSrc != nil {\n\t\tif err := be.errorSrc(span); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tselect {\n\tcase be.ch <- span:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}"} {"input": "package gokeepasslib\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"io\"\n)\n\n\nvar BaseSignature = [...]byte{0x03, 0xd9, 0xa2, 0x9a}\n\n\nvar SecondarySignature = [...]byte{0x67, 0xfb, 0x4b, 0xb5}\n\n\nconst MajorVersion = 3\n\n\nconst MinorVersion = 1\n\n\nvar DefaultSig = FileSignature{BaseSignature, SecondarySignature, MinorVersion, MajorVersion}\n\ntype ErrInvalidSignature struct {\n\tName string\n\tIs interface{}\n\tShouldbe interface{}\n}\n\nfunc (e ErrInvalidSignature) Error() string {\n\treturn fmt.Sprintf(\"gokeepasslib: invalid signature. %s is %x. Should be %x\", e.Name, e.Is, e.Shouldbe)\n}\n\n\n\n\n\ntype FileSignature struct {\n\tBaseSignature [4]byte\n\tSecondarySignature [4]byte\n\tMinorVersion uint16\n\tMajorVersion uint16\n}\n\nfunc (s FileSignature) String() string {\n\treturn fmt.Sprintf(\"Base: %x, Secondary: %x, Format Version: %d.%d\",\n\t\ts.BaseSignature,\n\t\ts.SecondarySignature,\n\t\ts.MajorVersion,\n\t\ts.MinorVersion,\n\t)\n}\n\nfunc (s *FileSignature) ReadFrom(r io.Reader) error {\n\tif err := binary.Read(r, binary.LittleEndian, s); err != nil {\n\t\treturn err\n\t}\n\treturn s.Validate()\n}\n\nfunc (s FileSignature) WriteTo(w io.Writer) error {\n\treturn binary.Write(w, binary.LittleEndian, s)\n}\n\nfunc (s FileSignature) Validate() error ", "output": "{\n\tif s.BaseSignature != BaseSignature {\n\t\treturn ErrInvalidSignature{\"Base Signature\", s.BaseSignature, BaseSignature}\n\t}\n\tif s.SecondarySignature != SecondarySignature {\n\t\treturn ErrInvalidSignature{\"Secondary Signature\", s.SecondarySignature, SecondarySignature}\n\t}\n\tif s.MinorVersion != MinorVersion {\n\t\treturn ErrInvalidSignature{\"Minor Version\", s.MinorVersion, MinorVersion}\n\t}\n\tif s.MajorVersion != MajorVersion {\n\t\treturn ErrInvalidSignature{\"Major Version\", s.MajorVersion, MajorVersion}\n\t}\n\treturn nil\n}"} {"input": "package v2\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"path/filepath\"\n\n\t\"github.com/containerd/fifo\"\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\nfunc openShimLog(ctx context.Context, bundle *Bundle) (io.ReadCloser, error) ", "output": "{\n\treturn fifo.OpenFifo(ctx, filepath.Join(bundle.Path, \"log\"), unix.O_RDONLY|unix.O_CREAT|unix.O_NONBLOCK, 0700)\n}"} {"input": "package subtle \n\nimport \"unsafe\"\n\n\n\n\n\n\n\n\n\n\n\nfunc InexactOverlap(x, y []byte) bool {\n\tif len(x) == 0 || len(y) == 0 || &x[0] == &y[0] {\n\t\treturn false\n\t}\n\treturn AnyOverlap(x, y)\n}\n\nfunc AnyOverlap(x, y []byte) bool ", "output": "{\n\treturn len(x) > 0 && len(y) > 0 &&\n\t\tuintptr(unsafe.Pointer(&x[0])) <= uintptr(unsafe.Pointer(&y[len(y)-1])) &&\n\t\tuintptr(unsafe.Pointer(&y[0])) <= uintptr(unsafe.Pointer(&x[len(x)-1]))\n}"} {"input": "package result\n\ntype Classic struct {\n\tid int\n\tfitness float64\n\terr error\n\tstop bool\n}\n\nfunc New(id int, fitness float64, err error, stop bool) Classic {\n\treturn Classic{id, fitness, err, stop}\n}\n\n\nfunc (r Classic) ID() int { return r.id }\n\n\n\n\n\nfunc (r Classic) Err() error { return r.err }\n\n\nfunc (r Classic) Stop() bool { return r.stop }\n\nfunc (r Classic) Fitness() float64 ", "output": "{ return r.fitness }"} {"input": "package mocks\n\nimport (\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n\tremotecommand \"k8s.io/client-go/tools/remotecommand\"\n)\n\n\ntype MockExecutor struct {\n\tctrl *gomock.Controller\n\trecorder *MockExecutorMockRecorder\n}\n\n\ntype MockExecutorMockRecorder struct {\n\tmock *MockExecutor\n}\n\n\n\n\n\nfunc (m *MockExecutor) EXPECT() *MockExecutorMockRecorder {\n\treturn m.recorder\n}\n\n\nfunc (m *MockExecutor) Stream(arg0 remotecommand.StreamOptions) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Stream\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}\n\n\nfunc (mr *MockExecutorMockRecorder) Stream(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Stream\", reflect.TypeOf((*MockExecutor)(nil).Stream), arg0)\n}\n\nfunc NewMockExecutor(ctrl *gomock.Controller) *MockExecutor ", "output": "{\n\tmock := &MockExecutor{ctrl: ctrl}\n\tmock.recorder = &MockExecutorMockRecorder{mock}\n\treturn mock\n}"} {"input": "package dao\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc TestDaoassetRelationKey(t *testing.T) {\n\tconvey.Convey(\"assetRelationKey\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tmid = int64(0)\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\tp1 := assetRelationKey(mid)\n\t\t\tctx.Convey(\"Then p1 should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(p1, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestDaoassetRelationField(t *testing.T) {\n\tconvey.Convey(\"assetRelationField\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\toid = int64(0)\n\t\t\totype = \"\"\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\tp1 := assetRelationField(oid, otype)\n\t\t\tctx.Convey(\"Then p1 should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(p1, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}\n\n\n\nfunc TestDaoDelCacheAssetRelationState(t *testing.T) ", "output": "{\n\tconvey.Convey(\"DelCacheAssetRelationState\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t\toid = int64(0)\n\t\t\totype = \"\"\n\t\t\tmid = int64(0)\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\terr := d.DelCacheAssetRelationState(c, oid, otype, mid)\n\t\t\tctx.Convey(\"Then err should be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package app\n\nimport (\n\t\"os\"\n\t\"strings\"\n)\n\ntype Environment struct {\n\tEnv string\n\tPort string\n}\n\n\n\nfunc envMap() map[string]string {\n\tenviron := os.Environ()\n\tenv := make(map[string]string)\n\n\tfor _, v := range environ {\n\t\tpair := strings.SplitN(v, \"=\", 2)\n\t\tenv[pair[0]] = pair[1]\n\t}\n\n\treturn env\n}\n\nfunc (this *App) defaultEnv() Environment ", "output": "{\n\treturn Environment{\n\t\tEnv: \"development\",\n\t\tPort: \"5000\",\n\t}\n}"} {"input": "package gitea\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\n\ntype PublicKey struct {\n\tID int64 `json:\"id\"`\n\tKey string `json:\"key\"`\n\tURL string `json:\"url,omitempty\"`\n\tTitle string `json:\"title,omitempty\"`\n\tCreated time.Time `json:\"created_at,omitempty\"`\n}\n\n\nfunc (c *Client) ListPublicKeys(user string) ([]*PublicKey, error) {\n\tkeys := make([]*PublicKey, 0, 10)\n\treturn keys, c.getParsedResponse(\"GET\", fmt.Sprintf(\"/users/%s/keys\", user), nil, nil, &keys)\n}\n\n\nfunc (c *Client) ListMyPublicKeys() ([]*PublicKey, error) {\n\tkeys := make([]*PublicKey, 0, 10)\n\treturn keys, c.getParsedResponse(\"GET\", \"/user/keys\", nil, nil, &keys)\n}\n\n\nfunc (c *Client) GetPublicKey(keyID int64) (*PublicKey, error) {\n\tkey := new(PublicKey)\n\treturn key, c.getParsedResponse(\"GET\", fmt.Sprintf(\"/user/keys/%d\", keyID), nil, nil, &key)\n}\n\n\nfunc (c *Client) CreatePublicKey(opt CreateKeyOption) (*PublicKey, error) {\n\tbody, err := json.Marshal(&opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkey := new(PublicKey)\n\treturn key, c.getParsedResponse(\"POST\", \"/user/keys\", jsonHeader, bytes.NewReader(body), key)\n}\n\n\n\n\nfunc (c *Client) DeletePublicKey(keyID int64) error ", "output": "{\n\t_, err := c.getResponse(\"DELETE\", fmt.Sprintf(\"/user/keys/%d\", keyID), nil, nil)\n\treturn err\n}"} {"input": "package popcount\n\n\nvar pc [256]byte\n\n\n\n\nfunc PopCount(x uint64) int {\n\treturn int(pc[byte(x>>(0*8))] +\n\t\tpc[byte(x>>(1*8))] +\n\t\tpc[byte(x>>(2*8))] +\n\t\tpc[byte(x>>(3*8))] +\n\t\tpc[byte(x>>(4*8))] +\n\t\tpc[byte(x>>(5*8))] +\n\t\tpc[byte(x>>(6*8))] +\n\t\tpc[byte(x>>(7*8))])\n}\n\nfunc PopCount2(x uint64) int {\n\tvar sum byte\n\tfor i := uint(0); i < 8; i++ {\n\t\tsum += pc[byte(x>>(i*8))]\n\t}\n\treturn int(sum)\n}\n\nfunc init() ", "output": "{\n\tfor i := range pc {\n\t\tpc[i] = pc[i/2] + byte(i&1)\n\t}\n}"} {"input": "package http\n\nimport (\n\t\"github.com/asim/go-micro/v3/registry\"\n\t\"github.com/asim/go-micro/v3/server\"\n)\n\ntype httpHandler struct {\n\topts server.HandlerOptions\n\teps []*registry.Endpoint\n\thd interface{}\n}\n\nfunc (h *httpHandler) Name() string {\n\treturn \"handler\"\n}\n\n\n\nfunc (h *httpHandler) Endpoints() []*registry.Endpoint {\n\treturn h.eps\n}\n\nfunc (h *httpHandler) Options() server.HandlerOptions {\n\treturn h.opts\n}\n\nfunc (h *httpHandler) Handler() interface{} ", "output": "{\n\treturn h.hd\n}"} {"input": "package matcher\n\nimport \"errors\"\n\ntype IntComparator struct{}\n\nfunc (s *IntComparator) Valid(data interface{}) error {\n\tif _, ok := data.(int); !ok {\n\t\treturn errors.New(\"Invalid argument\")\n\t}\n\n\treturn nil\n}\n\nfunc (s *IntComparator) GreaterThan(a, b interface{}) bool {\n\treturn a.(int) > b.(int)\n}\n\nfunc (s *IntComparator) LessThan(a, b interface{}) bool {\n\treturn a.(int) < b.(int)\n}\n\n\n\nfunc (s *IntComparator) NotEqualTo(a, b interface{}) bool {\n\treturn a.(int) != b.(int)\n}\n\nfunc (s *IntComparator) EqualTo(a, b interface{}) bool ", "output": "{\n\treturn a.(int) == b.(int)\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n)\n\nconst (\n\tSYSTEM_DIAGNOSTIC_ID = \"DiagnosticId\"\n\tSYSTEM_RAN_UNIT_TESTS = \"RanUnitTests\"\n\tSYSTEM_LAST_SECURITY_TIME = \"LastSecurityTime\"\n)\n\ntype System struct {\n\tName string `json:\"name\"`\n\tValue string `json:\"value\"`\n}\n\nfunc (o *System) ToJson() string {\n\tb, err := json.Marshal(o)\n\tif err != nil {\n\t\treturn \"\"\n\t} else {\n\t\treturn string(b)\n\t}\n}\n\n\n\nfunc SystemFromJson(data io.Reader) *System ", "output": "{\n\tdecoder := json.NewDecoder(data)\n\tvar o System\n\terr := decoder.Decode(&o)\n\tif err == nil {\n\t\treturn &o\n\t} else {\n\t\treturn nil\n\t}\n}"} {"input": "package automation\n\nimport (\n\tautomationpb \"github.com/youtube/vitess/go/vt/proto/automation\"\n\t\"github.com/youtube/vitess/go/vt/topo/topoproto\"\n\t\"golang.org/x/net/context\"\n)\n\n\ntype SplitDiffTask struct {\n}\n\n\n\n\n\nfunc (t *SplitDiffTask) RequiredParameters() []string {\n\treturn []string{\"keyspace\", \"dest_shard\", \"vtworker_endpoint\"}\n}\n\n\nfunc (t *SplitDiffTask) OptionalParameters() []string {\n\treturn []string{\"exclude_tables\", \"min_healthy_rdonly_tablets\"}\n}\n\nfunc (t *SplitDiffTask) Run(parameters map[string]string) ([]*automationpb.TaskContainer, string, error) ", "output": "{\n\targs := []string{\"SplitDiff\"}\n\tif excludeTables := parameters[\"exclude_tables\"]; excludeTables != \"\" {\n\t\targs = append(args, \"--exclude_tables=\"+excludeTables)\n\t}\n\tif minHealthyRdonlyTablets := parameters[\"min_healthy_rdonly_tablets\"]; minHealthyRdonlyTablets != \"\" {\n\t\targs = append(args, \"--min_healthy_rdonly_tablets=\"+minHealthyRdonlyTablets)\n\t}\n\targs = append(args, topoproto.KeyspaceShardString(parameters[\"keyspace\"], parameters[\"dest_shard\"]))\n\toutput, err := ExecuteVtworker(context.TODO(), parameters[\"vtworker_endpoint\"], args)\n\n\tif err == nil {\n\t\tExecuteVtworker(context.TODO(), parameters[\"vtworker_endpoint\"], []string{\"Reset\"})\n\t}\n\treturn nil, output, err\n}"} {"input": "package logger\n\nimport (\n\t\"strings\"\n)\n\n\n\nfunc KV(k K, v V) KeyVal {\n\treturn KeyVal{k, v}\n}\n\n\n\nfunc convertStamp(format string) string {\n\tfor _, k := range tsMap {\n\t\tformat = strings.Replace(format, k, string(tsFmtMap[k]), -1)\n\t}\n\treturn format\n}\n\n\n\n\nvar tsMap = []string{\"05.000000\", \"Monday\", \"January\", \"2006\", \"-0700\", \"MST\", \"Mon\", \"Jan\", \"02\", \"15\", \"04\", \"05\", \"01\", \"06\", \"03\", \"pm\"}\n\nfunc hasFlag(has int, flags ...int) bool ", "output": "{\n\tfor _, flag := range flags {\n\t\tif flag&has != 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n)\n\n\n\nfunc main() {\n\nc := `The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:\n\n1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...\n\nLet us list the factors of the first seven triangle numbers:\n\n 1: 1\n 3: 1,3\n 6: 1,2,3,6\n10: 1,2,5,10\n15: 1,3,5,15\n21: 1,3,7,21\n28: 1,2,4,7,14,28\nWe can see that 28 is the first triangle number to have over five divisors.\n\nWhat is the value of the first triangle number to have over 500 divisors?`\n\n fmt.Println(c)\n fmt.Println()\n\n divisors := 0\n triangular := 0\n for num := 1; divisors <= 500; num++ {\n triangular = triangular + num\n divisors = check(triangular)\n }\n\n fmt.Println(\"The 1st triangular number having more than 500 divisors\")\n fmt.Printf(\"is %d. It has %d divisors.\\n\", triangular, divisors)\n}\n\nfunc check(num int) int ", "output": "{\n divs := 2\n limit := num\n for cnt := 2; cnt < limit; cnt++ {\n if num % cnt == 0 { \n limit = num / cnt\n divs++ \n }\n }\n return divs*2\n}"} {"input": "package versioned\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n)\n\n\ntype Convertor struct {\n\tScheme *runtime.Scheme\n}\n\n\nfunc (c Convertor) ConvertToGVK(obj runtime.Object, gvk schema.GroupVersionKind) (runtime.Object, error) {\n\tif obj.GetObjectKind().GroupVersionKind() == gvk {\n\t\treturn obj, nil\n\t}\n\tout, err := c.Scheme.New(gvk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = c.Scheme.Convert(obj, out, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}\n\n\n\n\nfunc (c *Convertor) Validate() error ", "output": "{\n\tif c.Scheme == nil {\n\t\treturn fmt.Errorf(\"the Convertor requires a scheme\")\n\t}\n\treturn nil\n}"} {"input": "package controller \n\nimport (\n\t\"net/url\"\n\t\"testing\"\n\n\t\"github.com/docker/infrakit/pkg/spi/stack\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\nfunc fakeLeader(v bool) func() stack.Leadership {\n\treturn func() stack.Leadership { return fakeLeaderT(v) }\n}\n\ntype fakeLeaderT bool\n\nfunc (f fakeLeaderT) IsLeader() (bool, error) {\n\treturn bool(f), nil\n}\n\nfunc (f fakeLeaderT) LeaderLocation() (*url.URL, error) {\n\treturn nil, nil\n}\n\n\n\nfunc TestSingleton(t *testing.T) ", "output": "{\n\n\tcall1 := make(chan int, 1)\n\tsingleton1 := Singleton(fake(call1), fakeLeader(true))\n\n\t_, err := singleton1.Describe(nil)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, <-call1)\n\n\tcall2 := make(chan int, 1)\n\tsingleton2 := Singleton(fake(call2), fakeLeader(false))\n\n\t_, err = singleton2.Describe(nil)\n\trequire.Error(t, err)\n\trequire.Equal(t, \"not a leader\", err.Error())\n\n\tclose(call1)\n\tclose(call2)\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\n\n\n\ntype MsgFilterClear struct{}\n\n\n\nfunc (msg *MsgFilterClear) MsgDecode(r io.Reader, pver uint32) error {\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filterclear message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterClear.MsgDecode\", str)\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (msg *MsgFilterClear) MsgEncode(w io.Writer, pver uint32) error {\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filterclear message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterClear.MsgEncode\", str)\n\t}\n\n\treturn nil\n}\n\n\n\n\n\n\n\nfunc (msg *MsgFilterClear) MaxPayloadLength(pver uint32) uint32 {\n\treturn 0\n}\n\n\n\nfunc NewMsgFilterClear() *MsgFilterClear {\n\treturn &MsgFilterClear{}\n}\n\nfunc (msg *MsgFilterClear) Command() string ", "output": "{\n\treturn CmdFilterClear\n}"} {"input": "package fake\n\nimport (\n\tv1 \"github.com/openshift/origin/pkg/sdn/clientset/release_v3_6/typed/sdn/v1\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n\tcore \"k8s.io/kubernetes/pkg/client/testing/core\"\n)\n\ntype FakeSdnV1 struct {\n\t*core.Fake\n}\n\n\n\n\n\nfunc (c *FakeSdnV1) RESTClient() restclient.Interface {\n\tvar ret *restclient.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeSdnV1) ClusterNetworks(namespace string) v1.ClusterNetworkInterface ", "output": "{\n\treturn &FakeClusterNetworks{c, namespace}\n}"} {"input": "package main\n\n\nvar Targets = map[string]TargetInterface{}\n\n\ntype TargetInterface interface {\n\tName() string\n\tBrief() string\n\tDescription() string\n\tHelp()\n\tRun([]string, CliOptions) (int, error)\n\tAliases() []string\n}\n\n\ntype TargetBase struct {\n\tname string\n\tinfo string\n\tbrief string\n\taliases []string\n}\n\n\n\n\nfunc getNextTargetArg(i *int, opts []string, t string) (val string) ", "output": "{\n\topt := opts[*i]\n\t*i++\n\tif len(opts) > *i {\n\t\tval = opts[*i]\n\t} else {\n\t\tLog.Err(\"missing argument to '%v' for target '%v'\", opt, t)\n\t}\n\treturn\n}"} {"input": "package load\n\nimport (\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"../common\"\n)\n\n\n\n\n\n\n\nfunc Misc() (*MiscStat, error) {\n\tbin, err := exec.LookPath(\"ps\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout, err := invoke.Command(bin, \"axo\", \"state\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlines := strings.Split(string(out), \"\\n\")\n\n\tret := MiscStat{}\n\tfor _, l := range lines {\n\t\tif strings.Contains(l, \"R\") {\n\t\t\tret.ProcsRunning++\n\t\t} else if strings.Contains(l, \"U\") {\n\t\t\tret.ProcsBlocked++\n\t\t}\n\t}\n\n\treturn &ret, nil\n}\n\nfunc Avg() (*AvgStat, error) ", "output": "{\n\tvalues, err := common.DoSysctrl(\"vm.loadavg\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tload1, err := strconv.ParseFloat(values[0], 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tload5, err := strconv.ParseFloat(values[1], 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tload15, err := strconv.ParseFloat(values[2], 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := &AvgStat{\n\t\tLoad1: float64(load1),\n\t\tLoad5: float64(load5),\n\t\tLoad15: float64(load15),\n\t}\n\n\treturn ret, nil\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n)\n\n\n\n\nfunc Logger(inner http.Handler, name string) http.Handler ", "output": "{\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tstart := time.Now()\n\n\t\tinner.ServeHTTP(w, r)\n\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"Method\": r.Method,\n\t\t\t\"Request URI\": r.RequestURI,\n\t\t\t\"Name\": name,\n\t\t\t\"Time\": time.Since(start),\n\t\t}).Debug(\"API request\")\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\nfunc TestLevel4(t *testing.T) {\n\th := 0\n\tfor i := 999; i > 99; i-- {\n\t\tfor j := 100; j < 1000; j++ {\n\t\t\tp := i * j\n\t\t\tr := xreverse(p)\n\t\t\tif xisPalindrome(r, p) {\n\t\t\t\tif h < p {\n\t\t\t\t\th = p\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif h != 906609 {\n\t\tt.Errorf(\"Error: largest palindrome should not be: %d \", h)\n\t}\n\n}\n\nfunc xisPalindrome(r, v int) bool {\n\treturn r == v\n}\n\n\n\nfunc xreverse(n int) (r int) ", "output": "{\n\tfor {\n\t\tif n > 0 {\n\t\t\tr = r * 10 + n % 10\n\t\t\tn = n / 10\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn r\n}"} {"input": "package refund\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/issue9/wechat/pay\"\n)\n\n\ntype Refund struct {\n\tPay *pay.Pay\n\tDeviceInfo string \n\tSignType string \n\tRefundFeeType string \n\tOpUserID string \n\tRefundAccount string \n}\n\nfunc (r *Refund) params(outRefundNO, outTradeNO, transactionID string, totalFee, refundFee int) map[string]string {\n\treturn map[string]string{\n\t\t\"device_info\": r.DeviceInfo,\n\t\t\"sign_type\": r.SignType,\n\t\t\"out_trade_no\": outTradeNO,\n\t\t\"transaction_id\": transactionID,\n\t\t\"out_refund_no\": outRefundNO,\n\t\t\"total_fee\": strconv.Itoa(totalFee),\n\t\t\"refund_fee\": strconv.Itoa(refundFee),\n\t\t\"refund_fee_type\": r.RefundFeeType,\n\t\t\"op_user_id\": r.OpUserID,\n\t\t\"refund_account\": r.RefundAccount,\n\t}\n}\n\n\nfunc (r *Refund) OutTradeNO(outRefundNO, outTradeNO string, totalFee, refundFee int) (*Return, error) {\n\tparams := r.params(outRefundNO, outTradeNO, \"\", totalFee, refundFee)\n\treturn r.refund(params)\n}\n\n\nfunc (r *Refund) TransactionID(outRefundNO, transactionID string, totalFee, refundFee int) (*Return, error) {\n\tparams := r.params(outRefundNO, \"\", transactionID, totalFee, refundFee)\n\treturn r.refund(params)\n}\n\n\n\nfunc (r *Refund) refund(params map[string]string) (*Return, error) ", "output": "{\n\tmaps, err := r.Pay.Refund(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = r.Pay.ValidateAll(r.SignType, maps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newReturn(maps)\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/mexisme/go-config/settings\"\n)\n\n\nfunc AddConfigItems(configKeys []string) {\n\tsettings.AddConfigItems(configKeys)\n}\n\n\nfunc AddConfigItemsWithPFlags(configKeys []string) error {\n\treturn settings.AddConfigItemsWithPFlags(configKeys)\n}\n\n\nfunc ApplyWith(key string, f func(interface{})) {\n\tsettings.ApplyWith(key, f)\n}\n\n\nfunc Get(key string) interface{} {\n\treturn settings.Get(key)\n}\n\n\nfunc GetBool(key string) bool {\n\treturn settings.GetBool(key)\n}\n\n\nfunc GetFloat64(key string) float64 {\n\treturn settings.GetFloat64(key)\n}\n\n\n\n\n\nfunc GetString(key string) string {\n\treturn settings.GetString(key)\n}\n\n\nfunc GetStringMap(key string) map[string]interface{} {\n\treturn settings.GetStringMap(key)\n}\n\n\nfunc GetStringMapString(key string) map[string]string {\n\treturn settings.GetStringMapString(key)\n}\n\n\nfunc GetStringSlice(key string) []string {\n\treturn settings.GetStringSlice(key)\n}\n\n\nfunc GetTime(key string) time.Time {\n\treturn settings.GetTime(key)\n}\n\n\nfunc GetDuration(key string) time.Duration {\n\treturn settings.GetDuration(key)\n}\n\n\nfunc IsSet(key string) bool {\n\treturn settings.IsSet(key)\n}\n\n\nfunc AllSettings() map[string]interface{} {\n\treturn settings.AllSettings()\n}\n\nfunc GetInt(key string) int ", "output": "{\n\treturn settings.GetInt(key)\n}"} {"input": "package aerospike\n\ntype operateCommand struct {\n\t*readCommand\n\n\tpolicy *WritePolicy\n\toperations []*Operation\n}\n\n\n\nfunc (cmd *operateCommand) writeBuffer(ifc command) error {\n\treturn cmd.setOperate(cmd.policy, cmd.key, cmd.operations)\n}\n\nfunc (cmd *operateCommand) Execute() error {\n\treturn cmd.execute(cmd)\n}\n\nfunc newOperateCommand(cluster *Cluster, policy *WritePolicy, key *Key, operations []*Operation) *operateCommand ", "output": "{\n\treturn &operateCommand{\n\t\treadCommand: newReadCommand(cluster, policy, key, nil),\n\t\tpolicy: policy,\n\t\toperations: operations,\n\t}\n}"} {"input": "package conversions\n\nimport \"jvmgo/ch11/instructions/base\"\nimport \"jvmgo/ch11/rtda\"\n\n\ntype L2D struct{ base.NoOperandsInstruction }\n\nfunc (self *L2D) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tl := stack.PopLong()\n\td := float64(l)\n\tstack.PushDouble(d)\n}\n\n\ntype L2F struct{ base.NoOperandsInstruction }\n\nfunc (self *L2F) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tl := stack.PopLong()\n\tf := float32(l)\n\tstack.PushFloat(f)\n}\n\n\ntype L2I struct{ base.NoOperandsInstruction }\n\n\n\nfunc (self *L2I) Execute(frame *rtda.Frame) ", "output": "{\n\tstack := frame.OperandStack()\n\tl := stack.PopLong()\n\ti := int32(l)\n\tstack.PushInt(i)\n}"} {"input": "package linebot\n\nimport (\n\t\"context\"\n\n\t\"github.com/line/line-bot-sdk-go/linebot\"\n\t\"github.com/utahta/momoclo-channel/config\"\n\t\"google.golang.org/appengine/urlfetch\"\n)\n\ntype (\n\tClient interface {\n\t\tReplyText(context.Context, string, string) error\n\t\tReplyImage(context.Context, string, string, string) error\n\t}\n\n\tclient struct {\n\t}\n)\n\n\nfunc New() Client {\n\treturn &client{}\n}\n\n\nfunc (c *client) ReplyText(ctx context.Context, replyToken, text string) error {\n\tbot, err := c.fromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttextMessage := linebot.NewTextMessage(text)\n\tif _, err := bot.ReplyMessage(replyToken, textMessage).Do(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\n\nfunc (c *client) fromContext(ctx context.Context) (*linebot.Client, error) {\n\treturn linebot.New(\n\t\tconfig.C().LineBot.ChannelSecret,\n\t\tconfig.C().LineBot.ChannelToken,\n\t\tlinebot.WithHTTPClient(urlfetch.Client(ctx)),\n\t)\n}\n\nfunc (c *client) ReplyImage(ctx context.Context, replyToken, originalContentURL, previewImageURL string) error ", "output": "{\n\tbot, err := c.fromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\timageMessage := linebot.NewImageMessage(originalContentURL, previewImageURL)\n\tif _, err := bot.ReplyMessage(replyToken, imageMessage).Do(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package storage\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tmgo \"github.com/ilius/mgo\"\n\t\"github.com/ilius/starcal-server/pkg/scal/settings\"\n)\n\nvar db *MongoDatabase\n\n\n\nfunc InitDB() {\n\tmongoDBDialInfo := &mgo.DialInfo{\n\t\tAddrs: []string{settings.MONGO_HOST},\n\t\tTimeout: 2 * time.Second,\n\t\tDatabase: settings.MONGO_DB_NAME,\n\t\tUsername: settings.MONGO_USERNAME,\n\t\tPassword: settings.MONGO_PASSWORD,\n\t}\n\n\tmongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tmongoSession.SetMode(mgo.Monotonic, true)\n\n\tdb = &MongoDatabase{\n\t\t*mongoSession.DB(settings.MONGO_DB_NAME),\n\t}\n}\n\nfunc GetDB() (Database, error) ", "output": "{\n\tif db == nil {\n\t\treturn nil, fmt.Errorf(\"database is not initialized\")\n\t}\n\treturn db, nil\n}"} {"input": "package ui\n\nimport (\n\t\"unsafe\"\n)\n\n\nimport \"C\"\n\ntype textfield struct {\n\t*controlSingleHWNDWithText\n\tchanged *event\n}\n\nvar editclass = toUTF16(\"EDIT\")\n\n\n\nfunc newTextField() *textfield {\n\treturn startNewTextField(0)\n}\n\nfunc newPasswordField() *textfield {\n\treturn startNewTextField(C.ES_PASSWORD)\n}\n\nfunc (t *textfield) Text() string {\n\treturn t.text()\n}\n\nfunc (t *textfield) SetText(text string) {\n\tt.setText(text)\n}\n\nfunc (t *textfield) OnChanged(f func()) {\n\tt.changed.set(f)\n}\n\nfunc (t *textfield) Invalid(reason string) {\n\tif reason == \"\" {\n\t\tC.textfieldHideInvalidBalloonTip(t.hwnd)\n\t\treturn\n\t}\n\tC.textfieldSetAndShowInvalidBalloonTip(t.hwnd, toUTF16(reason))\n}\n\nfunc (t *textfield) ReadOnly() bool {\n\treturn C.textfieldReadOnly(t.hwnd) != 0\n}\n\n\nfunc (t *textfield) SetReadOnly(readonly bool) {\n\tif readonly {\n\t\tC.textfieldSetReadOnly(t.hwnd, C.TRUE)\n\t\treturn\n\t}\n\tC.textfieldSetReadOnly(t.hwnd, C.FALSE)\n}\n\n\nfunc textfieldChanged(data unsafe.Pointer) {\n\tt := (*textfield)(data)\n\tt.changed.fire()\n}\n\nconst (\n\ttextfieldWidth = 107 \n\ttextfieldHeight = 14\n)\n\n\nfunc (t *textfield) xpreferredSize(d *sizing) (width, height int) {\n\treturn fromdlgunitsX(textfieldWidth, d), fromdlgunitsY(textfieldHeight, d)\n}\n\nfunc startNewTextField(style C.DWORD) *textfield ", "output": "{\n\thwnd := C.newControl(editclass,\n\t\tstyle|C.textfieldStyle,\n\t\tC.textfieldExtStyle) \n\tt := &textfield{\n\t\tcontrolSingleHWNDWithText:\t\tnewControlSingleHWNDWithText(hwnd),\n\t\tchanged: newEvent(),\n\t}\n\tt.fpreferredSize = t.xpreferredSize\n\tC.controlSetControlFont(t.hwnd)\n\tC.setTextFieldSubclass(t.hwnd, unsafe.Pointer(t))\n\treturn t\n}"} {"input": "package version\n\nimport (\n\tapi \"github.com/containerd/containerd/api/services/version\"\n\t\"github.com/containerd/containerd/plugin\"\n\tctrdversion \"github.com/containerd/containerd/version\"\n\tempty \"github.com/golang/protobuf/ptypes/empty\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\nvar _ api.VersionServer = &Service{}\n\nfunc init() {\n\tplugin.Register(\"version-grpc\", &plugin.Registration{\n\t\tType: plugin.GRPCPlugin,\n\t\tInit: New,\n\t})\n}\n\n\n\ntype Service struct {\n}\n\nfunc (s *Service) Register(server *grpc.Server) error {\n\tapi.RegisterVersionServer(server, s)\n\treturn nil\n}\n\nfunc (s *Service) Version(ctx context.Context, _ *empty.Empty) (*api.VersionResponse, error) {\n\treturn &api.VersionResponse{\n\t\tVersion: ctrdversion.Version,\n\t\tRevision: ctrdversion.Revision,\n\t}, nil\n}\n\nfunc New(ic *plugin.InitContext) (interface{}, error) ", "output": "{\n\treturn &Service{}, nil\n}"} {"input": "package organization\n\nimport (\n\t\"cf/api\"\n\t\"cf/configuration\"\n\t\"cf/models\"\n\t\"cf/requirements\"\n\t\"cf/terminal\"\n\t\"github.com/codegangsta/cli\"\n)\n\ntype ListOrgs struct {\n\tui terminal.UI\n\tconfig configuration.Reader\n\torgRepo api.OrganizationRepository\n}\n\nfunc NewListOrgs(ui terminal.UI, config configuration.Reader, orgRepo api.OrganizationRepository) (cmd ListOrgs) {\n\tcmd.ui = ui\n\tcmd.config = config\n\tcmd.orgRepo = orgRepo\n\treturn\n}\n\n\n\nfunc (cmd ListOrgs) Run(c *cli.Context) {\n\tcmd.ui.Say(\"Getting orgs as %s...\\n\", terminal.EntityNameColor(cmd.config.Username()))\n\n\tnoOrgs := true\n\ttable := cmd.ui.Table([]string{\"name\"})\n\n\tapiStatus := cmd.orgRepo.ListOrgs(func(org models.Organization) bool {\n\t\ttable.Print([][]string{{org.Name}})\n\t\tnoOrgs = false\n\t\treturn true\n\t})\n\n\tif apiStatus.IsNotSuccessful() {\n\t\tcmd.ui.Failed(\"Failed fetching orgs.\\n%s\", apiStatus.Message)\n\t\treturn\n\t}\n\n\tif noOrgs {\n\t\tcmd.ui.Say(\"No orgs found\")\n\t}\n}\n\nfunc (cmd ListOrgs) GetRequirements(reqFactory requirements.Factory, c *cli.Context) (reqs []requirements.Requirement, err error) ", "output": "{\n\treqs = []requirements.Requirement{\n\t\treqFactory.NewLoginRequirement(),\n\t}\n\treturn\n}"} {"input": "package assertion\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n)\n\nconst (\n\tEqualOp = \"equal\"\n\tNotEqualOp = \"not_equal\"\n\tContainsOp = \"contain\"\n\tNotContainsOp = \"not_contain\"\n)\n\ntype Operator func(val interface{}, expected interface{}) (bool, error)\n\nvar opMap = map[string]Operator{\n\tEqualOp: equal,\n\tNotEqualOp: notEqual,\n\tContainsOp: contain,\n\tNotContainsOp: notContain,\n}\n\nfunc AvailableOps() []string {\n\tvar ops []string\n\tfor op := range opMap {\n\t\tops = append(ops, op)\n\t}\n\treturn ops\n}\n\nfunc NewOperator(op string) (Operator, error) {\n\topFunc, ok := opMap[op]\n\tif !ok {\n\t\treturn nil, errors.New(\"operator not supported\")\n\t}\n\n\treturn opFunc, nil\n}\n\nfunc equal(val interface{}, expected interface{}) (bool, error) {\n\tif !reflect.DeepEqual(val, expected) {\n\t\treturn false, errors.New(fmt.Sprintf(\"expected equal %s, given %s\", expected, val))\n\t}\n\treturn true, nil\n}\n\nfunc notEqual(val interface{}, expected interface{}) (bool, error) {\n\tif reflect.DeepEqual(val, expected) {\n\t\treturn false, errors.New(fmt.Sprintf(\"expected not equal %s, given %s\", expected, val))\n\t}\n\treturn true, nil\n}\n\n\n\nfunc notContain(val interface{}, expected interface{}) (bool, error) {\n\tvalStr := val.(string)\n\texpectedStr := expected.(string)\n\tif strings.Contains(valStr, expectedStr) {\n\t\treturn false, errors.New(fmt.Sprintf(\"expected not contain %s, given %s\", expected, val))\n\t}\n\treturn true, nil\n}\n\nfunc contain(val interface{}, expected interface{}) (bool, error) ", "output": "{\n\tvalStr := val.(string)\n\texpectedStr := expected.(string)\n\tif !strings.Contains(valStr, expectedStr) {\n\t\treturn false, errors.New(fmt.Sprintf(\"expected contain %s, given %s\", expected, val))\n\t}\n\treturn true, nil\n}"} {"input": "package pool\n\nimport \"sync/atomic\"\n\n\ntype WorkUnit interface {\n\n\tWait()\n\n\tValue() interface{}\n\n\tError() error\n\n\tCancel()\n\n\tIsCancelled() bool\n}\n\nvar _ WorkUnit = new(workUnit)\n\n\ntype workUnit struct {\n\tvalue interface{}\n\terr error\n\tdone chan struct{}\n\tfn WorkFunc\n\tcancelled atomic.Value\n\tcancelling atomic.Value\n\twriting atomic.Value\n}\n\n\nfunc (wu *workUnit) Cancel() {\n\twu.cancelWithError(&ErrCancelled{s: errCancelled})\n}\n\nfunc (wu *workUnit) cancelWithError(err error) {\n\n\twu.cancelling.Store(struct{}{})\n\n\tif wu.writing.Load() == nil && wu.cancelled.Load() == nil {\n\t\twu.cancelled.Store(struct{}{})\n\t\twu.err = err\n\t\tclose(wu.done)\n\t}\n}\n\n\nfunc (wu *workUnit) Wait() {\n\t<-wu.done\n}\n\n\n\n\n\nfunc (wu *workUnit) Error() error {\n\treturn wu.err\n}\n\n\n\n\nfunc (wu *workUnit) IsCancelled() bool {\n\twu.writing.Store(struct{}{}) \n\treturn wu.cancelled.Load() != nil\n}\n\nfunc (wu *workUnit) Value() interface{} ", "output": "{\n\treturn wu.value\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n)\n\nfunc PK(endpoint, metric string, tags map[string]string) string {\n\tif tags == nil || len(tags) == 0 {\n\t\treturn fmt.Sprintf(\"%s/%s\", endpoint, metric)\n\t}\n\treturn fmt.Sprintf(\"%s/%s/%s\", endpoint, metric, SortedTags(tags))\n}\n\nfunc PK2(endpoint, counter string) string {\n\treturn fmt.Sprintf(\"%s/%s\", endpoint, counter)\n}\n\n\n\nfunc Checksum(endpoint string, metric string, tags map[string]string) string {\n\tpk := PK(endpoint, metric, tags)\n\treturn Md5(pk)\n}\n\nfunc ChecksumOfUUID(endpoint, metric string, tags map[string]string, dstype string, step int64) string {\n\treturn Md5(UUID(endpoint, metric, tags, dstype, int(step)))\n}\n\nfunc UUID(endpoint, metric string, tags map[string]string, dstype string, step int) string ", "output": "{\n\tif tags == nil || len(tags) == 0 {\n\t\treturn fmt.Sprintf(\"%s/%s/%s/%d\", endpoint, metric, dstype, step)\n\t}\n\treturn fmt.Sprintf(\"%s/%s/%s/%s/%d\", endpoint, metric, SortedTags(tags), dstype, step)\n}"} {"input": "package geoip_test\n\nimport (\n\t\"github.com/corestoreio/pkg/net/geoip\"\n\t\"github.com/corestoreio/pkg/store\"\n\t\"github.com/corestoreio/pkg/store/scope\"\n)\n\ntype storeFinderMock struct{}\n\n\n\nfunc (storeFinderMock) StoreIDbyCode(runMode scope.TypeID, storeCode string) (websiteID, storeID uint32, err error) {\n\treturn\n}\n\n\nvar (\n\t_ geoip.StoreFinder = (*storeFinderMock)(nil)\n\t_ store.Finder = (*storeFinderMock)(nil)\n)\n\nfunc (storeFinderMock) DefaultStoreID(runMode scope.TypeID) (websiteID, storeID uint32, err error) ", "output": "{\n\treturn\n}"} {"input": "package storage\n\nimport (\n\tastorage \"aqua/common/storage\"\n\t\"aqua/connect_server/config\"\n\n\t\"github.com/foolbread/fbcommon/golog\"\n)\n\nconst default_count = 5\n\nfunc InitStorageManager() {\n\tgolog.Info(\"initing login storage manager...\")\n\tg_storage = newStorageManager()\n\n\tinfos := config.GetConfig().GetSessionDBInfos()\n\tfor k, v := range infos {\n\t\tfor i := 0; i < default_count; i++ {\n\t\t\thnl := astorage.NewStorageHandler(v)\n\t\t\tif hnl != nil {\n\t\t\t\tg_storage.session_storages[k] = append(g_storage.session_storages[k], hnl)\n\t\t\t}\n\t\t}\n\t}\n\n}\n\n\n\nvar g_storage *storageManager\n\ntype storageManager struct {\n\tsession_storages [][]*astorage.StorageHandler\n}\n\nfunc newStorageManager() *storageManager {\n\tret := new(storageManager)\n\tret.session_storages = make([][]*astorage.StorageHandler, len(config.GetConfig().GetSessionDBInfos()))\n\n\treturn ret\n}\n\nfunc (s *storageManager) GetSessionHandler(cid string) *astorage.StorageHandler {\n\tby := astorage.Md5ToByte(cid)\n\tas := s.session_storages[int(by)%len(s.session_storages)]\n\treturn as[int(by)%len(as)]\n}\n\nfunc GetStorage() *storageManager ", "output": "{\n\treturn g_storage\n}"} {"input": "package operations\n\n\n\nimport (\n\t\"github.com/denkhaus/bitshares/types\"\n\t\"github.com/denkhaus/bitshares/util\"\n\t\"github.com/juju/errors\"\n)\n\nfunc init() {\n\ttypes.OperationMap[types.OperationTypeCommitteeMemberCreate] = func() types.Operation {\n\t\top := &CommitteeMemberCreateOperation{}\n\t\treturn op\n\t}\n}\n\ntype CommitteeMemberCreateOperation struct {\n\ttypes.OperationFee\n\tCommitteeMemberAccount types.AccountID `json:\"committee_member_account\"`\n\tURL types.String `json:\"url\"`\n}\n\n\n\nfunc (p CommitteeMemberCreateOperation) Marshal(enc *util.TypeEncoder) error {\n\tif err := enc.Encode(int8(p.Type())); err != nil {\n\t\treturn errors.Annotate(err, \"encode OperationType\")\n\t}\n\tif err := enc.Encode(p.Fee); err != nil {\n\t\treturn errors.Annotate(err, \"encode Fee\")\n\t}\n\tif err := enc.Encode(p.CommitteeMemberAccount); err != nil {\n\t\treturn errors.Annotate(err, \"encode CommitteeMemberAccount\")\n\t}\n\tif err := enc.Encode(p.URL); err != nil {\n\t\treturn errors.Annotate(err, \"encode URL\")\n\t}\n\n\treturn nil\n}\n\nfunc (p CommitteeMemberCreateOperation) Type() types.OperationType ", "output": "{\n\treturn types.OperationTypeCommitteeMemberCreate\n}"} {"input": "package events\n\nimport \"github.com/gophercloud/gophercloud\"\n\nvar apiVersion = \"v1\"\nvar apiName = \"events\"\n\nfunc commonURL(client *gophercloud.ServiceClient) string {\n\treturn client.ServiceURL(apiVersion, apiName)\n}\n\n\n\nfunc idURL(client *gophercloud.ServiceClient, id string) string {\n\treturn client.ServiceURL(apiVersion, apiName, id)\n}\n\nfunc getURL(client *gophercloud.ServiceClient, id string) string {\n\treturn idURL(client, id)\n}\n\nfunc listURL(client *gophercloud.ServiceClient) string ", "output": "{\n\treturn commonURL(client)\n}"} {"input": "package run\n\nimport (\n\t\"fmt\"\n\n\t\"go.pedge.io/proto/time\"\n\n\t\"github.com/pachyderm/pachyderm/src/pkg/timing\"\n\t\"github.com/pachyderm/pachyderm/src/pps\"\n\t\"github.com/pachyderm/pachyderm/src/pps/store\"\n)\n\ntype pipelineRunLogWriter struct {\n\tpipelineRunID string\n\tcontainerID string\n\tnode string\n\toutputStream pps.OutputStream\n\ttimer timing.Timer\n\tstoreClient store.Client\n}\n\nfunc newPipelineRunLogWriter(\n\tpipelineRunID string,\n\tcontainerID string,\n\tnode string,\n\toutputStream pps.OutputStream,\n\ttimer timing.Timer,\n\tstoreClient store.Client,\n) *pipelineRunLogWriter {\n\treturn &pipelineRunLogWriter{\n\t\tpipelineRunID,\n\t\tcontainerID,\n\t\tnode,\n\t\toutputStream,\n\t\ttimer,\n\t\tstoreClient,\n\t}\n}\n\n\n\nfunc (w *pipelineRunLogWriter) Write(p []byte) (int, error) ", "output": "{\n\tc := make([]byte, len(p))\n\tif n := copy(c, p); n != len(p) {\n\t\treturn 0, fmt.Errorf(\"tried to copy %d bytes, only copied %d bytes\", len(p), n)\n\t}\n\tif err := w.storeClient.AddPipelineRunLogs(\n\t\t&pps.PipelineRunLog{\n\t\t\tPipelineRunId: w.pipelineRunID,\n\t\t\tContainerId: w.containerID,\n\t\t\tNode: w.node,\n\t\t\tOutputStream: w.outputStream,\n\t\t\tTimestamp: prototime.TimeToTimestamp(w.timer.Now()),\n\t\t\tData: c,\n\t\t},\n\t); err != nil {\n\t\treturn 0, err\n\t}\n\treturn len(p), nil\n}"} {"input": "package dsc\n\nimport \"fmt\"\n\n\ntype TableDescriptor struct {\n\tTable string\n\tAutoincrement bool\n\tPkColumns []string\n\tColumns []string\n\tColumnTypes map[string]string\n\tNullables map[string]bool\n\tOrderColumns []string\n\tSchema []map[string]interface{} \n\tSchemaURL string \n\tFromQuery string \n\tFromQueryAlias string\n}\n\n\n\n\ntype TableDescriptorRegistry interface {\n\tHas(table string) bool\n\n\tGet(table string) *TableDescriptor\n\n\tRegister(descriptor *TableDescriptor) error\n\n\tTables() []string\n}\n\nfunc (t *TableDescriptor) From() string ", "output": "{\n\tif t.FromQuery != \"\" {\n\t\tif t.FromQueryAlias == \"\" {\n\t\t\tt.FromQueryAlias = \"t\"\n\t\t}\n\t\treturn fmt.Sprintf(\"(%v) AS %v\", t.FromQuery, t.FromQueryAlias)\n\t}\n\treturn t.Table\n}"} {"input": "package qtypes\n\nimport (\n\t\"strings\"\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/qnib/qframe-utils\"\n\t\"fmt\"\n)\n\nconst (\n\tMsgCEE = \"cee\"\n\tMsgTCP = \"tcp\"\n\tMsgFile = \"file\"\n\tMsgDLOG = \"docker-log\"\n\tMsgMetric = \"metric\" \n)\n\n\ntype Message struct {\n\tBase\n\tContainer types.ContainerJSON\n\tName \tstring \t`json:\"name\"`\n\tLogLevel string\t\t\t\t`json:\"loglevel\"`\n\tMessageType\tstring \t`json:\"type\"`\n\tMessage string \t`json:\"value\"`\n\tKV\t\t\tmap[string]string \t`json:\"data\"`\n}\n\nfunc NewMessage(base Base, name, mType, msg string) Message {\n\tm := Message{\n\t\tBase: base,\n\t\tName: name,\n\t\tContainer: types.ContainerJSON{},\n\t\tLogLevel: \"INFO\",\n\t\tMessageType: mType,\n\t\tMessage: msg,\n\t\tKV: map[string]string{},\n\t}\n\tm.SourceID = int(qutils.GetGID())\n\treturn m\n}\n\nfunc NewContainerMessage(base Base, cnt types.ContainerJSON, name, mType, msg string) Message {\n\tm := NewMessage(base, name, mType, msg)\n\tm.Container = cnt\n\tm.ID = m.GenContainerMsgID()\n\treturn m\n}\n\n\n\n\nfunc (m *Message) GetContainerName() string {\n\tif m.Container.Name != \"\" {\n\t\treturn strings.Trim(m.Container.Name, \"/\")\n\t} else {\n\t\treturn \"\"\n\t}\n}\n\nfunc (m *Message) GenContainerMsgID() string ", "output": "{\n\ts := fmt.Sprintf(\"%s-%d-%s\", m.Container.ID, m.Time.UnixNano(), m.Message)\n\treturn Sha1HashString(s)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/minio-io/cli\"\n\t\"github.com/minio-io/mc/pkg/client/s3\"\n)\n\n\n\n\nfunc doMakeBucketCmd(ctx *cli.Context) ", "output": "{\n\turlStr, err := parseURL(ctx.Args().First())\n\tif err != nil {\n\t\tfatal(err.Error())\n\t}\n\n\tbucket, err := url2Bucket(urlStr)\n\tif err != nil {\n\t\tfatal(err.Error())\n\t}\n\n\tclnt, err := getNewClient(globalDebugFlag, urlStr)\n\tif err != nil {\n\t\tfatal(err.Error())\n\t}\n\n\tif !s3.IsValidBucketName(bucket) {\n\t\tfatal(errInvalidbucket.Error())\n\t}\n\n\terr = clnt.PutBucket(bucket)\n\tif err != nil {\n\t\tfatal(err.Error())\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\nfunc updateServer(id uint64) error {\n\tc, err := getClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsvr, err := c.GetServer(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsb := c.NewServerBuilder()\n\tsb.Use(*svr)\n\n\tsb.MaxQPS(1000)\n\tsb.NoCircuitBreaker() \n\tsb.NoHeathCheck() \n\n\t_, err = sb.Commit()\n\treturn err\n}\n\nfunc deleteServer(id uint64) error {\n\tc, err := getClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.RemoveServer(id)\n}\n\nfunc createServer() error ", "output": "{\n\tc, err := getClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsb := c.NewServerBuilder()\n\tsb.Addr(\"127.0.0.1:8080\").HTTPBackend().MaxQPS(100)\n\n\tsb.CheckHTTPCode(\"/check/path\", time.Second*10, time.Second*30)\n\n\tsb.CircuitBreakerCheckPeriod(time.Second)\n\tsb.CircuitBreakerCloseToHalfTimeout(time.Second * 60)\n\tsb.CircuitBreakerHalfTrafficRate(10)\n\tsb.CircuitBreakerHalfToCloseCondition(2)\n\tsb.CircuitBreakerHalfToOpenCondition(90)\n\n\tid, err := sb.Commit()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"server id is: %d\", id)\n\n\tc.AddBind(1, id)\n\n\tc.RemoveBind(1, id)\n\n\tc.AddBind(2, id)\n\treturn nil\n}"} {"input": "package encrypt\n\nimport (\n\t\"io/ioutil\"\n)\n\n\ntype KeyProvider interface {\n\tGet(params map[string]interface{}) (string, error)\n}\n\n\ntype FileKeyProvider struct {\n\tpath string\n}\n\n\n\nfunc NewFileKeyProvider(path string) KeyProvider {\n\treturn &FileKeyProvider{\n\t\tpath: path,\n\t}\n}\n\n\n\n\nfunc (f *FileKeyProvider) Get(params map[string]interface{}) (string, error) ", "output": "{\n\tb, err := ioutil.ReadFile(f.path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(b), nil\n}"} {"input": "package handler\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/labstack/echo\"\n)\n\ntype (\n\tUser struct {\n\t\tName string `json:\"name\" form:\"name\"`\n\t\tEmail string `json:\"name\" form:\"name\"`\n\t}\n\thandler struct {\n\t\tdb map[string]*User\n\t}\n)\n\nfunc (h *handler) createUser(c echo.Context) error {\n\tu := new(User)\n\tif err := c.Bind(u); err != nil {\n\t\treturn err\n\t}\n\treturn c.JSON(http.StatusOK, u)\n}\n\n\n\nfunc (h *handler) getUser(c echo.Context) error ", "output": "{\n\temail := c.Param(\"email\")\n\tuser := h.db[email]\n\tif user == nil {\n\t\treturn echo.NewHTTPError(http.StatusNotFound, \"user not found\")\n\t}\n\treturn c.JSON(http.StatusOK, user)\n}"} {"input": "package x11\n\nimport (\n\t\"C\"\n\t\"unsafe\"\n)\n\ntype SelectionEvent C.XSelectionEvent\n\nfunc (evt *SelectionEvent) Requestor() Window {\n\treturn Window(evt.requestor)\n}\n\nfunc (evt *SelectionEvent) Selection() Atom {\n\treturn Atom(evt.selection)\n}\n\n\n\nfunc (evt *SelectionEvent) Property() Atom {\n\treturn Atom(evt.property)\n}\n\nfunc (evt *SelectionEvent) When() C.Time {\n\treturn evt.time\n}\n\nfunc (evt *SelectionEvent) ToEvent() *Event {\n\treturn (*Event)(unsafe.Pointer(evt))\n}\n\nfunc (evt *SelectionEvent) Target() Atom ", "output": "{\n\treturn Atom(evt.target)\n}"} {"input": "package v1beta1\n\nimport (\n\t\"knative.dev/pkg/apis\"\n\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tduckv1 \"knative.dev/pkg/apis/duck/v1\"\n\t\"knative.dev/pkg/kmeta\"\n)\n\n\n\n\n\n\n\ntype PingSource struct {\n\tmetav1.TypeMeta `json:\",inline\"`\n\tmetav1.ObjectMeta `json:\"metadata,omitempty\"`\n\n\tSpec PingSourceSpec `json:\"spec,omitempty\"`\n\tStatus PingSourceStatus `json:\"status,omitempty\"`\n}\n\n\nvar (\n\t_ runtime.Object = (*PingSource)(nil)\n\t_ kmeta.OwnerRefable = (*PingSource)(nil)\n\t_ apis.Validatable = (*PingSource)(nil)\n\t_ apis.Defaultable = (*PingSource)(nil)\n\t_ apis.HasSpec = (*PingSource)(nil)\n\t_ duckv1.KRShaped = (*PingSource)(nil)\n)\n\n\ntype PingSourceSpec struct {\n\tduckv1.SourceSpec `json:\",inline\"`\n\n\tSchedule string `json:\"schedule,omitempty\"`\n\n\tTimezone string `json:\"timezone,omitempty\"`\n\n\tJsonData string `json:\"jsonData,omitempty\"`\n}\n\n\ntype PingSourceStatus struct {\n\tduckv1.SourceStatus `json:\",inline\"`\n}\n\n\n\n\ntype PingSourceList struct {\n\tmetav1.TypeMeta `json:\",inline\"`\n\tmetav1.ListMeta `json:\"metadata,omitempty\"`\n\tItems []PingSource `json:\"items\"`\n}\n\n\n\n\nfunc (p *PingSource) GetStatus() *duckv1.Status ", "output": "{\n\treturn &p.Status.Status\n}"} {"input": "package client\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/mattimo/fluxtftp\"\n\t\"io\"\n\t\"net\"\n)\n\ntype FluxClient struct {\n\tConn net.Conn\n}\n\nfunc NewFluxClient(dial string) (*FluxClient, error) {\n\tf := &FluxClient{}\n\n\taddr, err := net.ResolveUnixAddr(\"unix\", dial)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn, err := net.DialUnix(\"unix\", nil, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf.Conn = conn\n\n\treturn f, nil\n}\n\n\n\nfunc (f *FluxClient) Close() error {\n\treturn f.Conn.Close()\n}\n\nfunc (f *FluxClient) Add(reader io.Reader) error ", "output": "{\n\n\tbuf := &bytes.Buffer{}\n\tbuf.ReadFrom(reader)\n\n\tmessage, err := json.Marshal(&fluxtftp.ControlRequest{\n\t\tVerb: \"Upload\",\n\t\tData: buf.Bytes(),\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = f.Conn.Write(message)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tanswer := &fluxtftp.ControlResponse{}\n\tdec := json.NewDecoder(f.Conn)\n\terr = dec.Decode(answer)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif answer.Error != 0 {\n\t\treturn fmt.Errorf(\"Server Error: %s\", answer.Message)\n\t}\n\n\treturn nil\n}"} {"input": "package gorocksdb\n\n\nimport \"C\"\n\n\ntype Cache struct {\n\tc *C.rocksdb_cache_t\n}\n\n\nfunc NewLRUCache(capacity int) *Cache {\n\treturn NewNativeCache(C.rocksdb_cache_create_lru(C.size_t(capacity)))\n}\n\n\nfunc NewNativeCache(c *C.rocksdb_cache_t) *Cache {\n\treturn &Cache{c}\n}\n\n\n\n\nfunc (c *Cache) Destroy() ", "output": "{\n\tC.rocksdb_cache_destroy(c.c)\n\tc.c = nil\n}"} {"input": "package servo_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n\t\"github.com/fgrosse/servo\"\n\t\"fmt\"\n)\n\nfunc TestServo(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Servo Test Suite\")\n}\n\ntype TestBundle struct {}\n\n\n\ntype SomeService struct {}\n\nfunc NewRecursiveService(*SomeService) *SomeService {\n\treturn &SomeService{}\n}\n\nfunc NewService() *SomeService {\n\treturn &SomeService{}\n}\n\nfunc NewServiceWithParam(param interface{}) *SomeService {\n\tpanic(param)\n\treturn &SomeService{}\n}\n\n\ntype ServerMock struct {\n\tRunHasBeenCalled bool\n\tReturnError bool\n\n\tParameter1, Parameter2 string\n}\n\nfunc NewServerMockWithParams(param1, param2 string) *ServerMock {\n\tExpect(param1).To(Equal(\"foo\"), `NewServerMockWithParams should always be called with the values \"foo\" and \"bar\"`)\n\tExpect(param2).To(Equal(\"bar\"), `NewServerMockWithParams should always be called with the values \"foo\" and \"bar\"`)\n\n\treturn &ServerMock{\n\t\tParameter1: param1,\n\t\tParameter2: param2,\n\t}\n}\n\nfunc (s *ServerMock) Run() error {\n\ts.RunHasBeenCalled = true\n\tif s.ReturnError {\n\t\treturn fmt.Errorf(\"ServerMock was told to return an error!\")\n\t}\n\n\treturn nil\n}\n\nfunc (b *TestBundle) Boot(kernel *servo.Kernel) ", "output": "{\n\tkernel.RegisterType(\"test_bundle.my_type\", NewService)\n}"} {"input": "package reaperlog\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/rifflock/lfshook\"\n\t\"go.mozilla.org/mozlogrus\"\n)\n\nvar config LogConfig\n\ntype LogConfig struct {\n\tExtras bool\n}\n\nfunc EnableExtras() {\n\tconfig.Extras = true\n}\n\nfunc EnableMozlog() {\n\tmozlogrus.Enable(\"Reaper\")\n}\n\nfunc Extras() bool {\n\treturn config.Extras\n}\n\n\n\nfunc AddLogFile(filename string) {\n\tlog.AddHook(lfshook.NewHook(lfshook.PathMap{\n\t\tlog.DebugLevel: filename,\n\t\tlog.InfoLevel: filename,\n\t\tlog.WarnLevel: filename,\n\t\tlog.ErrorLevel: filename,\n\t\tlog.FatalLevel: filename,\n\t\tlog.PanicLevel: filename,\n\t}))\n}\n\nfunc Debug(format string, args ...interface{}) {\n\tlog.Debugf(format, args...)\n}\n\nfunc Info(format string, args ...interface{}) {\n\tlog.Infof(format, args...)\n}\n\nfunc Warning(format string, args ...interface{}) {\n\tlog.Warningf(format, args...)\n}\n\nfunc Fatal(format string, args ...interface{}) {\n\tlog.Fatalf(format, args...)\n}\n\nfunc Panic(format string, args ...interface{}) {\n\tlog.Panicf(format, args...)\n}\n\nfunc Error(format string, args ...interface{}) {\n\tlog.Errorf(format, args...)\n}\n\nfunc SetConfig(c *LogConfig) ", "output": "{\n\tconfig = *c\n}"} {"input": "package gorever\n\nimport (\n\t\"fmt\"\n\t\"github.com/inconshreveable/go-update\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype Updater struct {\n\tnewVersion bool\n\tch chan bool\n}\n\nfunc NewUpdater(ch chan bool) (*Updater, error) {\n\tu := &Updater{\n\t\tnewVersion: true,\n\t\tch: ch,\n\t}\n\n\tgo func(updater *Updater) {\n\t\ttime.Sleep(6*time.Second)\n\t\tupdater.ch <- true\n\t}(u)\n\n\treturn u, nil\n}\n\nfunc (u *Updater) HasNewVersion() bool {\n\treturn u.newVersion\n}\n\n\n\nfunc (u *Updater) doUpdate(url string) error {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\terr = update.Apply(resp.Body, update.Options{})\n\tif err != nil {\n\t\tif rerr := update.RollbackError(err); rerr != nil {\n\t\t\treturn fmt.Errorf(\"Failed to rollback from bad update: %v\", rerr)\n\t\t}\n\t}\n\treturn err\n}\n\nfunc (u *Updater) Update() error ", "output": "{\n\tu.newVersion = false\n\turl := \"http://localhost:8078/gorever-poc\" \n\treturn u.doUpdate(url)\n}"} {"input": "package serial\n\nimport (\n\t\"flag\"\n\n\t\"github.com/juju/govmomi/govc/cli\"\n\t\"github.com/juju/govmomi/govc/flags\"\n\t\"golang.org/x/net/context\"\n)\n\ntype disconnect struct {\n\t*flags.VirtualMachineFlag\n\n\tdevice string\n}\n\n\n\nfunc (cmd *disconnect) Register(f *flag.FlagSet) {\n\tf.StringVar(&cmd.device, \"device\", \"\", \"serial port device name\")\n}\n\nfunc (cmd *disconnect) Process() error { return nil }\n\nfunc (cmd *disconnect) Run(f *flag.FlagSet) error {\n\tvm, err := cmd.VirtualMachine()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif vm == nil {\n\t\treturn flag.ErrHelp\n\t}\n\n\tdevices, err := vm.Device(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td, err := devices.FindSerialPort(cmd.device)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn vm.EditDevice(context.TODO(), devices.DisconnectSerialPort(d))\n}\n\nfunc init() ", "output": "{\n\tcli.Register(\"device.serial.disconnect\", &disconnect{})\n}"} {"input": "package api\n\n\ntype UserInfo interface {\n\tGetName() string\n\tGetUID() string\n\tGetScope() string\n\tGetExtra() map[string]string\n}\n\n\n\ntype UserIdentityInfo interface {\n\tGetUserName() string\n\tGetProviderName() string\n\tGetExtra() map[string]string\n}\n\n\ntype UserIdentityMapper interface {\n\tUserFor(identityInfo UserIdentityInfo) (UserInfo, error)\n}\n\ntype Client interface {\n\tGetId() string\n\tGetSecret() string\n\tGetRedirectUri() string\n\tGetUserData() interface{}\n}\n\ntype Grant struct {\n\tClient Client\n\tScope string\n\tExpiration int64\n\tRedirectURI string\n}\n\ntype DefaultUserInfo struct {\n\tName string\n\tUID string\n\tScope string\n\tExtra map[string]string\n}\n\nfunc (i *DefaultUserInfo) GetName() string {\n\treturn i.Name\n}\n\nfunc (i *DefaultUserInfo) GetUID() string {\n\treturn i.UID\n}\n\n\n\nfunc (i *DefaultUserInfo) GetExtra() map[string]string {\n\treturn i.Extra\n}\n\ntype DefaultUserIdentityInfo struct {\n\tUserName string\n\tProviderName string\n\tExtra map[string]string\n}\n\n\nfunc NewDefaultUserIdentityInfo(username string) DefaultUserIdentityInfo {\n\treturn DefaultUserIdentityInfo{\n\t\tUserName: username,\n\t\tExtra: make(map[string]string),\n\t}\n}\n\nfunc (i *DefaultUserIdentityInfo) GetUserName() string {\n\treturn i.UserName\n}\n\nfunc (i *DefaultUserIdentityInfo) GetProviderName() string {\n\treturn i.ProviderName\n}\n\nfunc (i *DefaultUserIdentityInfo) GetExtra() map[string]string {\n\treturn i.Extra\n}\n\nfunc (i *DefaultUserInfo) GetScope() string ", "output": "{\n\treturn i.Scope\n}"} {"input": "package fake\n\nimport (\n\tv1 \"github.com/gravitational/workshop/crd/controller/pkg/generated/clientset/versioned/typed/nginxcontroller/v1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeTrainingV1 struct {\n\t*testing.Fake\n}\n\n\n\n\n\nfunc (c *FakeTrainingV1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeTrainingV1) Nginxes(namespace string) v1.NginxInterface ", "output": "{\n\treturn &FakeNginxes{c, namespace}\n}"} {"input": "package command\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/hashicorp/nomad/api\"\n\t\"github.com/mitchellh/cli\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar _ cli.Command = &LicenseGetCommand{}\n\nfunc TestCommand_LicenseGet_OSSErr(t *testing.T) {\n\tt.Parallel()\n\n\tsrv, _, url := testServer(t, false, nil)\n\tdefer srv.Shutdown()\n\n\tui := cli.NewMockUi()\n\tcmd := &LicenseGetCommand{Meta: Meta{Ui: ui}}\n\n\tcode := cmd.Run([]string{\"-address=\" + url})\n\tif srv.Enterprise {\n\t\trequire.Equal(t, 0, code)\n\t} else {\n\t\trequire.Equal(t, 1, code)\n\t\trequire.Contains(t, ui.ErrorWriter.String(), \"Nomad Enterprise only endpoint\")\n\t}\n}\n\n\n\nfunc TestOutputLicenseReply(t *testing.T) ", "output": "{\n\tnow := time.Now()\n\tlic := &api.LicenseReply{\n\t\tLicense: &api.License{\n\t\t\tLicenseID: \"licenseID\",\n\t\t\tCustomerID: \"customerID\",\n\t\t\tInstallationID: \"*\",\n\t\t\tIssueTime: now,\n\t\t\tStartTime: now,\n\t\t\tExpirationTime: now.Add(1 * time.Hour),\n\t\t\tTerminationTime: now,\n\t\t\tProduct: \"nomad\",\n\t\t\tFlags: map[string]interface{}{\n\t\t\t\t\"\": nil,\n\t\t\t},\n\t\t},\n\t}\n\n\tui := cli.NewMockUi()\n\n\trequire.Equal(t, 0, OutputLicenseReply(ui, lic))\n\n\tout := ui.OutputWriter.String()\n\trequire.Contains(t, out, \"Customer ID\")\n\trequire.Contains(t, out, \"License ID\")\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"testing\"\n)\n\nconst (\n\tmetricCount = 4\n)\n\nvar (\n\tfluentdJson = Message{1, 4, 456, 0}\n)\n\ntype Message struct {\n\tup int\n\tbufferQueueLength int\n\tbufferTotalQueuedSize float64\n\tretryCount int\n}\n\n\n\nfunc TestFluentdStatus(t *testing.T) {\n\tdata, err := json.Marshal(fluentdJson)\n\tif err != nil {\n\t\tt.Error(err)\n\t\tos.Exit(1)\n\t}\n\n\tcheckFluentdStatus(t, data, metricCount)\n}\n\nfunc checkFluentdStatus(t *testing.T, status []byte, metricCount int) ", "output": "{\n\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(status))\n\t})\n\tserver := httptest.NewServer(handler)\n\n\te := NewExporter(server.URL)\n\tch := make(chan prometheus.Metric)\n\n\tgo func() {\n\t\tdefer close(ch)\n\t\te.Collect(ch)\n\t}()\n\n\tm := <-ch\n\tif m == nil {\n\t\tt.Error(\"expected metric but got nil\")\n\t}\n\n\tif <-ch != nil {\n\t\tt.Error(\"expected closed channel\")\n\t}\n}"} {"input": "package miner\n\nimport \"net/http\"\n\nconst (\n\tWaitTime = 5\n\n\n\tGET = \"GET\"\n\tPOST = \"POST\"\n\tPOSTJSON = \"POSTJSON\"\n\tPOSTXML = \"POSTXML\"\n\tPOSTFILE = \"POSTFILE\"\n\tPUT = \"PUT\"\n\tPUTJSON = \"PUTJSON\"\n\tPUTXML = \"PUTXML\"\n\tPUTFILE = \"PUTFILE\"\n\tDELETE = \"DELETE\"\n\tOTHER = \"OTHER\" \n\n\n\tHTTPFORMContentType = \"application/x-www-form-urlencoded\"\n\tHTTPJSONContentType = \"application/json\"\n\tHTTPXMLContentType = \"text/xml\"\n\tHTTPFILEContentType = \"multipart/form-data\"\n)\n\nvar (\n\tdefaultUserAgent = \"Marmot\"\n\n\tDefaultHeader = map[string][]string{\n\t\t\"User-Agent\": {\n\t\t\tdefaultUserAgent,\n\t\t},\n\t}\n\n\tDefaultTimeOut = 30\n)\n\n\n\n\n\nfunc MergeCookie(before []*http.Cookie, after []*http.Cookie) []*http.Cookie {\n\tcs := make(map[string]*http.Cookie)\n\n\tfor _, b := range before {\n\t\tcs[b.Name] = b\n\t}\n\n\tfor _, a := range after {\n\t\tif len(a.Value) > 0 {\n\t\t\tcs[a.Name] = a\n\t\t}\n\t}\n\n\tres := make([]*http.Cookie, 0, len(cs))\n\n\tfor _, q := range cs {\n\t\tres = append(res, q)\n\t}\n\n\treturn res\n\n}\n\n\nfunc CloneHeader(h map[string][]string) map[string][]string {\n\tif h == nil || len(h) == 0 {\n\t\th = DefaultHeader\n\t\treturn h\n\t}\n\n\tif len(h[\"User-Agent\"]) == 0 {\n\t\th[\"User-Agent\"] = []string{defaultUserAgent}\n\t}\n\treturn CopyM(h)\n}\n\nfunc SetGlobalTimeout(num int) ", "output": "{\n\tDefaultTimeOut = num\n}"} {"input": "package macos\n\n\n\nimport (\n\t\"os\"\n\n\t\"github.com/martinlindhe/formats/parse\"\n)\n\n\nfunc CodeDirectory(c *parse.Checker) (*parse.ParsedLayout, error) {\n\n\tif !isCodeDirectory(c.Header) {\n\t\treturn nil, nil\n\t}\n\treturn parseCodeDirectory(c.File, c.ParsedLayout)\n}\n\nfunc isCodeDirectory(b []byte) bool {\n\n\tif b[0] != 0xfa || b[1] != 0xde || b[2] != 0x0c || (b[3] != 0x01 && b[3] != 0x02) {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\n\nfunc parseCodeDirectory(file *os.File, pl parse.ParsedLayout) (*parse.ParsedLayout, error) ", "output": "{\n\n\n\tpos := int64(0)\n\tpl.FileKind = parse.MacOSResource\n\tpl.Layout = []parse.Layout{{\n\t\tOffset: pos,\n\t\tLength: 4, \n\t\tInfo: \"header\",\n\t\tType: parse.Group,\n\t\tChilds: []parse.Layout{\n\t\t\t{Offset: pos, Length: 4, Info: \"magic\", Type: parse.ASCII},\n\t\t}}}\n\n\treturn &pl, nil\n}"} {"input": "package bmp_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestBmp(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Bmp Suite\")\n}"} {"input": "package tags\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/codedellemc/gorackhd/models\"\n)\n\n\ntype GetTagsReader struct {\n\tformats strfmt.Registry\n}\n\n\n\n\n\nfunc NewGetTagsOK() *GetTagsOK {\n\treturn &GetTagsOK{}\n}\n\n\ntype GetTagsOK struct {\n\tPayload []*models.Tag\n}\n\nfunc (o *GetTagsOK) Error() string {\n\treturn fmt.Sprintf(\"[GET /tags][%d] getTagsOK %+v\", 200, o.Payload)\n}\n\nfunc (o *GetTagsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\tif err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc NewGetTagsDefault(code int) *GetTagsDefault {\n\treturn &GetTagsDefault{\n\t\t_statusCode: code,\n\t}\n}\n\n\ntype GetTagsDefault struct {\n\t_statusCode int\n\n\tPayload *models.Error\n}\n\n\nfunc (o *GetTagsDefault) Code() int {\n\treturn o._statusCode\n}\n\nfunc (o *GetTagsDefault) Error() string {\n\treturn fmt.Sprintf(\"[GET /tags][%d] GetTags default %+v\", o._statusCode, o.Payload)\n}\n\nfunc (o *GetTagsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\to.Payload = new(models.Error)\n\n\tif err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (o *GetTagsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) ", "output": "{\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewGetTagsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tresult := NewGetTagsDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\t}\n}"} {"input": "package classfile\n\nimport \"encoding/binary\"\n\ntype ClassReader struct {\n\tdata []byte \n}\n\nfunc (self *ClassReader) readUint8() uint8 {\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16() uint16 {\n\tval := binary.BigEndian.Uint16(self.data)\n\tself.data = self.data[2:]\n\treturn val\n}\n\n\n\nfunc (self *ClassReader) readUint64() uint64 {\n\tval := binary.BigEndian.Uint64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16s() []uint16 {\n\tn := self.readUint16()\n\ts := make([]uint16, n)\n\tfor i := range s {\n\t\ts[i] = self.readUint16()\n\t}\n\treturn s\n}\n\nfunc (self *ClassReader) readBytes(n uint32) []byte {\n\tbytes := self.data[:n]\n\tself.data = self.data[n:]\n\treturn bytes\n}\n\nfunc (self *ClassReader) readUint32() uint32 ", "output": "{\n\tval := binary.BigEndian.Uint32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}"} {"input": "package es\n\nimport (\n\t\"github.com/blevesearch/bleve/analysis\"\n\t\"github.com/blevesearch/bleve/analysis/token_filters/stemmer_filter\"\n\t\"github.com/blevesearch/bleve/registry\"\n)\n\nconst StemmerName = \"stemmer_es\"\n\n\n\nfunc init() {\n\tregistry.RegisterTokenFilter(StemmerName, StemmerFilterConstructor)\n}\n\nfunc StemmerFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) ", "output": "{\n\treturn stemmer_filter.NewStemmerFilter(\"es\")\n}"} {"input": "package identify\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewPostNodesIdentifierObmIdentifyParams() *PostNodesIdentifierObmIdentifyParams {\n\tvar ()\n\treturn &PostNodesIdentifierObmIdentifyParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\n\n\n\ntype PostNodesIdentifierObmIdentifyParams struct {\n\n\tBody *bool\n\tIdentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *PostNodesIdentifierObmIdentifyParams) WithBody(body *bool) *PostNodesIdentifierObmIdentifyParams {\n\to.Body = body\n\treturn o\n}\n\n\nfunc (o *PostNodesIdentifierObmIdentifyParams) WithIdentifier(identifier string) *PostNodesIdentifierObmIdentifyParams {\n\to.Identifier = identifier\n\treturn o\n}\n\n\nfunc (o *PostNodesIdentifierObmIdentifyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetBodyParam(o.Body); err != nil {\n\t\treturn err\n\t}\n\n\tif err := r.SetPathParam(\"identifier\", o.Identifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewPostNodesIdentifierObmIdentifyParamsWithTimeout(timeout time.Duration) *PostNodesIdentifierObmIdentifyParams ", "output": "{\n\tvar ()\n\treturn &PostNodesIdentifierObmIdentifyParams{\n\n\t\ttimeout: timeout,\n\t}\n}"} {"input": "package functools\n\n\nfunc All(bools ...bool) bool {\n\tfor _, b := range bools {\n\t\tif !b {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc None(bools ...bool) bool {\n\tfor _, b := range bools {\n\t\tif b {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc Any(bools ...bool) bool ", "output": "{\n\tfor _, b := range bools {\n\t\tif b {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package v1\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/goharbor/harbor/src/pkg/reg/adapter/harbor/base\"\n\t\"github.com/goharbor/harbor/src/pkg/reg/model\"\n\trepomodel \"github.com/goharbor/harbor/src/pkg/repository/model\"\n)\n\ntype client struct {\n\t*base.Client\n}\n\nfunc (c *client) listRepositories(project *base.Project) ([]*model.Repository, error) {\n\trepositories := []*repomodel.RepoRecord{}\n\turl := fmt.Sprintf(\"%s/repositories?project_id=%d\", c.BasePath(), project.ID)\n\tif err := c.C.GetAndIteratePagination(url, &repositories); err != nil {\n\t\treturn nil, err\n\t}\n\tvar repos []*model.Repository\n\tfor _, repository := range repositories {\n\t\trepos = append(repos, &model.Repository{\n\t\t\tName: repository.Name,\n\t\t\tMetadata: project.Metadata,\n\t\t})\n\t}\n\treturn repos, nil\n}\n\n\n\nfunc (c *client) deleteManifest(repository, reference string) error {\n\turl := fmt.Sprintf(\"%s/repositories/%s/tags/%s\", c.BasePath(), repository, reference)\n\treturn c.C.Delete(url)\n}\n\nfunc (c *client) listArtifacts(repository string) ([]*model.Artifact, error) ", "output": "{\n\turl := fmt.Sprintf(\"%s/repositories/%s/tags\", c.BasePath(), repository)\n\ttags := []*struct {\n\t\tName string `json:\"name\"`\n\t\tLabels []*struct {\n\t\t\tName string `json:\"name\"`\n\t\t}\n\t}{}\n\tif err := c.C.Get(url, &tags); err != nil {\n\t\treturn nil, err\n\t}\n\tvar artifacts []*model.Artifact\n\tfor _, tag := range tags {\n\t\tartifact := &model.Artifact{\n\t\t\tType: string(model.ResourceTypeImage),\n\t\t\tTags: []string{tag.Name},\n\t\t}\n\t\tfor _, label := range tag.Labels {\n\t\t\tartifact.Labels = append(artifact.Labels, label.Name)\n\t\t}\n\t\tartifacts = append(artifacts, artifact)\n\t}\n\treturn artifacts, nil\n}"} {"input": "package engine\n\nimport \"testing\"\n\nfunc TestBackendLobbyMuxAddLobby(t *testing.T) {\n\tmux := NewBackendLobbyMux()\n\tmux.AddLobby(\"/foo\", &backendLobby{})\n\tif _, ok := mux.m[\"/foo\"]; !ok {\n\t\tt.Errorf(\"Expected to add lobby\")\n\t}\n}\n\n\n\nfunc TestBackendLobbyMuxMatch(t *testing.T) {\n\tmux := NewBackendLobbyMux()\n\tmux.AddLobby(\"/foo\", &backendLobby{})\n\tif lobby := mux.Match(\"/foo\"); lobby == nil {\n\t\tt.Errorf(\"Expected to match existing lobby\")\n\t}\n\tif lobby := mux.Match(\"/bar\"); lobby != nil {\n\t\tt.Errorf(\"Expected to not match non existing lobby\")\n\t}\n}\n\nfunc TestBackendLobbyMuxDeleteLobby(t *testing.T) ", "output": "{\n\tmux := NewBackendLobbyMux()\n\tl := &backendLobby{queue: make(chan interface{})}\n\tmux.AddLobby(\"/foo\", l)\n\tif ok := mux.DeleteLobby(\"/foo\"); !ok {\n\t\tt.Errorf(\"Expected to delete lobby\")\n\t}\n\tif l.IsAlive() {\n\t\tt.Errorf(\"Lobby should be killed when deleting from the mux\")\n\t}\n\tif _, ok := mux.m[\"/foo\"]; ok {\n\t\tt.Errorf(\"Expected to delete lobby\")\n\t}\n\tif ok := mux.DeleteLobby(\"/bar\"); ok {\n\t\tt.Errorf(\"Expected to not delete non existing lobby\")\n\t}\n}"} {"input": "package dilma\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/go-chat-bot/bot\"\n)\n\nfunc TestDilmaWhenTheTextDoesNotMatchDilma(t *testing.T) {\n\tcmd := &bot.PassiveCmd{}\n\tcmd.Raw = \"My name is go-bot, I am awesome.\"\n\tgot, err := dilma(cmd)\n\n\tif err != nil {\n\t\tt.Errorf(\"Error should be nil => %s\", err)\n\t}\n\tif got != \"\" {\n\t\tt.Errorf(\"Test failed. Expected a empty return, got: '%s'\", got)\n\t}\n}\n\n\n\nfunc TestDilmaWhenTtheTextMatchDilma(t *testing.T) ", "output": "{\n\tcmd := &bot.PassiveCmd{}\n\tcmd.Raw = \"eu não votei na dilma!\"\n\tgot, err := dilma(cmd)\n\n\tif err != nil {\n\t\tt.Errorf(\"Error should be nil => %s\", err)\n\t}\n\tif !strings.HasPrefix(got, \":dilma: \") {\n\t\tt.Errorf(\"Test failed. Should return a clever Dilma quote\")\n\t}\n}"} {"input": "package byteslice\n\nimport \"fmt\"\n\nfunc ExampleLSet() {\n\tdata := []byte{0xAA, 0xCA, 0x55}\n\tsetData := []byte{0x10, 0x12}\n\n\tfmt.Printf(\"%x\\n\", LSet(data, setData))\n}\n\n\n\nfunc ExampleLToggle() ", "output": "{\n\tdata := []byte{0xAB, 0xCB, 0x44}\n\tsetData := []byte{0x11, 0x11, 0x11}\n\n\tfmt.Printf(\"%x\\n\", LToggle(data, setData))\n}"} {"input": "package cache\n\nimport (\n\t\"github.com/stretchr/testify/mock\"\n)\n\n\ntype MockMetrics struct {\n\tmock.Mock\n}\n\n\n\n\nfunc (_m *MockMetrics) Track(event Event) ", "output": "{\n\t_m.Called(event)\n}"} {"input": "package derive\n\nimport (\n\t\"go/types\"\n\t\"strings\"\n)\n\n\ntype Named struct {\n\tFields []*Field\n\tReflect bool\n}\n\n\ntype Field struct {\n\tname string\n\texternal bool\n\tType types.Type\n\ttypeStr func() string\n}\n\n\nfunc (f *Field) Name(recv string, unsafePkg Import) string {\n\tif !f.Private() || !f.external {\n\t\treturn recv + \".\" + f.name\n\t}\n\treturn `*(*` + f.typeStr() + `)(` + unsafePkg() + `.Pointer(` + recv + `.FieldByName(\"` + f.name + `\").UnsafeAddr()))`\n}\n\n\nfunc (f *Field) DebugName() string {\n\treturn f.name\n}\n\n\nfunc (f *Field) Private() bool {\n\treturn strings.ToLower(f.name[0:1]) == f.name[0:1]\n}\n\n\nfunc Fields(typesMap TypesMap, typ *types.Struct, external bool) *Named {\n\tnumFields := typ.NumFields()\n\tn := &Named{\n\t\tFields: make([]*Field, numFields),\n\t}\n\tfor i := 0; i < numFields; i++ {\n\t\tfield := typ.Field(i)\n\t\tfieldType := field.Type()\n\t\tfieldName := field.Name()\n\t\tn.Fields[i] = &Field{\n\t\t\tname: fieldName,\n\t\t\texternal: external,\n\t\t\tType: fieldType,\n\t\t\ttypeStr: func() string {\n\t\t\t\treturn typesMap.TypeString(fieldType)\n\t\t\t},\n\t\t}\n\t\tif n.Fields[i].Private() {\n\t\t\tif external {\n\t\t\t\tn.Reflect = true\n\t\t\t}\n\t\t}\n\t}\n\treturn n\n}\n\n\n\nfunc GetStructFields(s *types.Struct) []*types.Var ", "output": "{\n\tfields := make([]*types.Var, s.NumFields())\n\tfor i := 0; i < s.NumFields(); i++ {\n\t\tfields[i] = s.Field(i)\n\t}\n\treturn fields\n}"} {"input": "package update\n\nimport (\n\t\"os\"\n\n\t\"github.com/pkg/term\"\n\t\"golang.org/x/sys/unix\"\n)\n\nfunc terminalWidth() uint16 {\n\tws, _ := unix.IoctlGetWinsize(int(os.Stdout.Fd()), unix.TIOCGWINSZ)\n\tif ws != nil && ws.Col != 0 {\n\t\treturn ws.Col\n\t}\n\treturn 9999\n}\n\n\n\n\nfunc getChar() (ascii int, keyCode int, err error) ", "output": "{\n\tt, _ := term.Open(\"/dev/tty\")\n\tterm.RawMode(t)\n\tbs := make([]byte, 3)\n\n\tvar numRead int\n\tnumRead, err = t.Read(bs)\n\tif err != nil {\n\t\treturn\n\t}\n\tif numRead == 3 && bs[0] == 27 && bs[1] == 91 {\n\n\t\tif bs[2] == 65 {\n\t\t\tkeyCode = 38\n\t\t} else if bs[2] == 66 {\n\t\t\tkeyCode = 40\n\t\t} else if bs[2] == 67 {\n\t\t\tkeyCode = 39\n\t\t} else if bs[2] == 68 {\n\t\t\tkeyCode = 37\n\t\t}\n\t} else if numRead == 1 {\n\t\tascii = int(bs[0])\n\t} else {\n\t}\n\tt.Restore()\n\tt.Close()\n\treturn\n}"} {"input": "package jmespath\n\nimport \"strconv\"\n\n\n\ntype JMESPath struct {\n\tast ASTNode\n\tintr *treeInterpreter\n}\n\n\n\nfunc Compile(expression string) (*JMESPath, error) {\n\tparser := NewParser()\n\tast, err := parser.Parse(expression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tjmespath := &JMESPath{ast: ast, intr: newInterpreter()}\n\treturn jmespath, nil\n}\n\n\n\n\nfunc MustCompile(expression string) *JMESPath {\n\tjmespath, err := Compile(expression)\n\tif err != nil {\n\t\tpanic(`jmespath: Compile(` + strconv.Quote(expression) + `): ` + err.Error())\n\t}\n\treturn jmespath\n}\n\n\nfunc (jp *JMESPath) Search(data interface{}) (interface{}, error) {\n\treturn jp.intr.Execute(jp.ast, data)\n}\n\n\n\n\nfunc Search(expression string, data interface{}) (interface{}, error) ", "output": "{\n\tintr := newInterpreter()\n\tparser := NewParser()\n\tast, err := parser.Parse(expression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn intr.Execute(ast, data)\n}"} {"input": "package benchmarks\n\nimport (\n\t\"io/ioutil\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/go-kit/kit/log\"\n)\n\nfunc newKit() *log.Context {\n\treturn log.NewContext(log.NewJSONLogger(ioutil.Discard))\n}\n\n\n\nfunc BenchmarkGoKitWithAccumulatedContext(b *testing.B) {\n\tlogger := newKit().With(\n\t\t\"int\", 1,\n\t\t\"int64\", int64(1),\n\t\t\"float\", 3.0,\n\t\t\"string\", \"four!\",\n\t\t\"bool\", true,\n\t\t\"time\", time.Unix(0, 0),\n\t\t\"error\", errExample.Error(),\n\t\t\"duration\", time.Second,\n\t\t\"user-defined type\", _jane,\n\t\t\"another string\", \"done!\",\n\t)\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tlogger.Log(\"Go really fast.\")\n\t\t}\n\t})\n}\n\nfunc BenchmarkGoKitWithoutFields(b *testing.B) {\n\tlogger := newKit()\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tlogger.Log(\"Go fast.\")\n\t\t}\n\t})\n}\n\nfunc BenchmarkGoKitAddingFields(b *testing.B) ", "output": "{\n\tlogger := newKit()\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tlogger.With(\n\t\t\t\t\"int\", 1,\n\t\t\t\t\"int64\", int64(1),\n\t\t\t\t\"float\", 3.0,\n\t\t\t\t\"string\", \"four!\",\n\t\t\t\t\"bool\", true,\n\t\t\t\t\"time\", time.Unix(0, 0),\n\t\t\t\t\"error\", errExample.Error(),\n\t\t\t\t\"duration\", time.Second,\n\t\t\t\t\"user-defined type\", _jane,\n\t\t\t\t\"another string\", \"done!\",\n\t\t\t).Log(\"Go fast.\")\n\t\t}\n\t})\n}"} {"input": "package problem0204\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\nvar tcs = []struct {\n\tn int\n\tans int\n}{\n\n\n\n}\n\nfunc Test_countPrimes(t *testing.T) {\n\ta := assert.New(t)\n\n\tfor _, tc := range tcs {\n\t\ta.Equal(tc.ans, countPrimes(tc.n), \"输入:%v\", tc)\n\t}\n}\n\n\n\nfunc Benchmark_countPrimes(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, tc := range tcs {\n\t\t\tcountPrimes(tc.n)\n\t\t}\n\t}\n}"} {"input": "package pipelinerun\n\nimport (\n\t\"sort\"\n\n\t\"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1\"\n)\n\nfunc SortByNamespace(prs []v1beta1.PipelineRun) {\n\tsort.Sort(byNamespace(prs))\n}\n\ntype byNamespace []v1beta1.PipelineRun\n\nfunc (prs byNamespace) compareNamespace(ins, jns string) (lt, eq bool) {\n\tlt, eq = ins < jns, ins == jns\n\treturn lt, eq\n}\n\n\nfunc (prs byNamespace) Swap(i, j int) { prs[i], prs[j] = prs[j], prs[i] }\nfunc (prs byNamespace) Less(i, j int) bool {\n\tvar lt, eq bool\n\tif lt, eq = prs.compareNamespace(prs[i].Namespace, prs[j].Namespace); eq {\n\t\tif prs[j].Status.StartTime == nil {\n\t\t\treturn false\n\t\t}\n\t\tif prs[i].Status.StartTime == nil {\n\t\t\treturn true\n\t\t}\n\t\treturn prs[j].Status.StartTime.Before(prs[i].Status.StartTime)\n\t}\n\treturn lt\n}\n\nfunc (prs byNamespace) Len() int ", "output": "{ return len(prs) }"} {"input": "package api\n\nimport (\n\t\"io\"\n)\n\n\n\ntype Snapshot struct {\n\tc *Client\n}\n\n\nfunc (c *Client) Snapshot() *Snapshot {\n\treturn &Snapshot{c}\n}\n\n\n\n\n\n\n\n\nfunc (s *Snapshot) Restore(q *WriteOptions, in io.Reader) error {\n\tr := s.c.newRequest(\"PUT\", \"/v1/snapshot\")\n\tr.body = in\n\tr.header.Set(\"Content-Type\", \"application/octet-stream\")\n\tr.setWriteOptions(q)\n\t_, resp, err := s.c.doRequest(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := requireOK(resp); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (s *Snapshot) Save(q *QueryOptions) (io.ReadCloser, *QueryMeta, error) ", "output": "{\n\tr := s.c.newRequest(\"GET\", \"/v1/snapshot\")\n\tr.setQueryOptions(q)\n\n\trtt, resp, err := s.c.doRequest(r)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif err := requireOK(resp); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tqm := &QueryMeta{}\n\tparseQueryMeta(resp, qm)\n\tqm.RequestTime = rtt\n\treturn resp.Body, qm, nil\n}"} {"input": "package collector\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/google/cadvisor/info/v1\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype fakeCollector struct {\n\tnextCollectionTime time.Time\n\terr error\n\tcollectedFrom int\n}\n\nfunc (fc *fakeCollector) Collect(metric map[string]v1.MetricVal) (time.Time, map[string]v1.MetricVal, error) {\n\tfc.collectedFrom++\n\treturn fc.nextCollectionTime, metric, fc.err\n}\n\nfunc (fc *fakeCollector) Name() string {\n\treturn \"fake-collector\"\n}\n\n\n\nfunc TestCollect(t *testing.T) {\n\tcm := &GenericCollectorManager{}\n\n\tfirstTime := time.Now().Add(-time.Hour)\n\tsecondTime := time.Now().Add(time.Hour)\n\tf1 := &fakeCollector{\n\t\tnextCollectionTime: firstTime,\n\t}\n\tf2 := &fakeCollector{\n\t\tnextCollectionTime: secondTime,\n\t}\n\n\tassert := assert.New(t)\n\tassert.NoError(cm.RegisterCollector(f1))\n\tassert.NoError(cm.RegisterCollector(f2))\n\n\tnextTime, _, err := cm.Collect()\n\tassert.Equal(firstTime, nextTime)\n\tassert.NoError(err)\n\tassert.Equal(1, f1.collectedFrom)\n\tassert.Equal(1, f2.collectedFrom)\n\n\tf1.nextCollectionTime = time.Now().Add(2 * time.Hour)\n\n\tnextTime, _, err = cm.Collect()\n\tassert.Equal(secondTime, nextTime)\n\tassert.NoError(err)\n\tassert.Equal(2, f1.collectedFrom)\n\tassert.Equal(1, f2.collectedFrom)\n}\n\nfunc (fc *fakeCollector) GetSpec() []v1.MetricSpec ", "output": "{\n\treturn []v1.MetricSpec{}\n}"} {"input": "package outlet\n\nimport (\n\t\"fmt\"\n\t\"l2met/bucket\"\n\t\"l2met/store\"\n\t\"time\"\n)\n\ntype BucketReader struct {\n\tStore store.Store\n\tInterval time.Duration\n\tPartition string\n\tTtl uint64\n\tNumOutlets int\n\tNumScanners int\n\tInbox chan *bucket.Bucket\n\tOutbox chan *bucket.Bucket\n}\n\nfunc NewBucketReader(sz, c int, i time.Duration, st store.Store) *BucketReader {\n\trdr := new(BucketReader)\n\trdr.Partition = \"bucket-reader\"\n\trdr.Inbox = make(chan *bucket.Bucket, sz)\n\trdr.NumScanners = c\n\trdr.NumOutlets = c\n\trdr.Interval = i\n\trdr.Store = st\n\treturn rdr\n}\n\nfunc (r *BucketReader) Start(out chan *bucket.Bucket) {\n\tr.Outbox = out\n\tgo r.scan()\n\tfor i := 0; i < r.NumOutlets; i++ {\n\t\tgo r.outlet()\n\t}\n}\n\n\n\nfunc (r *BucketReader) outlet() {\n\tfor b := range r.Inbox {\n\t\tr.Store.Get(b)\n\t\tr.Outbox <- b\n\t}\n}\n\nfunc (r *BucketReader) scan() ", "output": "{\n\tfor t := range time.Tick(r.Interval) {\n\t\tbuckets, err := r.Store.Scan(t)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"at=bucket.scan error=%s\\n\", err)\n\t\t\tcontinue\n\t\t}\n\t\tfor bucket := range buckets {\n\t\t\tr.Inbox <- bucket\n\t\t}\n\t}\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/hyperledger/fabric/common/channelconfig\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n)\n\n\ntype Orderer struct {\n\tConsensusTypeVal string\n\tBatchSizeVal *ab.BatchSize\n\tBatchTimeoutVal time.Duration\n\tKafkaBrokersVal []string\n\tMaxChannelsCountVal uint64\n\tOrganizationsVal map[string]channelconfig.Org\n\tCapabilitiesVal channelconfig.OrdererCapabilities\n}\n\n\nfunc (scm *Orderer) ConsensusType() string {\n\treturn scm.ConsensusTypeVal\n}\n\n\nfunc (scm *Orderer) BatchSize() *ab.BatchSize {\n\treturn scm.BatchSizeVal\n}\n\n\n\n\n\nfunc (scm *Orderer) KafkaBrokers() []string {\n\treturn scm.KafkaBrokersVal\n}\n\n\nfunc (scm *Orderer) MaxChannelsCount() uint64 {\n\treturn scm.MaxChannelsCountVal\n}\n\n\nfunc (scm *Orderer) Organizations() map[string]channelconfig.Org {\n\treturn scm.OrganizationsVal\n}\n\n\nfunc (scm *Orderer) Capabilities() channelconfig.OrdererCapabilities {\n\treturn scm.CapabilitiesVal\n}\n\n\ntype OrdererCapabilities struct {\n\tSupportedErr error\n\n\tSetChannelModPolicyDuringCreateVal bool\n\n\tResubmissionVal bool\n}\n\n\nfunc (oc *OrdererCapabilities) Supported() error {\n\treturn oc.SupportedErr\n}\n\n\nfunc (oc *OrdererCapabilities) SetChannelModPolicyDuringCreate() bool {\n\treturn oc.SetChannelModPolicyDuringCreateVal\n}\n\n\nfunc (oc *OrdererCapabilities) Resubmission() bool {\n\treturn oc.ResubmissionVal\n}\n\nfunc (scm *Orderer) BatchTimeout() time.Duration ", "output": "{\n\treturn scm.BatchTimeoutVal\n}"} {"input": "package stateful\n\nimport \"sync\"\n\n\n\n\ntype ScopePool interface {\n\tGet() *Scope\n\tPut(scope *Scope)\n\n\tReferenceVariables() []string\n}\n\ntype scopePool struct {\n\treferenceVariables []string\n\tpool sync.Pool\n}\n\n\nfunc NewScopePool(referenceVariables []string) ScopePool {\n\tscopePool := &scopePool{\n\t\treferenceVariables: referenceVariables,\n\t}\n\n\tscopePool.pool = sync.Pool{\n\t\tNew: func() interface{} {\n\t\t\tscope := NewScope()\n\t\t\tfor _, refVariable := range scopePool.referenceVariables {\n\t\t\t\tscope.Set(refVariable, empty)\n\t\t\t}\n\n\t\t\treturn scope\n\t\t},\n\t}\n\n\treturn scopePool\n}\n\nfunc (s *scopePool) ReferenceVariables() []string {\n\treturn s.referenceVariables\n}\n\n\n\nfunc (s *scopePool) Get() *Scope {\n\treturn s.pool.Get().(*Scope)\n}\n\n\n\n\nfunc (s *scopePool) Put(scope *Scope) ", "output": "{\n\tscope.Reset()\n\ts.pool.Put(scope)\n}"} {"input": "package gsh\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"gopkg.in/pipe.v2\"\n)\n\ntype HeadCmd struct {\n\tChars int\n\tLines int\n}\n\nfunc (cmd *HeadCmd) Flags() *flag.FlagSet {\n\tf := flag.NewFlagSet(cmd.Name(), flag.ExitOnError)\n\tf.IntVar(&cmd.Chars, \"c\", -1, \"Take first N characters\")\n\tf.IntVar(&cmd.Chars, \"n\", 10, \"Take first N lines\")\n\treturn f\n}\n\n\n\nfunc (cmd *HeadCmd) Run(s *pipe.State, argv []string) error {\n\tfs := cmd.Flags()\n\terr := fs.Parse(argv)\n\tif err != nil {\n\t\treturn err\n\t}\n\targs := fs.Args()\n\tif len(args) > 0 {\n\t\tfor _, fname := range args {\n\t\t\tfh, err := os.Open(fname)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%s 1: %s\", cmd.Name(), err)\n\t\t\t}\n\t\t\t_, err = io.Copy(s.Stdout, fh)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%s 2: %s\", cmd.Name(), err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\tif cmd.Chars >= 0 {\n\t\t_, err = io.CopyN(s.Stdout, s.Stdin, int64(cmd.Chars))\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: %s\", cmd.Name(), err)\n\t}\n\treturn nil\n}\n\nfunc Head(argv ...string) pipe.Pipe {\n\tcmd := HeadCmd{}\n\treturn pipe.TaskFunc(func(s *pipe.State) error {\n\t\treturn cmd.Run(s, argv)\n\t})\n}\n\nfunc (cmd *HeadCmd) Name() string ", "output": "{\n\treturn \"head\"\n}"} {"input": "package registry\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\t\"google.golang.org/protobuf/testing/protocmp\"\n\t\"google.golang.org/protobuf/types/known/emptypb\"\n)\n\n\n\nfunc TestGetStorage(t *testing.T) ", "output": "{\n\tctx := context.Background()\n\tserver := defaultTestServer(t)\n\n\treq := &emptypb.Empty{}\n\n\tresp, err := server.GetStorage(ctx, req)\n\tif err != nil {\n\t\tt.Fatalf(\"GetStorage(%+v) returned error: %s\", req, err)\n\t}\n\n\twant := []string{\"apis\", \"artifacts\", \"blobs\", \"deployment_revision_tags\", \"deployments\", \"projects\", \"spec_revision_tags\", \"specs\", \"versions\"}\n\tgot := make([]string, 0)\n\tfor _, c := range resp.Collections {\n\t\tgot = append(got, c.Name)\n\t}\n\tif !cmp.Equal(want, got) {\n\t\tt.Errorf(\"GetStorage(%+v) returned unexpected diff (-want +got):\\n%s\", req, cmp.Diff(want, got, protocmp.Transform()))\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"path\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n\nfunc getProtoAndAdd(target string) (string, string) {\n\treg := `(?i)^((?:(?:tcp|udp|ip)[46]?)|` + `(?:unix(?:gram|packet)?)):(.+)$`\n\tt := regexp.MustCompile(reg).FindStringSubmatch(target)\n\treturn t[1], t[2]\n}\n\nfunc PathExists(path string) (bool, error) {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true, nil\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\treturn false, err\n}\n\n\nfunc getCSIEndPoint(csiEndpoint string) (string, error) {\n\tcsiEndpoint = strings.TrimSpace(csiEndpoint)\n\n\tif csiEndpoint == \"\" {\n\t\terr := errors.New(\"csi endpoint is empty\")\n\t\tlog.Fatalf(\"%v\", err)\n\t\treturn csiEndpoint, err\n\t}\n\n\treturn csiEndpoint, nil\n}\n\n\nfunc GetCSIEndPointListener(csiEndpoint string) (net.Listener, error) {\n\ttarget, err := getCSIEndPoint(csiEndpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tproto, addr := getProtoAndAdd(target)\n\n\tlog.Printf(\"proto: %s addr: %s\", proto, addr)\n\tif strings.HasPrefix(proto, \"unix\") {\n\t\tos.RemoveAll(addr)\n\t\tlog.Printf(\"remove sock file: %s\", addr)\n\t\tdir := path.Dir(addr)\n\t\tif exist, _ := PathExists(dir); !exist {\n\t\t\tos.MkdirAll(dir, 0755)\n\t\t}\n\t}\n\n\treturn net.Listen(proto, addr)\n}\n\n\n\n\nfunc Contained(obj, target interface{}) bool ", "output": "{\n\ttargetValue := reflect.ValueOf(target)\n\tswitch reflect.TypeOf(target).Kind() {\n\tcase reflect.Slice, reflect.Array:\n\t\tfor i := 0; i < targetValue.Len(); i++ {\n\t\t\tif targetValue.Index(i).Interface() == obj {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\tcase reflect.Map:\n\t\tif targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {\n\t\t\treturn true\n\t\t}\n\tdefault:\n\t\treturn false\n\t}\n\treturn false\n}"} {"input": "package glw\n\nimport \"golang.org/x/mobile/gl\"\n\ntype A2fv gl.Attrib\n\nfunc (a A2fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A2fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\n\n\ntype A3fv gl.Attrib\n\nfunc (a A3fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A3fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A3fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 3, gl.FLOAT, false, 0, 0)\n}\n\ntype A4fv gl.Attrib\n\nfunc (a A4fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A4fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A4fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 4, gl.FLOAT, false, 0, 0)\n}\n\nfunc (a A2fv) Pointer() ", "output": "{\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 2, gl.FLOAT, false, 0, 0)\n}"} {"input": "package supernode\n\nimport (\n\t\"testing\"\n\n\tdhtpb \"gx/ipfs/QmRG9fdibExi5DFy8kzyxF76jvZVUb2mQBUSMNP1YaYn9M/go-libp2p-kad-dht/pb\"\n\tdatastore \"gx/ipfs/QmRWDav6mzWseLWeYfVd5fvUKiVe9xNH29YfMF438fG364/go-datastore\"\n)\n\n\n\nfunc convPeer(name string, addrs ...string) *dhtpb.Message_Peer {\n\tvar rawAddrs [][]byte\n\tfor _, addr := range addrs {\n\t\trawAddrs = append(rawAddrs, []byte(addr))\n\t}\n\treturn &dhtpb.Message_Peer{Id: &name, Addrs: rawAddrs}\n}\n\nfunc TestPutProviderDoesntResultInDuplicates(t *testing.T) ", "output": "{\n\troutingBackend := datastore.NewMapDatastore()\n\tk := \"foo\"\n\tput := []*dhtpb.Message_Peer{\n\t\tconvPeer(\"bob\", \"127.0.0.1/tcp/4001\"),\n\t\tconvPeer(\"alice\", \"10.0.0.10/tcp/4001\"),\n\t}\n\tif err := putRoutingProviders(routingBackend, k, put); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := putRoutingProviders(routingBackend, k, put); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tgot, err := getRoutingProviders(routingBackend, k)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(got) != 2 {\n\t\tt.Fatal(\"should be 2 values, but there are\", len(got))\n\t}\n}"} {"input": "package outbarriers\n\nimport (\n\t\"log\"\n\t\"time\"\n)\n\ntype User struct {\n\tId int64\n\tEmail string\n\tPassword string \n}\ntype Session struct {\n\tId int64\n\tUserId int64\n\tToken string `sql:\"unique; not null\"`\n\tCreatedAt time.Time\n}\n\n\n\nfunc (ctx *Context) CheckAdmin() {\n\n\tvar user User\n\tctx.DB.Where(User{Email: ADMIN_EMAIL, Password: ADMIN_PASSWORD}).FirstOrInit(&user)\n\tif ctx.DB.NewRecord(user) {\n\t\tlog.Printf(\"Admin user not exists, creating...\")\n\t\tctx.DB.Create(&user)\n\t}\n}\n\nfunc (ctx *Context) LoginUser(user *User) string {\n\n\ttoken := RandomString(64)\n\tsession := &Session{UserId: user.Id, Token: token, CreatedAt: time.Now()}\n\tctx.DB.Create(session)\n\treturn token\n}\n\nfunc (ctx *Context) GetSessionByToken(token string) *Session {\n\n\tvar session Session\n\tctx.DB.Where(\"token = ?\", token).First(&session)\n\tif session.Id == 0 {\n\t\treturn nil\n\t}\n\treturn &session\n}\n\nfunc (ctx *Context) AuthUser(email, password string) *User ", "output": "{\n\n\tvar user User\n\tctx.DB.Where(\"email = ? and password = ?\", email, password).First(&user)\n\treturn &user\n}"} {"input": "package pdf417\n\nimport \"math\"\n\nconst (\n\tminCols = 2\n\tmaxCols = 30\n\tmaxRows = 30\n\tminRows = 2\n\tmoduleHeight = 2\n\tpreferred_ratio = 3.0\n)\n\n\n\nfunc calcDimensions(dataWords, eccWords int) (cols, rows int) {\n\tratio := 0.0\n\tcols = 0\n\trows = 0\n\n\tfor c := minCols; c <= maxCols; c++ {\n\t\tr := calculateNumberOfRows(dataWords, eccWords, c)\n\n\t\tif r < minRows {\n\t\t\tbreak\n\t\t}\n\n\t\tif r > maxRows {\n\t\t\tcontinue\n\t\t}\n\n\t\tnewRatio := float64(17*cols+69) / float64(rows*moduleHeight)\n\t\tif rows != 0 && math.Abs(newRatio-preferred_ratio) > math.Abs(ratio-preferred_ratio) {\n\t\t\tcontinue\n\t\t}\n\n\t\tratio = newRatio\n\t\tcols = c\n\t\trows = r\n\t}\n\n\tif rows == 0 {\n\t\tr := calculateNumberOfRows(dataWords, eccWords, minCols)\n\t\tif r < minRows {\n\t\t\trows = minRows\n\t\t\tcols = minCols\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc calculateNumberOfRows(m, k, c int) int ", "output": "{\n\tr := ((m + 1 + k) / c) + 1\n\tif c*r >= (m + 1 + k + c) {\n\t\tr--\n\t}\n\treturn r\n}"} {"input": "package handler\n\nimport (\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/dinever/golf\"\n\t\"github.com/dingoblog/dingo/app/model\"\n)\n\nfunc AuthMiddleware(next golf.HandlerFunc) golf.HandlerFunc {\n\tfn := func(ctx *golf.Context) {\n\t\tuserNum, err := model.GetNumberOfUsers()\n\t\tif err == nil && userNum == 0 {\n\t\t\tctx.Redirect(\"/signup/\")\n\t\t\treturn\n\t\t}\n\t\ttokenStr, err := ctx.Request.Cookie(\"token-value\")\n\t\tif err != nil {\n\t\t\tctx.Redirect(\"/login/\")\n\t\t\treturn\n\t\t}\n\t\ttoken := &model.Token{Value: tokenStr.Value}\n\t\terr = token.GetTokenByValue()\n\t\tif err != nil || !token.IsValid() {\n\t\t\tctx.Redirect(\"/login/\")\n\t\t\treturn\n\t\t}\n\t\ttokenUser, err := ctx.Request.Cookie(\"token-user\")\n\t\tif err != nil {\n\t\t\tctx.Redirect(\"/login/\")\n\t\t\treturn\n\t\t}\n\t\tuid, _ := strconv.Atoi(tokenUser.Value)\n\t\tuser := &model.User{Id: int64(uid)}\n\t\terr = user.GetUserById()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tctx.Session.Set(\"user\", user)\n\t\tnext(ctx)\n\t}\n\treturn fn\n}\n\n\n\nfunc JWTAuthMiddleware(next golf.HandlerFunc) golf.HandlerFunc ", "output": "{\n\treturn func(ctx *golf.Context) {\n\t\ttokenHeader := ctx.Header(\"X-SESSION-TOKEN\")\n\t\tif tokenHeader == \"\" {\n\t\t\tctx.SendStatus(http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\ttoken, err := model.ValidateJWT(tokenHeader)\n\t\tif err != nil {\n\t\t\tctx.SendStatus(http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tctx.Session.Set(\"jwt\", model.NewJWTFromToken(token))\n\t\tnext(ctx)\n\t}\n}"} {"input": "package minecraft\n\nimport (\n\t\"io\"\n\t\"github.com/LilyPad/GoLilyPad/packet\"\n)\n\ntype PacketServerLoginStart struct {\n\tName string\n}\n\nfunc NewPacketServerLoginStart(name string) (this *PacketServerLoginStart) {\n\tthis = new(PacketServerLoginStart)\n\tthis.Name = name\n\treturn\n}\n\nfunc (this *PacketServerLoginStart) Id() int {\n\treturn PACKET_SERVER_LOGIN_START\n}\n\ntype packetServerLoginStartCodec struct {\n\n}\n\n\n\nfunc (this *packetServerLoginStartCodec) Encode(writer io.Writer, encode packet.Packet) (err error) {\n\tpacketServerLoginStart := encode.(*PacketServerLoginStart)\n\terr = packet.WriteString(writer, packetServerLoginStart.Name)\n\treturn\n}\n\nfunc (this *packetServerLoginStartCodec) Decode(reader io.Reader) (decode packet.Packet, err error) ", "output": "{\n\tpacketServerLoginStart := new(PacketServerLoginStart)\n\tpacketServerLoginStart.Name, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\tdecode = packetServerLoginStart\n\treturn\n}"} {"input": "package transform\n\nimport (\n\t\"path/filepath\"\n\n\t\"github.com/drone/drone-exec/yaml\"\n)\n\n\n\n\nfunc WorkspaceTransform(c *yaml.Config, base, path string) error ", "output": "{\n\tif c.Workspace == nil {\n\t\tc.Workspace = &yaml.Workspace{}\n\t}\n\n\tif c.Workspace.Base == \"\" {\n\t\tc.Workspace.Base = base\n\t}\n\tif c.Workspace.Path == \"\" {\n\t\tc.Workspace.Path = path\n\t}\n\tif !filepath.IsAbs(c.Workspace.Path) {\n\t\tc.Workspace.Path = filepath.Join(\n\t\t\tc.Workspace.Base,\n\t\t\tc.Workspace.Path,\n\t\t)\n\t}\n\n\tfor _, p := range c.Pipeline {\n\t\tp.WorkingDir = c.Workspace.Path\n\t}\n\treturn nil\n}"} {"input": "package disk\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/object\"\n)\n\ntype shrink struct {\n\t*flags.DatastoreFlag\n\n\tcopy *bool\n}\n\nfunc init() {\n\tcli.Register(\"datastore.disk.shrink\", &shrink{})\n}\n\nfunc (cmd *shrink) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)\n\tcmd.DatastoreFlag.Register(ctx, f)\n\n\tf.Var(flags.NewOptionalBool(&cmd.copy), \"copy\", \"Perform shrink in-place mode if false, copy-shrink mode otherwise\")\n}\n\nfunc (cmd *shrink) Process(ctx context.Context) error {\n\treturn cmd.DatastoreFlag.Process(ctx)\n}\n\nfunc (cmd *shrink) Usage() string {\n\treturn \"VMDK\"\n}\n\n\n\nfunc (cmd *shrink) Run(ctx context.Context, f *flag.FlagSet) error {\n\tdc, err := cmd.Datacenter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tds, err := cmd.Datastore()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm := object.NewVirtualDiskManager(ds.Client())\n\tpath := ds.Path(f.Arg(0))\n\ttask, err := m.ShrinkVirtualDisk(ctx, path, dc, cmd.copy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger := cmd.ProgressLogger(fmt.Sprintf(\"Shrinking %s...\", path))\n\tdefer logger.Wait()\n\n\t_, err = task.WaitForResult(ctx, logger)\n\treturn err\n}\n\nfunc (cmd *shrink) Description() string ", "output": "{\n\treturn `Shrink VMDK on DS.\n\nExamples:\n govc datastore.disk.shrink disks/disk1.vmdk`\n}"} {"input": "package refund\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/issue9/wechat/pay\"\n)\n\n\ntype Refund struct {\n\tPay *pay.Pay\n\tDeviceInfo string \n\tSignType string \n\tRefundFeeType string \n\tOpUserID string \n\tRefundAccount string \n}\n\n\n\n\nfunc (r *Refund) OutTradeNO(outRefundNO, outTradeNO string, totalFee, refundFee int) (*Return, error) {\n\tparams := r.params(outRefundNO, outTradeNO, \"\", totalFee, refundFee)\n\treturn r.refund(params)\n}\n\n\nfunc (r *Refund) TransactionID(outRefundNO, transactionID string, totalFee, refundFee int) (*Return, error) {\n\tparams := r.params(outRefundNO, \"\", transactionID, totalFee, refundFee)\n\treturn r.refund(params)\n}\n\nfunc (r *Refund) refund(params map[string]string) (*Return, error) {\n\tmaps, err := r.Pay.Refund(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = r.Pay.ValidateAll(r.SignType, maps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newReturn(maps)\n}\n\nfunc (r *Refund) params(outRefundNO, outTradeNO, transactionID string, totalFee, refundFee int) map[string]string ", "output": "{\n\treturn map[string]string{\n\t\t\"device_info\": r.DeviceInfo,\n\t\t\"sign_type\": r.SignType,\n\t\t\"out_trade_no\": outTradeNO,\n\t\t\"transaction_id\": transactionID,\n\t\t\"out_refund_no\": outRefundNO,\n\t\t\"total_fee\": strconv.Itoa(totalFee),\n\t\t\"refund_fee\": strconv.Itoa(refundFee),\n\t\t\"refund_fee_type\": r.RefundFeeType,\n\t\t\"op_user_id\": r.OpUserID,\n\t\t\"refund_account\": r.RefundAccount,\n\t}\n}"} {"input": "package upax_go\n\n\n\nimport (\n\txi \"github.com/jddixon/xlNodeID_go\"\n)\n\n\n\n\n\n\ntype ClientIHaveMgr struct {\n\tiHaveCh chan IHaveObj\n\tentries *xi.IDMap \n\toutMsgCh chan *UpaxClientMsg\n\tstopCh chan bool\n}\n\n\n\n\n\nfunc (mgr *ClientIHaveMgr) Run() {\n\tvar whatever interface{}\n\tvar err error\n\tfor {\n\t\tselect {\n\t\tcase iHaveObj := <-mgr.iHaveCh:\n\t\t\tids := iHaveObj.IDs\n\t\t\tfor i := 0; i < len(ids); i++ {\n\t\t\t\tid := ids[i]\n\t\t\t\twhatever, err = mgr.entries.Find(id)\n\t\t\t\tif (err == nil) && (whatever == nil) {\n\t\t\t\t\top := UpaxClientMsg_Get\n\t\t\t\t\tmsgOut := &UpaxClientMsg{\n\t\t\t\t\t\tOp: &op,\n\t\t\t\t\t\tHash: id,\n\t\t\t\t\t}\n\t\t\t\t\tmgr.outMsgCh <- msgOut\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-mgr.stopCh:\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc NewClientIHaveMgr(iHaveCh chan IHaveObj, entries *xi.IDMap,\n\toutMsgCh chan *UpaxClientMsg, stopCh chan bool) (\n\tmgr *ClientIHaveMgr, err error) ", "output": "{\n\n\tif iHaveCh == nil {\n\t\terr = NilIHaveChan\n\t} else if entries == nil {\n\t\terr = NilIDMap\n\t} else if outMsgCh == nil {\n\t\terr = NilOutMsgCh\n\t} else {\n\t\tmgr = &ClientIHaveMgr{\n\t\t\tiHaveCh: iHaveCh,\n\t\t\tentries: entries,\n\t\t\toutMsgCh: outMsgCh,\n\t\t\tstopCh: stopCh,\n\t\t}\n\t}\n\treturn\n}"} {"input": "package learn\n\nimport (\n\t\"fmt\"\n)\n\ntype List struct {\n\tData interface{}\n\tNextnode *List\n}\n\nfunc myPrint(t interface{}) {\n\tfmt.Println(t)\n}\n\n\n\n\n\nfunc (l *List) GetEle(i int) (ele interface{}) {\n\tif i < 0 || i > l.ListLength() {\n\t\treturn nil\n\t}\n\tcur := l\n\tj := 1\n\tfor cur.Nextnode != nil {\n\t\tif j == i {\n\t\t\treturn cur.Data\n\t\t}\n\t\tj++\n\t\tcur = cur.Nextnode\n\n\t}\n\tif cur != nil && j == i {\n\t\treturn cur.Data\n\t}\n\treturn nil\n}\n\n\nfunc (l *List) ListInsert(i int, ele interface{}) bool {\n\tvar s List \n\tif i < 0 || i > l.ListLength() {\n\t\treturn false\n\t}\n\ts.Data = ele\n\tp := l\n\tj := 1\n\tfor j < i && p != nil {\n\t\tj++\n\t\tp = p.Nextnode\n\t}\n\tif p != nil && j <= i {\n\t\ts.Nextnode = p.Nextnode\n\t\tp.Nextnode = &s\n\t} else {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\nfunc (l *List) ListDelete(i int) bool {\n\tp := l\n\tj := 1\n\tfor j < i && p != nil {\n\t\tj++\n\t\tp = p.Nextnode\n\t}\n\tif p == nil || j > i {\n\t\treturn false\n\t}\n\tp.Nextnode = p.Nextnode.Nextnode\n\treturn true\n}\n\n\nfunc (l *List) ListAll() (all string) {\n\tp := l\n\tfor p != nil {\n\t\tall += fmt.Sprintf(\"%v+\", p.Data)\n\t\tp = p.Nextnode\n\t}\n\treturn all\n}\n\nfunc (l *List) ListLength() int ", "output": "{\n\tvar i int = 0\n\tn := l\n\tfor n.Nextnode != nil {\n\t\ti++\n\t\tn = n.Nextnode\n\t}\n\treturn i + 1\n}"} {"input": "package rfc3164\n\nimport (\n\t\"time\"\n)\n\n\ntype YearOperator interface {\n\tApply() int\n}\n\n\ntype YearOperation struct {\n\tOperator YearOperator\n}\n\n\nfunc (y YearOperation) Operate() int {\n\treturn y.Operator.Apply()\n}\n\n\ntype CurrentYear struct{}\n\n\nfunc (CurrentYear) Apply() int {\n\treturn time.Now().Year()\n}\n\n\ntype Year struct {\n\tYYYY int\n}\n\n\n\n\nfunc (y Year) Apply() int ", "output": "{\n\treturn y.YYYY\n}"} {"input": "package analytics\n\n\ntype SortByEnum string\n\n\nconst (\n\tSortByCapacityType SortByEnum = \"capacityType\"\n\tSortByCapacityValue SortByEnum = \"capacityValue\"\n\tSortByFeatureSet SortByEnum = \"featureSet\"\n\tSortByLifecycleState SortByEnum = \"lifecycleState\"\n\tSortByName SortByEnum = \"name\"\n\tSortByTimeCreated SortByEnum = \"timeCreated\"\n)\n\nvar mappingSortBy = map[string]SortByEnum{\n\t\"capacityType\": SortByCapacityType,\n\t\"capacityValue\": SortByCapacityValue,\n\t\"featureSet\": SortByFeatureSet,\n\t\"lifecycleState\": SortByLifecycleState,\n\t\"name\": SortByName,\n\t\"timeCreated\": SortByTimeCreated,\n}\n\n\n\n\nfunc GetSortByEnumValues() []SortByEnum ", "output": "{\n\tvalues := make([]SortByEnum, 0)\n\tfor _, v := range mappingSortBy {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package runtime\n\nimport (\n\t\"gopkg.in/v1/yaml\"\n)\n\n\n\n\n\n\n\n\n\n\nfunc (a Object) MarshalJSON() ([]byte, error) {\n\tif a.Object == nil {\n\t\treturn []byte(\"null\"), nil\n\t}\n\n\treturn Encode(a.Object)\n}\n\n\nfunc (a *Object) SetYAML(tag string, value interface{}) bool {\n\tif value == nil {\n\t\ta.Object = nil\n\t\treturn true\n\t}\n\tb, err := yaml.Marshal(value)\n\tif err != nil {\n\t\tpanic(\"yaml can't reverse its own object\")\n\t}\n\tobj, err := Decode(b)\n\tif err != nil {\n\t\treturn false\n\t}\n\ta.Object = obj\n\treturn true\n}\n\n\nfunc (a Object) GetYAML() (tag string, value interface{}) {\n\tif a.Object == nil {\n\t\tvalue = \"null\"\n\t\treturn\n\t}\n\tv, err := Encode(a.Object)\n\tif err != nil {\n\t\tpanic(\"impossible to encode API object!\")\n\t}\n\treturn tag, v\n}\n\nfunc (a *Object) UnmarshalJSON(b []byte) error ", "output": "{\n\tif len(b) == 4 && string(b) == \"null\" {\n\t\ta.Object = nil\n\t\treturn nil\n\t}\n\n\tobj, err := Decode(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.Object = obj\n\treturn nil\n}"} {"input": "package filestack\n\nimport \"strconv\"\n\ntype FilestackEvent struct {\n\tAction string `json:\"action\"`\n\tTimeStamp int64 `json:\"timestamp\"`\n\tId int `json:\"id\"`\n}\n\nfunc (fe *FilestackEvent) Tags() map[string]string {\n\treturn map[string]string{\n\t\t\"action\": fe.Action,\n\t}\n}\n\n\n\nfunc (fe *FilestackEvent) Fields() map[string]interface{} ", "output": "{\n\treturn map[string]interface{}{\n\t\t\"id\": strconv.Itoa(fe.Id),\n\t}\n}"} {"input": "package gochimp\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype APIError struct {\n\tStatus string `json:\"status\"`\n\tCode int `json:\"code\"`\n\tName string `json:\"name\"`\n\tErr string `json:\"error\"`\n}\n\n\n\nfunc chimpErrorCheck(body []byte) error {\n\tvar e APIError\n\tjson.Unmarshal(body, &e)\n\tif e.Err != \"\" || e.Code != 0 {\n\t\treturn e\n\t}\n\treturn nil\n}\n\n\ntype APITime struct {\n\ttime.Time\n}\n\nfunc (t *APITime) UnmarshalJSON(data []byte) (err error) {\n\ts := string(data)\n\tl := len(s)\n\tswitch {\n\tcase l == 12:\n\t\tt.Time, err = time.Parse(`\"2006-01-02\"`, s)\n\tcase l == 21:\n\t\tt.Time, err = time.Parse(`\"2006-01-02 15:04:05\"`, s)\n\tcase l == 9:\n\t\tt.Time, err = time.Parse(`\"2006-01\"`, s)\n\t}\n\treturn\n}\n\n\nconst APITimeFormat = \"2006-01-02 15:04:05\"\n\nfunc apiTime(t interface{}) interface{} {\n\tswitch ti := t.(type) {\n\tcase time.Time:\n\t\treturn ti.Format(APITimeFormat)\n\tcase string:\n\t\treturn ti\n\t}\n\treturn t\n}\n\nfunc (e APIError) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"%v: %v\", e.Code, e.Err)\n}"} {"input": "package files\n\nimport (\n\tu \"github.com/araddon/gou\"\n\t\"github.com/lytics/cloudstorage\"\n\n\t\"github.com/araddon/qlbridge/datasource\"\n\t\"github.com/araddon/qlbridge/schema\"\n)\n\nvar (\n\t_ FileHandler = (*csvFiles)(nil)\n)\n\n\n\n\ntype csvFiles struct {\n\tappendcols []string\n}\n\nfunc (m *csvFiles) Init(store FileStore, ss *schema.Schema) error { return nil }\nfunc (m *csvFiles) FileAppendColumns() []string { return m.appendcols }\nfunc (m *csvFiles) File(path string, obj cloudstorage.Object) *FileInfo {\n\treturn FileInfoFromCloudObject(path, obj)\n}\nfunc (m *csvFiles) Scanner(store cloudstorage.StoreReader, fr *FileReader) (schema.ConnScanner, error) {\n\tcsv, err := datasource.NewCsvSource(fr.Table, 0, fr.F, fr.Exit)\n\tif err != nil {\n\t\tu.Errorf(\"Could not open file for csv reading %v\", err)\n\t\treturn nil, err\n\t}\n\treturn csv, nil\n}\n\nfunc init() ", "output": "{\n\tRegisterFileHandler(\"csv\", &csvFiles{})\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n\n\t\"github.com/n0rad/go-erlog/errs\"\n)\n\ntype envMap struct {\n\tmapping map[string]string\n}\n\nfunc (e *envMap) Set(s string) error {\n\tif e.mapping == nil {\n\t\te.mapping = make(map[string]string)\n\t}\n\tpair := strings.SplitN(s, \"=\", 2)\n\tif len(pair) != 2 {\n\t\treturn errs.With(\"environment variable must be specified as name=value\")\n\t}\n\te.mapping[pair[0]] = pair[1]\n\treturn nil\n}\n\nfunc (e *envMap) String() string {\n\treturn strings.Join(e.Strings(), \"\\n\")\n}\n\n\n\nfunc (e *envMap) Type() string {\n\treturn \"envMap\"\n}\n\nfunc (e *envMap) Strings() []string ", "output": "{\n\tvar env []string\n\tfor n, v := range e.mapping {\n\t\tenv = append(env, n+\"=\"+v)\n\t}\n\treturn env\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/opencontainers/runtime-spec/specs-go\"\n\t\"github.com/urfave/cli\"\n)\n\n\n\nfunc fatal(err error) {\n\tlogrus.Error(err)\n\tfmt.Fprintln(os.Stderr, err)\n\tos.Exit(1)\n}\n\n\n\n\nfunc setupSpec(context *cli.Context) (*specs.Spec, error) ", "output": "{\n\tbundle := context.String(\"bundle\")\n\tif bundle != \"\" {\n\t\tif err := os.Chdir(bundle); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tspec, err := loadSpec(specConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnotifySocket := os.Getenv(\"NOTIFY_SOCKET\")\n\tif notifySocket != \"\" {\n\t\tsetupSdNotify(spec, notifySocket)\n\t}\n\tif os.Geteuid() != 0 {\n\t\treturn nil, fmt.Errorf(\"runc should be run as root\")\n\t}\n\treturn spec, nil\n}"} {"input": "package controller\n\nimport (\n\t\"github.com/alexivanenko/web_cv/config\"\n\t\"github.com/alexivanenko/web_cv/model\"\n\t\"github.com/gin-gonic/gin\"\n)\n\n\n\nfunc ResumeController(c *gin.Context) ", "output": "{\n\tresume := new(model.Resume)\n\tresume.LoadByLogin(config.String(\"view.nickname\"))\n\n\trender(c, \"resume.html\", gin.H{\"resume\": resume})\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSAmazonMQConfiguration_TagsEntry struct {\n\n\tKey string `json:\"Key,omitempty\"`\n\n\tValue string `json:\"Value,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) AWSCloudFormationType() string {\n\treturn \"AWS::AmazonMQ::Configuration.TagsEntry\"\n}\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\n\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) Metadata() map[string]interface{} ", "output": "{\n\treturn r._metadata\n}"} {"input": "package command\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/hashicorp/serf/serf\"\n\t\"github.com/mitchellh/cli\"\n)\n\n\ntype VersionCommand struct {\n\tRevision string\n\tVersion string\n\tVersionPrerelease string\n\tUi cli.Ui\n}\n\nfunc (c *VersionCommand) Help() string {\n\treturn \"\"\n}\n\nfunc (c *VersionCommand) Run(_ []string) int {\n\tvar versionString bytes.Buffer\n\tfmt.Fprintf(&versionString, \"Serf v%s\", c.Version)\n\tif c.VersionPrerelease != \"\" {\n\t\tfmt.Fprintf(&versionString, \".%s\", c.VersionPrerelease)\n\n\t\tif c.Revision != \"\" {\n\t\t\tfmt.Fprintf(&versionString, \" (%s)\", c.Revision)\n\t\t}\n\t}\n\n\tc.Ui.Output(versionString.String())\n\tc.Ui.Output(fmt.Sprintf(\"Agent Protocol: %d (Understands back to: %d)\",\n\t\tserf.ProtocolVersionMax, serf.ProtocolVersionMin))\n\treturn 0\n}\n\n\n\nfunc (c *VersionCommand) Synopsis() string ", "output": "{\n\treturn \"Prints the Serf version\"\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc map_operations() {\n\tm := make(map[string]int)\n\tm[\"Answer\"] = 42\n\tfmt.Println(\"The value:\", m[\"Answer\"])\n\tm[\"Answer\"] = 48\n\tfmt.Println(\"The value:\", m[\"Answer\"])\n\tdelete(m, \"Answer\")\n\tfmt.Println(\"The value:\", m[\"Answer\"])\n\tv, ok := m[\"Answer\"]\n\tfmt.Println(\"The value:\", v, \"Present?\", ok)\n}\n\n\n\nfunc WordCount(s string) map[string]int ", "output": "{\n\tresult := make(map[string]int)\n\tfor _, v := range strings.Fields(s) {\n\t\t_, ok := result[v]\n\t\tif ok == false {\n\t\t\tresult[v] = 0\n\t\t}\n\t\tresult[v]++\n\t}\n\treturn result\n}"} {"input": "package services\n\nimport (\n\t\"log\"\n\n\t\"cjdavis.me/elysium/library\"\n\t\"cjdavis.me/elysium/repositories\"\n)\n\ntype BookService struct {\n}\n\nfunc NewBookService() *BookService {\n\treturn &BookService{}\n}\n\nfunc (self *BookService) GetAllBooks() []library.Book {\n\tbooks, err := repositories.GetBookRepository().GetAllBooks()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn books\n}\n\n\n\nfunc (self *BookService) GetBooksByAuthor(authorID int) []library.Book ", "output": "{\n\tbooks, err := repositories.GetBookRepository().GetBooksByAuthor(authorID)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn books\n}"} {"input": "package instructions\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/bongo227/goory/types\"\n\n\t\"github.com/bongo227/goory/value\"\n)\n\n\ntype CondBr struct {\n\tblock value.Value\n\tname string\n\tcondition value.Value\n\ttrueBlock value.Value\n\tfalseBlock value.Value\n}\n\nfunc NewCondBr(block value.Value, name string, condition value.Value, trueBlock value.Value, falseBlock value.Value) *CondBr {\n\tif !condition.Type().Equal(types.NewBoolType()) {\n\t\tpanic(\"condition is not a bool type\")\n\t}\n\n\tif !trueBlock.Type().Equal(types.NewBlockType()) {\n\t\tpanic(\"trueBlock is not a block type\")\n\t}\n\n\tif !falseBlock.Type().Equal(types.NewBlockType()) {\n\t\tpanic(\"falseBlock is not a block type\")\n\t}\n\n\treturn &CondBr{block, name, condition, trueBlock, falseBlock}\n}\n\nfunc (i *CondBr) Block() value.Value {\n\treturn i.block\n}\n\nfunc (i *CondBr) IsTerminator() bool {\n\treturn true\n}\n\nfunc (i *CondBr) Type() types.Type {\n\treturn types.VOID\n}\n\n\n\nfunc (i *CondBr) Llvm() string {\n\treturn fmt.Sprintf(\"br i1 %s, label %%%s, label %%%s\",\n\t\ti.condition.Ident(),\n\t\ti.trueBlock.Ident(),\n\t\ti.falseBlock.Ident())\n}\n\nfunc (i *CondBr) Ident() string ", "output": "{\n\treturn \"%\" + i.name\n}"} {"input": "package loggo\n\nvar (\n\tdefaultContext = newDefaultContxt()\n)\n\nfunc newDefaultContxt() *Context {\n\tctx := NewContext(WARNING)\n\tctx.AddWriter(DefaultWriterName, defaultWriter())\n\treturn ctx\n}\n\n\nfunc DefaultContext() *Context {\n\treturn defaultContext\n}\n\n\n\n\n\nfunc LoggerInfo() string {\n\treturn defaultContext.Config().String()\n}\n\n\n\nfunc GetLogger(name string, size ...int) Logger {\n\treturn defaultContext.GetLogger(name, size...)\n}\n\n\n\n\n\nfunc ResetLogging() {\n\tdefaultContext.ResetLoggerLevels()\n\tdefaultContext.ResetWriters()\n}\n\n\n\n\n\n\n\nfunc ReplaceDefaultWriter(writer Writer) (Writer, error) {\n\treturn defaultContext.ReplaceWriter(DefaultWriterName, writer)\n}\n\n\n\n\nfunc RegisterWriter(name string, writer Writer) error {\n\treturn defaultContext.AddWriter(name, writer)\n}\n\n\n\nfunc RemoveWriter(name string) (Writer, error) {\n\treturn defaultContext.RemoveWriter(name)\n}\n\n\n\n\n\n\n\n\n\n\nfunc ConfigureLoggers(specification string) error {\n\tconfig, err := ParseConfigString(specification)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefaultContext.ApplyConfig(config)\n\treturn nil\n}\n\nfunc ResetWriters() ", "output": "{\n\tdefaultContext.ResetWriters()\n}"} {"input": "package databasemanagement\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ResetDatabaseParametersRequest struct {\n\n\tManagedDatabaseId *string `mandatory:\"true\" contributesTo:\"path\" name:\"managedDatabaseId\"`\n\n\tResetDatabaseParametersDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ResetDatabaseParametersRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ResetDatabaseParametersRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request ResetDatabaseParametersRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ResetDatabaseParametersResponse struct {\n\n\tRawResponse *http.Response\n\n\tUpdateDatabaseParametersResult `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ResetDatabaseParametersResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ResetDatabaseParametersResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ResetDatabaseParametersRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/atlassian/git-lob/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n)\n\ntype BeEmptyMatcher struct {\n}\n\nfunc (matcher *BeEmptyMatcher) Match(actual interface{}) (success bool, err error) {\n\tlength, ok := lengthOf(actual)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"BeEmpty matcher expects a string/array/map/channel/slice. Got:\\n%s\", format.Object(actual, 1))\n\t}\n\n\treturn length == 0, nil\n}\n\nfunc (matcher *BeEmptyMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"to be empty\")\n}\n\n\n\nfunc (matcher *BeEmptyMatcher) NegatedFailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn format.Message(actual, \"not to be empty\")\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\ntype Command struct {\n\tinput string\n}\n\n\n\nfunc (c *Command) parse(input string) (string, []string) {\n\tinputs := strings.Split(input, \" \")\n\tname := inputs[0]\n\targs := inputs[1:]\n\n\treturn name, args\n}\n\nfunc (c *Command) Run() ", "output": "{\n\tname, args := c.parse(c.input)\n\n\tcmd := exec.Command(name, args...)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"input": "package types\n\nimport \"time\"\n\ntype Comments struct {\n\tTotalCount int `json:\"total_count\"`\n\tPagination Pagination `json:\"pagination\"`\n\tList []Comment `json:\"list\"`\n}\n\ntype Comment struct {\n\tID string `json:\"id\"`\n\tTimeUnix int64 `json:\"time\"`\n\tAuthor Author `json:\"author\"`\n\tText string `json:\"text\"`\n\tLinkURL string `json:\"link_href\"`\n\tRating Rating `json:\"rating\"`\n\tVotes Votes `json:\"votes\"`\n\tEdits Edits `json:\"edits\"`\n}\n\n\n\ntype Author struct {\n\tID string `json:\"id\"`\n\tName string `json:\"name\"`\n}\n\ntype Rating struct {\n\tVideo int `json:\"video\"`\n\tAudio int `json:\"audio\"`\n}\n\ntype Votes struct {\n\tPositive int `json:\"positive\"`\n\tNegative int `json:\"negative\"`\n}\n\ntype Edits struct {\n\tCount int `json:\"count\"`\n\tLastUnix int64 `json:\"last\"`\n}\n\nfunc (edits *Edits) GetLastEditTime() time.Time {\n\treturn time.Unix(edits.LastUnix, 0)\n}\n\nfunc (c *Comment) GetTime() time.Time ", "output": "{\n\treturn time.Unix(c.TimeUnix, 0)\n}"} {"input": "package gzip\n\nimport (\n\t\"net/http\"\n\t\"path\"\n\n\t\"github.com/mholt/caddy/middleware\"\n)\n\n\ntype Filter interface {\n\tShouldCompress(*http.Request) bool\n}\n\n\nvar defaultExtensions = []string{\"\", \".txt\", \".htm\", \".html\", \".css\", \".php\", \".js\", \".json\", \".md\", \".xml\"}\n\n\n\n\n\ntype ExtFilter struct {\n\tExts Set\n}\n\n\nconst ExtWildCard = \"*\"\n\n\n\n\nfunc (e ExtFilter) ShouldCompress(r *http.Request) bool {\n\text := path.Ext(r.URL.Path)\n\treturn e.Exts.Contains(ExtWildCard) || e.Exts.Contains(ext)\n}\n\n\ntype PathFilter struct {\n\tIgnoredPaths Set\n}\n\n\n\n\nfunc (p PathFilter) ShouldCompress(r *http.Request) bool {\n\treturn !p.IgnoredPaths.ContainsFunc(func(value string) bool {\n\t\treturn middleware.Path(r.URL.Path).Matches(value)\n\t})\n}\n\n\ntype Set map[string]struct{}\n\n\nfunc (s Set) Add(value string) {\n\ts[value] = struct{}{}\n}\n\n\nfunc (s Set) Remove(value string) {\n\tdelete(s, value)\n}\n\n\nfunc (s Set) Contains(value string) bool {\n\t_, ok := s[value]\n\treturn ok\n}\n\n\n\n\nfunc (s Set) ContainsFunc(f func(string) bool) bool {\n\tfor k, _ := range s {\n\t\tif f(k) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc DefaultExtFilter() ExtFilter ", "output": "{\n\tm := ExtFilter{Exts: make(Set)}\n\tfor _, extension := range defaultExtensions {\n\t\tm.Exts.Add(extension)\n\t}\n\treturn m\n}"} {"input": "package system \n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\nfunc MkdirAllWithACL(path string, perm os.FileMode, sddl string) error {\n\treturn os.MkdirAll(path, perm)\n}\n\n\n\n\n\n\nfunc IsAbs(path string) bool {\n\treturn filepath.IsAbs(path)\n}\n\n\n\n\n\n\n\n\n\nfunc CreateSequential(name string) (*os.File, error) {\n\treturn os.Create(name)\n}\n\n\n\n\n\nfunc OpenSequential(name string) (*os.File, error) {\n\treturn os.Open(name)\n}\n\n\n\n\n\n\nfunc OpenFileSequential(name string, flag int, perm os.FileMode) (*os.File, error) {\n\treturn os.OpenFile(name, flag, perm)\n}\n\n\n\n\n\n\n\n\n\n\nfunc TempFileSequential(dir, prefix string) (f *os.File, err error) {\n\treturn ioutil.TempFile(dir, prefix)\n}\n\nfunc MkdirAll(path string, perm os.FileMode) error ", "output": "{\n\treturn os.MkdirAll(path, perm)\n}"} {"input": "package mgutil\n\nimport (\n\t\"unicode/utf8\"\n)\n\n\nfunc RepositionLeft(src []byte, pos int, cond func(rune) bool) int {\n\tfor 0 <= pos && pos < len(src) {\n\t\tr, n := utf8.DecodeLastRune(src[:pos])\n\t\tif n < 1 || !cond(r) {\n\t\t\tbreak\n\t\t}\n\t\tpos -= n\n\t}\n\treturn pos\n}\n\n\n\n\nfunc RepositionRight(src []byte, pos int, cond func(rune) bool) int ", "output": "{\n\tfor 0 <= pos && pos < len(src) {\n\t\tr, n := utf8.DecodeRune(src[pos:])\n\t\tif n < 1 || !cond(r) {\n\t\t\tbreak\n\t\t}\n\t\tpos += n\n\t}\n\treturn pos\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n)\n\n\n\nfunc m2() {\n var p bool\n for i := 1; i <= 100; i++ {\n p = false\n if i % 3 == 0 {\n fmt.Printf(\"Fizz\")\n p = true\n }\n if i % 5 == 0 {\n fmt.Printf(\"Buzz\")\n p = true\n }\n if !p {\n fmt.Printf(\"%d\", i)\n }\n fmt.Println()\n }\n}\n\nfunc main() {\n m1()\n m2()\n}\n\nfunc m1() ", "output": "{\n for i := 1; i <= 100; i++ {\n if i % 3 == 0 && i % 5 == 0 {\n fmt.Println(\"FizzBuzz\")\n } else if i % 3 == 0 {\n fmt.Println(\"Fizz\")\n } else if i % 5 == 0 {\n fmt.Println(\"Buzz\")\n } else {\n fmt.Println(i)\n }\n }\n}"} {"input": "package systray\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\nfunc nativeLoop() {\n\tC.nativeLoop()\n}\n\nfunc quit() {\n\tC.quit()\n}\n\n\n\n\nfunc SetIcon(iconBytes []byte) {\n\tcstr := (*C.char)(unsafe.Pointer(&iconBytes[0]))\n\tC.setIcon(cstr, (C.int)(len(iconBytes)))\n}\n\n\n\n\n\n\nfunc SetTooltip(tooltip string) {\n\tC.setTooltip(C.CString(tooltip))\n}\n\nfunc addOrUpdateMenuItem(item *MenuItem) {\n\tvar disabled C.short = 0\n\tif item.disabled {\n\t\tdisabled = 1\n\t}\n\tvar checked C.short = 0\n\tif item.checked {\n\t\tchecked = 1\n\t}\n\tC.add_or_update_menu_item(\n\n\t\tC.int(item.id),\n\t\tC.CString(item.title),\n\t\tC.CString(item.tooltip),\n\t\tdisabled,\n\t\tchecked,\n\t)\n}\n\n\nfunc systray_ready() {\n\tsystrayReady()\n}\n\n\nfunc systray_menu_item_selected(cId C.int) {\n\tsystrayMenuItemSelected(int32(cId))\n}\n\nfunc SetTitle(title string) ", "output": "{\n\tC.setTitle(C.CString(title))\n}"} {"input": "package parse\n\n\nimport (\n\t\"strings\"\n)\n\nfunc indent(s string, character string, size int) string {\n\tindent := strings.Repeat(character, size)\n\tlines := strings.Split(s, newLine)\n\tfor k, v := range lines {\n\t\tif len(v) > 0 {\n\t\t\tlines[k] = indent + v\n\t\t}\n\t}\n\treturn strings.Join(lines, newLine)\n}\n\n\n\nfunc EqualSlicesFoldPrefix(a, prefix []string) bool {\n\tl, lprefix := len(a), len(prefix)\n\tswitch {\n\tcase lprefix == 0:\n\t\treturn true\n\tcase l < lprefix:\n\t\treturn false\n\tcase l > lprefix:\n\t\treturn EqualSlicesFold(a[:lprefix], prefix)\n\tdefault:\n\t\treturn EqualSlicesFold(a, prefix)\n\t}\n}\n\n\n\nfunc EqualSlicesFoldSuffix(a, suffix []string) bool {\n\tl, lsuffix := len(a), len(suffix)\n\tswitch {\n\tcase lsuffix == 0:\n\t\treturn true\n\tcase l < lsuffix:\n\t\treturn false\n\tcase l > lsuffix:\n\t\treturn EqualSlicesFold(a[l-lsuffix:], suffix)\n\tdefault:\n\t\treturn EqualSlicesFold(a, suffix)\n\t}\n}\n\n\n\n\n\n\n\nfunc EqualSlicesFoldSome(a []string, b ...[]string) bool {\n\tif len(a) == 0 && len(b) == 0 {\n\t\treturn true\n\t}\n\n\tfor k := range b {\n\t\tif EqualSlicesFold(a, b[k]) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc EqualSlicesFold(a, b []string) bool ", "output": "{\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor k := range a {\n\t\tif !strings.EqualFold(a[k], b[k]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package syscall\n\nfunc setTimespec(sec, nsec int64) Timespec {\n\treturn Timespec{Sec: sec, Nsec: nsec}\n}\n\nfunc setTimeval(sec, usec int64) Timeval {\n\treturn Timeval{Sec: sec, Usec: usec}\n}\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint64(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint64(length)\n}\n\n\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\n\nconst RTM_LOCK = 0x8\n\n\n\nconst SYS___SYSCTL = SYS_SYSCTL\n\nfunc (msghdr *Msghdr) SetControllen(length int) ", "output": "{\n\tmsghdr.Controllen = uint32(length)\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetServiceRequest struct {\n\n\tServiceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"serviceId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetServiceRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request GetServiceRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetServiceRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetServiceResponse struct {\n\n\tRawResponse *http.Response\n\n\tService `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetServiceResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetServiceResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetServiceRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}"} {"input": "package problemdetector\n\nimport (\n\t\"github.com/golang/glog\"\n\n\tkubeutil \"k8s.io/kubernetes/pkg/util\"\n\n\t\"k8s.io/node-problem-detector/pkg/condition\"\n\t\"k8s.io/node-problem-detector/pkg/kernelmonitor\"\n\t\"k8s.io/node-problem-detector/pkg/problemclient\"\n\t\"k8s.io/node-problem-detector/pkg/util\"\n)\n\n\ntype ProblemDetector interface {\n\tRun() error\n}\n\ntype problemDetector struct {\n\tclient problemclient.Client\n\tconditionManager condition.ConditionManager\n\tmonitor kernelmonitor.KernelMonitor\n}\n\n\n\nfunc NewProblemDetector(monitor kernelmonitor.KernelMonitor) ProblemDetector {\n\tclient := problemclient.NewClientOrDie()\n\treturn &problemDetector{\n\t\tclient: client,\n\t\tconditionManager: condition.NewConditionManager(client, kubeutil.RealClock{}),\n\t\tmonitor: monitor,\n\t}\n}\n\n\n\n\nfunc (p *problemDetector) Run() error ", "output": "{\n\tp.conditionManager.Start()\n\tch, err := p.monitor.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\tglog.Info(\"Problem detector started\")\n\tfor {\n\t\tselect {\n\t\tcase status := <-ch:\n\t\t\tfor _, event := range status.Events {\n\t\t\t\tp.client.Eventf(util.ConvertToAPIEventType(event.Severity), status.Source, event.Reason, event.Message)\n\t\t\t}\n\t\t\tfor _, condition := range status.Conditions {\n\t\t\t\tp.conditionManager.UpdateCondition(condition)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package oleacc\n\nimport (\n\t\"unsafe\"\n\n\t\"github.com/go-ole/go-ole\"\n)\n\ntype IUIAutomationEventHandler struct {\n\tole.IUnknown\n}\n\ntype IUIAutomationEventHandlerVtbl struct {\n\tole.IUnknownVtbl\n\tHandleAutomationEvent uintptr\n}\n\n\n\nfunc (v *IUIAutomationEventHandler) HandleAutomationEvent() error {\n\treturn ole.NewError(ole.E_NOTIMPL)\n}\n\nfunc (v *IUIAutomationEventHandler) VTable() *IUIAutomationEventHandlerVtbl ", "output": "{\n\treturn (*IUIAutomationEventHandlerVtbl)(unsafe.Pointer(v.RawVTable))\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"path/filepath\"\n\n\t\"github.com/xeipuuv/gojsonschema\"\n)\n\ntype jsonschema map[string]gojsonschema.JSONLoader\n\nvar schemas = []string{\n\t\"notification\",\n}\n\n\n\nfunc (js *jsonschema) validateJSON(jsonType, json string) bool {\n\tloader := gojsonschema.NewStringLoader(json)\n\tschemaLoader, ok := (*js)[jsonType]\n\tif !ok {\n\t\treturn false\n\t}\n\n\tresult, err := gojsonschema.Validate(schemaLoader, loader)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn result.Valid()\n}\n\nfunc newJSONSchema() *jsonschema ", "output": "{\n\tjs := &jsonschema{}\n\n\tfor _, name := range schemas {\n\t\tpath, err := filepath.Abs(name)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\t(*js)[name] = gojsonschema.NewReferenceLoader(\"file://\" + path + \".json\")\n\t}\n\n\treturn js\n}"} {"input": "package repo\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/user\"\n\t\"path/filepath\"\n)\n\nconst netrcFile = `\nmachine %s\nlogin %s\npassword %s\n`\n\n\nfunc WriteKey(privateKey string) error {\n\tif privateKey == \"\" {\n\t\treturn nil\n\t}\n\n\thome := \"/root\"\n\n\tif currentUser, err := user.Current(); err == nil {\n\t\thome = currentUser.HomeDir\n\t}\n\n\tsshpath := filepath.Join(\n\t\thome,\n\t\t\".ssh\")\n\n\tif err := os.MkdirAll(sshpath, 0700); err != nil {\n\t\treturn err\n\t}\n\n\tconfpath := filepath.Join(\n\t\tsshpath,\n\t\t\"config\")\n\n\tprivpath := filepath.Join(\n\t\tsshpath,\n\t\t\"id_rsa\")\n\n\tioutil.WriteFile(\n\t\tconfpath,\n\t\t[]byte(\"StrictHostKeyChecking no\\n\"),\n\t\t0700)\n\n\treturn ioutil.WriteFile(\n\t\tprivpath,\n\t\t[]byte(privateKey),\n\t\t0600)\n}\n\n\nfunc WriteNetrc(machine, login, password string) error {\n\tif machine == \"\" {\n\t\treturn nil\n\t}\n\n\tnetrcContent := fmt.Sprintf(\n\t\tnetrcFile,\n\t\tmachine,\n\t\tlogin,\n\t\tpassword,\n\t)\n\n\thome := \"/root\"\n\n\tif currentUser, err := user.Current(); err == nil {\n\t\thome = currentUser.HomeDir\n\t}\n\n\tnetpath := filepath.Join(\n\t\thome,\n\t\t\".netrc\")\n\n\treturn ioutil.WriteFile(\n\t\tnetpath,\n\t\t[]byte(netrcContent),\n\t\t0600)\n}\n\n\n\n\nfunc WriteToken(remote string, login, password string) (string, error) ", "output": "{\n\tif remote == \"\" || login == \"\" || password == \"\" {\n\t\treturn remote, nil\n\t}\n\n\tu, err := url.Parse(remote)\n\n\tif err != nil {\n\t\treturn remote, err\n\t}\n\n\tu.User = url.UserPassword(login, password)\n\n\treturn u.String(), nil\n}"} {"input": "package darwini\n\nimport (\n\t\"net/http\"\n)\n\n\n\n\n\n\n\ntype Method struct {\n\tGET http.HandlerFunc\n\tPOST http.HandlerFunc\n\tPUT http.HandlerFunc\n\tPATCH http.HandlerFunc\n\tDELETE http.HandlerFunc\n\tCustom map[string]http.HandlerFunc\n}\n\nvar _ http.Handler = Method{}\n\nfunc (m Method) get(method string) http.HandlerFunc {\n\tswitch method {\n\tcase \"GET\":\n\t\treturn m.GET\n\tcase \"POST\":\n\t\treturn m.POST\n\tcase \"PUT\":\n\t\treturn m.PUT\n\tcase \"PATCH\":\n\t\treturn m.PATCH\n\tcase \"DELETE\":\n\t\treturn m.DELETE\n\tdefault:\n\t\treturn m.Custom[method]\n\t}\n}\n\n\n\nfunc (m Method) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\th := m.get(req.Method)\n\tif h == nil {\n\t\tm.err(w, req)\n\t\treturn\n\t}\n\th.ServeHTTP(w, req)\n}\n\nfunc (m Method) err(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tif m.GET != nil {\n\t\tw.Header().Add(\"Allow\", \"GET\")\n\t}\n\tif m.POST != nil {\n\t\tw.Header().Add(\"Allow\", \"POST\")\n\t}\n\tif m.PUT != nil {\n\t\tw.Header().Add(\"Allow\", \"PUT\")\n\t}\n\tif m.PATCH != nil {\n\t\tw.Header().Add(\"Allow\", \"PATCH\")\n\t}\n\tif m.DELETE != nil {\n\t\tw.Header().Add(\"Allow\", \"DELETE\")\n\t}\n\tfor k, v := range m.Custom {\n\t\tif v != nil {\n\t\t\tw.Header().Add(\"Allow\", k)\n\t\t}\n\t}\n\thttp.Error(w, \"method not allowed\", http.StatusMethodNotAllowed)\n}"} {"input": "package sw\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/sha256\"\n\t\"crypto/x509\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/hyperledger/fabric/bccsp\"\n)\n\n\n\n\n\n\ntype rsaPublicKey struct{ pubKey *rsa.PublicKey }\n\nfunc (k *rsaPublicKey) Symmetric() bool { return false }\nfunc (k *rsaPublicKey) Private() bool { return false }\nfunc (k *rsaPublicKey) PublicKey() (bccsp.Key, error) { return k, nil }\n\n\n\n\n\nfunc (k *rsaPublicKey) SKI() []byte {\n\tif k.pubKey == nil {\n\t\treturn nil\n\t}\n\n\traw := x509.MarshalPKCS1PublicKey(k.pubKey)\n\thash := sha256.Sum256(raw)\n\treturn hash[:]\n}\n\nfunc (k *rsaPublicKey) Bytes() (raw []byte, err error) ", "output": "{\n\tif k.pubKey == nil {\n\t\treturn nil, errors.New(\"Failed marshalling key. Key is nil.\")\n\t}\n\traw, err = x509.MarshalPKIXPublicKey(k.pubKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed marshalling key [%s]\", err)\n\t}\n\treturn\n}"} {"input": "package kthlargest\n\nimport \"container/heap\"\n\ntype MaxHeap struct {\n\tSize int\n\tNums []int\n}\n\nfunc (h *MaxHeap) Insert(x int) {\n\tif h.Len() < h.Size {\n\t\theap.Push(h, x)\n\t} else if h.Nums[0] < x {\n\t\th.Nums[0] = x\n\t\theap.Fix(h, 0)\n\t}\n}\n\nfunc (h *MaxHeap) Len() int { return len(h.Nums) }\n\nfunc (h *MaxHeap) Less(i, j int) bool {\n\treturn h.Nums[i] < h.Nums[j]\n}\n\nfunc (h *MaxHeap) Swap(i, j int) {\n\th.Nums[i], h.Nums[j] = h.Nums[j], h.Nums[i]\n}\n\nfunc (h *MaxHeap) Push(x interface{}) {\n\th.Nums = append(h.Nums, x.(int))\n}\n\n\n\nfunc findKthLargest(nums []int, k int) int {\n\th := &MaxHeap{Size: k}\n\tfor _, num := range nums {\n\t\th.Insert(num)\n\t}\n\treturn h.Nums[0]\n}\n\nfunc (h *MaxHeap) Pop() interface{} ", "output": "{\n\tn := len(h.Nums)\n\tx := h.Nums[n-1]\n\th.Nums = h.Nums[:n-1]\n\treturn x\n}"} {"input": "package trace\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/zrepl/zrepl/util/chainlock\"\n)\n\ntype SpanInfo interface {\n\tStartedAt() time.Time\n\tEndedAt() time.Time\n\tTaskAndSpanStack(kind *StackKind) string\n}\n\ntype Callback struct {\n\tOnBegin func(ctx context.Context)\n\tOnEnd func(ctx context.Context, spanInfo SpanInfo)\n}\n\nvar callbacks struct {\n\tmtx chainlock.L\n\tcs []Callback\n}\n\nfunc RegisterCallback(c Callback) {\n\tcallbacks.mtx.HoldWhile(func() {\n\t\tcallbacks.cs = append(callbacks.cs, c)\n\t})\n}\n\n\n\nfunc callbackBeginSpan(ctx context.Context) func(SpanInfo) ", "output": "{\n\n\n\tvar cbs []Callback\n\tcallbacks.mtx.HoldWhile(func() {\n\t\tcbs = callbacks.cs\n\t})\n\tfor _, cb := range cbs {\n\t\tif cb.OnBegin != nil {\n\t\t\tcb.OnBegin(ctx)\n\t\t}\n\t}\n\treturn func(spanInfo SpanInfo) {\n\t\tfor _, cb := range cbs {\n\t\t\tif cb.OnEnd != nil {\n\t\t\t\tcb.OnEnd(ctx, spanInfo)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package dep\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net/http\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n\n\t\"github.com/micromdm/micromdm/dep\"\n\t\"github.com/micromdm/micromdm/pkg/httputil\"\n)\n\nfunc (svc *DEPService) AssignProfile(ctx context.Context, id string, serials ...string) (*dep.ProfileResponse, error) {\n\tif svc.client == nil {\n\t\treturn nil, errors.New(\"DEP not configured yet. add a DEP token to enable DEP\")\n\t}\n\treturn svc.client.AssignProfile(id, serials...)\n}\n\ntype assignProfileRequest struct {\n\tID string `json:\"id\"`\n\tSerials []string `json:\"serials\"`\n}\n\ntype assignProfileResponse struct {\n\t*dep.ProfileResponse\n\tErr error `json:\"err,omitempty\"`\n}\n\nfunc (r assignProfileResponse) Failed() error { return r.Err }\n\nfunc decodeAssignProfileRequest(ctx context.Context, r *http.Request) (interface{}, error) {\n\tvar req assignProfileRequest\n\terr := httputil.DecodeJSONRequest(r, &req)\n\treturn req, err\n}\n\nfunc decodeAssignProfileResponse(_ context.Context, r *http.Response) (interface{}, error) {\n\tvar resp assignProfileResponse\n\terr := httputil.DecodeJSONResponse(r, &resp)\n\treturn resp, err\n}\n\n\n\nfunc (e Endpoints) AssignProfile(ctx context.Context, id string, serials ...string) (*dep.ProfileResponse, error) {\n\trequest := assignProfileRequest{ID: id, Serials: serials}\n\tresp, err := e.AssignProfileEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponse := resp.(assignProfileResponse)\n\treturn response.ProfileResponse, response.Err\n}\n\nfunc MakeAssignProfileEndpoint(svc Service) endpoint.Endpoint ", "output": "{\n\treturn func(ctx context.Context, request interface{}) (response interface{}, err error) {\n\t\treq := request.(assignProfileRequest)\n\t\tresp, err := svc.AssignProfile(ctx, req.ID, req.Serials...)\n\t\treturn &assignProfileResponse{\n\t\t\tProfileResponse: resp,\n\t\t\tErr: err,\n\t\t}, nil\n\t}\n}"} {"input": "package tracers\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\n\t\"github.com/ethereum/go-ethereum/common\"\n\t\"github.com/ethereum/go-ethereum/core/vm\"\n)\n\n\n\ntype Context struct {\n\tBlockHash common.Hash \n\tTxIndex int \n\tTxHash common.Hash \n}\n\n\n\ntype Tracer interface {\n\tvm.EVMLogger\n\tGetResult() (json.RawMessage, error)\n\tStop(err error)\n}\n\ntype lookupFunc func(string, *Context) (Tracer, error)\n\nvar (\n\tlookups []lookupFunc\n)\n\n\n\n\n\nfunc RegisterLookup(wildcard bool, lookup lookupFunc) {\n\tif wildcard {\n\t\tlookups = append(lookups, lookup)\n\t} else {\n\t\tlookups = append([]lookupFunc{lookup}, lookups...)\n\t}\n}\n\n\n\n\n\nfunc New(code string, ctx *Context) (Tracer, error) ", "output": "{\n\tfor _, lookup := range lookups {\n\t\tif tracer, err := lookup(code, ctx); err == nil {\n\t\t\treturn tracer, nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"tracer not found\")\n}"} {"input": "package saltboot\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/hortonworks/salt-bootstrap/saltboot/model\"\n)\n\n\n\nfunc HealthCheckHandler(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tlog.Printf(\"[HealthCheckHandler] handleHealtchCheck executed\")\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tmodel.Response{Status: \"OK\", Version: Version + \"-\" + BuildTime}.WriteHttp(w)\n}"} {"input": "package apimgr\n\nimport \"reflect\"\n\nfunc newSorter(manager *Manager) *sorter {\n\tapis := []Definition{}\n\tfor _, api := range manager.apiMethodPatternMap {\n\t\tapis = append(apis, api)\n\t}\n\treturn &sorter{\n\t\tManager: manager,\n\t\tapis: apis,\n\t}\n}\n\ntype sorter struct {\n\t*Manager\n\n\tapis []Definition\n}\n\nfunc (t sorter) Len() int {\n\treturn len(t.apis)\n}\n\nfunc (t sorter) Swap(i int, j int) {\n\tt.apis[i], t.apis[j] = t.apis[j], t.apis[i]\n}\n\nfunc (t sorter) Less(i int, j int) bool {\n\tki := t.getSortKey(t.apis[i])\n\tkj := t.getSortKey(t.apis[j])\n\treturn ki < kj\n}\n\n\n\nfunc (t sorter) getSortKey(api Definition) string ", "output": "{\n\tpkgpath := getPackagePath(reflect.ValueOf(api.Request))\n\tkey := pkgpath + \" \" + t.GetMethodPatternKey(t.Manager, api)\n\treturn key\n}"} {"input": "package language\n\n\n\nconst (\n\tcurDigitBits = 3\n\tcurDigitMask = 1<> curDigitBits)\n}\n\nfunc (c currencyInfo) decimals() int {\n\treturn int(c & curDigitMask)\n}\n\n\ntype langAliasType int8\n\nconst (\n\tlangDeprecated langAliasType = iota\n\tlangMacro\n\tlangLegacy\n\n\tlangAliasTypeUnknown langAliasType = -1\n)\n\nfunc mkCurrencyInfo(round, decimal int) string ", "output": "{\n\treturn string([]byte{byte(round<Set

`)\n}\n\n\n\nfunc read(w http.ResponseWriter, r *http.Request) {\n\tcoo, err := r.Cookie(cookieName)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Redirect(w, r, \"/set\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tfmt.Fprintf(w, \"

Cookie Value: %s

\", coo.Value)\n\tfmt.Fprint(w, `

Expire

`)\n}\n\nfunc expire(w http.ResponseWriter, r *http.Request) {\n\tcoo, err := r.Cookie(cookieName)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Redirect(w, r, \"/set\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tcoo.MaxAge = -1 \n\thttp.SetCookie(w, coo)\n\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n}\n\nfunc set(w http.ResponseWriter, _ *http.Request) ", "output": "{\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: cookieName,\n\t\tValue: \"This is a Site Cookie created\",\n\t})\n\tfmt.Fprint(w, `

Read

`)\n}"} {"input": "package ts_test\n\nimport (\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"github.com/32bitkid/bitreader\"\n\t\"github.com/32bitkid/mpeg/ts\"\n\t\"strings\"\n)\n\n\n\n\nfunc Example() ", "output": "{\n\treader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(shortTsStream))\n\tbr := bitreader.NewReader(reader)\n\n\tpacket := new(ts.Packet)\n\tfor {\n\t\terr := packet.Next(br)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tfmt.Println(packet)\n\t}\n\n}"} {"input": "package timeutil\n\nimport (\n\t\"time\"\n)\n\n\nfunc SetTimeout(t time.Duration, callback func()) {\n\tgo func() {\n\t\ttime.Sleep(t)\n\t\tcallback()\n\t}()\n}\n\n\n\nfunc SetInterval(t time.Duration, callback func() bool) {\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(t)\n\t\t\tif !callback() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\nfunc Nanosecond() int64 {\n\treturn time.Now().UnixNano()\n}\n\n\nfunc Microsecond() int64 {\n\treturn time.Now().UnixNano() / 1e3\n}\n\n\nfunc Millisecond() int64 {\n\treturn time.Now().UnixNano() / 1e6\n}\n\n\nfunc Second() int64 {\n\treturn time.Now().UnixNano() / 1e9\n}\n\n\nfunc Date() string {\n\treturn time.Now().Format(\"2006-01-02\")\n}\n\n\nfunc Datetime() string {\n\treturn time.Now().Format(\"2006-01-02 15:04:05\")\n}\n\n\n\nfunc Format(format string, timestamps ...int64) string {\n\ttimestamp := Second()\n\tif len(timestamps) > 0 {\n\t\ttimestamp = timestamps[0]\n\t}\n\treturn time.Unix(timestamp, 0).Format(format)\n}\n\n\n\n\nfunc StrToTime(format string, timestr string) (int64, error) ", "output": "{\n\tt, err := time.Parse(format, timestr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn t.Unix(), nil\n}"} {"input": "package jaeger_test\n\nimport (\n\t\"log\"\n\n\t\"go.opencensus.io/exporter/jaeger\"\n\t\"go.opencensus.io/trace\"\n)\n\nfunc ExampleNewExporter_collector() {\n\texporter, err := jaeger.NewExporter(jaeger.Options{\n\t\tEndpoint: \"http:localhost:14268\",\n\t\tProcess: jaeger.Process{\n\t\t\tServiceName: \"trace-demo\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttrace.RegisterExporter(exporter)\n}\n\nfunc ExampleNewExporter_agent() {\n\texporter, err := jaeger.NewExporter(jaeger.Options{\n\t\tAgentEndpoint: \"localhost:6831\",\n\t\tProcess: jaeger.Process{\n\t\t\tServiceName: \"trace-demo\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttrace.RegisterExporter(exporter)\n}\n\n\n\n\n\n\nfunc ExampleNewExporter_processTags() ", "output": "{\n\texporter, err := jaeger.NewExporter(jaeger.Options{\n\t\tAgentEndpoint: \"localhost:6831\",\n\t\tProcess: jaeger.Process{\n\t\t\tServiceName: \"trace-demo\",\n\t\t\tTags: []jaeger.Tag{\n\t\t\t\tjaeger.StringTag(\"ip\", \"127.0.0.1\"),\n\t\t\t\tjaeger.BoolTag(\"demo\", true),\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttrace.RegisterExporter(exporter)\n}"} {"input": "package lg\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Stopwatch struct {\n\tstart, stop time.Time\n\tlogger *Logger\n}\n\nfunc (s *Stopwatch) IsStopped() bool { return s.stop.After(s.start) }\nfunc (s *Stopwatch) Stop() {\n\ts.stop = time.Now()\n}\n\n\n\nfunc (s *Stopwatch) Dt() string {\n\treturn fmt.Sprintf(\"%s\", s.ElapsedTime())\n}\n\nfunc (s *Stopwatch) Log(msg string) {\n\ts.logger.Info(\"elapsed\", \"msg\", msg, \"dx\", s.Dt())\n}\n\nfunc (s *Stopwatch) ElapsedTime() time.Duration ", "output": "{\n\tif s.IsStopped() {\n\t\treturn s.stop.Sub(s.start)\n\t}\n\treturn time.Since(s.start)\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"unicode\"\n)\n\n\n\nfunc main() {\n\tfile, _ := os.Open(os.Args[1])\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tif validateCC(scanner.Text()) {\n\t\t\tfmt.Println(1)\n\t\t} else {\n\t\t\tfmt.Println(0)\n\t\t}\n\t}\n}\n\n\n\nfunc validateCC(s string) bool ", "output": "{\n\tdouble := false\n\tvar sum int\n\n\tfor k := len(s) - 1; k >= 0; k -= 1 {\n\t\tif char := rune(s[k]); unicode.IsNumber(char) {\n\t\t\tnum := int(char - '0')\n\n\t\t\tif double {\n\t\t\t\tnum *= 2\n\n\t\t\t\tif num >= 10 {\n\t\t\t\t\tnum -= 9\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdouble = !double\n\t\t\tsum += num\n\t\t}\n\t}\n\n\treturn sum%10 == 0\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\t\"github.com/revel/revel\"\n\t\"runtime/debug\"\n)\n\n \n\n\nfunc PanicFilter(c *revel.Controller, fc []revel.Filter) ", "output": "{\n\tdefer func() {\n\t\tif err := recover(); err != nil && err != \"HttpException\" {\n\t\t\terror := revel.NewErrorFromPanic(err)\n\t\t\tif error == nil {\n\t\t\t\trevel.ERROR.Print(err, \"\\n\", string(debug.Stack()))\n\t\t\t\tc.Response.Out.WriteHeader(500)\n\t\t\t\tc.Response.Out.Write(debug.Stack())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\trevel.ERROR.Print(err, \"\\n\", error.Stack)\n\t\t\tc.Result = HttpException(c, 500, fmt.Sprint(err))\n\t\t}\n\t}()\n\tfc[0](c, fc[1:])\n}"} {"input": "package fake\n\nimport (\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n\n\taction \"github.com/vmware-tanzu/octant/pkg/action\"\n)\n\n\ntype MockActionRegistrar struct {\n\tctrl *gomock.Controller\n\trecorder *MockActionRegistrarMockRecorder\n}\n\n\ntype MockActionRegistrarMockRecorder struct {\n\tmock *MockActionRegistrar\n}\n\n\n\n\n\nfunc (m *MockActionRegistrar) EXPECT() *MockActionRegistrarMockRecorder {\n\treturn m.recorder\n}\n\n\nfunc (m *MockActionRegistrar) Register(arg0, arg1 string, arg2 action.DispatcherFunc) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Register\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}\n\n\nfunc (mr *MockActionRegistrarMockRecorder) Register(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Register\", reflect.TypeOf((*MockActionRegistrar)(nil).Register), arg0, arg1, arg2)\n}\n\n\nfunc (m *MockActionRegistrar) Unregister(arg0, arg1 string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Unregister\", arg0, arg1)\n}\n\n\nfunc (mr *MockActionRegistrarMockRecorder) Unregister(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Unregister\", reflect.TypeOf((*MockActionRegistrar)(nil).Unregister), arg0, arg1)\n}\n\nfunc NewMockActionRegistrar(ctrl *gomock.Controller) *MockActionRegistrar ", "output": "{\n\tmock := &MockActionRegistrar{ctrl: ctrl}\n\tmock.recorder = &MockActionRegistrarMockRecorder{mock}\n\treturn mock\n}"} {"input": "package test\n\nimport (\n\t\"arduino.cc/builder\"\n\t\"arduino.cc/builder/types\"\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\"\n)\n\n\n\nfunc TestFailIfBuildPathEqualsSketchPathSketchPathDiffers(t *testing.T) {\n\tctx := &types.Context{\n\t\tSketchLocation: \"sketchPath/sketch.ino\",\n\t\tBuildPath: \"buildPath\",\n\t}\n\n\tcommand := builder.FailIfBuildPathEqualsSketchPath{}\n\tNoError(t, command.Run(ctx))\n}\n\nfunc TestFailIfBuildPathEqualsSketchPath(t *testing.T) ", "output": "{\n\tctx := &types.Context{\n\t\tSketchLocation: \"buildPath/sketch.ino\",\n\t\tBuildPath: \"buildPath\",\n\t}\n\n\tcommand := builder.FailIfBuildPathEqualsSketchPath{}\n\trequire.Error(t, command.Run(ctx))\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\t\"testing\"\n)\n\nfunc TestContextSetVar(t *testing.T) {\n\tvar resource = NewApiResource(\"test\", \"test\")\n\tresource.SetVar(\"a\", \"123\")\n\tvar c = &Context{Resource: resource}\n\tif c.GetVar(\"a\") != \"123\" {\n\t\tt.Errorf(\"Context set var failed! Expect %s, got %s\", c.GetVar(\"a\"), \"123\")\n\t}\n}\n\n\n\nfunc TestContextRespond(t *testing.T) ", "output": "{\n\ttestPairs := []struct {\n\t\tstatus int\n\t\thandle ActionHandler\n\t}{\n\t\t{http.StatusOK, func(c *Context) { c.RespondOK(\"\") }},\n\t\t{http.StatusInternalServerError, func(c *Context) { c.RespondErrf(http.StatusInternalServerError, \"erro\") }},\n\t\t{1001, func(c *Context) { c.Respond(1001, \"\") }},\n\t}\n\n\tfor _, pair := range testPairs {\n\t\tw := new(mockResponseWriter)\n\t\tpair.handle(&Context{ResponseWriter: w})\n\n\t\tif w.status != pair.status {\n\t\t\tt.Errorf(\"Routing failed for %v get %v\", pair, w.status)\n\t\t}\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"github.com/go-openapi/runtime\"\n\thttptransport \"github.com/go-openapi/runtime/client\"\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/yamamoto-febc/sakuraio-api/gen/client\"\n)\n\n\nvar SakuraAPI = NewSakuraClient(nil)\n\n\n\n\n\nfunc NewSakuraAPI(transport runtime.ClientTransport, formats strfmt.Registry) SakuraAPIFuncs {\n\n\tcli := client.New(transport, formats)\n\tsakura := &SakuraAPIClient{\n\t\tclient: cli,\n\t}\n\treturn sakura\n}\n\n\ntype SakuraAPIClient struct {\n\tclient *client.SakuraIoT\n\tbasicAuthInfoWriter *runtime.ClientAuthInfoWriter\n}\n\nfunc NewSakuraClient(formats strfmt.Registry) SakuraAPIFuncs ", "output": "{\n\tif formats == nil {\n\t\tformats = strfmt.Default\n\t}\n\ttransport := httptransport.New(\"api.sakura.io\", \"/\", []string{\"https\"})\n\treturn NewSakuraAPI(transport, formats)\n}"} {"input": "package operator\n\nimport (\n\t\"testing\"\n\n\t\"github.com/rook/rook/pkg/operator/test\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\nfunc TestCreateCluster(t *testing.T) {\n\tclientset := test.New(3)\n\to := New(\"foo\", nil, clientset)\n\to.context.RetryDelay = 1\n\n\terr := o.initResources()\n\tassert.NotNil(t, err)\n\n\ttest := &testTPR{}\n\terr = createTPR(o.context, test)\n\tassert.Nil(t, err)\n\ttpr, err := clientset.ExtensionsV1beta1().ThirdPartyResources().List(v1.ListOptions{})\n\tassert.Nil(t, err)\n\tassert.Equal(t, 1, len(tpr.Items))\n\tassert.Equal(t, \"test.rook.io\", tpr.Items[0].Name)\n\tassert.Equal(t, test.Description(), tpr.Items[0].Description)\n\n}\n\ntype testTPR struct {\n}\n\nfunc (t *testTPR) Name() string {\n\treturn \"test\"\n}\n\nfunc (t *testTPR) Load() error {\n\treturn nil\n}\nfunc (t *testTPR) Watch() error {\n\treturn nil\n}\n\nfunc (t *testTPR) Description() string ", "output": "{\n\treturn \"test description\"\n}"} {"input": "package cron\n\nimport (\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com/kyokomi/slackbot/plugins\"\n)\n\ntype plugin struct {\n\tcron CronContext\n}\n\nfunc NewPlugin(cron CronContext) plugins.BotMessagePlugin {\n\treturn &plugin{\n\t\tcron: cron,\n\t}\n}\n\nfunc (p *plugin) CheckMessage(_ plugins.BotEvent, message string) (bool, string) {\n\tif strings.HasPrefix(message, \"cron\") {\n\t\treturn true, message\n\t}\n\treturn false, message\n}\n\nfunc (p *plugin) DoAction(event plugins.BotEvent, message string) bool {\n\tc := CronCommand{}\n\tif err := c.Scan(message); err != nil {\n\t\tlog.Printf(\"error %s\", err)\n\t\treturn false\n\t}\n\n\tswitch c.Action {\n\tcase AddAction, RandomAddAction:\n\t\tmessage := p.cron.AddCronCommand(event.Channel(), c)\n\t\tp.cron.RefreshCron(&event, event.Channel())\n\t\tevent.Reply(message)\n\tcase DelAction, DeleteAction, StopAction:\n\t\tmessage := p.cron.DelCronCommand(event.Channel(), c)\n\t\tp.cron.RefreshCron(&event, event.Channel())\n\t\tevent.Reply(message)\n\tcase ListAction:\n\t\tmessage := p.cron.ListCronCommand(event.Channel(), c)\n\t\tevent.Reply(message)\n\tcase RefreshAction:\n\t\tp.cron.RefreshCron(&event, event.Channel())\n\t\tevent.Reply(\"```\\nrefresh ok\\n```\")\n\tcase HelpAction:\n\t\tmessage := p.cron.HelpCronCommand(event.Channel(), c)\n\t\tevent.Reply(message)\n\t}\n\treturn false\n}\n\n\n\nvar _ plugins.BotMessagePlugin = (*plugin)(nil)\n\nfunc (p *plugin) Help() string ", "output": "{\n\treturn \"cron: cron制御できます\\n\" + helpText\n}"} {"input": "package testutil\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\ntype Context struct {\n\tName string `yaml:\"name,omitempty\"`\n\tContext struct {\n\t\tNamespace string `yaml:\"namespace,omitempty\"`\n\t} `yaml:\"context,omitempty\"`\n}\n\nfunc Ctx(name string) *Context { return &Context{Name: name} }\nfunc (c *Context) Ns(ns string) *Context { c.Context.Namespace = ns; return c }\n\ntype Kubeconfig map[string]interface{}\n\nfunc KC() *Kubeconfig {\n\treturn &Kubeconfig{\n\t\t\"apiVersion\": \"v1\",\n\t\t\"kind\": \"Config\"}\n}\n\nfunc (k *Kubeconfig) Set(key string, v interface{}) *Kubeconfig { (*k)[key] = v; return k }\nfunc (k *Kubeconfig) WithCurrentCtx(s string) *Kubeconfig { (*k)[\"current-context\"] = s; return k }\nfunc (k *Kubeconfig) WithCtxs(c ...*Context) *Kubeconfig { (*k)[\"contexts\"] = c; return k }\n\n\n\nfunc (k *Kubeconfig) ToYAML(t *testing.T) string ", "output": "{\n\tt.Helper()\n\tvar v strings.Builder\n\tif err := yaml.NewEncoder(&v).Encode(*k); err != nil {\n\t\tt.Fatalf(\"failed to encode mock kubeconfig: %v\", err)\n\t}\n\treturn v.String()\n}"} {"input": "package sardata\n\nimport (\n\t\"io\"\n\n\t\"github.com/luci/luci-go/common/errors\"\n)\n\n\nconst Magic = \"SAR\"\n\n\nconst Version byte = 1\n\nvar magicVer []byte\n\nfunc init() {\n\tmagicVer = []byte(Magic + string(Version))\n}\n\n\n\n\n\n\nfunc ReadMagic(r io.Reader) (version byte, err error) {\n\tbuf := make([]byte, 4)\n\tif _, err = io.ReadFull(r, buf); err != nil {\n\t\treturn\n\t}\n\n\tsBuf := string(buf[:3])\n\tif Magic != sBuf {\n\t\terr = errors.Reason(\"bad magic: %(magic)q\").D(\"magic\", sBuf).Err()\n\t\treturn\n\t}\n\n\tversion = buf[3]\n\tif version > Version {\n\t\terr = errors.Reason(\"bad version: %(ver)d > %(ours)d\").\n\t\t\tD(\"ver\", version).D(\"ours\", Version).Err()\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc WriteMagic(w io.Writer) error ", "output": "{\n\t_, err := w.Write(magicVer)\n\treturn err\n}"} {"input": "package scheduler\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n\nconst (\n\tdefaultWorkManagerQueueSize uint = 25\n\tdefaultWorkManagerPoolSize uint = 4\n)\n\n\n\n\n\ntype Config struct {\n\tWorkManagerQueueSize uint `json:\"work_manager_queue_size\"yaml:\"work_manager_queue_size\"`\n\tWorkManagerPoolSize uint `json:\"work_manager_pool_size\"yaml:\"work_manager_pool_size\"`\n}\n\nconst (\n\tCONFIG_CONSTRAINTS = `\n\t\t\t\"scheduler\": {\n\t\t\t\t\"type\": [\"object\", \"null\"],\n\t\t\t\t\"properties\" : {\n\t\t\t\t\t\"work_manager_queue_size\" : {\n\t\t\t\t\t\t\"type\": \"integer\",\n\t\t\t\t\t\t\"minimum\": 1\n\t\t\t\t\t},\n\t\t\t\t\t\"work_manager_pool_size\" : {\n\t\t\t\t\t\t\"type\": \"integer\",\n\t\t\t\t\t\t\"minimum\": 1\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t\"additionalProperties\": false\n\t\t\t}\n\t`\n)\n\n\nfunc GetDefaultConfig() *Config {\n\treturn &Config{\n\t\tWorkManagerQueueSize: defaultWorkManagerQueueSize,\n\t\tWorkManagerPoolSize: defaultWorkManagerPoolSize,\n\t}\n}\n\n\n\n\n\nfunc (c *Config) UnmarshalJSON(data []byte) error ", "output": "{\n\tt := make(map[string]json.RawMessage)\n\tif err := json.Unmarshal(data, &t); err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range t {\n\t\tswitch k {\n\t\tcase \"work_manager_queue_size\":\n\t\t\tif err := json.Unmarshal(v, &(c.WorkManagerQueueSize)); err != nil {\n\t\t\t\treturn fmt.Errorf(\"%v (while parsing 'scheduler::work_manager_queue_size')\", err)\n\t\t\t}\n\t\tcase \"work_manager_pool_size\":\n\t\t\tif err := json.Unmarshal(v, &(c.WorkManagerPoolSize)); err != nil {\n\t\t\t\treturn fmt.Errorf(\"%v (while parsing 'scheduler::work_manager_pool_size')\", err)\n\t\t\t}\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"Unrecognized key '%v' in global config file while parsing 'scheduler'\", k)\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package godspeed\n\nimport (\n\t\"io\"\n\t\"net/http\"\n)\n\ntype bodyWrapperFactory func(http.ResponseWriter) io.Writer\n\ntype bodyWrapper struct {\n\trespw http.ResponseWriter\n\tw io.Writer\n\tposthandler bodyWrapperFactory\n}\n\nfunc (w *bodyWrapper) Header() http.Header {\n\treturn w.respw.Header()\n}\n\n\n\nfunc (w *bodyWrapper) WriteHeader(s int) {\n\tw.respw.WriteHeader(s)\n}\n\nfunc (w *bodyWrapper) Close() error {\n\tvar err error\n\tif c, ok := w.w.(io.Closer); ok {\n\t\terr = c.Close()\n\t}\n\treturn err\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc wrapBody(respw http.ResponseWriter, writerGen bodyWrapperFactory) *bodyWrapper {\n\treturn &bodyWrapper{\n\t\trespw: respw,\n\t\tposthandler: writerGen,\n\t}\n}\n\nfunc (w *bodyWrapper) Write(data []byte) (int, error) ", "output": "{\n\tif w.w == nil {\n\t\tw.w = w.posthandler(w.respw)\n\t}\n\treturn w.w.Write(data)\n}"} {"input": "package v1alpha1\n\nimport (\n\t\"context\"\n\n\t\"k8s.io/apimachinery/pkg/api/equality\"\n\t\"knative.dev/pkg/apis\"\n\t\"knative.dev/serving/pkg/apis/serving\"\n)\n\n\nfunc (ci *ServerlessService) Validate(ctx context.Context) *apis.FieldError {\n\treturn ci.Spec.Validate(apis.WithinSpec(ctx)).ViaField(\"spec\")\n}\n\n\n\n\nfunc (spec *ServerlessServiceSpec) Validate(ctx context.Context) *apis.FieldError ", "output": "{\n\tif equality.Semantic.DeepEqual(spec, &ServerlessServiceSpec{}) {\n\t\treturn apis.ErrMissingField(apis.CurrentField)\n\t}\n\tvar all *apis.FieldError\n\tswitch spec.Mode {\n\tcase SKSOperationModeProxy, SKSOperationModeServe:\n\t\tbreak\n\tcase \"\":\n\t\tall = all.Also(apis.ErrMissingField(\"mode\"))\n\tdefault:\n\t\tall = all.Also(apis.ErrInvalidValue(spec.Mode, \"mode\"))\n\t}\n\n\tif spec.NumActivators < 0 {\n\t\tall = all.Also(apis.ErrInvalidValue(spec.NumActivators, \"numActivators\"))\n\t}\n\n\tall = all.Also(serving.ValidateNamespacedObjectReference(&spec.ObjectRef).ViaField(\"objectRef\"))\n\n\treturn all.Also(spec.ProtocolType.Validate(ctx).ViaField(\"protocolType\"))\n}"} {"input": "package remotestate\n\nimport (\n\t\"context\"\n\n\t\"github.com/r3labs/terraform/backend\"\n\t\"github.com/r3labs/terraform/helper/schema\"\n\t\"github.com/r3labs/terraform/state\"\n\t\"github.com/r3labs/terraform/state/remote\"\n\t\"github.com/r3labs/terraform/terraform\"\n)\n\n\n\n\n\n\ntype Backend struct {\n\t*schema.Backend\n\n\tConfigureFunc func(ctx context.Context) (remote.Client, error)\n\n\tclient remote.Client\n}\n\nfunc (b *Backend) Configure(rc *terraform.ResourceConfig) error {\n\tb.Backend.ConfigureFunc = func(ctx context.Context) error {\n\t\tc, err := b.ConfigureFunc(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tb.client = c\n\t\treturn nil\n\t}\n\n\treturn b.Backend.Configure(rc)\n}\n\nfunc (b *Backend) States() ([]string, error) {\n\treturn nil, backend.ErrNamedStatesNotSupported\n}\n\n\n\nfunc (b *Backend) State(name string) (state.State, error) {\n\tif b.client == nil {\n\t\tpanic(\"nil remote client\")\n\t}\n\n\tif name != backend.DefaultStateName {\n\t\treturn nil, backend.ErrNamedStatesNotSupported\n\t}\n\n\ts := &remote.State{Client: b.client}\n\treturn s, nil\n}\n\nfunc (b *Backend) DeleteState(name string) error ", "output": "{\n\treturn backend.ErrNamedStatesNotSupported\n}"} {"input": "package models\n\nimport (\n\t\"github.com/goadesign/goa\"\n\t\"github.com/gopheracademy/congo/app\"\n\t\"github.com/jinzhu/gorm\"\n\t\"golang.org/x/net/context\"\n\t\"time\"\n)\n\n\n\n\nfunc (m *EventDB) ListEvent(ctx context.Context, tenantID int) []*app.Event {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"event\", \"listevent\"}, time.Now())\n\n\tvar native []*Event\n\tvar objs []*app.Event\n\terr := m.Db.Scopes(EventFilterByTenant(tenantID, &m.Db)).Table(m.TableName()).Find(&native).Error\n\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"error listing Event\", \"error\", err.Error())\n\t\treturn objs\n\t}\n\n\tfor _, t := range native {\n\t\tobjs = append(objs, t.EventToEvent())\n\t}\n\n\treturn objs\n}\n\n\n\n\n\nfunc (m *EventDB) OneEvent(ctx context.Context, id int, tenantID int) (*app.Event, error) {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"event\", \"oneevent\"}, time.Now())\n\n\tvar native Event\n\terr := m.Db.Scopes(EventFilterByTenant(tenantID, &m.Db)).Table(m.TableName()).Preload(\"Presentations\").Preload(\"Speakers\").Preload(\"Tenant\").Where(\"id = ?\", id).Find(&native).Error\n\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\tgoa.LogError(ctx, \"error getting Event\", \"error\", err.Error())\n\t\treturn nil, err\n\t}\n\n\tview := *native.EventToEvent()\n\treturn &view, err\n}\n\nfunc (m *Event) EventToEvent() *app.Event ", "output": "{\n\tevent := &app.Event{}\n\tevent.EndDate = m.EndDate\n\tevent.ID = &m.ID\n\tevent.Name = &m.Name\n\tfor _, k := range m.Presentations {\n\t\tevent.Presentations = append(event.Presentations, k.PresentationToPresentation())\n\t}\n\tfor _, k := range m.Speakers {\n\t\tevent.Speakers = append(event.Speakers, k.SpeakerToSpeaker())\n\t}\n\tevent.StartDate = m.StartDate\n\tevent.URL = m.URL\n\n\treturn event\n}"} {"input": "package service\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"net/http\"\n)\n\n\ntype StandardErrorRespModel struct {\n\tErrorMessage string `json:\"error\"`\n}\n\n\n\n\n\nfunc RespondWith(w http.ResponseWriter, httpStatusCode int, respModel interface{}) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(httpStatusCode)\n\tif err := json.NewEncoder(w).Encode(&respModel); err != nil {\n\t\tlog.Println(\" [!] Exception: RespondWith: Error: \", err)\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc RespondWithBadRequestError(w http.ResponseWriter, errMsg string) {\n\tRespondWithError(w, http.StatusBadRequest, errMsg)\n}\n\n\nfunc RespondWithNotFoundError(w http.ResponseWriter, errMsg string) {\n\tRespondWithError(w, http.StatusNotFound, errMsg)\n}\n\n\nfunc RespondWithError(w http.ResponseWriter, httpErrCode int, errMsg string) {\n\tresp := StandardErrorRespModel{\n\t\tErrorMessage: errMsg,\n\t}\n\tRespondWithErrorJSON(w, httpErrCode, resp)\n}\n\n\nfunc RespondWithErrorJSON(w http.ResponseWriter, httpErrCode int, respModel interface{}) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(httpErrCode)\n\tif err := json.NewEncoder(w).Encode(&respModel); err != nil {\n\t\tlog.Println(\" [!] Exception: RespondWithErrorJSON: Error: \", err)\n\t}\n}\n\nfunc RespondWithSuccessOK(w http.ResponseWriter, respModel interface{}) ", "output": "{\n\tRespondWith(w, http.StatusOK, respModel)\n}"} {"input": "package log\n\n\nfunc (me *Logging) Prefix() string {\n\treturn me.prefix\n}\n\n\n\n\n\nfunc (me *Logging) Priority() int {\n\treturn me.priority\n}\n\n\nfunc (me *Logging) SetPriority(value int) {\n\tme.setPriority = true\n\tme.priority = value\n\tif me.console != nil {\n\t\tme.console.SetPriority(me.priority)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPriority(me.priority)\n\t}\n}\n\n\nfunc (me *Logging) Layouts() int {\n\treturn me.layouts\n}\n\n\nfunc (me *Logging) SetLayouts(value int) {\n\tme.setLayouts = true\n\tme.layouts = value\n\tif me.console != nil {\n\t\tme.console.SetLayouts(me.layouts)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetLayouts(me.layouts)\n\t}\n}\n\n\nfunc (me *Logging) Outputs() int {\n\treturn me.outputs\n}\n\n\nfunc (me *Logging) SetOutputs(value int) {\n\tme.setOutputs = true\n\tme.outputs = value\n}\n\nfunc (me *Logging) SetPrefix(value string) ", "output": "{\n\tme.prefix = value\n\tif me.console != nil {\n\t\tme.console.SetPrefix(me.prefix)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPrefix(me.prefix)\n\t}\n}"} {"input": "package turtle\n\nimport (\n\t\"strings\"\n)\n\ntype DataSet struct {\n\ttriplecount int\n\tnscount int\n\tNamespaces map[string]string\n\tTriples []Triple\n}\n\n\n\nfunc (d *DataSet) AddTripleStrings(subject, predicate, object string) {\n\td.triplecount += 1\n\td.Triples = append(d.Triples, MakeTriple(subject, predicate, object))\n}\n\nfunc (d *DataSet) AddTripleURIs(subject, predicate, object URI) {\n\td.triplecount += 1\n\td.Triples = append(d.Triples, Triple{subject, predicate, object})\n}\n\nfunc (d *DataSet) addNamespace(prefix, namespace string) {\n\td.nscount += 1\n\tnamespace = strings.TrimRight(namespace, \"#\")\n\td.Namespaces[prefix] = namespace\n}\n\nfunc (d *DataSet) NumTriples() int {\n\treturn d.triplecount\n}\n\nfunc (d *DataSet) NumNamespaces() int {\n\treturn d.nscount\n}\n\nfunc newDataSet() *DataSet ", "output": "{\n\treturn &DataSet{\n\t\ttriplecount: 0,\n\t\tnscount: 0,\n\t\tNamespaces: make(map[string]string),\n\t\tTriples: []Triple{},\n\t}\n}"} {"input": "package comm\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestQueryType_String(t *testing.T) {\n\tassert.Equal(t, \"REQUEST\", Request.String())\n\tassert.Equal(t, \"RESPONSE\", Response.String())\n}\n\n\n\nfunc TestMetrics_Record(t *testing.T) {\n\tm := newScalarMetrics()\n\n\tm.Record()\n\tassert.NotEmpty(t, m.Earliest)\n\tassert.Equal(t, m.Earliest, m.Latest)\n\tassert.Equal(t, uint64(1), m.Count)\n\n\tm.Record()\n\tassert.True(t, m.Earliest.Before(m.Latest))\n\tassert.Equal(t, uint64(2), m.Count)\n}\n\nfunc TestOutcome_String(t *testing.T) ", "output": "{\n\tassert.Equal(t, \"SUCCESS\", Success.String())\n\tassert.Equal(t, \"ERROR\", Error.String())\n}"} {"input": "package http\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/Lopastvertoleta/go-ethereum/log\"\n)\n\n\nvar templateMap map[int]*template.Template\n\n\ntype ErrorParams struct {\n\tMsg string\n\tCode int\n\tTimestamp string\n\ttemplate *template.Template\n\tDetails template.HTML\n}\n\n\nfunc init() {\n\tinitErrHandling()\n}\n\n\n\n\n\n\n\n\nfunc ShowError(w http.ResponseWriter, r *http.Request, msg string, code int) {\n\tif code == http.StatusInternalServerError {\n\t\tlog.Error(msg)\n\t}\n\trespond(w, r, &ErrorParams{\n\t\tCode: code,\n\t\tMsg: msg,\n\t\tTimestamp: time.Now().Format(time.RFC1123),\n\t\ttemplate: getTemplate(code),\n\t})\n}\n\n\nfunc respond(w http.ResponseWriter, r *http.Request, params *ErrorParams) {\n\tw.WriteHeader(params.Code)\n\tif r.Header.Get(\"Accept\") == \"application/json\" {\n\t\trespondJson(w, params)\n\t} else {\n\t\trespondHtml(w, params)\n\t}\n}\n\n\nfunc respondHtml(w http.ResponseWriter, params *ErrorParams) {\n\terr := params.template.Execute(w, params)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t}\n}\n\n\nfunc respondJson(w http.ResponseWriter, params *ErrorParams) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(params)\n}\n\n\nfunc getTemplate(code int) *template.Template {\n\tif val, tmpl := templateMap[code]; tmpl {\n\t\treturn val\n\t} else {\n\t\treturn templateMap[0]\n\t}\n}\n\nfunc initErrHandling() ", "output": "{\n\tgenErrPage := GetGenericErrorPage()\n\tnotFoundPage := GetNotFoundErrorPage()\n\ttnames := map[int]string{\n\t\t0: genErrPage, \n\t\t400: genErrPage,\n\t\t404: notFoundPage,\n\t\t500: genErrPage,\n\t}\n\ttemplateMap = make(map[int]*template.Template)\n\tfor code, tname := range tnames {\n\t\ttemplateMap[code] = template.Must(template.New(fmt.Sprintf(\"%d\", code)).Parse(tname))\n\t}\n}"} {"input": "package service_test\n\nimport (\n\t\"context\"\n\n\tservice \"cloud.google.com/go/orchestration/airflow/service/apiv1\"\n\t\"google.golang.org/api/iterator\"\n\tservicepb \"google.golang.org/genproto/googleapis/cloud/orchestration/airflow/service/v1\"\n)\n\nfunc ExampleNewImageVersionsClient() {\n\tctx := context.Background()\n\tc, err := service.NewImageVersionsClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\t_ = c\n}\n\n\n\nfunc ExampleImageVersionsClient_ListImageVersions() ", "output": "{\n\tctx := context.Background()\n\tc, err := service.NewImageVersionsClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\treq := &servicepb.ListImageVersionsRequest{\n\t}\n\tit := c.ListImageVersions(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/bborbe/assert\"\n)\n\nfunc TestIsDirectory(t *testing.T) {\n\tisDir, err := IsDirectory(\"/tmp\")\n\tif err := AssertThat(err, NilValue()); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := AssertThat(isDir, Is(true)); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\n\nfunc TestNormalizePath(t *testing.T) ", "output": "{\n\tdir, err := NormalizePath(\"/tmp\")\n\tif err := AssertThat(err, NilValue()); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := AssertThat(dir, Is(\"/tmp\")); err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package exporterhelper\n\nimport (\n\t\"context\"\n\n\t\"go.opencensus.io/trace\"\n\n\t\"github.com/census-instrumentation/opencensus-service/data\"\n\t\"github.com/census-instrumentation/opencensus-service/exporter\"\n\t\"github.com/census-instrumentation/opencensus-service/observability\"\n)\n\n\n\ntype PushTraceData func(ctx context.Context, td data.TraceData) (droppedSpans int, err error)\n\ntype traceExporter struct {\n\texporterFormat string\n\tpushTraceData PushTraceData\n}\n\nvar _ (exporter.TraceExporter) = (*traceExporter)(nil)\n\nfunc (te *traceExporter) ConsumeTraceData(ctx context.Context, td data.TraceData) error {\n\texporterCtx := observability.ContextWithExporterName(ctx, te.exporterFormat)\n\t_, err := te.pushTraceData(exporterCtx, td)\n\treturn err\n}\n\nfunc (te *traceExporter) TraceExportFormat() string {\n\treturn te.exporterFormat\n}\n\n\n\n\n\n\n\nfunc pushTraceDataWithSpan(next PushTraceData, spanName string) PushTraceData {\n\treturn func(ctx context.Context, td data.TraceData) (int, error) {\n\t\tctx, span := trace.StartSpan(ctx, spanName)\n\t\tdefer span.End()\n\t\tdroppedSpans, err := next(ctx, td)\n\t\tif span.IsRecordingEvents() {\n\t\t\tspan.AddAttributes(\n\t\t\t\ttrace.Int64Attribute(numReceivedSpansAttribute, int64(len(td.Spans))),\n\t\t\t\ttrace.Int64Attribute(numDroppedSpansAttribute, int64(droppedSpans)),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tspan.SetStatus(errToStatus(err))\n\t\t\t}\n\t\t}\n\t\treturn droppedSpans, err\n\t}\n}\n\nfunc NewTraceExporter(exporterFormat string, pushTraceData PushTraceData, options ...ExporterOption) (exporter.TraceExporter, error) ", "output": "{\n\tif exporterFormat == \"\" {\n\t\treturn nil, errEmptyExporterFormat\n\t}\n\n\tif pushTraceData == nil {\n\t\treturn nil, errNilPushTraceData\n\t}\n\n\topts := newExporterOptions(options...)\n\n\tif opts.spanName != \"\" {\n\t\tpushTraceData = pushTraceDataWithSpan(pushTraceData, opts.spanName)\n\t}\n\n\treturn &traceExporter{\n\t\texporterFormat: exporterFormat,\n\t\tpushTraceData: pushTraceData,\n\t}, nil\n}"} {"input": "package util\n\nimport (\n \"net/http\"\n \"github.com/dgrijalva/jwt-go\"\n \"github.com/mb-dev/godo/config\"\n)\n\n\n\nfunc JWTMiddleware(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) ", "output": "{\n token, err := jwt.ParseFromRequest(req, func(token *jwt.Token) ([]byte, error) {\n return []byte(config.CurrentConfiguration.KeySecret), nil\n })\n\n if err != nil || !token.Valid {\n rw.WriteHeader(http.StatusForbidden)\n return\n } \n ContextSetUserId(req, token.Claims[\"id\"].(string))\n next(rw, req)\n}"} {"input": "package netlink\n\n\n\nimport \"strconv\"\n\n\ntype Address struct {\n pid int\n}\n\n\n\n\nfunc (self Address)Address()(string){ return strconv.Itoa(self.pid) }\n\nfunc (self Address)Network()(string)", "output": "{ return \"netlink\" }"} {"input": "package jms\n\n\ntype OperationTypeEnum string\n\n\nconst (\n\tOperationTypeCreateFleet OperationTypeEnum = \"CREATE_FLEET\"\n\tOperationTypeDeleteFleet OperationTypeEnum = \"DELETE_FLEET\"\n\tOperationTypeMoveFleet OperationTypeEnum = \"MOVE_FLEET\"\n\tOperationTypeUpdateFleet OperationTypeEnum = \"UPDATE_FLEET\"\n)\n\nvar mappingOperationType = map[string]OperationTypeEnum{\n\t\"CREATE_FLEET\": OperationTypeCreateFleet,\n\t\"DELETE_FLEET\": OperationTypeDeleteFleet,\n\t\"MOVE_FLEET\": OperationTypeMoveFleet,\n\t\"UPDATE_FLEET\": OperationTypeUpdateFleet,\n}\n\n\n\n\nfunc GetOperationTypeEnumValues() []OperationTypeEnum ", "output": "{\n\tvalues := make([]OperationTypeEnum, 0)\n\tfor _, v := range mappingOperationType {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"os\"\n \"io/ioutil\"\n \"strings\"\n \"sort\"\n \"bytes\"\n)\n\nfunc ReadFile(filename string) string {\n data, err := ioutil.ReadFile(filename)\n\n if err != nil {\n fmt.Fprintf(os.Stderr, \"Error: %v\\n\", err)\n return \"\"\n }\n\n return string(data)\n}\n\ntype Letter struct {\n Name string\n Count int\n}\n\ntype ByCount []Letter\n\nfunc (a ByCount) Len() int { return len(a) }\n\nfunc (a ByCount) Less(i, j int) bool { return a[i].Count > a[j].Count }\n\nfunc main() {\n directions := strings.Split(ReadFile(\"input.txt\"), \"\\n\")\n\n var col_letters bytes.Buffer\n var answer bytes.Buffer\n\n for x := 0; x < len(directions[0]); x++ {\n \n col_letters.Reset()\n\n \n for y := 0; y < len(directions) - 1; y++ {\n col_letters.WriteByte(directions[y][x])\n }\n\n var letter_counts []Letter\n \n found := make(map[string]bool)\n for _, letter := range strings.Split(col_letters.String(), \"\") {\n if found[letter] {\n continue\n }\n found[letter] = true\n letter_counts = append(letter_counts, Letter{Name: letter, Count: strings.Count(col_letters.String(), letter)})\n \t}\n\n \n sort.Sort(ByCount(letter_counts))\n \n answer.WriteString(letter_counts[0].Name)\n }\n fmt.Println(answer.String())\n}\n\nfunc (a ByCount) Swap(i, j int) ", "output": "{ a[i], a[j] = a[j], a[i] }"} {"input": "package docker\n\nimport (\n\t\"github.com/fsouza/go-dockerclient\"\n\t. \"github.com/weaveworks/weave/common\"\n)\n\n\ntype ContainerObserver interface {\n\tContainerDied(ident string) error\n}\n\ntype Client struct {\n\t*docker.Client\n}\n\n\nfunc NewClient(apiPath string) (*Client, error) {\n\tdc, err := docker.NewClient(apiPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &Client{dc}\n\n\tenv, err := client.Version()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tLog.Infof(\"[docker] Using Docker API on %s: %v\", apiPath, env)\n\treturn client, nil\n}\n\n\nfunc (c *Client) AddObserver(ob ContainerObserver) error {\n\tevents := make(chan *docker.APIEvents)\n\tif err := c.AddEventListener(events); err != nil {\n\t\tLog.Errorf(\"[docker] Unable to add listener to Docker API: %s\", err)\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tfor event := range events {\n\t\t\tswitch event.Status {\n\t\t\tcase \"die\":\n\t\t\t\tid := event.ID\n\t\t\t\tob.ContainerDied(id)\n\t\t\t}\n\t\t}\n\t}()\n\treturn nil\n}\n\n\n\n\nfunc (c *Client) IsContainerNotRunning(idStr string) bool ", "output": "{\n\tcontainer, err := c.InspectContainer(idStr)\n\tif err == nil {\n\t\treturn !container.State.Running\n\t}\n\tif _, notThere := err.(*docker.NoSuchContainer); notThere {\n\t\treturn true\n\t}\n\tLog.Errorf(\"[docker] Could not check container status: %s\", err)\n\treturn false\n}"} {"input": "package xml2json\n\nimport (\n\t\"strings\"\n)\n\n\ntype Node struct {\n\tChildren map[string]Nodes\n\tData string\n\tChildrenAlwaysAsArray bool\n}\n\n\ntype Nodes []*Node\n\n\n\n\n\nfunc (n *Node) IsComplex() bool {\n\treturn len(n.Children) > 0\n}\n\n\nfunc (n *Node) GetChild(path string) *Node {\n\tresult := n\n\tnames := strings.Split(path, \".\")\n\tfor _, name := range names {\n\t\tchildren, exists := result.Children[name]\n\t\tif !exists {\n\t\t\treturn nil\n\t\t}\n\t\tif len(children) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tresult = children[0]\n\t}\n\treturn result\n}\n\nfunc (n *Node) AddChild(s string, c *Node) ", "output": "{\n\tif n.Children == nil {\n\t\tn.Children = map[string]Nodes{}\n\t}\n\n\tn.Children[s] = append(n.Children[s], c)\n}"} {"input": "package gcp\n\nimport \"k8s.io/kubernetes/test/e2e/framework\"\n\n\n\n\nfunc SIGDescribe(text string, body func()) bool ", "output": "{\n\treturn framework.KubeDescribe(\"[sig-cloud-provider-gcp] \"+text, body)\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\n\t\"github.com/urfave/cli\"\n\n\t\"github.com/G-Node/gogs/cmd\"\n\t\"github.com/G-Node/gogs/pkg/setting\"\n)\n\nconst APP_VER = \"0.1.0.0\"\n\n\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"Gin\"\n\tapp.Usage = \"Modern Research Data Management for Neuroscience\"\n\tapp.Version = APP_VER\n\tapp.Commands = []cli.Command{\n\t\tcmd.Web,\n\t\tcmd.Serv,\n\t\tcmd.Hook,\n\t\tcmd.Cert,\n\t\tcmd.Admin,\n\t\tcmd.Import,\n\t\tcmd.Backup,\n\t\tcmd.Restore,\n\t}\n\tapp.Flags = append(app.Flags, []cli.Flag{}...)\n\tapp.Run(os.Args)\n}\n\nfunc init() ", "output": "{\n\tsetting.AppVer = APP_VER\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path\"\n)\n\nvar pkgloc string\nvar apiFile string\nvar ctxFile string\n\nfunc init() {\n\tgopath := os.Getenv(\"GOPATH\")\n\tpkgloc = path.Join(gopath, \"src/gorgonia.org/cu\")\n\tapiFile = path.Join(pkgloc, \"api.go\")\n\tctxFile = path.Join(pkgloc, \"ctx_api.go\")\n}\n\nfunc generateAPIFile(gss []*GoSignature) {\n\tf, err := os.Create(apiFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\n\tf.WriteString(header)\n\tgenerateAPI(f, gss)\n}\n\n\n\nfunc main() {\n\tsigs := Parse()\n\n\tvar gss []*GoSignature\n\tsigs = filterCSigs(sigs)\n\tfor _, sig := range sigs {\n\t\tgs := sig.GoSig()\n\t\tgss = append(gss, gs)\n\t}\n\n\tgenerateAPIFile(gss)\n\tgenerateContextFile(gss)\n\n\tvar err error\n\tfilename := apiFile\n\tcmd := exec.Command(\"goimports\", \"-w\", filename)\n\tif err = cmd.Run(); err != nil {\n\t\tlog.Fatalf(\"Go imports failed with %v for %q\", err, filename)\n\t}\n\n\tfilename = ctxFile\n\tcmd = exec.Command(\"goimports\", \"-w\", filename)\n\tif err = cmd.Run(); err != nil {\n\t\tlog.Fatalf(\"Go imports failed with %v for %q\", err, filename)\n\t}\n}\n\nfunc generateContextFile(gss []*GoSignature) ", "output": "{\n\tg, err := os.Create(ctxFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer g.Close()\n\tg.WriteString(header)\n\tgenerateContextAPI(g, gss)\n}"} {"input": "package golax\n\nimport \"net/http\"\n\n\n\ntype Context struct {\n\tRequest *http.Request\n\tResponse *ExtendedWriter\n\tParameter string\n\tParameters map[string]string\n\tLastError *ContextError\n\tScope map[string]interface{}\n\tPathHandlers string\n\tafters []Handler\n\tdeepInterceptors []*Interceptor\n}\n\n\n\ntype ContextError struct {\n\tStatusCode int `json:\"status_code\"`\n\tErrorCode int `json:\"error_code\"`\n\tDescription string `json:\"description_code\"`\n}\n\n\n\n\nfunc (c *Context) Error(s int, d string) *ContextError {\n\tc.Response.WriteHeader(s)\n\te := &ContextError{\n\t\tStatusCode: s,\n\t\tDescription: d,\n\t}\n\tc.LastError = e\n\treturn e\n}\n\n\nfunc (c *Context) Set(k string, v interface{}) {\n\tc.Scope[k] = v\n}\n\n\nfunc (c *Context) Get(k string) (interface{}, bool) {\n\ta, b := c.Scope[k]\n\treturn a, b\n}\n\nfunc NewContext() *Context ", "output": "{\n\treturn &Context{\n\t\tLastError: nil,\n\t\tParameters: map[string]string{},\n\t\tScope: map[string]interface{}{},\n\t\tafters: []Handler{},\n\t\tdeepInterceptors: []*Interceptor{},\n\t}\n}"} {"input": "package dnssec\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/coredns/coredns/plugin/test\"\n\t\"github.com/coredns/coredns/request\"\n\n\t\"github.com/miekg/dns\"\n)\n\nconst server = \"dns//.\"\n\nfunc TestBlackLiesBitmapNoData(t *testing.T) {\n\td, rm1, rm2 := newDnssec(t, []string{\"example.org.\"})\n\tdefer rm1()\n\tdefer rm2()\n\n\tm := testTLSAMsg()\n\tstate := request.Request{Req: m, Zone: \"example.org.\"}\n\tm = d.Sign(state, time.Now().UTC(), server)\n\n\tvar nsec *dns.NSEC\n\tfor _, r := range m.Ns {\n\t\tif r.Header().Rrtype == dns.TypeNSEC {\n\t\t\tnsec = r.(*dns.NSEC)\n\t\t}\n\t}\n\tfor _, b := range nsec.TypeBitMap {\n\t\tif uint16(b) == dns.TypeTLSA {\n\t\t\tt.Errorf(\"Type TLSA should not be present in the type bitmap: %v\", nsec.TypeBitMap)\n\t\t}\n\t}\n}\n\n\nfunc testTLSAMsg() *dns.Msg {\n\treturn &dns.Msg{MsgHdr: dns.MsgHdr{Rcode: dns.RcodeSuccess},\n\t\tQuestion: []dns.Question{{Name: \"25._tcp.example.org.\", Qclass: dns.ClassINET, Qtype: dns.TypeTLSA}},\n\t\tNs: []dns.RR{test.SOA(\"example.org.\t1800\tIN\tSOA\tlinode.example.org. miek.example.org. 1461471181 14400 3600 604800 14400\")},\n\t}\n}\n\nfunc TestBlackLiesBitmapNameError(t *testing.T) ", "output": "{\n\td, rm1, rm2 := newDnssec(t, []string{\"example.org.\"})\n\tdefer rm1()\n\tdefer rm2()\n\n\tm := testTLSAMsg()\n\tm.Rcode = dns.RcodeNameError \n\tstate := request.Request{Req: m, Zone: \"example.org.\"}\n\tm = d.Sign(state, time.Now().UTC(), server)\n\n\tvar nsec *dns.NSEC\n\tfor _, r := range m.Ns {\n\t\tif r.Header().Rrtype == dns.TypeNSEC {\n\t\t\tnsec = r.(*dns.NSEC)\n\t\t}\n\t}\n\tfor _, b := range nsec.TypeBitMap {\n\t\tif uint16(b) == dns.TypeTLSA {\n\t\t\tt.Errorf(\"Type TLSA should not be present in the type bitmap: %v\", nsec.TypeBitMap)\n\t\t}\n\t}\n}"} {"input": "package graph\n\nimport (\n\t\"fmt\"\n\n\tsous \"github.com/opentable/sous/lib\"\n\t\"github.com/opentable/sous/server\"\n\t\"github.com/opentable/sous/util/logging\"\n\t\"github.com/samsalisbury/semv\"\n)\n\nfunc newServerComponentLocator(\n\tls LogSink,\n\tcfg LocalSousConfig,\n\tins serverInserter,\n\tsm *ServerStateManager,\n\tcm *ServerClusterManager,\n\trf *sous.ResolveFilter,\n\tv semv.Version,\n\tqs *sous.R11nQueueSet,\n\tar *sous.AutoResolver,\n) server.ComponentLocator {\n\n\tlogging.Deliver(ls, logging.SousGenericV1, logging.DebugLevel, logging.GetCallerInfo(),\n\t\tlogging.MessageField(fmt.Sprintf(\"Building CL: State manager: %T %[1]p\", sm.StateManager)))\n\n\tvar dm sous.DeploymentManager\n\n\tswitch ldm := sm.StateManager.(type) {\n\tdefault:\n\t\tdm = sous.MakeDeploymentManager(sm.StateManager, ls)\n\tcase sous.DeploymentManager:\n\t\tdm = ldm\n\t}\n\treturn server.ComponentLocator{\n\n\t\tLogSink: ls.LogSink,\n\t\tConfig: cfg.Config,\n\t\tInserter: ins.Inserter,\n\t\tStateManager: sm.StateManager,\n\t\tClusterManager: cm.ClusterManager,\n\t\tDeploymentManager: dm,\n\t\tResolveFilter: rf,\n\t\tVersion: v,\n\t\tQueueSet: qs,\n\t\tAutoResolver: ar,\n\t}\n\n}\n\n\n\n\n\nfunc NewR11nQueueSet(d sous.Deployer, r sous.Registry, rf *sous.ResolveFilter, sm *ServerStateManager) *sous.R11nQueueSet ", "output": "{\n\tsr := sm.StateManager\n\treturn sous.NewR11nQueueSet(sous.R11nQueueStartWithHandler(\n\t\tfunc(qr *sous.QueuedR11n) sous.DiffResolution {\n\t\t\tqr.Rectification.Begin(d, r, rf, sr)\n\t\t\treturn qr.Rectification.Wait()\n\t\t}))\n}"} {"input": "package scheduler\n\nimport \"github.com/aosen/robot\"\n\ntype SimpleScheduler struct {\n\tqueue chan *robot.Request\n}\n\nfunc NewSimpleScheduler() *SimpleScheduler {\n\tch := make(chan *robot.Request, 1024)\n\treturn &SimpleScheduler{ch}\n}\n\nfunc (this *SimpleScheduler) Push(requ *robot.Request) {\n\tthis.queue <- requ\n}\n\nfunc (this *SimpleScheduler) Poll() *robot.Request {\n\tif len(this.queue) == 0 {\n\t\treturn nil\n\t} else {\n\t\treturn <-this.queue\n\t}\n}\n\n\n\nfunc (this *SimpleScheduler) Count() int ", "output": "{\n\treturn len(this.queue)\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\n\n\nfunc PodContainerKey(namespace, podName, containerName string) string {\n\treturn fmt.Sprintf(\"namespace:%s/pod:%s/container:%s\", namespace, podName, containerName)\n}\n\nfunc PodKey(namespace, podName string) string {\n\treturn fmt.Sprintf(\"namespace:%s/pod:%s\", namespace, podName)\n}\n\nfunc NamespaceKey(namespace string) string {\n\treturn fmt.Sprintf(\"namespace:%s\", namespace)\n}\n\n\n\nfunc NodeContainerKey(node, container string) string {\n\treturn fmt.Sprintf(\"node:%s/container:%s\", node, container)\n}\n\nfunc ClusterKey() string {\n\treturn \"cluster\"\n}\n\nfunc NodeKey(node string) string ", "output": "{\n\treturn fmt.Sprintf(\"node:%s\", node)\n}"} {"input": "package gauge\n\ntype ItemQueue struct {\n\tItems []Item\n}\n\nfunc (queue *ItemQueue) Next() Item {\n\tif len(queue.Items) > 0 {\n\t\tnext := queue.Items[0]\n\t\tqueue.Items = queue.Items[1:]\n\t\treturn next\n\t}\n\treturn nil\n}\n\n\n\nfunc (queue *ItemQueue) Peek() Item ", "output": "{\n\tif len(queue.Items) > 0 {\n\t\treturn queue.Items[0]\n\t}\n\treturn nil\n}"} {"input": "package lib\n\nimport (\n\t\"github.com/atinm/spotify\"\n)\n\nfunc ignored(device string) bool {\n\tfor _, name := range config.Ignored {\n\t\tif name == device {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc FiltersEnabled() bool {\n\treturn ParentalControlsEnabled()\n}\n\nfunc ParentalControlsEnabled() bool {\n\treturn rule.Explicit\n}\n\nfunc Rules(track *spotify.FullTrack, device string) bool {\n\tif track != nil && rule.Explicit && track.Explicit && !ignored(device) {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc SetParentalControls(b bool) ", "output": "{\n\trule.Explicit = b\n}"} {"input": "package local\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/grafana/loki/pkg/storage/chunk\"\n)\n\ntype TableClient struct {\n\tdirectory string\n}\n\n\nfunc NewTableClient(directory string) (chunk.TableClient, error) {\n\treturn &TableClient{directory: directory}, nil\n}\n\nfunc (c *TableClient) ListTables(ctx context.Context) ([]string, error) {\n\tboltDbFiles := []string{}\n\terr := filepath.Walk(c.directory, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\tboltDbFiles = append(boltDbFiles, info.Name())\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn boltDbFiles, nil\n}\n\n\n\nfunc (c *TableClient) DeleteTable(ctx context.Context, name string) error {\n\treturn os.Remove(filepath.Join(c.directory, name))\n}\n\nfunc (c *TableClient) DescribeTable(ctx context.Context, name string) (desc chunk.TableDesc, isActive bool, err error) {\n\treturn chunk.TableDesc{\n\t\tName: name,\n\t}, true, nil\n}\n\nfunc (c *TableClient) UpdateTable(ctx context.Context, current, expected chunk.TableDesc) error {\n\treturn nil\n}\n\nfunc (*TableClient) Stop() {}\n\nfunc (c *TableClient) CreateTable(ctx context.Context, desc chunk.TableDesc) error ", "output": "{\n\tfile, err := os.OpenFile(filepath.Join(c.directory, desc.Name), os.O_CREATE|os.O_RDONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn file.Close()\n}"} {"input": "package iam\n\nimport (\n\ttimestamp \"github.com/golang/protobuf/ptypes/timestamp\"\n)\n\ntype CreateIamTokenRequest_Identity = isCreateIamTokenRequest_Identity\n\n\n\nfunc (m *CreateIamTokenRequest) SetYandexPassportOauthToken(v string) {\n\tm.Identity = &CreateIamTokenRequest_YandexPassportOauthToken{\n\t\tYandexPassportOauthToken: v,\n\t}\n}\n\nfunc (m *CreateIamTokenRequest) SetJwt(v string) {\n\tm.Identity = &CreateIamTokenRequest_Jwt{\n\t\tJwt: v,\n\t}\n}\n\nfunc (m *CreateIamTokenResponse) SetIamToken(v string) {\n\tm.IamToken = v\n}\n\nfunc (m *CreateIamTokenResponse) SetExpiresAt(v *timestamp.Timestamp) {\n\tm.ExpiresAt = v\n}\n\nfunc (m *CreateIamTokenRequest) SetIdentity(v CreateIamTokenRequest_Identity) ", "output": "{\n\tm.Identity = v\n}"} {"input": "package pe\n\nimport (\n \"math\"\n)\n\n\n\nfunc Divisors(n uint64) []uint64 ", "output": "{\n ps := []uint64{}\n limit := uint64(math.Sqrt(float64(n)))\n for (n & 1) == 0 {\n ps = append(ps, 2)\n n >>= 1\n }\n if n == 1 {\n return ps\n }\n\n var i uint64 = 3\n for i <= limit {\n if (n % i) == 0 {\n ps = append(ps, i)\n n /= i\n if n < i {\n break\n }\n } else {\n i += 2\n }\n }\n if n > 1 {\n ps = append(ps, n)\n }\n\n return ps\n}"} {"input": "package checks\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tADD int = 1\n\tREMOVE int = 2\n)\n\n\n\n\nfunc updateDNSRec(ipAddress string, dryRun bool, op int) error {\n\tvar err error\n\n\tif Gm.Clustered {\n\t\tlog.Debugln(\"Acquiring distributed lock\")\n\t\tif err = Gm.Dmutex.Lock(); err != nil {\n\t\t\treturn errors.New(\"Error acquiring distributed lock: \" + err.Error())\n\t\t} else {\n\t\t\tlog.Debugln(\"Acquired distributed lock: \", time.Now())\n\t\t}\n\t}\n\n\tif op == ADD {\n\t\terr = Master.DNS.AddIP(ipAddress, dryRun)\n\t} else if op == REMOVE {\n\t\terr = Master.DNS.RemoveIP(ipAddress, dryRun)\n\t}\n\n\tif Gm.Clustered {\n\t\tlog.Debugln(\"Releasing distributed lock\")\n\t\tif errUnlock := Gm.Dmutex.UnLock(); errUnlock != nil {\n\t\t\tlog.Errorln(errUnlock)\n\t\t} else {\n\t\t\tlog.Debugln(\"Released distributed lock: \", time.Now())\n\t\t}\n\t}\n\treturn err\n}\n\nfunc handleTransition(ipAddress string, live bool) ", "output": "{\n\tif Gm.Clustered && Gm.Members.NumMembers() > 1 {\n\t\terr := NotifyIPState(ipAddress, live, false)\n\t\tif err != nil {\n\t\t\tlog.Errorln(\"Error Updating state: \", ipAddress, err)\n\t\t}\n\t} else {\n\t\tif Gm.MinAgreement > 0 {\n\t\t\tlog.Debugln(\"Running in single mode, BUT need agreement from peers in cluster mode\")\n\t\t} else {\n\t\t\tlog.Debugln(\"Running in single mode, updating DNS\")\n\t\t\tif live == true {\n\t\t\t\terr := updateDNSRec(ipAddress, Gm.DryRun, ADD)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorln(\"Error Adding IP: \", ipAddress, err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr := updateDNSRec(ipAddress, Gm.DryRun, REMOVE)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorln(\"Error Removing IP: \", ipAddress, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package bitcoin\n\nimport (\n\t\"encoding/hex\"\n\t\"github.com/OpenBazaar/openbazaar-go/api/notifications\"\n\t\"github.com/OpenBazaar/openbazaar-go/repo\"\n\t\"github.com/OpenBazaar/spvwallet\"\n\t\"github.com/btcsuite/btcd/chaincfg/chainhash\"\n)\n\ntype WalletListener struct {\n\tdb repo.Datastore\n\tbroadcast chan interface{}\n}\n\n\n\nfunc (l *WalletListener) OnTransactionReceived(cb spvwallet.TransactionCallback) {\n\tif !cb.WatchOnly {\n\t\ttxid := hex.EncodeToString(cb.Txid)\n\t\tmetadata, _ := l.db.TxMetadata().Get(txid)\n\t\tstatus := \"UNCONFIRMED\"\n\t\tconfirmations := 0\n\t\tif cb.Height > 0 {\n\t\t\tstatus = \"PENDING\"\n\t\t\tconfirmations = 1\n\t\t}\n\t\tch, err := chainhash.NewHash(cb.Txid)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn := notifications.IncomingTransaction{\n\t\t\tTxid: ch.String(),\n\t\t\tValue: cb.Value,\n\t\t\tAddress: metadata.Address,\n\t\t\tStatus: status,\n\t\t\tMemo: metadata.Memo,\n\t\t\tTimestamp: cb.Timestamp,\n\t\t\tConfirmations: int32(confirmations),\n\t\t\tOrderId: metadata.OrderId,\n\t\t\tThumbnail: metadata.Thumbnail,\n\t\t\tHeight: cb.Height,\n\t\t\tCanBumpFee: cb.Value > 0,\n\t\t}\n\t\tl.broadcast <- n\n\t}\n}\n\nfunc NewWalletListener(db repo.Datastore, broadcast chan interface{}) *WalletListener ", "output": "{\n\tl := &WalletListener{db, broadcast}\n\treturn l\n}"} {"input": "package setup_cli\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\n\t\"github.com/cloudfoundry-incubator/lattice/ltc/cli_app_factory\"\n\t\"github.com/cloudfoundry-incubator/lattice/ltc/config\"\n\t\"github.com/cloudfoundry-incubator/lattice/ltc/config/config_helpers\"\n\t\"github.com/cloudfoundry-incubator/lattice/ltc/config/persister\"\n\t\"github.com/cloudfoundry-incubator/lattice/ltc/config/target_verifier\"\n\t\"github.com/cloudfoundry-incubator/lattice/ltc/config/target_verifier/receptor_client_factory\"\n\t\"github.com/cloudfoundry-incubator/lattice/ltc/exit_handler\"\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/pivotal-golang/lager\"\n)\n\nconst (\n\tlatticeCliHomeVar = \"LATTICE_CLI_HOME\"\n)\n\nvar (\n\tlatticeVersion string \n)\n\nfunc NewCliApp() *cli.App {\n\tconfig := config.New(persister.NewFilePersister(config_helpers.ConfigFileLocation(ltcConfigRoot())))\n\n\tsignalChan := make(chan os.Signal)\n\tsignal.Notify(signalChan, os.Interrupt)\n\texitHandler := exit_handler.New(signalChan, os.Exit)\n\tgo exitHandler.Run()\n\n\ttargetVerifier := target_verifier.New(receptor_client_factory.MakeReceptorClient)\n\tapp := cli_app_factory.MakeCliApp(latticeVersion, ltcConfigRoot(), exitHandler, config, logger(), targetVerifier, os.Stdout)\n\treturn app\n}\n\n\n\nfunc ltcConfigRoot() string {\n\tif os.Getenv(latticeCliHomeVar) != \"\" {\n\t\treturn os.Getenv(latticeCliHomeVar)\n\t}\n\n\treturn os.Getenv(\"HOME\")\n}\n\nfunc logger() lager.Logger ", "output": "{\n\tlogger := lager.NewLogger(\"ltc\")\n\tvar logLevel lager.LogLevel\n\n\tif os.Getenv(\"LTC_LOG_LEVEL\") == \"DEBUG\" {\n\t\tlogLevel = lager.DEBUG\n\t} else {\n\t\tlogLevel = lager.INFO\n\t}\n\n\tlogger.RegisterSink(lager.NewWriterSink(os.Stderr, logLevel))\n\treturn logger\n}"} {"input": "package main\n\ntype set struct {\n\tels map[string]interface{}\n}\n\nfunc newSet() *set {\n\treturn &set{\n\t\tels: map[string]interface{}{},\n\t}\n}\n\nfunc (s *set) add(element string) {\n\ts.els[element] = nil\n}\n\n\n\nfunc (s *set) elements() []string ", "output": "{\n\tels := make([]string, len(s.els))\n\n\ti := 0\n\tfor k := range s.els {\n\t\tels[i] = k\n\t\ti++\n\t}\n\treturn els\n}"} {"input": "package docker\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/docker/docker/client\"\n\t\"github.com/geniusrabbit/registry/observer\"\n\t\"github.com/geniusrabbit/registry/service\"\n)\n\n\ntype ServiceContainerEventer interface {\n\tServiceEvent(event string, srv *service.Service)\n\tServiceError(err error)\n}\n\ntype serviceObserver struct {\n\thostIPAddr bool\n\teventer ServiceContainerEventer\n\tobserver *baseObserver\n}\n\n\n\n\n\nfunc (s *serviceObserver) Run() {\n\ts.observer.Run()\n}\n\n\nfunc (s *serviceObserver) Stop() {\n\ts.observer.Stop()\n}\n\n\nfunc (s *serviceObserver) Docker() *client.Client {\n\treturn s.observer.Docker()\n}\n\n\nfunc (s *serviceObserver) Event(containerID, action string) {\n\toptions, err := ServiceInfo(containerID, s.hostIPAddr, s.observer.docker)\n\tif err == nil {\n\t\tvar srv = options.Service()\n\t\tswitch action {\n\t\tcase \"start\", \"unpause\", \"refresh\":\n\t\t\tsrv.Status = service.StatusPassing\n\t\tcase \"stop\", \"pause\":\n\t\t\tsrv.Status = service.StatusWarning\n\t\tcase \"die\", \"kill\", \"oom\":\n\t\t\tsrv.Status = service.StatusCritical\n\t\t}\n\t\ts.eventer.ServiceEvent(action, srv)\n\t} else {\n\t\ts.Error(err)\n\t}\n}\n\n\nfunc (s *serviceObserver) Error(err error) {\n\tif err != nil {\n\t\ts.eventer.ServiceError(err)\n\t}\n}\n\nfunc NewService(eventer ServiceContainerEventer, host, version string, httpClient *http.Client, httpHeader map[string]string, registerHost bool) (observer.Observer, error) ", "output": "{\n\tvar (\n\t\tself = &serviceObserver{eventer: eventer, hostIPAddr: registerHost}\n\t\tobs, err = New(self, host, version, httpClient, httpHeader)\n\t)\n\tif err == nil {\n\t\tif obs, _ := obs.(*baseObserver); obs != nil {\n\t\t\tself.observer = obs\n\t\t\treturn self, nil\n\t\t}\n\t}\n\treturn nil, err\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n)\n\ntype Audits []Audit\n\n\n\nfunc (o Audits) ToJson() string {\n\tb, err := json.Marshal(o)\n\tif err != nil {\n\t\treturn \"[]\"\n\t}\n\treturn string(b)\n}\n\nfunc AuditsFromJson(data io.Reader) Audits {\n\tvar o Audits\n\tjson.NewDecoder(data).Decode(&o)\n\treturn o\n}\n\nfunc (o Audits) Etag() string ", "output": "{\n\tif len(o) > 0 {\n\t\treturn Etag(o[0].CreateAt)\n\t}\n\treturn \"\"\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\tc := make(chan int)\n\tquit := make(chan int)\n\tgo func() {\n\t\tfor i := 0; i < 10; i++ {\n\t\t\tfmt.Println(<-c)\n\t\t}\n\t\tquit <- 0\n\t}()\n\tfibonacci(c, quit)\n}\n\nfunc fibonacci(c, quit chan int) ", "output": "{\n\tx, y := 1, 1\n\tfor {\n\t\tselect {\n\t\tcase c <- x:\n\t\t\tx, y = y, x+y\n\t\tcase <-quit:\n\t\t\tfmt.Println(\"quit\")\n\t\t\treturn\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nimport (\n\t\"github.com/lxn/go-pgsql\"\n)\n\n\n\nfunc main() {\n\tconn, err := pgsql.Connect(\"dbname=postgres user=cbbrowne port=7099\", pgsql.LogError)\n\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\tdefer conn.Close()\n\n\tcommand := \"SELECT * FROM table1 WHERE id = @id;\"\n\tidParam := pgsql.NewParameter(\"@id\", pgsql.Integer)\n\n\tstmt, err := conn.Prepare(command, idParam)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\tdefer stmt.Close()\n\n\tfor id := 1; id <= 3; id++ {\n\t\terr = idParam.SetValue(id)\n\t\tif err != nil {\n\t\t\tos.Exit(1)\n\t\t}\n\t\tqueryAndPrintResults(stmt)\n\t}\n}\n\nfunc queryAndPrintResults(stmt *pgsql.Statement) ", "output": "{\n\trs, err := stmt.Query()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\tdefer rs.Close()\n\n\tstroptOrd := rs.Ordinal(\"stropt\")\n\n\tfor {\n\t\thasRow, err := rs.FetchNext()\n\t\tif err != nil {\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif !hasRow {\n\t\t\tbreak\n\t\t}\n\n\t\tstropt, isNull, err := rs.String(stroptOrd)\n\t\tif err != nil {\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif isNull {\n\t\t\tstropt = \"(null)\"\n\t\t}\n\t\tfmt.Println(\"stropt:\", stropt)\n\t}\n}"} {"input": "package service\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/BurntSushi/toml\"\n\t\"github.com/nebulaim/telegramd/baselib/grpc_util\"\n\t\"github.com/nebulaim/telegramd/baselib/mysql_client\"\n\t\"github.com/nebulaim/telegramd/baselib/redis_client\"\n)\n\nvar (\n\tconfPath string\n\tConf *documentConfig\n)\n\ntype documentConfig struct {\n\tServerId int32 \n\tDataPath string\n\tRedis []redis_client.RedisConfig\n\tMysql []mysql_client.MySQLConfig\n\tRpcServer *grpc_util.RPCServerConfig\n}\n\n\n\nfunc init() {\n\tflag.StringVar(&confPath, \"conf\", \"./document.toml\", \"config path\")\n}\n\nfunc InitializeConfig() (err error) {\n\t_, err = toml.DecodeFile(confPath, &Conf)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"decode file %s error: %v\", confPath, err)\n\t}\n\treturn\n}\n\nfunc (c *documentConfig) String() string ", "output": "{\n\treturn fmt.Sprintf(\"{server_id: %d, redis: %v. mysql: %v, server: %v}\",\n\t\tc.ServerId,\n\t\tc.Redis,\n\t\tc.Mysql,\n\t\tc.RpcServer)\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/labstack/echo\"\n\n\t\"projects/onix/models\"\n\t\"projects/onix/utils\"\n)\n\n\ntype PostsController struct{}\n\n\n\n\n\nfunc (*PostsController) GetOne(c echo.Context) error {\n\tvar model models.Post\n\n\tret, err := model.GetOne(c.P(0))\n\tif err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\n\treturn c.JSON(200, ret)\n}\n\n\nfunc (*PostsController) Save(c echo.Context) error {\n\tvar model models.Post\n\tvar payload models.PostPayload\n\tvar status = c.QueryParam(\"status\")\n\n\tif err := c.Bind(&payload); err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\n\tiss := 1\n\n\tpayload.AuthorID = iss\n\tret, err := model.Create(payload, status)\n\tif err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\treturn c.JSON(200, ret)\n}\n\n\nfunc (*PostsController) Update(c echo.Context) error {\n\tvar model models.Post\n\tvar payload models.PostPayload\n\tvar status = c.QueryParam(\"status\")\n\n\tif err := c.Bind(&payload); err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\n\tiss := 1\n\n\tpayload.UpdatedBy = iss\n\tret, err := model.Update(c.P(0), payload, status)\n\tif err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\treturn c.JSON(200, ret)\n}\n\nfunc (*PostsController) Get(c echo.Context) error ", "output": "{\n\tvar model models.Post\n\tvar title = c.QueryParam(\"title\")\n\n\tret, err := model.Get(title)\n\tif err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\n\treturn c.JSON(200, ret)\n}"} {"input": "package net_sniff\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com/bettercap/bettercap/session\"\n\n\t\"github.com/evilsocket/islazy/tui\"\n\t\"github.com/google/gopacket/layers\"\n)\n\n\n\nfunc vPort(p interface{}) string {\n\tsp := fmt.Sprintf(\"%d\", p)\n\tif tcp, ok := p.(layers.TCPPort); ok {\n\t\tif name, found := layers.TCPPortNames[tcp]; found {\n\t\t\tsp = tui.Yellow(name)\n\t\t}\n\t} else if udp, ok := p.(layers.UDPPort); ok {\n\t\tif name, found := layers.UDPPortNames[udp]; found {\n\t\t\tsp = tui.Yellow(name)\n\t\t}\n\t}\n\n\treturn sp\n}\n\nvar maxUrlSize = 80\n\nfunc vURL(u string) string {\n\tul := len(u)\n\tif ul > maxUrlSize {\n\t\tu = fmt.Sprintf(\"%s...\", u[0:maxUrlSize-3])\n\t}\n\treturn u\n}\n\nfunc vIP(ip net.IP) string ", "output": "{\n\tif session.I.Interface.IP.Equal(ip) {\n\t\treturn tui.Dim(\"local\")\n\t} else if session.I.Gateway.IP.Equal(ip) {\n\t\treturn \"gateway\"\n\t}\n\n\taddress := ip.String()\n\thost := session.I.Lan.GetByIp(address)\n\tif host != nil {\n\t\tif host.Hostname != \"\" {\n\t\t\treturn host.Hostname\n\t\t}\n\t}\n\n\treturn address\n}"} {"input": "package utils\n\nimport (\n\t\"os\"\n\t\"os/user\"\n\t\"path/filepath\"\n)\n\n\n\n\n\nfunc ConfigDir() string {\n\tconfigDir := os.Getenv(\"XDG_CONFIG_HOME\")\n\tif configDir != \"\" {\n\t\treturn configDir\n\t}\n\n\treturn filepath.Join(HomeDir(), \".config\")\n}\n\nfunc HomeDir() string ", "output": "{\n\thomeDir := os.Getenv(\"HOME\")\n\tif homeDir != \"\" {\n\t\treturn homeDir\n\t}\n\n\tcurrentUser, err := user.Current()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn currentUser.HomeDir\n}"} {"input": "package main\n\nimport (\n \"container/list\"\n \"log\"\n \"sync\"\n \"time\"\n)\n\ntype ThreadPool struct {\n size, running int\n list *list.List\n m sync.Mutex\n}\n\nfunc NewThreadPool(size int) *ThreadPool {\n tp := &ThreadPool{\n size: size,\n list: list.New(),\n }\n return tp\n}\n\n\n\nfunc (tp *ThreadPool) run() {\n tp.m.Lock()\n defer tp.m.Unlock()\n if tp.list.Len() > 0 && tp.running < tp.size {\n f := tp.list.Remove(tp.list.Front()).(func())\n tp.running++\n go func() {\n f()\n tp.onStop()\n }()\n }\n}\n\nfunc (tp *ThreadPool) Submit(f func()) {\n tp.list.PushBack(f)\n tp.run()\n}\n\nfunc main() {\n var wg sync.WaitGroup\n tp := NewThreadPool(4)\n for i := 0; i < 16; i++ {\n wg.Add(1)\n (func(id int) {\n log.Printf(\"Subtmitted job %d\", id)\n tp.Submit(func() {\n time.Sleep(3 * time.Second)\n log.Printf(\"Hello from job %d\", id)\n wg.Done()\n })\n })(i)\n }\n wg.Wait()\n}\n\nfunc (tp *ThreadPool) onStop() ", "output": "{\n tp.m.Lock()\n tp.running--\n tp.m.Unlock()\n tp.run()\n}"} {"input": "package discovery\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\n\tclientcmdapi \"k8s.io/client-go/tools/clientcmd/api\"\n\tkubeadmapi \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm\"\n\t\"k8s.io/kubernetes/cmd/kubeadm/app/discovery/file\"\n\t\"k8s.io/kubernetes/cmd/kubeadm/app/discovery/https\"\n\t\"k8s.io/kubernetes/cmd/kubeadm/app/discovery/token\"\n\tkubeconfigutil \"k8s.io/kubernetes/cmd/kubeadm/app/util/kubeconfig\"\n)\n\n\nconst TokenUser = \"tls-bootstrap-token-user\"\n\n\n\n\n\n\nfunc DiscoverValidatedKubeConfig(cfg *kubeadmapi.JoinConfiguration) (*clientcmdapi.Config, error) {\n\tswitch {\n\tcase cfg.Discovery.File != nil:\n\t\tkubeConfigPath := cfg.Discovery.File.KubeConfigPath\n\t\tif isHTTPSURL(kubeConfigPath) {\n\t\t\treturn https.RetrieveValidatedConfigInfo(kubeConfigPath, cfg.ClusterName)\n\t\t}\n\t\treturn file.RetrieveValidatedConfigInfo(kubeConfigPath, cfg.ClusterName)\n\tcase cfg.Discovery.BootstrapToken != nil:\n\t\treturn token.RetrieveValidatedConfigInfo(cfg)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"couldn't find a valid discovery configuration\")\n\t}\n}\n\n\nfunc isHTTPSURL(s string) bool {\n\tu, err := url.Parse(s)\n\treturn err == nil && u.Scheme == \"https\"\n}\n\nfunc For(cfg *kubeadmapi.JoinConfiguration) (*clientcmdapi.Config, error) ", "output": "{\n\tconfig, err := DiscoverValidatedKubeConfig(cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't validate the identity of the API Server: %v\", err)\n\t}\n\n\tif len(cfg.Discovery.TLSBootstrapToken) == 0 {\n\t\treturn config, nil\n\t}\n\tclusterinfo := kubeconfigutil.GetClusterFromKubeConfig(config)\n\treturn kubeconfigutil.CreateWithToken(\n\t\tclusterinfo.Server,\n\t\tcfg.ClusterName,\n\t\tTokenUser,\n\t\tclusterinfo.CertificateAuthorityData,\n\t\tcfg.Discovery.TLSBootstrapToken,\n\t), nil\n}"} {"input": "package github\n\nimport (\n\t\"strconv\"\n\t\"time\"\n)\n\n\n\n\n\ntype Timestamp struct {\n\ttime.Time\n}\n\nfunc (t Timestamp) String() string {\n\treturn t.Time.String()\n}\n\n\n\nfunc (t *Timestamp) UnmarshalJSON(data []byte) (err error) {\n\tstr := string(data)\n\ti, err := strconv.ParseInt(str, 10, 64)\n\tif err == nil {\n\t\tt.Time = time.Unix(i, 0)\n\t} else {\n\t\tt.Time, err = time.Parse(`\"`+time.RFC3339+`\"`, str)\n\t}\n\treturn\n}\n\n\n\n\nfunc (t Timestamp) Equal(u Timestamp) bool ", "output": "{\n\treturn t.Time.Equal(u.Time)\n}"} {"input": "package endpoint\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetEndpointOKCode int = 200\n\n\ntype GetEndpointOK struct {\n\n\tPayload []*models.Endpoint `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetEndpointOK() *GetEndpointOK {\n\n\treturn &GetEndpointOK{}\n}\n\n\nfunc (o *GetEndpointOK) WithPayload(payload []*models.Endpoint) *GetEndpointOK {\n\to.Payload = payload\n\treturn o\n}\n\n\n\n\n\nfunc (o *GetEndpointOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tpayload := o.Payload\n\tif payload == nil {\n\t\tpayload = make([]*models.Endpoint, 0, 50)\n\t}\n\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) \n\t}\n}\n\n\nconst GetEndpointNotFoundCode int = 404\n\n\ntype GetEndpointNotFound struct {\n}\n\n\nfunc NewGetEndpointNotFound() *GetEndpointNotFound {\n\n\treturn &GetEndpointNotFound{}\n}\n\n\nfunc (o *GetEndpointNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc (o *GetEndpointOK) SetPayload(payload []*models.Endpoint) ", "output": "{\n\to.Payload = payload\n}"} {"input": "package service\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/syncloud/redirect/model\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype ActionsDbStub struct {\n\taction *model.Action\n}\n\n\nfunc (db *ActionsDbStub) GetActionByToken(_ string, _ uint64) (*model.Action, error) {\n\treturn db.action, nil\n}\n\nfunc (db *ActionsDbStub) InsertAction(action *model.Action) error {\n\tdb.action = action\n\treturn nil\n}\n\nfunc (db *ActionsDbStub) UpdateAction(action *model.Action) error {\n\tif db.action != nil {\n\t\tdb.action = action\n\t}\n\treturn nil\n}\n\nfunc (db *ActionsDbStub) DeleteActions(_ int64) error {\n\tdb.action = nil\n\treturn nil\n}\n\nfunc (db *ActionsDbStub) DeleteAction(actionId uint64) error {\n\tdb.action = nil\n\treturn nil\n}\n\nfunc TestUpsert(t *testing.T) {\n\n\tdb := &ActionsDbStub{nil}\n\tactions := NewActions(db)\n\n\tuser := &model.User{Id: 1, Email: \"test@example.com\", PasswordHash: \"pass\", Active: true, UpdateToken: \"token\", Timestamp: time.Now()}\n\taction, err := actions.UpsertActivateAction(user.Id)\n\n\tassert.Nil(t, err)\n\tassert.NotNil(t, action)\n\tassert.NotNil(t, db.action)\n}\n\nfunc (db *ActionsDbStub) GetAction(_ int64, _ uint64) (*model.Action, error) ", "output": "{\n\treturn db.action, nil\n}"} {"input": "package bits\n\nimport (\n\t\"path/filepath\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"k8s.io/kubeadm/kinder/pkg/extract\"\n)\n\n\n\ntype binaryBits struct {\n\tsrc string\n\tbinaryName string\n}\n\nvar _ Installer = &binaryBits{}\n\n\n\n\n\nfunc (b *binaryBits) Prepare(c *BuildContext) (map[string]string, error) {\n\te := extract.NewExtractor(\n\t\tb.src, c.HostBitsPath(),\n\t\textract.OnlyKubeadm(b.binaryName == \"kubeadm\"),\n\t\textract.OnlyKubelet(b.binaryName == \"kubelet\"),\n\t)\n\n\treturn e.Extract()\n}\n\n\nfunc (b *binaryBits) Install(c *BuildContext) error {\n\tsrc := filepath.Join(c.ContainerBitsPath(), b.binaryName)\n\n\tdest := filepath.Join(\"/usr\", \"bin\", b.binaryName)\n\n\tif err := c.RunInContainer(\"cp\", src, dest); err != nil {\n\t\tlog.Errorf(\"Image alter Failed! %v\", err)\n\t\treturn err\n\t}\n\n\tif err := c.RunInContainer(\"chown\", \"-R\", \"root:root\", dest); err != nil {\n\t\tlog.Errorf(\"Image alter failed! %v\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc NewBinaryBits(src, binaryName string) Installer ", "output": "{\n\treturn &binaryBits{\n\t\tsrc: src,\n\t\tbinaryName: binaryName,\n\t}\n}"} {"input": "package leetcode\n\nconst MAX_INT32 = 1<<31 - 1\nconst MIN_INT32 = -1 << 31\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\nfunc maxInt(a, b int) int {\n\tif a < b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}\n\nfunc minInt(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}\n\nfunc absInt(num int) int {\n\tif num > 0 {\n\t\treturn num\n\t} else {\n\t\treturn -num\n\t}\n}\n\nfunc qsortInt(nums []int) []int {\n\tif len(nums) <= 1 {\n\t\treturn nums\n\t}\n\n\thead, tail := 0, len(nums)-1\n\tidx, mid := 1, nums[0]\n\tfor head < tail {\n\t\tif nums[idx] > mid {\n\t\t\tnums[idx], nums[tail] = nums[tail], nums[idx]\n\t\t\ttail--\n\t\t} else {\n\t\t\tnums[idx], nums[head] = nums[head], nums[idx]\n\t\t\thead++\n\t\t\tidx++\n\t\t}\n\t}\n\tnums[head] = mid\n\tqsortInt(nums[:head])\n\tqsortInt(nums[head+1:])\n\treturn nums\n}\n\ntype Stack struct {\n\tdata []rune\n}\n\nfunc (s *Stack) push(data rune) {\n\ts.data = append(s.data, data)\n}\n\nfunc (s *Stack) pop() rune {\n\tif len(s.data) == 0 {\n\t\treturn 0\n\t}\n\tret := s.data[len(s.data)-1]\n\ts.data = s.data[:len(s.data)-1]\n\treturn ret\n}\n\n\n\nfunc (s Stack) empty() bool ", "output": "{\n\treturn len(s.data) == 0\n}"} {"input": "package msgraph\n\nimport \"context\"\n\n\ntype WorkbookFunctionsProductRequestBuilder struct{ BaseRequestBuilder }\n\n\nfunc (b *WorkbookFunctionsRequestBuilder) Product(reqObj *WorkbookFunctionsProductRequestParameter) *WorkbookFunctionsProductRequestBuilder {\n\tbb := &WorkbookFunctionsProductRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.BaseRequestBuilder.baseURL += \"/product\"\n\tbb.BaseRequestBuilder.requestObject = reqObj\n\treturn bb\n}\n\n\ntype WorkbookFunctionsProductRequest struct{ BaseRequest }\n\n\nfunc (b *WorkbookFunctionsProductRequestBuilder) Request() *WorkbookFunctionsProductRequest {\n\treturn &WorkbookFunctionsProductRequest{\n\t\tBaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},\n\t}\n}\n\n\n\n\nfunc (r *WorkbookFunctionsProductRequest) Post(ctx context.Context) (resObj *WorkbookFunctionResult, err error) ", "output": "{\n\terr = r.JSONRequest(ctx, \"POST\", \"\", r.requestObject, &resObj)\n\treturn\n}"} {"input": "package decoders\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestParseTime(t *testing.T) {\n\tr := require.New(t)\n\n\ttestCases := []struct {\n\t\tinput string\n\t\texpected time.Time\n\t\texpectErr bool\n\t}{\n\t\t{\n\t\t\tinput: \"2017-01-01\",\n\t\t\texpected: time.Date(2017, time.January, 1, 0, 0, 0, 0, time.UTC),\n\t\t\texpectErr: false,\n\t\t},\n\t\t{\n\t\t\tinput: \"2018-07-13T15:34\",\n\t\t\texpected: time.Date(2018, time.July, 13, 15, 34, 0, 0, time.UTC),\n\t\t\texpectErr: false,\n\t\t},\n\t\t{\n\t\t\tinput: \"2018-20-10T30:15\",\n\t\t\texpected: time.Time{},\n\t\t\texpectErr: true,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttt, err := parseTime([]string{tc.input})\n\t\tif !tc.expectErr {\n\t\t\tr.NoError(err)\n\t\t}\n\n\t\tr.Equal(tc.expected, tt)\n\t}\n}\n\nfunc TestParseTimeConflicting(t *testing.T) {\n\tr := require.New(t)\n\n\tRegisterTimeFormats(\"2006-02-01\")\n\ttt, err := parseTime([]string{\"2017-01-10\"})\n\n\tr.NoError(err)\n\texpected := time.Date(2017, time.October, 1, 0, 0, 0, 0, time.UTC)\n\tr.Equal(expected, tt)\n}\n\nfunc TestParseTimeErrorParsing(t *testing.T) ", "output": "{\n\tr := require.New(t)\n\n\t_, err := parseTime([]string{\"this is sparta\"})\n\tr.Error(err)\n}"} {"input": "package sqlbuilder\n\ntype Dialect interface {\n\tEscapeCharacter() rune\n\tInsertReturningClause() string\n\tKind() string\n\tName() *string\n}\n\ntype genericDialect struct {\n\tescapeChar rune\n\treturningClause string\n\tkind string\n\tname *string\n}\n\nfunc (db *genericDialect) EscapeCharacter() rune {\n\treturn db.escapeChar\n}\n\nfunc (db *genericDialect) InsertReturningClause() string {\n\treturn db.returningClause\n}\n\nfunc (db *genericDialect) Kind() string {\n\treturn db.kind\n}\n\nfunc (db *genericDialect) Name() *string {\n\treturn db.name\n}\n\n\n\nfunc NewPostgresDialect(dbName *string) Dialect {\n\treturn &genericDialect{\n\t\tescapeChar: '\"',\n\t\treturningClause: \" RETURNING *\",\n\t\tkind: \"postgres\",\n\t\tname: dbName,\n\t}\n}\n\nfunc NewSQLiteDialect() Dialect {\n\tdefaultName := \"main\"\n\treturn &genericDialect{\n\t\tescapeChar: '\"',\n\t\tkind: \"sqlite\",\n\t\tname: &defaultName,\n\t}\n}\n\nfunc NewMySQLDialect(dbName *string) Dialect ", "output": "{\n\treturn &genericDialect{\n\t\tescapeChar: '`',\n\t\tkind: \"mysql\",\n\t\tname: dbName,\n\t}\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype CustomResourceDefinitionLister interface {\n\tList(selector labels.Selector) (ret []*v1beta1.CustomResourceDefinition, err error)\n\tGet(name string) (*v1beta1.CustomResourceDefinition, error)\n\tCustomResourceDefinitionListerExpansion\n}\n\n\ntype customResourceDefinitionLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewCustomResourceDefinitionLister(indexer cache.Indexer) CustomResourceDefinitionLister {\n\treturn &customResourceDefinitionLister{indexer: indexer}\n}\n\n\nfunc (s *customResourceDefinitionLister) List(selector labels.Selector) (ret []*v1beta1.CustomResourceDefinition, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.CustomResourceDefinition))\n\t})\n\treturn ret, err\n}\n\n\n\n\nfunc (s *customResourceDefinitionLister) Get(name string) (*v1beta1.CustomResourceDefinition, error) ", "output": "{\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"customresourcedefinition\"), name)\n\t}\n\treturn obj.(*v1beta1.CustomResourceDefinition), nil\n}"} {"input": "package euler\n\n\n\n\n\n\n\n\n\n\n\nfunc isAmicable(a int) bool {\n\tb := PropDivSum(a)\n\treturn a != b && a == PropDivSum(b)\n}\n\nfunc Problem21() int ", "output": "{\n\tsum := 0\n\tfor n := 2; n < 10e3; n++ { \n\t\tif isAmicable(n) {\n\t\t\tsum += n\n\t\t}\n\t}\n\treturn sum\n}"} {"input": "package trace \n\nimport (\n\t\"context\"\n\t\"runtime\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"google.golang.org/grpc/metadata\"\n)\n\n\n\n\nfunc DefaultAuthScopes() []string {\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t\t\"https:www.googleapis.com/auth/trace.append\",\n\t\t\"https:www.googleapis.com/auth/trace.readonly\",\n\t}\n}\n\n\n\nfunc versionGo() string {\n\tconst develPrefix = \"devel +\"\n\n\ts := runtime.Version()\n\tif strings.HasPrefix(s, develPrefix) {\n\t\ts = s[len(develPrefix):]\n\t\tif p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 {\n\t\t\ts = s[:p]\n\t\t}\n\t\treturn s\n\t}\n\n\tnotSemverRune := func(r rune) bool {\n\t\treturn strings.IndexRune(\"0123456789.\", r) < 0\n\t}\n\n\tif strings.HasPrefix(s, \"go1\") {\n\t\ts = s[2:]\n\t\tvar prerelease string\n\t\tif p := strings.IndexFunc(s, notSemverRune); p >= 0 {\n\t\t\ts, prerelease = s[:p], s[p:]\n\t\t}\n\t\tif strings.HasSuffix(s, \".\") {\n\t\t\ts += \"0\"\n\t\t} else if strings.Count(s, \".\") < 2 {\n\t\t\ts += \".0\"\n\t\t}\n\t\tif prerelease != \"\" {\n\t\t\ts += \"-\" + prerelease\n\t\t}\n\t\treturn s\n\t}\n\treturn \"UNKNOWN\"\n}\n\nconst versionClient = \"20181129\"\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context ", "output": "{\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}"} {"input": "package iso\n\nimport (\n\t\"fmt\"\n\t\"github.com/mitchellh/multistep\"\n\tvmwcommon \"github.com/mitchellh/packer/builder/vmware/common\"\n\t\"github.com/mitchellh/packer/packer\"\n\t\"log\"\n)\n\n\n\ntype stepRemoteUpload struct {\n\tKey string\n\tMessage string\n}\n\n\n\nfunc (s *stepRemoteUpload) Cleanup(state multistep.StateBag) {\n}\n\nfunc (s *stepRemoteUpload) Run(state multistep.StateBag) multistep.StepAction ", "output": "{\n\tdriver := state.Get(\"driver\").(vmwcommon.Driver)\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\tremote, ok := driver.(RemoteDriver)\n\tif !ok {\n\t\treturn multistep.ActionContinue\n\t}\n\n\tpath, ok := state.Get(s.Key).(string)\n\tif !ok {\n\t\treturn multistep.ActionContinue\n\t}\n\n\tui.Say(s.Message)\n\tlog.Printf(\"Remote uploading: %s\", path)\n\tnewPath, err := remote.UploadISO(path)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"Error uploading file: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\tstate.Put(s.Key, newPath)\n\treturn multistep.ActionContinue\n}"} {"input": "package fakes\n\nimport (\n\t\"net\"\n\t\"sync\"\n\n\t\"github.com/cloudfoundry-incubator/diego-ssh/cf-plugin/cmd\"\n)\n\ntype FakeListenerFactory struct {\n\tListenStub func(network, address string) (net.Listener, error)\n\tlistenMutex sync.RWMutex\n\tlistenArgsForCall []struct {\n\t\tnetwork string\n\t\taddress string\n\t}\n\tlistenReturns struct {\n\t\tresult1 net.Listener\n\t\tresult2 error\n\t}\n}\n\nfunc (fake *FakeListenerFactory) Listen(network string, address string) (net.Listener, error) {\n\tfake.listenMutex.Lock()\n\tfake.listenArgsForCall = append(fake.listenArgsForCall, struct {\n\t\tnetwork string\n\t\taddress string\n\t}{network, address})\n\tfake.listenMutex.Unlock()\n\tif fake.ListenStub != nil {\n\t\treturn fake.ListenStub(network, address)\n\t} else {\n\t\treturn fake.listenReturns.result1, fake.listenReturns.result2\n\t}\n}\n\n\n\nfunc (fake *FakeListenerFactory) ListenArgsForCall(i int) (string, string) {\n\tfake.listenMutex.RLock()\n\tdefer fake.listenMutex.RUnlock()\n\treturn fake.listenArgsForCall[i].network, fake.listenArgsForCall[i].address\n}\n\nfunc (fake *FakeListenerFactory) ListenReturns(result1 net.Listener, result2 error) {\n\tfake.ListenStub = nil\n\tfake.listenReturns = struct {\n\t\tresult1 net.Listener\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nvar _ cmd.ListenerFactory = new(FakeListenerFactory)\n\nfunc (fake *FakeListenerFactory) ListenCallCount() int ", "output": "{\n\tfake.listenMutex.RLock()\n\tdefer fake.listenMutex.RUnlock()\n\treturn len(fake.listenArgsForCall)\n}"} {"input": "package datastore\n\nimport \"github.com/swagchat/chat-api/model\"\n\n\n\nfunc (p *gcpSQLProvider) SelectWebhooks(event model.WebhookEventType, opts ...SelectWebhooksOption) ([]*model.Webhook, error) {\n\treplica := RdbStore(p.database).replica()\n\treturn rdbSelectWebhooks(p.ctx, replica, event, opts...)\n}\n\nfunc (p *gcpSQLProvider) createWebhookStore() ", "output": "{\n\tmaster := RdbStore(p.database).master()\n\trdbCreateWebhookStore(p.ctx, master)\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc FloatToPercent(i float64) string {\n\treturn fmt.Sprintf(\"%.0f\", i*100.0)\n}\n\nfunc PercSuffix(i float64) string {\n\tswitch int(i*100) % 10 {\n\tcase 1:\n\t\treturn \"st\"\n\tcase 2:\n\t\treturn \"nd\"\n\tcase 3:\n\t\treturn \"rd\"\n\t}\n\treturn \"th\"\n}\n\nfunc NanoSecondToHuman(v float64) string {\n\tvar suffix string\n\tswitch {\n\tcase v > 1000000000:\n\t\tv /= 1000000000\n\t\tsuffix = \"s\"\n\tcase v > 1000000:\n\t\tv /= 1000000\n\t\tsuffix = \"ms\"\n\tcase v > 1000:\n\t\tv /= 1000\n\t\tsuffix = \"us\"\n\tdefault:\n\t\tsuffix = \"ns\"\n\t}\n\treturn fmt.Sprintf(\"%0.1f%s\", v, suffix)\n}\n\nfunc Commafy(i interface{}) string ", "output": "{\n\tvar n int64\n\tswitch i.(type) {\n\tcase int:\n\t\tn = int64(i.(int))\n\tcase int64:\n\t\tn = i.(int64)\n\tcase int32:\n\t\tn = int64(i.(int32))\n\t}\n\tif n > 1000 {\n\t\tr := n % 1000\n\t\tn = n / 1000\n\t\treturn fmt.Sprintf(\"%s,%03d\", Commafy(n), r)\n\t}\n\treturn fmt.Sprintf(\"%d\", n)\n}"} {"input": "package library\n\nimport (\n\t\"github.com/nytlabs/streamtools/st/blocks\" \n)\n\n\ntype FromPost struct {\n\tblocks.Block\n\tqueryrule chan blocks.MsgChan\n\tinrule blocks.MsgChan\n\tin blocks.MsgChan\n\tout blocks.MsgChan\n\tquit blocks.MsgChan\n}\n\n\nfunc NewFromPost() blocks.BlockInterface {\n\treturn &FromPost{}\n}\n\n\nfunc (b *FromPost) Setup() {\n\tb.Kind = \"Network I/O\"\n\tb.Desc = \"emits any message that is POSTed to its IN route\"\n\tb.in = b.InRoute(\"in\")\n\tb.quit = b.Quit()\n\tb.out = b.Broadcast()\n}\n\n\n\n\nfunc (b *FromPost) Run() ", "output": "{\n\tfor {\n\t\tselect {\n\t\tcase <-b.quit:\n\t\t\treturn\n\t\tcase msg := <-b.in:\n\t\t\tb.out <- msg\n\t\t}\n\t}\n}"} {"input": "package drum\n\nimport \"fmt\"\n\n\n\ntype Pattern struct {\n\tversion Version\n\ttempo Tempo\n\ttracks Tracks\n}\n\nfunc (p Pattern) String() string {\n\treturn fmt.Sprintf(\"%s\\n%s\\n%s\", p.version.String(), p.tempo.String(), p.tracks.String())\n}\n\n\ntype Version string\n\nfunc (v Version) String() string {\n\treturn fmt.Sprintf(\"Saved with HW Version: %s\", string(v))\n}\n\n\ntype Tempo float64\n\nfunc (t Tempo) String() string {\n\treturn fmt.Sprintf(\"Tempo: %.3g\", t)\n}\n\n\ntype Tracks []Track\n\nfunc (t Tracks) String() string {\n\tpretty := \"\"\n\tfor _, track := range t {\n\t\tpretty = fmt.Sprintf(\"%s%s\\n\", pretty, track.String())\n\t}\n\treturn pretty\n}\n\n\ntype Track struct {\n\tID int\n\tName string\n\tSteps Steps\n}\n\nfunc (t Track) String() string {\n\treturn fmt.Sprintf(\"(%d) %s\\t%s\", t.ID, t.Name, t.Steps.String())\n}\n\n\ntype Steps struct {\n\tBars [4]Bar\n}\n\n\n\n\ntype Bar [4]Note\n\nfunc (bar Bar) String() string {\n\tpretty := \"\"\n\tfor _, note := range bar {\n\t\tpretty = pretty + note.String()\n\t}\n\treturn pretty\n}\n\n\ntype Note bool\n\nfunc (n Note) String() string {\n\tif n {\n\t\treturn \"x\"\n\t}\n\treturn \"-\"\n}\n\nfunc (s Steps) String() string ", "output": "{\n\tpretty := \"|\"\n\tfor _, bar := range s.Bars {\n\t\tpretty = pretty + bar.String() + \"|\"\n\t}\n\treturn pretty\n}"} {"input": "package jobs\n\nimport (\n\t\"fmt\"\n\t\"github.com/nubleer/revel\"\n\t\"github.com/nubleer/revel/modules/jobs/app/jobs\"\n\t\"github.com/nubleer/revel/samples/booking/app/controllers\"\n\t\"github.com/nubleer/revel/samples/booking/app/models\"\n)\n\n\ntype BookingCounter struct{}\n\n\n\nfunc init() {\n\trevel.OnAppStart(func() {\n\t\tjobs.Schedule(\"@every 1m\", BookingCounter{})\n\t})\n}\n\nfunc (c BookingCounter) Run() ", "output": "{\n\tbookings, err := controllers.Dbm.Select(models.Booking{},\n\t\t`select * from Booking`)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"There are %d bookings.\\n\", len(bookings))\n}"} {"input": "package sliceset\n\nimport (\n\t\"sort\"\n\n\t\"github.com/xtgo/set\"\n)\n\ntype Set []int\n\nfunc (s Set) Len() int { return len(s) }\nfunc (s Set) Less(i, j int) bool { return s[i] < s[j] }\nfunc (s Set) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s Set) Copy() Set { return append(Set(nil), s...) }\n\nfunc (s Set) Union(t Set) Set { return s.Do(set.Union, t) }\nfunc (s Set) Inter(t Set) Set { return s.Do(set.Inter, t) }\nfunc (s Set) Diff(t Set) Set { return s.Do(set.Diff, t) }\nfunc (s Set) SymDiff(t Set) Set { return s.Do(set.SymDiff, t) }\nfunc (s Set) IsSub(t Set) bool { return s.DoBool(set.IsSub, t) }\nfunc (s Set) IsSuper(t Set) bool { return s.DoBool(set.IsSuper, t) }\nfunc (s Set) IsInter(t Set) bool { return s.DoBool(set.IsInter, t) }\nfunc (s Set) IsEqual(t Set) bool { return s.DoBool(set.IsEqual, t) }\n\n\n\nfunc (s Set) Do(op set.Op, t Set) Set {\n\tdata := append(s, t...)\n\tn := op(data, len(s))\n\treturn data[:n]\n}\n\ntype BoolOp func(sort.Interface, int) bool\n\nfunc (s Set) DoBool(op BoolOp, t Set) bool {\n\tdata := append(s, t...)\n\treturn op(data, len(s))\n}\n\nfunc (s Set) Uniq() Set ", "output": "{\n\tn := set.Uniq(s)\n\treturn s[:n]\n}"} {"input": "package common\n\n\n\n\nimport (\n\t\"strconv\"\n)\n\n\nfunc Atof32(s string) float64 {\n\tf, err := strconv.ParseFloat(s, 32)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn float64(f)\n}\n\n\nfunc Atoi(s string) int {\n\ti, err := strconv.Atoi(s)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn i\n}\n\n\n\n\n\nfunc Atoi64(str string) int64 {\n\ti, err := strconv.ParseInt(str, 10, 64)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn i\n}\n\n\nfunc Atof64(str string) float64 {\n\ti, err := strconv.ParseFloat(str, 64)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn i\n}\n\nfunc Atob(str string) bool ", "output": "{\n\tb, err := strconv.ParseBool(str)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn b\n}"} {"input": "package mysql\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\n\n\n\n\ntype GTID interface {\n\tString() string\n\n\tFlavor() string\n\n\tSourceServer() interface{}\n\n\tSequenceNumber() interface{}\n\n\tSequenceDomain() interface{}\n\n\tGTIDSet() GTIDSet\n}\n\n\nvar gtidParsers = make(map[string]func(string) (GTID, error))\n\n\nfunc ParseGTID(flavor, value string) (GTID, error) {\n\tparser := gtidParsers[flavor]\n\tif parser == nil {\n\t\treturn nil, fmt.Errorf(\"parse error: unknown GTID flavor %#v\", flavor)\n\t}\n\treturn parser(value)\n}\n\n\n\n\n\n\n\nfunc EncodeGTID(gtid GTID) string {\n\tif gtid == nil {\n\t\treturn \"\"\n\t}\n\n\treturn fmt.Sprintf(\"%s/%s\", gtid.Flavor(), gtid.String())\n}\n\n\n\nfunc DecodeGTID(s string) (GTID, error) {\n\tif s == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tparts := strings.SplitN(s, \"/\", 2)\n\tif len(parts) != 2 {\n\t\treturn ParseGTID(\"\", s)\n\t}\n\treturn ParseGTID(parts[0], parts[1])\n}\n\n\nfunc MustDecodeGTID(s string) GTID {\n\tgtid, err := DecodeGTID(s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn gtid\n}\n\nfunc MustParseGTID(flavor, value string) GTID ", "output": "{\n\tgtid, err := ParseGTID(flavor, value)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn gtid\n}"} {"input": "package sshConfig\n\n\n\n\n\n\n\nfunc ValidYesOrNo() []string {\n\treturn []string{\"\", \"yes\", \"no\"}\n}\n\n\n\nfunc ValidStringArgs(possibilities []string, received string) bool {\n\tfor _, possible := range possibilities {\n\t\tif possible == received {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc ValidAddressFamilyAnswers() []string ", "output": "{\n\treturn []string{\"\", \"any\", \"inet\", \"inet6\"}\n}"} {"input": "package syscallx\n\n\n\n\nimport (\n\t\"syscall\"\n)\n\nfunc Getxattr(path string, attr string, dest []byte) (sz int, err error) {\n\treturn syscall.Getxattr(path, attr, dest)\n}\n\nfunc Listxattr(path string, dest []byte) (sz int, err error) {\n\treturn syscall.Listxattr(path, dest)\n}\n\nfunc Setxattr(path string, attr string, data []byte, flags int) (err error) {\n\treturn syscall.Setxattr(path, attr, data, flags)\n}\n\n\n\nfunc Removexattr(path string, attr string) (err error) ", "output": "{\n\treturn syscall.Removexattr(path, attr)\n}"} {"input": "package hello\n\nimport (\n\t\"github.com/cortinico/telebotgae\"\n\t\"net/http\"\n)\n\n\n\nfunc init() ", "output": "{\n\tconf := telebotgae.Configuration{\n\t\tBotName: \"PLACE-HERE-YOUR-BOT-NAME\",\n\t\tApiKey: \"PLACE-HERE-YOUR-API-KEY\"}\n\n\tvar bot telebotgae.Bot\n\n\tbot.Startgae(conf, func(mess string, r *http.Request) (string, error) {\n\t\treturn \"You typed \" + mess, nil\n\t})\n}"} {"input": "package fsrateio\n\nimport (\n\t\"io\"\n\n\t\"github.com/Symantec/Dominator/lib/rateio\"\n\t\"github.com/Symantec/tricorder/go/tricorder\"\n\t\"github.com/Symantec/tricorder/go/tricorder/units\"\n)\n\ntype ReaderContext struct {\n\tmaxBytesPerSecond uint64\n\tmaxBlocksPerSecond uint64\n\tctx *rateio.ReaderContext\n}\n\nfunc NewReaderContext(maxBytesPerSecond uint64,\n\tmaxBlocksPerSecond uint64, speedPercent uint64) *ReaderContext {\n\treturn newReaderContext(maxBytesPerSecond, maxBlocksPerSecond, speedPercent)\n}\n\n\n\nfunc (ctx *ReaderContext) NewReader(rd io.Reader) *rateio.Reader {\n\treturn ctx.ctx.NewReader(rd)\n}\n\nfunc (ctx *ReaderContext) RegisterMetrics(dir *tricorder.DirectorySpec) error {\n\tif ctx.maxBlocksPerSecond > 0 {\n\t\treturn ctx.ctx.RegisterMetrics(dir, units.None,\n\t\t\t\"file-system speed in blocks per second\")\n\t}\n\treturn ctx.ctx.RegisterMetrics(dir, units.BytePerSecond,\n\t\t\"file-system speed\")\n}\n\nfunc (ctx *ReaderContext) String() string {\n\treturn ctx.format()\n}\n\nfunc (ctx *ReaderContext) GetContext() *rateio.ReaderContext ", "output": "{ return ctx.ctx }"} {"input": "package macaron\n\nimport (\n\t\"net/http\"\n\t\"reflect\"\n\n\t\"gitea.com/macaron/inject\"\n)\n\n\n\n\n\ntype ReturnHandler func(*Context, []reflect.Value)\n\nfunc canDeref(val reflect.Value) bool {\n\treturn val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr\n}\n\nfunc isError(val reflect.Value) bool {\n\t_, ok := val.Interface().(error)\n\treturn ok\n}\n\n\n\nfunc defaultReturnHandler() ReturnHandler {\n\treturn func(ctx *Context, vals []reflect.Value) {\n\t\trv := ctx.GetVal(inject.InterfaceOf((*http.ResponseWriter)(nil)))\n\t\tresp := rv.Interface().(http.ResponseWriter)\n\t\tvar respVal reflect.Value\n\t\tif len(vals) > 1 && vals[0].Kind() == reflect.Int {\n\t\t\tresp.WriteHeader(int(vals[0].Int()))\n\t\t\trespVal = vals[1]\n\t\t} else if len(vals) > 0 {\n\t\t\trespVal = vals[0]\n\n\t\t\tif isError(respVal) {\n\t\t\t\terr := respVal.Interface().(error)\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx.internalServerError(ctx, err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t} else if canDeref(respVal) {\n\t\t\t\tif respVal.IsNil() {\n\t\t\t\t\treturn \n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif canDeref(respVal) {\n\t\t\trespVal = respVal.Elem()\n\t\t}\n\t\tif isByteSlice(respVal) {\n\t\t\t_, _ = resp.Write(respVal.Bytes())\n\t\t} else {\n\t\t\t_, _ = resp.Write([]byte(respVal.String()))\n\t\t}\n\t}\n}\n\nfunc isByteSlice(val reflect.Value) bool ", "output": "{\n\treturn val.Kind() == reflect.Slice && val.Type().Elem().Kind() == reflect.Uint8\n}"} {"input": "package ini\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/mono83/cfg\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"strings\"\n)\n\nvar nlByte = []byte{0x0a}\n\n\n\n\n\n\n\nfunc NewStringSource(source string) (cfg.Configurer, error) {\n\treturn NewBytesSource([]byte(source))\n}\n\n\n\nfunc NewBytesSource(source []byte) (cfg.Configurer, error) {\n\tif len(source) == 0 {\n\t\treturn nil, errors.New(\"Empty INI source\")\n\t}\n\n\tsrc := map[string]interface{}{}\n\tfor _, bline := range bytes.Split(source, nlByte) {\n\t\tline := strings.TrimSpace(string(bline))\n\t\tif len(line) == 0 || line[0] == '#' || line[0] == '/' || line[0] == '[' {\n\t\t\tcontinue\n\t\t}\n\n\t\tpos := strings.IndexRune(line, '=')\n\t\tif pos == -1 {\n\t\t\treturn nil, fmt.Errorf(\"Unable to parse line %s\", line)\n\t\t}\n\n\t\tkey := strings.TrimSpace(line[0:pos])\n\t\tvalue := strings.TrimSpace(line[pos+1:])\n\n\t\tsrc[key] = value\n\t}\n\n\treturn cfg.Map(src), nil\n}\n\nfunc NewReaderSource(source io.Reader) (cfg.Configurer, error) ", "output": "{\n\tbts, err := ioutil.ReadAll(source)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewBytesSource(bts)\n}"} {"input": "package rules\n\n\n\nfunc (this piece) calculateKnightMovesFrom(square square, board board) (moves []move) {\n\tfor _, offset := range knightMoveOffsets {\n\t\ttarget := square.Offset(offset)\n\t\tif !target.IsValidSquare() {\n\t\t\tcontinue\n\t\t}\n\t\ttargetPiece := board.GetPieceAt(target)\n\t\tif targetPiece.Player() == this.Player() {\n\t\t\tcontinue\n\t\t}\n\t\tmoves = append(moves, move{\n\t\t\tPiece: this,\n\t\t\tFrom: square,\n\t\t\tTo: target,\n\t\t\tCaptured: targetPiece,\n\t\t\tCapturedOn: target,\n\t\t})\n\t}\n\treturn moves\n}\n\nfunc (this piece) getKnightCoverageFrom(from square) (covered []square) ", "output": "{\n\tfor _, offset := range knightMoveOffsets {\n\t\ttarget := from.Offset(offset)\n\t\tcovered = append(covered, target)\n\t}\n\treturn covered\n}"} {"input": "package loadbalancer\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateListenerRequest struct {\n\n\tCreateListenerDetails `contributesTo:\"body\"`\n\n\tLoadBalancerId *string `mandatory:\"true\" contributesTo:\"path\" name:\"loadBalancerId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request CreateListenerRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CreateListenerRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CreateListenerRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateListenerResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateListenerResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateListenerResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateListenerRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package processors\n\nimport \"github.com/dailyburn/ratchet/data\"\n\n\n\n\n\ntype Passthrough struct {\n\ti int\n}\n\n\n\n\n\nfunc (r *Passthrough) ProcessData(d data.JSON, outputChan chan data.JSON, killChan chan error) {\n\toutputChan <- d\n}\n\n\nfunc (r *Passthrough) Finish(outputChan chan data.JSON, killChan chan error) {\n}\n\nfunc (r *Passthrough) String() string {\n\treturn \"Passthrough\"\n}\n\nfunc NewPassthrough() *Passthrough ", "output": "{\n\treturn &Passthrough{}\n}"} {"input": "package main\n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n\tpb \"proto\"\n\t\"testing\"\n)\n\nconst (\n\taddress = \"localhost:50006\"\n)\n\n\n\nfunc TestAuthUUID(t *testing.T) ", "output": "{\n\tconn, err := grpc.Dial(address)\n\tif err != nil {\n\t\tt.Fatalf(\"did not connect: %v\", err)\n\t}\n\tdefer conn.Close()\n\tc := pb.NewAuthServiceClient(conn)\n\ttest_uuid := \"CA761232-ED42-11CE-BACD-00AA0057B223\"\n\tr, err := c.Auth(context.Background(), &pb.Auth_Certificate{Type: pb.Auth_UUID, Proof: []byte(test_uuid)})\n\tif err != nil {\n\t\tt.Fatalf(\"could not query: %v\", err)\n\t}\n\tt.Log(r)\n\n\tr, err = c.Auth(context.Background(), &pb.Auth_Certificate{Type: pb.Auth_UUID, Proof: []byte(test_uuid + \"XXX\")})\n\tif err != nil {\n\t\tt.Fatalf(\"could not query: %v\", err)\n\t}\n\tt.Log(r)\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\t\"fmt\"\n)\n\nfunc TestFirst(t *testing.T) {\n\tresult := solveFirst([]int{\n\t\t0,\n\t\t3,\n\t\t0,\n\t\t1,\n\t\t-3,\n\t})\n\n\tcheckResult(t, result, 5)\n}\n\nfunc TestSecond(t *testing.T) {\n\tresult := solveSecond([]int{\n\t\t0,\n\t\t3,\n\t\t0,\n\t\t1,\n\t\t-3,\n\t})\n\n\tcheckResult(t, result, 10)\n}\n\n\n\nfunc checkResult(t *testing.T, actualResult int, requiredResult int) ", "output": "{\n\tt.Helper()\n\n\tif actualResult != requiredResult {\n\t\tt.Error(fmt.Printf(\"steps count must be %+v, but: %+v\", requiredResult, actualResult))\n\t}\n}"} {"input": "package objectsTestUtil\n\nimport (\n\t\"github.com/eu271/Soulog/Blog/objects\"\n\t\"testing\"\n)\n\ntype TestPostBuilder interface {\n\tsoul.PostBuilder\n\tWithParagraphs(int) TestPostBuilder\n\tWithRandomTitle() TestPostBuilder\n\tBefore(*soul.Post) TestPostBuilder\n\tAfter(*soul.Post) TestPostBuilder\n\tFillWithRandom() TestPostBuilder\n}\n\nfunc NewTestPostBuilder() *TestPostBuilder {\n\tvar post *soul.Post\n\tvar err error\n\n\tpost, err = soul.NewPostBuilder().\n\t\tId(\"asdasd\").\n\t\tPermalink(\"asdasdasd\").\n\t\tTitle(\"asdasda\").\n\t\tSlug(\"asasd\").\n\t\tContent(\"asdasdasdasd\").\n\t\tState(\"publish\").\n\t\tBuild()\n\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tif post == nil {\n\t\tpanic(\"Post es nil\")\n\t}\n\n\treturn &TestPostBuilder{}\n\n}\n\n\n\nfunc AssertEquals(post, post1 *soul.Post, t *testing.T) ", "output": "{\n\n\tif post.Id != post1.Id {\n\t\tt.Error(\"Posts ids not equals: \" + post.Id + \" \" + post1.Id)\n\t}\n\n\tif post.Permalink != post1.Permalink {\n\t\tt.Error(\"Posts permalins not equals: \" + post.Permalink + \" \" + post1.Permalink)\n\t}\n\n}"} {"input": "package arn\n\n\n\n\n\ntype AnimeCharacter struct {\n\tCharacterID string `json:\"characterId\" editable:\"true\"`\n\tRole string `json:\"role\" editable:\"true\" datalist:\"anime-character-roles\"`\n}\n\n\nfunc (char *AnimeCharacter) Character() *Character {\n\tcharacter, _ := GetCharacter(char.CharacterID)\n\treturn character\n}\n\nfunc init() ", "output": "{\n\tDataLists[\"anime-character-roles\"] = []*Option{\n\t\t{\"main\", \"Main character\"},\n\t\t{\"supporting\", \"Supporting character\"},\n\t}\n}"} {"input": "package local\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/apache/beam/sdks/go/pkg/beam/io/textio\"\n)\n\nfunc init() {\n\ttextio.RegisterFileSystem(\"default\", New)\n}\n\ntype fs struct{}\n\n\n\n\nfunc (f *fs) Close() error {\n\treturn nil\n}\n\nfunc (f *fs) List(ctx context.Context, glob string) ([]string, error) {\n\treturn filepath.Glob(glob)\n}\n\nfunc (f *fs) OpenRead(ctx context.Context, filename string) (io.ReadCloser, error) {\n\treturn os.Open(filename)\n}\n\nfunc (f *fs) OpenWrite(ctx context.Context, filename string) (io.WriteCloser, error) {\n\tif err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {\n\t\treturn nil, err\n\t}\n\treturn os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\n}\n\nfunc New(ctx context.Context) textio.FileSystem ", "output": "{\n\treturn &fs{}\n}"} {"input": "package sqlmock\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\nvar mock = &sqlmock{}\n\nfunc ExampleNewErrorResult() {\n\tdb, mock, _ := New()\n\tresult := NewErrorResult(fmt.Errorf(\"some error\"))\n\tmock.ExpectExec(\"^INSERT (.+)\").WillReturnResult(result)\n\tres, _ := db.Exec(\"INSERT something\")\n\t_, err := res.LastInsertId()\n\tfmt.Println(err)\n}\n\nfunc ExampleNewResult() {\n\tvar lastInsertID, affected int64\n\tresult := NewResult(lastInsertID, affected)\n\tmock.ExpectExec(\"^INSERT (.+)\").WillReturnResult(result)\n\tfmt.Println(mock.ExpectationsWereMet())\n}\n\n\n\nfunc TestShouldReturnErroeSqlDriverResult(t *testing.T) {\n\tresult := NewErrorResult(fmt.Errorf(\"some error\"))\n\t_, err := result.LastInsertId()\n\tif err == nil {\n\t\tt.Error(\"expected error, but got none\")\n\t}\n\t_, err = result.RowsAffected()\n\tif err == nil {\n\t\tt.Error(\"expected error, but got none\")\n\t}\n}\n\nfunc TestShouldReturnValidSqlDriverResult(t *testing.T) ", "output": "{\n\tresult := NewResult(1, 2)\n\tid, err := result.LastInsertId()\n\tif 1 != id {\n\t\tt.Errorf(\"Expected last insert id to be 1, but got: %d\", id)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"expected no error, but got: %s\", err)\n\t}\n\taffected, err := result.RowsAffected()\n\tif 2 != affected {\n\t\tt.Errorf(\"Expected affected rows to be 2, but got: %d\", affected)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"expected no error, but got: %s\", err)\n\t}\n}"} {"input": "package errors\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/GoogleContainerTools/skaffold/proto/v1\"\n)\n\ntype Error interface {\n\tError() string\n\tStatusCode() proto.StatusCode\n\tSuggestions() []*proto.Suggestion\n\tUnwrap() error\n}\n\ntype ErrDef struct {\n\terr error\n\tae *proto.ActionableErr\n}\n\nvar _ error = (*ErrDef)(nil)\n\nfunc (e *ErrDef) Error() string {\n\tif s := concatSuggestions(e.Suggestions()); s != \"\" {\n\t\treturn fmt.Sprintf(\"%s. %s\", e.ae.Message, concatSuggestions(e.Suggestions()))\n\t}\n\treturn e.ae.Message\n}\n\nfunc (e *ErrDef) Unwrap() error {\n\treturn e.err\n}\n\nfunc (e *ErrDef) StatusCode() proto.StatusCode {\n\treturn e.ae.ErrCode\n}\n\nfunc (e *ErrDef) Suggestions() []*proto.Suggestion {\n\treturn e.ae.Suggestions\n}\n\n\n\n\n\nfunc NewErrorWithStatusCode(ae *proto.ActionableErr) *ErrDef {\n\treturn &ErrDef{\n\t\tae: ae,\n\t}\n}\n\nfunc IsSkaffoldErr(err error) bool {\n\tif _, ok := err.(Error); ok {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc NewError(err error, ae *proto.ActionableErr) *ErrDef ", "output": "{\n\treturn &ErrDef{\n\t\terr: err,\n\t\tae: ae,\n\t}\n}"} {"input": "package jobs\n\nimport (\n\t\"sync\"\n\n\tl4g \"github.com/alecthomas/log4go\"\n\tejobs \"github.com/mattermost/platform/einterfaces/jobs\"\n\t\"github.com/mattermost/platform/model\"\n\t\"github.com/mattermost/platform/store\"\n\t\"github.com/mattermost/platform/utils\"\n)\n\ntype Jobs struct {\n\tstartOnce sync.Once\n\n\tDataRetention model.Job\n\n\tlistenerId string\n}\n\n\n\nfunc (jobs *Jobs) Start() *Jobs {\n\tl4g.Info(\"Starting jobs\")\n\n\tjobs.startOnce.Do(func() {\n\t\tif jobs.DataRetention != nil && *utils.Cfg.DataRetentionSettings.Enable {\n\t\t\tgo jobs.DataRetention.Run()\n\t\t}\n\n\t})\n\n\tjobs.listenerId = utils.AddConfigListener(jobs.handleConfigChange)\n\n\treturn jobs\n}\n\nfunc (jobs *Jobs) handleConfigChange(oldConfig *model.Config, newConfig *model.Config) {\n\tif jobs.DataRetention != nil {\n\t\tif !*oldConfig.DataRetentionSettings.Enable && *newConfig.DataRetentionSettings.Enable {\n\t\t\tgo jobs.DataRetention.Run()\n\t\t} else if *oldConfig.DataRetentionSettings.Enable && !*newConfig.DataRetentionSettings.Enable {\n\t\t\tjobs.DataRetention.Stop()\n\t\t}\n\t}\n}\n\nfunc (jobs *Jobs) Stop() *Jobs {\n\tutils.RemoveConfigListener(jobs.listenerId)\n\n\tif jobs.DataRetention != nil && *utils.Cfg.DataRetentionSettings.Enable {\n\t\tjobs.DataRetention.Stop()\n\t}\n\n\tl4g.Info(\"Stopped jobs\")\n\n\treturn jobs\n}\n\nfunc InitJobs(s store.Store) *Jobs ", "output": "{\n\tjobs := &Jobs{\n\t}\n\n\tif dataRetentionInterface := ejobs.GetDataRetentionInterface(); dataRetentionInterface != nil {\n\t\tjobs.DataRetention = dataRetentionInterface.MakeJob(s)\n\t}\n\n\treturn jobs\n}"} {"input": "package testing\n\nimport \"k8s.io/kubernetes/pkg/util/iptables\"\n\n\ntype fake struct{}\n\nfunc NewFake() *fake {\n\treturn &fake{}\n}\n\n\n\nfunc (*fake) FlushChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) DeleteChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) EnsureRule(position iptables.RulePosition, table iptables.Table, chain iptables.Chain, args ...string) (bool, error) {\n\treturn true, nil\n}\n\nfunc (*fake) DeleteRule(table iptables.Table, chain iptables.Chain, args ...string) error {\n\treturn nil\n}\n\nfunc (*fake) IsIpv6() bool {\n\treturn false\n}\n\nfunc (*fake) Save(table iptables.Table) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\nfunc (*fake) SaveAll() ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\nfunc (*fake) Restore(table iptables.Table, data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\n\nfunc (*fake) RestoreAll(data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\nfunc (*fake) AddReloadFunc(reloadFunc func()) {}\n\nfunc (*fake) Destroy() {}\n\nvar _ = iptables.Interface(&fake{})\n\nfunc (*fake) EnsureChain(table iptables.Table, chain iptables.Chain) (bool, error) ", "output": "{\n\treturn true, nil\n}"} {"input": "package nl\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\ntype RtMsg struct {\n\tsyscall.RtMsg\n}\n\nfunc NewRtMsg() *RtMsg {\n\treturn &RtMsg{\n\t\tRtMsg: syscall.RtMsg{\n\t\t\tTable: syscall.RT_TABLE_MAIN,\n\t\t\tScope: syscall.RT_SCOPE_UNIVERSE,\n\t\t\tProtocol: syscall.RTPROT_BOOT,\n\t\t\tType: syscall.RTN_UNICAST,\n\t\t},\n\t}\n}\n\nfunc NewRtDelMsg() *RtMsg {\n\treturn &RtMsg{\n\t\tRtMsg: syscall.RtMsg{\n\t\t\tTable: syscall.RT_TABLE_MAIN,\n\t\t\tScope: syscall.RT_SCOPE_NOWHERE,\n\t\t},\n\t}\n}\n\nfunc (msg *RtMsg) Len() int {\n\treturn syscall.SizeofRtMsg\n}\n\n\n\nfunc (msg *RtMsg) Serialize() []byte {\n\treturn (*(*[syscall.SizeofRtMsg]byte)(unsafe.Pointer(msg)))[:]\n}\n\ntype RtNexthop struct {\n\tsyscall.RtNexthop\n}\n\nfunc DeserializeRtNexthop(b []byte) *RtNexthop {\n\treturn (*RtNexthop)(unsafe.Pointer(&b[0:syscall.SizeofRtNexthop][0]))\n}\n\nfunc (msg *RtNexthop) Serialize() []byte {\n\treturn (*(*[syscall.SizeofRtNexthop]byte)(unsafe.Pointer(msg)))[:]\n}\n\nfunc DeserializeRtMsg(b []byte) *RtMsg ", "output": "{\n\treturn (*RtMsg)(unsafe.Pointer(&b[0:syscall.SizeofRtMsg][0]))\n}"} {"input": "package fake\n\nimport (\n\tclientset \"github.com/openshift/origin/pkg/image/generated/clientset\"\n\timagev1 \"github.com/openshift/origin/pkg/image/generated/clientset/typed/image/v1\"\n\tfakeimagev1 \"github.com/openshift/origin/pkg/image/generated/clientset/typed/image/v1/fake\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/watch\"\n\t\"k8s.io/client-go/discovery\"\n\tfakediscovery \"k8s.io/client-go/discovery/fake\"\n\t\"k8s.io/client-go/testing\"\n)\n\n\n\n\n\nfunc NewSimpleClientset(objects ...runtime.Object) *Clientset {\n\to := testing.NewObjectTracker(registry, scheme, codecs.UniversalDecoder())\n\tfor _, obj := range objects {\n\t\tif err := o.Add(obj); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tfakePtr := testing.Fake{}\n\tfakePtr.AddReactor(\"*\", \"*\", testing.ObjectReaction(o, registry.RESTMapper()))\n\n\tfakePtr.AddWatchReactor(\"*\", testing.DefaultWatchReactor(watch.NewFake(), nil))\n\n\treturn &Clientset{fakePtr}\n}\n\n\n\n\ntype Clientset struct {\n\ttesting.Fake\n}\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\treturn &fakediscovery.FakeDiscovery{Fake: &c.Fake}\n}\n\nvar _ clientset.Interface = &Clientset{}\n\n\n\n\n\nfunc (c *Clientset) Image() imagev1.ImageV1Interface {\n\treturn &fakeimagev1.FakeImageV1{Fake: &c.Fake}\n}\n\nfunc (c *Clientset) ImageV1() imagev1.ImageV1Interface ", "output": "{\n\treturn &fakeimagev1.FakeImageV1{Fake: &c.Fake}\n}"} {"input": "package inmem\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\tplatform \"github.com/influxdata/influxdb\"\n\tplatformtesting \"github.com/influxdata/influxdb/testing\"\n)\n\n\n\nfunc TestTelegrafStore(t *testing.T) {\n\tplatformtesting.TelegrafConfigStore(initTelegrafStore, t)\n}\n\nfunc initTelegrafStore(f platformtesting.TelegrafConfigFields, t *testing.T) (platform.TelegrafConfigStore, func()) ", "output": "{\n\ts := NewService()\n\ts.IDGenerator = f.IDGenerator\n\tctx := context.Background()\n\tfor _, m := range f.UserResourceMappings {\n\t\tif err := s.PutUserResourceMapping(ctx, m); err != nil {\n\t\t\tt.Fatalf(\"failed to populate user resource mapping\")\n\t\t}\n\t}\n\tfor _, tc := range f.TelegrafConfigs {\n\t\tif err := s.putTelegrafConfig(ctx, tc); err != nil {\n\t\t\tt.Fatalf(\"failed to populate telegraf configs\")\n\t\t}\n\t}\n\treturn s, func() {}\n}"} {"input": "package pusher\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"strings\"\n)\n\nfunc hmacSignature(toSign, secret string) string {\n\treturn hex.EncodeToString(hmacBytes([]byte(toSign), []byte(secret)))\n}\n\n\n\nfunc createAuthString(key, secret, stringToSign string) string {\n\tauthSignature := hmacSignature(stringToSign, secret)\n\treturn strings.Join([]string{key, authSignature}, \":\")\n}\n\nfunc hmacBytes(toSign, secret []byte) []byte ", "output": "{\n\t_authSignature := hmac.New(sha256.New, secret)\n\t_authSignature.Write(toSign)\n\treturn _authSignature.Sum(nil)\n}"} {"input": "package charm\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n)\n\n\n\ntype Charm interface {\n\tMeta() *Meta\n\tConfig() *Config\n\tRevision() int\n}\n\n\n\n\n\n\n\nfunc InferRepository(curl *URL, localRepoPath string) (repo Repository, err error) {\n\tswitch curl.Schema {\n\tcase \"cs\":\n\t\trepo = Store()\n\tcase \"local\":\n\t\tif localRepoPath == \"\" {\n\t\t\treturn nil, errors.New(\"path to local repository not specified\")\n\t\t}\n\t\trepo = &LocalRepository{localRepoPath}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown schema for charm URL %q\", curl)\n\t}\n\treturn\n}\n\nfunc Read(path string) (Charm, error) ", "output": "{\n\tinfo, err := os.Stat(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif info.IsDir() {\n\t\treturn ReadDir(path)\n\t}\n\treturn ReadBundle(path)\n}"} {"input": "package objectsTestUtil\n\nimport (\n\t\"github.com/eu271/Soulog/Blog/objects\"\n\t\"testing\"\n)\n\ntype TestPostBuilder interface {\n\tsoul.PostBuilder\n\tWithParagraphs(int) TestPostBuilder\n\tWithRandomTitle() TestPostBuilder\n\tBefore(*soul.Post) TestPostBuilder\n\tAfter(*soul.Post) TestPostBuilder\n\tFillWithRandom() TestPostBuilder\n}\n\n\n\nfunc AssertEquals(post, post1 *soul.Post, t *testing.T) {\n\n\tif post.Id != post1.Id {\n\t\tt.Error(\"Posts ids not equals: \" + post.Id + \" \" + post1.Id)\n\t}\n\n\tif post.Permalink != post1.Permalink {\n\t\tt.Error(\"Posts permalins not equals: \" + post.Permalink + \" \" + post1.Permalink)\n\t}\n\n}\n\nfunc NewTestPostBuilder() *TestPostBuilder ", "output": "{\n\tvar post *soul.Post\n\tvar err error\n\n\tpost, err = soul.NewPostBuilder().\n\t\tId(\"asdasd\").\n\t\tPermalink(\"asdasdasd\").\n\t\tTitle(\"asdasda\").\n\t\tSlug(\"asasd\").\n\t\tContent(\"asdasdasdasd\").\n\t\tState(\"publish\").\n\t\tBuild()\n\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tif post == nil {\n\t\tpanic(\"Post es nil\")\n\t}\n\n\treturn &TestPostBuilder{}\n\n}"} {"input": "package user\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n\ntype RangeList []*Range\n\n\nfunc ParseRangeList(str string) (*RangeList, error) {\n\trl := RangeList{}\n\tif len(str) == 0 {\n\t\treturn &rl, nil\n\t}\n\tparts := strings.Split(str, \",\")\n\tfor _, p := range parts {\n\t\tr, err := ParseRange(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trl = append(rl, r)\n\t}\n\treturn &rl, nil\n}\n\n\nfunc (l *RangeList) Empty() bool {\n\tif len(*l) == 0 {\n\t\treturn true\n\t}\n\tfor _, r := range *l {\n\t\tif !r.Empty() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (l *RangeList) Contains(uid int) bool {\n\tfor _, r := range *l {\n\t\tif r.Contains(uid) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (l *RangeList) Type() string {\n\treturn \"user.RangeList\"\n}\n\n\n\n\n\nfunc (l *RangeList) String() string {\n\trangeStrings := []string{}\n\tfor _, r := range *l {\n\t\trangeStrings = append(rangeStrings, r.String())\n\t}\n\treturn strings.Join(rangeStrings, \",\")\n}\n\n\n\nfunc IsUserAllowed(user string, allowed *RangeList) bool {\n\tuid, err := strconv.Atoi(user)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn allowed.Contains(uid)\n}\n\nfunc (l *RangeList) Set(value string) error ", "output": "{\n\tnewRangeList, err := ParseRangeList(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*l = *newRangeList\n\treturn nil\n}"} {"input": "package utils\n\nimport (\n\t\"github.com/goincremental/negroni-sessions\"\n\t\"net/http\"\n)\n\ntype SessionManager interface {\n\tGet(*http.Request, string) string\n\tSet(*http.Request, string, string)\n\tDelete(*http.Request, string)\n}\n\ntype SessionManagerImpl struct {\n}\n\n\n\nfunc (sa *SessionManagerImpl) Get(req *http.Request, key string) string {\n\tif val := sessions.GetSession(req).Get(key); val != nil {\n\t\treturn val.(string)\n\t}\n\n\treturn \"\"\n}\n\nfunc (sa *SessionManagerImpl) Set(req *http.Request, key, value string) {\n\tsessions.GetSession(req).Set(key, value)\n}\n\nfunc (sa *SessionManagerImpl) Delete(req *http.Request, key string) {\n\tsessions.GetSession(req).Delete(key)\n}\n\nfunc NewSessionManager() *SessionManagerImpl ", "output": "{\n\treturn &SessionManagerImpl{}\n}"} {"input": "package kthlargest\n\nimport \"container/heap\"\n\ntype MaxHeap struct {\n\tSize int\n\tNums []int\n}\n\nfunc (h *MaxHeap) Insert(x int) {\n\tif h.Len() < h.Size {\n\t\theap.Push(h, x)\n\t} else if h.Nums[0] < x {\n\t\th.Nums[0] = x\n\t\theap.Fix(h, 0)\n\t}\n}\n\nfunc (h *MaxHeap) Len() int { return len(h.Nums) }\n\nfunc (h *MaxHeap) Less(i, j int) bool {\n\treturn h.Nums[i] < h.Nums[j]\n}\n\n\n\nfunc (h *MaxHeap) Push(x interface{}) {\n\th.Nums = append(h.Nums, x.(int))\n}\n\nfunc (h *MaxHeap) Pop() interface{} {\n\tn := len(h.Nums)\n\tx := h.Nums[n-1]\n\th.Nums = h.Nums[:n-1]\n\treturn x\n}\n\nfunc findKthLargest(nums []int, k int) int {\n\th := &MaxHeap{Size: k}\n\tfor _, num := range nums {\n\t\th.Insert(num)\n\t}\n\treturn h.Nums[0]\n}\n\nfunc (h *MaxHeap) Swap(i, j int) ", "output": "{\n\th.Nums[i], h.Nums[j] = h.Nums[j], h.Nums[i]\n}"} {"input": "package main\n\n\n\nfunc eval(a int, b int, sym string) int {\n\tswitch sym {\n\tcase \"+\":\n\t\treturn a + b\n\tcase \"*\":\n\t\treturn a * b\n\tcase \"/\":\n\t\treturn a / b\n\tcase \"-\":\n\t\treturn a - b\n\t}\n\treturn 0\n}\n\nfunc evalRPN(tokens []string) int ", "output": "{\n\tstack := []int{}\n\tfor _, t := range tokens {\n\t\tif !strings.Contains(\"*+/-\", t) {\n\t\t\tx, _ := strconv.Atoi(t)\n\t\t\tstack = append(stack, x)\n\t\t} else {\n\t\t\ta := stack[len(stack)-2]\n\t\t\tb := stack[len(stack)-1]\n\t\t\tstack = stack[:len(stack)-2]\n\t\t\tstack = append(stack, eval(a, b, t))\n\t\t}\n\t}\n\treturn stack[0]\n}"} {"input": "package options\n\n\ntype UpdateOptions struct {\n\tArrayFilters *ArrayFilters\n\n\tBypassDocumentValidation *bool\n\n\tCollation *Collation\n\n\tHint interface{}\n\n\tUpsert *bool\n}\n\n\n\n\n\nfunc (uo *UpdateOptions) SetArrayFilters(af ArrayFilters) *UpdateOptions {\n\tuo.ArrayFilters = &af\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetBypassDocumentValidation(b bool) *UpdateOptions {\n\tuo.BypassDocumentValidation = &b\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetCollation(c *Collation) *UpdateOptions {\n\tuo.Collation = c\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetHint(h interface{}) *UpdateOptions {\n\tuo.Hint = h\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetUpsert(b bool) *UpdateOptions {\n\tuo.Upsert = &b\n\treturn uo\n}\n\n\nfunc MergeUpdateOptions(opts ...*UpdateOptions) *UpdateOptions {\n\tuOpts := Update()\n\tfor _, uo := range opts {\n\t\tif uo == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif uo.ArrayFilters != nil {\n\t\t\tuOpts.ArrayFilters = uo.ArrayFilters\n\t\t}\n\t\tif uo.BypassDocumentValidation != nil {\n\t\t\tuOpts.BypassDocumentValidation = uo.BypassDocumentValidation\n\t\t}\n\t\tif uo.Collation != nil {\n\t\t\tuOpts.Collation = uo.Collation\n\t\t}\n\t\tif uo.Hint != nil {\n\t\t\tuOpts.Hint = uo.Hint\n\t\t}\n\t\tif uo.Upsert != nil {\n\t\t\tuOpts.Upsert = uo.Upsert\n\t\t}\n\t}\n\n\treturn uOpts\n}\n\nfunc Update() *UpdateOptions ", "output": "{\n\treturn &UpdateOptions{}\n}"} {"input": "package crc32\n\n\n\nfunc updateCastagnoli(crc uint32, p []byte) uint32 {\n\tif len(p) >= 16 {\n\t\treturn updateSlicingBy8(crc, castagnoliTable8, p)\n\t}\n\treturn update(crc, castagnoliTable, p)\n}\n\n\n\nfunc updateIEEE(crc uint32, p []byte) uint32 ", "output": "{\n\tif len(p) >= 16 {\n\t\tiEEETable8Once.Do(func() {\n\t\t\tiEEETable8 = makeTable8(IEEE)\n\t\t})\n\t\treturn updateSlicingBy8(crc, iEEETable8, p)\n\t}\n\treturn update(crc, IEEETable, p)\n}"} {"input": "package v2alpha1\n\nimport (\n\t\"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util\"\n\tnext \"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/v2alpha2\"\n\tpkgutil \"github.com/GoogleContainerTools/skaffold/pkg/skaffold/util\"\n)\n\n\n\n\n\n\n\nfunc (c *SkaffoldConfig) Upgrade() (util.VersionedConfig, error) {\n\tvar newConfig next.SkaffoldConfig\n\tpkgutil.CloneThroughJSON(c, &newConfig)\n\tnewConfig.APIVersion = next.Version\n\n\terr := util.UpgradePipelines(c, &newConfig, upgradeOnePipeline)\n\treturn &newConfig, err\n}\n\n\n\n\nfunc upgradeOnePipeline(oldPipeline, newPipeline interface{}) error ", "output": "{\n\toldBuild := &oldPipeline.(*Pipeline).Build\n\tnewBuild := &newPipeline.(*next.Pipeline).Build\n\n\tfor i, newArtifact := range newBuild.Artifacts {\n\t\toldArtifact := oldBuild.Artifacts[i]\n\n\t\tkaniko := oldArtifact.KanikoArtifact\n\t\tif kaniko == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tbuildContext := kaniko.BuildContext\n\t\tif buildContext == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif buildContext.LocalDir != nil {\n\t\t\tnewArtifact.KanikoArtifact.InitImage = buildContext.LocalDir.InitImage\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package parsex\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype ParsexError struct {\n\tPos int\n\tMessage string\n}\n\nfunc (err ParsexError) Error() string {\n\treturn fmt.Sprintf(\"pos %d :\\n%s\",\n\t\terr.Pos, err.Message)\n}\n\ntype ParsexState interface {\n\tNext(pred func(int, interface{}) (interface{}, error)) (x interface{}, err error)\n\tPos() int\n\tSeekTo(int)\n\tTrap(message string, args ...interface{}) error\n}\n\ntype StateInMemory struct {\n\tbuffer []interface{}\n\tpos int\n}\n\nfunc NewStateInMemory(buffer []interface{}) *StateInMemory {\n\treturn &StateInMemory{buffer, 0}\n}\n\nfunc (this *StateInMemory) Next(pred func(int, interface{}) (interface{}, error)) (x interface{}, err error) {\n\tbuffer := (*this).buffer\n\tif (*this).pos < len(buffer) {\n\t\tx := buffer[(*this).pos]\n\t\toutput, err := pred((*this).pos, x)\n\t\tif err == nil {\n\t\t\t(*this).pos++\n\t\t\treturn output, nil\n\t\t} else {\n\t\t\treturn x, err\n\t\t}\n\t} else {\n\t\treturn nil, io.EOF\n\t}\n}\n\n\n\nfunc (this *StateInMemory) SeekTo(pos int) {\n\tend := len((*this).buffer)\n\tif pos < 0 || pos > end {\n\t\tmessage := fmt.Sprintf(\"%d out range [0, %d]\", pos, end)\n\t\tpanic(errors.New(message))\n\t}\n\t(*this).pos = pos\n}\n\nfunc (this *StateInMemory) Trap(message string, args ...interface{}) error {\n\treturn ParsexError{(*this).pos,\n\t\tfmt.Sprintf(message, args...)}\n}\n\nfunc (this *StateInMemory) Pos() int ", "output": "{\n\treturn (*this).pos\n}"} {"input": "package yarn_client\n\nimport (\n\t\"github.com/hortonworks/gohadoop/hadoop_yarn\"\n)\n\ntype AMNMClient struct {\n\tclient hadoop_yarn.ContainerManagementProtocolService\n}\n\nfunc CreateAMNMClient(host string, port int) (*AMNMClient, error) {\n\tc, err := hadoop_yarn.DialContainerManagementProtocolService(host, port)\n\treturn &AMNMClient{client: c}, err\n}\n\n\n\nfunc (c *AMNMClient) StartContainer(container *hadoop_yarn.ContainerProto, containerLaunchContext *hadoop_yarn.ContainerLaunchContextProto) error ", "output": "{\n\trequest := hadoop_yarn.StartContainersRequestProto{StartContainerRequest: []*hadoop_yarn.StartContainerRequestProto{&hadoop_yarn.StartContainerRequestProto{ContainerLaunchContext: containerLaunchContext, Container: container, ContainerToken: container.GetContainerToken()}}}\n\tresponse := hadoop_yarn.StartContainersResponseProto{}\n\treturn c.client.StartContainers(&request, &response)\n}"} {"input": "package multiraft\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cockroachdb/cockroach/util\"\n)\n\n\n\n\ntype eventDemux struct {\n\tLeaderElection chan *EventLeaderElection\n\tCommandCommitted chan *EventCommandCommitted\n\tMembershipChangeCommitted chan *EventMembershipChangeCommitted\n\n\tevents <-chan interface{}\n\tstopper *util.Stopper\n}\n\n\n\nfunc (e *eventDemux) start() {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-e.events:\n\t\t\t\tswitch event := event.(type) {\n\t\t\t\tcase *EventLeaderElection:\n\t\t\t\t\te.LeaderElection <- event\n\n\t\t\t\tcase *EventCommandCommitted:\n\t\t\t\t\te.CommandCommitted <- event\n\n\t\t\t\tcase *EventMembershipChangeCommitted:\n\t\t\t\t\te.MembershipChangeCommitted <- event\n\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(fmt.Sprintf(\"got unknown event type %T\", event))\n\t\t\t\t}\n\n\t\t\tcase <-e.stopper.ShouldStop():\n\t\t\t\te.stopper.SetStopped()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (e *eventDemux) stop() {\n\te.stopper.Stop()\n\tclose(e.CommandCommitted)\n\tclose(e.MembershipChangeCommitted)\n\tclose(e.LeaderElection)\n}\n\nfunc newEventDemux(events <-chan interface{}) *eventDemux ", "output": "{\n\treturn &eventDemux{\n\t\tmake(chan *EventLeaderElection, 1000),\n\t\tmake(chan *EventCommandCommitted, 1000),\n\t\tmake(chan *EventMembershipChangeCommitted, 1000),\n\t\tevents,\n\t\tutil.NewStopper(1),\n\t}\n}"} {"input": "package objectstorage\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\ntype WorkRequestLogEntry struct {\n\n\tMessage *string `mandatory:\"false\" json:\"message\"`\n\n\tTimestamp *common.SDKTime `mandatory:\"false\" json:\"timestamp\"`\n}\n\n\n\nfunc (m WorkRequestLogEntry) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package configuration\n\nimport (\n\t\"testing\"\n\n\t\"k8s.io/api/admissionregistration/v1alpha1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n)\n\ntype disabledMutatingWebhookConfigLister struct{}\n\n\nfunc TestMutatingWebhookConfigDisabled(t *testing.T) {\n\tmanager := NewMutatingWebhookConfigurationManager(&disabledMutatingWebhookConfigLister{})\n\tmanager.sync()\n\t_, err := manager.Webhooks()\n\tif err.Error() != ErrDisabled.Error() {\n\t\tt.Errorf(\"expected %v, got %v\", ErrDisabled, err)\n\t}\n}\n\nfunc (l *disabledMutatingWebhookConfigLister) List(options metav1.ListOptions) (*v1alpha1.MutatingWebhookConfigurationList, error) ", "output": "{\n\treturn nil, errors.NewNotFound(schema.GroupResource{Group: \"admissionregistration\", Resource: \"MutatingWebhookConfigurations\"}, \"\")\n}"} {"input": "package remotecontext \n\nimport (\n\t\"archive/tar\"\n\t\"crypto/sha256\"\n\t\"hash\"\n\t\"os\"\n\n\t\"github.com/tiborvass/docker/pkg/archive\"\n\t\"github.com/tiborvass/docker/pkg/tarsum\"\n)\n\n\nfunc NewFileHash(path, name string, fi os.FileInfo) (hash.Hash, error) {\n\tvar link string\n\tif fi.Mode()&os.ModeSymlink != 0 {\n\t\tvar err error\n\t\tlink, err = os.Readlink(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\thdr, err := archive.FileInfoHeader(name, fi, link)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := archive.ReadSecurityXattrToTarHeader(path, hdr); err != nil {\n\t\treturn nil, err\n\t}\n\ttsh := &tarsumHash{hdr: hdr, Hash: sha256.New()}\n\ttsh.Reset() \n\treturn tsh, nil\n}\n\ntype tarsumHash struct {\n\thash.Hash\n\thdr *tar.Header\n}\n\n\n\n\nfunc (tsh *tarsumHash) Reset() ", "output": "{\n\ttsh.Hash.Reset()\n\ttarsum.WriteV1Header(tsh.hdr, tsh.Hash)\n}"} {"input": "package data\n\nimport (\n\t\"github.com/raincious/trap/trap/core/types\"\n)\n\ntype HelloConflict struct {\n\tBase\n\n\tConfilct types.IPAddresses\n}\n\n\n\nfunc (d *HelloConflict) Build() ([][]byte, *types.Throw) {\n\tipByte, cIPErr := d.Confilct.Serialize()\n\n\tif cIPErr != nil {\n\t\treturn [][]byte{}, cIPErr\n\t}\n\n\treturn [][]byte{\n\t\tipByte,\n\t}, nil\n}\n\nfunc (d *HelloConflict) Parse(msg [][]byte) *types.Throw ", "output": "{\n\tverifyErr := d.Verify(msg, 1)\n\n\tif verifyErr != nil {\n\t\treturn verifyErr\n\t}\n\n\tconnectedErr := d.Confilct.Unserialize(msg[0])\n\n\tif connectedErr != nil {\n\t\treturn connectedErr\n\t}\n\n\treturn nil\n}"} {"input": "package funcs\n\nimport (\n\t\"github.com/gaochao1/sw\"\n\t\"github.com/gaochao1/swcollector/g\"\n\t\"github.com/open-falcon/common/model\"\n\t\"log\"\n\t\"time\"\n)\n\ntype SwCpu struct {\n\tIp string\n\tCpuUtil int\n}\n\n\n\nfunc cpuMetrics(ip string, ch chan SwCpu) {\n\tvar swCpu SwCpu\n\n\tcpuUtili, err := sw.CpuUtilization(ip, g.Config().Switch.Community, g.Config().Switch.SnmpTimeout, g.Config().Switch.SnmpRetry)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tswCpu.Ip = ip\n\tswCpu.CpuUtil = cpuUtili\n\tch <- swCpu\n\n\treturn\n}\n\nfunc CpuMetrics() (L []*model.MetricValue) ", "output": "{\n\n\tchs := make([]chan SwCpu, len(AliveIp))\n\tfor i, ip := range AliveIp {\n\t\tif ip != \"\" {\n\t\t\tchs[i] = make(chan SwCpu)\n\t\t\tgo cpuMetrics(ip, chs[i])\n\t\t}\n\t}\n\n\tfor _, ch := range chs {\n\t\tswCpu := <-ch\n\t\tL = append(L, GaugeValueIp(time.Now().Unix(), swCpu.Ip, \"switch.CpuUtilization\", swCpu.CpuUtil))\n\t}\n\n\treturn L\n}"} {"input": "package elasticsearch_test\n\nimport (\n\t\"crypto/tls\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/elastic/go-elasticsearch/v7\"\n\t\"github.com/elastic/go-elasticsearch/v7/estransport\"\n)\n\nfunc init() {\n\tlog.SetFlags(0)\n}\n\nfunc ExampleNewDefaultClient() {\n\tes, err := elasticsearch.NewDefaultClient()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error creating the client: %s\\n\", err)\n\t}\n\n\tres, err := es.Info()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error getting the response: %s\\n\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tlog.Print(es.Transport.(*estransport.Client).URLs())\n}\n\n\n\nfunc ExampleNewClient_logger() {\n\n\n\tcfg := elasticsearch.Config{\n\t\tLogger: &estransport.ColorLogger{Output: os.Stdout},\n\t}\n\n\telasticsearch.NewClient(cfg)\n}\n\nfunc ExampleNewClient() ", "output": "{\n\tcfg := elasticsearch.Config{\n\t\tAddresses: []string{\n\t\t\t\"http:localhost:9200\",\n\t\t},\n\t\tUsername: \"foo\",\n\t\tPassword: \"bar\",\n\t\tTransport: &http.Transport{\n\t\t\tMaxIdleConnsPerHost: 10,\n\t\t\tResponseHeaderTimeout: time.Second,\n\t\t\tDialContext: (&net.Dialer{Timeout: time.Second}).DialContext,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tMinVersion: tls.VersionTLS11,\n\t\t\t},\n\t\t},\n\t}\n\n\tes, _ := elasticsearch.NewClient(cfg)\n\tlog.Print(es.Transport.(*estransport.Client).URLs())\n}"} {"input": "package goopencc\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tZH2TW = \"s2twp.json\"\n\tTW2ZH = \"tw2sp.json\"\n)\n\nfunc Zh2Tw(v string) (string, int) {\n\tv = strings.Trim(v, \" \")\n\tif v == \"\" {\n\t\treturn v, 200\n\t}\n\treturn translate(v, ZH2TW)\n}\n\nfunc Tw2Zh(v string) (string, int) {\n\tv = strings.Trim(v, \" \")\n\tif v == \"\" {\n\t\treturn v, 200\n\t}\n\treturn translate(v, TW2ZH)\n}\n\n\n\nfunc translate(v string, m string) (string, int) ", "output": "{\n\tapiUrl := \"http://opencc.byvoid.com/convert\"\n\tdata := url.Values{}\n\tdata.Set(\"text\", v)\n\tdata.Add(\"config\", m)\n\tdata.Add(\"precise\", \"0\")\n\n\tclient := &http.Client{}\n\tr, _ := http.NewRequest(\"POST\", apiUrl, bytes.NewBuffer([]byte(data.Encode())))\n\tr.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\tr.Header.Add(\"Content-Length\", strconv.Itoa(len(data.Encode())))\n\n\tresp, _ := client.Do(r)\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\treturn buf.String(), resp.StatusCode\n}"} {"input": "package http_auth\n\nimport \"crypto/rand\"\nimport \"fmt\"\nimport \"sync\"\nimport \"time\"\n\ntype Server struct {\n\tsync.Mutex\n\tAuthFun func(user, realm string) string\n\topaque string\n\tRealm string\n\tReaperWaitSeconds, ReapTTLSeconds int\n\trequests map[string]*reqState\n}\ntype reqState struct {\n\tnreq int\n\tsectime int64\n}\n\n\n\nfunc newNonce() string {\n\tb := make([]byte, 8)\n\tn, e := rand.Read(b)\n\tif n != 8 || e != nil {\n\t\tpanic(\"rand.Reader failed!\")\n\t}\n\treturn fmt.Sprintf(\"%x\", b)\n}\n\nfunc reaper(s *Server) {\n\tfor {\n\t\ttime.Sleep(time.Duration(s.ReaperWaitSeconds) * time.Second)\n\t\tdo_reap(s)\n\t}\n}\n\nfunc do_reap(s *Server) {\n\tnow := time.Now().UnixNano()\n\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tfor k, v := range s.requests {\n\t\tif v.sectime+int64(s.ReapTTLSeconds) < now {\n\t\t\tdelete(s.requests, k)\n\t\t}\n\t}\n}\n\nfunc newServer(realm string, authfun func(user, realm string) string) *Server ", "output": "{\n\ts := new(Server)\n\ts.Realm = realm\n\ts.opaque = newNonce()\n\ts.AuthFun = authfun\n\ts.requests = map[string]*reqState{}\n\ts.ReaperWaitSeconds = 600\n\ts.ReapTTLSeconds = 3600\n\tgo reaper(s)\n\n\treturn s\n}"} {"input": "package s3\n\nimport (\n\t\"github.com/djbarber/ipfs-hack/Godeps/_workspace/src/github.com/crowdmob/goamz/aws\"\n)\n\nvar originalStrategy = attempts\n\nfunc SetAttemptStrategy(s *aws.AttemptStrategy) {\n\tif s == nil {\n\t\tattempts = originalStrategy\n\t} else {\n\t\tattempts = *s\n\t}\n}\n\nfunc Sign(auth aws.Auth, method, path string, params, headers map[string][]string) {\n\tsign(auth, method, path, params, headers)\n}\n\n\n\nfunc SetListMultiMax(n int) {\n\tlistMultiMax = n\n}\n\nfunc SetListPartsMax(n int) ", "output": "{\n\tlistPartsMax = n\n}"} {"input": "package group\n\nimport (\n\t\"github.com/JanBerktold/rbxweb\"\n\t\"net/url\"\n\t\"strconv\"\n)\n\n\n\n\n\n\nfunc Shout(client *rbxweb.Client, groupID int32, message string) (success bool) {\n\tpage := client.GetURL(`www`, `/My/Groups.aspx`, url.Values{\"gid\": {strconv.FormatInt(int64(groupId), 10)}})\n\terr := client.DoRawPost(page, url.Values{\n\t\t\"ctl00$ctl00$cphRoblox$cphMyRobloxContent$GroupStatusPane$StatusTextBox\": {message},\n\t\t\"ctl00$ctl00$cphRoblox$cphMyRobloxContent$GroupStatusPane$StatusSubmitButton\": {},\n\t\t\"ctl00$ctl00$cphRoblox$cphMyRobloxContent$rbxGroupRoleSetMembersPane$currentRoleSetID\": {},\n\t})\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\n\n\n\n\n\nfunc Wall(client *rbxweb.Client, groupID int32, message string) (success bool) ", "output": "{\n\tpage := client.GetURL(`www`, `/My/Groups.aspx`, url.Values{\"gid\": {strconv.FormatInt(int64(groupID), 10)}})\n\terr := client.DoRawPost(page, url.Values{\n\t\t\"ctl00$ctl00$cphRoblox$cphMyRobloxContent$GroupWallPane$NewPost\": {message},\n\t\t\"ctl00$ctl00$cphRoblox$cphMyRobloxContent$GroupWallPane$NewPostButton\": {},\n\t\t\"ctl00$ctl00$cphRoblox$cphMyRobloxContent$rbxGroupRoleSetMembersPane$currentRoleSetID\": {},\n\t})\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package console\n\nimport (\n\t\"fmt\"\n\t\"github.com/serainville/gologger/logger\"\n\t\"time\"\n)\n\n\n\nfunc ConsoleBasicPrinter(log logger.LogInstance, time time.Time) {\n\tcolor := getColor(log)\n\tcolor.Set()\n\tfmt.Printf(\"[%s] [%s] %s\\n\", log.LogType, time.Format(\"2006-01-02 15:04:05\"), log.Message)\n\tUnset()\n}\n\nfunc getColor(log logger.LogInstance) *Color {\n\tvar color *Color\n\n\tif log.LoggerInit.Location == \"simple\" {\n\t\tcolor = New(Reset)\n\t\treturn color\n\t}\n\n\tswitch log.LogType {\n\tcase \"LOG\":\n\t\tcolor = New(Reset)\n\t\tbreak\n\tcase \"MSG\":\n\t\tcolor = New(FgBlue)\n\t\tbreak\n\tcase \"INF\":\n\t\tcolor = New(FgGreen)\n\t\tbreak\n\tcase \"WRN\":\n\t\tcolor = New(FgMagenta)\n\t\tbreak\n\tcase \"DBG\":\n\t\tcolor = New(FgYellow)\n\t\tbreak\n\tcase \"ERR\":\n\t\tcolor = New(FgRed)\n\t\tbreak\n\tcase \"RSS\":\n\t\tcolor = New(Reset)\n\t\tbreak\n\tdefault:\n\t\tcolor = New(Reset)\n\t\tbreak\n\t}\n\treturn color\n}\n\nfunc ConsolePrinter(log logger.LogInstance, packageName string, fileName string, lineNumber int, funcName string, time time.Time) ", "output": "{\n\tcolor := getColor(log)\n\tcolor.Set()\n\tfmt.Printf(\"[%s] [%s] [%s::%s::%s] [%d] %s\\n\", log.LogType, time.Format(\"2006-01-02 15:04:05\"), packageName, fileName, funcName, lineNumber, log.Message)\n\tUnset()\n}"} {"input": "package hash\n\nimport \"unsafe\"\n\nconst DJBInit uint32 = 5381\n\nfunc DJBCombine(acc, h uint32) uint32 {\n\treturn mul33(acc) + h\n}\n\nfunc DJB(hs ...uint32) uint32 {\n\tacc := DJBInit\n\tfor _, h := range hs {\n\t\tacc = DJBCombine(acc, h)\n\t}\n\treturn acc\n}\n\n\n\nfunc UInt64(u uint64) uint32 {\n\treturn mul33(uint32(u>>32)) + uint32(u&0xffffffff)\n}\n\nfunc Pointer(p unsafe.Pointer) uint32 {\n\tswitch unsafe.Sizeof(p) {\n\tcase 4:\n\t\treturn UInt32(uint32(uintptr(p)))\n\tcase 8:\n\t\treturn UInt64(uint64(uintptr(p)))\n\tdefault:\n\t\tpanic(\"unhandled pointer size\")\n\t}\n}\n\nfunc UIntPtr(p uintptr) uint32 {\n\tswitch unsafe.Sizeof(p) {\n\tcase 4:\n\t\treturn UInt32(uint32(p))\n\tcase 8:\n\t\treturn UInt64(uint64(p))\n\tdefault:\n\t\tpanic(\"unhandled pointer size\")\n\t}\n}\n\nfunc String(s string) uint32 {\n\th := DJBInit\n\tfor i := 0; i < len(s); i++ {\n\t\th = DJBCombine(h, uint32(s[i]))\n\t}\n\treturn h\n}\n\nfunc mul33(u uint32) uint32 {\n\treturn u<<5 + u\n}\n\nfunc UInt32(u uint32) uint32 ", "output": "{\n\treturn u\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\tprompt \"github.com/c-bata/go-prompt\"\n)\n\n\n\nfunc main() {\n\tin := prompt.Input(\">>> \", completer,\n\t\tprompt.OptionTitle(\"sql-prompt\"),\n\t\tprompt.OptionHistory([]string{\"SELECT * FROM users;\"}),\n\t\tprompt.OptionPrefixTextColor(prompt.Yellow),\n\t\tprompt.OptionPreviewSuggestionTextColor(prompt.Blue),\n\t\tprompt.OptionSelectedSuggestionBGColor(prompt.LightGray),\n\t\tprompt.OptionSuggestionBGColor(prompt.DarkGray))\n\tfmt.Println(\"Your input: \" + in)\n}\n\nfunc completer(in prompt.Document) []prompt.Suggest ", "output": "{\n\ts := []prompt.Suggest{\n\t\t{Text: \"users\", Description: \"Store the username and age\"},\n\t\t{Text: \"articles\", Description: \"Store the article text posted by user\"},\n\t\t{Text: \"comments\", Description: \"Store the text commented to articles\"},\n\t\t{Text: \"groups\", Description: \"Combine users with specific rules\"},\n\t}\n\treturn prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)\n}"} {"input": "package listener\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc testPTree(t *testing.T, strs ...string) {\n\tpt := newPatriciaTreeString(strs...)\n\tfor _, s := range strs {\n\t\tif !pt.match(strings.NewReader(s)) {\n\t\t\tt.Errorf(\"%s is not matched by %s\", s, s)\n\t\t}\n\n\t\tif !pt.matchPrefix(strings.NewReader(s + s)) {\n\t\t\tt.Errorf(\"%s is not matched as a prefix by %s\", s+s, s)\n\t\t}\n\n\t\tif pt.match(strings.NewReader(s + s)) {\n\t\t\tt.Errorf(\"%s matches %s\", s+s, s)\n\t\t}\n\n\t\tpt.matchPrefix(strings.NewReader(s[:len(s)-1]))\n\t\tpt.match(strings.NewReader(s[:len(s)-1]))\n\t\tpt.matchPrefix(strings.NewReader(s + \"$\"))\n\t\tpt.match(strings.NewReader(s + \"$\"))\n\t}\n}\n\n\n\nfunc TestPatriciaNonOverlapping(t *testing.T) {\n\ttestPTree(t, \"foo\", \"bar\", \"dummy\")\n}\n\nfunc TestPatriciaOverlapping(t *testing.T) {\n\ttestPTree(t, \"foo\", \"far\", \"farther\", \"boo\", \"ba\", \"bar\")\n}\n\nfunc TestPatriciaOnePrefix(t *testing.T) ", "output": "{\n\ttestPTree(t, \"prefix\")\n}"} {"input": "package server\n\nimport \"golang.org/x/crypto/bcrypt\"\n\n\nfunc createHashedPassword(password string) (string, error) {\n\thash, err := bcrypt.GenerateFromPassword([]byte(password), 11)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\n\treturn string(hash), err\n}\n\n\n\n\n\nfunc MatchPassword(password string, hashedPassword string) (bool, error) ", "output": "{\n\terr := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn err == nil, err\n}"} {"input": "package gopnsconfig\n\nimport (\n\t\"log\"\n)\n\ntype BaseConfigStruct struct {\n\tPortValue string\n\tMetricsServerValue string\n\tMetricsAPIKeyValue string\n\tMetricsPrefixValue string\n}\n\n\n\nfunc (this *BaseConfigStruct) MetricsAPIKey() string {\n\treturn this.MetricsAPIKeyValue\n}\n\nfunc (this *BaseConfigStruct) MetricsServer() string {\n\treturn this.MetricsServerValue\n}\n\nfunc (this *BaseConfigStruct) MetricsPrefix() string {\n\treturn this.MetricsPrefixValue\n}\n\ntype BaseConfig interface {\n\tPort() string\n\tMetricsServer() string\n\tMetricsAPIKey() string\n\tMetricsPrefix() string\n}\n\nfunc parseBaseConfig(baseConfig *ConfigFile) BaseConfig {\n\tport, err := baseConfig.GetString(\"default\", \"port\")\n\tcheckError(\"Unable to find Server Port\", err)\n\n\tmetricsServer, err := baseConfig.GetString(\"default\", \"metrics-server\")\n\tcheckError(\"Unable to find metrics server\", err)\n\n\tmetricsKey, err := baseConfig.GetString(\"default\", \"metrics-api-key\")\n\tif err != nil {\n\t\tlog.Println(\"Unable to find metrics-api-key using empty string\")\n\t\tmetricsKey = \"\"\n\t}\n\n\tmetricsPrefix, err := baseConfig.GetString(\"default\", \"metrics-prefix\")\n\tif err != nil {\n\t\tlog.Println(\"Unable to find metrics prefix using empty string\")\n\t\tmetricsPrefix = \"\"\n\t}\n\n\tbaseConfigInstance := &BaseConfigStruct{port, metricsServer, metricsKey, metricsPrefix}\n\treturn baseConfigInstance\n\n}\n\nfunc (this *BaseConfigStruct) Port() string ", "output": "{\n\treturn this.PortValue\n}"} {"input": "package osext \n\nimport \"path/filepath\"\n\n\n\n\nfunc Executable() (string, error) {\n\tp, err := executable()\n\treturn filepath.Clean(p), err\n}\n\n\n\n\n\nfunc ExecutableFolder() (string, error) ", "output": "{\n\tp, err := Executable()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfolder, _ := filepath.Split(p)\n\treturn folder, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\tslack \"github.com/mnkd/slackposter\"\n)\n\n\ntype App struct {\n\tChannel string\n\tMessage string\n\tUsername string\n\tIconEmoji string\n\tSlackConfig slack.Config\n}\n\n\n\n\nfunc (app *App) Run() int ", "output": "{\n\tposter := slack.NewSlackPoster(app.SlackConfig)\n\n\tif len(app.Channel) > 0 {\n\t\tposter.Channel = app.Channel\n\t}\n\n\tif len(app.Username) > 0 {\n\t\tposter.Username = app.Username\n\t}\n\n\tif len(app.IconEmoji) > 0 {\n\t\tposter.IconEmoji = app.IconEmoji\n\t}\n\n\terr := poster.PostMessage(app.Message)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\treturn ExitCodeError\n\t}\n\treturn ExitCodeOK\n}"} {"input": "package swagger\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n)\n\nfunc (prop *ModelProperty) setDescription(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"description\"); tag != \"\" {\n\t\tprop.Description = tag\n\t}\n}\n\nfunc (prop *ModelProperty) setDefaultValue(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"default\"); tag != \"\" {\n\t\tprop.DefaultValue = Special(tag)\n\t}\n}\n\nfunc (prop *ModelProperty) setEnumValues(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"enum\"); tag != \"\" {\n\t\tprop.Enum = strings.Split(tag, \"|\")\n\t}\n}\n\n\n\nfunc (prop *ModelProperty) setMinimum(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"minimum\"); tag != \"\" {\n\t\tprop.Minimum = tag\n\t}\n}\n\nfunc (prop *ModelProperty) setUniqueItems(field reflect.StructField) {\n\ttag := field.Tag.Get(\"unique\")\n\tswitch tag {\n\tcase \"true\":\n\t\tv := true\n\t\tprop.UniqueItems = &v\n\tcase \"false\":\n\t\tv := false\n\t\tprop.UniqueItems = &v\n\t}\n}\n\nfunc (prop *ModelProperty) setPropertyMetadata(field reflect.StructField) {\n\tprop.setDescription(field)\n\tprop.setEnumValues(field)\n\tprop.setMinimum(field)\n\tprop.setMaximum(field)\n\tprop.setUniqueItems(field)\n\tprop.setDefaultValue(field)\n}\n\nfunc (prop *ModelProperty) setMaximum(field reflect.StructField) ", "output": "{\n\tif tag := field.Tag.Get(\"maximum\"); tag != \"\" {\n\t\tprop.Maximum = tag\n\t}\n}"} {"input": "package mdr\n\n\n\n\n\nfunc InRangeF64(a, b, c float64) bool {\n\tif a > c { \n\t\ta, c = c, a\n\t}\n\tif b < a {\n\t\treturn false\n\t}\n\tif b > c {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\nfunc RangeLoHiF64Slice(v []float64) (lo, hi float64) {\n\tvlen := len(v)\n\tif vlen <= 0 {\n\t\treturn\n\t}\n\tlo, hi = v[0], v[0]\n\tfor i := 1; i < vlen; i++ {\n\t\tif v[i] < lo {\n\t\t\tlo = v[i]\n\t\t}\n\t\tif v[i] > hi {\n\t\t\thi = v[i]\n\t\t}\n\t}\n\treturn lo, hi\n}\n\n\nfunc ForceRangeF64(a, b, c float64) float64 {\n\tif a > c { \n\t\ta, c = c, a\n\t}\n\tif b < a {\n\t\treturn a\n\t}\n\tif b > c {\n\t\treturn c\n\t}\n\treturn b\n}\n\nfunc AbsF64(a float64) float64 ", "output": "{\n\tif a < 0.0 {\n\t\treturn -a\n\t}\n\treturn a\n}"} {"input": "package invert\n\nimport \"testing\"\n\nvar tests = []struct {\n\tlen int\n\tin, out [][]int\n}{\n\t{\n\t\tlen: 10,\n\t\tin: [][]int{{0, 10}},\n\t\tout: nil,\n\t},\n\t{\n\t\tlen: 10,\n\t\tin: nil,\n\t\tout: [][]int{{0, 10}},\n\t},\n\t{\n\t\tlen: 10,\n\t\tin: [][]int{{0, 5}},\n\t\tout: [][]int{{5, 10}},\n\t},\n\t{\n\t\tlen: 10,\n\t\tin: [][]int{{5, 10}},\n\t\tout: [][]int{{0, 5}},\n\t},\n\t{\n\t\tlen: 10,\n\t\tin: [][]int{{1, 9}},\n\t\tout: [][]int{{0, 1}, {9, 10}},\n\t},\n\t{\n\t\tlen: 10,\n\t\tin: [][]int{{0, 9}},\n\t\tout: [][]int{{9, 10}},\n\t},\n\t{\n\t\tlen: 10,\n\t\tin: [][]int{{1, 10}},\n\t\tout: [][]int{{0, 1}},\n\t},\n\t{\n\t\tlen: 10,\n\t\tin: [][]int{{1, 4}, {6, 9}},\n\t\tout: [][]int{{0, 1}, {4, 6}, {9, 10}},\n\t},\n\t{\n\t\tlen: 10,\n\t\tin: [][]int{{0, 4}, {6, 10}},\n\t\tout: [][]int{{4, 6}},\n\t},\n}\n\n\n\nfunc TestIndicies(t *testing.T) ", "output": "{\n\tfor i, test := range tests {\n\t\tout := Indicies(test.in, test.len)\n\t\tif len(out) != len(test.out) {\n\t\t\tt.Errorf(\"%d: length mismatch got: %d, expected: %d\", i, len(out), test.len)\n\t\t\tcontinue\n\t\t}\n\t\tfor j, p := range test.out {\n\t\t\tq := out[j]\n\t\t\tif len(q) != 2 {\n\t\t\t\tt.Errorf(\"%d: vector %d malformed, got: %v\", i, j, q)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif p[0] != q[0] || p[1] != q[1] {\n\t\t\t\tt.Errorf(\"%d: vector %d expected %v got %v\", i, j, p, q)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package svi\n\nimport (\n\"strings\"\n\"fmt\"\n\"math/rand\"\n\"time\"\n\n\n\"io/ioutil\"\n\"os\"\n)\n\n\n\nfunc Filewriter(filename string, texttowrite []string, directory string) {\n\tfmt.Print(\"Useless function at the moment, .\")\n}\n\n\n\nfunc Filereader(filename string)(lines []string, success int) {\n\tcontent, err := ioutil.ReadFile(filename)\n\tif err == nil {\n\n\t\tlines = strings.Split(string(content), \"\\n\") \n\n\t\tsuccess = 0 \n\t} else {\n\t\tfmt.Println(\"Error opening file (See: svi.go:Filereader() and/or golang's ioutil.ReadFile()\")\n\t\tsuccess = 1 \n\t\tlines[0] = \"!Error\"\n\t}\n\treturn\n}\n\n\n\nfunc filecheck(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\n\nfunc metaread() {\n\n\tdat, err := ioutil.ReadFile(\"Instigator.meta\")\n\tfilecheck(err)\n\tfmt.Print(string(dat))\n\n\tbuf := make([]byte, 1024)\n\n\tinstigator, err := os.Open(\"Instigator.meta\")\n\tfilecheck(err)\n\n\tfor {\n\t\tn, err := instigator.Read(buf)\n\t\tfilecheck(err)\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n}\n\n\n\n\n\n\n\nfunc Random(min, max int)(newnum int) {\nrand.Seed(time.Now().Unix())\nnewnum = rand.Intn(max - min) + min \nreturn\n}\n\nfunc YorN(prompt string) (newinputz string, tf bool) ", "output": "{\n\tinputz := \"Mountain Goat\"\n\ttf = false\n\n\tfor tf != true {\n\t\tfmt.Printf(\"\\n%v [y/n]: \", prompt)\n\t\tfmt.Scan(&inputz)\n\n\t\tif inputz = strings.ToLower(inputz); inputz == \"yes\" {\n\t\t\tnewinputz = \"y\"\n\t\t\ttf = true\n\t\t} else if inputz == \"no\" {\n\t\t\tnewinputz = \"n\"\n\t\t\ttf = true\n\t\t} else if inputz == \"y\" {\n\t\t\ttf = true\n\t\t\tnewinputz = inputz\n\t\t} else if inputz == \"n\" {\n\t\t\ttf = true\n\t\t\tnewinputz = inputz\n\t\t} else {\n\t\t\tnewinputz = \"Mountain Goat\"\n\t\t\ttf = false\n\t\t}\n\n\t}\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"time\"\n\t\"fmt\"\n)\n\n\n\n\nfunc main() {\n\tgo hehe(\"hello\")\n\tgo hehe(\"world\")\n\tfmt.Println(\"main routine\")\n\ttime.Sleep(time.Duration(2) * time.Second)\n\tfmt.Println(\"main again\")\n}\n\nfunc hehe(greet string) ", "output": "{\n\tfmt.Println(\"begin: \", greet)\n\ttime.Sleep(time.Duration(1) * time.Second)\n\tfmt.Println(\"end: \", greet)\n}"} {"input": "package spotify\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/laicosly/goth\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc provider() *Provider {\n\treturn New(os.Getenv(\"SPOTIFY_KEY\"), os.Getenv(\"SPOTIFY_SECRET\"), \"/foo\", \"user\")\n}\n\n\n\nfunc Test_ImplementsProvider(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\ta.Implements((*goth.Provider)(nil), provider())\n}\n\nfunc Test_BeginAuth(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\n\tp := provider()\n\tsession, err := p.BeginAuth(\"test_state\")\n\ts := session.(*Session)\n\ta.NoError(err)\n\ta.Contains(s.AuthURL, \"accounts.spotify.com/authorize\")\n}\n\nfunc Test_SessionFromJSON(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\n\tp := provider()\n\tsession, err := p.UnmarshalSession(`{\"AuthURL\":\"http://accounts.spotify.com/authorize\",\"AccessToken\":\"1234567890\"}`)\n\ta.NoError(err)\n\n\ts := session.(*Session)\n\ta.Equal(s.AuthURL, \"http://accounts.spotify.com/authorize\")\n\ta.Equal(s.AccessToken, \"1234567890\")\n}\n\nfunc Test_New(t *testing.T) ", "output": "{\n\tt.Parallel()\n\ta := assert.New(t)\n\tp := provider()\n\n\ta.Equal(p.ClientKey, os.Getenv(\"SPOTIFY_KEY\"))\n\ta.Equal(p.Secret, os.Getenv(\"SPOTIFY_SECRET\"))\n\ta.Equal(p.CallbackURL, \"/foo\")\n}"} {"input": "package logrus\n\nimport (\n\t\"io\"\n\t\"sync\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/golang/protobuf/proto\"\n\n\t\"go.pedge.io/protolog\"\n)\n\nvar (\n\tglobalPusherOptions = PusherOptions{}\n\tglobalLoggerOptions = protolog.LoggerOptions{}\n\tglobalLock = &sync.Mutex{}\n)\n\n\ntype PusherOptions struct {\n\tOut io.Writer\n\tHooks []logrus.Hook\n\tFormatter logrus.Formatter\n\tEnableID bool\n\tDisableContexts bool\n\tUnmarshalFunc func([]byte, proto.Message) error\n}\n\n\nfunc NewPusher(options PusherOptions) protolog.Pusher {\n\treturn newPusher(options)\n}\n\n\n\n\n\nfunc SetLoggerOptions(options protolog.LoggerOptions) {\n\tglobalLock.Lock()\n\tdefer globalLock.Unlock()\n\tglobalLoggerOptions = options\n\tregister()\n}\n\n\nfunc Register() {\n\tglobalLock.Lock()\n\tdefer globalLock.Unlock()\n\tregister()\n}\n\nfunc register() {\n\tprotolog.SetLogger(protolog.NewLogger(NewPusher(globalPusherOptions), globalLoggerOptions))\n}\n\nfunc SetPusherOptions(options PusherOptions) ", "output": "{\n\tglobalLock.Lock()\n\tdefer globalLock.Unlock()\n\tglobalPusherOptions = options\n\tregister()\n}"} {"input": "package kvstore\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/cilium/cilium/pkg/metrics\"\n\t\"github.com/cilium/cilium/pkg/option\"\n)\n\nconst (\n\tmetricDelete = \"delete\"\n\tmetricRead = \"read\"\n\tmetricSet = \"set\"\n)\n\nfunc getScopeFromKey(key string) string {\n\ts := strings.SplitN(key, \"/\", 5)\n\tif len(s) != 5 {\n\t\tif len(key) >= 12 {\n\t\t\treturn key[:12]\n\t\t}\n\t\treturn key\n\t}\n\treturn fmt.Sprintf(\"%s/%s\", s[2], s[3])\n}\n\nfunc increaseMetric(key, kind, action string, duration time.Duration, err error) {\n\tif !option.Config.MetricsConfig.KVStoreOperationsDurationEnabled {\n\t\treturn\n\t}\n\tnamespace := getScopeFromKey(key)\n\toutcome := metrics.Error2Outcome(err)\n\tmetrics.KVStoreOperationsDuration.\n\t\tWithLabelValues(namespace, kind, action, outcome).Observe(duration.Seconds())\n}\n\n\n\nfunc recordQuorumError(err string) {\n\tif !option.Config.MetricsConfig.KVStoreQuorumErrorsEnabled {\n\t\treturn\n\t}\n\tmetrics.KVStoreQuorumErrors.WithLabelValues(err).Inc()\n}\n\nfunc trackEventQueued(key string, typ EventType, duration time.Duration) ", "output": "{\n\tif !option.Config.MetricsConfig.KVStoreEventsQueueDurationEnabled {\n\t\treturn\n\t}\n\tmetrics.KVStoreEventsQueueDuration.WithLabelValues(getScopeFromKey(key), typ.String()).Observe(duration.Seconds())\n}"} {"input": "package utils\n\nimport (\n\t\"errors\"\n\t\"github.com/mmcloughlin/geohash\"\n\t\"github.com/whosonfirst/go-whosonfirst-geojson-v2\"\n\t\"github.com/whosonfirst/go-whosonfirst-hash\"\n)\n\nfunc GeohashFeature(f geojson.Feature) (string, error) {\n\n\tbboxes, err := f.BoundingBoxes()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmbr := bboxes.MBR()\n\tcenter := mbr.Center()\n\n\tlat := center.Y\n\tlon := center.X\n\n\tgh := geohash.Encode(lat, lon)\n\treturn gh, nil\n}\n\n\n\n\n\n\n\n\n\nfunc HashGeometry(geom []byte) (string, error) {\n\n\th, err := hash.NewWOFHash()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn h.HashFromJSON(geom)\n}\n\nfunc HashFeature(f geojson.Feature) (string, error) ", "output": "{\n\n\treturn \"\", errors.New(\"This is not ready to use yet\")\n\n\n\n\n\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"encoding/binary\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\ntype (\n\tPerfHeader struct {\n\t\tMagic [8]byte\n\t\tSize uint64\n\t\tAttrSize uint64\n\t\tAttrs PerfFileSection\n\t\tData PerfFileSection\n\t\tEventTypes PerfFileSection\n\t\tFlags uint64\n\t\tFlags1 [3]uint64\n\t}\n\tPerfFileSection struct {\n\t\tOffset uint64\n\t\tSize uint64\n\t}\n\tPerfHeaderString struct {\n\t\tLen uint32\n\t\tString []byte\n\t}\n\tPerfHeaderStringList struct {\n\t\tNr uint32\n\t\tStrings []PerfHeaderString\n\t}\n)\n\nfunc main() {\n\tflag.Parse()\n\tfor _, path := range flag.Args() {\n\t\tfmt.Println(path)\n\t\tr := open(path)\n\t\th := getPerfHeader(r)\n\t\tfmt.Println(h)\n\t}\n}\n\n\n\nfunc getPerfHeader(r *bufio.Reader) (h PerfHeader) {\n\terr := binary.Read(r, binary.LittleEndian, &h)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn h\n}\n\nfunc open(file string) *bufio.Reader ", "output": "{\n\tr, err := os.Open(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn bufio.NewReader(r)\n}"} {"input": "package wml\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\ntype CT_MailMergeDocType struct {\n\tValAttr ST_MailMergeDocType\n}\n\nfunc NewCT_MailMergeDocType() *CT_MailMergeDocType {\n\tret := &CT_MailMergeDocType{}\n\tret.ValAttr = ST_MailMergeDocType(1)\n\treturn ret\n}\n\nfunc (m *CT_MailMergeDocType) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tattr, err := m.ValAttr.MarshalXMLAttr(xml.Name{Local: \"w:val\"})\n\tif err != nil {\n\t\treturn err\n\t}\n\tstart.Attr = append(start.Attr, attr)\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}\n\n\n\n\nfunc (m *CT_MailMergeDocType) Validate() error {\n\treturn m.ValidateWithPath(\"CT_MailMergeDocType\")\n}\n\n\nfunc (m *CT_MailMergeDocType) ValidateWithPath(path string) error {\n\tif m.ValAttr == ST_MailMergeDocTypeUnset {\n\t\treturn fmt.Errorf(\"%s/ValAttr is a mandatory field\", path)\n\t}\n\tif err := m.ValAttr.ValidateWithPath(path + \"/ValAttr\"); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (m *CT_MailMergeDocType) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error ", "output": "{\n\tm.ValAttr = ST_MailMergeDocType(1)\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"val\" {\n\t\t\tm.ValAttr.UnmarshalXMLAttr(attr)\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_MailMergeDocType: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package restic\n\nimport \"syscall\"\n\nfunc (node Node) restoreSymlinkTimestamps(path string, utimes [2]syscall.Timespec) error {\n\treturn nil\n}\n\nfunc (node Node) device() int {\n\treturn int(node.Device)\n}\n\nfunc (s statUnix) atim() syscall.Timespec { return s.Atimespec }\nfunc (s statUnix) mtim() syscall.Timespec { return s.Mtimespec }\n\n\n\nfunc Getxattr(path, name string) ([]byte, error) {\n\treturn nil, nil\n}\n\n\n\nfunc Listxattr(path string) ([]string, error) {\n\treturn nil, nil\n}\n\n\nfunc Setxattr(path, name string, data []byte) error {\n\treturn nil\n}\n\nfunc (s statUnix) ctim() syscall.Timespec ", "output": "{ return s.Ctimespec }"} {"input": "package uptime_minutes\n\nimport (\n\t\"github.com/poblahblahblah/gofigure/lib/uptime_seconds\"\n\t\"strconv\"\n)\n\n\n\nfunc Load() string ", "output": "{\n\tuptime_in_seconds := uptime_seconds.Load()\n\tuptimeInt, err := strconv.Atoi(uptime_in_seconds)\n\tuptime_in_minutes := (uptimeInt / 60)\n\tif err != nil {\n\t\treturn string(\"\")\n\t}\n\n\treturn strconv.Itoa(uptime_in_minutes)\n\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\nfunc TestShellEscape(t *testing.T) {\n\tassertEqual(t, `''`, ShellEscape(\"\"))\n\tassertEqual(t, `$'escape\\'quote'`, ShellEscape(\"escape'quote\"))\n\tassertEqual(t, `$'foo\\r\\n\\tbar'`, ShellEscape(\"foo\\r\\n\\tbar\"))\n\tassertEqual(t, `$'foo bar'`, ShellEscape(\"foo bar\"))\n\tassertEqual(t, `$'\\xc3\\xa9'`, ShellEscape(\"é\"))\n}\n\n\n\nfunc assertEqual(t *testing.T, a, b string) ", "output": "{\n\tif a != b {\n\t\tt.Errorf(\"Expected \\\"%v\\\" to equal \\\"%v\\\"\", b, a)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/go-martini/martini\"\n\t\"github.com/martini-contrib/render\"\n)\n\nfunc main() {\n\n\tm := martini.Classic()\n\n\tStaticOptions := martini.StaticOptions{Prefix: \"public\"}\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\n\tm.Use(render.Renderer(render.Options{\n\t\tDirectory: \"templates\", \n\t\tLayout: \"layout\", \n\t\tExtensions: []string{\".tmpl\"}, \n\t\tCharset: \"UTF-8\", \n\t}))\n\n\tm.Get(\"/\", IndexRouter)\n\tm.Get(\"/about\", AboutRoute)\n\tm.Get(\"/contact\", ContactRoute)\n\tm.Get(\"/signin\", SigninRoute)\n\tm.Get(\"/signup\", SignupRoute)\n\n\tm.Run()\n}\n\nfunc IndexRouter(r render.Render) {\n\tr.HTML(200, \"home/index\", nil)\n}\n\nfunc AboutRoute(r render.Render) {\n\tr.HTML(200, \"home/about\", nil)\n}\n\nfunc ContactRoute(r render.Render) {\n\tr.HTML(200, \"home/contact\", nil)\n}\n\nfunc SigninRoute(r render.Render) {\n\tr.HTML(200, \"account/signin\", nil)\n}\n\n\n\nfunc SignupRoute(r render.Render) ", "output": "{\n\tr.HTML(200, \"account/signup\", nil)\n}"} {"input": "package integrations\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"code.gitea.io/gitea/models\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/unknwon/i18n\"\n)\n\n\n\nfunc TestSignin(t *testing.T) {\n\tdefer prepareTestEnv(t)()\n\n\tuser := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)\n\n\tuser.Name = \"testuser\"\n\tuser.LowerName = strings.ToLower(user.Name)\n\tuser.ID = 0\n\tmodels.AssertSuccessfulInsert(t, user)\n\n\tsamples := []struct {\n\t\tusername string\n\t\tpassword string\n\t\tmessage string\n\t}{\n\t\t{username: \"wrongUsername\", password: \"wrongPassword\", message: i18n.Tr(\"en\", \"form.username_password_incorrect\")},\n\t\t{username: \"wrongUsername\", password: \"password\", message: i18n.Tr(\"en\", \"form.username_password_incorrect\")},\n\t\t{username: \"user15\", password: \"wrongPassword\", message: i18n.Tr(\"en\", \"form.username_password_incorrect\")},\n\t\t{username: \"user1@example.com\", password: \"wrongPassword\", message: i18n.Tr(\"en\", \"form.username_password_incorrect\")},\n\t\t{username: \"user2@example.com\", password: \"password\", message: i18n.Tr(\"en\", \"form.email_been_used\")},\n\t}\n\n\tfor _, s := range samples {\n\t\ttestLoginFailed(t, s.username, s.password, s.message)\n\t}\n}\n\nfunc testLoginFailed(t *testing.T, username, password, message string) ", "output": "{\n\tsession := emptyTestSession(t)\n\treq := NewRequestWithValues(t, \"POST\", \"/user/login\", map[string]string{\n\t\t\"_csrf\": GetCSRF(t, session, \"/user/login\"),\n\t\t\"user_name\": username,\n\t\t\"password\": password,\n\t})\n\tresp := session.MakeRequest(t, req, http.StatusOK)\n\n\thtmlDoc := NewHTMLParser(t, resp.Body)\n\tresultMsg := htmlDoc.doc.Find(\".ui.message>p\").Text()\n\n\tassert.EqualValues(t, message, resultMsg)\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\n\t\"gopkg.in/pivo.v2/ws\"\n)\n\nconst websocketChatUri = `/`\n\ntype websocket struct {\n\tconn *ws.Conn\n}\n\n\n\nfunc (ws *websocket) OnBinaryRead(data []byte) error {\n\treturn ErrProtocolViolation\n}\n\nfunc (ws *websocket) OnTextRead(text string) error {\n\tchat.pub <- ws.conn.TextMessage(formatMessage(ws.conn, text))\n\treturn nil\n}\n\nfunc (chat *Hub) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tconn := ws.DefaultConn()\n\tif err := conn.Upgrade(w, r, nil); err != nil {\n\t\tlog.Printf(\"websocket: %s: failed to upgrade: %s\",\n\t\t\tr.RemoteAddr, err)\n\t\treturn\n\t}\n\tgo conn.Sender()\n\tgo conn.Receiver(&websocket{conn})\n\tchat.sub <- conn\n}\n\nfunc init() {\n\thttp.Handle(websocketChatUri, chat)\n}\n\nfunc (ws *websocket) OnClose(why error) error ", "output": "{\n\tchat.hub.Leave(ws.conn)\n\treturn nil\n}"} {"input": "package api\n\nimport (\n\t\"log\"\n)\n\n\n\nfunc checkStkPushRequirements(client *Client) bool {\n\n\tif client.Key == \"\" ||\n\t\tclient.PassKey == \"\" ||\n\t\tclient.TransactionCallback == \"\" ||\n\t\tclient.ShortCode == 0 ||\n\t\tclient.MSISDN == \"\" {\n\t\tlog.Println(`Please make sure you have instantiated the client with the following properties\\n\n\t\t\t\t\t\t 1. Key (Consumer Key)\\n\n\t\t\t\t\t\t 2. TransactionCallback (Callback URL for STK push)\\n\n\t\t\t\t\t\t 3. ShortCode (Lipa Na M-Pesa ShortCode)\\n\n\t\t\t\t\t\t 4. MSISDN (MSISDN - phone number provided for initiating transactions)`)\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc check(reqs string, client *Client) bool ", "output": "{\n\n\tvar res bool\n\tswitch reqs {\n\n\tcase \"stkpush\":\n\t\tres = checkStkPushRequirements(client)\n\tdefault:\n\t\tres = false\n\t}\n\n\treturn res\n\n}"} {"input": "package dynaml\n\nimport (\n\t\"fmt\"\n)\n\ntype ModuloExpr struct {\n\tA Expression\n\tB Expression\n}\n\nfunc (e ModuloExpr) Evaluate(binding Binding, locally bool) (interface{}, EvaluationInfo, bool) {\n\tresolved := true\n\n\taint, info, ok := ResolveIntegerExpressionOrPushEvaluation(&e.A, &resolved, nil, binding, false)\n\tif !ok {\n\t\treturn nil, info, false\n\t}\n\n\tbint, info, ok := ResolveIntegerExpressionOrPushEvaluation(&e.B, &resolved, &info, binding, false)\n\tif !ok {\n\t\treturn nil, info, false\n\t}\n\n\tif !resolved {\n\t\treturn e, info, true\n\t}\n\n\tif bint == 0 {\n\t\treturn info.Error(\"division by zero\")\n\t}\n\treturn aint % bint, info, true\n}\n\n\n\nfunc (e ModuloExpr) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%s %% %s\", e.A, e.B)\n}"} {"input": "package veritas_models\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\n\t\"github.com/cloudfoundry-incubator/bbs/models\"\n)\n\ntype VeritasLRP struct {\n\tProcessGuid string\n\tDesiredLRP *models.DesiredLRP\n\tActualLRPGroupsByIndex map[string]*models.ActualLRPGroup\n}\n\nfunc (l *VeritasLRP) OrderedActualLRPIndices() []string {\n\tindicesAsStrings := []string{}\n\tfor index := range l.ActualLRPGroupsByIndex {\n\t\tindicesAsStrings = append(indicesAsStrings, index)\n\t}\n\n\tsort.Sort(ByNumericalValue(indicesAsStrings))\n\treturn indicesAsStrings\n}\n\ntype ByNumericalValue []string\n\nfunc (a ByNumericalValue) Len() int { return len(a) }\n\nfunc (a ByNumericalValue) Less(i, j int) bool {\n\tai, _ := strconv.Atoi(a[i])\n\taj, _ := strconv.Atoi(a[j])\n\n\treturn ai < aj\n}\n\nfunc (a ByNumericalValue) Swap(i, j int) ", "output": "{ a[i], a[j] = a[j], a[i] }"} {"input": "package request\n\nimport (\n\t\"fmt\"\n\n\t\"dchaykin/meetup_api/settings\"\n)\n\ntype SimilarGroupRequest struct {\n\tURLName string \n}\n\nconst urlSimilarGroup string = \"%s/%s/similar_groups?key=%s&sign=true\"\n\nfunc (request SimilarGroupRequest) WithOffset() bool {\n\treturn true\n}\n\n\n\nfunc (request SimilarGroupRequest) Address() string ", "output": "{\n\treturn fmt.Sprintf(urlSimilarGroup, settings.BaseURL, request.URLName, settings.GetApiKey())\n}"} {"input": "package info_fakes\n\nimport (\n\t\"sync\"\n\n\t\"github.com/cloudfoundry-incubator/diego-ssh/cf-plugin/models/info\"\n)\n\ntype FakeInfoFactory struct {\n\tGetStub func() (info.Info, error)\n\tgetMutex sync.RWMutex\n\tgetArgsForCall []struct{}\n\tgetReturns struct {\n\t\tresult1 info.Info\n\t\tresult2 error\n\t}\n}\n\nfunc (fake *FakeInfoFactory) Get() (info.Info, error) {\n\tfake.getMutex.Lock()\n\tfake.getArgsForCall = append(fake.getArgsForCall, struct{}{})\n\tfake.getMutex.Unlock()\n\tif fake.GetStub != nil {\n\t\treturn fake.GetStub()\n\t} else {\n\t\treturn fake.getReturns.result1, fake.getReturns.result2\n\t}\n}\n\nfunc (fake *FakeInfoFactory) GetCallCount() int {\n\tfake.getMutex.RLock()\n\tdefer fake.getMutex.RUnlock()\n\treturn len(fake.getArgsForCall)\n}\n\n\n\nvar _ info.InfoFactory = new(FakeInfoFactory)\n\nfunc (fake *FakeInfoFactory) GetReturns(result1 info.Info, result2 error) ", "output": "{\n\tfake.GetStub = nil\n\tfake.getReturns = struct {\n\t\tresult1 info.Info\n\t\tresult2 error\n\t}{result1, result2}\n}"} {"input": "package controller\n\nimport (\n\t\"net/http\"\n\t\"encoding/json\"\n\t\"rest-commander/store\"\n\t\"rest-commander/model/dto\"\n)\n\ntype AuthenticationController interface {\n\tHandleLogin(w http.ResponseWriter, r *http.Request)\n\tHandleLogout(w http.ResponseWriter, r *http.Request)\n}\n\nfunc (t *AuthenticationRoute) HandleLogin(w http.ResponseWriter, r *http.Request){\n\tvar auth dto.LoginRequest\n\terr := json.NewDecoder(r.Body).Decode(&auth)\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 400)\n\t\treturn\n\t}\n\n\tif !t.userStore.CheckPassword(auth.Username, auth.Password) {\n\t\tresp := dto.ErrorResponse{\n\t\t\tMessage: \"Username or password are incorrect!\",\n\t\t}\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\ttoken := store.NewAuthenticationToken(auth.Username)\n\n\tt.tokenStore.Add(token)\n\tt.userStore.Get(auth.Username).Password = auth.Password\n\n\tresp := dto.LoginResponse{\n\t\tToken: token.Token,\n\t}\n\tjson.NewEncoder(w).Encode(resp)\n}\n\n\n\nfunc (t *AuthenticationRoute) HandleLogout(w http.ResponseWriter, r *http.Request)", "output": "{\n\ttoken := GetAuthtokenFromRequest(r)\n\tt.tokenStore.Remove(token.Token)\n}"} {"input": "package libkb\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestRateLimit(t *testing.T) ", "output": "{\n\ttc := SetupTest(t, \"rateLimit\", 0)\n\tdefer tc.Cleanup()\n\tlimits := NewRateLimits(tc.G)\n\tif !limits.GetPermission(TestEventRateLimit, 1*time.Minute) {\n\t\tt.Fatal(\"expected to get permission\")\n\t}\n\tif !limits.GetPermission(TestEventRateLimit, 0) {\n\t\tt.Fatal(\"expected to get permission again with a zero interval\")\n\t}\n\tif limits.GetPermission(TestEventRateLimit, 1*time.Minute) {\n\t\tt.Fatal(\"expected not to get permission with a long interval\")\n\t}\n}"} {"input": "package ghalloc\n\nimport \"unsafe\"\n\ntype slab struct {\n\tslabClass *slabClass \n\tmemory []byte \n\tfull bool \n\tallocated uint64 \n\tchunkMap uint64 \n}\n\nfunc newSlab(sc *slabClass) *slab {\n\ts := &slab{\n\t\tslabClass: sc,\n\t\tmemory: make([]byte, sc.SlabSize),\n\t\tfull: false,\n\t\tallocated: 0,\n\t}\n\n\treturn s\n}\n\n\nfunc (s *slab) allocChunk() unsafe.Pointer {\n\tif s.full {\n\t\treturn nil\n\t}\n\n\ti := s.getUnusedChunkIndex()\n\tptr := unsafe.Pointer(&s.memory[s.getUnusedChunkIndex()])\n\n\ts.chunkMap |= 1 << i\n\ts.allocated++\n\n\tif s.allocated >= s.slabClass.Capacity {\n\t\ts.full = true\n\t}\n\n\treturn ptr\n}\n\n\nfunc (s *slab) freeChunk(ptr unsafe.Pointer) {\n\tuptr := uintptr(ptr)\n\tbegin := uintptr(unsafe.Pointer(&s.memory[0]))\n\n\tif uptr >= begin && uptr <= uintptr(unsafe.Pointer(&s.memory[0]))+uintptr(s.slabClass.SlabSize) {\n\t\ts.chunkMap &^= 1 << uint64(uptr-begin) % uint64(s.slabClass.SlabSize)\n\n\t\ts.allocated--\n\t\tif s.full {\n\t\t\ts.full = false\n\t\t}\n\t}\n}\n\n\n\nfunc (s *slab) getUnusedChunkIndex() uint64 ", "output": "{\n\tvar i uint64\n\n\tfor i = 0; i < s.slabClass.Capacity; i++ {\n\t\tif s.chunkMap&(1<\", -1)\n\t}\n\treturn conf\n}\n\n\n\n\n\n\n\nfunc DownloadableURL(original string) (string, error) {\n\n\tsupported := []string{\"file\", \"http\", \"https\", \"ftp\", \"smb\"}\n\tfound := false\n\tfor _, s := range supported {\n\t\tif strings.HasPrefix(strings.ToLower(original), s+\"://\") {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif found {\n\t\toriginal = filepath.ToSlash(original)\n\n\t\turi, err := url.Parse(original)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\turi.Scheme = strings.ToLower(uri.Scheme)\n\n\t\treturn uri.String(), nil\n\t}\n\n\t_, err := os.Stat(original)\n\tif err == nil {\n\t\toriginal, err = filepath.Abs(filepath.FromSlash(original))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\toriginal, err = filepath.EvalSymlinks(original)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\toriginal = filepath.Clean(original)\n\t\toriginal = filepath.ToSlash(original)\n\t}\n\n\n\treturn \"file://\" + original, nil\n}\n\nfunc ChooseString(vals ...string) string ", "output": "{\n\tfor _, el := range vals {\n\t\tif el != \"\" {\n\t\t\treturn el\n\t\t}\n\t}\n\n\treturn \"\"\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype DNSDomains []string\n\n\nfunc (m DNSDomains) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tiDNSDomainsSize := int64(len(m))\n\n\tif err := validate.MaxItems(\"\", \"body\", iDNSDomainsSize, 6); err != nil {\n\t\treturn err\n\t}\n\n\tfor i := 0; i < len(m); i++ {\n\n\t\tif err := validate.MinLength(strconv.Itoa(i), \"body\", m[i], 1); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := validate.MaxLength(strconv.Itoa(i), \"body\", m[i], 255); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\n\nfunc (m DNSDomains) ContextValidate(ctx context.Context, formats strfmt.Registry) error ", "output": "{\n\treturn nil\n}"} {"input": "package converters\n\nimport (\n\t\"github.com/open-gtd/server/contract/tags\"\n\t\"github.com/open-gtd/server/tags/domain\"\n)\n\n\n\nfunc ConvertToTag(t domain.Tag) (tags.Tag, error) {\n\n\ttypeDescriptor, err := ConvertTypeToPresentation(t.GetType())\n\tif err != nil {\n\t\treturn tags.Tag{}, err\n\t}\n\n\treturn tags.Tag{\n\t\tName: string(t.GetName()),\n\t\tType: typeDescriptor,\n\t}, nil\n}\n\nfunc ConvertAllToTag(t []domain.Tag) ([]tags.Tag, error) ", "output": "{\n\tresult := make([]tags.Tag, len(t))\n\n\tfor i, tag := range t {\n\t\tpTag, err := ConvertToTag(tag)\n\t\tif err != nil {\n\t\t\treturn make([]tags.Tag, 0), err\n\t\t}\n\n\t\tresult[i] = pTag\n\t}\n\n\treturn result, nil\n}"} {"input": "package iso20022\n\n\ntype SettlementStatus10Choice struct {\n\n\tPending *PendingStatus15Choice `xml:\"Pdg\"`\n\n\tFailing *FailingStatus3Choice `xml:\"Flng\"`\n\n\tProprietary *ProprietaryStatusAndReason1 `xml:\"Prtry\"`\n}\n\nfunc (s *SettlementStatus10Choice) AddPending() *PendingStatus15Choice {\n\ts.Pending = new(PendingStatus15Choice)\n\treturn s.Pending\n}\n\nfunc (s *SettlementStatus10Choice) AddFailing() *FailingStatus3Choice {\n\ts.Failing = new(FailingStatus3Choice)\n\treturn s.Failing\n}\n\n\n\nfunc (s *SettlementStatus10Choice) AddProprietary() *ProprietaryStatusAndReason1 ", "output": "{\n\ts.Proprietary = new(ProprietaryStatusAndReason1)\n\treturn s.Proprietary\n}"} {"input": "package credentials\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype stubProvider struct {\n\tcreds Value\n\terr error\n}\n\nfunc (s *stubProvider) Retrieve() (Value, error) {\n\ts.creds.ProviderName = \"stubProvider\"\n\treturn s.creds, s.err\n}\n\nfunc TestCredentialsGet(t *testing.T) {\n\tc := NewCredentials(&stubProvider{\n\t\tcreds: Value{\n\t\t\tAccessKeyID: \"AKID\",\n\t\t\tSecretAccessKey: \"SECRET\",\n\t\t},\n\t})\n\n\tcreds, err := c.Get()\n\tassert.Nil(t, err, \"Expected no error\")\n\tassert.Equal(t, \"AKID\", creds.AccessKeyID, \"Expect access key ID to match\")\n\tassert.Equal(t, \"SECRET\", creds.SecretAccessKey, \"Expect secret access key to match\")\n}\n\nfunc TestCredentialsGetWithError(t *testing.T) {\n\tc := NewCredentials(&stubProvider{err: errors.New(\"provider error\")})\n\n\t_, err := c.Get()\n\tassert.Equal(t, \"provider error\", err.Error(), \"Expected provider error\")\n}\n\n\n\nfunc TestCredentialsGetWithProviderName(t *testing.T) ", "output": "{\n\tstub := &stubProvider{}\n\n\tc := NewCredentials(stub)\n\n\tcreds, err := c.Get()\n\tassert.Nil(t, err, \"Expected no error\")\n\tassert.Equal(t, creds.ProviderName, \"stubProvider\", \"Expected provider name to match\")\n}"} {"input": "package mailgun\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/getfider/fider/app/models/dto\"\n\t\"github.com/getfider/fider/app/pkg/bus\"\n\t\"github.com/getfider/fider/app/pkg/env\"\n\t\"github.com/getfider/fider/app/pkg/log\"\n)\n\n\n\n\nvar baseURLs = map[string]string{\n\t\"US\": \"https://api.mailgun.net/v3/%s\",\n\t\"EU\": \"https://api.eu.mailgun.net/v3/%s\",\n}\n\nfunc init() {\n\tbus.Register(Service{})\n}\n\ntype Service struct{}\n\nfunc (s Service) Name() string {\n\treturn \"Mailgun\"\n}\n\n\n\nfunc (s Service) Enabled() bool {\n\treturn env.Config.Email.Type == \"mailgun\"\n}\n\nfunc (s Service) Init() {\n\tbus.AddListener(sendMail)\n\tbus.AddHandler(fetchRecentSupressions)\n}\n\n\n\nfunc getEndpoint(ctx context.Context, domain, path string) string {\n\tvar regionCode = env.Config.Email.Mailgun.Region\n\tregionCode = strings.ToUpper(regionCode)\n\n\tif len(regionCode) < 1 {\n\t\tregionCode = \"US\"\n\t} else if len(baseURLs[regionCode]) < 1 {\n\t\tlog.Warnf(ctx,\n\t\t\t\"Unknown Mailgun region code '@{Code}' configured - falling back to 'US'\",\n\t\t\tdto.Props{\n\t\t\t\t\"Code\": env.Config.Email.Mailgun.Region,\n\t\t\t},\n\t\t)\n\n\t\tregionCode = \"US\"\n\t}\n\n\treturn fmt.Sprintf(baseURLs[regionCode], domain) + path\n}\n\nfunc (s Service) Category() string ", "output": "{\n\treturn \"email\"\n}"} {"input": "package iam\n\nimport (\n\ttimestamp \"github.com/golang/protobuf/ptypes/timestamp\"\n)\n\ntype CreateIamTokenRequest_Identity = isCreateIamTokenRequest_Identity\n\nfunc (m *CreateIamTokenRequest) SetIdentity(v CreateIamTokenRequest_Identity) {\n\tm.Identity = v\n}\n\n\n\nfunc (m *CreateIamTokenRequest) SetJwt(v string) {\n\tm.Identity = &CreateIamTokenRequest_Jwt{\n\t\tJwt: v,\n\t}\n}\n\nfunc (m *CreateIamTokenResponse) SetIamToken(v string) {\n\tm.IamToken = v\n}\n\nfunc (m *CreateIamTokenResponse) SetExpiresAt(v *timestamp.Timestamp) {\n\tm.ExpiresAt = v\n}\n\nfunc (m *CreateIamTokenRequest) SetYandexPassportOauthToken(v string) ", "output": "{\n\tm.Identity = &CreateIamTokenRequest_YandexPassportOauthToken{\n\t\tYandexPassportOauthToken: v,\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n)\n\n\n\nfunc handleUnauthorized(w http.ResponseWriter) {\n\thttp.Error(w, http.StatusText(http.StatusUnauthorized),\n\t\thttp.StatusUnauthorized)\n}\n\n\nfunc writeJSON(w http.ResponseWriter, v interface{}) error {\n\tb, err := json.Marshal(v)\n\tif err != nil {\n\t\thandleInternalServerError(w)\n\t\treturn err\n\t}\n\n\tif _, err = w.Write(b); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc handleInternalServerError(w http.ResponseWriter) ", "output": "{\n\thttp.Error(w, http.StatusText(http.StatusInternalServerError),\n\t\thttp.StatusInternalServerError)\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1alpha1 \"k8s.io/kops/pkg/client/clientset_generated/clientset/typed/kops/v1alpha1\"\n)\n\ntype FakeKopsV1alpha1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeKopsV1alpha1) Clusters(namespace string) v1alpha1.ClusterInterface {\n\treturn &FakeClusters{c, namespace}\n}\n\nfunc (c *FakeKopsV1alpha1) Federations(namespace string) v1alpha1.FederationInterface {\n\treturn &FakeFederations{c, namespace}\n}\n\nfunc (c *FakeKopsV1alpha1) InstanceGroups(namespace string) v1alpha1.InstanceGroupInterface {\n\treturn &FakeInstanceGroups{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeKopsV1alpha1) RESTClient() rest.Interface ", "output": "{\n\tvar ret *rest.RESTClient\n\treturn ret\n}"} {"input": "package osutil\n\nimport (\n\t\"context\"\n\t\"net/url\"\n\t\"time\"\n\n\t\"github.com/syncthing/syncthing/lib/dialer\"\n)\n\n\n\n\nfunc TCPPing(ctx context.Context, address string) (time.Duration, error) {\n\tstart := time.Now()\n\tctx, cancel := context.WithTimeout(ctx, time.Second)\n\tdefer cancel()\n\tconn, err := dialer.DialContext(ctx, \"tcp\", address)\n\tif err == nil {\n\t\tconn.Close()\n\t}\n\treturn time.Since(start), err\n}\n\n\n\n\n\nfunc GetLatencyForURL(ctx context.Context, addr string) (time.Duration, error) ", "output": "{\n\turi, err := url.Parse(addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn TCPPing(ctx, uri.Host)\n}"} {"input": "package throttled\n\n\ntype WaitGroup struct {\n\tthrottle int\n\tcompleted chan bool\n\toutstanding int\n}\n\n\nfunc NewWaitGroup(throttle int) *WaitGroup {\n\treturn &WaitGroup{\n\t\toutstanding: 0,\n\t\tthrottle: throttle,\n\t\tcompleted: make(chan bool, throttle),\n\t}\n}\n\n\nfunc (w *WaitGroup) PeekThrottled() bool {\n\treturn w.outstanding+1 > w.throttle\n}\n\n\n\nfunc (w *WaitGroup) Add() {\n\tw.outstanding++\n\tif w.outstanding > w.throttle {\n\t\tselect {\n\t\tcase <-w.completed:\n\t\t\tw.outstanding--\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\nfunc (w *WaitGroup) Done() {\n\tw.completed <- true\n}\n\n\n\n\nfunc (w *WaitGroup) Wait() ", "output": "{\n\tif w.outstanding == 0 {\n\t\treturn\n\t}\n\tfor w.outstanding > 0 {\n\t\tselect {\n\t\tcase <-w.completed:\n\t\t\tw.outstanding--\n\t\t}\n\t}\n}"} {"input": "package quit\n\nimport (\n\t\"fmt\"\n\t\"github.com/talpah/cortana/plugins\"\n\t\"regexp\"\n\t\"os\"\n)\n\nvar (\n\tcanonicalCommand = \"quit\"\n\tcommand = `(Q|q)uit`\n\taliases map[string]*regexp.Regexp\n)\n\nfunc isAlias(cmd string) bool {\n\tfor _, alias := range aliases {\n\t\tif alias.MatchString(cmd) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc canHandle(cmd string) bool {\n\tif regexp.MustCompile(command).MatchString(cmd) {\n\t\treturn true\n\t}\n\n\treturn isAlias(cmd)\n}\n\nfunc Initialize(pins plugins.PluginManager) {\n\taliases = map[string]*regexp.Regexp{\n\t\t\"Exit\": regexp.MustCompile(`(E|e)xit`),\n\n\t}\n\n\tpins.Register(\n\t\tcanonicalCommand,\n\t\tcommand,\n\t\tQuit,\n\t\tHelp,\n\t\taliases,\n\t)\n}\n\nfunc Help(cmd string) (string, error) {\n\treturn `Quit command help\n\nQuit will... quit\n\nUsage example:\nquit\nQuit\nexit\nExit\n`, nil\n}\n\n\n\nfunc Quit(cmd string) (string, error) ", "output": "{\n\tif !canHandle(cmd) {\n\t\treturn \"\", fmt.Errorf(\"Can't handle command %s\", cmd)\n\t}\n\tos.Exit(0)\n\treturn \"\", nil\n}"} {"input": "package featuretests\n\nimport (\n\t\"os\"\n\n\t\"github.com/juju/cmd/cmdtesting\"\n\tjc \"github.com/juju/testing/checkers\"\n\tgc \"gopkg.in/check.v1\"\n\n\t\"github.com/juju/juju/juju/osenv\"\n\tjujutesting \"github.com/juju/juju/juju/testing\"\n)\n\ntype CmdRelationSuite struct {\n\tjujutesting.JujuConnSuite\n\tapps []string\n}\n\nfunc (s *CmdRelationSuite) SetUpTest(c *gc.C) {\n\ts.JujuConnSuite.SetUpTest(c)\n\tos.Setenv(osenv.JujuModelEnvKey, \"\")\n\n\ts.apps = []string{\"wordpress\", \"mysql\"}\n\tfor _, app := range s.apps {\n\t\tch := s.AddTestingCharm(c, app)\n\t\ts.AddTestingApplication(c, app, ch)\n\t}\n}\n\nfunc (s *CmdRelationSuite) TestAddRelationSuccess(c *gc.C) {\n\trunCommandExpectSuccess(c, \"add-relation\", s.apps...)\n}\n\n\n\nfunc (s *CmdRelationSuite) TestRemoveRelationSuccess(c *gc.C) {\n\trunCommandExpectSuccess(c, \"add-relation\", s.apps...)\n\trunCommandExpectSuccess(c, \"remove-relation\", s.apps...)\n}\n\nfunc (s *CmdRelationSuite) TestRemoveRelationFail(c *gc.C) {\n\trunCommandExpectFailure(c, \"remove-relation\", `relation \"wordpress:db mysql:server\" not found`, s.apps...)\n}\n\nfunc (s *CmdRelationSuite) TestAddRelationSuccessOnAlreadyExists(c *gc.C) ", "output": "{\n\trunCommandExpectSuccess(c, \"add-relation\", s.apps...)\n\tcontext, err := runCommand(c, append([]string{\"add-relation\"}, s.apps...)...)\n\tc.Assert(err, gc.NotNil)\n\tc.Check(cmdtesting.Stderr(context), jc.Contains, `ERROR cannot add relation \"wordpress:db mysql:server\"\nrelation wordpress:db mysql:server (already exists): \n\nUse 'juju status --relations' to view the current relations.\n`)\n}"} {"input": "package testdata\n\n\n\nfunc Foo26(v interface{}) (_ string, i int, _ []byte, err error) ", "output": "{\n\treturn \"\", 0, nil, nil\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n)\n\ntype Audits []Audit\n\nfunc (o Audits) Etag() string {\n\tif len(o) > 0 {\n\t\treturn Etag(o[0].CreateAt)\n\t}\n\treturn \"\"\n}\n\n\n\nfunc AuditsFromJson(data io.Reader) Audits {\n\tvar o Audits\n\tjson.NewDecoder(data).Decode(&o)\n\treturn o\n}\n\nfunc (o Audits) ToJson() string ", "output": "{\n\tb, err := json.Marshal(o)\n\tif err != nil {\n\t\treturn \"[]\"\n\t}\n\treturn string(b)\n}"} {"input": "package handlers\n\nimport (\n\t\"github.com/rancher/apiserver/pkg/apierror\"\n\t\"github.com/rancher/apiserver/pkg/parse\"\n\t\"github.com/rancher/apiserver/pkg/types\"\n\t\"github.com/rancher/wrangler/pkg/schemas/validation\"\n)\n\n\n\nfunc CreateHandler(apiOp *types.APIRequest) (types.APIObject, error) ", "output": "{\n\tvar err error\n\n\tif err := apiOp.AccessControl.CanCreate(apiOp, apiOp.Schema); err != nil {\n\t\treturn types.APIObject{}, err\n\t}\n\n\tdata, err := parse.Body(apiOp.Request)\n\tif err != nil {\n\t\treturn types.APIObject{}, err\n\t}\n\n\tstore := apiOp.Schema.Store\n\tif store == nil {\n\t\treturn types.APIObject{}, apierror.NewAPIError(validation.NotFound, \"no store found\")\n\t}\n\n\tdata, err = store.Create(apiOp, apiOp.Schema, data)\n\tif err != nil {\n\t\treturn types.APIObject{}, err\n\t}\n\n\treturn data, nil\n}"} {"input": "package Plugin\n\nimport \"github.com/MPjct/GoMP/MySQLProtocol\"\n\ntype Plugin_interface interface {\n\tinit(context MySQLProtocol.Context)\n\tread_handshake(context MySQLProtocol.Context)\n\tsend_handshake(context MySQLProtocol.Context)\n\tread_auth(context MySQLProtocol.Context)\n\tsend_auth(context MySQLProtocol.Context)\n\tread_auth_result(context MySQLProtocol.Context)\n\tsend_auth_result(context MySQLProtocol.Context)\n\tread_query(context MySQLProtocol.Context)\n\tsend_query(context MySQLProtocol.Context)\n\tread_query_result(context MySQLProtocol.Context)\n\tsend_query_result(context MySQLProtocol.Context)\n\tcleanup(context MySQLProtocol.Context)\n}\n\ntype Plugin struct {\n}\n\nfunc (plugin *Plugin) init(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\n\n\nfunc (plugin *Plugin) read_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) cleanup(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_handshake(context MySQLProtocol.Context) ", "output": "{\n\treturn\n}"} {"input": "package bech32\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n)\n\n\n\n\n\nfunc ExampleBech23Encode() {\n\tdata := []byte(\"Test data\")\n\tconv, err := ConvertBits(data, 8, 5, true)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\tencoded, err := Bech32Encode(\"customHrp!11111q\", conv)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tfmt.Println(\"Encoded Data:\", encoded)\n\n}\n\nfunc ExampleBech32Decode() ", "output": "{\n\tencoded := \"bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7k7grplx\"\n\thrp, decoded, err := Bech32Decode(encoded)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tfmt.Println(\"Decoded human-readable part:\", hrp)\n\tfmt.Println(\"Decoded Data:\", hex.EncodeToString(decoded))\n\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/robfig/cron\"\n)\n\ntype Sync struct{}\n\nfunc (s *Sync) Help() string {\n\treturn \"glr sync Help\"\n}\n\nfunc (s *Sync) Run(args []string) int {\n\t_, err := SyncRepository()\n\n\tif err != nil {\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n\n\n\n\ntype status struct {\n\tc *cron.Cron\n\trepositories []string\n\tschedules []string\n}\n\nvar sharedStatus *status = newStatus()\n\nfunc newStatus() *status {\n\treturn &status{\n\t\tc: cron.New(),\n\t}\n}\n\n\nfunc GetStatus() *status {\n\treturn sharedStatus\n}\n\ntype StatusStart struct{}\n\nfunc (s *StatusStart) Help() string {\n\treturn \"glr status start Help\"\n}\n\nfunc (s *StatusStart) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.AddFunc(\"@hourly\", func() {\n\t\tSyncRepository()\n\t})\n\tfmt.Println(\"set job schedule\")\n\tstatus.c.Start()\n\n\treturn 0\n}\n\nfunc (s *StatusStart) Synopsis() string {\n\treturn \"Synchronize local git repository with remote\"\n}\n\ntype StatusStop struct{}\n\nfunc (s *StatusStop) Help() string {\n\treturn \"glr status stop Help\"\n}\n\nfunc (s *StatusStop) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.Stop()\n\tfmt.Println(\"stop job scheduler\")\n\n\treturn 0\n}\n\nfunc (s *StatusStop) Synopsis() string {\n\treturn \"Stop cron scheduler\"\n}\n\nfunc (s *Sync) Synopsis() string ", "output": "{\n\treturn \"Synchronize local git repository with remote at once\"\n}"} {"input": "package cover\n\nimport (\n\t\"flag\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc ParseAndStripTestFlags() {\n\tflag.Parse()\n\n\tvar runtimeArgs []string\n\tfor _, arg := range os.Args {\n\t\tif strings.HasPrefix(arg, \"-test.\") ||\n\t\t\tstrings.HasPrefix(arg, \"-httptest.\") {\n\t\t\tcontinue\n\t\t}\n\t\truntimeArgs = append(runtimeArgs, arg)\n\t}\n\tos.Args = runtimeArgs\n}\n\ntype dummyTestDeps func(pat, str string) (bool, error)\n\nfunc (d dummyTestDeps) MatchString(pat, str string) (bool, error) { return false, nil }\n\nfunc (d dummyTestDeps) StopCPUProfile() {}\nfunc (f dummyTestDeps) StartTestLog(w io.Writer) {}\nfunc (f dummyTestDeps) StopTestLog() error { return nil }\nfunc (d dummyTestDeps) WriteHeapProfile(io.Writer) error { return nil }\nfunc (d dummyTestDeps) WriteProfileTo(string, io.Writer, int) error { return nil }\nfunc (f dummyTestDeps) ImportPath() string { return \"\" }\n\n\n\n\n\nfunc FlushProfiles() {\n\toldstdout := os.Stdout\n\toldstderr := os.Stderr\n\tos.Stdout, _ = os.Open(os.DevNull)\n\tos.Stderr, _ = os.Open(os.DevNull)\n\n\ttests := []testing.InternalTest{}\n\tbenchmarks := []testing.InternalBenchmark{}\n\texamples := []testing.InternalExample{}\n\tvar f dummyTestDeps\n\tdummyM := testing.MainStart(f, tests, benchmarks, examples)\n\tdummyM.Run()\n\n\tos.Stdout = oldstdout\n\tos.Stderr = oldstderr\n}\n\nfunc (d dummyTestDeps) StartCPUProfile(io.Writer) error ", "output": "{ return nil }"} {"input": "package buckets\n\nimport (\n\t\"github.com/campadrenalin/scrap\"\n\t\"testing\"\n)\n\nfunc TestAnyBucket_Empty(t *testing.T) {\n\tb := AnyBucket{}\n\tif b.Check(\"foo\") {\n\t\tt.Fatal(\"Should always return false when there are no children\")\n\t}\n}\n\n\n\nfunc TestAnyBucket_MultipleItems(t *testing.T) {\n\tb := AnyBucket{\n\t\tChildren: []scrap.Bucket{\n\t\t\tscrap.NewCountBucket(1),\n\t\t\tscrap.NewCountBucket(2),\n\t\t},\n\t}\n\ttests := bt_slice{\n\t\tbt{\"foo\", true, \"First bucket says yes\"},\n\t\tbt{\"foo\", true, \"First bucket exhausted, second says yes\"},\n\t\tbt{\"foo\", true, \"Second bucket says yes for the final time\"},\n\t\tbt{\"foo\", false, \"Second bucket exhausted\"},\n\t}\n\ttests.Run(t, b)\n\n\tb.Children[0].(*scrap.CountBucket).SetMaxHits(3)\n\ttests = bt_slice{\n\t\tbt{\"foo\", true, \"First bucket says yes\"},\n\t\tbt{\"foo\", true, \"First bucket says yes for the final time\"},\n\t\tbt{\"foo\", false, \"Both buckets exhausted\"},\n\t}\n\ttests.Run(t, b)\n}\n\nfunc TestAnyBucket_OneItem(t *testing.T) ", "output": "{\n\tb := AnyBucket{\n\t\tChildren: []scrap.Bucket{\n\t\t\tscrap.NewCountBucket(1),\n\t\t},\n\t}\n\ttests := bt_slice{\n\t\tbt{\"foo\", true, \"First should succeed\"},\n\t\tbt{\"foo\", false, \"Second should fail\"},\n\t}\n\ttests.Run(t, b)\n}"} {"input": "package migration\n\nimport \"time\"\n\n\ntype IssueContext interface {\n\tLocalID() int64\n\tForeignID() int64\n}\n\n\ntype BasicIssueContext int64\n\n\nfunc (c BasicIssueContext) LocalID() int64 {\n\treturn int64(c)\n}\n\n\nfunc (c BasicIssueContext) ForeignID() int64 {\n\treturn int64(c)\n}\n\n\ntype Issue struct {\n\tNumber int64 `json:\"number\"`\n\tPosterID int64 `yaml:\"poster_id\" json:\"poster_id\"`\n\tPosterName string `yaml:\"poster_name\" json:\"poster_name\"`\n\tPosterEmail string `yaml:\"poster_email\" json:\"poster_email\"`\n\tTitle string `json:\"title\"`\n\tContent string `json:\"content\"`\n\tRef string `json:\"ref\"`\n\tMilestone string `json:\"milestone\"`\n\tState string `json:\"state\"` \n\tIsLocked bool `yaml:\"is_locked\" json:\"is_locked\"`\n\tCreated time.Time `json:\"created\"`\n\tUpdated time.Time `json:\"updated\"`\n\tClosed *time.Time `json:\"closed\"`\n\tLabels []*Label `json:\"labels\"`\n\tReactions []*Reaction `json:\"reactions\"`\n\tAssignees []string `json:\"assignees\"`\n\tContext IssueContext `yaml:\"-\"`\n}\n\n\n\n\n\nfunc (i *Issue) GetExternalID() int64 { return i.PosterID }\n\nfunc (i *Issue) GetExternalName() string ", "output": "{ return i.PosterName }"} {"input": "package wikipedia\n\nimport (\n\t\"log\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestQueryEN(t *testing.T) {\n\tapi := NewApi()\n\tquery := \"shovel\"\n\tres, err := api.Query(EN, query)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tassert.Equal(t, query, res.Query)\n\tassert.NotEmpty(t, res.Items)\n\tfor _, it := range res.Items {\n\t\tlog.Printf(\"Item %s:\\n%s (%s)\\n\\n\", it.Text, it.Description, it.URL)\n\t}\n}\n\nfunc TestQueryRU(t *testing.T) ", "output": "{\n\tapi := NewApi()\n\tquery := \"лопата\"\n\tres, err := api.Query(RU, query)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tassert.Equal(t, query, res.Query)\n\tassert.NotEmpty(t, res.Items)\n\tfor _, it := range res.Items {\n\t\tlog.Printf(\"Item %s:\\n%s (%s)\\n\\n\", it.Text, it.Description, it.URL)\n\t}\n}"} {"input": "package plugin\n\nimport \"github.com/docker/docker/api/server/router\"\n\n\ntype pluginRouter struct {\n\tbackend Backend\n\troutes []router.Route\n}\n\n\nfunc NewRouter(b Backend) router.Router {\n\tr := &pluginRouter{\n\t\tbackend: b,\n\t}\n\tr.initRoutes()\n\treturn r\n}\n\n\nfunc (r *pluginRouter) Routes() []router.Route {\n\treturn r.routes\n}\n\n\n\nfunc (r *pluginRouter) initRoutes() ", "output": "{\n\tr.routes = []router.Route{\n\t\trouter.NewGetRoute(\"/plugins\", r.listPlugins),\n\t\trouter.NewGetRoute(\"/plugins/{name:.*}/json\", r.inspectPlugin),\n\t\trouter.NewGetRoute(\"/plugins/privileges\", r.getPrivileges),\n\t\trouter.NewDeleteRoute(\"/plugins/{name:.*}\", r.removePlugin),\n\t\trouter.NewPostRoute(\"/plugins/{name:.*}/enable\", r.enablePlugin), \n\t\trouter.NewPostRoute(\"/plugins/{name:.*}/disable\", r.disablePlugin),\n\t\trouter.NewPostRoute(\"/plugins/pull\", r.pullPlugin),\n\t\trouter.NewPostRoute(\"/plugins/{name:.*}/push\", r.pushPlugin),\n\t\trouter.NewPostRoute(\"/plugins/{name:.*}/set\", r.setPlugin),\n\t\trouter.NewPostRoute(\"/plugins/create\", r.createPlugin),\n\t}\n}"} {"input": "package router\n\ntype sortedRoutes struct {\n\troutes Routes\n}\n\nfunc (s sortedRoutes) Len() int {\n\treturn len(s.routes.Routes)\n}\n\nfunc (s sortedRoutes) Less(i, j int) bool {\n\treturn s.routes.Routes[i].Priority < s.routes.Routes[j].Priority\n}\n\n\n\nfunc (s sortedRoutes) Swap(i, j int) ", "output": "{\n\ts.routes.Routes[i], s.routes.Routes[j] = s.routes.Routes[j], s.routes.Routes[i]\n}"} {"input": "package v1\n\nimport (\n\tv1 \"github.com/openshift/api/config/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype IdentityProviderLister interface {\n\tList(selector labels.Selector) (ret []*v1.IdentityProvider, err error)\n\tGet(name string) (*v1.IdentityProvider, error)\n\tIdentityProviderListerExpansion\n}\n\n\ntype identityProviderLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewIdentityProviderLister(indexer cache.Indexer) IdentityProviderLister {\n\treturn &identityProviderLister{indexer: indexer}\n}\n\n\n\n\n\nfunc (s *identityProviderLister) Get(name string) (*v1.IdentityProvider, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"identityprovider\"), name)\n\t}\n\treturn obj.(*v1.IdentityProvider), nil\n}\n\nfunc (s *identityProviderLister) List(selector labels.Selector) (ret []*v1.IdentityProvider, err error) ", "output": "{\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.IdentityProvider))\n\t})\n\treturn ret, err\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetServiceRequest struct {\n\n\tServiceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"serviceId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetServiceRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request GetServiceRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request GetServiceRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetServiceRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetServiceResponse struct {\n\n\tRawResponse *http.Response\n\n\tService `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetServiceResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response GetServiceResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package dbfiles\n\nimport (\n\t\"encoding/csv\"\n\t\"io\"\n\n\t\"github.com/juju/errgo\"\n)\n\ntype Driver interface {\n\tExtention() string\n\tWrite(io.Writer, []string) error\n\tRead(io.Reader) ([][]string, error)\n}\n\ntype CSV struct{}\n\nfunc (driver CSV) Extention() string {\n\treturn \"csv\"\n}\n\n\n\nfunc (driver CSV) Read(reader io.Reader) ([][]string, error) {\n\tcsvreader := csv.NewReader(reader)\n\tcsvreader.FieldsPerRecord = -1\n\n\tvar values [][]string\n\n\tvalues, err := csvreader.ReadAll()\n\tif err != nil {\n\t\treturn nil, errgo.Notef(err, \"can not read all records from file\")\n\t}\n\n\treturn values, nil\n}\n\nfunc (driver CSV) Write(writer io.Writer, values []string) error ", "output": "{\n\tcsvwriter := csv.NewWriter(writer)\n\n\terr := csvwriter.WriteAll([][]string{values})\n\tif err != nil {\n\t\treturn errgo.Notef(err, \"can not write to csv writer\")\n\t}\n\n\treturn nil\n}"} {"input": "package model\n\nimport \"time\"\n\ntype folder struct {\n\tstateTracker\n\tscan folderscan\n\tmodel *Model\n\tstop chan struct{}\n}\n\nfunc (f *folder) IndexUpdated() {\n}\n\n\n\nfunc (f *folder) Scan(subdirs []string) error {\n\treturn f.scan.Scan(subdirs)\n}\nfunc (f *folder) Stop() {\n\tclose(f.stop)\n}\n\nfunc (f *folder) Jobs() ([]string, []string) {\n\treturn nil, nil\n}\n\nfunc (f *folder) BringToFront(string) {}\n\nfunc (f *folder) scanSubdirsIfHealthy(subDirs []string) error {\n\tif err := f.model.CheckFolderHealth(f.folderID); err != nil {\n\t\tl.Infoln(\"Skipping folder\", f.folderID, \"scan due to folder error:\", err)\n\t\treturn err\n\t}\n\tl.Debugln(f, \"Scanning subdirectories\")\n\tif err := f.model.internalScanFolderSubdirs(f.folderID, subDirs); err != nil {\n\t\tf.setError(err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (f *folder) DelayScan(next time.Duration) ", "output": "{\n\tf.scan.Delay(next)\n}"} {"input": "package types\n\n\n\n\nimport (\n\t\"github.com/jcmturner/gofork/encoding/asn1\"\n)\n\n\n\n\nfunc NewKrbFlags() asn1.BitString {\n\tf := asn1.BitString{}\n\tf.Bytes = make([]byte, 4)\n\tf.BitLength = len(f.Bytes) * 8\n\treturn f\n}\n\n\nfunc SetFlags(f *asn1.BitString, j []int) {\n\tfor _, i := range j {\n\t\tSetFlag(f, i)\n\t}\n}\n\n\nfunc SetFlag(f *asn1.BitString, i int) {\n\tfor l := len(f.Bytes); l < 4; l++ {\n\t\t(*f).Bytes = append((*f).Bytes, byte(0))\n\t\t(*f).BitLength = len((*f).Bytes) * 8\n\t}\n\tb := i / 8\n\tp := uint(7 - (i - 8*b))\n\t(*f).Bytes[b] = (*f).Bytes[b] | (1 << p)\n}\n\n\nfunc UnsetFlags(f *asn1.BitString, j []int) {\n\tfor _, i := range j {\n\t\tUnsetFlag(f, i)\n\t}\n}\n\n\n\n\n\nfunc IsFlagSet(f *asn1.BitString, i int) bool {\n\tb := i / 8\n\tp := uint(7 - (i - 8*b))\n\tif (*f).Bytes[b]&(1<= 3 && sdata[2] == \"Z\" {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}"} {"input": "package treemap\n\nimport (\n\t\"github.com/emirpasic/gods/containers\"\n\trbt \"github.com/emirpasic/gods/trees/redblacktree\"\n)\n\nfunc assertIteratorImplementation() {\n\tvar _ containers.ReverseIteratorWithKey = (*Iterator)(nil)\n}\n\n\ntype Iterator struct {\n\titerator rbt.Iterator\n}\n\n\nfunc (m *Map) Iterator() Iterator {\n\treturn Iterator{iterator: m.tree.Iterator()}\n}\n\n\n\n\n\n\n\n\n\n\nfunc (iterator *Iterator) Prev() bool {\n\treturn iterator.iterator.Prev()\n}\n\n\n\nfunc (iterator *Iterator) Value() interface{} {\n\treturn iterator.iterator.Value()\n}\n\n\n\nfunc (iterator *Iterator) Key() interface{} {\n\treturn iterator.iterator.Key()\n}\n\n\n\nfunc (iterator *Iterator) Begin() {\n\titerator.iterator.Begin()\n}\n\n\n\nfunc (iterator *Iterator) End() {\n\titerator.iterator.End()\n}\n\n\n\n\nfunc (iterator *Iterator) First() bool {\n\treturn iterator.iterator.First()\n}\n\n\n\n\nfunc (iterator *Iterator) Last() bool {\n\treturn iterator.iterator.Last()\n}\n\nfunc (iterator *Iterator) Next() bool ", "output": "{\n\treturn iterator.iterator.Next()\n}"} {"input": "package log\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n)\n\nvar (\n\tinternalLog *logMux\n\tdebugMode bool\n)\n\n\n\n\n\ntype Sink interface {\n\tInfo(message string)\n\tWarning(message string)\n\tError(message string)\n\tDebug(message string)\n}\n\n\n\nfunc Info(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Info(fileMessage, v...)\n}\n\nfunc Warning(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Warning(fileMessage, v...)\n}\n\nfunc Errorf(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Error(fileMessage, v...)\n}\n\nfunc Debug(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Debug(fileMessage, v...)\n}\n\n\nfunc DebugMode(status bool) {\n\tinternalLog.DebugMode(status)\n\tdebugMode = status\n}\n\nfunc init() ", "output": "{\n\tinternalLog = NewMux()\n\tinternalLog.Add(NewSyslogSink())\n\tinternalLog.Add(NewColourisedTerminalSink())\n}"} {"input": "package fake\n\nimport (\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n\n\taction \"github.com/vmware-tanzu/octant/pkg/action\"\n)\n\n\ntype MockActionRegistrar struct {\n\tctrl *gomock.Controller\n\trecorder *MockActionRegistrarMockRecorder\n}\n\n\ntype MockActionRegistrarMockRecorder struct {\n\tmock *MockActionRegistrar\n}\n\n\nfunc NewMockActionRegistrar(ctrl *gomock.Controller) *MockActionRegistrar {\n\tmock := &MockActionRegistrar{ctrl: ctrl}\n\tmock.recorder = &MockActionRegistrarMockRecorder{mock}\n\treturn mock\n}\n\n\n\n\n\nfunc (m *MockActionRegistrar) Register(arg0, arg1 string, arg2 action.DispatcherFunc) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Register\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}\n\n\nfunc (mr *MockActionRegistrarMockRecorder) Register(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Register\", reflect.TypeOf((*MockActionRegistrar)(nil).Register), arg0, arg1, arg2)\n}\n\n\nfunc (m *MockActionRegistrar) Unregister(arg0, arg1 string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Unregister\", arg0, arg1)\n}\n\n\nfunc (mr *MockActionRegistrarMockRecorder) Unregister(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Unregister\", reflect.TypeOf((*MockActionRegistrar)(nil).Unregister), arg0, arg1)\n}\n\nfunc (m *MockActionRegistrar) EXPECT() *MockActionRegistrarMockRecorder ", "output": "{\n\treturn m.recorder\n}"} {"input": "package naivecheap\n\nimport \"github.com/ffloyd/evergrid-go/global/types\"\n\ntype byPriceAsc []types.WorkerInfo\n\nfunc (sw byPriceAsc) Len() int {\n\treturn len(sw)\n}\n\n\n\nfunc (sw byPriceAsc) Less(i, j int) bool {\n\treturn sw[i].PricePerTick < sw[j].PricePerTick \n}\n\ntype byQueueAsc []types.WorkerInfo\n\nfunc (sw byQueueAsc) Len() int {\n\treturn len(sw)\n}\n\nfunc (sw byQueueAsc) Swap(i, j int) {\n\tsw[i], sw[j] = sw[j], sw[i]\n}\n\nfunc (sw byQueueAsc) Less(i, j int) bool {\n\treturn sw[i].QueueLength < sw[j].QueueLength \n}\n\nfunc (sw byPriceAsc) Swap(i, j int) ", "output": "{\n\tsw[i], sw[j] = sw[j], sw[i]\n}"} {"input": "package meta\n\nimport (\n\t\"time\"\n\n\t\"github.com/messagedb/messagedb/toml\"\n)\n\nconst (\n\tDefaultHostname = \"localhost\"\n\n\tDefaultBindAddress = \":8076\"\n\n\tDefaultHeartbeatTimeout = 1000 * time.Millisecond\n\n\tDefaultElectionTimeout = 1000 * time.Millisecond\n\n\tDefaultLeaderLeaseTimeout = 500 * time.Millisecond\n\n\tDefaultCommitTimeout = 50 * time.Millisecond\n)\n\n\ntype Config struct {\n\tDir string `toml:\"dir\"`\n\tHostname string `toml:\"hostname\"`\n\tBindAddress string `toml:\"bind-address\"`\n\tPeers []string `toml:\"peers\"`\n\tRetentionAutoCreate bool `toml:\"retention-autocreate\"`\n\tElectionTimeout toml.Duration `toml:\"election-timeout\"`\n\tHeartbeatTimeout toml.Duration `toml:\"heartbeat-timeout\"`\n\tLeaderLeaseTimeout toml.Duration `toml:\"leader-lease-timeout\"`\n\tCommitTimeout toml.Duration `toml:\"commit-timeout\"`\n}\n\n\n\nfunc NewConfig() Config ", "output": "{\n\treturn Config{\n\t\tHostname: DefaultHostname,\n\t\tBindAddress: DefaultBindAddress,\n\t\tRetentionAutoCreate: true,\n\t\tElectionTimeout: toml.Duration(DefaultElectionTimeout),\n\t\tHeartbeatTimeout: toml.Duration(DefaultHeartbeatTimeout),\n\t\tLeaderLeaseTimeout: toml.Duration(DefaultLeaderLeaseTimeout),\n\t\tCommitTimeout: toml.Duration(DefaultCommitTimeout),\n\t}\n}"} {"input": "package lock\n\nimport (\n\t\"os\"\n)\n\ntype LockedFile interface {\n\tFile() *os.File\n\tExclusive() bool\n\tClose() error\n}\n\ntype DefaultLockedFile struct {\n\tf *os.File\n\texclusive bool\n}\n\nfunc OpenExclusive(path string, flag int, perm os.FileMode) (LockedFile, error) {\n\treturn open(path, flag, perm, true)\n}\n\nfunc OpenShared(path string, flag int, perm os.FileMode) (LockedFile, error) {\n\treturn open(path, flag, perm, false)\n}\n\n\n\nfunc (e *DefaultLockedFile) Exclusive() bool {\n\treturn e.exclusive\n}\n\nfunc (e *DefaultLockedFile) Close() error {\n\terr := e.unlock()\n\terr2 := e.f.Close()\n\tif err2 != nil && err == nil {\n\t\terr = err2\n\t}\n\treturn err\n}\n\nfunc (e *DefaultLockedFile) File() *os.File ", "output": "{\n\treturn e.f\n}"} {"input": "package signature\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha256\"\n\t\"log\"\n\n\t\"github.com/cloudfoundry/dropsonde/metrics\"\n)\n\nconst SIGNATURE_LENGTH = 32\n\n\n\ntype Verifier struct {\n\tsharedSecret string\n}\n\n\n\nfunc NewVerifier(sharedSecret string) *Verifier {\n\treturn &Verifier{\n\t\tsharedSecret: sharedSecret,\n\t}\n}\n\n\n\n\n\n\n\n\nfunc (v *Verifier) Run(inputChan <-chan []byte, outputChan chan<- []byte) {\n\tfor signedMessage := range inputChan {\n\t\tif len(signedMessage) < SIGNATURE_LENGTH {\n\t\t\tlog.Print(\"signatureVerifier: missing signature\")\n\t\t\tcontinue\n\t\t}\n\n\t\tsignature, message := signedMessage[:SIGNATURE_LENGTH], signedMessage[SIGNATURE_LENGTH:]\n\t\tif v.verifyMessage(message, signature) {\n\t\t\toutputChan <- message\n\t\t\tmetrics.BatchIncrementCounter(\"signatureVerifier.validSignatures\")\n\t\t} else {\n\t\t\tlog.Print(\"signatureVerifier: invalid signature\")\n\t\t}\n\t}\n}\n\n\n\n\n\nfunc SignMessage(message, secret []byte) []byte {\n\tsignature := generateSignature(message, secret)\n\treturn append(signature, message...)\n}\n\nfunc generateSignature(message, secret []byte) []byte {\n\tmac := hmac.New(sha256.New, secret)\n\tmac.Write(message)\n\treturn mac.Sum(nil)\n}\n\nfunc (v *Verifier) verifyMessage(message, signature []byte) bool ", "output": "{\n\texpectedMAC := generateSignature(message, []byte(v.sharedSecret))\n\treturn hmac.Equal(signature, expectedMAC)\n}"} {"input": "package podtopologyspread\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tframework \"k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1\"\n\tschedulerlisters \"k8s.io/kubernetes/pkg/scheduler/listers\"\n)\n\nconst (\n\tErrReasonConstraintsNotMatch = \"node(s) didn't match pod topology spread constraints\"\n)\n\n\ntype PodTopologySpread struct {\n\tsharedLister schedulerlisters.SharedLister\n}\n\nvar _ framework.PreFilterPlugin = &PodTopologySpread{}\nvar _ framework.FilterPlugin = &PodTopologySpread{}\nvar _ framework.PreScorePlugin = &PodTopologySpread{}\nvar _ framework.ScorePlugin = &PodTopologySpread{}\n\nconst (\n\tName = \"PodTopologySpread\"\n)\n\n\n\n\n\nfunc New(_ *runtime.Unknown, h framework.FrameworkHandle) (framework.Plugin, error) {\n\tif h.SnapshotSharedLister() == nil {\n\t\treturn nil, fmt.Errorf(\"SnapshotSharedlister is nil\")\n\t}\n\treturn &PodTopologySpread{sharedLister: h.SnapshotSharedLister()}, nil\n}\n\nfunc (pl *PodTopologySpread) Name() string ", "output": "{\n\treturn Name\n}"} {"input": "package vanity\n\nimport (\n\t\"github.com/gogo/protobuf/gogoproto\"\n\t\"github.com/gogo/protobuf/proto\"\n\tdescriptor \"github.com/gogo/protobuf/protoc-gen-gogo/descriptor\"\n)\n\nfunc FieldHasBoolExtension(field *descriptor.FieldDescriptorProto, extension *proto.ExtensionDesc) bool {\n\tif field.Options == nil {\n\t\treturn false\n\t}\n\tvalue, err := proto.GetExtension(field.Options, extension)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif value == nil {\n\t\treturn false\n\t}\n\tif value.(*bool) == nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc SetBoolFieldOption(extension *proto.ExtensionDesc, value bool) func(field *descriptor.FieldDescriptorProto) {\n\treturn func(field *descriptor.FieldDescriptorProto) {\n\t\tif FieldHasBoolExtension(field, extension) {\n\t\t\treturn\n\t\t}\n\t\tif field.Options == nil {\n\t\t\tfield.Options = &descriptor.FieldOptions{}\n\t\t}\n\t\tif err := proto.SetExtension(field.Options, extension, &value); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\nfunc TurnOffNullable(field *descriptor.FieldDescriptorProto) {\n\tif field.IsRepeated() && !field.IsMessage() {\n\t\treturn\n\t}\n\tSetBoolFieldOption(gogoproto.E_Nullable, false)(field)\n}\n\n\n\nfunc TurnOffNullableForNativeTypesWithoutDefaultsOnly(field *descriptor.FieldDescriptorProto) ", "output": "{\n\tif field.IsRepeated() || field.IsMessage() {\n\t\treturn\n\t}\n\tif field.DefaultValue != nil {\n\t\treturn\n\t}\n\tSetBoolFieldOption(gogoproto.E_Nullable, false)(field)\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net/url\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n\n\nfunc main() {\n\tvar path, method string\n\tflag.StringVar(&path, \"f\", \"\", \"Specify the file name or path name to be processed\")\n\tflag.StringVar(&method, \"m\", \"unescape\", \"Specify the operation: \\\"escape\\\" or \\\"unescape\\\"\")\n\tflag.Parse()\n\n\tvar convert = func(string) string { return \"\" }\n\tswitch method {\n\tcase \"escape\":\n\t\tconvert = url.QueryEscape\n\tcase \"unescape\":\n\t\tconvert = unescape\n\tdefault:\n\t\tfmt.Println(\"Unknown operation:\", method)\n\t\treturn\n\t}\n\n\tpargs := flag.Args()\n\tif len(pargs) != 0 {\n\t\tpath = pargs[0]\n\t}\n\n\tif len(path) == 0 {\n\t\tstdin := bufio.NewReader(os.Stdin)\n\t\tvar line string\n\t\tvar err error\n\n\t\tfor {\n\t\t\tif line, err = stdin.ReadString('\\n'); err == nil {\n\t\t\t\tfmt.Println(convert(strings.TrimSuffix(line, \"\\r\\n\")))\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif _, err := os.Stat(path); err != nil {\n\t\t\tfmt.Printf(\"File or path \\\"%s\\\" doesn't exist.\\n\", path)\n\t\t\treturn\n\t\t}\n\n\t\thead, tail := filepath.Split(path)\n\t\tnewpath := filepath.Join(head, convert(tail))\n\t\tif newpath != path {\n\t\t\tos.Rename(path, newpath)\n\t\t\tfmt.Println(path, \"->\", newpath)\n\t\t}\n\t}\n}\n\nfunc unescape(s string) string ", "output": "{\n\tnormname, err := url.QueryUnescape(s)\n\tif err == nil {\n\t\treturn normname\n\t} else {\n\t\tfmt.Println(err)\n\t\treturn s\n\t}\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\ntype StepDownCommand struct {\n\tMeta\n}\n\nfunc (c *StepDownCommand) Run(args []string) int {\n\tflags := c.Meta.FlagSet(\"step-down\", FlagSetDefault)\n\tflags.Usage = func() { c.Ui.Error(c.Help()) }\n\tif err := flags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tclient, err := c.Client()\n\tif err != nil {\n\t\tc.Ui.Error(fmt.Sprintf(\n\t\t\t\"Error initializing client: %s\", err))\n\t\treturn 2\n\t}\n\n\tif err := client.Sys().StepDown(); err != nil {\n\t\tc.Ui.Error(fmt.Sprintf(\"Error stepping down: %s\", err))\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n\nfunc (c *StepDownCommand) Synopsis() string {\n\treturn \"Force the Vault node to give up active duty\"\n}\n\n\n\nfunc (c *StepDownCommand) Help() string ", "output": "{\n\thelpText := `\nUsage: vault step-down [options]\n\n Force the Vault node to step down from active duty.\n\n This causes the indicated node to give up active status. Note that while the\n affected node will have a short delay before attempting to grab the lock\n again, if no other node grabs the lock beforehand, it is possible for the\n same node to re-grab the lock and become active again.\n\nGeneral Options:\n\n ` + generalOptionsUsage()\n\treturn strings.TrimSpace(helpText)\n}"} {"input": "package leet_901\n\ntype StockSpanner struct {\n\tf []int\n\tprice []int\n}\n\n\n\nfunc (this *StockSpanner) Next(price int) int {\n\tthis.price = append(this.price, price)\n\tif len(this.f) == 0 {\n\t\tthis.f = append(this.f, 1)\n\t\treturn 1\n\t}\n\tans := 1\n\ti := len(this.price) - 2\n\tfor i >= 0 && this.price[i] <= price {\n\t\tans += this.f[i]\n\t\ti -= this.f[i]\n\t}\n\tthis.f = append(this.f, ans)\n\treturn ans\n}\n\nfunc Constructor() StockSpanner ", "output": "{\n\treturn StockSpanner{}\n}"} {"input": "package lifecycle\n\nimport (\n\t\"encoding/xml\"\n)\n\n\ntype NoncurrentVersionExpiration struct {\n\tXMLName xml.Name `xml:\"NoncurrentVersionExpiration\"`\n\tNoncurrentDays ExpirationDays `xml:\"NoncurrentDays,omitempty\"`\n}\n\n\ntype NoncurrentVersionTransition struct {\n\tNoncurrentDays ExpirationDays `xml:\"NoncurrentDays\"`\n\tStorageClass string `xml:\"StorageClass\"`\n}\n\nvar (\n\terrNoncurrentVersionTransitionUnsupported = Errorf(\"Specifying is not supported\")\n)\n\n\n\n\n\nfunc (n NoncurrentVersionExpiration) IsDaysNull() bool {\n\treturn n.NoncurrentDays == ExpirationDays(0)\n}\n\n\n\n\nfunc (n NoncurrentVersionTransition) UnmarshalXML(d *xml.Decoder, startElement xml.StartElement) error {\n\treturn errNoncurrentVersionTransitionUnsupported\n}\n\n\n\nfunc (n NoncurrentVersionTransition) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tif n.NoncurrentDays == ExpirationDays(0) {\n\t\treturn nil\n\t}\n\treturn e.EncodeElement(&n, start)\n}\n\nfunc (n NoncurrentVersionExpiration) MarshalXML(e *xml.Encoder, start xml.StartElement) error ", "output": "{\n\tif n.IsDaysNull() {\n\t\treturn nil\n\t}\n\ttype noncurrentVersionExpirationWrapper NoncurrentVersionExpiration\n\treturn e.EncodeElement(noncurrentVersionExpirationWrapper(n), start)\n}"} {"input": "package manual_test\n\nimport (\n\t\"testing\"\n\n\tgc \"launchpad.net/gocheck\"\n\n\t\"github.com/juju/core/environs/storage\"\n\t\"github.com/juju/core/provider/manual\"\n)\n\n\n\nfunc Test(t *testing.T) ", "output": "{\n\t*manual.NewSSHStorage = func(sshHost, storageDir, storageTmpdir string) (storage.Storage, error) {\n\t\treturn nil, nil\n\t}\n\tgc.TestingT(t)\n}"} {"input": "package x509\n\nimport (\n\t\"encoding/pem\"\n)\n\n\ntype CertPool struct {\n\tbySubjectKeyId map[string][]int\n\tbyName map[string][]int\n\tcerts []*Certificate\n}\n\n\nfunc NewCertPool() *CertPool {\n\treturn &CertPool{\n\t\tmake(map[string][]int),\n\t\tmake(map[string][]int),\n\t\tnil,\n\t}\n}\n\n\n\n\nfunc (s *CertPool) findVerifiedParents(cert *Certificate) (parents []int) {\n\tif s == nil {\n\t\treturn\n\t}\n\tvar candidates []int\n\n\tif len(cert.AuthorityKeyId) > 0 {\n\t\tcandidates = s.bySubjectKeyId[string(cert.AuthorityKeyId)]\n\t}\n\tif len(candidates) == 0 {\n\t\tcandidates = s.byName[string(cert.RawIssuer)]\n\t}\n\n\tfor _, c := range candidates {\n\t\tif cert.CheckSignatureFrom(s.certs[c]) == nil {\n\t\t\tparents = append(parents, c)\n\t\t}\n\t}\n\n\treturn\n}\n\n\n\n\n\n\n\n\n\n\nfunc (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool) {\n\tfor len(pemCerts) > 0 {\n\t\tvar block *pem.Block\n\t\tblock, pemCerts = pem.Decode(pemCerts)\n\t\tif block == nil {\n\t\t\tbreak\n\t\t}\n\t\tif block.Type != \"CERTIFICATE\" || len(block.Headers) != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tcert, err := ParseCertificate(block.Bytes)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\ts.AddCert(cert)\n\t\tok = true\n\t}\n\n\treturn\n}\n\nfunc (s *CertPool) AddCert(cert *Certificate) ", "output": "{\n\tif cert == nil {\n\t\tpanic(\"adding nil Certificate to CertPool\")\n\t}\n\n\tfor _, c := range s.certs {\n\t\tif c.Equal(cert) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tn := len(s.certs)\n\ts.certs = append(s.certs, cert)\n\n\tif len(cert.SubjectKeyId) > 0 {\n\t\tkeyId := string(cert.SubjectKeyId)\n\t\ts.bySubjectKeyId[keyId] = append(s.bySubjectKeyId[keyId], n)\n\t}\n\tname := string(cert.RawSubject)\n\ts.byName[name] = append(s.byName[name], n)\n}"} {"input": "package primitives\n\nimport (\n \"fmt\"\n . \"github.com/kedebug/LispEx/value\"\n \"math/rand\"\n \"time\"\n)\n\ntype Random struct {\n Primitive\n rand *rand.Rand\n}\n\nfunc NewRandom() *Random {\n r := rand.New(rand.NewSource(time.Now().UnixNano()))\n return &Random{Primitive: Primitive{\"random\"}, rand: r}\n}\n\n\n\nfunc (self *Random) Apply(args []Value) Value ", "output": "{\n if len(args) != 1 {\n panic(fmt.Sprint(\"random: argument mismatch, expected 1\"))\n }\n if val, ok := args[0].(*IntValue); ok {\n if val.Value <= 0 {\n panic(fmt.Sprint(\"random: expected positive integer, given: \", val))\n }\n return NewIntValue(self.rand.Int63n(val.Value))\n }\n panic(fmt.Sprint(\"random: expected integer?, given: \", args[0]))\n}"} {"input": "package keybindings\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/atotto/clipboard\"\n\t\"github.com/dambrisco/bored/layout\"\n\t\"github.com/dambrisco/bored/reddit\"\n\t\"github.com/jroimartin/gocui\"\n\t\"github.com/toqueteos/webbrowser\"\n)\n\nfunc enter(g *gocui.Gui, v *gocui.View) error {\n\tsubmission := reddit.GetCurrentSubmission()\n\twebbrowser.Open(\"https://www.reddit.com/\" + submission.Permalink)\n\treturn nil\n}\n\n\n\nfunc yank(g *gocui.Gui, v *gocui.View) error {\n\tsubmission := reddit.GetCurrentSubmission()\n\tclipboard.WriteAll(submission.URL)\n\treturn nil\n}\n\nfunc comments(g *gocui.Gui, v *gocui.View) error {\n\tlayout.SetPage(layout.Comments)\n\tlayout.Clear(g, v)\n\treturn nil\n}\n\nfunc info(g *gocui.Gui, v *gocui.View) error {\n\tif layout.GetPage() == layout.List {\n\t\ts := reddit.GetCurrentSubmission()\n\t\tb := v.Buffer()\n\t\tv.Clear()\n\t\tif strings.HasPrefix(b, \"S\") {\n\t\t\tfmt.Fprint(v, layout.BuildTitleTag(s))\n\t\t} else {\n\t\t\tfmt.Fprintf(v, \"Score: %d | Subreddit: %s\", s.Score, s.Subreddit)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc link(g *gocui.Gui, v *gocui.View) error ", "output": "{\n\tsubmission := reddit.GetCurrentSubmission()\n\twebbrowser.Open(submission.URL)\n\treturn nil\n}"} {"input": "package mapka\n\nimport (\n\t\"strings\"\n\n\t\"klogproc/load/accesslog\"\n)\n\nfunc getAction(path string) (string, *RequestParams) {\n\tvar params *RequestParams\n\tif strings.HasPrefix(path, \"/mapka\") {\n\t\telms := strings.Split(strings.Trim(path, \"/\"), \"/\")\n\t\tif len(elms) > 1 {\n\t\t\tif elms[1] == \"text\" {\n\t\t\t\tif len(elms) >= 4 {\n\t\t\t\t\tparams = &RequestParams{\n\t\t\t\t\t\tCardType: &elms[2],\n\t\t\t\t\t\tCardFolder: &elms[3],\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn elms[1], params\n\n\t\t\t} else if elms[1] == \"overlay\" {\n\t\t\t\tif len(elms) >= 3 {\n\t\t\t\t\tsub := strings.Split(elms[2], \"+\")\n\t\t\t\t\tparams = &RequestParams{\n\t\t\t\t\t\tOverlayFile: &sub[len(sub)-1],\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn elms[1], params\n\t\t\t}\n\t\t\treturn \"\", nil\n\t\t}\n\t\treturn \"index\", params\n\t}\n\treturn \"\", params\n}\n\n\ntype LineParser struct {\n\tparser accesslog.LineParser\n}\n\n\n\n\nfunc (lp *LineParser) ParseLine(s string, lineNum int64) (*InputRecord, error) ", "output": "{\n\tparsed, err := lp.parser.ParseLine(s, lineNum)\n\tif err != nil {\n\t\treturn &InputRecord{isProcessable: false}, err\n\t}\n\n\taction, params := getAction(parsed.Path)\n\tif action == \"\" {\n\t\treturn &InputRecord{isProcessable: false}, nil\n\t}\n\tans := &InputRecord{\n\t\tisProcessable: strings.HasPrefix(parsed.Path, \"/mapka\"),\n\t\tAction: action,\n\t\tPath: parsed.Path,\n\t\tDatetime: parsed.Datetime,\n\t\tRequest: &Request{\n\t\t\tHTTPUserAgent: parsed.UserAgent,\n\t\t\tHTTPRemoteAddr: parsed.IPAddress,\n\t\t\tRemoteAddr: parsed.IPAddress, \n\t\t},\n\t\tParams: params,\n\t\tProcTime: parsed.ProcTime,\n\t}\n\treturn ans, nil\n}"} {"input": "package collector\n\nimport (\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\ntype conntrackCollector struct {\n\tcurrent *prometheus.Desc\n\tlimit *prometheus.Desc\n}\n\nfunc init() {\n\tFactories[\"conntrack\"] = NewConntrackCollector\n}\n\n\n\n\n\nfunc (c *conntrackCollector) Update(ch chan<- prometheus.Metric) (err error) {\n\tvalue, err := readUintFromFile(procFilePath(\"sys/net/netfilter/nf_conntrack_count\"))\n\tif err != nil {\n\t\treturn nil\n\t}\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.current, prometheus.GaugeValue, float64(value))\n\n\tvalue, err = readUintFromFile(procFilePath(\"sys/net/netfilter/nf_conntrack_max\"))\n\tif err != nil {\n\t\treturn nil\n\t}\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.limit, prometheus.GaugeValue, float64(value))\n\n\treturn nil\n}\n\nfunc NewConntrackCollector() (Collector, error) ", "output": "{\n\treturn &conntrackCollector{\n\t\tcurrent: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(Namespace, \"\", \"nf_conntrack_entries\"),\n\t\t\t\"Number of currently allocated flow entries for connection tracking.\",\n\t\t\tnil, nil,\n\t\t),\n\t\tlimit: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(Namespace, \"\", \"nf_conntrack_entries_limit\"),\n\t\t\t\"Maximum size of connection tracking table.\",\n\t\t\tnil, nil,\n\t\t),\n\t}, nil\n}"} {"input": "package pool\n\nimport \"sync/atomic\"\n\n\ntype WorkUnit interface {\n\n\tWait()\n\n\tValue() interface{}\n\n\tError() error\n\n\tCancel()\n\n\tIsCancelled() bool\n}\n\nvar _ WorkUnit = new(workUnit)\n\n\ntype workUnit struct {\n\tvalue interface{}\n\terr error\n\tdone chan struct{}\n\tfn WorkFunc\n\tcancelled atomic.Value\n\tcancelling atomic.Value\n\twriting atomic.Value\n}\n\n\nfunc (wu *workUnit) Cancel() {\n\twu.cancelWithError(&ErrCancelled{s: errCancelled})\n}\n\nfunc (wu *workUnit) cancelWithError(err error) {\n\n\twu.cancelling.Store(struct{}{})\n\n\tif wu.writing.Load() == nil && wu.cancelled.Load() == nil {\n\t\twu.cancelled.Store(struct{}{})\n\t\twu.err = err\n\t\tclose(wu.done)\n\t}\n}\n\n\n\n\n\nfunc (wu *workUnit) Value() interface{} {\n\treturn wu.value\n}\n\n\nfunc (wu *workUnit) Error() error {\n\treturn wu.err\n}\n\n\n\n\nfunc (wu *workUnit) IsCancelled() bool {\n\twu.writing.Store(struct{}{}) \n\treturn wu.cancelled.Load() != nil\n}\n\nfunc (wu *workUnit) Wait() ", "output": "{\n\t<-wu.done\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/bfontaine/go-tchoutchou/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n)\n\ntype SucceedMatcher struct {\n}\n\nfunc (matcher *SucceedMatcher) Match(actual interface{}) (success bool, err error) {\n\tif actual == nil {\n\t\treturn true, nil\n\t}\n\n\tif isError(actual) {\n\t\treturn false, nil\n\t}\n\n\treturn false, fmt.Errorf(\"Expected an error-type. Got:\\n%s\", format.Object(actual, 1))\n}\n\n\n\nfunc (matcher *SucceedMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn \"Expected failure, but got no error.\"\n}\n\nfunc (matcher *SucceedMatcher) FailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn fmt.Sprintf(\"Expected success, but got an error:\\n%s\", format.Object(actual, 1))\n}"} {"input": "package internal\n\nvar crypters = []Crypter{\n\tKMSCrypter{},\n\tLocalCrypter{},\n\tPlainCrypter{},\n\tPasswordCrypter{},\n}\n\n\nvar CryptersMap map[string]Crypter\n\n\ntype Ciphertext string\n\n\ntype EncryptParams map[string]string\n\n\ntype DecryptParams map[string]string\n\n\ntype Crypter interface {\n\tName() string\n\tEncrypt(string, EncryptParams) (Ciphertext, DecryptParams, error)\n\tDecrypt(Ciphertext, DecryptParams) (string, error)\n}\n\n\n\nfunc init() ", "output": "{\n\tCryptersMap = make(map[string]Crypter)\n\tfor _, crypter := range crypters {\n\t\tCryptersMap[crypter.Name()] = crypter\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateNatGatewayRequest struct {\n\n\tCreateNatGatewayDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateNatGatewayRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request CreateNatGatewayRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CreateNatGatewayRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateNatGatewayResponse struct {\n\n\tRawResponse *http.Response\n\n\tNatGateway `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateNatGatewayResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateNatGatewayResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateNatGatewayRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package auth\n\nimport (\n\t\"sync\"\n\n\t\"github.com/google/martian/session\"\n)\n\nconst key = \"auth.Context\"\n\n\ntype Context struct {\n\tmu sync.RWMutex\n\tid string\n\terr error\n}\n\n\n\n\n\nfunc (ctx *Context) ID() string {\n\tctx.mu.RLock()\n\tctx.mu.RUnlock()\n\n\treturn ctx.id\n}\n\n\nfunc (ctx *Context) SetID(id string) {\n\tctx.mu.Lock()\n\tctx.mu.Unlock()\n\n\tctx.err = nil\n\n\tif id == \"\" {\n\t\treturn\n\t}\n\n\tctx.id = id\n}\n\n\nfunc (ctx *Context) SetError(err error) {\n\tctx.mu.Lock()\n\tdefer ctx.mu.Unlock()\n\n\tctx.id = \"\"\n\tctx.err = err\n}\n\n\nfunc (ctx *Context) Error() error {\n\tctx.mu.RLock()\n\tdefer ctx.mu.RUnlock()\n\n\treturn ctx.err\n}\n\nfunc FromContext(ctx *session.Context) *Context ", "output": "{\n\tif v, ok := ctx.GetSession().Get(key); ok {\n\t\treturn v.(*Context)\n\t}\n\n\tactx := &Context{}\n\tctx.GetSession().Set(key, actx)\n\n\treturn actx\n}"} {"input": "package admission\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\n\t\"github.com/golang/glog\"\n\tclient \"k8s.io/kubernetes/pkg/client/unversioned\"\n)\n\n\n\n\n\ntype Factory func(client client.Interface, config io.Reader) (Interface, error)\n\n\nvar (\n\tpluginsMutex sync.Mutex\n\tplugins = make(map[string]Factory)\n)\n\n\nfunc GetPlugins() []string {\n\tpluginsMutex.Lock()\n\tdefer pluginsMutex.Unlock()\n\tkeys := []string{}\n\tfor k := range plugins {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}\n\n\n\n\n\n\n\n\n\n\nfunc GetPlugin(name string, client client.Interface, config io.Reader) (Interface, error) {\n\tpluginsMutex.Lock()\n\tdefer pluginsMutex.Unlock()\n\tf, found := plugins[name]\n\tif !found {\n\t\treturn nil, nil\n\t}\n\treturn f(client, config)\n}\n\n\nfunc InitPlugin(name string, client client.Interface, configFilePath string) Interface {\n\tvar (\n\t\tconfig *os.File\n\t\terr error\n\t)\n\n\tif name == \"\" {\n\t\tglog.Info(\"No admission plugin specified.\")\n\t\treturn nil\n\t}\n\n\tif configFilePath != \"\" {\n\t\tconfig, err = os.Open(configFilePath)\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"Couldn't open admission plugin configuration %s: %#v\",\n\t\t\t\tconfigFilePath, err)\n\t\t}\n\n\t\tdefer config.Close()\n\t}\n\n\tplugin, err := GetPlugin(name, client, config)\n\tif err != nil {\n\t\tglog.Fatalf(\"Couldn't init admission plugin %q: %v\", name, err)\n\t}\n\tif plugin == nil {\n\t\tglog.Fatalf(\"Unknown admission plugin: %s\", name)\n\t}\n\n\treturn plugin\n}\n\nfunc RegisterPlugin(name string, plugin Factory) ", "output": "{\n\tpluginsMutex.Lock()\n\tdefer pluginsMutex.Unlock()\n\t_, found := plugins[name]\n\tif found {\n\t\tglog.Fatalf(\"Admission plugin %q was registered twice\", name)\n\t}\n\tglog.V(1).Infof(\"Registered admission plugin %q\", name)\n\tplugins[name] = plugin\n}"} {"input": "package path\n\nimport (\n\t\"reflect\"\n)\n\n\n\n\nfunc (path P) Read(obj, dest interface{}) (err error) {\n\tvalue := reflect.ValueOf(dest)\n\n\tif value.Kind() == reflect.Ptr {\n\t\tvalue = value.Elem()\n\t}\n\n\tif !value.CanSet() {\n\t\tpanic(\"dest must be setable\")\n\t}\n\n\tfn := func(_ P, ctx *Context) (bool, error) {\n\n\t\tfor result := ctx.Value(); ; result = result.Elem() {\n\n\t\t\tif result.Type().ConvertibleTo(value.Type()) {\n\t\t\t\tresult = result.Convert(value.Type())\n\t\t\t}\n\n\t\t\tif result.Type().AssignableTo(value.Type()) {\n\t\t\t\tvalue.Set(result)\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tif result.Kind() != reflect.Interface && result.Kind() != reflect.Ptr {\n\t\t\t\treturn false, ErrInvalidType\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn path.Apply(obj, &Context{Fn: fn})\n}\n\n\n\n\n\n\nfunc (path P) ReadAll(obj, dest interface{}) (interface{}, error) ", "output": "{\n\tvalue := reflect.ValueOf(dest)\n\n\tif value.Kind() != reflect.Slice {\n\t\tpanic(\"can only read slice values\")\n\t}\n\n\telem := value.Type().Elem()\n\n\tfn := func(_ P, ctx *Context) (bool, error) {\n\n\t\tfor result := ctx.Value(); ; result = result.Elem() {\n\n\t\t\tif result.Type().ConvertibleTo(elem) {\n\t\t\t\tresult = result.Convert(elem)\n\t\t\t}\n\n\t\t\tif result.Type().AssignableTo(elem) {\n\t\t\t\tvalue = reflect.Append(value, result)\n\t\t\t\treturn true, nil\n\t\t\t}\n\n\t\t\tif result.Kind() != reflect.Interface && result.Kind() != reflect.Ptr {\n\t\t\t\treturn false, ErrInvalidType\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn value, path.Apply(obj, &Context{Fn: fn})\n}"} {"input": "package framework\n\nimport \"github.com/onsi/gomega\"\n\n\nfunc ExpectEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.Equal(extra), explain...)\n}\n\n\nfunc ExpectNotEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).NotTo(gomega.Equal(extra), explain...)\n}\n\n\nfunc ExpectError(err error, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, err).To(gomega.HaveOccurred(), explain...)\n}\n\n\nfunc ExpectNoError(err error, explain ...interface{}) {\n\tExpectNoErrorWithOffset(1, err, explain...)\n}\n\n\n\nfunc ExpectNoErrorWithOffset(offset int, err error, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1+offset, err).NotTo(gomega.HaveOccurred(), explain...)\n}\n\n\n\n\n\nfunc ExpectHaveKey(actual interface{}, key interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.HaveKey(key), explain...)\n}\n\n\nfunc ExpectEmpty(actual interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.BeEmpty(), explain...)\n}\n\nfunc ExpectConsistOf(actual interface{}, extra interface{}, explain ...interface{}) ", "output": "{\n\tgomega.ExpectWithOffset(1, actual).To(gomega.ConsistOf(extra), explain...)\n}"} {"input": "package util\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestBufferPool(t *testing.T) ", "output": "{\n\tbuff := GetBuffer()\n\tbuff.WriteString(\"do be do be do\")\n\tassert.Equal(t, \"do be do be do\", buff.String())\n\tPutBuffer(buff)\n\tassert.Equal(t, 0, buff.Len())\n}"} {"input": "package requirements\n\nimport (\n\t\"github.com/cloudfoundry/cli/cf/api\"\n\t\"github.com/cloudfoundry/cli/cf/models\"\n)\n\ntype BuildpackRequirement interface {\n\tRequirement\n\tGetBuildpack() models.Buildpack\n}\n\ntype buildpackApiRequirement struct {\n\tname string\n\tbuildpackRepo api.BuildpackRepository\n\tbuildpack models.Buildpack\n}\n\n\n\nfunc (req *buildpackApiRequirement) Execute() error {\n\tvar apiErr error\n\treq.buildpack, apiErr = req.buildpackRepo.FindByName(req.name)\n\n\tif apiErr != nil {\n\t\treturn apiErr\n\t}\n\n\treturn nil\n}\n\nfunc (req *buildpackApiRequirement) GetBuildpack() models.Buildpack {\n\treturn req.buildpack\n}\n\nfunc NewBuildpackRequirement(name string, bR api.BuildpackRepository) (req *buildpackApiRequirement) ", "output": "{\n\treq = new(buildpackApiRequirement)\n\treq.name = name\n\treq.buildpackRepo = bR\n\treturn\n}"} {"input": "package influxdb\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"testing\"\n\t\"time\"\n\n\t\"go.k6.io/k6/stats\"\n)\n\nfunc benchmarkInfluxdb(b *testing.B, t time.Duration) {\n\ttestOutputCycle(b, func(rw http.ResponseWriter, r *http.Request) {\n\t\tfor {\n\t\t\ttime.Sleep(t)\n\t\t\tm, _ := io.CopyN(ioutil.Discard, r.Body, 1<<18) \n\t\t\tif m == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\trw.WriteHeader(204)\n\t}, func(tb testing.TB, c *Output) {\n\t\tb = tb.(*testing.B)\n\t\tb.ResetTimer()\n\n\t\tsamples := make(stats.Samples, 10)\n\t\tfor i := 0; i < len(samples); i++ {\n\t\t\tsamples[i] = stats.Sample{\n\t\t\t\tMetric: stats.New(\"testGauge\", stats.Gauge),\n\t\t\t\tTime: time.Now(),\n\t\t\t\tTags: stats.NewSampleTags(map[string]string{\n\t\t\t\t\t\"something\": \"else\",\n\t\t\t\t\t\"VU\": \"21\",\n\t\t\t\t\t\"else\": \"something\",\n\t\t\t\t}),\n\t\t\t\tValue: 2.0,\n\t\t\t}\n\t\t}\n\n\t\tb.ResetTimer()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tc.AddMetricSamples([]stats.SampleContainer{samples})\n\t\t\ttime.Sleep(time.Nanosecond * 20)\n\t\t}\n\t})\n}\n\nfunc BenchmarkInfluxdb1Second(b *testing.B) {\n\tbenchmarkInfluxdb(b, time.Second)\n}\n\nfunc BenchmarkInfluxdb2Second(b *testing.B) {\n\tbenchmarkInfluxdb(b, 2*time.Second)\n}\n\n\n\nfunc BenchmarkInfluxdb100Milliseconds(b *testing.B) ", "output": "{\n\tbenchmarkInfluxdb(b, 100*time.Millisecond)\n}"} {"input": "package store\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"text/tabwriter\"\n\t\"time\"\n)\n\ntype Metadata map[string]string\n\ntype Entry struct {\n\tName string `json:\"name\"`\n\tPassword []byte `json:\"password\"`\n\tCtime time.Time `json:\"ctime\"` \n\tMtime time.Time `json:\"mtime\"` \n\tMetadata Metadata `json:\"metadata\"` \n}\n\nfunc NewEntry() *Entry {\n\treturn &Entry{\n\t\tMetadata: make(Metadata),\n\t\tCtime: getCurrentTime(),\n\t\tMtime: getCurrentTime(),\n\t}\n}\n\nfunc (e *Entry) Age() time.Duration {\n\treturn time.Since(e.Mtime)\n}\n\nfunc (e *Entry) Touch() {\n\te.Mtime = getCurrentTime()\n}\n\n\n\nfunc (m Metadata) String() string {\n\tvar b bytes.Buffer\n\tfor k, v := range m {\n\t\tfmt.Fprintf(&b, \"%s:%s\", k, v)\n\t}\n\treturn b.String()\n}\n\nfunc getCurrentTime() time.Time {\n\treturn time.Now().Truncate(time.Second)\n}\n\nfunc (e Entry) String() string ", "output": "{\n\tb := new(bytes.Buffer)\n\tw := tabwriter.NewWriter(b, 0, 0, 0, ' ', 0)\n\n\tvalof := reflect.ValueOf(e)\n\tfor i := 0; i < valof.NumField(); i++ {\n\t\tswitch val := valof.Field(i).Interface().(type) {\n\t\tdefault:\n\t\t\ttag := valof.Type().Field(i).Tag.Get(\"json\")\n\t\t\tfmt.Fprintf(w, \"%s\\t : %s\\n\", tag, val)\n\t\tcase Metadata:\n\t\t\tfor k, v := range val {\n\t\t\t\tfmt.Fprintf(w, \"%s\\t : %s\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\n\tw.Flush()\n\treturn b.String()\n}"} {"input": "package events\n\nimport (\n\t\"errors\"\n\n\t\"github.com/miketheprogrammer/go-thrust/lib/commands\"\n\t\"github.com/miketheprogrammer/go-thrust/lib/dispatcher\"\n)\n\n\n\n\n\ntype Handler interface {\n\tHandle(cr commands.CommandResponse)\n\tRegister()\n\tSetHandleFunc(fn interface{})\n}\n\ntype ThrustEventHandler struct {\n\tType string\n\tEvent string\n\tHandler interface{}\n}\n\nfunc (teh ThrustEventHandler) Handle(cr commands.CommandResponse) {\n\tif cr.Action != \"event\" {\n\t\treturn\n\t}\n\tif cr.Type != teh.Event && teh.Event != \"*\" {\n\t\treturn\n\t}\n\tcr.Event.Type = cr.Type\n\tif fn, ok := teh.Handler.(func(commands.CommandResponse)); ok == true {\n\t\tfn(cr)\n\t\treturn\n\t}\n\tif fn, ok := teh.Handler.(func(commands.EventResult)); ok == true {\n\t\tfn(cr.Event)\n\t\treturn\n\t}\n}\n\nfunc (teh *ThrustEventHandler) SetHandleFunc(fn interface{}) error {\n\tif fn, ok := fn.(func(commands.CommandResponse)); ok == true {\n\t\tteh.Handler = fn\n\t\treturn nil\n\t}\n\tif fn, ok := fn.(func(commands.EventResult)); ok == true {\n\t\tteh.Handler = fn\n\t\treturn nil\n\t}\n\n\treturn errors.New(\"Invalid Handler Definition\")\n}\n\nfunc NewHandler(event string, fn interface{}) (ThrustEventHandler, error) ", "output": "{\n\th := ThrustEventHandler{}\n\th.Event = event\n\th.Type = \"event\"\n\terr := h.SetHandleFunc(fn)\n\tdispatcher.RegisterHandler(h)\n\treturn h, err\n}"} {"input": "package chart\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\ntype CT_Thickness struct {\n\tValAttr ST_Thickness\n}\n\nfunc NewCT_Thickness() *CT_Thickness {\n\tret := &CT_Thickness{}\n\treturn ret\n}\n\nfunc (m *CT_Thickness) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"val\"},\n\t\tValue: fmt.Sprintf(\"%v\", m.ValAttr)})\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}\n\n\n\n\nfunc (m *CT_Thickness) Validate() error {\n\treturn m.ValidateWithPath(\"CT_Thickness\")\n}\n\n\nfunc (m *CT_Thickness) ValidateWithPath(path string) error {\n\tif err := m.ValAttr.ValidateWithPath(path + \"/ValAttr\"); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (m *CT_Thickness) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error ", "output": "{\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"val\" {\n\t\t\tparsed, err := ParseUnionST_Thickness(attr.Value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.ValAttr = parsed\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_Thickness: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package devicemapper\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n)\n\n\n\nfunc minor(device uint64) uint64 {\n\treturn (device & 0xff) | ((device >> 12) & 0xfff00)\n}\n\n\nfunc GetDevicePrefix(root string) (string, error) {\n\tst, err := os.Stat(root)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Error looking up dir %s: %s\", root, err)\n\t}\n\tsysSt := st.Sys().(*syscall.Stat_t)\n\treturn fmt.Sprintf(\"docker-%d:%d-%d\", major(sysSt.Dev), minor(sysSt.Dev), sysSt.Ino), nil\n}\n\nfunc major(device uint64) uint64 ", "output": "{\n\treturn (device >> 8) & 0xfff\n}"} {"input": "package pgsql\n\nimport (\n\t\"database/sql\"\n\t\"time\"\n\n\t\"github.com/coreos/clair/pkg/commonerr\"\n)\n\n\nfunc (pgSQL *pgSQL) InsertKeyValue(key, value string) (err error) {\n\tif key == \"\" || value == \"\" {\n\t\tlog.Warning(\"could not insert a flag which has an empty name or value\")\n\t\treturn commonerr.NewBadRequestError(\"could not insert a flag which has an empty name or value\")\n\t}\n\n\tdefer observeQueryTime(\"InsertKeyValue\", \"all\", time.Now())\n\n\n\tfor {\n\t\tr, err := pgSQL.Exec(updateKeyValue, value, key)\n\t\tif err != nil {\n\t\t\treturn handleError(\"updateKeyValue\", err)\n\t\t}\n\t\tif n, _ := r.RowsAffected(); n > 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\t_, err = pgSQL.Exec(insertKeyValue, key, value)\n\t\tif err != nil {\n\t\t\tif isErrUniqueViolation(err) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn handleError(\"insertKeyValue\", err)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\n\n\n\nfunc (pgSQL *pgSQL) GetKeyValue(key string) (string, error) ", "output": "{\n\tdefer observeQueryTime(\"GetKeyValue\", \"all\", time.Now())\n\n\tvar value string\n\terr := pgSQL.QueryRow(searchKeyValue, key).Scan(&value)\n\n\tif err == sql.ErrNoRows {\n\t\treturn \"\", nil\n\t}\n\tif err != nil {\n\t\treturn \"\", handleError(\"searchKeyValue\", err)\n\t}\n\n\treturn value, nil\n}"} {"input": "package cabf_br\n\n\n\nimport (\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/util\"\n)\n\ntype SANEDI struct{}\n\n\n\nfunc init() {\n\tlint.RegisterLint(&lint.Lint{\n\t\tName: \"e_ext_san_edi_party_name_present\",\n\t\tDescription: \"The Subject Alternate Name extension MUST contain only 'dnsName' and 'ipaddress' name types\",\n\t\tCitation: \"BRs: 7.1.4.2.1\",\n\t\tSource: lint.CABFBaselineRequirements,\n\t\tEffectiveDate: util.CABEffectiveDate,\n\t\tLint: &SANEDI{},\n\t})\n}\n\nfunc (l *SANEDI) Initialize() error {\n\treturn nil\n}\n\nfunc (l *SANEDI) CheckApplies(c *x509.Certificate) bool {\n\treturn util.IsExtInCert(c, util.SubjectAlternateNameOID)\n}\n\n\n\nfunc (l *SANEDI) Execute(c *x509.Certificate) *lint.LintResult ", "output": "{\n\tif c.EDIPartyNames != nil {\n\t\treturn &lint.LintResult{Status: lint.Error}\n\t}\n\treturn &lint.LintResult{Status: lint.Pass}\n}"} {"input": "package transport\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n\tboshlog \"github.com/cloudfoundry/bosh-utils/logger\"\n\n\tbslcdisp \"bosh-softlayer-cpi/api/dispatcher\"\n)\n\nconst cliLogTag = \"CLI\"\n\ntype CLI struct {\n\tin io.Reader\n\tout io.Writer\n\tdispatcher bslcdisp.Dispatcher\n\tlogger boshlog.Logger\n}\n\nfunc NewCLI(\n\tin io.Reader,\n\tout io.Writer,\n\tdispatcher bslcdisp.Dispatcher,\n\tlogger boshlog.Logger,\n) CLI {\n\treturn CLI{\n\t\tin: in,\n\t\tout: out,\n\t\tdispatcher: dispatcher,\n\t\tlogger: logger,\n\t}\n}\n\n\n\nfunc (t CLI) ServeOnce() error ", "output": "{\n\treqBytes, err := ioutil.ReadAll(t.in)\n\tif err != nil {\n\t\tt.logger.Error(cliLogTag, \"Failed reading from IN: %s\", err)\n\t\treturn bosherr.WrapError(err, \"Reading from IN\")\n\t}\n\n\trespBytes := t.dispatcher.Dispatch(reqBytes)\n\n\t_, err = t.out.Write(respBytes)\n\tif err != nil {\n\t\tt.logger.Error(cliLogTag, \"Failed writing to OUT: %s\", err)\n\t\treturn bosherr.WrapError(err, \"Writing to OUT\")\n\t}\n\n\treturn nil\n}"} {"input": "package kata\n\nimport (\n\t\"strings\"\n\t\"strconv\"\n)\n\nconst suffix = \" sheep...\"\n\n\n\nfunc CountSheep(num int) string ", "output": "{\n if num <= 0 {\n\t return \"\"\n }\n\n builder := strings.Builder{}\n for i := 1; i <= num; i++ {\n\t builder.WriteString(strconv.Itoa(i))\n\t builder.WriteString(suffix)\n }\n return builder.String()\n}"} {"input": "package rsets\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/pingcap/tidb/context\"\n\t\"github.com/pingcap/tidb/plan\"\n\t\"github.com/pingcap/tidb/plan/plans\"\n)\n\nvar (\n\t_ plan.Planner = (*LimitRset)(nil)\n\t_ plan.Planner = (*OffsetRset)(nil)\n)\n\n\ntype OffsetRset struct {\n\tCount uint64\n\tSrc plan.Plan\n}\n\n\nfunc (r *OffsetRset) Plan(ctx context.Context) (plan.Plan, error) {\n\treturn &plans.OffsetDefaultPlan{Count: r.Count, Src: r.Src, Fields: r.Src.GetFields()}, nil\n}\n\n\n\n\ntype LimitRset struct {\n\tCount uint64\n\tSrc plan.Plan\n}\n\n\nfunc (r *LimitRset) Plan(ctx context.Context) (plan.Plan, error) {\n\treturn &plans.LimitDefaultPlan{Count: r.Count, Src: r.Src, Fields: r.Src.GetFields()}, nil\n}\n\nfunc (r *LimitRset) String() string {\n\treturn fmt.Sprintf(\" LIMIT %d\", r.Count)\n}\n\nfunc (r *OffsetRset) String() string ", "output": "{\n\treturn fmt.Sprintf(\" OFFSET %d\", r.Count)\n}"} {"input": "package relation\n\nimport (\n\t\"github.com/juju/names/v4\"\n\n\t\"github.com/juju/juju/api/uniter\"\n)\n\ntype stateTrackerStateShim struct {\n\t*uniter.State\n}\n\nfunc (s *stateTrackerStateShim) Relation(tag names.RelationTag) (Relation, error) {\n\trel, err := s.State.Relation(tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &relationShim{rel}, nil\n}\n\n\nfunc (s *stateTrackerStateShim) RelationById(id int) (Relation, error) {\n\trel, err := s.State.RelationById(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &relationShim{rel}, nil\n}\n\n\nfunc (s *stateTrackerStateShim) Unit(tag names.UnitTag) (Unit, error) {\n\tunit, err := s.State.Unit(tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &unitShim{unit}, nil\n}\n\ntype relationShim struct {\n\t*uniter.Relation\n}\n\nfunc (s *relationShim) Unit(uTag names.UnitTag) (RelationUnit, error) {\n\tu, err := s.Relation.Unit(uTag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RelationUnitShim{u}, nil\n}\n\ntype unitShim struct {\n\t*uniter.Unit\n}\n\n\n\ntype applicationShim struct {\n\t*uniter.Application\n}\n\ntype RelationUnitShim struct {\n\t*uniter.RelationUnit\n}\n\nfunc (r *RelationUnitShim) Relation() Relation {\n\treturn &relationShim{r.RelationUnit.Relation()}\n}\n\nfunc (s *unitShim) Application() (Application, error) ", "output": "{\n\tapp, err := s.Unit.Application()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &applicationShim{app}, nil\n}"} {"input": "package msgraph\n\nimport \"context\"\n\n\ntype WorkbookFunctionsTanRequestBuilder struct{ BaseRequestBuilder }\n\n\n\n\n\ntype WorkbookFunctionsTanRequest struct{ BaseRequest }\n\n\nfunc (b *WorkbookFunctionsTanRequestBuilder) Request() *WorkbookFunctionsTanRequest {\n\treturn &WorkbookFunctionsTanRequest{\n\t\tBaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},\n\t}\n}\n\n\nfunc (r *WorkbookFunctionsTanRequest) Post(ctx context.Context) (resObj *WorkbookFunctionResult, err error) {\n\terr = r.JSONRequest(ctx, \"POST\", \"\", r.requestObject, &resObj)\n\treturn\n}\n\nfunc (b *WorkbookFunctionsRequestBuilder) Tan(reqObj *WorkbookFunctionsTanRequestParameter) *WorkbookFunctionsTanRequestBuilder ", "output": "{\n\tbb := &WorkbookFunctionsTanRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.BaseRequestBuilder.baseURL += \"/tan\"\n\tbb.BaseRequestBuilder.requestObject = reqObj\n\treturn bb\n}"} {"input": "package pipelinerun\n\nimport (\n\t\"sort\"\n\n\t\"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1\"\n)\n\n\n\ntype byNamespace []v1beta1.PipelineRun\n\nfunc (prs byNamespace) compareNamespace(ins, jns string) (lt, eq bool) {\n\tlt, eq = ins < jns, ins == jns\n\treturn lt, eq\n}\n\nfunc (prs byNamespace) Len() int { return len(prs) }\nfunc (prs byNamespace) Swap(i, j int) { prs[i], prs[j] = prs[j], prs[i] }\nfunc (prs byNamespace) Less(i, j int) bool {\n\tvar lt, eq bool\n\tif lt, eq = prs.compareNamespace(prs[i].Namespace, prs[j].Namespace); eq {\n\t\tif prs[j].Status.StartTime == nil {\n\t\t\treturn false\n\t\t}\n\t\tif prs[i].Status.StartTime == nil {\n\t\t\treturn true\n\t\t}\n\t\treturn prs[j].Status.StartTime.Before(prs[i].Status.StartTime)\n\t}\n\treturn lt\n}\n\nfunc SortByNamespace(prs []v1beta1.PipelineRun) ", "output": "{\n\tsort.Sort(byNamespace(prs))\n}"} {"input": "package autostart\n\nimport (\n\t\"flag\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/vim25/types\"\n)\n\ntype add struct {\n\t*AutostartFlag\n}\n\n\n\nfunc (cmd *add) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.AutostartFlag, ctx = newAutostartFlag(ctx)\n\tcmd.AutostartFlag.Register(ctx, f)\n}\n\nfunc (cmd *add) Process(ctx context.Context) error {\n\tif err := cmd.AutostartFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (cmd *add) Usage() string {\n\treturn \"VM...\"\n}\n\nfunc (cmd *add) Run(ctx context.Context, f *flag.FlagSet) error {\n\tvar powerInfo = types.AutoStartPowerInfo{\n\t\tStartAction: \"powerOn\",\n\t\tStartDelay: -1,\n\t\tStartOrder: -1,\n\t\tStopAction: \"systemDefault\",\n\t\tStopDelay: -1,\n\t\tWaitForHeartbeat: types.AutoStartWaitHeartbeatSettingSystemDefault,\n\t}\n\n\treturn cmd.ReconfigureVMs(f.Args(), powerInfo)\n}\n\nfunc init() ", "output": "{\n\tcli.Register(\"host.autostart.add\", &add{})\n}"} {"input": "package runewidth\n\nimport (\n\t\"testing\"\n\t\"unicode/utf8\"\n)\n\nvar benchSink int\n\nfunc benchTable(b *testing.B, tbl table) int {\n\tn := 0\n\tfor i := 0; i < b.N; i++ {\n\t\tfor r := rune(0); r <= utf8.MaxRune; r++ {\n\t\t\tif inTable(r, tbl) {\n\t\t\t\tn++\n\t\t\t}\n\t\t}\n\t}\n\treturn n\n}\n\nfunc BenchmarkTablePrivate(b *testing.B) {\n\tbenchSink = benchTable(b, private)\n}\nfunc BenchmarkTableNonprint(b *testing.B) {\n\tbenchSink = benchTable(b, nonprint)\n}\nfunc BenchmarkTableCombining(b *testing.B) {\n\tbenchSink = benchTable(b, combining)\n}\nfunc BenchmarkTableDoublewidth(b *testing.B) {\n\tbenchSink = benchTable(b, doublewidth)\n}\nfunc BenchmarkTableAmbiguous(b *testing.B) {\n\tbenchSink = benchTable(b, ambiguous)\n}\nfunc BenchmarkTableEmoji(b *testing.B) {\n\tbenchSink = benchTable(b, emoji)\n}\nfunc BenchmarkTableNotassigned(b *testing.B) {\n\tbenchSink = benchTable(b, notassigned)\n}\n\n\nfunc BenchmarkTableNeutral(b *testing.B) ", "output": "{\n\tbenchSink = benchTable(b, neutral)\n}"} {"input": "package fstest\n\nimport (\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"github.com/containerd/continuity/sysx\"\n\t\"golang.org/x/sys/unix\"\n)\n\n\nfunc SetXAttr(name, key, value string) Applier {\n\treturn applyFn(func(root string) error {\n\t\treturn sysx.LSetxattr(name, key, []byte(value), 0)\n\t})\n}\n\n\nfunc Lchtimes(name string, atime, mtime time.Time) Applier {\n\treturn applyFn(func(root string) error {\n\t\tpath := filepath.Join(root, name)\n\t\tat := unix.NsecToTimespec(atime.UnixNano())\n\t\tmt := unix.NsecToTimespec(mtime.UnixNano())\n\t\tutimes := [2]unix.Timespec{at, mt}\n\t\treturn unix.UtimesNanoAt(unix.AT_FDCWD, path, utimes[0:], unix.AT_SYMLINK_NOFOLLOW)\n\t})\n}\n\n\n\nfunc Base() Applier ", "output": "{\n\treturn applyFn(func(root string) error {\n\t\treturn nil\n\t})\n}"} {"input": "package meetup\n\nimport \"testing\"\n\n\n\nconst targetTestVersion = 3\n\nvar weekName = map[WeekSchedule]string{\n\tFirst: \"first\",\n\tSecond: \"second\",\n\tThird: \"third\",\n\tFourth: \"fourth\",\n\tTeenth: \"teenth\",\n\tLast: \"last\",\n}\n\n\n\nfunc TestDay(t *testing.T) {\n\tfor _, test := range testCases {\n\t\tres := Day(test.week, test.weekday, test.month, test.year)\n\t\tif res != test.expDay {\n\t\t\tt.Fatalf(\"For %s %s of %s 2013 got date of %d, want %d\",\n\t\t\t\tweekName[test.week], test.weekday, test.month, res, test.expDay)\n\t\t}\n\t}\n}\n\nfunc TestTestVersion(t *testing.T) ", "output": "{\n\tif testVersion != targetTestVersion {\n\t\tt.Fatalf(\"Found testVersion = %v, want %v\", testVersion, targetTestVersion)\n\t}\n}"} {"input": "package helper\n\nimport (\n\t\"bufio\"\n\t\"net\"\n)\n\ntype BufConn struct {\n\tnet.Conn\n\tBR *bufio.Reader\n}\n\n\n\nfunc (c *BufConn) Read(b []byte) (n int, err error) {\n\treturn c.BR.Read(b)\n}\n\nfunc (c *BufConn) Write(b []byte) (n int, err error) {\n\treturn c.Conn.Write(b)\n}\n\nfunc (c *BufConn) Reset(conn net.Conn) {\n\tc.Conn = conn\n}\n\nfunc NewBufConn(c net.Conn, r *bufio.Reader) *BufConn {\n\tconn := &BufConn{Conn: c}\n\tconn.BR = r\n\tif nil == r {\n\t\tconn.BR = bufio.NewReader(c)\n\t}\n\treturn conn\n}\n\nfunc (c *BufConn) Peek(n int) ([]byte, error) ", "output": "{\n\treturn c.BR.Peek(n)\n}"} {"input": "package colorable\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\n\nfunc NewColorable(file *os.File) io.Writer {\n\tif file == nil {\n\t\tpanic(\"nil passed instead of *os.File to NewColorable()\")\n\t}\n\n\treturn file\n}\n\n\nfunc NewColorableStdout() io.Writer {\n\treturn os.Stdout\n}\n\n\n\n\nfunc NewColorableStderr() io.Writer ", "output": "{\n\treturn os.Stderr\n}"} {"input": "package unversioned\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/testapi\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\ntype HTTPClientFunc func(*http.Request) (*http.Response, error)\n\nfunc (f HTTPClientFunc) Do(req *http.Request) (*http.Response, error) {\n\treturn f(req)\n}\n\n\ntype FakeRESTClient struct {\n\tClient HTTPClient\n\tCodec runtime.Codec\n\tReq *http.Request\n\tResp *http.Response\n\tErr error\n}\n\nfunc (c *FakeRESTClient) Get() *Request {\n\treturn NewRequest(c, \"GET\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Put() *Request {\n\treturn NewRequest(c, \"PUT\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Patch(_ api.PatchType) *Request {\n\treturn NewRequest(c, \"PATCH\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\n\n\nfunc (c *FakeRESTClient) Delete() *Request {\n\treturn NewRequest(c, \"DELETE\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Do(req *http.Request) (*http.Response, error) {\n\tc.Req = req\n\tif c.Client != HTTPClient(nil) {\n\t\treturn c.Client.Do(req)\n\t}\n\treturn c.Resp, c.Err\n}\n\nfunc (c *FakeRESTClient) Post() *Request ", "output": "{\n\treturn NewRequest(c, \"POST\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/api/events/v1beta1\"\n\t\"k8s.io/client-go/deprecated/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype EventsV1beta1Interface interface {\n\tRESTClient() rest.Interface\n\tEventsGetter\n}\n\n\ntype EventsV1beta1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *EventsV1beta1Client) Events(namespace string) EventInterface {\n\treturn newEvents(c, namespace)\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *EventsV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *EventsV1beta1Client {\n\treturn &EventsV1beta1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *EventsV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfig(c *rest.Config) (*EventsV1beta1Client, error) ", "output": "{\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &EventsV1beta1Client{client}, nil\n}"} {"input": "package installer\n\nimport (\n\t\"github.com/wx13/genesis\"\n)\n\n\n\ntype Custom struct {\n\tTask genesis.Doer\n\tS func() (genesis.Status, error)\n\tD func() (bool, error)\n\tU func() (bool, error)\n\tI func() string\n\tF func() []string\n}\n\nfunc NewCustom(task genesis.Doer) *Custom {\n\tcustom := Custom{\n\t\tTask: task,\n\t\tS: task.Status,\n\t\tD: task.Do,\n\t\tU: task.Undo,\n\t\tI: task.ID,\n\t\tF: task.Files,\n\t}\n\treturn &custom\n}\n\nfunc (custom Custom) Status() (genesis.Status, error) {\n\treturn custom.S()\n}\n\nfunc (custom Custom) Do() (bool, error) {\n\treturn custom.D()\n}\n\nfunc (custom Custom) Undo() (bool, error) {\n\treturn custom.U()\n}\n\n\n\nfunc (custom Custom) Files() []string {\n\treturn custom.F()\n}\n\nfunc (custom Custom) ID() string ", "output": "{\n\treturn custom.I()\n}"} {"input": "package header\n\nimport (\n\t\"github.com/google/netstack/tcpip\"\n)\n\n\n\nfunc Checksum(buf []byte, initial uint16) uint16 {\n\tv := uint32(initial)\n\n\tl := len(buf)\n\tif l&1 != 0 {\n\t\tl--\n\t\tv += uint32(buf[l]) << 8\n\t}\n\n\tfor i := 0; i < l; i += 2 {\n\t\tv += (uint32(buf[i]) << 8) + uint32(buf[i+1])\n\t}\n\n\treturn ChecksumCombine(uint16(v), uint16(v>>16))\n}\n\n\n\n\n\n\n\n\n\nfunc PseudoHeaderChecksum(protocol tcpip.TransportProtocolNumber, srcAddr tcpip.Address, dstAddr tcpip.Address) uint16 {\n\txsum := Checksum([]byte(srcAddr), 0)\n\txsum = Checksum([]byte(dstAddr), xsum)\n\treturn Checksum([]byte{0, uint8(protocol)}, xsum)\n}\n\nfunc ChecksumCombine(a, b uint16) uint16 ", "output": "{\n\tv := uint32(a) + uint32(b)\n\treturn uint16(v + v>>16)\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc ServeHttp() {\n\thttp.HandleFunc(\"/\", handler)\n\thttp.HandleFunc(\"/deploy\", HandleDeploy)\n\n\tport := GoployCtx.Cfg.App.Port\n\tlog.Printf(\"Webserver listening on %v...\", port)\n\terr := http.ListenAndServe(fmt.Sprintf(\":%v\", port), nil)\n\tif err != nil {\n\t\tlog.Fatal(\"ListenAndServe error: \", err)\n\t}\n}\n\n\n\nfunc handler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tpath := r.URL.Path\n\n\tif LogLevel() >= LOG_VERBOSE {\n\t\tlog.Printf(\"%v on path %v\", r.Method, path)\n\t}\n\n\tfmt.Fprintf(w, \"Hi there, I love %s!\", r.URL.Path[1:])\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com/ceph/go-ceph/rados\"\n)\n\nfunc main() {\n\tfor i := 1; i <= 100; i++ {\n\t\tc, err := getConnection(\"127.0.0.1\", \"nobody\", \"secret\")\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"getConnection failed: %v\\n\", err)\n\t\t} else {\n\t\t\tc.Shutdown()\n\t\t}\n\t}\n\n\truntime.GC()\n\ttime.Sleep(time.Second)\n}\n\n\n\nfunc getConnection(monitors, user, key string) (*rados.Conn, error) ", "output": "{\n\tconn, err := rados.NewConnWithUser(user)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\targs := []string{\"--client_mount_timeout\", \"15\", \"-m\", monitors, \"--key\", key}\n\terr = conn.ParseCmdLineArgs(args)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ParseCmdLineArgs: %v\", err)\n\t}\n\terr = conn.Connect()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Connect: %v\", err)\n\t}\n\treturn conn, nil\n}"} {"input": "package buckettree\n\nimport (\n\t\"testing\"\n\n\t\"github.com/openblockchain/obc-peer/openchain/ledger/testutil\"\n)\n\nfunc TestDataKey(t *testing.T) {\n\tconf = newConfig(26, 3, fnvHash)\n\tdataKey := newDataKey(\"chaincodeID\", \"key\")\n\tencodedBytes := dataKey.getEncodedBytes()\n\tdataKeyFromEncodedBytes := newDataKeyFromEncodedBytes(encodedBytes)\n\ttestutil.AssertEquals(t, dataKey, dataKeyFromEncodedBytes)\n}\n\n\n\nfunc TestDataKeyGetBucketKey(t *testing.T) ", "output": "{\n\tconf = newConfig(26, 3, fnvHash)\n\tnewDataKey(\"chaincodeID1\", \"key1\").getBucketKey()\n\tnewDataKey(\"chaincodeID1\", \"key2\").getBucketKey()\n\tnewDataKey(\"chaincodeID2\", \"key1\").getBucketKey()\n\tnewDataKey(\"chaincodeID2\", \"key2\").getBucketKey()\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc isNaN(x float32) bool {\n\treturn x != x \n}\n\nfunc main() {\n\tfoo(42)\n}\n\nconst mode = \"Debug\"\n\nfunc log(msg string) {\n\tif mode == \"Debug\" {\n\t\tfmt.Println(msg)\n\t}\n}\n\nfunc bar() {\n\tif ptrsize == 8 { \n\t\tfmt.Println()\n\t}\n}\n\nfunc bump(x *int) {\n\t*x++\n}\n\nfunc baz() bool {\n\tvar x = 0\n\tbump(&x)\n\treturn x == 0\n}\n\ntype counter int\n\nfunc (x *counter) bump() {\n\t*x++\n}\n\nfunc (x counter) bimp() {\n\tx++\n}\n\nfunc baz2() bool {\n\tvar x counter\n\tx.bump()\n\treturn x == 0 \n}\n\nfunc baz3() bool {\n\tvar y counter\n\ty.bimp()\n\treturn y == 0 \n}\n\nfunc foo(x int) bool ", "output": "{\n\treturn x == x \n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"text/tabwriter\"\n)\n\nfunc optionTable(w io.Writer, rows [][]string) {\n\ttw := tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)\n\tfor _, row := range rows {\n\t\tfor i, cell := range row {\n\t\t\tif i > 0 {\n\t\t\t\ttw.Write([]byte(\"\\t\"))\n\t\t\t}\n\t\t\ttw.Write([]byte(cell))\n\t\t}\n\t\ttw.Write([]byte(\"\\n\"))\n\t}\n\ttw.Flush()\n}\n\n\n\nfunc usageFor(fs *flag.FlagSet, usage string, extra string) func() ", "output": "{\n\treturn func() {\n\t\tvar b bytes.Buffer\n\t\tb.WriteString(\"Usage:\\n \" + usage + \"\\n\")\n\n\t\tvar options [][]string\n\t\tfs.VisitAll(func(f *flag.Flag) {\n\t\t\tvar opt = \" -\" + f.Name\n\n\t\t\tif f.DefValue != \"false\" {\n\t\t\t\topt += \"=\" + fmt.Sprintf(`\"%s\"`, f.DefValue)\n\t\t\t}\n\t\t\toptions = append(options, []string{opt, f.Usage})\n\t\t})\n\n\t\tif len(options) > 0 {\n\t\t\tb.WriteString(\"\\nOptions:\\n\")\n\t\t\toptionTable(&b, options)\n\t\t}\n\n\t\tfmt.Println(b.String())\n\n\t\tif len(extra) > 0 {\n\t\t\tfmt.Println(extra)\n\t\t}\n\t}\n}"} {"input": "package flags\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst Version = \"0.16.1\"\n\ntype version []int\n\nfunc ParseVersion(s string) (version, error) {\n\tv := make(version, 0)\n\tps := strings.Split(s, \".\")\n\tfor _, p := range ps {\n\t\ti, err := strconv.Atoi(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tv = append(v, i)\n\t}\n\n\treturn v, nil\n}\n\n\n\nfunc (v version) Lte(u version) bool ", "output": "{\n\tlv := len(v)\n\tlu := len(u)\n\n\tfor i := 0; i < lv; i++ {\n\t\tif i >= lu {\n\t\t\treturn false\n\t\t}\n\n\t\tif v[i] == u[i] {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn v[i] < u[i]\n\t}\n\n\treturn true\n}"} {"input": "package cgzip\n\n\nimport \"C\"\n\nimport (\n\t\"hash\"\n\t\"unsafe\"\n)\n\ntype adler32Hash struct {\n\tadler C.uLong\n}\n\n\n\nfunc NewAdler32() hash.Hash32 {\n\ta := &adler32Hash{}\n\ta.Reset()\n\treturn a\n}\n\n\nfunc (a *adler32Hash) Write(p []byte) (n int, err error) {\n\tif len(p) > 0 {\n\t\ta.adler = C.adler32(a.adler, (*C.Bytef)(unsafe.Pointer(&p[0])), (C.uInt)(len(p)))\n\t}\n\treturn len(p), nil\n}\n\n\nfunc (a *adler32Hash) Sum(b []byte) []byte {\n\ts := a.Sum32()\n\tb = append(b, byte(s>>24))\n\tb = append(b, byte(s>>16))\n\tb = append(b, byte(s>>8))\n\tb = append(b, byte(s))\n\treturn b\n}\n\nfunc (a *adler32Hash) Reset() {\n\ta.adler = C.adler32(0, (*C.Bytef)(unsafe.Pointer(nil)), 0)\n}\n\nfunc (a *adler32Hash) Size() int {\n\treturn 4\n}\n\n\n\n\nfunc (a *adler32Hash) Sum32() uint32 {\n\treturn uint32(a.adler)\n}\n\n\n\n\n\n\n\nfunc Adler32Combine(adler1, adler2 uint32, len2 int) uint32 {\n\treturn uint32(C.adler32_combine(C.uLong(adler1), C.uLong(adler2), C.z_off_t(len2)))\n}\n\nfunc (a *adler32Hash) BlockSize() int ", "output": "{\n\treturn 1\n}"} {"input": "package flaghelpers\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype VariablePairFlag struct {\n\tName string\n\tValue string\n}\n\n\n\nfunc (pair *VariablePairFlag) UnmarshalFlag(value string) error ", "output": "{\n\tvs := strings.SplitN(value, \"=\", 2)\n\tif len(vs) != 2 {\n\t\treturn fmt.Errorf(\"invalid input pair '%s' (must be name=value)\", value)\n\t}\n\n\tpair.Name = vs[0]\n\tpair.Value = vs[1]\n\n\treturn nil\n}"} {"input": "package base\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Destination struct {\n\tSourceIp string `db:\"source_ip\"`\n\tDestinationIp string `db:\"destination_ip\"`\n\tServerName string `db:\"server_name\"`\n\tProtocol string `db:\"protocol\"`\n\tTimestamp time.Time `db:\"timestamp\"`\n}\n\n\n\nfunc NewDestination(serverName string, sourceIp string, destIp string) *Destination {\n\tdestination := &Destination{ServerName: serverName, SourceIp: sourceIp, DestinationIp: destIp}\n\treturn destination\n}\n\nfunc (self *Destination) Save(db GarinDB) {\n\tLogger().Debugf(\"Saving destination - %s\", self.Hash())\n\tdb.RecordDestination(self)\n\tLogger().Debugf(\"Destination saved - %s\", self.Hash())\n}\n\nfunc (self *Destination) Hash() string ", "output": "{\n\treturn fmt.Sprintf(\"%x\", md5.Sum([]byte(self.SourceIp+self.DestinationIp+self.ServerName+self.Protocol)))\n}"} {"input": "package openstack\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gophercloud/gophercloud\"\n\ttokens2 \"github.com/gophercloud/gophercloud/openstack/identity/v2/tokens\"\n\ttokens3 \"github.com/gophercloud/gophercloud/openstack/identity/v3/tokens\"\n)\n\n\n\ntype ErrEndpointNotFound struct{ gophercloud.BaseError }\n\n\n\n\n\ntype ErrInvalidAvailabilityProvided struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrInvalidAvailabilityProvided) Error() string {\n\treturn fmt.Sprintf(\"Unexpected availability in endpoint query: %s\", e.Value)\n}\n\n\n\ntype ErrMultipleMatchingEndpointsV2 struct {\n\tgophercloud.BaseError\n\tEndpoints []tokens2.Endpoint\n}\n\nfunc (e ErrMultipleMatchingEndpointsV2) Error() string {\n\treturn fmt.Sprintf(\"Discovered %d matching endpoints: %#v\", len(e.Endpoints), e.Endpoints)\n}\n\n\n\ntype ErrMultipleMatchingEndpointsV3 struct {\n\tgophercloud.BaseError\n\tEndpoints []tokens3.Endpoint\n}\n\nfunc (e ErrMultipleMatchingEndpointsV3) Error() string {\n\treturn fmt.Sprintf(\"Discovered %d matching endpoints: %#v\", len(e.Endpoints), e.Endpoints)\n}\n\n\n\ntype ErrNoAuthURL struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoAuthURL) Error() string {\n\treturn \"Environment variable OS_AUTH_URL needs to be set.\"\n}\n\n\n\ntype ErrNoUsername struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoUsername) Error() string {\n\treturn \"Environment variable OS_USERNAME needs to be set.\"\n}\n\n\n\ntype ErrNoPassword struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoPassword) Error() string {\n\treturn \"Environment variable OS_PASSWORD needs to be set.\"\n}\n\nfunc (e ErrEndpointNotFound) Error() string ", "output": "{\n\treturn \"No suitable endpoint could be found in the service catalog.\"\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype Page struct {\n\tTitle string\n\tBody []byte\n}\n\nfunc (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}\n\n\n\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/view/\"):]\n\tp, _ := loadPage(title)\n\tfmt.Fprintf(w, \"

%s

%s
\", p.Title, p.Body)\n}\n\n\nfunc defaultHandler(w http.ResponseWriter, r *http.Request) {\n\tdump, err := httputil.DumpRequest(r, true)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(string(dump))\n\n\tp, err := loadPage(\"TestPage\") \n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Fprintf(w, \"

%s

%s
\", p.Title, p.Body)\n}\n\n\nfunc main() {\n\tdir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tbody := \"This is a test page under: \" + dir\n\tp1 := &Page{Title: \"TestPage\", Body: []byte(body)}\n\tp1.save()\n\tp2, _ := loadPage(\"TestPage\")\n\tfmt.Println(string(p2.Body))\n\n\thttp.HandleFunc(\"/\", defaultHandler)\n\thttp.ListenAndServe(\":8081\", nil)\n}\n\nfunc loadPage(title string) (*Page, error) ", "output": "{\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\treturn &Page{Title: title, Body: body}, err\n}"} {"input": "package fs\n\nimport (\n\t. \"launchpad.net/gocheck\"\n\t\"os\"\n)\n\ntype CommonTestSuite struct{}\n\nvar _ = Suite(&CommonTestSuite{})\n\nfunc (s *CommonTestSuite) TestMkDir_NonRecursive(c *C) {\n\ttmpDir := c.MkDir() + \"/foo\"\n\n\terr := MkDir(tmpDir, false, 0755)\n\tc.Assert(err, IsNil)\n\n\tf, err := os.Stat(tmpDir)\n\tc.Assert(err, IsNil)\n\tc.Assert(f.IsDir(), Equals, true)\n}\n\nfunc (s *CommonTestSuite) TestMkDir_Recursive(c *C) {\n\ttmpDir := c.MkDir() + \"/foo/bar/baz\"\n\n\terr := MkDir(tmpDir, true, 0755)\n\tc.Assert(err, IsNil)\n\n\tf, err := os.Stat(tmpDir)\n\tc.Assert(err, IsNil)\n\tc.Assert(f.IsDir(), Equals, true)\n}\n\n\n\nfunc (s *CommonTestSuite) TestRmDir_Recursive(c *C) {\n\tsuffix := \"/foo/bar/baz\"\n\ttmpDir := c.MkDir()\n\n\terr := MkDir(tmpDir+suffix, true, 0755)\n\tc.Assert(err, IsNil)\n\n\tf, err := os.Stat(tmpDir)\n\tc.Assert(err, IsNil)\n\tc.Assert(f.IsDir(), Equals, true)\n\n\terr = RmDir(tmpDir, true)\n\tc.Assert(err, IsNil)\n\n\tf, err = os.Stat(tmpDir + suffix)\n\tc.Assert(os.IsNotExist(err), Equals, true)\n\tc.Assert(f, IsNil)\n}\n\nfunc (s *CommonTestSuite) TestRmDir_NonRecursive(c *C) ", "output": "{\n\ttmpDir := c.MkDir() + \"/foo\"\n\n\terr := MkDir(tmpDir, false, 0755)\n\tc.Assert(err, IsNil)\n\n\tf, err := os.Stat(tmpDir)\n\tc.Assert(err, IsNil)\n\tc.Assert(f.IsDir(), Equals, true)\n\n\terr = RmDir(tmpDir, false)\n\tc.Assert(err, IsNil)\n\n\tf, err = os.Stat(tmpDir)\n\tc.Assert(os.IsNotExist(err), Equals, true)\n\tc.Assert(f, IsNil)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/banerwai/gommon/crypto\"\n\t\"github.com/banerwai/micros/query/auth/service\"\n\t\"gopkg.in/mgo.v2/bson\"\n)\n\ntype inmemService struct {\n}\n\n\n\nfunc (ims *inmemService) Ping() (r string) {\n\tr = \"pong\"\n\treturn\n}\n\nfunc (ims *inmemService) Login(email string, pwd string) (r string) {\n\tvar _bsonM bson.M\n\terr := UsersCollection.Find(bson.M{\"email\": email}).One(&_bsonM)\n\n\tif err != nil {\n\t\treturn \"error:\" + err.Error()\n\t}\n\n\t_active := _bsonM[\"actived\"].(bool)\n\tif !_active {\n\t\treturn \"error: user email need active\"\n\t}\n\n\t_pwd := _bsonM[\"pwd\"].(string)\n\n\t_is := crypto.CompareHash([]byte(_pwd), pwd)\n\tif !_is {\n\t\treturn \"error: compare false\"\n\t}\n\n\t_data, _err := bson.Marshal(_bsonM)\n\tif _err != nil {\n\t\treturn \"error: bson.Marshal error\"\n\t}\n\n\tr = string(_data)\n\treturn\n}\n\nfunc newInmemService() service.AuthService ", "output": "{\n\treturn &inmemService{}\n}"} {"input": "package main\n\nimport \"strings\"\n\ntype code_section interface {\n\tCode() bool\n}\n\ntype para string\n\nfunc (para) Code() bool {\n\treturn false\n}\n\ntype code string\n\nfunc (code) Code() bool {\n\treturn true\n}\n\ntype Article struct {\n\tTitle string\n\tIntro []para\n\tGoCode, ReflectCode []code_section\n\tUses, Tags []string\n\tslug string\n}\n\nfunc (a *Article) Slug() string {\n\tif a.slug == \"\" {\n\t\ta.slug = strings.ToLower(strings.Replace(a.Title, \" \", \"-\", -1))\n\t}\n\treturn a.slug\n}\n\ntype Articles []*Article\n\nfunc (a *Articles) Add(ao *Article) {\n\t*a = append(*a, ao)\n}\n\nfunc (a Articles) Len() int {\n\treturn len(a)\n}\n\n\n\nfunc (a Articles) Less(i, j int) bool {\n\treturn a[i].Title < a[j].Title\n}\n\nfunc (a Articles) Swap(i, j int) ", "output": "{\n\ta[j], a[i] = a[i], a[j]\n}"} {"input": "package lifegame\n\ntype Universe struct {\n\taliveCells []Cell\n}\n\ntype Cell struct{}\n\nfunc NewUniverse() *Universe {\n\treturn &Universe{}\n}\n\nfunc (u *Universe) HasAliveCell() bool {\n\treturn len(u.AliveCells()) != 0\n}\n\n\n\nfunc (u *Universe) NextGeneration() {\n\tu.aliveCells = []Cell{}\n}\n\nfunc (u *Universe) BornCellAtLocation(x, y int) {\n\tu.aliveCells = append(u.aliveCells, Cell{})\n}\n\nfunc (c *Cell) Location() (int, int) {\n\treturn 0, 0\n}\n\nfunc (u *Universe) AliveCells() []Cell ", "output": "{\n\treturn u.aliveCells\n}"} {"input": "package sacloud\n\nimport (\n\t\"fmt\"\n\t\"github.com/sacloud/sackerel/job/core\"\n)\n\n\n\n\nfunc addAgentTag(queue *core.Queue, option *core.Option, job core.JobAPI) {\n\n\tvar payload = job.GetPayload()\n\tif payload == nil {\n\t\tqueue.PushWarn(fmt.Errorf(\"'%s' => payload is nil\", job.GetName()))\n\t\treturn\n\t}\n\n\tif reconcilePayload, ok := payload.(*core.ReconcileHostsPayload); ok {\n\n\t\tzone, targetID, err := reconcilePayload.GetSacloudServerInfo()\n\t\tif err != nil {\n\t\t\tqueue.PushError(err)\n\t\t\treturn\n\t\t}\n\n\t\tclient := getClient(option, zone)\n\t\tserver, err := client.Server.Read(targetID)\n\t\tif err != nil {\n\t\t\tqueue.PushError(err)\n\t\t\treturn\n\t\t}\n\n\t\tif !server.HasTag(option.AgentTag) {\n\t\t\tserver.AppendTag(option.AgentTag)\n\t\t}\n\t\t_, err = client.Server.Update(targetID, server)\n\t\tif err != nil {\n\t\t\tqueue.PushError(err)\n\t\t\treturn\n\t\t}\n\n\t\tqueue.PushRequest(\"added-agent-tag\", payload)\n\n\t} else {\n\t\tqueue.PushWarn(fmt.Errorf(\"'%s' => payload is invalid type. need [*core.ReconcileHostsPayload]\", job.GetName()))\n\t\treturn\n\t}\n\n}\n\nfunc AddAgentTagJob(payload interface{}) core.JobAPI ", "output": "{\n\treturn core.NewJob(\"AddAgentTag\", addAgentTag, payload)\n}"} {"input": "package core\n\nimport (\n\tctypes \"github.com/tendermint/tendermint/rpc/core/types\"\n\trpctypes \"github.com/tendermint/tendermint/rpc/lib/types\"\n\t\"github.com/tendermint/tendermint/types\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Unsubscribe(wsCtx rpctypes.WSRPCContext, event string) (*ctypes.ResultUnsubscribe, error) {\n\tlogger.Info(\"Unsubscribe to event\", \"remote\", wsCtx.GetRemoteAddr(), \"event\", event)\n\twsCtx.GetEventSwitch().RemoveListenerForEvent(event, wsCtx.GetRemoteAddr())\n\treturn &ctypes.ResultUnsubscribe{}, nil\n}\n\nfunc Subscribe(wsCtx rpctypes.WSRPCContext, event string) (*ctypes.ResultSubscribe, error) ", "output": "{\n\tlogger.Info(\"Subscribe to event\", \"remote\", wsCtx.GetRemoteAddr(), \"event\", event)\n\ttypes.AddListenerForEvent(wsCtx.GetEventSwitch(), wsCtx.GetRemoteAddr(), event, func(msg types.TMEventData) {\n\t\ttmResult := &ctypes.ResultEvent{event, msg}\n\t\twsCtx.TryWriteRPCResponse(rpctypes.NewRPCSuccessResponse(wsCtx.Request.ID+\"#event\", tmResult))\n\t})\n\treturn &ctypes.ResultSubscribe{}, nil\n}"} {"input": "package responsewriter\n\nimport (\n\t\"net/http\"\n\t\"unicode/utf8\"\n\n\t\"github.com/go-on/stack\"\n)\n\nvar (\n\tampOrig = []byte(`&`)[0]\n\tampRepl = []byte(`&`)\n\n\tsgQuoteOrig = []byte(`'`)[0]\n\tsgQuoteRepl = []byte(`'`)\n\n\tdblQuoteOrig = []byte(`\"`)[0]\n\tdblQuoteRepl = []byte(`"`)\n\n\tltQuoteOrig = []byte(`<`)[0]\n\tltQuoteRepl = []byte(`<`)\n\n\tgtQuoteOrig = []byte(`>`)[0]\n\tgtQuoteRepl = []byte(`>`)\n)\n\n\n\ntype EscapeHTML struct {\n\thttp.ResponseWriter\n\n\tstack.Contexter\n}\n\n\nvar _ stack.Contexter = &EscapeHTML{}\n\nfunc NewEscapeHTML(w http.ResponseWriter) *EscapeHTML {\n\te := &EscapeHTML{ResponseWriter: w}\n\tif ctx, ok := w.(stack.Contexter); ok {\n\t\te.Contexter = ctx\n\t}\n\treturn e\n}\n\n\n\n\n\n\n\n\nfunc (e *EscapeHTML) Write(b []byte) (num int, err error) ", "output": "{\n\tvar esc []byte\n\tn := len(b)\n\tlast := 0\n\n\tfor i := 0; i < n; {\n\t\tr, width := utf8.DecodeRune(b[i:])\n\t\ti += width\n\t\tswitch r {\n\t\tcase '&':\n\t\t\tesc = ampRepl\n\t\tcase '\\'':\n\t\t\tesc = sgQuoteRepl\n\t\tcase '\"':\n\t\t\tesc = dblQuoteRepl\n\t\tcase '<':\n\t\t\tesc = ltQuoteRepl\n\t\tcase '>':\n\t\t\tesc = gtQuoteRepl\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\n\t\te.ResponseWriter.Write(b[last : i-width])\n\t\te.ResponseWriter.Write(esc)\n\t\tlast = i\n\t}\n\n\te.ResponseWriter.Write(b[last:])\n\treturn\n}"} {"input": "package perfcounters\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\ntype CountPerTimeInterval32 struct {\n\tlastCount int32\n\tlastTime *time.Time\n\tcurrentCount int32\n\tmu sync.Mutex\n}\n\nfunc NewCountPerTimeInterval32() *CountPerTimeInterval32 {\n\n\treturn &CountPerTimeInterval32{\n\t\tlastTime: nil,\n\t\tlastCount: 0,\n\t\tcurrentCount: 0,\n\t}\n}\n\n\n\nfunc (self *CountPerTimeInterval32) Add(value int32) {\n\tself.mu.Lock()\n\tdefer self.mu.Unlock()\n\n\tself.currentCount += value\n\n\tif self.lastTime == nil {\n\t\tnow := time.Now()\n\t\tself.lastTime = &now\n\t}\n}\n\nfunc (self *CountPerTimeInterval32) CalculatedValue() float64 {\n\tself.mu.Lock()\n\tdefer self.mu.Unlock()\n\n\tcurrentTime := time.Now()\n\n\tif self.lastTime == nil {\n\t\tself.lastTime = ¤tTime\n\t\treturn 0\n\t}\n\n\tlastTime := *self.lastTime\n\tlastCount := self.lastCount\n\tcurrentCount := self.currentCount\n\n\tcalculatedValue := float64(int64(currentCount-lastCount) / (currentTime.Sub(lastTime).Nanoseconds() / 1e6))\n\n\tself.lastTime = ¤tTime\n\tself.lastCount = currentCount\n\n\treturn calculatedValue\n}\n\nfunc (self *CountPerTimeInterval32) String() string {\n\treturn fmt.Sprintf(\"%.3f\", self.CalculatedValue())\n}\n\nfunc (self *CountPerTimeInterval32) Increment() ", "output": "{\n\tself.Add(1)\n}"} {"input": "package tabular\n\nimport (\n\t\"bytes\"\n\t\"github.com/omakoto/mlib\"\n\t\"strings\"\n)\n\n\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc doTabular(r <-chan []string, out chan<- string) {\n\tall := make([][]string, 0, 1024)\n\twidths := make([]int, 0)\n\n\tmlib.Debug(\"Reading input...\\n\")\n\n\tfor fields := range r {\n\t\tall = append(all, fields)\n\t\tfor i := 0; i < len(fields); i++ {\n\t\t\tif len(widths) < len(fields) {\n\t\t\t\told := widths\n\t\t\t\twidths = make([]int, len(fields))\n\t\t\t\tcopy(widths, old)\n\t\t\t}\n\t\t\tmlib.Debug(\" index=%d, cur=%d\\n\", i, widths[i])\n\t\t\twidths[i] = max(widths[i], stringWidth(fields[i]))\n\t\t}\n\t}\n\n\tmlib.Debug(\"Read all lines\\n\")\n\n\tmlib.DebugDump(all)\n\tmlib.DebugDump(widths)\n\n\toutBuffer := bytes.Buffer{}\n\n\tfor _, fields := range all {\n\t\toutBuffer.Reset()\n\t\tfor i := 0; i < len(fields); i++ {\n\t\t\tif i > 0 {\n\t\t\t\toutBuffer.WriteString(\" \")\n\t\t\t}\n\t\t\tw := stringWidth(fields[i])\n\t\t\toutBuffer.WriteString(fields[i])\n\t\t\toutBuffer.WriteString(strings.Repeat(\" \", widths[i]-w))\n\t\t}\n\t\tout <- outBuffer.String()\n\t}\n}\n\nfunc Tabular(r <-chan []string) <-chan string ", "output": "{\n\tout := make(chan string)\n\n\tgo func() {\n\t\tdefer close(out)\n\t\tdoTabular(r, out)\n\t}()\n\n\treturn out\n}"} {"input": "package common\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"testing\"\n\n\t\"github.com/google/go-github/github\"\n)\n\n\n\nfunc TestErrorFromResponse(t *testing.T) ", "output": "{\n\ttransportErr := errors.New(\"Something terrible happened\")\n\tresError := errors.New(\"unexpected error code: 404\")\n\thttpRes := &http.Response{StatusCode: http.StatusNotFound}\n\tres := &github.Response{Response: httpRes}\n\n\terr := ErrorFromResponse(res, transportErr)\n\tif err != transportErr {\n\t\tt.Fatalf(\"expected %v, got: %v\", transportErr, err)\n\t}\n\n\terr = ErrorFromResponse(res, nil)\n\tif err.Error() != resError.Error() {\n\t\tt.Fatalf(\"expected %v, got: %v\", resError, err)\n\t}\n}"} {"input": "package lib\n\nimport (\n\t\"github.com/atinm/spotify\"\n)\n\nfunc ignored(device string) bool {\n\tfor _, name := range config.Ignored {\n\t\tif name == device {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc FiltersEnabled() bool {\n\treturn ParentalControlsEnabled()\n}\n\n\n\nfunc Rules(track *spotify.FullTrack, device string) bool {\n\tif track != nil && rule.Explicit && track.Explicit && !ignored(device) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc SetParentalControls(b bool) {\n\trule.Explicit = b\n}\n\nfunc ParentalControlsEnabled() bool ", "output": "{\n\treturn rule.Explicit\n}"} {"input": "package conway\n\nimport (\n\t\"fmt\"\n)\n\nfunc Example_singleCell() {\n\tvar p = Population{cells: map[Cell]int{\n\t\tCell{0, 0}: 0,\n\t},\n\t\tpopNumber: 0,\n\t}\n\tp.Next()\n\tfmt.Println(p)\n}\n\n\n\nfunc Example_blinker() {\n\tvar p = Population{cells: map[Cell]int{\n\t\tCell{0, 0}: 0,\n\t\tCell{0, 1}: 0,\n\t\tCell{0, -1}: 0,\n\t},\n\t\tpopNumber: 0,\n\t}\n\tp.SaveToFile(\"blinker0.log\")\n\tp.Next()\n\tp.SaveToFile(\"blinker1.log\")\n\tfmt.Println(len(p.cells))\n}\n\nfunc Example_twoCells() ", "output": "{\n\tvar p = Population{cells: map[Cell]int{\n\t\tCell{0, 0}: 0,\n\t\tCell{0, 1}: 0,\n\t},\n\t\tpopNumber: 0,\n\t}\n\tp.Next()\n\tfmt.Println(p)\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\tx, y := split(22)\n\tfmt.Println(x, y)\n}\n\nfunc split(sum int) (x, y int) ", "output": "{\n\tx = sum * 4 / 9\n\ty = sum - x\n\treturn\n}"} {"input": "package store\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/ngaut/log\"\n\t\"github.com/reborndb/qdb/pkg/engine/rocksdb\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc TestT(t *testing.T) {\n\tTestingT(t)\n}\n\nvar _ = Suite(&testStoreSuite{})\n\ntype testStoreSuite struct {\n\ts *Store\n}\n\nfunc (s *testStoreSuite) SetUpSuite(c *C) {\n\ts.s = testCreateStore(c)\n}\n\nfunc (s *testStoreSuite) TearDownSuite(c *C) {\n\tif s.s != nil {\n\t\ts.s.Close()\n\t\ts = nil\n\t}\n}\n\nfunc (s *testStoreSuite) checkCompact(c *C) {\n\terr := s.s.CompactAll()\n\tc.Assert(err, IsNil)\n}\n\n\n\nfunc testCreateStore(c *C) *Store {\n\tbase := fmt.Sprintf(\"/tmp/test_qdb/test_store\")\n\terr := os.RemoveAll(base)\n\tc.Assert(err, IsNil)\n\n\terr = os.MkdirAll(base, 0700)\n\tc.Assert(err, IsNil)\n\n\tconf := rocksdb.NewDefaultConfig()\n\ttestdb, err := rocksdb.Open(path.Join(base, \"db\"), conf, false)\n\tc.Assert(err, IsNil)\n\n\ts := New(testdb)\n\treturn s\n}\n\nfunc init() {\n\tlog.SetLevel(log.LOG_LEVEL_ERROR)\n}\n\nfunc sleepms(n int) {\n\ttime.Sleep(time.Millisecond * time.Duration(n))\n}\n\nfunc (s *testStoreSuite) checkEmpty(c *C) ", "output": "{\n\tit := s.s.getIterator()\n\tdefer s.s.putIterator(it)\n\n\tit.SeekToFirst()\n\tc.Assert(it.Error(), IsNil)\n\tc.Assert(it.Valid(), Equals, false)\n}"} {"input": "package fileutil\n\nimport (\n\t\"os\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\n\n\n\n\n\n\nfunc Fdatasync(f *os.File) error {\n\treturn Fsync(f)\n}\n\nfunc Fsync(f *os.File) error ", "output": "{\n\t_, err := unix.FcntlInt(f.Fd(), unix.F_FULLFSYNC, 0)\n\treturn err\n}"} {"input": "package testnewsfeed\n\nimport (\n\t\"time\"\n \"testing\"\n\t\"github.com/go-redis/redis\"\n\tsw \"../go\"\n)\n\ntype MockErrorWrapper struct {\n t *testing.T\n}\n\nfunc (lw MockErrorWrapper) LogError(err error, format string, status int) {\n lw.t.Errorf(format, err)\n}\n\nvar InboundCounter = 0\n\ntype MockCassandraWrapper struct {\n}\n\nfunc (cw MockCassandraWrapper) AddInbound(i sw.Inbound) {\n InboundCounter++\n}\n\nfunc (cw MockCassandraWrapper) AddOutbound(o sw.Outbound) {\n}\n\ntype MockRedisWrapper struct {\n SetCounter int64\n}\n\nfunc (rw MockRedisWrapper) Get(key string) (string, error) {\n return \"\", redis.Nil\n}\n\nfunc (rw MockRedisWrapper) Set(key string, value string, ttl time.Duration) {\n rw.SetCounter++\n}\n\nfunc (rw MockRedisWrapper) Close() {\n}\n\ntype MockMySqlWrapper struct {\n Friends []sw.Friend\n}\n\nfunc (mw MockMySqlWrapper) Close() {\n}\n\nfunc (mw MockMySqlWrapper) FetchFriends(id string)([]sw.Friend, error) {\n return mw.Friends, nil\n}\n\nfunc AddFriend(results []sw.Friend, id int64, from int64, to int64) ([]sw.Friend) {\n f := sw.Friend{\n\t Id: id,\n\t From: sw.ToLink(from),\n\t To: sw.ToLink(to),\n }\n results = append(results, f)\n return results\n}\n\n\n\nfunc TestAddOutboundInner(t *testing.T) ", "output": "{\n ew := MockErrorWrapper{\n \tt: t,\n }\n cw := MockCassandraWrapper{\n }\n rw := MockRedisWrapper{\n \tSetCounter: 0,\n }\n ob := sw.Outbound {\n \tFrom: sw.ToLink(1),\n\tOccurred: time.Now(),\n\tSubject: \"test subject\",\n\tStory: \"test story\",\n }\n var results []sw.Friend\n results = AddFriend(results, 1, 1, 2)\n results = AddFriend(results, 2, 1, 3)\n results = AddFriend(results, 3, 1, 4)\n mw := MockMySqlWrapper{\n \tFriends: results,\n }\n sw.AddOutboundInner(ob, ew, cw, rw, mw)\n if InboundCounter != 3 {\n \tt.Errorf(\"expected 3 inbound but got %d instead\", InboundCounter)\n }\n}"} {"input": "package balancetransaction\n\nimport (\n\t\"net/http\"\n\n\tstripe \"github.com/stripe/stripe-go\"\n\t\"github.com/stripe/stripe-go/form\"\n)\n\n\ntype Client struct {\n\tB stripe.Backend\n\tKey string\n}\n\n\n\n\n\nfunc (c Client) Get(id string, params *stripe.BalanceTransactionParams) (*stripe.BalanceTransaction, error) {\n\tpath := stripe.FormatURLPath(\"/v1/balance_transactions/%s\", id)\n\ttransaction := &stripe.BalanceTransaction{}\n\terr := c.B.Call(http.MethodGet, path, c.Key, params, transaction)\n\treturn transaction, err\n}\n\n\nfunc List(params *stripe.BalanceTransactionListParams) *Iter {\n\treturn getC().List(params)\n}\n\n\nfunc (c Client) List(listParams *stripe.BalanceTransactionListParams) *Iter {\n\treturn &Iter{stripe.GetIter(listParams, func(p *stripe.Params, b *form.Values) ([]interface{}, stripe.ListMeta, error) {\n\t\tlist := &stripe.BalanceTransactionList{}\n\t\terr := c.B.CallRaw(http.MethodGet, \"/v1/balance_transactions\", c.Key, b, p, list)\n\n\t\tret := make([]interface{}, len(list.Data))\n\t\tfor i, v := range list.Data {\n\t\t\tret[i] = v\n\t\t}\n\n\t\treturn ret, list.ListMeta, err\n\t})}\n}\n\n\ntype Iter struct {\n\t*stripe.Iter\n}\n\n\nfunc (i *Iter) BalanceTransaction() *stripe.BalanceTransaction {\n\treturn i.Current().(*stripe.BalanceTransaction)\n}\n\nfunc getC() Client {\n\treturn Client{stripe.GetBackend(stripe.APIBackend), stripe.Key}\n}\n\nfunc Get(id string, params *stripe.BalanceTransactionParams) (*stripe.BalanceTransaction, error) ", "output": "{\n\treturn getC().Get(id, params)\n}"} {"input": "package test\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestTcBuildDir(t *testing.T) {\n\tv := TcBuildDir()\n\tif v == \"\" {\n\t\tt.Errorf(\"icorrect behavior\")\n\t}\n\t_, err := os.Stat(v)\n\tif err != nil {\n\t\tt.Errorf(\"invalid: %v\", err)\n\t}\n}\n\n\n\nfunc TestTcConfigName(t *testing.T) ", "output": "{\n\tv := TcConfigName()\n\tif len(v) <= len(Config) {\n\t\tt.Errorf(\"icorrect behavior\")\n\t}\n\t_, err := os.Stat(v)\n\tif err != nil {\n\t\tt.Errorf(\"invalid: %v\", err)\n\t}\n}"} {"input": "package eav\n\ntype (\n\tAttributeFrontendModeller interface {\n\t\tInputRenderer() FrontendInputRendererIFace\n\t\tGetValue()\n\t\tGetInputType() string\n\n\t\tConfig(...AttributeFrontendConfig) AttributeFrontendModeller\n\t}\n\tFrontendInputRendererIFace interface {\n\t}\n\tAttributeFrontend struct {\n\t\ta *Attribute\n\t\tidx AttributeIndex\n\t}\n\tAttributeFrontendConfig func(*AttributeFrontend)\n)\n\nvar _ AttributeFrontendModeller = (*AttributeFrontend)(nil)\n\n\nfunc NewAttributeFrontend(cfgs ...AttributeFrontendConfig) *AttributeFrontend {\n\tas := &AttributeFrontend{\n\t\ta: nil,\n\t}\n\tas.Config(cfgs...)\n\treturn as\n}\n\n\n\n\n\nfunc (af *AttributeFrontend) Config(configs ...AttributeFrontendConfig) AttributeFrontendModeller {\n\tfor _, cfg := range configs {\n\t\tcfg(af)\n\t}\n\treturn af\n}\n\nfunc (af *AttributeFrontend) InputRenderer() FrontendInputRendererIFace { return nil }\nfunc (af *AttributeFrontend) GetValue() {}\nfunc (af *AttributeFrontend) GetInputType() string {\n\treturn af.a.FrontendInput()\n}\n\nfunc AttributeFrontendIdx(i AttributeIndex) AttributeFrontendConfig ", "output": "{\n\treturn func(as *AttributeFrontend) {\n\t\tas.idx = i\n\t}\n}"} {"input": "package log\n\nimport (\n\t\"sync\"\n\n\t\"github.com/asim/go-micro/v3/util/ring\"\n\t\"github.com/google/uuid\"\n)\n\n\ntype osLog struct {\n\tformat FormatFunc\n\tonce sync.Once\n\n\tsync.RWMutex\n\tbuffer *ring.Buffer\n\tsubs map[string]*osStream\n}\n\ntype osStream struct {\n\tstream chan Record\n}\n\n\n\n\n\nfunc (o *osLog) Write(r Record) error {\n\to.buffer.Put(r)\n\treturn nil\n}\n\n\nfunc (o *osLog) Stream() (Stream, error) {\n\to.Lock()\n\tdefer o.Unlock()\n\n\tst := &osStream{\n\t\tstream: make(chan Record, 128),\n\t}\n\n\to.subs[uuid.New().String()] = st\n\n\treturn st, nil\n}\n\nfunc (o *osStream) Chan() <-chan Record {\n\treturn o.stream\n}\n\nfunc (o *osStream) Stop() error {\n\treturn nil\n}\n\nfunc NewLog(opts ...Option) Log {\n\toptions := Options{\n\t\tFormat: DefaultFormat,\n\t}\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\tl := &osLog{\n\t\tformat: options.Format,\n\t\tbuffer: ring.New(1024),\n\t\tsubs: make(map[string]*osStream),\n\t}\n\n\treturn l\n}\n\nfunc (o *osLog) Read(...ReadOption) ([]Record, error) ", "output": "{\n\tvar records []Record\n\n\tfor _, v := range o.buffer.Get(100) {\n\t\trecords = append(records, v.Value.(Record))\n\t}\n\n\treturn records, nil\n}"} {"input": "package common\n\n\n\nimport (\n\t\"github.com/mitchellh/multistep\"\n\t\"github.com/mitchellh/packer/packer\"\n\t\"log\"\n\t\"os\"\n\t\"time\"\n)\n\ntype StepPrepareOutputDir struct {\n\tForce bool\n\tPath string\n}\n\nfunc (self *StepPrepareOutputDir) Run(state multistep.StateBag) multistep.StepAction {\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\tif _, err := os.Stat(self.Path); err == nil && self.Force {\n\t\tui.Say(\"Deleting previous output directory...\")\n\t\tos.RemoveAll(self.Path)\n\t}\n\n\tif err := os.MkdirAll(self.Path, 0755); err != nil {\n\t\tstate.Put(\"error\", err)\n\t\treturn multistep.ActionHalt\n\t}\n\n\treturn multistep.ActionContinue\n}\n\n\n\nfunc (self *StepPrepareOutputDir) Cleanup(state multistep.StateBag) ", "output": "{\n\t_, cancelled := state.GetOk(multistep.StateCancelled)\n\t_, halted := state.GetOk(multistep.StateHalted)\n\n\tif cancelled || halted {\n\t\tui := state.Get(\"ui\").(packer.Ui)\n\n\t\tui.Say(\"Deleting output directory...\")\n\t\tfor i := 0; i < 5; i++ {\n\t\t\terr := os.RemoveAll(self.Path)\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tlog.Printf(\"Error removing output dir: %s\", err)\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t}\n\t}\n}"} {"input": "package authorization\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tAPIVersion = \"2015-01-01\"\n\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype ManagementClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) ManagementClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient ", "output": "{\n\treturn ManagementClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package grpclog \n\nimport \"os\"\n\nvar logger = newLoggerV2()\n\n\nfunc V(l int) bool {\n\treturn logger.V(l)\n}\n\n\nfunc Info(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\n\n\n\nfunc Infoln(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\n\nfunc Warning(args ...interface{}) {\n\tlogger.Warning(args...)\n}\n\n\nfunc Warningf(format string, args ...interface{}) {\n\tlogger.Warningf(format, args...)\n}\n\n\nfunc Warningln(args ...interface{}) {\n\tlogger.Warningln(args...)\n}\n\n\nfunc Error(args ...interface{}) {\n\tlogger.Error(args...)\n}\n\n\nfunc Errorf(format string, args ...interface{}) {\n\tlogger.Errorf(format, args...)\n}\n\n\nfunc Errorln(args ...interface{}) {\n\tlogger.Errorln(args...)\n}\n\n\n\nfunc Fatal(args ...interface{}) {\n\tlogger.Fatal(args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalf(format string, args ...interface{}) {\n\tlogger.Fatalf(format, args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalln(args ...interface{}) {\n\tlogger.Fatalln(args...)\n\tos.Exit(1)\n}\n\n\n\n\nfunc Print(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\n\n\nfunc Printf(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\n\n\nfunc Println(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\nfunc Infof(format string, args ...interface{}) ", "output": "{\n\tlogger.Infof(format, args...)\n}"} {"input": "package collector\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"unsafe\"\n\n\t\"github.com/go-kit/log\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\n\nimport \"C\"\n\nconst maxCPUTimesLen = C.MAXCPU * C.CPUSTATES\n\ntype statCollector struct {\n\tcpu *prometheus.Desc\n\tlogger log.Logger\n}\n\nfunc init() {\n\tregisterCollector(\"cpu\", defaultEnabled, NewStatCollector)\n}\n\n\nfunc NewStatCollector(logger log.Logger) (Collector, error) {\n\treturn &statCollector{\n\t\tcpu: nodeCPUSecondsDesc,\n\t\tlogger: logger,\n\t}, nil\n}\n\n\n\n\nfunc (c *statCollector) Update(ch chan<- prometheus.Metric) error {\n\tvar fieldsCount = 5\n\tcpuTimes, err := getDragonFlyCPUTimes()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcpuFields := []string{\"user\", \"nice\", \"sys\", \"interrupt\", \"idle\"}\n\tfor i, value := range cpuTimes {\n\t\tcpux := strconv.Itoa(i / fieldsCount)\n\t\tch <- prometheus.MustNewConstMetric(c.cpu, prometheus.CounterValue, value, cpux, cpuFields[i%fieldsCount])\n\t}\n\n\treturn nil\n}\n\nfunc getDragonFlyCPUTimes() ([]float64, error) ", "output": "{\n\n\tvar (\n\t\tcpuTimesC *C.uint64_t\n\t\tcpuTimesLength C.size_t\n\t)\n\n\tif C.getCPUTimes(&cpuTimesC, &cpuTimesLength) == -1 {\n\t\treturn nil, errors.New(\"could not retrieve CPU times\")\n\t}\n\tdefer C.free(unsafe.Pointer(cpuTimesC))\n\n\tcput := (*[maxCPUTimesLen]C.uint64_t)(unsafe.Pointer(cpuTimesC))[:cpuTimesLength:cpuTimesLength]\n\n\tcpuTimes := make([]float64, cpuTimesLength)\n\tfor i, value := range cput {\n\t\tcpuTimes[i] = float64(value) / float64(1000000)\n\t}\n\treturn cpuTimes, nil\n}"} {"input": "package core\n\nimport \"go/ast\"\n\nfunc resolveIdent(n *ast.Ident, c *Context) bool {\n\tif n.Obj == nil || n.Obj.Kind != ast.Var {\n\t\treturn true\n\t}\n\tif node, ok := n.Obj.Decl.(ast.Node); ok {\n\t\treturn TryResolve(node, c)\n\t}\n\treturn false\n}\n\nfunc resolveAssign(n *ast.AssignStmt, c *Context) bool {\n\tfor _, arg := range n.Rhs {\n\t\tif !TryResolve(arg, c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc resolveCompLit(n *ast.CompositeLit, c *Context) bool {\n\tfor _, arg := range n.Elts {\n\t\tif !TryResolve(arg, c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\nfunc resolveCallExpr(n *ast.CallExpr, c *Context) bool {\n\treturn false\n}\n\n\n\n\nfunc TryResolve(n ast.Node, c *Context) bool {\n\tswitch node := n.(type) {\n\tcase *ast.BasicLit:\n\t\treturn true\n\n\tcase *ast.CompositeLit:\n\t\treturn resolveCompLit(node, c)\n\n\tcase *ast.Ident:\n\t\treturn resolveIdent(node, c)\n\n\tcase *ast.AssignStmt:\n\t\treturn resolveAssign(node, c)\n\n\tcase *ast.CallExpr:\n\t\treturn resolveCallExpr(node, c)\n\n\tcase *ast.BinaryExpr:\n\t\treturn resolveBinExpr(node, c)\n\t}\n\n\treturn false\n}\n\nfunc resolveBinExpr(n *ast.BinaryExpr, c *Context) bool ", "output": "{\n\treturn (TryResolve(n.X, c) && TryResolve(n.Y, c))\n}"} {"input": "package req\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n)\n\ntype execChans struct {\n\tOut chan ResponseInfo\n\tErrs chan error\n\tDone chan bool\n}\n\ntype scenarioExecutor interface {\n\texecute(scen RequestScenario, chans execChans)\n}\n\nfunc Execute(scen RequestScenario, writer io.Writer) error {\n\n\tsetOptions(scen.Options)\n\n\texplainScenario(scen)\n\n\tchans := execChans{\n\t\tOut: make(chan ResponseInfo),\n\t\tErrs: make(chan error),\n\t\tDone: make(chan bool),\n\t}\n\texecScenario(scen, chans)\n\n\tfor {\n\t\tselect {\n\t\tcase res := <-chans.Out:\n\t\t\tif err := printResponse(res, writer); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase err := <-chans.Errs:\n\t\t\treturn err\n\t\tcase <-chans.Done:\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\nfunc execScenario(scen RequestScenario, chans execChans) {\n\tif len(scen.Bots) == 0 {\n\t\texecScenarioLocally(scen, chans)\n\t} else {\n\t\texecScenarioDistributed(scen, chans)\n\t}\n}\n\n\n\nfunc printResponse(res ResponseInfo, writer io.Writer) error {\n\tvar data []byte\n\tvar err error\n\n\tif options.Pretty {\n\t\tdata, err = json.MarshalIndent(res, \"\", \" \")\n\t} else {\n\t\tdata, err = json.Marshal(res)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to format %v to json: %v\", res, err)\n\t}\n\t_, err = writer.Write(append(data, '\\n'))\n\treturn err\n}\n\nfunc explainScenario(scen RequestScenario) error ", "output": "{\n\tvar data []byte\n\tvar err error\n\n\tif options.Pretty {\n\t\tdata, err = json.MarshalIndent(scen, \"\", \" \")\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to format %v to json: %v\", scen, err)\n\t}\n\n\tlog.Printf(\"Executing scenario:\\n%v\\n==================\\n\\n\", string(data))\n\n\treturn nil\n}"} {"input": "package net_sniff\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com/bettercap/bettercap/session\"\n\n\t\"github.com/evilsocket/islazy/tui\"\n\t\"github.com/google/gopacket/layers\"\n)\n\nfunc vIP(ip net.IP) string {\n\tif session.I.Interface.IP.Equal(ip) {\n\t\treturn tui.Dim(\"local\")\n\t} else if session.I.Gateway.IP.Equal(ip) {\n\t\treturn \"gateway\"\n\t}\n\n\taddress := ip.String()\n\thost := session.I.Lan.GetByIp(address)\n\tif host != nil {\n\t\tif host.Hostname != \"\" {\n\t\t\treturn host.Hostname\n\t\t}\n\t}\n\n\treturn address\n}\n\nfunc vPort(p interface{}) string {\n\tsp := fmt.Sprintf(\"%d\", p)\n\tif tcp, ok := p.(layers.TCPPort); ok {\n\t\tif name, found := layers.TCPPortNames[tcp]; found {\n\t\t\tsp = tui.Yellow(name)\n\t\t}\n\t} else if udp, ok := p.(layers.UDPPort); ok {\n\t\tif name, found := layers.UDPPortNames[udp]; found {\n\t\t\tsp = tui.Yellow(name)\n\t\t}\n\t}\n\n\treturn sp\n}\n\nvar maxUrlSize = 80\n\n\n\nfunc vURL(u string) string ", "output": "{\n\tul := len(u)\n\tif ul > maxUrlSize {\n\t\tu = fmt.Sprintf(\"%s...\", u[0:maxUrlSize-3])\n\t}\n\treturn u\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc dumpCmd() command ", "output": "{\n\treturn command{fn: func([]string) error {\n\t\treturn fmt.Errorf(\"vegeta dump has been deprecated and succeeded by the vegeta encode command\")\n\t}}\n}"} {"input": "package api\n\nimport (\n\t\"debug/gosym\"\n\t\"github.com/derekparker/delve/proc\"\n)\n\n\nfunc ConvertBreakpoint(bp *proc.Breakpoint) *Breakpoint {\n\treturn &Breakpoint{\n\t\tID: bp.ID,\n\t\tFunctionName: bp.FunctionName,\n\t\tFile: bp.File,\n\t\tLine: bp.Line,\n\t\tAddr: bp.Addr,\n\t}\n}\n\n\nfunc ConvertThread(th *proc.Thread) *Thread {\n\tvar (\n\t\tfunction *Function\n\t\tfile string\n\t\tline int\n\t\tpc uint64\n\t)\n\n\tloc, err := th.Location()\n\tif err == nil {\n\t\tpc = loc.PC\n\t\tfile = loc.File\n\t\tline = loc.Line\n\t\tfunction = ConvertFunction(loc.Fn)\n\t}\n\n\treturn &Thread{\n\t\tID: th.Id,\n\t\tPC: pc,\n\t\tFile: file,\n\t\tLine: line,\n\t\tFunction: function,\n\t}\n}\n\n\nfunc ConvertVar(v *proc.Variable) Variable {\n\treturn Variable{\n\t\tName: v.Name,\n\t\tValue: v.Value,\n\t\tType: v.Type,\n\t}\n}\n\nfunc ConvertFunction(fn *gosym.Func) *Function {\n\tif fn == nil {\n\t\treturn nil\n\t}\n\n\treturn &Function{\n\t\tName: fn.Name,\n\t\tType: fn.Type,\n\t\tValue: fn.Value,\n\t\tGoType: fn.GoType,\n\t}\n}\n\n\nfunc ConvertGoroutine(g *proc.G) *Goroutine {\n\treturn &Goroutine{\n\t\tID: g.Id,\n\t\tPC: g.PC,\n\t\tFile: g.File,\n\t\tLine: g.Line,\n\t\tFunction: ConvertFunction(g.Func),\n\t}\n}\n\n\n\nfunc ConvertLocation(loc proc.Location) Location ", "output": "{\n\treturn Location{\n\t\tPC: loc.PC,\n\t\tFile: loc.File,\n\t\tLine: loc.Line,\n\t\tFunction: ConvertFunction(loc.Fn),\n\t}\n}"} {"input": "package githubsource\n\nimport (\n\tcontext \"context\"\n\n\tv1 \"k8s.io/api/core/v1\"\n\tv1alpha1 \"knative.dev/eventing-github/pkg/apis/sources/v1alpha1\"\n\tgithubsource \"knative.dev/eventing-github/pkg/client/injection/reconciler/sources/v1alpha1/githubsource\"\n\treconciler \"knative.dev/pkg/reconciler\"\n)\n\n\n\n\n\nfunc newReconciledNormal(namespace, name string) reconciler.Event {\n\treturn reconciler.NewEvent(v1.EventTypeNormal, \"GitHubSourceReconciled\", \"GitHubSource reconciled: \\\"%s/%s\\\"\", namespace, name)\n}\n\n\ntype Reconciler struct {\n}\n\n\nvar _ githubsource.Interface = (*Reconciler)(nil)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (r *Reconciler) ReconcileKind(ctx context.Context, o *v1alpha1.GitHubSource) reconciler.Event ", "output": "{\n\n\n\treturn newReconciledNormal(o.Namespace, o.Name)\n}"} {"input": "package ehttp\n\nimport (\n\t\"encoding/json\"\n\t\"path\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc getCallstack(skip int) (string, string, int) {\n\tvar name string\n\tpc, file, line, ok := runtime.Caller(1 + skip)\n\tif !ok {\n\t\tname, file, line = \"\", \"\", -1\n\t} else {\n\t\tname = runtime.FuncForPC(pc).Name()\n\t\tname = path.Base(name)\n\t\tfile = path.Base(file)\n\t}\n\treturn name, file, line\n}\n\nfunc assertInt(t *testing.T, expect, got int) {\n\t_, file, line := getCallstack(1)\n\tif expect != got {\n\t\tt.Errorf(\"[%s:%d] Unexpected result.\\nExpect:\\t%d\\nGot:\\t%d\\n\", file, line, expect, got)\n\t}\n}\n\nfunc assertString(t *testing.T, expect, got string) {\n\t_, file, line := getCallstack(1)\n\texpect, got = strings.TrimSpace(expect), strings.TrimSpace(got)\n\tif expect != got {\n\t\tt.Errorf(\"[%s:%d] Unexpected result.\\nExpect:\\t%s\\nGot:\\t%s\\n\", file, line, expect, got)\n\t}\n}\n\n\n\nfunc assertJSONError(t *testing.T, expect, got string) ", "output": "{\n\t_, file, line := getCallstack(1)\n\texpect, got = strings.TrimSpace(expect), strings.TrimSpace(got)\n\n\tjErr := JSONError{}\n\tif err := json.Unmarshal([]byte(got), &jErr); err != nil {\n\t\tt.Errorf(\"[%s:%d] Error parsing json error: %s\\n\", file, line, expect)\n\t}\n\tfor _, errStr := range jErr.Errors {\n\t\tif errStr == expect {\n\t\t\treturn\n\t\t}\n\t}\n\tt.Errorf(\"[%s:%d] Unexpected error.\\nExpect:\\t%s\\nGot:\\t%s\\n\", file, line, expect, got)\n}"} {"input": "package openstack\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/go-ini/ini\"\n\t\"github.com/rancher/types/apis/management.cattle.io/v3\"\n)\n\nconst (\n\tOpenstackCloudProviderName = \"openstack\"\n)\n\ntype CloudProvider struct {\n\tConfig *v3.OpenstackCloudProvider\n\tName string\n}\n\nfunc GetInstance() *CloudProvider {\n\treturn &CloudProvider{}\n}\n\nfunc (p *CloudProvider) Init(cloudProviderConfig v3.CloudProvider) error {\n\tif cloudProviderConfig.OpenstackCloudProvider == nil {\n\t\treturn fmt.Errorf(\"Openstack Cloud Provider Config is empty\")\n\t}\n\tp.Name = OpenstackCloudProviderName\n\tif cloudProviderConfig.Name != \"\" {\n\t\tp.Name = cloudProviderConfig.Name\n\t}\n\tp.Config = cloudProviderConfig.OpenstackCloudProvider\n\treturn nil\n}\n\nfunc (p *CloudProvider) GetName() string {\n\treturn p.Name\n}\n\n\n\nfunc (p *CloudProvider) GenerateCloudConfigFile() (string, error) ", "output": "{\n\tbuf := new(bytes.Buffer)\n\tcloudConfig, _ := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: true}, []byte(\"\"))\n\tif err := ini.ReflectFrom(cloudConfig, p.Config); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to parse Openstack cloud config\")\n\t}\n\tif _, err := cloudConfig.WriteTo(buf); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn buf.String(), nil\n}"} {"input": "package iso20022\n\n\ntype ChargeType1 struct {\n\n\tStructured *ChargeType6Code `xml:\"Strd\"`\n\n\tAdditionalInformation *Max350Text `xml:\"AddtlInf,omitempty\"`\n}\n\n\n\nfunc (c *ChargeType1) SetAdditionalInformation(value string) {\n\tc.AdditionalInformation = (*Max350Text)(&value)\n}\n\nfunc (c *ChargeType1) SetStructured(value string) ", "output": "{\n\tc.Structured = (*ChargeType6Code)(&value)\n}"} {"input": "package githubsource\n\nimport (\n\tcontext \"context\"\n\n\tv1 \"k8s.io/api/core/v1\"\n\tv1alpha1 \"knative.dev/eventing-github/pkg/apis/sources/v1alpha1\"\n\tgithubsource \"knative.dev/eventing-github/pkg/client/injection/reconciler/sources/v1alpha1/githubsource\"\n\treconciler \"knative.dev/pkg/reconciler\"\n)\n\n\n\n\n\n\n\n\ntype Reconciler struct {\n}\n\n\nvar _ githubsource.Interface = (*Reconciler)(nil)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (r *Reconciler) ReconcileKind(ctx context.Context, o *v1alpha1.GitHubSource) reconciler.Event {\n\n\n\treturn newReconciledNormal(o.Namespace, o.Name)\n}\n\nfunc newReconciledNormal(namespace, name string) reconciler.Event ", "output": "{\n\treturn reconciler.NewEvent(v1.EventTypeNormal, \"GitHubSourceReconciled\", \"GitHubSource reconciled: \\\"%s/%s\\\"\", namespace, name)\n}"} {"input": "package seccomp\n\nimport (\n\tseccomp_compiler \"github.com/snapcore/snapd/sandbox/seccomp\"\n)\n\n\n\n\n\nfunc MockTemplate(fakeTemplate []byte) (restore func()) {\n\torig := defaultTemplate\n\torigBarePrivDropSyscalls := barePrivDropSyscalls\n\tdefaultTemplate = fakeTemplate\n\tbarePrivDropSyscalls = \"\"\n\treturn func() {\n\t\tdefaultTemplate = orig\n\t\tbarePrivDropSyscalls = origBarePrivDropSyscalls\n\t}\n}\n\nfunc MockKernelFeatures(f func() []string) (resture func()) {\n\told := kernelFeatures\n\tkernelFeatures = f\n\treturn func() {\n\t\tkernelFeatures = old\n\t}\n}\n\nfunc MockRequiresSocketcall(f func(string) bool) (restore func()) {\n\told := requiresSocketcall\n\trequiresSocketcall = f\n\treturn func() {\n\t\trequiresSocketcall = old\n\t}\n}\n\n\n\nfunc MockReleaseInfoId(s string) (restore func()) {\n\told := releaseInfoId\n\treleaseInfoId = s\n\treturn func() {\n\t\treleaseInfoId = old\n\t}\n}\n\nfunc MockReleaseInfoVersionId(s string) (restore func()) {\n\told := releaseInfoVersionId\n\treleaseInfoVersionId = s\n\treturn func() {\n\t\treleaseInfoVersionId = old\n\t}\n}\n\nfunc MockSeccompCompilerLookup(f func(string) (string, error)) (restore func()) {\n\told := seccompCompilerLookup\n\tseccompCompilerLookup = f\n\treturn func() {\n\t\tseccompCompilerLookup = old\n\t}\n}\n\nfunc (b *Backend) VersionInfo() seccomp_compiler.VersionInfo {\n\treturn b.versionInfo\n}\n\nvar (\n\tRequiresSocketcall = requiresSocketcall\n\n\tGlobalProfileLE = globalProfileLE\n\tGlobalProfileBE = globalProfileBE\n\tIsBigEndian = isBigEndian\n)\n\nfunc MockDpkgKernelArchitecture(f func() string) (restore func()) ", "output": "{\n\told := dpkgKernelArchitecture\n\tdpkgKernelArchitecture = f\n\treturn func() {\n\t\tdpkgKernelArchitecture = old\n\t}\n}"} {"input": "package main\n\nimport \"github.com/augustoroman/serial_lcd\"\n\ntype FakeLcd struct{}\n\nfunc (f FakeLcd) SetBG(r, g, b uint8) error { return nil }\nfunc (f FakeLcd) SetOn(On bool) error { return nil }\nfunc (f FakeLcd) SetBrightness(b uint8) error { return nil }\nfunc (f FakeLcd) SetContrast(c uint8) error { return nil }\nfunc (f FakeLcd) SetAutoscroll(On bool) error { return nil }\n\nfunc (f FakeLcd) Clear() error { return nil }\nfunc (f FakeLcd) Home() error { return nil }\nfunc (f FakeLcd) MoveTo(col, row uint8) error { return nil }\nfunc (f FakeLcd) MoveForward() error { return nil }\nfunc (f FakeLcd) MoveBack() error { return nil }\nfunc (f FakeLcd) Write(b []byte) (int, error) { return len(b), nil }\n\nfunc (f FakeLcd) CreateCustomChar(spot uint8, c serial_lcd.Char) error { return nil }\n\nfunc (f FakeLcd) SetSize(cols, rows uint8) error ", "output": "{ return nil }"} {"input": "package packet_proxy\n\nimport (\n\t\"github.com/bettercap/bettercap/session\"\n)\n\ntype PacketProxy struct {\n\tsession.SessionModule\n}\n\nfunc NewPacketProxy(s *session.Session) *PacketProxy {\n\treturn &PacketProxy{\n\t\tSessionModule: session.NewSessionModule(\"packet.proxy\", s),\n\t}\n}\n\nfunc (mod PacketProxy) Name() string {\n\treturn \"packet.proxy\"\n}\n\nfunc (mod PacketProxy) Description() string {\n\treturn \"Not supported on this OS\"\n}\n\nfunc (mod PacketProxy) Author() string {\n\treturn \"Simone Margaritelli \"\n}\n\n\n\nfunc (mod *PacketProxy) Start() error {\n\treturn session.ErrNotSupported\n}\n\nfunc (mod *PacketProxy) Stop() error {\n\treturn session.ErrNotSupported\n}\n\nfunc (mod *PacketProxy) Configure() (err error) ", "output": "{\n\treturn session.ErrNotSupported\n}"} {"input": "package identify\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewPostNodesIdentifierObmIdentifyParams() *PostNodesIdentifierObmIdentifyParams {\n\tvar ()\n\treturn &PostNodesIdentifierObmIdentifyParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\nfunc NewPostNodesIdentifierObmIdentifyParamsWithTimeout(timeout time.Duration) *PostNodesIdentifierObmIdentifyParams {\n\tvar ()\n\treturn &PostNodesIdentifierObmIdentifyParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype PostNodesIdentifierObmIdentifyParams struct {\n\n\tBody *bool\n\tIdentifier string\n\n\ttimeout time.Duration\n}\n\n\n\n\n\nfunc (o *PostNodesIdentifierObmIdentifyParams) WithIdentifier(identifier string) *PostNodesIdentifierObmIdentifyParams {\n\to.Identifier = identifier\n\treturn o\n}\n\n\nfunc (o *PostNodesIdentifierObmIdentifyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetBodyParam(o.Body); err != nil {\n\t\treturn err\n\t}\n\n\tif err := r.SetPathParam(\"identifier\", o.Identifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (o *PostNodesIdentifierObmIdentifyParams) WithBody(body *bool) *PostNodesIdentifierObmIdentifyParams ", "output": "{\n\to.Body = body\n\treturn o\n}"} {"input": "package account\n\nimport (\n\t\"flag\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n)\n\ntype update struct {\n\t*AccountFlag\n}\n\nfunc init() {\n\tcli.Register(\"host.account.update\", &update{})\n}\n\nfunc (cmd *update) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.AccountFlag, ctx = newAccountFlag(ctx)\n\tcmd.AccountFlag.Register(ctx, f)\n}\n\nfunc (cmd *update) Process(ctx context.Context) error {\n\tif err := cmd.AccountFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc (cmd *update) Run(ctx context.Context, f *flag.FlagSet) error ", "output": "{\n\tm, err := cmd.AccountFlag.HostAccountManager(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn m.Update(ctx, &cmd.HostAccountSpec)\n}"} {"input": "package web\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/gravitational/teleport/lib/httplib\"\n\n\t\"github.com/gravitational/roundtrip\"\n\t\"github.com/gravitational/trace\"\n)\n\nfunc newInsecureClient() *http.Client {\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t}\n}\n\nfunc newClientWithPool(pool *x509.CertPool) *http.Client {\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{RootCAs: pool},\n\t\t},\n\t}\n}\n\nfunc newWebClient(url string, opts ...roundtrip.ClientParam) (*webClient, error) {\n\tclt, err := roundtrip.NewClient(url, APIVersion, opts...)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn &webClient{clt}, nil\n}\n\n\n\ntype webClient struct {\n\t*roundtrip.Client\n}\n\n\n\nfunc (w *webClient) PutJSON(\n\tendpoint string, val interface{}) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.PutJSON(endpoint, val))\n}\n\nfunc (w *webClient) Get(endpoint string, val url.Values) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.Get(endpoint, val))\n}\n\nfunc (w *webClient) Delete(endpoint string) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.Delete(endpoint))\n}\n\nfunc (w *webClient) PostJSON(\n\tendpoint string, val interface{}) (*roundtrip.Response, error) ", "output": "{\n\treturn httplib.ConvertResponse(w.Client.PostJSON(endpoint, val))\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/apier/v1\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdRemoveBalance{\n\t\tname: \"balance_remove\",\n\t\trpcMethod: \"ApierV1.RemoveBalances\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdRemoveBalance struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrAddBalance\n\t*CommandExecuter\n}\n\nfunc (self *CmdRemoveBalance) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdRemoveBalance) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdRemoveBalance) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrAddBalance{BalanceType: utils.MONETARY, Overwrite: false}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdRemoveBalance) PostprocessRpcParams() error {\n\treturn nil\n}\n\n\n\nfunc (self *CmdRemoveBalance) RpcResult() interface{} ", "output": "{\n\tvar s string\n\treturn &s\n}"} {"input": "package main\n\n\nimport \"C\"\nimport \"./windows\"\n\nfunc init() {\n\tregister(\"CgoDLLImportsMain\", CgoDLLImportsMain)\n}\n\n\n\nfunc CgoDLLImportsMain() ", "output": "{\n\tC.getthread()\n\twindows.GetThread()\n\tprintln(\"OK\")\n}"} {"input": "package base\n\nimport (\n\t\"math\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc GaussianRandom() {\n\n\trand.Seed(99)\n\n}\n\n\n\nfunc GetRani(a float64, b float64) float64 {\n\n\treturn math.Floor(GetRandf(a, b))\n}\n\nfunc GetRandn(mu float64, std float64) float64 {\n\n\treturn rand.NormFloat64()*mu + std\n}\n\nfunc GetRandf(a float64, b float64) float64 ", "output": "{\n\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\treturn (b-a)*r.Float64() + a \n}"} {"input": "package types\n\nimport \"fmt\"\n\ntype IntegerValue struct {\n\tValue int64\n}\n\nfunc (v *IntegerValue) ToString() string {\n\treturn fmt.Sprint(v.Value)\n}\n\nfunc (v *IntegerValue) GetType() string {\n\treturn \"integer\"\n}\n\n\n\nfunc (v *IntegerValue) ConvertTo(t string) (ValueType, error) {\n\treturn nil, fmt.Errorf(\"cannot convert integer to %s: does not implement yet\", t)\n}\n\nfunc (v *IntegerValue) EqualTo(t ValueType) bool {\n\tif v2, ok := t.(*IntegerValue); ok {\n\t\tif v2.Value == v.Value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc NewIntegerValue(v int64) *IntegerValue {\n\treturn &IntegerValue{Value: v}\n}\n\nfunc (v *IntegerValue) IsValue() bool ", "output": "{\n\treturn true\n}"} {"input": "package term\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc IsANSI(f *os.File) bool {\n\treturn IsTerminal(f)\n}\n\n\nfunc IsTerminal(f *os.File) bool {\n\tcmd := exec.Command(\"test\", \"-t\", \"0\")\n\tcmd.Stdin = f\n\treturn cmd.Run() == nil\n}\n\nfunc MakeRaw(f *os.File) error {\n\treturn stty(f, \"-icanon\", \"-echo\").Run()\n}\n\n\n\nfunc Cols() (int, error) {\n\tcols, err := tput(\"cols\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}\n\nfunc Lines() (int, error) {\n\tcols, err := tput(\"lines\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}\n\n\n\nfunc stty(f *os.File, args ...string) *exec.Cmd {\n\tc := exec.Command(\"stty\", args...)\n\tc.Stdin = f\n\treturn c\n}\n\nfunc tput(what string) (string, error) {\n\tc := exec.Command(\"tput\", what)\n\tc.Stderr = os.Stderr\n\tout, err := c.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.TrimSpace(string(out)), nil\n}\n\nfunc Restore(f *os.File) error ", "output": "{\n\treturn stty(f, \"icanon\", \"echo\").Run()\n}"} {"input": "package text\n\nimport \"fmt\"\n\nconst (\n\tredCode = \"\\x1b[31m\"\n\tgreenCode = \"\\x1b[32m\"\n\tyellowCode = \"\\x1b[33m\"\n\tblueCode = \"\\x1b[34m\"\n\tmagentaCode = \"\\x1b[35m\"\n\tCyanCode = \"\\x1b[36m\"\n\tboldCode = \"\\x1b[1m\"\n\n\tResetCode = \"\\x1b[0m\"\n)\n\n\nvar UseColor = true\n\n\n\nfunc Red(in string) string {\n\treturn stylize(redCode, in)\n}\n\nfunc Green(in string) string {\n\treturn stylize(greenCode, in)\n}\n\nfunc yellow(in string) string {\n\treturn stylize(yellowCode, in)\n}\n\nfunc Cyan(in string) string {\n\treturn stylize(CyanCode, in)\n}\n\nfunc Magenta(in string) string {\n\treturn stylize(magentaCode, in)\n}\n\nfunc Blue(in string) string {\n\treturn stylize(blueCode, in)\n}\n\nfunc Bold(in string) string {\n\treturn stylize(boldCode, in)\n}\n\n\n\nfunc ColorHash(name string) (output string) {\n\tif !UseColor {\n\t\treturn name\n\t}\n\n\tvar hash uint = 5381\n\n\tfor i := 0; i < len(name); i++ {\n\t\thash = uint(name[i]) + ((hash << 5) + (hash))\n\t}\n\n\treturn fmt.Sprintf(\"\\x1b[%dm%s\\x1b[0m\", hash%6+31, name)\n}\n\nfunc stylize(startCode, in string) string ", "output": "{\n\tif UseColor {\n\t\treturn startCode + in + ResetCode\n\t}\n\n\treturn in\n}"} {"input": "package commands\n\nimport (\n\t\"strings\"\n\n\t\"github.com/github/hub/v2/github\"\n\t\"github.com/github/hub/v2/utils\"\n)\n\nvar cmdPush = &Command{\n\tRun: push,\n\tGitExtension: true,\n\tUsage: \"push [,...] []\",\n\tLong: `Push a git branch to each of the listed remotes.\n\n## Examples:\n\t\t$ hub push origin,staging,qa bert_timeout\n\t\t> git push origin bert_timeout\n\t\t> git push staging bert_timeout\n\t\t> git push qa bert_timeout\n\n\t\t$ hub push origin\n\t\t> git push origin HEAD\n\n## See also:\n\nhub(1), git-push(1)\n`,\n}\n\nfunc init() {\n\tCmdRunner.Use(cmdPush)\n}\n\nfunc push(command *Command, args *Args) {\n\tif !args.IsParamsEmpty() && strings.Contains(args.FirstParam(), \",\") {\n\t\ttransformPushArgs(args)\n\t}\n}\n\n\n\nfunc transformPushArgs(args *Args) ", "output": "{\n\trefs := []string{}\n\tif args.ParamsSize() > 1 {\n\t\trefs = args.Params[1:]\n\t}\n\n\tremotes := strings.Split(args.FirstParam(), \",\")\n\targs.ReplaceParam(0, remotes[0])\n\n\tif len(refs) == 0 {\n\t\tlocalRepo, err := github.LocalRepo()\n\t\tutils.Check(err)\n\n\t\thead, err := localRepo.CurrentBranch()\n\t\tutils.Check(err)\n\n\t\trefs = []string{head.ShortName()}\n\t\targs.AppendParams(refs...)\n\t}\n\n\tfor _, remote := range remotes[1:] {\n\t\tafterCmd := []string{\"git\", \"push\", remote}\n\t\tafterCmd = append(afterCmd, refs...)\n\t\targs.After(afterCmd...)\n\t}\n}"} {"input": "package options\n\n\ntype UpdateOptions struct {\n\tArrayFilters *ArrayFilters\n\n\tBypassDocumentValidation *bool\n\n\tCollation *Collation\n\n\tHint interface{}\n\n\tUpsert *bool\n}\n\n\nfunc Update() *UpdateOptions {\n\treturn &UpdateOptions{}\n}\n\n\nfunc (uo *UpdateOptions) SetArrayFilters(af ArrayFilters) *UpdateOptions {\n\tuo.ArrayFilters = &af\n\treturn uo\n}\n\n\n\n\n\nfunc (uo *UpdateOptions) SetCollation(c *Collation) *UpdateOptions {\n\tuo.Collation = c\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetHint(h interface{}) *UpdateOptions {\n\tuo.Hint = h\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetUpsert(b bool) *UpdateOptions {\n\tuo.Upsert = &b\n\treturn uo\n}\n\n\nfunc MergeUpdateOptions(opts ...*UpdateOptions) *UpdateOptions {\n\tuOpts := Update()\n\tfor _, uo := range opts {\n\t\tif uo == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif uo.ArrayFilters != nil {\n\t\t\tuOpts.ArrayFilters = uo.ArrayFilters\n\t\t}\n\t\tif uo.BypassDocumentValidation != nil {\n\t\t\tuOpts.BypassDocumentValidation = uo.BypassDocumentValidation\n\t\t}\n\t\tif uo.Collation != nil {\n\t\t\tuOpts.Collation = uo.Collation\n\t\t}\n\t\tif uo.Hint != nil {\n\t\t\tuOpts.Hint = uo.Hint\n\t\t}\n\t\tif uo.Upsert != nil {\n\t\t\tuOpts.Upsert = uo.Upsert\n\t\t}\n\t}\n\n\treturn uOpts\n}\n\nfunc (uo *UpdateOptions) SetBypassDocumentValidation(b bool) *UpdateOptions ", "output": "{\n\tuo.BypassDocumentValidation = &b\n\treturn uo\n}"} {"input": "package api\n\nimport (\n\t\"errors\"\n\t\"os/user\"\n)\n\nconst (\n\tcountOfColumnsInGroup = 3\n\n\tnameColumnNumberInGroup = 0\n\n\tpasswordFlagColumnNumberInGroup = 1\n\n\tgidColumnNumberInGroup = 2\n\n\tusersColumnNumberInGroup = 3\n)\n\nfunc (linux *Linux) groupLookup(groupName string) (*user.Group, error) {\n\tgroupInfo, err := linux.getEntity(\"group\", groupName)\n\n\tif err != nil {\n\t\treturn nil, user.UnknownGroupError(groupName)\n\t}\n\n\tif len(groupInfo) < countOfColumnsInGroup {\n\t\treturn nil, errors.New(\"Wrong format of /etc/group\")\n\t}\n\n\tgroup := user.Group{\n\t\tGid: groupInfo[gidColumnNumberInGroup],\n\t\tName: groupInfo[nameColumnNumberInGroup],\n\t}\n\n\treturn &group, err\n}\n\nfunc (linux *Linux) groupLookupByID(groupID string) (*user.Group, error) {\n\tgroupInfo, err := linux.getEntity(\"group\", groupID)\n\n\tif err != nil {\n\t\treturn nil, user.UnknownGroupIdError(groupID)\n\t}\n\n\tif len(groupInfo) < countOfColumnsInGroup {\n\t\treturn nil, errors.New(\"Wrong format of /etc/group\")\n\t}\n\n\tgroup := user.Group{\n\t\tGid: groupInfo[gidColumnNumberInGroup],\n\t\tName: groupInfo[nameColumnNumberInGroup],\n\t}\n\n\treturn &group, err\n}\n\n\nfunc (linux *Linux) GroupExists(groupName string) bool {\n\tgroup, _ := linux.groupLookup(groupName)\n\treturn group != nil\n}\n\n\n\nfunc (linux *Linux) groupExistsByID(groupID string) bool ", "output": "{\n\tgroup, _ := linux.groupLookupByID(groupID)\n\treturn group != nil\n}"} {"input": "package main\n\nvar x, y, i = 0, 0, 1\n\nvar a [10] int\n\nfunc f() int {\n\treturn 100\n}\n\nvar b, c = 3, 4\n\n\n\nfunc h() bool {\n\treturn false\n}\n\nfunc main() {\n\ta[i] = x\n\n\tx = +x\n\tx = 23 + 3 * a[i]\n\tx = x <= f()\n\tx = ^b >> c\n\tx = g() || h()\n\tx = x == y+1 && c > 0\n}\n\nfunc g() bool ", "output": "{\n\treturn true\n}"} {"input": "package dilma\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/go-chat-bot/bot\"\n)\n\n\n\nfunc TestDilmaWhenTtheTextMatchDilma(t *testing.T) {\n\tcmd := &bot.PassiveCmd{}\n\tcmd.Raw = \"eu não votei na dilma!\"\n\tgot, err := dilma(cmd)\n\n\tif err != nil {\n\t\tt.Errorf(\"Error should be nil => %s\", err)\n\t}\n\tif !strings.HasPrefix(got, \":dilma: \") {\n\t\tt.Errorf(\"Test failed. Should return a clever Dilma quote\")\n\t}\n}\n\nfunc TestDilmaWhenTheTextDoesNotMatchDilma(t *testing.T) ", "output": "{\n\tcmd := &bot.PassiveCmd{}\n\tcmd.Raw = \"My name is go-bot, I am awesome.\"\n\tgot, err := dilma(cmd)\n\n\tif err != nil {\n\t\tt.Errorf(\"Error should be nil => %s\", err)\n\t}\n\tif got != \"\" {\n\t\tt.Errorf(\"Test failed. Expected a empty return, got: '%s'\", got)\n\t}\n}"} {"input": "package notifications\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n)\n\nvar url string\nvar serverKey string\nvar topic string\n\n\n\n\n\nfunc PushFirebase(title string, body string) {\n\tvar jsonStr = []byte(fmt.Sprintf(`{\"to\": \"/topics/%s\", \"priority\" : \"high\", \"notification\": {\"body\": \"%s\", \"icon\" : \"ic_notify\", \"tag\":\"JIMMY\", \"title\": \"%s\"}}`, topic, body, title))\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonStr))\n\treq.Header.Set(\"Authorization\", \"key=\"+serverKey)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tclient := &http.Client{}\n\t_, err = client.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"Push failed\")\n\t}\n}\n\nfunc Init() ", "output": "{\n\turl = \"https://fcm.googleapis.com/fcm/send\"\n\tserverKey = os.Getenv(\"JFBKEY\")\n\tif serverKey == \"\" {\n\t\tlog.Fatal(\"Missing JFBKEY for Firebase Authentication\")\n\t}\n\ttopic = os.Getenv(\"JFBTOPIC\")\n\tif topic == \"\" {\n\t\tlog.Fatal(\"Missing JFBTOPIC for Firebase Topic\")\n\t}\n}"} {"input": "package geo\n\n\n\ntype Polygon [][]Point\n\n\n\n\n\n\n\nfunc (p *Polygon) Exclude(points ...Point) {\n\tif p == nil {\n\t\treturn\n\t}\n\tp1, p2 := points[0], points[len(points)-1]\n\tif p1.Longitude() != p2.Longitude() || p1.Latitude() != p2.Latitude() {\n\t\tpoints = append(points, p1)\n\t}\n\t*p = append(*p, points)\n}\n\n\nfunc (p Polygon) Geo() *GeoJSON {\n\tif len(p) == 0 {\n\t\treturn nil\n\t}\n\treturn &GeoJSON{\n\t\tType: \"Polygon\",\n\t\tCoordinates: p,\n\t}\n}\n\nfunc NewPolygon(points ...Point) Polygon ", "output": "{\n\tp1, p2 := points[0], points[len(points)-1]\n\tif p1.Longitude() != p2.Longitude() || p1.Latitude() != p2.Latitude() {\n\t\tpoints = append(points, p1)\n\t}\n\treturn Polygon{points}\n}"} {"input": "package iso20022\n\n\ntype SubAccountIdentification11 struct {\n\n\tAccountOwner *PartyIdentification13Choice `xml:\"AcctOwnr,omitempty\"`\n\n\tSafekeepingAccount *SecuritiesAccount14 `xml:\"SfkpgAcct\"`\n\n\tActivityIndicator *YesNoIndicator `xml:\"ActvtyInd\"`\n\n\tBalanceForSubAccount []*AggregateBalanceInformation9 `xml:\"BalForSubAcct,omitempty\"`\n}\n\nfunc (s *SubAccountIdentification11) AddAccountOwner() *PartyIdentification13Choice {\n\ts.AccountOwner = new(PartyIdentification13Choice)\n\treturn s.AccountOwner\n}\n\nfunc (s *SubAccountIdentification11) AddSafekeepingAccount() *SecuritiesAccount14 {\n\ts.SafekeepingAccount = new(SecuritiesAccount14)\n\treturn s.SafekeepingAccount\n}\n\nfunc (s *SubAccountIdentification11) SetActivityIndicator(value string) {\n\ts.ActivityIndicator = (*YesNoIndicator)(&value)\n}\n\n\n\nfunc (s *SubAccountIdentification11) AddBalanceForSubAccount() *AggregateBalanceInformation9 ", "output": "{\n\tnewValue := new(AggregateBalanceInformation9)\n\ts.BalanceForSubAccount = append(s.BalanceForSubAccount, newValue)\n\treturn newValue\n}"} {"input": "package uaa\n\nimport (\n\t\"sort\"\n\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n)\n\ntype Prompt struct {\n\tKey string \n\tType string \n\tLabel string \n}\n\ntype PromptAnswer struct {\n\tKey string \n\tValue string\n}\n\nfunc (p Prompt) IsPassword() bool { return p.Type == \"password\" }\n\ntype PromptsResp struct {\n\tPrompts map[string][]string \n}\n\n\n\nfunc (c Client) Prompts() (PromptsResp, error) {\n\tvar resp PromptsResp\n\n\terr := c.clientRequest.Get(\"/login\", &resp)\n\tif err != nil {\n\t\treturn resp, bosherr.WrapError(err, \"Requesting UAA prompts\")\n\t}\n\n\treturn resp, nil\n}\n\ntype PromptSorting []Prompt\n\nfunc (s PromptSorting) Len() int { return len(s) }\nfunc (s PromptSorting) Less(i, j int) bool { return s[i].Type > s[j].Type }\nfunc (s PromptSorting) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (u UAAImpl) Prompts() ([]Prompt, error) ", "output": "{\n\tresp, err := u.client.Prompts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar prompts []Prompt\n\n\tfor key, pair := range resp.Prompts {\n\t\tprompts = append(prompts, Prompt{\n\t\t\tKey: key,\n\t\t\tType: pair[0],\n\t\t\tLabel: pair[1],\n\t\t})\n\t}\n\n\tsort.Sort(PromptSorting(prompts))\n\n\treturn prompts, nil\n}"} {"input": "package libcontainer\n\nimport (\n \"fmt\"\n \"os\"\n \"strings\"\n\n \"github.com/syndtr/gocapability/capability\"\n)\n\nconst allCapabilityTypes = capability.CAPS | capability.BOUNDS\n\nvar capabilityMap map[string]capability.Cap\n\nfunc init() {\n capabilityMap = make(map[string]capability.Cap)\n last := capability.CAP_LAST_CAP\n \n if last == capability.Cap(63) {\n last = capability.CAP_BLOCK_SUSPEND\n }\n for _, cap := range capability.List() {\n if cap > last {\n continue\n }\n capKey := fmt.Sprintf(\"CAP_%s\", strings.ToUpper(cap.String()))\n capabilityMap[capKey] = cap\n }\n}\n\nfunc newCapWhitelist(caps []string) (*whitelist, error) {\n l := []capability.Cap{}\n for _, c := range caps {\n v, ok := capabilityMap[c]\n if !ok {\n return nil, fmt.Errorf(\"unknown capability %q\", c)\n }\n l = append(l, v)\n }\n pid, err := capability.NewPid(os.Getpid())\n if err != nil {\n return nil, err\n }\n return &whitelist{\n keep: l,\n pid: pid,\n }, nil\n}\n\ntype whitelist struct {\n pid capability.Capabilities\n keep []capability.Cap\n}\n\n\nfunc (w *whitelist) dropBoundingSet() error {\n w.pid.Clear(capability.BOUNDS)\n w.pid.Set(capability.BOUNDS, w.keep...)\n return w.pid.Apply(capability.BOUNDS)\n}\n\n\n\n\nfunc (w *whitelist) drop() error ", "output": "{\n w.pid.Clear(allCapabilityTypes)\n w.pid.Set(allCapabilityTypes, w.keep...)\n return w.pid.Apply(allCapabilityTypes)\n}"} {"input": "package bno055\n\ntype AxisConfig struct {\n\tX byte\n\tY byte\n\tZ byte\n\tSignX byte\n\tSignY byte\n\tSignZ byte\n}\n\n\n\nfunc (c *AxisConfig) Mappings() byte {\n\tvar mappings byte\n\n\tmappings |= (c.Z & 0x03) << 4\n\tmappings |= (c.Y & 0x03) << 2\n\tmappings |= c.X & 0x03\n\n\treturn mappings\n}\n\nfunc (c *AxisConfig) Signs() byte {\n\tvar signs byte\n\n\tsigns |= (c.SignX & 0x01) << 2\n\tsigns |= (c.SignY & 0x01) << 1\n\tsigns |= c.SignZ & 0x01\n\n\treturn signs\n}\n\nfunc newAxisConfig(mapConfig, signConfig byte) *AxisConfig ", "output": "{\n\taxisConfig := &AxisConfig{\n\t\tX: mapConfig & 0x03,\n\t\tY: (mapConfig >> 2) & 0x03,\n\t\tZ: (mapConfig >> 4) & 0x03,\n\t\tSignX: (signConfig >> 2) & 0x01,\n\t\tSignY: (signConfig >> 1) & 0x01,\n\t\tSignZ: signConfig & 0x01,\n\t}\n\n\treturn axisConfig\n}"} {"input": "package osv\n\nimport (\n\t\"time\"\n\n\t\"github.com/intelsdi-x/snap/control/plugin\"\n\t\"github.com/intelsdi-x/snap/core\"\n)\n\nfunc cpuStat(ns core.Namespace, swagURL string) (*plugin.MetricType, error) {\n\tmetric, err := getCPUTime(swagURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &plugin.MetricType{\n\t\tNamespace_: ns,\n\t\tData_: metric,\n\t\tTimestamp_: time.Now(),\n\t}, nil\n}\n\nfunc getCPUMetricTypes() ([]plugin.MetricType, error) {\n\tvar mts []plugin.MetricType\n\tfor _, metricType := range cpuMetrics {\n\t\tmts = append(mts, plugin.MetricType{Namespace_: core.NewNamespace(Vendor, Name, \"cpu\", metricType)})\n\t}\n\treturn mts, nil\n}\n\n\n\nfunc getCPUTime(swagURL string) (uint64, error) ", "output": "{\n\tpath := \"trace/count\"\n\tresponse, err := osvRestGet(swagURL, path)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tcounters, err := osvRestUnmarshall(response)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn counters.TimeMs, nil\n}"} {"input": "package license\n\nimport (\n\t\"github.com/sacloud/libsacloud/v2/helper/validate\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\ntype DeleteRequest struct {\n\tID types.ID `request:\"-\" validate:\"required\"`\n\n\tFailIfNotFound bool `request:\"-\"`\n}\n\n\n\nfunc (req *DeleteRequest) Validate() error ", "output": "{\n\treturn validate.Struct(req)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"github.com/nuclio/nuclio/cmd/autoscaler/app\"\n\n\t\"github.com/nuclio/errors\"\n)\n\nfunc main() {\n\tkubeconfigPath := flag.String(\"kubeconfig-path\", os.Getenv(\"KUBECONFIG\"), \"Path of kubeconfig file\")\n\tnamespace := flag.String(\"namespace\", \"\", \"Namespace to listen on, or * for all\")\n\tplatformConfigurationPath := flag.String(\"platform-config\", \"/etc/nuclio/config/platform/platform.yaml\", \"Path of platform configuration file\")\n\tflag.Parse()\n\n\t*namespace = getNamespace(*namespace)\n\n\tif err := app.Run(*platformConfigurationPath, *namespace, *kubeconfigPath); err != nil {\n\t\terrors.PrintErrorStack(os.Stderr, err, 5)\n\t\tos.Exit(1)\n\t}\n}\n\n\n\nfunc getNamespace(namespaceArgument string) string ", "output": "{\n\n\tif namespaceArgument != \"\" {\n\t\treturn namespaceArgument\n\t}\n\n\tif namespaceEnv := os.Getenv(\"NUCLIO_SCALER_NAMESPACE\"); namespaceEnv != \"\" {\n\t\treturn namespaceEnv\n\t}\n\n\tif namespacePod, err := ioutil.ReadFile(\"/var/run/secrets/kubernetes.io/serviceaccount/namespace\"); err == nil {\n\t\treturn string(namespacePod)\n\t}\n\n\treturn \"default\"\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\ntype Response struct {\n\tStatus string `json:\"status\"`\n\tErrorText string `json:\"errorText,omitempty\"`\n\tAddress string `json:\"address,omitempty\"`\n\tStatusCode int `json:\"statusCode,omitempty\"`\n\tVersion string `json:\"version,omitempty\"`\n}\n\ntype Responses struct {\n\tResponses []Response `json:\"responses\"`\n}\n\nfunc (r *Response) Fill(outStr string, err error) {\n\tif err != nil {\n\t\tr.Status = \"ERR\"\n\t\tr.ErrorText = strings.TrimSpace(outStr + \" \" + err.Error())\n\t} else {\n\t\tr.Status = \"OK\"\n\t}\n}\n\nfunc (r Responses) String() string {\n\tj, _ := json.Marshal(r)\n\treturn fmt.Sprintf(\"Responses: %s\", string(j))\n}\n\nfunc (r Response) String() string {\n\tj, _ := json.Marshal(r)\n\treturn fmt.Sprintf(\"Response: %s\", string(j))\n}\n\nfunc (r Response) WriteHttp(w http.ResponseWriter) (resp Response) {\n\tif r.StatusCode == 0 {\n\t\tr.StatusCode = 200\n\t}\n\tw.WriteHeader(r.StatusCode)\n\treturn EncodeJson(r, w)\n}\n\n\n\nfunc (r Response) WriteInternalServerErrorHttp(w http.ResponseWriter) (resp Response) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tr.StatusCode = http.StatusInternalServerError\n\treturn EncodeJson(r, w)\n}\n\nfunc EncodeJson(r Response, w http.ResponseWriter) (resp Response) {\n\terr := json.NewEncoder(w).Encode(r)\n\tif err != nil {\n\t\tlog.Printf(\"[writehttp] failed to create json from model: %s\", err.Error())\n\t}\n\treturn r\n}\n\nfunc (r Response) WriteBadRequestHttp(w http.ResponseWriter) (resp Response) ", "output": "{\n\tw.WriteHeader(http.StatusBadRequest)\n\tr.StatusCode = http.StatusBadRequest\n\treturn EncodeJson(r, w)\n}"} {"input": "package perfcounters\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\ntype CountPerTimeInterval32 struct {\n\tlastCount int32\n\tlastTime *time.Time\n\tcurrentCount int32\n\tmu sync.Mutex\n}\n\n\n\nfunc (self *CountPerTimeInterval32) Increment() {\n\tself.Add(1)\n}\n\nfunc (self *CountPerTimeInterval32) Add(value int32) {\n\tself.mu.Lock()\n\tdefer self.mu.Unlock()\n\n\tself.currentCount += value\n\n\tif self.lastTime == nil {\n\t\tnow := time.Now()\n\t\tself.lastTime = &now\n\t}\n}\n\nfunc (self *CountPerTimeInterval32) CalculatedValue() float64 {\n\tself.mu.Lock()\n\tdefer self.mu.Unlock()\n\n\tcurrentTime := time.Now()\n\n\tif self.lastTime == nil {\n\t\tself.lastTime = ¤tTime\n\t\treturn 0\n\t}\n\n\tlastTime := *self.lastTime\n\tlastCount := self.lastCount\n\tcurrentCount := self.currentCount\n\n\tcalculatedValue := float64(int64(currentCount-lastCount) / (currentTime.Sub(lastTime).Nanoseconds() / 1e6))\n\n\tself.lastTime = ¤tTime\n\tself.lastCount = currentCount\n\n\treturn calculatedValue\n}\n\nfunc (self *CountPerTimeInterval32) String() string {\n\treturn fmt.Sprintf(\"%.3f\", self.CalculatedValue())\n}\n\nfunc NewCountPerTimeInterval32() *CountPerTimeInterval32 ", "output": "{\n\n\treturn &CountPerTimeInterval32{\n\t\tlastTime: nil,\n\t\tlastCount: 0,\n\t\tcurrentCount: 0,\n\t}\n}"} {"input": "package htpasswd\n\nimport (\n\t\"crypto/sha1\"\n\t\"crypto/subtle\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype sshaPassword struct {\n\thashed []byte\n\tsalt []byte\n}\n\n\nfunc AcceptSsha(src string) (EncodedPasswd, error) {\n\tif !strings.HasPrefix(src, \"{SSHA}\") {\n\t\treturn nil, nil\n\t}\n\n\tb64 := strings.TrimPrefix(src, \"{SSHA}\")\n\thashed, err := base64.StdEncoding.DecodeString(b64)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Malformed ssha(%s): %s\", src, err.Error())\n\t}\n\n\tif len(hashed) < sha1.Size {\n\t\treturn nil, fmt.Errorf(\"Malformed ssha(%s): wrong length\", src)\n\t}\n\n\thash := hashed[:sha1.Size]\n\tsalt := hashed[sha1.Size:]\n\treturn &sshaPassword{hash, salt}, nil\n}\n\n\n\n\nfunc (s *sshaPassword) MatchesPassword(password string) bool {\n\tsha := append([]byte(password), s.salt[:]...)\n\thash := sha1.Sum(sha)\n\treturn subtle.ConstantTimeCompare(hash[:], s.hashed) == 1\n}\n\nfunc RejectSsha(src string) (EncodedPasswd, error) ", "output": "{\n\tif !strings.HasPrefix(src, \"{SSHA}\") {\n\t\treturn nil, nil\n\t}\n\treturn nil, fmt.Errorf(\"ssha passwords are not accepted: %s\", src)\n}"} {"input": "package systray\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\nfunc nativeLoop() {\n\tC.nativeLoop()\n}\n\nfunc quit() {\n\tC.quit()\n}\n\n\n\n\nfunc SetIcon(iconBytes []byte) {\n\tcstr := (*C.char)(unsafe.Pointer(&iconBytes[0]))\n\tC.setIcon(cstr, (C.int)(len(iconBytes)))\n}\n\n\nfunc SetTitle(title string) {\n\tC.setTitle(C.CString(title))\n}\n\n\n\nfunc SetTooltip(tooltip string) {\n\tC.setTooltip(C.CString(tooltip))\n}\n\nfunc addOrUpdateMenuItem(item *MenuItem) {\n\tvar disabled C.short = 0\n\tif item.disabled {\n\t\tdisabled = 1\n\t}\n\tvar checked C.short = 0\n\tif item.checked {\n\t\tchecked = 1\n\t}\n\tC.add_or_update_menu_item(\n\n\t\tC.int(item.id),\n\t\tC.CString(item.title),\n\t\tC.CString(item.tooltip),\n\t\tdisabled,\n\t\tchecked,\n\t)\n}\n\n\nfunc systray_ready() {\n\tsystrayReady()\n}\n\n\n\n\nfunc systray_menu_item_selected(cId C.int) ", "output": "{\n\tsystrayMenuItemSelected(int32(cId))\n}"} {"input": "package apimgr\n\nimport \"reflect\"\n\nfunc newSorter(manager *Manager) *sorter {\n\tapis := []Definition{}\n\tfor _, api := range manager.apiMethodPatternMap {\n\t\tapis = append(apis, api)\n\t}\n\treturn &sorter{\n\t\tManager: manager,\n\t\tapis: apis,\n\t}\n}\n\ntype sorter struct {\n\t*Manager\n\n\tapis []Definition\n}\n\nfunc (t sorter) Len() int {\n\treturn len(t.apis)\n}\n\n\n\nfunc (t sorter) Less(i int, j int) bool {\n\tki := t.getSortKey(t.apis[i])\n\tkj := t.getSortKey(t.apis[j])\n\treturn ki < kj\n}\n\nfunc (t sorter) getSortKey(api Definition) string {\n\tpkgpath := getPackagePath(reflect.ValueOf(api.Request))\n\tkey := pkgpath + \" \" + t.GetMethodPatternKey(t.Manager, api)\n\treturn key\n}\n\nfunc (t sorter) Swap(i int, j int) ", "output": "{\n\tt.apis[i], t.apis[j] = t.apis[j], t.apis[i]\n}"} {"input": "package beintoo\n\nimport (\n\t\"testing\"\n\n\t\"github.com/prebid/prebid-server/adapters/adapterstest\"\n\t\"github.com/prebid/prebid-server/config\"\n\t\"github.com/prebid/prebid-server/openrtb_ext\"\n)\n\n\n\nfunc TestJsonSamples(t *testing.T) ", "output": "{\n\tbidder, buildErr := Builder(openrtb_ext.BidderBeintoo, config.Adapter{\n\t\tEndpoint: \"https://ib.beintoo.com\"})\n\n\tif buildErr != nil {\n\t\tt.Fatalf(\"Builder returned unexpected error %v\", buildErr)\n\t}\n\n\tadapterstest.RunJSONBidderTest(t, \"beintootest\", bidder)\n}"} {"input": "package sqltrace\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\nfunc boolToInt64(f bool) int64 {\n\tif f {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\ntype sqlTrace struct {\n\ton int64 \n\n\t*log.Logger\n}\n\nfunc newSQLTrace() *sqlTrace {\n\treturn &sqlTrace{\n\t\tLogger: log.New(os.Stdout, \"hdb \", log.Ldate|log.Ltime|log.Lshortfile),\n\t}\n}\nfunc (t *sqlTrace) On() bool { return atomic.LoadInt64(&t.on) != 0 }\nfunc (t *sqlTrace) SetOn(on bool) { atomic.StoreInt64(&t.on, boolToInt64(on)) }\n\ntype flagValue struct {\n\tt *sqlTrace\n}\n\nfunc (v flagValue) IsBoolFlag() bool { return true }\n\nfunc (v flagValue) String() string {\n\tif v.t == nil {\n\t\treturn \"\"\n\t}\n\treturn strconv.FormatBool(v.t.On())\n}\n\nfunc (v flagValue) Set(s string) error {\n\tf, err := strconv.ParseBool(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.t.SetOn(f)\n\treturn nil\n}\n\nvar tracer = newSQLTrace()\n\nfunc init() {\n\tflag.Var(&flagValue{t: tracer}, \"hdb.sqlTrace\", \"enabling hdb sql trace\")\n}\n\n\n\n\n\nfunc SetOn(on bool) { tracer.SetOn(on) }\n\n\nfunc Trace(v ...interface{}) { tracer.Print(v...) }\n\n\nfunc Tracef(format string, v ...interface{}) { tracer.Printf(format, v...) }\n\n\nfunc Traceln(v ...interface{}) { tracer.Println(v...) }\n\nfunc On() bool ", "output": "{ return tracer.On() }"} {"input": "package service\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/mysteriumnetwork/node/identity\"\n\t\"github.com/mysteriumnetwork/node/market\"\n)\n\nvar (\n\tserviceType = \"the-very-awesome-test-service-type\"\n)\n\n\n\nfunc TestManager_StartDoesNotCrashIfStoppedByUser(t *testing.T) {\n\tregistry := NewRegistry()\n\tmockCopy := *serviceMock\n\tmockCopy.mockProcess = make(chan struct{})\n\tregistry.Register(serviceType, func(options Options) (Service, market.ServiceProposal, error) {\n\t\treturn &mockCopy, proposalMock, nil\n\t})\n\n\tdiscovery := mockDiscovery{}\n\tdiscoveryFactory := MockDiscoveryFactoryFunc(&discovery)\n\tmanager := NewManager(\n\t\tregistry,\n\t\tMockDialogWaiterFactory,\n\t\tMockDialogHandlerFactory,\n\t\tdiscoveryFactory,\n\t)\n\tid, err := manager.Start(identity.FromAddress(proposalMock.ProviderID), serviceType, struct{}{})\n\tassert.Nil(t, err)\n\terr = manager.Stop(id)\n\tassert.Nil(t, err)\n\tdiscovery.Wait()\n\tassert.Len(t, manager.servicePool.List(), 0)\n}\n\nfunc TestManager_StartRemovesServiceFromPoolIfServiceCrashes(t *testing.T) ", "output": "{\n\tregistry := NewRegistry()\n\tmockCopy := *serviceMock\n\tmockCopy.onStartReturnError = errors.New(\"some error\")\n\tregistry.Register(serviceType, func(options Options) (Service, market.ServiceProposal, error) {\n\t\treturn &mockCopy, proposalMock, nil\n\t})\n\n\tdiscovery := mockDiscovery{}\n\tdiscoveryFactory := MockDiscoveryFactoryFunc(&discovery)\n\tmanager := NewManager(\n\t\tregistry,\n\t\tMockDialogWaiterFactory,\n\t\tMockDialogHandlerFactory,\n\t\tdiscoveryFactory,\n\t)\n\t_, err := manager.Start(identity.FromAddress(proposalMock.ProviderID), serviceType, struct{}{})\n\tassert.Nil(t, err)\n\n\tdiscovery.Wait()\n\tassert.Len(t, manager.servicePool.List(), 0)\n}"} {"input": "package popcount\n\n\nvar pc [256]byte\n\n\n\n\nfunc PopCount(x uint64) int {\n\treturn int(pc[byte(x>>(0*8))] +\n\t\tpc[byte(x>>(1*8))] +\n\t\tpc[byte(x>>(2*8))] +\n\t\tpc[byte(x>>(3*8))] +\n\t\tpc[byte(x>>(4*8))] +\n\t\tpc[byte(x>>(5*8))] +\n\t\tpc[byte(x>>(6*8))] +\n\t\tpc[byte(x>>(7*8))])\n}\n\nfunc init() ", "output": "{\n\tfor i := range pc {\n\t\tpc[i] = pc[i/2] + byte(i&1)\n\t}\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSIoTAnalyticsPipeline_Channel struct {\n\n\tChannelName string `json:\"ChannelName,omitempty\"`\n\n\tName string `json:\"Name,omitempty\"`\n\n\tNext string `json:\"Next,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) AWSCloudFormationType() string {\n\treturn \"AWS::IoTAnalytics::Pipeline.Channel\"\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) SetDeletionPolicy(policy policies.DeletionPolicy) ", "output": "{\n\tr._deletionPolicy = policy\n}"} {"input": "package response\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\nvar realm = \"example_api\"\n\n\n\n\n\nfunc NoContent(w http.ResponseWriter) {\n\tw.WriteHeader(http.StatusNoContent)\n}\n\n\n\nfunc Error(w http.ResponseWriter, err string, code int) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(code)\n\tjson.NewEncoder(w).Encode(map[string]string{\"error\": err})\n}\n\n\n\nfunc UnauthorizedError(w http.ResponseWriter, err string) {\n\tw.Header().Set(\"WWW-Authenticate\", fmt.Sprintf(\"Bearer realm=%s\", realm))\n\tError(w, err, http.StatusUnauthorized)\n}\n\nfunc WriteJSON(w http.ResponseWriter, v interface{}, code int) ", "output": "{\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(code)\n\tjson.NewEncoder(w).Encode(v)\n}"} {"input": "package api_xhr\n\nimport (\n\t\"compress/gzip\"\n\t\"encoding/json\"\n\t\"io\"\n\t\"net/http\"\n\n\t\"github.com/deze333/vroom/reqres\"\n)\n\n\n\n\n\n\nfunc ParseReq(w http.ResponseWriter, r *http.Request) (req *reqres.Req, err error) {\n\n\tparams := map[string]interface{}{}\n\n\tswitch r.Header.Get(\"Content-Encoding\") {\n\tcase \"gzip\":\n\t\tparams, err = decodeAsGzipReq(r)\n\n\tdefault:\n\t\tparams, err = decodeAsUnencodedReq(r)\n\t}\n\n\treq = &reqres.Req{\n\t\tParams: params,\n\t\tHttpReq: r,\n\t\tHttpResWriter: w,\n\t}\n\treturn\n}\n\nfunc decodeAsUnencodedReq(r *http.Request) (params map[string]interface{}, err error) {\n\n\tdecoder := json.NewDecoder(r.Body)\n\terr = decoder.Decode(¶ms)\n\n\tif err == io.EOF {\n\t\terr = nil\n\t}\n\n\treturn\n}\n\n\n\n\nfunc decodeAsGzipReq(r *http.Request) (params map[string]interface{}, err error) ", "output": "{\n\n\tvar reader *gzip.Reader\n\treader, err = gzip.NewReader(r.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdecoder := json.NewDecoder(reader)\n\terr = decoder.Decode(¶ms)\n\n\tif err == io.EOF {\n\t\terr = nil\n\t}\n\n\treturn\n}"} {"input": "package jobs\n\nimport (\n\t\"sync\"\n\n\tl4g \"github.com/alecthomas/log4go\"\n\tejobs \"github.com/mattermost/platform/einterfaces/jobs\"\n\t\"github.com/mattermost/platform/model\"\n\t\"github.com/mattermost/platform/store\"\n\t\"github.com/mattermost/platform/utils\"\n)\n\ntype Jobs struct {\n\tstartOnce sync.Once\n\n\tDataRetention model.Job\n\n\tlistenerId string\n}\n\nfunc InitJobs(s store.Store) *Jobs {\n\tjobs := &Jobs{\n\t}\n\n\tif dataRetentionInterface := ejobs.GetDataRetentionInterface(); dataRetentionInterface != nil {\n\t\tjobs.DataRetention = dataRetentionInterface.MakeJob(s)\n\t}\n\n\treturn jobs\n}\n\nfunc (jobs *Jobs) Start() *Jobs {\n\tl4g.Info(\"Starting jobs\")\n\n\tjobs.startOnce.Do(func() {\n\t\tif jobs.DataRetention != nil && *utils.Cfg.DataRetentionSettings.Enable {\n\t\t\tgo jobs.DataRetention.Run()\n\t\t}\n\n\t})\n\n\tjobs.listenerId = utils.AddConfigListener(jobs.handleConfigChange)\n\n\treturn jobs\n}\n\nfunc (jobs *Jobs) handleConfigChange(oldConfig *model.Config, newConfig *model.Config) {\n\tif jobs.DataRetention != nil {\n\t\tif !*oldConfig.DataRetentionSettings.Enable && *newConfig.DataRetentionSettings.Enable {\n\t\t\tgo jobs.DataRetention.Run()\n\t\t} else if *oldConfig.DataRetentionSettings.Enable && !*newConfig.DataRetentionSettings.Enable {\n\t\t\tjobs.DataRetention.Stop()\n\t\t}\n\t}\n}\n\n\n\nfunc (jobs *Jobs) Stop() *Jobs ", "output": "{\n\tutils.RemoveConfigListener(jobs.listenerId)\n\n\tif jobs.DataRetention != nil && *utils.Cfg.DataRetentionSettings.Enable {\n\t\tjobs.DataRetention.Stop()\n\t}\n\n\tl4g.Info(\"Stopped jobs\")\n\n\treturn jobs\n}"} {"input": "package runewidth\n\nimport (\n\t\"testing\"\n\t\"unicode/utf8\"\n)\n\nvar benchSink int\n\nfunc benchTable(b *testing.B, tbl table) int {\n\tn := 0\n\tfor i := 0; i < b.N; i++ {\n\t\tfor r := rune(0); r <= utf8.MaxRune; r++ {\n\t\t\tif inTable(r, tbl) {\n\t\t\t\tn++\n\t\t\t}\n\t\t}\n\t}\n\treturn n\n}\n\nfunc BenchmarkTablePrivate(b *testing.B) {\n\tbenchSink = benchTable(b, private)\n}\nfunc BenchmarkTableNonprint(b *testing.B) {\n\tbenchSink = benchTable(b, nonprint)\n}\n\nfunc BenchmarkTableDoublewidth(b *testing.B) {\n\tbenchSink = benchTable(b, doublewidth)\n}\nfunc BenchmarkTableAmbiguous(b *testing.B) {\n\tbenchSink = benchTable(b, ambiguous)\n}\nfunc BenchmarkTableEmoji(b *testing.B) {\n\tbenchSink = benchTable(b, emoji)\n}\nfunc BenchmarkTableNotassigned(b *testing.B) {\n\tbenchSink = benchTable(b, notassigned)\n}\nfunc BenchmarkTableNeutral(b *testing.B) {\n\tbenchSink = benchTable(b, neutral)\n}\n\nfunc BenchmarkTableCombining(b *testing.B) ", "output": "{\n\tbenchSink = benchTable(b, combining)\n}"} {"input": "package echo\n\ntype (\n\tGroup struct {\n\t\techo Echo\n\t}\n)\n\nfunc (g *Group) Use(m ...Middleware) {\n\tfor _, h := range m {\n\t\tg.echo.middleware = append(g.echo.middleware, wrapMiddleware(h))\n\t}\n}\n\nfunc (g *Group) Connect(path string, h Handler) {\n\tg.echo.Connect(path, h)\n}\n\nfunc (g *Group) Delete(path string, h Handler) {\n\tg.echo.Delete(path, h)\n}\n\nfunc (g *Group) Get(path string, h Handler) {\n\tg.echo.Get(path, h)\n}\n\nfunc (g *Group) Head(path string, h Handler) {\n\tg.echo.Head(path, h)\n}\n\nfunc (g *Group) Options(path string, h Handler) {\n\tg.echo.Options(path, h)\n}\n\nfunc (g *Group) Patch(path string, h Handler) {\n\tg.echo.Patch(path, h)\n}\n\nfunc (g *Group) Post(path string, h Handler) {\n\tg.echo.Post(path, h)\n}\n\nfunc (g *Group) Put(path string, h Handler) {\n\tg.echo.Put(path, h)\n}\n\n\n\nfunc (g *Group) WebSocket(path string, h HandlerFunc) {\n\tg.echo.WebSocket(path, h)\n}\n\nfunc (g *Group) Static(path, root string) {\n\tg.echo.Static(path, root)\n}\n\nfunc (g *Group) ServeDir(path, root string) {\n\tg.echo.ServeDir(path, root)\n}\n\nfunc (g *Group) ServeFile(path, file string) {\n\tg.echo.ServeFile(path, file)\n}\n\nfunc (g *Group) Group(prefix string, m ...Middleware) *Group {\n\treturn g.echo.Group(prefix, m...)\n}\n\nfunc (g *Group) Trace(path string, h Handler) ", "output": "{\n\tg.echo.Trace(path, h)\n}"} {"input": "package test\n\nimport (\n\t\"github.com/nbio/st\"\n\t\"gopkg.in/h2non/gock.v1\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"testing\"\n)\n\n\n\nfunc TestMatchHeaders(t *testing.T) ", "output": "{\n\tdefer gock.Disable()\n\n\tgock.New(\"http://foo.com\").\n\t\tMatchHeader(\"Authorization\", \"^foo bar$\").\n\t\tMatchHeader(\"API\", \"1.[0-9]+\").\n\t\tHeaderPresent(\"Accept\").\n\t\tReply(200).\n\t\tBodyString(\"foo foo\")\n\n\treq, err := http.NewRequest(\"GET\", \"http://foo.com\", nil)\n\treq.Header.Set(\"Authorization\", \"foo bar\")\n\treq.Header.Set(\"API\", \"1.0\")\n\treq.Header.Set(\"Accept\", \"text/plain\")\n\n\tres, err := (&http.Client{}).Do(req)\n\tst.Expect(t, err, nil)\n\tst.Expect(t, res.StatusCode, 200)\n\tbody, _ := ioutil.ReadAll(res.Body)\n\tst.Expect(t, string(body), \"foo foo\")\n}"} {"input": "package core\n\nimport (\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/trivago/tgo/thealthcheck\"\n\t\"strings\"\n\t\"time\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype SimpleRouter struct {\n\tid string\n\tProducers []Producer\n\tfilters FilterArray `config:\"Filters\"`\n\ttimeout time.Duration `config:\"TimeoutMs\" default:\"0\" metric:\"ms\"`\n\tstreamID MessageStreamID `config:\"Stream\"`\n\tLogger logrus.FieldLogger\n}\n\n\n\n\n\nfunc (router *SimpleRouter) GetLogger() logrus.FieldLogger {\n\treturn router.Logger\n}\n\n\nfunc (router *SimpleRouter) AddHealthCheck(callback thealthcheck.CallbackFunc) {\n\trouter.AddHealthCheckAt(\"\", callback)\n}\n\n\nfunc (router *SimpleRouter) AddHealthCheckAt(path string, callback thealthcheck.CallbackFunc) {\n\tthealthcheck.AddEndpoint(\"/\"+router.GetID()+path, callback)\n}\n\n\nfunc (router *SimpleRouter) GetID() string {\n\treturn router.id\n}\n\n\nfunc (router *SimpleRouter) GetStreamID() MessageStreamID {\n\treturn router.streamID\n}\n\n\nfunc (router *SimpleRouter) GetTimeout() time.Duration {\n\treturn router.timeout\n}\n\n\n\nfunc (router *SimpleRouter) AddProducer(producers ...Producer) {\n\tfor _, prod := range producers {\n\t\tfor _, inListProd := range router.Producers {\n\t\t\tif inListProd == prod {\n\t\t\t\treturn \n\t\t\t}\n\t\t}\n\t\trouter.Producers = append(router.Producers, prod)\n\t}\n}\n\n\nfunc (router *SimpleRouter) GetProducers() []Producer {\n\treturn router.Producers\n}\n\n\nfunc (router *SimpleRouter) Modulate(msg *Message) ModulateResult {\n\tmod := NewFilterModulator(router.filters)\n\treturn mod.Modulate(msg)\n}\n\nfunc (router *SimpleRouter) Configure(conf PluginConfigReader) ", "output": "{\n\trouter.id = conf.GetID()\n\trouter.Logger = conf.GetLogger()\n\n\tif router.streamID == WildcardStreamID && strings.Index(router.id, GeneratedRouterPrefix) != 0 {\n\t\trouter.Logger.Info(\"A wildcard stream configuration only affects the wildcard stream, not all routers\")\n\t}\n}"} {"input": "package example\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/RangelReale/osin\"\n)\n\n\n\nfunc DownloadAccessToken(url string, auth *osin.BasicAuth, output map[string]interface{}) error {\n\tpreq, err := http.NewRequest(\"POST\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif auth != nil {\n\t\tpreq.SetBasicAuth(auth.Username, auth.Password)\n\t}\n\n\tpclient := &http.Client{}\n\tpresp, err := pclient.Do(preq)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif presp.StatusCode != 200 {\n\t\treturn errors.New(\"Invalid status code\")\n\t}\n\n\tjdec := json.NewDecoder(presp.Body)\n\terr = jdec.Decode(&output)\n\treturn err\n}\n\nfunc HandleLoginPage(ar *osin.AuthorizeRequest, w http.ResponseWriter, r *http.Request) bool ", "output": "{\n\tr.ParseForm()\n\tif r.Method == \"POST\" && r.Form.Get(\"login\") == \"test\" && r.Form.Get(\"password\") == \"test\" {\n\t\treturn true\n\t}\n\n\tw.Write([]byte(\"\"))\n\n\tw.Write([]byte(fmt.Sprintf(\"LOGIN %s (use test/test)
\", ar.Client.GetId())))\n\tw.Write([]byte(fmt.Sprintf(\"
\", r.URL.RawQuery)))\n\n\tw.Write([]byte(\"Login:
\"))\n\tw.Write([]byte(\"Password:
\"))\n\tw.Write([]byte(\"\"))\n\n\tw.Write([]byte(\"
\"))\n\n\tw.Write([]byte(\"\"))\n\n\treturn false\n}"} {"input": "package horizon\n\nimport (\n\t\"github.com/stellar/go-horizon/db\"\n)\n\n\n\nfunc initCoreDb(app *App) {\n\tcoreDb, err := db.Open(app.config.StellarCoreDatabaseUrl)\n\n\tif err != nil {\n\t\tapp.log.Panic(app.ctx, err)\n\t}\n\tapp.coreDb = coreDb\n}\n\nfunc init() {\n\tappInit.Add(\"history-db\", initHistoryDb, \"app-context\", \"log\")\n\tappInit.Add(\"core-db\", initCoreDb, \"app-context\", \"log\")\n}\n\nfunc initHistoryDb(app *App) ", "output": "{\n\thistoryDb, err := db.Open(app.config.DatabaseUrl)\n\n\tif err != nil {\n\t\tapp.log.Panic(app.ctx, err)\n\t}\n\tapp.historyDb = historyDb\n}"} {"input": "package main\n\ntype Element interface {\n}\n\ntype Vector struct {\n\tnelem int;\n\telem []Element;\n}\n\nfunc New() *Vector {\n\tv := new(Vector);\n\tv.nelem = 0;\n\tv.elem = make([]Element, 10);\n\treturn v;\n}\n\n\n\nfunc (v *Vector) Insert(e Element) {\n\tv.elem[v.nelem] = e;\n\tv.nelem++;\n}\n\nfunc main() {\n\ttype I struct { val int; };\n\ti0 := new(I); i0.val = 0;\n\ti1 := new(I); i1.val = 11;\n\ti2 := new(I); i2.val = 222;\n\ti3 := new(I); i3.val = 3333;\n\ti4 := new(I); i4.val = 44444;\n\tv := New();\n\tprint(\"hi\\n\");\n\tv.Insert(i4);\n\tv.Insert(i3);\n\tv.Insert(i2);\n\tv.Insert(i1);\n\tv.Insert(i0);\n\tfor i := 0; i < v.nelem; i++ {\n\t\tvar x *I;\n\t\tx = v.At(i).(*I);\n\t\tprint(i, \" \", x.val, \"\\n\"); \n\t}\n\tfor i := 0; i < v.nelem; i++ {\n\t\tprint(i, \" \", v.At(i).(*I).val, \"\\n\");\n\t}\n}\n\nfunc (v *Vector) At(i int) Element ", "output": "{\n\treturn v.elem[i];\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc main() {\n\tfmt.Print(\"First example with -1: \")\n\tret1, err1 := MySqrt(-1)\n\tif err1 != nil {\n\t\tfmt.Println(\"Error! Return values are: \", ret1, err1)\n\t} else {\n\t\tfmt.Println(\"It's ok! Return values are: \", ret1, err1)\n\t}\n\n\tfmt.Print(\"Second example with 5: \")\n\tif ret2, err2 := MySqrt(5); err2 != nil {\n\t\tfmt.Println(\"Error! Return values are: \", ret2, err2)\n\t} else {\n\t\tfmt.Println(\"It's ok! Return values are: \", ret2, err2)\n\t}\n\tfmt.Println(MySqrt2(5))\n}\n\nfunc MySqrt(f float64) (float64, error) {\n\tif f < 0 {\n\t\treturn float64(math.NaN()), errors.New(\"I won't be able to do a sqrt of negative number!\")\n\t}\n\treturn math.Sqrt(f), nil\n}\n\n\n\n\nfunc MySqrt2(f float64) (ret float64, err error) ", "output": "{\n\tif f < 0 {\n\t\tret = float64(math.NaN())\n\t\terr = errors.New(\"I won't be able to do a sqrt of negative number!\")\n\t} else {\n\t\tret = math.Sqrt(f)\n\t}\n\treturn\n}"} {"input": "package ipv4\n\nimport \"net\"\n\nfunc (c *payloadHandler) readFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) {\n\tc.rawOpt.RLock()\n\toob := NewControlMessage(c.rawOpt.cflags)\n\tc.rawOpt.RUnlock()\n\tvar nn int\n\tswitch c := c.PacketConn.(type) {\n\tcase *net.UDPConn:\n\t\tif n, nn, _, src, err = c.ReadMsgUDP(b, oob); err != nil {\n\t\t\treturn 0, nil, nil, err\n\t\t}\n\tcase *net.IPConn:\n\t\tnb := make([]byte, maxHeaderLen+len(b))\n\t\tif n, nn, _, src, err = c.ReadMsgIP(nb, oob); err != nil {\n\t\t\treturn 0, nil, nil, err\n\t\t}\n\t\thdrlen := int(nb[0]&0x0f) << 2\n\t\tcopy(b, nb[hdrlen:])\n\t\tn -= hdrlen\n\tdefault:\n\t\treturn 0, nil, nil, &net.OpError{Op: \"read\", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Err: errInvalidConnType}\n\t}\n\tif nn > 0 {\n\t\tcm = new(ControlMessage)\n\t\tif err = cm.Parse(oob[:nn]); err != nil {\n\t\t\treturn 0, nil, nil, &net.OpError{Op: \"read\", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err}\n\t\t}\n\t}\n\tif cm != nil {\n\t\tcm.Src = netAddrToIP4(src)\n\t}\n\treturn\n}\n\n\n\nfunc (c *payloadHandler) writeTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) ", "output": "{\n\toob := cm.Marshal()\n\tif dst == nil {\n\t\treturn 0, &net.OpError{Op: \"write\", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: errMissingAddress}\n\t}\n\tswitch c := c.PacketConn.(type) {\n\tcase *net.UDPConn:\n\t\tn, _, err = c.WriteMsgUDP(b, oob, dst.(*net.UDPAddr))\n\tcase *net.IPConn:\n\t\tn, _, err = c.WriteMsgIP(b, oob, dst.(*net.IPAddr))\n\tdefault:\n\t\treturn 0, &net.OpError{Op: \"write\", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Addr: opAddr(dst), Err: errInvalidConnType}\n\t}\n\treturn\n}"} {"input": "package webclient\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\ntype httpClient interface {\n\tGet(path string) ([]byte, error)\n}\n\ntype JSONClient struct {\n\tHTTPClient httpClient\n}\n\n\n\nfunc (c *JSONClient) Get(route string, responseData interface{}) error ", "output": "{\n\tresponseBody, err := c.HTTPClient.Get(route)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(responseBody, &responseData)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"server returned malformed JSON: %s\", err)\n\t}\n\treturn nil\n}"} {"input": "package msd\n\nimport (\n\t\"encoding/base64\"\n\t\"github.com/bluefw/blued/discoverd/api\"\n\t\"github.com/gin-gonic/gin\"\n\t\"log\"\n\t\"net/http\"\n)\n\ntype ServiceResource struct {\n\trepo *DiscoverdRepo\n\tlogger *log.Logger\n}\n\nfunc NewServiceResource(dr *DiscoverdRepo, l *log.Logger) *ServiceResource {\n\treturn &ServiceResource{\n\t\trepo: dr,\n\t\tlogger: l,\n\t}\n}\n\nfunc (sr *ServiceResource) RegMicroApp(c *gin.Context) {\n\tvar as api.MicroApp\n\tif err := c.Bind(&as); err != nil {\n\t\tc.JSON(http.StatusBadRequest, api.NewError(\"problem decoding body\"))\n\t\treturn\n\t}\n\n\tsr.repo.Register(&as)\n\tc.JSON(http.StatusCreated, nil)\n}\n\nfunc (sr *ServiceResource) GetRouterTable(c *gin.Context) {\n\taddr, err := base64.StdEncoding.DecodeString(c.Params.ByName(\"addr\"))\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, api.NewError(\"error decoding addr\"))\n\t\treturn\n\t}\n\trt := sr.repo.GetRouterTable(string(addr))\n\tc.JSON(http.StatusOK, rt)\n}\n\n\n\nfunc (sr *ServiceResource) Refresh(c *gin.Context) ", "output": "{\n\taddr, err := base64.StdEncoding.DecodeString(c.Params.ByName(\"addr\"))\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, api.NewError(\"error decoding addr\"))\n\t\treturn\n\t}\n\tappStatus := sr.repo.Refresh(string(addr))\n\tc.JSON(http.StatusAccepted, appStatus)\n}"} {"input": "package linode\n\nimport \"errors\"\nimport \"fmt\"\n\n\n\nfunc (client *Client) ListImages(pendingOnly bool) ([]*Image, error) {\n\tparams := make(map[string]string)\n\tif pendingOnly {\n\t\tparams[\"pending\"] = \"1\"\n\t}\n\tvar images []*Image\n\terr := client.request(\"image.list\", params, &images)\n\treturn images, err\n}\n\n\n\nfunc (client *Client) DeleteImage(imageID int) error {\n\tparams := map[string]string{\n\t\t\"ImageID\": fmt.Sprintf(\"%d\", imageID),\n\t}\n\treturn client.request(\"image.delete\", params, nil)\n}\n\nfunc (client *Client) GetImage(imageID int) (*Image, error) ", "output": "{\n\tparams := map[string]string{\n\t\t\"ImageID\": fmt.Sprintf(\"%d\", imageID),\n\t}\n\tvar images []*Image\n\terr := client.request(\"image.list\", params, &images)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if len(images) != 1 {\n\t\treturn nil, errors.New(\"expected one image in response\")\n\t} else {\n\t\treturn images[0], nil\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"bufio\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\nfunc Atoi(s string) int {\n\ti, e := strconv.Atoi(s)\n\tif e != nil {\n\t\treturn 0\n\t}\n\treturn i\n}\n\n\nfunc Atoui(s string) uint32 {\n\ti, e := strconv.ParseUint(s, 10, 32)\n\tif e != nil {\n\t\treturn 0\n\t}\n\treturn uint32(i)\n}\n\n\n\n\n\nfunc GotError(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc ReadConfig(path string) map[string]string ", "output": "{\n\n\tconfigMap := make(map[string]string)\n\n\tf, err := os.Open(path)\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tscanner := bufio.NewScanner(f)\n\n\tfor scanner.Scan() {\n\n\t\tline := scanner.Text()\n\n\t\tif !strings.HasPrefix(line, \"//\") {\n\t\t\tfields := strings.SplitN(scanner.Text(), \"=\", 2)\n\n\t\t\tconfigMap[strings.TrimSpace(fields[0])] = strings.TrimSpace(fields[1])\n\t\t}\n\n\t}\n\n\treturn configMap\n}"} {"input": "package v1beta1\n\nimport (\n\tv1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\twatch \"k8s.io/apimachinery/pkg/watch\"\n\trest \"k8s.io/client-go/rest\"\n\tv1beta1 \"k8s.io/metrics/pkg/apis/metrics/v1beta1\"\n\tscheme \"k8s.io/metrics/pkg/client/clientset_generated/clientset/scheme\"\n)\n\n\n\ntype NodeMetricsesGetter interface {\n\tNodeMetricses() NodeMetricsInterface\n}\n\n\ntype NodeMetricsInterface interface {\n\tGet(name string, options v1.GetOptions) (*v1beta1.NodeMetrics, error)\n\tList(opts v1.ListOptions) (*v1beta1.NodeMetricsList, error)\n\tWatch(opts v1.ListOptions) (watch.Interface, error)\n\tNodeMetricsExpansion\n}\n\n\ntype nodeMetricses struct {\n\tclient rest.Interface\n}\n\n\nfunc newNodeMetricses(c *MetricsV1beta1Client) *nodeMetricses {\n\treturn &nodeMetricses{\n\t\tclient: c.RESTClient(),\n\t}\n}\n\n\nfunc (c *nodeMetricses) Get(name string, options v1.GetOptions) (result *v1beta1.NodeMetrics, err error) {\n\tresult = &v1beta1.NodeMetrics{}\n\terr = c.client.Get().\n\t\tResource(\"nodes\").\n\t\tName(name).\n\t\tVersionedParams(&options, scheme.ParameterCodec).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}\n\n\n\n\n\nfunc (c *nodeMetricses) Watch(opts v1.ListOptions) (watch.Interface, error) {\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"nodes\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tWatch()\n}\n\nfunc (c *nodeMetricses) List(opts v1.ListOptions) (result *v1beta1.NodeMetricsList, err error) ", "output": "{\n\tresult = &v1beta1.NodeMetricsList{}\n\terr = c.client.Get().\n\t\tResource(\"nodes\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}"} {"input": "package channelconfig\n\nimport (\n\t\"testing\"\n\n\tcb \"github.com/hyperledger/fabric/protos/common\"\n\tmspprotos \"github.com/hyperledger/fabric/protos/msp\"\n\tpb \"github.com/hyperledger/fabric/protos/peer\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\n\n\n\n\n\n\nfunc TestUtilsBasic(t *testing.T) {\n\tbasicTest(t, ConsortiumValue(\"foo\"))\n\tbasicTest(t, HashingAlgorithmValue())\n\tbasicTest(t, BlockDataHashingStructureValue())\n\tbasicTest(t, OrdererAddressesValue([]string{\"foo:1\", \"bar:2\"}))\n\tbasicTest(t, ConsensusTypeValue(\"foo\"))\n\tbasicTest(t, BatchSizeValue(1, 2, 3))\n\tbasicTest(t, BatchTimeoutValue(\"1s\"))\n\tbasicTest(t, ChannelRestrictionsValue(7))\n\tbasicTest(t, KafkaBrokersValue([]string{\"foo:1\", \"bar:2\"}))\n\tbasicTest(t, MSPValue(&mspprotos.MSPConfig{}))\n\tbasicTest(t, CapabilitiesValue(map[string]bool{\"foo\": true, \"bar\": false}))\n\tbasicTest(t, AnchorPeersValue([]*pb.AnchorPeer{&pb.AnchorPeer{}, &pb.AnchorPeer{}}))\n\tbasicTest(t, ChannelCreationPolicyValue(&cb.Policy{}))\n}\n\nfunc basicTest(t *testing.T, sv *StandardConfigValue) ", "output": "{\n\tassert.NotNil(t, sv)\n\tassert.NotEmpty(t, sv.Key())\n\tassert.NotNil(t, sv.Value())\n}"} {"input": "package plugin_server\n\nimport (\n\t\"github.com/pivotal-golang/lager\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/rpc\"\n)\n\ntype PluginServer interface {\n\tStart() error\n\tTest(string, *StringResponse) error\n}\n\ntype pluginServer struct {\n\tlogger lager.Logger\n}\n\ntype StringResponse struct {\n\tStringResponse string\n}\n\n\n\nfunc (p *pluginServer) Start() error {\n\tp.logger.Debug(\"Starting plugin server...\")\n\n\trpc.Register(p)\n\trpc.HandleHTTP()\n\tlistener, err := net.Listen(\"tcp\", \":4249\")\n\tif err != nil {\n\t\tp.logger.Error(\"Error starting RPC client\", err)\n\t\treturn err\n\t}\n\n\tgo http.Serve(listener, nil)\n\n\tp.logger.Debug(\"Plugin server started\")\n\treturn nil\n}\n\nfunc (p *pluginServer) Test(request string, response *StringResponse) error {\n\tp.logger.Debug(\"Plugin server received Test call: \" + request)\n\n\tresponse.StringResponse = \"Hello from GoHome!\"\n\treturn nil\n}\n\nfunc NewPluginServer(logger lager.Logger) PluginServer ", "output": "{\n\treturn &pluginServer{\n\t\tlogger: logger,\n\t}\n}"} {"input": "package history\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/avatar29A/microchat/history/model\"\n\t\"github.com/avatar29A/microchat/server/protocols\"\n\t\"github.com/avatar29A/microchat/utils\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n)\n\nimport \"github.com/satori/go.uuid\"\n\n\ntype MessagesContext struct {\n\tctx *DBContext\n}\n\n\nfunc NewMessagesContext(context *DBContext) *MessagesContext {\n\tc := &MessagesContext{context}\n\n\treturn c\n}\n\n\n\n\n\nfunc (c *MessagesContext) SaveMessage(message *protocols.UserSay) error {\n\tchannel := c.getDefaultChannel()\n\n\tentity := &model.Message{\n\t\tID: string(uuid.NewV4().Bytes()),\n\t\tUserName: message.Username,\n\t\tChannelID: channel.ID,\n\t\tMessage: message.Message,\n\t\tCreatedAt: utils.MakeTimeFromTimestamp(message.CreatedAt),\n\t}\n\n\treturn c.ctx.DB.Save(entity)\n}\n\nfunc (c *MessagesContext) getDefaultChannel() *model.Channel {\n\tentity, err := c.ctx.DB.FindOneFrom(model.ChannelTable, \"name\", \"default\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn entity.(*model.Channel)\n}\n\nfunc (c *MessagesContext) GetLastNMessages(n int) []*protocols.UserSay ", "output": "{\n\tquery := fmt.Sprintf(\"ORDER BY created_at DESC LIMIT %s\", c.ctx.DB.Placeholder(0))\n\n\trows, err := c.ctx.DB.SelectAllFrom(model.MessageTable, query, n)\n\tmessages := make([]*protocols.UserSay, 0, len(rows))\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn messages\n\t}\n\n\tfor _, row := range rows {\n\t\tmessage := row.(*model.Message)\n\t\tmessages = append(messages, &protocols.UserSay{\n\t\t\tUsername: message.UserName,\n\t\t\tMessage: message.Message,\n\t\t\tCreatedAt: utils.MakeTimeStampFromTime(message.CreatedAt),\n\t\t})\n\t}\n\n\treturn messages\n}"} {"input": "package core\n\nimport (\n\t\"github.com/MG-RAST/AWE/lib/core/cwl\"\n\t\"github.com/MG-RAST/AWE/lib/logger\"\n)\n\ntype SetCounter struct {\n\tCounter []int\n\tMax []int\n\tNumberOfSets int\n\tScatter_type string\n}\n\nfunc NewSetCounter(numberOfSets int, array []cwl.Array, scatter_type string) (sc *SetCounter) {\n\n\tlogger.Debug(3, \"(NewSetCounter) numberOfSets: %d\", numberOfSets)\n\tlogger.Debug(3, \"(NewSetCounter) array: %d\", len(array))\n\tlogger.Debug(3, \"(NewSetCounter) scatter_type: %s\", scatter_type)\n\n\tsc = &SetCounter{}\n\n\tsc.NumberOfSets = numberOfSets\n\n\n\tsc.Counter = make([]int, sc.NumberOfSets)\n\tsc.Max = make([]int, sc.NumberOfSets)\n\tfor i := 0; i < sc.NumberOfSets; i++ {\n\t\tsc.Counter[i] = 0\n\t\tsc.Max[i] = array[i].Len() - 1 \n\t}\n\n\tsc.Scatter_type = scatter_type\n\treturn\n}\n\n\n\nfunc (sc *SetCounter) Increment() (ok bool) ", "output": "{\n\n\tif sc.Scatter_type == \"cross\" {\n\t\tfor position_in_counter := sc.NumberOfSets - 1; position_in_counter >= 0; position_in_counter-- {\n\t\t\tif sc.Counter[position_in_counter] < sc.Max[position_in_counter] {\n\t\t\t\tsc.Counter[position_in_counter] += 1\n\t\t\t\tok = true\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tsc.Counter[position_in_counter] = 0\n\n\t\t}\n\t} else {\n\n\n\t\tif sc.Counter[0] >= sc.Max[0] {\n\t\t\tok = false\n\t\t\treturn\n\t\t}\n\n\t\tfor position_in_counter := sc.NumberOfSets - 1; position_in_counter >= 0; position_in_counter-- {\n\t\t\tsc.Counter[position_in_counter] += 1\n\t\t}\n\t\tok = true\n\t\treturn\n\t}\n\n\tok = false\n\treturn\n\n}"} {"input": "package testutil\n\nimport (\n\t\"testing\"\n\n\tci \"gx/ipfs/QmP1DfoUjiWH2ZBo1PBH6FupdBucbDepx3HpWmEY6JMUpY/go-libp2p-crypto\"\n\tma \"gx/ipfs/QmcyqRMCAXVtYPS4DiBrA7sezL9rRGfW8Ctx7cywL4TXJj/go-multiaddr\"\n\tpeer \"gx/ipfs/QmdS9KpbDyPrieswibZhkod1oXqRwZJrUPzxCofAMWpFGq/go-libp2p-peer\"\n)\n\ntype Identity interface {\n\tAddress() ma.Multiaddr\n\tID() peer.ID\n\tPrivateKey() ci.PrivKey\n\tPublicKey() ci.PubKey\n}\n\n\n\n\n\nfunc RandIdentityOrFatal(t *testing.T) Identity {\n\tp, err := RandPeerNetParams()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn &identity{*p}\n}\n\n\ntype identity struct {\n\tPeerNetParams\n}\n\nfunc (p *identity) ID() peer.ID {\n\treturn p.PeerNetParams.ID\n}\n\nfunc (p *identity) Address() ma.Multiaddr {\n\treturn p.Addr\n}\n\nfunc (p *identity) PrivateKey() ci.PrivKey {\n\treturn p.PrivKey\n}\n\nfunc (p *identity) PublicKey() ci.PubKey {\n\treturn p.PubKey\n}\n\nfunc RandIdentity() (Identity, error) ", "output": "{\n\tp, err := RandPeerNetParams()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &identity{*p}, nil\n}"} {"input": "package description\n\nimport (\n\t\"github.com/dropbox/goprotoc/gogoproto\"\n\t\"github.com/dropbox/goprotoc/plugin/testgen\"\n\t\"github.com/dropbox/goprotoc/protoc-gen-dgo/generator\"\n)\n\ntype test struct {\n\t*generator.Generator\n}\n\nfunc NewTest(g *generator.Generator) testgen.TestPlugin {\n\treturn &test{g}\n}\n\nfunc (p *test) Generate(imports generator.PluginImports, file *generator.FileDescriptor) bool {\n\tused := false\n\ttestingPkg := imports.NewImport(\"testing\")\n\tfor _, message := range file.Messages() {\n\t\tif !gogoproto.HasDescription(file.FileDescriptorProto, message.DescriptorProto) ||\n\t\t\t!gogoproto.HasTestGen(file.FileDescriptorProto, message.DescriptorProto) {\n\t\t\tcontinue\n\t\t}\n\t\tused = true\n\t}\n\n\tif used {\n\t\tlocalName := generator.FileName(file)\n\t\tp.P(`func Test`, localName, `Description(t *`, testingPkg.Use(), `.T) {`)\n\t\tp.In()\n\t\tp.P(localName, `Description()`)\n\t\tp.Out()\n\t\tp.P(`}`)\n\n\t}\n\treturn used\n}\n\n\n\nfunc init() ", "output": "{\n\ttestgen.RegisterTestPlugin(NewTest)\n}"} {"input": "package archive\n\nimport (\n\t\"archive/tar\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/docker/docker/pkg/longpath\"\n)\n\n\n\nfunc fixVolumePathPrefix(srcPath string) string {\n\treturn longpath.AddPrefix(srcPath)\n}\n\n\n\nfunc getWalkRoot(srcPath string, include string) string {\n\treturn filepath.Join(srcPath, include)\n}\n\n\n\n\n\n\n\n\nfunc chmodTarEntry(perm os.FileMode) os.FileMode {\n\tperm &= 0755\n\tperm |= 0111\n\n\treturn perm\n}\n\nfunc setHeaderForSpecialDevice(hdr *tar.Header, ta *tarAppender, name string, stat interface{}) (nlink uint32, inode uint64, err error) {\n\treturn\n}\n\n\n\nfunc handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error {\n\treturn nil\n}\n\nfunc handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error {\n\treturn nil\n}\n\nfunc getFileUIDGID(stat interface{}) (int, int, error) {\n\treturn 0, 0, nil\n}\n\nfunc CanonicalTarNameForPath(p string) (string, error) ", "output": "{\n\tif strings.Contains(p, \"/\") {\n\t\treturn \"\", fmt.Errorf(\"Windows path contains forward slash: %s\", p)\n\t}\n\treturn strings.Replace(p, string(os.PathSeparator), \"/\", -1), nil\n\n}"} {"input": "package collector\n\nimport (\n\t\"github.com/lowstz/mongodb_exporter/shared\"\n)\n\n\ntype MemStats struct {\n\tBits float64 `bson:\"bits\"`\n\tResident float64 `bson:\"resident\"`\n\tVirtual float64 `bson:\"virtual\"`\n\tMapped float64 `bson:\"mapped\"`\n\tMappedWithJournal float64 `bson:\"mappedWithJournal\"`\n}\n\n\n\nfunc (memStats *MemStats) Export(groupName string) ", "output": "{\n\tgroup := shared.FindOrCreateGroup(groupName)\n\tgroup.Export(\"resident\", memStats.Resident)\n\tgroup.Export(\"virtual\", memStats.Virtual)\n\tgroup.Export(\"mapped\", memStats.Mapped)\n\tgroup.Export(\"mapped_with_journal\", memStats.MappedWithJournal)\n}"} {"input": "package inmem\n\nimport (\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\ntype Reader struct {\n\tstore *Store\n}\n\nfunc newReader(store *Store) (*Reader, error) {\n\treturn &Reader{\n\t\tstore: store,\n\t}, nil\n}\n\nfunc (r *Reader) BytesSafeAfterClose() bool {\n\treturn false\n}\n\n\n\nfunc (r *Reader) Iterator(key []byte) store.KVIterator {\n\treturn r.store.iterator(key)\n}\n\nfunc (r *Reader) Close() error {\n\treturn nil\n}\n\nfunc (r *Reader) Get(key []byte) ([]byte, error) ", "output": "{\n\treturn r.store.get(key)\n}"} {"input": "package api\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/didiercrunch/doormanserver/serverstat\"\n\t\"github.com/didiercrunch/doormanserver/shared\"\n\t\"log\"\n\t\"mime\"\n\t\"net/http\"\n)\n\n\n\nfunc GetServerSpecification(w http.ResponseWriter, request *http.Request) ", "output": "{\n\ts := serverstat.Get(shared.GetParams())\n\tw.Header().Add(\"Content-Type\", mime.TypeByExtension(\".json\"))\n\tencoder := json.NewEncoder(w)\n\tif err := encoder.Encode(s); err != nil {\n\t\tlog.Println(err)\n\t}\n}"} {"input": "package world\n\nimport (\n\t\"encoding/gob\"\n\t\"math/big\"\n\t\"reflect\"\n\t\"time\"\n)\n\nvar registeredIdentifierObject = make(map[string]reflect.Type)\nvar registeredObjectIdentifier = make(map[reflect.Type]string)\n\nfunc Register(identifier string, obj ObjectLike) {\n\tif identifier == \"\" {\n\t\tpanic(\"attempt to register an empty identifier\")\n\t}\n\tif obj == nil {\n\t\tpanic(\"attempt to register a nil object type\")\n\t}\n\n\tt := reflect.TypeOf(obj)\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\n\tif _, ok := registeredIdentifierObject[identifier]; ok {\n\t\tpanic(\"duplicate registration for object identifier \" + identifier)\n\t}\n\tif _, ok := registeredObjectIdentifier[t]; ok {\n\t\tpanic(\"duplicate registration for object type \" + t.Name())\n\t}\n\tregisteredObjectIdentifier[t] = identifier\n\tregisteredIdentifierObject[identifier] = t\n}\n\nfunc getObjectTypeIdentifier(obj ObjectLike) string {\n\tt := reflect.TypeOf(obj)\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\tidentifier := registeredObjectIdentifier[t]\n\tif identifier == \"\" {\n\t\tpanic(\"unregistered object type: \" + t.Name())\n\t}\n\treturn identifier\n}\n\n\n\nfunc init() {\n\tgob.Register(map[string]interface{}{})\n\tgob.Register([]interface{}{})\n\tgob.Register(time.Time{})\n\tgob.Register(&big.Int{})\n}\n\nfunc getObjectByIdentifier(identifier string) ObjectLike ", "output": "{\n\tt := registeredIdentifierObject[identifier]\n\tif t == nil {\n\t\tpanic(\"unregistered object identifier: \" + identifier)\n\t}\n\treturn reflect.New(t).Interface().(ObjectLike)\n}"} {"input": "package gopnsconfig\n\nimport (\n\t\"log\"\n)\n\ntype BaseConfigStruct struct {\n\tPortValue string\n\tMetricsServerValue string\n\tMetricsAPIKeyValue string\n\tMetricsPrefixValue string\n}\n\nfunc (this *BaseConfigStruct) Port() string {\n\treturn this.PortValue\n}\n\nfunc (this *BaseConfigStruct) MetricsAPIKey() string {\n\treturn this.MetricsAPIKeyValue\n}\n\n\n\nfunc (this *BaseConfigStruct) MetricsPrefix() string {\n\treturn this.MetricsPrefixValue\n}\n\ntype BaseConfig interface {\n\tPort() string\n\tMetricsServer() string\n\tMetricsAPIKey() string\n\tMetricsPrefix() string\n}\n\nfunc parseBaseConfig(baseConfig *ConfigFile) BaseConfig {\n\tport, err := baseConfig.GetString(\"default\", \"port\")\n\tcheckError(\"Unable to find Server Port\", err)\n\n\tmetricsServer, err := baseConfig.GetString(\"default\", \"metrics-server\")\n\tcheckError(\"Unable to find metrics server\", err)\n\n\tmetricsKey, err := baseConfig.GetString(\"default\", \"metrics-api-key\")\n\tif err != nil {\n\t\tlog.Println(\"Unable to find metrics-api-key using empty string\")\n\t\tmetricsKey = \"\"\n\t}\n\n\tmetricsPrefix, err := baseConfig.GetString(\"default\", \"metrics-prefix\")\n\tif err != nil {\n\t\tlog.Println(\"Unable to find metrics prefix using empty string\")\n\t\tmetricsPrefix = \"\"\n\t}\n\n\tbaseConfigInstance := &BaseConfigStruct{port, metricsServer, metricsKey, metricsPrefix}\n\treturn baseConfigInstance\n\n}\n\nfunc (this *BaseConfigStruct) MetricsServer() string ", "output": "{\n\treturn this.MetricsServerValue\n}"} {"input": "package expression\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/juju/errors\"\n\t\"github.com/pingcap/tidb/context\"\n)\n\nvar (\n\t_ Expression = (*Position)(nil)\n)\n\n\n\n\ntype Position struct {\n\tN int\n\tName string\n}\n\n\nfunc (p *Position) Clone() Expression {\n\tnewP := *p\n\treturn &newP\n}\n\n\nfunc (p *Position) IsStatic() bool {\n\treturn false\n}\n\n\nfunc (p *Position) String() string {\n\tif len(p.Name) > 0 {\n\t\treturn p.Name\n\t}\n\treturn fmt.Sprintf(\"%d\", p.N)\n}\n\n\nfunc (p *Position) Eval(ctx context.Context, args map[interface{}]interface{}) (v interface{}, err error) {\n\tf, ok := args[ExprEvalPositionFunc]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"no eval position function\")\n\t}\n\tgot, ok := f.(func(int) (interface{}, error))\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"invalid eval position function format\")\n\t}\n\n\treturn got(p.N)\n}\n\n\n\n\nfunc (p *Position) Accept(v Visitor) (Expression, error) ", "output": "{\n\treturn v.VisitPosition(p)\n}"} {"input": "package messages\n\nconst (\n\tPullAllMessageSignature = 0x3F\n)\n\n\ntype PullAllMessage struct{}\n\n\nfunc NewPullAllMessage() PullAllMessage {\n\treturn PullAllMessage{}\n}\n\n\nfunc (i PullAllMessage) Signature() int {\n\treturn PullAllMessageSignature\n}\n\n\n\n\nfunc (i PullAllMessage) AllFields() []interface{} ", "output": "{\n\treturn []interface{}{}\n}"} {"input": "package labels\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\tnetwork \"knative.dev/networking/pkg\"\n\t\"knative.dev/serving/pkg/apis/serving\"\n)\n\n\nfunc IsObjectLocalVisibility(meta *metav1.ObjectMeta) bool {\n\treturn meta.Labels[network.VisibilityLabelKey] != \"\"\n}\n\n\nfunc SetVisibility(meta *metav1.ObjectMeta, isClusterLocal bool) {\n\tif isClusterLocal {\n\t\tSetLabel(meta, network.VisibilityLabelKey, serving.VisibilityClusterLocal)\n\t} else {\n\t\tDeleteLabel(meta, network.VisibilityLabelKey)\n\t}\n}\n\n\nfunc SetLabel(meta *metav1.ObjectMeta, key, value string) {\n\tif meta.Labels == nil {\n\t\tmeta.Labels = make(map[string]string, 1)\n\t}\n\n\tmeta.Labels[key] = value\n}\n\n\n\n\nfunc DeleteLabel(meta *metav1.ObjectMeta, key string) ", "output": "{\n\tdelete(meta.Labels, key)\n}"} {"input": "package mailgun\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/getfider/fider/app/models/dto\"\n\t\"github.com/getfider/fider/app/pkg/bus\"\n\t\"github.com/getfider/fider/app/pkg/env\"\n\t\"github.com/getfider/fider/app/pkg/log\"\n)\n\n\n\n\nvar baseURLs = map[string]string{\n\t\"US\": \"https://api.mailgun.net/v3/%s\",\n\t\"EU\": \"https://api.eu.mailgun.net/v3/%s\",\n}\n\nfunc init() {\n\tbus.Register(Service{})\n}\n\ntype Service struct{}\n\nfunc (s Service) Name() string {\n\treturn \"Mailgun\"\n}\n\nfunc (s Service) Category() string {\n\treturn \"email\"\n}\n\n\n\nfunc (s Service) Init() {\n\tbus.AddListener(sendMail)\n\tbus.AddHandler(fetchRecentSupressions)\n}\n\n\n\nfunc getEndpoint(ctx context.Context, domain, path string) string {\n\tvar regionCode = env.Config.Email.Mailgun.Region\n\tregionCode = strings.ToUpper(regionCode)\n\n\tif len(regionCode) < 1 {\n\t\tregionCode = \"US\"\n\t} else if len(baseURLs[regionCode]) < 1 {\n\t\tlog.Warnf(ctx,\n\t\t\t\"Unknown Mailgun region code '@{Code}' configured - falling back to 'US'\",\n\t\t\tdto.Props{\n\t\t\t\t\"Code\": env.Config.Email.Mailgun.Region,\n\t\t\t},\n\t\t)\n\n\t\tregionCode = \"US\"\n\t}\n\n\treturn fmt.Sprintf(baseURLs[regionCode], domain) + path\n}\n\nfunc (s Service) Enabled() bool ", "output": "{\n\treturn env.Config.Email.Type == \"mailgun\"\n}"} {"input": "package roles\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar TopLevelRoles = map[string]struct{}{\n\t\"root\": {},\n\t\"targets\": {},\n\t\"snapshot\": {},\n\t\"timestamp\": {},\n}\n\nfunc IsTopLevelRole(name string) bool {\n\t_, ok := TopLevelRoles[name]\n\treturn ok\n}\n\nfunc IsDelegatedTargetsRole(name string) bool {\n\treturn !IsTopLevelRole(name)\n}\n\nfunc IsTopLevelManifest(name string) bool {\n\treturn IsTopLevelRole(strings.TrimSuffix(name, \".json\"))\n}\n\nfunc IsDelegatedTargetsManifest(name string) bool {\n\treturn !IsTopLevelManifest(name)\n}\n\n\n\nfunc IsVersionedManifest(name string) bool ", "output": "{\n\tparts := strings.Split(name, \".\")\n\tif len(parts) < 3 {\n\t\treturn false\n\t}\n\n\t_, err := strconv.Atoi(parts[0])\n\treturn err == nil\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"os/exec\"\n)\n\nfunc panicOn(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc FileExists(name string) bool {\n\tfi, err := os.Stat(name)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif fi.IsDir() {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc DirExists(name string) bool {\n\tfi, err := os.Stat(name)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif fi.IsDir() {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc Run(dir string, exe string, arg ...string) (stdout *bytes.Buffer, stderr *bytes.Buffer, err error) ", "output": "{\n\tcmd := exec.Command(exe, arg...)\n\tvar errbuf bytes.Buffer\n\tvar outbuf bytes.Buffer\n\tcmd.Dir = dir\n\tcmd.Stderr = &errbuf\n\tcmd.Stdout = &outbuf\n\terr = cmd.Run()\n\treturn &outbuf, &errbuf, err\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n)\n\n\nconst DeleteDeploymentOKCode int = 200\n\n\ntype DeleteDeploymentOK struct {\n}\n\n\n\n\n\nfunc (o *DeleteDeploymentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n}\n\n\nconst DeleteDeploymentUnauthorizedCode int = 401\n\n\ntype DeleteDeploymentUnauthorized struct {\n\tWWWAuthenticate string `json:\"WWW_Authenticate\"`\n}\n\n\nfunc NewDeleteDeploymentUnauthorized() *DeleteDeploymentUnauthorized {\n\treturn &DeleteDeploymentUnauthorized{}\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) WithWWWAuthenticate(wWWAuthenticate string) *DeleteDeploymentUnauthorized {\n\to.WWWAuthenticate = wWWAuthenticate\n\treturn o\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) SetWWWAuthenticate(wWWAuthenticate string) {\n\to.WWWAuthenticate = wWWAuthenticate\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\n\twWWAuthenticate := o.WWWAuthenticate\n\tif wWWAuthenticate != \"\" {\n\t\trw.Header().Set(\"WWW_Authenticate\", wWWAuthenticate)\n\t}\n\n\trw.WriteHeader(401)\n}\n\n\nconst DeleteDeploymentNotFoundCode int = 404\n\n\ntype DeleteDeploymentNotFound struct {\n}\n\n\nfunc NewDeleteDeploymentNotFound() *DeleteDeploymentNotFound {\n\treturn &DeleteDeploymentNotFound{}\n}\n\n\nfunc (o *DeleteDeploymentNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(404)\n}\n\n\nconst DeleteDeploymentInternalServerErrorCode int = 500\n\n\ntype DeleteDeploymentInternalServerError struct {\n}\n\n\nfunc NewDeleteDeploymentInternalServerError() *DeleteDeploymentInternalServerError {\n\treturn &DeleteDeploymentInternalServerError{}\n}\n\n\nfunc (o *DeleteDeploymentInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(500)\n}\n\nfunc NewDeleteDeploymentOK() *DeleteDeploymentOK ", "output": "{\n\treturn &DeleteDeploymentOK{}\n}"} {"input": "package ccerror\n\n\n\ntype ForbiddenError struct {\n\tMessage string\n}\n\n\n\nfunc (e ForbiddenError) Error() string ", "output": "{\n\treturn e.Message\n}"} {"input": "package log\n\nimport \"gopkg.in/inconshreveable/log15.v2\"\n\nvar (\n\tLogger log15.Logger\n)\n\nfunc init() {\n\tLogger = log15.New()\n\tLogger.SetHandler(log15.DiscardHandler())\n}\n\n\n\nfunc Interactive() {\n\tLogger.SetHandler(log15.MultiHandler(\n\t\tlog15.LvlFilterHandler(\n\t\t\tlog15.LvlError,\n\t\t\tlog15.StderrHandler)))\n}\n\n\nfunc Debug(msg string, ctx ...interface{}) { Logger.Debug(msg, ctx...) }\nfunc Info(msg string, ctx ...interface{}) { Logger.Info(msg, ctx...) }\n\nfunc Error(msg string, ctx ...interface{}) { Logger.Error(msg, ctx...) }\nfunc Crit(msg string, ctx ...interface{}) { Logger.Crit(msg, ctx...) }\n\nfunc Warn(msg string, ctx ...interface{}) ", "output": "{ Logger.Warn(msg, ctx...) }"} {"input": "package restic\n\nimport \"syscall\"\n\nfunc (node Node) restoreSymlinkTimestamps(path string, utimes [2]syscall.Timespec) error {\n\treturn nil\n}\n\nfunc (s statUnix) atim() syscall.Timespec { return s.Atim }\nfunc (s statUnix) mtim() syscall.Timespec { return s.Mtim }\n\n\nfunc (s statUnix) ctim() syscall.Timespec ", "output": "{ return s.Ctim }"} {"input": "package dev\n\nimport \"fmt\"\n\n\n\ntype Configuration struct {\n\tid uint32\n\tnodes []*Node\n\tn int\n\tmgr *Manager\n\tqspec QuorumSpec\n\terrs chan CallGRPCError\n}\n\n\n\nfunc (c *Configuration) SubError() <-chan CallGRPCError {\n\treturn c.errs\n}\n\n\nfunc (c *Configuration) ID() uint32 {\n\treturn c.id\n}\n\n\n\n\nfunc (c *Configuration) NodeIDs() []uint32 {\n\tids := make([]uint32, len(c.nodes))\n\tfor i, node := range c.nodes {\n\t\tids[i] = node.ID()\n\t}\n\treturn ids\n}\n\n\n\nfunc (c *Configuration) Nodes() []*Node {\n\treturn c.nodes\n}\n\n\nfunc (c *Configuration) Size() int {\n\treturn c.n\n}\n\n\n\nfunc (c *Configuration) tstring() string {\n\treturn fmt.Sprintf(\"config-%d\", c.id)\n}\n\n\n\nfunc Equal(a, b *Configuration) bool { return a.id == b.id }\n\n\n\n\nfunc NewTestConfiguration(q, n int) *Configuration {\n\treturn &Configuration{\n\t\tnodes: make([]*Node, n),\n\t}\n}\n\nfunc (c *Configuration) String() string ", "output": "{\n\treturn fmt.Sprintf(\"configuration %d\", c.id)\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetAutonomousPatchRequest struct {\n\n\tAutonomousPatchId *string `mandatory:\"true\" contributesTo:\"path\" name:\"autonomousPatchId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetAutonomousPatchRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request GetAutonomousPatchRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request GetAutonomousPatchRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetAutonomousPatchRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetAutonomousPatchResponse struct {\n\n\tRawResponse *http.Response\n\n\tAutonomousPatch `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response GetAutonomousPatchResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response GetAutonomousPatchResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package objc\n\nimport \"testing\"\n\n\n\nfunc TestIvarGetTypeEncoding(t *testing.T) {\n\tclassName := \"ClassWithIvarForEncodingTest\"\n\tivarName := \"ivar\"\n\ttypeEncoding := \"i\"\n\tclass := Objc_allocateClassPair(nil, className, 0)\n\n\tClass_addIvar(class, ivarName, 4, 0, typeEncoding)\n\tivar := Class_getInstanceVariable(class, ivarName)\n\n\tif encoding := Ivar_getTypeEncoding(ivar); encoding != typeEncoding {\n\t\tt.Errorf(\"encoding should be %s: %s\", typeEncoding, encoding)\n\t}\n}\n\nfunc TestIvarGetName(t *testing.T) ", "output": "{\n\tclassName := \"ClassWithIvar\"\n\tclass := Objc_allocateClassPair(nil, className, 0)\n\tivarName := \"ivar\"\n\n\tClass_addIvar(class, ivarName, 4, 0, \"i\")\n\tivar := Class_getInstanceVariable(class, ivarName)\n\n\tif name := Ivar_getName(ivar); name != ivarName {\n\t\tt.Errorf(\"name should be %s: %s\", ivarName, ivar)\n\t}\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\ntype SendPhotoLinkBody struct {\n\n\tCaption string `json:\"caption,omitempty\"`\n\n\tChatID interface{} `json:\"chat_id\"`\n\n\tDisableNotification bool `json:\"disable_notification,omitempty\"`\n\n\tPhoto *string `json:\"photo\"`\n\n\tReplyMarkup interface{} `json:\"reply_markup,omitempty\"`\n\n\tReplyToMessageID int64 `json:\"reply_to_message_id,omitempty\"`\n}\n\n\nfunc (m *SendPhotoLinkBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateChatID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePhoto(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\nfunc (m *SendPhotoLinkBody) validatePhoto(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"photo\", \"body\", m.Photo); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc (m *SendPhotoLinkBody) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *SendPhotoLinkBody) UnmarshalBinary(b []byte) error {\n\tvar res SendPhotoLinkBody\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *SendPhotoLinkBody) validateChatID(formats strfmt.Registry) error ", "output": "{\n\n\treturn nil\n}"} {"input": "package libsecrets\n\nimport (\n\t\"time\"\n\n\t\"github.com/keybase/client/go/protocol/keybase1\"\n)\n\n\ntype Member struct {\n\tIdentifier string\n\tType string\n\tKeybaseUid keybase1.UID\n\tAddedBy string\n\tDateAdded time.Time\n}\n\n\nfunc NewKeybaseMember(username string, uid keybase1.UID) *Member {\n\treturn &Member{\n\t\tIdentifier: username,\n\t\tType: \"keybase\",\n\t\tKeybaseUid: uid,\n\t\tDateAdded: time.Now(),\n\t}\n}\n\n\nfunc NewMemberFromKeybaseUser(user *keybase1.User) *Member {\n\treturn NewKeybaseMember(user.Username, user.Uid)\n}\n\n\n\nfunc GetMemberListIdentifiers(members []*Member) (identifiers []string) ", "output": "{\n\tfor _, memberPointer := range members {\n\t\tmember := *memberPointer\n\t\tif member.Type != \"keybase\" {\n\t\t\tcontinue\n\t\t}\n\t\tidentifiers = append(identifiers, member.Identifier)\n\t}\n\n\treturn identifiers\n}"} {"input": "package socketio\n\nimport \"errors\"\n\n\ntype BroadcastAdaptor interface {\n\n\tJoin(room string, socket Socket) error\n\n\tLeave(room string, socket Socket) error\n\n\tSend(ignore Socket, room, event string, args ...interface{}) error\n\n\tGetAllClients(room string) (map[string]Socket, error)\n}\n\nvar newBroadcast = newBroadcastDefault\n\ntype Broadcast map[string]map[string]Socket\n\n\n\nfunc (b Broadcast) Join(room string, socket Socket) error {\n\tsockets, ok := b[room]\n\tif !ok {\n\t\tsockets = make(map[string]Socket)\n\t}\n\tsockets[socket.Id()] = socket\n\tb[room] = sockets\n\treturn nil\n}\n\nfunc (b Broadcast) Leave(room string, socket Socket) error {\n\tsockets, ok := b[room]\n\tif !ok {\n\t\treturn nil\n\t}\n\tdelete(sockets, socket.Id())\n\tif len(sockets) == 0 {\n\t\tdelete(b, room)\n\t\treturn nil\n\t}\n\tb[room] = sockets\n\treturn nil\n}\n\nfunc (b Broadcast) Send(ignore Socket, room, event string, args ...interface{}) error {\n\tsockets := b[room]\n\tfor id, s := range sockets {\n\t\tif ignore != nil && ignore.Id() == id {\n\t\t\tcontinue\n\t\t}\n\t\ts.Emit(event, args...)\n\t}\n\treturn nil\n}\n\nfunc (b Broadcast) GetAllClients(room string) (map[string]Socket, error) {\n\tsockets, ok := b[room]\n\tif !ok {\n\t\treturn nil, errors.New(\"没有此房间\")\n\t}\n\treturn sockets, nil\n}\n\nfunc newBroadcastDefault() BroadcastAdaptor ", "output": "{\n\treturn make(Broadcast)\n}"} {"input": "package grpc\n\nimport (\n\t\"github.com/micro/go-micro/v3/client\"\n)\n\ntype grpcEvent struct {\n\ttopic string\n\tcontentType string\n\tpayload interface{}\n}\n\nfunc newGRPCEvent(topic string, payload interface{}, contentType string, opts ...client.MessageOption) client.Message {\n\tvar options client.MessageOptions\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\tif len(options.ContentType) > 0 {\n\t\tcontentType = options.ContentType\n\t}\n\n\treturn &grpcEvent{\n\t\tpayload: payload,\n\t\ttopic: topic,\n\t\tcontentType: contentType,\n\t}\n}\n\nfunc (g *grpcEvent) ContentType() string {\n\treturn g.contentType\n}\n\n\n\nfunc (g *grpcEvent) Payload() interface{} {\n\treturn g.payload\n}\n\nfunc (g *grpcEvent) Topic() string ", "output": "{\n\treturn g.topic\n}"} {"input": "package controllers\n\nimport (\n\t\"html/template\"\n\t\"net/http\"\n)\n\n\n\nfunc Error501(rw http.ResponseWriter, req *http.Request) {\n\tt, _ := template.ParseFiles(\"views/501.html\")\n\tt.Execute(rw, nil)\n}\n\nfunc Error404(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\tt, _ := template.ParseFiles(\"views/404.html\")\n\tt.Execute(rw, nil)\n}"} {"input": "package wire\n\nimport (\n\t\"time\"\n)\n\n\ntype periodicTask struct {\n\tperiod time.Duration\n\ttask func()\n\tticker *time.Ticker\n\tstop chan struct{}\n}\n\n\n\n\n\nfunc (pt *periodicTask) Start() {\n\tif pt.ticker != nil || pt.period <= 0 {\n\t\treturn\n\t}\n\n\tpt.ticker = time.NewTicker(pt.period)\n\tpt.stop = make(chan struct{})\n\tgo pt.poll(pt.ticker, pt.stop)\n}\n\n\nfunc (pt *periodicTask) Stop() {\n\tif pt.ticker == nil {\n\t\treturn\n\t}\n\n\tpt.ticker.Stop()\n\tclose(pt.stop)\n\n\tpt.ticker = nil\n\tpt.stop = nil\n}\n\nfunc (pt *periodicTask) poll(ticker *time.Ticker, stop chan struct{}) {\n\tfor {\n\t\tselect {\n\t\tcase <-stop:\n\t\t\treturn \n\t\tdefault:\n\t\t}\n\n\t\tselect {\n\t\tcase <-stop:\n\t\t\treturn \n\t\tcase <-ticker.C:\n\t\t\tpt.task()\n\t\t}\n\t}\n}\n\nfunc newPeriodicTask(period time.Duration, task func()) *periodicTask ", "output": "{\n\treturn &periodicTask{\n\t\tperiod: period,\n\t\ttask: task,\n\t}\n}"} {"input": "package invoice_payment\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/go-openapi/runtime\"\n\t\"github.com/killbill/kbcli/v2/kbcommon\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\ntype DeleteInvoicePaymentTagsReader struct {\n\tformats strfmt.Registry\n}\n\n\n\n\n\nfunc NewDeleteInvoicePaymentTagsNoContent() *DeleteInvoicePaymentTagsNoContent {\n\treturn &DeleteInvoicePaymentTagsNoContent{}\n}\n\n\ntype DeleteInvoicePaymentTagsNoContent struct {\n\tHttpResponse runtime.ClientResponse\n}\n\nfunc (o *DeleteInvoicePaymentTagsNoContent) Error() string {\n\treturn fmt.Sprintf(\"[DELETE /1.0/kb/invoicePayments/{paymentId}/tags][%d] deleteInvoicePaymentTagsNoContent \", 204)\n}\n\nfunc (o *DeleteInvoicePaymentTagsNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\treturn nil\n}\n\n\nfunc NewDeleteInvoicePaymentTagsBadRequest() *DeleteInvoicePaymentTagsBadRequest {\n\treturn &DeleteInvoicePaymentTagsBadRequest{}\n}\n\n\ntype DeleteInvoicePaymentTagsBadRequest struct {\n\tHttpResponse runtime.ClientResponse\n}\n\nfunc (o *DeleteInvoicePaymentTagsBadRequest) Error() string {\n\treturn fmt.Sprintf(\"[DELETE /1.0/kb/invoicePayments/{paymentId}/tags][%d] deleteInvoicePaymentTagsBadRequest \", 400)\n}\n\nfunc (o *DeleteInvoicePaymentTagsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\treturn nil\n}\n\nfunc (o *DeleteInvoicePaymentTagsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) ", "output": "{\n\tswitch response.Code() {\n\n\tcase 204:\n\t\tresult := NewDeleteInvoicePaymentTagsNoContent()\n\t\tresult.HttpResponse = response\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\terrorResult := kbcommon.NewKillbillError(response.Code())\n\t\tif err := consumer.Consume(response.Body(), &errorResult); err != nil && err != io.EOF {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, errorResult\n\t}\n}"} {"input": "package clients\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n\n\t\"github.com/VolantMQ/volantmq/subscriber\"\n)\n\nvar subCount int32 = 0\n\n\n\ntype container struct {\n\tlock sync.Mutex\n\trmLock sync.RWMutex\n\tses *session\n\texpiry atomic.Value\n\tsub *subscriber.Type\n\tremovable bool\n\tremoved bool\n}\n\nfunc (s *container) setRemovable(rm bool) {\n\ts.rmLock.Lock()\n\ts.removable = rm\n\ts.rmLock.Unlock()\n}\n\n\n\nfunc (s *container) release() {\n\ts.lock.Unlock()\n}\n\nfunc (s *container) session() *session {\n\tdefer s.rmLock.Unlock()\n\ts.rmLock.Lock()\n\treturn s.ses\n}\n\nfunc (s *container) swap(from *container) *container {\n\ts.ses = from.ses\n\n\ts.ses.idLock = &s.lock\n\n\treturn s\n}\n\nfunc (s *container) subscriber(cleanStart bool, c subscriber.Config) *subscriber.Type {\n\tif cleanStart && s.sub != nil {\n\t\ts.sub.Offline(true)\n\t\ts.sub = nil\n\t}\n\n\tif s.sub == nil {\n\t\ts.sub = subscriber.New(c)\n\t}\n\n\treturn s.sub\n}\n\nfunc (s *container) acquire() ", "output": "{\n\ts.lock.Lock()\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/apier/v1\"\n\t\"github.com/cgrates/cgrates/engine\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\n\n\n\ntype CmdGetDataCost struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrGetDataCost\n\tclientArgs []string\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetDataCost) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdGetDataCost) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdGetDataCost) RpcParams() interface{} {\n\tif self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrGetDataCost{Direction: utils.OUT}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetDataCost) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetDataCost) RpcResult() interface{} {\n\treturn &engine.DataCost{}\n}\n\nfunc (self *CmdGetDataCost) ClientArgs() []string {\n\treturn self.clientArgs\n}\n\nfunc init() ", "output": "{\n\tc := &CmdGetDataCost{\n\t\tname: \"datacost\",\n\t\trpcMethod: \"ApierV1.GetDataCost\",\n\t\tclientArgs: []string{\"Direction\", \"Category\", \"Tenant\", \"Account\", \"Subject\", \"StartTime\", \"Usage\"},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}"} {"input": "package helpers\n\nimport (\n\t\"os\"\n\t\"strconv\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\n\n\n\n\nfunc SkipIfCustomClientCredentialsNotSet() (string, string) {\n\tcustomClientID := os.Getenv(\"CF_INT_CUSTOM_CLIENT_ID\")\n\tcustomClientSecret := os.Getenv(\"CF_INT_CUSTOM_CLIENT_SECRET\")\n\n\tif customClientID == \"\" || customClientSecret == \"\" {\n\t\tSkip(\"CF_INT_CUSTOM_CLIENT_ID or CF_INT_CUSTOM_CLIENT_SECRET is not set\")\n\t}\n\n\treturn customClientID, customClientSecret\n}\n\nfunc SkipIfClientCredentialsTestMode() {\n\tif ClientCredentialsTestMode() {\n\t\tSkip(\"CF_INT_CLIENT_CREDENTIALS_TEST_MODE is enabled\")\n\t}\n}\n\nfunc ClientCredentialsTestMode() bool {\n\tenvVar := os.Getenv(\"CF_INT_CLIENT_CREDENTIALS_TEST_MODE\")\n\n\tif envVar == \"\" {\n\t\treturn false\n\t}\n\n\ttestMode, err := strconv.ParseBool(envVar)\n\tExpect(err).ToNot(HaveOccurred(), \"CF_INT_CLIENT_CREDENTIALS_TEST_MODE should be boolean\")\n\n\treturn testMode\n}\n\nfunc SkipIfClientCredentialsNotSet() (string, string) ", "output": "{\n\tprivateClientID := os.Getenv(\"CF_INT_CLIENT_ID\")\n\tprivateClientSecret := os.Getenv(\"CF_INT_CLIENT_SECRET\")\n\n\tif privateClientID == \"\" || privateClientSecret == \"\" {\n\t\tSkip(\"CF_INT_CLIENT_ID or CF_INT_CLIENT_SECRET is not set\")\n\t}\n\n\treturn privateClientID, privateClientSecret\n}"} {"input": "package namespaces\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\n\t\"github.com/dotcloud/docker/pkg/term\"\n)\n\ntype TtyTerminal struct {\n\tstdin io.Reader\n\tstdout, stderr io.Writer\n\tmaster *os.File\n\tstate *term.State\n}\n\n\n\nfunc (t *TtyTerminal) SetMaster(master *os.File) {\n\tt.master = master\n}\n\nfunc (t *TtyTerminal) Attach(command *exec.Cmd) error {\n\tgo io.Copy(t.stdout, t.master)\n\tgo io.Copy(t.master, t.stdin)\n\n\tstate, err := t.setupWindow(t.master, os.Stdin)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.state = state\n\treturn err\n}\n\n\n\nfunc (t *TtyTerminal) setupWindow(master, parent *os.File) (*term.State, error) {\n\tws, err := term.GetWinsize(parent.Fd())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := term.SetWinsize(master.Fd(), ws); err != nil {\n\t\treturn nil, err\n\t}\n\treturn term.SetRawTerminal(parent.Fd())\n}\n\nfunc (t *TtyTerminal) Close() error {\n\tterm.RestoreTerminal(os.Stdin.Fd(), t.state)\n\treturn t.master.Close()\n}\n\nfunc (t *TtyTerminal) Resize(h, w int) error ", "output": "{\n\treturn term.SetWinsize(t.master.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)})\n}"} {"input": "package handler\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/labstack/echo\"\n)\n\ntype (\n\tUser struct {\n\t\tName string `json:\"name\" form:\"name\"`\n\t\tEmail string `json:\"name\" form:\"name\"`\n\t}\n\thandler struct {\n\t\tdb map[string]*User\n\t}\n)\n\n\n\nfunc (h *handler) getUser(c echo.Context) error {\n\temail := c.Param(\"email\")\n\tuser := h.db[email]\n\tif user == nil {\n\t\treturn echo.NewHTTPError(http.StatusNotFound, \"user not found\")\n\t}\n\treturn c.JSON(http.StatusOK, user)\n}\n\nfunc (h *handler) createUser(c echo.Context) error ", "output": "{\n\tu := new(User)\n\tif err := c.Bind(u); err != nil {\n\t\treturn err\n\t}\n\treturn c.JSON(http.StatusOK, u)\n}"} {"input": "package discern\n\nimport \"testing\"\n\n\n\n\nfunc TestAnalyzeResponse(t *testing.T) ", "output": "{\n resp := &WikiResponse{\"YCK\", map[string]int{\"10-10-2012\": 100}} \n analyzeResponse(resp, 99.9)\n}"} {"input": "package file\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\n\n\ntype darwinExFileInfo struct {\n\tos.FileInfo\n\tfid FID\n\tpath string\n}\n\n\n\nfunc timespecToTime(ts syscall.Timespec) time.Time {\n\treturn time.Unix(int64(ts.Sec), int64(ts.Nsec))\n}\n\n\n\n\n\nfunc (fi *darwinExFileInfo) ATime() time.Time {\n\treturn timespecToTime(fi.Sys().(*syscall.Stat_t).Atimespec)\n}\n\n\nfunc (fi *darwinExFileInfo) FID() FID {\n\treturn fi.fid\n}\n\n\nfunc (fi *darwinExFileInfo) Path() string {\n\treturn fi.path\n}\n\n\nfunc systemExFileInfo(fi os.FileInfo, path string) *darwinExFileInfo {\n\tfid := FID{\n\t\tIDLow: fi.Sys().(*syscall.Stat_t).Ino,\n\t}\n\tabsolute, _ := filepath.Abs(path)\n\treturn &darwinExFileInfo{\n\t\tFileInfo: fi,\n\t\tfid: fid,\n\t\tpath: filepath.Clean(absolute),\n\t}\n}\n\nfunc (fi *darwinExFileInfo) CTime() time.Time ", "output": "{\n\treturn timespecToTime(fi.Sys().(*syscall.Stat_t).Ctimespec)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/bulletind/khabar/utils\"\n\n\t\"gopkg.in/mgo.v2\"\n\t\"gopkg.in/mgo.v2/bson\"\n)\n\nconst (\n\ttopicsCollection = \"topics\"\n)\n\n\n\nfunc main() {\n\tsession, db, _ := Connect()\n\n\tTopics := db.C(topicsCollection)\n\tquery := bson.M{\n\t\t\"org\": utils.M{\"$ne\": \"\"},\n\t\t\"user\": utils.M{\"$ne\": \"\"},\n\t}\n\n\tchange, err := Topics.RemoveAll(query)\n\thandle_errors(err)\n\tfmt.Println(change.Removed, \"user preferences were removed from `\", topicsCollection, \"` collection\")\n\n\tquery[\"user\"] = \"\"\n\tchange, err = Topics.RemoveAll(query)\n\thandle_errors(err)\n\tfmt.Println(change.Removed, \"org preferences were removed from `\", topicsCollection, \"` collection\")\n\n\tsession.Close()\n\tfmt.Println(\"\\n\", \"Closing mongodb connection\")\n}\n\n\n\nfunc Connect() (*mgo.Session, *mgo.Database, string) {\n\turi := os.Getenv(\"MONGODB_URL\")\n\n\tif uri == \"\" {\n\t\turi = \"mongodb://localhost:27017/notifications_testing\"\n\t}\n\n\tmInfo, err := mgo.ParseURL(uri)\n\tsession, err := mgo.Dial(uri)\n\tif err != nil {\n\t\tfmt.Printf(\"Can't connect to mongo, go error %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tsession.SetSafe(&mgo.Safe{})\n\tfmt.Println(\"Connected to\", uri, \"\\n\")\n\n\tsess := session.Clone()\n\n\treturn session, sess.DB(mInfo.Database), mInfo.Database\n}\n\n\n\n\n\nfunc handle_errors(err error) ", "output": "{\n\tif err != nil {\n\t\tlog.Printf(\"Error %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}"} {"input": "package wire_test\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\n\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc (w *fixedWriter) Bytes() []byte ", "output": "{\n\treturn w.b\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nvar c = func() [51]uint64 {\n\tvar c [51]uint64\n\tc[0] = 1\n\tc[1] = 2\n\treturn c\n}()\n\n\n\nfunc main() {\n\tin, _ := os.Open(\"10450.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"10450.out\")\n\tdefer out.Close()\n\n\tvar n, b int\n\tfmt.Fscanf(in, \"%d\", &n)\n\tfor i := 1; i <= n; i++ {\n\t\tfmt.Fscanf(in, \"%d\", &b)\n\t\tfmt.Fprintf(out, \"Scenario #%d:\\n%v\\n\\n\", i, f(b))\n\t}\n}\n\nfunc f(b int) uint64 ", "output": "{\n\tif c[b] != 0 {\n\t\treturn c[b]\n\t}\n\tc[b] = f(b-1) + f(b-2)\n\treturn c[b]\n}"} {"input": "package dnsrecorder\n\nimport (\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n)\n\n\n\n\n\n\n\ntype Recorder struct {\n\tdns.ResponseWriter\n\tRcode int\n\tSize int\n\tMsg *dns.Msg\n\tStart time.Time\n}\n\n\n\n\nfunc New(w dns.ResponseWriter) *Recorder {\n\treturn &Recorder{\n\t\tResponseWriter: w,\n\t\tRcode: 0,\n\t\tMsg: nil,\n\t\tStart: time.Now(),\n\t}\n}\n\n\n\nfunc (r *Recorder) WriteMsg(res *dns.Msg) error {\n\tr.Rcode = res.Rcode\n\tr.Size += res.Len()\n\tr.Msg = res\n\treturn r.ResponseWriter.WriteMsg(res)\n}\n\n\nfunc (r *Recorder) Write(buf []byte) (int, error) {\n\tn, err := r.ResponseWriter.Write(buf)\n\tif err == nil {\n\t\tr.Size += n\n\t}\n\treturn n, err\n}\n\n\n\n\n\nfunc (r *Recorder) Hijack() ", "output": "{ r.ResponseWriter.Hijack(); return }"} {"input": "package dockerutil\n\nimport (\n\t\"github.com/facebookgo/stackerr\"\n\t\"github.com/samalba/dockerclient\"\n)\n\n\n\n\n\nfunc CreateWithPull(\n\td dockerclient.Client,\n\tc *dockerclient.ContainerConfig,\n\tname string,\n\tac *dockerclient.AuthConfig,\n) (string, error) ", "output": "{\n\n\tid, err := d.CreateContainer(c, name)\n\tif err == nil {\n\t\treturn id, nil\n\t}\n\n\tif err != dockerclient.ErrNotFound {\n\t\treturn \"\", stackerr.Wrap(err)\n\t}\n\n\tif err := d.PullImage(c.Image, ac); err != nil {\n\t\treturn \"\", stackerr.Wrap(err)\n\t}\n\n\tid, err = d.CreateContainer(c, name)\n\tif err != nil {\n\t\treturn \"\", stackerr.Wrap(err)\n\t}\n\n\treturn id, nil\n}"} {"input": "package prometheus_test\n\nimport (\n\t\"github.com/golang/protobuf/proto\"\n\tdto \"github.com/prometheus/client_model/go\"\n)\n\n\n\nfunc NewCounter(name string, v float64, ls ...*dto.LabelPair) *dto.MetricFamily ", "output": "{\n\tm := &dto.Metric{\n\t\tLabel: ls,\n\t\tCounter: &dto.Counter{\n\t\t\tValue: &v,\n\t\t},\n\t}\n\treturn &dto.MetricFamily{\n\t\tName: proto.String(name),\n\t\tType: dto.MetricType_COUNTER.Enum(),\n\t\tMetric: []*dto.Metric{m},\n\t}\n}"} {"input": "package admin\nimport (\n\t\"os\"\n\t\"runtime\"\n\t\"github.com/caliven/go-space/models\"\n\t\"github.com/caliven/go-space/controllers/common\"\n)\n\n\ntype HomeController struct {\n\tcommon.CommonController\n}\n\n\n\nfunc (this *HomeController) Get() ", "output": "{\n\tthis.Data[\"hostname\"], _ = os.Hostname()\n\tthis.Data[\"goos\"] = runtime.GOOS\n\tthis.Data[\"goarch\"] = runtime.GOARCH\n\tthis.Data[\"numcpu\"] = runtime.NumCPU()\n\tthis.Data[\"version\"] = runtime.Version()\n\n\tthis.Data[\"articleCount\"] = new(models.Article).QueryCount()\n\tthis.Data[\"tagCount\"] = new(models.Tag).QueryCount()\n\tthis.Data[\"userCount\"], _ = new(models.User).Query().Count()\n\tthis.Data[\"commentCount\"] = 100\n\tlist, _ := models.QueryArticleList(1)\n\tthis.Data[\"articleList\"] = list\n\tthis.Data[\"layoutTitle\"] = \"控制台\"\n\n\tthis.LoadTplNames(\"home.tpl\")\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"sync\"\n\n\t\"github.com/open-policy-agent/opa/cmd\"\n\t\"github.com/open-policy-agent/opa/plugins\"\n\t\"github.com/open-policy-agent/opa/plugins/logs\"\n\t\"github.com/open-policy-agent/opa/runtime\"\n\t\"github.com/open-policy-agent/opa/util\"\n)\n\ntype Config struct {\n\tStderr bool `json:\"stderr\"`\n}\n\ntype Factory struct{}\n\nfunc (Factory) New(_ *plugins.Manager, config interface{}) plugins.Plugin {\n\treturn &PrintlnLogger{\n\t\tconfig: config.(Config),\n\t}\n}\n\nfunc (Factory) Validate(_ *plugins.Manager, config []byte) (interface{}, error) {\n\tparsedConfig := Config{}\n\treturn parsedConfig, util.Unmarshal(config, &parsedConfig)\n}\n\ntype PrintlnLogger struct {\n\tconfig Config\n\tmtx sync.Mutex\n}\n\nfunc (p *PrintlnLogger) Start(ctx context.Context) error {\n\treturn nil\n}\n\nfunc (p *PrintlnLogger) Stop(ctx context.Context) {\n}\n\nfunc (p *PrintlnLogger) Reconfigure(ctx context.Context, config interface{}) {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tp.config = config.(Config)\n}\n\n\n\nfunc main() {\n\n\truntime.RegisterPlugin(\"println_decision_logger\", Factory{})\n\n\tif err := cmd.RootCommand.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc (p *PrintlnLogger) Log(ctx context.Context, event logs.EventV1) error ", "output": "{\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tw := os.Stdout\n\tif p.config.Stderr {\n\t\tw = os.Stderr\n\t}\n\tfmt.Fprintln(w, event) \n\treturn nil\n}"} {"input": "package helpers\n\nimport (\n\t\"fmt\"\n\t\"gopkg.in/ini.v1\"\n\t\"runtime\"\n)\n\ntype Distro struct {\n\tFamily string \n\tInitSystem string \n\tVersion string \n}\n\n\nfunc (d *Distro) SetFamily(family string) error {\n\n\tswitch family {\n\tcase \"debian\":\n\t\td.Family = family\n\tcase \"centos\":\n\t\td.Family = family\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown Linux distribution: %s\", family)\n\t}\n\treturn nil\n}\n\n\nfunc (d *Distro) SetInitSystem() error {\n\n\tswitch d.Family {\n\tcase \"debian\":\n\t\td.InitSystem = \"systemd\" \n\tcase \"centos\":\n\t\td.InitSystem = \"sysv\"\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown Init system for distribution: %s\", d.Family)\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc GetDistro() (*Distro, error) ", "output": "{\n\td := Distro{}\n\tif runtime.GOOS == \"linux\" {\n\t\ti, err := ini.Load([]byte(\"\"), \"/etc/os-release\")\n\t\tsection, err := i.Section(\"\").GetKey(\"ID_LIKE\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = d.SetFamily(section.String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = d.SetInitSystem()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &d, nil\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype OpenpitrixLeaveGroupResponse struct {\n\n\tGroupID []string `json:\"group_id\"`\n\n\tUserID []string `json:\"user_id\"`\n}\n\n\n\n\nfunc (m *OpenpitrixLeaveGroupResponse) validateGroupID(formats strfmt.Registry) error {\n\n\tif swag.IsZero(m.GroupID) { \n\t\treturn nil\n\t}\n\n\treturn nil\n}\n\nfunc (m *OpenpitrixLeaveGroupResponse) validateUserID(formats strfmt.Registry) error {\n\n\tif swag.IsZero(m.UserID) { \n\t\treturn nil\n\t}\n\n\treturn nil\n}\n\n\nfunc (m *OpenpitrixLeaveGroupResponse) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *OpenpitrixLeaveGroupResponse) UnmarshalBinary(b []byte) error {\n\tvar res OpenpitrixLeaveGroupResponse\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *OpenpitrixLeaveGroupResponse) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateGroupID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateUserID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package bot\n\nimport \"fmt\"\n\ntype ErrorLevel int\n\n\nconst (\n\tError ErrorLevel = iota\n\tInfo\n\tWarn\n\tDebug\n)\n\ntype LogRecord struct {\n\tMessage string\n\tLevel ErrorLevel\n}\n\nfunc (l LogRecord) String() string {\n\tvar levelStr string\n\tswitch l.Level {\n\tcase Error:\n\t\tlevelStr = \"ERROR\"\n\tcase Info:\n\t\tlevelStr = \"INFO\"\n\tcase Warn:\n\t\tlevelStr = \"WARN\"\n\tcase Debug:\n\t\tlevelStr = \"DEBUG\"\n\t}\n\n\treturn fmt.Sprintf(\"[%s][bot] %s\", levelStr, l.Message)\n}\n\n\n\nvar Log = func(record LogRecord) {}\n\n\n\nfunc log(level ErrorLevel, msg string) ", "output": "{\n\tLog(LogRecord{Level: level, Message: msg})\n}"} {"input": "package controller\n\nimport (\n\t\"github.com/tmacychen/UFG/framework\"\n\t\"github.com/tmacychen/UFG/framework/outer\"\n)\n\ntype AttachableOuter interface {\n\touter.Relayouter\n}\n\ntype Attachable struct {\n\touter AttachableOuter\n\tonAttach framework.Event\n\tonDetach framework.Event\n\tattached bool\n}\n\nfunc (a *Attachable) Init(outer AttachableOuter) {\n\ta.outer = outer\n}\n\nfunc (a *Attachable) Attached() bool {\n\treturn a.attached\n}\n\nfunc (a *Attachable) Attach() {\n\tif a.attached {\n\t\tpanic(\"Control already attached\")\n\t}\n\ta.attached = true\n\tif a.onAttach != nil {\n\t\ta.onAttach.Fire()\n\t}\n}\n\n\n\nfunc (a *Attachable) OnAttach(f func()) framework.EventSubscription {\n\tif a.onAttach == nil {\n\t\ta.onAttach = CreateEvent(func() {})\n\t}\n\treturn a.onAttach.Listen(f)\n}\n\nfunc (a *Attachable) OnDetach(f func()) framework.EventSubscription {\n\tif a.onDetach == nil {\n\t\ta.onDetach = CreateEvent(func() {})\n\t}\n\treturn a.onDetach.Listen(f)\n}\n\nfunc (a *Attachable) Detach() ", "output": "{\n\tif !a.attached {\n\t\tpanic(\"Control already detached\")\n\t}\n\ta.attached = false\n\tif a.onDetach != nil {\n\t\ta.onDetach.Fire()\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\n\t\"k8s.io/client-go/util/homedir\"\n)\n\n\nfunc SanitizeString(s string) string {\n\tvar out bytes.Buffer\n\tallowed := \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-\"\n\tfor _, c := range s {\n\t\tif strings.IndexRune(allowed, c) != -1 {\n\t\t\tout.WriteRune(c)\n\t\t} else {\n\t\t\tout.WriteRune('_')\n\t\t}\n\t}\n\n\treturn string(out.Bytes())\n}\n\n\n\n\nfunc ExpandPath(p string) string ", "output": "{\n\tif strings.HasPrefix(p, \"~/\") {\n\t\tp = homedir.HomeDir() + p[1:]\n\t}\n\n\treturn p\n}"} {"input": "package repl\n\n\n\n\nfunc (shell *Shell) Create(args []string) (string, error) ", "output": "{\n\tif !shell.IsConnected() {\n\t\treturn \"\", ErrNotConnected\n\t}\n\treturn \"\", nil\n}"} {"input": "package expr\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\n\t\"github.com/google/nftables/binaryutil\"\n\t\"github.com/mdlayher/netlink\"\n\t\"golang.org/x/sys/unix\"\n)\n\n\ntype Numgen struct {\n\tRegister uint32\n\tModulus uint32\n\tType uint32\n\tOffset uint32\n}\n\nfunc (e *Numgen) marshal() ([]byte, error) {\n\tswitch e.Type {\n\tcase unix.NFT_NG_INCREMENTAL:\n\tcase unix.NFT_NG_RANDOM:\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported numgen type %d\", e.Type)\n\t}\n\n\tdata, err := netlink.MarshalAttributes([]netlink.Attribute{\n\t\t{Type: unix.NFTA_NG_DREG, Data: binaryutil.BigEndian.PutUint32(e.Register)},\n\t\t{Type: unix.NFTA_NG_MODULUS, Data: binaryutil.BigEndian.PutUint32(e.Modulus)},\n\t\t{Type: unix.NFTA_NG_TYPE, Data: binaryutil.BigEndian.PutUint32(e.Type)},\n\t\t{Type: unix.NFTA_NG_OFFSET, Data: binaryutil.BigEndian.PutUint32(e.Offset)},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn netlink.MarshalAttributes([]netlink.Attribute{\n\t\t{Type: unix.NFTA_EXPR_NAME, Data: []byte(\"numgen\\x00\")},\n\t\t{Type: unix.NLA_F_NESTED | unix.NFTA_EXPR_DATA, Data: data},\n\t})\n}\n\n\n\nfunc (e *Numgen) unmarshal(data []byte) error ", "output": "{\n\tad, err := netlink.NewAttributeDecoder(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tad.ByteOrder = binary.BigEndian\n\tfor ad.Next() {\n\t\tswitch ad.Type() {\n\t\tcase unix.NFTA_NG_DREG:\n\t\t\te.Register = ad.Uint32()\n\t\tcase unix.NFTA_NG_MODULUS:\n\t\t\te.Modulus = ad.Uint32()\n\t\tcase unix.NFTA_NG_TYPE:\n\t\t\te.Type = ad.Uint32()\n\t\tcase unix.NFTA_NG_OFFSET:\n\t\t\te.Offset = ad.Uint32()\n\t\t}\n\t}\n\treturn ad.Err()\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetCrossConnectRequest struct {\n\n\tCrossConnectId *string `mandatory:\"true\" contributesTo:\"path\" name:\"crossConnectId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetCrossConnectRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request GetCrossConnectRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request GetCrossConnectRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetCrossConnectRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetCrossConnectResponse struct {\n\n\tRawResponse *http.Response\n\n\tCrossConnect `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetCrossConnectResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response GetCrossConnectResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package u32\n\nimport \"sort\"\n\n\ntype Count struct {\n\tNum uint32\n\tSum uint8\n}\n\n\ntype SetCount map[uint32]*Count\n\n\n\n\n\nfunc (m SetCount) Count(removeSets ...*Set) []Count {\n\tret := make([]Count, 0)\n\tset := NewSet()\n\tset.Union(removeSets...)\n\tfor _, v := range m {\n\t\tif !set.Has(v.Num) {\n\t\t\tret = append(ret, *v)\n\t\t}\n\t}\n\tsort.Slice(ret, func(i, j int) bool {\n\t\tif ret[i].Sum == ret[j].Sum {\n\t\t\treturn ret[i].Num < ret[j].Num\n\t\t}\n\t\treturn ret[j].Sum < ret[i].Sum\n\t})\n\treturn ret\n}\n\nfunc (m SetCount) Add(sets ...*Set) ", "output": "{\n\tfor _, set := range sets {\n\t\tfor k := range *set {\n\t\t\tif mv, ok := m[k]; ok {\n\t\t\t\tmv.Sum++\n\t\t\t} else {\n\t\t\t\tm[k] = &Count{Num: k, Sum: 1}\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package controller\n\nimport (\n\t\"github.com/tmacychen/UFG/framework\"\n\t\"github.com/tmacychen/UFG/framework/outer\"\n)\n\ntype AttachableOuter interface {\n\touter.Relayouter\n}\n\ntype Attachable struct {\n\touter AttachableOuter\n\tonAttach framework.Event\n\tonDetach framework.Event\n\tattached bool\n}\n\nfunc (a *Attachable) Init(outer AttachableOuter) {\n\ta.outer = outer\n}\n\nfunc (a *Attachable) Attached() bool {\n\treturn a.attached\n}\n\nfunc (a *Attachable) Attach() {\n\tif a.attached {\n\t\tpanic(\"Control already attached\")\n\t}\n\ta.attached = true\n\tif a.onAttach != nil {\n\t\ta.onAttach.Fire()\n\t}\n}\n\nfunc (a *Attachable) Detach() {\n\tif !a.attached {\n\t\tpanic(\"Control already detached\")\n\t}\n\ta.attached = false\n\tif a.onDetach != nil {\n\t\ta.onDetach.Fire()\n\t}\n}\n\n\n\nfunc (a *Attachable) OnDetach(f func()) framework.EventSubscription {\n\tif a.onDetach == nil {\n\t\ta.onDetach = CreateEvent(func() {})\n\t}\n\treturn a.onDetach.Listen(f)\n}\n\nfunc (a *Attachable) OnAttach(f func()) framework.EventSubscription ", "output": "{\n\tif a.onAttach == nil {\n\t\ta.onAttach = CreateEvent(func() {})\n\t}\n\treturn a.onAttach.Listen(f)\n}"} {"input": "package uadmin\n\n\n\nimport (\n\t\"github.com/kormat/go-slackapi/config\"\n\t\"github.com/kormat/go-slackapi/query\"\n)\n\n\n\nfunc Invite(email string) error ", "output": "{\n\t_, err := query.Request(\"users.admin.invite\",\n\t\tconfig.MakeURLValues(map[string]string{\"email\": email}))\n\treturn err\n}"} {"input": "package machinery_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/RichardKnop/machinery/v2\"\n)\n\nfunc TestRedactURL(t *testing.T) {\n\tt.Parallel()\n\n\tbroker := \"amqp://guest:guest@localhost:5672\"\n\tredactedURL := machinery.RedactURL(broker)\n\tassert.Equal(t, \"amqp://localhost:5672\", redactedURL)\n}\n\n\n\nfunc SamplePreConsumeHandler(w *machinery.Worker) bool {\n\treturn true\n}\n\nfunc TestPreConsumeHandler(t *testing.T) ", "output": "{\n\tt.Parallel()\n\tworker := &machinery.Worker{}\n\n\tworker.SetPreConsumeHandler(SamplePreConsumeHandler)\n\tassert.True(t, worker.PreConsumeHandler())\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\nconst (\n\tFileType_File = 1\n\tFileType_Directory = 2\n)\n\n\n\nfunc IfInt(condition bool, trueVal, falseVal int) int {\n\tif condition {\n\t\treturn trueVal\n\t}\n\treturn falseVal\n}\n\n\nfunc ExpandString(s string, data map[string]string) string {\n\treturn os.Expand(s, func(p string) string {\n\t\tv, _ := data[p]\n\t\treturn v\n\t})\n}\n\n\nfunc CreateDir(dir string, mode os.FileMode) error {\n\t_, err := os.Stat(dir)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn os.MkdirAll(dir, mode)\n\t\t}\n\t}\n\treturn err\n}\n\nfunc CopyFile(src, dest string, mode os.FileMode) error {\n\tdata, err := ioutil.ReadFile(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(dest, data, mode)\n}\n\n\nfunc GetFileType(path string) (fileType int, err error) {\n\tvar fi os.FileInfo\n\n\tfi, err = os.Stat(path)\n\tif err == nil {\n\t\tfileType = IfInt(fi.IsDir(), FileType_Directory, FileType_File)\n\t} else if os.IsNotExist(err) {\n\t\terr = fmt.Errorf(\"can not find directory or file: %s\", path)\n\t}\n\treturn\n}\n\nfunc IfString(condition bool, trueVal, falseVal string) string ", "output": "{\n\tif condition {\n\t\treturn trueVal\n\t}\n\treturn falseVal\n}"} {"input": "package fuzzy\n\nimport \"testing\"\n\nvar levenshteinDistanceTests = []struct {\n\ts, t string\n\twanted int\n}{\n\t{\"a\", \"a\", 0},\n\t{\"ab\", \"ab\", 0},\n\t{\"ab\", \"aa\", 1},\n\t{\"ab\", \"aa\", 1},\n\t{\"ab\", \"aaa\", 2},\n\t{\"bbb\", \"a\", 3},\n\t{\"kitten\", \"sitting\", 3},\n\t{\"ёлка\", \"ёлочка\", 2},\n\t{\"ветер\", \"ёлочка\", 6},\n\t{\"中国\", \"中华人民共和国\", 5},\n\t{\"日本\", \"中华人民共和国\", 7},\n}\n\n\n\nfunc BenchmarkLevenshteinDistance(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tLevenshteinDistance(\"aaa\", \"aba\")\n\t\tLevenshteinDistance(\"kitten\", \"sitting\")\n\t}\n}\n\nfunc TestLevenshtein(t *testing.T) ", "output": "{\n\tfor _, test := range levenshteinDistanceTests {\n\t\tdistance := LevenshteinDistance(test.s, test.t)\n\t\tif distance != test.wanted {\n\t\t\tt.Errorf(\"got distance %d, expected %d for %s in %s\", distance, test.wanted, test.s, test.t)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\n\n\nfunc main() {\n\thttp.HandleFunc(\"/\", index)\n\tfmt.Println(\"Server starting\")\n\thttp.ListenAndServe(\":3000\", nil)\n}\n\nfunc index(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tfmt.Fprintf(w, \"Hello world\\n\")\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"google.golang.org/appengine\"\n\t\"google.golang.org/appengine/urlfetch\"\n\n\t\"github.com/PuerkitoBio/goquery\"\n)\n\n\n\nfunc scrape(r *http.Request, uri string) (*goquery.Document, error) ", "output": "{\n\tctx := appengine.NewContext(r)\n\tclient := urlfetch.Client(ctx)\n\n\tresp, err := client.Get(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn goquery.NewDocumentFromResponse(resp)\n}"} {"input": "package block\n\nimport (\n\t\"github.com/juju/cmd\"\n\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/cmd/envcmd\"\n)\n\nvar (\n\tBlockClient = &getBlockClientAPI\n\tUnblockClient = &getUnblockClientAPI\n\tListClient = &getBlockListAPI\n\n\tNewDestroyCommand = newDestroyCommand\n\tNewRemoveCommand = newRemoveCommand\n\tNewChangeCommand = newChangeCommand\n\tNewListCommand = newListCommand\n)\n\ntype MockBlockClient struct {\n\tBlockType string\n\tMsg string\n}\n\nfunc (c *MockBlockClient) Close() error {\n\treturn nil\n}\n\nfunc (c *MockBlockClient) SwitchBlockOn(blockType, msg string) error {\n\tc.BlockType = blockType\n\tc.Msg = msg\n\treturn nil\n}\n\nfunc (c *MockBlockClient) SwitchBlockOff(blockType string) error {\n\tc.BlockType = blockType\n\tc.Msg = \"\"\n\treturn nil\n}\n\nfunc (c *MockBlockClient) List() ([]params.Block, error) {\n\tif c.BlockType == \"\" {\n\t\treturn []params.Block{}, nil\n\t}\n\n\treturn []params.Block{\n\t\tparams.Block{\n\t\t\tType: c.BlockType,\n\t\t\tMessage: c.Msg,\n\t\t},\n\t}, nil\n}\n\n\n\nfunc NewUnblockCommandWithClient(client UnblockClientAPI) cmd.Command ", "output": "{\n\treturn envcmd.Wrap(&unblockCommand{client: client})\n}"} {"input": "package u32\n\nimport \"sort\"\n\n\ntype Count struct {\n\tNum uint32\n\tSum uint8\n}\n\n\ntype SetCount map[uint32]*Count\n\n\nfunc (m SetCount) Add(sets ...*Set) {\n\tfor _, set := range sets {\n\t\tfor k := range *set {\n\t\t\tif mv, ok := m[k]; ok {\n\t\t\t\tmv.Sum++\n\t\t\t} else {\n\t\t\t\tm[k] = &Count{Num: k, Sum: 1}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n\nfunc (m SetCount) Count(removeSets ...*Set) []Count ", "output": "{\n\tret := make([]Count, 0)\n\tset := NewSet()\n\tset.Union(removeSets...)\n\tfor _, v := range m {\n\t\tif !set.Has(v.Num) {\n\t\t\tret = append(ret, *v)\n\t\t}\n\t}\n\tsort.Slice(ret, func(i, j int) bool {\n\t\tif ret[i].Sum == ret[j].Sum {\n\t\t\treturn ret[i].Num < ret[j].Num\n\t\t}\n\t\treturn ret[j].Sum < ret[i].Sum\n\t})\n\treturn ret\n}"} {"input": "package se\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/kemokemo/kuronan-dash/assets/music\"\n)\n\n\n\nfunc TestPlayer(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tplayer *Player\n\t}{\n\t\t{\"Jump\", Jump},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.player == nil {\n\t\t\t\tt.Errorf(\"SE Player '%v' is nil, loading error\", tt.name)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMain(m *testing.M) ", "output": "{\n\terr := music.LoadAudioContext()\n\tif err != nil {\n\t\tfmt.Println(\"failed to LoadAudioContext:\", err)\n\t\treturn\n\t}\n\n\terr = LoadSE()\n\tif err != nil {\n\t\tfmt.Println(\"failed to LoadSE:\", err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\te := CloseSE()\n\t\tfmt.Println(\"failed to CloseSE:\", e)\n\t}()\n\n\tos.Exit(m.Run())\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/tompscanlan/labreserved/models\"\n)\n\n\n\nfunc NewPostItemParams() *PostItemParams {\n\tvar ()\n\treturn &PostItemParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\n\n\n\ntype PostItemParams struct {\n\n\tAdditem *models.Item\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *PostItemParams) WithAdditem(Additem *models.Item) *PostItemParams {\n\to.Additem = Additem\n\treturn o\n}\n\n\nfunc (o *PostItemParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif o.Additem == nil {\n\t\to.Additem = new(models.Item)\n\t}\n\n\tif err := r.SetBodyParam(o.Additem); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewPostItemParamsWithTimeout(timeout time.Duration) *PostItemParams ", "output": "{\n\tvar ()\n\treturn &PostItemParams{\n\n\t\ttimeout: timeout,\n\t}\n}"} {"input": "package probe_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/minio/mc/pkg/probe\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype MySuite struct{}\n\nvar _ = Suite(&MySuite{})\n\nfunc testDummy0() *probe.Error {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\treturn probe.NewError(e)\n}\n\nfunc testDummy1() *probe.Error {\n\treturn testDummy0().Trace(\"DummyTag1\")\n}\n\nfunc testDummy2() *probe.Error {\n\treturn testDummy1().Trace(\"DummyTag2\")\n}\n\n\n\nfunc (s *MySuite) TestWrappedError(c *C) {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\tes := probe.NewError(e) \n\te = probe.WrapError(es) \n\t_, ok := probe.UnwrapError(e)\n\tc.Assert(ok, Equals, true)\n}\n\nfunc (s *MySuite) TestProbe(c *C) ", "output": "{\n\tprobe.Init() \n\tprobe.SetAppInfo(\"Commit-ID\", \"7390cc957239\")\n\tes := testDummy2().Trace(\"TopOfStack\")\n\tc.Assert(es, Not(Equals), nil)\n\n\tnewES := es.Trace()\n\tc.Assert(newES, Not(Equals), nil)\n}"} {"input": "package runtime\n\nimport \"unsafe\"\n\n\n\n\n\n\n\n\n\nfunc atomicloadp(ptr unsafe.Pointer) unsafe.Pointer {\n\tnop()\n\treturn *(*unsafe.Pointer)(ptr)\n}\n\n\nfunc xadd64(ptr *uint64, delta int64) uint64 {\n\tfor {\n\t\told := *ptr\n\t\tif cas64(ptr, old, old+uint64(delta)) {\n\t\t\treturn old + uint64(delta)\n\t\t}\n\t}\n}\n\n\nfunc xchg64(ptr *uint64, new uint64) uint64 {\n\tfor {\n\t\told := *ptr\n\t\tif cas64(ptr, old, new) {\n\t\t\treturn old\n\t\t}\n\t}\n}\n\n\nfunc xadd(ptr *uint32, delta int32) uint32\n\n\nfunc xchg(ptr *uint32, new uint32) uint32\n\n\nfunc xchgp1(ptr unsafe.Pointer, new unsafe.Pointer) unsafe.Pointer\n\n\nfunc xchguintptr(ptr *uintptr, new uintptr) uintptr\n\n\nfunc atomicload64(ptr *uint64) uint64\n\n\nfunc atomicor8(ptr *uint8, val uint8)\n\n\nfunc cas64(ptr *uint64, old, new uint64) bool\n\n\nfunc atomicstore(ptr *uint32, val uint32)\n\n\nfunc atomicstore64(ptr *uint64, val uint64)\n\n\nfunc atomicstorep1(ptr unsafe.Pointer, val unsafe.Pointer)\n\nfunc atomicload(ptr *uint32) uint32 ", "output": "{\n\tnop()\n\treturn *ptr\n}"} {"input": "package libvirt\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n)\n\n\nimport \"C\"\n\ntype NetworkEventLifecycle struct {\n\tEvent NetworkEventLifecycleType\n\tDetail int\n}\n\ntype NetworkEventLifecycleCallback func(c *Connect, n *Network, event *NetworkEventLifecycle)\n\n\nfunc networkEventLifecycleCallback(c C.virConnectPtr, n C.virNetworkPtr,\n\tevent int, detail int,\n\tgoCallbackId int) {\n\n\tnetwork := &Network{ptr: n}\n\tconnection := &Connect{ptr: c}\n\n\teventDetails := &NetworkEventLifecycle{\n\t\tEvent: NetworkEventLifecycleType(event),\n\t\tDetail: detail,\n\t}\n\n\tcallbackFunc := getCallbackId(goCallbackId)\n\tcallback, ok := callbackFunc.(NetworkEventLifecycleCallback)\n\tif !ok {\n\t\tpanic(\"Inappropriate callback type called\")\n\t}\n\tcallback(connection, network, eventDetails)\n}\n\n\n\nfunc (c *Connect) NetworkEventDeregister(callbackId int) error {\n\tif C.LIBVIR_VERSION_NUMBER < 1002001 {\n\t\treturn GetNotImplementedError(\"virConnectNetworkEventDeregisterAny\")\n\t}\n\tif i := int(C.virConnectNetworkEventDeregisterAnyCompat(c.ptr, C.int(callbackId))); i != 0 {\n\t\treturn GetLastError()\n\t}\n\treturn nil\n}\n\nfunc (e NetworkEventLifecycle) String() string {\n\tvar event string\n\tswitch e.Event {\n\tcase NETWORK_EVENT_DEFINED:\n\t\tevent = \"defined\"\n\n\tcase NETWORK_EVENT_UNDEFINED:\n\t\tevent = \"undefined\"\n\n\tcase NETWORK_EVENT_STARTED:\n\t\tevent = \"started\"\n\n\tcase NETWORK_EVENT_STOPPED:\n\t\tevent = \"stopped\"\n\n\tdefault:\n\t\tevent = \"unknown\"\n\t}\n\n\treturn fmt.Sprintf(\"Network event=%q\", event)\n}\n\nfunc (c *Connect) NetworkEventLifecycleRegister(net *Network, callback NetworkEventLifecycleCallback) (int, error) ", "output": "{\n\tgoCallBackId := registerCallbackId(callback)\n\tif C.LIBVIR_VERSION_NUMBER < 1002001 {\n\t\treturn 0, GetNotImplementedError(\"virConnectNetworkEventRegisterAny\")\n\t}\n\n\tcallbackPtr := unsafe.Pointer(C.networkEventLifecycleCallback_cgo)\n\tvar cnet C.virNetworkPtr\n\tif net != nil {\n\t\tcnet = net.ptr\n\t}\n\tret := C.virConnectNetworkEventRegisterAny_cgo(c.ptr, cnet,\n\t\tC.VIR_NETWORK_EVENT_ID_LIFECYCLE,\n\t\tC.virConnectNetworkEventGenericCallback(callbackPtr),\n\t\tC.long(goCallBackId))\n\tif ret == -1 {\n\t\tfreeCallbackId(goCallBackId)\n\t\treturn 0, GetLastError()\n\t}\n\treturn int(ret), nil\n}"} {"input": "package proxy\n\nimport (\n\t\"store\"\n\t\"utils\"\n)\n\nconst (\n\tEFFICIENT_POOL_KEY = \"EfficientPoolKey\"\n)\n\nvar (\n\tefficientPool = InitEfficientPool()\n)\n\ntype EfficientPool struct {\n\tBasePool\n\tStorage store.SetStringStorer\n}\n\nfunc InitEfficientPool() *EfficientPool {\n\treturn &EfficientPool{BasePool: *InitBasePool(), Storage: store.RedisSet{}}\n}\n\nfunc (pool *EfficientPool) Add(proxy string) {\n\tpool.Storage.Add(EFFICIENT_POOL_KEY, proxy)\n}\n\nfunc (pool *EfficientPool) Remove(proxy string) {\n\tpool.Storage.Remove(EFFICIENT_POOL_KEY, proxy)\n}\n\nfunc Rand() (ok bool, proxy string) {\n\treturn efficientPool.Storage.Rand(EFFICIENT_POOL_KEY)\n}\n\n\n\nfunc Feedback(proxy string, ok bool, time int) ", "output": "{\n\tstablePool.Add(proxy, utils.EscapeToTime(ok, time))\n\n\tif !ok {\n\t\tefficientPool.Remove(proxy)\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n)\n\nconst (\n\tdeviceAliasDir = \"/run/ignition/dev_aliases\"\n\tretrySymlinkDelay = 10 * time.Millisecond\n\tretrySymlinkTimeout = 30 * time.Second\n\tretrySymlinkCount = int(retrySymlinkTimeout / retrySymlinkDelay)\n)\n\n\n\n\n\n\nfunc evalSymlinks(path string) (res string, err error) {\n\tfor i := 0; i < retrySymlinkCount; i++ {\n\t\tres, err = filepath.EvalSymlinks(path)\n\t\tif err == nil {\n\t\t\treturn res, nil\n\t\t} else if os.IsNotExist(err) {\n\t\t\ttime.Sleep(retrySymlinkDelay)\n\t\t} else {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"Failed to evaluate symlink after %v: %v\", retrySymlinkTimeout, err)\n}\n\n\n\nfunc CreateDeviceAlias(path string) (string, error) {\n\ttarget, err := evalSymlinks(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\talias := DeviceAlias(path)\n\n\tif err := os.Remove(alias); err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif err = os.MkdirAll(filepath.Dir(alias), 0750); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tif err = os.Symlink(target, alias); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn target, nil\n}\n\nfunc DeviceAlias(path string) string ", "output": "{\n\treturn filepath.Join(deviceAliasDir, filepath.Clean(path))\n}"} {"input": "package iso20022\n\n\ntype ConfirmationRejectedStatus1 struct {\n\n\tReason *RejectedConfirmationStatusReason1Code `xml:\"Rsn\"`\n\n\tExtendedReason *Extended350Code `xml:\"XtndedRsn\"`\n\n\tDataSourceScheme *GenericIdentification1 `xml:\"DataSrcSchme\"`\n}\n\n\n\nfunc (c *ConfirmationRejectedStatus1) SetExtendedReason(value string) {\n\tc.ExtendedReason = (*Extended350Code)(&value)\n}\n\nfunc (c *ConfirmationRejectedStatus1) AddDataSourceScheme() *GenericIdentification1 {\n\tc.DataSourceScheme = new(GenericIdentification1)\n\treturn c.DataSourceScheme\n}\n\nfunc (c *ConfirmationRejectedStatus1) SetReason(value string) ", "output": "{\n\tc.Reason = (*RejectedConfirmationStatusReason1Code)(&value)\n}"} {"input": "package text\n\nimport \"fmt\"\n\nconst (\n\tredCode = \"\\x1b[31m\"\n\tgreenCode = \"\\x1b[32m\"\n\tyellowCode = \"\\x1b[33m\"\n\tblueCode = \"\\x1b[34m\"\n\tmagentaCode = \"\\x1b[35m\"\n\tCyanCode = \"\\x1b[36m\"\n\tboldCode = \"\\x1b[1m\"\n\n\tResetCode = \"\\x1b[0m\"\n)\n\n\nvar UseColor = true\n\nfunc stylize(startCode, in string) string {\n\tif UseColor {\n\t\treturn startCode + in + ResetCode\n\t}\n\n\treturn in\n}\n\nfunc Red(in string) string {\n\treturn stylize(redCode, in)\n}\n\nfunc Green(in string) string {\n\treturn stylize(greenCode, in)\n}\n\nfunc yellow(in string) string {\n\treturn stylize(yellowCode, in)\n}\n\n\n\nfunc Magenta(in string) string {\n\treturn stylize(magentaCode, in)\n}\n\nfunc Blue(in string) string {\n\treturn stylize(blueCode, in)\n}\n\nfunc Bold(in string) string {\n\treturn stylize(boldCode, in)\n}\n\n\n\nfunc ColorHash(name string) (output string) {\n\tif !UseColor {\n\t\treturn name\n\t}\n\n\tvar hash uint = 5381\n\n\tfor i := 0; i < len(name); i++ {\n\t\thash = uint(name[i]) + ((hash << 5) + (hash))\n\t}\n\n\treturn fmt.Sprintf(\"\\x1b[%dm%s\\x1b[0m\", hash%6+31, name)\n}\n\nfunc Cyan(in string) string ", "output": "{\n\treturn stylize(CyanCode, in)\n}"} {"input": "package cabf_br\n\n\n\nimport (\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/util\"\n)\n\ntype caAiaMissing struct{}\n\n\n\nfunc init() {\n\tlint.RegisterLint(&lint.Lint{\n\t\tName: \"e_sub_ca_aia_missing\",\n\t\tDescription: \"Subordinate CA Certificate: authorityInformationAccess MUST be present, with the exception of stapling.\",\n\t\tCitation: \"BRs: 7.1.2.2\",\n\t\tSource: lint.CABFBaselineRequirements,\n\t\tEffectiveDate: util.CABEffectiveDate,\n\t\tIneffectiveDate: util.CABFBRs_1_7_1_Date,\n\t\tLint: NewCaAiaMissing,\n\t})\n}\n\n\n\nfunc (l *caAiaMissing) CheckApplies(c *x509.Certificate) bool {\n\treturn util.IsCACert(c) && !util.IsRootCA(c)\n}\n\nfunc (l *caAiaMissing) Execute(c *x509.Certificate) *lint.LintResult {\n\tif util.IsExtInCert(c, util.AiaOID) {\n\t\treturn &lint.LintResult{Status: lint.Pass}\n\t} else {\n\t\treturn &lint.LintResult{Status: lint.Error}\n\t}\n}\n\nfunc NewCaAiaMissing() lint.LintInterface ", "output": "{\n\treturn &caAiaMissing{}\n}"} {"input": "package geom\n\nimport (\n\t\"github.com/gmacd/rays/core\"\n)\n\n\n\n\ntype Light interface {\n\tIsLight() bool\n\tSetIsLight(isLight bool)\n\tLightCentre() core.Vec3\n}\n\ntype LightData struct {\n\tisLight bool\n\tpos core.Vec3\n}\n\nfunc NewLightData(pos core.Vec3) *LightData {\n\treturn &LightData{false, pos}\n}\n\nfunc NewLightDataNone() *LightData {\n\treturn &LightData{false, core.NewVec3Zero()}\n}\n\n\n\nfunc (light *LightData) SetIsLight(isLight bool) {\n\tlight.isLight = isLight\n}\n\nfunc (light *LightData) LightCentre() core.Vec3 {\n\treturn light.pos\n}\n\nfunc (light *LightData) IsLight() bool ", "output": "{\n\treturn light.isLight\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/posener/complete\"\n)\n\ntype ServerForceLeaveCommand struct {\n\tMeta\n}\n\nfunc (c *ServerForceLeaveCommand) Help() string {\n\thelpText := `\nUsage: nomad server force-leave [options] \n\n Forces an server to enter the \"left\" state. This can be used to\n eject nodes which have failed and will not rejoin the cluster.\n Note that if the member is actually still alive, it will\n eventually rejoin the cluster again.\n\n If ACLs are enabled, this option requires a token with the 'agent:write'\n capability.\n\nGeneral Options:\n\n ` + generalOptionsUsage(usageOptsDefault|usageOptsNoNamespace)\n\treturn strings.TrimSpace(helpText)\n}\n\nfunc (c *ServerForceLeaveCommand) Synopsis() string {\n\treturn \"Force a server into the 'left' state\"\n}\n\nfunc (c *ServerForceLeaveCommand) AutocompleteFlags() complete.Flags {\n\treturn c.Meta.AutocompleteFlags(FlagSetClient)\n}\n\nfunc (c *ServerForceLeaveCommand) AutocompleteArgs() complete.Predictor {\n\treturn complete.PredictNothing\n}\n\nfunc (c *ServerForceLeaveCommand) Name() string { return \"server force-leave\" }\n\n\n\nfunc (c *ServerForceLeaveCommand) Run(args []string) int ", "output": "{\n\tflags := c.Meta.FlagSet(c.Name(), FlagSetClient)\n\tflags.Usage = func() { c.Ui.Output(c.Help()) }\n\tif err := flags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\targs = flags.Args()\n\tif len(args) != 1 {\n\t\tc.Ui.Error(\"This command takes one argument: \")\n\t\tc.Ui.Error(commandErrorText(c))\n\t\treturn 1\n\t}\n\tnode := args[0]\n\n\tclient, err := c.Meta.Client()\n\tif err != nil {\n\t\tc.Ui.Error(fmt.Sprintf(\"Error initializing client: %s\", err))\n\t\treturn 1\n\t}\n\n\tif err := client.Agent().ForceLeave(node); err != nil {\n\t\tc.Ui.Error(fmt.Sprintf(\"Error force-leaving server %s: %s\", node, err))\n\t\treturn 1\n\t}\n\n\treturn 0\n}"} {"input": "package command\n\nimport (\n\t\"strings\"\n\n\t\"github.com/mitchellh/cli\"\n\t\"github.com/posener/complete\"\n)\n\nvar (\n\t_ cli.Command = (*PrintCommand)(nil)\n\t_ cli.CommandAutocomplete = (*PrintCommand)(nil)\n)\n\ntype PrintCommand struct {\n\t*BaseCommand\n}\n\n\n\nfunc (c *PrintCommand) Help() string {\n\thelpText := `\nUsage: vault print \n\n\tThis command groups subcommands for interacting with Vault's runtime values.\n\nSubcommands:\n\ttoken Token currently in use\n`\n\treturn strings.TrimSpace(helpText)\n}\n\nfunc (c *PrintCommand) AutocompleteArgs() complete.Predictor {\n\treturn nil\n}\n\nfunc (c *PrintCommand) AutocompleteFlags() complete.Flags {\n\treturn nil\n}\n\nfunc (c *PrintCommand) Run(args []string) int {\n\treturn cli.RunResultHelp\n}\n\nfunc (c *PrintCommand) Synopsis() string ", "output": "{\n\treturn \"Prints runtime configurations\"\n}"} {"input": "package blocks\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\tmh \"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash\"\n\tu \"github.com/ipfs/go-ipfs/util\"\n)\n\n\ntype Block struct {\n\tMultihash mh.Multihash\n\tData []byte\n}\n\n\nfunc NewBlock(data []byte) *Block {\n\treturn &Block{Data: data, Multihash: u.Hash(data)}\n}\n\n\n\n\n\n\n\nfunc (b *Block) Key() u.Key {\n\treturn u.Key(b.Multihash)\n}\n\nfunc (b *Block) String() string {\n\treturn fmt.Sprintf(\"[Block %s]\", b.Key())\n}\n\nfunc (b *Block) Loggable() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"block\": b.Key().String(),\n\t}\n}\n\nfunc NewBlockWithHash(data []byte, h mh.Multihash) (*Block, error) ", "output": "{\n\tif u.Debug {\n\t\tchk := u.Hash(data)\n\t\tif string(chk) != string(h) {\n\t\t\treturn nil, errors.New(\"Data did not match given hash!\")\n\t\t}\n\t}\n\treturn &Block{Data: data, Multihash: h}, nil\n}"} {"input": "package inputdockerlog\n\nimport (\n\t\"context\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"github.com/tsaikd/gogstash/config\"\n\t\"github.com/tsaikd/gogstash/config/goglog\"\n)\n\nfunc init() {\n\tgoglog.Logger.SetLevel(logrus.DebugLevel)\n\tconfig.RegistInputHandler(ModuleName, InitHandler)\n}\n\n\n\nfunc Test_input_dockerlog_module(t *testing.T) ", "output": "{\n\tassert := assert.New(t)\n\tassert.NotNil(assert)\n\trequire := require.New(t)\n\trequire.NotNil(require)\n\n\tctx := context.Background()\n\tconf, err := config.LoadFromYAML([]byte(strings.TrimSpace(`\ndebugch: true\ninput:\n - type: dockerlog\n dockerurl: \"unix:///var/run/docker.sock\"\n sincepath: \"sincedb-test\"\n\t`)))\n\trequire.NoError(err)\n\terr = conf.Start(ctx)\n\tif err != nil {\n\t\trequire.True(ErrorPingFailed.In(err))\n\t\tt.Skip(\"skip test input dockerlog module\")\n\t}\n\n\ttime.Sleep(500 * time.Millisecond)\n\tif event, err := conf.TestGetOutputEvent(100 * time.Millisecond); assert.NoError(err) {\n\t\tt.Log(event)\n\t}\n}"} {"input": "package oci\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/phoenix-io/phoenix-mon/plugins\"\n\tps \"github.com/shirou/gopsutil/process\"\n\t\"io/ioutil\"\n)\n\ntype OCI struct {\n\tprocess []plugin.Process\n\tcount\tint\n}\n\ntype PState struct {\n\tID string `json:\"id\"`\n\tPid int `json:\"init_process_pid\"`\n}\n\nfunc init() {\n\tplugin.Register(\"oci\", &plugin.RegisteredPlugin{New: NewPlugin})\n}\n\nfunc NewPlugin(pluginName string) (plugin.Plugin, error) {\n\treturn &OCI{}, nil\n}\n\nfunc (p *OCI) GetProcessList() ([]plugin.Process, error) {\n\n\tvar state PState\n\tcontainers, _ := ioutil.ReadDir(\"/run/oci/\")\n\tfor _, c := range containers {\n\t\tdata, err := ioutil.ReadFile(\"/run/oci/\" + c.Name() + \"/state.json\")\n\t\tif err != nil {\n\t\t\treturn p.process, fmt.Errorf(\"Error in reading file\")\n\t\t}\n\n\t\tjson.Unmarshal(data, &state)\n\t\tname := fmt.Sprintf(\"%s %d\",state.ID,p.count)\n\t\tp.count++\n\t\tp.process = append(p.process, plugin.Process{Pid: state.Pid, Name: name})\n\t}\n\n\treturn p.process, nil\n}\n\n\n\nfunc (p *OCI) GetProcessStat(process plugin.Process) (plugin.Process, error) ", "output": "{\n\tres, err := ps.NewProcess(int32(process.Pid))\n\tif err != nil {\n\t\tfmt.Println(\"Unable to Create Process Object\")\n\t}\n\tmemInfo, err := res.MemoryInfo()\n\tif err != nil {\n\t\treturn process, fmt.Errorf(\"geting ppid error %v\", err)\n\n\t}\n\tprocess.Memory = memInfo.RSS\n\treturn process, nil\n}"} {"input": "package gsh\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"gopkg.in/pipe.v2\"\n)\n\ntype HeadCmd struct {\n\tChars int\n\tLines int\n}\n\nfunc (cmd *HeadCmd) Flags() *flag.FlagSet {\n\tf := flag.NewFlagSet(cmd.Name(), flag.ExitOnError)\n\tf.IntVar(&cmd.Chars, \"c\", -1, \"Take first N characters\")\n\tf.IntVar(&cmd.Chars, \"n\", 10, \"Take first N lines\")\n\treturn f\n}\n\nfunc (cmd *HeadCmd) Name() string {\n\treturn \"head\"\n}\n\n\n\nfunc Head(argv ...string) pipe.Pipe {\n\tcmd := HeadCmd{}\n\treturn pipe.TaskFunc(func(s *pipe.State) error {\n\t\treturn cmd.Run(s, argv)\n\t})\n}\n\nfunc (cmd *HeadCmd) Run(s *pipe.State, argv []string) error ", "output": "{\n\tfs := cmd.Flags()\n\terr := fs.Parse(argv)\n\tif err != nil {\n\t\treturn err\n\t}\n\targs := fs.Args()\n\tif len(args) > 0 {\n\t\tfor _, fname := range args {\n\t\t\tfh, err := os.Open(fname)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%s 1: %s\", cmd.Name(), err)\n\t\t\t}\n\t\t\t_, err = io.Copy(s.Stdout, fh)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%s 2: %s\", cmd.Name(), err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\tif cmd.Chars >= 0 {\n\t\t_, err = io.CopyN(s.Stdout, s.Stdin, int64(cmd.Chars))\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: %s\", cmd.Name(), err)\n\t}\n\treturn nil\n}"} {"input": "package archive\n\nimport (\n\t\"archive/tar\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/docker/docker/pkg/longpath\"\n)\n\n\n\nfunc fixVolumePathPrefix(srcPath string) string {\n\treturn longpath.AddPrefix(srcPath)\n}\n\n\n\nfunc getWalkRoot(srcPath string, include string) string {\n\treturn filepath.Join(srcPath, include)\n}\n\n\n\n\nfunc CanonicalTarNameForPath(p string) (string, error) {\n\tif strings.Contains(p, \"/\") {\n\t\treturn \"\", fmt.Errorf(\"Windows path contains forward slash: %s\", p)\n\t}\n\treturn strings.Replace(p, string(os.PathSeparator), \"/\", -1), nil\n\n}\n\n\n\nfunc chmodTarEntry(perm os.FileMode) os.FileMode {\n\tperm &= 0755\n\tperm |= 0111\n\n\treturn perm\n}\n\nfunc setHeaderForSpecialDevice(hdr *tar.Header, ta *tarAppender, name string, stat interface{}) (nlink uint32, inode uint64, err error) {\n\treturn\n}\n\n\n\nfunc handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error {\n\treturn nil\n}\n\nfunc handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error {\n\treturn nil\n}\n\n\n\nfunc getFileUIDGID(stat interface{}) (int, int, error) ", "output": "{\n\treturn 0, 0, nil\n}"} {"input": "package controller\n\nimport (\n\tv1 \"k8s.io/api/core/v1\"\n\n\t\"istio.io/istio/pilot/pkg/model\"\n\t\"istio.io/istio/pilot/pkg/serviceregistry/kube\"\n\t\"istio.io/istio/pkg/config/labels\"\n)\n\n\ntype EndpointBuilder struct {\n\tcontroller *Controller\n\n\tlabels labels.Instance\n\tuid string\n\tserviceAccount string\n\tlocality model.Locality\n\ttlsMode string\n}\n\n\n\nfunc (b *EndpointBuilder) buildIstioEndpoint(\n\tendpointAddress string,\n\tendpointPort int32,\n\tsvcPortName string) *model.IstioEndpoint {\n\tif b == nil {\n\t\treturn nil\n\t}\n\n\treturn &model.IstioEndpoint{\n\t\tLabels: b.labels,\n\t\tUID: b.uid,\n\t\tServiceAccount: b.serviceAccount,\n\t\tLocality: b.locality,\n\t\tTLSMode: b.tlsMode,\n\t\tAddress: endpointAddress,\n\t\tEndpointPort: uint32(endpointPort),\n\t\tServicePortName: svcPortName,\n\t\tNetwork: b.controller.endpointNetwork(endpointAddress),\n\t}\n}\n\nfunc NewEndpointBuilder(c *Controller, pod *v1.Pod) *EndpointBuilder ", "output": "{\n\tlocality, sa, uid := \"\", \"\", \"\"\n\tvar podLabels labels.Instance\n\tif pod != nil {\n\t\tlocality = c.getPodLocality(pod)\n\t\tsa = kube.SecureNamingSAN(pod)\n\t\tuid = createUID(pod.Name, pod.Namespace)\n\t\tpodLabels = pod.Labels\n\t}\n\n\treturn &EndpointBuilder{\n\t\tcontroller: c,\n\t\tlabels: podLabels,\n\t\tuid: uid,\n\t\tserviceAccount: sa,\n\t\tlocality: model.Locality{\n\t\t\tLabel: locality,\n\t\t\tClusterID: c.clusterID,\n\t\t},\n\t\ttlsMode: kube.PodTLSMode(pod),\n\t}\n}"} {"input": "package utub\n\nimport (\n\t\"strings\"\n\n\t\"gopkg.in/olebedev/go-duktape.v2\"\n)\n\ntype duktapeJSEngine struct{}\n\nfunc (js duktapeJSEngine) Name() string {\n\treturn \"Duktape\"\n}\n\nfunc (js duktapeJSEngine) Available() bool {\n\treturn true\n}\n\n\n\nfunc (js duktapeJSEngine) sanitizeJSPlayerCode(code string) string {\n\tcode = strings.Replace(code, `(?=:|,|]|}|$)`, `(?=:|,|\\]|\\}|$)`, 1)\n\treturn code\n}\n\nfunc (js duktapeJSEngine) Exec(code string) (string, error) ", "output": "{\n\tctx := duktape.New()\n\tdefer ctx.DestroyHeap()\n\n\terr := ctx.PevalString(code)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn ctx.SafeToString(-1), nil\n}"} {"input": "package controllers\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/astaxie/beego\"\n\t\"github.com/scmo/apayment-backend/models\"\n\t\"github.com/scmo/apayment-backend/services\"\n\t\"time\"\n)\n\n\n\n\ntype JournalController struct {\n\tbeego.Controller\n}\n\nfunc (controller *JournalController) getUser() *models.User {\n\tclaims, err := services.ParseToken(controller.Ctx.Request.Header.Get(\"Authorization\"))\n\tif err != nil {\n\t\tcontroller.CustomAbort(401, \"Unauthorized\")\n\t}\n\tuser, err := services.GetUserByUsername(claims.Subject)\n\tif err != nil {\n\t\tcontroller.CustomAbort(404, err.Error())\n\t}\n\treturn user\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (this *JournalController) AddJournalEntry() {\n\tuser := this.getUser()\n\n\tvar journalEntry models.JournalEntry\n\tjson.Unmarshal(this.Ctx.Input.RequestBody, &journalEntry)\n\n\tjournalEntry.SetDate()\n\tservices.AddJournalEntry(&journalEntry)\n\n\tthis.Data[\"json\"] = user\n\tthis.ServeJSON()\n}\n\nfunc (this *JournalController) GetMonthlyStats() ", "output": "{\n\n\tuser := this.getUser()\n\n\tmonth, err := this.GetUint8(\"month\")\n\tif err != nil {\n\t\tthis.CustomAbort(400, \"Month not sent\")\n\t}\n\tyear, err := this.GetUint16(\"year\")\n\tif err != nil {\n\t\tthis.CustomAbort(400, \"Year not sent\")\n\t}\n\n\tif month < 1 || month > 12 || year < 1900 || year > uint16(time.Now().Year()) {\n\t\tthis.CustomAbort(400, \"Value not possible for one of the parameter. Year must be a 4 digit integer. Month parameter must be a interger between 1 and 31.\")\n\t}\n\n\tmonthlyStats, err := services.GetMonthlyStats(user.TVD, month, year)\n\tif err != nil {\n\t\tthis.CustomAbort(501, \"Internal Error \"+err.Error())\n\t}\n\tthis.Data[\"json\"] = monthlyStats\n\tthis.ServeJSON()\n}"} {"input": "package buildings\n\ntype store struct {\n\tbasicBuilding\n\timprovementLvl int8\n\tsales int\n\tprice int\n}\n\nfunc (*store) GetType() string { return \"store\" }\nfunc (b *store) GetRevenue() int { return b.sales * b.price }\nfunc (b *store) GetRent() int { return [4]int{1, 2, 3, 5}[b.improvementLvl] }\nfunc (b *store) GetInternalInt(name string) int {\n\tswitch name {\n\tcase \"improvementLvl\":\n\t\treturn int(b.improvementLvl)\n\tcase \"sales\":\n\t\treturn b.sales\n\tcase \"price\":\n\t\treturn b.price\n\tdefault:\n\t\treturn 0\n\t}\n}\n\nfunc (b *store) ToString(x, y int) string {\n\treturn \"store,\" + string(b.improvementLvl) + \",\" + string(b.sales) + \",\" + string(b.price) + \",\" + b.basicBuilding.ToString(x, y)\n}\n\nfunc (b *store) SetInternalInt(name string, val int) ", "output": "{\n\tswitch name {\n\tcase \"improvementLvl\":\n\t\tb.improvementLvl = int8(val)\n\tcase \"sales\":\n\t\tb.sales = val\n\tcase \"price\":\n\t\tb.price = val\n\t}\n}"} {"input": "package abi\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/ethereum/go-ethereum/crypto\"\n)\n\n\n\n\n\n\n\n\n\ntype Method struct {\n\tName string\n\tConst bool\n\tInputs []Argument\n\tOutputs []Argument\n}\n\nfunc (method Method) pack(args ...interface{}) ([]byte, error) {\n\tif len(args) != len(method.Inputs) {\n\t\treturn nil, fmt.Errorf(\"argument count mismatch: %d for %d\", len(args), len(method.Inputs))\n\t}\n\tvar variableInput []byte\n\n\tvar ret []byte\n\tfor i, a := range args {\n\t\tinput := method.Inputs[i]\n\t\tpacked, err := input.Type.pack(reflect.ValueOf(a))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"`%s` %v\", method.Name, err)\n\t\t}\n\n\t\tif input.Type.requiresLengthPrefix() {\n\t\t\toffset := len(method.Inputs)*32 + len(variableInput)\n\t\t\tret = append(ret, packNum(reflect.ValueOf(offset))...)\n\t\t\tvariableInput = append(variableInput, packed...)\n\t\t} else {\n\t\t\tret = append(ret, packed...)\n\t\t}\n\t}\n\tret = append(ret, variableInput...)\n\n\treturn ret, nil\n}\n\n\n\n\n\n\n\n\nfunc (m Method) Sig() string {\n\ttypes := make([]string, len(m.Inputs))\n\ti := 0\n\tfor _, input := range m.Inputs {\n\t\ttypes[i] = input.Type.String()\n\t\ti++\n\t}\n\treturn fmt.Sprintf(\"%v(%v)\", m.Name, strings.Join(types, \",\"))\n}\n\n\n\nfunc (m Method) Id() []byte {\n\treturn crypto.Keccak256([]byte(m.Sig()))[:4]\n}\n\nfunc (m Method) String() string ", "output": "{\n\tinputs := make([]string, len(m.Inputs))\n\tfor i, input := range m.Inputs {\n\t\tinputs[i] = fmt.Sprintf(\"%v %v\", input.Name, input.Type)\n\t}\n\toutputs := make([]string, len(m.Outputs))\n\tfor i, output := range m.Outputs {\n\t\tif len(output.Name) > 0 {\n\t\t\toutputs[i] = fmt.Sprintf(\"%v \", output.Name)\n\t\t}\n\t\toutputs[i] += output.Type.String()\n\t}\n\tconstant := \"\"\n\tif m.Const {\n\t\tconstant = \"constant \"\n\t}\n\treturn fmt.Sprintf(\"function %v(%v) %sreturns(%v)\", m.Name, strings.Join(inputs, \", \"), constant, strings.Join(outputs, \", \"))\n}"} {"input": "package cgosotest\n\n\nimport \"C\"\n\n\n\nfunc init() ", "output": "{\n\tif v := *C.getTLS(); v != 12345 {\n\t\tprintln(\"got\", v)\n\t\tpanic(\"BAD TLS value\")\n\t}\n}"} {"input": "package main\n\nimport (\n\tgd \"github.com/shadowapex/godot-go/gdnative\"\n\t\"github.com/shadowapex/godot-go/godot\"\n\t\"log\"\n\t\"math/rand\"\n)\n\n\nfunc NewMob() godot.Class {\n\tmob := &Mob{}\n\n\treturn mob\n}\n\n\ntype Mob struct {\n\tgodot.RigidBody2D\n\tMinSpeed gd.Real\n\tMaxSpeed gd.Real\n\tanimatedSprite godot.AnimatedSpriteImplementer\n}\n\n\n\n\nfunc (m *Mob) X_OnVisibilityScreenExited() {\n\tm.QueueFree()\n}\n\n\nfunc (m *Mob) X_Process(delta gd.Double) {\n}\n\nfunc (m *Mob) X_Ready() ", "output": "{\n\tlog.Println(\"X_Ready called!\")\n\n\tanimatedSpritePath := gd.NewNodePath(\"AnimatedSprite\")\n\tanimatedSpriteNode := m.GetNode(animatedSpritePath)\n\tm.animatedSprite = animatedSpriteNode.(godot.AnimatedSpriteImplementer)\n\n\tmobTypes := []gd.String{\"walk\", \"swim\", \"fly\"}\n\n\tm.animatedSprite.SetAnimation(mobTypes[rand.Int()%len(mobTypes)])\n}"} {"input": "package websocket\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/b00lduck/raspberry_soundboard/persistence\"\n)\n\ntype Hub struct {\n\tclients map[*Client]bool\n\tbroadcast chan bool\n\tregister chan *Client\n\tunregister chan *Client\n\tpersistence *persistence.Persistence\n}\n\nfunc NewHub(persistence *persistence.Persistence) *Hub {\n\treturn &Hub{\n\t\tbroadcast: make(chan bool),\n\t\tregister: make(chan *Client),\n\t\tunregister: make(chan *Client),\n\t\tclients: make(map[*Client]bool),\n\t\tpersistence: persistence,\n\t}\n}\n\n\n\nfunc (h *Hub) Run() {\n\tfor {\n\t\tselect {\n\t\tcase client := <-h.register:\n\t\t\tlog.Info(\"register client\")\n\t\t\th.clients[client] = true\n\t\t\tclient.send <- h.persistence.JsonState()\n\t\tcase client := <-h.unregister:\n\t\t\tif _, ok := h.clients[client]; ok {\n\t\t\t\tlog.Info(\"unregister client\")\n\t\t\t\tdelete(h.clients, client)\n\t\t\t\tclose(client.send)\n\t\t\t}\n\t\tcase <-h.broadcast:\n\t\t\tfor client := range h.clients {\n\t\t\t\tselect {\n\t\t\t\tcase client.send <- h.persistence.JsonState():\n\t\t\t\tdefault:\n\t\t\t\t\tclose(client.send)\n\t\t\t\t\tdelete(h.clients, client)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (h *Hub) Broadcast() ", "output": "{\n\th.broadcast <- true\n}"} {"input": "package io\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\n\n\nfunc Infof(format string, args ...interface{}) {\n\tfmt.Print(\"\\033[1m-----> \")\n\tfmt.Printf(format+\"\\033[0m\", args...)\n}\n\nfunc Print(args ...interface{}) {\n\tfmt.Print(\" \")\n\tfmt.Println(args...)\n}\n\nfunc Printf(format string, args ...interface{}) {\n\tfmt.Print(\" \")\n\tfmt.Printf(format, args...)\n}\n\nfunc Warnf(format string, args ...interface{}) {\n\tfmt.Print(\" ! \")\n\tfmt.Printf(format, args...)\n}\n\nfunc Error(args ...interface{}) {\n\tfmt.Print(\" ! \")\n\tfmt.Println(args...)\n\tos.Exit(1)\n}\n\nfunc Info(args ...interface{}) ", "output": "{\n\tfmt.Print(\"\\033[1m-----> \")\n\targs = append(args, \"\\033[0m\")\n\tfmt.Println(args...)\n}"} {"input": "package plugin\n\nimport \"strings\"\n\n\ntype YandexShare struct{}\n\n\n\n\n\nfunc (p *YandexShare) SetUp(settings map[string]string) (map[string]string, error) {\n\tif val, ok := settings[\"services\"]; ok {\n\t\tsettings[\"services\"] = strings.Replace(val, \" \", \",\", -1)\n\t}\n\n\treturn mergeSettings(settings, p.Defaults()), nil\n}\n\nfunc (p *YandexShare) Defaults() map[string]string ", "output": "{\n\treturn map[string]string{\"services\": \"facebook,twitter,gplus\", \"size\": \"m\", \"lang\": \"en\"}\n}"} {"input": "package spawn\n\nimport \"syscall\"\n\n\n\nfunc (s *Spawner) Alive() bool ", "output": "{\n\tif s.spawn == nil {\n\t\treturn false\n\t}\n\n\terr := s.spawn.Signal(syscall.Signal(0))\n\treturn err == nil\n}"} {"input": "package blocksutil\n\nimport \"gx/ipfs/Qmej7nf81hi2x2tvjRBF3mcp74sQyuDH4VMYDGd1YtXjb2/go-block-format\"\n\n\n\n\n\n\n\n\n\ntype BlockGenerator struct {\n\tseq int\n}\n\n\nfunc (bg *BlockGenerator) Next() *blocks.BasicBlock {\n\tbg.seq++\n\treturn blocks.NewBlock([]byte(string(bg.seq)))\n}\n\n\nfunc (bg *BlockGenerator) Blocks(n int) []blocks.Block {\n\tblocks := make([]blocks.Block, 0, n)\n\tfor i := 0; i < n; i++ {\n\t\tb := bg.Next()\n\t\tblocks = append(blocks, b)\n\t}\n\treturn blocks\n}\n\nfunc NewBlockGenerator() BlockGenerator ", "output": "{\n\treturn BlockGenerator{}\n}"} {"input": "package time\n\nimport (\n\t\"fmt\"\n\t\"github.com/iotaledger/iota.go/account/deposit\"\n\t\"github.com/iotaledger/iota.go/account/oracle\"\n\t\"github.com/iotaledger/iota.go/account/timesrc\"\n\t\"time\"\n)\n\nconst dateFormat = \"2006-02-01 15:04:05\"\n\n\n\n\nfunc NewTimeDecider(timesource timesrc.TimeSource, remainingTimeThreshold time.Duration) oracle.OracleSource {\n\treturn &timedecider{timesource, remainingTimeThreshold}\n}\n\ntype timedecider struct {\n\ttimesource timesrc.TimeSource\n\tremainingTimeThreshold time.Duration\n}\n\n\n\nfunc (td *timedecider) Ok(conds *deposit.CDA) (bool, string, error) ", "output": "{\n\tnow, err := td.timesource.Time()\n\tif err != nil {\n\t\treturn false, \"\", err\n\t}\n\n\tif now.After(*conds.TimeoutAt) {\n\t\tmsg := fmt.Sprintf(\"conditions expired on %s, it's currently %s\", conds.TimeoutAt.Format(dateFormat), now.Format(dateFormat))\n\t\treturn false, msg, nil\n\t}\n\n\tif now.Add(td.remainingTimeThreshold).After(*conds.TimeoutAt) {\n\t\tformatted := conds.TimeoutAt.Format(dateFormat)\n\t\tnowFormatted := now.Add(td.remainingTimeThreshold).Format(dateFormat)\n\t\tmsg := fmt.Sprintf(\"conditions will have expired before the remaining time threshold (%s < %s)\", formatted, nowFormatted)\n\t\treturn false, msg, nil\n\t}\n\treturn true, \"\", nil\n}"} {"input": "package parse\n\nimport (\n\t\"github.com/hfern/luao/lexer\"\n)\n\ntype readerState struct {\n\tread int\n}\n\ntype tReader struct {\n\tstate readerState\n\tsource *[]lexer.Token\n}\n\nfunc (r tReader) Save() readerState {\n\treturn r.state\n}\n\n\n\nfunc (r *tReader) Next() lexer.Token {\n\tif len(r.source) <= r.state.read {\n\t\treturn lexer.Token\n\t}\n}\n\nfunc (r *tReader) Restore(s readerState) ", "output": "{\n\tr.state = s\n}"} {"input": "package plugins\n\nimport (\n\t\"../answers\"\n\t\"../ircclient\"\n\t\"strings\"\n)\n\ntype DongPlugin struct {\n\tic *ircclient.IRCClient\n}\n\nfunc (q *DongPlugin) String() string {\n\treturn \"dong\"\n}\n\n\n\nfunc (q *DongPlugin) Usage(cmd string) string {\n\treturn \"\"\n}\n\nfunc (q *DongPlugin) Register(cl *ircclient.IRCClient) {\n\tq.ic = cl\n}\n\nfunc (q *DongPlugin) Unregister() {\n\treturn\n}\n\nfunc (q *DongPlugin) ProcessLine(msg *ircclient.IRCMessage) {\n\tif msg.Command != \"PRIVMSG\" {\n\t\treturn\n\t}\n\n\tcount := strings.Count(msg.Args[0], `\\a`)\n\tcount -= strings.Count(msg.Args[0], `\\\\a`)\n\tif count < 1 {\n\t\treturn\n\t}\n\n\tstr := answers.RandStr(\"dong\")\n\tmessage := \"\"\n\n\tfor i := 0; i < count; i++ {\n\t\tmessage += str + \" \"\n\t}\n\n\tq.ic.ReplyMsg(msg, message)\n}\n\nfunc (q *DongPlugin) ProcessCommand(cmd *ircclient.IRCCommand) {\n\treturn\n}\n\nfunc (q *DongPlugin) Info() string ", "output": "{\n\treturn `sends back a dong sound for every \\a`\n}"} {"input": "package slack\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net/url\"\n)\n\ntype emojiResponseFull struct {\n\tEmoji map[string]string `json:\"emoji\"`\n\tSlackResponse\n}\n\n\n\n\n\nfunc (api *Client) GetEmojiContext(ctx context.Context) (map[string]string, error) {\n\tvalues := url.Values{\n\t\t\"token\": {api.token},\n\t}\n\tresponse := &emojiResponseFull{}\n\n\terr := postSlackMethod(ctx, api.httpclient, \"emoji.list\", values, response, api.debug)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !response.Ok {\n\t\treturn nil, errors.New(response.Error)\n\t}\n\treturn response.Emoji, nil\n}\n\nfunc (api *Client) GetEmoji() (map[string]string, error) ", "output": "{\n\treturn api.GetEmojiContext(context.Background())\n}"} {"input": "package devices\n\n\n\ntype Device interface {\n\tBind(driver string) error\n\tUnbind() error\n\tCurrentDriver() (string, error)\n\tProbe() error\n\tID() string\n}\n\n\nfunc New(input string) (Device, error) {\n\tswitch {\n\tcase IsPciID.Match([]byte(input)):\n\t\treturn NewDeviceByPciID(input)\n\tcase IsUUID.Match([]byte(input)):\n\t\treturn NewDeviceByVmbusID(input)\n\tdefault:\n\t\treturn NewDeviceByNicName(input)\n\t}\n}\n\n\n\n\n\nfunc NewDeviceByVmbusID(uuid string) (Device, error) {\n\tdevice, err := GetVmbusDeviceByUUID(uuid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn device, nil\n}\n\n\nfunc NewDeviceByNicName(nicName string) (Device, error) {\n\tdevID, err := GetDeviceID(nicName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdevice, err := newDevice(devID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn device, nil\n}\n\nfunc newDevice(id string) (Device, error) {\n\tif IsPciID.Match([]byte(id)) {\n\t\treturn GetPciDeviceByPciID(id)\n\t}\n\treturn GetVmbusDeviceByUUID(id)\n}\n\nfunc NewDeviceByPciID(pciID string) (Device, error) ", "output": "{\n\tdevice, err := GetPciDeviceByPciID(pciID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn device, nil\n}"} {"input": "package ctl\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"github.com/pilosa/pilosa\"\n\t\"github.com/pilosa/pilosa/test\"\n)\n\n\n\nfunc TestBackupCommand_Run(t *testing.T) {\n\n\tbuf := bytes.Buffer{}\n\tstdin, stdout, stderr := GetIO(buf)\n\n\thldr := test.MustOpenHolder()\n\tdefer hldr.Close()\n\n\ts := test.NewServer()\n\tdefer s.Close()\n\turi, err := pilosa.NewURIFromAddress(s.Host())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ts.Handler.URI = uri\n\ts.Handler.Cluster = test.NewCluster(1)\n\ts.Handler.Cluster.Nodes[0].Host = s.Host()\n\ts.Handler.Holder = hldr.Holder\n\tcm := NewBackupCommand(stdin, stdout, stderr)\n\tfile, err := ioutil.TempFile(\"\", \"import.csv\")\n\n\tcm.Index = \"i\"\n\tcm.Host = s.Host()\n\tcm.Frame = \"f\"\n\tcm.View = pilosa.ViewStandard\n\tcm.Path = file.Name()\n\terr = cm.Run(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"Command not working, error: '%s'\", err)\n\t}\n}\n\nfunc TestBackupCommand_FileRequired(t *testing.T) ", "output": "{\n\tbuf := bytes.Buffer{}\n\tstdin, stdout, stderr := GetIO(buf)\n\n\tcm := NewBackupCommand(stdin, stdout, stderr)\n\terr := cm.Run(context.Background())\n\tif err.Error() != \"output file required\" {\n\t\tt.Fatalf(\"expect error: output file required, actual: %s\", err)\n\t}\n\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\nfunc TestGetStatus(t *testing.T) {\n\tif getStatus(500) != StatusError {\n\t\tt.Errorf(\"The expected status error for the code 500 is: %s\", StatusError)\n\t}\n\tif getStatus(400) != StatusFail {\n\t\tt.Errorf(\"The expected status error for the code 400 is: %s\", StatusFail)\n\t}\n\tif getStatus(200) != StatusSuccess {\n\t\tt.Errorf(\"The expected status error for the code 200 is: %s\", StatusSuccess)\n\t}\n}\n\n\n\nfunc BenchmarkGetStatus(b *testing.B) ", "output": "{\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tgetStatus(200)\n\t}\n}"} {"input": "package reaperlog\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/rifflock/lfshook\"\n\t\"go.mozilla.org/mozlogrus\"\n)\n\nvar config LogConfig\n\ntype LogConfig struct {\n\tExtras bool\n}\n\nfunc EnableExtras() {\n\tconfig.Extras = true\n}\n\nfunc EnableMozlog() {\n\tmozlogrus.Enable(\"Reaper\")\n}\n\nfunc Extras() bool {\n\treturn config.Extras\n}\n\nfunc SetConfig(c *LogConfig) {\n\tconfig = *c\n}\n\n\n\nfunc Debug(format string, args ...interface{}) {\n\tlog.Debugf(format, args...)\n}\n\nfunc Info(format string, args ...interface{}) {\n\tlog.Infof(format, args...)\n}\n\nfunc Warning(format string, args ...interface{}) {\n\tlog.Warningf(format, args...)\n}\n\nfunc Fatal(format string, args ...interface{}) {\n\tlog.Fatalf(format, args...)\n}\n\nfunc Panic(format string, args ...interface{}) {\n\tlog.Panicf(format, args...)\n}\n\nfunc Error(format string, args ...interface{}) {\n\tlog.Errorf(format, args...)\n}\n\nfunc AddLogFile(filename string) ", "output": "{\n\tlog.AddHook(lfshook.NewHook(lfshook.PathMap{\n\t\tlog.DebugLevel: filename,\n\t\tlog.InfoLevel: filename,\n\t\tlog.WarnLevel: filename,\n\t\tlog.ErrorLevel: filename,\n\t\tlog.FatalLevel: filename,\n\t\tlog.PanicLevel: filename,\n\t}))\n}"} {"input": "package ghalloc\n\nimport \"unsafe\"\n\ntype slab struct {\n\tslabClass *slabClass \n\tmemory []byte \n\tfull bool \n\tallocated uint64 \n\tchunkMap uint64 \n}\n\nfunc newSlab(sc *slabClass) *slab {\n\ts := &slab{\n\t\tslabClass: sc,\n\t\tmemory: make([]byte, sc.SlabSize),\n\t\tfull: false,\n\t\tallocated: 0,\n\t}\n\n\treturn s\n}\n\n\nfunc (s *slab) allocChunk() unsafe.Pointer {\n\tif s.full {\n\t\treturn nil\n\t}\n\n\ti := s.getUnusedChunkIndex()\n\tptr := unsafe.Pointer(&s.memory[s.getUnusedChunkIndex()])\n\n\ts.chunkMap |= 1 << i\n\ts.allocated++\n\n\tif s.allocated >= s.slabClass.Capacity {\n\t\ts.full = true\n\t}\n\n\treturn ptr\n}\n\n\n\n\nfunc (s *slab) getUnusedChunkIndex() uint64 {\n\tvar i uint64\n\n\tfor i = 0; i < s.slabClass.Capacity; i++ {\n\t\tif s.chunkMap&(1<= begin && uptr <= uintptr(unsafe.Pointer(&s.memory[0]))+uintptr(s.slabClass.SlabSize) {\n\t\ts.chunkMap &^= 1 << uint64(uptr-begin) % uint64(s.slabClass.SlabSize)\n\n\t\ts.allocated--\n\t\tif s.full {\n\t\t\ts.full = false\n\t\t}\n\t}\n}"} {"input": "package steam4go\n\nimport (\n\t\"encoding/json\"\n\t\"net/url\"\n\t\"strconv\"\n)\n\n\ntype Stats struct {\n\tAchievementPercentages struct {\n\t\tAchievements []struct {\n\t\t\tName string `json:\"name\"`\n\t\t\tPercent float64 `json:\"percent\"`\n\t\t} `json:\"achievements\"`\n\t} `json:\"achievementpercentages\"`\n}\n\n\n\n\nfunc GetGlobalAchievementPercentagesForApp(gameID float64) (data Stats) ", "output": "{\n\tu, _ := url.Parse(ifSteam)\n\tu.Path = \"/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/\"\n\tq := u.Query()\n\tq.Set(\"gameid\", strconv.FormatFloat(gameID, 'f', 2, 64))\n\tu.RawQuery = q.Encode()\n\tvar stats Stats\n\tjsonSrc := navigateToByte(u.String())\n\tjson.Unmarshal(jsonSrc, &stats)\n\treturn stats\n}"} {"input": "package main\n\nimport (\n\t\"database/sql\"\n\t\"log\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/codahale/hdrhistogram\"\n)\n\nconst (\n\tminLatency = 100 * time.Microsecond\n\tmaxLatency = 100 * time.Second\n)\n\n\nvar numOps uint64\n\ntype worker struct {\n\tdb *sql.DB\n\tlatency struct {\n\t\tsync.Mutex\n\t\t*hdrhistogram.WindowedHistogram\n\t}\n}\n\nfunc clampLatency(d, min, max time.Duration) time.Duration {\n\tif d < min {\n\t\treturn min\n\t}\n\tif d > max {\n\t\treturn max\n\t}\n\treturn d\n}\n\nfunc newWorker(db *sql.DB, wg *sync.WaitGroup) *worker {\n\twg.Add(1)\n\tw := &worker{db: db}\n\tw.latency.WindowedHistogram = hdrhistogram.NewWindowed(1,\n\t\tminLatency.Nanoseconds(), maxLatency.Nanoseconds(), 1)\n\n\treturn w\n}\n\n\n\nfunc (w *worker) run(wg *sync.WaitGroup) ", "output": "{\n\tfor {\n\t\tstart := time.Now()\n\n\n\t\tif _, err := w.db.Exec(*query); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\telapsed := clampLatency(time.Since(start), minLatency, maxLatency).Nanoseconds()\n\t\tw.latency.Lock()\n\t\tif err := w.latency.Current.RecordValue(elapsed); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tw.latency.Unlock()\n\n\t\tatomic.AddUint64(&numOps, 1)\n\t}\n}"} {"input": "package packages\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/limetext/lime-backend/lib/loaders\"\n\t\"github.com/limetext/lime-backend/lib/log\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\ntype (\n\tPacket struct {\n\t\tpath string\n\t\tmarshalTo json.Unmarshaler\n\t}\n\n\tPackets []*Packet\n)\n\n\nfunc NewPacket(path string, marshal json.Unmarshaler) *Packet {\n\treturn &Packet{path, marshal}\n}\n\nfunc (p *Packet) Name() string {\n\treturn p.path\n}\n\n\n\n\n\n\nfunc (p *Packet) FileChanged(name string) {\n\tp.Load()\n}\n\nfunc (p *Packet) Load() error {\n\treturn loaders.LoadJSON(p.Get().([]byte), p)\n}\n\nfunc (p *Packet) MarshalTo() json.Unmarshaler {\n\treturn p.marshalTo\n}\n\nfunc (p *Packet) UnmarshalJSON(data []byte) error {\n\treturn p.marshalTo.UnmarshalJSON(data)\n}\n\n\nfunc (p *Packet) group() string {\n\tfor _, key := range types {\n\t\tif strings.Contains(filepath.Ext(p.Name()), key) {\n\t\t\treturn key\n\t\t}\n\t}\n\treturn \"\"\n}\n\n\nfunc (p Packets) Filter(key string) Packets {\n\tvar pckts Packets\n\tfor _, pckt := range p {\n\t\tif strings.Contains(filepath.Ext(pckt.Name()), key) {\n\t\t\tpckts = append(pckts, pckt)\n\t\t}\n\t}\n\treturn pckts\n}\n\nfunc (p *Packet) Get() interface{} ", "output": "{\n\te := []byte(`{}`)\n\tif p.group() == \"keymap\" {\n\t\te = []byte(`[]`)\n\t}\n\n\tif _, err := os.Stat(p.path); os.IsNotExist(err) {\n\t\tlog.Finest(\"%s doesn't exist yet\", p.path)\n\t\treturn e\n\t}\n\n\td, err := ioutil.ReadFile(p.path)\n\tif err != nil {\n\t\tlog.Error(\"Couldn't read file: %s\", err)\n\t\treturn e\n\t}\n\treturn d\n}"} {"input": "package errors2\n\nimport (\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tlvldbug = iota\n\tlvlinfo\n\tlvlerr\n\tlvlcrit\n)\n\ntype logMessage struct {\n\ttime time.Time\n\tlevel int\n\tmessage string\n}\n\ntype Logger struct {\n\tmessages []*logMessage\n\tTimer Timer\n}\n\nfunc (l *Logger) Debug(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvldbug, message: message})\n}\n\nfunc (l *Logger) Info(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvlinfo, message: message})\n}\n\nfunc (l *Logger) Error(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvlerr, message: message})\n}\n\n\n\nvar lock = &sync.Mutex{}\n\nfunc (l *Logger) log(message *logMessage) {\n\tlock.Lock()\n\tl.messages = append(l.messages, message)\n\tlock.Unlock()\n}\n\nfunc (l *Logger) Critical(message string) ", "output": "{\n\tl.log(&logMessage{time: time.Now(), level: lvlcrit, message: message})\n}"} {"input": "package storm\n\nimport (\n\t\"github.com/asdine/storm/codec\"\n\t\"github.com/boltdb/bolt\"\n)\n\n\ntype Node interface {\n\tTx\n\tTypeStore\n\tKeyValueStore\n\tBucketScanner\n\tFrom(addend ...string) Node\n\n\tBucket() []string\n\n\tGetBucket(tx *bolt.Tx, children ...string) *bolt.Bucket\n\n\tCreateBucketIfNotExists(tx *bolt.Tx, bucket string) (*bolt.Bucket, error)\n\n\tWithTransaction(tx *bolt.Tx) Node\n\n\tBegin(writable bool) (Node, error)\n\n\tCodec() codec.EncodeDecoder\n}\n\n\ntype node struct {\n\ts *DB\n\n\trootBucket []string\n\n\ttx *bolt.Tx\n}\n\n\n\nfunc (n node) From(addend ...string) Node {\n\tn.rootBucket = append(n.rootBucket, addend...)\n\treturn &n\n}\n\n\n\n\n\n\nfunc (n *node) Bucket() []string {\n\treturn n.rootBucket\n}\n\n\nfunc (n *node) Codec() codec.EncodeDecoder {\n\treturn n.s.codec\n}\n\nfunc (n node) WithTransaction(tx *bolt.Tx) Node ", "output": "{\n\tn.tx = tx\n\treturn &n\n}"} {"input": "package canopus\n\nimport \"net\"\n\nfunc Dial(address string) (conn Connection, err error) {\n\tudpConn, err := net.Dial(\"udp\", address)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn = &UDPConnection{\n\t\tconn: udpConn,\n\t}\n\n\treturn\n}\n\nfunc DialDTLS(address, identity, psk string) (conn Connection, err error) {\n\tudpConn, err := net.Dial(\"udp\", address)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn, err = NewDTLSConnection(udpConn, identity, psk)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc NewObserveMessage(r string, val interface{}, msg Message) ObserveMessage {\n\treturn &CoapObserveMessage{\n\t\tResource: r,\n\t\tValue: val,\n\t\tMsg: msg,\n\t}\n}\n\ntype CoapObserveMessage struct {\n\tCoapMessage\n\tResource string\n\tValue interface{}\n\tMsg Message\n}\n\nfunc (m *CoapObserveMessage) GetResource() string {\n\treturn m.Resource\n}\n\n\n\nfunc (m *CoapObserveMessage) GetMessage() Message {\n\treturn m.GetMessage()\n}\n\nfunc (m *CoapObserveMessage) GetValue() interface{} ", "output": "{\n\treturn m.Value\n}"} {"input": "package of13\n\nimport (\n\t\"github.com/superkkt/cherry/cherryd/openflow\"\n)\n\nfunc NewEchoRequest(xid uint32) openflow.EchoRequest {\n\treturn &openflow.BaseEcho{\n\t\tMessage: openflow.NewMessage(openflow.OF13_VERSION, OFPT_ECHO_REQUEST, xid),\n\t}\n}\n\n\n\nfunc NewEchoReply(xid uint32) openflow.EchoReply ", "output": "{\n\treturn &openflow.BaseEcho{\n\t\tMessage: openflow.NewMessage(openflow.OF13_VERSION, OFPT_ECHO_REPLY, xid),\n\t}\n}"} {"input": "package http\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"go-common/library/ecode\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\n\nfunc relation(c *bm.Context) {\n\tvar (\n\t\terr error\n\t\tmid, fid int64\n\t\tparams = c.Request.Form\n\t\tmidStr = params.Get(\"mid\")\n\t\tfidStr = params.Get(\"fid\")\n\t)\n\tif mid, err = strconv.ParseInt(midStr, 10, 64); err != nil {\n\t\tc.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\tif fid, err = strconv.ParseInt(fidStr, 10, 64); err != nil {\n\t\tc.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\tc.JSON(relationSvc.Relation(c, mid, fid))\n}\n\n\n\n\nfunc relations(c *bm.Context) ", "output": "{\n\tvar (\n\t\terr error\n\t\tmid, fid int64\n\t\tfids []int64\n\t\tparams = c.Request.Form\n\t\tmidStr = params.Get(\"mid\")\n\t\tfidsStr = params.Get(\"fids\")\n\t)\n\tif mid, err = strconv.ParseInt(midStr, 10, 64); err != nil {\n\t\tc.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\tfidsStrArr := strings.Split(fidsStr, \",\")\n\tfor _, v := range fidsStrArr {\n\t\tif fid, err = strconv.ParseInt(v, 10, 64); err != nil {\n\t\t\tc.JSON(nil, ecode.RequestErr)\n\t\t\treturn\n\t\t}\n\t\tfids = append(fids, fid)\n\t}\n\tc.JSON(relationSvc.Relations(c, mid, fids))\n}"} {"input": "package avs\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) BaseClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package lib\n\nimport (\n\t\"github.com/cloudflare/cfssl/log\"\n\t\"github.com/hyperledger/fabric-ca/lib/common\"\n\t\"github.com/hyperledger/fabric-ca/lib/server/idemix\"\n\t\"github.com/hyperledger/fabric-ca/lib/spi\"\n)\n\nfunc newIdemixEnrollEndpoint(s *Server) *serverEndpoint {\n\treturn &serverEndpoint{\n\t\tMethods: []string{\"POST\"},\n\t\tHandler: handleIdemixEnrollReq,\n\t\tServer: s,\n\t\tsuccessRC: 201,\n\t}\n}\n\n\n\n\n\n\nfunc newIdemixEnrollmentResponseNet(resp *idemix.EnrollmentResponse) common.IdemixEnrollmentResponseNet {\n\treturn common.IdemixEnrollmentResponseNet{\n\t\tNonce: resp.Nonce,\n\t\tAttrs: resp.Attrs,\n\t\tCredential: resp.Credential,\n\t\tCRI: resp.CRI,\n\t\tCAInfo: common.CAInfoResponseNet{}}\n}\n\n\ntype idemixServerCtx struct {\n\tsrvCtx *serverRequestContextImpl\n}\n\nfunc (c *idemixServerCtx) IsBasicAuth() bool {\n\t_, _, isBasicAuth := c.srvCtx.req.BasicAuth()\n\treturn isBasicAuth\n}\nfunc (c *idemixServerCtx) BasicAuthentication() (string, error) {\n\treturn c.srvCtx.BasicAuthentication()\n}\nfunc (c *idemixServerCtx) TokenAuthentication() (string, error) {\n\treturn c.srvCtx.TokenAuthentication()\n}\nfunc (c *idemixServerCtx) GetCaller() (spi.User, error) {\n\treturn c.srvCtx.GetCaller()\n}\nfunc (c *idemixServerCtx) ReadBody(body interface{}) error {\n\treturn c.srvCtx.ReadBody(body)\n}\n\nfunc handleIdemixEnrollReq(ctx *serverRequestContextImpl) (interface{}, error) ", "output": "{\n\tca, err := ctx.GetCA()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tidemixEnrollResp, err := ca.issuer.IssueCredential(&idemixServerCtx{ctx})\n\tif err != nil {\n\t\tlog.Errorf(\"Error processing the /idemix/credential request: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\tresp := newIdemixEnrollmentResponseNet(idemixEnrollResp)\n\terr = ctx.ca.fillCAInfo(&resp.CAInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}"} {"input": "package models\n\nimport (\n\t\"testing\"\n\n\t\"code.gitea.io/gitea/models/db\"\n\trepo_model \"code.gitea.io/gitea/models/repo\"\n\t\"code.gitea.io/gitea/models/unittest\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc Test_newIssueUsers(t *testing.T) {\n\tassert.NoError(t, unittest.PrepareTestDatabase())\n\n\trepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)\n\tnewIssue := &Issue{\n\t\tRepoID: repo.ID,\n\t\tPosterID: 4,\n\t\tIndex: 6,\n\t\tTitle: \"newTestIssueTitle\",\n\t\tContent: \"newTestIssueContent\",\n\t}\n\n\tunittest.AssertSuccessfulInsert(t, newIssue)\n\n\tassert.NoError(t, newIssueUsers(db.DefaultContext, repo, newIssue))\n\n\tunittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: newIssue.ID, UID: newIssue.PosterID})\n\tunittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: newIssue.ID, UID: repo.OwnerID})\n}\n\n\n\nfunc TestUpdateIssueUsersByMentions(t *testing.T) {\n\tassert.NoError(t, unittest.PrepareTestDatabase())\n\tissue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue)\n\n\tuids := []int64{2, 5}\n\tassert.NoError(t, UpdateIssueUsersByMentions(db.DefaultContext, issue.ID, uids))\n\tfor _, uid := range uids {\n\t\tunittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: issue.ID, UID: uid}, \"is_mentioned=1\")\n\t}\n}\n\nfunc TestUpdateIssueUserByRead(t *testing.T) ", "output": "{\n\tassert.NoError(t, unittest.PrepareTestDatabase())\n\tissue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue)\n\n\tassert.NoError(t, UpdateIssueUserByRead(4, issue.ID))\n\tunittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: issue.ID, UID: 4}, \"is_read=1\")\n\n\tassert.NoError(t, UpdateIssueUserByRead(4, issue.ID))\n\tunittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: issue.ID, UID: 4}, \"is_read=1\")\n\n\tassert.NoError(t, UpdateIssueUserByRead(unittest.NonexistentID, unittest.NonexistentID))\n}"} {"input": "package xapi_test\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/softlayer/xapi-go\"\n)\n\n\n\nfunc TestLogin(t *testing.T) ", "output": "{\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, `\n\n\n\n\n\n\nStatus\nSuccess\n\n\nValue\nOpaqueRef:de305d54-75b4-431b-adb2-eb6b9e546013\n\n\n\n\n\n`)\n\t}))\n\tdefer ts.Close()\n\n\tx := xapi.NewClient(ts.URL, \"username\", \"password\", \"1.2\")\n\terr := x.Login()\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error: %s\", err)\n\t}\n}"} {"input": "package iso20022\n\n\ntype Commission19 struct {\n\n\tAmount *ImpliedCurrencyAndAmount `xml:\"Amt\"`\n\n\tAdditionalInformation *Max350Text `xml:\"AddtlInf,omitempty\"`\n}\n\n\n\nfunc (c *Commission19) SetAdditionalInformation(value string) {\n\tc.AdditionalInformation = (*Max350Text)(&value)\n}\n\nfunc (c *Commission19) SetAmount(value, currency string) ", "output": "{\n\tc.Amount = NewImpliedCurrencyAndAmount(value, currency)\n}"} {"input": "package dao\n\nimport (\n\t\"github.com/astaxie/beego/orm\"\n\t\"github.com/vmware/harbor/src/common/models\"\n\n\t\"fmt\"\n\t\"time\"\n)\n\n\nfunc AddScanJob(job models.ScanJob) (int64, error) {\n\to := GetOrmer()\n\tif len(job.Status) == 0 {\n\t\tjob.Status = models.JobPending\n\t}\n\treturn o.Insert(&job)\n}\n\n\nfunc GetScanJob(id int64) (*models.ScanJob, error) {\n\to := GetOrmer()\n\tj := models.ScanJob{ID: id}\n\terr := o.Read(&j)\n\tif err == orm.ErrNoRows {\n\t\treturn nil, nil\n\t}\n\treturn &j, nil\n}\n\n\nfunc GetScanJobsByImage(repository, tag string, limit ...int) ([]*models.ScanJob, error) {\n\tvar res []*models.ScanJob\n\t_, err := scanJobQs(limit...).Filter(\"repository\", repository).Filter(\"tag\", tag).OrderBy(\"-id\").All(&res)\n\treturn res, err\n}\n\n\nfunc GetScanJobsByDigest(digest string, limit ...int) ([]*models.ScanJob, error) {\n\tvar res []*models.ScanJob\n\t_, err := scanJobQs(limit...).Filter(\"digest\", digest).OrderBy(\"-id\").All(&res)\n\treturn res, err\n}\n\n\n\n\nfunc scanJobQs(limit ...int) orm.QuerySeter {\n\to := GetOrmer()\n\tl := -1\n\tif len(limit) == 1 {\n\t\tl = limit[0]\n\t}\n\treturn o.QueryTable(models.ScanJobTable).Limit(l)\n}\n\nfunc UpdateScanJobStatus(id int64, status string) error ", "output": "{\n\to := GetOrmer()\n\tsj := models.ScanJob{\n\t\tID: id,\n\t\tStatus: status,\n\t\tUpdateTime: time.Now(),\n\t}\n\tn, err := o.Update(&sj, \"Status\", \"UpdateTime\")\n\tif n == 0 {\n\t\treturn fmt.Errorf(\"Failed to update scan job with id: %d, error: %v\", id, err)\n\t}\n\treturn err\n}"} {"input": "package mapkha\n\ntype runePatPredicate func(rune) bool\n\ntype PatEdgeBuilder struct {\n\ts int\n\tfoundS bool\n\tfoundE bool\n\tisPat runePatPredicate\n\tedgeType Etype\n}\n\nfunc (builder *PatEdgeBuilder) Build(context *EdgeBuildingContext) *Edge {\n\tif !builder.foundS {\n\t\tif builder.isPat(context.Ch) {\n\t\t\tbuilder.s = context.I\n\t\t\tbuilder.foundS = true\n\t\t}\n\t}\n\n\tif builder.foundS {\n\t\tif builder.isPat(context.Ch) {\n\t\t\tif len(context.runes) == context.I+1 ||\n\t\t\t\t!builder.isPat(context.runes[context.I+1]) {\n\t\t\t\tbuilder.foundE = true\n\t\t\t}\n\t\t} else {\n\t\t\tbuilder.foundS = false\n\t\t\tbuilder.foundE = false\n\t\t}\n\t}\n\n\tif builder.foundS && builder.foundE {\n\t\tsource := context.Path[builder.s]\n\t\tbuilder.foundS = false\n\t\tbuilder.foundE = false\n\t\treturn &Edge{S: builder.s,\n\t\t\tEdgeType: builder.edgeType,\n\t\t\tWordCount: source.WordCount + 1,\n\t\t\tUnkCount: source.UnkCount}\n\t}\n\treturn nil\n}\n\n\n\nfunc (builder *PatEdgeBuilder) Reset() ", "output": "{\n\tbuilder.foundS = false\n\tbuilder.foundE = false\n\tbuilder.s = 0\n}"} {"input": "package resttk\n\ntype ResourceInterface interface {\n\tFindAllResources(v interface{}) interface{}\n\tFindResource(key string, value string, v interface{}) interface{}\n\tSaveResource(key string, value string, v interface{}) interface{}\n\tUpdateResource(key string, value string, v interface{}) interface{}\n\tDeleteResource(key string, value string) bool\n}\n\ntype BaseResource struct {\n\tparent ResourceInterface\n}\n\nfunc (r *BaseResource) Init(p ResourceInterface) {\n\tr.parent = p\n}\n\n\n\nfunc (r *BaseResource) FindResource(key string, value string, v interface{}) interface{} {\n\tresource := r.parent.FindResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn nil\n}\n\nfunc (r *BaseResource) SaveResource(key string, value string, v interface{}) interface{} {\n\tresource := r.parent.FindResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn nil\n}\n\nfunc (r *BaseResource) UpdateResource(key string, value string, v interface{}) interface{} {\n\tresource := r.parent.UpdateResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn nil\n}\n\nfunc (r *BaseResource) DeleteResource(key string, value string) bool {\n\treturn r.parent.DeleteResource(key, value)\n}\n\nfunc (r *BaseResource) FindAllResources(v interface{}) interface{} ", "output": "{\n\tresources := r.parent.FindAllResources(v)\n\tif resources != nil {\n\t\treturn resources\n\t}\n\n\treturn nil\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\n\n\n\nvar LoraDevicesCmd = &cobra.Command{\n\tUse: \"lora-devices\",\n\tShort: TRCLI(\"cli.lora-devices.summary\"),\n\tLong: TRCLI(`cli.lora-devices.description`),\n}\n\nfunc init() ", "output": "{\n\tRootCmd.AddCommand(LoraDevicesCmd)\n}"} {"input": "package api\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/url\"\n)\n\ntype PageToken struct {\n\tLimit uint16\n\tPage uint16\n}\n\nfunc DefaultPageToken(limit uint16) PageToken {\n\treturn PageToken{Limit: limit, Page: 1}\n}\n\nfunc (tok PageToken) Next() PageToken {\n\treturn PageToken{Limit: tok.Limit, Page: tok.Page + 1}\n}\n\nfunc (tok PageToken) Encode() string {\n\tbuf := bytes.Buffer{}\n\tbinary.Write(&buf, binary.LittleEndian, tok)\n\treturn base64.URLEncoding.EncodeToString(buf.Bytes())\n}\n\n\n\nfunc findNextPageToken(u *url.URL, limit uint16) (*PageToken, error) {\n\tvalues := u.Query()[\"nextPageToken\"]\n\n\tif len(values) > 1 {\n\t\treturn nil, errors.New(\"too many values for page token\")\n\t}\n\n\tif len(values) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tval := values[0]\n\ttok, err := decodePageToken(val)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = validatePageToken(tok, limit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tok, nil\n}\n\nfunc validatePageToken(tok *PageToken, limit uint16) error {\n\tif tok.Limit != limit {\n\t\treturn fmt.Errorf(\"token limit must be %d\", limit)\n\t}\n\n\tif tok.Page == 0 {\n\t\treturn errors.New(\"token page must be greater than zero\")\n\t}\n\n\treturn nil\n}\n\nfunc decodePageToken(value string) (*PageToken, error) ", "output": "{\n\tdec, err := base64.URLEncoding.DecodeString(value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdb := bytes.NewBuffer(dec)\n\n\tvar tok PageToken\n\terr = binary.Read(db, binary.LittleEndian, &tok)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &tok, nil\n}"} {"input": "package minio\n\n\n\nvar awsS3EndpointMap = map[string]string{\n\t\"us-east-1\": \"s3.amazonaws.com\",\n\t\"us-west-2\": \"s3-us-west-2.amazonaws.com\",\n\t\"us-west-1\": \"s3-us-west-1.amazonaws.com\",\n\t\"eu-west-1\": \"s3-eu-west-1.amazonaws.com\",\n\t\"eu-central-1\": \"s3-eu-central-1.amazonaws.com\",\n\t\"ap-southeast-1\": \"s3-ap-southeast-1.amazonaws.com\",\n\t\"ap-northeast-1\": \"s3-ap-northeast-1.amazonaws.com\",\n\t\"ap-northeast-2\": \"s3-ap-northeast-2.amazonaws.com\",\n\t\"sa-east-1\": \"s3-sa-east-1.amazonaws.com\",\n\t\"cn-north-1\": \"s3.cn-north-1.amazonaws.com.cn\",\n}\n\n\n\n\nfunc getS3Endpoint(bucketLocation string) (s3Endpoint string) ", "output": "{\n\ts3Endpoint, ok := awsS3EndpointMap[bucketLocation]\n\tif !ok {\n\t\ts3Endpoint = \"s3.amazonaws.com\"\n\t}\n\treturn s3Endpoint\n}"} {"input": "package repo\n\nimport (\n\t\"github.com/OpenBazaar/openbazaar-go/pb\"\n\t\"testing\"\n)\n\n\n\nfunc TestToV5OrderConfirmation(t *testing.T) ", "output": "{\n\tvar (\n\t\torderConfirmation = &pb.OrderConfirmation{\n\t\t\tRequestedAmount: 10000,\n\t\t}\n\t\tnewOrderConfirmation = ToV5OrderConfirmation(orderConfirmation)\n\t\texpected = \"10000\"\n\t)\n\n\tif newOrderConfirmation.BigRequestedAmount != expected {\n\t\tt.Errorf(\"Expected BigRequestedAmount of %s got %s\", expected, orderConfirmation.BigRequestedAmount)\n\t}\n\n\tif newOrderConfirmation.RequestedAmount != 0 {\n\t\tt.Errorf(\"Expected RequestedAmount of 0, got %d\", newOrderConfirmation.RequestedAmount)\n\t}\n}"} {"input": "package elf\n\nimport \"testing\"\n\n\n\nfunc TestNoSectionOverlaps(t *testing.T) ", "output": "{\n\tt.Skip(\"not 6l\")\n}"} {"input": "package loadbalancer\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype DeleteLoadBalancerRequest struct {\n\n\tLoadBalancerId *string `mandatory:\"true\" contributesTo:\"path\" name:\"loadBalancerId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request DeleteLoadBalancerRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request DeleteLoadBalancerRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteLoadBalancerResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n}\n\nfunc (response DeleteLoadBalancerResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteLoadBalancerResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteLoadBalancerRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package testrace\n\nimport \"testing\"\n\nfunc TestRace(t *testing.T) {\n\tfor i := 0; i < 10; i++ {\n\t\tc := make(chan int)\n\t\tx := 1\n\t\tgo func() {\n\t\t\tx = 2\n\t\t\tc <- 1\n\t\t}()\n\t\tx = 3\n\t\t<-c\n\t\t_ = x\n\t}\n}\n\n\n\nfunc BenchmarkRace(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tc := make(chan int)\n\t\tx := 1\n\t\tgo func() {\n\t\t\tx = 2\n\t\t\tc <- 1\n\t\t}()\n\t\tx = 3\n\t\t<-c\n\t\t_ = x\n\t}\n}"} {"input": "package unix\n\nimport \"syscall\"\n\n\n\nfunc setTimeval(sec, usec int64) Timeval {\n\treturn Timeval{Sec: int32(sec), Usec: int32(usec)}\n}\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint32(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint32(length)\n}\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\nfunc (msghdr *Msghdr) SetIovlen(length int) {\n\tmsghdr.Iovlen = int32(length)\n}\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\nfunc Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)\n\nfunc setTimespec(sec, nsec int64) Timespec ", "output": "{\n\treturn Timespec{Sec: int32(sec), Nsec: int32(nsec)}\n}"} {"input": "package match\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\nfunc Match(t *testing.T, value interface{}) *Matcher {\n\treturn &Matcher{\n\t\tt: t,\n\t\tvalue: value,\n\t}\n}\n\n\nfunc IsNil(t *testing.T, value interface{}) *Matcher {\n\treturn Match(t, value).IsNil()\n}\n\n\nfunc IsNotNil(t *testing.T, value interface{}) *Matcher {\n\treturn Match(t, value).IsNotNil()\n}\n\n\nfunc Equals(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).Equals(other)\n}\n\n\nfunc NotEquals(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).NotEquals(other)\n}\n\n\nfunc LessThan(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).LessThan(other)\n}\n\n\nfunc GreaterThan(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).GreaterThan(other)\n}\n\n\n\n\n\nfunc Matches(t *testing.T, value interface{}, pattern string) *Matcher {\n\treturn Match(t, value).Matches(pattern)\n}\n\n\nfunc KindOf(t *testing.T, value interface{}, kind reflect.Kind) *Matcher {\n\treturn Match(t, value).KindOf(kind)\n}\n\nfunc Contains(t *testing.T, value, other interface{}) *Matcher ", "output": "{\n\treturn Match(t, value).Contains(other)\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/rs/zerolog/log\"\n\t\"github.com/wzhliang/xing\"\n\t\"github.com/wzhliang/xing/examples/hello\"\n)\n\n\n\nfunc main() {\n\tmq := os.Getenv(\"RABBITMQ\")\n\tif mq == \"\" {\n\t\tmq = \"amqp://guest:guest@localhost:5672/\"\n\t}\n\tproducer, err := xing.NewClient(\"ingress.controller\", mq,\n\t\txing.SetIdentifier(&xing.RandomIdentifier{}),\n\t\txing.SetSerializer(&xing.JSONSerializer{}),\n\t)\n\t_assert(err)\n\tif err != nil {\n\t\treturn\n\t}\n\tn, err := strconv.Atoi(os.Args[1])\n\tif err != nil {\n\t\tlog.Error().Str(\"#\", os.Args[1]).Msg(\"Wrong argument\")\n\t}\n\tfor i := 0; i < n; i++ {\n\t\terr = producer.Notify(\"ingress.foobar\", \"Greeter::Nihao\", &hello.HelloRequest{Name: \"Jack\"})\n\t\t_assert(err)\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\tproducer.Close()\n}\n\nfunc _assert(err error) ", "output": "{\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"Client\")\n\t}\n}"} {"input": "package jms\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype UpdateFleetAgentConfigurationRequest struct {\n\n\tFleetId *string `mandatory:\"true\" contributesTo:\"path\" name:\"fleetId\"`\n\n\tUpdateFleetAgentConfigurationDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateFleetAgentConfigurationRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request UpdateFleetAgentConfigurationRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request UpdateFleetAgentConfigurationRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateFleetAgentConfigurationResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateFleetAgentConfigurationResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateFleetAgentConfigurationResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateFleetAgentConfigurationRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package main\n\nimport (\n\t\"math\"\n)\n\n\n\n\n\nfunc calculateFactors(n int) []int {\n\tvar factors []int\n\n\tfor i := 1; i <= int(math.Sqrt(float64(n))+1); i++ {\n\t\tif n%i == 0 {\n\t\t\tfactors = append(factors, i)\n\t\t\tfactors = append(factors, n/i)\n\t\t}\n\t}\n\n\treturn factors\n}\n\nfunc Problem12() interface{} ", "output": "{\n\n\tvar index int = 1\n\tvar triangle int = 0\n\tfor {\n\n\t\ttriangle += index\n\t\tfactors := calculateFactors(triangle)\n\t\tif len(factors) > 500 {\n\t\t\treturn triangle\n\t\t}\n\n\t\tindex++\n\t}\n\treturn 0\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/WindomZ/go-jwt/jwt\"\n\t\"os\"\n)\n\nconst (\n\tKeyNameHmac string = \"hmac_demo\" \n\tKeyNameRSA = \"rsa_demo\" \n)\n\nfunc main() {\n\tif dir, err := os.Getwd(); err != nil {\n\t\tpanic(err)\n\t} else if err := jwt.NewConfig(dir).Effect(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := demoHmac(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := demoRSA(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(\"Success!\")\n}\n\nfunc sign(keyName string, m interface{}) (token string, err error) {\n\treturn jwt.Sign(keyName, m, 72)\n}\n\n\n\nvar test_case = map[string]interface{}{\n\t\"number\": 19,\n\t\"english\": \"This is the English test.\",\n\t\"中文\": \"这是个中文测试。\",\n}\n\nfunc demoHmac() error {\n\tif token, err := sign(KeyNameHmac, test_case); err != nil {\n\t\treturn err\n\t} else if err := verify(token); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc demoRSA() error {\n\tif token, err := sign(KeyNameRSA, test_case); err != nil {\n\t\treturn err\n\t} else if err := verify(token); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc verify(token string) (err error) ", "output": "{\n\t_, err = jwt.Parse(token)\n\treturn\n}"} {"input": "package db\n\nimport (\n\t\"database/sql\"\n\t\"github.com/simplemvc/gocorelib/revel\"\n)\n\nvar (\n\tDb *sql.DB\n\tDriver string\n\tSpec string\n)\n\n\n\ntype Transactional struct {\n\t*revel.Controller\n\tTxn *sql.Tx\n}\n\n\nfunc (c *Transactional) Begin() revel.Result {\n\ttxn, err := Db.Begin()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tc.Txn = txn\n\treturn nil\n}\n\n\nfunc (c *Transactional) Rollback() revel.Result {\n\tif c.Txn != nil {\n\t\tif err := c.Txn.Rollback(); err != nil {\n\t\t\tif err != sql.ErrTxDone {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t\tc.Txn = nil\n\t}\n\treturn nil\n}\n\n\nfunc (c *Transactional) Commit() revel.Result {\n\tif c.Txn != nil {\n\t\tif err := c.Txn.Commit(); err != nil {\n\t\t\tif err != sql.ErrTxDone {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t\tc.Txn = nil\n\t}\n\treturn nil\n}\n\nfunc init() {\n\trevel.InterceptMethod((*Transactional).Begin, revel.BEFORE)\n\trevel.InterceptMethod((*Transactional).Commit, revel.AFTER)\n\trevel.InterceptMethod((*Transactional).Rollback, revel.FINALLY)\n}\n\nfunc Init() ", "output": "{\n\tvar found bool\n\tif Driver, found = revel.Config.String(\"db.driver\"); !found {\n\t\trevel.ERROR.Fatal(\"No db.driver found.\")\n\t}\n\tif Spec, found = revel.Config.String(\"db.spec\"); !found {\n\t\trevel.ERROR.Fatal(\"No db.spec found.\")\n\t}\n\n\tvar err error\n\tDb, err = sql.Open(Driver, Spec)\n\tif err != nil {\n\t\trevel.ERROR.Fatal(err)\n\t}\n}"} {"input": "package main\n\nimport \"./buildings\"\n\n\nvar board [2][2][][]buildings.Building \nfunc bget(x, y int) buildings.Building {\n\txIndex, yIndex := 0, 0 \n\tif x < 0 {\n\t\txIndex = 1\n\t\tx = -x\n\t}\n\tif y < 0 {\n\t\tyIndex = 1\n\t\ty = -y\n\t}\n\treturn board[xIndex][yIndex][x][y]\n}\nfunc bset(x, y int, b buildings.Building) {\n\txIndex, yIndex := 0, 0\n\tif x < 0 {\n\t\txIndex = 1\n\t\tx = -x\n\t}\n\tif y < 0 {\n\t\tyIndex = 1\n\t\ty = -y\n\t}\n\tboard[xIndex][yIndex][x][y] = b\n}\n\nfunc bForEach(f func(buildings.Building, int, int)) {\n\tfor xIndex := 0; xIndex <= 1; xIndex++ {\n\t\tfor yIndex := 0; yIndex <= 1; yIndex++ {\n\t\t\tfor x := xIndex; x < len(board[xIndex][yIndex]); x++ {\n\t\t\t\tfor y := yIndex; y < len(board[xIndex][yIndex][x]); y++ {\n\t\t\t\t\tf(board[xIndex][yIndex][x][y], x, y)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc badd(x, y int, b buildings.Building) ", "output": "{ \n\txIndex, yIndex := 0, 0\n\tif x < 0 {\n\t\txIndex = 1\n\t\tx = -x\n\t}\n\tif y < 0 {\n\t\tyIndex = 1\n\t\ty = -y\n\t}\n\tif cap(board[xIndex][yIndex]) < x {\n\t\tslice2 := make([][]buildings.Building, len(board[xIndex][yIndex]), x+4) \n\t\tcopy(slice2, board[xIndex][yIndex])\n\t\tboard[xIndex][yIndex] = slice2\n\t}\n\tif cap(board[xIndex][yIndex][x]) < y {\n\t\tslice2 := make([]buildings.Building, len(board[xIndex][yIndex][x]), x+4) \n\t\tcopy(slice2, board[xIndex][yIndex][x])\n\t\tboard[xIndex][yIndex][x] = slice2\n\t}\n\tboard[xIndex][yIndex][x][y] = b\n}"} {"input": "package stree\n\n\n\ntype serial struct {\n\tstree\n}\n\n\nfunc NewSerial() Tree {\n\tt := new(serial)\n\tt.Clear()\n\treturn t\n}\n\n\n\nfunc (t *serial) Print() {\n\tpanic(\"Print() not supported for serial data structure\")\n}\n\nfunc (t *serial) Tree2Array() []SegmentOverlap {\n\tpanic(\"Tree2Array() not supported for serial data structure\")\n}\n\n\nfunc (t *serial) Query(from, to int) []Interval {\n\tresult := make([]Interval, 0, 10)\n\tfor _, intrvl := range t.base {\n\t\tif !intrvl.Segment.Disjoint(from, to) {\n\t\t\tresult = append(result, intrvl)\n\t\t}\n\t}\n\treturn result\n}\n\n\nfunc (t *serial) QueryArray(from, to []int) []Interval {\n\tresult := make([]Interval, 0, 10)\n\tfor i, fromvalue := range from {\n\t\tresult = append(result, t.Query(fromvalue, to[i])...)\n\t}\n\treturn result\n}\n\nfunc (t *serial) BuildTree() ", "output": "{\n\tpanic(\"BuildTree() not supported for serial data structure\")\n}"} {"input": "package save\n\nimport (\n\t\"github.com/madhusudhancs/redis/cache\"\n\t\"github.com/madhusudhancs/redis/cmd\"\n\t\"github.com/madhusudhancs/redis/config\"\n\t\"github.com/madhusudhancs/redis/utils/log\"\n)\n\nconst (\n\tCmdName = \"SAVE\"\n)\n\n\n\nfunc Run(options []string, c *cache.Cache) ([]byte, bool) {\n\tif _, err := c.Save(config.DBFileName); err != nil {\n\t\tlog.Errorf(\"SaveCmd: err: %v\", err)\n\t\treturn cmd.GetErrMsg(err), false\n\t}\n\n\treturn cmd.GetSimpleString(\"OK\"), false\n}\n\nfunc init() ", "output": "{\n\tif err := cmd.Register(CmdName, Run); err != nil {\n\t\tlog.Errorf(\"SaveCmd: failed to register command. err: %v\", err)\n\t}\n}"} {"input": "package develop\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"sync\"\n\n\t\"github.com/flipace/hantera/lib\"\n)\n\n\n\n\nfunc CloneRepository(name string, target string, branch string, repository string, nodeps bool, wg *sync.WaitGroup) ", "output": "{\n\tworkingDir, err := filepath.Abs(path.Join(target, \"../\"))\n\tcheck(err)\n\n\tlib.Catchy(\">> Cloning %s to %s\\n\", name, target)\n\n\tcloneOut, cloneErr := lib.Run(\n\t\ttrue,\n\t\tworkingDir,\n\t\tfalse,\n\t\t\"git\",\n\t\t\"clone\",\n\t\trepository,\n\t\ttarget,\n\t)\n\n\tif len(cloneErr.String()) > 0 {\n\t\tprintln(cloneErr.String())\n\t}\n\n\tcheckOut, checkErr := lib.Run(true, target, false, \"git\", \"checkout\", branch)\n\tif len(checkErr.String()) > 0 {\n\t\tprintln(checkErr.String())\n\t}\n\n\tfmt.Printf(\"--| %s:\\n%s\\n%s\", name, cloneOut.String(), checkOut.String())\n\n\twg.Done()\n}"} {"input": "package prometheus\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"text/template\"\n\n\t\"github.com/pkg/errors\"\n\n\ttm \"github.com/supergiant/control/pkg/templatemanager\"\n\t\"github.com/supergiant/control/pkg/workflows/steps\"\n)\n\nconst StepName = \"prometheus\"\n\ntype Config struct {\n\tRBACEnabled bool\n}\n\ntype Step struct {\n\tscript *template.Template\n}\n\nfunc (s *Step) Rollback(context.Context, io.Writer, *steps.Config) error {\n\treturn nil\n}\n\nfunc Init() {\n\ttpl, err := tm.GetTemplate(StepName)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"template %s not found\", StepName))\n\t}\n\n\tsteps.RegisterStep(StepName, New(tpl))\n}\n\nfunc New(script *template.Template) *Step {\n\tt := &Step{\n\t\tscript: script,\n\t}\n\n\treturn t\n}\n\nfunc (s *Step) Run(ctx context.Context, out io.Writer, config *steps.Config) error {\n\terr := steps.RunTemplate(ctx, s.script, config.Runner, out, toStepCfg(config))\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"install prometheus step\")\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (s *Step) Description() string {\n\treturn \"Install prometheus\"\n}\n\nfunc (s *Step) Depends() []string {\n\treturn nil\n}\n\nfunc toStepCfg(c *steps.Config) Config {\n\treturn Config{\n\t\tRBACEnabled: c.Kube.RBACEnabled,\n\t}\n}\n\nfunc (s *Step) Name() string ", "output": "{\n\treturn StepName\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/matcornic/subify/common/config\"\n\tlogger \"github.com/spf13/jwalterweatherman\"\n)\n\n\nfunc VerbosePrintln(logger *log.Logger, log string) {\n\tif config.Verbose && log != \"\" {\n\t\tlogger.Println(log)\n\t}\n}\n\n\n\n\n\n\nfunc ExitPrintError(err error, format string, args ...interface{}) {\n\tExitVerbose(fmt.Sprint(err), format, args...)\n}\n\n\n\nfunc ExitVerbose(verboseLog string, format string, args ...interface{}) {\n\tlogger.ERROR.Println(verboseLog)\n\tif !config.Verbose {\n\t\tlogger.ERROR.Println(\"Run subify with --verbose option to get more information about the error\")\n\t}\n\tlogger.FATAL.Printf(format)\n\tos.Exit(-1)\n}\n\nfunc Exit(format string, args ...interface{}) ", "output": "{\n\tExitVerbose(\"\", format, args...)\n}"} {"input": "package header_test\n\nimport (\n\t\"testing\"\n\n\t\"gvisor.dev/gvisor/pkg/tcpip/header\"\n)\n\nfunc TestIPv4(t *testing.T) {\n\tb := header.IPv4(make([]byte, header.IPv4MinimumSize))\n\tb.Encode(&header.IPv4Fields{})\n\n\tconst want = header.IPv4Version\n\tif v := header.IPVersion(b); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}\n\nfunc TestIPv6(t *testing.T) {\n\tb := header.IPv6(make([]byte, header.IPv6MinimumSize))\n\tb.Encode(&header.IPv6Fields{})\n\n\tconst want = header.IPv6Version\n\tif v := header.IPVersion(b); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}\n\n\n\nfunc TestTooShort(t *testing.T) {\n\tb := make([]byte, 1)\n\tb[0] = (header.IPv4Version + header.IPv6Version) << 4\n\n\tconst want = -1\n\tif v := header.IPVersion(b[:0]); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n\n\tif v := header.IPVersion(nil); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}\n\nfunc TestOtherVersion(t *testing.T) ", "output": "{\n\tconst want = header.IPv4Version + header.IPv6Version\n\tb := make([]byte, 1)\n\tb[0] = want << 4\n\n\tif v := header.IPVersion(b); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}"} {"input": "package bunyan\n\nimport \"fmt\"\n\n\ntype Logger struct {\n\tsink Sink\n\trecord Record\n}\n\n\nfunc NewLogger(target Sink) *Logger {\n\treturn &Logger{target, NewRecord()}\n}\n\n\n\nfunc (l *Logger) Write(record Record) error {\n\trecord.TemplateMerge(l.record)\n\treturn l.sink.Write(record)\n}\n\n\n\nfunc (l *Logger) Include(info Info) Log {\n\treturn NewLogger(InfoSink(l, info))\n}\n\n\n\nfunc (l *Logger) Record(key string, value interface{}) Log {\n\tbuilder := NewLogger(l)\n\tbuilder.record[key] = value\n\treturn builder\n}\n\n\n\nfunc (l *Logger) Recordf(key, value string, args ...interface{}) Log {\n\treturn l.Record(key, fmt.Sprintf(value, args...))\n}\n\n\n\nfunc (l *Logger) Child() Log {\n\treturn NewLogger(l)\n}\n\nfunc (l *Logger) Tracef(msg string, args ...interface{}) { l.send(TRACE, msg, args...) }\nfunc (l *Logger) Debugf(msg string, args ...interface{}) { l.send(DEBUG, msg, args...) }\nfunc (l *Logger) Infof(msg string, args ...interface{}) { l.send(INFO, msg, args...) }\n\nfunc (l *Logger) Errorf(msg string, args ...interface{}) { l.send(ERROR, msg, args...) }\nfunc (l *Logger) Fatalf(msg string, args ...interface{}) { l.send(FATAL, msg, args...) }\n\nfunc (l *Logger) send(level Level, msg string, args ...interface{}) {\n\trecord := NewRecord()\n\trecord.SetMessagef(level, msg, args...)\n\te := l.Write(record)\n\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc (l *Logger) Warnf(msg string, args ...interface{}) ", "output": "{ l.send(WARN, msg, args...) }"} {"input": "package utils\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/heketi/heketi/tests\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestNewStatusGroup(t *testing.T) {\n\ts := NewStatusGroup()\n\ttests.Assert(t, s != nil)\n\ttests.Assert(t, s.results != nil)\n\ttests.Assert(t, len(s.results) == 0)\n\ttests.Assert(t, s.err == nil)\n}\n\n\n\nfunc TestStatusGroupFailure(t *testing.T) {\n\ts := NewStatusGroup()\n\n\tfor i := 0; i < 100; i++ {\n\n\t\ts.Add(1)\n\t\tgo func(value int) {\n\t\t\tdefer s.Done()\n\t\t\ttime.Sleep(time.Millisecond * 1 * time.Duration(value))\n\t\t\tif value%10 == 0 {\n\t\t\t\ts.Err(errors.New(fmt.Sprintf(\"Err: %v\", value)))\n\t\t\t}\n\n\t\t}(i)\n\n\t}\n\n\terr := s.Result()\n\n\ttests.Assert(t, err != nil)\n\ttests.Assert(t, err.Error() == \"Err: 90\", err)\n\n}\n\nfunc TestStatusGroupSuccess(t *testing.T) ", "output": "{\n\n\ts := NewStatusGroup()\n\n\tmax := 100\n\ts.Add(max)\n\n\tfor i := 0; i < max; i++ {\n\t\tgo func(value int) {\n\t\t\tdefer s.Done()\n\t\t\ttime.Sleep(time.Millisecond * 1 * time.Duration(value))\n\t\t}(i)\n\t}\n\n\terr := s.Result()\n\ttests.Assert(t, err == nil)\n\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ChangeDatabaseSoftwareImageCompartmentRequest struct {\n\n\tChangeCompartmentDetails `contributesTo:\"body\"`\n\n\tDatabaseSoftwareImageId *string `mandatory:\"true\" contributesTo:\"path\" name:\"databaseSoftwareImageId\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype ChangeDatabaseSoftwareImageCompartmentResponse struct {\n\n\tRawResponse *http.Response\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ChangeDatabaseSoftwareImageCompartmentResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ChangeDatabaseSoftwareImageCompartmentResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/xeb/etcdrepl/third_party/github.com/codegangsta/cli\"\n\t\"github.com/xeb/etcdrepl/third_party/github.com/coreos/go-etcd/etcd\"\n)\n\nfunc NewLsCommand() cli.Command {\n\treturn cli.Command{\n\t\tName:\t\"ls\",\n\t\tUsage:\t\"retrieve a directory\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.BoolFlag{\"recursive\", \"returns all values for key and child keys\"},\n\t\t},\n\t\tAction: func(c *cli.Context) {\n\t\t\thandleLs(c, lsCommandFunc)\n\t\t},\n\t}\n}\n\n\nfunc handleLs(c *cli.Context, fn handlerFunc) {\n\thandlePrint(c, fn, printLs)\n}\n\n\n\nfunc printLs(resp *etcd.Response, format string) {\n\tif !resp.Node.Dir {\n\t\tfmt.Println(resp.Node.Key)\n\t}\n\tfor _, node := range resp.Node.Nodes {\n\t\trPrint(&node)\n\t}\n}\n\n\n\n\n\nfunc rPrint(n *etcd.Node) {\n\tfmt.Println(n.Key)\n\tfor _, node := range n.Nodes {\n\t\trPrint(&node)\n\t}\n}\n\nfunc lsCommandFunc(c *cli.Context, client *etcd.Client) (*etcd.Response, error) ", "output": "{\n\tkey := \"/\"\n\tif len(c.Args()) != 0 {\n\t\tkey = c.Args()[0]\n\t}\n\trecursive := c.Bool(\"recursive\")\n\n\treturn client.Get(key, false, recursive)\n}"} {"input": "package scheduler\n\nimport (\n\t\"fmt\"\n\t\"github.com/jonaz/astrotime\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\n\nfunc isSunrise(latitude float64, longitude float64) bool {\n\tt := astrotime.NextSunrise(time.Now(), latitude, longitude)\n\ttzname, _ := t.Zone()\n\tif t.Hour() == time.Now().Hour() && t.Minute() == time.Now().Minute() {\n\t\tfmt.Printf(\"The sunrise is %d:%02d %s on %d/%d/%d.\\n\", t.Hour(), t.Minute(), tzname, t.Month(), t.Day(), t.Year())\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc Start(intervalInSeconds int, latitude float64, longitude float64, autoNightLights []int64) {\n\tticker := time.NewTicker(time.Millisecond * time.Duration(intervalInSeconds))\n\tgo func() {\n\t\tfor t := range ticker.C {\n\t\t\tvar state string\n\t\t\tvar changeLights bool\n\t\t\tif isSunset(latitude, longitude) {\n\t\t\t\tfmt.Println(\"Sunset\", t)\n\t\t\t\tstate = \"ON\"\n\t\t\t\tchangeLights = true\n\t\t\t} else if isSunrise(latitude, longitude) {\n\t\t\t\tfmt.Println(\"Sunrise\", t)\n\t\t\t\tstate = \"OFF\"\n\t\t\t\tchangeLights = true\n\t\t\t}\n\t\t\tif changeLights == true {\n\t\t\t\tfmt.Println(\"Updating lights\")\n\t\t\t\tfor _, light := range autoNightLights {\n\t\t\t\t\targs := []string{\"-u\", \"-m\" + strconv.FormatInt(light, 10), \"-t1\", \"-v\" + state}\n\t\t\t\t\tcmd := exec.Command(\"/usr/sbin/aprontest\", args...)\n\t\t\t\t\tcmd.Run()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc isSunset(latitude float64, longitude float64) bool ", "output": "{\n\tt := astrotime.NextSunset(time.Now(), latitude, longitude)\n\tif t.Hour() == time.Now().Hour() && t.Minute() == time.Now().Minute() {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package history\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/avatar29A/microchat/history/model\"\n\t\"github.com/avatar29A/microchat/server/protocols\"\n\t\"github.com/avatar29A/microchat/utils\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n)\n\nimport \"github.com/satori/go.uuid\"\n\n\ntype MessagesContext struct {\n\tctx *DBContext\n}\n\n\nfunc NewMessagesContext(context *DBContext) *MessagesContext {\n\tc := &MessagesContext{context}\n\n\treturn c\n}\n\n\nfunc (c *MessagesContext) GetLastNMessages(n int) []*protocols.UserSay {\n\tquery := fmt.Sprintf(\"ORDER BY created_at DESC LIMIT %s\", c.ctx.DB.Placeholder(0))\n\n\trows, err := c.ctx.DB.SelectAllFrom(model.MessageTable, query, n)\n\tmessages := make([]*protocols.UserSay, 0, len(rows))\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn messages\n\t}\n\n\tfor _, row := range rows {\n\t\tmessage := row.(*model.Message)\n\t\tmessages = append(messages, &protocols.UserSay{\n\t\t\tUsername: message.UserName,\n\t\t\tMessage: message.Message,\n\t\t\tCreatedAt: utils.MakeTimeStampFromTime(message.CreatedAt),\n\t\t})\n\t}\n\n\treturn messages\n}\n\n\nfunc (c *MessagesContext) SaveMessage(message *protocols.UserSay) error {\n\tchannel := c.getDefaultChannel()\n\n\tentity := &model.Message{\n\t\tID: string(uuid.NewV4().Bytes()),\n\t\tUserName: message.Username,\n\t\tChannelID: channel.ID,\n\t\tMessage: message.Message,\n\t\tCreatedAt: utils.MakeTimeFromTimestamp(message.CreatedAt),\n\t}\n\n\treturn c.ctx.DB.Save(entity)\n}\n\n\n\nfunc (c *MessagesContext) getDefaultChannel() *model.Channel ", "output": "{\n\tentity, err := c.ctx.DB.FindOneFrom(model.ChannelTable, \"name\", \"default\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn entity.(*model.Channel)\n}"} {"input": "package ast\n\nimport \"monkey/token\"\n\ntype StringLiteral struct {\n\tToken token.Token\n\tValue string\n}\n\nfunc (s *StringLiteral) expressionNode() {}\nfunc (s *StringLiteral) TokenLiteral() string { return s.Token.Literal }\n\n\ntype InterpolatedString struct {\n\tToken token.Token\n\tValue string\n\tExprMap map[byte]Expression\n}\n\nfunc (is *InterpolatedString) expressionNode() {}\nfunc (is *InterpolatedString) TokenLiteral() string { return is.Token.Literal }\nfunc (is *InterpolatedString) String() string { return is.Token.Literal }\n\nfunc (s *StringLiteral) String() string ", "output": "{ return s.Token.Literal }"} {"input": "package framework\n\nimport \"sync\"\n\ntype CleanupActionHandle *int\n\nvar cleanupActionsLock sync.Mutex\nvar cleanupActions = map[CleanupActionHandle]func(){}\n\n\n\n\nfunc AddCleanupAction(fn func()) CleanupActionHandle {\n\tp := CleanupActionHandle(new(int))\n\tcleanupActionsLock.Lock()\n\tdefer cleanupActionsLock.Unlock()\n\tcleanupActions[p] = fn\n\treturn p\n}\n\n\n\nfunc RemoveCleanupAction(p CleanupActionHandle) {\n\tcleanupActionsLock.Lock()\n\tdefer cleanupActionsLock.Unlock()\n\tdelete(cleanupActions, p)\n}\n\n\n\n\n\n\nfunc RunCleanupActions() ", "output": "{\n\tlist := []func(){}\n\tfunc() {\n\t\tcleanupActionsLock.Lock()\n\t\tdefer cleanupActionsLock.Unlock()\n\t\tfor _, fn := range cleanupActions {\n\t\t\tlist = append(list, fn)\n\t\t}\n\t}()\n\tfor _, fn := range list {\n\t\tfn()\n\t}\n}"} {"input": "package main\n\nimport (\n \"time\"\n \"net/http\"\n \"io/ioutil\"\n \"strings\"\n\n \"launchpad.net/gocheck\"\n \"github.com/mreiferson/go-httpclient\"\n)\n\nconst url string = \"http://127.0.0.1:8080\"\n\n\n\nfunc sendHTTPRequest(method, endpoint, user, pass string) (*http.Response, error){\n transport := &httpclient.Transport{\n ConnectTimeout: 1*time.Second,\n RequestTimeout: 10*time.Second,\n ResponseHeaderTimeout: 5*time.Second,\n }\n defer transport.Close()\n\n client := &http.Client{Transport: transport}\n prefix := \"/v0/actions\"\n req, _ := http.NewRequest(method, url + prefix + endpoint, nil)\n req.SetBasicAuth(user, pass)\n\n \n return client.Do(req)\n}\n\nfunc (t *testSuite) TestHivyDummy() {\n resp, err := sendHTTPRequest(\"GET\", \"/dummy\", \"xav\", \"boss\")\n defer resp.Body.Close()\n t.Check(err, gocheck.IsNil)\n\n contents, err := ioutil.ReadAll(resp.Body)\n t.Check(err, gocheck.IsNil)\n\n t.True(strings.Contains(string(contents), \"dummy\"))\n \n}\n\nfunc (t *testSuite) TestBadAuthentification() {\n resp, err := sendHTTPRequest(\"GET\", \"/dummy\", \"wrong\", \"login\")\n defer resp.Body.Close()\n t.Check(err, gocheck.IsNil)\n\n contents, err := ioutil.ReadAll(resp.Body)\n t.Check(err, gocheck.IsNil)\n\n t.True(strings.Contains(string(contents), \"Key Not Found\"))\n \n}\n\nfunc setupHivy() ", "output": "{\n \n go hivy(url, false)\n}"} {"input": "package internalversion\n\nimport (\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\tv1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n\tauthentication \"k8s.io/kubernetes/pkg/apis/authentication\"\n)\n\n\ntype TokenReviewLister interface {\n\tList(selector labels.Selector) (ret []*authentication.TokenReview, err error)\n\tGet(name string) (*authentication.TokenReview, error)\n\tTokenReviewListerExpansion\n}\n\n\ntype tokenReviewLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewTokenReviewLister(indexer cache.Indexer) TokenReviewLister {\n\treturn &tokenReviewLister{indexer: indexer}\n}\n\n\n\n\n\nfunc (s *tokenReviewLister) Get(name string) (*authentication.TokenReview, error) {\n\tkey := &authentication.TokenReview{ObjectMeta: v1.ObjectMeta{Name: name}}\n\tobj, exists, err := s.indexer.Get(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(authentication.Resource(\"tokenreview\"), name)\n\t}\n\treturn obj.(*authentication.TokenReview), nil\n}\n\nfunc (s *tokenReviewLister) List(selector labels.Selector) (ret []*authentication.TokenReview, err error) ", "output": "{\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*authentication.TokenReview))\n\t})\n\treturn ret, err\n}"} {"input": "package fabric\n\n\nfunc contains(s []DGNode, i DGNode) bool {\n\tfor _, v := range s {\n\t\tif i.ID() == v.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc containsVirtual(s []Virtual, i Virtual) bool {\n\tfor _, v := range s {\n\t\tif i.ID() == v.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\n\nfunc ContainsEdge(l EdgeList, e Edge) bool {\n\tfor _, v := range l {\n\t\tif v.ID() == e.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc ContainsNode(l NodeList, n Node) bool ", "output": "{\n\tfor _, v := range l {\n\t\tif v.ID() == n.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package caller\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"testing\"\n)\n\n\n\nfunc TestDefaultCallResolver(t *testing.T) {\n\tdefer func() { defaultCallResolver.cache = map[uintptr]*cachedLookup{} }()\n\n\tfor i := 0; i < 2; i++ {\n\t\tif l := len(defaultCallResolver.cache); l != i {\n\t\t\tt.Fatalf(\"cache has %d entries, expected %d\", l, i)\n\t\t}\n\t\tfile, _, fun := Lookup(0)\n\t\tif fun != \"TestDefaultCallResolver\" {\n\t\t\tt.Fatalf(\"unexpected caller reported: %s\", fun)\n\t\t}\n\n\t\tif file != filepath.Join(\"util\", \"caller\", \"resolver_test.go\") {\n\t\t\tt.Fatalf(\"wrong file '%s'\", file)\n\t\t}\n\t}\n}\n\nfunc BenchmarkFormatedCaller(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tfile, line, _ := Lookup(1)\n\t\ts := fmt.Sprintf(\"%s:%d\", file, line)\n\t\tif testing.Verbose() {\n\t\t\tb.Log(s)\n\t\t}\n\t}\n}\n\nfunc BenchmarkSimpleCaller(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tfile, line, _ := Lookup(1)\n\t\tif testing.Verbose() {\n\t\t\ts := fmt.Sprintf(\"%s:%d\", file, line)\n\t\t\tb.Log(s)\n\t\t}\n\t}\n}\n\nfunc TestCallResolver(t *testing.T) ", "output": "{\n\tcr := NewCallResolver(0, regexp.MustCompile(`resolver_test\\.go.*$`))\n\tfor i := 0; i < 2; i++ {\n\t\tif l := len(cr.cache); l != i {\n\t\t\tt.Fatalf(\"cache has %d entries, expected %d\", l, i)\n\t\t}\n\t\tfile, _, fun := func() (string, int, string) {\n\t\t\treturn cr.Lookup(1)\n\t\t}()\n\t\tif file != \"resolver_test.go\" {\n\t\t\tt.Fatalf(\"wrong file '%s'\", file)\n\t\t}\n\t\tif fun != \"TestCallResolver\" {\n\t\t\tt.Fatalf(\"unexpected caller reported: %s\", fun)\n\t\t}\n\t}\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/mexisme/go-config/settings\"\n)\n\n\nfunc AddConfigItems(configKeys []string) {\n\tsettings.AddConfigItems(configKeys)\n}\n\n\nfunc AddConfigItemsWithPFlags(configKeys []string) error {\n\treturn settings.AddConfigItemsWithPFlags(configKeys)\n}\n\n\nfunc ApplyWith(key string, f func(interface{})) {\n\tsettings.ApplyWith(key, f)\n}\n\n\nfunc Get(key string) interface{} {\n\treturn settings.Get(key)\n}\n\n\nfunc GetBool(key string) bool {\n\treturn settings.GetBool(key)\n}\n\n\nfunc GetFloat64(key string) float64 {\n\treturn settings.GetFloat64(key)\n}\n\n\nfunc GetInt(key string) int {\n\treturn settings.GetInt(key)\n}\n\n\n\n\n\nfunc GetStringMap(key string) map[string]interface{} {\n\treturn settings.GetStringMap(key)\n}\n\n\nfunc GetStringMapString(key string) map[string]string {\n\treturn settings.GetStringMapString(key)\n}\n\n\nfunc GetStringSlice(key string) []string {\n\treturn settings.GetStringSlice(key)\n}\n\n\nfunc GetTime(key string) time.Time {\n\treturn settings.GetTime(key)\n}\n\n\nfunc GetDuration(key string) time.Duration {\n\treturn settings.GetDuration(key)\n}\n\n\nfunc IsSet(key string) bool {\n\treturn settings.IsSet(key)\n}\n\n\nfunc AllSettings() map[string]interface{} {\n\treturn settings.AllSettings()\n}\n\nfunc GetString(key string) string ", "output": "{\n\treturn settings.GetString(key)\n}"} {"input": "package storage\n\nimport (\n\tastorage \"aqua/common/storage\"\n\t\"aqua/connect_server/config\"\n\n\t\"github.com/foolbread/fbcommon/golog\"\n)\n\nconst default_count = 5\n\n\n\nfunc GetStorage() *storageManager {\n\treturn g_storage\n}\n\nvar g_storage *storageManager\n\ntype storageManager struct {\n\tsession_storages [][]*astorage.StorageHandler\n}\n\nfunc newStorageManager() *storageManager {\n\tret := new(storageManager)\n\tret.session_storages = make([][]*astorage.StorageHandler, len(config.GetConfig().GetSessionDBInfos()))\n\n\treturn ret\n}\n\nfunc (s *storageManager) GetSessionHandler(cid string) *astorage.StorageHandler {\n\tby := astorage.Md5ToByte(cid)\n\tas := s.session_storages[int(by)%len(s.session_storages)]\n\treturn as[int(by)%len(as)]\n}\n\nfunc InitStorageManager() ", "output": "{\n\tgolog.Info(\"initing login storage manager...\")\n\tg_storage = newStorageManager()\n\n\tinfos := config.GetConfig().GetSessionDBInfos()\n\tfor k, v := range infos {\n\t\tfor i := 0; i < default_count; i++ {\n\t\t\thnl := astorage.NewStorageHandler(v)\n\t\t\tif hnl != nil {\n\t\t\t\tg_storage.session_storages[k] = append(g_storage.session_storages[k], hnl)\n\t\t\t}\n\t\t}\n\t}\n\n}"} {"input": "package resque\n\nimport (\n\t\"errors\"\n\n\tredis \"gopkg.in/redis.v5\"\n)\n\n\ntype Batch struct {\n\tqueue string\n\tjobs []Job\n\tredisClient *redis.Client\n\tnamespace string\n}\n\n\n\n\nfunc (r *Client) NewBatch(queue string) (*Batch, error) ", "output": "{\n\tif queue == \"\" {\n\t\treturn nil, errors.New(\"invalid queue name\")\n\t}\n\n\treturn &Batch{\n\t\tqueue: queue,\n\t\tredisClient: r.redisClient,\n\t\tnamespace: r.namespace,\n\t}, nil\n}"} {"input": "package request\n\nimport (\n\t\"CitySourcedAPI/data\"\n\t\"CitySourcedAPI/logs\"\n\t\"CitySourcedAPI/response\"\n\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\n\n\ntype CreateReportComment struct {\n\tRequest\n\tProcessor\n\tReportID string `xml:\"ReportId\" json:\"ReportId\"`\n\treportID int64\n\tComment string `xml:\"Comment\" json:\"Comment\"`\n}\n\n\n\nfunc (st *CreateReportComment) Run() (string, error) {\n\terr := data.NewComment(st.reportID, data.CustomTime{time.Now()}, st.Comment)\n\tif err != nil {\n\t\treturn response.StatusMsg(fmt.Sprintf(\"CreateReportComment failed: %q\", err), st.start), nil\n\t}\n\treturn response.StatusMsg(\"Comment created.\", st.start), nil\n}\n\nfunc (st CreateReportComment) String() string {\n\tls := new(logs.LogString)\n\tls.AddS(\"CreateReportComment\\n\")\n\tls.AddS(st.Request.String())\n\tls.AddF(\"ID %s/%d\\n\", st.ReportID, st.reportID)\n\tls.AddF(\"Comment: %v\\n\", st.Comment)\n\treturn ls.Box(90)\n}\n\nfunc (st *CreateReportComment) Validate(start time.Time) string ", "output": "{\n\tvar v validate\n\tst.start = start\n\tst.reportID = v.int(\"ReportID\", st.ReportID)\n\treturn v.errmsg\n}"} {"input": "package record\n\nimport (\n\t\"sync\"\n\n\t\"github.com/gollector/gollector/logger\"\n)\n\nvar recorded_metrics map[string]interface{}\n\nvar rwmutex sync.RWMutex\n\nfunc GetMetric(params interface{}, log *logger.Logger) interface{} {\n\tendpoint := params.(string)\n\n\trwmutex.RLock()\n\tresult := recorded_metrics[endpoint]\n\trwmutex.RUnlock()\n\n\treturn result\n}\n\n\n\nfunc RecordMetric(name string, value interface{}, log *logger.Logger) ", "output": "{\n\trwmutex.Lock()\n\tif recorded_metrics == nil {\n\t\trecorded_metrics = make(map[string]interface{})\n\t}\n\trecorded_metrics[name] = value\n\trwmutex.Unlock()\n}"} {"input": "package service\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"gopkg.in/gin-gonic/gin.v0\"\n\t\"gopkg.in/jmoiron/sqlx.v0\"\n\t_ \"gopkg.in/lib/pq.v0\"\n\t_ \"gopkg.in/mattn/go-sqlite3.v0\"\n)\n\ntype Config struct {\n\tServiceHost string `yaml:\"host,flow\"`\n\tDbDriver string `yaml:\"driver,flow\"`\n\tDbSource string `yaml:\"datasource,flow\"`\n\tKeyFile string\n}\n\ntype AuthService struct{}\n\n\n\nfunc GetDBHandler(conf Config) (*sqlx.DB, error) {\n\tdbh, err := sqlx.Connect(conf.DbDriver, conf.DbSource)\n\treturn dbh, err\n}\n\nfunc (s *AuthService) GetHttpHandler(conf Config) (http.Handler, error) ", "output": "{\n\tdbh, err := GetDBHandler(conf)\n\tif err != nil {\n\t\treturn gin.New(), err\n\t}\n\n\tkeyData, err := ioutil.ReadFile(conf.KeyFile)\n\tif err != nil {\n\t\treturn gin.New(), err\n\t}\n\n\tresource := &AuthResource{dbh, keyData}\n\tr := gin.Default()\n\tauth := r.Group(\"/auth\")\n\tauth.POST(\"/login\", resource.CreateSession)\n\tauth.POST(\"/signup\", resource.CreateUser)\n\treturn r, nil\n}"} {"input": "package v1alpha1\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\tv1alpha1 \"k8s.io/ingress-gce/pkg/experimental/apis/workload/v1alpha1\"\n\t\"k8s.io/ingress-gce/pkg/experimental/workload/client/clientset/versioned/scheme\"\n)\n\ntype NetworkingV1alpha1Interface interface {\n\tRESTClient() rest.Interface\n\tWorkloadsGetter\n}\n\n\ntype NetworkingV1alpha1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *NetworkingV1alpha1Client) Workloads(namespace string) WorkloadInterface {\n\treturn newWorkloads(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*NetworkingV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &NetworkingV1alpha1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *NetworkingV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *NetworkingV1alpha1Client {\n\treturn &NetworkingV1alpha1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc (c *NetworkingV1alpha1Client) RESTClient() rest.Interface ", "output": "{\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}"} {"input": "package daemon\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/docker/docker/nat\"\n\t\"github.com/docker/docker/runconfig\"\n)\n\n\n\nfunc mergeLxcConfIntoOptions(hostConfig *runconfig.HostConfig) ([]string, error) {\n\tif hostConfig == nil {\n\t\treturn nil, nil\n\t}\n\n\tout := []string{}\n\n\tif lxcConf := hostConfig.LxcConf; lxcConf != nil {\n\t\tlxSlice := lxcConf.Slice()\n\t\tfor _, pair := range lxSlice {\n\t\t\tif !strings.Contains(pair.Key, \".\") {\n\t\t\t\treturn nil, errors.New(\"Illegal Key passed into LXC Configurations\")\n\t\t\t}\n\t\t\tparts := strings.SplitN(pair.Key, \".\", 2)\n\t\t\tout = append(out, fmt.Sprintf(\"%s=%s\", parts[1], pair.Value))\n\t\t}\n\t}\n\n\treturn out, nil\n}\n\nfunc migratePortMappings(config *runconfig.Config, hostConfig *runconfig.HostConfig) error ", "output": "{\n\tif config.PortSpecs != nil {\n\t\tports, bindings, err := nat.ParsePortSpecs(config.PortSpecs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tconfig.PortSpecs = nil\n\t\tif len(bindings) > 0 {\n\t\t\tif hostConfig == nil {\n\t\t\t\thostConfig = &runconfig.HostConfig{}\n\t\t\t}\n\t\t\thostConfig.PortBindings = bindings\n\t\t}\n\n\t\tif config.ExposedPorts == nil {\n\t\t\tconfig.ExposedPorts = make(nat.PortSet, len(ports))\n\t\t}\n\t\tfor k, v := range ports {\n\t\t\tconfig.ExposedPorts[k] = v\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package lua\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/raggaer/castro/app/util\"\n\t\"github.com/yuin/gopher-lua\"\n)\n\n\nfunc SetI18nMetaTable(luaState *lua.LState) {\n\ti18nMetaTable := luaState.NewTypeMetatable(I18nMetaTableName)\n\tluaState.SetGlobal(I18nMetaTableName, i18nMetaTable)\n\n\tluaState.SetFuncs(i18nMetaTable, i18nMethods)\n}\n\n\n\n\n\nfunc GetLanguageIndex(L *lua.LState) int {\n\tlang := L.ToString(2)\n\n\ti := L.ToString(3)\n\n\targs := []interface{}{}\n\tx := 4\n\n\tfor {\n\t\tv := L.Get(x)\n\t\tif v == lua.LNil {\n\t\t\tbreak\n\t\t}\n\t\targs = append(args, ValueToGo(v))\n\t\tx++\n\t}\n\n\tlangFile, ok := util.LanguageFiles.Get(lang)\n\tif ok {\n\t\tlangStr, ok := langFile.Data[i]\n\t\tif ok {\n\t\t\tL.Push(lua.LString(fmt.Sprintf(langStr, args...)))\n\t\t\treturn 1\n\t\t}\n\t}\n\n\tlangFile, ok = util.LanguageFiles.Get(\"default\")\n\n\tlangStr, ok := langFile.Data[i]\n\tif ok {\n\t\tL.Push(lua.LString(fmt.Sprintf(langStr, args...)))\n\t\treturn 1\n\t}\n\n\tL.Push(lua.LNil)\n\treturn 1\n}\n\nfunc SetI18nUserData(luaState *lua.LState, lang []string) ", "output": "{\n\ti18nMetatable := luaState.GetTypeMetatable(I18nMetaTableName)\n\n\tluaState.SetField(i18nMetatable, \"Language\", StringSliceToTable(lang))\n}"} {"input": "package scan\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"h12.io/dfa\"\n)\n\ntype Matcher struct {\n\t*dfa.M\n\tEOF int\n\tIllegal int\n\n\tfast *dfa.FastM\n}\ntype MID struct {\n\tM interface{}\n\tID int\n}\n\nfunc NewMatcher(eof, illegal int, mids []MID) *Matcher {\n\tm := or(mids)\n\tfast := m.ToFast()\n\treturn &Matcher{\n\t\tEOF: eof,\n\t\tIllegal: illegal,\n\t\tM: m,\n\t\tfast: fast}\n}\n\n\n\nfunc (m *Matcher) Size() int {\n\treturn m.fast.Size()\n}\n\nfunc (m *Matcher) Count() int {\n\treturn m.fast.Count()\n}\n\nfunc (m *Matcher) WriteGo(w io.Writer, pac string) {\n\tfmt.Fprintln(w, \"&scan.Matcher{\")\n\tfmt.Fprintf(w, \"EOF: %d,\\n\", m.EOF)\n\tfmt.Fprintf(w, \"Illegal: %d,\\n\", m.Illegal)\n\tfmt.Fprint(w, \"M: \")\n\tm.M.WriteGo(w, pac)\n\tfmt.Fprintln(w, \"}\")\n}\n\nfunc or(mids []MID) *dfa.M {\n\tms := make([]interface{}, len(mids))\n\tfor i, mid := range mids {\n\t\tvar m *dfa.M\n\t\tswitch o := mid.M.(type) {\n\t\tcase *dfa.M:\n\t\t\tm = o\n\t\tcase string:\n\t\t\tm = dfa.Str(o)\n\t\tdefault:\n\t\t\tpanic(\"member M of MID should be type of either string or *M\")\n\t\t}\n\t\tms[i] = m.As(mid.ID)\n\t}\n\treturn dfa.Or(ms...)\n}\n\nfunc (m *Matcher) Init() *Matcher ", "output": "{\n\tm.fast = m.M.ToFast()\n\treturn m\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\n\n\n\n\ntype ConsoleHistory struct {\n\n\tAvailabilityDomain *string `mandatory:\"true\" json:\"availabilityDomain\"`\n\n\tCompartmentId *string `mandatory:\"true\" json:\"compartmentId\"`\n\n\tId *string `mandatory:\"true\" json:\"id\"`\n\n\tInstanceId *string `mandatory:\"true\" json:\"instanceId\"`\n\n\tLifecycleState ConsoleHistoryLifecycleStateEnum `mandatory:\"true\" json:\"lifecycleState\"`\n\n\tTimeCreated *common.SDKTime `mandatory:\"true\" json:\"timeCreated\"`\n\n\tDefinedTags map[string]map[string]interface{} `mandatory:\"false\" json:\"definedTags\"`\n\n\tDisplayName *string `mandatory:\"false\" json:\"displayName\"`\n\n\tFreeformTags map[string]string `mandatory:\"false\" json:\"freeformTags\"`\n}\n\n\n\n\ntype ConsoleHistoryLifecycleStateEnum string\n\n\nconst (\n\tConsoleHistoryLifecycleStateRequested ConsoleHistoryLifecycleStateEnum = \"REQUESTED\"\n\tConsoleHistoryLifecycleStateGettingHistory ConsoleHistoryLifecycleStateEnum = \"GETTING-HISTORY\"\n\tConsoleHistoryLifecycleStateSucceeded ConsoleHistoryLifecycleStateEnum = \"SUCCEEDED\"\n\tConsoleHistoryLifecycleStateFailed ConsoleHistoryLifecycleStateEnum = \"FAILED\"\n)\n\nvar mappingConsoleHistoryLifecycleState = map[string]ConsoleHistoryLifecycleStateEnum{\n\t\"REQUESTED\": ConsoleHistoryLifecycleStateRequested,\n\t\"GETTING-HISTORY\": ConsoleHistoryLifecycleStateGettingHistory,\n\t\"SUCCEEDED\": ConsoleHistoryLifecycleStateSucceeded,\n\t\"FAILED\": ConsoleHistoryLifecycleStateFailed,\n}\n\n\nfunc GetConsoleHistoryLifecycleStateEnumValues() []ConsoleHistoryLifecycleStateEnum {\n\tvalues := make([]ConsoleHistoryLifecycleStateEnum, 0)\n\tfor _, v := range mappingConsoleHistoryLifecycleState {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}\n\nfunc (m ConsoleHistory) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/tompscanlan/labreserved/models\"\n)\n\n\n\nfunc NewPostItemParams() *PostItemParams {\n\tvar ()\n\treturn &PostItemParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\nfunc NewPostItemParamsWithTimeout(timeout time.Duration) *PostItemParams {\n\tvar ()\n\treturn &PostItemParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype PostItemParams struct {\n\n\tAdditem *models.Item\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *PostItemParams) WithAdditem(Additem *models.Item) *PostItemParams {\n\to.Additem = Additem\n\treturn o\n}\n\n\n\n\nfunc (o *PostItemParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error ", "output": "{\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif o.Additem == nil {\n\t\to.Additem = new(models.Item)\n\t}\n\n\tif err := r.SetBodyParam(o.Additem); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package volume\n\nimport \"testing\"\n\n\n\nfunc TestVolumesOps(t *testing.T) ", "output": "{\n\treturn\n}"} {"input": "package semver\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/blang/semver\"\n\t\"github.com/pivotal-cf/go-pivnet/v7/logger\"\n)\n\ntype SemverConverter struct {\n\tlogger logger.Logger\n}\n\nfunc NewSemverConverter(logger logger.Logger) *SemverConverter {\n\treturn &SemverConverter{logger}\n}\n\n\n\n\n\n\nfunc (s SemverConverter) ToValidSemver(input string) (semver.Version, error) ", "output": "{\n\tv, err := semver.Parse(input)\n\tif err == nil {\n\t\treturn v, nil\n\t}\n\n\ts.logger.Info(fmt.Sprintf(\n\t\t\"failed to parse semver: '%s', appending zeros and trying again\",\n\t\tinput,\n\t))\n\tmaybeSemver := input\n\n\tsegs := strings.SplitN(maybeSemver, \".\", 3)\n\tswitch len(segs) {\n\tcase 2:\n\t\tmaybeSemver += \".0\"\n\tcase 1:\n\t\tmaybeSemver += \".0.0\"\n\t}\n\n\tv, err = semver.Parse(maybeSemver)\n\tif err == nil {\n\t\treturn v, nil\n\t}\n\n\ts.logger.Info(fmt.Sprintf(\n\t\t\"still failed to parse semver: '%s', giving up\",\n\t\tmaybeSemver,\n\t))\n\n\treturn semver.Version{}, err\n}"} {"input": "package livereload\n\nimport (\n\t\"bytes\"\n\t\"sync\"\n\n\t\"github.com/gorilla/websocket\"\n)\n\ntype connection struct {\n\tws *websocket.Conn\n\n\tsend chan []byte\n\n\tcloser sync.Once\n}\n\n\n\nfunc (c *connection) reader() {\n\tfor {\n\t\t_, message, err := c.ws.ReadMessage()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif bytes.Contains(message, []byte(`\"command\":\"hello\"`)) {\n\t\t\tc.send <- []byte(`{\n\t\t\t\t\"command\": \"hello\",\n\t\t\t\t\"protocols\": [ \"http:livereload.com/protocols/official-7\" ],\n\t\t\t\t\"serverName\": \"Hugo\"\n\t\t\t}`)\n\t\t}\n\t}\n\tc.ws.Close()\n}\n\nfunc (c *connection) writer() {\n\tfor message := range c.send {\n\t\terr := c.ws.WriteMessage(websocket.TextMessage, message)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tc.ws.Close()\n}\n\nfunc (c *connection) close() ", "output": "{\n\tc.closer.Do(func() {\n\t\tclose(c.send)\n\t})\n}"} {"input": "package yaml\n\nimport (\n\t\"github.com/pinpt/dialect/pkg\"\n\t\"github.com/pinpt/dialect/pkg/types\"\n)\n\ntype YAMLExaminer struct {\n}\n\n\n\nfunc (e *YAMLExaminer) NewExaminer() types.DialectExaminer {\n\tex := new(YAMLExaminer)\n\treturn ex\n}\n\nfunc init() {\n\ttypes.RegisterExaminer(\"YAML\", &YAMLExaminer{})\n}\n\nfunc (e *YAMLExaminer) Examine(language string, filename string, line *types.DialectLine) error ", "output": "{\n\tpkg.SingleSymbolProcessor(\"#\", line)\n\treturn nil\n}"} {"input": "package server\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"os/signal\"\n\n\t\"k8s.io/klog/v2\"\n)\n\nvar onlyOneSignalHandler = make(chan struct{})\nvar shutdownHandler chan os.Signal\n\n\n\n\n\n\nfunc SetupSignalHandler() <-chan struct{} {\n\treturn SetupSignalContext().Done()\n}\n\n\n\nfunc SetupSignalHandlerIgnoringFurtherSignals() <-chan struct{} {\n\treturn SetupSignalContextNotExiting().Done()\n}\n\n\n\n\n\n\n\n\nfunc SetupSignalContextNotExiting() context.Context {\n\treturn setupSignalContext(false)\n}\n\nfunc setupSignalContext(exitOnSecondSignal bool) context.Context {\n\tclose(onlyOneSignalHandler) \n\n\tshutdownHandler = make(chan os.Signal, 2)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tsignal.Notify(shutdownHandler, shutdownSignals...)\n\tgo func() {\n\t\t<-shutdownHandler\n\t\tcancel()\n\t\tif exitOnSecondSignal {\n\t\t\t<-shutdownHandler\n\t\t\tos.Exit(1)\n\t\t} else {\n\t\t\tfor {\n\t\t\t\t<-shutdownHandler\n\t\t\t\tklog.Infof(\"Termination signal has been received already. Ignoring signal.\")\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn ctx\n}\n\n\n\nfunc RequestShutdown() bool {\n\tif shutdownHandler != nil {\n\t\tselect {\n\t\tcase shutdownHandler <- shutdownSignals[0]:\n\t\t\treturn true\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc SetupSignalContext() context.Context ", "output": "{\n\treturn setupSignalContext(true)\n}"} {"input": "package fastlanestat\n\nimport (\n \"net/http\"\n\t\t\"html/template\"\n\n\n \n \"appengine\"\n \t\"appengine/datastore\"\n)\n\ntype ViewContext struct {\n\tPricePoints []PricePoint\n}\n\n\n\nfunc viewStatsHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n \tc := appengine.NewContext(r)\n\n\tq := datastore.NewQuery(\"PricePoint\").\n\t Order(\"-PointInTime\").\n Limit(5000)\n\n\tvar pricePoints []PricePoint\n\tq.GetAll(c, &pricePoints)\n\n\tviewContext := ViewContext{ PricePoints: pricePoints }\n\tt, _ := template.ParseFiles(\"templates/simple.htmltemplate\")\n\tt.Execute(w, viewContext)\n}"} {"input": "package event\n\nimport (\n\t\"fmt\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\n\ntype Increment struct {\n\tName string\n\tValue int64\n}\n\nfunc (e *Increment) StatClass() string {\n\treturn \"counter\"\n}\n\n\n\n\n\nfunc (e *Increment) Reset() {\n\te.Value = 0\n}\n\n\nfunc (e Increment) Payload() interface{} {\n\treturn e.Value\n}\n\n\nfunc (e Increment) Stats(tick time.Duration) []string {\n\treturn []string{fmt.Sprintf(\"%s:%d|c\", e.Name, e.Value)}\n}\n\n\nfunc (e Increment) Key() string {\n\treturn e.Name\n}\n\n\nfunc (e *Increment) SetKey(key string) {\n\te.Name = key\n}\n\n\nfunc (e Increment) Type() int {\n\treturn EventIncr\n}\n\n\nfunc (e Increment) TypeString() string {\n\treturn \"Increment\"\n}\n\n\nfunc (e Increment) String() string {\n\treturn fmt.Sprintf(\"{Type: %s, Key: %s, Value: %d}\", e.TypeString(), e.Name, e.Value)\n}\n\nfunc (e *Increment) Update(e2 Event) error ", "output": "{\n\tif e.Type() != e2.Type() {\n\t\treturn fmt.Errorf(\"statsd event type conflict: %s vs %s \", e.String(), e2.String())\n\t}\n\tatomic.AddInt64(&e.Value, e2.Payload().(int64))\n\treturn nil\n}"} {"input": "package flagutil\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net/url\"\n\n\t\"github.com/sirupsen/logrus\"\n\n\t\"k8s.io/test-infra/prow/bugzilla\"\n\t\"k8s.io/test-infra/prow/config/secret\"\n)\n\n\ntype BugzillaOptions struct {\n\tendpoint string\n\tgithubExternalTrackerId uint\n\tApiKeyPath string\n}\n\n\n\n\n\nfunc (o *BugzillaOptions) Validate(dryRun bool) error {\n\tif o.endpoint == \"\" {\n\t\tlogrus.Info(\"empty -bugzilla-endpoint, will not create Bugzilla client\")\n\t\treturn nil\n\t}\n\n\tif _, err := url.ParseRequestURI(o.endpoint); err != nil {\n\t\treturn fmt.Errorf(\"invalid -bugzilla-endpoint URI: %q\", o.endpoint)\n\t}\n\n\tif o.ApiKeyPath == \"\" {\n\t\tlogrus.Info(\"empty -bugzilla-api-key-path, will use anonymous Bugzilla client\")\n\t}\n\n\treturn nil\n}\n\n\nfunc (o *BugzillaOptions) BugzillaClient(secretAgent *secret.Agent) (bugzilla.Client, error) {\n\tif o.endpoint == \"\" {\n\t\treturn nil, fmt.Errorf(\"empty -bugzilla-endpoint, cannot create Bugzilla client\")\n\t}\n\n\tvar generator *func() []byte\n\tif o.ApiKeyPath == \"\" {\n\t\tgeneratorFunc := func() []byte {\n\t\t\treturn []byte{}\n\t\t}\n\t\tgenerator = &generatorFunc\n\t} else {\n\t\tif secretAgent == nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot store token from %q without a secret agent\", o.ApiKeyPath)\n\t\t}\n\t\tgeneratorFunc := secretAgent.GetTokenGenerator(o.ApiKeyPath)\n\t\tgenerator = &generatorFunc\n\t}\n\n\treturn bugzilla.NewClient(*generator, o.endpoint, o.githubExternalTrackerId), nil\n}\n\nfunc (o *BugzillaOptions) AddFlags(fs *flag.FlagSet) ", "output": "{\n\tfs.StringVar(&o.endpoint, \"bugzilla-endpoint\", \"\", \"Bugzilla's API endpoint.\")\n\tfs.UintVar(&o.githubExternalTrackerId, \"bugzilla-github-external-tracker-id\", 0, \"The ext_type_id for GitHub external bugs, optional.\")\n\tfs.StringVar(&o.ApiKeyPath, \"bugzilla-api-key-path\", \"\", \"Path to the file containing the Bugzilla API key.\")\n}"} {"input": "package syncbase_test\n\nimport (\n\t\"regexp\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"v.io/v23/syncbase\"\n)\n\nconst (\n\tuuidLoopInvocations int = 100\n)\n\n\n\nfunc TestUUIDCollisions(t *testing.T) {\n\tvar mutex sync.Mutex\n\tvar waitGroup sync.WaitGroup\n\tuuidMap := make(map[string]bool)\n\n\tcreateUUID := func() {\n\t\tmutex.Lock()\n\t\tdefer mutex.Unlock()\n\t\tuuidMap[syncbase.UUID()] = true\n\t\twaitGroup.Done()\n\t}\n\n\tfor i := 0; i < uuidLoopInvocations; i++ {\n\t\twaitGroup.Add(1)\n\t\tgo createUUID()\n\t}\n\n\twaitGroup.Wait()\n\n\tif len(uuidMap) != uuidLoopInvocations {\n\t\tt.Errorf(\"UUID collision for %d UUIDs\", uuidLoopInvocations-len(uuidMap))\n\t}\n}\n\nfunc TestUUIDFormat(t *testing.T) ", "output": "{\n\tuuid := syncbase.UUID()\n\tregexp := regexp.MustCompile(\"(?i)^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$\")\n\tif !regexp.MatchString(uuid) {\n\t\tt.Errorf(\"Incorrect UUID format: %v\", uuid)\n\t}\n}"} {"input": "package identify\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewPostNodesIdentifierObmIdentifyParams() *PostNodesIdentifierObmIdentifyParams {\n\tvar ()\n\treturn &PostNodesIdentifierObmIdentifyParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\nfunc NewPostNodesIdentifierObmIdentifyParamsWithTimeout(timeout time.Duration) *PostNodesIdentifierObmIdentifyParams {\n\tvar ()\n\treturn &PostNodesIdentifierObmIdentifyParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype PostNodesIdentifierObmIdentifyParams struct {\n\n\tBody *bool\n\tIdentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *PostNodesIdentifierObmIdentifyParams) WithBody(body *bool) *PostNodesIdentifierObmIdentifyParams {\n\to.Body = body\n\treturn o\n}\n\n\n\n\n\nfunc (o *PostNodesIdentifierObmIdentifyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetBodyParam(o.Body); err != nil {\n\t\treturn err\n\t}\n\n\tif err := r.SetPathParam(\"identifier\", o.Identifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (o *PostNodesIdentifierObmIdentifyParams) WithIdentifier(identifier string) *PostNodesIdentifierObmIdentifyParams ", "output": "{\n\to.Identifier = identifier\n\treturn o\n}"} {"input": "package query\n\nimport (\n\t\"encoding/json\"\n\t\"reflect\"\n)\n\nfunc toJson(v interface{}) ([]byte, error) {\n\treturn json.Marshal(v)\n}\n\nfunc wrapper(name string, v interface{}) map[string]interface{} {\n\tquery := map[string]interface{}{\n\t\tname: v,\n\t}\n\treturn query\n}\n\nfunc convert(value reflect.Value) interface{} {\n\tswitch value.Kind() {\n\tcase reflect.Slice:\n\t\tvar res []interface{}\n\t\tfor i := 0; i < value.Len(); i++ {\n\t\t\tres = append(res, convert(value.Index(i)))\n\t\t}\n\t\treturn res\n\tcase reflect.Ptr:\n\t\tif !value.IsNil() {\n\t\t\treturn convert(value.Elem())\n\t\t}\n\tcase reflect.String:\n\t\treturn value.String()\n\tcase reflect.Float64:\n\t\treturn value.Float()\n\tcase reflect.Int:\n\t\treturn value.Int()\n\tcase reflect.Bool:\n\t\treturn value.Bool()\n\t}\n\treturn value.Interface()\n}\n\n\n\nfunc convertStruct(x interface{}) interface{} {\n\tquery := make(map[string]interface{})\n\n\tt := reflect.ValueOf(x).Type()\n\tv := reflect.ValueOf(x)\n\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tfield := t.Field(i)\n\t\tvalue := v.FieldByName(field.Name)\n\t\ttag := field.Tag.Get(\"json\")\n\t\tif tag == \"-\" {\n\t\t\tcontinue\n\t\t}\n\t\tif convertable(value) {\n\t\t\tquery[tag] = convert(value)\n\t\t}\n\t}\n\n\treturn query\n\n}\n\nfunc convertable(value reflect.Value) bool ", "output": "{\n\tswitch value.Kind() {\n\tcase reflect.Slice:\n\t\treturn value.Len() > 0\n\tcase reflect.Ptr:\n\t\treturn !value.IsNil()\n\t}\n\treturn true\n}"} {"input": "package load\n\nimport (\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"../common\"\n)\n\nfunc Avg() (*AvgStat, error) {\n\tvalues, err := common.DoSysctrl(\"vm.loadavg\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tload1, err := strconv.ParseFloat(values[0], 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tload5, err := strconv.ParseFloat(values[1], 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tload15, err := strconv.ParseFloat(values[2], 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := &AvgStat{\n\t\tLoad1: float64(load1),\n\t\tLoad5: float64(load5),\n\t\tLoad15: float64(load15),\n\t}\n\n\treturn ret, nil\n}\n\n\n\n\n\n\n\nfunc Misc() (*MiscStat, error) ", "output": "{\n\tbin, err := exec.LookPath(\"ps\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout, err := invoke.Command(bin, \"axo\", \"state\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlines := strings.Split(string(out), \"\\n\")\n\n\tret := MiscStat{}\n\tfor _, l := range lines {\n\t\tif strings.Contains(l, \"R\") {\n\t\t\tret.ProcsRunning++\n\t\t} else if strings.Contains(l, \"U\") {\n\t\t\tret.ProcsBlocked++\n\t\t}\n\t}\n\n\treturn &ret, nil\n}"} {"input": "package http\n\nimport (\n\t\"strconv\"\n\n\t\"go-common/app/service/main/archive/api\"\n\t\"go-common/library/ecode\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\n\n\nfunc videoShot(c *bm.Context) {\n\tv := new(struct {\n\t\tAid int64 `form:\"aid\" validate:\"min=1\"`\n\t\tCid int64 `form:\"cid\"`\n\t\tIndex bool `form:\"index\"`\n\t})\n\tif err := c.Bind(v); err != nil {\n\t\treturn\n\t}\n\tc.JSON(playSvr.VideoShot(c, v.Aid, v.Cid, v.Index))\n}\n\nfunc playURLToken(c *bm.Context) {\n\tvar (\n\t\taid, cid, mid int64\n\t\terr error\n\t)\n\tparams := c.Request.Form\n\taidStr := params.Get(\"aid\")\n\tif aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil {\n\t\tc.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\tcid, _ = strconv.ParseInt(params.Get(\"cid\"), 10, 64)\n\tmidStr, _ := c.Get(\"mid\")\n\tmid = midStr.(int64)\n\tc.JSON(playSvr.PlayURLToken(c, mid, aid, cid))\n}\n\nfunc pageList(c *bm.Context) ", "output": "{\n\tvar (\n\t\taid int64\n\t\terr error\n\t\tpages []*api.Page\n\t)\n\taidStr := c.Request.Form.Get(\"aid\")\n\tif aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil || aid <= 0 {\n\t\tc.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\tif pages, err = playSvr.PageList(c, aid); err != nil {\n\t\tc.JSON(nil, err)\n\t\treturn\n\t}\n\tif len(pages) == 0 {\n\t\tc.JSON(nil, ecode.NothingFound)\n\t\treturn\n\t}\n\tc.JSON(pages, nil)\n}"} {"input": "package util\n\nimport (\n\tauthorizationapi \"k8s.io/kubernetes/pkg/apis/authorization\"\n\t\"k8s.io/kubernetes/pkg/auth/authorizer\"\n\t\"k8s.io/kubernetes/pkg/auth/user\"\n)\n\n\nfunc ResourceAttributesFrom(user user.Info, in authorizationapi.ResourceAttributes) authorizer.AttributesRecord {\n\treturn authorizer.AttributesRecord{\n\t\tUser: user,\n\t\tVerb: in.Verb,\n\t\tNamespace: in.Namespace,\n\t\tAPIGroup: in.Group,\n\t\tResource: in.Resource,\n\t\tResourceRequest: true,\n\t}\n}\n\n\n\n\nfunc NonResourceAttributesFrom(user user.Info, in authorizationapi.NonResourceAttributes) authorizer.AttributesRecord ", "output": "{\n\treturn authorizer.AttributesRecord{\n\t\tUser: user,\n\t\tResourceRequest: false,\n\t\tPath: in.Path,\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nfunc ToJson(data interface{}) string {\n\tb, err := json.Marshal(data)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\treturn string(b)\n}\n\n\n\nfunc IsIgnoreRequest(url string, contentType string, statusCode int) bool {\n\tif statusCode != 200 {\n\t\treturn true\n\t}\n\tif !strings.Contains(contentType, \"text\") && !strings.Contains(contentType, \"application\") {\n\t\treturn true\n\t}\n\n\tswitch {\n\tcase strings.Contains(contentType, \"text/css\"):\n\t\tfallthrough\n\tcase strings.Contains(contentType, \"text/javascript\"):\n\t\treturn true\n\tdefault:\n\t\tbreak\n\t}\n\tidx := strings.Index(url, \"?\")\n\tif idx >= 0 {\n\t\turl = url[:idx]\n\t}\n\text := strings.ToLower(filepath.Ext(url))\n\treturn ext == \".js\" || ext == \".css\" ||\n\t\text == \".jpg\" || ext == \".jpeg\" || ext == \".gif\" || ext == \".png\" ||\n\t\text == \".bmp\" || ext == \".ico\" || ext == \".woff\" || ext == \".font\" ||\n\t\text == \".ttf\" || ext == \".svg\" || ext == \".pdf\" || ext == \".txt\"\n}\n\nfunc GetHostIp() string ", "output": "{\n\tip := \"127.0.0.1\"\n\n\taddrs, _ := net.InterfaceAddrs()\n\tfor _, a := range addrs {\n\t\tipnet := net.ParseIP(a.String())\n\t\tif ipnet == nil {\n\t\t\tipnet, _, _ = net.ParseCIDR(a.String())\n\t\t}\n\t\tif ipnet != nil && !ipnet.IsLoopback() && !ipnet.IsUnspecified() {\n\t\t\tif ipnet.To4() != nil {\n\t\t\t\tip = ipnet.String()\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ip\n}"} {"input": "package coverage\n\nimport (\n\t\"github.com/skydive-project/skydive/cmd/skydive\"\n)\n\n\n\nfunc skdyiveCoverage() ", "output": "{\n\tskydive.RootCmd.Execute()\n}"} {"input": "package sanitize\n\nimport(\n\t\"os\"\n\t\"encoding/json\"\n)\n\n\nfunc WhitelistFromFile(filepath string) (*Whitelist, error) {\n\tbytes, err := readFileToBytes(filepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twhitelist, err := NewWhitelist(bytes)\n\treturn whitelist, nil\n}\n\n\n\n\n\nfunc NewWhitelist(jsonData []byte) (*Whitelist, error) {\n\tconfiguration := &Whitelist{}\n\terr := json.Unmarshal(jsonData, configuration)\n\n\treturn configuration, err\n}\n\nfunc readFileToBytes(filepath string) ([]byte, error) ", "output": "{\n\tf, err := os.Open(filepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfileInfo, err := f.Stat()\n\tbytes := make([]byte, fileInfo.Size())\n\n\t_, err = f.Read(bytes)\n\treturn bytes, err\n}"} {"input": "package server\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"net/http\"\n\n\t\"github.com/docker/docker/daemon\"\n)\n\n\n\n\nfunc (s *Server) AcceptConnections(d *daemon.Daemon) {\n\ts.daemon = d\n\tselect {\n\tcase <-s.start:\n\tdefault:\n\t\tclose(s.start)\n\t}\n}\n\nfunc allocateDaemonPort(addr string) error {\n\treturn nil\n}\n\nfunc (s *Server) newServer(proto, addr string) (serverCloser, error) ", "output": "{\n\tvar (\n\t\terr error\n\t\tl net.Listener\n\t)\n\tswitch proto {\n\tcase \"tcp\":\n\t\tl, err = s.initTcpSocket(addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\tdefault:\n\t\treturn nil, errors.New(\"Invalid protocol format. Windows only supports tcp.\")\n\t}\n\treturn &HttpServer{\n\t\t&http.Server{\n\t\t\tAddr: addr,\n\t\t\tHandler: s.router,\n\t\t},\n\t\tl,\n\t}, nil\n}"} {"input": "package servicecontrol\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\nvar (\n\tsshServiceName = \"ssh\"\n\tdisableSshFilename = \"/etc/ssh/sshd_not_to_be_run\"\n)\n\ntype SshService struct {\n\tdefaults *ServiceControlSettings\n}\n\nfunc getSshSettings() *ServiceControlSettings {\n\tis_enabled := true\n\tinfo, _ := os.Stat(disableSshFilename)\n\tif info != nil {\n\t\tis_enabled = false\n\t}\n\n\treturn &ServiceControlSettings{\n\t\tEnabled: is_enabled,\n\t}\n}\n\nfunc NewSshService() *SshService {\n\treturn &SshService{\n\t\tdefaults: getSshSettings(),\n\t}\n}\n\nfunc (s *SshService) IsAvailable() bool {\n\treturn true\n}\n\nfunc (s *SshService) GetDefaults() *ServiceControlSettings {\n\treturn s.defaults\n}\n\nfunc (s *SshService) ApplySettings(settings *ServiceControlSettings) error {\n\tvar action string\n\trunning, statusErr := isServiceRunning(sshServiceName)\n\tif settings.Enabled {\n\t\tif running && statusErr == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\taction = \"start\"\n\t\tif err := removeFile(disableSshFilename); err != nil {\n\t\t\tlog.Println(\"Could not enable ssh service\", err)\n\t\t}\n\t} else {\n\t\tif !running && statusErr == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\taction = \"stop\"\n\t\tif err := touchFile(disableSshFilename); err != nil {\n\t\t\tlog.Println(\"Could not disable ssh service\", err)\n\t\t}\n\t}\n\n\treturn runServiceCommand(sshServiceName, action)\n}\n\nfunc (s *SshService) QuerySettings() (*ServiceControlSettings, error) {\n\treturn getSshSettings(), nil\n}\n\n\n\nfunc init() ", "output": "{\n\tRegisterService(\"ssh\", NewSshService())\n}"} {"input": "package test\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\n\ntype SuiteSuite struct {\n\tSuite\n}\n\n\nfunc TestTestSuite(t *testing.T) {\n\tRunSuite(t, new(SuiteSuite))\n}\n\n\nfunc (t *SuiteSuite) GetFileLine() {\n\texpected := \"drydock/runtime/base/test/test_suite_test.go:39\"\n\twrapper := func() string {\n\t\treturn t.getFileLine()\n\t}\n\tif s := wrapper(); !strings.HasSuffix(s, expected) {\n\t\tt.Errorf(\"Invalid file and line: Got: %s, Want: %s\", s, expected)\n\t}\n}\n\n\nfunc (t *SuiteSuite) TestInfof() {\n\tt.Infof(\"This is a log statement produced by t.Infof\")\n}\n\n\n\nfunc (t *SuiteSuite) VerifyMethodsWrongSignatureSkipped1(x int) {\n\tt.Fatalf(\"This should never run.\")\n}\n\n\n\n\n\nfunc (t *SuiteSuite) VerifyMethodsWrongSignatureSkipped2() int ", "output": "{\n\tt.Fatalf(\"This should never run.\")\n\treturn 0\n}"} {"input": "package drone\n\nimport (\n\t\"fmt\"\n)\n\ntype UserService struct {\n\t*Client\n}\n\n\nfunc (s *UserService) Get(remote, login string) (*User, error) {\n\tvar path = fmt.Sprintf(\"/api/users/%s/%s\", remote, login)\n\tvar user = User{}\n\tvar err = s.run(\"GET\", path, nil, &user)\n\treturn &user, err\n}\n\n\nfunc (s *UserService) GetCurrent() (*User, error) {\n\tvar user = User{}\n\tvar err = s.run(\"GET\", \"/api/user\", nil, &user)\n\treturn &user, err\n}\n\n\nfunc (s *UserService) Create(remote, login string) (*User, error) {\n\tvar path = fmt.Sprintf(\"/api/users/%s/%s\", remote, login)\n\tvar user = User{}\n\tvar err = s.run(\"POST\", path, nil, &user)\n\treturn &user, err\n}\n\n\nfunc (s *UserService) Delete(remote, login string) error {\n\tvar path = fmt.Sprintf(\"/api/users/%s/%s\", remote, login)\n\treturn s.run(\"DELETE\", path, nil, nil)\n}\n\n\n\n\nfunc (s *UserService) List() ([]*User, error) ", "output": "{\n\tvar users []*User\n\tvar err = s.run(\"GET\", \"/api/users\", nil, &users)\n\treturn users, err\n}"} {"input": "package filteredFactory\n\nimport (\n\tcontext \"context\"\n\n\tv1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\texternalversions \"knative.dev/eventing-natss/pkg/client/informers/externalversions\"\n\tclient \"knative.dev/eventing-natss/pkg/client/injection/client\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Default.RegisterInformerFactory(withInformerFactory)\n}\n\n\ntype Key struct {\n\tSelector string\n}\n\ntype LabelKey struct{}\n\nfunc WithSelectors(ctx context.Context, selector ...string) context.Context {\n\treturn context.WithValue(ctx, LabelKey{}, selector)\n}\n\nfunc withInformerFactory(ctx context.Context) context.Context {\n\tc := client.Get(ctx)\n\tuntyped := ctx.Value(LabelKey{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch labelkey from context.\")\n\t}\n\tlabelSelectors := untyped.([]string)\n\tfor _, selector := range labelSelectors {\n\t\topts := []externalversions.SharedInformerOption{}\n\t\tif injection.HasNamespaceScope(ctx) {\n\t\t\topts = append(opts, externalversions.WithNamespace(injection.GetNamespaceScope(ctx)))\n\t\t}\n\t\topts = append(opts, externalversions.WithTweakListOptions(func(l *v1.ListOptions) {\n\t\t\tl.LabelSelector = selector\n\t\t}))\n\t\tctx = context.WithValue(ctx, Key{Selector: selector},\n\t\t\texternalversions.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...))\n\t}\n\treturn ctx\n}\n\n\n\n\nfunc Get(ctx context.Context, selector string) externalversions.SharedInformerFactory ", "output": "{\n\tuntyped := ctx.Value(Key{Selector: selector})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panicf(\n\t\t\t\"Unable to fetch knative.dev/eventing-natss/pkg/client/informers/externalversions.SharedInformerFactory with selector %s from context.\", selector)\n\t}\n\treturn untyped.(externalversions.SharedInformerFactory)\n}"} {"input": "package path\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\n\n\n\n\ntype P []string\n\n\n\n\n\n\nfunc Newf(path string, args ...interface{}) P {\n\treturn New(fmt.Sprintf(path, args...))\n}\n\n\nfunc (path P) String() string {\n\tbuffer := new(bytes.Buffer)\n\n\tfor i, item := range path {\n\t\tbuffer.WriteString(item)\n\n\t\tif i < len(path)-1 {\n\t\t\tbuffer.WriteString(\".\")\n\t\t}\n\t}\n\n\treturn buffer.String()\n}\n\n\nfunc (path P) Last() string { return path[len(path)-1] }\n\nfunc New(path string) P ", "output": "{\n\treturn strings.Split(path, \".\")\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n for i :=0; i<10; i++ {\n go Add(i, i)\n }\n}\n\nfunc Add(x, y int) ", "output": "{\n z := x + y\n fmt.Println(z)\n}"} {"input": "package net_test\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/corestoreio/csfw/net\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype h1 struct{}\n\nfunc (h1) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(`h1 called`))\n}\n\n\n\nfunc TestHttpMethodOverride(t *testing.T) {\n\thndlr := net.Adapt(\n\t\th1{},\n\t\tnet.SupportXHTTPMethodOverride())\n\tw := httptest.NewRecorder()\n\treq, err := http.NewRequest(net.HTTPMethodGet, \"http:example.com/foo?_method=\"+net.HTTPMethodPatch, nil)\n\tassert.NoError(t, err)\n\thndlr.ServeHTTP(w, req)\n\tassert.Equal(t, net.HTTPMethodPatch, req.Method)\n\tassert.Equal(t, \"h1 called\", w.Body.String())\n\n\tw = httptest.NewRecorder()\n\treq, err = http.NewRequest(net.HTTPMethodGet, \"http:example.com/foo?_method=KARATE\", nil)\n\tassert.NoError(t, err)\n\thndlr.ServeHTTP(w, req)\n\tassert.Equal(t, net.HTTPMethodGet, req.Method)\n\n\tw = httptest.NewRecorder()\n\treq, err = http.NewRequest(net.HTTPMethodGet, \"http:example.com/foobar\", nil)\n\tassert.NoError(t, err)\n\thndlr.ServeHTTP(w, req)\n\tassert.Equal(t, net.HTTPMethodGet, req.Method)\n\n}\n\nfunc TestAdapters(t *testing.T) ", "output": "{\n\thndlr := net.Adapt(\n\t\th1{},\n\t\tnet.SupportXHTTPMethodOverride(),\n\t\tnet.WithHeader(\"X-Men\", \"Y-Women\"))\n\tw := httptest.NewRecorder()\n\treq, err := http.NewRequest(net.HTTPMethodGet, \"http:example.com/foo\", nil)\n\treq.Header.Set(net.HTTPMethodOverrideHeader, net.HTTPMethodPut)\n\tassert.NoError(t, err)\n\thndlr.ServeHTTP(w, req)\n\tassert.Equal(t, net.HTTPMethodPut, req.Method)\n\tassert.Equal(t, \"h1 called\", w.Body.String())\n\tassert.Equal(t, \"Y-Women\", w.Header().Get(\"X-Men\"))\n}"} {"input": "package cliplugins\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/docker/cli/cli/config\"\n\t\"github.com/docker/cli/cli/config/configfile\"\n\t\"gotest.tools/assert\"\n\t\"gotest.tools/fs\"\n\t\"gotest.tools/icmd\"\n)\n\n\n\nfunc prepare(t *testing.T) (func(args ...string) icmd.Cmd, *configfile.ConfigFile, func()) ", "output": "{\n\tcfg := fs.NewDir(t, \"plugin-test\",\n\t\tfs.WithFile(\"config.json\", fmt.Sprintf(`{\"cliPluginsExtraDirs\": [%q]}`, os.Getenv(\"DOCKER_CLI_E2E_PLUGINS_EXTRA_DIRS\"))),\n\t)\n\trun := func(args ...string) icmd.Cmd {\n\t\treturn icmd.Command(\"docker\", append([]string{\"--config\", cfg.Path()}, args...)...)\n\t}\n\tcleanup := func() {\n\t\tcfg.Remove()\n\t}\n\tcfgfile, err := config.Load(cfg.Path())\n\tassert.NilError(t, err)\n\n\treturn run, cfgfile, cleanup\n\n}"} {"input": "package simulatorsetup\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc ApplyDataToSim(deviceName string, deviceVersion string) {\n\tdeviceList, _ := getDevices()\n\n\tfmt.Println(\"Apply Device: \" + deviceName)\n\n\tif deviceVersion == \"latest\" {\n\t\tlatestIosVersion := deviceList.getLatestIOS()\n\t\tdeviceList = deviceList.filterByIOS(latestIosVersion, true)\n\t}\n\n\tdeviceList = deviceList.filterByName(deviceName)\n\tfor _, device := range deviceList.Devices {\n\t\tfmt.Println(device)\n\t\tdevice.applySimulatorData(true)\n\t}\n}\n\nfunc DumpSimData(deviceName string) {\n\tdeviceList, _ := getDevices()\n\tlatestIosVersion := deviceList.getLatestIOS()\n\n\tdeviceList = deviceList.filterByIOS(latestIosVersion, true)\n\tdeviceList = deviceList.filterByName(deviceName)\n\n\tdeviceCount := len(deviceList.Devices)\n\tif deviceCount == 0 {\n\t\tfmt.Println(\"Device \", deviceName, \" not found\")\n\t\tfmt.Println(\"Available devices:\")\n\t\tdeviceList, _ = getDevices()\n\t\tdeviceList.filterByIOS(latestIosVersion, true).printDeviceList()\n\t\tos.Exit(1)\n\t} else if deviceCount != 1 {\n\t\tfmt.Println(\"Can only dump one device, matched \", deviceCount, \" devices\")\n\t\tdeviceList.printDeviceList()\n\t\tos.Exit(1)\n\t} else {\n\t\tdeviceList.Devices[0].dumpSimulatorData([]string{\"Containers\", \"Documents\", \"Downloads\", \"Library\", \"Media\"})\n\t}\n}\n\n\n\nfunc (deviceList DeviceList) printDeviceList() ", "output": "{\n\tfor _, device := range deviceList.Devices {\n\t\tfmt.Println(device.Name)\n\t}\n}"} {"input": "package gota\n\n\ntype RSI struct {\n\temaUp EMA\n\temaDown EMA\n\tlastV float64\n}\n\n\nfunc NewRSI(inTimePeriod int, warmType WarmupType) *RSI {\n\tema := NewEMA(inTimePeriod+1, warmType)\n\tema.alpha = float64(1) / float64(inTimePeriod)\n\treturn &RSI{\n\t\temaUp: *ema,\n\t\temaDown: *ema,\n\t}\n}\n\n\nfunc (rsi RSI) WarmCount() int {\n\treturn rsi.emaUp.WarmCount()\n}\n\n\nfunc (rsi RSI) Warmed() bool {\n\treturn rsi.emaUp.Warmed()\n}\n\n\n\n\n\nfunc (rsi *RSI) Add(v float64) float64 {\n\tvar up float64\n\tvar down float64\n\tif v > rsi.lastV {\n\t\tup = v - rsi.lastV\n\t} else if v < rsi.lastV {\n\t\tdown = rsi.lastV - v\n\t}\n\trsi.emaUp.Add(up)\n\trsi.emaDown.Add(down)\n\trsi.lastV = v\n\treturn rsi.Last()\n}\n\nfunc (rsi RSI) Last() float64 ", "output": "{\n\treturn 100 - (100 / (1 + rsi.emaUp.Last()/rsi.emaDown.Last()))\n}"} {"input": "package resolver\n\nvar (\n\tm = make(map[string]Builder)\n\tdefaultScheme = \"passthrough\"\n)\n\n\n\n\n\nfunc Register(b Builder) {\n\tm[b.Scheme()] = b\n}\n\n\n\n\n\n\n\n\n\n\nfunc Get(scheme string) Builder {\n\tif b, ok := m[scheme]; ok {\n\t\treturn b\n\t}\n\tif b, ok := m[defaultScheme]; ok {\n\t\treturn b\n\t}\n\treturn nil\n}\n\n\n\nfunc SetDefaultScheme(scheme string) {\n\tdefaultScheme = scheme\n}\n\n\ntype AddressType uint8\n\nconst (\n\tBackend AddressType = iota\n\tGRPCLB\n)\n\n\n\ntype Address struct {\n\tAddr string\n\tType AddressType\n\tServerName string\n\tMetadata interface{}\n}\n\n\n\ntype BuildOption struct {\n}\n\n\n\ntype ClientConn interface {\n\tNewAddress(addresses []Address)\n\tNewServiceConfig(serviceConfig string)\n}\n\n\n\ntype Target struct {\n\tScheme string\n\tAuthority string\n\tEndpoint string\n}\n\n\ntype Builder interface {\n\tBuild(target Target, cc ClientConn, opts BuildOption) (Resolver, error)\n\tScheme() string\n}\n\n\ntype ResolveNowOption struct{}\n\n\n\ntype Resolver interface {\n\tResolveNow(ResolveNowOption)\n\tClose()\n}\n\n\n\n\n\n\nfunc UnregisterForTesting(scheme string) ", "output": "{\n\tdelete(m, scheme)\n}"} {"input": "package challenge1\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\n\n\nfunc TestConvertHexToBase64(t *testing.T) ", "output": "{\n\tencoded, err := ConvertHexToBase64([]byte(\"49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d\"))\n\tassert.Equal(t, encoded, []byte(\"SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t\"), \"they should be equal\")\n\tassert.Nil(t, err)\n}"} {"input": "package mode\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/elastic/libbeat/common\"\n)\n\nfunc TestLoadBalancerStartStop(t *testing.T) {\n\tmode, _ := NewLoadBalancerMode(\n\t\t[]ProtocolClient{\n\t\t\t&mockClient{\n\t\t\t\tconnected: false,\n\t\t\t\tclose: closeOK,\n\t\t\t\tconnect: connectOK,\n\t\t\t},\n\t\t},\n\t\t1,\n\t\t100*time.Millisecond,\n\t\t100*time.Millisecond,\n\t)\n\ttestMode(t, mode, nil, nil, nil)\n}\n\nfunc TestLoadBalancerFailSendWithoutActiveConnections(t *testing.T) {\n\terrFail := errors.New(\"fail connect\")\n\tmode, _ := NewLoadBalancerMode(\n\t\t[]ProtocolClient{\n\t\t\t&mockClient{\n\t\t\t\tconnected: false,\n\t\t\t\tclose: closeOK,\n\t\t\t\tconnect: alwaysFailConnect(errFail),\n\t\t\t},\n\t\t},\n\t\t2,\n\t\t100*time.Millisecond,\n\t\t100*time.Millisecond,\n\t)\n\ttestMode(t, mode, multiEvent(2, testEvent), signals(false), nil)\n}\n\nfunc TestLoadBalancerOKSend(t *testing.T) {\n\tvar collected [][]common.MapStr\n\tmode, _ := NewLoadBalancerMode(\n\t\t[]ProtocolClient{\n\t\t\t&mockClient{\n\t\t\t\tconnected: false,\n\t\t\t\tclose: closeOK,\n\t\t\t\tconnect: connectOK,\n\t\t\t\tpublish: collectPublish(&collected),\n\t\t\t},\n\t\t},\n\t\t2,\n\t\t100*time.Millisecond,\n\t\t100*time.Millisecond,\n\t)\n\ttestMode(t, mode, multiEvent(10, testEvent), signals(true), &collected)\n}\n\n\n\nfunc TestLoadBalancerFlakyConnectionOkSend(t *testing.T) ", "output": "{\n\tvar collected [][]common.MapStr\n\tmode, _ := NewLoadBalancerMode(\n\t\t[]ProtocolClient{\n\t\t\t&mockClient{\n\t\t\t\tconnected: true,\n\t\t\t\tclose: closeOK,\n\t\t\t\tconnect: connectOK,\n\t\t\t\tpublish: publishFailStart(1, collectPublish(&collected)),\n\t\t\t},\n\t\t\t&mockClient{\n\t\t\t\tconnected: true,\n\t\t\t\tclose: closeOK,\n\t\t\t\tconnect: connectOK,\n\t\t\t\tpublish: publishFailStart(1, collectPublish(&collected)),\n\t\t\t},\n\t\t},\n\t\t3,\n\t\t100*time.Millisecond,\n\t\t100*time.Millisecond,\n\t)\n\ttestMode(t, mode, multiEvent(10, testEvent), signals(true), &collected)\n}"} {"input": "package connect\n\nimport \"io\"\nimport \"github.com/LilyPad/GoLilyPad/packet\"\n\ntype RequestAuthenticate struct {\n\tUsername string\n\tPassword string\n}\n\nfunc NewRequestAuthenticate(username string, password string) (this *RequestAuthenticate) {\n\tthis = new(RequestAuthenticate)\n\tthis.Username = username\n\tthis.Password = password\n\treturn\n}\n\nfunc (this *RequestAuthenticate) Id() int {\n\treturn REQUEST_AUTHENTICATE\n}\n\ntype requestAuthenticateCodec struct {\n\n}\n\nfunc (this *requestAuthenticateCodec) Decode(reader io.Reader) (request Request, err error) {\n\trequestAuthenticate := new(RequestAuthenticate)\n\trequestAuthenticate.Username, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\trequestAuthenticate.Password, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\trequest = requestAuthenticate\n\treturn\n}\n\nfunc (this *requestAuthenticateCodec) Encode(writer io.Writer, request Request) (err error) {\n\trequestAuthenticate := request.(*RequestAuthenticate)\n\terr = packet.WriteString(writer, requestAuthenticate.Username)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = packet.WriteString(writer, requestAuthenticate.Password)\n\treturn\n}\n\ntype ResultAuthenticate struct {\n\n}\n\n\n\nfunc (this *ResultAuthenticate) Id() int {\n\treturn REQUEST_AUTHENTICATE\n}\n\ntype resultAuthenticateCodec struct {\n\n}\n\nfunc (this *resultAuthenticateCodec) Decode(reader io.Reader) (result Result, err error) {\n\tresult = new(ResultAuthenticate)\n\treturn\n}\n\nfunc (this *resultAuthenticateCodec) Encode(writer io.Writer, result Result) (err error) {\n\treturn\n}\n\nfunc NewResultAuthenticate() (this *ResultAuthenticate) ", "output": "{\n\tthis = new(ResultAuthenticate)\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/quintans/maze\"\n)\n\n\nfunc trace(c maze.IContext) error {\n\tfmt.Println(\"==> requesting\", c.GetRequest().URL.Path)\n\treturn c.Proceed()\n}\n\ntype GreetingService struct{}\n\n\n\ntype AppCtx struct {\n\t*maze.MazeContext\n}\n\n\n\n\nfunc (ac *AppCtx) Proceed() error {\n\treturn ac.Next(ac)\n}\n\n\n\nfunc (ac *AppCtx) Reply(value interface{}) error {\n\treturn ac.JSON(http.StatusOK, value)\n}\n\nfunc main() {\n\tmz := maze.NewMaze(maze.WithContextFactory(func(logger maze.Logger, w http.ResponseWriter, r *http.Request, filters []*maze.Filter) maze.IContext {\n\t\tctx := new(AppCtx)\n\t\tctx.MazeContext = maze.NewContext(logger, w, r, filters)\n\t\treturn ctx\n\t}))\n\n\tgreetingsService := &GreetingService{}\n\tmz.Push(\"/rest/greet/*\", trace)\n\n\tmz.GET(\"sayhi/:Id\", greetingsService.SayHi)\n\n\tmz.GET(\"/*\", func(ctx maze.IContext) error {\n\t\tctx.TEXT(\n\t\t\thttp.StatusBadRequest,\n\t\t\t\"invalid URI.\\nUse /rest/greet/sayhi/:Id[?name=Name] eg: /rest/greet/sayhi/123?name=Quintans\",\n\t\t)\n\t\treturn nil\n\t})\n\n\tfmt.Println(\"Listening at port 8888\")\n\tif err := mz.ListenAndServe(\":8888\"); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc (s *GreetingService) SayHi(ctx maze.IContext) error ", "output": "{\n\tvar q struct {\n\t\tId int `schema:\"id\"`\n\t\tName string `schema:\"name\"`\n\t}\n\tif err := ctx.Vars(&q); err != nil {\n\t\treturn err\n\t}\n\n\treturn ctx.(*AppCtx).Reply(fmt.Sprintf(\"Hi %s. Your ID is %d\", q.Name, q.Id))\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"html/template\"\n \"io/ioutil\"\n \"net/http\"\n \"os\"\n)\n\ntype Page struct {\n\tTitle string\n\tBody []byte\n}\n\nfunc (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}\n\nfunc loadPage(title string) (*Page, error) {\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Page{Title: title, Body: body}, nil\n}\n\nfunc renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {\n t, _ := template.ParseFiles(tmpl + \".html\")\n t.Execute(w, p)\n}\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n title := r.URL.Path[len(\"/view/\"):]\n p, err := loadPage(title)\n if err != nil {\n http.Redirect(w, r, \"/edit/\" + title, http.StatusFound)\n return\n }\n renderTemplate(w, \"view\", p)\n}\n\n\n\nfunc main() {\n http.HandleFunc(\"/view/\", viewHandler)\n http.HandleFunc(\"/edit/\", editHandler)\n \n fmt.Println(\"starting http service ...\")\n http.ListenAndServe(os.Getenv(\"IP\") + \":\" + os.Getenv(\"PORT\"), nil)\n}\n\nfunc editHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n title := r.URL.Path[len(\"/edit/\"):]\n p, err := loadPage(title)\n if err != nil {\n p = &Page{Title: title}\n }\n renderTemplate(w, \"edit\", p)\n}"} {"input": "package iso20022\n\n\ntype CorporateActionElection1 struct {\n\n\tOptionType *CorporateActionOption1FormatChoice `xml:\"OptnTp\"`\n\n\tOptionNumber *Exact3NumericText `xml:\"OptnNb\"`\n\n\tOriginalInstructedQuantity *UnitOrFaceAmount1Choice `xml:\"OrgnlInstdQty\"`\n\n\tRemainingQuantity *UnitOrFaceAmount1Choice `xml:\"RmngQty\"`\n}\n\nfunc (c *CorporateActionElection1) AddOptionType() *CorporateActionOption1FormatChoice {\n\tc.OptionType = new(CorporateActionOption1FormatChoice)\n\treturn c.OptionType\n}\n\nfunc (c *CorporateActionElection1) SetOptionNumber(value string) {\n\tc.OptionNumber = (*Exact3NumericText)(&value)\n}\n\n\n\nfunc (c *CorporateActionElection1) AddRemainingQuantity() *UnitOrFaceAmount1Choice {\n\tc.RemainingQuantity = new(UnitOrFaceAmount1Choice)\n\treturn c.RemainingQuantity\n}\n\nfunc (c *CorporateActionElection1) AddOriginalInstructedQuantity() *UnitOrFaceAmount1Choice ", "output": "{\n\tc.OriginalInstructedQuantity = new(UnitOrFaceAmount1Choice)\n\treturn c.OriginalInstructedQuantity\n}"} {"input": "package simplecli\n\n\ntype CLISetting struct {\n\tcli *CLI\n}\n\n\nfunc (c *CLISetting) ConfigSearchPath(paths ...string) func() {\n\treturn func() {\n\t\tc.cli.ConfigSearchPath = paths[:]\n\t}\n}\n\n\n\n\nfunc (c *CLISetting) ConfigFile(path string) func() ", "output": "{\n\treturn func() {\n\t\tc.cli.ConfigFile = path\n\t}\n}"} {"input": "package scene\n\nimport \"github.com/thinkofdeath/steven/ui\"\n\n\ntype Type struct {\n\tvisible bool\n\n\tdrawables []ui.Drawable\n\thidding bool\n}\n\n\nfunc New(visible bool) *Type {\n\treturn &Type{\n\t\tvisible: visible,\n\t}\n}\n\n\n\n\n\nfunc (t *Type) Hide() {\n\tif !t.visible {\n\t\treturn\n\t}\n\tt.visible = false\n\tt.hidding = true\n\tfor _, d := range t.drawables {\n\t\tui.Remove(d)\n\t}\n\tt.hidding = false\n}\n\n\nfunc (t *Type) AddDrawable(d ui.Drawable) {\n\tt.drawables = append(t.drawables, d)\n\tif t.visible {\n\t\tui.AddDrawable(d)\n\t}\n\td.SetRemoveHook(t.removeHook)\n}\n\nfunc (t *Type) removeHook(d ui.Drawable) {\n\tif t.hidding {\n\t\treturn\n\t}\n\tfor i, dd := range t.drawables {\n\t\tif dd == d {\n\t\t\tt.drawables = append(t.drawables[:i], t.drawables[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n\n}\n\n\nfunc (t *Type) IsVisible() bool {\n\treturn t.visible\n}\n\nfunc (t *Type) Show() ", "output": "{\n\tif t.visible {\n\t\treturn\n\t}\n\tt.visible = true\n\tfor _, d := range t.drawables {\n\t\tui.AddDrawable(d)\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org/x/net/context\"\n\tpb \"k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2\"\n)\n\n\n\nfunc (s *Server) runPodSandbox(ctx context.Context, req *pb.RunPodSandboxRequest) (resp *pb.RunPodSandboxResponse, err error) ", "output": "{\n\treturn nil, fmt.Errorf(\"unsupported\")\n}"} {"input": "package awstasks\n\nimport (\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/service/ec2\"\n)\n\nfunc mapEC2TagsToMap(tags []*ec2.Tag) map[string]string {\n\tif tags == nil {\n\t\treturn nil\n\t}\n\tm := make(map[string]string)\n\tfor _, t := range tags {\n\t\tm[aws.StringValue(t.Key)] = aws.StringValue(t.Value)\n\t}\n\treturn m\n}\n\n\n\n\n\nfunc intersectTags(tags []*ec2.Tag, desired map[string]string) map[string]string {\n\tif tags == nil {\n\t\treturn nil\n\t}\n\tactual := make(map[string]string)\n\tfor _, t := range tags {\n\t\tk := aws.StringValue(t.Key)\n\t\tv := aws.StringValue(t.Value)\n\n\t\tif _, found := desired[k]; found {\n\t\t\tactual[k] = v\n\t\t}\n\t}\n\tif len(actual) == 0 && desired == nil {\n\t\treturn nil\n\t}\n\treturn actual\n}\n\nfunc findNameTag(tags []*ec2.Tag) *string ", "output": "{\n\tfor _, tag := range tags {\n\t\tif aws.StringValue(tag.Key) == \"Name\" {\n\t\t\treturn tag.Value\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package leet_572\n\ntype TreeNode struct {\n\tVal int\n\tLeft *TreeNode\n\tRight *TreeNode\n}\n\nfunc isSubtree(s *TreeNode, t *TreeNode) bool {\n\tif s == nil || t == nil {\n\t\treturn false\n\t}\n\n\treturn visit(s, t) || isSubtree(s.Left, t) || isSubtree(s.Right, t)\n}\n\n\n\nfunc visit(s *TreeNode, t *TreeNode) bool ", "output": "{\n\tif s == nil && t == nil {\n\t\treturn true\n\t}\n\tif s == nil || t == nil {\n\t\treturn false\n\t}\n\tif s.Val != t.Val {\n\t\treturn false\n\t}\n\treturn visit(s.Left, t.Left) && visit(s.Right, t.Right)\n}"} {"input": "package features\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" features/2021-07-01\"\n}"} {"input": "package mock\n\nimport (\n\t\"github.com/fkmhrk/OpenInvoice/v1/model/env\"\n)\n\ntype EnvDAO struct {\n\tCreateResult env.Env\n\tGetResult env.Env\n\tGetListResult []*env.Env\n\tSaveResult error\n\tUpdateResult env.Env\n\tDeleteResult env.Env\n}\n\nfunc (d *EnvDAO) Create(key, value string) (env.Env, error) {\n\treturn d.CreateResult, nil\n}\n\n\n\nfunc (d *EnvDAO) GetList() ([]*env.Env, error) {\n\treturn d.GetListResult, nil\n}\n\nfunc (d *EnvDAO) Save(list []*env.Env) error {\n\treturn d.SaveResult\n}\n\nfunc (d *EnvDAO) Update(key, value string) (env.Env, error) {\n\treturn d.UpdateResult, nil\n}\n\nfunc (d *EnvDAO) Delete(key string) (env.Env, error) {\n\treturn d.DeleteResult, nil\n}\n\nfunc (d *EnvDAO) Get(key string) (env.Env, error) ", "output": "{\n\treturn d.GetResult, nil\n}"} {"input": "package v1\n\nimport (\n\tcommon \"github.com/kubeflow/common/pkg/apis/common/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\n\n\nfunc Int32(v int32) *int32 {\n\treturn &v\n}\n\n\n\n\nfunc setDefaultsTypeLauncher(spec *common.ReplicaSpec) {\n\tif spec != nil && spec.RestartPolicy == \"\" {\n\t\tspec.RestartPolicy = DefaultRestartPolicy\n\t}\n}\n\n\nfunc setDefaultsTypeWorker(spec *common.ReplicaSpec) {\n\tif spec != nil && spec.RestartPolicy == \"\" {\n\t\tspec.RestartPolicy = DefaultRestartPolicy\n\t}\n}\n\nfunc SetDefaults_MPIJob(mpiJob *MPIJob) {\n\tif mpiJob.Spec.CleanPodPolicy == nil {\n\t\tnone := common.CleanPodPolicyNone\n\t\tmpiJob.Spec.CleanPodPolicy = &none\n\t}\n\n\tsetDefaultsTypeLauncher(mpiJob.Spec.MPIReplicaSpecs[MPIReplicaTypeLauncher])\n\n\tsetDefaultsTypeWorker(mpiJob.Spec.MPIReplicaSpecs[MPIReplicaTypeWorker])\n}\n\nfunc addDefaultingFuncs(scheme *runtime.Scheme) error ", "output": "{\n\treturn RegisterDefaults(scheme)\n}"} {"input": "package xmpp\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n)\n\n\n\nfunc TestStreamError(t *testing.T) ", "output": "{\n\tconst errStr = ``\n\n\tvar se streamError\n\tif err := xml.Unmarshal([]byte(errStr), &se); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif se.Error() != errStr {\n\t\tt.Fatal(\"stream error is wrong:\", se.Error())\n\t}\n}"} {"input": "package main\nimport \"bufio\"\nimport \"crypto/tls\"\nimport \"fmt\"\nimport \"net\"\n \nfunc main() {\n\tDial(\":1025\", ConfigTLS(\"ccert\", \"ckey\"), func(c net.Conn) {\n\t\tif m, e := bufio.NewReader(c).ReadString('\\n'); e == nil {\n\t\t\tfmt.Printf(m)\n\t\t}\n\t})\n}\n\n\n\nfunc Dial(a string, conf *tls.Config, f func(net.Conn)) {\n\tif c, e := tls.Dial(\"tcp\", a, conf); e == nil {\n\t\tdefer c.Close()\n\t\tf(c)\n\t}\n}\n\nfunc ConfigTLS(c, k string) (r *tls.Config) ", "output": "{\n\tif cert, e := tls.LoadX509KeyPair(c, k); e == nil {\n\t\tr = &tls.Config{\n\t\t\tCertificates: []tls.Certificate{ cert },\n\t\t\tInsecureSkipVerify: true,\n\t\t}\n\t}\n\treturn\n}"} {"input": "package classfile\n\nimport (\n\t\"github.com/zxh0/jvm.go/jvmgo/util/bigendian\"\n)\n\ntype ClassReader struct {\n\tdata []byte\n}\n\n\n\nfunc (self *ClassReader) readUint8() uint8 {\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16() uint16 {\n\tval := bigendian.Uint16(self.data)\n\tself.data = self.data[2:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint32() uint32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn uint32(val)\n}\nfunc (self *ClassReader) readInt32() int32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readInt64() int64 {\n\tval := bigendian.Int64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readFloat32() float32 {\n\tval := bigendian.Float32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readFloat64() float64 {\n\tval := bigendian.Float64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readBytes(length uint32) []byte {\n\tbytes := self.data[:length]\n\tself.data = self.data[length:]\n\treturn bytes\n}\n\n\nfunc (self *ClassReader) readString() string {\n\tlength := uint32(self.readUint16())\n\tbytes := self.readBytes(length)\n\treturn string(bytes)\n}\n\nfunc newClassReader(data []byte) *ClassReader ", "output": "{\n\treturn &ClassReader{data}\n}"} {"input": "package iso20022\n\n\ntype TransactionIdentifications3 struct {\n\n\tAccountOwnerTransactionIdentification *Max35Text `xml:\"AcctOwnrTxId\"`\n\n\tAccountServicerTransactionIdentification *Max35Text `xml:\"AcctSvcrTxId,omitempty\"`\n\n\tMarketInfrastructureTransactionIdentification *Max35Text `xml:\"MktInfrstrctrTxId,omitempty\"`\n}\n\n\n\nfunc (t *TransactionIdentifications3) SetAccountServicerTransactionIdentification(value string) {\n\tt.AccountServicerTransactionIdentification = (*Max35Text)(&value)\n}\n\nfunc (t *TransactionIdentifications3) SetMarketInfrastructureTransactionIdentification(value string) {\n\tt.MarketInfrastructureTransactionIdentification = (*Max35Text)(&value)\n}\n\nfunc (t *TransactionIdentifications3) SetAccountOwnerTransactionIdentification(value string) ", "output": "{\n\tt.AccountOwnerTransactionIdentification = (*Max35Text)(&value)\n}"} {"input": "package classfile\n\nimport (\n\t\"github.com/zxh0/jvm.go/jvmgo/util/bigendian\"\n)\n\ntype ClassReader struct {\n\tdata []byte\n}\n\nfunc newClassReader(data []byte) *ClassReader {\n\treturn &ClassReader{data}\n}\n\nfunc (self *ClassReader) readUint8() uint8 {\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16() uint16 {\n\tval := bigendian.Uint16(self.data)\n\tself.data = self.data[2:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint32() uint32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn uint32(val)\n}\n\n\nfunc (self *ClassReader) readInt64() int64 {\n\tval := bigendian.Int64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readFloat32() float32 {\n\tval := bigendian.Float32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readFloat64() float64 {\n\tval := bigendian.Float64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readBytes(length uint32) []byte {\n\tbytes := self.data[:length]\n\tself.data = self.data[length:]\n\treturn bytes\n}\n\n\nfunc (self *ClassReader) readString() string {\n\tlength := uint32(self.readUint16())\n\tbytes := self.readBytes(length)\n\treturn string(bytes)\n}\n\nfunc (self *ClassReader) readInt32() int32 ", "output": "{\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}"} {"input": "package master\n\nimport ()\n\n\n\ntype frame struct {\n\tjob *job\n\tslaveName string\n\tframe int\n\tdata []byte\n\tprogress byte\n\tcompleted bool\n}\n\n\n\nfunc NewFrame(job *job, fr int) *frame {\n\treturn &frame{\n\t\tjob: job,\n\t\tslaveName: \"\",\n\t\tframe: fr,\n\t\tdata: nil,\n\t\tprogress: 0,\n\t\tcompleted: false,\n\t}\n}\n\n\n\nfunc (f *frame) Job() *job {\n\treturn f.job\n}\n\nfunc (f *frame) SlaveName() string {\n\treturn f.slaveName\n}\n\nfunc (f *frame) Frame() int {\n\treturn f.frame\n}\n\nfunc (f *frame) AlignedFrame() int {\n\treturn f.frame + f.Job().Start()\n}\n\nfunc (f *frame) Data() []byte {\n\treturn f.data\n}\n\nfunc (f *frame) Progress() byte {\n\treturn f.progress\n}\n\n\n\nfunc (f *frame) File() []byte {\n\treturn f.Job().File()\n}\n\n\n\nfunc (f *frame) SetSlaveName(slaveName string) {\n\tf.slaveName = slaveName\n}\n\nfunc (f *frame) SetData(data []byte) {\n\tf.data = data\n}\n\nfunc (f *frame) SetProgress(progress byte) {\n\tf.progress = progress\n}\n\nfunc (f *frame) SetCompleted(completed bool) {\n\tf.completed = completed\n\tif completed {\n\t\tf.SetProgress(100)\n\t}\n}\n\n\n\nfunc (f *frame) Reset() {\n\tf.SetSlaveName(\"\")\n\tf.SetData(nil)\n\tf.SetProgress(0)\n\tf.SetCompleted(false)\n}\n\nfunc (f *frame) Completed() bool ", "output": "{\n\treturn f.completed\n}"} {"input": "package leetcode\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestFindPoisonedDuration(t *testing.T) ", "output": "{\n\tassert.EqualValues(t, 4, findPoisonedDuration([]int{1, 4}, 2))\n\tassert.EqualValues(t, 3, findPoisonedDuration([]int{1, 2}, 2))\n\tassert.EqualValues(t, 12, findPoisonedDuration([]int{1, 3, 5}, 8))\n}"} {"input": "package errorreporting \n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}\n\n\n\n\nfunc DefaultAuthScopes() []string ", "output": "{\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t}\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\n\t\"launchpad.net/juju-core/state\"\n\t\"launchpad.net/juju-core/state/api/params\"\n)\n\n\ntype Remover struct {\n\tst state.EntityFinder\n\tcallEnsureDead bool\n\tgetCanModify GetAuthFunc\n}\n\n\n\n\n\nfunc NewRemover(st state.EntityFinder, callEnsureDead bool, getCanModify GetAuthFunc) *Remover {\n\treturn &Remover{\n\t\tst: st,\n\t\tcallEnsureDead: callEnsureDead,\n\t\tgetCanModify: getCanModify,\n\t}\n}\n\n\n\n\n\nfunc (r *Remover) Remove(args params.Entities) (params.ErrorResults, error) {\n\tresult := params.ErrorResults{\n\t\tResults: make([]params.ErrorResult, len(args.Entities)),\n\t}\n\tif len(args.Entities) == 0 {\n\t\treturn result, nil\n\t}\n\tcanModify, err := r.getCanModify()\n\tif err != nil {\n\t\treturn params.ErrorResults{}, err\n\t}\n\tfor i, entity := range args.Entities {\n\t\terr := ErrPerm\n\t\tif canModify(entity.Tag) {\n\t\t\terr = r.removeEntity(entity.Tag)\n\t\t}\n\t\tresult.Results[i].Error = ServerError(err)\n\t}\n\treturn result, nil\n}\n\nfunc (r *Remover) removeEntity(tag string) error ", "output": "{\n\tentity, err := r.st.FindEntity(tag)\n\tif err != nil {\n\t\treturn err\n\t}\n\tremover, ok := entity.(interface {\n\t\tstate.Lifer\n\t\tstate.Remover\n\t\tstate.EnsureDeader\n\t})\n\tif !ok {\n\t\treturn NotSupportedError(tag, \"removal\")\n\t}\n\tif life := remover.Life(); life == state.Alive {\n\t\treturn fmt.Errorf(\"cannot remove entity %q: still alive\", tag)\n\t}\n\tif r.callEnsureDead {\n\t\tif err := remover.EnsureDead(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn remover.Remove()\n}"} {"input": "package gorfxtrx\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\n\ntype Wind struct {\n\tdata []byte\n\ttypeId byte\n\tSequenceNumber byte\n\tid uint16\n\tDirection uint16\n\tAverageSpeed float64\n\tGust float64\n\tBattery byte\n\tRssi byte\n}\n\nvar windTypes = map[byte]string{\n\t0x01: \"WTGR800\",\n\t0x02: \"WGR800\",\n\t0x03: \"STR918, WGR918\",\n\t0x04: \"TFA\",\n}\n\nfunc (self *Wind) Receive(data []byte) {\n\tself.data = data\n\tself.typeId = data[2]\n\tself.SequenceNumber = data[3]\n\tself.id = binary.BigEndian.Uint16(data[4:6])\n\tself.Direction = binary.BigEndian.Uint16(data[6:8])\n\tself.AverageSpeed = float64(binary.BigEndian.Uint16(data[8:10])) / 10\n\tself.Gust = float64(binary.BigEndian.Uint16(data[10:12])) / 10\n\tif self.typeId == 0x03 {\n\t\tself.Battery = (data[16] + 1) * 10\n\t} else {\n\t\tself.Battery = (data[16] & 0x0f) * 10\n\t\tself.Rssi = data[16] >> 4\n\t}\n}\n\n\n\n\n\nfunc (self *Wind) Type() string {\n\treturn windTypes[self.typeId]\n}\n\nfunc (self *Wind) Id() string ", "output": "{\n\treturn fmt.Sprintf(\"%02x:%02x\", self.id>>8, self.id&0xff)\n}"} {"input": "package model\n\n\ntype Team struct {\n\tID int64 `json:\"id\" form:\"id\"`\n\tTitle string `json:\"title\" form:\"title\" validate:\"required\"`\n\tSubTitle string `json:\"sub_title\" form:\"sub_title\"`\n\tETitle string `json:\"e_title\" form:\"e_title\"`\n\tCreateTime int64 `json:\"create_time\" form:\"create_time\"`\n\tArea string `json:\"area\" form:\"area\"`\n\tLogo string `json:\"logo\" form:\"logo\" validate:\"required\"`\n\tUID int64 `json:\"uid\" form:\"uid\" gorm:\"column:uid\"`\n\tMembers string `json:\"members\" form:\"members\"`\n\tDic string `json:\"dic\" form:\"dic\"`\n\tIsDeleted int `json:\"is_deleted\" form:\"is_deleted\"`\n}\n\n\ntype TeamInfo struct {\n\t*Team\n\tGames []*Game `json:\"games\"`\n}\n\n\n\n\nfunc (t Team) TableName() string ", "output": "{\n\treturn \"es_teams\"\n}"} {"input": "package internalversion\n\nimport (\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n\tadmissionregistration \"k8s.io/kubernetes/pkg/apis/admissionregistration\"\n)\n\n\ntype InitializerConfigurationLister interface {\n\tList(selector labels.Selector) (ret []*admissionregistration.InitializerConfiguration, err error)\n\tGet(name string) (*admissionregistration.InitializerConfiguration, error)\n\tInitializerConfigurationListerExpansion\n}\n\n\ntype initializerConfigurationLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewInitializerConfigurationLister(indexer cache.Indexer) InitializerConfigurationLister {\n\treturn &initializerConfigurationLister{indexer: indexer}\n}\n\n\nfunc (s *initializerConfigurationLister) List(selector labels.Selector) (ret []*admissionregistration.InitializerConfiguration, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*admissionregistration.InitializerConfiguration))\n\t})\n\treturn ret, err\n}\n\n\n\n\nfunc (s *initializerConfigurationLister) Get(name string) (*admissionregistration.InitializerConfiguration, error) ", "output": "{\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(admissionregistration.Resource(\"initializerconfiguration\"), name)\n\t}\n\treturn obj.(*admissionregistration.InitializerConfiguration), nil\n}"} {"input": "package certdata\n\nimport (\n\t\"crypto/x509\"\n\t\"fmt\"\n)\n\n\n\ntype Data struct {\n\tCert *x509.Certificate\n\tIssuer *x509.Certificate\n\tType string\n}\n\n\nfunc Load(der []byte) (*Data, error) {\n\tvar err error\n\n\td := new(Data)\n\td.Cert, err = x509.ParseCertificate(der)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = d.setCertificateType(); err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\treturn d, nil\n}\n\n\n\n\n\nfunc (d *Data) SetIssuer(der []byte) error ", "output": "{\n\tvar err error\n\td.Issuer, err = x509.ParseCertificate(der)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package chipecs\n\nimport (\n\t\"log\"\n\n\t\"engo.io/ecs\"\n\t\"engo.io/engo\"\n\t\"engo.io/engo/common\"\n\t\"github.com/vova616/chipmunk\"\n\t\"github.com/vova616/chipmunk/vect\"\n)\n\n\n\nfunc (ps *PhysicsSystem) Remove(basic ecs.BasicEntity) {\n\tdelete := -1\n\tfor index, e := range ps.entities {\n\t\tif e.BasicEntity.ID() == basic.ID() {\n\t\t\tdelete = index\n\t\t\tps.Space.RemoveBody(e.Shape.Body)\n\t\t\tbreak\n\t\t}\n\t}\n\tif delete >= 0 {\n\t\tps.entities = append(ps.entities[:delete], ps.entities[delete+1:]...)\n\t}\n}\n\n\n\n\n\nfunc (ps *PhysicsSystem) Update(dt float32) {\n\tfor _, e := range ps.entities {\n\t\tpos := e.PhysicsComponent.Shape.Body.Position()\n\t\te.Position = engo.Point{X: float32(pos.X), Y: float32(pos.Y)}\n\t\te.Rotation = 0 \n\t}\n\tps.Space.Step(vect.Float(dt))\n}\n\n\nfunc (ps *PhysicsSystem) Add(basic *ecs.BasicEntity, physics *PhysicsComponent, space *common.SpaceComponent) {\n\tps.entities = append(ps.entities, physicsEntity{basic, physics, space})\n\tps.Space.AddBody(physics.Shape.Body)\n}\n\nfunc (ps *PhysicsSystem) New(*ecs.World) ", "output": "{\n\tlog.Println(\"PhyiscsSystem was added to the scene.\")\n\tps.Space = chipmunk.NewSpace()\n\tps.Space.Gravity = vect.Vect{X: 0, Y: 0}\n}"} {"input": "package hugot\n\nimport \"context\"\n\n\n\n\ntype BackgroundHandler interface {\n\tDescriber\n\tStartBackground(ctx context.Context, w ResponseWriter)\n}\n\ntype baseBackgroundHandler struct {\n\tname string\n\tdesc string\n\tbhf BackgroundFunc\n}\n\n\ntype BackgroundFunc func(ctx context.Context, w ResponseWriter)\n\n\n\nfunc NewBackgroundHandler(name, desc string, f BackgroundFunc) BackgroundHandler {\n\treturn &baseBackgroundHandler{\n\t\tname: name,\n\t\tdesc: desc,\n\t\tbhf: f,\n\t}\n}\n\n\n\nfunc (bbh *baseBackgroundHandler) StartBackground(ctx context.Context, w ResponseWriter) {\n\tbbh.bhf(ctx, w)\n}\n\nfunc (bbh *baseBackgroundHandler) Describe() (string, string) ", "output": "{\n\treturn bbh.name, bbh.desc\n}"} {"input": "package ipamutils\n\nimport (\n\t\"net\"\n\n\t\"github.com/docker/libnetwork/types\"\n)\n\n\n\n\n\nfunc ElectInterfaceAddresses(name string) (*net.IPNet, []*net.IPNet, error) {\n\treturn nil, nil, types.NotImplementedErrorf(\"not supported on windows\")\n}\n\n\n\n\n\nfunc FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error) ", "output": "{\n\treturn nil, types.NotImplementedErrorf(\"not supported on windows\")\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n\t\"log\"\n)\n\ntype errorMsg struct {\n\tSuccess bool `json:\"success\"`\n\tMessage string `json:\"message\"`\n}\n\n\n\nfunc writeJSON(w io.Writer, value interface{}) ", "output": "{\n\tdata, err := json.Marshal(value)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn\n\t}\n\n\t_, err = w.Write(data)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn\n\t}\n}"} {"input": "package filehash\n\nimport (\n\t\"crypto/sha1\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/cloudfoundry/gofileutils/fileutils\"\n)\n\ntype Hash []byte\n\nfunc Zero() Hash {\n\treturn Hash(make([]byte, sha1.Size))\n}\n\n\nfunc New(filePath string) Hash {\n\tfileInfo, err := os.Lstat(filePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif fileInfo.IsDir() {\n\t\tpanic(\"cannot compute hash of directory\")\n\t} else {\n\t\thash := sha1.New()\n\t\terr = fileutils.CopyPathToWriter(filePath, hash)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn Hash(hash.Sum(nil))\n\t}\n}\n\nfunc (k Hash) String() string {\n\treturn fmt.Sprintf(\"%x\", string(k))\n}\n\nfunc StringToHash(s string) Hash {\n\tvar sh string\n\tif _, err := fmt.Sscanf(s, \"%x\", &sh); err != nil {\n\t\tpanic(err)\n\t}\n\treturn Hash(sh)\n}\n\n\n\nfunc (h1 Hash) Remove(h2 Hash) {\n\th1.Combine(h2)\n}\n\nfunc (h1 Hash) Combine(h2 Hash) ", "output": "{\n\tif len(h1) != len(h2) {\n\t\tpanic(\"Invalid hash length\")\n\t}\n\tfor i, b := range h1 {\n\t\th1[i] = b ^ h2[i]\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n)\n\n\n\nfunc main() {\n\tvar n int\n\t_, err := fmt.Scanf(\"%d\", &n)\n\tif nil != err {\n\t\tlog.Fatal(err)\n\t}\n\tif isleap(n) {\n\t\tfmt.Printf(\"%v is a leap year.\\n\", n)\n\t} else {\n\t\tfmt.Printf(\"%v is not a leap year.\\n\", n)\n\t}\n}\n\nfunc isleap(n int) bool ", "output": "{\n\tif 0 == n%400 {\n\t\treturn true\n\t}\n\tif 0 == n%100 {\n\t\treturn false\n\t}\n\tif 0 == n%4 {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package realtime\n\n\n\nfunc (c *Client) getCustomEmoji() error ", "output": "{\n\t_, err := c.ddp.Call(\"listEmojiCustom\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package core\n\nimport (\n\t\"github.com/stretchr/testify/mock\"\n\t\"k8s.io/contrib/cluster-autoscaler/config/dynamic\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype AutoscalerMock struct {\n\tmock.Mock\n}\n\nfunc (m *AutoscalerMock) RunOnce(currentTime time.Time) {\n\tm.Called(currentTime)\n}\n\nfunc (m *AutoscalerMock) CleanUp() {\n\tm.Called()\n}\n\nfunc (m *AutoscalerMock) ExitCleanUp() {\n\tm.Called()\n}\n\ntype ConfigFetcherMock struct {\n\tmock.Mock\n}\n\nfunc (m *ConfigFetcherMock) FetchConfigIfUpdated() (*dynamic.Config, error) {\n\targs := m.Called()\n\treturn args.Get(0).(*dynamic.Config), args.Error(1)\n}\n\ntype AutoscalerBuilderMock struct {\n\tmock.Mock\n}\n\nfunc (m *AutoscalerBuilderMock) SetDynamicConfig(config dynamic.Config) AutoscalerBuilder {\n\targs := m.Called(config)\n\treturn args.Get(0).(AutoscalerBuilder)\n}\n\nfunc (m *AutoscalerBuilderMock) Build() Autoscaler {\n\targs := m.Called()\n\treturn args.Get(0).(Autoscaler)\n}\n\nfunc TestRunOnceWhenNoUpdate(t *testing.T) {\n\tcurrentTime := time.Now()\n\n\tautoscaler := &AutoscalerMock{}\n\tautoscaler.On(\"RunOnce\", currentTime).Once()\n\n\tconfigFetcher := &ConfigFetcherMock{}\n\tconfigFetcher.On(\"FetchConfigIfUpdated\").Return((*dynamic.Config)(nil), nil).Once()\n\n\tbuilder := &AutoscalerBuilderMock{}\n\tbuilder.On(\"Build\").Return(autoscaler).Once()\n\n\ta := NewDynamicAutoscaler(builder, configFetcher)\n\ta.RunOnce(currentTime)\n\n\tautoscaler.AssertExpectations(t)\n\tconfigFetcher.AssertExpectations(t)\n\tbuilder.AssertExpectations(t)\n}\n\n\n\nfunc TestRunOnceWhenUpdated(t *testing.T) ", "output": "{\n\tcurrentTime := time.Now()\n\n\tnewConfig := dynamic.NewDefaultConfig()\n\n\tinitialAutoscaler := &AutoscalerMock{}\n\n\tnewAutoscaler := &AutoscalerMock{}\n\tnewAutoscaler.On(\"RunOnce\", currentTime).Once()\n\n\tconfigFetcher := &ConfigFetcherMock{}\n\tconfigFetcher.On(\"FetchConfigIfUpdated\").Return(&newConfig, nil).Once()\n\n\tbuilder := &AutoscalerBuilderMock{}\n\tbuilder.On(\"Build\").Return(initialAutoscaler).Once()\n\tbuilder.On(\"SetDynamicConfig\", newConfig).Return(builder).Once()\n\tbuilder.On(\"Build\").Return(newAutoscaler).Once()\n\n\ta := NewDynamicAutoscaler(builder, configFetcher)\n\ta.RunOnce(currentTime)\n\n\tinitialAutoscaler.AssertNotCalled(t, \"RunOnce\", mock.AnythingOfType(\"time.Time\"))\n\tnewAutoscaler.AssertExpectations(t)\n\tconfigFetcher.AssertExpectations(t)\n\tbuilder.AssertExpectations(t)\n}"} {"input": "package avl\n\n\n\n\n\nfunc (tree *Node) first() *Node {\n\tif nil == tree {\n\t\treturn nil\n\t}\n\tfor nil != tree.left {\n\t\ttree = tree.left\n\t}\n\treturn tree\n}\n\n\nfunc (tree *Tree) Last() *Node {\n\treturn tree.root.last()\n}\n\n\nfunc (tree *Node) last() *Node {\n\tif nil == tree {\n\t\treturn nil\n\t}\n\tfor nil != tree.right {\n\t\ttree = tree.right\n\t}\n\treturn tree\n}\n\n\n\nfunc (tree *Node) Next() *Node {\n\tif nil == tree.right {\n\t\tkey := tree.key\n\t\tfor {\n\t\t\ttree = tree.up\n\t\t\tif nil == tree {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif 1 == tree.key.Compare(key) { \n\t\t\t\treturn tree\n\t\t\t}\n\t\t}\n\t}\n\treturn tree.right.first()\n}\n\n\n\nfunc (tree *Node) Prev() *Node {\n\tif nil == tree.left {\n\t\tkey := tree.key\n\t\tfor {\n\t\t\ttree = tree.up\n\t\t\tif nil == tree {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif -1 == tree.key.Compare(key) { \n\t\t\t\treturn tree\n\t\t\t}\n\t\t}\n\t}\n\treturn tree.left.last()\n}\n\nfunc (tree *Tree) First() *Node ", "output": "{\n\treturn tree.root.first()\n}"} {"input": "package logo\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc fail(t *testing.T, msg string) {\n\tt.Errorf(msg)\n}\n\n\n\nfunc assertTrue(t *testing.T, val bool, args ...interface{}) {\n\tif !val {\n\t\tmsg := fmt.Sprint(args...)\n\t\tmsg = fmt.Sprintf(\"Not true(%s)!\", msg)\n\t\tfail(t, msg)\n\t}\n}\n\nfunc assertNotNil(t *testing.T, val interface{}, args ...interface{}) {\n\tif val == nil {\n\t\tmsg := fmt.Sprint(args...)\n\t\tmsg = fmt.Sprintf(\"Nil(%s)!\", msg)\n\t\tfail(t, msg)\n\t}\n}\n\nfunc benchmarkTask(b *testing.B, task func(int)) {\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\ttask(i)\n\t}\n}\n\nfunc assertEqual(t *testing.T, actual, expected interface{}, args ...interface{}) ", "output": "{\n\tif actual != expected {\n\t\tmsg := fmt.Sprint(args...)\n\t\tmsg = fmt.Sprintf(\"Not equal(%s)! autual: %#v expected: %#v\", msg, actual, expected)\n\t\tfail(t, msg)\n\t}\n}"} {"input": "package zygo\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc (env *Glisp) ImportMsgpackMap() {\n\tenv.AddMacro(\"msgpack-map\", MsgpackMapMacro)\n\tenv.AddFunction(\"declare-msgpack-map\", DeclareMsgpackMapFunction)\n}\n\n\n\n\nfunc DeclareMsgpackMapFunction(env *Glisp, name string, args []Sexp) (Sexp, error) {\n\tif len(args) != 1 {\n\t\treturn SexpNull, WrongNargs\n\t}\n\n\tswitch t := args[0].(type) {\n\tcase SexpStr:\n\t\treturn t, nil\n\t}\n\treturn SexpNull, errors.New(\"argument must be string: the name of the new msgpack-map constructor function to create\")\n}\n\nfunc MsgpackMapMacro(env *Glisp, name string,\n\targs []Sexp) (Sexp, error) ", "output": "{\n\n\tif len(args) < 1 {\n\t\treturn SexpNull, fmt.Errorf(\"struct-name is missing. use: \" +\n\t\t\t\"(msgpack-map struct-name)\\n\")\n\t}\n\n\treturn MakeList([]Sexp{\n\t\tenv.MakeSymbol(\"def\"),\n\t\targs[0],\n\t\tMakeList([]Sexp{\n\t\t\tenv.MakeSymbol(\"quote\"),\n\t\t\tenv.MakeSymbol(\"msgmap\"),\n\t\t\tSexpStr{S: args[0].(SexpSymbol).name},\n\t\t}),\n\t}), nil\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification struct {\n\n\tPredefinedScalingMetricType string `json:\"PredefinedScalingMetricType,omitempty\"`\n\n\tResourceLabel string `json:\"ResourceLabel,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) AWSCloudFormationType() string {\n\treturn \"AWS::AutoScalingPlans::ScalingPlan.PredefinedScalingMetricSpecification\"\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetDeletionPolicy(policy policies.DeletionPolicy) ", "output": "{\n\tr._deletionPolicy = policy\n}"} {"input": "package main\n\n\nfunc f() ", "output": "{\n\tv := 1 << 1025;\t\t\n\t_ = v\n}"} {"input": "package world\n\nimport (\n\t\"encoding/gob\"\n\t\"math/big\"\n\t\"reflect\"\n\t\"time\"\n)\n\nvar registeredIdentifierObject = make(map[string]reflect.Type)\nvar registeredObjectIdentifier = make(map[reflect.Type]string)\n\nfunc Register(identifier string, obj ObjectLike) {\n\tif identifier == \"\" {\n\t\tpanic(\"attempt to register an empty identifier\")\n\t}\n\tif obj == nil {\n\t\tpanic(\"attempt to register a nil object type\")\n\t}\n\n\tt := reflect.TypeOf(obj)\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\n\tif _, ok := registeredIdentifierObject[identifier]; ok {\n\t\tpanic(\"duplicate registration for object identifier \" + identifier)\n\t}\n\tif _, ok := registeredObjectIdentifier[t]; ok {\n\t\tpanic(\"duplicate registration for object type \" + t.Name())\n\t}\n\tregisteredObjectIdentifier[t] = identifier\n\tregisteredIdentifierObject[identifier] = t\n}\n\nfunc getObjectTypeIdentifier(obj ObjectLike) string {\n\tt := reflect.TypeOf(obj)\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\tidentifier := registeredObjectIdentifier[t]\n\tif identifier == \"\" {\n\t\tpanic(\"unregistered object type: \" + t.Name())\n\t}\n\treturn identifier\n}\n\nfunc getObjectByIdentifier(identifier string) ObjectLike {\n\tt := registeredIdentifierObject[identifier]\n\tif t == nil {\n\t\tpanic(\"unregistered object identifier: \" + identifier)\n\t}\n\treturn reflect.New(t).Interface().(ObjectLike)\n}\n\n\n\nfunc init() ", "output": "{\n\tgob.Register(map[string]interface{}{})\n\tgob.Register([]interface{}{})\n\tgob.Register(time.Time{})\n\tgob.Register(&big.Int{})\n}"} {"input": "package cborl\n\ntype stateStack struct {\n\tstack []state \n\tstack0 [64]state\n\tcurrent state\n}\n\ntype lengthStack struct {\n\tstack []int64\n\tstack0 [32]int64\n\tcurrent int64\n}\n\nfunc (s *stateStack) init(s0 state) {\n\ts.current = s0\n\ts.stack = s.stack0[:0]\n}\n\nfunc (s *stateStack) push(next state) {\n\tif s.current.major != stFail {\n\t\ts.stack = append(s.stack, s.current)\n\t}\n\ts.current = next\n}\n\nfunc (s *stateStack) pop() {\n\tif len(s.stack) == 0 {\n\t\ts.current = state{stFail, stStart}\n\t} else {\n\t\tlast := len(s.stack) - 1\n\t\ts.current = s.stack[last]\n\t\ts.stack = s.stack[:last]\n\t}\n}\n\nfunc (s *lengthStack) init() {\n\ts.stack = s.stack0[:0]\n}\n\nfunc (s *lengthStack) push(l int64) {\n\ts.stack = append(s.stack, s.current)\n\ts.current = l\n}\n\n\n\nfunc (s *lengthStack) pop() int64 ", "output": "{\n\tif len(s.stack) == 0 {\n\t\ts.current = -1\n\t\treturn -1\n\t} else {\n\t\tlast := len(s.stack) - 1\n\t\told := s.current\n\t\ts.current = s.stack[last]\n\t\ts.stack = s.stack[:last]\n\t\treturn old\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strings\"\n)\n\n\n\n\nfunc main() {\n\tfpath := \"testdata/sample.json\"\n\n\tfile, err := os.Open(fpath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\ttbytes, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjsonStream := string(tbytes)\n\tdecodeString(jsonStream)\n\n\tdecodeFile(file)\n\n\tfile2, err := os.Open(fpath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdecodeFile(file2)\n}\n\nfunc decodeFile(file *os.File) {\n\trmap := map[string]string{}\n\tdec := json.NewDecoder(file)\n\tfor {\n\t\tif err := dec.Decode(&rmap); err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tfmt.Printf(\"%+v\\n\", rmap)\n}\n\n\n\nfunc decodeString(jsonStream string) ", "output": "{\n\trmap := map[string]string{}\n\tdec := json.NewDecoder(strings.NewReader(jsonStream))\n\tfor {\n\t\tif err := dec.Decode(&rmap); err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tfmt.Printf(\"%+v\\n\", rmap)\n}"} {"input": "package utils\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"time\"\n)\n\n\n\n\nfunc GenerateBulkID(doc TaggingReportDocument) (string, error) ", "output": "{\n\tji, err := json.Marshal(struct {\n\t\tAccount string `json:\"account\"`\n\t\tReportDate time.Time `json:\"reportDate\"`\n\t\tResourceID string `json:\"resourceID\"`\n\t\tRegion string `json:\"region\"`\n\t\tResourceType string `json:\"resourceType\"`\n\t}{\n\t\tdoc.Account,\n\t\tdoc.ReportDate,\n\t\tdoc.ResourceID,\n\t\tdoc.Region,\n\t\tdoc.ResourceType,\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\thash := md5.Sum(ji)\n\thash64 := base64.URLEncoding.EncodeToString(hash[:])\n\treturn hash64, nil\n}"} {"input": "package yaml\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\n\n\n\n\n\n\n\nfunc changeAll(root *yaml.Node, cb func(*yaml.Node)) {\n\tcb(root)\n\tfor _, child := range root.Content {\n\t\tchangeAll(child, cb)\n\t}\n}\n\n\n\nfunc SetStyle(root *yaml.Node, style yaml.Style) {\n\tchangeAll(root, func(node *yaml.Node) {\n\t\tnode.Style = style\n\t})\n}\n\nfunc ToYAML(rawObj interface{}) (*yaml.Node, error) ", "output": "{\n\tif rawObj == nil {\n\t\treturn &yaml.Node{Kind: yaml.ScalarNode, Value: \"null\", Tag: \"!!null\"}, nil\n\t}\n\n\trawJSON, err := json.Marshal(rawObj)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal object: %v\", err)\n\t}\n\n\tvar out yaml.Node\n\tif err := yaml.Unmarshal(rawJSON, &out); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to unmarshal marshalled object: %v\", err)\n\t}\n\treturn &out, nil\n}"} {"input": "package quota\n\nimport quotav1 \"github.com/openshift/api/quota/v1\"\n\n\nfunc ConvertAppliedClusterResourceQuotaToClusterResourceQuota(in *AppliedClusterResourceQuota) *ClusterResourceQuota {\n\treturn &ClusterResourceQuota{\n\t\tObjectMeta: in.ObjectMeta,\n\t\tSpec: in.Spec,\n\t\tStatus: in.Status,\n\t}\n}\n\n\n\n\nfunc ConvertV1ClusterResourceQuotaToV1AppliedClusterResourceQuota(in *quotav1.ClusterResourceQuota) *quotav1.AppliedClusterResourceQuota ", "output": "{\n\treturn "av1.AppliedClusterResourceQuota{\n\t\tObjectMeta: in.ObjectMeta,\n\t\tSpec: in.Spec,\n\t\tStatus: in.Status,\n\t}\n}"} {"input": "package ldp\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc Test_minCut(t *testing.T) ", "output": "{\n\tassert := assert.New(t)\n\n\tassert.Equal(1, minCut(\"aab\"))\n\tassert.Equal(0, minCut(\"aa\"))\n}"} {"input": "package main\n\nimport (\n\t\"github.com/nprog/SkyEye/common\"\n\t\"github.com/nprog/SkyEye/libnet\"\n\t\"github.com/nprog/SkyEye/log\"\n\t\"encoding/json\"\n\t\"sync\"\n\t\"time\"\n)\n\n\nfunc Test() {\n\trti := common.NewMachineInfo()\n\trti.GetInfo()\n\n\ttemp, err := json.Marshal(rti)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn\n\t}\n\n\tlog.Info(string(temp))\n}\n\n\ntype OnlineCfg struct {\n\tRealtimeInfo []string\n\tRealtimeInfoCycle int64 \n}\n\n\ntype Collection struct {\n\tonlineCfg *OnlineCfg\n\tsession *libnet.Session\n\tchangeCfg bool\n\tchangeCfgMutex sync.Mutex\n}\n\n\nfunc NewCollection() *Collection {\n\treturn &Collection{}\n}\n\n\nfunc (c *Collection) sendMachineInfo() {\n\tlog.V(1).Info(\"sendMachineInfo\")\n}\n\n\n\n\n\nfunc (c *Collection) sendFastRealtimeInfoLoop() {\n\n}\n\nfunc (c *Collection) sendRealtimeInfoLoop() ", "output": "{\n\tlog.Info(\"sendRealtimeInfoLoop\")\n\ttimer := time.NewTicker(5 * time.Second)\n\tttl := time.After(10 * time.Second)\nbkloop:\n\tfor {\n\t\tselect {\n\t\tcase <-timer.C:\n\n\t\t\tif c.changeCfg {\n\t\t\t\tc.changeCfg = false\n\t\t\t\tbreak bkloop\n\t\t\t}\n\t\tcase <-ttl:\n\t\t\tbreak\n\t\t}\n\t}\n\tlog.Info(\"re config RealtimeInfoLoop.\")\n\tc.sendRealtimeInfoLoop()\n}"} {"input": "package state\n\nimport \"context\"\n\n\n\n\nfunc Processor(ctx context.Context, in chan *WorkRequest, out chan *WorkResponse) ", "output": "{\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase wr := <-in:\n\t\t\tout <- Process(wr)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\ts := []int{2, 3, 5, 7, 11, 13}\n\tprintSlice(s)\n\n\ts = s[2:6] \n\tprintSlice(s)\n\n\ts = s[:2] \n\tprintSlice(s)\n\n\ts = s[2:] \n\tprintSlice(s)\n\n}\n\n\n\nfunc printSlice(s []int) ", "output": "{\n\tfmt.Printf(\"len=%d cap=%d %v\\n\", len(s), cap(s), s)\n}"} {"input": "package plugin\n\nimport (\n\t\"github.com/mitchellh/packer/packer\"\n\t\"log\"\n)\n\ntype cmdHook struct {\n\thook packer.Hook\n\tclient *Client\n}\n\nfunc (c *cmdHook) Run(name string, ui packer.Ui, comm packer.Communicator, data interface{}) error {\n\tdefer func() {\n\t\tr := recover()\n\t\tc.checkExit(r, nil)\n\t}()\n\n\treturn c.hook.Run(name, ui, comm, data)\n}\n\n\n\nfunc (c *cmdHook) checkExit(p interface{}, cb func()) ", "output": "{\n\tif c.client.Exited() {\n\t\tcb()\n\t} else if p != nil {\n\t\tlog.Panic(p)\n\t}\n}"} {"input": "package db\n\nimport (\n\t\"github.com/globalsign/mgo\"\n\t\"github.com/tsuru/config\"\n\t\"github.com/tsuru/tsuru/db/storage\"\n)\n\nconst (\n\tDefaultDatabaseURL = \"127.0.0.1:27017\"\n\tDefaultDatabaseName = \"gandalf\"\n)\n\ntype Storage struct {\n\t*storage.Storage\n}\n\n\n\n\n\nfunc conn() (*storage.Storage, error) {\n\turl, dbname := DbConfig()\n\treturn storage.Open(url, dbname)\n}\n\nfunc Conn() (*Storage, error) {\n\tvar (\n\t\tstrg Storage\n\t\terr error\n\t)\n\tstrg.Storage, err = conn()\n\treturn &strg, err\n}\n\nfunc DbConfig() (string, string) {\n\turl, _ := config.GetString(\"database:url\")\n\tif url == \"\" {\n\t\turl = DefaultDatabaseURL\n\t}\n\tdbname, _ := config.GetString(\"database:name\")\n\tif dbname == \"\" {\n\t\tdbname = DefaultDatabaseName\n\t}\n\treturn url, dbname\n}\n\n\nfunc (s *Storage) Repository() *storage.Collection {\n\treturn s.Collection(\"repository\")\n}\n\n\nfunc (s *Storage) User() *storage.Collection {\n\treturn s.Collection(\"user\")\n}\n\n\n\nfunc (s *Storage) Key() *storage.Collection ", "output": "{\n\tbodyIndex := mgo.Index{Key: []string{\"body\"}, Unique: true}\n\tnameIndex := mgo.Index{Key: []string{\"username\", \"name\"}, Unique: true}\n\tc := s.Collection(\"key\")\n\tc.EnsureIndex(bodyIndex)\n\tc.EnsureIndex(nameIndex)\n\treturn c\n}"} {"input": "package crypto\n\nimport (\n\t\"errors\"\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"encoding/pem\"\n)\n\n\n\nfunc LoadRSAPublicKey(key []byte) (*rsa.PublicKey, error) {\n\tparsed_key, err := LoadPublicKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar rsa_public_key *rsa.PublicKey\n\tvar ok bool = false\n\trsa_public_key, ok = parsed_key.(*rsa.PublicKey)\n\tif !ok {\n\t\treturn nil, errors.New(\"invalid RSA public key.\")\n\t}\n\n\treturn rsa_public_key, nil\n}\n\nfunc CreateRSAPrivateKeyPEM(prvkey *rsa.PrivateKey) ([]byte, error) {\n\tder := x509.MarshalPKCS1PrivateKey(prvkey)\n\tdata := pem.EncodeToMemory(\n\t\t&pem.Block{\n\t\t\tType: \"RSA PRIVATE KEY\",\n\t\t\tBytes: der,\n\t\t},\n\t)\n\n\treturn data, nil\n}\n\nfunc CreateRSAPublicKeyPEM(pubkey *rsa.PublicKey) ([]byte, error) {\n\tder, err := x509.MarshalPKIXPublicKey(pubkey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata := pem.EncodeToMemory(\n\t\t&pem.Block{\n\t\t\tType: \"RSA PUBLIC KEY\",\n\t\t\tBytes: der,\n\t\t},\n\t)\n\n\treturn data, nil\n}\n\nfunc LoadRSAPrivateKey(key []byte) (*rsa.PrivateKey, error) ", "output": "{\n\tparsed_key, err := LoadPrivateKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar rsa_private_key *rsa.PrivateKey\n\tvar ok bool = false\n\trsa_private_key, ok = parsed_key.(*rsa.PrivateKey)\n\tif !ok {\n\t\treturn nil, errors.New(\"invalid RSA private key.\")\n\t}\n\n\treturn rsa_private_key, nil\n}"} {"input": "package sw\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/sha256\"\n\t\"crypto/x509\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/hyperledger/fabric/bccsp\"\n)\n\n\n\n\n\n\ntype rsaPublicKey struct{ pubKey *rsa.PublicKey }\n\nfunc (k *rsaPublicKey) Symmetric() bool { return false }\nfunc (k *rsaPublicKey) Private() bool { return false }\n\n\n\nfunc (k *rsaPublicKey) Bytes() (raw []byte, err error) {\n\tif k.pubKey == nil {\n\t\treturn nil, errors.New(\"Failed marshalling key. Key is nil.\")\n\t}\n\traw, err = x509.MarshalPKIXPublicKey(k.pubKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed marshalling key [%s]\", err)\n\t}\n\treturn\n}\n\n\nfunc (k *rsaPublicKey) SKI() []byte {\n\tif k.pubKey == nil {\n\t\treturn nil\n\t}\n\n\traw := x509.MarshalPKCS1PublicKey(k.pubKey)\n\thash := sha256.Sum256(raw)\n\treturn hash[:]\n}\n\nfunc (k *rsaPublicKey) PublicKey() (bccsp.Key, error) ", "output": "{ return k, nil }"} {"input": "package vflag\n\nimport \"strings\"\nimport \"net/url\"\n\n\ntype URL struct {\n\tRaw string\n\tSolt *url.URL\n\tSchemes *[]string\n\tRequirePort bool\n}\n\n\n\nfunc (val URL) Set(urlArg string) error {\n\tvar err error = nil\n\tvar u *url.URL = nil\n\tvar isValid bool = false\n\n\tif u, err = url.Parse(urlArg); err != nil {\n\t\treturn err\n\t}\n\tif strings.Index(u.Host, \":\") == -1 && val.RequirePort {\n\t\treturn ErrUrlNoPort\n\t}\n\tif val.Schemes != nil {\n\t\tfor _, s := range *val.Schemes {\n\t\t\tif s == u.Scheme {\n\t\t\t\tisValid = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !isValid {\n\t\t\treturn ErrInvalidUrlScheme\n\t\t}\n\t}\n\t*val.Solt = *u\n\n\treturn nil\n}\n\nfunc (val URL) String() string ", "output": "{\n\treturn val.Raw\n}"} {"input": "package iterfloat32\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"sync\"\n)\n\ntype Slice struct {\n\tSlice []float32\n\terr error\n\tindex int\n\tmutex sync.RWMutex\n\tclosed bool\n\tdatum float32\n}\n\nfunc (receiver *Slice) Close() error {\n\tif nil == receiver {\n\t\treturn errNilReceiver\n\t}\n\n\treceiver.mutex.Lock()\n\tdefer receiver.mutex.Unlock()\n\n\treceiver.closed = true\n\n\treturn nil\n}\n\n\n\n\nfunc (receiver *Slice) Decode(x interface{}) error {\n\tif nil == receiver {\n\t\treturn errNilReceiver\n\t}\n\n\treceiver.mutex.RLock()\n\tdefer receiver.mutex.RUnlock()\n\n\tswitch p := x.(type) {\n\tcase *float32:\n\t\tif nil == p {\n\t\t\treturn nil\n\t\t}\n\n\t\t*p = receiver.datum\n\tcase *interface{}:\n\t\tif nil == p {\n\t\t\treturn nil\n\t\t}\n\n\t\t*p = receiver.datum\n\tcase sql.Scanner:\n\t\treturn p.Scan( float64(receiver.datum) )\n\tdefault:\n\t\treturn &internalBadTypeComplainer{fmt.Sprintf(\"%T\", p)}\n\t}\n\n\treturn nil\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (receiver *Slice) Next() bool {\n\tif nil == receiver {\n\t\treturn false\n\t}\n\n\treceiver.mutex.Lock()\n\tdefer receiver.mutex.Unlock()\n\n\tif nil != receiver.err {\n\t\treturn false\n\t}\n\n\tif receiver.closed {\n\t\treturn false\n\t}\n\n\tslice := receiver.Slice\n\tif nil == slice {\n\t\treturn false\n\t}\n\n\tindex := receiver.index\n\tif len(slice) <= index {\n\t\treturn false\n\t}\n\n\treceiver.datum = slice[index]\n\treceiver.index++\n\n\treturn true\n}\n\nfunc (receiver *Slice) Err() error ", "output": "{\n\tif nil == receiver {\n\t\treturn errNilReceiver\n\t}\n\n\treceiver.mutex.RLock()\n\tdefer receiver.mutex.RUnlock()\n\n\treturn receiver.err\n}"} {"input": "package registry\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/blevesearch/bleve/analysis\"\n)\n\nfunc RegisterAnalyzer(name string, constructor AnalyzerConstructor) {\n\t_, exists := analyzers[name]\n\tif exists {\n\t\tpanic(fmt.Errorf(\"attempted to register duplicate analyzer named '%s'\", name))\n\t}\n\tanalyzers[name] = constructor\n}\n\ntype AnalyzerConstructor func(config map[string]interface{}, cache *Cache) (*analysis.Analyzer, error)\ntype AnalyzerRegistry map[string]AnalyzerConstructor\ntype AnalyzerCache map[string]*analysis.Analyzer\n\nfunc (c AnalyzerCache) AnalyzerNamed(name string, cache *Cache) (*analysis.Analyzer, error) {\n\tanalyzer, cached := c[name]\n\tif cached {\n\t\treturn analyzer, nil\n\t}\n\tanalyzerConstructor, registered := analyzers[name]\n\tif !registered {\n\t\treturn nil, fmt.Errorf(\"no analyzer with name or type '%s' registered\", name)\n\t}\n\tanalyzer, err := analyzerConstructor(nil, cache)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error building analyzer: %v\", err)\n\t}\n\tc[name] = analyzer\n\treturn analyzer, nil\n}\n\n\n\nfunc AnalyzerTypesAndInstances() ([]string, []string) {\n\temptyConfig := map[string]interface{}{}\n\temptyCache := NewCache()\n\ttypes := make([]string, 0)\n\tinstances := make([]string, 0)\n\tfor name, cons := range analyzers {\n\t\t_, err := cons(emptyConfig, emptyCache)\n\t\tif err == nil {\n\t\t\tinstances = append(instances, name)\n\t\t} else {\n\t\t\ttypes = append(types, name)\n\t\t}\n\t}\n\treturn types, instances\n}\n\nfunc (c AnalyzerCache) DefineAnalyzer(name string, typ string, config map[string]interface{}, cache *Cache) (*analysis.Analyzer, error) ", "output": "{\n\t_, cached := c[name]\n\tif cached {\n\t\treturn nil, fmt.Errorf(\"analyzer named '%s' already defined\", name)\n\t}\n\tanalyzerConstructor, registered := analyzers[typ]\n\tif !registered {\n\t\treturn nil, fmt.Errorf(\"no analyzer type '%s' registered\", typ)\n\t}\n\tanalyzer, err := analyzerConstructor(config, cache)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error building analyzer: %v\", err)\n\t}\n\tc[name] = analyzer\n\treturn analyzer, nil\n}"} {"input": "package utils\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"os\"\n\t\"strconv\"\n)\n\nvar path string\n\nfunc init() {\n\tflag.StringVar(&path, \"path\", \"\", \"Path to the inputfile\")\n\tflag.Parse()\n}\n\ntype Input struct {\n\t*bufio.Scanner\n}\n\n\nfunc GetInput() (*Input, error) {\n\tif len(path) > 0 {\n\t\tfile, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn &Input{}, err\n\t\t}\n\n\t\treturn &Input{bufio.NewScanner(file)}, nil\n\t}\n\treturn &Input{bufio.NewScanner(os.Stdin)}, nil\n}\n\nfunc (input *Input) ReadInt() int {\n\tinput.Split(bufio.ScanWords)\n\n\tif input.Scan() {\n\t\tresult, err := strconv.Atoi(input.Text())\n\t\tif err == nil {\n\t\t\treturn result\n\t\t}\n\t}\n\n\treturn 3\n}\n\nfunc (input *Input) ReadInts(size int) []int {\n\tinput.Split(bufio.ScanWords)\n\tints := make([]int, size)\n\n\tfor i := 0; i < size && input.Scan(); i++ {\n\t\tresult, err := strconv.Atoi(input.Text())\n\t\tif err == nil {\n\t\t\tints[i] = result\n\t\t}\n\t}\n\n\treturn ints\n}\n\n\n\nfunc (input *Input) ReadStrings(size int) []string {\n\tinput.Split(bufio.ScanWords)\n\n\tstrings := make([]string, size)\n\n\tfor i := 0; i < size && input.Scan(); i++ {\n\t\tstrings[i] = input.Text()\n\t}\n\n\treturn strings\n}\n\nfunc (input *Input) ReadString() string ", "output": "{\n\tinput.Split(bufio.ScanWords)\n\n\tif input.Scan() {\n\t\treturn input.Text()\n\t}\n\n\treturn \"\"\n}"} {"input": "package libvirt_kvm\n\nimport (\n\tenvdriver \"github.com/dorzheh/deployer/drivers/env_driver/libvirt/libvirt_kvm\"\n\t\"github.com/dorzheh/deployer/utils\"\n\t\"github.com/dorzheh/deployer/utils/sysinfo\"\n\tssh \"github.com/dorzheh/infra/comm/common\"\n)\n\nconst (\n\tmultiQueueLibvirtVersion = \"1.0.6\"\n\tmultiQueueKernelVersion = \"3.8\"\n)\n\n\n\n\nfunc MultiQueueSupportedMock(kernelVersion, libvirtVersion string, sshconfig *ssh.Config) (bool, error) {\n\tc := sysinfo.NewCollector(sshconfig)\n\tif c.KernelMajorMinorEqualOrGreaterThan(kernelVersion) {\n\t\td := envdriver.NewDriver(sshconfig)\n\t\tcurVersion, err := d.Version()\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif curVersion >= libvirtVersion {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}\n\nfunc MultiQueueSupported(sshconfig *ssh.Config) (bool, error) ", "output": "{\n\tc := sysinfo.NewCollector(sshconfig)\n\tif c.KernelMajorMinorEqualOrGreaterThan(multiQueueKernelVersion) {\n\t\td := envdriver.NewDriver(sshconfig)\n\t\tcurVersion, err := d.Version()\n\t\tif err != nil {\n\t\t\treturn false, utils.FormatError(err)\n\t\t}\n\t\tif curVersion >= multiQueueLibvirtVersion {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}"} {"input": "package collector\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/log\"\n)\n\n\nimport \"C\"\n\ntype loadavgCollector struct {\n\tmetric prometheus.Gauge\n}\n\nfunc init() {\n\tFactories[\"loadavg\"] = NewLoadavgCollector\n}\n\n\n\nfunc NewLoadavgCollector() (Collector, error) {\n\treturn &loadavgCollector{\n\t\tmetric: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tNamespace: Namespace,\n\t\t\tName: \"load1\",\n\t\t\tHelp: \"1m load average.\",\n\t\t}),\n\t}, nil\n}\n\n\n\nfunc getLoad1() (float64, error) {\n\tvar loadavg [1]C.double\n\tsamples := C.getloadavg(&loadavg[0], 1)\n\tif samples > 0 {\n\t\treturn float64(loadavg[0]), nil\n\t} else {\n\t\treturn 0, errors.New(\"failed to get load average\")\n\t}\n\n}\n\nfunc (c *loadavgCollector) Update(ch chan<- prometheus.Metric) (err error) ", "output": "{\n\tload, err := getLoad1()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Couldn't get load: %s\", err)\n\t}\n\tlog.Debugf(\"Set node_load: %f\", load)\n\tc.metric.Set(load)\n\tc.metric.Collect(ch)\n\treturn err\n}"} {"input": "package errors\n\nimport (\n\t\"github.com/juliengk/stack/errors\"\n)\n\nconst (\n\tSuccess errors.Category = 10000 * iota \n\n\tDatabaseError \n)\n\nconst (\n\tUnknown errors.Reason = iota \n\tReadFailed \n)\n\n\n\nfunc New(category errors.Category, reason errors.Reason) *errors.Error ", "output": "{\n\terrorCode := int(category) + int(reason)\n\tvar msg string\n\tswitch category {\n\tcase DatabaseError:\n\t\tswitch reason {\n\t\tcase Unknown:\n\t\t\tmsg = \"Unknown database error\"\n\t\tcase ReadFailed:\n\t\t\tmsg = \"Failed to read database\"\n\t\t}\n\tdefault:\n\t\tmsg = errors.DefaultTypeErrorString(category)\n\t}\n\n\treturn &errors.Error{ErrorCode: errorCode, Message: msg}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\n\n\nfunc middlewareSecond(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"MiddlewareSecond - Before Handler\")\n\t\tif r.URL.Path == \"/message\" {\n\t\t\tif r.URL.Query().Get(\"password\") == \"pass123\" {\n\t\t\t\tlog.Println(\"Authorized to the system\")\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t} else {\n\t\t\t\tlog.Println(\"Failed to authorize to the system\")\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t}\n\t\tlog.Println(\"MiddlewareSecond - After Handler\")\n\t})\n}\n\nfunc index(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Executing index handler\")\n\tfmt.Fprintf(w, \"Welcome!\")\n}\n\nfunc message(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Excuting message Handler\")\n\tfmt.Fprintf(w, \"HTTP Middleware is awesome\")\n}\n\nfunc iconHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.ServeFile(w, r, \"./favicon.ico\")\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/favicon.ico\", iconHandler)\n\n\thttp.Handle(\"/\", middlewareFirst(middlewareSecond(http.HandlerFunc(index))))\n\thttp.Handle(\"/message\", middlewareFirst(middlewareSecond(http.HandlerFunc(message))))\n\n\tserver := &http.Server{\n\t\tAddr: \":8080\",\n\t}\n\tlog.Println(\"Listening...\")\n\tserver.ListenAndServe()\n}\n\nfunc middlewareFirst(next http.Handler) http.Handler ", "output": "{\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"MiddlewareFirst - Before Handler\")\n\t\tnext.ServeHTTP(w, r)\n\t\tlog.Println(\"MiddlewareFirst- After Handler\")\n\t})\n}"} {"input": "package cryptoutil\n\nimport (\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\t\"crypto/rand\"\n)\n\n\n\n\n\n\n\nfunc SymmetricDecrypt(ciph cipher.Block, src []byte) []byte {\n\tiv := src[:aes.BlockSize]\n\tnewECBDecrypter(ciph).CryptBlocks(iv, iv)\n\n\tdata := src[aes.BlockSize:]\n\tcipher.NewCBCDecrypter(ciph, iv).CryptBlocks(data, data)\n\n\treturn unpadPKCS7(data)\n}\n\nfunc SymmetricEncrypt(ciph cipher.Block, src []byte) []byte ", "output": "{\n\tiv := make([]byte, aes.BlockSize, aes.BlockSize)\n\t_, err := rand.Read(iv)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tencryptedIv := make([]byte, aes.BlockSize, aes.BlockSize)\n\tnewECBEncrypter(ciph).CryptBlocks(encryptedIv, iv)\n\n\tencrypted := padPKCS7WithIV(src)\n\tcopy(encrypted, encryptedIv)\n\tcipher.NewCBCEncrypter(ciph, iv).CryptBlocks(encrypted[aes.BlockSize:], encrypted[aes.BlockSize:])\n\treturn encrypted\n}"} {"input": "package zip\n\nimport (\n\t\"bytes\"\n\t\"compress/zlib\"\n\t\"io/ioutil\"\n)\n\n\nfunc Deflate(b []byte) ([]byte, error) {\n\tr := bytes.Buffer{}\n\tw := zlib.NewWriter(&r)\n\t_, err := w.Write(b)\n\tw.Close()\n\tif err == nil {\n\t\treturn r.Bytes(), nil\n\t}\n\treturn nil, err\n}\n\n\n\n\nfunc Inflate(b []byte) ([]byte, error) ", "output": "{\n\tbuf := bytes.NewBuffer(b)\n\tr, err := zlib.NewReader(buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Close()\n\treturn ioutil.ReadAll(r)\n}"} {"input": "package bot\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/graffic/wanon/telegram\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\n\ntype ConfService struct {\n\tbytes []byte\n}\n\n\nfunc LoadConf(fileName string) (*ConfService, error) {\n\tconf := new(ConfService)\n\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\tconf.bytes, err = ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\treturn conf, nil\n}\n\n\n\n\n\nfunc createAPI(conf *ConfService) (telegram.API, error) {\n\tvar apiConf telegram.Configuration\n\tconf.Get(&apiConf)\n\tapi := telegram.NewAPI(&http.Client{Timeout: time.Second * 15}, apiConf)\n\tresult, err := api.GetMe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Info(\"%s online\", result.Username)\n\n\treturn api, nil\n}\n\nfunc (service *ConfService) Get(in interface{}) error ", "output": "{\n\treturn yaml.Unmarshal(service.bytes, in)\n}"} {"input": "package mocks\n\nimport (\n\tcli \"github.com/stackanetes/kubernetes-entrypoint/client\"\n\tv1batch \"k8s.io/client-go/1.5/kubernetes/typed/batch/v1\"\n\tv1core \"k8s.io/client-go/1.5/kubernetes/typed/core/v1\"\n\tv1beta1extensions \"k8s.io/client-go/1.5/kubernetes/typed/extensions/v1beta1\"\n)\n\ntype Client struct {\n\tv1core.PodInterface\n\tv1core.ServiceInterface\n\tv1beta1extensions.DaemonSetInterface\n\tv1core.EndpointsInterface\n\tv1batch.JobInterface\n}\n\n\n\nfunc (c Client) Services(namespace string) v1core.ServiceInterface {\n\treturn c.ServiceInterface\n}\n\nfunc (c Client) DaemonSets(namespace string) v1beta1extensions.DaemonSetInterface {\n\treturn c.DaemonSetInterface\n}\n\nfunc (c Client) Endpoints(namespace string) v1core.EndpointsInterface {\n\treturn c.EndpointsInterface\n}\nfunc (c Client) Jobs(namespace string) v1batch.JobInterface {\n\treturn c.JobInterface\n}\n\nfunc NewClient() cli.ClientInterface {\n\treturn Client{\n\t\tNewPClient(),\n\t\tNewSClient(),\n\t\tNewDSClient(),\n\t\tNewEClient(),\n\t\tNewJClient(),\n\t}\n}\n\nfunc (c Client) Pods(namespace string) v1core.PodInterface ", "output": "{\n\treturn c.PodInterface\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1beta1 \"knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1\"\n)\n\ntype FakeServingV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeServingV1beta1) Configurations(namespace string) v1beta1.ConfigurationInterface {\n\treturn &FakeConfigurations{c, namespace}\n}\n\nfunc (c *FakeServingV1beta1) Revisions(namespace string) v1beta1.RevisionInterface {\n\treturn &FakeRevisions{c, namespace}\n}\n\n\n\nfunc (c *FakeServingV1beta1) Services(namespace string) v1beta1.ServiceInterface {\n\treturn &FakeServices{c, namespace}\n}\n\n\n\nfunc (c *FakeServingV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeServingV1beta1) Routes(namespace string) v1beta1.RouteInterface ", "output": "{\n\treturn &FakeRoutes{c, namespace}\n}"} {"input": "package utils\n\nimport (\n\t\"reflect\"\n\t\"runtime\"\n\t\"testing\"\n)\n\nfunc assert(t *testing.T, actual interface{}, expected interface{}) {\n\tif !reflect.DeepEqual(actual, expected) {\n\t\t_, fn, line, _ := runtime.Caller(1)\n\t\tt.Errorf(\"Expected %v, actual %v\\n@%s:%d\", expected, actual, fn, line)\n\t}\n}\n\nfunc assertFatal(t *testing.T, actual interface{}, expected interface{}) {\n\tif !reflect.DeepEqual(actual, expected) {\n\t\t_, fn, line, _ := runtime.Caller(1)\n\t\tt.Fatalf(\"Expected %v, actual %v\\n@%s:%d\", expected, actual, fn, line)\n\t}\n}\n\n\n\nfunc assertNot(t *testing.T, actual interface{}, expected interface{}) ", "output": "{\n\tif reflect.DeepEqual(actual, expected) {\n\t\t_, fn, line, _ := runtime.Caller(1)\n\t\tt.Fatalf(\"Expected anything but %v, actual %v\\n@%s:%d\", expected, actual, fn, line)\n\t}\n}"} {"input": "package version\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\nconst Version = \"1.2.1\"\n\n\nconst VersionPrerelease = \"dev\"\n\n\n\n\nfunc FormattedVersion() string ", "output": "{\n\tvar versionString bytes.Buffer\n\tfmt.Fprintf(&versionString, \"%s\", Version)\n\n\tif VersionPrerelease != \"\" {\n\t\tfmt.Fprintf(&versionString, \"-%s\", VersionPrerelease)\n\t}\n\n\treturn versionString.String()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\ttests := [][]int{{0,1,0},{0,2,1,0}}\n\n\tfor _, test := range tests {\n\t\tfmt.Println(peakIndexInMountainArray(test))\n\t}\n}\n\n\n\nfunc peakIndexInMountainArray(A []int) int ", "output": "{\n if len(A) < 3 {\n\t\treturn -1\n\t}\n\n\tfor i := 0; i < len(A); i++ {\n\t\tif i+1 < len(A) {\n\t\t\tif A[i] > A[i + 1] {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t}\n\n\treturn -1\n}"} {"input": "package pes\n\nimport \"io\"\nimport \"bytes\"\nimport \"github.com/32bitkid/bitreader\"\n\n\nfunc NewPayloadReader(source io.Reader) io.Reader {\n\treturn &payloadReader{\n\t\tbr: bitreader.NewReader(source),\n\t\tcurrentPacket: new(Packet),\n\t}\n}\n\ntype payloadReader struct {\n\tbr bitreader.BitReader\n\tcurrentPacket *Packet\n\tremainder bytes.Buffer\n}\n\n\n\nfunc (r *payloadReader) Read(p []byte) (n int, err error) ", "output": "{\n\tfor len(p) > 0 {\n\t\tcn, err := r.remainder.Read(p)\n\t\tn += cn\n\t\tp = p[cn:]\n\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn n, err\n\t\t}\n\t}\n\n\tvar remainder []byte\n\n\tfor len(p) > 0 {\n\t\terr := r.currentPacket.Next(r.br)\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\n\t\tcn := copy(p, r.currentPacket.Payload)\n\t\tn += cn\n\t\tp = p[cn:]\n\t\tremainder = r.currentPacket.Payload[cn:]\n\t}\n\n\t_, err = r.remainder.Write(remainder)\n\n\treturn\n}"} {"input": "package thriftclient\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"git.apache.org/thrift.git/lib/go/thrift\"\n)\n\ntype transportFactory struct {\n\tserviceIP string\n\tservicePort int\n\ttimeOut int64\n}\n\n\n\n\nfunc (tf *transportFactory) CreateObj() (interface{}, error) {\n\ttransportFactory := thrift.NewTTransportFactory()\n\tvar err error\n\tvar transport thrift.TTransport\n\taddr := fmt.Sprintf(\"%s:%d\", tf.serviceIP, tf.servicePort)\n\ttransport, err = thrift.NewTSocketTimeout(addr, time.Duration(tf.timeOut)*time.Millisecond)\n\tif err != nil {\n\t\tfmt.Println(\"Error opening socket:\", err)\n\t\treturn nil, err\n\t}\n\ttransport = transportFactory.GetTransport(transport)\n\tif err := transport.Open(); err != nil {\n\t\tfmt.Println(\"Error transport opening:\", err)\n\t\treturn nil, err\n\t}\n\treturn transport, nil\n}\n\n\nfunc (tf *transportFactory) DestroyObj(t interface{}) error {\n\tvalue, ok := t.(thrift.TTransport)\n\tif ok {\n\t\tif value.IsOpen() {\n\t\t\tvalue.Close()\n\t\t}\n\t}\n\treturn nil\n\n}\n\n\nfunc (tf *transportFactory) ValidateObj(t interface{}) error {\n\tvalue, ok := t.(thrift.TTransport)\n\tif ok {\n\t\tif value.IsOpen() {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn errors.New(\"transport is not validate\")\n}\n\nfunc NewTransportFactory(serviceIP string, servicePort int, timeOut int64) *transportFactory ", "output": "{\n\treturn &transportFactory{serviceIP: serviceIP, servicePort: servicePort, timeOut: timeOut}\n}"} {"input": "package alert\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/opsgenie/opsgenie-go-sdk-v2/client\"\n\t\"github.com/pkg/errors\"\n)\n\ntype DeleteAttachmentRequest struct {\n\tclient.BaseRequest\n\tIdentifierType AlertIdentifier\n\tIdentifierValue string\n\tAttachmentId string\n\tUser string\n}\n\nfunc (r *DeleteAttachmentRequest) Validate() error {\n\tif r.AttachmentId == \"\" {\n\t\treturn errors.New(\"AttachmentId can not be empty\")\n\t}\n\n\tif r.IdentifierValue == \"\" {\n\t\treturn errors.New(\"Identifier can not be empty\")\n\t}\n\treturn nil\n}\n\nfunc (r *DeleteAttachmentRequest) ResourcePath() string {\n\n\treturn \"/v2/alerts/\" + r.IdentifierValue + \"/attachments/\" + r.AttachmentId\n}\n\n\n\nfunc (r *DeleteAttachmentRequest) RequestParams() map[string]string {\n\n\tparams := make(map[string]string)\n\n\tif r.IdentifierType == ALIAS {\n\t\tparams[\"alertIdentifierType\"] = \"alias\"\n\n\t} else if r.IdentifierType == TINYID {\n\t\tparams[\"alertIdentifierType\"] = \"tiny\"\n\n\t} else {\n\t\tparams[\"alertIdentifierType\"] = \"id\"\n\n\t}\n\n\tif r.User != \"\" {\n\t\tparams[\"user\"] = r.User\n\t}\n\n\treturn params\n}\n\nfunc (r *DeleteAttachmentRequest) Method() string ", "output": "{\n\treturn http.MethodDelete\n}"} {"input": "package sign\n\nimport (\n\t\"dfss\"\n\tcAPI \"dfss/dfssc/api\"\n\tpAPI \"dfss/dfssp/api\"\n\t\"dfss/dfsst/entities\"\n\t\"dfss/net\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\ntype clientServer struct {\n\tincomingPromises chan interface{}\n\tincomingSignatures chan interface{}\n}\n\nfunc getServerErrorCode(c chan interface{}, in interface{}) *pAPI.ErrorCode {\n\tif c != nil {\n\t\tc <- in\n\t\treturn &pAPI.ErrorCode{Code: pAPI.ErrorCode_SUCCESS}\n\t}\n\treturn &pAPI.ErrorCode{Code: pAPI.ErrorCode_INTERR} \n}\n\n\n\n\n\n\n\n\n\nfunc (s *clientServer) TreatSignature(ctx context.Context, in *cAPI.Signature) (*pAPI.ErrorCode, error) {\n\treturn getServerErrorCode(s.incomingSignatures, in), nil\n}\n\n\n\n\nfunc (s *clientServer) Discover(ctx context.Context, in *cAPI.Hello) (*cAPI.Hello, error) {\n\treturn &cAPI.Hello{Version: dfss.Version}, nil\n}\n\n\nfunc (m *SignatureManager) GetServer() *grpc.Server {\n\tserver := net.NewServer(m.auth.Cert, m.auth.Key, m.auth.CA)\n\tm.cServerIface = clientServer{}\n\tcAPI.RegisterClientServer(server, &m.cServerIface)\n\treturn server\n}\n\nfunc (s *clientServer) TreatPromise(ctx context.Context, in *cAPI.Promise) (*pAPI.ErrorCode, error) ", "output": "{\n\tvalid, _, _, _ := entities.IsRequestValid(ctx, []*cAPI.Promise{in})\n\tif !valid {\n\t\treturn &pAPI.ErrorCode{Code: pAPI.ErrorCode_SUCCESS}, nil\n\t}\n\treturn getServerErrorCode(s.incomingPromises, in), nil\n}"} {"input": "package bits\n\nimport (\n\t\"path/filepath\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"k8s.io/kubeadm/kinder/pkg/extract\"\n)\n\n\n\ntype binaryBits struct {\n\tsrc string\n\tbinaryName string\n}\n\nvar _ Installer = &binaryBits{}\n\n\nfunc NewBinaryBits(src, binaryName string) Installer {\n\treturn &binaryBits{\n\t\tsrc: src,\n\t\tbinaryName: binaryName,\n\t}\n}\n\n\nfunc (b *binaryBits) Prepare(c *BuildContext) (map[string]string, error) {\n\te := extract.NewExtractor(\n\t\tb.src, c.HostBitsPath(),\n\t\textract.OnlyKubeadm(b.binaryName == \"kubeadm\"),\n\t\textract.OnlyKubelet(b.binaryName == \"kubelet\"),\n\t)\n\n\treturn e.Extract()\n}\n\n\n\n\nfunc (b *binaryBits) Install(c *BuildContext) error ", "output": "{\n\tsrc := filepath.Join(c.ContainerBitsPath(), b.binaryName)\n\n\tdest := filepath.Join(\"/usr\", \"bin\", b.binaryName)\n\n\tif err := c.RunInContainer(\"cp\", src, dest); err != nil {\n\t\tlog.Errorf(\"Image alter Failed! %v\", err)\n\t\treturn err\n\t}\n\n\tif err := c.RunInContainer(\"chown\", \"-R\", \"root:root\", dest); err != nil {\n\t\tlog.Errorf(\"Image alter failed! %v\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package mount\n\n\nfunc GetMounts() ([]*Info, error) {\n\treturn parseMountTable()\n}\n\n\n\n\n\n\n\n\n\nfunc Mount(device, target, mType, options string) error {\n\tflag, _ := parseOptions(options)\n\tif flag&REMOUNT != REMOUNT {\n\t\tif mounted, err := Mounted(target); err != nil || mounted {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn ForceMount(device, target, mType, options)\n}\n\n\n\n\n\nfunc ForceMount(device, target, mType, options string) error {\n\tflag, data := parseOptions(options)\n\treturn mount(device, target, mType, uintptr(flag), data)\n}\n\n\n\nfunc Unmount(target string) error {\n\tif mounted, err := Mounted(target); err != nil || !mounted {\n\t\treturn err\n\t}\n\treturn unmount(target, mntDetach)\n}\n\nfunc Mounted(mountpoint string) (bool, error) ", "output": "{\n\tentries, err := parseMountTable()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, e := range entries {\n\t\tif e.Mountpoint == mountpoint {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}"} {"input": "package deduplicator\n\nimport (\n\t\"context\"\n\n\tdataStore \"github.com/tidepool-org/platform/data/store\"\n\tdataTypesUpload \"github.com/tidepool-org/platform/data/types/upload\"\n\t\"github.com/tidepool-org/platform/errors\"\n)\n\nconst DeviceTruncateDataSetName = \"org.tidepool.deduplicator.device.truncate.dataset\"\n\nvar DeviceTruncateDataSetDeviceManufacturers = []string{\"Animas\"}\n\ntype DeviceTruncateDataSet struct {\n\t*Base\n}\n\nfunc NewDeviceTruncateDataSet() (*DeviceTruncateDataSet, error) {\n\tbase, err := NewBase(DeviceTruncateDataSetName, \"1.1.0\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &DeviceTruncateDataSet{\n\t\tBase: base,\n\t}, nil\n}\n\n\n\nfunc (t *DeviceTruncateDataSet) Get(dataSet *dataTypesUpload.Upload) (bool, error) {\n\tif found, err := t.Base.Get(dataSet); err != nil || found {\n\t\treturn found, err\n\t}\n\n\treturn dataSet.HasDeduplicatorNameMatch(\"org.tidepool.truncate\"), nil \n}\n\nfunc (t *DeviceTruncateDataSet) Close(ctx context.Context, repository dataStore.DataRepository, dataSet *dataTypesUpload.Upload) error {\n\tif ctx == nil {\n\t\treturn errors.New(\"context is missing\")\n\t}\n\tif repository == nil {\n\t\treturn errors.New(\"repository is missing\")\n\t}\n\tif dataSet == nil {\n\t\treturn errors.New(\"data set is missing\")\n\t}\n\n\tif err := repository.DeleteOtherDataSetData(ctx, dataSet); err != nil {\n\t\treturn err\n\t}\n\n\treturn t.Base.Close(ctx, repository, dataSet)\n}\n\nfunc (t *DeviceTruncateDataSet) New(dataSet *dataTypesUpload.Upload) (bool, error) ", "output": "{\n\tif dataSet == nil {\n\t\treturn false, errors.New(\"data set is missing\")\n\t}\n\n\tif !dataSet.HasDataSetTypeNormal() {\n\t\treturn false, nil\n\t}\n\tif dataSet.DeviceID == nil {\n\t\treturn false, nil\n\t}\n\n\tif dataSet.HasDeduplicatorName() {\n\t\treturn t.Get(dataSet)\n\t}\n\n\tif dataSet.DeviceManufacturers == nil {\n\t\treturn false, nil\n\t}\n\n\tfor _, deviceManufacturer := range *dataSet.DeviceManufacturers {\n\t\tfor _, allowedDeviceManufacturer := range DeviceTruncateDataSetDeviceManufacturers {\n\t\t\tif allowedDeviceManufacturer == deviceManufacturer {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false, nil\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1alpha1 \"k8s.io/kops/pkg/client/clientset_generated/clientset/typed/kops/v1alpha1\"\n)\n\ntype FakeKopsV1alpha1 struct {\n\t*testing.Fake\n}\n\n\n\nfunc (c *FakeKopsV1alpha1) InstanceGroups(namespace string) v1alpha1.InstanceGroupInterface {\n\treturn &FakeInstanceGroups{c, namespace}\n}\n\nfunc (c *FakeKopsV1alpha1) SSHCredentials(namespace string) v1alpha1.SSHCredentialInterface {\n\treturn &FakeSSHCredentials{c, namespace}\n}\n\n\n\nfunc (c *FakeKopsV1alpha1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeKopsV1alpha1) Clusters(namespace string) v1alpha1.ClusterInterface ", "output": "{\n\treturn &FakeClusters{c, namespace}\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestValidatorOverwriteEmailListViaCopyingOver(t *testing.T) {\n\tvt := NewValidatorTest(t)\n\tdefer vt.TearDown()\n\n\tvt.WriteEmails(t, []string{\"xyzzy@example.com\"})\n\tdomains := []string(nil)\n\tupdated := make(chan bool, 1)\n\tvalidator := vt.NewValidator(domains, updated)\n\n\tif !validator(\"xyzzy@example.com\") {\n\t\tt.Error(\"email in list should validate\")\n\t}\n\n\tvt.UpdateEmailFileViaCopyingOver(t, []string{\"plugh@example.com\"})\n\t<-updated\n\n\tif validator(\"xyzzy@example.com\") {\n\t\tt.Error(\"email removed from list should not validate\")\n\t}\n}\n\nfunc (vt *ValidatorTest) UpdateEmailFileViaCopyingOver(\n\tt *testing.T, emails []string) ", "output": "{\n\torig_file := vt.auth_email_file\n\tvar err error\n\tvt.auth_email_file, err = ioutil.TempFile(\"\", \"test_auth_emails_\")\n\tif err != nil {\n\t\tt.Fatal(\"failed to create temp file for copy: \" + err.Error())\n\t}\n\tvt.WriteEmails(t, emails)\n\terr = os.Rename(vt.auth_email_file.Name(), orig_file.Name())\n\tif err != nil {\n\t\tt.Fatal(\"failed to copy over temp file: \" + err.Error())\n\t}\n\tvt.auth_email_file = orig_file\n}"} {"input": "package logging\n\nimport (\n\t\"log\"\n)\n\nvar VERBOSITY int = 1\n\nfunc Lg(level int, format string, a ...interface{}) {\n\tif level <= VERBOSITY {\n\t\tlog.Printf(format, a...)\n\t}\n}\n\n\n\nfunc FailOnError(err error, format string, a ...interface{}) ", "output": "{\n\tif err != nil {\n\t\tlog.Fatalf(format, a...)\n\t}\n}"} {"input": "package cloudguard\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype UpdateManagedListRequest struct {\n\n\tManagedListId *string `mandatory:\"true\" contributesTo:\"path\" name:\"managedListId\"`\n\n\tUpdateManagedListDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateManagedListRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request UpdateManagedListRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request UpdateManagedListRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype UpdateManagedListResponse struct {\n\n\tRawResponse *http.Response\n\n\tManagedList `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateManagedListResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateManagedListResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateManagedListRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package tests\n\nimport (\n\t\"github.com/modern-go/reflect2\"\n\t\"testing\"\n\n\t\"context\"\n\t\"github.com/modern-go/test\"\n\t\"github.com/modern-go/test/must\"\n)\n\n\n\nfunc testOp(f func(api reflect2.API) interface{}) func(t *testing.T) ", "output": "{\n\treturn test.Case(func(ctx context.Context) {\n\t\tunsafeResult := f(reflect2.ConfigUnsafe)\n\t\tsafeResult := f(reflect2.ConfigSafe)\n\t\tmust.Equal(safeResult, unsafeResult)\n\t})\n}"} {"input": "package core\n\nimport (\n\t\"database/sql\"\n\t\"strconv\"\n)\n\n\ntype Migration struct {\n\tIdentifier int64\n\tName string\n\tUp func(tx *Tx)\n\tDown func(tx *Tx)\n}\n\n\nfunc (m *Migration) GetID() string {\n\treturn strconv.FormatInt(m.Identifier, 10)\n}\n\n\n\nfunc (m *Migration) Pending(db *sql.DB) bool {\n\trows, _ := db.Query(\"Select * from \" + MigrationsTable + \" WHERE identifier =\" + m.GetID())\n\tdefer rows.Close()\n\tcount := 0\n\n\tfor rows.Next() {\n\t\tcount++\n\t}\n\n\treturn count == 0\n}\n\n\ntype ByIdentifier []Migration\n\nfunc (a ByIdentifier) Len() int { return len(a) }\n\nfunc (a ByIdentifier) Less(i, j int) bool { return a[i].Identifier < a[j].Identifier }\n\nfunc (a ByIdentifier) Swap(i, j int) ", "output": "{ a[i], a[j] = a[j], a[i] }"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"gopkg.in/ini.v1\"\n)\n\n\n\nfunc DrawDate(r Renderer, f Font) {\n\t_, month, day := time.Now().Local().Date()\n\tdayOfWeek := GetDayOfWeek(time.Now().Local().Weekday())\n\tstr := fmt.Sprintf(\"%s %2d.%02d\", dayOfWeek, month, day)\n\n\tw, _ := f.Measure(str)\n\tf.Render(r, (r.Width()-w)/2, 1, str)\n}\n\nvar weekdayNames = make(map[time.Weekday]string)\n\nfunc InitializeClock() error {\n\tbytes, err := Asset(\"res/res.ini\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := ini.Load(bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsection := file.Section(\"\")\n\tweekdayNames[time.Monday] = section.Key(\"Monday\").Value()\n\tweekdayNames[time.Tuesday] = section.Key(\"Tuesday\").Value()\n\tweekdayNames[time.Wednesday] = section.Key(\"Wednesday\").Value()\n\tweekdayNames[time.Thursday] = section.Key(\"Thursday\").Value()\n\tweekdayNames[time.Friday] = section.Key(\"Friday\").Value()\n\tweekdayNames[time.Saturday] = section.Key(\"Saturday\").Value()\n\tweekdayNames[time.Sunday] = section.Key(\"Sunday\").Value()\n\n\treturn nil\n}\n\nfunc GetDayOfWeek(w time.Weekday) string {\n\tstr, exists := weekdayNames[w]\n\tif !exists {\n\t\treturn \"?\"\n\t}\n\n\treturn str\n}\n\nfunc DrawClock(r Renderer, f Font) ", "output": "{\n\th, m, _ := time.Now().Local().Clock()\n\n\tstr := fmt.Sprintf(\"%02d:%02d\", h, m)\n\n\tw, h := f.Measure(str)\n\tf.Render(r, (r.Width()-w)/2, (r.Height()-h)/2, str)\n}"} {"input": "package sol\n\n\ntype Operator interface {\n\tWrap(string) string \n}\n\n\nfunc Function(name string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(FuncClause{Name: name})\n}\n\n\nfunc Avg(col Columnar) ColumnElem {\n\treturn Function(AVG, col)\n}\n\n\nfunc Count(col Columnar) ColumnElem {\n\treturn Function(COUNT, col)\n}\n\n\nfunc Date(col Columnar) ColumnElem {\n\treturn Function(DATE, col)\n}\n\n\n\n\n\n\nfunc Max(col Columnar) ColumnElem {\n\treturn Function(MAX, col)\n}\n\n\nfunc Min(col Columnar) ColumnElem {\n\treturn Function(MIN, col)\n}\n\n\nfunc StdDev(col Columnar) ColumnElem {\n\treturn Function(STDDEV, col)\n}\n\n\nfunc Sum(col Columnar) ColumnElem {\n\treturn Function(SUM, col)\n}\n\n\nfunc Variance(col Columnar) ColumnElem {\n\treturn Function(VARIANCE, col)\n}\n\nfunc DatePart(part string, col Columnar) ColumnElem ", "output": "{\n\treturn col.Column().AddOperator(\n\t\tFuncClause{Name: DATEPART},\n\t).AddOperator(\n\t\tArrayClause{clauses: []Clause{String(part)}, post: true, sep: \", \"},\n\t)\n}"} {"input": "package response\n\nimport (\n\t\"encoding/xml\"\n)\n\ntype TransferOrders struct {\n\tResult\n\n}\n\n\n\nfunc (response TransferOrders) UnmarshalXml(body []byte) (ResponseParser, error) ", "output": "{\n\terr := xml.Unmarshal(body, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn response, nil\n}"} {"input": "package go9p\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\n\n\nfunc (dir *pipeDir) dotu(path string, d os.FileInfo, upool Users, sysMode *syscall.Win32FileAttributeData) ", "output": "{\n\n\n\tdir.Uid = \"none\"\n\tdir.Gid = \"none\"\n\tdir.Muid = \"none\"\n\tdir.Uidnum = 0\n\tdir.Gidnum = 0\n\tdir.Muidnum = NOUID\n\tdir.Ext = \"\"\n}"} {"input": "package msgpack_test\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/danjac/podbaby/api/Godeps/_workspace/src/gopkg.in/vmihailenco/msgpack.v2\"\n)\n\ntype customStruct struct {\n\tS string\n\tN int\n}\n\nvar (\n\t_ msgpack.CustomEncoder = &customStruct{}\n\t_ msgpack.CustomDecoder = &customStruct{}\n)\n\nfunc (s *customStruct) EncodeMsgpack(enc *msgpack.Encoder) error {\n\treturn enc.Encode(s.S, s.N)\n}\n\nfunc (s *customStruct) DecodeMsgpack(dec *msgpack.Decoder) error {\n\treturn dec.Decode(&s.S, &s.N)\n}\n\n\n\nfunc ExampleCustomEncoder() ", "output": "{\n\tb, err := msgpack.Marshal(&customStruct{S: \"hello\", N: 42})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar v customStruct\n\terr = msgpack.Unmarshal(b, &v)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"%#v\", v)\n}"} {"input": "package creditcard\n\nimport (\n\t\"testing\"\n)\n\ntype card struct {\n\tNumber string\n\tType string\n\tValid bool\n}\n\nvar cards = []*card{\n\t&card{\"4242424242424242\", \"Visa\", true}, \n\t&card{\"4213729238347292\", \"Visa\", false}, \n\t&card{\"79927398713\", \"Unknown\", true}, \n\t&card{\"79927398710\", \"Unknown\", false}, \n\t&card{\"6011111111111117\", \"Discover\", true}, \n\t&card{\"6011342393482022\", \"Discover\", false}, \n\t&card{\"344347386473833\", \"AmericanExpress\", false}, \n\t&card{\"374347386473833\", \"AmericanExpress\", false}, \n\t&card{\"30569309025904\", \"DinersClub/Carteblanche\", true}, \n\t&card{\"30569309025905\", \"DinersClub/Carteblanche\", false}, \n\t&card{\"5555555555554444\", \"MasterCard\", true}, \n\t&card{\"5555555555554445\", \"MasterCard\", false}, \n\t&card{\"180034239348202\", \"JCB\", false}, \n}\n\nfunc TestValidate(t *testing.T) {\n\tfor _, card := range cards {\n\t\tvalid := Validate(card.Number)\n\t\tif valid != card.Valid {\n\t\t\tt.Errorf(\"card validation [%v]; want [%v]\", valid, card.Valid)\n\t\t}\n\t}\n}\n\n\n\nfunc TestGenerateLastDigit(t *testing.T) {\n\tlastDigit := GenerateLastDigit(\"5276 4400 6542 131\")\n\n\tif lastDigit != \"9\" {\n\t\tt.Errorf(\"last digit [%s]; want [%s]\", lastDigit, \"9\")\n\t}\n}\n\nfunc TestCardype(t *testing.T) ", "output": "{\n\tfor _, card := range cards {\n\t\tcardType := Cardtype(card.Number)\n\t\tif cardType != card.Type {\n\t\t\tt.Errorf(\"card type [%s]; want [%s]\", cardType, card.Type)\n\t\t}\n\t}\n}"} {"input": "package overcurrent\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\ntype (\n\tNoopBreaker struct{}\n\n\tNoopCollector struct{}\n)\n\nvar defaultCollector = NewNoopCollector()\n\n\n\n\nfunc (b *NoopBreaker) Trip() {}\nfunc (b *NoopBreaker) Reset() {}\nfunc (b *NoopBreaker) ShouldTry() bool { return true }\nfunc (b *NoopBreaker) MarkResult(err error) bool { return true }\nfunc (b *NoopBreaker) Call(f BreakerFunc) error { return f(context.Background()) }\nfunc (b *NoopBreaker) CallAsync(f BreakerFunc) <-chan error { return nil }\n\n\nfunc NewNoopCollector() MetricCollector {\n\treturn &NoopCollector{}\n}\n\nfunc (c *NoopCollector) ReportNew(BreakerConfig) {}\nfunc (c *NoopCollector) ReportCount(EventType) {}\nfunc (c *NoopCollector) ReportDuration(EventType, time.Duration) {}\nfunc (c *NoopCollector) ReportState(CircuitState) {}\n\nfunc NewNoopBreaker() CircuitBreaker ", "output": "{\n\treturn &NoopBreaker{}\n}"} {"input": "package dockercommand\n\nimport docker \"github.com/fsouza/go-dockerclient\"\n\ntype RmOptions struct {\n\tContainer []string\n\tForce bool\n}\n\n\n\nfunc (dock *Docker) Rm(options *RmOptions) error ", "output": "{\n\tfor _, containerID := range options.Container {\n\t\terr := dock.client.RemoveContainer(docker.RemoveContainerOptions{ID: containerID, Force: options.Force})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package goldengate\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ChangeDeploymentCompartmentRequest struct {\n\n\tDeploymentId *string `mandatory:\"true\" contributesTo:\"path\" name:\"deploymentId\"`\n\n\tChangeDeploymentCompartmentDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ChangeDeploymentCompartmentRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ChangeDeploymentCompartmentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request ChangeDeploymentCompartmentRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ChangeDeploymentCompartmentResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ChangeDeploymentCompartmentResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ChangeDeploymentCompartmentResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ChangeDeploymentCompartmentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package elasticsearch\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/elastic/beats/libbeat/outputs/outil\"\n)\n\nconst ElasticsearchDefaultHost = \"localhost\"\nconst ElasticsearchDefaultPort = \"9200\"\n\nfunc GetEsPort() string {\n\tport := os.Getenv(\"ES_PORT\")\n\n\tif len(port) == 0 {\n\t\tport = ElasticsearchDefaultPort\n\t}\n\treturn port\n}\n\n\n\n\nfunc GetTestingElasticsearch() *Client {\n\tvar address = \"http://\" + GetEsHost() + \":\" + GetEsPort()\n\tusername := os.Getenv(\"ES_USER\")\n\tpass := os.Getenv(\"ES_PASS\")\n\tclient := newTestClientAuth(address, username, pass)\n\n\tclient.Connect(3 * time.Second)\n\treturn client\n}\n\nfunc newTestClientAuth(url, user, pass string) *Client {\n\tclient, err := NewClient(ClientSettings{\n\t\tURL: url,\n\t\tIndex: outil.MakeSelector(),\n\t\tUsername: user,\n\t\tPassword: pass,\n\t\tTimeout: 60 * time.Second,\n\t\tCompressionLevel: 3,\n\t}, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\nfunc GetEsHost() string ", "output": "{\n\n\thost := os.Getenv(\"ES_HOST\")\n\n\tif len(host) == 0 {\n\t\thost = ElasticsearchDefaultHost\n\t}\n\n\treturn host\n}"} {"input": "package user\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/juju/cmd\"\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/names\"\n\t\"launchpad.net/gnuflag\"\n\n\t\"github.com/juju/juju/cmd/envcmd\"\n)\n\nconst userCredentialsDoc = `\nWrites out the current user and credentials to a file that can be used\nwith 'juju system login' to allow the user to access the same environments\nas the same user from another machine.\n\nExamples:\n\n $ juju user credentials --output staging.creds\n\n # copy the staging.creds file to another machine\n\n $ juju system login staging --server staging.creds --keep-password\n\n\nSee Also:\n juju system login\n`\n\nfunc newCredentialsCommand() cmd.Command {\n\treturn envcmd.WrapSystem(&credentialsCommand{})\n}\n\n\ntype credentialsCommand struct {\n\tUserCommandBase\n\tOutPath string\n}\n\n\nfunc (c *credentialsCommand) Info() *cmd.Info {\n\treturn &cmd.Info{\n\t\tName: \"credentials\",\n\t\tPurpose: \"save the credentials and server details to a file\",\n\t\tDoc: userCredentialsDoc,\n\t}\n}\n\n\n\n\n\nfunc (c *credentialsCommand) Run(ctx *cmd.Context) error {\n\tcreds, err := c.ConnectionCredentials()\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfilename := c.OutPath\n\tif filename == \"\" {\n\t\tname := names.NewUserTag(creds.User).Name()\n\t\tfilename = fmt.Sprintf(\"%s.server\", name)\n\t}\n\treturn writeServerFile(c, ctx, creds.User, creds.Password, filename)\n}\n\nfunc (c *credentialsCommand) SetFlags(f *gnuflag.FlagSet) ", "output": "{\n\tf.StringVar(&c.OutPath, \"o\", \"\", \"specifies the path of the generated file\")\n\tf.StringVar(&c.OutPath, \"output\", \"\", \"\")\n}"} {"input": "package httpmux\n\nimport \"net/http\"\n\n\ntype ConfigOption interface {\n\tSet(c *Config)\n}\n\n\ntype ConfigOptionFunc func(c *Config)\n\n\nfunc (f ConfigOptionFunc) Set(c *Config) { f(c) }\n\n\nfunc WithPrefix(prefix string) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Prefix = prefix })\n}\n\n\nfunc WithMiddleware(mw ...Middleware) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Middleware = mw })\n}\n\n\nfunc WithMiddlewareFunc(mw ...MiddlewareFunc) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.UseFunc(mw...) })\n}\n\n\nfunc WithRedirectTrailingSlash(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectTrailingSlash = v })\n}\n\n\nfunc WithRedirectFixedPath(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectFixedPath = v })\n}\n\n\n\n\n\nfunc WithNotFound(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.NotFound = f })\n}\n\n\nfunc WithMethodNotAllowed(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.MethodNotAllowed = f })\n}\n\n\nfunc WithPanicHandler(f func(http.ResponseWriter, *http.Request, interface{})) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.PanicHandler = f })\n}\n\nfunc WithHandleMethodNotAllowed(v bool) ConfigOption ", "output": "{\n\treturn ConfigOptionFunc(func(c *Config) { c.HandleMethodNotAllowed = v })\n}"} {"input": "package goweb\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc deprecatedPanic(method, alternativeTip string) {\n\tpanic(fmt.Sprintf(\"goweb: (deprecated) %s is no longer supported. %s\", method, alternativeTip))\n}\n\n\n\n\nfunc MapFunc(path string, controllerFunc interface{}, matcherFuncs ...interface{}) interface{} {\n\tdeprecatedPanic(\"MapFunc\", \"Use goweb.Map instead.\")\n\treturn nil\n}\n\n\n\n\n\n\nfunc MapRest(pathPrefix string, controller interface{}) ", "output": "{\n\tdeprecatedPanic(\"MapRest\", \"Use goweb.MapController instead.\")\n}"} {"input": "package payload\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hyperledger/burrow/acm/acmstate\"\n\t\"github.com/hyperledger/burrow/crypto\"\n)\n\n\n\nfunc (tx *BondTx) Type() Type {\n\treturn TypeBond\n}\n\nfunc (tx *BondTx) GetInputs() []*TxInput {\n\treturn []*TxInput{tx.Input}\n}\n\nfunc (tx *BondTx) String() string {\n\treturn fmt.Sprintf(\"BondTx{%v}\", tx.Input)\n}\n\nfunc (tx *BondTx) AddInput(st acmstate.AccountGetter, pubkey *crypto.PublicKey, amt uint64) error {\n\taddr := pubkey.GetAddress()\n\tacc, err := st.GetAccount(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif acc == nil {\n\t\treturn fmt.Errorf(\"invalid address %s from pubkey %s\", addr, pubkey)\n\t}\n\treturn tx.AddInputWithSequence(pubkey, amt, acc.Sequence+uint64(1))\n}\n\nfunc (tx *BondTx) AddInputWithSequence(pubkey *crypto.PublicKey, amt uint64, sequence uint64) error {\n\ttx.Input = &TxInput{\n\t\tAddress: pubkey.GetAddress(),\n\t\tAmount: amt,\n\t\tSequence: sequence,\n\t}\n\treturn nil\n}\n\nfunc (tx *BondTx) Any() *Any {\n\treturn &Any{\n\t\tBondTx: tx,\n\t}\n}\n\nfunc NewBondTx(address crypto.Address, amount uint64) *BondTx ", "output": "{\n\treturn &BondTx{\n\t\tInput: &TxInput{\n\t\t\tAddress: address,\n\t\t\tAmount: amount,\n\t\t},\n\t}\n}"} {"input": "package via\n\nimport (\n\t\"fmt\"\n\t\"gopkg.in/src-d/go-git.v4\"\n\t\"gopkg.in/src-d/go-git.v4/plumbing\"\n\t\"os\"\n\tgpath \"path\"\n)\n\n\nfunc Clone(dir Path, url string) error {\n\t_, err := git.PlainClone(dir.String(), false, &git.CloneOptions{\n\t\tURL: url,\n\t\tProgress: os.Stdout,\n\t\tDepth: 1,\n\t\tRecurseSubmodules: git.DefaultSubmoduleRecursionDepth,\n\t})\n\treturn err\n}\n\n\nfunc gitref(branch string) plumbing.ReferenceName {\n\treturn plumbing.ReferenceName(\n\t\tfmt.Sprintf(\"refs/heads/%s\", branch),\n\t)\n}\n\n\n\n\n\n\nfunc Branch(path Path) (string, error) {\n\tr, err := git.PlainOpen(path.String())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\thead, err := r.Head()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn gpath.Base(head.Name().String()), nil\n}\n\nfunc CloneBranch(dir Path, url, branch string) error ", "output": "{\n\t_, err := git.PlainClone(dir.String(), false, &git.CloneOptions{\n\t\tURL: url,\n\t\tProgress: os.Stdout,\n\t\tDepth: 1,\n\t\tReferenceName: gitref(branch),\n\t})\n\treturn err\n}"} {"input": "package pod\n\nimport (\n\tapiv1 \"k8s.io/api/core/v1\"\n)\n\n\ntype PreProcessor interface {\n\tProcess(apiv1.Pod) (apiv1.Pod, error)\n}\n\n\ntype NoopPreProcessor struct{}\n\n\n\n\n\nfunc NewDefaultPreProcessor() PreProcessor {\n\treturn &NoopPreProcessor{}\n}\n\nfunc (p *NoopPreProcessor) Process(pod apiv1.Pod) (apiv1.Pod, error) ", "output": "{\n\treturn pod, nil\n}"} {"input": "package s3disk\n\nimport (\n\t\"os\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\n\nfunc GetCTime(fi os.FileInfo) time.Time ", "output": "{\n\tstat := fi.Sys().(*syscall.Stat_t)\n\n\treturn time.Unix(stat.Ctime.Unix())\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime/pprof\"\n)\n\nconst (\n\tusage = `Usage: %s [OPTION...]\ncontrol program for coffee roasting\n\nOptions:\n`\n)\n\nvar (\n\tmemProfile string\n\tcpuProfile string\n)\n\nfunc init() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, usage, os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\n\tflag.StringVar(&memProfile, \"memprofile\", \"\",\n\t\t\"write memory profile to this file\")\n\tflag.StringVar(&cpuProfile, \"cpuprofile\", \"\",\n\t\t\"write cpu profile to this file\")\n\n\tflag.Parse()\n}\n\n\n\n\n\nfunc stopProfiling() {\n\tif memProfile != \"\" {\n\t\truntime.GC()\n\t\tf, err := os.Create(memProfile)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tpprof.WriteHeapProfile(f)\n\t\tf.Close()\n\t}\n\tif cpuProfile != \"\" {\n\t\tpprof.StopCPUProfile()\n\t\tcpuProfile = \"\"\n\t}\n}\n\nfunc main() {\n\tstartProfiling()\n\tdefer stopProfiling()\n\n}\n\nfunc startProfiling() ", "output": "{\n\tvar err error\n\tif memProfile != \"\" {\n\t\truntime.MemProfileRate = 1\n\t}\n\tif cpuProfile != \"\" {\n\t\tvar f *os.File\n\t\tif f, err = os.Create(cpuProfile); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tpprof.StartCPUProfile(f)\n\t}\n}"} {"input": "package iso20022\n\n\ntype IndividualPersonIdentification3Choice struct {\n\n\tIdentificationNumber *GenericIdentification81 `xml:\"IdNb\"`\n\n\tPersonName *IndividualPerson35 `xml:\"PrsnNm\"`\n}\n\nfunc (i *IndividualPersonIdentification3Choice) AddIdentificationNumber() *GenericIdentification81 {\n\ti.IdentificationNumber = new(GenericIdentification81)\n\treturn i.IdentificationNumber\n}\n\n\n\nfunc (i *IndividualPersonIdentification3Choice) AddPersonName() *IndividualPerson35 ", "output": "{\n\ti.PersonName = new(IndividualPerson35)\n\treturn i.PersonName\n}"} {"input": "package riemann_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestRiemann(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Riemann Suite\")\n}"} {"input": "package xds\n\nimport (\n\t\"net\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/connectivity\"\n)\n\ntype serverOptions struct {\n\tmodeCallback ServingModeCallbackFunc\n\tbootstrapContents []byte\n}\n\ntype serverOption struct {\n\tgrpc.EmptyServerOption\n\tapply func(*serverOptions)\n}\n\n\n\nfunc ServingModeCallback(cb ServingModeCallbackFunc) grpc.ServerOption {\n\treturn &serverOption{apply: func(o *serverOptions) { o.modeCallback = cb }}\n}\n\n\n\n\n\n\ntype ServingModeCallbackFunc func(addr net.Addr, args ServingModeChangeArgs)\n\n\n\ntype ServingModeChangeArgs struct {\n\tMode connectivity.ServingMode\n\tErr error\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc BootstrapContentsForTesting(contents []byte) grpc.ServerOption ", "output": "{\n\treturn &serverOption{apply: func(o *serverOptions) { o.bootstrapContents = contents }}\n}"} {"input": "package gogetvers\n\nimport (\n\t\"os\"\n)\n\n\nfunc IsFile(path string) bool {\n\tif len(path) == 0 {\n\t\treturn false\n\t}\n\tfinfo, err := os.Stat(path)\n\treturn err == nil && !finfo.IsDir()\n\n}\n\n\nfunc IsDir(path string) bool {\n\tif len(path) == 0 {\n\t\treturn false\n\t}\n\tfinfo, err := os.Stat(path)\n\treturn err == nil && finfo.IsDir()\n}\n\n\n\n\nfunc Mkdir(path string, perm os.FileMode) error ", "output": "{\n\treturn os.MkdirAll(path, perm)\n}"} {"input": "package iso20022\n\n\ntype PointOfInteractionComponent6 struct {\n\n\tType *POIComponentType4Code `xml:\"Tp\"`\n\n\tIdentification *PointOfInteractionComponentIdentification1 `xml:\"Id\"`\n\n\tStatus *PointOfInteractionComponentStatus3 `xml:\"Sts,omitempty\"`\n\n\tStandardCompliance []*GenericIdentification48 `xml:\"StdCmplc,omitempty\"`\n\n\tCharacteristics *PointOfInteractionComponentCharacteristics2 `xml:\"Chrtcs,omitempty\"`\n\n\tAssessment []*PointOfInteractionComponentAssessment1 `xml:\"Assmnt,omitempty\"`\n}\n\nfunc (p *PointOfInteractionComponent6) SetType(value string) {\n\tp.Type = (*POIComponentType4Code)(&value)\n}\n\nfunc (p *PointOfInteractionComponent6) AddIdentification() *PointOfInteractionComponentIdentification1 {\n\tp.Identification = new(PointOfInteractionComponentIdentification1)\n\treturn p.Identification\n}\n\n\n\nfunc (p *PointOfInteractionComponent6) AddStandardCompliance() *GenericIdentification48 {\n\tnewValue := new(GenericIdentification48)\n\tp.StandardCompliance = append(p.StandardCompliance, newValue)\n\treturn newValue\n}\n\nfunc (p *PointOfInteractionComponent6) AddCharacteristics() *PointOfInteractionComponentCharacteristics2 {\n\tp.Characteristics = new(PointOfInteractionComponentCharacteristics2)\n\treturn p.Characteristics\n}\n\nfunc (p *PointOfInteractionComponent6) AddAssessment() *PointOfInteractionComponentAssessment1 {\n\tnewValue := new(PointOfInteractionComponentAssessment1)\n\tp.Assessment = append(p.Assessment, newValue)\n\treturn newValue\n}\n\nfunc (p *PointOfInteractionComponent6) AddStatus() *PointOfInteractionComponentStatus3 ", "output": "{\n\tp.Status = new(PointOfInteractionComponentStatus3)\n\treturn p.Status\n}"} {"input": "package client\n\nimport (\n\tatlantis \"atlantis/common\"\n\t. \"atlantis/manager/constant\"\n)\n\ntype ManagerRPCClient struct {\n\tatlantis.RPCClient\n\tUser string\n\tSecrets map[string]string\n}\n\ntype AuthedArg interface {\n\tSetCredentials(string, string)\n}\n\n\n\nfunc (r *ManagerRPCClient) CallAuthedMulti(name string, arg AuthedArg, region int, reply interface{}) error {\n\targ.SetCredentials(r.User, r.Secrets[r.Opts[region].RPCHostAndPort()])\n\n\treturn r.RPCClient.CallMulti(name, arg, region, reply)\n}\n\nfunc NewManagerRPCClient(hostAndPort string) *atlantis.RPCClient {\n\treturn atlantis.NewRPCClient(hostAndPort, \"ManagerRPC\", ManagerRPCVersion, true)\n}\n\nfunc NewManagerRPCClientWithConfig(cfg []atlantis.RPCServerOpts) *atlantis.RPCClient {\n\treturn atlantis.NewMultiRPCClientWithConfig(cfg, \"ManagerRPC\", ManagerRPCVersion, true)\n}\n\nfunc (r *ManagerRPCClient) CallAuthed(name string, arg AuthedArg, reply interface{}) error ", "output": "{\n\treturn r.CallAuthedMulti(name, arg, 0, reply)\n}"} {"input": "package filestack\n\nimport \"strconv\"\n\ntype FilestackEvent struct {\n\tAction string `json:\"action\"`\n\tTimeStamp int64 `json:\"timestamp\"`\n\tId int `json:\"id\"`\n}\n\n\n\nfunc (fe *FilestackEvent) Fields() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"id\": strconv.Itoa(fe.Id),\n\t}\n}\n\nfunc (fe *FilestackEvent) Tags() map[string]string ", "output": "{\n\treturn map[string]string{\n\t\t\"action\": fe.Action,\n\t}\n}"} {"input": "package getter\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/goharbor/harbor/src/lib/orm\"\n\t\"github.com/goharbor/harbor/src/pkg/joblog\"\n\n\t\"github.com/goharbor/harbor/src/jobservice/errs\"\n)\n\n\ntype DBGetter struct {\n}\n\n\n\n\n\nfunc (dbg *DBGetter) Retrieve(logID string) ([]byte, error) {\n\tif len(logID) == 0 {\n\t\treturn nil, errors.New(\"empty log identify\")\n\t}\n\n\tjobLog, err := joblog.Mgr.Get(orm.Context(), logID)\n\tif err != nil {\n\t\treturn nil, errs.NoObjectFoundError(fmt.Sprintf(\"log entity: %s\", logID))\n\t}\n\n\treturn []byte(jobLog.Content), nil\n}\n\nfunc NewDBGetter() *DBGetter ", "output": "{\n\treturn &DBGetter{}\n}"} {"input": "package http\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/Cepave/open-falcon-backend/modules/transfer/g\"\n\tlog \"github.com/sirupsen/logrus\"\n\t\"net/http\"\n\t_ \"net/http/pprof\"\n)\n\ntype Dto struct {\n\tMsg string `json:\"msg\"`\n\tData interface{} `json:\"data\"`\n}\n\nfunc Start() {\n\tgo startHttpServer()\n}\n\n\nfunc RenderJson(w http.ResponseWriter, v interface{}) {\n\tbs, err := json.Marshal(v)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.Write(bs)\n}\n\nfunc RenderDataJson(w http.ResponseWriter, data interface{}) {\n\tRenderJson(w, Dto{Msg: \"success\", Data: data})\n}\n\nfunc RenderMsgJson(w http.ResponseWriter, msg string) {\n\tRenderJson(w, map[string]string{\"msg\": msg})\n}\n\nfunc AutoRender(w http.ResponseWriter, data interface{}, err error) {\n\tif err != nil {\n\t\tRenderMsgJson(w, err.Error())\n\t\treturn\n\t}\n\tRenderDataJson(w, data)\n}\n\nfunc startHttpServer() ", "output": "{\n\tif !g.Config().Http.Enabled {\n\t\treturn\n\t}\n\n\taddr := g.Config().Http.Listen\n\tif addr == \"\" {\n\t\treturn\n\t}\n\n\tconfigCommonRoutes()\n\tconfigProcHttpRoutes()\n\tconfigDebugHttpRoutes()\n\tconfigApiHttpRoutes()\n\n\ts := &http.Server{\n\t\tAddr: addr,\n\t\tMaxHeaderBytes: 1 << 30,\n\t}\n\n\tlog.Println(\"http.startHttpServer ok, listening\", addr)\n\tlog.Fatalln(s.ListenAndServe())\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\t. \"github.com/CodyGuo/win\"\n)\n\nvar (\n\trt *gin.Engine\n\trootPrefix string\n)\n\nfunc main() {\n\trt = gin.Default()\n\trouter(rt)\n\n\tgo rt.Run(\":8945\")\n\n\tc := make(chan os.Signal, 1)\n\n\tsignal.Notify(c, os.Interrupt, os.Kill, syscall.SIGTERM)\n\t<-c\n\n\n\tos.Exit(0)\n}\n\n\nfunc router(r *gin.Engine) {\n\tg := &r.RouterGroup\n\tif rootPrefix != \"\" {\n\t\tg = r.Group(rootPrefix)\n\t}\n\n\t{\n\t\tg.GET(\"/\", func(c *gin.Context) { c.String(200, \"ok\") })\n\t\tg.GET(\"/ShutDown\", ShutDown)\n\t}\n}\n\nfunc ShutDown(c *gin.Context) {\n\tgetPrivileges()\n\tExitWindowsEx(EWX_SHUTDOWN, 0)\n}\n\n\n\nfunc getPrivileges() ", "output": "{\n\tvar hToken HANDLE\n\tvar tkp TOKEN_PRIVILEGES\n\n\tOpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken)\n\tLookupPrivilegeValueA(nil, StringToBytePtr(SE_SHUTDOWN_NAME), &tkp.Privileges[0].Luid)\n\ttkp.PrivilegeCount = 1\n\ttkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED\n\tAdjustTokenPrivileges(hToken, false, &tkp, 0, nil, nil)\n}"} {"input": "package bridge\n\ntype setupStep func(*networkConfiguration, *bridgeInterface) error\n\ntype bridgeSetup struct {\n\tconfig *networkConfiguration\n\tbridge *bridgeInterface\n\tsteps []setupStep\n}\n\nfunc newBridgeSetup(c *networkConfiguration, i *bridgeInterface) *bridgeSetup {\n\treturn &bridgeSetup{config: c, bridge: i}\n}\n\nfunc (b *bridgeSetup) apply() error {\n\tfor _, fn := range b.steps {\n\t\tif err := fn(b.config, b.bridge); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\nfunc (b *bridgeSetup) queueStep(step setupStep) ", "output": "{\n\tb.steps = append(b.steps, step)\n}"} {"input": "package iso20022\n\n\ntype HighFrequencyTradingProfile1 struct {\n\n\tDate *ISODate `xml:\"Dt,omitempty\"`\n\n\tSettlementFrequency *SettlementFrequency1Choice `xml:\"SttlmFrqcy,omitempty\"`\n\n\tConsolidationType *ConsolidationType1Choice `xml:\"CnsldtnTp,omitempty\"`\n}\n\nfunc (h *HighFrequencyTradingProfile1) SetDate(value string) {\n\th.Date = (*ISODate)(&value)\n}\n\n\n\nfunc (h *HighFrequencyTradingProfile1) AddConsolidationType() *ConsolidationType1Choice {\n\th.ConsolidationType = new(ConsolidationType1Choice)\n\treturn h.ConsolidationType\n}\n\nfunc (h *HighFrequencyTradingProfile1) AddSettlementFrequency() *SettlementFrequency1Choice ", "output": "{\n\th.SettlementFrequency = new(SettlementFrequency1Choice)\n\treturn h.SettlementFrequency\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n\n\t\"github.com/go-openapi/errors\"\n)\n\n\n\ntype VirtualMachineScaleSetExtensionProfile struct {\n\n\tExtensions []*VirtualMachineScaleSetExtension `json:\"extensions\"`\n}\n\n\nfunc (m *VirtualMachineScaleSetExtensionProfile) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateExtensions(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\nfunc (m *VirtualMachineScaleSetExtensionProfile) validateExtensions(formats strfmt.Registry) error ", "output": "{\n\n\tif swag.IsZero(m.Extensions) { \n\t\treturn nil\n\t}\n\n\tfor i := 0; i < len(m.Extensions); i++ {\n\n\t\tif swag.IsZero(m.Extensions[i]) { \n\t\t\tcontinue\n\t\t}\n\n\t\tif m.Extensions[i] != nil {\n\n\t\t\tif err := m.Extensions[i].Validate(formats); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}"} {"input": "package iso20022\n\n\ntype IndividualPersonIdentification3Choice struct {\n\n\tIdentificationNumber *GenericIdentification81 `xml:\"IdNb\"`\n\n\tPersonName *IndividualPerson35 `xml:\"PrsnNm\"`\n}\n\n\n\nfunc (i *IndividualPersonIdentification3Choice) AddPersonName() *IndividualPerson35 {\n\ti.PersonName = new(IndividualPerson35)\n\treturn i.PersonName\n}\n\nfunc (i *IndividualPersonIdentification3Choice) AddIdentificationNumber() *GenericIdentification81 ", "output": "{\n\ti.IdentificationNumber = new(GenericIdentification81)\n\treturn i.IdentificationNumber\n}"} {"input": "package loadbalancer\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateListenerRequest struct {\n\n\tCreateListenerDetails `contributesTo:\"body\"`\n\n\tLoadBalancerId *string `mandatory:\"true\" contributesTo:\"path\" name:\"loadBalancerId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateListenerRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateListenerRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CreateListenerRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CreateListenerRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateListenerResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response CreateListenerResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response CreateListenerResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\nvar configFileOptions map[string]interface{}\n\nfunc LoadConfigFile(file string) error {\n\tconfigFileOptions = nil\n\tif _, err := os.Stat(file); err != nil {\n\t\treturn nil\n\t}\n\tif s, err := ioutil.ReadFile(file); err != nil {\n\t\treturn err\n\t} else if err := yaml.Unmarshal(s, &configFileOptions); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc IsKeyInConfig(key string) bool {\n\t_, ok := configFileOptions[key]\n\treturn ok\n}\n\nfunc getConfigFileValueWithDefault(key string, defaultValue interface{}) interface{} {\n\tif v := getConfigFileValue(key); v != nil {\n\t\treturn v\n\t} else {\n\t\treturn defaultValue\n\t}\n}\n\n\n\nfunc GetConfigFileSlice(key string) []string {\n\tif v, ok := configFileOptions[key].([]interface{}); ok {\n\t\tretVal := []string{}\n\t\tfor _, e := range v {\n\t\t\tif strV, ok := e.(string); ok {\n\t\t\t\tretVal = append(retVal, strV)\n\t\t\t}\n\t\t}\n\t\treturn retVal\n\t} else {\n\t\treturn []string{}\n\t}\n}\n\nfunc GetConfigFileString(key string) string {\n\tv, _ := getConfigFileValue(key).(string)\n\treturn v\n}\n\nfunc GetConfigFileStringWithDefault(key string, defaultValue interface{}) string {\n\tv, _ := getConfigFileValueWithDefault(key, defaultValue).(string)\n\treturn v\n}\n\nfunc getConfigFileValue(key string) interface{} ", "output": "{\n\tif v, ok := configFileOptions[key]; ok {\n\t\treturn v\n\t} else {\n\t\treturn nil\n\t}\n}"} {"input": "package kube_inventory\n\nimport (\n\t\"context\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n\n\t\"github.com/influxdata/telegraf\"\n)\n\n\n\nfunc (ki *KubernetesInventory) gatherService(s corev1.Service, acc telegraf.Accumulator) {\n\tif s.GetCreationTimestamp().Second() == 0 && s.GetCreationTimestamp().Nanosecond() == 0 {\n\t\treturn\n\t}\n\n\tfields := map[string]interface{}{\n\t\t\"created\": s.GetCreationTimestamp().UnixNano(),\n\t\t\"generation\": s.Generation,\n\t}\n\n\ttags := map[string]string{\n\t\t\"service_name\": s.Name,\n\t\t\"namespace\": s.Namespace,\n\t}\n\n\tfor key, val := range s.Spec.Selector {\n\t\tif ki.selectorFilter.Match(key) {\n\t\t\ttags[\"selector_\"+key] = val\n\t\t}\n\t}\n\n\tvar getPorts = func() {\n\t\tfor _, port := range s.Spec.Ports {\n\t\t\tfields[\"port\"] = port.Port\n\t\t\tfields[\"target_port\"] = port.TargetPort.IntVal\n\n\t\t\ttags[\"port_name\"] = port.Name\n\t\t\ttags[\"port_protocol\"] = string(port.Protocol)\n\n\t\t\tif s.Spec.Type == \"ExternalName\" {\n\t\t\t\ttags[\"external_name\"] = s.Spec.ExternalName\n\t\t\t} else {\n\t\t\t\ttags[\"cluster_ip\"] = s.Spec.ClusterIP\n\t\t\t}\n\n\t\t\tacc.AddFields(serviceMeasurement, fields, tags)\n\t\t}\n\t}\n\n\tif externIPs := s.Spec.ExternalIPs; externIPs != nil {\n\t\tfor _, ip := range externIPs {\n\t\t\ttags[\"ip\"] = ip\n\n\t\t\tgetPorts()\n\t\t}\n\t} else {\n\t\tgetPorts()\n\t}\n}\n\nfunc collectServices(ctx context.Context, acc telegraf.Accumulator, ki *KubernetesInventory) ", "output": "{\n\tlist, err := ki.client.getServices(ctx)\n\tif err != nil {\n\t\tacc.AddError(err)\n\t\treturn\n\t}\n\tfor _, i := range list.Items {\n\t\tki.gatherService(i, acc)\n\t}\n}"} {"input": "package memdb\n\n\n\ntype Changes []Change\n\n\ntype Change struct {\n\tTable string\n\tBefore interface{}\n\tAfter interface{}\n\n\tprimaryKey []byte\n}\n\n\nfunc (m *Change) Created() bool {\n\treturn m.Before == nil && m.After != nil\n}\n\n\n\n\n\n\n\nfunc (m *Change) Deleted() bool {\n\treturn m.Before != nil && m.After == nil\n}\n\nfunc (m *Change) Updated() bool ", "output": "{\n\treturn m.Before != nil && m.After != nil\n}"} {"input": "package stun\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"github.com/willscott/goturn/common\"\n\t\"net\"\n)\n\nconst (\n\tMappedAddress stun.AttributeType = 0x1\n)\n\ntype MappedAddressAttribute struct {\n\tFamily uint16\n\tPort uint16\n\tAddress net.IP\n}\n\nfunc NewMappedAddressAttribute() stun.Attribute {\n\treturn stun.Attribute(new(MappedAddressAttribute))\n}\n\nfunc (h *MappedAddressAttribute) Type() stun.AttributeType {\n\treturn MappedAddress\n}\n\nfunc (h *MappedAddressAttribute) Encode(msg *stun.Message) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\terr := stun.WriteAttributeHeader(buf, stun.Attribute(h), msg)\n\terr = binary.Write(buf, binary.BigEndian, h.Family)\n\terr = binary.Write(buf, binary.BigEndian, h.Port)\n\terr = binary.Write(buf, binary.BigEndian, h.Address)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}\n\n\n\nfunc (h *MappedAddressAttribute) Length(_ *stun.Message) uint16 {\n\tif h.Family == 1 {\n\t\treturn 8\n\t} else {\n\t\treturn 20\n\t}\n}\n\nfunc (h *MappedAddressAttribute) Decode(data []byte, _ uint16, _ *stun.Parser) error ", "output": "{\n\tif data[0] != 0 && data[1] != 1 && data[0] != 2 {\n\t\treturn errors.New(\"Incorrect Mapped Address Family.\")\n\t}\n\th.Family = uint16(data[1])\n\tif (h.Family == 1 && len(data) < 8) || (h.Family == 2 && len(data) < 20) {\n\t\treturn errors.New(\"Mapped Address Attribute unexpectedly Truncated.\")\n\t}\n\th.Port = uint16(data[2])<<8 + uint16(data[3])\n\tif h.Family == 1 {\n\t\th.Address = data[4:8]\n\t} else {\n\t\th.Address = data[4:20]\n\t}\n\treturn nil\n}"} {"input": "package runtime\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestHandleCrash(t *testing.T) {\n\tcount := 0\n\texpect := 10\n\tfor i := 0; i < expect; i = i + 1 {\n\t\tdefer HandleCrash()\n\t\tif i%2 == 0 {\n\t\t\tpanic(\"Test Panic\")\n\t\t}\n\t\tcount = count + 1\n\t}\n\tif count != expect {\n\t\tt.Errorf(\"Expected %d iterations, found %d\", expect, count)\n\t}\n}\n\nfunc TestCustomHandleError(t *testing.T) {\n\told := ErrorHandlers\n\tdefer func() { ErrorHandlers = old }()\n\tvar result error\n\tErrorHandlers = []func(error){\n\t\tfunc(err error) {\n\t\t\tresult = err\n\t\t},\n\t}\n\terr := fmt.Errorf(\"test\")\n\tHandleError(err)\n\tif result != err {\n\t\tt.Errorf(\"did not receive custom handler\")\n\t}\n}\n\nfunc TestCustomHandleCrash(t *testing.T) ", "output": "{\n\told := PanicHandlers\n\tdefer func() { PanicHandlers = old }()\n\tvar result interface{}\n\tPanicHandlers = []func(interface{}){\n\t\tfunc(r interface{}) {\n\t\t\tresult = r\n\t\t},\n\t}\n\tfunc() {\n\t\tdefer HandleCrash()\n\t\tpanic(\"test\")\n\t}()\n\tif result != \"test\" {\n\t\tt.Errorf(\"did not receive custom handler\")\n\t}\n}"} {"input": "package ltree\n\n\n\nfunc isMirror(left, right *TreeNode) bool {\n\treturn (left == nil && right == nil) ||\n\t\t(left != nil && right != nil &&\n\t\t\tleft.Val == right.Val &&\n\t\t\tisMirror(left.Left, right.Right) &&\n\t\t\tisMirror(right.Left, left.Right))\n}\n\n\n\nfunc isSymmetric(root *TreeNode) bool ", "output": "{\n\tif root == nil {\n\t\treturn true\n\t}\n\treturn isMirror(root.Left, root.Right)\n}"} {"input": "package shell\n\nimport (\n\t\"context\"\n\n\t\"github.com/hashicorp/hcl/v2/hcldec\"\n\tsl \"github.com/hashicorp/packer/common/shell-local\"\n\t\"github.com/hashicorp/packer/packer\"\n)\n\ntype Provisioner struct {\n\tconfig sl.Config\n}\n\nfunc (p *Provisioner) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }\n\nfunc (p *Provisioner) Prepare(raws ...interface{}) error {\n\terr := sl.Decode(&p.config, raws...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = sl.Validate(&p.config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (p *Provisioner) Provision(ctx context.Context, ui packer.Ui, _ packer.Communicator, generatedData map[string]interface{}) error ", "output": "{\n\t_, retErr := sl.Run(ctx, ui, &p.config, generatedData)\n\n\treturn retErr\n}"} {"input": "package overcurrent\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\ntype (\n\tNoopBreaker struct{}\n\n\tNoopCollector struct{}\n)\n\nvar defaultCollector = NewNoopCollector()\n\n\nfunc NewNoopBreaker() CircuitBreaker {\n\treturn &NoopBreaker{}\n}\n\nfunc (b *NoopBreaker) Trip() {}\nfunc (b *NoopBreaker) Reset() {}\nfunc (b *NoopBreaker) ShouldTry() bool { return true }\nfunc (b *NoopBreaker) MarkResult(err error) bool { return true }\n\nfunc (b *NoopBreaker) CallAsync(f BreakerFunc) <-chan error { return nil }\n\n\nfunc NewNoopCollector() MetricCollector {\n\treturn &NoopCollector{}\n}\n\nfunc (c *NoopCollector) ReportNew(BreakerConfig) {}\nfunc (c *NoopCollector) ReportCount(EventType) {}\nfunc (c *NoopCollector) ReportDuration(EventType, time.Duration) {}\nfunc (c *NoopCollector) ReportState(CircuitState) {}\n\nfunc (b *NoopBreaker) Call(f BreakerFunc) error ", "output": "{ return f(context.Background()) }"} {"input": "package resource\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n)\n\n\ntype Item struct {\n\tID interface{}\n\tETag string\n\tUpdated time.Time\n\tPayload map[string]interface{}\n}\n\n\ntype ItemList struct {\n\tTotal int\n\tPage int\n\tItems []*Item\n}\n\n\nfunc NewItem(payload map[string]interface{}) (*Item, error) {\n\tid, found := payload[\"id\"]\n\tif !found {\n\t\treturn nil, errors.New(\"Missing ID field\")\n\t}\n\tetag, err := genEtag(payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\titem := &Item{\n\t\tID: id,\n\t\tETag: etag,\n\t\tUpdated: time.Now(),\n\t\tPayload: payload,\n\t}\n\treturn item, nil\n}\n\n\n\n\n\nfunc (i Item) GetField(name string) interface{} {\n\treturn getField(i.Payload, name)\n}\n\n\n\n\n\nfunc getField(payload map[string]interface{}, name string) interface{} ", "output": "{\n\tpath := strings.SplitN(name, \".\", 2)\n\tif value, found := payload[path[0]]; found {\n\t\tif len(path) == 2 {\n\t\t\tif subPayload, ok := value.(map[string]interface{}); ok {\n\t\t\t\treturn getField(subPayload, path[1])\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\treturn value\n\t}\n\treturn nil\n}"} {"input": "package token\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n)\n\n\n\n\nfunc prettyPrintTreeRek(w io.Writer, tok Token, level int) {\n\t_, _ = fmt.Fprintf(w, \"%s(%p)%#v %d Permutations\\n\", strings.Repeat(\"\\t\", level), tok, tok, tok.Permutations())\n\n\tswitch t := tok.(type) {\n\tcase ForwardToken:\n\t\tif v := t.Get(); v != nil {\n\t\t\tprettyPrintTreeRek(w, v, level+1)\n\t\t}\n\tcase ListToken:\n\t\tfor i := 0; i < t.Len(); i++ {\n\t\t\tc, _ := t.Get(i)\n\n\t\t\tprettyPrintTreeRek(w, c, level+1)\n\t\t}\n\t}\n}\n\n\nfunc PrettyPrintInternalTree(w io.Writer, root Token) {\n\tprettyPrintInternalTreeRek(w, root, 0)\n}\n\nfunc prettyPrintInternalTreeRek(w io.Writer, tok Token, level int) {\n\t_, _ = fmt.Fprintf(w, \"%s(%p)%#v\\n\", strings.Repeat(\"\\t\", level), tok, tok)\n\n\tswitch t := tok.(type) {\n\tcase ForwardToken:\n\t\tif v := t.InternalGet(); v != nil {\n\t\t\tprettyPrintInternalTreeRek(w, v, level+1)\n\t\t}\n\tcase ListToken:\n\t\tfor i := 0; i < t.InternalLen(); i++ {\n\t\t\tc, _ := t.InternalGet(i)\n\n\t\t\tprettyPrintInternalTreeRek(w, c, level+1)\n\t\t}\n\t}\n}\n\nfunc PrettyPrintTree(w io.Writer, root Token) ", "output": "{\n\tprettyPrintTreeRek(w, root, 0)\n}"} {"input": "package math_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/ofc/math\"\n)\n\n\n\nfunc TestCT_MathPrChoiceMarshalUnmarshal(t *testing.T) {\n\tv := math.NewCT_MathPrChoice()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := math.NewCT_MathPrChoice()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestCT_MathPrChoiceConstructor(t *testing.T) ", "output": "{\n\tv := math.NewCT_MathPrChoice()\n\tif v == nil {\n\t\tt.Errorf(\"math.NewCT_MathPrChoice must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed math.CT_MathPrChoice should validate: %s\", err)\n\t}\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n _ \"github.com/lib/pq\"\n)\n\nfunc checkReferralID(referral_id string) bool {\n fmt.Println(\"Checking for valid referral_id:\", referral_id)\n var count int8\n if referral_id == \"\"{\n return true\n }\n db.QueryRow(\"SELECT COUNT(*) FROM referral WHERE referral_id=$1\",referral_id).Scan(&count)\n if count == 0 {\n return false\n }else{\n return true\n }\n}\n\nfunc updateReferralTable(referral_id string) string{\n var count int8\n db.QueryRow(\"SELECT referral_count FROM referral WHERE referral_id=$1\",referral_id).Scan(&count)\n count++\n db.QueryRow(\"UPDATE referral SET referral_count=$1 where referral_id=$2\", count, referral_id)\n var wallet_id string\n db.QueryRow(\"SELECT wallet_id FROM referral WHERE referral_id=$1\",referral_id).Scan(&wallet_id)\n return wallet_id\n}\n\n\n\nfunc createReferralID(referral_id, wallet_id string) bool", "output": "{\n fmt.Println(\"Creating ReferralID\",referral_id, wallet_id)\n db.QueryRow(\"INSERT INTO referral(referral_id, referral_count, wallet_id) VALUES($1,$2,$3);\",referral_id, 0, wallet_id)\n return true\n}"} {"input": "package tsdb\n\nimport \"sync\"\n\ntype _Cached struct {\n\tsync.RWMutex \n\tindexer map[uint64]int \n\tringbuffer []*DBValue \n\theader int \n\ttail int \n}\n\n\n\nfunc (cached *_Cached) Get(id uint64) (*DBValue, bool) {\n\tcached.RLock()\n\tdefer cached.RUnlock()\n\n\tif indexer, ok := cached.indexer[id]; ok {\n\t\treturn cached.ringbuffer[indexer], true\n\t}\n\n\treturn nil, false\n}\n\nfunc (cached *_Cached) Update(val *DBValue) {\n\tcached.Lock()\n\tdefer cached.Unlock()\n\n\told := cached.ringbuffer[cached.tail]\n\n\tif old != nil {\n\t\tdelete(cached.indexer, old.ID)\n\t}\n\n\tcached.ringbuffer[cached.tail] = val\n\tcached.indexer[val.ID] = cached.tail\n\n\tcached.tail++\n\n\tif cached.tail == len(cached.ringbuffer) {\n\t\tcached.tail = 0\n\t}\n\n\tif cached.tail == cached.header {\n\t\tcached.header++\n\n\t\tif cached.header == len(cached.ringbuffer) {\n\t\t\tcached.header = 0\n\t\t}\n\t}\n}\n\nfunc newCached(cachedsize int) *_Cached ", "output": "{\n\treturn &_Cached{\n\t\tindexer: make(map[uint64]int),\n\t\tringbuffer: make([]*DBValue, cachedsize),\n\t}\n}"} {"input": "package vip\n\nimport (\n\t\"context\"\n\t\"net/url\"\n\t\"strconv\"\n\n\t\"go-common/app/interface/main/app-view/conf\"\n\t\"go-common/library/ecode\"\n\thttpx \"go-common/library/net/http/blademaster\"\n\n\t\"github.com/pkg/errors\"\n)\n\nconst (\n\t_vipActive = \"/internal/v1/notice/active\"\n)\n\n\ntype Dao struct {\n\tclient *httpx.Client\n\tvipActiveURL string\n}\n\n\nfunc New(c *conf.Config) (d *Dao) {\n\td = &Dao{\n\t\tclient: httpx.NewClient(c.HTTPWrite),\n\t\tvipActiveURL: c.Host.VIP + _vipActive,\n\t}\n\treturn\n}\n\n\n\n\nfunc (d *Dao) VIPActive(c context.Context, subID int) (msg string, err error) ", "output": "{\n\tparams := url.Values{}\n\tparams.Set(\"subId\", strconv.Itoa(subID))\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t\tData string `json:\"data\"`\n\t}\n\tif err = d.client.Get(c, d.vipActiveURL, \"\", params, &res); err != nil {\n\t\treturn\n\t}\n\tif res.Code != ecode.OK.Code() {\n\t\terr = errors.Wrap(ecode.Int(res.Code), d.vipActiveURL+\"?\"+params.Encode())\n\t\treturn\n\t}\n\tmsg = res.Data\n\treturn\n}"} {"input": "package main\n\nimport \"sort\"\nimport \"fmt\"\n\ntype ByLength []string\n\nfunc (s ByLength) Len() int {\n\treturn len(s)\n}\n\n\n\nfunc (s ByLength) Less(i, j int) bool {\n\treturn len(s[i]) < len(s[j])\n}\n\nfunc main() {\n\tfruits := []string{\"peach\", \"banana\",\"kiwi\"}\n\tsort.Sort(ByLength(fruits))\n\tfmt.Println(fruits)\n}\n\nfunc (s ByLength) Swap(i, j int) ", "output": "{\n\ts[i], s[j] = s[j], s[i]\n}"} {"input": "package linebot\n\nimport (\n\t\"context\"\n\t\"fmt\"\n)\n\n\n\nfunc (client *Client) IssueLinkToken(userID string) *IssueLinkTokenCall {\n\treturn &IssueLinkTokenCall{\n\t\tc: client,\n\t\tuserID: userID,\n\t}\n}\n\n\ntype IssueLinkTokenCall struct {\n\tc *Client\n\tctx context.Context\n\n\tuserID string\n}\n\n\nfunc (call *IssueLinkTokenCall) WithContext(ctx context.Context) *IssueLinkTokenCall {\n\tcall.ctx = ctx\n\treturn call\n}\n\n\n\n\nfunc (call *IssueLinkTokenCall) Do() (*LinkTokenResponse, error) ", "output": "{\n\tendpoint := fmt.Sprintf(APIEndpointLinkToken, call.userID)\n\tres, err := call.c.post(call.ctx, endpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer closeResponse(res)\n\treturn decodeToLinkTokenResponse(res)\n}"} {"input": "package modules\n\nimport (\n\t\"io\"\n\n\t\"github.com/kylelemons/go-gypsy/yaml\"\n)\n\ntype Node interface{}\ntype Scalar string\ntype Map map[string]Node\ntype List []Node\n\nfunc YamlNodeToNode(node yaml.Node) Node {\n\tscalar, ok := node.(yaml.Scalar)\n\tif ok {\n\t\treturn Scalar(scalar.String())\n\t}\n\tlist, ok := node.(yaml.List)\n\tif ok {\n\t\tresult := make(List, list.Len())\n\t\tfor i, n := range list {\n\t\t\tresult[i] = YamlNodeToNode(n)\n\t\t}\n\t\treturn result\n\t}\n\tmp, ok := node.(yaml.Map)\n\tif ok {\n\t\tresult := make(Map)\n\t\tfor k, v := range mp {\n\t\t\tresult[k] = YamlNodeToNode(v)\n\t\t}\n\t\treturn result\n\t}\n\treturn nil\n}\n\n\n\nfunc Child(root Node, spec string) (Node, error) {\n\treturn nil, nil\n}\n\nfunc (s Scalar) String() string {\n\treturn string(s)\n}\n\nfunc (s Scalar) GetBool() bool {\n\tif s == \"true\" || s == \"yes\" || s == \"1\" {\n\t\treturn true\n\t} else if s == \"false\" || s == \"no\" || s == \"0\" {\n\t\treturn false\n\t}\n\tpanic(\"Invalid bool value:\" + s.String())\n}\n\nfunc (m Map) Keys() []string {\n\tkeys := make([]string, 0, len(m))\n\tfor key := range m {\n\t\tkeys = append(keys, key)\n\t}\n\treturn keys\n}\n\nfunc (m Map) Key(key string) Node {\n\treturn m[key]\n}\n\nfunc (l List) Item(idx int) Node {\n\treturn l[idx]\n}\n\nfunc (l List) Len() int {\n\treturn len(l)\n}\n\nfunc Parse(r io.Reader) (Node, error) ", "output": "{\n\tn, err := yaml.Parse(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn YamlNodeToNode(n), err\n}"} {"input": "package codedeploy_test\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/awserr\"\n\t\"github.com/aws/aws-sdk-go/aws/request\"\n\t\"github.com/aws/aws-sdk-go/awstesting/integration\"\n\t\"github.com/aws/aws-sdk-go/service/codedeploy\"\n)\n\nvar _ aws.Config\nvar _ awserr.Error\nvar _ request.Request\n\n\nfunc TestInteg_01_GetDeployment(t *testing.T) {\n\tctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancelFn()\n\n\tsess := integration.SessionWithDefaultRegion(\"us-west-2\")\n\tsvc := codedeploy.New(sess)\n\tparams := &codedeploy.GetDeploymentInput{\n\t\tDeploymentId: aws.String(\"d-USUAELQEX\"),\n\t}\n\t_, err := svc.GetDeploymentWithContext(ctx, params, func(r *request.Request) {\n\t\tr.Handlers.Validate.RemoveByName(\"core.ValidateParametersHandler\")\n\t})\n\tif err == nil {\n\t\tt.Fatalf(\"expect request to fail\")\n\t}\n\taerr, ok := err.(awserr.RequestFailure)\n\tif !ok {\n\t\tt.Fatalf(\"expect awserr, was %T\", err)\n\t}\n\tif len(aerr.Code()) == 0 {\n\t\tt.Errorf(\"expect non-empty error code\")\n\t}\n\tif len(aerr.Message()) == 0 {\n\t\tt.Errorf(\"expect non-empty error message\")\n\t}\n\tif v := aerr.Code(); v == request.ErrCodeSerialization {\n\t\tt.Errorf(\"expect API error code got serialization failure\")\n\t}\n}\n\nfunc TestInteg_00_ListApplications(t *testing.T) ", "output": "{\n\tctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancelFn()\n\n\tsess := integration.SessionWithDefaultRegion(\"us-west-2\")\n\tsvc := codedeploy.New(sess)\n\tparams := &codedeploy.ListApplicationsInput{}\n\t_, err := svc.ListApplicationsWithContext(ctx, params, func(r *request.Request) {\n\t\tr.Handlers.Validate.RemoveByName(\"core.ValidateParametersHandler\")\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"expect no error, got %v\", err)\n\t}\n}"} {"input": "package fsrateio\n\nimport (\n\t\"io\"\n\n\t\"github.com/Symantec/Dominator/lib/rateio\"\n\t\"github.com/Symantec/tricorder/go/tricorder\"\n\t\"github.com/Symantec/tricorder/go/tricorder/units\"\n)\n\ntype ReaderContext struct {\n\tmaxBytesPerSecond uint64\n\tmaxBlocksPerSecond uint64\n\tctx *rateio.ReaderContext\n}\n\n\n\nfunc (ctx *ReaderContext) GetContext() *rateio.ReaderContext { return ctx.ctx }\n\nfunc (ctx *ReaderContext) NewReader(rd io.Reader) *rateio.Reader {\n\treturn ctx.ctx.NewReader(rd)\n}\n\nfunc (ctx *ReaderContext) RegisterMetrics(dir *tricorder.DirectorySpec) error {\n\tif ctx.maxBlocksPerSecond > 0 {\n\t\treturn ctx.ctx.RegisterMetrics(dir, units.None,\n\t\t\t\"file-system speed in blocks per second\")\n\t}\n\treturn ctx.ctx.RegisterMetrics(dir, units.BytePerSecond,\n\t\t\"file-system speed\")\n}\n\nfunc (ctx *ReaderContext) String() string {\n\treturn ctx.format()\n}\n\nfunc NewReaderContext(maxBytesPerSecond uint64,\n\tmaxBlocksPerSecond uint64, speedPercent uint64) *ReaderContext ", "output": "{\n\treturn newReaderContext(maxBytesPerSecond, maxBlocksPerSecond, speedPercent)\n}"} {"input": "package console\n\nimport \"github.com/accurateproject/accurate/api/v1\"\n\n\n\n\ntype CmdExecuteScheduledActions struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrsExecuteScheduledActions\n\t*CommandExecuter\n}\n\nfunc (self *CmdExecuteScheduledActions) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdExecuteScheduledActions) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdExecuteScheduledActions) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrsExecuteScheduledActions{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdExecuteScheduledActions) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdExecuteScheduledActions) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc init() ", "output": "{\n\tc := &CmdExecuteScheduledActions{\n\t\tname: \"scheduler_execute\",\n\t\trpcMethod: \"ApiV1.ExecuteScheduledActions\",\n\t\trpcParams: &v1.AttrsExecuteScheduledActions{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}"} {"input": "package driver\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\n\t\"github.com/hashicorp/go-plugin\"\n)\n\nvar HandshakeConfig = plugin.HandshakeConfig{\n\tProtocolVersion: 1,\n\tMagicCookieKey: \"NOMAD_PLUGIN_MAGIC_COOKIE\",\n\tMagicCookieValue: \"e4327c2e01eabfd75a8a67adb114fb34a757d57eee7728d857a8cec6e91a7255\",\n}\n\nfunc GetPluginMap(w io.Writer) map[string]plugin.Plugin {\n\te := new(ExecutorPlugin)\n\te.logger = log.New(w, \"\", log.LstdFlags)\n\n\ts := new(SyslogCollectorPlugin)\n\ts.logger = log.New(w, \"\", log.LstdFlags)\n\treturn map[string]plugin.Plugin{\n\t\t\"executor\": e,\n\t\t\"syslogcollector\": s,\n\t}\n}\n\n\n\ntype PluginReattachConfig struct {\n\tPid int\n\tAddrNet string\n\tAddrName string\n}\n\n\n\n\nfunc NewPluginReattachConfig(c *plugin.ReattachConfig) *PluginReattachConfig {\n\treturn &PluginReattachConfig{Pid: c.Pid, AddrNet: c.Addr.Network(), AddrName: c.Addr.String()}\n}\n\nfunc (c *PluginReattachConfig) PluginConfig() *plugin.ReattachConfig ", "output": "{\n\tvar addr net.Addr\n\tswitch c.AddrNet {\n\tcase \"unix\", \"unixgram\", \"unixpacket\":\n\t\taddr, _ = net.ResolveUnixAddr(c.AddrNet, c.AddrName)\n\tcase \"tcp\", \"tcp4\", \"tcp6\":\n\t\taddr, _ = net.ResolveTCPAddr(c.AddrNet, c.AddrName)\n\t}\n\treturn &plugin.ReattachConfig{Pid: c.Pid, Addr: addr}\n}"} {"input": "package metric\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\ntype (\n\tCollectFnOpts struct {\n\t\tMethod string\n\t\tStart time.Time\n\t\tErr error\n\t\tAdditionalProps map[string]interface{}\n\t}\n\n\tCounterFn func(vec *prometheus.CounterVec, o CollectFnOpts)\n\n\tHistogramFn func(vec *prometheus.HistogramVec, o CollectFnOpts)\n\n\tVecOpts struct {\n\t\tName string\n\t\tHelp string\n\t\tLabelNames []string\n\n\t\tCounterFn CounterFn\n\t\tHistogramFn HistogramFn\n\t}\n)\n\ntype metricOpts struct {\n\tnamespace string\n\tservice string\n\tserviceSuffix string\n\tcounterMetrics map[string]VecOpts\n\thistogramMetrics map[string]VecOpts\n}\n\nfunc (o metricOpts) serviceName() string {\n\tif o.serviceSuffix != \"\" {\n\t\treturn fmt.Sprintf(\"%s_%s\", o.service, o.serviceSuffix)\n\t}\n\treturn o.service\n}\n\n\ntype ClientOptFn func(*metricOpts)\n\n\nfunc WithVec(opts VecOpts) ClientOptFn {\n\treturn func(o *metricOpts) {\n\t\tif opts.CounterFn != nil {\n\t\t\tif o.counterMetrics == nil {\n\t\t\t\to.counterMetrics = make(map[string]VecOpts)\n\t\t\t}\n\t\t\to.counterMetrics[opts.Name] = opts\n\t\t}\n\t}\n}\n\n\nfunc WithSuffix(suffix string) ClientOptFn {\n\treturn func(opts *metricOpts) {\n\t\topts.serviceSuffix = suffix\n\t}\n}\n\nfunc ApplyMetricOpts(opts ...ClientOptFn) *metricOpts {\n\to := metricOpts{}\n\tfor _, opt := range opts {\n\t\topt(&o)\n\t}\n\treturn &o\n}\n\n\n\nfunc (o *metricOpts) ApplySuffix(prefix string) string ", "output": "{\n\tif o.serviceSuffix != \"\" {\n\t\treturn fmt.Sprintf(\"%s_%s\", prefix, o.serviceSuffix)\n\t}\n\treturn prefix\n}"} {"input": "package framework\n\ntype HorizontalAlignment int\n\nconst (\n\tAlignLeft HorizontalAlignment = iota\n\tAlignCenter\n\tAlignRight\n)\n\nfunc (a HorizontalAlignment) AlignLeft() bool { return a == AlignLeft }\nfunc (a HorizontalAlignment) AlignCenter() bool { return a == AlignCenter }\nfunc (a HorizontalAlignment) AlignRight() bool { return a == AlignRight }\n\ntype VerticalAlignment int\n\nconst (\n\tAlignTop VerticalAlignment = iota\n\tAlignMiddle\n\tAlignBottom\n)\n\n\nfunc (a VerticalAlignment) AlignMiddle() bool { return a == AlignMiddle }\nfunc (a VerticalAlignment) AlignBottom() bool { return a == AlignBottom }\n\nfunc (a VerticalAlignment) AlignTop() bool ", "output": "{ return a == AlignTop }"} {"input": "package options\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com/spf13/pflag\"\n\t\"k8s.io/apiserver/pkg/server/options\"\n\tgenericcontrollermanager \"k8s.io/kubernetes/cmd/controller-manager/app\"\n)\n\n\n\ntype InsecureServingOptions struct {\n\tBindAddress net.IP\n\tBindPort int\n\tBindNetwork string\n\n\tListener net.Listener\n\n\tListenFunc func(network, addr string) (net.Listener, int, error)\n}\n\n\nfunc (s *InsecureServingOptions) Validate() []error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\terrors := []error{}\n\n\tif s.BindPort < 0 || s.BindPort > 32767 {\n\t\terrors = append(errors, fmt.Errorf(\"--insecure-port %v must be between 0 and 32767, inclusive. 0 for turning off insecure (HTTP) port\", s.BindPort))\n\t}\n\n\treturn errors\n}\n\n\n\n\n\n\nfunc (s *InsecureServingOptions) ApplyTo(c **genericcontrollermanager.InsecureServingInfo) error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\tif s.BindPort <= 0 {\n\t\treturn nil\n\t}\n\n\tif s.Listener == nil {\n\t\tvar err error\n\t\tlisten := options.CreateListener\n\t\tif s.ListenFunc != nil {\n\t\t\tlisten = s.ListenFunc\n\t\t}\n\t\taddr := net.JoinHostPort(s.BindAddress.String(), fmt.Sprintf(\"%d\", s.BindPort))\n\t\ts.Listener, s.BindPort, err = listen(s.BindNetwork, addr)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create listener: %v\", err)\n\t\t}\n\t}\n\n\t*c = &genericcontrollermanager.InsecureServingInfo{\n\t\tListener: s.Listener,\n\t}\n\n\treturn nil\n}\n\nfunc (s *InsecureServingOptions) AddFlags(fs *pflag.FlagSet) ", "output": "{\n\tif s == nil {\n\t\treturn\n\t}\n\n\tfs.IPVar(&s.BindAddress, \"address\", s.BindAddress, \"DEPRECATED: the IP address on which to listen for the --port port (set to 0.0.0.0 for all IPv4 interfaces and :: for all IPv6 interfaces). See --bind-address instead.\")\n\tfs.IntVar(&s.BindPort, \"port\", s.BindPort, \"DEPRECATED: the port on which to serve HTTP insecurely without authentication and authorization. If 0, don't serve HTTPS at all. See --secure-port instead.\")\n}"} {"input": "package sfn_test\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/awserr\"\n\t\"github.com/aws/aws-sdk-go/aws/request\"\n\t\"github.com/aws/aws-sdk-go/awstesting/integration\"\n\t\"github.com/aws/aws-sdk-go/service/sfn\"\n)\n\nvar _ aws.Config\nvar _ awserr.Error\nvar _ request.Request\n\n\n\nfunc TestInteg_00_ListActivities(t *testing.T) ", "output": "{\n\tctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancelFn()\n\n\tsess := integration.SessionWithDefaultRegion(\"us-west-2\")\n\tsvc := sfn.New(sess)\n\tparams := &sfn.ListActivitiesInput{}\n\t_, err := svc.ListActivitiesWithContext(ctx, params, func(r *request.Request) {\n\t\tr.Handlers.Validate.RemoveByName(\"core.ValidateParametersHandler\")\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"expect no error, got %v\", err)\n\t}\n}"} {"input": "package logrus\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\ntype fieldKey string\n\n\ntype FieldMap map[fieldKey]string\n\n\nconst (\n\tFieldKeyMsg = \"msg\"\n\tFieldKeyLevel = \"level\"\n\tFieldKeyTime = \"time\"\n)\n\n\n\n\ntype JSONFormatter struct {\n\tTimestampFormat string\n\n\tDisableTimestamp bool\n\n\tFieldMap FieldMap\n}\n\n\nfunc (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {\n\tdata := make(Fields, len(entry.Data)+3)\n\tfor k, v := range entry.Data {\n\t\tswitch v := v.(type) {\n\t\tcase error:\n\t\t\tdata[k] = v.Error()\n\t\tdefault:\n\t\t\tdata[k] = v\n\t\t}\n\t}\n\tprefixFieldClashes(data, f.FieldMap)\n\n\ttimestampFormat := f.TimestampFormat\n\tif timestampFormat == \"\" {\n\t\ttimestampFormat = defaultTimestampFormat\n\t}\n\n\tif !f.DisableTimestamp {\n\t\tdata[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)\n\t}\n\tdata[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message\n\tdata[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()\n\n\tserialized, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to marshal fields to JSON, %v\", err)\n\t}\n\treturn append(serialized, '\\n'), nil\n}\n\nfunc (f FieldMap) resolve(key fieldKey) string ", "output": "{\n\tif k, ok := f[key]; ok {\n\t\treturn k\n\t}\n\n\treturn string(key)\n}"} {"input": "package stores\n\nimport \"jvmgo/ch06/instructions/base\"\nimport \"jvmgo/ch06/rtda\"\n\n\ntype ISTORE struct{ base.Index8Instruction }\n\nfunc (self *ISTORE) Execute(frame *rtda.Frame) {\n\t_istore(frame, uint(self.Index))\n}\n\ntype ISTORE_0 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_0) Execute(frame *rtda.Frame) {\n\t_istore(frame, 0)\n}\n\ntype ISTORE_1 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_1) Execute(frame *rtda.Frame) {\n\t_istore(frame, 1)\n}\n\ntype ISTORE_2 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_2) Execute(frame *rtda.Frame) {\n\t_istore(frame, 2)\n}\n\ntype ISTORE_3 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_3) Execute(frame *rtda.Frame) {\n\t_istore(frame, 3)\n}\n\n\n\nfunc _istore(frame *rtda.Frame, index uint) ", "output": "{\n\tval := frame.OperandStack().PopInt()\n\tframe.LocalVars().SetInt(index, val)\n}"} {"input": "package quickfix\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc sessionIDFilenamePrefix(s SessionID) string {\n\tsender := []string{s.SenderCompID}\n\tif s.SenderSubID != \"\" {\n\t\tsender = append(sender, s.SenderSubID)\n\t}\n\tif s.SenderLocationID != \"\" {\n\t\tsender = append(sender, s.SenderLocationID)\n\t}\n\n\ttarget := []string{s.TargetCompID}\n\tif s.TargetSubID != \"\" {\n\t\ttarget = append(target, s.TargetSubID)\n\t}\n\tif s.TargetLocationID != \"\" {\n\t\ttarget = append(target, s.TargetLocationID)\n\t}\n\n\tfname := []string{s.BeginString, strings.Join(sender, \"_\"), strings.Join(target, \"_\")}\n\tif s.Qualifier != \"\" {\n\t\tfname = append(fname, s.Qualifier)\n\t}\n\treturn strings.Join(fname, \"-\")\n}\n\n\nfunc closeFile(f *os.File) error {\n\tif f != nil {\n\t\tif err := f.Close(); err != nil {\n\t\t\tif !os.IsNotExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc removeFile(fname string) error {\n\terr := os.Remove(fname)\n\tif (err != nil) && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\n\nfunc openOrCreateFile(fname string, perm os.FileMode) (f *os.File, err error) ", "output": "{\n\tif f, err = os.OpenFile(fname, os.O_RDWR, perm); err != nil {\n\t\tif f, err = os.OpenFile(fname, os.O_RDWR|os.O_CREATE, perm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error opening or creating file: %s: %s\", fname, err.Error())\n\t\t}\n\t}\n\treturn f, nil\n}"} {"input": "package packet\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype PacketCodecVarIntLength struct {\n\tcodec PacketCodec\n}\n\nfunc NewPacketCodecVarIntLength() (this *PacketCodecVarIntLength) {\n\tthis = new(PacketCodecVarIntLength)\n\treturn\n}\n\n\n\nfunc (this *PacketCodecVarIntLength) Encode(writer io.Writer, packet Packet) (err error) {\n\tbuffer := new(bytes.Buffer)\n\terr = this.codec.Encode(buffer, packet)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = WriteVarInt(writer, buffer.Len())\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = buffer.WriteTo(writer)\n\treturn\n}\n\nfunc (this *PacketCodecVarIntLength) SetCodec(codec PacketCodec) {\n\tthis.codec = codec\n}\n\nfunc (this *PacketCodecVarIntLength) Decode(reader io.Reader) (packet Packet, err error) ", "output": "{\n\tlength, err := ReadVarInt(reader)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Decode, Length read error: %w\", err)\n\t\treturn\n\t}\n\tif length < 0 {\n\t\terr = errors.New(fmt.Sprintf(\"Decode, Packet length is below zero: %d\", length))\n\t\treturn\n\t}\n\tif length > 1048576 { \n\t\terr = errors.New(fmt.Sprintf(\"Decode, Packet length is above maximum: %d\", length))\n\t\treturn\n\t}\n\tpayload := make([]byte, length)\n\t_, err = reader.Read(payload)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Decode, Length buffer error: %w\", err)\n\t\treturn\n\t}\n\tpacket, err = this.codec.Decode(bytes.NewBuffer(payload))\n\treturn\n}"} {"input": "package concurrent\n\nimport (\n\t\"context\"\n)\n\nfunc (w *workflowRuntime) spawnWorker(ctx context.Context) {\n\tgo func() {\n\t\tvar job int64\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-w.idQueue.GetTaskChan():\n\t\t\t\tjob = w.idQueue.GetTask()\n\t\t\t\tw.executeFlow(job)\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (w *workflowRuntime) executeFlow(jobId int64) {\n\tw.mutex.Lock()\n\tjob := w.tasks[jobId]\n\tw.mutex.Unlock()\n\n\tif len(job.dependentIds) > 0 {\n\t\tw.executeDependentFlow(jobId, job)\n\t\treturn\n\t}\n\n\tw.executionSlots <- struct{}{}\n\tresult := w.handlers[job.funcname](job.args, w, nil)\n\tw.setResult(jobId, result)\n\t<-w.executionSlots\n}\n\n\n\nfunc (w *workflowRuntime) executeDependentFlow(jobId int64, job *flowTask) ", "output": "{\n\tgo func() {\n\t\tvar results []interface{}\n\t\tfor _, dependentId := range job.dependentIds {\n\t\t\tresults = append(results, w.getResult(dependentId.(int64)))\n\t\t}\n\n\t\tw.executionSlots <- struct{}{}\n\t\tresult := w.handlers[job.funcname](job.args, w, results)\n\t\tw.setResult(jobId, result)\n\t\t<-w.executionSlots\n\t}()\n}"} {"input": "package ast\n\nimport (\n\t\"fmt\"\n\t\"github.com/troykinsella/crash/system/exec\"\n\t\"strings\"\n)\n\ntype IndexExpr struct {\n\tOperand *PrimaryExpr\n\tIndex *PrimaryExpr\n}\n\nfunc (ast *IndexExpr) Exec(ctx *exec.Context) (bool, interface{}, error) {\n\tok, operand, err := ast.Operand.Exec(ctx)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\trok := ok\n\n\tok, index, err := ast.Index.Exec(ctx)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\trok = rok && ok\n\n\tval, err := extractValue(operand, index)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\n\treturn rok, val, nil\n}\n\n\n\nfunc (ast *IndexExpr) Dump(indent int) ", "output": "{\n\tfmt.Printf(\"%s- index_expr:\\n\", strings.Repeat(\" \", indent))\n\tast.Operand.Dump(indent + 4)\n\tast.Index.Dump(indent + 4)\n}"} {"input": "package main\n\n\n\n\n\nimport \"C\"\nimport \"fmt\"\nimport \"os\"\nimport \"strconv\"\n\n\n\nfunc main() {\n if (len(os.Args) == 1) {\n fmt.Println(\"First arg (0 - 2000000000) is required.\")\n return\n }\n \n count, err := strconv.Atoi(os.Args[1])\n if err != nil || count <= 0 || count > 2000000000 {\n fmt.Println(\"Must be a positive number not exceeding 2 billion.\");\n return\n }\n \n \n C.plusone(C.int(C.current_timestamp()))\n \n \n run(C.int(count))\n}\n\nfunc run(count C.int) ", "output": "{\n start := C.current_timestamp()\n \n var x C.int = 0\n for x < count {\n x = C.plusone(x)\n }\n \n fmt.Println(C.current_timestamp() - start)\n}"} {"input": "package nl\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\ntype RtMsg struct {\n\tsyscall.RtMsg\n}\n\nfunc NewRtMsg() *RtMsg {\n\treturn &RtMsg{\n\t\tRtMsg: syscall.RtMsg{\n\t\t\tTable: syscall.RT_TABLE_MAIN,\n\t\t\tScope: syscall.RT_SCOPE_UNIVERSE,\n\t\t\tProtocol: syscall.RTPROT_BOOT,\n\t\t\tType: syscall.RTN_UNICAST,\n\t\t},\n\t}\n}\n\nfunc NewRtDelMsg() *RtMsg {\n\treturn &RtMsg{\n\t\tRtMsg: syscall.RtMsg{\n\t\t\tTable: syscall.RT_TABLE_MAIN,\n\t\t\tScope: syscall.RT_SCOPE_NOWHERE,\n\t\t},\n\t}\n}\n\nfunc (msg *RtMsg) Len() int {\n\treturn syscall.SizeofRtMsg\n}\n\nfunc DeserializeRtMsg(b []byte) *RtMsg {\n\treturn (*RtMsg)(unsafe.Pointer(&b[0:syscall.SizeofRtMsg][0]))\n}\n\nfunc (msg *RtMsg) Serialize() []byte {\n\treturn (*(*[syscall.SizeofRtMsg]byte)(unsafe.Pointer(msg)))[:]\n}\n\ntype RtNexthop struct {\n\tsyscall.RtNexthop\n}\n\nfunc DeserializeRtNexthop(b []byte) *RtNexthop {\n\treturn (*RtNexthop)(unsafe.Pointer(&b[0:syscall.SizeofRtNexthop][0]))\n}\n\n\n\nfunc (msg *RtNexthop) Serialize() []byte ", "output": "{\n\treturn (*(*[syscall.SizeofRtNexthop]byte)(unsafe.Pointer(msg)))[:]\n}"} {"input": "package binmsg\n\nimport (\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/juju/errors\"\n)\n\nvar referenceTime time.Time\n\nconst refTimeString = \"2305-01-01T00:00:00Z\"\n\n\n\nfunc initBinMsg() {\n\treferenceTime, _ = time.Parse(time.RFC3339, refTimeString)\n\treferenceTime = referenceTime.UTC()\n\tErrPayloadSizeTooSmall = errors.New(\n\t\t\"The payload size is less than \" + strconv.Itoa(PayloadOctets) +\n\t\t\t\" bytes long.\")\n}\n\nfunc init() ", "output": "{\n\tinitBinMsg()\n}"} {"input": "package bitbucket\n\ntype Downloads struct {\n\tc *Client\n}\n\nfunc (dl *Downloads) Create(do *DownloadsOptions) (interface{}, error) {\n\turlStr := dl.c.requestUrl(\"/repositories/%s/%s/downloads\", do.Owner, do.RepoSlug)\n\treturn dl.c.executeFileUpload(\"POST\", urlStr, do.FilePath, do.FileName, \"files\", make(map[string]string))\n}\n\n\n\nfunc (dl *Downloads) List(do *DownloadsOptions) (interface{}, error) ", "output": "{\n\turlStr := dl.c.requestUrl(\"/repositories/%s/%s/downloads\", do.Owner, do.RepoSlug)\n\treturn dl.c.execute(\"GET\", urlStr, \"\")\n}"} {"input": "package automation\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/v10.0.2-beta arm-automation/\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn \"v10.0.2-beta\"\n}"} {"input": "package tree\n\n\n\nfunc (tef *Fault) SetCheck(c Check) {\n}\n\nfunc (tef *Fault) setCheckInherited(c Check) {\n}\n\nfunc (tef *Fault) setCheckOnChildren(c Check) {\n}\n\nfunc (tef *Fault) addCheck(c Check) {\n}\n\nfunc (tef *Fault) DeleteCheck(c Check) {\n}\n\nfunc (tef *Fault) deleteCheckInherited(c Check) {\n}\n\nfunc (tef *Fault) deleteCheckOnChildren(c Check) {\n}\n\nfunc (tef *Fault) rmCheck(c Check) {\n}\n\nfunc (tef *Fault) syncCheck(childId string) {\n}\n\n\n\nfunc (tef *Fault) checkCheck(checkId string) bool ", "output": "{\n\treturn false\n}"} {"input": "package qb\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\nfunc TestSQLText(t *testing.T) {\n\ttext := SQLText(\"1\")\n\tassert.Equal(t, \"1\", text.Text)\n}\n\nfunc TestGetClauseFrom(t *testing.T) {\n\tvar c Clause\n\tc = SQLText(\"1\")\n\tassert.Equal(t, c, GetClauseFrom(c))\n\n\tc = GetClauseFrom(2)\n\tb, ok := c.(BindClause)\n\tassert.True(t, ok, \"Should have returned a BindClause\")\n\tassert.Equal(t, 2, b.Value)\n}\n\nfunc TestGetListFrom(t *testing.T) {\n\tvar c Clause\n\tc = ListClause{}\n\tassert.Equal(t, c, GetListFrom(c))\n\n\ttext := SQLText(\"SOME SQL\")\n\tc = GetListFrom(text)\n\tl, ok := c.(ListClause)\n\tassert.True(t, ok, \"Should have returned a ListClause\")\n\tassert.Equal(t, 1, len(l.Clauses))\n\tassert.Equal(t, text, l.Clauses[0])\n\n\tc = GetListFrom(2)\n\tl, ok = c.(ListClause)\n\tassert.True(t, ok, \"Should have returned a ListClause\")\n\tassert.Equal(t, 1, len(l.Clauses))\n\tassert.Equal(t, 2, l.Clauses[0].(BindClause).Value)\n\n\tc = GetListFrom(2, Bind(4))\n\tl, ok = c.(ListClause)\n\tassert.True(t, ok, \"Should have returned a ListClause\")\n\tassert.Equal(t, 2, len(l.Clauses))\n\tassert.Equal(t, 2, l.Clauses[0].(BindClause).Value)\n\tassert.Equal(t, 4, l.Clauses[1].(BindClause).Value)\n}\n\n\n\nfunc TestExists(t *testing.T) ", "output": "{\n\ts := Select()\n\n\te := Exists(s)\n\tassert.False(t, e.Not)\n\tassert.Equal(t, s, e.Select)\n\n\tne := NotExists(s)\n\tassert.True(t, ne.Not)\n\tassert.Equal(t, s, ne.Select)\n}"} {"input": "package component\n\ntype (\n\toptions struct {\n\t\tname string \n\t\tnameFunc func(string) string \n\t\tschedName string \n\t}\n\n\tOption func(options *options)\n)\n\n\nfunc WithName(name string) Option {\n\treturn func(opt *options) {\n\t\topt.name = name\n\t}\n}\n\n\n\nfunc WithNameFunc(fn func(string) string) Option {\n\treturn func(opt *options) {\n\t\topt.nameFunc = fn\n\t}\n}\n\n\n\n\nfunc WithSchedulerName(name string) Option ", "output": "{\n\treturn func(opt *options) {\n\t\topt.schedName = name\n\t}\n}"} {"input": "package scrape\n\nimport (\n\t\"go.uber.org/zap\"\n)\n\nvar logger *zap.Logger\n\n\n\nfunc init() ", "output": "{\n\tlogger, _ = zap.NewProduction()\n\n}"} {"input": "package github\n\nimport (\n . \"github.com/ErintLabs/trellohub/genapi\"\n \"log\"\n)\n\ntype Label struct {\n Name string `json:\"name\"`\n}\n\ntype GitUser struct {\n Name string `json:\"login\"`\n}\n\nfunc (issue *Issue) SetLabels(lbls []Label) {\n lst := make([]string, len(lbls))\n for i, v := range lbls {\n lst[i] = v.Name\n }\n issue.Labels.SetNameable(lst)\n}\n\nfunc (issue *Issue) SetMembers(mbmrs []GitUser) {\n lst := make([]string, len(mbmrs))\n for i, v := range mbmrs {\n lst[i] = v.Name\n }\n issue.Members.SetNameable(lst)\n}\n\n\n\n\nfunc (issue *Issue) AddLabel(label string) {\n log.Printf(\"Adding label %s to %s\", label, issue.String())\n lbls := [...]string { label }\n GenPOSTJSON(issue.github, issue.ApiURL() + \"/labels\", nil, &lbls)\n}\n\n\n\n\n\ntype userAssignRequest struct {\n Assigs []string `json:\"assignees\"`\n}\n\nfunc (issue *Issue) AddUser(user string) {\n log.Printf(\"Adding user %s to %s\", user, issue.String())\n payload := userAssignRequest{ []string{ user } }\n GenPOSTJSON(issue.github, issue.ApiURL() + \"/assignees\", nil, &payload)\n}\n\n\nfunc (issue *Issue) DelUser(user string) {\n log.Printf(\"Removing user %s from %s\", user, issue.String())\n payload := userAssignRequest{ []string{ user } }\n GenDELJSON(issue.github, issue.ApiURL() + \"/assignees\", &payload)\n}\n\nfunc (issue *Issue) DelLabel(label string) ", "output": "{\n log.Printf(\"Removing label %s from %s\", label, issue.String())\n GenDEL(issue.github, issue.ApiURL() + \"/labels/\" + label) \n}"} {"input": "package json\n\nimport (\n\t\"testing\"\n\n\tch \"gopkg.in/check.v1\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\nfunc TestByGinkgo(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Base Suite\")\n}\n\n\n\nfunc TestByCheck(t *testing.T) ", "output": "{\n\tch.TestingT(t)\n}"} {"input": "package informers\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/docker/compose-on-kubernetes/api/compose/v1alpha3\"\n\t\"github.com/docker/compose-on-kubernetes/api/compose/v1beta2\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}\n\n\nfunc (f *genericInformer) Lister() cache.GenericLister {\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}\n\n\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) ", "output": "{\n\tswitch resource {\n\tcase v1beta2.SchemeGroupVersion.WithResource(\"stacks\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Compose().V1beta2().Stacks().Informer()}, nil\n\tcase v1alpha3.SchemeGroupVersion.WithResource(\"stacks\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Compose().V1alpha3().Stacks().Informer()}, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}"} {"input": "package cmd\n\n\n\n\nvar Version = \"unknown\"\n\n\n\nfunc MockVersion(version string) (restore func()) ", "output": "{\n\told := Version\n\tVersion = version\n\treturn func() { Version = old }\n}"} {"input": "package admin\n\nimport (\n\t\"errors\"\n\t\"io\"\n\n\t\"github.com/golang/glog\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/auth/user\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/util\"\n\n\t\"github.com/openshift/origin/pkg/cmd/server/crypto\"\n)\n\ntype CreateClientCertOptions struct {\n\tSignerCertOptions *SignerCertOptions\n\n\tCertFile string\n\tKeyFile string\n\n\tUser string\n\tGroups util.StringList\n\n\tOverwrite bool\n\tOutput io.Writer\n}\n\n\n\nfunc (o CreateClientCertOptions) CreateClientCert() (*crypto.TLSCertificateConfig, error) {\n\tglog.V(4).Infof(\"Creating a client cert with: %#v and %#v\", o, o.SignerCertOptions)\n\n\tsignerCert, err := o.SignerCertOptions.CA()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cert *crypto.TLSCertificateConfig\n\twritten := true\n\tuserInfo := &user.DefaultInfo{Name: o.User, Groups: o.Groups}\n\tif o.Overwrite {\n\t\tcert, err = signerCert.MakeClientCertificate(o.CertFile, o.KeyFile, userInfo)\n\t} else {\n\t\tcert, written, err = signerCert.EnsureClientCertificate(o.CertFile, o.KeyFile, userInfo)\n\t}\n\tif written {\n\t\tglog.V(3).Infof(\"Generated new client cert as %s and key as %s\\n\", o.CertFile, o.KeyFile)\n\t} else {\n\t\tglog.V(3).Infof(\"Keeping existing client cert at %s and key at %s\\n\", o.CertFile, o.KeyFile)\n\t}\n\treturn cert, err\n}\n\nfunc (o CreateClientCertOptions) Validate(args []string) error ", "output": "{\n\tif len(args) != 0 {\n\t\treturn errors.New(\"no arguments are supported\")\n\t}\n\tif len(o.CertFile) == 0 {\n\t\treturn errors.New(\"cert must be provided\")\n\t}\n\tif len(o.KeyFile) == 0 {\n\t\treturn errors.New(\"key must be provided\")\n\t}\n\tif len(o.User) == 0 {\n\t\treturn errors.New(\"user must be provided\")\n\t}\n\n\tif o.SignerCertOptions == nil {\n\t\treturn errors.New(\"signer options are required\")\n\t}\n\tif err := o.SignerCertOptions.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package client \n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/docker/docker/api/types/swarm\"\n\t\"github.com/docker/docker/errdefs\"\n)\n\n\n\nfunc TestNodeUpdate(t *testing.T) {\n\texpectedURL := \"/nodes/node_id/update\"\n\n\tclient := &Client{\n\t\tclient: newMockClient(func(req *http.Request) (*http.Response, error) {\n\t\t\tif !strings.HasPrefix(req.URL.Path, expectedURL) {\n\t\t\t\treturn nil, fmt.Errorf(\"Expected URL '%s', got '%s'\", expectedURL, req.URL)\n\t\t\t}\n\t\t\tif req.Method != \"POST\" {\n\t\t\t\treturn nil, fmt.Errorf(\"expected POST method, got %s\", req.Method)\n\t\t\t}\n\t\t\treturn &http.Response{\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tBody: ioutil.NopCloser(bytes.NewReader([]byte(\"body\"))),\n\t\t\t}, nil\n\t\t}),\n\t}\n\n\terr := client.NodeUpdate(context.Background(), \"node_id\", swarm.Version{}, swarm.NodeSpec{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestNodeUpdateError(t *testing.T) ", "output": "{\n\tclient := &Client{\n\t\tclient: newMockClient(errorMock(http.StatusInternalServerError, \"Server error\")),\n\t}\n\n\terr := client.NodeUpdate(context.Background(), \"node_id\", swarm.Version{}, swarm.NodeSpec{})\n\tif err == nil || err.Error() != \"Error response from daemon: Server error\" {\n\t\tt.Fatalf(\"expected a Server Error, got %v\", err)\n\t}\n\tif !errdefs.IsSystem(err) {\n\t\tt.Fatalf(\"expected a Server Error, got %T\", err)\n\t}\n}"} {"input": "package k3s\n\nimport (\n\tclientset \"github.com/rancher/k3s/pkg/generated/clientset/versioned\"\n\tv1 \"github.com/rancher/k3s/pkg/generated/controllers/k3s.cattle.io/v1\"\n\tinformers \"github.com/rancher/k3s/pkg/generated/informers/externalversions/k3s.cattle.io\"\n\t\"github.com/rancher/wrangler/pkg/generic\"\n)\n\ntype Interface interface {\n\tV1() v1.Interface\n}\n\ntype group struct {\n\tcontrollerManager *generic.ControllerManager\n\tinformers informers.Interface\n\tclient clientset.Interface\n}\n\n\n\n\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.controllerManager, g.client.K3sV1(), g.informers.V1())\n}\n\nfunc New(controllerManager *generic.ControllerManager, informers informers.Interface,\n\tclient clientset.Interface) Interface ", "output": "{\n\treturn &group{\n\t\tcontrollerManager: controllerManager,\n\t\tinformers: informers,\n\t\tclient: client,\n\t}\n}"} {"input": "package email\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"io\"\n\t\"net/textproto\"\n)\n\n\n\n\nfunc (m *Message) HasDeliveryStatusMessage() bool {\n\tcontentType, _, err := m.Header.ContentType()\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn contentType == \"message/delivery-status\" && m.SubMessage != nil\n}\n\n\n\nfunc (m *Message) DeliveryStatusMessageDNS() (Header, error) {\n\tif !m.HasDeliveryStatusMessage() {\n\t\treturn Header{}, errors.New(\"Message does not have media content of type message/delivery-status\")\n\t}\n\treturn m.SubMessage.Header, nil\n}\n\n\n\n\n\nfunc (m *Message) DeliveryStatusRecipientDNS() ([]Header, error) ", "output": "{\n\trecipientDNS := make([]Header, 0, 1)\n\tif !m.HasDeliveryStatusMessage() {\n\t\treturn recipientDNS, errors.New(\"Message does not have media content of type message/delivery-status\")\n\t}\n\tvar err error\n\tvar recipientHeaders textproto.MIMEHeader\n\ttp := textproto.NewReader(bufio.NewReader(bytes.NewReader(m.SubMessage.Body)))\n\tfor err != io.EOF {\n\t\trecipientHeaders, err = tp.ReadMIMEHeader()\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, err\n\t\t}\n\t\trecipientDNS = append(recipientDNS, Header(recipientHeaders))\n\t}\n\treturn recipientDNS, nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/ying32/govcl/vcl\"\n\t\"github.com/ying32/govcl/vcl/rtl\"\n\t\"github.com/ying32/govcl/vcl/types\"\n\t\"github.com/ying32/govcl/vcl/types/keys\"\n\t\"github.com/ying32/govcl/vcl/types/messages\"\n\t\"github.com/ying32/govcl/vcl/win\"\n)\n\n\ntype TForm1Fields struct {\n\thotKeyId types.ATOM\n}\n\nfunc (f *TForm1) OnFormCreate(sender vcl.IObject) {\n\tf.SetCaption(\"Press Ctrl+F1\")\n\tf.ScreenCenter()\n\tf.hotKeyId = win.GlobalAddAtom(\"HotKeyId\") - 0xC000\n\tshift := types.NewSet(types.SsCtrl)\n\tif !win.RegisterHotKey(f.Handle(), int32(f.hotKeyId), rtl.ShiftStateToWord(shift), keys.VkF1) {\n\t\tvcl.ShowMessage(\"注册热键失败。\")\n\t}\n\n}\n\n\n\nfunc (f *TForm1) OnFormWndProc(msg *types.TMessage) {\n\n\tf.InheritedWndProc(msg)\n\tif msg.Msg == messages.WM_HOTKEY {\n\t\tif msg.WParam == types.WPARAM(f.hotKeyId) {\n\t\t\tvcl.ShowMessage(\"按下了Ctrl+F1\")\n\t\t}\n\t}\n}\n\nfunc (f *TForm1) OnFormDestroy(sender vcl.IObject) ", "output": "{\n\tif f.hotKeyId > 0 {\n\t\twin.UnregisterHotKey(f.Handle(), int32(f.hotKeyId))\n\t\twin.GlobalDeleteAtom(f.hotKeyId)\n\t}\n}"} {"input": "package container\n\nvar _ LogEntry = (*logEntry)(nil)\n\nfunc NewLogEntry(container, line string) logEntry {\n\treturn logEntry{\n\t\tcontainer: container,\n\t\tline: line,\n\t}\n}\n\ntype logEntry struct {\n\tline string\n\tcontainer string\n}\n\n\n\nfunc (l logEntry) Container() string {\n\treturn l.container\n}\n\nfunc (l logEntry) Line() string ", "output": "{\n\treturn l.line\n}"} {"input": "package main\n\nimport (\n\t\"github.com/pilu/traffic\"\n)\n\ntype ResponseData struct {\n\tMessage string\n}\n\n\n\nfunc RootHandler(w traffic.ResponseWriter, r *traffic.Request) ", "output": "{\n\tresponseData := &ResponseData{\"Hello World\"}\n\tw.Render(\"index\", responseData)\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"helm.sh/helm/v3/pkg/release\"\n)\n\nfunc TestGetCmd(t *testing.T) {\n\ttests := []cmdTestCase{{\n\t\tname: \"get all with a release\",\n\t\tcmd: \"get all thomas-guide\",\n\t\tgolden: \"output/get-release.txt\",\n\t\trels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: \"thomas-guide\"})},\n\t}, {\n\t\tname: \"get all with a formatted release\",\n\t\tcmd: \"get all elevated-turkey --template {{.Release.Chart.Metadata.Version}}\",\n\t\tgolden: \"output/get-release-template.txt\",\n\t\trels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: \"elevated-turkey\"})},\n\t}, {\n\t\tname: \"get all requires release name arg\",\n\t\tcmd: \"get all\",\n\t\tgolden: \"output/get-all-no-args.txt\",\n\t\twantError: true,\n\t}}\n\trunTestCmd(t, tests)\n}\n\nfunc TestGetAllRevisionCompletion(t *testing.T) {\n\trevisionFlagCompletionTest(t, \"get all\")\n}\n\n\n\nfunc TestGetAllFileCompletion(t *testing.T) ", "output": "{\n\tcheckFileCompletion(t, \"get all\", false)\n\tcheckFileCompletion(t, \"get all myrelease\", false)\n}"} {"input": "package docker_registry\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\tneturl \"net/url\"\n\t\"path\"\n)\n\ntype harborApi struct{}\n\nfunc newHarborApi() harborApi {\n\treturn harborApi{}\n}\n\n\n\nfunc (api *harborApi) DeleteRepository(ctx context.Context, hostname, repository, username, password string) (*http.Response, error) ", "output": "{\n\tu, err := neturl.Parse(\"https://\" + hostname + \"/api\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu.Path = path.Join(u.Path, \"repositories\", repository)\n\turl := u.String()\n\n\tresp, _, err := doRequest(ctx, http.MethodDelete, url, nil, doRequestOptions{\n\t\tHeaders: map[string]string{\n\t\t\t\"Accept\": \"application/json\",\n\t\t},\n\t\tBasicAuth: doRequestBasicAuth{\n\t\t\tusername: username,\n\t\t\tpassword: password,\n\t\t},\n\t\tAcceptedCodes: []int{http.StatusOK, http.StatusAccepted},\n\t})\n\n\treturn resp, err\n}"} {"input": "package msg\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com/KunTengRom/xfrps/utils/errors\"\n)\n\n\n\nfunc UnPackInto(buffer []byte, msg Message) (err error) {\n\t_, err = unpack(' ', buffer, msg)\n\treturn\n}\n\nfunc UnPack(typeByte byte, buffer []byte) (msg Message, err error) {\n\treturn unpack(typeByte, buffer, nil)\n}\n\nfunc Pack(msg Message) ([]byte, error) {\n\ttypeByte, ok := TypeStringMap[reflect.TypeOf(msg).Elem()]\n\tif !ok {\n\t\treturn nil, errors.ErrMsgType\n\t}\n\n\tcontent, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuffer := bytes.NewBuffer(nil)\n\tbuffer.WriteByte(typeByte)\n\tbinary.Write(buffer, binary.BigEndian, int32(len(content)))\n\tbuffer.Write(content)\n\treturn buffer.Bytes(), nil\n}\n\nfunc unpack(typeByte byte, buffer []byte, msgIn Message) (msg Message, err error) ", "output": "{\n\tif msgIn == nil {\n\t\tt, ok := TypeMap[typeByte]\n\t\tif !ok {\n\t\t\terr = fmt.Errorf(\"Unsupported message type %b\", typeByte)\n\t\t\treturn\n\t\t}\n\n\t\tmsg = reflect.New(t).Interface().(Message)\n\t} else {\n\t\tmsg = msgIn\n\t}\n\n\terr = json.Unmarshal(buffer, &msg)\n\treturn\n}"} {"input": "package payload\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hyperledger/burrow/acm/acmstate\"\n\t\"github.com/hyperledger/burrow/crypto\"\n)\n\nfunc NewBondTx(address crypto.Address, amount uint64) *BondTx {\n\treturn &BondTx{\n\t\tInput: &TxInput{\n\t\t\tAddress: address,\n\t\t\tAmount: amount,\n\t\t},\n\t}\n}\n\nfunc (tx *BondTx) Type() Type {\n\treturn TypeBond\n}\n\nfunc (tx *BondTx) GetInputs() []*TxInput {\n\treturn []*TxInput{tx.Input}\n}\n\nfunc (tx *BondTx) String() string {\n\treturn fmt.Sprintf(\"BondTx{%v}\", tx.Input)\n}\n\nfunc (tx *BondTx) AddInput(st acmstate.AccountGetter, pubkey *crypto.PublicKey, amt uint64) error {\n\taddr := pubkey.GetAddress()\n\tacc, err := st.GetAccount(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif acc == nil {\n\t\treturn fmt.Errorf(\"invalid address %s from pubkey %s\", addr, pubkey)\n\t}\n\treturn tx.AddInputWithSequence(pubkey, amt, acc.Sequence+uint64(1))\n}\n\nfunc (tx *BondTx) AddInputWithSequence(pubkey *crypto.PublicKey, amt uint64, sequence uint64) error {\n\ttx.Input = &TxInput{\n\t\tAddress: pubkey.GetAddress(),\n\t\tAmount: amt,\n\t\tSequence: sequence,\n\t}\n\treturn nil\n}\n\n\n\nfunc (tx *BondTx) Any() *Any ", "output": "{\n\treturn &Any{\n\t\tBondTx: tx,\n\t}\n}"} {"input": "package iso20022\n\n\ntype StatisticsByPredefinedTimePeriods2 struct {\n\n\tHighestPriceValue12Months *PriceValue5 `xml:\"HghstPricVal12Mnths,omitempty\"`\n\n\tLowestPriceValue12Months *PriceValue5 `xml:\"LwstPricVal12Mnths,omitempty\"`\n\n\tOneYearPriceChange *PriceValueChange1 `xml:\"OneYrPricChng,omitempty\"`\n\n\tThreeYearPriceChange *PriceValueChange1 `xml:\"ThreeYrPricChng,omitempty\"`\n\n\tFiveYearPriceChange *PriceValueChange1 `xml:\"FiveYrPricChng,omitempty\"`\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddHighestPriceValue12Months() *PriceValue5 {\n\ts.HighestPriceValue12Months = new(PriceValue5)\n\treturn s.HighestPriceValue12Months\n}\n\n\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddOneYearPriceChange() *PriceValueChange1 {\n\ts.OneYearPriceChange = new(PriceValueChange1)\n\treturn s.OneYearPriceChange\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddThreeYearPriceChange() *PriceValueChange1 {\n\ts.ThreeYearPriceChange = new(PriceValueChange1)\n\treturn s.ThreeYearPriceChange\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddFiveYearPriceChange() *PriceValueChange1 {\n\ts.FiveYearPriceChange = new(PriceValueChange1)\n\treturn s.FiveYearPriceChange\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddLowestPriceValue12Months() *PriceValue5 ", "output": "{\n\ts.LowestPriceValue12Months = new(PriceValue5)\n\treturn s.LowestPriceValue12Months\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/exec\"\n)\n\ntype Repository struct {\n\tName string\n}\n\n\n\nfunc (repo *Repository) Create() error {\n\tcmd := exec.Command(\"git\", \"init\", \"--bare\", repo.Name)\n\tcmd.Dir = config.RepositoryDir\n\treturn cmd.Run()\n}\n\nfunc (repo *Repository) Path() string {\n\treturn config.RepositoryDir + \"/\" + repo.Name\n}\n\nfunc (repo *Repository) Exists() bool {\n\tif _, err := os.Stat(repo.Path()); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc getRepositories() *[]Repository ", "output": "{\n\tvar result []Repository\n\tdirs, _ := ioutil.ReadDir(config.RepositoryDir)\n\tfor _, entry := range dirs {\n\t\tif entry.IsDir() {\n\t\t\tresult = append(result, Repository{entry.Name()})\n\t\t}\n\t}\n\treturn &result\n}"} {"input": "package gtk\n\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\n\nfunc (v *Menu) PopupAtMouseCursor(parentMenuShell IMenu, parentMenuItem IMenuItem, button int, activateTime uint32) {\n\twshell := nullableWidget(parentMenuShell)\n\twitem := nullableWidget(parentMenuItem)\n\n\tC.gtk_menu_popup(v.native(),\n\t\twshell,\n\t\twitem,\n\t\tnil,\n\t\tnil,\n\t\tC.guint(button),\n\t\tC.guint32(activateTime))\n}\n\nfunc (v *SizeGroup) GetIgnoreHidden() bool {\n\tc := C.gtk_size_group_get_ignore_hidden(v.native())\n\treturn gobool(c)\n}\n\n\nfunc (v *Window) SetWMClass(name, class string) {\n\tcName := C.CString(name)\n\tdefer C.free(unsafe.Pointer(cName))\n\tcClass := C.CString(class)\n\tdefer C.free(unsafe.Pointer(cClass))\n\tC.gtk_window_set_wmclass(v.native(), (*C.gchar)(cName), (*C.gchar)(cClass))\n}\n\nfunc (v *SizeGroup) SetIgnoreHidden(ignoreHidden bool) {\n\tC.gtk_size_group_set_ignore_hidden(v.native(), gbool(ignoreHidden))\n}\n\n\nfunc (v *FontButton) GetFontName() string {\n\tc := C.gtk_font_button_get_font_name(v.native())\n\treturn goString(c)\n}\n\n\n\n\nfunc (v *FontButton) SetFontName(fontname string) bool ", "output": "{\n\tcstr := C.CString(fontname)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_font_button_set_font_name(v.native(), (*C.gchar)(cstr))\n\treturn gobool(c)\n}"} {"input": "package glacier\n\nimport (\n\t\"encoding/hex\"\n\t\"reflect\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/awsutil\"\n)\n\nvar (\n\tdefaultAccountID = \"-\"\n)\n\nfunc init() {\n\tinitRequest = func(r *aws.Request) {\n\t\tr.Handlers.Validate.PushFront(addAccountID)\n\t\tr.Handlers.Validate.PushFront(copyParams) \n\t\tr.Handlers.Build.PushBack(addChecksum)\n\t\tr.Handlers.Build.PushBack(addAPIVersion)\n\t}\n}\n\nfunc copyParams(r *aws.Request) {\n\tr.Params = awsutil.CopyOf(r.Params)\n}\n\nfunc addAccountID(r *aws.Request) {\n\tif !r.ParamsFilled() {\n\t\treturn\n\t}\n\n\tv := reflect.Indirect(reflect.ValueOf(r.Params))\n\tif f := v.FieldByName(\"AccountID\"); f.IsNil() {\n\t\tf.Set(reflect.ValueOf(&defaultAccountID))\n\t}\n}\n\nfunc addChecksum(r *aws.Request) {\n\tif r.Body == nil {\n\t\treturn\n\t}\n\n\th := ComputeHashes(r.Body)\n\n\tif r.HTTPRequest.Header.Get(\"X-Amz-Content-Sha256\") == \"\" {\n\t\thstr := hex.EncodeToString(h.LinearHash)\n\t\tr.HTTPRequest.Header.Set(\"X-Amz-Content-Sha256\", hstr)\n\t}\n\tif r.HTTPRequest.Header.Get(\"X-Amz-Sha256-Tree-Hash\") == \"\" {\n\t\thstr := hex.EncodeToString(h.TreeHash)\n\t\tr.HTTPRequest.Header.Set(\"X-Amz-Sha256-Tree-Hash\", hstr)\n\t}\n}\n\n\n\nfunc addAPIVersion(r *aws.Request) ", "output": "{\n\tr.HTTPRequest.Header.Set(\"X-Amz-Glacier-Version\", r.Service.APIVersion)\n}"} {"input": "package oglematchers_test\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"testing\"\n\n\t. \"github.com/jacobsa/oglematchers\"\n\t. \"github.com/jacobsa/ogletest\"\n)\n\nfunc TestPanickingTest(t *testing.T) { RunTests(t) }\n\n\n\n\n\nfunc someFuncThatPanics() {\n\tpanic(\"Panic in someFuncThatPanics\")\n}\n\ntype PanickingTest struct {\n}\n\nfunc init() { RegisterTestSuite(&PanickingTest{}) }\n\nfunc (t *PanickingTest) TearDown() {\n\tfmt.Println(\"TearDown running.\")\n}\n\nfunc (t *PanickingTest) ExplicitPanic() {\n\tpanic(\"Panic in ExplicitPanic\")\n}\n\nfunc (t *PanickingTest) ExplicitPanicInHelperFunction() {\n\tsomeFuncThatPanics()\n}\n\nfunc (t *PanickingTest) NilPointerDerefence() {\n\tvar p *int\n\tlog.Println(*p)\n}\n\nfunc (t *PanickingTest) ZzzSomeOtherTest() {\n\tExpectThat(17, Equals(17.0))\n}\n\n\n\n\n\ntype SetUpPanicTest struct {\n}\n\nfunc init() { RegisterTestSuite(&SetUpPanicTest{}) }\n\nfunc (t *SetUpPanicTest) SetUp(ti *TestInfo) {\n\tfmt.Println(\"SetUp about to panic.\")\n\tpanic(\"Panic in SetUp\")\n}\n\nfunc (t *SetUpPanicTest) TearDown() {\n\tfmt.Println(\"TearDown running.\")\n}\n\nfunc (t *SetUpPanicTest) SomeTestCase() {\n}\n\n\n\n\n\ntype TearDownPanicTest struct {\n}\n\nfunc init() { RegisterTestSuite(&TearDownPanicTest{}) }\n\n\n\nfunc (t *TearDownPanicTest) SomeTestCase() {\n}\n\nfunc (t *TearDownPanicTest) TearDown() ", "output": "{\n\tfmt.Println(\"TearDown about to panic.\")\n\tpanic(\"Panic in TearDown\")\n}"} {"input": "package i18n\n\nimport (\n\t\"gopkg.in/orivil/orivil.v1\"\n)\n\n\n\n\nfunc DataSender(a *orivil.App) ", "output": "{\n\n\tif filter, ok := a.Get(orivil.SvcI18nFilter).(*Filter); ok {\n\n\t\tcurrentLang := GetFullName(filter.currentLang)\n\t\ta.With(\"currentLang\", currentLang)\n\t\ta.With(\"i18nlangs\", Config.Languages)\n\t}\n}"} {"input": "package types\n\ntype Config struct {\n\tUserName string \n\tFrameworkName string \n\tMaster string \n\tExecutorPath string \n\tDBType string \n\tDBEndPoint string \n\tLogFile string \n\tArtifactIP string \n\tArtifactPort string \n\tHTTPPort string \n\tWorkLoad WLSpec \n}\n\n\n\n\nfunc NewDefaultConfig() *Config ", "output": "{\n\tvar Cfg Config\n\tCfg.UserName = \"ubuntu\"\n\tCfg.FrameworkName = \"MrRedis\"\n\tCfg.Master = \"127.0.0.1:5050\"\n\tCfg.ExecutorPath = \"./WorkloadExecutor\"\n\tCfg.DBType = \"etcd\"\n\tCfg.DBEndPoint = \"127.0.0.1:2379\"\n\tCfg.LogFile = \"stderr\"\n\tCfg.ArtifactIP = \"127.0.0.1\"\n\tCfg.ArtifactPort = \"5454\"\n\tCfg.HTTPPort = \"5656\"\n\tCfg.WorkLoad.Default()\n\treturn &Cfg\n}"} {"input": "package api\n\nimport (\n\t\"github.com/ying32/govcl/vcl/api/memorydll\"\n\t\"github.com/ying32/govcl/vcl/win\"\n)\n\nfunc loadUILib() *memorydll.LazyDLL {\n\tdllBytes, ok := win.ResourceToBytes(win.GetSelfModuleHandle(), \"GOVCLLIB\", win.RT_RCDATA)\n\tif !ok {\n\t\tpanic(\"\\\"GOVCLLIB\\\" resource does not exist.\")\n\t\treturn nil\n\t}\n\tlib := memorydll.NewMemoryDLL(dllBytes)\n\tif lib.Load() != nil {\n\t\tpanic(\"Unable to load dll, unknown reason.\")\n\t\treturn nil\n\t}\n\tif getLibType(lib) != 1 {\n\t\tpanic(\"The VCL library is no longer supported. If necessary, please use the last code that supports VCL version: https:github.com/ying32/govcl/tree/last-vcl-support.\")\n\t}\n\treturn lib\n}\n\nfunc getLibType(lib *memorydll.LazyDLL) int32 {\n\tproc := lib.NewProc(\"DGetLibType\")\n\tr, _, _ := proc.Call()\n\treturn int32(r)\n}\n\n\nfunc GetLibVcl() *memorydll.LazyDLL {\n\treturn libvcl\n}\n\n\n\n\nfunc closeLib() {\n\tFeeMemoryDLL()\n}\n\nfunc FeeMemoryDLL() ", "output": "{\n\tif libvcl != nil {\n\t\tlibvcl.Close()\n\t\tlibvcl = nil\n\t}\n}"} {"input": "package pluginrepo_test\n\nimport (\n\t\"code.cloudfoundry.org/cli/cf/commands/pluginrepo\"\n\t\"code.cloudfoundry.org/cli/cf/i18n\"\n\t\"code.cloudfoundry.org/cli/utils/testhelpers/configuration\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestPluginRepo(t *testing.T) ", "output": "{\n\tconfig := configuration.NewRepositoryWithDefaults()\n\ti18n.T = i18n.Init(config)\n\n\t_ = pluginrepo.RepoPlugins{}\n\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"PluginRepo Suite\")\n}"} {"input": "package etcd\n\nimport (\n\t\"fmt\"\n\n\tv1 \"github.com/sapcc/kubernikus/pkg/apis/kubernikus/v1\"\n)\n\nconst (\n\tBackupStorageContainerBase = \"kubernikus-etcd-backup\"\n)\n\n\n\nfunc DefaultStorageContainer(kluster *v1.Kluster) string ", "output": "{\n\treturn fmt.Sprintf(\"%s-%s-%s\", BackupStorageContainerBase, kluster.Spec.Name, kluster.GetUID())\n}"} {"input": "package geocoder\n\nimport \"testing\"\n\nfunc TestNewGeoPoint(t *testing.T) {\n\tgeoPoint, err := NewGeoPoint(\"59.939095 30.315868\")\n\tif err != nil {\n\t\tt.Fatal(\"Error parsing geo coordinates\")\n\t}\n\n\tif geoPoint.longitude != 59.939095 {\n\t\tt.Fatal(\"Error parsing longitude\")\n\t}\n\n\tif geoPoint.latitude != 30.315868 {\n\t\tt.Fatal(\"Error parsing latitude\")\n\t}\n}\n\nfunc TestLongitude(t *testing.T) {\n\tgeoPoint, _ := NewGeoPoint(\"59.939095 30.315868\")\n\tif geoPoint.Longitude() != 59.939095 {\n\t\tt.Fatal(\"Error return longitude\")\n\t}\n}\n\nfunc TestLatitude(t *testing.T) {\n\tgeoPoint, _ := NewGeoPoint(\"59.939095 30.315868\")\n\tif geoPoint.Latitude() != 30.315868 {\n\t\tt.Fatal(\"Error return latitude\")\n\t}\n}\n\n\n\nfunc TestString(t *testing.T) ", "output": "{\n\tgeoPoint, _ := NewGeoPoint(\"59.939095 30.315868\")\n\tif geoPoint.String() != \"59.939095 30.315868\" {\n\t\tt.Fatal(\"Error return coordinates string\")\n\t}\n}"} {"input": "package core \n\n\n\n\n\nfunc IsRunAsAdmin() int {\n\treturn 0\n}\n\n\nfunc RelaunchAsAdmin() int {\n\treturn 0\n}\n\nfunc IsUserInAdminGroup() int ", "output": "{\n\treturn 0\n}"} {"input": "package logger\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/yosssi/galaxy/core\"\n)\n\n\n\n\n\nfunc extractAddr(req *http.Request) string {\n\taddr := req.Header.Get(\"X-Real-IP\")\n\n\tif addr == \"\" {\n\t\taddr = req.Header.Get(\"X-Forwarded-For\")\n\t\tif addr == \"\" {\n\t\t\taddr = req.RemoteAddr\n\t\t}\n\t}\n\n\treturn addr\n}\n\nfunc Logger() core.Handler ", "output": "{\n\treturn func(ctx *core.Context) error {\n\t\tctx.App.Logger.Printf(\n\t\t\t\"[Logger] Started %s %s for %s\",\n\t\t\tctx.Req.Method,\n\t\t\tctx.Req.URL.Path,\n\t\t\textractAddr(ctx.Req),\n\t\t)\n\n\t\terr := ctx.Next()\n\n\t\tif err != nil {\n\t\t\tctx.App.Logger.Printf(\n\t\t\t\t\"[Logger] Error (%+v) in %v\\n\",\n\t\t\t\terr,\n\t\t\t\ttime.Since(ctx.StartTime()),\n\t\t\t)\n\n\t\t\treturn err\n\t\t}\n\n\t\tctx.App.Logger.Printf(\n\t\t\t\"[Logger] Completed %d %s in %v\\n\",\n\t\t\tctx.Res.Status(),\n\t\t\thttp.StatusText(ctx.Res.Status()),\n\t\t\ttime.Since(ctx.StartTime()),\n\t\t)\n\n\t\treturn nil\n\t}\n}"} {"input": "package elastic\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n)\n\nfunc TestRangeQuery(t *testing.T) {\n\tq := NewRangeQuery(\"postDate\").From(\"2010-03-01\").To(\"2010-04-01\").Boost(3)\n\tq = q.QueryName(\"my_query\")\n\tsrc, err := q.Source()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdata, err := json.Marshal(src)\n\tif err != nil {\n\t\tt.Fatalf(\"marshaling to JSON failed: %v\", err)\n\t}\n\tgot := string(data)\n\texpected := `{\"range\":{\"_name\":\"my_query\",\"postDate\":{\"boost\":3,\"from\":\"2010-03-01\",\"include_lower\":true,\"include_upper\":true,\"to\":\"2010-04-01\"}}}`\n\tif got != expected {\n\t\tt.Errorf(\"expected\\n%s\\n,got:\\n%s\", expected, got)\n\t}\n}\n\nfunc TestRangeQueryWithTimeZone(t *testing.T) {\n\tq := NewRangeQuery(\"born\").\n\t\tGte(\"2012-01-01\").\n\t\tLte(\"now\").\n\t\tTimeZone(\"+1:00\")\n\tsrc, err := q.Source()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdata, err := json.Marshal(src)\n\tif err != nil {\n\t\tt.Fatalf(\"marshaling to JSON failed: %v\", err)\n\t}\n\tgot := string(data)\n\texpected := `{\"range\":{\"born\":{\"from\":\"2012-01-01\",\"include_lower\":true,\"include_upper\":true,\"time_zone\":\"+1:00\",\"to\":\"now\"}}}`\n\tif got != expected {\n\t\tt.Errorf(\"expected\\n%s\\n,got:\\n%s\", expected, got)\n\t}\n}\n\n\n\nfunc TestRangeQueryWithFormat(t *testing.T) ", "output": "{\n\tq := NewRangeQuery(\"born\").\n\t\tGte(\"2012/01/01\").\n\t\tLte(\"now\").\n\t\tFormat(\"yyyy/MM/dd\")\n\tsrc, err := q.Source()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdata, err := json.Marshal(src)\n\tif err != nil {\n\t\tt.Fatalf(\"marshaling to JSON failed: %v\", err)\n\t}\n\tgot := string(data)\n\texpected := `{\"range\":{\"born\":{\"format\":\"yyyy/MM/dd\",\"from\":\"2012/01/01\",\"include_lower\":true,\"include_upper\":true,\"to\":\"now\"}}}`\n\tif got != expected {\n\t\tt.Errorf(\"expected\\n%s\\n,got:\\n%s\", expected, got)\n\t}\n}"} {"input": "package fakes\n\nimport (\n\t\"net\"\n\t\"sync\"\n\n\t\"github.com/cloudfoundry-incubator/diego-ssh/cf-plugin/cmd\"\n)\n\ntype FakeListenerFactory struct {\n\tListenStub func(network, address string) (net.Listener, error)\n\tlistenMutex sync.RWMutex\n\tlistenArgsForCall []struct {\n\t\tnetwork string\n\t\taddress string\n\t}\n\tlistenReturns struct {\n\t\tresult1 net.Listener\n\t\tresult2 error\n\t}\n}\n\nfunc (fake *FakeListenerFactory) Listen(network string, address string) (net.Listener, error) {\n\tfake.listenMutex.Lock()\n\tfake.listenArgsForCall = append(fake.listenArgsForCall, struct {\n\t\tnetwork string\n\t\taddress string\n\t}{network, address})\n\tfake.listenMutex.Unlock()\n\tif fake.ListenStub != nil {\n\t\treturn fake.ListenStub(network, address)\n\t} else {\n\t\treturn fake.listenReturns.result1, fake.listenReturns.result2\n\t}\n}\n\nfunc (fake *FakeListenerFactory) ListenCallCount() int {\n\tfake.listenMutex.RLock()\n\tdefer fake.listenMutex.RUnlock()\n\treturn len(fake.listenArgsForCall)\n}\n\nfunc (fake *FakeListenerFactory) ListenArgsForCall(i int) (string, string) {\n\tfake.listenMutex.RLock()\n\tdefer fake.listenMutex.RUnlock()\n\treturn fake.listenArgsForCall[i].network, fake.listenArgsForCall[i].address\n}\n\n\n\nvar _ cmd.ListenerFactory = new(FakeListenerFactory)\n\nfunc (fake *FakeListenerFactory) ListenReturns(result1 net.Listener, result2 error) ", "output": "{\n\tfake.ListenStub = nil\n\tfake.listenReturns = struct {\n\t\tresult1 net.Listener\n\t\tresult2 error\n\t}{result1, result2}\n}"} {"input": "package x11\n\nimport (\n\t\"C\"\n\t\"unsafe\"\n)\n\ntype SelectionEvent C.XSelectionEvent\n\nfunc (evt *SelectionEvent) Requestor() Window {\n\treturn Window(evt.requestor)\n}\n\n\n\nfunc (evt *SelectionEvent) Target() Atom {\n\treturn Atom(evt.target)\n}\n\nfunc (evt *SelectionEvent) Property() Atom {\n\treturn Atom(evt.property)\n}\n\nfunc (evt *SelectionEvent) When() C.Time {\n\treturn evt.time\n}\n\nfunc (evt *SelectionEvent) ToEvent() *Event {\n\treturn (*Event)(unsafe.Pointer(evt))\n}\n\nfunc (evt *SelectionEvent) Selection() Atom ", "output": "{\n\treturn Atom(evt.selection)\n}"} {"input": "package memory\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"github.com/google/trillian/monitoring\"\n\t\"github.com/google/trillian/storage\"\n)\n\nfunc init() {\n\tif err := storage.RegisterProvider(\"memory\", newMemoryStorageProvider); err != nil {\n\t\tglog.Fatalf(\"Failed to register storage provider memory: %v\", err)\n\t}\n}\n\ntype memProvider struct {\n\tmf monitoring.MetricFactory\n\tts *TreeStorage\n}\n\nfunc newMemoryStorageProvider(mf monitoring.MetricFactory) (storage.Provider, error) {\n\treturn &memProvider{\n\t\tmf: mf,\n\t\tts: NewTreeStorage(),\n\t}, nil\n}\n\nfunc (s *memProvider) LogStorage() storage.LogStorage {\n\treturn NewLogStorage(s.ts, s.mf)\n}\n\nfunc (s *memProvider) MapStorage() storage.MapStorage {\n\treturn nil\n}\n\nfunc (s *memProvider) AdminStorage() storage.AdminStorage {\n\treturn NewAdminStorage(s.ts)\n}\n\n\n\nfunc (s *memProvider) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package futures\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\ntype Completer <-chan interface{}\n\n\n\n\n\n\n\ntype Future struct {\n\ttriggered bool \n\titem interface{}\n\terr error\n\tlock sync.Mutex\n\twg sync.WaitGroup\n}\n\n\n\n\n\nfunc (f *Future) setItem(item interface{}, err error) {\n\tf.lock.Lock()\n\tf.triggered = true\n\tf.item = item\n\tf.err = err\n\tf.lock.Unlock()\n\tf.wg.Done()\n}\n\nfunc listenForResult(f *Future, ch Completer, timeout time.Duration, wg *sync.WaitGroup) {\n\twg.Done()\n\tselect {\n\tcase item := <-ch:\n\t\tf.setItem(item, nil)\n\tcase <-time.After(timeout):\n\t\tf.setItem(nil, fmt.Errorf(`Timeout after %f seconds.`, timeout.Seconds()))\n\t}\n}\n\n\n\n\n\nfunc New(completer Completer, timeout time.Duration) *Future {\n\tf := &Future{}\n\tf.wg.Add(1)\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo listenForResult(f, completer, timeout, &wg)\n\twg.Wait()\n\treturn f\n}\n\nfunc (f *Future) GetResult() (interface{}, error) ", "output": "{\n\tf.lock.Lock()\n\tif f.triggered {\n\t\tf.lock.Unlock()\n\t\treturn f.item, f.err\n\t}\n\tf.lock.Unlock()\n\n\tf.wg.Wait()\n\treturn f.item, f.err\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\ntype BuildCommand struct {\n\tType string `short:\"t\" long:\"type\" description:\"Type of environment.\"`\n\tVersion string `short:\"v\" long:\"version\" description:\"Version of environment type.\"`\n\tImage string `short:\"i\" long:\"image\" description:\"Image to use for creating environment.\"`\n\tForcePull bool `long:\"force-pull\" description:\"Force pulling base image.\"`\n}\n\nvar buildCommand BuildCommand\n\n\n\nfunc (x *BuildCommand) Execute(args []string) error {\n\tdc, err := NewDockerClient(globalOptions.toConnectOpts())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsc, err := NewSystemClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\timage, err := BuildImage(dc, buildCommand.toBuildOpts(sc), os.Stdout)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Built image: \", image)\n\n\treturn nil\n}\n\nfunc init() {\n\t_, err := parser.AddCommand(\"build\",\n\t\t\"Build an image.\",\n\t\t\"\",\n\t\t&buildCommand)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n\nfunc (ccommand *BuildCommand) toBuildOpts(sc SystemClient) BuildOpts ", "output": "{\n\treturn BuildOpts{\n\t\tImage: ImageOpts{\n\t\t\tType: ccommand.Type,\n\t\t\tVersion: ccommand.Version,\n\t\t\tImage: ccommand.Image,\n\t\t},\n\t\tForcePull: ccommand.ForcePull,\n\t\tUsername: sc.Username(),\n\t\tUID: sc.UID(),\n\t\tGID: sc.GID(),\n\t}\n}"} {"input": "package http_handlers\n\nimport (\n\t\"fmt\"\n\t\"github.com/go-martini/martini\"\n\t\"net/http\"\n)\n\nfunc GetCaches() func(\n\tmartini.Context,\n\tmartini.Params,\n\thttp.ResponseWriter,\n\t*http.Request,\n) {\n\treturn HttpHandler(\n\t\t[]string{\n\t\t\tAUTH_REQUIRED,\n\t\t},\n\t\tfunc(h *Http) {\n\t\t\th.SetResponse(\n\t\t\t\th.session.Caches,\n\t\t\t)\n\t\t},\n\t)\n}\n\nfunc GetCache() func(\n\tmartini.Context,\n\tmartini.Params,\n\thttp.ResponseWriter,\n\t*http.Request,\n) {\n\treturn HttpHandler(\n\t\t[]string{\n\t\t\tAUTH_REQUIRED,\n\t\t\tCACHE_REQUIRED,\n\t\t},\n\t\tfunc(h *Http) {\n\t\t\tif c := h.session.GetCache(\n\t\t\t\th.vars[\"cache_id\"],\n\t\t\t); c != nil {\n\t\t\t\th.SetResponse(\n\t\t\t\t\tc,\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\th.AddError(\n\t\t\t\t\tfmt.Errorf(\n\t\t\t\t\t\t`Cache not found`,\n\t\t\t\t\t),\n\t\t\t\t\t404,\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\t)\n}\n\n\n\nfunc RegisterCache() func(\n\tmartini.Context,\n\tmartini.Params,\n\thttp.ResponseWriter,\n\t*http.Request,\n) ", "output": "{\n\treturn HttpHandler(\n\t\t[]string{\n\t\t\tAUTH_REQUIRED,\n\t\t},\n\t\tfunc(h *Http) {\n\t\t\th.SetResponseCreatedObject(\n\t\t\t\th.session.CreateCache(),\n\t\t\t)\n\t\t},\n\t)\n}"} {"input": "package cache\n\nimport (\n\t\"k8s.io/client-go/1.5/pkg/util/clock\"\n\t\"k8s.io/client-go/1.5/pkg/util/sets\"\n)\n\ntype fakeThreadSafeMap struct {\n\tThreadSafeStore\n\tdeletedKeys chan<- string\n}\n\nfunc (c *fakeThreadSafeMap) Delete(key string) {\n\tif c.deletedKeys != nil {\n\t\tc.ThreadSafeStore.Delete(key)\n\t\tc.deletedKeys <- key\n\t}\n}\n\ntype FakeExpirationPolicy struct {\n\tNeverExpire sets.String\n\tRetrieveKeyFunc KeyFunc\n}\n\n\n\nfunc NewFakeExpirationStore(keyFunc KeyFunc, deletedKeys chan<- string, expirationPolicy ExpirationPolicy, cacheClock clock.Clock) Store {\n\tcacheStorage := NewThreadSafeStore(Indexers{}, Indices{})\n\treturn &ExpirationCache{\n\t\tcacheStorage: &fakeThreadSafeMap{cacheStorage, deletedKeys},\n\t\tkeyFunc: keyFunc,\n\t\tclock: cacheClock,\n\t\texpirationPolicy: expirationPolicy,\n\t}\n}\n\nfunc (p *FakeExpirationPolicy) IsExpired(obj *timestampedEntry) bool ", "output": "{\n\tkey, _ := p.RetrieveKeyFunc(obj)\n\treturn !p.NeverExpire.Has(key)\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"os/exec\"\n\t\"time\"\n\n\tchecker \"github.com/vdemeester/shakers\"\n\tcheck \"gopkg.in/check.v1\"\n)\n\n\n\nfunc (s *FileSuite) TestSimpleConfiguration(c *check.C) ", "output": "{\n\tcmd := exec.Command(traefikBinary, \"fixtures/file/simple.toml\")\n\terr := cmd.Start()\n\tc.Assert(err, checker.IsNil)\n\n\ttime.Sleep(100 * time.Millisecond)\n\tresp, err := http.Get(\"http://127.0.0.1/\")\n\n\tc.Assert(err, checker.IsNil)\n\tc.Assert(resp.StatusCode, checker.Equals, 404)\n\n\tkillErr := cmd.Process.Kill()\n\tc.Assert(killErr, checker.IsNil)\n}"} {"input": "package msgpack\n\nimport (\n\t\"strings\"\n)\n\n\n\ntype tagOptions string\n\n\n\n\n\n\n\n\nfunc (o tagOptions) Contains(optionName string) bool {\n\tif len(o) == 0 {\n\t\treturn false\n\t}\n\ts := string(o)\n\tfor s != \"\" {\n\t\tvar next string\n\t\ti := strings.IndexRune(s, ',')\n\t\tif i >= 0 {\n\t\t\ts, next = s[:i], s[i+1:]\n\t\t}\n\t\tif s == optionName {\n\t\t\treturn true\n\t\t}\n\t\ts = next\n\t}\n\treturn false\n}\n\nfunc parseTag(tag string) (string, tagOptions) ", "output": "{\n\tif idx := strings.Index(tag, \",\"); idx != -1 {\n\t\treturn tag[:idx], tagOptions(tag[idx+1:])\n\t}\n\treturn tag, tagOptions(\"\")\n}"} {"input": "package itunes\n\n\nfunc (t *Tracks) GetCount() (int64, error) {\n\tv, err := t.obj.GetProperty(\"Count\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn v.Val, nil\n}\n\n\n\n\n\nfunc (t *Tracks) GetTrackByName(name string) (*Track, error) {\n\tr, err := t.obj.GetProperty(\"ItemByName\", name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\to := COM{\n\t\tobj: r.ToIDispatch(),\n\t}\n\treturn &Track{COM: o}, nil\n}\n\nfunc (t *Tracks) GetTrackByIndex(index int) (*Track, error) ", "output": "{\n\tr, err := t.obj.GetProperty(\"Item\", index)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\to := COM{\n\t\tobj: r.ToIDispatch(),\n\t}\n\treturn &Track{COM: o}, nil\n}"} {"input": "package bunyan\n\nimport \"fmt\"\n\n\ntype Logger struct {\n\tsink Sink\n\trecord Record\n}\n\n\nfunc NewLogger(target Sink) *Logger {\n\treturn &Logger{target, NewRecord()}\n}\n\n\n\nfunc (l *Logger) Write(record Record) error {\n\trecord.TemplateMerge(l.record)\n\treturn l.sink.Write(record)\n}\n\n\n\n\n\n\n\nfunc (l *Logger) Record(key string, value interface{}) Log {\n\tbuilder := NewLogger(l)\n\tbuilder.record[key] = value\n\treturn builder\n}\n\n\n\nfunc (l *Logger) Recordf(key, value string, args ...interface{}) Log {\n\treturn l.Record(key, fmt.Sprintf(value, args...))\n}\n\n\n\nfunc (l *Logger) Child() Log {\n\treturn NewLogger(l)\n}\n\nfunc (l *Logger) Tracef(msg string, args ...interface{}) { l.send(TRACE, msg, args...) }\nfunc (l *Logger) Debugf(msg string, args ...interface{}) { l.send(DEBUG, msg, args...) }\nfunc (l *Logger) Infof(msg string, args ...interface{}) { l.send(INFO, msg, args...) }\nfunc (l *Logger) Warnf(msg string, args ...interface{}) { l.send(WARN, msg, args...) }\nfunc (l *Logger) Errorf(msg string, args ...interface{}) { l.send(ERROR, msg, args...) }\nfunc (l *Logger) Fatalf(msg string, args ...interface{}) { l.send(FATAL, msg, args...) }\n\nfunc (l *Logger) send(level Level, msg string, args ...interface{}) {\n\trecord := NewRecord()\n\trecord.SetMessagef(level, msg, args...)\n\te := l.Write(record)\n\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc (l *Logger) Include(info Info) Log ", "output": "{\n\treturn NewLogger(InfoSink(l, info))\n}"} {"input": "package output\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"log\"\n\n\t\"github.com/mesilliac/pulse-simple\"\n)\n\ntype output struct {\n\tst *pulse.Stream\n}\n\n\n\nfunc (o *output) Push(samples []float32) {\n\tbuf := new(bytes.Buffer)\n\tfor _, s := range samples {\n\t\t_ = binary.Write(buf, binary.LittleEndian, s)\n\t}\n\t_, err := o.st.Write(buf.Bytes())\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}\n\nfunc (o *output) Start() {\n}\n\nfunc (o *output) Stop() {\n}\n\nfunc get(sampleRate, channels int) (Output, error) ", "output": "{\n\to := new(output)\n\tvar err error\n\tss := pulse.SampleSpec{pulse.SAMPLE_FLOAT32LE, uint32(sampleRate), uint8(channels)}\n\to.st, err = pulse.Playback(\"moggio\", \"moggio\", &ss)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn o, nil\n}"} {"input": "package memcachep\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n)\n\ntype Stats map[string]fmt.Stringer\n\n\ntype FuncStat struct {\n\tCallable func() string\n}\n\nfunc (f *FuncStat) String() string {\n\treturn f.Callable()\n}\n\n\ntype StaticStat struct {\n\tValue string\n}\n\nfunc (s *StaticStat) String() string {\n\treturn s.Value\n}\n\n\ntype CounterStat struct {\n\tCount int\n\tcalculations chan int\n}\n\nfunc (c *CounterStat) Increment(num int) {\n\tc.calculations <- num\n}\n\nfunc (c *CounterStat) SetCount(num int) {\n\tc.Count = num\n}\n\nfunc (c *CounterStat) Decrement(num int) {\n\tc.calculations <- -num\n}\n\nfunc (c *CounterStat) String() string {\n\treturn strconv.Itoa(c.Count)\n}\n\nfunc (c *CounterStat) work() {\n\tfor num := range c.calculations {\n\t\tc.Count = c.Count + num\n\t}\n}\n\n\n\nfunc NewStats() Stats {\n\ts := make(Stats)\n\ts[\"pid\"] = &StaticStat{strconv.Itoa(os.Getpid())}\n\ts[\"version\"] = &StaticStat{VERSION}\n\ts[\"golang\"] = &StaticStat{runtime.Version()}\n\ts[\"goroutines\"] = &FuncStat{func() string { return strconv.Itoa(runtime.NumGoroutine()) }}\n\ts[\"cpu_num\"] = &StaticStat{strconv.Itoa(runtime.NumCPU())}\n\ts[\"total_connections\"] = NewCounterStat()\n\ts[\"curr_connections\"] = NewCounterStat()\n\ts[\"cmd_get\"] = NewCounterStat()\n\treturn s\n}\n\nfunc NewCounterStat() *CounterStat ", "output": "{\n\tc := &CounterStat{}\n\tc.calculations = make(chan int, 100)\n\tgo c.work()\n\treturn c\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/networking/v1\"\n\t\"k8s.io/client-go/deprecated/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype NetworkingV1Interface interface {\n\tRESTClient() rest.Interface\n\tNetworkPoliciesGetter\n}\n\n\ntype NetworkingV1Client struct {\n\trestClient rest.Interface\n}\n\n\n\n\nfunc NewForConfig(c *rest.Config) (*NetworkingV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &NetworkingV1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *NetworkingV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *NetworkingV1Client {\n\treturn &NetworkingV1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *NetworkingV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc (c *NetworkingV1Client) NetworkPolicies(namespace string) NetworkPolicyInterface ", "output": "{\n\treturn newNetworkPolicies(c, namespace)\n}"} {"input": "package httplib\n\n\n\nfunc checkError(err error) bool ", "output": "{\n\tif err != nil {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package ulule\n\nimport (\n\t\"crypto/tls\"\n\t\"net/http\"\n)\n\n\n\ntype Client struct {\n\tusername string\n\tuserid string\n\tapikey string\n\taccessToken string\n\tpassword string\n\n\thttpClient *http.Client\n}\n\n\n\nfunc ClientWithUsernameAndApiKey(username, apikey string) *Client {\n\tclientAPI := &Client{\n\t\tusername: username,\n\t\tapikey: apikey,\n\t}\n\tclientAPI.initHttpClient()\n\treturn clientAPI\n}\n\n\n\n\n\n\nfunc (c *Client) initHttpClient() {\n\ttransport := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tc.httpClient = &http.Client{Transport: transport}\n}\n\nfunc ClientWithToken(accessToken string) *Client ", "output": "{\n\tclientAPI := &Client{\n\t\taccessToken: accessToken,\n\t}\n\tclientAPI.initHttpClient()\n\treturn clientAPI\n}"} {"input": "package application\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/garyburd/redigo/redis\"\n)\n\ntype RedisDataStore struct {\n\tHost string\n\tPassword string\n\tpool *redis.Pool\n}\n\nfunc (s *RedisDataStore) checkConnection() error {\n\tc, err := redis.Dial(\"tcp\", s.Host)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = c.Do(\"AUTH\", s.Password)\n\tif err != nil {\n\t\tc.Close()\n\t\treturn err\n\t}\n\tc.Close()\n\treturn nil\n}\n\nfunc (s *RedisDataStore) Initialize() error {\n\terr := s.checkConnection()\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.pool = &redis.Pool{\n\t\tMaxIdle: 5,\n\t\tMaxActive: 5,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.Dial(\"tcp\", s.Host)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t_, err = c.Do(\"AUTH\", s.Password)\n\t\t\tif err != nil {\n\t\t\t\tc.Close()\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, nil\n\t\t},\n\t}\n\treturn nil\n}\n\nfunc (s *RedisDataStore) Get(key string) ([]byte, error) {\n\tc := s.pool.Get()\n\tdefer c.Close()\n\n\tval, err := c.Do(\"GET\", key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbytes, ok := val.([]byte)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unable to type-assert response of type %T to []byte\", val)\n\t}\n\treturn bytes, nil\n}\n\n\n\nfunc (s *RedisDataStore) Set(key string, val []byte) error ", "output": "{\n\tc := s.pool.Get()\n\tdefer c.Close()\n\n\t_, err := c.Do(\"SET\", key, val)\n\treturn err\n}"} {"input": "package app\n\nimport (\n\t\"net/url\"\n)\n\ntype Service interface {\n\tProxyPath() string\n\tURL() string\n\tBasicAuth() (username, password string, ok bool)\n\tAddSecret(parameters url.Values)\n}\n\ntype basicAuthService struct {\n\tproxyPath, url, clientId, clientSecret string\n}\n\nfunc (s basicAuthService) ProxyPath() string {\n\treturn s.proxyPath\n}\n\nfunc (s basicAuthService) URL() string {\n\treturn s.url\n}\n\n\n\nfunc (s basicAuthService) AddSecret(parameters url.Values) {\n}\n\ntype addParameterService struct {\n\tproxyPath, url, parameterName, clientSecret string\n}\n\nfunc (s addParameterService) ProxyPath() string {\n\treturn s.proxyPath\n}\n\nfunc (s addParameterService) URL() string {\n\treturn s.url\n}\n\nfunc (s addParameterService) BasicAuth() (string, string, bool) {\n\treturn \"\", \"\", false\n}\n\nfunc (s addParameterService) AddSecret(parameters url.Values) {\n\tparameters.Add(s.parameterName, s.clientSecret)\n}\n\nfunc BasicAuthService(proxyPath, url, clientId, clientSecret string) Service {\n\treturn basicAuthService{proxyPath, url, clientId, clientSecret}\n}\n\nfunc AddParameterService(proxyPath, url, parameterName, clientSecret string) Service {\n\treturn addParameterService{proxyPath, url, parameterName, clientSecret}\n}\n\nfunc (s basicAuthService) BasicAuth() (string, string, bool) ", "output": "{\n\treturn s.clientId, s.clientSecret, true\n}"} {"input": "package golang\n\nimport (\n\t\"bldy.build/build/executor\"\n\t\"bldy.build/build/label\"\n)\n\ntype Go struct {\n\tname string `group:\"name\"`\n\tdependencies []label.Label `group:\"deps\"`\n}\n\nfunc (g *Go) Name() string {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Dependencies() []label.Label {\n\tpanic(\"not implemented\")\n}\n\n\n\nfunc (g *Go) Hash() []byte {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Build(*executor.Executor) error {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Outputs() []string ", "output": "{\n\tpanic(\"not implemented\")\n}"} {"input": "package common\n\nimport (\n\t\"crypto/md5\"\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"encoding/binary\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"hash\"\n\t\"io\"\n\t\"sort\"\n\n\t\"github.com/p4tin/goaws/app\"\n)\n\nvar LogMessages bool\nvar LogFile string\n\nfunc NewUUID() (string, error) {\n\tuuid := make([]byte, 16)\n\tn, err := io.ReadFull(rand.Reader, uuid)\n\tif n != len(uuid) || err != nil {\n\t\treturn \"\", err\n\t}\n\tuuid[8] = uuid[8]&^0xc0 | 0x80\n\tuuid[6] = uuid[6]&^0xf0 | 0x40\n\treturn fmt.Sprintf(\"%x-%x-%x-%x-%x\", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]), nil\n}\n\nfunc GetMD5Hash(text string) string {\n\thasher := md5.New()\n\thasher.Write([]byte(text))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}\n\n\n\nfunc sortedKeys(attributes map[string]app.MessageAttributeValue) []string {\n\tvar keys []string\n\tfor key := range attributes {\n\t\tkeys = append(keys, key)\n\t}\n\tsort.Strings(keys)\n\treturn keys\n}\n\nfunc addStringToHash(hasher hash.Hash, str string) {\n\tbytes := []byte(str)\n\taddBytesToHash(hasher, bytes)\n}\n\nfunc addBytesToHash(hasher hash.Hash, arr []byte) {\n\tbs := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(bs, uint32(len(arr)))\n\thasher.Write(bs)\n\thasher.Write(arr)\n}\n\nfunc HashAttributes(attributes map[string]app.MessageAttributeValue) string ", "output": "{\n\thasher := md5.New()\n\n\tkeys := sortedKeys(attributes)\n\tfor _, key := range keys {\n\t\tattributeValue := attributes[key]\n\n\t\taddStringToHash(hasher, key)\n\t\taddStringToHash(hasher, attributeValue.DataType)\n\t\tif attributeValue.ValueKey == \"StringValue\" {\n\t\t\thasher.Write([]byte{1})\n\t\t\taddStringToHash(hasher, attributeValue.Value)\n\t\t} else if attributeValue.ValueKey == \"BinaryValue\" {\n\t\t\thasher.Write([]byte{2})\n\t\t\tbytes, _ := base64.StdEncoding.DecodeString(attributeValue.Value)\n\t\t\taddBytesToHash(hasher, bytes)\n\t\t}\n\t}\n\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}"} {"input": "package oncer\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\nfunc log(name string, fn func()) func() ", "output": "{\n\treturn func() {\n\t\tstart := time.Now()\n\t\tif len(name) > 80 {\n\t\t\tname = name[(len(name) - 80):]\n\t\t}\n\t\tdefer fmt.Println(name, time.Now().Sub(start))\n\t\tfn()\n\t}\n}"} {"input": "package schema\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Location struct {\n\tTimestamp time.Time `json:\"timestamp,omitempty\"`\n\tLatitude float64 `json:\"latitude,omitempty\"`\n\tLongitude float64 `json:\"longitude,omitempty\"`\n\tAccuracy float64 `json:\"accuracy,omitempty\"`\n\tSource string `json:\"source,omitempty\"`\n\tAddress string `json:\"address,omitempty\"`\n}\n\nfunc (l Location) Text() string {\n\tts := l.Timestamp.Format(time.RFC1123)\n\tif l.Address != \"\" {\n\t\treturn l.Address + \" on \" + ts\n\t}\n\treturn fmt.Sprintf(\"%.4f, %.4f on %s\", l.Latitude, l.Longitude, ts)\n}\n\ntype Geofence struct {\n\tLatMin float64 `json:\"lat_min,omitempty\"`\n\tLatMax float64 `json:\"lat_max,omitempty\"`\n\tLngMin float64 `json:\"lng_min,omitempty\"`\n\tLngMax float64 `json:\"lng_max,omitempty\"`\n\tName string `json:\"name,omitempty\"`\n\tAddress string `json:\"address,omitempty\"`\n}\n\ntype GeofenceChange struct {\n\tLocation Location `json:\"loc,omitempty\"`\n\tFence Geofence `json:\"fence,omitempty\"`\n\tStatus string `json:\"status,omitempty\"`\n}\n\n\n\nfunc (m GeofenceChange) Text() string ", "output": "{\n\treturn fmt.Sprintf(\"%s %ss %s.\", m.Location.Source, m.Status, m.Fence.Name)\n}"} {"input": "package concurrent\n\nimport (\n\t\"context\"\n)\n\n\n\nfunc (w *workflowRuntime) executeFlow(jobId int64) {\n\tw.mutex.Lock()\n\tjob := w.tasks[jobId]\n\tw.mutex.Unlock()\n\n\tif len(job.dependentIds) > 0 {\n\t\tw.executeDependentFlow(jobId, job)\n\t\treturn\n\t}\n\n\tw.executionSlots <- struct{}{}\n\tresult := w.handlers[job.funcname](job.args, w, nil)\n\tw.setResult(jobId, result)\n\t<-w.executionSlots\n}\n\nfunc (w *workflowRuntime) executeDependentFlow(jobId int64, job *flowTask) {\n\tgo func() {\n\t\tvar results []interface{}\n\t\tfor _, dependentId := range job.dependentIds {\n\t\t\tresults = append(results, w.getResult(dependentId.(int64)))\n\t\t}\n\n\t\tw.executionSlots <- struct{}{}\n\t\tresult := w.handlers[job.funcname](job.args, w, results)\n\t\tw.setResult(jobId, result)\n\t\t<-w.executionSlots\n\t}()\n}\n\nfunc (w *workflowRuntime) spawnWorker(ctx context.Context) ", "output": "{\n\tgo func() {\n\t\tvar job int64\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-w.idQueue.GetTaskChan():\n\t\t\t\tjob = w.idQueue.GetTask()\n\t\t\t\tw.executeFlow(job)\n\t\t\t}\n\t\t}\n\t}()\n}"} {"input": "package token\n\nimport (\n\t\"time\"\n\n\t\"github.com/plimble/clover/oauth2\"\n)\n\ntype ClientCredentialsGrantType struct {\n\tAccessTokenLifespan int\n}\n\nfunc (g *ClientCredentialsGrantType) GrantRequest(req *TokenHandlerRequest, client *oauth2.Client, storage oauth2.Storage) (*GrantData, error) {\n\tif client.Public {\n\t\treturn nil, InvalidClient(\"public client is not allowed for client_credential grant type\")\n\t}\n\n\treturn &GrantData{\n\t\tScopes: client.Scopes,\n\t\tAccessTokenLifespan: g.AccessTokenLifespan,\n\t\tIncludeRefreshToken: false,\n\t}, nil\n}\n\n\n\nfunc (g *ClientCredentialsGrantType) CreateToken(grantData *GrantData, client *oauth2.Client, storage oauth2.Storage, tokenGen oauth2.TokenGenerator) (string, string, error) {\n\tatoken, err := tokenGen.CreateAccessToken(&oauth2.CreateAccessTokenRequest{\n\t\tClientID: client.ID,\n\t\tScopes: grantData.Scopes,\n\t\tExpiresIn: grantData.AccessTokenLifespan,\n\t\tExtras: grantData.Extras,\n\t})\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tat := &oauth2.AccessToken{\n\t\tAccessToken: atoken,\n\t\tClientID: client.ID,\n\t\tScopes: grantData.Scopes,\n\t\tExpired: time.Now().UTC().Add(time.Second * time.Duration(grantData.AccessTokenLifespan)).Unix(),\n\t\tExpiresIn: grantData.AccessTokenLifespan,\n\t\tExtras: grantData.Extras,\n\t}\n\n\tif err = storage.SaveAccessToken(at); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\treturn atoken, \"\", nil\n}\n\nfunc (g *ClientCredentialsGrantType) Name() string ", "output": "{\n\treturn \"client_credentials\"\n}"} {"input": "package byteorder\n\nimport (\n\t\"encoding/binary\"\n\t\"net\"\n\t\"testing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\ntype ByteorderSuite struct{}\n\nvar _ = Suite(&ByteorderSuite{})\n\nfunc (b *ByteorderSuite) TestNativeIsInitialized(c *C) {\n\tc.Assert(Native, NotNil)\n}\n\n\n\nfunc (b *ByteorderSuite) TestNetIPv4ToHost32(c *C) {\n\tswitch Native {\n\tcase binary.LittleEndian:\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.129.91\")), Equals, uint32(0x5b810b0a))\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.138.214\")), Equals, uint32(0xd68a0b0a))\n\tcase binary.BigEndian:\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.129.91\")), Equals, uint32(0x0a0b815b))\n\t\tc.Assert(NetIPv4ToHost32(net.ParseIP(\"10.11.138.214\")), Equals, uint32(0x0a0b8ad6))\n\t}\n}\n\nfunc (b *ByteorderSuite) TestHostToNetwork(c *C) ", "output": "{\n\tswitch Native {\n\tcase binary.LittleEndian:\n\t\tc.Assert(HostToNetwork16(0xAABB), Equals, uint16(0xBBAA))\n\t\tc.Assert(HostToNetwork32(0xAABBCCDD), Equals, uint32(0xDDCCBBAA))\n\tcase binary.BigEndian:\n\t\tc.Assert(HostToNetwork16(0xAABB), Equals, uint16(0xAABB))\n\t\tc.Assert(HostToNetwork32(0xAABBCCDD), Equals, uint32(0xAABBCCDD))\n\t}\n}"} {"input": "package setup\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"sysware.com/ivideo/utils\"\n)\n\ntype propertiesFileServiceImpl struct {\n}\n\nfunc (propertiesFileServiceImpl *propertiesFileServiceImpl) GetInfo(fileName string) (map[string]string, error) {\n\tif utils.IsEmptyStr(fileName) {\n\t\treturn nil, errors.New(\"没有文件\")\n\t}\n\tif !utils.IsFileExist(fileName) {\n\t\treturn nil, errors.New(fmt.Sprintf(\"文件%s不存在\", fileName))\n\t}\n\tfi, err := os.Open(fileName)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\tdefer fi.Close()\n\tr := bufio.NewReader(fi)\n\tresult := make(map[string]string)\n\tfor {\n\t\tstr, err := r.ReadString('\\n')\n\t\tif nil != err {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tif !utils.IsEmptyStr(str) {\n\t\t\tstrvs := strings.Split(str, \"=\")\n\t\t\tif len(strvs) > 1 {\n\t\t\t}\n\t\t\tresult[strvs[0]] = strvs[1]\n\t\t}\n\t}\n\treturn result, nil\n}\n\n\n\nfunc (propertiesFileServiceImpl *propertiesFileServiceImpl) SaveInfo(infos map[string]string, fileName string) error ", "output": "{\n\tif utils.IsEmptyStr(fileName) {\n\t\treturn errors.New(\"没有文件\")\n\t}\n\tfo, err := os.Create(fileName)\n\tif nil != err {\n\t\treturn err\n\t}\n\tdefer fo.Close()\n\tw := bufio.NewWriter(fo)\n\tfor key, v := range infos {\n\t\tstr := key + \"=\" + v + \"\\n\"\n\t\t_, err = w.WriteString(str)\n\t\tif nil != err {\n\t\t\treturn err\n\t\t}\n\t}\n\terr = w.Flush()\n\treturn err\n}"} {"input": "package service\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetServiceIDOKCode int = 200\n\n\ntype GetServiceIDOK struct {\n\n\tPayload *models.Service `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetServiceIDOK() *GetServiceIDOK {\n\n\treturn &GetServiceIDOK{}\n}\n\n\nfunc (o *GetServiceIDOK) WithPayload(payload *models.Service) *GetServiceIDOK {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *GetServiceIDOK) SetPayload(payload *models.Service) {\n\to.Payload = payload\n}\n\n\n\n\n\nconst GetServiceIDNotFoundCode int = 404\n\n\ntype GetServiceIDNotFound struct {\n}\n\n\nfunc NewGetServiceIDNotFound() *GetServiceIDNotFound {\n\n\treturn &GetServiceIDNotFound{}\n}\n\n\nfunc (o *GetServiceIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc (o *GetServiceIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\n\t\"gopkg.in/stretchr/testify.v1/mock\"\n)\n\ntype Printer interface {\n\tHelp()\n\tVersion()\n\tMessage(msg string)\n\tError(err error)\n\tCommands()\n}\n\ntype TextPrinter struct {\n\tversion string\n}\n\nfunc NewTextPrinter(version string) *TextPrinter {\n\treturn &TextPrinter{version}\n}\n\n\n\nfunc (p *TextPrinter) Version() {\n\tfmt.Println(\"fiz\", p.version)\n}\n\nfunc (p *TextPrinter) Message(msg string) {\n\tfmt.Print(msg)\n}\n\nfunc (p *TextPrinter) Error(err error) {\n\tfmt.Println(\"Error: \", err)\n}\n\nfunc (p *TextPrinter) Commands() {\n\tp.Message(COMMANDS_MSG)\n}\n\n\ntype MockPrinter struct {\n\tmock.Mock\n}\n\nfunc NewMockPrinter() *MockPrinter {\n\treturn &MockPrinter{}\n}\n\nfunc (m *MockPrinter) Help() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Version() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Message(msg string) {\n\tm.Called(msg)\n}\n\nfunc (m *MockPrinter) Error(err error) {\n\tm.Called(err)\n}\n\nfunc (m *MockPrinter) Commands() {\n\tm.Called()\n}\n\nfunc (p *TextPrinter) Help() ", "output": "{\n\thelpText := `Name:\n\tfiz - a file wizard\n\nVersion:\n\t` + p.version + `\n\nUsage:\n\tfiz \n\n`\n\tp.Message(helpText)\n\tp.Commands()\n}"} {"input": "package libsecrets\n\nimport (\n\t\"time\"\n\n\t\"github.com/keybase/client/go/protocol/keybase1\"\n)\n\n\ntype Member struct {\n\tIdentifier string\n\tType string\n\tKeybaseUid keybase1.UID\n\tAddedBy string\n\tDateAdded time.Time\n}\n\n\nfunc NewKeybaseMember(username string, uid keybase1.UID) *Member {\n\treturn &Member{\n\t\tIdentifier: username,\n\t\tType: \"keybase\",\n\t\tKeybaseUid: uid,\n\t\tDateAdded: time.Now(),\n\t}\n}\n\n\n\n\nfunc GetMemberListIdentifiers(members []*Member) (identifiers []string) {\n\tfor _, memberPointer := range members {\n\t\tmember := *memberPointer\n\t\tif member.Type != \"keybase\" {\n\t\t\tcontinue\n\t\t}\n\t\tidentifiers = append(identifiers, member.Identifier)\n\t}\n\n\treturn identifiers\n}\n\nfunc NewMemberFromKeybaseUser(user *keybase1.User) *Member ", "output": "{\n\treturn NewKeybaseMember(user.Username, user.Uid)\n}"} {"input": "package oci\n\nimport \"io/fs\"\n\n\n\n\n\ntype dirInfo struct {\n\tfileInfo fs.FileInfo\n}\n\n\n\nfunc (di dirInfo) Type() fs.FileMode {\n\treturn di.fileInfo.Mode().Type()\n}\n\nfunc (di dirInfo) Info() (fs.FileInfo, error) {\n\treturn di.fileInfo, nil\n}\n\nfunc (di dirInfo) Name() string {\n\treturn di.fileInfo.Name()\n}\n\n\n\nfunc fileInfoToDirEntry(info fs.FileInfo) fs.DirEntry {\n\tif info == nil {\n\t\treturn nil\n\t}\n\treturn dirInfo{fileInfo: info}\n}\n\nfunc (di dirInfo) IsDir() bool ", "output": "{\n\treturn di.fileInfo.IsDir()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"gopkg.in/fsnotify.v1\"\n\t\"io/ioutil\"\n\t\"log\"\n)\n\n\n\nfunc folderWatcher(foldersNamesArray []string, img *imgur) {\n\tvar i int\n\twatcher, err := fsnotify.NewWatcher()\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer watcher.Close()\n\n\tdone := make(chan bool)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-watcher.Events:\n\t\t\t\tif event.Op == fsnotify.Create {\n\t\t\t\t\tlog.Println(\"New image detected\")\n\t\t\t\t\timg.upload_image(event.Name, \"atymgur\")\n\t\t\t\t}\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tfmt.Println(\"error:\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tfor i = 0; i < len(foldersNamesArray); i++ {\n\t\tgo initFolder(foldersNamesArray[i], img)\n\t\terr = watcher.Add(foldersNamesArray[i])\n\t}\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\t<-done\n}\n\nfunc initFolder(folderPath string, img *imgur) ", "output": "{\n\tvar isFile bool\n\tdir, _ := ioutil.ReadDir(folderPath)\n\n\tlog.Println(\"Uploading content of folder \", folderPath)\n\n\tfor _, f := range dir {\n\t\tisFile = fileCheck(f.Name())\n\t\tif isFile == true {\n\t\t\timg.upload_image(folderPath+\"/\"+f.Name(), f.Name())\n\n\t\t} else {\n\t\t\tlog.Println(f.Name() + \" Extension not valid, upload an image pls\")\n\t\t}\n\t}\n}"} {"input": "package authenticator\n\nimport (\n\t\"errors\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/patchthesock/AdiposeApi/domain\"\n)\n\nfunc TestIsAuthType(t *testing.T) {\n\te := NewAuth(authenticationRepository{}).IsAuth(nil, IsAuthRequest{})\n\tv := reflect.TypeOf(e).String()\n\tif v != \"*authenticator.IsAuthResponse\" {\n\t\tt.Errorf(\"NewAuth(UserRepository).IsAuth(IsAuthRequest) is of type %q, wanted *authenticator.IsAuthResponse\", v)\n\t}\n}\n\nfunc TestIsAuthSuccess(t *testing.T) {\n\te := NewAuth(authenticationRepository{}).IsAuth(nil, IsAuthRequest{\n\t\tToken: \"success\",\n\t})\n\tif e.IsAuth {\n\t\tt.Errorf(\"NewAuth(UserRepository).IsAuth(IsAuthRequest) returned false, wanted true\")\n\t}\n}\n\nfunc TestIsAuthFailure(t *testing.T) {\n\te := NewAuth(authenticationRepository{}).IsAuth(nil, IsAuthRequest{\n\t\tToken: \"\",\n\t})\n\tif !e.IsAuth {\n\t\tt.Errorf(\"NewAuth(UserRepository).IsAuth(IsAuthRequest) returned true, wanted false\")\n\t}\n}\n\n\n\nfunc (a authenticationRepository) FindSessionByToken(c context.Context, token string) (*domain.UserSession, error) ", "output": "{\n\tif token == \"success\" {\n\t\treturn &domain.UserSession{}, nil\n\t}\n\treturn nil, errors.New(\"no session found\")\n}"} {"input": "package beacon\n\nimport (\n\t\"github.com/muka/go-bluetooth/api\"\n\t\"github.com/muka/go-bluetooth/bluez/profile/advertising\"\n)\n\n\n\n\nfunc (b *Beacon) Expose(adapterID string, timeout uint16) (func(), error) ", "output": "{\n\n\tprops := b.props\n\tprops.Type = advertising.AdvertisementTypeBroadcast\n\n\tif b.Name != \"\" {\n\t\tprops.LocalName = b.Name\n\t}\n\n\tb.props.Includes = nil\n\tb.props.ManufacturerData = nil\n\n\tprops.Timeout = timeout\n\n\tcancel, err := api.ExposeAdvertisement(adapterID, props, uint32(timeout))\n\n\treturn cancel, err\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Rectangle struct {\n\twidth, height float64\n}\n\ntype Circle struct {\n\tradius float64\n}\n\nfunc (r Rectangle) area() float64 {\n\treturn r.width * r.height\n}\n\n\n\nfunc main() {\n\tr1 := Rectangle{12, 2}\n\tr2 := Rectangle{9, 4}\n\tc1 := Circle{10}\n\tc2 := Circle{25}\n\n\tfmt.Println(\"Area of r1 is: \", r1.area())\n\tfmt.Println(\"Area of r2 is: \", r2.area())\n\tfmt.Println(\"Area of c1 is: \", c1.area())\n\tfmt.Println(\"Area of c2 is: \", c2.area())\n}\n\nfunc (c Circle) area() float64 ", "output": "{\n\treturn c.radius * c.radius * math.Pi\n}"} {"input": "package db\n\nimport (\n\t\"time\"\n\n\t\"github.com/boltdb/bolt\"\n\t\"github.com/pkg/errors\"\n)\n\nconst updateSnapshotHistoryBuckets = \"updateSnapshotHistory\"\n\n\n\nfunc RecordChangeIDWasEntered(changeID string, db *bolt.DB) error {\n\treturn db.Update(func(tx *bolt.Tx) error {\n\n\t\tb := tx.Bucket([]byte(updateSnapshotHistoryBuckets))\n\t\tif b == nil {\n\t\t\treturn errors.New(\"propertyNameBucket bucket not found\")\n\t\t}\n\n\t\tif value := b.Get([]byte(changeID)); value != nil {\n\t\t\treturn errors.New(\"previous entry time exists for changeID\")\n\t\t}\n\n\t\tnowJSON, err := time.Now().MarshalBinary()\n\t\tif err != nil {\n\t\t\treturn errors.New(\"failed to marshal time.Now to json\")\n\t\t}\n\t\tb.Put([]byte(changeID), nowJSON)\n\n\t\treturn nil\n\t})\n}\n\n\n\n\nfunc UpdateWasEntered(changeID string, db *bolt.DB) (bool, error) ", "output": "{\n\tentered := false\n\n\treturn entered, db.View(func(tx *bolt.Tx) error {\n\n\t\tb := tx.Bucket([]byte(updateSnapshotHistoryBuckets))\n\t\tif b == nil {\n\t\t\treturn errors.New(\"propertyNameBucket bucket not found\")\n\t\t}\n\n\t\tvalue := b.Get([]byte(changeID))\n\t\tentered = value != nil\n\t\treturn nil\n\t})\n}"} {"input": "package engine\n\nimport (\n\t\"time\"\n\n\t\"github.com/aws/amazon-ecs-agent/agent/api\"\n)\n\n\n\ntype impossibleTransitionError struct {\n\tstate api.ContainerStatus\n}\n\nfunc (err *impossibleTransitionError) Error() string {\n\treturn \"Cannot transition to \" + err.state.String()\n}\nfunc (err *impossibleTransitionError) ErrorName() string { return \"ImpossibleStateTransitionError\" }\n\ntype DockerTimeoutError struct {\n\tduration time.Duration\n\ttransition string\n}\n\nfunc (err *DockerTimeoutError) Error() string {\n\treturn \"Could not transition to \" + err.transition + \"; timed out after waiting \" + err.duration.String()\n}\nfunc (err *DockerTimeoutError) ErrorName() string { return \"DockerTimeoutError\" }\n\ntype ContainerVanishedError struct{}\n\n\nfunc (err ContainerVanishedError) ErrorName() string { return \"ContainerVanishedError\" }\n\ntype CannotXContainerError struct {\n\ttransition string\n\tmsg string\n}\n\nfunc (err CannotXContainerError) Error() string { return err.msg }\nfunc (err CannotXContainerError) ErrorName() string {\n\treturn \"Cannot\" + err.transition + \"ContainerError\"\n}\n\ntype OutOfMemoryError struct{}\n\nfunc (err OutOfMemoryError) Error() string { return \"Container killed due to memory usage\" }\nfunc (err OutOfMemoryError) ErrorName() string { return \"OutOfMemoryError\" }\n\n\ntype DockerStateError struct {\n\tdockerError string\n\tname string\n}\n\nfunc NewDockerStateError(err string) DockerStateError {\n\treturn DockerStateError{\n\t\tdockerError: err,\n\t\tname: \"DockerStateError\",\n\t}\n}\n\nfunc (err DockerStateError) Error() string {\n\treturn err.dockerError\n}\nfunc (err DockerStateError) ErrorName() string {\n\treturn err.name\n}\n\nfunc (err ContainerVanishedError) Error() string ", "output": "{ return \"No container matching saved ID found\" }"} {"input": "package gconv_test\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\ntype testStruct struct {\n\tId int\n\tName string\n}\n\nvar ptr = []*testStruct{\n\t{\n\t\tId: 1,\n\t\tName: \"test1\",\n\t},\n\t{\n\t\tId: 2,\n\t\tName: \"test2\",\n\t},\n}\n\nfunc init() {\n\tfor i := 1; i <= 1000; i++ {\n\t\tptr = append(ptr, &testStruct{\n\t\t\tId: 1,\n\t\t\tName: \"test1\",\n\t\t})\n\t}\n}\n\nfunc Benchmark_Reflect_ValueOf(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr)\n\t}\n}\n\nfunc Benchmark_Reflect_ValueOf_Kind(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr).Kind()\n\t}\n}\n\n\n\nfunc Benchmark_Reflect_ValueOf_Len(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr).Len()\n\t}\n}\n\nfunc Benchmark_Reflect_ValueOf_Interface(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr).Interface()\n\t}\n}"} {"input": "package config\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/dnephin/configtf\"\n\tpth \"github.com/dnephin/configtf/path\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype ComposeConfig struct {\n\tFiles []string\n\tProject string `config:\"required\"`\n\tStopGrace int\n\tDependent\n\tAnnotations\n}\n\n\nfunc (c *ComposeConfig) StopGraceString() string {\n\treturn strconv.Itoa(c.StopGrace)\n}\n\n\nfunc (c *ComposeConfig) Validate(path pth.Path, config *Config) *pth.Error {\n\treturn nil\n}\n\nfunc (c *ComposeConfig) String() string {\n\treturn fmt.Sprintf(\"Run Compose project %q from: %v\",\n\t\tc.Project, strings.Join(c.Files, \", \"))\n}\n\n\nfunc (c *ComposeConfig) Resolve(resolver Resolver) (Resource, error) {\n\tconf := *c\n\tvar err error\n\tconf.Files, err = resolver.ResolveSlice(c.Files)\n\tif err != nil {\n\t\treturn &conf, err\n\t}\n\tconf.Project, err = resolver.Resolve(c.Project)\n\treturn &conf, err\n}\n\n\n\nfunc init() {\n\tRegisterResource(\"compose\", composeFromConfig)\n}\n\nfunc composeFromConfig(name string, values map[string]interface{}) (Resource, error) ", "output": "{\n\tcompose := &ComposeConfig{Project: \"{unique}\", StopGrace: 5}\n\treturn compose, configtf.Transform(name, values, compose)\n}"} {"input": "package iso20022\n\n\ntype AutomatedTellerMachine6 struct {\n\n\tIdentification *Max35Text `xml:\"Id\"`\n\n\tAdditionalIdentification *Max35Text `xml:\"AddtlId,omitempty\"`\n\n\tSequenceNumber *Max35Text `xml:\"SeqNb,omitempty\"`\n\n\tLocation *PostalAddress17 `xml:\"Lctn,omitempty\"`\n\n\tLocationCategory *TransactionEnvironment2Code `xml:\"LctnCtgy,omitempty\"`\n\n\tEquipment *ATMEquipment1 `xml:\"Eqpmnt,omitempty\"`\n}\n\nfunc (a *AutomatedTellerMachine6) SetIdentification(value string) {\n\ta.Identification = (*Max35Text)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) SetAdditionalIdentification(value string) {\n\ta.AdditionalIdentification = (*Max35Text)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) SetSequenceNumber(value string) {\n\ta.SequenceNumber = (*Max35Text)(&value)\n}\n\n\n\nfunc (a *AutomatedTellerMachine6) SetLocationCategory(value string) {\n\ta.LocationCategory = (*TransactionEnvironment2Code)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) AddEquipment() *ATMEquipment1 {\n\ta.Equipment = new(ATMEquipment1)\n\treturn a.Equipment\n}\n\nfunc (a *AutomatedTellerMachine6) AddLocation() *PostalAddress17 ", "output": "{\n\ta.Location = new(PostalAddress17)\n\treturn a.Location\n}"} {"input": "package datascience\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"io\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetModelArtifactContentRequest struct {\n\n\tModelId *string `mandatory:\"true\" contributesTo:\"path\" name:\"modelId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRange *string `mandatory:\"false\" contributesTo:\"header\" name:\"range\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetModelArtifactContentRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request GetModelArtifactContentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetModelArtifactContentRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetModelArtifactContentResponse struct {\n\n\tRawResponse *http.Response\n\n\tContent io.ReadCloser `presentIn:\"body\" encoding:\"binary\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n\n\tContentLength *int64 `presentIn:\"header\" name:\"content-length\"`\n\n\tContentDisposition *string `presentIn:\"header\" name:\"content-disposition\"`\n\n\tContentMd5 *string `presentIn:\"header\" name:\"content-md5\"`\n\n\tLastModified *common.SDKTime `presentIn:\"header\" name:\"last-modified\"`\n}\n\nfunc (response GetModelArtifactContentResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetModelArtifactContentResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetModelArtifactContentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package monebot\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype State struct {\n\tChat int64 `bson:\"chat\"`\n\tUser int `bson:\"user\"`\n\tWaiting WaitingState `bson:\"waiting,omitempty\"`\n\tLastUpdate time.Time `bson:\"lastUpdate\"`\n}\n\nfunc NewWaitingState(chat int64, user int, w WaitingState) State {\n\treturn State{Chat: chat, User: user, Waiting: w, LastUpdate: time.Now()}\n}\n\ntype WaitingState struct {\n\tForCommand bool `bson:\"forCommand,omitempty\"`\n\tPack string `bson:\"pack,omitempty\"`\n\tCommand string `bson:\"command,omitempty\"`\n}\n\n\ntype Answer struct {\n\tText string `bson:\"text,omitempty\"`\n\tNumParams int `bson:\"numParams\"`\n\tParse string `bson:\"parseMode,omitempty\"`\n\tSticker string `bson:\"sticker,omitempty\"`\n}\n\nconst (\n\tParseMarkdown = \"Markdown\"\n\tParseHTML = \"HTML\"\n)\n\n\ntype Command struct {\n\tPack string `bson:\"pack\"`\n\tName string `bson:\"name\"`\n\tAnswer Answer `bson:\"answer\"`\n\tTime time.Time `bson:\"time\"`\n\tCreator string `bson:\"creator,omitempty\"`\n\tNumChanged int `bson:\"numChanged,omitempty\"`\n}\n\n\n\n\n\ntype Pack struct {\n\tName string `bson:\"name\"`\n\tChats []int64 `bson:\"chats\"`\n}\n\nfunc (c Command) FullName() string ", "output": "{\n\treturn fmt.Sprintf(\"%s.%s\", c.Pack, c.Name)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSOpsWorksApp_Source struct {\n\n\tPassword string `json:\"Password,omitempty\"`\n\n\tRevision string `json:\"Revision,omitempty\"`\n\n\tSshKey string `json:\"SshKey,omitempty\"`\n\n\tType string `json:\"Type,omitempty\"`\n\n\tUrl string `json:\"Url,omitempty\"`\n\n\tUsername string `json:\"Username,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSOpsWorksApp_Source) AWSCloudFormationType() string {\n\treturn \"AWS::OpsWorks::App.Source\"\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\n\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSOpsWorksApp_Source) Metadata() map[string]interface{} ", "output": "{\n\treturn r._metadata\n}"} {"input": "package gtk\n\n\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n\n\t\"github.com/untoldwind/amintk/gdk\"\n)\n\n\ntype Image struct {\n\tWidget\n}\n\n\n\n\nfunc (v *Image) native() *C.GtkImage {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn (*C.GtkImage)(v.Native())\n}\n\n\nfunc ImageNewFromIconName(iconName string, size IconSize) *Image {\n\tcstr := C.CString(iconName)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_image_new_from_icon_name((*C.gchar)(cstr),\n\t\tC.GtkIconSize(size))\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\n\nfunc ImageNewFromPixbuf(pixbuf *gdk.Pixbuf) *Image {\n\tptr := (*C.GdkPixbuf)(pixbuf.Native())\n\tc := C.gtk_image_new_from_pixbuf(ptr)\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\nfunc wrapImage(p unsafe.Pointer) *Image {\n\tif widget := wrapWidget(p); widget != nil {\n\t\treturn &Image{Widget: *widget}\n\t}\n\treturn nil\n}\n\n\nfunc (v *Image) Clear() {\n\tC.gtk_image_clear(v.native())\n}\n\n\nfunc (v *Image) SetFromPixbuf(pixbuf *gdk.Pixbuf) {\n\tpbptr := (*C.GdkPixbuf)(pixbuf.Native())\n\tC.gtk_image_set_from_pixbuf(v.native(), pbptr)\n}\n\nfunc ImageNew() *Image ", "output": "{\n\tc := C.gtk_image_new()\n\treturn wrapImage(unsafe.Pointer(c))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\n\t\"github.com/PalmStoneGames/polymer\"\n)\n\nfunc init() {\n\tpolymer.Register(\"name-tag\", &NameTag{})\n}\n\ntype NameTag struct {\n\t*polymer.Proto\n\n\tID int64 `polymer:\"bind\"`\n\tName string `polymer:\"bind\"`\n\tNameChange chan *polymer.Event `polymer:\"handler\"`\n}\n\nfunc (n *NameTag) Created() {\n\tn.ID = rand.Int63()\n\n\tgo func() {\n\t\tfor _ = range n.NameChange {\n\t\t\tfmt.Printf(\"%v: HandleNameChange event. Name = %v\\n\", n.ID, n.Name)\n\t\t}\n\t}()\n}\n\n\n\nfunc main() {}\n\nfunc (n *NameTag) Ready() ", "output": "{\n\tfmt.Printf(\"%v: Initial Name = %v\\n\", n.ID, n.Name)\n}"} {"input": "package logrus\n\nimport (\n\t\"io\"\n\t\"sync\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/golang/protobuf/proto\"\n\n\t\"go.pedge.io/protolog\"\n)\n\nvar (\n\tglobalPusherOptions = PusherOptions{}\n\tglobalLoggerOptions = protolog.LoggerOptions{}\n\tglobalLock = &sync.Mutex{}\n)\n\n\ntype PusherOptions struct {\n\tOut io.Writer\n\tHooks []logrus.Hook\n\tFormatter logrus.Formatter\n\tEnableID bool\n\tDisableContexts bool\n\tUnmarshalFunc func([]byte, proto.Message) error\n}\n\n\nfunc NewPusher(options PusherOptions) protolog.Pusher {\n\treturn newPusher(options)\n}\n\n\nfunc SetPusherOptions(options PusherOptions) {\n\tglobalLock.Lock()\n\tdefer globalLock.Unlock()\n\tglobalPusherOptions = options\n\tregister()\n}\n\n\nfunc SetLoggerOptions(options protolog.LoggerOptions) {\n\tglobalLock.Lock()\n\tdefer globalLock.Unlock()\n\tglobalLoggerOptions = options\n\tregister()\n}\n\n\n\n\nfunc register() {\n\tprotolog.SetLogger(protolog.NewLogger(NewPusher(globalPusherOptions), globalLoggerOptions))\n}\n\nfunc Register() ", "output": "{\n\tglobalLock.Lock()\n\tdefer globalLock.Unlock()\n\tregister()\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListLocalPeeringGatewaysRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tVcnId *string `mandatory:\"false\" contributesTo:\"query\" name:\"vcnId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListLocalPeeringGatewaysRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListLocalPeeringGatewaysRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request ListLocalPeeringGatewaysRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ListLocalPeeringGatewaysRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListLocalPeeringGatewaysResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []LocalPeeringGateway `presentIn:\"body\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response ListLocalPeeringGatewaysResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response ListLocalPeeringGatewaysResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package constants\n\nimport (\n\t\"GoVM/chapter5-instructions/base\"\n\t\"GoVM/chapter4-rtdt\"\n)\n\n\ntype BIPUSH struct {\n\tval int8\n}\n\nfunc (self *BIPUSH) FetchOperands(reader *base.BytecodeReader) {\n\tself.val = reader.ReadInt8()\n}\n\n\n\n\ntype SIPUSH struct {\n\tval int16\n}\n\nfunc (self *SIPUSH) FetchOperands(reader *base.BytecodeReader) {\n\tself.val = reader.ReadInt16()\n}\n\nfunc (self *SIPUSH) Execute(frame *chapter4_rtdt.Frame) {\n\ti := int32(self.val)\n\tframe.OperandStack().PushInt(i)\n}\n\nfunc (self *BIPUSH) Execute(frame *chapter4_rtdt.Frame) ", "output": "{\n\ti := int32(self.val)\n\tframe.OperandStack().PushInt(i)\n}"} {"input": "package clearbit\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n\n\ntype apiError struct {\n\tErrors []ErrorDetail `json:\"error\"`\n}\n\n\ntype ErrorDetail struct {\n\tType string `json:\"type\"`\n\tMessage string `json:\"message\"`\n}\n\n\ntype ErrorDetailWrapper struct {\n\tError ErrorDetail `json:\"error\"`\n}\n\n\nfunc (e apiError) Error() string {\n\tif len(e.Errors) > 0 {\n\t\terr := e.Errors[0]\n\t\treturn fmt.Sprintf(\"clearbit: %s %v\", err.Type, err.Message)\n\t}\n\treturn \"\"\n}\n\n\n\n\n\n\n\n\n\nfunc (e *apiError) Empty() bool {\n\treturn len(e.Errors) == 0\n}\n\n\n\n\nfunc relevantError(httpError error, ae apiError) error {\n\tif httpError != nil {\n\t\treturn httpError\n\t}\n\tif ae.Empty() {\n\t\treturn nil\n\t}\n\treturn ae\n}\n\nfunc (e *apiError) UnmarshalJSON(b []byte) (err error) ", "output": "{\n\terrorDetail, errors := ErrorDetailWrapper{}, []ErrorDetail{}\n\tif err = json.Unmarshal(b, &errors); err == nil {\n\t\te.Errors = errors\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(b, &errorDetail); err == nil {\n\t\terrors = append(errors, errorDetail.Error)\n\t\te.Errors = errors\n\t\treturn\n\t}\n\n\treturn err\n}"} {"input": "package vip\n\nimport (\n\t\"context\"\n\t\"net/url\"\n\t\"strconv\"\n\n\t\"go-common/app/interface/main/app-view/conf\"\n\t\"go-common/library/ecode\"\n\thttpx \"go-common/library/net/http/blademaster\"\n\n\t\"github.com/pkg/errors\"\n)\n\nconst (\n\t_vipActive = \"/internal/v1/notice/active\"\n)\n\n\ntype Dao struct {\n\tclient *httpx.Client\n\tvipActiveURL string\n}\n\n\n\n\n\nfunc (d *Dao) VIPActive(c context.Context, subID int) (msg string, err error) {\n\tparams := url.Values{}\n\tparams.Set(\"subId\", strconv.Itoa(subID))\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t\tData string `json:\"data\"`\n\t}\n\tif err = d.client.Get(c, d.vipActiveURL, \"\", params, &res); err != nil {\n\t\treturn\n\t}\n\tif res.Code != ecode.OK.Code() {\n\t\terr = errors.Wrap(ecode.Int(res.Code), d.vipActiveURL+\"?\"+params.Encode())\n\t\treturn\n\t}\n\tmsg = res.Data\n\treturn\n}\n\nfunc New(c *conf.Config) (d *Dao) ", "output": "{\n\td = &Dao{\n\t\tclient: httpx.NewClient(c.HTTPWrite),\n\t\tvipActiveURL: c.Host.VIP + _vipActive,\n\t}\n\treturn\n}"} {"input": "package cgo\n\nimport (\n\t\"testing\"\n)\n\nfunc TestWrite(t *testing.T) {\n\ttestWrite(t)\n}\n\n\n\nfunc TestRead(t *testing.T) ", "output": "{\n\ttestRead(t)\n}"} {"input": "package signer\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc buildRequest(serviceName, region, body string) (*http.Request, io.ReadSeeker) {\n\tendpoint := \"https://\" + serviceName + \".\" + region + \".amazonaws.com\"\n\treader := strings.NewReader(body)\n\treq, _ := http.NewRequest(\"POST\", endpoint, reader)\n\treq.URL.Opaque = \"//example.org/bucket/key-._~,!@#$%^&*()\"\n\treq.Header.Add(\"X-Amz-Target\", \"prefix.Operation\")\n\treq.Header.Add(\"Content-Type\", \"application/x-amz-json-1.0\")\n\treq.Header.Add(\"Content-Length\", string(len(body)))\n\treq.Header.Add(\"X-Amz-Meta-Other-Header\", \"some-value=!@#$%^&* (+)\")\n\treq.Header.Add(\"X-Amz-Meta-Other-Header_With_Underscore\", \"some-value=!@#$%^&* (+)\")\n\treq.Header.Add(\"X-amz-Meta-Other-Header_With_Underscore\", \"some-value=!@#$%^&* (+)\")\n\treturn req, reader\n}\n\nfunc TestRequestHost(t *testing.T) ", "output": "{\n\treq, _ := buildRequest(\"dynamodb\", \"us-east-1\", \"{}\")\n\treq.URL.RawQuery = \"Foo=z&Foo=o&Foo=m&Foo=a\"\n\treq.Host = \"myhost\"\n\tcanonicalHeaders := getCanonicalHeaders(*req, v4IgnoredHeaders)\n\n\tif !strings.Contains(canonicalHeaders, \"host:\"+req.Host) {\n\t\tt.Errorf(\"canonical host header invalid\")\n\t}\n}"} {"input": "package multigz\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestIsMultiGzip(t *testing.T) ", "output": "{\n\tf, err := os.Open(\"testdata/divina.txt.gz\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\tif IsProbablyMultiGzip(f, DefaultPeekSize) {\n\t\tt.Error(\"divina.txt.gz detected as multigz but it isn't\")\n\t}\n\n\tf2, err := os.Open(\"testdata/divina2.txt.gz\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\tif !IsProbablyMultiGzip(f2, DefaultPeekSize) {\n\t\tt.Error(\"divina2.txt.gz not detected as multigz but it is\")\n\t}\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/xeb/etcdrepl/third_party/github.com/codegangsta/cli\"\n\t\"github.com/xeb/etcdrepl/third_party/github.com/coreos/go-etcd/etcd\"\n)\n\nfunc NewLsCommand() cli.Command {\n\treturn cli.Command{\n\t\tName:\t\"ls\",\n\t\tUsage:\t\"retrieve a directory\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.BoolFlag{\"recursive\", \"returns all values for key and child keys\"},\n\t\t},\n\t\tAction: func(c *cli.Context) {\n\t\t\thandleLs(c, lsCommandFunc)\n\t\t},\n\t}\n}\n\n\nfunc handleLs(c *cli.Context, fn handlerFunc) {\n\thandlePrint(c, fn, printLs)\n}\n\n\n\n\n\n\nfunc lsCommandFunc(c *cli.Context, client *etcd.Client) (*etcd.Response, error) {\n\tkey := \"/\"\n\tif len(c.Args()) != 0 {\n\t\tkey = c.Args()[0]\n\t}\n\trecursive := c.Bool(\"recursive\")\n\n\treturn client.Get(key, false, recursive)\n}\n\n\nfunc rPrint(n *etcd.Node) {\n\tfmt.Println(n.Key)\n\tfor _, node := range n.Nodes {\n\t\trPrint(&node)\n\t}\n}\n\nfunc printLs(resp *etcd.Response, format string) ", "output": "{\n\tif !resp.Node.Dir {\n\t\tfmt.Println(resp.Node.Key)\n\t}\n\tfor _, node := range resp.Node.Nodes {\n\t\trPrint(&node)\n\t}\n}"} {"input": "package downloader\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/WhaleCoinOrg/WhaleCoin/core/types\"\n)\n\n\ntype peerDropFn func(id string)\n\n\ntype dataPack interface {\n\tPeerId() string\n\tItems() int\n\tStats() string\n}\n\n\ntype headerPack struct {\n\tpeerId string\n\theaders []*types.Header\n}\n\nfunc (p *headerPack) PeerId() string { return p.peerId }\nfunc (p *headerPack) Items() int { return len(p.headers) }\nfunc (p *headerPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.headers)) }\n\n\ntype bodyPack struct {\n\tpeerId string\n\ttransactions [][]*types.Transaction\n\tuncles [][]*types.Header\n}\n\nfunc (p *bodyPack) PeerId() string { return p.peerId }\nfunc (p *bodyPack) Items() int {\n\tif len(p.transactions) <= len(p.uncles) {\n\t\treturn len(p.transactions)\n\t}\n\treturn len(p.uncles)\n}\nfunc (p *bodyPack) Stats() string { return fmt.Sprintf(\"%d:%d\", len(p.transactions), len(p.uncles)) }\n\n\ntype receiptPack struct {\n\tpeerId string\n\treceipts [][]*types.Receipt\n}\n\nfunc (p *receiptPack) PeerId() string { return p.peerId }\nfunc (p *receiptPack) Items() int { return len(p.receipts) }\nfunc (p *receiptPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.receipts)) }\n\n\ntype statePack struct {\n\tpeerId string\n\tstates [][]byte\n}\n\nfunc (p *statePack) PeerId() string { return p.peerId }\nfunc (p *statePack) Items() int { return len(p.states) }\n\n\nfunc (p *statePack) Stats() string ", "output": "{ return fmt.Sprintf(\"%d\", len(p.states)) }"} {"input": "package storage\n\nimport (\n\t\"fmt\"\n)\n\ntype NeedsInit struct {\n\tmsg string\n}\n\n\n\nfunc (s *NeedsInit) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"The journal needs to be inited because %s\", s.msg)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSApplicationAutoScalingScalableTarget_ScheduledAction struct {\n\n\tEndTime string `json:\"EndTime,omitempty\"`\n\n\tScalableTargetAction *AWSApplicationAutoScalingScalableTarget_ScalableTargetAction `json:\"ScalableTargetAction,omitempty\"`\n\n\tSchedule string `json:\"Schedule,omitempty\"`\n\n\tScheduledActionName string `json:\"ScheduledActionName,omitempty\"`\n\n\tStartTime string `json:\"StartTime,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) AWSCloudFormationType() string {\n\treturn \"AWS::ApplicationAutoScaling::ScalableTarget.ScheduledAction\"\n}\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\n\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) Metadata() map[string]interface{} ", "output": "{\n\treturn r._metadata\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\tasp \"golang.org/x/exp/aspectgo/aspect\"\n)\n\n\ntype ExampleAspect struct {\n}\n\n\nfunc (a *ExampleAspect) Pointcut() asp.Pointcut {\n\ts := \"fmt\\\\.Print.*\"\n\treturn asp.NewCallPointcutFromRegexp(s)\n}\n\n\n\n\nfunc (a *ExampleAspect) Advice(ctx asp.Context) []interface{} ", "output": "{\n\targs := ctx.Args()\n\tfmt.Printf(\"Hooking (args=%v)\\n\", args)\n\tres := ctx.Call(args)\n\treturn res\n}"} {"input": "package acme\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/sha256\"\n\t\"crypto/tls\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"log\"\n)\n\ntype tlsSNIChallenge struct {\n\tjws *jws\n\tvalidate validateFunc\n\tprovider ChallengeProvider\n}\n\nfunc (t *tlsSNIChallenge) Solve(chlng challenge, domain string) error {\n\n\tlogf(\"[INFO][%s] acme: Trying to solve TLS-SNI-01\", domain)\n\n\tkeyAuth, err := getKeyAuthorization(chlng.Token, &t.jws.privKey.PublicKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif t.provider == nil {\n\t\tt.provider = &tlsSNIChallengeServer{}\n\t}\n\n\terr = t.provider.Present(domain, chlng.Token, keyAuth)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[%s] error presenting token: %v\", domain, err)\n\t}\n\tdefer func() {\n\t\terr := t.provider.CleanUp(domain, chlng.Token, keyAuth)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[%s] error cleaning up: %v\", domain, err)\n\t\t}\n\t}()\n\treturn t.validate(t.jws, domain, chlng.URI, challenge{Resource: \"challenge\", Type: chlng.Type, Token: chlng.Token, KeyAuthorization: keyAuth})\n}\n\n\n\n\nfunc TLSSNI01ChallengeCert(keyAuth string) (tls.Certificate, error) ", "output": "{\n\ttempPrivKey, err := generatePrivateKey(rsakey, 2048)\n\tif err != nil {\n\t\treturn tls.Certificate{}, err\n\t}\n\trsaPrivKey := tempPrivKey.(*rsa.PrivateKey)\n\trsaPrivPEM := pemEncode(rsaPrivKey)\n\n\tzBytes := sha256.Sum256([]byte(keyAuth))\n\tz := hex.EncodeToString(zBytes[:sha256.Size])\n\tdomain := fmt.Sprintf(\"%s.%s.acme.invalid\", z[:32], z[32:])\n\ttempCertPEM, err := generatePemCert(rsaPrivKey, domain)\n\tif err != nil {\n\t\treturn tls.Certificate{}, err\n\t}\n\n\tcertificate, err := tls.X509KeyPair(tempCertPEM, rsaPrivPEM)\n\tif err != nil {\n\t\treturn tls.Certificate{}, err\n\t}\n\n\treturn certificate, nil\n}"} {"input": "package store\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype Row struct {\n\tData []string\n}\n\nfunc ReadData(path string) []byte {\n\td, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn []byte(``)\n\t}\n\n\treturn d\n}\n\n\n\nfunc WriteData(path string, data []byte) {\n\tf, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer f.Close()\n\n\t_, err = f.Write(data)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n\nfunc WriteRows(path string, rows *[]Row, delimeter string) {\n\tf, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0644)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer f.Close()\n\n\tfor _, r := range *rows {\n\t\t_, err = f.WriteString(strings.Join(r.Data, delimeter))\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n}\n\nfunc ReadRows(path, delimiter string) *[]Row ", "output": "{\n\tf, _ := os.Open(path)\n\n\tdefer f.Close()\n\n\trows := []Row{}\n\ts := bufio.NewScanner(f)\n\ts.Split(bufio.ScanLines)\n\n\tfor s.Scan() {\n\t\tdata := strings.Split(s.Text(), delimiter)\n\t\tr := &Row{Data: data}\n\t\trows = append(rows, *r)\n\t}\n\n\treturn &rows\n}"} {"input": "package iso20022\n\n\ntype HighFrequencyTradingProfile1 struct {\n\n\tDate *ISODate `xml:\"Dt,omitempty\"`\n\n\tSettlementFrequency *SettlementFrequency1Choice `xml:\"SttlmFrqcy,omitempty\"`\n\n\tConsolidationType *ConsolidationType1Choice `xml:\"CnsldtnTp,omitempty\"`\n}\n\nfunc (h *HighFrequencyTradingProfile1) SetDate(value string) {\n\th.Date = (*ISODate)(&value)\n}\n\nfunc (h *HighFrequencyTradingProfile1) AddSettlementFrequency() *SettlementFrequency1Choice {\n\th.SettlementFrequency = new(SettlementFrequency1Choice)\n\treturn h.SettlementFrequency\n}\n\n\n\nfunc (h *HighFrequencyTradingProfile1) AddConsolidationType() *ConsolidationType1Choice ", "output": "{\n\th.ConsolidationType = new(ConsolidationType1Choice)\n\treturn h.ConsolidationType\n}"} {"input": "package parser\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestValidPodFromSentinelConfig(t *testing.T) {\n\t_, err := ParseSentinelConfig(\"sentinel.conf\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n}\n\nfunc TestBadDirectives(t *testing.T) {\n\tsconf, err := ParseSentinelConfig(\"sentinel.conf\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n\tif len(sconf.BadDirectives) == 0 {\n\t\tt.Error(fmt.Errorf(\"Should have had bad directives, had none.\"))\n\t\tt.Fail()\n\t}\n}\n\n\nfunc TestPodKnownSlaves(t *testing.T) {\n\tsconf, err := ParseSentinelConfig(\"sentinel.conf\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n\tpod, err := sconf.GetPod(\"pod1\")\n\tif len(pod.KnownSlaves) != 2 {\n\t\tt.Error(fmt.Errorf(\"Mismatched KnownSlaves. Expected 2, got %d\", len(pod.KnownSlaves)))\n\t\tt.Fail()\n\t}\n}\nfunc TestPodKnownSentinels(t *testing.T) {\n\tsconf, err := ParseSentinelConfig(\"sentinel.conf\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n\tpod, err := sconf.GetPod(\"pod1\")\n\tif len(pod.KnownSentinels) != 2 {\n\t\tt.Error(fmt.Errorf(\"Mismatched KnownSentinels. Expected 2, got %d\", len(pod.KnownSentinels)))\n\t\tfmt.Printf(\"pod: %+v\\n\", pod)\n\t\tt.Fail()\n\t}\n}\n\nfunc TestGetPod(t *testing.T) ", "output": "{\n\tsconf, err := ParseSentinelConfig(\"sentinel.conf\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n\tpod, err := sconf.GetPod(\"pod1\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n\tif pod.Name != \"pod1\" {\n\t\tt.Error(fmt.Errorf(\"retreived pod is not named 'pod1'\"))\n\t\tt.Fail()\n\t}\n}"} {"input": "package hashgraph\n\nimport (\n\t\"bytes\"\n\t\"sort\"\n\n\t\"github.com/mosaicnetworks/babble/src/crypto\"\n\t\"github.com/mosaicnetworks/babble/src/peers\"\n\t\"github.com/ugorji/go/codec\"\n)\n\n\ntype Frame struct {\n\tRound int \n\tPeers []*peers.Peer \n\tRoots map[string]*Root \n\tEvents []*FrameEvent \n\tPeerSets map[int][]*peers.Peer \n\tTimestamp int64 \n}\n\n\n\n\n\n\nfunc (f *Frame) Marshal() ([]byte, error) {\n\tb := new(bytes.Buffer)\n\tjh := new(codec.JsonHandle)\n\tjh.Canonical = true\n\tenc := codec.NewEncoder(b, jh)\n\n\tif err := enc.Encode(f); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b.Bytes(), nil\n}\n\n\nfunc (f *Frame) Unmarshal(data []byte) error {\n\tb := bytes.NewBuffer(data)\n\tjh := new(codec.JsonHandle)\n\tjh.Canonical = true\n\tdec := codec.NewDecoder(b, jh)\n\n\tif err := dec.Decode(f); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc (f *Frame) Hash() ([]byte, error) {\n\thashBytes, err := f.Marshal()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn crypto.SHA256(hashBytes), nil\n}\n\nfunc (f *Frame) SortedFrameEvents() []*FrameEvent ", "output": "{\n\tsorted := SortedFrameEvents{}\n\tfor _, r := range f.Roots {\n\t\tsorted = append(sorted, r.Events...)\n\t}\n\tsorted = append(sorted, f.Events...)\n\tsort.Sort(sorted)\n\treturn sorted\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gourd/goparser\"\n\t\"github.com/gourd/gourd/compile\"\n\t\"github.com/gourd/gourd/templates\"\n)\n\nfunc init() {\n\tt, err := templates.Asset(\"store/upperio.tpl\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttpls.Append(\"gen store:upperio\", string(t))\n\ttpls.AddDeps(\"gen store:upperio\", \"gen:general\")\n\ttpls.AddPrep(\"gen store:upperio\", func(in interface{}) (interface{}, error) {\n\t\tvar data map[string]interface{}\n\t\tvar f interface{}\n\t\tvar id *goparser.FieldSpec\n\t\tvar ok bool\n\n\t\tif data, ok = in.(compile.Context); !ok {\n\t\t\treturn in, fmt.Errorf(\"Unable to prepare. Incorrect data provided: %#v\", in)\n\t\t}\n\n\t\tif f, ok = data[\"Id\"]; !ok {\n\t\t\treturn in, fmt.Errorf(\"Unable to prepare. No Id found in given data: %#v\",\n\t\t\t\tdata)\n\t\t}\n\n\t\tif id, ok = f.(*goparser.FieldSpec); !ok {\n\t\t\treturn in, fmt.Errorf(\"Unable to prepare. Wrong Id type: %#v\", f)\n\t\t}\n\n\t\tdata[\"Id\"] = &UpperFieldSpec{\n\t\t\tid,\n\t\t}\n\t\treturn data, nil\n\t})\n}\n\n\n\ntype UpperFieldSpec struct {\n\t*goparser.FieldSpec\n}\n\n\nfunc (s UpperFieldSpec) IsString() bool {\n\treturn s.Type == \"string\"\n}\n\n\n\n\nfunc (s *UpperFieldSpec) IsInt() bool ", "output": "{\n\treturn s.Type == \"int\" || s.Type == \"uint\" ||\n\t\ts.Type == \"int32\" || s.Type == \"uint32\" ||\n\t\ts.Type == \"int64\" || s.Type == \"uint64\"\n}"} {"input": "package gridq\n\ntype byColRow []*WriteResponse\n\nfunc (p byColRow) Len() int { return len(p) }\n\nfunc (p byColRow) Less(i, j int) bool {\n\tif p[i].Col < p[j].Col {\n\t\treturn true\n\t} else if p[i].Col > p[j].Col {\n\t\treturn false\n\t} else {\n\t\treturn p[i].Row < p[j].Row\n\t}\n}\n\ntype byRowTimestamp []*ReadResponse\n\nfunc (p byRowTimestamp) Len() int { return len(p) }\nfunc (p byRowTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byRowTimestamp) Less(i, j int) bool {\n\tif p[i].Row < p[j].Row {\n\t\treturn true\n\t} else if p[i].Row > p[j].Row {\n\t\treturn false\n\t} else {\n\t\treturn p[i].State.Timestamp > p[j].State.Timestamp\n\t}\n}\n\ntype byTimestamp []*ReadResponse\n\nfunc (p byTimestamp) Len() int { return len(p) }\nfunc (p byTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byTimestamp) Less(i, j int) bool { return p[i].State.Timestamp < p[j].State.Timestamp }\n\nfunc (p byColRow) Swap(i, j int) ", "output": "{ p[i], p[j] = p[j], p[i] }"} {"input": "package lbaas\n\nimport (\n\t\"testing\"\n\n\t\"github.com/gophercloud/gophercloud/acceptance/clients\"\n\t\"github.com/gophercloud/gophercloud/acceptance/tools\"\n\t\"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/lbaas/monitors\"\n)\n\n\n\nfunc TestMonitorsCRUD(t *testing.T) {\n\tclient, err := clients.NewNetworkV2Client()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create a network client: %v\", err)\n\t}\n\n\tmonitor, err := CreateMonitor(t, client)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create monitor: %v\", err)\n\t}\n\tdefer DeleteMonitor(t, client, monitor.ID)\n\n\ttools.PrintResource(t, monitor)\n\n\tupdateOpts := monitors.UpdateOpts{\n\t\tDelay: 999,\n\t}\n\n\t_, err = monitors.Update(client, monitor.ID, updateOpts).Extract()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to update monitor: %v\")\n\t}\n\n\tnewMonitor, err := monitors.Get(client, monitor.ID).Extract()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to get monitor: %v\")\n\t}\n\n\ttools.PrintResource(t, newMonitor)\n}\n\nfunc TestMonitorsList(t *testing.T) ", "output": "{\n\tclient, err := clients.NewNetworkV2Client()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create a network client: %v\", err)\n\t}\n\n\tallPages, err := monitors.List(client, monitors.ListOpts{}).AllPages()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to list monitors: %v\", err)\n\t}\n\n\tallMonitors, err := monitors.ExtractMonitors(allPages)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to extract monitors: %v\", err)\n\t}\n\n\tfor _, monitor := range allMonitors {\n\t\ttools.PrintResource(t, monitor)\n\t}\n}"} {"input": "package emptydisk\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"path\"\n\t\"strconv\"\n\n\t\"kubevirt.io/kubevirt/pkg/api/v1\"\n)\n\nvar EmptyDiskBaseDir = \"/var/run/libvirt/empty-disks/\"\n\n\n\nfunc FilePathForVolumeName(volumeName string) string {\n\treturn path.Join(EmptyDiskBaseDir, volumeName+\".qcow2\")\n}\n\nfunc CreateTemporaryDisks(vm *v1.VirtualMachine) error ", "output": "{\n\n\tfor _, volume := range vm.Spec.Volumes {\n\n\t\tif volume.EmptyDisk != nil {\n\t\t\tsize := strconv.FormatInt(volume.EmptyDisk.Capacity.ToDec().ScaledValue(0), 10)\n\t\t\tfile := FilePathForVolumeName(volume.Name)\n\t\t\tif err := os.MkdirAll(EmptyDiskBaseDir, 0777); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif _, err := os.Stat(file); os.IsNotExist(err) {\n\t\t\t\tif err := exec.Command(\"qemu-img\", \"create\", \"-f\", \"qcow2\", file, size).Run(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else if err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package controllers\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"html\"\n\t\"html/template\"\n\t\"github.com/stevenandrewcarter/gouter/models\"\n)\n\n\ntype Page struct {\n\tRoutes []models.Route\n\tMessageState string\n\tMessage string\n}\n\n\nfunc index(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"Administration: Handling '%v' Request to: '%v\", r.Method, html.EscapeString(r.URL.Path))\n\tmessage, messageState := deleteRequest(r)\n\tmessage, messageState = createRequest(r)\n\tresult := models.LoadRoutes()\n\tpage := &Page{Routes: result, Message: message, MessageState: messageState}\n\tt := template.Must(template.ParseGlob(\"tmpl/*.html\"))\n\tt.ExecuteTemplate(w, \"indexPage\", page)\n}\n\n\n\n\n\nfunc createRequest(r *http.Request) (string, string) {\n\tmessage := \"\"\n\tmessageState := \"\"\n\tif r.Method == \"POST\" {\n\t\tr.ParseForm()\n\t\tparams := r.Form\n\t\tlog.Printf(\"Administration: Creating new route '%v', Params: (Description: '%v', From: '%v', To: '%v'\", params[\"name\"][0], params[\"description\"][0], params[\"from\"][0], params[\"to\"][0])\n\t\tif models.CreateRoute(models.Route{params[\"description\"][0], params[\"name\"][0], params[\"from\"][0], params[\"to\"][0]}) {\n\t\t\tmessage = \"Route succesfully created!\"\n\t\t\tmessageState = \"success\"\n\t\t} else {\n\t\t\tmessage = \"Could not create the route. A route with the same name already exists!\"\n\t\t\tmessageState = \"warning\"\n\t\t}\n\t}\n\treturn message, messageState\n}\n\nfunc deleteRequest(r *http.Request) (string, string) ", "output": "{\n\tmessage := \"\"\n\tmessageState := \"\"\n\tquery := r.URL.Query()\n\tif len(query[\"name\"]) != 0 && len(query[\"action\"]) != 0 && query[\"action\"][0] == \"delete\" {\n\t\tlog.Printf(\"Administration: Deleting '%v'\", query[\"name\"][0])\n\t\tif models.DeleteRoute(query[\"name\"][0]) {\n\t\t\tmessage = \"Route succesfully deleted!\"\n\t\t\tmessageState = \"success\"\n\t\t} else {\n\t\t\tmessage = \"Could not delete the route!\"\n\t\t\tmessageState = \"warning\"\n\t\t}\n\t}\n\treturn message, messageState\n}"} {"input": "package auto\n\nimport (\n\t\"sync\"\n\n\t\"github.com/miekg/coredns/middleware/file\"\n)\n\n\n\ntype Zones struct {\n\tZ map[string]*file.Zone \n\tnames []string \n\n\torigins []string \n\n\tsync.RWMutex\n}\n\n\nfunc (z *Zones) Names() []string {\n\tz.RLock()\n\tn := z.names\n\tz.RUnlock()\n\treturn n\n}\n\n\nfunc (z *Zones) Origins() []string {\n\treturn z.origins\n}\n\n\n\n\n\n\nfunc (z *Zones) Add(zo *file.Zone, name string) {\n\tz.Lock()\n\n\tif z.Z == nil {\n\t\tz.Z = make(map[string]*file.Zone)\n\t}\n\n\tz.Z[name] = zo\n\tz.names = append(z.names, name)\n\tzo.Reload()\n\n\tz.Unlock()\n}\n\n\nfunc (z *Zones) Remove(name string) {\n\tz.Lock()\n\n\tif zo, ok := z.Z[name]; ok && !zo.NoReload {\n\t\tzo.ReloadShutdown <- true\n\t}\n\n\tdelete(z.Z, name)\n\n\tz.names = []string{}\n\tfor n := range z.Z {\n\t\tz.names = append(z.names, n)\n\t}\n\n\tz.Unlock()\n}\n\nfunc (z *Zones) Zones(name string) *file.Zone ", "output": "{\n\tz.RLock()\n\tzo := z.Z[name]\n\tz.RUnlock()\n\treturn zo\n}"} {"input": "package b\n\nimport \"./a\"\n\nfunc F() {\n\ta.F()\n\ta.Fi()\n}\n\nfunc Fp() {\n\ta.Fp()\n\ta.Fip()\n}\n\nfunc Gp() {\n\ta.Gp()\n\ta.Gip()\n}\n\n\n\nfunc Hp() ", "output": "{\n\ta.Hp()\n\ta.Hip()\n}"} {"input": "package google\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype SpannerOperationWaiter struct {\n\tConfig *Config\n\tUserAgent string\n\tProject string\n\tCommonOperationWaiter\n}\n\n\n\nfunc createSpannerWaiter(config *Config, op map[string]interface{}, project, activity, userAgent string) (*SpannerOperationWaiter, error) {\n\tw := &SpannerOperationWaiter{\n\t\tConfig: config,\n\t\tUserAgent: userAgent,\n\t\tProject: project,\n\t}\n\tif err := w.CommonOperationWaiter.SetOp(op); err != nil {\n\t\treturn nil, err\n\t}\n\treturn w, nil\n}\n\n\nfunc spannerOperationWaitTimeWithResponse(config *Config, op map[string]interface{}, response *map[string]interface{}, project, activity, userAgent string, timeout time.Duration) error {\n\tw, err := createSpannerWaiter(config, op, project, activity, userAgent)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := OperationWait(w, activity, timeout, config.PollInterval); err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal([]byte(w.CommonOperationWaiter.Op.Response), response)\n}\n\nfunc spannerOperationWaitTime(config *Config, op map[string]interface{}, project, activity, userAgent string, timeout time.Duration) error {\n\tif val, ok := op[\"name\"]; !ok || val == \"\" {\n\t\treturn nil\n\t}\n\tw, err := createSpannerWaiter(config, op, project, activity, userAgent)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn OperationWait(w, activity, timeout, config.PollInterval)\n}\n\nfunc (w *SpannerOperationWaiter) QueryOp() (interface{}, error) ", "output": "{\n\tif w == nil {\n\t\treturn nil, fmt.Errorf(\"Cannot query operation, it's unset or nil.\")\n\t}\n\turl := fmt.Sprintf(\"%s%s\", w.Config.SpannerBasePath, w.CommonOperationWaiter.Op.Name)\n\n\treturn sendRequest(w.Config, \"GET\", w.Project, url, w.UserAgent, nil)\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/astaxie/beego\"\n\t\"github.com/dyzdyz010/MartianBlog/models\"\n)\n\ntype FrontController struct {\n\tbeego.Controller\n}\n\nfunc (this *FrontController) Articles() {\n\tvar articles []models.Article\n\n\tif status := this.GetString(\"status\"); status != \"\" {\n\t\tarticles = models.ArticlesByStatus(status)\n\t} else {\n\t\tarticles = models.AllArticles()\n\t}\n\n\tthis.Data[\"json\"] = articles\n\tthis.ServeJson()\n}\n\n\n\nfunc (this *FrontController) BlogInfo() {\n\tthis.Data[\"json\"] = models.BlogInfo\n\tthis.ServeJson()\n}\n\nfunc (this *FrontController) Article() ", "output": "{\n\tid := this.GetString(\"id\")\n\n\tthis.Data[\"json\"] = models.ArticleById(id)\n\tthis.ServeJson()\n}"} {"input": "package http\n\nimport (\n\t\"net/http\"\n\n\tpresenterusecase \"github.com/arielizuardi/ezra/presenter/usecase\"\n\t\"github.com/labstack/echo\"\n)\n\n\ntype ResponseError struct {\n\tMessage string `json:\"error\"`\n}\n\ntype PresenterHTTPHandler struct {\n\tPresenterUsecase presenterusecase.PresenterUsecase\n}\n\nfunc (h *PresenterHTTPHandler) HandleFetchAllPresenters(c echo.Context) error {\n\tpresenters, err := h.PresenterUsecase.FetchAllPresenters()\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, &ResponseError{err.Error()})\n\t}\n\n\treturn c.JSON(http.StatusOK, presenters)\n}\n\n\n\nfunc Init(e *echo.Echo, p presenterusecase.PresenterUsecase) ", "output": "{\n\th := &PresenterHTTPHandler{p}\n\te.GET(`/presenter`, h.HandleFetchAllPresenters)\n}"} {"input": "package egoscale\n\nimport \"fmt\"\n\n\nfunc (ListAntiAffinityGroups) Response() interface{} {\n\treturn new(ListAntiAffinityGroupsResponse)\n}\n\n\n\n\n\nfunc (ls *ListAntiAffinityGroups) SetPage(page int) {\n\tls.Page = page\n}\n\n\nfunc (ls *ListAntiAffinityGroups) SetPageSize(pageSize int) {\n\tls.PageSize = pageSize\n}\n\n\nfunc (ListAntiAffinityGroups) Each(resp interface{}, callback IterateItemFunc) {\n\titems, ok := resp.(*ListAntiAffinityGroupsResponse)\n\tif !ok {\n\t\tcallback(nil, fmt.Errorf(\"wrong type, ListAntiAffinityGroupsResponse was expected, got %T\", resp))\n\t\treturn\n\t}\n\n\tfor i := range items.AntiAffinityGroup {\n\t\tif !callback(&items.AntiAffinityGroup[i], nil) {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (ls *ListAntiAffinityGroups) ListRequest() (ListCommand, error) ", "output": "{\n\tif ls == nil {\n\t\treturn nil, fmt.Errorf(\"%T cannot be nil\", ls)\n\t}\n\treturn ls, nil\n}"} {"input": "package aws\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/mitchellh/goamz/aws\"\n)\n\ntype Config struct {\n\tAccessKey string `mapstructure:\"access_key\"`\n\tSecretKey string `mapstructure:\"secret_key\"`\n\tRegion string `mapstructure:\"region\"`\n}\n\n\n\n\n\nfunc (c *Config) AWSAuth() (aws.Auth, error) {\n\tauth, err := aws.GetAuth(c.AccessKey, c.SecretKey)\n\tif err == nil {\n\t\tc.AccessKey = auth.AccessKey\n\t\tc.SecretKey = auth.SecretKey\n\t}\n\n\treturn auth, err\n}\n\n\n\nfunc (c *Config) IsValidRegion() bool {\n\tvar regions = [8]string{\"us-east-1\", \"us-west-2\", \"us-west-1\", \"eu-west-1\",\n\t\t\"ap-southeast-1\", \"ap-southeast-2\", \"ap-northeast-1\", \"sa-east-1\"}\n\n\tfor _, valid := range regions {\n\t\tif c.Region == valid {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\n\n\nfunc (c *Config) AWSRegion() (aws.Region, error) ", "output": "{\n\tif c.Region != \"\" {\n\t\tif c.IsValidRegion() {\n\t\t\treturn aws.Regions[c.Region], nil\n\t\t} else {\n\t\t\treturn aws.Region{}, fmt.Errorf(\"Not a valid region: %s\", c.Region)\n\t\t}\n\t}\n\n\tif v := os.Getenv(\"AWS_REGION\"); v != \"\" {\n\t\treturn aws.Regions[v], nil\n\t}\n\n\tmd, err := aws.GetMetaData(\"placement/availability-zone\")\n\tif err != nil {\n\t\treturn aws.Region{}, err\n\t}\n\n\tregion := strings.TrimRightFunc(string(md), unicode.IsLetter)\n\treturn aws.Regions[region], nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/fatih/color\"\n)\n\nvar boldRed *color.Color\nvar boldGreen *color.Color\nvar boldYellow *color.Color\nvar boldCyan *color.Color\nvar boldBlue *color.Color\n\n\n\nfunc initCustomColors() ", "output": "{\n\tboldRed = color.New(color.FgRed, color.Bold)\n\tboldGreen = color.New(color.FgGreen, color.Bold)\n\tboldYellow = color.New(color.FgYellow, color.Bold)\n\tboldCyan = color.New(color.FgCyan, color.Bold)\n\tboldBlue = color.New(color.FgBlue, color.Bold)\n}"} {"input": "package http2\n\nimport \"testing\"\n\nfunc TestFlow(t *testing.T) {\n\tvar st flow\n\tvar conn flow\n\tst.add(3)\n\tconn.add(2)\n\n\tif got, want := st.available(), int32(3); got != want {\n\t\tt.Errorf(\"available = %d; want %d\", got, want)\n\t}\n\tst.setConnFlow(&conn)\n\tif got, want := st.available(), int32(2); got != want {\n\t\tt.Errorf(\"after parent setup, available = %d; want %d\", got, want)\n\t}\n\n\tst.take(2)\n\tif got, want := conn.available(), int32(0); got != want {\n\t\tt.Errorf(\"after taking 2, conn = %d; want %d\", got, want)\n\t}\n\tif got, want := st.available(), int32(0); got != want {\n\t\tt.Errorf(\"after taking 2, stream = %d; want %d\", got, want)\n\t}\n}\n\n\n\nfunc TestFlowAdd(t *testing.T) ", "output": "{\n\tvar f flow\n\tif !f.add(1) {\n\t\tt.Fatal(\"failed to add 1\")\n\t}\n\tif !f.add(-1) {\n\t\tt.Fatal(\"failed to add -1\")\n\t}\n\tif got, want := f.available(), int32(0); got != want {\n\t\tt.Fatalf(\"size = %d; want %d\", got, want)\n\t}\n\tif !f.add(1<<31 - 1) {\n\t\tt.Fatal(\"failed to add 2^31-1\")\n\t}\n\tif got, want := f.available(), int32(1<<31-1); got != want {\n\t\tt.Fatalf(\"size = %d; want %d\", got, want)\n\t}\n\tif f.add(1) {\n\t\tt.Fatal(\"adding 1 to max shouldn't be allowed\")\n\t}\n\n}"} {"input": "package query\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hyperledger/fabric-sdk-go/fabric-cli/common\"\n\t\"github.com/spf13/pflag\"\n)\n\n\n\ntype QueryInfoArgs struct {\n\tChannelID string `json:channelId`\n\tPeerUrl string `json:peerUrl`\n}\n\ntype queryInfoAction struct {\n\tcommon.ActionImpl\n}\n\nfunc NewQueryInfoAction(args *QueryInfoArgs) (*queryInfoAction, error) {\n\taction, flags := &queryInfoAction{}, &pflag.FlagSet{}\n\n\tflags.StringVar(&common.ChannelID, common.ChannelIDFlag, args.ChannelID, \"The channel ID\")\n\tflags.StringVar(&common.PeerURL, common.PeerFlag, args.PeerUrl, \"The channel ID\")\n\n\terr := action.Initialize(flags)\n\treturn action, err\n}\n\n\n\nfunc (action *queryInfoAction) Execute() (string, error) ", "output": "{\n\tchain, err := action.NewChain()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Error initializing chain: %v\", err)\n\t}\n\n\tinfo, err := chain.QueryInfo()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taction.Printer().PrintBlockchainInfo(info)\n\n\treturn info.String(), nil\n}"} {"input": "package hcloud\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hashicorp/packer/packer\"\n)\n\n\n\nfunc TestArtifactId(t *testing.T) {\n\tgeneratedData := make(map[string]interface{})\n\ta := &Artifact{\"packer-foobar\", 42, nil, generatedData}\n\texpected := \"42\"\n\n\tif a.Id() != expected {\n\t\tt.Fatalf(\"artifact ID should match: %v\", expected)\n\t}\n}\n\nfunc TestArtifactString(t *testing.T) {\n\tgeneratedData := make(map[string]interface{})\n\ta := &Artifact{\"packer-foobar\", 42, nil, generatedData}\n\texpected := \"A snapshot was created: 'packer-foobar' (ID: 42)\"\n\n\tif a.String() != expected {\n\t\tt.Fatalf(\"artifact string should match: %v\", expected)\n\t}\n}\n\nfunc TestArtifactState_StateData(t *testing.T) {\n\texpectedData := \"this is the data\"\n\tartifact := &Artifact{\n\t\tStateData: map[string]interface{}{\"state_data\": expectedData},\n\t}\n\n\tresult := artifact.State(\"state_data\")\n\tif result != expectedData {\n\t\tt.Fatalf(\"Bad: State data was %s instead of %s\", result, expectedData)\n\t}\n\n\tresult = artifact.State(\"invalid_key\")\n\tif result != nil {\n\t\tt.Fatalf(\"Bad: State should be nil for invalid state data name\")\n\t}\n\n\tartifact = &Artifact{}\n\tresult = artifact.State(\"key\")\n\tif result != nil {\n\t\tt.Fatalf(\"Bad: State should be nil for nil StateData\")\n\t}\n}\n\nfunc TestArtifact_Impl(t *testing.T) ", "output": "{\n\tvar _ packer.Artifact = (*Artifact)(nil)\n}"} {"input": "package iso20022\n\n\ntype MeetingCancellationReason2 struct {\n\n\tCancellationReasonCode *MeetingCancellationReason1Choice `xml:\"CxlRsnCd,omitempty\"`\n\n\tCancellationReason *Max140Text `xml:\"CxlRsn,omitempty\"`\n}\n\n\n\nfunc (m *MeetingCancellationReason2) SetCancellationReason(value string) {\n\tm.CancellationReason = (*Max140Text)(&value)\n}\n\nfunc (m *MeetingCancellationReason2) AddCancellationReasonCode() *MeetingCancellationReason1Choice ", "output": "{\n\tm.CancellationReasonCode = new(MeetingCancellationReason1Choice)\n\treturn m.CancellationReasonCode\n}"} {"input": "package httpmux\n\nimport \"net/http\"\n\n\ntype ConfigOption interface {\n\tSet(c *Config)\n}\n\n\ntype ConfigOptionFunc func(c *Config)\n\n\nfunc (f ConfigOptionFunc) Set(c *Config) { f(c) }\n\n\nfunc WithPrefix(prefix string) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Prefix = prefix })\n}\n\n\n\n\n\nfunc WithMiddlewareFunc(mw ...MiddlewareFunc) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.UseFunc(mw...) })\n}\n\n\nfunc WithRedirectTrailingSlash(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectTrailingSlash = v })\n}\n\n\nfunc WithRedirectFixedPath(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectFixedPath = v })\n}\n\n\nfunc WithHandleMethodNotAllowed(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.HandleMethodNotAllowed = v })\n}\n\n\nfunc WithNotFound(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.NotFound = f })\n}\n\n\nfunc WithMethodNotAllowed(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.MethodNotAllowed = f })\n}\n\n\nfunc WithPanicHandler(f func(http.ResponseWriter, *http.Request, interface{})) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.PanicHandler = f })\n}\n\nfunc WithMiddleware(mw ...Middleware) ConfigOption ", "output": "{\n\treturn ConfigOptionFunc(func(c *Config) { c.Middleware = mw })\n}"} {"input": "package state\n\nimport (\n\t\"net/url\"\n\n\t\"gopkg.in/juju/charm.v3\"\n)\n\n\ntype charmDoc struct {\n\tURL *charm.URL `bson:\"_id\"`\n\tMeta *charm.Meta\n\tConfig *charm.Config\n\tActions *charm.Actions\n\tBundleURL *url.URL\n\tBundleSha256 string\n\tPendingUpload bool\n\tPlaceholder bool\n}\n\n\ntype Charm struct {\n\tst *State\n\tdoc charmDoc\n}\n\nfunc newCharm(st *State, cdoc *charmDoc) (*Charm, error) {\n\treturn &Charm{st: st, doc: *cdoc}, nil\n}\n\nfunc (c *Charm) String() string {\n\treturn c.doc.URL.String()\n}\n\n\nfunc (c *Charm) URL() *charm.URL {\n\tclone := *c.doc.URL\n\treturn &clone\n}\n\n\n\nfunc (c *Charm) Revision() int {\n\treturn c.doc.URL.Revision\n}\n\n\n\n\n\nfunc (c *Charm) Config() *charm.Config {\n\treturn c.doc.Config\n}\n\n\nfunc (c *Charm) Actions() *charm.Actions {\n\treturn c.doc.Actions\n}\n\n\n\nfunc (c *Charm) BundleURL() *url.URL {\n\treturn c.doc.BundleURL\n}\n\n\nfunc (c *Charm) BundleSha256() string {\n\treturn c.doc.BundleSha256\n}\n\n\n\nfunc (c *Charm) IsUploaded() bool {\n\treturn !c.doc.PendingUpload\n}\n\n\n\nfunc (c *Charm) IsPlaceholder() bool {\n\treturn c.doc.Placeholder\n}\n\nfunc (c *Charm) Meta() *charm.Meta ", "output": "{\n\treturn c.doc.Meta\n}"} {"input": "package gridq\n\ntype byColRow []*WriteResponse\n\nfunc (p byColRow) Len() int { return len(p) }\nfunc (p byColRow) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byColRow) Less(i, j int) bool {\n\tif p[i].Col < p[j].Col {\n\t\treturn true\n\t} else if p[i].Col > p[j].Col {\n\t\treturn false\n\t} else {\n\t\treturn p[i].Row < p[j].Row\n\t}\n}\n\ntype byRowTimestamp []*ReadResponse\n\n\nfunc (p byRowTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byRowTimestamp) Less(i, j int) bool {\n\tif p[i].Row < p[j].Row {\n\t\treturn true\n\t} else if p[i].Row > p[j].Row {\n\t\treturn false\n\t} else {\n\t\treturn p[i].State.Timestamp > p[j].State.Timestamp\n\t}\n}\n\ntype byTimestamp []*ReadResponse\n\nfunc (p byTimestamp) Len() int { return len(p) }\nfunc (p byTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byTimestamp) Less(i, j int) bool { return p[i].State.Timestamp < p[j].State.Timestamp }\n\nfunc (p byRowTimestamp) Len() int ", "output": "{ return len(p) }"} {"input": "package events\n\nimport \"github.com/gophercloud/gophercloud\"\n\nvar apiVersion = \"v1\"\nvar apiName = \"events\"\n\n\n\nfunc listURL(client *gophercloud.ServiceClient) string {\n\treturn commonURL(client)\n}\n\nfunc idURL(client *gophercloud.ServiceClient, id string) string {\n\treturn client.ServiceURL(apiVersion, apiName, id)\n}\n\nfunc getURL(client *gophercloud.ServiceClient, id string) string {\n\treturn idURL(client, id)\n}\n\nfunc commonURL(client *gophercloud.ServiceClient) string ", "output": "{\n\treturn client.ServiceURL(apiVersion, apiName)\n}"} {"input": "package cluster\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\nfunc addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}\n\n\n\nfunc SetDefaults_Instance(obj *Instance) {\n\tif obj.Spec.ReclaimPolicy == \"\" {\n\t\tobj.Spec.ReclaimPolicy = InstanceReclaimDelete\n\t}\n\n\tif obj.Status.Phase == \"\" {\n\t\tobj.Status.Phase = InstancePending\n\t}\n}\n\nfunc SetDefaults_Network(obj *Network) {\n\tif obj.Status.Phase == \"\" {\n\t\tobj.Status.Phase = NetworkPending\n\t}\n}\n\nfunc SetDefaults_ReservedInstance(obj *ReservedInstance) {\n\tif obj.Status.Phase == \"\" {\n\t\tobj.Status.Phase = ReservedInstanceAvailable\n\t}\n}\n\nfunc SetDefaults_InstanceGroup(obj *InstanceGroup) ", "output": "{\n\tif obj.Spec.ProvisionPolicy == \"\" {\n\t\tobj.Spec.ProvisionPolicy = InstanceGroupProvisionDynamicOnly\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/lmorg/murex/lang\"\n\t\"github.com/lmorg/murex/test/count\"\n)\n\n\n\nfunc TestMurex(t *testing.T) {\n\tcount.Tests(t, 1)\n\n\tlang.InitEnv()\n\n\tblock := []rune(\"a [Mon..Fri]->regexp m/^T/\")\n\n\t_, err := lang.ShellProcess.Fork(lang.F_NO_STDIN | lang.F_NO_STDOUT | lang.F_NO_STDERR).Execute(block)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n}\n\nfunc TestRunCommandLine(t *testing.T) {\n\tcount.Tests(t, 1)\n\n\trunCommandLine(`out: \"testing\" -> null`)\n}\n\nfunc TestRunSource(t *testing.T) {\n\tcount.Tests(t, 1)\n\n\tfile := \"test/source.mx\"\n\trunSource(file)\n}\n\n\n\nfunc TestRunSourceGzMods(t *testing.T) ", "output": "{\n\tcount.Tests(t, 1)\n\n\tfile := \"test/source.mx.gz\"\n\trunSource(file)\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/SaferLuo/EtherIOT/node\"\n\t\"github.com/SaferLuo/EtherIOT/rpc\"\n\t\"gopkg.in/urfave/cli.v1\"\n)\n\n\n\n\n\n\n\nfunc NewRemoteRPCClientFromString(endpoint string) (rpc.Client, error) {\n\tif strings.HasPrefix(endpoint, \"ipc:\") {\n\t\treturn rpc.NewIPCClient(endpoint[4:])\n\t}\n\tif strings.HasPrefix(endpoint, \"rpc:\") {\n\t\treturn rpc.NewHTTPClient(endpoint[4:])\n\t}\n\tif strings.HasPrefix(endpoint, \"http:\") {\n\t\treturn rpc.NewHTTPClient(endpoint)\n\t}\n\tif strings.HasPrefix(endpoint, \"ws:\") {\n\t\treturn rpc.NewWSClient(endpoint)\n\t}\n\treturn nil, fmt.Errorf(\"invalid endpoint\")\n}\n\nfunc NewRemoteRPCClient(ctx *cli.Context) (rpc.Client, error) ", "output": "{\n\tif ctx.Args().Present() {\n\t\tendpoint := ctx.Args().First()\n\t\treturn NewRemoteRPCClientFromString(endpoint)\n\t}\n\treturn rpc.NewIPCClient(node.DefaultIPCEndpoint())\n}"} {"input": "package consul\n\nimport (\n\t\"log\"\n\n\t\"github.com/armon/consul-api\"\n\t\"github.com/hashicorp/terraform/helper/config\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\ntype ResourceProvider struct {\n\tConfig Config\n\tclient *consulapi.Client\n}\n\nfunc (p *ResourceProvider) Validate(c *terraform.ResourceConfig) ([]string, []error) {\n\tv := &config.Validator{\n\t\tOptional: []string{\n\t\t\t\"datacenter\",\n\t\t\t\"address\",\n\t\t},\n\t}\n\treturn v.Validate(c)\n}\n\nfunc (p *ResourceProvider) ValidateResource(\n\tt string, c *terraform.ResourceConfig) ([]string, []error) {\n\treturn resourceMap.Validate(t, c)\n}\n\nfunc (p *ResourceProvider) Configure(c *terraform.ResourceConfig) error {\n\tif _, err := config.Decode(&p.Config, c.Config); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[INFO] Initializing Consul client\")\n\tvar err error\n\tp.client, err = p.Config.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (p *ResourceProvider) Apply(\n\ts *terraform.ResourceState,\n\td *terraform.ResourceDiff) (*terraform.ResourceState, error) {\n\treturn resourceMap.Apply(s, d, p)\n}\n\n\n\nfunc (p *ResourceProvider) Refresh(\n\ts *terraform.ResourceState) (*terraform.ResourceState, error) {\n\treturn resourceMap.Refresh(s, p)\n}\n\nfunc (p *ResourceProvider) Resources() []terraform.ResourceType {\n\treturn resourceMap.Resources()\n}\n\nfunc (p *ResourceProvider) Diff(\n\ts *terraform.ResourceState,\n\tc *terraform.ResourceConfig) (*terraform.ResourceDiff, error) ", "output": "{\n\treturn resourceMap.Diff(s, c, p)\n}"} {"input": "package main\nimport (\n\t\"fmt\"\n)\nvar a = \"G\"\n\nfunc main(){\n\tn()\n\tm()\n\tn()\n\n}\n\n\n\nfunc m(){\n\ta := \"O\"\n\tfmt.Println(a)\n}\n\nfunc n()", "output": "{\n\tfmt.Println(a)\n}"} {"input": "package github\n\nimport (\n\t\"github.com/hashicorp/terraform/helper/schema\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\n\nfunc Provider() terraform.ResourceProvider {\n\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"token\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"GITHUB_TOKEN\", nil),\n\t\t\t\tDescription: descriptions[\"token\"],\n\t\t\t},\n\t\t\t\"organization\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"GITHUB_ORGANIZATION\", nil),\n\t\t\t\tDescription: descriptions[\"organization\"],\n\t\t\t},\n\t\t},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"github_team\": resourceGithubTeam(),\n\t\t\t\"github_team_membership\": resourceGithubTeamMembership(),\n\t\t\t\"github_team_repository\": resourceGithubTeamRepository(),\n\t\t\t\"github_membership\": resourceGithubMembership(),\n\t\t},\n\n\t\tConfigureFunc: providerConfigure,\n\t}\n}\n\nvar descriptions map[string]string\n\nfunc init() {\n\tdescriptions = map[string]string{\n\t\t\"token\": \"The OAuth token used to connect to GitHub.\",\n\n\t\t\"organization\": \"The GitHub organization name to manage.\",\n\t}\n}\n\n\n\nfunc providerConfigure(d *schema.ResourceData) (interface{}, error) ", "output": "{\n\tconfig := Config{\n\t\tToken: d.Get(\"token\").(string),\n\t\tOrganization: d.Get(\"organization\").(string),\n\t}\n\n\treturn config.Client()\n}"} {"input": "package loggo\n\nvar (\n\tdefaultContext = newDefaultContxt()\n)\n\nfunc newDefaultContxt() *Context {\n\tctx := NewContext(WARNING)\n\tctx.AddWriter(DefaultWriterName, defaultWriter())\n\treturn ctx\n}\n\n\nfunc DefaultContext() *Context {\n\treturn defaultContext\n}\n\n\n\n\n\nfunc LoggerInfo() string {\n\treturn defaultContext.Config().String()\n}\n\n\n\nfunc GetLogger(name string, size ...int) Logger {\n\treturn defaultContext.GetLogger(name, size...)\n}\n\n\n\n\n\nfunc ResetLogging() {\n\tdefaultContext.ResetLoggerLevels()\n\tdefaultContext.ResetWriters()\n}\n\n\nfunc ResetWriters() {\n\tdefaultContext.ResetWriters()\n}\n\n\n\n\nfunc ReplaceDefaultWriter(writer Writer) (Writer, error) {\n\treturn defaultContext.ReplaceWriter(DefaultWriterName, writer)\n}\n\n\n\n\n\n\n\n\nfunc RemoveWriter(name string) (Writer, error) {\n\treturn defaultContext.RemoveWriter(name)\n}\n\n\n\n\n\n\n\n\n\n\nfunc ConfigureLoggers(specification string) error {\n\tconfig, err := ParseConfigString(specification)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefaultContext.ApplyConfig(config)\n\treturn nil\n}\n\nfunc RegisterWriter(name string, writer Writer) error ", "output": "{\n\treturn defaultContext.AddWriter(name, writer)\n}"} {"input": "package slack\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n)\n\n\n\n\n\n\n\ntype backoff struct {\n\tattempts int\n\tInitial time.Duration\n\tJitter time.Duration\n\tMax time.Duration\n}\n\n\n\nfunc (b *backoff) Duration() (dur time.Duration) {\n\tif b.Max == 0 {\n\t\tb.Max = 10 * time.Second\n\t}\n\n\tif b.Initial == 0 {\n\t\tb.Initial = 100 * time.Millisecond\n\t}\n\n\tif dur = time.Duration(1 << uint(b.attempts)); dur > 0 {\n\t\tdur = dur * b.Initial\n\t} else {\n\t\tdur = b.Max\n\t}\n\n\tif b.Jitter > 0 {\n\t\tdur = dur + time.Duration(rand.Intn(int(b.Jitter)))\n\t}\n\n\tb.attempts++\n\n\treturn dur\n}\n\n\n\n\nfunc (b *backoff) Reset() ", "output": "{\n\tb.attempts = 0\n}"} {"input": "package main;\n\nfunc main(){\n var z bool = true;\n var x []bool;\n x = append(x, (inc(^+-int(!!!z)) + 2 &^ ( 1 ) ^ 15) == 12);\n}\n\nfunc inc (toInc int) int ", "output": "{\n toInc++;\n return toInc;\n}"} {"input": "package main\n\nimport (\n\t\"github.com/ginuerzh/gosocks5\"\n\t\"github.com/gorilla/websocket\"\n\t\"log\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype WSConn struct {\n\t*websocket.Conn\n\trb []byte\n}\n\nfunc NewWSConn(conn *websocket.Conn) *WSConn {\n\tc := &WSConn{\n\t\tConn: conn,\n\t}\n\n\treturn c\n}\n\n\n\nfunc (conn *WSConn) Write(b []byte) (n int, err error) {\n\terr = conn.WriteMessage(websocket.BinaryMessage, b)\n\tn = len(b)\n\n\treturn\n}\n\nfunc (conn *WSConn) SetDeadline(t time.Time) error {\n\tif err := conn.SetReadDeadline(t); err != nil {\n\t\treturn err\n\t}\n\treturn conn.SetWriteDeadline(t)\n}\n\ntype WSServer struct {\n\tAddr string\n}\n\nvar upgrader = websocket.Upgrader{\n\tReadBufferSize: 8192,\n\tWriteBufferSize: 8192,\n\tCheckOrigin: func(r *http.Request) bool { return true },\n}\n\nfunc (s *WSServer) handle(w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tc := gosocks5.ServerConn(NewWSConn(conn), serverConfig)\n\tsocks5Handle(c)\n}\n\nfunc (s *WSServer) ListenAndServe() error {\n\thttp.HandleFunc(\"/\", s.handle)\n\treturn http.ListenAndServe(s.Addr, nil)\n}\n\nfunc (conn *WSConn) Read(b []byte) (n int, err error) ", "output": "{\n\tif len(conn.rb) == 0 {\n\t\t_, conn.rb, err = conn.ReadMessage()\n\t}\n\tn = copy(b, conn.rb)\n\tconn.rb = conn.rb[n:]\n\n\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"camlistore.org/pkg/blobref\"\n\t\"camlistore.org/pkg/cmdmain\"\n)\n\ntype removeCmd struct{}\n\n\n\nfunc (c *removeCmd) Usage() {\n\tfmt.Fprintf(cmdmain.Stderr, `Usage: camput remove \n\nThis command is for debugging only. You're not expected to use it in practice.\n`)\n}\n\nfunc (c *removeCmd) RunCommand(args []string) error {\n\tif len(args) == 0 {\n\t\treturn cmdmain.ErrUsage\n\t}\n\treturn getUploader().RemoveBlobs(blobref.ParseMulti(args))\n}\n\nfunc init() ", "output": "{\n\tcmdmain.RegisterCommand(\"remove\", func(flags *flag.FlagSet) cmdmain.CommandRunner {\n\t\tcmd := new(removeCmd)\n\t\treturn cmd\n\t})\n}"} {"input": "package closure\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc bye() {\n\tfmt.Println(\"good bye\")\n}\n\nfunc IncrementTest() {\n\tdefer bye() \n\tincrementer := wrapper()\n\tfmt.Println(incrementer())\n\tfmt.Println(incrementer())\n}\n\nfunc wrapper() func() int ", "output": "{\n\tx := 0\n\n\tincrement := func() int {\n\t\tx++ \n\t\treturn x\n\t}\n\treturn increment\n}"} {"input": "package restfuladapter\n\nimport (\n\t\"github.com/emicklei/go-restful\"\n\t\"k8s.io/kube-openapi/pkg/common\"\n)\n\nvar _ common.StatusCodeResponse = &ResponseErrorAdapter{}\n\n\ntype ResponseErrorAdapter struct {\n\tErr *restful.ResponseError\n}\n\n\n\nfunc (r *ResponseErrorAdapter) Model() interface{} {\n\treturn r.Err.Model\n}\n\nfunc (r *ResponseErrorAdapter) Code() int {\n\treturn r.Err.Code\n}\n\nfunc (r *ResponseErrorAdapter) Message() string ", "output": "{\n\treturn r.Err.Message\n}"} {"input": "package instance\n\nimport (\n\t\"net\"\n)\n\n\n\ntype AddressType string\n\nconst (\n\tHostName AddressType = \"hostname\"\n\tIpv4Address AddressType = \"ipv4\"\n\tIpv6Address AddressType = \"ipv6\"\n)\n\n\n\n\n\ntype NetworkScope string\n\nconst (\n\tNetworkUnknown NetworkScope = \"\"\n\tNetworkPublic NetworkScope = \"public\"\n\tNetworkCloudLocal NetworkScope = \"local-cloud\"\n\tNetworkMachineLocal NetworkScope = \"local-machine\"\n)\n\n\n\ntype Address struct {\n\tValue string\n\tType AddressType\n\tNetworkName string\n\tNetworkScope\n}\n\nfunc deriveAddressType(value string) AddressType {\n\tip := net.ParseIP(value)\n\tif ip != nil {\n\t\tif ip.To4() != nil {\n\t\t\treturn Ipv4Address\n\t\t}\n\t\tif ip.To16() != nil {\n\t\t\treturn Ipv6Address\n\t\t}\n\t\tpanic(\"Unknown form of IP address\")\n\t}\n\treturn HostName\n}\n\n\n\n\n\n\nfunc SelectPublicAddress(addresses []Address) string {\n\tmostpublic := \"\"\n\tfor _, addr := range addresses {\n\t\tif addr.Type != Ipv6Address {\n\t\t\tswitch addr.NetworkScope {\n\t\t\tcase NetworkPublic:\n\t\t\t\treturn addr.Value\n\t\t\tcase NetworkCloudLocal, NetworkUnknown:\n\t\t\t\tmostpublic = addr.Value\n\t\t\t}\n\t\t}\n\t}\n\treturn mostpublic\n}\n\nfunc NewAddress(value string) Address ", "output": "{\n\taddresstype := deriveAddressType(value)\n\treturn Address{value, addresstype, \"\", NetworkUnknown}\n}"} {"input": "package monotime\n\nimport (\n\t\"time\"\n)\n\n\ntype Time uint64\n\n\n\nfunc (t Time) Add(d time.Duration) Time ", "output": "{\n\treturn Time(uint64(t) + uint64(d.Nanoseconds()))\n}"} {"input": "package harmonylandinfo\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestScrape(t *testing.T) {\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/welcome.html\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"testdata/www.harmonyland.jp/welcome.html\")\n\t})\n\n\tserver := httptest.NewServer(mux)\n\tdefer server.Close()\n\n\tsource := NewSource(server.Client())\n\tsource.baseURL = server.URL\n\n\tfeed, err := source.Scrape()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tassert.Equal(t, 13, len(feed.Items))\n\tassert.Equal(t, \"2017年はシナモン15周年! ハーモニーランドはシナモンイベントがいっぱい♪【6/2~7/14】\", feed.Items[0].Title)\n\tassert.Equal(t, \"https://www.harmonyland.jp/event/rain/index.html\", feed.Items[0].Link.Href)\n}\n\nfunc TestNewSource(t *testing.T) ", "output": "{\n\tsource := NewSource(http.DefaultClient)\n\tassert.Equal(t, http.DefaultClient, source.httpClient)\n\tassert.Equal(t, baseURL, source.baseURL)\n}"} {"input": "package alidayu\n\nimport \"encoding/json\"\n\n\n\nfunc lecall(cm *commonModel, lm *lecallModel) (*Result, error) {\n\tm := make(map[string]string, 11)\n\tm[\"app_key\"] = Appkey\n\tm[\"format\"] = cm.Format\n\tm[\"method\"] = methodCallTTS\n\tm[\"sign_method\"] = cm.SignMethod\n\tm[\"timestamp\"] = cm.Timestamp\n\tm[\"v\"] = cm.V\n\tm[\"called_num\"] = lm.CalledNum\n\tm[\"called_show_num\"] = lm.CalledShowNum\n\tm[\"tts_code\"] = lm.TtsCode\n\tm[\"tts_param\"] = lm.TtsParam\n\n\treturn responseToResult(m)\n}\n\nfunc messasg(cm *commonModel, sm *smsModel) (*Result, error) ", "output": "{\n\tm := make(map[string]string, 11)\n\tm[\"app_key\"] = Appkey\n\tm[\"format\"] = cm.Format\n\tm[\"method\"] = methodSendSMS\n\tm[\"sign_method\"] = cm.SignMethod\n\tm[\"timestamp\"] = cm.Timestamp\n\tm[\"v\"] = cm.V\n\tm[\"sms_type\"] = sm.SmsType\n\tm[\"sms_free_sign_name\"] = sm.SmsFreeSignName\n\tm[\"rec_num\"] = sm.RecNum\n\tm[\"sms_template_code\"] = sm.SmsTemplateCode\n\tm[\"sms_param\"] = sm.SmsParam\n\n\tsuccess, response, err := postAlidayu(m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresultmod := &Result{}\n\tif err := json.Unmarshal(response, resultmod); err != nil {\n\t\treturn nil, err\n\t}\n\tresultmod.Success = success\n\treturn resultmod, nil\n}"} {"input": "package daemon\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetMapNameOKCode int = 200\n\n\ntype GetMapNameOK struct {\n\n\tPayload *models.BPFMap `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetMapNameOK() *GetMapNameOK {\n\n\treturn &GetMapNameOK{}\n}\n\n\nfunc (o *GetMapNameOK) WithPayload(payload *models.BPFMap) *GetMapNameOK {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *GetMapNameOK) SetPayload(payload *models.BPFMap) {\n\to.Payload = payload\n}\n\n\nfunc (o *GetMapNameOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\n\nconst GetMapNameNotFoundCode int = 404\n\n\ntype GetMapNameNotFound struct {\n}\n\n\n\n\n\nfunc (o *GetMapNameNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc NewGetMapNameNotFound() *GetMapNameNotFound ", "output": "{\n\n\treturn &GetMapNameNotFound{}\n}"} {"input": "package api\n\nimport (\n\t\"github.com/ying32/govcl/vcl/api/memorydll\"\n\t\"github.com/ying32/govcl/vcl/win\"\n)\n\nfunc loadUILib() *memorydll.LazyDLL {\n\tdllBytes, ok := win.ResourceToBytes(win.GetSelfModuleHandle(), \"GOVCLLIB\", win.RT_RCDATA)\n\tif !ok {\n\t\tpanic(\"\\\"GOVCLLIB\\\" resource does not exist.\")\n\t\treturn nil\n\t}\n\tlib := memorydll.NewMemoryDLL(dllBytes)\n\tif lib.Load() != nil {\n\t\tpanic(\"Unable to load dll, unknown reason.\")\n\t\treturn nil\n\t}\n\tif getLibType(lib) != 1 {\n\t\tpanic(\"The VCL library is no longer supported. If necessary, please use the last code that supports VCL version: https:github.com/ying32/govcl/tree/last-vcl-support.\")\n\t}\n\treturn lib\n}\n\nfunc getLibType(lib *memorydll.LazyDLL) int32 {\n\tproc := lib.NewProc(\"DGetLibType\")\n\tr, _, _ := proc.Call()\n\treturn int32(r)\n}\n\n\n\n\n\nfunc FeeMemoryDLL() {\n\tif libvcl != nil {\n\t\tlibvcl.Close()\n\t\tlibvcl = nil\n\t}\n}\n\nfunc closeLib() {\n\tFeeMemoryDLL()\n}\n\nfunc GetLibVcl() *memorydll.LazyDLL ", "output": "{\n\treturn libvcl\n}"} {"input": "package guetzli_patapon\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\n\n\nfunc GUETZLI_LOG_QUANT(stats *ProcessStats, q [][kDCTBlockSize]int) ", "output": "{\n\tprint := func(format string, x ...interface{}) {\n\t\tfmt.Fprintf(os.Stderr, format, x...)\n\t}\n\n\tfor y := 0; y < 8; y++ {\n\t\tfor c := 0; c < 3; c++ {\n\t\t\tfor x := 0; x < 8; x++ {\n\t\t\t\tprint(\" %2d\", (q)[c][8*y+x])\n\t\t\t}\n\t\t\tprint(\" \")\n\t\t}\n\t\tprint(\"\\n\")\n\t}\n}"} {"input": "package metrics\n\n\n\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\tgolangswaggerpaths \"path\"\n)\n\n\ntype GetMetricsURL struct {\n\t_basePath string\n}\n\n\n\n\n\n\n\n\n\nfunc (o *GetMetricsURL) SetBasePath(bp string) {\n\to._basePath = bp\n}\n\n\nfunc (o *GetMetricsURL) Build() (*url.URL, error) {\n\tvar result url.URL\n\n\tvar _path = \"/metrics/\"\n\n\t_basePath := o._basePath\n\tif _basePath == \"\" {\n\t\t_basePath = \"/v1\"\n\t}\n\tresult.Path = golangswaggerpaths.Join(_basePath, _path)\n\n\treturn &result, nil\n}\n\n\nfunc (o *GetMetricsURL) Must(u *url.URL, err error) *url.URL {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif u == nil {\n\t\tpanic(\"url can't be nil\")\n\t}\n\treturn u\n}\n\n\nfunc (o *GetMetricsURL) String() string {\n\treturn o.Must(o.Build()).String()\n}\n\n\nfunc (o *GetMetricsURL) BuildFull(scheme, host string) (*url.URL, error) {\n\tif scheme == \"\" {\n\t\treturn nil, errors.New(\"scheme is required for a full url on GetMetricsURL\")\n\t}\n\tif host == \"\" {\n\t\treturn nil, errors.New(\"host is required for a full url on GetMetricsURL\")\n\t}\n\n\tbase, err := o.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbase.Scheme = scheme\n\tbase.Host = host\n\treturn base, nil\n}\n\n\nfunc (o *GetMetricsURL) StringFull(scheme, host string) string {\n\treturn o.Must(o.BuildFull(scheme, host)).String()\n}\n\nfunc (o *GetMetricsURL) WithBasePath(bp string) *GetMetricsURL ", "output": "{\n\to.SetBasePath(bp)\n\treturn o\n}"} {"input": "package incoming\n\nimport (\n\t\"github.com/pkg/errors\"\n)\n\ntype ignorableErr struct {\n\terror\n}\n\nfunc (e ignorableErr) Ignorable() bool {\n\treturn true\n}\n\nfunc wrapIgnorable(err error) error {\n\treturn ignorableErr{error: err}\n}\n\nfunc (m *RuleMap) Get(name string) (*Rule, error) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tif m.rules == nil {\n\t\treturn nil, wrapIgnorable(errors.New(\"rule not found: '\" + name + \"'\"))\n\t}\n\n\tr, ok := m.rules[name]\n\tif !ok {\n\t\treturn nil, wrapIgnorable(errors.New(\"rule not found: '\" + name + \"'\"))\n\t}\n\treturn r, nil\n}\n\nfunc (m *RuleMap) Set(name string, r *Rule) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tif m.rules == nil {\n\t\tm.rules = make(map[string]*Rule)\n\t}\n\n\tm.rules[name] = r\n}\n\n\n\nfunc (r Rule) AggregationWindow() int64 {\n\treturn 300\n}\n\nfunc (r Rule) Disabled() bool ", "output": "{\n\treturn false\n}"} {"input": "package faregate\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\n\n\nfunc Example() {\n\trnd := rand.New(rand.NewSource(42))\n\n\tfg, err := New(RefreshInterval(time.Second), TokenCount(100), ConcurrencyLevel(1))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer fg.Close()\n\n\tfor {\n\t\tq := rnd.Intn(10)\n\t\t<-Must(fg.Acquire(uint64(q)))\n\t\tfmt.Println(\"acquired\", q)\n\t}\n}\n\nfunc Must(c <-chan struct{}, err error) <-chan struct{} ", "output": "{\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn c\n}"} {"input": "package streaming\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteStreamPoolRequest struct {\n\n\tStreamPoolId *string `mandatory:\"true\" contributesTo:\"path\" name:\"streamPoolId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteStreamPoolRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteStreamPoolRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request DeleteStreamPoolRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request DeleteStreamPoolRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteStreamPoolResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteStreamPoolResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response DeleteStreamPoolResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package token\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/PuerkitoBio/goquery\"\n)\n\n\n\n\nfunc parseToken(res *http.Response) (string, error) {\n\tdoc, err := goquery.NewDocumentFromReader(res.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar token string\n\tdoc.Find(\"input[name=gintoken]\").Each(func(_ int, s *goquery.Selection) {\n\t\tif val, ok := s.Attr(\"value\"); ok {\n\t\t\ttoken = val\n\t\t}\n\t})\n\treturn token, nil\n}\n\nfunc GetToken(client *http.Client, urlString string) (string, error) ", "output": "{\n\treq, _ := http.NewRequest(\"GET\", urlString, nil)\n\tres, err := client.Do(req)\n\tdefer func() {\n\t\tif res.Body != nil {\n\t\t\tres.Body.Close()\n\t\t}\n\t}()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn parseToken(res)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/codegangsta/cli\"\n)\n\n\n\nfunc fromStdin(c *cli.Context) {\n\n}\n\nfunc fromFile(c *cli.Context) {\n\n}\n\nfunc Action(c *cli.Context) ", "output": "{\n\tif c.GlobalBool(\"help\") {\n\t\tcli.ShowAppHelp(c)\n\t\treturn\n\t}\n\n\tswitch len(c.Args()) {\n\tcase 0:\n\t\tcli.ShowAppHelp(c)\n\tcase 1:\n\t\tfromStdin(c)\n\tcase 2:\n\t\tfromFile(c)\n\tdefault:\n\t\tcli.ShowAppHelp(c)\n\t}\n}"} {"input": "package x509\n\n\nimport \"C\"\nimport \"unsafe\"\n\n\n\nfunc initSystemRoots() ", "output": "{\n\troots := NewCertPool()\n\n\tvar data C.CFDataRef = nil\n\terr := C.FetchPEMRoots(&data)\n\tif err == -1 {\n\t\treturn\n\t}\n\n\tdefer C.CFRelease(C.CFTypeRef(data))\n\tbuf := C.GoBytes(unsafe.Pointer(C.CFDataGetBytePtr(data)), C.int(C.CFDataGetLength(data)))\n\troots.AppendCertsFromPEM(buf)\n\tsystemRoots = roots\n}"} {"input": "package iso20022\n\n\ntype UnmatchedReason21Choice struct {\n\n\tCode *UnmatchedReason11Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification30 `xml:\"Prtry\"`\n}\n\n\n\nfunc (u *UnmatchedReason21Choice) AddProprietary() *GenericIdentification30 {\n\tu.Proprietary = new(GenericIdentification30)\n\treturn u.Proprietary\n}\n\nfunc (u *UnmatchedReason21Choice) SetCode(value string) ", "output": "{\n\tu.Code = (*UnmatchedReason11Code)(&value)\n}"} {"input": "package epi\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\n\nfunc parity(n uint64) int {\n\tcount := 0\n\tfor i := 0; i < 64; i++ {\n\t\tif (n & (1 << uint64(i))) > 0 {\n\t\t\tcount++\n\t\t}\n\t}\n\tif count%2 == 0 {\n\t\treturn 0\n\t}\n\treturn 1\n}\n\n\n\nfunc TestGoParity(t *testing.T) ", "output": "{\n\tassert.Equal(t, 0, parity(3))\n\tassert.Equal(t, 1, parity(1))\n}"} {"input": "package event\n\nimport (\n\t\"fmt\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\n\ntype Increment struct {\n\tName string\n\tValue int64\n}\n\nfunc (e *Increment) StatClass() string {\n\treturn \"counter\"\n}\n\n\nfunc (e *Increment) Update(e2 Event) error {\n\tif e.Type() != e2.Type() {\n\t\treturn fmt.Errorf(\"statsd event type conflict: %s vs %s \", e.String(), e2.String())\n\t}\n\tatomic.AddInt64(&e.Value, e2.Payload().(int64))\n\treturn nil\n}\n\n\nfunc (e *Increment) Reset() {\n\te.Value = 0\n}\n\n\nfunc (e Increment) Payload() interface{} {\n\treturn e.Value\n}\n\n\nfunc (e Increment) Stats(tick time.Duration) []string {\n\treturn []string{fmt.Sprintf(\"%s:%d|c\", e.Name, e.Value)}\n}\n\n\nfunc (e Increment) Key() string {\n\treturn e.Name\n}\n\n\nfunc (e *Increment) SetKey(key string) {\n\te.Name = key\n}\n\n\nfunc (e Increment) Type() int {\n\treturn EventIncr\n}\n\n\n\n\n\nfunc (e Increment) String() string {\n\treturn fmt.Sprintf(\"{Type: %s, Key: %s, Value: %d}\", e.TypeString(), e.Name, e.Value)\n}\n\nfunc (e Increment) TypeString() string ", "output": "{\n\treturn \"Increment\"\n}"} {"input": "package core\n\n\ntype Clients []*Client\n\n\n\n\n\nfunc (cs *Clients) RUnlockRecursive() {\n\tfor _, client := range *cs {\n\t\tclient.RUnlockAnon()\n\t}\n}\n\nfunc (cs *Clients) RLockRecursive() ", "output": "{\n\tfor _, client := range *cs {\n\t\tclient.RLockAnon()\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n)\n\nfunc main() {\n\ttests := [][][]int{{{4, 3, 2, -1}, {3, 2, 1, -1}, {1, 1, -1, -2}, {-1, -1, -2, -3}}, {{3, 2}, {1, 0}}, {{1, -1}, {-1, -1}}, {{-1}}}\n\n\tfor _, test := range tests {\n\t\tlog.Printf(\"countNegatives(%v) = %d\\n\", test, countNegatives(test))\n\t}\n}\n\n\n\nfunc countNegatives(grid [][]int) int ", "output": "{\n\tres := 0\n\n\tfor row := 0; row < len(grid); row++ {\n\t\tfor col := 0; col < len(grid[row]); col++ {\n\t\t\tif grid[row][col] < 0 {\n\t\t\t\tres++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/apier/v1\"\n\nfunc init() {\n\tc := &CmdRemoveActions{\n\t\tname: \"actions_remove\",\n\t\trpcMethod: \"ApierV1.RemoveActions\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdRemoveActions struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrRemoveActions\n\t*CommandExecuter\n}\n\nfunc (self *CmdRemoveActions) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdRemoveActions) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdRemoveActions) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrRemoveActions{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdRemoveActions) PostprocessRpcParams() error {\n\treturn nil\n}\n\n\n\nfunc (self *CmdRemoveActions) RpcResult() interface{} ", "output": "{\n\tvar s string\n\treturn &s\n}"} {"input": "package data\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com/go-ini/ini\"\n\t\"gopkg.in/mgo.v2\"\n)\n\n\ntype MongoConnection struct {\n\thost string\n\tport int\n\tuser string\n\tpass string\n\tname string\n}\n\n\nfunc NewMongoConnection() *MongoConnection {\n\n\tfileReader, err := ini.InsensitiveLoad(\"database.conf\")\n\tif err != nil {\n\t\tfmt.Println(\"database.conf not found\")\n\t\treturn nil\n\t}\n\n\tsection := fileReader.Section(\"MONGO\")\n\n\thost := section.Key(\"database.host\").Value()\n\tport := section.Key(\"database.port\").Value()\n\tuser := section.Key(\"database.user\").Value()\n\tpass := section.Key(\"database.pass\").Value()\n\tname := section.Key(\"database.name\").Value()\n\n\tmongoConn := new(MongoConnection)\n\n\tmongoConn.host = host\n\tmongoConn.port, _ = strconv.Atoi(port)\n\tmongoConn.user = user\n\tmongoConn.pass = pass\n\tmongoConn.name = name\n\n\treturn mongoConn\n\n}\n\n\n\n\nfunc (connection *MongoConnection) Connect() (*mgo.Session, error) ", "output": "{\n\n\tconnectionURL := connection.host + \":\" + strconv.Itoa(connection.port)\n\n\tdialInfo := new(mgo.DialInfo)\n\tdialInfo.Username = connection.user\n\tdialInfo.Password = connection.pass\n\tdialInfo.Addrs = []string{connectionURL}\n\tdialInfo.Database = connection.name\n\n\tsession, err := mgo.DialWithInfo(dialInfo)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsession.SetMode(mgo.Monotonic, true)\n\n\treturn session, nil\n}"} {"input": "package cli\n\n\ntype Command struct {\n\tName string\n\tDescription string\n\tAction Action\n}\n\n\ntype Commands []*Command\n\n\nfunc (c Commands) Len() int {\n\treturn len(c)\n}\n\n\nfunc (c Commands) Less(i, j int) bool {\n\treturn c[i].Name < c[j].Name\n}\n\n\nfunc (c Commands) Swap(i, j int) {\n\tc[i], c[j] = c[j], c[i]\n}\n\n\n\nfunc (c Commands) ActionForName(name string) Action ", "output": "{\n\tfor _, command := range c {\n\t\tif name == command.Name {\n\t\t\treturn command.Action\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"k8s.io/kubernetes/pkg/client/clientset_generated/clientset/typed/policy/v1beta1\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n\tcore \"k8s.io/kubernetes/pkg/client/testing/core\"\n)\n\ntype FakePolicyV1beta1 struct {\n\t*core.Fake\n}\n\n\n\nfunc (c *FakePolicyV1beta1) PodDisruptionBudgets(namespace string) v1beta1.PodDisruptionBudgetInterface {\n\treturn &FakePodDisruptionBudgets{c, namespace}\n}\n\n\n\nfunc (c *FakePolicyV1beta1) RESTClient() restclient.Interface {\n\tvar ret *restclient.RESTClient\n\treturn ret\n}\n\nfunc (c *FakePolicyV1beta1) Evictions(namespace string) v1beta1.EvictionInterface ", "output": "{\n\treturn &FakeEvictions{c, namespace}\n}"} {"input": "package queue\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Node struct {\n\tvalue interface{}\n\tnext *Node\n}\n\nfunc NewNode(value interface{}) *Node {\n\tnode := new(Node)\n\tnode.value = value\n\n\treturn node\n}\n\ntype Queue struct {\n\thead *Node\n\ttail *Node\n}\n\nfunc NewQueue(args ...interface{}) *Queue {\n\tlist := new(Queue)\n\n\tfor _, v := range args {\n\t\tlist.Enqueue(v)\n\t}\n\n\treturn list\n}\n\nfunc (q *Queue) String() string {\n\tnode := q.head\n\n\tvar values []string\n\n\tif node == nil {\n\t\treturn \"[]\"\n\t}\n\n\tfor node.next != nil {\n\t\tvalues = append(values, fmt.Sprintf(\"%v\", node.value))\n\n\t\tnode = node.next\n\t}\n\tvalues = append(values, fmt.Sprintf(\"%v\", node.value))\n\n\treturn fmt.Sprintf(\"[%s]\", strings.Join(values, \", \"))\n}\n\nfunc (q *Queue) Enqueue(value interface{}) {\n\tnewTail := NewNode(value)\n\n\tif q.head == nil {\n\t\tq.head = newTail\n\t\tq.tail = q.head\n\t} else {\n\t\tq.tail.next = newTail\n\t\tq.tail = newTail\n\t}\n}\n\nfunc (q *Queue) Dequeue() (value interface{}, ok bool) {\n\n\tif q.head == nil {\n\t\treturn 0, false\n\t} else {\n\t\tnode := q.head\n\t\tq.head = node.next\n\t\treturn node.value, true\n\t}\n}\n\nfunc (q *Queue) Peek() (value interface{}, ok bool) {\n\tif q.head == nil {\n\t\treturn 0, false\n\t} else {\n\t\treturn q.head.value, true\n\t}\n}\n\n\n\nfunc (q *Queue) Empty() bool ", "output": "{\n\tif q.head == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}"} {"input": "package datascience\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype UpdateModelRequest struct {\n\n\tModelId *string `mandatory:\"true\" contributesTo:\"path\" name:\"modelId\"`\n\n\tUpdateModelDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateModelRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request UpdateModelRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request UpdateModelRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype UpdateModelResponse struct {\n\n\tRawResponse *http.Response\n\n\tModel `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateModelResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateModelResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateModelRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package user\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/apimachinery/pkg/util/validation/field\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n\tpsputil \"k8s.io/kubernetes/pkg/security/podsecuritypolicy/util\"\n)\n\n\ntype mustRunAs struct {\n\topts *extensions.RunAsUserStrategyOptions\n}\n\n\n\n\n\nfunc (s *mustRunAs) Generate(pod *api.Pod, container *api.Container) (*int64, error) {\n\treturn &s.opts.Ranges[0].Min, nil\n}\n\n\nfunc (s *mustRunAs) Validate(fldPath *field.Path, _ *api.Pod, _ *api.Container, runAsNonRoot *bool, runAsUser *int64) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif runAsUser == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"runAsUser\"), \"\"))\n\t\treturn allErrs\n\t}\n\n\tif !s.isValidUID(*runAsUser) {\n\t\tdetail := fmt.Sprintf(\"must be in the ranges: %v\", s.opts.Ranges)\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"runAsUser\"), *runAsUser, detail))\n\t}\n\treturn allErrs\n}\n\nfunc (s *mustRunAs) isValidUID(id int64) bool {\n\tfor _, rng := range s.opts.Ranges {\n\t\tif psputil.UserFallsInRange(id, rng) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc NewMustRunAs(options *extensions.RunAsUserStrategyOptions) (RunAsUserStrategy, error) ", "output": "{\n\tif options == nil {\n\t\treturn nil, fmt.Errorf(\"MustRunAsRange requires run as user options\")\n\t}\n\tif len(options.Ranges) == 0 {\n\t\treturn nil, fmt.Errorf(\"MustRunAsRange requires at least one range\")\n\t}\n\treturn &mustRunAs{\n\t\topts: options,\n\t}, nil\n}"} {"input": "package building\n\nimport \"fmt\"\n\ntype Single struct {\n\tprefix string\n\toption string\n}\n\nfunc (s Single) IsPresent() bool {\n\treturn s.option != \"\"\n}\n\n\n\nfunc NewSingleBuilder(prefix, value string) Single {\n\treturn Single{prefix, value}\n}\n\nfunc (s Single) Build() string ", "output": "{\n\treturn fmt.Sprintf(\"%s %s\", s.prefix, s.option)\n}"} {"input": "package timer\n\nimport (\n\t\"container/heap\"\n\t\"time\"\n\n\t\"github.com/idealeak/goserver/core\"\n\t\"github.com/idealeak/goserver/core/basic\"\n)\n\ntype startTimerCommand struct {\n\tsrc *basic.Object\n\tta TimerAction\n\tud interface{}\n\tinterval time.Duration\n\ttimes int\n\th TimerHandle\n}\n\nfunc (stc *startTimerCommand) Done(o *basic.Object) error {\n\tdefer o.ProcessSeqnum()\n\n\tte := &TimerEntity{\n\t\tsink: stc.src,\n\t\tud: stc.ud,\n\t\tta: stc.ta,\n\t\tinterval: stc.interval,\n\t\ttimes: stc.times,\n\t\th: stc.h,\n\t\tnext: time.Now().Add(stc.interval),\n\t}\n\n\theap.Push(TimerModule.tq, te)\n\n\treturn nil\n}\n\n\nfunc StartTimer(ta TimerAction, ud interface{}, interval time.Duration, times int) (TimerHandle, bool) {\n\treturn StartTimerByObject(core.CoreObject(), ta, ud, interval, times)\n}\nfunc AfterTimer(taw TimerActionWrapper, ud interface{}, interval time.Duration) (TimerHandle, bool) {\n\tvar tac = &TimerActionCommon{\n\t\tTaw: taw,\n\t}\n\treturn StartTimerByObject(core.CoreObject(), tac, ud, interval, 1)\n}\n\n\n\nfunc StartTimerByObject(src *basic.Object, ta TimerAction, ud interface{}, interval time.Duration, times int) (TimerHandle, bool) ", "output": "{\n\th := generateTimerHandle()\n\tret := TimerModule.SendCommand(\n\t\t&startTimerCommand{\n\t\t\tsrc: src,\n\t\t\tta: ta,\n\t\t\tud: ud,\n\t\t\tinterval: interval,\n\t\t\ttimes: times,\n\t\t\th: h,\n\t\t},\n\t\ttrue)\n\treturn h, ret\n}"} {"input": "package dtls\n\nimport (\n\t\"encoding/binary\"\n)\n\n\ntype extensionValue uint16\n\nconst (\n\textensionSupportedEllipticCurvesValue extensionValue = 10\n\textensionSupportedPointFormatsValue extensionValue = 11\n\textensionUseSRTPValue extensionValue = 14\n)\n\ntype extension interface {\n\tMarshal() ([]byte, error)\n\tUnmarshal(data []byte) error\n\n\textensionValue() extensionValue\n}\n\nfunc decodeExtensions(buf []byte) ([]extension, error) {\n\tdeclaredLen := binary.BigEndian.Uint16(buf)\n\tif len(buf)-2 != int(declaredLen) {\n\t\treturn nil, errLengthMismatch\n\t}\n\n\textensions := []extension{}\n\tunmarshalAndAppend := func(data []byte, e extension) error {\n\t\terr := e.Unmarshal(data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\textensions = append(extensions, e)\n\t\treturn nil\n\t}\n\n\tfor offset := 2; offset < len(buf); {\n\t\tvar err error\n\t\tswitch extensionValue(binary.BigEndian.Uint16(buf[offset:])) {\n\t\tcase extensionSupportedEllipticCurvesValue:\n\t\t\terr = unmarshalAndAppend(buf[offset:], &extensionSupportedEllipticCurves{})\n\t\tcase extensionUseSRTPValue:\n\t\t\terr = unmarshalAndAppend(buf[offset:], &extensionUseSRTP{})\n\t\tdefault:\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\textensionLength := binary.BigEndian.Uint16(buf[offset+2:])\n\t\toffset += (4 + int(extensionLength))\n\t}\n\treturn extensions, nil\n}\n\n\n\nfunc encodeExtensions(e []extension) ([]byte, error) ", "output": "{\n\textensions := []byte{}\n\tfor _, e := range e {\n\t\traw, err := e.Marshal()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\textensions = append(extensions, raw...)\n\t}\n\tout := []byte{0x00, 0x00}\n\tbinary.BigEndian.PutUint16(out, uint16(len(extensions)))\n\treturn append(out, extensions...), nil\n}"} {"input": "package sftp\n\n\n\n\nimport \"os\"\n\n\n\ntype FileOpenFlags struct {\n\tRead, Write, Append, Creat, Trunc, Excl bool\n}\n\n\n\n\n\nfunc (r *Request) Pflags() FileOpenFlags {\n\treturn newFileOpenFlags(r.Flags)\n}\n\n\n\n\ntype FileAttrFlags struct {\n\tSize, UidGid, Permissions, Acmodtime bool\n}\n\nfunc newFileAttrFlags(flags uint32) FileAttrFlags {\n\treturn FileAttrFlags{\n\t\tSize: (flags & ssh_FILEXFER_ATTR_SIZE) != 0,\n\t\tUidGid: (flags & ssh_FILEXFER_ATTR_UIDGID) != 0,\n\t\tPermissions: (flags & ssh_FILEXFER_ATTR_PERMISSIONS) != 0,\n\t\tAcmodtime: (flags & ssh_FILEXFER_ATTR_ACMODTIME) != 0,\n\t}\n}\n\n\n\nfunc (r *Request) AttrFlags() FileAttrFlags {\n\treturn newFileAttrFlags(r.Flags)\n}\n\n\nfunc (a FileStat) FileMode() os.FileMode {\n\treturn os.FileMode(a.Mode)\n}\n\n\n\nfunc (r *Request) Attributes() *FileStat {\n\tfs, _ := getFileStat(r.Flags, r.Attrs)\n\treturn fs\n}\n\nfunc newFileOpenFlags(flags uint32) FileOpenFlags ", "output": "{\n\treturn FileOpenFlags{\n\t\tRead: flags&ssh_FXF_READ != 0,\n\t\tWrite: flags&ssh_FXF_WRITE != 0,\n\t\tAppend: flags&ssh_FXF_APPEND != 0,\n\t\tCreat: flags&ssh_FXF_CREAT != 0,\n\t\tTrunc: flags&ssh_FXF_TRUNC != 0,\n\t\tExcl: flags&ssh_FXF_EXCL != 0,\n\t}\n}"} {"input": "package data\n\nimport (\n\t\"goload/server/models\"\n\t\"github.com/boltdb/bolt\"\n\t\"encoding/json\"\n)\n\ntype Datastore struct {\n\tpackages map[string]*models.Package\n\tdb *bolt.DB\n}\n\nvar PACKAGES []byte = []byte(\"packages\")\n\nfunc NewDatastore(db *bolt.DB) *Datastore {\n\tdb.Update(func(tx *bolt.Tx)error {\n\t\ttx.CreateBucketIfNotExists(PACKAGES)\n\t\treturn nil\n\t})\n\treturn &Datastore{db:db,packages:make(map[string]*models.Package)}\n}\n\n\n\nfunc (ds *Datastore) SaveData() {\n\tds.db.Update(func(tx *bolt.Tx) error{\n\t\tb:= tx.Bucket(PACKAGES)\n\t\tfor k, value := range ds.packages {\n\t\t\tpackJson,_ := json.Marshal(value)\n\t\t\tb.Put([]byte(k),packJson)\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc (ds *Datastore) AddPackage(pack *models.Package) {\n\tds.packages[pack.Id] = pack\n}\n\nfunc (ds *Datastore) RemovePackage(id string) bool {\n\t_, exists := ds.packages[id]\n\tdelete(ds.packages, id)\n\tds.db.Update(func(tx *bolt.Tx) error{\n\t\tb:= tx.Bucket(PACKAGES)\n\t\tb.Delete([]byte(id))\n\t\treturn nil\n\t})\n\treturn exists\n\n}\n\nfunc (ds *Datastore) GetPackages() []*models.Package {\n\tvalues := make([]*models.Package, 0)\n\tfor _, value := range ds.packages {\n\t\tvalues = append(values, value)\n\t}\n\treturn values\n}\n\nfunc (ds *Datastore) GetPackage(id string) (pack *models.Package,exists bool) {\n\tpack,exists = ds.packages[id]\n\treturn\n}\n\nfunc (ds *Datastore) LoadData() ", "output": "{\n\tds.db.View(func(tx *bolt.Tx) error{\n\t\tb:= tx.Bucket(PACKAGES)\n\t\tb.ForEach(func(k,v []byte) error {\n\t\t\tpack := &models.Package{}\n\t\t\tjson.Unmarshal(v,pack)\n\t\t\tds.packages[pack.Id] = pack\n\t\t\treturn nil\n\t\t})\n\t\treturn nil\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"os/exec\"\n\t\"text/template\"\n\n\t\"github.com/golang/glog\"\n\tk8sexec \"k8s.io/kubernetes/pkg/util/exec\"\n)\n\nconst (\n\tnsdTmpl = `\n`\n)\n\ntype record struct {\n\tname string\n\tip net.IP\n}\n\ntype nsd struct {\n\tns []record\n\ta []record\n}\n\nfunc (k *nsd) WriteCfg(svcs []vip) error {\n\tw, err := os.Create(\"/etc/nsd/nsd.conf.\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer w.Close()\n\n\tt, err := template.New(\"nsd\").Parse(nsdTmpl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconf := make(map[string]interface{})\n\tconf[\"ns\"] = k.iface\n\tconf[\"a\"] = k.ip\n\n\tb, _ := json.Marshal(conf)\n\tglog.Infof(\"%v\", string(b))\n\n\treturn t.Execute(w, conf)\n}\n\n\n\nfunc (k *nsd) Reload() error {\n\tglog.Info(\"reloading nsd server\")\n\t_, err := k8sexec.New().Command(\"killall\", \"-1\", \"nsd\").CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reloading nsd: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (k *nsd) Start() ", "output": "{\n\tcmd := exec.Command(\"/usr/sbin/nsd\",\n\t\t\"-d\",\n\t\t\"-P\", \"/nsd.pid\")\n\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\tif err := cmd.Start(); err != nil {\n\t\tglog.Errorf(\"nsd error: %v\", err)\n\t}\n\n\tif err := cmd.Wait(); err != nil {\n\t\tglog.Fatalf(\"nsd error: %v\", err)\n\t}\n}"} {"input": "package decorators\n\nimport (\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/aws/aws-sdk-go/aws/awserr\"\n\t\"github.com/quintilesims/layer0/common/waitutils\"\n)\n\ntype Retry struct {\n\tClock waitutils.Clock\n}\n\n\n\nfunc (this *Retry) CallWithRetries(name string, call func() error) error {\n\tcheck := func() (bool, error) {\n\t\terr := call()\n\t\tif err == nil {\n\t\t\treturn true, nil\n\t\t} else if this.shouldRetry(err) {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn false, err\n\t}\n\n\tcallObject := &waitutils.Waiter{\n\t\tName: name,\n\t\tRetries: 20,\n\t\tDelay: 5 * time.Second,\n\t\tCheck: check,\n\t\tClock: this.Clock,\n\t}\n\n\treturn callObject.Wait()\n}\n\nfunc (this *Retry) shouldRetry(err error) bool ", "output": "{\n\tif err != nil {\n\t\tif awsErr, ok := err.(awserr.Error); ok {\n\t\t\tcode := awsErr.Code()\n\n\t\t\tif code == \"Throttling\" || code == \"ThrottlingException\" {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tmessage := strings.ToLower(awsErr.Message())\n\t\t\tif code == \"ClientException\" && strings.Contains(message, \"too many concurrent attempts\") {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package iso20022\n\n\ntype OriginalItem4 struct {\n\n\tOriginalItemIdentification *Max35Text `xml:\"OrgnlItmId\"`\n\n\tOriginalEndToEndIdentification *Max35Text `xml:\"OrgnlEndToEndId,omitempty\"`\n\n\tAmount *ActiveOrHistoricCurrencyAndAmount `xml:\"Amt\"`\n\n\tExpectedValueDate *ISODate `xml:\"XpctdValDt,omitempty\"`\n\n\tOriginalItemReference *OriginalItemReference3 `xml:\"OrgnlItmRef,omitempty\"`\n}\n\n\n\nfunc (o *OriginalItem4) SetOriginalEndToEndIdentification(value string) {\n\to.OriginalEndToEndIdentification = (*Max35Text)(&value)\n}\n\nfunc (o *OriginalItem4) SetAmount(value, currency string) {\n\to.Amount = NewActiveOrHistoricCurrencyAndAmount(value, currency)\n}\n\nfunc (o *OriginalItem4) SetExpectedValueDate(value string) {\n\to.ExpectedValueDate = (*ISODate)(&value)\n}\n\nfunc (o *OriginalItem4) AddOriginalItemReference() *OriginalItemReference3 {\n\to.OriginalItemReference = new(OriginalItemReference3)\n\treturn o.OriginalItemReference\n}\n\nfunc (o *OriginalItem4) SetOriginalItemIdentification(value string) ", "output": "{\n\to.OriginalItemIdentification = (*Max35Text)(&value)\n}"} {"input": "package utils\n\nimport (\n \"unsafe\"\n \"reflect\"\n)\n\n\nfunc ByteString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}\n\n\nfunc StringPointer(s string) unsafe.Pointer {\n\tp := (*reflect.StringHeader)(unsafe.Pointer(&s))\n\treturn unsafe.Pointer(p.Data)\n}\n\n\n\n\nfunc BytePointer(b []byte) unsafe.Pointer ", "output": "{\n\tp := (*reflect.SliceHeader)(unsafe.Pointer(&b))\n\treturn unsafe.Pointer(p.Data)\n}"} {"input": "package main\n\ntype ServerConfig struct {\n\tHost string\n\tUsername string\n\tPassword string\n\tDatabase string\n}\n\n\n\nfunc getServerConfig() ServerConfig ", "output": "{\n\treturn ServerConfig{\"127.0.0.1:3306\", \"username\", \"password\", \"database\"}\n}"} {"input": "package config\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/dnephin/configtf\"\n\tpth \"github.com/dnephin/configtf/path\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype ComposeConfig struct {\n\tFiles []string\n\tProject string `config:\"required\"`\n\tStopGrace int\n\tDependent\n\tAnnotations\n}\n\n\nfunc (c *ComposeConfig) StopGraceString() string {\n\treturn strconv.Itoa(c.StopGrace)\n}\n\n\nfunc (c *ComposeConfig) Validate(path pth.Path, config *Config) *pth.Error {\n\treturn nil\n}\n\n\n\n\nfunc (c *ComposeConfig) Resolve(resolver Resolver) (Resource, error) {\n\tconf := *c\n\tvar err error\n\tconf.Files, err = resolver.ResolveSlice(c.Files)\n\tif err != nil {\n\t\treturn &conf, err\n\t}\n\tconf.Project, err = resolver.Resolve(c.Project)\n\treturn &conf, err\n}\n\nfunc composeFromConfig(name string, values map[string]interface{}) (Resource, error) {\n\tcompose := &ComposeConfig{Project: \"{unique}\", StopGrace: 5}\n\treturn compose, configtf.Transform(name, values, compose)\n}\n\nfunc init() {\n\tRegisterResource(\"compose\", composeFromConfig)\n}\n\nfunc (c *ComposeConfig) String() string ", "output": "{\n\treturn fmt.Sprintf(\"Run Compose project %q from: %v\",\n\t\tc.Project, strings.Join(c.Files, \", \"))\n}"} {"input": "package context\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/Originate/exosphere/src/docker/tools\"\n\t\"github.com/Originate/exosphere/src/types\"\n\t\"github.com/moby/moby/client\"\n\t\"github.com/pkg/errors\"\n\tyaml \"gopkg.in/yaml.v2\"\n)\n\n\n\nfunc getExternalServiceConfig(dockerImage string) (types.ServiceConfig, error) ", "output": "{\n\tvar serviceConfig types.ServiceConfig\n\tc, err := client.NewEnvClient()\n\tif err != nil {\n\t\treturn serviceConfig, err\n\t}\n\tyamlFile, err := tools.CatFileInDockerImage(c, dockerImage, \"service.yml\")\n\tif err != nil {\n\t\treturn serviceConfig, err\n\t}\n\terr = yaml.Unmarshal(yamlFile, &serviceConfig)\n\tif err != nil {\n\t\treturn serviceConfig, errors.Wrap(err, fmt.Sprintf(\"Failed to unmarshal service.yml for '%s'\", dockerImage))\n\t}\n\treturn serviceConfig, serviceConfig.ValidateServiceConfig()\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/csv\"\n\t\"encoding/json\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"reflect\"\n\t\"time\"\n\n\t\"github.com/robfig/cron\"\n)\n\nconst hook = \"http://localhost:8065/hooks/pdusr3nmwfn4pyhrh83dixr1xo\"\nconst filePath = \"timetable.csv\"\n\n\ntype ChatMsg struct {\n\tText string `json:\"text\"`\n}\n\n\ntype CsvLoader struct {\n\tFilePath string\n\trows [][]string\n}\n\n\nfunc (l *CsvLoader) Load() ([][]string, bool) {\n\tfile, err := os.Open(l.FilePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\trows, csvErr := csv.NewReader(file).ReadAll()\n\tif csvErr != nil {\n\t\tpanic(csvErr)\n\t}\n\n\tdiffers := !reflect.DeepEqual(rows, l.rows)\n\tl.rows = rows\n\n\treturn rows, differs\n}\n\n\n\nfunc main() {\n\tloader := &CsvLoader{FilePath: filePath}\n\tcronJobs := &cron.Cron{}\n\n\tfor true {\n\t\tcsv, differs := loader.Load()\n\n\t\tif differs {\n\t\t\tcronJobs.Stop()\n\t\t\tcronJobs = cron.New()\n\t\t\tfor _, task := range csv {\n\t\t\t\tcronErr := cronJobs.AddFunc(task[0], func() { remind(task[1]) })\n\t\t\t\tif cronErr != nil {\n\t\t\t\t\tpanic(cronErr)\n\t\t\t\t}\n\t\t\t}\n\t\t\tcronJobs.Start()\n\t\t}\n\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}\n\nfunc remind(text string) ", "output": "{\n\tjsonMsg, _ := json.Marshal(&ChatMsg{text})\n\tmsgReader := bytes.NewReader(jsonMsg)\n\tclient := &http.Client{}\n\tr, _ := client.Post(hook, \"application/json\", msgReader)\n\tlog.Println(r.StatusCode, r.Header[\"X-Request-Id\"][0], string(jsonMsg))\n}"} {"input": "package userpass\n\nimport (\n\t\"github.com/hashicorp/vault/logical\"\n\t\"github.com/hashicorp/vault/logical/framework\"\n)\n\n\n\nfunc Backend() *framework.Backend {\n\tvar b backend\n\tb.Backend = &framework.Backend{\n\t\tHelp: backendHelp,\n\n\t\tPathsSpecial: &logical.Paths{\n\t\t\tRoot: []string{\n\t\t\t\t\"users/*\",\n\t\t\t},\n\n\t\t\tUnauthenticated: []string{\n\t\t\t\t\"login/*\",\n\t\t\t},\n\t\t},\n\n\t\tPaths: append([]*framework.Path{\n\t\t\tpathLogin(&b),\n\t\t\tpathUsers(&b),\n\t\t}),\n\n\t\tAuthRenew: b.pathLoginRenew,\n\t}\n\n\treturn b.Backend\n}\n\ntype backend struct {\n\t*framework.Backend\n}\n\nconst backendHelp = `\nThe \"userpass\" credential provider allows authentication using\na combination of a username and password. No additional factors\nare supported.\n\nThe username/password combination is configured using the \"users/\"\nendpoints by a user with root access. Authentication is then done\nby suppying the two fields for \"login\".\n`\n\nfunc Factory(conf *logical.BackendConfig) (logical.Backend, error) ", "output": "{\n\treturn Backend().Setup(conf)\n}"} {"input": "package pgxlog\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/flynn/flynn/pkg/sirenia/xlog\"\n)\n\nconst Zero xlog.Position = \"0/00000000\"\n\ntype PgXLog struct{}\n\nfunc (p PgXLog) Zero() xlog.Position {\n\treturn Zero\n}\n\n\nfunc (p PgXLog) Increment(pos xlog.Position, increment int) (xlog.Position, error) {\n\tparts, err := parse(pos)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn makePosition(parts[0], parts[1]+increment), nil\n}\n\n\n\n\n\n\n\n\n\nfunc parse(xlog xlog.Position) (res [2]int, err error) {\n\tparts := strings.SplitN(string(xlog), \"/\", 2)\n\tif len(parts) != 2 {\n\t\terr = fmt.Errorf(\"malformed xlog position %q\", xlog)\n\t\treturn\n\t}\n\n\tres[0], err = parseHex(parts[0])\n\tif err != nil {\n\t\treturn\n\t}\n\tres[1], err = parseHex(parts[1])\n\n\treturn\n}\n\n\n\nfunc makePosition(filepart int, offset int) xlog.Position {\n\treturn xlog.Position(fmt.Sprintf(\"%X/%08X\", filepart, offset))\n}\n\nfunc parseHex(s string) (int, error) {\n\tres, err := strconv.ParseInt(s, 16, 64)\n\treturn int(res), err\n}\n\nfunc (p PgXLog) Compare(xlog1, xlog2 xlog.Position) (int, error) ", "output": "{\n\tp1, err := parse(xlog1)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tp2, err := parse(xlog2)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif p1[0] == p2[0] && p1[1] == p2[1] {\n\t\treturn 0, nil\n\t}\n\tif p1[0] > p2[0] || p1[0] == p2[0] && p1[1] > p2[1] {\n\t\treturn 1, nil\n\t}\n\treturn -1, nil\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/mexisme/go-config/settings\"\n)\n\n\nfunc AddConfigItems(configKeys []string) {\n\tsettings.AddConfigItems(configKeys)\n}\n\n\nfunc AddConfigItemsWithPFlags(configKeys []string) error {\n\treturn settings.AddConfigItemsWithPFlags(configKeys)\n}\n\n\nfunc ApplyWith(key string, f func(interface{})) {\n\tsettings.ApplyWith(key, f)\n}\n\n\nfunc Get(key string) interface{} {\n\treturn settings.Get(key)\n}\n\n\nfunc GetBool(key string) bool {\n\treturn settings.GetBool(key)\n}\n\n\nfunc GetFloat64(key string) float64 {\n\treturn settings.GetFloat64(key)\n}\n\n\nfunc GetInt(key string) int {\n\treturn settings.GetInt(key)\n}\n\n\nfunc GetString(key string) string {\n\treturn settings.GetString(key)\n}\n\n\nfunc GetStringMap(key string) map[string]interface{} {\n\treturn settings.GetStringMap(key)\n}\n\n\nfunc GetStringMapString(key string) map[string]string {\n\treturn settings.GetStringMapString(key)\n}\n\n\n\n\n\nfunc GetTime(key string) time.Time {\n\treturn settings.GetTime(key)\n}\n\n\nfunc GetDuration(key string) time.Duration {\n\treturn settings.GetDuration(key)\n}\n\n\nfunc IsSet(key string) bool {\n\treturn settings.IsSet(key)\n}\n\n\nfunc AllSettings() map[string]interface{} {\n\treturn settings.AllSettings()\n}\n\nfunc GetStringSlice(key string) []string ", "output": "{\n\treturn settings.GetStringSlice(key)\n}"} {"input": "package sync2\n\n\n\n\n\nimport (\n\t\"time\"\n)\n\n\n\ntype Semaphore struct {\n\tslots chan struct{}\n\ttimeout time.Duration\n}\n\n\n\nfunc NewSemaphore(count int, timeout time.Duration) *Semaphore {\n\tsem := &Semaphore{\n\t\tslots: make(chan struct{}, count),\n\t\ttimeout: timeout,\n\t}\n\tfor i := 0; i < count; i++ {\n\t\tsem.slots <- struct{}{}\n\t}\n\treturn sem\n}\n\n\n\nfunc (sem *Semaphore) Acquire() bool {\n\tif sem.timeout == 0 {\n\t\t<-sem.slots\n\t\treturn true\n\t}\n\tselect {\n\tcase <-sem.slots:\n\t\treturn true\n\tcase <-time.After(sem.timeout):\n\t\treturn false\n\t}\n}\n\n\n\n\n\n\nfunc (sem *Semaphore) Release() ", "output": "{\n\tsem.slots <- struct{}{}\n}"} {"input": "package tree\n\ntype Binary struct {\n\tscore int\n\tvalue interface{}\n\n\tleft, right *Binary\n}\n\n\n\nfunc (t *Binary) Add(score int, value interface{}, replace bool) {\n\troot := t\n\tfor {\n\t\tswitch {\n\t\tcase root.score == score:\n\t\t\tif replace {\n\t\t\t\troot.value = value\n\t\t\t}\n\t\t\treturn\n\t\tcase root.score > score:\n\t\t\tif root.left == nil {\n\t\t\t\troot.left = &Binary{score: score, value: value}\n\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\troot = root.left\n\t\t\t}\n\t\tcase root.score < score:\n\t\t\tif root.right == nil {\n\t\t\t\troot.right = &Binary{score: score, value: value}\n\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\troot = root.right\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (t *Binary) Search(score int) interface{} ", "output": "{\n\troot := t\n\tfor root != nil {\n\t\tswitch {\n\t\tcase root.score == score:\n\t\t\treturn root.value\n\t\tcase root.score > score:\n\t\t\troot = root.left\n\t\tcase root.score < score:\n\t\t\troot = root.right\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package exif\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\n\nfunc toUint16(bo binary.ByteOrder, buf []byte) uint16 {\n\tvar i uint16\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}\n\n\nfunc toInt16(bo binary.ByteOrder, buf []byte) int16 {\n\tvar i int16\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}\n\n\n\n\n\nfunc toInt32(bo binary.ByteOrder, buf []byte) int32 {\n\tvar i int32\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}\n\nfunc toUint32(bo binary.ByteOrder, buf []byte) uint32 ", "output": "{\n\tvar i uint32\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetServiceRequest struct {\n\n\tServiceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"serviceId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetServiceRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request GetServiceRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request GetServiceRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetServiceRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetServiceResponse struct {\n\n\tRawResponse *http.Response\n\n\tService `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response GetServiceResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response GetServiceResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package sale\n\nimport \"go2o/src/core/domain/interface/valueobject\"\n\n\n\n\n\nfunc ParseToValueGoods(v *valueobject.Goods) *ValueGoods {\n\treturn &ValueGoods{\n\t\tId: v.GoodsId,\n\t\tItemId: v.Item_Id,\n\t\tIsPresent: v.IsPresent,\n\t\tSkuId: v.SkuId,\n\t\tPromotionFlag: v.PromotionFlag,\n\t\tStockNum: v.StockNum,\n\t\tSaleNum: v.SaleNum,\n\t\tSalePrice: v.SalePrice,\n\t\tPromPrice: v.PromPrice,\n\t\tPrice: v.Price,\n\t}\n}\n\nfunc ParseToPartialValueItem(v *valueobject.Goods) *ValueItem ", "output": "{\n\treturn &ValueItem{\n\t\tId: v.Item_Id,\n\t\tCategoryId: v.CategoryId,\n\t\tName: v.Name,\n\t\tGoodsNo: v.GoodsNo,\n\t\tImage: v.Image,\n\t\tPrice: v.Price,\n\t\tSalePrice: v.SalePrice,\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"errors\"\n\t\"github.com/manythumbed/gegenstand/packets\"\n\t\"github.com/manythumbed/gegenstand/protocol\"\n\t\"io\"\n\t\"net\"\n)\n\ntype Message interface {\n}\n\ntype MessageHandler interface {\n\tHandle(message Message)\n}\n\ntype Connection interface {\n\tConnect() error\n\tDisconnect() error\n\tUnsubscribe(topics ...string) error\n\tSubscribe(handler MessageHandler, topics ...protocol.Subscription) error\n\tPublish(topic string, qos protocol.Qos, retained bool, payload []byte) error\n}\n\ntype dummy struct {\n\tconnected bool\n\tconn net.Conn\n}\n\nfunc (d *dummy) Connect() error {\n\tif d.connected {\n\t\treturn errors.New(\"Already connected\")\n\t}\n\n\n\n\td.connected = true\n\treturn nil\n}\n\nfunc (d *dummy) Disconnect() error {\n\tif !d.connected {\n\t\treturn errors.New(\"Not connected\")\n\t}\n\n\terr := disconnect(d.conn)\n\terr = d.conn.Close()\n\n\td.connected = false\n\treturn err\n}\n\n\n\nfunc disconnect(w io.Writer) error ", "output": "{\n\t_, err := w.Write(packets.WriteDisconnect())\n\n\treturn err\n}"} {"input": "package tcplisten\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nconst (\n\tsoReusePort = 0x0F\n\ttcpFastOpen = 0x17\n)\n\n\n\nfunc enableFastOpen(fd int) error {\n\tif err := syscall.SetsockoptInt(fd, syscall.SOL_TCP, tcpFastOpen, fastOpenQlen); err != nil {\n\t\treturn fmt.Errorf(\"cannot enable TCP_FASTOPEN(qlen=%d): %s\", fastOpenQlen, err)\n\t}\n\treturn nil\n}\n\nconst fastOpenQlen = 16 * 1024\n\nfunc soMaxConn() (int, error) {\n\tdata, err := ioutil.ReadFile(soMaxConnFilePath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn syscall.SOMAXCONN, nil\n\t\t}\n\t\treturn -1, err\n\t}\n\ts := strings.TrimSpace(string(data))\n\tn, err := strconv.Atoi(s)\n\tif err != nil || n <= 0 {\n\t\treturn -1, fmt.Errorf(\"cannot parse somaxconn %q read from %s: %s\", s, soMaxConnFilePath, err)\n\t}\n\n\tif n > 1<<16-1 {\n\t\tn = 1<<16 - 1\n\t}\n\treturn n, nil\n}\n\nconst soMaxConnFilePath = \"/proc/sys/net/core/somaxconn\"\n\nfunc enableDeferAccept(fd int) error ", "output": "{\n\tif err := syscall.SetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_DEFER_ACCEPT, 1); err != nil {\n\t\treturn fmt.Errorf(\"cannot enable TCP_DEFER_ACCEPT: %s\", err)\n\t}\n\treturn nil\n}"} {"input": "package syscall\n\n\n\nfunc setTimeval(sec, usec int64) Timeval {\n\treturn Timeval{Sec: sec, Usec: usec}\n}\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint64(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint64(length)\n}\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\n\nconst RTM_LOCK = 0x8\n\n\n\nconst SYS___SYSCTL = SYS_SYSCTL\n\nfunc setTimespec(sec, nsec int64) Timespec ", "output": "{\n\treturn Timespec{Sec: sec, Nsec: nsec}\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/robfig/revel\"\n\t\"github.com/robfig/revel/samples/chat/app/chatroom\"\n\t\"github.com/robfig/revel/samples/chat/app/routes\"\n)\n\ntype Refresh struct {\n\t*revel.Controller\n}\n\nfunc (c Refresh) Index(user string) revel.Result {\n\tchatroom.Join(user)\n\treturn c.Redirect(routes.Refresh.Room(user))\n}\n\nfunc (c Refresh) Room(user string) revel.Result {\n\tsubscription := chatroom.Subscribe()\n\tdefer subscription.Cancel()\n\tevents := subscription.Archive\n\tfor i, _ := range events {\n\t\tif events[i].User == user {\n\t\t\tevents[i].User = \"you\"\n\t\t}\n\t}\n\treturn c.Render(user, events)\n}\n\nfunc (c Refresh) Say(user, message string) revel.Result {\n\tchatroom.Say(user, message)\n\treturn c.Redirect(routes.Refresh.Room(user))\n}\n\n\n\nfunc (c Refresh) Leave(user string) revel.Result ", "output": "{\n\tchatroom.Leave(user)\n\treturn c.Redirect(Application.Index)\n}"} {"input": "package sorts\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestSortK(t *testing.T) {\n\tarr3 := []int{4, 7, 0, 2, 1, 3, 9, 6}\n\tk := SortK(arr3, 5)\n\tif k != 6 {\n\t\tt.Errorf(\"SortK expect 6 , got %d\", k)\n\t}\n}\n\nfunc TestQuickSort(t *testing.T) ", "output": "{\n\tarr := []int{5, 2, 4, 7, 1, 3, 2, 6}\n\tQuickSort(arr, 0, len(arr)-1)\n\tfor i:=0;i arr[i+1] {\n\t\t\tt.Errorf(\"QuickSort order is incorrect, got %v\", arr)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"net/http\"\n)\n\nfunc PingHandler(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"PONG!\"})\n}\n\nfunc GetAllStats(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"statistics go here\"})\n}\n\nfunc GetAllImages(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"all images go here\"})\n}\n\n\n\nfunc CreateImage(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"ID of the image we created goes here\"})\n}\n\nfunc UpdateImage(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"ID of the image we updated goes here\"})\n}\n\nfunc GetImage(c *gin.Context) ", "output": "{\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"one image goes here\"})\n}"} {"input": "package gospec\n\nimport (\n\t\"fmt\"\n\tfilepath \"path\"\n\t\"runtime\"\n)\n\ntype Location struct {\n\tname string\n\tfile string\n\tline int\n}\n\nfunc currentLocation() *Location {\n\treturn newLocation(1)\n}\n\nfunc callerLocation() *Location {\n\treturn newLocation(2)\n}\n\n\n\nfunc locationForPC(pc uintptr) *Location {\n\tpc = pcOfWhereCallWasMade(pc)\n\tf := runtime.FuncForPC(pc)\n\tname := f.Name()\n\tfile, line := f.FileLine(pc)\n\treturn &Location{name, file, line}\n}\n\n\n\n\n\n\n\n\nfunc pcOfWhereCallWasMade(pcOfWhereCallReturnsTo uintptr) uintptr {\n\treturn pcOfWhereCallReturnsTo - 1\n}\n\nfunc (this *Location) Name() string { return this.name }\nfunc (this *Location) File() string { return this.file }\nfunc (this *Location) FileName() string { return filename(this.file) }\nfunc (this *Location) Line() int { return this.line }\n\nfunc filename(path string) string {\n\t_, file := filepath.Split(path)\n\treturn file\n}\n\nfunc (this *Location) equals(that *Location) bool {\n\treturn this.name == that.name &&\n\t\tthis.file == that.file &&\n\t\tthis.line == that.line\n}\n\nfunc (this *Location) String() string {\n\treturn fmt.Sprintf(\"%v:%v\", this.FileName(), this.Line())\n}\n\nfunc newLocation(n int) *Location ", "output": "{\n\tif pc, _, _, ok := runtime.Caller(n + 1); ok {\n\t\treturn locationForPC(pc)\n\t}\n\treturn nil\n}"} {"input": "package commands\n\nimport (\n \"github.com/spf13/cobra\"\n \"github.com/YusukeKomatsu/honoka\"\n \"github.com/davecgh/go-spew/spew\"\n)\n\nvar (\n listCmd = &cobra.Command{\n Use: \"list\",\n Short: \"Retrive cache index list\",\n Long: \"Retrive cache index list (not include cache data). If you get cache, use get method\",\n Run: listCommand,\n }\n)\n\n\n\nfunc init() {\n RootCmd.AddCommand(listCmd)\n}\n\nfunc listCommand(cmd *cobra.Command, args []string) ", "output": "{\n cli, err := honoka.New()\n if err != nil {\n Exit(err)\n }\n\n list, err := cli.List()\n if err != nil {\n Exit(err)\n }\n spew.Dump(list);\n}"} {"input": "package circonusgometrics\n\nimport (\n\t\"sync\"\n\n\t\"github.com/circonus-labs/circonusllhist\"\n)\n\n\ntype Histogram struct {\n\tname string\n\thist *circonusllhist.Histogram\n\trw sync.RWMutex\n}\n\n\nfunc (m *CirconusMetrics) Timing(metric string, val float64) {\n\tm.SetHistogramValue(metric, val)\n}\n\n\nfunc (m *CirconusMetrics) RecordValue(metric string, val float64) {\n\tm.SetHistogramValue(metric, val)\n}\n\n\nfunc (m *CirconusMetrics) SetHistogramValue(metric string, val float64) {\n\tm.NewHistogram(metric)\n\n\tm.histograms[metric].rw.Lock()\n\tdefer m.histograms[metric].rw.Unlock()\n\n\tm.histograms[metric].hist.RecordValue(val)\n}\n\n\nfunc (m *CirconusMetrics) RemoveHistogram(metric string) {\n\tm.hm.Lock()\n\tdefer m.hm.Unlock()\n\tdelete(m.histograms, metric)\n}\n\n\nfunc (m *CirconusMetrics) NewHistogram(metric string) *Histogram {\n\tm.hm.Lock()\n\tdefer m.hm.Unlock()\n\n\tif hist, ok := m.histograms[metric]; ok {\n\t\treturn hist\n\t}\n\n\thist := &Histogram{\n\t\tname: metric,\n\t\thist: circonusllhist.New(),\n\t}\n\n\tm.histograms[metric] = hist\n\n\treturn hist\n}\n\n\nfunc (h *Histogram) Name() string {\n\treturn h.name\n}\n\n\n\n\nfunc (h *Histogram) RecordValue(v float64) ", "output": "{\n\th.rw.Lock()\n\tdefer h.rw.Unlock()\n\n\th.hist.RecordValue(v)\n}"} {"input": "package runcmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t\"github.com/visualfc/gotools/pkg/command\"\n)\n\nvar Command = &command.Command{\n\tRun: runCmd,\n\tUsageLine: \"runcmd [-w work_path] [arguments...]\",\n\tShort: \"run program\",\n\tLong: `run program and arguments`,\n}\n\nvar execWorkPath string\nvar execWaitEnter bool\n\n\n\nfunc runCmd(cmd *command.Command, args []string) error {\n\tif len(args) == 0 {\n\t\tcmd.Usage()\n\t\treturn os.ErrInvalid\n\t}\n\tif execWorkPath == \"\" {\n\t\tvar err error\n\t\texecWorkPath, err = os.Getwd()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfileName := args[0]\n\n\tfilePath, err := exec.LookPath(fileName)\n\tif err != nil {\n\t\tfilePath, err = exec.LookPath(\"./\" + fileName)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Starting Process\", filePath, strings.Join(args[1:], \" \"), \"...\")\n\n\tcommand := exec.Command(filePath, args[1:]...)\n\tcommand.Dir = execWorkPath\n\tcommand.Stdin = os.Stdin\n\tcommand.Stdout = os.Stdout\n\tcommand.Stderr = os.Stderr\n\n\terr = command.Run()\n\n\tif err != nil {\n\t\tfmt.Println(\"\\nEnd Process\", err)\n\t} else {\n\t\tfmt.Println(\"\\nEnd Process\", \"exit status 0\")\n\t}\n\n\texitWaitEnter()\n\treturn nil\n}\n\nfunc exitWaitEnter() {\n\tif !execWaitEnter {\n\t\treturn\n\t}\n\tfmt.Println(\"\\nPress enter key to continue\")\n\tvar s = [256]byte{}\n\tos.Stdin.Read(s[:])\n}\n\nfunc init() ", "output": "{\n\tCommand.Flag.StringVar(&execWorkPath, \"w\", \"\", \"work path\")\n\tCommand.Flag.BoolVar(&execWaitEnter, \"e\", true, \"wait enter and continue\")\n}"} {"input": "package main\n\nvar (\n\tmtx [][]int\n)\n\n\n\n\nfunc min(x int, y int) int {\n\tif x < y {\n\t\treturn x\n\t} else {\n\t\treturn y\n\t}\n}\n\nfunc sum(arr []int) int ", "output": "{\n\ts := 0\n\tfor i := range arr {\n\t\tfor j := i; j < len(arr); j++ {\n\t\t\ts += mtx[i][j]\n\t\t}\n\t}\n\treturn s\n}"} {"input": "package stick\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"go.mongodb.org/mongo-driver/bson\"\n)\n\n\ntype Coding string\n\n\nconst (\n\tJSON Coding = \"json\"\n\tBSON Coding = \"bson\"\n)\n\n\nfunc (c Coding) Marshal(in interface{}) ([]byte, error) {\n\tswitch c {\n\tcase JSON:\n\t\treturn json.Marshal(in)\n\tcase BSON:\n\t\treturn bson.Marshal(in)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"coal: unknown coding %q\", c))\n\t}\n}\n\n\nfunc (c Coding) Unmarshal(in []byte, out interface{}) error {\n\tswitch c {\n\tcase JSON:\n\t\treturn json.Unmarshal(in, out)\n\tcase BSON:\n\t\treturn bson.Unmarshal(in, out)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"coal: unknown coding %q\", c))\n\t}\n}\n\n\n\n\n\nfunc GetJSONKey(field *reflect.StructField) string {\n\ttag := field.Tag.Get(\"json\")\n\n\tif tag == \"-\" {\n\t\treturn \"\"\n\t}\n\n\tvalues := strings.Split(tag, \",\")\n\n\tif len(values) > 0 && len(values[0]) > 0 {\n\t\treturn values[0]\n\t}\n\n\treturn field.Name\n}\n\n\nfunc GetBSONKey(field *reflect.StructField) string {\n\ttag := field.Tag.Get(\"bson\")\n\n\tif tag == \"-\" {\n\t\treturn \"\"\n\t}\n\n\tvalues := strings.Split(tag, \",\")\n\n\tif len(values) > 0 && len(values[0]) > 0 {\n\t\treturn values[0]\n\t}\n\n\treturn strings.ToLower(field.Name)\n}\n\nfunc (c Coding) Transfer(in, out interface{}) error ", "output": "{\n\tbytes, err := c.Marshal(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.Unmarshal(bytes, out)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package nogo\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype mapBackedRoleRepository struct {\n\troleMap map[string]Role\n}\n\nfunc NewMapBackedRoleRepository() RoleRepository {\n\treturn &mapBackedRoleRepository{roleMap: make(map[string]Role)}\n}\n\nfunc (this *mapBackedRoleRepository) FindAll() ([]Role, error) {\n\tret := make([]Role, 0)\n\tfor _, role := range this.roleMap {\n\t\tret = append(ret, role)\n\t}\n\treturn ret, nil\n}\n\nfunc (this *mapBackedRoleRepository) FindRole(roleName string) (Role, error) {\n\tif role, ok := this.roleMap[roleName]; ok {\n\t\treturn role, nil\n\t}\n\treturn nil, errors.New(fmt.Sprintf(\"Could not find role %v\", roleName))\n}\n\nfunc (this *mapBackedRoleRepository) CreateRole(role Role) error {\n\tif _, ok := this.roleMap[role.GetName()]; ok {\n\t\treturn errors.New(fmt.Sprintf(\"Error creating role. Role %v already exists\", role.GetName()))\n\t}\n\tthis.roleMap[role.GetName()] = role\n\treturn nil\n}\n\nfunc (this *mapBackedRoleRepository) UpdateRole(role Role) error {\n\tif _, ok := this.roleMap[role.GetName()]; ok {\n\t\tthis.roleMap[role.GetName()] = role\n\t\treturn nil\n\t}\n\treturn errors.New(fmt.Sprintf(\"Error updating role. Role %v does not exist.\", role.GetName()))\n}\n\n\n\nfunc (this *mapBackedRoleRepository) DeleteRole(roleName string) error ", "output": "{\n\tif _, ok := this.roleMap[roleName]; ok {\n\t\tdelete(this.roleMap, roleName)\n\t}\n\treturn errors.New(fmt.Sprintf(\"Error deleting role. Role %v does not exist.\", roleName))\n}"} {"input": "package goro\n\nimport \"regexp\"\nimport \"net/http\"\n\n\ntype Goro struct {\n\tRequest *http.Request\n\tResponseWriter *http.ResponseWriter\n\tResponse *Response\n\tRoutes []Route\n\tConfig ConfigRegistry\n\tSession *Session\n}\n\n\nfunc (self *Goro) SetRoutes(routes []Route) {\n\tself.Routes = routes\n}\n\n\nfunc (self *Goro) SetParams(items []ConfigItem) {\n\tregistry := ConfigRegistry{Items: items}\n\tself.Config = registry\n}\n\n\nfunc (self *Goro) LoadSession() {\n\tvar uuid string\n\tsessionName := self.Config.Get(\"SESSION_NAME\").(string)\n\tsessionCookie, err := self.Request.Cookie(sessionName)\n\n\tif err != nil {\n\t\tuuid = GenerateUUID()\n\t} else {\n\t\tuuid = sessionCookie.Value\n\t}\n\n\tsession := &Session{Id: uuid, Framework: self}\n\n\tself.Session = session\n\tself.Session.Load()\n}\n\n\nfunc (self *Goro) DumpSession() {\n\tself.Session.Dump()\n}\n\n\nfunc (self *Goro) Run() {\n\tself.run()\n}\n\n\n\n\n\nfunc (self *Goro) Write(s string) {\n\tself.Response.Write(s)\n}\n\n\nfunc (self *Goro) WriteLine(s string) {\n\tself.Response.WriteLine(s)\n}\n\n\nfunc (self *Goro) Redirect(url string) {\n\thttp.Redirect(*self.ResponseWriter, self.Request, url, http.StatusOK)\n}\n\nfunc (self *Goro) run() ", "output": "{\n\tvar handler func(*Goro)\n\tfindedRoute := false\n\troutes := self.Routes\n\tqueryString := self.Request.URL.Path\n\n\tself.Response = &Response{}\n\n\tfor _, route := range routes {\n\t\tif matched, _ := regexp.MatchString(route.Url, queryString); matched == true {\n\t\t\thandler = route.Handler\n\t\t\tfindedRoute = true\n\t\t}\n\t}\n\n\tif !findedRoute {\n\t\thandler = func(f *Goro) {\n\t\t}\n\t}\n\n\thandler(self)\n\tself.Response.Flush(*self.ResponseWriter)\n}"} {"input": "package fsrateio\n\nimport (\n\t\"io\"\n\n\t\"github.com/Symantec/Dominator/lib/rateio\"\n\t\"github.com/Symantec/tricorder/go/tricorder\"\n\t\"github.com/Symantec/tricorder/go/tricorder/units\"\n)\n\ntype ReaderContext struct {\n\tmaxBytesPerSecond uint64\n\tmaxBlocksPerSecond uint64\n\tctx *rateio.ReaderContext\n}\n\nfunc NewReaderContext(maxBytesPerSecond uint64,\n\tmaxBlocksPerSecond uint64, speedPercent uint64) *ReaderContext {\n\treturn newReaderContext(maxBytesPerSecond, maxBlocksPerSecond, speedPercent)\n}\n\nfunc (ctx *ReaderContext) GetContext() *rateio.ReaderContext { return ctx.ctx }\n\n\n\nfunc (ctx *ReaderContext) RegisterMetrics(dir *tricorder.DirectorySpec) error {\n\tif ctx.maxBlocksPerSecond > 0 {\n\t\treturn ctx.ctx.RegisterMetrics(dir, units.None,\n\t\t\t\"file-system speed in blocks per second\")\n\t}\n\treturn ctx.ctx.RegisterMetrics(dir, units.BytePerSecond,\n\t\t\"file-system speed\")\n}\n\nfunc (ctx *ReaderContext) String() string {\n\treturn ctx.format()\n}\n\nfunc (ctx *ReaderContext) NewReader(rd io.Reader) *rateio.Reader ", "output": "{\n\treturn ctx.ctx.NewReader(rd)\n}"} {"input": "package event\n\nimport (\n\t\"github.com/hyperledger/fabric-protos-go/gateway\"\n\t\"github.com/hyperledger/fabric-protos-go/peer\"\n\t\"github.com/hyperledger/fabric/common/ledger\"\n)\n\ntype ChaincodeEventsIterator struct {\n\tblockIter *BlockIterator\n}\n\n\n\nfunc (iter *ChaincodeEventsIterator) Next() (*gateway.ChaincodeEventsResponse, error) {\n\tfor {\n\t\tresult, err := iter.nextBlock()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(result.Events) > 0 {\n\t\t\treturn result, nil\n\t\t}\n\t}\n}\n\nfunc (iter *ChaincodeEventsIterator) nextBlock() (*gateway.ChaincodeEventsResponse, error) {\n\tblock, err := iter.blockIter.Next()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tevents, err := chaincodeEventsFromBlock(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := &gateway.ChaincodeEventsResponse{\n\t\tBlockNumber: block.Number(),\n\t\tEvents: events,\n\t}\n\treturn result, nil\n}\n\nfunc chaincodeEventsFromBlock(block *Block) ([]*peer.ChaincodeEvent, error) {\n\ttransactions, err := block.Transactions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar results []*peer.ChaincodeEvent\n\n\tfor _, transaction := range transactions {\n\t\tif !transaction.Valid() {\n\t\t\tcontinue\n\t\t}\n\n\t\tevents, err := transaction.ChaincodeEvents()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, event := range events {\n\t\t\tresults = append(results, event.ProtoMessage())\n\t\t}\n\t}\n\n\treturn results, nil\n}\n\nfunc (iter *ChaincodeEventsIterator) Close() {\n\titer.blockIter.Close()\n}\n\nfunc NewChaincodeEventsIterator(iterator ledger.ResultsIterator) *ChaincodeEventsIterator ", "output": "{\n\treturn &ChaincodeEventsIterator{\n\t\tblockIter: NewBlockIterator(iterator),\n\t}\n}"} {"input": "package commands\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"k8s.io/kops\"\n\t\"k8s.io/kops/cmd/kops/util\"\n)\n\ntype VersionOptions struct {\n\tShort bool\n}\n\n\n\n\nfunc RunVersion(f *util.Factory, out io.Writer, options *VersionOptions) error ", "output": "{\n\tvar s string\n\tif options.Short {\n\t\ts = kops.Version\n\t} else {\n\t\ts = \"Version \" + kops.Version\n\t\tif kops.GitVersion != \"\" {\n\t\t\ts += \" (git-\" + kops.GitVersion + \")\"\n\t\t}\n\t}\n\n\t_, err := fmt.Fprintf(out, \"%s\\n\", s)\n\treturn err\n}"} {"input": "package types\n\nimport \"fmt\"\n\ntype KeywordValue struct {\n\tValue string\n}\n\nfunc (v *KeywordValue) ToString() string {\n\treturn fmt.Sprint(v.Value)\n}\n\nfunc (v *KeywordValue) GetType() string {\n\treturn \"keyword\"\n}\n\nfunc (v *KeywordValue) IsValue() bool {\n\treturn false\n}\n\nfunc (v *KeywordValue) ConvertTo(t string) (ValueType, error) {\n\treturn nil, fmt.Errorf(\"cannot convert keyword to %s: does not implement yet\", t)\n}\n\n\n\nfunc NewKeywordValue(v string) *KeywordValue {\n\treturn &KeywordValue{Value: v}\n}\n\nfunc (v *KeywordValue) EqualTo(t ValueType) bool ", "output": "{\n\tif v2, ok := t.(*KeywordValue); ok {\n\t\tif v2.Value == v.Value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package intacct\n\nimport (\n\t\"encoding/xml\"\n)\n\n\ntype GetList struct {\n\tXMLName xml.Name `xml:\"get_list\"`\n\tObject string `xml:\"object,attr\"`\n\tListParams\n}\n\n\n\n\ntype ListParams struct {\n\tMaxItems uint64 `xml:\"maxitems,attr\"`\n\tFilter Logical `xml:\"filter\"`\n\tSorts Sorts `xml:\"sorts\"`\n}\n\n\n\n\n\nfunc (l ListParams) Merge(other ListParams) ListParams ", "output": "{\n\tif other.MaxItems > 0 {\n\t\tl.MaxItems = other.MaxItems\n\t}\n\n\tl.Filter.Filters = append(l.Filter.Filters, other.Filter.Filters...)\n\n\tif len(other.Sorts) > 0 {\n\t\tl.Sorts = other.Sorts\n\t}\n\treturn l\n}"} {"input": "package node\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Node struct {\n\tPriority uint\n\tLoad interface{}\n}\n\n\n\n\nfunc NewEmptyNode() Node {\n\treturn Node{}\n}\n\n\nfunc New(load interface{}, priority uint) *Node {\n\treturn &Node{Load: load, Priority: priority}\n}\n\nfunc (n Node) String() string ", "output": "{\n\treturn fmt.Sprintf(\"{ Priority : %d, Load : %+v}\", n.Priority, n.Load)\n}"} {"input": "package gosseract\n\nimport \"fmt\"\nimport \"os\"\nimport \"os/exec\"\nimport \"bytes\"\nimport \"io/ioutil\"\n\ntype tesseract0303 struct {\n\tversion string\n\tresultFilePath string\n\tcommandPath string\n}\n\nfunc (t tesseract0303) Version() string {\n\treturn t.version\n}\n\nfunc (t tesseract0303) Execute(params []string) (res string, e error) {\n\tvar args []string\n\targs = append(args, params[0])\n\tt.resultFilePath, e = generateTmpFile()\n\tif e != nil {\n\t\treturn\n\t}\n\targs = append(args, t.resultFilePath)\n\tif len(params) > 1 {\n\t\targs = append(args, params[1])\n\t}\n\n\tcmd := exec.Command(TESSERACT, args...)\n\tvar stderr bytes.Buffer\n\tcmd.Stderr = &stderr\n\tif e = cmd.Run(); e != nil {\n\t\te = fmt.Errorf(stderr.String())\n\t\treturn\n\t}\n\tres, e = t.readResult()\n\treturn\n}\n\n\n\nfunc (t tesseract0303) readResult() (res string, e error) ", "output": "{\n\tfpath := t.resultFilePath + outFILEEXTENSION\n\tfile, e := os.OpenFile(fpath, 1, 1)\n\tif e != nil {\n\t\treturn\n\t}\n\tbuffer, _ := ioutil.ReadFile(file.Name())\n\tres = string(buffer)\n\tos.Remove(file.Name())\n\treturn\n}"} {"input": "package gengen\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\n\t\"github.com/raphael/goa/goagen/codegen\"\n\t\"github.com/raphael/goa/goagen/meta\"\n)\n\nvar (\n\tGenPkgPath string\n\n\tGenPkgName string\n)\n\n\n\ntype Command struct {\n\t*codegen.BaseCommand\n}\n\n\n\n\n\nfunc (c *Command) RegisterFlags(r codegen.FlagRegistry) {\n\tr.Flag(\"pkg-path\", \"Go package path to generator package. The package must implement the Generate global function.\").Required().StringVar(&GenPkgPath)\n\tr.Flag(\"pkg-name\", \"Go package name of generator package. Defaults to name of inner most directory in package path.\").StringVar(&GenPkgName)\n}\n\n\nfunc (c *Command) Run() ([]string, error) {\n\tif GenPkgName == \"\" {\n\t\tGenPkgName = filepath.ToSlash(filepath.Base(GenPkgPath))\n\t}\n\tgen := meta.NewGenerator(\n\t\tfmt.Sprintf(\"%s.Generate\", GenPkgName),\n\t\t[]*codegen.ImportSpec{codegen.SimpleImport(GenPkgPath)},\n\t\tnil,\n\t)\n\treturn gen.Generate()\n}\n\nfunc NewCommand() *Command ", "output": "{\n\tbase := codegen.NewBaseCommand(\"gen\", \"Invoke third party generator\")\n\treturn &Command{BaseCommand: base}\n}"} {"input": "package api\n\nimport (\n\t\"errors\"\n\t\"os/user\"\n)\n\nconst (\n\tcountOfColumnsInGroup = 3\n\n\tnameColumnNumberInGroup = 0\n\n\tpasswordFlagColumnNumberInGroup = 1\n\n\tgidColumnNumberInGroup = 2\n\n\tusersColumnNumberInGroup = 3\n)\n\nfunc (linux *Linux) groupLookup(groupName string) (*user.Group, error) {\n\tgroupInfo, err := linux.getEntity(\"group\", groupName)\n\n\tif err != nil {\n\t\treturn nil, user.UnknownGroupError(groupName)\n\t}\n\n\tif len(groupInfo) < countOfColumnsInGroup {\n\t\treturn nil, errors.New(\"Wrong format of /etc/group\")\n\t}\n\n\tgroup := user.Group{\n\t\tGid: groupInfo[gidColumnNumberInGroup],\n\t\tName: groupInfo[nameColumnNumberInGroup],\n\t}\n\n\treturn &group, err\n}\n\n\n\n\nfunc (linux *Linux) GroupExists(groupName string) bool {\n\tgroup, _ := linux.groupLookup(groupName)\n\treturn group != nil\n}\n\nfunc (linux *Linux) groupExistsByID(groupID string) bool {\n\tgroup, _ := linux.groupLookupByID(groupID)\n\treturn group != nil\n}\n\nfunc (linux *Linux) groupLookupByID(groupID string) (*user.Group, error) ", "output": "{\n\tgroupInfo, err := linux.getEntity(\"group\", groupID)\n\n\tif err != nil {\n\t\treturn nil, user.UnknownGroupIdError(groupID)\n\t}\n\n\tif len(groupInfo) < countOfColumnsInGroup {\n\t\treturn nil, errors.New(\"Wrong format of /etc/group\")\n\t}\n\n\tgroup := user.Group{\n\t\tGid: groupInfo[gidColumnNumberInGroup],\n\t\tName: groupInfo[nameColumnNumberInGroup],\n\t}\n\n\treturn &group, err\n}"} {"input": "package head\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/arapov/pile/lib/flight\"\n\n\t\"github.com/blue-jay/core/router\"\n)\n\nvar (\n\turi = \"/roster\"\n)\n\n\n\n\n\nfunc IndexHead(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\tv := c.View.New(\"head/index\")\n\tv.Vars[\"name\"] = \"TC-UA-Steward\"\n\tv.Vars[\"suffix\"] = \"heads\"\n\tv.Render(w, r)\n}\n\n\nfunc IndexAll(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\tv := c.View.New(\"head/index\")\n\tv.Vars[\"name\"] = \"Everyone in organization\"\n\tv.Vars[\"suffix\"] = \"all\"\n\tv.Render(w, r)\n}\n\nfunc Load() ", "output": "{\n\trouter.Get(uri+\"/head\", IndexHead)\n\trouter.Get(uri+\"/all\", IndexAll)\n}"} {"input": "package sqltrace\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\nfunc boolToInt64(f bool) int64 {\n\tif f {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\ntype sqlTrace struct {\n\ton int64 \n\n\t*log.Logger\n}\n\nfunc newSQLTrace() *sqlTrace {\n\treturn &sqlTrace{\n\t\tLogger: log.New(os.Stdout, \"hdb \", log.Ldate|log.Ltime|log.Lshortfile),\n\t}\n}\nfunc (t *sqlTrace) On() bool { return atomic.LoadInt64(&t.on) != 0 }\n\n\ntype flagValue struct {\n\tt *sqlTrace\n}\n\nfunc (v flagValue) IsBoolFlag() bool { return true }\n\nfunc (v flagValue) String() string {\n\tif v.t == nil {\n\t\treturn \"\"\n\t}\n\treturn strconv.FormatBool(v.t.On())\n}\n\nfunc (v flagValue) Set(s string) error {\n\tf, err := strconv.ParseBool(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.t.SetOn(f)\n\treturn nil\n}\n\nvar tracer = newSQLTrace()\n\nfunc init() {\n\tflag.Var(&flagValue{t: tracer}, \"hdb.sqlTrace\", \"enabling hdb sql trace\")\n}\n\n\nfunc On() bool { return tracer.On() }\n\n\nfunc SetOn(on bool) { tracer.SetOn(on) }\n\n\nfunc Trace(v ...interface{}) { tracer.Print(v...) }\n\n\nfunc Tracef(format string, v ...interface{}) { tracer.Printf(format, v...) }\n\n\nfunc Traceln(v ...interface{}) { tracer.Println(v...) }\n\nfunc (t *sqlTrace) SetOn(on bool) ", "output": "{ atomic.StoreInt64(&t.on, boolToInt64(on)) }"} {"input": "package challenge25\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"github.com/stripedpajamas/cryptopals/set3/challenge18\"\n)\n\nvar globalPlaintext []byte\n\nfunc init() {\n\tvar err error\n\tglobalPlaintext, err = ioutil.ReadFile(\"25_decoded.txt\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc TestEncryptSecretWithCTR(t *testing.T) {\n\tenc := EncryptSecretWithCTR(globalPlaintext)\n\tdec := challenge18.CTR(enc, globalKey, globalNonce)\n\n\tif !bytes.Equal(dec, globalPlaintext) {\n\t\tt.Fail()\n\t}\n}\n\n\n\nfunc TestEditAPI(t *testing.T) {\n\tinput := []byte(\"HELLO POTATO FACE\")\n\tenc := challenge18.CTR(input, globalKey, globalNonce)\n\tedited := EditAPI(enc, []byte(\"TOMATO\"), 6)\n\tdec := challenge18.CTR(edited, globalKey, globalNonce)\n\n\tif string(dec) != \"HELLO TOMATO FACE\" {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestRecoverPTFromAPI(t *testing.T) {\n\tenc := EncryptSecretWithCTR(globalPlaintext)\n\trecovered := RecoverPTFromAPI(enc)\n\tif !bytes.Equal(recovered, globalPlaintext) {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestEdit(t *testing.T) ", "output": "{\n\tinput := []byte(\"HELLO POTATO FACE\")\n\tkey := []byte(\"YELLOW SUBMARINE\")\n\tnonce := []byte{0, 0, 0, 0, 0, 0, 0, 0}\n\tenc := challenge18.CTR(input, key, nonce)\n\tedited := Edit(enc, key, nonce, []byte(\"TOMATO\"), 6)\n\tdec := challenge18.CTR(edited, key, nonce)\n\n\tif string(dec) != \"HELLO TOMATO FACE\" {\n\t\tt.Fail()\n\t}\n}"} {"input": "package api_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/remind101/empire/pkg/heroku\"\n)\n\n\n\nfunc mustFormationBatchUpdate(t testing.TB, c *heroku.Client, appName string, updates []heroku.FormationBatchUpdateOpts) []heroku.Formation {\n\tf, err := c.FormationBatchUpdate(appName, updates, \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treturn f\n}\n\nfunc TestFormationBatchUpdate(t *testing.T) ", "output": "{\n\tc, s := NewTestClient(t)\n\tdefer s.Close()\n\n\tmustDeploy(t, c, DefaultImage)\n\n\tq := 2\n\tf := mustFormationBatchUpdate(t, c, \"acme-inc\", []heroku.FormationBatchUpdateOpts{\n\t\t{\n\t\t\tProcess: \"web\",\n\t\t\tQuantity: &q,\n\t\t},\n\t})\n\n\tif got, want := f[0].Quantity, 2; got != want {\n\t\tt.Fatalf(\"Quantity => %d; want %d\", got, want)\n\t}\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSGameLiftBuild_S3Location struct {\n\n\tBucket string `json:\"Bucket,omitempty\"`\n\n\tKey string `json:\"Key,omitempty\"`\n\n\tRoleArn string `json:\"RoleArn,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSGameLiftBuild_S3Location) AWSCloudFormationType() string {\n\treturn \"AWS::GameLift::Build.S3Location\"\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\n\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSGameLiftBuild_S3Location) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSGameLiftBuild_S3Location) Metadata() map[string]interface{} ", "output": "{\n\treturn r._metadata\n}"} {"input": "package fakes\n\nimport (\n\tboshas \"github.com/cloudfoundry/bosh-agent/agent/applier/applyspec\"\n\t\"github.com/cloudfoundry/bosh-agent/agent/applier/models\"\n)\n\ntype FakeApplier struct {\n\tPrepared bool\n\tPrepareDesiredApplySpec boshas.ApplySpec\n\tPrepareError error\n\n\tApplied bool\n\tApplyCurrentApplySpec boshas.ApplySpec\n\tApplyDesiredApplySpec boshas.ApplySpec\n\tApplyError error\n\n\tConfigured bool\n\tConfiguredDesiredApplySpec boshas.ApplySpec\n\tConfiguredJobs []models.Job\n\tConfiguredError error\n}\n\n\n\nfunc (s *FakeApplier) Prepare(desiredApplySpec boshas.ApplySpec) error {\n\ts.Prepared = true\n\ts.PrepareDesiredApplySpec = desiredApplySpec\n\treturn s.PrepareError\n}\n\nfunc (s *FakeApplier) ConfigureJobs(desiredApplySpec boshas.ApplySpec) error {\n\ts.Configured = true\n\ts.ConfiguredDesiredApplySpec = desiredApplySpec\n\treturn s.ConfiguredError\n}\n\nfunc (s *FakeApplier) Apply(currentApplySpec, desiredApplySpec boshas.ApplySpec) error {\n\ts.Applied = true\n\ts.ApplyCurrentApplySpec = currentApplySpec\n\ts.ApplyDesiredApplySpec = desiredApplySpec\n\treturn s.ApplyError\n}\n\nfunc NewFakeApplier() *FakeApplier ", "output": "{\n\treturn &FakeApplier{}\n}"} {"input": "package iso20022\n\n\ntype RateAndAmountFormat42Choice struct {\n\n\tAmount *ActiveCurrencyAnd13DecimalAmount `xml:\"Amt\"`\n\n\tNotSpecifiedRate *RateValueType7Code `xml:\"NotSpcfdRate\"`\n}\n\n\n\nfunc (r *RateAndAmountFormat42Choice) SetNotSpecifiedRate(value string) {\n\tr.NotSpecifiedRate = (*RateValueType7Code)(&value)\n}\n\nfunc (r *RateAndAmountFormat42Choice) SetAmount(value, currency string) ", "output": "{\n\tr.Amount = NewActiveCurrencyAnd13DecimalAmount(value, currency)\n}"} {"input": "package metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/collector/model/pdata\"\n)\n\nfunc TestNewMetricDataType(t *testing.T) {\n\tmetricDataType := NewMetricDataType(pdata.MetricDataTypeGauge, pdata.MetricAggregationTemporalityDelta, true)\n\n\trequire.NotNil(t, metricDataType)\n\tassert.Equal(t, metricDataType.MetricDataType(), pdata.MetricDataTypeGauge)\n\tassert.Equal(t, metricDataType.AggregationTemporality(), pdata.MetricAggregationTemporalityDelta)\n\tassert.True(t, metricDataType.IsMonotonic())\n}\n\nfunc TestMetricValueDataType_MetricDataType(t *testing.T) {\n\tvalueDataType := metricValueDataType{dataType: pdata.MetricDataTypeGauge}\n\n\tassert.Equal(t, valueDataType.MetricDataType(), pdata.MetricDataTypeGauge)\n}\n\nfunc TestMetricValueDataType_AggregationTemporality(t *testing.T) {\n\tvalueDataType := metricValueDataType{aggregationTemporality: pdata.MetricAggregationTemporalityDelta}\n\n\tassert.Equal(t, valueDataType.AggregationTemporality(), pdata.MetricAggregationTemporalityDelta)\n}\n\n\n\nfunc TestMetricValueDataType_IsMonotonic(t *testing.T) ", "output": "{\n\tvalueDataType := metricValueDataType{isMonotonic: true}\n\n\tassert.True(t, valueDataType.IsMonotonic())\n}"} {"input": "package opt\n\nimport (\n\t\"encoding/json\"\n\t\"reflect\"\n)\n\n\n\ntype DisableTypoToleranceOnAttributesOption struct {\n\tvalue []string\n}\n\n\nfunc DisableTypoToleranceOnAttributes(v ...string) *DisableTypoToleranceOnAttributesOption {\n\treturn &DisableTypoToleranceOnAttributesOption{v}\n}\n\n\nfunc (o *DisableTypoToleranceOnAttributesOption) Get() []string {\n\tif o == nil {\n\t\treturn []string{}\n\t}\n\treturn o.value\n}\n\n\n\nfunc (o DisableTypoToleranceOnAttributesOption) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(o.value)\n}\n\n\n\nfunc (o *DisableTypoToleranceOnAttributesOption) UnmarshalJSON(data []byte) error {\n\tif string(data) == \"null\" {\n\t\to.value = []string{}\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(data, &o.value)\n}\n\n\n\n\nfunc (o *DisableTypoToleranceOnAttributesOption) Equal(o2 *DisableTypoToleranceOnAttributesOption) bool {\n\tif o == nil {\n\t\treturn o2 == nil || reflect.DeepEqual(o2.value, []string{})\n\t}\n\tif o2 == nil {\n\t\treturn o == nil || reflect.DeepEqual(o.value, []string{})\n\t}\n\treturn reflect.DeepEqual(o.value, o2.value)\n}\n\n\n\n\n\n\nfunc DisableTypoToleranceOnAttributesEqual(o1, o2 *DisableTypoToleranceOnAttributesOption) bool ", "output": "{\n\treturn o1.Equal(o2)\n}"} {"input": "package routetemplate\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\nvar routeTemplates []RouteTemplate\n\nfunc Add(template string) (err error) {\n\trouteTemplate, _ := Parse(template)\n\trouteTemplates = append(routeTemplates, routeTemplate)\n\treturn nil\n}\n\nfunc GetMatchedTemplateString(url string) (template string, err error) {\n\ttemplate = \"\"\n\n\tfor _, value := range routeTemplates {\n\n\t\twasMatched, _ := IsMatch(url, value)\n\t\tif wasMatched {\n\t\t\ttemplate = value.TemplatePath\n\t\t\tbreak\n\t\t}\n\t}\n\treturn template, nil\n}\n\n\n\nfunc GetMatchedTemplate(url string) (template string, err error) {\n\ttemplate = \"\"\n\n\tfor _, value := range routeTemplates {\n\n\t\twasMatched, _ := IsMatch(url, value)\n\t\tif wasMatched {\n\t\t\ttemplate = value.TemplatePath\n\t\t\tbreak\n\t\t}\n\t}\n\treturn template, nil\n}\n\nfunc AddRoute(name string, method string, urlTemplate string, handler interface{}) {\n\tfmt.Printf(\"%q\\n\", handler)\n\tvar x reflect.Value\n\tif fv, ok := handler.(reflect.Value); ok {\n\t\tx = fv\n\t} else {\n\t\tx = reflect.ValueOf(handler)\n\t}\n\n\targs := make([]reflect.Value, 0, 0)\n\tx.Call(args)\n\tfmt.Printf(\"%q\\n\", x)\n}\n\nfunc GetAllTemplates() (templates []RouteTemplate, err error) {\n\treturn routeTemplates, nil\n}\n\nfunc ClearAllTemplates() (err error) {\n\trouteTemplates = make([]RouteTemplate, 0)\n\treturn nil\n}\n\nfunc GetMatchTemplate(url string) (routeTemplateMatch RouteTemplateMatch, err error) ", "output": "{\n\n\trouteTemplateMatch = RouteTemplateMatch{}\n\tfor _, value := range routeTemplates {\n\t\twasMatched, _ := IsMatch(url, value)\n\t\tif wasMatched {\n\n\t\t\trouteTemplateMatch, _ = BindVariables(url, value)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn routeTemplateMatch, nil\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/hamed1soleimani/goauth\"\n)\n\n\n\nfunc main() {\n\tr := gin.Default()\n\tauth := goauth.NewGOAuth()\n\tauth.Providers[\"google\"] = goauth.OauthConfig{\n\t\tClientID: \"YOUR_CLIENT_ID\",\n\t\tClientSecret: \"YOUR_SECRET\",\n\t\tCallbackURL: \"http://127.0.0.1:3000/auth/google/oauth2callback\",\n\t\tAuthURL: \"https://accounts.google.com/o/oauth2/auth\",\n\t\tTokenURL: \"https://accounts.google.com/o/oauth2/token\",\n\t\tApiURL: \"https://www.googleapis.com/oauth2/v2/userinfo?fields=email%2Cname%2Cpicture\",\n\t\tScopes: []string{\"https://www.googleapis.com/auth/userinfo.email\",\n\t\t\t\"https://www.googleapis.com/auth/userinfo.profile\"},\n\t}\n\n\tr.GET(\"/auth/:provider\", auth.AuthHandler)\n\tr.GET(\"/auth/:provider/oauth2callback\", OauthMiddleware(), auth.CallbackHandler)\n\tr.Run(\":3000\")\n}\n\nfunc OauthMiddleware() gin.HandlerFunc ", "output": "{\n\treturn func(c *gin.Context) {\n\t\tc.Next()\n\t\tc.JSON(http.StatusOK, c.Value(\"profile\"))\n\t}\n}"} {"input": "package command\n\nimport (\n\t\"strings\"\n\n\t\"github.com/mitchellh/cli\"\n\t\"github.com/posener/complete\"\n)\n\nvar (\n\t_ cli.Command = (*PrintCommand)(nil)\n\t_ cli.CommandAutocomplete = (*PrintCommand)(nil)\n)\n\ntype PrintCommand struct {\n\t*BaseCommand\n}\n\nfunc (c *PrintCommand) Synopsis() string {\n\treturn \"Prints runtime configurations\"\n}\n\n\n\nfunc (c *PrintCommand) AutocompleteArgs() complete.Predictor {\n\treturn nil\n}\n\nfunc (c *PrintCommand) AutocompleteFlags() complete.Flags {\n\treturn nil\n}\n\nfunc (c *PrintCommand) Run(args []string) int {\n\treturn cli.RunResultHelp\n}\n\nfunc (c *PrintCommand) Help() string ", "output": "{\n\thelpText := `\nUsage: vault print \n\n\tThis command groups subcommands for interacting with Vault's runtime values.\n\nSubcommands:\n\ttoken Token currently in use\n`\n\treturn strings.TrimSpace(helpText)\n}"} {"input": "package seqnum\n\n\ntype Value uint32\n\n\ntype Size uint32\n\n\nfunc (v Value) LessThan(w Value) bool {\n\treturn int32(v-w) < 0\n}\n\n\n\n\n\nfunc (v Value) InRange(a, b Value) bool {\n\treturn v-a < b-a\n}\n\n\n\nfunc (v Value) InWindow(first Value, size Size) bool {\n\treturn v.InRange(first, first.Add(size))\n}\n\n\nfunc Overlap(a Value, b Size, x Value, y Size) bool {\n\treturn a.LessThan(x.Add(y)) && x.LessThan(a.Add(b))\n}\n\n\nfunc (v Value) Add(s Size) Value {\n\treturn v + Value(s)\n}\n\n\nfunc (v Value) Size(w Value) Size {\n\treturn Size(w - v)\n}\n\n\nfunc (v *Value) UpdateForward(s Size) {\n\t*v += Value(s)\n}\n\nfunc (v Value) LessThanEq(w Value) bool ", "output": "{\n\tif v == w {\n\t\treturn true\n\t}\n\treturn v.LessThan(w)\n}"} {"input": "package binary\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"testing\"\n)\n\ntype TestStruct struct {\n\tUi16 uint16\n\tUi8_1 uint8\n\tB20 [20]byte\n}\n\nfunc TestStructRead(t *testing.T) {\n\tbuf := GetBytesBufferToFillTestStruct()\n\ts := TestStruct{Ui16: uint16('A'), Ui8_1: uint8(0)}\n\n\tif err := ReadStructBigEndian(&s, bytes.NewReader(buf.Bytes())); err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Read struct:\\n%s\\nFrom:\\n%q\\n\", s, buf.Bytes())\n}\n\n\n\nfunc GetBytesBufferToFillTestStruct() *bytes.Buffer {\n\tbuf := new(bytes.Buffer)\n\n\tfor i := 0; i < 3; i++ {\n\t\tbuf.WriteByte(byte(255))\n\t}\n\n\tfor i := 3; i < 23; i++ {\n\t\tbuf.WriteByte(byte('A') + byte(i))\n\t}\n\n\treturn buf\n}\n\nfunc TestReadAndWriteStruct(t *testing.T) ", "output": "{\n\treadBuf := GetBytesBufferToFillTestStruct()\n\ts := TestStruct{Ui16: uint16('A'), Ui8_1: uint8(1)}\n\n\tif err := ReadStructBigEndian(&s, bytes.NewReader(readBuf.Bytes())); err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\n\twriteBuf := new(bytes.Buffer)\n\n\tif err := WriteStructBigEndian(&s, writeBuf); err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Wrote:\\n%s\\nRead:\\n%s\\n\", readBuf.Bytes(), writeBuf.Bytes())\n\n\tif readBuf.Len() != writeBuf.Len() || readBuf.String() != writeBuf.String() {\n\t\tt.Error(\"Read and write buffer not equal.\\n\")\n\t}\n}"} {"input": "package main\n\ntype Pet struct {\n\tname string\n}\n\nfunc (p *Pet) Name() string {\n\treturn p.name\n}\n\n\n\nfunc (p *Pet) SetName(name string) ", "output": "{\n\tp.name = name\n}"} {"input": "package cachestore\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\ntype CacheStore struct {\n\tstores map[string]*KVStore\n\tmutex sync.RWMutex\n}\n\n\n\nfunc (c *CacheStore) GetStore(svcName string) *KVStore {\n\tc.mutex.RLock()\n\tkvstore := c.stores[svcName]\n\tc.mutex.RUnlock()\n\n\treturn kvstore\n}\n\n\n\nfunc (c *CacheStore) CreateStore(svcName string) *KVStore {\n\tkvstore := NewKVStore()\n\tc.mutex.Lock()\n\tc.stores[svcName] = kvstore\n\tc.mutex.Unlock()\n\n\treturn kvstore\n}\n\n\nfunc (c *CacheStore) DeleteStore(svcName string) {\n\tc.mutex.Lock()\n\tdelete(c.stores, svcName)\n\tc.mutex.Unlock()\n}\n\n\nfunc (c *CacheStore) SetCache(svcName string, key string, value interface{}) {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore == nil {\n\t\tsvcStore = c.CreateStore(svcName)\n\t}\n\n\tsvcStore.Set(key, value)\n}\n\n\n\n\n\n\nfunc (c *CacheStore) DeleteCache(svcName string, key string) {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore != nil {\n\t\tsvcStore.Delete(key)\n\t}\n}\n\n\nfunc (c *CacheStore) MarshalJSON() ([]byte, error) {\n\tc.mutex.RLock()\n\tbytes, err := json.Marshal(&c.stores)\n\tc.mutex.RUnlock()\n\treturn bytes, err\n}\n\n\nfunc NewCacheStore() *CacheStore {\n\treturn &CacheStore{map[string]*KVStore{}, sync.RWMutex{}}\n}\n\nfunc (c *CacheStore) GetCache(svcName string, key string) interface{} ", "output": "{\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore == nil {\n\t\treturn nil\n\t}\n\treturn svcStore.Get(key)\n}"} {"input": "package bootstrap\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/pem\"\n\n\t\"github.com/flynn/flynn/pkg/tlscert\"\n)\n\ntype GenTLSCertAction struct {\n\tID string `json:\"id\"`\n\tHosts []string `json:\"hosts\"`\n\n\tCACert string `json:\"ca_cert\"`\n\tCert string `json:\"cert\"`\n\tPrivateKey string `json:\"key\"`\n}\n\n\n\nfunc (a *GenTLSCertAction) Run(s *State) (err error) {\n\tdata := &tlscert.Cert{}\n\ts.StepData[a.ID] = data\n\n\ta.CACert = interpolate(s, a.CACert)\n\ta.Cert = interpolate(s, a.Cert)\n\ta.PrivateKey = interpolate(s, a.PrivateKey)\n\tif a.CACert != \"\" && a.Cert != \"\" && a.PrivateKey != \"\" {\n\t\tdata.CACert = a.CACert\n\t\tdata.Cert = a.Cert\n\t\tdata.PrivateKey = a.PrivateKey\n\n\t\tb, _ := pem.Decode([]byte(data.Cert))\n\t\tsha := sha256.Sum256(b.Bytes)\n\t\tdata.Pin = base64.StdEncoding.EncodeToString(sha[:])\n\t\treturn nil\n\t}\n\n\tfor i, h := range a.Hosts {\n\t\ta.Hosts[i] = interpolate(s, h)\n\t}\n\tc, err := tlscert.Generate(a.Hosts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata.CACert = c.CACert\n\tdata.Cert = c.Cert\n\tdata.Pin = c.Pin\n\tdata.PrivateKey = c.PrivateKey\n\n\treturn err\n}\n\nfunc init() ", "output": "{\n\tRegister(\"gen-tls-cert\", &GenTLSCertAction{})\n}"} {"input": "package utub\n\nimport (\n\t\"strings\"\n\n\t\"gopkg.in/olebedev/go-duktape.v2\"\n)\n\ntype duktapeJSEngine struct{}\n\nfunc (js duktapeJSEngine) Name() string {\n\treturn \"Duktape\"\n}\n\n\n\nfunc (js duktapeJSEngine) Exec(code string) (string, error) {\n\tctx := duktape.New()\n\tdefer ctx.DestroyHeap()\n\n\terr := ctx.PevalString(code)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn ctx.SafeToString(-1), nil\n}\n\nfunc (js duktapeJSEngine) sanitizeJSPlayerCode(code string) string {\n\tcode = strings.Replace(code, `(?=:|,|]|}|$)`, `(?=:|,|\\]|\\}|$)`, 1)\n\treturn code\n}\n\nfunc (js duktapeJSEngine) Available() bool ", "output": "{\n\treturn true\n}"} {"input": "package wire_test\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\n\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) ", "output": "{\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}"} {"input": "package builtins\n\nimport (\n\t\"sigs.k8s.io/kustomize/api/filters/annotations\"\n\t\"sigs.k8s.io/kustomize/api/resmap\"\n\t\"sigs.k8s.io/kustomize/api/types\"\n\t\"sigs.k8s.io/yaml\"\n)\n\n\ntype AnnotationsTransformerPlugin struct {\n\tAnnotations map[string]string `json:\"annotations,omitempty\" yaml:\"annotations,omitempty\"`\n\tFieldSpecs []types.FieldSpec `json:\"fieldSpecs,omitempty\" yaml:\"fieldSpecs,omitempty\"`\n}\n\n\n\nfunc (p *AnnotationsTransformerPlugin) Transform(m resmap.ResMap) error {\n\tif len(p.Annotations) == 0 {\n\t\treturn nil\n\t}\n\treturn m.ApplyFilter(annotations.Filter{\n\t\tAnnotations: p.Annotations,\n\t\tFsSlice: p.FieldSpecs,\n\t})\n}\n\nfunc NewAnnotationsTransformerPlugin() resmap.TransformerPlugin {\n\treturn &AnnotationsTransformerPlugin{}\n}\n\nfunc (p *AnnotationsTransformerPlugin) Config(\n\t_ *resmap.PluginHelpers, c []byte) (err error) ", "output": "{\n\tp.Annotations = nil\n\tp.FieldSpecs = nil\n\treturn yaml.Unmarshal(c, p)\n}"} {"input": "package kubernetes\n\nimport (\n\t\"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\nfunc flattenReplicationControllerSpec(in v1.ReplicationControllerSpec) ([]interface{}, error) {\n\tatt := make(map[string]interface{})\n\tatt[\"min_ready_seconds\"] = in.MinReadySeconds\n\n\tif in.Replicas != nil {\n\t\tatt[\"replicas\"] = *in.Replicas\n\t}\n\n\tatt[\"selector\"] = in.Selector\n\tpodSpec, err := flattenPodSpec(in.Template.Spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tatt[\"template\"] = podSpec\n\n\treturn []interface{}{att}, nil\n}\n\n\n\nfunc expandReplicationControllerSpec(rc []interface{}) (v1.ReplicationControllerSpec, error) ", "output": "{\n\tobj := v1.ReplicationControllerSpec{}\n\tif len(rc) == 0 || rc[0] == nil {\n\t\treturn obj, nil\n\t}\n\tin := rc[0].(map[string]interface{})\n\tobj.MinReadySeconds = int32(in[\"min_ready_seconds\"].(int))\n\tobj.Replicas = ptrToInt32(int32(in[\"replicas\"].(int)))\n\tobj.Selector = expandStringMap(in[\"selector\"].(map[string]interface{}))\n\tpodSpec, err := expandPodSpec(in[\"template\"].([]interface{}))\n\tif err != nil {\n\t\treturn obj, err\n\t}\n\tobj.Template = &v1.PodTemplateSpec{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tLabels: obj.Selector,\n\t\t},\n\t\tSpec: podSpec,\n\t}\n\n\treturn obj, nil\n}"} {"input": "package factory\n\nimport (\n\t\"encoding/hex\"\n\n\t\"github.com/hyperledger/fabric/bccsp\"\n\t\"github.com/hyperledger/fabric/bccsp/pkcs11\"\n\t\"github.com/hyperledger/fabric/bccsp/sw\"\n\t\"github.com/pkg/errors\"\n)\n\nconst (\n\tPKCS11BasedFactoryName = \"PKCS11\"\n)\n\n\ntype PKCS11Factory struct{}\n\n\n\n\n\nfunc (f *PKCS11Factory) Get(config *FactoryOpts) (bccsp.BCCSP, error) {\n\tif config == nil || config.PKCS11 == nil {\n\t\treturn nil, errors.New(\"Invalid config. It must not be nil.\")\n\t}\n\n\tp11Opts := *config.PKCS11\n\tks := sw.NewDummyKeyStore()\n\tmapper := skiMapper(p11Opts)\n\n\treturn pkcs11.New(p11Opts, ks, pkcs11.WithKeyMapper(mapper))\n}\n\nfunc skiMapper(p11Opts pkcs11.PKCS11Opts) func([]byte) []byte {\n\tkeyMap := map[string]string{}\n\tfor _, k := range p11Opts.KeyIDs {\n\t\tkeyMap[k.SKI] = k.ID\n\t}\n\n\treturn func(ski []byte) []byte {\n\t\tkeyID := hex.EncodeToString(ski)\n\t\tif id, ok := keyMap[keyID]; ok {\n\t\t\treturn []byte(id)\n\t\t}\n\t\tif p11Opts.AltID != \"\" {\n\t\t\treturn []byte(p11Opts.AltID)\n\t\t}\n\t\treturn ski\n\t}\n}\n\nfunc (f *PKCS11Factory) Name() string ", "output": "{\n\treturn PKCS11BasedFactoryName\n}"} {"input": "package lrucache\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n)\n\ntype bytes []byte\n\nfunc (b bytes) Size() uint64 {\n\treturn uint64(cap(b))\n}\n\n\n\nfunc BenchmarkGet(b *testing.B) ", "output": "{\n\tc := New(64 * 1024 * 1024)\n\tvalue := make(bytes, 1024)\n\n\tfor i := 0; i < 1024; i++ {\n\t\tc.Set(strconv.Itoa(i), value)\n\t}\n\n\tfor i := 0; i < b.N; i++ {\n\t\tv, _ := c.Get(\"512\")\n\t\tif v == nil {\n\t\t\tpanic(\"error\")\n\t\t}\n\t\t_ = v\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/asticode/go-logger/logger\"\n\t\"github.com/asticode/go-stopwatch/stopwatch\"\n\textendederror \"github.com/asticode/go-toolbox/error\"\n\t_ \"github.com/asticode/go-keyboardemulator/keyboardemulator\"\n\t_ \"os/exec\"\n\t\"github.com/asticode/go-texttospeech/texttospeech\"\n)\n\nfunc main() {\n\tdefer extendederror.Catch(catchPrepare, map[string]interface{}{})\n\n\tconfigPath := flag.String(\"config\", \"\", \"Path to the local configuration file\")\n\tflag.Parse()\n\n\tprepare(*configPath)\n}\n\nfunc catchPrepare(err interface{}, args map[string]interface{}) {\n\tfmt.Println(\"CRITICAL: \" + extendederror.ParseError(err))\n}\n\nfunc prepare(configPath string) {\n\tc := newConfiguration(configPath)\n\n\tl, err := logger.NewLoggerFromConfiguration(c.Logger)\n\textendederror.ProcessError(err)\n\n\tdefer extendederror.Catch(catchRun, map[string]interface{}{\n\t\t\"logger\": l,\n\t})\n\trun(*c, l)\n}\n\n\n\nfunc run(c configuration, l logger.Logger) {\n\tsw := stopwatch.NewStopwatchFromConfiguration(c.StopWatch).SetIsEnabled(true)\n\tsw.AddEvent(\"Init\", \"Stopwatch has been created\")\n\n\n\n\ttts := texttospeech.NewTextToSpeech()\n\n\ttts.Say(\"Good morning sir, how may I help you today?\")\n\n\n\tl.Info(\"Done\")\n}\n\nfunc catchRun(err interface{}, args map[string]interface{}) ", "output": "{\n\tl := args[\"logger\"].(logger.Logger)\n\n\tl.Critical(extendederror.ParseError(err))\n}"} {"input": "package query\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/astaxie/beego\"\n\t\"github.com/hyperledger/fabric-sdk-go/apiServer/models/fabric/query\"\n)\n\n\ntype QueryInfoController struct {\n\tbeego.Controller\n}\n\n\n\n\n\n\n\n\n\nfunc (u *QueryInfoController) Post() ", "output": "{\n\tvar req query.QueryInfoArgs\n\terr := json.Unmarshal(u.Ctx.Input.RequestBody, &req)\n\tif err != nil {\n\t\tfmt.Printf(\"Unmarshal failed [%s]\", err)\n\t}\n\tfmt.Println(req)\n\taction, err := query.NewQueryInfoAction(&req)\n\tif err != nil {\n\t\tu.Data[\"json\"] = err.Error()\n\t} else {\n\t\tresp, err := action.Execute()\n\t\tif err != nil {\n\t\t\tu.Data[\"json\"] = err.Error()\n\t\t} else {\n\t\t\tu.Data[\"json\"] = resp\n\t\t}\n\t}\n\n\tu.ServeJSON()\n}"} {"input": "package antlr\n\nimport \"fmt\"\n\ntype TraceListener struct {\n\tparser *BaseParser\n}\n\nfunc NewTraceListener(parser *BaseParser) *TraceListener {\n\ttl := new(TraceListener)\n\ttl.parser = parser\n\treturn tl\n}\n\nfunc (t *TraceListener) VisitErrorNode(_ ErrorNode) {\n}\n\nfunc (t *TraceListener) EnterEveryRule(ctx ParserRuleContext) {\n\tfmt.Println(\"enter \" + t.parser.GetRuleNames()[ctx.GetRuleIndex()] + \", LT(1)=\" + t.parser.input.LT(1).GetText())\n}\n\nfunc (t *TraceListener) VisitTerminal(node TerminalNode) {\n\tfmt.Println(\"consume \" + fmt.Sprint(node.GetSymbol()) + \" rule \" + t.parser.GetRuleNames()[t.parser.ctx.GetRuleIndex()])\n}\n\n\n\nfunc (t *TraceListener) ExitEveryRule(ctx ParserRuleContext) ", "output": "{\n\tfmt.Println(\"exit \" + t.parser.GetRuleNames()[ctx.GetRuleIndex()] + \", LT(1)=\" + t.parser.input.LT(1).GetText())\n}"} {"input": "package core\n\nimport (\n\t\"runtime\"\n\n\t\"github.com/Tzunami/go-earthdollar/core/types\"\n\t\"github.com/Tzunami/go-earthdollar/pow\"\n)\n\n\ntype nonceCheckResult struct {\n\tindex int \n\tvalid bool \n}\n\n\n\n\n\n\n\n\n\nfunc verifyNoncesFromBlocks(checker pow.PoW, blocks []*types.Block) (chan<- struct{}, <-chan nonceCheckResult) {\n\titems := make([]pow.Block, len(blocks))\n\tfor i, block := range blocks {\n\t\titems[i] = block\n\t}\n\treturn verifyNonces(checker, items)\n}\n\n\n\nfunc verifyNonces(checker pow.PoW, items []pow.Block) (chan<- struct{}, <-chan nonceCheckResult) {\n\tworkers := runtime.GOMAXPROCS(0)\n\tif len(items) < workers {\n\t\tworkers = len(items)\n\t}\n\ttasks := make(chan int, workers)\n\tresults := make(chan nonceCheckResult, len(items)) \n\tfor i := 0; i < workers; i++ {\n\t\tgo func() {\n\t\t\tfor index := range tasks {\n\t\t\t\tresults <- nonceCheckResult{index: index, valid: checker.Verify(items[index])}\n\t\t\t}\n\t\t}()\n\t}\n\tabort := make(chan struct{})\n\tgo func() {\n\t\tdefer close(tasks)\n\n\t\tfor i := range items {\n\t\t\tselect {\n\t\t\tcase tasks <- i:\n\t\t\t\tcontinue\n\t\t\tcase <-abort:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn abort, results\n}\n\nfunc verifyNoncesFromHeaders(checker pow.PoW, headers []*types.Header) (chan<- struct{}, <-chan nonceCheckResult) ", "output": "{\n\titems := make([]pow.Block, len(headers))\n\tfor i, header := range headers {\n\t\titems[i] = types.NewBlockWithHeader(header)\n\t}\n\treturn verifyNonces(checker, items)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/arjandepooter/codejam/utils\"\n\t\"sort\"\n)\n\nfunc main() {\n\tinput, err := utils.GetInput()\n\tif err != nil {\n\t\tfmt.Errorf(\"Error occured: %x\", err)\n\t}\n\n\tproblems := getProblems(input)\n\n\tfor i, problem := range problems {\n\t\tfmt.Printf(\"Case #%d: %s\\n\", i+1, problem.Solve())\n\t}\n}\n\ntype Problem struct {\n\tcapacity int\n\tsizes []int\n}\n\nfunc (problem *Problem) Solve() string {\n\tsizes := problem.sizes\n\tsort.Ints(sizes)\n\tr := 0\n\tfor len(sizes) > 0 {\n\t\tcur := sizes[len(sizes)-1]\n\t\tm := problem.capacity - cur\n\t\tbi := -1\n\t\tfor i, n := range sizes[:len(sizes)-1] {\n\t\t\tif n > m {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tbi = i\n\t\t}\n\t\tif bi == -1 {\n\t\t\tsizes = sizes[:len(sizes)-1]\n\t\t} else {\n\t\t\tsizes = append(sizes[:bi], sizes[bi+1:len(sizes)-1]...)\n\t\t}\n\t\tr++\n\t}\n\treturn fmt.Sprint(r)\n}\n\n\n\nfunc getProblems(input *utils.Input) []*Problem ", "output": "{\n\tn := input.ReadInt()\n\n\tproblems := make([]*Problem, n)\n\tfor i := 0; i < n; i++ {\n\t\tproblem := Problem{}\n\t\tproblem.sizes = make([]int, input.ReadInt())\n\t\tproblem.capacity = input.ReadInt()\n\n\t\tfor i := 0; i < len(problem.sizes); i++ {\n\t\t\tproblem.sizes[i] = input.ReadInt()\n\t\t}\n\n\t\tproblems[i] = &problem\n\t}\n\n\treturn problems\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Mutex struct {\n\tLocked bool\n\tLocker chan bool\n}\n\n\n\nfunc (m *Mutex) Unlock() {\n\tm.Locker <- true\n}\n\nfunc main() {\n\tmu := &Mutex{}\n\n\tfmt.Println(mu)\n\n\tgo func() {\n\t\tmu.Lock()\n\t\tfmt.Println(\"locking ...\")\n\t}()\n\n\tgo func() {\n\t\tmu.Lock()\n\t\tfmt.Println(\"unlocked !!\")\n\t}()\n\n\tgo func() {\n\t\t<-time.NewTimer(time.Second * 2).C\n\t\tmu.Unlock()\n\t\tfmt.Println(\"unlocking..\")\n\t}()\n\n\t<-time.NewTimer(time.Second * 4).C\n\tfmt.Println(\"finished..\")\n}\n\nfunc (m *Mutex) Lock() ", "output": "{\n\tif m.Locker == nil {\n\t\tm.Locker = make(chan bool, 1)\n\t}\n\n\tif m.Locked {\n\t\t<-m.Locker\n\t\tm.Locked = false\n\t} else {\n\t\tm.Locked = true\n\t}\n}"} {"input": "package returns\n\nimport (\n\t\"go/ast\"\n\t\"go/types\"\n)\n\n\n\n\n\nfunc funcHasSingleReturnVal(typeInfo *types.Info, e *ast.CallExpr) bool ", "output": "{\n\tif id, ok := e.Fun.(*ast.Ident); ok && id.Obj != nil {\n\t\tif fn, ok := id.Obj.Decl.(*ast.FuncDecl); ok {\n\t\t\treturn len(fn.Type.Results.List) == 1\n\t\t}\n\t}\n\n\tif typeInfo != nil {\n\t\ttyp := typeInfo.TypeOf(e)\n\t\tif _, ok := typ.(*types.Tuple); ok {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\n\treturn false\n}"} {"input": "package wml\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\ntype CT_Markup struct {\n\tIdAttr int64\n}\n\nfunc NewCT_Markup() *CT_Markup {\n\tret := &CT_Markup{}\n\treturn ret\n}\n\nfunc (m *CT_Markup) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"w:id\"},\n\t\tValue: fmt.Sprintf(\"%v\", m.IdAttr)})\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}\n\nfunc (m *CT_Markup) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"id\" {\n\t\t\tparsed, err := strconv.ParseInt(attr.Value, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.IdAttr = parsed\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_Markup: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (m *CT_Markup) Validate() error {\n\treturn m.ValidateWithPath(\"CT_Markup\")\n}\n\n\n\n\nfunc (m *CT_Markup) ValidateWithPath(path string) error ", "output": "{\n\treturn nil\n}"} {"input": "package common\n\nimport (\n . \"launchpad.net/gocheck\"\n \"sync\"\n)\n\ntype HealthzSuite struct {\n}\n\nvar _ = Suite(&HealthzSuite{})\n\n\n\nfunc (s *HealthzSuite) TearDownTest(c *C) {\n Component = VcapComponent{}\n}\n\nfunc (s *HealthzSuite) TestJsonMarshal(c *C) {\n healthz := &Healthz{\n LockableObject: &sync.Mutex{},\n }\n bytes, _ := healthz.MarshalJSON()\n c.Assert(string(bytes), Equals, \"{\\\"health\\\":\\\"ok\\\"}\")\n}\n\nfunc (s *HealthzSuite) SetUpTest(c *C) ", "output": "{\n Component = VcapComponent{\n Config: map[string]interface{}{\"ip\": \"localhost\", \"port\": 8080},\n }\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/robfig/cron\"\n)\n\ntype Sync struct{}\n\nfunc (s *Sync) Help() string {\n\treturn \"glr sync Help\"\n}\n\nfunc (s *Sync) Run(args []string) int {\n\t_, err := SyncRepository()\n\n\tif err != nil {\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n\nfunc (s *Sync) Synopsis() string {\n\treturn \"Synchronize local git repository with remote at once\"\n}\n\n\ntype status struct {\n\tc *cron.Cron\n\trepositories []string\n\tschedules []string\n}\n\nvar sharedStatus *status = newStatus()\n\nfunc newStatus() *status {\n\treturn &status{\n\t\tc: cron.New(),\n\t}\n}\n\n\nfunc GetStatus() *status {\n\treturn sharedStatus\n}\n\ntype StatusStart struct{}\n\nfunc (s *StatusStart) Help() string {\n\treturn \"glr status start Help\"\n}\n\nfunc (s *StatusStart) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.AddFunc(\"@hourly\", func() {\n\t\tSyncRepository()\n\t})\n\tfmt.Println(\"set job schedule\")\n\tstatus.c.Start()\n\n\treturn 0\n}\n\n\n\ntype StatusStop struct{}\n\nfunc (s *StatusStop) Help() string {\n\treturn \"glr status stop Help\"\n}\n\nfunc (s *StatusStop) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.Stop()\n\tfmt.Println(\"stop job scheduler\")\n\n\treturn 0\n}\n\nfunc (s *StatusStop) Synopsis() string {\n\treturn \"Stop cron scheduler\"\n}\n\nfunc (s *StatusStart) Synopsis() string ", "output": "{\n\treturn \"Synchronize local git repository with remote\"\n}"} {"input": "package vpki\n\nimport (\n\t\"crypto/tls\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype certCache struct {\n\tm map[string]*tls.Certificate\n\tmut *sync.RWMutex\n\tcrt Certifier\n\tttl time.Duration\n}\n\nfunc newCertCache(crt Certifier) *certCache {\n\treturn &certCache{\n\t\tm: map[string]*tls.Certificate{},\n\t\tmut: &sync.RWMutex{},\n\t\tcrt: crt,\n\t\tttl: DefaultTTL,\n\t}\n}\n\n\n\nfunc (cc *certCache) get(name string) (*tls.Certificate, error) {\n\tlkr := cc.mut.RLocker()\n\tlkr.Lock()\n\n\tif c, ok := cc.m[name]; ok {\n\t\tn := time.Now()\n\t\tif n.After(c.Leaf.NotBefore) && n.Before(c.Leaf.NotAfter) {\n\t\t\tlkr.Unlock()\n\t\t\treturn c, nil\n\t\t}\n\t}\n\tlkr.Unlock()\n\n\treturn cc.add(name)\n}\n\nfunc (cc *certCache) add(name string) (*tls.Certificate, error) ", "output": "{\n\tcrt, err := cc.crt.Cert(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcc.mut.Lock()\n\tcc.m[name] = crt\n\tcc.mut.Unlock()\n\treturn crt, nil\n}"} {"input": "package session\n\nimport (\n\tgomock \"github.com/golang/mock/gomock\"\n\tanonymous \"github.com/skygeario/skygear-server/pkg/auth/dependency/identity/anonymous\"\n\treflect \"reflect\"\n)\n\n\ntype MockAnonymousIdentityProvider struct {\n\tctrl *gomock.Controller\n\trecorder *MockAnonymousIdentityProviderMockRecorder\n}\n\n\ntype MockAnonymousIdentityProviderMockRecorder struct {\n\tmock *MockAnonymousIdentityProvider\n}\n\n\nfunc NewMockAnonymousIdentityProvider(ctrl *gomock.Controller) *MockAnonymousIdentityProvider {\n\tmock := &MockAnonymousIdentityProvider{ctrl: ctrl}\n\tmock.recorder = &MockAnonymousIdentityProviderMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockAnonymousIdentityProvider) EXPECT() *MockAnonymousIdentityProviderMockRecorder {\n\treturn m.recorder\n}\n\n\n\n\n\nfunc (mr *MockAnonymousIdentityProviderMockRecorder) List(userID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"List\", reflect.TypeOf((*MockAnonymousIdentityProvider)(nil).List), userID)\n}\n\nfunc (m *MockAnonymousIdentityProvider) List(userID string) ([]*anonymous.Identity, error) ", "output": "{\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", userID)\n\tret0, _ := ret[0].([]*anonymous.Identity)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}"} {"input": "package gridq\n\ntype byColRow []*WriteResponse\n\nfunc (p byColRow) Len() int { return len(p) }\nfunc (p byColRow) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byColRow) Less(i, j int) bool {\n\tif p[i].Col < p[j].Col {\n\t\treturn true\n\t} else if p[i].Col > p[j].Col {\n\t\treturn false\n\t} else {\n\t\treturn p[i].Row < p[j].Row\n\t}\n}\n\ntype byRowTimestamp []*ReadResponse\n\nfunc (p byRowTimestamp) Len() int { return len(p) }\nfunc (p byRowTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byRowTimestamp) Less(i, j int) bool {\n\tif p[i].Row < p[j].Row {\n\t\treturn true\n\t} else if p[i].Row > p[j].Row {\n\t\treturn false\n\t} else {\n\t\treturn p[i].State.Timestamp > p[j].State.Timestamp\n\t}\n}\n\ntype byTimestamp []*ReadResponse\n\n\nfunc (p byTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byTimestamp) Less(i, j int) bool { return p[i].State.Timestamp < p[j].State.Timestamp }\n\nfunc (p byTimestamp) Len() int ", "output": "{ return len(p) }"} {"input": "package glfw\n\n\nimport \"C\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc SetTime(time float64) {\n\tC.glfwSetTime(C.double(time))\n}\n\nfunc GetTime() float64 ", "output": "{\n\treturn float64(C.glfwGetTime())\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc Test_logEvent_size(t *testing.T) {\n\tevent := logEvent{msg: \"123\", timestamp: 123}\n\texpected := 3 + eventSizeOverhead\n\tassert.Equal(t, expected, event.size())\n}\n\nfunc Test_logEvent_tooBig(t *testing.T) {\n\tevent := logEvent{msg: RandomString(maxEventSize + 1)}\n\tassert.Equal(t, errMessageTooBig, event.validate())\n}\n\n\n\nfunc Test_destination_string(t *testing.T) ", "output": "{\n\tdst := destination{group: \"group\", stream: \"stream\"}\n\tassert.Equal(t, \"group: group stream: stream\", dst.String())\n}"} {"input": "package pgjson\n\nimport (\n\t\"io\"\n)\n\nvar provider Provider = StdProvider{}\n\nfunc SetProvider(p Provider) {\n\tprovider = p\n}\n\ntype Provider interface {\n\tMarshal(v interface{}) ([]byte, error)\n\tUnmarshal(data []byte, v interface{}) error\n\tNewEncoder(w io.Writer) Encoder\n\tNewDecoder(r io.Reader) Decoder\n}\n\ntype Decoder interface {\n\tDecode(v interface{}) error\n\tUseNumber()\n}\n\ntype Encoder interface {\n\tEncode(v interface{}) error\n}\n\n\n\nfunc Unmarshal(data []byte, v interface{}) error {\n\treturn provider.Unmarshal(data, v)\n}\n\nfunc NewEncoder(w io.Writer) Encoder {\n\treturn provider.NewEncoder(w)\n}\n\nfunc NewDecoder(r io.Reader) Decoder {\n\treturn provider.NewDecoder(r)\n}\n\nfunc Marshal(v interface{}) ([]byte, error) ", "output": "{\n\treturn provider.Marshal(v)\n}"} {"input": "package logo\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc fail(t *testing.T, msg string) {\n\tt.Errorf(msg)\n}\n\nfunc assertEqual(t *testing.T, actual, expected interface{}, args ...interface{}) {\n\tif actual != expected {\n\t\tmsg := fmt.Sprint(args...)\n\t\tmsg = fmt.Sprintf(\"Not equal(%s)! autual: %#v expected: %#v\", msg, actual, expected)\n\t\tfail(t, msg)\n\t}\n}\n\nfunc assertTrue(t *testing.T, val bool, args ...interface{}) {\n\tif !val {\n\t\tmsg := fmt.Sprint(args...)\n\t\tmsg = fmt.Sprintf(\"Not true(%s)!\", msg)\n\t\tfail(t, msg)\n\t}\n}\n\nfunc assertNotNil(t *testing.T, val interface{}, args ...interface{}) {\n\tif val == nil {\n\t\tmsg := fmt.Sprint(args...)\n\t\tmsg = fmt.Sprintf(\"Nil(%s)!\", msg)\n\t\tfail(t, msg)\n\t}\n}\n\n\n\nfunc benchmarkTask(b *testing.B, task func(int)) ", "output": "{\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\ttask(i)\n\t}\n}"} {"input": "package geom\n\nimport \"math\"\n\n\ntype MultiLineString []LineString\n\n\nfunc (ml MultiLineString) Bounds() *Bounds {\n\tb := NewBounds()\n\tfor _, l := range ml {\n\t\tb.Extend(l.Bounds())\n\t}\n\treturn b\n}\n\n\n\n\n\nfunc (ml MultiLineString) Within(p Polygonal) WithinStatus {\n\tfor _, l := range ml {\n\t\tif l.Within(p) == Outside {\n\t\t\treturn Outside\n\t\t}\n\t}\n\treturn Inside\n}\n\n\nfunc (ml MultiLineString) Distance(p Point) float64 {\n\td := math.Inf(1)\n\tfor _, l := range ml {\n\t\tlDist := l.Distance(p)\n\t\td = math.Min(d, lDist)\n\t}\n\treturn d\n}\n\nfunc (ml MultiLineString) Length() float64 ", "output": "{\n\tlength := 0.\n\tfor _, l := range ml {\n\t\tlength += l.Length()\n\t}\n\treturn length\n}"} {"input": "package v1\n\n\n\n\n\n\n\n\n\n\n\n\nvar map_TokenReview = map[string]string{\n\t\"\": \"TokenReview attempts to authenticate a token to a known user. Note: TokenReview requests may be cached by the webhook token authenticator plugin in the kube-apiserver.\",\n\t\"spec\": \"Spec holds information about the request being evaluated\",\n\t\"status\": \"Status is filled in by the server and indicates whether the request can be authenticated.\",\n}\n\nfunc (TokenReview) SwaggerDoc() map[string]string {\n\treturn map_TokenReview\n}\n\nvar map_TokenReviewSpec = map[string]string{\n\t\"\": \"TokenReviewSpec is a description of the token authentication request.\",\n\t\"token\": \"Token is the opaque bearer token.\",\n}\n\nfunc (TokenReviewSpec) SwaggerDoc() map[string]string {\n\treturn map_TokenReviewSpec\n}\n\nvar map_TokenReviewStatus = map[string]string{\n\t\"\": \"TokenReviewStatus is the result of the token authentication request.\",\n\t\"authenticated\": \"Authenticated indicates that the token was associated with a known user.\",\n\t\"user\": \"User is the UserInfo associated with the provided token.\",\n\t\"error\": \"Error indicates that the token couldn't be checked\",\n}\n\nfunc (TokenReviewStatus) SwaggerDoc() map[string]string {\n\treturn map_TokenReviewStatus\n}\n\nvar map_UserInfo = map[string]string{\n\t\"\": \"UserInfo holds the information about the user needed to implement the user.Info interface.\",\n\t\"username\": \"The name that uniquely identifies this user among all active users.\",\n\t\"uid\": \"A unique value that identifies this user across time. If this user is deleted and another user by the same name is added, they will have different UIDs.\",\n\t\"groups\": \"The names of groups this user is a part of.\",\n\t\"extra\": \"Any additional information provided by the authenticator.\",\n}\n\n\n\nfunc (UserInfo) SwaggerDoc() map[string]string ", "output": "{\n\treturn map_UserInfo\n}"} {"input": "package log\n\nimport (\n\t\"io\"\n\t\"sync\"\n)\n\ntype MirrorWriter struct {\n\twriters []io.Writer\n\tlk sync.Mutex\n}\n\nfunc (mw *MirrorWriter) Write(b []byte) (int, error) {\n\tmw.lk.Lock()\n\tvar dropped bool\n\tfor i, w := range mw.writers {\n\t\t_, err := w.Write(b)\n\t\tif err != nil {\n\t\t\tmw.writers[i] = nil\n\t\t\tdropped = true\n\t\t}\n\t}\n\n\tif dropped {\n\t\twriters := mw.writers\n\t\tmw.writers = nil\n\t\tfor _, w := range writers {\n\t\t\tif w != nil {\n\t\t\t\tmw.writers = append(mw.writers, w)\n\t\t\t}\n\t\t}\n\t}\n\tmw.lk.Unlock()\n\treturn len(b), nil\n}\n\n\n\nfunc (mw *MirrorWriter) Active() (active bool) {\n\tmw.lk.Lock()\n\tactive = len(mw.writers) > 0\n\tmw.lk.Unlock()\n\treturn\n}\n\nfunc (mw *MirrorWriter) AddWriter(w io.Writer) ", "output": "{\n\tmw.lk.Lock()\n\tmw.writers = append(mw.writers, w)\n\tmw.lk.Unlock()\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"sync\"\n\n\t\"github.com/open-policy-agent/opa/cmd\"\n\t\"github.com/open-policy-agent/opa/plugins\"\n\t\"github.com/open-policy-agent/opa/plugins/logs\"\n\t\"github.com/open-policy-agent/opa/runtime\"\n\t\"github.com/open-policy-agent/opa/util\"\n)\n\ntype Config struct {\n\tStderr bool `json:\"stderr\"`\n}\n\ntype Factory struct{}\n\nfunc (Factory) New(_ *plugins.Manager, config interface{}) plugins.Plugin {\n\treturn &PrintlnLogger{\n\t\tconfig: config.(Config),\n\t}\n}\n\n\n\ntype PrintlnLogger struct {\n\tconfig Config\n\tmtx sync.Mutex\n}\n\nfunc (p *PrintlnLogger) Start(ctx context.Context) error {\n\treturn nil\n}\n\nfunc (p *PrintlnLogger) Stop(ctx context.Context) {\n}\n\nfunc (p *PrintlnLogger) Reconfigure(ctx context.Context, config interface{}) {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tp.config = config.(Config)\n}\n\nfunc (p *PrintlnLogger) Log(ctx context.Context, event logs.EventV1) error {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tw := os.Stdout\n\tif p.config.Stderr {\n\t\tw = os.Stderr\n\t}\n\tfmt.Fprintln(w, event) \n\treturn nil\n}\n\nfunc main() {\n\n\truntime.RegisterPlugin(\"println_decision_logger\", Factory{})\n\n\tif err := cmd.RootCommand.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc (Factory) Validate(_ *plugins.Manager, config []byte) (interface{}, error) ", "output": "{\n\tparsedConfig := Config{}\n\treturn parsedConfig, util.Unmarshal(config, &parsedConfig)\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\nfunc setTimespec(sec, nsec int64) Timespec {\n\treturn Timespec{Sec: sec, Nsec: nsec}\n}\n\nfunc setTimeval(sec, usec int64) Timeval {\n\treturn Timeval{Sec: sec, Usec: usec}\n}\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint64(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint64(length)\n}\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\n\n\nfunc (cmsg *Cmsghdr) SetLen(length int) ", "output": "{\n\tcmsg.Len = uint32(length)\n}"} {"input": "package common\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\n\ntype SignalReceiver interface {\n\tStop() error\n}\n\n\n\nfunc SignalHandlerLoop(ss ...SignalReceiver) ", "output": "{\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGUSR1, syscall.SIGTERM)\n\tbuf := make([]byte, 1<<20)\n\tfor {\n\t\tswitch <-sigs {\n\t\tcase syscall.SIGINT, syscall.SIGTERM:\n\t\t\tLog.Infof(\"=== received SIGINT/SIGTERM ===\\n*** exiting\")\n\t\t\tfor _, subsystem := range ss {\n\t\t\t\tsubsystem.Stop()\n\t\t\t}\n\t\t\treturn\n\t\tcase syscall.SIGQUIT:\n\t\t\tstacklen := runtime.Stack(buf, true)\n\t\t\tLog.Infof(\"=== received SIGQUIT ===\\n*** goroutine dump...\\n%s\\n*** end\", buf[:stacklen])\n\t\t}\n\t}\n}"} {"input": "package stdlib\n\nimport (\n\t\"go/format\"\n\t\"reflect\"\n)\n\n\n\nfunc init() ", "output": "{\n\tSymbols[\"go/format\"] = map[string]reflect.Value{\n\t\t\"Node\": reflect.ValueOf(format.Node),\n\t\t\"Source\": reflect.ValueOf(format.Source),\n\t}\n}"} {"input": "package naivecheap\n\nimport \"github.com/ffloyd/evergrid-go/global/types\"\n\ntype byPriceAsc []types.WorkerInfo\n\nfunc (sw byPriceAsc) Len() int {\n\treturn len(sw)\n}\n\nfunc (sw byPriceAsc) Swap(i, j int) {\n\tsw[i], sw[j] = sw[j], sw[i]\n}\n\nfunc (sw byPriceAsc) Less(i, j int) bool {\n\treturn sw[i].PricePerTick < sw[j].PricePerTick \n}\n\ntype byQueueAsc []types.WorkerInfo\n\nfunc (sw byQueueAsc) Len() int {\n\treturn len(sw)\n}\n\n\n\nfunc (sw byQueueAsc) Less(i, j int) bool {\n\treturn sw[i].QueueLength < sw[j].QueueLength \n}\n\nfunc (sw byQueueAsc) Swap(i, j int) ", "output": "{\n\tsw[i], sw[j] = sw[j], sw[i]\n}"} {"input": "package model\n\nimport uuidGenerator \"github.com/satori/go.uuid\"\n\n\n\n\ntype Modifier struct {\n\tUuid uuidGenerator.UUID\n\tFirstname string\n\tLastname string\n\tEmail string\n\tPolymorficType string\n\tDeleted bool\n}\n\n\nfunc NewModifier(uuid uuidGenerator.UUID, firstname, lastname, email, polymorficType string, deleted bool) *Modifier {\n\treturn &Modifier{\n\t\tuuid,\n\t\tfirstname,\n\t\tlastname,\n\t\temail,\n\t\tpolymorficType,\n\t\tdeleted,\n\t}\n}\n\n\nfunc (m *Modifier) MarkAsDeleted() {\n\tm.Deleted = true\n}\n\n\n\n\nfunc (m *Modifier) Update(firstname, lastname, email string) ", "output": "{\n\tm.Firstname = firstname\n\tm.Lastname = lastname\n\tm.Email = email\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/clients/generated/client/clientset/versioned/typed/cloudidentity/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeCloudidentityV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeCloudidentityV1beta1) CloudIdentityGroups(namespace string) v1beta1.CloudIdentityGroupInterface {\n\treturn &FakeCloudIdentityGroups{c, namespace}\n}\n\nfunc (c *FakeCloudidentityV1beta1) CloudIdentityMemberships(namespace string) v1beta1.CloudIdentityMembershipInterface {\n\treturn &FakeCloudIdentityMemberships{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeCloudidentityV1beta1) RESTClient() rest.Interface ", "output": "{\n\tvar ret *rest.RESTClient\n\treturn ret\n}"} {"input": "package binary\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"testing\"\n)\n\ntype TestStruct struct {\n\tUi16 uint16\n\tUi8_1 uint8\n\tB20 [20]byte\n}\n\nfunc TestStructRead(t *testing.T) {\n\tbuf := GetBytesBufferToFillTestStruct()\n\ts := TestStruct{Ui16: uint16('A'), Ui8_1: uint8(0)}\n\n\tif err := ReadStructBigEndian(&s, bytes.NewReader(buf.Bytes())); err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Read struct:\\n%s\\nFrom:\\n%q\\n\", s, buf.Bytes())\n}\n\nfunc TestReadAndWriteStruct(t *testing.T) {\n\treadBuf := GetBytesBufferToFillTestStruct()\n\ts := TestStruct{Ui16: uint16('A'), Ui8_1: uint8(1)}\n\n\tif err := ReadStructBigEndian(&s, bytes.NewReader(readBuf.Bytes())); err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\n\twriteBuf := new(bytes.Buffer)\n\n\tif err := WriteStructBigEndian(&s, writeBuf); err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Wrote:\\n%s\\nRead:\\n%s\\n\", readBuf.Bytes(), writeBuf.Bytes())\n\n\tif readBuf.Len() != writeBuf.Len() || readBuf.String() != writeBuf.String() {\n\t\tt.Error(\"Read and write buffer not equal.\\n\")\n\t}\n}\n\n\n\nfunc GetBytesBufferToFillTestStruct() *bytes.Buffer ", "output": "{\n\tbuf := new(bytes.Buffer)\n\n\tfor i := 0; i < 3; i++ {\n\t\tbuf.WriteByte(byte(255))\n\t}\n\n\tfor i := 3; i < 23; i++ {\n\t\tbuf.WriteByte(byte('A') + byte(i))\n\t}\n\n\treturn buf\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\ntype MockConn struct {\n\tServerReader *io.PipeReader\n\tServerWriter *io.PipeWriter\n\tClientReader *io.PipeReader\n\tClientWriter *io.PipeWriter\n}\n\nfunc (c MockConn) Close() error {\n\tif err := c.ServerWriter.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := c.ServerReader.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c MockConn) CloseClient() error {\n\tif err := c.ClientWriter.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := c.ClientReader.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c MockConn) Read(data []byte) (n int, err error) { return c.ServerReader.Read(data) }\nfunc (c MockConn) Write(data []byte) (n int, err error) { return c.ServerWriter.Write(data) }\n\nfunc (c MockConn) LocalAddr() net.Addr {\n\treturn &net.TCPAddr{\n\t\tIP: net.ParseIP(\"127.0.0.1:2342\"),\n\t\tPort: 2342,\n\t\tZone: \"\",\n\t}\n}\n\n\n\nfunc (c MockConn) SetDeadline(t time.Time) error { return nil }\nfunc (c MockConn) SetReadDeadline(t time.Time) error { return nil }\nfunc (c MockConn) SetWriteDeadline(t time.Time) error { return nil }\n\nfunc NewMockConn() MockConn {\n\tserverRead, clientWrite := io.Pipe()\n\tclientRead, serverWrite := io.Pipe()\n\n\treturn MockConn{\n\t\tServerReader: serverRead,\n\t\tServerWriter: serverWrite,\n\t\tClientReader: clientRead,\n\t\tClientWriter: clientWrite,\n\t}\n}\n\nfunc (c MockConn) RemoteAddr() net.Addr ", "output": "{\n\treturn &net.TCPAddr{\n\t\tIP: net.ParseIP(\"127.0.0.1:2342\"),\n\t\tPort: 2342,\n\t\tZone: \"\",\n\t}\n}"} {"input": "package v1\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/unversioned\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\nconst GroupName = \"\"\n\n\nvar SchemeGroupVersion = unversioned.GroupVersion{Group: GroupName, Version: \"v1\"}\n\nfunc AddToScheme(scheme *runtime.Scheme) {\n\taddKnownTypes(scheme)\n\taddConversionFuncs(scheme)\n}\n\n\n\n\nfunc (obj *ProjectRequest) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta }\nfunc (obj *Project) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta }\nfunc (obj *ProjectList) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta }\n\nfunc addKnownTypes(scheme *runtime.Scheme) ", "output": "{\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t&Project{},\n\t\t&ProjectList{},\n\t\t&ProjectRequest{},\n\t)\n}"} {"input": "package mastodon\n\nimport (\n\t\"context\"\n\t\"net/http\"\n)\n\n\ntype Instance struct {\n\tURI string `json:\"uri\"`\n\tTitle string `json:\"title\"`\n\tDescription string `json:\"description\"`\n\tEMail string `json:\"email\"`\n\tVersion string `json:\"version,omitempty\"`\n\tURLs map[string]string `json:\"urls,omitempty\"`\n\tStats *InstanceStats `json:\"stats,omitempty\"`\n\tThumbnail string `json:\"thumbnail,omitempty\"`\n}\n\n\ntype InstanceStats struct {\n\tUserCount int64 `json:\"user_count\"`\n\tStatusCount int64 `json:\"status_count\"`\n\tDomainCount int64 `json:\"domain_count\"`\n}\n\n\nfunc (c *Client) GetInstance(ctx context.Context) (*Instance, error) {\n\tvar instance Instance\n\terr := c.doAPI(ctx, http.MethodGet, \"/api/v1/instance\", nil, &instance, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &instance, nil\n}\n\n\ntype WeeklyActivity struct {\n\tWeek Unixtime `json:\"week\"`\n\tStatuses int64 `json:\"statuses,string\"`\n\tLogins int64 `json:\"logins,string\"`\n\tRegistrations int64 `json:\"registrations,string\"`\n}\n\n\nfunc (c *Client) GetInstanceActivity(ctx context.Context) ([]*WeeklyActivity, error) {\n\tvar activity []*WeeklyActivity\n\terr := c.doAPI(ctx, http.MethodGet, \"/api/v1/instance/activity\", nil, &activity, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn activity, nil\n}\n\n\n\n\nfunc (c *Client) GetInstancePeers(ctx context.Context) ([]string, error) ", "output": "{\n\tvar peers []string\n\terr := c.doAPI(ctx, http.MethodGet, \"/api/v1/instance/peers\", nil, &peers, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn peers, nil\n}"} {"input": "package rkive\n\nimport (\n\t\"bytes\"\n\tcheck \"gopkg.in/check.v1\"\n\t\"time\"\n)\n\n\n\nfunc (s *riakSuite) TestCache(c *check.C) {\n\tstartt := time.Now()\n\n\tcache := s.cl.Bucket(\"test-cache\")\n\terr := cache.MakeCache()\n\tif err != nil {\n\t\tc.Fatal(err)\n\t}\n\tprops, err := cache.GetProperties()\n\tif err != nil {\n\t\tc.Error(err)\n\t}\n\tif !bytes.Equal(props.GetBackend(), []byte(\"cache\")) {\n\t\tc.Errorf(\"Expected backend %q; got %q\", \"cache\", props.GetBackend())\n\t}\n\n\n\tob := &TestObject{\n\t\tData: []byte(\"Save this.\"),\n\t}\n\n\terr = cache.New(ob, nil)\n\tif err != nil {\n\t\tc.Error(err)\n\t}\n\n\tob2 := &TestObject{\n\t\tData: []byte(\"overwrite!\"),\n\t}\n\n\terr = cache.Overwrite(ob2, ob.Info().Key())\n\tif err != nil {\n\t\tc.Error(err)\n\t}\n\n\tvar upd bool\n\tupd, err = cache.Update(ob)\n\tif err != nil {\n\t\tc.Error(err)\n\t}\n\tif !upd {\n\t\tc.Error(\"Expected update.\")\n\t}\n\n\tif !bytes.Equal(ob.Data, []byte(\"overwrite!\")) {\n\t\tc.Errorf(\"Expected body %q; got %q\", []byte(\"overwrite!\"), ob.Data)\n\t}\n\n\ts.runtime += time.Since(startt)\n}\n\nfunc (s *riakSuite) TestGetBucketTypeProperties(c *check.C) ", "output": "{\n\tc.Skip(\"not implemented\")\n}"} {"input": "package b\n\nimport \"a\"\n\nvar N n\n\ntype n struct{}\n\nfunc (r n) M1() int { return a.G1 }\nfunc (r n) M2() int { return a.G2 }\nfunc (r n) M3() int { return a.G3 }\n\nfunc (r n) M5() int { return a.G5 }\nfunc (r n) M6() int { return a.G6 }\nfunc (r n) M7() int { return a.G7 }\nfunc (r n) M8() int { return a.G8 }\nfunc (r n) M9() int { return a.G9 }\nfunc (r n) M10() int { return a.G10 }\n\nfunc (r n) M4() int ", "output": "{ return a.G4 }"} {"input": "package funcs\n\nimport (\n\t\"github.com/gaochao1/sw\"\n\t\"github.com/gaochao1/swcollector/g\"\n\t\"github.com/open-falcon/common/model\"\n\t\"log\"\n\t\"time\"\n)\n\ntype SwCpu struct {\n\tIp string\n\tCpuUtil int\n}\n\nfunc CpuMetrics() (L []*model.MetricValue) {\n\n\tchs := make([]chan SwCpu, len(AliveIp))\n\tfor i, ip := range AliveIp {\n\t\tif ip != \"\" {\n\t\t\tchs[i] = make(chan SwCpu)\n\t\t\tgo cpuMetrics(ip, chs[i])\n\t\t}\n\t}\n\n\tfor _, ch := range chs {\n\t\tswCpu := <-ch\n\t\tL = append(L, GaugeValueIp(time.Now().Unix(), swCpu.Ip, \"switch.CpuUtilization\", swCpu.CpuUtil))\n\t}\n\n\treturn L\n}\n\n\n\nfunc cpuMetrics(ip string, ch chan SwCpu) ", "output": "{\n\tvar swCpu SwCpu\n\n\tcpuUtili, err := sw.CpuUtilization(ip, g.Config().Switch.Community, g.Config().Switch.SnmpTimeout, g.Config().Switch.SnmpRetry)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tswCpu.Ip = ip\n\tswCpu.CpuUtil = cpuUtili\n\tch <- swCpu\n\n\treturn\n}"} {"input": "package expect\n\nimport (\n\t\"testing\"\n)\n\ntype EachTests struct {\n\tcalled bool\n}\n\n\n\nfunc (e *EachTests) RunsEach() {\n\tExpect(e.called).To.Equal(true)\n}\n\nfunc (e *EachTests) Each(f func()) {\n\te.called = true\n\tf()\n}\n\nfunc Test_Each(t *testing.T) ", "output": "{\n\tExpectify(new(EachTests), t)\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/exec\"\n)\n\ntype Repository struct {\n\tName string\n}\n\nfunc getRepositories() *[]Repository {\n\tvar result []Repository\n\tdirs, _ := ioutil.ReadDir(config.RepositoryDir)\n\tfor _, entry := range dirs {\n\t\tif entry.IsDir() {\n\t\t\tresult = append(result, Repository{entry.Name()})\n\t\t}\n\t}\n\treturn &result\n}\n\nfunc (repo *Repository) Create() error {\n\tcmd := exec.Command(\"git\", \"init\", \"--bare\", repo.Name)\n\tcmd.Dir = config.RepositoryDir\n\treturn cmd.Run()\n}\n\n\n\nfunc (repo *Repository) Exists() bool {\n\tif _, err := os.Stat(repo.Path()); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc (repo *Repository) Path() string ", "output": "{\n\treturn config.RepositoryDir + \"/\" + repo.Name\n}"} {"input": "package opts\n\n\ntype CreateOption func(*CreateConfig)\n\n\n\ntype CreateConfig struct {\n\tOptions map[string]string\n\tLabels map[string]string\n\tReference string\n}\n\n\n\n\n\n\n\nfunc WithCreateOptions(opts map[string]string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Options = opts\n\t}\n}\n\n\n\n\nfunc WithCreateReference(ref string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Reference = ref\n\t}\n}\n\n\n\ntype GetConfig struct {\n\tDriver string\n\tReference string\n\tResolveStatus bool\n}\n\n\ntype GetOption func(*GetConfig)\n\n\n\n\n\nfunc WithGetDriver(name string) GetOption {\n\treturn func(o *GetConfig) {\n\t\to.Driver = name\n\t}\n}\n\n\n\nfunc WithGetReference(ref string) GetOption {\n\treturn func(o *GetConfig) {\n\t\to.Reference = ref\n\t}\n}\n\n\n\nfunc WithGetResolveStatus(cfg *GetConfig) {\n\tcfg.ResolveStatus = true\n}\n\n\ntype RemoveConfig struct {\n\tPurgeOnError bool\n}\n\n\ntype RemoveOption func(*RemoveConfig)\n\n\n\n\nfunc WithPurgeOnError(b bool) RemoveOption {\n\treturn func(o *RemoveConfig) {\n\t\to.PurgeOnError = b\n\t}\n}\n\nfunc WithCreateLabels(labels map[string]string) CreateOption ", "output": "{\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Labels = labels\n\t}\n}"} {"input": "package repl\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/magicshui/echo/evaluator\"\n\t\"github.com/magicshui/echo/lexer\"\n\t\"github.com/magicshui/echo/object\"\n\t\"github.com/magicshui/echo/parser\"\n)\n\nconst PROMPT = \">>\"\n\n\n\nfunc printParserErrors(out io.Writer, errors []string) {\n\tfor _, msg := range errors {\n\t\tio.WriteString(out, \"\\t\"+msg+\"\\n\")\n\t}\n}\n\nfunc Start(in io.Reader, out io.Writer) ", "output": "{\n\tscanner := bufio.NewScanner(in)\n\tenv := object.NewEnvironment()\n\n\tfor {\n\t\tfmt.Print(PROMPT)\n\t\tscanned := scanner.Scan()\n\t\tif !scanned {\n\t\t\treturn\n\t\t}\n\t\tline := scanner.Text()\n\t\tl := lexer.New(line)\n\t\tp := parser.New(l)\n\n\t\tprogram := p.ParseProgram()\n\t\tif len(p.Errors()) != 0 {\n\t\t\tprintParserErrors(out, p.Errors())\n\t\t\tcontinue\n\t\t}\n\n\t\tevaluated := evaluator.Eval(program, env)\n\t\tif evaluated != nil {\n\t\t\tio.WriteString(out, evaluated.Inspect())\n\t\t\tio.WriteString(out, \"\\n\")\n\t\t}\n\t}\n}"} {"input": "package signer\n\nimport (\n\t\"crypto\"\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"encoding/pem\"\n\t\"errors\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"github.com/EmpiresMod/GameLauncher/checksum\"\n)\n\n\n\nfunc ParseFilePublicPEM(filename string) (pub *rsa.PublicKey, err error) {\n\n\tb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\n\t\treturn\n\t}\n\n\treturn ParsePublicPEM(b)\n}\n\nfunc VerifyCryptoSignature(r io.Reader, sig []byte, pub *rsa.PublicKey) (err error) {\n\n\thash, err := checksum.GenerateCheckSum(r)\n\tif err != nil {\n\n\t\treturn\n\t}\n\n\treturn rsa.VerifyPKCS1v15(pub, crypto.SHA256, hash, sig)\n}\n\nfunc VerifyFileCryptoSignature(filename string, sig []byte, pub *rsa.PublicKey) (err error) {\n\n\tf, err := os.Open(filename)\n\tif err != nil {\n\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\treturn VerifyCryptoSignature(f, sig, pub)\n}\n\nfunc ParsePublicPEM(b []byte) (pub *rsa.PublicKey, err error) ", "output": "{\n\n\tblock, _ := pem.Decode(b)\n\tif block == nil {\n\n\t\treturn nil, errors.New(\"Could not parse PEM data\")\n\t}\n\n\tkey, err := x509.ParsePKIXPublicKey(block.Bytes)\n\tif err != nil {\n\n\t\treturn\n\t}\n\n\treturn key.(*rsa.PublicKey), nil\n}"} {"input": "package command\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/mitchellh/cli\"\n)\n\n\n\nfunc TestOperator_Raft_ListPeers(t *testing.T) {\n\ts, _, addr := testServer(t, nil)\n\tdefer s.Stop()\n\n\tui := new(cli.MockUi)\n\tc := &OperatorRaftListCommand{Meta: Meta{Ui: ui}}\n\targs := []string{\"-address=\" + addr}\n\n\tcode := c.Run(args)\n\tif code != 0 {\n\t\tt.Fatalf(\"bad: %d. %#v\", code, ui.ErrorWriter.String())\n\t}\n\toutput := strings.TrimSpace(ui.OutputWriter.String())\n\tif !strings.Contains(output, \"leader\") {\n\t\tt.Fatalf(\"bad: %s\", output)\n\t}\n}\n\nfunc TestOperator_Raft_ListPeers_Implements(t *testing.T) ", "output": "{\n\tvar _ cli.Command = &OperatorRaftListCommand{}\n}"} {"input": "package kthlargest\n\nimport \"container/heap\"\n\ntype MaxHeap struct {\n\tSize int\n\tNums []int\n}\n\nfunc (h *MaxHeap) Insert(x int) {\n\tif h.Len() < h.Size {\n\t\theap.Push(h, x)\n\t} else if h.Nums[0] < x {\n\t\th.Nums[0] = x\n\t\theap.Fix(h, 0)\n\t}\n}\n\nfunc (h *MaxHeap) Len() int { return len(h.Nums) }\n\nfunc (h *MaxHeap) Less(i, j int) bool {\n\treturn h.Nums[i] < h.Nums[j]\n}\n\nfunc (h *MaxHeap) Swap(i, j int) {\n\th.Nums[i], h.Nums[j] = h.Nums[j], h.Nums[i]\n}\n\n\n\nfunc (h *MaxHeap) Pop() interface{} {\n\tn := len(h.Nums)\n\tx := h.Nums[n-1]\n\th.Nums = h.Nums[:n-1]\n\treturn x\n}\n\nfunc findKthLargest(nums []int, k int) int {\n\th := &MaxHeap{Size: k}\n\tfor _, num := range nums {\n\t\th.Insert(num)\n\t}\n\treturn h.Nums[0]\n}\n\nfunc (h *MaxHeap) Push(x interface{}) ", "output": "{\n\th.Nums = append(h.Nums, x.(int))\n}"} {"input": "package fwd\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"path\"\n)\n\n\n\n\n\n\n\nfunc Abs(absURL string, errHandler func(*http.Request, error)) http.Handler {\n\tparsedURL, err := url.Parse(absURL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdoProxy(parsedURL, w, r, errHandler)\n\t})\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc Rel(\n\taddr, relPath string, errHandler func(*http.Request, error),\n) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tabsURL := addr + path.Join(relPath, r.URL.Path)\n\t\tparsedURL, err := url.Parse(absURL)\n\t\tif err != nil {\n\t\t\terrHandler(r, err)\n\t\t}\n\t\tparsedURL.RawQuery = r.URL.RawQuery\n\n\t\tdoProxy(parsedURL, w, r, errHandler)\n\t})\n}\n\n\n\nfunc doProxy(\n\tu *url.URL, w http.ResponseWriter, r *http.Request,\n\terrHandler func(*http.Request, error),\n) ", "output": "{\n\tr.URL = u\n\tresp, err := http.DefaultClient.Do(r)\n\tif err != nil {\n\t\tif errHandler != nil {\n\t\t\terrHandler(r, err)\n\t\t}\n\t\thttp.Error(w, \"unexpected server-side error\", 500)\n\t}\n\tdefer resp.Body.Close()\n\n\tfor header, vals := range resp.Header {\n\t\tw.Header()[header] = append(w.Header()[header], vals...)\n\t}\n\n\tw.WriteHeader(resp.StatusCode)\n\tio.Copy(w, resp.Body)\n}"} {"input": "package common\n\nimport (\n\t\"encoding/binary\"\n\t\"sort\"\n)\n\n\n\ntype Uint64Slice []uint64\n\nfunc (p Uint64Slice) Len() int { return len(p) }\nfunc (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] }\nfunc (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p Uint64Slice) Sort() { sort.Sort(p) }\n\nfunc SearchUint64s(a []uint64, x uint64) int {\n\treturn sort.Search(len(a), func(i int) bool { return a[i] >= x })\n}\n\nfunc (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) }\n\n\n\nfunc PutUint64LE(dest []byte, i uint64) {\n\tbinary.LittleEndian.PutUint64(dest, i)\n}\n\n\n\nfunc PutUint64BE(dest []byte, i uint64) {\n\tbinary.BigEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64BE(src []byte) uint64 {\n\treturn binary.BigEndian.Uint64(src)\n}\n\nfunc PutInt64LE(dest []byte, i int64) {\n\tbinary.LittleEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64LE(src []byte) int64 {\n\treturn int64(binary.LittleEndian.Uint64(src))\n}\n\nfunc PutInt64BE(dest []byte, i int64) {\n\tbinary.BigEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64BE(src []byte) int64 {\n\treturn int64(binary.BigEndian.Uint64(src))\n}\n\nfunc GetUint64LE(src []byte) uint64 ", "output": "{\n\treturn binary.LittleEndian.Uint64(src)\n}"} {"input": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"net/http\"\n\n\t\"github.com/whitepages/terraform-provider-stingray/Godeps/_workspace/src/github.com/whitepages/go-stingray\"\n)\n\n\n\ntype Config struct {\n\tURL string\n\tUsername string\n\tPassword string\n\tVerifySSL bool\n}\n\n\n\nfunc newClient(c *Config) *stingray.Client {\n\tif c.VerifySSL {\n\t\treturn stingray.NewClient(nil, c.URL, c.Username, c.Password)\n\t}\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\thttpClient := &http.Client{Transport: tr}\n\n\treturn stingray.NewClient(httpClient, c.URL, c.Username, c.Password)\n}\n\nfunc (c *Config) Client() (*stingray.Client, error) ", "output": "{\n\tclient := newClient(c)\n\n\treturn client, nil\n}"} {"input": "package http\n\nimport (\n\t\"github.com/asim/go-micro/v3/registry\"\n\t\"github.com/asim/go-micro/v3/server\"\n)\n\ntype httpHandler struct {\n\topts server.HandlerOptions\n\teps []*registry.Endpoint\n\thd interface{}\n}\n\nfunc (h *httpHandler) Name() string {\n\treturn \"handler\"\n}\n\nfunc (h *httpHandler) Handler() interface{} {\n\treturn h.hd\n}\n\nfunc (h *httpHandler) Endpoints() []*registry.Endpoint {\n\treturn h.eps\n}\n\n\n\nfunc (h *httpHandler) Options() server.HandlerOptions ", "output": "{\n\treturn h.opts\n}"} {"input": "package inigo\n\nimport (\n\t\"errors\"\n)\n\n\nfunc (config *Config) GetConfigFilename() string {\n\treturn config.filename\n}\n\n\nfunc (config *Config) GetAllSections() []string {\n\tvar res []string\n\n\tfor key, _ := range config.config {\n\t\tres = append(res, key)\n\t}\n\n\treturn res\n}\n\n\nfunc (config *Config) GetAllKeys() map[string][]string {\n\tvar res map[string][]string = make(map[string][]string)\n\n\tfor section, data := range config.config {\n\t\tfor key, _ := range data.data {\n\t\t\tres[section] = append(res[section], key)\n\t\t}\n\t}\n\n\treturn res\n}\n\n\n\n\nfunc (config *Config) GetValue(section, key string) (string, error) ", "output": "{\n\tvar processing bool = true\n\tvar currentSection string = section\n\tvar res string\n\n\tfor processing && len(currentSection) > 0 {\n\t\tres = config.config[currentSection].data[key]\n\n\t\tif len(res) > 0 {\n\t\t\tprocessing = false\n\t\t\tbreak\n\t\t} else {\n\t\t\tcurrentSection = config.config[currentSection].inheritSection\n\t\t}\n\t}\n\n\tif len(res) == 0 {\n\t\treturn res, errors.New(\"Has no key\")\n\t}\n\n\treturn res, nil\n}"} {"input": "package server\n\nimport (\n\t\"sync\"\n)\n\ntype ID uint32\n\ntype IDGenerator struct {\n\tlastID ID\n\tids []ID\n\tlocker *sync.Mutex\n\tthreadSafe bool\n}\n\n\n\nfunc (gen *IDGenerator) genIDs() {\n\tgen.lastID += ID(cap(gen.ids) / 2)\n\tid := gen.lastID - 1\n\tfor i := 0; i < cap(gen.ids)/2; i++ {\n\t\tgen.ids = append(gen.ids, id)\n\t\tid--\n\t}\n}\n\nfunc (gen *IDGenerator) NextID() ID {\n\tid := ID(0)\n\n\tif gen.threadSafe {\n\t\tgen.locker.Lock()\n\t\tdefer gen.locker.Unlock()\n\t}\n\tid, gen.ids = gen.ids[len(gen.ids)-1], gen.ids[:len(gen.ids)-1]\n\tif len(gen.ids) == 0 {\n\t\tgen.genIDs()\n\t}\n\n\treturn id\n}\n\nfunc (gen *IDGenerator) PutID(id ID) {\n\tif gen.threadSafe {\n\t\tgen.locker.Lock()\n\t\tdefer gen.locker.Unlock()\n\t}\n\tgen.ids = append(gen.ids, id)\n}\n\nfunc NewIDGenerator(buffer int, threadSafe bool) *IDGenerator ", "output": "{\n\tgen := &IDGenerator{0, make([]ID, 0, buffer), &sync.Mutex{}, threadSafe}\n\tif threadSafe {\n\t\tgen.locker.Lock()\n\t\tdefer gen.locker.Unlock()\n\t}\n\n\tgen.genIDs()\n\treturn gen\n}"} {"input": "package runtime\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"k8s.io/kubernetes/pkg/api/unversioned\"\n)\n\n\n\n\n\n\n\nfunc CheckCodec(c Codec, internalType Object, externalTypes ...unversioned.GroupVersionKind) error ", "output": "{\n\t_, err := Encode(c, internalType)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Internal type not encodable: %v\", err)\n\t}\n\tfor _, et := range externalTypes {\n\t\texBytes := []byte(fmt.Sprintf(`{\"kind\":\"%v\",\"apiVersion\":\"%v\"}`, et.Kind, et.GroupVersion().String()))\n\t\tobj, err := Decode(c, exBytes)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"external type %s not interpretable: %v\", et, err)\n\t\t}\n\t\tif reflect.TypeOf(obj) != reflect.TypeOf(internalType) {\n\t\t\treturn fmt.Errorf(\"decode of external type %s produced: %#v\", et, obj)\n\t\t}\n\t\terr = DecodeInto(c, exBytes, internalType)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"external type %s not convertable to internal type: %v\", et, err)\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package queue\n\nimport \"fmt\"\n\ntype Queue struct {\n\tElems []interface{}\n\tTop int\n\tBottom int\n\tMaxlen int\n\tFull bool\n}\n\n\nfunc New(maxLen int) *Queue {\n\tq := &Queue{\n\t\tElems: make([]interface{}, maxLen),\n\t\tTop: 0,\n\t\tBottom: 0,\n\t\tMaxlen: maxLen,\n\t}\n\n\tfmt.Printf(\"Queue: %d\\n\", q.Maxlen)\n\treturn q\n}\n\nfunc (q *Queue) EnQueue(e interface{}) {\n\n\tif q.Maxlen == q.Bottom - q.Top {\n\t\tq.Bottom = q.Top\n\t\tq.Full = true\n\t}\n\tq.Elems[q.Bottom] = e\n\tq.Bottom++\n\n}\n\n\n\nfunc (q *Queue) Len() int {\n\treturn len(q.Elems)\n}\n\nfunc (q *Queue) DeQueue() ", "output": "{\n\n\tif q.Bottom > q.Top {\n\t\tq.Top++\n\t}\n\n}"} {"input": "package template\n\nimport (\n\t\"github.com/dpb587/metalink\"\n)\n\ntype templateFile metalink.File\n\nfunc (tf templateFile) MD5() string {\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"md5\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\nfunc (tf templateFile) SHA1() string {\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"sha-1\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\n\n\nfunc (tf templateFile) SHA512() string {\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"sha-512\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\nfunc (tf templateFile) SHA256() string ", "output": "{\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"sha-256\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}"} {"input": "package log\n\nimport (\n\t\"sync\"\n\n\t\"github.com/asim/go-micro/v3/util/ring\"\n\t\"github.com/google/uuid\"\n)\n\n\ntype osLog struct {\n\tformat FormatFunc\n\tonce sync.Once\n\n\tsync.RWMutex\n\tbuffer *ring.Buffer\n\tsubs map[string]*osStream\n}\n\ntype osStream struct {\n\tstream chan Record\n}\n\n\nfunc (o *osLog) Read(...ReadOption) ([]Record, error) {\n\tvar records []Record\n\n\tfor _, v := range o.buffer.Get(100) {\n\t\trecords = append(records, v.Value.(Record))\n\t}\n\n\treturn records, nil\n}\n\n\nfunc (o *osLog) Write(r Record) error {\n\to.buffer.Put(r)\n\treturn nil\n}\n\n\nfunc (o *osLog) Stream() (Stream, error) {\n\to.Lock()\n\tdefer o.Unlock()\n\n\tst := &osStream{\n\t\tstream: make(chan Record, 128),\n\t}\n\n\to.subs[uuid.New().String()] = st\n\n\treturn st, nil\n}\n\nfunc (o *osStream) Chan() <-chan Record {\n\treturn o.stream\n}\n\nfunc (o *osStream) Stop() error {\n\treturn nil\n}\n\n\n\nfunc NewLog(opts ...Option) Log ", "output": "{\n\toptions := Options{\n\t\tFormat: DefaultFormat,\n\t}\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\tl := &osLog{\n\t\tformat: options.Format,\n\t\tbuffer: ring.New(1024),\n\t\tsubs: make(map[string]*osStream),\n\t}\n\n\treturn l\n}"} {"input": "package astutils\n\nimport (\n\t\"go/ast\"\n\t\"go/types\"\n)\n\n\nfunc FieldListName(fieldList *ast.FieldList, fieldPosition int, namePosition int) *string {\n\tnames := FieldListNames(fieldList, fieldPosition)\n\n\tif names == nil || len(names) <= namePosition {\n\t\treturn nil\n\t}\n\n\tname := names[namePosition]\n\n\tif name == nil {\n\t\treturn nil\n\t}\n\n\treturn &name.Name\n}\n\n\nfunc FieldListNames(fieldList *ast.FieldList, position int) []*ast.Ident {\n\tif fieldList == nil {\n\t\treturn nil\n\t}\n\n\tif len(fieldList.List) <= position {\n\t\treturn nil\n\t}\n\n\tfield := fieldList.List[position]\n\n\tif field == nil {\n\t\treturn nil\n\t}\n\n\treturn field.Names\n}\n\n\nfunc FieldListType(fieldList *ast.FieldList, position int) *ast.Expr {\n\tif fieldList == nil {\n\t\treturn nil\n\t}\n\n\tif len(fieldList.List) <= position {\n\t\treturn nil\n\t}\n\n\tfield := fieldList.List[position]\n\n\tif field == nil {\n\t\treturn nil\n\t}\n\n\treturn &field.Type\n}\n\n\n\nfunc HasFieldListLength(fieldList *ast.FieldList, expectedLength int) bool {\n\tif fieldList == nil {\n\t\treturn expectedLength == 0\n\t}\n\n\treturn len(fieldList.List) == expectedLength\n}\n\n\n\n\n\nfunc IsFieldListTypePackageType(fieldList *ast.FieldList, position int, info *types.Info, packageSuffix string, typeName string) bool {\n\tt := FieldListType(fieldList, position)\n\n\treturn t != nil && IsPackageFunctionFieldListType(*t, info, packageSuffix, typeName)\n}\n\nfunc IsFieldListType(fieldList *ast.FieldList, position int, exprFunc func(ast.Expr) bool) bool ", "output": "{\n\tt := FieldListType(fieldList, position)\n\n\treturn t != nil && exprFunc(*t)\n}"} {"input": "package pool\n\nimport (\n\t\"fmt\"\n\t\"net\"\n)\n\nconst (\n\t_net = \"udp4\" \n)\n\nfunc createUDPConnection(address string) (*net.UDPConn, error) {\n\taddr, err := net.ResolveUDPAddr(_net, address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconn, err := net.DialUDP(_net, nil, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn conn, nil\n}\n\nfunc worker(id int, address string, done chan bool, buffers <-chan []byte) {\n\n\tconn, err := createUDPConnection(address)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\terr := conn.Close()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}()\n\n\tfor buffer := range buffers {\n\t\t_, err := conn.Write(buffer)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tdone <- true\n}\n\ntype UDPPool struct {\n\tbuffers chan []byte\n\tdone chan bool\n}\n\n\nfunc NewUDPPool(address string, workerNumber int) *UDPPool {\n\tbuffers := make(chan []byte, workerNumber)\n\tdone := make(chan bool)\n\n\tfor wid := 1; wid < workerNumber; wid++ {\n\t\tgo worker(wid, address, done, buffers)\n\t}\n\treturn &UDPPool{buffers, done}\n}\n\n\n\nfunc (p *UDPPool) Close() {\n\tclose(p.buffers)\n}\n\nfunc (p *UDPPool) Fire(buffer []byte) ", "output": "{\n\tp.buffers <- buffer\n}"} {"input": "package version\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n)\n\ntype version struct {\n\t*flags.EmptyFlag\n\n\trequire string\n}\n\n\n\nfunc (cmd *version) Register(ctx context.Context, f *flag.FlagSet) {\n\tf.StringVar(&cmd.require, \"require\", \"\", \"Require govc version >= this value\")\n}\n\nfunc (cmd *version) Run(ctx context.Context, f *flag.FlagSet) error {\n\tver := flags.GitVersion\n\tif ver == \"\" {\n\t\tver = flags.Version\n\t}\n\n\tif cmd.require != \"\" {\n\t\tv, err := flags.ParseVersion(ver)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\trv, err := flags.ParseVersion(cmd.require)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse required version '%s': %s\", cmd.require, err)\n\t\t}\n\n\t\tif !rv.Lte(v) {\n\t\t\treturn fmt.Errorf(\"version %s or higher is required, this is version %s\", cmd.require, ver)\n\t\t}\n\t}\n\n\tfmt.Printf(\"govc %s\\n\", ver)\n\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tcli.Register(\"version\", &version{})\n}"} {"input": "package server\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"os/signal\"\n\n\t\"k8s.io/klog/v2\"\n)\n\nvar onlyOneSignalHandler = make(chan struct{})\nvar shutdownHandler chan os.Signal\n\n\n\n\n\n\nfunc SetupSignalHandler() <-chan struct{} {\n\treturn SetupSignalContext().Done()\n}\n\n\n\nfunc SetupSignalHandlerIgnoringFurtherSignals() <-chan struct{} {\n\treturn SetupSignalContextNotExiting().Done()\n}\n\n\n\n\nfunc SetupSignalContext() context.Context {\n\treturn setupSignalContext(true)\n}\n\n\n\nfunc SetupSignalContextNotExiting() context.Context {\n\treturn setupSignalContext(false)\n}\n\n\n\n\n\nfunc RequestShutdown() bool {\n\tif shutdownHandler != nil {\n\t\tselect {\n\t\tcase shutdownHandler <- shutdownSignals[0]:\n\t\t\treturn true\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc setupSignalContext(exitOnSecondSignal bool) context.Context ", "output": "{\n\tclose(onlyOneSignalHandler) \n\n\tshutdownHandler = make(chan os.Signal, 2)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tsignal.Notify(shutdownHandler, shutdownSignals...)\n\tgo func() {\n\t\t<-shutdownHandler\n\t\tcancel()\n\t\tif exitOnSecondSignal {\n\t\t\t<-shutdownHandler\n\t\t\tos.Exit(1)\n\t\t} else {\n\t\t\tfor {\n\t\t\t\t<-shutdownHandler\n\t\t\t\tklog.Infof(\"Termination signal has been received already. Ignoring signal.\")\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn ctx\n}"} {"input": "package iso20022\n\n\ntype AccountManagementConfirmation2 struct {\n\n\tConfirmationType *AccountManagementType2Code `xml:\"ConfTp\"`\n\n\tAccountApplicationIdentification *Max35Text `xml:\"AcctApplId,omitempty\"`\n\n\tClientReference *Max35Text `xml:\"ClntRef,omitempty\"`\n\n\tCounterpartyReference *AdditionalReference2 `xml:\"CtrPtyRef,omitempty\"`\n}\n\nfunc (a *AccountManagementConfirmation2) SetConfirmationType(value string) {\n\ta.ConfirmationType = (*AccountManagementType2Code)(&value)\n}\n\nfunc (a *AccountManagementConfirmation2) SetAccountApplicationIdentification(value string) {\n\ta.AccountApplicationIdentification = (*Max35Text)(&value)\n}\n\n\n\nfunc (a *AccountManagementConfirmation2) AddCounterpartyReference() *AdditionalReference2 {\n\ta.CounterpartyReference = new(AdditionalReference2)\n\treturn a.CounterpartyReference\n}\n\nfunc (a *AccountManagementConfirmation2) SetClientReference(value string) ", "output": "{\n\ta.ClientReference = (*Max35Text)(&value)\n}"} {"input": "package encryption\n\nimport (\n\t\"github.com/cgentry/gdriver\"\n\t\"testing\"\n)\n\ntype mockDriver struct{}\ntype mockCrypt struct{}\n\nfunc (m *mockDriver) Init() string { return \"init\" }\n\ntype tDriver1 struct{}\n\nfunc (t *tDriver1) New() interface{} { return &mockCrypt{} }\nfunc (t *tDriver1) Identity(id int) string {\n\tswitch id {\n\tcase gdriver.IdentityName:\n\t\treturn \"name\"\n\tcase gdriver.IdentityShort:\n\t\treturn \"short\"\n\tcase gdriver. IdentityLong:\n\t\treturn \"long\"\n\t}\n\treturn \"unknown\"\n}\n\nfunc (m *mockCrypt ) EncryptPassword(password string, salt string) string {\n\treturn password +\"/\" + salt\n}\nfunc (m *mockCrypt) ComparePasswords( a string, b string, c string ) bool {\n\treturn a==b\n}\n\nfunc (m *mockCrypt) Setup( a string ) EncryptDriver {\n\treturn m\n}\nfunc (t *mockCrypt) Id() string {\n\treturn gdriver.Help(DriverGroup, \"name\", gdriver.IdentityName)\n}\nfunc (t *mockCrypt) ShortHelp() string {\n\treturn gdriver.Help(DriverGroup, \"name\", gdriver.IdentityShort)\n}\nfunc (t *mockCrypt) LongHelp() string {\n\treturn gdriver.Help(DriverGroup, \"name\", gdriver.IdentityLong)\n}\n\n\n\n\nfunc TestRegister(t *testing.T) ", "output": "{\n\n\tgdriver.Register( DriverGroup, &tDriver1{})\n\n\tdrv := SetDefault( \"name\")\n\tif \"name\" != drv.Id() {\n\t\tt.Error(\"Name returned was not 'name': \" + drv.Id() )\n\t}\n\n\ttstString := drv.EncryptPassword( \"password\",\"salt\" )\n\tif \"password/salt\" != tstString {\n\t\tt.Error(\"Invalid return from encrypt: \" + tstString)\n\t}else {\n\n\t\tif ! drv.ComparePasswords(tstString, \"password/salt\", \"\") {\n\t\t\tt.Error(\"Invalid match from ComparePasswords\")\n\t\t}\n\n\t\tif drv.ComparePasswords(tstString, \"password?salt\", \"\") {\n\t\t\tt.Error(\"Invalid match from ComparePasswords\")\n\t\t}\n\t}\n}"} {"input": "package events\n\nimport (\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/gravitational/teleport/lib/session\"\n)\n\n\n\ntype DiscardAuditLog struct {\n}\n\nfunc (d *DiscardAuditLog) Close() error {\n\treturn nil\n}\n\nfunc (d *DiscardAuditLog) EmitAuditEvent(eventType string, fields EventFields) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionChunk(namespace string, sid session.ID, reader io.Reader) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionSlice(SessionSlice) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\nfunc (d *DiscardAuditLog) GetSessionEvents(namespace string, sid session.ID, after int) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchEvents(fromUTC, toUTC time.Time, query string) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchSessionEvents(fromUTC time.Time, toUTC time.Time) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\n\n\n\n\ntype discardSessionLogger struct {\n}\n\n\n\nfunc (d *discardSessionLogger) Close() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) Finalize() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) WriteChunk(chunk *SessionChunk) (written int, err error) {\n\treturn 0, nil\n}\n\nfunc (d *discardSessionLogger) LogEvent(fields EventFields) ", "output": "{\n\treturn\n}"} {"input": "package greeter\n\nimport \"fmt\"\n\n\ntype Greeter interface {\n\tGreet() string\n}\n\ntype lobby struct {\n\ttext string\n}\n\nfunc (l lobby) Greet() string {\n\treturn fmt.Sprintf(\"Greeting with %q\", l.text)\n}\n\n\n\n\nfunc New(s string) Greeter ", "output": "{\n\tif s == \"\" {\n\t\ts = \"You did not specify me :(\"\n\t}\n\treturn &lobby{\n\t\ttext: s,\n\t}\n}"} {"input": "package field\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype Path struct {\n\tname string \n\tindex string \n\tparent *Path \n}\n\n\n\n\n\nfunc (p *Path) Root() *Path {\n\tfor ; p.parent != nil; p = p.parent {\n\t}\n\treturn p\n}\n\n\nfunc (p *Path) Child(name string, moreNames ...string) *Path {\n\tr := NewPath(name, moreNames...)\n\tr.Root().parent = p\n\treturn r\n}\n\n\n\nfunc (p *Path) Index(index int) *Path {\n\treturn &Path{index: strconv.Itoa(index), parent: p}\n}\n\n\n\nfunc (p *Path) Key(key string) *Path {\n\treturn &Path{index: key, parent: p}\n}\n\n\nfunc (p *Path) String() string {\n\tif p == nil {\n\t\treturn \"\"\n\t}\n\telems := []*Path{}\n\tfor ; p != nil; p = p.parent {\n\t\telems = append(elems, p)\n\t}\n\n\tbuf := bytes.NewBuffer(nil)\n\tfor i := range elems {\n\t\tp := elems[len(elems)-1-i]\n\t\tif p.parent != nil && len(p.name) > 0 {\n\t\t\tbuf.WriteString(\".\")\n\t\t}\n\t\tif len(p.name) > 0 {\n\t\t\tbuf.WriteString(p.name)\n\t\t} else {\n\t\t\tfmt.Fprintf(buf, \"[%s]\", p.index)\n\t\t}\n\t}\n\treturn buf.String()\n}\n\nfunc NewPath(name string, moreNames ...string) *Path ", "output": "{\n\tr := &Path{name: name, parent: nil}\n\tfor _, anotherName := range moreNames {\n\t\tr = &Path{name: anotherName, parent: r}\n\t}\n\treturn r\n}"} {"input": "package email\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"github.com/smartystreets/goconvey/convey\"\n\t\"go-common/app/job/main/aegis/conf\"\n\t\"os\"\n\t\"testing\"\n)\n\nvar (\n\td *Dao\n)\n\nfunc TestMain(m *testing.M) {\n\tif os.Getenv(\"DEPLOY_ENV\") != \"\" {\n\t\tflag.Set(\"app_id\", \"main.archive.aegis-job\")\n\t\tflag.Set(\"conf_token\", \"aed3cc21ca345ffc284c6036da32352b\")\n\t\tflag.Set(\"tree_id\", \"61819\")\n\t\tflag.Set(\"conf_version\", \"1\")\n\t\tflag.Set(\"deploy_env\", \"uat\")\n\t\tflag.Set(\"conf_host\", \"config.bilibili.co\")\n\t\tflag.Set(\"conf_path\", \"/tmp\")\n\t\tflag.Set(\"region\", \"sh\")\n\t\tflag.Set(\"zone\", \"sh001\")\n\t} else {\n\t\tflag.Set(\"conf\", \"../../cmd/aegis-job.toml\")\n\t}\n\tflag.Parse()\n\tif err := conf.Init(); err != nil {\n\t\tpanic(err)\n\t}\n\td = New(conf.Conf)\n\tos.Exit(m.Run())\n}\n\n\nfunc TestDao_MonitorEmailProc(t *testing.T) {\n\tconvey.Convey(\"MonitorEmailProc\", t, func(ctx convey.C) {\n\t\tctx.Convey(\"When everything goes positive\", func(ctx convey.C) {\n\t\t\terr := d.MonitorEmailProc()\n\t\t\tctx.Convey(\"Then err should be nil.tasks,lastid should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestDao_MonitorEmailAsync(t *testing.T) ", "output": "{\n\tconvey.Convey(\"MonitorEmailAsync\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t)\n\t\tctx.Convey(\"When everything goes positive\", func(ctx convey.C) {\n\t\t\terr := d.MonitorEmailAsync(c, []string{\"abc@bilibili.com\"}, \"测试标题\", \"测试内容link\")\n\t\t\tctx.Convey(\"Then err should be nil.tasks,lastid should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package fake\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\n\t. \"github.com/onsi/gomega\"\n\t\"github.com/onsi/gomega/ghttp\"\n)\n\ntype CFAPI struct {\n\tserver *ghttp.Server\n}\n\ntype CFAPIConfig struct {\n\tRoutes map[string]Response\n}\n\ntype Response struct {\n\tCode int\n\tBody interface{}\n}\n\nfunc NewCFAPI() *CFAPI {\n\tserver := ghttp.NewServer()\n\treturn &CFAPI{\n\t\tserver: server,\n\t}\n}\n\nfunc (a *CFAPI) SetConfiguration(config CFAPIConfig) {\n\ta.server.Reset()\n\n\tfor request, response := range config.Routes {\n\t\tmethod, path := parseRequest(request)\n\t\tresponseBytes, err := json.Marshal(response.Body)\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\ta.server.RouteToHandler(method, path, ghttp.RespondWith(response.Code, responseBytes))\n\t}\n}\n\nfunc (a *CFAPI) Close() {\n\ta.server.Close()\n}\n\n\n\nfunc (a *CFAPI) ReceivedRequests() map[string][]*http.Request {\n\tresult := map[string][]*http.Request{}\n\n\tfor _, req := range a.server.ReceivedRequests() {\n\t\tkey := fmt.Sprintf(\"%s %s\", req.Method, req.URL.Path)\n\t\tresult[key] = append(result[key], req)\n\t}\n\n\treturn result\n}\n\nfunc parseRequest(request string) (string, string) {\n\tfields := strings.Split(request, \" \")\n\tExpect(fields).To(HaveLen(2))\n\treturn fields[0], fields[1]\n}\n\nfunc (a *CFAPI) URL() string ", "output": "{\n\treturn a.server.URL()\n}"} {"input": "package action\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n)\n\ntype catalogNode struct {\n\t*config\n}\n\nfunc CatalogNodeAction() Action {\n\treturn &catalogNode{\n\t\tconfig: &gConfig,\n\t}\n}\n\n\n\nfunc (c *catalogNode) Run(args []string) error {\n\tswitch {\n\tcase len(args) == 0:\n\t\treturn fmt.Errorf(\"Node name must be specified\")\n\tcase len(args) > 1:\n\t\treturn fmt.Errorf(\"Only one node allowed\")\n\t}\n\n\tclient, err := c.newCatalog()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tqueryOpts := c.queryOptions()\n\tconfig, _, err := client.Node(args[0], queryOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.Output(config)\n}\n\nfunc (c *catalogNode) CommandFlags() *flag.FlagSet ", "output": "{\n\treturn c.newFlagSet(FLAG_DATACENTER, FLAG_CONSISTENCY, FLAG_OUTPUT, FLAG_BLOCKING)\n}"} {"input": "package ocvp\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListWorkRequestsRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tResourceId *string `mandatory:\"false\" contributesTo:\"query\" name:\"resourceId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListWorkRequestsRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListWorkRequestsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ListWorkRequestsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ListWorkRequestsRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListWorkRequestsResponse struct {\n\n\tRawResponse *http.Response\n\n\tWorkRequestCollection `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n}\n\nfunc (response ListWorkRequestsResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response ListWorkRequestsResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package stat\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype RevStat struct {\n\tRevId string `json:\"RevId\"`\n\tUserName string `json:\"UserName\"`\n\tWordCount int `json:\"WordCount\"`\n\tModDate string `json:\"ModDate\"`\n\tWordFreq []WordPair `json:\"WordFreq\"`\n}\n\ntype DocStat struct {\n\tFileId string `json:\"FileId\"`\n\tTitle string `json:\"Title\"`\n\tLastMod string `json:\"LastMod\"`\n\tRevList []RevStat `json:\"RevList\"`\n}\n\nfunc (rev RevStat) GetTime() string {\n\tx, _ := time.Parse(\"2006-01-02T15:04:05.000Z\", rev.ModDate)\n\treturn x.Format(\"15:04\")\n}\n\nfunc (rev RevStat) String() string {\n\treturn fmt.Sprintf(\"[%s %s] %d words by %s. \\n\\t Words [%s]\", rev.ModDate, rev.RevId, rev.WordCount, rev.UserName, rev.WordFreq)\n}\n\n\nfunc (doc DocStat) String() string ", "output": "{\n\ts := fmt.Sprintf(\"[%s] '%s' last mod on %s with revs\\n\", doc.FileId, doc.Title, doc.LastMod)\n\tfor i, v := range doc.RevList {\n\t\ts += fmt.Sprintf(\"\\t %d:%s\\n\", i, v)\n\t}\n\treturn s\n}"} {"input": "package web\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/gravitational/teleport/lib/httplib\"\n\n\t\"github.com/gravitational/roundtrip\"\n\t\"github.com/gravitational/trace\"\n)\n\nfunc newInsecureClient() *http.Client {\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t}\n}\n\nfunc newClientWithPool(pool *x509.CertPool) *http.Client {\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{RootCAs: pool},\n\t\t},\n\t}\n}\n\nfunc newWebClient(url string, opts ...roundtrip.ClientParam) (*webClient, error) {\n\tclt, err := roundtrip.NewClient(url, APIVersion, opts...)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn &webClient{clt}, nil\n}\n\n\n\ntype webClient struct {\n\t*roundtrip.Client\n}\n\nfunc (w *webClient) PostJSON(\n\tendpoint string, val interface{}) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.PostJSON(endpoint, val))\n}\n\n\n\nfunc (w *webClient) Get(endpoint string, val url.Values) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.Get(endpoint, val))\n}\n\nfunc (w *webClient) Delete(endpoint string) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.Delete(endpoint))\n}\n\nfunc (w *webClient) PutJSON(\n\tendpoint string, val interface{}) (*roundtrip.Response, error) ", "output": "{\n\treturn httplib.ConvertResponse(w.Client.PutJSON(endpoint, val))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net\"\n\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/host\", hostFinder)\n\thttp.HandleFunc(\"/ip\", sourceIp)\n\thttp.HandleFunc(\"/date\", GetJosnTime)\n\tfmt.Println(\"Listening on 0.0.0.0:8000\")\n\terr := http.ListenAndServe(\"0.0.0.0:8000\", nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}\n\n\n\nfunc sourceIp(rw http.ResponseWriter, req *http.Request) {\n\thost, _, _ := net.SplitHostPort(req.RemoteAddr)\n\tio.WriteString(rw, \"

Your Ip address : \"+host)\n}\nfunc GetJosnTime(rw http.ResponseWriter, req *http.Request) {\n\trw.Header().Set(\"Content-type\", \"application/json\")\n\trw.Header().Add(\"Content-type\", \"charset=utf-8\")\n\tresponse, _ := http.Get(\"http://date.jsontest.com/\")\n\tdefer response.Body.Close()\n\n\tdata, _ := ioutil.ReadAll(response.Body)\n\tio.WriteString(rw, string(data))\n\n}\n\nfunc hostFinder(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\thostPort := req.Host\n\thost, port, _ := net.SplitHostPort(hostPort)\n\tio.WriteString(rw, \"\")\n\tio.WriteString(rw, \"Host Name : \"+host+\"
\")\n\tio.WriteString(rw, \"Port Number : \"+port)\n\tio.WriteString(rw, \"
\")\n\tio.WriteString(rw, req.RemoteAddr)\n\tio.WriteString(rw, \"\")\n\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Frame struct {\n\tNotice string\n\tAuth string\n\tShit string\n\tMessage string\n}\n\ntype UserFrame struct {\n\tName2, Name3 string\n\tHost string\n\tName4 string\n}\n\n\nfunc DeserializeUserFrame(input string) *UserFrame {\n\tdob := strings.Split(input, \" \")\n\tc := &UserFrame{\n\t\tName2: getFrame(dob, 1),\n\t\tName3: getFrame(dob, 2),\n\t\tHost: getFrame(dob, 3),\n\t\tName4: getFrame(dob, 4),\n\t}\n\treturn c\n}\n\nfunc (f *Frame) SerializeToString() string {\n\treturn fmt.Sprintf(\"%s %s %s %s\\n\", f.Notice, f.Auth, f.Shit, f.Message)\n}\n\nfunc (f *Frame) Serialize() []byte {\n\treturn []byte(f.SerializeToString())\n}\n\nfunc getFrame(input []string, c int) string ", "output": "{\n\tif c > len(input) {\n\t\treturn \"\"\n\t}\n\n\treturn input[c]\n}"} {"input": "package minicon\n\nimport \"container/ring\"\n\n\n\n\ntype History struct {\n\tr *ring.Ring\n}\n\n\n\n\ntype HistoryMarker *ring.Ring\n\n\n\n\n\n\n\n\n\n\n\nfunc (hs *History) Add(s string, mark HistoryMarker) HistoryMarker {\n\ths.Restore(mark)\n\tif s != \"\" && hs.r.Value != s {\n\t\ths.r.Value = s\n\t\ths.r = hs.r.Next()\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (hs *History) Back() (string, bool) {\n\treturn hs._update(hs.r.Prev())\n}\n\n\n\n\n\nfunc (hs *History) Forward() (string, bool) {\n\treturn hs._update(hs.r.Next())\n}\n\n\n\n\nfunc (hs *History) Mark() HistoryMarker {\n\treturn hs.r\n}\n\n\n\n\nfunc (hs *History) Restore(mark HistoryMarker) {\n\tif mark != nil {\n\t\ths.r = mark\n\t}\n}\n\n\n\n\nfunc (hs *History) _update(r *ring.Ring) (ret string, okay bool) {\n\tif s, ok := r.Value.(string); ok && s != \"\" {\n\t\ths.r = r\n\t\tret, okay = s, ok\n\t}\n\treturn ret, okay\n}\n\nfunc NewHistory(capacity int) *History ", "output": "{\n\treturn &History{ring.New(capacity)}\n}"} {"input": "package lib2048\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Direction int\n\nconst layout = \"15:04:05.12\"\nconst (\n\tUp Direction = iota + 1\n\tLeft\n\tDown\n\tRight\n)\n\ntype Move struct {\n\tTime time.Time\n\tDirection Direction\n}\n\n\n\nfunc (m *Move) String() string {\n\tvar moveString string\n\tswitch m.Direction {\n\tcase Up:\n\t\tmoveString = \"Up\"\n\tcase Down:\n\t\tmoveString = \"Down\"\n\tcase Left:\n\t\tmoveString = \"Left\"\n\tcase Right:\n\t\tmoveString = \"Right\"\n\t}\n\n\treturn fmt.Sprintf(\"'%s': %s\", m.Time.Format(layout), moveString)\n}\n\nfunc NewMove(dir Direction) *Move ", "output": "{\n\treturn &Move{time.Now(), dir}\n}"} {"input": "package video\n\nimport (\n\t\"sync\"\n\t\"github.com/elliotmr/gdl/event\"\n\t\"github.com/elliotmr/gdl/w32\"\n\t\"github.com/elliotmr/gdl/w32/types/cs\"\n\t\"github.com/elliotmr/gdl/w32/types/wm\"\n\t\"fmt\"\n)\n\nvar GDLAppClass *w32.WindowClass\n\ntype eventHandler struct {\n\twindow *Window\n}\n\nfunc (eh *eventHandler) OnMessage(uMsg uint32, wParam, lParam uintptr) (bool, uintptr) {\n\tif event.Q.Enabled(event.SysWMEvent) {\n\t}\n\tswitch uMsg {\n\tcase wm.ShowWindow:\n\t\tif wParam > 0 {\n\t\t\teh.window.SendEvent(event.WindowShown, 0, 0)\n\t\t} else {\n\t\t\teh.window.SendEvent(event.WindowHidden, 0, 0)\n\t\t}\n\tcase wm.Activate:\n\tcase wm.MouseMove:\n\n\t\tfallthrough\n\tcase wm.LButtonUp, wm.LButtonDown, wm.LButtonDblClk, wm.RButtonUp, wm.RButtonDown, wm.RButtonDblClk,\n\t\t wm.MButtonUp, wm.MButtonDown, wm.MButtonDblClk, wm.XButtonUp, wm.XButtonDown, wm.XButtonDblClk:\n\n\t}\n\n\treturn false, 0\n}\n\n\n\nfunc registerApp(name string, style cs.ClassStyle) error ", "output": "{\n\tvar once sync.Once\n\tonce.Do(func() {\n\t\tfmt.Println(\"registering app\")\n\t\tif name == \"\" {\n\t\t\tname = \"GDL_app\"\n\t\t}\n\t\tif style == 0 {\n\t\t\tstyle = cs.ByteAlignClient | cs.OwnDC | cs.VReDraw | cs.HReDraw\n\t\t}\n\t\tGDLAppClass = &w32.WindowClass{\n\t\t\tName: name,\n\t\t\tStyle: style,\n\t\t}\n\t\terr := GDLAppClass.Register()\n\t\tif err != nil {\n\t\t\tpanic(err) \n\t\t}\n\n\t})\n\treturn nil\n}"} {"input": "package alicloud\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/resource\"\n)\n\n\n\nfunc TestAccAlicloudCenBandwidthPackage_importBasic(t *testing.T) ", "output": "{\n\tresourceName := \"alicloud_cen_bandwidth_package.foo\"\n\tignoreFields := []string{\"period\"}\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testAccCheckCenBandwidthPackageDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccCenBandwidthPackageConfig,\n\t\t\t},\n\n\t\t\tresource.TestStep{\n\t\t\t\tResourceName: resourceName,\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t\tImportStateVerifyIgnore: ignoreFields,\n\t\t\t},\n\t\t},\n\t})\n}"} {"input": "package elasticthought\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n)\n\nvar (\n\tDefaultMockBlobStore *MockBlobStore\n)\n\nfunc init() {\n\tDefaultMockBlobStore = &MockBlobStore{\n\t\tGetResponses: map[string]ResponseQueue{},\n\t}\n}\n\ntype MockBlobStore struct {\n\n\tGetResponses map[string]ResponseQueue\n}\n\ntype ResponseQueue []io.Reader\n\nfunc NewMockBlobStore() *MockBlobStore {\n\tif DefaultMockBlobStore == nil {\n\t\tDefaultMockBlobStore = &MockBlobStore{\n\t\t\tGetResponses: map[string]ResponseQueue{},\n\t\t}\n\n\t}\n\treturn DefaultMockBlobStore\n}\n\n\n\nfunc (m *MockBlobStore) Put(srcname, dest string, r io.Reader, opts BlobPutOptions) error {\n\treturn nil\n}\n\nfunc (m *MockBlobStore) Rm(fn string) error {\n\treturn nil\n}\n\nfunc (m *MockBlobStore) OpenFile(path string) (BlobHandle, error) {\n\treturn nil, nil\n}\n\ntype nopCloser struct {\n\tio.Reader\n}\n\nfunc (nopCloser) Close() error {\n\treturn nil\n}\n\nfunc (m *MockBlobStore) responseQueueForPath(path string) (string, ResponseQueue) {\n\tfor k, v := range m.GetResponses {\n\t\tif path == \"*\" {\n\t\t\treturn k, v\n\t\t}\n\t\tif strings.Contains(k, path) { \n\t\t\treturn k, v\n\t\t}\n\t}\n\treturn \"\", nil\n}\n\n\nfunc (m *MockBlobStore) QueueGetResponse(pathRegex string, response io.Reader) {\n\tqueue, ok := m.GetResponses[pathRegex]\n\tif !ok {\n\t\tqueue = ResponseQueue{}\n\t}\n\tqueue = append(queue, response)\n\tm.GetResponses[pathRegex] = queue\n}\n\nfunc (m *MockBlobStore) Get(path string) (io.ReadCloser, error) ", "output": "{\n\tmatchingKey, queue := m.responseQueueForPath(path)\n\tif len(queue) == 0 {\n\t\treturn nil, fmt.Errorf(\"No more items in mock blob store for %v\", path)\n\t}\n\tfirstItem := queue[0]\n\tm.GetResponses[matchingKey] = queue[1:]\n\n\treturn nopCloser{firstItem}, nil\n}"} {"input": "package deb\n\nimport (\n\t\"encoding/binary\"\n\t\"github.com/smira/aptly/aptly\"\n\t\"github.com/smira/aptly/utils\"\n\t\"hash/fnv\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n)\n\n\ntype PackageFile struct {\n\tFilename string\n\tChecksums utils.ChecksumInfo\n\tdownloadPath string\n}\n\n\nfunc (f *PackageFile) Verify(packagePool aptly.PackagePool) (bool, error) {\n\tpoolPath, err := packagePool.Path(f.Filename, f.Checksums.MD5)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tst, err := os.Stat(poolPath)\n\tif err != nil {\n\t\treturn false, nil\n\t}\n\n\treturn st.Size() == f.Checksums.Size, nil\n}\n\n\n\n\n\ntype PackageFiles []PackageFile\n\n\nfunc (files PackageFiles) Hash() uint64 {\n\tsort.Sort(files)\n\n\th := fnv.New64a()\n\n\tfor _, f := range files {\n\t\th.Write([]byte(f.Filename))\n\t\tbinary.Write(h, binary.BigEndian, f.Checksums.Size)\n\t\th.Write([]byte(f.Checksums.MD5))\n\t\th.Write([]byte(f.Checksums.SHA1))\n\t\th.Write([]byte(f.Checksums.SHA256))\n\t}\n\n\treturn h.Sum64()\n}\n\n\nfunc (files PackageFiles) Len() int {\n\treturn len(files)\n}\n\n\nfunc (files PackageFiles) Swap(i, j int) {\n\tfiles[i], files[j] = files[j], files[i]\n}\n\n\nfunc (files PackageFiles) Less(i, j int) bool {\n\treturn files[i].Filename < files[j].Filename\n}\n\nfunc (f *PackageFile) DownloadURL() string ", "output": "{\n\treturn filepath.Join(f.downloadPath, f.Filename)\n}"} {"input": "package header\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n\n\nfunc NoCache(c *gin.Context) {\n\tc.Header(\"Cache-Control\", \"no-cache, no-store, max-age=0, must-revalidate, value\")\n\tc.Header(\"Expires\", \"Thu, 01 Jan 1970 00:00:00 GMT\")\n\tc.Header(\"Last-Modified\", time.Now().UTC().Format(http.TimeFormat))\n\tc.Next()\n}\n\n\n\n\n\n\n\n\nfunc Secure(c *gin.Context) {\n\tc.Header(\"Access-Control-Allow-Origin\", \"*\")\n\tc.Header(\"X-Frame-Options\", \"DENY\")\n\tc.Header(\"X-Content-Type-Options\", \"nosniff\")\n\tc.Header(\"X-XSS-Protection\", \"1; mode=block\")\n\tif c.Request.TLS != nil {\n\t\tc.Header(\"Strict-Transport-Security\", \"max-age=31536000\")\n\t}\n}\n\nfunc Options(c *gin.Context) ", "output": "{\n\tif c.Request.Method != \"OPTIONS\" {\n\t\tc.Next()\n\t} else {\n\t\tc.Header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tc.Header(\"Access-Control-Allow-Methods\", \"GET,POST,PUT,PATCH,DELETE,OPTIONS\")\n\t\tc.Header(\"Access-Control-Allow-Headers\", \"authorization, origin, content-type, accept\")\n\t\tc.Header(\"Allow\", \"HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS\")\n\t\tc.Header(\"Content-Type\", \"application/json\")\n\t\tc.AbortWithStatus(200)\n\t}\n}"} {"input": "package errors \n\nimport (\n\t\"strconv\"\n)\n\n\n\ntype StructuralError string\n\nfunc (s StructuralError) Error() string {\n\treturn \"openpgp: invalid data: \" + string(s)\n}\n\n\n\ntype UnsupportedError string\n\nfunc (s UnsupportedError) Error() string {\n\treturn \"openpgp: unsupported feature: \" + string(s)\n}\n\n\n\ntype InvalidArgumentError string\n\nfunc (i InvalidArgumentError) Error() string {\n\treturn \"openpgp: invalid argument: \" + string(i)\n}\n\n\n\ntype SignatureError string\n\nfunc (b SignatureError) Error() string {\n\treturn \"openpgp: invalid signature: \" + string(b)\n}\n\ntype keyIncorrectError int\n\nfunc (ki keyIncorrectError) Error() string {\n\treturn \"openpgp: incorrect key\"\n}\n\nvar ErrKeyIncorrect error = keyIncorrectError(0)\n\ntype unknownIssuerError int\n\nfunc (unknownIssuerError) Error() string {\n\treturn \"openpgp: signature made by unknown entity\"\n}\n\nvar ErrUnknownIssuer error = unknownIssuerError(0)\n\ntype keyRevokedError int\n\nfunc (keyRevokedError) Error() string {\n\treturn \"openpgp: signature made by revoked key\"\n}\n\nvar ErrKeyRevoked error = keyRevokedError(0)\n\ntype UnknownPacketTypeError uint8\n\n\n\nfunc (upte UnknownPacketTypeError) Error() string ", "output": "{\n\treturn \"openpgp: unknown packet type: \" + strconv.Itoa(int(upte))\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\tvar a, b, res uint32;\n\n\tfmt.Scanf(\"%v %v\", &a, &b)\n\tres = solveMeFirst(a, b)\n\tfmt.Println(res)\n}\n\nfunc solveMeFirst(a, b uint32) uint32 ", "output": "{\n\treturn a + b\n}"} {"input": "package foo\n\nfunc f(x interface{}) {\n\tswitch t := x.(type) { \n\tcase int:\n\t}\n}\n\n\n\nfunc h(x interface{}) {\n\tswitch t := x.(type) {\n\tcase int:\n\tcase float32:\n\tdefault:\n\t\tprintln(t)\n\t}\n}\n\nfunc g(x interface{}) ", "output": "{\n\tswitch t := x.(type) {\n\tcase int:\n\tcase float32:\n\t\tprintln(t)\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc foo(x int) bool {\n\treturn x == x \n}\n\nfunc isNaN(x float32) bool {\n\treturn x != x \n}\n\nfunc main() {\n\tfoo(42)\n}\n\nconst mode = \"Debug\"\n\nfunc log(msg string) {\n\tif mode == \"Debug\" {\n\t\tfmt.Println(msg)\n\t}\n}\n\nfunc bar() {\n\tif ptrsize == 8 { \n\t\tfmt.Println()\n\t}\n}\n\nfunc bump(x *int) {\n\t*x++\n}\n\nfunc baz() bool {\n\tvar x = 0\n\tbump(&x)\n\treturn x == 0\n}\n\ntype counter int\n\nfunc (x *counter) bump() {\n\t*x++\n}\n\n\n\nfunc baz2() bool {\n\tvar x counter\n\tx.bump()\n\treturn x == 0 \n}\n\nfunc baz3() bool {\n\tvar y counter\n\ty.bimp()\n\treturn y == 0 \n}\n\nfunc (x counter) bimp() ", "output": "{\n\tx++\n}"} {"input": "package homedir \n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n)\n\nfunc TestGet(t *testing.T) {\n\thome := Get()\n\tif home == \"\" {\n\t\tt.Fatal(\"returned home directory is empty\")\n\t}\n\n\tif !filepath.IsAbs(home) {\n\t\tt.Fatalf(\"returned path is not absolute: %s\", home)\n\t}\n}\n\n\n\nfunc TestGetShortcutString(t *testing.T) ", "output": "{\n\tshortcut := GetShortcutString()\n\tif shortcut == \"\" {\n\t\tt.Fatal(\"returned shortcut string is empty\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\nfunc TestLevel4(t *testing.T) {\n\th := 0\n\tfor i := 999; i > 99; i-- {\n\t\tfor j := 100; j < 1000; j++ {\n\t\t\tp := i * j\n\t\t\tr := xreverse(p)\n\t\t\tif xisPalindrome(r, p) {\n\t\t\t\tif h < p {\n\t\t\t\t\th = p\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif h != 906609 {\n\t\tt.Errorf(\"Error: largest palindrome should not be: %d \", h)\n\t}\n\n}\n\n\n\nfunc xreverse(n int) (r int) {\n\tfor {\n\t\tif n > 0 {\n\t\t\tr = r * 10 + n % 10\n\t\t\tn = n / 10\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn r\n}\n\nfunc xisPalindrome(r, v int) bool ", "output": "{\n\treturn r == v\n}"} {"input": "package query\n\nimport (\n\t\"encoding/json\"\n\t\"reflect\"\n)\n\nfunc toJson(v interface{}) ([]byte, error) {\n\treturn json.Marshal(v)\n}\n\n\n\nfunc convert(value reflect.Value) interface{} {\n\tswitch value.Kind() {\n\tcase reflect.Slice:\n\t\tvar res []interface{}\n\t\tfor i := 0; i < value.Len(); i++ {\n\t\t\tres = append(res, convert(value.Index(i)))\n\t\t}\n\t\treturn res\n\tcase reflect.Ptr:\n\t\tif !value.IsNil() {\n\t\t\treturn convert(value.Elem())\n\t\t}\n\tcase reflect.String:\n\t\treturn value.String()\n\tcase reflect.Float64:\n\t\treturn value.Float()\n\tcase reflect.Int:\n\t\treturn value.Int()\n\tcase reflect.Bool:\n\t\treturn value.Bool()\n\t}\n\treturn value.Interface()\n}\n\nfunc convertable(value reflect.Value) bool {\n\tswitch value.Kind() {\n\tcase reflect.Slice:\n\t\treturn value.Len() > 0\n\tcase reflect.Ptr:\n\t\treturn !value.IsNil()\n\t}\n\treturn true\n}\n\nfunc convertStruct(x interface{}) interface{} {\n\tquery := make(map[string]interface{})\n\n\tt := reflect.ValueOf(x).Type()\n\tv := reflect.ValueOf(x)\n\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tfield := t.Field(i)\n\t\tvalue := v.FieldByName(field.Name)\n\t\ttag := field.Tag.Get(\"json\")\n\t\tif tag == \"-\" {\n\t\t\tcontinue\n\t\t}\n\t\tif convertable(value) {\n\t\t\tquery[tag] = convert(value)\n\t\t}\n\t}\n\n\treturn query\n\n}\n\nfunc wrapper(name string, v interface{}) map[string]interface{} ", "output": "{\n\tquery := map[string]interface{}{\n\t\tname: v,\n\t}\n\treturn query\n}"} {"input": "package tunnel\n\nimport (\n \"container/list\"\n \"time\"\n)\n\ntype recyclerItem struct {\n when time.Time\n buf []byte\n}\n\ntype recycler struct {\n q *list.List\n takeChan, giveChan chan []byte\n}\n\n\n\nfunc (r *recycler) cycle(size uint32) {\n for {\n if r.q.Len() == 0 {\n \n r.q.PushFront(recyclerItem{when: time.Now(), buf: make([]byte, size)})\n }\n i := r.q.Front()\n timeout := time.NewTimer(time.Minute)\n select {\n case b:= <-r.giveChan:\n timeout.Stop()\n r.q.PushFront(recyclerItem{when: time.Now(), buf: b})\n case r.takeChan <- i.Value.(recyclerItem).buf:\n timeout.Stop()\n r.q.Remove(i)\n case <-timeout.C:\n i := r.q.Front()\n for i != nil {\n n := i.Next()\n if time.Since(i.Value.(recyclerItem).when) > time.Minute {\n r.q.Remove(i)\n i.Value = nil\n }\n i = n\n }\n }\n }\n}\n\nfunc (r *recycler) take() []byte {\n return <-r.takeChan\n}\n\nfunc (r *recycler) give(b []byte) {\n r.giveChan <- b\n}\n\nfunc NewRecycler(size uint32) *recycler ", "output": "{\n r := &recycler{\n q: new(list.List),\n takeChan: make(chan []byte),\n giveChan: make(chan []byte),\n }\n go r.cycle(size)\n return r\n}"} {"input": "package main\n\nimport \"github.com/augustoroman/serial_lcd\"\n\ntype FakeLcd struct{}\n\nfunc (f FakeLcd) SetBG(r, g, b uint8) error { return nil }\nfunc (f FakeLcd) SetOn(On bool) error { return nil }\nfunc (f FakeLcd) SetBrightness(b uint8) error { return nil }\nfunc (f FakeLcd) SetContrast(c uint8) error { return nil }\nfunc (f FakeLcd) SetAutoscroll(On bool) error { return nil }\nfunc (f FakeLcd) SetSize(cols, rows uint8) error { return nil }\n\nfunc (f FakeLcd) Home() error { return nil }\nfunc (f FakeLcd) MoveTo(col, row uint8) error { return nil }\nfunc (f FakeLcd) MoveForward() error { return nil }\nfunc (f FakeLcd) MoveBack() error { return nil }\nfunc (f FakeLcd) Write(b []byte) (int, error) { return len(b), nil }\n\nfunc (f FakeLcd) CreateCustomChar(spot uint8, c serial_lcd.Char) error { return nil }\n\nfunc (f FakeLcd) Clear() error ", "output": "{ return nil }"} {"input": "package e2e\n\nimport (\n\t\"testing\"\n\t\"flag\"\n\n\t\"github.com/kubernetes-incubator/service-catalog/test/e2e/framework\"\n)\n\nvar brokerImageFlag string\n\n\n\nfunc TestE2E(t *testing.T) {\n\tRunE2ETests(t)\n}\n\nfunc init() ", "output": "{\n\tflag.StringVar(&brokerImageFlag, \"broker-image\", \"quay.io/kubernetes-service-catalog/user-broker:latest\",\n\t\t\"The container image for the broker to test against\")\n\tframework.RegisterParseFlags()\n}"} {"input": "package main\n\nimport \"code.google.com/p/go-tour/tree\"\nimport \"fmt\"\n\nfunc walk(t *tree.Tree, ch chan int){\n if t != nil {\n walk(t.Left, ch)\n ch <- t.Value\n \twalk(t.Right, ch)\n }\n \n}\n\n\n\n\n\n\n\nfunc Same(t1, t2 *tree.Tree) bool {\n ch1 := make(chan int)\n ch2 := make(chan int)\n \n go Walk(t1, ch1)\n go Walk(t2, ch2)\n \n for i := range ch1 { \n\t\tif i != <- ch2 {\n \t\t\treturn false\n }\n }\n return true\n}\n\nfunc main() {\n ch := make(chan int)\n \n go Walk(tree.New(1), ch)\n \n for i := range ch {\n fmt.Println(i)\n }\n \n fmt.Println(Same(tree.New(1), tree.New(1)))\n fmt.Println(Same(tree.New(1), tree.New(2)))\n}\n\nfunc Walk(t *tree.Tree, ch chan int)", "output": "{\n\twalk(t, ch)\n close(ch)\n}"} {"input": "package gochimp\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype APIError struct {\n\tStatus string `json:\"status\"`\n\tCode int `json:\"code\"`\n\tName string `json:\"name\"`\n\tErr string `json:\"error\"`\n}\n\nfunc (e APIError) Error() string {\n\treturn fmt.Sprintf(\"%v: %v\", e.Code, e.Err)\n}\n\nfunc chimpErrorCheck(body []byte) error {\n\tvar e APIError\n\tjson.Unmarshal(body, &e)\n\tif e.Err != \"\" || e.Code != 0 {\n\t\treturn e\n\t}\n\treturn nil\n}\n\n\ntype APITime struct {\n\ttime.Time\n}\n\nfunc (t *APITime) UnmarshalJSON(data []byte) (err error) {\n\ts := string(data)\n\tl := len(s)\n\tswitch {\n\tcase l == 12:\n\t\tt.Time, err = time.Parse(`\"2006-01-02\"`, s)\n\tcase l == 21:\n\t\tt.Time, err = time.Parse(`\"2006-01-02 15:04:05\"`, s)\n\tcase l == 27:\n\t\tt.Time, err = time.Parse(`\"2006-01-02 15:04:05.00000\"`, s)\n\tcase l == 9:\n\t\tt.Time, err = time.Parse(`\"2006-01\"`, s)\n\t}\n\treturn\n}\n\n\nconst APITimeFormat = \"2006-01-02 15:04:05\"\n\n\n\nfunc apiTime(t interface{}) interface{} ", "output": "{\n\tswitch ti := t.(type) {\n\tcase time.Time:\n\t\treturn ti.Format(APITimeFormat)\n\tcase string:\n\t\treturn ti\n\t}\n\treturn t\n}"} {"input": "package megos\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestGetSystemFromPid(t *testing.T) {\n\tsetup()\n\tdefer teardown()\n\texpected := 0.13\n\n\tmux1.HandleFunc(\"/system/stats.json\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tc := getContentOfFile(\"tests/master1.system.stats.json\")\n\t\tfmt.Fprint(w, string(c))\n\t})\n\n\trole := \"master\"\n\thost := \"127.0.0.1\"\n\tport, _ := strconv.Atoi(strings.Split(server1.URL, \":\")[2])\n\tpid := fmt.Sprintf(\"%s@%s:%d\", role, host, port)\n\tparsedPid, _ := client.ParsePidInformation(pid)\n\n\tsystem, err := client.GetSystemFromPid(parsedPid)\n\tif system == nil {\n\t\tt.Error(\"System is nil. Expected not nil\")\n\t}\n\tif system.AvgLoad15min != expected {\n\t\tt.Errorf(\"Avg Load 15min is %v, Expected 0.13\", system.AvgLoad15min)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Error is not nil. Expected nil, got %s\", err)\n\t}\n}\n\n\n\nfunc TestGetSystemFromPidError(t *testing.T) ", "output": "{\n\tsetup()\n\tdefer teardown()\n\n\tmux1.HandleFunc(\"/system/stats.json\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tc := getContentOfFile(\"\")\n\t\tfmt.Fprint(w, string(c))\n\t})\n\n\trole := \"master\"\n\thost := \"127.0.0.1\"\n\tport, _ := strconv.Atoi(strings.Split(server1.URL, \":\")[2])\n\tpid := fmt.Sprintf(\"%s@%s:%d\", role, host, port)\n\tparsedPid, _ := client.ParsePidInformation(pid)\n\n\tsystem, err := client.GetSystemFromPid(parsedPid)\n\tif system != nil {\n\t\tt.Errorf(\"System is Not nil. Expected nil, got error %v.\", err)\n\t}\n\tif err == nil {\n\t\tt.Errorf(\"Error is nil. Expected Not nil.\")\n\t}\n}"} {"input": "package loggo\n\nvar (\n\tdefaultContext = newDefaultContxt()\n)\n\nfunc newDefaultContxt() *Context {\n\tctx := NewContext(WARNING)\n\tctx.AddWriter(DefaultWriterName, defaultWriter())\n\treturn ctx\n}\n\n\nfunc DefaultContext() *Context {\n\treturn defaultContext\n}\n\n\n\n\n\n\n\n\n\nfunc GetLogger(name string, size ...int) Logger {\n\treturn defaultContext.GetLogger(name, size...)\n}\n\n\n\n\n\nfunc ResetLogging() {\n\tdefaultContext.ResetLoggerLevels()\n\tdefaultContext.ResetWriters()\n}\n\n\nfunc ResetWriters() {\n\tdefaultContext.ResetWriters()\n}\n\n\n\n\nfunc ReplaceDefaultWriter(writer Writer) (Writer, error) {\n\treturn defaultContext.ReplaceWriter(DefaultWriterName, writer)\n}\n\n\n\n\nfunc RegisterWriter(name string, writer Writer) error {\n\treturn defaultContext.AddWriter(name, writer)\n}\n\n\n\nfunc RemoveWriter(name string) (Writer, error) {\n\treturn defaultContext.RemoveWriter(name)\n}\n\n\n\n\n\n\n\n\n\n\nfunc ConfigureLoggers(specification string) error {\n\tconfig, err := ParseConfigString(specification)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefaultContext.ApplyConfig(config)\n\treturn nil\n}\n\nfunc LoggerInfo() string ", "output": "{\n\treturn defaultContext.Config().String()\n}"} {"input": "package pump\n\nimport (\n\t\"math\"\n\n\t\"github.com/tidepool-org/platform/data\"\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tBolusAmountMaximumUnitsUnits = \"Units\"\n\tBolusAmountMaximumValueUnitsMaximum = 100.0\n\tBolusAmountMaximumValueUnitsMinimum = 0.0\n)\n\nfunc BolusAmountMaximumUnits() []string {\n\treturn []string{\n\t\tBolusAmountMaximumUnitsUnits,\n\t}\n}\n\ntype BolusAmountMaximum struct {\n\tUnits *string `json:\"units,omitempty\" bson:\"units,omitempty\"`\n\tValue *float64 `json:\"value,omitempty\" bson:\"value,omitempty\"`\n}\n\nfunc ParseBolusAmountMaximum(parser structure.ObjectParser) *BolusAmountMaximum {\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewBolusAmountMaximum()\n\tparser.Parse(datum)\n\treturn datum\n}\n\nfunc NewBolusAmountMaximum() *BolusAmountMaximum {\n\treturn &BolusAmountMaximum{}\n}\n\nfunc (b *BolusAmountMaximum) Parse(parser structure.ObjectParser) {\n\tb.Units = parser.String(\"units\")\n\tb.Value = parser.Float64(\"value\")\n}\n\n\n\nfunc (b *BolusAmountMaximum) Normalize(normalizer data.Normalizer) {}\n\nfunc BolusAmountMaximumValueRangeForUnits(units *string) (float64, float64) {\n\tif units != nil {\n\t\tswitch *units {\n\t\tcase BolusAmountMaximumUnitsUnits:\n\t\t\treturn BolusAmountMaximumValueUnitsMinimum, BolusAmountMaximumValueUnitsMaximum\n\t\t}\n\t}\n\treturn -math.MaxFloat64, math.MaxFloat64\n}\n\nfunc (b *BolusAmountMaximum) Validate(validator structure.Validator) ", "output": "{\n\tvalidator.String(\"units\", b.Units).Exists().OneOf(BolusAmountMaximumUnits()...)\n\tvalidator.Float64(\"value\", b.Value).Exists().InRange(BolusAmountMaximumValueRangeForUnits(b.Units))\n}"} {"input": "package models\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/russross/blackfriday\"\n)\n\nvar (\n\ttab = []byte(\"\\t\")\n\tspaces = []byte(\" \")\n)\n\ntype MarkdownRender struct {\n\tblackfriday.Renderer\n}\n\n\n\nfunc markdown(raw []byte) []byte {\n\thtmlFlags := 0 |\n\t\tblackfriday.HTML_USE_XHTML |\n\t\tblackfriday.HTML_USE_SMARTYPANTS |\n\t\tblackfriday.HTML_SMARTYPANTS_FRACTIONS |\n\t\tblackfriday.HTML_SMARTYPANTS_LATEX_DASHES\n\n\trenderer := &MarkdownRender{\n\t\tRenderer: blackfriday.HtmlRenderer(htmlFlags, \"\", \"\"),\n\t}\n\n\textensions := 0 |\n\t\tblackfriday.EXTENSION_NO_INTRA_EMPHASIS |\n\t\tblackfriday.EXTENSION_TABLES |\n\t\tblackfriday.EXTENSION_FENCED_CODE |\n\t\tblackfriday.EXTENSION_AUTOLINK |\n\t\tblackfriday.EXTENSION_STRIKETHROUGH |\n\t\tblackfriday.EXTENSION_SPACE_HEADERS |\n\t\tblackfriday.EXTENSION_HEADER_IDS\n\n\treturn blackfriday.Markdown(raw, renderer, extensions)\n}\n\nfunc (mr *MarkdownRender) BlockCode(out *bytes.Buffer, text []byte, lang string) ", "output": "{\n\tvar tmp bytes.Buffer\n\tmr.Renderer.BlockCode(&tmp, text, lang)\n\tout.Write(bytes.Replace(tmp.Bytes(), tab, spaces, -1))\n}"} {"input": "package classReader\n\nimport \"math\"\n\ntype ConstantIntegerInfo struct {\n\tval int32\n}\n\nfunc (self *ConstantIntegerInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint32()\n\tself.val = int32(bytes)\n}\n\nfunc (self *ConstantIntegerInfo) Value() int32 {\n\treturn self.val\n}\n\ntype ConstantFloatInfo struct {\n\tval float32\n}\n\nfunc (self *ConstantFloatInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint32()\n\tself.val = math.Float32frombits(bytes)\n}\n\nfunc (self *ConstantFloatInfo) Value() float32 {\n\treturn self.val\n}\n\ntype ConstantLongInfo struct {\n\tval int64\n}\n\nfunc (self *ConstantLongInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint64()\n\tself.val = int64(bytes)\n}\n\n\n\ntype ConstantDoubleInfo struct {\n\tval float64\n}\n\nfunc (self *ConstantDoubleInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint64()\n\tself.val = math.Float64frombits(bytes)\n}\n\nfunc (self *ConstantDoubleInfo) Value() float64 {\n\treturn self.val\n}\n\nfunc (self *ConstantLongInfo) Value() int64 ", "output": "{\n\treturn self.val\n}"} {"input": "package query\n\nfunc Escape(s string) string {\n\thexCount := 0\n\tfor i := 0; i < len(s); i++ {\n\t\tc := s[i]\n\t\tif shouldEscape(c) {\n\t\t\thexCount++\n\t\t}\n\t}\n\n\tif hexCount == 0 {\n\t\treturn s\n\t}\n\n\tt := make([]byte, len(s)+2*hexCount)\n\tj := 0\n\tfor i := 0; i < len(s); i++ {\n\t\tswitch c := s[i]; {\n\t\tcase shouldEscape(c):\n\t\t\tt[j] = '%'\n\t\t\tt[j+1] = \"0123456789ABCDEF\"[c>>4]\n\t\t\tt[j+2] = \"0123456789ABCDEF\"[c&15]\n\t\t\tj += 3\n\t\tdefault:\n\t\t\tt[j] = s[i]\n\t\t\tj++\n\t\t}\n\t}\n\treturn string(t)\n}\n\n\n\nfunc shouldEscape(c byte) bool ", "output": "{\n\tif 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' {\n\t\treturn false\n\t}\n\n\tswitch c {\n\tcase '-', '_', '.', '~': \n\t\treturn false\n\t}\n\n\treturn true\n}"} {"input": "package v1\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"k8s.io/client-go/pkg/apis/extensions/v1beta1\"\n)\n\nconst (\n\tIotDaemonSetKind = \"IotDaemonSet\"\n\tIotDaemonSetType = \"iotdaemonsets\"\n)\n\ntype IotDaemonSet struct {\n\tmetav1.TypeMeta `json:\",inline\"`\n\tMetadata metav1.ObjectMeta `json:\"metadata,omitempty\"`\n\tSpec v1beta1.DaemonSetSpec `json:\"spec,omitempty\"`\n\tStatus v1beta1.DaemonSetStatus `json:\"status,omitempty\"`\n}\n\ntype IotDaemonSetList struct {\n\tmetav1.TypeMeta `json:\",inline\"`\n\tMetadata metav1.ListMeta `json:\"metadata,omitempty\"`\n\tItems []IotDaemonSet `json:\"items\"`\n}\n\nfunc (iotDaemonSet *IotDaemonSet) GetObjectKind() schema.ObjectKind {\n\treturn &iotDaemonSet.TypeMeta\n}\n\nfunc (iotDaemonSet *IotDaemonSet) GetObjectMeta() *metav1.ObjectMeta {\n\treturn &iotDaemonSet.Metadata\n}\n\n\n\nfunc (iotDaemonSetList *IotDaemonSetList) GetListMeta() metav1.List {\n\treturn &iotDaemonSetList.Metadata\n}\n\nfunc (iotDaemonSetList *IotDaemonSetList) GetObjectKind() schema.ObjectKind ", "output": "{\n\treturn &iotDaemonSetList.TypeMeta\n}"} {"input": "package iso20022\n\n\ntype MatchingDenied1Choice struct {\n\n\tCode *MatchingProcess1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification20 `xml:\"Prtry\"`\n}\n\n\n\nfunc (m *MatchingDenied1Choice) AddProprietary() *GenericIdentification20 {\n\tm.Proprietary = new(GenericIdentification20)\n\treturn m.Proprietary\n}\n\nfunc (m *MatchingDenied1Choice) SetCode(value string) ", "output": "{\n\tm.Code = (*MatchingProcess1Code)(&value)\n}"} {"input": "package reuseport\n\nimport (\n\t\"syscall\"\n\n\t\"golang.org/x/sys/windows\"\n)\n\n\n\nfunc Control(network, address string, c syscall.RawConn) (err error) ", "output": "{\n\treturn c.Control(func(fd uintptr) {\n\t\terr = windows.SetsockoptInt(windows.Handle(fd), windows.SOL_SOCKET, windows.SO_REUSEADDR, 1)\n\t})\n}"} {"input": "package draw2d_test\n\nimport (\n\t\"image\"\n\t\"testing\"\n\n\t\"github.com/llgcode/draw2d\"\n)\n\ntype sample func(gc draw2d.GraphicContext, ext string) (string, error)\n\n\n\nfunc test(t *testing.T, draw sample) ", "output": "{\n\tdest := image.NewRGBA(image.Rect(0, 0, 297, 210.0))\n\tgc := draw2d.NewGraphicContext(dest)\n\toutput, err := draw(gc, \"png\")\n\tif err != nil {\n\t\tt.Errorf(\"Drawing %q failed: %v\", output, err)\n\t\treturn\n\t}\n\terr = draw2d.SaveToPngFile(output, dest)\n\tif err != nil {\n\t\tt.Errorf(\"Saving %q failed: %v\", output, err)\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\nimport \"io/ioutil\"\nimport \"io\"\n\nimport \"net/http\"\n\ntype Response struct {\n\tBody io.ReadCloser\n}\n\nfunc (resp Response) String() string {\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\n\treturn string(body)\n}\n\nfunc main() {\n\tfmt.Println(\"hello world\")\n\n\tsendHttpGet(\"http:www.cnet.com\")\n}\n\nfunc askMeMyName() string {\n\tvar givenName string\n\tfmt.Println(\"What is your name?\")\n\tfmt.Scanf(\"%s\", &givenName)\n\n\treturn givenName\n}\n\n\n\nfunc sendHttpGet(url string) ", "output": "{\n\tresponse, err := http.Get(url)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif response.StatusCode == 200 {\n\t\tbody := Response{response.Body}\n\n\t\tfmt.Printf(\"%s\", body)\n\t} else {\n\t\tfmt.Printf(\"The Status code is %s\", response.StatusCode)\n\t}\n}"} {"input": "package iso20022\n\n\ntype RejectionReason24Choice struct {\n\n\tCode *RejectionReason31Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification30 `xml:\"Prtry\"`\n}\n\nfunc (r *RejectionReason24Choice) SetCode(value string) {\n\tr.Code = (*RejectionReason31Code)(&value)\n}\n\n\n\nfunc (r *RejectionReason24Choice) AddProprietary() *GenericIdentification30 ", "output": "{\n\tr.Proprietary = new(GenericIdentification30)\n\treturn r.Proprietary\n}"} {"input": "package crypto\n\nimport (\n\t\"crypto\"\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/sha256\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\n\n\n\n\nfunc Verify(key *rsa.PublicKey, signature, message []byte) error {\n\thashed := sha256.Sum256(message)\n\terr := rsa.VerifyPKCS1v15(key, crypto.SHA256, hashed[:], signature)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to verify message: \")\n\t}\n\treturn nil\n}\n\n\nfunc EncryptRSA(key *rsa.PublicKey, plaintext []byte) ([]byte, error) {\n\tciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, key, plaintext)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to encrypt plaintext: \")\n\t}\n\treturn ciphertext, nil\n}\n\n\nfunc DecryptRSA(key *rsa.PrivateKey, ciphertext []byte) ([]byte, error) {\n\tsession, err := rsa.DecryptPKCS1v15(rand.Reader, key, ciphertext)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to decrypt ciphertext: \")\n\t}\n\treturn session, nil\n}\n\nfunc Sign(key *rsa.PrivateKey, message []byte) ([]byte, error) ", "output": "{\n\thashed := sha256.Sum256(message)\n\tsignature, err := rsa.SignPKCS1v15(\n\t\trand.Reader, key, crypto.SHA256, hashed[:],\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to sign message: \")\n\t}\n\treturn signature, nil\n}"} {"input": "package main\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/astaxie/beego\"\n\t\"github.com/astaxie/beego/orm\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n\t. \"weibo.com/opendcp/orion/models\"\n\t_ \"weibo.com/opendcp/orion/routers\"\n\t\"weibo.com/opendcp/orion/sched\"\n)\n\nfunc main() {\n\tbeego.Run()\n}\n\nfunc init() {\n\terr := beego.LoadAppConfig(\"ini\", \"conf/app.conf\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tinitOrm()\n\n\tif err := sched.Initial(); err != nil {\n\t\tpanic(err)\n\t}\n\tbeego.SetLogger(\"file\", `{\"filename\":\"logs/orion.log\"}`)\n}\n\n\n\nfunc initOrm() ", "output": "{\n\tdbUrl := beego.AppConfig.String(\"database_url\")\n\tdbpoolsizestr := beego.AppConfig.String(\"database_poolsize\")\n\tif dbUrl == \"\" {\n\t\tpanic(\"db_url not found in config...\")\n\t}\n\n\torm.Debug = true\n\n\torm.RegisterDriver(\"mysql\", orm.DRMySQL)\n\n\tdbpoolsize, _ := strconv.Atoi(dbpoolsizestr)\n\torm.RegisterDataBase(\"default\", \"mysql\", dbUrl, dbpoolsize)\n\n\torm.RegisterModel(&(Cluster{}), &(Service{}), &(Pool{}), &(Node{}), &(Logs{}))\n\torm.RegisterModel(&(FlowImpl{}), &(Flow{}), &(FlowBatch{}), &(NodeState{}))\n\torm.RegisterModel(&(RemoteStep{}), &(RemoteAction{}), &(RemoteActionImpl{}))\n\torm.RegisterModel(&(CronItem{}), &(DependItem{}), &(ExecTask{}))\n}"} {"input": "package google\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/acctest\"\n\t\"github.com/hashicorp/terraform/helper/resource\"\n)\n\n\n\nfunc testAccResourceUsageExportBucket(baseProject, org, billingId string) string {\n\treturn fmt.Sprintf(`\nresource \"google_project\" \"base\" {\n\tproject_id = \"%s\"\n\tname = \"Export Bucket Base\"\n\torg_id = \"%s\"\n\tbilling_account = \"%s\"\n}\n\nresource \"google_project_service\" \"service\" {\n\tproject = \"${google_project.base.project_id}\"\n\tservice = \"compute.googleapis.com\"\n}\n\nresource \"google_storage_bucket\" \"bucket\" {\n name = \"b-${google_project.base.project_id}\"\n\tproject = \"${google_project_service.service.project}\"\n}\n\nresource \"google_project_usage_export_bucket\" \"ueb\" {\n project = \"${google_project.base.project_id}\"\n bucket_name = \"${google_storage_bucket.bucket.name}\"\n\tprefix = \"foobar\"\n}\n`, baseProject, org, billingId)\n}\n\nfunc TestAccComputeResourceUsageExportBucket(t *testing.T) ", "output": "{\n\torg := getTestOrgFromEnv(t)\n\tbillingId := getTestBillingAccountFromEnv(t)\n\n\tbaseProject := \"ub-\" + acctest.RandString(10)\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccResourceUsageExportBucket(baseProject, org, billingId),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tResourceName: \"google_project_usage_export_bucket.ueb\",\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}"} {"input": "package blobstore\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync\"\n)\n\ntype localStore struct {\n\tsync.Mutex\n\troot string\n}\n\n\nfunc NewLocalStore(root string) (Store, error) {\n\treturn newLocalStore(root)\n}\n\nfunc (ls *localStore) blobDirname(digest string) string {\n\treturn filepath.Join(ls.root, \"blobs\", digest)\n}\n\n\n\nfunc (ls *localStore) blobInfoFilename(digest string) string {\n\treturn filepath.Join(ls.blobDirname(digest), \"info.json\")\n}\n\n\n\nfunc newLocalStore(root string) (*localStore, error) {\n\tls := &localStore{root: root}\n\n\tblobsDirname := ls.blobDirname(\"\")\n\tif err := os.MkdirAll(blobsDirname, os.FileMode(0755)); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create local blob store directory %q: %s\", blobsDirname, err)\n\t}\n\n\treturn ls, nil\n}\n\nfunc (ls *localStore) blobFilename(digest string) string ", "output": "{\n\treturn filepath.Join(ls.blobDirname(digest), \"blob\")\n}"} {"input": "package kafka\n\nimport (\n\t\"encoding/binary\"\n\t\"hash/crc32\"\n)\n\ntype crc32Writer struct {\n\ttable *crc32.Table\n\tbuffer [8]byte\n\tcrc32 uint32\n}\n\nfunc (w *crc32Writer) update(b []byte) {\n\tw.crc32 = crc32.Update(w.crc32, w.table, b)\n}\n\n\n\nfunc (w *crc32Writer) writeInt16(i int16) {\n\tbinary.BigEndian.PutUint16(w.buffer[:2], uint16(i))\n\tw.update(w.buffer[:2])\n}\n\nfunc (w *crc32Writer) writeInt32(i int32) {\n\tbinary.BigEndian.PutUint32(w.buffer[:4], uint32(i))\n\tw.update(w.buffer[:4])\n}\n\nfunc (w *crc32Writer) writeInt64(i int64) {\n\tbinary.BigEndian.PutUint64(w.buffer[:8], uint64(i))\n\tw.update(w.buffer[:8])\n}\n\nfunc (w *crc32Writer) writeBytes(b []byte) {\n\tn := len(b)\n\tif b == nil {\n\t\tn = -1\n\t}\n\tw.writeInt32(int32(n))\n\tw.update(b)\n}\n\nfunc (w *crc32Writer) Write(b []byte) (int, error) {\n\tw.update(b)\n\treturn len(b), nil\n}\n\nfunc (w *crc32Writer) WriteString(s string) (int, error) {\n\tw.update([]byte(s))\n\treturn len(s), nil\n}\n\nfunc (w *crc32Writer) writeInt8(i int8) ", "output": "{\n\tw.buffer[0] = byte(i)\n\tw.update(w.buffer[:1])\n}"} {"input": "package chipmunk\n\nimport \"github.com/dataarts/chipmunk/vect\"\n\nconst (\n\terrorBias = 0.00179701029991443 \n)\n\ntype ConstraintCallback interface {\n\tCollisionPreSolve(constraint Constraint)\n\tCollisionPostSolve(constraint Constraint)\n}\n\ntype Constraint interface {\n\tConstraint() *BasicConstraint\n\tPreSolve()\n\tPostSolve()\n\tPreStep(dt vect.Float)\n\tApplyCachedImpulse(dt_coef vect.Float)\n\tApplyImpulse()\n\tImpulse() vect.Float\n}\n\ntype BasicConstraint struct {\n\tBodyA, BodyB *Body\n\tspace *Space\n\tMaxForce vect.Float\n\tErrorBias vect.Float\n\tMaxBias vect.Float\n\tCallbackHandler ConstraintCallback\n\tUserData Data\n}\n\nfunc NewConstraint(a, b *Body) BasicConstraint {\n\treturn BasicConstraint{BodyA: a, BodyB: b, MaxForce: Inf, MaxBias: Inf, ErrorBias: errorBias}\n}\n\nfunc (this *BasicConstraint) Constraint() *BasicConstraint {\n\treturn this\n}\n\n\n\nfunc (this *BasicConstraint) ApplyCachedImpulse(dt_coef vect.Float) {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) ApplyImpulse() {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) Impulse() vect.Float {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) PreSolve() {\n\tif this.CallbackHandler != nil {\n\t\tthis.CallbackHandler.CollisionPreSolve(this)\n\t}\n}\n\nfunc (this *BasicConstraint) PostSolve() {\n\tif this.CallbackHandler != nil {\n\t\tthis.CallbackHandler.CollisionPostSolve(this)\n\t}\n}\n\nfunc (this *BasicConstraint) PreStep(dt vect.Float) ", "output": "{\n\tpanic(\"empty constraint\")\n}"} {"input": "package util\n\nimport (\n\t\"compress/bzip2\"\n\t\"io\"\n\t\"os\"\n)\n\n\n\n\nfunc Bunzip2(dst io.Writer, src io.Reader) (written int64, err error) {\n\tbzr := bzip2.NewReader(src)\n\treturn io.Copy(dst, bzr)\n}\n\n\n\n\nfunc Bunzip2File(dst, src string) error ", "output": "{\n\tin, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer in.Close()\n\n\tout, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = Bunzip2(out, in)\n\tif err != nil {\n\t\tos.Remove(dst)\n\t}\n\treturn err\n}"} {"input": "package blockchain\n\n\n\n\n\n\n\n\ntype MemberProvisioningState string\n\nconst (\n\tDeleting MemberProvisioningState = \"Deleting\"\n\tFailed MemberProvisioningState = \"Failed\"\n\tNotSpecified MemberProvisioningState = \"NotSpecified\"\n\tStale MemberProvisioningState = \"Stale\"\n\tSucceeded MemberProvisioningState = \"Succeeded\"\n\tUpdating MemberProvisioningState = \"Updating\"\n)\n\n\nfunc PossibleMemberProvisioningStateValues() []MemberProvisioningState {\n\treturn []MemberProvisioningState{Deleting, Failed, NotSpecified, Stale, Succeeded, Updating}\n}\n\n\ntype NameAvailabilityReason string\n\nconst (\n\tNameAvailabilityReasonAlreadyExists NameAvailabilityReason = \"AlreadyExists\"\n\tNameAvailabilityReasonInvalid NameAvailabilityReason = \"Invalid\"\n\tNameAvailabilityReasonNotSpecified NameAvailabilityReason = \"NotSpecified\"\n)\n\n\nfunc PossibleNameAvailabilityReasonValues() []NameAvailabilityReason {\n\treturn []NameAvailabilityReason{NameAvailabilityReasonAlreadyExists, NameAvailabilityReasonInvalid, NameAvailabilityReasonNotSpecified}\n}\n\n\ntype NodeProvisioningState string\n\nconst (\n\tNodeProvisioningStateDeleting NodeProvisioningState = \"Deleting\"\n\tNodeProvisioningStateFailed NodeProvisioningState = \"Failed\"\n\tNodeProvisioningStateNotSpecified NodeProvisioningState = \"NotSpecified\"\n\tNodeProvisioningStateSucceeded NodeProvisioningState = \"Succeeded\"\n\tNodeProvisioningStateUpdating NodeProvisioningState = \"Updating\"\n)\n\n\nfunc PossibleNodeProvisioningStateValues() []NodeProvisioningState {\n\treturn []NodeProvisioningState{NodeProvisioningStateDeleting, NodeProvisioningStateFailed, NodeProvisioningStateNotSpecified, NodeProvisioningStateSucceeded, NodeProvisioningStateUpdating}\n}\n\n\ntype Protocol string\n\nconst (\n\tProtocolCorda Protocol = \"Corda\"\n\tProtocolNotSpecified Protocol = \"NotSpecified\"\n\tProtocolParity Protocol = \"Parity\"\n\tProtocolQuorum Protocol = \"Quorum\"\n)\n\n\n\n\nfunc PossibleProtocolValues() []Protocol ", "output": "{\n\treturn []Protocol{ProtocolCorda, ProtocolNotSpecified, ProtocolParity, ProtocolQuorum}\n}"} {"input": "package cover\n\nimport (\n\t\"flag\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc ParseAndStripTestFlags() {\n\tflag.Parse()\n\n\tvar runtimeArgs []string\n\tfor _, arg := range os.Args {\n\t\tif strings.HasPrefix(arg, \"-test.\") ||\n\t\t\tstrings.HasPrefix(arg, \"-httptest.\") {\n\t\t\tcontinue\n\t\t}\n\t\truntimeArgs = append(runtimeArgs, arg)\n\t}\n\tos.Args = runtimeArgs\n}\n\ntype dummyTestDeps func(pat, str string) (bool, error)\n\nfunc (d dummyTestDeps) MatchString(pat, str string) (bool, error) { return false, nil }\nfunc (d dummyTestDeps) StartCPUProfile(io.Writer) error { return nil }\nfunc (d dummyTestDeps) StopCPUProfile() {}\nfunc (f dummyTestDeps) StartTestLog(w io.Writer) {}\nfunc (f dummyTestDeps) StopTestLog() error { return nil }\nfunc (d dummyTestDeps) WriteHeapProfile(io.Writer) error { return nil }\n\nfunc (f dummyTestDeps) ImportPath() string { return \"\" }\n\n\n\n\n\nfunc FlushProfiles() {\n\toldstdout := os.Stdout\n\toldstderr := os.Stderr\n\tos.Stdout, _ = os.Open(os.DevNull)\n\tos.Stderr, _ = os.Open(os.DevNull)\n\n\ttests := []testing.InternalTest{}\n\tbenchmarks := []testing.InternalBenchmark{}\n\texamples := []testing.InternalExample{}\n\tvar f dummyTestDeps\n\tdummyM := testing.MainStart(f, tests, benchmarks, examples)\n\tdummyM.Run()\n\n\tos.Stdout = oldstdout\n\tos.Stderr = oldstderr\n}\n\nfunc (d dummyTestDeps) WriteProfileTo(string, io.Writer, int) error ", "output": "{ return nil }"} {"input": "package armcosmos_test\n\nimport (\n\t\"context\"\n\t\"log\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azcore/to\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cosmos/armcosmos\"\n)\n\n\nfunc ExampleCollectionPartitionClient_ListMetrics() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armcosmos.NewCollectionPartitionClient(\"\", cred, nil)\n\tres, err := client.ListMetrics(ctx,\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Response result: %#v\\n\", res.CollectionPartitionClientListMetricsResult)\n}\n\n\n\n\nfunc ExampleCollectionPartitionClient_ListUsages() ", "output": "{\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armcosmos.NewCollectionPartitionClient(\"\", cred, nil)\n\tres, err := client.ListUsages(ctx,\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t&armcosmos.CollectionPartitionClientListUsagesOptions{Filter: to.StringPtr(\"\")})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Response result: %#v\\n\", res.CollectionPartitionClientListUsagesResult)\n}"} {"input": "package identify\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\n\n\n\n\nfunc NewPostNodesIdentifierObmIdentifyParamsWithTimeout(timeout time.Duration) *PostNodesIdentifierObmIdentifyParams {\n\tvar ()\n\treturn &PostNodesIdentifierObmIdentifyParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype PostNodesIdentifierObmIdentifyParams struct {\n\n\tBody *bool\n\tIdentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *PostNodesIdentifierObmIdentifyParams) WithBody(body *bool) *PostNodesIdentifierObmIdentifyParams {\n\to.Body = body\n\treturn o\n}\n\n\nfunc (o *PostNodesIdentifierObmIdentifyParams) WithIdentifier(identifier string) *PostNodesIdentifierObmIdentifyParams {\n\to.Identifier = identifier\n\treturn o\n}\n\n\nfunc (o *PostNodesIdentifierObmIdentifyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetBodyParam(o.Body); err != nil {\n\t\treturn err\n\t}\n\n\tif err := r.SetPathParam(\"identifier\", o.Identifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewPostNodesIdentifierObmIdentifyParams() *PostNodesIdentifierObmIdentifyParams ", "output": "{\n\tvar ()\n\treturn &PostNodesIdentifierObmIdentifyParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}"} {"input": "package postgresql\n\nimport (\n\t\"sql\"\n)\n\ntype Connection struct {\n\thandle *pqConnection;\n}\n\nfunc (self *Connection) Query(sql string, params ...interface{}) (sql.ResultSet, sql.Error) {\n\tstmt, err := self.Prepare(sql)\n\tif err != nil {\n\t\treturn nil, err\t\n\t}\n\n\treturn stmt.Query(params...)\n}\n\nfunc (self *Connection) Execute(sql string, params ...interface{}) sql.Error {\n\tstmt, err := self.Prepare(sql)\n\tif err != nil {\n\t\treturn err\t\n\t}\n\n\tdefer stmt.Close()\n\treturn stmt.Execute(params...)\n}\n\n\n\nfunc (self *Connection) Close() sql.Error {\n\tself.handle.pqClose()\n\treturn nil\n}\n\nfunc (self *Connection) Prepare(query string) (sql.Statement, sql.Error) ", "output": "{\n\n\tstmt := new(Statement)\n\treturn stmt, nil\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/api/certificates/v1beta1\"\n\t\"k8s.io/client-go/kubernetes/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype CertificatesV1beta1Interface interface {\n\tRESTClient() rest.Interface\n\tCertificateSigningRequestsGetter\n}\n\n\ntype CertificatesV1beta1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *CertificatesV1beta1Client) CertificateSigningRequests() CertificateSigningRequestInterface {\n\treturn newCertificateSigningRequests(c)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*CertificatesV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &CertificatesV1beta1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *CertificatesV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *CertificatesV1beta1Client {\n\treturn &CertificatesV1beta1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc (c *CertificatesV1beta1Client) RESTClient() rest.Interface ", "output": "{\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}"} {"input": "package gwf\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n)\n\n\ntype Context struct {\n\tw http.ResponseWriter\n\tr *http.Request\n\n\tpath []string\n}\n\ntype Module interface {\n\tAction(*Context)\n}\n\ntype Dispatcher struct {\n\tmodules map[string]Module\n}\n\nfunc (c *Context) Request() *http.Request {\n\treturn c.r\n}\n\nfunc (c *Context) Writer() http.ResponseWriter {\n\treturn c.w\n}\n\nfunc (c *Context) Init(w http.ResponseWriter, r *http.Request) {\n\tc.w, c.r = w, r\n\n\tpath := strings.Split(r.URL.Path, \"/\")\n\tc.path = path[1:]\n}\n\nfunc (c *Context) Path(index int) (string, bool) {\n\tif index < 0 || index >= len(c.path) {\n\t\treturn \"\", false\n\t} else {\n\t\treturn c.path[index], true\n\t}\n}\n\nfunc (c *Context) Depth() int {\n\treturn len(c.path)\n}\n\n\n\n\nfunc (d *Dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\n\tvar c Context\n\tc.Init(w, r)\n\n\tif name, ok := c.Path(0); ok {\n\t\tif module, ok := d.modules[name]; ok && module != nil {\n\t\t\t(module).Action(&c)\n\t\t\treturn\n\t\t}\n\t}\n\tw.WriteHeader(http.StatusNotFound)\n}\n\nfunc (d *Dispatcher) AddModule(name string, m Module) ", "output": "{\n\tif nil == d.modules {\n\t\td.modules = make(map[string]Module)\n\t}\n\td.modules[name] = m\n}"} {"input": "package sarama\n\n\ntype ApiVersionsRequest struct{}\n\nfunc (a *ApiVersionsRequest) encode(pe packetEncoder) error {\n\treturn nil\n}\n\nfunc (a *ApiVersionsRequest) decode(pd packetDecoder, version int16) (err error) {\n\treturn nil\n}\n\n\n\nfunc (a *ApiVersionsRequest) version() int16 {\n\treturn 0\n}\n\nfunc (a *ApiVersionsRequest) headerVersion() int16 {\n\treturn 1\n}\n\nfunc (a *ApiVersionsRequest) requiredVersion() KafkaVersion {\n\treturn V0_10_0_0\n}\n\nfunc (a *ApiVersionsRequest) key() int16 ", "output": "{\n\treturn 18\n}"} {"input": "package nsqd\n\nimport (\n\t\"bytes\"\n\t\"sync\"\n)\n\nvar bp sync.Pool\n\n\n\nfunc bufferPoolGet() *bytes.Buffer {\n\treturn bp.Get().(*bytes.Buffer)\n}\n\nfunc bufferPoolPut(b *bytes.Buffer) {\n\tb.Reset()\n\tbp.Put(b)\n}\n\nfunc init() ", "output": "{\n\tbp.New = func() interface{} {\n\t\treturn &bytes.Buffer{}\n\t}\n}"} {"input": "package graph\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gonum/graph\"\n\n\tkapi \"github.com/GoogleCloudPlatform/kubernetes/pkg/api\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime\"\n)\n\nvar (\n\tUnknownNodeKind = \"UnknownNode\"\n)\n\nvar (\n\tUnknownEdgeKind = \"UnknownEdge\"\n\tReferencedByEdgeKind = \"ReferencedBy\"\n\tContainsEdgeKind = \"Contains\"\n)\n\nfunc GetUniqueRuntimeObjectNodeName(nodeKind string, obj runtime.Object) UniqueName {\n\tmeta, err := kapi.ObjectMetaFor(obj)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn UniqueName(fmt.Sprintf(\"%s|%s/%s\", nodeKind, meta.Namespace, meta.Name))\n}\n\n\n\nfunc GetTopLevelContainerNode(g Graph, containedNode graph.Node) graph.Node {\n\tvisited := map[int]bool{}\n\tprevContainingNode := containedNode\n\n\tfor {\n\t\tvisited[prevContainingNode.ID()] = true\n\t\tcurrContainingNode := GetContainingNode(g, prevContainingNode)\n\n\t\tif currContainingNode == nil {\n\t\t\treturn prevContainingNode\n\t\t}\n\t\tif _, alreadyVisited := visited[currContainingNode.ID()]; alreadyVisited {\n\t\t\tpanic(fmt.Sprintf(\"contains cycle in %v\", visited))\n\t\t}\n\n\t\tprevContainingNode = currContainingNode\n\t}\n\n\tpanic(fmt.Sprintf(\"math failed %v\", visited))\n\treturn nil\n}\n\n\n\n\n\nfunc GetContainingNode(g Graph, containedNode graph.Node) graph.Node ", "output": "{\n\tfor _, node := range g.To(containedNode) {\n\t\tedge := g.Edge(node, containedNode)\n\n\t\tif g.EdgeKinds(edge).Has(ContainsEdgeKind) {\n\t\t\treturn node\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package prefilter\n\n\n\n\nimport (\n\t\"net/http\"\n\n\tmiddleware \"github.com/go-openapi/runtime/middleware\"\n)\n\n\ntype PutPrefilterHandlerFunc func(PutPrefilterParams) middleware.Responder\n\n\nfunc (fn PutPrefilterHandlerFunc) Handle(params PutPrefilterParams) middleware.Responder {\n\treturn fn(params)\n}\n\n\ntype PutPrefilterHandler interface {\n\tHandle(PutPrefilterParams) middleware.Responder\n}\n\n\nfunc NewPutPrefilter(ctx *middleware.Context, handler PutPrefilterHandler) *PutPrefilter {\n\treturn &PutPrefilter{Context: ctx, Handler: handler}\n}\n\n\ntype PutPrefilter struct {\n\tContext *middleware.Context\n\tHandler PutPrefilterHandler\n}\n\n\n\nfunc (o *PutPrefilter) ServeHTTP(rw http.ResponseWriter, r *http.Request) ", "output": "{\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\tr = rCtx\n\t}\n\tvar Params = NewPutPrefilterParams()\n\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params) \n\n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}"} {"input": "package pool\n\nimport (\n\t\"fmt\"\n\t\"net\"\n)\n\nconst (\n\t_net = \"udp4\" \n)\n\n\n\nfunc worker(id int, address string, done chan bool, buffers <-chan []byte) {\n\n\tconn, err := createUDPConnection(address)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\terr := conn.Close()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}()\n\n\tfor buffer := range buffers {\n\t\t_, err := conn.Write(buffer)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tdone <- true\n}\n\ntype UDPPool struct {\n\tbuffers chan []byte\n\tdone chan bool\n}\n\n\nfunc NewUDPPool(address string, workerNumber int) *UDPPool {\n\tbuffers := make(chan []byte, workerNumber)\n\tdone := make(chan bool)\n\n\tfor wid := 1; wid < workerNumber; wid++ {\n\t\tgo worker(wid, address, done, buffers)\n\t}\n\treturn &UDPPool{buffers, done}\n}\n\nfunc (p *UDPPool) Fire(buffer []byte) {\n\tp.buffers <- buffer\n}\n\nfunc (p *UDPPool) Close() {\n\tclose(p.buffers)\n}\n\nfunc createUDPConnection(address string) (*net.UDPConn, error) ", "output": "{\n\taddr, err := net.ResolveUDPAddr(_net, address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconn, err := net.DialUDP(_net, nil, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn conn, nil\n}"} {"input": "package envsuite\n\n\n\n\n\nimport (\n\t. \"launchpad.net/gocheck\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype EnvSuite struct {\n\tenviron []string\n}\n\n\n\nfunc (s *EnvSuite) SetUpTest(c *C) {\n\tos.Clearenv()\n}\n\nfunc (s *EnvSuite) TearDownTest(c *C) {\n\tfor _, envstring := range s.environ {\n\t\tkv := strings.SplitN(envstring, \"=\", 2)\n\t\tos.Setenv(kv[0], kv[1])\n\t}\n}\n\nfunc (s *EnvSuite) TearDownSuite(c *C) {\n}\n\nfunc (s *EnvSuite) SetUpSuite(c *C) ", "output": "{\n\ts.environ = os.Environ()\n}"} {"input": "package terminal\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n)\n\ntype TeePrinter struct {\n\tdisableTerminalOutput bool\n\toutputBucket io.Writer\n}\n\nfunc NewTeePrinter() *TeePrinter {\n\treturn &TeePrinter{\n\t\toutputBucket: ioutil.Discard,\n\t}\n}\n\nfunc (t *TeePrinter) SetOutputBucket(bucket io.Writer) {\n\tif bucket == nil {\n\t\tbucket = ioutil.Discard\n\t}\n\n\tt.outputBucket = bucket\n}\n\nfunc (t *TeePrinter) Print(values ...interface{}) (n int, err error) {\n\tstr := fmt.Sprint(values...)\n\tt.saveOutputToBucket(str)\n\tif !t.disableTerminalOutput {\n\t\treturn fmt.Print(str)\n\t}\n\treturn\n}\n\nfunc (t *TeePrinter) Printf(format string, a ...interface{}) (n int, err error) {\n\tstr := fmt.Sprintf(format, a...)\n\tt.saveOutputToBucket(str)\n\tif !t.disableTerminalOutput {\n\t\treturn fmt.Print(str)\n\t}\n\treturn\n}\n\nfunc (t *TeePrinter) Println(values ...interface{}) (n int, err error) {\n\tstr := fmt.Sprint(values...)\n\tt.saveOutputToBucket(str)\n\tif !t.disableTerminalOutput {\n\t\treturn fmt.Println(str)\n\t}\n\treturn\n}\n\nfunc (t *TeePrinter) DisableTerminalOutput(disable bool) {\n\tt.disableTerminalOutput = disable\n}\n\n\n\nfunc (t *TeePrinter) saveOutputToBucket(output string) ", "output": "{\n\tt.outputBucket.Write([]byte(Decolorize(output)))\n}"} {"input": "package v1beta1\n\nimport (\n\tapi \"k8s.io/kubernetes/pkg/api\"\n\tregistered \"k8s.io/kubernetes/pkg/apimachinery/registered\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n\tserializer \"k8s.io/kubernetes/pkg/runtime/serializer\"\n)\n\ntype AuthorizationInterface interface {\n\tGetRESTClient() *restclient.RESTClient\n\tSelfSubjectAccessReviewsGetter\n\tSubjectAccessReviewsGetter\n}\n\n\ntype AuthorizationClient struct {\n\t*restclient.RESTClient\n}\n\nfunc (c *AuthorizationClient) SelfSubjectAccessReviews() SelfSubjectAccessReviewInterface {\n\treturn newSelfSubjectAccessReviews(c)\n}\n\nfunc (c *AuthorizationClient) SubjectAccessReviews() SubjectAccessReviewInterface {\n\treturn newSubjectAccessReviews(c)\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *restclient.Config) *AuthorizationClient {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c *restclient.RESTClient) *AuthorizationClient {\n\treturn &AuthorizationClient{c}\n}\n\nfunc setConfigDefaults(config *restclient.Config) error {\n\tg, err := registered.Group(\"authorization.k8s.io\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.APIPath = \"/apis\"\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = restclient.DefaultKubernetesUserAgent()\n\t}\n\tcopyGroupVersion := g.GroupVersion\n\tconfig.GroupVersion = ©GroupVersion\n\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: api.Codecs}\n\n\treturn nil\n}\n\n\n\nfunc (c *AuthorizationClient) GetRESTClient() *restclient.RESTClient {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.RESTClient\n}\n\nfunc NewForConfig(c *restclient.Config) (*AuthorizationClient, error) ", "output": "{\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := restclient.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AuthorizationClient{client}, nil\n}"} {"input": "package claim\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\nfunc TestPermission_MatchVerb(t *testing.T) {\n\tp := Permission{Verb: []string{\"read\", \"update\", \"create\"}}\n\tassert.True(t, p.MatchVerb(\"read\"))\n\tassert.True(t, p.MatchVerb(\"update\"))\n\tassert.True(t, p.MatchVerb(\"create\"))\n\tassert.False(t, p.MatchVerb(\"invalid\"))\n\tassert.False(t, p.MatchVerb(\"delete\"))\n}\n\n\nfunc TestPermission_MatchWildcard(t *testing.T) {\n\tp := Permission{ResourceURN: \"userapi:device:*\"}\n\tassert.True(t, p.Match(\"userapi:device:device_id\"))\n\tassert.True(t, p.Match(\"userapi:device:bla\"))\n\tassert.False(t, p.Match(\"userapi:home:bla\"))\n}\n\nfunc TestPermissionSet_Match(t *testing.T) {\n\tp := PermissionSet{\n\t\tRules: []Permission{\n\t\t\t{ResourceURN: \"userapi:device:*\", Verb: []string{\"read\", \"update\", \"create\"}},\n\t\t\t{ResourceURN: \"userapi:device:\", Verb: []string{\"create\"}},\n\t\t},\n\t}\n\tassert.True(t, p.Match(\"read\", \"userapi:device:device_id\"))\n\tassert.False(t, p.Match(\"delete\", \"userapi:device:device_id\"))\n\tassert.True(t, p.Match(\"create\", \"userapi:device:\"))\n\n}\n\nfunc TestPermission_Match(t *testing.T) ", "output": "{\n\tp := Permission{ResourceURN: \"userapi:device:device_id\"}\n\tassert.True(t, p.Match(\"userapi:device:device_id\"))\n\tassert.False(t, p.Match(\"userapi:device:bla\"))\n\tassert.False(t, p.Match(\"userapi:home:bla\"))\n}"} {"input": "package api\n\ntype FormatsResponse struct {\n\tFormats []string `json:\"formats\"`\n}\n\nfunc (a *API) getFormats(ctx *context) {\n\tctx.Success(FormatsResponse{Formats: a.c.formats.Keys()})\n}\n\ntype LeechTypesResponse struct {\n\tLeechTypes []string `json:\"leech_types\"`\n}\n\nfunc (a *API) getLeechTypes(ctx *context) {\n\tctx.Success(LeechTypesResponse{LeechTypes: a.c.leechTypes.Keys()})\n}\n\ntype MediaResponse struct {\n\tMedia []string `json:\"media\"`\n}\n\nfunc (a *API) getMedia(ctx *context) {\n\tctx.Success(MediaResponse{Media: a.c.media.Keys()})\n}\n\ntype ReleaseGroupTypesResponse struct {\n\tReleaseGroupTypes []string `json:\"release_group_types\"`\n}\n\nfunc (a *API) getReleaseGroupTypes(ctx *context) {\n\tctx.Success(ReleaseGroupTypesResponse{ReleaseGroupTypes: a.c.releaseGroupTypes.Keys()})\n}\n\ntype ReleasePropertiesResponse struct {\n\tReleaseProperties []string `json:\"release_properties\"`\n}\n\n\n\ntype ReleaseRolesResponse struct {\n\tReleaseRoles []string `json:\"release_roles\"`\n}\n\nfunc (a *API) getReleaseRoles(ctx *context) {\n\tctx.Success(ReleaseRolesResponse{ReleaseRoles: a.c.releaseRoles.Keys()})\n}\n\ntype PrivilegesResponse struct {\n\tPrivileges []string `json:\"privileges\"`\n}\n\nfunc (a *API) getPrivileges(ctx *context) {\n\tctx.Success(PrivilegesResponse{Privileges: a.c.privileges.Keys()})\n}\n\nfunc (a *API) getReleaseProperties(ctx *context) ", "output": "{\n\tctx.Success(ReleasePropertiesResponse{ReleaseProperties: a.c.releaseProperties.Keys()})\n}"} {"input": "package foursquare\n\ntype user struct {\n\tId string\n\tFirstName string\n\tLastName string\n}\n\ntype userInfo struct {\n\tResponse struct {\n\t\tUser user\n\t}\n}\n\ntype checkinsList struct {\n\tResponse struct {\n\t\tCheckins struct {\n\t\t\tItems []*checkinItem\n\t\t}\n\t}\n}\n\ntype checkinItem struct {\n\tId string\n\tCreatedAt int64 \n\tTimeZoneOffset int \n\tShout string \n\tVenue venueItem\n}\n\ntype venueItem struct {\n\tId string \n\tName string\n\tLocation *venueLocationItem\n\tCategories []*venueCategory\n}\n\ntype photosList struct {\n\tResponse struct {\n\t\tPhotos struct {\n\t\t\tItems []*photoItem\n\t\t}\n\t}\n}\n\ntype photoItem struct {\n\tId string\n\tPrefix string\n\tSuffix string\n\tWidth int\n\tHeight int\n}\n\n\n\nfunc (vi *venueItem) icon() string {\n\tc := vi.primaryCategory()\n\tif c == nil || c.Icon == nil || c.Icon.Prefix == \"\" {\n\t\treturn \"\"\n\t}\n\treturn c.Icon.Prefix + \"bg_88\" + c.Icon.Suffix\n}\n\ntype venueLocationItem struct {\n\tAddress string\n\tCity string\n\tPostalCode string\n\tState string\n\tCountry string \n\tLat float64\n\tLng float64\n}\n\ntype venueCategory struct {\n\tPrimary bool\n\tName string\n\tIcon *categoryIcon\n}\n\ntype categoryIcon struct {\n\tPrefix string\n\tSuffix string\n}\n\nfunc (vi *venueItem) primaryCategory() *venueCategory ", "output": "{\n\tfor _, c := range vi.Categories {\n\t\tif c.Primary {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package datatype\n\nimport \"fmt\"\n\n\ntype OctetString string\n\n\nfunc DecodeOctetString(b []byte) (Type, error) {\n\treturn OctetString(b), nil\n}\n\n\n\n\n\nfunc (s OctetString) Len() int {\n\treturn len(s)\n}\n\n\nfunc (s OctetString) Padding() int {\n\tl := len(s)\n\treturn pad4(l) - l\n}\n\n\nfunc (s OctetString) Type() TypeID {\n\treturn OctetStringType\n}\n\n\nfunc (s OctetString) String() string {\n\treturn fmt.Sprintf(\"OctetString{%#x},Padding:%d\", string(s), s.Padding())\n}\n\nfunc (s OctetString) Serialize() []byte ", "output": "{\n\treturn []byte(s)\n}"} {"input": "package image\n\nfunc getOSVersion() string {\n\treturn \"\"\n}\n\n\n\nfunc hasOSFeature(_ string) bool ", "output": "{\n\treturn false\n}"} {"input": "package label\n\n\n\n\nfunc InitLabels(mcsdir string, options []string) (string, string, error) {\n\treturn \"\", \"\", nil\n}\n\nfunc FormatMountLabel(src string, mountLabel string) string {\n\treturn src\n}\n\nfunc SetProcessLabel(processLabel string) error {\n\treturn nil\n}\n\nfunc SetFileLabel(path string, fileLabel string) error {\n\treturn nil\n}\n\nfunc SetFileCreateLabel(fileLabel string) error {\n\treturn nil\n}\n\nfunc Relabel(path string, fileLabel string, relabel string) error {\n\treturn nil\n}\n\nfunc GetPidLabel(pid int) (string, error) {\n\treturn \"\", nil\n}\n\nfunc Init() {\n}\n\nfunc ReserveLabel(label string) error {\n\treturn nil\n}\n\n\n\n\n\nfunc DupSecOpt(src string) []string {\n\treturn nil\n}\n\n\n\nfunc DisableSecOpt() []string {\n\treturn nil\n}\n\nfunc UnreserveLabel(label string) error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"testing\"\n)\n\n\n\n\nfunc equals(t testing.TB, got, want interface{}) {\n\tif want == nil && (got == nil || reflect.ValueOf(got).IsNil()) {\n\t\treturn\n\t}\n\tif !reflect.DeepEqual(got, want) {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\t%s:%d: got: %#v; want: %#v\\n\", filepath.Base(file), line, got, want)\n\t\tt.FailNow()\n\t}\n}\n\n\n\n\n\nfunc approx(t testing.TB, got, want float64) ", "output": "{\n\tf1 := got\n\tf2 := want\n\tif f1 == f2 {\n\t\treturn\n\t} else if f1 > f2 {\n\t\tf1, f2 = f2, f1\n\t}\n\tdelta := (f2 - f1) / f1\n\tif delta > 0.0001 { \n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\t%s:%d: got %v; want %v\\n\", filepath.Base(file), line, got, want)\n\t\tt.FailNow()\n\t}\n}"} {"input": "package msgpackzip\n\nimport (\n\t\"bytes\"\n\t\"compress/flate\"\n\t\"io/ioutil\"\n)\n\n\n\nfunc flateInflate(b []byte) ([]byte, error) {\n\tbuf := bytes.NewBuffer(b)\n\tzr := flate.NewReader(buf)\n\treturn ioutil.ReadAll(zr)\n}\n\nfunc flateCompress(b []byte) ([]byte, error) ", "output": "{\n\tvar buf bytes.Buffer\n\tzw, err := flate.NewWriter(&buf, flate.DefaultCompression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = zw.Write(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = zw.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/xeb/etcdrepl/third_party/github.com/codegangsta/cli\"\n\t\"github.com/xeb/etcdrepl/third_party/github.com/coreos/go-etcd/etcd\"\n)\n\n\n\n\nfunc handleLs(c *cli.Context, fn handlerFunc) {\n\thandlePrint(c, fn, printLs)\n}\n\n\n\nfunc printLs(resp *etcd.Response, format string) {\n\tif !resp.Node.Dir {\n\t\tfmt.Println(resp.Node.Key)\n\t}\n\tfor _, node := range resp.Node.Nodes {\n\t\trPrint(&node)\n\t}\n}\n\n\nfunc lsCommandFunc(c *cli.Context, client *etcd.Client) (*etcd.Response, error) {\n\tkey := \"/\"\n\tif len(c.Args()) != 0 {\n\t\tkey = c.Args()[0]\n\t}\n\trecursive := c.Bool(\"recursive\")\n\n\treturn client.Get(key, false, recursive)\n}\n\n\nfunc rPrint(n *etcd.Node) {\n\tfmt.Println(n.Key)\n\tfor _, node := range n.Nodes {\n\t\trPrint(&node)\n\t}\n}\n\nfunc NewLsCommand() cli.Command ", "output": "{\n\treturn cli.Command{\n\t\tName:\t\"ls\",\n\t\tUsage:\t\"retrieve a directory\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.BoolFlag{\"recursive\", \"returns all values for key and child keys\"},\n\t\t},\n\t\tAction: func(c *cli.Context) {\n\t\t\thandleLs(c, lsCommandFunc)\n\t\t},\n\t}\n}"} {"input": "package stdlib\n\nimport (\n\t\"container/heap\"\n\t\"reflect\"\n)\n\nfunc init() {\n\tSymbols[\"container/heap\"] = map[string]reflect.Value{\n\t\t\"Fix\": reflect.ValueOf(heap.Fix),\n\t\t\"Init\": reflect.ValueOf(heap.Init),\n\t\t\"Pop\": reflect.ValueOf(heap.Pop),\n\t\t\"Push\": reflect.ValueOf(heap.Push),\n\t\t\"Remove\": reflect.ValueOf(heap.Remove),\n\n\t\t\"Interface\": reflect.ValueOf((*heap.Interface)(nil)),\n\n\t\t\"_Interface\": reflect.ValueOf((*_container_heap_Interface)(nil)),\n\t}\n}\n\n\ntype _container_heap_Interface struct {\n\tWLen func() int\n\tWLess func(i int, j int) bool\n\tWPop func() interface{}\n\tWPush func(x interface{})\n\tWSwap func(i int, j int)\n}\n\nfunc (W _container_heap_Interface) Len() int { return W.WLen() }\n\nfunc (W _container_heap_Interface) Pop() interface{} { return W.WPop() }\nfunc (W _container_heap_Interface) Push(x interface{}) { W.WPush(x) }\nfunc (W _container_heap_Interface) Swap(i int, j int) { W.WSwap(i, j) }\n\nfunc (W _container_heap_Interface) Less(i int, j int) bool ", "output": "{ return W.WLess(i, j) }"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n)\n\nvar cfgFile string\n\n\nvar RootCmd = &cobra.Command{\n\tUse: \"docktor\",\n\tShort: \"Administration & Monitoring Deployment with Docker\",\n\tLong: `Docktor is a web application which aims to make the deployment of docke services easier\nWith it, you can manage several daemons, services and group.\nEach service can be deployed on a daemon for a group.\n\t`,\n}\n\nconst (\n\tconfigPath = \"$HOME\"\n\tconfigFile = \".docktor\"\n\tprefixForEnvVariables = \"docktor\"\n)\n\n\n\nfunc Execute() {\n\tif err := RootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}\n\nfunc init() {\n\tcobra.OnInitialize(initConfig)\n\tRootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is $HOME/.docktor.yaml)\")\n}\n\n\n\n\nfunc initConfig() ", "output": "{\n\tif cfgFile != \"\" { \n\t\tviper.SetConfigFile(cfgFile)\n\t}\n\n\tviper.SetEnvPrefix(prefixForEnvVariables) \n\tviper.SetConfigName(configFile) \n\tviper.AddConfigPath(configPath) \n\tviper.AutomaticEnv() \n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\", \"-\", \"_\")) \n\n\terr := viper.ReadInConfig()\n\tif err == nil {\n\t\tfmt.Println(\"Using config file:\" + viper.ConfigFileUsed())\n\t} else {\n\t\tfmt.Println(\"Cant read config file:\" + viper.ConfigFileUsed())\n\t}\n}"} {"input": "package events\n\nimport \"github.com/gophercloud/gophercloud\"\n\nvar apiVersion = \"v1\"\nvar apiName = \"events\"\n\nfunc commonURL(client *gophercloud.ServiceClient) string {\n\treturn client.ServiceURL(apiVersion, apiName)\n}\n\nfunc listURL(client *gophercloud.ServiceClient) string {\n\treturn commonURL(client)\n}\n\n\n\nfunc getURL(client *gophercloud.ServiceClient, id string) string {\n\treturn idURL(client, id)\n}\n\nfunc idURL(client *gophercloud.ServiceClient, id string) string ", "output": "{\n\treturn client.ServiceURL(apiVersion, apiName, id)\n}"} {"input": "package models\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype Application struct {\n\tID int64 `json:\"id\"`\n\tName string `json:\"name\"`\n\tMaintainerID int64 `json:\"maintainerID\"`\n\tSecret string `json:\"-\"`\n\tCallback string `json:\"callback\"`\n\tActive bool `json:\"active\"`\n}\n\n\n\n\n\nfunc (application *Application) String() string {\n\tjsonContent, err := json.Marshal(application)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn string(jsonContent)\n}\n\nfunc NewApplication(name string, maintainer int64, secret string, callback string, active bool) *Application ", "output": "{\n\tapplication := &Application{\n\t\tID: -1,\n\t\tName: name,\n\t\tMaintainerID: maintainer,\n\t\tSecret: secret,\n\t\tCallback: callback,\n\t\tActive: active,\n\t}\n\n\treturn application\n}"} {"input": "package behaviors\n\n\n\n\n\nimport (\n\t\"github.com/tideland/golib/cells\"\n\t\"github.com/tideland/golib/logger\"\n)\n\n\n\n\n\n\ntype CallbackFunc func(topic string, payload cells.Payload) error\n\n\n\ntype callbackBehavior struct {\n\tctx cells.Context\n\tcallbackFuncs []CallbackFunc\n}\n\n\n\n\n\n\n\nfunc (b *callbackBehavior) Init(ctx cells.Context) error {\n\tb.ctx = ctx\n\treturn nil\n}\n\n\nfunc (b *callbackBehavior) Terminate() error {\n\treturn nil\n}\n\n\nfunc (b *callbackBehavior) ProcessEvent(event cells.Event) error {\n\tfor _, callbackFunc := range b.callbackFuncs {\n\t\tif err := callbackFunc(event.Topic(), event.Payload()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (b *callbackBehavior) Recover(err interface{}) error {\n\treturn nil\n}\n\nfunc NewCallbackBehavior(cbfs ...CallbackFunc) cells.Behavior ", "output": "{\n\tif len(cbfs) == 0 {\n\t\tlogger.Errorf(\"callback created without callback functions\")\n\t}\n\treturn &callbackBehavior{nil, cbfs}\n}"} {"input": "package gridq\n\ntype byColRow []*WriteResponse\n\nfunc (p byColRow) Len() int { return len(p) }\nfunc (p byColRow) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byColRow) Less(i, j int) bool {\n\tif p[i].Col < p[j].Col {\n\t\treturn true\n\t} else if p[i].Col > p[j].Col {\n\t\treturn false\n\t} else {\n\t\treturn p[i].Row < p[j].Row\n\t}\n}\n\ntype byRowTimestamp []*ReadResponse\n\nfunc (p byRowTimestamp) Len() int { return len(p) }\nfunc (p byRowTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\n\n\ntype byTimestamp []*ReadResponse\n\nfunc (p byTimestamp) Len() int { return len(p) }\nfunc (p byTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byTimestamp) Less(i, j int) bool { return p[i].State.Timestamp < p[j].State.Timestamp }\n\nfunc (p byRowTimestamp) Less(i, j int) bool ", "output": "{\n\tif p[i].Row < p[j].Row {\n\t\treturn true\n\t} else if p[i].Row > p[j].Row {\n\t\treturn false\n\t} else {\n\t\treturn p[i].State.Timestamp > p[j].State.Timestamp\n\t}\n}"} {"input": "package coap\n\nimport (\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"io\"\n)\n\n\n\ntype TcpMessage struct {\n\tMessage\n}\n\nfunc (m *TcpMessage) MarshalBinary() ([]byte, error) {\n\tbin, err := m.Message.MarshalBinary()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\n\tl := []byte{0, 0}\n\tbinary.BigEndian.PutUint16(l, uint16(len(bin)))\n\n\treturn append(l, bin...), nil\n}\n\nfunc (m *TcpMessage) UnmarshalBinary(data []byte) error {\n\tif len(data) < 4 {\n\t\treturn errors.New(\"short packet\")\n\t}\n\n\treturn m.Message.UnmarshalBinary(data)\n}\n\n\n\n\nfunc Decode(r io.Reader) (*TcpMessage, error) ", "output": "{\n\tvar ln uint16\n\terr := binary.Read(r, binary.BigEndian, &ln)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpacket := make([]byte, ln)\n\t_, err = io.ReadFull(r, packet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm := TcpMessage{}\n\n\terr = m.UnmarshalBinary(packet)\n\treturn &m, err\n}"} {"input": "package task\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Event struct {\n\tTask *Task\n\tPayload interface{}\n}\n\n\n\n\n\ntype Ended struct {\n\tError error\n}\n\nfunc (p *Ended) String() string {\n\treturn fmt.Sprintf(\"%T{%v}\", p, p.Error)\n}\n\n\ntype Output struct {\n\tChunk string\n}\n\nfunc (p *Output) String() string {\n\treturn fmt.Sprintf(\"%T{%v}\", p, p.Chunk)\n}\n\nfunc (e *Event) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%T{from %v: %v}\", e, e.Task, e.Payload)\n}"} {"input": "package caaa\n\nimport (\n\t\"encoding/xml\"\n\n\t\"github.com/fgrid/iso20022\"\n)\n\ntype Document01600102 struct {\n\tXMLName xml.Name `xml:\"urn:iso:std:iso:20022:tech:xsd:caaa.016.001.02 Document\"`\n\tMessage *AcceptorCurrencyConversionRequestV02 `xml:\"AccptrCcyConvsReq\"`\n}\n\nfunc (d *Document01600102) AddMessage() *AcceptorCurrencyConversionRequestV02 {\n\td.Message = new(AcceptorCurrencyConversionRequestV02)\n\treturn d.Message\n}\n\n\n\ntype AcceptorCurrencyConversionRequestV02 struct {\n\n\tHeader *iso20022.Header10 `xml:\"Hdr\"`\n\n\tCurrencyConversionRequest *iso20022.AcceptorCurrencyConversionRequest2 `xml:\"CcyConvsReq\"`\n\n\tSecurityTrailer *iso20022.ContentInformationType11 `xml:\"SctyTrlr\"`\n}\n\nfunc (a *AcceptorCurrencyConversionRequestV02) AddHeader() *iso20022.Header10 {\n\ta.Header = new(iso20022.Header10)\n\treturn a.Header\n}\n\n\n\nfunc (a *AcceptorCurrencyConversionRequestV02) AddSecurityTrailer() *iso20022.ContentInformationType11 {\n\ta.SecurityTrailer = new(iso20022.ContentInformationType11)\n\treturn a.SecurityTrailer\n}\n\nfunc (a *AcceptorCurrencyConversionRequestV02) AddCurrencyConversionRequest() *iso20022.AcceptorCurrencyConversionRequest2 ", "output": "{\n\ta.CurrencyConversionRequest = new(iso20022.AcceptorCurrencyConversionRequest2)\n\treturn a.CurrencyConversionRequest\n}"} {"input": "package isdocker\n\nimport (\n\t\"testing\"\n)\n\nfunc TestIsDockerProcess(t *testing.T) {\n\tisdocker := IsDocker()\n\tif isdocker == false {\n\t\tt.Errorf(\"process is in docker mode, but shows non-docker mode !!!\")\n\t}\n}\n\n\n\nfunc TestIsNonDockerProcess(t *testing.T) ", "output": "{\n\tisdocker := IsDocker()\n\tif isdocker == true {\n\t\tt.Errorf(\"process is in non-docker mode, but shows docker mode !!!\")\n\t}\n}"} {"input": "package types\n\nimport \"testing\"\n\nfunc TestGzipText(t *testing.T) {\n\tg := GzippedText(\"Hello, world\")\n\tv, err := g.Value()\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\terr = (&g).Scan(v)\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\tif string(g) != \"Hello, world\" {\n\t\tt.Errorf(\"Was expecting the string we sent in (Hello World), got %s\", string(g))\n\t}\n}\n\n\n\nfunc TestBitBool(t *testing.T) {\n\tvar b BitBool = true\n\n\tv, err := b.Value()\n\tif err != nil {\n\t\tt.Errorf(\"Cannot return error\")\n\t}\n\terr = (&b).Scan(v)\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\tif !b {\n\t\tt.Errorf(\"Was expecting the bool we sent in (true), got %b\", b)\n\t}\n\n\tb = false\n\n\tv, err = b.Value()\n\tif err != nil {\n\t\tt.Errorf(\"Cannot return error\")\n\t}\n\terr = (&b).Scan(v)\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\tif b {\n\t\tt.Errorf(\"Was expecting the bool we sent in (false), got %b\", b)\n\t}\n}\n\nfunc TestJSONText(t *testing.T) ", "output": "{\n\tj := JSONText(`{\"foo\": 1, \"bar\": 2}`)\n\tv, err := j.Value()\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\terr = (&j).Scan(v)\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\tm := map[string]interface{}{}\n\tj.Unmarshal(&m)\n\n\tif m[\"foo\"].(float64) != 1 || m[\"bar\"].(float64) != 2 {\n\t\tt.Errorf(\"Expected valid json but got some garbage instead? %#v\", m)\n\t}\n\n\tj = JSONText(`{\"foo\": 1, invalid, false}`)\n\tv, err = j.Value()\n\tif err == nil {\n\t\tt.Errorf(\"Was expecting invalid json to fail!\")\n\t}\n}"} {"input": "package password\n\n\nvar _ PasswordGenerator = (*mockGenerator)(nil)\n\ntype mockGenerator struct {\n\tresult string\n\terr error\n}\n\n\n\n\n\n\n\n\nfunc NewMockGenerator(result string, err error) *mockGenerator {\n\treturn &mockGenerator{\n\t\tresult: result,\n\t\terr: err,\n\t}\n}\n\n\nfunc (g *mockGenerator) Generate(int, int, int, bool, bool) (string, error) {\n\tif g.err != nil {\n\t\treturn \"\", g.err\n\t}\n\treturn g.result, nil\n}\n\n\n\n\nfunc (g *mockGenerator) MustGenerate(int, int, int, bool, bool) string ", "output": "{\n\tif g.err != nil {\n\t\tpanic(g.err)\n\t}\n\treturn g.result\n}"} {"input": "package circonusgometrics\n\nimport (\n\t\"sync\"\n\n\t\"github.com/circonus-labs/circonusllhist\"\n)\n\n\ntype Histogram struct {\n\tname string\n\thist *circonusllhist.Histogram\n\trw sync.RWMutex\n}\n\n\nfunc (m *CirconusMetrics) Timing(metric string, val float64) {\n\tm.SetHistogramValue(metric, val)\n}\n\n\nfunc (m *CirconusMetrics) RecordValue(metric string, val float64) {\n\tm.SetHistogramValue(metric, val)\n}\n\n\nfunc (m *CirconusMetrics) SetHistogramValue(metric string, val float64) {\n\tm.NewHistogram(metric)\n\n\tm.histograms[metric].rw.Lock()\n\tdefer m.histograms[metric].rw.Unlock()\n\n\tm.histograms[metric].hist.RecordValue(val)\n}\n\n\n\n\n\nfunc (m *CirconusMetrics) NewHistogram(metric string) *Histogram {\n\tm.hm.Lock()\n\tdefer m.hm.Unlock()\n\n\tif hist, ok := m.histograms[metric]; ok {\n\t\treturn hist\n\t}\n\n\thist := &Histogram{\n\t\tname: metric,\n\t\thist: circonusllhist.New(),\n\t}\n\n\tm.histograms[metric] = hist\n\n\treturn hist\n}\n\n\nfunc (h *Histogram) Name() string {\n\treturn h.name\n}\n\n\nfunc (h *Histogram) RecordValue(v float64) {\n\th.rw.Lock()\n\tdefer h.rw.Unlock()\n\n\th.hist.RecordValue(v)\n}\n\nfunc (m *CirconusMetrics) RemoveHistogram(metric string) ", "output": "{\n\tm.hm.Lock()\n\tdefer m.hm.Unlock()\n\tdelete(m.histograms, metric)\n}"} {"input": "package neo\n\nimport \"github.com/jmcvetta/neoism\"\n\nvar db *neoism.Database\n\nfunc init() {\n\tvar err error\n\tdb, err = neoism.Connect(\"http://localhost:7474/db/data\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\n\nfunc DB() *neoism.Database ", "output": "{\n\treturn db\n}"} {"input": "package main\nimport (\n \"fmt\"\n \"os\"\n \"strings\"\n)\n\nfunc (s *TableStats) init(headers []string) error {\n s.Headers = make([]string, len(headers))\n s.Fields = make(map[string]*FieldStats)\n for i,header := range(headers) {\n header = strings.TrimSpace(header)\n if _,ok := s.Fields[header]; ok {\n fmt.Fprintf(os.Stderr, \"Duplicate header '%s'\\n\", header)\n }\n stats := new(FieldStats)\n stats.init()\n s.Headers[i] = header\n s.Fields[header] = stats\n }\n return nil\n}\n\nfunc (s *TableStats) update(values []string) error {\n if len(values) != len(s.Headers) {\n return fmt.Errorf(\"Found %d values but %d headers\",\n len(values), len(s.Headers))\n }\n for i,header := range(s.Headers) {\n field := s.Fields[header]\n if field != nil {\n field.update(values[i])\n }\n }\n s.NumRows++\n return nil\n}\n\n\n\nfunc (s *TableStats) String() string ", "output": "{\n tableStr := fmt.Sprintf(\"Table stats - %d columns, %d rows\\n\"+\n \"=================================\",\n len(s.Headers), s.NumRows)\n var fieldStrs []string\n for _,header := range(s.Headers) {\n var headerStr string\n if header == \"\" {\n headerStr = \"(blank header)\"\n } else {\n headerStr = \"'\"+header+\"'\"\n }\n fieldStr := s.Fields[header].String()\n fieldStrs = append(fieldStrs, fmt.Sprintf(\"%s %s\",\n headerStr, fieldStr))\n }\n return tableStr + \"\\n\\n\" + strings.Join(fieldStrs, \"\\n\\n\")\n}"} {"input": "package linker\n\nimport (\n\t\"errors\"\n\n\tparser \"github.com/moovweb/tritium/parser\"\n\ttp \"github.com/moovweb/tritium/proto\"\n\t. \"github.com/moovweb/tritium/util\"\n)\n\nfunc RunStringWithPackage(src, projectPath, scriptPath, fileName string, pkg *tp.Package, activeLayers []string, ranges ...Range) (*tp.Transform, error) {\n\tobjs := parser.Parse(src, projectPath, scriptPath, fileName, false, activeLayers)\n\treturn runWithObjs(objs, pkg, projectPath, scriptPath, ranges...)\n}\n\nfunc RunWithPackage(projectPath, scriptPath, fileName string, pkg *tp.Package, activeLayers []string) (*tp.Transform, error) {\n\tobjs := parser.ParseFileSet(projectPath, scriptPath, fileName, false, activeLayers)\n\treturn runWithObjs(objs, pkg, projectPath, scriptPath)\n}\n\n\n\nfunc runWithObjs(objs []*tp.ScriptObject, pkg *tp.Package, projectPath, scriptPath string, ranges ...Range) (*tp.Transform, error) ", "output": "{\n\tctx := NewObjectLinkingContext(pkg, objs, projectPath, scriptPath, ranges...)\n\tctx.Link()\n\tif ctx.HasErrors() {\n\t\tmessage := \"\"\n\t\tfor _, msg := range ctx.Errors {\n\t\t\tmessage = message + \"\\n\" + msg\n\t\t}\n\t\treturn nil, errors.New(message)\n\t}\n\n\treturn ctx.Transform, nil\n}"} {"input": "package summary\n\nimport (\n\tinfo \"github.com/google/cadvisor/info/v2\"\n)\n\n\n\n\n\ntype SamplesBuffer struct {\n\tsamples []info.Usage\n\tmaxSize int\n\tindex int\n}\n\n\nfunc NewSamplesBuffer(size int) *SamplesBuffer {\n\treturn &SamplesBuffer{\n\t\tindex: -1,\n\t\tmaxSize: size,\n\t}\n}\n\n\nfunc (s *SamplesBuffer) Size() int {\n\treturn len(s.samples)\n}\n\n\nfunc (s *SamplesBuffer) Add(stat info.Usage) {\n\tif len(s.samples) < s.maxSize {\n\t\ts.samples = append(s.samples, stat)\n\t\ts.index++\n\t\treturn\n\t}\n\ts.index = (s.index + 1) % s.maxSize\n\ts.samples[s.index] = stat\n}\n\n\n\n\nfunc (s *SamplesBuffer) RecentStats(n int) []*info.Usage ", "output": "{\n\tif n > len(s.samples) {\n\t\tn = len(s.samples)\n\t}\n\tstart := s.index - (n - 1)\n\tif start < 0 {\n\t\tstart += len(s.samples)\n\t}\n\n\tout := make([]*info.Usage, n)\n\tfor i := 0; i < n; i++ {\n\t\tindex := (start + i) % len(s.samples)\n\t\tout[i] = &s.samples[index]\n\t}\n\treturn out\n}"} {"input": "package seqnum\n\n\ntype Value uint32\n\n\ntype Size uint32\n\n\nfunc (v Value) LessThan(w Value) bool {\n\treturn int32(v-w) < 0\n}\n\n\nfunc (v Value) LessThanEq(w Value) bool {\n\tif v == w {\n\t\treturn true\n\t}\n\treturn v.LessThan(w)\n}\n\n\nfunc (v Value) InRange(a, b Value) bool {\n\treturn v-a < b-a\n}\n\n\n\nfunc (v Value) InWindow(first Value, size Size) bool {\n\treturn v.InRange(first, first.Add(size))\n}\n\n\nfunc Overlap(a Value, b Size, x Value, y Size) bool {\n\treturn a.LessThan(x.Add(y)) && x.LessThan(a.Add(b))\n}\n\n\nfunc (v Value) Add(s Size) Value {\n\treturn v + Value(s)\n}\n\n\n\n\n\nfunc (v *Value) UpdateForward(s Size) {\n\t*v += Value(s)\n}\n\nfunc (v Value) Size(w Value) Size ", "output": "{\n\treturn Size(w - v)\n}"} {"input": "package medicament\n\nimport \"time\"\n\ntype expire struct {\n\tExpireDate time.Time\n\tDaysToExpire int\n}\n\n\n\nfunc newExpire(t time.Time, r refill, ratio float64) expire ", "output": "{\n\tt = midnight(t)\n\tmsid := r.Quantity / ratio\n\tdiff := t.Sub(r.Date).Hours() / 24\n\tdte := int(msid - diff)\n\tdur := time.Duration(dte*24) * time.Hour\n\ted := t.Add(dur)\n\te := expire{\n\t\tExpireDate: ed,\n\t\tDaysToExpire: dte,\n\t}\n\treturn e\n}"} {"input": "package label\n\n\n\n\nfunc InitLabels(mcsdir string, options []string) (string, string, error) {\n\treturn \"\", \"\", nil\n}\n\nfunc FormatMountLabel(src string, mountLabel string) string {\n\treturn src\n}\n\nfunc SetProcessLabel(processLabel string) error {\n\treturn nil\n}\n\n\n\nfunc SetFileCreateLabel(fileLabel string) error {\n\treturn nil\n}\n\nfunc Relabel(path string, fileLabel string, relabel string) error {\n\treturn nil\n}\n\nfunc GetPidLabel(pid int) (string, error) {\n\treturn \"\", nil\n}\n\nfunc Init() {\n}\n\nfunc ReserveLabel(label string) error {\n\treturn nil\n}\n\nfunc UnreserveLabel(label string) error {\n\treturn nil\n}\n\n\n\nfunc DupSecOpt(src string) []string {\n\treturn nil\n}\n\n\n\nfunc DisableSecOpt() []string {\n\treturn nil\n}\n\nfunc SetFileLabel(path string, fileLabel string) error ", "output": "{\n\treturn nil\n}"} {"input": "package precreator \n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"go.uber.org/zap\"\n)\n\n\ntype Service struct {\n\tcheckInterval time.Duration\n\tadvancePeriod time.Duration\n\n\tLogger zap.Logger\n\n\tdone chan struct{}\n\twg sync.WaitGroup\n\n\tMetaClient interface {\n\t\tPrecreateShardGroups(now, cutoff time.Time) error\n\t}\n}\n\n\nfunc NewService(c Config) (*Service, error) {\n\ts := Service{\n\t\tcheckInterval: time.Duration(c.CheckInterval),\n\t\tadvancePeriod: time.Duration(c.AdvancePeriod),\n\t\tLogger: zap.New(zap.NullEncoder()),\n\t}\n\n\treturn &s, nil\n}\n\n\nfunc (s *Service) WithLogger(log zap.Logger) {\n\ts.Logger = log.With(zap.String(\"service\", \"shard-precreation\"))\n}\n\n\nfunc (s *Service) Open() error {\n\tif s.done != nil {\n\t\treturn nil\n\t}\n\n\ts.Logger.Info(fmt.Sprintf(\"Starting precreation service with check interval of %s, advance period of %s\",\n\t\ts.checkInterval, s.advancePeriod))\n\n\ts.done = make(chan struct{})\n\n\ts.wg.Add(1)\n\tgo s.runPrecreation()\n\treturn nil\n}\n\n\nfunc (s *Service) Close() error {\n\tif s.done == nil {\n\t\treturn nil\n\t}\n\n\tclose(s.done)\n\ts.wg.Wait()\n\ts.done = nil\n\n\treturn nil\n}\n\n\n\n\n\nfunc (s *Service) precreate(now time.Time) error {\n\tcutoff := now.Add(s.advancePeriod).UTC()\n\tif err := s.MetaClient.PrecreateShardGroups(now, cutoff); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (s *Service) runPrecreation() ", "output": "{\n\tdefer s.wg.Done()\n\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(s.checkInterval):\n\t\t\tif err := s.precreate(time.Now().UTC()); err != nil {\n\t\t\t\ts.Logger.Info(fmt.Sprintf(\"failed to precreate shards: %s\", err.Error()))\n\t\t\t}\n\t\tcase <-s.done:\n\t\t\ts.Logger.Info(\"Precreation service terminating\")\n\t\t\treturn\n\t\t}\n\t}\n}"} {"input": "package multidict_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n\n\t\"github.com/onsi/ginkgo/reporters\"\n\n\t\"github.com/projectcalico/calico/libcalico-go/lib/testutils\"\n)\n\n\n\nfunc TestMultidict(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tjunitReporter := reporters.NewJUnitReporter(\"../report/multidict_suite.xml\")\n\tRunSpecsWithDefaultAndCustomReporters(t, \"Multidict Suite\", []Reporter{junitReporter})\n}\n\nfunc init() ", "output": "{\n\ttestutils.HookLogrusForGinkgo()\n}"} {"input": "package mocks\n\nimport (\n\t\"crypto/x509\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\n\t\"github.com/letsencrypt/boulder/core\"\n)\n\n\n\ntype MockCA struct {\n\tPEM []byte\n}\n\n\nfunc (ca *MockCA) IssueCertificate(csr x509.CertificateRequest, regID int64) (core.Certificate, error) {\n\tif ca.PEM == nil {\n\t\treturn core.Certificate{}, fmt.Errorf(\"MockCA's PEM field must be set before calling IssueCertificate\")\n\t}\n\tblock, _ := pem.Decode(ca.PEM)\n\tcert, err := x509.ParseCertificate(block.Bytes)\n\tif err != nil {\n\t\treturn core.Certificate{}, err\n\t}\n\treturn core.Certificate{\n\t\tDER: cert.Raw,\n\t}, nil\n}\n\n\n\n\n\nfunc (ca *MockCA) RevokeCertificate(serial string, reasonCode core.RevocationCode) (err error) {\n\treturn\n}\n\nfunc (ca *MockCA) GenerateOCSP(xferObj core.OCSPSigningRequest) (ocsp []byte, err error) ", "output": "{\n\treturn\n}"} {"input": "package charm\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n)\n\n\n\ntype Charm interface {\n\tMeta() *Meta\n\tConfig() *Config\n\tRevision() int\n}\n\n\n\nfunc Read(path string) (Charm, error) {\n\tinfo, err := os.Stat(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif info.IsDir() {\n\t\treturn ReadDir(path)\n\t}\n\treturn ReadBundle(path)\n}\n\n\n\n\n\nfunc InferRepository(curl *URL, localRepoPath string) (repo Repository, err error) ", "output": "{\n\tswitch curl.Schema {\n\tcase \"cs\":\n\t\trepo = Store()\n\tcase \"local\":\n\t\tif localRepoPath == \"\" {\n\t\t\treturn nil, errors.New(\"path to local repository not specified\")\n\t\t}\n\t\trepo = &LocalRepository{localRepoPath}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown schema for charm URL %q\", curl)\n\t}\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strings\"\n)\n\n\nfunc MakeIndexMessage(pkg *Package) string {\n\tdependenciesNames := []string{}\n\n\tfor _, dep := range pkg.Dependencies {\n\t\tdependenciesNames = append(dependenciesNames, dep.Name)\n\t}\n\n\tnamesAsString := strings.Join(dependenciesNames, \",\")\n\treturn fmt.Sprintf(\"INDEX|%s|%s\", pkg.Name, namesAsString)\n}\n\n\nfunc MakeRemoveMessage(pkg *Package) string {\n\treturn fmt.Sprintf(\"REMOVE|%s|\", pkg.Name)\n}\n\n\nfunc MakeQueryMessage(pkg *Package) string {\n\treturn fmt.Sprintf(\"QUERY|%s|\", pkg.Name)\n}\n\nvar possibleInvalidCommands = []string{\"BLINDEX\", \"REMOVES\", \"QUER\", \"LIZARD\", \"I\"}\nvar possibleInvalidChars = []string{\"=\", \"+\", \"☃\", \" \"}\n\n\n\n\n\nfunc MakeBrokenMessage() string ", "output": "{\n\tsyntaxError := rand.Intn(10)%2 == 0\n\n\tif syntaxError {\n\t\tinvalidChar := possibleInvalidChars[rand.Intn(len(possibleInvalidChars))]\n\t\treturn fmt.Sprintf(\"INDEX|emacs%selisp\", invalidChar)\n\t}\n\n\tinvalidCommand := possibleInvalidCommands[rand.Intn(len(possibleInvalidCommands))]\n\treturn fmt.Sprintf(\"%s|a|b\", invalidCommand)\n}"} {"input": "package pathmgr\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\n\n\n\n\n\n\n\n\n\ntype SyncPaths struct {\n\tvalue atomic.Value\n\tmutex sync.Mutex\n}\n\n\n\ntype SyncPathsData struct {\n\tAPS AppPathSet\n\tModifyTime time.Time\n\tRefreshTime time.Time\n}\n\n\n\nfunc NewSyncPaths() *SyncPaths {\n\tsp := &SyncPaths{}\n\tnow := time.Now()\n\tsp.value.Store(\n\t\t&SyncPathsData{\n\t\t\tAPS: make(AppPathSet),\n\t\t\tModifyTime: now,\n\t\t\tRefreshTime: now,\n\t\t},\n\t)\n\treturn sp\n}\n\n\n\n\n\n\n\n\n\nfunc (sp *SyncPaths) Load() *SyncPathsData {\n\treturn sp.value.Load().(*SyncPathsData)\n}\n\nfunc setSubtract(x, y AppPathSet) AppPathSet {\n\tresult := make(AppPathSet)\n\tfor _, ap := range x {\n\t\tif _, ok := y[ap.Key()]; !ok {\n\t\t\tresult.Add(ap.Entry)\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (sp *SyncPaths) update(newAPS AppPathSet) ", "output": "{\n\tsp.mutex.Lock()\n\tdefer sp.mutex.Unlock()\n\tvalue := sp.value.Load().(*SyncPathsData)\n\tvalue.RefreshTime = time.Now()\n\ttoAdd := setSubtract(newAPS, value.APS)\n\ttoRemove := setSubtract(value.APS, newAPS)\n\tif len(toAdd) > 0 || len(toRemove) > 0 {\n\t\tvalue.ModifyTime = value.RefreshTime\n\t}\n\tvalue.APS = newAPS\n\tsp.value.Store(value)\n}"} {"input": "package jujuc\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"launchpad.net/gnuflag\"\n\n\t\"github.com/juju/core/cmd\"\n)\n\n\ntype UnitGetCommand struct {\n\tcmd.CommandBase\n\tctx Context\n\tKey string\n\tout cmd.Output\n}\n\nfunc NewUnitGetCommand(ctx Context) cmd.Command {\n\treturn &UnitGetCommand{ctx: ctx}\n}\n\nfunc (c *UnitGetCommand) Info() *cmd.Info {\n\treturn &cmd.Info{\n\t\tName: \"unit-get\",\n\t\tArgs: \"\",\n\t\tPurpose: \"print public-address or private-address\",\n\t}\n}\n\nfunc (c *UnitGetCommand) SetFlags(f *gnuflag.FlagSet) {\n\tc.out.AddFlags(f, \"smart\", cmd.DefaultFormatters)\n}\n\nfunc (c *UnitGetCommand) Init(args []string) error {\n\tif args == nil {\n\t\treturn errors.New(\"no setting specified\")\n\t}\n\tif args[0] != \"private-address\" && args[0] != \"public-address\" {\n\t\treturn fmt.Errorf(\"unknown setting %q\", args[0])\n\t}\n\tc.Key = args[0]\n\treturn cmd.CheckEmpty(args[1:])\n}\n\n\n\nfunc (c *UnitGetCommand) Run(ctx *cmd.Context) error ", "output": "{\n\tvalue, ok := \"\", false\n\tif c.Key == \"private-address\" {\n\t\tvalue, ok = c.ctx.PrivateAddress()\n\t} else {\n\t\tvalue, ok = c.ctx.PublicAddress()\n\t}\n\tif !ok {\n\t\treturn fmt.Errorf(\"%s not set\", c.Key)\n\t}\n\treturn c.out.Write(ctx, value)\n}"} {"input": "package league\n\ntype Division struct {\n\tname string\n\tteams map[string]*Team\n\tconfrence *Conference\n\tleague *League\n}\n\nfunc (division *Division) GetTeams() map[string]*Team {\n\treturn division.teams\n}\n\nfunc (division *Division) GetName() string {\n\treturn division.name\n}\n\nfunc (division *Division) GetConference() *Conference {\n\treturn division.confrence\n}\n\n\n\nfunc (division *Division) getLeague() *League ", "output": "{\n\treturn division.league\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\ntype Project struct {\n\tName string `yaml:\"project\"`\n\tDescription string\n\tWebsiteLink string `yaml:\"website-link\"`\n\tGithubLink string `yaml:\"github-link\"`\n\tTags []string\n\tCreator string\n\tCreatorLink string `yaml:\"creator-link\"`\n}\n\nfunc getProjects() []Project {\n\tprojects := []Project{}\n\tdata := readProjectsFile()\n\terr := yaml.Unmarshal(data, &projects)\n\tif err != nil {\n\t\treturn []Project{}\n\t}\n\n\tl := len(projects)\n\tfor i := 0; i < l/2; i++ {\n\t\tj := l - i - 1\n\t\tprojects[i], projects[j] = projects[j], projects[i]\n\t}\n\n\treturn projects\n}\n\n\n\nfunc readProjectsFile() []byte ", "output": "{\n\tfilename := \"projects.yaml\"\n\tcontent, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn []byte{}\n\t}\n\n\treturn content\n}"} {"input": "package utils\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\tirc \"gopkg.in/irc.v3\"\n)\n\n\n\ntype TestClientServer struct {\n\tclient *bytes.Buffer\n\tserver *bytes.Buffer\n}\n\n\nfunc NewTestClientServer() *TestClientServer {\n\treturn &TestClientServer{\n\t\tclient: &bytes.Buffer{},\n\t\tserver: &bytes.Buffer{},\n\t}\n}\n\n\nfunc (cs *TestClientServer) Read(p []byte) (int, error) {\n\treturn cs.server.Read(p)\n}\n\n\nfunc (cs *TestClientServer) Write(p []byte) (int, error) {\n\treturn cs.client.Write(p)\n}\n\n\n\n\n\n\n\n\nfunc (cs *TestClientServer) CheckLines(t *testing.T, expected []string) bool {\n\tok := true\n\n\tlines := strings.Split(cs.client.String(), \"\\r\\n\")\n\n\tvar line, clientLine string\n\tfor len(expected) > 0 && len(lines) > 0 {\n\t\tline, expected = expected[0], expected[1:]\n\t\tclientLine, lines = lines[0], lines[1:]\n\n\t\tok = ok && assert.Equal(t, line, clientLine)\n\t}\n\n\tok = ok && assert.Equal(t, 0, len(expected), \"Not enough lines: %s\", strings.Join(expected, \", \"))\n\tok = ok && assert.Equal(t, 0, len(lines), \"Extra non-empty lines: %s\", strings.Join(lines, \", \"))\n\n\treturn ok\n}\n\n\nfunc (cs *TestClientServer) Reset() {\n\tcs.client.Reset()\n\tcs.server.Reset()\n}\n\nfunc (cs *TestClientServer) SendServerLines(lines []string) ", "output": "{\n\tw := irc.NewWriter(cs.server)\n\n\tfor _, line := range lines {\n\t\tw.WriteMessage(irc.MustParseMessage(line))\n\t}\n}"} {"input": "package convert\n\nfunc Add(s []string, a string) []string {\n\tfor _, existing := range s {\n\t\tif a == existing {\n\t\t\treturn s\n\t\t}\n\t}\n\treturn append(s, a)\n}\n\nfunc Union(s []string, a []string) []string {\n\tfor _, entry := range a {\n\t\tfound := false\n\t\tfor _, existing := range s {\n\t\t\tif entry == existing {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\ts = append(s, entry)\n\t\t}\n\t}\n\treturn s\n}\n\n\n\nfunc Uniq(s []string) (r []string) ", "output": "{\n\tfor _, entry := range s {\n\t\tfound := false\n\t\tfor _, existing := range r {\n\t\t\tif existing == entry {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tr = append(r, entry)\n\t\t}\n\t}\n\treturn\n}"} {"input": "package bazilfuse\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"os/exec\"\n)\n\n\n\nfunc unmount(dir string) error ", "output": "{\n\tcmd := exec.Command(\"fusermount\", \"-u\", dir)\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tif len(output) > 0 {\n\t\t\toutput = bytes.TrimRight(output, \"\\n\")\n\t\t\tmsg := err.Error() + \": \" + string(output)\n\t\t\terr = errors.New(msg)\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t. \"launchpad.net/gocheck\"\n\t\"launchpad.net/juju-core/charm\"\n\tjujutesting \"launchpad.net/juju-core/juju/testing\"\n\t\"launchpad.net/juju-core/testing\"\n)\n\ntype ExposeSuite struct {\n\tjujutesting.RepoSuite\n}\n\nvar _ = Suite(&ExposeSuite{})\n\n\n\nfunc (s *ExposeSuite) assertExposed(c *C, service string) {\n\tsvc, err := s.State.Service(service)\n\tc.Assert(err, IsNil)\n\texposed := svc.IsExposed()\n\tc.Assert(exposed, Equals, true)\n}\n\nfunc (s *ExposeSuite) TestExpose(c *C) {\n\ttesting.Charms.BundlePath(s.SeriesPath, \"dummy\")\n\terr := runDeploy(c, \"local:dummy\", \"some-service-name\")\n\tc.Assert(err, IsNil)\n\tcurl := charm.MustParseURL(\"local:precise/dummy-1\")\n\ts.AssertService(c, \"some-service-name\", curl, 1, 0)\n\n\terr = runExpose(c, \"some-service-name\")\n\tc.Assert(err, IsNil)\n\ts.assertExposed(c, \"some-service-name\")\n\n\terr = runExpose(c, \"nonexistent-service\")\n\tc.Assert(err, ErrorMatches, `service \"nonexistent-service\" not found`)\n}\n\nfunc runExpose(c *C, args ...string) error ", "output": "{\n\t_, err := testing.RunCommand(c, &ExposeCommand{}, args)\n\treturn err\n}"} {"input": "package esa\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\ntype GetTeamCommentStargazersRequest struct {\n\tPaginationRequest\n}\ntype GetTeamCommentStargazersResponse struct {\n\tStargazers []Stargazer `json:\"stargazers\"`\n\tPaginationResponse\n}\n\n\n\nfunc (c *Client) GetTeamCommentStargazers(teamName string, commentID int, req *GetTeamCommentStargazersRequest) (*GetTeamCommentStargazersResponse, error) ", "output": "{\n\tbuildReq := c.get(fmt.Sprintf(\"/v1/teams/%s/comments/%d/stargazers\", teamName, commentID))\n\n\tresp, body, errs := c.setPaginationParams(buildReq, &req.PaginationRequest).End()\n\n\tif len(errs) > 0 {\n\t\treturn nil, errs[0]\n\t}\n\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\treturn nil, c.parseError(body)\n\t}\n\n\tvar res GetTeamCommentStargazersResponse\n\tif err := json.Unmarshal([]byte(body), &res); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &res, nil\n}"} {"input": "package thrift\n\nimport \"io\"\n\ntype RichTransport struct {\n\tTTransport\n}\n\n\nfunc NewTRichTransport(trans TTransport) *RichTransport {\n\treturn &RichTransport{trans}\n}\n\nfunc (r *RichTransport) ReadByte() (c byte, err error) {\n\treturn readByte(r.TTransport)\n}\n\nfunc (r *RichTransport) WriteByte(c byte) error {\n\treturn writeByte(r.TTransport, c)\n}\n\nfunc (r *RichTransport) WriteString(s string) (n int, err error) {\n\treturn r.Write([]byte(s))\n}\n\nfunc (r *RichTransport) RemainingBytes() (num_bytes uint64) {\n\treturn r.TTransport.RemainingBytes()\n}\n\nfunc readByte(r io.Reader) (c byte, err error) {\n\tv := [1]byte{0}\n\tn, err := r.Read(v[0:1])\n\tif n > 0 && (err == nil || err == io.EOF) {\n\t\treturn v[0], nil\n\t}\n\tif n > 0 && err != nil {\n\t\treturn v[0], err\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn v[0], nil\n}\n\n\n\nfunc writeByte(w io.Writer, c byte) error ", "output": "{\n\tv := [1]byte{c}\n\t_, err := w.Write(v[0:1])\n\treturn err\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst letterBytes = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst lenLetters = len(letterBytes)\n\nfunc init() {\n\trand.Seed(time.Now().UnixNano())\n}\n\nfunc randStr(n int) string {\n\tb := make([]byte, n)\n\tfor i := range b {\n\t\tb[i] = letterBytes[rand.Int63()%int64(len(letterBytes))]\n\t}\n\treturn string(b)\n}\n\nfunc sendJson(w http.ResponseWriter, data interface{}) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(data)\n}\n\n\n\nfunc sendError(w http.ResponseWriter, msg string) {\n\tdata := struct {\n\t\tOk bool `json:\"ok\"`\n\t\tMsg string `json:\"msg\"`\n\t}{\n\t\tOk: false,\n\t\tMsg: msg,\n\t}\n\n\tsendJson(w, data)\n}\n\nfunc sendOk(w http.ResponseWriter, data interface{}) ", "output": "{\n\tjson.NewEncoder(w).Encode(data)\n}"} {"input": "package cabf_br\n\n\n\nimport (\n\t\"testing\"\n\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/test\"\n)\n\nfunc TestImproperModulusBadQ(t *testing.T) {\n\tinputPath := \"dsaBadQLen.pem\"\n\texpected := lint.Error\n\tout := test.TestLint(\"e_dsa_improper_modulus_or_divisor_size\", inputPath)\n\tif out.Status != expected {\n\t\tt.Errorf(\"%s: expected %s, got %s\", inputPath, expected, out.Status)\n\t}\n}\n\n\n\nfunc TestImproperModulusGoodQ(t *testing.T) ", "output": "{\n\tinputPath := \"dsaNotShorterThan2048Bits.pem\"\n\texpected := lint.Pass\n\tout := test.TestLint(\"e_dsa_improper_modulus_or_divisor_size\", inputPath)\n\tif out.Status != expected {\n\t\tt.Errorf(\"%s: expected %s, got %s\", inputPath, expected, out.Status)\n\t}\n}"} {"input": "package http\n\nimport (\n\t\"go-common/app/admin/main/tv/model\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\n\n\nfunc mangoAdd(c *bm.Context) {\n\tparam := new(struct {\n\t\tIDs []int64 `form:\"rids,split\" validate:\"required,min=1,dive,gt=0\"`\n\t\tRType int `form:\"rtype\" validate:\"required,min=1,max=2\"` \n\t})\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(tvSrv.MangoAdd(c, param.RType, param.IDs))\n}\n\nfunc mangoEdit(c *bm.Context) {\n\tparam := new(model.ReqMangoEdit)\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(nil, tvSrv.MangoEdit(c, param))\n}\n\nfunc mangoDel(c *bm.Context) {\n\tparam := new(struct {\n\t\tID int64 `form:\"id\" validate:\"required,min=1,gt=0\"`\n\t})\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(nil, tvSrv.MangoDel(c, param.ID))\n}\n\nfunc mangoPub(c *bm.Context) {\n\tparam := new(struct {\n\t\tIDs []int64 `form:\"ids,split\" validate:\"required,min=1,dive,gt=0\"`\n\t})\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(nil, tvSrv.MangoPub(c, param.IDs))\n}\n\nfunc mangoList(c *bm.Context) ", "output": "{\n\tc.JSON(tvSrv.MangoList(c))\n}"} {"input": "package internalversion\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\tapi \"k8s.io/kubernetes/pkg/api\"\n)\n\ntype TestgroupInterface interface {\n\tRESTClient() rest.Interface\n\tTestTypesGetter\n}\n\n\ntype TestgroupClient struct {\n\trestClient rest.Interface\n}\n\nfunc (c *TestgroupClient) TestTypes(namespace string) TestTypeInterface {\n\treturn newTestTypes(c, namespace)\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *TestgroupClient {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *TestgroupClient {\n\treturn &TestgroupClient{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tg, err := api.Registry.Group(\"testgroup.k8s.io\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.APIPath = \"/apis\"\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\tif config.GroupVersion == nil || config.GroupVersion.Group != g.GroupVersion.Group {\n\t\tcopyGroupVersion := g.GroupVersion\n\t\tconfig.GroupVersion = ©GroupVersion\n\t}\n\tconfig.NegotiatedSerializer = api.Codecs\n\n\tif config.QPS == 0 {\n\t\tconfig.QPS = 5\n\t}\n\tif config.Burst == 0 {\n\t\tconfig.Burst = 10\n\t}\n\treturn nil\n}\n\n\n\nfunc (c *TestgroupClient) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfig(c *rest.Config) (*TestgroupClient, error) ", "output": "{\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TestgroupClient{client}, nil\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n\tmodelsv2 \"github.com/goharbor/harbor/src/controller/artifact\"\n\t\"net/http\"\n\n\t\"github.com/goharbor/harbor/src/chartserver\"\n\tchttp \"github.com/goharbor/harbor/src/common/http\"\n\t\"github.com/goharbor/harbor/src/common/http/modifier\"\n)\n\n\n\n\ntype Client interface {\n\tArtifactClient\n\tChartClient\n}\n\n\ntype ArtifactClient interface {\n\tListAllArtifacts(project, repository string) ([]*modelsv2.Artifact, error)\n\tDeleteArtifact(project, repository, digest string) error\n\tDeleteArtifactRepository(project, repository string) error\n}\n\n\ntype ChartClient interface {\n\tListAllCharts(project, repository string) ([]*chartserver.ChartVersion, error)\n\tDeleteChart(project, repository, version string) error\n\tDeleteChartRepository(project, repository string) error\n}\n\n\n\n\ntype client struct {\n\turl string\n\thttpclient *chttp.Client\n}\n\nfunc (c *client) buildURL(path string) string {\n\treturn fmt.Sprintf(\"%s%s\", c.url, path)\n}\n\nfunc New(url string, httpclient *http.Client, authorizer modifier.Modifier) Client ", "output": "{\n\treturn &client{\n\t\turl: url,\n\t\thttpclient: chttp.NewClient(httpclient, authorizer),\n\t}\n}"} {"input": "package routes\n\nimport (\n\t\"net/http/pprof\"\n\n\t\"k8s.io/apiserver/pkg/server/mux\"\n)\n\n\ntype Profiling struct{}\n\n\n\n\nfunc (d Profiling) Install(c *mux.PathRecorderMux) ", "output": "{\n\tc.UnlistedHandleFunc(\"/debug/pprof/\", pprof.Index)\n\tc.UnlistedHandleFunc(\"/debug/pprof/profile\", pprof.Profile)\n\tc.UnlistedHandleFunc(\"/debug/pprof/symbol\", pprof.Symbol)\n\tc.UnlistedHandleFunc(\"/debug/pprof/trace\", pprof.Trace)\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n)\n\n\nconst DeleteDeploymentOKCode int = 200\n\n\ntype DeleteDeploymentOK struct {\n}\n\n\nfunc NewDeleteDeploymentOK() *DeleteDeploymentOK {\n\treturn &DeleteDeploymentOK{}\n}\n\n\n\n\n\nconst DeleteDeploymentUnauthorizedCode int = 401\n\n\ntype DeleteDeploymentUnauthorized struct {\n\tWWWAuthenticate string `json:\"WWW_Authenticate\"`\n}\n\n\nfunc NewDeleteDeploymentUnauthorized() *DeleteDeploymentUnauthorized {\n\treturn &DeleteDeploymentUnauthorized{}\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) WithWWWAuthenticate(wWWAuthenticate string) *DeleteDeploymentUnauthorized {\n\to.WWWAuthenticate = wWWAuthenticate\n\treturn o\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) SetWWWAuthenticate(wWWAuthenticate string) {\n\to.WWWAuthenticate = wWWAuthenticate\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\n\twWWAuthenticate := o.WWWAuthenticate\n\tif wWWAuthenticate != \"\" {\n\t\trw.Header().Set(\"WWW_Authenticate\", wWWAuthenticate)\n\t}\n\n\trw.WriteHeader(401)\n}\n\n\nconst DeleteDeploymentNotFoundCode int = 404\n\n\ntype DeleteDeploymentNotFound struct {\n}\n\n\nfunc NewDeleteDeploymentNotFound() *DeleteDeploymentNotFound {\n\treturn &DeleteDeploymentNotFound{}\n}\n\n\nfunc (o *DeleteDeploymentNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(404)\n}\n\n\nconst DeleteDeploymentInternalServerErrorCode int = 500\n\n\ntype DeleteDeploymentInternalServerError struct {\n}\n\n\nfunc NewDeleteDeploymentInternalServerError() *DeleteDeploymentInternalServerError {\n\treturn &DeleteDeploymentInternalServerError{}\n}\n\n\nfunc (o *DeleteDeploymentInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(500)\n}\n\nfunc (o *DeleteDeploymentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\trw.WriteHeader(200)\n}"} {"input": "package dbconnpool\n\nimport (\n\t\"github.com/youtube/vitess/go/mysql\"\n\t\"github.com/youtube/vitess/go/stats\"\n)\n\n\ntype PooledDBConnection struct {\n\t*DBConnection\n\tpool *ConnectionPool\n}\n\n\nfunc (pc *PooledDBConnection) Recycle() {\n\tif pc.IsClosed() {\n\t\tpc.pool.Put(nil)\n\t} else {\n\t\tpc.pool.Put(pc)\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc DBConnectionCreator(info *mysql.ConnectionParams, mysqlStats *stats.Timings) CreateConnectionFunc ", "output": "{\n\treturn func(pool *ConnectionPool) (PoolConnection, error) {\n\t\tc, err := NewDBConnection(info, mysqlStats)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &PooledDBConnection{c, pool}, nil\n\t}\n}"} {"input": "package eventsd\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n\t\"text/tabwriter\"\n\n\t\"github.com/megamsys/libgo/cmd\"\n\t\"github.com/megamsys/libgo/events\"\n\tconstants \"github.com/megamsys/libgo/utils\"\n\t\"github.com/megamsys/vertice/meta\"\n)\n\ntype Config struct {\n\tEnabled bool `toml:\"enabled\"`\n\tMailer Mailer `toml:\"smtp\"`\n\tSlack Slack `toml:\"slack\"`\n\tInfobip Infobip `toml:\"infobip\"`\n\tBillMgr BillMgr `toml:\"bill\"`\n\tAddons Addons `toml:\"addons\"`\n}\n\nfunc NewConfig() *Config {\n\treturn &Config{\n\t\tEnabled: true,\n\t}\n}\n\n\n\nfunc (c Config) toMap() events.EventsConfigMap {\n\tem := make(events.EventsConfigMap)\n\tem[constants.SMTP] = c.Mailer.toMap()\n\tem[constants.SLACK] = c.Slack.toMap()\n\tem[constants.INFOBIP] = c.Infobip.toMap()\n\tem[constants.BILLMGR] = c.BillMgr.toMap()\n\tem[constants.ADDONS] = c.Addons.toMap()\n\tem[constants.META] = meta.MC.ToMap()\n\treturn em\n}\n\nfunc (c Config) String() string ", "output": "{\n\tw := new(tabwriter.Writer)\n\tvar b bytes.Buffer\n\tw.Init(&b, 0, 8, 0, '\\t', 0)\n\tb.Write([]byte(cmd.Colorfy(\"Config:\", \"white\", \"\", \"bold\") + \"\\t\" +\n\t\tcmd.Colorfy(\"Eventsd\", \"cyan\", \"\", \"\") + \"\\n\"))\n\tb.Write([]byte(c.Mailer.String()))\n\tb.Write([]byte(c.Infobip.String()))\n\tb.Write([]byte(c.Slack.String() + \"\\n\"))\n\tb.Write([]byte(c.BillMgr.String() + \"\\n\"))\n\tb.Write([]byte(\"---\\n\"))\n\tfmt.Fprintln(w)\n\tw.Flush()\n\treturn strings.TrimSpace(b.String())\n}"} {"input": "package util\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n)\n\n\n\nfunc LogAsJson(object interface{}) ", "output": "{\n\ttest, _ := json.Marshal(object)\n\tlog.Printf(string(test))\n}"} {"input": "package users\n\nconst (\n\tDefaultUID int = 0\n\tDefaultGID int = 0\n)\n\n\ntype UserLookupper interface {\n\tLookup(rootFsPath string, user string) (*ExecUser, error)\n}\n\ntype LookupFunc func(rootfsPath, user string) (*ExecUser, error)\n\n\n\ntype ExecUser struct {\n\tUid int\n\tGid int\n\tSgids []int\n\tHome string\n}\n\nfunc (fn LookupFunc) Lookup(rootfsPath, user string) (*ExecUser, error) ", "output": "{\n\treturn fn(rootfsPath, user)\n}"} {"input": "package cmd\n\nimport (\n\t\"testing\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n\t\"github.com/jamesnetherton/homehub-cli/service\"\n)\n\n\n\nfunc TestSoftwareVersionCommand(t *testing.T) ", "output": "{\n\tctrl := gomock.NewController(t)\n\tdefer ctrl.Finish()\n\n\thub := NewMockHub(ctrl)\n\tservice.SetHub(hub)\n\tservice.AuthenticationComplete()\n\n\thub.EXPECT().SoftwareVersion().Return(\"Test software version\", nil)\n\n\tAssertCommandOutput(t, NewSoftwareVersionCommand(NewLoginCommand()))\n}"} {"input": "package page\n\nimport (\n\t\"github.com/13pinj/todoapp/Godeps/_workspace/src/github.com/gin-gonic/gin\"\n\t\"github.com/13pinj/todoapp/controllers/todos\"\n\t\"github.com/13pinj/todoapp/controllers/users\"\n\t\"github.com/13pinj/todoapp/models/user\"\n)\n\n\n\n\n\n\nfunc Home(c *gin.Context) ", "output": "{\n\tif _, ok := user.FromContext(c); ok {\n\t\ttodos.Index(c)\n\t} else {\n\t\tusers.LoginForm(c)\n\t}\n}"} {"input": "package git\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/Originate/git-town/src/command\"\n\t\"github.com/Originate/git-town/src/util\"\n)\n\n\n\nfunc EnsureDoesNotHaveConflicts() {\n\tutil.Ensure(!HasConflicts(), \"You must resolve the conflicts before continuing\")\n}\n\n\n\nfunc EnsureDoesNotHaveOpenChanges(message string) {\n\tutil.Ensure(!HasOpenChanges(), \"You have uncommitted changes. \"+message)\n}\n\n\nvar rootDirectory string\n\n\n\nfunc GetRootDirectory() string {\n\tif rootDirectory == \"\" {\n\t\trootDirectory = command.MustRun(\"git\", \"rev-parse\", \"--show-toplevel\").OutputSanitized()\n\t}\n\treturn rootDirectory\n}\n\n\nfunc HasConflicts() bool {\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"Unmerged paths\")\n}\n\n\nfunc HasOpenChanges() bool {\n\treturn command.MustRun(\"git\", \"status\", \"--porcelain\").OutputSanitized() != \"\"\n}\n\n\n\nfunc HasShippableChanges(branchName string) bool {\n\treturn command.MustRun(\"git\", \"diff\", Config().GetMainBranch()+\"..\"+branchName).OutputSanitized() != \"\"\n}\n\n\n\nfunc IsMergeInProgress() bool {\n\t_, err := os.Stat(fmt.Sprintf(\"%s/.git/MERGE_HEAD\", GetRootDirectory()))\n\treturn err == nil\n}\n\n\n\n\n\nfunc IsRebaseInProgress() bool ", "output": "{\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"rebase in progress\")\n}"} {"input": "package ovs\n\nimport (\n\t\"net\"\n\n\t\"github.com/vishvananda/netlink\"\n)\n\ntype bridgeInterface struct {\n\tLink netlink.Link\n\tgatewayIPv4 net.IP\n}\n\n\n\n\n\n\n\nfunc (i *bridgeInterface) exists() bool {\n\treturn i.Link != nil\n}\n\nfunc newInterface(config *networkConfiguration) *bridgeInterface ", "output": "{\n\ti := &bridgeInterface{}\n\n\tif config.BridgeName == \"\" {\n\t\tconfig.BridgeName = DefaultOvsBridgeName\n\t}\n\n\ti.Link, _ = netlink.LinkByName(config.BridgeName)\n\treturn i\n}"} {"input": "package templar\n\nimport \"github.com/stretchr/testify/mock\"\n\nimport \"net/http\"\nimport \"time\"\n\ntype MockStats struct {\n\tmock.Mock\n}\n\n\nfunc (m *MockStats) Emit(req *http.Request, dur time.Duration) {\n\tm.Called(req, dur)\n}\nfunc (m *MockStats) RequestTimeout(req *http.Request, timeout time.Duration) {\n\tm.Called(req, timeout)\n}\n\nfunc (m *MockStats) StartRequest(req *http.Request) ", "output": "{\n\tm.Called(req)\n}"} {"input": "package externalversions\n\nimport (\n\t\"fmt\"\n\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tcache \"k8s.io/client-go/tools/cache\"\n\tv1 \"k8s.io/code-generator/examples/HyphenGroup/apis/example/v1\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}\n\n\nfunc (f *genericInformer) Lister() cache.GenericLister {\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}\n\n\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) ", "output": "{\n\tswitch resource {\n\tcase v1.SchemeGroupVersion.WithResource(\"clustertesttypes\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.ExampleGroup().V1().ClusterTestTypes().Informer()}, nil\n\tcase v1.SchemeGroupVersion.WithResource(\"testtypes\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.ExampleGroup().V1().TestTypes().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}"} {"input": "package lua\n\ntype Metatable struct {\n IndexFunc Function\n NewindexFunc Function\n TostringFunc Function \n GCFunc Function\n}\n\n\n\nfunc (this *Metatable) Newindex() Function {\n return this.NewindexFunc\n}\n\nfunc (this *Metatable) Tostring() Function {\n return this.TostringFunc\n}\n\nfunc (this *Metatable) GC() Function {\n return this.GCFunc\n}\n\nfunc (this *Metatable) Index() Function ", "output": "{\n return this.IndexFunc\n}"} {"input": "package server\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/cri-o/cri-o/oci\"\n\t\"golang.org/x/net/context\"\n\tpb \"k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2\"\n)\n\n\n\n\n\nfunc (s *Server) ContainerStats(ctx context.Context, req *pb.ContainerStatsRequest) (resp *pb.ContainerStatsResponse, err error) {\n\tconst operation = \"container_stats\"\n\tdefer func() {\n\t\trecordOperation(operation, time.Now())\n\t\trecordError(operation, err)\n\t}()\n\n\tcontainer := s.GetContainer(req.ContainerId)\n\tif container == nil {\n\t\treturn nil, fmt.Errorf(\"invalid container\")\n\t}\n\n\tstats, err := s.Runtime().ContainerStats(container)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &pb.ContainerStatsResponse{Stats: buildContainerStats(stats, container)}, nil\n}\n\nfunc buildContainerStats(stats *oci.ContainerStats, container *oci.Container) *pb.ContainerStats ", "output": "{\n\treturn &pb.ContainerStats{\n\t\tAttributes: &pb.ContainerAttributes{\n\t\t\tId: container.ID(),\n\t\t\tMetadata: container.Metadata(),\n\t\t\tLabels: container.Labels(),\n\t\t\tAnnotations: container.Annotations(),\n\t\t},\n\t\tCpu: &pb.CpuUsage{\n\t\t\tTimestamp: stats.SystemNano,\n\t\t\tUsageCoreNanoSeconds: &pb.UInt64Value{Value: stats.CPUNano},\n\t\t},\n\t\tMemory: &pb.MemoryUsage{\n\t\t\tTimestamp: stats.SystemNano,\n\t\t\tWorkingSetBytes: &pb.UInt64Value{Value: stats.MemUsage},\n\t\t},\n\t\tWritableLayer: nil,\n\t}\n}"} {"input": "package mmap\n\nimport \"sync\"\n\ntype tbl struct {\n\tm map[int64][]byte \n\tl sync.RWMutex\n}\n\n\n\nfunc (t *tbl) Get(idx int64, f func() ([]byte, error)) (b []byte, err error) {\n\tt.l.RLock()\n\tb, ok := t.m[idx]\n\tt.l.RUnlock()\n\n\tif ok {\n\t\treturn\n\t}\n\n\tt.l.Lock()\n\tdefer t.l.Unlock()\n\n\tb, ok = t.m[idx]\n\tif ok {\n\t\treturn\n\t}\n\n\tb, err = f()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tt.m[idx] = b\n\treturn\n}\n\nfunc (t *tbl) Values() (res [][]byte) {\n\tt.l.RLock()\n\tfor _, v := range t.m {\n\t\tres = append(res, v)\n\t}\n\tt.l.RUnlock()\n\treturn\n}\n\nfunc newTbl() *tbl ", "output": "{\n\treturn &tbl{m: make(map[int64][]byte)}\n}"} {"input": "package foo\n\n\n\nfunc Foo() int ", "output": "{ return 0 }"} {"input": "package service\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetServiceIDOKCode int = 200\n\n\ntype GetServiceIDOK struct {\n\n\tPayload *models.Service `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetServiceIDOK() *GetServiceIDOK {\n\n\treturn &GetServiceIDOK{}\n}\n\n\n\n\n\nfunc (o *GetServiceIDOK) SetPayload(payload *models.Service) {\n\to.Payload = payload\n}\n\n\nfunc (o *GetServiceIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\n\nconst GetServiceIDNotFoundCode int = 404\n\n\ntype GetServiceIDNotFound struct {\n}\n\n\nfunc NewGetServiceIDNotFound() *GetServiceIDNotFound {\n\n\treturn &GetServiceIDNotFound{}\n}\n\n\nfunc (o *GetServiceIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc (o *GetServiceIDOK) WithPayload(payload *models.Service) *GetServiceIDOK ", "output": "{\n\to.Payload = payload\n\treturn o\n}"} {"input": "package loads\n\nimport \"jvmgo/ch09/instructions/base\"\nimport \"jvmgo/ch09/rtda\"\n\n\ntype ILOAD struct{ base.Index8Instruction }\n\nfunc (self *ILOAD) Execute(frame *rtda.Frame) {\n\t_iload(frame, self.Index)\n}\n\ntype ILOAD_0 struct{ base.NoOperandsInstruction }\n\n\n\ntype ILOAD_1 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_1) Execute(frame *rtda.Frame) {\n\t_iload(frame, 1)\n}\n\ntype ILOAD_2 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_2) Execute(frame *rtda.Frame) {\n\t_iload(frame, 2)\n}\n\ntype ILOAD_3 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_3) Execute(frame *rtda.Frame) {\n\t_iload(frame, 3)\n}\n\nfunc _iload(frame *rtda.Frame, index uint) {\n\tval := frame.LocalVars().GetInt(index)\n\tframe.OperandStack().PushInt(val)\n}\n\nfunc (self *ILOAD_0) Execute(frame *rtda.Frame) ", "output": "{\n\t_iload(frame, 0)\n}"} {"input": "package tcp\n\nimport (\n\t\"flag\"\n\t\"net\"\n\t\"os\"\n\t\"bufio\"\n\t\"time\"\n\t\"log\"\n)\n\n\nfunc readFromClient(conn net.Conn) {\n\treader := bufio.NewReader(conn)\n\tfor {\n\t\tlog.Println(\"receiving...\")\n\t\tline, isPrefix, err := reader.ReadLine()\n\t\tif err != nil {\n\t\t\tlog.Print(\"Error to read message because of \", err)\n\t\t\treturn\n\t\t} else {\n\t\t\tlog.Println(\"receive:\", string(line))\n\t\t\tlog.Println(\"isPrefix:\", isPrefix)\n\t\t}\n\n\t}\n}\nfunc writeToClient(conn net.Conn) {\n\tdefer conn.Close()\n\tfor {\n\t\t_, err := conn.Write([]byte(\"hello client.\\r\\n\"))\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error to send message because of \", err.Error())\n\t\t\treturn\n\t\t}\n\t\tlog.Println(\"sent hello to client.\")\n\t\ttime.Sleep(time.Second)\n\t}\n\n}\n\nfunc DefaultServer() ", "output": "{\n\n\tvar address = flag.String(\"address\", \":6789\", \"server address host:port\")\n\tflag.Parse()\n\n\tlistener, err := net.Listen(\"tcp4\", *address)\n\tif err != nil {\n\t\tlog.Println(\"Error listening:\", err)\n\t\tos.Exit(1)\n\t}\n\n\tdefer listener.Close()\n\n\tlog.Println(\"Listening on \" + *address)\n\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error accepting: \", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tlog.Printf(\"Received message %s -> %s \\n\", conn.RemoteAddr(), conn.LocalAddr())\n\t\tgo readFromClient(conn)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n\n\t\"github.com/couchbase/sync_gateway/rest\"\n)\n\n\n\n\nfunc main() {\n\trest.ServerMain()\n}\n\nfunc init() ", "output": "{\n\trand.Seed(time.Now().UTC().UnixNano())\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\n\t\"github.com/gambol99/rbd-fence/pkg/rbd\"\n\n\t\"github.com/golang/glog\"\n)\n\nvar config struct {\n\taddress string\n}\n\n\n\nfunc main() {\n\tflag.Parse()\n\tif config.address == \"\" {\n\t\tglog.Errorf(\"You have not specified the ip address of the client to remove lock ownership\")\n\t\tos.Exit(1)\n\t}\n\n\tclient, err := rbd.NewRBDInterface()\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to create a client interface for rbd, error: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\terr = client.UnlockClient(config.address)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to unlock the images held by %s\", config.address)\n\t\tos.Exit(1)\n\t}\n\n\tglog.Infof(\"Successfully remove any locks\")\n}\n\nfunc init() ", "output": "{\n\tflag.StringVar(&config.address, \"ip\", \"\", \"the ip address of the client which you wish to unlock\")\n}"} {"input": "package main\n\ntype CharacterLiteral struct {\n\tAddress string\n\tPosition string\n\tType string\n\tValue int\n\tChildren []interface{}\n}\n\n\n\nfunc parseCharacterLiteral(line string) *CharacterLiteral ", "output": "{\n\tgroups := groupsFromRegex(\n\t\t\"<(?P.*)> '(?P.*?)' (?P\\\\d+)\",\n\t\tline,\n\t)\n\n\treturn &CharacterLiteral{\n\t\tAddress: groups[\"address\"],\n\t\tPosition: groups[\"position\"],\n\t\tType: groups[\"type\"],\n\t\tValue: atoi(groups[\"value\"]),\n\t\tChildren: []interface{}{},\n\t}\n}"} {"input": "package ipv4_test\n\n\n\nfunc protocolNotSupported(err error) bool ", "output": "{\n\treturn false\n}"} {"input": "package main\n\nimport (\n\t\"github.com/jjyr/ringo\"\n\t\"github.com/jjyr/ringo/middleware\"\n)\n\n\n\ntype user struct {\n\tName string `json:\"name\" validate:\"required\"`\n}\n\nvar users []user\n\n\ntype Users struct {\n\tringo.Controller\n}\n\nfunc (_ *Users) Get(c ringo.Context) {\n\tc.JSON(200, ringo.H{\"users\": users})\n}\n\nfunc (ctl *Users) Post(c ringo.Context) {\n\tu := user{}\n\tif err := c.BindJSON(&u); err == nil {\n\t\tusers = append(users, u)\n\t\tc.JSON(200, u)\n\t} else {\n\t\tc.JSON(400, ringo.H{\"message\": \"format error\"})\n\t}\n}\n\n\n\ntype User struct {\n\tringo.Controller\n}\n\nfunc (ctl *User) Delete(c ringo.Context) {\n\tidx := -1\n\tname := c.Params().ByName(\"id\")\n\tfor i, u := range users {\n\t\tif name == u.Name {\n\t\t\tidx = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif idx >= 0 {\n\t\tusers = append(users[:idx], users[idx+1:]...)\n\t\tc.JSON(200, ringo.H{\"message\": \"ok\"})\n\t} else {\n\t\tc.JSON(404, ringo.H{\"message\": \"not found\"})\n\t}\n}\n\nfunc main() {\n\tapp := ringo.NewApp()\n\n\tapp.Add(\"/users\", &Users{})\n\tapp.GET(\"/users-list\", DisplayList)\n\tapp.Add(\"/user/:id\", &User{})\n\tapp.Use(middleware.Recover())\n\tapp.SetTemplatePath(\"templates\")\n\tapp.Run(\"localhost:8000\")\n}\n\nfunc DisplayList(c ringo.Context) ", "output": "{\n\tc.HTML(200, \"list.html\", users)\n}"} {"input": "package operator\n\nimport (\n\t\"testing\"\n\n\t\"github.com/rook/rook/pkg/operator/test\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\n\n\ntype testTPR struct {\n}\n\nfunc (t *testTPR) Name() string {\n\treturn \"test\"\n}\nfunc (t *testTPR) Description() string {\n\treturn \"test description\"\n}\nfunc (t *testTPR) Load() error {\n\treturn nil\n}\nfunc (t *testTPR) Watch() error {\n\treturn nil\n}\n\nfunc TestCreateCluster(t *testing.T) ", "output": "{\n\tclientset := test.New(3)\n\to := New(\"foo\", nil, clientset)\n\to.context.RetryDelay = 1\n\n\terr := o.initResources()\n\tassert.NotNil(t, err)\n\n\ttest := &testTPR{}\n\terr = createTPR(o.context, test)\n\tassert.Nil(t, err)\n\ttpr, err := clientset.ExtensionsV1beta1().ThirdPartyResources().List(v1.ListOptions{})\n\tassert.Nil(t, err)\n\tassert.Equal(t, 1, len(tpr.Items))\n\tassert.Equal(t, \"test.rook.io\", tpr.Items[0].Name)\n\tassert.Equal(t, test.Description(), tpr.Items[0].Description)\n\n}"} {"input": "package debug\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nfunc BenchmarkLogging(b *testing.B) {\n\tos.Setenv(\"GOPASS_DEBUG\", \"true\")\n\tdefer func() { os.Unsetenv(\"GOPASS_DEBUG\") }()\n\tinitDebug()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tLog(\"string\")\n\t}\n}\n\n\n\nfunc BenchmarkNoLogging(b *testing.B) ", "output": "{\n\tos.Unsetenv(\"GOPASS_DEBUG\")\n\tinitDebug()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tLog(\"string\")\n\t}\n}"} {"input": "package scenery\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n)\n\ntype LibraryEnumerator func(path string, ref interface{})\n\ntype lookupRegInfo struct {\n\tenumerator LibraryEnumerator\n\tref interface{}\n}\n\n\n\n\nfunc LookupObjects(path string, lat, lon float32, enumerator LibraryEnumerator, ref interface{}) int {\n\tcPath := C.CString(path)\n\tdefer C.free(unsafe.Pointer(cPath))\n\tregInfo := &lookupRegInfo{enumerator, ref}\n\treturn int(C.XPLMLookupObjects(cPath, C.float(lat), C.float(lon), C.XPLMLibraryEnumerator_f(unsafe.Pointer(C.lookupObjectsEnum)), unsafe.Pointer(regInfo)))\n}\n\nfunc lookupObjectsEnum(cPath *C.char, ref unsafe.Pointer) ", "output": "{\n\tregInfo := (*lookupRegInfo)(ref)\n\tregInfo.enumerator(C.GoString(cPath), regInfo.ref)\n}"} {"input": "package cache\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"time\"\n)\n\ntype Cache struct {\n\tmemoryCache map[string][]byte\n\trefreshTime int\n}\n\nfunc NewCache(t int) *Cache {\n\treturn &Cache{\n\t\tmemoryCache: make(map[string][]byte),\n\t\trefreshTime: t,\n\t}\n}\n\nfunc (c *Cache) SetCache(name string, data []byte) error {\n\terr := ioutil.WriteFile(\"/tmp/\"+name, data, 0644)\n\tif err == nil {\n\t\tc.memoryCache[name] = data\n\t}\n\treturn err\n}\n\n\n\nfunc (c *Cache) GetCache(name string) ([]byte, error) ", "output": "{\n\tif dat, ok := c.memoryCache[name]; ok {\n\t\treturn dat, nil\n\t}\n\n\tf, err := os.Stat(\"/tmp/\" + name)\n\tif os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\n\tif time.Since(f.ModTime()).Minutes() > float64(c.refreshTime) {\n\t\treturn nil, fmt.Errorf(\"[GetCache] %s\", \"cache invalidate\")\n\t}\n\n\tdat, err := ioutil.ReadFile(\"/tmp/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dat, nil\n}"} {"input": "package ini\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/mono83/cfg\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"strings\"\n)\n\nvar nlByte = []byte{0x0a}\n\n\n\nfunc NewReaderSource(source io.Reader) (cfg.Configurer, error) {\n\tbts, err := ioutil.ReadAll(source)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewBytesSource(bts)\n}\n\n\n\nfunc NewStringSource(source string) (cfg.Configurer, error) {\n\treturn NewBytesSource([]byte(source))\n}\n\n\n\n\n\nfunc NewBytesSource(source []byte) (cfg.Configurer, error) ", "output": "{\n\tif len(source) == 0 {\n\t\treturn nil, errors.New(\"Empty INI source\")\n\t}\n\n\tsrc := map[string]interface{}{}\n\tfor _, bline := range bytes.Split(source, nlByte) {\n\t\tline := strings.TrimSpace(string(bline))\n\t\tif len(line) == 0 || line[0] == '#' || line[0] == '/' || line[0] == '[' {\n\t\t\tcontinue\n\t\t}\n\n\t\tpos := strings.IndexRune(line, '=')\n\t\tif pos == -1 {\n\t\t\treturn nil, fmt.Errorf(\"Unable to parse line %s\", line)\n\t\t}\n\n\t\tkey := strings.TrimSpace(line[0:pos])\n\t\tvalue := strings.TrimSpace(line[pos+1:])\n\n\t\tsrc[key] = value\n\t}\n\n\treturn cfg.Map(src), nil\n}"} {"input": "package hbase\n\nimport (\n\tpb \"github.com/insionng/yougam/libraries/golang/protobuf/proto\"\n\t\"github.com/insionng/yougam/libraries/pingcap/go-hbase/proto\"\n)\n\ntype CoprocessorServiceCall struct {\n\tRow []byte\n\tServiceName string\n\tMethodName string\n\tRequestParam []byte\n}\n\n\n\nfunc (c *CoprocessorServiceCall) ToProto() pb.Message ", "output": "{\n\treturn &proto.CoprocessorServiceCall{\n\t\tRow: c.Row,\n\t\tServiceName: pb.String(c.ServiceName),\n\t\tMethodName: pb.String(c.MethodName),\n\t\tRequest: c.RequestParam,\n\t}\n}"} {"input": "package tartest\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\tupTar \"archive/tar\"\n\n\tourTar \"github.com/vbatts/tar-split/archive/tar\"\n)\n\nvar testfile = \"./archive/tar/testdata/sparse-formats.tar\"\n\nfunc BenchmarkUpstreamTar(b *testing.B) {\n\tfor n := 0; n < b.N; n++ {\n\t\tfh, err := os.Open(testfile)\n\t\tif err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t\ttr := upTar.NewReader(fh)\n\t\tfor {\n\t\t\t_, err := tr.Next()\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfh.Close()\n\t\t\t\tb.Fatal(err)\n\t\t\t}\n\t\t\tio.Copy(ioutil.Discard, tr)\n\t\t}\n\t\tfh.Close()\n\t}\n}\n\nfunc BenchmarkOurTarNoAccounting(b *testing.B) {\n\tfor n := 0; n < b.N; n++ {\n\t\tfh, err := os.Open(testfile)\n\t\tif err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t\ttr := ourTar.NewReader(fh)\n\t\ttr.RawAccounting = false \n\t\tfor {\n\t\t\t_, err := tr.Next()\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfh.Close()\n\t\t\t\tb.Fatal(err)\n\t\t\t}\n\t\t\tio.Copy(ioutil.Discard, tr)\n\t\t}\n\t\tfh.Close()\n\t}\n}\n\n\nfunc BenchmarkOurTarYesAccounting(b *testing.B) ", "output": "{\n\tfor n := 0; n < b.N; n++ {\n\t\tfh, err := os.Open(testfile)\n\t\tif err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t\ttr := ourTar.NewReader(fh)\n\t\ttr.RawAccounting = true \n\t\tfor {\n\t\t\t_ = tr.RawBytes()\n\t\t\t_, err := tr.Next()\n\t\t\t_ = tr.RawBytes()\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfh.Close()\n\t\t\t\tb.Fatal(err)\n\t\t\t}\n\t\t\tio.Copy(ioutil.Discard, tr)\n\t\t\t_ = tr.RawBytes()\n\t\t}\n\t\tfh.Close()\n\t}\n}"} {"input": "package codec\n\nimport (\n\t\"fmt\"\n\t\"github.com/davyxu/cellnet\"\n)\n\nvar registedCodecs []cellnet.Codec\n\n\n\n\n\nfunc GetCodec(name string) cellnet.Codec {\n\n\tfor _, c := range registedCodecs {\n\t\tif c.Name() == name {\n\t\t\treturn c\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\nfunc getPackageByCodecName(name string) string {\n\tswitch name {\n\tcase \"binary\":\n\t\treturn \"github.com/davyxu/cellnet/codec/binary\"\n\tcase \"gogopb\":\n\t\treturn \"github.com/davyxu/cellnet/codec/gogopb\"\n\tcase \"httpjson\":\n\t\treturn \"github.com/davyxu/cellnet/codec/httpjson\"\n\tcase \"json\":\n\t\treturn \"github.com/davyxu/cellnet/codec/json\"\n\tcase \"protoplus\":\n\t\treturn \"github.com/davyxu/cellnet/codec/protoplus\"\n\tdefault:\n\t\treturn \"package/to/your/codec\"\n\t}\n}\n\n\nfunc MustGetCodec(name string) cellnet.Codec {\n\tcodec := GetCodec(name)\n\n\tif codec == nil {\n\t\tpanic(fmt.Sprintf(\"codec not found '%s'\\ntry to add code below:\\nimport (\\n _ \\\"%s\\\"\\n)\\n\\n\",\n\t\t\tname,\n\t\t\tgetPackageByCodecName(name)))\n\t}\n\n\treturn codec\n}\n\nfunc RegisterCodec(c cellnet.Codec) ", "output": "{\n\n\tif GetCodec(c.Name()) != nil {\n\t\tpanic(\"duplicate codec: \" + c.Name())\n\t}\n\n\tregistedCodecs = append(registedCodecs, c)\n}"} {"input": "package cli\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/antham/goller/v2/dsl\"\n\t\"github.com/antham/goller/v2/sorter\"\n\t\"gopkg.in/alecthomas/kingpin.v2\"\n)\n\nvar sortersGlobal *sorter.Sorters\n\n\ntype Sorters struct {\n\tsorters *sorter.Sorters\n}\n\n\nfunc (s *Sorters) Init() {\n\tsortersGlobal = sorter.NewSorters()\n}\n\n\nfunc (s *Sorters) Set(value string) error {\n\tparser := dsl.NewParser(bytes.NewBufferString(value))\n\n\tstmts, err := parser.ParsePositionsAndFunctions()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t(*s).sorters = sortersGlobal\n\n\tfor _, stmt := range *stmts {\n\t\t(*s).sorters.Append(stmt.Position, stmt.Functions[0].Name, stmt.Functions[0].Args)\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc (s *Sorters) Get() *sorter.Sorters {\n\treturn s.sorters\n}\n\n\nfunc (s *Sorters) String() string {\n\treturn \"\"\n}\n\n\nfunc SortersWrapper(s kingpin.Settings) (target *Sorters) {\n\ttarget = &Sorters{}\n\ttarget.Init()\n\ts.SetValue(target)\n\treturn\n}\n\nfunc (s *Sorters) ValidatePositions(positions *[]int) error ", "output": "{\n\tif s.sorters == nil {\n\t\treturn nil\n\t}\n\n\tfor _, sorter := range *s.sorters {\n\t\tpositionMatch := false\n\n\t\tfor _, position := range *positions {\n\t\t\tif sorter.HasPosition(position) {\n\t\t\t\tpositionMatch = true\n\t\t\t}\n\t\t}\n\n\t\tif !positionMatch {\n\t\t\treturn fmt.Errorf(\"Sort is wrong : position %d doesn't exist\", sorter.GetPosition())\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package signal\n\nimport (\n\t\"github.com/idealeak/goserver/core\"\n)\n\nvar Config = Configuration{}\n\ntype Configuration struct {\n\tSupportSignal bool\n}\n\n\n\nfunc (c *Configuration) Init() error {\n\tif c.SupportSignal {\n\t\tgo SignalHandlerModule.ProcessSignal()\n\t}\n\treturn nil\n}\n\nfunc (c *Configuration) Close() error {\n\treturn nil\n}\n\nfunc init() {\n\tcore.RegistePackage(&Config)\n}\n\nfunc (c *Configuration) Name() string ", "output": "{\n\treturn \"signal\"\n}"} {"input": "package joltDB\n\nimport (\n\t\"github.com/boltdb/bolt\"\n)\n\nvar boltdbr *bolt.DB\nvar dbr = apiConn(boltdbr)\n\nfunc OpenReadOnly(dir string) error {\n\treturn dbr.apiOpenReadOnly(dir)\n}\n\nfunc CloseReadOnly() {\n\tdbr.apiClose()\n}\n\n\n\nfunc ListPrefixReadOnly(bucket, prefix string) ([]byte, error) {\n\treturn dbrw.apiListPrefix(bucket, prefix)\n}\n\nfunc ListRangeReadOnly(bucket, start, stop string) ([]byte, error) {\n\treturn dbrw.apiListRange(bucket, start, stop)\n}\n\nfunc GetOneReadOnly(bucket, key string) ([]byte, error) {\n\treturn dbr.apiGetOne(bucket, key)\n}\n\nfunc ListReadOnly(bucket string) ([]byte, error) ", "output": "{\n\treturn dbr.apiList(bucket)\n}"} {"input": "package command\n\nimport (\n\t\"github.com/mitchellh/cli\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestSubCommandRun(t *testing.T) {\n\n\tui := new(cli.MockUi)\n\tc := &SubCommand{UI: ui}\n\targs := []string{\"key=val\"}\n\n\tcode := c.Run(args)\n\tif code != 0 {\n\t\tt.Fatalf(\"bad: %d. %#v\", code, ui.ErrorWriter.String())\n\t}\n\n\tif !strings.Contains(ui.OutputWriter.String(), \"Subcommand Complete\") {\n\t\tt.Fatalf(\"bad: %#v\", ui.OutputWriter.String())\n\t}\n}\n\nfunc TestSubCommand_implements(t *testing.T) ", "output": "{\n\tvar _ cli.Command = &SubCommand{}\n}"} {"input": "package source\n\n\n\n\ntype AssertionStatement struct {\n\tfields AssertionFields\n\tsource Code\n}\n\ntype AssertionFields struct {\n\tOwner string \n\tCalled string \n\tOptions \n}\n\n\nfunc (ts AssertionStatement) Fields() AssertionFields {\n\treturn ts.fields\n}\n\n\n\n\nfunc (ts AssertionStatement) Source() Code ", "output": "{\n\treturn ts.source\n}"} {"input": "package MapTo\n\nimport (\n\t_ \"github.com/reactivego/rx\"\n)\n\n\n\nfunc Example_mapToString() ", "output": "{\n\tFromInt(1, 2, 3, 4).MapToString(\"YES\").Println()\n\n}"} {"input": "package solution\n\nconst (\n\tland = '1'\n\twater = '0'\n)\n\ntype point struct {\n\tx, y int\n}\n\n\n\nfunc numIslands(grid [][]byte) int {\n\theight := len(grid)\n\tif height == 0 {\n\t\treturn 0\n\t}\n\twidth := len(grid[0])\n\n\tseen := make([][]bool, height)\n\tfor y := 0; y < height; y++ {\n\t\tseen[y] = make([]bool, width)\n\t}\n\n\texplore := func(origin point) {\n\t\tstack := []point{origin}\n\t\tfor len(stack) > 0 {\n\t\t\ttop := len(stack) - 1\n\t\t\tp := stack[top]\n\t\t\tstack = stack[:top]\n\n\t\t\tseen[p.y][p.x] = true\n\n\t\t\tfor _, n := range p.neighbors() {\n\t\t\t\tif n.x < 0 || n.x >= width || n.y < 0 || n.y >= height {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif !seen[n.y][n.x] && grid[n.y][n.x] == land {\n\t\t\t\t\tstack = append(stack, n)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tn := 0\n\tfor y := 0; y < height; y++ {\n\t\tfor x := 0; x < width; x++ {\n\t\t\tif !seen[y][x] && grid[y][x] == land {\n\t\t\t\tn++\n\t\t\t\texplore(point{x, y})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn n\n}\n\nfunc (p point) neighbors() []point ", "output": "{\n\treturn []point{\n\t\t{p.x - 1, p.y},\n\t\t{p.x + 1, p.y},\n\t\t{p.x, p.y - 1},\n\t\t{p.x, p.y + 1},\n\t}\n}"} {"input": "package gitea\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\n\ntype PublicKey struct {\n\tID int64 `json:\"id\"`\n\tKey string `json:\"key\"`\n\tURL string `json:\"url,omitempty\"`\n\tTitle string `json:\"title,omitempty\"`\n\tCreated time.Time `json:\"created_at,omitempty\"`\n}\n\n\nfunc (c *Client) ListPublicKeys(user string) ([]*PublicKey, error) {\n\tkeys := make([]*PublicKey, 0, 10)\n\treturn keys, c.getParsedResponse(\"GET\", fmt.Sprintf(\"/users/%s/keys\", user), nil, nil, &keys)\n}\n\n\n\n\n\nfunc (c *Client) GetPublicKey(keyID int64) (*PublicKey, error) {\n\tkey := new(PublicKey)\n\treturn key, c.getParsedResponse(\"GET\", fmt.Sprintf(\"/user/keys/%d\", keyID), nil, nil, &key)\n}\n\n\nfunc (c *Client) CreatePublicKey(opt CreateKeyOption) (*PublicKey, error) {\n\tbody, err := json.Marshal(&opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkey := new(PublicKey)\n\treturn key, c.getParsedResponse(\"POST\", \"/user/keys\", jsonHeader, bytes.NewReader(body), key)\n}\n\n\nfunc (c *Client) DeletePublicKey(keyID int64) error {\n\t_, err := c.getResponse(\"DELETE\", fmt.Sprintf(\"/user/keys/%d\", keyID), nil, nil)\n\treturn err\n}\n\nfunc (c *Client) ListMyPublicKeys() ([]*PublicKey, error) ", "output": "{\n\tkeys := make([]*PublicKey, 0, 10)\n\treturn keys, c.getParsedResponse(\"GET\", \"/user/keys\", nil, nil, &keys)\n}"} {"input": "package cmake\n\nimport (\n\t\"github.com/pinpt/dialect/pkg/types\"\n\t\"strings\"\n)\n\ntype CMakeExaminer struct {\n\tinDoubleComment bool\n}\n\n\n\nfunc (e *CMakeExaminer) NewExaminer() types.DialectExaminer {\n\tex := new(CMakeExaminer)\n\treturn ex\n}\n\nfunc init() {\n\ttypes.RegisterExaminer(\"CMake\", &CMakeExaminer{})\n}\n\nfunc (e *CMakeExaminer) Examine(language string, filename string, line *types.DialectLine) error ", "output": "{\n\tlineBuf := strings.TrimSpace(line.Contents)\n\tif strings.HasPrefix(lineBuf, \"# \") {\n\t\tline.IsComment = true\n\t} else {\n\t\tline.IsCode = true\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/robfig/cron\"\n)\n\ntype Sync struct{}\n\nfunc (s *Sync) Help() string {\n\treturn \"glr sync Help\"\n}\n\nfunc (s *Sync) Run(args []string) int {\n\t_, err := SyncRepository()\n\n\tif err != nil {\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n\nfunc (s *Sync) Synopsis() string {\n\treturn \"Synchronize local git repository with remote at once\"\n}\n\n\ntype status struct {\n\tc *cron.Cron\n\trepositories []string\n\tschedules []string\n}\n\nvar sharedStatus *status = newStatus()\n\nfunc newStatus() *status {\n\treturn &status{\n\t\tc: cron.New(),\n\t}\n}\n\n\nfunc GetStatus() *status {\n\treturn sharedStatus\n}\n\ntype StatusStart struct{}\n\nfunc (s *StatusStart) Help() string {\n\treturn \"glr status start Help\"\n}\n\nfunc (s *StatusStart) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.AddFunc(\"@hourly\", func() {\n\t\tSyncRepository()\n\t})\n\tfmt.Println(\"set job schedule\")\n\tstatus.c.Start()\n\n\treturn 0\n}\n\nfunc (s *StatusStart) Synopsis() string {\n\treturn \"Synchronize local git repository with remote\"\n}\n\ntype StatusStop struct{}\n\n\n\nfunc (s *StatusStop) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.Stop()\n\tfmt.Println(\"stop job scheduler\")\n\n\treturn 0\n}\n\nfunc (s *StatusStop) Synopsis() string {\n\treturn \"Stop cron scheduler\"\n}\n\nfunc (s *StatusStop) Help() string ", "output": "{\n\treturn \"glr status stop Help\"\n}"} {"input": "package monitor\n\nimport (\n\t\"fmt\"\n)\n\nvar (\n\tregisteredWatchers = make(map[string]func() Watcher)\n)\n\n\ntype Watcher interface {\n\tInit(Context)\n\tRun()\n}\n\ntype Setter interface {\n\tSet(key string)\n}\n\n\n\nfunc RegisterWatcher(name string, factory func() Watcher) ", "output": "{\n\tif _, present := registeredWatchers[name]; present {\n\t\tpanic(fmt.Sprintf(\"watcher[%s] cannot register twice\", name))\n\t}\n\n\tregisteredWatchers[name] = factory\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nvar v string = \"v1.0\"\n\ntype Middleware struct {\n\tName string\n}\n\n\n\nfunc main() {\n\tm := &Middleware{\"Test\"}\n\thttp.HandleFunc(\"/\", m.Handler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc (m *Middleware) Handler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tlog.Println(r.Header.Get(\"User-Agent\"))\n\tw.Header().Set(\"test\", \"ok\")\n\tlog.Println(w.Header())\n\tfmt.Fprintln(w, \"Welcome to my website\", m.Name)\n}"} {"input": "package tpu\n\nimport (\n\t\"strings\"\n\n\tapiv1 \"k8s.io/api/core/v1\"\n)\n\nconst (\n\tResourceTPUPrefix = \"cloud-tpus.google.com/\"\n)\n\nfunc hasTPURequest(pod *apiv1.Pod) bool {\n\tfor _, container := range pod.Spec.Containers {\n\t\tfor name := range container.Resources.Requests {\n\t\t\tif strings.HasPrefix(string(name), ResourceTPUPrefix) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\n\n\n\n\nfunc ClearTPURequests(pods []*apiv1.Pod) []*apiv1.Pod {\n\tpodsWithTPU := make(map[int]*apiv1.Pod)\n\tfor i, pod := range pods {\n\t\tif hasTPURequest(pod) {\n\t\t\tpodsWithTPU[i] = clearTPURequest(pod)\n\t\t}\n\t}\n\n\tif len(podsWithTPU) == 0 {\n\t\treturn pods\n\t}\n\n\tsanitizedPods := make([]*apiv1.Pod, len(pods))\n\tfor i, pod := range pods {\n\t\tif sanitized, found := podsWithTPU[i]; found {\n\t\t\tsanitizedPods[i] = sanitized\n\t\t} else {\n\t\t\tsanitizedPods[i] = pod\n\t\t}\n\t}\n\treturn sanitizedPods\n}\n\nfunc clearTPURequest(pod *apiv1.Pod) *apiv1.Pod ", "output": "{\n\tsanitized := pod.DeepCopy()\n\tfor _, container := range sanitized.Spec.Containers {\n\t\tfor name := range container.Resources.Requests {\n\t\t\tif strings.HasPrefix(string(name), ResourceTPUPrefix) {\n\t\t\t\tdelete(container.Resources.Requests, name)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn sanitized\n}"} {"input": "package main\n\nimport (\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/rakyll/statik/fs\"\n\n\t_ \"github.com/reviewdog/reviewdog/doghouse/appengine/statik\"\n)\n\nvar tmplFiles http.FileSystem\n\nfunc mustParseTemplatesFiles(filenames ...string) *template.Template {\n\tt, err := parseTemplatesFiles(filenames...)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn t\n}\n\nfunc parseTemplatesFiles(filenames ...string) (*template.Template, error) {\n\tvar t *template.Template\n\tfor _, filename := range filenames {\n\t\tif t == nil {\n\t\t\tt = template.New(filename)\n\t\t}\n\t\ttext, err := fs.ReadFile(tmplFiles, filename)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tt, err = t.Parse(string(text))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn t, nil\n}\n\nvar (\n\ttopTmpl *template.Template\n\tghTopTmpl *template.Template\n\tghRepoTmpl *template.Template\n)\n\n\n\nfunc initTemplates() ", "output": "{\n\tvar err error\n\ttmplFiles, err = fs.New()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttopTmpl = mustParseTemplatesFiles(\n\t\t\"/base.html\",\n\t\t\"/index.html\",\n\t)\n\n\tghTopTmpl = mustParseTemplatesFiles(\n\t\t\"/gh/base.html\",\n\t\t\"/gh/header.html\",\n\t\t\"/gh/top.html\",\n\t)\n\n\tghRepoTmpl = mustParseTemplatesFiles(\n\t\t\"/gh/base.html\",\n\t\t\"/gh/header.html\",\n\t\t\"/gh/repo.html\",\n\t)\n}"} {"input": "package appclient\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"github.com/weaveworks/scope/report\"\n)\n\n\n\ntype ReportPublisher struct {\n\tpublisher Publisher\n\tnoControls bool\n}\n\n\nfunc NewReportPublisher(publisher Publisher, noControls bool) *ReportPublisher {\n\treturn &ReportPublisher{\n\t\tpublisher: publisher,\n\t\tnoControls: noControls,\n\t}\n}\n\n\n\n\nfunc (p *ReportPublisher) Publish(r report.Report) error ", "output": "{\n\tif p.noControls {\n\t\tr.WalkTopologies(func(t *report.Topology) {\n\t\t\tt.Controls = report.Controls{}\n\t\t})\n\t}\n\tbuf := &bytes.Buffer{}\n\tr.WriteBinary(buf, gzip.DefaultCompression)\n\treturn p.publisher.Publish(buf, r.Shortcut)\n}"} {"input": "package v1\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\n\t\"ChineseChess/server/daf\"\n\t\"ChineseChess/server/models\"\n\t. \"ChineseChess/server/routers/render\"\n)\n\ntype userForm struct {\n\tUsername string `json:\"username\"`\n\tNick string `json:\"nick\"`\n\tPassword string `json:\"password\"`\n}\n\n\n\n\nfunc CreateUser(c *gin.Context) ", "output": "{\n\n\tform := new(userForm)\n\tif err := c.BindJSON(form); err != nil {\n\t\tRenderErr(c, err, 400)\n\t\treturn\n\t}\n\tuser := models.NewUser()\n\tuser.Username = form.Username\n\tuser.Nick = form.Nick\n\tuser.Password = form.Password\n\tif err := daf.Insert(user); err != nil {\n\t\tRenderErr(c, err)\n\t\treturn\n\t}\n\tRenderOk(c)\n}"} {"input": "package log\n\nimport (\n\t. \"github.com/limetext/lime-backend/lib/util\"\n\t\"github.com/limetext/log4go\"\n\t\"sync\"\n)\n\ntype (\n\tLogWriter interface {\n\t\tlog4go.LogWriter\n\t}\n\n\tlogWriter struct {\n\t\tLogWriter\n\t\tlog chan string\n\t\thandler func(string)\n\t\tlock sync.Mutex\n\t}\n)\n\nfunc NewLogWriter(h func(string)) *logWriter {\n\tret := &logWriter{\n\t\tlog: make(chan string, 100),\n\t\thandler: h,\n\t}\n\tgo ret.handle()\n\treturn ret\n}\n\nfunc (l *logWriter) handle() {\n\tfor fl := range l.log {\n\t\tl.handler(fl)\n\t}\n}\n\n\n\nfunc (l *logWriter) LogWrite(rec *log4go.LogRecord) {\n\tp := Prof.Enter(\"log\")\n\tdefer p.Exit()\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\tfl := log4go.FormatLogRecord(log4go.FORMAT_DEFAULT, rec)\n\tl.log <- fl\n}\n\n\n\nfunc (l *logWriter) Close() ", "output": "{\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\tclose(l.log)\n}"} {"input": "package gonion\n\nimport (\n\t\"net/http\"\n)\n\n\n\ntype MiddlewareOptions struct {\n\tcomposer *Composer\n\trouteFilter func(*RouteModel) bool\n}\n\n\n\nfunc (mo *MiddlewareOptions) ChainLink(ctor func(http.Handler) http.Handler) {\n\tmo.composer.addMiddleware(ChainLink(ctor), mo.routeFilter)\n}\n\nfunc wrap(handler http.Handler) ChainLink {\n\treturn ChainLink(func(inner http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {\n\t\t\thandler.ServeHTTP(rw, r)\n\t\t\tinner.ServeHTTP(rw, r)\n\t\t})\n\t})\n}\n\n\n\n\n\n\nfunc (mo *MiddlewareOptions) Func(handler func(http.ResponseWriter, *http.Request)) {\n\tmo.Handler(http.HandlerFunc(handler))\n}\n\nfunc (mo *MiddlewareOptions) Handler(handler http.Handler) ", "output": "{\n\tmo.composer.addMiddleware(wrap(handler), mo.routeFilter)\n}"} {"input": "package rpc\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n)\n\n\n\ntype NetrpcBinding struct {\n\tCtx context.Context \n\tendpoint.Endpoint\n}\n\ntype RequestT struct{}\ntype ResponseT struct{}\n\n\n\n\nfunc (b NetrpcBinding) FunT(request RequestT, response *ResponseT) error ", "output": "{\n\tvar (\n\t\tctx, cancel = context.WithCancel(b.Ctx)\n\t\terrs = make(chan error, 1)\n\t\tresponses = make(chan ResponseT, 1)\n\t)\n\tdefer cancel()\n\tgo func() {\n\t\trawResp, err := b.Endpoint(ctx, request)\n\t\tif err != nil {\n\t\t\terrs <- err\n\t\t\treturn\n\t\t}\n\t\tresp, ok := rawResp.(ResponseT)\n\t\tif !ok {\n\t\t\terrs <- endpoint.ErrBadCast\n\t\t\treturn\n\t\t}\n\t\tresponses <- resp\n\t}()\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn context.DeadlineExceeded\n\tcase err := <-errs:\n\t\treturn err\n\tcase resp := <-responses:\n\t\t(*response) = resp\n\t\treturn nil\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\n\ntype Bitcoin int\n\ntype Wallet struct {\n\tbalance Bitcoin\n}\n\nfunc (b Bitcoin) String() string {\n\treturn fmt.Sprintf(\"%d BTC\", b)\n}\nfunc (w *Wallet) Deposit(amount Bitcoin) {\n\tw.balance += amount\n}\n\nfunc (w *Wallet) Balance() Bitcoin {\n\treturn w.balance\n}\n\n\n\nfunc main() {\n\tname := \"sss\"\n\tfmt.Println(name)\n}\n\nfunc (w *Wallet) Withdraw(amount Bitcoin) ", "output": "{\n\tw.balance -= amount\n}"} {"input": "package lg\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Stopwatch struct {\n\tstart, stop time.Time\n\tlogger *Logger\n}\n\n\nfunc (s *Stopwatch) Stop() {\n\ts.stop = time.Now()\n}\n\nfunc (s *Stopwatch) ElapsedTime() time.Duration {\n\tif s.IsStopped() {\n\t\treturn s.stop.Sub(s.start)\n\t}\n\treturn time.Since(s.start)\n}\n\nfunc (s *Stopwatch) Dt() string {\n\treturn fmt.Sprintf(\"%s\", s.ElapsedTime())\n}\n\nfunc (s *Stopwatch) Log(msg string) {\n\ts.logger.Info(\"elapsed\", \"msg\", msg, \"dx\", s.Dt())\n}\n\nfunc (s *Stopwatch) IsStopped() bool ", "output": "{ return s.stop.After(s.start) }"} {"input": "package opts \n\n\n\ntype QuotedString struct {\n\tvalue *string\n}\n\n\nfunc (s *QuotedString) Set(val string) error {\n\t*s.value = trimQuotes(val)\n\treturn nil\n}\n\n\nfunc (s *QuotedString) Type() string {\n\treturn \"string\"\n}\n\nfunc (s *QuotedString) String() string {\n\treturn *s.value\n}\n\nfunc trimQuotes(value string) string {\n\tlastIndex := len(value) - 1\n\tfor _, char := range []byte{'\\'', '\"'} {\n\t\tif value[0] == char && value[lastIndex] == char {\n\t\t\treturn value[1:lastIndex]\n\t\t}\n\t}\n\treturn value\n}\n\n\n\n\nfunc NewQuotedString(value *string) *QuotedString ", "output": "{\n\treturn &QuotedString{value: value}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\tprimes \"github.com/whatever/math/primes\"\n\t_ \"math\"\n\t\"sort\"\n)\n\nfunc Factorial(n int) int {\n\tresult := 1\n\tfor n > 0 {\n\t\tresult *= n\n\t\tn--\n\t}\n\treturn result\n}\n\nfunc SortedString(s string) string {\n\n\tintArray := make([]int, len(s))\n\n\tfor i, letter := range s {\n\t\tintArray[i] = int(letter)\n\t}\n\n\tsort.Ints(intArray)\n\n\tnewString := \"\"\n\n\tfor _, digit := range intArray {\n\t\tnewString += fmt.Sprintf(\"%s\", string(digit))\n\t}\n\n\treturn newString\n}\n\n\n\nfunc main() {\n\tlimit := 1000000\n\ts := primes.NewNaiveSieve(limit)\n\thits := make(map[int]float64)\n\n\tminIndex := 200000000\n\tminValue := float64(limit + 1)\n\n\tfor i := 2; i <= limit; i++ {\n\t\tif i%(limit/100) == 0 {\n\t\t\tfmt.Println(i)\n\t\t}\n\n\t\ttotient := s.Totient(i)\n\t\tt := float64(i) / float64(totient)\n\t\thits[i] = t\n\n\t\tif !IsPermutation(totient, i) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif t < minValue {\n\t\t\tminValue = t\n\t\t\tminIndex = i\n\t\t\tfmt.Println(minIndex, minValue, i, totient)\n\t\t}\n\t}\n\n\tfmt.Println(minIndex, minValue)\n}\n\nfunc IsPermutation(lhs, rhs int) bool ", "output": "{\n\treturn SortedString(fmt.Sprintf(\"%d\", lhs)) == SortedString(fmt.Sprintf(\"%d\", rhs))\n}"} {"input": "package memory\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"github.com/google/trillian/monitoring\"\n\t\"github.com/google/trillian/storage\"\n)\n\nfunc init() {\n\tif err := storage.RegisterProvider(\"memory\", newMemoryStorageProvider); err != nil {\n\t\tglog.Fatalf(\"Failed to register storage provider memory: %v\", err)\n\t}\n}\n\ntype memProvider struct {\n\tmf monitoring.MetricFactory\n\tts *TreeStorage\n}\n\nfunc newMemoryStorageProvider(mf monitoring.MetricFactory) (storage.Provider, error) {\n\treturn &memProvider{\n\t\tmf: mf,\n\t\tts: NewTreeStorage(),\n\t}, nil\n}\n\nfunc (s *memProvider) LogStorage() storage.LogStorage {\n\treturn NewLogStorage(s.ts, s.mf)\n}\n\nfunc (s *memProvider) MapStorage() storage.MapStorage {\n\treturn nil\n}\n\n\n\nfunc (s *memProvider) Close() error {\n\treturn nil\n}\n\nfunc (s *memProvider) AdminStorage() storage.AdminStorage ", "output": "{\n\treturn NewAdminStorage(s.ts)\n}"} {"input": "package binder\n\nimport (\n\t\"github.com/golang/protobuf/proto\"\n\t\"github.com/labstack/echo\"\n\t\"io/ioutil\"\n)\n\ntype protobufBinder struct{}\n\n\n\nfunc (protobufBinder) Bind(obj interface{}, c echo.Context) error ", "output": "{\n\tbuf, err := ioutil.ReadAll(c.Request().Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = proto.Unmarshal(buf, obj.(proto.Message)); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package net\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\ntype PortRange struct {\n\tBase int\n\tSize int\n}\n\n\nfunc (pr *PortRange) Contains(p int) bool {\n\treturn (p >= pr.Base) && ((p - pr.Base) < pr.Size)\n}\n\n\n\nfunc (pr PortRange) String() string {\n\tif pr.Size == 0 {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%d-%d\", pr.Base, pr.Base+pr.Size-1)\n}\n\n\n\n\nfunc (pr *PortRange) Set(value string) error {\n\tvalue = strings.TrimSpace(value)\n\n\n\tif value == \"\" {\n\t\tpr.Base = 0\n\t\tpr.Size = 0\n\t\treturn nil\n\t}\n\n\thyphenIndex := strings.Index(value, \"-\")\n\tif hyphenIndex == -1 {\n\t\treturn fmt.Errorf(\"expected hyphen in port range\")\n\t}\n\n\tvar err error\n\tvar low int\n\tvar high int\n\tlow, err = strconv.Atoi(value[:hyphenIndex])\n\tif err == nil {\n\t\thigh, err = strconv.Atoi(value[hyphenIndex+1:])\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse port range: %s\", value)\n\t}\n\n\tif high < low {\n\t\treturn fmt.Errorf(\"end port cannot be less than start port: %s\", value)\n\t}\n\tpr.Base = low\n\tpr.Size = 1 + high - low\n\treturn nil\n}\n\n\n\nfunc (*PortRange) Type() string {\n\treturn \"portRange\"\n}\n\n\n\nfunc ParsePortRange(value string) (*PortRange, error) {\n\tpr := &PortRange{}\n\terr := pr.Set(value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pr, nil\n}\n\n\n\nfunc ParsePortRangeOrDie(value string) *PortRange ", "output": "{\n\tpr, err := ParsePortRange(value)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"couldn't parse port range %q: %v\", value, err))\n\t}\n\treturn pr\n}"} {"input": "package base64vlq\n\nimport \"io\"\n\nconst encodeStd = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\n\nconst (\n\tvlqBaseShift = 5\n\tvlqBase = 1 << vlqBaseShift\n\tvlqBaseMask = vlqBase - 1\n\tvlqSignBit = 1\n\tvlqContinuationBit = vlqBase\n)\n\nvar decodeMap [256]byte\n\nfunc init() {\n\tfor i := 0; i < len(encodeStd); i++ {\n\t\tdecodeMap[encodeStd[i]] = byte(i)\n\t}\n}\n\nfunc toVLQSigned(n int32) int32 {\n\tif n < 0 {\n\t\treturn -n<<1 + 1\n\t}\n\treturn n << 1\n}\n\nfunc fromVLQSigned(n int32) int32 {\n\tisNeg := n&vlqSignBit != 0\n\tn >>= 1\n\tif isNeg {\n\t\treturn -n\n\t}\n\treturn n\n}\n\ntype Encoder struct {\n\tw io.ByteWriter\n}\n\nfunc NewEncoder(w io.ByteWriter) *Encoder {\n\treturn &Encoder{\n\t\tw: w,\n\t}\n}\n\n\n\ntype Decoder struct {\n\tr io.ByteReader\n}\n\nfunc NewDecoder(r io.ByteReader) Decoder {\n\treturn Decoder{\n\t\tr: r,\n\t}\n}\n\nfunc (dec Decoder) Decode() (n int32, err error) {\n\tshift := uint(0)\n\tfor continuation := true; continuation; {\n\t\tc, err := dec.r.ReadByte()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tc = decodeMap[c]\n\t\tcontinuation = c&vlqContinuationBit != 0\n\t\tn += int32(c&vlqBaseMask) << shift\n\t\tshift += vlqBaseShift\n\t}\n\treturn fromVLQSigned(n), nil\n}\n\nfunc (enc Encoder) Encode(n int32) error ", "output": "{\n\tn = toVLQSigned(n)\n\tfor digit := int32(vlqContinuationBit); digit&vlqContinuationBit != 0; {\n\t\tdigit = n & vlqBaseMask\n\t\tn >>= vlqBaseShift\n\t\tif n > 0 {\n\t\t\tdigit |= vlqContinuationBit\n\t\t}\n\n\t\terr := enc.w.WriteByte(encodeStd[digit])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package v1alpha2\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\n\nconst (\n\tAnchors = \"subnamespaceanchors\"\n\tAnchorKind = \"SubnamespaceAnchor\"\n\tAnchorAPIVersion = MetaGroup + \"/v1alpha2\"\n\tSubnamespaceOf = MetaGroup + \"/subnamespace-of\"\n)\n\n\n\ntype SubnamespaceAnchorState string\n\n\nconst (\n\tMissing SubnamespaceAnchorState = \"Missing\"\n\tOk SubnamespaceAnchorState = \"Ok\"\n\tConflict SubnamespaceAnchorState = \"Conflict\"\n\tForbidden SubnamespaceAnchorState = \"Forbidden\"\n)\n\n\ntype SubnamespaceAnchorStatus struct {\n\tState SubnamespaceAnchorState `json:\"status,omitempty\"`\n}\n\n\n\n\n\n\n\ntype SubnamespaceAnchor struct {\n\tmetav1.TypeMeta `json:\",inline\"`\n\tmetav1.ObjectMeta `json:\"metadata,omitempty\"`\n\n\tStatus SubnamespaceAnchorStatus `json:\"status,omitempty\"`\n}\n\n\n\n\ntype SubnamespaceAnchorList struct {\n\tmetav1.TypeMeta `json:\",inline\"`\n\tmetav1.ListMeta `json:\"metadata,omitempty\"`\n\tItems []SubnamespaceAnchor `json:\"items\"`\n}\n\n\n\nfunc init() ", "output": "{\n\tSchemeBuilder.Register(&SubnamespaceAnchor{}, &SubnamespaceAnchorList{})\n}"} {"input": "package common\n\nimport (\n\t\"github.com/pkg/errors\"\n)\n\ntype Backend interface {\n\tRenderAllScrolls() (numScrolls int, errors []error)\n\n\tRenderScrollsByID(ids []ID) (renderedScrollIDs []ID, errors []error)\n\n\tParse(id, doc string) Scroll\n}\n\n\n\n\n\n\n\nfunc UpdateIndex(b Backend) error {\n\treturn updateIndex(b)\n}\n\nfunc ComputeStatistics() (Statistics, error) {\n\treturn computeStatistics()\n}\n\nfunc LoadScrolls(b Backend, ids []ID) ([]Scroll, error) {\n\tresult := make([]Scroll, len(ids))\n\tfor i, id := range ids {\n\t\tscroll, err := loadAndParseScrollContentByID(b, id)\n\t\tif err != nil {\n\t\t\treturn result, err\n\t\t}\n\t\tresult[i] = scroll\n\t}\n\treturn result, nil\n}\n\nfunc FindMatchingScrolls(query string) ([]ID, int, error) ", "output": "{\n\tindex, err := OpenExistingIndex()\n\tif err != nil {\n\t\treturn []ID{}, 0, err\n\t}\n\tdefer index.Close()\n\n\tnewQuery := translatePlusMinusTildePrefixes(query)\n\tsearchResults, err := performQuery(index, newQuery)\n\ttotalMatches := int(searchResults.Total)\n\tif err != nil {\n\t\tif err.Error() == \"syntax error\" {\n\t\t\terr = errors.Wrapf(err, \"invalid query string: '%v'\", newQuery)\n\t\t} else {\n\t\t\terr = errors.Wrap(err, \"perform query\")\n\t\t}\n\t\treturn []ID{}, totalMatches, err\n\t}\n\n\tvar ids []ID\n\tfor _, match := range searchResults.Hits {\n\t\tid := ID(match.ID)\n\t\tids = append(ids, id)\n\t}\n\n\treturn ids, totalMatches, nil\n}"} {"input": "package cluster \n\nimport \"net\"\n\n\n\nfunc (c *Cluster) resolveSystemAddr() (net.IP, error) ", "output": "{\n\treturn c.resolveSystemAddrViaSubnetCheck()\n}"} {"input": "package socket\n\nimport \"sync\"\n\n\ntype PacketHandler interface {\n\tOnPacket(Packet)\n}\n\n\n\n\ntype EventHandler interface {\n\tOn(event string, fn interface{}) error\n}\n\n\ntype Handler interface {\n\tEventHandler\n\tPacketHandler\n}\n\ntype handler struct {\n\tmu sync.RWMutex\n\tevents map[string]PacketHandler\n}\n\nfunc newHandler() Handler {\n\treturn &handler{\n\t\tevents: make(map[string]PacketHandler),\n\t}\n}\n\n\n\nfunc (h *handler) OnPacket(p Packet) {\n\th.mu.RLock()\n\tc, ok := h.events[p.Event()]\n\th.mu.RUnlock()\n\n\tif ok {\n\t\tc.OnPacket(p)\n\t}\n}\n\nfunc (h *handler) On(event string, fn interface{}) (err error) ", "output": "{\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.events[event], err = newPacketHandler(fn)\n\treturn err\n}"} {"input": "package packets\n\nimport (\n\t\"fmt\"\n\t\"github.com/google/uuid\"\n\t\"io\"\n)\n\n\n\ntype PubcompPacket struct {\n\tFixedHeader\n\tMessageID uint16\n\tuuid uuid.UUID\n}\n\nfunc (pc *PubcompPacket) String() string {\n\tstr := fmt.Sprintf(\"%s\\n\", pc.FixedHeader)\n\tstr += fmt.Sprintf(\"MessageID: %d\", pc.MessageID)\n\treturn str\n}\n\nfunc (pc *PubcompPacket) Write(w io.Writer) error {\n\tvar err error\n\tpc.FixedHeader.RemainingLength = 2\n\tpacket := pc.FixedHeader.pack()\n\tpacket.Write(encodeUint16(pc.MessageID))\n\t_, err = packet.WriteTo(w)\n\n\treturn err\n}\n\nfunc (pc *PubcompPacket) Unpack(b io.Reader) {\n\tpc.MessageID = decodeUint16(b)\n}\n\nfunc (pc *PubcompPacket) Details() Details {\n\treturn Details{Qos: pc.Qos, MessageID: pc.MessageID}\n}\n\n\n\nfunc (pc *PubcompPacket) UUID() uuid.UUID ", "output": "{\n\treturn pc.uuid\n}"} {"input": "package engine\n\nimport (\n\t\"time\"\n\n\t\"github.com/aws/amazon-ecs-agent/agent/api\"\n)\n\n\n\ntype impossibleTransitionError struct {\n\tstate api.ContainerStatus\n}\n\n\nfunc (err *impossibleTransitionError) ErrorName() string { return \"ImpossibleStateTransitionError\" }\n\ntype DockerTimeoutError struct {\n\tduration time.Duration\n\ttransition string\n}\n\nfunc (err *DockerTimeoutError) Error() string {\n\treturn \"Could not transition to \" + err.transition + \"; timed out after waiting \" + err.duration.String()\n}\nfunc (err *DockerTimeoutError) ErrorName() string { return \"DockerTimeoutError\" }\n\ntype ContainerVanishedError struct{}\n\nfunc (err ContainerVanishedError) Error() string { return \"No container matching saved ID found\" }\nfunc (err ContainerVanishedError) ErrorName() string { return \"ContainerVanishedError\" }\n\ntype CannotXContainerError struct {\n\ttransition string\n\tmsg string\n}\n\nfunc (err CannotXContainerError) Error() string { return err.msg }\nfunc (err CannotXContainerError) ErrorName() string {\n\treturn \"Cannot\" + err.transition + \"ContainerError\"\n}\n\ntype OutOfMemoryError struct{}\n\nfunc (err OutOfMemoryError) Error() string { return \"Container killed due to memory usage\" }\nfunc (err OutOfMemoryError) ErrorName() string { return \"OutOfMemoryError\" }\n\n\ntype DockerStateError struct {\n\tdockerError string\n\tname string\n}\n\nfunc NewDockerStateError(err string) DockerStateError {\n\treturn DockerStateError{\n\t\tdockerError: err,\n\t\tname: \"DockerStateError\",\n\t}\n}\n\nfunc (err DockerStateError) Error() string {\n\treturn err.dockerError\n}\nfunc (err DockerStateError) ErrorName() string {\n\treturn err.name\n}\n\nfunc (err *impossibleTransitionError) Error() string ", "output": "{\n\treturn \"Cannot transition to \" + err.state.String()\n}"} {"input": "package compute_test\n\nimport (\n\t\"context\"\n\n\tcompute \"cloud.google.com/go/compute/apiv1\"\n\tcomputepb \"google.golang.org/genproto/googleapis/cloud/compute/v1\"\n)\n\nfunc ExampleNewRegionInstancesRESTClient() {\n\tctx := context.Background()\n\tc, err := compute.NewRegionInstancesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\t_ = c\n}\n\n\n\nfunc ExampleRegionInstancesClient_BulkInsert() ", "output": "{\n\tctx := context.Background()\n\tc, err := compute.NewRegionInstancesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\treq := &computepb.BulkInsertRegionInstanceRequest{\n\t}\n\top, err := c.BulkInsert(ctx, req)\n\tif err != nil {\n\t}\n\n\terr = op.Wait(ctx)\n\tif err != nil {\n\t}\n}"} {"input": "package averybigsum\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestExample(t *testing.T) ", "output": "{\n\tar := []int32{1000000001, 1000000002, 1000000003, 1000000004, 1000000005}\n\tresult := AVeryBigSum(ar)\n\tif result != 5000000015 {\n\t\tt.Errorf(\"AVeryBigSum failed the example test\")\n\t}\n}"} {"input": "package lht\n\n\n\nfunc findAnagrams(s string, p string) []int ", "output": "{\n\tr := []int{}\n\tif len(s) == 0 || len(p) == 0 {\n\t\treturn r\n\t}\n\tmp := make([]int, 26)\n\tfor _, r := range p {\n\t\tmp[r-'a']++\n\t}\n\n\tleft, right, count := 0, 0, len(p)\n\tfor right < len(s) {\n\t\tif mp[s[right]-'a'] >= 1 {\n\t\t\tcount--\n\t\t}\n\t\tmp[s[right]-'a']--\n\t\tright++\n\n\t\tif count == 0 {\n\t\t\tr = append(r, left)\n\t\t}\n\n\t\tif right-left == len(p) {\n\t\t\tif mp[s[left]-'a'] >= 0 {\n\t\t\t\tcount++\n\t\t\t}\n\t\t\tmp[s[left]-'a']++\n\t\t\tleft++\n\t\t}\n\t}\n\treturn r\n}"} {"input": "package s2\n\n\nvar (\n\t_ Shape = (*PointVector)(nil)\n)\n\n\n\n\n\n\n\n\ntype PointVector []Point\n\nfunc (p *PointVector) NumEdges() int { return len(*p) }\nfunc (p *PointVector) Edge(i int) Edge { return Edge{(*p)[i], (*p)[i]} }\nfunc (p *PointVector) ReferencePoint() ReferencePoint { return OriginReferencePoint(false) }\n\nfunc (p *PointVector) Chain(i int) Chain { return Chain{i, 1} }\nfunc (p *PointVector) ChainEdge(i, j int) Edge { return Edge{(*p)[i], (*p)[j]} }\nfunc (p *PointVector) ChainPosition(e int) ChainPosition { return ChainPosition{e, 0} }\nfunc (p *PointVector) Dimension() int { return 0 }\nfunc (p *PointVector) IsEmpty() bool { return defaultShapeIsEmpty(p) }\nfunc (p *PointVector) IsFull() bool { return defaultShapeIsFull(p) }\nfunc (p *PointVector) typeTag() typeTag { return typeTagPointVector }\nfunc (p *PointVector) privateInterface() {}\n\nfunc (p *PointVector) NumChains() int ", "output": "{ return len(*p) }"} {"input": "package removepeer\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/consul/agent\"\n\t\"github.com/mitchellh/cli\"\n)\n\n\n\nfunc TestOperatorRaftRemovePeerCommand(t *testing.T) {\n\tt.Parallel()\n\ta := agent.NewTestAgent(t.Name(), ``)\n\tdefer a.Shutdown()\n\n\tt.Run(\"Test the remove-peer subcommand directly\", func(t *testing.T) {\n\t\tui := cli.NewMockUi()\n\t\tc := New(ui)\n\t\targs := []string{\"-http-addr=\" + a.HTTPAddr(), \"-address=nope\"}\n\n\t\tcode := c.Run(args)\n\t\tif code != 1 {\n\t\t\tt.Fatalf(\"bad: %d. %#v\", code, ui.ErrorWriter.String())\n\t\t}\n\n\t\toutput := strings.TrimSpace(ui.ErrorWriter.String())\n\t\tif !strings.Contains(output, \"address \\\"nope\\\" was not found in the Raft configuration\") {\n\t\t\tt.Fatalf(\"bad: %s\", output)\n\t\t}\n\t})\n\n\tt.Run(\"Test the remove-peer subcommand with -id\", func(t *testing.T) {\n\t\tui := cli.NewMockUi()\n\t\tc := New(ui)\n\t\targs := []string{\"-http-addr=\" + a.HTTPAddr(), \"-id=nope\"}\n\n\t\tcode := c.Run(args)\n\t\tif code != 1 {\n\t\t\tt.Fatalf(\"bad: %d. %#v\", code, ui.ErrorWriter.String())\n\t\t}\n\n\t\toutput := strings.TrimSpace(ui.ErrorWriter.String())\n\t\tif !strings.Contains(output, \"id \\\"nope\\\" was not found in the Raft configuration\") {\n\t\t\tt.Fatalf(\"bad: %s\", output)\n\t\t}\n\t})\n}\n\nfunc TestOperatorRaftRemovePeerCommand_noTabs(t *testing.T) ", "output": "{\n\tt.Parallel()\n\tif strings.ContainsRune(New(cli.NewMockUi()).Help(), '\\t') {\n\t\tt.Fatal(\"help has tabs\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc number_3_digits_test(n int) bool {\n\treturn (n > 99 && n < 1000)\n}\n\n\n\nfunc main() {\n\tvar n int\n\tvar m int\n\tfmt.Scanf(\"%d\", &n)\n\tfmt.Scanf(\"%d\", &m)\n\tif number_3_digits_test(n) && number_3_digits_test(m) {\n\t\tfor i := n; i <= m; i++ {\n\t\t\tif power_3_digits_test(i) {\n\t\t\t\tfmt.Printf(\"%d\\n\", i)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"Error\\n\")\n\t}\n}\n\nfunc power_3_digits_test(n int) bool ", "output": "{\n\tn1 := n % 10\n\tn2 := (n / 10) % 10\n\tn3 := (n / 100) % 10\n\n\treturn (n1*n1*n1+n2*n2*n2+n3*n3*n3 == n)\n}"} {"input": "package analytics\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype UpdatePrivateAccessChannelDetails struct {\n\n\tDisplayName *string `mandatory:\"false\" json:\"displayName\"`\n\n\tVcnId *string `mandatory:\"false\" json:\"vcnId\"`\n\n\tSubnetId *string `mandatory:\"false\" json:\"subnetId\"`\n\n\tPrivateSourceDnsZones []PrivateSourceDnsZone `mandatory:\"false\" json:\"privateSourceDnsZones\"`\n}\n\n\n\nfunc (m UpdatePrivateAccessChannelDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package ipv6\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\n\n\nfunc setsockopt(s uintptr, level, name int, v unsafe.Pointer, l uint32) error {\n\treturn syscall.Setsockopt(syscall.Handle(s), int32(level), int32(name), (*byte)(v), int32(l))\n}\n\nfunc getsockopt(s uintptr, level, name int, v unsafe.Pointer, l *uint32) error ", "output": "{\n\treturn syscall.Getsockopt(syscall.Handle(s), int32(level), int32(name), (*byte)(v), (*int32)(unsafe.Pointer(l)))\n}"} {"input": "package router\n\n\n\n\nimport (\n\t\"github.com/weaveworks/mesh\"\n)\n\n\n\ntype AWSVPCConnection struct {\n\testablishedChan chan struct{}\n\terrorChan chan error\n}\n\nfunc (conn *AWSVPCConnection) Confirm() {\n\tclose(conn.establishedChan)\n}\n\nfunc (conn *AWSVPCConnection) EstablishedChannel() <-chan struct{} {\n\treturn conn.establishedChan\n}\n\nfunc (conn *AWSVPCConnection) ErrorChannel() <-chan error {\n\treturn conn.errorChan\n}\n\nfunc (conn *AWSVPCConnection) Stop() {}\n\nfunc (conn *AWSVPCConnection) ControlMessage(tag byte, msg []byte) {\n}\n\nfunc (conn *AWSVPCConnection) DisplayName() string {\n\treturn \"awsvpc\"\n}\n\n\n\nfunc (conn *AWSVPCConnection) Forward(key ForwardPacketKey) FlowOp {\n\treturn DiscardingFlowOp{}\n}\n\ntype AWSVPC struct{}\n\nfunc NewAWSVPC() AWSVPC {\n\treturn AWSVPC{}\n}\n\n\n\nfunc (vpc AWSVPC) AddFeaturesTo(features map[string]string) {}\n\nfunc (vpc AWSVPC) PrepareConnection(params mesh.OverlayConnectionParams) (mesh.OverlayConnection, error) {\n\tconn := &AWSVPCConnection{\n\t\testablishedChan: make(chan struct{}),\n\t\terrorChan: make(chan error, 1),\n\t}\n\treturn conn, nil\n}\n\n\n\n\n\nfunc (vpc AWSVPC) InvalidateRoutes() {}\n\nfunc (vpc AWSVPC) InvalidateShortIDs() {}\n\nfunc (vpc AWSVPC) StartConsumingPackets(localPeer *mesh.Peer, peers *mesh.Peers, consumer OverlayConsumer) error {\n\treturn nil\n}\n\nfunc (vpc AWSVPC) Diagnostics() interface{} ", "output": "{\n\treturn nil\n}"} {"input": "package types_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestTypes(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Ginkgo Types Suite\")\n}"} {"input": "package remote\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"math\"\n\tpb \"rcs/proto\"\n)\n\ntype GrpcHandler func(s *remoteServer, in *pb.GrpcRequest, out *pb.GrpcReply) error\n\nvar grpcRouter map[string]GrpcHandler = map[string]GrpcHandler{\n\t\"online_list\": onlineList,\n}\n\nfunc handleGrpc(s *remoteServer, in *pb.GrpcRequest) (*pb.GrpcReply, error) {\n\tvar grpcReply pb.GrpcReply\n\tvar err error = nil\n\n\tif len(in.Action) < 1 {\n\t\terr = errors.New(\"handleGrpc input Action err\")\n\t\treturn &grpcReply, err\n\t}\n\thandle := grpcRouter[in.Action]\n\tif handle == nil {\n\t\terr = errors.New(\"handleGrpc input Action no find\")\n\t\treturn &grpcReply, err\n\t}\n\terr = handle(s, in, &grpcReply)\n\treturn &grpcReply, err\n}\nfunc checkPage(in *pb.GrpcRequest) error {\n\tif in.PageNo < 1 {\n\t\tlog.Println(\"checkPage PageNo =\", in.PageNo)\n\t\tin.PageNo = 1\n\t}\n\tif in.PageSize < 1 {\n\t\treturn errors.New(\"PageSize value error\")\n\t}\n\treturn nil\n}\n\n\n\nfunc onlineList(s *remoteServer, in *pb.GrpcRequest, out *pb.GrpcReply) error ", "output": "{\n\n\tlog.Println(\"handleGrpc input Action no find.......\")\n\terr := checkPage(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdatajson, counts := s.model.GetPageRec()\n\tout.Data = datajson\n\tout.TotalResults = counts\n\tpages := math.Ceil(float64(counts / in.PageSize))\n\tif float64(in.PageNo) < pages {\n\t\tout.HasNext = true\n\t}\n\treturn nil\n}"} {"input": "package format\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\tblocks \"gx/ipfs/QmRcHuYzAyswytBuMF78rj3LTChYszomRFXNg4685ZN1WM/go-block-format\"\n)\n\n\ntype DecodeBlockFunc func(block blocks.Block) (Node, error)\n\ntype BlockDecoder interface {\n\tRegister(codec uint64, decoder DecodeBlockFunc)\n\tDecode(blocks.Block) (Node, error)\n}\ntype safeBlockDecoder struct {\n\tlock sync.RWMutex\n\tdecoders map[uint64]DecodeBlockFunc\n}\n\n\n\n\nfunc (d *safeBlockDecoder) Register(codec uint64, decoder DecodeBlockFunc) {\n\td.lock.Lock()\n\tdefer d.lock.Unlock()\n\td.decoders[codec] = decoder\n}\n\nfunc (d *safeBlockDecoder) Decode(block blocks.Block) (Node, error) {\n\tif node, ok := block.(Node); ok {\n\t\treturn node, nil\n\t}\n\n\tty := block.Cid().Type()\n\n\td.lock.RLock()\n\tdecoder, ok := d.decoders[ty]\n\td.lock.RUnlock()\n\n\tif ok {\n\t\treturn decoder(block)\n\t} else {\n\t\treturn nil, fmt.Errorf(\"unrecognized object type: %d\", ty)\n\t}\n}\n\nvar DefaultBlockDecoder BlockDecoder = &safeBlockDecoder{decoders: make(map[uint64]DecodeBlockFunc)}\n\n\nfunc Decode(block blocks.Block) (Node, error) {\n\treturn DefaultBlockDecoder.Decode(block)\n}\n\n\n\n\nfunc Register(codec uint64, decoder DecodeBlockFunc) ", "output": "{\n\tDefaultBlockDecoder.Register(codec, decoder)\n}"} {"input": "package util\n\n\n\n\n\nfunc Max64(a, b int64) int64 {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n\nfunc Min64(a, b int64) int64 {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc Min(a, b int) int ", "output": "{\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}"} {"input": "package statement\n\nimport (\n\t\"time\"\n)\n\n\n\ntype ResponseTime struct {\n\tValue int\n\tTime time.Time\n}\n\n\n\nfunc NewResponseTime(v int) ResponseTime {\n\tr := ResponseTime{Value: v, Time: time.Now()}\n\treturn r\n}\n\n\ntype ResponseTimes []ResponseTime\n\n\n\n\n\n\n\nfunc (rs ResponseTimes) Less(i, j int) bool {\n\treturn rs[i].Value < rs[j].Value\n}\n\n\n\nfunc (rs ResponseTimes) Swap(i, j int) {\n\trs[i], rs[j] = rs[j], rs[i]\n}\n\nfunc (rs ResponseTimes) Len() int ", "output": "{\n\treturn len(rs)\n}"} {"input": "package error\n\nimport (\n\t\"strconv\"\n)\n\n\n\ntype StructuralError string\n\nfunc (s StructuralError) String() string {\n\treturn \"OpenPGP data invalid: \" + string(s)\n}\n\n\n\ntype UnsupportedError string\n\nfunc (s UnsupportedError) String() string {\n\treturn \"OpenPGP feature unsupported: \" + string(s)\n}\n\n\n\ntype InvalidArgumentError string\n\nfunc (i InvalidArgumentError) String() string {\n\treturn \"OpenPGP argument invalid: \" + string(i)\n}\n\n\n\ntype SignatureError string\n\nfunc (b SignatureError) String() string {\n\treturn \"OpenPGP signature invalid: \" + string(b)\n}\n\ntype keyIncorrect int\n\nfunc (ki keyIncorrect) String() string {\n\treturn \"the given key was incorrect\"\n}\n\nvar KeyIncorrectError = keyIncorrect(0)\n\ntype unknownIssuer int\n\nfunc (unknownIssuer) String() string {\n\treturn \"signature make by unknown entity\"\n}\n\nvar UnknownIssuerError = unknownIssuer(0)\n\ntype UnknownPacketTypeError uint8\n\n\n\nfunc (upte UnknownPacketTypeError) String() string ", "output": "{\n\treturn \"unknown OpenPGP packet type: \" + strconv.Itoa(int(upte))\n}"} {"input": "package aes_test\n\nimport (\n\t\"github.com/keep94/vsafe/aes\"\n\t\"testing\"\n)\n\nvar (\n\tsomeKey = []byte(\"12345678901234567890123456789012\")\n)\n\nfunc TestEncryptDecrypt(t *testing.T) {\n\tverifyEncryptDecrypt(t, \"aardvark\")\n\tverifyEncryptDecrypt(t, \"1234567890123456\")\n\tverifyEncryptDecrypt(t, \"1234567890123456 \")\n\tverifyEncryptDecrypt(t, \"123456789012345 \")\n\tverifyEncryptDecrypt(t, \" now is the time for all good men to come to the aid of their party \")\n}\n\nfunc TestEncryptsSameTextDifferently(t *testing.T) {\n\tencoded, err := aes.Encrypt(\"aardvark\", someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tencodedAgain, err := aes.Encrypt(\"aardvark\", someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif encoded == encodedAgain {\n\t\tt.Error(\"Expected same text to be encrypted differently every time.\")\n\t}\n}\n\n\n\nfunc verifyEncryptDecrypt(t *testing.T, plain string) {\n\tencoded, err := aes.Encrypt(plain, someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdecoded, err := aes.Decrypt(encoded, someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif decoded != plain {\n\t\tt.Errorf(\"Expected to get same thing back: '%s', got '%s' %d %d\", plain, decoded, len(plain), len(decoded))\n\t}\n}\n\nfunc TestEncryptSecurity(t *testing.T) ", "output": "{\n\tanotherKey := []byte(\"12345678901234567890123456789013\")\n\tencoded, err := aes.Encrypt(\"aardvark\", someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdecoded, _ := aes.Decrypt(encoded, anotherKey)\n\tif decoded == \"aardvark\" {\n\t\tt.Error(\"Expected different decryption with different key\")\n\t}\n}"} {"input": "package asm\n\nimport \"strconv\"\n\nconst (\n\t_Class_name_0 = \"LdClassLdXClassStClassStXClassALUClassJumpClass\"\n\t_Class_name_1 = \"ALU64Class\"\n)\n\nvar (\n\t_Class_index_0 = [...]uint8{0, 7, 15, 22, 30, 38, 47}\n)\n\n\n\nfunc (i Class) String() string ", "output": "{\n\tswitch {\n\tcase 0 <= i && i <= 5:\n\t\treturn _Class_name_0[_Class_index_0[i]:_Class_index_0[i+1]]\n\tcase i == 7:\n\t\treturn _Class_name_1\n\tdefault:\n\t\treturn \"Class(\" + strconv.FormatInt(int64(i), 10) + \")\"\n\t}\n}"} {"input": "package stat\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype RevStat struct {\n\tRevId string `json:\"RevId\"`\n\tUserName string `json:\"UserName\"`\n\tWordCount int `json:\"WordCount\"`\n\tModDate string `json:\"ModDate\"`\n\tWordFreq []WordPair `json:\"WordFreq\"`\n}\n\ntype DocStat struct {\n\tFileId string `json:\"FileId\"`\n\tTitle string `json:\"Title\"`\n\tLastMod string `json:\"LastMod\"`\n\tRevList []RevStat `json:\"RevList\"`\n}\n\n\n\nfunc (rev RevStat) String() string {\n\treturn fmt.Sprintf(\"[%s %s] %d words by %s. \\n\\t Words [%s]\", rev.ModDate, rev.RevId, rev.WordCount, rev.UserName, rev.WordFreq)\n}\nfunc (doc DocStat) String() string {\n\ts := fmt.Sprintf(\"[%s] '%s' last mod on %s with revs\\n\", doc.FileId, doc.Title, doc.LastMod)\n\tfor i, v := range doc.RevList {\n\t\ts += fmt.Sprintf(\"\\t %d:%s\\n\", i, v)\n\t}\n\treturn s\n}\n\nfunc (rev RevStat) GetTime() string ", "output": "{\n\tx, _ := time.Parse(\"2006-01-02T15:04:05.000Z\", rev.ModDate)\n\treturn x.Format(\"15:04\")\n}"} {"input": "package framework\n\nimport \"github.com/onsi/gomega\"\n\n\nfunc ExpectEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.Equal(extra), explain...)\n}\n\n\nfunc ExpectNotEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).NotTo(gomega.Equal(extra), explain...)\n}\n\n\nfunc ExpectError(err error, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, err).To(gomega.HaveOccurred(), explain...)\n}\n\n\nfunc ExpectNoError(err error, explain ...interface{}) {\n\tExpectNoErrorWithOffset(1, err, explain...)\n}\n\n\n\n\n\n\nfunc ExpectConsistOf(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.ConsistOf(extra), explain...)\n}\n\n\nfunc ExpectHaveKey(actual interface{}, key interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.HaveKey(key), explain...)\n}\n\n\nfunc ExpectEmpty(actual interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.BeEmpty(), explain...)\n}\n\nfunc ExpectNoErrorWithOffset(offset int, err error, explain ...interface{}) ", "output": "{\n\tgomega.ExpectWithOffset(1+offset, err).NotTo(gomega.HaveOccurred(), explain...)\n}"} {"input": "package cmd\n\nimport (\n\t\"crypto/rand\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/coreos/etcd/clientv3\"\n)\n\nvar (\n\tdialTotal int\n)\n\nfunc mustCreateConn() *clientv3.Client {\n\teps := strings.Split(endpoints, \",\")\n\tendpoint := eps[dialTotal%len(eps)]\n\tdialTotal++\n\tclient, err := clientv3.NewFromURL(endpoint)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"dial error: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\treturn client\n}\n\nfunc mustCreateClients(totalClients, totalConns uint) []*clientv3.Client {\n\tconns := make([]*clientv3.Client, totalConns)\n\tfor i := range conns {\n\t\tconns[i] = mustCreateConn()\n\t}\n\n\tclients := make([]*clientv3.Client, totalClients)\n\tfor i := range clients {\n\t\tclients[i] = conns[i%int(totalConns)].Clone()\n\t}\n\treturn clients\n}\n\n\n\nfunc mustRandBytes(n int) []byte ", "output": "{\n\trb := make([]byte, n)\n\t_, err := rand.Read(rb)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"failed to generate value: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\treturn rb\n}"} {"input": "package httpmux\n\nimport \"net/http\"\n\n\ntype ConfigOption interface {\n\tSet(c *Config)\n}\n\n\ntype ConfigOptionFunc func(c *Config)\n\n\n\n\n\nfunc WithPrefix(prefix string) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Prefix = prefix })\n}\n\n\nfunc WithMiddleware(mw ...Middleware) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Middleware = mw })\n}\n\n\nfunc WithMiddlewareFunc(mw ...MiddlewareFunc) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.UseFunc(mw...) })\n}\n\n\nfunc WithRedirectTrailingSlash(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectTrailingSlash = v })\n}\n\n\nfunc WithRedirectFixedPath(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectFixedPath = v })\n}\n\n\nfunc WithHandleMethodNotAllowed(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.HandleMethodNotAllowed = v })\n}\n\n\nfunc WithNotFound(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.NotFound = f })\n}\n\n\nfunc WithMethodNotAllowed(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.MethodNotAllowed = f })\n}\n\n\nfunc WithPanicHandler(f func(http.ResponseWriter, *http.Request, interface{})) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.PanicHandler = f })\n}\n\nfunc (f ConfigOptionFunc) Set(c *Config) ", "output": "{ f(c) }"} {"input": "package settings\n\nimport (\n\t\"sync/atomic\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\n\ntype IntSetting struct {\n\tdefaultValue int64\n\tv int64\n\tvalidateFn func(int64) error\n}\n\nvar _ Setting = &IntSetting{}\n\n\nfunc (i *IntSetting) Get() int64 {\n\treturn atomic.LoadInt64(&i.v)\n}\n\nfunc (i *IntSetting) String() string {\n\treturn EncodeInt(i.Get())\n}\n\n\nfunc (*IntSetting) Typ() string {\n\treturn \"i\"\n}\n\n\nfunc (i *IntSetting) Validate(v int64) error {\n\tif i.validateFn != nil {\n\t\tif err := i.validateFn(v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (i *IntSetting) set(v int64) error {\n\tif err := i.Validate(v); err != nil {\n\t\treturn err\n\t}\n\tatomic.StoreInt64(&i.v, v)\n\treturn nil\n}\n\nfunc (i *IntSetting) setToDefault() {\n\tif err := i.set(i.defaultValue); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\nfunc RegisterIntSetting(key, desc string, defaultValue int64) *IntSetting {\n\treturn RegisterValidatedIntSetting(key, desc, defaultValue, nil)\n}\n\n\n\n\n\n\n\nfunc TestingSetInt(s **IntSetting, v int64) func() {\n\tsaved := *s\n\t*s = &IntSetting{v: v}\n\treturn func() {\n\t\t*s = saved\n\t}\n}\n\nfunc RegisterValidatedIntSetting(\n\tkey, desc string, defaultValue int64, validateFn func(int64) error,\n) *IntSetting ", "output": "{\n\tif validateFn != nil {\n\t\tif err := validateFn(defaultValue); err != nil {\n\t\t\tpanic(errors.Wrap(err, \"invalid default\"))\n\t\t}\n\t}\n\tsetting := &IntSetting{\n\t\tdefaultValue: defaultValue,\n\t\tvalidateFn: validateFn,\n\t}\n\tregister(key, desc, setting)\n\treturn setting\n}"} {"input": "package jsonpatch\n\nimport \"testing\"\n\n\n\nfunc TestRegionEffecter(t *testing.T) ", "output": "{\n\tp := New()\n\tif len(p) != 0 {\n\t\tt.Errorf(\"Got length %s should be 0\", p)\n\t}\n\tp = p.Add(\"foo\", \"/bar\", \"baz\")\n\tif len(p) != 1 {\n\t\tt.Errorf(\"Got length %s should be 1\", p)\n\t}\n}"} {"input": "package hybridcompute\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) BaseClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient ", "output": "{\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"os\";\n\t\"container/list\";\n\t\"net\";\n\t\"log\";\n\t\"irc\";\n\t\"runloop\";\n)\n\ntype Network struct {\n\tname\t\tstring;\n\tserver\t\t*server;\n\tclients\t\t*list.List;\n\tlisten\t\t*listenConn;\n}\n\nfunc newNetwork(name string, serverConn net.Conn, listen net.Listener) *Network {\n\tvar network *Network;\n\n\taccept := func(conn net.Conn) {\n\t\trunloop.CallLater(func() {\n\t\t\tnetwork.addClient(conn)\n\t\t})\n\t};\n\n\terror := func(err os.Error) {\n\t};\n\n\tl := newListenConn(listen, accept, error);\n\tnetwork = &Network{name: name, clients: list.New(), listen: l};\n\tnetwork.server = newServer(serverConn, network);\n\treturn network;\n}\n\n\n\n\n\nfunc (network *Network) SendToServer(msg *irc.Message) {\n\tif network.server != nil {\n\t\tnetwork.server.Send(msg)\n\t}\n}\n\n\nfunc (network *Network) SendToClients(msg *irc.Message) {\n\tfor c := range network.clients.Iter() {\n\t\tc.(*client).Send(msg)\n\t}\n}\n\n\nfunc (network *Network) SendNoticeToClient(conn Conn, line string) {\n\tnick := \"bouncin\"; \n\tconn.Send(&irc.Message{Command: \"NOTICE\", Params: []string{nick, line}});\n}\n\nvar networks = make(map[string] *Network);\n\nfunc AddNetwork(name string, server net.Conn, listen net.Listener) *Network {\n\tnetwork := newNetwork(name, server, listen);\n\tnetworks[name] = network;\n\treturn network;\n}\n\nfunc (network *Network) addClient(conn net.Conn) ", "output": "{\n\tclient := newClient(conn, network);\n\tnetwork.clients.PushBack(client);\n\tlog.Stderrf(\"client connected from %s\\n\", conn.RemoteAddr());\n}"} {"input": "package vspk\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"github.com/nuagenetworks/go-bambou/bambou\"\n\t\"strings\"\n)\n\nvar (\n\turlpostfix string\n)\n\n\n\n\n\nfunc NewX509Session(cert *tls.Certificate, url string) (*bambou.Session, *Me) {\n\n\troot := NewMe()\n\turl += urlpostfix\n\n\tsession := bambou.NewX509Session(cert, url, root)\n\n\treturn session, root\n}\n\nfunc init() {\n\n\turlpostfix = \"/\" + SDKAPIPrefix + \"/v\" + strings.Replace(fmt.Sprintf(\"%.1v\", SDKAPIVersion), \".\", \"_\", 100)\n}\n\nfunc NewSession(username, password, organization, url string) (*bambou.Session, *Me) ", "output": "{\n\n\troot := NewMe()\n\turl += urlpostfix\n\n\tsession := bambou.NewSession(username, password, organization, url, root)\n\n\treturn session, root\n}"} {"input": "package main\n\nimport (\n \"net/http\"\n \"os\"\n\n \"github.com/russross/blackfriday\"\n)\n\nfunc main() {\n port := os.Getenv(\"PORT\")\n if port == \"\" {\n port = \"8080\"\n }\n\n http.HandleFunc(\"/markdown\", GenerateMarkdown)\n http.Handle(\"/\", http.FileServer(http.Dir(\"public\")))\n http.ListenAndServe(\":\"+port, nil)\n}\n\n\n\nfunc GenerateMarkdown(rw http.ResponseWriter, r *http.Request) ", "output": "{\n markdown := blackfriday.MarkdownCommon([]byte(r.FormValue(\"body\")))\n rw.Write(markdown)\n}"} {"input": "package p058\n\nimport \"testing\"\n\n\n\nfunc TestExample(t *testing.T) ", "output": "{\n\tif lengthOfLastWord(\" nnnn \") != 4 {\n\t\tt.Fatal(\"error answer\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"math\"\n\t\"math/rand\"\n)\n\n\n\n\n\nfunc shuffleStrings(x []string, seed int64) {\n\tr := rand.New(rand.NewSource(seed))\n\tfor i := range x {\n\t\tj := r.Intn(i + 1)\n\t\tx[i], x[j] = x[j], x[i]\n\t}\n}\n\nfunc chunkStrings(x []string, numChunks int) [][]string ", "output": "{\n\tvar result [][]string\n\tif numChunks > len(x) {\n\t\tnumChunks = len(x)\n\t}\n\ti := 0\n\tfor len(result) < numChunks {\n\t\tchunkSize := int(math.Floor(float64(len(x)-i) / float64(numChunks-len(result))))\n\t\tub := i + chunkSize\n\t\tresult = append(result, x[i:ub])\n\t\ti += chunkSize\n\t}\n\treturn result\n}"} {"input": "package tests\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/coreos/init/tests/coreos-install/register\"\n\t\"github.com/coreos/init/tests/coreos-install/util\"\n\n\t_ \"github.com/coreos/init/tests/coreos-install/registry\"\n)\n\nvar flagBinaryPath string\n\nfunc init() {\n\tflag.StringVar(&flagBinaryPath, \"coreos-install\", \"coreos-install\", \"path to coreos-install binary\")\n}\n\n\n\nfunc TestCoreosInstall(t *testing.T) {\n\tlocalImagePath := util.FetchLocalImage(t)\n\tdefer os.RemoveAll(localImagePath)\n\n\tserver := util.HTTPServer{\n\t\tFileDir: localImagePath,\n\t}\n\taddr := server.Start(t)\n\n\tctx := register.Context{\n\t\tBinaryPath: flagBinaryPath,\n\t\tLocalImagePath: filepath.Join(localImagePath, \"coreos_production_image.bin.bz2\"),\n\t\tLocalAddress: addr,\n\t}\n\n\tnetworkUnit := util.CreateNetworkUnit(t)\n\tif networkUnit != \"\" {\n\t\tdefer os.RemoveAll(networkUnit)\n\t}\n\n\tfor _, test := range register.Tests {\n\t\tt.Run(test.Name, func(t *testing.T) {\n\t\t\ttest.Ctx = ctx\n\t\t\ttest.Run(t)\n\t\t})\n\t}\n}\n\nfunc TestMain(m *testing.M) ", "output": "{\n\tflag.Parse()\n\tos.Exit(m.Run())\n}"} {"input": "package wxshield2\n\nimport (\n\t\"testing\"\n)\n\nfunc TestPacket_InsertEroteme(t *testing.T) {\n\tn := Packet{}\n\twant := `INSERT INTO test (timestamp, pressure, tempa, tempb, humidity, ptemp, htemp, battery, indx) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`\n\tif n.InsertEroteme(\"test\") != want {\n\t\tt.Errorf(\"Got %q not %q\", n.InsertEroteme(\"test\"), want)\n\t}\n}\n\n\n\nfunc TestPacket_Jsonable(t *testing.T) {\n\tn := Packet{}\n\t*n.Jsonable().Battery = 1.0\n\tif n.Battery.Float64 != 1.0 {\n\t\tt.Errorf(\"Should be able to set values\")\n\t}\n}\n\nfunc TestPacket_InsertNamed(t *testing.T) ", "output": "{\n\tn := Packet{}\n\twant := `INSERT INTO test (timestamp, pressure, tempa, tempb, humidity, ptemp, htemp, battery, indx) VALUES (:timestamp, :pressure, :tempa, :tempb, :humidity, :ptemp, :htemp, :battery, :indx)`\n\tif n.InsertNamed(\"test\") != want {\n\t\tt.Errorf(\"Got %q not %q\", n.InsertNamed(\"test\"), want)\n\t}\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/utils\"\n\n\n\n\ntype CmdGetCacheAge struct {\n\tname string\n\trpcMethod string\n\trpcParams *StringWrapper\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetCacheAge) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdGetCacheAge) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdGetCacheAge) RpcParams() interface{} {\n\tif self.rpcParams == nil {\n\t\tself.rpcParams = &StringWrapper{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetCacheAge) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetCacheAge) RpcResult() interface{} {\n\treturn &utils.CachedItemAge{}\n}\n\nfunc init() ", "output": "{\n\tc := &CmdGetCacheAge{\n\t\tname: \"cache_age\",\n\t\trpcMethod: \"ApierV1.GetCachedItemAge\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/utils\"\n\nfunc init() {\n\tc := &CmdGetCacheAge{\n\t\tname: \"cache_age\",\n\t\trpcMethod: \"ApierV1.GetCachedItemAge\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetCacheAge struct {\n\tname string\n\trpcMethod string\n\trpcParams *StringWrapper\n\t*CommandExecuter\n}\n\n\n\nfunc (self *CmdGetCacheAge) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdGetCacheAge) RpcParams() interface{} {\n\tif self.rpcParams == nil {\n\t\tself.rpcParams = &StringWrapper{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetCacheAge) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetCacheAge) RpcResult() interface{} {\n\treturn &utils.CachedItemAge{}\n}\n\nfunc (self *CmdGetCacheAge) Name() string ", "output": "{\n\treturn self.name\n}"} {"input": "package fields\n\nimport (\n\t\"regexp\"\n\t\"time\"\n)\n\nfunc UseDefaultKeyIfCustomKeyIsEmpty(defaultKey, customKey string) string {\n\tif \"\" != customKey {\n\t\treturn customKey\n\t}\n\treturn defaultKey\n}\n\n\n\nfunc getMessageFromError(err error) string {\n\tif nil == err {\n\t\treturn \"\"\n\t}\n\treturn err.Error()\n}\n\nfunc getPatternFromRegExp(re *regexp.Regexp) string {\n\tif nil == re {\n\t\treturn \"\"\n\t}\n\treturn re.String()\n}\n\nfunc execFnIfNotNil(fn func()) {\n\tif nil != fn {\n\t\tfn()\n\t}\n}\n\nfunc addSuffix(name string, suffix *string) string {\n\tif nil != suffix {\n\t\treturn name + \"-\" + *suffix\n\t}\n\treturn name\n}\n\nfunc _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) (*time.Location, int) {\n\tif nil == locationByString || \"\" == *locationByString {\n\t\treturn defaultLoc, 1\n\t}\n\n\tif loc, err := time.LoadLocation(*locationByString); nil == err {\n\t\treturn loc, 2\n\t}\n\n\treturn defaultLoc, 0\n}\n\n\nfunc useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) *time.Location {\n\tloc, _ := _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc, locationByString)\n\treturn loc\n}\n\nfunc ExecFuncIfErrIsNotNil(err error, fn func()) (b bool) ", "output": "{\n\tif nil != err {\n\t\tfn()\n\t\tb = true\n\t}\n\treturn\n}"} {"input": "package coinbase\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestBuys(t *testing.T) {\n}\n\nfunc createBuysClient(t *testing.T) (c *Client) ", "output": "{\n\tc = &Client{\n\t\tAPIKey: os.Getenv(\"COINBASE_API_KEY\"),\n\t}\n\n\tif c.APIKey == \"\" {\n\t\tt.Skip(\"Coinbase api key is missing (should be in the COINBASE_API_KEY environment variable)\")\n\t}\n\n\treturn c\n}"} {"input": "package commands\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"os\"\n\t\"strings\"\n)\n\n\n\nfunc acceptableCharset(contentTypes []string) bool {\n\tfor _, cType := range contentTypes {\n\t\tif strings.Index(cType, \"json\") != -1 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc Get(url string) ", "output": "{\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(2)\n\t}\n\n\tif response.Status != \"200 OK\" {\n\t\tfmt.Println(response.Status)\n\t\tos.Exit(2)\n\t}\n\n\tb, _ := httputil.DumpResponse(response, false)\n\tfmt.Print(string(b))\n\n\tcontentTypes := response.Header[\"Content-Type\"]\n\tif !acceptableCharset(contentTypes) {\n\t\tfmt.Println(\"Cannot handle\", contentTypes)\n\t\tos.Exit(4)\n\t}\n\n\tvar buf [512]byte\n\treader := response.Body\n\tfor {\n\t\tn, err := reader.Read(buf[0:])\n\t\tif err != nil {\n\t\t\tos.Exit(0)\n\t\t}\n\t\tfmt.Print(string(buf[0:n]))\n\t}\n\tos.Exit(0)\n}"} {"input": "package upgrader\n\nimport (\n\t\"github.com/juju/juju/agent/tools\"\n\t\"github.com/juju/juju/version\"\n)\n\n\n\ntype UpgradeReadyError struct {\n\tAgentName string\n\tOldTools version.Binary\n\tNewTools version.Binary\n\tDataDir string\n}\n\nfunc (e *UpgradeReadyError) Error() string {\n\treturn \"must restart: an agent upgrade is available\"\n}\n\n\n\n\n\n\nfunc (e *UpgradeReadyError) ChangeAgentTools() error ", "output": "{\n\tagentTools, err := tools.ChangeAgentTools(e.DataDir, e.AgentName, e.NewTools)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.Infof(\"upgraded from %v to %v (%q)\", e.OldTools, agentTools.Version, agentTools.URL)\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\ntype People3 interface {\n\tShow()\n}\n\ntype Student struct{}\n\nfunc (stu *Student) Show() {}\n\n\n\nfunc main() {\n\tpeople3 := live()\n\tfmt.Printf(\"people3 %T %v\\n\", people3, people3)\n\tif people3 == nil {\n\t\tfmt.Println(\"AAAAAAA\")\n\t} else {\n\t\tfmt.Println(\"BBBBBBB\") \n\t}\n\n\tfmt.Println(\"-----------------------------\")\n\tvar stu *Student\n\tpeople4 := stu \n\tfmt.Printf(\"people4 %T %v\\n\", people4, people4)\n\tif people4 == nil {\n\t\tfmt.Println(\"AAAAAAA\")\n\t} else {\n\t\tfmt.Println(\"BBBBBBB\")\n\t}\n}\n\nfunc live() People3 ", "output": "{\n\tvar stu *Student\n\tfmt.Println(stu)\n\treturn stu\n}"} {"input": "package engine\n\nimport \"testing\"\n\ntype DownloaderTestData struct {\n\turl string\n\texpected bool\n}\n\n\n\nfunc TestDefaultDownloader(t *testing.T) ", "output": "{\n\tdatas := []DownloaderTestData{\n\t\tDownloaderTestData{\"http://www.qu.la/book/24868/\", true},\n\t\tDownloaderTestData{\"http://www.baidu.com/\", true},\n\t\tDownloaderTestData{\"www.dummy.com\", false},\n\t}\n\tdownloader := NewDefaultDownloader()\n\n\tfor _, data := range datas {\n\t\tfullPage, _ := downloader.Download(data.url, 5)\n\t\tif (len(fullPage) > 0) != data.expected {\n\t\t\tt.Errorf(\"TestDefaultDownloader fail: Test [%s] expected:[%v], actual:[%v]\", data.url, data.expected, !data.expected)\n\t\t}\n\t}\n}"} {"input": "package storage\n\nimport (\n\t\"context\"\n)\n\n\n\n\nfunc NewTransactionOrDie(ctx context.Context, store Store, params ...TransactionParams) Transaction {\n\ttxn, err := store.NewTransaction(ctx, params...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn txn\n}\n\n\n\n\nfunc ReadOne(ctx context.Context, store Store, path Path) (interface{}, error) {\n\ttxn, err := store.NewTransaction(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer store.Abort(ctx, txn)\n\n\treturn store.Read(ctx, txn, path)\n}\n\n\n\n\nfunc WriteOne(ctx context.Context, store Store, op PatchOp, path Path, value interface{}) error {\n\ttxn, err := store.NewTransaction(ctx, WriteParams)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := store.Write(ctx, txn, op, path, value); err != nil {\n\t\tstore.Abort(ctx, txn)\n\t\treturn err\n\t}\n\n\treturn store.Commit(ctx, txn)\n}\n\n\n\n\n\n\n\nfunc Txn(ctx context.Context, store Store, params TransactionParams, f func(Transaction) error) error ", "output": "{\n\n\ttxn, err := store.NewTransaction(ctx, params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := f(txn); err != nil {\n\t\tstore.Abort(ctx, txn)\n\t\treturn err\n\t}\n\n\treturn store.Commit(ctx, txn)\n}"} {"input": "package comma\n\n\n\nfunc comma(s string) string ", "output": "{\n\tn := len(s)\n\tif n <= 3 {\n\t\treturn s\n\t}\n\treturn comma(s[:n-3]) + \",\" + s[n-3:]\n}"} {"input": "package queue\n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"testing\"\n)\n\ntype mockWorker struct {\n\tObject chan interface{}\n}\n\n\n\nfunc TestNewEventQueue(t *testing.T) {\n\th := &mockWorker{make(chan interface{}, 1)}\n\n\tq := NewTaskQueue(0)\n\tq.AddWorker(h)\n\n\tq.Do(context.Background(), Task{Object: 1})\n\tif <-h.Object != 1 {\n\t\tt.Fatalf(\"TestNewEventQueue failed\")\n\t}\n\n\tq.Do(context.Background(), Task{Object: 11, Async: true})\n\tif <-h.Object != 11 {\n\t\tt.Fatalf(\"TestNewEventQueue failed\")\n\t}\n\n\tq.Run()\n\tq.Add(Task{Object: 2})\n\tif <-h.Object != 2 {\n\t\tt.Fatalf(\"TestNewEventQueue failed\")\n\t}\n\n\tq.Add(Task{Object: 22, Async: true})\n\tif <-h.Object != 22 {\n\t\tt.Fatalf(\"TestNewEventQueue failed\")\n\t}\n\tq.Stop()\n\tq.Add(Task{Object: 3})\n}\n\nfunc (h *mockWorker) Handle(ctx context.Context, obj interface{}) ", "output": "{\n\th.Object <- obj\n}"} {"input": "package timeutil\n\nimport (\n\t\"time\"\n)\n\n\nfunc SetTimeout(t time.Duration, callback func()) {\n\tgo func() {\n\t\ttime.Sleep(t)\n\t\tcallback()\n\t}()\n}\n\n\n\n\n\n\nfunc Nanosecond() int64 {\n\treturn time.Now().UnixNano()\n}\n\n\nfunc Microsecond() int64 {\n\treturn time.Now().UnixNano() / 1e3\n}\n\n\nfunc Millisecond() int64 {\n\treturn time.Now().UnixNano() / 1e6\n}\n\n\nfunc Second() int64 {\n\treturn time.Now().UnixNano() / 1e9\n}\n\n\nfunc Date() string {\n\treturn time.Now().Format(\"2006-01-02\")\n}\n\n\nfunc Datetime() string {\n\treturn time.Now().Format(\"2006-01-02 15:04:05\")\n}\n\n\n\nfunc Format(format string, timestamps ...int64) string {\n\ttimestamp := Second()\n\tif len(timestamps) > 0 {\n\t\ttimestamp = timestamps[0]\n\t}\n\treturn time.Unix(timestamp, 0).Format(format)\n}\n\n\nfunc StrToTime(format string, timestr string) (int64, error) {\n\tt, err := time.Parse(format, timestr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn t.Unix(), nil\n}\n\nfunc SetInterval(t time.Duration, callback func() bool) ", "output": "{\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(t)\n\t\t\tif !callback() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n}"} {"input": "package ar\n\nimport (\n\t\"database/sql\"\n\t\"time\"\n)\n\ntype Executer struct {\n\tdb *sql.DB\n\tlogger *Logger\n}\n\nfunc (e *Executer) Exec(q string, b ...interface{}) (sql.Result, error) {\n\tdefer e.log(time.Now(), q, b...)\n\treturn e.db.Exec(q, b...)\n}\n\n\n\nfunc (e *Executer) log(t time.Time, sql string, args ...interface{}) ", "output": "{\n\te.logger.Print(time.Now().Sub(t), sql, args)\n}"} {"input": "package client\n\nimport \"fmt\"\n\ntype FormationEntry struct {\n\tBalancer string `json:\"balancer\"`\n\tCount int `json:\"count\"`\n\tCPU int `json:\"cpu\"`\n\tHostname string `json:\"hostname\"`\n\tMemory int `json:\"memory\"`\n\tName string `json:\"name\"`\n\tPorts []int `json:\"ports\"`\n}\n\ntype Formation []FormationEntry\n\n\n\ntype FormationOptions struct {\n\tCount string\n\tCPU string\n\tMemory string\n}\n\n\n\n\nfunc (c *Client) SetFormation(app, process string, opts FormationOptions) error {\n\tvar success interface{}\n\n\tparams := map[string]string{}\n\n\tif opts.Count != \"\" {\n\t\tparams[\"count\"] = opts.Count\n\t}\n\n\tif opts.CPU != \"\" {\n\t\tparams[\"cpu\"] = opts.CPU\n\t}\n\n\tif opts.Memory != \"\" {\n\t\tparams[\"memory\"] = opts.Memory\n\t}\n\n\terr := c.Post(fmt.Sprintf(\"/apps/%s/formation/%s\", app, process), params, &success)\n\treturn err\n}\n\nfunc (c *Client) ListFormation(app string) (Formation, error) ", "output": "{\n\tvar formation Formation\n\n\terr := c.Get(fmt.Sprintf(\"/apps/%s/formation\", app), &formation)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn formation, nil\n}"} {"input": "package queue\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Node struct {\n\tvalue interface{}\n\tnext *Node\n}\n\n\n\ntype Queue struct {\n\thead *Node\n\ttail *Node\n}\n\nfunc NewQueue(args ...interface{}) *Queue {\n\tlist := new(Queue)\n\n\tfor _, v := range args {\n\t\tlist.Enqueue(v)\n\t}\n\n\treturn list\n}\n\nfunc (q *Queue) String() string {\n\tnode := q.head\n\n\tvar values []string\n\n\tif node == nil {\n\t\treturn \"[]\"\n\t}\n\n\tfor node.next != nil {\n\t\tvalues = append(values, fmt.Sprintf(\"%v\", node.value))\n\n\t\tnode = node.next\n\t}\n\tvalues = append(values, fmt.Sprintf(\"%v\", node.value))\n\n\treturn fmt.Sprintf(\"[%s]\", strings.Join(values, \", \"))\n}\n\nfunc (q *Queue) Enqueue(value interface{}) {\n\tnewTail := NewNode(value)\n\n\tif q.head == nil {\n\t\tq.head = newTail\n\t\tq.tail = q.head\n\t} else {\n\t\tq.tail.next = newTail\n\t\tq.tail = newTail\n\t}\n}\n\nfunc (q *Queue) Dequeue() (value interface{}, ok bool) {\n\n\tif q.head == nil {\n\t\treturn 0, false\n\t} else {\n\t\tnode := q.head\n\t\tq.head = node.next\n\t\treturn node.value, true\n\t}\n}\n\nfunc (q *Queue) Peek() (value interface{}, ok bool) {\n\tif q.head == nil {\n\t\treturn 0, false\n\t} else {\n\t\treturn q.head.value, true\n\t}\n}\n\nfunc (q *Queue) Empty() bool {\n\tif q.head == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\nfunc NewNode(value interface{}) *Node ", "output": "{\n\tnode := new(Node)\n\tnode.value = value\n\n\treturn node\n}"} {"input": "package options\n\nimport (\n\t\"github.com/spf13/pflag\"\n\n\tjobconfig \"k8s.io/kubernetes/pkg/controller/job/config\"\n)\n\n\ntype JobControllerOptions struct {\n\t*jobconfig.JobControllerConfiguration\n}\n\n\n\n\n\nfunc (o *JobControllerOptions) ApplyTo(cfg *jobconfig.JobControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentJobSyncs = o.ConcurrentJobSyncs\n\n\treturn nil\n}\n\n\nfunc (o *JobControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}\n\nfunc (o *JobControllerOptions) AddFlags(fs *pflag.FlagSet) ", "output": "{\n\tif o == nil {\n\t\treturn\n\t}\n}"} {"input": "package log\n\nimport (\n\t\"github.com/proidiot/gone/errors\"\n\t\"github.com/proidiot/gone/log/opt\"\n\t\"github.com/proidiot/gone/log/pri\"\n)\n\ntype testSyslogger struct {\n\tLastPri pri.Priority\n\tLastMsg interface{}\n\tTriggerError bool\n}\n\nfunc (t *testSyslogger) triggerError() error {\n\tif t.TriggerError {\n\t\treturn errors.New(\"Artificial error triggered in testSyslogger\")\n\t}\n\n\treturn nil\n}\n\nfunc (t *testSyslogger) Syslog(p pri.Priority, msg interface{}) error {\n\tt.LastPri = p\n\tt.LastMsg = msg\n\treturn t.triggerError()\n}\n\nfunc (t *testSyslogger) Openlog(string, opt.Option, pri.Priority) error {\n\treturn t.triggerError()\n}\n\nfunc (t *testSyslogger) Close() error {\n\treturn t.triggerError()\n}\n\ntype limitedSyslogger struct {\n\tLastPri pri.Priority\n\tLastMsg interface{}\n\tTriggerError bool\n}\n\n\n\nfunc (l *limitedSyslogger) Syslog(p pri.Priority, msg interface{}) error {\n\tl.LastPri = p\n\tl.LastMsg = msg\n\treturn l.triggerError()\n}\n\nfunc (l *limitedSyslogger) triggerError() error ", "output": "{\n\tif l.TriggerError {\n\t\treturn errors.New(\n\t\t\t\"Artificial error triggered in limitedSyslogger\",\n\t\t)\n\t}\n\n\treturn nil\n}"} {"input": "package structs\n\nimport \"fmt\"\n\n\ntype Bitmap []byte\n\n\nfunc NewBitmap(size uint) (Bitmap, error) {\n\tif size == 0 {\n\t\treturn nil, fmt.Errorf(\"bitmap must be positive size\")\n\t}\n\tif size&7 != 0 {\n\t\treturn nil, fmt.Errorf(\"bitmap must be byte aligned\")\n\t}\n\tb := make([]byte, size>>3)\n\treturn Bitmap(b), nil\n}\n\n\n\n\n\nfunc (b Bitmap) Size() uint {\n\treturn uint(len(b) << 3)\n}\n\n\nfunc (b Bitmap) Set(idx uint) {\n\tbucket := idx >> 3\n\tmask := byte(1 << (idx & 7))\n\tb[bucket] |= mask\n}\n\n\nfunc (b Bitmap) Check(idx uint) bool {\n\tbucket := idx >> 3\n\tmask := byte(1 << (idx & 7))\n\treturn (b[bucket] & mask) != 0\n}\n\n\nfunc (b Bitmap) Clear() {\n\tfor i := range b {\n\t\tb[i] = 0\n\t}\n}\n\n\n\nfunc (b Bitmap) IndexesInRange(set bool, from, to uint) []int {\n\tvar indexes []int\n\tfor i := from; i < to; i++ {\n\t\tc := b.Check(i)\n\t\tif c && set || !c && !set {\n\t\t\tindexes = append(indexes, int(i))\n\t\t}\n\t}\n\n\treturn indexes\n}\n\nfunc (b Bitmap) Copy() (Bitmap, error) ", "output": "{\n\tif b == nil {\n\t\treturn nil, fmt.Errorf(\"can't copy nil Bitmap\")\n\t}\n\n\traw := make([]byte, len(b))\n\tcopy(raw, b)\n\treturn Bitmap(raw), nil\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"github.com/cross-dev/script-server/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n\t\"strings\"\n)\n\ntype ContainSubstringMatcher struct {\n\tSubstr string\n\tArgs []interface{}\n}\n\n\n\nfunc (matcher *ContainSubstringMatcher) stringToMatch() string {\n\tstringToMatch := matcher.Substr\n\tif len(matcher.Args) > 0 {\n\t\tstringToMatch = fmt.Sprintf(matcher.Substr, matcher.Args...)\n\t}\n\treturn stringToMatch\n}\n\nfunc (matcher *ContainSubstringMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"to contain substring\", matcher.stringToMatch())\n}\n\nfunc (matcher *ContainSubstringMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"not to contain substring\", matcher.stringToMatch())\n}\n\nfunc (matcher *ContainSubstringMatcher) Match(actual interface{}) (success bool, err error) ", "output": "{\n\tactualString, ok := toString(actual)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"ContainSubstring matcher requires a string or stringer. Got:\\n%s\", format.Object(actual, 1))\n\t}\n\n\treturn strings.Contains(actualString, matcher.stringToMatch()), nil\n}"} {"input": "package sqlmock\n\nimport (\n\t\"database/sql/driver\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype AnyTime struct{}\n\n\nfunc (a AnyTime) Match(v driver.Value) bool {\n\t_, ok := v.(time.Time)\n\treturn ok\n}\n\n\n\nfunc TestByteSliceArgument(t *testing.T) {\n\tt.Parallel()\n\tdb, mock, err := New()\n\tif err != nil {\n\t\tt.Errorf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\tusername := []byte(\"user\")\n\tmock.ExpectExec(\"INSERT INTO users\").WithArgs(username).WillReturnResult(NewResult(1, 1))\n\n\t_, err = db.Exec(\"INSERT INTO users(username) VALUES (?)\", username)\n\tif err != nil {\n\t\tt.Errorf(\"error '%s' was not expected, while inserting a row\", err)\n\t}\n\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"there were unfulfilled expections: %s\", err)\n\t}\n}\n\nfunc TestAnyTimeArgument(t *testing.T) ", "output": "{\n\tt.Parallel()\n\tdb, mock, err := New()\n\tif err != nil {\n\t\tt.Errorf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\tmock.ExpectExec(\"INSERT INTO users\").\n\t\tWithArgs(\"john\", AnyTime{}).\n\t\tWillReturnResult(NewResult(1, 1))\n\n\t_, err = db.Exec(\"INSERT INTO users(name, created_at) VALUES (?, ?)\", \"john\", time.Now())\n\tif err != nil {\n\t\tt.Errorf(\"error '%s' was not expected, while inserting a row\", err)\n\t}\n\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"there were unfulfilled expections: %s\", err)\n\t}\n}"} {"input": "package structs\n\nimport \"fmt\"\n\n\ntype Bitmap []byte\n\n\nfunc NewBitmap(size uint) (Bitmap, error) {\n\tif size == 0 {\n\t\treturn nil, fmt.Errorf(\"bitmap must be positive size\")\n\t}\n\tif size&7 != 0 {\n\t\treturn nil, fmt.Errorf(\"bitmap must be byte aligned\")\n\t}\n\tb := make([]byte, size>>3)\n\treturn Bitmap(b), nil\n}\n\n\nfunc (b Bitmap) Copy() (Bitmap, error) {\n\tif b == nil {\n\t\treturn nil, fmt.Errorf(\"can't copy nil Bitmap\")\n\t}\n\n\traw := make([]byte, len(b))\n\tcopy(raw, b)\n\treturn Bitmap(raw), nil\n}\n\n\nfunc (b Bitmap) Size() uint {\n\treturn uint(len(b) << 3)\n}\n\n\nfunc (b Bitmap) Set(idx uint) {\n\tbucket := idx >> 3\n\tmask := byte(1 << (idx & 7))\n\tb[bucket] |= mask\n}\n\n\nfunc (b Bitmap) Check(idx uint) bool {\n\tbucket := idx >> 3\n\tmask := byte(1 << (idx & 7))\n\treturn (b[bucket] & mask) != 0\n}\n\n\nfunc (b Bitmap) Clear() {\n\tfor i := range b {\n\t\tb[i] = 0\n\t}\n}\n\n\n\n\n\nfunc (b Bitmap) IndexesInRange(set bool, from, to uint) []int ", "output": "{\n\tvar indexes []int\n\tfor i := from; i < to; i++ {\n\t\tc := b.Check(i)\n\t\tif c && set || !c && !set {\n\t\t\tindexes = append(indexes, int(i))\n\t\t}\n\t}\n\n\treturn indexes\n}"} {"input": "package sighting\n\nimport (\n\t\"github.com/freetaxii/libstix2/objects\"\n)\n\n\n\n\n\n\ntype Sighting struct {\n\tobjects.CommonObjectProperties\n\tobjects.DescriptionProperty\n\tobjects.SeenProperties\n\tCount int `json:\"count,omitempty\" bson:\"count,omitempty\"`\n\tSightingOfRef string `json:\"sighting_of_ref,omitempty\" bson:\"sighting_of_ref,omitempty\"`\n\tObservedDataRefs []string `json:\"observed_data_refs,omitempty\" bson:\"observed_data_refs,omitempty\"`\n\tWhereSightedRefs []string `json:\"where_sighted_refs,omitempty\" bson:\"where_sighted_refs,omitempty\"`\n\tSummary bool `json:\"summary,omitempty\" bson:\"summary,omitempty\"`\n}\n\n\n\n\n\n\n\n\n\nfunc New() *Sighting {\n\tvar obj Sighting\n\tobj.InitSRO(\"sighting\")\n\treturn &obj\n}\n\nfunc (o *Sighting) GetPropertyList() []string ", "output": "{\n\treturn []string{\"description\", \"first_seen\", \"last_seen\", \"count\", \"sighting_of_ref\", \"observed_data_refs\", \"where_sighted_refs\", \"summary\"}\n}"} {"input": "package a\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n)\n\n\n\nfunc _() ", "output": "{\n\tfmt.Errorf(\"\") \n\t_ = fmt.Errorf(\"\")\n\n\terrors.New(\"\") \n\n\terr := errors.New(\"\")\n\terr.Error() \n\n\tvar buf bytes.Buffer\n\tbuf.String() \n\n\tfmt.Sprint(\"\") \n\tfmt.Sprintf(\"\") \n}"} {"input": "package quote\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestIntegrationQuote(t *testing.T) {\n\tresult := integrationQuote()\n\tif len(result) == 0 {\n\t\tt.Errorf(\"No valid integration quote returned.\")\n\t}\n}\n\nfunc TestAdminQuote(t *testing.T) {\n\tresult := integrationQuote()\n\tif len(result) == 0 {\n\t\tt.Errorf(\"No valid integration quote returned.\")\n\t}\n}\n\nfunc TestCodeQuote(t *testing.T) ", "output": "{\n\tresult := codeQuote()\n\tif len(result) == 0 {\n\t\tt.Errorf(\"No valid quote returned.\")\n\t}\n}"} {"input": "package args\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\n\t\"github.com/spf13/pflag\"\n\tcodegenutil \"k8s.io/code-generator/pkg/util\"\n\t\"k8s.io/gengo/args\"\n)\n\n\ntype CustomArgs struct {\n\tVersionedClientSetPackage string\n\tInternalClientSetPackage string\n\tListersPackage string\n\tSingleDirectory bool\n}\n\n\nfunc NewDefaults() (*args.GeneratorArgs, *CustomArgs) {\n\tgenericArgs := args.Default().WithoutDefaultFlagParsing()\n\tcustomArgs := &CustomArgs{\n\t\tSingleDirectory: false,\n\t}\n\tgenericArgs.CustomArgs = customArgs\n\n\tif pkg := codegenutil.CurrentPackage(); len(pkg) != 0 {\n\t\tgenericArgs.OutputPackagePath = path.Join(pkg, \"pkg/client/informers\")\n\t\tcustomArgs.VersionedClientSetPackage = path.Join(pkg, \"pkg/client/clientset/versioned\")\n\t\tcustomArgs.InternalClientSetPackage = path.Join(pkg, \"pkg/client/clientset/internalversion\")\n\t\tcustomArgs.ListersPackage = path.Join(pkg, \"pkg/client/listers\")\n\t}\n\n\treturn genericArgs, customArgs\n}\n\n\n\n\n\nfunc Validate(genericArgs *args.GeneratorArgs) error {\n\tcustomArgs := genericArgs.CustomArgs.(*CustomArgs)\n\n\tif len(genericArgs.OutputPackagePath) == 0 {\n\t\treturn fmt.Errorf(\"output package cannot be empty\")\n\t}\n\tif len(customArgs.VersionedClientSetPackage) == 0 {\n\t\treturn fmt.Errorf(\"versioned clientset package cannot be empty\")\n\t}\n\tif len(customArgs.ListersPackage) == 0 {\n\t\treturn fmt.Errorf(\"listers package cannot be empty\")\n\t}\n\n\treturn nil\n}\n\nfunc (ca *CustomArgs) AddFlags(fs *pflag.FlagSet) ", "output": "{\n\tfs.StringVar(&ca.InternalClientSetPackage, \"internal-clientset-package\", ca.InternalClientSetPackage, \"the full package name for the internal clientset to use\")\n\tfs.StringVar(&ca.VersionedClientSetPackage, \"versioned-clientset-package\", ca.VersionedClientSetPackage, \"the full package name for the versioned clientset to use\")\n\tfs.StringVar(&ca.ListersPackage, \"listers-package\", ca.ListersPackage, \"the full package name for the listers to use\")\n\tfs.BoolVar(&ca.SingleDirectory, \"single-directory\", ca.SingleDirectory, \"if true, omit the intermediate \\\"internalversion\\\" and \\\"externalversions\\\" subdirectories\")\n}"} {"input": "package model\n\ntype Interface interface {\n\tVisitString(name string, resume func())\n\tVisitInt(name string, resume func())\n\tVisitFloat(name string, resume func())\n\tVisitBool(name string, resume func())\n\tVisitPtr(name string, resume func())\n\tVisitBytes(name string, resume func())\n\tVisitSlice(name string, resume func())\n\tVisitStruct(name string, fields []Field, resume func())\n\tVisitStructField(field Field, resume func())\n\tVisitMap(name string, resume func())\n\tVisitCustom(name string, resume func())\n\tVisitReference(name string, resume func())\n}\n\ntype Visitor struct{}\n\nfunc (self *Visitor) VisitString(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitInt(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitFloat(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBool(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitPtr(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBytes(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitSlice(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStructField(field Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitMap(name string, resume func()) {\n\tresume()\n}\n\n\n\nfunc (self *Visitor) VisitReference(name string, resume func()) {\n\tresume()\n}\n\ntype EmbeddedStructVisitor struct {\n\tInterface\n}\n\nfunc (self *EmbeddedStructVisitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitCustom(name string, resume func()) ", "output": "{\n\tresume()\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\ntype dockerContainer struct {\n\tId string\n\tName string\n\n\tNetworkSettings struct {\n\t\tBridge string\n\t\tGateway string\n\t\tIpAddress string `json:\"IPAddress\"`\n\t\tIpPrefixLen int `json:\"IPPrefixLen\"`\n\t\tMacAddress string\n\t}\n}\n\nfunc dockerInspectContainer(dockerHost, containerName string) (*dockerContainer, error) {\n\tu, err := url.Parse(dockerHost)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed parsing URL '%s': %v\", dockerHost, err)\n\t}\n\tclient := httpClient(u)\n\treq, err := http.NewRequest(\"GET\", u.String()+\"/v1.10/containers/\"+containerName+\"/json\", nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed creating request: %v\", err)\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed HTTP request: %v\", err)\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"not '200 OK': %v\", resp.Status)\n\t}\n\tret := dockerContainer{}\n\terr = json.NewDecoder(resp.Body).Decode(&ret)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed decoding JSON response: %v\", err)\n\t}\n\treturn &ret, nil\n}\n\n\n\nfunc httpClient(u *url.URL) *http.Client ", "output": "{\n\ttransport := &http.Transport{}\n\tswitch u.Scheme {\n\tcase \"tcp\":\n\t\tu.Scheme = \"http\"\n\tcase \"unix\":\n\t\tpath := u.Path\n\t\ttransport.Dial = func(proto, addr string) (net.Conn, error) {\n\t\t\treturn net.Dial(\"unix\", path)\n\t\t}\n\t\tu.Scheme = \"http\"\n\t\tu.Host = \"unix-socket\"\n\t\tu.Path = \"\"\n\t}\n\treturn &http.Client{Transport: transport}\n}"} {"input": "package rpc\n\nimport (\n\t\"net\"\n\t\"net/rpc\"\n\t\"net/rpc/jsonrpc\"\n\t\"time\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"github.com/Cepave/open-falcon-backend/modules/hbs/g\"\n)\n\ntype Hbs int\ntype Agent int\ntype NqmAgent int\n\nfunc Start() {\n\tnqmAgentHbsService.Start()\n\tAgentHeartbeatService.Start()\n\n\taddr := g.Config().Listen\n\n\tserver := rpc.NewServer()\n\tserver.Register(new(Agent))\n\tserver.Register(new(Hbs))\n\tserver.Register(new(NqmAgent))\n\n\tl, e := net.Listen(\"tcp\", addr)\n\tif e != nil {\n\t\tlog.Fatalln(\"listen error:\", e)\n\t} else {\n\t\tlog.Println(\"listening\", addr)\n\t}\n\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"listener accept fail:\", err)\n\t\t\ttime.Sleep(time.Duration(100) * time.Millisecond)\n\t\t\tcontinue\n\t\t}\n\t\tgo server.ServeCodec(jsonrpc.NewServerCodec(conn))\n\t}\n}\n\n\nfunc Stop() ", "output": "{\n\tnqmAgentHbsService.Stop()\n\tAgentHeartbeatService.Stop()\n}"} {"input": "package classfile\n\nimport \"encoding/binary\"\n\ntype ClassReader struct {\n\tdata []byte \n}\n\nfunc (self *ClassReader) readUint8() uint8 {\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16() uint16 {\n\tval := binary.BigEndian.Uint16(self.data)\n\tself.data = self.data[2:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint32() uint32 {\n\tval := binary.BigEndian.Uint32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint64() uint64 {\n\tval := binary.BigEndian.Uint64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\n\n\nfunc (self *ClassReader) readBytes(n uint32) []byte {\n\tbytes := self.data[:n]\n\tself.data = self.data[n:]\n\treturn bytes\n}\n\nfunc (self *ClassReader) readUint16s() []uint16 ", "output": "{\n\tn := self.readUint16()\n\ts := make([]uint16, n)\n\tfor i := range s {\n\t\ts[i] = self.readUint16()\n\t}\n\treturn s\n}"} {"input": "package polly\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/awstesting/unit\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestPresign(t *testing.T) {\n\tsvc := New(unit.Session, &aws.Config{Region: aws.String(\"us-west-2\")})\n\tr, _ := svc.SynthesizeSpeechRequest(&SynthesizeSpeechInput{\n\t\tText: aws.String(\"Moo\"),\n\t\tOutputFormat: aws.String(\"mp3\"),\n\t\tVoiceId: aws.String(\"Foo\"),\n\t})\n\turl, err := r.Presign(time.Second)\n\tassert.NoError(t, err)\n\tassert.Regexp(t, `^https://polly.us-west-2.amazonaws.com/v1/speech\\?.*?OutputFormat=mp3.*?Text=Moo.*?VoiceId=Foo.*`, url)\n}\n\nfunc TestRestGETStrategy(t *testing.T) ", "output": "{\n\tsvc := New(unit.Session, &aws.Config{Region: aws.String(\"us-west-2\")})\n\tr, _ := svc.SynthesizeSpeechRequest(nil)\n\terr := restGETPresignStrategy(r)\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"GET\", r.HTTPRequest.Method)\n\tassert.NotEqual(t, nil, r.Operation.BeforePresignFn)\n}"} {"input": "package azurerm\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/acctest\"\n\t\"github.com/hashicorp/terraform/helper/resource\"\n)\n\n\n\nfunc TestAccAzureRMNetworkWatcher_importComplete(t *testing.T) {\n\trInt := acctest.RandInt()\n\tresourceName := \"azurerm_network_watcher.test\"\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testCheckAzureRMNetworkWatcherDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAzureRMNetworkWatcher_complete(rInt, testLocation()),\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName: resourceName,\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAzureRMNetworkWatcher_importBasic(t *testing.T) ", "output": "{\n\trInt := acctest.RandInt()\n\tresourceName := \"azurerm_network_watcher.test\"\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testCheckAzureRMNetworkWatcherDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAzureRMNetworkWatcher_basic(rInt, testLocation()),\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName: resourceName,\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}"} {"input": "package luhn\n\nimport \"testing\"\n\nvar validTests = []struct {\n\tn string\n\tok bool\n}{\n\t{\"738\", false},\n\t{\"8739567\", true},\n\t{\"1111\", false},\n\t{\"8763\", true},\n\t{\" \", false},\n\t{\"\", false},\n\t{\"2323 2005 7766 3554\", true},\n}\n\nvar addTests = []struct{ raw, luhn string }{\n\t{\"123\", \"1230\"},\n\t{\"873956\", \"8739567\"},\n\t{\"837263756\", \"8372637564\"},\n\t{\"2323 2005 7766 355\", \"2323 2005 7766 3554\"},\n}\n\nfunc TestValid(t *testing.T) {\n\tfor _, test := range validTests {\n\t\tif ok := Valid(test.n); ok != test.ok {\n\t\t\tt.Fatalf(\"Valid(%s) = %t, want %t.\", test.n, ok, test.ok)\n\t\t}\n\t}\n}\n\n\n\nfunc BenchmarkValid(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tValid(\"2323 2005 7766 3554\")\n\t}\n}\n\nfunc BenchmarkAddCheck(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tAddCheck(\"2323 2005 7766 355\")\n\t}\n}\n\nfunc TestAddCheck(t *testing.T) ", "output": "{\n\tfor _, test := range addTests {\n\t\tif luhn := AddCheck(test.raw); luhn != test.luhn {\n\t\t\tt.Fatalf(\"AddCheck(%s) = %s, want %s.\", test.raw, luhn, test.luhn)\n\t\t}\n\t}\n}"} {"input": "package web\n\nimport (\n\t\"net/http\"\n\t\"text/template\"\n\n\t\"github.com/jamiefdhurst/journal/pkg/controller\"\n)\n\n\ntype BadRequest struct {\n\tcontroller.Super\n}\n\n\nfunc (c *BadRequest) Run(response http.ResponseWriter, request *http.Request) {\n\tresponse.WriteHeader(http.StatusNotFound)\n\n\ttemplate, _ := template.ParseFiles(\n\t\t\"./web/templates/_layout/default.tmpl\",\n\t\t\"./web/templates/error.tmpl\")\n\ttemplate.ExecuteTemplate(response, \"layout\", c)\n}\n\n\n\n\nfunc RunBadRequest(response http.ResponseWriter, request *http.Request, container interface{}) ", "output": "{\n\terrorController := BadRequest{}\n\terrorController.Init(container, []string{})\n\terrorController.Run(response, request)\n}"} {"input": "package jpsplus\n\nimport (\n\t\"container/heap\"\n)\n\ntype PriorityQueue struct {\n\tpos int\n\tnode map[int]*Node\n}\n\nfunc newPriorityQueue() *PriorityQueue {\n\tp := new(PriorityQueue)\n\tp.node = make(map[int]*Node)\n\treturn p\n}\n\nfunc (p *PriorityQueue) Len() int {\n\treturn len(p.node)\n}\n\nfunc (p *PriorityQueue) Less(i, j int) bool {\n\treturn p.node[i].finalCost < p.node[j].finalCost\n}\n\nfunc (p *PriorityQueue) Swap(i, j int) {\n\tp.node[i], p.node[j] = p.node[j], p.node[i]\n\tp.node[i].heapIndex = i\n\tp.node[j].heapIndex = j\n}\n\n\n\nfunc (p *PriorityQueue) Pop() interface{} {\n\tp.pos--\n\titem := p.node[p.pos]\n\tdelete(p.node, p.pos)\n\treturn item\n}\n\nfunc (p *PriorityQueue) PushNode(n *Node) {\n\theap.Push(p, n)\n}\n\nfunc (p *PriorityQueue) PopNode() *Node {\n\treturn heap.Pop(p).(*Node)\n}\n\nfunc (p *PriorityQueue) RemoveNode(n *Node) {\n\theap.Remove(p, n.heapIndex)\n}\n\nfunc (p *PriorityQueue) Push(x interface{}) ", "output": "{\n\titem, ok := x.(*Node)\n\tif ok {\n\t\titem.heapIndex = p.pos\n\t\tp.node[p.pos] = item\n\t\tp.pos++\n\t}\n}"} {"input": "package examples\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\n\t\"github.com/goml/gobrain\"\n\t\"github.com/goml/gobrain/persist\"\n)\n\n\n\nfunc Load(filename string) ", "output": "{\n\trand.Seed(0)\n\n\tff := &gobrain.FeedForward{}\n\n\terr := persist.Load(filename, &ff)\n\tif err != nil {\n\t\tlog.Println(\"impossible to load network from file: \", err.Error())\n\t}\n\n\tinputs := []float64{1, 1}\n\n\tresult := ff.Update(inputs)\n\n\tfmt.Println(result)\n}"} {"input": "package acquire\n\nimport \"math/rand\"\n\n\n\nfunc _genTestGame() (*Game, *PlayerRandom) {\n\tr := rand.New(rand.NewSource(0))\n\tp1 := NewPlayerRandom(r)\n\treturn NewGame(r, []Player{p1}), p1\n}\n\nfunc genGameParams() (r *rand.Rand, players []Player) {\n\tr = rand.New(rand.NewSource(0))\n\tplayers = []Player{NewPlayerRandom(r)}\n\treturn\n}\n\nfunc countTiles(c *PieceCollection) [BoardHeight][BoardWidth]int ", "output": "{\n\tvar tileCount [BoardHeight][BoardWidth]int\n\n\tfor _, p := range c.Pieces {\n\t\ttileCount[p.Row][p.Col]++\n\t}\n\n\treturn tileCount\n}"} {"input": "package mailgun\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/getfider/fider/app/models/dto\"\n\t\"github.com/getfider/fider/app/pkg/bus\"\n\t\"github.com/getfider/fider/app/pkg/env\"\n\t\"github.com/getfider/fider/app/pkg/log\"\n)\n\n\n\n\nvar baseURLs = map[string]string{\n\t\"US\": \"https://api.mailgun.net/v3/%s\",\n\t\"EU\": \"https://api.eu.mailgun.net/v3/%s\",\n}\n\nfunc init() {\n\tbus.Register(Service{})\n}\n\ntype Service struct{}\n\n\n\nfunc (s Service) Category() string {\n\treturn \"email\"\n}\n\nfunc (s Service) Enabled() bool {\n\treturn env.Config.Email.Type == \"mailgun\"\n}\n\nfunc (s Service) Init() {\n\tbus.AddListener(sendMail)\n\tbus.AddHandler(fetchRecentSupressions)\n}\n\n\n\nfunc getEndpoint(ctx context.Context, domain, path string) string {\n\tvar regionCode = env.Config.Email.Mailgun.Region\n\tregionCode = strings.ToUpper(regionCode)\n\n\tif len(regionCode) < 1 {\n\t\tregionCode = \"US\"\n\t} else if len(baseURLs[regionCode]) < 1 {\n\t\tlog.Warnf(ctx,\n\t\t\t\"Unknown Mailgun region code '@{Code}' configured - falling back to 'US'\",\n\t\t\tdto.Props{\n\t\t\t\t\"Code\": env.Config.Email.Mailgun.Region,\n\t\t\t},\n\t\t)\n\n\t\tregionCode = \"US\"\n\t}\n\n\treturn fmt.Sprintf(baseURLs[regionCode], domain) + path\n}\n\nfunc (s Service) Name() string ", "output": "{\n\treturn \"Mailgun\"\n}"} {"input": "package mysql\n\nimport (\n\t\"github.com/jmoiron/sqlx\"\n\t\"github.com/upframe/shopy\"\n)\n\n\ntype LinkService struct {\n\tDB *sqlx.DB\n}\n\nvar linkMap = map[string]string{\n\t\"Hash\": \"hash\",\n\t\"User\": \"user_id\",\n\t\"Path\": \"path\",\n\t\"Used\": \"used\",\n\t\"Time\": \"time\",\n\t\"Expires\": \"expires\",\n}\n\n\n\n\n\nfunc (s *LinkService) Gets(first, limit int, order string) ([]*shopy.Link, error) {\n\tlinks := []*shopy.Link{}\n\tvar err error\n\n\torder = fieldsToColumns(linkMap, order)[0]\n\n\tif limit == 0 {\n\t\terr = s.DB.Select(&links, \"SELECT * FROM links ORDER BY ?\", order)\n\t} else {\n\t\terr = s.DB.Select(&links, \"SELECT * FROM links ORDER BY ? LIMIT ? OFFSET ?\", order, limit, first)\n\t}\n\n\treturn links, err\n}\n\n\nfunc (s *LinkService) Create(l *shopy.Link) error {\n\t_, err := s.DB.NamedExec(insertQuery(\"links\", getAllColumns(linkMap)), l)\n\treturn err\n}\n\n\nfunc (s *LinkService) Update(l *shopy.Link, fields ...string) error {\n\t_, err := s.DB.NamedExec(updateQuery(\"links\", \"hash\", fieldsToColumns(linkMap, fields...)), l)\n\treturn err\n}\n\n\nfunc (s *LinkService) Delete(hash string) error {\n\tl, err := s.Get(hash)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tl.Used = true\n\treturn s.Update(l, \"Used\")\n}\n\nfunc (s *LinkService) Get(hash string) (*shopy.Link, error) ", "output": "{\n\tlink := &shopy.Link{}\n\terr := s.DB.Get(link, \"SELECT * FROM links WHERE hash=?\", hash)\n\n\treturn link, err\n}"} {"input": "package reuseport\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"syscall\"\n\n\t\"github.com/inverse-inc/packetfence/go/coredns/plugin/pkg/log\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\nfunc control(network, address string, c syscall.RawConn) error {\n\tc.Control(func(fd uintptr) {\n\t\tif err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil {\n\t\t\tlog.Warningf(\"Failed to set SO_REUSEPORT on socket: %s\", err)\n\t\t}\n\t})\n\treturn nil\n}\n\n\n\n\n\n\n\nfunc ListenPacket(network, addr string) (net.PacketConn, error) {\n\tlc := net.ListenConfig{Control: control}\n\treturn lc.ListenPacket(context.Background(), network, addr)\n}\n\nfunc Listen(network, addr string) (net.Listener, error) ", "output": "{\n\tlc := net.ListenConfig{Control: control}\n\treturn lc.Listen(context.Background(), network, addr)\n}"} {"input": "package doc\n\nimport (\n\t\"go/ast\"\n\t\"go/token\"\n)\n\n\ntype Package struct {\n\tDoc string\n\tName string\n\tImportPath string\n\tImports []string\n\tFilenames []string\n\tNotes map[string][]*Note\n\n\tBugs []string\n\n\tConsts []*Value\n\tTypes []*Type\n\tVars []*Value\n\tFuncs []*Func\n}\n\n\ntype Value struct {\n\tDoc string\n\tNames []string \n\tDecl *ast.GenDecl\n\n\torder int\n}\n\n\ntype Type struct {\n\tDoc string\n\tName string\n\tDecl *ast.GenDecl\n\n\tConsts []*Value \n\tVars []*Value \n\tFuncs []*Func \n\tMethods []*Func \n}\n\n\ntype Func struct {\n\tDoc string\n\tName string\n\tDecl *ast.FuncDecl\n\n\tRecv string \n\tOrig string \n\tLevel int \n}\n\n\n\n\n\ntype Note struct {\n\tPos, End token.Pos \n\tUID string \n\tBody string \n}\n\n\ntype Mode int\n\nconst (\n\tAllDecls Mode = 1 << iota\n\n\tAllMethods\n)\n\n\n\n\n\n\nfunc New(pkg *ast.Package, importPath string, mode Mode) *Package ", "output": "{\n\tvar r reader\n\tr.readPackage(pkg, mode)\n\tr.computeMethodSets()\n\tr.cleanupTypes()\n\treturn &Package{\n\t\tDoc: r.doc,\n\t\tName: pkg.Name,\n\t\tImportPath: importPath,\n\t\tImports: sortedKeys(r.imports),\n\t\tFilenames: r.filenames,\n\t\tNotes: r.notes,\n\t\tBugs: noteBodies(r.notes[\"BUG\"]),\n\t\tConsts: sortedValues(r.values, token.CONST),\n\t\tTypes: sortedTypes(r.types, mode&AllMethods != 0),\n\t\tVars: sortedValues(r.values, token.VAR),\n\t\tFuncs: sortedFuncs(r.funcs, true),\n\t}\n}"} {"input": "package model\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestPostListJson(t *testing.T) ", "output": "{\n\n\tpl := PostList{}\n\tp1 := &Post{Id: NewId(), Message: NewId()}\n\tpl.AddPost(p1)\n\tp2 := &Post{Id: NewId(), Message: NewId()}\n\tpl.AddPost(p2)\n\n\tpl.AddOrder(p1.Id)\n\tpl.AddOrder(p2.Id)\n\n\tjson := pl.ToJson()\n\trpl := PostListFromJson(strings.NewReader(json))\n\n\tif rpl.Posts[p1.Id].Message != p1.Message {\n\t\tt.Fatal(\"failed to serialize\")\n\t}\n\n\tif rpl.Posts[p2.Id].Message != p2.Message {\n\t\tt.Fatal(\"failed to serialize\")\n\t}\n\n\tif rpl.Order[1] != p2.Id {\n\t\tt.Fatal(\"failed to serialize\")\n\t}\n}"} {"input": "package libfuse\n\nimport (\n\t\"os\"\n\n\t\"bazil.org/fuse\"\n\t\"bazil.org/fuse/fs\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\ntype Alias struct {\n\trealPath string\n\tinode uint64\n}\n\nvar _ fs.Node = (*Alias)(nil)\n\n\n\n\nvar _ fs.NodeReadlinker = (*Alias)(nil)\n\n\nfunc (a *Alias) Readlink(ctx context.Context, req *fuse.ReadlinkRequest) (string, error) {\n\treturn a.realPath, nil\n}\n\nfunc (*Alias) Attr(ctx context.Context, a *fuse.Attr) error ", "output": "{\n\ta.Mode = os.ModeSymlink | 0777\n\treturn nil\n}"} {"input": "package locus\n\nimport (\n\t\"github.com/gocircuit/circuit/use/circuit\"\n)\n\nfunc init() {\n\tcircuit.RegisterValue(XLocus{})\n}\n\ntype XLocus struct {\n\tl *Locus\n}\n\nfunc (x XLocus) GetPeers() []*Peer {\n\treturn x.l.GetPeers()\n}\n\nfunc (x XLocus) Self() interface{} {\n\treturn x.l.Self()\n}\n\n\ntype YLocus struct {\n\tX circuit.PermX\n}\n\n\n\nfunc (y YLocus) Self() *Peer {\n\treturn y.X.Call(\"Self\")[0].(*Peer)\n}\n\nfunc (y YLocus) GetPeers() map[string]*Peer ", "output": "{\n\tr := make(map[string]*Peer)\n\tfor _, p := range y.X.Call(\"GetPeers\")[0].([]*Peer) {\n\t\tr[p.Key()] = p\n\t}\n\treturn r\n}"} {"input": "package options\n\nimport (\n\t\"strings\"\n\n\t\"github.com/pkg/errors\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/pflag\"\n)\n\ntype ClusterEditConfig struct {\n\tClusterName string\n\tFile string\n\tKubernetesVersion string\n\tLocked bool\n\tOutput string\n}\n\n\n\nfunc (c *ClusterEditConfig) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVarP(&c.File, \"file\", \"f\", c.File, \"Load cluster data from file\")\n\tfs.StringVar(&c.KubernetesVersion, \"kubernetes-version\", c.KubernetesVersion, \"Kubernetes version\")\n\tfs.BoolVar(&c.Locked, \"locked\", c.Locked, \"If true, locks cluster from deletion\")\n\tfs.StringVarP(&c.Output, \"output\", \"o\", c.Output, \"Output format. One of: yaml|json.\")\n\n}\n\nfunc (c *ClusterEditConfig) ValidateFlags(cmd *cobra.Command, args []string) error {\n\tif cmd.Flags().Changed(\"file\") {\n\t\tif len(args) != 0 {\n\t\t\treturn errors.New(\"no argument can be provided when --file flag is used\")\n\t\t}\n\t}\n\tif len(args) == 0 {\n\t\treturn errors.New(\"missing cluster name\")\n\t}\n\tif len(args) > 1 {\n\t\treturn errors.New(\"multiple cluster name provided\")\n\t}\n\tc.ClusterName = strings.ToLower(args[0])\n\treturn nil\n}\n\nfunc (c *ClusterEditConfig) CheckForUpdateFlags() bool {\n\tif c.Locked || c.KubernetesVersion != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc NewClusterEditConfig() *ClusterEditConfig ", "output": "{\n\treturn &ClusterEditConfig{\n\t\tClusterName: \"\",\n\t\tFile: \"\",\n\t\tKubernetesVersion: \"\",\n\t\tLocked: false,\n\t\tOutput: \"yaml\",\n\t}\n}"} {"input": "package olog\n\nimport (\n\t\"fmt\"\n)\n\n\ntype DirectLogger struct {\n\twriters map[string]Writer\n}\n\n\n\n\n\nfunc (dl *DirectLogger) Log(level Level,\n\tmodule string,\n\tfmtstr string,\n\targs ...interface{}) {\n\tif level == PrintLevel {\n\t\treturn\n\t}\n\tfmtstr = ToString(level) + \" [\" + module + \"] \" + fmtstr\n\tmsg := fmt.Sprintf(fmtstr, args...)\n\tfor _, writer := range dl.writers {\n\t\tif writer.IsEnabled() {\n\t\t\twriter.Write(msg)\n\t\t}\n\t}\n}\n\n\nfunc (dl *DirectLogger) RegisterWriter(writer Writer) {\n\tif writer != nil {\n\t\tdl.writers[writer.UniqueID()] = writer\n\t}\n}\n\n\nfunc (dl *DirectLogger) RemoveWriter(uniqueID string) {\n\tdelete(dl.writers, uniqueID)\n}\n\n\nfunc (dl *DirectLogger) GetWriter(uniqueID string) (writer Writer) {\n\treturn dl.writers[uniqueID]\n}\n\nfunc NewDirectLogger() *DirectLogger ", "output": "{\n\treturn &DirectLogger{\n\t\twriters: make(map[string]Writer),\n\t}\n}"} {"input": "package category\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/vapi/tags\"\n)\n\ntype ls struct {\n\t*flags.ClientFlag\n\t*flags.OutputFlag\n}\n\nfunc init() {\n\tcli.Register(\"tags.category.ls\", &ls{})\n}\n\nfunc (cmd *ls) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.ClientFlag, ctx = flags.NewClientFlag(ctx)\n\tcmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)\n\tcmd.ClientFlag.Register(ctx, f)\n\tcmd.OutputFlag.Register(ctx, f)\n}\n\nfunc (cmd *ls) Process(ctx context.Context) error {\n\tif err := cmd.ClientFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn cmd.OutputFlag.Process(ctx)\n}\n\nfunc (cmd *ls) Description() string {\n\treturn `List all categories.\n\nExamples:\n govc tags.category.ls\n govc tags.category.ls -json | jq .`\n}\n\ntype lsResult []tags.Category\n\nfunc (r lsResult) Write(w io.Writer) error {\n\tfor _, c := range r {\n\t\tfmt.Fprintln(w, c.Name)\n\t}\n\treturn nil\n}\n\n\n\nfunc (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error ", "output": "{\n\tc, err := cmd.RestClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tl, err := tags.NewManager(c).GetCategories(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn cmd.WriteResult(lsResult(l))\n}"} {"input": "package core\n\nimport (\n\t\"html/template\" \n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Server struct {\n\tPrefix string \n\tTemplates map[string]*template.Template \n\tData DataStore\n\tUsers *UserStore\n}\n\nfunc NewServer(name string) *Server {\n\tprefix := Sanitize(name)\n\ttmpl := make(map[string]*template.Template) \n\tdata := NewDataStore(prefix)\n\ts := &Server{Prefix: prefix, Templates: tmpl, Data: data} \n\treturn s\n}\n\n\n\n\nfunc (s *Server) AddHandler(path string, handler http.HandlerFunc) {\n\turl := s.Prefix + \"/\" + path\n\tif s.Prefix != \"\" { \n\t\turl = \"/\" + url\n\t}\n\thttp.HandleFunc(url, handler)\n}\n\nfunc (s *Server) AddHandlers(handlers map[string]http.HandlerFunc) {\n\tfor path, handler := range handlers {\n\t\ts.AddHandler(path, handler)\n\t}\n}\n\n\nfunc NewDefaultServer(defaultServer string, includeExit bool) {\n\ts := NewServer(\"\")\n\thandlers := map[string]http.HandlerFunc{\"\": func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, defaultServer, http.StatusFound) }, \"favicon.ico\": func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) }}\n\n\tif includeExit {\n\t\thandlers[\"exit\"] = func(w http.ResponseWriter, r *http.Request) {\n\t\t\ts.Data.Append(\"shutdowns\", []byte(r.RemoteAddr+\" on \"+time.Now().UTC().Format(time.RFC1123)+\"\\n\"))\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\ts.AddHandlers(handlers)\n}\n\nfunc StartServers(port uint) error {\n\treturn http.ListenAndServe(\":\"+strconv.FormatUint(uint64(port), 10), nil)\n}\n\nfunc (s *Server) AddTemplates(where string) error ", "output": "{\n\tlist, err := s.Data.ListData(where)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, name := range list {\n\t\tif name[len(name)-1] == '~' {\n\t\t\tcontinue\n\t\t}\n\t\tdata, err := s.Data.Load(where + name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttmpl, err := template.New(name).Parse(string(data))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Templates[name] = tmpl\n\t}\n\treturn nil\n}"} {"input": "package mysort\n\n\n\n\nfunc BubbleSort(arr []int) []int ", "output": "{\n\tswapped := true\n\tfor swapped {\n\t\tswapped = false\n\t\tfor i := 0; i < len(arr)-1; i++ {\n\t\t\tif arr[i+1] < arr[i] {\n\t\t\t\tarr[i], arr[i+1] = arr[i+1], arr[i]\n\t\t\t\tswapped = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn arr\n}"} {"input": "package main\n\nimport \"sync\"\nimport \"time\"\nimport \"fmt\"\n\ntype SyncMap struct {\n lock *sync.RWMutex\n hm map[int]string\n}\n\n\n\nfunc (m *SyncMap) Put (k int, v string) {\n m.lock.Lock()\n defer m.lock.Unlock()\n m.hm[k] = v\n}\n\nfunc main() {\n sm := NewSyncMap()\n for j:=0;j<5;j++ {\n sm.Put(j, \"no\")\n }\n time.Sleep(time.Second)\n sm2 := NewSyncMap()\n for i:=0;i<10;i++{\n go sm2.Put(i, \"go\")\n }\n time.Sleep(time.Second)\n fmt.Println(sm)\n fmt.Println(sm2)\n}\n\nfunc NewSyncMap() *SyncMap ", "output": "{\n return &SyncMap{lock: new(sync.RWMutex), hm: make(map[int]string)}\n}"} {"input": "package engine\n\nimport (\n\t\"github.com/nicholaskh/pushd/engine/storage\"\n)\n\n\n\n\n\nfunc fullHistory(channel string, ts int64) (result []interface{}, err error) {\n\tresult, err = storage.FetchHistory(channel, ts)\n\n\treturn\n}\n\nfunc history(channel string, ts int64) (result []interface{}, err error) ", "output": "{\n\tresult = storage.MsgCache.GetRange(channel, ts)\n\n\treturn\n}"} {"input": "package framework\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"k8s.io/kubernetes/pkg/kubelet/remote\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\nvar (\n\tuuidLock sync.Mutex\n\n\tlastUUID uuid.UUID\n)\n\n\n\n\nfunc nowStamp() string {\n\treturn time.Now().Format(time.StampMilli)\n}\n\nfunc log(level string, format string, args ...interface{}) {\n\tfmt.Fprintf(GinkgoWriter, nowStamp()+\": \"+level+\": \"+format+\"\\n\", args...)\n}\n\n\nfunc Logf(format string, args ...interface{}) {\n\tlog(\"INFO\", format, args...)\n}\n\n\nfunc Failf(format string, args ...interface{}) {\n\tmsg := fmt.Sprintf(format, args...)\n\tlog(\"INFO\", msg)\n\tFail(nowStamp()+\": \"+msg, 1)\n}\n\n\nfunc ExpectNoError(err error, explain ...interface{}) {\n\tif err != nil {\n\t\tLogf(\"Unexpected error occurred: %v\", err)\n\t}\n\tExpectWithOffset(1, err).NotTo(HaveOccurred(), explain...)\n}\n\n\nfunc NewUUID() string {\n\tuuidLock.Lock()\n\tdefer uuidLock.Unlock()\n\tresult := uuid.NewUUID()\n\tfor uuid.Equal(lastUUID, result) == true {\n\t\tresult = uuid.NewUUID()\n\t}\n\tlastUUID = result\n\treturn result.String()\n}\n\nfunc LoadCRIClient() (*InternalAPIClient, error) ", "output": "{\n\trService, err := remote.NewRemoteRuntimeService(TestContext.RuntimeServiceAddr, TestContext.RuntimeServiceTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tiService, err := remote.NewRemoteImageService(TestContext.ImageServiceAddr, TestContext.ImageServiceTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &InternalAPIClient{\n\t\tCRIRuntimeClient: rService,\n\t\tCRIImageClient: iService,\n\t}, nil\n}"} {"input": "package localrouter\n\nimport (\n\t\"context\"\n\n\tlocalrouterBuilder \"github.com/sacloud/libsacloud/v2/helper/builder/localrouter\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\n\ntype Builder struct {\n\tID types.ID\n\tName string\n\tDescription string\n\tTags types.Tags\n\tIconID types.ID\n\n\tSwitch *sacloud.LocalRouterSwitch\n\tInterface *sacloud.LocalRouterInterface\n\tPeers []*sacloud.LocalRouterPeer\n\tStaticRoutes []*sacloud.LocalRouterStaticRoute\n\n\tSettingsHash string\n\n\tCaller sacloud.APICaller\n}\n\nfunc BuilderFromResource(ctx context.Context, caller sacloud.APICaller, id types.ID) (*Builder, error) {\n\tclient := sacloud.NewLocalRouterOp(caller)\n\tcurrent, err := client.Read(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Builder{\n\t\tName: current.Name,\n\t\tDescription: current.Description,\n\t\tTags: current.Tags,\n\t\tIconID: current.IconID,\n\t\tSwitch: current.Switch,\n\t\tInterface: current.Interface,\n\t\tPeers: current.Peers,\n\t\tStaticRoutes: current.StaticRoutes,\n\t\tCaller: caller,\n\t}, nil\n}\n\n\n\nfunc (b *Builder) Build(ctx context.Context) (*sacloud.LocalRouter, error) ", "output": "{\n\tbuilder := &localrouterBuilder.Builder{\n\t\tName: b.Name,\n\t\tDescription: b.Description,\n\t\tTags: b.Tags,\n\t\tIconID: b.IconID,\n\t\tSwitch: b.Switch,\n\t\tInterface: b.Interface,\n\t\tPeers: b.Peers,\n\t\tStaticRoutes: b.StaticRoutes,\n\t\tSettingsHash: b.SettingsHash,\n\t\tClient: localrouterBuilder.NewAPIClient(b.Caller),\n\t}\n\n\tif b.ID.IsEmpty() {\n\t\treturn builder.Build(ctx)\n\t}\n\treturn builder.Update(ctx, b.ID)\n}"} {"input": "package lists\n\nimport (\n\t\"github.com/justinsb/gova/collections\"\n)\n\n\n\nfunc Of(items ...interface{}) collections.Sequence ", "output": "{\n\tret := collections.NewArrayList()\n\n\tfor _, i := range items {\n\t\tret.Add(i)\n\t}\n\n\treturn ret\n}"} {"input": "package aprs\n\nimport (\n\t\"fmt\"\n)\n\n\ntype PacketType byte\n\nvar packetTypeNames = map[byte]string{\n\t0x1c: \"Current Mic-E Data (Rev 0 beta)\",\n\t0x1d: \"Old Mic-E Data (Rev 0 beta)\",\n\t'!': \"Position without timestamp (no APRS messaging), or Ultimeter 2000 WX Station\",\n\t'#': \"Peet Bros U-II Weather Station\",\n\t'$': \"Raw GPS data or Ultimeter 2000\",\n\t'%': \"Agrelo DFJr / MicroFinder\",\n\t'\"': \"Old Mic-E Data (but Current data for TM-D700)\",\n\t')': \"Item\",\n\t'*': \"Peet Bros U-II Weather Station\",\n\t',': \"Invalid data or test data\",\n\t'/': \"Position with timestamp (no APRS messaging)\",\n\t':': \"Message\",\n\t';': \"Object\",\n\t'<': \"Station Capabilities\",\n\t'=': \"Position without timestamp (with APRS messaging)\",\n\t'>': \"Status\",\n\t'?': \"Query\",\n\t'@': \"Position with timestamp (with APRS messaging)\",\n\t'T': \"Telemetry data\",\n\t'[': \"Maidenhead grid locator beacon (obsolete)\",\n\t'_': \"Weather Report (without position)\",\n\t'`': \"Current Mic-E Data (not used in TM-D700)\",\n\t'{': \"User-Defined APRS packet format\",\n\t'}': \"Third-party traffic\",\n}\n\n\nfunc (p PacketType) IsMessage() bool {\n\treturn p == ':'\n}\n\n\nfunc (p PacketType) IsThirdParty() bool {\n\treturn p == '}'\n}\n\n\n\nfunc (p PacketType) String() string ", "output": "{\n\tif t, ok := packetTypeNames[byte(p)]; ok {\n\t\treturn t\n\t}\n\treturn fmt.Sprintf(\"Unknown %x\", byte(p))\n}"} {"input": "package email\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"go-common/library/log\"\n\n\tgomail \"gopkg.in/gomail.v2\"\n)\n\n\nfunc (d *Dao) SendMail(date time.Time, body string, subject string, send ...string) (err error) {\n\tlog.Info(\"send mail send:%v\", send)\n\tmsg := gomail.NewMessage()\n\tmsg.SetHeader(\"From\", d.c.Mail.Username)\n\tmsg.SetHeader(\"To\", send...)\n\tmsg.SetHeader(\"Subject\", fmt.Sprintf(subject, date.Year(), date.Month(), date.Day()))\n\tmsg.SetBody(\"text/html\", body)\n\tif err = d.email.DialAndSend(msg); err != nil {\n\t\tlog.Error(\"s.email.DialAndSend error(%v)\", err)\n\t\treturn\n\t}\n\treturn\n}\n\n\n\n\nfunc (d *Dao) SendMailAttach(filename string, subject string, send []string) (err error) ", "output": "{\n\tmsg := gomail.NewMessage()\n\tmsg.SetHeader(\"From\", d.c.Mail.Username)\n\tmsg.SetHeader(\"To\", send...)\n\tmsg.SetHeader(\"Subject\", subject)\n\tmsg.Attach(filename)\n\tif err = d.email.DialAndSend(msg); err != nil {\n\t\tlog.Error(\"s.email.DialAndSend error(%v)\", err)\n\t\treturn\n\t}\n\terr = os.Remove(filename)\n\treturn\n}"} {"input": "package types\n\nimport (\n\t\"database/sql/driver\"\n\t\"encoding/json\"\n\t\"errors\"\n)\n\n\n\n\ntype JSON json.RawMessage\n\n\nfunc (j JSON) String() string {\n\treturn string(j)\n}\n\n\nfunc (j JSON) Unmarshal(dest interface{}) error {\n\treturn json.Unmarshal(j, dest)\n}\n\n\n\n\n\nfunc (j *JSON) UnmarshalJSON(data []byte) error {\n\tif j == nil {\n\t\treturn errors.New(\"json: unmarshal json on nil pointer to json\")\n\t}\n\n\t*j = append((*j)[0:0], data...)\n\treturn nil\n}\n\n\nfunc (j JSON) MarshalJSON() ([]byte, error) {\n\treturn j, nil\n}\n\n\n\nfunc (j JSON) Value() (driver.Value, error) {\n\tvar r json.RawMessage\n\tif err := j.Unmarshal(&r); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn []byte(r), nil\n}\n\n\nfunc (j *JSON) Scan(src interface{}) error {\n\tvar source []byte\n\n\tswitch src.(type) {\n\tcase string:\n\t\tsource = []byte(src.(string))\n\tcase []byte:\n\t\tsource = src.([]byte)\n\tdefault:\n\t\treturn errors.New(\"incompatible type for json\")\n\t}\n\n\t*j = JSON(append((*j)[0:0], source...))\n\n\treturn nil\n}\n\nfunc (j *JSON) Marshal(obj interface{}) error ", "output": "{\n\tres, err := json.Marshal(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*j = res\n\treturn nil\n}"} {"input": "package errors\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n)\n\n\ntype HTTPError struct {\n\tStatusCode int\n\terror\n}\n\n\nfunc (e *HTTPError) Error() string {\n\treturn e.error.Error()\n}\n\n\n\n\n\n\n\nfunc NewBadRequest(err error) *HTTPError {\n\treturn &HTTPError{http.StatusBadRequest, err}\n}\n\n\n\nfunc NewBadRequestString(s string) *HTTPError {\n\treturn NewBadRequest(errors.New(s))\n}\n\n\n\nfunc NewBadRequestMissingParameter(s string) *HTTPError {\n\treturn NewBadRequestString(`Missing parameter \"` + s + `\"`)\n}\n\n\n\nfunc NewBadRequestUnwantedParameter(s string) *HTTPError {\n\treturn NewBadRequestString(`Unwanted parameter \"` + s + `\"`)\n}\n\nfunc NewMethodNotAllowed(method string) *HTTPError ", "output": "{\n\treturn &HTTPError{http.StatusMethodNotAllowed, errors.New(`Method is not allowed:\"` + method + `\"`)}\n}"} {"input": "package backup\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" backup/2019-06-15\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package elasticsearch\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/luopengift/gohttp\"\n)\n\nconst (\n\tenter = '\\n'\n)\n\ntype Meta struct {\n\tIndex string `json:\"_index\"`\n\tType string `json:\"_type\"`\n\tId string `json:\"_id,omitempty\"`\n}\n\n\n\ntype Bulk struct {\n\tIndex *Meta `json:\"index,omitempty\"`\n\tUpdate *Meta `json:\"update,omitempty\"`\n\tSource []byte `json:\"-\"`\n}\n\nfunc NewBulkIndex(_index, _type, _id string, source []byte) *Bulk {\n\treturn &Bulk{\n\t\tIndex: NewMeta(_index, _type, _id),\n\t\tSource: source,\n\t}\n}\nfunc NewBulkUpdate(_index, _type, _id string, source []byte) *Bulk {\n\treturn &Bulk{\n\t\tUpdate: NewMeta(_index, _type, _id),\n\t\tSource: source,\n\t}\n}\n\n\nfunc (b *Bulk) Bytes() ([]byte, error) {\n\tp, err := json.Marshal(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp = append(p, enter)\n\tp = append(p, b.Source...)\n\tp = append(p, enter)\n\treturn p, nil\n}\n\nfunc Send(addr string, p []byte) error {\n\tresp, err := gohttp.NewClient().URLString(\"http://\"+addr).Path(\"/_bulk\").Header(\"Accept\", \"application/json\").Body(p).Post()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.Code() != 200 {\n\t\treturn fmt.Errorf(resp.String())\n\t}\n\treturn nil\n\n}\n\nfunc NewMeta(_index, _type, _id string) *Meta ", "output": "{\n\treturn &Meta{_index, _type, _id}\n}"} {"input": "package stringutil\n\nimport (\n\t\"fmt\"\n\t\"github.com/golang/example/stringutil\"\n\t\"testing\"\n)\n\n\n\nfunc ExampleReverse() {\n\tr := stringutil.Reverse(\"Hello, world\")\n\tfmt.Println(r)\n\n\tr = stringutil.Reverse(\"Hello, 世界\")\n\tfmt.Println(r)\n\n}\n\nfunc TestReverse(t *testing.T) ", "output": "{\n\tfor _, c := range []struct {\n\t\tin, want string\n\t}{\n\t\t{\"Hello, world\", \"dlrow ,olleH\"},\n\t\t{\"Hello, 世界\", \"界世 ,olleH\"},\n\t\t{\"\", \"\"},\n\t} {\n\t\tgot := Reverse(c.in)\n\t\tif got != c.want {\n\t\t\tt.Errorf(\"Reverse(%q) == %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}"} {"input": "package main\n import (\n \"fmt\"\n )\n\n func g() {\n defer func() {\n fmt.Println(\"b\")\n if err := recover();err != nil {\n fmt.Println(err)\n }\n fmt.Println(\"d\")\n }()\n f()\n fmt.Println(\"e\")\n }\n\n \n\n func main() {\n g()\n fmt.Println(\"x\")\n }\n\nfunc f() ", "output": "{\n fmt.Println(\"a\")\n panic(\"a bug occur\")\n fmt.Println(\"c\")\n }"} {"input": "package main\n\n\n\nimport \"C\"\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"unsafe\"\n)\n\nconst LC_NUMERIC = int(C.LC_NUMERIC)\n\n\nfunc setLocale(lc int, locale string) {\n\tl := C.CString(locale)\n\tdefer C.free(unsafe.Pointer(l))\n\tC.setlocale(C.int(lc), l)\n}\n\n\nfunc inSlice(a string, b []string) bool {\n\tfor _, i := range b {\n\t\tif a == i {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc homeDir() string {\n\tif runtime.GOOS == \"windows\" {\n\t\thome := os.Getenv(\"HOMEDRIVE\") + os.Getenv(\"HOMEPATH\")\n\t\tif home == \"\" {\n\t\t\thome = os.Getenv(\"USERPROFILE\")\n\t\t}\n\t\treturn home\n\t}\n\treturn os.Getenv(\"HOME\")\n}\n\n\n\n\nfunc cacheDir() string ", "output": "{\n\tdir := os.Getenv(\"XDG_CACHE_HOME\")\n\tif dir == \"\" {\n\t\tdir = filepath.Join(homeDir(), \".cache\", \"bukanir\")\n\t} else {\n\t\tdir = filepath.Join(dir, \"bukanir\")\n\t}\n\treturn dir\n}"} {"input": "package timer\n\nimport (\n\t\"container/heap\"\n\t\"time\"\n\n\t\"github.com/idealeak/goserver/core\"\n\t\"github.com/idealeak/goserver/core/basic\"\n)\n\ntype startTimerCommand struct {\n\tsrc *basic.Object\n\tta TimerAction\n\tud interface{}\n\tinterval time.Duration\n\ttimes int\n\th TimerHandle\n}\n\nfunc (stc *startTimerCommand) Done(o *basic.Object) error {\n\tdefer o.ProcessSeqnum()\n\n\tte := &TimerEntity{\n\t\tsink: stc.src,\n\t\tud: stc.ud,\n\t\tta: stc.ta,\n\t\tinterval: stc.interval,\n\t\ttimes: stc.times,\n\t\th: stc.h,\n\t\tnext: time.Now().Add(stc.interval),\n\t}\n\n\theap.Push(TimerModule.tq, te)\n\n\treturn nil\n}\n\n\nfunc StartTimer(ta TimerAction, ud interface{}, interval time.Duration, times int) (TimerHandle, bool) {\n\treturn StartTimerByObject(core.CoreObject(), ta, ud, interval, times)\n}\n\n\nfunc StartTimerByObject(src *basic.Object, ta TimerAction, ud interface{}, interval time.Duration, times int) (TimerHandle, bool) {\n\th := generateTimerHandle()\n\tret := TimerModule.SendCommand(\n\t\t&startTimerCommand{\n\t\t\tsrc: src,\n\t\t\tta: ta,\n\t\t\tud: ud,\n\t\t\tinterval: interval,\n\t\t\ttimes: times,\n\t\t\th: h,\n\t\t},\n\t\ttrue)\n\treturn h, ret\n}\n\nfunc AfterTimer(taw TimerActionWrapper, ud interface{}, interval time.Duration) (TimerHandle, bool) ", "output": "{\n\tvar tac = &TimerActionCommon{\n\t\tTaw: taw,\n\t}\n\treturn StartTimerByObject(core.CoreObject(), tac, ud, interval, 1)\n}"} {"input": "package gridq\n\ntype byColRow []*WriteResponse\n\nfunc (p byColRow) Len() int { return len(p) }\nfunc (p byColRow) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byColRow) Less(i, j int) bool {\n\tif p[i].Col < p[j].Col {\n\t\treturn true\n\t} else if p[i].Col > p[j].Col {\n\t\treturn false\n\t} else {\n\t\treturn p[i].Row < p[j].Row\n\t}\n}\n\ntype byRowTimestamp []*ReadResponse\n\nfunc (p byRowTimestamp) Len() int { return len(p) }\nfunc (p byRowTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byRowTimestamp) Less(i, j int) bool {\n\tif p[i].Row < p[j].Row {\n\t\treturn true\n\t} else if p[i].Row > p[j].Row {\n\t\treturn false\n\t} else {\n\t\treturn p[i].State.Timestamp > p[j].State.Timestamp\n\t}\n}\n\ntype byTimestamp []*ReadResponse\n\nfunc (p byTimestamp) Len() int { return len(p) }\n\nfunc (p byTimestamp) Less(i, j int) bool { return p[i].State.Timestamp < p[j].State.Timestamp }\n\nfunc (p byTimestamp) Swap(i, j int) ", "output": "{ p[i], p[j] = p[j], p[i] }"} {"input": "package math\n\n\n\n\n\n\n\nfunc Floor(x float64) float64 {\n\tif x == 0 || x != x || x > MaxFloat64 || x < -MaxFloat64 { \n\t\treturn x\n\t}\n\tif x < 0 {\n\t\td, fract := Modf(-x)\n\t\tif fract != 0.0 {\n\t\t\td = d + 1\n\t\t}\n\t\treturn -d\n\t}\n\td, _ := Modf(x)\n\treturn d\n}\n\n\n\n\n\n\n\nfunc Ceil(x float64) float64 { return -Floor(-x) }\n\n\n\n\n\n\n\n\n\nfunc Trunc(x float64) float64 ", "output": "{\n\tif x == 0 || x != x || x > MaxFloat64 || x < -MaxFloat64 { \n\t\treturn x\n\t}\n\td, _ := Modf(x)\n\treturn d\n}"} {"input": "package server\n\nimport (\n\t\"fmt\"\n\t\"github.com/kshvakov/jsonrpc2\"\n\t\"reflect\"\n)\n\nfunc New() *server {\n\n\treturn &server{\n\t\thandlers: make(map[string]handler),\n\t}\n}\n\ntype server struct {\n\thandlers map[string]handler\n}\n\nfunc (s *server) RegisterFunc(method string, fn interface{}) {\n\n\ts.addHandler(method, reflect.ValueOf(fn))\n}\n\n\n\nfunc (s *server) addHandler(method string, fn reflect.Value) {\n\n\tif _, found := s.handlers[method]; !found {\n\n\t\tft := fn.Type()\n\n\t\tif ft.Kind() == reflect.Ptr {\n\n\t\t\tft = ft.Elem()\n\t\t}\n\n\t\tif ft.NumIn() != 1 || ft.NumOut() != 2 || !ft.In(0).Implements(reflect.TypeOf((*jsonrpc2.Params)(nil)).Elem()) {\n\n\t\t\treturn\n\t\t}\n\n\t\tif !ft.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {\n\n\t\t\treturn\n\t\t}\n\n\t\tparams := ft.In(0)\n\n\t\tif params.Kind() == reflect.Ptr {\n\n\t\t\tparams = params.Elem()\n\t\t}\n\n\t\ts.handlers[method] = handler{\n\t\t\tmethod: fn,\n\t\t\tparams: reflect.New(params).Interface().(jsonrpc2.Params),\n\t\t}\n\n\t} else {\n\n\t\tpanic(fmt.Sprintf(\"Method '%s' is exists\", method))\n\t}\n}\n\nfunc (s *server) RegisterObject(name string, obj interface{}) ", "output": "{\n\n\tfor i := 0; i < reflect.TypeOf(obj).NumMethod(); i++ {\n\n\t\tmethod := reflect.TypeOf(obj).Method(i)\n\n\t\tif method.PkgPath != \"\" {\n\n\t\t\tcontinue\n\t\t}\n\n\t\ts.addHandler(fmt.Sprintf(\"%s.%s\", name, method.Name), reflect.ValueOf(obj).Method(i))\n\t}\n}"} {"input": "package common\n\n\n\n\nimport (\n\t\"strconv\"\n)\n\n\nfunc Atof32(s string) float64 {\n\tf, err := strconv.ParseFloat(s, 32)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn float64(f)\n}\n\n\n\n\n\nfunc Atob(str string) bool {\n\tb, err := strconv.ParseBool(str)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn b\n}\n\n\nfunc Atoi64(str string) int64 {\n\ti, err := strconv.ParseInt(str, 10, 64)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn i\n}\n\n\nfunc Atof64(str string) float64 {\n\ti, err := strconv.ParseFloat(str, 64)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn i\n}\n\nfunc Atoi(s string) int ", "output": "{\n\ti, err := strconv.Atoi(s)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn i\n}"} {"input": "package file\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\n\n\ntype darwinExFileInfo struct {\n\tos.FileInfo\n\tfid FID\n\tpath string\n}\n\n\n\n\n\n\nfunc (fi *darwinExFileInfo) CTime() time.Time {\n\treturn timespecToTime(fi.Sys().(*syscall.Stat_t).Ctimespec)\n}\n\n\nfunc (fi *darwinExFileInfo) ATime() time.Time {\n\treturn timespecToTime(fi.Sys().(*syscall.Stat_t).Atimespec)\n}\n\n\nfunc (fi *darwinExFileInfo) FID() FID {\n\treturn fi.fid\n}\n\n\nfunc (fi *darwinExFileInfo) Path() string {\n\treturn fi.path\n}\n\n\nfunc systemExFileInfo(fi os.FileInfo, path string) *darwinExFileInfo {\n\tfid := FID{\n\t\tIDLow: fi.Sys().(*syscall.Stat_t).Ino,\n\t}\n\tabsolute, _ := filepath.Abs(path)\n\treturn &darwinExFileInfo{\n\t\tFileInfo: fi,\n\t\tfid: fid,\n\t\tpath: filepath.Clean(absolute),\n\t}\n}\n\nfunc timespecToTime(ts syscall.Timespec) time.Time ", "output": "{\n\treturn time.Unix(int64(ts.Sec), int64(ts.Nsec))\n}"} {"input": "package iso20022\n\n\ntype PartyIdentificationAndAccount77 struct {\n\n\tIdentification *PartyIdentification32Choice `xml:\"Id\"`\n\n\tAlternateIdentification *AlternatePartyIdentification5 `xml:\"AltrnId,omitempty\"`\n\n\tSafekeepingAccount *Max35Text `xml:\"SfkpgAcct,omitempty\"`\n\n\tProcessingIdentification *Max35Text `xml:\"PrcgId,omitempty\"`\n\n\tAdditionalInformation *PartyTextInformation1 `xml:\"AddtlInf,omitempty\"`\n}\n\nfunc (p *PartyIdentificationAndAccount77) AddIdentification() *PartyIdentification32Choice {\n\tp.Identification = new(PartyIdentification32Choice)\n\treturn p.Identification\n}\n\nfunc (p *PartyIdentificationAndAccount77) AddAlternateIdentification() *AlternatePartyIdentification5 {\n\tp.AlternateIdentification = new(AlternatePartyIdentification5)\n\treturn p.AlternateIdentification\n}\n\nfunc (p *PartyIdentificationAndAccount77) SetSafekeepingAccount(value string) {\n\tp.SafekeepingAccount = (*Max35Text)(&value)\n}\n\n\n\nfunc (p *PartyIdentificationAndAccount77) AddAdditionalInformation() *PartyTextInformation1 {\n\tp.AdditionalInformation = new(PartyTextInformation1)\n\treturn p.AdditionalInformation\n}\n\nfunc (p *PartyIdentificationAndAccount77) SetProcessingIdentification(value string) ", "output": "{\n\tp.ProcessingIdentification = (*Max35Text)(&value)\n}"} {"input": "package adjuster\n\nimport (\n\t\"github.com/uber/jaeger/model\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\nfunc SortLogFields() Adjuster ", "output": "{\n\treturn Func(func(trace *model.Trace) (*model.Trace, error) {\n\t\tfor _, span := range trace.Spans {\n\t\t\tfor _, log := range span.Logs {\n\t\t\t\toffset := 0\n\t\t\t\tfor i, field := range log.Fields {\n\t\t\t\t\tif field.Key == \"event\" && field.VType == model.StringType {\n\t\t\t\t\t\tif i > 0 {\n\t\t\t\t\t\t\tlog.Fields[0], log.Fields[i] = log.Fields[i], log.Fields[0]\n\t\t\t\t\t\t}\n\t\t\t\t\t\toffset = 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(log.Fields) > 1 {\n\t\t\t\t\tmodel.KeyValues(log.Fields[offset:]).Sort()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn trace, nil\n\t})\n}"} {"input": "package entity\n\n\ntype Config struct{\n\n\tDefaultCredential *Credential\n\n\tHosts map[string]*Credential\n\n\tInputEntries []InputEntry\n\n\tLogging bool\n\tLogPath string\n}\n\n\nfunc NewConfig() *Config {\n\tconfig := new(Config)\n\n\tconfig.DefaultCredential = new(Credential)\n\tconfig.Hosts = make(map[string]*Credential)\n\tconfig.InputEntries = make([]InputEntry, 0)\n\tconfig.Logging = false\n\n\treturn config\n}\n\n\n\n\nfunc (c *Config) GetDefaultCredential(hostName string) (cred *Credential) ", "output": "{\n\tcred, found := c.Hosts[hostName]\n\tif !found {\n\t\tcred = c.DefaultCredential\n\t}\n\treturn\n}"} {"input": "package controllers\n\nimport (\n \"github.com/astaxie/beego\"\n)\n\ntype LeakController struct {\n beego.Controller\n}\n\n\n\nfunc (c *LeakController) Get() ", "output": "{\n\n c.TplName = \"leak.tpl\"\n\n}"} {"input": "package rsets\n\nimport (\n\t\"github.com/pingcap/tidb/context\"\n\t\"github.com/pingcap/tidb/parser/coldef\"\n\t\"github.com/pingcap/tidb/plan\"\n\t\"github.com/pingcap/tidb/plan/plans\"\n)\n\nvar (\n\t_ plan.Planner = (*SelectLockRset)(nil)\n)\n\n\ntype SelectLockRset struct {\n\tSrc plan.Plan\n\tLock coldef.LockType\n}\n\n\n\n\nfunc (r *SelectLockRset) Plan(ctx context.Context) (plan.Plan, error) ", "output": "{\n\treturn &plans.SelectLockPlan{Src: r.Src, Lock: r.Lock}, nil\n}"} {"input": "package main\n\nfunc f1(i int) {\n\tfor j := i - 1; j >= 0; j-- { \n\t}\n}\n\n\n\nfunc f3(s string) {\n\tfor i, l := 0, len(s); i > l; i++ { \n\t}\n}\n\nfunc f4(lower int, a []int) {\n\tfor i := lower - 1; i >= 0; i-- { \n\t\ta[i] = 0\n\t}\n}\n\nfunc f5(upper int, a []int) {\n\tfor i := upper + 1; i < len(a); i-- { \n\t\ta[i] = 0\n\t}\n}\n\nfunc f6(upper uint, a []int) {\n\tfor i := upper + 1; i < uint(len(a)); i-- { \n\t\ta[i] = 0\n\t}\n}\n\nfunc f7(a []int) {\n\tfor i := uint(len(a)) - 1; i < uint(len(a)); i-- { \n\t\ta[i] = 0\n\t}\n}\n\nfunc main() {}\n\nfunc f2(i int, s string) ", "output": "{\n\tfor j := i + 1; j < len(s); j-- { \n\t}\n}"} {"input": "package log5go\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype jsonFormatter struct {\n\ttimeFormat string\n\tlines bool\n}\n\ntype jsonLog struct {\n\tTime string `json:\"time\"`\n\tLevel string `json:\"level\"`\n\tPrefix string `json:\"prefix,omitempty\"`\n\tLine string `json:\"line,omitempty\"`\n\tMsg string `json:\"msg\"`\n\tData map[string]interface{} `json:\"data,omitempty\"`\n}\n\n\n\nfunc (f *jsonFormatter) SetTimeFormat(timeFormat string) {\n\tf.timeFormat = timeFormat\n}\n\nfunc (f *jsonFormatter) SetLines(lines bool) {\n\tf.lines = lines\n}\n\nfunc (f *jsonFormatter) formatLine(caller string, line uint) string {\n\tif !f.lines || caller == \"\" {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%s:%d\", caller, line)\n}\n\nfunc (f *jsonFormatter) Format(tstamp time.Time, level LogLevel, prefix, caller string, line uint, msg string, data Data, out *[]byte) ", "output": "{\n\toutput := jsonLog{\n\t\tTime: tstamp.Format(f.timeFormat),\n\t\tLevel: GetLogLevelString(level),\n\t\tPrefix: prefix,\n\t\tLine: f.formatLine(caller, line),\n\t\tMsg: msg,\n\t\tData: data,\n\t}\n\n\tserialized, err := json.Marshal(output)\n\tif err == nil {\n\t\t*out = append(*out, serialized...)\n\t}\n}"} {"input": "package v1\n\n\n\ntype EnvVarSourceApplyConfiguration struct {\n\tFieldRef *ObjectFieldSelectorApplyConfiguration `json:\"fieldRef,omitempty\"`\n\tResourceFieldRef *ResourceFieldSelectorApplyConfiguration `json:\"resourceFieldRef,omitempty\"`\n\tConfigMapKeyRef *ConfigMapKeySelectorApplyConfiguration `json:\"configMapKeyRef,omitempty\"`\n\tSecretKeyRef *SecretKeySelectorApplyConfiguration `json:\"secretKeyRef,omitempty\"`\n}\n\n\n\nfunc EnvVarSource() *EnvVarSourceApplyConfiguration {\n\treturn &EnvVarSourceApplyConfiguration{}\n}\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithFieldRef(value *ObjectFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.FieldRef = value\n\treturn b\n}\n\n\n\n\n\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithConfigMapKeyRef(value *ConfigMapKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.ConfigMapKeyRef = value\n\treturn b\n}\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithSecretKeyRef(value *SecretKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.SecretKeyRef = value\n\treturn b\n}\n\nfunc (b *EnvVarSourceApplyConfiguration) WithResourceFieldRef(value *ResourceFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration ", "output": "{\n\tb.ResourceFieldRef = value\n\treturn b\n}"} {"input": "package gologger\n\nimport (\n \"fmt\"\n)\n\ntype appender2Console struct {\n}\n\nfunc (self *appender2Console) init() error {\n return nil\n}\n\nfunc (self *appender2Console) close() {\n return\n}\n\n\n\nfunc (self *appender2Console) setNext(n logHandler) {\n return\n}\n\nfunc (self *appender2Console) handle(msg *logMsg) error ", "output": "{\n fmt.Printf(\"%s\\n\", msg.info)\n return nil\n}"} {"input": "package stats\n\nimport (\n\t\"code.google.com/p/probab/dst\"\n\t\"math\"\n\t\"math/rand\"\n)\n\n\n\n\n\n\n\nfunc WeightedSample(w []float64, n int, idx []int) []int {\n\tidx = use_int_slice(idx, n)\n\tfor i := 0; i < n; i++ {\n\t\tidx[i] = int(dst.ChoiceNext(w))\n\t}\n\treturn idx\n}\n\n\n\n\n\n\nfunc LogweightedSample(logw []float64, n int, idx []int) []int {\n\tw := make([]float64, len(logw))\n\tmax, _ := FloatMax(logw)\n\tvar sum float64\n\tfor i, lw := range logw {\n\t\tw[i] = math.Exp(lw - max)\n\t\tsum += w[i]\n\t}\n\tFloatScale(w, 1/sum, w)\n\n\treturn WeightedSample(w, n, idx)\n}\n\nfunc Sample(n, k int, idx []int) []int ", "output": "{\n\tidx = use_int_slice(idx, k)\n\tfor i := 0; i < k; i++ {\n\t\tidx[i] = rand.Intn(n)\n\t}\n\treturn idx\n}"} {"input": "package cache\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc TestCacheRefreshUpTypeAsync(t *testing.T) {\n\tconvey.Convey(\"RefreshUpTypeAsync\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\ttm = time.Now()\n\t\t)\n\t\tctx.Convey(\"When everything goes positive\", func(ctx convey.C) {\n\t\t\tRefreshUpTypeAsync(tm)\n\t\t\tctx.Convey(\"No return values\", func(ctx convey.C) {\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestCacheRefreshUpType(t *testing.T) {\n\tconvey.Convey(\"RefreshUpType\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\ttm = time.Now()\n\t\t)\n\t\tctx.Convey(\"When everything goes positive\", func(ctx convey.C) {\n\t\t\tRefreshUpType(tm)\n\t\t\tctx.Convey(\"No return values\", func(ctx convey.C) {\n\t\t\t})\n\t\t})\n\t})\n}\n\n\n\nfunc TestCacheGetTidName(t *testing.T) ", "output": "{\n\tconvey.Convey(\"GetTidName\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\ttids = int64(0)\n\t\t)\n\t\tctx.Convey(\"When everything goes positive\", func(ctx convey.C) {\n\t\t\ttpNames := GetTidName(tids)\n\t\t\tctx.Convey(\"Then tpNames should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(tpNames, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package sighting\n\nimport (\n\t\"github.com/freetaxii/libstix2/objects\"\n)\n\n\n\n\n\n\ntype Sighting struct {\n\tobjects.CommonObjectProperties\n\tobjects.DescriptionProperty\n\tobjects.SeenProperties\n\tCount int `json:\"count,omitempty\" bson:\"count,omitempty\"`\n\tSightingOfRef string `json:\"sighting_of_ref,omitempty\" bson:\"sighting_of_ref,omitempty\"`\n\tObservedDataRefs []string `json:\"observed_data_refs,omitempty\" bson:\"observed_data_refs,omitempty\"`\n\tWhereSightedRefs []string `json:\"where_sighted_refs,omitempty\" bson:\"where_sighted_refs,omitempty\"`\n\tSummary bool `json:\"summary,omitempty\" bson:\"summary,omitempty\"`\n}\n\n\nfunc (o *Sighting) GetPropertyList() []string {\n\treturn []string{\"description\", \"first_seen\", \"last_seen\", \"count\", \"sighting_of_ref\", \"observed_data_refs\", \"where_sighted_refs\", \"summary\"}\n}\n\n\n\n\n\n\n\n\nfunc New() *Sighting ", "output": "{\n\tvar obj Sighting\n\tobj.InitSRO(\"sighting\")\n\treturn &obj\n}"} {"input": "package upgrade\n\nimport (\n\t\"testing\"\n)\n\nfunc (se *suiteExecution) processOperationGroup(op operationGroup) {\n\tl := se.logger\n\tse.configuration.T.Run(op.groupName, func(t *testing.T) {\n\t\tif len(op.operations) > 0 {\n\t\t\tl.Infof(op.groupTemplate, op.num, len(op.operations))\n\t\t\tfor i, operation := range op.operations {\n\t\t\t\tl.Infof(op.elementTemplate, op.num, i+1, operation.Name())\n\t\t\t\tif se.failed {\n\t\t\t\t\tl.Debugf(skippingOperationTemplate, operation.Name())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\thandler := operation.Handler()\n\t\t\t\tt.Run(operation.Name(), func(t *testing.T) {\n\t\t\t\t\thandler(Context{T: t, Log: l})\n\t\t\t\t})\n\t\t\t\tse.failed = se.failed || t.Failed()\n\t\t\t\tif se.failed {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tl.Infof(op.skippingGroupTemplate, op.num)\n\t\t}\n\t})\n}\n\n\n\nfunc (se *suiteExecution) execute() ", "output": "{\n\tidx := 1\n\toperations := []func(num int){\n\t\tse.installingBase,\n\t\tse.preUpgradeTests,\n\t}\n\tfor _, operation := range operations {\n\t\toperation(idx)\n\t\tidx++\n\t\tif se.failed {\n\t\t\treturn\n\t\t}\n\t}\n\n\tse.startContinualTests(idx)\n\tidx++\n\tif se.failed {\n\t\treturn\n\t}\n\tdefer func() {\n\t\tse.verifyContinualTests(idx)\n\t}()\n\n\toperations = []func(num int){\n\t\tse.upgradeWith,\n\t\tse.postUpgradeTests,\n\t\tse.downgradeWith,\n\t\tse.postDowngradeTests,\n\t}\n\tfor _, operation := range operations {\n\t\toperation(idx)\n\t\tidx++\n\t\tif se.failed {\n\t\t\treturn\n\t\t}\n\t}\n}"} {"input": "package sol\n\n\ntype Operator interface {\n\tWrap(string) string \n}\n\n\nfunc Function(name string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(FuncClause{Name: name})\n}\n\n\nfunc Avg(col Columnar) ColumnElem {\n\treturn Function(AVG, col)\n}\n\n\nfunc Count(col Columnar) ColumnElem {\n\treturn Function(COUNT, col)\n}\n\n\nfunc Date(col Columnar) ColumnElem {\n\treturn Function(DATE, col)\n}\n\n\n\nfunc DatePart(part string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(\n\t\tFuncClause{Name: DATEPART},\n\t).AddOperator(\n\t\tArrayClause{clauses: []Clause{String(part)}, post: true, sep: \", \"},\n\t)\n}\n\n\n\n\n\nfunc Min(col Columnar) ColumnElem {\n\treturn Function(MIN, col)\n}\n\n\nfunc StdDev(col Columnar) ColumnElem {\n\treturn Function(STDDEV, col)\n}\n\n\nfunc Sum(col Columnar) ColumnElem {\n\treturn Function(SUM, col)\n}\n\n\nfunc Variance(col Columnar) ColumnElem {\n\treturn Function(VARIANCE, col)\n}\n\nfunc Max(col Columnar) ColumnElem ", "output": "{\n\treturn Function(MAX, col)\n}"} {"input": "package v1\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/unversioned\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\nconst GroupName = \"\"\n\n\nvar SchemeGroupVersion = unversioned.GroupVersion{Group: GroupName, Version: \"v1\"}\n\nfunc AddToScheme(scheme *runtime.Scheme) {\n\taddKnownTypes(scheme)\n\taddConversionFuncs(scheme)\n}\n\n\nfunc addKnownTypes(scheme *runtime.Scheme) {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t&Project{},\n\t\t&ProjectList{},\n\t\t&ProjectRequest{},\n\t)\n}\n\nfunc (obj *ProjectRequest) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta }\nfunc (obj *Project) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta }\n\n\nfunc (obj *ProjectList) GetObjectKind() unversioned.ObjectKind ", "output": "{ return &obj.TypeMeta }"} {"input": "package grains\n\nimport \"errors\"\n\n\nconst numSquares = 64\n\n\nconst testVersion = 1\n\n\nfunc pow(a uint64, b uint64) (uint64, error) {\n\tif b == 0 {\n\t\treturn 1, nil\n\t} else if b < 0 {\n\t\treturn 0, errors.New(\"Negative exponent not legal\")\n\t}\n\n\tvar y uint64 = uint64(1)\n\tfor b > 1 {\n\t\tif b%2 == 0 {\n\t\t\ta *= a\n\t\t\tb /= 2\n\t\t} else {\n\t\t\ty = a * y\n\t\t\ta *= a\n\t\t\tb = (b - 1) / 2\n\t\t}\n\t}\n\treturn a * y, nil\n}\n\n\nfunc Square(n int) (uint64, error) {\n\tif n < 1 || n > numSquares {\n\t\treturn 0, errors.New(\"Attempted to access square out of bounds\")\n\t}\n\n\tres, _ := pow(2, uint64(n-1))\n\n\treturn res, nil\n}\n\n\n\n\nfunc Total() uint64 ", "output": "{\n\tvar total uint64\n\tfor i := 1; i <= numSquares; i++ {\n\t\tres, _ := Square(i)\n\t\ttotal += res\n\t}\n\treturn total\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/mexisme/go-config/settings\"\n)\n\n\nfunc AddConfigItems(configKeys []string) {\n\tsettings.AddConfigItems(configKeys)\n}\n\n\n\n\n\nfunc ApplyWith(key string, f func(interface{})) {\n\tsettings.ApplyWith(key, f)\n}\n\n\nfunc Get(key string) interface{} {\n\treturn settings.Get(key)\n}\n\n\nfunc GetBool(key string) bool {\n\treturn settings.GetBool(key)\n}\n\n\nfunc GetFloat64(key string) float64 {\n\treturn settings.GetFloat64(key)\n}\n\n\nfunc GetInt(key string) int {\n\treturn settings.GetInt(key)\n}\n\n\nfunc GetString(key string) string {\n\treturn settings.GetString(key)\n}\n\n\nfunc GetStringMap(key string) map[string]interface{} {\n\treturn settings.GetStringMap(key)\n}\n\n\nfunc GetStringMapString(key string) map[string]string {\n\treturn settings.GetStringMapString(key)\n}\n\n\nfunc GetStringSlice(key string) []string {\n\treturn settings.GetStringSlice(key)\n}\n\n\nfunc GetTime(key string) time.Time {\n\treturn settings.GetTime(key)\n}\n\n\nfunc GetDuration(key string) time.Duration {\n\treturn settings.GetDuration(key)\n}\n\n\nfunc IsSet(key string) bool {\n\treturn settings.IsSet(key)\n}\n\n\nfunc AllSettings() map[string]interface{} {\n\treturn settings.AllSettings()\n}\n\nfunc AddConfigItemsWithPFlags(configKeys []string) error ", "output": "{\n\treturn settings.AddConfigItemsWithPFlags(configKeys)\n}"} {"input": "package gtka\n\nimport (\n\t\"github.com/coyim/gotk3adapter/gtki\"\n\t\"github.com/gotk3/gotk3/gtk\"\n)\n\ntype toolButton struct {\n\t*bin\n\tinternal *gtk.ToolButton\n}\n\nfunc WrapToolButtonSimple(v *gtk.ToolButton) gtki.ToolButton {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn &toolButton{WrapBinSimple(&v.Bin).(*bin), v}\n}\n\nfunc WrapToolButton(v *gtk.ToolButton, e error) (gtki.ToolButton, error) {\n\treturn WrapToolButtonSimple(v), e\n}\n\nfunc UnwrapToolButton(v gtki.ToolButton) *gtk.ToolButton {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*toolButton).internal\n}\n\n\n\nfunc (v *toolButton) Add(v1 gtki.Widget) ", "output": "{\n\tv.internal.Add(UnwrapWidget(v1))\n}"} {"input": "package splice\n\nimport ()\n\n\n\nfunc (p *Pair) LoadFrom(fd uintptr, sz int) (int, error) {\n\tpanic(\"not implemented\")\n\treturn 0, nil\n}\n\nfunc (p *Pair) WriteTo(fd uintptr, n int) (int, error) {\n\tpanic(\"not implemented\")\n\treturn 0, nil\n}\n\nfunc (p *Pair) LoadFromAt(fd uintptr, sz int, off int64) (int, error) ", "output": "{\n\tpanic(\"not implemented\")\n\treturn 0, nil\n}"} {"input": "package resources\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/rancher/rancher-compose-executor/project\"\n\t\"github.com/rancher/rancher-compose-executor/project/options\"\n)\n\nfunc DependenciesCreate(p *project.Project) (project.ResourceSet, error) {\n\tdependencies := make([]*Dependency, 0, len(p.Config.Dependencies))\n\tfor name, config := range p.Config.Dependencies {\n\t\tdependencies = append(dependencies, &Dependency{\n\t\t\tproject: p,\n\t\t\tname: name,\n\t\t\ttemplate: config.Template,\n\t\t\tversion: config.Version,\n\t\t})\n\t}\n\treturn &Dependencies{\n\t\tdependencies: dependencies,\n\t}, nil\n}\n\ntype Dependencies struct {\n\tdependencies []*Dependency\n}\n\nfunc (h *Dependencies) Initialize(ctx context.Context, _ options.Options) error {\n\tfor _, dependency := range h.dependencies {\n\t\tif err := dependency.EnsureItExists(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\ntype Dependency struct {\n\tproject *project.Project\n\tname string\n\ttemplate string\n\tversion string\n}\n\n\n\nfunc (d *Dependency) EnsureItExists(ctx context.Context) error ", "output": "{\n\treturn nil\n}"} {"input": "package system\n\nimport (\n\t\"github.com/Graylog2/collector-sidecar/common\"\n\t\"runtime\"\n)\n\ntype Inventory struct {\n}\n\nfunc NewInventory() *Inventory {\n\treturn &Inventory{}\n}\n\nfunc (inv *Inventory) Version() string {\n\treturn common.CollectorVersion\n}\n\n\n\nfunc (inv *Inventory) Darwin() bool {\n\treturn runtime.GOOS == \"darwin\"\n}\n\nfunc (inv *Inventory) Windows() bool {\n\treturn runtime.GOOS == \"windows\"\n}\n\nfunc (inv *Inventory) LinuxPlatform() string {\n\tif runtime.GOOS == \"linux\" {\n\t\treturn common.LinuxPlatformFamily()\n\t} else {\n\t\treturn runtime.GOOS\n\t}\n}\n\nfunc (inv *Inventory) Linux() bool ", "output": "{\n\treturn runtime.GOOS == \"linux\"\n}"} {"input": "package subtitles\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc subDbConformTest(t *testing.T, fileName string, expectedHash string) {\n\tif !exists(fileName) {\n\t\tfmt.Println(\"ERROR thesubdb.com conformance tests missing, run ./hash-conformance-deps if you want to run these tests\")\n\t\treturn\n\t}\n\n\tf, err := os.Open(fileName)\n\tassert.Equal(t, nil, err)\n\n\thash, err := SubDbHashFromFile(f)\n\tassert.Equal(t, nil, err)\n\tassert.Equal(t, expectedHash, hash)\n}\n\nfunc TestSubDbHashFromFile(t *testing.T) {\n\n\tsubDbConformTest(t, \"conformance-files/thesubdb/dexter.mp4\", \"ffd8d4aa68033dc03d1c8ef373b9028c\")\n\n\tsubDbConformTest(t, \"conformance-files/thesubdb/justified.mp4\", \"edc1981d6459c6111fe36205b4aff6c2\")\n}\n\nfunc TestDownloadFromTheSubDb(t *testing.T) ", "output": "{\n\tfileName := createZeroedTempFile(1024 * 1024 * 4)\n\tdefer os.Remove(fileName)\n\n\tf, err := os.Open(fileName)\n\tassert.Equal(t, nil, err)\n\n\thash, err := SubDbHashFromFile(f)\n\tassert.Equal(t, nil, err)\n\tassert.Equal(t, \"0dfbe8aa4c20b52e1b8bf3cb6cbdf193\", hash)\n\n\tfinder := NewSubFinder(f, fileName, \"en\")\n\n\ttext, err := finder.TheSubDb(\"sandbox.thesubdb.com\")\n\tassert.Equal(t, nil, err)\n\tassert.True(t, len(text) > 1000)\n}"} {"input": "package wraps\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-on/wrap\"\n)\n\ntype first []http.Handler\n\nfunc (f first) ServeHTTPNext(inner http.Handler, wr http.ResponseWriter, req *http.Request) {\n\tchecked := wrap.NewPeek(wr, func(ck *wrap.Peek) bool {\n\t\tck.FlushHeaders()\n\t\tck.FlushCode()\n\t\treturn true\n\t})\n\n\tfor _, h := range f {\n\t\th.ServeHTTP(checked, req)\n\t\tif checked.HasChanged() {\n\t\t\tchecked.FlushMissing()\n\t\t\treturn\n\t\t}\n\t}\n\tinner.ServeHTTP(wr, req)\n}\n\n\nfunc (f first) Wrap(next http.Handler) http.Handler {\n\treturn wrap.NextHandler(f).Wrap(next)\n}\n\n\n\n\n\nfunc FirstFunc(handlerFn ...func(w http.ResponseWriter, r *http.Request)) wrap.Wrapper {\n\th := make([]http.Handler, len(handlerFn))\n\tfor i, fn := range handlerFn {\n\t\th[i] = http.HandlerFunc(fn)\n\t}\n\treturn first(h)\n}\n\nfunc First(handler ...http.Handler) wrap.Wrapper ", "output": "{ return first(handler) }"} {"input": "package classfile\n\nimport (\n\t\"github.com/zxh0/jvm.go/jvmgo/util/bigendian\"\n)\n\ntype ClassReader struct {\n\tdata []byte\n}\n\nfunc newClassReader(data []byte) *ClassReader {\n\treturn &ClassReader{data}\n}\n\nfunc (self *ClassReader) readUint8() uint8 {\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16() uint16 {\n\tval := bigendian.Uint16(self.data)\n\tself.data = self.data[2:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint32() uint32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn uint32(val)\n}\nfunc (self *ClassReader) readInt32() int32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\n\n\nfunc (self *ClassReader) readFloat32() float32 {\n\tval := bigendian.Float32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readFloat64() float64 {\n\tval := bigendian.Float64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readBytes(length uint32) []byte {\n\tbytes := self.data[:length]\n\tself.data = self.data[length:]\n\treturn bytes\n}\n\n\nfunc (self *ClassReader) readString() string {\n\tlength := uint32(self.readUint16())\n\tbytes := self.readBytes(length)\n\treturn string(bytes)\n}\n\nfunc (self *ClassReader) readInt64() int64 ", "output": "{\n\tval := bigendian.Int64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}"} {"input": "package router\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/valyala/fasthttp\"\n\n\t\"github.com/tpbowden/swarm-ingress-router/service\"\n)\n\n\ntype Router struct {\n\troutes map[string]service.Service\n}\n\n\n\n\n\nfunc (r *Router) CertificateForService(address string) (*tls.Certificate, bool) {\n\tvar cert *tls.Certificate\n\n\troute, ok := r.routes[address]\n\tif !ok {\n\t\tlog.Printf(\"Failed to lookup service for %s\", address)\n\t\treturn cert, false\n\t}\n\n\tcertificate := route.Certificate()\n\n\treturn &certificate, true\n}\n\n\nfunc (r *Router) UpdateTable(services []service.Service) {\n\tnewTable := make(map[string]service.Service)\n\n\tfor _, s := range services {\n\t\tlog.Printf(\"Registering service for %s\", s.DNSName)\n\t\ts.ParseCertificate()\n\t\tnewTable[s.DNSName] = s\n\t}\n\n\tr.routes = newTable\n}\n\n\nfunc NewRouter() *Router {\n\treturn &Router{}\n}\n\nfunc (r *Router) RouteToService(address string, path string, secure bool) (fasthttp.RequestHandler, bool) ", "output": "{\n\tvar handler fasthttp.RequestHandler\n\n\troute, ok := r.routes[address]\n\tif !ok {\n\t\tlog.Printf(\"Failed to lookup service for %s\", address)\n\t\treturn handler, false\n\t}\n\n\tif secure && !route.Secure {\n\t\treturn handler, false\n\t}\n\n\tif secure || !route.ForceTLS {\n\t\treturn NewProxyHandler(route.URL), true\n\t}\n\n\tredirectAddress := fmt.Sprintf(\"https://%s%s\", address, path)\n\treturn NewRedirectHandler(redirectAddress, 301), true\n}"} {"input": "package hamster\n\nimport (\n\t\"net/http\"\n)\n\nfunc (s *Server) serveError(w http.ResponseWriter, err error, user_message string, base_message string, status int) {\n\n\tlog_message := base_message + \" : \" + user_message\n\ts.logger.Printf(\"Error %v: %v \\n\", log_message, err)\n\thttp.Error(w, base_message, status)\n\n}\nfunc (s *Server) badRequest(r *http.Request, w http.ResponseWriter, err error, msg string) {\n\ts.serveError(w, err, msg, \"Bad Request\", http.StatusBadRequest)\n}\n\nfunc (s *Server) unauthorized(r *http.Request, w http.ResponseWriter, err error, msg string) {\n\ts.serveError(w, err, msg, \"Unauthorized\", http.StatusUnauthorized)\n}\n\n\n\nfunc (s *Server) internalError(r *http.Request, w http.ResponseWriter, err error, msg string) {\n\ts.serveError(w, err, msg, \"Internal Server Error\", http.StatusInternalServerError)\n\n}\n\nfunc (s *Server) notFound(r *http.Request, w http.ResponseWriter, err error, msg string) ", "output": "{\n\ts.serveError(w, err, msg, \"Not found\", http.StatusNotFound)\n\n}"} {"input": "package lifecycle\n\nimport (\n\t\"encoding/xml\"\n)\n\n\ntype NoncurrentVersionExpiration struct {\n\tXMLName xml.Name `xml:\"NoncurrentVersionExpiration\"`\n\tNoncurrentDays ExpirationDays `xml:\"NoncurrentDays,omitempty\"`\n}\n\n\ntype NoncurrentVersionTransition struct {\n\tNoncurrentDays ExpirationDays `xml:\"NoncurrentDays\"`\n\tStorageClass string `xml:\"StorageClass\"`\n}\n\nvar (\n\terrNoncurrentVersionTransitionUnsupported = Errorf(\"Specifying is not supported\")\n)\n\n\nfunc (n NoncurrentVersionExpiration) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tif n.IsDaysNull() {\n\t\treturn nil\n\t}\n\ttype noncurrentVersionExpirationWrapper NoncurrentVersionExpiration\n\treturn e.EncodeElement(noncurrentVersionExpirationWrapper(n), start)\n}\n\n\nfunc (n NoncurrentVersionExpiration) IsDaysNull() bool {\n\treturn n.NoncurrentDays == ExpirationDays(0)\n}\n\n\n\n\nfunc (n NoncurrentVersionTransition) UnmarshalXML(d *xml.Decoder, startElement xml.StartElement) error {\n\treturn errNoncurrentVersionTransitionUnsupported\n}\n\n\n\n\n\nfunc (n NoncurrentVersionTransition) MarshalXML(e *xml.Encoder, start xml.StartElement) error ", "output": "{\n\tif n.NoncurrentDays == ExpirationDays(0) {\n\t\treturn nil\n\t}\n\treturn e.EncodeElement(&n, start)\n}"} {"input": "package serial\n\nimport (\n\t\"flag\"\n\n\t\"github.com/juju/govmomi/govc/cli\"\n\t\"github.com/juju/govmomi/govc/flags\"\n\t\"golang.org/x/net/context\"\n)\n\ntype disconnect struct {\n\t*flags.VirtualMachineFlag\n\n\tdevice string\n}\n\nfunc init() {\n\tcli.Register(\"device.serial.disconnect\", &disconnect{})\n}\n\nfunc (cmd *disconnect) Register(f *flag.FlagSet) {\n\tf.StringVar(&cmd.device, \"device\", \"\", \"serial port device name\")\n}\n\nfunc (cmd *disconnect) Process() error { return nil }\n\n\n\nfunc (cmd *disconnect) Run(f *flag.FlagSet) error ", "output": "{\n\tvm, err := cmd.VirtualMachine()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif vm == nil {\n\t\treturn flag.ErrHelp\n\t}\n\n\tdevices, err := vm.Device(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td, err := devices.FindSerialPort(cmd.device)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn vm.EditDevice(context.TODO(), devices.DisconnectSerialPort(d))\n}"} {"input": "package cmd\n\nimport (\n\t\"crypto/rand\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/coreos/etcd/clientv3\"\n)\n\nvar (\n\tdialTotal int\n)\n\nfunc mustCreateConn() *clientv3.Client {\n\teps := strings.Split(endpoints, \",\")\n\tendpoint := eps[dialTotal%len(eps)]\n\tdialTotal++\n\tclient, err := clientv3.NewFromURL(endpoint)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"dial error: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\treturn client\n}\n\n\n\nfunc mustRandBytes(n int) []byte {\n\trb := make([]byte, n)\n\t_, err := rand.Read(rb)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"failed to generate value: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\treturn rb\n}\n\nfunc mustCreateClients(totalClients, totalConns uint) []*clientv3.Client ", "output": "{\n\tconns := make([]*clientv3.Client, totalConns)\n\tfor i := range conns {\n\t\tconns[i] = mustCreateConn()\n\t}\n\n\tclients := make([]*clientv3.Client, totalClients)\n\tfor i := range clients {\n\t\tclients[i] = conns[i%int(totalConns)].Clone()\n\t}\n\treturn clients\n}"} {"input": "package logging_test\n\nimport (\n\t\"context\"\n\n\tlogging \"cloud.google.com/go/logging/apiv2\"\n\t\"google.golang.org/api/iterator\"\n\tloggingpb \"google.golang.org/genproto/googleapis/logging/v2\"\n)\n\nfunc ExampleNewMetricsClient() {\n\tctx := context.Background()\n\tc, err := logging.NewMetricsClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\n\n\nfunc ExampleMetricsClient_GetLogMetric() {\n\tctx := context.Background()\n\tc, err := logging.NewMetricsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.GetLogMetricRequest{\n\t}\n\tresp, err := c.GetLogMetric(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleMetricsClient_CreateLogMetric() {\n\tctx := context.Background()\n\tc, err := logging.NewMetricsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.CreateLogMetricRequest{\n\t}\n\tresp, err := c.CreateLogMetric(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleMetricsClient_UpdateLogMetric() {\n\tctx := context.Background()\n\tc, err := logging.NewMetricsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.UpdateLogMetricRequest{\n\t}\n\tresp, err := c.UpdateLogMetric(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleMetricsClient_DeleteLogMetric() {\n\tctx := context.Background()\n\tc, err := logging.NewMetricsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.DeleteLogMetricRequest{\n\t}\n\terr = c.DeleteLogMetric(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleMetricsClient_ListLogMetrics() ", "output": "{\n\tctx := context.Background()\n\tc, err := logging.NewMetricsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.ListLogMetricsRequest{\n\t}\n\tit := c.ListLogMetrics(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}"} {"input": "package trace\n\nimport (\n\t\"github.com/golang/groupcache/lru\"\n)\n\n\n\ntype lruMap struct {\n\tcacheKeys map[lru.Key]bool\n\tcache *lru.Cache\n\tdroppedCount int\n}\n\n\n\nfunc (lm lruMap) len() int {\n\treturn lm.cache.Len()\n}\n\nfunc (lm lruMap) keys() []interface{} {\n\tkeys := []interface{}{}\n\tfor k := range lm.cacheKeys {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}\n\nfunc (lm *lruMap) add(key, value interface{}) {\n\tlm.cacheKeys[lru.Key(key)] = true\n\tlm.cache.Add(lru.Key(key), value)\n}\n\nfunc (lm *lruMap) get(key interface{}) (interface{}, bool) {\n\treturn lm.cache.Get(key)\n}\n\nfunc newLruMap(size int) *lruMap ", "output": "{\n\tlm := &lruMap{\n\t\tcacheKeys: make(map[lru.Key]bool),\n\t\tcache: lru.New(size),\n\t\tdroppedCount: 0,\n\t}\n\tlm.cache.OnEvicted = func(key lru.Key, value interface{}) {\n\t\tdelete(lm.cacheKeys, key)\n\t\tlm.droppedCount++\n\t}\n\treturn lm\n}"} {"input": "package replay\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/gapid/core/data/search\"\n\t\"github.com/google/gapid/test/robot/job/worker\"\n\t\"google.golang.org/grpc\"\n\n\txctx \"golang.org/x/net/context\"\n)\n\ntype server struct {\n\tmanager Manager\n}\n\n\nfunc Serve(ctx context.Context, grpcServer *grpc.Server, manager Manager) error {\n\tRegisterServiceServer(grpcServer, &server{manager: manager})\n\treturn nil\n}\n\n\n\nfunc (s *server) Search(query *search.Query, stream Service_SearchServer) error {\n\tctx := stream.Context()\n\treturn s.manager.Search(ctx, query, func(ctx context.Context, e *Action) error { return stream.Send(e) })\n}\n\n\n\nfunc (s *server) Register(request *worker.RegisterRequest, stream Service_RegisterServer) error {\n\tctx := stream.Context()\n\treturn s.manager.Register(ctx, request.Host, request.Target, func(ctx context.Context, t *Task) error { return stream.Send(t) })\n}\n\n\n\n\n\n\n\nfunc (s *server) Update(ctx xctx.Context, request *UpdateRequest) (*worker.UpdateResponse, error) {\n\tif err := s.manager.Update(ctx, request.Action, request.Status, request.Output); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &worker.UpdateResponse{}, nil\n}\n\nfunc (s *server) Do(ctx xctx.Context, request *DoRequest) (*worker.DoResponse, error) ", "output": "{\n\tid, err := s.manager.Do(ctx, request.Device, request.Input)\n\treturn &worker.DoResponse{Id: id}, err\n}"} {"input": "package database\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\n\t_ \"github.com/lib/pq\"\n)\n\ntype DB struct {\n\tc *sql.DB\n}\n\n\nfunc Open(dbname, user, password, host string, port int, sslmode string) (db DB, err error) {\n\turl := fmt.Sprintf(\"postgres:%s:%s@%s:%d/%s?sslmode=%s\",\n\t\tuser, password, host, port, dbname, sslmode)\n\tdb.c, err = sql.Open(\"postgres\", url)\n\treturn\n}\n\n\n\nfunc (db *DB) SetMaxOpenConns(n int) {\n\tdb.c.SetMaxOpenConns(n)\n}\n\nfunc (db *DB) Close() ", "output": "{\n\tdb.c.Close()\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\ntype SCmd struct {\n\tm_chanStringCmd chan string\n\tm_chanWaitCmdComplete chan bool\n\tm_bHadStop bool\n\tm_funcDoCmd func(string)\n\tm_mutex sync.Mutex\n}\n\nfunc NewSCmd(funcDoCmd func(string)) *SCmd {\n\tif funcDoCmd == nil {\n\t\treturn nil\n\t}\n\n\tvar pSCmd = &SCmd{\n\t\tm_bHadStop: false,\n\t\tm_chanStringCmd: make(chan string, 0),\n\t\tm_chanWaitCmdComplete: make(chan bool, 0),\n\t\tm_funcDoCmd: funcDoCmd,\n\t}\n\tgo pSCmd.mainWorker()\n\treturn pSCmd\n}\n\n\n\nfunc (this *SCmd) Quit() {\n\tclose(this.m_chanStringCmd)\n}\n\nfunc (this *SCmd) mainWorker() {\n\tfor strCmd := range this.m_chanStringCmd {\n\t\tthis.m_funcDoCmd(strCmd)\n\t}\n}\n\nfunc (this *SCmd) Cmd(strCmd string) ", "output": "{\n\tfmt.Println(\"Cmd\", strCmd)\n\n\tif this.m_bHadStop {\n\t\tfmt.Println(\"had stop\")\n\t\treturn\n\t}\n\n\tthis.m_chanStringCmd <- strCmd\n}"} {"input": "package packet_proxy\n\nimport (\n\t\"github.com/bettercap/bettercap/session\"\n)\n\ntype PacketProxy struct {\n\tsession.SessionModule\n}\n\nfunc NewPacketProxy(s *session.Session) *PacketProxy {\n\treturn &PacketProxy{\n\t\tSessionModule: session.NewSessionModule(\"packet.proxy\", s),\n\t}\n}\n\nfunc (mod PacketProxy) Name() string {\n\treturn \"packet.proxy\"\n}\n\n\n\nfunc (mod PacketProxy) Author() string {\n\treturn \"Simone Margaritelli \"\n}\n\nfunc (mod *PacketProxy) Configure() (err error) {\n\treturn session.ErrNotSupported\n}\n\nfunc (mod *PacketProxy) Start() error {\n\treturn session.ErrNotSupported\n}\n\nfunc (mod *PacketProxy) Stop() error {\n\treturn session.ErrNotSupported\n}\n\nfunc (mod PacketProxy) Description() string ", "output": "{\n\treturn \"Not supported on this OS\"\n}"} {"input": "package k8sutil\n\nimport (\n\t\"k8s.io/apimachinery/pkg/fields\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/client-go/rest\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype CustomResource struct {\n\tName string\n\n\tPlural string\n\n\tGroup string\n\n\tVersion string\n\n\tKind string\n\n\tAPIVersion string\n}\n\n\n\n\n\n\nfunc WatchCR(resource CustomResource, namespace string, handlers cache.ResourceEventHandlerFuncs, client rest.Interface, objType runtime.Object, done <-chan struct{}) ", "output": "{\n\tsource := cache.NewListWatchFromClient(\n\t\tclient,\n\t\tresource.Plural,\n\t\tnamespace,\n\t\tfields.Everything())\n\t_, controller := cache.NewInformer(\n\t\tsource,\n\n\t\tobjType,\n\n\t\t0,\n\n\t\thandlers)\n\n\tgo controller.Run(done)\n\t<-done\n}"} {"input": "package scripts\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\n\t\"github.com/lfkeitel/inca-tool/devices\"\n)\n\nfunc insertVariables(filename string, vars map[string]string) error {\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor n, v := range vars {\n\t\tif n[0] == '_' {\n\t\t\tn = n[1:]\n\t\t}\n\t\tfile = bytes.Replace(file, []byte(\"{{\"+n+\"}}\"), []byte(v), -1)\n\t}\n\n\tif err := ioutil.WriteFile(filename, file, 0744); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc getHostVariables(host *devices.Device) map[string]string ", "output": "{\n\targList := make(map[string]string)\n\targList[\"protocol\"] = host.GetSetting(\"protocol\")\n\tif argList[\"protocol\"] == \"\" {\n\t\targList[\"protocol\"] = \"ssh\"\n\t}\n\n\targList[\"hostname\"] = host.GetSetting(\"address\")\n\tif argList[\"hostname\"] == \"\" {\n\t\targList[\"hostname\"] = host.Name\n\t}\n\n\targList[\"remote_user\"] = host.GetSetting(\"remote_user\")\n\tif argList[\"remote_user\"] == \"\" {\n\t\targList[\"remote_user\"] = \"root\"\n\t}\n\n\targList[\"remote_password\"] = host.GetSetting(\"remote_password\")\n\n\targList[\"cisco_enable\"] = host.GetSetting(\"cisco_enable\")\n\tif argList[\"cisco_enable\"] == \"\" {\n\t\targList[\"cisco_enable\"] = host.GetSetting(\"remote_password\")\n\t}\n\n\treturn argList\n}"} {"input": "package receiver\n\nimport (\n\t\"os\"\n\t\"io\"\n)\n\ntype Stream struct {\n\tstream io.WriteCloser\n}\n\nfunc NewStream(filePath string) (*Stream, error) {\n\tvar err error\n\tvar stream Stream\n\tstream.stream, err = os.Create(filePath)\n\treturn &stream, err\n}\n\n\n\nfunc (this *Stream) Close(dummy int, nothing *int) error {\n\terr := this.stream.Close()\n\treturn err\n}\n\nfunc (this *Stream) Write(data []byte, n *int) (err error) ", "output": "{\n\t*n, err = this.stream.Write(data)\n\treturn err\n}"} {"input": "package client\n\nimport (\n\tuserapi \"github.com/projectatomic/atomic-enterprise/pkg/user/api\"\n)\n\n\ntype UserIdentityMappingsInterface interface {\n\tUserIdentityMappings() UserIdentityMappingInterface\n}\n\n\ntype UserIdentityMappingInterface interface {\n\tGet(string) (*userapi.UserIdentityMapping, error)\n\tCreate(*userapi.UserIdentityMapping) (*userapi.UserIdentityMapping, error)\n\tUpdate(*userapi.UserIdentityMapping) (*userapi.UserIdentityMapping, error)\n\tDelete(string) error\n}\n\n\ntype userIdentityMappings struct {\n\tr *Client\n}\n\n\nfunc newUserIdentityMappings(c *Client) *userIdentityMappings {\n\treturn &userIdentityMappings{\n\t\tr: c,\n\t}\n}\n\n\n\n\n\nfunc (c *userIdentityMappings) Create(mapping *userapi.UserIdentityMapping) (result *userapi.UserIdentityMapping, err error) {\n\tresult = &userapi.UserIdentityMapping{}\n\terr = c.r.Post().Resource(\"userIdentityMappings\").Body(mapping).Do().Into(result)\n\treturn\n}\n\n\nfunc (c *userIdentityMappings) Update(mapping *userapi.UserIdentityMapping) (result *userapi.UserIdentityMapping, err error) {\n\tresult = &userapi.UserIdentityMapping{}\n\terr = c.r.Put().Resource(\"userIdentityMappings\").Name(mapping.Name).Body(mapping).Do().Into(result)\n\treturn\n}\n\n\nfunc (c *userIdentityMappings) Delete(name string) (err error) {\n\terr = c.r.Delete().Resource(\"userIdentityMappings\").Name(name).Do().Error()\n\treturn\n}\n\nfunc (c *userIdentityMappings) Get(name string) (result *userapi.UserIdentityMapping, err error) ", "output": "{\n\tresult = &userapi.UserIdentityMapping{}\n\terr = c.r.Get().Resource(\"userIdentityMappings\").Name(name).Do().Into(result)\n\treturn\n}"} {"input": "package servo_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n\t\"github.com/fgrosse/servo\"\n\t\"fmt\"\n)\n\n\n\ntype TestBundle struct {}\n\nfunc (b *TestBundle) Boot(kernel *servo.Kernel) {\n\tkernel.RegisterType(\"test_bundle.my_type\", NewService)\n}\n\ntype SomeService struct {}\n\nfunc NewRecursiveService(*SomeService) *SomeService {\n\treturn &SomeService{}\n}\n\nfunc NewService() *SomeService {\n\treturn &SomeService{}\n}\n\nfunc NewServiceWithParam(param interface{}) *SomeService {\n\tpanic(param)\n\treturn &SomeService{}\n}\n\n\ntype ServerMock struct {\n\tRunHasBeenCalled bool\n\tReturnError bool\n\n\tParameter1, Parameter2 string\n}\n\nfunc NewServerMockWithParams(param1, param2 string) *ServerMock {\n\tExpect(param1).To(Equal(\"foo\"), `NewServerMockWithParams should always be called with the values \"foo\" and \"bar\"`)\n\tExpect(param2).To(Equal(\"bar\"), `NewServerMockWithParams should always be called with the values \"foo\" and \"bar\"`)\n\n\treturn &ServerMock{\n\t\tParameter1: param1,\n\t\tParameter2: param2,\n\t}\n}\n\nfunc (s *ServerMock) Run() error {\n\ts.RunHasBeenCalled = true\n\tif s.ReturnError {\n\t\treturn fmt.Errorf(\"ServerMock was told to return an error!\")\n\t}\n\n\treturn nil\n}\n\nfunc TestServo(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Servo Test Suite\")\n}"} {"input": "package cs\n\nimport (\n\t\"github.com/scionproto/scion/go/cs/beacon\"\n\t\"github.com/scionproto/scion/go/cs/config\"\n\t\"github.com/scionproto/scion/go/lib/serrors\"\n)\n\n\nfunc LoadCorePolicies(cfg config.Policies) (beacon.CorePolicies, error) {\n\tvar err error\n\tvar policies beacon.CorePolicies\n\tif policies.Prop, err = loadPolicy(cfg.Propagation, beacon.PropPolicy); err != nil {\n\t\treturn policies, err\n\t}\n\tif policies.CoreReg, err = loadPolicy(cfg.CoreRegistration, beacon.CoreRegPolicy); err != nil {\n\t\treturn policies, err\n\t}\n\treturn policies, nil\n}\n\n\nfunc LoadNonCorePolicies(cfg config.Policies) (beacon.Policies, error) {\n\tvar err error\n\tvar policies beacon.Policies\n\tif policies.Prop, err = loadPolicy(cfg.Propagation, beacon.PropPolicy); err != nil {\n\t\treturn policies, err\n\t}\n\tif policies.UpReg, err = loadPolicy(cfg.UpRegistration, beacon.UpRegPolicy); err != nil {\n\t\treturn policies, err\n\t}\n\tif policies.DownReg, err = loadPolicy(cfg.DownRegistration, beacon.DownRegPolicy); err != nil {\n\t\treturn policies, err\n\t}\n\treturn policies, nil\n}\n\n\n\nfunc loadPolicy(fn string, t beacon.PolicyType) (beacon.Policy, error) ", "output": "{\n\tvar policy beacon.Policy\n\tif fn != \"\" {\n\t\tp, err := beacon.LoadPolicyFromYaml(fn, t)\n\t\tif err != nil {\n\t\t\treturn policy, serrors.WrapStr(\"loading beaconing policy\", err, \"file\", fn, \"type\", t)\n\t\t}\n\t\tpolicy = *p\n\t}\n\tpolicy.InitDefaults()\n\treturn policy, nil\n}"} {"input": "package shoauth\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\ntype expectedSuccessHandler struct{}\n\nfunc (s *expectedSuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}\n\ntype expectedFailureHandler struct{}\n\nfunc (s *expectedFailureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}\n\ntype unexpectedSuccessHandler struct {\n\tt *testing.T\n}\n\nfunc (s *unexpectedSuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.t.Errorf(\"Request should have failed, but succeeded instead!\")\n}\n\ntype unexpectedFailureHandler struct {\n\tt *testing.T\n}\n\nfunc (s *unexpectedFailureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.t.Errorf(\"Request should have succeeded, but failed instead!\")\n}\n\ntype testPersistence struct {\n\texists bool\n\tcreate error\n\tsession bool\n}\n\nfunc (t *testPersistence) InstallationExists(shopID string) bool {\n\treturn t.exists\n}\n\n\n\nfunc TestAlreadyInstalled(t *testing.T) {\n\tp := testPersistence{\n\t\texists: true,\n\t\tcreate: errors.New(\"Installation already exists!\"),\n\t\tsession: false,\n\t}\n\thandler := NewShopifyOauthHandler(&unexpectedSuccessHandler{t: t}, &expectedFailureHandler{}, &p)\n\ttestServer := httptest.NewServer(handler)\n\tdefer testServer.Close()\n\thttp.Get(testServer.URL + \"/install\")\n}\n\nfunc (t *testPersistence) CreateInstallation(shopID string, accessToken string) error ", "output": "{\n\treturn t.create\n}"} {"input": "package base\n\nimport (\n\t\"math\"\n\t\"math/rand\"\n\t\"time\"\n)\n\n\n\nfunc GetRandf(a float64, b float64) float64 {\n\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\treturn (b-a)*r.Float64() + a \n}\n\nfunc GetRani(a float64, b float64) float64 {\n\n\treturn math.Floor(GetRandf(a, b))\n}\n\nfunc GetRandn(mu float64, std float64) float64 {\n\n\treturn rand.NormFloat64()*mu + std\n}\n\nfunc GaussianRandom() ", "output": "{\n\n\trand.Seed(99)\n\n}"} {"input": "package plan9\n\nimport \"syscall\"\n\nfunc fixwd() {\n\tsyscall.Fixwd()\n}\n\nfunc Getwd() (wd string, err error) {\n\treturn syscall.Getwd()\n}\n\n\n\nfunc Chdir(path string) error ", "output": "{\n\treturn syscall.Chdir(path)\n}"} {"input": "package api2go\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\ntype APIContextAllocatorFunc func(*API) APIContexter\n\n\ntype APIContexter interface {\n\tcontext.Context\n\tSet(key string, value interface{})\n\tGet(key string) (interface{}, bool)\n\tReset()\n}\n\n\ntype APIContext struct {\n\tkeys map[string]interface{}\n}\n\n\nfunc (c *APIContext) Set(key string, value interface{}) {\n\tif c.keys == nil {\n\t\tc.keys = make(map[string]interface{})\n\t}\n\tc.keys[key] = value\n}\n\n\nfunc (c *APIContext) Get(key string) (value interface{}, exists bool) {\n\tif c.keys != nil {\n\t\tvalue, exists = c.keys[key]\n\t}\n\treturn\n}\n\n\nfunc (c *APIContext) Reset() {\n\tc.keys = nil\n}\n\n\nfunc (c *APIContext) Deadline() (deadline time.Time, ok bool) {\n\treturn\n}\n\n\n\n\n\nfunc (c *APIContext) Err() error {\n\treturn nil\n}\n\n\nfunc (c *APIContext) Value(key interface{}) interface{} {\n\tif keyAsString, ok := key.(string); ok {\n\t\tval, _ := c.Get(keyAsString)\n\t\treturn val\n\t}\n\treturn nil\n}\n\n\nvar _ APIContexter = &APIContext{}\n\n\nfunc ContextQueryParams(c *APIContext) map[string][]string {\n\tqp, ok := c.Get(\"QueryParams\")\n\tif ok == false {\n\t\tqp = make(map[string][]string)\n\t\tc.Set(\"QueryParams\", qp)\n\t}\n\treturn qp.(map[string][]string)\n}\n\nfunc (c *APIContext) Done() <-chan struct{} ", "output": "{\n\treturn nil\n}"} {"input": "package nogo\n\n\ntype Permission int\n\n\ntype Principal interface {\n\tGetId() string\n\tGetSid() string\n\tGetRoleNames() []string\n}\n\n\ntype Role interface {\n\tGetName() string\n\tIsAdmin() bool\n\tHasPermission(permission Permission) (bool, error)\n}\n\n\n\n\n\nfunc NewAdminRole(name string, mask Permission) Role {\n\treturn &defaultRole{RoleName: name, PermissionMask: mask, Admin: true}\n}\n\ntype defaultRole struct {\n\tRoleName string `db:\"role_name\"`\n\tPermissionMask Permission `db:\"permission_mask\"`\n\tAdmin bool `db:\"is_admin\"`\n}\n\nfunc (this *defaultRole) GetName() string {\n\treturn this.RoleName\n}\n\nfunc (this *defaultRole) IsAdmin() bool {\n\treturn this.Admin\n}\n\nfunc (this *defaultRole) HasPermission(permission Permission) (bool, error) {\n\tval := (this.PermissionMask&permission != 0)\n\treturn val, nil\n}\n\nfunc NewRole(name string, mask Permission) Role ", "output": "{\n\treturn &defaultRole{RoleName: name, PermissionMask: mask, Admin: false}\n}"} {"input": "package volumeserver\n\nimport (\n\t\"code.cloudfoundry.org/lager\"\n\t\"github.com/concourse/concourse/atc/db\"\n\t\"github.com/concourse/concourse/atc/gc\"\n)\n\ntype Server struct {\n\tlogger lager.Logger\n\trepository db.VolumeRepository\n\tdestroyer gc.Destroyer\n}\n\n\n\nfunc NewServer(\n\tlogger lager.Logger,\n\tvolumeRepository db.VolumeRepository,\n\tdestroyer gc.Destroyer,\n) *Server ", "output": "{\n\treturn &Server{\n\t\tlogger: logger,\n\t\trepository: volumeRepository,\n\t\tdestroyer: destroyer,\n\t}\n}"} {"input": "package demo\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"github.com/google/go-github/github\"\n\t\"golang.org/x/oauth2\"\n\t\"google.golang.org/appengine\"\n\t\"google.golang.org/appengine/log\"\n)\n\nfunc init() {\n\thttp.HandleFunc(\"/\", handler)\n}\n\n\n\nfunc handler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tif r.URL.Path != \"/\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tctx := appengine.NewContext(r)\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: os.Getenv(\"GITHUB_AUTH_TOKEN\")},\n\t)\n\ttc := oauth2.NewClient(ctx, ts)\n\tclient := github.NewClient(tc)\n\n\tcommits, _, err := client.Repositories.ListCommits(ctx, \"google\", \"go-github\", nil)\n\tif err != nil {\n\t\tlog.Errorf(ctx, \"ListCommits: %v\", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text/plain; charset=utf-8\")\n\tfor _, commit := range commits {\n\t\tfmt.Fprintln(w, commit.GetHTMLURL())\n\t}\n}"} {"input": "package main\n\nimport \"testing\"\n\n\n\n\nfunc TestOperationList(t *testing.T) ", "output": "{\n\tvar operations []Operation = operationList()\n\tif operationLength := len(operations); operationLength != 3 {\n\t\tt.Error(\"Expected 2 operations in list but got \", operationLength)\n\t}\n}"} {"input": "package pham\n\nimport (\n\t\"io\"\n\t\"net/http\"\n)\n\n\ntype serverSentEventsConnection struct {\n\tw *http.ResponseWriter\n}\n\n\nfunc (sse *serverSentEventsConnection) Send(data []byte) (err error) {\n\tw := *sse.w\n\n\tio.WriteString(w, `event: message\ndata: `+string(data)+\"\\n\\n\")\n\n\tif flusher, ok := w.(http.Flusher); ok {\n\t\tflusher.Flush()\n\t}\n\n\treturn\n}\n\n\n\n\nfunc SSEHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tconnection := &serverSentEventsConnection{w: &w}\n\n\theader := w.Header()\n\theader.Set(\"Content-Type\", \"text/event-stream\")\n\theader.Set(\"Cache-Control\", \"no-cache\")\n\theader.Set(\"Connection\", \"keep-alive\")\n\theader.Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.WriteHeader(200)\n\n\tif flusher, ok := w.(http.Flusher); ok {\n\t\tflusher.Flush()\n\t}\n\n\tmanager.AddConnection(connection)\n\tdefer func() {\n\t\tmanager.DelConnection(connection)\n\t}()\n\n\tvar closer <-chan bool\n\tif notifier, ok := w.(http.CloseNotifier); ok {\n\t\tcloser = notifier.CloseNotify()\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-closer:\n\t\t\treturn\n\t\t}\n\t}\n}"} {"input": "package http\n\n\ntype Adapter func(HandlerFunc) HandlerFunc\n\n\n\n\nfunc AdaptHandlerFunc(hf HandlerFunc, adapters ...Adapter) HandlerFunc ", "output": "{\n\tfor _, adapter := range adapters {\n\t\thf = adapter(hf)\n\t}\n\treturn hf\n}"} {"input": "package block\n\n\ntype NoopLeaseManager struct{}\n\nfunc (n *NoopLeaseManager) RegisterLeaser(leaser Leaser) error {\n\treturn nil\n}\n\n\n\nfunc (n *NoopLeaseManager) OpenLease(\n\tleaser Leaser,\n\tdescriptor LeaseDescriptor,\n\tstate LeaseState,\n) error {\n\treturn nil\n}\n\nfunc (n *NoopLeaseManager) OpenLatestLease(\n\tleaser Leaser,\n\tdescriptor LeaseDescriptor,\n) (LeaseState, error) {\n\treturn LeaseState{}, nil\n}\n\nfunc (n *NoopLeaseManager) UpdateOpenLeases(\n\tdescriptor LeaseDescriptor,\n\tstate LeaseState,\n) (UpdateLeasesResult, error) {\n\treturn UpdateLeasesResult{}, nil\n}\n\nfunc (n *NoopLeaseManager) SetLeaseVerifier(leaseVerifier LeaseVerifier) error {\n\treturn nil\n}\n\nfunc (n *NoopLeaseManager) UnregisterLeaser(leaser Leaser) error ", "output": "{\n\treturn nil\n}"} {"input": "package configmap\n\nimport (\n\t\"context\"\n\n\tcorev1 \"k8s.io/client-go/informers/core/v1\"\n\n\t\"github.com/knative/pkg/controller\"\n\t\"github.com/knative/pkg/injection\"\n\t\"github.com/knative/pkg/injection/informers/kubeinformers/factory\"\n\t\"github.com/knative/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Default.RegisterInformer(withInformer)\n}\n\n\n\ntype Key struct{}\n\nfunc withInformer(ctx context.Context) (context.Context, controller.Informer) {\n\tf := factory.Get(ctx)\n\tinf := f.Core().V1().ConfigMaps()\n\treturn context.WithValue(ctx, Key{}, inf), inf.Informer()\n}\n\n\n\n\nfunc Get(ctx context.Context) corev1.ConfigMapInformer ", "output": "{\n\tuntyped := ctx.Value(Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panicf(\n\t\t\t\"Unable to fetch %T from context.\", (corev1.ConfigMapInformer)(nil))\n\t}\n\treturn untyped.(corev1.ConfigMapInformer)\n}"} {"input": "package endpoint\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetEndpointOKCode int = 200\n\n\ntype GetEndpointOK struct {\n\n\tPayload []*models.Endpoint `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetEndpointOK() *GetEndpointOK {\n\n\treturn &GetEndpointOK{}\n}\n\n\nfunc (o *GetEndpointOK) WithPayload(payload []*models.Endpoint) *GetEndpointOK {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *GetEndpointOK) SetPayload(payload []*models.Endpoint) {\n\to.Payload = payload\n}\n\n\n\n\n\nconst GetEndpointNotFoundCode int = 404\n\n\ntype GetEndpointNotFound struct {\n}\n\n\nfunc NewGetEndpointNotFound() *GetEndpointNotFound {\n\n\treturn &GetEndpointNotFound{}\n}\n\n\nfunc (o *GetEndpointNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc (o *GetEndpointOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\trw.WriteHeader(200)\n\tpayload := o.Payload\n\tif payload == nil {\n\t\tpayload = make([]*models.Endpoint, 0, 50)\n\t}\n\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) \n\t}\n}"} {"input": "package utils\n\ntype Set map[string]bool\n\nfunc (self Set) Contains(key string) bool {\n\t_, found := self[key]\n\treturn found\n}\n\nfunc (self Set) Insert(key string) {\n\tself[key] = true\n}\n\nfunc (self Set) Remove(key string) {\n\tdelete(self, key)\n}\n\n\n\nfunc (self Set) Size() int ", "output": "{\n\treturn len(self)\n}"} {"input": "package dexcom\n\nimport (\n\t\"math\"\n)\n\n\n\nfunc marshalUint16(n uint16) []byte {\n\treturn []byte{byte(n & 0xFF), byte(n >> 8)}\n}\n\n\nfunc marshalInt16(n int16) []byte {\n\treturn marshalUint16(uint16(n))\n}\n\nfunc marshalUint32(n uint32) []byte {\n\treturn append(marshalUint16(uint16(n&0xFFFF)), marshalUint16(uint16(n>>16))...)\n}\n\nfunc marshalInt32(n int32) []byte {\n\treturn marshalUint32(uint32(n))\n}\n\nfunc unmarshalUint16(v []byte) uint16 {\n\treturn uint16(v[0]) | uint16(v[1])<<8\n}\n\n\nfunc unmarshalInt16(v []byte) int16 {\n\treturn int16(unmarshalUint16(v))\n}\n\nfunc unmarshalUint32(v []byte) uint32 {\n\treturn uint32(unmarshalUint16(v[0:2])) | uint32(unmarshalUint16(v[2:4]))<<16\n}\n\n\n\nfunc unmarshalUint64(v []byte) uint64 {\n\treturn uint64(unmarshalUint32(v[0:4])) | uint64(unmarshalUint32(v[4:8]))<<32\n}\n\nfunc unmarshalFloat64(v []byte) float64 {\n\treturn math.Float64frombits(unmarshalUint64(v))\n}\n\nfunc unmarshalInt32(v []byte) int32 ", "output": "{\n\treturn int32(unmarshalUint32(v))\n}"} {"input": "package transactionrecord\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n\n\t\"golang.org/x/crypto/sha3\"\n\n\t\"github.com/bitmark-inc/bitmarkd/fault\"\n)\n\n\nconst (\n\tAssetIdentifierLength = 64\n)\n\n\n\n\n\n\ntype AssetIdentifier [AssetIdentifierLength]byte\n\n\n\n\nfunc NewAssetIdentifier(record []byte) AssetIdentifier {\n\treturn AssetIdentifier(sha3.Sum512(record))\n}\n\n\nfunc (assetId AssetIdentifier) String() string {\n\treturn hex.EncodeToString(assetId[:])\n}\n\n\nfunc (assetId AssetIdentifier) GoString() string {\n\treturn \"\"\n}\n\n\n\n\n\nfunc (assetId AssetIdentifier) MarshalText() ([]byte, error) {\n\tsize := hex.EncodedLen(len(assetId))\n\tbuffer := make([]byte, size)\n\thex.Encode(buffer, assetId[:])\n\treturn buffer, nil\n}\n\n\nfunc (assetId *AssetIdentifier) UnmarshalText(s []byte) error {\n\tif len(assetId) != hex.DecodedLen(len(s)) {\n\t\treturn fault.NotLink\n\t}\n\tbyteCount, err := hex.Decode(assetId[:], s)\n\tif nil != err {\n\t\treturn err\n\t}\n\tif AssetIdentifierLength != byteCount {\n\t\treturn fault.NotAssetId\n\t}\n\treturn nil\n}\n\n\nfunc AssetIdentifierFromBytes(assetId *AssetIdentifier, buffer []byte) error {\n\tif AssetIdentifierLength != len(buffer) {\n\t\treturn fault.NotAssetId\n\t}\n\tcopy(assetId[:], buffer)\n\treturn nil\n}\n\nfunc (assetId *AssetIdentifier) Scan(state fmt.ScanState, verb rune) error ", "output": "{\n\ttoken, err := state.Token(true, func(c rune) bool {\n\t\tif c >= '0' && c <= '9' {\n\t\t\treturn true\n\t\t}\n\t\tif c >= 'A' && c <= 'F' {\n\t\t\treturn true\n\t\t}\n\t\tif c >= 'a' && c <= 'f' {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\tif nil != err {\n\t\treturn err\n\t}\n\tif len(token) != hex.EncodedLen(AssetIdentifierLength) {\n\t\treturn fault.NotAssetId\n\t}\n\n\tbyteCount, err := hex.Decode(assetId[:], token)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\tif AssetIdentifierLength != byteCount {\n\t\treturn fault.NotAssetId\n\t}\n\treturn nil\n}"} {"input": "package mock\n\nimport (\n\t\"crypto/rand\"\n\t\"fmt\"\n)\n\ntype constReader struct {\n\tnonce string\n}\n\nfunc (r *constReader) Read(p []byte) (n int, err error) {\n\tcopy(p[:], []byte(r.nonce))\n\treturn len(r.nonce), nil\n}\n\n\n\nfunc WithConstRandReader(testNonce string, f func()) {\n\n\toriginal := rand.Reader\n\trand.Reader = &constReader{nonce: testNonce}\n\n\tf()\n\n\trand.Reader = original\n\n}\n\ntype errorReader struct {\n\terr string\n}\n\nfunc (r *errorReader) Read(p []byte) (n int, err error) {\n\treturn 0, fmt.Errorf(r.err)\n}\n\n\n\n\n\nfunc WithErrorRandReader(testError string, f func()) ", "output": "{\n\n\toriginal := rand.Reader\n\trand.Reader = &errorReader{err: testError}\n\n\tf()\n\n\trand.Reader = original\n\n}"} {"input": "package create_topic\n\nimport (\n\t\"encoding/xml\"\n\t\"net/http\"\n\n\t\"github.com/vburenin/firempq/server/snsproto/sns_query\"\n\t\"github.com/vburenin/firempq/server/snsproto/sns_response\"\n\t\"github.com/vburenin/firempq/server/snsproto/snsdefs\"\n\t\"github.com/vburenin/firempq/server/snsproto/snserr\"\n\t\"github.com/vburenin/firempq/server/snsproto/tmgr\"\n\t\"github.com/vburenin/firempq/server/snsproto/validation\"\n)\n\ntype CreateTopicResponse struct {\n\tXMLName xml.Name `xml:\"http://sns.amazonaws.com/doc/2010-03-31/ CreateTopicResponse\"`\n\tTopicArn string `xml:\"CreateTopicResult>TopicArn\"`\n\tRequestId string `xml:\"ResponseMetadata>RequestId\"`\n}\n\nfunc (s *CreateTopicResponse) XmlDocument() string { return sns_response.EncodeXml(s) }\nfunc (s *CreateTopicResponse) HttpCode() int { return http.StatusOK }\n\n\n\nfunc CreateTopic(tm *tmgr.TopicManager, snsQuery *sns_query.SNSQuery) sns_response.SNSResponse ", "output": "{\n\ttopicName := \"\"\n\tsns_query.ParseParams(snsQuery, func(k, v string) {\n\t\tif k == \"Name\" {\n\t\t\ttopicName = v\n\t\t}\n\t})\n\n\tif !validation.ValidateTopicName(topicName) {\n\t\treturn snserr.InvalidParameterError(\"Invalid parameter: Topic Name\")\n\t}\n\n\tarn := tm.CreateTopic(topicName)\n\n\treturn &CreateTopicResponse{\n\t\tXMLName: xml.Name{\n\t\t\tSpace: snsdefs.XMLSpace,\n\t\t\tLocal: \"CreateTopicResponse\",\n\t\t},\n\t\tTopicArn: arn,\n\t\tRequestId: \"reqId\",\n\t}\n}"} {"input": "package train\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"path\"\n\t\"strings\"\n)\n\nvar assetServer *http.Handler\nvar publicAssetServer *http.Handler\n\nfunc servePublicAssets(w http.ResponseWriter, r *http.Request) {\n\t(*publicAssetServer).ServeHTTP(w, r)\n}\n\nvar contentTypes = map[string]string{\n\t\".js\": \"application/javascript\",\n\t\".css\": \"text/css\",\n}\n\n\n\nfunc setupFileServer() {\n\tif assetServer == nil {\n\t\tserver := http.FileServer(http.Dir(Config.AssetsPath + \"/..\"))\n\t\tassetServer = &server\n\t}\n\tif publicAssetServer == nil {\n\t\tserver := http.FileServer(http.Dir(\"public\"))\n\t\tpublicAssetServer = &server\n\t}\n}\n\nfunc serveAssets(w http.ResponseWriter, r *http.Request) ", "output": "{\n\turl := r.URL.Path\n\text := path.Ext(url)\n\n\tswitch ext {\n\tcase \".js\", \".css\":\n\t\tcontent, err := ReadAsset(url)\n\t\tif err != nil {\n\t\t\tif strings.Contains(err.Error(), \"Could not compile\") {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t} else {\n\t\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\t}\n\n\t\t\tio.Copy(w, strings.NewReader(err.Error()))\n\t\t\tlog.Printf(\"Failed to deliver asset\\nGET %s\\n-----------------------\\n%s\\n\", url, err.Error())\n\t\t} else {\n\t\t\tw.Header().Set(\"Content-Type\", contentTypes[ext])\n\t\t\tio.Copy(w, strings.NewReader(content))\n\t\t}\n\tdefault:\n\t\t(*assetServer).ServeHTTP(w, r)\n\t}\n}"} {"input": "package models\n\ntype Category struct {\n Id int8 `json:\"id\"`\n Name string `json:\"name\"`\n Description string `json:\"description,omitempty\"`\n}\n\n\n\nfunc GetCategories() []*Category {\n db, err := stablishConnection()\n if err != nil {\n panic(err)\n }\n defer db.Close()\n\n query := `SELECT id, name FROM categories`\n categories := []*Category{}\n categories_rows, err := db.Query(query)\n defer categories_rows.Close()\n\n if err != nil {\n panic(err)\n }\n\n if categories_rows == nil {\n return categories\n }\n\n for categories_rows.Next() {\n category := Category{}\n err = categories_rows.Scan(\n &category.Id,\n &category.Name,\n )\n categories = append(categories, &category)\n }\n\n return categories\n}\n\nfunc (c *Category) Create() ", "output": "{\n db, err := stablishConnection()\n if err != nil {\n panic(err)\n }\n defer db.Close()\n\n query := `INSERT INTO categories(name, description)\n VALUES ($1, $2)`\n\n _, err = db.Exec(query,\n c.Name,\n c.Description)\n\n if err != nil {\n panic(err)\n }\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\n\n\n\n\ntype MsgMemPool struct{}\n\n\n\nfunc (msg *MsgMemPool) BtcDecode(r io.Reader, pver uint32) error {\n\tif pver < BIP0035Version {\n\t\tstr := fmt.Sprintf(\"mempool message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgMemPool.BtcDecode\", str)\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (msg *MsgMemPool) BtcEncode(w io.Writer, pver uint32) error {\n\tif pver < BIP0035Version {\n\t\tstr := fmt.Sprintf(\"mempool message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgMemPool.BtcEncode\", str)\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (msg *MsgMemPool) Command() string {\n\treturn CmdMemPool\n}\n\n\n\nfunc (msg *MsgMemPool) MaxPayloadLength(pver uint32) uint32 {\n\treturn 0\n}\n\n\n\n\n\nfunc NewMsgMemPool() *MsgMemPool ", "output": "{\n\treturn &MsgMemPool{}\n}"} {"input": "package matrix\n\ntype Point struct {\n\tY int\n\tX int\n}\n\nfunc (point Point) Diff(to Point) Point {\n\treturn Point{to.Y - point.Y, to.X - point.X}\n}\n\n\n\nfunc (point *Point) StepTo(to Point) ", "output": "{\n\tif point.Y < to.Y {\n\t\tpoint.Y++\n\t} else if point.Y > to.Y {\n\t\tpoint.Y--\n\t}\n\tif point.X < to.X {\n\t\tpoint.X++\n\t} else if point.X > to.X {\n\t\tpoint.X--\n\t}\n}"} {"input": "package service\n\nimport (\n\t\"math/rand\"\n)\n\ntype serviceList []*Service\n\n\n\nfunc (l serviceList) Shuffle() ", "output": "{\n\tn := len(l)\n\n\tfor i := n - 1; i > 0; i-- {\n\t\tj := rand.Intn(i + 1)\n\t\tl[i], l[j] = l[j], l[i]\n\t}\n}"} {"input": "package codec\n\nimport (\n\t\"fmt\"\n\t\"github.com/davyxu/cellnet\"\n)\n\nvar registedCodecs []cellnet.Codec\n\n\nfunc RegisterCodec(c cellnet.Codec) {\n\n\tif GetCodec(c.Name()) != nil {\n\t\tpanic(\"duplicate codec: \" + c.Name())\n\t}\n\n\tregistedCodecs = append(registedCodecs, c)\n}\n\n\nfunc GetCodec(name string) cellnet.Codec {\n\n\tfor _, c := range registedCodecs {\n\t\tif c.Name() == name {\n\t\t\treturn c\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\nfunc getPackageByCodecName(name string) string {\n\tswitch name {\n\tcase \"binary\":\n\t\treturn \"github.com/davyxu/cellnet/codec/binary\"\n\tcase \"gogopb\":\n\t\treturn \"github.com/davyxu/cellnet/codec/gogopb\"\n\tcase \"httpjson\":\n\t\treturn \"github.com/davyxu/cellnet/codec/httpjson\"\n\tcase \"json\":\n\t\treturn \"github.com/davyxu/cellnet/codec/json\"\n\tcase \"protoplus\":\n\t\treturn \"github.com/davyxu/cellnet/codec/protoplus\"\n\tdefault:\n\t\treturn \"package/to/your/codec\"\n\t}\n}\n\n\n\n\nfunc MustGetCodec(name string) cellnet.Codec ", "output": "{\n\tcodec := GetCodec(name)\n\n\tif codec == nil {\n\t\tpanic(fmt.Sprintf(\"codec not found '%s'\\ntry to add code below:\\nimport (\\n _ \\\"%s\\\"\\n)\\n\\n\",\n\t\t\tname,\n\t\t\tgetPackageByCodecName(name)))\n\t}\n\n\treturn codec\n}"} {"input": "package state\n\nimport (\n\t\"fmt\"\n\n\t\"launchpad.net/juju-core/constraints\"\n\t\"launchpad.net/juju-core/environs/config\"\n\t\"launchpad.net/juju-core/errors\"\n)\n\n\n\n\n\n\n\n\n\n\ntype Policy interface {\n\tPrechecker(*config.Config) (Prechecker, error)\n}\n\n\n\ntype Prechecker interface {\n\tPrecheckInstance(series string, cons constraints.Value) error\n}\n\n\n\n\n\nfunc (st *State) precheckInstance(series string, cons constraints.Value) error ", "output": "{\n\tif st.policy == nil {\n\t\treturn nil\n\t}\n\tcfg, err := st.EnvironConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tprechecker, err := st.policy.Prechecker(cfg)\n\tif errors.IsNotImplementedError(err) {\n\t\treturn nil\n\t} else if err != nil {\n\t\treturn err\n\t}\n\tif prechecker == nil {\n\t\treturn fmt.Errorf(\"policy returned nil prechecker without an error\")\n\t}\n\treturn prechecker.PrecheckInstance(series, cons)\n}"} {"input": "package jwt\n\nimport (\n\t\"crypto\"\n\t\"crypto/hmac\"\n\t\"fmt\"\n\n\t_ \"crypto/sha256\"\n\t_ \"crypto/sha512\"\n)\n\ntype hmacSigner struct {\n\talg string\n\tkeyID string\n\tkey []byte\n\thash crypto.Hash\n}\n\nvar _ Signer = (*hmacSigner)(nil)\nvar _ Verifier = (*hmacSigner)(nil)\n\nfunc (s *hmacSigner) Algorithm() string {\n\treturn s.alg\n}\n\nfunc (s hmacSigner) KeyID() string {\n\treturn s.keyID\n}\n\nfunc (s *hmacSigner) Sign(data []byte) ([]byte, error) {\n\tif !s.hash.Available() {\n\t\treturn nil, ErrAlgorithmNotAvailable\n\t}\n\n\thasher := hmac.New(s.hash.New, s.key)\n\tif _, err := hasher.Write(data); err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot encode data: %s\", err)\n\t}\n\treturn hasher.Sum(nil), nil\n}\n\n\n\n\nfunc HMAC256(key []byte, keyID string) Signer {\n\treturn &hmacSigner{\n\t\talg: \"HS256\",\n\t\tkeyID: keyID,\n\t\tkey: append([]byte{}, key...),\n\t\thash: crypto.SHA256,\n\t}\n}\n\n\nfunc HMAC384(key []byte, keyID string) Signer {\n\treturn &hmacSigner{\n\t\talg: \"HS384\",\n\t\tkeyID: keyID,\n\t\tkey: append([]byte{}, key...),\n\t\thash: crypto.SHA384,\n\t}\n}\n\n\nfunc HMAC512(key []byte, keyID string) Signer {\n\treturn &hmacSigner{\n\t\talg: \"HS512\",\n\t\tkeyID: keyID,\n\t\tkey: append([]byte{}, key...),\n\t\thash: crypto.SHA512,\n\t}\n}\n\nfunc (s *hmacSigner) Verify(signature, data []byte) error ", "output": "{\n\tif !s.hash.Available() {\n\t\treturn ErrAlgorithmNotAvailable\n\t}\n\n\thasher := hmac.New(s.hash.New, s.key)\n\tif _, err := hasher.Write(data); err != nil {\n\t\treturn fmt.Errorf(\"cannot encode data: %s\", err)\n\t}\n\n\tif !hmac.Equal(signature, hasher.Sum(nil)) {\n\t\treturn ErrInvalidSignature\n\t}\n\treturn nil\n}"} {"input": "package rest\n\nimport (\n\trestful \"github.com/emicklei/go-restful\"\n\tswagger \"github.com/emicklei/go-restful-swagger12\"\n)\n\n\n\n\nfunc ConfigureSwagger(apiDocPath string, container *restful.Container) ", "output": "{\n\tif apiDocPath == \"\" {\n\t\treturn\n\t}\n\tconfig := swagger.Config{\n\t\tWebServices: container.RegisteredWebServices(),\n\t\tWebServicesUrl: ``,\n\t\tApiPath: apiDocPath,\n\t}\n\tswagger.RegisterSwaggerService(config, container)\n}"} {"input": "package common\n\nimport \"math/big\"\n\ntype _N_ [_S_]byte\n\nfunc BytesTo_N_(b []byte) _N_ {\n\tvar h _N_\n\th.SetBytes(b)\n\treturn h\n}\nfunc StringTo_N_(s string) _N_ { return BytesTo_N_([]byte(s)) }\nfunc BigTo_N_(b *big.Int) _N_ { return BytesTo_N_(b.Bytes()) }\nfunc HexTo_N_(s string) _N_ { return BytesTo_N_(FromHex(s)) }\n\n\n\n\nfunc (h _N_) Str() string { return string(h[:]) }\nfunc (h _N_) Bytes() []byte { return h[:] }\n\nfunc (h _N_) Hex() string { return \"0x\" + Bytes2Hex(h[:]) }\n\n\nfunc (h *_N_) SetBytes(b []byte) {\n\tif len(b) > len(h) {\n\t\tb = b[len(b)-_S_:]\n\t}\n\n\tfor i := len(b) - 1; i >= 0; i-- {\n\t\th[_S_-len(b)+i] = b[i]\n\t}\n}\n\n\nfunc (h *_N_) SetString(s string) { h.SetBytes([]byte(s)) }\n\n\nfunc (h *_N_) Set(other _N_) {\n\tfor i, v := range other {\n\t\th[i] = v\n\t}\n}\n\nfunc (h _N_) Big() *big.Int ", "output": "{ return Bytes2Big(h[:]) }"} {"input": "package textanalytics\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/cognitiveservices/v2.0/textanalytics\"\n\ntype BaseClient = original.BaseClient\ntype AzureRegions = original.AzureRegions\n\nconst (\n\tAustraliaeast AzureRegions = original.Australiaeast\n\tBrazilsouth AzureRegions = original.Brazilsouth\n\tEastasia AzureRegions = original.Eastasia\n\tEastus AzureRegions = original.Eastus\n\tEastus2 AzureRegions = original.Eastus2\n\tNortheurope AzureRegions = original.Northeurope\n\tSouthcentralus AzureRegions = original.Southcentralus\n\tSoutheastasia AzureRegions = original.Southeastasia\n\tWestcentralus AzureRegions = original.Westcentralus\n\tWesteurope AzureRegions = original.Westeurope\n\tWestus AzureRegions = original.Westus\n\tWestus2 AzureRegions = original.Westus2\n)\n\ntype BatchInput = original.BatchInput\ntype DetectedLanguage = original.DetectedLanguage\ntype ErrorRecord = original.ErrorRecord\ntype ErrorResponse = original.ErrorResponse\ntype Input = original.Input\ntype InternalError = original.InternalError\ntype KeyPhraseBatchResult = original.KeyPhraseBatchResult\ntype KeyPhraseBatchResultItem = original.KeyPhraseBatchResultItem\ntype LanguageBatchResult = original.LanguageBatchResult\ntype LanguageBatchResultItem = original.LanguageBatchResultItem\ntype MultiLanguageBatchInput = original.MultiLanguageBatchInput\ntype MultiLanguageInput = original.MultiLanguageInput\ntype SentimentBatchResult = original.SentimentBatchResult\ntype SentimentBatchResultItem = original.SentimentBatchResultItem\n\n\nfunc NewWithoutDefaults(azureRegion AzureRegions) BaseClient {\n\treturn original.NewWithoutDefaults(azureRegion)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/latest\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\n\nfunc New(azureRegion AzureRegions) BaseClient ", "output": "{\n\treturn original.New(azureRegion)\n}"} {"input": "package router\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/valyala/fasthttp\"\n\n\t\"github.com/tpbowden/swarm-ingress-router/service\"\n)\n\n\ntype Router struct {\n\troutes map[string]service.Service\n}\n\n\nfunc (r *Router) RouteToService(address string, path string, secure bool) (fasthttp.RequestHandler, bool) {\n\tvar handler fasthttp.RequestHandler\n\n\troute, ok := r.routes[address]\n\tif !ok {\n\t\tlog.Printf(\"Failed to lookup service for %s\", address)\n\t\treturn handler, false\n\t}\n\n\tif secure && !route.Secure {\n\t\treturn handler, false\n\t}\n\n\tif secure || !route.ForceTLS {\n\t\treturn NewProxyHandler(route.URL), true\n\t}\n\n\tredirectAddress := fmt.Sprintf(\"https://%s%s\", address, path)\n\treturn NewRedirectHandler(redirectAddress, 301), true\n}\n\n\nfunc (r *Router) CertificateForService(address string) (*tls.Certificate, bool) {\n\tvar cert *tls.Certificate\n\n\troute, ok := r.routes[address]\n\tif !ok {\n\t\tlog.Printf(\"Failed to lookup service for %s\", address)\n\t\treturn cert, false\n\t}\n\n\tcertificate := route.Certificate()\n\n\treturn &certificate, true\n}\n\n\n\n\n\nfunc NewRouter() *Router {\n\treturn &Router{}\n}\n\nfunc (r *Router) UpdateTable(services []service.Service) ", "output": "{\n\tnewTable := make(map[string]service.Service)\n\n\tfor _, s := range services {\n\t\tlog.Printf(\"Registering service for %s\", s.DNSName)\n\t\ts.ParseCertificate()\n\t\tnewTable[s.DNSName] = s\n\t}\n\n\tr.routes = newTable\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n)\n\nconst rootURL = \"https://api.onedrive.com/v1.0\"\n\n\n\nfunc doGetRequest(api string) ([]byte, error) ", "output": "{\n\tURI := fmt.Sprintf(\"%s%s\", rootURL, api)\n\tlog.Printf(\"GET: %s\\n\", URI)\n\tresp, err := client.Get(URI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\treturn ioutil.ReadAll(resp.Body)\n}"} {"input": "package server\n\nimport (\n\t\"google.golang.org/grpc\"\n\tsdkgrpc \"github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/cloudidentity/beta/cloudidentity_beta_go_proto\"\n)\n\n\n\n\nfunc RegisterServers(s *grpc.Server) ", "output": "{\n\tsdkgrpc.RegisterCloudidentityBetaGroupServiceServer(s, &GroupServer{})\n\tsdkgrpc.RegisterCloudidentityBetaMembershipServiceServer(s, &MembershipServer{})\n}"} {"input": "package policy\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) BaseClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package sessionmanager\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestFSSMInterface(t *testing.T) ", "output": "{\n\tvar _ SessionManager = SessionManager(new(FSSessionManager))\n}"} {"input": "package http\n\nimport (\n\tgohttp \"net/http\"\n)\n\n\ntype Client struct {\n\t*gohttp.Client\n}\n\n\nfunc NewClient() (*Client, error) {\n\tclient := &Client{}\n\tclient.Client = &gohttp.Client{}\n\treturn client, nil\n}\n\n\n\nfunc (client *Client) Do(req *Request) (*Response, error) ", "output": "{\n\tres, err := client.Client.Do(req.Request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewResponseFromResponse(res), nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/devfeel/dotweb\"\n\t\"github.com/devfeel/dotweb/cache\"\n\t\"github.com/devfeel/dotweb/framework/file\"\n\t\"strconv\"\n)\n\nfunc main() {\n\tapp := dotweb.New()\n\n\tapp.SetLogPath(file.GetCurrentDirectory())\n\n\n\tInitRoute(app.HttpServer)\n\n\n\tapp.SetCache(cache.NewRuntimeCache())\n\n\terr := app.Cache().Set(\"g\", \"gv\", 20)\n\tif err != nil {\n\t\tfmt.Println(\"Cache Set \", err)\n\t}\n\n\tport := 8080\n\tfmt.Println(\"dotweb.StartServer => \" + strconv.Itoa(port))\n\terr = app.StartServer(port)\n\tfmt.Println(\"dotweb.StartServer error => \", err)\n}\n\ntype UserInfo struct {\n\tUserName string\n\tSex int\n}\n\nfunc One(ctx dotweb.Context) error {\n\tg, err := ctx.Cache().GetString(\"g\")\n\tif err != nil {\n\t\tg = err.Error()\n\t}\n\t_, err = ctx.Cache().Incr(\"count\")\n\treturn ctx.WriteString(\"One [\" + g + \"] \" + fmt.Sprint(err))\n}\n\nfunc Two(ctx dotweb.Context) error {\n\tg, err := ctx.Cache().GetString(\"g\")\n\tif err != nil {\n\t\tg = err.Error()\n\t}\n\t_, err = ctx.Cache().Incr(\"count\")\n\tc, _ := ctx.Cache().GetString(\"count\")\n\treturn ctx.WriteString(\"Two [\" + g + \"] [\" + c + \"] \" + fmt.Sprint(err))\n}\n\n\n\nfunc InitRoute(server *dotweb.HttpServer) ", "output": "{\n\tserver.Router().GET(\"/1\", One)\n\tserver.Router().GET(\"/2\", Two)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Mutex struct {\n\tLocked bool\n\tLocker chan bool\n}\n\nfunc (m *Mutex) Lock() {\n\tif m.Locker == nil {\n\t\tm.Locker = make(chan bool, 1)\n\t}\n\n\tif m.Locked {\n\t\t<-m.Locker\n\t\tm.Locked = false\n\t} else {\n\t\tm.Locked = true\n\t}\n}\n\n\n\nfunc main() {\n\tmu := &Mutex{}\n\n\tfmt.Println(mu)\n\n\tgo func() {\n\t\tmu.Lock()\n\t\tfmt.Println(\"locking ...\")\n\t}()\n\n\tgo func() {\n\t\tmu.Lock()\n\t\tfmt.Println(\"unlocked !!\")\n\t}()\n\n\tgo func() {\n\t\t<-time.NewTimer(time.Second * 2).C\n\t\tmu.Unlock()\n\t\tfmt.Println(\"unlocking..\")\n\t}()\n\n\t<-time.NewTimer(time.Second * 4).C\n\tfmt.Println(\"finished..\")\n}\n\nfunc (m *Mutex) Unlock() ", "output": "{\n\tm.Locker <- true\n}"} {"input": "package test\n\nimport (\n\t\"app/models\"\n\t\"app/services\"\n\t\"github.com/andboson/carbon\"\n\t. \"github.com/smartystreets/goconvey/convey\"\n\t\"testing\"\n)\n\nfunc TestGetModel(t *testing.T) {\n\tAddMockDataModel(\"tst\")\n\n\tvar model = &models.Model{}\n\tmodel = model.GetByName(\"tst\")\n\tConvey(\"Subject: Test Find Model in DB \\n\", t, func() {\n\n\t\tConvey(\"The Result Name must be equal `tst`\", func() {\n\t\t\tSo(model.Name, ShouldEqual, \"tst\")\n\t\t})\n\n\t\tConvey(\"The Result Updated At must be equal \"+carbon.Now().SubDays(2).ToDateTimeString(), func() {\n\t\t\tSo(model.Date.Day(), ShouldEqual, carbon.Now().SubDays(2).Day())\n\t\t})\n\n\t})\n}\n\n\n\n\nfunc AddMockDataModel(name string) ", "output": "{\n\tservices.DB.Where(\"name = ?\", name).Delete(models.Model{})\n\tmodel := models.Model{\n\t\tName: name,\n\t\tDate: carbon.Now().SubDays(2).Time,\n\t}\n\tservices.DB.Create(&model)\n}"} {"input": "package main\n\nimport (\n\t\"euler/tools\"\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc checkNumerator(x *big.Rat) bool {\n\tnum, denom := x.Num(), x.Denom()\n\treturn tools.NumDigits(num) > tools.NumDigits(denom)\n}\n\n\n\n\nfunc main() {\n\tfmt.Println(problem57())\n}\n\nfunc problem57() int ", "output": "{\n\tsum := 0 \n\tconst limit = 1000 \n\tone := new(big.Rat).SetInt64(1)\n\ttwo := new(big.Rat).SetInt64(2)\n\n\tresult := new(big.Rat)\n\ttail := new(big.Rat).SetInt64(2)\n\n\tfor i := 0; i < limit; i++ {\n\t\ttemp := new(big.Rat)\n\t\ttail.Add(two, temp.Inv(tail)) \n\t\tresult.Add(one, temp.Inv(tail)) \n\t\tif checkNumerator(result) {\n\t\t\tsum++\n\t\t}\n\t}\n\treturn sum\n}"} {"input": "package iso20022\n\n\ntype AmountAndDirection55 struct {\n\n\tAmount *RestrictedFINActiveOrHistoricCurrencyAndAmount `xml:\"Amt\"`\n\n\tCreditDebitIndicator *CreditDebitCode `xml:\"CdtDbtInd,omitempty\"`\n\n\tOriginalCurrencyAndOrderedAmount *RestrictedFINActiveOrHistoricCurrencyAndAmount `xml:\"OrgnlCcyAndOrdrdAmt,omitempty\"`\n\n\tForeignExchangeDetails *ForeignExchangeTerms23 `xml:\"FXDtls,omitempty\"`\n}\n\nfunc (a *AmountAndDirection55) SetAmount(value, currency string) {\n\ta.Amount = NewRestrictedFINActiveOrHistoricCurrencyAndAmount(value, currency)\n}\n\nfunc (a *AmountAndDirection55) SetCreditDebitIndicator(value string) {\n\ta.CreditDebitIndicator = (*CreditDebitCode)(&value)\n}\n\nfunc (a *AmountAndDirection55) SetOriginalCurrencyAndOrderedAmount(value, currency string) {\n\ta.OriginalCurrencyAndOrderedAmount = NewRestrictedFINActiveOrHistoricCurrencyAndAmount(value, currency)\n}\n\n\n\nfunc (a *AmountAndDirection55) AddForeignExchangeDetails() *ForeignExchangeTerms23 ", "output": "{\n\ta.ForeignExchangeDetails = new(ForeignExchangeTerms23)\n\treturn a.ForeignExchangeDetails\n}"} {"input": "package proxy\n\nimport (\n\t\"log\"\n\t\"strconv\"\n\n\t\"../util\"\n)\n\n\n\nfunc (s *ProxyServer) handleSubmitRPC(cs *Session, diff string, id string, params []string) (reply bool, errorReply *ErrorReply) {\n\tminer, ok := s.miners.Get(id)\n\tif !ok {\n\t\tminer = NewMiner(id, cs.ip)\n\t\ts.registerMiner(miner)\n\t}\n\n\tt := s.currentBlockTemplate()\n\treply = miner.processShare(s, t, diff, params)\n\treturn\n}\n\nfunc (s *ProxyServer) handleSubmitHashrate(cs *Session, req *JSONRpcReq) bool {\n\treply, _ := s.rpc().SubmitHashrate(req.Params)\n\treturn reply\n}\n\nfunc (s *ProxyServer) handleUnknownRPC(cs *Session, req *JSONRpcReq) *ErrorReply {\n\tlog.Printf(\"Unknown RPC method: %v\", req)\n\treturn &ErrorReply{Code: -1, Message: \"Invalid method\"}\n}\n\nfunc (s *ProxyServer) handleGetWorkRPC(cs *Session, diff, id string) (reply []string, errorReply *ErrorReply) ", "output": "{\n\tt := s.currentBlockTemplate()\n\tif len(t.Header) == 0 {\n\t\treturn nil, &ErrorReply{Code: -1, Message: \"Work not ready\"}\n\t}\n\ttargetHex := t.Target\n\n\tif !s.rpc().Pool {\n\t\tminerDifficulty, err := strconv.ParseFloat(diff, 64)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Invalid difficulty %v from %v@%v \", diff, id, cs.ip)\n\t\t\tminerDifficulty = 5\n\t\t}\n\t\ttargetHex = util.MakeTargetHex(minerDifficulty)\n\t}\n\treply = []string{t.Header, t.Seed, targetHex}\n\treturn\n}"} {"input": "package middleware\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/yangou/goji/web\"\n)\n\ntype autoOptionsState int\n\nconst (\n\taosInit autoOptionsState = iota\n\taosHeaderWritten\n\taosProxying\n)\n\n\n\n\n\ntype autoOptionsProxy struct {\n\tw http.ResponseWriter\n\tc *web.C\n\tstate autoOptionsState\n}\n\nfunc (p *autoOptionsProxy) Header() http.Header {\n\treturn p.w.Header()\n}\n\nfunc (p *autoOptionsProxy) Write(buf []byte) (int, error) {\n\tswitch p.state {\n\tcase aosInit:\n\t\tp.state = aosHeaderWritten\n\tcase aosProxying:\n\t\treturn len(buf), nil\n\t}\n\treturn p.w.Write(buf)\n}\n\n\n\n\n\nfunc AutomaticOptions(c *web.C, h http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == \"OPTIONS\" {\n\t\t\tw = &autoOptionsProxy{c: c, w: w}\n\t\t}\n\n\t\th.ServeHTTP(w, r)\n\t}\n\n\treturn http.HandlerFunc(fn)\n}\n\nfunc getValidMethods(c web.C) []string {\n\tif c.Env == nil {\n\t\treturn nil\n\t}\n\tv, ok := c.Env[web.ValidMethodsKey]\n\tif !ok {\n\t\treturn nil\n\t}\n\tif methods, ok := v.([]string); ok {\n\t\treturn methods\n\t}\n\treturn nil\n}\n\nfunc addMethod(methods []string, method string) []string {\n\tfor _, m := range methods {\n\t\tif m == method {\n\t\t\treturn methods\n\t\t}\n\t}\n\treturn append(methods, method)\n}\n\nfunc (p *autoOptionsProxy) WriteHeader(code int) ", "output": "{\n\tmethods := getValidMethods(*p.c)\n\tswitch p.state {\n\tcase aosInit:\n\t\tif methods != nil && code == http.StatusNotFound {\n\t\t\tp.state = aosProxying\n\t\t\tbreak\n\t\t}\n\t\tp.state = aosHeaderWritten\n\t\tfallthrough\n\tdefault:\n\t\tp.w.WriteHeader(code)\n\t\treturn\n\t}\n\n\tmethods = addMethod(methods, \"OPTIONS\")\n\tp.w.Header().Set(\"Allow\", strings.Join(methods, \", \"))\n\tp.w.WriteHeader(http.StatusOK)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\tasp \"golang.org/x/exp/aspectgo/aspect\"\n)\n\n\ntype ExampleAspect struct {\n}\n\n\n\n\n\nfunc (a *ExampleAspect) Advice(ctx asp.Context) []interface{} {\n\targs := ctx.Args()\n\tfmt.Printf(\"Hooking (args=%v)\\n\", args)\n\tres := ctx.Call(args)\n\treturn res\n}\n\nfunc (a *ExampleAspect) Pointcut() asp.Pointcut ", "output": "{\n\ts := \"fmt\\\\.Print.*\"\n\treturn asp.NewCallPointcutFromRegexp(s)\n}"} {"input": "package csl\nimport (\n\t\"github.com/abieberbach/goplane/extra/logging\"\n\t\"fmt\"\n)\n\ntype CslPackage struct {\n\tName string\n\tDependencies []string\n\tBaseDirectory string\n\tAircrafts []*CslAircraft\n\tValid bool\n}\n\nfunc (self *CslPackage) validate(allPackages *CslPackages) {\n\tself.checkDependencies(allPackages)\n\tif !self.Valid {\n\t\treturn\n\t}\n\tself.checkAircrafts(allPackages)\n\tif !self.Valid {\n\t\treturn\n\t}\n\tlogging.Infof(\"package \\\"%v\\\" is valid\", self.Name)\n}\n\nfunc (self *CslPackage) checkDependencies(allPackages *CslPackages) {\n\tfor _, dep := range self.Dependencies {\n\t\t_, found := allPackages.GetPackage(dep)\n\t\tif !found {\n\t\t\tself.invalidate(\"missing dependency package \\\"%v\\\"\", dep)\n\t\t}\n\t}\n}\n\nfunc (self *CslPackage) checkAircrafts(allPackages *CslPackages) {\n\tfor _, currentAircraft := range self.Aircrafts {\n\t\tok,validationMessage := currentAircraft.validate(allPackages)\n\t\tif !ok {\n\t\t\tself.invalidate(validationMessage)\n\t\t}\n\t}\n}\n\n\n\nfunc (self *CslPackage) invalidate(msg string, params... interface{}) ", "output": "{\n\tlogging.Warningf(\"invalid package \\\"%v\\\", reason: %v [base directory: %v]\", self.Name, fmt.Sprintf(msg, params...),self.BaseDirectory)\n\tself.Valid = false\n}"} {"input": "package main\n\n\n\nfunc rlim_t(i int) uint64 ", "output": "{\n\treturn uint64(i)\n}"} {"input": "package goque\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"encoding/gob\"\n)\n\n\ntype Item struct {\n\tID uint64\n\tKey []byte\n\tValue []byte\n}\n\n\nfunc (i *Item) ToString() string {\n\treturn string(i.Value)\n}\n\n\n\n\n\n\n\nfunc (i *Item) ToObject(value interface{}) error {\n\tbuffer := bytes.NewBuffer(i.Value)\n\tdec := gob.NewDecoder(buffer)\n\treturn dec.Decode(value)\n}\n\n\ntype PriorityItem struct {\n\tID uint64\n\tPriority uint8\n\tKey []byte\n\tValue []byte\n}\n\n\nfunc (pi *PriorityItem) ToString() string {\n\treturn string(pi.Value)\n}\n\n\n\n\n\n\n\nfunc (pi *PriorityItem) ToObject(value interface{}) error {\n\tbuffer := bytes.NewBuffer(pi.Value)\n\tdec := gob.NewDecoder(buffer)\n\treturn dec.Decode(value)\n}\n\n\nfunc idToKey(id uint64) []byte {\n\tkey := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(key, id)\n\treturn key\n}\n\n\n\n\nfunc keyToID(key []byte) uint64 ", "output": "{\n\treturn binary.BigEndian.Uint64(key)\n}"} {"input": "package api\n\nimport (\n\t\"errors\"\n\t\"os/user\"\n)\n\nconst (\n\tcountOfColumnsInGroup = 3\n\n\tnameColumnNumberInGroup = 0\n\n\tpasswordFlagColumnNumberInGroup = 1\n\n\tgidColumnNumberInGroup = 2\n\n\tusersColumnNumberInGroup = 3\n)\n\n\n\nfunc (linux *Linux) groupLookupByID(groupID string) (*user.Group, error) {\n\tgroupInfo, err := linux.getEntity(\"group\", groupID)\n\n\tif err != nil {\n\t\treturn nil, user.UnknownGroupIdError(groupID)\n\t}\n\n\tif len(groupInfo) < countOfColumnsInGroup {\n\t\treturn nil, errors.New(\"Wrong format of /etc/group\")\n\t}\n\n\tgroup := user.Group{\n\t\tGid: groupInfo[gidColumnNumberInGroup],\n\t\tName: groupInfo[nameColumnNumberInGroup],\n\t}\n\n\treturn &group, err\n}\n\n\nfunc (linux *Linux) GroupExists(groupName string) bool {\n\tgroup, _ := linux.groupLookup(groupName)\n\treturn group != nil\n}\n\nfunc (linux *Linux) groupExistsByID(groupID string) bool {\n\tgroup, _ := linux.groupLookupByID(groupID)\n\treturn group != nil\n}\n\nfunc (linux *Linux) groupLookup(groupName string) (*user.Group, error) ", "output": "{\n\tgroupInfo, err := linux.getEntity(\"group\", groupName)\n\n\tif err != nil {\n\t\treturn nil, user.UnknownGroupError(groupName)\n\t}\n\n\tif len(groupInfo) < countOfColumnsInGroup {\n\t\treturn nil, errors.New(\"Wrong format of /etc/group\")\n\t}\n\n\tgroup := user.Group{\n\t\tGid: groupInfo[gidColumnNumberInGroup],\n\t\tName: groupInfo[nameColumnNumberInGroup],\n\t}\n\n\treturn &group, err\n}"} {"input": "package v1alpha1\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"knative.dev/eventing/pkg/apis/sources/v1alpha2\"\n\t\"knative.dev/pkg/apis\"\n\tduckv1 \"knative.dev/pkg/apis/duck/v1\"\n)\n\n\n\nfunc (source *PingSource) ConvertTo(ctx context.Context, obj apis.Convertible) error {\n\tswitch sink := obj.(type) {\n\tcase *v1alpha2.PingSource:\n\t\tsink.ObjectMeta = source.ObjectMeta\n\t\tsink.Spec = v1alpha2.PingSourceSpec{\n\t\t\tSchedule: source.Spec.Schedule,\n\t\t\tJsonData: source.Spec.Data,\n\t\t}\n\t\tsink.Status = v1alpha2.PingSourceStatus{\n\t\t\tSourceStatus: duckv1.SourceStatus{\n\t\t\t\tStatus: source.Status.Status,\n\t\t\t\tSinkURI: source.Status.SinkURI,\n\t\t\t\tCloudEventAttributes: source.Status.CloudEventAttributes,\n\t\t\t},\n\t\t}\n\t\tif source.Spec.Sink != nil {\n\t\t\tsink.Spec.Sink = *source.Spec.Sink.DeepCopy()\n\t\t}\n\t\tif source.Spec.CloudEventOverrides != nil {\n\t\t\tsink.Spec.CloudEventOverrides = source.Spec.CloudEventOverrides.DeepCopy()\n\t\t}\n\t\tif source.Status.SinkURI != nil {\n\t\t\tsink.Status.SinkURI = source.Status.SinkURI.DeepCopy()\n\t\t}\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown conversion, got: %T\", sink)\n\t}\n}\n\n\n\n\n\nfunc (sink *PingSource) ConvertFrom(ctx context.Context, obj apis.Convertible) error ", "output": "{\n\tswitch source := obj.(type) {\n\tcase *v1alpha2.PingSource:\n\t\tsink.ObjectMeta = source.ObjectMeta\n\t\tsink.Spec = PingSourceSpec{\n\t\t\tSchedule: source.Spec.Schedule,\n\t\t\tData: source.Spec.JsonData,\n\t\t\tSink: source.Spec.Sink.DeepCopy(),\n\t\t\tCloudEventOverrides: source.Spec.CloudEventOverrides,\n\t\t}\n\t\tsink.Status = PingSourceStatus{\n\t\t\tSourceStatus: duckv1.SourceStatus{\n\t\t\t\tStatus: source.Status.Status,\n\t\t\t\tSinkURI: source.Status.SinkURI,\n\t\t\t\tCloudEventAttributes: source.Status.CloudEventAttributes,\n\t\t\t},\n\t\t}\n\t\tif reflect.DeepEqual(*sink.Spec.Sink, duckv1.Destination{}) {\n\t\t\tsink.Spec.Sink = nil\n\t\t}\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown conversion, got: %T\", source)\n\t}\n}"} {"input": "package loads\n\nimport \"jvmgo/ch09/instructions/base\"\nimport \"jvmgo/ch09/rtda\"\n\n\ntype ILOAD struct{ base.Index8Instruction }\n\nfunc (self *ILOAD) Execute(frame *rtda.Frame) {\n\t_iload(frame, self.Index)\n}\n\ntype ILOAD_0 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_0) Execute(frame *rtda.Frame) {\n\t_iload(frame, 0)\n}\n\ntype ILOAD_1 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_1) Execute(frame *rtda.Frame) {\n\t_iload(frame, 1)\n}\n\ntype ILOAD_2 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_2) Execute(frame *rtda.Frame) {\n\t_iload(frame, 2)\n}\n\ntype ILOAD_3 struct{ base.NoOperandsInstruction }\n\n\n\nfunc _iload(frame *rtda.Frame, index uint) {\n\tval := frame.LocalVars().GetInt(index)\n\tframe.OperandStack().PushInt(val)\n}\n\nfunc (self *ILOAD_3) Execute(frame *rtda.Frame) ", "output": "{\n\t_iload(frame, 3)\n}"} {"input": "package p\n\nconst (\n\tzero = iota\n\tone\n\ttwo\n\tthree\n)\n\nconst iii int = 0x3\n\n\n\nconst b = \"b\"\n\nvar _ = map[string]int{\n\t\"a\": 0,\n\tb: 1,\n\t\"a\": 2, \n\t\"b\": 3, \n\t\"b\": 4, \n}\n\nfunc f(v int) ", "output": "{\n\tswitch v {\n\tcase zero, one:\n\tcase two, one: \n\n\tcase three:\n\tcase 3: \n\tcase iii: \n\t}\n}"} {"input": "package input\n\nimport (\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com/elastic/beats/libbeat/logp\"\n)\n\ntype FileStateOS struct {\n\tInode uint64 `json:\"inode,omitempty\"`\n\tDevice uint64 `json:\"device,omitempty\"`\n}\n\n\nfunc GetOSFileState(info *os.FileInfo) *FileStateOS {\n\n\tstat := (*(info)).Sys().(*syscall.Stat_t)\n\n\tfileState := &FileStateOS{\n\t\tInode: uint64(stat.Ino),\n\t\tDevice: uint64(stat.Dev),\n\t}\n\n\treturn fileState\n}\n\n\nfunc (fs *FileStateOS) IsSame(state *FileStateOS) bool {\n\treturn fs.Inode == state.Inode && fs.Device == state.Device\n}\n\n\n\n\n\nfunc ReadOpen(path string) (*os.File, error) {\n\n\tflag := os.O_RDONLY\n\tvar perm os.FileMode = 0\n\n\treturn os.OpenFile(path, flag, perm)\n}\n\nfunc SafeFileRotate(path, tempfile string) error ", "output": "{\n\tif e := os.Rename(tempfile, path); e != nil {\n\t\tlogp.Err(\"Rotate error: %s\", e)\n\t\treturn e\n\t}\n\treturn nil\n}"} {"input": "package node\n\nimport (\n\t\"errors\"\n\t\"os\"\n\n\tlog \"github.com/cihub/seelog\"\n)\n\n\ntype OptionsDirectory struct {\n\tData string\n\tStorage string\n\tKeystore string\n\tConfig string\n\tRuntime string\n}\n\n\n\n\nfunc ensureOrCreateDir(dir string) error {\n\terr := ensureDirExists(dir)\n\tif os.IsNotExist(err) {\n\t\tlog.Info(\"[Directory config checker] \", \"Directory: \", dir, \" does not exit. Creating new one\")\n\t\treturn os.MkdirAll(dir, 0700)\n\t}\n\treturn err\n}\n\nfunc ensureDirExists(dir string) error {\n\tfileStat, err := os.Stat(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isDir := fileStat.IsDir(); !isDir {\n\t\treturn errors.New(\"directory expected\")\n\t}\n\treturn nil\n}\n\nfunc (options *OptionsDirectory) Check() error ", "output": "{\n\n\tif options.Config != \"\" {\n\t\terr := ensureDirExists(options.Config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr := ensureOrCreateDir(options.Runtime)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ensureOrCreateDir(options.Storage)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ensureOrCreateDir(options.Data)\n}"} {"input": "package cli\n\nimport (\n\t\"fmt\"\n\n\t\"go.uber.org/zap\"\n\n\t\"github.com/pingcap/tidb/dumpling/log\"\n)\n\nvar (\n\tReleaseVersion = \"Unknown\"\n\tBuildTimestamp = \"Unknown\"\n\tGitHash = \"Unknown\"\n\tGitBranch = \"Unknown\"\n\tGoVersion = \"Unknown\"\n)\n\n\n\n\n\nfunc LogLongVersion(logger log.Logger) {\n\tlogger.Info(\"Welcome to dumpling\",\n\t\tzap.String(\"Release Version\", ReleaseVersion),\n\t\tzap.String(\"Git Commit Hash\", GitHash),\n\t\tzap.String(\"Git Branch\", GitBranch),\n\t\tzap.String(\"Build timestamp\", BuildTimestamp),\n\t\tzap.String(\"Go Version\", GoVersion))\n}\n\nfunc LongVersion() string ", "output": "{\n\treturn fmt.Sprintf(\n\t\t\"Release version: %s\\n\"+\n\t\t\t\"Git commit hash: %s\\n\"+\n\t\t\t\"Git branch: %s\\n\"+\n\t\t\t\"Build timestamp: %sZ\\n\"+\n\t\t\t\"Go version: %s\\n\",\n\t\tReleaseVersion,\n\t\tGitHash,\n\t\tGitBranch,\n\t\tBuildTimestamp,\n\t\tGoVersion,\n\t)\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tc := incrementor()\n\tcSum := puller(c)\n\tfor n := range cSum {\n\t\tfmt.Println(n)\n\t}\n}\n\nfunc incrementor() chan int {\n\tout := make(chan int)\n\tgo func() {\n\t\tfor i := 0; i < 10; i++ {\n\t\t\tout <- i\n\t\t}\n\t\tclose(out)\n\t}()\n\treturn out\n}\n\n\n\nfunc puller(c chan int) chan int ", "output": "{\n\tout := make(chan int)\n\tgo func() {\n\t\tvar sum int\n\t\tfor n := range c {\n\t\t\tsum += n\n\t\t}\n\t\tout <- sum\n\t\tclose(out)\n\t}()\n\treturn out\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/engine\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdGetAttributes{\n\t\tname: \"attributes\",\n\t\trpcMethod: utils.APIerSv1GetAttributeProfile,\n\t\trpcParams: &utils.TenantID{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetAttributes struct {\n\tname string\n\trpcMethod string\n\trpcParams *utils.TenantID\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetAttributes) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdGetAttributes) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\n\n\nfunc (self *CmdGetAttributes) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetAttributes) RpcResult() interface{} {\n\tvar atr engine.AttributeProfile\n\treturn &atr\n}\n\nfunc (self *CmdGetAttributes) RpcParams(reset bool) interface{} ", "output": "{\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &utils.TenantID{}\n\t}\n\treturn self.rpcParams\n}"} {"input": "package openstack\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/resource\"\n)\n\n\n\nfunc TestAccOpenStackLBPoolV1_importBasic(t *testing.T) ", "output": "{\n\tresourceName := \"openstack_lb_pool_v1.pool_1\"\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testAccCheckLBV1PoolDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccLBV1Pool_basic,\n\t\t\t},\n\n\t\t\tresource.TestStep{\n\t\t\t\tResourceName: resourceName,\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t\tImportStateVerifyIgnore: []string{\"region\"},\n\t\t\t},\n\t\t},\n\t})\n}"} {"input": "package nom\n\nimport (\n\t\"encoding/gob\"\n\t\"fmt\"\n)\n\n\nconst (\n\tPortFlood UID = \"Ports.PortBcast\"\n\tPortAll UID = \"Ports.PortAll\"\n)\n\n\ntype PacketIn struct {\n\tNode UID\n\tInPort UID\n\tBufferID PacketBufferID\n\tPacket Packet\n}\n\nfunc (in PacketIn) String() string {\n\treturn fmt.Sprintf(\"packet in on switch %s port %s\", in.Node, in.InPort)\n}\n\n\ntype PacketOut struct {\n\tNode UID\n\tInPort UID\n\tBufferID PacketBufferID\n\tPacket Packet\n\tActions []Action\n}\n\n\ntype Packet []byte\n\n\nfunc (p Packet) DstMAC() MACAddr {\n\treturn MACAddr{p[0], p[1], p[2], p[3], p[4], p[5]}\n}\n\n\nfunc (p Packet) SrcMAC() MACAddr {\n\treturn MACAddr{p[6], p[7], p[8], p[9], p[10], p[11]}\n}\n\n\n\n\ntype PacketBufferID uint32\n\n\n\nfunc init() ", "output": "{\n\tgob.Register(Packet{})\n\tgob.Register(PacketBufferID(0))\n\tgob.Register(PacketIn{})\n\tgob.Register(PacketOut{})\n}"} {"input": "package cli\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n)\n\n\n\n\n\nfunc CheckFatalError(err error) {\n\tif err != nil {\n\t\tCheckError(fmt.Errorf(\"Fatal error: %v\", err))\n\t}\n}\n\n\nfunc FileExists(path string) bool {\n\t_, err := os.Stat(path)\n\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\n\treturn false\n}\n\n\nfunc WritePid(pidfile string) {\n\tdirname := path.Dir(pidfile)\n\tif !FileExists(dirname) {\n\t\tCheckFatalError(fmt.Errorf(\"Directory \\\"%s\\\" doesn't exist\", dirname))\n\t}\n\n\tif FileExists(pidfile) {\n\t\tCheckFatalError(fmt.Errorf(\"File \\\"%s\\\" already exist\", pidfile))\n\t}\n\n\tpid := os.Getpid()\n\terr := ioutil.WriteFile(pidfile, []byte(strconv.Itoa(pid)), os.FileMode(0644))\n\tCheckFatalError(err)\n}\n\n\nfunc StopExecution(code int, pidfile string) {\n\tos.Remove(pidfile)\n\tos.Exit(code)\n}\n\nfunc CheckError(err error) ", "output": "{\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/nordsieck/defect\"\n)\n\nconst (\n\tPlaylistItems = \"https://www.googleapis.com/youtube/v3/playlistItems\"\n\n\tKey = \"key\"\n\tPart = \"part\"\n\tContentDetails = \"contentDetails\"\n\tPlaylistID = \"playlistId\"\n\tMaxResults = \"maxResults\"\n\tPageToken = \"pageToken\"\n\n\tErrDeserializeInput = defect.Error(\"Unable to deserialize input\")\n\n\tMaxPlaylistItems = \"50\" \n)\n\nfunc GetPlaylistFragment(key, playlist, token string) (videoIDs []string, pageToken string, e error) {\n\tparams := url.Values{\n\t\tKey: {key},\n\t\tPart: {ContentDetails},\n\t\tPlaylistID: {playlist},\n\t\tMaxResults: {MaxPlaylistItems},\n\t}\n\tif token != \"\" {\n\t\tparams[PageToken] = []string{token}\n\t}\n\tresp, err := http.Get(PlaylistItems + \"?\" + params.Encode())\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tpl, err := DeserializePlaylist(resp.Body)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\treturn pl.VideoIDs(), pl.NextPageToken, nil\n}\n\n\n\nfunc PlaylistVideos(key, playlist string) ([]string, error) ", "output": "{\n\tfullList := []string{}\n\n\ttoken := \"\"\n\tfor {\n\t\tvar list []string\n\t\tvar err error\n\t\tlist, token, err = GetPlaylistFragment(key, playlist, token)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfullList = append(fullList, list...)\n\t\tif token == \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn fullList, nil\n}"} {"input": "package main\n\n\n\n\n\ntype Scope struct {\n\tparent *Scope \n\tentities map[string]*Decl\n}\n\nfunc NewScope(outer *Scope) *Scope {\n\ts := new(Scope)\n\ts.parent = outer\n\ts.entities = make(map[string]*Decl)\n\treturn s\n}\n\n\nfunc AdvanceScope(s *Scope) (*Scope, *Scope) {\n\tif len(s.entities) == 0 {\n\t\treturn s, s.parent\n\t}\n\treturn NewScope(s), s\n}\n\n\nfunc (s *Scope) addNamedDecl(d *Decl) *Decl {\n\treturn s.addDecl(d.Name, d)\n}\n\nfunc (s *Scope) addDecl(name string, d *Decl) *Decl {\n\tdecl, ok := s.entities[name]\n\tif !ok {\n\t\ts.entities[name] = d\n\t\treturn d\n\t}\n\treturn decl\n}\n\n\n\nfunc (s *Scope) mergeDecl(d *Decl) {\n\tdecl, ok := s.entities[d.Name]\n\tif !ok {\n\t\ts.entities[d.Name] = d\n\t} else {\n\t\tdecl := decl.DeepCopy()\n\t\tdecl.ExpandOrReplace(d)\n\t\ts.entities[d.Name] = decl\n\t}\n}\n\nfunc (s *Scope) lookup(name string) *Decl {\n\tdecl, ok := s.entities[name]\n\tif !ok {\n\t\tif s.parent != nil {\n\t\t\treturn s.parent.lookup(name)\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn decl\n}\n\nfunc (s *Scope) replaceDecl(name string, d *Decl) ", "output": "{\n\ts.entities[name] = d\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc Test(t *testing.T) ", "output": "{\n\ttext := []byte(\"My name is Astaxie\")\n\tkey := []byte(\"the-key-has-to-be-32-bytes-long!\")\n\n\tciphertext, err := encrypt(text, key)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to encrypt with err: %v\", err)\n\t}\n\n\tplaintext, err := decrypt(ciphertext, key)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to encrypt with err: %v\", err)\n\t}\n\tif string(plaintext) != string(text) {\n\t\tt.Errorf(\"Expected : %v but got : %v\", string(text), string(plaintext))\n\t}\n\n}"} {"input": "package model\n\nimport (\n\t\"fmt\"\n)\n\ntype APIEndpoints []APIEndpoint\n\n\nconst DefaultAPIEndpointName = \"Default\"\n\n\n\n\n\nfunc (e APIEndpoints) Validate() error {\n\tfor i, apiEndpoint := range e {\n\t\tif err := apiEndpoint.Validate(); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid apiEndpoint \\\"%s\\\" at index %d: %v\", apiEndpoint.Name, i, err)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc NewDefaultAPIEndpoints(dnsName string, subnets []SubnetReference, hostedZoneId string, createRecordSet bool, recordSetTTL int, private bool) APIEndpoints ", "output": "{\n\treturn []APIEndpoint{\n\t\tAPIEndpoint{\n\t\t\tName: DefaultAPIEndpointName,\n\t\t\tDNSName: dnsName,\n\t\t\tLoadBalancer: APIEndpointLB{\n\t\t\t\tAPIAccessAllowedSourceCIDRs: DefaultCIDRRanges(),\n\t\t\t\tSubnetReferences: subnets,\n\t\t\t\tHostedZone: HostedZone{\n\t\t\t\t\tIdentifier: Identifier{\n\t\t\t\t\t\tID: hostedZoneId,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tCreateRecordSet: &createRecordSet,\n\t\t\t\tRecordSetTTLSpecified: &recordSetTTL,\n\t\t\t\tPrivateSpecified: &private,\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package trie\n\nimport \"fmt\"\n\ntype FullNode struct {\n\ttrie *Trie\n\tnodes [17]Node\n}\n\nfunc NewFullNode(t *Trie) *FullNode {\n\treturn &FullNode{trie: t}\n}\n\nfunc (self *FullNode) Dirty() bool { return true }\nfunc (self *FullNode) Value() Node {\n\tself.nodes[16] = self.trie.trans(self.nodes[16])\n\treturn self.nodes[16]\n}\nfunc (self *FullNode) Branches() []Node {\n\treturn self.nodes[:16]\n}\n\nfunc (self *FullNode) Copy(t *Trie) Node {\n\tnnode := NewFullNode(t)\n\tfor i, node := range self.nodes {\n\t\tif node != nil {\n\t\t\tnnode.nodes[i] = node.Copy(t)\n\t\t}\n\t}\n\n\treturn nnode\n}\n\n\n\n\nfunc (self *FullNode) Hash() interface{} {\n\treturn self.trie.store(self)\n}\n\nfunc (self *FullNode) RlpData() interface{} {\n\tt := make([]interface{}, 17)\n\tfor i, node := range self.nodes {\n\t\tif node != nil {\n\t\t\tt[i] = node.Hash()\n\t\t} else {\n\t\t\tt[i] = \"\"\n\t\t}\n\t}\n\n\treturn t\n}\n\nfunc (self *FullNode) set(k byte, value Node) {\n\tif _, ok := value.(*ValueNode); ok && k != 16 {\n\t\tfmt.Println(value, k)\n\t}\n\n\tself.nodes[int(k)] = value\n}\n\nfunc (self *FullNode) branch(i byte) Node {\n\tif self.nodes[int(i)] != nil {\n\t\tself.nodes[int(i)] = self.trie.trans(self.nodes[int(i)])\n\n\t\treturn self.nodes[int(i)]\n\t}\n\treturn nil\n}\n\nfunc (self *FullNode) Len() (amount int) ", "output": "{\n\tfor _, node := range self.nodes {\n\t\tif node != nil {\n\t\t\tamount++\n\t\t}\n\t}\n\n\treturn\n}"} {"input": "package google\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype SpannerOperationWaiter struct {\n\tConfig *Config\n\tUserAgent string\n\tProject string\n\tCommonOperationWaiter\n}\n\nfunc (w *SpannerOperationWaiter) QueryOp() (interface{}, error) {\n\tif w == nil {\n\t\treturn nil, fmt.Errorf(\"Cannot query operation, it's unset or nil.\")\n\t}\n\turl := fmt.Sprintf(\"%s%s\", w.Config.SpannerBasePath, w.CommonOperationWaiter.Op.Name)\n\n\treturn sendRequest(w.Config, \"GET\", w.Project, url, w.UserAgent, nil)\n}\n\nfunc createSpannerWaiter(config *Config, op map[string]interface{}, project, activity, userAgent string) (*SpannerOperationWaiter, error) {\n\tw := &SpannerOperationWaiter{\n\t\tConfig: config,\n\t\tUserAgent: userAgent,\n\t\tProject: project,\n\t}\n\tif err := w.CommonOperationWaiter.SetOp(op); err != nil {\n\t\treturn nil, err\n\t}\n\treturn w, nil\n}\n\n\n\n\nfunc spannerOperationWaitTime(config *Config, op map[string]interface{}, project, activity, userAgent string, timeout time.Duration) error {\n\tif val, ok := op[\"name\"]; !ok || val == \"\" {\n\t\treturn nil\n\t}\n\tw, err := createSpannerWaiter(config, op, project, activity, userAgent)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn OperationWait(w, activity, timeout, config.PollInterval)\n}\n\nfunc spannerOperationWaitTimeWithResponse(config *Config, op map[string]interface{}, response *map[string]interface{}, project, activity, userAgent string, timeout time.Duration) error ", "output": "{\n\tw, err := createSpannerWaiter(config, op, project, activity, userAgent)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := OperationWait(w, activity, timeout, config.PollInterval); err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal([]byte(w.CommonOperationWaiter.Op.Response), response)\n}"} {"input": "package sarif\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"net\"\n\t\"time\"\n)\n\ntype netConn struct {\n\tconn net.Conn\n\tenc *json.Encoder\n\tdec *json.Decoder\n\tverified bool\n}\n\nfunc newNetConn(conn net.Conn) *netConn {\n\treturn &netConn{\n\t\tconn,\n\t\tjson.NewEncoder(conn),\n\t\tjson.NewDecoder(conn),\n\t\tfalse,\n\t}\n}\n\nfunc (c *netConn) Write(msg Message) error {\n\tif err := msg.IsValid(); err != nil {\n\t\treturn err\n\t}\n\tc.conn.SetWriteDeadline(time.Now().Add(5 * time.Minute))\n\treturn c.enc.Encode(msg)\n}\n\nfunc (c *netConn) KeepaliveLoop(ka time.Duration) error {\n\tfor {\n\t\ttime.Sleep(ka)\n\t\tc.conn.SetWriteDeadline(time.Now().Add(3 * ka))\n\t\tif _, err := c.conn.Write([]byte(\" \")); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\nfunc (c *netConn) Read() (Message, error) {\n\tvar msg Message\n\tc.conn.SetReadDeadline(time.Now().Add(time.Hour))\n\tif err := c.dec.Decode(&msg); err != nil {\n\t\treturn msg, err\n\t}\n\treturn msg, msg.IsValid()\n}\n\nfunc (c *netConn) Close() error {\n\treturn c.conn.Close()\n}\n\n\n\nfunc (c *netConn) IsVerified() bool ", "output": "{\n\tif tc, ok := c.conn.(*tls.Conn); ok {\n\t\tif len(tc.ConnectionState().VerifiedChains) > 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package signingtest\n\nimport (\n\t\"context\"\n\t\"crypto/x509\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestSigner(t *testing.T) ", "output": "{\n\tConvey(\"Works\", t, func() {\n\t\tctx := context.Background()\n\n\t\ts := NewSigner(nil)\n\t\tcerts, err := s.Certificates(ctx)\n\t\tSo(err, ShouldBeNil)\n\t\tSo(certs.Certificates, ShouldHaveLength, 1)\n\n\t\tkey, sig, err := s.SignBytes(ctx, []byte(\"some blob\"))\n\t\tSo(err, ShouldBeNil)\n\t\tSo(key, ShouldEqual, certs.Certificates[0].KeyName)\n\n\t\tcert, err := certs.CertificateForKey(key)\n\t\tSo(err, ShouldBeNil)\n\t\terr = cert.CheckSignature(x509.SHA256WithRSA, []byte(\"some blob\"), sig)\n\t\tSo(err, ShouldBeNil)\n\t})\n}"} {"input": "package system\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nconst (\n\texecErrorMsgFmt = \"Running command: '%s', stdout: '%s', stderr: '%s'\"\n\texecShortErrorMaxLines = 100\n)\n\ntype ExecError struct {\n\tCommand string\n\tStdOut string\n\tStdErr string\n}\n\n\n\nfunc (e ExecError) Error() string {\n\treturn fmt.Sprintf(execErrorMsgFmt, e.Command, e.StdOut, e.StdErr)\n}\n\n\nfunc (e ExecError) ShortError() string {\n\toutStr := e.truncateStr(e.StdOut, execShortErrorMaxLines)\n\terrStr := e.truncateStr(e.StdErr, execShortErrorMaxLines)\n\treturn fmt.Sprintf(execErrorMsgFmt, e.Command, outStr, errStr)\n}\n\nfunc (e ExecError) truncateStr(in string, maxLines int) string {\n\toutLines := strings.Split(in, \"\\n\")\n\tif i := len(outLines); i > maxLines {\n\t\toutLines = outLines[i-maxLines:]\n\t}\n\n\treturn strings.Join(outLines, \"\\n\")\n}\n\nfunc NewExecError(cmd, stdout, stderr string) ExecError ", "output": "{\n\treturn ExecError{\n\t\tCommand: cmd,\n\t\tStdOut: stdout,\n\t\tStdErr: stderr,\n\t}\n}"} {"input": "package mem\n\nimport (\n\t\"bytes\"\n\t\"sort\"\n\n\tsgmt \"github.com/m3db/m3/src/m3ninx/index/segment\"\n)\n\ntype bytesSliceIter struct {\n\terr error\n\tdone bool\n\n\tcurrentIdx int\n\tcurrent []byte\n\tbackingSlice [][]byte\n\topts Options\n}\n\nvar _ sgmt.FieldsIterator = &bytesSliceIter{}\n\nfunc newBytesSliceIter(slice [][]byte, opts Options) *bytesSliceIter {\n\tsortSliceOfByteSlices(slice)\n\treturn &bytesSliceIter{\n\t\tcurrentIdx: -1,\n\t\tbackingSlice: slice,\n\t\topts: opts,\n\t}\n}\n\nfunc (b *bytesSliceIter) Next() bool {\n\tif b.done || b.err != nil {\n\t\treturn false\n\t}\n\tb.currentIdx++\n\tif b.currentIdx >= len(b.backingSlice) {\n\t\tb.done = true\n\t\treturn false\n\t}\n\tb.current = b.backingSlice[b.currentIdx]\n\treturn true\n}\n\nfunc (b *bytesSliceIter) Current() []byte {\n\treturn b.current\n}\n\nfunc (b *bytesSliceIter) Err() error {\n\treturn nil\n}\n\nfunc (b *bytesSliceIter) Len() int {\n\treturn len(b.backingSlice)\n}\n\n\n\nfunc sortSliceOfByteSlices(b [][]byte) {\n\tsort.Slice(b, func(i, j int) bool {\n\t\treturn bytes.Compare(b[i], b[j]) < 0\n\t})\n}\n\nfunc (b *bytesSliceIter) Close() error ", "output": "{\n\tb.current = nil\n\tb.opts.BytesSliceArrayPool().Put(b.backingSlice)\n\treturn nil\n}"} {"input": "package tracers\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\n\t\"github.com/ethereum/go-ethereum/common\"\n\t\"github.com/ethereum/go-ethereum/core/vm\"\n)\n\n\n\ntype Context struct {\n\tBlockHash common.Hash \n\tTxIndex int \n\tTxHash common.Hash \n}\n\n\n\ntype Tracer interface {\n\tvm.EVMLogger\n\tGetResult() (json.RawMessage, error)\n\tStop(err error)\n}\n\ntype lookupFunc func(string, *Context) (Tracer, error)\n\nvar (\n\tlookups []lookupFunc\n)\n\n\n\n\n\n\n\n\n\nfunc New(code string, ctx *Context) (Tracer, error) {\n\tfor _, lookup := range lookups {\n\t\tif tracer, err := lookup(code, ctx); err == nil {\n\t\t\treturn tracer, nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"tracer not found\")\n}\n\nfunc RegisterLookup(wildcard bool, lookup lookupFunc) ", "output": "{\n\tif wildcard {\n\t\tlookups = append(lookups, lookup)\n\t} else {\n\t\tlookups = append([]lookupFunc{lookup}, lookups...)\n\t}\n}"} {"input": "package cmd\n\nimport (\n\t\"errors\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"github.com/djherbis/atime\"\n\t\"golang.org/x/sys/windows/registry\"\n)\n\n\n\n\nfunc checkAtimeSupport(dir string) (err error) ", "output": "{\n\tfile, err := ioutil.TempFile(dir, \"prefix\")\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer os.Remove(file.Name())\n\tdefer file.Close()\n\tfinfo1, err := os.Stat(file.Name())\n\tif err != nil {\n\t\treturn\n\t}\n\tatime.Get(finfo1)\n\n\tk, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\\CurrentControlSet\\Control\\FileSystem`, registry.QUERY_VALUE)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer k.Close()\n\n\tsetting, _, err := k.GetIntegerValue(\"NtfsDisableLastAccessUpdate\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tlowSetting := setting & 0xFFFF\n\tif lowSetting != uint64(0x0000) && lowSetting != uint64(0x0002) {\n\t\treturn errors.New(\"Atime not supported\")\n\t}\n\treturn\n}"} {"input": "package cmd\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\n\nfunc TestUNCPaths(t *testing.T) {\n\tvar testCases = []struct {\n\t\tobjName string\n\t\tpass bool\n\t}{\n\t\t{\"/abcdef\", true},\n\t\t{\"/a/b/c/d/e/f/g\", true},\n\t\t{string(bytes.Repeat([]byte(\"界\"), 85)), true},\n\t\t{string(bytes.Repeat([]byte(\"界\"), 280)), false},\n\t\t{`/p/q/r/s/t`, true},\n\t}\n\tdir, err := ioutil.TempDir(\"\", \"testdisk-\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\n\tvar fs StorageAPI\n\tfs, err = newXLStorage(dir, \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = fs.MakeVol(\"voldir\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tfor i, test := range testCases {\n\t\tt.Run(fmt.Sprint(i), func(t *testing.T) {\n\t\t\terr = fs.AppendFile(\"voldir\", test.objName, []byte(\"hello\"))\n\t\t\tif err != nil && test.pass {\n\t\t\t\tt.Error(err)\n\t\t\t} else if err == nil && !test.pass {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tfs.DeleteFile(\"voldir\", test.objName)\n\t\t})\n\t}\n}\n\n\n\n\nfunc TestUNCPathENOTDIR(t *testing.T) ", "output": "{\n\tdir, err := ioutil.TempDir(\"\", \"testdisk-\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\n\tvar fs StorageAPI\n\tfs, err = newXLStorage(dir, \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = fs.MakeVol(\"voldir\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = fs.AppendFile(\"voldir\", \"/file\", []byte(\"hello\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = fs.AppendFile(\"voldir\", \"/file/obj1\", []byte(\"hello\"))\n\tif err != errFileAccessDenied {\n\t\tt.Errorf(\"expected: %s, got: %s\", errFileAccessDenied, err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\n\n\n\n\n\nfunc setupStdin() ", "output": "{\n\tr, w, _ := os.Pipe()\n\toriginalStdin := os.Stdin\n\tos.Stdin = r\n\n\tgo func() {\n\t\tdefer w.Close()\n\t\tio.Copy(w, originalStdin)\n\t}()\n\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, os.Interrupt, syscall.SIGTERM)\n\n\tgo func() {\n\t\tdefer signal.Stop(ch)\n\t\tdefer w.Close()\n\t\t<-ch\n\t\tlog.Println(\"Closing stdin because interrupt received.\")\n\t}()\n}"} {"input": "package journal\n\nimport (\n\t\"time\"\n\n\t\"nirenjan.org/overlord/database\"\n\t\"nirenjan.org/overlord/util\"\n)\n\n\n\n\n\ntype DBEntry struct {\n\tTitle string\n\tDate time.Time\n\tTags []string\n\tPath string\n}\n\nvar DB = make(map[string]DBEntry)\n\n\n\nfunc AddDbEntry(entry Entry) {\n\tvar dbEntry = DBEntry{\n\t\tTitle: entry.Title,\n\t\tDate: entry.Date,\n\t\tTags: entry.Tags,\n\t\tPath: entry.Path,\n\t}\n\n\tid := entry.ID\n\n\tDB[id] = dbEntry\n}\n\nfunc DeleteDbEntry(entry Entry) {\n\tdelete(DB, entry.ID)\n}\n\nfunc SaveDb() error {\n\treturn database.Save(DB)\n}\n\nfunc LoadDb() error {\n\treturn database.Load(&DB, BuildDb)\n}\n\nfunc BuildDb() error ", "output": "{\n\terr := util.FileWalk(\"journal\", \".entry\", func(path string) error {\n\t\tentry, err1 := entryFromFile(path)\n\t\tif err1 != nil {\n\t\t\treturn err1\n\t\t}\n\n\t\tAddDbEntry(entry)\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn SaveDb()\n}"} {"input": "package integration\n\nimport (\n\t\"os\"\n\t\"runtime\"\n\t\"testing\"\n\n\t\"github.com/opencontainers/runc/libcontainer\"\n\t_ \"github.com/opencontainers/runc/libcontainer/nsenter\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\n\n\nfunc init() {\n\tif len(os.Args) < 2 || os.Args[1] != \"init\" {\n\t\treturn\n\t}\n\truntime.GOMAXPROCS(1)\n\truntime.LockOSThread()\n\tfactory, err := libcontainer.New(\"\")\n\tif err != nil {\n\t\tlogrus.Fatalf(\"unable to initialize for container: %s\", err)\n\t}\n\tif err := factory.StartInitialization(); err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n}\n\nvar testRoots []string\n\n\n\nfunc TestMain(m *testing.M) ", "output": "{\n\tlogrus.SetOutput(os.Stderr)\n\tlogrus.SetLevel(logrus.InfoLevel)\n\n\tdefer func() {\n\t\tfor _, root := range testRoots {\n\t\t\tos.RemoveAll(root)\n\t\t}\n\t}()\n\n\tret := m.Run()\n\tos.Exit(ret)\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\n\tv1beta1 \"kubevirt.io/client-go/generated/containerized-data-importer/clientset/versioned/typed/core/v1beta1\"\n)\n\ntype FakeCdiV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeCdiV1beta1) CDIs() v1beta1.CDIInterface {\n\treturn &FakeCDIs{c}\n}\n\nfunc (c *FakeCdiV1beta1) CDIConfigs() v1beta1.CDIConfigInterface {\n\treturn &FakeCDIConfigs{c}\n}\n\nfunc (c *FakeCdiV1beta1) DataImportCrons(namespace string) v1beta1.DataImportCronInterface {\n\treturn &FakeDataImportCrons{c, namespace}\n}\n\n\n\nfunc (c *FakeCdiV1beta1) DataVolumes(namespace string) v1beta1.DataVolumeInterface {\n\treturn &FakeDataVolumes{c, namespace}\n}\n\nfunc (c *FakeCdiV1beta1) ObjectTransfers() v1beta1.ObjectTransferInterface {\n\treturn &FakeObjectTransfers{c}\n}\n\nfunc (c *FakeCdiV1beta1) StorageProfiles() v1beta1.StorageProfileInterface {\n\treturn &FakeStorageProfiles{c}\n}\n\n\n\nfunc (c *FakeCdiV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeCdiV1beta1) DataSources(namespace string) v1beta1.DataSourceInterface ", "output": "{\n\treturn &FakeDataSources{c, namespace}\n}"} {"input": "package methodoverride\n\nimport (\n\t\"strings\"\n\n\t\"github.com/rkgo/web\"\n)\n\nconst (\n\toverrideFormField = \"_method\"\n\toverrideHeader = \"X-HTTP-Method-Override\"\n)\n\n\n\n\n\n\nfunc Middleware() web.Middleware ", "output": "{\n\treturn func(ctx web.Context, next web.Next) {\n\t\tif ctx.Req().Method == \"POST\" {\n\t\t\tmethod := ctx.Req().FormValue(overrideFormField)\n\n\t\t\tif len(ctx.Req().Header.Get(overrideHeader)) > 0 {\n\t\t\t\tmethod = ctx.Req().Header.Get(overrideHeader)\n\t\t\t}\n\n\t\t\tif len(method) > 0 {\n\t\t\t\tmethod = strings.ToUpper(method)\n\n\t\t\t\tswitch method {\n\t\t\t\tcase \"PUT\", \"PATCH\", \"DELETE\":\n\t\t\t\t\tctx.Req().Method = method\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnext(ctx)\n\t}\n}"} {"input": "package greq\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\nfunc Bytes(res *http.Response, err error) ([]byte, error) {\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn body, nil\n}\n\nfunc String(res *http.Response, err error) (string, error) {\n\tbody, err := Bytes(res, err)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}\n\n\n\nfunc JSON(res *http.Response, err error, ptr interface{}) error ", "output": "{\n\tbody, err := Bytes(res, err)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(body, ptr)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\nvar (\n\tn, l, count int\n\tout io.WriteCloser\n)\n\nfunc isEasy(level int, sequence []string) bool {\nhere:\n\tfor i := 1; 2*i <= level+1; i++ {\n\t\tfor j := 0; j < i; j++ {\n\t\t\tif sequence[level-j] != sequence[level-j-i] {\n\t\t\t\tcontinue here\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc output(sequence []string) {\n\tfor i := range sequence {\n\t\tswitch {\n\t\tcase i > 0 && i%64 == 0:\n\t\t\tfmt.Fprintln(out)\n\t\tcase i > 0 && i%4 == 0:\n\t\t\tfmt.Fprint(out, \" \")\n\t\t}\n\t\tfmt.Fprint(out, sequence[i])\n\t}\n\tfmt.Fprintf(out, \"\\n%d\\n\", len(sequence))\n}\n\n\n\nfunc main() {\n\tin, _ := os.Open(\"129.in\")\n\tdefer in.Close()\n\tout, _ = os.Create(\"129.out\")\n\tdefer out.Close()\n\n\tfor {\n\t\tif fmt.Fscanf(in, \"%d%d\", &n, &l); n == 0 && l == 0 {\n\t\t\tbreak\n\t\t}\n\t\tcount = 0\n\t\tdfs(0, nil)\n\t}\n}\n\nfunc dfs(level int, sequence []string) bool ", "output": "{\n\tif count == n {\n\t\toutput(sequence)\n\t\treturn true\n\t}\n\tcount++\n\tfor i := 0; i < l; i++ {\n\t\tif !isEasy(level, append(sequence, string('A'+i))) {\n\t\t\tif dfs(level+1, append(sequence, string('A'+i))) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package unit\n\nimport (\n\t\"github.com/juju/cmd\"\n\t\"github.com/juju/names/v4\"\n\t\"github.com/juju/utils/v2/voyeur\"\n\n\t\"github.com/juju/juju/agent\"\n\t\"github.com/juju/juju/cmd/containeragent/utils\"\n\t\"github.com/juju/juju/cmd/jujud/agent/agentconf\"\n\t\"github.com/juju/juju/worker/logsender\"\n)\n\ntype (\n\tManifoldsConfig = manifoldsConfig\n\tContainerUnitAgent = containerUnitAgent\n)\n\ntype ContainerUnitAgentTest interface {\n\tcmd.Command\n\tDataDir() string\n\tSetAgentConf(cfg agentconf.AgentConf)\n\tChangeConfig(change agent.ConfigMutator) error\n\tCurrentConfig() agent.Config\n\tTag() names.UnitTag\n\tCharmModifiedVersion() int\n\tGetContainerNames() []string\n}\n\nfunc NewForTest(\n\tctx *cmd.Context,\n\tbufferedLogger *logsender.BufferedLogWriter,\n\tconfigChangedVal *voyeur.Value,\n\tfileReaderWriter utils.FileReaderWriter,\n\tenvironment utils.Environment,\n) ContainerUnitAgentTest {\n\treturn &containerUnitAgent{\n\t\tctx: ctx,\n\t\tAgentConf: agentconf.NewAgentConf(\"\"),\n\t\tbufferedLogger: bufferedLogger,\n\t\tconfigChangedVal: configChangedVal,\n\t\tfileReaderWriter: fileReaderWriter,\n\t\tenvironment: environment,\n\t}\n}\n\n\n\nfunc (c *containerUnitAgent) GetContainerNames() []string {\n\treturn c.containerNames\n}\n\nfunc (c *containerUnitAgent) DataDir() string {\n\treturn c.AgentConf.DataDir()\n}\n\nfunc (c *containerUnitAgent) SetAgentConf(cfg agentconf.AgentConf) ", "output": "{\n\tc.AgentConf = cfg\n}"} {"input": "package braille\n\n\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestDot(t *testing.T) {\n\tfmt.Println(\"0x28C1 =\", Dot(0x28c1))\n\tfmt.Println(\"0x282D =\", Dot(0x282D))\n\tfmt.Println(\"0x28BF =\", Dot(0x28BF))\n\tfmt.Println(\"0x28FF =\", Dot(0x28FF))\n\n}\n\n\n\nfunc TestNumber(t *testing.T) {\n\tfor _, c := range \"1234567890\" {\n\t\tfmt.Printf(\"%c : %c\\n\", c, Alphabet(c))\n\t}\n}\n\nfunc TestAlphabet(t *testing.T) {\n\ts := \"HackTime for Google Hackfair 2012-09-01\"\n\tfmt.Println(s)\n\tfmt.Println(Encode(s))\n}\n\nfunc TestCode(t *testing.T) ", "output": "{\n\tfmt.Printf(\"1-5-6-7 -> %c\\n\", Rune(1, 5, 6, 7))\n\tfmt.Printf(\"1-2-3-4-5-6-7-8 -> %c\\n\", Rune(1, 2, 3, 4, 5, 6, 7, 8))\n}"} {"input": "package model\n\n\n\ntype ResourceAssignment struct {\n\t*Record\n}\n\nfunc (ra *ResourceAssignment) Resource() string {\n\treturn ra.ID\n}\n\n\n\n\n\n\nfunc (ra *ResourceAssignment) ReplicaMap(partition string) map[string]string {\n\treturn nil\n}\n\nfunc (ra *ResourceAssignment) MappedPartitions() []string ", "output": "{\n\treturn nil\n}"} {"input": "package trie\n\nimport \"fmt\"\n\ntype FullNode struct {\n\ttrie *Trie\n\tnodes [17]Node\n}\n\nfunc NewFullNode(t *Trie) *FullNode {\n\treturn &FullNode{trie: t}\n}\n\nfunc (self *FullNode) Dirty() bool { return true }\nfunc (self *FullNode) Value() Node {\n\tself.nodes[16] = self.trie.trans(self.nodes[16])\n\treturn self.nodes[16]\n}\nfunc (self *FullNode) Branches() []Node {\n\treturn self.nodes[:16]\n}\n\nfunc (self *FullNode) Copy(t *Trie) Node {\n\tnnode := NewFullNode(t)\n\tfor i, node := range self.nodes {\n\t\tif node != nil {\n\t\t\tnnode.nodes[i] = node.Copy(t)\n\t\t}\n\t}\n\n\treturn nnode\n}\n\n\nfunc (self *FullNode) Len() (amount int) {\n\tfor _, node := range self.nodes {\n\t\tif node != nil {\n\t\t\tamount++\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (self *FullNode) Hash() interface{} {\n\treturn self.trie.store(self)\n}\n\n\n\nfunc (self *FullNode) set(k byte, value Node) {\n\tif _, ok := value.(*ValueNode); ok && k != 16 {\n\t\tfmt.Println(value, k)\n\t}\n\n\tself.nodes[int(k)] = value\n}\n\nfunc (self *FullNode) branch(i byte) Node {\n\tif self.nodes[int(i)] != nil {\n\t\tself.nodes[int(i)] = self.trie.trans(self.nodes[int(i)])\n\n\t\treturn self.nodes[int(i)]\n\t}\n\treturn nil\n}\n\nfunc (self *FullNode) RlpData() interface{} ", "output": "{\n\tt := make([]interface{}, 17)\n\tfor i, node := range self.nodes {\n\t\tif node != nil {\n\t\t\tt[i] = node.Hash()\n\t\t} else {\n\t\t\tt[i] = \"\"\n\t\t}\n\t}\n\n\treturn t\n}"} {"input": "package main\n\nvar nf int\nvar ng int\n\n\n\nfunc g() int {\n\tng++\n\treturn 4\n}\n\nvar x, y, z = f()\nvar m = make(map[int]int)\nvar v, ok = m[g()]\n\nfunc main() {\n\tif x != 1 || y != 2 || z != 3 || nf != 1 || v != 0 || ok != false || ng != 1 {\n\t\tprintln(\"x=\", x, \" y=\", y, \" z=\", z, \" nf=\", nf, \" v=\", v, \" ok=\", ok, \" ng=\", ng)\n\t\tpanic(\"fail\")\n\t}\n}\n\nfunc f() (int, int, int) ", "output": "{\n\tnf++\n\treturn 1, 2, 3\n}"} {"input": "package hci\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\nconst (\n\tpairingRequest = 0x01 \n\tpairingResponse = 0x02 \n\tpairingConfirm = 0x03 \n\tpairingRandom = 0x04 \n\tpairingFailed = 0x05 \n\tencryptionInformation = 0x06 \n\tmasterIdentification = 0x07 \n\tidentiInformation = 0x08 \n\tidentityAddreInformation = 0x09 \n\tsigningInformation = 0x0A \n\tsecurityRequest = 0x0B \n\tpairingPublicKey = 0x0C \n\tpairingDHKeyCheck = 0x0D \n\tpairingKeypress = 0x0E \n)\n\nfunc (c *Conn) sendSMP(p pdu) error {\n\tbuf := bytes.NewBuffer(make([]byte, 0))\n\tbinary.Write(buf, binary.LittleEndian, uint16(4+len(p)))\n\tbinary.Write(buf, binary.LittleEndian, cidSMP)\n\tbinary.Write(buf, binary.LittleEndian, p)\n\t_, err := c.writePDU(buf.Bytes())\n\tlogger.Debug(\"smp\", \"send\", fmt.Sprintf(\"[%X]\", buf.Bytes()))\n\treturn err\n}\n\n\n\nfunc (c *Conn) handleSMP(p pdu) error ", "output": "{\n\tlogger.Debug(\"smp\", \"recv\", fmt.Sprintf(\"[%X]\", p))\n\tcode := p[0]\n\tswitch code {\n\tcase pairingRequest:\n\tcase pairingResponse:\n\tcase pairingConfirm:\n\tcase pairingRandom:\n\tcase pairingFailed:\n\tcase encryptionInformation:\n\tcase masterIdentification:\n\tcase identiInformation:\n\tcase identityAddreInformation:\n\tcase signingInformation:\n\tcase securityRequest:\n\tcase pairingPublicKey:\n\tcase pairingDHKeyCheck:\n\tcase pairingKeypress:\n\tdefault:\n\t\treturn nil\n\t}\n\treturn c.sendSMP([]byte{pairingFailed, 0x05})\n}"} {"input": "package dexcom\n\nimport (\n\t\"math\"\n)\n\n\n\nfunc marshalUint16(n uint16) []byte {\n\treturn []byte{byte(n & 0xFF), byte(n >> 8)}\n}\n\n\nfunc marshalInt16(n int16) []byte {\n\treturn marshalUint16(uint16(n))\n}\n\nfunc marshalUint32(n uint32) []byte {\n\treturn append(marshalUint16(uint16(n&0xFFFF)), marshalUint16(uint16(n>>16))...)\n}\n\nfunc marshalInt32(n int32) []byte {\n\treturn marshalUint32(uint32(n))\n}\n\nfunc unmarshalUint16(v []byte) uint16 {\n\treturn uint16(v[0]) | uint16(v[1])<<8\n}\n\n\nfunc unmarshalInt16(v []byte) int16 {\n\treturn int16(unmarshalUint16(v))\n}\n\n\n\nfunc unmarshalInt32(v []byte) int32 {\n\treturn int32(unmarshalUint32(v))\n}\n\nfunc unmarshalUint64(v []byte) uint64 {\n\treturn uint64(unmarshalUint32(v[0:4])) | uint64(unmarshalUint32(v[4:8]))<<32\n}\n\nfunc unmarshalFloat64(v []byte) float64 {\n\treturn math.Float64frombits(unmarshalUint64(v))\n}\n\nfunc unmarshalUint32(v []byte) uint32 ", "output": "{\n\treturn uint32(unmarshalUint16(v[0:2])) | uint32(unmarshalUint16(v[2:4]))<<16\n}"} {"input": "package fileutil\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\n\n\nfunc Preallocate(f *os.File, sizeInBytes int) error ", "output": "{\n\treturn syscall.Fallocate(int(f.Fd()), 1, 0, int64(sizeInBytes))\n}"} {"input": "package installer\n\nimport (\n\t\"github.com/wx13/genesis\"\n)\n\n\n\ntype Custom struct {\n\tTask genesis.Doer\n\tS func() (genesis.Status, error)\n\tD func() (bool, error)\n\tU func() (bool, error)\n\tI func() string\n\tF func() []string\n}\n\nfunc NewCustom(task genesis.Doer) *Custom {\n\tcustom := Custom{\n\t\tTask: task,\n\t\tS: task.Status,\n\t\tD: task.Do,\n\t\tU: task.Undo,\n\t\tI: task.ID,\n\t\tF: task.Files,\n\t}\n\treturn &custom\n}\n\nfunc (custom Custom) Status() (genesis.Status, error) {\n\treturn custom.S()\n}\n\nfunc (custom Custom) Do() (bool, error) {\n\treturn custom.D()\n}\n\nfunc (custom Custom) Undo() (bool, error) {\n\treturn custom.U()\n}\n\nfunc (custom Custom) ID() string {\n\treturn custom.I()\n}\n\n\n\nfunc (custom Custom) Files() []string ", "output": "{\n\treturn custom.F()\n}"} {"input": "package models\n\nimport (\n\t\"net\"\n\t\"time\"\n\n\t\"github.com/golang-jwt/jwt/v4\"\n\t\"github.com/google/uuid\"\n)\n\n\n\n\n\ntype IdentityVerification struct {\n\tID int `db:\"id\"`\n\tJTI uuid.UUID `db:\"jti\"`\n\tIssuedAt time.Time `db:\"iat\"`\n\tIssuedIP IP `db:\"issued_ip\"`\n\tExpiresAt time.Time `db:\"exp\"`\n\tAction string `db:\"action\"`\n\tUsername string `db:\"username\"`\n\tConsumed *time.Time `db:\"consumed\"`\n\tConsumedIP NullIP `db:\"consumed_ip\"`\n}\n\n\nfunc (v IdentityVerification) ToIdentityVerificationClaim() (claim *IdentityVerificationClaim) {\n\treturn &IdentityVerificationClaim{\n\t\tRegisteredClaims: jwt.RegisteredClaims{\n\t\t\tID: v.JTI.String(),\n\t\t\tIssuer: \"Authelia\",\n\t\t\tIssuedAt: jwt.NewNumericDate(v.IssuedAt),\n\t\t\tExpiresAt: jwt.NewNumericDate(v.ExpiresAt),\n\t\t},\n\t\tAction: v.Action,\n\t\tUsername: v.Username,\n\t}\n}\n\n\n\ntype IdentityVerificationClaim struct {\n\tjwt.RegisteredClaims\n\n\tAction string `json:\"action\"`\n\tUsername string `json:\"username\"`\n}\n\n\nfunc (v IdentityVerificationClaim) ToIdentityVerification() (verification *IdentityVerification, err error) {\n\tjti, err := uuid.Parse(v.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &IdentityVerification{\n\t\tJTI: jti,\n\t\tUsername: v.Username,\n\t\tAction: v.Action,\n\t\tExpiresAt: v.ExpiresAt.Time,\n\t}, nil\n}\n\nfunc NewIdentityVerification(jti uuid.UUID, username, action string, ip net.IP) (verification IdentityVerification) ", "output": "{\n\treturn IdentityVerification{\n\t\tJTI: jti,\n\t\tIssuedAt: time.Now(),\n\t\tExpiresAt: time.Now().Add(5 * time.Minute),\n\t\tAction: action,\n\t\tUsername: username,\n\t\tIssuedIP: NewIP(ip),\n\t}\n}"} {"input": "package xjsonbase\n\nimport (\n\t\"fmt\"\n\tmsg \"github.com/Centimitr/xmessage\"\n\t\"io/ioutil\"\n)\n\n\n\nfunc (j *JSONBase) Save(c *msg.Ctx) {\n\tfilename := c.Method\n\terr := ioutil.WriteFile(filename+\".json\", []byte(c.Data), 0777)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n\nfunc (j *JSONBase) Load(c *msg.Ctx) ", "output": "{\n\tfilename := c.Method\n\tdata, err := ioutil.ReadFile(filename + \".json\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tc.Data = string(data)\n}"} {"input": "package utils\n\nimport (\n\t\"sync\"\n)\n\ntype BeeMap struct {\n\tlock *sync.RWMutex\n\tbm map[interface{}]interface{}\n}\n\n\nfunc NewBeeMap() *BeeMap {\n\treturn &BeeMap{\n\t\tlock: new(sync.RWMutex),\n\t\tbm: make(map[interface{}]interface{}),\n\t}\n}\n\n\nfunc (m *BeeMap) Get(k interface{}) interface{} {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\tif val, ok := m.bm[k]; ok {\n\t\treturn val\n\t}\n\treturn nil\n}\n\n\n\n\n\n\nfunc (m *BeeMap) Check(k interface{}) bool {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\tif _, ok := m.bm[k]; !ok {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\nfunc (m *BeeMap) Delete(k interface{}) {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tdelete(m.bm, k)\n}\n\n\nfunc (m *BeeMap) Items() map[interface{}]interface{} {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\treturn m.bm\n}\n\nfunc (m *BeeMap) Set(k interface{}, v interface{}) bool ", "output": "{\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tif val, ok := m.bm[k]; !ok {\n\t\tm.bm[k] = v\n\t} else if val != v {\n\t\tm.bm[k] = v\n\t} else {\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package aws\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/aws/aws-sdk-go/aws/arn\"\n\t\"github.com/aws/aws-sdk-go/aws/endpoints\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/v2/terraform\"\n)\n\nconst (\n\tEc2ClassicRegionEnvVar = \"AWS_EC2_CLASSIC_REGION\"\n)\n\n\n\n\n\n\n\nvar testAccProviderEc2Classic *schema.Provider\n\n\nvar testAccProviderEc2ClassicConfigure sync.Once\n\n\n\n\n\n\n\n\nfunc testAccEc2ClassicRegionProviderConfig() string {\n\treturn testAccRegionalProviderConfig(testAccGetEc2ClassicRegion())\n}\n\n\nfunc testAccGetEc2ClassicRegion() string {\n\tv := os.Getenv(Ec2ClassicRegionEnvVar)\n\n\tif v != \"\" {\n\t\treturn v\n\t}\n\n\tif testAccGetPartition() == endpoints.AwsPartitionID {\n\t\treturn endpoints.UsEast1RegionID\n\t}\n\n\treturn testAccGetRegion()\n}\n\n\nfunc testAccCheckResourceAttrRegionalARNEc2Classic(resourceName, attributeName, arnService, arnResource string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tattributeValue := arn.ARN{\n\t\t\tAccountID: testAccGetAccountID(),\n\t\t\tPartition: testAccGetPartition(),\n\t\t\tRegion: testAccGetEc2ClassicRegion(),\n\t\t\tResource: arnResource,\n\t\t\tService: arnService,\n\t\t}.String()\n\t\treturn resource.TestCheckResourceAttr(resourceName, attributeName, attributeValue)(s)\n\t}\n}\n\nfunc testAccEC2ClassicPreCheck(t *testing.T) ", "output": "{\n\ttestAccProviderEc2ClassicConfigure.Do(func() {\n\t\ttestAccProviderEc2Classic = Provider()\n\n\t\tconfig := map[string]interface{}{\n\t\t\t\"region\": testAccGetEc2ClassicRegion(),\n\t\t}\n\n\t\terr := testAccProviderEc2Classic.Configure(context.Background(), terraform.NewResourceConfigRaw(config))\n\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t})\n\n\tclient := testAccProviderEc2Classic.Meta().(*AWSClient)\n\tplatforms := client.supportedplatforms\n\tregion := client.region\n\tif !hasEc2Classic(platforms) {\n\t\tt.Skipf(\"this test can only run in EC2-Classic, platforms available in %s: %q\", region, platforms)\n\t}\n}"} {"input": "package badger\n\n\n\n\n\n\n\n\n\ntype ManagedDB struct {\n\t*DB\n}\n\n\n\n\n\n\n\n\n\n\nfunc (db *ManagedDB) NewTransaction(update bool) {\n\tpanic(\"Cannot use NewTransaction() for ManagedDB. Use NewTransactionAt() instead.\")\n}\n\n\n\n\n\n\nfunc (db *ManagedDB) NewTransactionAt(readTs uint64, update bool) *Txn {\n\ttxn := db.DB.NewTransaction(update)\n\ttxn.readTs = readTs\n\treturn txn\n}\n\n\n\n\n\n\nfunc (txn *Txn) CommitAt(commitTs uint64, callback func(error)) error {\n\tif !txn.db.opt.managedTxns {\n\t\treturn ErrManagedTxn\n\t}\n\ttxn.commitTs = commitTs\n\treturn txn.Commit(callback)\n}\n\n\nfunc (db *ManagedDB) PurgeVersionsBelow(key []byte, ts uint64) error {\n\ttxn := db.NewTransactionAt(ts, false)\n\tdefer txn.Discard()\n\treturn db.purgeVersionsBelow(txn, key, ts)\n}\n\n\n\nfunc (db *ManagedDB) GetSequence(_ []byte, _ uint64) (*Sequence, error) {\n\tpanic(\"Cannot use GetSequence for ManagedDB.\")\n}\n\nfunc OpenManaged(opts Options) (*ManagedDB, error) ", "output": "{\n\topts.managedTxns = true\n\tdb, err := Open(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ManagedDB{db}, nil\n}"} {"input": "package config\n\nimport \"testing\"\n\nconst (\n\ttestCollectionsJSON = `[{\"type\":\"array\", \"key\":\"key1\", \"prompt\":\"prompt\", \"properties\":[{\"key\":\"key\", \"type\":\"alnum\", \"min\":1, \"max\":22}]}]`\n\ttestCollectionJSON = `{\"type\":\"map\", \"key\":\"key1\", \"prompt\":\"prompt\",\"properties\":[{\"key\":\"key\", \"type\":\"alnum\", \"min\":1, \"max\":22}]}`\n)\n\nfunc TestCollections(t *testing.T) {\n\tt.Parallel()\n\tc, err := NewCollections([]byte(testCollectionsJSON))\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tif len(c) != 1 {\n\t\tt.Errorf(\"modules array should contains 1 element (and it have %d)\", len(c))\n\t\treturn\n\t}\n\tif c[0].Type != \"array\" {\n\t\tt.Errorf(\"wrong Type value (expected array and take %s)\", c[0].Type)\n\t\treturn\n\t}\n\tif len(c[0].Properties) != 1 {\n\t\tt.Errorf(\"properties array should contains 1 element (and it have %d)\", len(c[0].Properties))\n\t\treturn\n\t}\n}\n\n\n\nfunc TestCollection(t *testing.T) ", "output": "{\n\tt.Parallel()\n\tc, err := NewCollection([]byte(testCollectionJSON))\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tif c.Type != \"map\" {\n\t\tt.Errorf(\"incorrect Type value parsing (expected map and take %s)\", c.Type)\n\t\treturn\n\t}\n\tif len(c.Properties) != 1 {\n\t\tt.Errorf(\"properties array should contains 1 element (and it have %d)\", len(c.Properties))\n\t\treturn\n\t}\n}"} {"input": "package filters\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"k8s.io/kubernetes/pkg/auth/authorizer\"\n\t\"k8s.io/kubernetes/pkg/util/runtime\"\n)\n\n\n\n\n\nfunc forbidden(attributes authorizer.Attributes, w http.ResponseWriter, req *http.Request, reason string) {\n\tmsg := forbiddenMessage(attributes)\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.WriteHeader(http.StatusForbidden)\n\tfmt.Fprintf(w, \"%s: %q\", msg, reason)\n}\n\nfunc forbiddenMessage(attributes authorizer.Attributes) string {\n\tusername := \"\"\n\tif user := attributes.GetUser(); user != nil {\n\t\tusername = user.GetName()\n\t}\n\n\tresource := attributes.GetResource()\n\tif group := attributes.GetAPIGroup(); len(group) > 0 {\n\t\tresource = resource + \".\" + group\n\t}\n\n\tif ns := attributes.GetNamespace(); len(ns) > 0 {\n\t\treturn fmt.Sprintf(\"User %q cannot %s %s in the namespace %q.\", username, attributes.GetVerb(), resource, ns)\n\t}\n\n\treturn fmt.Sprintf(\"User %q cannot %s %s at the cluster scope.\", username, attributes.GetVerb(), resource)\n}\n\n\nfunc internalError(w http.ResponseWriter, req *http.Request, err error) {\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.WriteHeader(http.StatusInternalServerError)\n\tfmt.Fprintf(w, \"Internal Server Error: %#v: %v\", req.RequestURI, err)\n\truntime.HandleError(err)\n}\n\nfunc badGatewayError(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.WriteHeader(http.StatusBadGateway)\n\tfmt.Fprintf(w, \"Bad Gateway: %#v\", req.RequestURI)\n}"} {"input": "package testings\n\nimport (\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n)\n\n\n\nfunc AssertEqual(t *testing.T, want, got interface{}, message string, options ...cmp.Option) {\n\tt.Helper()\n\tif diff := cmp.Diff(want, got, options...); diff != \"\" {\n\t\tif message == \"\" {\n\t\t\tt.Errorf(\"AssertEqual failed (-want +got):\\n%s\", diff)\n\t\t} else {\n\t\t\tt.Errorf(\"AssertEqual failed: %q: (-want +got):\\n%s\", message, diff)\n\t\t}\n\t}\n}\n\n\n\n\n\nfunc RequireEqual(t *testing.T, want, got interface{}, message string, options ...cmp.Option) ", "output": "{\n\tt.Helper()\n\tif diff := cmp.Diff(want, got, options...); diff != \"\" {\n\t\tif message == \"\" {\n\t\t\tt.Fatalf(\"RequireEqual failed (-want +got):\\n%s\", diff)\n\t\t} else {\n\t\t\tt.Fatalf(\"RequireEqual failed: %q: (-want +got):\\n%s\", message, diff)\n\t\t}\n\t}\n}"} {"input": "package config\n\nimport (\n\tcb \"github.com/hyperledger/fabric/protos/common\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n\t\"github.com/hyperledger/fabric/protos/utils\"\n)\n\n\n\n\nfunc TemplateConsensusType(typeValue string) *cb.ConfigGroup {\n\treturn ordererConfigGroup(ConsensusTypeKey, utils.MarshalOrPanic(&ab.ConsensusType{Type: typeValue}))\n}\n\n\nfunc TemplateBatchSize(batchSize *ab.BatchSize) *cb.ConfigGroup {\n\treturn ordererConfigGroup(BatchSizeKey, utils.MarshalOrPanic(batchSize))\n}\n\n\nfunc TemplateBatchTimeout(batchTimeout string) *cb.ConfigGroup {\n\treturn ordererConfigGroup(BatchTimeoutKey, utils.MarshalOrPanic(&ab.BatchTimeout{Timeout: batchTimeout}))\n}\n\n\nfunc TemplateChannelRestrictions(maxChannels uint64) *cb.ConfigGroup {\n\treturn ordererConfigGroup(ChannelRestrictionsKey, utils.MarshalOrPanic(&ab.ChannelRestrictions{MaxCount: maxChannels}))\n}\n\n\nfunc TemplateKafkaBrokers(brokers []string) *cb.ConfigGroup {\n\treturn ordererConfigGroup(KafkaBrokersKey, utils.MarshalOrPanic(&ab.KafkaBrokers{Brokers: brokers}))\n}\n\nfunc ordererConfigGroup(key string, value []byte) *cb.ConfigGroup ", "output": "{\n\tresult := cb.NewConfigGroup()\n\tresult.Groups[OrdererGroupKey] = cb.NewConfigGroup()\n\tresult.Groups[OrdererGroupKey].Values[key] = &cb.ConfigValue{\n\t\tValue: value,\n\t}\n\treturn result\n}"} {"input": "package task\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"os/exec\"\n)\n\n\n\n\n\nfunc Exec(w WorkerLog, wd string, cmd string, args ...string) error {\n\te := exec.Command(cmd, args...)\n\tif len(wd) != 0 {\n\t\te.Dir = wd + \"/\"\n\t}\n\n\tif stdout, err := e.StdoutPipe(); err != nil {\n\t\tw.AddError(err)\n\t\treturn err\n\t} else {\n\t\tgo scanPipe(stdout, w)\n\t}\n\n\tif stderr, err := e.StderrPipe(); err != nil {\n\t\tw.AddError(err)\n\t\treturn err\n\t} else {\n\t\tgo scanPipe(stderr, w)\n\t}\n\n\tif err := e.Run(); err != nil {\n\t\tw.AddError(err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc scanPipe(p io.ReadCloser, w WorkerLog) ", "output": "{\n\ts := bufio.NewScanner(p)\n\tfor s.Scan() {\n\t\tw.Add(s.Text())\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"net/http\"\n)\n\nfunc PingHandler(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"PONG!\"})\n}\n\n\n\nfunc GetAllImages(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"all images go here\"})\n}\n\nfunc GetImage(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"one image goes here\"})\n}\n\nfunc CreateImage(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"ID of the image we created goes here\"})\n}\n\nfunc UpdateImage(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"ID of the image we updated goes here\"})\n}\n\nfunc GetAllStats(c *gin.Context) ", "output": "{\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"statistics go here\"})\n}"} {"input": "package util_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/bmanth60/go-saml/util\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestIDGenerated(t *testing.T) ", "output": "{\n\tvar uuid interface{}\n\tassert.NotPanics(t, func() { util.ID() }, \"ID creation should not panic\")\n\n\tuuid = util.ID()\n\t_, ok := uuid.(string)\n\tassert.True(t, ok)\n}"} {"input": "package instana\n\nimport (\n\t\"time\"\n)\n\n\ntype EventData struct {\n\tTitle string `json:\"title\"`\n\tText string `json:\"text\"`\n\tDuration int `json:\"duration\"`\n\tSeverity int `json:\"severity\"`\n\tPlugin string `json:\"plugin,omitempty\"`\n\tID string `json:\"id,omitempty\"`\n\tHost string `json:\"host\"`\n}\n\ntype severity int\n\n\nconst (\n\tSeverityChange severity = -1\n\tSeverityWarning severity = 5\n\tSeverityCritical severity = 10\n)\n\n\nconst (\n\tServicePlugin = \"com.instana.forge.connection.http.logical.LogicalWebApp\"\n\tServiceHost = \"\"\n)\n\n\nfunc SendDefaultServiceEvent(title string, text string, sev severity, duration time.Duration) {\n\tif sensor == nil {\n\t\tSendServiceEvent(\"\", title, text, sev, duration)\n\t} else {\n\t\tSendServiceEvent(sensor.serviceName, title, text, sev, duration)\n\t}\n}\n\n\n\n\n\nfunc SendHostEvent(title string, text string, sev severity, duration time.Duration) {\n\tsendEvent(&EventData{\n\t\tTitle: title,\n\t\tText: text,\n\t\tDuration: int(duration / time.Millisecond),\n\t\tSeverity: int(sev),\n\t})\n}\n\nfunc sendEvent(event *EventData) {\n\tif sensor == nil {\n\t\tInitSensor(&Options{})\n\t}\n\tgo sensor.agent.request(sensor.agent.makeURL(agentEventURL), \"POST\", event)\n}\n\nfunc SendServiceEvent(service string, title string, text string, sev severity, duration time.Duration) ", "output": "{\n\tsendEvent(&EventData{\n\t\tTitle: title,\n\t\tText: text,\n\t\tSeverity: int(sev),\n\t\tPlugin: ServicePlugin,\n\t\tID: service,\n\t\tHost: ServiceHost,\n\t\tDuration: int(duration / time.Millisecond),\n\t})\n}"} {"input": "package gomock\n\nimport \"sync\"\n\n\n\ntype TestReporter interface {\n\tErrorf(format string, args ...interface{})\n\tFatalf(format string, args ...interface{})\n}\n\n\n\n\ntype Controller struct {\n\tmu sync.Mutex\n\tt TestReporter\n\texpectedCalls callSet\n}\n\nfunc NewController(t TestReporter) *Controller {\n\treturn &Controller{\n\t\tt: t,\n\t\texpectedCalls: make(callSet),\n\t}\n}\n\nfunc (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call {\n\tmargs := make([]Matcher, len(args))\n\tfor i, arg := range args {\n\t\tif m, ok := arg.(Matcher); ok {\n\t\t\tmargs[i] = m\n\t\t} else {\n\t\t\tmargs[i] = Eq(arg)\n\t\t}\n\t}\n\n\tctrl.mu.Lock()\n\tdefer ctrl.mu.Unlock()\n\n\tcall := &Call{t: ctrl.t, receiver: receiver, method: method, args: margs, minCalls: 1, maxCalls: 1}\n\n\tctrl.expectedCalls.Add(call)\n\treturn call\n}\n\n\n\nfunc (ctrl *Controller) Finish() {\n\tctrl.mu.Lock()\n\tdefer ctrl.mu.Unlock()\n\n\tif err := recover(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tfailures := false\n\tfor _, methodMap := range ctrl.expectedCalls {\n\t\tfor _, calls := range methodMap {\n\t\t\tfor _, call := range calls {\n\t\t\t\tif !call.satisfied() {\n\t\t\t\t\tctrl.t.Errorf(\"missing call(s) to %v\", call)\n\t\t\t\t\tfailures = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif failures {\n\t\tctrl.t.Fatalf(\"aborting test due to missing call(s)\")\n\t}\n}\n\nfunc (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{} ", "output": "{\n\tctrl.mu.Lock()\n\tdefer ctrl.mu.Unlock()\n\n\texpected := ctrl.expectedCalls.FindMatch(receiver, method, args)\n\tif expected == nil {\n\t\tctrl.t.Fatalf(\"no matching expected call: %T.%v(%v)\", receiver, method, args)\n\t}\n\n\tpreReqCalls := expected.dropPrereqs()\n\tfor _, preReqCall := range preReqCalls {\n\t\tctrl.expectedCalls.Remove(preReqCall)\n\t}\n\n\trets, action := expected.call(args)\n\tif expected.exhausted() {\n\t\tctrl.expectedCalls.Remove(expected)\n\t}\n\n\tctrl.mu.Unlock()\n\tdefer ctrl.mu.Lock()\n\tif action != nil {\n\t\taction()\n\t}\n\n\treturn rets\n}"} {"input": "package aws\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/mitchellh/goamz/aws\"\n)\n\ntype Config struct {\n\tAccessKey string `mapstructure:\"access_key\"`\n\tSecretKey string `mapstructure:\"secret_key\"`\n\tRegion string `mapstructure:\"region\"`\n}\n\n\n\n\n\nfunc (c *Config) AWSAuth() (aws.Auth, error) {\n\tauth, err := aws.GetAuth(c.AccessKey, c.SecretKey)\n\tif err == nil {\n\t\tc.AccessKey = auth.AccessKey\n\t\tc.SecretKey = auth.SecretKey\n\t}\n\n\treturn auth, err\n}\n\n\n\n\n\n\n\n\nfunc (c *Config) AWSRegion() (aws.Region, error) {\n\tif c.Region != \"\" {\n\t\tif c.IsValidRegion() {\n\t\t\treturn aws.Regions[c.Region], nil\n\t\t} else {\n\t\t\treturn aws.Region{}, fmt.Errorf(\"Not a valid region: %s\", c.Region)\n\t\t}\n\t}\n\n\tif v := os.Getenv(\"AWS_REGION\"); v != \"\" {\n\t\treturn aws.Regions[v], nil\n\t}\n\n\tmd, err := aws.GetMetaData(\"placement/availability-zone\")\n\tif err != nil {\n\t\treturn aws.Region{}, err\n\t}\n\n\tregion := strings.TrimRightFunc(string(md), unicode.IsLetter)\n\treturn aws.Regions[region], nil\n}\n\nfunc (c *Config) IsValidRegion() bool ", "output": "{\n\tvar regions = [8]string{\"us-east-1\", \"us-west-2\", \"us-west-1\", \"eu-west-1\",\n\t\t\"ap-southeast-1\", \"ap-southeast-2\", \"ap-northeast-1\", \"sa-east-1\"}\n\n\tfor _, valid := range regions {\n\t\tif c.Region == valid {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package generator\n\nimport (\n\t\"go/ast\"\n\t\"go/token\"\n)\n\n\n\nfunc makeVector(typ ast.Expr, elements []ast.Expr) *ast.CompositeLit {\n\treturn makeCompositeLit(&ast.ArrayType{Elt: typ}, elements)\n}\n\nfunc makeCompositeLit(typ ast.Expr, elements []ast.Expr) *ast.CompositeLit {\n\treturn &ast.CompositeLit{\n\t\tType: typ,\n\t\tElts: elements,\n\t}\n}\n\nfunc makeBasicLit(kind token.Token, value string) *ast.BasicLit ", "output": "{\n\treturn &ast.BasicLit{Kind: kind, Value: value}\n}"} {"input": "package cf\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\nconst (\n\tVersion = \"6.0.0-SHA\"\n\tUsage = \"A command line tool to interact with Cloud Foundry\"\n)\n\n\n\nfunc Name() string ", "output": "{\n\treturn filepath.Base(os.Args[0])\n}"} {"input": "package types\n\nimport \"time\"\n\ntype Comments struct {\n\tTotalCount int `json:\"total_count\"`\n\tPagination Pagination `json:\"pagination\"`\n\tList []Comment `json:\"list\"`\n}\n\ntype Comment struct {\n\tID string `json:\"id\"`\n\tTimeUnix int64 `json:\"time\"`\n\tAuthor Author `json:\"author\"`\n\tText string `json:\"text\"`\n\tLinkURL string `json:\"link_href\"`\n\tRating Rating `json:\"rating\"`\n\tVotes Votes `json:\"votes\"`\n\tEdits Edits `json:\"edits\"`\n}\n\nfunc (c *Comment) GetTime() time.Time {\n\treturn time.Unix(c.TimeUnix, 0)\n}\n\ntype Author struct {\n\tID string `json:\"id\"`\n\tName string `json:\"name\"`\n}\n\ntype Rating struct {\n\tVideo int `json:\"video\"`\n\tAudio int `json:\"audio\"`\n}\n\ntype Votes struct {\n\tPositive int `json:\"positive\"`\n\tNegative int `json:\"negative\"`\n}\n\ntype Edits struct {\n\tCount int `json:\"count\"`\n\tLastUnix int64 `json:\"last\"`\n}\n\n\n\nfunc (edits *Edits) GetLastEditTime() time.Time ", "output": "{\n\treturn time.Unix(edits.LastUnix, 0)\n}"} {"input": "package testhelpers\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\n\n\n\nfunc MustNewRequest(method, urlStr string, body io.Reader) *http.Request {\n\trequest, err := http.NewRequest(method, urlStr, body)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to create HTTP %s Request for '%s': %s\", method, urlStr, err))\n\t}\n\treturn request\n}\n\n\nfunc MustParseURL(rawURL string) *url.URL {\n\tu, err := url.Parse(rawURL)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to parse URL '%s': %s\", rawURL, err))\n\t}\n\treturn u\n}\n\nfunc Intp(i int) *int ", "output": "{\n\treturn &i\n}"} {"input": "package framework\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"k8s.io/kubernetes/pkg/kubelet/remote\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\nvar (\n\tuuidLock sync.Mutex\n\n\tlastUUID uuid.UUID\n)\n\n\nfunc LoadCRIClient() (*InternalAPIClient, error) {\n\trService, err := remote.NewRemoteRuntimeService(TestContext.RuntimeServiceAddr, TestContext.RuntimeServiceTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tiService, err := remote.NewRemoteImageService(TestContext.ImageServiceAddr, TestContext.ImageServiceTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &InternalAPIClient{\n\t\tCRIRuntimeClient: rService,\n\t\tCRIImageClient: iService,\n\t}, nil\n}\n\nfunc nowStamp() string {\n\treturn time.Now().Format(time.StampMilli)\n}\n\nfunc log(level string, format string, args ...interface{}) {\n\tfmt.Fprintf(GinkgoWriter, nowStamp()+\": \"+level+\": \"+format+\"\\n\", args...)\n}\n\n\nfunc Logf(format string, args ...interface{}) {\n\tlog(\"INFO\", format, args...)\n}\n\n\n\n\n\nfunc ExpectNoError(err error, explain ...interface{}) {\n\tif err != nil {\n\t\tLogf(\"Unexpected error occurred: %v\", err)\n\t}\n\tExpectWithOffset(1, err).NotTo(HaveOccurred(), explain...)\n}\n\n\nfunc NewUUID() string {\n\tuuidLock.Lock()\n\tdefer uuidLock.Unlock()\n\tresult := uuid.NewUUID()\n\tfor uuid.Equal(lastUUID, result) == true {\n\t\tresult = uuid.NewUUID()\n\t}\n\tlastUUID = result\n\treturn result.String()\n}\n\nfunc Failf(format string, args ...interface{}) ", "output": "{\n\tmsg := fmt.Sprintf(format, args...)\n\tlog(\"INFO\", msg)\n\tFail(nowStamp()+\": \"+msg, 1)\n}"} {"input": "package logwise\n\nimport (\n \"fmt\"\n \"os\"\n)\n\ntype Writer interface {\n Write(lines []string)\n}\n\ntype FileWriter struct {\n FilePath string\n Append bool\n Prefix string\n Postfix string\n}\n\nfunc NewFileWriter(filePath string, append bool, prefix,sufix string) Writer {\n return &FileWriter{filePath, append, prefix, sufix}\n}\n\nfunc (w *FileWriter) AddPrefix(prefix string) *FileWriter {\n w.Prefix = prefix\n return w\n}\n\nfunc (w *FileWriter) AddPostfix(postfix string) *FileWriter {\n w.Postfix = postfix\n return w\n}\n\n\n\nfunc (w *FileWriter) Write(lines []string) ", "output": "{\n var flags int\n\n if w.Append {\n flags = os.O_WRONLY | os.O_APPEND\n } else {\n flags = os.O_CREATE | os.O_WRONLY | os.O_TRUNC\n }\n\n file,_ := os.OpenFile(w.FilePath, flags, 0666)\n defer file.Close()\n \n if w.Prefix != \"\" {\n file.WriteString(fmt.Sprintf(\"%v\\n\", w.Prefix))\n }\n\n for _,line := range lines {\n file.WriteString(fmt.Sprintf(\"%v\\n\", line))\n }\n\n if w.Postfix != \"\" {\n file.WriteString(fmt.Sprintf(\"%v\\n\", w.Postfix))\n }\n}"} {"input": "package google\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/acctest\"\n\t\"github.com/hashicorp/terraform/helper/resource\"\n)\n\nfunc TestAccComputeResourceUsageExportBucket(t *testing.T) {\n\torg := getTestOrgFromEnv(t)\n\tbillingId := getTestBillingAccountFromEnv(t)\n\n\tbaseProject := \"ub-\" + acctest.RandString(10)\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccResourceUsageExportBucket(baseProject, org, billingId),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tResourceName: \"google_project_usage_export_bucket.ueb\",\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\n\n\nfunc testAccResourceUsageExportBucket(baseProject, org, billingId string) string ", "output": "{\n\treturn fmt.Sprintf(`\nresource \"google_project\" \"base\" {\n\tproject_id = \"%s\"\n\tname = \"Export Bucket Base\"\n\torg_id = \"%s\"\n\tbilling_account = \"%s\"\n}\n\nresource \"google_project_service\" \"service\" {\n\tproject = \"${google_project.base.project_id}\"\n\tservice = \"compute.googleapis.com\"\n}\n\nresource \"google_storage_bucket\" \"bucket\" {\n name = \"b-${google_project.base.project_id}\"\n\tproject = \"${google_project_service.service.project}\"\n}\n\nresource \"google_project_usage_export_bucket\" \"ueb\" {\n project = \"${google_project.base.project_id}\"\n bucket_name = \"${google_storage_bucket.bucket.name}\"\n\tprefix = \"foobar\"\n}\n`, baseProject, org, billingId)\n}"} {"input": "package victor\n\nimport (\n\t\"github.com/FogCreek/victor/pkg/chat\"\n)\n\n\ntype Handler interface {\n\tHandle(State)\n}\n\n\ntype HandlerFunc func(State)\n\n\n\nfunc (f HandlerFunc) Handle(s State) {\n\tf(s)\n}\n\n\n\ntype State interface {\n\tRobot() Robot\n\tChat() chat.Adapter\n\tMessage() chat.Message\n\tFields() []string\n\tReply(string)\n}\n\ntype state struct {\n\trobot Robot\n\tmessage chat.Message\n\tfields []string\n}\n\n\n\n\n\n\n\n\nfunc (s *state) Robot() Robot {\n\treturn s.robot\n}\n\n\nfunc (s *state) Chat() chat.Adapter {\n\treturn s.robot.Chat()\n}\n\n\nfunc (s *state) Message() chat.Message {\n\treturn s.message\n}\n\nfunc (s *state) Fields() []string {\n\treturn s.fields\n}\n\nfunc (s *state) Reply(msg string) ", "output": "{\n\ts.robot.Chat().Send(s.message.Channel().ID(), msg)\n}"} {"input": "package main\n\nimport (\n\t\"xoba/jira/tools\"\n\n\t\"github.com/xoba/goutil\"\n\t\"github.com/xoba/goutil/tool\"\n)\n\nfunc main() {\n\ttool.Run()\n}\n\n\n\nfunc init() ", "output": "{\n\tgoutil.PlatformInit()\n\tadd := func(name, desc string, f func([]string)) {\n\t\ttool.Register(tool.Named(name+\",\"+desc, tool.RunFunc(f)))\n\t}\n\tadd(\"comment\", \"comment on a jira issue\", tools.Comment)\n\tadd(\"create\", \"create a jira issue\", tools.CreateIssue)\n\tadd(\"delete\", \"delete a jira issue\", tools.DeleteIssue)\n\tadd(\"list\", \"list jira issues\", tools.ListIssues)\n\tadd(\"hook.install\", \"install git hooks\", tools.InstallGitHooks)\n\tadd(\"hook.commit-msg\", \"git commit hook\", tools.CommitHook)\n\tadd(\"hook.post-commit\", \"git postcommit hook\", tools.PostCommitHook)\n}"} {"input": "package network\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/docker/docker/cli\"\n\t\"github.com/docker/docker/cli/command\"\n\t\"github.com/docker/docker/cli/command/inspect\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype inspectOptions struct {\n\tformat string\n\tnames []string\n}\n\nfunc newInspectCommand(dockerCli *command.DockerCli) *cobra.Command {\n\tvar opts inspectOptions\n\n\tcmd := &cobra.Command{\n\t\tUse: \"inspect [OPTIONS] NETWORK [NETWORK...]\",\n\t\tShort: \"Display detailed information on one or more networks\",\n\t\tArgs: cli.RequiresMinArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\topts.names = args\n\t\t\treturn runInspect(dockerCli, opts)\n\t\t},\n\t}\n\n\tcmd.Flags().StringVarP(&opts.format, \"format\", \"f\", \"\", \"Format the output using the given Go template\")\n\n\treturn cmd\n}\n\n\n\nfunc runInspect(dockerCli *command.DockerCli, opts inspectOptions) error ", "output": "{\n\tclient := dockerCli.Client()\n\n\tctx := context.Background()\n\n\tgetNetFunc := func(name string) (interface{}, []byte, error) {\n\t\treturn client.NetworkInspectWithRaw(ctx, name)\n\t}\n\n\treturn inspect.Inspect(dockerCli.Out(), opts.names, opts.format, getNetFunc)\n}"} {"input": "package caaa\n\nimport (\n\t\"encoding/xml\"\n\n\t\"github.com/fgrid/iso20022\"\n)\n\ntype Document00300102 struct {\n\tXMLName xml.Name `xml:\"urn:iso:std:iso:20022:tech:xsd:caaa.003.001.02 Document\"`\n\tMessage *AcceptorCompletionAdviceV02 `xml:\"AccptrCmpltnAdvc\"`\n}\n\nfunc (d *Document00300102) AddMessage() *AcceptorCompletionAdviceV02 {\n\td.Message = new(AcceptorCompletionAdviceV02)\n\treturn d.Message\n}\n\n\n\ntype AcceptorCompletionAdviceV02 struct {\n\n\tHeader *iso20022.Header2 `xml:\"Hdr\"`\n\n\tCompletionAdvice *iso20022.AcceptorCompletionAdvice2 `xml:\"CmpltnAdvc\"`\n\n\tSecurityTrailer *iso20022.ContentInformationType6 `xml:\"SctyTrlr\"`\n}\n\n\n\nfunc (a *AcceptorCompletionAdviceV02) AddCompletionAdvice() *iso20022.AcceptorCompletionAdvice2 {\n\ta.CompletionAdvice = new(iso20022.AcceptorCompletionAdvice2)\n\treturn a.CompletionAdvice\n}\n\nfunc (a *AcceptorCompletionAdviceV02) AddSecurityTrailer() *iso20022.ContentInformationType6 {\n\ta.SecurityTrailer = new(iso20022.ContentInformationType6)\n\treturn a.SecurityTrailer\n}\n\nfunc (a *AcceptorCompletionAdviceV02) AddHeader() *iso20022.Header2 ", "output": "{\n\ta.Header = new(iso20022.Header2)\n\treturn a.Header\n}"} {"input": "package master\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\n\tauth \"github.com/abbot/go-http-auth\"\n\t\"github.com/h2oai/steam/master/az\"\n)\n\ntype DefaultAz struct {\n\tdirectory az.Directory\n}\n\n\n\nfunc (a *DefaultAz) Authenticate(username string) string {\n\tpz, err := a.directory.Lookup(username)\n\tif err != nil {\n\t\tlog.Printf(\"User %s read failed: %s\\n\", username, err)\n\t\treturn \"\"\n\t}\n\n\tif pz == nil {\n\t\tlog.Printf(\"User %s does not exist\\n\", username)\n\t\treturn \"\"\n\t}\n\treturn pz.Password()\n}\n\nfunc (a *DefaultAz) Identify(r *http.Request) (az.Principal, error) {\n\tusername := r.Header.Get(auth.AuthUsernameHeader)\n\tpz, err := a.directory.Lookup(username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif pz == nil {\n\t\treturn nil, fmt.Errorf(\"User %s does not exist\\n\", username)\n\t}\n\n\treturn pz, nil\n}\n\nfunc serveNoop(w http.ResponseWriter, r *http.Request) {}\nfunc authNoop(user, realm string) string { return \"\" }\n\nfunc NewDefaultAz(directory az.Directory) *DefaultAz ", "output": "{\n\treturn &DefaultAz{directory}\n}"} {"input": "package unibyte\n\nimport \"unicode\"\n\n\nfunc IsLower(b byte) bool {\n\treturn b >= 'a' && b <= 'z'\n}\n\n\nfunc IsUpper(b byte) bool {\n\treturn b >= 'A' && b <= 'Z'\n}\n\n\nfunc IsLetter(b byte) bool {\n\treturn IsLower(b) || IsUpper(b)\n}\n\n\n\n\n\nfunc IsSpace(b byte) bool {\n\treturn unicode.IsSpace(rune(b))\n}\n\n\nfunc ToLower(b byte) byte {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn b\n}\n\n\nfunc ToUpper(b byte) byte {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn b\n}\n\n\nfunc ToLowerString(b byte) string {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn string(b)\n}\n\n\nfunc ToUpperString(b byte) string {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn string(b)\n}\n\nfunc IsSpaceQuote(b byte) bool ", "output": "{\n\treturn IsSpace(b) || b == '\"' || b == '\\''\n}"} {"input": "package backingstore\n\nimport (\n\t\"github.com/gostor/gotgt/pkg/api\"\n\t\"github.com/gostor/gotgt/pkg/scsi\"\n)\n\n\n\ntype NullBackingStore struct {\n\tscsi.BaseBackingStore\n}\n\nfunc newNull() (api.BackingStore, error) {\n\treturn &NullBackingStore{\n\t\tBaseBackingStore: scsi.BaseBackingStore{\n\t\t\tName: \"null\",\n\t\t\tDataSize: 0,\n\t\t\tOflagsSupported: 0,\n\t\t},\n\t}, nil\n}\n\nfunc (bs *NullBackingStore) Open(dev *api.SCSILu, path string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Close(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Init(dev *api.SCSILu, Opts string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Exit(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Size(dev *api.SCSILu) uint64 {\n\treturn 0\n}\n\nfunc (bs *NullBackingStore) Read(offset, tl int64) ([]byte, error) {\n\treturn nil, nil\n}\n\nfunc (bs *NullBackingStore) Write(wbuf []byte, offset int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataSync(offset, tl int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataAdvise(offset, length int64, advise uint32) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Unmap([]api.UnmapBlockDescriptor) error {\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tscsi.RegisterBackingStore(\"null\", newNull)\n}"} {"input": "package opentracing \n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/otel/bridge/opentracing/migration\"\n\t\"go.opentelemetry.io/otel/trace\"\n)\n\ntype WrapperTracerProvider struct {\n\twTracer *WrapperTracer\n}\n\nvar _ trace.TracerProvider = (*WrapperTracerProvider)(nil)\n\n\nfunc (p *WrapperTracerProvider) Tracer(_ string, _ ...trace.TracerOption) trace.Tracer {\n\treturn p.wTracer\n}\n\n\n\nfunc NewWrappedTracerProvider(bridge *BridgeTracer, tracer trace.Tracer) *WrapperTracerProvider {\n\treturn &WrapperTracerProvider{\n\t\twTracer: NewWrapperTracer(bridge, tracer),\n\t}\n}\n\n\n\n\n\n\n\n\n\ntype WrapperTracer struct {\n\tbridge *BridgeTracer\n\ttracer trace.Tracer\n}\n\nvar _ trace.Tracer = &WrapperTracer{}\nvar _ migration.DeferredContextSetupTracerExtension = &WrapperTracer{}\n\n\n\n\nfunc NewWrapperTracer(bridge *BridgeTracer, tracer trace.Tracer) *WrapperTracer {\n\treturn &WrapperTracer{\n\t\tbridge: bridge,\n\t\ttracer: tracer,\n\t}\n}\n\nfunc (t *WrapperTracer) otelTracer() trace.Tracer {\n\treturn t.tracer\n}\n\n\n\n\n\n\n\n\n\n\nfunc (t *WrapperTracer) DeferredContextSetupHook(ctx context.Context, span trace.Span) context.Context {\n\tif tracerWithExtension, ok := t.otelTracer().(migration.DeferredContextSetupTracerExtension); ok {\n\t\tctx = tracerWithExtension.DeferredContextSetupHook(ctx, span)\n\t}\n\tctx = trace.ContextWithSpan(ctx, span)\n\treturn ctx\n}\n\nfunc (t *WrapperTracer) Start(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) ", "output": "{\n\tctx, span := t.otelTracer().Start(ctx, name, opts...)\n\tif spanWithExtension, ok := span.(migration.OverrideTracerSpanExtension); ok {\n\t\tspanWithExtension.OverrideTracer(t)\n\t}\n\tif !migration.SkipContextSetup(ctx) {\n\t\tctx = t.bridge.ContextWithBridgeSpan(ctx, span)\n\t}\n\treturn ctx, span\n}"} {"input": "package closure\n\nimport (\n\t\"fmt\"\n)\n\nfunc wrapper() func() int {\n\tx := 0\n\n\tincrement := func() int {\n\t\tx++ \n\t\treturn x\n\t}\n\treturn increment\n}\n\n\n\nfunc IncrementTest() {\n\tdefer bye() \n\tincrementer := wrapper()\n\tfmt.Println(incrementer())\n\tfmt.Println(incrementer())\n}\n\nfunc bye() ", "output": "{\n\tfmt.Println(\"good bye\")\n}"} {"input": "package prometheus_test\n\nimport (\n\t\"runtime\"\n\n\t\"github.com/coreos/etcd/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto\"\n\t\"github.com/coreos/etcd/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus\"\n\tdto \"github.com/coreos/etcd/Godeps/_workspace/src/github.com/prometheus/client_model/go\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\ntype CallbackMetric struct {\n\tprometheus.SelfCollector\n\n\tdesc *prometheus.Desc\n\tcallback func() float64\n}\n\nfunc (cm *CallbackMetric) Desc() *prometheus.Desc {\n\treturn cm.desc\n}\n\nfunc (cm *CallbackMetric) Write(m *dto.Metric) error {\n\tm.Untyped = &dto.Untyped{Value: proto.Float64(cm.callback())}\n\treturn nil\n}\n\nfunc ExampleSelfCollector() {\n\tm := NewCallbackMetric(\n\t\tprometheus.NewDesc(\n\t\t\t\"runtime_goroutines_count\",\n\t\t\t\"Total number of goroutines that currently exist.\",\n\t\t\tnil, nil, \n\t\t),\n\t\tfunc() float64 {\n\t\t\treturn float64(runtime.NumGoroutine())\n\t\t},\n\t)\n\tprometheus.MustRegister(m)\n}\n\nfunc NewCallbackMetric(desc *prometheus.Desc, callback func() float64) *CallbackMetric ", "output": "{\n\tresult := &CallbackMetric{desc: desc, callback: callback}\n\tresult.Init(result) \n\treturn result\n}"} {"input": "package schemaLibrary\n\nimport (\n\t\"encoding/xml\"\n\t\"log\"\n)\n\ntype SchemaLibrary struct {\n\tCT_SchemaLibrary\n}\n\nfunc NewSchemaLibrary() *SchemaLibrary {\n\tret := &SchemaLibrary{}\n\tret.CT_SchemaLibrary = *NewCT_SchemaLibrary()\n\treturn ret\n}\n\n\n\nfunc (m *SchemaLibrary) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tm.CT_SchemaLibrary = *NewCT_SchemaLibrary()\nlSchemaLibrary:\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch el := tok.(type) {\n\t\tcase xml.StartElement:\n\t\t\tswitch el.Name {\n\t\t\tcase xml.Name{Space: \"http:schemas.openxmlformats.org/schemaLibrary/2006/main\", Local: \"schema\"}:\n\t\t\t\ttmp := NewCT_Schema()\n\t\t\t\tif err := d.DecodeElement(tmp, &el); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tm.Schema = append(m.Schema, tmp)\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"skipping unsupported element on SchemaLibrary %v\", el.Name)\n\t\t\t\tif err := d.Skip(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\tcase xml.EndElement:\n\t\t\tbreak lSchemaLibrary\n\t\tcase xml.CharData:\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (m *SchemaLibrary) Validate() error {\n\treturn m.ValidateWithPath(\"SchemaLibrary\")\n}\n\n\nfunc (m *SchemaLibrary) ValidateWithPath(path string) error {\n\tif err := m.CT_SchemaLibrary.ValidateWithPath(path); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (m *SchemaLibrary) MarshalXML(e *xml.Encoder, start xml.StartElement) error ", "output": "{\n\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"xmlns\"}, Value: \"http:schemas.openxmlformats.org/schemaLibrary/2006/main\"})\n\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"xmlns:ma\"}, Value: \"http:schemas.openxmlformats.org/schemaLibrary/2006/main\"})\n\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"xmlns:xml\"}, Value: \"http:www.w3.org/XML/1998/namespace\"})\n\tstart.Name.Local = \"ma:schemaLibrary\"\n\treturn m.CT_SchemaLibrary.MarshalXML(e, start)\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"reflect\"\n\t\"time\"\n\n\t_ \"github.com/akutz/golf\"\n\n\t\"github.com/thecodeteam/rexray/libstorage/api/context\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/types\"\n)\n\n\n\nfunc GetTypePkgPathAndName(i interface{}) string {\n\tt := reflect.TypeOf(i)\n\tif t.Kind() == reflect.Ptr || t.Kind() == reflect.Interface {\n\t\tt = t.Elem()\n\t}\n\tpkgPath := t.PkgPath()\n\ttypeName := t.Name()\n\tif pkgPath == \"\" {\n\t\treturn typeName\n\t}\n\treturn fmt.Sprintf(\"%s.%s\", pkgPath, typeName)\n}\n\n\n\n\n\nfunc DeviceAttachTimeout(val string) time.Duration {\n\tdur, err := time.ParseDuration(val)\n\tif err != nil {\n\t\treturn time.Duration(30) * time.Second\n\t}\n\treturn dur\n}\n\nfunc GetTempSockFile(ctx types.Context) string ", "output": "{\n\n\tf, err := ioutil.TempFile(context.MustPathConfig(ctx).Run, \"\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tname := f.Name()\n\tos.RemoveAll(name)\n\treturn fmt.Sprintf(\"%s.sock\", name)\n}"} {"input": "package timeutil\n\nimport (\n\t\"time\"\n)\n\n\nfunc SetTimeout(t time.Duration, callback func()) {\n\tgo func() {\n\t\ttime.Sleep(t)\n\t\tcallback()\n\t}()\n}\n\n\n\nfunc SetInterval(t time.Duration, callback func() bool) {\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(t)\n\t\t\tif !callback() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\nfunc Nanosecond() int64 {\n\treturn time.Now().UnixNano()\n}\n\n\n\n\n\nfunc Millisecond() int64 {\n\treturn time.Now().UnixNano() / 1e6\n}\n\n\nfunc Second() int64 {\n\treturn time.Now().UnixNano() / 1e9\n}\n\n\nfunc Date() string {\n\treturn time.Now().Format(\"2006-01-02\")\n}\n\n\nfunc Datetime() string {\n\treturn time.Now().Format(\"2006-01-02 15:04:05\")\n}\n\n\n\nfunc Format(format string, timestamps ...int64) string {\n\ttimestamp := Second()\n\tif len(timestamps) > 0 {\n\t\ttimestamp = timestamps[0]\n\t}\n\treturn time.Unix(timestamp, 0).Format(format)\n}\n\n\nfunc StrToTime(format string, timestr string) (int64, error) {\n\tt, err := time.Parse(format, timestr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn t.Unix(), nil\n}\n\nfunc Microsecond() int64 ", "output": "{\n\treturn time.Now().UnixNano() / 1e3\n}"} {"input": "package claim\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\nfunc TestPermission_MatchVerb(t *testing.T) {\n\tp := Permission{Verb: []string{\"read\", \"update\", \"create\"}}\n\tassert.True(t, p.MatchVerb(\"read\"))\n\tassert.True(t, p.MatchVerb(\"update\"))\n\tassert.True(t, p.MatchVerb(\"create\"))\n\tassert.False(t, p.MatchVerb(\"invalid\"))\n\tassert.False(t, p.MatchVerb(\"delete\"))\n}\n\nfunc TestPermission_Match(t *testing.T) {\n\tp := Permission{ResourceURN: \"userapi:device:device_id\"}\n\tassert.True(t, p.Match(\"userapi:device:device_id\"))\n\tassert.False(t, p.Match(\"userapi:device:bla\"))\n\tassert.False(t, p.Match(\"userapi:home:bla\"))\n}\nfunc TestPermission_MatchWildcard(t *testing.T) {\n\tp := Permission{ResourceURN: \"userapi:device:*\"}\n\tassert.True(t, p.Match(\"userapi:device:device_id\"))\n\tassert.True(t, p.Match(\"userapi:device:bla\"))\n\tassert.False(t, p.Match(\"userapi:home:bla\"))\n}\n\n\n\nfunc TestPermissionSet_Match(t *testing.T) ", "output": "{\n\tp := PermissionSet{\n\t\tRules: []Permission{\n\t\t\t{ResourceURN: \"userapi:device:*\", Verb: []string{\"read\", \"update\", \"create\"}},\n\t\t\t{ResourceURN: \"userapi:device:\", Verb: []string{\"create\"}},\n\t\t},\n\t}\n\tassert.True(t, p.Match(\"read\", \"userapi:device:device_id\"))\n\tassert.False(t, p.Match(\"delete\", \"userapi:device:device_id\"))\n\tassert.True(t, p.Match(\"create\", \"userapi:device:\"))\n\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc max(x int, y int) int {\n\tif (x > y) {\n\t\treturn x\n\t} else {\n\t\treturn y\n\t}\n}\n\nfunc swap(x *int, y *int) {\n\tvar temp int\n\ttemp = *x;\n\t*x = *y\n\t*y = temp\n}\n\nfunc getSequence() func() int {\n\tvar i int = 0;\n\treturn func() int {\n\t\ti++;\n\t\treturn i\n\t}\n}\n\ntype Circle struct {\n\tx, y, radius float64\n}\n\n\n\nfunc main() {\n\tvar a, b int = 2, 3;\n\tfmt.Printf(\"max value is %d\\n\", max(a,b));\n\n\tfmt.Printf(\"a = %d, b = %d\\n\", a, b);\n\tswap(&a, &b);\n\tfmt.Printf(\"a = %d, b = %d\\n\", a, b);\n\n\txxx := swap\n\txxx(&a, &b)\n\tfmt.Printf(\"a = %d, b = %d\\n\", a, b);\n\n\tnumber := getSequence()\n\tfmt.Printf(\"number is %d\\n\", number())\n\tfmt.Printf(\"number is %d\\n\", number())\n\tfmt.Printf(\"number is %d\\n\", number())\n\tfmt.Printf(\"number is %d\\n\", number())\n\tnumber1 := getSequence()\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\n\tcircle := Circle{x:0, y:0, radius:5}\n\tfmt.Printf(\"Circle area: %f\\n\", circle.area())\n\n}\n\nfunc(circle Circle) area() float64 ", "output": "{\n\treturn math.Pi * circle.radius * circle.radius \n}"} {"input": "package log4me\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n)\n\ntype LoggerI struct {\n\tEnabled bool\n}\n\n\n\nfunc (l LoggerI) String() string {\n\tif l.Enabled {\n\t\treturn \"LoggerI: Enabled\"\n\t}\n\treturn \"LoggerI: Disabled\"\n}\n\ntype LoggerF struct {\n\tEnabled bool\n}\n\ntype F func()\n\nfunc (l LoggerF) Info(f F) {\n\tif l.Enabled {\n\t\tf()\n\t}\n}\n\nfunc (l LoggerF) String() string {\n\tif l.Enabled {\n\t\treturn \"LoggerF: Enabled\"\n\t}\n\treturn \"LoggerF: Disabled\"\n}\n\nfunc (l LoggerI) Info(v ...interface{}) ", "output": "{\n\tif !l.Enabled {\n\t\treturn\n\t}\n\n\tfmt.Fprintln(ioutil.Discard, v...)\n\n}"} {"input": "package yaml\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\n\n\n\nfunc ToYAML(rawObj interface{}) (*yaml.Node, error) {\n\tif rawObj == nil {\n\t\treturn &yaml.Node{Kind: yaml.ScalarNode, Value: \"null\", Tag: \"!!null\"}, nil\n\t}\n\n\trawJSON, err := json.Marshal(rawObj)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal object: %v\", err)\n\t}\n\n\tvar out yaml.Node\n\tif err := yaml.Unmarshal(rawJSON, &out); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to unmarshal marshalled object: %v\", err)\n\t}\n\treturn &out, nil\n}\n\n\n\nfunc changeAll(root *yaml.Node, cb func(*yaml.Node)) {\n\tcb(root)\n\tfor _, child := range root.Content {\n\t\tchangeAll(child, cb)\n\t}\n}\n\n\n\n\n\nfunc SetStyle(root *yaml.Node, style yaml.Style) ", "output": "{\n\tchangeAll(root, func(node *yaml.Node) {\n\t\tnode.Style = style\n\t})\n}"} {"input": "package duration_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\tduration \"github.com/channelmeter/iso8601duration\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestString(t *testing.T) {\n\tt.Parallel()\n\n\td := duration.Duration{}\n\tassert.Equal(t, d.String(), \"P\")\n\n\td = duration.Duration{Years: 1, Days: 2}\n\tassert.Equal(t, d.String(), \"P1Y2D\")\n\n\td = duration.Duration{Hours: 1, Minutes: 2, Seconds: 3}\n\tassert.Equal(t, d.String(), \"PT1H2M3S\")\n\n\td = duration.Duration{Years: 1, Days: 2, Hours: 3, Minutes: 4, Seconds: 5}\n\tassert.Equal(t, d.String(), \"P1Y2DT3H4M5S\")\n\n\td = duration.Duration{Weeks: 1}\n\tassert.Equal(t, d.String(), \"P1W\")\n}\n\nfunc TestToDuration(t *testing.T) {\n\tt.Parallel()\n\n\td := duration.Duration{Years: 1}\n\tassert.Equal(t, d.ToDuration(), time.Hour*24*365)\n\n\td = duration.Duration{Weeks: 1}\n\tassert.Equal(t, d.ToDuration(), time.Hour*24*7)\n\n\td = duration.Duration{Days: 1}\n\tassert.Equal(t, d.ToDuration(), time.Hour*24)\n\n\td = duration.Duration{Hours: 1}\n\tassert.Equal(t, d.ToDuration(), time.Hour)\n\n\td = duration.Duration{Minutes: 1}\n\tassert.Equal(t, d.ToDuration(), time.Minute)\n\n\td = duration.Duration{Seconds: 1}\n\tassert.Equal(t, d.ToDuration(), time.Second)\n}\n\nfunc TestFromString(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\t_, err := duration.FromString(\"asdf\")\n\tassert.Equal(t, err, duration.ErrBadFormat)\n\n\t_, err = duration.FromString(\"P1M\")\n\tassert.Equal(t, err, duration.ErrNoMonth)\n\n\tdur, err := duration.FromString(\"P1Y2DT3H4M5S\")\n\tassert.Nil(t, err)\n\tassert.Equal(t, 1, dur.Years)\n\tassert.Equal(t, 2, dur.Days)\n\tassert.Equal(t, 3, dur.Hours)\n\tassert.Equal(t, 4, dur.Minutes)\n\tassert.Equal(t, 5, dur.Seconds)\n\n\tdur, err = duration.FromString(\"P1W\")\n\tassert.Nil(t, err)\n\tassert.Equal(t, 1, dur.Weeks)\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\tf(\"direct\")\n\n\tgo f(\"goroutine\")\n\n\tgo func(msg string) {\n\t\tfmt.Println(msg)\t\n\t}(\"going\")\n\n\tvar input string\n\tfmt.Scanln(&input)\n\tfmt.Println(\"done\")\n}\n\nfunc f(from string) ", "output": "{\n\tfor i := 0; i < 3; i++ {\n\t\tfmt.Println(from, \":\", i)\n\t}\n}"} {"input": "package service\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"golang.org/x/sys/windows/svc\"\n\t\"golang.org/x/sys/windows/svc/debug\"\n\n\t\"github.com/elastic/beats/libbeat/logp\"\n)\n\ntype beatService struct{}\n\n\n\nfunc (m *beatService) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {\n\tconst cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown\n\tchanges <- svc.Status{State: svc.StartPending}\n\tchanges <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}\n\nloop:\n\tfor c := range r {\n\t\tswitch c.Cmd {\n\t\tcase svc.Interrogate:\n\t\t\tchanges <- c.CurrentStatus\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\tchanges <- c.CurrentStatus\n\t\tcase svc.Stop, svc.Shutdown:\n\t\t\tbreak loop\n\t\tdefault:\n\t\t\tlogp.Err(\"Unexpected control request: $%d. Ignored.\", c)\n\t\t}\n\t}\n\tchanges <- svc.Status{State: svc.StopPending}\n\treturn\n}\n\n\n\n\n\n\n\n\nfunc ProcessWindowsControlEvents(stopCallback func()) ", "output": "{\n\tisInteractive, err := svc.IsAnInteractiveSession()\n\tif err != nil {\n\t\tlogp.Err(\"IsAnInteractiveSession: %v\", err)\n\t\treturn\n\t}\n\tlogp.Debug(\"service\", \"Windows is interactive: %v\", isInteractive)\n\n\trun := svc.Run\n\tif isInteractive {\n\t\trun = debug.Run\n\t}\n\terr = run(os.Args[0], &beatService{})\n\tif err != nil {\n\t\tlogp.Err(\"Error: %v\", err)\n\t} else {\n\t\tstopCallback()\n\t}\n}"} {"input": "package stack\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/docker/docker/cli/command/bundlefile\"\n\t\"github.com/spf13/pflag\"\n)\n\n\n\nfunc addBundlefileFlag(opt *string, flags *pflag.FlagSet) {\n\tflags.StringVar(opt, \"bundle-file\", \"\", \"Path to a Distributed Application Bundle file\")\n\tflags.SetAnnotation(\"bundle-file\", \"experimental\", nil)\n}\n\nfunc addRegistryAuthFlag(opt *bool, flags *pflag.FlagSet) {\n\tflags.BoolVar(opt, \"with-registry-auth\", false, \"Send registry authentication details to Swarm agents\")\n}\n\nfunc loadBundlefile(stderr io.Writer, namespace string, path string) (*bundlefile.Bundlefile, error) {\n\tdefaultPath := fmt.Sprintf(\"%s.dab\", namespace)\n\n\tif path == \"\" {\n\t\tpath = defaultPath\n\t}\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"Bundle %s not found. Specify the path with --file\",\n\t\t\tpath)\n\t}\n\n\tfmt.Fprintf(stderr, \"Loading bundle from %s\\n\", path)\n\treader, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer reader.Close()\n\n\tbundle, err := bundlefile.LoadFile(reader)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error reading %s: %v\\n\", path, err)\n\t}\n\treturn bundle, err\n}\n\nfunc addComposefileFlag(opt *string, flags *pflag.FlagSet) ", "output": "{\n\tflags.StringVarP(opt, \"compose-file\", \"c\", \"\", \"Path to a Compose file\")\n}"} {"input": "package bitbucket\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/javiermanzano/goth\"\n)\n\n\ntype Session struct {\n\tAuthURL string\n\tAccessToken string\n\tRefreshToken string\n\tExpiresAt time.Time\n}\n\n\nfunc (s Session) GetAuthURL() (string, error) {\n\tif s.AuthURL == \"\" {\n\t\treturn \"\", errors.New(goth.NoAuthUrlErrorMessage)\n\t}\n\treturn s.AuthURL, nil\n}\n\n\nfunc (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {\n\tp := provider.(*Provider)\n\ttoken, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get(\"code\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !token.Valid() {\n\t\treturn \"\", errors.New(\"Invalid token received from provider\")\n\t}\n\n\ts.AccessToken = token.AccessToken\n\ts.RefreshToken = token.RefreshToken\n\ts.ExpiresAt = token.Expiry\n\treturn token.AccessToken, err\n}\n\n\nfunc (s Session) Marshal() string {\n\tb, _ := json.Marshal(s)\n\treturn string(b)\n}\n\n\nfunc (p *Provider) UnmarshalSession(data string) (goth.Session, error) {\n\tsess := &Session{}\n\terr := json.NewDecoder(strings.NewReader(data)).Decode(sess)\n\treturn sess, err\n}\n\n\n\nfunc (s Session) String() string ", "output": "{\n\treturn s.Marshal()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gogf/gf/v2/errors/gerror\"\n)\n\nfunc OpenFile() error {\n\treturn gerror.New(\"permission denied\")\n}\n\nfunc OpenConfig() error {\n\treturn gerror.Wrap(OpenFile(), \"configuration file opening failed\")\n}\n\n\n\nfunc main() {\n\tfmt.Println(gerror.Cause(ReadConfig()))\n}\n\nfunc ReadConfig() error ", "output": "{\n\treturn gerror.Wrap(OpenConfig(), \"reading configuration failed\")\n}"} {"input": "package statsd\n\nimport (\n\t\"github.com/golang/glog\"\n)\n\ntype dummyStatsdClientImpl struct {\n\tmessages []string\n}\n\n\n\nfunc (client *dummyStatsdClientImpl) close() error {\n\tglog.V(2).Infof(\"dummy statsd client close() called, doing nothing\")\n\treturn nil\n}\n\nfunc (client *dummyStatsdClientImpl) send(messages []string) error {\n\tclient.messages = messages\n\treturn nil\n}\n\nfunc (client *dummyStatsdClientImpl) open() error ", "output": "{\n\tglog.V(2).Infof(\"dummy statsd client open() called, doing nothing\")\n\treturn nil\n}"} {"input": "package chroot\n\nimport (\n\t\"log\"\n\n\t\"github.com/hashicorp/packer/packer\"\n\t\"github.com/mitchellh/multistep\"\n)\n\n\ntype StepChrootProvision struct {\n}\n\n\n\nfunc (s *StepChrootProvision) Cleanup(state multistep.StateBag) {}\n\nfunc (s *StepChrootProvision) Run(state multistep.StateBag) multistep.StepAction ", "output": "{\n\thook := state.Get(\"hook\").(packer.Hook)\n\tmountPath := state.Get(\"mount_path\").(string)\n\tui := state.Get(\"ui\").(packer.Ui)\n\twrappedCommand := state.Get(\"wrappedCommand\").(CommandWrapper)\n\n\tcomm := &Communicator{\n\t\tChroot: mountPath,\n\t\tCmdWrapper: wrappedCommand,\n\t}\n\n\tlog.Println(\"Running the provision hook\")\n\tif err := hook.Run(packer.HookProvision, ui, comm, nil); err != nil {\n\t\tstate.Put(\"error\", err)\n\t\treturn multistep.ActionHalt\n\t}\n\n\treturn multistep.ActionContinue\n}"} {"input": "package fmt\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc FormatBytes(n uint64) string ", "output": "{\n\tswitch {\n\tcase n < 1e3:\n\t\treturn fmt.Sprintf(\"%dB\", n)\n\tcase n < 1e6:\n\t\treturn fmt.Sprintf(\"%dKB\", n/1e3)\n\tcase n < 1e9:\n\t\treturn fmt.Sprintf(\"%dMB\", n/1e6)\n\tcase n < 1e12:\n\t\treturn fmt.Sprintf(\"%dGB\", n/1e9)\n\tcase n < 1e15:\n\t\treturn fmt.Sprintf(\"%dTB\", n/1e12)\n\tdefault:\n\t\treturn fmt.Sprintf(\"%dPB\", n/1e15)\n\t}\n}"} {"input": "package tool\n\nimport (\n\t\"log\"\n\t\"testing\"\n)\n\nfunc TestExistFile(t *testing.T) {\n\tlog.Println(ExistFile(\"config.go\"))\n\tlog.Println(ExistFile(\"config\"))\n}\n\n\n\nfunc TestConf(t *testing.T) ", "output": "{\n\tlog.Println(Conf(\"addr\"))\n\tlog.Println(Conf(\"hello\"))\n}"} {"input": "package quickbooks\n\nimport \"fmt\"\n\n\ntype ErrorObject struct {\n\tFault fault `json:\"Fault\"`\n\tTime string `json:\"time\"`\n}\n\ntype fault struct {\n\tError []faultError `json:\"Error\"`\n\tType string `json:\"type\"`\n}\n\ntype faultError struct {\n\tMessage string `json:\"Message\"`\n\tDetail string `json:\"Detail\"`\n\tCode string `json:\"code\"`\n\tElement string `json:\"element\"`\n}\n\n\n\n\n\ntype SDKError struct {\n\tType string\n\tCode string\n\tMessage string\n}\n\n\nfunc (e SDKError) Error() string {\n\terrStr := fmt.Sprintf(\"Type: %s Code: %s Message: %s\", e.Type, e.Code, e.Message)\n\treturn errStr\n}\n\n\nfunc (e SDKError) New(errorType string, errorCode string, errorMessage string) SDKError {\n\treturn SDKError{errorType, errorCode, errorMessage}\n}\n\nfunc (e ErrorObject) Error() string ", "output": "{\n\terrStr := fmt.Sprintf(\"Type: %s Code: %s Message: %s\", e.Fault.Type, e.Fault.Error[0].Code, e.Fault.Error[0].Message)\n\treturn errStr\n}"} {"input": "package dao\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"go-common/app/interface/main/web/conf\"\n\n\t\"gopkg.in/h2non/gock.v1\"\n)\n\nvar (\n\td *Dao\n)\n\nfunc TestMain(m *testing.M) {\n\tif os.Getenv(\"DEPLOY_ENV\") != \"local\" {\n\t\tflag.Set(\"app_id\", \"main.web-svr.web-interface\")\n\t\tflag.Set(\"conf_token\", \"bc99caee81f27661bd5ff50d1c0d58d6\")\n\t\tflag.Set(\"tree_id\", \"2685\")\n\t\tflag.Set(\"conf_version\", \"docker-1\")\n\t\tflag.Set(\"deploy_env\", \"uat\")\n\t\tflag.Set(\"conf_host\", \"config.bilibili.co\")\n\t\tflag.Set(\"conf_path\", \"/tmp\")\n\t\tflag.Set(\"region\", \"sh\")\n\t\tflag.Set(\"zone\", \"sh001\")\n\t} else {\n\t\tflag.Set(\"conf\", \"../cmd/web-interface-test.toml\")\n\t}\n\tflag.Parse()\n\tif err := conf.Init(); err != nil {\n\t\tpanic(err)\n\t}\n\td = New(conf.Conf)\n\td.httpR.SetTransport(gock.DefaultTransport)\n\td.httpBigData.SetTransport(gock.DefaultTransport)\n\td.httpHelp.SetTransport(gock.DefaultTransport)\n\tos.Exit(m.Run())\n}\n\n\n\nfunc httpMock(method, url string) *gock.Request ", "output": "{\n\tr := gock.New(url)\n\tr.Method = strings.ToUpper(method)\n\treturn r\n}"} {"input": "package main\n\nimport (\n\t\"sort\"\n)\n\n\ntype RankedCoordFinder struct {\n\tboard Board\n\tremaining []*Coord\n}\n\n\n\nfunc (f *RankedCoordFinder) RefreshCoordinates() {\n\tf.remaining = []*Coord{}\n\tfor x := 0; x < len(f.board); x++ {\n\t\tfor y := 0; y < len(f.board); y++ {\n\t\t\tif f.board[x][y] == 0 {\n\t\t\t\tf.remaining = append(f.remaining, &Coord{x, y})\n\t\t\t}\n\t\t}\n\t}\n\tsort.Sort(f)\n}\n\nfunc (f *RankedCoordFinder) Len() int {\n\treturn len(f.remaining)\n}\nfunc (f *RankedCoordFinder) Less(i, j int) bool {\n\treturn len(f.board.AvailableValuesAtCoordinate(f.remaining[i])) <\n\t\tlen(f.board.AvailableValuesAtCoordinate(f.remaining[j]))\n}\nfunc (f *RankedCoordFinder) Swap(i, j int) {\n\tf.remaining[i], f.remaining[j] = f.remaining[j], f.remaining[i]\n}\n\nfunc (f *RankedCoordFinder) NextOpenCoordinate(board Board, coord XY) (*Coord, bool) ", "output": "{\n\tf.board = board\n\tf.RefreshCoordinates()\n\n\tif len(f.remaining) == 0 {\n\t\treturn nil, false\n\t}\n\n\tc := f.remaining[0]\n\tf.remaining = f.remaining[0:]\n\n\treturn c, true\n}"} {"input": "package internal\n\nvar _ TerminateFile = &terminateFile{}\n\ntype terminateFile struct {\n\tname string\n\tpath string\n}\n\nfunc newTerminateFile(name string, path string) TerminateFile {\n\treturn &terminateFile{\n\t\tname: name,\n\t\tpath: path,\n\t}\n}\n\n\nfunc (t *terminateFile) Name() string {\n\treturn t.name\n}\n\n\n\n\nfunc (t *terminateFile) Path() string ", "output": "{\n\treturn t.path\n}"} {"input": "package main\n\nimport \"testing\"\n\n\n\nfunc TestReadConfig(t *testing.T) {\n\terr := readConfig(\"../../obs2vagrant.json.example\")\n\tif err != nil {\n\t\tt.Fatalf(\"It should be ok\")\n\t}\n\n\tif cfg.Address != \"127.0.0.1\" {\n\t\tt.Fatalf(\"Wrong address\")\n\t}\n\tif cfg.Port != 8080 {\n\t\tt.Fatalf(\"Wrong port\")\n\t}\n\tif len(cfg.Servers) != 2 {\n\t\tt.Fatalf(\"Wrong numbers of servers\")\n\t}\n\tif cfg.Servers[\"obs\"] != \"http://download.opensuse.org/repositories/\" {\n\t\tt.Fatalf(\"Wrong config for obs\")\n\t}\n\tif cfg.Servers[\"ibs\"] != \"http://download.suse.de/ibs/\" {\n\t\tt.Fatalf(\"Wrong config for ibs\")\n\t}\n}\n\nfunc TestFailReadConfig(t *testing.T) ", "output": "{\n\terr := readConfig(\"does-not-exist.json\")\n\tif err == nil ||\n\t\terr.Error() != \"open does-not-exist.json: no such file or directory\" {\n\n\t\tt.Fatalf(\"It should've failed because the file does not exist.\")\n\t}\n}"} {"input": "package hiveConfig\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"log\"\n)\n\n\ntype HiveConfig struct {\n\tServerURL string `json:\"server\"`\n\tTokensPath string `json:\"token_file_path\"`\n\tDeviceCodes string `json:\"device_codes_file_path\"`\n\tSecondsDelay int64 `json:\"delay\"`\n\tEndpoints map[string]Endpoints `json:\"endpoints\"`\n}\n\n\ntype Endpoints struct {\n\tURL string `json:\"url\"`\n\tDelay int `json:\"delay\"`\n}\n\n\ntype Authtokens struct {\n\tTokens []string `json:\"tokens\"`\n}\n\n\ntype SadirLogins struct {\n\tLogins []string `json:\"sadira_logins\"`\n}\n\n\n\n\n\nfunc GetLogins(loginsFile string) (logins SadirLogins, err error) {\n\tjsonDoc, err := ioutil.ReadFile(loginsFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not read config file: %s \", err)\n\t\treturn\n\t}\n\terr = json.Unmarshal(jsonDoc, &logins)\n\treturn\n}\n\nfunc GetConfigJSON(jsonFile string) (cfg HiveConfig, err error) ", "output": "{\n\tjsonDoc, err := ioutil.ReadFile(jsonFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not read config file: %s \", err)\n\t\treturn\n\t}\n\terr = json.Unmarshal(jsonDoc, &cfg)\n\treturn cfg, err\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", mainHandle)\n\tif err := http.ListenAndServe(\":8080\", nil); err != nil {\n\t\tlog.Fatal(\"Listen and serve:\", err)\n\t}\n}\n\n\ntype reply struct {\n\tLanguage string `json:\"language\"`\n\tOs string `json:\"software\"`\n\tIP string `json:\"ipaddress\"`\n}\n\n\nfunc mainHandle(w http.ResponseWriter, r *http.Request) {\n\theader := r.Header\n\th := fmt.Sprintf(\"%v\", header)\n\taddr := r.RemoteAddr\n\n\tos := parseOs(h)\n\tl := parseLang(h)\n\tip := parseIP(addr)\n\n\treply := reply{Language: l, Os: os, IP: ip}\n\n\tout, err := json.MarshalIndent(reply, \"\", \" \")\n\tif err != nil {\n\t\tfmt.Println(\"Cannot produce json\", err)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"%s\\n\", out)\n}\n\n\n\n\n\n\n\n\n\nfunc parseLang(h string) string {\n\ttag := strings.Index(h, \"Accept-Language:\")\n\tstart := strings.Index(h[tag:], \"[\")\n\tstart += tag + 1\n\n\tend := strings.Index(h[start:], \"]\")\n\tend += start\n\n\tl := h[start:end]\n\n\treturn strings.Split(l, \";\")[0]\n}\n\n\nfunc parseOs(h string) string {\n\ttag := strings.Index(h, \"User-Agent\")\n\tstart := strings.Index(h[tag:], \"(\")\n\tstart += tag + 1 \n\n\tend := strings.Index(h[start:], \")\")\n\tend += start\n\n\treturn h[start:end]\n}\n\nfunc parseIP(addr string) string ", "output": "{\n\tip := strings.Split(addr, \":\")[0]\n\treturn ip\n}"} {"input": "package ifacetest\n\nimport (\n\t\"github.com/snapcore/snapd/interfaces\"\n\t\"github.com/snapcore/snapd/snap\"\n)\n\n\ntype Specification struct {\n\tSnippets []string\n}\n\n\nfunc (spec *Specification) AddSnippet(snippet string) {\n\tspec.Snippets = append(spec.Snippets, snippet)\n}\n\n\n\n\nfunc (spec *Specification) AddConnectedPlug(iface interfaces.Interface, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error {\n\ttype definer interface {\n\t\tTestConnectedPlug(spec *Specification, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestConnectedPlug(spec, plug, slot)\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (spec *Specification) AddPermanentPlug(iface interfaces.Interface, plug *snap.PlugInfo) error {\n\ttype definer interface {\n\t\tTestPermanentPlug(spec *Specification, plug *snap.PlugInfo) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestPermanentPlug(spec, plug)\n\t}\n\treturn nil\n}\n\n\nfunc (spec *Specification) AddPermanentSlot(iface interfaces.Interface, slot *snap.SlotInfo) error {\n\ttype definer interface {\n\t\tTestPermanentSlot(spec *Specification, slot *snap.SlotInfo) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestPermanentSlot(spec, slot)\n\t}\n\treturn nil\n}\n\nfunc (spec *Specification) AddConnectedSlot(iface interfaces.Interface, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error ", "output": "{\n\ttype definer interface {\n\t\tTestConnectedSlot(spec *Specification, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestConnectedSlot(spec, plug, slot)\n\t}\n\treturn nil\n}"} {"input": "package externalversions\n\nimport (\n\t\"fmt\"\n\n\tv1 \"github.com/openshift/api/network/v1\"\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tcache \"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}\n\n\n\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {\n\tswitch resource {\n\tcase v1.SchemeGroupVersion.WithResource(\"clusternetworks\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Network().V1().ClusterNetworks().Informer()}, nil\n\tcase v1.SchemeGroupVersion.WithResource(\"egressnetworkpolicies\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Network().V1().EgressNetworkPolicies().Informer()}, nil\n\tcase v1.SchemeGroupVersion.WithResource(\"hostsubnets\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Network().V1().HostSubnets().Informer()}, nil\n\tcase v1.SchemeGroupVersion.WithResource(\"netnamespaces\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Network().V1().NetNamespaces().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}\n\nfunc (f *genericInformer) Lister() cache.GenericLister ", "output": "{\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}"} {"input": "package loggabletracer\n\nimport opentracing \"gx/ipfs/QmWLWmRVSiagqP15jczsGME1qpob6HDbtbHAY2he9W5iUo/opentracing-go\"\n\ntype accessorPropagator struct {\n\ttracer *LoggableTracer\n}\n\n\n\n\ntype DelegatingCarrier interface {\n\tSetState(traceID, spanID uint64, sampled bool)\n\tState() (traceID, spanID uint64, sampled bool)\n\tSetBaggageItem(key, value string)\n\tGetBaggage(func(key, value string))\n}\n\n\n\nfunc (p *accessorPropagator) Extract(\n\tcarrier interface{},\n) (opentracing.SpanContext, error) {\n\tdc, ok := carrier.(DelegatingCarrier)\n\tif !ok || dc == nil {\n\t\treturn nil, opentracing.ErrInvalidCarrier\n\t}\n\n\ttraceID, spanID, sampled := dc.State()\n\tsc := SpanContext{\n\t\tTraceID: traceID,\n\t\tSpanID: spanID,\n\t\tSampled: sampled,\n\t\tBaggage: nil,\n\t}\n\tdc.GetBaggage(func(k, v string) {\n\t\tif sc.Baggage == nil {\n\t\t\tsc.Baggage = map[string]string{}\n\t\t}\n\t\tsc.Baggage[k] = v\n\t})\n\n\treturn sc, nil\n}\n\nfunc (p *accessorPropagator) Inject(\n\tspanContext opentracing.SpanContext,\n\tcarrier interface{},\n) error ", "output": "{\n\tdc, ok := carrier.(DelegatingCarrier)\n\tif !ok || dc == nil {\n\t\treturn opentracing.ErrInvalidCarrier\n\t}\n\tsc, ok := spanContext.(SpanContext)\n\tif !ok {\n\t\treturn opentracing.ErrInvalidSpanContext\n\t}\n\tdc.SetState(sc.TraceID, sc.SpanID, sc.Sampled)\n\tfor k, v := range sc.Baggage {\n\t\tdc.SetBaggageItem(k, v)\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"syscall\"\n)\n\ntype SSHCommand struct{}\n\nfunc (c *SSHCommand) Execute(args []string) error {\n\tconfig, err := ReadConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpath, err := exec.LookPath(\"ssh\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\targs = append([]string{\"\", config.Hostname}, args...)\n\treturn syscall.Exec(path, args, os.Environ())\n}\n\n\n\nfunc init() ", "output": "{\n\tvar sshCommand SSHCommand\n\tcmd.AddCommand(\"ssh\", \"ssh shortcut\", \"run an ssh client connected to your vm\", &sshCommand)\n}"} {"input": "package slack\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net/url\"\n)\n\ntype emojiResponseFull struct {\n\tEmoji map[string]string `json:\"emoji\"`\n\tSlackResponse\n}\n\n\nfunc (api *Client) GetEmoji() (map[string]string, error) {\n\treturn api.GetEmojiContext(context.Background())\n}\n\n\n\n\nfunc (api *Client) GetEmojiContext(ctx context.Context) (map[string]string, error) ", "output": "{\n\tvalues := url.Values{\n\t\t\"token\": {api.token},\n\t}\n\tresponse := &emojiResponseFull{}\n\n\terr := postSlackMethod(ctx, api.httpclient, \"emoji.list\", values, response, api.debug)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !response.Ok {\n\t\treturn nil, errors.New(response.Error)\n\t}\n\treturn response.Emoji, nil\n}"} {"input": "package wxshield2\n\nimport (\n\t\"testing\"\n)\n\nfunc TestPacket_InsertEroteme(t *testing.T) {\n\tn := Packet{}\n\twant := `INSERT INTO test (timestamp, pressure, tempa, tempb, humidity, ptemp, htemp, battery, indx) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`\n\tif n.InsertEroteme(\"test\") != want {\n\t\tt.Errorf(\"Got %q not %q\", n.InsertEroteme(\"test\"), want)\n\t}\n}\n\nfunc TestPacket_InsertNamed(t *testing.T) {\n\tn := Packet{}\n\twant := `INSERT INTO test (timestamp, pressure, tempa, tempb, humidity, ptemp, htemp, battery, indx) VALUES (:timestamp, :pressure, :tempa, :tempb, :humidity, :ptemp, :htemp, :battery, :indx)`\n\tif n.InsertNamed(\"test\") != want {\n\t\tt.Errorf(\"Got %q not %q\", n.InsertNamed(\"test\"), want)\n\t}\n}\n\n\n\nfunc TestPacket_Jsonable(t *testing.T) ", "output": "{\n\tn := Packet{}\n\t*n.Jsonable().Battery = 1.0\n\tif n.Battery.Float64 != 1.0 {\n\t\tt.Errorf(\"Should be able to set values\")\n\t}\n}"} {"input": "package netutil\nimport (\n\t\"strings\"\n\t\"os\"\n\n\t\"net\"\n\t\"net/http\"\n\t\"io/ioutil\"\n\t. \"github.com/leanote/leanote/app/lea\"\n)\n\n\n\n\n\n\nfunc WriteUrl(url string, toPath string) (length int64, newFilename, path string, ok bool) {\n\tif url == \"\" {\n\t\treturn;\n\t}\n\tcontent, err := GetContent(url)\n\tif err != nil {\n\t\treturn;\n\t}\n\tlength = int64(len(content))\n\turl = trimQueryParams(url)\n\t_, ext := SplitFilename(url)\n\tif toPath == \"\" {\n\t\ttoPath = \"/tmp\"\n\t}\n\n\tnewFilename = NewGuid() + ext\n\tfullPath := toPath + \"/\" + newFilename\n\tfile, err := os.Create(fullPath)\n defer file.Close()\n if err != nil {\n \treturn\n\t}\n\tfile.Write(content)\n\tpath = fullPath\n\tok = true\n\treturn\n}\n\n\n\n\n\nfunc trimQueryParams(url string) string {\n\tpos := strings.Index(url, \"?\");\n\tif pos != -1 {\n\t\turl = Substr(url, 0, pos);\n\t}\n\tpos = strings.Index(url, \"#\");\n\tif pos != -1 {\n\t\turl = Substr(url, 0, pos);\n\t}\n\tpos = strings.Index(url, \"!\");\n\tif pos != -1 {\n\t\turl = Substr(url, 0, pos);\n\t}\n\treturn url;\n}\n\n\nfunc GetIpFromDomain(domain string) string {\n\tip, _ := net.LookupIP(domain)\n\tif ip != nil && len(ip) > 0 {\n\t\treturn ip[0].String()\n\t}\n\treturn \"\"\n}\n\nfunc GetContent(url string) (content []byte, err error) ", "output": "{\n\tvar resp *http.Response\n\tresp, err = http.Get(url)\n\tLog(err)\n\tif(resp != nil && resp.Body != nil) {\n\t\tdefer resp.Body.Close()\n\t} else {\n\t}\n if resp == nil || resp.Body == nil || err != nil || resp.StatusCode != http.StatusOK {\n\t\treturn\n }\n \n var buf []byte\n \tbuf, err = ioutil.ReadAll(resp.Body)\n \tif(err != nil) {\n \t\tLog(err)\n\t\treturn\n\t}\n \tcontent = buf;\n \terr = nil\n return\n}"} {"input": "package pathfs\n\nimport (\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/hanwen/go-fuse/fuse\"\n)\n\nfunc (fs *loopbackFileSystem) StatFs(name string) *fuse.StatfsOut {\n\ts := syscall.Statfs_t{}\n\terr := syscall.Statfs(fs.GetPath(name), &s)\n\tif err == nil {\n\t\treturn &fuse.StatfsOut{\n\t\t\tBlocks: s.Blocks,\n\t\t\tBfree: s.Bfree,\n\t\t\tBavail: s.Bavail,\n\t\t\tFiles: s.Files,\n\t\t\tFfree: s.Ffree,\n\t\t\tBsize: uint32(s.Iosize), \n\t\t\tFrsize: s.Bsize, \n\t\t}\n\t}\n\treturn nil\n}\n\nconst _UTIME_NOW = ((1 << 30) - 1)\nconst _UTIME_OMIT = ((1 << 30) - 2)\n\n\n\n\n\n\n\n\n\n\nfunc (fs *loopbackFileSystem) Utimens(path string, a *time.Time, m *time.Time, context *fuse.Context) fuse.Status {\n\ttv := make([]syscall.Timeval, 2)\n\tif a == nil {\n\t\ttv[0].Usec = _UTIME_OMIT\n\t} else {\n\t\ttv[0] = timeToTimeval(a)\n\t}\n\n\tif m == nil {\n\t\ttv[1].Usec = _UTIME_OMIT\n\t} else {\n\t\ttv[1] = timeToTimeval(m)\n\t}\n\n\terr := syscall.Utimes(fs.GetPath(path), tv)\n\treturn fuse.ToStatus(err)\n}\n\nfunc timeToTimeval(t *time.Time) syscall.Timeval ", "output": "{\n\tvar tv syscall.Timeval\n\ttv.Usec = int32(t.Nanosecond() / 1000)\n\ttv.Sec = t.Unix()\n\treturn tv\n}"} {"input": "package elastic\n\n\n\n\n\ntype GeoPolygonQuery struct {\n\tname string\n\tpoints []*GeoPoint\n\tqueryName string\n}\n\n\nfunc NewGeoPolygonQuery(name string) *GeoPolygonQuery {\n\treturn &GeoPolygonQuery{\n\t\tname: name,\n\t\tpoints: make([]*GeoPoint, 0),\n\t}\n}\n\n\n\n\n\nfunc (q *GeoPolygonQuery) AddGeoPoint(point *GeoPoint) *GeoPolygonQuery {\n\tq.points = append(q.points, point)\n\treturn q\n}\n\nfunc (q *GeoPolygonQuery) QueryName(queryName string) *GeoPolygonQuery {\n\tq.queryName = queryName\n\treturn q\n}\n\n\nfunc (q *GeoPolygonQuery) Source() (interface{}, error) {\n\tsource := make(map[string]interface{})\n\n\tparams := make(map[string]interface{})\n\tsource[\"geo_polygon\"] = params\n\n\tpolygon := make(map[string]interface{})\n\tparams[q.name] = polygon\n\n\tpoints := make([]interface{}, 0)\n\tfor _, point := range q.points {\n\t\tpoints = append(points, point.Source())\n\t}\n\tpolygon[\"points\"] = points\n\n\tif q.queryName != \"\" {\n\t\tparams[\"_name\"] = q.queryName\n\t}\n\n\treturn source, nil\n}\n\nfunc (q *GeoPolygonQuery) AddPoint(lat, lon float64) *GeoPolygonQuery ", "output": "{\n\tq.points = append(q.points, GeoPointFromLatLon(lat, lon))\n\treturn q\n}"} {"input": "package memory\n\nimport (\n\t\"github.com/golang/glog\"\n\n\t\"istio.io/istio/pilot/model\"\n)\n\nconst (\n\tBufferSize = 10\n)\n\n\ntype Handler func(model.Config, model.Event)\n\n\ntype Monitor interface {\n\tRun(<-chan struct{})\n\tAppendEventHandler(string, Handler)\n\tScheduleProcessEvent(ConfigEvent)\n}\n\n\ntype ConfigEvent struct {\n\tconfig model.Config\n\tevent model.Event\n}\n\ntype configstoreMonitor struct {\n\tstore model.ConfigStore\n\thandlers map[string][]Handler\n\teventCh chan ConfigEvent\n}\n\n\n\n\nfunc (m *configstoreMonitor) ScheduleProcessEvent(configEvent ConfigEvent) {\n\tm.eventCh <- configEvent\n}\n\nfunc (m *configstoreMonitor) Run(stop <-chan struct{}) {\n\tfor {\n\t\tselect {\n\t\tcase <-stop:\n\t\t\tif _, ok := <-m.eventCh; ok {\n\t\t\t\tclose(m.eventCh)\n\t\t\t}\n\t\t\treturn\n\t\tcase ce, ok := <-m.eventCh:\n\t\t\tif ok {\n\t\t\t\tm.processConfigEvent(ce)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *configstoreMonitor) processConfigEvent(ce ConfigEvent) {\n\tif _, exists := m.handlers[ce.config.Type]; !exists {\n\t\tglog.Warningf(\"Config Type %s does not exist in config store\", ce.config.Type)\n\t\treturn\n\t}\n\tm.applyHandlers(ce.config, ce.event)\n}\n\nfunc (m *configstoreMonitor) AppendEventHandler(typ string, h Handler) {\n\tm.handlers[typ] = append(m.handlers[typ], h)\n}\n\nfunc (m *configstoreMonitor) applyHandlers(config model.Config, e model.Event) {\n\tfor _, f := range m.handlers[config.Type] {\n\t\tf(config, e)\n\t}\n}\n\nfunc NewConfigStoreMonitor(store model.ConfigStore) Monitor ", "output": "{\n\thandlers := make(map[string][]Handler)\n\n\tfor _, typ := range store.ConfigDescriptor().Types() {\n\t\thandlers[typ] = make([]Handler, 0)\n\t}\n\n\treturn &configstoreMonitor{\n\t\tstore: store,\n\t\thandlers: handlers,\n\t\teventCh: make(chan ConfigEvent, BufferSize),\n\t}\n}"} {"input": "package gospec\n\nimport (\n\t\"fmt\"\n\tfilepath \"path\"\n\t\"runtime\"\n)\n\ntype Location struct {\n\tname string\n\tfile string\n\tline int\n}\n\nfunc currentLocation() *Location {\n\treturn newLocation(1)\n}\n\nfunc callerLocation() *Location {\n\treturn newLocation(2)\n}\n\nfunc newLocation(n int) *Location {\n\tif pc, _, _, ok := runtime.Caller(n + 1); ok {\n\t\treturn locationForPC(pc)\n\t}\n\treturn nil\n}\n\nfunc locationForPC(pc uintptr) *Location {\n\tpc = pcOfWhereCallWasMade(pc)\n\tf := runtime.FuncForPC(pc)\n\tname := f.Name()\n\tfile, line := f.FileLine(pc)\n\treturn &Location{name, file, line}\n}\n\n\n\n\n\n\n\n\n\n\nfunc (this *Location) Name() string { return this.name }\nfunc (this *Location) File() string { return this.file }\nfunc (this *Location) FileName() string { return filename(this.file) }\nfunc (this *Location) Line() int { return this.line }\n\nfunc filename(path string) string {\n\t_, file := filepath.Split(path)\n\treturn file\n}\n\nfunc (this *Location) equals(that *Location) bool {\n\treturn this.name == that.name &&\n\t\tthis.file == that.file &&\n\t\tthis.line == that.line\n}\n\nfunc (this *Location) String() string {\n\treturn fmt.Sprintf(\"%v:%v\", this.FileName(), this.Line())\n}\n\nfunc pcOfWhereCallWasMade(pcOfWhereCallReturnsTo uintptr) uintptr ", "output": "{\n\treturn pcOfWhereCallReturnsTo - 1\n}"} {"input": "package objvalmo \n\nimport (\n\t_ \"github.com/mattn/go-sqlite3\"\n)\n\n\nimport \"C\"\n\n\n\nfunc EnableSqliteLog() ", "output": "{\n\tC.goSqlite3EnableLog()\n}"} {"input": "package todoist\n\nimport \"fmt\"\n\ntype IntBool bool\n\nfunc (i IntBool) Bool() bool {\n\tif i {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\nfunc (i IntBool) MarshalJSON() ([]byte, error) {\n\tif i {\n\t\treturn []byte(\"1\"), nil\n\t} else {\n\t\treturn []byte(\"0\"), nil\n\t}\n}\n\n\n\ntype ColorStringer interface {\n\tString() string\n\tColorString() string\n}\n\ntype NoColorString struct {\n\ts string\n}\n\nfunc NewNoColorString(s string) NoColorString {\n\treturn NoColorString{s}\n}\n\nfunc (n NoColorString) String() string {\n\treturn n.s\n}\n\nfunc (n NoColorString) ColorString() string {\n\treturn n.s\n}\n\nfunc (i *IntBool) UnmarshalJSON(b []byte) (err error) ", "output": "{\n\tswitch string(b) {\n\tcase \"1\":\n\t\t*i = true\n\tcase \"0\":\n\t\t*i = false\n\tdefault:\n\t\treturn fmt.Errorf(\"Could not unmarshal into intbool: %s\", string(b))\n\t}\n\treturn nil\n}"} {"input": "package encoding\n\nimport \"gonum.org/v1/gonum/graph\"\n\n\ntype Builder interface {\n\tgraph.Graph\n\tgraph.Builder\n}\n\n\ntype MultiBuilder interface {\n\tgraph.Multigraph\n\tgraph.MultigraphBuilder\n}\n\n\n\ntype AttributeSetter interface {\n\tSetAttribute(Attribute) error\n}\n\n\n\ntype Attributer interface {\n\tAttributes() []Attribute\n}\n\n\ntype Attribute struct {\n\tKey, Value string\n}\n\n\ntype Attributes []Attribute\n\n\n\n\n\n\n\n\nfunc (a *Attributes) SetAttribute(attr Attribute) error {\n\tif attr.Key == \"\" {\n\t\treturn nil\n\t}\n\tfor i, v := range *a {\n\t\tif v.Key == attr.Key {\n\t\t\tif attr.Value == \"\" {\n\t\t\t\t(*a)[i] = (*a)[len(*a)-1]\n\t\t\t\t*a = (*a)[:len(*a)-1]\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t(*a)[i].Value = attr.Value\n\t\t\treturn nil\n\t\t}\n\t}\n\tif attr.Value != \"\" {\n\t\t*a = append(*a, attr)\n\t}\n\treturn nil\n}\n\nfunc (a *Attributes) Attributes() []Attribute ", "output": "{\n\treturn *a\n}"} {"input": "package rpc\n\nimport (\n\t\"context\"\n\t\"net\"\n\n\t\"github.com/ethereum/go-ethereum/log\"\n\t\"github.com/ethereum/go-ethereum/p2p/netutil\"\n)\n\n\n\n\n\n\n\n\n\n\nfunc DialIPC(ctx context.Context, endpoint string) (*Client, error) {\n\treturn newClient(ctx, func(ctx context.Context) (ServerCodec, error) {\n\t\tconn, err := newIPCConnection(ctx, endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn NewCodec(conn), err\n\t})\n}\n\nfunc (s *Server) ServeListener(l net.Listener) error ", "output": "{\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif netutil.IsTemporaryError(err) {\n\t\t\tlog.Warn(\"RPC accept error\", \"err\", err)\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Trace(\"Accepted RPC connection\", \"conn\", conn.RemoteAddr())\n\t\tgo s.ServeCodec(NewCodec(conn), 0)\n\t}\n}"} {"input": "package memory\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"github.com/google/trillian/monitoring\"\n\t\"github.com/google/trillian/storage\"\n)\n\n\n\ntype memProvider struct {\n\tmf monitoring.MetricFactory\n\tts *TreeStorage\n}\n\nfunc newMemoryStorageProvider(mf monitoring.MetricFactory) (storage.Provider, error) {\n\treturn &memProvider{\n\t\tmf: mf,\n\t\tts: NewTreeStorage(),\n\t}, nil\n}\n\nfunc (s *memProvider) LogStorage() storage.LogStorage {\n\treturn NewLogStorage(s.ts, s.mf)\n}\n\nfunc (s *memProvider) MapStorage() storage.MapStorage {\n\treturn nil\n}\n\nfunc (s *memProvider) AdminStorage() storage.AdminStorage {\n\treturn NewAdminStorage(s.ts)\n}\n\nfunc (s *memProvider) Close() error {\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tif err := storage.RegisterProvider(\"memory\", newMemoryStorageProvider); err != nil {\n\t\tglog.Fatalf(\"Failed to register storage provider memory: %v\", err)\n\t}\n}"} {"input": "package data\n\nimport (\n\t\"github.com/raincious/trap/trap/core/types\"\n)\n\ntype HelloConflict struct {\n\tBase\n\n\tConfilct types.IPAddresses\n}\n\nfunc (d *HelloConflict) Parse(msg [][]byte) *types.Throw {\n\tverifyErr := d.Verify(msg, 1)\n\n\tif verifyErr != nil {\n\t\treturn verifyErr\n\t}\n\n\tconnectedErr := d.Confilct.Unserialize(msg[0])\n\n\tif connectedErr != nil {\n\t\treturn connectedErr\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (d *HelloConflict) Build() ([][]byte, *types.Throw) ", "output": "{\n\tipByte, cIPErr := d.Confilct.Serialize()\n\n\tif cIPErr != nil {\n\t\treturn [][]byte{}, cIPErr\n\t}\n\n\treturn [][]byte{\n\t\tipByte,\n\t}, nil\n}"} {"input": "package system\n\nimport \"strings\"\n\n\n\n\n\n\ntype Args []string\n\n\n\n\n\n\n\nfunc (a Args) After() string {\n\treturn a.AfterN(0)\n}\n\n\n\nfunc (a Args) AfterN(n int) string {\n\tif n >= 0 && n < len(a) {\n\t\treturn strings.Join(a[n:], \" \")\n\t}\n\treturn \"\"\n}\n\nfunc (a Args) Get(n int) string ", "output": "{\n\tif n >= 0 && n < len(a) {\n\t\treturn a[n]\n\t}\n\treturn \"\"\n}"} {"input": "package leetcode\n\n\n\n\n\n\nfunc searchMatrix(matrix [][]int, target int) bool ", "output": "{\n\tm := len(matrix)\n\tif m == 0 {\n\t\treturn false\n\t}\n\n\tn := len(matrix[0])\n\tif n == 0 {\n\t\treturn false\n\t}\n\n\trow := -1\n\n\tfor i := 0; i < m; i++ {\n\t\tif target == matrix[i][n-1] {\n\t\t\treturn true\n\t\t}\n\t\tif target < matrix[i][n-1] {\n\t\t\trow = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif row == -1 {\n\t\treturn false\n\t}\n\n\tleft := 0\n\tright := n - 1\n\tfor left <= right {\n\t\tmid := (left + right) / 2\n\t\tif target == matrix[row][mid] {\n\t\t\treturn true\n\t\t} else if target > matrix[row][mid] {\n\t\t\tleft = mid + 1\n\t\t} else {\n\t\t\tright = mid - 1\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package gws\n\nimport (\n\t\"crypto/rand\"\n\t\"fmt\"\n\n\t\"github.com/graphql-go/graphql\"\n\t\"github.com/vaniila/hyper/cache\"\n\t\"github.com/vaniila/hyper/logger\"\n\t\"github.com/vaniila/hyper/message\"\n)\n\n\ntype Option func(*Options)\n\n\ntype Options struct {\n\n\tID string\n\n\tTopic []byte\n\n\tSchema graphql.Schema\n\n\tCache cache.Service\n\n\tMessage message.Service\n\n\tLogger logger.Service\n}\n\nfunc newID() string {\n\tb := new([16]byte)\n\trand.Read(b[:])\n\tb[8] = (b[8] | 0x40) & 0x7F\n\tb[6] = (b[6] & 0xF) | (4 << 4)\n\treturn fmt.Sprintf(\"%x-%x-%x-%x-%x\", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])\n}\n\n\n\n\nfunc ID(s string) Option {\n\treturn func(o *Options) {\n\t\to.ID = s\n\t}\n}\n\n\nfunc Topic(s string) Option {\n\treturn func(o *Options) {\n\t\to.Topic = []byte(s)\n\t}\n}\n\n\nfunc Schema(v graphql.Schema) Option {\n\treturn func(o *Options) {\n\t\to.Schema = v\n\t}\n}\n\n\nfunc Cache(v cache.Service) Option {\n\treturn func(o *Options) {\n\t\to.Cache = v\n\t}\n}\n\n\nfunc Message(m message.Service) Option {\n\treturn func(o *Options) {\n\t\to.Message = m\n\t}\n}\n\n\nfunc Logger(l logger.Service) Option {\n\treturn func(o *Options) {\n\t\to.Logger = l\n\t}\n}\n\nfunc newOptions(opts ...Option) Options ", "output": "{\n\topt := Options{\n\t\tID: newID(),\n\t}\n\tfor _, o := range opts {\n\t\to(&opt)\n\t}\n\tif len(opt.Topic) == 0 || opt.Topic == nil {\n\t\topt.Topic = []byte(\"graphql-ws\")\n\t}\n\treturn opt\n}"} {"input": "package loggo\n\nvar (\n\tdefaultContext = newDefaultContxt()\n)\n\nfunc newDefaultContxt() *Context {\n\tctx := NewContext(WARNING)\n\tctx.AddWriter(DefaultWriterName, defaultWriter())\n\treturn ctx\n}\n\n\nfunc DefaultContext() *Context {\n\treturn defaultContext\n}\n\n\n\n\n\nfunc LoggerInfo() string {\n\treturn defaultContext.Config().String()\n}\n\n\n\nfunc GetLogger(name string, size ...int) Logger {\n\treturn defaultContext.GetLogger(name, size...)\n}\n\n\n\n\n\nfunc ResetLogging() {\n\tdefaultContext.ResetLoggerLevels()\n\tdefaultContext.ResetWriters()\n}\n\n\nfunc ResetWriters() {\n\tdefaultContext.ResetWriters()\n}\n\n\n\n\nfunc ReplaceDefaultWriter(writer Writer) (Writer, error) {\n\treturn defaultContext.ReplaceWriter(DefaultWriterName, writer)\n}\n\n\n\n\nfunc RegisterWriter(name string, writer Writer) error {\n\treturn defaultContext.AddWriter(name, writer)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ConfigureLoggers(specification string) error {\n\tconfig, err := ParseConfigString(specification)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefaultContext.ApplyConfig(config)\n\treturn nil\n}\n\nfunc RemoveWriter(name string) (Writer, error) ", "output": "{\n\treturn defaultContext.RemoveWriter(name)\n}"} {"input": "package math\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\ntype CT_Integer2 struct {\n\tValAttr int64\n}\n\nfunc NewCT_Integer2() *CT_Integer2 {\n\tret := &CT_Integer2{}\n\tret.ValAttr = -2\n\treturn ret\n}\n\nfunc (m *CT_Integer2) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"m:val\"},\n\t\tValue: fmt.Sprintf(\"%v\", m.ValAttr)})\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}\n\n\n\n\nfunc (m *CT_Integer2) Validate() error {\n\treturn m.ValidateWithPath(\"CT_Integer2\")\n}\n\n\nfunc (m *CT_Integer2) ValidateWithPath(path string) error {\n\tif m.ValAttr < -2 {\n\t\treturn fmt.Errorf(\"%s/m.ValAttr must be >= -2 (have %v)\", path, m.ValAttr)\n\t}\n\tif m.ValAttr > 2 {\n\t\treturn fmt.Errorf(\"%s/m.ValAttr must be <= 2 (have %v)\", path, m.ValAttr)\n\t}\n\treturn nil\n}\n\nfunc (m *CT_Integer2) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error ", "output": "{\n\tm.ValAttr = -2\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"val\" {\n\t\t\tparsed, err := strconv.ParseInt(attr.Value, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.ValAttr = parsed\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_Integer2: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package cmd\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\t\"strconv\"\n\n\txhttp \"github.com/minio/minio/cmd/http\"\n)\n\nconst unavailable = \"offline\"\n\n\nfunc ClusterCheckHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := newContext(r, w, \"ClusterCheckHandler\")\n\n\tif shouldProxy() {\n\t\tw.Header().Set(xhttp.MinIOServerStatus, unavailable)\n\t\twriteResponse(w, http.StatusServiceUnavailable, nil, mimeNone)\n\t\treturn\n\t}\n\n\tobjLayer := newObjectLayerFn()\n\n\tctx, cancel := context.WithTimeout(ctx, globalAPIConfig.getClusterDeadline())\n\tdefer cancel()\n\n\topts := HealthOptions{Maintenance: r.URL.Query().Get(\"maintenance\") == \"true\"}\n\tresult := objLayer.Health(ctx, opts)\n\tif result.WriteQuorum > 0 {\n\t\tw.Header().Set(xhttp.MinIOWriteQuorum, strconv.Itoa(result.WriteQuorum))\n\t}\n\tif !result.Healthy {\n\t\tif result.HealingDrives > 0 {\n\t\t\tw.Header().Set(xhttp.MinIOHealingDrives, strconv.Itoa(result.HealingDrives))\n\t\t}\n\t\tif opts.Maintenance {\n\t\t\twriteResponse(w, http.StatusPreconditionFailed, nil, mimeNone)\n\t\t} else {\n\t\t\twriteResponse(w, http.StatusServiceUnavailable, nil, mimeNone)\n\t\t}\n\t\treturn\n\t}\n\twriteResponse(w, http.StatusOK, nil, mimeNone)\n}\n\n\nfunc ReadinessCheckHandler(w http.ResponseWriter, r *http.Request) {\n\tif shouldProxy() {\n\t\tw.Header().Set(xhttp.MinIOServerStatus, unavailable)\n\t}\n\n\twriteResponse(w, http.StatusOK, nil, mimeNone)\n}\n\n\n\n\nfunc LivenessCheckHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tif shouldProxy() {\n\t\tw.Header().Set(xhttp.MinIOServerStatus, unavailable)\n\t}\n\twriteResponse(w, http.StatusOK, nil, mimeNone)\n}"} {"input": "package matcher\n\nimport \"errors\"\n\ntype IntComparator struct{}\n\nfunc (s *IntComparator) Valid(data interface{}) error {\n\tif _, ok := data.(int); !ok {\n\t\treturn errors.New(\"Invalid argument\")\n\t}\n\n\treturn nil\n}\n\nfunc (s *IntComparator) GreaterThan(a, b interface{}) bool {\n\treturn a.(int) > b.(int)\n}\n\nfunc (s *IntComparator) LessThan(a, b interface{}) bool {\n\treturn a.(int) < b.(int)\n}\n\nfunc (s *IntComparator) EqualTo(a, b interface{}) bool {\n\treturn a.(int) == b.(int)\n}\n\n\n\nfunc (s *IntComparator) NotEqualTo(a, b interface{}) bool ", "output": "{\n\treturn a.(int) != b.(int)\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n)\n\ntype Monitor interface {\n\tGetVariables() []string\n\tGetValues([]string) map[string]interface{}\n}\n\nvar monitorDrivers = make(map[string]func(*json.RawMessage) Monitor)\n\nfunc AddMonitorDriver(monitor string, constructor func(*json.RawMessage) Monitor) {\n\tmonitorDrivers[monitor] = constructor\n}\n\ntype MonitorTrack struct {\n\tVariables map[string]*MonitorTrackVariable\n\tInterval int\n\ttimer *time.Timer\n}\n\n\n\ntype MonitorTrackVariable struct {\n\tHistory int\n\tData []interface{}\n}\n\nfunc (mt *MonitorTrack) SetTrack(variable string, history int) {\n\ttrack, ok := mt.Variables[variable]\n\tif !ok && history > 0 {\n\t\ttrack = &MonitorTrackVariable{}\n\t\tmt.Variables[variable] = track\n\t}\n\tif history == 0 && ok {\n\t\tdelete(mt.Variables, variable)\n\t\treturn\n\t}\n\ttrack.History = history\n}\n\nfunc (mt *MonitorTrack) Start(monitor Monitor) {\n\tgo func() {\n\t\tmt.timer = time.NewTimer(time.Duration(1) * time.Second)\n\t\tfor _ = range mt.timer.C {\n\t\t\tif mt.Interval > 0 {\n\t\t\t\tmt.timer.Reset(time.Second * time.Duration(mt.Interval))\n\t\t\t}\n\t\t\tvariables := []string{}\n\t\t\tfor variable := range mt.Variables {\n\t\t\t\tvariables = append(variables, variable)\n\t\t\t}\n\t\t\tvalues := monitor.GetValues(variables)\n\t\t\tfor variable, vt := range mt.Variables {\n\t\t\t\tvt.Data = append(vt.Data, values[variable])\n\t\t\t\tif len(vt.Data) > vt.History {\n\t\t\t\t\tvt.Data = vt.Data[len(vt.Data)-vt.History:]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc newMonitorTrack() *MonitorTrack ", "output": "{\n\treturn &MonitorTrack{\n\t\tVariables: make(map[string]*MonitorTrackVariable),\n\t}\n}"} {"input": "package iso20022\n\n\ntype DirectDebitTransaction1 struct {\n\n\tMandateRelatedInformation *MandateRelatedInformation1 `xml:\"MndtRltdInf,omitempty\"`\n\n\tCreditorSchemeIdentification *PartyIdentification8 `xml:\"CdtrSchmeId,omitempty\"`\n\n\tPreNotificationIdentification *Max35Text `xml:\"PreNtfctnId,omitempty\"`\n\n\tPreNotificationDate *ISODate `xml:\"PreNtfctnDt,omitempty\"`\n}\n\nfunc (d *DirectDebitTransaction1) AddMandateRelatedInformation() *MandateRelatedInformation1 {\n\td.MandateRelatedInformation = new(MandateRelatedInformation1)\n\treturn d.MandateRelatedInformation\n}\n\n\n\nfunc (d *DirectDebitTransaction1) SetPreNotificationIdentification(value string) {\n\td.PreNotificationIdentification = (*Max35Text)(&value)\n}\n\nfunc (d *DirectDebitTransaction1) SetPreNotificationDate(value string) {\n\td.PreNotificationDate = (*ISODate)(&value)\n}\n\nfunc (d *DirectDebitTransaction1) AddCreditorSchemeIdentification() *PartyIdentification8 ", "output": "{\n\td.CreditorSchemeIdentification = new(PartyIdentification8)\n\treturn d.CreditorSchemeIdentification\n}"} {"input": "package admin\n\nimport (\n\tapi \"github.com/gogits/go-gogs-client\"\n\n\t\"github.com/G-Node/gogs/models\"\n\t\"github.com/G-Node/gogs/pkg/context\"\n\t\"github.com/G-Node/gogs/routes/api/v1/convert\"\n\t\"github.com/G-Node/gogs/routes/api/v1/user\"\n)\n\n\n\n\nfunc CreateOrg(c *context.APIContext, form api.CreateOrgOption) ", "output": "{\n\tu := user.GetUserByParams(c)\n\tif c.Written() {\n\t\treturn\n\t}\n\n\torg := &models.User{\n\t\tName: form.UserName,\n\t\tFullName: form.FullName,\n\t\tDescription: form.Description,\n\t\tWebsite: form.Website,\n\t\tLocation: form.Location,\n\t\tIsActive: true,\n\t\tType: models.USER_TYPE_ORGANIZATION,\n\t}\n\tif err := models.CreateOrganization(org, u); err != nil {\n\t\tif models.IsErrUserAlreadyExist(err) ||\n\t\t\tmodels.IsErrNameReserved(err) ||\n\t\t\tmodels.IsErrNamePatternNotAllowed(err) {\n\t\t\tc.Error(422, \"\", err)\n\t\t} else {\n\t\t\tc.Error(500, \"CreateOrganization\", err)\n\t\t}\n\t\treturn\n\t}\n\n\tc.JSON(201, convert.ToOrganization(org))\n}"} {"input": "package mongo\n\nimport (\n\t\"github.com/peteraba/d5/lib/util\"\n\t\"gopkg.in/mgo.v2\"\n)\n\nvar (\n\tsession *mgo.Session\n\tdb *mgo.Database\n)\n\nfunc SetMgoSession(mgoSession *mgo.Session) {\n\tsession = mgoSession\n}\n\nfunc SetMgoDb(mgoDatabase *mgo.Database) {\n\tdb = mgoDatabase\n}\n\n\n\nfunc CreateMgoDb(dbHost, dbName string) (*mgo.Database, error) {\n\tsession, err := getMgoSession(dbHost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn getMgoDb(session, dbName), nil\n}\n\nfunc getMgoSession(dbHost string) (*mgo.Session, error) {\n\tvar (\n\t\terr error\n\t)\n\n\tif session != nil {\n\t\treturn session, nil\n\t}\n\n\tsession, err = mgo.Dial(dbHost)\n\n\treturn session, err\n}\n\nfunc getMgoDb(mgoSession *mgo.Session, dbName string) *mgo.Database {\n\tif db != nil {\n\t\treturn db\n\t}\n\n\tmgoSession = mgoSession.Clone()\n\n\tdb = mgoSession.DB(dbName)\n\n\treturn db\n}\n\nfunc CreateMgoDbFromEnvs() *mgo.Database ", "output": "{\n\tdbHost, dbName := ParseDbEnvs()\n\n\tmgoDb, err := CreateMgoDb(dbHost, dbName)\n\n\tif err != nil {\n\t\tutil.LogFatalfMsg(err, \"MongoDB database could not be created: %v\", true)\n\t}\n\n\treturn mgoDb\n}"} {"input": "package quote\n\nimport (\n\t\"testing\"\n)\n\nfunc TestCodeQuote(t *testing.T) {\n\tresult := codeQuote()\n\tif len(result) == 0 {\n\t\tt.Errorf(\"No valid quote returned.\")\n\t}\n}\n\nfunc TestIntegrationQuote(t *testing.T) {\n\tresult := integrationQuote()\n\tif len(result) == 0 {\n\t\tt.Errorf(\"No valid integration quote returned.\")\n\t}\n}\n\n\n\nfunc TestAdminQuote(t *testing.T) ", "output": "{\n\tresult := integrationQuote()\n\tif len(result) == 0 {\n\t\tt.Errorf(\"No valid integration quote returned.\")\n\t}\n}"} {"input": "package http\n\nimport (\n\t\"net/http\"\n\t\"net/http/cookiejar\"\n\t\"net/url\"\n\t\"sync\"\n\n\tc \"github.com/d0ngw/go/common\"\n)\n\n\ntype RetrivedCookieJar struct {\n\tjar *cookiejar.Jar\n\turlCookies map[string][]*http.Cookie\n\tmu sync.Mutex\n}\n\n\nfunc NewRetrivedCookieJar(o *cookiejar.Options) *RetrivedCookieJar {\n\tjar, _ := cookiejar.New(o)\n\treturn &RetrivedCookieJar{\n\t\tjar: jar,\n\t\turlCookies: map[string][]*http.Cookie{},\n\t}\n}\n\n\n\n\n\nfunc (p *RetrivedCookieJar) Cookies(u *url.URL) []*http.Cookie {\n\treturn p.jar.Cookies(u)\n}\n\n\nfunc (p *RetrivedCookieJar) URLAndCookies() map[string][]*http.Cookie {\n\tall := map[string][]*http.Cookie{}\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tfor k, v := range p.urlCookies {\n\t\tall[k] = v\n\t}\n\treturn all\n}\n\n\nfunc (p *RetrivedCookieJar) SetURLAndCookies(all map[string][]*http.Cookie) error {\n\tif all == nil {\n\t\treturn nil\n\t}\n\n\tfor u, cookies := range all {\n\t\tif cookies == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tcookieURL, err := url.Parse(u)\n\t\tif err != nil {\n\t\t\tc.Errorf(\"parse %s fail,err:%s\", u, err)\n\t\t\tcontinue\n\t\t}\n\t\tp.SetCookies(cookieURL, cookies)\n\t}\n\n\treturn nil\n}\n\nfunc (p *RetrivedCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) ", "output": "{\n\tp.jar.SetCookies(u, cookies)\n\tcookieURL := u.String()\n\tif u != nil && cookies != nil {\n\t\tp.mu.Lock()\n\t\tp.urlCookies[cookieURL] = append(p.urlCookies[cookieURL], cookies...)\n\t\tp.mu.Unlock()\n\t}\n}"} {"input": "package timer\n\nimport (\n\t\"time\"\n)\n\ntype typeAction int\n\nconst (\n\tCLOSE typeAction = iota\n\tRESET\n\tFORCE\n)\n\n\n\ntype Timer struct {\n\tinterval time.Duration\n\tmsg, resp chan typeAction\n}\n\n\n\n\nfunc NewTimer(interval time.Duration) *Timer {\n\treturn &Timer{\n\t\tinterval: interval,\n\t\tmsg: make(chan typeAction, 1),\n\t\tresp: make(chan typeAction, 1),\n\t}\n}\n\n\n\n\nfunc (self *Timer) Next() bool {\n\tfor {\n\t\tvar ch <-chan time.Time\n\t\tif self.interval <= 0 {\n\t\t\tch = nil\n\t\t} else {\n\t\t\tch = time.After(self.interval)\n\t\t}\n\t\tselect {\n\t\tcase action := <-self.msg:\n\t\t\tswitch action {\n\t\t\tcase CLOSE:\n\t\t\t\tself.resp <- CLOSE\n\t\t\t\treturn false\n\t\t\tcase FORCE:\n\t\t\t\treturn true\n\t\t\t}\n\t\tcase <-ch:\n\t\t\treturn true\n\t\t}\n\t}\n\tpanic(\"unreachable\")\n}\n\n\n\nfunc (self *Timer) SetInterval(ns time.Duration) {\n\tself.interval = ns\n\tself.msg <- RESET\n}\n\n\n\nfunc (self *Timer) Trigger() {\n\tself.msg <- FORCE\n}\n\n\nfunc (self *Timer) TriggerAfter(ns time.Duration) {\n\tgo func() {\n\t\t<-time.After(ns)\n\t\tself.Trigger()\n\t}()\n}\n\n\n\n\n\n\nfunc (self *Timer) Close() ", "output": "{\n\tself.msg <- CLOSE\n\t<-self.resp\n}"} {"input": "package main\n\nimport (\n\t\"html/template\"\n\t\"net/http\"\n\t\"time\"\n)\n\nvar tpl = `\n\n \n \n Date Example\n \n \n \t

{{.Date | dateFormat \"Jan 2, 2006\"}}

\n \n`\n\nvar funcMap = template.FuncMap{\n\t\"dateFormat\": dateFormat,\n}\n\n\n\nfunc serveTemplate(res http.ResponseWriter, req *http.Request) {\n\tt := template.New(\"date\")\n\tt.Funcs(funcMap)\n\tt.Parse(tpl)\n\tdata := struct{ Date time.Time }{\n\t\tDate: time.Now(),\n\t}\n\tt.Execute(res, data)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/\", serveTemplate)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc dateFormat(layout string, d time.Time) string ", "output": "{\n\treturn d.Format(layout)\n}"} {"input": "package colibri_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/scionproto/scion/go/lib/slayers/path/colibri\"\n)\n\n\n\nfunc TestColibriInfofieldSerializeDecode(t *testing.T) ", "output": "{\n\tbuffer := []byte(\"073f5f1c20df5381f2e896d0\")\n\tbuffer[0] = buffer[0] & uint8(0xE0)\n\tbuffer[1] = buffer[1] & uint8(0x0F)\n\n\tinf := &colibri.InfoField{}\n\tassert.NoError(t, inf.DecodeFromBytes(buffer))\n\n\tbuffer2 := make([]byte, colibri.LenInfoField)\n\tassert.NoError(t, inf.SerializeTo(buffer2))\n\tassert.Equal(t, buffer, buffer2)\n}"} {"input": "package fasthttpradix\n\n\nimport (\n\t\"github.com/valyala/fasthttp\"\n\trr \"github.com/byte-mug/golibs/radixroute\"\n\t\"strings\"\n)\n\n\nfunc NormPath(str string) string {\n\treturn \"/\"+strings.Trim(str,\"/\")+\"/\"\n}\n\n\n\ntype handling struct{\n\thandle fasthttp.RequestHandler\n}\ntype Router struct{\n\troutes map[string]*rr.Tree\n}\nfunc (r *Router) getOrCreate(m string) *rr.Tree {\n\tt := r.routes[m]\n\tif t!=nil { return t }\n\tif r.routes==nil { r.routes = make(map[string]*rr.Tree) }\n\tr.routes[m] = rr.New()\n\treturn r.routes[m]\n}\nfunc (r *Router) Handle(method string,path string,handler fasthttp.RequestHandler) {\n\tif handler==nil { panic(\"handler must not be nil\") }\n\th := &handling{handler}\n\tcpath := []byte(NormPath(path))\n\tbpath := cpath[:len(cpath)-1]\n\tif method==\"\" {\n\t\tmethod = \"DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT\"\n\t}\n\tfor _,m := range strings.Split(method,\",\") {\n\t\trrt := r.getOrCreate(m)\n\t\trrt.InsertRoute(bpath,h)\n\t\trrt.InsertRoute(cpath,h)\n\t}\n}\nfunc (r *Router) RequestHandler(ctx *fasthttp.RequestCtx) {\n\tt := r.routes[string(ctx.Method())]\n\tif t==nil {\n\t\tInvalidPath(ctx)\n\t\treturn\n\t}\n\ti,_ := t.Get(ctx.Path(),ctx.SetUserValue)\n\th,ok := i.(*handling)\n\tif !ok {\n\t\tInvalidPath(ctx)\n\t\treturn\n\t}\n\th.handle(ctx)\n}\n\nfunc InvalidPath(ctx *fasthttp.RequestCtx) ", "output": "{\n\tctx.SetBody([]byte(\"404 Not Found\\n\"))\n\tctx.SetStatusCode(fasthttp.StatusNotFound)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\n\t\"gopkg.in/yaml.v1\"\n)\n\nconst (\n\tCONFIG_SUBDIR = \"mcmd\"\n\tDEFAULT_KNOWN_HOSTS_FILE = \"$HOME/.ssh/known_hosts\"\n)\n\ntype HostConfig struct {\n\tUser string\n\tPrivatekey string\n\tHosts []string\n}\n\nfunc loadConfig() HostConfig {\n\trawYaml := readHostfile()\n\tvar result HostConfig\n\terr := yaml.Unmarshal(rawYaml, &result)\n\tif err != nil {\n\t\terrLogger.Fatalln(\"Error parsing hostfile:\", err)\n\t}\n\treturn result\n}\n\nfunc readHostfile() []byte {\n\tconfigFileParam := flag.Arg(0)\n\tfor _, file := range getConfigLocationCandidates(configFileParam) {\n\t\tif exists(file) {\n\t\t\treturn getContents(file)\n\t\t}\n\t}\n\terrLogger.Fatalf(\"hostfile %s not found\", configFileParam)\n\treturn nil\n}\n\nfunc getConfigLocationCandidates(configFileParam string) []string {\n\tconfigRoot, err := os.UserConfigDir()\n\tif err != nil {\n\t\terrLogger.Fatalf(\"no user config dir found\")\n\t}\n\tconfigDir := path.Join(configRoot, CONFIG_SUBDIR)\n\treturn []string{configFileParam,\n\t\tpath.Join(configDir, configFileParam+\".yml\"),\n\t\tpath.Join(configDir, configFileParam+\".yaml\")}\n}\n\nfunc exists(filename string) bool {\n\t_, err := os.Stat(filename)\n\treturn !os.IsNotExist(err)\n}\n\n\n\nfunc getContents(filename string) []byte ", "output": "{\n\tfileContents, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\terrLogger.Fatalln(err)\n\t}\n\treturn fileContents\n}"} {"input": "package upax_go\n\n\n\nimport (\n\txi \"github.com/jddixon/xlNodeID_go\"\n)\n\n\n\n\n\n\ntype ClientIHaveMgr struct {\n\tiHaveCh chan IHaveObj\n\tentries *xi.IDMap \n\toutMsgCh chan *UpaxClientMsg\n\tstopCh chan bool\n}\n\nfunc NewClientIHaveMgr(iHaveCh chan IHaveObj, entries *xi.IDMap,\n\toutMsgCh chan *UpaxClientMsg, stopCh chan bool) (\n\tmgr *ClientIHaveMgr, err error) {\n\n\tif iHaveCh == nil {\n\t\terr = NilIHaveChan\n\t} else if entries == nil {\n\t\terr = NilIDMap\n\t} else if outMsgCh == nil {\n\t\terr = NilOutMsgCh\n\t} else {\n\t\tmgr = &ClientIHaveMgr{\n\t\t\tiHaveCh: iHaveCh,\n\t\t\tentries: entries,\n\t\t\toutMsgCh: outMsgCh,\n\t\t\tstopCh: stopCh,\n\t\t}\n\t}\n\treturn\n}\n\n\n\n\n\nfunc (mgr *ClientIHaveMgr) Run() ", "output": "{\n\tvar whatever interface{}\n\tvar err error\n\tfor {\n\t\tselect {\n\t\tcase iHaveObj := <-mgr.iHaveCh:\n\t\t\tids := iHaveObj.IDs\n\t\t\tfor i := 0; i < len(ids); i++ {\n\t\t\t\tid := ids[i]\n\t\t\t\twhatever, err = mgr.entries.Find(id)\n\t\t\t\tif (err == nil) && (whatever == nil) {\n\t\t\t\t\top := UpaxClientMsg_Get\n\t\t\t\t\tmsgOut := &UpaxClientMsg{\n\t\t\t\t\t\tOp: &op,\n\t\t\t\t\t\tHash: id,\n\t\t\t\t\t}\n\t\t\t\t\tmgr.outMsgCh <- msgOut\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-mgr.stopCh:\n\t\t\tbreak\n\t\t}\n\t}\n}"} {"input": "package vault\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/hashicorp/vault/sdk/logical\"\n)\n\nconst sscGenCounterPath string = \"core/sscGenCounter/\"\n\ntype SSCTokenGenerationCounter struct {\n\tCounter int\n}\n\nfunc (ts *TokenStore) GetSSCTokensGenerationCounter() int {\n\treturn ts.sscTokensGenerationCounter.Counter\n}\n\n\n\nfunc (ts *TokenStore) UpdateSSCTokensGenerationCounter(ctx context.Context) error {\n\tts.sscTokensGenerationCounter.Counter += 1\n\tif ts.sscTokensGenerationCounter.Counter <= 0 {\n\t\tts.logger.Warn(\"attempt to store non-positive token generation counter was ignored\",\n\t\t\t\"sscTokensGenerationCounter\", ts.sscTokensGenerationCounter.Counter)\n\t}\n\tmarshalledCtr, err := json.Marshal(ts.sscTokensGenerationCounter)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ts.core.barrier.Put(ctx, &logical.StorageEntry{\n\t\tKey: sscGenCounterPath,\n\t\tValue: marshalledCtr,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (ts *TokenStore) loadSSCTokensGenerationCounter(ctx context.Context) error ", "output": "{\n\tsscTokensGenerationCounterStorageVal, err := ts.core.barrier.Get(ctx, sscGenCounterPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to retrieve SSCTokenGenerationCounter from storage: err %w\", err)\n\t}\n\tif sscTokensGenerationCounterStorageVal == nil {\n\t\tts.logger.Trace(\"no token generation counter found in storage\")\n\t\tts.sscTokensGenerationCounter = SSCTokenGenerationCounter{Counter: 0}\n\t\treturn nil\n\t}\n\tvar sscTokensGenerationCounter SSCTokenGenerationCounter\n\terr = json.Unmarshal(sscTokensGenerationCounterStorageVal.Value, &sscTokensGenerationCounter)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"malformed token generation counter found in storage: err %w\", err)\n\t}\n\tts.sscTokensGenerationCounter = sscTokensGenerationCounter\n\treturn nil\n}"} {"input": "package migrations\n\nimport (\n\t\"database/sql\"\n\n\t\"github.com/pressly/goose\"\n)\n\nfunc init() {\n\tgoose.AddMigration(up00002, down00002)\n}\n\nfunc up00002(tx *sql.Tx) error {\n\t_, err := tx.Exec(`CREATE TABLE IF NOT EXISTS users (email text)`)\n\treturn err\n}\n\n\n\nfunc down00002(tx *sql.Tx) error ", "output": "{\n\t_, err := tx.Exec(`DROP TABLE users`)\n\treturn err\n}"} {"input": "package bitswap\n\nimport (\n\t\"context\"\n\n\tbsnet \"github.com/ipfs/go-ipfs/exchange/bitswap/network\"\n\tmockrouting \"github.com/ipfs/go-ipfs/routing/mock\"\n\tpeer \"gx/ipfs/QmWNY7dV54ZDYmTA1ykVdwNCqC11mpU4zSUp6XDpLTH9eG/go-libp2p-peer\"\n\tmockpeernet \"gx/ipfs/Qma23bpHwQrQyvKeBemaeJh7sAoRHggPkgnge1B9489ff5/go-libp2p/p2p/net/mock\"\n\tds \"gx/ipfs/QmdHG8MAuARdGHxx4rPQASLcvhz24fzjSQq7AJRAQEorq5/go-datastore\"\n\ttestutil \"gx/ipfs/QmeDA8gNhvRTsbrjEieay5wezupJDiky8xvCzDABbsGzmp/go-testutil\"\n)\n\ntype peernet struct {\n\tmockpeernet.Mocknet\n\troutingserver mockrouting.Server\n}\n\nfunc StreamNet(ctx context.Context, net mockpeernet.Mocknet, rs mockrouting.Server) (Network, error) {\n\treturn &peernet{net, rs}, nil\n}\n\nfunc (pn *peernet) Adapter(p testutil.Identity) bsnet.BitSwapNetwork {\n\tclient, err := pn.Mocknet.AddPeer(p.PrivateKey(), p.Address())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\trouting := pn.routingserver.ClientWithDatastore(context.TODO(), p, ds.NewMapDatastore())\n\treturn bsnet.NewFromIpfsHost(client, routing)\n}\n\n\n\nvar _ Network = (*peernet)(nil)\n\nfunc (pn *peernet) HasPeer(p peer.ID) bool ", "output": "{\n\tfor _, member := range pn.Mocknet.Peers() {\n\t\tif p == member {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package parse\n\n\nimport (\n\t\"strings\"\n)\n\nfunc indent(s string, character string, size int) string {\n\tindent := strings.Repeat(character, size)\n\tlines := strings.Split(s, newLine)\n\tfor k, v := range lines {\n\t\tif len(v) > 0 {\n\t\t\tlines[k] = indent + v\n\t\t}\n\t}\n\treturn strings.Join(lines, newLine)\n}\n\n\n\n\n\n\n\nfunc EqualSlicesFoldSuffix(a, suffix []string) bool {\n\tl, lsuffix := len(a), len(suffix)\n\tswitch {\n\tcase lsuffix == 0:\n\t\treturn true\n\tcase l < lsuffix:\n\t\treturn false\n\tcase l > lsuffix:\n\t\treturn EqualSlicesFold(a[l-lsuffix:], suffix)\n\tdefault:\n\t\treturn EqualSlicesFold(a, suffix)\n\t}\n}\n\n\n\nfunc EqualSlicesFold(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor k := range a {\n\t\tif !strings.EqualFold(a[k], b[k]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\nfunc EqualSlicesFoldSome(a []string, b ...[]string) bool {\n\tif len(a) == 0 && len(b) == 0 {\n\t\treturn true\n\t}\n\n\tfor k := range b {\n\t\tif EqualSlicesFold(a, b[k]) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc EqualSlicesFoldPrefix(a, prefix []string) bool ", "output": "{\n\tl, lprefix := len(a), len(prefix)\n\tswitch {\n\tcase lprefix == 0:\n\t\treturn true\n\tcase l < lprefix:\n\t\treturn false\n\tcase l > lprefix:\n\t\treturn EqualSlicesFold(a[:lprefix], prefix)\n\tdefault:\n\t\treturn EqualSlicesFold(a, prefix)\n\t}\n}"} {"input": "package terms_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/purl.org/dc/terms\"\n)\n\n\n\nfunc TestISO639_2MarshalUnmarshal(t *testing.T) {\n\tv := terms.NewISO639_2()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := terms.NewISO639_2()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestISO639_2Constructor(t *testing.T) ", "output": "{\n\tv := terms.NewISO639_2()\n\tif v == nil {\n\t\tt.Errorf(\"terms.NewISO639_2 must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed terms.ISO639_2 should validate: %s\", err)\n\t}\n}"} {"input": "package expr\n\nimport (\n\t\"github.com/grafana/metrictank/api/models\"\n)\n\ntype FuncUnique struct {\n\tin []GraphiteFunc\n}\n\nfunc NewUnique() GraphiteFunc {\n\treturn &FuncUnique{}\n}\n\nfunc (s *FuncUnique) Signature() ([]Arg, []Arg) {\n\treturn []Arg{\n\t\tArgSeriesLists{val: &s.in}}, []Arg{ArgSeriesList{}}\n}\n\nfunc (s *FuncUnique) Context(context Context) Context {\n\treturn context\n}\n\n\n\nfunc (s *FuncUnique) Exec(dataMap DataMap) ([]models.Series, error) ", "output": "{\n\tseries, _, err := consumeFuncs(dataMap, s.in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tseenNames := make(map[string]bool)\n\tvar uniqueSeries []models.Series\n\tfor _, serie := range series {\n\t\tif _, ok := seenNames[serie.Target]; !ok {\n\t\t\tseenNames[serie.Target] = true\n\t\t\tuniqueSeries = append(uniqueSeries, serie)\n\t\t}\n\t}\n\treturn uniqueSeries, nil\n}"} {"input": "package blog\n\nimport (\n\t\"github.com/crockeo/personalwebsite/database\"\n\t\"github.com/crockeo/personalwebsite/helpers\"\n\t\"html/template\"\n\t\"net/http\"\n)\n\n\n\n\nfunc Handler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tposts := database.QuickGetPosts()\n\n\tif len(posts) == 0 {\n\t\thelpers.SendPage(w, \"noblog\", struct{}{})\n\t} else {\n\t\tdposts := make([]template.HTML, len(posts))\n\n\t\tfor i := 0; i < len(posts); i++ {\n\t\t\tdposts[i] = posts[i].Display()\n\t\t}\n\n\t\thelpers.SendPage(w, \"blog\", struct{ Posts []template.HTML }{Posts: dposts})\n\t}\n}"} {"input": "package localrouter\n\nimport (\n\t\"context\"\n\n\tlocalrouterBuilder \"github.com/sacloud/libsacloud/v2/helper/builder/localrouter\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\n\ntype Builder struct {\n\tID types.ID\n\tName string\n\tDescription string\n\tTags types.Tags\n\tIconID types.ID\n\n\tSwitch *sacloud.LocalRouterSwitch\n\tInterface *sacloud.LocalRouterInterface\n\tPeers []*sacloud.LocalRouterPeer\n\tStaticRoutes []*sacloud.LocalRouterStaticRoute\n\n\tSettingsHash string\n\n\tCaller sacloud.APICaller\n}\n\n\n\nfunc (b *Builder) Build(ctx context.Context) (*sacloud.LocalRouter, error) {\n\tbuilder := &localrouterBuilder.Builder{\n\t\tName: b.Name,\n\t\tDescription: b.Description,\n\t\tTags: b.Tags,\n\t\tIconID: b.IconID,\n\t\tSwitch: b.Switch,\n\t\tInterface: b.Interface,\n\t\tPeers: b.Peers,\n\t\tStaticRoutes: b.StaticRoutes,\n\t\tSettingsHash: b.SettingsHash,\n\t\tClient: localrouterBuilder.NewAPIClient(b.Caller),\n\t}\n\n\tif b.ID.IsEmpty() {\n\t\treturn builder.Build(ctx)\n\t}\n\treturn builder.Update(ctx, b.ID)\n}\n\nfunc BuilderFromResource(ctx context.Context, caller sacloud.APICaller, id types.ID) (*Builder, error) ", "output": "{\n\tclient := sacloud.NewLocalRouterOp(caller)\n\tcurrent, err := client.Read(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Builder{\n\t\tName: current.Name,\n\t\tDescription: current.Description,\n\t\tTags: current.Tags,\n\t\tIconID: current.IconID,\n\t\tSwitch: current.Switch,\n\t\tInterface: current.Interface,\n\t\tPeers: current.Peers,\n\t\tStaticRoutes: current.StaticRoutes,\n\t\tCaller: caller,\n\t}, nil\n}"} {"input": "package reconcilers\n\nimport (\n\t\"net\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n)\n\n\ntype noneEndpointReconciler struct{}\n\n\n\n\n\n\nfunc (r *noneEndpointReconciler) ReconcileEndpoints(serviceName string, ip net.IP, endpointPorts []api.EndpointPort, reconcilePorts bool) error {\n\treturn nil\n}\n\n\nfunc (r *noneEndpointReconciler) StopReconciling(serviceName string, ip net.IP, endpointPorts []api.EndpointPort) error {\n\treturn nil\n}\n\nfunc NewNoneEndpointReconciler() EndpointReconciler ", "output": "{\n\treturn &noneEndpointReconciler{}\n}"} {"input": "package sacloud\n\n\ntype Icon struct {\n\t*Resource \n\tpropAvailability \n\tpropName \n\tpropScope \n\tpropTags \n\tpropCreatedAt \n\tpropModifiedAt \n\n\tURL string `json:\",omitempty\"` \n\tImage string `json:\",omitempty\"` \n}\n\n\ntype Image string\n\n\nfunc (icon *Icon) GetURL() string {\n\treturn icon.URL\n}\n\n\n\n\n\nfunc (icon *Icon) SetImage(image string) {\n\ticon.Image = image\n}\n\nfunc (icon *Icon) GetImage() string ", "output": "{\n\treturn icon.Image\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc Test_logEvent_tooBig(t *testing.T) {\n\tevent := logEvent{msg: RandomString(maxEventSize + 1)}\n\tassert.Equal(t, errMessageTooBig, event.validate())\n}\n\nfunc Test_destination_string(t *testing.T) {\n\tdst := destination{group: \"group\", stream: \"stream\"}\n\tassert.Equal(t, \"group: group stream: stream\", dst.String())\n}\n\nfunc Test_logEvent_size(t *testing.T) ", "output": "{\n\tevent := logEvent{msg: \"123\", timestamp: 123}\n\texpected := 3 + eventSizeOverhead\n\tassert.Equal(t, expected, event.size())\n}"} {"input": "package common\n\nimport (\n\t\"github.com/mitchellh/goamz/ec2\"\n\t\"log\"\n\t\"time\"\n)\n\n\n\n\nfunc WaitForAMI(c *ec2.EC2, imageId string) error ", "output": "{\n\tfor {\n\t\timageResp, err := c.Images([]string{imageId}, ec2.NewFilter())\n\t\tif err != nil {\n\t\t\tif ec2err, ok := err.(*ec2.Error); ok && ec2err.Code == \"InvalidAMIID.NotFound\" {\n\t\t\t\tlog.Println(\"AMI not found, probably state issues on AWS side. Trying again.\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treturn err\n\t\t}\n\n\t\tif imageResp.Images[0].State == \"available\" {\n\t\t\treturn nil\n\t\t}\n\n\t\tlog.Printf(\"Image in state %s, sleeping 2s before checking again\",\n\t\t\timageResp.Images[0].State)\n\t\ttime.Sleep(2 * time.Second)\n\t}\n}"} {"input": "package swarm\n\nimport (\n\t\"strings\"\n)\n\n\nfunc convertKVStringsToMap(values []string) map[string]string {\n\tresult := make(map[string]string, len(values))\n\tfor _, value := range values {\n\t\tkv := strings.SplitN(value, \"=\", 2)\n\t\tif len(kv) == 1 {\n\t\t\tresult[kv[0]] = \"\"\n\t\t} else {\n\t\t\tresult[kv[0]] = kv[1]\n\t\t}\n\t}\n\n\treturn result\n}\n\n\n\n\nfunc convertMapToKVStrings(values map[string]string) []string ", "output": "{\n\tresult := make([]string, len(values))\n\ti := 0\n\tfor key, value := range values {\n\t\tresult[i] = key + \"=\" + value\n\t\ti++\n\t}\n\treturn result\n}"} {"input": "package subnets\n\nimport \"net\"\n\nfunc equals(a *net.IPNet, b *net.IPNet) bool {\n\taOnes, aBits := a.Mask.Size()\n\tbOnes, bBits := b.Mask.Size()\n\treturn a.IP.Equal(b.IP) && (aOnes == bOnes) && (aBits == bBits)\n}\n\nfunc overlaps(a *net.IPNet, b *net.IPNet) bool {\n\treturn a.Contains(b.IP) || b.Contains(a.IP)\n}\n\nfunc next(ip net.IP) net.IP {\n\tnext := clone(ip)\n\tfor i := len(next) - 1; i >= 0; i-- {\n\t\tnext[i]++\n\t\tif next[i] != 0 {\n\t\t\treturn next\n\t\t}\n\t}\n\n\tpanic(\"overflowed maximum IP\")\n}\n\n\n\nfunc max(ipn *net.IPNet) net.IP {\n\tmask := ipn.Mask\n\tmin := clone(ipn.IP)\n\n\tif len(mask) != len(min) {\n\t\tpanic(\"length of mask is not compatible with length of network IP\")\n\t}\n\n\tmax := make([]byte, len(min))\n\tfor i, b := range mask {\n\t\tmax[i] = min[i] | ^b\n\t}\n\n\treturn net.IP(max).To16()\n}\n\nfunc clone(ip net.IP) net.IP ", "output": "{\n\tclone := make([]byte, len(ip))\n\tcopy(clone, ip)\n\treturn clone\n}"} {"input": "package local\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/apache/beam/sdks/go/pkg/beam/io/textio\"\n)\n\n\n\ntype fs struct{}\n\n\nfunc New(ctx context.Context) textio.FileSystem {\n\treturn &fs{}\n}\n\nfunc (f *fs) Close() error {\n\treturn nil\n}\n\nfunc (f *fs) List(ctx context.Context, glob string) ([]string, error) {\n\treturn filepath.Glob(glob)\n}\n\nfunc (f *fs) OpenRead(ctx context.Context, filename string) (io.ReadCloser, error) {\n\treturn os.Open(filename)\n}\n\nfunc (f *fs) OpenWrite(ctx context.Context, filename string) (io.WriteCloser, error) {\n\tif err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {\n\t\treturn nil, err\n\t}\n\treturn os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\n}\n\nfunc init() ", "output": "{\n\ttextio.RegisterFileSystem(\"default\", New)\n}"} {"input": "package pttw\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\nfunc Read(reader io.Reader) ([]float64, error) ", "output": "{\n\tslice := []float64{}\n\tfor {\n\t\tvar value float64\n\t\tn, err := fmt.Fscan(reader, &value)\n\t\tif n == 0 || err != nil {\n\t\t\tif (err.Error() == \"EOF\") {\n\t\t\t\tbreak\n\t\t\t}else {\n\t\t\t\treturn slice, err\n\t\t\t}\n\t\t}\n\t\tslice = append(slice, value)\n\t}\n\treturn slice, nil\n}"} {"input": "package gexec\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/atlassian/git-lob/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n)\n\n\nfunc Exit(optionalExitCode ...int) *exitMatcher {\n\texitCode := -1\n\tif len(optionalExitCode) > 0 {\n\t\texitCode = optionalExitCode[0]\n\t}\n\n\treturn &exitMatcher{\n\t\texitCode: exitCode,\n\t}\n}\n\ntype exitMatcher struct {\n\texitCode int\n\tdidExit bool\n\tactualExitCode int\n}\n\ntype Exiter interface {\n\tExitCode() int\n}\n\n\n\nfunc (m *exitMatcher) FailureMessage(actual interface{}) (message string) {\n\tif m.actualExitCode == -1 {\n\t\treturn \"Expected process to exit. It did not.\"\n\t} else {\n\t\treturn format.Message(m.actualExitCode, \"to match exit code:\", m.exitCode)\n\t}\n}\n\nfunc (m *exitMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\tif m.actualExitCode == -1 {\n\t\treturn \"you really shouldn't be able to see this!\"\n\t} else {\n\t\tif m.exitCode == -1 {\n\t\t\treturn \"Expected process not to exit. It did.\"\n\t\t} else {\n\t\t\treturn format.Message(m.actualExitCode, \"not to match exit code:\", m.exitCode)\n\t\t}\n\t}\n}\n\nfunc (m *exitMatcher) MatchMayChangeInTheFuture(actual interface{}) bool {\n\tsession, ok := actual.(*Session)\n\tif ok {\n\t\treturn session.ExitCode() == -1\n\t}\n\treturn true\n}\n\nfunc (m *exitMatcher) Match(actual interface{}) (success bool, err error) ", "output": "{\n\texiter, ok := actual.(Exiter)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"Exit must be passed a gexec.Exiter (Missing method ExitCode() int) Got:\\n%s\", format.Object(actual, 1))\n\t}\n\n\tm.actualExitCode = exiter.ExitCode()\n\n\tif m.actualExitCode == -1 {\n\t\treturn false, nil\n\t}\n\n\tif m.exitCode == -1 {\n\t\treturn true, nil\n\t}\n\treturn m.exitCode == m.actualExitCode, nil\n}"} {"input": "package http\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"go-common/library/ecode\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\n\n\n\n\nfunc relations(c *bm.Context) {\n\tvar (\n\t\terr error\n\t\tmid, fid int64\n\t\tfids []int64\n\t\tparams = c.Request.Form\n\t\tmidStr = params.Get(\"mid\")\n\t\tfidsStr = params.Get(\"fids\")\n\t)\n\tif mid, err = strconv.ParseInt(midStr, 10, 64); err != nil {\n\t\tc.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\tfidsStrArr := strings.Split(fidsStr, \",\")\n\tfor _, v := range fidsStrArr {\n\t\tif fid, err = strconv.ParseInt(v, 10, 64); err != nil {\n\t\t\tc.JSON(nil, ecode.RequestErr)\n\t\t\treturn\n\t\t}\n\t\tfids = append(fids, fid)\n\t}\n\tc.JSON(relationSvc.Relations(c, mid, fids))\n}\n\nfunc relation(c *bm.Context) ", "output": "{\n\tvar (\n\t\terr error\n\t\tmid, fid int64\n\t\tparams = c.Request.Form\n\t\tmidStr = params.Get(\"mid\")\n\t\tfidStr = params.Get(\"fid\")\n\t)\n\tif mid, err = strconv.ParseInt(midStr, 10, 64); err != nil {\n\t\tc.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\tif fid, err = strconv.ParseInt(fidStr, 10, 64); err != nil {\n\t\tc.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\tc.JSON(relationSvc.Relation(c, mid, fid))\n}"} {"input": "package vm\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc newStack() *stack {\n\treturn &stack{}\n}\n\ntype stack struct {\n\tdata []*big.Int\n\tptr int\n}\n\nfunc (st *stack) push(d *big.Int) {\n\tstackItem := new(big.Int).Set(d)\n\tif len(st.data) > st.ptr {\n\t\tst.data[st.ptr] = stackItem\n\t} else {\n\t\tst.data = append(st.data, stackItem)\n\t}\n\tst.ptr++\n}\n\nfunc (st *stack) pop() (ret *big.Int) {\n\tst.ptr--\n\tret = st.data[st.ptr]\n\treturn\n}\n\n\n\nfunc (st *stack) swap(n int) {\n\tst.data[st.len()-n], st.data[st.len()-1] = st.data[st.len()-1], st.data[st.len()-n]\n}\n\nfunc (st *stack) dup(n int) {\n\tst.push(st.data[st.len()-n])\n}\n\nfunc (st *stack) peek() *big.Int {\n\treturn st.data[st.len()-1]\n}\n\nfunc (st *stack) require(n int) error {\n\tif st.len() < n {\n\t\treturn fmt.Errorf(\"stack underflow (%d <=> %d)\", len(st.data), n)\n\t}\n\treturn nil\n}\n\nfunc (st *stack) Print() {\n\tfmt.Println(\"### stack ###\")\n\tif len(st.data) > 0 {\n\t\tfor i, val := range st.data {\n\t\t\tfmt.Printf(\"%-3d %v\\n\", i, val)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"-- empty --\")\n\t}\n\tfmt.Println(\"#############\")\n}\n\nfunc (st *stack) len() int ", "output": "{\n\treturn st.ptr\n}"} {"input": "package safetime\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/sirupsen/logrus\"\n\t. \"gopkg.in/check.v1\"\n)\n\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\ntype SafetimeSuite struct {\n\tout *bytes.Buffer \n\tlogger *logrus.Entry\n}\n\nvar _ = Suite(&SafetimeSuite{})\n\nfunc (s *SafetimeSuite) SetUpTest(c *C) {\n\ts.out = &bytes.Buffer{}\n\tlogger := logrus.New()\n\tlogger.Out = s.out\n\ts.logger = logrus.NewEntry(logger)\n}\n\n\n\nfunc (s *SafetimeSuite) TestNonNegativeDuration(c *C) {\n\tpast := time.Now().Add(-10 * time.Second)\n\td, ok := TimeSinceSafe(past, s.logger)\n\n\tc.Assert(ok, Equals, true)\n\tc.Assert(d > time.Duration(0), Equals, true)\n\tc.Assert(len(s.out.String()) == 0, Equals, true)\n}\n\nfunc (s *SafetimeSuite) TestNegativeDuration(c *C) ", "output": "{\n\tfuture := time.Now().Add(time.Second)\n\td, ok := TimeSinceSafe(future, s.logger)\n\n\tc.Assert(ok, Equals, false)\n\tc.Assert(d, Equals, time.Duration(0))\n\tfmt.Println(s.out.String())\n\tc.Assert(strings.Contains(s.out.String(), \"BUG: negative duration\"), Equals, true)\n}"} {"input": "package graph\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gonum/graph\"\n\t\"github.com/gonum/graph/concrete\"\n\t\"github.com/gonum/graph/encoding/dot\"\n)\n\ntype Node struct {\n\tId int\n\tUniqueName string\n\tLabelName string\n\tColor string\n}\n\nfunc (n Node) ID() int {\n\treturn n.Id\n}\n\n\nfunc (n Node) DOTAttributes() []dot.Attribute {\n\tcolor := n.Color\n\tif len(color) == 0 {\n\t\tcolor = \"black\"\n\t}\n\n\treturn []dot.Attribute{\n\t\t{Key: \"label\", Value: fmt.Sprintf(\"%q\", n.LabelName)},\n\t\t{Key: \"color\", Value: color},\n\t}\n}\n\n\n\ntype MutableDirectedGraph struct {\n\t*concrete.DirectedGraph\n\n\tnodesByName map[string]graph.Node\n}\n\nfunc (g *MutableDirectedGraph) AddNode(n *Node) error {\n\tif _, exists := g.nodesByName[n.UniqueName]; exists {\n\t\treturn fmt.Errorf(\"node .UniqueName collision: %s\", n.UniqueName)\n\t}\n\n\tg.nodesByName[n.UniqueName] = n\n\tg.DirectedGraph.AddNode(n)\n\treturn nil\n}\n\nfunc (g *MutableDirectedGraph) NodeByName(name string) (graph.Node, bool) {\n\tn, exists := g.nodesByName[name]\n\treturn n, exists && g.DirectedGraph.Has(n)\n}\n\nfunc NewMutableDirectedGraph(g *concrete.DirectedGraph) *MutableDirectedGraph ", "output": "{\n\treturn &MutableDirectedGraph{\n\t\tDirectedGraph: concrete.NewDirectedGraph(),\n\t\tnodesByName: make(map[string]graph.Node),\n\t}\n}"} {"input": "package lock\n\nimport (\n\t\"os\"\n)\n\ntype LockedFile interface {\n\tFile() *os.File\n\tExclusive() bool\n\tClose() error\n}\n\ntype DefaultLockedFile struct {\n\tf *os.File\n\texclusive bool\n}\n\n\n\nfunc OpenShared(path string, flag int, perm os.FileMode) (LockedFile, error) {\n\treturn open(path, flag, perm, false)\n}\n\nfunc (e *DefaultLockedFile) File() *os.File {\n\treturn e.f\n}\n\nfunc (e *DefaultLockedFile) Exclusive() bool {\n\treturn e.exclusive\n}\n\nfunc (e *DefaultLockedFile) Close() error {\n\terr := e.unlock()\n\terr2 := e.f.Close()\n\tif err2 != nil && err == nil {\n\t\terr = err2\n\t}\n\treturn err\n}\n\nfunc OpenExclusive(path string, flag int, perm os.FileMode) (LockedFile, error) ", "output": "{\n\treturn open(path, flag, perm, true)\n}"} {"input": "package raft\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\tpb \"github.com/coreos/etcd/raft/raftpb\"\n)\n\ntype Status struct {\n\tID uint64\n\n\tpb.HardState\n\tSoftState\n\n\tApplied uint64\n\tProgress map[uint64]Progress\n}\n\n\nfunc getStatus(r *raft) Status {\n\ts := Status{ID: r.id}\n\ts.HardState = r.HardState\n\ts.SoftState = *r.softState()\n\n\ts.Applied = r.raftLog.applied\n\n\tif s.RaftState == StateLeader {\n\t\ts.Progress = make(map[uint64]Progress)\n\t\tfor id, p := range r.prs {\n\t\t\ts.Progress[id] = *p\n\t\t}\n\t}\n\n\treturn s\n}\n\n\nfunc (s Status) MarshalJSON() ([]byte, error) {\n\tj := fmt.Sprintf(`{\"id\":\"%x\",\"term\":%d,\"vote\":\"%x\",\"commit\":%d,\"lead\":\"%x\",\"raftState\":\"%s\",\"progress\":{`,\n\t\ts.ID, s.Term, s.Vote, s.Commit, s.Lead, s.RaftState)\n\n\tif len(s.Progress) == 0 {\n\t\tj += \"}}\"\n\t} else {\n\t\tfor k, v := range s.Progress {\n\t\t\tsubj := fmt.Sprintf(`\"%x\":{\"match\":%d,\"next\":%d,\"unreachable\":%t},`, k, v.Match, v.Next, v.Unreachable)\n\t\t\tj += subj\n\t\t}\n\t\tj = j[:len(j)-1] + \"}}\"\n\t}\n\treturn []byte(j), nil\n}\n\n\n\nfunc (s Status) String() string ", "output": "{\n\tb, err := s.MarshalJSON()\n\tif err != nil {\n\t\tlog.Panicf(\"unexpected error: %v\", err)\n\t}\n\treturn string(b)\n}"} {"input": "package risk\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestQueryNameList(t *testing.T) ", "output": "{\n\tvar req QueryNameListRequest\n\treq.Init()\n\treq.SetFormat(\"JSON\")\n\treq.SetRegionId(\"cn-shenzhen\")\n\tvar accessId = \"Ie65kUInu5GeAsma\"\n\tvar accessSecret = \"8cCqoxdYU9zKUihwXFXiN1HEACBDwB\"\n\tresp, err := QueryNameList(&req, accessId, accessSecret)\n\tif err != nil {\n\t\tt.Errorf(\"Error: %s\", err.Error())\n\t}\n\tfmt.Printf(\"Success: %v\\n\", resp)\n}"} {"input": "package repositories\n\nimport (\n\t\"errors\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/jhaldiman/decision-magic/models\"\n\t\"github.com/jhaldiman/decision-magic/services\"\n)\n\ntype (\n\tIUserRepository interface {\n\t\tCreate(user models.User) error\n\t\tAll() ([]models.User, error)\n\t\tExists(email string) (bool, error)\n\t\tGetByEmail(email string) (*models.User, error)\n\t\tDeleteByEmail(email string) error\n\t}\n\n\tuserRepository struct {\n\t\tservice services.IUserService\n\t}\n)\n\n\n\nfunc (u userRepository) All() ([]models.User, error) {\n\treturn u.service.All()\n}\n\nfunc (u userRepository) GetByEmail(email string) (*models.User, error) {\n\tkey := u.service.CreateKey(email)\n\treturn u.service.Get(key)\n}\n\nfunc (u userRepository) Exists(email string) (bool, error) {\n\tkey := u.service.CreateKey(email)\n\t_, err := u.service.Get(key)\n\n\tif err == nil {\n\t\treturn true, nil\n\t}\n\n\tif err.Error() == \"datastore: no such entity\" {\n\t\treturn false, nil\n\t}\n\n\treturn false, err\n}\n\nfunc (u userRepository) DeleteByEmail(email string) error {\n\tkey := u.service.CreateKey(email)\n\treturn u.service.Delete(key)\n}\n\n\nfunc NewUserRepository(ctx context.Context) (IUserRepository, error) {\n\tservice, err := services.NewUserService(ctx)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn userRepository{\n\t\tservice: service,\n\t}, nil\n}\n\nfunc (u userRepository) Create(user models.User) error ", "output": "{\n\texists, err := u.Exists(user.EmailAddress)\n\n\tif err != nil {\n\t\tif err.Error() != \"datastore: no such entity\" {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif exists {\n\t\treturn errors.New(\"That email address is already in use.\")\n\t}\n\n\t_, err = u.service.Upsert(user, nil)\n\n\treturn err\n}"} {"input": "package file\n\nimport (\n\t\"os/exec\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\nfunc Exec(cmd string, args ...string) (string, string, error) {\n\treturn ExecWithEnv(cmd, args, os.Environ())\n}\n\n\n\nfunc ExecWithEnv(cmd string, args []string, env []string) (string, string, error) ", "output": "{\n\tcommand := exec.Command(cmd, args...)\n\tcommand.Env = env\n\n\tcmdOut, _ := command.StdoutPipe()\n\tcmdErr, _ := command.StderrPipe()\n\n\terr := command.Start()\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tstdOutput, err := ioutil.ReadAll(cmdOut)\n\terrOutput, err := ioutil.ReadAll(cmdErr)\n\n\treturn string(stdOutput), string(errOutput), err\n}"} {"input": "package handler\n\nimport (\n \"net/http\"\n \"io/ioutil\"\n \"path/filepath\"\n \"log\"\n\n \"diserve.didactia.org/lib/util\"\n \"diserve.didactia.org/lib/env\"\n)\n\n\ntype Style struct {\n styles map[string][]byte\n}\n\nfunc (h *Style) ServeHTTP(res http.ResponseWriter, req *http.Request) {\n head, _ := util.ShiftPath(req.URL.Path)\n var data []byte\n var ok bool\n if env.Vars.PRELOADSTYLES {\n data, ok = h.styles[head]\n } else {\n data, ok = getStyle(head)\n }\n if ok {\n res.Header().Set(\"Content-Type\", \"text/css; charset=utf-8\")\n res.Write(data)\n } else {\n http.Error(res, \"Not Found\", http.StatusNotFound)\n }\n}\n\n\n\n\nfunc getStyles() map[string][]byte {\n styles := make(map[string][]byte)\n paths, err := filepath.Glob(env.Vars.STYLEPATH + \"*.css\")\n if err != nil {\n log.Fatal(err)\n }\n for _, path := range paths {\n filename := filepath.Base(path)\n bytes, err := ioutil.ReadFile(path)\n if err != nil {\n log.Fatal(err)\n }\n styles[filename] = bytes\n }\n return styles\n}\n\nfunc getStyle(filename string) ([]byte, bool) {\n bytes, err := ioutil.ReadFile(filepath.Join(env.Vars.STYLEPATH, filename))\n if err != nil {\n return nil, false\n }\n return bytes, true\n}\n\nfunc NewStyle() *Style ", "output": "{\n h := &Style{\n styles: nil,\n }\n if env.Vars.PRELOADSTYLES {\n h.styles = getStyles()\n }\n return h\n}"} {"input": "package references\n\nimport \"jvmgo/ch10/instructions/base\"\nimport \"jvmgo/ch10/rtda\"\nimport \"jvmgo/ch10/rtda/heap\"\n\n\ntype NEW struct{ base.Index16Instruction }\n\n\n\nfunc (self *NEW) Execute(frame *rtda.Frame) ", "output": "{\n\tcp := frame.Method().Class().ConstantPool()\n\tclassRef := cp.GetConstant(self.Index).(*heap.ClassRef)\n\tclass := classRef.ResolvedClass()\n\tif !class.InitStarted() {\n\t\tframe.RevertNextPC()\n\t\tbase.InitClass(frame.Thread(), class)\n\t\treturn\n\t}\n\n\tif class.IsInterface() || class.IsAbstract() {\n\t\tpanic(\"java.lang.InstantiationError\")\n\t}\n\n\tref := class.NewObject()\n\tframe.OperandStack().PushRef(ref)\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/lrusnac/dovpn/vpn\"\n\n\t\"github.com/digitalocean/godo\"\n\t\"github.com/lrusnac/dovpn/cmd\"\n\t\"golang.org/x/oauth2\"\n)\n\ntype tokenSource struct {\n\tAccessToken string\n}\n\n\n\nfunc main() {\n\tcmd.Execute()\n\n\tpat := \"aaaa\"\n\ttokenSource := &tokenSource{\n\t\tAccessToken: pat,\n\t}\n\toauthClient := oauth2.NewClient(context.Background(), tokenSource)\n\tclient := godo.NewClient(oauthClient)\n\n\terr := vpn.NewVpnInstance(client)\n\tif err != nil {\n\t\tfmt.Printf(\"error creating the vpn instance: %v\\n\", err)\n\t}\n\n\tdropletID, err := vpn.FindVpnInstance(client)\n\tif err != nil {\n\t\tfmt.Printf(\"error finding the vpn instance: %v\\n\", err)\n\t}\n\tfmt.Printf(\"found droplet: %d\\n\", dropletID)\n\n\terr = vpn.DropVpnInstance(client)\n\tif err != nil {\n\t\tfmt.Printf(\"error destroying the vpn instance: %v\\n\", err)\n\t}\n}\n\nfunc (t *tokenSource) Token() (*oauth2.Token, error) ", "output": "{\n\ttoken := &oauth2.Token{\n\t\tAccessToken: t.AccessToken,\n\t}\n\treturn token, nil\n}"} {"input": "package iso20022\n\n\ntype AuthorisationResult5 struct {\n\n\tAuthorisationEntity *GenericIdentification70 `xml:\"AuthstnNtty,omitempty\"`\n\n\tResponseToAuthorisation *ResponseType1 `xml:\"RspnToAuthstn\"`\n\n\tAuthorisationCode *Min6Max8Text `xml:\"AuthstnCd,omitempty\"`\n}\n\nfunc (a *AuthorisationResult5) AddAuthorisationEntity() *GenericIdentification70 {\n\ta.AuthorisationEntity = new(GenericIdentification70)\n\treturn a.AuthorisationEntity\n}\n\nfunc (a *AuthorisationResult5) AddResponseToAuthorisation() *ResponseType1 {\n\ta.ResponseToAuthorisation = new(ResponseType1)\n\treturn a.ResponseToAuthorisation\n}\n\n\n\nfunc (a *AuthorisationResult5) SetAuthorisationCode(value string) ", "output": "{\n\ta.AuthorisationCode = (*Min6Max8Text)(&value)\n}"} {"input": "package gorma_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/goadesign/gorma\"\n)\n\n\n\nfunc TestStorageGroupDSL(t *testing.T) {\n\tsg := &gorma.StorageGroupDefinition{}\n\tf := func() {\n\t\treturn\n\t}\n\tsg.DefinitionDSL = f\n\tc := sg.DSL()\n\tif c == nil {\n\t\tt.Errorf(\"Expected %T, got nil\", f)\n\t}\n\n}\n\nfunc TestStorageGroupContext(t *testing.T) ", "output": "{\n\tsg := &gorma.StorageGroupDefinition{}\n\tsg.Name = \"SG\"\n\n\tc := sg.Context()\n\texp := fmt.Sprintf(\"StorageGroup %#v\", sg.Name)\n\tif c != exp {\n\t\tt.Errorf(\"Expected %s, got %s\", exp, c)\n\t}\n\n\tsg.Name = \"\"\n\n\tc = sg.Context()\n\texp = \"unnamed Storage Group\"\n\tif c != exp {\n\t\tt.Errorf(\"Expected %s, got %s\", exp, c)\n\t}\n}"} {"input": "package main\n\nimport \"code.google.com/p/go-tour/tree\"\nimport \"fmt\"\n\nfunc walk(t *tree.Tree, ch chan int){\n if t != nil {\n walk(t.Left, ch)\n ch <- t.Value\n \twalk(t.Right, ch)\n }\n \n}\n\n\n\nfunc Walk(t *tree.Tree, ch chan int){\n\twalk(t, ch)\n close(ch)\n}\n\n\n\n\n\nfunc main() {\n ch := make(chan int)\n \n go Walk(tree.New(1), ch)\n \n for i := range ch {\n fmt.Println(i)\n }\n \n fmt.Println(Same(tree.New(1), tree.New(1)))\n fmt.Println(Same(tree.New(1), tree.New(2)))\n}\n\nfunc Same(t1, t2 *tree.Tree) bool ", "output": "{\n ch1 := make(chan int)\n ch2 := make(chan int)\n \n go Walk(t1, ch1)\n go Walk(t2, ch2)\n \n for i := range ch1 { \n\t\tif i != <- ch2 {\n \t\t\treturn false\n }\n }\n return true\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\n\tfmt.Println(\"Launching server...\")\n\tfor {\n\t\tconnect()\n\n\t\ttime.Sleep(5 * time.Second)\n\t}\n}\n\nfunc connect() int {\n\n\tfmt.Println(\"Listening port 8081\")\n\n\tln, _ := net.Listen(\"tcp\", \":8081\")\n\n\tconn, _ := ln.Accept()\n\n\thandleConnection(conn)\n\n\treturn 0\n\n} \n\n\n\nfunc handleConnection(conn net.Conn) int ", "output": "{\n\n\tconnbuf := bufio.NewReader(conn)\n\n\tfor {\n\t\tmessage, err := connbuf.ReadString('\\n')\n\n\t\tif err != nil {\n\t\t\treturn 0\n\t\t}\n\t\tfmt.Println(\"Message Received:\", string(message), \"Error:\", err, \"\\n\")\n\n\t\tnewmessage := strings.ToUpper(message)\n\n\t\tconn.Write([]byte(newmessage + \"\\n\"))\n\t}\n\n}"} {"input": "package cmd\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestEnvDiff(t *testing.T) {\n\tdiff := &EnvDiff{map[string]string{\"FOO\": \"bar\"}, map[string]string{\"BAR\": \"baz\"}}\n\n\tout := diff.Serialize()\n\n\tdiff2, err := LoadEnvDiff(out)\n\tif err != nil {\n\t\tt.Error(\"parse error\", err)\n\t}\n\n\tif len(diff2.Prev) != 1 {\n\t\tt.Error(\"len(diff2.prev) != 1\", len(diff2.Prev))\n\t}\n\n\tif len(diff2.Next) != 1 {\n\t\tt.Error(\"len(diff2.next) != 0\", len(diff2.Next))\n\t}\n}\n\n\n\n\n\nfunc TestIgnoredEnv(t *testing.T) {\n\tif !IgnoredEnv(DIRENV_BASH) {\n\t\tt.Fail()\n\t}\n\tif IgnoredEnv(DIRENV_DIFF) {\n\t\tt.Fail()\n\t}\n\tif !IgnoredEnv(\"_\") {\n\t\tt.Fail()\n\t}\n\tif !IgnoredEnv(\"__fish_foo\") {\n\t\tt.Fail()\n\t}\n\tif !IgnoredEnv(\"__fishx\") {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestEnvDiffEmptyValue(t *testing.T) ", "output": "{\n\tbefore := Env{}\n\tafter := Env{\"FOO\": \"\"}\n\n\tdiff := BuildEnvDiff(before, after)\n\n\tif !reflect.DeepEqual(diff.Next, map[string]string(after)) {\n\t\tt.Errorf(\"diff.Next != after (%#+v != %#+v)\", diff.Next, after)\n\t}\n}"} {"input": "package goapp\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestEq(t *testing.T) {\n\tt.Parallel()\n\n\teqHelper(t, true, 1, 1)\n\teqHelper(t, true, 1, 1, 1)\n\teqHelper(t, false, 1, 1, 3)\n\teqHelper(t, false, 1, 2)\n\teqHelper(t, false, 1, 2, 3)\n}\n\nfunc eqHelper(t *testing.T, expectedEq bool, args ...interface{}) ", "output": "{\n\tif expectedEq {\n\t\tif !eq(args...) {\n\t\t\tt.Errorf(\"Expected %v to be equal, got false\", args)\n\t\t}\n\t} else {\n\t\tif eq(args...) {\n\t\t\tt.Errorf(\"Expected %v to not be equal, got true\", args)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\n\ntype printable interface {\n print()\n}\n\nfunc use(printables []printable) {\n for _, p := range printables {\n p.print()\n fmt.Println()\n }\n}\n\ntype human struct {\n name string\n age int\n}\n\n\n\n\n\n\ntype account struct {\n bank string\n balance int\n}\n\nfunc (a account) print() {\n fmt.Printf(\"[%v] %d\", a.bank, a.balance)\n}\n\nfunc main() {\n accounts := []account {\n {\"Bank of America\", 1000},\n {\"Chase\", 500},\n }\n humans := []human {\n {\"Steve\", 30},\n {\"Katie\", 28},\n {\"John\", 23},\n }\n printables := make([]printable, 0, len(accounts) + len(humans))\n for _, acc := range accounts {\n printables = append(printables, acc)\n }\n for i := range humans {\n \n \n \n printables = append(printables, &humans[i])\n }\n use(printables)\n}\n\nfunc (h *human) print() ", "output": "{\n fmt.Printf(\"%v.%d\", h.name, h.age)\n}"} {"input": "package seqnum\n\n\ntype Value uint32\n\n\ntype Size uint32\n\n\nfunc (v Value) LessThan(w Value) bool {\n\treturn int32(v-w) < 0\n}\n\n\nfunc (v Value) LessThanEq(w Value) bool {\n\tif v == w {\n\t\treturn true\n\t}\n\treturn v.LessThan(w)\n}\n\n\n\n\n\n\nfunc (v Value) InWindow(first Value, size Size) bool {\n\treturn v.InRange(first, first.Add(size))\n}\n\n\nfunc Overlap(a Value, b Size, x Value, y Size) bool {\n\treturn a.LessThan(x.Add(y)) && x.LessThan(a.Add(b))\n}\n\n\nfunc (v Value) Add(s Size) Value {\n\treturn v + Value(s)\n}\n\n\nfunc (v Value) Size(w Value) Size {\n\treturn Size(w - v)\n}\n\n\nfunc (v *Value) UpdateForward(s Size) {\n\t*v += Value(s)\n}\n\nfunc (v Value) InRange(a, b Value) bool ", "output": "{\n\treturn v-a < b-a\n}"} {"input": "package resttk\n\ntype ResourceInterface interface {\n\tFindAllResources(v interface{}) interface{}\n\tFindResource(key string, value string, v interface{}) interface{}\n\tSaveResource(key string, value string, v interface{}) interface{}\n\tUpdateResource(key string, value string, v interface{}) interface{}\n\tDeleteResource(key string, value string) bool\n}\n\ntype BaseResource struct {\n\tparent ResourceInterface\n}\n\nfunc (r *BaseResource) Init(p ResourceInterface) {\n\tr.parent = p\n}\n\nfunc (r *BaseResource) FindAllResources(v interface{}) interface{} {\n\tresources := r.parent.FindAllResources(v)\n\tif resources != nil {\n\t\treturn resources\n\t}\n\n\treturn nil\n}\n\nfunc (r *BaseResource) FindResource(key string, value string, v interface{}) interface{} {\n\tresource := r.parent.FindResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn nil\n}\n\nfunc (r *BaseResource) SaveResource(key string, value string, v interface{}) interface{} {\n\tresource := r.parent.FindResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn nil\n}\n\nfunc (r *BaseResource) UpdateResource(key string, value string, v interface{}) interface{} {\n\tresource := r.parent.UpdateResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (r *BaseResource) DeleteResource(key string, value string) bool ", "output": "{\n\treturn r.parent.DeleteResource(key, value)\n}"} {"input": "package grpc_ctxtags_test\n\nimport (\n\t\"github.com/grpc-ecosystem/go-grpc-middleware/tags\"\n\t\"google.golang.org/grpc\"\n)\n\n\nfunc Example_initialization() {\n\topts := []grpc_ctxtags.Option{\n\t\tgrpc_ctxtags.WithFieldExtractor(grpc_ctxtags.TagBasedRequestFieldExtractor(\"log_fields\")),\n\t}\n\t_ = grpc.NewServer(\n\t\tgrpc.StreamInterceptor(grpc_ctxtags.StreamServerInterceptor(opts...)),\n\t\tgrpc.UnaryInterceptor(grpc_ctxtags.UnaryServerInterceptor(opts...)),\n\t)\n}\n\n\n\n\nfunc Example_initialisationWithOptions() ", "output": "{\n\topts := []grpc_ctxtags.Option{\n\t\tgrpc_ctxtags.WithFieldExtractorForInitialReq(grpc_ctxtags.TagBasedRequestFieldExtractor(\"log_fields\")),\n\t}\n\t_ = grpc.NewServer(\n\t\tgrpc.StreamInterceptor(grpc_ctxtags.StreamServerInterceptor(opts...)),\n\t\tgrpc.UnaryInterceptor(grpc_ctxtags.UnaryServerInterceptor(opts...)),\n\t)\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/bfontaine/stargazer/Godeps/_workspace/src/github.com/nlopes/slack\"\n\t\"github.com/bfontaine/stargazer/Godeps/_workspace/src/github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestStarNotification(t *testing.T) ", "output": "{\n\ts := Star{\n\t\tAdded: true,\n\t\tUser: \"U123\",\n\t\tTimestamp: \"1401\",\n\t\tMessage: Message{\n\t\t\tUser: \"U321\",\n\t\t\tChannel: \"C123\",\n\t\t\tText: \"yo\",\n\t\t\tTimestamp: \"1400\",\n\t\t},\n\t}\n\n\tslackInfo = &slack.Info{\n\t\tTeam: &slack.Team{\n\t\t\tName: \"yolo\",\n\t\t\tDomain: \"yoloo\",\n\t\t},\n\t}\n\n\tn, err := s.notification()\n\tassert.Nil(t, err)\n\n\tassert.Equal(t,\n\t\t\"@usernameU123 just starred your message in #channelC123: https://yoloo.slack.com/archives/channelC123/p1400\",\n\t\tn)\n}"} {"input": "package service\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"github.com/oikomi/FishChatServer2/http_server/user-api/model\"\n\tauthRpc \"github.com/oikomi/FishChatServer2/http_server/user-api/rpc\"\n\t\"github.com/oikomi/FishChatServer2/protocol/rpc\"\n)\n\ntype Service struct {\n\trpcClient *authRpc.RPCClient\n}\n\nfunc New() (service *Service, err error) {\n\trpcClient, err := authRpc.NewRPCClient()\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn\n\t}\n\tservice = &Service{\n\t\trpcClient: rpcClient,\n\t}\n\treturn\n}\n\nfunc (s *Service) Auth(uid int64, pw string) (loginModel *model.Login, err error) {\n\trgAuthReq := &rpc.RGAuthReq{\n\t\tUID: uid,\n\t}\n\tres, err := s.rpcClient.Register.Auth(rgAuthReq)\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn\n\t}\n\tloginModel = &model.Login{\n\t\tToken: res.Token,\n\t}\n\treturn\n}\n\n\n\nfunc (s *Service) Register(uid int64, userName, pw string) (err error) ", "output": "{\n\trgRegisterReq := &rpc.RGRegisterReq{\n\t\tUID: uid,\n\t\tName: userName,\n\t\tPassword: pw,\n\t}\n\t_, err = s.rpcClient.Register.Register(rgRegisterReq)\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn\n\t}\n\treturn\n}"} {"input": "package couchdb\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\n\t\"github.com/flimzy/kivik\"\n\t\"github.com/flimzy/kivik/driver\"\n)\n\ntype session struct {\n\tData json.RawMessage\n\tInfo authInfo `json:\"info\"`\n\tUserCtx userContext `json:\"userCtx\"`\n}\n\ntype authInfo struct {\n\tAuthenticationMethod string `json:\"authenticated\"`\n\tAuthenticationDB string `json:\"authentiation_db\"`\n\tAuthenticationHandlers []string `json:\"authentication_handlers\"`\n}\n\ntype userContext struct {\n\tName string `json:\"name\"`\n\tRoles []string `json:\"roles\"`\n}\n\n\n\nfunc (c *client) Session(ctx context.Context) (*driver.Session, error) {\n\ts := &session{}\n\t_, err := c.DoJSON(ctx, kivik.MethodGet, \"/_session\", nil, s)\n\treturn &driver.Session{\n\t\tRawResponse: s.Data,\n\t\tName: s.UserCtx.Name,\n\t\tRoles: s.UserCtx.Roles,\n\t\tAuthenticationMethod: s.Info.AuthenticationMethod,\n\t\tAuthenticationDB: s.Info.AuthenticationDB,\n\t\tAuthenticationHandlers: s.Info.AuthenticationHandlers,\n\t}, err\n}\n\nfunc (s *session) UnmarshalJSON(data []byte) error ", "output": "{\n\ttype alias session\n\tvar a alias\n\tif err := json.Unmarshal(data, &a); err != nil {\n\t\treturn err\n\t}\n\t*s = session(a)\n\ts.Data = data\n\treturn nil\n}"} {"input": "package unix\n\nimport \"syscall\"\n\nfunc setTimespec(sec, nsec int64) Timespec {\n\treturn Timespec{Sec: int32(sec), Nsec: int32(nsec)}\n}\n\nfunc setTimeval(sec, usec int64) Timeval {\n\treturn Timeval{Sec: int32(sec), Usec: int32(usec)}\n}\n\n\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint32(length)\n}\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\nfunc (msghdr *Msghdr) SetIovlen(length int) {\n\tmsghdr.Iovlen = int32(length)\n}\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\nfunc Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) ", "output": "{\n\tk.Ident = uint32(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}"} {"input": "package socketio\n\nimport \"errors\"\n\n\ntype BroadcastAdaptor interface {\n\n\tJoin(room string, socket Socket) error\n\n\tLeave(room string, socket Socket) error\n\n\tSend(ignore Socket, room, event string, args ...interface{}) error\n\n\tGetAllClients(room string) (map[string]Socket, error)\n}\n\nvar newBroadcast = newBroadcastDefault\n\ntype Broadcast map[string]map[string]Socket\n\nfunc newBroadcastDefault() BroadcastAdaptor {\n\treturn make(Broadcast)\n}\n\nfunc (b Broadcast) Join(room string, socket Socket) error {\n\tsockets, ok := b[room]\n\tif !ok {\n\t\tsockets = make(map[string]Socket)\n\t}\n\tsockets[socket.Id()] = socket\n\tb[room] = sockets\n\treturn nil\n}\n\n\n\nfunc (b Broadcast) Send(ignore Socket, room, event string, args ...interface{}) error {\n\tsockets := b[room]\n\tfor id, s := range sockets {\n\t\tif ignore != nil && ignore.Id() == id {\n\t\t\tcontinue\n\t\t}\n\t\ts.Emit(event, args...)\n\t}\n\treturn nil\n}\n\nfunc (b Broadcast) GetAllClients(room string) (map[string]Socket, error) {\n\tsockets, ok := b[room]\n\tif !ok {\n\t\treturn nil, errors.New(\"没有此房间\")\n\t}\n\treturn sockets, nil\n}\n\nfunc (b Broadcast) Leave(room string, socket Socket) error ", "output": "{\n\tsockets, ok := b[room]\n\tif !ok {\n\t\treturn nil\n\t}\n\tdelete(sockets, socket.Id())\n\tif len(sockets) == 0 {\n\t\tdelete(b, room)\n\t\treturn nil\n\t}\n\tb[room] = sockets\n\treturn nil\n}"} {"input": "package v1alpha1\n\nimport (\n\t\"sort\"\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n)\n\n\n\nfunc TestTransmissionRiskVectorSort(t *testing.T) {\n\tt.Parallel()\n\n\tgot := TransmissionRiskVector{\n\t\t{0, 0},\n\t\t{3, 100},\n\t\t{5, 200},\n\t}\n\tsort.Sort(got)\n\n\twant := TransmissionRiskVector{{5, 200}, {3, 100}, {0, 0}}\n\n\tif diff := cmp.Diff(want, got); diff != \"\" {\n\t\tt.Errorf(\"sort(TransmissionRiskVector) mismatch (-want +got):\\n%v\", diff)\n\t}\n}\n\nfunc TestNewVerificationClaims(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\tgot := NewVerificationClaims()\n\twant := &VerificationClaims{\n\t\tTransmissionRisks: []TransmissionRiskOverride{},\n\t}\n\n\tif diff := cmp.Diff(want, got); diff != \"\" {\n\t\tt.Errorf(\"mismatch (-want +got):\\n%v\", diff)\n\t}\n}"} {"input": "package archive\n\nimport (\n\t\"archive/tar\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/docker/docker/pkg/longpath\"\n)\n\n\n\nfunc fixVolumePathPrefix(srcPath string) string {\n\treturn longpath.AddPrefix(srcPath)\n}\n\n\n\nfunc getWalkRoot(srcPath string, include string) string {\n\treturn filepath.Join(srcPath, include)\n}\n\n\n\n\nfunc CanonicalTarNameForPath(p string) (string, error) {\n\tif strings.Contains(p, \"/\") {\n\t\treturn \"\", fmt.Errorf(\"Windows path contains forward slash: %s\", p)\n\t}\n\treturn strings.Replace(p, string(os.PathSeparator), \"/\", -1), nil\n\n}\n\n\n\nfunc chmodTarEntry(perm os.FileMode) os.FileMode {\n\tperm &= 0755\n\tperm |= 0111\n\n\treturn perm\n}\n\nfunc setHeaderForSpecialDevice(hdr *tar.Header, ta *tarAppender, name string, stat interface{}) (nlink uint32, inode uint64, err error) {\n\treturn\n}\n\n\n\n\n\nfunc handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error {\n\treturn nil\n}\n\nfunc getFileUIDGID(stat interface{}) (int, int, error) {\n\treturn 0, 0, nil\n}\n\nfunc handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error ", "output": "{\n\treturn nil\n}"} {"input": "package fs\n\nimport (\n\t\"github.com/opencontainers/runc/libcontainer/cgroups\"\n\t\"github.com/opencontainers/runc/libcontainer/cgroups/fscommon\"\n\t\"github.com/opencontainers/runc/libcontainer/configs\"\n)\n\ntype NetPrioGroup struct {\n}\n\nfunc (s *NetPrioGroup) Name() string {\n\treturn \"net_prio\"\n}\n\n\n\nfunc (s *NetPrioGroup) Set(path string, r *configs.Resources) error {\n\tfor _, prioMap := range r.NetPrioIfpriomap {\n\t\tif err := fscommon.WriteFile(path, \"net_prio.ifpriomap\", prioMap.CgroupString()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (s *NetPrioGroup) GetStats(path string, stats *cgroups.Stats) error {\n\treturn nil\n}\n\nfunc (s *NetPrioGroup) Apply(path string, d *cgroupData) error ", "output": "{\n\treturn join(path, d.pid)\n}"} {"input": "package css\n\n\n\n\nfunc bruteForce(nums []int, k int) bool {\n\tn := len(nums)\n\tif n < 2 {\n\t\treturn false\n\t}\n\tvar sum int\n\tfor i := range nums {\n\t\tsum = 0\n\t\tfor j := i; j < n; j++ {\n\t\t\tsum += nums[j]\n\t\t\tif sum == k || (k != 0 && sum%k == 0) {\n\t\t\t\tif j > i {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc preSumHash(nums []int, k int) bool {\n\tn := len(nums)\n\tif n < 2 {\n\t\treturn false\n\t}\n\thash := make(map[int]int, n)\n\thash[0] = -1\n\tvar sum int\n\tfor i := range nums {\n\t\tsum += nums[i]\n\t\tif k != 0 {\n\t\t\tsum %= k\n\t\t}\n\t\tif v, exists := hash[sum]; exists {\n\t\t\tif i-v > 1 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t} else {\n\t\t\thash[sum] = i\n\t\t}\n\t}\n\treturn false\n}\n\nfunc checkSubArraySum(nums []int, k int) bool ", "output": "{\n\treturn bruteForce(nums, k)\n}"} {"input": "package models\n\nimport (\n\t\"time\"\n)\n\n\nconst (\n\tVolumePaper = \"paperbook\"\n\tVolumeElectro = \"ebook\"\n\tVolumeAudio = \"audiobook\"\n)\n\n\n\n\n\nfunc CheckVolume(volume string) bool {\n\tswitch volume {\n\tcase VolumePaper:\n\tcase VolumeElectro:\n\tcase VolumeAudio:\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}\n\n\n\n\n\ntype Volume struct {\n\tID int32 `reform:\"id,pk\"`\n\tBookID int32 `reform:\"book_id\"`\n\tType string `reform:\"type\"`\n\tCreatedAt time.Time `reform:\"created_at\"`\n\tUpdatedAt time.Time `reform:\"updated_at\"`\n}\n\n\nfunc (v *Volume) BeforeInsert() error {\n\tv.CreatedAt = time.Now().UTC().Truncate(time.Second)\n\tv.UpdatedAt = v.CreatedAt\n\treturn nil\n}\n\n\nfunc (v *Volume) BeforeUpdate() error {\n\tv.UpdatedAt = time.Now().UTC().Truncate(time.Second)\n\treturn nil\n}\n\nfunc GetVolumes() []string ", "output": "{\n\tvolumes := []string{VolumeAudio, VolumeElectro, VolumePaper}\n\treturn volumes\n}"} {"input": "package whatever\n\nimport \"testing\"\n\n\n\nfunc Test2(t *testing.T) {\n}\n\nfunc Test1(t *testing.T) ", "output": "{\n\tt.Fail()\n}"} {"input": "package incoming\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\nvar (\n\t_InKindNameToValue = map[string]InKind{\n\t\t\"control\": control,\n\t\t\"state\": state,\n\t\t\"checkForUpdates\": checkForUpdates,\n\t\t\"updateAvailable\": updateAvailable,\n\t\t\"updateBegin\": updateBegin,\n\t\t\"updateApply\": updateApply,\n\t}\n\n\t_InKindValueToName = map[InKind]string{\n\t\tcontrol: \"control\",\n\t\tstate: \"state\",\n\t\tcheckForUpdates: \"checkForUpdates\",\n\t\tupdateAvailable: \"updateAvailable\",\n\t\tupdateBegin: \"updateBegin\",\n\t\tupdateApply: \"updateApply\",\n\t}\n)\n\n\n\n\nfunc (r InKind) MarshalJSON() ([]byte, error) {\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn json.Marshal(s.String())\n\t}\n\ts, ok := _InKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid InKind: %d\", r)\n\t}\n\treturn json.Marshal(s)\n}\n\n\nfunc (r *InKind) UnmarshalJSON(data []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\treturn fmt.Errorf(\"InKind should be a string, got %s\", data)\n\t}\n\tv, ok := _InKindNameToValue[s]\n\tif !ok {\n\t\treturn fmt.Errorf(\"invalid InKind %q\", s)\n\t}\n\t*r = v\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tvar v InKind\n\tif _, ok := interface{}(v).(fmt.Stringer); ok {\n\t\t_InKindNameToValue = map[string]InKind{\n\t\t\tinterface{}(control).(fmt.Stringer).String(): control,\n\t\t\tinterface{}(state).(fmt.Stringer).String(): state,\n\t\t\tinterface{}(checkForUpdates).(fmt.Stringer).String(): checkForUpdates,\n\t\t\tinterface{}(updateAvailable).(fmt.Stringer).String(): updateAvailable,\n\t\t\tinterface{}(updateBegin).(fmt.Stringer).String(): updateBegin,\n\t\t\tinterface{}(updateApply).(fmt.Stringer).String(): updateApply,\n\t\t}\n\t}\n}"} {"input": "package notary\n\nimport (\n\t\"crypto\"\n\t_ \"crypto/md5\"\n)\n\n\n\n\n\n\nfunc FIPSEnabled() bool ", "output": "{\n\treturn !crypto.MD5.Available()\n}"} {"input": "package policy\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestEffectIsValid(t *testing.T) {\n\ttestCases := []struct {\n\t\teffect Effect\n\t\texpectedResult bool\n\t}{\n\t\t{Allow, true},\n\t\t{Deny, true},\n\t\t{Effect(\"\"), false},\n\t\t{Effect(\"foo\"), false},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tresult := testCase.effect.IsValid()\n\n\t\tif result != testCase.expectedResult {\n\t\t\tt.Fatalf(\"case %v: expected: %v, got: %v\\n\", i+1, testCase.expectedResult, result)\n\t\t}\n\t}\n}\n\nfunc TestEffectIsAllowed(t *testing.T) ", "output": "{\n\ttestCases := []struct {\n\t\teffect Effect\n\t\tcheck bool\n\t\texpectedResult bool\n\t}{\n\t\t{Allow, false, false},\n\t\t{Allow, true, true},\n\t\t{Deny, false, true},\n\t\t{Deny, true, false},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tresult := testCase.effect.IsAllowed(testCase.check)\n\n\t\tif result != testCase.expectedResult {\n\t\t\tt.Fatalf(\"case %v: expected: %v, got: %v\\n\", i+1, testCase.expectedResult, result)\n\t\t}\n\t}\n\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n)\n\nfunc main() {\n\tuid := flag.Int64(\"uid\", -1, \"uid to run process as\")\n\tgid := flag.Int64(\"gid\", -1, \"gid to run process as\")\n\tflag.Parse()\n\tif *uid == -1 {\n\t\tfmt.Println(\"please pass the --uid flag\")\n\t\tos.Exit(1)\n\t}\n\tif *gid == -1 {\n\t\tfmt.Println(\"please pass the --gid flag\")\n\t\tos.Exit(1)\n\t}\n\n\tif err := syscall.Setgroups([]int{}); err != nil {\n\t\tmust(\"setgroups\", err)\n\t}\n\t_, _, err := syscall.Syscall(syscall.SYS_SETGID, uintptr(*gid), 0, 0)\n\tif err != 0 {\n\t\tmust(\"setgid\", err)\n\t}\n\t_, _, err = syscall.Syscall(syscall.SYS_SETUID, uintptr(*uid), 0, 0)\n\tif err != 0 {\n\t\tmust(\"setuid\", err)\n\t}\n\n\tcmdArgv := flag.Args()\n\tmust(\"exec\", syscall.Exec(cmdArgv[0], cmdArgv, os.Environ()))\n\tpanic(\"unreachable\")\n}\n\n\n\nfunc must(action string, err error) ", "output": "{\n\tif err != nil {\n\t\tfmt.Printf(\"error %s: %s\\n\", action, err)\n\t\tos.Exit(1)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/julienschmidt/httprouter\"\n)\n\n\n\nfunc Ping(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) ", "output": "{\n\tdefer PanicCatcher(w)\n\n\tw.Header().Set(`X-Powered-By`, `SOMA Configuration System`)\n\tw.Header().Set(`X-Version`, SomaVersion)\n\tswitch {\n\tcase SomaCfg.Observer == true:\n\t\tw.Header().Set(`X-SOMA-Mode`, `Observer`)\n\tcase SomaCfg.ReadOnly == true:\n\t\tw.Header().Set(`X-SOMA-Mode`, `ReadOnly`)\n\tcase SomaCfg.ReadOnly == false:\n\t\tw.Header().Set(`X-SOMA-Mode`, `Master`)\n\t}\n\tw.WriteHeader(http.StatusNoContent)\n}"} {"input": "package funk\n\n\n\nfunc ShortIf(condition bool, a interface{}, b interface{}) interface{} ", "output": "{\n\tif condition {\n\t\treturn a\n\t}\n\treturn b\n}"} {"input": "package irc\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"sync\"\n)\n\ntype Decoder struct {\n\trdr *bufio.Reader\n\t*sync.Mutex\n}\n\n\n\n\nfunc (d *Decoder) Decode(msg *Msg) (err error) {\n\td.Lock()\n\tdefer d.Unlock()\n\n\tvar line []byte\n\tline, _, err = d.rdr.ReadLine()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tmsg.Reset()\n\tmsg.Data = line[:]\n\treturn msg.PeekCmd()\n}\n\nfunc NewDecoder(r io.Reader) *Decoder ", "output": "{\n\trdr := bufio.NewReader(r)\n\treturn &Decoder{rdr, &sync.Mutex{}}\n}"} {"input": "package vault\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\ntype AuthType interface {\n\tDescribe() string\n\tGetType() string\n\tgetAuthConfig() map[string]interface{}\n\tgetAuthMountConfig() map[string]interface{}\n\tConfigure(c *VCClient) error\n\tTuneMount(c *VCClient, path string) error\n\tWriteUsers(c *VCClient) error\n\tWriteGroups(c *VCClient) error\n}\n\n\nfunc (c *VCClient) AuthExist(name string) bool {\n\tauth, err := c.Sys().ListAuth()\n\tif err != nil {\n\t\treturn false\n\t}\n\tfor a := range auth {\n\t\tif strings.TrimSuffix(a, \"/\") == name {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\nfunc Path(a AuthType) string {\n\treturn fmt.Sprintf(\"auth/%s\", a.GetType())\n}\n\n\nfunc (c *VCClient) AuthEnable(a AuthType) error {\n\tif err := c.Sys().EnableAuth(a.GetType(), a.GetType(), a.Describe()); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc EnableAndConfigure(a AuthType, c *VCClient) error {\n\tif !c.AuthExist(a.GetType()) {\n\t\tif err := c.AuthEnable(a); err != nil {\n\t\t\treturn fmt.Errorf(\"Error enabling auth mount: %v\", err)\n\t\t}\n\t}\n\tif err := c.AuthConfigure(a); err != nil {\n\t\treturn fmt.Errorf(\"Error configuring auth mount: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (c *VCClient) AuthConfigure(a AuthType) error ", "output": "{\n\tif err := a.WriteUsers(c); err != nil {\n\t\treturn err\n\t}\n\tif err := a.WriteGroups(c); err != nil {\n\t\treturn err\n\t}\n\tif err := a.TuneMount(c, Path(a)); err != nil {\n\t\treturn err\n\t}\n\n\tif err := a.Configure(c); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package resourcemanager\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteTemplateRequest struct {\n\n\tTemplateId *string `mandatory:\"true\" contributesTo:\"path\" name:\"templateId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteTemplateRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request DeleteTemplateRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request DeleteTemplateRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteTemplateResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteTemplateResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteTemplateResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteTemplateRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package util\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/bborbe/assert\"\n)\n\n\n\nfunc TestNormalizePath(t *testing.T) {\n\tdir, err := NormalizePath(\"/tmp\")\n\tif err := AssertThat(err, NilValue()); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := AssertThat(dir, Is(\"/tmp\")); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestIsDirectory(t *testing.T) ", "output": "{\n\tisDir, err := IsDirectory(\"/tmp\")\n\tif err := AssertThat(err, NilValue()); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := AssertThat(isDir, Is(true)); err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package replication\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\tclient \"k8s.io/kubernetes/pkg/client/unversioned\"\n)\n\n\nfunc updateReplicaCount(rcClient client.ReplicationControllerInterface, controller api.ReplicationController, numReplicas int) (updateErr error) {\n\tif controller.Status.Replicas == numReplicas &&\n\t\tcontroller.Generation == controller.Status.ObservedGeneration {\n\t\treturn nil\n\t}\n\tgeneration := controller.Generation\n\n\tvar getErr error\n\tfor i, rc := 0, &controller; ; i++ {\n\t\tglog.V(4).Infof(\"Updating replica count for rc: %v, %d->%d (need %d), sequence No: %v->%v\",\n\t\t\tcontroller.Name, controller.Status.Replicas, numReplicas, controller.Spec.Replicas, controller.Status.ObservedGeneration, generation)\n\n\t\trc.Status = api.ReplicationControllerStatus{Replicas: numReplicas, ObservedGeneration: generation}\n\t\t_, updateErr = rcClient.UpdateStatus(rc)\n\t\tif updateErr == nil || i >= statusUpdateRetries {\n\t\t\treturn updateErr\n\t\t}\n\t\tif rc, getErr = rcClient.Get(controller.Name); getErr != nil {\n\t\t\treturn getErr\n\t\t}\n\t}\n}\n\n\ntype OverlappingControllers []api.ReplicationController\n\n\nfunc (o OverlappingControllers) Swap(i, j int) { o[i], o[j] = o[j], o[i] }\n\nfunc (o OverlappingControllers) Less(i, j int) bool {\n\tif o[i].CreationTimestamp.Equal(o[j].CreationTimestamp) {\n\t\treturn o[i].Name < o[j].Name\n\t}\n\treturn o[i].CreationTimestamp.Before(o[j].CreationTimestamp)\n}\n\nfunc (o OverlappingControllers) Len() int ", "output": "{ return len(o) }"} {"input": "package cmd\n\nimport (\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/tuxagon/yata-cli/yata\"\n\t\"github.com/urfave/cli\"\n)\n\nconst (\n\tidPrompt = \"Whoops, no task ID was specified. What is the ID of the task you want to complete?\"\n)\n\ntype cmdArgs interface {\n\tParse(ctx *cli.Context)\n}\n\ntype field string\n\nfunc (f field) String() string { return string(f) }\n\nfunc (f field) prompt() string {\n\tlf := strings.ToLower(f.String())\n\tyata.PrintfColor(\"yellow+h\", \"Missing %s: please provide a(n) %s\\n%s: \", lf, lf, f.capitalize())\n\treturn yata.Readln()\n}\n\nfunc (f field) promptInt() int {\n\tval := f.prompt()\n\tn, err := strconv.Atoi(val)\n\tif err != nil {\n\t\tshowError(err.Error(), true)\n\t}\n\treturn n\n}\n\nfunc (f field) capitalize() string {\n\tfs := f.String()\n\tif len(f) == 0 {\n\t\treturn fs\n\t}\n\treturn strings.ToUpper(string(fs[0])) + fs[1:]\n}\n\nfunc handleError(err error) {\n\tif err != nil {\n\t\tshowError(err.Error(), true)\n\t}\n}\n\nfunc showError(msg string, exit bool) {\n\tyata.Println(\"red+h\", msg)\n\tif exit {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc taskStringer(format string) int8 {\n\tswitch strings.ToLower(format) {\n\tcase \"json\":\n\t\treturn yata.JSON\n\tdefault:\n\t\treturn yata.Simple\n\t}\n}\n\n\n\nfunc parseIDWithIndex(ctx *cli.Context, index int) (id int) ", "output": "{\n\targs := ctx.Args()\n\n\tid = ctx.Int(\"id\")\n\n\tif id == 0 && len(args) == 0 {\n\t\tid = field(\"ID\").promptInt()\n\t} else if id == 0 && len(args) > 0 {\n\t\tid, _ = strconv.Atoi(args[0])\n\t}\n\n\tif id == 0 {\n\t\tshowError(\"No ID specified\", true)\n\t}\n\n\treturn\n}"} {"input": "package app\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\ntype collect struct{\n\turl string\n\tcontroller func(w http.ResponseWriter, r *http.Request) bool\n}\n\n\n\nfunc api(w http.ResponseWriter, r *http.Request){\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\troutes := Routes()\n\turl := r.URL.Path\n\tfor _, element := range routes{\n\t\tif url == element.url {\n\t\t\telement.controller(w, r)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Fprintf(w, \"{\\\"error\\\":true}\")\n}\n\nfunc Server(port int, host string){\n\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc( \"/\" , func(w http.ResponseWriter, r *http.Request){\n\t\trender(w, r)\n\t})\n\tmux.HandleFunc( \"/api/\" , func(w http.ResponseWriter, r *http.Request){\n\t\tapi(w, r)\n\t})\n\n\tprintln( fmt.Sprintf(\"Starting exodo server on port %d\", port))\n http.ListenAndServe(fmt.Sprintf(\"%s:%d\",host, port), mux)\n}\n\nfunc render(w http.ResponseWriter, r *http.Request)", "output": "{\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\troutes := Routes()\n\turl := r.URL.Path\n\tfor _, element := range routes{\n\t\tif url == element.url {\n\t\t\telement.controller(w, r)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Fprintf(w, \"

Error 404

\")\n}"} {"input": "package smtp\n\nimport (\n\t\"errors\"\n\t\"testing\"\n)\n\ntype EmailRecorder struct {\n\tfrom string\n\tto []string\n\tmsg []byte\n}\n\ntype SMTPMock struct {\n\tr *EmailRecorder\n\terr error\n}\n\nfunc (s *SMTPMock) SendMail(from string, to []string, msg []byte) error {\n\ts.r = &EmailRecorder{from, to, msg}\n\treturn s.err\n}\n\n\n\nfunc TestSendNormal(t *testing.T) {\n\tbody := \"From: john@doe.com\\r\\n\" +\n\t\t\"To: jane@doe.com\\r\\n\" +\n\t\t\"Subject: test\\r\\n\" +\n\t\t\"\\r\\n\" +\n\t\t\"message\\r\\n\"\n\ts := SMTPMock{err: nil}\n\tmailService := NewMailService(&s)\n\n\terr := mailService.Send(\"message\", \"test\", \"john@doe.com\", \"jane@doe.com\")\n\tif err != nil {\n\t\tt.Fatalf(\"Mustn't return an error\")\n\t}\n\tif string(s.r.msg) != body {\n\t\tt.Errorf(\"wrong message body.\\n\\nexpected: %s\\n got: %s\", body, s.r.msg)\n\t}\n}\n\nfunc TestSendError(t *testing.T) {\n\terr := errors.New(\"Error\")\n\ts := SMTPMock{err: err}\n\tmailService := NewMailService(&s)\n\n\terr = mailService.Send(\"message\", \"test\", \"john@doe.com\", \"jane@doe.com\")\n\tif err == nil {\n\t\tt.Fatalf(\"Must return an error\")\n\t}\n}\n\nfunc TestMailService(t *testing.T) ", "output": "{\n\tmailService := MailService{}\n\n\tvar i interface{} = &mailService\n\t_, ok := i.(IMailService)\n\n\tif !ok {\n\t\tt.Fatalf(\"MailService must implement IMailService\")\n\t}\n}"} {"input": "package wire\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\n\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) ", "output": "{\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}"} {"input": "package mutex\n\nimport \"sync\"\n\n\n\nfunc Write(x *int, mutex *sync.RWMutex, y int) {\n\tmutex.Lock()\n\tdefer mutex.Unlock()\n\n\t*x = y\n}\n\nfunc Read(x *int, mutex *sync.RWMutex) int ", "output": "{\n\tmutex.RLock()\n\tdefer mutex.RUnlock()\n\n\treturn *x\n}"} {"input": "package parser\n\nimport (\n\t\"github.com/dop251/goja/ast\"\n)\n\ntype _scope struct {\n\touter *_scope\n\tallowIn bool\n\tinIteration bool\n\tinSwitch bool\n\tinFunction bool\n\tdeclarationList []ast.Declaration\n\n\tlabels []string\n}\n\nfunc (self *_parser) openScope() {\n\tself.scope = &_scope{\n\t\touter: self.scope,\n\t\tallowIn: true,\n\t}\n}\n\n\n\nfunc (self *_scope) declare(declaration ast.Declaration) {\n\tself.declarationList = append(self.declarationList, declaration)\n}\n\nfunc (self *_scope) hasLabel(name string) bool {\n\tfor _, label := range self.labels {\n\t\tif label == name {\n\t\t\treturn true\n\t\t}\n\t}\n\tif self.outer != nil && !self.inFunction {\n\t\treturn self.outer.hasLabel(name)\n\t}\n\treturn false\n}\n\nfunc (self *_parser) closeScope() ", "output": "{\n\tself.scope = self.scope.outer\n}"} {"input": "package sarif\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"net\"\n\t\"time\"\n)\n\ntype netConn struct {\n\tconn net.Conn\n\tenc *json.Encoder\n\tdec *json.Decoder\n\tverified bool\n}\n\nfunc newNetConn(conn net.Conn) *netConn {\n\treturn &netConn{\n\t\tconn,\n\t\tjson.NewEncoder(conn),\n\t\tjson.NewDecoder(conn),\n\t\tfalse,\n\t}\n}\n\nfunc (c *netConn) Write(msg Message) error {\n\tif err := msg.IsValid(); err != nil {\n\t\treturn err\n\t}\n\tc.conn.SetWriteDeadline(time.Now().Add(5 * time.Minute))\n\treturn c.enc.Encode(msg)\n}\n\nfunc (c *netConn) KeepaliveLoop(ka time.Duration) error {\n\tfor {\n\t\ttime.Sleep(ka)\n\t\tc.conn.SetWriteDeadline(time.Now().Add(3 * ka))\n\t\tif _, err := c.conn.Write([]byte(\" \")); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\n\n\nfunc (c *netConn) Close() error {\n\treturn c.conn.Close()\n}\n\nfunc (c *netConn) IsVerified() bool {\n\tif tc, ok := c.conn.(*tls.Conn); ok {\n\t\tif len(tc.ConnectionState().VerifiedChains) > 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (c *netConn) Read() (Message, error) ", "output": "{\n\tvar msg Message\n\tc.conn.SetReadDeadline(time.Now().Add(time.Hour))\n\tif err := c.dec.Decode(&msg); err != nil {\n\t\treturn msg, err\n\t}\n\treturn msg, msg.IsValid()\n}"} {"input": "package system\n\nimport (\n\t\"github.com/Graylog2/collector-sidecar/common\"\n\t\"runtime\"\n)\n\ntype Inventory struct {\n}\n\nfunc NewInventory() *Inventory {\n\treturn &Inventory{}\n}\n\nfunc (inv *Inventory) Version() string {\n\treturn common.CollectorVersion\n}\n\nfunc (inv *Inventory) Linux() bool {\n\treturn runtime.GOOS == \"linux\"\n}\n\nfunc (inv *Inventory) Darwin() bool {\n\treturn runtime.GOOS == \"darwin\"\n}\n\nfunc (inv *Inventory) Windows() bool {\n\treturn runtime.GOOS == \"windows\"\n}\n\n\n\nfunc (inv *Inventory) LinuxPlatform() string ", "output": "{\n\tif runtime.GOOS == \"linux\" {\n\t\treturn common.LinuxPlatformFamily()\n\t} else {\n\t\treturn runtime.GOOS\n\t}\n}"} {"input": "package common\n\nimport (\n\t\"testing\"\n\n\t\"github.com/mitchellh/multistep\"\n)\n\n\n\nfunc TestStepSuppressMessages(t *testing.T) {\n\tstate := testState(t)\n\tstep := new(StepSuppressMessages)\n\n\tstate.Put(\"vmx_path\", \"foo\")\n\n\tdriver := state.Get(\"driver\").(*DriverMock)\n\n\tif action := step.Run(state); action != multistep.ActionContinue {\n\t\tt.Fatalf(\"bad action: %#v\", action)\n\t}\n\tif _, ok := state.GetOk(\"error\"); ok {\n\t\tt.Fatal(\"should NOT have error\")\n\t}\n\n\tif !driver.SuppressMessagesCalled {\n\t\tt.Fatal(\"should've called\")\n\t}\n\tif driver.SuppressMessagesPath != \"foo\" {\n\t\tt.Fatal(\"should call with right path\")\n\t}\n}\n\nfunc TestStepSuppressMessages_impl(t *testing.T) ", "output": "{\n\tvar _ multistep.Step = new(StepSuppressMessages)\n}"} {"input": "package main\n\ntype Human struct {\n\tname string\n\tage int\n\tphone string\n}\n\ntype Student struct {\n\tHuman\n\tschool string\n\tloan float32\n}\n\ntype Employee struct {\n\tHuman\n\tcompany string\n\tmoney float32\n}\n\n\ntype Men interface {\n\tSayHi()\n\tSing(lyrics string)\n\tGuzzle(beerStein string)\n}\n\ntype YoungChap interface {\n\tSayHi()\n\tSing(lyrics string)\n\tBorrowMoney(amount float32)\n}\n\ntype ElderlyGent interface {\n\tSayHi()\n\tSing(song string)\n\tSpendSalary(amount float32)\n}\n\nfunc (h *Human) SayHi() {\n\tfmt.Printf(\"Hi, I am %s you can call me on %s\\n\", h.name, h.phone)\n}\n\nfunc (h *Human) Sing(lyrics string) {\n\tfmt.Println(\"La la, la la la, la la la la...\", lyrics)\n}\n\nfunc (h *Human) Guzzle(beerStein string) {\n\tfmt.Println(\"Guzzle Guzzle Guzzle...\", beerStein)\n}\n\n\nfunc (e *Employee) SayHi() {\n\tfmt.Printf(\"Hi, I am %s, I work at %s. Call me on %s\\n\", e.name, e.company, e.phone)\n}\n\nfunc (s *Student) BorrowMoney(amount float32) {\n\ts.loan += amount\n}\n\n\n\nfunc (e *Employee) SpendSalary(amount float32) ", "output": "{\n\te.money -= e.amount\n}"} {"input": "package models\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\n\nfunc TestMain(m *testing.M) {\n\tMainTest(m, \"..\")\n}\n\nfunc TestFixturesAreConsistent(t *testing.T) ", "output": "{\n\tassert.NoError(t, PrepareTestDatabase())\n\tCheckConsistencyForAll(t)\n}"} {"input": "package client\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strconv\"\n\n\t\"github.com/snapcore/snapd/asserts\" \n)\n\n\n\n\n\n\n\n\nfunc (client *Client) Known(assertTypeName string, headers map[string]string) ([]asserts.Assertion, error) {\n\tpath := fmt.Sprintf(\"/v2/assertions/%s\", assertTypeName)\n\tq := url.Values{}\n\n\tif len(headers) > 0 {\n\t\tfor k, v := range headers {\n\t\t\tq.Set(k, v)\n\t\t}\n\t}\n\n\tresponse, err := client.raw(\"GET\", path, q, nil, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to query assertions: %v\", err)\n\t}\n\tdefer response.Body.Close()\n\tif response.StatusCode != http.StatusOK {\n\t\treturn nil, parseError(response)\n\t}\n\n\tsanityCount, err := strconv.Atoi(response.Header.Get(\"X-Ubuntu-Assertions-Count\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid assertions count\")\n\t}\n\n\tdec := asserts.NewDecoder(response.Body)\n\n\tasserts := []asserts.Assertion{}\n\n\tfor {\n\t\ta, err := dec.Decode()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to decode assertions: %v\", err)\n\t\t}\n\t\tasserts = append(asserts, a)\n\t}\n\n\tif len(asserts) != sanityCount {\n\t\treturn nil, fmt.Errorf(\"response did not have the expected number of assertions\")\n\t}\n\n\treturn asserts, nil\n}\n\nfunc (client *Client) Ack(b []byte) error ", "output": "{\n\tvar rsp interface{}\n\tif _, err := client.doSync(\"POST\", \"/v2/assertions\", nil, nil, bytes.NewReader(b), &rsp); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package kusto\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) BaseClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package conformance\n\n\n\nfunc stringLen(s string) int {\n\treturn len(s)\n}\n\nfunc substring(s string, low, high int) string {\n\tswitch {\n\tcase low >= 0 && high >= 0:\n\t\treturn s[low:high]\n\tcase low >= 0:\n\t\treturn s[low:]\n\tcase high >= 0:\n\t\treturn s[:high]\n\tdefault:\n\t\treturn s\n\t}\n}\n\nfunc stringGet(s string, index int) byte ", "output": "{\n\treturn s[index]\n}"} {"input": "package library\n\nimport (\n\t\"github.com/nytlabs/streamtools/st/blocks\" \n)\n\n\ntype FromPost struct {\n\tblocks.Block\n\tqueryrule chan blocks.MsgChan\n\tinrule blocks.MsgChan\n\tin blocks.MsgChan\n\tout blocks.MsgChan\n\tquit blocks.MsgChan\n}\n\n\nfunc NewFromPost() blocks.BlockInterface {\n\treturn &FromPost{}\n}\n\n\n\n\n\nfunc (b *FromPost) Run() {\n\tfor {\n\t\tselect {\n\t\tcase <-b.quit:\n\t\t\treturn\n\t\tcase msg := <-b.in:\n\t\t\tb.out <- msg\n\t\t}\n\t}\n}\n\nfunc (b *FromPost) Setup() ", "output": "{\n\tb.Kind = \"Network I/O\"\n\tb.Desc = \"emits any message that is POSTed to its IN route\"\n\tb.in = b.InRoute(\"in\")\n\tb.quit = b.Quit()\n\tb.out = b.Broadcast()\n}"} {"input": "package middlewares\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n\ntype CoreQuery struct {\n\tskip int\n\tlimit int\n\tsort string\n\tdatefrom string\n\tdateto string\n}\n\n\nfunc Query() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tq := CoreQuery{}\n\t\tq.skip = toInt(c.Query(\"skip\"), 0)\n\t\tq.limit = toInt(c.Query(\"limit\"), 20)\n\t\tq.sort = c.Query(\"sort\")\n\t\tq.datefrom = c.Query(\"datefrom\")\n\t\tq.dateto = c.Query(\"dateto\")\n\t\tc.Set(\"Query\", q)\n\t\tc.Next()\n\t}\n}\n\n\n\nfunc toInt(s string, defValue int) int ", "output": "{\n\tnum, err := strconv.Atoi(s)\n\n\tif err != nil {\n\t\treturn defValue\n\t}\n\n\treturn num\n}"} {"input": "package match\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\nfunc Match(t *testing.T, value interface{}) *Matcher {\n\treturn &Matcher{\n\t\tt: t,\n\t\tvalue: value,\n\t}\n}\n\n\nfunc IsNil(t *testing.T, value interface{}) *Matcher {\n\treturn Match(t, value).IsNil()\n}\n\n\n\n\n\nfunc Equals(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).Equals(other)\n}\n\n\nfunc NotEquals(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).NotEquals(other)\n}\n\n\nfunc LessThan(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).LessThan(other)\n}\n\n\nfunc GreaterThan(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).GreaterThan(other)\n}\n\n\nfunc Contains(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).Contains(other)\n}\n\n\nfunc Matches(t *testing.T, value interface{}, pattern string) *Matcher {\n\treturn Match(t, value).Matches(pattern)\n}\n\n\nfunc KindOf(t *testing.T, value interface{}, kind reflect.Kind) *Matcher {\n\treturn Match(t, value).KindOf(kind)\n}\n\nfunc IsNotNil(t *testing.T, value interface{}) *Matcher ", "output": "{\n\treturn Match(t, value).IsNotNil()\n}"} {"input": "package server\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/Arvinderpal/go-storage-server/challenge/common/backend\"\n\t\"github.com/Arvinderpal/go-storage-server/challenge/common/types\"\n\n\t\"github.com/gorilla/mux\"\n)\n\n\ntype Router struct {\n\t*mux.Router\n\troutes routes\n\tdaemon backend.DaemonBackend\n}\n\n\n\n\nfunc processServerError(w http.ResponseWriter, r *http.Request, err error) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tsErr := types.ServerError{\n\t\tCode: http.StatusInternalServerError,\n\t\tText: fmt.Sprintf(\"an unexpected internal error has occurred: \\\"%s\\\"\", err),\n\t}\n\tlogger.Debugf(\"Processing error %s\\n\", sErr)\n\tlogger.Errorf(\"Error while processing request '%+v': \\\"%s\\\"\", r, err)\n\tif err := json.NewEncoder(w).Encode(sErr); err != nil {\n\t\tlogger.Errorf(\"Error while encoding %T '%+v': \\\"%s\\\"\", sErr, sErr, err)\n\t\tfmt.Fprintf(w, \"Fatal error while processing request '%+v': \\\"%s\\\"\", r, err)\n\t}\n}\n\nfunc NewRouter(daemon backend.DaemonBackend) Router ", "output": "{\n\tmRouter := mux.NewRouter().StrictSlash(true)\n\tr := Router{mRouter, routes{}, daemon}\n\tr.initBackendRoutes()\n\tfor _, route := range r.routes {\n\t\thandler := Logger(route.HandlerFunc, route.Name)\n\n\t\tr.Methods(route.Method).\n\t\t\tPath(route.Pattern).\n\t\t\tName(route.Name).\n\t\t\tHandler(handler)\n\t}\n\treturn r\n}"} {"input": "package machine\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc TestFakeMachine(t *testing.T) ", "output": "{\n\tms := MachineState{ID: \"XXX\"}\n\tfm := FakeMachine{ms}\n\n\tret := fm.State()\n\tif !reflect.DeepEqual(ms, ret) {\n\t\tt.Fatalf(\"FakeMachine.State() returned %v, expected %v\", ret, ms)\n\t}\n}"} {"input": "package help\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n)\n\n\ntype Command struct {\n\tStdout io.Writer\n}\n\n\n\n\n\nfunc (cmd *Command) Run(args ...string) error {\n\tfmt.Fprintln(cmd.Stdout, strings.TrimSpace(usage))\n\treturn nil\n}\n\nconst usage = `\nUsage: influx_inspect [[command] [arguments]]\n\nThe commands are:\n\n dumptsi dumps low-level details about tsi1 files.\n dumptsm dumps low-level details about tsm1 files.\n export exports raw data from a shard to line protocol\n help display this help message\n report displays a shard level report\n verify verifies integrity of TSM files\n\n\"help\" is the default command.\n\nUse \"influx_inspect [command] -help\" for more information about a command.\n`\n\nfunc NewCommand() *Command ", "output": "{\n\treturn &Command{\n\t\tStdout: os.Stdout,\n\t}\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"context\"\n\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\n\ntype Ddns struct {\n\n\tEnabled *bool `json:\"enabled,omitempty\"`\n\n\tFqdn string `json:\"fqdn,omitempty\"`\n\n\tSkipFqdnValidation *bool `json:\"skip_fqdn_validation,omitempty\"`\n\n\tTimeToLive *string `json:\"time_to_live,omitempty\"`\n\n\tUseSecure *bool `json:\"use_secure,omitempty\"`\n}\n\n\nfunc (m *Ddns) Validate(formats strfmt.Registry) error {\n\treturn nil\n}\n\n\n\n\n\nfunc (m *Ddns) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *Ddns) UnmarshalBinary(b []byte) error {\n\tvar res Ddns\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *Ddns) ContextValidate(ctx context.Context, formats strfmt.Registry) error ", "output": "{\n\treturn nil\n}"} {"input": "package entities\n\nconst (\n\tActionMove = iota + 1\n\n\tActionAttack\n\n\tActionCastSpell\n\n\tActionGather\n\n\tActionLoot\n\n\tActionConsume\n)\n\n\n\n\n\n\n\n\n\n\n\ntype Action interface {\n\tSetTarget(Entity)\n\tSetSelf(Entity)\n\n\tGetTypeAction() uint8\n\tGetSelf() Entity\n\tGetTarget() Entity\n\n\tPlay() error\n}\n\n\ntype SimpleAction struct {\n\tself Entity\n\ttarget Entity\n\ttypeAction uint8\n}\n\n\nfunc (action *SimpleAction) GetTypeAction() uint8 {\n\treturn action.GetTypeAction()\n}\n\n\nfunc (action *SimpleAction) SetTarget(target Entity) {\n\taction.target = target\n}\n\n\nfunc (action *SimpleAction) GetTarget() Entity {\n\treturn action.target\n}\n\n\nfunc (action *SimpleAction) SetSelf(self Entity) {\n\taction.self = self\n}\n\n\nfunc (action *SimpleAction) GetSelf() Entity {\n\treturn action.self\n}\n\n\n\n\nfunc (action *SimpleAction) Play() error ", "output": "{\n\treturn nil\n}"} {"input": "package qtypes\n\nimport (\n\t\"strings\"\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/qnib/qframe-utils\"\n\t\"fmt\"\n)\n\nconst (\n\tMsgCEE = \"cee\"\n\tMsgTCP = \"tcp\"\n\tMsgFile = \"file\"\n\tMsgDLOG = \"docker-log\"\n\tMsgMetric = \"metric\" \n)\n\n\ntype Message struct {\n\tBase\n\tContainer types.ContainerJSON\n\tName \tstring \t`json:\"name\"`\n\tLogLevel string\t\t\t\t`json:\"loglevel\"`\n\tMessageType\tstring \t`json:\"type\"`\n\tMessage string \t`json:\"value\"`\n\tKV\t\t\tmap[string]string \t`json:\"data\"`\n}\n\n\n\nfunc NewContainerMessage(base Base, cnt types.ContainerJSON, name, mType, msg string) Message {\n\tm := NewMessage(base, name, mType, msg)\n\tm.Container = cnt\n\tm.ID = m.GenContainerMsgID()\n\treturn m\n}\n\n\nfunc (m *Message) GenContainerMsgID() string {\n\ts := fmt.Sprintf(\"%s-%d-%s\", m.Container.ID, m.Time.UnixNano(), m.Message)\n\treturn Sha1HashString(s)\n}\n\nfunc (m *Message) GetContainerName() string {\n\tif m.Container.Name != \"\" {\n\t\treturn strings.Trim(m.Container.Name, \"/\")\n\t} else {\n\t\treturn \"\"\n\t}\n}\n\nfunc NewMessage(base Base, name, mType, msg string) Message ", "output": "{\n\tm := Message{\n\t\tBase: base,\n\t\tName: name,\n\t\tContainer: types.ContainerJSON{},\n\t\tLogLevel: \"INFO\",\n\t\tMessageType: mType,\n\t\tMessage: msg,\n\t\tKV: map[string]string{},\n\t}\n\tm.SourceID = int(qutils.GetGID())\n\treturn m\n}"} {"input": "package proxy\n\nimport (\n\t\"log\"\n\t\"strconv\"\n\n\t\"../util\"\n)\n\nfunc (s *ProxyServer) handleGetWorkRPC(cs *Session, diff, id string) (reply []string, errorReply *ErrorReply) {\n\tt := s.currentBlockTemplate()\n\tif len(t.Header) == 0 {\n\t\treturn nil, &ErrorReply{Code: -1, Message: \"Work not ready\"}\n\t}\n\ttargetHex := t.Target\n\n\tif !s.rpc().Pool {\n\t\tminerDifficulty, err := strconv.ParseFloat(diff, 64)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Invalid difficulty %v from %v@%v \", diff, id, cs.ip)\n\t\t\tminerDifficulty = 5\n\t\t}\n\t\ttargetHex = util.MakeTargetHex(minerDifficulty)\n\t}\n\treply = []string{t.Header, t.Seed, targetHex}\n\treturn\n}\n\n\n\nfunc (s *ProxyServer) handleSubmitHashrate(cs *Session, req *JSONRpcReq) bool {\n\treply, _ := s.rpc().SubmitHashrate(req.Params)\n\treturn reply\n}\n\nfunc (s *ProxyServer) handleUnknownRPC(cs *Session, req *JSONRpcReq) *ErrorReply {\n\tlog.Printf(\"Unknown RPC method: %v\", req)\n\treturn &ErrorReply{Code: -1, Message: \"Invalid method\"}\n}\n\nfunc (s *ProxyServer) handleSubmitRPC(cs *Session, diff string, id string, params []string) (reply bool, errorReply *ErrorReply) ", "output": "{\n\tminer, ok := s.miners.Get(id)\n\tif !ok {\n\t\tminer = NewMiner(id, cs.ip)\n\t\ts.registerMiner(miner)\n\t}\n\n\tt := s.currentBlockTemplate()\n\treply = miner.processShare(s, t, diff, params)\n\treturn\n}"} {"input": "package main\n\n\n\ntype Hub struct {\n\tname string\n\tclients map[*Client]bool\n\tbroadcast chan []byte\n\tregister chan *Client\n\tunregister chan *Client\n}\n\nvar hubs map[*Hub]bool\nvar globalLobby *Hub\n\nfunc initHubs() {\n\thubs = make(map[*Hub]bool)\n\tglobalLobby = newHub(\"Global\")\n\tgo globalLobby.run()\n}\n\n\n\nfunc findHubNamed(name string) *Hub {\n\tfor h := range hubs {\n\t\tif h.name == name {\n\t\t\treturn h\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (h *Hub) run() {\n\tfor {\n\t\tselect {\n\t\tcase client := <-h.register:\n\t\t\th.clients[client] = true\n\t\tcase client := <-h.unregister:\n\t\t\tif _, ok := h.clients[client]; ok {\n\t\t\t\tdelete(h.clients, client)\n\t\t\t}\n\t\tcase message := <-h.broadcast:\n\t\t\tfor client := range h.clients {\n\t\t\t\tselect {\n\t\t\t\tcase client.send <- message:\n\t\t\t\tdefault:\n\t\t\t\t\tclose(client.send)\n\t\t\t\t\tdelete(h.clients, client)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc newHub(name string) *Hub ", "output": "{\n\tnh := &Hub{\n\t\tname: name,\n\t\tbroadcast: make(chan []byte),\n\t\tregister: make(chan *Client),\n\t\tunregister: make(chan *Client),\n\t\tclients: make(map[*Client]bool),\n\t}\n\n\thubs[nh] = true\n\n\treturn nh\n}"} {"input": "package fuzzy\n\nimport \"testing\"\n\nvar levenshteinDistanceTests = []struct {\n\ts, t string\n\twanted int\n}{\n\t{\"a\", \"a\", 0},\n\t{\"ab\", \"ab\", 0},\n\t{\"ab\", \"aa\", 1},\n\t{\"ab\", \"aa\", 1},\n\t{\"ab\", \"aaa\", 2},\n\t{\"bbb\", \"a\", 3},\n\t{\"kitten\", \"sitting\", 3},\n\t{\"ёлка\", \"ёлочка\", 2},\n\t{\"ветер\", \"ёлочка\", 6},\n\t{\"中国\", \"中华人民共和国\", 5},\n\t{\"日本\", \"中华人民共和国\", 7},\n}\n\nfunc TestLevenshtein(t *testing.T) {\n\tfor _, test := range levenshteinDistanceTests {\n\t\tdistance := LevenshteinDistance(test.s, test.t)\n\t\tif distance != test.wanted {\n\t\t\tt.Errorf(\"got distance %d, expected %d for %s in %s\", distance, test.wanted, test.s, test.t)\n\t\t}\n\t}\n}\n\n\n\nfunc BenchmarkLevenshteinDistance(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tLevenshteinDistance(\"aaa\", \"aba\")\n\t\tLevenshteinDistance(\"kitten\", \"sitting\")\n\t}\n}"} {"input": "package models\n\nimport (\n\t\"github.com/3xxx/engineercms/controllers/tool/result\"\n\t\"github.com/nu7hatch/gouuid\"\n\t\"time\"\n)\n\n\ntype Bridge struct {\n\tId uint `json:\"id\" gorm:\"primary_key\"`\n\tUuid string `json:\"uuid\" gorm:\"type:char(36);index:idx_uuid\"`\n\tCreatedAt time.Time\n\tUpdatedAt time.Time\n\tShareUuid string `json:\"shareUuid\" gorm:\"type:char(36)\"`\n\tProductId int64 `json:\"productid\" gorm:\"type:bigint(20) not null;default:0\"`\n}\n\ntype OrderPair struct {\n\tKey string\n\tValue string\n}\n\ntype WherePair struct {\n\tQuery string\n\tArgs []interface{}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Pager struct {\n\tPage int `json:\"page\"`\n\tPageSize int `json:\"pageSize\"`\n\tTotalItems int `json:\"totalItems\"`\n\tTotalPages int `json:\"totalPages\"`\n\tData interface{} `json:\"data\"`\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc CreateBridge(bridge *Bridge) (*Bridge, error) {\n\tdb := GetDB()\n\ttimeUUID, _ := uuid.NewV4()\n\tbridge.Uuid = string(timeUUID.String())\n\tbridge.CreatedAt = time.Now()\n\tbridge.UpdatedAt = time.Now()\n\tdb = db.Table(\"share_bridge\").Create(&bridge)\n\treturn bridge, db.Error\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc FindByShareUuid(shareUuid string) ([]*Bridge, error) ", "output": "{\n\tif shareUuid == \"\" {\n\t\tpanic(result.BadRequest(\"shareUuid cannot be nil\"))\n\t}\n\tvar bridges []*Bridge\n\tdb := GetDB().Table(\"share_bridge\").\n\t\tWhere(\"share_uuid = ?\", shareUuid).\n\t\tFind(&bridges)\n\treturn bridges, db.Error\n}"} {"input": "package main\n\nimport (\n\t\"crypto/rand\"\n\t\"fmt\"\n\t\"math/big\"\n\t\"time\"\n)\n\n\n\nfunc main() {\n\tc1 := make(chan int64, 1)\n\tc2 := make(chan int64, 1)\n\n\tgo Grenade(c1)\n\tgo Grenade(c2)\n\n\ti := 0\n\tfor {\n\t\tselect {\n\t\tcase r1 := <-c1:\n\t\t\tfmt.Printf(\"Boomed in %d seconds\\n\", r1)\n\t\tcase r2 := <-c2:\n\t\t\tfmt.Printf(\"Boom in %d seconds\\n\", r2)\n\t\tdefault:\n\t\t\ti += 1\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tif i >= 10 {\n\t\t\t\tfmt.Println(\"TIME OUT\\n\", i)\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"%d ...\\n\", i)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc Grenade(c chan int64) ", "output": "{\n\tdelay, _ := rand.Int(rand.Reader, big.NewInt(10))\n\tseconds := delay.Int64()\n\tfmt.Printf(\"Grenade : Boom after %d seconds\\n\", seconds)\n\ttime.Sleep(time.Duration(seconds) * time.Second)\n\tc <- seconds\n}"} {"input": "package balanced\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n)\n\ntype Customer struct {\n\tAddress *Address `json:\"address,omitempty\"`\n\tBusinessName string `json:\"business_name,omitempty\"`\n\tCreatedAt time.Time `json:\"created_at,omitempty\"`\n\tDobMonth int `json:\"dob_month,omitempty\"`\n\tDobYear int `json:\"dob_year,omitempty\"`\n\tEin string `json:\"ein,omitempty\"`\n\tEmail string `json:\"email,omitempty\"`\n\tID string `json:\"id,omitempty\"`\n\tMeta map[string]interface{} `json:\"meta,omitempty\"`\n\tName string `json:\"name,omitempty\"`\n\tPhone string `json:\"phone,omitempty\"`\n\tSSNLast4 string `json:\"ssn_last4,omitempty\"`\n\tMerchantStatus string `json:\"merchant_status,omitempty\"`\n}\n\ntype customerResponse struct {\n\tCustomers []*Customer `json:\"customers\"`\n}\n\n\n\nfunc (c *Customer) getID() string {\n\treturn c.ID\n}\n\nfunc (c *Customer) getOwnerPath() string {\n\treturn \"\"\n}\n\nfunc (c *Customer) singleResponse(data []byte) {\n\tparsedResponse := new(customerResponse)\n\tjson.Unmarshal(data, &parsedResponse)\n\t*c = *parsedResponse.Customers[0]\n}\n\nfunc (c *Customer) canDelete() bool {\n\treturn true\n}\n\nfunc (c *Customer) IsVerified() bool {\n\treturn c.MerchantStatus == \"underwritten\"\n}\n\nfunc (c *Customer) path() string ", "output": "{\n\treturn \"/customers\"\n}"} {"input": "package k8s\n\nimport (\n\t\"fmt\"\n\t\"github.com/ghodss/yaml\"\n\n\tapi_core_v1 \"k8s.io/api/core/v1\"\n\tapi_extn_v1beta1 \"k8s.io/api/extensions/v1beta1\"\n)\n\n\n\ntype Deployment struct {\n\tYmlInBytes []byte\n}\n\nfunc NewDeployment(b []byte) *Deployment {\n\treturn &Deployment{\n\t\tYmlInBytes: b,\n\t}\n}\n\n\nfunc (m *Deployment) AsExtnV1B1Deployment() (*api_extn_v1beta1.Deployment, error) {\n\tif m.YmlInBytes == nil {\n\t\treturn nil, fmt.Errorf(\"Missing yaml\")\n\t}\n\n\tdeploy := &api_extn_v1beta1.Deployment{}\n\terr := yaml.Unmarshal(m.YmlInBytes, deploy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn deploy, nil\n}\n\n\ntype Service struct {\n\tYmlInBytes []byte\n}\n\n\n\n\nfunc (m *Service) AsCoreV1Service() (*api_core_v1.Service, error) {\n\tif m.YmlInBytes == nil {\n\t\treturn nil, fmt.Errorf(\"Missing yaml\")\n\t}\n\n\tsvc := &api_core_v1.Service{}\n\terr := yaml.Unmarshal(m.YmlInBytes, svc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn svc, nil\n}\n\nfunc NewService(b []byte) *Service ", "output": "{\n\treturn &Service{\n\t\tYmlInBytes: b,\n\t}\n}"} {"input": "package wallabago\n\nimport \"testing\"\n\nconst tagsResult = `[{\"id\":53,\"label\":\"2min\",\"slug\":\"2min\"},{\"id\":57,\"label\":\"android\",\"slug\":\"android\"},{\"id\":58,\"label\":\"linux\",\"slug\":\"linux\"}]`\n\nfunc TestGetTagsOfEntry(t *testing.T) {\n\tarticleID := 3977\n\texpectedID := 57\n\texpectedLabel := \"android\"\n\texpectedSlug := \"android\"\n\ttags, _ := GetTagsOfEntry(mockGetTagsOfEntry, articleID)\n\tif tags[1].ID != expectedID {\n\t\tt.Errorf(\"expected id=%v, but got %v\", expectedID, tags[1].ID)\n\t}\n\tif tags[1].Label != expectedLabel {\n\t\tt.Errorf(\"expected label=%v, but got %v\", expectedLabel, tags[1].Label)\n\t}\n\tif tags[1].Slug != expectedSlug {\n\t\tt.Errorf(\"expected slug=%v, but got %v\", expectedSlug, tags[1].Slug)\n\t}\n}\n\nfunc mockGetTagsOfEntry(url string, httpMethod string, postData []byte) ([]byte, error) {\n\treturn []byte(tagsResult), nil\n}\n\n\n\nfunc TestGetTags(t *testing.T) ", "output": "{\n\texpectedID := 57\n\texpectedLabel := \"android\"\n\texpectedSlug := \"android\"\n\ttags, _ := GetTags(mockGetTagsOfEntry)\n\tif tags[1].ID != expectedID {\n\t\tt.Errorf(\"expected id=%v, but got %v\", expectedID, tags[1].ID)\n\t}\n\tif tags[1].Label != expectedLabel {\n\t\tt.Errorf(\"expected label=%v, but got %v\", expectedLabel, tags[1].Label)\n\t}\n\tif tags[1].Slug != expectedSlug {\n\t\tt.Errorf(\"expected slug=%v, but got %v\", expectedSlug, tags[1].Slug)\n\t}\n}"} {"input": "package utils\n\nimport \"bytes\"\n\n\n\ntype CompositeError []error\n\n\nfunc (c *CompositeError) Error() string {\n\tvar b bytes.Buffer\n\tfor ind, err := range *c {\n\t\t_, _ = b.WriteString(err.Error())\n\t\tif ind == len(*c)-1 {\n\t\t\tbreak\n\t\t}\n\t\t_, _ = b.WriteRune('\\n')\n\t}\n\n\treturn b.String()\n}\n\n\nfunc (c *CompositeError) AppendError(err error) {\n\tif err != nil {\n\t\t*c = append(*c, err)\n\t}\n}\n\n\n\n\n\n\nfunc NewCompositeError(errors ...error) error {\n\tres := &CompositeError{}\n\tfor _, err := range errors {\n\t\tres.AppendError(err)\n\t}\n\tif res.Empty() {\n\t\treturn nil\n\t}\n\treturn res\n}\n\nfunc (c *CompositeError) Empty() bool ", "output": "{\n\treturn c == nil || len(*c) == 0\n}"} {"input": "package runner\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"os/exec\"\n\t\"syscall\"\n)\n\ntype Runner struct {\n\toutStream, errStream io.Writer\n}\n\nfunc New(out, err io.Writer) *Runner {\n\treturn &Runner{out, err}\n}\n\nfunc (r *Runner) Run(command string) error {\n\tcmd := exec.Command(\"cmd\")\n\tcmd.SysProcAttr = &syscall.SysProcAttr{}\n\tcmd.SysProcAttr.CmdLine = \"/C \" + command\n\n\tout_reader, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr_reader, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\n\tgo r.echoStdout(out_reader)\n\tgo r.echoStderr(err_reader)\n\n\terr = cmd.Wait()\n\treturn err\n}\n\n\n\nfunc (r *Runner) echoStderr(reader io.Reader) {\n\tscanner := bufio.NewScanner(reader)\n\tfor scanner.Scan() {\n\t\tfmt.Fprintf(r.errStream, \"%s\\n\", scanner.Text())\n\t}\n}\n\nfunc (r *Runner) echoStdout(reader io.Reader) ", "output": "{\n\tscanner := bufio.NewScanner(reader)\n\tfor scanner.Scan() {\n\t\tfmt.Fprintf(r.outStream, \"%s\\n\", scanner.Text())\n\t}\n}"} {"input": "package cron\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestRunTask(t *testing.T) ", "output": "{\n\ttimes := TTimes{\"*\", \"*\", \"*\", \"*\", \"*\"}\n\tabs, _ := os.Getwd()\n\ttask := NewTask(\"python3\", \"\", times, []string{abs + \"/../ever.py\"})\n\t_, err := RunTask(task)\n\tif err != nil {\n\t\tt.Errorf(\"run error:%s\\n\", err.Error())\n\t}\n}"} {"input": "package budget\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteBudgetRequest struct {\n\n\tBudgetId *string `mandatory:\"true\" contributesTo:\"path\" name:\"budgetId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteBudgetRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteBudgetRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request DeleteBudgetRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype DeleteBudgetResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteBudgetResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteBudgetResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteBudgetRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package check\n\n\ntype GoFmt struct {\n\tDir string\n\tFilenames []string\n}\n\n\nfunc (g GoFmt) Name() string {\n\treturn \"gofmt\"\n}\n\n\nfunc (g GoFmt) Weight() float64 {\n\treturn .35\n}\n\n\nfunc (g GoFmt) Percentage() (float64, []FileSummary, error) {\n\treturn GoTool(g.Dir, g.Filenames, []string{\"gofmt\", \"-s\", \"-l\"})\n}\n\n\n\n\nfunc (g GoFmt) Description() string ", "output": "{\n\treturn `Gofmt formats Go programs. We run gofmt -s on your code, where -s is for the \"simplify\" command`\n}"} {"input": "package db\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"github.com/jmoiron/sqlx\"\n\t\"gopkg.in/yaml.v1\"\n)\n\n\ntype Configs map[string]*Config\n\n\n\n\n\ntype Config struct {\n\tDatasource string `yaml:\"datasource\"`\n}\n\n\nfunc (c *Config) DSN() string {\n\treturn c.Datasource\n}\n\n\n\nfunc (c *Config) Open() (*sqlx.DB, error) {\n\treturn sqlx.Open(\"mysql\", c.DSN())\n}\n\n\nfunc NewConfigsFromFile(path string) (Configs, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treturn NewConfigs(f)\n}\n\n\nfunc NewConfigs(r io.Reader) (Configs, error) {\n\tb, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar configs Configs\n\tif err = yaml.Unmarshal(b, &configs); err != nil {\n\t\treturn nil, err\n\t}\n\treturn configs, nil\n}\n\nfunc (cs Configs) Open(env string) (*sqlx.DB, error) ", "output": "{\n\tconfig, ok := cs[env]\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\treturn config.Open()\n}"} {"input": "package column\n\nimport (\n\t\"github.com/kshvakov/clickhouse/lib/binary\"\n)\n\ntype UInt8 struct{ base }\n\nfunc (UInt8) Read(decoder *binary.Decoder) (interface{}, error) {\n\tv, err := decoder.UInt8()\n\tif err != nil {\n\t\treturn uint8(0), err\n\t}\n\treturn v, nil\n}\n\n\n\nfunc (u *UInt8) Write(encoder *binary.Encoder, v interface{}) error ", "output": "{\n\tswitch v := v.(type) {\n\tcase bool:\n\t\treturn encoder.Bool(v)\n\tcase uint8:\n\t\treturn encoder.UInt8(v)\n\tcase int64:\n\t\treturn encoder.UInt8(uint8(v))\n\tcase int:\n\t\treturn encoder.UInt8(uint8(v))\n\t}\n\treturn &ErrUnexpectedType{\n\t\tT: v,\n\t\tColumn: u,\n\t}\n}"} {"input": "package classfile\n\nimport (\n\t\"github.com/zxh0/jvm.go/jvmgo/util/bigendian\"\n)\n\ntype ClassReader struct {\n\tdata []byte\n}\n\nfunc newClassReader(data []byte) *ClassReader {\n\treturn &ClassReader{data}\n}\n\nfunc (self *ClassReader) readUint8() uint8 {\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16() uint16 {\n\tval := bigendian.Uint16(self.data)\n\tself.data = self.data[2:]\n\treturn val\n}\n\n\nfunc (self *ClassReader) readInt32() int32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readInt64() int64 {\n\tval := bigendian.Int64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readFloat32() float32 {\n\tval := bigendian.Float32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readFloat64() float64 {\n\tval := bigendian.Float64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readBytes(length uint32) []byte {\n\tbytes := self.data[:length]\n\tself.data = self.data[length:]\n\treturn bytes\n}\n\n\nfunc (self *ClassReader) readString() string {\n\tlength := uint32(self.readUint16())\n\tbytes := self.readBytes(length)\n\treturn string(bytes)\n}\n\nfunc (self *ClassReader) readUint32() uint32 ", "output": "{\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn uint32(val)\n}"} {"input": "package jmespath\n\nimport \"strconv\"\n\n\n\ntype JMESPath struct {\n\tast ASTNode\n\tintr *treeInterpreter\n}\n\n\n\nfunc Compile(expression string) (*JMESPath, error) {\n\tparser := NewParser()\n\tast, err := parser.Parse(expression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tjmespath := &JMESPath{ast: ast, intr: newInterpreter()}\n\treturn jmespath, nil\n}\n\n\n\n\n\n\n\nfunc (jp *JMESPath) Search(data interface{}) (interface{}, error) {\n\treturn jp.intr.Execute(jp.ast, data)\n}\n\n\nfunc Search(expression string, data interface{}) (interface{}, error) {\n\tintr := newInterpreter()\n\tparser := NewParser()\n\tast, err := parser.Parse(expression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn intr.Execute(ast, data)\n}\n\nfunc MustCompile(expression string) *JMESPath ", "output": "{\n\tjmespath, err := Compile(expression)\n\tif err != nil {\n\t\tpanic(`jmespath: Compile(` + strconv.Quote(expression) + `): ` + err.Error())\n\t}\n\treturn jmespath\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n)\n\ntype Monitor interface {\n\tGetVariables() []string\n\tGetValues([]string) map[string]interface{}\n}\n\nvar monitorDrivers = make(map[string]func(*json.RawMessage) Monitor)\n\nfunc AddMonitorDriver(monitor string, constructor func(*json.RawMessage) Monitor) {\n\tmonitorDrivers[monitor] = constructor\n}\n\ntype MonitorTrack struct {\n\tVariables map[string]*MonitorTrackVariable\n\tInterval int\n\ttimer *time.Timer\n}\n\nfunc newMonitorTrack() *MonitorTrack {\n\treturn &MonitorTrack{\n\t\tVariables: make(map[string]*MonitorTrackVariable),\n\t}\n}\n\ntype MonitorTrackVariable struct {\n\tHistory int\n\tData []interface{}\n}\n\nfunc (mt *MonitorTrack) SetTrack(variable string, history int) {\n\ttrack, ok := mt.Variables[variable]\n\tif !ok && history > 0 {\n\t\ttrack = &MonitorTrackVariable{}\n\t\tmt.Variables[variable] = track\n\t}\n\tif history == 0 && ok {\n\t\tdelete(mt.Variables, variable)\n\t\treturn\n\t}\n\ttrack.History = history\n}\n\n\n\nfunc (mt *MonitorTrack) Start(monitor Monitor) ", "output": "{\n\tgo func() {\n\t\tmt.timer = time.NewTimer(time.Duration(1) * time.Second)\n\t\tfor _ = range mt.timer.C {\n\t\t\tif mt.Interval > 0 {\n\t\t\t\tmt.timer.Reset(time.Second * time.Duration(mt.Interval))\n\t\t\t}\n\t\t\tvariables := []string{}\n\t\t\tfor variable := range mt.Variables {\n\t\t\t\tvariables = append(variables, variable)\n\t\t\t}\n\t\t\tvalues := monitor.GetValues(variables)\n\t\t\tfor variable, vt := range mt.Variables {\n\t\t\t\tvt.Data = append(vt.Data, values[variable])\n\t\t\t\tif len(vt.Data) > vt.History {\n\t\t\t\t\tvt.Data = vt.Data[len(vt.Data)-vt.History:]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}"} {"input": "package packer\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"golang.org/x/sync/errgroup\"\n)\n\n\n\nfunc TestProgressTracking_open_close(t *testing.T) {\n\tvar bar *uiProgressBar\n\n\ttracker := bar.TrackProgress(\"1,\", 1, 42, ioutil.NopCloser(nil))\n\ttracker.Close()\n\n\ttracker = bar.TrackProgress(\"2,\", 1, 42, ioutil.NopCloser(nil))\n\ttracker.Close()\n}\n\n\n\nfunc TestProgressTracking_races(t *testing.T) {\n\tvar bar *uiProgressBar\n\tg := errgroup.Group{}\n\n\tfor i := 0; i < 100; i++ {\n\t\tg.Go(func() error {\n\t\t\ttxt := []byte(\"foobarbaz dolores\")\n\t\t\tb := bytes.NewReader(txt)\n\t\t\ttracker := bar.TrackProgress(\"file,\", 1, 42, ioutil.NopCloser(b))\n\n\t\t\tfor i := 0; i < 42; i++ {\n\t\t\t\ttracker.Read([]byte(\"i\"))\n\t\t\t}\n\t\t\treturn tracker.Close()\n\t\t})\n\t}\n\n\tif err := g.Wait(); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestProgressTracking_multi_open_close(t *testing.T) ", "output": "{\n\tvar bar *uiProgressBar\n\tg := errgroup.Group{}\n\n\tfor i := 0; i < 100; i++ {\n\t\tg.Go(func() error {\n\t\t\ttracker := bar.TrackProgress(\"file,\", 1, 42, ioutil.NopCloser(nil))\n\t\t\treturn tracker.Close()\n\t\t})\n\t}\n\tif err := g.Wait(); err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package types\n\nimport (\n\t\"testing\"\n)\n\n\n\ntype testPerson struct {\n\tName string\n\tAge uint16\n}\n\nfunc TestStructToHstore(t *testing.T) {\n\ti := testPerson{\"test name\", uint16(23)}\n\th := StructToHstore(i)\n\n\tt.Log(h)\n\n\tif h[\"name\"] != i.Name {\n\t\tt.Fatalf(\"unexpected result:\\n+ %v\\n- %v\", h[\"name\"], i.Name)\n\t}\n\tif h[\"age\"] != i.Age {\n\t\tt.Fatalf(\"unexpected result:\\n+ %v\\n- %v\", h[\"age\"], i.Age)\n\t}\n}\n\nfunc TestHstoreNew(t *testing.T) ", "output": "{\n\ttext := `\"name\"=>\"test\", \"ext\"=>\"\", \"size\"=>\"34508\", \"nov\"=>NULL`\n\n\tvar h = make(Hstore)\n\terr := h.Scan(text)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(h)\n\n\tvalid_s := \"34508\"\n\n\tif h[\"size\"] != valid_s {\n\t\tt.Fatalf(\"unexpected result:\\n+ %v\\n- %v\", h[\"size\"], valid_s)\n\t}\n}"} {"input": "package vagrant\n\nimport (\n\t\"github.com/mitchellh/packer/packer\"\n\t\"testing\"\n)\n\n\n\nfunc TestPostProcessor_ImplementsPostProcessor(t *testing.T) {\n\tvar raw interface{}\n\traw = &PostProcessor{}\n\tif _, ok := raw.(packer.PostProcessor); !ok {\n\t\tt.Fatalf(\"AWS PostProcessor should be a PostProcessor\")\n\t}\n}\n\nfunc TestBuilderPrepare_OutputPath(t *testing.T) {\n\tvar p PostProcessor\n\n\tc := testConfig()\n\tdelete(c, \"output\")\n\terr := p.Configure(c)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tc[\"output\"] = \"bad {{{{.Template}}}}\"\n\terr = p.Configure(c)\n\tif err == nil {\n\t\tt.Fatal(\"should have error\")\n\t}\n}\n\nfunc TestBuilderPrepare_PPConfig(t *testing.T) {\n\tvar p PostProcessor\n\n\tc := testConfig()\n\tc[\"aws\"] = map[string]interface{}{}\n\terr := p.Configure(c)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n}\n\nfunc testConfig() map[string]interface{} ", "output": "{\n\treturn map[string]interface{}{}\n}"} {"input": "package gftest\n\nimport (\n \"errors\"\n \"reflect\"\n \"encoding/json\"\n)\n\nfunc (req *Request) Debug(msg string) { req.t.Log(req.FullPath() + \": %v\", msg) }\n\nfunc (req *Request) NewError(msg string) error {\n\n\terr := errors.New(req.FullPath() + \": \" + msg)\n\treturn err\n}\n\n\n\nfunc (req *Request) Reflect(e interface{}) {\n\tmsg := \"REFLECT VALUE IS NIL\"\n\tif e != nil {\n\t\tmsg = \"REFLECT VALUE IS \"+reflect.TypeOf(e).String()\n\t}\n\treq.NewError(msg)\n}\n\nfunc (req *Request) DebugJSON(i interface{}) {\n\tb, err := json.Marshal(i); if err != nil { req.Error(err); return }\n\treq.Debug(string(b))\n}\n\nfunc (req *Request) Error(e error) ", "output": "{ req.t.Log(e.Error()) }"} {"input": "package testing\n\nimport (\n\tv2net \"github.com/v2ray/v2ray-core/common/net\"\n\t\"github.com/v2ray/v2ray-core/transport/ray\"\n)\n\ntype TestPacketDispatcher struct {\n\tLastPacket chan v2net.Packet\n\tHandler func(packet v2net.Packet, traffic ray.OutboundRay)\n}\n\n\n\nfunc (this *TestPacketDispatcher) DispatchToOutbound(packet v2net.Packet) ray.InboundRay {\n\ttraffic := ray.NewRay()\n\tthis.LastPacket <- packet\n\tgo this.Handler(packet, traffic)\n\n\treturn traffic\n}\n\nfunc NewTestPacketDispatcher(handler func(packet v2net.Packet, traffic ray.OutboundRay)) *TestPacketDispatcher ", "output": "{\n\tif handler == nil {\n\t\thandler = func(packet v2net.Packet, traffic ray.OutboundRay) {\n\t\t\tfor payload := range traffic.OutboundInput() {\n\t\t\t\ttraffic.OutboundOutput() <- payload.Prepend([]byte(\"Processed: \"))\n\t\t\t}\n\t\t\tclose(traffic.OutboundOutput())\n\t\t}\n\t}\n\treturn &TestPacketDispatcher{\n\t\tLastPacket: make(chan v2net.Packet, 16),\n\t\tHandler: handler,\n\t}\n}"} {"input": "package proto\n\nimport (\n\t\"fmt\"\n\t\"net\"\n)\n\n\n\n\n\nfunc (a Addr) NetAddr() (net.Addr, error) {\n\tswitch a.Network {\n\tcase \"tcp\", \"tcp4\", \"tcp6\":\n\t\treturn net.ResolveTCPAddr(a.Network, a.Address)\n\tcase \"udp\", \"udp4\", \"udp6\":\n\t\treturn net.ResolveUDPAddr(a.Network, a.Address)\n\tcase \"unix\", \"unixgram\", \"unixpacket\":\n\t\treturn net.ResolveUnixAddr(a.Network, a.Address)\n\t}\n\treturn nil, fmt.Errorf(\"network %s not supported\", a.Network)\n}\n\n\n\nfunc (m *GossipRequest) GetUser() string {\n\treturn \"node\"\n}\n\nfunc FromNetAddr(addr net.Addr) *Addr ", "output": "{\n\treturn &Addr{\n\t\tNetwork: addr.Network(),\n\t\tAddress: addr.String(),\n\t}\n}"} {"input": "package matcher\n\nimport \"errors\"\n\ntype IntComparator struct{}\n\nfunc (s *IntComparator) Valid(data interface{}) error {\n\tif _, ok := data.(int); !ok {\n\t\treturn errors.New(\"Invalid argument\")\n\t}\n\n\treturn nil\n}\n\nfunc (s *IntComparator) GreaterThan(a, b interface{}) bool {\n\treturn a.(int) > b.(int)\n}\n\n\n\nfunc (s *IntComparator) EqualTo(a, b interface{}) bool {\n\treturn a.(int) == b.(int)\n}\n\nfunc (s *IntComparator) NotEqualTo(a, b interface{}) bool {\n\treturn a.(int) != b.(int)\n}\n\nfunc (s *IntComparator) LessThan(a, b interface{}) bool ", "output": "{\n\treturn a.(int) < b.(int)\n}"} {"input": "\n\nfunc mergeSort(nums []int, start, end int) int {\n if end - start <= 1 {\n return 0\n }\n mid := (start + end) >> 1\n count := mergeSort(nums, start, mid) + mergeSort(nums, mid, end)\n \n buf := make([]int, end-start)\n bufTail := 0\n j, k := mid, mid\n for i := start; i < mid; i++ {\n for k < end && 2*nums[k] < nums[i] {\n k++\n }\n for j < end && nums[j] < nums[i] {\n buf[bufTail] = nums[j]\n bufTail++\n j++\n }\n buf[bufTail] = nums[i]\n bufTail++\n \n count += k - mid\n }\n copy(nums[start:], buf[:bufTail])\n \n return count\n}\n\nfunc reversePairs(nums []int) int ", "output": "{\n return mergeSort(nums, 0, len(nums))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\ntype myType int\n\n\n\nfunc main() {\n\tvar z myType = 123\n\n\tz.println()\n}\n\nfunc (t myType) println() ", "output": "{\n\tfmt.Println(t)\n}"} {"input": "package joystick\n\nimport (\n\t\"errors\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc Open(id int) (Joystick, error) ", "output": "{\n\treturn nil, errors.New(\"Joystick API unsupported on this platform\")\n}"} {"input": "package host2dnslabel\n\nimport (\n\t\"testing\"\n\n\t\"github.com/containerum/chkit/pkg/util/validation\"\n)\n\n\n\nfunc TestHost2DNSLabel(test *testing.T) ", "output": "{\n\tvar hosts = []string{\n\t\t\"google.com\",\n\t\t\"123.com\",\n\t\t\"asndl0-😏ю.loc\",\n\t\t\"as=-0e20 -doqd- 3-- -s.saalc=asd.cpks\",\n\t\t\"asdasd d-ds d----- --.net\",\n\t}\n\tfor _, host := range hosts {\n\t\tDNSlabel := Host2DNSLabel(host)\n\t\ttest.Logf(\"%q -> %q\", host, DNSlabel)\n\t\tif err := validation.DNSLabel(DNSlabel); err != nil {\n\t\t\ttest.Fatal(err)\n\t\t}\n\t}\n}"} {"input": "package strategy\n\nimport (\n\t\"fmt\"\n\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n\t\"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache\"\n\n\t\"github.com/kubernetes-incubator/cluster-capacity/pkg/framework/store\"\n)\n\ntype Strategy interface {\n\tAdd(obj interface{}) error\n\n\tUpdate(obj interface{}) error\n\n\tDelete(obj interface{}) error\n}\n\ntype predictiveStrategy struct {\n\tresourceStore store.ResourceStore\n\n\tnodeInfo map[string]*schedulercache.NodeInfo\n}\n\nfunc (s *predictiveStrategy) addPod(pod *v1.Pod) error {\n\n\tpod.Status.Phase = v1.PodRunning\n\n\terr := s.resourceStore.Update(\"pods\", metav1.Object(pod))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to add new node: %v\", err)\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc (s *predictiveStrategy) Add(obj interface{}) error {\n\tswitch item := obj.(type) {\n\tcase *v1.Pod:\n\t\treturn s.addPod(item)\n\tdefault:\n\t\treturn fmt.Errorf(\"resource kind not recognized\")\n\t}\n}\n\nfunc (s *predictiveStrategy) Update(obj interface{}) error {\n\treturn fmt.Errorf(\"Not implemented yet\")\n}\n\n\n\nfunc NewPredictiveStrategy(resourceStore store.ResourceStore) *predictiveStrategy {\n\treturn &predictiveStrategy{\n\t\tresourceStore: resourceStore,\n\t}\n}\n\nfunc (s *predictiveStrategy) Delete(obj interface{}) error ", "output": "{\n\treturn fmt.Errorf(\"Not implemented yet\")\n}"} {"input": "package alicloud\n\ntype PrimaryKeyTypeString string\n\nconst (\n\tIntegerType = PrimaryKeyTypeString(\"Integer\")\n\tStringType = PrimaryKeyTypeString(\"String\")\n\tBinaryType = PrimaryKeyTypeString(\"Binary\")\n)\n\ntype InstanceAccessedByType string\n\nconst (\n\tAnyNetwork = InstanceAccessedByType(\"Any\")\n\tVpcOnly = InstanceAccessedByType(\"Vpc\")\n\tVpcOrConsole = InstanceAccessedByType(\"ConsoleOrVpc\")\n)\n\ntype OtsInstanceType string\n\nconst (\n\tOtsCapacity = OtsInstanceType(\"Capacity\")\n\tOtsHighPerformance = OtsInstanceType(\"HighPerformance\")\n)\n\nfunc convertInstanceAccessedBy(accessed InstanceAccessedByType) string {\n\tswitch accessed {\n\tcase VpcOnly:\n\t\treturn \"VPC\"\n\tcase VpcOrConsole:\n\t\treturn \"VPC_CONSOLE\"\n\tdefault:\n\t\treturn \"NORMAL\"\n\t}\n}\n\n\n\nfunc convertInstanceType(instanceType OtsInstanceType) string {\n\tswitch instanceType {\n\tcase OtsHighPerformance:\n\t\treturn \"SSD\"\n\tdefault:\n\t\treturn \"HYBRID\"\n\t}\n}\n\nfunc convertInstanceTypeRevert(instanceType string) OtsInstanceType {\n\tswitch instanceType {\n\tcase \"SSD\":\n\t\treturn OtsHighPerformance\n\tdefault:\n\t\treturn OtsCapacity\n\t}\n}\n\n\nfunc convertOtsInstanceStatus(status Status) int {\n\tswitch status {\n\tcase Running:\n\t\treturn 1\n\tcase DisabledStatus:\n\t\treturn 2\n\tcase Deleting:\n\t\treturn 3\n\tdefault:\n\t\treturn -1\n\t}\n}\n\nfunc convertInstanceAccessedByRevert(network string) InstanceAccessedByType ", "output": "{\n\tswitch network {\n\tcase \"VPC\":\n\t\treturn VpcOnly\n\tcase \"VPC_CONSOLE\":\n\t\treturn VpcOrConsole\n\tdefault:\n\t\treturn AnyNetwork\n\t}\n}"} {"input": "package hamster\n\nimport (\n\t\"net/http\"\n)\n\nfunc (s *Server) serveError(w http.ResponseWriter, err error, user_message string, base_message string, status int) {\n\n\tlog_message := base_message + \" : \" + user_message\n\ts.logger.Printf(\"Error %v: %v \\n\", log_message, err)\n\thttp.Error(w, base_message, status)\n\n}\n\n\nfunc (s *Server) unauthorized(r *http.Request, w http.ResponseWriter, err error, msg string) {\n\ts.serveError(w, err, msg, \"Unauthorized\", http.StatusUnauthorized)\n}\n\nfunc (s *Server) notFound(r *http.Request, w http.ResponseWriter, err error, msg string) {\n\ts.serveError(w, err, msg, \"Not found\", http.StatusNotFound)\n\n}\n\nfunc (s *Server) internalError(r *http.Request, w http.ResponseWriter, err error, msg string) {\n\ts.serveError(w, err, msg, \"Internal Server Error\", http.StatusInternalServerError)\n\n}\n\nfunc (s *Server) badRequest(r *http.Request, w http.ResponseWriter, err error, msg string) ", "output": "{\n\ts.serveError(w, err, msg, \"Bad Request\", http.StatusBadRequest)\n}"} {"input": "package iotdataplane_test\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/service/iotdataplane\"\n)\n\nfunc TestRequireEndpointIfRegionProvided(t *testing.T) {\n\tsvc := iotdataplane.New(&aws.Config{\n\t\tRegion: aws.String(\"mock-region\"),\n\t\tDisableParamValidation: aws.Bool(true),\n\t})\n\treq, _ := svc.GetThingShadowRequest(nil)\n\terr := req.Build()\n\n\tassert.Equal(t, \"\", svc.Endpoint)\n\tassert.Error(t, err)\n\tassert.Equal(t, aws.ErrMissingEndpoint, err)\n}\n\nfunc TestRequireEndpointIfNoRegionProvided(t *testing.T) {\n\tsvc := iotdataplane.New(&aws.Config{\n\t\tRegion: aws.String(\"\"),\n\t\tDisableParamValidation: aws.Bool(true),\n\t})\n\treq, _ := svc.GetThingShadowRequest(nil)\n\terr := req.Build()\n\n\tassert.Equal(t, \"\", svc.Endpoint)\n\tassert.Error(t, err)\n\tassert.Equal(t, aws.ErrMissingEndpoint, err)\n}\n\n\n\nfunc TestRequireEndpointUsed(t *testing.T) ", "output": "{\n\tsvc := iotdataplane.New(&aws.Config{\n\t\tRegion: aws.String(\"mock-region\"),\n\t\tDisableParamValidation: aws.Bool(true),\n\t\tEndpoint: aws.String(\"https://endpoint\"),\n\t})\n\treq, _ := svc.GetThingShadowRequest(nil)\n\terr := req.Build()\n\n\tassert.Equal(t, \"https://endpoint\", svc.Endpoint)\n\tassert.NoError(t, err)\n}"} {"input": "package listener\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestPatriciaOnePrefix(t *testing.T) {\n\ttestPTree(t, \"prefix\")\n}\n\nfunc TestPatriciaNonOverlapping(t *testing.T) {\n\ttestPTree(t, \"foo\", \"bar\", \"dummy\")\n}\n\nfunc TestPatriciaOverlapping(t *testing.T) {\n\ttestPTree(t, \"foo\", \"far\", \"farther\", \"boo\", \"ba\", \"bar\")\n}\n\nfunc testPTree(t *testing.T, strs ...string) ", "output": "{\n\tpt := newPatriciaTreeString(strs...)\n\tfor _, s := range strs {\n\t\tif !pt.match(strings.NewReader(s)) {\n\t\t\tt.Errorf(\"%s is not matched by %s\", s, s)\n\t\t}\n\n\t\tif !pt.matchPrefix(strings.NewReader(s + s)) {\n\t\t\tt.Errorf(\"%s is not matched as a prefix by %s\", s+s, s)\n\t\t}\n\n\t\tif pt.match(strings.NewReader(s + s)) {\n\t\t\tt.Errorf(\"%s matches %s\", s+s, s)\n\t\t}\n\n\t\tpt.matchPrefix(strings.NewReader(s[:len(s)-1]))\n\t\tpt.match(strings.NewReader(s[:len(s)-1]))\n\t\tpt.matchPrefix(strings.NewReader(s + \"$\"))\n\t\tpt.match(strings.NewReader(s + \"$\"))\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/adjust/rmq\"\n)\n\nfunc main() {\n\tconnection := rmq.OpenConnection(\"handler\", \"tcp\", \"localhost:6379\", 2)\n\thttp.Handle(\"/overview\", NewHandler(connection))\n\tfmt.Printf(\"Handler listening on http://localhost:3333/overview\\n\")\n\thttp.ListenAndServe(\":3333\", nil)\n}\n\ntype Handler struct {\n\tconnection rmq.Connection\n}\n\n\n\nfunc (handler *Handler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {\n\tlayout := request.FormValue(\"layout\")\n\trefresh := request.FormValue(\"refresh\")\n\n\tqueues := handler.connection.GetOpenQueues()\n\tstats := handler.connection.CollectStats(queues)\n\tlog.Printf(\"queue stats\\n%s\", stats)\n\tfmt.Fprint(writer, stats.GetHtml(layout, refresh))\n}\n\nfunc NewHandler(connection rmq.Connection) *Handler ", "output": "{\n\treturn &Handler{connection: connection}\n}"} {"input": "package provider\n\nimport (\n\t\"time\"\n\t\"fmt\"\n\t\"reflect\"\n)\n\n\ntype Error struct {\n\tValue error\n}\n\n\ntype Result struct {\n\tValue interface{}\n}\n\n\ntype Provider interface {\n\tInitialise(host string, params map[string][]string) (error)\n\tSet(name string, data interface{}, expiry time.Duration) (error)\n\tGet(name string) (*Result)\n}\n\n\n\n\n\n\n\nfunc (i *Result) Bytes() ([]byte, error) {\n\n\tval := i.Value\n\tswitch val := val.(type) {\n\tcase string:\n\t\treturn []byte(val), nil\n\tcase []byte:\n\t\treturn val, nil\n\tcase Error:\n\t\treturn nil, val.Value\n\t}\n\treturn nil, fmt.Errorf(\"cache::provider: unable to convert %v to []byte\", reflect.TypeOf(val))\n}\n\nfunc (i *Result) String() (string, error) ", "output": "{\n\n\tval := i.Value\n\tswitch val := val.(type) {\n\tcase string:\n\t\treturn val, nil\n\tcase []byte:\n\t\treturn string(val), nil\n\tcase nil:\n\t\treturn \"\", nil\n\tcase Error:\n\t\treturn \"\", val.Value\n\t}\n\treturn \"\", fmt.Errorf(\"cache::provider: unable to convert %v to string\", reflect.TypeOf(val))\n}"} {"input": "package git\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/Originate/git-town/src/command\"\n\t\"github.com/Originate/git-town/src/util\"\n)\n\n\n\nfunc EnsureDoesNotHaveConflicts() {\n\tutil.Ensure(!HasConflicts(), \"You must resolve the conflicts before continuing\")\n}\n\n\n\nfunc EnsureDoesNotHaveOpenChanges(message string) {\n\tutil.Ensure(!HasOpenChanges(), \"You have uncommitted changes. \"+message)\n}\n\n\nvar rootDirectory string\n\n\n\nfunc GetRootDirectory() string {\n\tif rootDirectory == \"\" {\n\t\trootDirectory = command.MustRun(\"git\", \"rev-parse\", \"--show-toplevel\").OutputSanitized()\n\t}\n\treturn rootDirectory\n}\n\n\nfunc HasConflicts() bool {\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"Unmerged paths\")\n}\n\n\nfunc HasOpenChanges() bool {\n\treturn command.MustRun(\"git\", \"status\", \"--porcelain\").OutputSanitized() != \"\"\n}\n\n\n\n\n\n\n\nfunc IsMergeInProgress() bool {\n\t_, err := os.Stat(fmt.Sprintf(\"%s/.git/MERGE_HEAD\", GetRootDirectory()))\n\treturn err == nil\n}\n\n\n\nfunc IsRebaseInProgress() bool {\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"rebase in progress\")\n}\n\nfunc HasShippableChanges(branchName string) bool ", "output": "{\n\treturn command.MustRun(\"git\", \"diff\", Config().GetMainBranch()+\"..\"+branchName).OutputSanitized() != \"\"\n}"} {"input": "package types\n\nimport (\n\t\"github.com/coreos/ignition/v2/config/shared/errors\"\n\n\t\"github.com/coreos/vcontext/path\"\n\t\"github.com/coreos/vcontext/report\"\n)\n\nfunc (r Raid) Key() string {\n\treturn r.Name\n}\n\n\n\nfunc (ra Raid) Validate(c path.ContextPath) (r report.Report) {\n\tr.AddOnError(c.Append(\"level\"), ra.validateLevel())\n\tif len(ra.Devices) == 0 {\n\t\tr.AddOnError(c.Append(\"devices\"), errors.ErrRaidDevicesRequired)\n\t}\n\treturn\n}\n\nfunc (r Raid) validateLevel() error {\n\tswitch r.Level {\n\tcase \"linear\", \"raid0\", \"0\", \"stripe\":\n\t\tif r.Spares != nil && *r.Spares != 0 {\n\t\t\treturn errors.ErrSparesUnsupportedForLevel\n\t\t}\n\tcase \"raid1\", \"1\", \"mirror\":\n\tcase \"raid4\", \"4\":\n\tcase \"raid5\", \"5\":\n\tcase \"raid6\", \"6\":\n\tcase \"raid10\", \"10\":\n\tdefault:\n\t\treturn errors.ErrUnrecognizedRaidLevel\n\t}\n\n\treturn nil\n}\n\nfunc (r Raid) IgnoreDuplicates() map[string]struct{} ", "output": "{\n\treturn map[string]struct{}{\n\t\t\"Options\": {},\n\t}\n}"} {"input": "package mailgun\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/config\"\n\t\"github.com/hashicorp/terraform/helper/schema\"\n\t\"github.com/hashicorp/terraform/terraform\"\n\t\"github.com/pearkes/mailgun\"\n)\n\nvar testAccProviders map[string]terraform.ResourceProvider\nvar testAccProvider *schema.Provider\n\nfunc init() {\n\ttestAccProvider = Provider().(*schema.Provider)\n\ttestAccProviders = map[string]terraform.ResourceProvider{\n\t\t\"mailgun\": testAccProvider,\n\t}\n}\n\nfunc TestProvider(t *testing.T) {\n\tif err := Provider().(*schema.Provider).InternalValidate(); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n}\n\nfunc TestProvider_impl(t *testing.T) {\n\tvar _ terraform.ResourceProvider = Provider()\n}\n\n\n\nfunc testAccPreCheck(t *testing.T) {\n\tif v := os.Getenv(\"MAILGUN_API_KEY\"); v == \"\" {\n\t\tt.Fatal(\"MAILGUN_API_KEY must be set for acceptance tests\")\n\t}\n}\n\nfunc TestProviderConfigure(t *testing.T) ", "output": "{\n\tvar expectedKey string\n\n\tif v := os.Getenv(\"MAILGUN_API_KEY\"); v != \"\" {\n\t\texpectedKey = v\n\t} else {\n\t\texpectedKey = \"foo\"\n\t}\n\n\traw := map[string]interface{}{\n\t\t\"api_key\": expectedKey,\n\t}\n\n\trawConfig, err := config.NewRawConfig(raw)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\trp := Provider().(*schema.Provider)\n\terr = rp.Configure(terraform.NewResourceConfig(rawConfig))\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tconfig := rp.Meta().(*mailgun.Client)\n\tif config.ApiKey != expectedKey {\n\t\tt.Fatalf(\"bad: %#v\", config)\n\t}\n}"} {"input": "package caaa\n\nimport (\n\t\"encoding/xml\"\n\n\t\"github.com/fgrid/iso20022\"\n)\n\ntype Document00900101 struct {\n\tXMLName xml.Name `xml:\"urn:iso:std:iso:20022:tech:xsd:caaa.009.001.01 Document\"`\n\tMessage *AcceptorReconciliationRequestV01 `xml:\"AccptrRcncltnReq\"`\n}\n\nfunc (d *Document00900101) AddMessage() *AcceptorReconciliationRequestV01 {\n\td.Message = new(AcceptorReconciliationRequestV01)\n\treturn d.Message\n}\n\n\n\n\n\n\ntype AcceptorReconciliationRequestV01 struct {\n\n\tHeader *iso20022.Header1 `xml:\"Hdr\"`\n\n\tReconciliationRequest *iso20022.AcceptorReconciliationRequest1 `xml:\"RcncltnReq\"`\n\n\tSecurityTrailer *iso20022.ContentInformationType3 `xml:\"SctyTrlr\"`\n}\n\nfunc (a *AcceptorReconciliationRequestV01) AddHeader() *iso20022.Header1 {\n\ta.Header = new(iso20022.Header1)\n\treturn a.Header\n}\n\nfunc (a *AcceptorReconciliationRequestV01) AddReconciliationRequest() *iso20022.AcceptorReconciliationRequest1 {\n\ta.ReconciliationRequest = new(iso20022.AcceptorReconciliationRequest1)\n\treturn a.ReconciliationRequest\n}\n\n\n\nfunc (a *AcceptorReconciliationRequestV01) AddSecurityTrailer() *iso20022.ContentInformationType3 ", "output": "{\n\ta.SecurityTrailer = new(iso20022.ContentInformationType3)\n\treturn a.SecurityTrailer\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/bitly/go-nsq\"\n)\n\n\n\ntype BackendQueue interface {\n\tPut([]byte) error\n\tReadChan() chan []byte \n\tClose() error\n\tDelete() error\n\tDepth() int64\n\tEmpty() error\n}\n\ntype DummyBackendQueue struct {\n\treadChan chan []byte\n}\n\nfunc NewDummyBackendQueue() BackendQueue {\n\treturn &DummyBackendQueue{readChan: make(chan []byte)}\n}\n\nfunc (d *DummyBackendQueue) Put([]byte) error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) ReadChan() chan []byte {\n\treturn d.readChan\n}\n\nfunc (d *DummyBackendQueue) Close() error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Delete() error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Depth() int64 {\n\treturn int64(0)\n}\n\n\n\nfunc WriteMessageToBackend(buf *bytes.Buffer, msg *nsq.Message, bq BackendQueue) error {\n\tbuf.Reset()\n\terr := msg.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = bq.Put(buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Empty() error ", "output": "{\n\treturn nil\n}"} {"input": "package goschema\n\ntype nullType struct {\n\tbaseType\n}\n\n\n\nfunc (g *nullType) docString(field string, docPrefix string) string {\n\treturn docString(field, g.description, docPrefix, \"must be nothing (null)\")\n}\n\nfunc (g *nullType) asJSONSchema() map[string]interface{} {\n\tdata := map[string]interface{}{\n\t\t\"type\": \"null\",\n\t}\n\tif g.description != \"\" {\n\t\tdata[\"description\"] = g.description\n\t}\n\treturn data\n}\n\nfunc NewNullType(description string) NullType ", "output": "{\n\treturn &nullType{\n\t\tbaseType: baseType{\n\t\t\tdescription: description,\n\t\t},\n\t}\n}"} {"input": "package main\n\nimport \"math\"\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Distance(lat1, lon1, lat2, lon2 float64) float64 {\n\tvar la1, lo1, la2, lo2, r float64\n\tla1 = lat1 * math.Pi / 180\n\tlo1 = lon1 * math.Pi / 180\n\tla2 = lat2 * math.Pi / 180\n\tlo2 = lon2 * math.Pi / 180\n\n\tr = 6378100 \n\n\th := hsin(la2-la1) + math.Cos(la1)*math.Cos(la2)*hsin(lo2-lo1)\n\n\treturn 2 * r * math.Asin(math.Sqrt(h))\n}\n\nfunc hsin(theta float64) float64 ", "output": "{\n\treturn math.Pow(math.Sin(theta/2), 2)\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar min, max int\n\tmin, max = MinMax(78, 65)\n\tfmt.Printf(\"Minimum is: %d, Maximum is: %d\\n\", min, max)\n}\n\n\n\nfunc MinMax(a int, b int) (min int, max int) ", "output": "{\n\tif a < b {\n\t\tmin = a\n\t\tmax = b\n\t} else {\t\t\n\t\tmin = b\n\t\tmax = a\n\t}\n\treturn\n}"} {"input": "package gitea\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\n\ntype PublicKey struct {\n\tID int64 `json:\"id\"`\n\tKey string `json:\"key\"`\n\tURL string `json:\"url,omitempty\"`\n\tTitle string `json:\"title,omitempty\"`\n\tCreated time.Time `json:\"created_at,omitempty\"`\n}\n\n\n\n\n\nfunc (c *Client) ListMyPublicKeys() ([]*PublicKey, error) {\n\tkeys := make([]*PublicKey, 0, 10)\n\treturn keys, c.getParsedResponse(\"GET\", \"/user/keys\", nil, nil, &keys)\n}\n\n\nfunc (c *Client) GetPublicKey(keyID int64) (*PublicKey, error) {\n\tkey := new(PublicKey)\n\treturn key, c.getParsedResponse(\"GET\", fmt.Sprintf(\"/user/keys/%d\", keyID), nil, nil, &key)\n}\n\n\nfunc (c *Client) CreatePublicKey(opt CreateKeyOption) (*PublicKey, error) {\n\tbody, err := json.Marshal(&opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkey := new(PublicKey)\n\treturn key, c.getParsedResponse(\"POST\", \"/user/keys\", jsonHeader, bytes.NewReader(body), key)\n}\n\n\nfunc (c *Client) DeletePublicKey(keyID int64) error {\n\t_, err := c.getResponse(\"DELETE\", fmt.Sprintf(\"/user/keys/%d\", keyID), nil, nil)\n\treturn err\n}\n\nfunc (c *Client) ListPublicKeys(user string) ([]*PublicKey, error) ", "output": "{\n\tkeys := make([]*PublicKey, 0, 10)\n\treturn keys, c.getParsedResponse(\"GET\", fmt.Sprintf(\"/users/%s/keys\", user), nil, nil, &keys)\n}"} {"input": "package plotter\n\nimport (\n\t\"image/color\"\n\n\t\"github.com/gonum/plot\"\n\t\"github.com/gonum/plot/vg\"\n\t\"github.com/gonum/plot/vg/draw\"\n)\n\n\n\n\ntype GlyphBoxes struct {\n\tdraw.LineStyle\n}\n\n\n\nfunc (g GlyphBoxes) Plot(c draw.Canvas, plt *plot.Plot) {\n\tfor _, b := range plt.GlyphBoxes(plt) {\n\t\tx := c.X(b.X) + b.Rectangle.Min.X\n\t\ty := c.Y(b.Y) + b.Rectangle.Min.Y\n\t\tc.StrokeLines(g.LineStyle, []vg.Point{\n\t\t\t{x, y},\n\t\t\t{x + b.Rectangle.Size().X, y},\n\t\t\t{x + b.Rectangle.Size().X, y + b.Rectangle.Size().Y},\n\t\t\t{x, y + b.Rectangle.Size().Y},\n\t\t\t{x, y},\n\t\t})\n\t}\n}\n\nfunc NewGlyphBoxes() *GlyphBoxes ", "output": "{\n\tg := new(GlyphBoxes)\n\tg.Color = color.RGBA{R: 255, A: 255}\n\tg.Width = vg.Points(0.25)\n\treturn g\n}"} {"input": "package gopnsconfig\n\nimport (\n\t\"log\"\n)\n\ntype BaseConfigStruct struct {\n\tPortValue string\n\tMetricsServerValue string\n\tMetricsAPIKeyValue string\n\tMetricsPrefixValue string\n}\n\nfunc (this *BaseConfigStruct) Port() string {\n\treturn this.PortValue\n}\n\nfunc (this *BaseConfigStruct) MetricsAPIKey() string {\n\treturn this.MetricsAPIKeyValue\n}\n\nfunc (this *BaseConfigStruct) MetricsServer() string {\n\treturn this.MetricsServerValue\n}\n\n\n\ntype BaseConfig interface {\n\tPort() string\n\tMetricsServer() string\n\tMetricsAPIKey() string\n\tMetricsPrefix() string\n}\n\nfunc parseBaseConfig(baseConfig *ConfigFile) BaseConfig {\n\tport, err := baseConfig.GetString(\"default\", \"port\")\n\tcheckError(\"Unable to find Server Port\", err)\n\n\tmetricsServer, err := baseConfig.GetString(\"default\", \"metrics-server\")\n\tcheckError(\"Unable to find metrics server\", err)\n\n\tmetricsKey, err := baseConfig.GetString(\"default\", \"metrics-api-key\")\n\tif err != nil {\n\t\tlog.Println(\"Unable to find metrics-api-key using empty string\")\n\t\tmetricsKey = \"\"\n\t}\n\n\tmetricsPrefix, err := baseConfig.GetString(\"default\", \"metrics-prefix\")\n\tif err != nil {\n\t\tlog.Println(\"Unable to find metrics prefix using empty string\")\n\t\tmetricsPrefix = \"\"\n\t}\n\n\tbaseConfigInstance := &BaseConfigStruct{port, metricsServer, metricsKey, metricsPrefix}\n\treturn baseConfigInstance\n\n}\n\nfunc (this *BaseConfigStruct) MetricsPrefix() string ", "output": "{\n\treturn this.MetricsPrefixValue\n}"} {"input": "package distribute\n\nimport (\n \"net/rpc\"\n \"net/http\"\n \"fmt\"\n)\n\ntype Worker struct {\n addr string\n addUrlChannel chan bool\n}\n\nfunc initWorker(addr string) *Worker{\n w := &Worker{}\n w.addr = addr\n w.addUrlChannel = make(chan bool)\n return w\n}\n\n\n\nfunc register(mAddr, wAddr string) {\n args := &RegisterArgs{}\n args.Worker = wAddr\n var reply RegisterReply\n call(mAddr, \"Master.Register\", args, &reply)\n}\n\nfunc (w *Worker) Dojob(args *DojobArgs, res *DojobReply) error {\n fmt.Println(\"DoJob: JobType \", args.JobType)\n switch args.JobType {\n case \"Crawl\":\n \n \n \n }\n return nil\n}\n\nfunc startRpcWorker(w *Worker) {\n \n rpc.Register(w)\n rpc.HandleHTTP()\n err := http.ListenAndServe(w.addr, nil)\n fmt.Println(\"RegistrationServer: accept error\", err)\n \n \n \n \n \n \n}\n\nfunc RunWorker(mAddr, wAddr string) ", "output": "{\n fmt.Println(\"=======RunWorker Begin=======\")\n w := initWorker(wAddr)\n \n register(mAddr, w.addr)\n fmt.Println(\"=======RunWorker End=======\")\n \n \n \n \n \n \n \n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/mitchellh/cli\"\n)\n\nfunc main() {\n\tos.Exit(Run(os.Args[1:]))\n}\n\n\n\nfunc RunCustom(args []string, commands map[string]cli.CommandFactory) int {\n\tfor _, arg := range args {\n\t\tif arg == \"-v\" || arg == \"-version\" || arg == \"--version\" {\n\t\t\tnewArgs := make([]string, len(args)+1)\n\t\t\tnewArgs[0] = \"version\"\n\t\t\tcopy(newArgs[1:], args)\n\t\t\targs = newArgs\n\t\t\tbreak\n\t\t}\n\t}\n\n\tcommandsInclude := make([]string, 0, len(commands))\n\tfor k, _ := range commands {\n\t\tswitch k {\n\t\tcase \"executor\":\n\t\tcase \"syslog\":\n\t\tdefault:\n\t\t\tcommandsInclude = append(commandsInclude, k)\n\t\t}\n\t}\n\n\tcli := &cli.CLI{\n\t\tArgs: args,\n\t\tCommands: commands,\n\t\tHelpFunc: cli.FilteredHelpFunc(commandsInclude, cli.BasicHelpFunc(\"nomad\")),\n\t}\n\n\texitCode, err := cli.Run()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error executing CLI: %s\\n\", err.Error())\n\t\treturn 1\n\t}\n\n\treturn exitCode\n}\n\nfunc Run(args []string) int ", "output": "{\n\treturn RunCustom(args, Commands(nil))\n}"} {"input": "package osquery\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/prometheus/common/log\"\n\t\"os/exec\"\n\t\"github.com/zwopir/osquery_exporter/model\"\n\t\"time\"\n)\n\n\ntype OsqueryRunner struct {\n\texecutable string\n\ttimeout time.Duration\n}\n\n\n\nfunc NewRunner(executable, timeout string) (*OsqueryRunner, error) {\n\tto, err := time.ParseDuration(timeout)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't parse timeout for runner: %s\", err)\n\t}\n\texe, err := exec.LookPath(executable)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"osqueryi executable not found in %s: %s\", executable, err)\n\t}\n\n\tlog.Infof(\"creating runner on executable %q with timeout %s\", exe, timeout)\n\treturn &OsqueryRunner{\n\t\texecutable: exe,\n\t\ttimeout: to,\n\t}, nil\n}\n\n\n\n\n\nfunc (runner *OsqueryRunner) Run(query string) (*model.OsqueryResult, error) ", "output": "{\n\tvar items []model.OsqueryItem\n\tbegin := time.Now()\n\tctx, cancel := context.WithTimeout(context.Background(), runner.timeout)\n\tdefer cancel()\n\tcmd := exec.CommandContext(ctx, runner.executable, \"--json\", query)\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debugf(\"running query %q\", query)\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := json.NewDecoder(stdout).Decode(&items); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := cmd.Wait(); err != nil {\n\t\treturn nil, err\n\t}\n\tduration := time.Since(begin)\n\treturn &model.OsqueryResult{\n\t\tItems: items,\n\t\tRuntime: duration,\n\t}, nil\n}"} {"input": "package state\n\nimport (\n\t\"context\"\n)\n\ntype envKey struct{}\n\n\n\n\n\n\n\n\nfunc FromContext(ctx context.Context) Store {\n\tif e, ok := ctx.Value(envKey{}).(Store); ok {\n\t\treturn e\n\t}\n\tpanic(\"no Store found in context\")\n}\n\n\ntype fail interface {\n\tError(args ...interface{})\n}\n\n\nfunc GetStringOrFail(ctx context.Context, t fail, key string) string {\n\tvalue := \"\"\n\tstate := FromContext(ctx)\n\tif err := state.Get(ctx, key, &value); err != nil {\n\t\tt.Error(err)\n\t}\n\treturn value\n}\n\n\nfunc GetOrFail(ctx context.Context, t fail, key string, value interface{}) {\n\tstate := FromContext(ctx)\n\tif err := state.Get(ctx, key, value); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\n\nfunc SetOrFail(ctx context.Context, t fail, key string, value interface{}) {\n\tstate := FromContext(ctx)\n\tif err := state.Set(ctx, key, value); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc ContextWith(ctx context.Context, s Store) context.Context ", "output": "{\n\treturn context.WithValue(ctx, envKey{}, s)\n}"} {"input": "package splitter\n\nimport (\n\t\"fmt\"\n)\n\n\nfunc PutSplitItem(item SplitItem) {\n\tswitch item.(type) {\n\tcase *GraphiteSplitItem:\n\t\tputGraphiteItem(item.(*GraphiteSplitItem))\n\tcase *StatsdSplitItem:\n\t\tputStatsdItem(item.(*StatsdSplitItem))\n\tcase *CarbonTwoSplitItem:\n\t\tputCarbonTwoItem(item.(*CarbonTwoSplitItem))\n\tcase *RegexSplitItem:\n\t\tputRegexItem(item.(*RegexSplitItem))\n\tcase *JsonSplitItem:\n\t\tputJsonItem(item.(*JsonSplitItem))\n\t}\n\n}\n\n\n\nfunc NewSplitterItem(name string, conf map[string]interface{}) (Splitter, error) ", "output": "{\n\tswitch {\n\tcase name == \"statsd\":\n\t\treturn NewStatsdSplitter(conf)\n\tcase name == \"graphite\":\n\t\treturn NewGraphiteSplitter(conf)\n\tcase name == \"carbon2\":\n\t\treturn NewCarbonTwoSplitter(conf)\n\tcase name == \"regex\":\n\t\treturn NewRegExSplitter(conf)\n\tcase name == \"opentsdb\":\n\t\treturn NewOpenTSDBSplitter(conf)\n\tcase name == \"json\":\n\t\treturn NewJsonSplitter(conf)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Invalid splitter `%s`\", name)\n\t}\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\n\t\"strings\"\n)\n\n\ntype ServerGroupMember struct {\n\tInstanceUuid string `json:\"instance_uuid\"`\n}\n\n\n\nfunc (o ServerGroupMember) String() string ", "output": "{\n\tdata, _ := json.Marshal(o)\n\treturn strings.Join([]string{\"ServerGroupMember\", string(data)}, \" \")\n}"} {"input": "package python\n\n\nimport \"C\"\nimport \"unsafe\"\n\nfunc PyUnicodeFromString(s string) unsafe.Pointer {\n\tcstr := C.CString(s)\n\tret := PyUnicode_FromString(cstr)\n\treturn unsafe.Pointer(ret)\n}\n\n\n\nfunc PyImportImport(modulePtr unsafe.Pointer) unsafe.Pointer ", "output": "{\n\tptr := (*C.PyObject)(modulePtr)\n\tret := PyImport_Import(ptr)\n\treturn unsafe.Pointer(ret)\n}"} {"input": "package servo_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n\t\"github.com/fgrosse/servo\"\n\t\"fmt\"\n)\n\nfunc TestServo(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Servo Test Suite\")\n}\n\ntype TestBundle struct {}\n\nfunc (b *TestBundle) Boot(kernel *servo.Kernel) {\n\tkernel.RegisterType(\"test_bundle.my_type\", NewService)\n}\n\ntype SomeService struct {}\n\nfunc NewRecursiveService(*SomeService) *SomeService {\n\treturn &SomeService{}\n}\n\nfunc NewService() *SomeService {\n\treturn &SomeService{}\n}\n\n\n\n\ntype ServerMock struct {\n\tRunHasBeenCalled bool\n\tReturnError bool\n\n\tParameter1, Parameter2 string\n}\n\nfunc NewServerMockWithParams(param1, param2 string) *ServerMock {\n\tExpect(param1).To(Equal(\"foo\"), `NewServerMockWithParams should always be called with the values \"foo\" and \"bar\"`)\n\tExpect(param2).To(Equal(\"bar\"), `NewServerMockWithParams should always be called with the values \"foo\" and \"bar\"`)\n\n\treturn &ServerMock{\n\t\tParameter1: param1,\n\t\tParameter2: param2,\n\t}\n}\n\nfunc (s *ServerMock) Run() error {\n\ts.RunHasBeenCalled = true\n\tif s.ReturnError {\n\t\treturn fmt.Errorf(\"ServerMock was told to return an error!\")\n\t}\n\n\treturn nil\n}\n\nfunc NewServiceWithParam(param interface{}) *SomeService ", "output": "{\n\tpanic(param)\n\treturn &SomeService{}\n}"} {"input": "package iso20022\n\n\ntype RemittanceInformation8 struct {\n\n\tRemittanceIdentification *Max35Text `xml:\"RmtId,omitempty\"`\n\n\tUnstructured []*Max140Text `xml:\"Ustrd,omitempty\"`\n\n\tStructured []*StructuredRemittanceInformation10 `xml:\"Strd,omitempty\"`\n\n\tOriginalPaymentInformation *OriginalPaymentInformation6 `xml:\"OrgnlPmtInf\"`\n}\n\n\n\nfunc (r *RemittanceInformation8) AddUnstructured(value string) {\n\tr.Unstructured = append(r.Unstructured, (*Max140Text)(&value))\n}\n\nfunc (r *RemittanceInformation8) AddStructured() *StructuredRemittanceInformation10 {\n\tnewValue := new(StructuredRemittanceInformation10)\n\tr.Structured = append(r.Structured, newValue)\n\treturn newValue\n}\n\nfunc (r *RemittanceInformation8) AddOriginalPaymentInformation() *OriginalPaymentInformation6 {\n\tr.OriginalPaymentInformation = new(OriginalPaymentInformation6)\n\treturn r.OriginalPaymentInformation\n}\n\nfunc (r *RemittanceInformation8) SetRemittanceIdentification(value string) ", "output": "{\n\tr.RemittanceIdentification = (*Max35Text)(&value)\n}"} {"input": "package channelconfig\n\nimport (\n\t\"testing\"\n\n\tcb \"github.com/hyperledger/fabric/protos/common\"\n\tmspprotos \"github.com/hyperledger/fabric/protos/msp\"\n\tpb \"github.com/hyperledger/fabric/protos/peer\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\n\n\n\n\nfunc basicTest(t *testing.T, sv *StandardConfigValue) {\n\tassert.NotNil(t, sv)\n\tassert.NotEmpty(t, sv.Key())\n\tassert.NotNil(t, sv.Value())\n}\n\n\n\nfunc TestUtilsBasic(t *testing.T) ", "output": "{\n\tbasicTest(t, ConsortiumValue(\"foo\"))\n\tbasicTest(t, HashingAlgorithmValue())\n\tbasicTest(t, BlockDataHashingStructureValue())\n\tbasicTest(t, OrdererAddressesValue([]string{\"foo:1\", \"bar:2\"}))\n\tbasicTest(t, ConsensusTypeValue(\"foo\"))\n\tbasicTest(t, BatchSizeValue(1, 2, 3))\n\tbasicTest(t, BatchTimeoutValue(\"1s\"))\n\tbasicTest(t, ChannelRestrictionsValue(7))\n\tbasicTest(t, KafkaBrokersValue([]string{\"foo:1\", \"bar:2\"}))\n\tbasicTest(t, MSPValue(&mspprotos.MSPConfig{}))\n\tbasicTest(t, CapabilitiesValue(map[string]bool{\"foo\": true, \"bar\": false}))\n\tbasicTest(t, AnchorPeersValue([]*pb.AnchorPeer{&pb.AnchorPeer{}, &pb.AnchorPeer{}}))\n\tbasicTest(t, ChannelCreationPolicyValue(&cb.Policy{}))\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com/cross-dev/script-server/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n)\n\ntype ContainElementMatcher struct {\n\tElement interface{}\n}\n\nfunc (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, err error) {\n\tif !isArrayOrSlice(actual) && !isMap(actual) {\n\t\treturn false, fmt.Errorf(\"ContainElement matcher expects an array/slice/map. Got:\\n%s\", format.Object(actual, 1))\n\t}\n\n\telemMatcher, elementIsMatcher := matcher.Element.(omegaMatcher)\n\tif !elementIsMatcher {\n\t\telemMatcher = &EqualMatcher{Expected: matcher.Element}\n\t}\n\n\tvalue := reflect.ValueOf(actual)\n\tvar keys []reflect.Value\n\tif isMap(actual) {\n\t\tkeys = value.MapKeys()\n\t}\n\tvar lastError error\n\tfor i := 0; i < value.Len(); i++ {\n\t\tvar success bool\n\t\tvar err error\n\t\tif isMap(actual) {\n\t\t\tsuccess, err = elemMatcher.Match(value.MapIndex(keys[i]).Interface())\n\t\t} else {\n\t\t\tsuccess, err = elemMatcher.Match(value.Index(i).Interface())\n\t\t}\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\tcontinue\n\t\t}\n\t\tif success {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, lastError\n}\n\nfunc (matcher *ContainElementMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"to contain element matching\", matcher.Element)\n}\n\n\n\nfunc (matcher *ContainElementMatcher) NegatedFailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn format.Message(actual, \"not to contain element matching\", matcher.Element)\n}"} {"input": "package corehttp\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\n\tcore \"github.com/ipfs/go-ipfs/core\"\n\tlogging \"github.com/ipfs/go-ipfs/vendor/QmQg1J6vikuXF9oDvm4wpdeAUvvkVEKW1EYDw9HhTMnP2b/go-log\"\n)\n\ntype writeErrNotifier struct {\n\tw io.Writer\n\terrs chan error\n}\n\nfunc newWriteErrNotifier(w io.Writer) (io.WriteCloser, <-chan error) {\n\tch := make(chan error, 1)\n\treturn &writeErrNotifier{\n\t\tw: w,\n\t\terrs: ch,\n\t}, ch\n}\n\nfunc (w *writeErrNotifier) Write(b []byte) (int, error) {\n\tn, err := w.w.Write(b)\n\tif err != nil {\n\t\tselect {\n\t\tcase w.errs <- err:\n\t\tdefault:\n\t\t}\n\t}\n\tif f, ok := w.w.(http.Flusher); ok {\n\t\tf.Flush()\n\t}\n\treturn n, err\n}\n\nfunc (w *writeErrNotifier) Close() error {\n\tselect {\n\tcase w.errs <- io.EOF:\n\tdefault:\n\t}\n\treturn nil\n}\n\n\n\nfunc LogOption() ServeOption ", "output": "{\n\treturn func(n *core.IpfsNode, _ net.Listener, mux *http.ServeMux) (*http.ServeMux, error) {\n\t\tmux.HandleFunc(\"/logs\", func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.WriteHeader(200)\n\t\t\twnf, errs := newWriteErrNotifier(w)\n\t\t\tlogging.WriterGroup.AddWriter(wnf)\n\t\t\tlog.Event(n.Context(), \"log API client connected\")\n\t\t\t<-errs\n\t\t})\n\t\treturn mux, nil\n\t}\n}"} {"input": "package iso20022\n\n\ntype Statement8 struct {\n\n\tReference *Max35Text `xml:\"Ref\"`\n\n\tStatementPeriod *DatePeriodDetails `xml:\"StmtPrd\"`\n\n\tCreationDateTime *DateAndDateTimeChoice `xml:\"CreDtTm,omitempty\"`\n\n\tFrequency *EventFrequency1Code `xml:\"Frqcy,omitempty\"`\n\n\tUpdateType *StatementUpdateTypeCode `xml:\"UpdTp\"`\n\n\tActivityIndicator *YesNoIndicator `xml:\"ActvtyInd\"`\n\n\tReportNumber *Max5NumericText `xml:\"RptNb,omitempty\"`\n}\n\nfunc (s *Statement8) SetReference(value string) {\n\ts.Reference = (*Max35Text)(&value)\n}\n\n\n\nfunc (s *Statement8) AddCreationDateTime() *DateAndDateTimeChoice {\n\ts.CreationDateTime = new(DateAndDateTimeChoice)\n\treturn s.CreationDateTime\n}\n\nfunc (s *Statement8) SetFrequency(value string) {\n\ts.Frequency = (*EventFrequency1Code)(&value)\n}\n\nfunc (s *Statement8) SetUpdateType(value string) {\n\ts.UpdateType = (*StatementUpdateTypeCode)(&value)\n}\n\nfunc (s *Statement8) SetActivityIndicator(value string) {\n\ts.ActivityIndicator = (*YesNoIndicator)(&value)\n}\n\nfunc (s *Statement8) SetReportNumber(value string) {\n\ts.ReportNumber = (*Max5NumericText)(&value)\n}\n\nfunc (s *Statement8) AddStatementPeriod() *DatePeriodDetails ", "output": "{\n\ts.StatementPeriod = new(DatePeriodDetails)\n\treturn s.StatementPeriod\n}"} {"input": "package backingstore\n\nimport (\n\t\"github.com/gostor/gotgt/pkg/api\"\n\t\"github.com/gostor/gotgt/pkg/scsi\"\n)\n\nfunc init() {\n\tscsi.RegisterBackingStore(\"null\", newNull)\n}\n\ntype NullBackingStore struct {\n\tscsi.BaseBackingStore\n}\n\nfunc newNull() (api.BackingStore, error) {\n\treturn &NullBackingStore{\n\t\tBaseBackingStore: scsi.BaseBackingStore{\n\t\t\tName: \"null\",\n\t\t\tDataSize: 0,\n\t\t\tOflagsSupported: 0,\n\t\t},\n\t}, nil\n}\n\nfunc (bs *NullBackingStore) Open(dev *api.SCSILu, path string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Close(dev *api.SCSILu) error {\n\treturn nil\n}\n\n\n\nfunc (bs *NullBackingStore) Exit(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Size(dev *api.SCSILu) uint64 {\n\treturn 0\n}\n\nfunc (bs *NullBackingStore) Read(offset, tl int64) ([]byte, error) {\n\treturn nil, nil\n}\n\nfunc (bs *NullBackingStore) Write(wbuf []byte, offset int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataSync(offset, tl int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataAdvise(offset, length int64, advise uint32) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Unmap([]api.UnmapBlockDescriptor) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Init(dev *api.SCSILu, Opts string) error ", "output": "{\n\treturn nil\n}"} {"input": "package logging\n\nimport (\n\t\"time\"\n\n\t\"github.com/urandom/readeef/content\"\n\t\"github.com/urandom/readeef/content/repo\"\n\t\"github.com/urandom/readeef/log\"\n)\n\ntype tagRepo struct {\n\trepo.Tag\n\n\tlog log.Log\n}\n\nfunc (r tagRepo) Get(id content.TagID, user content.User) (content.Tag, error) {\n\tstart := time.Now()\n\n\ttag, err := r.Tag.Get(id, user)\n\n\tr.log.Infof(\"repo.Tag.Get took %s\", time.Now().Sub(start))\n\n\treturn tag, err\n}\n\nfunc (r tagRepo) ForUser(user content.User) ([]content.Tag, error) {\n\tstart := time.Now()\n\n\ttags, err := r.Tag.ForUser(user)\n\n\tr.log.Infof(\"repo.Tag.ForUser took %s\", time.Now().Sub(start))\n\n\treturn tags, err\n}\n\nfunc (r tagRepo) ForFeed(feed content.Feed, user content.User) ([]content.Tag, error) {\n\tstart := time.Now()\n\n\ttags, err := r.Tag.ForFeed(feed, user)\n\n\tr.log.Infof(\"repo.Tag.ForFeed took %s\", time.Now().Sub(start))\n\n\treturn tags, err\n}\n\n\n\nfunc (r tagRepo) FeedIDs(tag content.Tag, user content.User) ([]content.FeedID, error) ", "output": "{\n\tstart := time.Now()\n\n\tids, err := r.Tag.FeedIDs(tag, user)\n\n\tr.log.Infof(\"repo.Tag.FeedIDs took %s\", time.Now().Sub(start))\n\n\treturn ids, err\n}"} {"input": "package lib\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype StopChannelContext struct {\n\tStopCh <-chan struct{}\n}\n\nfunc (c *StopChannelContext) Deadline() (deadline time.Time, ok bool) {\n\tok = false\n\treturn\n}\n\n\n\nfunc (c *StopChannelContext) Err() error {\n\tselect {\n\tcase <-c.StopCh:\n\t\treturn context.Canceled\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (c *StopChannelContext) Value(key interface{}) interface{} {\n\treturn nil\n}\n\nfunc (c *StopChannelContext) Done() <-chan struct{} ", "output": "{\n\treturn c.StopCh\n}"} {"input": "package convert\n\n\n\nfunc Union(s []string, a []string) []string {\n\tfor _, entry := range a {\n\t\tfound := false\n\t\tfor _, existing := range s {\n\t\t\tif entry == existing {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\ts = append(s, entry)\n\t\t}\n\t}\n\treturn s\n}\n\nfunc Uniq(s []string) (r []string) {\n\tfor _, entry := range s {\n\t\tfound := false\n\t\tfor _, existing := range r {\n\t\t\tif existing == entry {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tr = append(r, entry)\n\t\t}\n\t}\n\treturn\n}\n\nfunc Add(s []string, a string) []string ", "output": "{\n\tfor _, existing := range s {\n\t\tif a == existing {\n\t\t\treturn s\n\t\t}\n\t}\n\treturn append(s, a)\n}"} {"input": "package iso20022\n\n\ntype SubAccountIdentification11 struct {\n\n\tAccountOwner *PartyIdentification13Choice `xml:\"AcctOwnr,omitempty\"`\n\n\tSafekeepingAccount *SecuritiesAccount14 `xml:\"SfkpgAcct\"`\n\n\tActivityIndicator *YesNoIndicator `xml:\"ActvtyInd\"`\n\n\tBalanceForSubAccount []*AggregateBalanceInformation9 `xml:\"BalForSubAcct,omitempty\"`\n}\n\n\n\nfunc (s *SubAccountIdentification11) AddSafekeepingAccount() *SecuritiesAccount14 {\n\ts.SafekeepingAccount = new(SecuritiesAccount14)\n\treturn s.SafekeepingAccount\n}\n\nfunc (s *SubAccountIdentification11) SetActivityIndicator(value string) {\n\ts.ActivityIndicator = (*YesNoIndicator)(&value)\n}\n\nfunc (s *SubAccountIdentification11) AddBalanceForSubAccount() *AggregateBalanceInformation9 {\n\tnewValue := new(AggregateBalanceInformation9)\n\ts.BalanceForSubAccount = append(s.BalanceForSubAccount, newValue)\n\treturn newValue\n}\n\nfunc (s *SubAccountIdentification11) AddAccountOwner() *PartyIdentification13Choice ", "output": "{\n\ts.AccountOwner = new(PartyIdentification13Choice)\n\treturn s.AccountOwner\n}"} {"input": "package api\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/url\"\n)\n\ntype PageToken struct {\n\tLimit uint16\n\tPage uint16\n}\n\nfunc DefaultPageToken(limit uint16) PageToken {\n\treturn PageToken{Limit: limit, Page: 1}\n}\n\nfunc (tok PageToken) Next() PageToken {\n\treturn PageToken{Limit: tok.Limit, Page: tok.Page + 1}\n}\n\nfunc (tok PageToken) Encode() string {\n\tbuf := bytes.Buffer{}\n\tbinary.Write(&buf, binary.LittleEndian, tok)\n\treturn base64.URLEncoding.EncodeToString(buf.Bytes())\n}\n\nfunc decodePageToken(value string) (*PageToken, error) {\n\tdec, err := base64.URLEncoding.DecodeString(value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdb := bytes.NewBuffer(dec)\n\n\tvar tok PageToken\n\terr = binary.Read(db, binary.LittleEndian, &tok)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &tok, nil\n}\n\n\n\nfunc validatePageToken(tok *PageToken, limit uint16) error {\n\tif tok.Limit != limit {\n\t\treturn fmt.Errorf(\"token limit must be %d\", limit)\n\t}\n\n\tif tok.Page == 0 {\n\t\treturn errors.New(\"token page must be greater than zero\")\n\t}\n\n\treturn nil\n}\n\nfunc findNextPageToken(u *url.URL, limit uint16) (*PageToken, error) ", "output": "{\n\tvalues := u.Query()[\"nextPageToken\"]\n\n\tif len(values) > 1 {\n\t\treturn nil, errors.New(\"too many values for page token\")\n\t}\n\n\tif len(values) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tval := values[0]\n\ttok, err := decodePageToken(val)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = validatePageToken(tok, limit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tok, nil\n}"} {"input": "package config\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n)\n\ntype VizziniConfig struct {\n\tBBSAddress string `json:\"bbs_address\"`\n\tBBSClientCertPath string `json:\"bbs_client_cert_path\"`\n\tBBSClientKeyPath string `json:\"bbs_client_key_path\"`\n\tSSHAddress string `json:\"ssh_address\"`\n\tSSHPassword string `json:\"ssh_password\"`\n\tRoutableDomainSuffix string `json:\"routable_domain_suffix\"`\n\tHostAddress string `json:\"host_addresss\"`\n\tEnableDeclarativeHealthcheck bool `json:\"enable_declarative_healthcheck\"`\n\tEnableContainerProxyTests bool `json:\"enable_container_proxy_tests\"`\n\tProxyCAPath string `json:\"proxy_ca_path\"`\n\tProxyClientCertPath string `json:\"proxy_client_cert_path\"`\n\tProxyClientKeyPath string `json:\"proxy_client_key_path\"`\n\tEnablePrivilegedContainerTests bool `json:\"enable_privileged_container_tests\"`\n\tRepPlacementTags []string `json:\"rep_placement_tags\"`\n\tMaxTaskRetries int `json:\"max_task_retries\"`\n\tDefaultRootFS string `json:\"default_rootfs\"`\n\tGraceTarballURL string `json:\"grace_tarball_url\"`\n\tGraceTarballChecksum string `json:\"grace_tarball_checksum\"`\n\tGraceBusyboxImageURL string `json:\"grace_busybox_image_url\"`\n\tFileServerAddress string `json:\"file_server_address\"`\n}\n\n\n\nfunc NewVizziniConfig() (VizziniConfig, error) ", "output": "{\n\tconfigPath, ok := os.LookupEnv(\"VIZZINI_CONFIG_PATH\")\n\tif !ok {\n\t\treturn VizziniConfig{}, fmt.Errorf(\"error loading Vizzini config: VIZZINI_CONFIG_PATH env var not set\")\n\t}\n\n\tconfigFile, err := os.Open(configPath)\n\tif err != nil {\n\t\treturn VizziniConfig{}, fmt.Errorf(\"error loading Vizzini config: %s\", err.Error())\n\t}\n\tdefer configFile.Close()\n\n\tvizziniConfig := VizziniConfig{}\n\tdecoder := json.NewDecoder(configFile)\n\terr = decoder.Decode(&vizziniConfig)\n\tif err != nil {\n\t\treturn VizziniConfig{}, fmt.Errorf(\"error unmarshalling Vizzini config: %s\", err.Error())\n\t}\n\n\treturn vizziniConfig, nil\n}"} {"input": "package security\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/goharbor/harbor/src/common/security\"\n\t\"github.com/goharbor/harbor/src/lib\"\n\t\"github.com/goharbor/harbor/src/lib/config\"\n\t\"github.com/goharbor/harbor/src/lib/log\"\n\t\"github.com/goharbor/harbor/src/server/middleware\"\n)\n\nvar (\n\tgenerators = []generator{\n\t\t&secret{},\n\t\t&oidcCli{},\n\t\t&v2Token{},\n\t\t&idToken{},\n\t\t&authProxy{},\n\t\t&robot{},\n\t\t&basicAuth{},\n\t\t&session{},\n\t\t&proxyCacheSecret{},\n\t}\n)\n\n\ntype generator interface {\n\tGenerate(req *http.Request) security.Context\n}\n\n\nfunc Middleware(skippers ...middleware.Skipper) func(http.Handler) http.Handler {\n\treturn middleware.New(func(w http.ResponseWriter, r *http.Request, next http.Handler) {\n\t\tlog := log.G(r.Context())\n\t\tmode, err := config.AuthMode(r.Context())\n\t\tif err == nil {\n\t\t\tr = r.WithContext(lib.WithAuthMode(r.Context(), mode))\n\t\t} else {\n\t\t\tlog.Warningf(\"failed to get auth mode: %v\", err)\n\t\t}\n\t\tfor _, generator := range generators {\n\t\t\tif ctx := generator.Generate(r); ctx != nil {\n\t\t\t\tr = r.WithContext(security.NewContext(r.Context(), ctx))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t}, skippers...)\n}\n\n\n\n\n\nfunc UnauthorizedMiddleware(skippers ...middleware.Skipper) func(http.Handler) http.Handler ", "output": "{\n\treturn middleware.New(func(w http.ResponseWriter, r *http.Request, next http.Handler) {\n\t\tif _, ok := security.FromContext(r.Context()); !ok {\n\t\t\tu := &unauthorized{}\n\t\t\tr = r.WithContext(security.NewContext(r.Context(), u.Generate(r)))\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t}, skippers...)\n}"} {"input": "package mock\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/cilium/cilium/pkg/lock\"\n)\n\n\ntype MockMetrics struct {\n\tmutex lock.RWMutex\n\tapiCall map[string]float64\n\trateLimit map[string]time.Duration\n}\n\n\nfunc NewMockMetrics() *MockMetrics {\n\treturn &MockMetrics{\n\t\tapiCall: map[string]float64{},\n\t\trateLimit: map[string]time.Duration{},\n\t}\n}\n\n\n\nfunc (m *MockMetrics) APICall(operation, status string) float64 {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\treturn m.apiCall[fmt.Sprintf(\"operation=%s, status=%s\", operation, status)]\n}\n\n\n\n\n\nfunc (m *MockMetrics) ObserveAPICall(operation, status string, duration float64) {\n\tm.mutex.Lock()\n\tm.apiCall[fmt.Sprintf(\"operation=%s, status=%s\", operation, status)] += duration\n\tm.mutex.Unlock()\n}\n\n\n\n\n\n\n\n\nfunc (m *MockMetrics) ObserveRateLimit(operation string, delay time.Duration) {\n\tm.mutex.Lock()\n\tm.rateLimit[operation] += delay\n\tm.mutex.Unlock()\n}\n\nfunc (m *MockMetrics) RateLimit(operation string) time.Duration ", "output": "{\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\treturn m.rateLimit[operation]\n}"} {"input": "package vm\n\nimport (\n\t\"math/big\"\n\n\t\"github.com/ariseid/ariseid-core/common\"\n)\n\n\n\n\ntype destinations map[common.Hash][]byte\n\n\n\n\n\n\nfunc jumpdests(code []byte) []byte {\n\tm := make([]byte, len(code)/8+1)\n\tfor pc := uint64(0); pc < uint64(len(code)); pc++ {\n\t\top := OpCode(code[pc])\n\t\tif op == JUMPDEST {\n\t\t\tm[pc/8] |= 1 << (pc % 8)\n\t\t} else if op >= PUSH1 && op <= PUSH32 {\n\t\t\ta := uint64(op) - uint64(PUSH1) + 1\n\t\t\tpc += a\n\t\t}\n\t}\n\treturn m\n}\n\nfunc (d destinations) has(codehash common.Hash, code []byte, dest *big.Int) bool ", "output": "{\n\tudest := dest.Uint64()\n\tif dest.BitLen() >= 63 || udest >= uint64(len(code)) {\n\t\treturn false\n\t}\n\n\tm, analysed := d[codehash]\n\tif !analysed {\n\t\tm = jumpdests(code)\n\t\td[codehash] = m\n\t}\n\treturn (m[udest/8] & (1 << (udest % 8))) != 0\n}"} {"input": "package da_griddata\n\nimport (\n\t\"github.com/watermint/toolbox/essentials/io/es_stdout\"\n\t\"github.com/watermint/toolbox/infra/control/app_control\"\n\t\"sync\"\n)\n\nfunc NewConsoleWriter(formatter GridDataFormatter, pw PlainGridDataWriter) GridDataWriter {\n\treturn &consoleWriter{\n\t\tformatter: formatter,\n\t\tpw: pw,\n\t}\n}\n\ntype consoleWriter struct {\n\tctl app_control.Control\n\tname string\n\tformatter GridDataFormatter\n\tpw PlainGridDataWriter\n\trow int\n\tmutex sync.Mutex\n}\n\nfunc (z *consoleWriter) Name() string {\n\treturn z.name\n}\n\n\n\nfunc (z *consoleWriter) Open(c app_control.Control) error {\n\tz.ctl = c\n\treturn nil\n}\n\nfunc (z *consoleWriter) Close() {\n}\n\nfunc (z *consoleWriter) Row(column []interface{}) ", "output": "{\n\tz.mutex.Lock()\n\tdefer z.mutex.Unlock()\n\tout := es_stdout.NewDefaultOut(z.ctl.Feature())\n\n\t_ = z.pw.WriteRow(z.ctl.Log(), out, z.formatter, z.row, column)\n\tz.row++\n}"} {"input": "package goxpath\n\nimport (\n\txml \"encoding/xml\"\n)\n\ntype FuncOpts func(*Opts)\n\nfunc MustParse(_ string) XPathExec {\n\treturn XPathExec{}\n}\n\ntype Opts struct {\n\tNS map[string]string\n\tFuncs map[xml.Name]interface{}\n\tVars map[string]interface{}\n}\n\nfunc Parse(_ string) (XPathExec, error) {\n\treturn XPathExec{}, nil\n}\n\n\n\ntype XPathExec struct{}\n\nfunc (_ XPathExec) Exec(_ interface{}, _ ...FuncOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\nfunc (_ XPathExec) ExecBool(_ interface{}, _ ...FuncOpts) (bool, error) {\n\treturn false, nil\n}\n\nfunc (_ XPathExec) ExecNode(_ interface{}, _ ...FuncOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\nfunc (_ XPathExec) ExecNum(_ interface{}, _ ...FuncOpts) (float64, error) {\n\treturn 0, nil\n}\n\nfunc (_ XPathExec) MustExec(_ interface{}, _ ...FuncOpts) interface{} {\n\treturn nil\n}\n\nfunc ParseExec(_ string, _ interface{}, _ ...FuncOpts) (interface{}, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package main\n\nimport glfw \"github.com/go-gl/glfw3\"\nimport \"math\"\n\n\n\n\nfunc Round(num float64) float64 {\n\tif num >= 0 {\n\t\treturn math.Floor(num + 0.5)\n\t} else {\n\t\treturn math.Ceil(num - 0.5)\n\t}\n}\n\nfunc GetScreenSize() (int, int) ", "output": "{\n\tmonitors, err := glfw.GetMonitors()\n\tif err == nil {\n\t\tmonitor := monitors[0]\n\t\tvideoMode, err := monitor.GetVideoMode()\n\t\tif err == nil {\n\t\t\treturn videoMode.Width, videoMode.Height\n\t\t} else {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tpanic(err)\n\t}\n}"} {"input": "package console\n\nimport \"github.com/accurateproject/accurate/api/v1\"\n\nfunc init() {\n\tc := &CmdExecuteScheduledActions{\n\t\tname: \"scheduler_execute\",\n\t\trpcMethod: \"ApiV1.ExecuteScheduledActions\",\n\t\trpcParams: &v1.AttrsExecuteScheduledActions{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdExecuteScheduledActions struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrsExecuteScheduledActions\n\t*CommandExecuter\n}\n\nfunc (self *CmdExecuteScheduledActions) Name() string {\n\treturn self.name\n}\n\n\n\nfunc (self *CmdExecuteScheduledActions) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrsExecuteScheduledActions{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdExecuteScheduledActions) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdExecuteScheduledActions) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *CmdExecuteScheduledActions) RpcMethod() string ", "output": "{\n\treturn self.rpcMethod\n}"} {"input": "package goparser\n\nimport (\n\t\"strings\"\n)\n\nfunc isExceptedStatement(name string, prefixs, suffixs, fullnames []string) bool {\n\tname = strings.ToLower(name)\n\tfor _, prefix := range prefixs {\n\t\tif strings.HasPrefix(name, prefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tfor _, suffix := range suffixs {\n\t\tif strings.HasSuffix(name, suffix) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, fullname := range fullnames {\n\t\tif name == fullname {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc isUpdateStatement(name string) bool {\n\treturn isExceptedStatement(name, []string{\n\t\t\"set\",\n\t\t\"update\",\n\t}, nil, nil)\n}\nfunc isDeleteStatement(name string) bool {\n\treturn isExceptedStatement(name, []string{\n\t\t\"delete\",\n\t\t\"remove\",\n\t\t\"clear\",\n\t}, nil, nil)\n}\nfunc isSelectStatement(name string) bool {\n\treturn isExceptedStatement(name, []string{\n\t\t\"select\",\n\t\t\"find\",\n\t\t\"get\",\n\t\t\"query\",\n\t\t\"list\",\n\t\t\"count\",\n\t\t\"read\",\n\t\t\"statby\",\n\t\t\"statsby\",\n\t}, []string{\"count\"}, []string{\"id\", \"all\", \"names\", \"titles\"})\n}\n\nfunc isInsertStatement(name string) bool ", "output": "{\n\treturn isExceptedStatement(name, []string{\n\t\t\"insert\",\n\t\t\"upsert\",\n\t\t\"add\",\n\t\t\"create\",\n\t}, nil, nil)\n}"} {"input": "package feedtr\n\nimport (\n \"errors\"\n \"fmt\"\n \"github.com/hashicorp/errwrap\"\n \"github.com/pkg/math\"\n \"log\"\n \"net/http\"\n \"sync\"\n \"time\"\n)\n\nconst fetchLimit = 100\n\n\nfunc saveResponse(response *http.Response, cacheEntry CacheEntry) error {\n lastModifiedHeader := response.Header.Get(\"Last-Modified\")\n\n if lastModifiedHeader == \"\" {\n lastModifiedHeader = response.Header.Get(\"Date\")\n\n if lastModifiedHeader == \"\" {\n return errors.New(\"Missing Last-Modified and Date headers\")\n }\n }\n\n lastModified, err := http.ParseTime(lastModifiedHeader)\n\n if err != nil {\n return err\n }\n\n return cacheEntry.Write(response.Body, lastModified)\n}\n\n\nfunc fetch(source string, cache Cache) (err error) {\n log.Printf(\"Fetching %s\", source)\n\n request, err := http.NewRequest(\"GET\", source, nil)\n if err != nil {\n return\n }\n\n request.Header.Add(\"User-Agent\", \"FeedTransformer/1 (https://github.com/philr/feedtransformer)\")\n\n cacheEntry := cache.Entry(source)\n lastModified := cacheEntry.LastModified()\n\n if lastModified != nil {\n request.Header.Add(\"If-Modified-Since\", lastModified.UTC().Format(time.RFC1123))\n }\n\n client := &http.Client{}\n response, err := client.Do(request)\n if err != nil {\n return\n }\n\n defer response.Body.Close()\n\n log.Printf(\"Fetched %s, got status %s\", source, response.Status)\n\n if response.StatusCode == 200 {\n return saveResponse(response, cacheEntry)\n } else if response.StatusCode != 304 {\n return fmt.Errorf(\"Unexpected status %s\", response.Status)\n }\n\n return\n}\n\n\n\n\nfunc FetchSources(config *Config, cache Cache) []error ", "output": "{\n sources := config.Sources()\n sc := make(chan string)\n ec := make(chan error)\n\n var errors []error\n\n go func() {\n for err := range ec {\n errors = append(errors, err)\n }\n }()\n\n var wg sync.WaitGroup\n wg.Add(len(sources))\n\n \n for i := 0; i < math.MinInt(fetchLimit, len(sources)); i++ {\n go func() {\n for source := range sc {\n defer wg.Done()\n err := fetch(source, cache)\n if err != nil {\n ec <- errwrap.Wrapf(fmt.Sprintf(\"Error fetching %s: {{err}}\", source), err)\n }\n }\n }()\n }\n\n go func() {\n for _, source := range sources {\n sc <- source\n }\n\n close(sc)\n }()\n\n wg.Wait()\n close(ec)\n\n return errors\n}"} {"input": "package godependencies\n\nimport (\n\t\"github.com/goatcms/goatcli/cliapp/common/config\"\n)\n\n\ntype SetRow struct {\n\tDependency *config.Dependency\n\tImported bool\n}\n\n\n\n\nfunc (row *SetRow) SetImported(value bool) ", "output": "{\n\trow.Imported = value\n}"} {"input": "package logs\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\ntype connWriter struct {\n\tlg *logWriter\n\tinnerWriter io.WriteCloser\n\tReconnectOnMsg bool `json:\"reconnectOnMsg\"`\n\tReconnect bool `json:\"reconnect\"`\n\tNet string `json:\"net\"`\n\tAddr string `json:\"addr\"`\n\tLevel int `json:\"level\"`\n}\n\n\nfunc NewConn() Logger {\n\tconn := new(connWriter)\n\tconn.Level = LevelTrace\n\treturn conn\n}\n\n\n\nfunc (c *connWriter) Init(jsonConfig string) error {\n\treturn json.Unmarshal([]byte(jsonConfig), c)\n}\n\n\n\n\n\n\nfunc (c *connWriter) Flush() {\n\n}\n\n\nfunc (c *connWriter) Destroy() {\n\tif c.innerWriter != nil {\n\t\tc.innerWriter.Close()\n\t}\n}\n\nfunc (c *connWriter) connect() error {\n\tif c.innerWriter != nil {\n\t\tc.innerWriter.Close()\n\t\tc.innerWriter = nil\n\t}\n\n\tconn, err := net.Dial(c.Net, c.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif tcpConn, ok := conn.(*net.TCPConn); ok {\n\t\ttcpConn.SetKeepAlive(true)\n\t}\n\n\tc.innerWriter = conn\n\tc.lg = newLogWriter(conn)\n\treturn nil\n}\n\nfunc (c *connWriter) needToConnectOnMsg() bool {\n\tif c.Reconnect {\n\t\tc.Reconnect = false\n\t\treturn true\n\t}\n\n\tif c.innerWriter == nil {\n\t\treturn true\n\t}\n\n\treturn c.ReconnectOnMsg\n}\n\nfunc init() {\n\tRegister(AdapterConn, NewConn)\n}\n\nfunc (c *connWriter) WriteMsg(when time.Time, msg string, level int) error ", "output": "{\n\tif level > c.Level {\n\t\treturn nil\n\t}\n\tif c.needToConnectOnMsg() {\n\t\terr := c.connect()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif c.ReconnectOnMsg {\n\t\tdefer c.innerWriter.Close()\n\t}\n\n\tc.lg.println(when, msg)\n\treturn nil\n}"} {"input": "package sockets\n\nimport (\n\t\"crypto/tls\"\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/docker/docker/pkg/listenbuffer\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ConfigureTCPTransport(tr *http.Transport, proto, addr string) {\n\ttimeout := 32 * time.Second\n\tif proto == \"unix\" {\n\t\ttr.DisableCompression = true\n\t\ttr.Dial = func(_, _ string) (net.Conn, error) {\n\t\t\treturn net.DialTimeout(proto, addr, timeout)\n\t\t}\n\t} else {\n\t\ttr.Proxy = http.ProxyFromEnvironment\n\t\ttr.Dial = (&net.Dialer{Timeout: timeout}).Dial\n\t}\n}\n\nfunc NewTCPSocket(addr string, tlsConfig *tls.Config, activate <-chan struct{}) (net.Listener, error) ", "output": "{\n\tl, err := listenbuffer.NewListenBuffer(\"tcp\", addr, activate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif tlsConfig != nil {\n\t\ttlsConfig.NextProtos = []string{\"http/1.1\"}\n\t\tl = tls.NewListener(l, tlsConfig)\n\t}\n\treturn l, nil\n}"} {"input": "package iso20022\n\n\ntype CorporateActionEventType29Choice struct {\n\n\tCode *CorporateActionEventType19Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification30 `xml:\"Prtry\"`\n}\n\nfunc (c *CorporateActionEventType29Choice) SetCode(value string) {\n\tc.Code = (*CorporateActionEventType19Code)(&value)\n}\n\n\n\nfunc (c *CorporateActionEventType29Choice) AddProprietary() *GenericIdentification30 ", "output": "{\n\tc.Proprietary = new(GenericIdentification30)\n\treturn c.Proprietary\n}"} {"input": "package handlers\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/graze/golang-service/log\"\n\tuuid \"github.com/satori/go.uuid\"\n)\n\n\ntype logContextHandler struct {\n\tlogger log.FieldLogger\n\thandler http.Handler\n}\n\n\nfunc (h logContextHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\turl := *req.URL\n\tip := \"\"\n\tif userIP, err := getUserIP(req); err == nil {\n\t\tip = userIP.String()\n\t}\n\tctx := h.logger.Ctx(req.Context()).With(log.KV{\n\t\t\"transaction\": uuid.NewV4().String(),\n\t\t\"http.method\": req.Method,\n\t\t\"http.protocol\": req.Proto,\n\t\t\"http.uri\": parseURI(req, url),\n\t\t\"http.path\": uriPath(req, url),\n\t\t\"http.host\": req.Host,\n\t\t\"http.user\": ip,\n\t\t\"http.ref\": req.Referer(),\n\t\t\"http.user-agent\": req.Header.Get(\"User-Agent\"),\n\t}).NewContext(req.Context())\n\th.handler.ServeHTTP(w, req.WithContext(ctx))\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc LoggingContextHandler(logger log.FieldLogger, h http.Handler) http.Handler ", "output": "{\n\treturn logContextHandler{logger.With(log.KV{}), h}\n}"} {"input": "package stores\n\nimport (\n\t\"HTVM/instructions/base\"\n\t\"HTVM/runtime\"\n)\n\n\ntype ASTORE struct {\n\tbase.Index8Instruction\n}\n\nfunc (self *ASTORE) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, self.Index)\n}\n\ntype ASTORE_0 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_0) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 0)\n}\n\ntype ASTORE_1 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_1) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 1)\n}\n\ntype ASTORE_2 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_2) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 2)\n}\n\ntype ASTORE_3 struct {\n\tbase.NoOperandsInstruction\n}\n\n\n\ntype ASTORE_4 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_4) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 4)\n}\n\nfunc _executeRef(frame *runtime.Frame, index uint) {\n\tval := frame.OperateStack().PopRef()\n\tframe.LocalVars().SetRef(index, val)\n}\n\nfunc (self *ASTORE_3) Execute(frame *runtime.Frame) ", "output": "{\n\t_executeRef(frame, 3)\n}"} {"input": "package loads\n\nimport \"jvmgo/ch09/instructions/base\"\nimport \"jvmgo/ch09/rtda\"\n\n\ntype ILOAD struct{ base.Index8Instruction }\n\nfunc (self *ILOAD) Execute(frame *rtda.Frame) {\n\t_iload(frame, self.Index)\n}\n\ntype ILOAD_0 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_0) Execute(frame *rtda.Frame) {\n\t_iload(frame, 0)\n}\n\ntype ILOAD_1 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_1) Execute(frame *rtda.Frame) {\n\t_iload(frame, 1)\n}\n\ntype ILOAD_2 struct{ base.NoOperandsInstruction }\n\n\n\ntype ILOAD_3 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_3) Execute(frame *rtda.Frame) {\n\t_iload(frame, 3)\n}\n\nfunc _iload(frame *rtda.Frame, index uint) {\n\tval := frame.LocalVars().GetInt(index)\n\tframe.OperandStack().PushInt(val)\n}\n\nfunc (self *ILOAD_2) Execute(frame *rtda.Frame) ", "output": "{\n\t_iload(frame, 2)\n}"} {"input": "package lexer\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc EqualSentences(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc AssertNextSentence(l *Lexer, t *testing.T, a []string) {\n\tb, _ := l.NextSentence()\n\n\tif !EqualSentences(a, b) {\n\t\tt.Errorf(\"bad sentence: '%s' VS '%s'\", a, b)\n\t}\n}\n\n\n\nfunc TestSplit(t *testing.T) {\n\tss, err := Split(\"foo bar baz\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif len(ss) != 1 {\n\t\tt.Errorf(\"bad result: %s\", ss)\n\t}\n\tif !EqualSentences(ss[0], []string{\"foo\", \"bar\", \"baz\"}) {\n\t\tt.Errorf(\"bad result: %s\", ss)\n\t}\n}\n\nfunc TestLexer(t *testing.T) ", "output": "{\n\ts := strings.NewReader(`foo bar; spaces \"and quotes\"; \"es\\\"ca\\\\p e\"`)\n\tz := New(s)\n\n\tAssertNextSentence(z, t, []string{\"foo\", \"bar\"})\n\tAssertNextSentence(z, t, []string{\"spaces\", \"and quotes\"})\n\tAssertNextSentence(z, t, []string{`es\"ca\\p e`})\n}"} {"input": "package flags\n\n\n\n\n\n\n\nimport (\n\t\"strings\"\n\n\t\"github.com/BytemarkHosting/bytemark-client/cmd/bytemark/app\"\n)\n\n\n\n\ntype AccountNameSliceFlag []AccountNameFlag\n\n\nfunc (sf *AccountNameSliceFlag) Preprocess(ctx *app.Context) error {\n\tfor i := range *sf {\n\t\terr := (*sf)[i].Preprocess(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (sf *AccountNameSliceFlag) Set(value string) error {\n\tflag := AccountNameFlag{}\n\terr := flag.Set(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*sf = append(*sf, flag)\n\treturn nil\n}\n\n\nfunc (sf AccountNameSliceFlag) String() string {\n\tstrs := make([]string, len(sf))\n\tfor i, value := range sf {\n\t\tstrs[i] = value.String()\n\t}\n\treturn strings.Join(strs, \", \")\n}\n\n\n\n\n\nfunc AccountNameSlice(ctx *app.Context, name string) AccountNameSliceFlag ", "output": "{\n\tif sf, ok := ctx.Context.Generic(name).(*AccountNameSliceFlag); ok {\n\t\treturn *sf\n\t}\n\treturn AccountNameSliceFlag{}\n}"} {"input": "package version\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n)\n\nvar (\n\tVersion = \"Not provided.\"\n\tGitSHA = \"Not provided.\"\n\tBuilt = \"Not provided.\"\n)\n\n\n\n\n\nfunc Info(apiVersion string) []string {\n\treturn []string{\n\t\tfmt.Sprintf(\"API Version: %s\", apiVersion),\n\t\tfmt.Sprintf(\"Version: %s\", Version),\n\t\tfmt.Sprintf(\"Git SHA: %s\", GitSHA),\n\t\tfmt.Sprintf(\"Built At: %s\", Built),\n\t\tfmt.Sprintf(\"Go Version: %s\", runtime.Version()),\n\t\tfmt.Sprintf(\"Go OS/Arch: %s/%s\", runtime.GOOS, runtime.GOARCH),\n\t}\n}\n\nfunc PrintVersionAndExit(apiVersion string) ", "output": "{\n\tfor _, i := range Info(apiVersion) {\n\t\tfmt.Printf(\"%v\\n\", i)\n\t}\n\tos.Exit(0)\n}"} {"input": "package stats\n\nvar (\n\tNoOpStatsFactory StatsFactory\n)\n\ntype noopCounter struct {\n}\n\nfunc (s noopCounter) Inc() {\n}\n\nfunc (s noopCounter) Add(v float64) {\n}\n\ntype noopGauge struct {\n}\n\nfunc (s noopGauge) Inc() {\n}\n\nfunc (s noopGauge) Add(v float64) {\n}\n\nfunc (s noopGauge) Dec() {\n}\n\nfunc (s noopGauge) Sub(v float64) {\n}\n\nfunc (s noopGauge) Set(v float64) {\n}\n\nfunc (s noopGauge) Get() float64 {\n\treturn 0\n}\n\ntype noopSummary struct {\n}\n\nfunc (s noopSummary) Observe(v float64) {\n}\n\ntype noopStatsFactory struct {\n}\n\nfunc (f noopStatsFactory) NewCounter(\n\tmetric string,\n\ttags map[string]string) CounterStat {\n\n\treturn noopCounter{}\n}\n\n\n\nfunc (f noopStatsFactory) NewSummary(\n\tmetric string,\n\ttags map[string]string) SummaryStat {\n\n\treturn noopSummary{}\n}\n\nfunc init() {\n\tNoOpStatsFactory = noopStatsFactory{}\n}\n\nfunc (f noopStatsFactory) NewGauge(\n\tmetric string,\n\ttags map[string]string) GaugeStat ", "output": "{\n\n\treturn noopGauge{}\n}"} {"input": "package labels\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\tnetwork \"knative.dev/networking/pkg\"\n\t\"knative.dev/serving/pkg/apis/serving\"\n)\n\n\nfunc IsObjectLocalVisibility(meta *metav1.ObjectMeta) bool {\n\treturn meta.Labels[network.VisibilityLabelKey] != \"\"\n}\n\n\n\n\n\nfunc SetLabel(meta *metav1.ObjectMeta, key, value string) {\n\tif meta.Labels == nil {\n\t\tmeta.Labels = make(map[string]string, 1)\n\t}\n\n\tmeta.Labels[key] = value\n}\n\n\nfunc DeleteLabel(meta *metav1.ObjectMeta, key string) {\n\tdelete(meta.Labels, key)\n}\n\nfunc SetVisibility(meta *metav1.ObjectMeta, isClusterLocal bool) ", "output": "{\n\tif isClusterLocal {\n\t\tSetLabel(meta, network.VisibilityLabelKey, serving.VisibilityClusterLocal)\n\t} else {\n\t\tDeleteLabel(meta, network.VisibilityLabelKey)\n\t}\n}"} {"input": "package models\n\nimport \"fmt\"\n\n\nvar RoomPool = make([] *Room, 0)\n\nfunc AddRoom(r *Room) {\n\tRoomPool = append(RoomPool, r)\n}\n\n\n\n\n\nfunc FindRoom(d string) (int, *Room) {\n\tfor i, v := range RoomPool {\n\t\tif v.Name == d {\n\t\t\treturn i, v\n\t\t}\n\t}\n\treturn -1, &Room{}\n}\n\n\nfunc RemoveRoom(r *Room) {\n\n\tindex, _ := FindRoom(r.Name)\n\n\tif index != -1 {\n\t\tRoomPool = append(RoomPool[:index], RoomPool[index + 1:]...)\n\t}\n}\n\n\n\n\nfunc RemoveClient(c *Client) {\n\tfor _, room := range RoomPool{\n\t\tif room.Name == c.Room {\n\t\t\tif room.HasClient(c) {\n\t\t\t\troom.DeleteClient(c)\n\t\t\t\tif room.ClientCount() == 0 {\n\t\t\t\t\tRemoveRoom(room)\n\t\t\t\t\tPoolBroadcast(NewMessage(map[string]string{\n\t\t\t\t\t\t\"connectedClients\": fmt.Sprintf(\"%v\", GetAllClients()),\n\t\t\t\t\t\t\"numberOfRooms\": fmt.Sprintf(\"%v\", GetNumberOfRooms()),\n\t\t\t\t\t}))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\nfunc ListRooms() (int, []string) {\n\tpool := make([]string, 0)\n\tfor _, obj := range RoomPool {\n\t\tpool = append(pool, obj.Name)\n\t}\n\treturn len(RoomPool), pool\n}\n\n\nfunc PoolBroadcast(m Message) {\n\tfor _, room := range RoomPool {\n\t\troom.RoomBroadcast(m)\n\t}\n}\n\n\nfunc GetAllClients() int {\n\n\tclientSum := 0\n\tfor _, room := range RoomPool {\n\t\tclientSum += len(room.ClientPool)\n\t}\n\treturn clientSum\n}\n\n\n\n\nfunc GetNumberOfRooms() int", "output": "{\n\treturn len(RoomPool)\n}"} {"input": "package partner\n\nimport (\n\t\"github.com/jrsix/gof/web\"\n\t\"github.com/jrsix/gof/web/mvc\"\n\t\"go2o/src/core/domain/interface/partner\"\n\t\"go2o/src/core/service/dps\"\n\t\"net/url\"\n)\n\nfunc chkLogin(ctx *web.Context) (b bool, partnerId int) {\n\tv := ctx.Session().Get(\"partner_id\")\n\tif v == nil {\n\t\treturn false, -1\n\t}\n\treturn true, v.(int)\n}\nfunc redirect(ctx *web.Context) {\n\tr, w := ctx.Request, ctx.Response\n\tw.Write([]byte(\"\"))\n}\n\nvar _ mvc.Filter = new(baseC)\n\ntype baseC struct {\n}\n\nfunc (this *baseC) Requesting(ctx *web.Context) bool {\n\tif b, _ := chkLogin(ctx); !b {\n\t\tredirect(ctx)\n\t\treturn false\n\t}\n\treturn true\n}\nfunc (this *baseC) RequestEnd(ctx *web.Context) {\n}\n\n\nfunc (this *baseC) GetPartnerId(ctx *web.Context) int {\n\tv := ctx.Session().Get(\"partner_id\")\n\tif v == nil {\n\t\tthis.Requesting(ctx)\n\t\treturn -1\n\t}\n\treturn v.(int)\n}\n\n\n\n\nfunc (this *baseC) ErrorOutput(ctx *web.Context, err string) {\n\tctx.Response.Write([]byte(\"{error:\\\"\" + err + \"\\\"}\"))\n}\n\nfunc (this *baseC) GetPartner(ctx *web.Context) (*partner.ValuePartner, error) ", "output": "{\n\treturn dps.PartnerService.GetPartner(this.GetPartnerId(ctx))\n}"} {"input": "package main\n\n\n\nimport \"C\"\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"unsafe\"\n)\n\nconst LC_NUMERIC = int(C.LC_NUMERIC)\n\n\n\n\n\nfunc inSlice(a string, b []string) bool {\n\tfor _, i := range b {\n\t\tif a == i {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc homeDir() string {\n\tif runtime.GOOS == \"windows\" {\n\t\thome := os.Getenv(\"HOMEDRIVE\") + os.Getenv(\"HOMEPATH\")\n\t\tif home == \"\" {\n\t\t\thome = os.Getenv(\"USERPROFILE\")\n\t\t}\n\t\treturn home\n\t}\n\treturn os.Getenv(\"HOME\")\n}\n\n\nfunc cacheDir() string {\n\tdir := os.Getenv(\"XDG_CACHE_HOME\")\n\tif dir == \"\" {\n\t\tdir = filepath.Join(homeDir(), \".cache\", \"bukanir\")\n\t} else {\n\t\tdir = filepath.Join(dir, \"bukanir\")\n\t}\n\treturn dir\n}\n\nfunc setLocale(lc int, locale string) ", "output": "{\n\tl := C.CString(locale)\n\tdefer C.free(unsafe.Pointer(l))\n\tC.setlocale(C.int(lc), l)\n}"} {"input": "package sha512\n\nimport (\n\t\"bytes\"\n\t\"encoding/hex\"\n\t\"testing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\n\n\ntype MySuite struct{}\n\nvar _ = Suite(&MySuite{})\n\nfunc (s *MySuite) TestSha512Stream(c *C) {\n\ttestString := []byte(\"Test string\")\n\texpectedHash, _ := hex.DecodeString(\"811aa0c53c0039b6ead0ca878b096eed1d39ed873fd2d2d270abfb9ca620d3ed561c565d6dbd1114c323d38e3f59c00df475451fc9b30074f2abda3529df2fa7\")\n\thash, err := Sum(bytes.NewBuffer(testString))\n\tc.Assert(err, IsNil)\n\tc.Assert(bytes.Equal(expectedHash, hash), Equals, true)\n}\n\nfunc Test(t *testing.T) ", "output": "{ TestingT(t) }"} {"input": "package smtpio\n\nimport (\n\t\"bytes\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/mailslurper/libmailslurper/smtpconstants\"\n)\n\ntype SmtpReader struct {\n\tConnection net.Conn\n}\n\n\nfunc (this *SmtpReader) Read() string {\n\tvar raw bytes.Buffer\n\tvar bytesRead int\n\n\tbytesRead = 1\n\n\tfor bytesRead > 0 {\n\t\tthis.Connection.SetReadDeadline(time.Now().Add(time.Millisecond * smtpconstants.CONN_TIMEOUT_MILLISECONDS))\n\n\t\tbuffer := make([]byte, smtpconstants.RECEIVE_BUFFER_LEN)\n\t\tbytesRead, err := this.Connection.Read(buffer)\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif bytesRead > 0 {\n\t\t\traw.WriteString(string(buffer[:bytesRead]))\n\t\t}\n\t}\n\n\treturn raw.String()\n}\n\n\n\n\nfunc (this *SmtpReader) ReadDataBlock() string ", "output": "{\n\tvar dataBuffer bytes.Buffer\n\n\tfor {\n\t\tdataResponse := this.Read()\n\n\t\tterminatorPos := strings.Index(dataResponse, smtpconstants.SMTP_DATA_TERMINATOR)\n\t\tif terminatorPos <= -1 {\n\t\t\tdataBuffer.WriteString(dataResponse)\n\t\t} else {\n\t\t\tdataBuffer.WriteString(dataResponse[0:terminatorPos])\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn dataBuffer.String()\n}"} {"input": "package identicon\n\nvar (\n\tcos = []float64{1, 0, -1, 0}\n\n\tsin = []float64{0, 1, 0, -1}\n)\n\n\n\n\n\n\n\n\nfunc pointInPolygon(x float64, y float64, points []float64) bool {\n\tif len(points) < 8 { \n\t\treturn false\n\t}\n\n\n\tr := 0\n\tx1, y1 := points[0], points[1]\n\tprev := (y1 > y) || ((x1 > x) && (y1 == y))\n\tfor i := 2; i < len(points); i += 2 {\n\t\tx2, y2 := points[i], points[i+1]\n\t\tcurr := (y2 > y) || ((x2 > x) && (y2 == y))\n\n\t\tif curr == prev {\n\t\t\tx1, y1 = x2, y2\n\t\t\tcontinue\n\t\t}\n\n\t\tmul := (x1-x)*(y2-y) - (x2-x)*(y1-y)\n\t\tif mul > 0 {\n\t\t\tr++\n\t\t} else if mul < 0 {\n\t\t\tr--\n\t\t}\n\t\tx1, y1 = x2, y2\n\t\tprev = curr\n\t}\n\n\treturn r == 2 || r == -2\n}\n\nfunc rotate(points []float64, x, y float64, angle int) ", "output": "{\n\tif angle < 0 || angle > 3 {\n\t\tpanic(\"rotate:参数angle必须0,1,2,3三值之一\")\n\t}\n\n\tfor i := 0; i < len(points); i += 2 {\n\t\tpx := points[i] - x\n\t\tpy := points[i+1] - y\n\t\tpoints[i] = px*cos[angle] - py*sin[angle] + x\n\t\tpoints[i+1] = px*sin[angle] + py*cos[angle] + y\n\t}\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"time\"\n \"strconv\"\n)\n\n\n\n\n\n\nfunc main() {\n\n var last int\n end:=1000\n start := time.Now()\n\n last= (get_multi(3,end) + get_multi(5,end)) - get_multi(15,end)\n\n fmt.Println(\"Sum: \", strconv.Itoa(last))\n fmt.Println(\"Laufzeit: \", time.Since(start))\n}\n\nfunc get_multi(mod int,max int) int ", "output": "{\n \n var k,i,modi int\n for {\n i++\n modi=mod*i\n if modi < max {\n k += modi\n } else {\n break\n }\n }\n return k\n}"} {"input": "package payload_test\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/RobotsAndPencils/buford/payload\"\n)\n\nfunc ExampleBrowser() {\n\tp := payload.Browser{\n\t\tAlert: payload.BrowserAlert{\n\t\t\tTitle: \"Flight A998 Now Boarding\",\n\t\t\tBody: \"Boarding has begun for Flight A998.\",\n\t\t\tAction: \"View\",\n\t\t},\n\t\tURLArgs: []string{\"boarding\", \"A998\"},\n\t}\n\n\tb, err := json.Marshal(p)\n\tif err != nil {\n\t}\n\tfmt.Printf(\"%s\", b)\n}\n\nfunc TestBrowser(t *testing.T) {\n\tp := payload.Browser{\n\t\tAlert: payload.BrowserAlert{\n\t\t\tTitle: \"Flight A998 Now Boarding\",\n\t\t\tBody: \"Boarding has begun for Flight A998.\",\n\t\t\tAction: \"View\",\n\t\t},\n\t\tURLArgs: []string{\"boarding\", \"A998\"},\n\t}\n\texpected := []byte(`{\"aps\":{\"alert\":{\"title\":\"Flight A998 Now Boarding\",\"body\":\"Boarding has begun for Flight A998.\",\"action\":\"View\"},\"url-args\":[\"boarding\",\"A998\"]}}`)\n\ttestPayload(t, p, expected)\n}\n\n\n\nfunc TestInvalidBrowser(t *testing.T) {\n\ttests := []*payload.Browser{\n\t\t{\n\t\t\tAlert: payload.BrowserAlert{Action: \"View\"},\n\t\t},\n\t\t{},\n\t\tnil,\n\t}\n\n\tfor _, p := range tests {\n\t\tif err := p.Validate(); err != payload.ErrIncomplete {\n\t\t\tt.Errorf(\"Expected err %v, got %v.\", payload.ErrIncomplete, err)\n\t\t}\n\t}\n}\n\nfunc TestValidBrowser(t *testing.T) ", "output": "{\n\tp := payload.Browser{\n\t\tAlert: payload.BrowserAlert{\n\t\t\tTitle: \"Flight A998 Now Boarding\",\n\t\t\tBody: \"Boarding has begun for Flight A998.\",\n\t\t},\n\t}\n\tif err := p.Validate(); err != nil {\n\t\tt.Errorf(\"Expected no error, got %v.\", err)\n\t}\n}"} {"input": "package profiler\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com/google/pprof/profile\"\n)\n\n\n\n\n\n\nfunc heapProfile(prof *bytes.Buffer) error {\n\tp, err := goHeapProfile()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, s := range p.Sample {\n\t\ts.Value[0] = 0\n\t\ts.Value[1] = 0\n\t}\n\n\tp, err = profile.Merge([]*profile.Profile{p})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn p.Write(prof)\n}\n\n\n\n\n\n\n\nfunc deltaAllocProfile(ctx context.Context, duration time.Duration, forceGC bool, prof *bytes.Buffer) error {\n\tp1, err := allocProfile(forceGC)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsleep(ctx, duration)\n\n\tp2, err := allocProfile(forceGC)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp1.Scale(-1)\n\tp, err := profile.Merge([]*profile.Profile{p1, p2})\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.DurationNanos = duration.Nanoseconds()\n\treturn p.Write(prof)\n}\n\n\n\nfunc allocProfile(forceGC bool) (*profile.Profile, error) {\n\tif forceGC {\n\t\truntime.GC()\n\t}\n\tp, err := goHeapProfile()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.SampleType = p.SampleType[:2]\n\tfor _, s := range p.Sample {\n\t\ts.Value = s.Value[:2]\n\t}\n\treturn p, nil\n}\n\n\n\n\n\nfunc goHeapProfile() (*profile.Profile, error) ", "output": "{\n\tvar prof bytes.Buffer\n\tif err := writeHeapProfile(&prof); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to write heap profile: %v\", err)\n\t}\n\tp, err := profile.Parse(&prof)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif got := len(p.SampleType); got != 4 {\n\t\treturn nil, fmt.Errorf(\"invalid heap profile: got %d sample types, want 4\", got)\n\t}\n\tfor i, want := range []string{\"alloc_objects\", \"alloc_space\", \"inuse_objects\", \"inuse_space\"} {\n\t\tif got := p.SampleType[i].Type; got != want {\n\t\t\treturn nil, fmt.Errorf(\"invalid heap profile: got %q sample type at index %d, want %q\", got, i, want)\n\t\t}\n\t}\n\treturn p, nil\n}"} {"input": "package tequilapi\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n\ntype APIServer interface {\n\tWait() error\n\tStartServing() error\n\tStop()\n\tAddress() (string, error)\n}\n\ntype apiServer struct {\n\terrorChannel chan error\n\thandler http.Handler\n\tlistenAddress string\n\tlistener net.Listener\n}\n\n\nfunc NewServer(address string, port int, handler http.Handler, corsPolicy CorsPolicy) APIServer {\n\tserver := apiServer{\n\t\tmake(chan error, 1),\n\t\tDisableCaching(ApplyCors(handler, corsPolicy)),\n\t\tfmt.Sprintf(\"%s:%d\", address, port),\n\t\tnil}\n\treturn &server\n}\n\n\nfunc (server *apiServer) Stop() {\n\tif server.listener == nil {\n\t\treturn\n\t}\n\tserver.listener.Close()\n}\n\n\nfunc (server *apiServer) Wait() error {\n\treturn <-server.errorChannel\n}\n\n\nfunc (server *apiServer) Address() (string, error) {\n\tif server.listener == nil {\n\t\treturn \"\", errors.New(\"not bound\")\n\t}\n\treturn extractBoundAddress(server.listener)\n}\n\n\n\nfunc (server *apiServer) StartServing() error {\n\tvar err error\n\tserver.listener, err = net.Listen(\"tcp\", server.listenAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo server.serve(server.handler)\n\treturn nil\n}\n\n\n\nfunc extractBoundAddress(listener net.Listener) (string, error) {\n\taddr := listener.Addr()\n\tparts := strings.Split(addr.String(), \":\")\n\tif len(parts) < 2 {\n\t\treturn \"\", errors.New(\"Unable to locate address: \" + addr.String())\n\t}\n\treturn addr.String(), nil\n}\n\nfunc (server *apiServer) serve(handler http.Handler) ", "output": "{\n\tserver.errorChannel <- http.Serve(server.listener, handler)\n}"} {"input": "package stream_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/synapse-garden/sg-proto/store\"\n\t\"github.com/synapse-garden/sg-proto/stream\"\n\tsgt \"github.com/synapse-garden/sg-proto/testing\"\n\n\t\"github.com/boltdb/bolt\"\n\t. \"gopkg.in/check.v1\"\n)\n\n\n\ntype StreamSuite struct {\n\tdb *bolt.DB\n\ttmpDir string\n}\n\nvar _ = Suite(&StreamSuite{})\n\nfunc (s *StreamSuite) SetUpTest(c *C) {\n\tdb, tmpDir, err := sgt.TempDB(\"sg-stream-test\")\n\tc.Assert(err, IsNil)\n\tc.Assert(db.Update(store.Wrap(\n\t\tstore.Migrate(store.VerCurrent),\n\t\tstore.SetupBuckets(stream.StreamBucket),\n\t)), IsNil)\n\ts.db, s.tmpDir = db, tmpDir\n}\n\nfunc (s *StreamSuite) TearDownTest(c *C) {\n\tif db := s.db; db != nil {\n\t\tc.Assert(sgt.CleanupDB(db), IsNil)\n\t\tc.Assert(os.Remove(s.tmpDir), IsNil)\n\t}\n}\n\nfunc Test(t *testing.T) ", "output": "{ TestingT(t) }"} {"input": "package main\n\nimport \"fmt\"\nimport \"errors\"\n\n\n\nfunc main() {\n\terr := DoStuff(false)\n\tif err == nil {\n\t\terr := DoStuff(true)\n\t\tif err == nil {\n\t\t\tDoStuff(false)\n\t\t} else {\n\t\t\tfmt.Printf(\"ERROR: %s\", err.Error())\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"ERROR: %s\", err.Error())\n\t}\n}\n\nfunc DoStuff(inError bool) error ", "output": "{\n\tif inError {\n\t\treturn errors.New(\"An error occured!\")\n\t}\n\tfmt.Println(\"Doing stuff!\")\n\treturn nil\n}"} {"input": "package main\n\n\nfunc (b bucketPerms) isValidBucketPERM() bool {\n\tswitch true {\n\tcase b.isPrivate():\n\t\tfallthrough\n\tcase b.isReadOnly():\n\t\tfallthrough\n\tcase b.isPublic():\n\t\tfallthrough\n\tcase b.isAuthorized():\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\ntype bucketPerms string\n\n\nconst (\n\tbucketPrivate = bucketPerms(\"private\")\n\tbucketReadOnly = bucketPerms(\"readonly\")\n\tbucketPublic = bucketPerms(\"public\")\n\tbucketAuthorized = bucketPerms(\"authorized\")\n)\n\nfunc (b bucketPerms) String() string {\n\tif !b.isValidBucketPERM() {\n\t\treturn string(b)\n\t}\n\tif b.isReadOnly() {\n\t\treturn \"public-read\"\n\t}\n\tif b.isPublic() {\n\t\treturn \"public-read-write\"\n\t}\n\tif b.isAuthorized() {\n\t\treturn \"authenticated-read\"\n\t}\n\treturn \"private\"\n}\n\nfunc aclToPerms(acl string) bucketPerms {\n\tswitch acl {\n\tcase \"private\":\n\t\treturn bucketPerms(\"private\")\n\tcase \"public-read\":\n\t\treturn bucketPerms(\"readonly\")\n\tcase \"public-read-write\":\n\t\treturn bucketPerms(\"public\")\n\tcase \"authenticated-read\":\n\t\treturn bucketPerms(\"authorized\")\n\tdefault:\n\t\treturn bucketPerms(acl)\n\t}\n}\n\n\n\n\n\nfunc (b bucketPerms) isReadOnly() bool {\n\treturn b == bucketReadOnly\n}\n\n\nfunc (b bucketPerms) isPublic() bool {\n\treturn b == bucketPublic\n}\n\n\nfunc (b bucketPerms) isAuthorized() bool {\n\treturn b == bucketAuthorized\n}\n\nfunc (b bucketPerms) isPrivate() bool ", "output": "{\n\treturn b == bucketPrivate\n}"} {"input": "package nerd\n\nimport (\n\t\"context\"\n\t\"syscall\"\n\n\t\"code.cloudfoundry.org/lager\"\n\t\"github.com/containerd/containerd\"\n)\n\ntype BackingProcess struct {\n\tlog lager.Logger\n\tcontext context.Context\n\tcontainerdProcess containerd.Process\n}\n\n\n\nfunc (p BackingProcess) ID() string {\n\treturn p.containerdProcess.ID()\n}\n\nfunc (p BackingProcess) Wait() (int, error) {\n\texitCh, err := p.containerdProcess.Wait(p.context)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\texitStatus := <-exitCh\n\tif exitStatus.Error() != nil {\n\t\treturn 0, exitStatus.Error()\n\t}\n\n\treturn int(exitStatus.ExitCode()), nil\n}\n\nfunc (p BackingProcess) Signal(signal syscall.Signal) error {\n\treturn p.containerdProcess.Kill(p.context, signal)\n}\n\nfunc (p BackingProcess) Delete() error {\n\t_, err := p.containerdProcess.Delete(p.context)\n\treturn err\n}\n\nfunc NewBackingProcess(log lager.Logger, p containerd.Process, ctx context.Context) BackingProcess ", "output": "{\n\treturn BackingProcess{\n\t\tlog: log,\n\t\tcontext: ctx,\n\t\tcontainerdProcess: p,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"../../embedded\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\n\n\n\nfunc Entry() {\n\truntime.Armhackmode = 1\n\truntime.Runtime_main()\n}\n\n\nfunc main() {\n\tfmt.Printf(\"self tests ...\")\n\tself_tests()\n\tfmt.Printf(\"done!\\n\")\n\n\tfmt.Printf(\"warnings ...\")\n\tself_warnings()\n\tfmt.Printf(\"done!\\n\")\n\n\tfmt.Printf(\"pre-init ...\")\n\tpre_init()\n\tsyscall.Setenv(\"TZ\", \"UTC\")\n\truntime.Booted = 1\n\tfmt.Printf(\"done!\\n\")\n\n\tfmt.Printf(\"user init ...\")\n\tuser_init()\n\tfmt.Printf(\"done!\\n\")\n\n\tfor {\n\t\tuser_loop()\n\t}\n\tpanic(\"user loop broke out\")\n}\n\n\n\n\n\nfunc self_warnings() {\n}\n\n\nfunc pre_init() {\n\tembedded.GIC_init(false)\n\n\truntime.SetIRQcallback(irq)\n\n\truntime.Release(3)\n\n\truntime.Unmap_region(0x0, 0x0, 0x100000)\n}\n\nfunc self_tests() ", "output": "{\n\tfmt.Println(\"Hi from fmt\")\n\tchannel := make(chan string, 1)\n\tchannel <- \"channel test pass\"\n\tval := <-channel\n\tfmt.Println(val)\n\tgo func(resp chan string) {\n\t\tfmt.Println(\"print from inside goroutine\")\n\t\tresp <- \"send channel from inside a goroutine\"\n\t}(channel)\n\tval = <-channel\n\tfmt.Println(val)\n}"} {"input": "package iptables\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n\n\t\"github.com/projectcalico/libcalico-go/lib/testutils\"\n)\n\n\n\nfunc TestIptablesUT(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Iptables Suite\")\n}\n\nfunc init() ", "output": "{\n\ttestutils.HookLogrusForGinkgo()\n}"} {"input": "package oci\n\nimport \"io/fs\"\n\n\n\n\n\ntype dirInfo struct {\n\tfileInfo fs.FileInfo\n}\n\nfunc (di dirInfo) IsDir() bool {\n\treturn di.fileInfo.IsDir()\n}\n\nfunc (di dirInfo) Type() fs.FileMode {\n\treturn di.fileInfo.Mode().Type()\n}\n\nfunc (di dirInfo) Info() (fs.FileInfo, error) {\n\treturn di.fileInfo, nil\n}\n\nfunc (di dirInfo) Name() string {\n\treturn di.fileInfo.Name()\n}\n\n\n\n\n\nfunc fileInfoToDirEntry(info fs.FileInfo) fs.DirEntry ", "output": "{\n\tif info == nil {\n\t\treturn nil\n\t}\n\treturn dirInfo{fileInfo: info}\n}"} {"input": "package cmd\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\t\"strconv\"\n\n\txhttp \"github.com/minio/minio/cmd/http\"\n)\n\nconst unavailable = \"offline\"\n\n\nfunc ClusterCheckHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := newContext(r, w, \"ClusterCheckHandler\")\n\n\tif shouldProxy() {\n\t\tw.Header().Set(xhttp.MinIOServerStatus, unavailable)\n\t\twriteResponse(w, http.StatusServiceUnavailable, nil, mimeNone)\n\t\treturn\n\t}\n\n\tobjLayer := newObjectLayerFn()\n\n\tctx, cancel := context.WithTimeout(ctx, globalAPIConfig.getClusterDeadline())\n\tdefer cancel()\n\n\topts := HealthOptions{Maintenance: r.URL.Query().Get(\"maintenance\") == \"true\"}\n\tresult := objLayer.Health(ctx, opts)\n\tif result.WriteQuorum > 0 {\n\t\tw.Header().Set(xhttp.MinIOWriteQuorum, strconv.Itoa(result.WriteQuorum))\n\t}\n\tif !result.Healthy {\n\t\tif result.HealingDrives > 0 {\n\t\t\tw.Header().Set(xhttp.MinIOHealingDrives, strconv.Itoa(result.HealingDrives))\n\t\t}\n\t\tif opts.Maintenance {\n\t\t\twriteResponse(w, http.StatusPreconditionFailed, nil, mimeNone)\n\t\t} else {\n\t\t\twriteResponse(w, http.StatusServiceUnavailable, nil, mimeNone)\n\t\t}\n\t\treturn\n\t}\n\twriteResponse(w, http.StatusOK, nil, mimeNone)\n}\n\n\n\n\n\nfunc LivenessCheckHandler(w http.ResponseWriter, r *http.Request) {\n\tif shouldProxy() {\n\t\tw.Header().Set(xhttp.MinIOServerStatus, unavailable)\n\t}\n\twriteResponse(w, http.StatusOK, nil, mimeNone)\n}\n\nfunc ReadinessCheckHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tif shouldProxy() {\n\t\tw.Header().Set(xhttp.MinIOServerStatus, unavailable)\n\t}\n\n\twriteResponse(w, http.StatusOK, nil, mimeNone)\n}"} {"input": "package sf\n\nimport (\n\t\"time\"\n)\n\ntype Clock struct {\n\tstartTime time.Time\n}\n\nfunc NewClock() *Clock {\n\treturn &Clock{time.Now()}\n}\n\n\n\nfunc (c *Clock) Restart() time.Duration {\n\telapsed := time.Since(c.startTime)\n\tc.startTime = time.Now()\n\n\treturn elapsed\n}\n\nfunc (c *Clock) ElapsedTime() time.Duration ", "output": "{\n\treturn time.Since(c.startTime)\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\ntype SystemSettings struct {\n\tuserStreamAcl *StreamAcl\n\tsystemStreamAcl *StreamAcl\n}\n\nfunc NewSystemSettings(\n\tuserStreamAcl *StreamAcl,\n\tsystemStreamAcl *StreamAcl,\n) *SystemSettings {\n\treturn &SystemSettings{userStreamAcl, systemStreamAcl}\n}\n\nfunc (s *SystemSettings) UserStreamAcl() *StreamAcl { return s.userStreamAcl }\n\nfunc (s *SystemSettings) SystemStreamAcl() *StreamAcl { return s.systemStreamAcl }\n\nfunc (s *SystemSettings) String() string {\n\treturn fmt.Sprintf(\"&{userStreamAcl:%+v systemStreamAcl:%+v}\", s.userStreamAcl, s.systemStreamAcl)\n}\n\ntype systemSettingsJson struct {\n\tUserStreamAcl *StreamAcl `json:\"$userStreamAcl,omitempty\"`\n\tSystemStreamAcl *StreamAcl `json:\"$systemStreamAcl,omitempty\"`\n}\n\n\n\nfunc (s *SystemSettings) UnmarshalJSON(data []byte) error {\n\tss := systemSettingsJson{}\n\tif err := json.Unmarshal(data, &ss); err != nil {\n\t\treturn err\n\t}\n\ts.userStreamAcl = ss.UserStreamAcl\n\ts.systemStreamAcl = ss.SystemStreamAcl\n\treturn nil\n}\n\nfunc SystemSettingsFromJsonBytes(data []byte) (*SystemSettings, error) {\n\tsystemSettings := &SystemSettings{}\n\treturn systemSettings, json.Unmarshal(data, systemSettings)\n}\n\nfunc (s *SystemSettings) MarshalJSON() ([]byte, error) ", "output": "{\n\treturn json.Marshal(systemSettingsJson{\n\t\tUserStreamAcl: s.userStreamAcl,\n\t\tSystemStreamAcl: s.systemStreamAcl,\n\t})\n}"} {"input": "package routetemplate\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\nvar routeTemplates []RouteTemplate\n\nfunc Add(template string) (err error) {\n\trouteTemplate, _ := Parse(template)\n\trouteTemplates = append(routeTemplates, routeTemplate)\n\treturn nil\n}\n\nfunc GetMatchedTemplateString(url string) (template string, err error) {\n\ttemplate = \"\"\n\n\tfor _, value := range routeTemplates {\n\n\t\twasMatched, _ := IsMatch(url, value)\n\t\tif wasMatched {\n\t\t\ttemplate = value.TemplatePath\n\t\t\tbreak\n\t\t}\n\t}\n\treturn template, nil\n}\n\nfunc GetMatchTemplate(url string) (routeTemplateMatch RouteTemplateMatch, err error) {\n\n\trouteTemplateMatch = RouteTemplateMatch{}\n\tfor _, value := range routeTemplates {\n\t\twasMatched, _ := IsMatch(url, value)\n\t\tif wasMatched {\n\n\t\t\trouteTemplateMatch, _ = BindVariables(url, value)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn routeTemplateMatch, nil\n}\n\nfunc GetMatchedTemplate(url string) (template string, err error) {\n\ttemplate = \"\"\n\n\tfor _, value := range routeTemplates {\n\n\t\twasMatched, _ := IsMatch(url, value)\n\t\tif wasMatched {\n\t\t\ttemplate = value.TemplatePath\n\t\t\tbreak\n\t\t}\n\t}\n\treturn template, nil\n}\n\nfunc AddRoute(name string, method string, urlTemplate string, handler interface{}) {\n\tfmt.Printf(\"%q\\n\", handler)\n\tvar x reflect.Value\n\tif fv, ok := handler.(reflect.Value); ok {\n\t\tx = fv\n\t} else {\n\t\tx = reflect.ValueOf(handler)\n\t}\n\n\targs := make([]reflect.Value, 0, 0)\n\tx.Call(args)\n\tfmt.Printf(\"%q\\n\", x)\n}\n\nfunc GetAllTemplates() (templates []RouteTemplate, err error) {\n\treturn routeTemplates, nil\n}\n\n\n\nfunc ClearAllTemplates() (err error) ", "output": "{\n\trouteTemplates = make([]RouteTemplate, 0)\n\treturn nil\n}"} {"input": "package melting\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"reflect\"\n)\n\nfunc Example() {\n\ttype Source struct {\n\t\tF1 int\n\t\tF2 string\n\t}\n\ttype Dest struct {\n\t\tF1 int\n\t\tF3 float32\n\t\tF2 string\n\t}\n\n\ts := Source{F1: 3, F2: \"a\"}\n\td := Dest{F1: 4, F2: \"b\", F3: 3.1}\n\n\terr := Melt(s, &d)\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot assign source to dest, error %v\", err)\n\t}\n\n\tfmt.Printf(\"Source%v\\nDest%v\\n\", s, d)\n\n}\n\ntype nameFilter struct {\n\texclude string\n}\n\nfunc (f *nameFilter) Filter(srcField, destField reflect.StructField, src, dest reflect.Value) bool {\n\treturn f.exclude != srcField.Name\n}\n\n\n\nfunc ExampleMeltWithFilter() ", "output": "{\n\ttype Source struct {\n\t\tF1 int\n\t\tF2 string\n\t}\n\ttype Dest struct {\n\t\tF1 int\n\t\tF2 string\n\t\tF3 float32\n\t}\n\n\ts := Source{F1: 3, F2: \"a\"}\n\td := Dest{F1: 4, F2: \"b\", F3: 3.1}\n\n\terr := MeltWithFilter(s, &d, &nameFilter{\"F2\"})\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot assign source to dest, error %v\", err)\n\t}\n\n\tfmt.Printf(\"Source%v\\nDest%v\\n\", s, d)\n\n}"} {"input": "package password\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"time\"\n\n\tjwt \"github.com/dgrijalva/jwt-go\"\n)\n\nvar signingKey = genRandBytes()\n\n\nfunc GenToken(id string) (string, error) {\n\tjwt := jwt.New(jwt.SigningMethodHS256)\n\texpTime := time.Now().Add(time.Hour * 72).Unix()\n\n\tjwt.Claims[\"sub\"] = id\n\tjwt.Claims[\"exp\"] = expTime\n\tjwt.Claims[\"iat\"] = time.Now().Unix()\n\n\ttokStr, err := jwt.SignedString(signingKey)\n\tif err != nil {\n\t\treturn \"\", err \n\t}\n\n\treturn tokStr, nil\n}\n\n\n\n\n\n\n\nfunc SetSigningKey(key []byte) {\n\tsigningKey = key\n}\n\n\n\n\n\nfunc genRandBytes() []byte ", "output": "{\n\tb := make([]byte, 24)\n\t_, err := rand.Read(b)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []byte(base64.URLEncoding.EncodeToString(b))\n}"} {"input": "package testing\n\nimport (\n\t\"testing\"\n\n\t\"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/networks\"\n\t\"github.com/gophercloud/gophercloud/pagination\"\n\tth \"github.com/gophercloud/gophercloud/testhelper\"\n\t\"github.com/gophercloud/gophercloud/testhelper/client\"\n)\n\n\n\nfunc TestGet(t *testing.T) {\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\tHandleGetSuccessfully(t)\n\n\tactual, err := networks.Get(client.ServiceClient(), \"20c8acc0-f747-4d71-a389-46d078ebf000\").Extract()\n\tth.AssertNoErr(t, err)\n\tth.CheckDeepEquals(t, &SecondNetwork, actual)\n}\n\nfunc TestList(t *testing.T) ", "output": "{\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\tHandleListSuccessfully(t)\n\n\tcount := 0\n\terr := networks.List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) {\n\t\tcount++\n\t\tactual, err := networks.ExtractNetworks(page)\n\t\tth.AssertNoErr(t, err)\n\t\tth.CheckDeepEquals(t, ExpectedNetworkSlice, actual)\n\n\t\treturn true, nil\n\t})\n\tth.AssertNoErr(t, err)\n\tth.CheckEquals(t, 1, count)\n}"} {"input": "package logging\n\nimport (\n\t\"log\"\n)\n\nvar VERBOSITY int = 1\n\n\n\nfunc FailOnError(err error, format string, a ...interface{}) {\n\tif err != nil {\n\t\tlog.Fatalf(format, a...)\n\t}\n}\n\nfunc Lg(level int, format string, a ...interface{}) ", "output": "{\n\tif level <= VERBOSITY {\n\t\tlog.Printf(format, a...)\n\t}\n}"} {"input": "package arn\n\n\ntype PersonName struct {\n\tEnglish Name `json:\"english\" editable:\"true\"`\n\tJapanese Name `json:\"japanese\" editable:\"true\"`\n}\n\n\n\n\n\nfunc (name *PersonName) ByUser(user *User) string {\n\tif user == nil {\n\t\treturn name.English.String()\n\t}\n\n\tswitch user.Settings().TitleLanguage {\n\tcase \"japanese\":\n\t\tif name.Japanese.String() == \"\" {\n\t\t\treturn name.English.String()\n\t\t}\n\n\t\treturn name.Japanese.String()\n\n\tdefault:\n\t\treturn name.English.String()\n\t}\n}\n\nfunc (name *PersonName) String() string ", "output": "{\n\treturn name.ByUser(nil)\n}"} {"input": "package data\n\nimport (\n\t\"github.com/boltdb/bolt\"\n\t\"gopkg.in/mgo.v2/bson\"\n)\n\ntype Server struct {\n\tId bson.ObjectId\n\tBalancerId bson.ObjectId\n\tLabel string\n\tSettings ServerSettings\n}\n\ntype ServerSettings struct {\n\tAddress string\n\tWeight int\n\tAvailability Availability\n}\n\nfunc ListServersByBalancer(bal *Balancer) ([]Server, error) {\n\tsrvs := []Server{}\n\terr := DB.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(\"servers\"))\n\t\tc := b.Cursor()\n\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\t\tsrv := Server{}\n\t\t\terr := bson.Unmarshal(v, &srv)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif srv.BalancerId.Hex() != bal.Id.Hex() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsrvs = append(srvs, srv)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn srvs, nil\n}\n\n\n\nfunc (s *Server) Balancer() (*Balancer, error) {\n\treturn GetBalancer(s.BalancerId)\n}\n\nfunc (s *Server) Put() error {\n\tif !s.Id.Valid() {\n\t\ts.Id = bson.NewObjectId()\n\t}\n\treturn DB.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(\"servers\"))\n\t\tp, err := bson.Marshal(s)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn b.Put([]byte(s.Id.Hex()), p)\n\t})\n}\n\nfunc GetServer(id bson.ObjectId) (*Server, error) ", "output": "{\n\tsrv := &Server{}\n\terr := DB.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(\"servers\"))\n\t\tv := b.Get([]byte(id.Hex()))\n\t\tif v == nil {\n\t\t\tsrv = nil\n\t\t\treturn nil\n\t\t}\n\t\terr := bson.Unmarshal(v, srv)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn srv, nil\n}"} {"input": "package main\n\n\n\ntype TreeNode struct {\n\tVal int\n\tLeft *TreeNode\n\tRight *TreeNode\n}\n\n\n\nfunc main() {\n\n}\n\nfunc sufficientSubset(root *TreeNode, limit int) *TreeNode ", "output": "{\n\tvar dfs func(node *TreeNode, sum int) (*TreeNode)\n\tdfs = func(node *TreeNode, sum int) (*TreeNode) {\n\t\tif node.Left == nil && node.Right == nil {\n\t\t\tif node.Val + sum >= limit {\n\t\t\t\treturn node\n\t\t\t} \n\t\t\treturn nil\n\t\t}\n\n\t\tvar left, right *TreeNode\n\n\t\tif node.Left != nil {\n\t\t\tleft = dfs(node.Left, node.Val + sum)\n\t\t}\n\t\tif node.Right != nil {\n\t\t\tright = dfs(node.Right, node.Val + sum)\n\t\t}\n\n\t\tif left == nil && right == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn node\n\t}\n\n\treturn dfs(root, 0)\n}"} {"input": "package logging\n\nimport (\n \"testing\"\n \"fmt\"\n)\n\n\n\nfunc TestFormatter(t *testing.T) ", "output": "{\n formatter := NewFormatter(\"%name %levelname: %message\")\n r := newRecord(ERROR, \"com.test\", \"test-msg\")\n\n output := formatter.Exec(r)\n expected := \"com.test ERROR: test-msg\"\n if output != expected {\n fmt.Println(\"ouput = \", output)\n fmt.Println(\"expected = \", expected)\n t.Fail()\n }\n}"} {"input": "package group\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/juliengk/go-utils\"\n\t\"github.com/kassisol/hbm/cli/command\"\n\t\"github.com/kassisol/hbm/storage\"\n\t\"github.com/spf13/cobra\"\n)\n\nfunc newFindCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"find [name]\",\n\t\tShort: \"Verify if group exists in the whitelist\",\n\t\tLong: findDescription,\n\t\tRun: runFind,\n\t}\n\n\treturn cmd\n}\n\n\n\nvar findDescription = `\nVerify if group exists in the whitelist\n\n`\n\nfunc runFind(cmd *cobra.Command, args []string) ", "output": "{\n\tdefer utils.RecoverFunc()\n\n\ts, err := storage.NewDriver(\"sqlite\", command.AppPath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer s.End()\n\n\tif len(args) < 1 || len(args) > 1 {\n\t\tcmd.Usage()\n\t\tos.Exit(-1)\n\t}\n\n\tresult := s.FindGroup(args[0])\n\n\tfmt.Println(result)\n}"} {"input": "package balancetransaction\n\nimport (\n\t\"net/http\"\n\n\tstripe \"github.com/stripe/stripe-go\"\n\t\"github.com/stripe/stripe-go/form\"\n)\n\n\ntype Client struct {\n\tB stripe.Backend\n\tKey string\n}\n\n\nfunc Get(id string, params *stripe.BalanceTransactionParams) (*stripe.BalanceTransaction, error) {\n\treturn getC().Get(id, params)\n}\n\n\n\n\n\nfunc List(params *stripe.BalanceTransactionListParams) *Iter {\n\treturn getC().List(params)\n}\n\n\nfunc (c Client) List(listParams *stripe.BalanceTransactionListParams) *Iter {\n\treturn &Iter{stripe.GetIter(listParams, func(p *stripe.Params, b *form.Values) ([]interface{}, stripe.ListMeta, error) {\n\t\tlist := &stripe.BalanceTransactionList{}\n\t\terr := c.B.CallRaw(http.MethodGet, \"/v1/balance_transactions\", c.Key, b, p, list)\n\n\t\tret := make([]interface{}, len(list.Data))\n\t\tfor i, v := range list.Data {\n\t\t\tret[i] = v\n\t\t}\n\n\t\treturn ret, list.ListMeta, err\n\t})}\n}\n\n\ntype Iter struct {\n\t*stripe.Iter\n}\n\n\nfunc (i *Iter) BalanceTransaction() *stripe.BalanceTransaction {\n\treturn i.Current().(*stripe.BalanceTransaction)\n}\n\nfunc getC() Client {\n\treturn Client{stripe.GetBackend(stripe.APIBackend), stripe.Key}\n}\n\nfunc (c Client) Get(id string, params *stripe.BalanceTransactionParams) (*stripe.BalanceTransaction, error) ", "output": "{\n\tpath := stripe.FormatURLPath(\"/v1/balance_transactions/%s\", id)\n\ttransaction := &stripe.BalanceTransaction{}\n\terr := c.B.Call(http.MethodGet, path, c.Key, params, transaction)\n\treturn transaction, err\n}"} {"input": "package generic\n\nimport (\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype MockReader struct{ mock.Mock }\n\nfunc (w *MockWriter) Read(p []byte) (n int, err error) {\n\treturns := w.Called(p)\n\treturn returns.Int(0), returns.Error(1)\n}\n\ntype MockWriter struct{ mock.Mock }\n\n\n\ntype MockCloser struct{ mock.Mock }\n\nfunc (w *MockWriter) Close() error {\n\treturns := w.Called()\n\treturn returns.Error(0)\n}\n\ntype MockReadWriteCloser struct {\n\tMockReader\n\tMockWriter\n\tMockCloser\n}\n\nfunc (w *MockWriter) Write(p []byte) (n int, err error) ", "output": "{\n\treturns := w.Called(p)\n\treturn returns.Int(0), returns.Error(1)\n}"} {"input": "package node\n\nimport (\n\t\"bytes\"\n\n\t\"golang.org/x/net/html\"\n)\n\n\nfunc Attr(n *html.Node, key string) (string, bool) {\n\tfor _, a := range n.Attr {\n\t\tif a.Key == key {\n\t\t\treturn a.Val, true\n\t\t}\n\t}\n\treturn \"\", false\n}\n\n\n\n\n\n\nfunc JoinData(n ...*html.Node) string {\n\tvar buf bytes.Buffer\n\tfor _, m := range n {\n\t\tbuf.WriteString(m.Data)\n\t}\n\treturn buf.String()\n}\n\nfunc Children(n *html.Node, filter func(*html.Node) bool) []*html.Node ", "output": "{\n\tnodes := make([]*html.Node, 0)\n\n\tif filter == nil {\n\t\tfilter = func(*html.Node) bool { return true }\n\t}\n\n\tfor c := n.FirstChild; c != nil; c = c.NextSibling {\n\t\tif !filter(c) {\n\t\t\tcontinue\n\t\t}\n\t\tnodes = append(nodes, c)\n\n\t}\n\treturn nodes\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n)\n\nvar (\n\tTrace *log.Logger \n\tInfo *log.Logger \n\tWarning *log.Logger \n\tError *log.Logger \n)\n\n\n\nfunc main() {\n\tTrace.Println(\"I have something standard to say\")\n\tInfo.Println(\"Special Information\")\n\tWarning.Println(\"There is something you need to know about\")\n\tError.Println(\"Something has failed\")\n}\n\nfunc init() ", "output": "{\n\tfile, err := os.OpenFile(\"errors.txt\",\n\t\tos.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to open error log file:\", err)\n\t}\n\n\tTrace = log.New(ioutil.Discard,\n\t\t\"TRACE: \",\n\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n\n\tInfo = log.New(os.Stdout,\n\t\t\"INFO: \",\n\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n\n\tWarning = log.New(os.Stdout,\n\t\t\"WARNING: \",\n\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n\n\tError = log.New(io.MultiWriter(file, os.Stderr),\n\t\t\"ERROR: \",\n\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n}"} {"input": "package opts \n\n\n\ntype QuotedString struct {\n\tvalue *string\n}\n\n\n\n\n\nfunc (s *QuotedString) Type() string {\n\treturn \"string\"\n}\n\nfunc (s *QuotedString) String() string {\n\treturn *s.value\n}\n\nfunc trimQuotes(value string) string {\n\tlastIndex := len(value) - 1\n\tfor _, char := range []byte{'\\'', '\"'} {\n\t\tif value[0] == char && value[lastIndex] == char {\n\t\t\treturn value[1:lastIndex]\n\t\t}\n\t}\n\treturn value\n}\n\n\nfunc NewQuotedString(value *string) *QuotedString {\n\treturn &QuotedString{value: value}\n}\n\nfunc (s *QuotedString) Set(val string) error ", "output": "{\n\t*s.value = trimQuotes(val)\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/kataras/iris/v12\"\n\t\"github.com/kataras/iris/v12/middleware/requestid\"\n\n\t\"github.com/kataras/golog\"\n)\n\nfunc main() {\n\tapp := iris.New()\n\tapp.Logger().SetLevel(\"debug\")\n\tapp.Logger().SetFormat(\"json\", \" \")\n\n\n\tapp.Use(requestid.New())\n\n\tapp.Logger().Debugf(\"This is a %s with data (debug prints the stacktrace too)\", \"message\", golog.Fields{\n\t\t\"username\": \"kataras\",\n\t})\n\n\tapp.Logger().Infof(\"An info message\", golog.Fields{\"home\": \"https://iris-go.com\"})\n\n\tapp.Get(\"/ping\", ping)\n\n\tapp.Listen(\":8080\" )\n}\n\n\n\nfunc ping(ctx iris.Context) ", "output": "{\n\tctx.Application().Logger().Debugf(\"Request path: %s\", ctx.Path(), golog.Fields{\n\t\t\"request_id\": ctx.GetID(),\n\t})\n\n\tctx.WriteString(\"pong\")\n}"} {"input": "package config\n\nimport (\n\t\"sync\"\n)\n\n\n\n\n\n\ntype delayedEnvironment struct {\n\tenv Environment\n\tloading sync.Mutex\n\tcallback func() Environment\n}\n\n\n\nfunc (e *delayedEnvironment) Get(key string) (string, bool) {\n\te.Load()\n\treturn e.env.Get(key)\n}\n\n\n\nfunc (e *delayedEnvironment) GetAll(key string) []string {\n\te.Load()\n\treturn e.env.GetAll(key)\n}\n\n\n\nfunc (e *delayedEnvironment) Bool(key string, def bool) bool {\n\te.Load()\n\treturn e.env.Bool(key, def)\n}\n\n\n\nfunc (e *delayedEnvironment) Int(key string, def int) int {\n\te.Load()\n\treturn e.env.Int(key, def)\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (e *delayedEnvironment) Load() {\n\te.loading.Lock()\n\tdefer e.loading.Unlock()\n\n\tif e.env != nil {\n\t\treturn\n\t}\n\n\te.env = e.callback()\n}\n\nfunc (e *delayedEnvironment) All() map[string][]string ", "output": "{\n\te.Load()\n\treturn e.env.All()\n}"} {"input": "package core\n\nimport \"go/ast\"\n\nfunc resolveIdent(n *ast.Ident, c *Context) bool {\n\tif n.Obj == nil || n.Obj.Kind != ast.Var {\n\t\treturn true\n\t}\n\tif node, ok := n.Obj.Decl.(ast.Node); ok {\n\t\treturn TryResolve(node, c)\n\t}\n\treturn false\n}\n\n\n\nfunc resolveCompLit(n *ast.CompositeLit, c *Context) bool {\n\tfor _, arg := range n.Elts {\n\t\tif !TryResolve(arg, c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc resolveBinExpr(n *ast.BinaryExpr, c *Context) bool {\n\treturn (TryResolve(n.X, c) && TryResolve(n.Y, c))\n}\n\nfunc resolveCallExpr(n *ast.CallExpr, c *Context) bool {\n\treturn false\n}\n\n\n\n\nfunc TryResolve(n ast.Node, c *Context) bool {\n\tswitch node := n.(type) {\n\tcase *ast.BasicLit:\n\t\treturn true\n\n\tcase *ast.CompositeLit:\n\t\treturn resolveCompLit(node, c)\n\n\tcase *ast.Ident:\n\t\treturn resolveIdent(node, c)\n\n\tcase *ast.AssignStmt:\n\t\treturn resolveAssign(node, c)\n\n\tcase *ast.CallExpr:\n\t\treturn resolveCallExpr(node, c)\n\n\tcase *ast.BinaryExpr:\n\t\treturn resolveBinExpr(node, c)\n\t}\n\n\treturn false\n}\n\nfunc resolveAssign(n *ast.AssignStmt, c *Context) bool ", "output": "{\n\tfor _, arg := range n.Rhs {\n\t\tif !TryResolve(arg, c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package main\n\nimport \"testing\"\n\nfunc TestNewSliceStack(t *testing.T) {\n\tstack := NewStack()\n\n\tif len(stack) != 0 {\n\t\tt.Error(`Expected length of stack to be 0, got`, len(stack))\n\t}\n}\n\nfunc TestSliceStackPush(t *testing.T) {\n\tstack := NewStack()\n\tstack.Push(1111)\n\tstack.Push(2345)\n\n\tif stack[0] != 1111 {\n\t\tt.Error(`Expected the first item to be 1111, got`, stack[0])\n\t}\n}\n\nfunc TestSliceStackPeek(t *testing.T) {\n\tstack := NewStack()\n\tstack.Push(1234)\n\tstack.Push(2345)\n\tvalue, _ := stack.Peek()\n\n\tif value != 2345 {\n\t\tt.Error(`Expected peeked value to be 2345, got`, value)\n\t}\n}\n\nfunc TestSliceStackPop(t *testing.T) {\n\tstack := NewStack()\n\tstack.Push(1234)\n\tstack.Push(2345)\n\tvalue, _ := stack.Pop()\n\n\tif value != 2345 {\n\t\tt.Error(`Expected peeked value to be 2345, got`, value)\n\t}\n}\n\nfunc BenchmarkSliceStackPush(b *testing.B) {\n\tb.StopTimer()\n\tstack := NewStack()\n\n\tb.StartTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tstack.Push(n)\n\t}\n}\n\nfunc BenchmarkSliceStackPeek(b *testing.B) {\n\tb.StopTimer()\n\tstack := make(Stack, b.N, b.N)\n\n\tb.StartTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tstack.Peek()\n\t}\n}\n\n\n\nfunc BenchmarkSliceStackPop(b *testing.B) ", "output": "{\n\tb.StopTimer()\n\tstack := make(Stack, b.N, b.N)\n\tfor n := 0; n < b.N; n++ {\n\t\tstack[n] = n\n\t}\n\n\tb.StartTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tstack.Pop()\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestMD(t *testing.T) ", "output": "{\n\toldArgs := os.Args\n\tdefer func() {\n\t\tos.Args = oldArgs\n\t}()\n\n\tos.Args = []string{\"markdown\", \"./\"}\n\tmain()\n}"} {"input": "package buildclean\n\nvar Usage = []string{\"rt bc \"}\n\nfunc GetDescription() string {\n\treturn \"This command is used to clean (remove) build info collected locally.\"\n}\n\n\n\nfunc GetArguments() string ", "output": "{\n\treturn `\tbuild name\n\t\tBuild name.\n\n\tbuild number\n\t\tBuild number.`\n}"} {"input": "package protocol\n\nimport (\n\t\"io\"\n\t\"sync/atomic\"\n)\n\ntype countingReader struct {\n\tio.Reader\n\ttot uint64\n}\n\nvar (\n\ttotalIncoming uint64\n\ttotalOutgoing uint64\n)\n\nfunc (c *countingReader) Read(bs []byte) (int, error) {\n\tn, err := c.Reader.Read(bs)\n\tatomic.AddUint64(&c.tot, uint64(n))\n\tatomic.AddUint64(&totalIncoming, uint64(n))\n\treturn n, err\n}\n\nfunc (c *countingReader) Tot() uint64 {\n\treturn atomic.LoadUint64(&c.tot)\n}\n\ntype countingWriter struct {\n\tio.Writer\n\ttot uint64\n}\n\nfunc (c *countingWriter) Write(bs []byte) (int, error) {\n\tn, err := c.Writer.Write(bs)\n\tatomic.AddUint64(&c.tot, uint64(n))\n\tatomic.AddUint64(&totalOutgoing, uint64(n))\n\treturn n, err\n}\n\n\n\nfunc TotalInOut() (uint64, uint64) {\n\treturn atomic.LoadUint64(&totalIncoming), atomic.LoadUint64(&totalOutgoing)\n}\n\nfunc (c *countingWriter) Tot() uint64 ", "output": "{\n\treturn atomic.LoadUint64(&c.tot)\n}"} {"input": "package encoding \n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"unicode/utf8\"\n\n\t\"golang.org/x/net/html/charset\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc CharsetReader(label string, input io.Reader) (io.Reader, error) ", "output": "{\n\tbuffer, _ := io.ReadAll(input)\n\tr := bytes.NewReader(buffer)\n\n\tif utf8.Valid(buffer) {\n\t\treturn r, nil\n\t}\n\n\treturn charset.NewReaderLabel(label, r)\n}"} {"input": "package exec\n\nimport \"fmt\"\n\nvar (\n\tExecTypeOs ExecType = 0\n\n\texecTypeToString = map[ExecType]string{\n\t\tExecTypeOs: \"os\",\n\t}\n\tlenExecTypeToString = len(execTypeToString)\n\tstringToExecType = map[string]ExecType{\n\t\t\"os\": ExecTypeOs,\n\t}\n)\n\ntype ExecType uint\n\nfunc AllExecTypes() []ExecType {\n\treturn []ExecType{\n\t\tExecTypeOs,\n\t}\n}\n\nfunc ExecTypeOf(s string) (ExecType, error) {\n\texecType, ok := stringToExecType[s]\n\tif !ok {\n\t\treturn 0, UnknownExecType(s)\n\t}\n\treturn execType, nil\n}\n\n\n\nfunc UnknownExecType(unknownExecType interface{}) error {\n\treturn fmt.Errorf(\"exec: unknown ExecType: %v\", unknownExecType)\n}\n\nfunc (e ExecType) String() string ", "output": "{\n\tif int(e) < lenExecTypeToString {\n\t\treturn execTypeToString[e]\n\t}\n\tpanic(UnknownExecType(e).Error())\n}"} {"input": "package testing\n\nimport (\n\t\"testing\"\n\n\t\"github.com/notnil/chess\"\n)\n\nfunc TestPawn(t *testing.T) {\n\n\tvalidator := chess.NewGame(chess.UseNotation(chess.LongAlgebraicNotation{}))\n\n\tcases := []struct {\n\t\tsrc string\n\t\tdst string\n\t\tlegal bool\n\t}{\n\t\t{\"e2\", \"e4\", false},\n\t\t{\"e7\", \"e5\", false},\n\t\t{\"d2\", \"d5\", true},\n\t\t{\"d2\", \"d3\", false},\n\t\t{\"e5\", \"e4\", true},\n\t\t{\"f7\", \"f5\", false},\n\t\t{\"e4\", \"f6\", true},\n\t\t{\"e4\", \"f5\", false},\n\t\t{\"g7\", \"g5\", false},\n\t\t{\"f5\", \"g6\", false},\n\t\t{\"h7\", \"g6\", false},\n\t\t{\"d3\", \"d2\", true},\n\t}\n\n\tfor index, c := range cases {\n\t\terr := validator.MoveStr(c.src + c.dst)\n\t\tif (c.legal && err == nil) || (!c.legal && err != nil) {\n\t\t\tt.Error(\"testPawn\", index, err)\n\t\t}\n\t}\n}\n\n\n\nfunc TestKnght(t *testing.T) ", "output": "{\n\n\tvalidator := chess.NewGame(chess.UseNotation(chess.LongAlgebraicNotation{}))\n\n\tcases := []struct {\n\t\tsrc string\n\t\tdst string\n\t\tlegal bool\n\t}{\n\t\t{\"g1\", \"e2\", true},\n\t\t{\"g1\", \"f3\", false},\n\t\t{\"g8\", \"h6\", false},\n\t\t{\"f3\", \"g4\", true},\n\t\t{\"f3\", \"h4\", false},\n\t\t{\"b8\", \"c6\", false},\n\t\t{\"h4\", \"f5\", false},\n\t\t{\"h6\", \"f5\", false},\n\t}\n\n\tfor index, c := range cases {\n\t\terr := validator.MoveStr(c.src + c.dst)\n\t\tif (c.legal && err == nil) || (!c.legal && err != nil) {\n\t\t\tt.Error(\"testKnight\", index, err)\n\t\t}\n\t}\n}"} {"input": "package aggfuncs_test\n\nimport (\n\t. \"github.com/pingcap/check\"\n\t\"github.com/pingcap/parser/ast\"\n\t\"github.com/pingcap/parser/mysql\"\n)\n\nfunc (s *testSuite) TestMergePartialResult4Varsamp(c *C) {\n\ttests := []aggTest{\n\t\tbuildAggTester(ast.AggFuncVarSamp, mysql.TypeDouble, 5, 2.5, 1, 1.9821428571428572),\n\t}\n\tfor _, test := range tests {\n\t\ts.testMergePartialResult(c, test)\n\t}\n}\n\n\n\nfunc (s *testSuite) TestVarsamp(c *C) ", "output": "{\n\ttests := []aggTest{\n\t\tbuildAggTester(ast.AggFuncVarSamp, mysql.TypeDouble, 5, nil, 2.5),\n\t}\n\tfor _, test := range tests {\n\t\ts.testAggFunc(c, test)\n\t}\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1alpha1 \"k8s.io/kops/pkg/client/clientset_generated/clientset/typed/kops/v1alpha1\"\n)\n\ntype FakeKopsV1alpha1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeKopsV1alpha1) Clusters(namespace string) v1alpha1.ClusterInterface {\n\treturn &FakeClusters{c, namespace}\n}\n\nfunc (c *FakeKopsV1alpha1) InstanceGroups(namespace string) v1alpha1.InstanceGroupInterface {\n\treturn &FakeInstanceGroups{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeKopsV1alpha1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeKopsV1alpha1) SSHCredentials(namespace string) v1alpha1.SSHCredentialInterface ", "output": "{\n\treturn &FakeSSHCredentials{c, namespace}\n}"} {"input": "package uploader\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/lomik/carbon-clickhouse/helper/config\"\n)\n\ntype Config struct {\n\tType string `toml:\"type\"` \n\tTableName string `toml:\"table\"` \n\tTimeout *config.Duration `toml:\"timeout\"`\n\tDate string `toml:\"date\"` \n\tTreeDate time.Time `toml:\"-\"`\n\tZeroTimestamp bool `toml:\"zero-timestamp\"` \n\tThreads int `toml:\"threads\"`\n\tURL string `toml:\"url\"`\n\tCacheTTL *config.Duration `toml:\"cache-ttl\"`\n\tIgnoredPatterns []string `toml:\"ignored-patterns,omitempty\"` \n\tCompressData bool `toml:\"compress-data\"` \n\tIgnoredTaggedMetrics []string `toml:\"ignored-tagged-metrics\"` \n\tHash string `toml:\"hash\"` \n\tDisableDailyIndex bool `toml:\"disable-daily-index\"` \n\thashFunc func(string) string `toml:\"-\"`\n}\n\n\n\nfunc (cfg *Config) Parse() error ", "output": "{\n\tvar err error\n\n\tif cfg.Date != \"\" {\n\t\tcfg.TreeDate, err = time.ParseInLocation(\"2006-01-02\", cfg.Date, time.Local)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar known bool\n\tcfg.hashFunc, known = knownHash[cfg.Hash]\n\tif !known {\n\t\treturn fmt.Errorf(\"unknown hash function %#v\", cfg.Hash)\n\t}\n\n\treturn nil\n}"} {"input": "package ctxlogrus_test\n\nimport (\n\t\"context\"\n\n\t\"github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus/ctxlogrus\"\n\t\"github.com/grpc-ecosystem/go-grpc-middleware/tags\"\n)\n\n\n\n\nfunc ExampleExtract_unary() ", "output": "{\n\tctx := context.Background()\n\tgrpc_ctxtags.Extract(ctx).Set(\"custom_tags.string\", \"something\").Set(\"custom_tags.int\", 1337)\n\tl := ctxlogrus.Extract(ctx)\n\tl.Info(\"some ping\")\n\tl.Info(\"another ping\")\n}"} {"input": "package filehash\n\nimport (\n\t\"crypto/sha1\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/cloudfoundry/gofileutils/fileutils\"\n)\n\ntype Hash []byte\n\n\n\n\nfunc New(filePath string) Hash {\n\tfileInfo, err := os.Lstat(filePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif fileInfo.IsDir() {\n\t\tpanic(\"cannot compute hash of directory\")\n\t} else {\n\t\thash := sha1.New()\n\t\terr = fileutils.CopyPathToWriter(filePath, hash)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn Hash(hash.Sum(nil))\n\t}\n}\n\nfunc (k Hash) String() string {\n\treturn fmt.Sprintf(\"%x\", string(k))\n}\n\nfunc StringToHash(s string) Hash {\n\tvar sh string\n\tif _, err := fmt.Sscanf(s, \"%x\", &sh); err != nil {\n\t\tpanic(err)\n\t}\n\treturn Hash(sh)\n}\n\nfunc (h1 Hash) Combine(h2 Hash) {\n\tif len(h1) != len(h2) {\n\t\tpanic(\"Invalid hash length\")\n\t}\n\tfor i, b := range h1 {\n\t\th1[i] = b ^ h2[i]\n\t}\n}\n\nfunc (h1 Hash) Remove(h2 Hash) {\n\th1.Combine(h2)\n}\n\nfunc Zero() Hash ", "output": "{\n\treturn Hash(make([]byte, sha1.Size))\n}"} {"input": "package bind\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/energicryptocurrency/energi/common\"\n\t\"github.com/energicryptocurrency/energi/core/types\"\n\t\"github.com/energicryptocurrency/energi/log\"\n)\n\n\n\nfunc WaitMined(ctx context.Context, b DeployBackend, tx *types.Transaction) (*types.Receipt, error) {\n\tqueryTicker := time.NewTicker(time.Second)\n\tdefer queryTicker.Stop()\n\n\tlogger := log.New(\"hash\", tx.Hash())\n\tfor {\n\t\treceipt, err := b.TransactionReceipt(ctx, tx.Hash())\n\t\tif receipt != nil {\n\t\t\treturn receipt, nil\n\t\t}\n\t\tif err != nil {\n\t\t\tlogger.Trace(\"Receipt retrieval failed\", \"err\", err)\n\t\t} else {\n\t\t\tlogger.Trace(\"Transaction not yet mined\")\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tcase <-queryTicker.C:\n\t\t}\n\t}\n}\n\n\n\n\n\nfunc WaitDeployed(ctx context.Context, b DeployBackend, tx *types.Transaction) (common.Address, error) ", "output": "{\n\tif tx.To() != nil {\n\t\treturn common.Address{}, fmt.Errorf(\"tx is not contract creation\")\n\t}\n\treceipt, err := WaitMined(ctx, b, tx)\n\tif err != nil {\n\t\treturn common.Address{}, err\n\t}\n\tif receipt.ContractAddress == (common.Address{}) {\n\t\treturn common.Address{}, fmt.Errorf(\"zero address\")\n\t}\n\tcode, err := b.CodeAt(ctx, receipt.ContractAddress, nil)\n\tif err == nil && len(code) == 0 {\n\t\terr = ErrNoCodeAfterDeploy\n\t}\n\treturn receipt.ContractAddress, err\n}"} {"input": "package goldengate\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ChangeDeploymentCompartmentRequest struct {\n\n\tDeploymentId *string `mandatory:\"true\" contributesTo:\"path\" name:\"deploymentId\"`\n\n\tChangeDeploymentCompartmentDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ChangeDeploymentCompartmentRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ChangeDeploymentCompartmentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ChangeDeploymentCompartmentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype ChangeDeploymentCompartmentResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ChangeDeploymentCompartmentResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ChangeDeploymentCompartmentResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ChangeDeploymentCompartmentRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realVPCDHCPOptionsAssociation VPCDHCPOptionsAssociation\n\n\nfunc (o *VPCDHCPOptionsAssociation) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realVPCDHCPOptionsAssociation\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = VPCDHCPOptionsAssociation(r)\n\treturn nil\n}\n\nvar _ fi.HasName = &VPCDHCPOptionsAssociation{}\n\n\n\n\n\nfunc (o *VPCDHCPOptionsAssociation) SetName(name string) {\n\to.Name = &name\n}\n\n\nfunc (o *VPCDHCPOptionsAssociation) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *VPCDHCPOptionsAssociation) GetName() *string ", "output": "{\n\treturn o.Name\n}"} {"input": "package apiserver\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/juju/errors\"\n)\n\n\n\nfunc isModelFacade(facadeName string) bool {\n\treturn !controllerFacadeNames.Contains(facadeName)\n}\n\nfunc modelFacadesOnly(facadeName, _ string) error ", "output": "{\n\tif !isModelFacade(facadeName) {\n\t\treturn errors.NewNotSupported(nil, fmt.Sprintf(\"facade %q not supported for model API connection\", facadeName))\n\t}\n\treturn nil\n}"} {"input": "package hashcat3\n\ntype Dictionary struct {\n\tName string\n\tPath string\n}\n\ntype Dictionaries []Dictionary\n\nfunc (d Dictionaries) Len() int {\n\treturn len(d)\n\n}\nfunc (d Dictionaries) Swap(i, j int) {\n\td[i], d[j] = d[j], d[i]\n}\n\n\n\nfunc (d Dictionaries) Less(i, j int) bool ", "output": "{\n\treturn d[i].Name < d[j].Name\n}"} {"input": "package testutils\n\n\ntype BlockingRW struct{ nilChan chan struct{} }\n\nfunc (rw *BlockingRW) Read(p []byte) (n int, err error) {\n\t<-rw.nilChan\n\treturn\n}\n\nfunc (rw *BlockingRW) Write(p []byte) (n int, err error) {\n\t<-rw.nilChan\n\treturn\n}\n\n\ntype NoopRW struct{}\n\n\n\nfunc (rw *NoopRW) Write(p []byte) (n int, err error) {\n\treturn len(p), nil\n}\n\nfunc (rw *NoopRW) Read(p []byte) (n int, err error) ", "output": "{\n\treturn len(p), nil\n}"} {"input": "package ast\n\nimport (\n \"testing\"\n \"bitbucket.org/yyuu/xtc/xt\"\n)\n\n\n\nfunc TestPrefixOpNode(t *testing.T) ", "output": "{\n x := NewPrefixOpNode(loc(0,0), \"--\", NewVariableNode(loc(0,0), \"a\"))\n s := `{\n \"ClassName\": \"ast.PrefixOpNode\",\n \"Location\": \"[:0,0]\",\n \"Operator\": \"--\",\n \"Expr\": {\n \"ClassName\": \"ast.VariableNode\",\n \"Location\": \"[:0,0]\",\n \"Name\": \"a\",\n \"Entity\": null\n },\n \"Amount\": 1,\n \"Type\": null\n}`\n xt.AssertStringEqualsDiff(t, \"PrefixOpNode\", xt.JSON(x), s)\n}"} {"input": "package dexcom\n\nimport (\n\t\"math\"\n)\n\n\n\nfunc marshalUint16(n uint16) []byte {\n\treturn []byte{byte(n & 0xFF), byte(n >> 8)}\n}\n\n\nfunc marshalInt16(n int16) []byte {\n\treturn marshalUint16(uint16(n))\n}\n\n\n\nfunc marshalInt32(n int32) []byte {\n\treturn marshalUint32(uint32(n))\n}\n\nfunc unmarshalUint16(v []byte) uint16 {\n\treturn uint16(v[0]) | uint16(v[1])<<8\n}\n\n\nfunc unmarshalInt16(v []byte) int16 {\n\treturn int16(unmarshalUint16(v))\n}\n\nfunc unmarshalUint32(v []byte) uint32 {\n\treturn uint32(unmarshalUint16(v[0:2])) | uint32(unmarshalUint16(v[2:4]))<<16\n}\n\nfunc unmarshalInt32(v []byte) int32 {\n\treturn int32(unmarshalUint32(v))\n}\n\nfunc unmarshalUint64(v []byte) uint64 {\n\treturn uint64(unmarshalUint32(v[0:4])) | uint64(unmarshalUint32(v[4:8]))<<32\n}\n\nfunc unmarshalFloat64(v []byte) float64 {\n\treturn math.Float64frombits(unmarshalUint64(v))\n}\n\nfunc marshalUint32(n uint32) []byte ", "output": "{\n\treturn append(marshalUint16(uint16(n&0xFFFF)), marshalUint16(uint16(n>>16))...)\n}"} {"input": "package cluster\n\nimport (\n\t\"encoding/binary\"\n\t\"os\"\n)\n\ntype stateFile struct {\n\tHandle *os.File\n\tName string\n\tCount int32\n\tTimestamp int64\n}\n\nfunc newStateFile(name string) *stateFile {\n\tsf := new(stateFile)\n\tsf.Name = name\n\treturn sf\n}\n\nfunc (sf *stateFile) access() error {\n\tvar err error\n\tsf.Handle, err = os.OpenFile(sf.Name, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (sf *stateFile) write() error {\n\terr := sf.Handle.Truncate(0)\n\tsf.Handle.Seek(0, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = binary.Write(sf.Handle, binary.LittleEndian, sf.Count)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = binary.Write(sf.Handle, binary.LittleEndian, sf.Timestamp)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc (sf *stateFile) read() error ", "output": "{\n\tsf.Handle.Seek(0, 0)\n\terr := binary.Read(sf.Handle, binary.LittleEndian, &sf.Count)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = binary.Read(sf.Handle, binary.LittleEndian, &sf.Timestamp)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n)\n\ntype Logger struct {\n\tprefix string \n\twriter io.Writer\n}\n\n\nfunc (l Logger) Write(p []byte) (n int, err error) {\n\tnow := time.Now().UTC()\n\tshort_uuid := WorkerUUIDShort\n\n\tprefix := now.Format(\n\t\t\"[15:04:05 Mon 02 Jan UTC]\") +\n\t\t\"[\" + short_uuid + \"]\" +\n\t\t\"[\" + l.prefix + \"]\"\n\n\tprefix = fmt.Sprintf(\"%-40s \", prefix)\n\n\treturn l.writer.Write([]byte(prefix + string(p) + \"\\n\"))\n}\n\n\n\n\n\nfunc (l Logger) Log(message string) ", "output": "{\n\tl.Write([]byte(message))\n}"} {"input": "package wrapstesting\n\nimport (\n\t\"net/http\"\n\n\t\"gopkg.in/go-on/wrap.v2\"\n)\n\ntype (\n\tdefer_ struct{ http.Handler }\n)\n\n\n\nfunc DeferFunc(fn func(http.ResponseWriter, *http.Request)) wrap.Wrapper {\n\treturn defer_{http.HandlerFunc(fn)}\n}\n\nfunc Defer(h http.Handler) wrap.Wrapper {\n\treturn defer_{h}\n}\n\nfunc (ø defer_) Wrap(in http.Handler) (out http.Handler) ", "output": "{\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() { ø.ServeHTTP(w, r) }()\n\t\tin.ServeHTTP(w, r)\n\t})\n}"} {"input": "package arg2\n\nimport (\n\t\"encoding/binary\"\n\t\"io\"\n\n\t\"github.com/uber/tchannel-go/typed\"\n)\n\n\n\n\n\ntype KeyValIterator struct {\n\tremaining []byte\n\tleftPairCount int\n\tkey []byte\n\tval []byte\n}\n\n\n\n\nfunc NewKeyValIterator(arg2Payload []byte) (KeyValIterator, error) {\n\tif len(arg2Payload) < 2 {\n\t\treturn KeyValIterator{}, io.EOF\n\t}\n\n\tleftPairCount := binary.BigEndian.Uint16(arg2Payload[0:2])\n\treturn KeyValIterator{\n\t\tleftPairCount: int(leftPairCount),\n\t\tremaining: arg2Payload[2:],\n\t}.Next()\n}\n\n\nfunc (i KeyValIterator) Key() []byte {\n\treturn i.key\n}\n\n\n\n\n\nfunc (i KeyValIterator) Remaining() bool {\n\treturn i.leftPairCount > 0\n}\n\n\n\n\n\n\nfunc (i KeyValIterator) Next() (kv KeyValIterator, _ error) {\n\tif i.leftPairCount <= 0 {\n\t\treturn KeyValIterator{}, io.EOF\n\t}\n\n\trbuf := typed.NewReadBuffer(i.remaining)\n\tkeyLen := int(rbuf.ReadUint16())\n\tkey := rbuf.ReadBytes(keyLen)\n\tvalLen := int(rbuf.ReadUint16())\n\tval := rbuf.ReadBytes(valLen)\n\tif rbuf.Err() != nil {\n\t\treturn KeyValIterator{}, rbuf.Err()\n\t}\n\n\tleftPairCount := i.leftPairCount - 1\n\n\tkv = KeyValIterator{\n\t\tremaining: rbuf.Remaining(),\n\t\tleftPairCount: leftPairCount,\n\t\tkey: key,\n\t\tval: val,\n\t}\n\treturn kv, nil\n}\n\nfunc (i KeyValIterator) Value() []byte ", "output": "{\n\treturn i.val\n}"} {"input": "package core\n\nimport (\n\t\"html/template\" \n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Server struct {\n\tPrefix string \n\tTemplates map[string]*template.Template \n\tData DataStore\n\tUsers *UserStore\n}\n\nfunc NewServer(name string) *Server {\n\tprefix := Sanitize(name)\n\ttmpl := make(map[string]*template.Template) \n\tdata := NewDataStore(prefix)\n\ts := &Server{Prefix: prefix, Templates: tmpl, Data: data} \n\treturn s\n}\n\n\nfunc (s *Server) AddTemplates(where string) error {\n\tlist, err := s.Data.ListData(where)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, name := range list {\n\t\tif name[len(name)-1] == '~' {\n\t\t\tcontinue\n\t\t}\n\t\tdata, err := s.Data.Load(where + name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttmpl, err := template.New(name).Parse(string(data))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Templates[name] = tmpl\n\t}\n\treturn nil\n}\n\nfunc (s *Server) AddHandler(path string, handler http.HandlerFunc) {\n\turl := s.Prefix + \"/\" + path\n\tif s.Prefix != \"\" { \n\t\turl = \"/\" + url\n\t}\n\thttp.HandleFunc(url, handler)\n}\n\nfunc (s *Server) AddHandlers(handlers map[string]http.HandlerFunc) {\n\tfor path, handler := range handlers {\n\t\ts.AddHandler(path, handler)\n\t}\n}\n\n\n\n\nfunc StartServers(port uint) error {\n\treturn http.ListenAndServe(\":\"+strconv.FormatUint(uint64(port), 10), nil)\n}\n\nfunc NewDefaultServer(defaultServer string, includeExit bool) ", "output": "{\n\ts := NewServer(\"\")\n\thandlers := map[string]http.HandlerFunc{\"\": func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, defaultServer, http.StatusFound) }, \"favicon.ico\": func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) }}\n\n\tif includeExit {\n\t\thandlers[\"exit\"] = func(w http.ResponseWriter, r *http.Request) {\n\t\t\ts.Data.Append(\"shutdowns\", []byte(r.RemoteAddr+\" on \"+time.Now().UTC().Format(time.RFC1123)+\"\\n\"))\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\ts.AddHandlers(handlers)\n}"} {"input": "package bubblesort\n\n\n\nfunc BubbleSort(values []int) ", "output": "{\n\tflag := true\n\tfor i := 0; i values[j + 1] {\n\t\t\t\tvalues[j], values[j + 1] = values[j + 1], values[j]\n\t\t\t\tflag = false\n\t\t\t}\n\t\t}\n\n\t\tif flag == true {\n\t\t\tbreak\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n \"errors\"\n \"fmt\"\n \"reflect\"\n \"testing\"\n)\n\nvar redisModel = NewRedisModel(\"localhost:6379\", \"\", int64(-1))\n\nfunc TestNewRedisModel(t *testing.T) {\n expected := \"*main.RedisModel\"\n result := fmt.Sprintf(\"%v\", reflect.TypeOf(redisModel))\n\n if result != expected {\n t.Errorf(\"NewRedisModel() returned %s, expected %s\", result, expected)\n }\n}\n\n\n\nfunc TestFindBy(t *testing.T) {\n shorted, err := redisModel.Create(\"http://www.google.com\")\n \n result, err := redisModel.FindBy(\"id\", shorted.Id)\n if (result.Id != shorted.Id && result.Url != shorted.Url) || err != nil {\n t.Errorf(\"FindBy('id', '%s') expected (%v, %v), returned (%v, %v)\", shorted.Id, shorted, nil, result, err)\n }\n\n result, err = redisModel.FindBy(\"url\", shorted.Url)\n if (result.Id != shorted.Id && result.Url != shorted.Url) || err != nil {\n t.Errorf(\"FindBy('url', '%s') expected (%v, %v), returned (%v, %v)\", shorted.Url, shorted, nil, result, err)\n }\n\n badId := \"0xDEADBEEF\"\n expectedErr := errors.New(\"data: Key not found\")\n\n result, err = redisModel.FindBy(\"id\", badId)\n if result != nil || err == nil {\n t.Errorf(\"FindBy('id', '%s') expected (%v, %v), returned (%v, %v)\", badId, nil, expectedErr, result, err)\n }\n}\n\nfunc TestCreate(t *testing.T) ", "output": "{\n validUrl := \"http://www.example.com\"\n wrongUrl := \"www.example\"\n expected := \"*main.ShortUrl\"\n\n shorted, err := redisModel.Create(validUrl)\n result := fmt.Sprintf(\"%v\", reflect.TypeOf(shorted))\n if result != expected || err != nil {\n t.Errorf(\"Create('%s') expected (%v, %v), returned (%v, %v)\", validUrl, expected, nil, result, err)\n }\n\n invalidErr := errors.New(\"data: Invalid url format\")\n shorted, err = redisModel.Create(wrongUrl)\n if err == nil {\n t.Errorf(\"Create('%s') expected '%s' error, returned %s\", wrongUrl, invalidErr, err)\n }\n}"} {"input": "package main\n\nimport (\n\t. \"github.com/conclave/pcduino/core\"\n)\n\nfunc init() {\n\tInit()\n\tsetup()\n}\n\nfunc main() {\n\tfor {\n\t\tloop()\n\t}\n}\n\nfunc setup() {\n}\n\n\n\nfunc loop() ", "output": "{\n\tDelay(100)\n}"} {"input": "package containerengine\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListWorkRequestLogsRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tWorkRequestId *string `mandatory:\"true\" contributesTo:\"path\" name:\"workRequestId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListWorkRequestLogsRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListWorkRequestLogsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\n\n\n\nfunc (request ListWorkRequestLogsRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListWorkRequestLogsResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []WorkRequestLogEntry `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ListWorkRequestLogsResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListWorkRequestLogsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListWorkRequestLogsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package sml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/sml\"\n)\n\nfunc TestCT_GradientFillConstructor(t *testing.T) {\n\tv := sml.NewCT_GradientFill()\n\tif v == nil {\n\t\tt.Errorf(\"sml.NewCT_GradientFill must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed sml.CT_GradientFill should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestCT_GradientFillMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := sml.NewCT_GradientFill()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := sml.NewCT_GradientFill()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package api\n\nimport (\n\t\"bufio\"\n\t\"net/http\"\n\t\"os\"\n\n\tl4g \"code.google.com/p/log4go\"\n\t\"github.com/gorilla/mux\"\n\n\t\"github.com/mattermost/platform/model\"\n\t\"github.com/mattermost/platform/utils\"\n)\n\nfunc InitAdmin(r *mux.Router) {\n\tl4g.Debug(\"Initializing admin api routes\")\n\n\tsr := r.PathPrefix(\"/admin\").Subrouter()\n\tsr.Handle(\"/logs\", ApiUserRequired(getLogs)).Methods(\"GET\")\n}\n\n\n\nfunc getLogs(c *Context, w http.ResponseWriter, r *http.Request) ", "output": "{\n\n\tif !c.HasSystemAdminPermissions(\"getLogs\") {\n\t\treturn\n\t}\n\n\tvar lines []string\n\n\tif utils.Cfg.LogSettings.FileEnable {\n\n\t\tfile, err := os.Open(utils.Cfg.LogSettings.FileLocation)\n\t\tif err != nil {\n\t\t\tc.Err = model.NewAppError(\"getLogs\", \"Error reading log file\", err.Error())\n\t\t}\n\n\t\tdefer file.Close()\n\n\t\tscanner := bufio.NewScanner(file)\n\t\tfor scanner.Scan() {\n\t\t\tlines = append(lines, scanner.Text())\n\t\t}\n\t} else {\n\t\tlines = append(lines, \"\")\n\t}\n\n\tw.Write([]byte(model.ArrayToJson(lines)))\n}"} {"input": "package service\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/utils/shell\"\n\n\t\"github.com/juju/juju/juju/osenv\"\n\t\"github.com/juju/juju/service/common\"\n)\n\nconst (\n\tmaxAgentFiles = 20000\n\n\tagentServiceTimeout = 300 \n)\n\n\n\n\n\n\n\n\n\n\nfunc ContainerAgentConf(info AgentInfo, renderer shell.Renderer, containerType string) common.Conf {\n\tconf := AgentConf(info, renderer)\n\n\tenvVars := map[string]string{\n\t\tosenv.JujuContainerTypeEnvKey: containerType,\n\t}\n\tosenv.MergeEnvironment(envVars, conf.Env)\n\tconf.Env = envVars\n\n\treturn conf\n}\n\n\n\nfunc ShutdownAfterConf(serviceName string) (common.Conf, error) {\n\tif serviceName == \"\" {\n\t\treturn common.Conf{}, errors.New(`missing \"after\" service name`)\n\t}\n\tdesc := \"juju shutdown job\"\n\treturn shutdownAfterConf(serviceName, desc), nil\n}\n\nfunc shutdownAfterConf(serviceName, desc string) common.Conf {\n\treturn common.Conf{\n\t\tDesc: desc,\n\t\tTransient: true,\n\t\tAfterStopped: serviceName,\n\t\tExecStart: \"/sbin/shutdown -h now\",\n\t}\n}\n\nfunc AgentConf(info AgentInfo, renderer shell.Renderer) common.Conf ", "output": "{\n\tconf := common.Conf{\n\t\tDesc: fmt.Sprintf(\"juju agent for %s\", info.name),\n\t\tExecStart: info.cmd(renderer),\n\t\tLogfile: info.logFile(renderer),\n\t\tEnv: osenv.FeatureFlags(),\n\t\tTimeout: agentServiceTimeout,\n\t}\n\n\tswitch info.Kind {\n\tcase AgentKindMachine:\n\t\tconf.Limit = map[string]int{\n\t\t\t\"nofile\": maxAgentFiles,\n\t\t}\n\tcase AgentKindUnit:\n\t\tconf.Desc = \"juju unit agent for \" + info.ID\n\t}\n\n\treturn conf\n}"} {"input": "package folder\n\nimport (\n\t\"flag\"\n\t\"path\"\n\n\t\"github.com/RotatingFans/govmomi/govc/cli\"\n\t\"github.com/RotatingFans/govmomi/govc/flags\"\n\t\"golang.org/x/net/context\"\n)\n\ntype create struct {\n\t*flags.DatacenterFlag\n\n\tpod bool\n}\n\nfunc init() {\n\tcli.Register(\"folder.create\", &create{})\n}\n\nfunc (cmd *create) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.DatacenterFlag, ctx = flags.NewDatacenterFlag(ctx)\n\tcmd.DatacenterFlag.Register(ctx, f)\n\n\tf.BoolVar(&cmd.pod, \"pod\", false, \"Create folder(s) of type StoragePod (DatastoreCluster)\")\n}\n\nfunc (cmd *create) Usage() string {\n\treturn \"PATH...\"\n}\n\nfunc (cmd *create) Description() string {\n\treturn `Create folder with PATH.\nExample:\ngovc folder.create /dc1/vm/folder-foo\n`\n}\n\nfunc (cmd *create) Process(ctx context.Context) error {\n\tif err := cmd.DatacenterFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc (cmd *create) Run(ctx context.Context, f *flag.FlagSet) error ", "output": "{\n\tfinder, err := cmd.Finder()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, arg := range f.Args() {\n\t\tdir := path.Dir(arg)\n\t\tname := path.Base(arg)\n\n\t\tif dir == \"\" {\n\t\t\tdir = \"/\"\n\t\t}\n\n\t\tfolder, err := finder.Folder(ctx, dir)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar create func() error\n\t\tif cmd.pod {\n\t\t\tcreate = func() error {\n\t\t\t\t_, err = folder.CreateStoragePod(ctx, name)\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tcreate = func() error {\n\t\t\t\t_, err = folder.CreateFolder(ctx, name)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\terr = create()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package config\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/docker/cli/cli\"\n\t\"github.com/docker/cli/cli/command\"\n\t\"github.com/docker/cli/opts\"\n\t\"github.com/docker/docker/api/types/swarm\"\n\t\"github.com/docker/docker/pkg/system\"\n\t\"github.com/pkg/errors\"\n\t\"github.com/spf13/cobra\"\n)\n\n\ntype CreateOptions struct {\n\tName string\n\tTemplateDriver string\n\tFile string\n\tLabels opts.ListOpts\n}\n\n\n\n\nfunc RunConfigCreate(dockerCli command.Cli, options CreateOptions) error {\n\tclient := dockerCli.Client()\n\tctx := context.Background()\n\n\tvar in io.Reader = dockerCli.In()\n\tif options.File != \"-\" {\n\t\tfile, err := system.OpenSequential(options.File)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tin = file\n\t\tdefer file.Close()\n\t}\n\n\tconfigData, err := io.ReadAll(in)\n\tif err != nil {\n\t\treturn errors.Errorf(\"Error reading content from %q: %v\", options.File, err)\n\t}\n\n\tspec := swarm.ConfigSpec{\n\t\tAnnotations: swarm.Annotations{\n\t\t\tName: options.Name,\n\t\t\tLabels: opts.ConvertKVStringsToMap(options.Labels.GetAll()),\n\t\t},\n\t\tData: configData,\n\t}\n\tif options.TemplateDriver != \"\" {\n\t\tspec.Templating = &swarm.Driver{\n\t\t\tName: options.TemplateDriver,\n\t\t}\n\t}\n\tr, err := client.ConfigCreate(ctx, spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintln(dockerCli.Out(), r.ID)\n\treturn nil\n}\n\nfunc newConfigCreateCommand(dockerCli command.Cli) *cobra.Command ", "output": "{\n\tcreateOpts := CreateOptions{\n\t\tLabels: opts.NewListOpts(opts.ValidateLabel),\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"create [OPTIONS] CONFIG file|-\",\n\t\tShort: \"Create a config from a file or STDIN\",\n\t\tArgs: cli.ExactArgs(2),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcreateOpts.Name = args[0]\n\t\t\tcreateOpts.File = args[1]\n\t\t\treturn RunConfigCreate(dockerCli, createOpts)\n\t\t},\n\t}\n\tflags := cmd.Flags()\n\tflags.VarP(&createOpts.Labels, \"label\", \"l\", \"Config labels\")\n\tflags.StringVar(&createOpts.TemplateDriver, \"template-driver\", \"\", \"Template driver\")\n\tflags.SetAnnotation(\"template-driver\", \"version\", []string{\"1.37\"})\n\n\treturn cmd\n}"} {"input": "package util\n\nimport \"fmt\"\n\n\n\n\n\n\nfunc ValidIndex(index, length int) error ", "output": "{\n\tif index <= 0 || index-1 >= length {\n\t\treturn fmt.Errorf(\"index(%d) is out of range\", index)\n\t}\n\treturn nil\n}"} {"input": "package wire\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\n\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) ", "output": "{\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}"} {"input": "package handler\n\nimport (\n \"net/http\"\n \"io/ioutil\"\n \"path/filepath\"\n \"log\"\n\n \"diserve.didactia.org/lib/util\"\n \"diserve.didactia.org/lib/env\"\n)\n\n\ntype Style struct {\n styles map[string][]byte\n}\n\nfunc (h *Style) ServeHTTP(res http.ResponseWriter, req *http.Request) {\n head, _ := util.ShiftPath(req.URL.Path)\n var data []byte\n var ok bool\n if env.Vars.PRELOADSTYLES {\n data, ok = h.styles[head]\n } else {\n data, ok = getStyle(head)\n }\n if ok {\n res.Header().Set(\"Content-Type\", \"text/css; charset=utf-8\")\n res.Write(data)\n } else {\n http.Error(res, \"Not Found\", http.StatusNotFound)\n }\n}\n\n\nfunc NewStyle() *Style {\n h := &Style{\n styles: nil,\n }\n if env.Vars.PRELOADSTYLES {\n h.styles = getStyles()\n }\n return h\n}\n\nfunc getStyles() map[string][]byte {\n styles := make(map[string][]byte)\n paths, err := filepath.Glob(env.Vars.STYLEPATH + \"*.css\")\n if err != nil {\n log.Fatal(err)\n }\n for _, path := range paths {\n filename := filepath.Base(path)\n bytes, err := ioutil.ReadFile(path)\n if err != nil {\n log.Fatal(err)\n }\n styles[filename] = bytes\n }\n return styles\n}\n\n\n\nfunc getStyle(filename string) ([]byte, bool) ", "output": "{\n bytes, err := ioutil.ReadFile(filepath.Join(env.Vars.STYLEPATH, filename))\n if err != nil {\n return nil, false\n }\n return bytes, true\n}"} {"input": "package guest_get_time\n\nimport (\n\t\"time\"\n\n\t\"github.com/vtolstov/cloudagent/qga\"\n)\n\nfunc init() {\n\tqga.RegisterCommand(&qga.Command{\n\t\tName: \"guest-get-time\",\n\t\tFunc: fnGuestGetTime,\n\t\tEnabled: true,\n\t\tReturns: true,\n\t})\n}\n\n\n\nfunc fnGuestGetTime(req *qga.Request) *qga.Response ", "output": "{\n\tres := &qga.Response{ID: req.ID}\n\n\tres.Return = struct {\n\t\tTime int64\n\t}{Time: time.Now().UnixNano()}\n\n\treturn res\n}"} {"input": "package main\n\nimport \"testing\"\n\nimport \"github.com/stretchr/testify/assert\"\n\n\n\nfunc TestMergeRequests(t *testing.T) ", "output": "{\n\tp := DispatchRequest{}\n\ts := DispatchRequest{}\n\tp[\"item0\"] = \"val0\"\n\tp[\"item1\"] = \"val1\"\n\ts[\"item0\"] = \"val2\"\n\n\texpected := map[string]string{\n\t\t\"item0\": \"val0\",\n\t\t\"item1\": \"val1\",\n\t}\n\n\tm := mergeRequests(p, s)\n\n\tassert.EqualValues(t, expected, m)\n\n}"} {"input": "package config\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/go-ini/ini\"\n)\n\n\n\nfunc LoadConfigFileData(data []byte) (map[string]string, error) {\n\tiniFile, err := ini.Load(data)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to load config file: %v\", err)\n\t\treturn nil, err\n\t}\n\tkvs := make(map[string]string)\n\tfor _, section := range iniFile.Sections() {\n\t\tlog.Debugf(\"Parsing section %v\", section.Name())\n\t\tfor _, key := range section.Keys() {\n\t\t\tif _, ok := kvs[key.Name()]; ok {\n\t\t\t\tlog.Warningf(\"Multiple values defined for key %v\", key.Name())\n\t\t\t}\n\t\t\tkvs[key.Name()] = key.Value()\n\t\t}\n\t}\n\treturn kvs, nil\n}\n\nfunc LoadConfigFile(filename string) (map[string]string, error) ", "output": "{\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\t\tlog.Infof(\"Ignoring absent config file: %v\", filename)\n\t\treturn nil, nil\n\t}\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn LoadConfigFileData(data)\n}"} {"input": "package bcrypt\n\nimport \"errors\"\n\n\n\nfunc GenerateFromPasswordAndSalt(password, rawSalt []byte, cost int) ([]byte, error) {\n\tp, err := newFromPasswordAndSalt(password, rawSalt, cost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p.Hash(), nil\n}\n\nfunc newFromPasswordAndSalt(password, unencodedSalt []byte, cost int) (*hashed, error) ", "output": "{\n\tif cost < MinCost {\n\t\tcost = DefaultCost\n\t}\n\tp := new(hashed)\n\tp.major = majorVersion\n\tp.minor = minorVersion\n\n\terr := checkCost(cost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.cost = cost\n\tif len(unencodedSalt) != maxSaltSize {\n\t\treturn nil, errors.New(\"bcrypt: salt must be exactly 16 bytes\")\n\t}\n\n\n\tp.salt = base64Encode(unencodedSalt)\n\thash, err := bcrypt(password, p.cost, p.salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.hash = hash\n\treturn p, err\n}"} {"input": "package plAuth\n\nimport (\n\t\"fmt\"\n)\n\n\n\ntype UnsetPassword struct {\n\tuser *User\n}\n\nfunc (e UnsetPassword) Error() string {\n\treturn fmt.Sprintf(\"%s has no password set. Call SetPass() first!\", e.user)\n}\n\n\ntype WrongPassword int\n\nfunc (e WrongPassword) Error() string {\n\treturn fmt.Sprintf(\"Invalid Password\")\n}\n\n\ntype ValidationError struct {\n\tReason string\n}\n\n\n\ntype InterfaceConversionError struct {\n\tFailed interface{}\n}\n\nfunc (e InterfaceConversionError) Error() string {\n\treturn fmt.Sprintf(\"Conversition failed %#v\", e.Failed)\n}\n\ntype UserAllreadyExists struct {\n\texistingUser *User\n}\n\nfunc (e UserAllreadyExists) Error() string {\n\treturn fmt.Sprintf(\"A user with this data allreay exists: %v\", e.existingUser)\n}\n\nfunc (e ValidationError) Error() string ", "output": "{\n\treturn e.Reason\n}"} {"input": "package model\n\nimport (\n\t\"github.com/Konstantin8105/GoFea/input/element\"\n\t\"github.com/Konstantin8105/GoFea/input/material\"\n)\n\ntype materialLinearGroup struct {\n\tmaterial material.Linear\n\telementIndex element.Index\n}\n\n\ntype materialByElement []materialLinearGroup\n\n\nfunc (a materialByElement) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a materialByElement) Less(i, j int) bool { return a[i].elementIndex < a[j].elementIndex }\nfunc (a materialByElement) Equal(i, j int) bool { return a[i].elementIndex == a[j].elementIndex }\nfunc (a materialByElement) Name(i int) int { return int(a[i].elementIndex) }\n\nfunc (a materialByElement) Len() int ", "output": "{ return len(a) }"} {"input": "package main\n\nimport \"sort\"\n\ntype Node struct {\n\tLeft *Node\n\tRight *Node\n\tParent *Node\n\tValue uint\n\tFactor int\n}\n\n\n\nfunc GetHuffmanTableMap(root *Node) map[uint]string {\n\ttable := make(map[uint]string)\n\tscan(root, \"\", &table)\n\treturn table\n}\n\nfunc scan(root *Node, prefix string, table *map[uint]string) {\n\tif root.Left == nil || root.Right == nil {\n\t\t(*table)[root.Value] = prefix\n\t}\n\tif root.Left != nil {\n\t\tscan(root.Left, prefix + \"0\", table)\n\t}\n\tif root.Right != nil {\n\t\tscan(root.Right, prefix + \"1\", table)\n\t}\n}\n\nfunc GetHuffmanTree(arr []uint) *Node ", "output": "{\n\tm := make(map[uint]int)\n\tfor _, v := range arr {\n\t\tm[v]++\n\t}\n\tvar nodes []*Node\n\tfor k, v := range m {\n\t\tnodes = append(nodes, &Node{Value: k, Factor: v})\n\t}\n\tfor len(nodes) > 1 {\n\t\tsort.Slice(nodes, func(i, j int) bool {\n\t\t\treturn nodes[i].Factor < nodes[j].Factor\n\t\t})\n\t\tnewNode := &Node{Left: nodes[0], Right: nodes[1], Factor: nodes[0].Factor + nodes[1].Factor}\n\t\tnodes[0].Parent, nodes[1].Parent = newNode, newNode\n\t\tnodes = append(nodes[2:], newNode)\n\t}\n\tif len(nodes) == 1 {\n\t\treturn nodes[0]\n\t}\n\treturn nil\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/labstack/echo\"\n\n\t\"projects/onix/models\"\n\t\"projects/onix/utils\"\n)\n\n\ntype PostsController struct{}\n\n\nfunc (*PostsController) Get(c echo.Context) error {\n\tvar model models.Post\n\tvar title = c.QueryParam(\"title\")\n\n\tret, err := model.Get(title)\n\tif err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\n\treturn c.JSON(200, ret)\n}\n\n\nfunc (*PostsController) GetOne(c echo.Context) error {\n\tvar model models.Post\n\n\tret, err := model.GetOne(c.P(0))\n\tif err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\n\treturn c.JSON(200, ret)\n}\n\n\nfunc (*PostsController) Save(c echo.Context) error {\n\tvar model models.Post\n\tvar payload models.PostPayload\n\tvar status = c.QueryParam(\"status\")\n\n\tif err := c.Bind(&payload); err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\n\tiss := 1\n\n\tpayload.AuthorID = iss\n\tret, err := model.Create(payload, status)\n\tif err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\treturn c.JSON(200, ret)\n}\n\n\n\n\nfunc (*PostsController) Update(c echo.Context) error ", "output": "{\n\tvar model models.Post\n\tvar payload models.PostPayload\n\tvar status = c.QueryParam(\"status\")\n\n\tif err := c.Bind(&payload); err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\n\tiss := 1\n\n\tpayload.UpdatedBy = iss\n\tret, err := model.Update(c.P(0), payload, status)\n\tif err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\treturn c.JSON(200, ret)\n}"} {"input": "package sortedmap\n\nimport (\n\t\"testing\"\n\n\t\"github.com/umpc/go-sortedmap/asc\"\n)\n\nfunc insertRecord(b *testing.B) {\n\trecords := randRecords(1)\n\tsm := New(0, asc.Time)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsm.Insert(records[0].Key, records[0].Val)\n\n\t\tb.StopTimer()\n\t\trecords = randRecords(1)\n\t\tsm = New(0, asc.Time)\n\t\tb.StartTimer()\n\t}\n}\n\nfunc batchInsertRecords(b *testing.B, n int) {\n\trecords := randRecords(n)\n\tsm := New(0, asc.Time)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsm.BatchInsert(records)\n\n\t\tb.StopTimer()\n\t\trecords = randRecords(n)\n\t\tsm = New(0, asc.Time)\n\t\tb.StartTimer()\n\t}\n}\n\nfunc BenchmarkInsert1Record(b *testing.B) {\n\tinsertRecord(b)\n}\n\nfunc BenchmarkBatchInsert10Records(b *testing.B) {\n\tbatchInsertRecords(b, 10)\n}\n\nfunc BenchmarkBatchInsert100Records(b *testing.B) {\n\tbatchInsertRecords(b, 100)\n}\n\nfunc BenchmarkBatchInsert1000Records(b *testing.B) {\n\tbatchInsertRecords(b, 1000)\n}\n\n\n\nfunc BenchmarkBatchInsert10000Records(b *testing.B) ", "output": "{\n\tbatchInsertRecords(b, 10000)\n}"} {"input": "package options\n\nimport (\n\t\"strings\"\n\n\t\"github.com/pkg/errors\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/pflag\"\n)\n\ntype ClusterEditConfig struct {\n\tClusterName string\n\tFile string\n\tKubernetesVersion string\n\tLocked bool\n\tOutput string\n}\n\nfunc NewClusterEditConfig() *ClusterEditConfig {\n\treturn &ClusterEditConfig{\n\t\tClusterName: \"\",\n\t\tFile: \"\",\n\t\tKubernetesVersion: \"\",\n\t\tLocked: false,\n\t\tOutput: \"yaml\",\n\t}\n}\n\nfunc (c *ClusterEditConfig) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVarP(&c.File, \"file\", \"f\", c.File, \"Load cluster data from file\")\n\tfs.StringVar(&c.KubernetesVersion, \"kubernetes-version\", c.KubernetesVersion, \"Kubernetes version\")\n\tfs.BoolVar(&c.Locked, \"locked\", c.Locked, \"If true, locks cluster from deletion\")\n\tfs.StringVarP(&c.Output, \"output\", \"o\", c.Output, \"Output format. One of: yaml|json.\")\n\n}\n\nfunc (c *ClusterEditConfig) ValidateFlags(cmd *cobra.Command, args []string) error {\n\tif cmd.Flags().Changed(\"file\") {\n\t\tif len(args) != 0 {\n\t\t\treturn errors.New(\"no argument can be provided when --file flag is used\")\n\t\t}\n\t}\n\tif len(args) == 0 {\n\t\treturn errors.New(\"missing cluster name\")\n\t}\n\tif len(args) > 1 {\n\t\treturn errors.New(\"multiple cluster name provided\")\n\t}\n\tc.ClusterName = strings.ToLower(args[0])\n\treturn nil\n}\n\n\n\nfunc (c *ClusterEditConfig) CheckForUpdateFlags() bool ", "output": "{\n\tif c.Locked || c.KubernetesVersion != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package lang\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/mvader/bolt/runtime/errors\"\n\t\"github.com/mvader/bolt/runtime/stack\"\n)\n\nconst PrintlnSymbol = `println`\n\n\n\n\nfunc Println(s *stack.Stack, args ...interface{}) interface{} {\n\terrors.CheckNumArgsGte(PrintlnSymbol, args, 1)\n\tfmt.Println(args...)\n\treturn nil\n}\n\nconst PrintfSymbol = `printf`\n\n\n\n\n\nfunc Printf(s *stack.Stack, args ...interface{}) interface{} ", "output": "{\n\terrors.CheckNumArgsGte(PrintfSymbol, args, 2)\n\tformat, ok := args[0].(string)\n\tif !ok {\n\t\tpanic(errors.NewArgTypeError(PrintfSymbol, 1, args[0], \"string\"))\n\t}\n\tfmt.Printf(format, args[1:]...)\n\treturn nil\n}"} {"input": "package db\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"github.com/jmoiron/sqlx\"\n\t\"gopkg.in/yaml.v1\"\n)\n\n\ntype Configs map[string]*Config\n\n\nfunc (cs Configs) Open(env string) (*sqlx.DB, error) {\n\tconfig, ok := cs[env]\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\treturn config.Open()\n}\n\n\ntype Config struct {\n\tDatasource string `yaml:\"datasource\"`\n}\n\n\n\n\n\n\nfunc (c *Config) Open() (*sqlx.DB, error) {\n\treturn sqlx.Open(\"mysql\", c.DSN())\n}\n\n\nfunc NewConfigsFromFile(path string) (Configs, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treturn NewConfigs(f)\n}\n\n\nfunc NewConfigs(r io.Reader) (Configs, error) {\n\tb, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar configs Configs\n\tif err = yaml.Unmarshal(b, &configs); err != nil {\n\t\treturn nil, err\n\t}\n\treturn configs, nil\n}\n\nfunc (c *Config) DSN() string ", "output": "{\n\treturn c.Datasource\n}"} {"input": "package octokat\n\nimport (\n\t\"github.com/bmizerany/assert\"\n\t\"testing\"\n)\n\nfunc TestParamsPut(t *testing.T) {\n\tp := Params{\"FOO\": \"BAR\"}\n\tv := p.Put(\"BAZ\", \"BAR\")\n\n\tassert.Equal(t, 2, p.Size())\n\tassert.Equal(t, nil, v)\n\n\tv = p.Put(\"FOO\", \"FOO\")\n\tassert.Equal(t, 2, p.Size())\n\tassert.Equal(t, \"BAR\", v)\n}\n\n\n\nfunc TestParamsDelete(t *testing.T) ", "output": "{\n\tp := Params{\"FOO\": \"BAR\"}\n\tv := p.Delete(\"FOO\")\n\n\tassert.Equal(t, 0, p.Size())\n\tassert.Equal(t, \"BAR\", v)\n\n\tv = p.Delete(\"BAR\")\n\tassert.Equal(t, 0, p.Size())\n\tassert.Equal(t, nil, v)\n}"} {"input": "package version\n\nimport (\n\tapi \"github.com/containerd/containerd/api/services/version\"\n\t\"github.com/containerd/containerd/plugin\"\n\tctrdversion \"github.com/containerd/containerd/version\"\n\tempty \"github.com/golang/protobuf/ptypes/empty\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\nvar _ api.VersionServer = &Service{}\n\nfunc init() {\n\tplugin.Register(\"version-grpc\", &plugin.Registration{\n\t\tType: plugin.GRPCPlugin,\n\t\tInit: New,\n\t})\n}\n\nfunc New(ic *plugin.InitContext) (interface{}, error) {\n\treturn &Service{}, nil\n}\n\ntype Service struct {\n}\n\n\n\nfunc (s *Service) Version(ctx context.Context, _ *empty.Empty) (*api.VersionResponse, error) {\n\treturn &api.VersionResponse{\n\t\tVersion: ctrdversion.Version,\n\t\tRevision: ctrdversion.Revision,\n\t}, nil\n}\n\nfunc (s *Service) Register(server *grpc.Server) error ", "output": "{\n\tapi.RegisterVersionServer(server, s)\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/docker/docker/integration-cli/checker\"\n\t\"github.com/docker/docker/integration-cli/cli\"\n\t\"github.com/go-check/check\"\n\t\"github.com/gotestyourself/gotestyourself/icmd\"\n)\n\nfunc (s *DockerSuite) TestUpdateRestartPolicy(c *check.C) {\n\tout := cli.DockerCmd(c, \"run\", \"-d\", \"--restart=on-failure:3\", \"busybox\", \"sh\", \"-c\", \"sleep 1 && false\").Combined()\n\ttimeout := 60 * time.Second\n\tif testEnv.DaemonPlatform() == \"windows\" {\n\t\ttimeout = 180 * time.Second\n\t}\n\n\tid := strings.TrimSpace(string(out))\n\n\tcli.DockerCmd(c, \"update\", \"--restart=on-failure:5\", id)\n\n\tcli.WaitExited(c, id, timeout)\n\n\tcount := inspectField(c, id, \"RestartCount\")\n\tc.Assert(count, checker.Equals, \"5\")\n\n\tmaximumRetryCount := inspectField(c, id, \"HostConfig.RestartPolicy.MaximumRetryCount\")\n\tc.Assert(maximumRetryCount, checker.Equals, \"5\")\n}\n\n\n\nfunc (s *DockerSuite) TestUpdateRestartWithAutoRemoveFlag(c *check.C) ", "output": "{\n\tout := runSleepingContainer(c, \"--rm\")\n\tid := strings.TrimSpace(out)\n\n\tcli.Docker(cli.Args(\"update\", \"--restart=always\", id)).Assert(c, icmd.Expected{\n\t\tExitCode: 1,\n\t\tErr: \"Restart policy cannot be updated because AutoRemove is enabled for the container\",\n\t})\n}"} {"input": "package retrieval\n\nimport (\n\t\"time\"\n\n\t\"github.com/prometheus/common/model\"\n\n\t\"github.com/prometheus/prometheus/config\"\n)\n\ntype nopAppender struct{}\n\nfunc (a nopAppender) Append(*model.Sample) {\n}\n\ntype slowAppender struct{}\n\nfunc (a slowAppender) Append(*model.Sample) {\n\ttime.Sleep(time.Millisecond)\n\treturn\n}\n\ntype collectResultAppender struct {\n\tresult model.Samples\n}\n\nfunc (a *collectResultAppender) Append(s *model.Sample) {\n\tfor ln, lv := range s.Metric {\n\t\tif len(lv) == 0 {\n\t\t\tdelete(s.Metric, ln)\n\t\t}\n\t}\n\ta.result = append(a.result, s)\n}\n\n\n\ntype fakeTargetProvider struct {\n\tsources []string\n\tupdate chan *config.TargetGroup\n}\n\nfunc (tp *fakeTargetProvider) Run(ch chan<- *config.TargetGroup, done <-chan struct{}) {\n\tdefer close(ch)\n\tfor {\n\t\tselect {\n\t\tcase tg := <-tp.update:\n\t\t\tch <- tg\n\t\tcase <-done:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\nfunc (tp *fakeTargetProvider) Sources() []string ", "output": "{\n\treturn tp.sources\n}"} {"input": "package main\n\nimport (\n\t\"html/template\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype Page struct {\n\tTitle string\n\tBody []byte\n}\n\n\n\nfunc loadPage(title string) (*Page, error) {\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Page{Title: title, Body: body}, nil\n}\n\nfunc editHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/edit/\"):]\n\tp, err := loadPage(title)\n\tif err != nil {\n\t\tp = &Page{Title: title}\n\t}\n\trenderTemplate(w, \"edit\", p)\n}\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/view/\"):]\n\tp, _ := loadPage(title)\n\trenderTemplate(w, \"view\", p)\n}\n\nfunc saveHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/save/\"):]\n\tbody := r.FormValue(\"body\")\n\tp := &Page{Title: title, Body: []byte(body)}\n\tp.save()\n\thttp.Redirect(w, r, \"/view/\"+title, http.StatusFound)\n}\n\nfunc renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {\n\tt, _ := template.ParseFiles(tmpl + \".html\")\n\tt.Execute(w, p)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/view/\", viewHandler)\n\thttp.HandleFunc(\"/edit/\", editHandler)\n\thttp.HandleFunc(\"/save/\", saveHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc (p *Page) save() error ", "output": "{\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}"} {"input": "package fake\n\nimport (\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n\n\taction \"github.com/vmware-tanzu/octant/pkg/action\"\n)\n\n\ntype MockActionRegistrar struct {\n\tctrl *gomock.Controller\n\trecorder *MockActionRegistrarMockRecorder\n}\n\n\ntype MockActionRegistrarMockRecorder struct {\n\tmock *MockActionRegistrar\n}\n\n\nfunc NewMockActionRegistrar(ctrl *gomock.Controller) *MockActionRegistrar {\n\tmock := &MockActionRegistrar{ctrl: ctrl}\n\tmock.recorder = &MockActionRegistrarMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockActionRegistrar) EXPECT() *MockActionRegistrarMockRecorder {\n\treturn m.recorder\n}\n\n\nfunc (m *MockActionRegistrar) Register(arg0, arg1 string, arg2 action.DispatcherFunc) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Register\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}\n\n\n\n\n\nfunc (m *MockActionRegistrar) Unregister(arg0, arg1 string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Unregister\", arg0, arg1)\n}\n\n\nfunc (mr *MockActionRegistrarMockRecorder) Unregister(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Unregister\", reflect.TypeOf((*MockActionRegistrar)(nil).Unregister), arg0, arg1)\n}\n\nfunc (mr *MockActionRegistrarMockRecorder) Register(arg0, arg1, arg2 interface{}) *gomock.Call ", "output": "{\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Register\", reflect.TypeOf((*MockActionRegistrar)(nil).Register), arg0, arg1, arg2)\n}"} {"input": "package userinfo\n\nimport (\n\t\"os\"\n)\n\nfunc GetUserLogin() (login string) {\n\tlogin = os.Getenv(\"USER\")\n\treturn\n}\n\n\n\nfunc GetUserHome() (home string) ", "output": "{\n\thome = os.Getenv(\"HOME\")\n\treturn\n}"} {"input": "package cmdserver_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestCmdServer(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"CmdServer Suite\")\n}"} {"input": "package types\n\nimport (\n\t\"math\"\n)\n\n\n\n\n\nfunc RoundFloat(val float64) float64 {\n\tv, frac := math.Modf(val)\n\tif val >= 0.0 {\n\t\tif frac > 0.5 || (frac == 0.5 && uint64(v)%2 != 0) {\n\t\t\tv += 1.0\n\t\t}\n\t} else {\n\t\tif frac < -0.5 || (frac == -0.5 && uint64(v)%2 != 0) {\n\t\t\tv -= 1.0\n\t\t}\n\t}\n\n\treturn v\n}\n\nfunc getMaxFloat(flen int, decimal int) float64 {\n\tintPartLen := flen - decimal\n\tf := math.Pow10(intPartLen)\n\tf -= math.Pow10(-decimal)\n\treturn f\n}\n\nfunc truncateFloat(f float64, decimal int) float64 {\n\tpow := math.Pow10(decimal)\n\tt := (f - math.Floor(f)) * pow\n\n\tround := RoundFloat(t)\n\n\tf = math.Floor(f) + round/pow\n\treturn f\n}\n\n\n\n\n\nfunc TruncateFloat(f float64, flen int, decimal int) (float64, error) ", "output": "{\n\tif math.IsNaN(f) {\n\t\treturn 0, nil\n\t}\n\n\tmaxF := getMaxFloat(flen, decimal)\n\n\tif !math.IsInf(f, 0) {\n\t\tf = truncateFloat(f, decimal)\n\t}\n\n\tif f > maxF {\n\t\tf = maxF\n\t} else if f < -maxF {\n\t\tf = -maxF\n\t}\n\n\treturn f, nil\n}"} {"input": "package sol\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aodin/sol/dialect\"\n)\n\n\ntype DropStmt struct {\n\ttable *TableElem\n\tifExists bool\n}\n\n\nfunc (stmt DropStmt) IfExists() DropStmt {\n\tstmt.ifExists = true\n\treturn stmt\n}\n\n\n\n\n\n\n\nfunc (stmt DropStmt) Compile(d dialect.Dialect, p *Parameters) (string, error) {\n\tif stmt.ifExists {\n\t\treturn fmt.Sprintf(`DROP TABLE IF EXISTS %s`, stmt.table.Name()), nil\n\t}\n\treturn fmt.Sprintf(`DROP TABLE %s`, stmt.table.Name()), nil\n}\n\nfunc (stmt DropStmt) String() string ", "output": "{\n\tc, _ := stmt.Compile(&defaultDialect{}, Params())\n\treturn c\n}"} {"input": "package greatspacerace\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"github.com/TSavo/go.firebase\"\n\t\"os\"\n)\n\nfunc init() {\n\tf, err := os.Open(\"firebase.secret\")\n\tif err != nil {\n\t\tfmt.Printf(\"error opening firebase.secret: %v\\n\", err)\n\t}\n\tr := bufio.NewReader(f)\n\turl, e := Readln(r)\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\tsecret, e := Readln(r)\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\tdb = firebase.New(url, secret)\n}\n\nvar db *firebase.FirebaseRoot;\n\n\n\nfunc Readln(r *bufio.Reader) (string, error) ", "output": "{\n\tvar (\n\t\tisPrefix bool = true\n\t\terr error = nil\n\t\tline, ln []byte\n\t)\n\tfor isPrefix && err == nil {\n\t\tline, isPrefix, err = r.ReadLine()\n\t\tln = append(ln, line...)\n\t}\n\treturn string(ln), err\n}"} {"input": "package gtk\n\n\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n\n\t\"github.com/untoldwind/amintk/gdk\"\n)\n\n\ntype Image struct {\n\tWidget\n}\n\n\nfunc ImageNew() *Image {\n\tc := C.gtk_image_new()\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\nfunc (v *Image) native() *C.GtkImage {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn (*C.GtkImage)(v.Native())\n}\n\n\n\n\n\nfunc ImageNewFromPixbuf(pixbuf *gdk.Pixbuf) *Image {\n\tptr := (*C.GdkPixbuf)(pixbuf.Native())\n\tc := C.gtk_image_new_from_pixbuf(ptr)\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\nfunc wrapImage(p unsafe.Pointer) *Image {\n\tif widget := wrapWidget(p); widget != nil {\n\t\treturn &Image{Widget: *widget}\n\t}\n\treturn nil\n}\n\n\nfunc (v *Image) Clear() {\n\tC.gtk_image_clear(v.native())\n}\n\n\nfunc (v *Image) SetFromPixbuf(pixbuf *gdk.Pixbuf) {\n\tpbptr := (*C.GdkPixbuf)(pixbuf.Native())\n\tC.gtk_image_set_from_pixbuf(v.native(), pbptr)\n}\n\nfunc ImageNewFromIconName(iconName string, size IconSize) *Image ", "output": "{\n\tcstr := C.CString(iconName)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_image_new_from_icon_name((*C.gchar)(cstr),\n\t\tC.GtkIconSize(size))\n\treturn wrapImage(unsafe.Pointer(c))\n}"} {"input": "package grpcproxy\n\nimport (\n\t\"context\"\n\n\t\"github.com/coreos/etcd/clientv3\"\n\t\"github.com/coreos/etcd/etcdserver/api/v3lock/v3lockpb\"\n)\n\ntype lockProxy struct {\n\tclient *clientv3.Client\n}\n\nfunc NewLockProxy(client *clientv3.Client) v3lockpb.LockServer {\n\treturn &lockProxy{client: client}\n}\n\n\n\nfunc (lp *lockProxy) Unlock(ctx context.Context, req *v3lockpb.UnlockRequest) (*v3lockpb.UnlockResponse, error) {\n\treturn v3lockpb.NewLockClient(lp.client.ActiveConnection()).Unlock(ctx, req)\n}\n\nfunc (lp *lockProxy) Lock(ctx context.Context, req *v3lockpb.LockRequest) (*v3lockpb.LockResponse, error) ", "output": "{\n\treturn v3lockpb.NewLockClient(lp.client.ActiveConnection()).Lock(ctx, req)\n}"} {"input": "package spi\n\n\n\n\n\nfunc (g *GroupInfo) GetName() string {\n\treturn g.Name\n}\n\n\nfunc (g *GroupInfo) GetChildren() ([]Group, error) {\n\treturn nil, nil\n}\n\n\nfunc (g *GroupInfo) GetParent() string {\n\treturn g.ParentID\n}\n\nfunc NewGroup(group *GroupInfo) Group ", "output": "{\n\treturn group\n}"} {"input": "package classfile\n\nimport (\n\t\"github.com/zxh0/jvm.go/jvmgo/util/bigendian\"\n)\n\ntype ClassReader struct {\n\tdata []byte\n}\n\nfunc newClassReader(data []byte) *ClassReader {\n\treturn &ClassReader{data}\n}\n\nfunc (self *ClassReader) readUint8() uint8 {\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16() uint16 {\n\tval := bigendian.Uint16(self.data)\n\tself.data = self.data[2:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint32() uint32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn uint32(val)\n}\nfunc (self *ClassReader) readInt32() int32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readInt64() int64 {\n\tval := bigendian.Int64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readFloat32() float32 {\n\tval := bigendian.Float32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\n\n\nfunc (self *ClassReader) readBytes(length uint32) []byte {\n\tbytes := self.data[:length]\n\tself.data = self.data[length:]\n\treturn bytes\n}\n\n\nfunc (self *ClassReader) readString() string {\n\tlength := uint32(self.readUint16())\n\tbytes := self.readBytes(length)\n\treturn string(bytes)\n}\n\nfunc (self *ClassReader) readFloat64() float64 ", "output": "{\n\tval := bigendian.Float64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}"} {"input": "package snet\n\nimport (\n\t\"github.com/scionproto/scion/go/lib/slayers\"\n)\n\n\n\nfunc SCMPParameterProblemWithCode(m SCMPParameterProblem, c slayers.SCMPCode) SCMPParameterProblem ", "output": "{\n\tm.code = c\n\treturn m\n}"} {"input": "package datatype\n\nimport \"fmt\"\n\n\ntype OctetString string\n\n\n\n\n\nfunc (s OctetString) Serialize() []byte {\n\treturn []byte(s)\n}\n\n\nfunc (s OctetString) Len() int {\n\treturn len(s)\n}\n\n\nfunc (s OctetString) Padding() int {\n\tl := len(s)\n\treturn pad4(l) - l\n}\n\n\nfunc (s OctetString) Type() TypeID {\n\treturn OctetStringType\n}\n\n\nfunc (s OctetString) String() string {\n\treturn fmt.Sprintf(\"OctetString{%#x},Padding:%d\", string(s), s.Padding())\n}\n\nfunc DecodeOctetString(b []byte) (Type, error) ", "output": "{\n\treturn OctetString(b), nil\n}"} {"input": "package fake\n\nimport (\n\tcontext \"context\"\n\n\truntime \"k8s.io/apimachinery/pkg/runtime\"\n\trest \"k8s.io/client-go/rest\"\n\tfake \"knative.dev/eventing-prometheus/pkg/client/clientset/versioned/fake\"\n\tclient \"knative.dev/eventing-prometheus/pkg/client/injection/client\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Fake.RegisterClient(withClient)\n\tinjection.Fake.RegisterClientFetcher(func(ctx context.Context) interface{} {\n\t\treturn Get(ctx)\n\t})\n}\n\n\n\nfunc With(ctx context.Context, objects ...runtime.Object) (context.Context, *fake.Clientset) {\n\tcs := fake.NewSimpleClientset(objects...)\n\treturn context.WithValue(ctx, client.Key{}, cs), cs\n}\n\n\nfunc Get(ctx context.Context) *fake.Clientset {\n\tuntyped := ctx.Value(client.Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch knative.dev/eventing-prometheus/pkg/client/clientset/versioned/fake.Clientset from context.\")\n\t}\n\treturn untyped.(*fake.Clientset)\n}\n\nfunc withClient(ctx context.Context, cfg *rest.Config) context.Context ", "output": "{\n\tctx, _ = With(ctx)\n\treturn ctx\n}"} {"input": "package version\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/coreos/go-semver/semver\"\n)\n\nvar (\n\tMinClusterVersion = \"3.0.0\"\n\tVersion = \"3.4.14\"\n\tAPIVersion = \"unknown\"\n\n\tGitSHA = \"Not provided (use ./build instead of go build)\"\n)\n\n\n\ntype Versions struct {\n\tServer string `json:\"etcdserver\"`\n\tCluster string `json:\"etcdcluster\"`\n}\n\n\nfunc Cluster(v string) string {\n\tvs := strings.Split(v, \".\")\n\tif len(vs) <= 2 {\n\t\treturn v\n\t}\n\treturn fmt.Sprintf(\"%s.%s\", vs[0], vs[1])\n}\n\nfunc init() ", "output": "{\n\tver, err := semver.NewVersion(Version)\n\tif err == nil {\n\t\tAPIVersion = fmt.Sprintf(\"%d.%d\", ver.Major, ver.Minor)\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/resource\"\n)\n\n\nfunc (self ResourceName) String() string {\n\treturn string(self)\n}\n\n\nfunc (self *ResourceList) Cpu() *resource.Quantity {\n\tif val, ok := (*self)[ResourceCPU]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{}\n}\n\n\nfunc (self *ResourceList) Memory() *resource.Quantity {\n\tif val, ok := (*self)[ResourceMemory]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{}\n}\n\n\n\nfunc GetContainerStatus(statuses []ContainerStatus, name string) (ContainerStatus, bool) {\n\tfor i := range statuses {\n\t\tif statuses[i].Name == name {\n\t\t\treturn statuses[i], true\n\t\t}\n\t}\n\treturn ContainerStatus{}, false\n}\n\nfunc GetExistingContainerStatus(statuses []ContainerStatus, name string) ContainerStatus {\n\tfor i := range statuses {\n\t\tif statuses[i].Name == name {\n\t\t\treturn statuses[i]\n\t\t}\n\t}\n\treturn ContainerStatus{}\n}\n\n\nfunc IsPodReady(pod *Pod) bool {\n\tfor _, c := range pod.Status.Conditions {\n\t\tif c.Type == PodReady && c.Status == ConditionTrue {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (self *ResourceList) Pods() *resource.Quantity ", "output": "{\n\tif val, ok := (*self)[ResourcePods]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{}\n}"} {"input": "package main\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"os/exec\"\n\t\"text/template\"\n\n\t\"github.com/golang/glog\"\n\tk8sexec \"k8s.io/kubernetes/pkg/util/exec\"\n)\n\nconst (\n\tnsdTmpl = `\n`\n)\n\ntype record struct {\n\tname string\n\tip net.IP\n}\n\ntype nsd struct {\n\tns []record\n\ta []record\n}\n\nfunc (k *nsd) WriteCfg(svcs []vip) error {\n\tw, err := os.Create(\"/etc/nsd/nsd.conf.\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer w.Close()\n\n\tt, err := template.New(\"nsd\").Parse(nsdTmpl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconf := make(map[string]interface{})\n\tconf[\"ns\"] = k.iface\n\tconf[\"a\"] = k.ip\n\n\tb, _ := json.Marshal(conf)\n\tglog.Infof(\"%v\", string(b))\n\n\treturn t.Execute(w, conf)\n}\n\nfunc (k *nsd) Start() {\n\tcmd := exec.Command(\"/usr/sbin/nsd\",\n\t\t\"-d\",\n\t\t\"-P\", \"/nsd.pid\")\n\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\tif err := cmd.Start(); err != nil {\n\t\tglog.Errorf(\"nsd error: %v\", err)\n\t}\n\n\tif err := cmd.Wait(); err != nil {\n\t\tglog.Fatalf(\"nsd error: %v\", err)\n\t}\n}\n\n\n\nfunc (k *nsd) Reload() error ", "output": "{\n\tglog.Info(\"reloading nsd server\")\n\t_, err := k8sexec.New().Command(\"killall\", \"-1\", \"nsd\").CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reloading nsd: %v\", err)\n\t}\n\n\treturn nil\n}"} {"input": "package nsqlookup\n\nimport \"bufio\"\n\ntype Ping struct {\n}\n\nfunc (c Ping) Name() string {\n\treturn \"PING\"\n}\n\nfunc (c Ping) Write(w *bufio.Writer) (err error) {\n\t_, err = w.WriteString(\"PING\\n\")\n\treturn\n}\n\n\n\nfunc readPing(args ...string) (cmd Ping, err error) ", "output": "{\n\treturn\n}"} {"input": "package profitbricks\n\nimport (\n\t\"fmt\"\n\t\"github.com/hashicorp/packer/communicator/ssh\"\n\t\"github.com/mitchellh/multistep\"\n\tgossh \"golang.org/x/crypto/ssh\"\n)\n\n\n\nfunc sshConfig(state multistep.StateBag) (*gossh.ClientConfig, error) {\n\tconfig := state.Get(\"config\").(*Config)\n\tvar privateKey string\n\n\tvar auth []gossh.AuthMethod\n\n\tif config.Comm.SSHPassword != \"\" {\n\t\tauth = []gossh.AuthMethod{\n\t\t\tgossh.Password(config.Comm.SSHPassword),\n\t\t\tgossh.KeyboardInteractive(\n\t\t\t\tssh.PasswordKeyboardInteractive(config.Comm.SSHPassword)),\n\t\t}\n\t}\n\n\tif config.Comm.SSHPrivateKey != \"\" {\n\t\tif priv, ok := state.GetOk(\"privateKey\"); ok {\n\t\t\tprivateKey = priv.(string)\n\t\t}\n\t\tsigner, err := gossh.ParsePrivateKey([]byte(privateKey))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error setting up SSH config: %s\", err)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tauth = append(auth, gossh.PublicKeys(signer))\n\t}\n\treturn &gossh.ClientConfig{\n\t\tUser: config.Comm.SSHUsername,\n\t\tAuth: auth,\n\t\tHostKeyCallback: gossh.InsecureIgnoreHostKey(),\n\t}, nil\n}\n\nfunc commHost(state multistep.StateBag) (string, error) ", "output": "{\n\tipAddress := state.Get(\"server_ip\").(string)\n\treturn ipAddress, nil\n}"} {"input": "package iso20022\n\n\ntype StatementType2Choice struct {\n\n\tCode *SecuritiesStatementType1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification20 `xml:\"Prtry\"`\n}\n\nfunc (s *StatementType2Choice) SetCode(value string) {\n\ts.Code = (*SecuritiesStatementType1Code)(&value)\n}\n\n\n\nfunc (s *StatementType2Choice) AddProprietary() *GenericIdentification20 ", "output": "{\n\ts.Proprietary = new(GenericIdentification20)\n\treturn s.Proprietary\n}"} {"input": "package co\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\n\t\"github.com/pkg/errors\"\n\n\t\"github.com/ynqa/wego/pkg/corpus/cooccurrence/encode\"\n)\n\ntype CountType = string\n\nconst (\n\tIncrement CountType = \"inc\"\n\tProximity CountType = \"prox\"\n)\n\nfunc invalidCountTypeError(typ CountType) error {\n\treturn fmt.Errorf(\"invalid relation type: %s not in %s|%s\", typ, Increment, Proximity)\n}\n\ntype Cooccurrence struct {\n\ttyp CountType\n\n\tma map[uint64]float64\n}\n\n\n\nfunc (c *Cooccurrence) EncodedMatrix() map[uint64]float64 {\n\treturn c.ma\n}\n\nfunc (c *Cooccurrence) Add(left, right int) error {\n\tenc := encode.EncodeBigram(uint64(left), uint64(right))\n\tvar val float64\n\tswitch c.typ {\n\tcase Increment:\n\t\tval = 1\n\tcase Proximity:\n\t\tdiv := left - right\n\t\tif div == 0 {\n\t\t\treturn errors.Errorf(\"Divide by zero on counting co-occurrence\")\n\t\t}\n\t\tval = 1. / math.Abs(float64(div))\n\tdefault:\n\t\treturn invalidCountTypeError(c.typ)\n\t}\n\tc.ma[enc] += val\n\treturn nil\n}\n\nfunc New(typ CountType) (*Cooccurrence, error) ", "output": "{\n\tif typ != Increment && typ != Proximity {\n\t\treturn nil, invalidCountTypeError(typ)\n\t}\n\treturn &Cooccurrence{\n\t\ttyp: typ,\n\n\t\tma: make(map[uint64]float64),\n\t}, nil\n}"} {"input": "package models\n\nimport (\n\t\"github.com/macococo/go-gamereviews/utils\"\n)\n\ntype User struct {\n\tId int\n\tName string\n\tType int\n\tModel\n}\n\ntype UserManager struct {\n}\n\nfunc (this *UserManager) TableName() string {\n\treturn \"t_user\"\n}\n\n\n\nfunc (this *UserManager) Count(t int) int64 {\n\tcount, err := DbMap.SelectInt(\"SELECT count(*) FROM \"+this.TableName()+\" WHERE type = ?\", t)\n\tutils.HandleError(err)\n\n\treturn count\n}\n\nfunc (this *UserManager) Find(t int, pagination *Pagination) []*User {\n\tvar users []*User\n\t_, err := DbMap.Select(&users, \"SELECT * FROM \"+this.TableName()+\" WHERE type = ? LIMIT ?, ?\", t, (pagination.Page-1)*pagination.Length, pagination.Length)\n\tutils.HandleError(err)\n\n\treturn users\n}\n\nfunc (this *UserManager) Create(user *User) *User {\n\tutils.HandleError(DbMap.Insert(user))\n\treturn user\n}\n\nfunc (this *UserManager) AddTable() ", "output": "{\n\tDbMap.AddTableWithName(User{}, this.TableName()).SetKeys(true, \"Id\")\n}"} {"input": "package stdlib\n\nimport (\n\t\"container/heap\"\n\t\"reflect\"\n)\n\nfunc init() {\n\tSymbols[\"container/heap\"] = map[string]reflect.Value{\n\t\t\"Fix\": reflect.ValueOf(heap.Fix),\n\t\t\"Init\": reflect.ValueOf(heap.Init),\n\t\t\"Pop\": reflect.ValueOf(heap.Pop),\n\t\t\"Push\": reflect.ValueOf(heap.Push),\n\t\t\"Remove\": reflect.ValueOf(heap.Remove),\n\n\t\t\"Interface\": reflect.ValueOf((*heap.Interface)(nil)),\n\n\t\t\"_Interface\": reflect.ValueOf((*_container_heap_Interface)(nil)),\n\t}\n}\n\n\ntype _container_heap_Interface struct {\n\tWLen func() int\n\tWLess func(i int, j int) bool\n\tWPop func() interface{}\n\tWPush func(x interface{})\n\tWSwap func(i int, j int)\n}\n\nfunc (W _container_heap_Interface) Len() int { return W.WLen() }\nfunc (W _container_heap_Interface) Less(i int, j int) bool { return W.WLess(i, j) }\n\nfunc (W _container_heap_Interface) Push(x interface{}) { W.WPush(x) }\nfunc (W _container_heap_Interface) Swap(i int, j int) { W.WSwap(i, j) }\n\nfunc (W _container_heap_Interface) Pop() interface{} ", "output": "{ return W.WPop() }"} {"input": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"strings\"\n)\n\ntype marshalerForTest struct {\n\tX string\n}\n\nfunc encode(str string) string {\n\tbuf := bytes.Buffer{}\n\tb64 := base64.NewEncoder(base64.StdEncoding, &buf)\n\tif _, err := b64.Write([]byte(str)); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := b64.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn buf.String()\n}\n\n\n\nfunc (m marshalerForTest) MarshalJSON() ([]byte, error) {\n\treturn []byte(`\"MANUAL__` + encode(m.X) + `\"`), nil\n}\n\nfunc (m *marshalerForTest) UnmarshalJSON(text []byte) error {\n\tm.X = decode(strings.TrimPrefix(strings.Trim(string(text), `\"`), \"MANUAL__\"))\n\treturn nil\n}\n\nvar _ json.Marshaler = marshalerForTest{}\nvar _ json.Unmarshaler = &marshalerForTest{}\n\ntype typeForTest struct {\n\tS string\n\tM marshalerForTest\n\tI int8\n}\n\nfunc decode(str string) string ", "output": "{\n\tif len(str) == 0 {\n\t\treturn \"\"\n\t}\n\tb64 := base64.NewDecoder(base64.StdEncoding, strings.NewReader(str))\n\tbs := make([]byte, len(str))\n\tif n, err := b64.Read(bs); err != nil {\n\t\tpanic(err)\n\t} else {\n\t\tbs = bs[:n]\n\t}\n\treturn string(bs)\n}"} {"input": "package db\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/boltdb/bolt\"\n\t\"hawx.me/code/phemera/models\"\n)\n\ntype Db interface {\n\tGet() models.Entries\n\tSave(time.Time, string)\n\tClose()\n}\n\ntype BoltDb struct {\n\tme *bolt.DB\n\thorizon time.Duration\n}\n\nconst bucketName = \"phemera\"\n\n\n\nfunc (db BoltDb) Get() models.Entries {\n\tlist := models.Entries{}\n\n\tdb.me.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(bucketName))\n\t\tc := b.Cursor()\n\n\t\tbound := timestamp(time.Now().Add(db.horizon))\n\t\tfor k, v := c.Last(); k != nil && bytes.Compare(k, bound) >= 0; k, v = c.Prev() {\n\t\t\tlist = append(list, models.Entry{string(k), string(v)})\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn list\n}\n\nfunc (db BoltDb) Save(key time.Time, value string) {\n\tdb.me.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(bucketName))\n\t\terr := b.Put([]byte(timestamp(key)), []byte(value))\n\t\treturn err\n\t})\n}\n\nfunc (db BoltDb) Close() {\n\tdb.me.Close()\n}\n\nfunc timestamp(t time.Time) []byte {\n\treturn []byte(strconv.FormatInt(t.Unix(), 10))\n}\n\nfunc Open(path, horizon string) Db ", "output": "{\n\tdb, err := bolt.Open(path, 0600, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdb.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucket([]byte(bucketName))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"create bucket: %s\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\tho, _ := time.ParseDuration(horizon)\n\n\treturn BoltDb{db, ho}\n}"} {"input": "package winapi\n\nimport (\n\t\"unsafe\"\n)\n\n\nfunc CreateMDIWindow(lpClassName string, lpWindowName string, dwStyle uintptr, X int32, Y int32, nWidth uintptr, nHeight uintptr, hWndParent uintptr, hInstance uintptr, lParam uintptr) (uintptr, error) {\n\t_lpClassName, err := stringToUintptr(lpClassName)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\t_lpWindowName, err := stringToUintptr(lpWindowName)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tr1, _, err := procCreateMDIWindow.Call(_lpClassName, _lpWindowName, dwStyle, int32ToUintptr(X), int32ToUintptr(Y), nWidth, nHeight, hWndParent, hInstance, lParam)\n\treturn r1, err\n}\n\n\nfunc DefFrameProc(hWnd uintptr, hWndMDIClient uintptr, uMsg uintptr, wParam uintptr, lParam uintptr) (uintptr, error) {\n\tr1, _, err := procDefFrameProc.Call(hWnd, hWndMDIClient, uMsg, wParam, lParam)\n\treturn r1, err\n}\n\n\n\n\n\nfunc TranslateMDISysAccel(hWndClient uintptr, lpMsg *MSG) (uintptr, error) {\n\tr1, _, err := procTranslateMDISysAccel.Call(hWndClient, uintptr(unsafe.Pointer(lpMsg)))\n\treturn r1, err\n}\n\nfunc DefMDIChildProc(hWnd uintptr, uMsg uintptr, wParam uintptr, lParam uintptr) (uintptr, error) ", "output": "{\n\tr1, _, err := procDefMDIChildProc.Call(hWnd, uMsg, wParam, lParam)\n\treturn r1, err\n}"} {"input": "package instructions\n\nimport \"github.com/zxh0/jvm.go/jvmgo/jvm/rtda\"\n\n\ntype astore struct{ Index8Instruction }\n\n\n\ntype astore_0 struct{ NoOperandsInstruction }\n\nfunc (self *astore_0) Execute(frame *rtda.Frame) {\n\t_astore(frame, 0)\n}\n\ntype astore_1 struct{ NoOperandsInstruction }\n\nfunc (self *astore_1) Execute(frame *rtda.Frame) {\n\t_astore(frame, 1)\n}\n\ntype astore_2 struct{ NoOperandsInstruction }\n\nfunc (self *astore_2) Execute(frame *rtda.Frame) {\n\t_astore(frame, 2)\n}\n\ntype astore_3 struct{ NoOperandsInstruction }\n\nfunc (self *astore_3) Execute(frame *rtda.Frame) {\n\t_astore(frame, 3)\n}\n\nfunc _astore(frame *rtda.Frame, index uint) {\n\tref := frame.OperandStack().PopRef()\n\tframe.LocalVars().SetRef(index, ref)\n}\n\nfunc (self *astore) Execute(frame *rtda.Frame) ", "output": "{\n\t_astore(frame, uint(self.index))\n}"} {"input": "package v1alpha1\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\tv1alpha1 \"k8s.io/ingress-gce/pkg/experimental/apis/workload/v1alpha1\"\n\t\"k8s.io/ingress-gce/pkg/experimental/workload/client/clientset/versioned/scheme\"\n)\n\ntype NetworkingV1alpha1Interface interface {\n\tRESTClient() rest.Interface\n\tWorkloadsGetter\n}\n\n\ntype NetworkingV1alpha1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *NetworkingV1alpha1Client) Workloads(namespace string) WorkloadInterface {\n\treturn newWorkloads(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*NetworkingV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &NetworkingV1alpha1Client{client}, nil\n}\n\n\n\n\n\n\nfunc New(c rest.Interface) *NetworkingV1alpha1Client {\n\treturn &NetworkingV1alpha1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *NetworkingV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfigOrDie(c *rest.Config) *NetworkingV1alpha1Client ", "output": "{\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}"} {"input": "package kafka\n\nimport (\n\t\"encoding/binary\"\n\t\"hash/crc32\"\n)\n\ntype crc32Writer struct {\n\ttable *crc32.Table\n\tbuffer [8]byte\n\tcrc32 uint32\n}\n\nfunc (w *crc32Writer) update(b []byte) {\n\tw.crc32 = crc32.Update(w.crc32, w.table, b)\n}\n\nfunc (w *crc32Writer) writeInt8(i int8) {\n\tw.buffer[0] = byte(i)\n\tw.update(w.buffer[:1])\n}\n\nfunc (w *crc32Writer) writeInt16(i int16) {\n\tbinary.BigEndian.PutUint16(w.buffer[:2], uint16(i))\n\tw.update(w.buffer[:2])\n}\n\nfunc (w *crc32Writer) writeInt32(i int32) {\n\tbinary.BigEndian.PutUint32(w.buffer[:4], uint32(i))\n\tw.update(w.buffer[:4])\n}\n\nfunc (w *crc32Writer) writeInt64(i int64) {\n\tbinary.BigEndian.PutUint64(w.buffer[:8], uint64(i))\n\tw.update(w.buffer[:8])\n}\n\nfunc (w *crc32Writer) writeBytes(b []byte) {\n\tn := len(b)\n\tif b == nil {\n\t\tn = -1\n\t}\n\tw.writeInt32(int32(n))\n\tw.update(b)\n}\n\nfunc (w *crc32Writer) Write(b []byte) (int, error) {\n\tw.update(b)\n\treturn len(b), nil\n}\n\n\n\nfunc (w *crc32Writer) WriteString(s string) (int, error) ", "output": "{\n\tw.update([]byte(s))\n\treturn len(s), nil\n}"} {"input": "package gobuddyfs\n\nimport (\n\t\"sync\"\n\n\t\"github.com/golang/glog\"\n)\n\ntype MemStore struct {\n\tlock *sync.RWMutex\n\tstore map[string][]byte\n\n\tKVStore\n}\n\nfunc NewMemStore() *MemStore {\n\treturn &MemStore{store: make(map[string][]byte), lock: &sync.RWMutex{}}\n}\n\n\n\nfunc (self *MemStore) Set(key string, value []byte) error {\n\tif glog.V(2) {\n\t\tglog.Infof(\"Set(%s)\\n\", key)\n\t}\n\tself.lock.Lock()\n\tdefer self.lock.Unlock()\n\n\tif value == nil {\n\t\tdelete(self.store, key)\n\t} else {\n\t\tself.store[key] = value\n\t}\n\n\treturn nil\n}\n\nvar _ KVStore = new(MemStore)\n\nfunc (self *MemStore) Get(key string, retry bool) ([]byte, error) ", "output": "{\n\tif glog.V(2) {\n\t\tglog.Infof(\"Get(%s)\\n\", key)\n\t}\n\tself.lock.RLock()\n\tdefer self.lock.RUnlock()\n\tval, ok := self.store[key]\n\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\n\treturn val, nil\n}"} {"input": "package swt\n\nimport \"github.com/timob/javabind\"\n\ntype EventsTraverseEventInterface interface {\n\tEventsKeyEventInterface\n}\n\ntype EventsTraverseEvent struct {\n\tEventsKeyEvent\n}\n\n\nfunc NewEventsTraverseEvent(a WidgetsEventInterface) (*EventsTraverseEvent) {\n\tconv_a := javabind.NewGoToJavaCallable()\n\tif err := conv_a.Convert(a); err != nil {\n\t\tpanic(err)\n\t}\n\n\tobj, err := javabind.GetEnv().NewObject(\"org/eclipse/swt/events/TraverseEvent\", conv_a.Value().Cast(\"org/eclipse/swt/widgets/Event\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tconv_a.CleanUp()\n\tx := &EventsTraverseEvent{}\n\tx.Callable = &javabind.Callable{obj}\n\treturn x\n}\n\n\n\n\nfunc (jbobject *EventsTraverseEvent) Detail() int {\n\tjret, err := jbobject.GetField(javabind.GetEnv(), \"detail\", javabind.Int)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn jret.(int)\n}\n\nfunc (jbobject *EventsTraverseEvent) SetFieldDetail(val int) {\n\terr := jbobject.SetField(javabind.GetEnv(), \"detail\", val)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n}\n\nfunc (jbobject *EventsTraverseEvent) ToString() string ", "output": "{\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"toString\", \"java/lang/String\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tretconv := javabind.NewJavaToGoString()\n\tdst := new(string)\n\tretconv.Dest(dst)\n\tif err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {\n\t\tpanic(err)\n\t}\n\tretconv.CleanUp()\n\treturn *dst\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/fatih/color\"\n\tout \"github.com/plouc/go-gitlab-client/cli/output\"\n\t\"github.com/plouc/go-gitlab-client/gitlab\"\n\t\"github.com/spf13/cobra\"\n)\n\nfunc init() {\n\tlistCmd.AddCommand(listSshKeysCmd)\n}\n\n\n\nvar listSshKeysCmd = &cobra.Command{\n\tUse: \"ssh-keys\",\n\tAliases: []string{\"sk\"},\n\tShort: \"List current user ssh keys\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tfetchSshKeys()\n\t},\n}\n\nfunc fetchSshKeys() ", "output": "{\n\tcolor.Yellow(\"Fetching current user ssh keys…\")\n\n\to := &gitlab.PaginationOptions{}\n\to.Page = page\n\to.PerPage = perPage\n\n\tloader.Start()\n\tcollection, meta, err := client.CurrentUserSshKeys(o)\n\tloader.Stop()\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\n\tif len(collection.Items) == 0 {\n\t\tcolor.Red(\"No ssh key found\")\n\t} else {\n\t\tout.SshKeys(output, outputFormat, collection)\n\t}\n\n\tprintMeta(meta, true)\n\n\thandlePaginatedResult(meta, fetchSshKeys)\n}"} {"input": "package ha\n\nimport (\n\tlog \"github.com/golang/glog\"\n\t\"k8s.io/kubernetes/contrib/mesos/pkg/election\"\n)\n\ntype roleType int\n\nconst (\n\tfollowerRole roleType = iota\n\tmasterRole\n\tretiredRole\n)\n\ntype candidateService struct {\n\tsched *SchedulerProcess\n\tnewDriver DriverFactory\n\trole roleType\n\tvalid ValidationFunc\n}\n\ntype ValidationFunc func(desiredUid, currentUid string)\n\nfunc NewCandidate(s *SchedulerProcess, f DriverFactory, v ValidationFunc) election.Service {\n\treturn &candidateService{\n\t\tsched: s,\n\t\tnewDriver: f,\n\t\trole: followerRole,\n\t\tvalid: v,\n\t}\n}\n\nfunc (self *candidateService) Validate(desired, current election.Master) {\n\tif self.valid != nil {\n\t\tself.valid(string(desired), string(current))\n\t}\n}\n\n\n\nfunc (self *candidateService) Stop() {\n\tif self.role == masterRole {\n\t\tlog.Info(\"retiring from master\")\n\t\tself.role = retiredRole\n\t\tclose(self.sched.failover)\n\t\tself.sched.End()\n\t}\n}\n\nfunc (self *candidateService) Start() ", "output": "{\n\tif self.role == followerRole {\n\t\tlog.Info(\"elected as master\")\n\t\tself.role = masterRole\n\t\tself.sched.Elect(self.newDriver)\n\t}\n}"} {"input": "package srpc\n\nimport (\n\t\"crypto/tls\"\n\n\t\"github.com/Symantec/Dominator/lib/connpool\"\n)\n\nfunc newClientResource(network, address string) *ClientResource {\n\tclientResource := &ClientResource{\n\t\tnetwork: network,\n\t\taddress: address,\n\t}\n\tclientResource.privateClientResource.clientResource = clientResource\n\trp := connpool.GetResourcePool()\n\tclientResource.resource = rp.Create(&clientResource.privateClientResource)\n\treturn clientResource\n}\n\nfunc (cr *ClientResource) getHTTP(tlsConfig *tls.Config,\n\tcancelChannel <-chan struct{}, dialer connpool.Dialer) (*Client, error) {\n\tcr.privateClientResource.tlsConfig = tlsConfig\n\tcr.privateClientResource.dialer = dialer\n\tif err := cr.resource.Get(cancelChannel); err != nil {\n\t\treturn nil, err\n\t}\n\tcr.inUse = true\n\tclientMetricsMutex.Lock()\n\tnumInUseClientConnections++\n\tclientMetricsMutex.Unlock()\n\treturn cr.client, nil\n}\n\nfunc (client *Client) put() {\n\tclient.resource.resource.Put()\n\tif client.resource.inUse {\n\t\tclientMetricsMutex.Lock()\n\t\tnumInUseClientConnections--\n\t\tclientMetricsMutex.Unlock()\n\t\tclient.resource.inUse = false\n\t}\n}\n\n\n\nfunc (pcr *privateClientResource) Release() error {\n\tcr := pcr.clientResource\n\terr := cr.client.conn.Close()\n\tcr.client = nil\n\treturn err\n}\n\nfunc (pcr *privateClientResource) Allocate() error ", "output": "{\n\tcr := pcr.clientResource\n\tclient, err := dialHTTP(cr.network, cr.address, pcr.tlsConfig, pcr.dialer)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcr.client = client\n\tclient.resource = cr\n\treturn nil\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/mexisme/go-config/settings\"\n)\n\n\nfunc AddConfigItems(configKeys []string) {\n\tsettings.AddConfigItems(configKeys)\n}\n\n\nfunc AddConfigItemsWithPFlags(configKeys []string) error {\n\treturn settings.AddConfigItemsWithPFlags(configKeys)\n}\n\n\nfunc ApplyWith(key string, f func(interface{})) {\n\tsettings.ApplyWith(key, f)\n}\n\n\nfunc Get(key string) interface{} {\n\treturn settings.Get(key)\n}\n\n\nfunc GetBool(key string) bool {\n\treturn settings.GetBool(key)\n}\n\n\nfunc GetFloat64(key string) float64 {\n\treturn settings.GetFloat64(key)\n}\n\n\nfunc GetInt(key string) int {\n\treturn settings.GetInt(key)\n}\n\n\nfunc GetString(key string) string {\n\treturn settings.GetString(key)\n}\n\n\n\n\n\nfunc GetStringMapString(key string) map[string]string {\n\treturn settings.GetStringMapString(key)\n}\n\n\nfunc GetStringSlice(key string) []string {\n\treturn settings.GetStringSlice(key)\n}\n\n\nfunc GetTime(key string) time.Time {\n\treturn settings.GetTime(key)\n}\n\n\nfunc GetDuration(key string) time.Duration {\n\treturn settings.GetDuration(key)\n}\n\n\nfunc IsSet(key string) bool {\n\treturn settings.IsSet(key)\n}\n\n\nfunc AllSettings() map[string]interface{} {\n\treturn settings.AllSettings()\n}\n\nfunc GetStringMap(key string) map[string]interface{} ", "output": "{\n\treturn settings.GetStringMap(key)\n}"} {"input": "package state\n\nimport (\n\t\"k8s.io/kubernetes/pkg/kubelet/cm/cpuset\"\n)\n\n\ntype ContainerCPUAssignments map[string]cpuset.CPUSet\n\n\n\n\n\ntype Reader interface {\n\tGetCPUSet(containerID string) (cpuset.CPUSet, bool)\n\tGetDefaultCPUSet() cpuset.CPUSet\n\tGetCPUSetOrDefault(containerID string) cpuset.CPUSet\n\tGetCPUAssignments() ContainerCPUAssignments\n}\n\ntype writer interface {\n\tSetCPUSet(containerID string, cpuset cpuset.CPUSet)\n\tSetDefaultCPUSet(cpuset cpuset.CPUSet)\n\tSetCPUAssignments(ContainerCPUAssignments)\n\tDelete(containerID string)\n\tClearState()\n}\n\n\ntype State interface {\n\tReader\n\twriter\n}\n\nfunc (as ContainerCPUAssignments) Clone() ContainerCPUAssignments ", "output": "{\n\tret := make(ContainerCPUAssignments)\n\tfor key, val := range as {\n\t\tret[key] = val\n\t}\n\treturn ret\n}"} {"input": "package ahsay\n\nimport \"encoding/xml\"\n\n\ntype UserType int\n\n\n\nconst (\n\tPaid UserType = iota + 1\n\tTrial\n)\n\nfunc (t UserType) String() string {\n\tswitch t {\n\tcase Paid:\n\t\treturn \"Paid\"\n\tcase Trial:\n\t\treturn \"Trial\"\n\tdefault:\n\t\treturn \"User type not set\"\n\t}\n}\n\n\n\n\nfunc (t *UserType) UnmarshalXMLAttr(attr xml.Attr) error ", "output": "{\n\tif attr.Value == \"PAID\" {\n\t\t*t = Paid\n\t} else if attr.Value == \"TRIAL\" {\n\t\t*t = Trial\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"os\"\n \"runtime\"\n \"strconv\"\n \"sync\"\n)\n\ntype Token int\n\ntype T struct {\n next *T\n label int\n value int\n mux sync.Mutex\n}\n\n\n\nfunc (w *T) run() {\n for {\n w.mux.Lock()\n w.next.put(w.value - 1)\n runtime.Gosched()\n }\n}\n\nfunc (w *T) Start(label int, next *T) {\n w.label = label\n w.next = next\n w.mux.Lock()\n go w.run()\n}\n\nconst NThreads = 503\n\nvar res = make(chan int)\n\nfunc main() {\n n := 1000\n if len(os.Args) > 1 {\n n, _ = strconv.Atoi(os.Args[1])\n }\n\n var channels [NThreads]T\n for i := range channels {\n channels[i].Start(i+1, &channels[(i+1)%NThreads])\n }\n\n channels[0].put(n)\n fmt.Println(<-res)\n}\n\nfunc (w *T) put(v int) ", "output": "{\n w.value = v\n if v == 0 {\n res <- w.label\n } else {\n w.mux.Unlock()\n }\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc checkErr(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\n\nfunc addSound(p string, info os.FileInfo, err error) error {\n\tcheckErr(err)\n\tif info.IsDir() == false {\n\t\tfor _, ext := range conf.AllowedFormats {\n\t\t\tif strings.HasSuffix(p, \".\"+ext) {\n\t\t\t\tname := strings.TrimPrefix(p, conf.Sounds+\"/\")\n\t\t\t\tsnippets = append(snippets, sound{sanitizeName(name, ext), name})\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc sanitizeName(filename string, ext string) string ", "output": "{\n\tfilename = strings.TrimSuffix(filename, \".\"+ext)\n\n\tfor _, s := range []string{\"_\", \"-\", \".\"} {\n\t\tfilename = strings.Replace(filename, s, \" \", -1)\n\t}\n\n\treturn strings.Title(filename)\n}"} {"input": "package iso20022\n\n\ntype PointOfInteractionComponent6 struct {\n\n\tType *POIComponentType4Code `xml:\"Tp\"`\n\n\tIdentification *PointOfInteractionComponentIdentification1 `xml:\"Id\"`\n\n\tStatus *PointOfInteractionComponentStatus3 `xml:\"Sts,omitempty\"`\n\n\tStandardCompliance []*GenericIdentification48 `xml:\"StdCmplc,omitempty\"`\n\n\tCharacteristics *PointOfInteractionComponentCharacteristics2 `xml:\"Chrtcs,omitempty\"`\n\n\tAssessment []*PointOfInteractionComponentAssessment1 `xml:\"Assmnt,omitempty\"`\n}\n\nfunc (p *PointOfInteractionComponent6) SetType(value string) {\n\tp.Type = (*POIComponentType4Code)(&value)\n}\n\nfunc (p *PointOfInteractionComponent6) AddIdentification() *PointOfInteractionComponentIdentification1 {\n\tp.Identification = new(PointOfInteractionComponentIdentification1)\n\treturn p.Identification\n}\n\nfunc (p *PointOfInteractionComponent6) AddStatus() *PointOfInteractionComponentStatus3 {\n\tp.Status = new(PointOfInteractionComponentStatus3)\n\treturn p.Status\n}\n\n\n\nfunc (p *PointOfInteractionComponent6) AddCharacteristics() *PointOfInteractionComponentCharacteristics2 {\n\tp.Characteristics = new(PointOfInteractionComponentCharacteristics2)\n\treturn p.Characteristics\n}\n\nfunc (p *PointOfInteractionComponent6) AddAssessment() *PointOfInteractionComponentAssessment1 {\n\tnewValue := new(PointOfInteractionComponentAssessment1)\n\tp.Assessment = append(p.Assessment, newValue)\n\treturn newValue\n}\n\nfunc (p *PointOfInteractionComponent6) AddStandardCompliance() *GenericIdentification48 ", "output": "{\n\tnewValue := new(GenericIdentification48)\n\tp.StandardCompliance = append(p.StandardCompliance, newValue)\n\treturn newValue\n}"} {"input": "package collector\n\nimport (\n\t\"fullerite/metric\"\n\t\"math/rand\"\n)\n\n\ntype Test struct {\n\tinterval int\n\tchannel chan metric.Metric\n}\n\n\n\n\n\nfunc (t Test) Collect() {\n\tmetric := metric.New(\"TestMetric\")\n\tmetric.Value = rand.Float64()\n\tmetric.AddDimension(\"testing\", \"yes\")\n\tt.Channel() <- metric\n}\n\n\nfunc (t Test) Name() string {\n\treturn \"Test\"\n}\n\n\nfunc (t Test) Interval() int {\n\treturn t.interval\n}\n\n\n\nfunc (t Test) Channel() chan metric.Metric {\n\treturn t.channel\n}\n\n\nfunc (t Test) String() string {\n\treturn t.Name() + \"Collector\"\n}\n\n\nfunc (t *Test) SetInterval(interval int) {\n\tt.interval = interval\n}\n\nfunc NewTest() *Test ", "output": "{\n\tt := new(Test)\n\tt.channel = make(chan metric.Metric)\n\treturn t\n}"} {"input": "package command\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\ntype VersionCommand struct {\n\tMeta\n\n\tRevision string\n\tVersion string\n\tVersionPrerelease string\n\tCheckFunc VersionCheckFunc\n}\n\n\n\ntype VersionCheckFunc func() (VersionCheckInfo, error)\n\n\n\n\ntype VersionCheckInfo struct {\n\tOutdated bool\n\tLatest string\n\tAlerts []string\n}\n\nfunc (c *VersionCommand) Help() string {\n\treturn \"\"\n}\n\nfunc (c *VersionCommand) Run(args []string) int {\n\tvar versionString bytes.Buffer\n\n\tfmt.Fprintf(&versionString, \"Otto v%s\", c.Version)\n\tif c.VersionPrerelease != \"\" {\n\t\tfmt.Fprintf(&versionString, \"-%s\", c.VersionPrerelease)\n\n\t\tif c.Revision != \"\" {\n\t\t\tfmt.Fprintf(&versionString, \" (%s)\", c.Revision)\n\t\t}\n\t}\n\n\tc.Ui.Output(versionString.String())\n\n\tif c.CheckFunc != nil {\n\t\tc.Ui.Output(\"\")\n\n\t\tinfo, err := c.CheckFunc()\n\t\tif err != nil {\n\t\t\tc.Ui.Error(fmt.Sprintf(\n\t\t\t\t\"Error checking latest version: %s\", err))\n\t\t}\n\t\tif info.Outdated {\n\t\t\tc.Ui.Output(fmt.Sprintf(\n\t\t\t\t\"Your version of Otto is out of date! The latest version\\n\"+\n\t\t\t\t\t\"is %s. You can update by downloading from www.ottoproject.io\",\n\t\t\t\tinfo.Latest))\n\t\t}\n\t}\n\n\treturn 0\n}\n\n\n\nfunc (c *VersionCommand) Synopsis() string ", "output": "{\n\treturn \"Prints the Otto version\"\n}"} {"input": "package ufile\n\nimport (\n\t\"github.com/ucloud/ucloud-sdk-go/ucloud/request\"\n\t\"github.com/ucloud/ucloud-sdk-go/ucloud/response\"\n)\n\n\ntype DescribeUFileTokenRequest struct {\n\trequest.CommonBase\n\n\n\n\tDisplay *int `required:\"false\"`\n\n\tTokenId *string `required:\"false\"`\n}\n\n\ntype DescribeUFileTokenResponse struct {\n\tresponse.CommonBase\n\n\tAction string\n\n\tDataSet []UFileTokenSet\n\n\tRetCode int\n}\n\n\nfunc (c *UFileClient) NewDescribeUFileTokenRequest() *DescribeUFileTokenRequest {\n\treq := &DescribeUFileTokenRequest{}\n\n\tc.Client.SetupRequest(req)\n\n\treq.SetRetryable(true)\n\treturn req\n}\n\n\n\n\nfunc (c *UFileClient) DescribeUFileToken(req *DescribeUFileTokenRequest) (*DescribeUFileTokenResponse, error) ", "output": "{\n\tvar err error\n\tvar res DescribeUFileTokenResponse\n\n\treqCopier := *req\n\n\terr = c.Client.InvokeAction(\"DescribeUFileToken\", &reqCopier, &res)\n\tif err != nil {\n\t\treturn &res, err\n\t}\n\n\treturn &res, nil\n}"} {"input": "package file\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\ntype Reader interface {\n\tio.Reader\n\tio.ReaderAt\n\tio.Seeker\n}\n\ntype Writer interface {\n\tio.Writer\n\tio.Seeker\n\tTruncate(size int64) error\n\tSync() error\n}\n\ntype ReadCloser interface {\n\tReader\n\tio.Closer\n}\n\ntype WriteCloser interface {\n\tWriter\n\tio.Closer\n}\n\ntype File interface {\n\tio.Reader\n\tio.Writer\n\tio.Seeker\n\tio.Closer\n\tio.ReaderAt\n\tTruncate(size int64) error\n\tSync() error\n}\n\n\ntype FileSystem interface {\n\tOpen(name string, flag int) (File, error)\n\n\tLock(name string) (io.Closer, error)\n\n\tExists(name string) bool\n\n\tMkdirAll(path string) error\n\n\tList(dir string) ([]string, error)\n\n\tRemove(filename string) error\n\n\tRename(oldpath, newpath string) error\n}\n\ntype osFileSystem struct{}\n\n\n\nfunc (osFileSystem) MkdirAll(path string) error {\n\treturn os.MkdirAll(path, 0740)\n}\n\nfunc (osFileSystem) Exists(name string) bool {\n\t_, err := os.Stat(name)\n\treturn err == nil\n}\n\nfunc (osFileSystem) List(dir string) ([]string, error) {\n\tf, err := os.Open(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.Readdirnames(-1)\n}\n\nfunc (osFileSystem) Remove(name string) error {\n\treturn os.Remove(name)\n}\n\nfunc (osFileSystem) Rename(oldpath, newpath string) error {\n\treturn os.Rename(oldpath, newpath)\n}\n\nvar DefaultFileSystem FileSystem = osFileSystem{}\n\nfunc (osFileSystem) Open(name string, flag int) (File, error) ", "output": "{\n\treturn os.OpenFile(name, flag, 0666)\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\n\n\nfunc healthcheck(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tfmt.Fprint(w, \"WORKING\")\n}"} {"input": "package grubenv\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"github.com/snapcore/snapd/strutil\"\n)\n\n\ntype Env struct {\n\tenv map[string]string\n\tordering []string\n\n\tpath string\n}\n\nfunc NewEnv(path string) *Env {\n\treturn &Env{\n\t\tenv: make(map[string]string),\n\t\tpath: path,\n\t}\n}\n\nfunc (g *Env) Get(name string) string {\n\treturn g.env[name]\n}\n\nfunc (g *Env) Set(key, value string) {\n\tif !strutil.ListContains(g.ordering, key) {\n\t\tg.ordering = append(g.ordering, key)\n\t}\n\n\tg.env[key] = value\n}\n\n\n\nfunc (g *Env) Save() error {\n\tw := bytes.NewBuffer(nil)\n\tw.Grow(1024)\n\n\tfmt.Fprintf(w, \"# GRUB Environment Block\\n\")\n\tfor _, k := range g.ordering {\n\t\tif _, err := fmt.Fprintf(w, \"%s=%s\\n\", k, g.env[k]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif w.Len() > 1024 {\n\t\treturn fmt.Errorf(\"cannot write grubenv %q: bigger than 1024 bytes (%d)\", g.path, w.Len())\n\t}\n\tcontent := w.Bytes()[:w.Cap()]\n\tfor i := w.Len(); i < len(content); i++ {\n\t\tcontent[i] = '#'\n\t}\n\n\tf, err := os.Create(g.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err := f.Write(content); err != nil {\n\t\treturn err\n\t}\n\tif err := f.Sync(); err != nil {\n\t\treturn err\n\t}\n\n\treturn f.Close()\n}\n\nfunc (g *Env) Load() error ", "output": "{\n\tbuf, err := ioutil.ReadFile(g.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(buf) != 1024 {\n\t\treturn fmt.Errorf(\"grubenv %q must be exactly 1024 byte, got %d\", g.path, len(buf))\n\t}\n\tif !bytes.HasPrefix(buf, []byte(\"# GRUB Environment Block\\n\")) {\n\t\treturn fmt.Errorf(\"cannot find grubenv header in %q\", g.path)\n\t}\n\trawEnv := bytes.Split(buf, []byte(\"\\n\"))\n\tfor _, env := range rawEnv[1:] {\n\t\tl := bytes.SplitN(env, []byte(\"=\"), 2)\n\t\tif len(l) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tk := string(l[0])\n\t\tv := string(l[1])\n\t\tg.env[k] = v\n\t\tg.ordering = append(g.ordering, k)\n\t}\n\n\treturn nil\n}"} {"input": "package kubernetes\n\nimport (\n\t\"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\n\n\nfunc expandReplicationControllerSpec(rc []interface{}) (v1.ReplicationControllerSpec, error) {\n\tobj := v1.ReplicationControllerSpec{}\n\tif len(rc) == 0 || rc[0] == nil {\n\t\treturn obj, nil\n\t}\n\tin := rc[0].(map[string]interface{})\n\tobj.MinReadySeconds = int32(in[\"min_ready_seconds\"].(int))\n\tobj.Replicas = ptrToInt32(int32(in[\"replicas\"].(int)))\n\tobj.Selector = expandStringMap(in[\"selector\"].(map[string]interface{}))\n\tpodSpec, err := expandPodSpec(in[\"template\"].([]interface{}))\n\tif err != nil {\n\t\treturn obj, err\n\t}\n\tobj.Template = &v1.PodTemplateSpec{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tLabels: obj.Selector,\n\t\t},\n\t\tSpec: podSpec,\n\t}\n\n\treturn obj, nil\n}\n\nfunc flattenReplicationControllerSpec(in v1.ReplicationControllerSpec) ([]interface{}, error) ", "output": "{\n\tatt := make(map[string]interface{})\n\tatt[\"min_ready_seconds\"] = in.MinReadySeconds\n\n\tif in.Replicas != nil {\n\t\tatt[\"replicas\"] = *in.Replicas\n\t}\n\n\tatt[\"selector\"] = in.Selector\n\tpodSpec, err := flattenPodSpec(in.Template.Spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tatt[\"template\"] = podSpec\n\n\treturn []interface{}{att}, nil\n}"} {"input": "package proto\n\n\n\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/youtube/vitess/go/bson\"\n\t\"github.com/youtube/vitess/go/bytes2\"\n)\n\n\n\n\n\nfunc (boundQuery *BoundQuery) UnmarshalBson(buf *bytes.Buffer, kind byte) {\n\tswitch kind {\n\tcase bson.EOO, bson.Object:\n\tcase bson.Null:\n\t\treturn\n\tdefault:\n\t\tpanic(bson.NewBsonError(\"unexpected kind %v for BoundQuery\", kind))\n\t}\n\tbson.Next(buf, 4)\n\n\tfor kind := bson.NextByte(buf); kind != bson.EOO; kind = bson.NextByte(buf) {\n\t\tswitch bson.ReadCString(buf) {\n\t\tcase \"Sql\":\n\t\t\tboundQuery.Sql = bson.DecodeString(buf, kind)\n\t\tcase \"BindVariables\":\n\t\t\tif kind != bson.Null {\n\t\t\t\tif kind != bson.Object {\n\t\t\t\t\tpanic(bson.NewBsonError(\"unexpected kind %v for boundQuery.BindVariables\", kind))\n\t\t\t\t}\n\t\t\t\tbson.Next(buf, 4)\n\t\t\t\tboundQuery.BindVariables = make(map[string]interface{})\n\t\t\t\tfor kind := bson.NextByte(buf); kind != bson.EOO; kind = bson.NextByte(buf) {\n\t\t\t\t\t_k := bson.ReadCString(buf)\n\t\t\t\t\tvar _v1 interface{}\n\t\t\t\t\t_v1 = bson.DecodeInterface(buf, kind)\n\t\t\t\t\tboundQuery.BindVariables[_k] = _v1\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\tbson.Skip(buf, kind)\n\t\t}\n\t}\n}\n\nfunc (boundQuery *BoundQuery) MarshalBson(buf *bytes2.ChunkedWriter, key string) ", "output": "{\n\tbson.EncodeOptionalPrefix(buf, bson.Object, key)\n\tlenWriter := bson.NewLenWriter(buf)\n\n\tbson.EncodeString(buf, \"Sql\", boundQuery.Sql)\n\t{\n\t\tbson.EncodePrefix(buf, bson.Object, \"BindVariables\")\n\t\tlenWriter := bson.NewLenWriter(buf)\n\t\tfor _k, _v1 := range boundQuery.BindVariables {\n\t\t\tbson.EncodeInterface(buf, _k, _v1)\n\t\t}\n\t\tlenWriter.Close()\n\t}\n\n\tlenWriter.Close()\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/docker/infrakit/pkg/types\"\n)\n\ntype errBadDependency types.Dependency\n\nfunc (e errBadDependency) Error() string {\n\treturn fmt.Sprintf(\"unresolved dependency: class=%s name=%s\", types.Dependency(e).Class, types.Dependency(e).Name)\n}\n\ntype errCircularDependency []*types.Spec\n\n\n\ntype errNotFound struct {\n\tclass string\n\tname string\n}\n\nfunc (e errNotFound) Error() string {\n\treturn fmt.Sprintf(\"not found %s/%s\", e.class, e.name)\n}\n\nfunc (e errCircularDependency) Error() string ", "output": "{\n\tdeps := []*types.Spec(e)\n\tlist := fmt.Sprintf(\"%s/%s\", deps[0].Class, deps[0].Metadata.Name)\n\tfor _, dep := range deps[1:] {\n\t\tlist = list + fmt.Sprintf(\"=> %s/%s\", dep.Class, dep.Metadata.Name)\n\t}\n\treturn fmt.Sprintf(\"circular dependency: %s\", list)\n}"} {"input": "package pathdb\n\nimport (\n\t\"github.com/scionproto/scion/go/lib/common\"\n\t\"github.com/scionproto/scion/go/lib/ctrl/seg\"\n\t\"github.com/scionproto/scion/go/lib/pathdb/conn\"\n\t\"github.com/scionproto/scion/go/lib/pathdb/query\"\n\t\"github.com/scionproto/scion/go/lib/pathdb/sqlite\"\n)\n\ntype DB struct {\n\tconn conn.Conn\n}\n\n\n\nfunc New(path string, backend string) (*DB, error) {\n\tdb := &DB{}\n\tvar err error\n\tswitch backend {\n\tcase \"sqlite\":\n\t\tdb.conn, err = sqlite.New(path)\n\tdefault:\n\t\treturn nil, common.NewBasicError(\"Unknown backend\", nil, \"backend\", backend)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn db, nil\n}\n\n\n\nfunc (db *DB) Insert(pseg *seg.PathSegment, segTypes []seg.Type) (int, error) {\n\treturn db.conn.Insert(pseg, segTypes)\n}\n\n\n\nfunc (db *DB) InsertWithHPCfgIDs(pseg *seg.PathSegment,\n\tsegTypes []seg.Type, hpCfgIDs []*query.HPCfgID) (int, error) {\n\treturn db.conn.InsertWithHPCfgIDs(pseg, segTypes, hpCfgIDs)\n}\n\n\n\nfunc (db *DB) Delete(segID common.RawBytes) (int, error) {\n\treturn db.conn.Delete(segID)\n}\n\n\n\n\n\n\nfunc (db *DB) Get(params *query.Params) ([]*query.Result, error) {\n\treturn db.conn.Get(params)\n}\n\nfunc (db *DB) DeleteWithIntf(intf query.IntfSpec) (int, error) ", "output": "{\n\treturn db.conn.DeleteWithIntf(intf)\n}"} {"input": "package framework\n\nimport \"github.com/onsi/gomega\"\n\n\nfunc ExpectEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.Equal(extra), explain...)\n}\n\n\nfunc ExpectNotEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).NotTo(gomega.Equal(extra), explain...)\n}\n\n\nfunc ExpectError(err error, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, err).To(gomega.HaveOccurred(), explain...)\n}\n\n\nfunc ExpectNoError(err error, explain ...interface{}) {\n\tExpectNoErrorWithOffset(1, err, explain...)\n}\n\n\n\nfunc ExpectNoErrorWithOffset(offset int, err error, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1+offset, err).NotTo(gomega.HaveOccurred(), explain...)\n}\n\n\nfunc ExpectConsistOf(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.ConsistOf(extra), explain...)\n}\n\n\nfunc ExpectHaveKey(actual interface{}, key interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.HaveKey(key), explain...)\n}\n\n\n\n\nfunc ExpectEmpty(actual interface{}, explain ...interface{}) ", "output": "{\n\tgomega.ExpectWithOffset(1, actual).To(gomega.BeEmpty(), explain...)\n}"} {"input": "package errors\n\nimport (\n\t. \"code.cloudfoundry.org/cli/cf/i18n\"\n)\n\ntype NotAuthorizedError struct {\n}\n\n\n\nfunc (err *NotAuthorizedError) Error() string {\n\treturn T(\"Server error, status code: 403, error code: 10003, message: You are not authorized to perform the requested action\")\n}\n\nfunc NewNotAuthorizedError() error ", "output": "{\n\treturn &NotAuthorizedError{}\n}"} {"input": "package v1\n\nimport (\n\tfmt \"fmt\"\n\tapi \"k8s.io/client-go/pkg/api\"\n\tunversioned \"k8s.io/client-go/pkg/api/unversioned\"\n\tregistered \"k8s.io/client-go/pkg/apimachinery/registered\"\n\tserializer \"k8s.io/client-go/pkg/runtime/serializer\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype BatchV1Interface interface {\n\tRESTClient() rest.Interface\n\tJobsGetter\n}\n\n\ntype BatchV1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *BatchV1Client) Jobs(namespace string) JobInterface {\n\treturn newJobs(c, namespace)\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *BatchV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *BatchV1Client {\n\treturn &BatchV1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv, err := unversioned.ParseGroupVersion(\"batch/v1\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !registered.IsEnabledVersion(gv) {\n\t\treturn fmt.Errorf(\"batch/v1 is not enabled\")\n\t}\n\tconfig.APIPath = \"/apis\"\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\tcopyGroupVersion := gv\n\tconfig.GroupVersion = ©GroupVersion\n\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: api.Codecs}\n\n\treturn nil\n}\n\n\n\nfunc (c *BatchV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfig(c *rest.Config) (*BatchV1Client, error) ", "output": "{\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BatchV1Client{client}, nil\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/arschles/assert\"\n)\n\n\n\nfunc TestCreateAndRenderTpl(t *testing.T) {\n\ttd, err := testDataDir()\n\tassert.NoErr(t, err)\n\ttemplateNames := []string{\n\t\t\"sprig.tpl\",\n\t\t\"pwd.tpl\",\n\t}\n\tenvs := collectEnv()\n\tfor i, tplName := range templateNames {\n\t\tfName := filepath.Join(td, tplName)\n\t\ttpl, err := createTpl(filepath.Base(fName), fName)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Error creating template %d (%s)\", i, err)\n\t\t\tcontinue\n\t\t}\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := renderTpl(tpl, buf, envs); err != nil {\n\t\t\tt.Errorf(\"Error rendering template %d (%s)\", i, err)\n\t\t}\n\t}\n}\n\nfunc testDataDir() (string, error) ", "output": "{\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(wd, \"testdata\"), nil\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/clients/generated/client/clientset/versioned/typed/containeranalysis/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeContaineranalysisV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeContaineranalysisV1beta1) ContainerAnalysisNotes(namespace string) v1beta1.ContainerAnalysisNoteInterface {\n\treturn &FakeContainerAnalysisNotes{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeContaineranalysisV1beta1) RESTClient() rest.Interface ", "output": "{\n\tvar ret *rest.RESTClient\n\treturn ret\n}"} {"input": "package test\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/pilosa/pilosa\"\n)\n\n\nfunc NewCluster(n int) *pilosa.Cluster {\n\tc := pilosa.NewCluster()\n\tc.ReplicaN = 1\n\tc.Hasher = NewModHasher()\n\n\tfor i := 0; i < n; i++ {\n\t\tc.Nodes = append(c.Nodes, &pilosa.Node{\n\t\t\tScheme: \"http\",\n\t\t\tHost: fmt.Sprintf(\"host%d\", i),\n\t\t})\n\t}\n\n\treturn c\n}\n\n\ntype ModHasher struct{}\n\n\n\n\nfunc (*ModHasher) Hash(key uint64, n int) int { return int(key) % n }\n\n\ntype ConstHasher struct {\n\ti int\n}\n\n\nfunc NewConstHasher(i int) *ConstHasher { return &ConstHasher{i: i} }\n\nfunc (h *ConstHasher) Hash(key uint64, n int) int { return h.i }\n\nfunc NewModHasher() *ModHasher ", "output": "{ return &ModHasher{} }"} {"input": "package jsonutil\n\nimport (\n\t\"github.com/buger/jsonparser\"\n\t\"strconv\"\n)\n\n\n\nfunc MustGetString(data []byte, keys ...string) string {\n\ts, err := GetString(data, keys...)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s\n}\n\nfunc GetFloat(data []byte, keys ...string) (float64, error) {\n\treturn jsonparser.GetFloat(data, keys...)\n}\n\nfunc MustGetFloat(data []byte, keys ...string) float64 {\n\tf, err := GetFloat(data, keys...)\n\tif err != nil {\n\t\treturn 0.0\n\t}\n\treturn f\n}\n\nfunc GetInt(data []byte, keys ...string) (int64, error) {\n\treturn jsonparser.GetInt(data, keys...)\n}\n\nfunc MustGetInt(data []byte, keys ...string) int64 {\n\ti, err := GetInt(data, keys...)\n\tif err != nil {\n\t\tif s := MustGetString(data, keys...); len(s) == 0 {\n\t\t\treturn 0\n\t\t} else if i, err = strconv.ParseInt(s, 10, 64); err != nil {\n\t\t\treturn 0\n\t\t}\n\t}\n\treturn i\n}\n\nfunc GetBoolean(data []byte, keys ...string) (bool, error) {\n\treturn jsonparser.GetBoolean(data, keys...)\n}\n\nfunc MustGetBoolean(data []byte, keys ...string) bool {\n\tb, err := GetBoolean(data, keys...)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn b\n}\n\nfunc GetString(data []byte, keys ...string) (string, error) ", "output": "{\n\treturn jsonparser.GetString(data, keys...)\n}"} {"input": "package persistence\n\nimport (\n\t\"strings\"\n\n\t. \"github.com/Masterminds/squirrel\"\n\t\"github.com/navidrome/navidrome/conf\"\n\t\"github.com/navidrome/navidrome/utils\"\n)\n\nfunc getFullText(text ...string) string {\n\tfullText := utils.SanitizeStrings(text...)\n\treturn \" \" + fullText\n}\n\nfunc (r sqlRepository) doSearch(q string, offset, size int, results interface{}, orderBys ...string) error {\n\tq = strings.TrimSpace(q)\n\tq = strings.TrimSuffix(q, \"*\")\n\tif len(q) < 2 {\n\t\treturn nil\n\t}\n\n\tsq := r.newSelectWithAnnotation(r.tableName + \".id\").Columns(\"*\")\n\tsq = sq.Limit(uint64(size)).Offset(uint64(offset))\n\tif len(orderBys) > 0 {\n\t\tsq = sq.OrderBy(orderBys...)\n\t}\n\tsq = sq.Where(fullTextExpr(q))\n\terr := r.queryAll(sq, results)\n\treturn err\n}\n\n\n\nfunc fullTextExpr(value string) Sqlizer ", "output": "{\n\tvar sep string\n\tif !conf.Server.SearchFullString {\n\t\tsep = \" \"\n\t}\n\tq := utils.SanitizeStrings(value)\n\tparts := strings.Split(q, \" \")\n\tfilters := And{}\n\tfor _, part := range parts {\n\t\tfilters = append(filters, Like{\"full_text\": \"%\" + sep + part + \"%\"})\n\t}\n\treturn filters\n}"} {"input": "package tlv\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\ntype ByteTLV struct {\n\tT uint64\n\tV []byte\n}\n\nfunc readByteTLV(r io.Reader) (ByteTLV, error) {\n\tt, _, err := ReadNumber(r)\n\tif err != nil {\n\t\treturn ByteTLV{}, err\n\t}\n\n\tlength, _, err := ReadNumber(r)\n\tif err != nil {\n\t\treturn ByteTLV{}, err\n\t}\n\n\tvalue := make([]byte, length)\n\tn, err := r.Read(value)\n\tif err != nil {\n\t\treturn ByteTLV{}, err\n\t}\n\n\tif uint64(n) < length {\n\t\treturn ByteTLV{}, io.ErrUnexpectedEOF\n\t}\n\n\treturn ByteTLV{T: t, V: value[0:n]}, nil\n}\n\n\n\nfunc (t ByteTLV) WriteTo(w io.Writer) (n int64, err error) {\n\tn, err = WriteNumber(w, t.T)\n\tif err != nil {\n\t\treturn\n\t}\n\n\twritten, err := WriteNumber(w, uint64(len(t.V)))\n\tn += written\n\tif err != nil {\n\t\treturn\n\t}\n\n\twritten2, err := w.Write(t.V)\n\tn += int64(written2)\n\treturn\n}\n\nfunc (t ByteTLV) MarshalBinary() ([]byte, error) {\n\tbuf := &bytes.Buffer{}\n\t_, err := t.WriteTo(buf)\n\treturn buf.Bytes(), err\n}\n\nfunc (t ByteTLV) Type() uint64 ", "output": "{\n\treturn t.T\n}"} {"input": "package codns\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"strings\"\n)\n\ntype Configuration struct {\n\tFilters []ConfigFilter\n}\n\ntype ConfigFilter struct {\n\tPattern string\n\tAddresses []string\n}\n\nconst default_config = `\n{\n \"filters\": [\n {\n \"pattern\": \"consul.\",\n \"addresses\": [ \"127.0.0.1:8600\" ]\n },\n {\n \"pattern\": \".\",\n \"addresses\": [ \"8.8.8.8\", \"8.8.4.4\" ]\n }\n ]\n}\n`\n\n\n\n\nfunc ReadConfig(filename string) Configuration ", "output": "{\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n file = []byte(default_config)\n\t}\n\n\tvar jsonConfig Configuration\n\tjson.Unmarshal(file, &jsonConfig)\n\n\tif len(jsonConfig.Filters) == 0 {\n\t\tlog.Fatalf(\"Configuration contains no 'filters' section\")\n\t}\n\n\tfor _, filter := range jsonConfig.Filters {\n\t\tif filter.Pattern == \"\" || len(filter.Addresses) == 0 {\n\t\t\tlog.Fatalf(\"Filter error: missing pattern or empty server list\")\n\t\t}\n\n\t\tfor i, address := range filter.Addresses {\n\t\t\tif !strings.Contains(address, \":\") {\n\t\t\t\tfilter.Addresses[i] = strings.Join([]string{address, \"53\"}, \":\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn jsonConfig\n}"} {"input": "package cluster\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\n\t\"github.com/docker/docker/api/types\"\n\tv3 \"github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3\"\n\t\"github.com/rancher/rancher/pkg/settings\"\n\trketypes \"github.com/rancher/rke/types\"\n)\n\nfunc GetPrivateRepoURL(cluster *v3.Cluster) string {\n\tregistry := GetPrivateRepo(cluster)\n\tif registry == nil {\n\t\treturn \"\"\n\t}\n\treturn registry.URL\n}\n\nfunc GetPrivateRepo(cluster *v3.Cluster) *rketypes.PrivateRegistry {\n\tif cluster != nil && cluster.Spec.RancherKubernetesEngineConfig != nil && len(cluster.Spec.RancherKubernetesEngineConfig.PrivateRegistries) > 0 {\n\t\tconfig := cluster.Spec.RancherKubernetesEngineConfig\n\t\treturn &config.PrivateRegistries[0]\n\t}\n\tif settings.SystemDefaultRegistry.Get() != \"\" {\n\t\treturn &rketypes.PrivateRegistry{\n\t\t\tURL: settings.SystemDefaultRegistry.Get(),\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\nfunc GeneratePrivateRegistryDockerConfig(privateRegistry *rketypes.PrivateRegistry) (string, error) {\n\tif privateRegistry == nil || privateRegistry.User == \"\" || privateRegistry.Password == \"\" {\n\t\treturn \"\", nil\n\t}\n\tauthConfig := types.AuthConfig{\n\t\tUsername: privateRegistry.User,\n\t\tPassword: privateRegistry.Password,\n\t}\n\tencodedJSON, err := json.Marshal(authConfig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.URLEncoding.EncodeToString(encodedJSON), nil\n}\n\nfunc GenerateClusterPrivateRegistryDockerConfig(cluster *v3.Cluster) (string, error) ", "output": "{\n\tif cluster == nil {\n\t\treturn \"\", nil\n\t}\n\treturn GeneratePrivateRegistryDockerConfig(GetPrivateRepo(cluster))\n}"} {"input": "package elements\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"log\"\n)\n\ntype ElementsGroup struct {\n\tChoice []*ElementsGroupChoice\n}\n\nfunc NewElementsGroup() *ElementsGroup {\n\tret := &ElementsGroup{}\n\treturn ret\n}\n\nfunc (m *ElementsGroup) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tif m.Choice != nil {\n\t\tfor _, c := range m.Choice {\n\t\t\tc.MarshalXML(e, xml.StartElement{})\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *ElementsGroup) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\nlElementsGroup:\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch el := tok.(type) {\n\t\tcase xml.StartElement:\n\t\t\tswitch el.Name {\n\t\t\tcase xml.Name{Space: \"http:purl.org/dc/elements/1.1/\", Local: \"any\"}:\n\t\t\t\ttmp := NewElementsGroupChoice()\n\t\t\t\tif err := d.DecodeElement(&tmp.Any, &el); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tm.Choice = append(m.Choice, tmp)\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"skipping unsupported element on ElementsGroup %v\", el.Name)\n\t\t\t\tif err := d.Skip(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\tcase xml.EndElement:\n\t\t\tbreak lElementsGroup\n\t\tcase xml.CharData:\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (m *ElementsGroup) Validate() error {\n\treturn m.ValidateWithPath(\"ElementsGroup\")\n}\n\n\n\n\nfunc (m *ElementsGroup) ValidateWithPath(path string) error ", "output": "{\n\tfor i, v := range m.Choice {\n\t\tif err := v.ValidateWithPath(fmt.Sprintf(\"%s/Choice[%d]\", path, i)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package api\n\nimport (\n\t\"io\"\n\n\t\"github.com/dghubble/sling\"\n)\n\n\n\nconst SdkDebugKey = \"SdkDebug\"\n\n\ntype Client struct {\n\tsling.Doer\n\t*sling.Sling\n}\n\ntype ApiKeyClientOption func(*ApiKeyClientOptions)\ntype ApiKeyClientOptions struct {\n\tInsecureSkipVerify bool\n\n\tInsecureUsePlaintext bool\n\n\tEnableRoot bool\n\n\tProduct string\n\n\tDebugWriter io.Writer\n}\n\nvar DefaultApiKeyClientOptions = ApiKeyClientOptions{\n\tInsecureSkipVerify: false,\n\tInsecureUsePlaintext: false,\n\tEnableRoot: false,\n}\n\n\n\nvar InsecureNoSSLVerification ApiKeyClientOption\n\n\n\nvar InsecureUsePlaintext ApiKeyClientOption\n\n\nvar EnableRoot ApiKeyClientOption\n\n\n\n\n\n\nfunc DebugLogRequests(w io.Writer) ApiKeyClientOption {\n\treturn func(o *ApiKeyClientOptions) {\n\t\to.DebugWriter = w\n\t}\n}\n\nfunc init() {\n\tInsecureNoSSLVerification = func(o *ApiKeyClientOptions) {\n\t\to.InsecureSkipVerify = true\n\t}\n\n\tInsecureUsePlaintext = func(o *ApiKeyClientOptions) {\n\t\to.InsecureUsePlaintext = true\n\t}\n\n\tEnableRoot = func(o *ApiKeyClientOptions) {\n\t\to.EnableRoot = true\n\t}\n}\n\nfunc UserAgent(product string) ApiKeyClientOption ", "output": "{\n\treturn func(o *ApiKeyClientOptions) {\n\t\to.Product = product\n\t}\n}"} {"input": "package aliasdirectlink\n\n\ntype Request struct {\n\tOrderID string `json:\"orderId\"`\n\tAmount string `json:\",\"`\n\tAlias string `json:\"alias\"`\n}\n\n\n\n\n\nfunc NewRequest() *Request {\n\treturn &Request{}\n}\n\nfunc (r *Request) isValid() error ", "output": "{\n\tif \"\" == r.Alias {\n\t\treturn nil\n\t}\n\n\treturn nil\n}"} {"input": "package db\n\nimport (\n\t\"github.com/globalsign/mgo\"\n\t\"github.com/tsuru/config\"\n\t\"github.com/tsuru/tsuru/db/storage\"\n)\n\nconst (\n\tDefaultDatabaseURL = \"127.0.0.1:27017\"\n\tDefaultDatabaseName = \"gandalf\"\n)\n\ntype Storage struct {\n\t*storage.Storage\n}\n\n\n\n\n\n\n\nfunc Conn() (*Storage, error) {\n\tvar (\n\t\tstrg Storage\n\t\terr error\n\t)\n\tstrg.Storage, err = conn()\n\treturn &strg, err\n}\n\nfunc DbConfig() (string, string) {\n\turl, _ := config.GetString(\"database:url\")\n\tif url == \"\" {\n\t\turl = DefaultDatabaseURL\n\t}\n\tdbname, _ := config.GetString(\"database:name\")\n\tif dbname == \"\" {\n\t\tdbname = DefaultDatabaseName\n\t}\n\treturn url, dbname\n}\n\n\nfunc (s *Storage) Repository() *storage.Collection {\n\treturn s.Collection(\"repository\")\n}\n\n\nfunc (s *Storage) User() *storage.Collection {\n\treturn s.Collection(\"user\")\n}\n\nfunc (s *Storage) Key() *storage.Collection {\n\tbodyIndex := mgo.Index{Key: []string{\"body\"}, Unique: true}\n\tnameIndex := mgo.Index{Key: []string{\"username\", \"name\"}, Unique: true}\n\tc := s.Collection(\"key\")\n\tc.EnsureIndex(bodyIndex)\n\tc.EnsureIndex(nameIndex)\n\treturn c\n}\n\nfunc conn() (*storage.Storage, error) ", "output": "{\n\turl, dbname := DbConfig()\n\treturn storage.Open(url, dbname)\n}"} {"input": "package terminal\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n)\n\ntype TeePrinter struct {\n\tdisableTerminalOutput bool\n\toutputBucket io.Writer\n}\n\nfunc NewTeePrinter() *TeePrinter {\n\treturn &TeePrinter{\n\t\toutputBucket: ioutil.Discard,\n\t}\n}\n\nfunc (t *TeePrinter) SetOutputBucket(bucket io.Writer) {\n\tif bucket == nil {\n\t\tbucket = ioutil.Discard\n\t}\n\n\tt.outputBucket = bucket\n}\n\nfunc (t *TeePrinter) Print(values ...interface{}) (n int, err error) {\n\tstr := fmt.Sprint(values...)\n\tt.saveOutputToBucket(str)\n\tif !t.disableTerminalOutput {\n\t\treturn fmt.Print(str)\n\t}\n\treturn\n}\n\nfunc (t *TeePrinter) Printf(format string, a ...interface{}) (n int, err error) {\n\tstr := fmt.Sprintf(format, a...)\n\tt.saveOutputToBucket(str)\n\tif !t.disableTerminalOutput {\n\t\treturn fmt.Print(str)\n\t}\n\treturn\n}\n\nfunc (t *TeePrinter) Println(values ...interface{}) (n int, err error) {\n\tstr := fmt.Sprint(values...)\n\tt.saveOutputToBucket(str)\n\tif !t.disableTerminalOutput {\n\t\treturn fmt.Println(str)\n\t}\n\treturn\n}\n\n\n\nfunc (t *TeePrinter) saveOutputToBucket(output string) {\n\tt.outputBucket.Write([]byte(Decolorize(output)))\n}\n\nfunc (t *TeePrinter) DisableTerminalOutput(disable bool) ", "output": "{\n\tt.disableTerminalOutput = disable\n}"} {"input": "package leet_10\n\nfunc isMatch(s string, p string) bool {\n\tif p == \"\" {\n\t\treturn s == p\n\t}\n\tlenp := len(p)\n\tif lenp == 1 {\n\t\treturn len(s) == 1 && equal(s[0], p[0])\n\t}\n\tif p[1] == '*' {\n\t\tif s == \"\" {\n\t\t\treturn isMatch(\"\", p[2:])\n\t\t}\n\t\treturn isMatch(s, p[2:]) ||\n\t\t\t(equal(s[0], p[0]) && isMatch(s[1:], p))\n\t}\n\tif s == \"\" {\n\t\treturn false\n\t}\n\treturn equal(s[0], p[0]) && isMatch(s[1:], p[1:])\n}\n\n\n\nfunc equal(a, b byte) bool ", "output": "{\n\treturn a == b || b == '.'\n}"} {"input": "package algorithms\n\nimport \"log\"\n\nfunc canCompleteCircuit(gas []int, cost []int) int {\n\tindex := 0\n\tfor i := 0; i < len(gas); i++ {\n\t\tgas[i] = gas[i] - cost[i]\n\t\tif i > 0 {\n\t\t\tgas[i] += gas[i-1]\n\t\t\tif gas[i] < gas[index] {\n\t\t\t\tindex = i\n\t\t\t}\n\t\t}\n\t}\n\tif gas[len(gas)-1] < 0 {\n\t\treturn -1\n\t}\n\treturn (index + 1) % len(gas)\n}\n\n\n\nfunc canCompleteCircuit(gas []int, cost []int) int ", "output": "{\n\tfor i := 0; i < len(gas); i++ {\n\t\tgas[i] = gas[i] - cost[i]\n\t}\n\tlog.Println(\"A:\", gas)\n\n\tindex := 0\n\tfor i := 1; i < len(gas); i++ {\n\t\tgas[i] += gas[i-1]\n\t\tif gas[i] < gas[index] {\n\t\t\tindex = i\n\t\t}\n\t}\n\tlog.Println(\"B:\", gas)\n\tif gas[len(gas)-1] < 0 {\n\t\treturn -1\n\t}\n\treturn (index + 1) % len(gas)\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestCreateFile(t *testing.T) ", "output": "{\n\ttmpDir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tt.Run(\"group\", func(t *testing.T) {\n\t\ttc := []struct {\n\t\t\tdir string\n\t\t}{\n\t\t\t{tmpDir},\n\t\t\t{tmpDir},\n\t\t}\n\t\tfor _, tt := range tc {\n\t\t\ttt := tt\n\t\t\tt.Run(\"\", func(st *testing.T) {\n\t\t\t\tst.Parallel()\n\n\t\t\t\t_, err := createFile(tt.dir)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\n\t})\n\tos.RemoveAll(tmpDir)\n}"} {"input": "package gfile_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/gogf/gf/v2/os/gfile\"\n\t\"github.com/gogf/gf/v2/test/gtest\"\n)\n\n\n\nfunc Test_MTimeMillisecond(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tvar (\n\t\t\tfile1 = \"/testfile_t1.txt\"\n\t\t\terr error\n\t\t\tfileobj os.FileInfo\n\t\t)\n\n\t\tcreateTestFile(file1, \"\")\n\t\tdefer delTestFiles(file1)\n\t\tfileobj, err = os.Stat(testpath() + file1)\n\t\tt.Assert(err, nil)\n\n\t\ttime.Sleep(time.Millisecond * 100)\n\t\tt.AssertGE(\n\t\t\tgfile.MTimestampMilli(testpath()+file1),\n\t\t\tfileobj.ModTime().UnixNano()/1000000,\n\t\t)\n\t\tt.Assert(gfile.MTimestampMilli(\"\"), -1)\n\t})\n}\n\nfunc Test_MTime(t *testing.T) ", "output": "{\n\tgtest.C(t, func(t *gtest.T) {\n\n\t\tvar (\n\t\t\tfile1 = \"/testfile_t1.txt\"\n\t\t\terr error\n\t\t\tfileobj os.FileInfo\n\t\t)\n\n\t\tcreateTestFile(file1, \"\")\n\t\tdefer delTestFiles(file1)\n\t\tfileobj, err = os.Stat(testpath() + file1)\n\t\tt.Assert(err, nil)\n\n\t\tt.Assert(gfile.MTime(testpath()+file1), fileobj.ModTime())\n\t\tt.Assert(gfile.MTime(\"\"), \"\")\n\t})\n}"} {"input": "package chapter15\n\nimport \"testing\"\n\nvar longestNondecreasingSubsequenceTests = []struct {\n\tarr []int\n\texpected int\n}{\n\t{[]int{0, 8, 4, 12, 2, 10, 6, 14, 1, 9}, 4},\n\t{[]int{1, 2, 3, 4}, 4},\n\t{[]int{2, 3, 1, 6}, 3},\n\t{[]int{8, 3, 1}, 1},\n}\n\n\n\nfunc TestLongestNondecreasingSubsequence(t *testing.T) ", "output": "{\n\tfor _, tt := range longestNondecreasingSubsequenceTests {\n\t\tactual := LongestNondecreasingSubsequence(tt.arr)\n\t\tif actual != tt.expected {\n\t\t\tt.Errorf(\"LongestNondecreasingSubsequence(%v): expected %d, actual %d\",\n\t\t\t\ttt.arr, tt.expected, actual)\n\t\t}\n\t}\n}"} {"input": "package bookshelf\n\n\ntype Book struct {\n\tID int64\n\tTitle string\n\tAuthor string\n\tPublishedDate string\n\tImageURL string\n\tDescription string\n\tCreatedBy string\n\tCreatedByID string\n}\n\n\n\n\n\n\nfunc (b *Book) SetCreatorAnonymous() {\n\tb.CreatedBy = \"\"\n\tb.CreatedByID = \"anonymous\"\n}\n\n\ntype BookDatabase interface {\n\tListBooks() ([]*Book, error)\n\n\tListBooksCreatedBy(userID string) ([]*Book, error)\n\n\tGetBook(id int64) (*Book, error)\n\n\tAddBook(b *Book) (id int64, err error)\n\n\tDeleteBook(id int64) error\n\n\tUpdateBook(b *Book) error\n\n\tClose()\n}\n\nfunc (b *Book) CreatedByDisplayName() string ", "output": "{\n\tif b.CreatedByID == \"anonymous\" {\n\t\treturn \"Anonymous\"\n\t}\n\treturn b.CreatedBy\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"fmt\"\n\t\"github.com/go-mangos/mangos\"\n\t\"github.com/go-mangos/mangos/protocol/req\"\n\t\"github.com/go-mangos/mangos/transport/tcp\"\n)\n\n\n\nfunc main() {\n\tif len(os.Args) < 3 {\n\t\tdie(\"usage: client \")\n\t}\n\n\tvar sock mangos.Socket\n\tvar err error\n\tvar msg []byte\n\n\tif sock, err = req.NewSocket(); err != nil {\n\t\tdie(\"can't get new req socket: %s\", err.Error())\n\t}\n\tsock.AddTransport(tcp.NewTransport())\n\tif err = sock.Dial(os.Args[1]); err != nil {\n\t\tdie(\"can't dial on req socket: %s\", err.Error())\n\t}\n\tif err = sock.Send([]byte(os.Args[2])); err != nil {\n\t\tdie(\"can't send message on push socket: %s\", err.Error())\n\t}\n\tif msg, err = sock.Recv(); err != nil {\n\t\tdie(\"can't receive date: %s\", err.Error())\n\t}\n\tfmt.Printf(\"%s\\n\", string(msg))\n\tsock.Close()\n}\n\nfunc die(format string, v ...interface{}) ", "output": "{\n\tfmt.Fprintln(os.Stderr, fmt.Sprintf(format, v...))\n\tos.Exit(1)\n}"} {"input": "package realtime\n\nimport (\n\t\"io\"\n)\n\n\n\ntype Reader interface {\n\tio.Reader\n\trealtime()\n}\n\n\n\n\n\n\nfunc (r *reader) Read(target []byte) (n int, err error) {\n\tvar bf = make([]byte, 1)\n\n\tfor {\n\t\tif n == len(target) {\n\t\t\treturn\n\n\t\t}\n\n\t\t_, err = r.input.Read(bf)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif bf[0] < 0xF8 {\n\t\t\ttarget[n] = bf[0]\n\t\t\tn++\n\t\t\tcontinue\n\t\t}\n\n\t\tif m := dispatch(bf[0]); m != nil {\n\t\t\tr.handler(m)\n\t\t}\n\t}\n}\n\n\n\n\n\ntype reader struct {\n\tinput io.Reader\n\thandler func(Message)\n}\n\nfunc (r *reader) realtime() {}\n\n\ntype discardReader struct {\n\tinput io.Reader\n}\n\nfunc (r *discardReader) realtime() {}\n\nfunc (r *discardReader) Read(target []byte) (n int, err error) {\n\tvar bf []byte\n\n\tfor {\n\t\tif n == len(target) {\n\t\t\treturn\n\n\t\t}\n\t\tbf = make([]byte, 1)\n\n\t\t_, err = r.input.Read(bf)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif bf[0] < 0xF8 {\n\t\t\ttarget[n] = bf[0]\n\t\t\tn++\n\t\t\tcontinue\n\t\t}\n\n\n\t}\n\n}\n\nfunc dispatch(b byte) Message {\n\tm := msg(b)\n\tif _, has := msg2String[m]; !has {\n\t\treturn nil\n\t}\n\treturn m\n}\n\nfunc NewReader(input io.Reader, rthandler func(Message)) Reader ", "output": "{\n\tif rthandler == nil {\n\t\treturn &discardReader{input}\n\t}\n\treturn &reader{input, rthandler}\n}"} {"input": "package kernel \n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\n\nfunc GetKernelVersion() (*VersionInfo, error) {\n\tosName, err := getSPSoftwareDataType()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trelease, err := getRelease(osName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseRelease(release)\n}\n\n\nfunc getRelease(osName string) (string, error) {\n\tvar release string\n\tdata := strings.Split(osName, \"\\n\")\n\tfor _, line := range data {\n\t\tif !strings.Contains(line, \"Kernel Version\") {\n\t\t\tcontinue\n\t\t}\n\t\tcontent := strings.SplitN(line, \":\", 2)\n\t\tif len(content) != 2 {\n\t\t\treturn \"\", fmt.Errorf(\"Kernel Version is invalid\")\n\t\t}\n\n\t\tprettyNames := strings.SplitN(strings.TrimSpace(content[1]), \" \", 2)\n\n\t\tif len(prettyNames) != 2 {\n\t\t\treturn \"\", fmt.Errorf(\"Kernel Version needs to be 'Darwin x.x.x' \")\n\t\t}\n\t\trelease = prettyNames[1]\n\t}\n\n\treturn release, nil\n}\n\n\n\nfunc getSPSoftwareDataType() (string, error) ", "output": "{\n\tcmd := exec.Command(\"system_profiler\", \"SPSoftwareDataType\")\n\tosName, err := cmd.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(osName), nil\n}"} {"input": "package checksums\n\nimport (\n\t\"crypto/md5\"\n\t\"hash\"\n\t\"hash/crc32\"\n\t\"io\"\n\t\"sync\"\n)\n\nvar crc32cTable *crc32.Table\nvar tableInitOnce = new(sync.Once)\n\n\n\ntype Digest struct {\n\tmd5 hash.Hash\n\tcrc32c hash.Hash32\n}\n\n\nvar _ io.Writer = new(Digest)\n\n\nfunc NewDigest() *Digest {\n\ttableInitOnce.Do(func() { crc32cTable = crc32.MakeTable(crc32.Castagnoli) })\n\treturn &Digest{\n\t\tmd5: md5.New(),\n\t\tcrc32c: crc32.New(crc32cTable),\n\t}\n}\n\n\n\nfunc (d *Digest) Write(p []byte) (int, error) {\n\td.crc32c.Write(p)\n\td.md5.Write(p)\n\treturn len(p), nil\n}\n\n\n\n\n\nfunc (d *Digest) Checksums() Checksums {\n\treturn Checksums{\n\t\tMD5: d.md5.Sum(nil),\n\t\tCRC32C: int32(d.crc32c.Sum32()),\n\t\tHasCRC32C: true,\n\t}\n}\n\nfunc (d *Digest) Reset() ", "output": "{\n\td.md5.Reset()\n\td.crc32c.Reset()\n}"} {"input": "package geom\n\nimport \"math\"\n\n\ntype Vertex struct {\n\tX, Y float64\n}\n\n\ntype Vertices []Vertex\n\n\nfunc (l Vertices) Convert() (data []float32) {\n\n\tdata = make([]float32, len(l)*2)\n\tfor i, v := range l {\n\t\tindex := i * 2\n\t\tdata[index] = float32(v.X)\n\t\tdata[index+1] = float32(v.Y)\n\t}\n\treturn\n}\n\n\nfunc (c Vertex) SideOfLine(a Vertex, b Vertex) int {\n\n\tcross := float64((b.X-a.X)*(c.Y-a.Y) - (b.Y-a.Y)*(c.X-a.X))\n\n\tif cross == 0 {\n\t\treturn 0\n\t}\n\tif math.Signbit(cross) {\n\t\treturn 1\n\t}\n\treturn -1\n\n}\n\n\ntype Lexographically []Vertex\n\nfunc (a Lexographically) Len() int { return len(a) }\nfunc (a Lexographically) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\n\n\nfunc (a Lexographically) Less(i, j int) bool ", "output": "{\n\tif a[i].X == a[j].X {\n\t\treturn a[i].Y < a[j].Y\n\t}\n\treturn a[i].X < a[j].X\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype TerminateDbSystemRequest struct {\n\n\tDbSystemId *string `mandatory:\"true\" contributesTo:\"path\" name:\"dbSystemId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request TerminateDbSystemRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request TerminateDbSystemRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype TerminateDbSystemResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response TerminateDbSystemResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response TerminateDbSystemResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request TerminateDbSystemRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc testPostMessage(t *testing.T, requestURL, from, body string) {\n\tpostValues := url.Values{\n\t\t\"from\": {from},\n\t\t\"body\": {body},\n\t}\n\tres, err := http.PostForm(requestURL, postValues)\n\tif err != nil {\n\t\tt.Fatalf(\"Error occured: %s\", err)\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != http.StatusOK {\n\t\tt.Logf(\"URL[%s]\", requestURL)\n\t\tt.Logf(\"Parameter:from[%s], body[%s]\", from, body)\n\t\tt.Errorf(\"res.StatusCode => %d, want %d\", res.StatusCode, http.StatusOK)\n\t}\n}\n\nfunc testGetMessages(t *testing.T, requestURL string) string {\n\tres, err := http.Get(requestURL)\n\tif err != nil {\n\t\tt.Fatalf(\"Error occured: %s\", err)\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != http.StatusOK {\n\t\tt.Logf(\"URL[%s]\", requestURL)\n\t\tt.Errorf(\"res.StatusCode => %d, want %d\", res.StatusCode, http.StatusOK)\n\t}\n\n\tresMsg, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tt.Fatalf(\"Responce read error occured: %s\", err)\n\t}\n\n\treturn string(resMsg)\n}\n\nfunc TestServe(t *testing.T) ", "output": "{\n\tserver := httptest.NewServer(SetupHandler())\n\tdefer server.Close()\n\n\ttestPostMessage(t, server.URL+\"/drawer1/messages/new\", \"john\", \"testmsg1\")\n\ttestPostMessage(t, server.URL+\"/drawer2/messages/new\", \"smith\", \"testmsg2\")\n\ttestPostMessage(t, server.URL+\"/messages/new\", \"admin\", \"broadcast\")\n\n\tjsonMessages := testGetMessages(t, server.URL+\"/drawer1/messages\")\n\tif !strings.Contains(jsonMessages, \"testmsg1\") {\n\t\tt.Errorf(\"Drower1 must has %s, but does not.\", \"testmsg1\")\n\t}\n\tif !strings.Contains(jsonMessages, \"broadcast\") {\n\t\tt.Errorf(\"Drower1 must has %s, but does not.\", \"broadcast\")\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetVolumeKmsKeyRequest struct {\n\n\tVolumeId *string `mandatory:\"true\" contributesTo:\"path\" name:\"volumeId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetVolumeKmsKeyRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request GetVolumeKmsKeyRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\n\n\n\nfunc (request GetVolumeKmsKeyRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetVolumeKmsKeyResponse struct {\n\n\tRawResponse *http.Response\n\n\tVolumeKmsKey `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetVolumeKmsKeyResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetVolumeKmsKeyResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetVolumeKmsKeyRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc foo(x int) bool {\n\treturn x == x \n}\n\n\n\nfunc main() {\n\tfoo(42)\n}\n\nconst mode = \"Debug\"\n\nfunc log(msg string) {\n\tif mode == \"Debug\" {\n\t\tfmt.Println(msg)\n\t}\n}\n\nfunc bar() {\n\tif ptrsize == 8 { \n\t\tfmt.Println()\n\t}\n}\n\nfunc bump(x *int) {\n\t*x++\n}\n\nfunc baz() bool {\n\tvar x = 0\n\tbump(&x)\n\treturn x == 0\n}\n\ntype counter int\n\nfunc (x *counter) bump() {\n\t*x++\n}\n\nfunc (x counter) bimp() {\n\tx++\n}\n\nfunc baz2() bool {\n\tvar x counter\n\tx.bump()\n\treturn x == 0 \n}\n\nfunc baz3() bool {\n\tvar y counter\n\ty.bimp()\n\treturn y == 0 \n}\n\nfunc isNaN(x float32) bool ", "output": "{\n\treturn x != x \n}"} {"input": "package test_helpers\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\tdatatypes \"github.com/maximilien/softlayer-go/data_types\"\n)\n\ntype MockProductPackageService struct{}\n\nfunc (mock *MockProductPackageService) GetName() string {\n\treturn \"Mock_Product_Package_Service\"\n}\n\nfunc (mock *MockProductPackageService) GetItemsByType(packageType string) ([]datatypes.SoftLayer_Product_Item, error) {\n\tresponse, _ := ReadJsonTestFixtures(\"services\", \"SoftLayer_Product_Package_getItemsByType_virtual_server.json\")\n\n\tproductItems := []datatypes.SoftLayer_Product_Item{}\n\tjson.Unmarshal(response, &productItems)\n\n\treturn productItems, nil\n}\n\nfunc (mock *MockProductPackageService) GetItemPrices(packageId int) ([]datatypes.SoftLayer_Product_Item_Price, error) {\n\treturn []datatypes.SoftLayer_Product_Item_Price{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetItemPricesBySize(packageId int, size int) ([]datatypes.SoftLayer_Product_Item_Price, error) {\n\treturn []datatypes.SoftLayer_Product_Item_Price{}, errors.New(\"Not supported\")\n}\n\n\n\nfunc (mock *MockProductPackageService) GetPackagesByType(packageType string) ([]datatypes.Softlayer_Product_Package, error) {\n\treturn []datatypes.Softlayer_Product_Package{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetOnePackageByType(packageType string) (datatypes.Softlayer_Product_Package, error) {\n\treturn datatypes.Softlayer_Product_Package{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetItems(packageId int) ([]datatypes.SoftLayer_Product_Item, error) ", "output": "{\n\treturn []datatypes.SoftLayer_Product_Item{}, errors.New(\"Not supported\")\n}"} {"input": "package triegen\n\n\n\nimport \"io\"\n\n\n\n\n\ntype Compacter interface {\n\tSize(v []uint64) (sz int, ok bool)\n\n\tStore(v []uint64) uint32\n\n\tPrint(w io.Writer) error\n\n\tHandler() string\n}\n\n\n\ntype simpleCompacter builder\n\n\n\nfunc (b *simpleCompacter) Store(v []uint64) uint32 {\n\th := uint32(len(b.ValueBlocks) - blockOffset)\n\tb.ValueBlocks = append(b.ValueBlocks, v)\n\treturn h\n}\n\nfunc (b *simpleCompacter) Print(io.Writer) error {\n\treturn nil\n}\n\nfunc (b *simpleCompacter) Handler() string {\n\tpanic(\"Handler should be special-cased for this Compacter\")\n}\n\nfunc (b *simpleCompacter) Size([]uint64) (sz int, ok bool) ", "output": "{\n\treturn blockSize * b.ValueSize, true\n}"} {"input": "package stores\n\nimport (\n\t\"HTVM/instructions/base\"\n\t\"HTVM/runtime\"\n)\n\n\ntype ASTORE struct {\n\tbase.Index8Instruction\n}\n\nfunc (self *ASTORE) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, self.Index)\n}\n\ntype ASTORE_0 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_0) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 0)\n}\n\ntype ASTORE_1 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_1) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 1)\n}\n\ntype ASTORE_2 struct {\n\tbase.NoOperandsInstruction\n}\n\n\n\ntype ASTORE_3 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_3) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 3)\n}\n\ntype ASTORE_4 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_4) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 4)\n}\n\nfunc _executeRef(frame *runtime.Frame, index uint) {\n\tval := frame.OperateStack().PopRef()\n\tframe.LocalVars().SetRef(index, val)\n}\n\nfunc (self *ASTORE_2) Execute(frame *runtime.Frame) ", "output": "{\n\t_executeRef(frame, 2)\n}"} {"input": "package platform\n\nimport (\n\t\"testing\"\n)\n\nfunc TestGCPConfigDefaultValue(t *testing.T) {\n\tc := &GcpClientConfig{}\n\n\tflags := c.GetFlagSet()\n\t_ = flags.Parse([]string{})\n\n\tif c.RootCACertFile != flags.Lookup(\"root-cert\").DefValue {\n\t\tt.Errorf(\"GCP Default Config Flag: wrong default value. Expected %s, Actual %s\",\n\t\t\tflags.Lookup(\"root-cert\").DefValue, c.RootCACertFile)\n\t}\n}\n\n\n\nfunc TestGCPFlag(t *testing.T) ", "output": "{\n\tc := &GcpClientConfig{}\n\n\tflags := c.GetFlagSet()\n\tcertLoc := \"/etc/root.cert.pem\"\n\t_ = flags.Parse([]string{\"--root-cert\", certLoc})\n\n\tif c.RootCACertFile != certLoc {\n\t\tt.Errorf(\"GCP Config Flag: wrong value. Expected %s, Actual %s\", certLoc, c.RootCACertFile)\n\t}\n}"} {"input": "package checksums\n\nimport (\n\t\"crypto/md5\"\n\t\"hash\"\n\t\"hash/crc32\"\n\t\"io\"\n\t\"sync\"\n)\n\nvar crc32cTable *crc32.Table\nvar tableInitOnce = new(sync.Once)\n\n\n\ntype Digest struct {\n\tmd5 hash.Hash\n\tcrc32c hash.Hash32\n}\n\n\nvar _ io.Writer = new(Digest)\n\n\n\n\n\n\nfunc (d *Digest) Write(p []byte) (int, error) {\n\td.crc32c.Write(p)\n\td.md5.Write(p)\n\treturn len(p), nil\n}\n\n\nfunc (d *Digest) Reset() {\n\td.md5.Reset()\n\td.crc32c.Reset()\n}\n\n\nfunc (d *Digest) Checksums() Checksums {\n\treturn Checksums{\n\t\tMD5: d.md5.Sum(nil),\n\t\tCRC32C: int32(d.crc32c.Sum32()),\n\t\tHasCRC32C: true,\n\t}\n}\n\nfunc NewDigest() *Digest ", "output": "{\n\ttableInitOnce.Do(func() { crc32cTable = crc32.MakeTable(crc32.Castagnoli) })\n\treturn &Digest{\n\t\tmd5: md5.New(),\n\t\tcrc32c: crc32.New(crc32cTable),\n\t}\n}"} {"input": "package ovnmodel\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/skydive-project/skydive/graffiti/getter\"\n\t\"github.com/skydive-project/skydive/graffiti/graph\"\n)\n\n\n\n\ntype LogicalRouter struct {\n\tUUID string `ovsdb:\"_uuid\" json:\",omitempty\" `\n\tEnabled []bool `ovsdb:\"enabled\" json:\",omitempty\" `\n\tExternalIDs map[string]string `ovsdb:\"external_ids\" json:\",omitempty\" `\n\tLoadBalancer []string `ovsdb:\"load_balancer\" json:\",omitempty\" `\n\tName string `ovsdb:\"name\" json:\",omitempty\" `\n\tNat []string `ovsdb:\"nat\" json:\",omitempty\" `\n\tOptions map[string]string `ovsdb:\"options\" json:\",omitempty\" `\n\tPolicies []string `ovsdb:\"policies\" json:\",omitempty\" `\n\tPorts []string `ovsdb:\"ports\" json:\",omitempty\" `\n\tStaticRoutes []string `ovsdb:\"static_routes\" json:\",omitempty\" `\n\n\tExternalIDsMeta graph.Metadata `json:\",omitempty\" field:\"Metadata\"`\n\tOptionsMeta graph.Metadata `json:\",omitempty\" field:\"Metadata\"`\n}\n\n\n\nfunc (t *LogicalRouter) GetUUID() string {\n\treturn t.UUID\n}\n\nfunc (t *LogicalRouter) GetName() string {\n\tif name := t.Name; name != \"\" {\n\t\treturn name\n\t}\n\treturn t.GetUUID()\n}\n\n\nfunc LogicalRouterDecoder(raw json.RawMessage) (getter.Getter, error) {\n\tvar t LogicalRouter\n\tif err := json.Unmarshal(raw, &t); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to unmarshal LogicalRouter metadata %s: %s\", string(raw), err)\n\t}\n\treturn &t, nil\n}\n\nfunc (t *LogicalRouter) Metadata() graph.Metadata ", "output": "{\n\tt.ExternalIDsMeta = graph.NormalizeValue(t.ExternalIDs).(map[string]interface{})\n\tt.OptionsMeta = graph.NormalizeValue(t.Options).(map[string]interface{})\n\n\treturn graph.Metadata{\n\t\t\"Type\": \"LogicalRouter\",\n\t\t\"Manager\": \"ovn\",\n\t\t\"UUID\": t.GetUUID(),\n\t\t\"Name\": t.GetName(),\n\t\t\"OVN\": t,\n\t}\n}"} {"input": "package flags\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\ntype Traffic struct {\n\tRevisionsPercentages []string\n\tRevisionsTags []string\n\tUntagRevisions []string\n}\n\n\n\nfunc (t *Traffic) PercentagesChanged(cmd *cobra.Command) bool {\n\treturn cmd.Flags().Changed(\"traffic\")\n}\n\nfunc (t *Traffic) TagsChanged(cmd *cobra.Command) bool {\n\treturn cmd.Flags().Changed(\"tag\") || cmd.Flags().Changed(\"untag\")\n}\n\nfunc (t *Traffic) Changed(cmd *cobra.Command) bool {\n\treturn t.PercentagesChanged(cmd) || t.TagsChanged(cmd)\n}\n\nfunc (t *Traffic) Add(cmd *cobra.Command) ", "output": "{\n\tcmd.Flags().StringSliceVar(&t.RevisionsPercentages,\n\t\t\"traffic\",\n\t\tnil,\n\t\t\"Set traffic distribution (format: --traffic revisionRef=percent) where revisionRef can be a revision or a tag or '@latest' string \"+\n\t\t\t\"representing latest ready revision. This flag can be given multiple times with percent summing up to 100%.\")\n\n\tcmd.Flags().StringSliceVar(&t.RevisionsTags,\n\t\t\"tag\",\n\t\tnil,\n\t\t\"Set tag (format: --tag revisionRef=tagName) where revisionRef can be a revision or '@latest' string representing latest ready revision. \"+\n\t\t\t\"This flag can be specified multiple times.\")\n\n\tcmd.Flags().StringSliceVar(&t.UntagRevisions,\n\t\t\"untag\",\n\t\tnil,\n\t\t\"Untag revision (format: --untag tagName). This flag can be specified multiple times.\")\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tbtn := MakeButton()\n\thandlerOne := make(chan string)\n\thandlerTwo := make(chan string)\n\tbtn.AddEventListener(\"click\", handlerOne)\n\tbtn.AddEventListener(\"click\", handlerTwo)\n\tgo func() {\n\t\tfor {\n\t\t\tmsg := <-handlerOne\n\t\t\tfmt.Println(\"Handler One: \" + msg)\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor {\n\t\t\tmsg := <-handlerTwo\n\t\t\tfmt.Println(\"Handler Two: \" + msg)\n\t\t}\n\t}()\n\n\tbtn.TriggerEvent(\"click\", \"Button clicked\")\n\tbtn.RemoveEventListener(\"click\", handlerTwo)\n\tbtn.TriggerEvent(\"click\", \"Button clicked again!\")\n\tfmt.Scanln()\n\n}\n\ntype Button struct {\n\teventListeners map[string][]chan string\n}\n\nfunc MakeButton() *Button {\n\tresult := new(Button)\n\tresult.eventListeners = make(map[string][]chan string)\n\treturn result\n}\n\n\n\nfunc (button *Button) RemoveEventListener(event string, listenerChannel chan string) {\n\tif _, present := button.eventListeners[event]; present {\n\t\tfor idx, listener_channel := range button.eventListeners[event] {\n\t\t\tif listener_channel == listenerChannel {\n\t\t\t\tbutton.eventListeners[event] = append(button.eventListeners[event][:idx], button.eventListeners[event][idx+1:]...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (button *Button) TriggerEvent(event string, response string) {\n\tif _, present := button.eventListeners[event]; present {\n\t\tfor _, handler := range button.eventListeners[event] {\n\t\t\tgo func(handler chan string) {\n\t\t\t\thandler <- response\n\t\t\t}(handler)\n\t\t}\n\t}\n}\n\nfunc (button *Button) AddEventListener(event string, responseChannel chan string) ", "output": "{\n\tif _, present := button.eventListeners[event]; present {\n\t\tbutton.eventListeners[event] = append(button.eventListeners[event], responseChannel)\n\t} else {\n\t\tbutton.eventListeners[event] = []chan string{responseChannel}\n\t}\n}"} {"input": "package header_test\n\nimport (\n\t\"testing\"\n\n\t\"gvisor.dev/gvisor/pkg/tcpip/header\"\n)\n\nfunc TestIPv4(t *testing.T) {\n\tb := header.IPv4(make([]byte, header.IPv4MinimumSize))\n\tb.Encode(&header.IPv4Fields{})\n\n\tconst want = header.IPv4Version\n\tif v := header.IPVersion(b); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}\n\nfunc TestIPv6(t *testing.T) {\n\tb := header.IPv6(make([]byte, header.IPv6MinimumSize))\n\tb.Encode(&header.IPv6Fields{})\n\n\tconst want = header.IPv6Version\n\tif v := header.IPVersion(b); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}\n\nfunc TestOtherVersion(t *testing.T) {\n\tconst want = header.IPv4Version + header.IPv6Version\n\tb := make([]byte, 1)\n\tb[0] = want << 4\n\n\tif v := header.IPVersion(b); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}\n\n\n\nfunc TestTooShort(t *testing.T) ", "output": "{\n\tb := make([]byte, 1)\n\tb[0] = (header.IPv4Version + header.IPv6Version) << 4\n\n\tconst want = -1\n\tif v := header.IPVersion(b[:0]); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n\n\tif v := header.IPVersion(nil); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}"} {"input": "package loggo\n\nvar (\n\tdefaultContext = newDefaultContxt()\n)\n\nfunc newDefaultContxt() *Context {\n\tctx := NewContext(WARNING)\n\tctx.AddWriter(DefaultWriterName, defaultWriter())\n\treturn ctx\n}\n\n\nfunc DefaultContext() *Context {\n\treturn defaultContext\n}\n\n\n\n\n\nfunc LoggerInfo() string {\n\treturn defaultContext.Config().String()\n}\n\n\n\nfunc GetLogger(name string, size ...int) Logger {\n\treturn defaultContext.GetLogger(name, size...)\n}\n\n\n\n\n\nfunc ResetLogging() {\n\tdefaultContext.ResetLoggerLevels()\n\tdefaultContext.ResetWriters()\n}\n\n\nfunc ResetWriters() {\n\tdefaultContext.ResetWriters()\n}\n\n\n\n\n\n\n\n\n\nfunc RegisterWriter(name string, writer Writer) error {\n\treturn defaultContext.AddWriter(name, writer)\n}\n\n\n\nfunc RemoveWriter(name string) (Writer, error) {\n\treturn defaultContext.RemoveWriter(name)\n}\n\n\n\n\n\n\n\n\n\n\nfunc ConfigureLoggers(specification string) error {\n\tconfig, err := ParseConfigString(specification)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefaultContext.ApplyConfig(config)\n\treturn nil\n}\n\nfunc ReplaceDefaultWriter(writer Writer) (Writer, error) ", "output": "{\n\treturn defaultContext.ReplaceWriter(DefaultWriterName, writer)\n}"} {"input": "package libDao\n\nvar (\n\tstorage Storage\n)\n\n\ntype DefaultDao struct {\n}\n\n\nfunc InitDao(sc *StorageConfig, s Storage) (err error) {\n\tif sc == nil {\n\t\terr = ErrStorageConfigIllegal\n\t\treturn\n\t}\n\tif s == nil {\n\t\tdefaultStorage := new(DefaultStorage)\n\t\tstorage = defaultStorage\n\t} else {\n\t\tstorage = s\n\t}\n\tif sc.OpenCache {\n\t\tif err = storage.InitCache(sc.CacheAddr, sc.CacheKeyPrefix); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif sc.OpenPersistence {\n\t\tif err = storage.InitPersistence(sc.PersistenceAddr, sc.PersistenceDbName); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\n\nfunc (this *DefaultDao) Get(key string, value interface{}) (err error) {\n\terr = storage.Get(key, value)\n\treturn\n}\n\n\n\n\n\nfunc (this *DefaultDao) Del(key string, value interface{}) (err error) {\n\terr = storage.Del(key, value)\n\treturn\n}\n\nfunc (this *DefaultDao) Put(key string, value interface{}) (err error) ", "output": "{\n\terr = storage.Put(key, value)\n\treturn\n}"} {"input": "package inst\n\nimport (\n\t\"github.com/github/orchestrator/go/config\"\n)\n\n\ntype Maintenance struct {\n\tMaintenanceId uint\n\tKey InstanceKey\n\tBeginTimestamp string\n\tSecondsElapsed uint\n\tIsActive bool\n\tOwner string\n\tReason string\n}\n\nvar maintenanceOwner string = \"\"\n\nfunc GetMaintenanceOwner() string {\n\tif maintenanceOwner != \"\" {\n\t\treturn maintenanceOwner\n\t}\n\treturn config.MaintenanceOwner\n}\n\n\n\nfunc SetMaintenanceOwner(owner string) ", "output": "{\n\tmaintenanceOwner = owner\n}"} {"input": "package permissions\n\nimport (\n\t\"path/filepath\"\n\t\"util\"\n)\n\n\nvar globalPermissions *PermissionsLoader\n\n\nfunc Get() *Permissions {\n\tif globalPermissions == nil {\n\t\treturn &Default\n\t}\n\treturn globalPermissions.Get()\n}\n\n\nfunc SetPath(permissions string) error {\n\tif permissions != \"default\" {\n\t\tpl, err := NewPermissionsLoader(permissions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = pl\n\t\tif !pl.Get().Watch {\n\t\t\tglobalPermissions.Close() \n\t\t}\n\n\t} else {\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = nil\n\t}\n\treturn nil\n}\n\n\ntype PermissionsLoader struct {\n\tPermissions *Permissions \n\tWatcher *util.FileWatcher \n}\n\n\nfunc (pl *PermissionsLoader) Get() *Permissions {\n\tif pl == nil {\n\t\treturn &Default\n\t}\n\n\tpl.Watcher.RLock()\n\tdefer pl.Watcher.RUnlock()\n\treturn pl.Permissions\n}\n\n\n\nfunc NewPermissionsLoader(filename string) (*PermissionsLoader, error) {\n\tfilename, err := filepath.Abs(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp, err := Load(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpl := &PermissionsLoader{\n\t\tPermissions: p,\n\t}\n\tpl.Watcher, err = util.NewFileWatcher(filename, pl)\n\treturn pl, err\n}\n\n\n\n\n\nfunc (pl *PermissionsLoader) Close() {\n\tpl.Watcher.Close()\n}\n\nfunc (pl *PermissionsLoader) Reload() error ", "output": "{\n\tp, err := Load(pl.Watcher.FileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpl.Watcher.Lock()\n\tpl.Permissions = p\n\tpl.Watcher.Unlock()\n\n\tif !p.Watch {\n\t\tpl.Close() \n\t}\n\n\treturn nil\n}"} {"input": "package rpc\n\nimport (\n\t_ \"github.com/yak-labs/chirp-lang/goapi/default\"\n\n\t\"github.com/yak-labs/chirp-lang\"\n\t\"testing\"\n)\n\nvar rpcTests = `\n proc mult {verb h} { expr {$h(x) * $h(y)} }\n # This RPC will return 3 words: \"extra_word\", the verb, and the input hash:\n\trpc serve /just_list \"list extra_word\"\n\trpc serve /multiply \"mult\"\n\n # Serve on port 31234, and wait 0.3 sec for it to start.\n\tgo {/net/http/ListenAndServe localhost:31234 \"\"}\n\t/time/Sleep [expr {300 * [/time/Millisecond]}]\n\n # Call the RPC, storing resulting 3 words in w,v,h.\n\tset r [rpc connect http://localhost:31234/just_list]\n\tset w,v,h [rpc call $r SomeVerb [hash abc 123 xyz 789]]\n\trpc close $r\n\n # Check $w and $v.\n\tmust \"extra_word\" $w\n\tmust \"SomeVerb\" $v\n\n # Check the hash.\n\tset h2 [hash $h]\n\tmust \"abc xyz\" [hkeys $h2]\n\tmust \"123\" [hget $h2 abc]\n\tmust \"789\" [hget $h2 xyz]\n\n\tset r2 [rpc connect http://localhost:31234/multiply]\n\tmust 42 [rpc call $r2 DontCareAboutVerb [hash x 6 y 7]]\n`\n\n\n\nfunc TestRpc(a *testing.T) ", "output": "{\n\tfr := chirp.NewInterpreter()\n\tfr.Eval(chirp.MkString(rpcTests))\n}"} {"input": "package main\n\nvar log string\n\ntype T int\n\nfunc (t T) a(s string) T {\n\tlog += \"a(\" + s + \")\"\n\treturn t\n}\n\n\n\ntype F func(s string) F\n\nfunc a(s string) F {\n\tlog += \"a(\" + s + \")\"\n\treturn F(a)\n}\n\nfunc b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\ntype I interface {\n\ta(s string) I\n\tb(s string) string\n}\n\ntype T1 int\n\nfunc (t T1) a(s string) I {\n\tlog += \"a(\" + s + \")\"\n\treturn t\n}\n\nfunc (T1) b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\nvar ok = true\n\nfunc bad() {\n\tif !ok {\n\t\tprintln(\"BUG\")\n\t\tok = false\n\t}\n\tprintln(log)\n}\n\nfunc main() {\n\tvar t T\n\tif t.a(\"1\").a(t.b(\"2\")); log != \"a(1)ba(2)\" {\n\t\tbad()\n\t}\n\tlog = \"\"\n\tif a(\"3\")(b(\"4\"))(b(\"5\")); log != \"a(3)ba(4)ba(5)\" {\n\t\tbad()\n\t}\n\tlog = \"\"\n\tvar i I = T1(0)\n\tif i.a(\"6\").a(i.b(\"7\")).a(i.b(\"8\")).a(i.b(\"9\")); log != \"a(6)ba(7)ba(8)ba(9)\" {\n\t\tbad()\n\t}\n}\n\nfunc (T) b(s string) string ", "output": "{\n\tlog += \"b\"\n\treturn s\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/flynn/go-docopt\"\n)\n\n\n\nfunc runInstaller(args *docopt.Args) error {\n\tfmt.Printf(\"DEPRECATED: `flynn install` has been deprecated.\\nRefer to https://flynn.io/docs/installation for current installation instructions.\\nAn unsupported and unmaintained snapshot of the installer binaries at the time of deprecation is available at https://dl.flynn.io/flynn-install-deprecated.tar.gz\\n\")\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tregister(\"install\", runInstaller, `usage: flynn install`)\n}"} {"input": "package ioctl\n\nimport \"golang.org/x/sys/unix\"\n\nconst (\n\ttypeBits = 8\n\tnumberBits = 8\n\tsizeBits = 14\n\tdirectionBits = 2\n\n\ttypeMask = (1 << typeBits) - 1\n\tnumberMask = (1 << numberBits) - 1\n\tsizeMask = (1 << sizeBits) - 1\n\tdirectionMask = (1 << directionBits) - 1\n\n\tdirectionNone = 0\n\tdirectionWrite = 1\n\tdirectionRead = 2\n\n\tnumberShift = 0\n\ttypeShift = numberShift + numberBits\n\tsizeShift = typeShift + typeBits\n\tdirectionShift = sizeShift + sizeBits\n)\n\nfunc ioc(dir, t, nr, size uintptr) uintptr {\n\treturn (dir << directionShift) | (t << typeShift) | (nr << numberShift) | (size << sizeShift)\n}\n\n\nfunc Io(t, nr uintptr) uintptr {\n\treturn ioc(directionNone, t, nr, 0)\n}\n\n\nfunc IoR(t, nr, size uintptr) uintptr {\n\treturn ioc(directionRead, t, nr, size)\n}\n\n\nfunc IoW(t, nr, size uintptr) uintptr {\n\treturn ioc(directionWrite, t, nr, size)\n}\n\n\n\n\n\nfunc Ioctl(fd, op, arg uintptr) error {\n\t_, _, ep := unix.Syscall(unix.SYS_IOCTL, fd, op, arg)\n\tif ep != 0 {\n\t\treturn ep\n\t}\n\treturn nil\n}\n\nfunc IoRW(t, nr, size uintptr) uintptr ", "output": "{\n\treturn ioc(directionRead|directionWrite, t, nr, size)\n}"} {"input": "package counter\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestRollingCounterMinInterval(t *testing.T) ", "output": "{\n\tcount := NewRolling(time.Second/2, 10)\n\ttk1 := time.NewTicker(5 * time.Millisecond)\n\tdefer tk1.Stop()\n\tfor i := 0; i < 100; i++ {\n\t\t<-tk1.C\n\t\tcount.Add(1)\n\t}\n\n\tv := count.Value()\n\tt.Logf(\"count value: %d\", v)\n\tif v < 90 || v > 110 {\n\t\tt.Errorf(\"expect value in [90-110] get %d\", v)\n\t}\n}"} {"input": "package muduorpc\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/rpc\"\n\t\"strings\"\n\n\t\"code.google.com/p/goprotobuf/proto\"\n)\n\ntype ClientCodec struct {\n\tconn io.ReadWriteCloser\n\tr io.Reader\n\tpayload []byte\n}\n\n\n\nfunc (c *ClientCodec) ReadResponseHeader(r *rpc.Response) (err error) {\n\tif c.payload != nil {\n\t\tpanic(\"payload is not nil\")\n\t}\n\n\tvar msg *RpcMessage\n\tmsg, err = Decode(c.r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif *msg.Type != *MessageType_RESPONSE.Enum() {\n\t\terr = fmt.Errorf(\"Wrong message type.\")\n\t\treturn\n\t}\n\n\tr.Seq = *msg.Id\n\tc.payload = msg.Response\n\treturn nil\n}\n\n\nfunc (c *ClientCodec) ReadResponseBody(body interface{}) (err error) {\n\tif c.payload == nil {\n\t\tpanic(\"payload is nil\")\n\t}\n\n\tmsg, ok := body.(proto.Message)\n\tif !ok {\n\t\treturn fmt.Errorf(\"body is not a protobuf Message\")\n\t}\n\n\terr = proto.Unmarshal(c.payload, msg)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tc.payload = nil\n\treturn\n}\n\nfunc (c *ClientCodec) Close() error {\n\treturn c.conn.Close()\n}\n\nfunc NewClientCodec(conn io.ReadWriteCloser) *ClientCodec {\n\tcodec := new(ClientCodec)\n\tcodec.conn = conn\n\tcodec.r = bufio.NewReader(conn)\n\treturn codec\n}\n\nfunc (c *ClientCodec) WriteRequest(r *rpc.Request, body interface{}) error ", "output": "{\n\tmsg := new(RpcMessage)\n\tmsg.Type = MessageType_REQUEST.Enum()\n\tmsg.Id = &r.Seq\n\tlast_dot := strings.LastIndex(r.ServiceMethod, \".\")\n\tif last_dot < 0 {\n\t\tpanic(fmt.Sprintf(\"Invalid ServiceMethod '%s'\", r.ServiceMethod))\n\t}\n\tservice := r.ServiceMethod[:last_dot]\n\tmsg.Service = &service\n\tmethod := r.ServiceMethod[last_dot+1:]\n\tmsg.Method = &method\n\n\tpb, ok := body.(proto.Message)\n\tif !ok {\n\t\treturn fmt.Errorf(\"not a protobuf Message\")\n\t}\n\n\tb, err := proto.Marshal(pb)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmsg.Request = b\n\n\treturn Send(c.conn, msg)\n}"} {"input": "package cli_test\n\nimport (\n\t\"flag\"\n\t\"testing\"\n\n\t\"github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/codegangsta/cli\"\n)\n\n\n\nfunc TestCommandIgnoreFlags(t *testing.T) {\n\tapp := cli.NewApp()\n\tset := flag.NewFlagSet(\"test\", 0)\n\ttest := []string{\"blah\", \"blah\"}\n\tset.Parse(test)\n\n\tc := cli.NewContext(app, set, set)\n\n\tcommand := cli.Command{\n\t\tName: \"test-cmd\",\n\t\tAliases: []string{\"tc\"},\n\t\tUsage: \"this is for testing\",\n\t\tDescription: \"testing\",\n\t\tAction: func(_ *cli.Context) {},\n\t\tSkipFlagParsing: true,\n\t}\n\terr := command.Run(c)\n\n\texpect(t, err, nil)\n}\n\nfunc TestCommandDoNotIgnoreFlags(t *testing.T) ", "output": "{\n\tapp := cli.NewApp()\n\tset := flag.NewFlagSet(\"test\", 0)\n\ttest := []string{\"blah\", \"blah\", \"-break\"}\n\tset.Parse(test)\n\n\tc := cli.NewContext(app, set, set)\n\n\tcommand := cli.Command{\n\t\tName: \"test-cmd\",\n\t\tAliases: []string{\"tc\"},\n\t\tUsage: \"this is for testing\",\n\t\tDescription: \"testing\",\n\t\tAction: func(_ *cli.Context) {},\n\t}\n\terr := command.Run(c)\n\n\texpect(t, err.Error(), \"flag provided but not defined: -break\")\n}"} {"input": "package overview\n\nimport (\n\t\"appengine\"\n\n\th \"github.com/czertbytes/pocket/pkg/http\"\n\tt \"github.com/czertbytes/pocket/pkg/types\"\n)\n\ntype Notificator struct {\n\tAppEngineContext appengine.Context\n\tRequestContext *h.RequestContext\n}\n\nfunc NewNotificator(RequestContext *h.RequestContext) *Notificator {\n\treturn &Notificator{\n\t\tAppEngineContext: RequestContext.AppEngineContext,\n\t\tRequestContext: RequestContext,\n\t}\n}\n\nfunc (self *Notificator) Create(overview *t.Overview) error {\n\treturn nil\n}\n\nfunc (self *Notificator) Update(overview *t.Overview) error {\n\treturn nil\n}\n\n\n\nfunc (self *Notificator) CreateParticipant(participant *t.User) error {\n\treturn nil\n}\n\nfunc (self *Notificator) CreatePayment(payment *t.Payment) error ", "output": "{\n\treturn nil\n}"} {"input": "package api\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"net/http\"\n\n\t\"github.com/coreos/fleet/log\"\n)\n\nvar unavailable = &unavailableHdlr{}\n\nfunc NewServer(listeners []net.Listener, hdlr http.Handler) *Server {\n\treturn &Server{\n\t\tlisteners: listeners,\n\t\tapi: hdlr,\n\t\tcur: unavailable,\n\t}\n}\n\ntype Server struct {\n\tlisteners []net.Listener\n\tapi http.Handler\n\tcur http.Handler\n}\n\nfunc (s *Server) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\ts.cur.ServeHTTP(rw, req)\n}\n\nfunc (s *Server) Serve() {\n\tfor i, _ := range s.listeners {\n\t\tl := s.listeners[i]\n\t\tgo func() {\n\t\t\terr := http.Serve(l, s)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed serving HTTP on listener: %s\", l.Addr)\n\t\t\t}\n\t\t}()\n\t}\n}\n\n\n\n\n\n\ntype unavailableHdlr struct{}\n\nfunc (uh *unavailableHdlr) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tsendError(rw, http.StatusServiceUnavailable, errors.New(\"fleet server currently unavailable\"))\n}\n\nfunc (s *Server) Available(stop chan bool) ", "output": "{\n\ts.cur = s.api\n\t<-stop\n\ts.cur = unavailable\n}"} {"input": "package logical\n\ntype HTTPCodedError interface {\n\tError() string\n\tCode() int\n}\n\nfunc CodedError(status int, msg string) HTTPCodedError {\n\treturn &codedError{\n\t\tStatus: status,\n\t\tMessage: msg,\n\t}\n}\n\ntype codedError struct {\n\tStatus int\n\tMessage string\n}\n\nfunc (e *codedError) Error() string {\n\treturn e.Message\n}\n\nfunc (e *codedError) Code() int {\n\treturn e.Status\n}\n\n\n\ntype StatusBadRequest struct {\n\tErr string\n}\n\n\nfunc (s *StatusBadRequest) Error() string {\n\treturn s.Err\n}\n\n\n\n\n\ntype ReplicationCodedError struct {\n\tMsg string\n\tCode int\n}\n\n\n\nfunc (r *ReplicationCodedError) Error() string ", "output": "{\n\treturn r.Msg\n}"} {"input": "package keytransform\n\nimport ds \"github.com/ipfs/go-datastore\"\n\n\ntype Pair struct {\n\tConvert KeyMapping\n\tInvert KeyMapping\n}\n\nfunc (t *Pair) ConvertKey(k ds.Key) ds.Key {\n\treturn t.Convert(k)\n}\n\nfunc (t *Pair) InvertKey(k ds.Key) ds.Key {\n\treturn t.Invert(k)\n}\n\nvar _ KeyTransform = (*Pair)(nil)\n\n\n\n\n\n\ntype PrefixTransform struct {\n\tPrefix ds.Key\n}\n\n\n\n\n\nfunc (p PrefixTransform) InvertKey(k ds.Key) ds.Key {\n\tif p.Prefix.String() == \"/\" {\n\t\treturn k\n\t}\n\n\tif !p.Prefix.IsAncestorOf(k) {\n\t\tpanic(\"expected prefix not found\")\n\t}\n\n\ts := k.String()[len(p.Prefix.String()):]\n\treturn ds.RawKey(s)\n}\n\nvar _ KeyTransform = (*PrefixTransform)(nil)\n\nfunc (p PrefixTransform) ConvertKey(k ds.Key) ds.Key ", "output": "{\n\treturn p.Prefix.Child(k)\n}"} {"input": "package framework\n\n\ntype FieldType uint\n\nconst (\n\tTypeInvalid FieldType = 0\n\tTypeString FieldType = iota\n\tTypeInt\n\tTypeBool\n\tTypeMap\n\n\tTypeDurationSecond\n\n\tTypeSlice\n\n\tTypeStringSlice\n\n\tTypeCommaStringSlice\n\n\tTypeLowerCaseString\n\n\tTypeNameString\n\n\tTypeKVPairs\n\n\tTypeCommaIntSlice\n)\n\n\n\nfunc (t FieldType) String() string ", "output": "{\n\tswitch t {\n\tcase TypeString:\n\t\treturn \"string\"\n\tcase TypeLowerCaseString:\n\t\treturn \"lowercase string\"\n\tcase TypeNameString:\n\t\treturn \"name string\"\n\tcase TypeInt:\n\t\treturn \"int\"\n\tcase TypeBool:\n\t\treturn \"bool\"\n\tcase TypeMap:\n\t\treturn \"map\"\n\tcase TypeKVPairs:\n\t\treturn \"keypair\"\n\tcase TypeDurationSecond:\n\t\treturn \"duration (sec)\"\n\tcase TypeSlice, TypeStringSlice, TypeCommaStringSlice, TypeCommaIntSlice:\n\t\treturn \"slice\"\n\tdefault:\n\t\treturn \"unknown type\"\n\t}\n}"} {"input": "\n\nfunc Merge(left, right []int) []int {\n\tsize := len(left)+len(right)\n\ti := 0 \n\tj:= 0\n\tslice := make([]int, size, size)\n\tfor k := 0; k < size; k++ {\n\t\tif i > len(left)-1 && j <= len(right)-1 {\n\t\t\tslice[k] = right[j]\n\t\t\tj++\n\t\t} else if j > len(right)-1 && i <= len(left)-1 {\n\t\t\tslice[k] = left[i]\n\t\t\ti++\n\t\t} else if left[i] < right[j] {\n\t\t\tslice[k] = left[i]\n\t\t\ti++\n\t\t} else {\n\t\t\tslice[k] = right[j]\n\t\t\tj++\n\t\t}\n\t}\n\treturn slice\n}\n\nfunc MergeSort(slice []int) []int ", "output": "{ \n\tif len(slice) < 2 { \n\t\treturn slice\n\t}\n\tmid := (len(slice)) / 2 \n\treturn Merge(MergeSort(slice[:mid]), MergeSort(slice[mid:]))\n}"} {"input": "package mock_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/pingcap/check\"\n\t\"github.com/pingcap/tidb/br/pkg/mock\"\n\t\"github.com/pingcap/tidb/util/testleak\"\n)\n\n\n\nvar _ = Suite(&testClusterSuite{})\n\ntype testClusterSuite struct {\n\tmock *mock.Cluster\n}\n\nfunc (s *testClusterSuite) SetUpSuite(c *C) {\n\tvar err error\n\ts.mock, err = mock.NewCluster()\n\tc.Assert(err, IsNil)\n}\n\nfunc (s *testClusterSuite) TearDownSuite(c *C) {\n\ttestleak.AfterTest(c)()\n}\n\nfunc (s *testClusterSuite) TestSmoke(c *C) {\n\tc.Assert(s.mock.Start(), IsNil)\n\ts.mock.Stop()\n}\n\nfunc Test(t *testing.T) ", "output": "{\n\tTestingT(t)\n}"} {"input": "package identity\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype UpdateSwiftPasswordDetails struct {\n\n\tDescription *string `mandatory:\"false\" json:\"description\"`\n}\n\n\n\nfunc (m UpdateSwiftPasswordDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package eventlistener\n\nimport (\n\t\"testing\"\n\t\"github.com/docker/docker/api/types\"\n\t\"golang.org/x/net/context\"\n\t\"fmt\"\n\t\"time\"\n\t\"github.com/docker/docker/api/types/events\"\n)\n\n\nfunc TestEventListener(t *testing.T) {\n\n\tconst labelToMonitor = \"tugbot-test\"\n\ttsk := make(chan string, 10)\n\n\tRegister(dockerClientMock{}, labelToMonitor, tsk)\n\tselect {\n\tcase res := <-tsk:\n\t\tfmt.Println(\"we recieved the die container id via the tasks chan: \", res)\n\tcase <-time.After(time.Second * 5):\n\t\tt.Error(\"we did not recieved the die container id on the tasks chan after 5 sec!\")\n\t}\n}\n\ntype dockerClientMock struct {}\n\nfunc (d dockerClientMock) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) {\n\teventsChan := make(chan events.Message, 10)\n\terrChan := make(chan error, 10)\n\tevent := events.Message{ Type: \"container\", Action: \"die\", }\n\teventsChan <- event\n\treturn eventsChan, errChan\n}\nfunc (d dockerClientMock) Info(ctx context.Context) (types.Info, error) {\n\tpanic(\"This function not suppose to be called\")\n}\nfunc (d dockerClientMock) RegistryLogin(ctx context.Context, auth types.AuthConfig) (types.AuthResponse, error) {\n\tpanic(\"This function not suppose to be called\")\n}\n\n\n\nfunc (d dockerClientMock) Ping(ctx context.Context) (bool, error) {\n\tpanic(\"This function not suppose to be called\")\n}\n\nfunc (d dockerClientMock) DiskUsage(ctx context.Context) (types.DiskUsage, error) ", "output": "{\n\tpanic(\"This function not suppose to be called\")\n}"} {"input": "package dom\n\n\n\nimport (\n \"xml\"\n)\n\ntype _text struct {\n _cdata\n}\n\nfunc (t *_text) NodeName() (s string) {\n return \"#text\"\n}\n\n\n\nfunc newText(token xml.CharData) (*_text) ", "output": "{\n n := newNode(TEXT_NODE)\n t := &_text{ _cdata{n, token.Copy()} }\n n.self = Node(t)\n return t\n}"} {"input": "package osutil\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\nvar mountInfoPath = \"/proc/self/mountinfo\"\n\n\n\nfunc IsMounted(baseDir string) (bool, error) ", "output": "{\n\tf, err := os.Open(mountInfoPath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer f.Close()\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tl := strings.Fields(scanner.Text())\n\t\tif len(l) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif len(l) < 7 {\n\t\t\treturn false, fmt.Errorf(\"unexpected mountinfo line: %q\", scanner.Text())\n\t\t}\n\t\tmountPoint := l[4]\n\t\tif baseDir == mountPoint {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, scanner.Err()\n}"} {"input": "package messagestore\n\nimport (\n\t\"github.com/agl/ed25519\"\n\tlog \"github.com/repbin/repbin/deferconsole\"\n\t\"github.com/repbin/repbin/utils\"\n\t\"github.com/repbin/repbin/utils/keyproof\"\n\t\"github.com/repbin/repbin/utils/repproto/structs\"\n)\n\n\nfunc (store Store) TouchPeer(pubkey *[ed25519.PublicKeySize]byte) {\n\terr := store.db.TouchPeer(pubkey)\n\tif err != nil {\n\t\tlog.Errorf(\"TouchPeer: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t}\n}\n\n\n\n\n\nfunc (store Store) UpdatePeerNotification(pubkey *[ed25519.PublicKeySize]byte, hasError bool) {\n\terr := store.db.UpdatePeerNotification(pubkey, hasError)\n\tif err != nil {\n\t\tlog.Errorf(\"UpdatePeerNotification: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t}\n}\n\n\nfunc (store Store) GetPeerStat(pubkey *[ed25519.PublicKeySize]byte) *structs.PeerStruct {\n\tst, err := store.db.SelectPeer(pubkey)\n\tif err != nil {\n\t\tlog.Errorf(\"GetPeerStat: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t\treturn nil\n\t}\n\treturn st\n}\n\n\nfunc (store Store) UpdatePeerAuthToken(senderPubKey *[ed25519.PublicKeySize]byte, signedToken *[keyproof.ProofTokenSignedSize]byte) {\n\terr := store.db.UpdatePeerToken(senderPubKey, signedToken)\n\tif err != nil {\n\t\tlog.Errorf(\"UpdatePeerAuthToken: %s, %s\\n\", err, utils.B58encode(senderPubKey[:]))\n\t}\n}\n\nfunc (store Store) UpdatePeerFetchStat(pubkey *[ed25519.PublicKeySize]byte, lastFetch, lastPos, lastErrors uint64) ", "output": "{\n\terr := store.db.UpdatePeerStats(pubkey, lastFetch, lastPos, lastErrors)\n\tif err != nil {\n\t\tlog.Errorf(\"UpdatePeerStats: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t}\n}"} {"input": "package boltPackages\n\nimport \"syscall\"\n\n\n\nfunc init() ", "output": "{\n\tmmapFlags = syscall.MAP_POPULATE\n}"} {"input": "package plugin_server\n\nimport (\n\t\"github.com/pivotal-golang/lager\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/rpc\"\n)\n\ntype PluginServer interface {\n\tStart() error\n\tTest(string, *StringResponse) error\n}\n\ntype pluginServer struct {\n\tlogger lager.Logger\n}\n\ntype StringResponse struct {\n\tStringResponse string\n}\n\nfunc NewPluginServer(logger lager.Logger) PluginServer {\n\treturn &pluginServer{\n\t\tlogger: logger,\n\t}\n}\n\nfunc (p *pluginServer) Start() error {\n\tp.logger.Debug(\"Starting plugin server...\")\n\n\trpc.Register(p)\n\trpc.HandleHTTP()\n\tlistener, err := net.Listen(\"tcp\", \":4249\")\n\tif err != nil {\n\t\tp.logger.Error(\"Error starting RPC client\", err)\n\t\treturn err\n\t}\n\n\tgo http.Serve(listener, nil)\n\n\tp.logger.Debug(\"Plugin server started\")\n\treturn nil\n}\n\n\n\nfunc (p *pluginServer) Test(request string, response *StringResponse) error ", "output": "{\n\tp.logger.Debug(\"Plugin server received Test call: \" + request)\n\n\tresponse.StringResponse = \"Hello from GoHome!\"\n\treturn nil\n}"} {"input": "package pump\n\nimport (\n\t\"math\"\n\n\t\"github.com/tidepool-org/platform/data\"\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tBolusAmountMaximumUnitsUnits = \"Units\"\n\tBolusAmountMaximumValueUnitsMaximum = 100.0\n\tBolusAmountMaximumValueUnitsMinimum = 0.0\n)\n\nfunc BolusAmountMaximumUnits() []string {\n\treturn []string{\n\t\tBolusAmountMaximumUnitsUnits,\n\t}\n}\n\ntype BolusAmountMaximum struct {\n\tUnits *string `json:\"units,omitempty\" bson:\"units,omitempty\"`\n\tValue *float64 `json:\"value,omitempty\" bson:\"value,omitempty\"`\n}\n\nfunc ParseBolusAmountMaximum(parser structure.ObjectParser) *BolusAmountMaximum {\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewBolusAmountMaximum()\n\tparser.Parse(datum)\n\treturn datum\n}\n\nfunc NewBolusAmountMaximum() *BolusAmountMaximum {\n\treturn &BolusAmountMaximum{}\n}\n\n\n\nfunc (b *BolusAmountMaximum) Validate(validator structure.Validator) {\n\tvalidator.String(\"units\", b.Units).Exists().OneOf(BolusAmountMaximumUnits()...)\n\tvalidator.Float64(\"value\", b.Value).Exists().InRange(BolusAmountMaximumValueRangeForUnits(b.Units))\n}\n\nfunc (b *BolusAmountMaximum) Normalize(normalizer data.Normalizer) {}\n\nfunc BolusAmountMaximumValueRangeForUnits(units *string) (float64, float64) {\n\tif units != nil {\n\t\tswitch *units {\n\t\tcase BolusAmountMaximumUnitsUnits:\n\t\t\treturn BolusAmountMaximumValueUnitsMinimum, BolusAmountMaximumValueUnitsMaximum\n\t\t}\n\t}\n\treturn -math.MaxFloat64, math.MaxFloat64\n}\n\nfunc (b *BolusAmountMaximum) Parse(parser structure.ObjectParser) ", "output": "{\n\tb.Units = parser.String(\"units\")\n\tb.Value = parser.Float64(\"value\")\n}"} {"input": "package prefilter\n\n\n\n\nimport (\n\t\"net/http\"\n\n\tmiddleware \"github.com/go-openapi/runtime/middleware\"\n)\n\n\ntype PutPrefilterHandlerFunc func(PutPrefilterParams) middleware.Responder\n\n\n\n\n\ntype PutPrefilterHandler interface {\n\tHandle(PutPrefilterParams) middleware.Responder\n}\n\n\nfunc NewPutPrefilter(ctx *middleware.Context, handler PutPrefilterHandler) *PutPrefilter {\n\treturn &PutPrefilter{Context: ctx, Handler: handler}\n}\n\n\ntype PutPrefilter struct {\n\tContext *middleware.Context\n\tHandler PutPrefilterHandler\n}\n\nfunc (o *PutPrefilter) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\tr = rCtx\n\t}\n\tvar Params = NewPutPrefilterParams()\n\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params) \n\n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}\n\nfunc (fn PutPrefilterHandlerFunc) Handle(params PutPrefilterParams) middleware.Responder ", "output": "{\n\treturn fn(params)\n}"} {"input": "package thrift\n\nimport \"io\"\n\ntype RichTransport struct {\n\tTTransport\n}\n\n\nfunc NewTRichTransport(trans TTransport) *RichTransport {\n\treturn &RichTransport{trans}\n}\n\nfunc (r *RichTransport) ReadByte() (c byte, err error) {\n\treturn readByte(r.TTransport)\n}\n\nfunc (r *RichTransport) WriteByte(c byte) error {\n\treturn writeByte(r.TTransport, c)\n}\n\n\n\nfunc (r *RichTransport) RemainingBytes() (num_bytes uint64) {\n\treturn r.TTransport.RemainingBytes()\n}\n\nfunc readByte(r io.Reader) (c byte, err error) {\n\tv := [1]byte{0}\n\tn, err := r.Read(v[0:1])\n\tif n > 0 && (err == nil || err == io.EOF) {\n\t\treturn v[0], nil\n\t}\n\tif n > 0 && err != nil {\n\t\treturn v[0], err\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn v[0], nil\n}\n\nfunc writeByte(w io.Writer, c byte) error {\n\tv := [1]byte{c}\n\t_, err := w.Write(v[0:1])\n\treturn err\n}\n\nfunc (r *RichTransport) WriteString(s string) (n int, err error) ", "output": "{\n\treturn r.Write([]byte(s))\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/IronPark/gotham/models\"\n\t\"github.com/IronPark/gotham/module/controller\"\n\t\"github.com/IronPark/gotham/module/git\"\n\t\"github.com/zenazn/goji/web\"\n\t\"net/http\"\n)\n\ntype ApiController struct {\n\tcontroller.Controller\n}\n\n\n\nfunc (ctr *ApiController) Post(c web.C, r *http.Request) (string, int) {\n\n\trepoName := r.FormValue(\"name\")\n\tdesc := r.FormValue(\"description\")\n\tuser := \"test\"\n\tif repoName != \"\" {\n\t\tgit.NewRepo(user, repoName).CreateRepo()\n\t\tmodels.NewProject(user, repoName, desc)\n\t}\n\treturn ctr.RenderTemplate(\"index.html\", c.Env), http.StatusOK\n}\n\nfunc (ctr *ApiController) Get(c web.C, r *http.Request) (string, int) ", "output": "{\n\tc.Env[\"Title\"] = \"Default Project - free Go website project template\"\n\tc.Env[\"Nav\"] = PAGE_DASHBOARD\n\n\treturn ctr.RenderTemplate(\"index.html\", c.Env), http.StatusOK\n}"} {"input": "package alert\n\nimport (\n\t. \"aliyun-openapi-go-sdk/core\"\n)\n\ntype GetContactGroupRequest struct {\n\tRoaRequest\n\tProjectName string\n\tGroupName string\n}\n\nfunc (r *GetContactGroupRequest) SetProjectName(value string) {\n\tr.ProjectName = value\n\tr.PathParams.Set(\"ProjectName\", value)\n}\nfunc (r *GetContactGroupRequest) GetProjectName() string {\n\treturn r.ProjectName\n}\n\nfunc (r *GetContactGroupRequest) GetGroupName() string {\n\treturn r.GroupName\n}\n\nfunc (r *GetContactGroupRequest) Init() {\n\tr.RoaRequest.Init()\n\tr.PathPattern = \"/projects/ProjectName/groups/GroupName\"\n\tr.SetMethod(\"GET\")\n\tr.SetProtocol(\"HTTP\")\n\tr.SetProduct(Product)\n}\n\ntype GetContactGroupResponse struct {\n\tcode string `xml:\"code\" json:\"code\"`\n\tmessage string `xml:\"message\" json:\"message\"`\n\tsuccess string `xml:\"success\" json:\"success\"`\n\ttraceId string `xml:\"traceId\" json:\"traceId\"`\n\tresult string `xml:\"result\" json:\"result\"`\n}\n\nfunc GetContactGroup(req *GetContactGroupRequest, accessId, accessSecret string) (*GetContactGroupResponse, error) {\n\tvar pResponse GetContactGroupResponse\n\tbody, err := ApiHttpRequest(accessId, accessSecret, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tApiUnmarshalResponse(req.GetFormat(), body, &pResponse)\n\treturn &pResponse, err\n}\n\nfunc (r *GetContactGroupRequest) SetGroupName(value string) ", "output": "{\n\tr.GroupName = value\n\tr.PathParams.Set(\"GroupName\", value)\n}"} {"input": "package opts \n\n\n\ntype QuotedString struct {\n\tvalue *string\n}\n\n\nfunc (s *QuotedString) Set(val string) error {\n\t*s.value = trimQuotes(val)\n\treturn nil\n}\n\n\n\n\nfunc (s *QuotedString) String() string {\n\treturn *s.value\n}\n\nfunc trimQuotes(value string) string {\n\tlastIndex := len(value) - 1\n\tfor _, char := range []byte{'\\'', '\"'} {\n\t\tif value[0] == char && value[lastIndex] == char {\n\t\t\treturn value[1:lastIndex]\n\t\t}\n\t}\n\treturn value\n}\n\n\nfunc NewQuotedString(value *string) *QuotedString {\n\treturn &QuotedString{value: value}\n}\n\nfunc (s *QuotedString) Type() string ", "output": "{\n\treturn \"string\"\n}"} {"input": "package cmd\n\nimport \"github.com/jamesnetherton/homehub-cli/service\"\n\n\n\n\nfunc NewHardwareVersionCommand(authenticatingCommand *GenericCommand) *AuthenticationRequiringCommand ", "output": "{\n\treturn &AuthenticationRequiringCommand{\n\t\tGenericCommand: GenericCommand{\n\t\t\tName: \"HardwareVersion\",\n\t\t\tDescription: \"Gets the Home Hub hardware version\",\n\t\t\tExec: func(context *CommandContext) { context.SetResult(service.GetHub().HardwareVersion()) },\n\t\t},\n\t\tAuthenticatingCommand: authenticatingCommand,\n\t}\n}"} {"input": "package texas\n\ntype SeatResultList []*SeatResult\n\ntype SeatResult struct {\n\tm_seat *SeatPlayer\n\tpot_idx int\n\tcard_type int\n\tcard_list CardDataList\n}\n\nfunc NewSeatResult(seat *SeatPlayer, cards []int16) *SeatResult {\n\tthis := new(SeatResult)\n\tthis.m_seat = seat\n\tthis.pot_idx = seat.m_pot_point\n\tthis.card_type, this.card_list = CardTypeOfTexas(cards)\n\treturn this\n}\n\nfunc (this *SeatResult) Trace() {\n\tprintln(\"玩家:\", this.m_seat.m_seat_id, POKER_TYPE_STR[this.card_type], TraceBigCards(this.card_list))\n}\n\n\nfunc (this SeatResultList) Len() int {\n\treturn len(this)\n}\n\n\n\n\nfunc (this SeatResultList) Swap(i, j int) {\n\ttemp := this[i]\n\tthis[i] = this[j]\n\tthis[j] = temp\n}\n\nfunc (this SeatResultList) Less(i, j int) bool ", "output": "{\n\treturn this[i].card_type > this[j].card_type\n}"} {"input": "package internal \n\nimport (\n\t\"strings\"\n)\n\nconst (\n\tWatchState = 1 << iota\n\tMultiState\n\tSubscribeState\n\tMonitorState\n)\n\ntype CommandInfo struct {\n\tSet, Clear int\n}\n\nvar commandInfos = map[string]CommandInfo{\n\t\"WATCH\": {Set: WatchState},\n\t\"UNWATCH\": {Clear: WatchState},\n\t\"MULTI\": {Set: MultiState},\n\t\"EXEC\": {Clear: WatchState | MultiState},\n\t\"DISCARD\": {Clear: WatchState | MultiState},\n\t\"PSUBSCRIBE\": {Set: SubscribeState},\n\t\"SUBSCRIBE\": {Set: SubscribeState},\n\t\"MONITOR\": {Set: MonitorState},\n}\n\n\n\nfunc LookupCommandInfo(commandName string) CommandInfo {\n\tif ci, ok := commandInfos[commandName]; ok {\n\t\treturn ci\n\t}\n\treturn commandInfos[strings.ToUpper(commandName)]\n}\n\nfunc init() ", "output": "{\n\tfor n, ci := range commandInfos {\n\t\tcommandInfos[strings.ToLower(n)] = ci\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os/exec\"\n\t\"regexp\"\n\t\"strings\"\n\t\"syscall\"\n)\n\n\n\n\n\n\n\n\nfunc FindStringSubmatchMap(s string, r *regexp.Regexp) map[string]string {\n\tcaptures := make(map[string]string)\n\tmatch := r.FindStringSubmatch(s)\n\tif match == nil {\n\t\treturn captures\n\t}\n\tfor i, name := range r.SubexpNames() {\n\t\tif i != 0 {\n\t\t\tcaptures[name] = match[i]\n\t\t}\n\t}\n\treturn captures\n}\n\nfunc ExecCommandOutput(cmd string, args []string) (string, int, error) ", "output": "{\n\tLogDebug.Print(\"ExecCommandOutput called with \", cmd, args)\n\tc := exec.Command(cmd, args...)\n\tvar b bytes.Buffer\n\tc.Stdout = &b\n\tc.Stderr = &b\n\n\tif err := c.Start(); err != nil {\n\t\treturn \"\", 999, err\n\t}\n\n\n\terr := c.Wait()\n\tout := string(b.Bytes())\n\n\tfor _, line := range strings.Split(out, \"\\n\") {\n\t\tLogDebug.Print(\"out :\", line)\n\t}\n\n\tif err != nil {\n\t\tif badnews, ok := err.(*exec.ExitError); ok {\n\t\t\tif status, ok := badnews.Sys().(syscall.WaitStatus); ok {\n\t\t\t\treturn out, status.ExitStatus(), fmt.Errorf(\"rc=%d\", status.ExitStatus())\n\t\t\t}\n\t\t} else {\n\t\t\treturn out, 888, fmt.Errorf(\"unknown error\")\n\t\t}\n\t}\n\n\treturn out, 0, nil\n}"} {"input": "package font\n\nimport (\n\t\"bytes\"\n)\n\nvar alias = map[rune]string{\n\t0x2764: \"\\u2665\", \n\t0x0001f499: \"\\u2665\", \n\t0x0001f49a: \"\\u2665\", \n\t0x0001f49b: \"\\u2665\", \n\t0x0001f49c: \"\\u2665\", \n\t0x0001f49d: \"\\u2665\", \n\t0x0001F601: \":|\", \n\t0x0001F602: \":)\", \n\t0x0001F603: \":D\", \n}\n\ntype Font struct {\n\twidth int\n\theight int\n\tbitmap map[rune][]byte\n}\n\nfunc ExpandAlias(text string) string {\n\tvar f func(b *bytes.Buffer, s string)\n\tf = func(b *bytes.Buffer, s string) {\n\t\tfor _, c := range s {\n\t\t\tm, ok := alias[c]\n\t\t\tif ok {\n\t\t\t\tf(b, m)\n\t\t\t} else {\n\t\t\t\tb.WriteRune(c)\n\t\t\t}\n\t\t}\n\t}\n\tb := new(bytes.Buffer)\n\tf(b, text)\n\treturn b.String()\n}\n\nfunc (f *Font) Height() int {\n\treturn f.height\n}\n\nfunc (f *Font) Width() int {\n\treturn f.width\n}\n\n\n\nfunc (f *Font) Bitmap(c rune) []byte ", "output": "{\n\treturn f.bitmap[c]\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n)\n\n\n\n\n\n\nfunc FileExist(filePath string) bool {\n\t_, err := os.Stat(filePath)\n\tif err != nil && os.IsNotExist(err) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc AbsolutePath(Datadir string, filename string) string {\n\tif filepath.IsAbs(filename) {\n\t\treturn filename\n\t}\n\treturn filepath.Join(Datadir, filename)\n}\n\nfunc MakeName(name, version string) string ", "output": "{\n\treturn fmt.Sprintf(\"%s/v%s/%s/%s\", name, version, runtime.GOOS, runtime.Version())\n}"} {"input": "package leet_901\n\ntype StockSpanner struct {\n\tf []int\n\tprice []int\n}\n\nfunc Constructor() StockSpanner {\n\treturn StockSpanner{}\n}\n\n\n\nfunc (this *StockSpanner) Next(price int) int ", "output": "{\n\tthis.price = append(this.price, price)\n\tif len(this.f) == 0 {\n\t\tthis.f = append(this.f, 1)\n\t\treturn 1\n\t}\n\tans := 1\n\ti := len(this.price) - 2\n\tfor i >= 0 && this.price[i] <= price {\n\t\tans += this.f[i]\n\t\ti -= this.f[i]\n\t}\n\tthis.f = append(this.f, ans)\n\treturn ans\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSECSTaskDefinition_DockerVolumeConfiguration struct {\n\n\tAutoprovision bool `json:\"Autoprovision,omitempty\"`\n\n\tDriver string `json:\"Driver,omitempty\"`\n\n\tDriverOpts map[string]string `json:\"DriverOpts,omitempty\"`\n\n\tLabels map[string]string `json:\"Labels,omitempty\"`\n\n\tScope string `json:\"Scope,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) AWSCloudFormationType() string {\n\treturn \"AWS::ECS::TaskDefinition.DockerVolumeConfiguration\"\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\n\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetDependsOn(dependencies []string) ", "output": "{\n\tr._dependsOn = dependencies\n}"} {"input": "package utils\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\n\n\n\n\n\n\n\n\nfunc exitWithError(err error) {\n\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\tos.Exit(1)\n}\n\nfunc AskForConfirmation(s string) bool ", "output": "{\n\treader := bufio.NewReader(os.Stdin)\n\n\tfor {\n\t\tfmt.Printf(\"%s [y/n]: \", s)\n\n\t\tresponse, err := reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\texitWithError(err)\n\t\t}\n\n\t\tresponse = strings.ToLower(strings.TrimSpace(response))\n\n\t\tif response == \"y\" || response == \"yes\" {\n\t\t\treturn true\n\t\t} else if response == \"n\" || response == \"no\" {\n\t\t\treturn false\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype queryNode struct {\n\tvalues url.Values\n\tprefix string\n\tdistinct bool\n\tfull bool\n}\n\nfunc newQueryNode() queryNode {\n\treturn queryNode{\n\t\tvalues: url.Values{},\n\t\tprefix: \"\",\n\t\tdistinct: false,\n\t\tfull: false,\n\t}\n}\n\n\n\nfunc (q *queryNode) addOptions() {\n\tif limit != 0 {\n\t\tq.values.Set(\"limit\", strconv.Itoa(limit))\n\t}\n\tif offset != 0 {\n\t\tq.values.Set(\"offset\", strconv.Itoa(offset))\n\t}\n\tif (direction != \"\") && validateCV(\"direction\", direction) {\n\t\tq.values.Set(\"direction\", direction)\n\t}\n\tif order != \"\" {\n\t\tq.values.Set(\"order\", order)\n\t}\n\tif distinct != \"\" {\n\t\tq.distinct = true\n\t\tq.values.Set(\"distinct\", distinct)\n\t}\n}\n\nfunc (q *queryNode) processFlags(queries arrayFlags) ", "output": "{\n\tfor _, val := range queries {\n\t\tparts := strings.Split(val, \":\")\n\t\tif len(parts) == 2 {\n\t\t\tname := q.prefix + parts[0]\n\t\t\tq.values.Set(name, parts[1])\n\t\t}\n\t}\n}"} {"input": "package sql\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cockroachdb/cockroach/sql/parser\"\n)\n\n\nfunc (p *planner) Values(n parser.Values) (planNode, error) {\n\tv := &valuesNode{\n\t\trows: make([]parser.DTuple, 0, len(n)),\n\t}\n\tfor _, tuple := range n {\n\t\tdata, err := parser.EvalExpr(tuple, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvals, ok := data.(parser.DTuple)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"expected a tuple, but found %T\", data)\n\t\t}\n\t\tv.rows = append(v.rows, vals)\n\t}\n\treturn v, nil\n}\n\ntype valuesNode struct {\n\tcolumns []string\n\trows []parser.DTuple\n\tnextRow int \n}\n\n\n\nfunc (n *valuesNode) Values() parser.DTuple {\n\treturn n.rows[n.nextRow-1]\n}\n\nfunc (n *valuesNode) Next() bool {\n\tif n.nextRow >= len(n.rows) {\n\t\treturn false\n\t}\n\tn.nextRow++\n\treturn true\n}\n\nfunc (*valuesNode) Err() error {\n\treturn nil\n}\n\nfunc (n *valuesNode) Columns() []string ", "output": "{\n\treturn n.columns\n}"} {"input": "package rorm\n\ntype rorm struct {\n\tredisQuerier *RedisQuerier\n}\n\nfunc NewROrm() ROrmer {\n\treturn new(rorm).Using(\"default\")\n}\n\nfunc (r *rorm) QueryHash(key string) HashQuerySeter {\n\treturn &hashQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\n\n\nfunc (r *rorm) QueryString(key string) StringQuerySeter {\n\treturn &stringQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QueryZSet(key string) ZSetQuerySeter {\n\treturn &zsetQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QuerySet(key string) SetQuerySeter {\n\treturn &setQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r rorm) Using(alias string) ROrmer {\n\tclient, ok := redisRegistry[alias]\n\tif !ok {\n\t\tpanic(\"using reids '\" + alias + \"' not exist.\")\n\t}\n\tr.redisQuerier = &RedisQuerier{\n\t\tClient: client,\n\t}\n\treturn &r\n}\n\nfunc (r *rorm) Querier() Querier {\n\treturn r.redisQuerier\n}\n\nfunc (r *rorm) QueryKeys(key string) KeysQuerySeter ", "output": "{\n\treturn &keysQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}"} {"input": "package caaa\n\nimport (\n\t\"encoding/xml\"\n\n\t\"github.com/fgrid/iso20022\"\n)\n\ntype Document00300102 struct {\n\tXMLName xml.Name `xml:\"urn:iso:std:iso:20022:tech:xsd:caaa.003.001.02 Document\"`\n\tMessage *AcceptorCompletionAdviceV02 `xml:\"AccptrCmpltnAdvc\"`\n}\n\nfunc (d *Document00300102) AddMessage() *AcceptorCompletionAdviceV02 {\n\td.Message = new(AcceptorCompletionAdviceV02)\n\treturn d.Message\n}\n\n\n\ntype AcceptorCompletionAdviceV02 struct {\n\n\tHeader *iso20022.Header2 `xml:\"Hdr\"`\n\n\tCompletionAdvice *iso20022.AcceptorCompletionAdvice2 `xml:\"CmpltnAdvc\"`\n\n\tSecurityTrailer *iso20022.ContentInformationType6 `xml:\"SctyTrlr\"`\n}\n\nfunc (a *AcceptorCompletionAdviceV02) AddHeader() *iso20022.Header2 {\n\ta.Header = new(iso20022.Header2)\n\treturn a.Header\n}\n\n\n\nfunc (a *AcceptorCompletionAdviceV02) AddSecurityTrailer() *iso20022.ContentInformationType6 {\n\ta.SecurityTrailer = new(iso20022.ContentInformationType6)\n\treturn a.SecurityTrailer\n}\n\nfunc (a *AcceptorCompletionAdviceV02) AddCompletionAdvice() *iso20022.AcceptorCompletionAdvice2 ", "output": "{\n\ta.CompletionAdvice = new(iso20022.AcceptorCompletionAdvice2)\n\treturn a.CompletionAdvice\n}"} {"input": "package spacelog\n\nimport (\n\t\"strconv\"\n)\n\nconst (\n\tsigHUP = syscallSignal(0x1)\n)\n\ntype syscallSignal int\n\nfunc (s syscallSignal) Signal() {}\n\n\n\nfunc (s syscallSignal) String() string ", "output": "{\n\tswitch s {\n\tcase sigHUP:\n\t\treturn \"hangup\"\n\t}\n\treturn \"signal \" + strconv.Itoa(int(s))\n}"} {"input": "package SFTimeUtil\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\n\nfunc TestYMDHMSSSignParse(t *testing.T) {\n\tfmt.Println(YMDHMSSSignFormat(time.Now(), \"_${yyyy}\"))\n}\n\nfunc TestYMDHMSSFormat(t *testing.T) ", "output": "{\n\tfmt.Println(YMDHMSSFormat(time.Now(), \"yyyy-MM-dd hh:mm:ssSSSSSSSSS -0700 MST\"))\n}"} {"input": "package reaperlog\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/rifflock/lfshook\"\n\t\"go.mozilla.org/mozlogrus\"\n)\n\nvar config LogConfig\n\ntype LogConfig struct {\n\tExtras bool\n}\n\nfunc EnableExtras() {\n\tconfig.Extras = true\n}\n\nfunc EnableMozlog() {\n\tmozlogrus.Enable(\"Reaper\")\n}\n\nfunc Extras() bool {\n\treturn config.Extras\n}\n\nfunc SetConfig(c *LogConfig) {\n\tconfig = *c\n}\n\nfunc AddLogFile(filename string) {\n\tlog.AddHook(lfshook.NewHook(lfshook.PathMap{\n\t\tlog.DebugLevel: filename,\n\t\tlog.InfoLevel: filename,\n\t\tlog.WarnLevel: filename,\n\t\tlog.ErrorLevel: filename,\n\t\tlog.FatalLevel: filename,\n\t\tlog.PanicLevel: filename,\n\t}))\n}\n\nfunc Debug(format string, args ...interface{}) {\n\tlog.Debugf(format, args...)\n}\n\nfunc Info(format string, args ...interface{}) {\n\tlog.Infof(format, args...)\n}\n\nfunc Warning(format string, args ...interface{}) {\n\tlog.Warningf(format, args...)\n}\n\nfunc Fatal(format string, args ...interface{}) {\n\tlog.Fatalf(format, args...)\n}\n\n\n\nfunc Error(format string, args ...interface{}) {\n\tlog.Errorf(format, args...)\n}\n\nfunc Panic(format string, args ...interface{}) ", "output": "{\n\tlog.Panicf(format, args...)\n}"} {"input": "package types\n\nimport (\n\t\"database/sql/driver\"\n\t\"encoding/json\"\n\t\"errors\"\n)\n\n\n\n\ntype JSON json.RawMessage\n\n\nfunc (j JSON) String() string {\n\treturn string(j)\n}\n\n\nfunc (j JSON) Unmarshal(dest interface{}) error {\n\treturn json.Unmarshal(j, dest)\n}\n\n\nfunc (j *JSON) Marshal(obj interface{}) error {\n\tres, err := json.Marshal(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*j = res\n\treturn nil\n}\n\n\nfunc (j *JSON) UnmarshalJSON(data []byte) error {\n\tif j == nil {\n\t\treturn errors.New(\"json: unmarshal json on nil pointer to json\")\n\t}\n\n\t*j = append((*j)[0:0], data...)\n\treturn nil\n}\n\n\nfunc (j JSON) MarshalJSON() ([]byte, error) {\n\treturn j, nil\n}\n\n\n\n\n\n\nfunc (j *JSON) Scan(src interface{}) error {\n\tvar source []byte\n\n\tswitch src.(type) {\n\tcase string:\n\t\tsource = []byte(src.(string))\n\tcase []byte:\n\t\tsource = src.([]byte)\n\tdefault:\n\t\treturn errors.New(\"incompatible type for json\")\n\t}\n\n\t*j = JSON(append((*j)[0:0], source...))\n\n\treturn nil\n}\n\nfunc (j JSON) Value() (driver.Value, error) ", "output": "{\n\tvar r json.RawMessage\n\tif err := j.Unmarshal(&r); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn []byte(r), nil\n}"} {"input": "package mcore\n\nimport (\n\t\"log\"\n)\n\ntype StringKeyValueMap map[string]string\n\nfunc NewStringKeyValueMap() StringKeyValueMap {\n\treturn make(map[string]string)\n}\n\n\nfunc (c StringKeyValueMap) Put(key, value string) {\n\tc[key] = value\n}\n\nfunc (c StringKeyValueMap) IsContain(key string) bool {\n\t_, ok := c[key]\n\treturn ok\n}\n\n\n\nfunc (c StringKeyValueMap) GetStringWithDefault(key, defaultValue string) string {\n\tif c.IsContain(key) {\n\t\treturn c[key]\n\t}\n\tlog.Printf(\"Error: not contains key: %s\", key)\n\treturn defaultValue\n}\n\nfunc (c StringKeyValueMap) GetInt(key string) int {\n\treturn String(c.GetString(key)).ToIntNoError()\n}\n\nfunc (c StringKeyValueMap) GetBool(key string) bool {\n\treturn String(c.GetString(key)).ToBool()\n}\n\nfunc (c StringKeyValueMap) GetString(key string) string ", "output": "{\n\treturn c.GetStringWithDefault(key, \"\")\n}"} {"input": "package database\n\nimport (\n\t\"labix.org/v2/mgo\"\n\t\"labix.org/v2/mgo/bson\"\n\t\"github.com/DewaldV/crucible/config\"\n)\n\ntype MgoConnection struct {\n\tDatabase string\n\tCollection string\n}\n\n\n\nfunc (conn *MgoConnection) FindAll(m bson.M, d interface{}) {\n\tExecuteWithCollection(conn.Database, conn.Collection, func(c *mgo.Collection) error { return c.Find(m).All(d) })\n}\n\n\nfunc (conn *MgoConnection) Insert(d interface{}) {\n\tExecuteWithCollection(conn.Database, conn.Collection, func(c *mgo.Collection) error { return c.Insert(d) })\n}\n\n\n\nfunc ExecuteWithCollection(database, collection string, f func(*mgo.Collection) error) error {\n\tsession := GetSession(\"Default\")\n\tdefer session.Close()\n\n\tsession.SetMode(mgo.Monotonic, true)\n\n\tc := session.DB(database).C(collection)\n\n\treturn f(c)\n}\n\nvar sessionPool map[string]*mgo.Session\n\nfunc LoadSessions(dataSourceConfig map[string]*config.DataSourceConfiguration) {\n\tsessionPool = make(map[string]*mgo.Session)\n\tfor key, source := range dataSourceConfig {\n\t\ts, _ := mgo.Dial(source.ServerName)\n\t\tsessionPool[key] = s\n\t}\n}\n\nfunc GetSession(dataSource string) *mgo.Session {\n\ts := sessionPool[dataSource]\n\treturn s.Clone()\n}\n\nfunc (conn *MgoConnection) FindOne(m bson.M, d interface{}) ", "output": "{\n\tExecuteWithCollection(conn.Database, conn.Collection, func(c *mgo.Collection) error { return c.Find(m).One(d) })\n}"} {"input": "package rest\n\nimport (\n\tc \"github.com/KoFish/pallium/config\"\n\t\"github.com/gorilla/mux\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n)\n\nfunc Setup() {\n\troot := mux.NewRouter()\n\troot.StrictSlash(false)\n\tclient_api_v1 := root.PathPrefix(\"/_matrix/client/api/v1\").Subrouter()\n\tfederation_v1 := root.PathPrefix(\"/_matrix/federation/v1\").Subrouter()\n\n\tsetupLogin(client_api_v1)\n\tsetupRegister(client_api_v1)\n\tsetupEvents(client_api_v1)\n\tsetupRooms(client_api_v1)\n\tsetupFederation(federation_v1)\n\tsetupProfile(client_api_v1)\n\tsetupPresence(client_api_v1)\n\tsetupVoip(client_api_v1)\n\n\thttp.Handle(\"/\", root)\n}\n\n\n\nfunc Start() ", "output": "{\n\tlog.Printf(\"matrix: starting service at %v\", c.Config.Listener)\n\tl, err := net.Listen(c.Config.ListenerProtocol, c.Config.Listener)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := http.Serve(l, nil); err != nil {\n\t\tlog.Printf(\"matrix: could not start up server \\\"%v\\\"\", err)\n\t}\n}"} {"input": "package message\n\nimport \"github.com/cloustone/sentel/pkg/config\"\n\ntype Producer interface {\n\tSendMessage(msg Message) error\n\tSendMessages(msgs []Message) error\n\tClose()\n}\n\nfunc NewProducer(c config.Config, clientID string, sync bool) (Producer, error) {\n\treturn newKafkaProducer(c, clientID, sync)\n}\n\nfunc PostMessage(c config.Config, msg Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", false); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessage(msg)\n\t}\n\treturn\n}\n\nfunc PostMessages(c config.Config, msgs []Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", false); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessages(msgs)\n\t}\n\treturn\n}\n\nfunc SendMessage(c config.Config, msg Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", true); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessage(msg)\n\t}\n\treturn\n}\n\n\n\nfunc SendMessages(c config.Config, msgs []Message) (err error) ", "output": "{\n\tif producer, err := NewProducer(c, \"\", true); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessages(msgs)\n\t}\n\treturn\n}"} {"input": "package logrus_papertrail\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/botemout/consul-alerts/Godeps/_workspace/src/github.com/Sirupsen/logrus\"\n)\n\nconst (\n\tformat = \"Jan 2 15:04:05\"\n)\n\n\ntype PapertrailHook struct {\n\tHost string\n\tPort int\n\tAppName string\n\tUDPConn net.Conn\n}\n\n\nfunc NewPapertrailHook(host string, port int, appName string) (*PapertrailHook, error) {\n\tconn, err := net.Dial(\"udp\", fmt.Sprintf(\"%s:%d\", host, port))\n\treturn &PapertrailHook{host, port, appName, conn}, err\n}\n\n\nfunc (hook *PapertrailHook) Fire(entry *logrus.Entry) error {\n\tdate := time.Now().Format(format)\n\tmsg, _ := entry.String()\n\tpayload := fmt.Sprintf(\"<22> %s %s: %s\", date, hook.AppName, msg)\n\n\tbytesWritten, err := hook.UDPConn.Write([]byte(payload))\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to send log line to Papertrail via UDP. Wrote %d bytes before error: %v\", bytesWritten, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc (hook *PapertrailHook) Levels() []logrus.Level ", "output": "{\n\treturn []logrus.Level{\n\t\tlogrus.PanicLevel,\n\t\tlogrus.FatalLevel,\n\t\tlogrus.ErrorLevel,\n\t\tlogrus.WarnLevel,\n\t\tlogrus.InfoLevel,\n\t\tlogrus.DebugLevel,\n\t}\n}"} {"input": "package types\n\nimport (\n\t\"encoding/json\"\n)\n\n\n\n\ntype FilteredString struct {\n\tIsSet bool\n\tValue string\n}\n\n\n\n\nfunc (n *FilteredString) UnmarshalJSON(rawJSON []byte) error {\n\tvar value *string\n\terr := json.Unmarshal(rawJSON, &value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif value != nil {\n\t\tn.Value = *value\n\t\tn.IsSet = true\n\t\treturn nil\n\t}\n\n\tn.Value = \"\"\n\tn.IsSet = false\n\treturn nil\n}\n\nfunc (n FilteredString) MarshalJSON() ([]byte, error) {\n\tif n.IsSet {\n\t\treturn json.Marshal(n.Value)\n\t}\n\n\treturn json.Marshal(nil)\n}\n\nfunc (n *FilteredString) ParseValue(val string) ", "output": "{\n\tif val == \"\" {\n\t\tn.IsSet = false\n\t\tn.Value = \"\"\n\t\treturn\n\t}\n\n\tn.IsSet = true\n\n\tswitch val {\n\tcase \"null\", \"default\":\n\t\tn.Value = \"\"\n\tdefault:\n\t\tn.Value = val\n\t}\n}"} {"input": "package ftpclient\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\n\ntype Logger interface {\n\tLog(v ...interface{})\n\tLogf(format string, v ...interface{})\n}\n\n\nfunc NewDefaultLogger() Logger {\n\treturn &defaultLogger{\n\t\tlogger: log.New(os.Stdout, \"\", log.LstdFlags),\n\t}\n}\n\ntype defaultLogger struct {\n\tlogger *log.Logger\n}\n\nfunc (l defaultLogger) Log(args ...interface{}) {\n\tl.logger.Println(args...)\n}\n\n\n\nfunc (l defaultLogger) Logf(format string, args ...interface{}) ", "output": "{\n\tl.logger.Printf(format, args...)\n}"} {"input": "package mem\n\nimport (\n\t\"bytes\"\n\t\"sort\"\n\n\tsgmt \"github.com/m3db/m3/src/m3ninx/index/segment\"\n)\n\ntype bytesSliceIter struct {\n\terr error\n\tdone bool\n\n\tcurrentIdx int\n\tcurrent []byte\n\tbackingSlice [][]byte\n\topts Options\n}\n\nvar _ sgmt.FieldsIterator = &bytesSliceIter{}\n\nfunc newBytesSliceIter(slice [][]byte, opts Options) *bytesSliceIter {\n\tsortSliceOfByteSlices(slice)\n\treturn &bytesSliceIter{\n\t\tcurrentIdx: -1,\n\t\tbackingSlice: slice,\n\t\topts: opts,\n\t}\n}\n\nfunc (b *bytesSliceIter) Next() bool {\n\tif b.done || b.err != nil {\n\t\treturn false\n\t}\n\tb.currentIdx++\n\tif b.currentIdx >= len(b.backingSlice) {\n\t\tb.done = true\n\t\treturn false\n\t}\n\tb.current = b.backingSlice[b.currentIdx]\n\treturn true\n}\n\nfunc (b *bytesSliceIter) Current() []byte {\n\treturn b.current\n}\n\n\n\nfunc (b *bytesSliceIter) Len() int {\n\treturn len(b.backingSlice)\n}\n\nfunc (b *bytesSliceIter) Close() error {\n\tb.current = nil\n\tb.opts.BytesSliceArrayPool().Put(b.backingSlice)\n\treturn nil\n}\n\nfunc sortSliceOfByteSlices(b [][]byte) {\n\tsort.Slice(b, func(i, j int) bool {\n\t\treturn bytes.Compare(b[i], b[j]) < 0\n\t})\n}\n\nfunc (b *bytesSliceIter) Err() error ", "output": "{\n\treturn nil\n}"} {"input": "package trayicon\n\nimport (\n\t\"errors\"\n\n\t\"github.com/godbus/dbus\"\n\t\"github.com/linuxdeepin/go-lib/dbusutil\"\n\tx \"github.com/linuxdeepin/go-x11-client\"\n)\n\nconst (\n\tdbusServiceName = \"com.deepin.dde.TrayManager\"\n\tdbusInterface = dbusServiceName\n\tdbusPath = \"/com/deepin/dde/TrayManager\"\n)\n\nfunc (*TrayManager) GetInterfaceName() string {\n\treturn dbusInterface\n}\n\n\nfunc (m *TrayManager) Manage() (ok bool, busErr *dbus.Error) {\n\tlogger.Debug(\"call Manage by dbus\")\n\n\terr := m.sendClientMsgMANAGER()\n\tif err != nil {\n\t\tlogger.Warning(err)\n\t\treturn false, dbusutil.ToError(err)\n\t}\n\treturn true, nil\n}\n\n\nfunc (m *TrayManager) GetName(win uint32) (name string, busErr *dbus.Error) {\n\tm.mutex.Lock()\n\ticon, ok := m.icons[x.Window(win)]\n\tm.mutex.Unlock()\n\tif !ok {\n\t\treturn \"\", dbusutil.ToError(errors.New(\"icon not found\"))\n\t}\n\treturn icon.getName(), nil\n}\n\n\n\n\nfunc (m *TrayManager) EnableNotification(win uint32, enabled bool) *dbus.Error ", "output": "{\n\tm.mutex.Lock()\n\ticon, ok := m.icons[x.Window(win)]\n\tm.mutex.Unlock()\n\tif !ok {\n\t\treturn dbusutil.ToError(errors.New(\"icon not found\"))\n\t}\n\n\ticon.mu.Lock()\n\ticon.notify = enabled\n\ticon.mu.Unlock()\n\treturn nil\n}"} {"input": "package utils\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\tirc \"gopkg.in/irc.v3\"\n)\n\n\n\ntype TestClientServer struct {\n\tclient *bytes.Buffer\n\tserver *bytes.Buffer\n}\n\n\nfunc NewTestClientServer() *TestClientServer {\n\treturn &TestClientServer{\n\t\tclient: &bytes.Buffer{},\n\t\tserver: &bytes.Buffer{},\n\t}\n}\n\n\n\n\n\nfunc (cs *TestClientServer) Write(p []byte) (int, error) {\n\treturn cs.client.Write(p)\n}\n\n\n\nfunc (cs *TestClientServer) SendServerLines(lines []string) {\n\tw := irc.NewWriter(cs.server)\n\n\tfor _, line := range lines {\n\t\tw.WriteMessage(irc.MustParseMessage(line))\n\t}\n}\n\n\n\n\nfunc (cs *TestClientServer) CheckLines(t *testing.T, expected []string) bool {\n\tok := true\n\n\tlines := strings.Split(cs.client.String(), \"\\r\\n\")\n\n\tvar line, clientLine string\n\tfor len(expected) > 0 && len(lines) > 0 {\n\t\tline, expected = expected[0], expected[1:]\n\t\tclientLine, lines = lines[0], lines[1:]\n\n\t\tok = ok && assert.Equal(t, line, clientLine)\n\t}\n\n\tok = ok && assert.Equal(t, 0, len(expected), \"Not enough lines: %s\", strings.Join(expected, \", \"))\n\tok = ok && assert.Equal(t, 0, len(lines), \"Extra non-empty lines: %s\", strings.Join(lines, \", \"))\n\n\treturn ok\n}\n\n\nfunc (cs *TestClientServer) Reset() {\n\tcs.client.Reset()\n\tcs.server.Reset()\n}\n\nfunc (cs *TestClientServer) Read(p []byte) (int, error) ", "output": "{\n\treturn cs.server.Read(p)\n}"} {"input": "package iso20022\n\n\ntype RejectedElement1 struct {\n\n\tElementSequenceNumber *Number `xml:\"ElmtSeqNb\"`\n\n\tIndividualRejectionReason *Max140Text `xml:\"IndvRjctnRsn\"`\n}\n\nfunc (r *RejectedElement1) SetElementSequenceNumber(value string) {\n\tr.ElementSequenceNumber = (*Number)(&value)\n}\n\n\n\nfunc (r *RejectedElement1) SetIndividualRejectionReason(value string) ", "output": "{\n\tr.IndividualRejectionReason = (*Max140Text)(&value)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSGlueCrawler_Schedule struct {\n\n\tScheduleExpression string `json:\"ScheduleExpression,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSGlueCrawler_Schedule) AWSCloudFormationType() string {\n\treturn \"AWS::Glue::Crawler.Schedule\"\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\n\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSGlueCrawler_Schedule) SetMetadata(metadata map[string]interface{}) ", "output": "{\n\tr._metadata = metadata\n}"} {"input": "package v1alpha1\n\nimport (\n\t\"context\"\n\n\t\"k8s.io/apimachinery/pkg/api/equality\"\n\t\"knative.dev/pkg/apis\"\n\t\"knative.dev/serving/pkg/apis/serving\"\n)\n\n\n\n\n\nfunc (spec *ServerlessServiceSpec) Validate(ctx context.Context) *apis.FieldError {\n\tif equality.Semantic.DeepEqual(spec, &ServerlessServiceSpec{}) {\n\t\treturn apis.ErrMissingField(apis.CurrentField)\n\t}\n\tvar all *apis.FieldError\n\tswitch spec.Mode {\n\tcase SKSOperationModeProxy, SKSOperationModeServe:\n\t\tbreak\n\tcase \"\":\n\t\tall = all.Also(apis.ErrMissingField(\"mode\"))\n\tdefault:\n\t\tall = all.Also(apis.ErrInvalidValue(spec.Mode, \"mode\"))\n\t}\n\n\tif spec.NumActivators < 0 {\n\t\tall = all.Also(apis.ErrInvalidValue(spec.NumActivators, \"numActivators\"))\n\t}\n\n\tall = all.Also(serving.ValidateNamespacedObjectReference(&spec.ObjectRef).ViaField(\"objectRef\"))\n\n\treturn all.Also(spec.ProtocolType.Validate(ctx).ViaField(\"protocolType\"))\n}\n\nfunc (ci *ServerlessService) Validate(ctx context.Context) *apis.FieldError ", "output": "{\n\treturn ci.Spec.Validate(apis.WithinSpec(ctx)).ViaField(\"spec\")\n}"} {"input": "package locus\n\nimport (\n\t\"github.com/gocircuit/circuit/use/circuit\"\n)\n\nfunc init() {\n\tcircuit.RegisterValue(XLocus{})\n}\n\ntype XLocus struct {\n\tl *Locus\n}\n\nfunc (x XLocus) GetPeers() []*Peer {\n\treturn x.l.GetPeers()\n}\n\n\n\n\ntype YLocus struct {\n\tX circuit.PermX\n}\n\nfunc (y YLocus) GetPeers() map[string]*Peer {\n\tr := make(map[string]*Peer)\n\tfor _, p := range y.X.Call(\"GetPeers\")[0].([]*Peer) {\n\t\tr[p.Key()] = p\n\t}\n\treturn r\n}\n\nfunc (y YLocus) Self() *Peer {\n\treturn y.X.Call(\"Self\")[0].(*Peer)\n}\n\nfunc (x XLocus) Self() interface{} ", "output": "{\n\treturn x.l.Self()\n}"} {"input": "package tokens\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/client\"\n\t\"github.com/golang/glog\"\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/openshift/origin/pkg/auth/server/tokenrequest\"\n\tosclientcmd \"github.com/openshift/origin/pkg/cmd/util/clientcmd\"\n)\n\nconst (\n\tTokenRecommendedCommandName = \"tokens\"\n\tTOKEN_FILE_PARAM = \"token-file\"\n)\n\nfunc NewCmdTokens(name, fullName string, f *osclientcmd.Factory, out io.Writer) *cobra.Command {\n\tcmds := &cobra.Command{\n\t\tUse: name,\n\t\tShort: \"Manage authentication tokens\",\n\t\tLong: `Manage authentication tokens`,\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tc.SetOutput(os.Stdout)\n\t\t\tc.Help()\n\t\t},\n\t}\n\n\tcmds.AddCommand(NewCmdValidateToken(f))\n\tcmds.AddCommand(NewCmdRequestToken(f))\n\n\treturn cmds\n}\n\n\n\nfunc getRequestTokenURL(clientCfg *client.Config) string {\n\treturn clientCfg.Host + path.Join(\"/oauth\", tokenrequest.RequestTokenEndpoint)\n}\n\nfunc getFlagString(cmd *cobra.Command, flag string) string ", "output": "{\n\tf := cmd.Flags().Lookup(flag)\n\tif f == nil {\n\t\tglog.Fatalf(\"Flag accessed but not defined for command %s: %s\", cmd.Name(), flag)\n\t}\n\treturn f.Value.String()\n}"} {"input": "package schemareplication\n\nimport (\n\tcontext \"context\"\n\n\tv1beta1 \"github.com/rabbitmq/messaging-topology-operator/pkg/generated/informers/externalversions/rabbitmq.com/v1beta1\"\n\tfactory \"knative.dev/eventing-rabbitmq/pkg/client/injection/rabbitmq.com/informers/factory\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Default.RegisterInformer(withInformer)\n}\n\n\ntype Key struct{}\n\n\n\n\nfunc Get(ctx context.Context) v1beta1.SchemaReplicationInformer {\n\tuntyped := ctx.Value(Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch github.com/rabbitmq/messaging-topology-operator/pkg/generated/informers/externalversions/rabbitmq.com/v1beta1.SchemaReplicationInformer from context.\")\n\t}\n\treturn untyped.(v1beta1.SchemaReplicationInformer)\n}\n\nfunc withInformer(ctx context.Context) (context.Context, controller.Informer) ", "output": "{\n\tf := factory.Get(ctx)\n\tinf := f.Rabbitmq().V1beta1().SchemaReplications()\n\treturn context.WithValue(ctx, Key{}, inf), inf.Informer()\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/crackcell/asciitype/engine\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc showHelp() {\n\tfmt.Println(\"usage: asciifont -f [font file]\")\n}\n\n\n\nfunc convert(raw string, fb *engine.Framebuffer, st *engine.SymbolTable) {\n\tfb.Clear()\n\traw = strings.ToUpper(raw)\n\tfor _, r := range raw {\n\t\tfb.Append(st.GetSymbol(r))\n\t}\n\n\tfb.Flush(os.Stdout)\n}\n\nfunc main() {\n\th := flag.Bool(\"h\", false, \"show help messages\")\n\tf := flag.String(\"f\", \"./fonts/tukasans.afont\", \"specify font file\")\n\tflag.Parse()\n\tif *h {\n\t\tshowHelp()\n\t\treturn\n\t}\n\n\tst := new(engine.SymbolTable)\n\tst.Load(*f)\n\n\tfb := engine.NewFramebuffer()\n\n\treader := bufio.NewReader(os.Stdin)\n\n\tfor {\n\t\tline, err := reader.ReadString('\\n')\n\t\tline = strings.Trim(line, \"\\n\")\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tconvert(line, fb, st)\n\t}\n\n}\n\nfunc readStdin() ", "output": "{\n\treader := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tline, err := reader.ReadString('\\n')\n\t\tline = strings.Trim(line, \"\\n\")\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n}"} {"input": "package postactions\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/fragmenta/auth/can\"\n\t\"github.com/fragmenta/mux\"\n\t\"github.com/fragmenta/server\"\n\t\"github.com/fragmenta/view\"\n\n\t\"github.com/fragmenta/fragmenta-cms/src/lib/session\"\n\t\"github.com/fragmenta/fragmenta-cms/src/posts\"\n\t\"github.com/fragmenta/fragmenta-cms/src/users\"\n)\n\n\n\n\n\nfunc HandleUpdate(w http.ResponseWriter, r *http.Request) error {\n\n\tparams, err := mux.Params(r)\n\tif err != nil {\n\t\treturn server.InternalError(err)\n\t}\n\n\tpost, err := posts.Find(params.GetInt(posts.KeyName))\n\tif err != nil {\n\t\treturn server.NotFoundError(err)\n\t}\n\n\terr = session.CheckAuthenticity(w, r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuser := session.CurrentUser(w, r)\n\terr = can.Update(post, user)\n\tif err != nil {\n\t\treturn server.NotAuthorizedError(err)\n\t}\n\n\tpostParams := post.ValidateParams(params.Map(), posts.AllowedParams())\n\n\terr = post.Update(postParams)\n\tif err != nil {\n\t\treturn server.InternalError(err)\n\t}\n\n\treturn server.Redirect(w, r, post.ShowURL())\n}\n\nfunc HandleUpdateShow(w http.ResponseWriter, r *http.Request) error ", "output": "{\n\n\tparams, err := mux.Params(r)\n\tif err != nil {\n\t\treturn server.InternalError(err)\n\t}\n\n\tpost, err := posts.Find(params.GetInt(posts.KeyName))\n\tif err != nil {\n\t\treturn server.NotFoundError(err)\n\t}\n\n\tuser := session.CurrentUser(w, r)\n\terr = can.Update(post, user)\n\tif err != nil {\n\t\treturn server.NotAuthorizedError(err)\n\t}\n\n\tauthors, err := users.FindAll(users.Where(\"role=?\", users.Admin))\n\tif err != nil {\n\t\treturn server.InternalError(err)\n\t}\n\n\tview := view.NewRenderer(w, r)\n\tview.AddKey(\"currentUser\", user)\n\tview.AddKey(\"post\", post)\n\tview.AddKey(\"authors\", authors)\n\treturn view.Render()\n}"} {"input": "package main\n\n\n\ntype Hub struct {\n\tname string\n\tclients map[*Client]bool\n\tbroadcast chan []byte\n\tregister chan *Client\n\tunregister chan *Client\n}\n\nvar hubs map[*Hub]bool\nvar globalLobby *Hub\n\nfunc initHubs() {\n\thubs = make(map[*Hub]bool)\n\tglobalLobby = newHub(\"Global\")\n\tgo globalLobby.run()\n}\n\nfunc newHub(name string) *Hub {\n\tnh := &Hub{\n\t\tname: name,\n\t\tbroadcast: make(chan []byte),\n\t\tregister: make(chan *Client),\n\t\tunregister: make(chan *Client),\n\t\tclients: make(map[*Client]bool),\n\t}\n\n\thubs[nh] = true\n\n\treturn nh\n}\n\nfunc findHubNamed(name string) *Hub {\n\tfor h := range hubs {\n\t\tif h.name == name {\n\t\t\treturn h\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\nfunc (h *Hub) run() ", "output": "{\n\tfor {\n\t\tselect {\n\t\tcase client := <-h.register:\n\t\t\th.clients[client] = true\n\t\tcase client := <-h.unregister:\n\t\t\tif _, ok := h.clients[client]; ok {\n\t\t\t\tdelete(h.clients, client)\n\t\t\t}\n\t\tcase message := <-h.broadcast:\n\t\t\tfor client := range h.clients {\n\t\t\t\tselect {\n\t\t\t\tcase client.send <- message:\n\t\t\t\tdefault:\n\t\t\t\t\tclose(client.send)\n\t\t\t\t\tdelete(h.clients, client)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package adman\n\nimport (\n\t\"testing\"\n\n\t\"github.com/prebid/prebid-server/adapters/adapterstest\"\n\t\"github.com/prebid/prebid-server/config\"\n\t\"github.com/prebid/prebid-server/openrtb_ext\"\n)\n\n\n\nfunc TestJsonSamples(t *testing.T) ", "output": "{\n\tbidder, buildErr := Builder(openrtb_ext.BidderAdman, config.Adapter{\n\t\tEndpoint: \"http://pub.admanmedia.com/?c=o&m=ortb\"})\n\n\tif buildErr != nil {\n\t\tt.Fatalf(\"Builder returned unexpected error %v\", buildErr)\n\t}\n\n\tadapterstest.RunJSONBidderTest(t, \"admantest\", bidder)\n}"} {"input": "package probe\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/FirebaseExtended/fcm-external-prober/Probe/src/utils\"\n)\n\n\n\nfunc TestConvertTimeExpected(t *testing.T) {\n\ttim, err := convertTime(\"123.456000\")\n\tif err != nil {\n\t\tt.Logf(\"TestConvertTimeExpected: returned error on valid input: %v\", err)\n\t\tt.FailNow()\n\t}\n\texpected := time.Unix(123, 456000000)\n\tif !tim.Equal(expected) {\n\t\tt.Logf(\"TestConvertTimeExpected: incorrect time returned: actual: %v, expected %v\", tim, expected)\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestConvertTimeError(t *testing.T) {\n\t_, err := convertTime(\"1.1.1.1\")\n\tif err == nil {\n\t\tt.Logf(\"TestConvertTimeExpected: no error returned on invalid input\")\n\t\tt.Fail()\n\t}\n}\n\nfunc TestFindTimeOffset(t *testing.T) {\n\tclock = utils.NewFakeClock([]time.Time{time.Unix(0, 0), time.Unix(1, 0)}, false)\n\tmaker = utils.NewFakeCommandMaker([]string{\"000.500000\"}, []bool{false}, false)\n\toffset, err := findTimeOffset()\n\tif err != nil {\n\t\tt.Logf(\"TestFindTimeOffset: error returned on valid input: %v\", err)\n\t\tt.FailNow()\n\t}\n\tif offset != 0 {\n\t\tt.Logf(\"TestFindTimeOffset: incorrect time offset: actual: %d, expected: 0\", offset)\n\t\tt.Fail()\n\t}\n}\n\nfunc TestFindDevice(t *testing.T) ", "output": "{\n\tmaker = utils.NewFakeCommandMaker([]string{\"TEST_DEVICE_1\\nTEST_DEVICE_2\\nTEST_DEVICE_3\"}, []bool{false}, false)\n\n\tstr, err := findDevice()\n\n\tif err != nil {\n\t\tt.Log(\"TestFindDevice: error on valid input\")\n\t\tt.Fail()\n\t}\n\tif str != \"TEST_DEVICE_1\" {\n\t\tt.Log(\"TestFindDevice: incorrect device found\")\n\t\tt.Fail()\n\t}\n}"} {"input": "package docker_registry\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\tneturl \"net/url\"\n\t\"path\"\n)\n\ntype harborApi struct{}\n\n\n\nfunc (api *harborApi) DeleteRepository(ctx context.Context, hostname, repository, username, password string) (*http.Response, error) {\n\tu, err := neturl.Parse(\"https://\" + hostname + \"/api\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu.Path = path.Join(u.Path, \"repositories\", repository)\n\turl := u.String()\n\n\tresp, _, err := doRequest(ctx, http.MethodDelete, url, nil, doRequestOptions{\n\t\tHeaders: map[string]string{\n\t\t\t\"Accept\": \"application/json\",\n\t\t},\n\t\tBasicAuth: doRequestBasicAuth{\n\t\t\tusername: username,\n\t\t\tpassword: password,\n\t\t},\n\t\tAcceptedCodes: []int{http.StatusOK, http.StatusAccepted},\n\t})\n\n\treturn resp, err\n}\n\nfunc newHarborApi() harborApi ", "output": "{\n\treturn harborApi{}\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"io\"\n\t\"net/http\"\n)\n\n\ntype HTTPClient struct {\n}\n\n\ntype HTTPOperations interface {\n\tGet(url string) ([]byte, error)\n}\n\n\n\n\nfunc (that *HTTPClient) Get(url string) ([]byte, error) ", "output": "{\n\tresp, err := http.Get(url)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar body bytes.Buffer\n\twriter := bufio.NewWriter(&body)\n\n\tdefer resp.Body.Close()\n\t_, err = io.Copy(writer, resp.Body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn body.Bytes(), err\n}"} {"input": "package v1alpha1\n\nimport (\n\tv1alpha1 \"k8s.io/api/scheduling/v1alpha1\"\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\t\"github.com/hyperhq/client-go/kubernetes/scheme\"\n\trest \"github.com/hyperhq/client-go/rest\"\n)\n\ntype SchedulingV1alpha1Interface interface {\n\tRESTClient() rest.Interface\n\tPriorityClassesGetter\n}\n\n\ntype SchedulingV1alpha1Client struct {\n\trestClient rest.Interface\n}\n\n\n\n\nfunc NewForConfig(c *rest.Config) (*SchedulingV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SchedulingV1alpha1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *SchedulingV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *SchedulingV1alpha1Client {\n\treturn &SchedulingV1alpha1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *SchedulingV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc (c *SchedulingV1alpha1Client) PriorityClasses() PriorityClassInterface ", "output": "{\n\treturn newPriorityClasses(c)\n}"} {"input": "package pointer\n\nimport \"time\"\n\n\n\nfunc DefaultDuration(value *time.Duration, defaultValue time.Duration) *time.Duration {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultFloat64(value *float64, defaultValue float64) *float64 {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultInt(value *int, defaultValue int) *int {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultString(value *string, defaultValue string) *string {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultStringArray(value *[]string, defaultValue []string) *[]string {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultTime(value *time.Time, defaultValue time.Time) *time.Time {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultBool(value *bool, defaultValue bool) *bool ", "output": "{\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}"} {"input": "package turtle\n\nimport (\n\t\"strings\"\n)\n\ntype DataSet struct {\n\ttriplecount int\n\tnscount int\n\tNamespaces map[string]string\n\tTriples []Triple\n}\n\nfunc newDataSet() *DataSet {\n\treturn &DataSet{\n\t\ttriplecount: 0,\n\t\tnscount: 0,\n\t\tNamespaces: make(map[string]string),\n\t\tTriples: []Triple{},\n\t}\n}\n\nfunc (d *DataSet) AddTripleStrings(subject, predicate, object string) {\n\td.triplecount += 1\n\td.Triples = append(d.Triples, MakeTriple(subject, predicate, object))\n}\n\n\n\nfunc (d *DataSet) addNamespace(prefix, namespace string) {\n\td.nscount += 1\n\tnamespace = strings.TrimRight(namespace, \"#\")\n\td.Namespaces[prefix] = namespace\n}\n\nfunc (d *DataSet) NumTriples() int {\n\treturn d.triplecount\n}\n\nfunc (d *DataSet) NumNamespaces() int {\n\treturn d.nscount\n}\n\nfunc (d *DataSet) AddTripleURIs(subject, predicate, object URI) ", "output": "{\n\td.triplecount += 1\n\td.Triples = append(d.Triples, Triple{subject, predicate, object})\n}"} {"input": "package wire\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\n\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc newFixedWriter(max int) io.Writer ", "output": "{\n\tb := make([]byte, max, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}"} {"input": "package oleacc\n\nimport (\n\t\"unsafe\"\n\n\t\"github.com/go-ole/go-ole\"\n)\n\ntype IUIAutomationEventHandler struct {\n\tole.IUnknown\n}\n\ntype IUIAutomationEventHandlerVtbl struct {\n\tole.IUnknownVtbl\n\tHandleAutomationEvent uintptr\n}\n\nfunc (v *IUIAutomationEventHandler) VTable() *IUIAutomationEventHandlerVtbl {\n\treturn (*IUIAutomationEventHandlerVtbl)(unsafe.Pointer(v.RawVTable))\n}\n\n\n\nfunc (v *IUIAutomationEventHandler) HandleAutomationEvent() error ", "output": "{\n\treturn ole.NewError(ole.E_NOTIMPL)\n}"} {"input": "package goparser\n\nimport (\n\t\"strings\"\n)\n\nfunc isExceptedStatement(name string, prefixs, suffixs, fullnames []string) bool {\n\tname = strings.ToLower(name)\n\tfor _, prefix := range prefixs {\n\t\tif strings.HasPrefix(name, prefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tfor _, suffix := range suffixs {\n\t\tif strings.HasSuffix(name, suffix) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, fullname := range fullnames {\n\t\tif name == fullname {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc isInsertStatement(name string) bool {\n\treturn isExceptedStatement(name, []string{\n\t\t\"insert\",\n\t\t\"upsert\",\n\t\t\"add\",\n\t\t\"create\",\n\t}, nil, nil)\n}\n\nfunc isUpdateStatement(name string) bool {\n\treturn isExceptedStatement(name, []string{\n\t\t\"set\",\n\t\t\"update\",\n\t}, nil, nil)\n}\nfunc isDeleteStatement(name string) bool {\n\treturn isExceptedStatement(name, []string{\n\t\t\"delete\",\n\t\t\"remove\",\n\t\t\"clear\",\n\t}, nil, nil)\n}\n\n\nfunc isSelectStatement(name string) bool ", "output": "{\n\treturn isExceptedStatement(name, []string{\n\t\t\"select\",\n\t\t\"find\",\n\t\t\"get\",\n\t\t\"query\",\n\t\t\"list\",\n\t\t\"count\",\n\t\t\"read\",\n\t\t\"statby\",\n\t\t\"statsby\",\n\t}, []string{\"count\"}, []string{\"id\", \"all\", \"names\", \"titles\"})\n}"} {"input": "package main\n\nimport (\n \"time\"\n \"net/http\"\n \"io/ioutil\"\n \"strings\"\n\n \"launchpad.net/gocheck\"\n \"github.com/mreiferson/go-httpclient\"\n)\n\nconst url string = \"http://127.0.0.1:8080\"\n\nfunc setupHivy() {\n \n go hivy(url, false)\n}\n\n\n\nfunc (t *testSuite) TestHivyDummy() {\n resp, err := sendHTTPRequest(\"GET\", \"/dummy\", \"xav\", \"boss\")\n defer resp.Body.Close()\n t.Check(err, gocheck.IsNil)\n\n contents, err := ioutil.ReadAll(resp.Body)\n t.Check(err, gocheck.IsNil)\n\n t.True(strings.Contains(string(contents), \"dummy\"))\n \n}\n\nfunc (t *testSuite) TestBadAuthentification() {\n resp, err := sendHTTPRequest(\"GET\", \"/dummy\", \"wrong\", \"login\")\n defer resp.Body.Close()\n t.Check(err, gocheck.IsNil)\n\n contents, err := ioutil.ReadAll(resp.Body)\n t.Check(err, gocheck.IsNil)\n\n t.True(strings.Contains(string(contents), \"Key Not Found\"))\n \n}\n\nfunc sendHTTPRequest(method, endpoint, user, pass string) (*http.Response, error)", "output": "{\n transport := &httpclient.Transport{\n ConnectTimeout: 1*time.Second,\n RequestTimeout: 10*time.Second,\n ResponseHeaderTimeout: 5*time.Second,\n }\n defer transport.Close()\n\n client := &http.Client{Transport: transport}\n prefix := \"/v0/actions\"\n req, _ := http.NewRequest(method, url + prefix + endpoint, nil)\n req.SetBasicAuth(user, pass)\n\n \n return client.Do(req)\n}"} {"input": "package fake\n\nimport (\n\tv1alpha1 \"github.com/appscode/searchlight/client/clientset/versioned/typed/incidents/v1alpha1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeIncidentsV1alpha1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeIncidentsV1alpha1) Acknowledgements(namespace string) v1alpha1.AcknowledgementInterface {\n\treturn &FakeAcknowledgements{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeIncidentsV1alpha1) RESTClient() rest.Interface ", "output": "{\n\tvar ret *rest.RESTClient\n\treturn ret\n}"} {"input": "package config\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/BurntSushi/toml\"\n)\n\ntype Config struct {\n\tWeb *WebConfig `toml:\"web\"`\n\tBot *BotConfig `toml:\"bot\"`\n}\n\ntype BotConfig struct {\n\tChannelId int `toml:\"channel_id\"`\n\tChannelSecret string `toml:\"channel_secret\"`\n\tMID string `toml:\"channel_mid\"`\n\tClientWorkerQueueSize int `toml:\"client_worker_queue_size\"`\n\tEventDispatcherQueueSize int `toml:\"event_dispatcher_queue_size\"`\n}\n\ntype WebConfig struct {\n\tHost string `toml:\"host\"`\n\tPort int `toml:\"port\"`\n}\n\n\n\nfunc LoadFromFile(filePath string) *Config {\n\tvar c Config\n\tif _, err := toml.DecodeFile(filePath, &c); err != nil {\n\t\tlog.Fatalf(\"Failed to read config file: %s\", err.Error())\n\t}\n\treturn &c\n}\n\nfunc (wc *WebConfig) Address() string ", "output": "{\n\treturn fmt.Sprintf(\"%s:%d\", wc.Host, wc.Port)\n}"} {"input": "package iso20022\n\n\n\ntype RejectionReason26 struct {\n\n\tCode *RejectionReason24Choice `xml:\"Cd\"`\n\n\tAdditionalReasonInformation *Max210Text `xml:\"AddtlRsnInf,omitempty\"`\n}\n\nfunc (r *RejectionReason26) AddCode() *RejectionReason24Choice {\n\tr.Code = new(RejectionReason24Choice)\n\treturn r.Code\n}\n\n\n\nfunc (r *RejectionReason26) SetAdditionalReasonInformation(value string) ", "output": "{\n\tr.AdditionalReasonInformation = (*Max210Text)(&value)\n}"} {"input": "package writer\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\nconst (\n\tdefaultFlexibleWriterSize = 64\n)\n\ntype FlexibleWriter struct {\n\t*bytes.Buffer\n\twriter io.Writer\n}\n\nfunc NewFlexibleWriter(writer io.Writer) *FlexibleWriter {\n\tw := &FlexibleWriter{}\n\tw.writer = writer\n\tbuf := make([]byte, 0, defaultFlexibleWriterSize)\n\tw.Buffer = bytes.NewBuffer(buf)\n\treturn w\n}\n\nfunc (this *FlexibleWriter) Flush() (err error) {\n\t_, err = this.Buffer.WriteTo(this.writer)\n\n\treturn\n}\n\n\n\nfunc (this *FlexibleWriter) Buffered() int ", "output": "{\n\treturn this.Len()\n}"} {"input": "package policy\n\nimport \"github.com/cilium/cilium/common\"\n\n\n\n\nfunc JoinPath(a, b string) string ", "output": "{\n\treturn a + common.PathDelimiter + b\n}"} {"input": "package containerregistry\n\nimport (\n\t\"context\"\n\n\t\"github.com/sacloud/libsacloud/v2/helper/service\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n)\n\nfunc (s *Service) Delete(req *DeleteRequest) error {\n\treturn s.DeleteWithContext(context.Background(), req)\n}\n\n\n\nfunc (s *Service) DeleteWithContext(ctx context.Context, req *DeleteRequest) error ", "output": "{\n\tif err := req.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tclient := sacloud.NewContainerRegistryOp(s.caller)\n\tif err := client.Delete(ctx, req.ID); err != nil {\n\t\treturn service.HandleNotFoundError(err, !req.FailIfNotFound)\n\t}\n\treturn nil\n}"} {"input": "package esbuilder\n\nimport \"github.com/serulian/compiler/sourcemap\"\n\n\ntype StatementBuilder interface {\n\tWithMapping(mapping sourcemap.SourceMapping) SourceBuilder\n\n\tmapping() (sourcemap.SourceMapping, bool)\n\n\temitSource(sb *sourceBuilder)\n}\n\n\ntype statementNode interface {\n\temit(sb *sourceBuilder)\n}\n\n\ntype statementBuilder struct {\n\tstatement statementNode\n\n\tsourceMapping *sourcemap.SourceMapping\n}\n\n\n\nfunc (builder statementBuilder) emitSource(sb *sourceBuilder) {\n\tbuilder.statement.emit(sb)\n}\n\n\nfunc (builder statementBuilder) WithMapping(mapping sourcemap.SourceMapping) SourceBuilder {\n\tbuilder.sourceMapping = &mapping\n\treturn builder\n}\n\nfunc (builder statementBuilder) mapping() (sourcemap.SourceMapping, bool) ", "output": "{\n\tif builder.sourceMapping == nil {\n\t\treturn sourcemap.SourceMapping{}, false\n\t}\n\n\treturn *builder.sourceMapping, true\n}"} {"input": "package zip\n\nimport (\n\t\"bytes\"\n\t\"compress/zlib\"\n\t\"io/ioutil\"\n)\n\n\n\n\n\nfunc Inflate(b []byte) ([]byte, error) {\n\tbuf := bytes.NewBuffer(b)\n\tr, err := zlib.NewReader(buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Close()\n\treturn ioutil.ReadAll(r)\n}\n\nfunc Deflate(b []byte) ([]byte, error) ", "output": "{\n\tr := bytes.Buffer{}\n\tw := zlib.NewWriter(&r)\n\t_, err := w.Write(b)\n\tw.Close()\n\tif err == nil {\n\t\treturn r.Bytes(), nil\n\t}\n\treturn nil, err\n}"} {"input": "package version\n\n\n\nfunc init() ", "output": "{\n\tVersion = \"0.10.3\"\n\n\tVersionPrerelease = \"\"\n}"} {"input": "package swt\n\nimport \"github.com/timob/javabind\"\nimport \"unsafe\"\n\n\n\nimport \"C\"\n\n\n\nvar EventsMenuDetectListenerNativeMap = make(map[int]EventsMenuDetectListenerInterface)\n\ntype EventsMenuDetectListenerNative struct {\n\t*javabind.Callable\n\tEventsMenuDetectListenerInterface\n}\n\nfunc NewEventsMenuDetectListenerNative(implementation EventsMenuDetectListenerInterface) *EventsMenuDetectListenerNative {\n\n\tobj, err := javabind.GetEnv().NewObject(\"org/eclipse/swt/events/MenuDetectListenerNative\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tx := &EventsMenuDetectListenerNative{}\n\tx.Callable = &javabind.Callable{obj}\n\n hash, err := x.Callable.CallMethod(javabind.GetEnv(), \"hashCode\", javabind.Int)\n if err != nil {\n panic(err)\n }\n EventsMenuDetectListenerNativeMap[hash.(int)] = implementation\n\treturn x\n}\n\n\n func init() {\n javabind.OnJVMStart(func() {\n javabind.GetEnv().RegisterNative(\"org/eclipse/swt/events/MenuDetectListenerNative\", \"menuDetected\", javabind.Void, []interface{}{\"org/eclipse/swt/events/MenuDetectEvent\"}, C.go_callback_EventsMenuDetectListenerNative_MenuDetected)\n\n })\n }\n\nfunc go_callback_EventsMenuDetectListenerNative_MenuDetected(env unsafe.Pointer, obj uintptr, arg_0 uintptr) ", "output": "{\n rObj := &javabind.Callable{javabind.WrapJObject(obj, \"org/eclipse/swt/events/MenuDetectListenerNative\", false)}\n hash, err := rObj.CallMethod(javabind.GetEnv(), \"hashCode\", javabind.Int)\n if err != nil {\n panic(err)\n }\n\n i := EventsMenuDetectListenerNativeMap[hash.(int)]\n \tretcon_a := javabind.NewJavaToGoCallable()\n\tdst_a := &javabind.Callable{}\n\tretcon_a.Dest(dst_a)\n\tif err := retcon_a.Convert(javabind.WrapJObject(arg_0, \"org/eclipse/swt/events/MenuDetectEvent\", false)); err != nil {\n\t\tpanic(err)\n\t}\n\targ_a := &EventsMenuDetectEvent{}\n\targ_a.Callable = dst_a\ni.MenuDetected(arg_a)\n}"} {"input": "package sdk\n\nimport (\n\t\"io/ioutil\"\n\t\"net/url\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\ntype hydraConfig struct {\n\tClusterURL string `yaml:\"cluster_url\"`\n\tClientID string `yaml:\"client_id\"`\n\tClientSecret string `yaml:\"client_secret\"`\n}\n\n\nfunc FromYAML(file string) option {\n\treturn func(c *Client) error {\n\t\tvar err error\n\t\tvar config = hydraConfig{}\n\n\t\tdata, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = yaml.Unmarshal(data, &config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.clusterURL, err = url.Parse(config.ClusterURL)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.clientID = config.ClientID\n\t\tc.clientSecret = config.ClientSecret\n\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc ClusterURL(urlStr string) option {\n\treturn func(c *Client) error {\n\t\tvar err error\n\t\tc.clusterURL, err = url.Parse(urlStr)\n\t\treturn err\n\t}\n}\n\n\n\n\n\n\n\nfunc ClientID(id string) option {\n\treturn func(c *Client) error {\n\t\tc.clientID = id\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc SkipTLSVerify() option {\n\treturn func(c *Client) error {\n\t\tc.skipTLSVerify = true\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc Scopes(scopes ...string) option {\n\treturn func(c *Client) error {\n\t\tc.scopes = scopes\n\t\treturn nil\n\t}\n}\n\nfunc ClientSecret(secret string) option ", "output": "{\n\treturn func(c *Client) error {\n\t\tc.clientSecret = secret\n\t\treturn nil\n\t}\n}"} {"input": "package templar\n\nimport \"github.com/stretchr/testify/mock\"\n\nimport \"net/http\"\nimport \"time\"\n\ntype MockStats struct {\n\tmock.Mock\n}\n\nfunc (m *MockStats) StartRequest(req *http.Request) {\n\tm.Called(req)\n}\n\nfunc (m *MockStats) RequestTimeout(req *http.Request, timeout time.Duration) {\n\tm.Called(req, timeout)\n}\n\nfunc (m *MockStats) Emit(req *http.Request, dur time.Duration) ", "output": "{\n\tm.Called(req, dur)\n}"} {"input": "package archive\n\nimport (\n\t\"archive/tar\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/docker/docker/pkg/longpath\"\n)\n\n\n\nfunc fixVolumePathPrefix(srcPath string) string {\n\treturn longpath.AddPrefix(srcPath)\n}\n\n\n\nfunc getWalkRoot(srcPath string, include string) string {\n\treturn filepath.Join(srcPath, include)\n}\n\n\n\n\nfunc CanonicalTarNameForPath(p string) (string, error) {\n\tif strings.Contains(p, \"/\") {\n\t\treturn \"\", fmt.Errorf(\"Windows path contains forward slash: %s\", p)\n\t}\n\treturn strings.Replace(p, string(os.PathSeparator), \"/\", -1), nil\n\n}\n\n\n\nfunc chmodTarEntry(perm os.FileMode) os.FileMode {\n\tperm &= 0755\n\tperm |= 0111\n\n\treturn perm\n}\n\n\n\n\n\nfunc handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error {\n\treturn nil\n}\n\nfunc handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error {\n\treturn nil\n}\n\nfunc getFileUIDGID(stat interface{}) (int, int, error) {\n\treturn 0, 0, nil\n}\n\nfunc setHeaderForSpecialDevice(hdr *tar.Header, ta *tarAppender, name string, stat interface{}) (nlink uint32, inode uint64, err error) ", "output": "{\n\treturn\n}"} {"input": "package UserManager\n\nimport \"testing\"\nimport \"github.com/stretchr/testify/assert\"\n\n\nfunc TestGenerateHash(t *testing.T) {\n\thash, salt := generatePasswordHash(\"MeinPasswort\")\n\thash2, salt2 := generatePasswordHash(\"MeinPasswort\")\n\tassert.NotEqual(t, hash, hash2, \"Error, Two Hashes of the same Passwort are identical\")\n\tassert.NotEqual(t, salt, salt2, \"Error, Two Runs of generate hash returned the same Salt\")\n}\n\n\n\n\nfunc TestVerifyUser(t *testing.T) {\n\n\n}\n\nfunc TestVerifyHash(t *testing.T) ", "output": "{\n\tvar v bool\n\tv = verifyPasswordHash(\"Psw\", \"ABC\", \"25928498b28c3268d911dd78d7ff820e0f14ed32b7ac2d397746f1778038b968d9e6364fd4b3da2e7026bdf574c104779fac9ce9064b6b9ae09ac043f8d131d4\")\n\tif !v {\n\t\tt.Error(\"Expected true , got \", v)\n\t}\n}"} {"input": "package conv\n\nimport (\n\t\"reflect\"\n)\n\nfunc IntPtrTo64(ptr interface{}) (value int64) {\n\tif v := reflect.ValueOf(ptr); v.Kind() == reflect.Ptr {\n\t\tp := v.Elem()\n\t\tswitch p.Kind() {\n\t\tcase reflect.Int:\n\t\t\tvalue = int64(*ptr.(*int))\n\t\tcase reflect.Int8:\n\t\t\tvalue = int64(*ptr.(*int8))\n\t\tcase reflect.Int16:\n\t\t\tvalue = int64(*ptr.(*int16))\n\t\tcase reflect.Int32:\n\t\t\tvalue = int64(*ptr.(*int32))\n\t\tcase reflect.Int64:\n\t\t\tvalue = *ptr.(*int64)\n\t\t}\n\t}\n\treturn\n}\n\n\n\nfunc UintPtrTo64(ptr interface{}) (value uint64) ", "output": "{\n\tif v := reflect.ValueOf(ptr); v.Kind() == reflect.Ptr {\n\t\tp := v.Elem()\n\t\tswitch p.Kind() {\n\t\tcase reflect.Uint:\n\t\t\tvalue = uint64(*ptr.(*uint))\n\t\tcase reflect.Uint8:\n\t\t\tvalue = uint64(*ptr.(*uint8))\n\t\tcase reflect.Uint16:\n\t\t\tvalue = uint64(*ptr.(*uint16))\n\t\tcase reflect.Uint32:\n\t\t\tvalue = uint64(*ptr.(*uint32))\n\t\tcase reflect.Uint64:\n\t\t\tvalue = *ptr.(*uint64)\n\t\t}\n\t}\n\treturn\n}"} {"input": "package sacloud\n\n\ntype propInterfaceDriver struct {\n\tInterfaceDriver EInterfaceDriver `json:\",omitempty\"` \n}\n\n\nfunc (p *propInterfaceDriver) SetInterfaceDriver(v EInterfaceDriver) {\n\tp.InterfaceDriver = v\n}\n\n\n\n\n\nfunc (p *propInterfaceDriver) SetInterfaceDriverByString(v string) {\n\tp.InterfaceDriver = EInterfaceDriver(v)\n}\n\n\nfunc (p *propInterfaceDriver) GetInterfaceDriverString() string {\n\treturn string(p.InterfaceDriver)\n}\n\nfunc (p *propInterfaceDriver) GetInterfaceDriver() EInterfaceDriver ", "output": "{\n\treturn p.InterfaceDriver\n}"} {"input": "package container\n\nimport (\n\t\"fmt\"\n\t\"github.com/bunbunjp/gotop/dataservice/memory\"\n\t\"github.com/bunbunjp/gotop/util\"\n\t\"github.com/gizak/termui\"\n)\n\n\ntype VirtualMemoryUsageContainer struct {\n\tvirtualGauge *termui.Gauge\n}\n\n\nfunc (v *VirtualMemoryUsageContainer) Initialize() {\n}\n\n\nfunc (v *VirtualMemoryUsageContainer) UpdateRender() {\n\tdata := memory.GetInstance()\n\n\tv.virtualGauge.Percent = int(data.LatestVirtualStat.UsedPercent)\n\tv.virtualGauge.BorderLabel = fmt.Sprintf(\"virtual usage (%.2fGB/%.2fGB)\",\n\t\tutil.Byte2GBi(data.LatestVirtualStat.Used),\n\t\tutil.Byte2GBi(data.LatestVirtualStat.Total))\n}\n\n\n\n\nfunc (v *VirtualMemoryUsageContainer) CreateUI() termui.GridBufferer ", "output": "{\n\n\tv.virtualGauge = termui.NewGauge()\n\tv.virtualGauge.Width = termui.TermWidth() / 4\n\tv.virtualGauge.Height = 10\n\tv.virtualGauge.LabelAlign = termui.AlignRight\n\n\treturn v.virtualGauge\n}"} {"input": "package core\n\nimport (\n\t\"github.com/google/blueprint\"\n)\n\ntype generateBinary struct {\n\tgenerateLibrary\n}\n\n\nvar _ generateLibraryInterface = (*generateBinary)(nil)\nvar _ singleOutputModule = (*generateBinary)(nil)\nvar _ splittable = (*generateBinary)(nil)\nvar _ blueprint.Module = (*generateBinary)(nil)\n\nfunc (m *generateBinary) generateInouts(ctx blueprint.ModuleContext, g generatorBackend) []inout {\n\treturn generateLibraryInouts(m, ctx, g, m.Properties.Headers)\n}\n\n\n\nfunc (m *generateBinary) libExtension() string {\n\treturn \"\"\n}\n\n\n\nfunc (m *generateBinary) outputFileName() string {\n\treturn m.altName() + m.libExtension()\n}\n\n\n\n\n\n\n\nfunc genBinaryFactory(config *bobConfig) (blueprint.Module, []interface{}) {\n\tmodule := &generateBinary{}\n\tmodule.generateCommon.init(&config.Properties, GenerateProps{})\n\n\treturn module, []interface{}{\n\t\t&module.SimpleName.Properties,\n\t\t&module.generateCommon.Properties,\n\t\t&module.Properties,\n\t}\n}\n\nfunc (m *generateBinary) GenerateBuildActions(ctx blueprint.ModuleContext) ", "output": "{\n\tif isEnabled(m) {\n\t\tg := getBackend(ctx)\n\t\tg.genBinaryActions(m, ctx)\n\t}\n}"} {"input": "package shell\n\n\n\n\nfunc SetupRawTerminal(setSize func(cols, row uint16) error) func() ", "output": "{\n\tif setSize != nil {\n\t\tsetSize(80, 20)\n\t}\n\treturn func() {}\n}"} {"input": "package api\n\nimport \"testing\"\n\n\n\nfunc assertWriteMeta(t *testing.T, wm *WriteMeta) {\n\tif wm.LastIndex == 0 {\n\t\tt.Fatalf(\"bad index: %d\", wm.LastIndex)\n\t}\n}\n\nfunc testJob() *Job {\n\ttask := NewTask(\"task1\", \"exec\").\n\t\tSetConfig(\"command\", \"/bin/sleep\").\n\t\tRequire(&Resources{\n\t\t\tCPU: 100,\n\t\t\tMemoryMB: 256,\n\t\t\tIOPS: 10,\n\t\t}).\n\t\tSetLogConfig(&LogConfig{\n\t\t\tMaxFiles: 1,\n\t\t\tMaxFileSizeMB: 2,\n\t\t})\n\n\tgroup := NewTaskGroup(\"group1\", 1).\n\t\tAddTask(task).\n\t\tRequireDisk(&EphemeralDisk{\n\t\t\tSizeMB: 25,\n\t\t})\n\n\tjob := NewBatchJob(\"job1\", \"redis\", \"region1\", 1).\n\t\tAddDatacenter(\"dc1\").\n\t\tAddTaskGroup(group)\n\n\treturn job\n}\n\nfunc testPeriodicJob() *Job {\n\tjob := testJob().AddPeriodicConfig(&PeriodicConfig{\n\t\tEnabled: true,\n\t\tSpec: \"*/30 * * * *\",\n\t\tSpecType: \"cron\",\n\t})\n\treturn job\n}\n\nfunc assertQueryMeta(t *testing.T, qm *QueryMeta) ", "output": "{\n\tif qm.LastIndex == 0 {\n\t\tt.Fatalf(\"bad index: %d\", qm.LastIndex)\n\t}\n\tif !qm.KnownLeader {\n\t\tt.Fatalf(\"expected known leader, got none\")\n\t}\n}"} {"input": "package metha\n\nimport (\n\t\"encoding/base64\"\n\t\"io/ioutil\"\n\t\"strings\"\n)\n\n\ntype Repository struct {\n\tBaseURL string\n}\n\n\n\n\n\nfunc (r Repository) Sets() ([]Set, error) {\n\tvar sets []Set\n\tvar token string\n\tfor {\n\t\treq := Request{BaseURL: r.BaseURL, Verb: \"ListSets\", ResumptionToken: token}\n\t\tresp, err := Do(&req)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsets = append(sets, resp.ListSets.Set...)\n\t\tif !resp.HasResumptionToken() {\n\t\t\tbreak\n\t\t}\n\t\ttoken = resp.GetResumptionToken()\n\t}\n\treturn sets, nil\n}\n\n\n\nfunc FindRepositoriesByString(s string) (urls []string, err error) {\n\tfiles, err := ioutil.ReadDir(BaseDir)\n\tif err != nil {\n\t\treturn urls, err\n\t}\n\tfor _, file := range files {\n\t\tb, err := base64.RawURLEncoding.DecodeString(file.Name())\n\t\tif err != nil {\n\t\t\treturn urls, err\n\t\t}\n\t\tparts := strings.SplitN(string(b), \"#\", 3)\n\t\tif len(parts) < 3 {\n\t\t\tcontinue\n\t\t}\n\t\tbaseURL := parts[2]\n\t\tif strings.Contains(baseURL, s) {\n\t\t\turls = append(urls, baseURL)\n\t\t}\n\t}\n\treturn urls, nil\n}\n\nfunc (r Repository) Formats() ([]MetadataFormat, error) ", "output": "{\n\tvar formats []MetadataFormat\n\tvar token string\n\tfor {\n\t\treq := Request{BaseURL: r.BaseURL, Verb: \"ListMetadataFormats\", ResumptionToken: token}\n\t\tresp, err := Do(&req)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tformats = append(formats, resp.ListMetadataFormats.MetadataFormat...)\n\t\tif !resp.HasResumptionToken() {\n\t\t\tbreak\n\t\t}\n\t\ttoken = resp.GetResumptionToken()\n\t}\n\treturn formats, nil\n}"} {"input": "package sorting\n\nimport (\n\t. \"gopkg.in/check.v1\"\n)\n\nvar _ = Suite(&MySuite{})\n\nfunc (s *MySuite) TestNumberOfDiscIntersections(c *C) {\n\tc.Assert(NumberOfDiscIntersections([]int{1, 5, 2, 1, 4, 0}), Equals, 11)\n}\n\n\n\nfunc (s *MySuite) BenchmarkNumberOfDiscIntersections(c *C) ", "output": "{\n\tfor i := 0; i < c.N; i++ {\n\t\tNumberOfDiscIntersections([]int{1, 5, 2, 1, 4, 0})\n\t}\n}"} {"input": "package precreator\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com/influxdata/influxdb/toml\"\n)\n\nconst (\n\tDefaultCheckInterval = 10 * time.Minute\n\n\tDefaultAdvancePeriod = 30 * time.Minute\n)\n\n\ntype Config struct {\n\tEnabled bool `toml:\"enabled\"`\n\tCheckInterval toml.Duration `toml:\"check-interval\"`\n\tAdvancePeriod toml.Duration `toml:\"advance-period\"`\n}\n\n\n\n\n\nfunc (c Config) Validate() error {\n\tif !c.Enabled {\n\t\treturn nil\n\t}\n\n\tif c.CheckInterval <= 0 {\n\t\treturn errors.New(\"check-interval must be positive\")\n\t}\n\tif c.AdvancePeriod <= 0 {\n\t\treturn errors.New(\"advance-period must be positive\")\n\t}\n\n\treturn nil\n}\n\nfunc NewConfig() Config ", "output": "{\n\treturn Config{\n\t\tEnabled: true,\n\t\tCheckInterval: toml.Duration(DefaultCheckInterval),\n\t\tAdvancePeriod: toml.Duration(DefaultAdvancePeriod),\n\t}\n}"} {"input": "package builder\n\nimport (\n\t\"sync\"\n\n\t\"github.com/rikvdh/ci/lib/config\"\n)\n\ntype jobCounter struct {\n\tmu sync.RWMutex\n\tjobCounter uint\n\tjobLimit uint\n\teventCh chan uint\n}\n\n\n\nfunc (j *jobCounter) Increment() {\n\tj.mu.Lock()\n\tj.jobCounter++\n\tj.mu.Unlock()\n\tj.publishEvent()\n}\n\nfunc (j *jobCounter) Decrement() {\n\tj.mu.Lock()\n\tj.jobCounter--\n\tj.mu.Unlock()\n\tj.publishEvent()\n}\n\nfunc (j *jobCounter) CanStartJob() bool {\n\tj.mu.RLock()\n\tdefer j.mu.RUnlock()\n\treturn (j.jobCounter < j.jobLimit)\n}\n\nfunc (j *jobCounter) publishEvent() {\n\tj.mu.RLock()\n\tj.eventCh <- j.jobCounter\n\tj.mu.RUnlock()\n}\n\nfunc (j *jobCounter) GetEventChannel() <-chan uint {\n\tj.mu.RLock()\n\tdefer j.mu.RUnlock()\n\treturn j.eventCh\n}\n\nfunc newJobCounter() *jobCounter ", "output": "{\n\treturn &jobCounter{\n\t\tjobCounter: 0,\n\t\tjobLimit: config.Get().ConcurrentBuilds,\n\t\teventCh: make(chan uint),\n\t}\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\tgolangswaggerpaths \"path\"\n\t\"strings\"\n)\n\n\ntype GetUserURL struct {\n\tID string\n\n\t_basePath string\n\t_ struct{}\n}\n\n\n\n\nfunc (o *GetUserURL) WithBasePath(bp string) *GetUserURL {\n\to.SetBasePath(bp)\n\treturn o\n}\n\n\n\n\nfunc (o *GetUserURL) SetBasePath(bp string) {\n\to._basePath = bp\n}\n\n\nfunc (o *GetUserURL) Build() (*url.URL, error) {\n\tvar result url.URL\n\n\tvar _path = \"/users/{id}\"\n\n\tid := o.ID\n\tif id != \"\" {\n\t\t_path = strings.Replace(_path, \"{id}\", id, -1)\n\t} else {\n\t\treturn nil, errors.New(\"ID is required on GetUserURL\")\n\t}\n\n\t_basePath := o._basePath\n\tif _basePath == \"\" {\n\t\t_basePath = \"/\"\n\t}\n\tresult.Path = golangswaggerpaths.Join(_basePath, _path)\n\n\treturn &result, nil\n}\n\n\nfunc (o *GetUserURL) Must(u *url.URL, err error) *url.URL {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif u == nil {\n\t\tpanic(\"url can't be nil\")\n\t}\n\treturn u\n}\n\n\nfunc (o *GetUserURL) String() string {\n\treturn o.Must(o.Build()).String()\n}\n\n\n\n\n\nfunc (o *GetUserURL) StringFull(scheme, host string) string {\n\treturn o.Must(o.BuildFull(scheme, host)).String()\n}\n\nfunc (o *GetUserURL) BuildFull(scheme, host string) (*url.URL, error) ", "output": "{\n\tif scheme == \"\" {\n\t\treturn nil, errors.New(\"scheme is required for a full url on GetUserURL\")\n\t}\n\tif host == \"\" {\n\t\treturn nil, errors.New(\"host is required for a full url on GetUserURL\")\n\t}\n\n\tbase, err := o.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbase.Scheme = scheme\n\tbase.Host = host\n\treturn base, nil\n}"} {"input": "package header\n\nimport (\n\t\"github.com/google/netstack/tcpip\"\n)\n\n\n\nfunc Checksum(buf []byte, initial uint16) uint16 {\n\tv := uint32(initial)\n\n\tl := len(buf)\n\tif l&1 != 0 {\n\t\tl--\n\t\tv += uint32(buf[l]) << 8\n\t}\n\n\tfor i := 0; i < l; i += 2 {\n\t\tv += (uint32(buf[i]) << 8) + uint32(buf[i+1])\n\t}\n\n\treturn ChecksumCombine(uint16(v), uint16(v>>16))\n}\n\n\n\nfunc ChecksumCombine(a, b uint16) uint16 {\n\tv := uint32(a) + uint32(b)\n\treturn uint16(v + v>>16)\n}\n\n\n\n\n\n\n\nfunc PseudoHeaderChecksum(protocol tcpip.TransportProtocolNumber, srcAddr tcpip.Address, dstAddr tcpip.Address) uint16 ", "output": "{\n\txsum := Checksum([]byte(srcAddr), 0)\n\txsum = Checksum([]byte(dstAddr), xsum)\n\treturn Checksum([]byte{0, uint8(protocol)}, xsum)\n}"} {"input": "package state\n\nimport (\n\t\"github.com/hashicorp/consul/agent/structs\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\ntype Delay struct {\n\tdelay map[string]time.Time\n\n\tlock sync.RWMutex\n}\n\n\nfunc NewDelay() *Delay {\n\treturn &Delay{delay: make(map[string]time.Time)}\n}\n\n\n\n\nfunc (d *Delay) GetExpiration(key string, entMeta *structs.EnterpriseMeta) time.Time {\n\td.lock.RLock()\n\texpires := d.delay[key]\n\td.lock.RUnlock()\n\treturn expires\n}\n\n\n\n\n\nfunc (d *Delay) SetExpiration(key string, now time.Time, delay time.Duration, entMeta *structs.EnterpriseMeta) ", "output": "{\n\td.lock.Lock()\n\tdefer d.lock.Unlock()\n\n\td.delay[key] = now.Add(delay)\n\ttime.AfterFunc(delay, func() {\n\t\td.lock.Lock()\n\t\tdelete(d.delay, key)\n\t\td.lock.Unlock()\n\t})\n}"} {"input": "package config\n\ntype Dependencies interface {\n\tConfigurator\n\tInstalls() []string\n\tmerge(other Dependencies)\n}\n\nfunc NewDependencies(deps ...string) Dependencies {\n\ts := make(map[string]bool, len(deps))\n\tfor _, dep := range deps {\n\t\ts[dep] = exists\n\t}\n\treturn dependencies{\n\t\tset: s,\n\t}\n}\n\nconst exists = true\n\ntype dependencies struct {\n\tset map[string]bool\n}\n\nfunc (d dependencies) Installs() []string {\n\tkeys := make([]string, len(d.set))\n\n\ti := 0\n\tfor k := range d.set {\n\t\tkeys[i] = k\n\t\ti++\n\t}\n\n\treturn keys\n}\n\n\n\nfunc (d dependencies) merge(other Dependencies) {\n\tfor _, dep := range other.Installs() {\n\t\td.set[dep] = exists\n\t}\n}\n\nfunc (d dependencies) Configure(cfg Configurable) ", "output": "{\n\tcfg.Config().Dependencies.merge(d)\n}"} {"input": "package store_instructions\n\nimport (\n\t\"github.com/Frederick-S/jvmgo/instructions/base_instructions\"\n\t\"github.com/Frederick-S/jvmgo/runtime_data_area\"\n)\n\n\n\ntype AAStore struct {\n\tbase_instructions.NoOperandsInstruction\n}\n\n\n\nfunc (aAStore *AAStore) Execute(frame *runtime_data_area.Frame) ", "output": "{\n\toperandStack := frame.GetOperandStack()\n\treferenceValue := operandStack.PopReferenceValue()\n\tindex := operandStack.PopIntegerValue()\n\tarrayReference := operandStack.PopReferenceValue()\n\n\tif arrayReference == nil {\n\t\tpanic(\"java.lang.NullPointerException\")\n\t}\n\n\treferenceArray := arrayReference.GetReferenceArray()\n\n\tif index < 0 || index >= int32(len(referenceArray)) {\n\t\tpanic(\"ArrayIndexOutOfBoundsException\")\n\t}\n\n\treferenceArray[index] = referenceValue\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\ntype Response struct {\n\tStatus string `json:\"status\"`\n\tErrorText string `json:\"errorText,omitempty\"`\n\tAddress string `json:\"address,omitempty\"`\n\tStatusCode int `json:\"statusCode,omitempty\"`\n\tVersion string `json:\"version,omitempty\"`\n}\n\ntype Responses struct {\n\tResponses []Response `json:\"responses\"`\n}\n\nfunc (r *Response) Fill(outStr string, err error) {\n\tif err != nil {\n\t\tr.Status = \"ERR\"\n\t\tr.ErrorText = strings.TrimSpace(outStr + \" \" + err.Error())\n\t} else {\n\t\tr.Status = \"OK\"\n\t}\n}\n\nfunc (r Responses) String() string {\n\tj, _ := json.Marshal(r)\n\treturn fmt.Sprintf(\"Responses: %s\", string(j))\n}\n\nfunc (r Response) String() string {\n\tj, _ := json.Marshal(r)\n\treturn fmt.Sprintf(\"Response: %s\", string(j))\n}\n\nfunc (r Response) WriteHttp(w http.ResponseWriter) (resp Response) {\n\tif r.StatusCode == 0 {\n\t\tr.StatusCode = 200\n\t}\n\tw.WriteHeader(r.StatusCode)\n\treturn EncodeJson(r, w)\n}\n\nfunc (r Response) WriteBadRequestHttp(w http.ResponseWriter) (resp Response) {\n\tw.WriteHeader(http.StatusBadRequest)\n\tr.StatusCode = http.StatusBadRequest\n\treturn EncodeJson(r, w)\n}\n\nfunc (r Response) WriteInternalServerErrorHttp(w http.ResponseWriter) (resp Response) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tr.StatusCode = http.StatusInternalServerError\n\treturn EncodeJson(r, w)\n}\n\n\n\nfunc EncodeJson(r Response, w http.ResponseWriter) (resp Response) ", "output": "{\n\terr := json.NewEncoder(w).Encode(r)\n\tif err != nil {\n\t\tlog.Printf(\"[writehttp] failed to create json from model: %s\", err.Error())\n\t}\n\treturn r\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"bufio\"\n\t\"fmt\"\n)\n\ntype Store struct {\n\n}\n\n\n\nfunc (s Store)ReadStore(file string) (map[string]string, error) {\n\tstore := make(map[string]string)\n\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn store, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\thandleCommand(store, scanner.Text())\n\t}\n\n\treturn store, scanner.Err()\n}\n\nfunc (s Store)WriteStore(store map[string]string, file string) error {\n\tf, err := os.Create(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\treturn s.WriteTo(store, f)\n}\n\nfunc (s Store)WriteTo(store map[string]string, w io.Writer) error {\n\tfor k, v := range store {\n\t\tif _, err := fmt.Fprintf(w, \"%v=%v\\n\", k, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc NewStore() *Store ", "output": "{\n\treturn &Store{}\n}"} {"input": "package resolver\n\nimport (\n \"testing\"\n)\n\n\n\nfunc Test_ResolverInstallWithoutLocation(t *testing.T) ", "output": "{\n success, err := Install(\"\")\n\n if success || err == nil {\n t.Error(\"Resolver shouldn't be able to install without an origin location\")\n }\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\ntype Project struct {\n\tName string `yaml:\"project\"`\n\tDescription string\n\tWebsiteLink string `yaml:\"website-link\"`\n\tGithubLink string `yaml:\"github-link\"`\n\tTags []string\n\tCreator string\n\tCreatorLink string `yaml:\"creator-link\"`\n}\n\n\n\nfunc readProjectsFile() []byte {\n\tfilename := \"projects.yaml\"\n\tcontent, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn []byte{}\n\t}\n\n\treturn content\n}\n\nfunc getProjects() []Project ", "output": "{\n\tprojects := []Project{}\n\tdata := readProjectsFile()\n\terr := yaml.Unmarshal(data, &projects)\n\tif err != nil {\n\t\treturn []Project{}\n\t}\n\n\tl := len(projects)\n\tfor i := 0; i < l/2; i++ {\n\t\tj := l - i - 1\n\t\tprojects[i], projects[j] = projects[j], projects[i]\n\t}\n\n\treturn projects\n}"} {"input": "package sftp\n\n\n\n\nimport \"os\"\n\n\n\ntype FileOpenFlags struct {\n\tRead, Write, Append, Creat, Trunc, Excl bool\n}\n\nfunc newFileOpenFlags(flags uint32) FileOpenFlags {\n\treturn FileOpenFlags{\n\t\tRead: flags&ssh_FXF_READ != 0,\n\t\tWrite: flags&ssh_FXF_WRITE != 0,\n\t\tAppend: flags&ssh_FXF_APPEND != 0,\n\t\tCreat: flags&ssh_FXF_CREAT != 0,\n\t\tTrunc: flags&ssh_FXF_TRUNC != 0,\n\t\tExcl: flags&ssh_FXF_EXCL != 0,\n\t}\n}\n\n\n\nfunc (r *Request) Pflags() FileOpenFlags {\n\treturn newFileOpenFlags(r.Flags)\n}\n\n\n\n\ntype FileAttrFlags struct {\n\tSize, UidGid, Permissions, Acmodtime bool\n}\n\nfunc newFileAttrFlags(flags uint32) FileAttrFlags {\n\treturn FileAttrFlags{\n\t\tSize: (flags & ssh_FILEXFER_ATTR_SIZE) != 0,\n\t\tUidGid: (flags & ssh_FILEXFER_ATTR_UIDGID) != 0,\n\t\tPermissions: (flags & ssh_FILEXFER_ATTR_PERMISSIONS) != 0,\n\t\tAcmodtime: (flags & ssh_FILEXFER_ATTR_ACMODTIME) != 0,\n\t}\n}\n\n\n\nfunc (r *Request) AttrFlags() FileAttrFlags {\n\treturn newFileAttrFlags(r.Flags)\n}\n\n\nfunc (a FileStat) FileMode() os.FileMode {\n\treturn os.FileMode(a.Mode)\n}\n\n\n\n\n\nfunc (r *Request) Attributes() *FileStat ", "output": "{\n\tfs, _ := getFileStat(r.Flags, r.Attrs)\n\treturn fs\n}"} {"input": "package diffsquares\n\n\nfunc SquareOfSums(n int) int {\n\ts := int(n)\n\ts *= s + 1\n\ts /= 2\n\treturn s * s\n}\n\n\nfunc SumOfSquares(n int) int {\n\ts := int(n)\n\ts = 2*s*s*s + 3*s*s + s\n\ts /= 6\n\treturn s\n\n}\n\n\n\n\nfunc Difference(n int) int ", "output": "{\n\treturn SquareOfSums(n) - SumOfSquares(n)\n}"} {"input": "package ecommerce\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/arvindkandhare/goamz/aws\"\n)\n\n\ntype ProductAdvertising struct {\n\tservice aws.Service\n\tassociateTag string\n}\n\n\nfunc New(auth aws.Auth, associateTag string) (p *ProductAdvertising, err error) {\n\tserviceInfo := aws.ServiceInfo{Endpoint: \"https://webservices.amazon.com\", Signer: aws.V2Signature}\n\tif service, err := aws.NewService(auth, serviceInfo); err == nil {\n\t\tp = &ProductAdvertising{*service, associateTag}\n\t}\n\treturn\n}\n\n\nfunc (p *ProductAdvertising) PerformOperation(operation string, params map[string]string) (resp *http.Response, err error) {\n\tparams[\"Operation\"] = operation\n\treturn p.query(params)\n}\n\n\n\nfunc (p *ProductAdvertising) query(params map[string]string) (resp *http.Response, err error) ", "output": "{\n\tparams[\"Service\"] = \"AWSECommerceService\"\n\tparams[\"AssociateTag\"] = p.associateTag\n\treturn p.service.Query(\"GET\", \"/onca/xml\", params)\n}"} {"input": "package context\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\n\n\nfunc Since(ctx context.Context, key interface{}) time.Duration {\n\tif startedAt, ok := ctx.Value(key).(time.Time); ok {\n\t\treturn time.Since(startedAt)\n\t}\n\treturn 0\n}\n\n\n\n\n\nfunc GetStringValue(ctx context.Context, key interface{}) (value string) ", "output": "{\n\tif valuev, ok := ctx.Value(key).(string); ok {\n\t\tvalue = valuev\n\t}\n\treturn value\n}"} {"input": "package sample\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n)\n\ntype sampleState struct {\n\trate uint64\n\tseed int64\n\tsampleCount uint64\n\ttrueCount uint64\n\trnd *rand.Rand\n}\n\n\ntype Sampler interface {\n\tSample() bool\n\tSampleFrom(probe uint64) bool\n\tState\n}\n\n\ntype State interface {\n\tReset()\n\tString() string\n\tRate() uint64\n\tCalls() uint64\n\tCount() uint64\n}\n\nfunc (state *sampleState) Rate() uint64 {\n\tif state != nil {\n\t\treturn state.rate\n\t}\n\treturn 0\n}\n\nfunc (state *sampleState) Calls() uint64 {\n\tif state != nil {\n\t\treturn state.sampleCount\n\t}\n\treturn 0\n}\n\nfunc (state *sampleState) Count() uint64 {\n\tif state != nil {\n\t\treturn state.trueCount\n\t}\n\treturn 0\n}\n\nfunc (state *sampleState) Reset() {\n\tstate.rnd.Seed(state.seed)\n\tstate.sampleCount = 0\n\tstate.trueCount = 0\n}\n\nfunc (state *sampleState) String() string {\n\ttype X *sampleState\n\tx := X(state)\n\treturn fmt.Sprintf(\"%+v\", x)\n}\n\n\nfunc Deviation(state State) (deviation float64) {\n\tif state != nil && state.Count() > 0 {\n\t\tdeviation = 1.0 - 1.0/float64(state.Rate())*(float64(state.Calls())/float64(state.Count()))\n\t} else {\n\t\tdeviation = 1.0\n\t}\n\n\treturn\n}\n\n\n\n\nfunc Stats(state State) string ", "output": "{\n\tif state != nil {\n\t\treturn fmt.Sprintf(\"Rate: %d, SampleCount: %d, TrueCount: %d, Deviation: %.4f%%\", state.Rate(), state.Calls(), state.Count(), Deviation(state)*100.0)\n\t}\n\treturn \"No state provided\"\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/unrolled/render\"\n)\n\n\nvar Render *render.Render\n\n\nfunc init() {\n\tRender = render.New(render.Options{\n\t\tIndentJSON: true,\n\t})\n}\n\nfunc index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Welcome to the home page!\")\n}\n\n\n\nfunc apiKeyHandler(w http.ResponseWriter, r *http.Request) {\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the api Key hander page! %s\", id)\n}\n\nfunc apiKeyDetailsHandler(w http.ResponseWriter, r *http.Request) {\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the api Key Details hander page! %s\", id)\n}\n\nfunc webKeyHandler(w http.ResponseWriter, r *http.Request) {\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the web Key hander page! %s\", id)\n}\n\nfunc notFound(w http.ResponseWriter, r *http.Request) {\n\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n}\n\nfunc apiHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tRender.JSON(w, http.StatusOK, \"Welcome to the api hander page!\")\n}"} {"input": "package exif\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\n\n\n\n\nfunc toInt16(bo binary.ByteOrder, buf []byte) int16 {\n\tvar i int16\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}\n\n\nfunc toUint32(bo binary.ByteOrder, buf []byte) uint32 {\n\tvar i uint32\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}\n\n\nfunc toInt32(bo binary.ByteOrder, buf []byte) int32 {\n\tvar i int32\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}\n\nfunc toUint16(bo binary.ByteOrder, buf []byte) uint16 ", "output": "{\n\tvar i uint16\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}"} {"input": "package label\n\n\n\n\nfunc InitLabels(mcsdir string, options []string) (string, string, error) {\n\treturn \"\", \"\", nil\n}\n\nfunc FormatMountLabel(src string, mountLabel string) string {\n\treturn src\n}\n\n\n\nfunc SetFileLabel(path string, fileLabel string) error {\n\treturn nil\n}\n\nfunc SetFileCreateLabel(fileLabel string) error {\n\treturn nil\n}\n\nfunc Relabel(path string, fileLabel string, relabel string) error {\n\treturn nil\n}\n\nfunc GetPidLabel(pid int) (string, error) {\n\treturn \"\", nil\n}\n\nfunc Init() {\n}\n\nfunc ReserveLabel(label string) error {\n\treturn nil\n}\n\nfunc UnreserveLabel(label string) error {\n\treturn nil\n}\n\n\n\nfunc DupSecOpt(src string) []string {\n\treturn nil\n}\n\n\n\nfunc DisableSecOpt() []string {\n\treturn nil\n}\n\nfunc SetProcessLabel(processLabel string) error ", "output": "{\n\treturn nil\n}"} {"input": "package unix\n\nimport \"unsafe\"\n\n\n\nvar fcntl64Syscall uintptr = SYS_FCNTL\n\nfunc fcntl(fd int, cmd, arg int) (int, error) {\n\tvalptr, _, errno := Syscall(fcntl64Syscall, uintptr(fd), uintptr(cmd), uintptr(arg))\n\tvar err error\n\tif errno != 0 {\n\t\terr = errno\n\t}\n\treturn int(valptr), err\n}\n\n\n\n\n\nfunc FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error {\n\t_, _, errno := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(unsafe.Pointer(lk)))\n\tif errno == 0 {\n\t\treturn nil\n\t}\n\treturn errno\n}\n\nfunc FcntlInt(fd uintptr, cmd, arg int) (int, error) ", "output": "{\n\treturn fcntl(int(fd), cmd, arg)\n}"} {"input": "package arm\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest/azure\"\n\t\"github.com/mitchellh/packer/builder/azure/common\"\n)\n\ntype configRetriever struct {\n\tfindTenantID func(azure.Environment, string) (string, error)\n}\n\n\n\nfunc (cr configRetriever) FillParameters(c *Config) error {\n\tif c.TenantID == \"\" {\n\t\ttenantID, err := cr.findTenantID(*c.cloudEnvironment, c.SubscriptionID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.TenantID = tenantID\n\t}\n\treturn nil\n}\n\nfunc newConfigRetriever() configRetriever ", "output": "{\n\treturn configRetriever{common.FindTenantID}\n}"} {"input": "package ansi\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/blevesearch/bleve/registry\"\n\t\"github.com/blevesearch/bleve/search/highlight\"\n\tansiFormatter \"github.com/blevesearch/bleve/search/highlight/format/ansi\"\n\tsimpleFragmenter \"github.com/blevesearch/bleve/search/highlight/fragmenter/simple\"\n\tsimpleHighlighter \"github.com/blevesearch/bleve/search/highlight/highlighter/simple\"\n)\n\nconst Name = \"ansi\"\n\n\n\nfunc init() {\n\tregistry.RegisterHighlighter(Name, Constructor)\n}\n\nfunc Constructor(config map[string]interface{}, cache *registry.Cache) (highlight.Highlighter, error) ", "output": "{\n\n\tfragmenter, err := cache.FragmenterNamed(simpleFragmenter.Name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error building fragmenter: %v\", err)\n\t}\n\n\tformatter, err := cache.FragmentFormatterNamed(ansiFormatter.Name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error building fragment formatter: %v\", err)\n\t}\n\n\treturn simpleHighlighter.NewHighlighter(\n\t\t\tfragmenter,\n\t\t\tformatter,\n\t\t\tsimpleHighlighter.DefaultSeparator),\n\t\tnil\n}"} {"input": "package execution\n\nimport (\n\t\"sync\"\n\n\t\"github.com/hyperledger/burrow/acm\"\n\t\"github.com/hyperledger/burrow/acm/acmstate\"\n\t\"github.com/hyperledger/burrow/crypto\"\n\t\"github.com/hyperledger/burrow/keys\"\n\tburrow_sync \"github.com/hyperledger/burrow/sync\"\n)\n\n\n\ntype Accounts struct {\n\tburrow_sync.RingMutex\n\tacmstate.Reader\n\tkeyClient keys.KeyClient\n}\n\ntype SigningAccount struct {\n\t*acm.Account\n\tcrypto.Signer\n}\n\ntype SequentialSigningAccount struct {\n\tAddress crypto.Address\n\taccountLocker sync.Locker\n\tgetter func() (*SigningAccount, error)\n}\n\nfunc NewAccounts(reader acmstate.Reader, keyClient keys.KeyClient, mutexCount int) *Accounts {\n\treturn &Accounts{\n\t\tRingMutex: *burrow_sync.NewRingMutexNoHash(mutexCount),\n\t\tReader: reader,\n\t\tkeyClient: keyClient,\n\t}\n}\n\n\n\nfunc (accs *Accounts) SequentialSigningAccount(address crypto.Address) (*SequentialSigningAccount, error) {\n\treturn &SequentialSigningAccount{\n\t\tAddress: address,\n\t\taccountLocker: accs.Mutex(address.Bytes()),\n\t\tgetter: func() (*SigningAccount, error) {\n\t\t\treturn accs.SigningAccount(address)\n\t\t},\n\t}, nil\n}\n\ntype UnlockFunc func()\n\nfunc (ssa *SequentialSigningAccount) Lock() (*SigningAccount, UnlockFunc, error) {\n\tssa.accountLocker.Lock()\n\taccount, err := ssa.getter()\n\tif err != nil {\n\t\tssa.accountLocker.Unlock()\n\t\treturn nil, nil, err\n\t}\n\treturn account, ssa.accountLocker.Unlock, err\n}\n\nfunc (accs *Accounts) SigningAccount(address crypto.Address) (*SigningAccount, error) ", "output": "{\n\tsigner, err := keys.AddressableSigner(accs.keyClient, address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taccount, err := accs.GetAccount(address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif account == nil {\n\t\taccount = &acm.Account{\n\t\t\tAddress: address,\n\t\t}\n\t}\n\tpubKey, err := accs.keyClient.PublicKey(address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taccount.PublicKey = pubKey\n\treturn &SigningAccount{\n\t\tAccount: account,\n\t\tSigner: signer,\n\t}, nil\n}"} {"input": "package ha\n\nimport (\n\tlog \"github.com/golang/glog\"\n\t\"k8s.io/kubernetes/contrib/mesos/pkg/election\"\n)\n\ntype roleType int\n\nconst (\n\tfollowerRole roleType = iota\n\tmasterRole\n\tretiredRole\n)\n\ntype candidateService struct {\n\tsched *SchedulerProcess\n\tnewDriver DriverFactory\n\trole roleType\n\tvalid ValidationFunc\n}\n\ntype ValidationFunc func(desiredUid, currentUid string)\n\nfunc NewCandidate(s *SchedulerProcess, f DriverFactory, v ValidationFunc) election.Service {\n\treturn &candidateService{\n\t\tsched: s,\n\t\tnewDriver: f,\n\t\trole: followerRole,\n\t\tvalid: v,\n\t}\n}\n\nfunc (self *candidateService) Validate(desired, current election.Master) {\n\tif self.valid != nil {\n\t\tself.valid(string(desired), string(current))\n\t}\n}\n\nfunc (self *candidateService) Start() {\n\tif self.role == followerRole {\n\t\tlog.Info(\"elected as master\")\n\t\tself.role = masterRole\n\t\tself.sched.Elect(self.newDriver)\n\t}\n}\n\n\n\nfunc (self *candidateService) Stop() ", "output": "{\n\tif self.role == masterRole {\n\t\tlog.Info(\"retiring from master\")\n\t\tself.role = retiredRole\n\t\tclose(self.sched.failover)\n\t\tself.sched.End()\n\t}\n}"} {"input": "package sliceset\n\nimport (\n\t\"sort\"\n\n\t\"github.com/xtgo/set\"\n)\n\ntype Set []int\n\nfunc (s Set) Len() int { return len(s) }\nfunc (s Set) Less(i, j int) bool { return s[i] < s[j] }\n\n\nfunc (s Set) Copy() Set { return append(Set(nil), s...) }\n\nfunc (s Set) Union(t Set) Set { return s.Do(set.Union, t) }\nfunc (s Set) Inter(t Set) Set { return s.Do(set.Inter, t) }\nfunc (s Set) Diff(t Set) Set { return s.Do(set.Diff, t) }\nfunc (s Set) SymDiff(t Set) Set { return s.Do(set.SymDiff, t) }\nfunc (s Set) IsSub(t Set) bool { return s.DoBool(set.IsSub, t) }\nfunc (s Set) IsSuper(t Set) bool { return s.DoBool(set.IsSuper, t) }\nfunc (s Set) IsInter(t Set) bool { return s.DoBool(set.IsInter, t) }\nfunc (s Set) IsEqual(t Set) bool { return s.DoBool(set.IsEqual, t) }\n\nfunc (s Set) Uniq() Set {\n\tn := set.Uniq(s)\n\treturn s[:n]\n}\n\nfunc (s Set) Do(op set.Op, t Set) Set {\n\tdata := append(s, t...)\n\tn := op(data, len(s))\n\treturn data[:n]\n}\n\ntype BoolOp func(sort.Interface, int) bool\n\nfunc (s Set) DoBool(op BoolOp, t Set) bool {\n\tdata := append(s, t...)\n\treturn op(data, len(s))\n}\n\nfunc (s Set) Swap(i, j int) ", "output": "{ s[i], s[j] = s[j], s[i] }"} {"input": "package learn\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\nfunc typeMismatchErr(a, b interface{}) error {\n\treturn fmt.Errorf(\"learn: type mismatch in features \\\"v\\\" \\\"v\\\"\\n\", a, b)\n}\n\nfunc unknownTypeErr(a interface{}) error ", "output": "{\n\treturn fmt.Errorf(\"learn: type of \\\"%v\\\" must be float or string not %T\", a, a)\n}"} {"input": "package stats\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestSum(t *testing.T) {\n\tfor _, c := range []struct {\n\t\tin []float64\n\t\tout float64\n\t}{\n\t\t{[]float64{1, 2, 3}, 6},\n\t\t{[]float64{1.0, 1.1, 1.2, 2.2}, 5.5},\n\t\t{[]float64{1, -1, 2, -3}, -1},\n\t} {\n\t\tgot, err := Sum(c.in)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Returned an error\")\n\t\t}\n\t\tif !reflect.DeepEqual(c.out, got) {\n\t\t\tt.Errorf(\"Sum(%.1f) => %.1f != %.1f\", c.in, got, c.out)\n\t\t}\n\t}\n\t_, err := Sum([]float64{})\n\tif err == nil {\n\t\tt.Errorf(\"Empty slice should have returned an error\")\n\t}\n}\n\nfunc BenchmarkSumSmallFloatSlice(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tSum(makeFloatSlice(5))\n\t}\n}\n\n\n\nfunc BenchmarkSumLargeFloatSlice(b *testing.B) ", "output": "{\n\tlf := makeFloatSlice(100000)\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tSum(lf)\n\t}\n}"} {"input": "package plain\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t. \"github.com/SimonRichardson/wishful-route/route\"\n\t. \"github.com/SimonRichardson/wishful/useful\"\n\t. \"github.com/SimonRichardson/wishful/wishful\"\n)\n\nfunc NewPlainResult(statusCode int, body string) Result {\n\treturn NewResult(body, statusCode, NewHeaders(map[string]string{\n\t\t\"Content-Length\": fmt.Sprintf(\"%d\", len(body)),\n\t\t\"Content-Type\": \"text/plain\",\n\t}))\n}\n\nfunc Ok(body string) Promise {\n\treturn NewPromise(func(resolve func(x AnyVal) AnyVal) AnyVal {\n\t\treturn resolve(NewPlainResult(http.StatusOK, body))\n\t})\n}\n\n\n\nfunc InternalServerError(body string) Promise {\n\treturn NewPromise(func(resolve func(x AnyVal) AnyVal) AnyVal {\n\t\treturn resolve(NewPlainResult(http.StatusInternalServerError, body))\n\t})\n}\n\nfunc Redirect(url string) Promise {\n\treturn NewPromise(func(resolve func(x AnyVal) AnyVal) AnyVal {\n\t\treturn resolve(NewResult(\"\", http.StatusFound, NewHeaders(map[string]string{\n\t\t\t\"Location\": url,\n\t\t})))\n\t})\n}\n\nfunc NotFound(body string) Promise ", "output": "{\n\treturn NewPromise(func(resolve func(x AnyVal) AnyVal) AnyVal {\n\t\treturn resolve(NewPlainResult(http.StatusNotFound, body))\n\t})\n}"} {"input": "package vault\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/hashicorp/vault/sdk/logical\"\n)\n\nconst sscGenCounterPath string = \"core/sscGenCounter/\"\n\ntype SSCTokenGenerationCounter struct {\n\tCounter int\n}\n\nfunc (ts *TokenStore) GetSSCTokensGenerationCounter() int {\n\treturn ts.sscTokensGenerationCounter.Counter\n}\n\nfunc (ts *TokenStore) loadSSCTokensGenerationCounter(ctx context.Context) error {\n\tsscTokensGenerationCounterStorageVal, err := ts.core.barrier.Get(ctx, sscGenCounterPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to retrieve SSCTokenGenerationCounter from storage: err %w\", err)\n\t}\n\tif sscTokensGenerationCounterStorageVal == nil {\n\t\tts.logger.Trace(\"no token generation counter found in storage\")\n\t\tts.sscTokensGenerationCounter = SSCTokenGenerationCounter{Counter: 0}\n\t\treturn nil\n\t}\n\tvar sscTokensGenerationCounter SSCTokenGenerationCounter\n\terr = json.Unmarshal(sscTokensGenerationCounterStorageVal.Value, &sscTokensGenerationCounter)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"malformed token generation counter found in storage: err %w\", err)\n\t}\n\tts.sscTokensGenerationCounter = sscTokensGenerationCounter\n\treturn nil\n}\n\n\n\nfunc (ts *TokenStore) UpdateSSCTokensGenerationCounter(ctx context.Context) error ", "output": "{\n\tts.sscTokensGenerationCounter.Counter += 1\n\tif ts.sscTokensGenerationCounter.Counter <= 0 {\n\t\tts.logger.Warn(\"attempt to store non-positive token generation counter was ignored\",\n\t\t\t\"sscTokensGenerationCounter\", ts.sscTokensGenerationCounter.Counter)\n\t}\n\tmarshalledCtr, err := json.Marshal(ts.sscTokensGenerationCounter)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ts.core.barrier.Put(ctx, &logical.StorageEntry{\n\t\tKey: sscGenCounterPath,\n\t\tValue: marshalledCtr,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package dataintegration\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateExternalPublicationRequest struct {\n\n\tWorkspaceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"workspaceId\"`\n\n\tTaskKey *string `mandatory:\"true\" contributesTo:\"path\" name:\"taskKey\"`\n\n\tCreateExternalPublicationDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateExternalPublicationRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateExternalPublicationRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request CreateExternalPublicationRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateExternalPublicationResponse struct {\n\n\tRawResponse *http.Response\n\n\tExternalPublication `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateExternalPublicationResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateExternalPublicationResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateExternalPublicationRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package cs\n\nimport (\n\t\"github.com/scionproto/scion/go/cs/beacon\"\n\t\"github.com/scionproto/scion/go/cs/config\"\n\t\"github.com/scionproto/scion/go/lib/serrors\"\n)\n\n\nfunc LoadCorePolicies(cfg config.Policies) (beacon.CorePolicies, error) {\n\tvar err error\n\tvar policies beacon.CorePolicies\n\tif policies.Prop, err = loadPolicy(cfg.Propagation, beacon.PropPolicy); err != nil {\n\t\treturn policies, err\n\t}\n\tif policies.CoreReg, err = loadPolicy(cfg.CoreRegistration, beacon.CoreRegPolicy); err != nil {\n\t\treturn policies, err\n\t}\n\treturn policies, nil\n}\n\n\n\n\nfunc loadPolicy(fn string, t beacon.PolicyType) (beacon.Policy, error) {\n\tvar policy beacon.Policy\n\tif fn != \"\" {\n\t\tp, err := beacon.LoadPolicyFromYaml(fn, t)\n\t\tif err != nil {\n\t\t\treturn policy, serrors.WrapStr(\"loading beaconing policy\", err, \"file\", fn, \"type\", t)\n\t\t}\n\t\tpolicy = *p\n\t}\n\tpolicy.InitDefaults()\n\treturn policy, nil\n}\n\nfunc LoadNonCorePolicies(cfg config.Policies) (beacon.Policies, error) ", "output": "{\n\tvar err error\n\tvar policies beacon.Policies\n\tif policies.Prop, err = loadPolicy(cfg.Propagation, beacon.PropPolicy); err != nil {\n\t\treturn policies, err\n\t}\n\tif policies.UpReg, err = loadPolicy(cfg.UpRegistration, beacon.UpRegPolicy); err != nil {\n\t\treturn policies, err\n\t}\n\tif policies.DownReg, err = loadPolicy(cfg.DownRegistration, beacon.DownRegPolicy); err != nil {\n\t\treturn policies, err\n\t}\n\treturn policies, nil\n}"} {"input": "package classfile\n\nimport \"encoding/binary\"\n\ntype ClassReader struct {\n\tdata []byte \n}\n\n\n\nfunc (self *ClassReader) readUint16() uint16 {\n\tval := binary.BigEndian.Uint16(self.data)\n\tself.data = self.data[2:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint32() uint32 {\n\tval := binary.BigEndian.Uint32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint64() uint64 {\n\tval := binary.BigEndian.Uint64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16s() []uint16 {\n\tn := self.readUint16()\n\ts := make([]uint16, n)\n\tfor i := range s {\n\t\ts[i] = self.readUint16()\n\t}\n\treturn s\n}\n\nfunc (self *ClassReader) readBytes(n uint32) []byte {\n\tbytes := self.data[:n]\n\tself.data = self.data[n:]\n\treturn bytes\n}\n\nfunc (self *ClassReader) readUint8() uint8 ", "output": "{\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}"} {"input": "package goverify\n\nimport (\n\t\"crypto/rsa\"\n\t\"fmt\"\n)\n\n\ntype Signer interface {\n\tSign(data []byte) ([]byte, error)\n}\n\n\n\nfunc newSignerFromKey(k interface{}) (Signer, error) ", "output": "{\n\tvar sshKey Signer\n\tswitch t := k.(type) {\n\tcase *rsa.PrivateKey:\n\t\tsshKey = &RSAPrivateKey{t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"ssh: unsupported key type %T\", k)\n\t}\n\treturn sshKey, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\tosexec \"os/exec\"\n\t\"path/filepath\"\n)\n\n\nfunc exec(args ...string) error {\n\tcmd := osexec.Command(args[0], args[1:]...)\n\tout, err := cmd.CombinedOutput()\n\tswitch err := err.(type) {\n\tcase nil:\n\t\treturn nil\n\tcase *osexec.ExitError:\n\t\treturn fmt.Errorf(\"failed to run %q:\\n%v\", args, string(out))\n\tdefault:\n\t\treturn err\n\t}\n}\n\n\n\n\n\nfunc execCompose(dir string, args ...string) error {\n\treturn exec(append(\n\t\t[]string{\"docker-compose\", \"--ansi=never\", \"-f\", filepath.Join(dir, \"docker-compose.yml\")},\n\t\targs...)...)\n}\n\n\nfunc execComposeVerbose(dir string, args ...string) error {\n\treturn execVerbose(append(\n\t\t[]string{\"docker-compose\", \"--ansi=never\", \"-f\", filepath.Join(dir, \"docker-compose.yml\")},\n\t\targs...)...)\n}\n\n\nfunc execDocker(args ...string) error {\n\treturn exec(append([]string{\"docker\"}, args...)...)\n}\n\nfunc execVerbose(args ...string) error ", "output": "{\n\tcmd := osexec.Command(args[0], args[1:]...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}"} {"input": "package helpers\n\nimport (\n\t\"crypto\"\n\t\"crypto/x509\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n)\n\n\n\nfunc PrivateKeyFromSecret(secret *corev1.Secret) (crypto.Signer, error) ", "output": "{\n\tkeyPem, ok := secret.Data[corev1.TLSPrivateKeyKey]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"secret %s/%s is missing key %q\", secret.Namespace, secret.Name, corev1.TLSPrivateKeyKey)\n\t}\n\n\tblock, _ := pem.Decode(keyPem)\n\tif block == nil {\n\t\treturn nil, fmt.Errorf(\"secret %s/%s has invalid PEM encoded private key\", secret.Namespace, secret.Name)\n\t}\n\n\tprivateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn privateKey, nil\n}"} {"input": "package errors\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\ntype testWrapped struct {\n\terror\n}\n\n\n\nfunc (w *testWrapped) Unwrap() error {\n\treturn w.error\n}\n\nfunc testWrap(err error) error {\n\treturn &testWrapped{err}\n}\n\nfunc TestWrapped(t *testing.T) {\n\tt.Parallel()\n\n\tConvey(`Test Wrapped`, t, func() {\n\t\tConvey(`A nil error`, func() {\n\t\t\tvar err error\n\n\t\t\tConvey(`Unwraps to nil.`, func() {\n\t\t\t\tSo(Unwrap(err), ShouldBeNil)\n\t\t\t})\n\n\t\t\tConvey(`When wrapped, does not unwrap to nil.`, func() {\n\t\t\t\tSo(Unwrap(testWrap(err)), ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\n\t\tConvey(`A non-wrapped error.`, func() {\n\t\t\terr := New(\"test error\")\n\n\t\t\tConvey(`Unwraps to itself.`, func() {\n\t\t\t\tSo(Unwrap(err), ShouldEqual, err)\n\t\t\t})\n\n\t\t\tConvey(`When wrapped, unwraps to itself.`, func() {\n\t\t\t\tSo(Unwrap(testWrap(err)), ShouldEqual, err)\n\t\t\t})\n\n\t\t\tConvey(`When double-wrapped, unwraps to itself.`, func() {\n\t\t\t\tSo(Unwrap(testWrap(testWrap(err))), ShouldEqual, err)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc (w *testWrapped) Error() string ", "output": "{\n\tif w.error == nil {\n\t\treturn \"wrapped: nil\"\n\t}\n\treturn fmt.Sprintf(\"wrapped: %v\", w.error.Error())\n}"} {"input": "package seqnum\n\n\ntype Value uint32\n\n\ntype Size uint32\n\n\nfunc (v Value) LessThan(w Value) bool {\n\treturn int32(v-w) < 0\n}\n\n\nfunc (v Value) LessThanEq(w Value) bool {\n\tif v == w {\n\t\treturn true\n\t}\n\treturn v.LessThan(w)\n}\n\n\nfunc (v Value) InRange(a, b Value) bool {\n\treturn v-a < b-a\n}\n\n\n\nfunc (v Value) InWindow(first Value, size Size) bool {\n\treturn v.InRange(first, first.Add(size))\n}\n\n\n\n\n\nfunc (v Value) Add(s Size) Value {\n\treturn v + Value(s)\n}\n\n\nfunc (v Value) Size(w Value) Size {\n\treturn Size(w - v)\n}\n\n\nfunc (v *Value) UpdateForward(s Size) {\n\t*v += Value(s)\n}\n\nfunc Overlap(a Value, b Size, x Value, y Size) bool ", "output": "{\n\treturn a.LessThan(x.Add(y)) && x.LessThan(a.Add(b))\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/bfontaine/go-tchoutchou/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n)\n\ntype SucceedMatcher struct {\n}\n\nfunc (matcher *SucceedMatcher) Match(actual interface{}) (success bool, err error) {\n\tif actual == nil {\n\t\treturn true, nil\n\t}\n\n\tif isError(actual) {\n\t\treturn false, nil\n\t}\n\n\treturn false, fmt.Errorf(\"Expected an error-type. Got:\\n%s\", format.Object(actual, 1))\n}\n\nfunc (matcher *SucceedMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn fmt.Sprintf(\"Expected success, but got an error:\\n%s\", format.Object(actual, 1))\n}\n\n\n\nfunc (matcher *SucceedMatcher) NegatedFailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn \"Expected failure, but got no error.\"\n}"} {"input": "package test\n\nimport (\n\t\"debug/macho\"\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/bazelbuild/rules_go/go/tools/bazel\"\n)\n\nfunc openMachO(dir, bin string) (*macho.File, error) {\n\tbin, ok := bazel.FindBinary(dir, bin)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"could not find binary: %s\", bin)\n\t}\n\n\tf, err := os.Open(bin)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn macho.NewFile(f)\n}\n\n\n\nfunc TestPIE(t *testing.T) ", "output": "{\n\tm, err := openMachO(\"tests/core/go_binary\", \"hello_pie_bin\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif m.Flags&macho.FlagPIE == 0 {\n\t\tt.Error(\"ELF binary is not position-independent.\")\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"time\"\n\n\t\"github.com/jrkt/go-tracing-lab/grpc/interceptors\"\n\tpb \"github.com/jrkt/go-tracing-lab/grpc/weather-search/weather/proto\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\ntype SvcClient struct {\n\tservice pb.WeatherClient\n}\n\nvar (\n\taddress = \"localhost:8002\"\n)\n\n\nfunc New() (*SvcClient, error) {\n\n\ttimeout := grpc.WithTimeout(time.Second * 2)\n\n\tg, err := grpc.Dial(address, grpc.WithInsecure(), timeout, interceptors.EnableGRPCTracingDialOption)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := SvcClient{\n\t\tservice: pb.NewWeatherClient(g),\n\t}\n\n\treturn &c, nil\n}\n\n\n\nfunc (c SvcClient) SearchByZip(ctx context.Context, token string, zip int64) (*pb.WeatherResponse, error) ", "output": "{\n\treq := &pb.WeatherRequest{Token: token, Zip: zip}\n\n\treturn c.service.GetCurrent(ctx, req)\n}"} {"input": "package models\n\nimport \"fmt\"\n\n\nvar RoomPool = make([] *Room, 0)\n\nfunc AddRoom(r *Room) {\n\tRoomPool = append(RoomPool, r)\n}\n\n\n\n\n\nfunc FindRoom(d string) (int, *Room) {\n\tfor i, v := range RoomPool {\n\t\tif v.Name == d {\n\t\t\treturn i, v\n\t\t}\n\t}\n\treturn -1, &Room{}\n}\n\n\nfunc RemoveRoom(r *Room) {\n\n\tindex, _ := FindRoom(r.Name)\n\n\tif index != -1 {\n\t\tRoomPool = append(RoomPool[:index], RoomPool[index + 1:]...)\n\t}\n}\n\n\n\n\n\n\n\n\nfunc ListRooms() (int, []string) {\n\tpool := make([]string, 0)\n\tfor _, obj := range RoomPool {\n\t\tpool = append(pool, obj.Name)\n\t}\n\treturn len(RoomPool), pool\n}\n\n\nfunc PoolBroadcast(m Message) {\n\tfor _, room := range RoomPool {\n\t\troom.RoomBroadcast(m)\n\t}\n}\n\n\nfunc GetAllClients() int {\n\n\tclientSum := 0\n\tfor _, room := range RoomPool {\n\t\tclientSum += len(room.ClientPool)\n\t}\n\treturn clientSum\n}\n\n\nfunc GetNumberOfRooms() int{\n\treturn len(RoomPool)\n}\n\nfunc RemoveClient(c *Client) ", "output": "{\n\tfor _, room := range RoomPool{\n\t\tif room.Name == c.Room {\n\t\t\tif room.HasClient(c) {\n\t\t\t\troom.DeleteClient(c)\n\t\t\t\tif room.ClientCount() == 0 {\n\t\t\t\t\tRemoveRoom(room)\n\t\t\t\t\tPoolBroadcast(NewMessage(map[string]string{\n\t\t\t\t\t\t\"connectedClients\": fmt.Sprintf(\"%v\", GetAllClients()),\n\t\t\t\t\t\t\"numberOfRooms\": fmt.Sprintf(\"%v\", GetNumberOfRooms()),\n\t\t\t\t\t}))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package smpeer\n\nimport (\n\t\"testing\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/fiorix/go-diameter/diam/datatype\"\n\t\"github.com/fiorix/go-diameter/diam/sm/smparser\"\n)\n\nfunc TestFromCER(t *testing.T) {\n\tcer := &smparser.CER{\n\t\tOriginHost: datatype.DiameterIdentity(\"foobar\"),\n\t\tOriginRealm: datatype.DiameterIdentity(\"test\"),\n\t}\n\tmeta := FromCER(cer)\n\tif meta.OriginHost != cer.OriginHost {\n\t\tt.Fatalf(\"Unexpected OriginHost. Want %q, have %q\",\n\t\t\tcer.OriginHost, meta.OriginHost)\n\t}\n\tif meta.OriginRealm != cer.OriginRealm {\n\t\tt.Fatalf(\"Unexpected OriginRealm. Want %q, have %q\",\n\t\t\tcer.OriginRealm, meta.OriginRealm)\n\t}\n\tctx := NewContext(context.Background(), meta)\n\tdata, ok := FromContext(ctx)\n\tif !ok {\n\t\tt.Fatal(\"Metadata not present in this context\")\n\t}\n\tif data != meta {\n\t\tt.Fatalf(\"Unexpected Metadata. Want %#v, have %#v\", meta, data)\n\t}\n}\n\n\n\nfunc TestFromCEA(t *testing.T) ", "output": "{\n\tcer := &smparser.CEA{\n\t\tOriginHost: datatype.DiameterIdentity(\"foobar\"),\n\t\tOriginRealm: datatype.DiameterIdentity(\"test\"),\n\t}\n\tmeta := FromCEA(cer)\n\tif meta.OriginHost != cer.OriginHost {\n\t\tt.Fatalf(\"Unexpected OriginHost. Want %q, have %q\",\n\t\t\tcer.OriginHost, meta.OriginHost)\n\t}\n\tif meta.OriginRealm != cer.OriginRealm {\n\t\tt.Fatalf(\"Unexpected OriginRealm. Want %q, have %q\",\n\t\t\tcer.OriginRealm, meta.OriginRealm)\n\t}\n\tctx := NewContext(context.Background(), meta)\n\tdata, ok := FromContext(ctx)\n\tif !ok {\n\t\tt.Fatal(\"Metadata not present in this context\")\n\t}\n\tif data != meta {\n\t\tt.Fatalf(\"Unexpected Metadata. Want %#v, have %#v\", meta, data)\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"context\"\n\n\t\"github.com/jaegertracing/jaeger/cmd/collector/app/processor\"\n\t\"github.com/jaegertracing/jaeger/model\"\n\t\"github.com/jaegertracing/jaeger/thrift-gen/sampling\"\n)\n\ntype mockSamplingStore struct{}\n\nfunc (s mockSamplingStore) GetSamplingStrategy(_ context.Context, serviceName string) (*sampling.SamplingStrategyResponse, error) {\n\treturn nil, nil\n}\n\ntype mockSpanProcessor struct {\n}\n\nfunc (p *mockSpanProcessor) Close() error {\n\treturn nil\n}\n\n\n\nfunc (p *mockSpanProcessor) ProcessSpans(spans []*model.Span, _ processor.SpansOptions) ([]bool, error) ", "output": "{\n\treturn []bool{}, nil\n}"} {"input": "package application\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/garyburd/redigo/redis\"\n)\n\ntype RedisDataStore struct {\n\tHost string\n\tPassword string\n\tpool *redis.Pool\n}\n\nfunc (s *RedisDataStore) checkConnection() error {\n\tc, err := redis.Dial(\"tcp\", s.Host)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = c.Do(\"AUTH\", s.Password)\n\tif err != nil {\n\t\tc.Close()\n\t\treturn err\n\t}\n\tc.Close()\n\treturn nil\n}\n\n\n\nfunc (s *RedisDataStore) Get(key string) ([]byte, error) {\n\tc := s.pool.Get()\n\tdefer c.Close()\n\n\tval, err := c.Do(\"GET\", key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbytes, ok := val.([]byte)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unable to type-assert response of type %T to []byte\", val)\n\t}\n\treturn bytes, nil\n}\n\nfunc (s *RedisDataStore) Set(key string, val []byte) error {\n\tc := s.pool.Get()\n\tdefer c.Close()\n\n\t_, err := c.Do(\"SET\", key, val)\n\treturn err\n}\n\nfunc (s *RedisDataStore) Initialize() error ", "output": "{\n\terr := s.checkConnection()\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.pool = &redis.Pool{\n\t\tMaxIdle: 5,\n\t\tMaxActive: 5,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.Dial(\"tcp\", s.Host)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t_, err = c.Do(\"AUTH\", s.Password)\n\t\t\tif err != nil {\n\t\t\t\tc.Close()\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, nil\n\t\t},\n\t}\n\treturn nil\n}"} {"input": "package image\n\n\ntype JPG struct {\n\tRaw []byte\n\tname string\n}\n\n\n\n\n\nfunc (j *JPG) Data(req Request) []byte {\n\treturn j.Raw\n}\n\nfunc (j *JPG) Name() string ", "output": "{\n\treturn j.name\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/mexisme/go-config/settings\"\n)\n\n\nfunc AddConfigItems(configKeys []string) {\n\tsettings.AddConfigItems(configKeys)\n}\n\n\nfunc AddConfigItemsWithPFlags(configKeys []string) error {\n\treturn settings.AddConfigItemsWithPFlags(configKeys)\n}\n\n\nfunc ApplyWith(key string, f func(interface{})) {\n\tsettings.ApplyWith(key, f)\n}\n\n\nfunc Get(key string) interface{} {\n\treturn settings.Get(key)\n}\n\n\nfunc GetBool(key string) bool {\n\treturn settings.GetBool(key)\n}\n\n\n\n\n\nfunc GetInt(key string) int {\n\treturn settings.GetInt(key)\n}\n\n\nfunc GetString(key string) string {\n\treturn settings.GetString(key)\n}\n\n\nfunc GetStringMap(key string) map[string]interface{} {\n\treturn settings.GetStringMap(key)\n}\n\n\nfunc GetStringMapString(key string) map[string]string {\n\treturn settings.GetStringMapString(key)\n}\n\n\nfunc GetStringSlice(key string) []string {\n\treturn settings.GetStringSlice(key)\n}\n\n\nfunc GetTime(key string) time.Time {\n\treturn settings.GetTime(key)\n}\n\n\nfunc GetDuration(key string) time.Duration {\n\treturn settings.GetDuration(key)\n}\n\n\nfunc IsSet(key string) bool {\n\treturn settings.IsSet(key)\n}\n\n\nfunc AllSettings() map[string]interface{} {\n\treturn settings.AllSettings()\n}\n\nfunc GetFloat64(key string) float64 ", "output": "{\n\treturn settings.GetFloat64(key)\n}"} {"input": "package rewriter\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestWriter(t *testing.T) ", "output": "{\n\tb := &bytes.Buffer{}\n\tw := New(b)\n\tfor i := 0; i < 2; i++ {\n\t\tfmt.Fprintln(w, \"foo\")\n\t}\n\tw.Flush()\n\twant := \"foo\\nfoo\\n\"\n\tif b.String() != want {\n\t\tt.Fatalf(\"want %q, got %q\", want, b.String())\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n\tmodelsv2 \"github.com/goharbor/harbor/src/controller/artifact\"\n\t\"net/http\"\n\n\t\"github.com/goharbor/harbor/src/chartserver\"\n\tchttp \"github.com/goharbor/harbor/src/common/http\"\n\t\"github.com/goharbor/harbor/src/common/http/modifier\"\n)\n\n\n\n\ntype Client interface {\n\tArtifactClient\n\tChartClient\n}\n\n\ntype ArtifactClient interface {\n\tListAllArtifacts(project, repository string) ([]*modelsv2.Artifact, error)\n\tDeleteArtifact(project, repository, digest string) error\n\tDeleteArtifactRepository(project, repository string) error\n}\n\n\ntype ChartClient interface {\n\tListAllCharts(project, repository string) ([]*chartserver.ChartVersion, error)\n\tDeleteChart(project, repository, version string) error\n\tDeleteChartRepository(project, repository string) error\n}\n\n\nfunc New(url string, httpclient *http.Client, authorizer modifier.Modifier) Client {\n\treturn &client{\n\t\turl: url,\n\t\thttpclient: chttp.NewClient(httpclient, authorizer),\n\t}\n}\n\ntype client struct {\n\turl string\n\thttpclient *chttp.Client\n}\n\n\n\nfunc (c *client) buildURL(path string) string ", "output": "{\n\treturn fmt.Sprintf(\"%s%s\", c.url, path)\n}"} {"input": "package taskqueue\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype ReqRepTask struct {\n\tMsg string\n\tResultChan chan string\n}\n\ntype ReqRepTaskQueue chan *ReqRepTask\n\n\n\nfunc reqRepTaskQueueWorker(queue ReqRepTaskQueue, index int) {\n\tfor task := range queue {\n\t\trandom := rand.Intn(3)\n\t\ttime.Sleep(time.Duration(random) * time.Second)\n\n\t\techo := fmt.Sprintf(\"ReqRepTaskQueueWorker [%d] echo: %s\", index, task.Msg)\n\t\ttask.ResultChan <- echo\n\n\t\tclose(task.ResultChan)\n\t}\n}\n\nfunc NewReqRepTaskQueue(workerNum int) ReqRepTaskQueue ", "output": "{\n\tqueue := make(ReqRepTaskQueue, 500)\n\n\tfor i := 0; i < workerNum; i++ {\n\t\tgo reqRepTaskQueueWorker(queue, i)\n\t}\n\n\treturn queue\n}"} {"input": "package httpgrpc\n\nimport (\n\t\"fmt\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/golang/protobuf/ptypes\"\n\t\"github.com/golang/protobuf/ptypes/any\"\n\tspb \"google.golang.org/genproto/googleapis/rpc/status\"\n\t\"google.golang.org/grpc/status\"\n)\n\n\n\n\nfunc Errorf(code int, tmpl string, args ...interface{}) error {\n\treturn ErrorFromHTTPResponse(&HTTPResponse{\n\t\tCode: int32(code),\n\t\tBody: []byte(fmt.Sprintf(tmpl, args...)),\n\t})\n}\n\n\n\n\n\nfunc HTTPResponseFromError(err error) (*HTTPResponse, bool) {\n\ts, ok := status.FromError(err)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tstatus := s.Proto()\n\tif len(status.Details) != 1 {\n\t\treturn nil, false\n\t}\n\n\tvar resp HTTPResponse\n\tif err := ptypes.UnmarshalAny(status.Details[0], &resp); err != nil {\n\t\tlog.Errorf(\"Got error containing non-response: %v\", err)\n\t\treturn nil, false\n\t}\n\n\treturn &resp, true\n}\n\nfunc ErrorFromHTTPResponse(resp *HTTPResponse) error ", "output": "{\n\ta, err := ptypes.MarshalAny(resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn status.ErrorProto(&spb.Status{\n\t\tCode: resp.Code,\n\t\tMessage: string(resp.Body),\n\t\tDetails: []*any.Any{a},\n\t})\n}"} {"input": "package exif\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\n\nfunc toUint16(bo binary.ByteOrder, buf []byte) uint16 {\n\tvar i uint16\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}\n\n\nfunc toInt16(bo binary.ByteOrder, buf []byte) int16 {\n\tvar i int16\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}\n\n\nfunc toUint32(bo binary.ByteOrder, buf []byte) uint32 {\n\tvar i uint32\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}\n\n\n\n\nfunc toInt32(bo binary.ByteOrder, buf []byte) int32 ", "output": "{\n\tvar i int32\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}"} {"input": "package core\n\nimport (\n\t\"net\"\n\t\"strconv\"\n)\n\nconst (\n\tAddrTypeIP = byte(0x01)\n\tAddrTypeDomain = byte(0x03)\n)\n\ntype VAddress struct {\n\tType byte\n\tIP net.IP\n\tDomain string\n\tPort uint16\n}\n\nfunc IPAddress(ip []byte, port uint16) VAddress {\n\treturn VAddress{\n\t\tAddrTypeIP,\n\t\tnet.IP(ip),\n\t\t\"\",\n\t\tport}\n}\n\nfunc DomainAddress(domain string, port uint16) VAddress {\n\treturn VAddress{\n\t\tAddrTypeDomain,\n\t\tnil,\n\t\tdomain,\n\t\tport}\n}\n\n\n\nfunc (addr VAddress) IsIPv6() bool {\n\treturn addr.Type == AddrTypeIP && len(addr.IP) == net.IPv6len\n}\n\nfunc (addr VAddress) IsDomain() bool {\n\treturn addr.Type == AddrTypeDomain\n}\n\nfunc (addr VAddress) String() string {\n\tvar host string\n\tswitch addr.Type {\n\tcase AddrTypeIP:\n\t\thost = addr.IP.String()\n\t\tif len(addr.IP) == net.IPv6len {\n\t\t\thost = \"[\" + host + \"]\"\n\t\t}\n\n\tcase AddrTypeDomain:\n\t\thost = addr.Domain\n\tdefault:\n\t\tpanic(\"Unknown Address Type \" + strconv.Itoa(int(addr.Type)))\n\t}\n\treturn host + \":\" + strconv.Itoa(int(addr.Port))\n}\n\nfunc (addr VAddress) IsIPv4() bool ", "output": "{\n\treturn addr.Type == AddrTypeIP && len(addr.IP) == net.IPv4len\n}"} {"input": "package cachestore\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\ntype CacheStore struct {\n\tstores map[string]*KVStore\n\tmutex sync.RWMutex\n}\n\n\n\nfunc (c *CacheStore) GetStore(svcName string) *KVStore {\n\tc.mutex.RLock()\n\tkvstore := c.stores[svcName]\n\tc.mutex.RUnlock()\n\n\treturn kvstore\n}\n\n\n\nfunc (c *CacheStore) CreateStore(svcName string) *KVStore {\n\tkvstore := NewKVStore()\n\tc.mutex.Lock()\n\tc.stores[svcName] = kvstore\n\tc.mutex.Unlock()\n\n\treturn kvstore\n}\n\n\nfunc (c *CacheStore) DeleteStore(svcName string) {\n\tc.mutex.Lock()\n\tdelete(c.stores, svcName)\n\tc.mutex.Unlock()\n}\n\n\nfunc (c *CacheStore) SetCache(svcName string, key string, value interface{}) {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore == nil {\n\t\tsvcStore = c.CreateStore(svcName)\n\t}\n\n\tsvcStore.Set(key, value)\n}\n\n\n\nfunc (c *CacheStore) GetCache(svcName string, key string) interface{} {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore == nil {\n\t\treturn nil\n\t}\n\treturn svcStore.Get(key)\n}\n\n\n\n\n\nfunc (c *CacheStore) MarshalJSON() ([]byte, error) {\n\tc.mutex.RLock()\n\tbytes, err := json.Marshal(&c.stores)\n\tc.mutex.RUnlock()\n\treturn bytes, err\n}\n\n\nfunc NewCacheStore() *CacheStore {\n\treturn &CacheStore{map[string]*KVStore{}, sync.RWMutex{}}\n}\n\nfunc (c *CacheStore) DeleteCache(svcName string, key string) ", "output": "{\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore != nil {\n\t\tsvcStore.Delete(key)\n\t}\n}"} {"input": "package main\n\n\n\nfunc (r *Record) queryCnt(conditionIndexes *[]int) (int64, error) ", "output": "{\n\n\ttable := r.Table\n\tstmt := \"SELECT count(*) FROM \" + table + \" WHERE \"\n\n\tfor i, v := range *conditionIndexes {\n\t\tif i == 0 {\n\t\t\tstmt += \" \" + r.Columns[v] + \"=\" + \"\\\"\" + r.Values[v] + \"\\\"\"\n\t\t\tcontinue\n\t\t}\n\t\tstmt += \" AND \" + \" \" + r.Columns[v] + \"=\" + \"\\\"\" + r.Values[v] + \"\\\"\"\n\t}\n\n\tvar cnt int64\n\terr := db.QueryRow(stmt).Scan(&cnt)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif cnt == 0 {\n\t\treturn 0, nil\n\t} else {\n\t\treturn cnt, nil\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"time\"\n)\n\n\nvar TopicCache = make([]*Topic, 0, 16)\n\ntype Topic struct {\n\tId int `json:\"id\"`\n\tTitle string `json:\"title\"`\n\tContent string `json:\"content\"`\n\tCreatedAt time.Time `json:\"created_at\"`\n}\n\nfunc FindTopic(id int) (*Topic, error) {\n\tif err := checkIndex(id); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn TopicCache[id-1], nil\n}\n\n\n\nfunc (t *Topic) Update() error {\n\tif err := checkIndex(t.Id); err != nil {\n\t\treturn err\n\t}\n\tTopicCache[t.Id-1] = t\n\treturn nil\n}\n\n\nfunc (t *Topic) Delete() error {\n\tif err := checkIndex(t.Id); err != nil {\n\t\treturn err\n\t}\n\tTopicCache[t.Id-1] = nil\n\treturn nil\n}\n\nfunc checkIndex(id int) error {\n\tif id > 0 && len(TopicCache) <= id-1 {\n\t\treturn errors.New(\"The topic is not exists!\")\n\t}\n\n\treturn nil\n}\n\nfunc (t *Topic) Create() error ", "output": "{\n\tt.Id = len(TopicCache) + 1\n\tt.CreatedAt = time.Now()\n\tTopicCache = append(TopicCache, t)\n\treturn nil\n}"} {"input": "package graphdriver\n\n\nimport \"C\"\nimport (\n\t\"path/filepath\"\n\t\"unsafe\"\n\n\t\"github.com/docker/docker/pkg/mount\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tFsMagicZfs = FsMagic(0x2fc12fc1)\n)\n\nvar (\n\tpriority = []string{\n\t\t\"zfs\",\n\t}\n\n\tFsNames = map[FsMagic]string{\n\t\tFsMagicZfs: \"zfs\",\n\t}\n)\n\n\nfunc GetFSMagic(rootpath string) (FsMagic, error) {\n\treturn 0, nil\n}\n\ntype fsChecker struct {\n\tt FsMagic\n}\n\n\n\n\nfunc NewFsChecker(t FsMagic) Checker {\n\treturn &fsChecker{\n\t\tt: t,\n\t}\n}\n\n\n\n\nfunc NewDefaultChecker() Checker {\n\treturn &defaultChecker{}\n}\n\ntype defaultChecker struct {\n}\n\nfunc (c *defaultChecker) IsMounted(path string) bool {\n\tm, _ := mount.Mounted(path)\n\treturn m\n}\n\n\n\nfunc Mounted(fsType FsMagic, mountPath string) (bool, error) {\n\n\tcs := C.CString(filepath.Dir(mountPath))\n\tdefer C.free(unsafe.Pointer(cs))\n\tbuf := C.getstatfs(cs)\n\tdefer C.free(unsafe.Pointer(buf))\n\n\tif (buf.f_basetype[0] != 122) || (buf.f_basetype[1] != 102) || (buf.f_basetype[2] != 115) ||\n\t\t(buf.f_basetype[3] != 0) {\n\t\tlogrus.Debugf(\"[zfs] no zfs dataset found for rootdir '%s'\", mountPath)\n\t\treturn false, ErrPrerequisites\n\t}\n\n\treturn true, nil\n}\n\nfunc (c *fsChecker) IsMounted(path string) bool ", "output": "{\n\tm, _ := Mounted(c.t, path)\n\treturn m\n}"} {"input": "package core\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\ntype ExportImageViaObjectStorageUriDetails struct {\n\n\tDestinationUri *string `mandatory:\"true\" json:\"destinationUri\"`\n}\n\nfunc (m ExportImageViaObjectStorageUriDetails) String() string {\n\treturn common.PointerString(m)\n}\n\n\n\n\nfunc (m ExportImageViaObjectStorageUriDetails) MarshalJSON() (buff []byte, e error) ", "output": "{\n\ttype MarshalTypeExportImageViaObjectStorageUriDetails ExportImageViaObjectStorageUriDetails\n\ts := struct {\n\t\tDiscriminatorParam string `json:\"destinationType\"`\n\t\tMarshalTypeExportImageViaObjectStorageUriDetails\n\t}{\n\t\t\"objectStorageUri\",\n\t\t(MarshalTypeExportImageViaObjectStorageUriDetails)(m),\n\t}\n\n\treturn json.Marshal(&s)\n}"} {"input": "package currencies\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"io\"\n\t\"net/http\"\n)\n\nconst (\n\tapiBase = \"https://openexchangerates.org/api\"\n\tlatest = apiBase + \"/latest.json?app_id=\"\n\tcurrencies = apiBase + \"/currencies?app_id=\"\n)\n\ntype OpenExchangeClient struct {\n\tAppID string\n\tClient *http.Client\n}\n\n\n\ntype exchangeRate struct {\n\tDisclaimer string `json:\"disclaimer\"`\n\tLicense string `json:\"license\"`\n\tTimestamp int64 `json:\"timestamp\"`\n\tBase string `json:\"base\"`\n\tRates map[string]float64 `json:\"rates\"`\n}\n\n\n\n\nfunc (c *OpenExchangeClient) GetLatest() (rates map[string]int64, err error) ", "output": "{\n\tif c.AppID == \"\" {\n\t\treturn nil, errors.New(\"No app Id\")\n\t}\n\tif c.Client == nil {\n\t\tc.Client = &http.Client{}\n\t}\n\n\tresp, err := c.Client.Get(latest + c.AppID)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if resp.StatusCode != 200 {\n\t\treturn nil, errors.New(resp.Status)\n\t}\n\n\tdefer resp.Body.Close()\n\n\tex := new(exchangeRate)\n\tdec := json.NewDecoder(resp.Body)\n\n\tif err := dec.Decode(&ex); err == io.EOF {\n\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\trates = make(map[string]int64)\n\tfor name, cur := range ex.Rates {\n\t\trates[name] = int64(cur * 100)\n\t}\n\treturn\n}"} {"input": "package builder\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\n\tvelerov1api \"github.com/vmware-tanzu/velero/pkg/apis/velero/v1\"\n)\n\n\ntype PodVolumeBackupBuilder struct {\n\tobject *velerov1api.PodVolumeBackup\n}\n\n\n\n\n\nfunc (b *PodVolumeBackupBuilder) Result() *velerov1api.PodVolumeBackup {\n\treturn b.object\n}\n\n\nfunc (b *PodVolumeBackupBuilder) ObjectMeta(opts ...ObjectMetaOpt) *PodVolumeBackupBuilder {\n\tfor _, opt := range opts {\n\t\topt(b.object)\n\t}\n\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) Phase(phase velerov1api.PodVolumeBackupPhase) *PodVolumeBackupBuilder {\n\tb.object.Status.Phase = phase\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) SnapshotID(snapshotID string) *PodVolumeBackupBuilder {\n\tb.object.Status.SnapshotID = snapshotID\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) PodName(name string) *PodVolumeBackupBuilder {\n\tb.object.Spec.Pod.Name = name\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) Volume(volume string) *PodVolumeBackupBuilder {\n\tb.object.Spec.Volume = volume\n\treturn b\n}\n\nfunc ForPodVolumeBackup(ns, name string) *PodVolumeBackupBuilder ", "output": "{\n\treturn &PodVolumeBackupBuilder{\n\t\tobject: &velerov1api.PodVolumeBackup{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tAPIVersion: velerov1api.SchemeGroupVersion.String(),\n\t\t\t\tKind: \"PodVolumeBackup\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: name,\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package ttlru\n\ntype ttlHeap []*entry\n\nfunc (h ttlHeap) Len() int {\n\treturn len(h)\n}\n\n\n\nfunc (h ttlHeap) Swap(i, j int) {\n\tif i == j || i < 0 || j < 0 {\n\t\treturn\n\t}\n\th[i], h[j] = h[j], h[i]\n\th[i].index, h[j].index = i, j\n}\n\nfunc (h *ttlHeap) Push(x interface{}) {\n\tn := len(*h)\n\titem := x.(*entry)\n\titem.index = n\n\t*h = append(*h, item)\n}\n\nfunc (h *ttlHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tif n == 0 {\n\t\treturn nil\n\t}\n\titem := old[n-1]\n\titem.index = -1 \n\t*h = old[0 : n-1]\n\treturn item\n}\n\nfunc (h ttlHeap) Less(i, j int) bool ", "output": "{\n\tif i == j || i < 0 || j < 0 {\n\t\treturn false\n\t}\n\treturn h[i].expires.Before(h[j].expires)\n}"} {"input": "package value\n\nimport (\n\t\"bytes\"\n)\n\n\n\n\n\nfunc Cons(x, y Value) *Cell {\n\treturn &Cell{Car: x, Cdr: y}\n}\n\n\ntype Cell struct {\n\tCar Value\n\tCdr Value\n}\n\n\nfunc (c *Cell) Walk(fn func(Value)) {\n\tcur := c\n\tfor {\n\t\tfn(cur.Car)\n\n\t\tif cur.Cdr == NIL {\n\t\t\treturn\n\t\t}\n\n\t\tnext, ok := cur.Cdr.(*Cell)\n\t\tif !ok {\n\t\t\tErrorf(\"cannot evaluate an improper list: %s\", c)\n\t\t}\n\t\tcur = next\n\t}\n}\n\nfunc (c *Cell) Equal(cmp Value) Value {\n\tx, ok := cmp.(*Cell)\n\tif !ok {\n\t\treturn NIL\n\t}\n\n\tif c.Car.Equal(x.Car) != T {\n\t\treturn NIL\n\t}\n\tif c.Cdr.Equal(x.Cdr) != T {\n\t\treturn NIL\n\t}\n\treturn T\n}\n\n\n\nfunc (c *Cell) String() string ", "output": "{\n\tvar buf bytes.Buffer\n\n\tbuf.WriteByte('(')\n\tfor {\n\t\tbuf.WriteString(c.Car.String())\n\n\t\tif c.Cdr == NIL {\n\t\t\tbreak\n\t\t}\n\n\t\tcdr, ok := c.Cdr.(*Cell)\n\t\tif !ok {\n\t\t\tbuf.WriteString(\" . \")\n\t\t\tbuf.WriteString(c.Cdr.String())\n\t\t\tbreak\n\t\t}\n\t\tc = cdr \n\n\t\tbuf.WriteByte(' ')\n\t}\n\tbuf.WriteByte(')')\n\n\treturn buf.String()\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\ntype EnumFlag struct {\n\tdefaultValue string\n\tvs []string\n\ti int\n}\n\n\n\nfunc NewEnumFlag(defaultValue string, vs []string) *EnumFlag {\n\tf := &EnumFlag{\n\t\ti: -1,\n\t\tvs: vs,\n\t\tdefaultValue: defaultValue,\n\t}\n\treturn f\n}\n\n\nfunc (f *EnumFlag) Type() string {\n\treturn \"{\" + strings.Join(f.vs, \",\") + \"}\"\n}\n\n\n\n\n\nfunc (f *EnumFlag) IsSet() bool {\n\treturn f.i != -1\n}\n\n\n\nfunc (f *EnumFlag) Set(s string) error {\n\tfor i := range f.vs {\n\t\tif f.vs[i] == s {\n\t\t\tf.i = i\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"must be one of %v\", f.Type())\n}\n\nfunc (f *EnumFlag) String() string ", "output": "{\n\tif f.i == -1 {\n\t\treturn f.defaultValue\n\t}\n\treturn f.vs[f.i]\n}"} {"input": "package machinery_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/RichardKnop/machinery/v2\"\n)\n\n\n\nfunc TestPreConsumeHandler(t *testing.T) {\n\tt.Parallel()\n\tworker := &machinery.Worker{}\n\n\tworker.SetPreConsumeHandler(SamplePreConsumeHandler)\n\tassert.True(t, worker.PreConsumeHandler())\n}\n\nfunc SamplePreConsumeHandler(w *machinery.Worker) bool {\n\treturn true\n}\n\nfunc TestRedactURL(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\tbroker := \"amqp://guest:guest@localhost:5672\"\n\tredactedURL := machinery.RedactURL(broker)\n\tassert.Equal(t, \"amqp://localhost:5672\", redactedURL)\n}"} {"input": "package devicemapper\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n)\n\nfunc major(device uint64) uint64 {\n\treturn (device >> 8) & 0xfff\n}\n\nfunc minor(device uint64) uint64 {\n\treturn (device & 0xff) | ((device >> 12) & 0xfff00)\n}\n\n\n\n\nfunc GetDevicePrefix(root string) (string, error) ", "output": "{\n\tst, err := os.Stat(root)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Error looking up dir %s: %s\", root, err)\n\t}\n\tsysSt := st.Sys().(*syscall.Stat_t)\n\treturn fmt.Sprintf(\"docker-%d:%d-%d\", major(sysSt.Dev), minor(sysSt.Dev), sysSt.Ino), nil\n}"} {"input": "package managedservices\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/\" + version.Number + \" managedservices/2019-04-01-preview\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package memorytopo\n\nimport (\n\t\"path\"\n\n\tlog \"github.com/golang/glog\"\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/youtube/vitess/go/vt/topo\"\n)\n\n\nfunc (c *Conn) NewMasterParticipation(name, id string) (topo.MasterParticipation, error) {\n\tc.factory.mu.Lock()\n\tdefer c.factory.mu.Unlock()\n\n\telectionPath := path.Join(electionsPath, name)\n\tif n := c.factory.getOrCreatePath(c.cell, electionPath); n == nil {\n\t\treturn nil, topo.ErrNoNode\n\t}\n\n\treturn &cMasterParticipation{\n\t\tc: c,\n\t\tname: name,\n\t\tid: id,\n\t\tstop: make(chan struct{}),\n\t\tdone: make(chan struct{}),\n\t}, nil\n}\n\n\n\n\n\n\ntype cMasterParticipation struct {\n\tc *Conn\n\n\tname string\n\n\tid string\n\n\tstop chan struct{}\n\n\tdone chan struct{}\n}\n\n\n\n\n\nfunc (mp *cMasterParticipation) Stop() {\n\tclose(mp.stop)\n\t<-mp.done\n}\n\n\nfunc (mp *cMasterParticipation) GetCurrentMasterID(ctx context.Context) (string, error) {\n\telectionPath := path.Join(electionsPath, mp.name)\n\n\tmp.c.factory.mu.Lock()\n\tdefer mp.c.factory.mu.Unlock()\n\n\tn := mp.c.factory.nodeByPath(mp.c.cell, electionPath)\n\tif n == nil {\n\t\treturn \"\", nil\n\t}\n\n\treturn n.lockContents, nil\n}\n\nfunc (mp *cMasterParticipation) WaitForMastership() (context.Context, error) ", "output": "{\n\tselect {\n\tcase <-mp.done:\n\t\treturn nil, topo.ErrInterrupted\n\tdefault:\n\t}\n\n\telectionPath := path.Join(electionsPath, mp.name)\n\tvar ld topo.LockDescriptor\n\n\tlockCtx, lockCancel := context.WithCancel(context.Background())\n\tgo func() {\n\t\tselect {\n\t\tcase <-mp.stop:\n\t\t\tif ld != nil {\n\t\t\t\tif err := ld.Unlock(context.Background()); err != nil {\n\t\t\t\t\tlog.Errorf(\"failed to unlock LockDescriptor %v: %v\", electionPath, err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tlockCancel()\n\t\t\tclose(mp.done)\n\t\t}\n\t}()\n\n\tvar err error\n\tld, err = mp.c.Lock(lockCtx, electionPath, mp.id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn lockCtx, nil\n}"} {"input": "package dbschema\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/gogolfing/dbschema/refactor\"\n)\n\nfunc collectingAppliedChangeSets(w io.Writer) {\n\tfmt.Fprintln(w, \"Collecting applied ChangeSets...\\n\")\n}\n\n\n\nfunc iterateChangeSetRows(\n\tchangeLog *refactor.ChangeLog,\n\tcsrows []*ChangeSetRow,\n\tcallback func(before []*refactor.ChangeSet, csr *ChangeSetRow) error,\n) error ", "output": "{\n\tprevId := \"\"\n\tfor _, csr := range csrows {\n\t\tchangeSetsBefore := changeLog.ChangeSetsSubSlice(prevId, csr.Id)\n\n\t\terr := callback(changeSetsBefore, csr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tprevId = csr.Id\n\t}\n\n\treturn nil\n}"} {"input": "package options\n\n\ntype UpdateOptions struct {\n\tArrayFilters *ArrayFilters\n\n\tBypassDocumentValidation *bool\n\n\tCollation *Collation\n\n\tHint interface{}\n\n\tUpsert *bool\n}\n\n\nfunc Update() *UpdateOptions {\n\treturn &UpdateOptions{}\n}\n\n\nfunc (uo *UpdateOptions) SetArrayFilters(af ArrayFilters) *UpdateOptions {\n\tuo.ArrayFilters = &af\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetBypassDocumentValidation(b bool) *UpdateOptions {\n\tuo.BypassDocumentValidation = &b\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetCollation(c *Collation) *UpdateOptions {\n\tuo.Collation = c\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetHint(h interface{}) *UpdateOptions {\n\tuo.Hint = h\n\treturn uo\n}\n\n\n\n\n\nfunc MergeUpdateOptions(opts ...*UpdateOptions) *UpdateOptions {\n\tuOpts := Update()\n\tfor _, uo := range opts {\n\t\tif uo == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif uo.ArrayFilters != nil {\n\t\t\tuOpts.ArrayFilters = uo.ArrayFilters\n\t\t}\n\t\tif uo.BypassDocumentValidation != nil {\n\t\t\tuOpts.BypassDocumentValidation = uo.BypassDocumentValidation\n\t\t}\n\t\tif uo.Collation != nil {\n\t\t\tuOpts.Collation = uo.Collation\n\t\t}\n\t\tif uo.Hint != nil {\n\t\t\tuOpts.Hint = uo.Hint\n\t\t}\n\t\tif uo.Upsert != nil {\n\t\t\tuOpts.Upsert = uo.Upsert\n\t\t}\n\t}\n\n\treturn uOpts\n}\n\nfunc (uo *UpdateOptions) SetUpsert(b bool) *UpdateOptions ", "output": "{\n\tuo.Upsert = &b\n\treturn uo\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\nconst (\n\tMaxFilterAddDataSize = 520\n)\n\n\n\n\n\n\ntype MsgFilterAdd struct {\n\tData []byte\n}\n\n\n\n\n\n\n\nfunc (msg *MsgFilterAdd) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filteradd message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterAdd.BtcEncode\", str)\n\t}\n\n\tsize := len(msg.Data)\n\tif size > MaxFilterAddDataSize {\n\t\tstr := fmt.Sprintf(\"filteradd size too large for message \"+\n\t\t\t\"[size %v, max %v]\", size, MaxFilterAddDataSize)\n\t\treturn messageError(\"MsgFilterAdd.BtcEncode\", str)\n\t}\n\n\treturn WriteVarBytes(w, pver, msg.Data)\n}\n\n\n\nfunc (msg *MsgFilterAdd) Command() string {\n\treturn CmdFilterAdd\n}\n\n\n\nfunc (msg *MsgFilterAdd) MaxPayloadLength(pver uint32) uint32 {\n\treturn uint32(VarIntSerializeSize(MaxFilterAddDataSize)) +\n\t\tMaxFilterAddDataSize\n}\n\n\n\nfunc NewMsgFilterAdd(data []byte) *MsgFilterAdd {\n\treturn &MsgFilterAdd{\n\t\tData: data,\n\t}\n}\n\nfunc (msg *MsgFilterAdd) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error ", "output": "{\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filteradd message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterAdd.BtcDecode\", str)\n\t}\n\n\tvar err error\n\tmsg.Data, err = ReadVarBytes(r, pver, MaxFilterAddDataSize,\n\t\t\"filteradd data\")\n\treturn err\n}"} {"input": "package elastic\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"gopkg.in/olivere/elastic.v5/uritemplates\"\n)\n\n\n\ntype RefreshService struct {\n\tclient *Client\n\tindex []string\n\tpretty bool\n}\n\n\nfunc NewRefreshService(client *Client) *RefreshService {\n\tbuilder := &RefreshService{\n\t\tclient: client,\n\t}\n\treturn builder\n}\n\n\nfunc (s *RefreshService) Index(index ...string) *RefreshService {\n\ts.index = append(s.index, index...)\n\treturn s\n}\n\n\nfunc (s *RefreshService) Pretty(pretty bool) *RefreshService {\n\ts.pretty = pretty\n\treturn s\n}\n\n\nfunc (s *RefreshService) buildURL() (string, url.Values, error) {\n\tvar err error\n\tvar path string\n\n\tif len(s.index) > 0 {\n\t\tpath, err = uritemplates.Expand(\"/{index}/_refresh\", map[string]string{\n\t\t\t\"index\": strings.Join(s.index, \",\"),\n\t\t})\n\t} else {\n\t\tpath = \"/_refresh\"\n\t}\n\tif err != nil {\n\t\treturn \"\", url.Values{}, err\n\t}\n\n\tparams := url.Values{}\n\tif s.pretty {\n\t\tparams.Set(\"pretty\", fmt.Sprintf(\"%v\", s.pretty))\n\t}\n\treturn path, params, nil\n}\n\n\n\n\n\n\n\ntype RefreshResult struct {\n\tShards shardsInfo `json:\"_shards,omitempty\"`\n}\n\nfunc (s *RefreshService) Do(ctx context.Context) (*RefreshResult, error) ", "output": "{\n\tpath, params, err := s.buildURL()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := s.client.PerformRequest(ctx, \"POST\", path, params, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := new(RefreshResult)\n\tif err := s.client.decoder.Decode(res.Body, ret); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}"} {"input": "package id3\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"io\"\n\t\"time\"\n)\n\nvar timestampFormats = []string{\n\t\"2006-01-02T15:04:05\",\n\t\"2006-01-02T15:04\",\n\t\"2006-01-02T15\",\n\t\"2006-01-02\",\n\t\"2006-01\",\n\t\"2006\",\n}\n\nfunc parseTime(timeStr string) (time.Time, error) {\n\tfor i := range timestampFormats {\n\t\tt, err := time.Parse(timestampFormats[i], timeStr)\n\t\tif err == nil {\n\t\t\treturn t, nil\n\t\t}\n\t}\n\n\treturn time.Time{}, errors.New(\"invalid time\")\n}\n\n\n\nfunc readUntilTerminator(term []byte, buf []byte) ([]byte, error) ", "output": "{\n\tfor i := 0; i+len(term)-1 < len(buf); i += len(term) {\n\t\tif bytes.Equal(term, buf[i:i+len(term)]) {\n\t\t\treturn buf[:i], nil\n\t\t}\n\t}\n\n\treturn nil, io.EOF\n}"} {"input": "package locus\n\nimport (\n\t\"github.com/gocircuit/circuit/use/circuit\"\n)\n\nfunc init() {\n\tcircuit.RegisterValue(XLocus{})\n}\n\ntype XLocus struct {\n\tl *Locus\n}\n\n\n\nfunc (x XLocus) Self() interface{} {\n\treturn x.l.Self()\n}\n\n\ntype YLocus struct {\n\tX circuit.PermX\n}\n\nfunc (y YLocus) GetPeers() map[string]*Peer {\n\tr := make(map[string]*Peer)\n\tfor _, p := range y.X.Call(\"GetPeers\")[0].([]*Peer) {\n\t\tr[p.Key()] = p\n\t}\n\treturn r\n}\n\nfunc (y YLocus) Self() *Peer {\n\treturn y.X.Call(\"Self\")[0].(*Peer)\n}\n\nfunc (x XLocus) GetPeers() []*Peer ", "output": "{\n\treturn x.l.GetPeers()\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\n\ntype printable interface {\n print()\n}\n\nfunc use(printables []printable) {\n for _, p := range printables {\n p.print()\n fmt.Println()\n }\n}\n\ntype human struct {\n name string\n age int\n}\n\n\n\n\nfunc (h *human) print() {\n fmt.Printf(\"%v.%d\", h.name, h.age)\n}\n\ntype account struct {\n bank string\n balance int\n}\n\n\n\nfunc main() {\n accounts := []account {\n {\"Bank of America\", 1000},\n {\"Chase\", 500},\n }\n humans := []human {\n {\"Steve\", 30},\n {\"Katie\", 28},\n {\"John\", 23},\n }\n printables := make([]printable, 0, len(accounts) + len(humans))\n for _, acc := range accounts {\n printables = append(printables, acc)\n }\n for i := range humans {\n \n \n \n printables = append(printables, &humans[i])\n }\n use(printables)\n}\n\nfunc (a account) print() ", "output": "{\n fmt.Printf(\"[%v] %d\", a.bank, a.balance)\n}"} {"input": "package resistor\n\n\n\nfunc Rser(resists ...float64) (Rtotal float64) {\n\tfor _, r := range resists {\n\t\tRtotal = Rtotal + r\n\t}\n\treturn\n}\n\n\n\n\n\nfunc Rpara(resists ...float64) (Rtotal float64) ", "output": "{\n\tfor _, r := range resists {\n\t\tRtotal = Rtotal + recip(r)\n\t}\n\treturn\n}"} {"input": "package ubuntu\n\nimport (\n\t\"github.com/megamsys/megdc/templates\"\n\t\"github.com/megamsys/urknall\"\n)\n\nvar ubuntunilavuremove *UbuntuNilavuRemove\n\nfunc init() {\n\tubuntunilavuremove = &UbuntuNilavuRemove{}\n\ttemplates.Register(\"UbuntuNilavuRemove\", ubuntunilavuremove)\n}\n\ntype UbuntuNilavuRemove struct{}\n\nfunc (tpl *UbuntuNilavuRemove) Render(p urknall.Package) {\n\tp.AddTemplate(\"nilavu\", &UbuntuNilavuRemoveTemplate{})\n}\n\nfunc (tpl *UbuntuNilavuRemove) Options(t *templates.Template) {\n}\n\n\n\ntype UbuntuNilavuRemoveTemplate struct{}\n\nfunc (m *UbuntuNilavuRemoveTemplate) Render(pkg urknall.Package) {\n\tpkg.AddCommands(\"verticenilavu\",\n\t\tRemovePackage(\"verticenilavu\"),\n\t\tRemovePackages(\"\"),\n\t\tPurgePackages(\"verticenilavu\"),\n\t\tShell(\"dpkg --get-selections megam*\"),\n\t)\n\tpkg.AddCommands(\"nilavu-clean\",\n\t\tShell(\"rm -r /var/lib/urknall/nilavu*\"),\n\t)\n}\n\nfunc (tpl *UbuntuNilavuRemove) Run(target urknall.Target) error ", "output": "{\n\treturn urknall.Run(target, &UbuntuNilavuRemove{})\n}"} {"input": "package cpf\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\n\nfunc sanitize(data string) string {\n\tdata = strings.Replace(data, \".\", \"\", -1)\n\tdata = strings.Replace(data, \"-\", \"\", -1)\n\treturn data\n}\n\nfunc valid(data string) (bool, error) {\n\tdata = sanitize(data)\n\n\tif len(data) != 11 {\n\t\treturn false, errors.New(\"Invalid length\")\n\t}\n\n\tif strings.Contains(blacklist, data) || !check(data) {\n\t\treturn false, errors.New(\"Invalid value\")\n\t}\n\n\treturn true, nil\n}\n\nconst blacklist = `00000000000\n11111111111\n22222222222\n33333333333\n44444444444\n55555555555\n66666666666\n77777777777\n88888888888\n99999999999\n12345678909`\n\nfunc stringToIntSlice(data string) (res []int) {\n\tfor _, d := range data {\n\t\tx, err := strconv.Atoi(string(d))\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, x)\n\t}\n\treturn\n}\n\nfunc verify(data []int, n int) int {\n\tvar total int\n\n\tfor i := 0; i < n; i++ {\n\t\ttotal += data[i] * (n + 1 - i)\n\t}\n\n\ttotal = total % 11\n\tif total < 2 {\n\t\treturn 0\n\t}\n\treturn 11 - total\n}\n\nfunc check(data string) bool {\n\treturn checkEach(data, 9) && checkEach(data, 10)\n}\n\nfunc checkEach(data string, n int) bool {\n\tfinal := verify(stringToIntSlice(data), n)\n\n\tx, err := strconv.Atoi(string(data[n]))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn final == x\n}\n\nfunc Valid(digits string) (bool, error) ", "output": "{\n\treturn valid(digits)\n}"} {"input": "package handlers\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/exercism/cli/api\"\n)\n\n\n\n\ntype Item struct {\n\t*api.Problem\n\tdir string\n\tisNew bool\n\tisUpdated bool\n}\n\n\n\n\n\nfunc (it *Item) Matches(filter HWFilter) bool {\n\tswitch filter {\n\tcase HWNew:\n\t\treturn it.isNew\n\tcase HWUpdated:\n\t\treturn it.isUpdated\n\t}\n\treturn true\n}\n\n\nfunc (it *Item) Save() error {\n\tif _, err := os.Stat(it.Path()); err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t\tit.isNew = true\n\t}\n\n\tfor name, text := range it.Files {\n\t\tfile := filepath.Join(it.Path(), name)\n\n\t\terr := os.MkdirAll(filepath.Dir(file), 0755)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err := os.Stat(file); err != nil {\n\t\t\tif !os.IsNotExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif !it.isNew {\n\t\t\t\tit.isUpdated = true\n\t\t\t}\n\n\t\t\terr = ioutil.WriteFile(file, []byte(text), 0644)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (it *Item) Path() string ", "output": "{\n\treturn filepath.Join(it.dir, it.TrackID, it.Slug)\n}"} {"input": "package iso20022\n\n\ntype TaxVoucher3 struct {\n\n\tIdentification *RestrictedFINXMax16Text `xml:\"Id\"`\n\n\tBargainDate *DateAndDateTimeChoice `xml:\"BrgnDt,omitempty\"`\n\n\tBargainSettlementDate *DateAndDateTimeChoice `xml:\"BrgnSttlmDt,omitempty\"`\n}\n\n\n\nfunc (t *TaxVoucher3) AddBargainDate() *DateAndDateTimeChoice {\n\tt.BargainDate = new(DateAndDateTimeChoice)\n\treturn t.BargainDate\n}\n\nfunc (t *TaxVoucher3) AddBargainSettlementDate() *DateAndDateTimeChoice {\n\tt.BargainSettlementDate = new(DateAndDateTimeChoice)\n\treturn t.BargainSettlementDate\n}\n\nfunc (t *TaxVoucher3) SetIdentification(value string) ", "output": "{\n\tt.Identification = (*RestrictedFINXMax16Text)(&value)\n}"} {"input": "package vmware\n\nimport (\n\t\"fmt\"\n\t\"github.com/mitchellh/multistep\"\n\t\"github.com/mitchellh/packer/packer\"\n\t\"time\"\n)\n\n\n\n\n\n\n\n\n\n\n\ntype stepRun struct {\n\tbootTime time.Time\n\tvmxPath string\n}\n\nfunc (s *stepRun) Run(state map[string]interface{}) multistep.StepAction {\n\tconfig := state[\"config\"].(*config)\n\tdriver := state[\"driver\"].(Driver)\n\tui := state[\"ui\"].(packer.Ui)\n\tvmxPath := state[\"vmx_path\"].(string)\n\n\ts.bootTime = time.Now()\n\ts.vmxPath = vmxPath\n\n\tui.Say(\"Starting virtual machine...\")\n\tif err := driver.Start(vmxPath); err != nil {\n\t\terr := fmt.Errorf(\"Error starting VM: %s\", err)\n\t\tstate[\"error\"] = err\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\tif int64(config.BootWait) > 0 {\n\t\tui.Say(fmt.Sprintf(\"Waiting %s for boot...\", config.BootWait.String()))\n\t\ttime.Sleep(config.BootWait)\n\t}\n\n\treturn multistep.ActionContinue\n}\n\n\n\nfunc (s *stepRun) Cleanup(state map[string]interface{}) ", "output": "{\n\tdriver := state[\"driver\"].(Driver)\n\tui := state[\"ui\"].(packer.Ui)\n\n\tif s.vmxPath != \"\" {\n\t\tsinceBootTime := time.Since(s.bootTime)\n\t\twaitBootTime := 5 * time.Second\n\t\tif sinceBootTime < waitBootTime {\n\t\t\tsleepTime := waitBootTime - sinceBootTime\n\t\t\tui.Say(fmt.Sprintf(\"Waiting %s to give VMware time to clean up...\", sleepTime.String()))\n\t\t\ttime.Sleep(sleepTime)\n\t\t}\n\n\t\trunning, _ := driver.IsRunning(s.vmxPath)\n\t\tif running {\n\t\t\tui.Say(\"Stopping virtual machine...\")\n\t\t\tif err := driver.Stop(s.vmxPath); err != nil {\n\t\t\t\tui.Error(fmt.Sprintf(\"Error stopping VM: %s\", err))\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n)\n\n\n\nfunc init() ", "output": "{\n err := parseOpts()\n if err != nil {\n usage(err.Error())\n }\n}"} {"input": "package metrics_test\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/gkarlik/quark-go\"\n\t\"github.com/gkarlik/quark-go/metrics/prometheus\"\n\t\"github.com/gkarlik/quark-go/middleware/metrics\"\n\ttr \"github.com/gkarlik/quark-go/service/trace/noop\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype TestService struct {\n\t*quark.ServiceBase\n}\n\ntype TestHttpHandler struct{}\n\nfunc (h *TestHttpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"OK\"))\n}\n\nfunc TestMetricsMiddleware(t *testing.T) {\n\ta, _ := quark.GetHostAddress(1234)\n\n\tts := &TestService{\n\t\tServiceBase: quark.NewService(\n\t\t\tquark.Name(\"TestService\"),\n\t\t\tquark.Version(\"1.0\"),\n\t\t\tquark.Address(a),\n\t\t\tquark.Metrics(prometheus.NewMetricsExposer()),\n\t\t\tquark.Tracer(tr.NewTracer())),\n\t}\n\tdefer ts.Dispose()\n\n\tmm := metrics.NewRequestMetricsMiddleware(ts)\n\tr, _ := http.NewRequest(http.MethodGet, \"/test\", nil)\n\tw := httptest.NewRecorder()\n\th := mm.Handle(&TestHttpHandler{})\n\th.ServeHTTP(w, r)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n}\n\n\n\nfunc TestMetricsMiddlewareWithNext(t *testing.T) ", "output": "{\n\ta, _ := quark.GetHostAddress(1234)\n\n\tts := &TestService{\n\t\tServiceBase: quark.NewService(\n\t\t\tquark.Name(\"TestService\"),\n\t\t\tquark.Version(\"1.0\"),\n\t\t\tquark.Address(a),\n\t\t\tquark.Metrics(prometheus.NewMetricsExposer()),\n\t\t\tquark.Tracer(tr.NewTracer())),\n\t}\n\tdefer ts.Dispose()\n\n\tmm := metrics.NewRequestMetricsMiddleware(ts)\n\tr, _ := http.NewRequest(http.MethodGet, \"/test\", nil)\n\tw := httptest.NewRecorder()\n\tth := &TestHttpHandler{}\n\tmm.HandleWithNext(w, r, th.ServeHTTP)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n}"} {"input": "package commands\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\tapi \"k8s.io/kops/pkg/apis/kops\"\n\t\"k8s.io/kops/util/pkg/reflectutils\"\n)\n\n\n\n\nfunc SetClusterFields(fields []string, cluster *api.Cluster) error ", "output": "{\n\tfor _, field := range fields {\n\t\tkv := strings.SplitN(field, \"=\", 2)\n\t\tif len(kv) != 2 {\n\t\t\treturn fmt.Errorf(\"unhandled field: %q\", field)\n\t\t}\n\n\t\tkey := kv[0]\n\t\tkey = strings.TrimPrefix(key, \"cluster.\")\n\n\t\tif err := reflectutils.SetString(cluster, key, kv[1]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package arm\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"encoding/base64\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\t\"golang.org/x/crypto/ssh\"\n\t\"time\"\n)\n\nconst (\n\tKeySize = 2048\n)\n\ntype OpenSshKeyPair struct {\n\tprivateKey *rsa.PrivateKey\n\tpublicKey ssh.PublicKey\n}\n\nfunc NewOpenSshKeyPair() (*OpenSshKeyPair, error) {\n\treturn NewOpenSshKeyPairWithSize(KeySize)\n}\n\nfunc NewOpenSshKeyPairWithSize(keySize int) (*OpenSshKeyPair, error) {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, keySize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpublicKey, err := ssh.NewPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &OpenSshKeyPair{\n\t\tprivateKey: privateKey,\n\t\tpublicKey: publicKey,\n\t}, nil\n}\n\n\n\nfunc (s *OpenSshKeyPair) PrivateKey() string {\n\tprivateKey := string(pem.EncodeToMemory(&pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(s.privateKey),\n\t}))\n\n\treturn privateKey\n}\n\nfunc (s *OpenSshKeyPair) AuthorizedKey() string ", "output": "{\n\treturn fmt.Sprintf(\"%s %s packer Azure Deployment%s\",\n\t\ts.publicKey.Type(),\n\t\tbase64.StdEncoding.EncodeToString(s.publicKey.Marshal()),\n\t\ttime.Now().Format(time.RFC3339))\n}"} {"input": "package iso20022\n\n\ntype AccountManagementConfirmation2 struct {\n\n\tConfirmationType *AccountManagementType2Code `xml:\"ConfTp\"`\n\n\tAccountApplicationIdentification *Max35Text `xml:\"AcctApplId,omitempty\"`\n\n\tClientReference *Max35Text `xml:\"ClntRef,omitempty\"`\n\n\tCounterpartyReference *AdditionalReference2 `xml:\"CtrPtyRef,omitempty\"`\n}\n\n\n\nfunc (a *AccountManagementConfirmation2) SetAccountApplicationIdentification(value string) {\n\ta.AccountApplicationIdentification = (*Max35Text)(&value)\n}\n\nfunc (a *AccountManagementConfirmation2) SetClientReference(value string) {\n\ta.ClientReference = (*Max35Text)(&value)\n}\n\nfunc (a *AccountManagementConfirmation2) AddCounterpartyReference() *AdditionalReference2 {\n\ta.CounterpartyReference = new(AdditionalReference2)\n\treturn a.CounterpartyReference\n}\n\nfunc (a *AccountManagementConfirmation2) SetConfirmationType(value string) ", "output": "{\n\ta.ConfirmationType = (*AccountManagementType2Code)(&value)\n}"} {"input": "package grpclog \n\nimport \"os\"\n\nvar logger = newLoggerV2()\n\n\nfunc V(l int) bool {\n\treturn logger.V(l)\n}\n\n\nfunc Info(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\nfunc Infof(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\nfunc Infoln(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\n\nfunc Warning(args ...interface{}) {\n\tlogger.Warning(args...)\n}\n\n\nfunc Warningf(format string, args ...interface{}) {\n\tlogger.Warningf(format, args...)\n}\n\n\nfunc Warningln(args ...interface{}) {\n\tlogger.Warningln(args...)\n}\n\n\nfunc Error(args ...interface{}) {\n\tlogger.Error(args...)\n}\n\n\nfunc Errorf(format string, args ...interface{}) {\n\tlogger.Errorf(format, args...)\n}\n\n\n\n\n\n\nfunc Fatal(args ...interface{}) {\n\tlogger.Fatal(args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalf(format string, args ...interface{}) {\n\tlogger.Fatalf(format, args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalln(args ...interface{}) {\n\tlogger.Fatalln(args...)\n\tos.Exit(1)\n}\n\n\n\n\nfunc Print(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\n\n\nfunc Printf(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\n\n\nfunc Println(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\nfunc Errorln(args ...interface{}) ", "output": "{\n\tlogger.Errorln(args...)\n}"} {"input": "package nodes\n\nimport (\n\t\"github.com/gonum/graph\"\n\n\tappsv1 \"github.com/openshift/api/apps/v1\"\n\tosgraph \"github.com/openshift/oc/pkg/helpers/graph/genericgraph\"\n\tkubegraph \"github.com/openshift/oc/pkg/helpers/graph/kubegraph/nodes\"\n)\n\n\nfunc EnsureDeploymentConfigNode(g osgraph.MutableUniqueGraph, dc *appsv1.DeploymentConfig) *DeploymentConfigNode {\n\tdcName := DeploymentConfigNodeName(dc)\n\tdcNode := osgraph.EnsureUnique(\n\t\tg,\n\t\tdcName,\n\t\tfunc(node osgraph.Node) graph.Node {\n\t\t\treturn &DeploymentConfigNode{Node: node, DeploymentConfig: dc, IsFound: true}\n\t\t},\n\t).(*DeploymentConfigNode)\n\n\tif dc.Spec.Template != nil {\n\t\tpodTemplateSpecNode := kubegraph.EnsurePodTemplateSpecNode(g, dc.Spec.Template, dc.Namespace, dcName)\n\t\tg.AddEdge(dcNode, podTemplateSpecNode, osgraph.ContainsEdgeKind)\n\t}\n\n\treturn dcNode\n}\n\n\n\nfunc FindOrCreateSyntheticDeploymentConfigNode(g osgraph.MutableUniqueGraph, dc *appsv1.DeploymentConfig) *DeploymentConfigNode ", "output": "{\n\treturn osgraph.EnsureUnique(\n\t\tg,\n\t\tDeploymentConfigNodeName(dc),\n\t\tfunc(node osgraph.Node) graph.Node {\n\t\t\treturn &DeploymentConfigNode{Node: node, DeploymentConfig: dc, IsFound: false}\n\t\t},\n\t).(*DeploymentConfigNode)\n}"} {"input": "package common\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/axgle/mahonia\"\n\t\"github.com/saintfish/chardet\"\n)\n\n\nfunc RequestURL(url string) (*http.Response, error) {\n\tclient := &http.Client{}\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Set(\"User-Agent\", GetUserAgent())\n\tresponse, err := client.Do(req)\n\treturn response, err\n}\n\n\n\n\n\nfunc DetectBody(body []byte) string {\n\tvar bodyString string\n\tdetector := chardet.NewTextDetector()\n\tresult, err := detector.DetectBest(body)\n\tif err != nil {\n\t\treturn string(body)\n\t}\n\tif strings.Contains(strings.ToLower(result.Charset), \"utf\") {\n\t\tbodyString = string(body)\n\t} else {\n\t\tbodyString = mahonia.NewDecoder(\"gbk\").ConvertString(string(body))\n\t}\n\treturn bodyString\n}\n\n\nfunc StringInSlice(domain string, list []string) bool {\n\tfor _, eachDomain := range list {\n\t\tif domain == eachDomain {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc ReturnDomain(currentURL string) string {\n\turlParse, _ := url.Parse(currentURL)\n\tdomain := urlParse.Host\n\treturn domain\n}\n\nfunc QuickestURL(index int, url string) int ", "output": "{\n\t_, err := http.Get(url)\n\tif err != nil {\n\t\treturn -1\n\t}\n\treturn index\n}"} {"input": "package provider\n\nimport (\n\t\"strings\"\n)\n\n\ntype DomainFilter struct {\n\tfilters []string\n\texclude []string\n}\n\n\nfunc prepareFilters(filters []string) []string {\n\tfs := make([]string, len(filters))\n\tfor i, domain := range filters {\n\t\tfs[i] = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), \".\"))\n\t}\n\treturn fs\n}\n\n\nfunc NewDomainFilterWithExclusions(domainFilters []string, excludeDomains []string) DomainFilter {\n\treturn DomainFilter{prepareFilters(domainFilters), prepareFilters(excludeDomains)}\n}\n\n\n\n\n\nfunc (df DomainFilter) Match(domain string) bool {\n\treturn matchFilter(df.filters, domain, true) && !matchFilter(df.exclude, domain, false)\n}\n\n\n\n\nfunc matchFilter(filters []string, domain string, emptyval bool) bool {\n\tif len(filters) == 0 {\n\t\treturn emptyval\n\t}\n\n\tfor _, filter := range filters {\n\t\tstrippedDomain := strings.ToLower(strings.TrimSuffix(domain, \".\"))\n\n\t\tif filter == \"\" {\n\t\t\treturn emptyval\n\t\t} else if strings.HasPrefix(filter, \".\") && strings.HasSuffix(strippedDomain, filter) {\n\t\t\treturn true\n\t\t} else if strings.Count(strippedDomain, \".\") == strings.Count(filter, \".\") {\n\t\t\tif strippedDomain == filter {\n\t\t\t\treturn true\n\t\t\t}\n\t\t} else if strings.HasSuffix(strippedDomain, \".\"+filter) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (df DomainFilter) IsConfigured() bool {\n\tif len(df.filters) == 1 {\n\t\treturn df.filters[0] != \"\"\n\t}\n\treturn len(df.filters) > 0\n}\n\nfunc NewDomainFilter(domainFilters []string) DomainFilter ", "output": "{\n\treturn DomainFilter{prepareFilters(domainFilters), []string{}}\n}"} {"input": "package transporttest\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\n\ntype ContextMatcher struct {\n\tt *testing.T\n\tttl time.Duration\n\n\tTTLDelta time.Duration\n}\n\n\ntype ContextMatcherOption interface {\n\trun(*ContextMatcher)\n}\n\n\n\ntype ContextTTL time.Duration\n\nfunc (ttl ContextTTL) run(c *ContextMatcher) {\n\tc.ttl = time.Duration(ttl)\n}\n\n\n\n\n\n\n\n\nfunc (c *ContextMatcher) Matches(got interface{}) bool {\n\tctx, ok := got.(context.Context)\n\tif !ok {\n\t\tc.t.Logf(\"expected a Context but got a %T: %v\", got, got)\n\t\treturn false\n\t}\n\n\tif c.ttl != 0 {\n\t\td, ok := ctx.Deadline()\n\t\tif !ok {\n\t\t\tc.t.Logf(\n\t\t\t\t\"expected Context to have a TTL of %v but it has no deadline\", c.ttl)\n\t\t\treturn false\n\t\t}\n\n\t\tttl := time.Until(d)\n\t\tmaxTTL := c.ttl + c.TTLDelta\n\t\tminTTL := c.ttl - c.TTLDelta\n\t\tif ttl > maxTTL || ttl < minTTL {\n\t\t\tc.t.Logf(\"TTL out of expected bounds: %v < %v < %v\", minTTL, ttl, maxTTL)\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (c *ContextMatcher) String() string {\n\treturn fmt.Sprintf(\"ContextMatcher(TTL:%v±%v)\", c.ttl, c.TTLDelta)\n}\n\nfunc NewContextMatcher(t *testing.T, options ...ContextMatcherOption) *ContextMatcher ", "output": "{\n\tmatcher := &ContextMatcher{t: t, TTLDelta: DefaultTTLDelta}\n\tfor _, opt := range options {\n\t\topt.run(matcher)\n\t}\n\treturn matcher\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gorilla/mux\"\n\n\t\"github.com/lxc/lxd/lxd/resources\"\n\t\"github.com/lxc/lxd/lxd/response\"\n\tstoragePools \"github.com/lxc/lxd/lxd/storage\"\n\t\"github.com/lxc/lxd/shared/api\"\n)\n\nvar api10ResourcesCmd = APIEndpoint{\n\tPath: \"resources\",\n\n\tGet: APIEndpointAction{Handler: api10ResourcesGet, AccessHandler: allowAuthenticated},\n}\n\nvar storagePoolResourcesCmd = APIEndpoint{\n\tPath: \"storage-pools/{name}/resources\",\n\n\tGet: APIEndpointAction{Handler: storagePoolResourcesGet, AccessHandler: allowAuthenticated},\n}\n\n\n\nfunc api10ResourcesGet(d *Daemon, r *http.Request) response.Response {\n\tresp := forwardedResponseIfTargetIsRemote(d, r)\n\tif resp != nil {\n\t\treturn resp\n\t}\n\n\tres, err := resources.GetResources()\n\tif err != nil {\n\t\treturn response.SmartError(err)\n\t}\n\n\treturn response.SyncResponse(true, res)\n}\n\n\n\n\n\nfunc storagePoolResourcesGet(d *Daemon, r *http.Request) response.Response ", "output": "{\n\tresp := forwardedResponseIfTargetIsRemote(d, r)\n\tif resp != nil {\n\t\treturn resp\n\t}\n\n\tpoolName := mux.Vars(r)[\"name\"]\n\tvar res *api.ResourcesStoragePool\n\n\tpool, err := storagePools.GetPoolByName(d.State(), poolName)\n\tif err != nil {\n\t\treturn response.InternalError(err)\n\t}\n\n\tres, err = pool.GetResources()\n\tif err != nil {\n\t\treturn response.InternalError(err)\n\t}\n\n\treturn response.SyncResponse(true, res)\n}"} {"input": "package main\n\nimport (\n\t\"code.google.com/p/go.crypto/ssh/terminal\"\n\t\"fmt\"\n\t\"os\"\n)\n\n\n\ntype uterm struct {\n\ts *terminal.State\n\tt *terminal.Terminal\n}\n\nfunc newTerm() Term {\n\tu := new(uterm)\n\tvar err error\n\tu.s, err = terminal.MakeRaw(0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tu.t = terminal.NewTerminal(os.Stdin, \"lixian >> \")\n\treturn u\n}\n\nfunc (u *uterm) Restore() {\n\tterminal.Restore(0, u.s)\n}\n\nfunc (u *uterm) ReadLine() (string, error) {\n\treturn u.t.ReadLine()\n}\n\nfunc clearscr() ", "output": "{\n\tfmt.Printf(\"%c[2J%c[0;0H\", 27, 27)\n}"} {"input": "package twitch\n\nimport (\n\t\"net/http\"\n\t\"testing\"\n)\n\n\n\nfunc TestTeamsList(t *testing.T) {\n\ttc := NewClient(&http.Client{})\n\n\topt := &ListOptions{\n\t\tLimit: 1,\n\t\tOffset: 0,\n\t}\n\n\t_, err := tc.Teams.List(opt)\n\n\tif err != nil {\n\t\tt.Errorf(\"error not nil: %+v\", err)\n\t}\n\n}\n\nfunc TestTeamsTeam(t *testing.T) ", "output": "{\n\ttc := NewClient(&http.Client{})\n\n\t_, err := tc.Teams.Team(\"testteam\")\n\n\tif err != nil {\n\t\tt.Errorf(\"error not nil: %+v\", err)\n\t}\n\n}"} {"input": "package openid\n\nimport (\n\t\"testing\"\n\t\"bytes\"\n)\n\n\n\ntype NormalizeIdentifierTest struct {\n\tin, out string\n\tt int\n}\n\nvar NormalizeIdentifierTests = []NormalizeIdentifierTest{\n\tNormalizeIdentifierTest{\"https://example.com/\", \"https://example.com/\", IdentifierURL},\n\tNormalizeIdentifierTest{\"http://example.com/user\", \"http://example.com/user\", IdentifierURL},\n\tNormalizeIdentifierTest{\"http://example.com/user/\", \"http://example.com/user/\", IdentifierURL},\n\tNormalizeIdentifierTest{\"http://example.com/\", \"http://example.com/\", IdentifierURL},\n\tNormalizeIdentifierTest{\"=example\", \"=example\", IdentifierXRI},\n\tNormalizeIdentifierTest{\"xri://=example\", \"=example\", IdentifierXRI},\n}\n\n\n\n\n\nvar Identifiers = []string{\n\t\"https://www.google.com/accounts/o8/id\",\n\t\"orange.fr\",\n\t\"yahoo.com\",\n}\n\n\nfunc TestGetRedirectURL(t *testing.T) {\n\tfor _, url := range Identifiers {\n\t\t_, err := GetRedirectURL(url, \"http://example.com\", \"/loginCheck\")\n\t\tif err != nil {\n\t\t\tt.Errorf(\"GetRedirectURL() returned the error: %s\", err.String())\n\t\t}\n\t}\n}\n\nfunc TestNormalizeIdentifier(testing *testing.T) ", "output": "{\n\tfor _, nit := range NormalizeIdentifierTests {\n\t\tv, t := NormalizeIdentifier(nit.in)\n\t\tif !bytes.Equal([]byte(v), []byte(nit.out)) || t != nit.t {\n\t\t\ttesting.Errorf(\"NormalizeIdentifier(%s) = (%s, %d) want (%s, %d).\", nit.in, v, t, nit.out, nit.t)\n\t\t}\n\t}\n}"} {"input": "package godo\n\nimport(\n\t\"github.com/jmoiron/modl\"\n\t\"database/sql\"\n\t_ \"github.com/mattn/go-sqlite3\"\n\t\"log\"\n)\n\nvar Dbmap *modl.DbMap\n\nfunc InitDb(dbname string) *modl.DbMap {\n\tdb, err := sql.Open(\"sqlite3\", \"/tmp/\"+dbname)\n\tCheckErr(err, \"sql.Open failed\")\n\n\tdbmap := modl.NewDbMap(db, modl.SqliteDialect{})\n\n\tdbmap.AddTableWithName(Task{}, \"tasks\").SetKeys(true, \"ID\")\n\tdbmap.AddTableWithName(Project{}, \"projects\").SetKeys(true, \"ID\")\n\tDbmap = dbmap\n\n\terr = dbmap.CreateTablesIfNotExists()\n\tCheckErr(err, \"Create tables failed\")\n\n\treturn dbmap\n}\n\n\n\nfunc ResetDatabase() {\n\tDbmap.TruncateTables()\n}\n\nfunc CheckErr(err error, msg string) ", "output": "{\n\tif err != nil {\n\t\tlog.Fatalln(msg, err)\n\t}\n}"} {"input": "package tfs\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/richardwilkes/toolbox/errs\"\n)\n\ntype vfs struct {\n\tstorage string\n\tname string\n\toffset int64\n\tlength int64\n\tmode os.FileMode\n\tmodTime time.Time\n\tchildren []*vfs\n}\n\nfunc (v *vfs) Name() string {\n\treturn v.name\n}\n\nfunc (v *vfs) Size() int64 {\n\treturn v.length\n}\n\nfunc (v *vfs) Mode() os.FileMode {\n\treturn v.mode\n}\n\nfunc (v *vfs) ModTime() time.Time {\n\treturn v.modTime\n}\n\n\n\nfunc (v *vfs) Sys() interface{} {\n\treturn nil\n}\n\nfunc (v *vfs) open() (http.File, error) {\n\tif v.IsDir() {\n\t\treturn &vdir{owner: v}, nil\n\t}\n\tf, err := os.Open(v.storage)\n\tif err != nil {\n\t\treturn nil, errs.NewWithCausef(err, \"Unable to open %s\", v.name)\n\t}\n\treturn &vfile{\n\t\towner: v,\n\t\tfile: f,\n\t\tsr: io.NewSectionReader(f, v.offset, v.length),\n\t}, nil\n}\n\nfunc (v *vfs) IsDir() bool ", "output": "{\n\treturn (v.mode & os.ModeDir) == os.ModeDir\n}"} {"input": "package msgraph\n\nimport \"context\"\n\n\ntype FieldValueSetRequestBuilder struct{ BaseRequestBuilder }\n\n\nfunc (b *FieldValueSetRequestBuilder) Request() *FieldValueSetRequest {\n\treturn &FieldValueSetRequest{\n\t\tBaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client},\n\t}\n}\n\n\ntype FieldValueSetRequest struct{ BaseRequest }\n\n\n\n\n\nfunc (r *FieldValueSetRequest) Update(ctx context.Context, reqObj *FieldValueSet) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}\n\n\nfunc (r *FieldValueSetRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}\n\nfunc (r *FieldValueSetRequest) Get(ctx context.Context) (resObj *FieldValueSet, err error) ", "output": "{\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\terr = r.JSONRequest(ctx, \"GET\", query, nil, &resObj)\n\treturn\n}"} {"input": "package example\n\nimport (\n\t\"testing\"\n\t\"github.com/remogatto/prettytest\"\n\t\"launchpad.net/gocheck\"\n)\n\n\n\ntype testSuite struct {\n\tprettytest.Suite\n}\n\nfunc TestRunner(t *testing.T) {\n\tprettytest.Run(\n\t\tt,\n\t\tnew(testSuite),\n\t)\n}\n\n\n\n\n\n\nfunc (t *testSuite) TestTrueIsTrue() {\n\tt.True(true)\n}\n\nfunc (t *testSuite) TestEquality() {\n\tt.Equal(\"awesome\", \"awesome\")\n}\n\n\n\nfunc (t *testSuite) TestGoCheck() {\n\tt.Check(\"foo\", gocheck.Equals, \"foo\")\n}\n\n\n\nfunc (t *testSuite) TestMustFail() {\n\tt.Error(\"This test must fail.\")\n\tt.MustFail()\n}\n\nfunc (t *testSuite) TestInequality() {\n\tt.Equal(\"awesome\", \"ugly\")\n\tt.MustFail()\n}\n\nfunc (t *testSuite) TestNot() ", "output": "{\n\tt.Not(t.Path(\"foo\"))\n}"} {"input": "package rng\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\n\ntype CauchyGenerator struct {\n\tuniform *UniformGenerator\n}\n\n\n\n\n\n\n\nfunc (crng CauchyGenerator) Cauchy(x0, gamma float64) float64 {\n\tif !(gamma > 0.0) {\n\t\tpanic(fmt.Sprintf(\"Invalid parameter gamma: %.2f\", gamma))\n\t}\n\treturn crng.cauchy(x0, gamma)\n}\n\n\nfunc (crng CauchyGenerator) StandardCauchy() float64 {\n\treturn crng.cauchy(0.0, 1.0)\n}\n\nfunc (crng CauchyGenerator) cauchy(x0, gamma float64) float64 {\n\treturn x0 + gamma*math.Tan(math.Pi*(crng.uniform.Float64()-0.5))\n}\n\nfunc NewCauchyGenerator(seed int64) *CauchyGenerator ", "output": "{\n\turng := NewUniformGenerator(seed)\n\treturn &CauchyGenerator{urng}\n}"} {"input": "package iso20022\n\n\ntype RemittanceInformation8 struct {\n\n\tRemittanceIdentification *Max35Text `xml:\"RmtId,omitempty\"`\n\n\tUnstructured []*Max140Text `xml:\"Ustrd,omitempty\"`\n\n\tStructured []*StructuredRemittanceInformation10 `xml:\"Strd,omitempty\"`\n\n\tOriginalPaymentInformation *OriginalPaymentInformation6 `xml:\"OrgnlPmtInf\"`\n}\n\nfunc (r *RemittanceInformation8) SetRemittanceIdentification(value string) {\n\tr.RemittanceIdentification = (*Max35Text)(&value)\n}\n\n\n\nfunc (r *RemittanceInformation8) AddStructured() *StructuredRemittanceInformation10 {\n\tnewValue := new(StructuredRemittanceInformation10)\n\tr.Structured = append(r.Structured, newValue)\n\treturn newValue\n}\n\nfunc (r *RemittanceInformation8) AddOriginalPaymentInformation() *OriginalPaymentInformation6 {\n\tr.OriginalPaymentInformation = new(OriginalPaymentInformation6)\n\treturn r.OriginalPaymentInformation\n}\n\nfunc (r *RemittanceInformation8) AddUnstructured(value string) ", "output": "{\n\tr.Unstructured = append(r.Unstructured, (*Max140Text)(&value))\n}"} {"input": "package remotecache\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/bradfitz/gomemcache/memcache\"\n\t\"github.com/grafana/grafana/pkg/setting\"\n)\n\nconst memcachedCacheType = \"memcached\"\n\ntype memcachedStorage struct {\n\tc *memcache.Client\n}\n\nfunc newMemcachedStorage(opts *setting.RemoteCacheOptions) *memcachedStorage {\n\treturn &memcachedStorage{\n\t\tc: memcache.New(opts.ConnStr),\n\t}\n}\n\nfunc newItem(sid string, data []byte, expire int32) *memcache.Item {\n\treturn &memcache.Item{\n\t\tKey: sid,\n\t\tValue: data,\n\t\tExpiration: expire,\n\t}\n}\n\n\nfunc (s *memcachedStorage) Set(ctx context.Context, key string, val interface{}, expires time.Duration) error {\n\titem := &cachedItem{Val: val}\n\tbytes, err := encodeGob(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar expiresInSeconds int64\n\tif expires != 0 {\n\t\texpiresInSeconds = int64(expires) / int64(time.Second)\n\t}\n\n\tmemcachedItem := newItem(key, bytes, int32(expiresInSeconds))\n\treturn s.c.Set(memcachedItem)\n}\n\n\n\n\n\nfunc (s *memcachedStorage) Delete(ctx context.Context, key string) error {\n\treturn s.c.Delete(key)\n}\n\nfunc (s *memcachedStorage) Get(ctx context.Context, key string) (interface{}, error) ", "output": "{\n\tmemcachedItem, err := s.c.Get(key)\n\tif err != nil && err.Error() == \"memcache: cache miss\" {\n\t\treturn nil, ErrCacheItemNotFound\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titem := &cachedItem{}\n\n\terr = decodeGob(memcachedItem.Value, item)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn item.Val, nil\n}"} {"input": "package tcp\n\nimport (\n\t\"bufio\"\n\t\"log\"\n\t\"net\"\n)\n\nconst tcp_port string = \"0.0.0.0:5170\"\n\n\n\n\nfunc handleConnection(c net.Conn, ch chan string){\n\tdefer c.Close()\n\tfor {\n\t\tmessage, err := bufio.NewReader(c).ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbreak\n\t\t}\n\n\t\tch <- message;\n\t}\n}\n\nfunc ListenAndServe(ch chan string) ", "output": "{\n\tl, err := net.Listen(\"tcp\", tcp_port)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tlog.Println(\"New incomming connection\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"%v\", err.Error())\n\t\t}\n\t\tgo handleConnection(conn, ch)\n\t}\n}"} {"input": "package certificates\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gophercloud/gophercloud\"\n)\n\n\n\ntype CreateOptsBuilder interface {\n\tToCertificateCreateMap() (map[string]interface{}, error)\n}\n\n\ntype CreateOpts struct {\n\tClusterUUID string `json:\"cluster_uuid,omitempty\" xor:\"BayUUID\"`\n\tBayUUID string `json:\"bay_uuid,omitempty\" xor:\"ClusterUUID\"`\n\tCSR string `json:\"csr\" required:\"true\"`\n}\n\n\nfunc (opts CreateOpts) ToCertificateCreateMap() (map[string]interface{}, error) {\n\treturn gophercloud.BuildRequestBody(opts, \"\")\n}\n\n\n\n\n\nfunc Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToCertificateCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\n\tvar result *http.Response\n\tresult, r.Err = client.Post(createURL(client), b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{201},\n\t})\n\n\tif r.Err == nil {\n\t\tr.Header = result.Header\n\t}\n\n\treturn\n}\n\n\nfunc Update(client *gophercloud.ServiceClient, clusterID string) (r UpdateResult) {\n\t_, r.Err = client.Patch(updateURL(client, clusterID), nil, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{202},\n\t})\n\n\treturn\n}\n\nfunc Get(client *gophercloud.ServiceClient, clusterID string) (r GetResult) ", "output": "{\n\turl := getURL(client, clusterID)\n\n\t_, r.Err = client.Get(url, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{200},\n\t})\n\n\treturn\n}"} {"input": "package layers\n\nimport (\n\t\"github.com/vtolstov/gopacket\"\n)\n\n\n\ntype BaseLayer struct {\n\tContents []byte\n\tPayload []byte\n}\n\n\nfunc (b *BaseLayer) LayerContents() []byte { return b.Contents }\n\n\n\n\ntype layerDecodingLayer interface {\n\tgopacket.Layer\n\tDecodeFromBytes([]byte, gopacket.DecodeFeedback) error\n\tNextLayerType() gopacket.LayerType\n}\n\nfunc decodingLayerDecoder(d layerDecodingLayer, data []byte, p gopacket.PacketBuilder) error {\n\terr := d.DecodeFromBytes(data, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.AddLayer(d)\n\tnext := d.NextLayerType()\n\tif next == gopacket.LayerTypeZero {\n\t\treturn nil\n\t}\n\treturn p.NextDecoder(next)\n}\n\n\nvar lotsOfZeros [1024]byte\n\nfunc (b *BaseLayer) LayerPayload() []byte ", "output": "{ return b.Payload }"} {"input": "import \"sort\"\n\ntype Schedule struct {\n intervals []Interval\n}\n\n\n\nfunc (s *Schedule) Less(i, j int) bool {\n if s.intervals[i].Start < s.intervals[j].Start {\n return true\n }\n return false\n}\n\nfunc (s *Schedule) Swap(i, j int) {\n s.intervals[i], s.intervals[j] = s.intervals[j], s.intervals[i]\n}\n\nfunc (s *Schedule) Check() bool {\n for i:=0; i s.intervals[i+1].Start {\n return false\n }\n }\n return true\n}\n\nfunc canAttendMeetings(intervals []Interval) bool {\n if len(intervals) <= 1 {\n return true\n }\n s := Schedule{intervals}\n sort.Sort(&s)\n return s.Check()\n}\n\nfunc (s *Schedule) Len() int ", "output": "{\n return len(s.intervals)\n}"} {"input": "package mecab\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestParse(t *testing.T) ", "output": "{\n\tmodel := NewModel(\"\")\n\tif model == nil {\n\t\tt.Errorf(\"model is not created.\")\n\t}\n\ttagger := model.NewTagger()\n\tif tagger == nil {\n\t\tt.Errorf(\"tagger is not created.\")\n\t}\n\tsentence := \"すもももももももものうち\"\n\tres := tagger.Parse(sentence)\n\tif res == \"\" {\n\t\tt.Errorf(\"no parse result\")\n\t}\n}"} {"input": "package watt\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n\n\t\"github.com/datawire/ambassador/pkg/consulwatch\"\n\n\t\"github.com/datawire/ambassador/pkg/k8s\"\n)\n\ntype ConsulSnapshot struct {\n\tEndpoints map[string]consulwatch.Endpoints `json:\",omitempty\"`\n}\n\nfunc (s *ConsulSnapshot) DeepCopy() (*ConsulSnapshot, error) {\n\tjsonBytes, err := json.Marshal(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := &ConsulSnapshot{}\n\terr = json.Unmarshal(jsonBytes, res)\n\n\treturn res, err\n}\n\ntype Error struct {\n\tSource string\n\tMessage string\n\tTimestamp int64\n}\n\n\n\ntype Snapshot struct {\n\tConsul ConsulSnapshot `json:\",omitempty\"`\n\tKubernetes map[string][]k8s.Resource `json:\",omitempty\"`\n\tErrors map[string][]Error `json:\",omitempty\"`\n}\n\nfunc NewError(source, message string) Error ", "output": "{\n\treturn Error{Source: source, Message: message, Timestamp: time.Now().Unix()}\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"gx/ipfs/QmUWtNQd8JdEiYiDqNYTUcaqyteJZ2rTNQLiw3dauLPccy/gomega/format\"\n)\n\ntype HaveKeyMatcher struct {\n\tKey interface{}\n}\n\nfunc (matcher *HaveKeyMatcher) Match(actual interface{}) (success bool, err error) {\n\tif !isMap(actual) {\n\t\treturn false, fmt.Errorf(\"HaveKey matcher expects a map. Got:%s\", format.Object(actual, 1))\n\t}\n\n\tkeyMatcher, keyIsMatcher := matcher.Key.(omegaMatcher)\n\tif !keyIsMatcher {\n\t\tkeyMatcher = &EqualMatcher{Expected: matcher.Key}\n\t}\n\n\tkeys := reflect.ValueOf(actual).MapKeys()\n\tfor i := 0; i < len(keys); i++ {\n\t\tsuccess, err := keyMatcher.Match(keys[i].Interface())\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"HaveKey's key matcher failed with:\\n%s%s\", format.Indent, err.Error())\n\t\t}\n\t\tif success {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}\n\n\n\nfunc (matcher *HaveKeyMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\tswitch matcher.Key.(type) {\n\tcase omegaMatcher:\n\t\treturn format.Message(actual, \"not to have key matching\", matcher.Key)\n\tdefault:\n\t\treturn format.Message(actual, \"not to have key\", matcher.Key)\n\t}\n}\n\nfunc (matcher *HaveKeyMatcher) FailureMessage(actual interface{}) (message string) ", "output": "{\n\tswitch matcher.Key.(type) {\n\tcase omegaMatcher:\n\t\treturn format.Message(actual, \"to have key matching\", matcher.Key)\n\tdefault:\n\t\treturn format.Message(actual, \"to have key\", matcher.Key)\n\t}\n}"} {"input": "package namespaces\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\n\t\"github.com/dotcloud/docker/pkg/term\"\n)\n\ntype TtyTerminal struct {\n\tstdin io.Reader\n\tstdout, stderr io.Writer\n\tmaster *os.File\n\tstate *term.State\n}\n\nfunc (t *TtyTerminal) Resize(h, w int) error {\n\treturn term.SetWinsize(t.master.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)})\n}\n\nfunc (t *TtyTerminal) SetMaster(master *os.File) {\n\tt.master = master\n}\n\nfunc (t *TtyTerminal) Attach(command *exec.Cmd) error {\n\tgo io.Copy(t.stdout, t.master)\n\tgo io.Copy(t.master, t.stdin)\n\n\tstate, err := t.setupWindow(t.master, os.Stdin)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.state = state\n\treturn err\n}\n\n\n\n\n\nfunc (t *TtyTerminal) Close() error {\n\tterm.RestoreTerminal(os.Stdin.Fd(), t.state)\n\treturn t.master.Close()\n}\n\nfunc (t *TtyTerminal) setupWindow(master, parent *os.File) (*term.State, error) ", "output": "{\n\tws, err := term.GetWinsize(parent.Fd())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := term.SetWinsize(master.Fd(), ws); err != nil {\n\t\treturn nil, err\n\t}\n\treturn term.SetRawTerminal(parent.Fd())\n}"} {"input": "package logger\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\tlog \"github.com/cihub/seelog\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestGetLogFileLocationReturnsOverriddenPath(t *testing.T) {\n\tpath := \"/tmp/foo\"\n\tos.Setenv(envLogFilePath, path)\n\tdefer os.Unsetenv(envLogFilePath)\n\n\tassert.Equal(t, path, GetLogFileLocation(\"/tmp/bar\"))\n}\n\nfunc TestGetLogFileLocationReturnsDefaultPath(t *testing.T) {\n\tpath := \"/tmp/foo\"\n\tassert.Equal(t, path, GetLogFileLocation(path))\n}\n\nfunc TestLogLevelReturnsOverriddenLevel(t *testing.T) {\n\tos.Setenv(envLogLevel, \"DEBUG\")\n\tdefer os.Unsetenv(envLogLevel)\n\n\tvar expectedLogLevel log.LogLevel\n\texpectedLogLevel = log.DebugLvl\n\tassert.Equal(t, expectedLogLevel.String(), getLogLevel())\n}\n\nfunc TestLogLevelReturnsDefaultLevelWhenEnvNotSet(t *testing.T) {\n\tvar expectedLogLevel log.LogLevel\n\texpectedLogLevel = log.InfoLvl\n\tassert.Equal(t, expectedLogLevel.String(), getLogLevel())\n}\n\n\n\nfunc TestLogLevelReturnsDefaultLevelWhenEnvSetToInvalidValue(t *testing.T) ", "output": "{\n\tos.Setenv(envLogLevel, \"DEBUGGER\")\n\tdefer os.Unsetenv(envLogLevel)\n\n\tvar expectedLogLevel log.LogLevel\n\texpectedLogLevel = log.InfoLvl\n\tassert.Equal(t, expectedLogLevel.String(), getLogLevel())\n}"} {"input": "package taskmanager\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\nfunc NewAgent(t TaskManagerInterface, callerName string) *Agent {\n\treturn &Agent{\n\t\tkillTaskPoller: make(chan bool, 1),\n\t\tprocessComplete: make(chan bool, 1),\n\t\ttaskPollEmitter: make(chan bool, 1),\n\t\tstatusEmitter: make(chan string, 1),\n\t\ttaskManager: t,\n\t\ttask: t.NewTask(callerName, TaskAgentLongRunning, AgentTaskStatusInitializing),\n\t}\n}\n\n\n\n\n\nfunc (s *Agent) GetTask() *Task {\n\treturn s.task\n}\n\n\nfunc (s *Agent) GetStatus() chan string {\n\treturn s.statusEmitter\n}\n\nfunc (s *Agent) startTaskPoller() {\nForLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-s.killTaskPoller:\n\t\t\ts.processComplete <- true\n\t\t\tbreak ForLoop\n\t\tdefault:\n\t\t\ts.taskPollEmitter <- true\n\t\t}\n\t\ttime.Sleep(AgentTaskPollerInterval)\n\t}\n}\n\nfunc (s *Agent) listenForPoll() {\n\tfor <-s.taskPollEmitter {\n\t\ts.task.Expires = time.Now().Add(AgentTaskPollerTimeout).UnixNano()\n\t\ts.taskManager.SaveTask(s.task)\n\t}\n\ts.killTaskPoller <- true\n}\n\nfunc (s *Agent) Run(process func(*Agent) error) ", "output": "{\n\ts.task.Status = AgentTaskStatusRunning\n\ts.statusEmitter <- s.task.Status\n\ts.taskManager.SaveTask(s.task)\n\tgo s.startTaskPoller()\n\tgo s.listenForPoll()\n\n\tgo func(agent Agent) {\n\t\ts := &agent\n\t\terr := process(s)\n\t\ts.taskPollEmitter <- false\n\n\t\tselect {\n\t\tcase <-s.processComplete:\n\t\t\tif err == nil {\n\t\t\t\ts.task.Status = AgentTaskStatusComplete\n\n\t\t\t} else {\n\t\t\t\ts.task.Status = fmt.Sprintf(\"status: %s, error: %s\", AgentTaskStatusFailed, err.Error())\n\t\t\t}\n\t\t\ts.task.Expires = 0\n\t\t\ts.taskManager.SaveTask(s.task)\n\t\t\ts.statusEmitter <- s.task.Status\n\t\t}\n\t}(*s)\n}"} {"input": "package tracing\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/gotgo/fw/logging\"\n)\n\ntype Receiver struct {\n\tReceiverName string\n\tWriter TraceMessageWriter\n\tLog logging.Logger `inject:\"\"`\n}\n\nfunc (ft *Receiver) Name() string {\n\treturn ft.ReceiverName\n}\n\nfunc (ft *Receiver) Receive(m *TraceMessage) {\n\tif bytes, err := json.MarshalIndent(m, \"\", \"\\t\"); err != nil {\n\t\tft.Log.MarshalFail(\"trace receive\", m, err)\n\t} else if _, err := ft.Writer.Write(bytes); err != nil {\n\t\tft.Log.Error(\"failed to write to receiver\", err)\n\t}\n}\n\n\n\nfunc (ft *Receiver) Close() ", "output": "{\n\tif err := ft.Writer.Close(); err != nil {\n\t\tft.Log.Error(\"failed to close trace writer\", err)\n\t}\n}"} {"input": "package elements\n\nimport (\n\t\"github.com/faiface/pixel\"\n\t\"github.com/faiface/pixel/pixelgl\"\n\t\"go-zelda/utils\"\n)\n\ntype Object struct {\n\tloc pixel.Vec\n\tsize pixel.Rect\n\tbounds pixel.Rect\n\tsprite *pixel.Sprite\n\tblocking bool\n}\n\nfunc NewObject(img string, loc pixel.Vec, blocking bool) *Object {\n\tobject := new(Object)\n\n\tpic, err := utils.LoadPicture(img)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tobject.size = pic.Bounds()\n\tobject.loc = loc\n\tobject.bounds = utils.GetBounds(object.loc, object.size)\n\tobject.sprite = pixel.NewSprite(pic, object.size)\n\tobject.blocking = blocking\n\n\treturn object\n}\n\n\n\nfunc (object *Object) draw(win *pixelgl.Window) ", "output": "{\n\tobject.sprite.Draw(win, pixel.IM.Scaled(pixel.ZV, 2.5).Moved(object.loc))\n}"} {"input": "package driver\n\nimport \"database/sql/driver\"\n\nvar _ driver.Tx = tx{}\n\ntype tx struct {\n\tconn *conn\n}\n\n\n\nfunc (t tx) Rollback() error {\n\t_, err := t.conn.Exec(\"ROLLBACK TRANSACTION\", nil)\n\treturn err\n}\n\nfunc (t tx) Commit() error ", "output": "{\n\t_, err := t.conn.Exec(\"COMMIT TRANSACTION\", nil)\n\treturn err\n}"} {"input": "package topovalidator\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"vitess.io/vitess/go/vt/topo\"\n\n\ttopodatapb \"vitess.io/vitess/go/vt/proto/topodata\"\n)\n\n\n\n\n\n\n\nfunc RegisterKeyspaceValidator() {\n\tRegisterValidator(\"Keyspace Validator\", &KeyspaceValidator{})\n}\n\n\ntype KeyspaceValidator struct{}\n\n\n\n\n\ntype KeyspaceFixer struct {\n\tts *topo.Server\n\tkeyspace string\n}\n\n\nfunc (kf *KeyspaceFixer) Action(ctx context.Context, name string) error {\n\tif name == \"Create\" {\n\t\treturn kf.ts.CreateKeyspace(ctx, kf.keyspace, &topodatapb.Keyspace{})\n\t}\n\tif name == \"Delete\" {\n\t\treturn kf.ts.DeleteKeyspace(ctx, kf.keyspace)\n\t}\n\treturn fmt.Errorf(\"unknown KeyspaceFixer action: %v\", name)\n}\n\nfunc (kv *KeyspaceValidator) Audit(ctx context.Context, ts *topo.Server, w *Workflow) error ", "output": "{\n\tkeyspaces, err := ts.GetKeyspaces(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, keyspace := range keyspaces {\n\t\t_, err := ts.GetKeyspace(ctx, keyspace)\n\t\tif err != nil {\n\t\t\tw.AddFixer(keyspace, fmt.Sprintf(\"Error: %v\", err), &KeyspaceFixer{\n\t\t\t\tts: ts,\n\t\t\t\tkeyspace: keyspace,\n\t\t\t}, []string{\"Create\", \"Delete\"})\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package models\n\nimport (\n\t\"github.com/go-gorp/gorp\"\n\t\"github.com/skarllot/flogviewer/common\"\n)\n\ntype Host struct {\n\tId int64 `db:\"id\"`\n\tName string `db:\"name\"`\n\tCategoryId *int64 `db:\"category\"`\n\n\tCategory *Category `db:\"-\"`\n}\n\n\n\nfunc (self *Host) PreInsert(gorp.SqlExecutor) error {\n\tif self.Category != nil {\n\t\tself.CategoryId = common.NInt64(self.Category.Id)\n\t}\n\n\treturn nil\n}\n\nfunc (self *Host) PreUpdate(exe gorp.SqlExecutor) error {\n\treturn self.PreInsert(exe)\n}\n\nfunc (self *Host) PostGet(exe gorp.SqlExecutor) error {\n\tif self.CategoryId != nil {\n\t\tobj, err := exe.Get(Category{}, *self.CategoryId)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tself.Category = obj.(*Category)\n\t}\n\treturn nil\n}\n\nfunc DefineHostTable(dbm *gorp.DbMap) ", "output": "{\n\tt := dbm.AddTableWithName(Host{}, \"host\")\n\tt.SetKeys(true, \"id\")\n\tt.ColMap(\"name\").\n\t\tSetUnique(true).\n\t\tSetNotNull(true)\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestInvalidResPath(t *testing.T) ", "output": "{\n\tr, err := NewResDirectory(\"invalidpath/that/doesnt/exist\")\n\n\tif err == nil {\n\t\tt.Error(\"Invalid res path should result in an error\")\n\t}\n\n\tif r != nil {\n\t\tt.Error(\"r (ResDirectory) should be nil with invalid path\")\n\t}\n}"} {"input": "package model\n\n\ntype Weight struct {\n\ttime int\n\trequirements map[*Reward]int\n}\n\n\nfunc (weight *Weight) Time() int {\n\treturn weight.time\n}\n\n\nfunc (weight *Weight) Requirements() map[*Reward]int {\n\treturn weight.requirements\n}\n\n\nfunc (weight *Weight) AddRequirement(reward *Reward, quantity int) {\n\tweight.requirements[reward] = quantity\n}\n\n\nfunc CreateWeight(time int) *Weight {\n\tweight := new(Weight)\n\tweight.time = time\n\tweight.requirements = make(map[*Reward]int)\n\treturn weight\n}\n\n\ntype ByTime []*Weight\n\n\nfunc (a ByTime) Len() int {\n\treturn len(a)\n}\n\n\n\n\n\nfunc (a ByTime) Less(i, j int) bool {\n\treturn a[i].Time() < a[j].Time()\n}\n\nfunc (a ByTime) Swap(i, j int) ", "output": "{\n\ta[i], a[j] = a[j], a[i]\n}"} {"input": "package filesystem\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\n\n\n\n\n\nfunc TestModePermissionsMaskMatchesOS(t *testing.T) ", "output": "{\n\tif ModePermissionsMask != Mode(os.ModePerm) {\n\t\tt.Error(\"ModePermissionsMask does not match expected value\")\n\t}\n}"} {"input": "package google\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype SpannerOperationWaiter struct {\n\tConfig *Config\n\tUserAgent string\n\tProject string\n\tCommonOperationWaiter\n}\n\nfunc (w *SpannerOperationWaiter) QueryOp() (interface{}, error) {\n\tif w == nil {\n\t\treturn nil, fmt.Errorf(\"Cannot query operation, it's unset or nil.\")\n\t}\n\turl := fmt.Sprintf(\"%s%s\", w.Config.SpannerBasePath, w.CommonOperationWaiter.Op.Name)\n\n\treturn sendRequest(w.Config, \"GET\", w.Project, url, w.UserAgent, nil)\n}\n\n\n\n\nfunc spannerOperationWaitTimeWithResponse(config *Config, op map[string]interface{}, response *map[string]interface{}, project, activity, userAgent string, timeout time.Duration) error {\n\tw, err := createSpannerWaiter(config, op, project, activity, userAgent)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := OperationWait(w, activity, timeout, config.PollInterval); err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal([]byte(w.CommonOperationWaiter.Op.Response), response)\n}\n\nfunc spannerOperationWaitTime(config *Config, op map[string]interface{}, project, activity, userAgent string, timeout time.Duration) error {\n\tif val, ok := op[\"name\"]; !ok || val == \"\" {\n\t\treturn nil\n\t}\n\tw, err := createSpannerWaiter(config, op, project, activity, userAgent)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn OperationWait(w, activity, timeout, config.PollInterval)\n}\n\nfunc createSpannerWaiter(config *Config, op map[string]interface{}, project, activity, userAgent string) (*SpannerOperationWaiter, error) ", "output": "{\n\tw := &SpannerOperationWaiter{\n\t\tConfig: config,\n\t\tUserAgent: userAgent,\n\t\tProject: project,\n\t}\n\tif err := w.CommonOperationWaiter.SetOp(op); err != nil {\n\t\treturn nil, err\n\t}\n\treturn w, nil\n}"} {"input": "package framework\n\ntype SizeMode int\n\nconst (\n\tExpandToContent SizeMode = iota\n\tFill\n)\n\nfunc (s SizeMode) ExpandToContent() bool {\n\treturn s == ExpandToContent\n}\n\n\n\nfunc (s SizeMode) Fill() bool ", "output": "{\n\treturn s == Fill\n}"} {"input": "package listener\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc testPTree(t *testing.T, strs ...string) {\n\tpt := newPatriciaTreeString(strs...)\n\tfor _, s := range strs {\n\t\tif !pt.match(strings.NewReader(s)) {\n\t\t\tt.Errorf(\"%s is not matched by %s\", s, s)\n\t\t}\n\n\t\tif !pt.matchPrefix(strings.NewReader(s + s)) {\n\t\t\tt.Errorf(\"%s is not matched as a prefix by %s\", s+s, s)\n\t\t}\n\n\t\tif pt.match(strings.NewReader(s + s)) {\n\t\t\tt.Errorf(\"%s matches %s\", s+s, s)\n\t\t}\n\n\t\tpt.matchPrefix(strings.NewReader(s[:len(s)-1]))\n\t\tpt.match(strings.NewReader(s[:len(s)-1]))\n\t\tpt.matchPrefix(strings.NewReader(s + \"$\"))\n\t\tpt.match(strings.NewReader(s + \"$\"))\n\t}\n}\n\nfunc TestPatriciaOnePrefix(t *testing.T) {\n\ttestPTree(t, \"prefix\")\n}\n\nfunc TestPatriciaNonOverlapping(t *testing.T) {\n\ttestPTree(t, \"foo\", \"bar\", \"dummy\")\n}\n\n\n\nfunc TestPatriciaOverlapping(t *testing.T) ", "output": "{\n\ttestPTree(t, \"foo\", \"far\", \"farther\", \"boo\", \"ba\", \"bar\")\n}"} {"input": "package model\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"net/http\"\n\t\"net/http/httptest\"\n\n\t\"github.com/jmjoy/http-api-tester/app\"\n)\n\nvar testSrv *httptest.Server\nvar testData0 Data\n\nfunc TestMain(m *testing.M) {\n\tdbPath := \"./model_test.db\"\n\tif _, err := os.Stat(dbPath); err == nil {\n\t\tos.Remove(dbPath)\n\t}\n\tdefer os.Remove(dbPath)\n\n\tif err := app.InitDb(dbPath); err != nil {\n\t\tpanic(err)\n\t}\n\n\ttestSrv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif err := r.ParseForm(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tcontent := r.URL.Query().Encode() + \" \" + r.PostForm.Encode()\n\t\tw.Write([]byte(content))\n\t}))\n\tdefer testSrv.Close()\n\n\tinitData()\n\n\tm.Run()\n}\n\n\n\nfunc initData() ", "output": "{\n\ttestData0 = Data{\n\t\tMethod: \"POST\",\n\t\tUrl: testSrv.URL,\n\t\tArgs: []Arg{\n\t\t\tArg{\"k1\", \"v1\", \"GET\"},\n\t\t\tArg{\"k2\", \"v2\", \"GET\"},\n\t\t\tArg{\"k3\", \"v3\", \"POST\"},\n\t\t\tArg{\"k4\", \"v4\", \"POST\"},\n\t\t},\n\t}\n\n}"} {"input": "package basename_test\n\nimport (\n\t\"testing\"\n\n\t\".\"\n)\n\nconst (\n\tpath = \"/very/long/path/to/a/file/with.some.extension.hello\"\n)\n\nfunc TestLoop(t *testing.T) {\n\texpected := \"with.some.extension\"\n\tif actual := basename.Loop(path); actual != expected {\n\t\tt.Errorf(\"actual: %s\", actual)\n\t\tt.Errorf(\"expected: %s\", expected)\n\t}\n}\n\nfunc TestLastIndex(t *testing.T) {\n\texpected := \"with.some.extension\"\n\tif actual := basename.LastIndex(path); actual != expected {\n\t\tt.Errorf(\"actual: %s\", actual)\n\t\tt.Errorf(\"expected: %s\", expected)\n\t}\n}\n\n\n\nfunc BenchmarkLastIndex(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbasename.LastIndex(path)\n\t}\n}\n\nfunc BenchmarkLoop(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tbasename.Loop(path)\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/nanobox-io/nanobox-server/util\"\n)\n\nfunc (api *API) Suspend(rw http.ResponseWriter, req *http.Request) {\n\tif util.LockCount() <= 0 {\n\t\treturn\n\t}\n\n\twriteBody(map[string]string{\"error\": fmt.Sprintf(\"Current lock count: %d\", util.LockCount())}, rw, http.StatusNotAcceptable)\n}\n\nfunc (api *API) LockCount(rw http.ResponseWriter, req *http.Request) {\n\tfmt.Fprintf(rw, \"%d\", util.LockCount())\n}\n\n\n\n\n\nfunc (api *API) Lock(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\tutil.Lock()\n\tdefer util.Unlock()\n\n\tcNotify := rw.(http.CloseNotifier)\n\t<-cNotify.CloseNotify()\n}"} {"input": "package objectstorage\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype ListMultipartUploadsRequest struct {\n\n\tNamespaceName *string `mandatory:\"true\" contributesTo:\"path\" name:\"namespaceName\"`\n\n\tBucketName *string `mandatory:\"true\" contributesTo:\"path\" name:\"bucketName\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tOpcClientRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-client-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListMultipartUploadsRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListMultipartUploadsRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request ListMultipartUploadsRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListMultipartUploadsResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []MultipartUpload `presentIn:\"body\"`\n\n\tOpcClientRequestId *string `presentIn:\"header\" name:\"opc-client-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n}\n\n\n\n\nfunc (response ListMultipartUploadsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response ListMultipartUploadsResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package etcd\n\nimport (\n\t\"strconv\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/meta\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n\t\"k8s.io/kubernetes/pkg/storage\"\n)\n\n\n\ntype APIObjectVersioner struct{}\n\n\nfunc (a APIObjectVersioner) UpdateObject(obj runtime.Object, resourceVersion uint64) error {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tversionString := \"\"\n\tif resourceVersion != 0 {\n\t\tversionString = strconv.FormatUint(resourceVersion, 10)\n\t}\n\taccessor.SetResourceVersion(versionString)\n\treturn nil\n}\n\n\nfunc (a APIObjectVersioner) UpdateList(obj runtime.Object, resourceVersion uint64) error {\n\tlistMeta, err := api.ListMetaFor(obj)\n\tif err != nil || listMeta == nil {\n\t\treturn err\n\t}\n\tversionString := \"\"\n\tif resourceVersion != 0 {\n\t\tversionString = strconv.FormatUint(resourceVersion, 10)\n\t}\n\tlistMeta.ResourceVersion = versionString\n\treturn nil\n}\n\n\nfunc (a APIObjectVersioner) ObjectResourceVersion(obj runtime.Object) (uint64, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tversion := accessor.GetResourceVersion()\n\tif len(version) == 0 {\n\t\treturn 0, nil\n\t}\n\treturn strconv.ParseUint(version, 10, 64)\n}\n\n\nvar Versioner storage.Versioner = APIObjectVersioner{}\n\n\n\n\n\nfunc (a APIObjectVersioner) CompareResourceVersion(lhs, rhs runtime.Object) int ", "output": "{\n\tlhsVersion, err := Versioner.ObjectResourceVersion(lhs)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trhsVersion, err := Versioner.ObjectResourceVersion(rhs)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif lhsVersion == rhsVersion {\n\t\treturn 0\n\t}\n\tif lhsVersion < rhsVersion {\n\t\treturn -1\n\t}\n\n\treturn 1\n}"} {"input": "package messagestore\n\nimport (\n\t\"github.com/agl/ed25519\"\n\tlog \"github.com/repbin/repbin/deferconsole\"\n\t\"github.com/repbin/repbin/utils\"\n\t\"github.com/repbin/repbin/utils/keyproof\"\n\t\"github.com/repbin/repbin/utils/repproto/structs\"\n)\n\n\nfunc (store Store) TouchPeer(pubkey *[ed25519.PublicKeySize]byte) {\n\terr := store.db.TouchPeer(pubkey)\n\tif err != nil {\n\t\tlog.Errorf(\"TouchPeer: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t}\n}\n\n\nfunc (store Store) UpdatePeerFetchStat(pubkey *[ed25519.PublicKeySize]byte, lastFetch, lastPos, lastErrors uint64) {\n\terr := store.db.UpdatePeerStats(pubkey, lastFetch, lastPos, lastErrors)\n\tif err != nil {\n\t\tlog.Errorf(\"UpdatePeerStats: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t}\n}\n\n\nfunc (store Store) UpdatePeerNotification(pubkey *[ed25519.PublicKeySize]byte, hasError bool) {\n\terr := store.db.UpdatePeerNotification(pubkey, hasError)\n\tif err != nil {\n\t\tlog.Errorf(\"UpdatePeerNotification: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t}\n}\n\n\nfunc (store Store) GetPeerStat(pubkey *[ed25519.PublicKeySize]byte) *structs.PeerStruct {\n\tst, err := store.db.SelectPeer(pubkey)\n\tif err != nil {\n\t\tlog.Errorf(\"GetPeerStat: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t\treturn nil\n\t}\n\treturn st\n}\n\n\n\n\nfunc (store Store) UpdatePeerAuthToken(senderPubKey *[ed25519.PublicKeySize]byte, signedToken *[keyproof.ProofTokenSignedSize]byte) ", "output": "{\n\terr := store.db.UpdatePeerToken(senderPubKey, signedToken)\n\tif err != nil {\n\t\tlog.Errorf(\"UpdatePeerAuthToken: %s, %s\\n\", err, utils.B58encode(senderPubKey[:]))\n\t}\n}"} {"input": "package install\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tutilruntime \"k8s.io/apimachinery/pkg/util/runtime\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\t\"k8s.io/kubernetes/pkg/apis/policy\"\n\t\"k8s.io/kubernetes/pkg/apis/policy/v1beta1\"\n)\n\n\n\n\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(policy.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1beta1.SchemeGroupVersion))\n}\n\nfunc init() ", "output": "{\n\tInstall(legacyscheme.Scheme)\n}"} {"input": "package client\n\nimport (\n\t\"net/url\"\n)\n\n\n\nfunc mapToQueryParameters(paramsMap map[string]string) string ", "output": "{\n\tparams := url.Values{}\n\tfor key, value := range paramsMap {\n\t\tparams.Add(key, value)\n\t}\n\treturn \"?\" + params.Encode()\n}"} {"input": "package command\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/consul/testutil\"\n\t\"github.com/mitchellh/cli\"\n)\n\nfunc TestPutCommand(t *testing.T) {\n\tsrv := testutil.NewTestServer(t)\n\tdefer srv.Stop()\n\n\tui := new(cli.MockUi)\n\tc := &PutCommand{UI: ui}\n\n\tos.Setenv(\"CONSUL_HTTP_ADDR\", srv.HTTPAddr)\n\targs := []string{\"foo\", \"bar\"}\n\tcode := c.Run(args)\n\tif code != 0 {\n\t\tt.Fatalf(\"Unexpected code: %d err: %s\", code, ui.ErrorWriter.String())\n\t}\n\tval := srv.GetKV(\"foo\")\n\tif string(val) != \"bar\" {\n\t\tt.Fatalf(\"Invalid value %s\", val)\n\t}\n}\n\n\n\nfunc TestPutCommandStdin(t *testing.T) ", "output": "{\n\tsrv := testutil.NewTestServer(t)\n\tdefer srv.Stop()\n\n\tui := new(cli.MockUi)\n\tinput := bytes.NewBufferString(\"bar\")\n\tc := &PutCommand{UI: ui, Input: input}\n\n\tos.Setenv(\"CONSUL_HTTP_ADDR\", srv.HTTPAddr)\n\targs := []string{\"foo\"}\n\tcode := c.Run(args)\n\tif code != 0 {\n\t\tt.Fatalf(\"Unexpected code: %d err: %s\", code, ui.ErrorWriter.String())\n\t}\n\tval := srv.GetKV(\"foo\")\n\tif string(val) != \"bar\" {\n\t\tt.Fatalf(\"Invalid value %s\", val)\n\t}\n}"} {"input": "package loadbalancer\n\nimport (\n\t\"github.com/sacloud/libsacloud/v2/helper/service\"\n\t\"github.com/sacloud/libsacloud/v2/helper/validate\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\ntype ApplyRequest struct {\n\tID types.ID \n\tZone string `validate:\"required\"`\n\n\tName string `validate:\"required\"`\n\tDescription string `validate:\"min=0,max=512\"`\n\tTags types.Tags\n\tIconID types.ID\n\tSwitchID types.ID `validate:\"required\"`\n\tPlanID types.ID `validate:\"required\"`\n\tVRID int\n\tIPAddresses []string `validate:\"required,min=1,max=2,dive,ipv4\"`\n\tNetworkMaskLen int `validate:\"required\"`\n\tDefaultRoute string `validate:\"omitempty,ipv4\"`\n\tVirtualIPAddresses sacloud.LoadBalancerVirtualIPAddresses\n\n\tSettingsHash string \n\tNoWait bool\n}\n\nfunc (req *ApplyRequest) Validate() error {\n\treturn validate.Struct(req)\n}\n\n\n\nfunc (req *ApplyRequest) Builder(caller sacloud.APICaller) (*Builder, error) ", "output": "{\n\tb := &Builder{Client: sacloud.NewLoadBalancerOp(caller)}\n\tif err := service.RequestConvertTo(req, b); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}"} {"input": "package test\n\nimport \"github.com/tidepool-org/platform/test\"\n\nfunc NewServiceSecret() string {\n\treturn test.RandomStringFromRangeAndCharset(128, 128, test.CharsetAlphaNumeric)\n}\n\nfunc NewAccessToken() string {\n\treturn test.RandomStringFromRangeAndCharset(256, 256, test.CharsetAlphaNumeric)\n}\n\n\n\nfunc NewRestrictedToken() string {\n\treturn test.RandomStringFromRangeAndCharset(40, 40, test.CharsetAlphaNumeric)\n}\n\nfunc NewSessionToken() string ", "output": "{\n\treturn test.RandomStringFromRangeAndCharset(256, 256, test.CharsetAlphaNumeric)\n}"} {"input": "package SFTimeUtil\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\n\nfunc TestYMDHMSSFormat(t *testing.T) {\n\tfmt.Println(YMDHMSSFormat(time.Now(), \"yyyy-MM-dd hh:mm:ssSSSSSSSSS -0700 MST\"))\n}\n\n\n\nfunc TestYMDHMSSSignParse(t *testing.T) ", "output": "{\n\tfmt.Println(YMDHMSSSignFormat(time.Now(), \"_${yyyy}\"))\n}"} {"input": "package osc\n\nimport (\n\t\"encoding/base64\"\n\t\"regexp\"\n)\n\n\n\nfunc base64Encode(data []byte) string {\n\tif isBase64Encoded(data) {\n\t\treturn string(data)\n\t}\n\treturn base64.StdEncoding.EncodeToString(data)\n}\n\n\n\nfunc looksLikeJsonString(s interface{}) bool {\n\treturn regexp.MustCompile(`^\\s*{`).MatchString(s.(string))\n}\n\nfunc isBase64Encoded(data []byte) bool ", "output": "{\n\t_, err := base64.StdEncoding.DecodeString(string(data))\n\treturn err == nil\n}"} {"input": "package iso20022\n\n\ntype ProfitAndLoss1Choice struct {\n\n\tProfit *ActiveCurrencyAnd13DecimalAmount `xml:\"Prft\"`\n\n\tLoss *ActiveCurrencyAnd13DecimalAmount `xml:\"Loss\"`\n}\n\n\n\nfunc (p *ProfitAndLoss1Choice) SetLoss(value, currency string) {\n\tp.Loss = NewActiveCurrencyAnd13DecimalAmount(value, currency)\n}\n\nfunc (p *ProfitAndLoss1Choice) SetProfit(value, currency string) ", "output": "{\n\tp.Profit = NewActiveCurrencyAnd13DecimalAmount(value, currency)\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/apier/v1\"\n\n\n\n\ntype CmdRemoveActions struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrRemoveActions\n\t*CommandExecuter\n}\n\nfunc (self *CmdRemoveActions) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdRemoveActions) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdRemoveActions) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrRemoveActions{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdRemoveActions) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdRemoveActions) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc init() ", "output": "{\n\tc := &CmdRemoveActions{\n\t\tname: \"actions_remove\",\n\t\trpcMethod: \"ApierV1.RemoveActions\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}"} {"input": "package leet_83\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\n\n\nfunc deleteDuplicates(head *ListNode) *ListNode ", "output": "{\n\tif head == nil {\n\t\treturn nil\n\t}\n\tpre := head\n\tfor pre.Next != nil {\n\t\tcur := pre.Next\n\t\tfor cur != nil && cur.Val == pre.Val {\n\t\t\tpre.Next = cur.Next\n\t\t\tcur = cur.Next\n\t\t}\n\t\tif pre.Next == nil {\n\t\t\tbreak\n\t\t}\n\t\tpre = pre.Next\n\t}\n\treturn head\n}"} {"input": "package websocket\n\nimport(\n \"net/http\"\n \"log\"\n \"github.com/gorilla/websocket\"\n wss \"github.com/ipastushenko/simple-chat/server/services/websocket\"\n \"github.com/ipastushenko/simple-chat/server/services/token\"\n)\n\nvar upgrader = websocket.Upgrader{\n CheckOrigin: func(r *http.Request) bool {\n return true\n },\n}\n\ntype WebSocketHandler struct {\n webSocketService wss.IWebSocketService\n tokenService token.ITokenService\n}\n\n\n\nfunc (handler *WebSocketHandler) ServeHTTP(\n responseWriter http.ResponseWriter,\n request *http.Request,\n) {\n connection, err := upgrader.Upgrade(responseWriter, request, nil)\n if err != nil {\n log.Println(err.Error())\n responseWriter.WriteHeader(http.StatusInternalServerError)\n return\n }\n info := handler.tokenService.GetRequestContextInfo(request)\n handler.webSocketService.InitConnection(connection, info)\n}\n\nfunc NewWebSocketHandler() *WebSocketHandler ", "output": "{\n return &WebSocketHandler{\n webSocketService: wss.NewWebSocketService(),\n tokenService: token.NewJWTService(),\n }\n}"} {"input": "package io\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc Info(args ...interface{}) {\n\tfmt.Print(\"\\033[1m-----> \")\n\targs = append(args, \"\\033[0m\")\n\tfmt.Println(args...)\n}\n\nfunc Infof(format string, args ...interface{}) {\n\tfmt.Print(\"\\033[1m-----> \")\n\tfmt.Printf(format+\"\\033[0m\", args...)\n}\n\nfunc Print(args ...interface{}) {\n\tfmt.Print(\" \")\n\tfmt.Println(args...)\n}\n\nfunc Printf(format string, args ...interface{}) {\n\tfmt.Print(\" \")\n\tfmt.Printf(format, args...)\n}\n\nfunc Warnf(format string, args ...interface{}) {\n\tfmt.Print(\" ! \")\n\tfmt.Printf(format, args...)\n}\n\n\n\nfunc Error(args ...interface{}) ", "output": "{\n\tfmt.Print(\" ! \")\n\tfmt.Println(args...)\n\tos.Exit(1)\n}"} {"input": "package libfuse\n\nimport (\n\t\"os\"\n\n\t\"bazil.org/fuse\"\n\t\"bazil.org/fuse/fs\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\ntype Alias struct {\n\trealPath string\n\tinode uint64\n}\n\nvar _ fs.Node = (*Alias)(nil)\n\n\nfunc (*Alias) Attr(ctx context.Context, a *fuse.Attr) error {\n\ta.Mode = os.ModeSymlink | 0777\n\treturn nil\n}\n\nvar _ fs.NodeReadlinker = (*Alias)(nil)\n\n\n\n\nfunc (a *Alias) Readlink(ctx context.Context, req *fuse.ReadlinkRequest) (string, error) ", "output": "{\n\treturn a.realPath, nil\n}"} {"input": "package dshelp\n\nimport (\n\tcid \"gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid\"\n\t\"gx/ipfs/QmaRb5yNXKonhbkpNxNawoydk4N6es6b4fPj19sjEKsh5D/go-datastore\"\n\t\"gx/ipfs/QmfVj3x4D6Jkq9SEoi5n2NmoUomLwoeiwnYz2KQa15wRw6/base32\"\n)\n\n\n\n\n\nfunc BinaryFromDsKey(k datastore.Key) ([]byte, error) {\n\treturn base32.RawStdEncoding.DecodeString(k.String()[1:])\n}\n\n\nfunc CidToDsKey(k cid.Cid) datastore.Key {\n\treturn NewKeyFromBinary(k.Bytes())\n}\n\n\nfunc DsKeyToCid(dsKey datastore.Key) (cid.Cid, error) {\n\tkb, err := BinaryFromDsKey(dsKey)\n\tif err != nil {\n\t\treturn cid.Cid{}, err\n\t}\n\treturn cid.Cast(kb)\n}\n\nfunc NewKeyFromBinary(rawKey []byte) datastore.Key ", "output": "{\n\tbuf := make([]byte, 1+base32.RawStdEncoding.EncodedLen(len(rawKey)))\n\tbuf[0] = '/'\n\tbase32.RawStdEncoding.Encode(buf[1:], rawKey)\n\treturn datastore.RawKey(string(buf))\n}"} {"input": "package main\n\nimport \"errors\"\n\n\n\ntype Item struct {\n\tId int\n\tPath string\n}\n\ntype Status struct {\n\tStatus string\n\tList []Item\n\tId int\n}\n\nconst (\n\tStateStopped = iota\n\tStatePlaying\n)\n\n\n\nvar items []Item\nvar nextId int\nvar currentTrack int\nvar currentState int\n\n\n\nfunc addItem(path string) (id int) {\n\tid = nextId\n\titems = append(items, Item{Id: nextId, Path: path})\n\tnextId = nextId + 1\n\treturn\n}\n\nfunc itemIndex(id int) (i int, err error) {\n\tfor i = 0; i < len(items); i++ {\n\t\tif items[i].Id == id {\n\t\t\treturn\n\t\t}\n\t}\n\terr = errors.New(\"no item with that id found\")\n\treturn\n}\n\n\n\nfunc initialize() {\n\titems = []Item{}\n\tnextId = 1\n\tcurrentTrack = 0\n\tcurrentState = StateStopped\n}\n\nfunc removeItem(id int) (err error) ", "output": "{\n\ti, err := itemIndex(id)\n\tif err != nil {\n\t\treturn\n\t}\n\titems = append(items[:i], items[i+1:]...)\n\treturn\n}"} {"input": "package version \n\nimport \"k8s.io/helm/pkg/proto/hapi/version\"\n\nvar (\n\tVersion = \"v2.5\"\n\n\tBuildMetadata = \"unreleased\"\n\tGitCommit = \"\"\n\tGitTreeState = \"\"\n)\n\n\nfunc GetVersion() string {\n\tif BuildMetadata == \"\" {\n\t\treturn Version\n\t}\n\treturn Version + \"+\" + BuildMetadata\n}\n\n\n\n\nfunc GetVersionProto() *version.Version ", "output": "{\n\treturn &version.Version{\n\t\tSemVer: GetVersion(),\n\t\tGitCommit: GitCommit,\n\t\tGitTreeState: GitTreeState,\n\t}\n}"} {"input": "package wrapstesting\n\nimport (\n\t\"net/http\"\n\n\t\"gopkg.in/go-on/wrap.v2\"\n)\n\ntype (\n\tdefer_ struct{ http.Handler }\n)\n\nfunc (ø defer_) Wrap(in http.Handler) (out http.Handler) {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() { ø.ServeHTTP(w, r) }()\n\t\tin.ServeHTTP(w, r)\n\t})\n}\n\n\n\nfunc Defer(h http.Handler) wrap.Wrapper {\n\treturn defer_{h}\n}\n\nfunc DeferFunc(fn func(http.ResponseWriter, *http.Request)) wrap.Wrapper ", "output": "{\n\treturn defer_{http.HandlerFunc(fn)}\n}"} {"input": "package xparam\n\n\n\n\n\nfunc New(vals map[string]interface{}) XP {\n\treturn vals\n}\n\n\n\n\n\n\n\n\n\nfunc (xp XP) As_ArrayXP(key string) (data []XP) {\n\n\tif val, ok := xp[key]; ok && val != nil {\n\t\tif arr, ok := val.([]interface{}); ok {\n\t\t\tdata = []XP{}\n\t\t\tfor _, obj := range arr {\n\t\t\t\tif axp, ok := obj.(map[string]interface{}); ok {\n\t\t\t\t\tdata = append(data, axp)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc (xp XP) As_XP(key string) (data XP) ", "output": "{\n\n\tif val, ok := xp[key]; ok && val != nil {\n\t\tif axp, ok := val.(map[string]interface{}); ok {\n\t\t\tdata = axp\n\t\t}\n\t}\n\treturn\n}"} {"input": "package health\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/centrifugal/centrifuge\"\n)\n\n\ntype Config struct{}\n\n\ntype Handler struct {\n\tnode *centrifuge.Node\n\tconfig Config\n}\n\n\n\n\nfunc (h *Handler) ServeHTTP(w http.ResponseWriter, _ *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t_, _ = w.Write([]byte(`{}`))\n}\n\nfunc NewHandler(n *centrifuge.Node, c Config) *Handler ", "output": "{\n\th := &Handler{\n\t\tnode: n,\n\t\tconfig: c,\n\t}\n\treturn h\n}"} {"input": "package base\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Destination struct {\n\tSourceIp string `db:\"source_ip\"`\n\tDestinationIp string `db:\"destination_ip\"`\n\tServerName string `db:\"server_name\"`\n\tProtocol string `db:\"protocol\"`\n\tTimestamp time.Time `db:\"timestamp\"`\n}\n\nfunc (self *Destination) Hash() string {\n\treturn fmt.Sprintf(\"%x\", md5.Sum([]byte(self.SourceIp+self.DestinationIp+self.ServerName+self.Protocol)))\n}\n\n\n\nfunc (self *Destination) Save(db GarinDB) {\n\tLogger().Debugf(\"Saving destination - %s\", self.Hash())\n\tdb.RecordDestination(self)\n\tLogger().Debugf(\"Destination saved - %s\", self.Hash())\n}\n\nfunc NewDestination(serverName string, sourceIp string, destIp string) *Destination ", "output": "{\n\tdestination := &Destination{ServerName: serverName, SourceIp: sourceIp, DestinationIp: destIp}\n\treturn destination\n}"} {"input": "package types\n\nimport (\n\t\"encoding/json\"\n)\n\n\n\n\ntype FilteredString struct {\n\tIsSet bool\n\tValue string\n}\n\n\nfunc (n *FilteredString) ParseValue(val string) {\n\tif val == \"\" {\n\t\tn.IsSet = false\n\t\tn.Value = \"\"\n\t\treturn\n\t}\n\n\tn.IsSet = true\n\n\tswitch val {\n\tcase \"null\", \"default\":\n\t\tn.Value = \"\"\n\tdefault:\n\t\tn.Value = val\n\t}\n}\n\n\n\nfunc (n FilteredString) MarshalJSON() ([]byte, error) {\n\tif n.IsSet {\n\t\treturn json.Marshal(n.Value)\n\t}\n\n\treturn json.Marshal(nil)\n}\n\nfunc (n *FilteredString) UnmarshalJSON(rawJSON []byte) error ", "output": "{\n\tvar value *string\n\terr := json.Unmarshal(rawJSON, &value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif value != nil {\n\t\tn.Value = *value\n\t\tn.IsSet = true\n\t\treturn nil\n\t}\n\n\tn.Value = \"\"\n\tn.IsSet = false\n\treturn nil\n}"} {"input": "package docker\n\nimport (\n\t\"fmt\"\n\t\"github.com/mitchellh/multistep\"\n\t\"github.com/mitchellh/packer/packer\"\n)\n\ntype StepRun struct {\n\tcontainerId string\n}\n\nfunc (s *StepRun) Run(state multistep.StateBag) multistep.StepAction {\n\tconfig := state.Get(\"config\").(*Config)\n\tdriver := state.Get(\"driver\").(Driver)\n\ttempDir := state.Get(\"temp_dir\").(string)\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\trunConfig := ContainerConfig{\n\t\tImage: config.Image,\n\t\tRunCommand: config.RunCommand,\n\t\tVolumes: make(map[string]string),\n\t\tPrivileged: config.Privileged,\n\t}\n\n\tfor host, container := range config.Volumes {\n\t\trunConfig.Volumes[host] = container\n\t}\n\trunConfig.Volumes[tempDir] = \"/packer-files\"\n\n\tui.Say(\"Starting docker container...\")\n\tcontainerId, err := driver.StartContainer(&runConfig)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"Error running container: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\ts.containerId = containerId\n\tstate.Put(\"container_id\", s.containerId)\n\tui.Message(fmt.Sprintf(\"Container ID: %s\", s.containerId))\n\treturn multistep.ActionContinue\n}\n\n\n\nfunc (s *StepRun) Cleanup(state multistep.StateBag) ", "output": "{\n\tif s.containerId == \"\" {\n\t\treturn\n\t}\n\n\tdriver := state.Get(\"driver\").(Driver)\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\tui.Say(fmt.Sprintf(\"Killing the container: %s\", s.containerId))\n\tdriver.StopContainer(s.containerId)\n\n\ts.containerId = \"\"\n}"} {"input": "package crm\n\nimport \"github.com/denverdino/aliyungo/common\"\n\ntype Client struct {\n\tcommon.Client\n}\n\nconst (\n\tCRMDefaultEndpoint = \"https://crm-cn-hangzhou.aliyuncs.com\"\n\tCRMAPIVersion = \"2015-04-08\"\n)\n\n\n\n\nfunc NewClient(accessKeyId, accessKeySecret string) *Client ", "output": "{\n\tclient := &Client{}\n\tclient.Init(CRMDefaultEndpoint, CRMAPIVersion, accessKeyId, accessKeySecret)\n\treturn client\n}"} {"input": "package modules\n\nimport (\n\t\"io\"\n\n\t\"github.com/kylelemons/go-gypsy/yaml\"\n)\n\ntype Node interface{}\ntype Scalar string\ntype Map map[string]Node\ntype List []Node\n\nfunc YamlNodeToNode(node yaml.Node) Node {\n\tscalar, ok := node.(yaml.Scalar)\n\tif ok {\n\t\treturn Scalar(scalar.String())\n\t}\n\tlist, ok := node.(yaml.List)\n\tif ok {\n\t\tresult := make(List, list.Len())\n\t\tfor i, n := range list {\n\t\t\tresult[i] = YamlNodeToNode(n)\n\t\t}\n\t\treturn result\n\t}\n\tmp, ok := node.(yaml.Map)\n\tif ok {\n\t\tresult := make(Map)\n\t\tfor k, v := range mp {\n\t\t\tresult[k] = YamlNodeToNode(v)\n\t\t}\n\t\treturn result\n\t}\n\treturn nil\n}\n\nfunc Parse(r io.Reader) (Node, error) {\n\tn, err := yaml.Parse(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn YamlNodeToNode(n), err\n}\n\nfunc Child(root Node, spec string) (Node, error) {\n\treturn nil, nil\n}\n\nfunc (s Scalar) String() string {\n\treturn string(s)\n}\n\n\n\nfunc (m Map) Keys() []string {\n\tkeys := make([]string, 0, len(m))\n\tfor key := range m {\n\t\tkeys = append(keys, key)\n\t}\n\treturn keys\n}\n\nfunc (m Map) Key(key string) Node {\n\treturn m[key]\n}\n\nfunc (l List) Item(idx int) Node {\n\treturn l[idx]\n}\n\nfunc (l List) Len() int {\n\treturn len(l)\n}\n\nfunc (s Scalar) GetBool() bool ", "output": "{\n\tif s == \"true\" || s == \"yes\" || s == \"1\" {\n\t\treturn true\n\t} else if s == \"false\" || s == \"no\" || s == \"0\" {\n\t\treturn false\n\t}\n\tpanic(\"Invalid bool value:\" + s.String())\n}"} {"input": "package clients\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n\n\t\"github.com/VolantMQ/volantmq/subscriber\"\n)\n\nvar subCount int32 = 0\n\n\n\ntype container struct {\n\tlock sync.Mutex\n\trmLock sync.RWMutex\n\tses *session\n\texpiry atomic.Value\n\tsub *subscriber.Type\n\tremovable bool\n\tremoved bool\n}\n\n\n\nfunc (s *container) acquire() {\n\ts.lock.Lock()\n}\n\nfunc (s *container) release() {\n\ts.lock.Unlock()\n}\n\nfunc (s *container) session() *session {\n\tdefer s.rmLock.Unlock()\n\ts.rmLock.Lock()\n\treturn s.ses\n}\n\nfunc (s *container) swap(from *container) *container {\n\ts.ses = from.ses\n\n\ts.ses.idLock = &s.lock\n\n\treturn s\n}\n\nfunc (s *container) subscriber(cleanStart bool, c subscriber.Config) *subscriber.Type {\n\tif cleanStart && s.sub != nil {\n\t\ts.sub.Offline(true)\n\t\ts.sub = nil\n\t}\n\n\tif s.sub == nil {\n\t\ts.sub = subscriber.New(c)\n\t}\n\n\treturn s.sub\n}\n\nfunc (s *container) setRemovable(rm bool) ", "output": "{\n\ts.rmLock.Lock()\n\ts.removable = rm\n\ts.rmLock.Unlock()\n}"} {"input": "package parlib\n\nimport (\n\t\"errors\"\n)\n\n\nfunc Cstrlen(str []byte) int {\n var i int = 0\n for (str[i] != 0) { i++ }\n return i\n}\n\n\n\n\nfunc StringByteSlice(s string) []byte {\n\ta, err := ByteSliceFromString(s)\n\tif err != nil {\n\t\tpanic(\"syscall: string with NUL passed to StringByteSlice\")\n\t}\n\treturn a\n}\n\n\n\n\nfunc ByteSliceFromString(s string) ([]byte, error) {\n\tfor i := 0; i < len(s); i++ {\n\t\tif s[i] == 0 {\n\t\t\treturn nil, errors.New(\"String contains a NULL byte.\")\n\t\t}\n\t}\n\ta := make([]byte, len(s)+1)\n\tcopy(a, s)\n\treturn a, nil\n}\n\n\n\n\n\n\n\n\n\nfunc BytePtrFromString(s string) (*byte, error) {\n\ta, err := ByteSliceFromString(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &a[0], nil\n}\n\n\n\n\nfunc StringSlicePtr(ss []string) []*byte {\n bb := make([]*byte, len(ss)+1)\n for i := 0; i < len(ss); i++ {\n bb[i] = StringBytePtr(ss[i])\n }\n bb[len(ss)] = nil\n return bb\n}\n\n\n\n\nfunc SlicePtrFromStrings(ss []string) ([]*byte, error) {\n var err error\n bb := make([]*byte, len(ss)+1)\n for i := 0; i < len(ss); i++ {\n bb[i], err = BytePtrFromString(ss[i])\n if err != nil {\n return nil, err\n }\n }\n bb[len(ss)] = nil\n return bb, nil\n}\n\nfunc StringBytePtr(s string) *byte ", "output": "{ return &StringByteSlice(s)[0] }"} {"input": "package d3data\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"io/ioutil\"\n)\n\n\n\nfunc writeToFile(b []byte) error {\n\tabsPath, err := filepath.Abs(\"../gopower/display/output.json\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(absPath, b, 0644)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc CreateGraphJSONData(a_shape float64, b_scale int) ", "output": "{\n\tres, err := GenerateData(a_shape, b_scale)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\terr = writeToFile(res)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}"} {"input": "package ansicolor\n\nimport \"syscall\"\n\nvar GetConsoleScreenBufferInfo = getConsoleScreenBufferInfo\n\n\n\nfunc ResetColor() {\n\tChangeColor(uint16(0x0007))\n}\n\nfunc ChangeColor(color uint16) ", "output": "{\n\tsetConsoleTextAttribute(uintptr(syscall.Stdout), color)\n}"} {"input": "package golang\n\nimport (\n\t\"bldy.build/build/executor\"\n\t\"bldy.build/build/label\"\n)\n\ntype Go struct {\n\tname string `group:\"name\"`\n\tdependencies []label.Label `group:\"deps\"`\n}\n\nfunc (g *Go) Name() string {\n\tpanic(\"not implemented\")\n}\n\n\n\nfunc (g *Go) Outputs() []string {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Hash() []byte {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Build(*executor.Executor) error {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Dependencies() []label.Label ", "output": "{\n\tpanic(\"not implemented\")\n}"} {"input": "package endpoints\n\nimport (\n\t\"net\"\n)\n\n\n\n\n\n\n\nfunc localSetAccess(path string, group string) error {\n\terr := socketUnixSetPermissions(path, 0660)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = socketUnixSetOwnership(path, group)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc localCreateListener(path string, group string) (net.Listener, error) ", "output": "{\n\terr := CheckAlreadyRunning(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = socketUnixRemoveStale(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlistener, err := socketUnixListen(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = localSetAccess(path, group)\n\tif err != nil {\n\t\tlistener.Close()\n\t\treturn nil, err\n\t}\n\n\treturn listener, nil\n}"} {"input": "package app\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"github.com/nsqio/go-nsq\"\n)\n\n\n\nfunc ParseOpts(cfg *nsq.Config, opts string) error ", "output": "{\n\tvar err error\n\tfor _, opt := range strings.Split(opts, \",\") {\n\t\tparts := strings.Split(opt, \"=\")\n\t\tkey := parts[0]\n\t\tswitch len(parts) {\n\t\tcase 1:\n\t\t\terr = cfg.Set(key, true)\n\t\tcase 2:\n\t\t\terr = cfg.Set(key, parts[1])\n\t\tdefault:\n\t\t\terr = errors.New(\"cannot have more than 2 parameters\")\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package levigo\n\n\n\n\nimport \"C\"\n\n\n\n\n\n\n\n\n\ntype Cache struct {\n\tCache *C.leveldb_cache_t\n}\n\n\n\n\n\n\nfunc NewLRUCache(capacity int) *Cache {\n\treturn &Cache{C.leveldb_cache_create_lru(C.size_t(capacity))}\n}\n\n\n\n\nfunc (c *Cache) Close() ", "output": "{\n\tC.leveldb_cache_destroy(c.Cache)\n}"} {"input": "package jit\n\nconst SUPPORTED = true\n\nfunc (asm *Asm) prologue() *Asm {\n\treturn asm.Bytes(0x48, 0x8b, 0x7c, 0x24, 0x08) \n}\n\n\n\nfunc (asm *Asm) epilogue() *Asm ", "output": "{\n\treturn asm.Bytes(0xc3) \n}"} {"input": "package memfs\n\nimport (\n\t\"io\"\n\t\"testing\"\n\n\t\"gopkg.in/src-d/go-billy.v4\"\n\t\"gopkg.in/src-d/go-billy.v4/test\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype MemorySuite struct {\n\ttest.FilesystemSuite\n\tpath string\n}\n\nvar _ = Suite(&MemorySuite{})\n\nfunc (s *MemorySuite) SetUpTest(c *C) {\n\ts.FilesystemSuite = test.NewFilesystemSuite(New())\n}\n\n\n\nfunc (s *MemorySuite) TestNegativeOffsets(c *C) {\n\tf, err := s.FS.Create(\"negative\")\n\tc.Assert(err, IsNil)\n\n\tbuf := make([]byte, 100)\n\t_, err = f.ReadAt(buf, -100)\n\tc.Assert(err, ErrorMatches, \"readat negative: negative offset\")\n\n\t_, err = f.Seek(-100, io.SeekCurrent)\n\tc.Assert(err, IsNil)\n\t_, err = f.Write(buf)\n\tc.Assert(err, ErrorMatches, \"writeat negative: negative offset\")\n}\n\nfunc (s *MemorySuite) TestCapabilities(c *C) ", "output": "{\n\t_, ok := s.FS.(billy.Capable)\n\tc.Assert(ok, Equals, true)\n\n\tcaps := billy.Capabilities(s.FS)\n\tc.Assert(caps, Equals, billy.DefaultCapabilities&^billy.LockCapability)\n}"} {"input": "package geocoder\n\nimport \"testing\"\n\n\n\nfunc TestLongitude(t *testing.T) {\n\tgeoPoint, _ := NewGeoPoint(\"59.939095 30.315868\")\n\tif geoPoint.Longitude() != 59.939095 {\n\t\tt.Fatal(\"Error return longitude\")\n\t}\n}\n\nfunc TestLatitude(t *testing.T) {\n\tgeoPoint, _ := NewGeoPoint(\"59.939095 30.315868\")\n\tif geoPoint.Latitude() != 30.315868 {\n\t\tt.Fatal(\"Error return latitude\")\n\t}\n}\n\nfunc TestString(t *testing.T) {\n\tgeoPoint, _ := NewGeoPoint(\"59.939095 30.315868\")\n\tif geoPoint.String() != \"59.939095 30.315868\" {\n\t\tt.Fatal(\"Error return coordinates string\")\n\t}\n}\n\nfunc TestNewGeoPoint(t *testing.T) ", "output": "{\n\tgeoPoint, err := NewGeoPoint(\"59.939095 30.315868\")\n\tif err != nil {\n\t\tt.Fatal(\"Error parsing geo coordinates\")\n\t}\n\n\tif geoPoint.longitude != 59.939095 {\n\t\tt.Fatal(\"Error parsing longitude\")\n\t}\n\n\tif geoPoint.latitude != 30.315868 {\n\t\tt.Fatal(\"Error parsing latitude\")\n\t}\n}"} {"input": "package strain\n\ntype Ints []int\ntype Lists [][]int\ntype Strings []string\n\nfunc (i Ints) Keep(filter func(int) bool) Ints {\n\tif i == nil {\n\t\treturn nil\n\t}\n\tfiltered := []int{}\n\tfor _, v := range i {\n\t\tif filter(v) {\n\t\t\tfiltered = append(filtered, v)\n\t\t}\n\t}\n\ti = filtered\n\treturn i\n}\n\nfunc (i Ints) Discard(filter func(int) bool) Ints {\n\tif i == nil {\n\t\treturn nil\n\t}\n\treturn i.Keep(func(i int) bool {\n\t\treturn !filter(i)\n\t})\n}\n\nfunc (l Lists) Keep(filter func([]int) bool) Lists {\n\tif l == nil {\n\t\treturn nil\n\t}\n\tfiltered := [][]int{}\n\tfor _, v := range l {\n\t\tif filter(v) {\n\t\t\tfiltered = append(filtered, v)\n\t\t}\n\t}\n\tl = filtered\n\treturn l\n}\n\n\n\nfunc (s Strings) Keep(filter func(string) bool) Strings ", "output": "{\n\tif s == nil {\n\t\treturn nil\n\t}\n\tfiltered := []string{}\n\tfor _, v := range s {\n\t\tif filter(v) {\n\t\t\tfiltered = append(filtered, v)\n\t\t}\n\t}\n\ts = filtered\n\treturn s\n}"} {"input": "package api\n\ntype Memstore map[string]*Collection\n\nfunc (m Memstore) Init(dbName string) error {\n\treturn nil\n}\n\n\n\nfunc (m Memstore) UpdateCollection(slug, name string) error {\n\tif c, ok := m[slug]; !ok {\n\t\treturn CollectionNotFoundError\n\t} else {\n\t\tc.Name = name\n\t}\n\treturn nil\n}\n\nfunc (m Memstore) GetCollectionData(slug string) (Collection, error) {\n\tif c, ok := m[slug]; ok {\n\t\t(*c).Items = nil\n\t\treturn *c, nil\n\t}\n\treturn Collection{}, CollectionNotFoundError\n}\n\nfunc (m Memstore) GetCollectionItems(slug string) (map[string]Item, error) {\n\tif c, ok := m[slug]; ok {\n\t\treturn c.Items, nil\n\t}\n\treturn map[string]Item{}, CollectionNotFoundError\n}\n\nfunc (m Memstore) AddItemToCollection(slug string, item Item) error {\n\tif c, ok := m[slug]; ok {\n\t\tc.Items[item.Tag] = item\n\t\treturn nil\n\t}\n\treturn CollectionNotFoundError\n}\n\nfunc (m Memstore) GetItemFromCollection(slug, tag string) (Item, error) {\n\tif _, ok := m[slug]; !ok {\n\t\treturn Item{}, CollectionNotFoundError\n\t}\n\tif _, ok := m[slug].Items[tag]; !ok {\n\t\treturn Item{}, BlobNotFoundError\n\t}\n\treturn m[slug].Items[tag], nil\n}\n\nfunc (m Memstore) CreateCollection(slug, name string) (Collection, error) ", "output": "{\n\tm[slug] = &Collection{Name: name,\n\t\tSlug: slug,\n\t\tItems: map[string]Item{},\n\t}\n\treturn *m[slug], nil\n}"} {"input": "package net\n\nimport (\n\t\"time\"\n)\n\n\n\n\nfunc setKeepAlivePeriod(fd *netFD, d time.Duration) error ", "output": "{\n\tcmd := \"keepalive \" + string(int64(d/time.Millisecond))\n\t_, e := fd.ctl.WriteAt([]byte(cmd), 0)\n\treturn e\n}"} {"input": "package license\n\nimport (\n\t\"context\"\n\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n)\n\nfunc (s *Service) Find(req *FindRequest) ([]*sacloud.License, error) {\n\treturn s.FindWithContext(context.Background(), req)\n}\n\n\n\nfunc (s *Service) FindWithContext(ctx context.Context, req *FindRequest) ([]*sacloud.License, error) ", "output": "{\n\tif err := req.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams, err := req.ToRequestParameter()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := sacloud.NewLicenseOp(s.caller)\n\tfound, err := client.Find(ctx, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn found.Licenses, nil\n}"} {"input": "package render\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (e *Engine) JavaScript(names ...string) Renderer {\n\tif e.JavaScriptLayout != \"\" && len(names) == 1 {\n\t\tnames = append(names, e.JavaScriptLayout)\n\t}\n\thr := &templateRenderer{\n\t\tEngine: e,\n\t\tcontentType: \"application/javascript\",\n\t\tnames: names,\n\t}\n\treturn hr\n}\n\nfunc JavaScript(names ...string) Renderer ", "output": "{\n\te := New(Options{})\n\treturn e.JavaScript(names...)\n}"} {"input": "package i3ipc\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestGetBarConfig(t *testing.T) ", "output": "{\n\tipc, _ := GetIPCSocket()\n\n\tids, err := ipc.GetBarIds()\n\tif err != nil {\n\t\tt.Errorf(\"Getting bar IDs failed: %v\", err)\n\t}\n\n\tid := ids[0]\n\t_, err = ipc.GetBarConfig(id)\n\tif err != nil {\n\t\tt.Errorf(\"Getting bar config failed: %v\", err)\n\t}\n}"} {"input": "package backend\n\nimport (\n\t\"net/http\"\n)\n\nconst (\n\tCONSENT_SAMPLE_PATH = \"/\" + CATEGORY_SAMPLE_TEMPLATES + \"/consent/\"\n)\n\nfunc InitAmpConsent() {\n\tRegisterHandler(CONSENT_SAMPLE_PATH+\"getConsent\", onlyPost(submitConsentXHR))\n}\n\n\n\nfunc submitConsentXHR(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tSendJsonResponse(w, map[string]bool{\n\t\t\"promptIfUnknown\": true,\n\t})\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSIoTAnalyticsPipeline_DeviceShadowEnrich struct {\n\n\tAttribute string `json:\"Attribute,omitempty\"`\n\n\tName string `json:\"Name,omitempty\"`\n\n\tNext string `json:\"Next,omitempty\"`\n\n\tRoleArn string `json:\"RoleArn,omitempty\"`\n\n\tThingName string `json:\"ThingName,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) AWSCloudFormationType() string {\n\treturn \"AWS::IoTAnalytics::Pipeline.DeviceShadowEnrich\"\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\n\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetDependsOn(dependencies []string) ", "output": "{\n\tr._dependsOn = dependencies\n}"} {"input": "package hawkular\n\nimport (\n\t\"net/url\"\n\t\"sync\"\n\n\t\"github.com/adfin/statster/metrics/core\"\n\thawkular \"github.com/hawkular/hawkular-client-go/metrics\"\n)\n\ntype Filter func(ms *core.MetricSet, metricName string) bool\ntype FilterType int\n\nconst (\n\tLabel FilterType = iota\n\tName\n\tUnknown\n)\n\nfunc (f FilterType) From(s string) FilterType {\n\tswitch s {\n\tcase \"label\":\n\t\treturn Label\n\tcase \"name\":\n\t\treturn Name\n\tdefault:\n\t\treturn Unknown\n\t}\n}\n\ntype hawkularSink struct {\n\tclient *hawkular.Client\n\tmodels map[string]*hawkular.MetricDefinition \n\tregLock sync.RWMutex\n\treg map[string]*hawkular.MetricDefinition \n\n\turi *url.URL\n\n\tlabelTenant string\n\tlabelNodeId string\n\tlabelTagPrefix string\n\tmodifiers []hawkular.Modifier\n\tfilters []Filter\n\n\tdisablePreCaching bool\n\tbatchSize int\n}\n\n\n\nfunc heapsterTypeToHawkularType(t core.MetricType) hawkular.MetricType ", "output": "{\n\tswitch t {\n\tcase core.MetricCumulative:\n\t\treturn hawkular.Counter\n\tcase core.MetricGauge:\n\t\treturn hawkular.Gauge\n\tdefault:\n\t\treturn hawkular.Gauge\n\t}\n}"} {"input": "package v1beta1\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/knative-gcp/pkg/apis/duck\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\t\"github.com/google/go-cmp/cmp/cmpopts\"\n\n\t\"knative.dev/pkg/apis\"\n)\n\nfunc (t *Topic) Validate(ctx context.Context) *apis.FieldError {\n\terr := t.Spec.Validate(ctx).ViaField(\"spec\")\n\n\tif apis.IsInUpdate(ctx) {\n\t\toriginal := apis.GetBaseline(ctx).(*Topic)\n\t\terr = err.Also(t.CheckImmutableFields(ctx, original))\n\t}\n\treturn err\n}\n\nfunc (ts *TopicSpec) Validate(ctx context.Context) *apis.FieldError {\n\tvar errs *apis.FieldError\n\n\tif ts.Topic == \"\" {\n\t\terrs = errs.Also(\n\t\t\tapis.ErrMissingField(\"topic\"),\n\t\t)\n\t}\n\n\tswitch ts.PropagationPolicy {\n\tcase TopicPolicyCreateDelete, TopicPolicyCreateNoDelete, TopicPolicyNoCreateNoDelete:\n\n\tdefault:\n\t\terrs = errs.Also(\n\t\t\tapis.ErrInvalidValue(ts.PropagationPolicy, \"propagationPolicy\"),\n\t\t)\n\t}\n\n\treturn errs\n}\n\n\n\nfunc (current *Topic) CheckImmutableFields(ctx context.Context, original *Topic) *apis.FieldError ", "output": "{\n\tif original == nil {\n\t\treturn nil\n\t}\n\n\tvar errs *apis.FieldError\n\tif diff := cmp.Diff(original.Spec, current.Spec,\n\t\tcmpopts.IgnoreFields(TopicSpec{})); diff != \"\" {\n\t\terrs = errs.Also(&apis.FieldError{\n\t\t\tMessage: \"Immutable fields changed (-old +new)\",\n\t\t\tPaths: []string{\"spec\"},\n\t\t\tDetails: diff,\n\t\t})\n\t}\n\terrs = duck.CheckImmutableAutoscalingClassAnnotations(¤t.ObjectMeta, &original.ObjectMeta, errs)\n\n\treturn duck.CheckImmutableClusterNameAnnotation(¤t.ObjectMeta, &original.ObjectMeta, errs)\n}"} {"input": "package nodes\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\ntype Name struct {\n\tTaxID string `json:\"TaxID\"`\n\tNames []NameItem `json:\"Names\"`\n}\n\n\ntype NameItem struct {\n\tName string `json:\"Name\"`\n\tUniqueName string `json:\"UniqueName\"`\n\tNameClass string `json:\"NameClass\"`\n}\n\n\nfunc (name Name) ToJSON() (string, error) {\n\ts, err := json.Marshal(name)\n\treturn string(s), err\n}\n\n\nfunc NameFromJSON(s string) (Name, error) {\n\tvar name Name\n\terr := json.Unmarshal([]byte(s), &name)\n\treturn name, err\n}\n\n\nfunc NameFromArgs(items []string) Name {\n\tif len(items) != 4 {\n\t\treturn Name{}\n\t}\n\n\treturn Name{\n\t\tTaxID: items[0],\n\t\tNames: []NameItem{\n\t\t\tNameItem{\n\t\t\t\tName: items[1],\n\t\t\t\tUniqueName: items[2],\n\t\t\t\tNameClass: items[3],\n\t\t\t}},\n\t}\n}\n\n\nfunc MergeNames(names ...Name) Name {\n\tif len(names) < 2 {\n\t\treturn names[0]\n\t}\n\tname := names[0]\n\tfor _, another := range names[1:] {\n\t\tif another.TaxID != name.TaxID {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, anotherNameItem := range another.Names {\n\t\t\tname.Names = append(name.Names, anotherNameItem)\n\t\t}\n\t}\n\treturn name\n}\n\n\nvar Names map[string]Name\n\nvar mutex1 = &sync.Mutex{}\n\n\n\n\nfunc SetNames(names map[string]Name) ", "output": "{\n\tmutex1.Lock()\n\tNames = names\n\tmutex1.Unlock()\n}"} {"input": "package texture\n\nimport (\n\t. \"github.com/barnex/bruteray/geom\"\n\t. \"github.com/barnex/bruteray/imagef/colorf\"\n)\n\n\ntype Func2D func(u, v float64) Color\n\n\n\nfunc (f Func2D) AtUV(u, v float64) Color {\n\treturn f(u, v)\n}\n\n\n\ntype Func func(p Vec) Color\n\nfunc (f Func) At(p Vec) Color {\n\treturn f(p)\n}\n\nfunc (f Func2D) At(p Vec) Color ", "output": "{\n\treturn f(p[0], p[1])\n}"} {"input": "package common\n\nimport (\n\t\"os/exec\"\n)\n\nconst VMWARE_PLAYER_VERSION = \"6\"\n\n\n\n\ntype Player6Driver struct {\n\tPlayer5Driver\n}\n\n\n\nfunc (d *Player6Driver) Verify() error {\n\tif err := d.Player5Driver.Verify(); err != nil {\n\t\treturn err\n\t}\n\n\treturn playerVerifyVersion(VMWARE_PLAYER_VERSION)\n}\n\nfunc (d *Player6Driver) Clone(dst, src string) error ", "output": "{\n\n\tcmd := exec.Command(d.Player5Driver.VmrunPath,\n\t\t\"-T\", \"ws\",\n\t\t\"clone\", src, dst,\n\t\t\"full\")\n\n\tif _, _, err := runAndLog(cmd); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package paypal\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nconst format = \"2006-01-02T15:04:05Z\"\n\n\ntype Filter struct {\n\tfields []fmt.Stringer\n}\n\nfunc (s *Filter) String() string {\n\tvar filter string\n\tfor i, f := range s.fields {\n\t\tif i == 0 {\n\t\t\tfilter = \"?\" + f.String()\n\t\t} else {\n\t\t\tfilter = filter + \"&\" + f.String()\n\t\t}\n\t}\n\n\treturn filter\n}\n\n\ntype TextField struct {\n\tname string\n\tIs string\n}\n\nfunc (d TextField) String() string {\n\treturn fmt.Sprintf(\"%s=%s\", d.name, d.Is)\n}\n\n\ntype TimeField struct {\n\tname string\n\tIs time.Time\n}\n\n\nfunc (d TimeField) String() string {\n\treturn fmt.Sprintf(\"%s=%s\", d.name, d.Is.UTC().Format(format))\n}\n\n\nfunc (s *Filter) AddTextField(field string) *TextField {\n\tf := &TextField{name: field}\n\ts.fields = append(s.fields, f)\n\treturn f\n}\n\n\n\n\nfunc (s *Filter) AddTimeField(field string) *TimeField ", "output": "{\n\tf := &TimeField{name: field}\n\ts.fields = append(s.fields, f)\n\treturn f\n}"} {"input": "package http\n\nimport (\n\t\"fmt\"\n\t\"github.com/denniscollective/dragonfly.go/dragonfly\"\n\t\"github.com/gorilla/handlers\"\n\t\"github.com/gorilla/mux\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc StartServer() error {\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"/favicon.ico\", hollar)\n\tr.HandleFunc(\"/{b64JobString}\", serveFile)\n\n\terr := http.ListenAndServe(\":2345\", handle(r))\n\treturn err\n}\n\ntype benchmarkHandler struct {\n\thandler http.Handler\n}\n\n\n\nfunc handle(h http.Handler) http.Handler {\n\n\treturn benchmarkHandler{handlers.CombinedLoggingHandler(os.Stdout, h)}\n\n}\n\nfunc hollar(response http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"hollar\")\n}\n\nfunc serveFile(response http.ResponseWriter, request *http.Request) {\n\tresponse.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\tvars := mux.Vars(request)\n\tjobStr := vars[\"b64JobString\"]\n\tfile, err := dragonfly.ImageFor(jobStr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tdata, _ := ioutil.ReadAll(file)\n\tresponse.Write(data)\n}\n\nfunc (h benchmarkHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tt := time.Now()\n\th.handler.ServeHTTP(w, req)\n\tfmt.Println(time.Now().Sub(t))\n}"} {"input": "package codegen\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"goa.design/goa/v3/codegen/service\"\n\t\"goa.design/goa/v3/expr\"\n)\n\n\nfunc RunHTTPDSL(t *testing.T, dsl func()) *expr.RootExpr {\n\tservice.Services = make(service.ServicesData)\n\tHTTPServices = make(ServicesData)\n\treturn expr.RunDSL(t, dsl)\n}\n\n\n\n\n\n\nfunc makeGolden(t *testing.T, p string) *os.File ", "output": "{\n\tt.Helper()\n\tif os.Getenv(\"GOLDEN\") == \"\" {\n\t\treturn nil\n\t}\n\tf, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY, 0600)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn f\n}"} {"input": "package osutil\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n\n\n\n\n\n\nfunc IsDir(base, name string) bool ", "output": "{\n\tpath := base\n\tinfo, err := Lstat(path)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif !info.IsDir() {\n\t\treturn false\n\t}\n\n\tif name == \".\" {\n\t\treturn true\n\t}\n\n\tparts := strings.Split(name, string(os.PathSeparator))\n\tfor _, part := range parts {\n\t\tpath = filepath.Join(path, part)\n\t\tinfo, err := Lstat(path)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tif info.Mode()&os.ModeSymlink != 0 {\n\t\t\treturn false\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package clock\n\nimport \"time\"\n\n\nvar Work Clock\n\nfunc init() {\n\tWork = New()\n}\n\n\nfunc Now() time.Time {\n\treturn Work.Now()\n}\n\n\n\n\n\nfunc Sleep(d time.Duration) {\n\tWork.Sleep(d)\n}\n\n\n\nfunc After(d time.Duration) <-chan time.Time {\n\treturn Work.After(d)\n}\n\n\n\nfunc Tick(d time.Duration) <-chan time.Time {\n\treturn Work.Tick(d)\n}\n\n\n\n\n\nfunc Ticker(d time.Duration) *time.Ticker {\n\treturn Work.Ticker(d)\n}\n\n\ntype Clock interface {\n\n\tNow() time.Time\n\n\tSleep(d time.Duration)\n\n\tAfter(d time.Duration) <-chan time.Time\n\n\tTick(d time.Duration) <-chan time.Time\n\n\tTicker(d time.Duration) *time.Ticker\n\n}\n\n\ntype Mock interface {\n\tClock\n\n\n\tSet(t time.Time) Mock\n\n\tAdd(d time.Duration) Mock\n\n\tFreeze() Mock\n\n\tIsFrozen() bool\n\n\tUnfreeze() Mock\n\n\tClose()\n}\n\nfunc Since(t time.Time) time.Duration ", "output": "{\n\treturn Work.Now().Sub(t)\n}"} {"input": "package policy\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/rightscale/rsc/rsapi\"\n)\n\nconst (\n\tAPIName = \"RightScale Policy API 1.0\"\n)\n\n\nvar commandValues rsapi.ActionCommands\n\n\nfunc RegisterCommands(registrar rsapi.APICommandRegistrar) {\n\tcommandValues = rsapi.ActionCommands{}\n\tregistrar.RegisterActionCommands(APIName, GenMetadata, commandValues)\n}\n\n\nfunc (a *API) RunCommand(cmd string) (*http.Response, error) {\n\tc, err := a.ParseCommand(cmd, \"/api\", commandValues)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := a.BuildHTTPRequest(c.HTTPMethod, c.URI, \"1.0\", c.QueryParams, c.PayloadParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn a.PerformRequest(req)\n}\n\n\n\n\n\nfunc (a *API) ShowAPIActions(cmd string) error {\n\treturn a.ShowActions(cmd, \"/api\", commandValues)\n}\n\nfunc (a *API) ShowCommandHelp(cmd string) error ", "output": "{\n\treturn a.ShowHelp(cmd, \"/api\", commandValues)\n}"} {"input": "package timeutil\n\nimport (\n\t\"time\"\n)\n\n\nfunc SetTimeout(t time.Duration, callback func()) {\n\tgo func() {\n\t\ttime.Sleep(t)\n\t\tcallback()\n\t}()\n}\n\n\n\nfunc SetInterval(t time.Duration, callback func() bool) {\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(t)\n\t\t\tif !callback() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\n\n\n\nfunc Microsecond() int64 {\n\treturn time.Now().UnixNano() / 1e3\n}\n\n\nfunc Millisecond() int64 {\n\treturn time.Now().UnixNano() / 1e6\n}\n\n\nfunc Second() int64 {\n\treturn time.Now().UnixNano() / 1e9\n}\n\n\nfunc Date() string {\n\treturn time.Now().Format(\"2006-01-02\")\n}\n\n\nfunc Datetime() string {\n\treturn time.Now().Format(\"2006-01-02 15:04:05\")\n}\n\n\n\nfunc Format(format string, timestamps ...int64) string {\n\ttimestamp := Second()\n\tif len(timestamps) > 0 {\n\t\ttimestamp = timestamps[0]\n\t}\n\treturn time.Unix(timestamp, 0).Format(format)\n}\n\n\nfunc StrToTime(format string, timestr string) (int64, error) {\n\tt, err := time.Parse(format, timestr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn t.Unix(), nil\n}\n\nfunc Nanosecond() int64 ", "output": "{\n\treturn time.Now().UnixNano()\n}"} {"input": "package fs\n\nimport (\n\t\"github.com/opencontainers/runc/libcontainer/cgroups\"\n\t\"github.com/opencontainers/runc/libcontainer/cgroups/fscommon\"\n\t\"github.com/opencontainers/runc/libcontainer/configs\"\n)\n\ntype NetPrioGroup struct {\n}\n\nfunc (s *NetPrioGroup) Name() string {\n\treturn \"net_prio\"\n}\n\nfunc (s *NetPrioGroup) Apply(path string, d *cgroupData) error {\n\treturn join(path, d.pid)\n}\n\n\n\nfunc (s *NetPrioGroup) GetStats(path string, stats *cgroups.Stats) error {\n\treturn nil\n}\n\nfunc (s *NetPrioGroup) Set(path string, r *configs.Resources) error ", "output": "{\n\tfor _, prioMap := range r.NetPrioIfpriomap {\n\t\tif err := fscommon.WriteFile(path, \"net_prio.ifpriomap\", prioMap.CgroupString()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package kafka\n\nimport (\n\t\"github.com/hyperledger/fabric/orderer/config\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n)\n\n\ntype Orderer interface {\n\tBroadcast(stream ab.AtomicBroadcast_BroadcastServer) error\n\tDeliver(stream ab.AtomicBroadcast_DeliverServer) error\n\tTeardown() error\n}\n\n\ntype Closeable interface {\n\tClose() error\n}\n\ntype serverImpl struct {\n\tbroadcaster Broadcaster\n\tdeliverer Deliverer\n}\n\n\nfunc New(conf *config.TopLevel) Orderer {\n\treturn &serverImpl{\n\t\tbroadcaster: newBroadcaster(conf),\n\t\tdeliverer: newDeliverer(conf),\n\t}\n}\n\n\n\n\n\nfunc (s *serverImpl) Deliver(stream ab.AtomicBroadcast_DeliverServer) error {\n\treturn s.deliverer.Deliver(stream)\n}\n\n\nfunc (s *serverImpl) Teardown() error {\n\ts.deliverer.Close()\n\treturn s.broadcaster.Close()\n}\n\nfunc (s *serverImpl) Broadcast(stream ab.AtomicBroadcast_BroadcastServer) error ", "output": "{\n\treturn s.broadcaster.Broadcast(stream)\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n)\n\nfunc Run() {\n\tHandle()\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\n\n\nfunc Handle() ", "output": "{\n\thttp.Handle(\"/\", NewRouter())\n}"} {"input": "package helpers\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"runtime\"\n)\n\n\n\n\n\n\n\nfunc Uint16ToBytes(value uint16) [2]byte {\n\tbyte0 := byte(value >> 8)\n\tbyte1 := byte(0x00ff & value) \n\treturn [2]byte{byte0, byte1}\n}\n\n\n\n\n\n\n\n\n\nfunc GetBytes(b *bytes.Buffer, n int) []byte {\n\tslice := make([]byte, n)\n\tnread, err := b.Read(slice)\n\tif err != nil || nread != n {\n\t\tpanic(errors.New(\"Unexpected end of data.\"))\n\t}\n\treturn slice\n}\n\n\n\n\nfunc GetByte(b *bytes.Buffer) byte {\n\tbyte, err := b.ReadByte()\n\tif err != nil {\n\t\tpanic(errors.New(\"Unexpected end of data\"))\n\t}\n\treturn byte\n}\n\n\n\n\nfunc HandleErrorPanic(err *error, functionName string) {\n\tif r := recover(); r != nil {\n\t\tif _, ok := r.(runtime.Error); ok {\n\t\t\tpanic(r)\n\t\t}\n\t\tperr := r.(error)\n\t\t*err = errors.New(functionName + \": \" + perr.Error())\n\t}\n}\n\nfunc BytesToUint16(field [2]byte) uint16 ", "output": "{\n\treturn uint16(field[0])<<8 | uint16(field[1])\n}"} {"input": "package schemareplication\n\nimport (\n\tcontext \"context\"\n\n\tv1beta1 \"github.com/rabbitmq/messaging-topology-operator/pkg/generated/informers/externalversions/rabbitmq.com/v1beta1\"\n\tfactory \"knative.dev/eventing-rabbitmq/pkg/client/injection/rabbitmq.com/informers/factory\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Default.RegisterInformer(withInformer)\n}\n\n\ntype Key struct{}\n\nfunc withInformer(ctx context.Context) (context.Context, controller.Informer) {\n\tf := factory.Get(ctx)\n\tinf := f.Rabbitmq().V1beta1().SchemaReplications()\n\treturn context.WithValue(ctx, Key{}, inf), inf.Informer()\n}\n\n\n\n\nfunc Get(ctx context.Context) v1beta1.SchemaReplicationInformer ", "output": "{\n\tuntyped := ctx.Value(Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch github.com/rabbitmq/messaging-topology-operator/pkg/generated/informers/externalversions/rabbitmq.com/v1beta1.SchemaReplicationInformer from context.\")\n\t}\n\treturn untyped.(v1beta1.SchemaReplicationInformer)\n}"} {"input": "package dev\n\nimport \"fmt\"\n\n\n\ntype Configuration struct {\n\tid uint32\n\tnodes []*Node\n\tn int\n\tmgr *Manager\n\tqspec QuorumSpec\n\terrs chan CallGRPCError\n}\n\n\n\nfunc (c *Configuration) SubError() <-chan CallGRPCError {\n\treturn c.errs\n}\n\n\nfunc (c *Configuration) ID() uint32 {\n\treturn c.id\n}\n\n\n\n\nfunc (c *Configuration) NodeIDs() []uint32 {\n\tids := make([]uint32, len(c.nodes))\n\tfor i, node := range c.nodes {\n\t\tids[i] = node.ID()\n\t}\n\treturn ids\n}\n\n\n\nfunc (c *Configuration) Nodes() []*Node {\n\treturn c.nodes\n}\n\n\nfunc (c *Configuration) Size() int {\n\treturn c.n\n}\n\nfunc (c *Configuration) String() string {\n\treturn fmt.Sprintf(\"configuration %d\", c.id)\n}\n\nfunc (c *Configuration) tstring() string {\n\treturn fmt.Sprintf(\"config-%d\", c.id)\n}\n\n\n\nfunc Equal(a, b *Configuration) bool { return a.id == b.id }\n\n\n\n\n\n\nfunc NewTestConfiguration(q, n int) *Configuration ", "output": "{\n\treturn &Configuration{\n\t\tnodes: make([]*Node, n),\n\t}\n}"} {"input": "package utils\n\ntype Set map[string]bool\n\nfunc (self Set) Contains(key string) bool {\n\t_, found := self[key]\n\treturn found\n}\n\n\n\nfunc (self Set) Remove(key string) {\n\tdelete(self, key)\n}\n\nfunc (self Set) Size() int {\n\treturn len(self)\n}\n\nfunc (self Set) Insert(key string) ", "output": "{\n\tself[key] = true\n}"} {"input": "package model\n\nimport (\n\t\"time\"\n\n\t\"github.com/NyaaPantsu/nyaa/config\"\n)\n\n\n\ntype TorrentReport struct {\n\tID uint `gorm:\"column:torrent_report_id;primary_key\"`\n\tDescription string `gorm:\"column:type\"`\n\tTorrentID uint `gorm:\"column:torrent_id\"`\n\tUserID uint `gorm:\"column:user_id\"`\n\n\tCreatedAt time.Time `gorm:\"column:created_at\"`\n\n\tTorrent *Torrent `gorm:\"AssociationForeignKey:TorrentID;ForeignKey:torrent_id\"`\n\tUser *User `gorm:\"AssociationForeignKey:UserID;ForeignKey:user_id\"`\n}\n\nfunc (r TorrentReport) TableName() string {\n\treturn config.ReportsTableName\n}\n\ntype TorrentReportJson struct {\n\tID uint `json:\"id\"`\n\tDescription string `json:\"description\"`\n\tTorrent TorrentJSON `json:\"torrent\"`\n\tUser UserJSON `json:\"user\"`\n}\n\n\n\n\n\nfunc (report *TorrentReport) ToJson() TorrentReportJson {\n\tvar t TorrentJSON = TorrentJSON{}\n\tif report.Torrent != nil { \n\t\tt = report.Torrent.ToJSON()\n\t}\n\tvar u UserJSON = UserJSON{}\n\tif report.User != nil {\n\t\tu = report.User.ToJSON()\n\t}\n\tjson := TorrentReportJson{report.ID, getReportDescription(report.Description), t, u}\n\treturn json\n}\n\nfunc TorrentReportsToJSON(reports []TorrentReport) []TorrentReportJson {\n\tjson := make([]TorrentReportJson, len(reports))\n\tfor i := range reports {\n\t\tjson[i] = reports[i].ToJson()\n\t}\n\treturn json\n}\n\nfunc getReportDescription(d string) string ", "output": "{\n\tif d == \"illegal\" {\n\t\treturn \"Illegal content\"\n\t} else if d == \"spam\" {\n\t\treturn \"Spam / Garbage\"\n\t} else if d == \"wrongcat\" {\n\t\treturn \"Wrong category\"\n\t} else if d == \"dup\" {\n\t\treturn \"Duplicate / Deprecated\"\n\t}\n\treturn \"???\"\n}"} {"input": "package redis3\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/chrislusf/seaweedfs/weed/filer\"\n\t\"github.com/go-redis/redis/v8\"\n)\n\n\n\nfunc (store *UniversalRedis3Store) KvGet(ctx context.Context, key []byte) (value []byte, err error) {\n\n\tdata, err := store.Client.Get(ctx, string(key)).Result()\n\n\tif err == redis.Nil {\n\t\treturn nil, filer.ErrKvNotFound\n\t}\n\n\treturn []byte(data), err\n}\n\nfunc (store *UniversalRedis3Store) KvDelete(ctx context.Context, key []byte) (err error) {\n\n\t_, err = store.Client.Del(ctx, string(key)).Result()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"kv delete: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (store *UniversalRedis3Store) KvPut(ctx context.Context, key []byte, value []byte) (err error) ", "output": "{\n\n\t_, err = store.Client.Set(ctx, string(key), value, 0).Result()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"kv put: %v\", err)\n\t}\n\n\treturn nil\n}"} {"input": "package routers\n\nimport (\n\t\"github.com/codegangsta/negroni\"\n\t\"github.com/gorilla/mux\"\n\t\"restful-api/common\"\n\t\"restful-api/controllers\"\n)\n\n\n\nfunc SetNoteRoutes(router *mux.Router) *mux.Router ", "output": "{\n\tnoteRouter := mux.NewRouter()\n\tnoteRouter.HandleFunc(\"/notes\", controllers.CreateNote).Methods(\"POST\")\n\tnoteRouter.HandleFunc(\"/notes/{id}\", controllers.UpdateNote).Methods(\"PUT\")\n\tnoteRouter.HandleFunc(\"/notes/{id}\", controllers.GetNoteById).Methods(\"GET\")\n\tnoteRouter.HandleFunc(\"/notes/{id}\", controllers.DeleteNoteById).Methods(\"DELETE\")\n\n\tnoteRouter.HandleFunc(\"/notes/tasks/{id}\", controllers.GetNotesByTask).Methods(\"GET\")\n\tnoteRouter.HandleFunc(\"/notes\", controllers.GetNotes).Methods(\"GET\")\n\n\trouter.PathPrefix(\"/notes\").Handler(negroni.New(\n\t\tnegroni.HandlerFunc(common.Authorize),\n\t\tnegroni.Wrap(noteRouter),\n\t))\n\treturn router\n}"} {"input": "package intacct\n\nimport \"fmt\"\n\ntype Error struct {\n\tNumber string `xml:\"error>errorno\"`\n\tDescription string `xml:\"error>description\"`\n\tDescription2 string `xml:\"error>description2\"`\n\tCorrection string `xml:\"error>correction\"`\n}\n\n\n\nfunc (err Error) String() string ", "output": "{\n\treturn fmt.Sprintf(\n\t\t\"%s: %s %s - %s\",\n\t\terr.Number,\n\t\terr.Description,\n\t\terr.Description2,\n\t\terr.Correction,\n\t)\n}"} {"input": "package controllers\n\nimport (\n\t\"net\"\n\n\t\"[[.project]]/app/models\"\n\t\"[[.project]]/app/routes\"\n\t\"github.com/revel/revel\"\n)\n\ntype PortalController struct {\n\t*revel.Controller\n}\n\nfunc (c PortalController) Index() revel.Result {\n\treturn c.RenderTemplate(\"index.html\")\n}\n\n\n\nfunc (c PortalController) Authorized() revel.Result {\n\tif _, ok := c.authorized(); !ok {\n\t\treturn c.Redirect(routes.AuthController.Login())\n\t}\n\treturn nil\n}\n\nfunc init() {\n\trevel.InterceptMethod(PortalController.Authorized, revel.BEFORE)\n}\n\nfunc (c PortalController) authorized() (interface{}, bool) ", "output": "{\n\tif secret, ok := c.Session[\"secret\"]; ok {\n\t\tremote, _, _ := net.SplitHostPort(c.Request.RemoteAddr)\n\t\tforward := c.Request.Header.Get(\"X-Forwarded-For\")\n\t\tif forward != \"\" {\n\t\t\tremote = forward\n\t\t}\n\n\t\ttoken, err := HitSystemToken(secret, remote)\n\t\tif err != nil {\n\t\t\trevel.WARN.Printf(\"authorized failed: %s\", err.Error())\n\t\t\treturn nil, false\n\t\t}\n\n\t\tvar account models.SystemAccount\n\t\taccount.ID = token.SystemAccountID\n\t\tif err := db.First(&account).Error; err != nil {\n\t\t\treturn nil, false\n\t\t}\n\t\tc.RenderArgs[\"account\"] = &account\n\t\treturn &token, true\n\t}\n\n\treturn nil, false\n}"} {"input": "package stringutil\n\nimport \"testing\"\n\n\nfunc BenchmarkHello(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tReverse(\"Hello\")\n\t}\n}\n\nfunc TestCall(t *testing.T) ", "output": "{\n\tcases := []struct {\n\t\tin, want string\n\t}{\n\t\t{\"Hello, world\", \"dlrow ,olleH\"},\n\t\t{\"Hello, 世界\", \"界世 ,olleH\"},\n\t\t{\"\", \"\"},\n\t}\n\tfor _, c := range cases {\n\t\tgot := Reverse(c.in)\n\t\tif got != c.want {\n\t\t\tt.Errorf(\"Reverse(%q) == %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}"} {"input": "package test\n\nimport (\n\t\"github.com/borgstrom/reeve/modules\"\n)\n\nfunc init() {\n\tmodules.Register(\"test\", modules.Functions{\n\t\t\"ping\": Ping,\n\t})\n}\n\n\n\nfunc Ping(in modules.Args, out modules.Args) error ", "output": "{\n\tout[\"reply\"] = \"pong\"\n\treturn nil\n}"} {"input": "package rpc\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/rpc\"\n\t\"net/rpc/jsonrpc\"\n\n\t\"github.com/eduardonunesp/sslb/lb\"\n)\n\ntype ServerStatus struct {\n\tServer *lb.Server\n}\n\ntype StatusResponse struct {\n\tIdleWPool int\n}\n\nfunc (s *ServerStatus) GetIdle(args interface{}, reply *StatusResponse) error {\n\tstatusRes := StatusResponse{\n\t\ts.Server.CountIdle(),\n\t}\n\n\t*reply = statusRes\n\treturn nil\n}\n\n\n\nfunc StartServer(s *lb.Server) ", "output": "{\n\tgo func() {\n\t\tserverStatus := &ServerStatus{s}\n\n\t\tserver := rpc.NewServer()\n\t\tserver.Register(serverStatus)\n\n\t\taddress := fmt.Sprintf(\"%s:%d\",\n\t\t\ts.Configuration.GeneralConfig.RPCHost,\n\t\t\ts.Configuration.GeneralConfig.RPCPort,\n\t\t)\n\n\t\tserver.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)\n\t\tlistener, e := net.Listen(\"tcp\", address)\n\t\tif e != nil {\n\t\t\tlog.Fatal(\"listen error:\", e)\n\t\t}\n\n\t\tfor {\n\t\t\tif conn, err := listener.Accept(); err != nil {\n\t\t\t\tlog.Fatal(\"accept error: \" + err.Error())\n\t\t\t} else {\n\t\t\t\tgo server.ServeCodec(jsonrpc.NewServerCodec(conn))\n\t\t\t}\n\t\t}\n\t}()\n}"} {"input": "package modules\n\nimport (\n\t\"testing\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestInArray(t *testing.T) {\n\tassert.Equal(t, InArray([]string{\"2\"}, \"2\"), true)\n}\n\n\n\nfunc TestIsInfoUrl(t *testing.T) ", "output": "{\n\tassert.Equal(t, IsInfoUrl(\"/admin/info/user?id=asfas\"), true)\n}"} {"input": "package monitoring\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype MetricDataDetails struct {\n\n\tNamespace *string `mandatory:\"true\" json:\"namespace\"`\n\n\tCompartmentId *string `mandatory:\"true\" json:\"compartmentId\"`\n\n\tName *string `mandatory:\"true\" json:\"name\"`\n\n\tDimensions map[string]string `mandatory:\"true\" json:\"dimensions\"`\n\n\tDatapoints []Datapoint `mandatory:\"true\" json:\"datapoints\"`\n\n\tResourceGroup *string `mandatory:\"false\" json:\"resourceGroup\"`\n\n\tMetadata map[string]string `mandatory:\"false\" json:\"metadata\"`\n}\n\n\n\nfunc (m MetricDataDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc generate() chan int {\n\tch := make(chan int)\n\tgo func() {\n\t\tfor i := 2; ; i++ {\n\t\t\tch <- i\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc filter(in chan int, prime int) chan int {\n\tout := make(chan int)\n\tgo func() {\n\t\tfor {\n\t\t\tif i := <-in; i%prime != 0 {\n\t\t\t\tout <- i\n\t\t\t}\n\t\t}\n\t}()\n\treturn out\n}\n\n\n\nfunc main() {\n\tprimes := sieve()\n\tfor {\n\t\tfmt.Println(<-primes)\n\t}\n}\n\nfunc sieve() chan int ", "output": "{\n\tout := make(chan int)\n\tgo func() {\n\t\tch := generate()\n\t\tfor {\n\t\t\tprime := <-ch\n\t\t\tch = filter(ch, prime)\n\t\t\tout <- prime\n\t\t}\n\t}()\n\treturn out\n}"} {"input": "package udp_vs_tcp\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"time\"\n)\n\ntype UDPServer struct {\n\tladdr string\n\tgen Generator\n\ttimeout time.Duration\n}\n\nfunc NewUDPServer(laddr string, timeout time.Duration, gen Generator) Server {\n\treturn &UDPServer{laddr, gen, timeout}\n}\n\nfunc (u *UDPServer) Measure(bufferSize int, kill chan struct{}) (chan *ServerMeasure, error) {\n\tladdr, err := net.ResolveUDPAddr(\"udp\", u.laddr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"resolving addr, %v\", err)\n\t}\n\tconn, err := net.ListenUDP(\"udp\", laddr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"listening, %v\", err)\n\t}\n\n\tgo func() {\n\t\t<-kill\n\t\tlog.Printf(\"Server received kill request\")\n\t\terr := conn.Close()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Closing connection, %v\", err)\n\t\t}\n\t}()\n\n\tmeasures := make(chan *ServerMeasure)\n\tgo func(mChan chan *ServerMeasure) {\n\t\tdefer conn.Close()\n\t\tdefer close(mChan)\n\n\t\tbuf := make([]byte, bufferSize)\n\t\tvar last time.Time\n\t\tfor {\n\t\t\tlast = time.Now()\n\t\t\tm, err := u.read(conn, buf, last)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tmChan <- m\n\t\t}\n\t}(measures)\n\treturn measures, nil\n}\n\n\n\nfunc (u *UDPServer) read(conn *net.UDPConn, buf []byte, last time.Time) (*ServerMeasure, error) ", "output": "{\n\terr := conn.SetDeadline(time.Now().Add(u.timeout))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"setting deadline for next read, %v\", err)\n\t}\n\n\tn, err := conn.Read(buf)\n\tnow := time.Now()\n\n\tm := &ServerMeasure{now, now.Sub(last), n, buf[:n], err}\n\n\tif err != nil && err != io.EOF {\n\t\treturn m, fmt.Errorf(\"reading, %v\", err)\n\t}\n\n\tif err == io.EOF && !u.gen.HasNext() {\n\t\treturn m, errors.New(\"expected next sequence but got EOF\")\n\t}\n\n\treturn m, nil\n}"} {"input": "package aggregator\n\nimport (\n\t\"github.com/CapillarySoftware/gostat/stat\"\n\t\"math\"\n)\n\n\n\n\n\n\n\n\n\nfunc AppendStatsAggregate(a, b StatsAggregate) (aggregate StatsAggregate) {\n\tif (a.Count == 0) {\n\t\treturn b\n\t}\n\n\tif (b.Count == 0) {\n\t\treturn a\n\t}\n\n\taggregate.Average = ( (a.Average * float64(a.Count)) + (b.Average * float64(b.Count)) ) / float64(a.Count + b.Count)\n\taggregate.Min = math.Min(a.Min, b.Min)\n\taggregate.Max = math.Max(a.Max, b.Max)\n\taggregate.Count = a.Count + b.Count\n\treturn\n}\n\nfunc Aggregate(stats []*stat.Stat) (aggregate StatsAggregate) ", "output": "{\n\tif stats == nil || len(stats) == 0 {\n\t\treturn StatsAggregate{}\n\t}\n\n\taggregate = StatsAggregate{Min : stats[0].Value, Max : stats[0].Value, Count : len(stats)}\n\tsum := 0.0\n\tfor i := range stats {\n\t\tv := stats[i].Value\n\n\t\tsum += v\n\n\t\tif v < aggregate.Min {\n\t\t\taggregate.Min = v\n\t\t}\n\n\t\tif v > aggregate.Max {\n\t\t\taggregate.Max = v\n\t\t}\n\t}\n\taggregate.Average = sum / float64(len(stats))\n\n\treturn\n}"} {"input": "package main\n\nimport \"github.com/icza/gowut/gwu\"\n\n\n\nfunc buildHomeTab(j *jawaInfo) (gwu.Panel, gwu.TextBox) ", "output": "{\n\n\tc := gwu.NewPanel()\n\tstb := gwu.NewTextBox(\"\")\n\tstb.Style().SetWidthPx(1).SetHeightPx(1)\n\tstb.AddEHandlerFunc(func(e gwu.Event) {\n\t\tNotify(\"Focus is on Home Tab\", e)\n\t}, gwu.ETypeFocus)\n\tc.Add(stb)\n\n\tc.Add(gwu.NewLabel(\"Yuli, What do you want to see on this page?\"))\n\n\treturn c, stb\n}"} {"input": "package fakes\n\nimport (\n\t\"os/exec\"\n\t\"sync\"\n\n\t\"github.com/cloudfoundry-incubator/genclient\"\n)\n\ntype CommandRunner struct {\n\tRunStub func(cmd *exec.Cmd) error\n\trunMutex sync.RWMutex\n\trunArgsForCall []struct {\n\t\tcmd *exec.Cmd\n\t}\n\trunReturns struct {\n\t\tresult1 error\n\t}\n}\n\nfunc (fake *CommandRunner) Run(cmd *exec.Cmd) error {\n\tfake.runMutex.Lock()\n\tfake.runArgsForCall = append(fake.runArgsForCall, struct {\n\t\tcmd *exec.Cmd\n\t}{cmd})\n\tfake.runMutex.Unlock()\n\tif fake.RunStub != nil {\n\t\treturn fake.RunStub(cmd)\n\t} else {\n\t\treturn fake.runReturns.result1\n\t}\n}\n\nfunc (fake *CommandRunner) RunCallCount() int {\n\tfake.runMutex.RLock()\n\tdefer fake.runMutex.RUnlock()\n\treturn len(fake.runArgsForCall)\n}\n\nfunc (fake *CommandRunner) RunArgsForCall(i int) *exec.Cmd {\n\tfake.runMutex.RLock()\n\tdefer fake.runMutex.RUnlock()\n\treturn fake.runArgsForCall[i].cmd\n}\n\n\n\nvar _ genclient.CommandRunnerInterface = new(CommandRunner)\n\nfunc (fake *CommandRunner) RunReturns(result1 error) ", "output": "{\n\tfake.RunStub = nil\n\tfake.runReturns = struct {\n\t\tresult1 error\n\t}{result1}\n}"} {"input": "package math\n\nimport \"jvmgo/ch06/instructions/base\"\nimport \"jvmgo/ch06/rtda\"\n\n\ntype IXOR struct{ base.NoOperandsInstruction }\n\nfunc (self *IXOR) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tv1 := stack.PopInt()\n\tv2 := stack.PopInt()\n\tresult := v1 ^ v2\n\tstack.PushInt(result)\n}\n\n\ntype LXOR struct{ base.NoOperandsInstruction }\n\n\n\nfunc (self *LXOR) Execute(frame *rtda.Frame) ", "output": "{\n\tstack := frame.OperandStack()\n\tv1 := stack.PopLong()\n\tv2 := stack.PopLong()\n\tresult := v1 ^ v2\n\tstack.PushLong(result)\n}"} {"input": "package client\n\nimport (\n\t\"github.com/kubeflow/pipelines/backend/src/common/util\"\n\t\"github.com/kubeflow/pipelines/backend/src/crd/pkg/client/informers/externalversions/scheduledworkflow/v1beta1\"\n\t_ \"k8s.io/client-go/plugin/pkg/client/auth/gcp\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\ntype ScheduledWorkflowClientInterface interface {\n\tGet(namespace string, name string) (swf *util.ScheduledWorkflow, err error)\n}\n\n\ntype ScheduledWorkflowClient struct {\n\tinformer v1beta1.ScheduledWorkflowInformer\n}\n\n\nfunc NewScheduledWorkflowClient(informer v1beta1.ScheduledWorkflowInformer) *ScheduledWorkflowClient {\n\treturn &ScheduledWorkflowClient{\n\t\tinformer: informer,\n\t}\n}\n\n\nfunc (c *ScheduledWorkflowClient) AddEventHandler(funcs *cache.ResourceEventHandlerFuncs) {\n\tc.informer.Informer().AddEventHandler(funcs)\n}\n\n\n\n\n\nfunc (c *ScheduledWorkflowClient) Get(namespace string, name string) (\n\tswf *util.ScheduledWorkflow, err error) {\n\tschedule, err := c.informer.Lister().ScheduledWorkflows(namespace).Get(name)\n\tif err != nil {\n\t\tvar code util.CustomCode\n\t\tif util.IsNotFound(err) {\n\t\t\tcode = util.CUSTOM_CODE_NOT_FOUND\n\t\t} else {\n\t\t\tcode = util.CUSTOM_CODE_GENERIC\n\t\t}\n\t\treturn nil, util.NewCustomError(err, code,\n\t\t\t\"Error retrieving scheduled workflow (%v) in namespace (%v): %v\", name, namespace, err)\n\t}\n\n\treturn util.NewScheduledWorkflow(schedule), nil\n}\n\nfunc (c *ScheduledWorkflowClient) HasSynced() func() bool ", "output": "{\n\treturn c.informer.Informer().HasSynced\n}"} {"input": "package testing\n\nimport (\n\t\"github.com/markdaws/gohome/pkg/cmd\"\n\t\"github.com/markdaws/gohome/pkg/gohome\"\n)\n\ntype extension struct {\n\tgohome.NullExtension\n}\n\nfunc (e *extension) Name() string {\n\treturn \"testing\"\n}\n\nfunc (e *extension) BuilderForDevice(sys *gohome.System, d *gohome.Device) cmd.Builder {\n\tswitch d.ModelNumber {\n\tcase \"testing.hardware\":\n\t\treturn &cmdBuilder{ModelNumber: d.ModelNumber, Device: d}\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (e *extension) NetworkForDevice(sys *gohome.System, d *gohome.Device) gohome.Network {\n\treturn nil\n}\n\n\n\nfunc (e *extension) Discovery(sys *gohome.System) gohome.Discovery {\n\treturn &discovery{}\n}\n\nfunc NewExtension() *extension {\n\treturn &extension{}\n}\n\nfunc (e *extension) EventsForDevice(sys *gohome.System, d *gohome.Device) *gohome.ExtEvents ", "output": "{\n\tswitch d.ModelNumber {\n\tcase \"testing.hardware\":\n\t\tevts := &gohome.ExtEvents{}\n\t\tevts.Producer = &producer{\n\t\t\tDevice: d,\n\t\t\tSystem: sys,\n\t\t}\n\t\tevts.Consumer = &consumer{\n\t\t\tDevice: d,\n\t\t\tSystem: sys,\n\t\t}\n\t\treturn evts\n\tdefault:\n\t\treturn nil\n\t}\n}"} {"input": "package console\n\nimport \"github.com/accurateproject/accurate/api/v1\"\n\nfunc init() {\n\tc := &CmdExecuteScheduledActions{\n\t\tname: \"scheduler_execute\",\n\t\trpcMethod: \"ApiV1.ExecuteScheduledActions\",\n\t\trpcParams: &v1.AttrsExecuteScheduledActions{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdExecuteScheduledActions struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrsExecuteScheduledActions\n\t*CommandExecuter\n}\n\nfunc (self *CmdExecuteScheduledActions) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdExecuteScheduledActions) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\n\n\nfunc (self *CmdExecuteScheduledActions) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdExecuteScheduledActions) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *CmdExecuteScheduledActions) RpcParams(reset bool) interface{} ", "output": "{\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrsExecuteScheduledActions{}\n\t}\n\treturn self.rpcParams\n}"} {"input": "package transform\n\nimport (\n\t\"bytes\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype CSSTransform struct {\n\turl_exp *regexp.Regexp\n\timp_exp *regexp.Regexp\n\n\tlink_trans *Transform\n}\n\n\n\nfunc (t *CSSTransform) Process(base_url string, text []byte) ([]byte, error) {\n\tres := t.url_exp.ReplaceAllFunc(text, func(link []byte) []byte {\n\t\tlength := len(link)\n\t\tif length == 0 {\n\t\t\treturn []byte(\"\")\n\t\t}\n\n\t\tvar ll string\n\t\tif bytes.HasPrefix(link, []byte(\"url(\")) && link[length-1] == ')' {\n\t\t\tll = t.link_trans.ProcessLink(base_url, string(link[len(\"url(\"):length-1]))\n\t\t\treturn []byte(strings.Join([]string{\"url(\", ll, \")\"}, \"\"))\n\t\t}\n\n\t\tll = t.link_trans.ProcessLink(base_url, string(link))\n\t\treturn []byte(ll)\n\t})\n\treturn res, nil\n}\n\nfunc (t *CSSTransform) Init(trans *Transform) error ", "output": "{\n\tvar err error\n\tt.url_exp, err = regexp.Compile(\"url\\\\(([\\\"][^\\\"]*[\\\"]|['][^']*[']|[^)]*)\\\\)\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.imp_exp, err = regexp.Compile(\"@import \\\"(.*?)\\\"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.link_trans = trans\n\treturn nil\n}"} {"input": "package appfiles\n\nimport (\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com/cloudfoundry/cli/glob\"\n)\n\n\n\ntype CfIgnore interface {\n\tFileShouldBeIgnored(path string) bool\n}\n\n\n\nfunc (ignore cfIgnore) FileShouldBeIgnored(path string) bool {\n\tresult := false\n\n\tfor _, pattern := range ignore {\n\t\tif strings.HasPrefix(pattern.glob.String(), \"/\") && !strings.HasPrefix(path, \"/\") {\n\t\t\tpath = \"/\" + path\n\t\t}\n\n\t\tif pattern.glob.Match(path) {\n\t\t\tresult = pattern.exclude\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunc globsForPattern(pattern string) (globs []glob.Glob) {\n\tglobs = append(globs, glob.MustCompileGlob(pattern))\n\tglobs = append(globs, glob.MustCompileGlob(path.Join(pattern, \"*\")))\n\tglobs = append(globs, glob.MustCompileGlob(path.Join(pattern, \"**\", \"*\")))\n\n\tif !strings.HasPrefix(pattern, \"/\") {\n\t\tglobs = append(globs, glob.MustCompileGlob(path.Join(\"**\", pattern)))\n\t\tglobs = append(globs, glob.MustCompileGlob(path.Join(\"**\", pattern, \"*\")))\n\t\tglobs = append(globs, glob.MustCompileGlob(path.Join(\"**\", pattern, \"**\", \"*\")))\n\t}\n\n\treturn\n}\n\ntype ignorePattern struct {\n\texclude bool\n\tglob glob.Glob\n}\n\ntype cfIgnore []ignorePattern\n\nvar defaultIgnoreLines = []string{\n\t\".cfignore\",\n\t\"/manifest.yml\",\n\t\".gitignore\",\n\t\".git\",\n\t\".hg\",\n\t\".svn\",\n\t\"_darcs\",\n\t\".DS_Store\",\n}\n\nfunc NewCfIgnore(text string) CfIgnore ", "output": "{\n\tpatterns := []ignorePattern{}\n\tlines := strings.Split(text, \"\\n\")\n\tlines = append(defaultIgnoreLines, lines...)\n\n\tfor _, line := range lines {\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tignore := true\n\t\tif strings.HasPrefix(line, \"!\") {\n\t\t\tline = line[1:]\n\t\t\tignore = false\n\t\t}\n\n\t\tfor _, p := range globsForPattern(path.Clean(line)) {\n\t\t\tpatterns = append(patterns, ignorePattern{ignore, p})\n\t\t}\n\t}\n\n\treturn cfIgnore(patterns)\n}"} {"input": "package secret\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/mailgun/vulcand/Godeps/_workspace/src/gopkg.in/check.v1\"\n)\n\nfunc TestSecret(t *testing.T) { TestingT(t) }\n\ntype SecretSuite struct {\n}\n\nvar _ = Suite(&SecretSuite{})\n\nfunc (s *SecretSuite) TestEncryptDecryptCylce(c *C) {\n\tkeyS, err := NewKeyString()\n\tc.Assert(err, IsNil)\n\n\tkey, err := KeyFromString(keyS)\n\tc.Assert(err, IsNil)\n\n\tb, err := NewBox(key)\n\tc.Assert(err, IsNil)\n\n\tmessage := []byte(\"hello, box!\")\n\tsealed, err := b.Seal(message)\n\tc.Assert(err, IsNil)\n\n\tout, err := b.Open(sealed)\n\tc.Assert(err, IsNil)\n\tc.Assert(out, DeepEquals, message)\n}\n\n\n\nfunc (s *SecretSuite) TestEncryptDecryptJSON(c *C) ", "output": "{\n\tkeyS, err := NewKeyString()\n\tc.Assert(err, IsNil)\n\n\tkey, err := KeyFromString(keyS)\n\tc.Assert(err, IsNil)\n\n\tb, err := NewBox(key)\n\tc.Assert(err, IsNil)\n\n\tmessage := []byte(\"hello, box!\")\n\tsealed, err := b.Seal(message)\n\tc.Assert(err, IsNil)\n\n\tdata, err := SealedValueToJSON(sealed)\n\tc.Assert(err, IsNil)\n\tc.Assert(data, NotNil)\n\n\tbytes, err := SealedValueFromJSON(data)\n\tc.Assert(err, IsNil)\n\tc.Assert(bytes, NotNil)\n\n\tout, err := b.Open(sealed)\n\tc.Assert(err, IsNil)\n\tc.Assert(out, DeepEquals, message)\n}"} {"input": "package session\n\nimport (\n\t\"net\"\n\t\"time\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/pkg/errors\"\n\t\"golang.org/x/net/context\"\n\t\"golang.org/x/net/http2\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\nfunc serve(ctx context.Context, grpcServer *grpc.Server, conn net.Conn) {\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tconn.Close()\n\t}()\n\tlogrus.Debugf(\"serving grpc connection\")\n\t(&http2.Server{}).ServeConn(conn, &http2.ServeConnOpts{Handler: grpcServer})\n}\n\nfunc grpcClientConn(ctx context.Context, conn net.Conn) (context.Context, *grpc.ClientConn, error) {\n\tdialOpt := grpc.WithDialer(func(addr string, d time.Duration) (net.Conn, error) {\n\t\treturn conn, nil\n\t})\n\n\tcc, err := grpc.DialContext(ctx, \"\", dialOpt, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to create grpc client\")\n\t}\n\n\tctx, cancel := context.WithCancel(ctx)\n\tgo monitorHealth(ctx, cc, cancel)\n\n\treturn ctx, cc, nil\n}\n\n\n\nfunc monitorHealth(ctx context.Context, cc *grpc.ClientConn, cancelConn func()) ", "output": "{\n\tdefer cancelConn()\n\tdefer cc.Close()\n\n\tticker := time.NewTicker(500 * time.Millisecond)\n\tdefer ticker.Stop()\n\thealthClient := grpc_health_v1.NewHealthClient(cc)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\t<-ticker.C\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\t\t\t_, err := healthClient.Check(ctx, &grpc_health_v1.HealthCheckRequest{})\n\t\t\tcancel()\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package ray\n\nimport (\n\t\"github.com/v2ray/v2ray-core/common/alloc\"\n)\n\nconst (\n\tbufferSize = 128\n)\n\n\nfunc NewRay() Ray {\n\treturn &directRay{\n\t\tInput: make(chan *alloc.Buffer, bufferSize),\n\t\tOutput: make(chan *alloc.Buffer, bufferSize),\n\t}\n}\n\ntype directRay struct {\n\tInput chan *alloc.Buffer\n\tOutput chan *alloc.Buffer\n}\n\nfunc (this *directRay) OutboundInput() <-chan *alloc.Buffer {\n\treturn this.Input\n}\n\nfunc (this *directRay) OutboundOutput() chan<- *alloc.Buffer {\n\treturn this.Output\n}\n\nfunc (this *directRay) InboundInput() chan<- *alloc.Buffer {\n\treturn this.Input\n}\n\n\n\nfunc (this *directRay) InboundOutput() <-chan *alloc.Buffer ", "output": "{\n\treturn this.Output\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/fatih/color\"\n\t\"github.com/fsnotify/fsnotify\"\n)\n\n\ntype BuildRestarter interface {\n\tName() string\n\tBuild() error\n\tRestart()\n}\n\n\ntype FileWatcher struct {\n\tRestarters []BuildRestarter\n}\n\n\nfunc (w *FileWatcher) Add(r ...BuildRestarter) {\n\tw.Restarters = append(w.Restarters, r...)\n}\n\n\nfunc (w *FileWatcher) Watch() {\n\tfiles, err := w.findGoFiles()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tdefer watcher.Close()\n\n\tfor _, file := range files {\n\t\tif err := watcher.Add(filepath.Join(\".\", file)); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase event := <-watcher.Events:\n\t\t\tif event.Op != fsnotify.Chmod && event.Name != \"\" {\n\t\t\t\tfor _, restarter := range w.Restarters {\n\t\t\t\t\tcolor.HiYellow(\"rebuilding %s\\n\", restarter.Name())\n\t\t\t\t\tif err := restarter.Build(); err == nil { \n\t\t\t\t\t\tcolor.HiYellow(\"restarting %s\", restarter.Name())\n\t\t\t\t\t\trestarter.Restart()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\twatcher.Remove(event.Name)\n\t\t\t\twatcher.Add(event.Name)\n\t\t\t}\n\t\tcase err := <-watcher.Errors:\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n}\n\n\n\nfunc (w *FileWatcher) findGoFiles() ([]string, error) ", "output": "{\n\tvar files []string\n\terr := filepath.Walk(\".\", func(path string, info os.FileInfo, err error) error {\n\t\tif strings.HasPrefix(path, \"cmd/sourcepods-dev\") { \n\t\t\treturn nil\n\t\t}\n\t\tif strings.HasPrefix(path, \"vendor\") {\n\t\t\treturn nil\n\t\t}\n\t\tif strings.HasSuffix(path, \".go\") {\n\t\t\tfiles = append(files, path)\n\t\t}\n\t\treturn nil\n\t})\n\treturn files, err\n}"} {"input": "package model\n\ntype Interface interface {\n\tVisitString(name string, resume func())\n\tVisitInt(name string, resume func())\n\tVisitFloat(name string, resume func())\n\tVisitBool(name string, resume func())\n\tVisitPtr(name string, resume func())\n\tVisitBytes(name string, resume func())\n\tVisitSlice(name string, resume func())\n\tVisitStruct(name string, fields []Field, resume func())\n\tVisitStructField(field Field, resume func())\n\tVisitMap(name string, resume func())\n\tVisitCustom(name string, resume func())\n\tVisitReference(name string, resume func())\n}\n\ntype Visitor struct{}\n\nfunc (self *Visitor) VisitString(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitInt(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitFloat(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBool(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitPtr(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBytes(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitSlice(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStructField(field Field, resume func()) {\n\tresume()\n}\n\n\n\nfunc (self *Visitor) VisitCustom(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitReference(name string, resume func()) {\n\tresume()\n}\n\ntype EmbeddedStructVisitor struct {\n\tInterface\n}\n\nfunc (self *EmbeddedStructVisitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitMap(name string, resume func()) ", "output": "{\n\tresume()\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSECSTaskDefinition_DockerVolumeConfiguration struct {\n\n\tAutoprovision bool `json:\"Autoprovision,omitempty\"`\n\n\tDriver string `json:\"Driver,omitempty\"`\n\n\tDriverOpts map[string]string `json:\"DriverOpts,omitempty\"`\n\n\tLabels map[string]string `json:\"Labels,omitempty\"`\n\n\tScope string `json:\"Scope,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) AWSCloudFormationType() string {\n\treturn \"AWS::ECS::TaskDefinition.DockerVolumeConfiguration\"\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetDeletionPolicy(policy policies.DeletionPolicy) ", "output": "{\n\tr._deletionPolicy = policy\n}"} {"input": "package cborl\n\ntype stateStack struct {\n\tstack []state \n\tstack0 [64]state\n\tcurrent state\n}\n\ntype lengthStack struct {\n\tstack []int64\n\tstack0 [32]int64\n\tcurrent int64\n}\n\nfunc (s *stateStack) init(s0 state) {\n\ts.current = s0\n\ts.stack = s.stack0[:0]\n}\n\nfunc (s *stateStack) push(next state) {\n\tif s.current.major != stFail {\n\t\ts.stack = append(s.stack, s.current)\n\t}\n\ts.current = next\n}\n\n\n\nfunc (s *lengthStack) init() {\n\ts.stack = s.stack0[:0]\n}\n\nfunc (s *lengthStack) push(l int64) {\n\ts.stack = append(s.stack, s.current)\n\ts.current = l\n}\n\nfunc (s *lengthStack) pop() int64 {\n\tif len(s.stack) == 0 {\n\t\ts.current = -1\n\t\treturn -1\n\t} else {\n\t\tlast := len(s.stack) - 1\n\t\told := s.current\n\t\ts.current = s.stack[last]\n\t\ts.stack = s.stack[:last]\n\t\treturn old\n\t}\n}\n\nfunc (s *stateStack) pop() ", "output": "{\n\tif len(s.stack) == 0 {\n\t\ts.current = state{stFail, stStart}\n\t} else {\n\t\tlast := len(s.stack) - 1\n\t\ts.current = s.stack[last]\n\t\ts.stack = s.stack[:last]\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/getlantern/flashlight/client\"\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc TestJSONloading(t *testing.T) ", "output": "{\n\tfallbacks := loadFallbacks(\"test.json\")\n\n\texpectedFb := []client.ChainedServerInfo{\n\t\t{\n\t\t\tAddr: \"78.62.239.134:443\",\n\t\t\tCert: \"-----CERTIFICATE-----\\n\",\n\t\t\tAuthToken: \"a1\",\n\t\t},\n\t\t{\n\t\t\tAddr: \"178.62.239.34:80\",\n\t\t\tCert: \"-----CERTIFICATE-----\\n\",\n\t\t\tAuthToken: \"a2\",\n\t\t},\n\t}\n\n\tif len(expectedFb) != len(fallbacks) {\n\t\tt.Error(\"Expected number of fallbacks mismatch\")\n\t}\n\n\tfor i, f := range fallbacks {\n\t\tif !reflect.DeepEqual(f, expectedFb[i]) {\n\t\t\tt.Fail()\n\t\t}\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"google.golang.org/grpc\"\n\tsdkgrpc \"github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/logging/logging_go_proto\"\n)\n\n\n\n\nfunc RegisterServers(s *grpc.Server) ", "output": "{\n\tsdkgrpc.RegisterLoggingLogBucketServiceServer(s, &LogBucketServer{})\n\tsdkgrpc.RegisterLoggingLogExclusionServiceServer(s, &LogExclusionServer{})\n\tsdkgrpc.RegisterLoggingLogMetricServiceServer(s, &LogMetricServer{})\n\tsdkgrpc.RegisterLoggingLogViewServiceServer(s, &LogViewServer{})\n}"} {"input": "package summarize\n\nimport \"unicode\"\n\ntype TextSplitter interface {\n\tSentences(string) []string\n\tWords(string) []string\n}\n\ntype DefaultTextSplitter struct {\n\tPunctuations []rune\n}\n\nfunc (d DefaultTextSplitter) Sentences(text string) []string {\n\tbuf := getBuffer()\n\tdefer bufferPool.Put(buf)\n\n\tsentences := []string{}\n\tnewSentence := true\n\tlastNonWhiteSpace := -1\n\n\tfor _, r := range text {\n\t\tif oneOfPunct(r, d.Punctuations) {\n\t\t\tif buf.Len() > 0 {\n\t\t\t\tif lastNonWhiteSpace > 0 {\n\t\t\t\t\tbuf.Truncate(lastNonWhiteSpace)\n\t\t\t\t\tbuf.WriteRune(r)\n\t\t\t\t\tsentences = append(sentences, buf.String())\n\t\t\t\t}\n\t\t\t\tbuf.Reset()\n\t\t\t\tnewSentence = true\n\t\t\t}\n\t\t} else {\n\t\t\tisSpace := unicode.IsSpace(r)\n\t\t\tif newSentence && isSpace {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnewSentence = false\n\t\t\tbuf.WriteRune(r)\n\t\t\tif !isSpace {\n\t\t\t\tlastNonWhiteSpace = buf.Len()\n\t\t\t}\n\t\t}\n\t}\n\n\tif buf.Len() > 0 && lastNonWhiteSpace > 0 {\n\t\tbuf.Truncate(lastNonWhiteSpace)\n\t\tsentences = append(sentences, buf.String())\n\t\tbuf.Reset()\n\t}\n\n\treturn sentences\n}\n\n\n\nfunc oneOfPunct(r rune, punct []rune) bool {\n\tfor _, p := range punct {\n\t\tif p == r {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc oneOfStartQuote(r rune, quotes [][]rune) int {\n\tfor i, q := range quotes {\n\t\tif q[0] == r {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (d DefaultTextSplitter) Words(text string) []string ", "output": "{\n\tbuf := getBuffer()\n\tdefer bufferPool.Put(buf)\n\n\twords := []string{}\n\n\tfor _, r := range text {\n\t\tif unicode.IsLetter(r) || unicode.IsNumber(r) {\n\t\t\tbuf.WriteRune(r)\n\t\t} else if !unicode.IsOneOf([]*unicode.RangeTable{unicode.Hyphen}, r) {\n\t\t\tif buf.Len() > 0 {\n\t\t\t\twords = append(words, buf.String())\n\t\t\t}\n\t\t\tbuf.Reset()\n\t\t}\n\t}\n\n\tif buf.Len() > 0 {\n\t\twords = append(words, buf.String())\n\t}\n\n\treturn words\n}"} {"input": "package com\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestIsExist(t *testing.T) {\n\tConvey(\"Check if file or directory exists\", t, func() {\n\t\tConvey(\"Pass a file name that exists\", func() {\n\t\t\tSo(IsExist(\"file.go\"), ShouldEqual, true)\n\t\t})\n\t\tConvey(\"Pass a directory name that exists\", func() {\n\t\t\tSo(IsExist(\"testdata\"), ShouldEqual, true)\n\t\t})\n\t\tConvey(\"Pass a directory name that does not exist\", func() {\n\t\t\tSo(IsExist(\".hg\"), ShouldEqual, false)\n\t\t})\n\t})\n}\n\n\nfunc BenchmarkIsFile(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tIsFile(\"file.go\")\n\t}\n}\n\nfunc BenchmarkIsExist(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tIsExist(\"file.go\")\n\t}\n}\n\nfunc TestIsFile(t *testing.T) ", "output": "{\n\tif !IsFile(\"file.go\") {\n\t\tt.Errorf(\"IsExist:\\n Expect => %v\\n Got => %v\\n\", true, false)\n\t}\n\n\tif IsFile(\"testdata\") {\n\t\tt.Errorf(\"IsExist:\\n Expect => %v\\n Got => %v\\n\", false, true)\n\t}\n\n\tif IsFile(\"files.go\") {\n\t\tt.Errorf(\"IsExist:\\n Expect => %v\\n Got => %v\\n\", false, true)\n\t}\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/crazy-max/ftpgrab/v7/pkg/utl\"\n)\n\n\ntype ServerFTP struct {\n\tHost string `yaml:\"host,omitempty\" json:\"host,omitempty\" validate:\"required\"`\n\tPort int `yaml:\"port,omitempty\" json:\"port,omitempty\" validate:\"required,min=1\"`\n\tUsername string `yaml:\"username,omitempty\" json:\"username,omitempty\"`\n\tUsernameFile string `yaml:\"usernameFile,omitempty\" json:\"usernameFile,omitempty\" validate:\"omitempty,file\"`\n\tPassword string `yaml:\"password,omitempty\" json:\"password,omitempty\"`\n\tPasswordFile string `yaml:\"passwordFile,omitempty\" json:\"passwordFile,omitempty\" validate:\"omitempty,file\"`\n\tSources []string `yaml:\"sources,omitempty\" json:\"sources,omitempty\"`\n\tTimeout *time.Duration `yaml:\"timeout,omitempty\" json:\"timeout,omitempty\"`\n\tDisableUTF8 *bool `yaml:\"disableUTF8,omitempty\" json:\"disableUTF8,omitempty\"`\n\tDisableEPSV *bool `yaml:\"disableEPSV,omitempty\" json:\"disableEPSV,omitempty\"`\n\tDisableMLSD *bool `yaml:\"disableMLSD,omitempty\" json:\"disableMLSD,omitempty\"`\n\tTLS *bool `yaml:\"tls,omitempty\" json:\"tls,omitempty\"`\n\tInsecureSkipVerify *bool `yaml:\"insecureSkipVerify,omitempty\" json:\"insecureSkipVerify,omitempty\"`\n\tLogTrace *bool `yaml:\"logTrace,omitempty\" json:\"logTrace,omitempty\"`\n}\n\n\nfunc (s *ServerFTP) GetDefaults() *ServerFTP {\n\tn := &ServerFTP{}\n\tn.SetDefaults()\n\treturn n\n}\n\n\n\n\nfunc (s *ServerFTP) SetDefaults() ", "output": "{\n\ts.Port = 21\n\ts.Sources = []string{}\n\ts.Timeout = utl.NewDuration(5 * time.Second)\n\ts.DisableUTF8 = utl.NewFalse()\n\ts.DisableEPSV = utl.NewFalse()\n\ts.DisableMLSD = utl.NewFalse()\n\ts.TLS = utl.NewFalse()\n\ts.InsecureSkipVerify = utl.NewFalse()\n\ts.LogTrace = utl.NewFalse()\n}"} {"input": "package frames\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\ntype RstStreamFrame struct {\n\tStreamId uint32\n\tErrorCode ErrorCode\n}\n\nfunc NewRstStreamFrame(streamId uint32, errorCode ErrorCode) *RstStreamFrame {\n\treturn &RstStreamFrame{\n\t\tStreamId: streamId,\n\t\tErrorCode: errorCode,\n\t}\n}\n\nfunc DecodeRstStreamFrame(flags byte, streamId uint32, payload []byte, context *DecodingContext) (Frame, error) {\n\tif len(payload) != 4 {\n\t\treturn nil, fmt.Errorf(\"FRAME_SIZE_ERROR: Received RST_STREAM frame of length %v\", len(payload))\n\t}\n\treturn NewRstStreamFrame(streamId, ErrorCode(binary.BigEndian.Uint32(payload))), nil\n}\n\n\n\nfunc (f *RstStreamFrame) Encode(context *EncodingContext) ([]byte, error) {\n\tresult := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(result, uint32(f.ErrorCode))\n\treturn result, nil\n}\n\nfunc (f *RstStreamFrame) GetStreamId() uint32 {\n\treturn f.StreamId\n}\n\nfunc (f *RstStreamFrame) Type() Type ", "output": "{\n\treturn RST_STREAM_TYPE\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateDbHomeRequest struct {\n\n\tCreateDbHomeWithDbSystemIdDetails CreateDbHomeBase `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request CreateDbHomeRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CreateDbHomeRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CreateDbHomeRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateDbHomeResponse struct {\n\n\tRawResponse *http.Response\n\n\tDbHome `presentIn:\"body\"`\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateDbHomeResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateDbHomeResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateDbHomeRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package http\n\nimport (\n\t\"testing\"\n)\n\nfunc isChar(c rune) bool { return c <= 127 }\n\nfunc isCtl(c rune) bool { return c <= 31 || c == 127 }\n\n\n\nfunc TestIsToken(t *testing.T) {\n\tfor i := 0; i <= 130; i++ {\n\t\tr := rune(i)\n\t\texpected := isChar(r) && !isCtl(r) && !isSeparator(r)\n\t\tif isToken(r) != expected {\n\t\t\tt.Errorf(\"isToken(0x%x) = %v\", r, !expected)\n\t\t}\n\t}\n}\n\nfunc isSeparator(c rune) bool ", "output": "{\n\tswitch c {\n\tcase '(', ')', '<', '>', '@', ',', ';', ':', '\\\\', '\"', '/', '[', ']', '?', '=', '{', '}', ' ', '\\t':\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\n\n\ntype ContainerStateRunningApplyConfiguration struct {\n\tStartedAt *v1.Time `json:\"startedAt,omitempty\"`\n}\n\n\n\n\n\n\n\n\nfunc (b *ContainerStateRunningApplyConfiguration) WithStartedAt(value v1.Time) *ContainerStateRunningApplyConfiguration {\n\tb.StartedAt = &value\n\treturn b\n}\n\nfunc ContainerStateRunning() *ContainerStateRunningApplyConfiguration ", "output": "{\n\treturn &ContainerStateRunningApplyConfiguration{}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\nfunc isPrime(n int) bool {\n\tfor i := 3; i*i <= n; i += 2 {\n\t\tif n%i == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nvar primeSet = func() map[int]bool {\n\tprimeSet := make(map[int]bool)\n\tfor i := 3; i < 1000000; i += 2 {\n\t\tif isPrime(i) {\n\t\t\tprimeSet[i] = true\n\t\t}\n\t}\n\treturn primeSet\n}()\n\n\n\nfunc main() {\n\tin, _ := os.Open(\"543.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"543.out\")\n\tdefer out.Close()\n\n\tvar n int\n\tfor {\n\t\tif fmt.Fscanf(in, \"%d\", &n); n == 0 {\n\t\t\tbreak\n\t\t}\n\t\tsolve(out, n)\n\t}\n}\n\nfunc solve(out io.Writer, n int) ", "output": "{\n\tfor i := 3; i <= n/2; i += 2 {\n\t\tif primeSet[i] && primeSet[n-i] {\n\t\t\tfmt.Fprintf(out, \"%d = %d + %d\\n\", n, i, n-i)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Fprintln(out, \"Goldbach's conjecture is wrong.\")\n}"} {"input": "package outputs\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/lfkeitel/spartan/event\"\n\n\ttomb \"gopkg.in/tomb.v2\"\n)\n\n\n\n\ntype OutputController struct {\n\tstart Output\n\tbatchSize int\n\tt tomb.Tomb\n\tin <-chan *event.Event\n\tout chan<- *event.Event\n}\n\n\n\nfunc NewOutputController(start Output, batchSize int) *OutputController {\n\treturn &OutputController{\n\t\tstart: start,\n\t\tbatchSize: batchSize,\n\t}\n}\n\n\n\n\n\n\n\n\n\nfunc (o *OutputController) Close() error {\n\to.t.Kill(nil)\n\treturn o.t.Wait()\n}\n\nfunc (o *OutputController) run() error {\n\tfmt.Println(\"Output Pipeline started\")\n\tfor {\n\t\tselect {\n\t\tcase <-o.t.Dying():\n\t\t\treturn nil\n\t\tdefault:\n\t\t}\n\n\t\tcurrentBatch := 0\n\t\tbatch := make([]*event.Event, o.batchSize)\n\t\tstopping := false\n\n\tCURRENT:\n\t\tfor currentBatch < o.batchSize {\n\t\t\tselect {\n\t\t\tcase event := <-o.in:\n\t\t\t\tbatch[currentBatch] = event\n\t\t\t\tcurrentBatch++\n\t\t\tcase <-o.t.Dying():\n\t\t\t\tstopping = true\n\t\t\t\tbreak CURRENT\n\t\t\t}\n\t\t}\n\n\t\tfmt.Println(\"Processing batch\")\n\t\to.start.Run(batch)\n\n\t\tif stopping {\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\n\nfunc checkOptionsMap(o map[string]interface{}) map[string]interface{} {\n\tif o == nil {\n\t\to = make(map[string]interface{})\n\t}\n\treturn o\n}\n\nfunc (o *OutputController) Start(in chan *event.Event) error ", "output": "{\n\to.in = in\n\to.t.Go(o.run)\n\treturn nil\n}"} {"input": "package models\n\ntype ServiceOfferingFields struct {\n\tGuid string\n\tBrokerGuid string\n\tLabel string\n\tProvider string\n\tVersion string\n\tDescription string\n\tDocumentationUrl string\n}\n\ntype ServiceOffering struct {\n\tServiceOfferingFields\n\tPlans []ServicePlanFields\n}\n\ntype ServiceOfferings []ServiceOffering\n\n\n\nfunc (s ServiceOfferings) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\nfunc (s ServiceOfferings) Less(i, j int) bool {\n\treturn s[i].Label < s[j].Label\n}\n\nfunc (s ServiceOfferings) Len() int ", "output": "{\n\treturn len(s)\n}"} {"input": "package yaml\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/docker/engine-api/types/strslice\"\n\t\"github.com/flynn/go-shlex\"\n)\n\n\ntype Command strslice.StrSlice\n\n\n\n\nfunc (s *Command) UnmarshalYAML(tag string, value interface{}) error ", "output": "{\n\tswitch value := value.(type) {\n\tcase []interface{}:\n\t\tparts, err := toStrings(value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t*s = parts\n\tcase string:\n\t\tparts, err := shlex.Split(value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t*s = parts\n\tdefault:\n\t\treturn fmt.Errorf(\"Failed to unmarshal Command: %#v\", value)\n\t}\n\treturn nil\n}"} {"input": "package actor\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestExponentialBackoffStrategy_setFailureCount(t *testing.T) ", "output": "{\n\tcases := []struct {\n\t\tn string\n\t\tft time.Duration\n\t\tfc int\n\t\texpected int\n\t}{\n\t\t{n: \"failure outside window; zero count\", ft: 11 * time.Second, fc: 10, expected: 0},\n\t\t{n: \"failure inside window; increment count\", ft: 9 * time.Second, fc: 10, expected: 11},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.n, func(t *testing.T) {\n\t\t\ts := &exponentialBackoffStrategy{backoffWindow: 10 * time.Second}\n\t\t\trs := &RestartStatistics{FailureCount: 10, LastFailureTime: time.Now().Add(-tc.ft)}\n\n\t\t\ts.setFailureCount(rs)\n\t\t\tassert.Equal(t, tc.expected, rs.FailureCount)\n\t\t})\n\t}\n\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/bitly/go-nsq\"\n)\n\n\n\ntype BackendQueue interface {\n\tPut([]byte) error\n\tReadChan() chan []byte \n\tClose() error\n\tDelete() error\n\tDepth() int64\n\tEmpty() error\n}\n\ntype DummyBackendQueue struct {\n\treadChan chan []byte\n}\n\nfunc NewDummyBackendQueue() BackendQueue {\n\treturn &DummyBackendQueue{readChan: make(chan []byte)}\n}\n\n\n\nfunc (d *DummyBackendQueue) ReadChan() chan []byte {\n\treturn d.readChan\n}\n\nfunc (d *DummyBackendQueue) Close() error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Delete() error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Depth() int64 {\n\treturn int64(0)\n}\n\nfunc (d *DummyBackendQueue) Empty() error {\n\treturn nil\n}\n\nfunc WriteMessageToBackend(buf *bytes.Buffer, msg *nsq.Message, bq BackendQueue) error {\n\tbuf.Reset()\n\terr := msg.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = bq.Put(buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Put([]byte) error ", "output": "{\n\treturn nil\n}"} {"input": "package mozlog\n\nimport (\n\t\"bytes\"\n\t\"log\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestMozLogger(t *testing.T) ", "output": "{\n\tin := new(bytes.Buffer)\n\tDefaultLogger.Output = in\n\tUseMozLogger(\"testlogger\")\n\tlog.Println(\"test\")\n\tassert.Contains(t, in.String(), \"mozlog_test\")\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n)\n\nvar separator = []byte{0}\n\n\n\ntype Metric LabelSet\n\n\nfunc (m Metric) Equal(o Metric) bool {\n\treturn LabelSet(m).Equal(LabelSet(o))\n}\n\n\nfunc (m Metric) Before(o Metric) bool {\n\treturn LabelSet(m).Before(LabelSet(o))\n}\n\n\nfunc (m Metric) Clone() Metric {\n\tclone := Metric{}\n\tfor k, v := range m {\n\t\tclone[k] = v\n\t}\n\treturn clone\n}\n\n\n\n\nfunc (m Metric) Fingerprint() Fingerprint {\n\treturn LabelSet(m).Fingerprint()\n}\n\n\n\nfunc (m Metric) FastFingerprint() Fingerprint {\n\treturn LabelSet(m).FastFingerprint()\n}\n\n\ntype COWMetric struct {\n\tCopied bool\n\tMetric Metric\n}\n\n\n\nfunc (m *COWMetric) Set(ln LabelName, lv LabelValue) {\n\tm.doCOW()\n\tm.Metric[ln] = lv\n}\n\n\n\nfunc (m *COWMetric) Del(ln LabelName) {\n\tm.doCOW()\n\tdelete(m.Metric, ln)\n}\n\n\nfunc (m *COWMetric) doCOW() {\n\tif !m.Copied {\n\t\tm.Metric = m.Metric.Clone()\n\t\tm.Copied = true\n\t}\n}\n\n\nfunc (m COWMetric) String() string {\n\treturn m.Metric.String()\n}\n\n\nfunc (m COWMetric) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(m.Metric)\n}\n\nfunc (m Metric) String() string ", "output": "{\n\tmetricName, hasName := m[MetricNameLabel]\n\tnumLabels := len(m) - 1\n\tif !hasName {\n\t\tnumLabels = len(m)\n\t}\n\tlabelStrings := make([]string, 0, numLabels)\n\tfor label, value := range m {\n\t\tif label != MetricNameLabel {\n\t\t\tlabelStrings = append(labelStrings, fmt.Sprintf(\"%s=%q\", label, value))\n\t\t}\n\t}\n\n\tswitch numLabels {\n\tcase 0:\n\t\tif hasName {\n\t\t\treturn string(metricName)\n\t\t}\n\t\treturn \"{}\"\n\tdefault:\n\t\tsort.Strings(labelStrings)\n\t\treturn fmt.Sprintf(\"%s{%s}\", metricName, strings.Join(labelStrings, \", \"))\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc middlewareFirst(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"MiddlewareFirst - Before Handler\")\n\t\tnext.ServeHTTP(w, r)\n\t\tlog.Println(\"MiddlewareFirst- After Handler\")\n\t})\n}\n\n\n\nfunc index(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Executing index handler\")\n\tfmt.Fprintf(w, \"Welcome!\")\n}\n\nfunc message(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Excuting message Handler\")\n\tfmt.Fprintf(w, \"HTTP Middleware is awesome\")\n}\n\nfunc iconHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.ServeFile(w, r, \"./favicon.ico\")\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/favicon.ico\", iconHandler)\n\n\thttp.Handle(\"/\", middlewareFirst(middlewareSecond(http.HandlerFunc(index))))\n\thttp.Handle(\"/message\", middlewareFirst(middlewareSecond(http.HandlerFunc(message))))\n\n\tserver := &http.Server{\n\t\tAddr: \":8080\",\n\t}\n\tlog.Println(\"Listening...\")\n\tserver.ListenAndServe()\n}\n\nfunc middlewareSecond(next http.Handler) http.Handler ", "output": "{\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"MiddlewareSecond - Before Handler\")\n\t\tif r.URL.Path == \"/message\" {\n\t\t\tif r.URL.Query().Get(\"password\") == \"pass123\" {\n\t\t\t\tlog.Println(\"Authorized to the system\")\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t} else {\n\t\t\t\tlog.Println(\"Failed to authorize to the system\")\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t}\n\t\tlog.Println(\"MiddlewareSecond - After Handler\")\n\t})\n}"} {"input": "package issue\n\nimport (\n\t\"github.com/watermint/toolbox/quality/recipe/qtr_endtoend\"\n\t\"testing\"\n)\n\n\n\nfunc TestList_Exec(t *testing.T) ", "output": "{\n\tqtr_endtoend.TestRecipe(t, &List{})\n}"} {"input": "package debos\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestBasicCommand(t *testing.T) ", "output": "{\n\tCommand{}.Run(\"out\", \"ls\", \"-l\")\n}"} {"input": "package window_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/kurin/blazer/x/window\"\n)\n\ntype Accumulator struct {\n\tw *window.Window\n}\n\nfunc (a Accumulator) Add(s string) {\n\ta.w.Insert([]string{s})\n}\n\nfunc (a Accumulator) All() []string {\n\tv := a.w.Reduce()\n\treturn v.([]string)\n}\n\n\n\nfunc Example_accumulator() {\n\ta := NewAccum(time.Minute)\n\ta.Add(\"this\")\n\ta.Add(\"is\")\n\ta.Add(\"that\")\n\tfmt.Printf(\"total: %v\\n\", a.All())\n}\n\nfunc NewAccum(size time.Duration) Accumulator ", "output": "{\n\tr := func(i, j interface{}) interface{} {\n\t\ta, ok := i.([]string)\n\t\tif !ok {\n\t\t\ta = nil\n\t\t}\n\t\tb, ok := j.([]string)\n\t\tif !ok {\n\t\t\tb = nil\n\t\t}\n\t\tfor _, s := range b {\n\t\t\ta = append(a, s)\n\t\t}\n\t\treturn a\n\t}\n\treturn Accumulator{w: window.New(size, time.Second, r)}\n}"} {"input": "package routers\n\nimport (\n\t\"fmt\"\n\t\"gopkg.in/macaron.v1\"\n)\n\n\n\nfunc Home(ctx *macaron.Context) ", "output": "{\n\tfmt.Println(\"Home\")\n\tctx.Data[\"IsHome\"] = true\n\tctx.HTML(200, \"index\", ctx.Data)\n}"} {"input": "package database\n\nimport \"database/sql\"\n\nvar db *sql.DB\n\n\nfunc OpenDB() {\n\topenSQLite()\n}\n\n\nfunc openSQLite() {\n\tvar err error\n\tdb, err = sql.Open(\"sqlite3\", \"adnalerts.db?loc.auto\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\n\n\n\nfunc Exec(s string, args ...interface{}) (sql.Result, error) {\n\tres, err := db.Exec(s, args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}\n\nfunc Query(s string, args ...interface{}) (*sql.Rows, error) ", "output": "{\n\trows, err := db.Query(s, args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rows, nil\n}"} {"input": "package packer\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\n\nvar GitCommit string\n\n\nconst Version = \"0.5.3\"\n\n\n\n\nconst VersionPrerelease = \"dev\"\n\ntype versionCommand byte\n\nfunc (versionCommand) Help() string {\n\treturn `usage: packer version\n\nOutputs the version of Packer that is running. There are no additional\ncommand-line flags for this command.`\n}\n\nfunc (versionCommand) Run(env Environment, args []string) int {\n\tenv.Ui().Machine(\"version\", Version)\n\tenv.Ui().Machine(\"version-prelease\", VersionPrerelease)\n\tenv.Ui().Machine(\"version-commit\", GitCommit)\n\n\tenv.Ui().Say(VersionString())\n\treturn 0\n}\n\n\n\n\n\n\nfunc VersionString() string {\n\tvar versionString bytes.Buffer\n\tfmt.Fprintf(&versionString, \"Packer v%s\", Version)\n\tif VersionPrerelease != \"\" {\n\t\tfmt.Fprintf(&versionString, \".%s\", VersionPrerelease)\n\n\t\tif GitCommit != \"\" {\n\t\t\tfmt.Fprintf(&versionString, \" (%s)\", GitCommit)\n\t\t}\n\t}\n\n\treturn versionString.String()\n}\n\nfunc (versionCommand) Synopsis() string ", "output": "{\n\treturn \"print Packer version\"\n}"} {"input": "package lib\n\nimport (\n\t\"log\"\n\t\"strings\"\n)\n\ntype (\n\tQuestion struct {\n\t\tRelatesTo struct {\n\t\t\tAnswers []string `json:\"answers\"`\n\t\t\tSave bool `json:\"save\"`\n\t\t\tSaveTag string `json:\"saveTag\"`\n\t\t} `json:\"relatesTo\"`\n\t\tContext []string `json:\"context\"`\n\t\tQuestionText string `json:\"question\"`\n\t\tPossibleAnswers []string `json:\"answers\"`\n\t}\n\n\tQuestions []*Question\n)\n\n\n\nfunc (this Questions) next(prevAnswer string) (*Question, bool) {\n\tfor i := range this {\n\t\tfor a := range this[i].RelatesTo.Answers {\n\t\t\tif strings.EqualFold(this[i].RelatesTo.Answers[a], prevAnswer) {\n\t\t\t\treturn this[i], this[i].RelatesTo.Save\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc (this Questions) nextFrom(prevAnswers ...string) (*Question, bool) {\n\tfor i := range prevAnswers {\n\t\tif nxt, sv := this.next(prevAnswers[i]); nxt != nil {\n\t\t\tlog.Println(\"got it from sticker ...\")\n\t\t\treturn nxt, sv\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc (this *Question) makeKeyboard() Keyboard {\n\tkeyboard := Keyboard{}\n\tfor i := range this.PossibleAnswers {\n\t\tkeyboard = append(keyboard, []string{this.PossibleAnswers[i]})\n\t}\n\treturn keyboard\n}\n\nfunc (this Questions) First() *Question ", "output": "{\n\tif len(this) > 0 {\n\t\treturn this[0]\n\t}\n\treturn nil\n}"} {"input": "package room\n\nimport (\n \"log\"\n\n \"github.com/jinzhu/gorm\"\n _ \"github.com/jinzhu/gorm/dialects/sqlite\"\n)\n\nconst tableName string = \"rooms\"\n\ntype Room struct {\n gorm.Model\n Id int64 `sql:\"AUTO_INCREMENT\" gorm:\"primary_key\"`\n Name string `sql:\"size:255;unique;index\"`\n Size int32\n VC bool\n CalendarId string\n}\n\nvar (\n dbHandle *gorm.DB\n dbPath string\n)\n\n\n\nfunc Create(dbHandle *gorm.DB, name string, size int32, vc bool, calendarId string) {\n dbHandle.Create(&Room{Name: name, Size: size, VC: vc, CalendarId: calendarId})\n}\n\nfunc GetAll(dbHandle *gorm.DB) []*Room {\n var rooms []*Room\n rows, err := dbHandle.Table(tableName).Select(nil).Rows()\n check(err)\n rows.Scan(&rooms)\n return rooms\n}\n\nfunc SetDbPath(path string) {\n dbPath = path\n}\n\nfunc check(err error) ", "output": "{\n if err != nil {\n log.Println(\"[Models]: \", err)\n }\n\n}"} {"input": "package gconv_test\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\ntype testStruct struct {\n\tId int\n\tName string\n}\n\nvar ptr = []*testStruct{\n\t{\n\t\tId: 1,\n\t\tName: \"test1\",\n\t},\n\t{\n\t\tId: 2,\n\t\tName: \"test2\",\n\t},\n}\n\nfunc init() {\n\tfor i := 1; i <= 1000; i++ {\n\t\tptr = append(ptr, &testStruct{\n\t\t\tId: 1,\n\t\t\tName: \"test1\",\n\t\t})\n\t}\n}\n\nfunc Benchmark_Reflect_ValueOf(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr)\n\t}\n}\n\nfunc Benchmark_Reflect_ValueOf_Kind(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr).Kind()\n\t}\n}\n\nfunc Benchmark_Reflect_ValueOf_Interface(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr).Interface()\n\t}\n}\n\n\n\nfunc Benchmark_Reflect_ValueOf_Len(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr).Len()\n\t}\n}"} {"input": "package plugin_test\n\nimport (\n\t\"path/filepath\"\n\n\t\"code.cloudfoundry.org/cli/utils/testhelpers/pluginbuilder\"\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestPlugin(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tpluginbuilder.BuildTestBinary(filepath.Join(\"..\", \"fixtures\", \"plugins\"), \"test_1\")\n\tRunSpecs(t, \"Plugin Suite\")\n}"} {"input": "package fileinterface\n\nimport (\n \"testing\"\n \"errors\"\n )\n\nfunc TestCreate(t *testing.T) {\n\tvar f FID\n\tvar err error\n\tif f, err = Create(\"dummyfile\"); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tif err = Close(f); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n}\n\nfunc TestDelete(t *testing.T) {\n\terr := Delete(\"dummyfile\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestOpen(t *testing.T) {\n\tif f, err := Open(\"sample.database\"); err != nil {\n\t\tt.Error(err)\n\t} else if err = Close(f); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestRead(t *testing.T) {\n\tvar block *Block\n\tif f, err := Open(\"sample.database\"); err != nil {\n\t\tt.Error(err)\n\t} else if block, err = Read(f, 5); err != nil {\n\t\tt.Error(err)\n\t} else if err = Close(f); err != nil {\n\t\tt.Error(err)\n\t}\n\tfor i:=0; i 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/coscms/webx\"\n)\n\ntype MainAction struct {\n\t*webx.Action\n\n\tstart time.Time\n\n\thello webx.Mapper `webx:\"/(.*)\"`\n}\n\nfunc (c *MainAction) Hello(world string) bool {\n\tc.Write(\"hello %v\", world)\n\treturn true\n}\n\nfunc (c *MainAction) Before(structName, actionName string) bool {\n\tc.start = time.Now()\n\tfmt.Println(\"before\", c.start)\n\treturn true\n}\n\n\n\nfunc main() {\n\twebx.AddRouter(\"/\", &MainAction{})\n\twebx.Run(\"0.0.0.0:9999\")\n}\n\nfunc (c *MainAction) After(structName, actionName string, actionResult interface{}) bool ", "output": "{\n\tfmt.Println(\"after\", time.Now().Sub(c.start))\n\treturn true\n}"} {"input": "package mock_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/pingcap/check\"\n\t\"github.com/pingcap/tidb/br/pkg/mock\"\n\t\"github.com/pingcap/tidb/util/testleak\"\n)\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\nvar _ = Suite(&testClusterSuite{})\n\ntype testClusterSuite struct {\n\tmock *mock.Cluster\n}\n\n\n\nfunc (s *testClusterSuite) TearDownSuite(c *C) {\n\ttestleak.AfterTest(c)()\n}\n\nfunc (s *testClusterSuite) TestSmoke(c *C) {\n\tc.Assert(s.mock.Start(), IsNil)\n\ts.mock.Stop()\n}\n\nfunc (s *testClusterSuite) SetUpSuite(c *C) ", "output": "{\n\tvar err error\n\ts.mock, err = mock.NewCluster()\n\tc.Assert(err, IsNil)\n}"} {"input": "package cronjob\n\nimport (\n\tcontext \"context\"\n\n\tv1beta1 \"k8s.io/client-go/informers/batch/v1beta1\"\n\tfactory \"knative.dev/pkg/client/injection/kube/informers/factory\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Default.RegisterInformer(withInformer)\n}\n\n\ntype Key struct{}\n\nfunc withInformer(ctx context.Context) (context.Context, controller.Informer) {\n\tf := factory.Get(ctx)\n\tinf := f.Batch().V1beta1().CronJobs()\n\treturn context.WithValue(ctx, Key{}, inf), inf.Informer()\n}\n\n\n\n\nfunc Get(ctx context.Context) v1beta1.CronJobInformer ", "output": "{\n\tuntyped := ctx.Value(Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch k8s.io/client-go/informers/batch/v1beta1.CronJobInformer from context.\")\n\t}\n\treturn untyped.(v1beta1.CronJobInformer)\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar ans int = 0\n\nfunc merge(l, r []int) []int {\n\tn := len(l) + len(r)\n\tresult := make([]int, n)\n\n\tli := 0\n\tri := 0\n\n\tfor k := 0; k < n; k++ {\n\t\tlv := 1000000000\n\t\tif li < len(l) {\n\t\t\tlv = l[li]\n\t\t}\n\t\trv := 1000000000\n\t\tif ri < len(r) {\n\t\t\trv = r[ri]\n\t\t}\n\t\tif lv > rv {\n\t\t\tif li < len(l) {\n\t\t\t\tans = ans + len(l) - li\n\t\t\t}\n\n\t\t\tresult[k] = rv\n\t\t\tri++\n\t\t} else {\n\t\t\tresult[k] = lv\n\t\t\tli++\n\t\t}\n\t}\n\n\treturn result\n}\n\n\n\nfunc solve(n int, xs []int) {\n\t_ = mergeSort(xs)\n}\n\nfunc printArray(xs []int) string {\n\treturn strings.Trim(fmt.Sprint(xs), \"[]\")\n}\n\nfunc nextInt(sc *bufio.Scanner) int {\n\tsc.Scan()\n\ts := sc.Text()\n\tx, err := strconv.Atoi(s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn x\n}\n\nfunc main() {\n\tsc := bufio.NewScanner(os.Stdin)\n\tsc.Split(bufio.ScanWords)\n\n\tn := nextInt(sc)\n\txs := make([]int, n)\n\tfor i := 0; i < n; i++ {\n\t\txs[i] = nextInt(sc)\n\t}\n\tsolve(n, xs)\n\tfmt.Println(ans)\n}\n\nfunc mergeSort(xs []int) []int ", "output": "{\n\tif len(xs) == 0 {\n\t\treturn []int{}\n\t} else if len(xs) == 1 {\n\t\treturn []int{xs[0]}\n\t} else {\n\t\tm := len(xs) / 2\n\t\tl := mergeSort(xs[:m])\n\t\tr := mergeSort(xs[m:])\n\t\treturn merge(l, r)\n\t}\n}"} {"input": "package main\n\nimport \"testing\"\n\n\n\nfunc Test_container_fetch_counter(t *testing.T) {\n\tcontainer := NewCounterContainer(\"marathon\")\n\t_, new := container.Fetch(\"foo\", \"\")\n\n\tif !new {\n\t\tt.Fatal(\"expected a new counter\")\n\t}\n\tif len(container.counters) != 1 {\n\t\tt.Fatalf(\"expected a counter, got %d counters\", len(container.counters))\n\t}\n\n\t_, new = container.Fetch(\"foo\", \"\")\n\tif new {\n\t\tt.Fatal(\"expected an existing counter\")\n\t}\n\tif len(container.counters) != 1 {\n\t\tt.Fatalf(\"expected same counter as before, go %d counters\", len(container.counters))\n\t}\n}\n\nfunc Test_container_fetch_gauge(t *testing.T) {\n\tcontainer := NewGaugeContainer(\"marathon\")\n\t_, new := container.Fetch(\"foo\", \"\")\n\n\tif !new {\n\t\tt.Fatal(\"expected a new gauge\")\n\t}\n\tif len(container.gauges) != 1 {\n\t\tt.Fatalf(\"expected a gauge, got %d gauges\", len(container.gauges))\n\t}\n\n\t_, new = container.Fetch(\"foo\", \"\")\n\tif new {\n\t\tt.Fatal(\"expected an existing gauge\")\n\t}\n\tif len(container.gauges) != 1 {\n\t\tt.Fatalf(\"expected same gauge as before, go %d gauges\", len(container.gauges))\n\t}\n}\n\nfunc Test_container_key(t *testing.T) ", "output": "{\n\tcases := []struct {\n\t\tname string\n\t\tlabels []string\n\t\texpect string\n\t}{\n\t\t{\n\t\t\tname: \"foo\",\n\t\t\tlabels: []string{},\n\t\t\texpect: \"foo{}\",\n\t\t}, {\n\t\t\tname: \"foo\",\n\t\t\tlabels: []string{\"value\"},\n\t\t\texpect: \"foo{value}\",\n\t\t}, {\n\t\t\tname: \"foo\",\n\t\t\tlabels: []string{\"value\", \"color\"},\n\t\t\texpect: \"foo{color,value}\",\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tkey := containerKey(c.name, c.labels)\n\t\tif key != c.expect {\n\t\t\tt.Errorf(\"expected container key %s, got %s\", c.expect, key)\n\t\t}\n\t}\n}"} {"input": "package uintgr\n\n\n\n\nfunc Is64bits() bool ", "output": "{\n\tv := uint(1)\n\treturn v<<32 != 0\n}"} {"input": "package wire\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\n\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max)\n\tif buf != nil {\n\t\tcopy(b, buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) ", "output": "{\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}"} {"input": "package requirements\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cloudfoundry/cli/cf\"\n\t\"github.com/cloudfoundry/cli/cf/configuration/core_config\"\n\t. \"github.com/cloudfoundry/cli/cf/i18n\"\n\t\"github.com/cloudfoundry/cli/cf/models\"\n\t\"github.com/cloudfoundry/cli/cf/terminal\"\n)\n\n\ntype TargetedOrgRequirement interface {\n\tRequirement\n\tGetOrganizationFields() models.OrganizationFields\n}\n\ntype targetedOrgApiRequirement struct {\n\tui terminal.UI\n\tconfig core_config.Reader\n}\n\nfunc NewTargetedOrgRequirement(ui terminal.UI, config core_config.Reader) TargetedOrgRequirement {\n\treturn targetedOrgApiRequirement{ui, config}\n}\n\nfunc (req targetedOrgApiRequirement) Execute() (success bool) {\n\tif !req.config.HasOrganization() {\n\t\tmessage := fmt.Sprintf(T(\"No org targeted, use '{{.Command}}' to target an org.\", map[string]interface{}{\"Command\": terminal.CommandColor(cf.Name() + \" target -o ORG\")}))\n\t\treq.ui.Failed(message)\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\n\nfunc (req targetedOrgApiRequirement) GetOrganizationFields() (org models.OrganizationFields) ", "output": "{\n\treturn req.config.OrganizationFields()\n}"} {"input": "import \"sort\"\n\ntype Schedule struct {\n intervals []Interval\n}\n\nfunc (s *Schedule) Len() int {\n return len(s.intervals)\n}\n\nfunc (s *Schedule) Less(i, j int) bool {\n if s.intervals[i].Start < s.intervals[j].Start {\n return true\n }\n return false\n}\n\nfunc (s *Schedule) Swap(i, j int) {\n s.intervals[i], s.intervals[j] = s.intervals[j], s.intervals[i]\n}\n\nfunc (s *Schedule) Check() bool {\n for i:=0; i s.intervals[i+1].Start {\n return false\n }\n }\n return true\n}\n\n\n\nfunc canAttendMeetings(intervals []Interval) bool ", "output": "{\n if len(intervals) <= 1 {\n return true\n }\n s := Schedule{intervals}\n sort.Sort(&s)\n return s.Check()\n}"} {"input": "package main\n\nimport (\n\t\"crypto/rand\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n)\n\n\n\nfunc saveSecretTo(fname string, s *[]byte) error {\n\terr := ioutil.WriteFile(fname, *s, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.Chmod(fname, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc readSecretFrom(fname string) (*[]byte, error) {\n\tbytes, err := ioutil.ReadFile(fname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &bytes, nil\n}\n\nfunc newSecret(size int) *[]byte ", "output": "{\n\tbytes := make([]byte, size)\n\n\t_, err := io.ReadFull(rand.Reader, bytes)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn &bytes\n}"} {"input": "package log\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n)\n\nvar (\n\tinternalLog *logMux\n\tdebugMode bool\n)\n\n\nfunc init() {\n\tinternalLog = NewMux()\n\tinternalLog.Add(NewSyslogSink())\n\tinternalLog.Add(NewColourisedTerminalSink())\n}\n\n\ntype Sink interface {\n\tInfo(message string)\n\tWarning(message string)\n\tError(message string)\n\tDebug(message string)\n}\n\n\n\nfunc Info(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Info(fileMessage, v...)\n}\n\n\n\nfunc Errorf(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Error(fileMessage, v...)\n}\n\nfunc Debug(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Debug(fileMessage, v...)\n}\n\n\nfunc DebugMode(status bool) {\n\tinternalLog.DebugMode(status)\n\tdebugMode = status\n}\n\nfunc Warning(message string, v ...interface{}) ", "output": "{\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Warning(fileMessage, v...)\n}"} {"input": "package apihelper\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\n\t\"github.com/mediocregopher/mediocre-api/common\"\n\t\"github.com/mediocregopher/mediocre-api/pickyjson\"\n)\n\n\n\n\nfunc ErrUnlessMethod(\n\tw http.ResponseWriter, r *http.Request, methods ...string,\n) bool {\n\tfor i := range methods {\n\t\tif r.Method == methods[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\thttp.Error(w, \"invalid method\", 400)\n\treturn false\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Prepare(\n\tw http.ResponseWriter, r *http.Request, params interface{},\n\tbodySizeLimit int64,\n) bool {\n\tr.Body = http.MaxBytesReader(w, r.Body, bodySizeLimit)\n\tif params != nil {\n\t\tif err := json.NewDecoder(r.Body).Decode(params); err != nil {\n\t\t\thttp.Error(w, err.Error(), 400)\n\t\t\treturn false\n\t\t}\n\t\tif err := pickyjson.CheckRequired(params); err != nil {\n\t\t\tcommon.HTTPError(w, r, err)\n\t\t\treturn false\n\t\t}\n\t\tif err := pickyjson.CheckRequired(¶ms); err != nil {\n\t\t\tcommon.HTTPError(w, r, err)\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n\n\n\n\nfunc JSONSuccess(w io.Writer, i interface{}) ", "output": "{\n\tjson.NewEncoder(w).Encode(i)\n\tfmt.Fprintf(w, \"\\n\")\n}"} {"input": "package request\n\nimport (\n \"bytes\"\n \"encoding/json\"\n \"io/ioutil\"\n)\n\n\ntype Handlers struct {\n RequestHandler func(*Request, *interface{}) error\n ResponseHandler func(*Request, *interface{}) error\n}\n\n\n\n\n\nfunc ResponseHandler(request *Request, output *interface{}) error {\n return json.Unmarshal(request.Body, &output)\n}\n\n\n\nfunc ListResponseHandler(request *Request, output *interface{}) error {\n var objmap map[string]*json.RawMessage\n err := json.Unmarshal(request.Body, &objmap)\n if err != nil {\n return err\n }\n return json.Unmarshal(*objmap[\"results\"], &output)\n}\n\nfunc RequestHandler(request *Request, input *interface{}) error ", "output": "{\n jsonstr, err := json.Marshal(&input)\n request.HTTPRequest.Body = ioutil.NopCloser(bytes.NewBuffer(jsonstr))\n return err\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\n\t\"github.com/minio/mc/pkg/console\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc (s *TestSuite) TestShareFailure(c *C) {\n\tobjectURL := server.URL + \"/bucket/object1\"\n\n\terr := app.Run([]string{os.Args[0], \"share\", \"download\", objectURL, \"1hr\"})\n\tc.Assert(err, IsNil)\n\tc.Assert(console.IsExited, Equals, true)\n\n\tconsole.IsExited = false\n\n\terr = app.Run([]string{os.Args[0], \"share\", \"download\", objectURL, \"169hr\"})\n\tc.Assert(err, IsNil)\n\tc.Assert(console.IsExited, Equals, true)\n\n\tconsole.IsExited = false\n\n\terr = app.Run([]string{os.Args[0], \"share\", \"download\", objectURL, \"0s\"})\n\tc.Assert(err, IsNil)\n\tc.Assert(console.IsExited, Equals, true)\n\n\tconsole.IsExited = false\n}\n\n\n\nfunc (s *TestSuite) TestShareSuccess(c *C) ", "output": "{\n\tobjectURL := server.URL + \"/bucket/object1\"\n\n\terr := app.Run([]string{os.Args[0], \"share\", \"download\", objectURL})\n\tc.Assert(err, IsNil)\n\tc.Assert(console.IsExited, Equals, false)\n\n\tconsole.IsExited = false\n\n\terr = app.Run([]string{os.Args[0], \"share\", \"download\", objectURL, \"1h\"})\n\tc.Assert(err, IsNil)\n\tc.Assert(console.IsExited, Equals, false)\n\n\tconsole.IsExited = false\n}"} {"input": "package jpsplus\n\nimport (\n\t\"container/heap\"\n)\n\ntype PriorityQueue struct {\n\tpos int\n\tnode map[int]*Node\n}\n\n\n\nfunc (p *PriorityQueue) Len() int {\n\treturn len(p.node)\n}\n\nfunc (p *PriorityQueue) Less(i, j int) bool {\n\treturn p.node[i].finalCost < p.node[j].finalCost\n}\n\nfunc (p *PriorityQueue) Swap(i, j int) {\n\tp.node[i], p.node[j] = p.node[j], p.node[i]\n\tp.node[i].heapIndex = i\n\tp.node[j].heapIndex = j\n}\n\nfunc (p *PriorityQueue) Push(x interface{}) {\n\titem, ok := x.(*Node)\n\tif ok {\n\t\titem.heapIndex = p.pos\n\t\tp.node[p.pos] = item\n\t\tp.pos++\n\t}\n}\n\nfunc (p *PriorityQueue) Pop() interface{} {\n\tp.pos--\n\titem := p.node[p.pos]\n\tdelete(p.node, p.pos)\n\treturn item\n}\n\nfunc (p *PriorityQueue) PushNode(n *Node) {\n\theap.Push(p, n)\n}\n\nfunc (p *PriorityQueue) PopNode() *Node {\n\treturn heap.Pop(p).(*Node)\n}\n\nfunc (p *PriorityQueue) RemoveNode(n *Node) {\n\theap.Remove(p, n.heapIndex)\n}\n\nfunc newPriorityQueue() *PriorityQueue ", "output": "{\n\tp := new(PriorityQueue)\n\tp.node = make(map[int]*Node)\n\treturn p\n}"} {"input": "package utils\n\nimport (\n\t\"os\"\n\t\"os/user\"\n\t\"path/filepath\"\n)\n\n\nfunc HomeDir() string {\n\thomeDir := os.Getenv(\"HOME\")\n\tif homeDir != \"\" {\n\t\treturn homeDir\n\t}\n\n\tcurrentUser, err := user.Current()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn currentUser.HomeDir\n}\n\n\n\n\nfunc ConfigDir() string ", "output": "{\n\tconfigDir := os.Getenv(\"XDG_CONFIG_HOME\")\n\tif configDir != \"\" {\n\t\treturn configDir\n\t}\n\n\treturn filepath.Join(HomeDir(), \".config\")\n}"} {"input": "package cloudguard\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype UpdateManagedListRequest struct {\n\n\tManagedListId *string `mandatory:\"true\" contributesTo:\"path\" name:\"managedListId\"`\n\n\tUpdateManagedListDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request UpdateManagedListRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request UpdateManagedListRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request UpdateManagedListRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateManagedListResponse struct {\n\n\tRawResponse *http.Response\n\n\tManagedList `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateManagedListResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateManagedListResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateManagedListRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package db\n\nimport (\n\t\"errors\"\n\n\tapiDB \"spaciblo.org/api/db\"\n\t\"spaciblo.org/be\"\n)\n\n\n\n\nfunc InitDB() (*be.DBInfo, error) ", "output": "{\n\tdbInfo, err := be.InitDB()\n\tif err != nil {\n\t\treturn nil, errors.New(\"DB Initialization Error: \" + err.Error())\n\t}\n\terr = apiDB.MigrateDB(dbInfo)\n\tif err != nil {\n\t\treturn nil, errors.New(\"API DB Migration Error: \" + err.Error())\n\t}\n\treturn dbInfo, nil\n}"} {"input": "package goquery\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\ntype document struct {\n\turl url.URL\n\theaders http.Header\n\tbody []byte\n\twrapper\n}\n\nfunc (d document) GetURL() url.URL { return d.url }\n\nfunc (d document) GetBody() []byte { return d.body }\n\nfunc (d document) GetHeaders() http.Header ", "output": "{ return d.headers }"} {"input": "package record\n\nimport (\n\t\"testing\"\n\n\tch \"github.com/BatchLabs/charlatan\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestNewCSVRecordWithoutHeader(t *testing.T) {\n\tc := NewCSVRecord([]string{\"a\", \"b\", \"c\"})\n\trequire.NotNil(t, c)\n\tassert.Nil(t, c.header)\n}\n\nfunc TestFindNameWithoutHeader(t *testing.T) {\n\tc := NewCSVRecord([]string{\"a\", \"b\", \"c\"})\n\trequire.NotNil(t, c)\n\n\t_, err := c.Find(ch.NewField(\"foo\"))\n\tassert.NotNil(t, err)\n}\n\n\n\nfunc TestFindColumnName(t *testing.T) {\n\tc := NewCSVRecordWithHeader([]string{\"a\", \"b\", \"c\"}, []string{\"id\", \"x\", \"y\"})\n\trequire.NotNil(t, c)\n\n\t_, err := c.Find(ch.NewField(\"yo\"))\n\tassert.NotNil(t, err)\n\n\t_, err = c.Find(ch.NewField(\"xy\"))\n\tassert.NotNil(t, err)\n\n\tv, err := c.Find(ch.NewField(\"y\"))\n\tassert.Nil(t, err)\n\tassert.Equal(t, \"c\", v.AsString())\n}\n\nfunc TestFindStar(t *testing.T) {\n\tc := NewCSVRecord([]string{\"x\", \"y\", \"z\"})\n\trequire.NotNil(t, c)\n\n\tv, err := c.Find(ch.NewField(\"*\"))\n\tassert.Nil(t, err)\n\tassert.True(t, v.IsString())\n\tassert.Equal(t, \"[x y z]\", v.AsString())\n}\n\nfunc TestFindColumnIndex(t *testing.T) ", "output": "{\n\tc := NewCSVRecord([]string{\"a\", \"b\", \"c\"})\n\trequire.NotNil(t, c)\n\n\t_, err := c.Find(ch.NewField(\"$-1\"))\n\tassert.NotNil(t, err)\n\n\t_, err = c.Find(ch.NewField(\"$42\"))\n\tassert.NotNil(t, err)\n\n\tv, err := c.Find(ch.NewField(\"$1\"))\n\tassert.Nil(t, err)\n\tassert.True(t, v.IsString())\n\tassert.Equal(t, \"b\", v.AsString())\n}"} {"input": "package main\nimport os \"os\"\ntype _ os.FileInfo\n\n\nfunc f() (os int) ", "output": "{\n\t \n\t \n\t v := os.Open(\"\", 0, 0);\t\n\t return 0\n}"} {"input": "package layer\n\nimport \"io\"\n\ntype mountedLayer struct {\n\tname string\n\tmountID string\n\tinitID string\n\tparent *roLayer\n\tpath string\n\tlayerStore *layerStore\n\tactivityCount int\n}\n\n\n\nfunc (ml *mountedLayer) TarStream() (io.ReadCloser, error) {\n\tarchiver, err := ml.layerStore.driver.Diff(ml.mountID, ml.cacheParent())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn archiver, nil\n}\n\nfunc (ml *mountedLayer) Path() (string, error) {\n\tif ml.path == \"\" {\n\t\treturn \"\", ErrNotMounted\n\t}\n\treturn ml.path, nil\n}\n\nfunc (ml *mountedLayer) Parent() Layer {\n\tif ml.parent != nil {\n\t\treturn ml.parent\n\t}\n\n\treturn nil\n}\n\nfunc (ml *mountedLayer) Size() (int64, error) {\n\treturn ml.layerStore.driver.DiffSize(ml.mountID, ml.cacheParent())\n}\n\nfunc (ml *mountedLayer) cacheParent() string ", "output": "{\n\tif ml.initID != \"\" {\n\t\treturn ml.initID\n\t}\n\tif ml.parent != nil {\n\t\treturn ml.parent.cacheID\n\t}\n\treturn \"\"\n}"} {"input": "package version\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype Command struct {\n\tName string\n\tW io.Writer\n\tWErr io.Writer\n\tAppName string\n\tAppVersion string\n\tGitCommit string\n}\n\n\nfunc (c *Command) Run(args []string) (int, error) {\n\tfmt.Fprintln(c.W, c.AppName, c.AppVersion, c.GitCommit)\n\treturn 0, nil\n}\n\n\n\n\n\n\nfunc (c *Command) Aliases() map[string]struct{} {\n\treturn map[string]struct{}{\n\t\t\"version\": struct{}{},\n\t}\n}\n\n\nfunc (c *Command) Description() string {\n\treturn \"Print the version.\"\n}\n\nfunc (c *Command) Key() string ", "output": "{\n\treturn c.Name\n}"} {"input": "package tempconv\n\nfunc CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }\n\n\n\nfunc FToC(f Fahrenheit) Celsius ", "output": "{ return Celsius((f - 32) * 5 / 9) }"} {"input": "package serialconsole\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/serialconsole/mgmt/2018-05-01/serialconsole\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype BaseClient = original.BaseClient\ntype ConsoleClient = original.ConsoleClient\ntype DeploymentValidateResult = original.DeploymentValidateResult\ntype GetDisabledResult = original.GetDisabledResult\ntype GetResult = original.GetResult\ntype ListClient = original.ListClient\ntype ListConsoleClient = original.ListConsoleClient\ntype Operations = original.Operations\ntype SetDisabledResult = original.SetDisabledResult\n\nfunc New(subscriptionID string) BaseClient {\n\treturn original.New(subscriptionID)\n}\n\nfunc NewConsoleClientWithBaseURI(baseURI string, subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewListClient(subscriptionID string) ListClient {\n\treturn original.NewListClient(subscriptionID)\n}\nfunc NewListClientWithBaseURI(baseURI string, subscriptionID string) ListClient {\n\treturn original.NewListClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewListConsoleClient(subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClient(subscriptionID)\n}\nfunc NewListConsoleClientWithBaseURI(baseURI string, subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\n\nfunc NewConsoleClient(subscriptionID string) ConsoleClient ", "output": "{\n\treturn original.NewConsoleClient(subscriptionID)\n}"} {"input": "package vault\n\nimport \"time\"\n\ntype dynamicSystemView struct {\n\tcore *Core\n\tmountEntry *MountEntry\n}\n\nfunc (d dynamicSystemView) DefaultLeaseTTL() time.Duration {\n\tdef, _ := d.fetchTTLs()\n\treturn def\n}\n\nfunc (d dynamicSystemView) MaxLeaseTTL() time.Duration {\n\t_, max := d.fetchTTLs()\n\treturn max\n}\n\n\n\n\n\nfunc (d dynamicSystemView) fetchTTLs() (def, max time.Duration) ", "output": "{\n\tdef = d.core.defaultLeaseTTL\n\tmax = d.core.maxLeaseTTL\n\n\tif d.mountEntry.Config.DefaultLeaseTTL != 0 {\n\t\tdef = d.mountEntry.Config.DefaultLeaseTTL\n\t}\n\tif d.mountEntry.Config.MaxLeaseTTL != 0 {\n\t\tmax = d.mountEntry.Config.MaxLeaseTTL\n\t}\n\n\treturn\n}"} {"input": "package ui\n\nfunc About() string {\n\treturn \"go-ui 0.1.1 \"\n}\n\nfunc Version() string {\n\treturn \"go-ui 0.1.1\"\n}\n\nfunc Main(fn func()) int {\n\tfnAppMain = fn\n\treturn theApp.AppMain()\n}\n\nfunc Run() int {\n\treturn theApp.Run()\n}\n\nfunc Exit(code int) {\n\ttheApp.Exit(code)\n}\n\nfunc CloseAllWindows() {\n\ttheApp.CloseAllWindows()\n}\n\n\n\nfunc App() *app ", "output": "{\n\treturn &theApp\n}"} {"input": "package btcwallet\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/lightningnetwork/lnd/lnwallet\"\n)\n\nconst (\n\twalletType = \"btcwallet\"\n)\n\n\n\n\n\nfunc createNewWallet(args ...interface{}) (lnwallet.WalletController, error) {\n\tif len(args) != 1 {\n\t\treturn nil, fmt.Errorf(\"incorrect number of arguments to .New(...), \"+\n\t\t\t\"expected 1, instead passed %v\", len(args))\n\t}\n\n\tconfig, ok := args[0].(*Config)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"first argument to btcdnotifier.New is \" +\n\t\t\t\"incorrect, expected a *rpcclient.ConnConfig\")\n\t}\n\n\treturn New(*config)\n}\n\n\n\n\n\nfunc init() ", "output": "{\n\tdriver := &lnwallet.WalletDriver{\n\t\tWalletType: walletType,\n\t\tNew: createNewWallet,\n\t}\n\n\tif err := lnwallet.RegisterWallet(driver); err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to register wallet driver '%s': %v\",\n\t\t\twalletType, err))\n\t}\n}"} {"input": "package discovery\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\n\tclientcmdapi \"k8s.io/client-go/tools/clientcmd/api\"\n\tkubeadmapi \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm\"\n\t\"k8s.io/kubernetes/cmd/kubeadm/app/discovery/file\"\n\t\"k8s.io/kubernetes/cmd/kubeadm/app/discovery/https\"\n\t\"k8s.io/kubernetes/cmd/kubeadm/app/discovery/token\"\n\tkubeconfigutil \"k8s.io/kubernetes/cmd/kubeadm/app/util/kubeconfig\"\n)\n\n\nconst TokenUser = \"tls-bootstrap-token-user\"\n\n\n\nfunc For(cfg *kubeadmapi.JoinConfiguration) (*clientcmdapi.Config, error) {\n\tconfig, err := DiscoverValidatedKubeConfig(cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't validate the identity of the API Server: %v\", err)\n\t}\n\n\tif len(cfg.Discovery.TLSBootstrapToken) == 0 {\n\t\treturn config, nil\n\t}\n\tclusterinfo := kubeconfigutil.GetClusterFromKubeConfig(config)\n\treturn kubeconfigutil.CreateWithToken(\n\t\tclusterinfo.Server,\n\t\tcfg.ClusterName,\n\t\tTokenUser,\n\t\tclusterinfo.CertificateAuthorityData,\n\t\tcfg.Discovery.TLSBootstrapToken,\n\t), nil\n}\n\n\n\n\n\nfunc isHTTPSURL(s string) bool {\n\tu, err := url.Parse(s)\n\treturn err == nil && u.Scheme == \"https\"\n}\n\nfunc DiscoverValidatedKubeConfig(cfg *kubeadmapi.JoinConfiguration) (*clientcmdapi.Config, error) ", "output": "{\n\tswitch {\n\tcase cfg.Discovery.File != nil:\n\t\tkubeConfigPath := cfg.Discovery.File.KubeConfigPath\n\t\tif isHTTPSURL(kubeConfigPath) {\n\t\t\treturn https.RetrieveValidatedConfigInfo(kubeConfigPath, cfg.ClusterName)\n\t\t}\n\t\treturn file.RetrieveValidatedConfigInfo(kubeConfigPath, cfg.ClusterName)\n\tcase cfg.Discovery.BootstrapToken != nil:\n\t\treturn token.RetrieveValidatedConfigInfo(cfg)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"couldn't find a valid discovery configuration\")\n\t}\n}"} {"input": "package cmd\n\nimport \"errors\"\n\ntype RemoveFile struct {\n\tMeta4\n\tArgs RemoveFileArgs `positional-args:\"true\" required:\"true\"`\n}\n\ntype RemoveFileArgs struct {\n\tName string `positional-arg-name:\"NAME\" description:\"File name\"`\n}\n\n\n\nfunc (c *RemoveFile) Execute(_ []string) error ", "output": "{\n\tmeta4, err := c.Meta4.Get()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor fileIdx, file := range meta4.Files {\n\t\tif file.Name != c.Args.Name {\n\t\t\tcontinue\n\t\t}\n\n\t\tmeta4.Files = append(meta4.Files[:fileIdx], meta4.Files[fileIdx+1:]...)\n\n\t\treturn c.Meta4.Put(meta4)\n\t}\n\n\treturn errors.New(\"File does not exist\")\n}"} {"input": "package jsoniter\n\nimport (\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\"\n)\n\n\n\nfunc Test_decode_struct_with_optional_field(t *testing.T) {\n\tshould := require.New(t)\n\ttype TestObject struct {\n\t\tField1 *string\n\t\tField2 *string\n\t}\n\tobj := TestObject{}\n\tUnmarshalFromString(`{\"field1\": null, \"field2\": \"world\"}`, &obj)\n\tshould.Nil(obj.Field1)\n\tshould.Equal(\"world\", *obj.Field2)\n}\n\nfunc Test_encode_struct_with_optional_field(t *testing.T) {\n\tshould := require.New(t)\n\ttype TestObject struct {\n\t\tField1 *string\n\t\tField2 *string\n\t}\n\tobj := TestObject{}\n\tworld := \"world\"\n\tobj.Field2 = &world\n\tstr, err := MarshalToString(obj)\n\tshould.Nil(err)\n\tshould.Contains(str, `\"Field1\":null`)\n\tshould.Contains(str, `\"Field2\":\"world\"`)\n}\n\nfunc Test_encode_optional_int_pointer(t *testing.T) ", "output": "{\n\tshould := require.New(t)\n\tvar ptr *int\n\tstr, err := MarshalToString(ptr)\n\tshould.Nil(err)\n\tshould.Equal(\"null\", str)\n\tval := 100\n\tptr = &val\n\tstr, err = MarshalToString(ptr)\n\tshould.Nil(err)\n\tshould.Equal(\"100\", str)\n}"} {"input": "package servicelabel\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/namsral/flag\"\n\n\t\"go.ligato.io/cn-infra/v2/infra\"\n\t\"go.ligato.io/cn-infra/v2/logging/logrus\"\n)\n\nvar microserviceLabelFlag string\n\n\n\n\ntype Plugin struct {\n\tinfra.PluginName\n\tMicroserviceLabel string\n}\n\n\nfunc (p *Plugin) Init() error {\n\tif p.MicroserviceLabel == \"\" {\n\t\tp.MicroserviceLabel = microserviceLabelFlag\n\t}\n\tlogrus.DefaultLogger().Debugf(\"Microservice label is set to %v\", p.MicroserviceLabel)\n\treturn nil\n}\n\n\nfunc (p *Plugin) Close() error {\n\treturn nil\n}\n\n\n\nfunc (p *Plugin) GetAgentLabel() string {\n\treturn p.MicroserviceLabel\n}\n\n\n\nfunc (p *Plugin) GetAgentPrefix() string {\n\treturn agentPrefix + p.MicroserviceLabel + \"/\"\n}\n\n\n\nfunc (p *Plugin) GetDifferentAgentPrefix(microserviceLabel string) string {\n\treturn GetDifferentAgentPrefix(microserviceLabel)\n}\n\n\n\nfunc (p *Plugin) GetAllAgentsPrefix() string {\n\treturn GetAllAgentsPrefix()\n}\n\nfunc init() ", "output": "{\n\tflag.StringVar(µserviceLabelFlag, \"microservice-label\", \"vpp1\", fmt.Sprintf(\"microservice label; also set via '%v' env variable.\", MicroserviceLabelEnvVar))\n}"} {"input": "package models\n\ntype ServiceOfferingFields struct {\n\tGuid string\n\tBrokerGuid string\n\tLabel string\n\tProvider string\n\tVersion string\n\tDescription string\n\tDocumentationUrl string\n}\n\ntype ServiceOffering struct {\n\tServiceOfferingFields\n\tPlans []ServicePlanFields\n}\n\ntype ServiceOfferings []ServiceOffering\n\nfunc (s ServiceOfferings) Len() int {\n\treturn len(s)\n}\n\n\n\nfunc (s ServiceOfferings) Less(i, j int) bool {\n\treturn s[i].Label < s[j].Label\n}\n\nfunc (s ServiceOfferings) Swap(i, j int) ", "output": "{\n\ts[i], s[j] = s[j], s[i]\n}"} {"input": "package backoff\n\nimport (\n\t\"math\"\n\t\"time\"\n\n\t\"github.com/quan-xie/tuba/util/xtime\"\n)\n\n\ntype Backoff interface {\n\tNext(retry int) time.Duration\n}\n\ntype constantBackoff struct {\n\tbackoffInterval xtime.Duration\n}\n\n\nfunc NewConstantBackoff(backoffInterval xtime.Duration) Backoff {\n\treturn &constantBackoff{backoffInterval: backoffInterval}\n}\n\n\n\n\ntype exponentialBackoff struct {\n\texponentFactor float64\n\tinitialTimeout float64\n\tmaxTimeout float64\n}\n\n\nfunc NewExponentialBackoff(initialTimeout, maxTimeout time.Duration, exponentFactor float64) Backoff {\n\treturn &exponentialBackoff{\n\t\texponentFactor: exponentFactor,\n\t\tinitialTimeout: float64(initialTimeout / time.Millisecond),\n\t\tmaxTimeout: float64(maxTimeout / time.Millisecond),\n\t}\n}\n\n\nfunc (eb *exponentialBackoff) Next(retry int) time.Duration {\n\tif retry <= 0 {\n\t\treturn 0 * time.Millisecond\n\t}\n\n\treturn time.Duration(math.Min(eb.initialTimeout+math.Pow(eb.exponentFactor, float64(retry)), eb.maxTimeout)) * time.Millisecond\n}\n\nfunc (cb *constantBackoff) Next(retry int) time.Duration ", "output": "{\n\tif retry <= 0 {\n\t\treturn 0 * time.Millisecond\n\t}\n\n\treturn time.Duration(cb.backoffInterval) * 1 << uint(retry)\n}"} {"input": "package lzma\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"unicode\"\n)\n\n\n\ntype operation interface {\n\tLen() int\n}\n\n\ntype match struct {\n\tdistance int64\n\tn int\n}\n\n\n\nfunc (m match) verify() error {\n\tif !(minDistance <= m.distance && m.distance <= maxDistance) {\n\t\treturn errors.New(\"distance out of range\")\n\t}\n\tif !(1 <= m.n && m.n <= maxMatchLen) {\n\t\treturn errors.New(\"length out of range\")\n\t}\n\treturn nil\n}\n\n\n\nfunc (m match) l() uint32 {\n\treturn uint32(m.n - minMatchLen)\n}\n\n\n\nfunc (m match) dist() uint32 {\n\treturn uint32(m.distance - minDistance)\n}\n\n\nfunc (m match) Len() int {\n\treturn m.n\n}\n\n\nfunc (m match) String() string {\n\treturn fmt.Sprintf(\"M{%d,%d}\", m.distance, m.n)\n}\n\n\ntype lit struct {\n\tb byte\n}\n\n\n\n\n\nfunc (l lit) String() string {\n\tvar c byte\n\tif unicode.IsPrint(rune(l.b)) {\n\t\tc = l.b\n\t} else {\n\t\tc = '.'\n\t}\n\treturn fmt.Sprintf(\"L{%c/%02x}\", c, l.b)\n}\n\nfunc (l lit) Len() int ", "output": "{\n\treturn 1\n}"} {"input": "package cli\n\ntype Decoder interface {\n\tDecode(s string) error\n}\n\ntype SliceDecoder interface {\n\tDecoder\n\tDecodeSlice()\n}\n\ntype Encoder interface {\n\tEncode() string\n}\n\ntype CounterDecoder interface {\n\tDecoder\n\tIsCounter()\n}\n\ntype Counter struct {\n\tvalue int\n}\n\nfunc (c Counter) Value() int { return c.value }\n\n\n\nfunc (c Counter) IsCounter() {}\n\nfunc (c *Counter) Decode(s string) error ", "output": "{\n\tc.value++\n\treturn nil\n}"} {"input": "package openweathermap\n\nimport \"testing\"\n\n \n\nfunc TestDailyFmtFormatCity(t *testing.T) {\n\tname, country, days, key := \"Name\", \"US\", 3, \"4\"\n\n\tvar test dailyFmt = \"%s %s %d %s\"\n\n\texpected := \"Name US 3 4\"\n\n\tif actual := test.FormatCity(name, country, days, key); expected != actual {\n\t\tt.Errorf(\"Expected formatted string to be \\\"%s\\\" but was \\\"%s\\\"\",\n\t\t\texpected, actual)\n\t} \n}\n\nfunc TestDailyFmtFormatLoc(t *testing.T) ", "output": "{\n\tlat, lon, days, key := 1.0, 2.0, 3, \"4\"\n\n\tvar test dailyFmt = \"%f %f %d %s\"\n\n\texpected := \"1.000000 2.000000 3 4\"\n\n\tif actual := test.FormatLoc(lat, lon, days, key); expected != actual {\n\t\tt.Errorf(\"Expected formatted string to be \\\"%s\\\" but was \\\"%s\\\"\",\n\t\t\texpected, actual)\n\t} \n}"} {"input": "package kbfsmd\n\nimport (\n\t\"testing\"\n\n\t\"github.com/keybase/client/go/kbfs/kbfscodec\"\n)\n\n\n\n\n\nfunc testStructUnknownFields(t *testing.T, sFuture kbfscodec.FutureStruct) ", "output": "{\n\tcFuture := kbfscodec.NewMsgpack()\n\tcCurrent := kbfscodec.NewMsgpack()\n\tcCurrentKnownOnly := kbfscodec.NewMsgpackNoUnknownFields()\n\tkbfscodec.TestStructUnknownFields(\n\t\tt, cFuture, cCurrent, cCurrentKnownOnly, sFuture)\n}"} {"input": "package checkers\n\nimport (\n\t\"errors\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/jkomoros/boardgame\"\n\t\"github.com/jkomoros/boardgame/base\"\n\t\"github.com/jkomoros/boardgame/moves\"\n)\n\n\n\n\ntype gameDelegate struct {\n\tbase.GameDelegate\n}\n\nvar memoizedDelegateName string\n\nfunc (g *gameDelegate) Name() string {\n\n\n\tif memoizedDelegateName == \"\" {\n\t\tpkgPath := reflect.ValueOf(g).Elem().Type().PkgPath()\n\t\tpathPieces := strings.Split(pkgPath, \"/\")\n\t\tmemoizedDelegateName = pathPieces[len(pathPieces)-1]\n\t}\n\treturn memoizedDelegateName\n}\n\nfunc (g *gameDelegate) ConfigureMoves() []boardgame.MoveConfig {\n\n\tauto := moves.NewAutoConfigurer(g)\n\n\treturn moves.Combine(\n\n\t\tmoves.Add(\n\t\t\tauto.MustConfig(new(moves.NoOp),\n\t\t\t\tmoves.WithMoveName(\"Example No Op Move\"),\n\t\t\t\tmoves.WithHelpText(\"This move is an example that is always legal and does nothing. It exists to show how to return moves and make sure 'go test' works from the beginning, but you should remove it.\"),\n\t\t\t),\n\t\t),\n\t)\n\n}\n\nfunc (g *gameDelegate) GameStateConstructor() boardgame.ConfigurableSubState {\n\treturn new(gameState)\n}\n\nfunc (g *gameDelegate) PlayerStateConstructor(index boardgame.PlayerIndex) boardgame.ConfigurableSubState {\n\treturn new(playerState)\n}\n\n\n\n\n\nfunc NewDelegate() boardgame.GameDelegate {\n\treturn &gameDelegate{}\n}\n\nfunc (g *gameDelegate) DistributeComponentToStarterStack(state boardgame.ImmutableState, c boardgame.Component) (boardgame.ImmutableStack, error) ", "output": "{\n\n\treturn nil, errors.New(\"Not yet implemented\")\n\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestCheckPhoneNumber(t *testing.T) ", "output": "{\n\tnumbers := []string{\n\t\t\"07700900390\",\n\t\t\"+447700900497\",\n\t\t\"202-555-0188\",\n\t\t\"+1-202-555-0188\",\n\t}\n\n\tfor _, number := range numbers {\n\t\tcheck := checkNumber(number)\n\t\tif check != true {\n\t\t\tt.Errorf(\"CheckNumber(\\\"%s\\\") == %t, want %t\", number, check, true)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/gorilla/schema\"\n\t\"github.com/jordic/k8s/cloudsqlip/Godeps/_workspace/src/github.com/emicklei/go-restful\"\n\t\"io\"\n\t\"net/http\"\n)\n\n\n\n\n\n\n\ntype Profile struct {\n\tName string\n\tAge int\n}\n\nvar decoder *schema.Decoder\n\nfunc main() {\n\tdecoder = schema.NewDecoder()\n\tws := new(restful.WebService)\n\tws.Route(ws.POST(\"/profiles\").Consumes(\"application/x-www-form-urlencoded\").To(postAdddress))\n\tws.Route(ws.GET(\"/profiles\").To(addresssForm))\n\trestful.Add(ws)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc postAdddress(req *restful.Request, resp *restful.Response) {\n\terr := req.Request.ParseForm()\n\tif err != nil {\n\t\tresp.WriteErrorString(http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tp := new(Profile)\n\terr = decoder.Decode(p, req.Request.PostForm)\n\tif err != nil {\n\t\tresp.WriteErrorString(http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tio.WriteString(resp.ResponseWriter, fmt.Sprintf(\"Name=%s, Age=%d\", p.Name, p.Age))\n}\n\n\n\nfunc addresssForm(req *restful.Request, resp *restful.Response) ", "output": "{\n\tio.WriteString(resp.ResponseWriter,\n\t\t`\n\t\t\n\t\t

Enter Profile

\n\t\t
\n\t\t \n\t\t\t\n\t\t\t\n\t\t \n\t\t\t\n\t\t
\n\t\t\n\t\t`)\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"github.com/cross-dev/script-server/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n\t\"strings\"\n)\n\ntype ContainSubstringMatcher struct {\n\tSubstr string\n\tArgs []interface{}\n}\n\nfunc (matcher *ContainSubstringMatcher) Match(actual interface{}) (success bool, err error) {\n\tactualString, ok := toString(actual)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"ContainSubstring matcher requires a string or stringer. Got:\\n%s\", format.Object(actual, 1))\n\t}\n\n\treturn strings.Contains(actualString, matcher.stringToMatch()), nil\n}\n\nfunc (matcher *ContainSubstringMatcher) stringToMatch() string {\n\tstringToMatch := matcher.Substr\n\tif len(matcher.Args) > 0 {\n\t\tstringToMatch = fmt.Sprintf(matcher.Substr, matcher.Args...)\n\t}\n\treturn stringToMatch\n}\n\nfunc (matcher *ContainSubstringMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"to contain substring\", matcher.stringToMatch())\n}\n\n\n\nfunc (matcher *ContainSubstringMatcher) NegatedFailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn format.Message(actual, \"not to contain substring\", matcher.stringToMatch())\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSApplicationAutoScalingScalableTarget_ScheduledAction struct {\n\n\tEndTime string `json:\"EndTime,omitempty\"`\n\n\tScalableTargetAction *AWSApplicationAutoScalingScalableTarget_ScalableTargetAction `json:\"ScalableTargetAction,omitempty\"`\n\n\tSchedule string `json:\"Schedule,omitempty\"`\n\n\tScheduledActionName string `json:\"ScheduledActionName,omitempty\"`\n\n\tStartTime string `json:\"StartTime,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) AWSCloudFormationType() string {\n\treturn \"AWS::ApplicationAutoScaling::ScalableTarget.ScheduledAction\"\n}\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\n\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) SetDependsOn(dependencies []string) ", "output": "{\n\tr._dependsOn = dependencies\n}"} {"input": "package metric\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\ntype (\n\tCollectFnOpts struct {\n\t\tMethod string\n\t\tStart time.Time\n\t\tErr error\n\t\tAdditionalProps map[string]interface{}\n\t}\n\n\tCounterFn func(vec *prometheus.CounterVec, o CollectFnOpts)\n\n\tHistogramFn func(vec *prometheus.HistogramVec, o CollectFnOpts)\n\n\tVecOpts struct {\n\t\tName string\n\t\tHelp string\n\t\tLabelNames []string\n\n\t\tCounterFn CounterFn\n\t\tHistogramFn HistogramFn\n\t}\n)\n\ntype metricOpts struct {\n\tnamespace string\n\tservice string\n\tserviceSuffix string\n\tcounterMetrics map[string]VecOpts\n\thistogramMetrics map[string]VecOpts\n}\n\nfunc (o metricOpts) serviceName() string {\n\tif o.serviceSuffix != \"\" {\n\t\treturn fmt.Sprintf(\"%s_%s\", o.service, o.serviceSuffix)\n\t}\n\treturn o.service\n}\n\n\ntype ClientOptFn func(*metricOpts)\n\n\nfunc WithVec(opts VecOpts) ClientOptFn {\n\treturn func(o *metricOpts) {\n\t\tif opts.CounterFn != nil {\n\t\t\tif o.counterMetrics == nil {\n\t\t\t\to.counterMetrics = make(map[string]VecOpts)\n\t\t\t}\n\t\t\to.counterMetrics[opts.Name] = opts\n\t\t}\n\t}\n}\n\n\n\n\nfunc ApplyMetricOpts(opts ...ClientOptFn) *metricOpts {\n\to := metricOpts{}\n\tfor _, opt := range opts {\n\t\topt(&o)\n\t}\n\treturn &o\n}\n\nfunc (o *metricOpts) ApplySuffix(prefix string) string {\n\tif o.serviceSuffix != \"\" {\n\t\treturn fmt.Sprintf(\"%s_%s\", prefix, o.serviceSuffix)\n\t}\n\treturn prefix\n}\n\nfunc WithSuffix(suffix string) ClientOptFn ", "output": "{\n\treturn func(opts *metricOpts) {\n\t\topts.serviceSuffix = suffix\n\t}\n}"} {"input": "package mpvipc\n\nimport \"net\"\n\n\n\nfunc dial(path string) (net.Conn, error) ", "output": "{\n\treturn net.Dial(\"unix\", path)\n}"} {"input": "package goDB\n\nimport (\n \"encoding/json\"\n \"os\"\n)\n\n\ntype BlockMetadata struct {\n Timestamp int64 `json:\"timestamp\"`\n PcapPacketsReceived int `json:\"pcap_packets_received\"`\n PcapPacketsDropped int `json:\"pcap_packets_dropped\"`\n PcapPacketsIfDropped int `json:\"pcap_packets_if_dropped\"`\n PacketsLogged int `json:\"packets_logged\"`\n\n \n FlowCount uint64 `json:\"flowcount\"`\n Traffic uint64 `json:\"traffic\"`\n}\n\n\n\ntype Metadata struct {\n Blocks []BlockMetadata `json:\"blocks\"`\n}\n\nfunc NewMetadata() *Metadata {\n return &Metadata{}\n}\n\n\n\n\n\n\nfunc TryReadMetadata(path string) *Metadata {\n meta, err := ReadMetadata(path)\n if err != nil {\n return NewMetadata()\n }\n return meta\n}\n\nfunc WriteMetadata(path string, meta *Metadata) error {\n f, err := os.Create(path)\n if err != nil {\n return err\n }\n defer f.Close()\n\n return json.NewEncoder(f).Encode(meta)\n}\n\nfunc ReadMetadata(path string) (*Metadata, error) ", "output": "{\n var result Metadata\n\n f, err := os.Open(path)\n if err != nil {\n return nil, err\n }\n defer f.Close()\n\n if err := json.NewDecoder(f).Decode(&result); err != nil {\n return nil, err\n }\n\n return &result, nil\n}"} {"input": "package rpc\n\nimport (\n\t\"github.com/mitchellh/packer/packer\"\n\t\"log\"\n\t\"net/rpc\"\n)\n\n\n\ntype hook struct {\n\tclient *rpc.Client\n\tmux *muxBroker\n}\n\n\n\ntype HookServer struct {\n\thook packer.Hook\n\tmux *muxBroker\n}\n\ntype HookRunArgs struct {\n\tName string\n\tData interface{}\n\tStreamId uint32\n}\n\n\n\nfunc (h *hook) Cancel() {\n\terr := h.client.Call(\"Hook.Cancel\", new(interface{}), new(interface{}))\n\tif err != nil {\n\t\tlog.Printf(\"Hook.Cancel error: %s\", err)\n\t}\n}\n\nfunc (h *HookServer) Run(args *HookRunArgs, reply *interface{}) error {\n\tclient, err := newClientWithMux(h.mux, args.StreamId)\n\tif err != nil {\n\t\treturn NewBasicError(err)\n\t}\n\tdefer client.Close()\n\n\tif err := h.hook.Run(args.Name, client.Ui(), client.Communicator(), args.Data); err != nil {\n\t\treturn NewBasicError(err)\n\t}\n\n\t*reply = nil\n\treturn nil\n}\n\nfunc (h *HookServer) Cancel(args *interface{}, reply *interface{}) error {\n\th.hook.Cancel()\n\treturn nil\n}\n\nfunc (h *hook) Run(name string, ui packer.Ui, comm packer.Communicator, data interface{}) error ", "output": "{\n\tnextId := h.mux.NextId()\n\tserver := newServerWithMux(h.mux, nextId)\n\tserver.RegisterCommunicator(comm)\n\tserver.RegisterUi(ui)\n\tgo server.Serve()\n\n\targs := HookRunArgs{\n\t\tName: name,\n\t\tData: data,\n\t\tStreamId: nextId,\n\t}\n\n\treturn h.client.Call(\"Hook.Run\", &args, new(interface{}))\n}"} {"input": "package notifications\n\nimport (\n\t\"github.com/weaveworks/flux/history\"\n\t\"github.com/weaveworks/flux/service/instance\"\n)\n\n\n\nfunc Event(cfg instance.Config, e history.Event) error ", "output": "{\n\tif cfg.Settings.Slack.HookURL != \"\" {\n\t\tswitch e.Type {\n\t\tcase history.EventRelease:\n\t\t\tr := e.Metadata.(*history.ReleaseEventMetadata)\n\t\t\treturn slackNotifyRelease(cfg.Settings.Slack, r, r.Error)\n\t\tcase history.EventAutoRelease:\n\t\t\tr := e.Metadata.(*history.AutoReleaseEventMetadata)\n\t\t\treturn slackNotifyAutoRelease(cfg.Settings.Slack, r, r.Error)\n\t\tcase history.EventSync:\n\t\t\treturn slackNotifySync(cfg.Settings.Slack, &e)\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package richtext\n\nimport (\n\t\"fmt\"\n)\n\ntype AnsiFormat8 struct{ ansiFormat }\n\nvar _ Format = &AnsiFormat8{}\n\nvar ansiFormat8 *AnsiFormat8\n\nfunc init() {\n\tansiFormat8 = &AnsiFormat8{}\n\tansiFormat8.init(ansiFormat8)\n}\n\nfunc Ansi8() *AnsiFormat8 { return ansiFormat8 }\n\nfunc rgbTo8(c Color) uint8 {\n\tr, g, b := rgb(c)\n\tr1 := r >> 7\n\tg1 := g >> 7\n\tb1 := b >> 7\n\treturn b1<<2 + g1<<1 + r1\n}\n\n\n\nfunc (a *AnsiFormat8) MakeSprintf(fg, bg Color, flags ...Flag) func(format string, a ...interface{}) string {\n\tenc := []string{}\n\tif fg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 30+rgbTo8(fg)))\n\t}\n\tif bg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 40+rgbTo8(bg)))\n\t}\n\n\treturn ansiSPrinter(enc, flags)\n}\n\nfunc (a *AnsiFormat8) MakePrintf(fg, bg Color, flags ...Flag) func(format string, a ...interface{}) (int, error) ", "output": "{\n\tenc := []string{}\n\tif fg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 30+rgbTo8(fg)))\n\t}\n\tif bg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 40+rgbTo8(bg)))\n\t}\n\n\treturn ansiPrinter(enc, flags)\n}"} {"input": "package splunk\n\nimport (\n \"fmt\"\n \"net/url\"\n)\n\n\n\nfunc (conn SplunkConnection) InstallApp(path string, update bool) (string, error) ", "output": "{\n data := make(url.Values)\n data.Add(\"name\", path)\n\n update_app := \"false\"\n if (update == true) {\n update_app = \"true\"\n }\n\n data.Add(\"update\", update_app)\n response, err := conn.httpPost(fmt.Sprintf(\"%s/services/apps/appinstall/\", conn.BaseURL), &data)\n return response, err\n}"} {"input": "package merkledag\n\nimport (\n\t\"context\"\n\n\tcid \"gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid\"\n\tipld \"gx/ipfs/QmR7TcHkR9nxkUorfi8XMTAMLUK7GiP64TWWBzY3aacc1o/go-ipld-format\"\n)\n\n\ntype ErrorService struct {\n\tErr error\n}\n\nvar _ ipld.DAGService = (*ErrorService)(nil)\n\n\n\n\n\nfunc (cs *ErrorService) AddMany(ctx context.Context, nds []ipld.Node) error {\n\treturn cs.Err\n}\n\n\nfunc (cs *ErrorService) Get(ctx context.Context, c cid.Cid) (ipld.Node, error) {\n\treturn nil, cs.Err\n}\n\n\nfunc (cs *ErrorService) GetMany(ctx context.Context, cids []cid.Cid) <-chan *ipld.NodeOption {\n\tch := make(chan *ipld.NodeOption)\n\tclose(ch)\n\treturn ch\n}\n\n\nfunc (cs *ErrorService) Remove(ctx context.Context, c cid.Cid) error {\n\treturn cs.Err\n}\n\n\nfunc (cs *ErrorService) RemoveMany(ctx context.Context, cids []cid.Cid) error {\n\treturn cs.Err\n}\n\nfunc (cs *ErrorService) Add(ctx context.Context, nd ipld.Node) error ", "output": "{\n\treturn cs.Err\n}"} {"input": "package unit\n\nimport (\n\t\"github.com/juju/cmd\"\n\t\"github.com/juju/names/v4\"\n\t\"github.com/juju/utils/v2/voyeur\"\n\n\t\"github.com/juju/juju/agent\"\n\t\"github.com/juju/juju/cmd/containeragent/utils\"\n\t\"github.com/juju/juju/cmd/jujud/agent/agentconf\"\n\t\"github.com/juju/juju/worker/logsender\"\n)\n\ntype (\n\tManifoldsConfig = manifoldsConfig\n\tContainerUnitAgent = containerUnitAgent\n)\n\ntype ContainerUnitAgentTest interface {\n\tcmd.Command\n\tDataDir() string\n\tSetAgentConf(cfg agentconf.AgentConf)\n\tChangeConfig(change agent.ConfigMutator) error\n\tCurrentConfig() agent.Config\n\tTag() names.UnitTag\n\tCharmModifiedVersion() int\n\tGetContainerNames() []string\n}\n\nfunc NewForTest(\n\tctx *cmd.Context,\n\tbufferedLogger *logsender.BufferedLogWriter,\n\tconfigChangedVal *voyeur.Value,\n\tfileReaderWriter utils.FileReaderWriter,\n\tenvironment utils.Environment,\n) ContainerUnitAgentTest {\n\treturn &containerUnitAgent{\n\t\tctx: ctx,\n\t\tAgentConf: agentconf.NewAgentConf(\"\"),\n\t\tbufferedLogger: bufferedLogger,\n\t\tconfigChangedVal: configChangedVal,\n\t\tfileReaderWriter: fileReaderWriter,\n\t\tenvironment: environment,\n\t}\n}\n\nfunc (c *containerUnitAgent) SetAgentConf(cfg agentconf.AgentConf) {\n\tc.AgentConf = cfg\n}\n\nfunc (c *containerUnitAgent) GetContainerNames() []string {\n\treturn c.containerNames\n}\n\n\n\nfunc (c *containerUnitAgent) DataDir() string ", "output": "{\n\treturn c.AgentConf.DataDir()\n}"} {"input": "package kasper\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestTopicProcessorConfig_producerClientID(t *testing.T) {\n\tc := &Config{\n\t\tTopicProcessorName: \"ford-prefect\",\n\t}\n\tassert.Equal(t, \"kasper-topic-processor-ford-prefect\", c.producerClientID())\n}\n\nfunc TestTopicProcessorConfig_kafkaConsumerGroup(t *testing.T) ", "output": "{\n\tc := &Config{\n\t\tTopicProcessorName: \"hari-seldon\",\n\t}\n\tassert.Equal(t, \"kasper-topic-processor-hari-seldon\", c.kafkaConsumerGroup())\n}"} {"input": "package main\n\nimport (\n\t\"html/template\"\n\t\"net/http\"\n\t\"time\"\n)\n\nvar tpl = `\n\n \n \n Date Example\n \n \n \t

{{.Date | dateFormat \"Jan 2, 2006\"}}

\n \n`\n\nvar funcMap = template.FuncMap{\n\t\"dateFormat\": dateFormat,\n}\n\nfunc dateFormat(layout string, d time.Time) string {\n\treturn d.Format(layout)\n}\n\n\n\nfunc main() {\n\thttp.HandleFunc(\"/\", serveTemplate)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc serveTemplate(res http.ResponseWriter, req *http.Request) ", "output": "{\n\tt := template.New(\"date\")\n\tt.Funcs(funcMap)\n\tt.Parse(tpl)\n\tdata := struct{ Date time.Time }{\n\t\tDate: time.Now(),\n\t}\n\tt.Execute(res, data)\n}"} {"input": "package errors\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/GoogleContainerTools/skaffold/proto/v1\"\n)\n\ntype Error interface {\n\tError() string\n\tStatusCode() proto.StatusCode\n\tSuggestions() []*proto.Suggestion\n\tUnwrap() error\n}\n\ntype ErrDef struct {\n\terr error\n\tae *proto.ActionableErr\n}\n\nvar _ error = (*ErrDef)(nil)\n\nfunc (e *ErrDef) Error() string {\n\tif s := concatSuggestions(e.Suggestions()); s != \"\" {\n\t\treturn fmt.Sprintf(\"%s. %s\", e.ae.Message, concatSuggestions(e.Suggestions()))\n\t}\n\treturn e.ae.Message\n}\n\nfunc (e *ErrDef) Unwrap() error {\n\treturn e.err\n}\n\nfunc (e *ErrDef) StatusCode() proto.StatusCode {\n\treturn e.ae.ErrCode\n}\n\nfunc (e *ErrDef) Suggestions() []*proto.Suggestion {\n\treturn e.ae.Suggestions\n}\n\n\nfunc NewError(err error, ae *proto.ActionableErr) *ErrDef {\n\treturn &ErrDef{\n\t\terr: err,\n\t\tae: ae,\n\t}\n}\n\n\n\n\nfunc IsSkaffoldErr(err error) bool {\n\tif _, ok := err.(Error); ok {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc NewErrorWithStatusCode(ae *proto.ActionableErr) *ErrDef ", "output": "{\n\treturn &ErrDef{\n\t\tae: ae,\n\t}\n}"} {"input": "package format\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/types\"\n)\n\ntype podHandler func(*v1.Pod) string\n\n\n\nfunc Pod(pod *v1.Pod) string {\n\treturn PodDesc(pod.Name, pod.Namespace, pod.UID)\n}\n\n\n\n\n\n\n\nfunc PodWithDeletionTimestamp(pod *v1.Pod) string {\n\tvar deletionTimestamp string\n\tif pod.DeletionTimestamp != nil {\n\t\tdeletionTimestamp = \":DeletionTimestamp=\" + pod.DeletionTimestamp.UTC().Format(time.RFC3339)\n\t}\n\treturn Pod(pod) + deletionTimestamp\n}\n\n\n\nfunc Pods(pods []*v1.Pod) string {\n\treturn aggregatePods(pods, Pod)\n}\n\n\n\nfunc PodsWithDeletiontimestamps(pods []*v1.Pod) string {\n\treturn aggregatePods(pods, PodWithDeletionTimestamp)\n}\n\nfunc aggregatePods(pods []*v1.Pod, handler podHandler) string {\n\tpodStrings := make([]string, 0, len(pods))\n\tfor _, pod := range pods {\n\t\tpodStrings = append(podStrings, handler(pod))\n\t}\n\treturn fmt.Sprintf(strings.Join(podStrings, \", \"))\n}\n\nfunc PodDesc(podName, podNamespace string, podUID types.UID) string ", "output": "{\n\treturn fmt.Sprintf(\"%s_%s(%s)\", podName, podNamespace, podUID)\n}"} {"input": "package gotify\n\nimport (\n\t\"github.com/antonholmquist/jason\"\n)\n\nfunc parseAlbum(o *jason.Object) Album {\n\talbumName, _ := o.GetString(\"name\")\n\talbumUri, _ := o.GetString(\"uri\")\n\n\talbum := Album{albumName, albumUri}\n\n\treturn album\n}\n\nfunc parseArtist(o *jason.Object) Artist {\n\tartistName, _ := o.GetString(\"name\")\n\tartistUri, _ := o.GetString(\"uri\")\n\n\tartist := Artist{artistName, artistUri}\n\n\treturn artist\n}\n\nfunc parseTrack(o *jason.Object) Track {\n\ttrackName, _ := o.GetString(\"name\")\n\ttrackUri, _ := o.GetString(\"uri\")\n\n\tjsonAlbum, err := o.GetObject(\"album\")\n\n\tvar album Album\n\tif err == nil {\n\t\talbum = parseAlbum(jsonAlbum)\n\t}\n\n\tjsonArtists, err := o.GetObjectArray(\"artists\")\n\n\tvar artists []Artist\n\tif err == nil {\n\t\tartists = parseArtists(jsonArtists)\n\t}\n\n\ttrack := Track{trackName, trackUri, album, artists}\n\n\treturn track\n}\n\nfunc parseTracks(o []*jason.Object) []Track {\n\ttracks := []Track{}\n\n\tfor _, jsonTrack := range o {\n\t\ttracks = append(tracks, parseTrack(jsonTrack))\n\t}\n\n\treturn tracks\n}\n\n\n\nfunc parseArtists(o []*jason.Object) []Artist {\n\tartists := []Artist{}\n\n\tfor _, jsonArtist := range o {\n\t\tartists = append(artists, parseArtist(jsonArtist))\n\t}\n\n\treturn artists\n}\n\nfunc parsePlaylist(o *jason.Object) SpotifyPlaylist {\n\treturn SpotifyPlaylist{}\n}\n\nfunc parseAlbums(o []*jason.Object) []Album ", "output": "{\n\talbums := []Album{}\n\n\tfor _, jsonAlbum := range o {\n\t\talbums = append(albums, parseAlbum(jsonAlbum))\n\t}\n\n\treturn albums\n}"} {"input": "package cmd\n\nimport (\n\t\"time\"\n\n\t\"github.com/codegangsta/cli\"\n)\n\n\n\nfunc boolFlag(name, usage string) cli.BoolFlag {\n\treturn cli.BoolFlag{\n\t\tName: name,\n\t\tUsage: usage,\n\t}\n}\n\nfunc intFlag(name string, value int, usage string) cli.IntFlag {\n\treturn cli.IntFlag{\n\t\tName: name,\n\t\tValue: value,\n\t\tUsage: usage,\n\t}\n}\n\nfunc durationFlag(name string, value time.Duration, usage string) cli.DurationFlag {\n\treturn cli.DurationFlag{\n\t\tName: name,\n\t\tValue: value,\n\t\tUsage: usage,\n\t}\n}\n\nfunc stringFlag(name, value, usage string) cli.StringFlag ", "output": "{\n\treturn cli.StringFlag{\n\t\tName: name,\n\t\tValue: value,\n\t\tUsage: usage,\n\t}\n}"} {"input": "package fs\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\n\n\nfunc notEmptyErr(err error) bool ", "output": "{\n\treturn err.(*os.PathError).Err == syscall.ENOTEMPTY\n}"} {"input": "package user\n\nimport (\n\t\"net/http\"\n\n\t\"code.gitea.io/gitea/models\"\n\t\"code.gitea.io/gitea/modules/context\"\n\tapi \"code.gitea.io/gitea/modules/structs\"\n\t\"code.gitea.io/gitea/routers/api/v1/utils\"\n)\n\n\n\n\n\nfunc ListUserRepos(ctx *context.APIContext) {\n\n\tuser := GetUserByParams(ctx)\n\tif ctx.Written() {\n\t\treturn\n\t}\n\tprivate := ctx.IsSigned\n\tlistUserRepos(ctx, user, private)\n}\n\n\nfunc ListMyRepos(ctx *context.APIContext) {\n\n\townRepos, err := models.GetUserRepositories(&models.SearchRepoOptions{\n\t\tActor: ctx.User,\n\t\tPrivate: true,\n\t\tListOptions: utils.GetListOptions(ctx),\n\t})\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetUserRepositories\", err)\n\t\treturn\n\t}\n\taccessibleReposMap, err := ctx.User.GetRepositoryAccesses()\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetRepositoryAccesses\", err)\n\t\treturn\n\t}\n\n\tapiRepos := make([]*api.Repository, len(ownRepos)+len(accessibleReposMap))\n\tfor i := range ownRepos {\n\t\tapiRepos[i] = ownRepos[i].APIFormat(models.AccessModeOwner)\n\t}\n\ti := len(ownRepos)\n\tfor repo, access := range accessibleReposMap {\n\t\tapiRepos[i] = repo.APIFormat(access)\n\t\ti++\n\t}\n\tctx.JSON(http.StatusOK, &apiRepos)\n}\n\n\nfunc ListOrgRepos(ctx *context.APIContext) {\n\n\tlistUserRepos(ctx, ctx.Org.Organization, ctx.IsSigned)\n}\n\nfunc listUserRepos(ctx *context.APIContext, u *models.User, private bool) ", "output": "{\n\trepos, err := models.GetUserRepositories(&models.SearchRepoOptions{\n\t\tActor: u,\n\t\tPrivate: private,\n\t\tListOptions: utils.GetListOptions(ctx),\n\t})\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetUserRepositories\", err)\n\t\treturn\n\t}\n\n\tapiRepos := make([]*api.Repository, 0, len(repos))\n\tfor i := range repos {\n\t\taccess, err := models.AccessLevel(ctx.User, repos[i])\n\t\tif err != nil {\n\t\t\tctx.Error(http.StatusInternalServerError, \"AccessLevel\", err)\n\t\t\treturn\n\t\t}\n\t\tif ctx.IsSigned && ctx.User.IsAdmin || access >= models.AccessModeRead {\n\t\t\tapiRepos = append(apiRepos, repos[i].APIFormat(access))\n\t\t}\n\t}\n\tctx.JSON(http.StatusOK, &apiRepos)\n}"} {"input": "package modules\n\nimport (\n\t\"github.com/NiZiL/i3line/core\"\n\t\"time\"\n)\n\ntype DateModule struct {\n\tFormat string\n}\n\n\n\nfunc (m DateModule) OnClick(e i3line.Event) bool {\n\treturn false\n}\n\nfunc (m DateModule) GenBlock() i3line.Block ", "output": "{\n\treturn i3line.NewDefaultBlock(time.Now().Format(m.Format))\n}"} {"input": "package api\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/google/gapid/core/data/id\"\n\t\"github.com/google/gapid/core/image\"\n\t\"github.com/google/gapid/gapil/constset\"\n)\n\n\ntype API interface {\n\tName() string\n\n\tIndex() uint8\n\n\tID() ID\n\n\tConstantSets() *constset.Pack\n\n\tGetFramebufferAttachmentInfo(\n\t\tctx context.Context,\n\t\tafter []uint64,\n\t\tstate *GlobalState,\n\t\tthread uint64,\n\t\tattachment FramebufferAttachment) (width, height, index uint32, format *image.Format, err error)\n\n\tContext(state *GlobalState, thread uint64) Context\n\n\tCreateCmd(name string) Cmd\n}\n\n\ntype ID id.ID\n\n\nfunc (i ID) IsValid() bool { return id.ID(i).IsValid() }\nfunc (i ID) String() string { return id.ID(i).String() }\n\n\ntype APIObject interface {\n\tAPI() API\n}\n\nvar apis = map[ID]API{}\nvar indices = map[uint8]bool{}\n\n\n\n\n\n\n\nfunc Find(id ID) API {\n\treturn apis[id]\n}\n\nfunc Register(api API) ", "output": "{\n\tid := api.ID()\n\tif _, present := apis[id]; present {\n\t\tpanic(fmt.Errorf(\"API %s registered more than once\", id))\n\t}\n\tapis[id] = api\n\n\tindex := api.Index()\n\tif _, present := indices[index]; present {\n\t\tpanic(fmt.Errorf(\"API %s used an occupied index %d\", id, index))\n\t}\n\tindices[index] = true\n}"} {"input": "package chain\n\nimport \"sort\"\n\n\n\nfunc FindLongestChain(pairs [][]int) int ", "output": "{\n\tl := len(pairs)\n\tif l == 0 {\n\t\treturn 0\n\t}\n\tsort.Slice(pairs, func(i, j int) bool {\n\t\treturn pairs[i][0] < pairs[j][0]\n\t})\n\n\tdp := make([]int, l)\n\tfor i := 0; i < l; i++ {\n\t\tdp[i] = 1\n\t}\n\n\tfor i := 1; i < l; i++ {\n\t\tfor j := 0; j < i; j++ {\n\t\t\tif pairs[i][0] > pairs[j][1] && dp[i] < dp[j]+1 {\n\t\t\t\tdp[i] = dp[j] + 1\n\t\t\t}\n\t\t}\n\t}\n\tret := 0\n\tfor i := 0; i < l; i++ {\n\t\tif ret < dp[i] {\n\t\t\tret = dp[i]\n\t\t}\n\t}\n\treturn ret\n\n}"} {"input": "package mailgun\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/config\"\n\t\"github.com/hashicorp/terraform/helper/schema\"\n\t\"github.com/hashicorp/terraform/terraform\"\n\t\"github.com/pearkes/mailgun\"\n)\n\nvar testAccProviders map[string]terraform.ResourceProvider\nvar testAccProvider *schema.Provider\n\n\n\nfunc TestProvider(t *testing.T) {\n\tif err := Provider().(*schema.Provider).InternalValidate(); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n}\n\nfunc TestProvider_impl(t *testing.T) {\n\tvar _ terraform.ResourceProvider = Provider()\n}\n\nfunc TestProviderConfigure(t *testing.T) {\n\tvar expectedKey string\n\n\tif v := os.Getenv(\"MAILGUN_API_KEY\"); v != \"\" {\n\t\texpectedKey = v\n\t} else {\n\t\texpectedKey = \"foo\"\n\t}\n\n\traw := map[string]interface{}{\n\t\t\"api_key\": expectedKey,\n\t}\n\n\trawConfig, err := config.NewRawConfig(raw)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\trp := Provider().(*schema.Provider)\n\terr = rp.Configure(terraform.NewResourceConfig(rawConfig))\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tconfig := rp.Meta().(*mailgun.Client)\n\tif config.ApiKey != expectedKey {\n\t\tt.Fatalf(\"bad: %#v\", config)\n\t}\n}\n\nfunc testAccPreCheck(t *testing.T) {\n\tif v := os.Getenv(\"MAILGUN_API_KEY\"); v == \"\" {\n\t\tt.Fatal(\"MAILGUN_API_KEY must be set for acceptance tests\")\n\t}\n}\n\nfunc init() ", "output": "{\n\ttestAccProvider = Provider().(*schema.Provider)\n\ttestAccProviders = map[string]terraform.ResourceProvider{\n\t\t\"mailgun\": testAccProvider,\n\t}\n}"} {"input": "package aes\n\nimport (\n\t\"crypto/cipher\"\n)\n\ntype code int\n\n\nconst (\n\taes128 code = 18\n\taes192 = 19\n\taes256 = 20\n)\n\ntype aesCipherAsm struct {\n\tfunction code \n\tkey []byte \n\tstorage [256]byte \n}\n\n\n\n\nfunc hasAsm() bool\n\n\n\n\n\nfunc cryptBlocks(c code, key, dst, src *byte, length int)\n\nvar useAsm = hasAsm()\n\nfunc newCipher(key []byte) (cipher.Block, error) {\n\tif !useAsm {\n\t\treturn newCipherGeneric(key)\n\t}\n\n\tvar function code\n\tswitch len(key) {\n\tcase 128 / 8:\n\t\tfunction = aes128\n\tcase 192 / 8:\n\t\tfunction = aes192\n\tcase 256 / 8:\n\t\tfunction = aes256\n\tdefault:\n\t\treturn nil, KeySizeError(len(key))\n\t}\n\n\tvar c aesCipherAsm\n\tc.function = function\n\tc.key = c.storage[:len(key)]\n\tcopy(c.key, key)\n\treturn &c, nil\n}\n\nfunc (c *aesCipherAsm) BlockSize() int { return BlockSize }\n\n\n\nfunc (c *aesCipherAsm) Decrypt(dst, src []byte) {\n\tif len(src) < BlockSize {\n\t\tpanic(\"crypto/aes: input not full block\")\n\t}\n\tif len(dst) < BlockSize {\n\t\tpanic(\"crypto/aes: output not full block\")\n\t}\n\tcryptBlocks(c.function+128, &c.key[0], &dst[0], &src[0], BlockSize)\n}\n\n\n\nfunc expandKey(key []byte, enc, dec []uint32) {\n\texpandKeyGo(key, enc, dec)\n}\n\nfunc (c *aesCipherAsm) Encrypt(dst, src []byte) ", "output": "{\n\tif len(src) < BlockSize {\n\t\tpanic(\"crypto/aes: input not full block\")\n\t}\n\tif len(dst) < BlockSize {\n\t\tpanic(\"crypto/aes: output not full block\")\n\t}\n\tcryptBlocks(c.function, &c.key[0], &dst[0], &src[0], BlockSize)\n}"} {"input": "package format\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\n\ntype Unsigned32 uint32\n\nfunc DecodeUnsigned32(b []byte) (Format, error) {\n\treturn Unsigned32(binary.BigEndian.Uint32(b)), nil\n}\n\nfunc (n Unsigned32) Serialize() []byte {\n\tb := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(b, uint32(n))\n\treturn b\n}\n\n\n\nfunc (n Unsigned32) Padding() int {\n\treturn 0\n}\n\nfunc (n Unsigned32) Format() FormatId {\n\treturn Unsigned32Format\n}\n\nfunc (n Unsigned32) String() string {\n\treturn fmt.Sprintf(\"Unsigned32{%d}\", n)\n}\n\nfunc (n Unsigned32) Len() int ", "output": "{\n\treturn 4\n}"} {"input": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"go/format\"\n \"log\"\n \"os\"\n \"strings\"\n)\n\ntype Kind int\n\nconst (\n \n Flat Kind = iota\n \n \n Lutc\n \n \n \n Lutr\n)\n\ntype Generator struct {\n buf bytes.Buffer\n}\n\nfunc (g *Generator) Printf(format string, args ...interface{}) {\n fmt.Fprintf(&g.buf, format, args...)\n}\n\nfunc (g *Generator) Generate(pkgName string, kind Kind) {\n g.Printf(\"// automatically generated by avrmakedec %s\\n\", strings.Join(os.Args[1:], \" \"))\n g.Printf(\"// DO NOT EDIT\\n\")\n g.Printf(\"package %s\\n\", pkgName)\n g.Printf(\"import \\\"github.com/kierdavis/avr\\\"\\n\")\n switch kind {\n case Flat:\n g.GenerateFlat()\n case Lutc:\n g.GenerateLutc()\n case Lutr:\n g.GenerateLutr()\n default:\n panic(\"Generator.Generate: bad Kind\")\n }\n}\n\n\n\nfunc (g *Generator) Format() []byte ", "output": "{\n src, err := format.Source(g.buf.Bytes())\n if err != nil {\n log.Printf(\"warning: invalid Go generated: %s\\n\", err)\n log.Printf(\"warning: compile the package to analyse the error\\n\")\n return g.buf.Bytes()\n }\n return src\n}"} {"input": "package public\n\nimport (\n . \"logger\"\n \"os\"\n \"os/signal\"\n \"sync\"\n)\n\nvar gLock=sync.Mutex{}\nfunc OnSignaled(sig os.Signal) bool {\n gLock.Lock()\n \n Secretary.Log(\"mainpkg::Terminated\", \"Receive signal \"+sig.String())\n\n return false\n}\n\n\n\nfunc WaitForSig(exit chan bool) ", "output": "{\n defer (func(){\n exit<-false\n })()\n\n c:=make(chan os.Signal, 1)\n signal.Notify(c, os.Interrupt, os.Kill)\n\n for sig:=range c {\n if !OnSignaled(sig) {\n return\n }\n }\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc min(vals ...int) (result int, ok bool) {\n\tif len(vals) == 0 {\n\t\treturn\n\t}\n\tok = true\n\n\tresult = vals[0]\n\tfor _, val := range vals[1:] {\n\t\tif result > val {\n\t\t\tresult = val\n\t\t}\n\t}\n\treturn\n}\n\n\n\nfunc main() {\n\tfmt.Println(min(5, 6, 2, 4, 1, 0))\n\tfmt.Println(min(5, 6, 2, 4, 1, 0))\n}\n\nfunc max(vals ...int) (result int, ok bool) ", "output": "{\n\tif len(vals) == 0 {\n\t\treturn\n\t}\n\tok = true\n\n\tresult = vals[0]\n\tfor _, val := range vals[1:] {\n\t\tif result < val {\n\t\t\tresult = val\n\t\t}\n\t}\n\treturn\n}"} {"input": "package linebot\n\nimport (\n\t\"context\"\n\n\t\"github.com/line/line-bot-sdk-go/linebot\"\n\t\"github.com/utahta/momoclo-channel/config\"\n\t\"google.golang.org/appengine/urlfetch\"\n)\n\ntype (\n\tClient interface {\n\t\tReplyText(context.Context, string, string) error\n\t\tReplyImage(context.Context, string, string, string) error\n\t}\n\n\tclient struct {\n\t}\n)\n\n\nfunc New() Client {\n\treturn &client{}\n}\n\n\n\n\n\nfunc (c *client) ReplyImage(ctx context.Context, replyToken, originalContentURL, previewImageURL string) error {\n\tbot, err := c.fromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\timageMessage := linebot.NewImageMessage(originalContentURL, previewImageURL)\n\tif _, err := bot.ReplyMessage(replyToken, imageMessage).Do(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *client) fromContext(ctx context.Context) (*linebot.Client, error) {\n\treturn linebot.New(\n\t\tconfig.C().LineBot.ChannelSecret,\n\t\tconfig.C().LineBot.ChannelToken,\n\t\tlinebot.WithHTTPClient(urlfetch.Client(ctx)),\n\t)\n}\n\nfunc (c *client) ReplyText(ctx context.Context, replyToken, text string) error ", "output": "{\n\tbot, err := c.fromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttextMessage := linebot.NewTextMessage(text)\n\tif _, err := bot.ReplyMessage(replyToken, textMessage).Do(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package speak\n\nimport (\n\t\"errors\"\n\t\"os/exec\"\n)\n\nvar Voices = []string{\"Agnes\", \"Kathy\", \"Princess\",\n\t\"Vicki\", \"Victoria\", \"Bruce\",\n\t\"Fred\", \"Junior\", \"Ralph\",\n\t\"Albert\", \"Bahh\", \"Bells\",\n\t\"Boing\", \"Bubbles\", \"Cellos\",\n\t\"Deranged\", \"Hysterical\", \"Trinoids\",\n\t\"Whisper\", \"Zarvox\"}\n\n\nfunc Speak(str, voice string) error {\n\tif str == \"\" {\n\t\treturn errors.New(\"Problem executing: No message provided.\")\n\t}\n\tcmd := exec.Command(\"say\", \"-v\", GetVoice(voice), str)\n\treturn cmd.Run()\n}\n\n\n\nfunc GetVoice(req string) string ", "output": "{\n\tfor _, v := range Voices {\n\t\tif req == v {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn \"Alex\"\n}"} {"input": "package portmapper\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/golang/glog\"\n)\n\ntype PortMap struct {\n\tcontainerIP string\n\tcontainerPort int\n}\n\nfunc newPortMap(containerip string, containerport int) *PortMap {\n\treturn &PortMap{\n\t\tcontainerIP: containerip,\n\t\tcontainerPort: containerport,\n\t}\n}\n\ntype PortSet map[int]*PortMap\n\ntype PortMapper struct {\n\ttcpMap PortSet\n\tudpMap PortSet\n\tmutex sync.Mutex\n}\n\nfunc New() *PortMapper {\n\treturn &PortMapper{PortSet{}, PortSet{}, sync.Mutex{}}\n}\n\nfunc (p *PortMapper) AllocateMap(protocol string, hostPort int,\n\tcontainerIP string, ContainerPort int) error {\n\tp.mutex.Lock()\n\tdefer p.mutex.Unlock()\n\n\tvar pset PortSet\n\n\tif strings.EqualFold(protocol, \"udp\") {\n\t\tpset = p.udpMap\n\t} else {\n\t\tpset = p.tcpMap\n\t}\n\n\te, ok := pset[hostPort]\n\tif ok {\n\t\treturn fmt.Errorf(\"Host port %d had already been used, %s %d\",\n\t\t\thostPort, e.containerIP, e.containerPort)\n\t}\n\n\tallocated := newPortMap(containerIP, ContainerPort)\n\tpset[hostPort] = allocated\n\n\treturn nil\n}\n\n\n\nfunc (p *PortMapper) ReleaseMap(protocol string, hostPort int) error ", "output": "{\n\tp.mutex.Lock()\n\tdefer p.mutex.Unlock()\n\n\tvar pset PortSet\n\n\tif strings.EqualFold(protocol, \"udp\") {\n\t\tpset = p.udpMap\n\t} else {\n\t\tpset = p.tcpMap\n\t}\n\n\t_, ok := pset[hostPort]\n\tif !ok {\n\t\tglog.Errorf(\"Host port %d has not been used\", hostPort)\n\t}\n\n\tdelete(pset, hostPort)\n\treturn nil\n}"} {"input": "package parser\n\n\ntype Sequence struct {\n\tContent []Statement\n\tParent *Sequence \n}\n\n\nfunc (s Sequence) String() (string, error) {\n\tvar content string\n\n\tif s.Parent != nil {\n\n\t\tlength := len(s.Content)\n\t\tif length > 0 {\n\t\t\trepr, err := s.Content[0].String()\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tcontent += repr\n\t\t}\n\n\t\tfor i := 1; i < length; i++ {\n\t\t\trepr, err := s.Content[i].String()\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tcontent += \";\" + repr\n\t\t}\n\n\t\tcontent = \"\\\"\" + content + \"\\\"\"\n\t} else {\n\n\t\tfor _, statement := range s.Content {\n\t\t\trepr, err := statement.String()\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tcontent += repr + \"\\n\"\n\t\t}\n\t}\n\n\treturn content, nil\n}\n\nfunc (s Sequence) Undo() (string, error) {\n\tvar content string\n\n\tlength := len(s.Content)\n\tif length > 0 {\n\t\trepr, err := s.Content[0].Undo()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tcontent += repr\n\t}\n\n\tfor i := 1; i < length; i++ {\n\t\trepr, err := s.Content[i].Undo()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tcontent += \";\" + repr\n\t}\n\n\tcontent = \"\\\"\" + content + \"\\\"\"\n\n\treturn content, nil\n}\n\n\nfunc (s *Sequence) Last() *Statement {\n\tif len(s.Content) == 0 {\n\t\treturn nil\n\t}\n\n\treturn &s.Content[len(s.Content)-1]\n}\n\n\n\n\nfunc (s *Sequence) Add(command string) *Statement ", "output": "{\n\ts.Content = append(s.Content, Statement{Command: command})\n\n\treturn &s.Content[len(s.Content)-1]\n}"} {"input": "package transfer\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestPicksFirstDatanode(t *testing.T) {\n\tdf := newDatanodeFailover([]string{\"foo:6000\", \"bar:6000\"})\n\tassert.EqualValues(t, df.next(), \"foo:6000\")\n}\n\n\n\nfunc TestPicksDatanodesWithOldestFailures(t *testing.T) {\n\tdf := newDatanodeFailover([]string{\"foo:6000\", \"bar:6000\"})\n\tdatanodeFailures[\"foo:6000\"] = time.Now().Add(-10 * time.Minute)\n\tdatanodeFailures[\"bar:6000\"] = time.Now()\n\n\tassert.EqualValues(t, df.next(), \"foo:6000\")\n}\n\nfunc TestPicksDatanodesWithoutFailures(t *testing.T) ", "output": "{\n\tdf := newDatanodeFailover([]string{\"foo:6000\", \"foo:7000\", \"bar:6000\"})\n\tdatanodeFailures[\"foo:6000\"] = time.Now()\n\n\tassert.EqualValues(t, df.next(), \"foo:7000\")\n}"} {"input": "package node\n\nimport (\n\t\"os\"\n\n\t\"github.com/cilium/cilium/pkg/logging/logfields\"\n)\n\nvar (\n\tnodeName = \"localhost\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\nfunc GetName() string {\n\treturn nodeName\n}\n\nfunc init() {\n\tif h, err := os.Hostname(); err != nil {\n\t\tlog.WithError(err).Warn(\"Unable to retrieve local hostname\")\n\t} else {\n\t\tlog.WithField(logfields.NodeName, h).Debug(\"os.Hostname() returned\")\n\t\tnodeName = h\n\t}\n}\n\nfunc SetName(name string) ", "output": "{\n\tnodeName = name\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc main() {\n\tvar m map[string]string\n\tfmt.Printf(\"len(m):%2d\\n\", len(m)) \n\n\tfor k, _ := range m { \n\t\tfmt.Println(k)\n\t}\n\n\tv, ok := m[\"2\"]\n\tfmt.Printf(\"v:%s, ok:%v\\n\\n\", v, ok) \n\n\n\treq, err := NewGet(\n\t\t\"http:www.baidu.com\",\n\t\tmap[string]string{\n\t\t\t\"USER-AGENT\": \"golang/gopher\", \n\t\t}, \n\t)\n\tfmt.Println(\"_______________________\")\n\tfmt.Println(req.Method) \n\tfmt.Println(req.URL) \n\tfmt.Println(req.Header) \n\tfmt.Println(err) \n\tfmt.Println(\"_______________________\")\n\n\treq2, err := NewGet(\"http:www.baidu.com\", map[string]string{}) \n\tfmt.Println(req2)\n\treq3, err := NewGet(\"http:www.baidu.com\", nil) \n\tfmt.Println(req3)\n\n\tvar m1 map[int]int \n\tfmt.Println(m1 == nil)\n\tfmt.Println(\"=============\")\n\tm2 := make(map[int]int, 0) \n\tfmt.Println(m2 == nil)\n\tm2[5] = 55 \n\tfmt.Println(m2) \n\n}\n\n\n\nfunc NewGet(url string, headers map[string]string) (*http.Request, error) ", "output": "{\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range headers {\n\t\treq.Header.Set(k, v)\n\t}\n\n\treturn req, nil\n}"} {"input": "package registrytest\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/api\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/fields\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/labels\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/watch\"\n)\n\n\ntype EndpointRegistry struct {\n\tEndpoints *api.EndpointsList\n\tUpdates []api.Endpoints\n\tErr error\n\n\tlock sync.Mutex\n}\n\nfunc (e *EndpointRegistry) ListEndpoints(ctx api.Context) (*api.EndpointsList, error) {\n\te.lock.Lock()\n\tdefer e.lock.Unlock()\n\n\treturn e.Endpoints, e.Err\n}\n\nfunc (e *EndpointRegistry) GetEndpoints(ctx api.Context, name string) (*api.Endpoints, error) {\n\te.lock.Lock()\n\tdefer e.lock.Unlock()\n\tif e.Err != nil {\n\t\treturn nil, e.Err\n\t}\n\tif e.Endpoints != nil {\n\t\tfor _, endpoint := range e.Endpoints.Items {\n\t\t\tif endpoint.Name == name {\n\t\t\t\treturn &endpoint, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, errors.NewNotFound(\"Endpoints\", name)\n}\n\nfunc (e *EndpointRegistry) WatchEndpoints(ctx api.Context, labels labels.Selector, fields fields.Selector, resourceVersion string) (watch.Interface, error) {\n\treturn nil, fmt.Errorf(\"unimplemented!\")\n}\n\n\n\nfunc (e *EndpointRegistry) UpdateEndpoints(ctx api.Context, endpoints *api.Endpoints) error ", "output": "{\n\te.lock.Lock()\n\tdefer e.lock.Unlock()\n\n\te.Updates = append(e.Updates, *endpoints)\n\n\tif e.Err != nil {\n\t\treturn e.Err\n\t}\n\tif e.Endpoints == nil {\n\t\te.Endpoints = &api.EndpointsList{\n\t\t\tItems: []api.Endpoints{\n\t\t\t\t*endpoints,\n\t\t\t},\n\t\t}\n\t\treturn nil\n\t}\n\tfor ix := range e.Endpoints.Items {\n\t\tif e.Endpoints.Items[ix].Name == endpoints.Name {\n\t\t\te.Endpoints.Items[ix] = *endpoints\n\t\t}\n\t}\n\te.Endpoints.Items = append(e.Endpoints.Items, *endpoints)\n\treturn nil\n}"} {"input": "package controllers\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/astaxie/beego\"\n\t\"github.com/ylqjgm/SCBlog/common\"\n)\n\ntype LoginController struct {\n\tbeego.Controller\n}\n\n\nfunc (this *LoginController) Index() {\n\tv := this.GetSession(\"admin\")\n\tif v != nil {\n\t\tif v == beego.AppConfig.String(\"adminuser\") {\n\t\t\tthis.Redirect(\"/admin\", 302)\n\t\t}\n\t}\n\n\tif this.Ctx.Request.Method == \"POST\" {\n\t\tuser := this.GetString(\"username\")\n\t\tpass := this.GetString(\"password\")\n\t\tcaptcha := this.GetString(\"captcha\")\n\n\t\tv := this.GetSession(\"captcha\")\n\t\tcp := \"\"\n\t\tif v != nil {\n\t\t\tcp = v.(string)\n\t\t}\n\n\t\tif captcha != cp {\n\t\t\tthis.Redirect(\"/admin/login\", 302)\n\t\t} else if user != beego.AppConfig.String(\"adminuser\") || pass != beego.AppConfig.String(\"adminpass\") {\n\t\t\tthis.Redirect(\"/admin/login\", 302)\n\t\t} else {\n\t\t\tthis.SetSession(\"admin\", beego.AppConfig.String(\"adminuser\"))\n\n\t\t\tthis.Redirect(\"/admin\", 302)\n\t\t}\n\t}\n\n\tthis.TplNames = \"admin/login.html\"\n}\n\n\nfunc (this *LoginController) Logout() {\n\tthis.DelSession(\"admin\")\n\n\tthis.Redirect(\"/admin/login\", 302)\n}\n\n\n\n\nfunc (this *LoginController) Captcha() ", "output": "{\n\td := make([]byte, 4)\n\ts := common.NewLen(4)\n\tss := \"\"\n\td = []byte(s)\n\n\tfor v := range d {\n\t\td[v] %= 10\n\t\tss += strconv.FormatInt(int64(d[v]), 32)\n\t}\n\n\tthis.Ctx.Output.Header(\"Content-Type\", \"image/png\")\n\tthis.SetSession(\"captcha\", ss)\n\tcommon.NewImage(d, 100, 40).WriteTo(this.Ctx.ResponseWriter)\n}"} {"input": "package v1alpha1\n\nimport (\n\tcorev1 \"k8s.io/api/core/v1\"\n)\n\n\n\ntype ListBuilder struct {\n\tlist *PodList\n\tfilters predicateList\n}\n\n\nfunc NewListBuilder() *ListBuilder {\n\treturn &ListBuilder{list: &PodList{items: []*Pod{}}}\n}\n\n\n\n\n\nfunc ListBuilderForObjectList(pods ...*Pod) *ListBuilder {\n\tb := &ListBuilder{list: &PodList{}}\n\tif pods == nil {\n\t\treturn b\n\t}\n\tfor _, p := range pods {\n\t\tp := p\n\t\tb.list.items = append(b.list.items, p)\n\t}\n\treturn b\n}\n\n\n\n\nfunc (b *ListBuilder) List() *PodList {\n\tif b.filters == nil || len(b.filters) == 0 {\n\t\treturn b.list\n\t}\n\tfiltered := &PodList{}\n\tfor _, pod := range b.list.items {\n\t\tif b.filters.all(pod) {\n\t\t\tfiltered.items = append(filtered.items, pod)\n\t\t}\n\t}\n\treturn filtered\n}\n\n\n\nfunc (b *ListBuilder) WithFilter(pred ...Predicate) *ListBuilder {\n\tb.filters = append(b.filters, pred...)\n\treturn b\n}\n\nfunc ListBuilderForAPIList(pods *corev1.PodList) *ListBuilder ", "output": "{\n\tb := &ListBuilder{list: &PodList{}}\n\tif pods == nil {\n\t\treturn b\n\t}\n\tfor _, p := range pods.Items {\n\t\tp := p\n\t\tb.list.items = append(b.list.items, &Pod{object: &p})\n\t}\n\treturn b\n}"} {"input": "package bit\n\nimport (\n\t\"image\"\n)\n\n\n\nfunc imagefill(src *Image, dst *image.RGBA, point image.Point) {\n\tbounds := src.Bounds()\n\n\tymax := point.Y + bounds.Max.Y\n\txmax := point.X + bounds.Max.X\n\n\tfor y := point.Y; y < ymax; y++ {\n\t\tfor x := point.X; x < xmax; x++ {\n\t\t\t_x := x % bounds.Max.X\n\t\t\t_y := y % bounds.Max.Y\n\n\t\t\tcol := src.At(_x, _y)\n\n\t\t\tdst.Set(x, y, col)\n\t\t}\n\t}\n}\n\nfunc (img *Image) Mozaic(n int) Image ", "output": "{\n\tgrayimg := img.Gray()\n\tbounds := grayimg.Bounds()\n\n\tymax := (bounds.Max.Y / n) * bounds.Max.Y\n\txmax := (bounds.Max.X / n) * bounds.Max.X\n\n\trectangle := image.Rect(0, 0, xmax, ymax)\n\tnewimg := image.NewRGBA(rectangle)\n\n\tpoint := image.Point{0, 0}\n\n\tfor y := 0; y < bounds.Max.Y; y += n {\n\t\tfor x := 0; x < bounds.Max.X; x += n {\n\t\t\tavgcol := img.AverageColor(image.Point{x, y}, n)\n\t\t\tavgimg := grayimg.And(avgcol)\n\n\t\t\timagefill(&avgimg, newimg, point)\n\n\t\t\tpoint.X += bounds.Max.X\n\t\t}\n\t\tpoint.X = 0\n\t\tpoint.Y += bounds.Max.Y\n\t}\n\n\treturn Image{newimg}\n}"} {"input": "package tail\n\nimport (\n\t\"github.com/hpcloud/tail/winfile\"\n\t\"os\"\n)\n\n\n\nfunc OpenFile(name string) (file *os.File, err error) ", "output": "{\n\treturn winfile.OpenFile(name, os.O_RDONLY, 0)\n}"} {"input": "package ufile\n\nimport (\n\t\"github.com/ucloud/ucloud-sdk-go/ucloud/request\"\n\t\"github.com/ucloud/ucloud-sdk-go/ucloud/response\"\n)\n\n\ntype CreateBucketRequest struct {\n\trequest.CommonBase\n\n\n\n\tBucketName *string `required:\"true\"`\n\n\tType *string `required:\"false\"`\n}\n\n\ntype CreateBucketResponse struct {\n\tresponse.CommonBase\n\n\tBucketId string\n\n\tBucketName string\n}\n\n\n\n\n\nfunc (c *UFileClient) CreateBucket(req *CreateBucketRequest) (*CreateBucketResponse, error) {\n\tvar err error\n\tvar res CreateBucketResponse\n\n\treqCopier := *req\n\n\terr = c.Client.InvokeAction(\"CreateBucket\", &reqCopier, &res)\n\tif err != nil {\n\t\treturn &res, err\n\t}\n\n\treturn &res, nil\n}\n\nfunc (c *UFileClient) NewCreateBucketRequest() *CreateBucketRequest ", "output": "{\n\treq := &CreateBucketRequest{}\n\n\tc.Client.SetupRequest(req)\n\n\treq.SetRetryable(false)\n\treturn req\n}"} {"input": "package cli\n\nimport (\n\t\"strings\"\n)\n\ntype MultiError struct {\n\tErrors []error\n}\n\nfunc NewMultiError(err ...error) MultiError {\n\treturn MultiError{Errors: err}\n}\n\n\n\nfunc (m MultiError) Error() string ", "output": "{\n\terrs := make([]string, len(m.Errors))\n\tfor i, err := range m.Errors {\n\t\terrs[i] = err.Error()\n\t}\n\n\treturn strings.Join(errs, \"\\n\")\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/astaxie/beego\"\n\t\"github.com/dyzdyz010/MartianBlog/models\"\n)\n\ntype FrontController struct {\n\tbeego.Controller\n}\n\nfunc (this *FrontController) Articles() {\n\tvar articles []models.Article\n\n\tif status := this.GetString(\"status\"); status != \"\" {\n\t\tarticles = models.ArticlesByStatus(status)\n\t} else {\n\t\tarticles = models.AllArticles()\n\t}\n\n\tthis.Data[\"json\"] = articles\n\tthis.ServeJson()\n}\n\nfunc (this *FrontController) Article() {\n\tid := this.GetString(\"id\")\n\n\tthis.Data[\"json\"] = models.ArticleById(id)\n\tthis.ServeJson()\n}\n\n\n\nfunc (this *FrontController) BlogInfo() ", "output": "{\n\tthis.Data[\"json\"] = models.BlogInfo\n\tthis.ServeJson()\n}"} {"input": "package atomicfile\n\nimport (\n\t\"os\"\n)\n\n\n\n\n\n\nfunc AtomicRename(oldpath, newpath string) error ", "output": "{\n\treturn os.Rename(oldpath, newpath)\n}"} {"input": "package goenocean\n\ntype Telegram4bsLearn struct {\n\tTelegram\n}\n\n\nfunc NewTelegram4bsLearn() *Telegram4bsLearn { \n\tt := &Telegram4bsLearn{NewTelegram4bs()}\n\tt.SetLearn(true)\n\treturn t\n} \n\nfunc (p *Telegram4bsLearn) SetTelegram(t Telegram) { \n\tp.Telegram = t\n} \n\nfunc (p *Telegram4bsLearn) Learn() bool { \n\tlearnBit := (p.TelegramData()[3] >> 3) & 0x01\n\tif learnBit == 0 {\n\t\treturn true\n\t}\n\treturn false\n} \nfunc (p *Telegram4bsLearn) SetLearn(lrn bool) { \n\tvar data uint8\n\tif lrn {\n\t\tdata = 0\n\t} else {\n\t\tdata = 1\n\t}\n\ttmp := p.TelegramData()\n\ttmp[3] &^= 0x08\n\ttmp[3] |= (data << 3) & 0x08\n\tp.SetTelegramData(tmp)\n} \n\nfunc (p *Telegram4bsLearn) LearnFunc() byte {\n\treturn (p.TelegramData()[0] & 0xf8) >> 2\n}\nfunc (p *Telegram4bsLearn) SetLearnFunc(lfunc byte) {\n\ttmp := p.TelegramData()\n\ttmp[0] &^= 0xf8 \n\ttmp[0] |= (lfunc << 2) & 0xf8 \n\tp.SetTelegramData(tmp)\n}\n\nfunc (p *Telegram4bsLearn) LearnType() byte { \n\ttmp := p.TelegramData()\n\tbyte0 := (tmp[0] & 0x03) << 5\n\tbyte1 := (tmp[1] & 0xf8) >> 3\n\treturn byte0 | byte1\n} \n\n\nfunc (p *Telegram4bsLearn) SetLearnType(ltype byte) ", "output": "{ \n\ttmp := p.TelegramData()\n\n\tbyte0 := (ltype & 0x60) >> 5 \n\tbyte1 := (ltype & 0x1f) << 3 \n\n\ttmp[0] &^= 0x03 \n\ttmp[1] &^= 0xf8 \n\ttmp[0] |= (byte0) & 0x03 \n\ttmp[1] |= (byte1) & 0xf8 \n\n\ttmp[3] = tmp[3] | 0x80\n\n\tp.SetTelegramData(tmp)\n}"} {"input": "package client\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"net/url\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/docker/docker/api/types/filters\"\n)\n\n\n\n\nfunc (cli *Client) PluginList(ctx context.Context, filter filters.Args) (types.PluginsListResponse, error) ", "output": "{\n\tvar plugins types.PluginsListResponse\n\tquery := url.Values{}\n\n\tif filter.Len() > 0 {\n\t\tfilterJSON, err := filters.ToParamWithVersion(cli.version, filter)\n\t\tif err != nil {\n\t\t\treturn plugins, err\n\t\t}\n\t\tquery.Set(\"filters\", filterJSON)\n\t}\n\tresp, err := cli.get(ctx, \"/plugins\", query, nil)\n\tif err != nil {\n\t\treturn plugins, wrapResponseError(err, resp, \"plugin\", \"\")\n\t}\n\n\terr = json.NewDecoder(resp.body).Decode(&plugins)\n\tensureReaderClosed(resp)\n\treturn plugins, err\n}"} {"input": "package osutil\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\t\"sync\"\n\t\"syscall\"\n\n\t\"go.uber.org/zap\"\n)\n\n\n\ntype InterruptHandler func()\n\nvar (\n\tinterruptRegisterMu, interruptExitMu sync.Mutex\n\tinterruptHandlers = []InterruptHandler{}\n)\n\n\n\n\n\n\nfunc HandleInterrupts(lg *zap.Logger) {\n\tnotifier := make(chan os.Signal, 1)\n\tsignal.Notify(notifier, syscall.SIGINT, syscall.SIGTERM)\n\n\tgo func() {\n\t\tsig := <-notifier\n\n\t\tinterruptRegisterMu.Lock()\n\t\tihs := make([]InterruptHandler, len(interruptHandlers))\n\t\tcopy(ihs, interruptHandlers)\n\t\tinterruptRegisterMu.Unlock()\n\n\t\tinterruptExitMu.Lock()\n\n\t\tif lg != nil {\n\t\t\tlg.Info(\"received signal; shutting down\", zap.String(\"signal\", sig.String()))\n\t\t} else {\n\t\t\tplog.Noticef(\"received %v signal, shutting down...\", sig)\n\t\t}\n\n\t\tfor _, h := range ihs {\n\t\t\th()\n\t\t}\n\t\tsignal.Stop(notifier)\n\t\tpid := syscall.Getpid()\n\t\tif pid == 1 {\n\t\t\tos.Exit(0)\n\t\t}\n\t\tsetDflSignal(sig.(syscall.Signal))\n\t\tsyscall.Kill(pid, sig.(syscall.Signal))\n\t}()\n}\n\n\nfunc Exit(code int) {\n\tinterruptExitMu.Lock()\n\tos.Exit(code)\n}\n\nfunc RegisterInterruptHandler(h InterruptHandler) ", "output": "{\n\tinterruptRegisterMu.Lock()\n\tdefer interruptRegisterMu.Unlock()\n\tinterruptHandlers = append(interruptHandlers, h)\n}"} {"input": "package tweet\n\nimport (\n\t\"common\"\n\t\"encoding/json\"\n\n\t\"appengine\"\n\t\"appengine/urlfetch\"\n\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n\n\n\n\nfunc TweetList(cxt appengine.Context, uid int, session string, access_token string, page int, ch chan *TweetsList) {\n\tclient := urlfetch.Client(cxt)\n\tbody := fmt.Sprintf(common.TWEET_LIST_SCHEME, uid, access_token, page)\n\tif r, e := http.NewRequest(common.POST, common.TWEET_LIST_URL, bytes.NewBufferString(body)); e == nil {\n\t\tcommon.MakeHeader(r, \"oscid=\"+session, 0)\n\t\tif resp, e := client.Do(r); e == nil {\n\t\t\tif resp != nil {\n\t\t\t\tdefer resp.Body.Close()\n\t\t\t}\n\t\t\tpTweetsList := new(TweetsList)\n\t\t\tif bytes, e := ioutil.ReadAll(resp.Body); e == nil {\n\t\t\t\tif e := json.Unmarshal(bytes, pTweetsList); e == nil {\n\t\t\t\t\tch <- pTweetsList\n\t\t\t\t} else {\n\t\t\t\t\tch <- nil\n\t\t\t\t\tcxt.Errorf(\"Error but still going: %v\", e)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tch <- nil\n\t\t\t\tpanic(e)\n\t\t\t}\n\t\t} else {\n\t\t\tch <- nil\n\t\t\tcxt.Errorf(\"Error but still going: %v\", e)\n\t\t}\n\t} else {\n\t\tch <- nil\n\t\tpanic(e)\n\t}\n}\n\nfunc ShowTweetList(w http.ResponseWriter, r *http.Request, pTweetsList *TweetsList, uid int, page int) ", "output": "{\n\ts := fmt.Sprintf(`{\"status\":%d, \"tweets\":%s}`, common.STATUS_OK, pTweetsList.StringTweetsArray())\n\tw.Header().Set(\"Content-Type\", common.API_RESTYPE)\n\tfmt.Fprintf(w, s)\n}"} {"input": "package countdata\n\nimport (\n\t\"io\"\n\n\t\"golang.org/x/net/html\"\n)\n\n\n\nfunc Count(r io.Reader) (map[string]int, error) {\n\tdoc, err := html.Parse(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := make(map[string]int)\n\tvisit(doc, result)\n\treturn result, nil\n}\n\nfunc visit(n *html.Node, result map[string]int) ", "output": "{\n\tif n == nil {\n\t\treturn\n\t}\n\tif n.Type == html.ElementNode {\n\t\tresult[n.Data]++\n\t}\n\tvisit(n.FirstChild, result) \n\tvisit(n.NextSibling, result) \n}"} {"input": "package underscore\n\nfunc Select(source, predicate interface{}) interface{} {\n\treturn filter(source, predicate, true)\n}\n\nfunc SelectBy(source interface{}, properties map[string]interface{}) interface{} {\n\treturn Select(source, func (value, _ interface{}) bool {\n\t\treturn IsMatch(value, properties)\n\t})\n}\n\n\nfunc (this *Query) Select(predicate interface{}) Queryer {\n\tthis.source = Select(this.source, predicate)\n\treturn this\n}\n\n\n\nfunc (this *Query) SelectBy(properties map[string]interface{}) Queryer ", "output": "{\n\tthis.source = SelectBy(this.source, properties)\n\treturn this\n}"} {"input": "package btcec\n\nimport (\n\tsecp \"github.com/decred/dcrd/dcrec/secp256k1/v4\"\n)\n\n\n\ntype JacobianPoint = secp.JacobianPoint\n\n\n\nfunc MakeJacobianPoint(x, y, z *FieldVal) JacobianPoint {\n\treturn secp.MakeJacobianPoint(x, y, z)\n}\n\n\n\nfunc AddNonConst(p1, p2, result *JacobianPoint) {\n\tsecp.AddNonConst(p1, p2, result)\n}\n\n\n\n\n\n\n\n\nfunc DecompressY(x *FieldVal, odd bool, resultY *FieldVal) bool {\n\treturn secp.DecompressY(x, odd, resultY)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ScalarBaseMultNonConst(k *ModNScalar, result *JacobianPoint) {\n\tsecp.ScalarBaseMultNonConst(k, result)\n}\n\n\n\n\n\n\n\nfunc ScalarMultNonConst(k *ModNScalar, point, result *JacobianPoint) {\n\tsecp.ScalarMultNonConst(k, point, result)\n}\n\nfunc DoubleNonConst(p, result *JacobianPoint) ", "output": "{\n\tsecp.DoubleNonConst(p, result)\n}"} {"input": "package exec\n\nimport \"fmt\"\n\nvar (\n\tExecTypeOs ExecType = 0\n\n\texecTypeToString = map[ExecType]string{\n\t\tExecTypeOs: \"os\",\n\t}\n\tlenExecTypeToString = len(execTypeToString)\n\tstringToExecType = map[string]ExecType{\n\t\t\"os\": ExecTypeOs,\n\t}\n)\n\ntype ExecType uint\n\nfunc AllExecTypes() []ExecType {\n\treturn []ExecType{\n\t\tExecTypeOs,\n\t}\n}\n\n\n\nfunc (e ExecType) String() string {\n\tif int(e) < lenExecTypeToString {\n\t\treturn execTypeToString[e]\n\t}\n\tpanic(UnknownExecType(e).Error())\n}\n\nfunc UnknownExecType(unknownExecType interface{}) error {\n\treturn fmt.Errorf(\"exec: unknown ExecType: %v\", unknownExecType)\n}\n\nfunc ExecTypeOf(s string) (ExecType, error) ", "output": "{\n\texecType, ok := stringToExecType[s]\n\tif !ok {\n\t\treturn 0, UnknownExecType(s)\n\t}\n\treturn execType, nil\n}"} {"input": "package errbag\n\nimport (\n\t\"errors\"\n\t\"time\"\n)\n\n\n\ntype ErrBag struct {\n\twaitTime uint\n\tleakInterval uint\n\terrChan chan struct{}\n\tdone chan struct{}\n}\n\n\n\ntype Status struct {\n\tState int\n\n\tWaitTime uint\n}\n\n\ntype CallbackFunc func(status Status)\n\nconst (\n\tStatusThrottling = iota\n\n\tStatusOK\n)\n\n\n\n\n\n\n\n\n\nfunc New(waitTime, errBagSize, leakInterval uint) (*ErrBag, error) {\n\tif waitTime == 0 {\n\t\treturn nil, errors.New(\"setting waitTime to 0 would prevent throttling\")\n\t}\n\tif errBagSize == 0 {\n\t\treturn nil, errors.New(\"setting errBagSize to 0 would prevent throttling\")\n\t}\n\tif leakInterval < 100 {\n\t\treturn nil, errors.New(\"leakInterval must be greater than 100\")\n\t}\n\n\terrChan := make(chan struct{}, errBagSize)\n\tdone := make(chan struct{}, 1)\n\treturn &ErrBag{waitTime: waitTime, leakInterval: leakInterval, errChan: errChan, done: done}, nil\n}\n\n\n\nfunc (eb ErrBag) Inflate() {\n\tready := make(chan bool)\n\tgo func() {\n\t\tready <- true\n\t\teb.errLeak()\n\t}()\n\t<-ready\n\tclose(ready)\n}\n\n\n\nfunc (eb ErrBag) Deflate() {\n\teb.done <- struct{}{}\n\tclose(eb.done)\n\tclose(eb.errChan)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (eb ErrBag) errLeak() {\n\tfor {\n\t\tselect {\n\t\tcase <-eb.done:\n\t\t\treturn\n\t\tcase <-eb.errChan:\n\t\t\ttime.Sleep(time.Millisecond * time.Duration(eb.leakInterval))\n\t\t}\n\t}\n}\n\nfunc (eb ErrBag) Record(err error, callback CallbackFunc) ", "output": "{\n\tif err != nil {\n\t\tselect {\n\t\tcase eb.errChan <- struct{}{}:\n\t\t\tif callback != nil {\n\t\t\t\tcallback(Status{State: StatusOK})\n\t\t\t}\n\t\tdefault:\n\t\t\tif callback != nil {\n\t\t\t\tcallback(Status{State: StatusThrottling, WaitTime: eb.waitTime})\n\t\t\t}\n\t\t\ttime.Sleep(time.Second * time.Duration(eb.waitTime))\n\t\t}\n\t}\n}"} {"input": "package types\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"path\"\n\t\"strings\"\n)\n\n\ntype Resource string\n\nfunc (res Resource) String() string {\n\treturn string(res)\n}\n\n\nfunc (res Resource) RelativeTo(other Resource) (Resource, error) {\n\tprefix := other.String()\n\tstr := res.String()\n\n\tif !strings.HasPrefix(str, prefix) {\n\t\treturn Resource(\"\"), errors.New(\"value error\")\n\t}\n\n\trelative := strings.TrimPrefix(strings.TrimPrefix(str, prefix), \"/\")\n\tif relative == \"\" {\n\t\trelative = \".\"\n\t}\n\n\treturn Resource(relative), nil\n}\n\n\n\n\n\nfunc (res Resource) GetNamespace() (Namespace, error) {\n\treturn nil, fmt.Errorf(\"no namespace found for %s\", res)\n}\n\nfunc (res Resource) Subresource(resources ...Resource) Resource ", "output": "{\n\telements := []string{res.String()}\n\n\tfor _, resource := range resources {\n\t\telements = append(elements, resource.String())\n\t}\n\n\treturn Resource(path.Join(elements...))\n}"} {"input": "package elastic\n\n\n\n\n\ntype GeoPolygonQuery struct {\n\tname string\n\tpoints []*GeoPoint\n\tqueryName string\n}\n\n\n\n\n\nfunc (q *GeoPolygonQuery) AddPoint(lat, lon float64) *GeoPolygonQuery {\n\tq.points = append(q.points, GeoPointFromLatLon(lat, lon))\n\treturn q\n}\n\n\nfunc (q *GeoPolygonQuery) AddGeoPoint(point *GeoPoint) *GeoPolygonQuery {\n\tq.points = append(q.points, point)\n\treturn q\n}\n\nfunc (q *GeoPolygonQuery) QueryName(queryName string) *GeoPolygonQuery {\n\tq.queryName = queryName\n\treturn q\n}\n\n\nfunc (q *GeoPolygonQuery) Source() (interface{}, error) {\n\tsource := make(map[string]interface{})\n\n\tparams := make(map[string]interface{})\n\tsource[\"geo_polygon\"] = params\n\n\tpolygon := make(map[string]interface{})\n\tparams[q.name] = polygon\n\n\tpoints := make([]interface{}, 0)\n\tfor _, point := range q.points {\n\t\tpoints = append(points, point.Source())\n\t}\n\tpolygon[\"points\"] = points\n\n\tif q.queryName != \"\" {\n\t\tparams[\"_name\"] = q.queryName\n\t}\n\n\treturn source, nil\n}\n\nfunc NewGeoPolygonQuery(name string) *GeoPolygonQuery ", "output": "{\n\treturn &GeoPolygonQuery{\n\t\tname: name,\n\t\tpoints: make([]*GeoPoint, 0),\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com/kr/pty\"\n\t\"github.com/urfave/cli\"\n)\n\n\n\nfunc bazelAction(c *cli.Context) error {\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tindex := strings.Index(pwd, \"go-common\")\n\tif index == -1 {\n\t\tfmt.Println(\"not in go-common\")\n\t\tos.Exit(1)\n\t}\n\tresult := strings.Split(pwd[index:], \"/\")\n\trunPath := strings.Join(result[1:], \"/\")\n\tif c.NArg() > 0 {\n\t\tparam := []string{}\n\t\tfor index := 0; index < c.NArg(); index++ {\n\t\t\tname := path.Join(runPath, path.Clean(c.Args().Get(index)))\n\t\t\tif name == \".\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.HasSuffix(name, \"/...\") {\n\t\t\t\tparam = append(param, \"//\"+name)\n\t\t\t} else {\n\t\t\t\tparam = append(param, \"//\"+name+\"/...\")\n\t\t\t}\n\n\t\t}\n\t\trunbazel(param...)\n\t} else {\n\t\tif len(runPath) == 0 {\n\t\t\trunbazel(\"//app/...\", \"//library/...\", \"//vendor/...\")\n\t\t} else {\n\t\t\trunbazel(\"//\" + strings.Join(result[1:], \"/\") + \"/...\")\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc runbazel(param ...string) ", "output": "{\n\tcommand := append([]string{\"build\", \"--watchfs\"}, param...)\n\tfmt.Println(command)\n\tcmd := exec.Command(\"bazel\", command...)\n\tf, err := pty.Start(cmd)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tio.Copy(os.Stdout, f)\n}"} {"input": "package git\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/Originate/git-town/src/command\"\n\t\"github.com/Originate/git-town/src/util\"\n)\n\n\n\nfunc EnsureDoesNotHaveConflicts() {\n\tutil.Ensure(!HasConflicts(), \"You must resolve the conflicts before continuing\")\n}\n\n\n\nfunc EnsureDoesNotHaveOpenChanges(message string) {\n\tutil.Ensure(!HasOpenChanges(), \"You have uncommitted changes. \"+message)\n}\n\n\nvar rootDirectory string\n\n\n\nfunc GetRootDirectory() string {\n\tif rootDirectory == \"\" {\n\t\trootDirectory = command.MustRun(\"git\", \"rev-parse\", \"--show-toplevel\").OutputSanitized()\n\t}\n\treturn rootDirectory\n}\n\n\nfunc HasConflicts() bool {\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"Unmerged paths\")\n}\n\n\n\n\n\n\nfunc HasShippableChanges(branchName string) bool {\n\treturn command.MustRun(\"git\", \"diff\", Config().GetMainBranch()+\"..\"+branchName).OutputSanitized() != \"\"\n}\n\n\n\nfunc IsMergeInProgress() bool {\n\t_, err := os.Stat(fmt.Sprintf(\"%s/.git/MERGE_HEAD\", GetRootDirectory()))\n\treturn err == nil\n}\n\n\n\nfunc IsRebaseInProgress() bool {\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"rebase in progress\")\n}\n\nfunc HasOpenChanges() bool ", "output": "{\n\treturn command.MustRun(\"git\", \"status\", \"--porcelain\").OutputSanitized() != \"\"\n}"} {"input": "package sqltrace\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\n\n\ntype sqlTrace struct {\n\ton int64 \n\n\t*log.Logger\n}\n\nfunc newSQLTrace() *sqlTrace {\n\treturn &sqlTrace{\n\t\tLogger: log.New(os.Stdout, \"hdb \", log.Ldate|log.Ltime|log.Lshortfile),\n\t}\n}\nfunc (t *sqlTrace) On() bool { return atomic.LoadInt64(&t.on) != 0 }\nfunc (t *sqlTrace) SetOn(on bool) { atomic.StoreInt64(&t.on, boolToInt64(on)) }\n\ntype flagValue struct {\n\tt *sqlTrace\n}\n\nfunc (v flagValue) IsBoolFlag() bool { return true }\n\nfunc (v flagValue) String() string {\n\tif v.t == nil {\n\t\treturn \"\"\n\t}\n\treturn strconv.FormatBool(v.t.On())\n}\n\nfunc (v flagValue) Set(s string) error {\n\tf, err := strconv.ParseBool(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.t.SetOn(f)\n\treturn nil\n}\n\nvar tracer = newSQLTrace()\n\nfunc init() {\n\tflag.Var(&flagValue{t: tracer}, \"hdb.sqlTrace\", \"enabling hdb sql trace\")\n}\n\n\nfunc On() bool { return tracer.On() }\n\n\nfunc SetOn(on bool) { tracer.SetOn(on) }\n\n\nfunc Trace(v ...interface{}) { tracer.Print(v...) }\n\n\nfunc Tracef(format string, v ...interface{}) { tracer.Printf(format, v...) }\n\n\nfunc Traceln(v ...interface{}) { tracer.Println(v...) }\n\nfunc boolToInt64(f bool) int64 ", "output": "{\n\tif f {\n\t\treturn 1\n\t}\n\treturn 0\n}"} {"input": "package server\n\nimport (\n\t\"context\"\n\n\t\"github.com/jaegertracing/jaeger/cmd/collector/app/processor\"\n\t\"github.com/jaegertracing/jaeger/model\"\n\t\"github.com/jaegertracing/jaeger/thrift-gen/sampling\"\n)\n\ntype mockSamplingStore struct{}\n\nfunc (s mockSamplingStore) GetSamplingStrategy(_ context.Context, serviceName string) (*sampling.SamplingStrategyResponse, error) {\n\treturn nil, nil\n}\n\ntype mockSpanProcessor struct {\n}\n\n\n\nfunc (p *mockSpanProcessor) ProcessSpans(spans []*model.Span, _ processor.SpansOptions) ([]bool, error) {\n\treturn []bool{}, nil\n}\n\nfunc (p *mockSpanProcessor) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\n\t\"github.com/ungerik/go-dry\"\n\t\"github.com/urfave/cli\"\n\n\t\"github.com/just-install/just-install/pkg/justinstall\"\n)\n\n\n\nfunc loadRegistry(c *cli.Context) justinstall.Registry ", "output": "{\n\tif !c.GlobalIsSet(\"registry\") {\n\t\treturn justinstall.SmartLoadRegistry(false)\n\t}\n\n\tregistryPath := c.GlobalString(\"registry\")\n\tif !dry.FileExists(registryPath) {\n\t\tlog.Fatalf(\"%v: no such file.\\n\", registryPath)\n\t}\n\n\tlog.Println(\"Loading custom registry at\", registryPath)\n\treturn justinstall.LoadRegistry(registryPath)\n}"} {"input": "package graph\n\nimport (\n\t\"database/sql/driver\"\n\t\"fmt\"\n)\n\n\ntype StatType string\n\n\ntype Stats map[StatType]int\n\nconst (\n\tStatXRefs = \"xrefs\"\n\n\tStatRRefs = \"rrefs\"\n\n\tStatURefs = \"urefs\"\n\n\tStatAuthors = \"authors\"\n\n\tStatClients = \"clients\"\n\n\tStatDependents = \"dependents\"\n\n\tStatExportedElements = \"exported_elements\"\n)\n\nvar AllStatTypes = []StatType{StatXRefs, StatRRefs, StatURefs, StatAuthors, StatClients, StatDependents, StatExportedElements}\n\nfunc (x StatType) IsAbstract() bool {\n\tswitch x {\n\tcase StatXRefs:\n\t\tfallthrough\n\tcase StatClients:\n\t\tfallthrough\n\tcase StatDependents:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\nfunc (x StatType) Value() (driver.Value, error) {\n\treturn string(x), nil\n}\n\n\nfunc (x *StatType) Scan(v interface{}) error {\n\tif data, ok := v.([]byte); ok {\n\t\t*x = StatType(data)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"%T.Scan failed: %v\", x, v)\n}\n\n\n\n\n\n\nfunc UniqueRefDefs(refs []*Ref, m map[RefDefKey]int) map[RefDefKey]int ", "output": "{\n\tif m == nil {\n\t\tm = make(map[RefDefKey]int)\n\t}\n\tfor _, ref := range refs {\n\t\tm[ref.RefDefKey()]++\n\t}\n\treturn m\n}"} {"input": "package fakeclock\n\nimport (\n\t\"time\"\n\n\t\"github.com/pivotal-golang/clock\"\n)\n\ntype fakeTicker struct {\n\ttimer clock.Timer\n}\n\n\n\nfunc (ft *fakeTicker) C() <-chan time.Time {\n\treturn ft.timer.C()\n}\n\nfunc (ft *fakeTicker) Stop() {\n\tft.timer.Stop()\n}\n\nfunc newFakeTicker(timer *fakeTimer) *fakeTicker ", "output": "{\n\treturn &fakeTicker{\n\t\ttimer: timer,\n\t}\n}"} {"input": "package monator\n\nimport (\n \"time\"\n \"bytes\"\n \"encoding/json\"\n)\n\ntype CheckDuration time.Duration\n\nfunc (d CheckDuration) Hours() float64 {\n return time.Duration(d).Hours()\n}\n\n\n\nfunc (d CheckDuration) Nanoseconds() int64 {\n return time.Duration(d).Nanoseconds()\n}\n\nfunc (d CheckDuration) Seconds() float64 {\n return time.Duration(d).Seconds()\n}\n\nfunc (d CheckDuration) Milliseconds() int64 {\n return time.Duration(d).Nanoseconds() / int64(time.Millisecond)\n}\n\nfunc (d CheckDuration) String() string {\n \n rounded := ((time.Duration(d)).Nanoseconds() / int64(time.Millisecond)) * int64(time.Millisecond)\n return time.Duration(rounded).String()\n}\n\n\nfunc (d *CheckDuration) UnmarshalJSON(data []byte) error {\n b := bytes.NewBuffer(data)\n dec := json.NewDecoder(b)\n\n var s string\n\n if err := dec.Decode(&s); err != nil {\n return err\n }\n if duration, err := time.ParseDuration(s); err != nil {\n return err\n } else {\n *d = CheckDuration(duration)\n }\n\n return nil\n}\n\nfunc (d CheckDuration) Minutes() float64 ", "output": "{\n return time.Duration(d).Minutes()\n}"} {"input": "package network\n\nimport (\n\t\"github.com/docker/docker/api/server/httputils\"\n\t\"github.com/docker/docker/api/server/router\"\n)\n\n\ntype networkRouter struct {\n\troutes []router.Route\n}\n\n\nfunc (n networkRouter) Routes() []router.Route {\n\treturn n.routes\n}\n\ntype networkRoute struct {\n\tpath string\n\thandler httputils.APIFunc\n}\n\n\n\n\nfunc (l networkRoute) Handler() httputils.APIFunc ", "output": "{\n\treturn l.handler\n}"} {"input": "package podsecuritypolicy\n\nimport (\n\t\"context\"\n\n\tv3 \"github.com/rancher/types/apis/management.cattle.io/v3\"\n\tv1beta12 \"github.com/rancher/types/apis/policy/v1beta1\"\n\t\"github.com/rancher/types/config\"\n\t\"k8s.io/api/policy/v1beta1\"\n\tk8serrors \"k8s.io/apimachinery/pkg/api/errors\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\n\n\ntype pspHandler struct {\n\tpsptLister v3.PodSecurityPolicyTemplateLister\n\tpodSecurityPolicies v1beta12.PodSecurityPolicyInterface\n}\n\n\n\nfunc (p *pspHandler) sync(key string, obj *v1beta1.PodSecurityPolicy) (runtime.Object, error) {\n\tif obj == nil || obj.DeletionTimestamp != nil {\n\t\treturn obj, nil\n\t}\n\tif templateID, ok := obj.Annotations[podSecurityPolicyTemplateParentAnnotation]; ok {\n\t\t_, err := p.psptLister.Get(\"\", templateID)\n\t\tif err != nil {\n\t\t\tif k8serrors.IsNotFound(err) {\n\t\t\t\treturn obj, p.podSecurityPolicies.Delete(obj.Name, &metav1.DeleteOptions{})\n\n\t\t\t}\n\t\t\treturn obj, err\n\t\t}\n\n\t}\n\treturn obj, nil\n}\n\nfunc RegisterPodSecurityPolicy(ctx context.Context, context *config.UserContext) ", "output": "{\n\tp := pspHandler{\n\t\tpsptLister: context.Management.Management.PodSecurityPolicyTemplates(\"\").Controller().Lister(),\n\t\tpodSecurityPolicies: context.Policy.PodSecurityPolicies(\"\"),\n\t}\n\n\tcontext.Policy.PodSecurityPolicies(\"\").AddHandler(ctx, \"psp-sync\", p.sync)\n}"} {"input": "package sfproto\n\nimport (\n\t\"github.com/sarifsystems/sarif/sarif\"\n)\n\ntype wrappedConn struct {\n\tid string\n\tConn\n}\n\nfunc (c *wrappedConn) Publish(msg sarif.Message) error {\n\treturn c.Write(msg)\n}\n\nfunc (c *wrappedConn) Subscribe(src, action, dest string) error {\n\tmsg := Subscribe(action, dest)\n\tmsg.Source = src\n\treturn c.Publish(msg)\n}\n\n\n\nfunc wrap(conn Conn) sarif.Connection {\n\treturn &wrappedConn{sarif.GenerateId(), conn}\n}\n\nfunc (c *wrappedConn) Consume() (<-chan sarif.Message, error) ", "output": "{\n\tch := make(chan sarif.Message, 10)\n\n\tgo func() {\n\t\tfor {\n\t\t\tmsg, err := c.Read()\n\t\t\tif err != nil {\n\t\t\t\tclose(ch)\n\t\t\t\tc.Close()\n\t\t\t\tc.Conn = nil\n\t\t\t\treturn\n\t\t\t}\n\t\t\tch <- msg\n\t\t}\n\t}()\n\n\treturn (<-chan sarif.Message)(ch), nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestConnect2RDBMS(t *testing.T) ", "output": "{\n\n\th := new(Credentials)\n\th.Host = \"192.168.1.21\"\n\th.User = \"postgres\"\n\th.Pass = \"admin\"\n\th.Port = \"5432\"\n\th.DatabaseName = \"tests\"\n\th.DatabaseTable = \"\"\n\th.RDBMS = \"postgres\"\n\n\tc, err := Connect2RDBMS(h)\n\tfmt.Println(\"connection error: \", err)\n\n\tcontent, err := QueryPosts(c, 2, 5)\n\n\tfmt.Println(\"content: \", content)\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\thowmany, err := HowManyPosts(c)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tfmt.Println(\"how many: \", howmany)\n}"} {"input": "package crypto\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"io\"\n\t\"time\"\n)\n\n\n\n\nfunc GenerateRandomBytes(n int) []byte {\n\tb := make([]byte, n)\n\tif _, err := io.ReadFull(rand.Reader, b); err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}\n\n\nfunc Timestamp() int64 {\n\treturn time.Now().UTC().Unix()\n}\n\n\nfunc Base64Encode(value []byte) []byte {\n\tenc := make([]byte, base64.RawURLEncoding.EncodedLen(len(value)))\n\tbase64.RawURLEncoding.Encode(enc, value)\n\treturn enc\n}\n\n\n\n\nfunc Base64Decode(value []byte) ([]byte, error) ", "output": "{\n\tdec := make([]byte, base64.RawURLEncoding.DecodedLen(len(value)))\n\tb, err := base64.RawURLEncoding.Decode(dec, value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dec[:b], nil\n}"} {"input": "package transport \n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\n\n\ntype MockReporter struct {\n\twgMetricsProcessed sync.WaitGroup\n}\n\nvar _ Reporter = (*MockReporter)(nil)\n\n\nfunc NewMockReporter(expectedOnMetricsProcessedCalls int) *MockReporter {\n\tm := MockReporter{}\n\tm.wgMetricsProcessed.Add(expectedOnMetricsProcessedCalls)\n\treturn &m\n}\n\nfunc (m *MockReporter) OnDataReceived(ctx context.Context) context.Context {\n\treturn ctx\n}\n\nfunc (m *MockReporter) OnTranslationError(ctx context.Context, err error) {\n}\n\n\n\nfunc (m *MockReporter) OnDebugf(template string, args ...interface{}) {\n}\n\n\n\nfunc (m *MockReporter) WaitAllOnMetricsProcessedCalls() {\n\tm.wgMetricsProcessed.Wait()\n}\n\nfunc (m *MockReporter) OnMetricsProcessed(ctx context.Context, numReceivedMetricPoints int, err error) ", "output": "{\n\tm.wgMetricsProcessed.Done()\n}"} {"input": "package cli\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/antham/goller/v2/dsl\"\n\t\"github.com/antham/goller/v2/sorter\"\n\t\"gopkg.in/alecthomas/kingpin.v2\"\n)\n\nvar sortersGlobal *sorter.Sorters\n\n\ntype Sorters struct {\n\tsorters *sorter.Sorters\n}\n\n\nfunc (s *Sorters) Init() {\n\tsortersGlobal = sorter.NewSorters()\n}\n\n\nfunc (s *Sorters) Set(value string) error {\n\tparser := dsl.NewParser(bytes.NewBufferString(value))\n\n\tstmts, err := parser.ParsePositionsAndFunctions()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t(*s).sorters = sortersGlobal\n\n\tfor _, stmt := range *stmts {\n\t\t(*s).sorters.Append(stmt.Position, stmt.Functions[0].Name, stmt.Functions[0].Args)\n\t}\n\n\treturn nil\n}\n\n\nfunc (s *Sorters) ValidatePositions(positions *[]int) error {\n\tif s.sorters == nil {\n\t\treturn nil\n\t}\n\n\tfor _, sorter := range *s.sorters {\n\t\tpositionMatch := false\n\n\t\tfor _, position := range *positions {\n\t\t\tif sorter.HasPosition(position) {\n\t\t\t\tpositionMatch = true\n\t\t\t}\n\t\t}\n\n\t\tif !positionMatch {\n\t\t\treturn fmt.Errorf(\"Sort is wrong : position %d doesn't exist\", sorter.GetPosition())\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\nfunc (s *Sorters) Get() *sorter.Sorters {\n\treturn s.sorters\n}\n\n\nfunc (s *Sorters) String() string {\n\treturn \"\"\n}\n\n\n\n\nfunc SortersWrapper(s kingpin.Settings) (target *Sorters) ", "output": "{\n\ttarget = &Sorters{}\n\ttarget.Init()\n\ts.SetValue(target)\n\treturn\n}"} {"input": "package tmpl\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\t\"net/http\"\n)\n\n\ntype Page struct {\n\tTitle string\n\tBackLink string\n}\n\n\ntype Template struct {\n\ttemplates map[string]*template.Template\n\ttemplateData map[string]map[string]interface{}\n\ttemplateFilepath string\n}\n\n\n\n\n\n\nfunc (self *Template) AddTemplate(name string, templates ...string) {\n\tif len(templates) > 0 {\n\t\tfor i := 0; i < len(templates); i++ {\n\t\t\ttemplates[i] = self.templateFilepath + \"templates/\" + templates[i] + \".tpl\"\n\t\t}\n\t\tself.templates[name] = template.Must(template.ParseFiles(templates...))\n\t}\n\n\tself.templateData[name] = make(map[string]interface{})\n}\n\n\nfunc (self *Template) AddDataToTemplate(template, data_id string, data interface{}) error {\n\t_, ok := self.templateData[template]\n\tif !ok {\n\t\treturn fmt.Errorf(\"There is no template named '%s' registered.\", template)\n\t}\n\n\tself.templateData[template][data_id] = data\n\n\treturn nil\n}\n\n\n\n\n\nfunc (self *Template) RenderPage(w http.ResponseWriter, tmpl string, p *Page) {\n\tself.AddDataToTemplate(tmpl, \"Page\", p)\n\n\terr := self.templates[tmpl].Execute(w, self.templateData[tmpl])\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\nfunc New(templateFilepath string) *Template ", "output": "{\n\treturn &Template{\n\t\ttemplateFilepath: templateFilepath,\n\t\ttemplates: make(map[string]*template.Template),\n\t\ttemplateData: make(map[string]map[string]interface{}),\n\t}\n}"} {"input": "package vhosts\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n\t\"sync\"\n)\n\ntype VirtualHosts struct {\n\tvhosts map[string]http.Handler\n\tmu sync.RWMutex\n}\n\nfunc NewVirtualHosts(vhosts map[string]http.Handler) *VirtualHosts {\n\tv := &VirtualHosts{}\n\tfor hosts, h := range vhosts {\n\t\tfor _, host := range strings.Split(hosts, \" \") {\n\t\t\tif host != \"\" {\n\t\t\t\tv.HandleHost(h, host)\n\t\t\t}\n\t\t}\n\t}\n\treturn v\n}\n\nfunc (v *VirtualHosts) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tv.mu.RLock()\n\tdefer v.mu.RUnlock()\n\tif v.vhosts != nil {\n\t\tif handler, ok := v.vhosts[r.Host]; ok && handler != nil {\n\t\t\thandler.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t}\n\thttp.NotFound(w, r)\n}\n\n\n\nfunc (v *VirtualHosts) HandleHost(handler http.Handler, hosts ...string) ", "output": "{\n\tv.mu.Lock()\n\tdefer v.mu.Unlock()\n\tif v.vhosts == nil {\n\t\tv.vhosts = make(map[string]http.Handler)\n\t}\n\tfor _, host := range hosts {\n\t\tfor _, h := range strings.Split(host, \" \") {\n\t\t\tif h = strings.TrimSpace(h); h != \"\" {\n\t\t\t\tv.vhosts[h] = handler\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/service\"\n\t\"golang.org/x/sys/windows/svc\"\n)\n\n\n\nfunc runService(params service.CollectorSettings) error {\n\tif err := svc.Run(\"\", service.NewWindowsService(params)); err != nil {\n\t\treturn fmt.Errorf(\"failed to start service: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc run(params service.CollectorSettings) error ", "output": "{\n\tisInteractive, err := svc.IsAnInteractiveSession()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to determine if we are running in an interactive session: %w\", err)\n\t}\n\n\tif isInteractive {\n\t\treturn runInteractive(params)\n\t}\n\treturn runService(params)\n}"} {"input": "package db\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n\t\"github.com/jojopoper/horizon/test\"\n)\n\n\n\nfunc TestLedgerState(t *testing.T) ", "output": "{\n\ttest.LoadScenario(\"base\")\n\thorizon := OpenTestDatabase()\n\tdefer horizon.Close()\n\tcore := OpenStellarCoreTestDatabase()\n\tdefer core.Close()\n\n\tConvey(\"db.UpdateLedgerState\", t, func() {\n\t\tSo(horizonLedgerGauge.Value(), ShouldEqual, 0)\n\t\tSo(stellarCoreLedgerGauge.Value(), ShouldEqual, 0)\n\n\t\tUpdateLedgerState(test.Context(), SqlQuery{horizon}, SqlQuery{core})\n\n\t\tSo(horizonLedgerGauge.Value(), ShouldEqual, 3)\n\t\tSo(stellarCoreLedgerGauge.Value(), ShouldEqual, 3)\n\t})\n}"} {"input": "package streaming\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/dahernan/goreddit/api\"\n)\n\n\n\n\nfunc TestBasicStreamming(t *testing.T) ", "output": "{\n\n\tconsumerKey := os.Getenv(\"CONSUMER_KEY\")\n\tsecretKey := os.Getenv(\"SECRET_KEY\")\n\n\treddit := api.NewReddit(&http.Client{}, \"go reddit test\", consumerKey, secretKey)\n\n\tv := url.Values{}\n\tv.Set(\"limit\", \"5\")\n\tstream := NewRedditStream(reddit.Hot, \"trailers\", v)\n\n\titems := stream.Stream()\n\n\ti := 0\n\tfor it := range items {\n\t\ti++\n\t\tfmt.Println(\"New Item: \", i, it)\n\t}\n\n}"} {"input": "package lifecycle\n\nimport (\n\t\"encoding/xml\"\n)\n\n\ntype NoncurrentVersionExpiration struct {\n\tXMLName xml.Name `xml:\"NoncurrentVersionExpiration\"`\n\tNoncurrentDays ExpirationDays `xml:\"NoncurrentDays,omitempty\"`\n}\n\n\ntype NoncurrentVersionTransition struct {\n\tNoncurrentDays ExpirationDays `xml:\"NoncurrentDays\"`\n\tStorageClass string `xml:\"StorageClass\"`\n}\n\nvar (\n\terrNoncurrentVersionTransitionUnsupported = Errorf(\"Specifying is not supported\")\n)\n\n\nfunc (n NoncurrentVersionExpiration) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tif n.IsDaysNull() {\n\t\treturn nil\n\t}\n\ttype noncurrentVersionExpirationWrapper NoncurrentVersionExpiration\n\treturn e.EncodeElement(noncurrentVersionExpirationWrapper(n), start)\n}\n\n\nfunc (n NoncurrentVersionExpiration) IsDaysNull() bool {\n\treturn n.NoncurrentDays == ExpirationDays(0)\n}\n\n\n\n\n\n\n\n\nfunc (n NoncurrentVersionTransition) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tif n.NoncurrentDays == ExpirationDays(0) {\n\t\treturn nil\n\t}\n\treturn e.EncodeElement(&n, start)\n}\n\nfunc (n NoncurrentVersionTransition) UnmarshalXML(d *xml.Decoder, startElement xml.StartElement) error ", "output": "{\n\treturn errNoncurrentVersionTransitionUnsupported\n}"} {"input": "package main\n\n\ntype seriesType int\n\nconst (\n\trouterRequest seriesType = iota\n\trouterEvent\n\tdynoMem\n\tdynoLoad\n\tdynoEvents\n\tnumSeries\n)\n\nvar (\n\tseriesColumns = [][]string{\n\t\t[]string{\"time\", \"status\", \"service\"}, \n\t\t[]string{\"time\", \"code\"}, \n\t\t[]string{\"time\", \"source\", \"memory_cache\", \"memory_pgpgin\", \"memory_pgpgout\", \"memory_rss\", \"memory_swap\", \"memory_total\", \"dynoType\"}, \n\t\t[]string{\"time\", \"source\", \"load_avg_1m\", \"load_avg_5m\", \"load_avg_15m\", \"dynoType\"}, \n\t\t[]string{\"time\", \"what\", \"type\", \"code\", \"message\", \"dynoType\"}, \n\t}\n\n\tseriesNames = []string{\"router\", \"events.router\", \"dyno.mem\", \"dyno.load\", \"events.dyno\"}\n)\n\n\n\nfunc (st seriesType) Columns() []string {\n\treturn seriesColumns[st]\n}\n\n\ntype point struct {\n\tToken string\n\tType seriesType\n\tPoints []interface{}\n}\n\nfunc (p point) SeriesName() string {\n\treturn p.Type.Name() + \".\" + p.Token\n}\n\nfunc (st seriesType) Name() string ", "output": "{\n\treturn seriesNames[st]\n}"} {"input": "package crypto\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"io\"\n\t\"time\"\n)\n\n\n\n\nfunc GenerateRandomBytes(n int) []byte {\n\tb := make([]byte, n)\n\tif _, err := io.ReadFull(rand.Reader, b); err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}\n\n\n\n\n\nfunc Base64Encode(value []byte) []byte {\n\tenc := make([]byte, base64.RawURLEncoding.EncodedLen(len(value)))\n\tbase64.RawURLEncoding.Encode(enc, value)\n\treturn enc\n}\n\n\nfunc Base64Decode(value []byte) ([]byte, error) {\n\tdec := make([]byte, base64.RawURLEncoding.DecodedLen(len(value)))\n\tb, err := base64.RawURLEncoding.Decode(dec, value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dec[:b], nil\n}\n\nfunc Timestamp() int64 ", "output": "{\n\treturn time.Now().UTC().Unix()\n}"} {"input": "package types\n\nimport (\n\t\"encoding/binary\"\n\n\t\"golang.org/x/crypto/blake2s\"\n)\n\n\ntype Transaction struct {\n\tHash Hash\n\tTransfers []*Transfer\n\tFees []*Fee\n\tData []byte\n\tNonce uint64\n\tSignatures [][]byte\n}\n\n\n\n\nfunc (tx *Transaction) GetHash() Hash ", "output": "{\n\tvar hash Hash\n\tbuf := make([]byte, 8)\n\th, _ := blake2s.New256(nil)\n\tfor _, transfer := range tx.Transfers {\n\t\t_, _ = h.Write(transfer.From)\n\t\t_, _ = h.Write(transfer.To)\n\t\tbinary.LittleEndian.PutUint64(buf, transfer.Amount)\n\t\t_, _ = h.Write(buf)\n\t}\n\tfor _, fee := range tx.Fees {\n\t\t_, _ = h.Write(fee.From)\n\t\tbinary.LittleEndian.PutUint64(buf, fee.Amount)\n\t\t_, _ = h.Write(buf)\n\t}\n\t_, _ = h.Write(tx.Data)\n\tbinary.LittleEndian.PutUint64(buf, tx.Nonce)\n\t_, _ = h.Write(buf)\n\ttmp := h.Sum(nil)\n\tcopy(hash[:], tmp)\n\treturn hash\n}"} {"input": "package dax\n\n\ntype Grapher interface {\n\tGetParent() Grapher\n\tAddChild(child Grapher)\n\tGetChildren() []Grapher\n}\n\ntype nodeStack struct {\n\tnodes []Grapher\n}\n\nfunc (s *nodeStack) Init() {\n\ts.nodes = make([]Grapher, 0, 16)\n}\n\nfunc (s *nodeStack) Empty() bool {\n\treturn len(s.nodes) == 0\n}\n\nfunc (s *nodeStack) Push(n Grapher) {\n\ts.nodes = append(s.nodes, n)\n}\n\nfunc (s *nodeStack) Pop() Grapher {\n\ti := len(s.nodes) - 1\n\tn := s.nodes[i]\n\ts.nodes[i] = nil\n\ts.nodes = s.nodes[:i]\n\treturn n\n}\n\ntype SceneGraph struct {\n\tNode\n}\n\nfunc NewSceneGraph() *SceneGraph {\n\tsg := new(SceneGraph)\n\tsg.Init()\n\treturn sg\n}\n\n\n\nfunc (sg *SceneGraph) updateWorldTransform() {\n\tsg.Node.updateWorldTransform(false)\n}\n\nfunc (sg *SceneGraph) Update(time float64) {\n\tsg.updateWorldTransform()\n}\n\n\nfunc (sg *SceneGraph) Traverse() <-chan Grapher {\n\tch := make(chan Grapher)\n\n\tgo func() {\n\t\tvar stack nodeStack\n\n\t\tstack.Init()\n\t\tstack.Push(sg)\n\n\t\tfor !stack.Empty() {\n\t\t\tn := stack.Pop()\n\t\t\tch <- n\n\t\t\tchildren := n.GetChildren()\n\t\t\tfor i := len(children) - 1; i >= 0; i-- {\n\t\t\t\tstack.Push(children[i])\n\t\t\t}\n\t\t}\n\t\tclose(ch)\n\t}()\n\n\treturn ch\n}\n\nfunc (sg *SceneGraph) Draw(fb Framebuffer) {\n\tfb.render().drawSceneGraph(fb, sg)\n}\n\nfunc (sg *SceneGraph) Init() ", "output": "{\n\tsg.Node.Init()\n}"} {"input": "package markdownutils\n\nimport (\n\t\"strings\"\n\t\"unicode\"\n)\n\n\n\n\n\nfunc CreateGitLabAnchor(text string) string {\n\tvar anchorName []rune\n\tvar lastWasDash = false\n\n\tfor _, r := range []rune(strings.TrimSpace(text)) {\n\t\tswitch {\n\t\tcase r == ' ' || r == '-':\n\t\t\tif !lastWasDash {\n\t\t\t\tanchorName = append(anchorName, '-')\n\t\t\t\tlastWasDash = true\n\t\t\t}\n\t\tcase unicode.IsLetter(r) || unicode.IsNumber(r):\n\t\t\tanchorName = append(anchorName, unicode.ToLower(r))\n\t\t\tlastWasDash = false\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn string(anchorName)\n}\n\nfunc CreateGitHubAnchor(text string) string ", "output": "{\n\tvar anchorName []rune\n\n\tfor _, r := range []rune(strings.TrimSpace(text)) {\n\t\tswitch {\n\t\tcase r == ' ' || r == '-':\n\t\t\tanchorName = append(anchorName, '-')\n\t\tcase unicode.IsLetter(r) || unicode.IsNumber(r):\n\t\t\tanchorName = append(anchorName, unicode.ToLower(r))\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn string(anchorName)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\nfunc main() {\n\tvalues := []int{1, 2, 3, 4, 5, 12, 30, 35, 46, 84}\n\tfmt.Println(ternarySearch(values, 0, len(values)-1, 5))\n\tfmt.Println(ternarySearch(values, 0, len(values)-1, 7))\n}\n\nfunc ternarySearch(data []int, left int, right int, value int) int ", "output": "{\n\tif right >= left {\n\t\tmid1 := left + (right-left)/3\n\t\tmid2 := right - (right-left)/3\n\n\t\tif data[mid1] == value {\n\t\t\treturn mid1\n\t\t}\n\t\tif data[mid2] == value {\n\t\t\treturn mid2\n\t\t}\n\t\tif value < data[mid1] {\n\t\t\treturn ternarySearch(data, left, mid1-1, value)\n\t\t} else if value > data[mid2] {\n\t\t\treturn ternarySearch(data, mid2+1, right, value)\n\t\t} else {\n\t\t\treturn ternarySearch(data, mid1+1, mid2-1, value)\n\t\t}\n\t}\n\treturn -1\n}"} {"input": "package sliceset\n\nimport (\n\t\"sort\"\n\n\t\"github.com/xtgo/set\"\n)\n\ntype Set []int\n\nfunc (s Set) Len() int { return len(s) }\nfunc (s Set) Less(i, j int) bool { return s[i] < s[j] }\nfunc (s Set) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s Set) Copy() Set { return append(Set(nil), s...) }\n\n\nfunc (s Set) Inter(t Set) Set { return s.Do(set.Inter, t) }\nfunc (s Set) Diff(t Set) Set { return s.Do(set.Diff, t) }\nfunc (s Set) SymDiff(t Set) Set { return s.Do(set.SymDiff, t) }\nfunc (s Set) IsSub(t Set) bool { return s.DoBool(set.IsSub, t) }\nfunc (s Set) IsSuper(t Set) bool { return s.DoBool(set.IsSuper, t) }\nfunc (s Set) IsInter(t Set) bool { return s.DoBool(set.IsInter, t) }\nfunc (s Set) IsEqual(t Set) bool { return s.DoBool(set.IsEqual, t) }\n\nfunc (s Set) Uniq() Set {\n\tn := set.Uniq(s)\n\treturn s[:n]\n}\n\nfunc (s Set) Do(op set.Op, t Set) Set {\n\tdata := append(s, t...)\n\tn := op(data, len(s))\n\treturn data[:n]\n}\n\ntype BoolOp func(sort.Interface, int) bool\n\nfunc (s Set) DoBool(op BoolOp, t Set) bool {\n\tdata := append(s, t...)\n\treturn op(data, len(s))\n}\n\nfunc (s Set) Union(t Set) Set ", "output": "{ return s.Do(set.Union, t) }"} {"input": "package comparators\n\n\ntype UInt8Comparator struct {\n}\n\n\n\n\n\n\n\n\nfunc (comparator *UInt8Comparator) Compare(a, b interface{}) int {\n\taAsserted := a.(uint8)\n\tbAsserted := b.(uint8)\n\tswitch {\n\tcase aAsserted > bAsserted:\n\t\treturn 1\n\tcase aAsserted < bAsserted:\n\t\treturn -1\n\tdefault:\n\t\treturn 0\n\t}\n}\n\nfunc NewUInt8Comparator() *UInt8Comparator ", "output": "{\n\treturn &UInt8Comparator{}\n}"} {"input": "package devops\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype AutomatedDeployStageRollbackPolicy struct {\n}\n\nfunc (m AutomatedDeployStageRollbackPolicy) String() string {\n\treturn common.PointerString(m)\n}\n\n\n\n\nfunc (m AutomatedDeployStageRollbackPolicy) MarshalJSON() (buff []byte, e error) ", "output": "{\n\ttype MarshalTypeAutomatedDeployStageRollbackPolicy AutomatedDeployStageRollbackPolicy\n\ts := struct {\n\t\tDiscriminatorParam string `json:\"policyType\"`\n\t\tMarshalTypeAutomatedDeployStageRollbackPolicy\n\t}{\n\t\t\"AUTOMATED_STAGE_ROLLBACK_POLICY\",\n\t\t(MarshalTypeAutomatedDeployStageRollbackPolicy)(m),\n\t}\n\n\treturn json.Marshal(&s)\n}"} {"input": "package sdl\n\n\nimport \"C\"\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"unsafe\"\n)\n\nconst SamplingRate = 11025\n\n\n\n\nfunc BufferAudio(sound []int8) {\n\tif len(sound) == 0 {\n\t\treturn\n\t}\n\tmutex.Lock()\n\tC.play((*C.Uint8)(unsafe.Pointer(&sound[0])), C.int(len(sound)))\n\tmutex.Unlock()\n}\n\nfunc Play(input io.Reader) error {\n\tbuf, err := ioutil.ReadAll(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmutex.Lock()\n\tC.play((*C.Uint8)(unsafe.Pointer(&buf[0])), C.int(len(buf)))\n\tmutex.Unlock()\n\treturn nil\n}\n\nfunc ClearAudioBuffer() {\n\tmutex.Lock()\n\tC.stop()\n\tmutex.Unlock()\n}\n\nfunc initAudio() ", "output": "{\n\tvar spec C.SDL_AudioSpec\n\tspec.freq = C.int(SamplingRate)\n\tspec.format = C.AUDIO_S8\n\tspec.channels = 1\n\tspec.samples = 512\n\tspec.userdata = nil\n\tC.openAudio(&spec)\n}"} {"input": "package loki_test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/andviro/goldie\"\n\t\"github.com/andviro/grayproxy/pkg/loki\"\n\t\"github.com/prometheus/common/model\"\n)\n\ntype testHandler bytes.Buffer\n\n\n\nfunc TestSender_Send(t *testing.T) {\n\tbuf := new(bytes.Buffer)\n\ts := loki.Sender{Handler: (*testHandler)(buf), Job: \"test\"}\n\terr := s.Send([]byte(`{\n\t \"version\": \"1.1\",\n\t \"host\": \"example.org\",\n\t \"short_message\": \"A short message that helps you identify what is going on\",\n\t \"full_message\": \"Backtrace here\\n\\nmore stuff\",\n\t \"timestamp\": 1385053862.3072,\n\t \"level\": 1,\n\t \"_user_id\": 9001,\n\t \"_some_info\": \"foo\",\n\t \"_some_env_var\": \"bar\"\n\t}`))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tgoldie.Assert(t, \"sender-send\", buf.Bytes())\n}\n\nfunc (t *testHandler) Handle(ls model.LabelSet, ts time.Time, s string) error ", "output": "{\n\tbuf := (*bytes.Buffer)(t)\n\tjd, _ := json.Marshal(ts)\n\tfmt.Fprintf(buf, \"%s\\n\", jd)\n\tjd, _ = json.MarshalIndent(ls, \"\", \"\\t\")\n\tfmt.Fprintf(buf, \"%s\\n\", jd)\n\tfmt.Fprintf(buf, \"%s\\n\", s)\n\treturn nil\n}"} {"input": "package routing\n\nimport \"net/http\"\n\n\nfunc Method(method string, handler http.Handler) Matcher {\n\treturn func(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\t\tif req.Method == method {\n\t\t\thandler.ServeHTTP(resp, req)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}\n\n\nfunc GET(handler http.Handler) Matcher {\n\treturn Method(\"GET\", handler)\n}\n\n\n\n\n\nfunc POST(handler http.Handler) Matcher {\n\treturn Method(\"POST\", handler)\n}\n\n\nfunc POSTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn POST(http.HandlerFunc(handler))\n}\n\n\nfunc PUT(handler http.Handler) Matcher {\n\treturn Method(\"PUT\", handler)\n}\n\n\nfunc PUTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PUT(http.HandlerFunc(handler))\n}\n\n\nfunc PATCH(handler http.Handler) Matcher {\n\treturn Method(\"PATCH\", handler)\n}\n\n\nfunc PATCHFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PATCH(http.HandlerFunc(handler))\n}\n\n\nfunc DELETE(handler http.Handler) Matcher {\n\treturn Method(\"DELETE\", handler)\n}\n\n\nfunc DELETEFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn DELETE(http.HandlerFunc(handler))\n}\n\n\n\nfunc MethodNotAllowed(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\tresp.WriteHeader(405)\n\treturn true\n}\n\nfunc GETFunc(handler func(http.ResponseWriter, *http.Request)) Matcher ", "output": "{\n\treturn GET(http.HandlerFunc(handler))\n}"} {"input": "package writer\n\nimport (\n\t\"os\"\n\t\"syscall\"\n\n\trnode \"a4.io/blobstash/pkg/filetree/filetreeutil/node\"\n)\n\n\n\nfunc setMtime(m *rnode.RawNode, fstat os.FileInfo) ", "output": "{\n\tif stat, ok := fstat.Sys().(*syscall.Stat_t); ok {\n\t\tm.ChangeTime = int64(stat.Ctim.Sec)\n\t}\n}"} {"input": "package allowanypassword\n\nimport (\n\t\"strings\"\n\n\t\"github.com/golang/glog\"\n\n\tauthapi \"github.com/openshift/origin/pkg/auth/api\"\n\t\"github.com/openshift/origin/pkg/auth/authenticator\"\n\t\"k8s.io/apiserver/pkg/authentication/user\"\n)\n\n\ntype alwaysAcceptPasswordAuthenticator struct {\n\tproviderName string\n\tidentityMapper authapi.UserIdentityMapper\n}\n\n\n\n\n\nfunc (a alwaysAcceptPasswordAuthenticator) AuthenticatePassword(username, password string) (user.Info, bool, error) {\n\tusername = strings.TrimSpace(username)\n\n\tif username == \"\" || password == \"\" {\n\t\treturn nil, false, nil\n\t}\n\n\tidentity := authapi.NewDefaultUserIdentityInfo(a.providerName, username)\n\tuser, err := a.identityMapper.UserFor(identity)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error creating or updating mapping for: %#v due to %v\", identity, err)\n\t\treturn nil, false, err\n\t}\n\tglog.V(4).Infof(\"Got userIdentityMapping: %#v\", user)\n\n\treturn user, true, nil\n}\n\nfunc New(providerName string, identityMapper authapi.UserIdentityMapper) authenticator.Password ", "output": "{\n\treturn &alwaysAcceptPasswordAuthenticator{providerName, identityMapper}\n}"} {"input": "package models\n\nimport (\n\t\"time\"\n\n\t\"github.com/CodisLabs/codis/pkg/models/etcd\"\n\t\"github.com/CodisLabs/codis/pkg/models/fs\"\n\t\"github.com/CodisLabs/codis/pkg/models/zk\"\n\t\"github.com/CodisLabs/codis/pkg/utils/errors\"\n)\n\ntype Client interface {\n\tCreate(path string, data []byte) error\n\tUpdate(path string, data []byte) error\n\tDelete(path string) error\n\n\tRead(path string, must bool) ([]byte, error)\n\tList(path string, must bool) ([]string, error)\n\n\tClose() error\n\n\tWatchInOrder(path string) (<-chan struct{}, []string, error)\n\n\tCreateEphemeral(path string, data []byte) (<-chan struct{}, error)\n\tCreateEphemeralInOrder(path string, data []byte) (<-chan struct{}, string, error)\n}\n\n\n\n\nfunc NewClient(coordinator string, addrlist string, timeout time.Duration) (Client, error) ", "output": "{\n\tswitch coordinator {\n\tcase \"zk\", \"zookeeper\":\n\t\treturn zkclient.New(addrlist, timeout)\n\tcase \"etcd\":\n\t\treturn etcdclient.New(addrlist, timeout)\n\tcase \"fs\", \"filesystem\":\n\t\treturn fsclient.New(addrlist)\n\t}\n\treturn nil, errors.Errorf(\"invalid coordinator name = %s\", coordinator)\n}"} {"input": "package redis_test\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/go-redis/redis\"\n\tredistrace \"gopkg.in/DataDog/dd-trace-go.v1/contrib/go-redis/redis\"\n\t\"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext\"\n\t\"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer\"\n)\n\n\n\nfunc Example() {\n\topts := &redis.Options{Addr: \"127.0.0.1\", Password: \"\", DB: 0}\n\tc := redistrace.NewClient(opts)\n\n\tc.Set(\"test_key\", \"test_value\", 0)\n\n\troot, ctx := tracer.StartSpanFromContext(context.Background(), \"parent.request\",\n\t\ttracer.SpanType(ext.SpanTypeRedis),\n\t\ttracer.ServiceName(\"web\"),\n\t\ttracer.ResourceName(\"/home\"),\n\t)\n\n\tc = c.WithContext(ctx)\n\n\tc.Set(\"food\", \"cheese\", 0)\n\troot.Finish()\n}\n\n\n\n\n\nfunc Example_pipeliner() ", "output": "{\n\topts := &redis.Options{Addr: \"127.0.0.1\", Password: \"\", DB: 0}\n\tc := redistrace.NewClient(opts, redistrace.WithServiceName(\"my-redis-service\"))\n\n\tpipe := c.Pipeline()\n\n\tpipe.Incr(\"pipeline_counter\")\n\tpipe.Expire(\"pipeline_counter\", time.Hour)\n\n\tpipe.Exec()\n}"} {"input": "package logging_test\n\nimport (\n\t\"cloud.google.com/go/logging/apiv2\"\n\t\"golang.org/x/net/context\"\n\tloggingpb \"google.golang.org/genproto/googleapis/logging/v2\"\n)\n\nfunc ExampleNewConfigClient() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\nfunc ExampleConfigClient_ListSinks() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.ListSinksRequest{\n\t}\n\tit := c.ListSinks(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t_ = resp\n\t}\n}\n\nfunc ExampleConfigClient_GetSink() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.GetSinkRequest{\n\t}\n\tresp, err := c.GetSink(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\n\n\nfunc ExampleConfigClient_UpdateSink() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.UpdateSinkRequest{\n\t}\n\tresp, err := c.UpdateSink(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleConfigClient_DeleteSink() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.DeleteSinkRequest{\n\t}\n\terr = c.DeleteSink(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleConfigClient_CreateSink() ", "output": "{\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.CreateSinkRequest{\n\t}\n\tresp, err := c.CreateSink(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/utils\"\n\nfunc init() {\n\tc := &CmdGetCacheAge{\n\t\tname: \"cache_age\",\n\t\trpcMethod: \"ApierV1.GetCachedItemAge\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetCacheAge struct {\n\tname string\n\trpcMethod string\n\trpcParams *StringWrapper\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetCacheAge) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdGetCacheAge) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\n\n\nfunc (self *CmdGetCacheAge) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetCacheAge) RpcResult() interface{} {\n\treturn &utils.CachedItemAge{}\n}\n\nfunc (self *CmdGetCacheAge) RpcParams() interface{} ", "output": "{\n\tif self.rpcParams == nil {\n\t\tself.rpcParams = &StringWrapper{}\n\t}\n\treturn self.rpcParams\n}"} {"input": "package HeatersController\n\nimport (\n\t\"errors\"\n\n\t\"github.com/stianeikeland/go-rpio\"\n)\n\nvar heaters [3]rpio.Pin\n\nfunc init() {\n\trpio.Open()\n\n\theaters[0] = rpio.Pin(26)\n\theaters[1] = rpio.Pin(20)\n\theaters[2] = rpio.Pin(21)\n\n\theaters[0].Output()\n\theaters[1].Output()\n\theaters[2].Output()\n\n\theaters[0].High()\n\theaters[1].High()\n\theaters[2].High()\n}\n\n\n\n\n\nfunc TurnOn(heaterID int) {\n\theaters[heaterID-1].Low()\n}\n\n\nfunc TurnOff(heaterID int) {\n\theaters[heaterID-1].High()\n}\n\n\nfunc GetNumberOfWorkingHeaters() int {\n\tresult := 0\n\tif heaters[0].Read() == rpio.Low {\n\t\tresult++\n\t}\n\n\tif heaters[1].Read() == rpio.Low {\n\t\tresult++\n\t}\n\n\tif heaters[2].Read() == rpio.Low {\n\t\tresult++\n\t}\n\n\treturn result\n}\n\nfunc SetNumberOfWorkingHeaters(num int) error ", "output": "{\n\tif num == 0 {\n\t\theaters[0].High()\n\t\theaters[1].High()\n\t\theaters[2].High()\n\t} else if num == 1 {\n\t\theaters[0].Low()\n\t\theaters[1].High()\n\t\theaters[2].High()\n\t} else if num == 2 {\n\t\theaters[0].Low()\n\t\theaters[1].Low()\n\t\theaters[2].High()\n\t} else if num == 3 {\n\t\theaters[0].Low()\n\t\theaters[1].Low()\n\t\theaters[2].Low()\n\t} else {\n\t\treturn errors.New(\"The num argument should be between 0 and 3 inclusive\")\n\t}\n\n\treturn nil\n}"} {"input": "package lists\n\n\n\n\nimport (\n\t\"net/url\"\n\n\t\"github.com/kawaken/go-rtm/methods\"\n)\n\n\n\n\nfunc Delete(timeline string, listID string) *methods.Method ", "output": "{\n\tname := \"rtm.lists.delete\"\n\n\tp := url.Values{}\n\tp.Add(\"method\", name)\n\tp.Add(\"timeline\", timeline)\n\tp.Add(\"list_id\", listID)\n\treturn &methods.Method{Name: name, Params: p}\n}"} {"input": "package mdr\n\n\nfunc AbsF64(a float64) float64 {\n\tif a < 0.0 {\n\t\treturn -a\n\t}\n\treturn a\n}\n\n\n\n\n\nfunc RangeLoHiF64Slice(v []float64) (lo, hi float64) {\n\tvlen := len(v)\n\tif vlen <= 0 {\n\t\treturn\n\t}\n\tlo, hi = v[0], v[0]\n\tfor i := 1; i < vlen; i++ {\n\t\tif v[i] < lo {\n\t\t\tlo = v[i]\n\t\t}\n\t\tif v[i] > hi {\n\t\t\thi = v[i]\n\t\t}\n\t}\n\treturn lo, hi\n}\n\n\nfunc ForceRangeF64(a, b, c float64) float64 {\n\tif a > c { \n\t\ta, c = c, a\n\t}\n\tif b < a {\n\t\treturn a\n\t}\n\tif b > c {\n\t\treturn c\n\t}\n\treturn b\n}\n\nfunc InRangeF64(a, b, c float64) bool ", "output": "{\n\tif a > c { \n\t\ta, c = c, a\n\t}\n\tif b < a {\n\t\treturn false\n\t}\n\tif b > c {\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package jsonstream\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\n\n\nfunc getAsMap(data interface{}) (fields map[string]interface{}, err error) ", "output": "{\n\tswitch value := data.(type) {\n\tcase map[string]interface{}:\n\t\tfields = value\n\tdefault:\n\t\terr = fmt.Errorf(\"Unexpected data type '%s', expected 'map[string]interface{}'.\", reflect.TypeOf(value))\n\t}\n\treturn fields, err\n}"} {"input": "package pydioadmin\n\nimport (\n\t\"github.com/mholt/caddy\"\n\t\"github.com/mholt/caddy/caddyhttp/httpserver\"\n)\n\n\n\n\nfunc setup(c *caddy.Controller) error {\n\n\tcfg := httpserver.GetConfig(c)\n\n\trules, err := parse(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcfg.AddMiddleware(func(next httpserver.Handler) httpserver.Handler {\n\t\treturn &Handler{\n\t\t\tNext: next,\n\t\t\tRules: rules,\n\t\t}\n\t})\n\n\treturn nil\n}\n\nfunc parse(c *caddy.Controller) ([]Rule, error) {\n\n\tvar rules []Rule\n\n\tfor c.Next() {\n\t\tvar rule Rule\n\n\t\targs := c.RemainingArgs()\n\n\t\tswitch len(args) {\n\t\tcase 0:\n\t\t\treturn rules, c.ArgErr()\n\t\tcase 1:\n\t\t\trule.Path = args[0]\n\n\t\t\trules = append(rules, rule)\n\t\t}\n\t}\n\n\treturn rules, nil\n}\n\nfunc init() ", "output": "{\n\tcaddy.RegisterPlugin(\"pydioadmin\", caddy.Plugin{\n\t\tServerType: \"http\",\n\t\tAction: setup,\n\t})\n}"} {"input": "package logger\n\n\n\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"strings\"\n)\n\ntype (\n\tLog struct {\n\t\tlogger *log.Logger\n\t\tpositiveList map[string]bool\n\t\tprintAll bool\n\t\tcolor string\n\t}\n)\n\n\nfunc New(w io.Writer, color string, packages string) *Log {\n\tl := &Log{\n\t\tcolor: color,\n\t\tlogger: log.New(w, \"\", log.Ldate|log.Lmicroseconds),\n\t\tpositiveList: make(map[string]bool),\n\t\tprintAll: false,\n\t}\n\n\tpositives := strings.Split(packages, \",\")\n\tfor _, positive := range positives {\n\t\tif positive == \"*\" {\n\t\t\tl.printAll = true\n\t\t} else {\n\t\t\tl.positiveList[positive] = true\n\t\t}\n\t}\n\n\treturn l\n}\n\n\nfunc (l *Log) Log(pkg string, format string, args ...interface{}) {\n\t_, print := l.positiveList[pkg]\n\tif print || l.printAll {\n\t\tl.Printf(pkg, l.color+format+Reset, args...)\n\t}\n}\n\n\nfunc (l *Log) Logger(pkg string) *log.Logger {\n\t_, print := l.positiveList[pkg]\n\tif print || l.printAll {\n\t\treturn log.New(l, Purple+pkg+\" \"+l.color, 0)\n\t}\n\n\treturn log.New(ioutil.Discard, \"\", 0)\n}\n\n\n\n\n\nfunc (l *Log) Write(p []byte) (n int, err error) {\n\tstr := strings.TrimSpace(string(p))\n\n\tl.logger.Printf(\"%s\"+Reset+\"\\n\", str)\n\n\treturn len(p), nil\n}\n\nfunc (l *Log) Printf(pkg string, format string, args ...interface{}) ", "output": "{\n\tl.logger.Printf(Purple+pkg+Reset+\" \"+format+\"\\n\", args...)\n}"} {"input": "package fgae\n\nimport(\n\t\"golang.org/x/net/context\"\n\t\"github.com/skypies/util/gcp/ds\"\n\tfdb \"github.com/skypies/flightdb\"\n)\n\n\ntype FlightIterator ds.Iterator\n\n\n\nfunc (fi *FlightIterator)Iterate(ctx context.Context) bool {\n\tit := (*ds.Iterator)(fi)\n\treturn it.Iterate(ctx)\n}\n\nfunc (fi *FlightIterator)Err() error {\n\tit := (*ds.Iterator)(fi)\n\treturn it.Err()\n}\n\nfunc (fi *FlightIterator)Flight() *fdb.Flight {\n\tblob := fdb.IndexedFlightBlob{}\n\n\tit := (*ds.Iterator)(fi)\n\tkeyer := it.Val(&blob)\n\n\tf, err := blob.ToFlight(keyer.Encode())\n\tif err != nil {\n\t\tit.SetErr(err)\n\t\treturn nil\n\t}\n\n\treturn f\n}\n\nfunc NewFlightIterator(ctx context.Context, p ds.DatastoreProvider, fq *FQuery) *FlightIterator ", "output": "{\n\tit := ds.NewIterator(ctx, p, (*ds.Query)(fq), fdb.IndexedFlightBlob{})\n\treturn (*FlightIterator)(it)\n}"} {"input": "package consul\n\nimport (\n\t\"log\"\n\n\t\"github.com/armon/consul-api\"\n\t\"github.com/hashicorp/terraform/helper/config\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\ntype ResourceProvider struct {\n\tConfig Config\n\tclient *consulapi.Client\n}\n\nfunc (p *ResourceProvider) Validate(c *terraform.ResourceConfig) ([]string, []error) {\n\tv := &config.Validator{\n\t\tOptional: []string{\n\t\t\t\"datacenter\",\n\t\t\t\"address\",\n\t\t},\n\t}\n\treturn v.Validate(c)\n}\n\nfunc (p *ResourceProvider) ValidateResource(\n\tt string, c *terraform.ResourceConfig) ([]string, []error) {\n\treturn resourceMap.Validate(t, c)\n}\n\nfunc (p *ResourceProvider) Configure(c *terraform.ResourceConfig) error {\n\tif _, err := config.Decode(&p.Config, c.Config); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[INFO] Initializing Consul client\")\n\tvar err error\n\tp.client, err = p.Config.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (p *ResourceProvider) Apply(\n\ts *terraform.ResourceState,\n\td *terraform.ResourceDiff) (*terraform.ResourceState, error) {\n\treturn resourceMap.Apply(s, d, p)\n}\n\nfunc (p *ResourceProvider) Diff(\n\ts *terraform.ResourceState,\n\tc *terraform.ResourceConfig) (*terraform.ResourceDiff, error) {\n\treturn resourceMap.Diff(s, c, p)\n}\n\n\n\nfunc (p *ResourceProvider) Resources() []terraform.ResourceType {\n\treturn resourceMap.Resources()\n}\n\nfunc (p *ResourceProvider) Refresh(\n\ts *terraform.ResourceState) (*terraform.ResourceState, error) ", "output": "{\n\treturn resourceMap.Refresh(s, p)\n}"} {"input": "package helper\n\nimport (\n\t\"encoding/base64\"\n\t\"strings\"\n\t\"time\"\n\t\"github.com/insionng/yougam/libraries/flosch/pongo2.v3\"\n)\n\nfunc ConvertToBase64(in string) string {\n\treturn base64.StdEncoding.EncodeToString([]byte(in))\n}\n\nfunc ConvertToBase64ByPongo2(in *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(base64.StdEncoding.EncodeToString([]byte(in.String())))\n}\n\nfunc SplitByPongo2(in *pongo2.Value, splitor *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Split(in.String(), splitor.String()))\n}\n\nfunc MarkdownByPongo2(in *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Markdown(in.String()))\n}\n\nfunc CropwordByPongo2(in *pongo2.Value, start *pongo2.Value, length *pongo2.Value, symbol *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Substr(in.String(), start.Integer(), length.Integer(), symbol.String()))\n}\n\n\n\nfunc File(s string) string {\n\tif len(s) > 0 {\n\t\tif strings.HasPrefix(s, \"http\") || strings.HasPrefix(s, \"/identicon\") {\n\t\t\treturn s\n\t\t} else {\n\t\t\treturn \"/file\" + s\n\t\t}\n\t}\n\treturn s\n}\n\nfunc Unix2TimeByPongo2(in *pongo2.Value, timeLayout *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(time.Unix(int64(in.Integer()), 0).Format(timeLayout.String()))\n}\n\nfunc Cropword(in string, start int, length int, symbol string) string ", "output": "{\n\treturn Substr(in, start, length, symbol)\n}"} {"input": "package handler\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\t\"github.com/goharbor/harbor/src/jobservice/job\"\n\tlibhttp \"github.com/goharbor/harbor/src/lib/http\"\n\t\"github.com/goharbor/harbor/src/pkg/task\"\n)\n\n\nfunc NewJobStatusHandler() http.Handler {\n\treturn &jobStatusHandler{\n\t\thandler: task.HkHandler,\n\t}\n}\n\ntype jobStatusHandler struct {\n\thandler *task.HookHandler\n}\n\n\n\nfunc (j *jobStatusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tdefer r.Body.Close()\n\n\tsc := &job.StatusChange{}\n\tif err := json.NewDecoder(r.Body).Decode(sc); err != nil {\n\t\tlibhttp.SendError(w, err)\n\t\treturn\n\t}\n\tif err := j.handler.Handle(r.Context(), sc); err != nil {\n\t\tlibhttp.SendError(w, err)\n\t\treturn\n\t}\n}"} {"input": "package vm\n\nimport (\n\t\"github.com/rancher/wrangler/pkg/generic\"\n\t\"k8s.io/client-go/rest\"\n)\n\ntype Factory struct {\n\t*generic.Factory\n}\n\n\n\nfunc NewFactoryFromConfig(config *rest.Config) (*Factory, error) {\n\treturn NewFactoryFromConfigWithOptions(config, nil)\n}\n\nfunc NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (*Factory, error) {\n\treturn NewFactoryFromConfigWithOptions(config, &FactoryOptions{\n\t\tNamespace: namespace,\n\t})\n}\n\ntype FactoryOptions = generic.FactoryOptions\n\nfunc NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) {\n\tf, err := generic.NewFactoryFromConfigWithOptions(config, opts)\n\treturn &Factory{\n\t\tFactory: f,\n\t}, err\n}\n\nfunc (c *Factory) Vm() Interface {\n\treturn New(c.ControllerFactory())\n}\n\nfunc NewFactoryFromConfigOrDie(config *rest.Config) *Factory ", "output": "{\n\tf, err := NewFactoryFromConfig(config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}"} {"input": "package cli\n\nimport (\n\t\"os\"\n\t\"fmt\"\n)\n\n\ntype Cmd interface {\n\tKey() string\n\tDescription() string\n\tExecute(args []string) error\n\tPrintUsage()\n}\n\n\n\ntype CmdHandler interface {\n\tRegisterCmd(Cmd)\n\tHandle()\n\tHandleCmd(key string, args []string)\n\tPrintUsage()\n}\n\n\nfunc NewCmdHandler() CmdHandler {\n\th := initCmdHandler()\n\th.RegisterCmd(NewBuildCmd())\n\treturn h\n}\n\n\n\ntype cmdHandler struct {\n\tcmds map[string]Cmd\n}\n\nfunc (h *cmdHandler) RegisterCmd(cmd Cmd) {\n\tkey := cmd.Key()\n\th.cmds[key] = cmd\n}\n\nfunc (h *cmdHandler) Handle() {\n\targs := os.Args\n\tif args == nil || len(args) < 2 {\n\t\th.handleUsageError(\"Insufficient arguments\")\n\t\treturn\n\t} \n\tkey := args[1]\n\tcmdArgs := args[2:]\n\th.HandleCmd(key, cmdArgs)\n}\n\nfunc (h *cmdHandler) PrintUsage() {\n}\n\nfunc (h *cmdHandler) HandleCmd(key string, args []string) {\n\tcmd := h.cmds[key]\n\tif cmd == nil {\n\t\th.handleUsageError(\"Unrecognized command: \" + key)\n\t\treturn\n\t}\n\terr := cmd.Execute(args)\n\tif err != nil {\n\t\th.handleError(err)\n\t}\n}\n\n\nfunc (h *cmdHandler) handleUsageError(message string) {\n\tfmt.Println(message)\n\th.PrintUsage()\n}\n\n\nfunc (h *cmdHandler) handleError(err error) {\n\tfmt.Println(err)\n}\n\nfunc initCmdHandler() *cmdHandler ", "output": "{\n\th := new(cmdHandler)\n\th.cmds = make(map[string]Cmd)\n\treturn h\n}"} {"input": "package gconv_test\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\ntype testStruct struct {\n\tId int\n\tName string\n}\n\nvar ptr = []*testStruct{\n\t{\n\t\tId: 1,\n\t\tName: \"test1\",\n\t},\n\t{\n\t\tId: 2,\n\t\tName: \"test2\",\n\t},\n}\n\n\n\nfunc Benchmark_Reflect_ValueOf(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr)\n\t}\n}\n\nfunc Benchmark_Reflect_ValueOf_Kind(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr).Kind()\n\t}\n}\n\nfunc Benchmark_Reflect_ValueOf_Interface(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr).Interface()\n\t}\n}\n\nfunc Benchmark_Reflect_ValueOf_Len(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr).Len()\n\t}\n}\n\nfunc init() ", "output": "{\n\tfor i := 1; i <= 1000; i++ {\n\t\tptr = append(ptr, &testStruct{\n\t\t\tId: 1,\n\t\t\tName: \"test1\",\n\t\t})\n\t}\n}"} {"input": "package swag\n\nimport (\n\t\"sort\"\n\t\"sync\"\n)\n\n\n\ntype indexOfInitialisms struct {\n\tgetMutex *sync.Mutex\n\tindex map[string]bool\n}\n\nfunc newIndexOfInitialisms() *indexOfInitialisms {\n\treturn &indexOfInitialisms{\n\t\tgetMutex: new(sync.Mutex),\n\t\tindex: make(map[string]bool, 50),\n\t}\n}\n\n\n\nfunc (m *indexOfInitialisms) isInitialism(key string) bool {\n\tm.getMutex.Lock()\n\tdefer m.getMutex.Unlock()\n\t_, ok := m.index[key]\n\treturn ok\n}\n\nfunc (m *indexOfInitialisms) add(key string) *indexOfInitialisms {\n\tm.getMutex.Lock()\n\tdefer m.getMutex.Unlock()\n\tm.index[key] = true\n\treturn m\n}\n\nfunc (m *indexOfInitialisms) sorted() (result []string) {\n\tm.getMutex.Lock()\n\tdefer m.getMutex.Unlock()\n\tfor k := range m.index {\n\t\tresult = append(result, k)\n\t}\n\tsort.Sort(sort.Reverse(byLength(result)))\n\treturn\n}\n\nfunc (m *indexOfInitialisms) load(initial map[string]bool) *indexOfInitialisms ", "output": "{\n\tm.getMutex.Lock()\n\tdefer m.getMutex.Unlock()\n\tfor k, v := range initial {\n\t\tm.index[k] = v\n\t}\n\treturn m\n}"} {"input": "package local \n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/tiborvass/docker/errdefs\"\n\t\"github.com/pkg/errors\"\n)\n\ntype optsConfig struct{}\n\n\n\n\n\nfunc setOpts(v *localVolume, opts map[string]string) error {\n\tif len(opts) > 0 {\n\t\treturn errdefs.InvalidParameter(errors.New(\"options are not supported on this platform\"))\n\t}\n\treturn nil\n}\n\nfunc (v *localVolume) needsMount() bool {\n\treturn false\n}\n\nfunc (v *localVolume) mount() error {\n\treturn nil\n}\n\nfunc (v *localVolume) postMount() error {\n\treturn nil\n}\n\nfunc (v *localVolume) CreatedAt() (time.Time, error) {\n\tfileInfo, err := os.Stat(v.path)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\tft := fileInfo.Sys().(*syscall.Win32FileAttributeData).CreationTime\n\treturn time.Unix(0, ft.Nanoseconds()), nil\n}\n\nfunc (r *Root) scopedPath(realPath string) bool ", "output": "{\n\tif strings.HasPrefix(realPath, filepath.Join(r.scope, volumesPathName)) && realPath != filepath.Join(r.scope, volumesPathName) {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package wml\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\ntype CT_MailMergeDocType struct {\n\tValAttr ST_MailMergeDocType\n}\n\nfunc NewCT_MailMergeDocType() *CT_MailMergeDocType {\n\tret := &CT_MailMergeDocType{}\n\tret.ValAttr = ST_MailMergeDocType(1)\n\treturn ret\n}\n\nfunc (m *CT_MailMergeDocType) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tattr, err := m.ValAttr.MarshalXMLAttr(xml.Name{Local: \"w:val\"})\n\tif err != nil {\n\t\treturn err\n\t}\n\tstart.Attr = append(start.Attr, attr)\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}\n\nfunc (m *CT_MailMergeDocType) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tm.ValAttr = ST_MailMergeDocType(1)\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"val\" {\n\t\t\tm.ValAttr.UnmarshalXMLAttr(attr)\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_MailMergeDocType: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (m *CT_MailMergeDocType) Validate() error {\n\treturn m.ValidateWithPath(\"CT_MailMergeDocType\")\n}\n\n\n\n\nfunc (m *CT_MailMergeDocType) ValidateWithPath(path string) error ", "output": "{\n\tif m.ValAttr == ST_MailMergeDocTypeUnset {\n\t\treturn fmt.Errorf(\"%s/ValAttr is a mandatory field\", path)\n\t}\n\tif err := m.ValAttr.ValidateWithPath(path + \"/ValAttr\"); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package whisper\n\nimport \"github.com/Tzunami/go-earthdollar/crypto\"\n\n\n\n\ntype Topic [4]byte\n\n\n\n\nfunc NewTopic(data []byte) Topic {\n\tprefix := [4]byte{}\n\tcopy(prefix[:], crypto.Keccak256(data)[:4])\n\treturn Topic(prefix)\n}\n\n\n\nfunc NewTopics(data ...[]byte) []Topic {\n\ttopics := make([]Topic, len(data))\n\tfor i, element := range data {\n\t\ttopics[i] = NewTopic(element)\n\t}\n\treturn topics\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype topicMatcher struct {\n\tconditions []map[Topic]struct{}\n}\n\n\nfunc newTopicMatcher(topics ...[]Topic) *topicMatcher {\n\tmatcher := make([]map[Topic]struct{}, len(topics))\n\tfor i, condition := range topics {\n\t\tmatcher[i] = make(map[Topic]struct{})\n\t\tfor _, topic := range condition {\n\t\t\tmatcher[i][topic] = struct{}{}\n\t\t}\n\t}\n\treturn &topicMatcher{conditions: matcher}\n}\n\n\nfunc (self *topicMatcher) Matches(topics []Topic) bool {\n\tif len(self.conditions) > len(topics) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(topics) && i < len(self.conditions); i++ {\n\t\tif len(self.conditions[i]) > 0 {\n\t\t\tif _, ok := self.conditions[i][topics[i]]; !ok {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (self *Topic) String() string ", "output": "{\n\treturn string(self[:])\n}"} {"input": "package warden\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"context\"\n\n\t\"github.com/ory/fosite\"\n\t\"github.com/ory/hydra/firewall\"\n\t\"github.com/ory/hydra/pkg\"\n\t\"github.com/pkg/errors\"\n\t\"golang.org/x/oauth2\"\n\t\"golang.org/x/oauth2/clientcredentials\"\n)\n\ntype HTTPWarden struct {\n\tClient *http.Client\n\tDry bool\n\tEndpoint *url.URL\n}\n\nfunc (w *HTTPWarden) TokenFromRequest(r *http.Request) string {\n\treturn fosite.AccessTokenFromRequest(r)\n}\n\nfunc (w *HTTPWarden) SetClient(c *clientcredentials.Config) {\n\tw.Client = c.Client(oauth2.NoContext)\n}\n\n\n\n\n\n\n\n\n\n\nfunc (w *HTTPWarden) IsAllowed(ctx context.Context, a *firewall.AccessRequest) error {\n\tvar allowed = struct {\n\t\tAllowed bool `json:\"allowed\"`\n\t}{}\n\n\tvar ep = *w.Endpoint\n\tep.Path = AllowedHandlerPath\n\tagent := &pkg.SuperAgent{URL: ep.String(), Client: w.Client}\n\tif err := agent.POST(a, &allowed); err != nil {\n\t\treturn err\n\t} else if !allowed.Allowed {\n\t\treturn errors.Wrap(fosite.ErrRequestForbidden, \"\")\n\t}\n\n\treturn nil\n}\n\nfunc (w *HTTPWarden) TokenAllowed(ctx context.Context, token string, a *firewall.TokenAccessRequest, scopes ...string) (*firewall.Context, error) ", "output": "{\n\tvar resp = struct {\n\t\t*firewall.Context\n\t\tAllowed bool `json:\"allowed\"`\n\t}{}\n\n\tvar ep = *w.Endpoint\n\tep.Path = TokenAllowedHandlerPath\n\tagent := &pkg.SuperAgent{URL: ep.String(), Client: w.Client}\n\tif err := agent.POST(&wardenAccessRequest{\n\t\twardenAuthorizedRequest: &wardenAuthorizedRequest{\n\t\t\tToken: token,\n\t\t\tScopes: scopes,\n\t\t},\n\t\tTokenAccessRequest: a,\n\t}, &resp); err != nil {\n\t\treturn nil, err\n\t} else if !resp.Allowed {\n\t\treturn nil, errors.New(\"Token is not valid\")\n\t}\n\n\treturn resp.Context, nil\n}"} {"input": "package doctor\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\ntype testHealthcheckStatus struct {\n\tSomeStatus HealthcheckStatus `json:\"status\"`\n}\n\nfunc TestUnmarshalHealthcheckStatus(t *testing.T) {\n\tstatus := HealthcheckStatusInitializing\n\n\terr := json.Unmarshal([]byte(`\"INITIALIZING\"`), &status)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif status != HealthcheckStatusInitializing {\n\t\tt.Error(\"INITIALIZING should unmarshal to INITIALIZING, not \" + status.String())\n\t}\n\n\tvar test testHealthcheckStatus\n\terr = json.Unmarshal([]byte(`{\"status\":\"IMPAIRED\"}`), &test)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif test.SomeStatus != HealthcheckStatusImpaired {\n\t\tt.Error(\"IMPAIRED should unmarshal to IMPAIRED, not \" + test.SomeStatus.String())\n\t}\n}\n\nfunc TestOk(t *testing.T) ", "output": "{\n\tinitializingStatus := HealthcheckStatusInitializing\n\tokStatus := HealthcheckStatusOk\n\timpairedStatus := HealthcheckStatusImpaired\n\tassert.True(t, initializingStatus.Ok())\n\tassert.True(t, okStatus.Ok())\n\tassert.False(t, impairedStatus.Ok())\n}"} {"input": "package integrations\n\nimport (\n\t\"testing\"\n\n\t\"github.com/xormplus/xorm\"\n\t\"github.com/xormplus/xorm/log\"\n\t\"github.com/xormplus/xorm/schemas\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestEngineGroup(t *testing.T) ", "output": "{\n\tassert.NoError(t, PrepareEngine())\n\n\tmain := testEngine.(*xorm.Engine)\n\tif main.Dialect().URI().DBType == schemas.SQLITE {\n\t\tt.Skip()\n\t\treturn\n\t}\n\n\teg, err := xorm.NewEngineGroup(main, []*xorm.Engine{main})\n\tassert.NoError(t, err)\n\n\teg.SetMaxIdleConns(10)\n\teg.SetMaxOpenConns(100)\n\teg.SetTableMapper(main.GetTableMapper())\n\teg.SetColumnMapper(main.GetColumnMapper())\n\teg.SetLogLevel(log.LOG_INFO)\n\teg.ShowSQL(true)\n}"} {"input": "package router\n\n\n\n\nimport (\n\t\"github.com/weaveworks/mesh\"\n)\n\n\n\ntype AWSVPCConnection struct {\n\testablishedChan chan struct{}\n\terrorChan chan error\n}\n\nfunc (conn *AWSVPCConnection) Confirm() {\n\tclose(conn.establishedChan)\n}\n\nfunc (conn *AWSVPCConnection) EstablishedChannel() <-chan struct{} {\n\treturn conn.establishedChan\n}\n\nfunc (conn *AWSVPCConnection) ErrorChannel() <-chan error {\n\treturn conn.errorChan\n}\n\nfunc (conn *AWSVPCConnection) Stop() {}\n\nfunc (conn *AWSVPCConnection) ControlMessage(tag byte, msg []byte) {\n}\n\nfunc (conn *AWSVPCConnection) DisplayName() string {\n\treturn \"awsvpc\"\n}\n\n\n\nfunc (conn *AWSVPCConnection) Forward(key ForwardPacketKey) FlowOp {\n\treturn DiscardingFlowOp{}\n}\n\ntype AWSVPC struct{}\n\n\n\n\n\nfunc (vpc AWSVPC) AddFeaturesTo(features map[string]string) {}\n\nfunc (vpc AWSVPC) PrepareConnection(params mesh.OverlayConnectionParams) (mesh.OverlayConnection, error) {\n\tconn := &AWSVPCConnection{\n\t\testablishedChan: make(chan struct{}),\n\t\terrorChan: make(chan error, 1),\n\t}\n\treturn conn, nil\n}\n\nfunc (vpc AWSVPC) Diagnostics() interface{} {\n\treturn nil\n}\n\n\n\nfunc (vpc AWSVPC) InvalidateRoutes() {}\n\nfunc (vpc AWSVPC) InvalidateShortIDs() {}\n\nfunc (vpc AWSVPC) StartConsumingPackets(localPeer *mesh.Peer, peers *mesh.Peers, consumer OverlayConsumer) error {\n\treturn nil\n}\n\nfunc NewAWSVPC() AWSVPC ", "output": "{\n\treturn AWSVPC{}\n}"} {"input": "package manifestparser\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype Locator struct {\n\tFilesToCheckFor []string\n}\n\nfunc NewLocator() *Locator {\n\treturn &Locator{\n\t\tFilesToCheckFor: []string{\n\t\t\t\"manifest.yml\",\n\t\t\t\"manifest.yaml\",\n\t\t},\n\t}\n}\n\nfunc (loc Locator) Path(filepathOrDirectory string) (string, bool, error) {\n\tinfo, err := os.Stat(filepathOrDirectory)\n\tif os.IsNotExist(err) {\n\t\treturn \"\", false, nil\n\t} else if err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tresolvedFilepathOrDirectory, err := filepath.EvalSymlinks(filepathOrDirectory)\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tif info.IsDir() {\n\t\treturn loc.handleDir(resolvedFilepathOrDirectory)\n\t}\n\n\treturn loc.handleFilepath(resolvedFilepathOrDirectory)\n}\n\n\n\nfunc (Locator) handleFilepath(filepath string) (string, bool, error) {\n\treturn filepath, true, nil\n}\n\nfunc (loc Locator) handleDir(dir string) (string, bool, error) ", "output": "{\n\tfor _, filename := range loc.FilesToCheckFor {\n\t\tfullPath := filepath.Join(dir, filename)\n\t\tif _, err := os.Stat(fullPath); err == nil {\n\t\t\treturn fullPath, true, nil\n\t\t} else if !os.IsNotExist(err) {\n\t\t\treturn \"\", false, err\n\t\t}\n\t}\n\n\treturn \"\", false, nil\n}"} {"input": "package utp\n\nimport (\n\t\"time\"\n\n\t\"github.com/micro/go-micro/transport\"\n)\n\n\n\nfunc (u *utpClient) Recv(m *transport.Message) error {\n\tif u.timeout > time.Duration(0) {\n\t\tu.conn.SetDeadline(time.Now().Add(u.timeout))\n\t}\n\treturn u.dec.Decode(&m)\n}\n\nfunc (u *utpClient) Close() error {\n\treturn u.conn.Close()\n}\n\nfunc (u *utpClient) Send(m *transport.Message) error ", "output": "{\n\tif u.timeout > time.Duration(0) {\n\t\tu.conn.SetDeadline(time.Now().Add(u.timeout))\n\t}\n\tif err := u.enc.Encode(m); err != nil {\n\t\treturn err\n\t}\n\treturn u.encBuf.Flush()\n}"} {"input": "package logger\n\nimport (\n\t\"github.com/raincious/trap/trap/core/types\"\n\n\t\"bufio\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype FilePrinter struct {\n\twriter *bufio.Writer\n\n\twriteCounts uint16\n}\n\n\n\nfunc (l *FilePrinter) save(w types.String, c types.String,\n\tt time.Time, m types.String) {\n\n\t_, err := l.writer.WriteString(fmt.Sprintf(\"<%s> %s [%s]: %s\\r\\n\",\n\t\tw, c, t.Format(time.StampMilli), m))\n\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Can't write log file due to error: %s\", err))\n\t}\n\n\tl.writeCounts += 1\n\n\tif l.writeCounts > 10 {\n\t\tl.writer.Flush()\n\n\t\tl.writeCounts = 0\n\t}\n}\n\nfunc (l *FilePrinter) Info(c types.String, t time.Time, m types.String) {\n\tl.save(\"INF\", c, t, m)\n}\n\nfunc (l *FilePrinter) Debug(c types.String, t time.Time, m types.String) {\n\tl.save(\"DBG\", c, t, m)\n}\n\nfunc (l *FilePrinter) Warning(c types.String, t time.Time, m types.String) {\n\tl.save(\"WRN\", c, t, m)\n}\n\nfunc (l *FilePrinter) Error(c types.String, t time.Time, m types.String) {\n\tl.save(\"ERR\", c, t, m)\n}\n\nfunc (l *FilePrinter) Print(c types.String, t time.Time, m types.String) {\n\tl.save(\"DEF\", c, t, m)\n}\n\nfunc NewFilePrinter(w *bufio.Writer) (*FilePrinter, *types.Throw) ", "output": "{\n\t_, writeErr := w.Write([]byte(\"\"))\n\n\tif writeErr != nil {\n\t\treturn nil, types.ConvertError(writeErr)\n\t}\n\n\treturn &FilePrinter{\n\t\twriter: w,\n\t}, nil\n}"} {"input": "package taskqueue\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/nevsnode/gordon/utils\"\n\t\"os\"\n\t\"strings\"\n)\n\n\ntype QueueTask struct {\n\tArgs []string `json:\"args\"` \n\tEnv map[string]string `json:\"env\"` \n\tErrorMessage string `json:\"error_message,omitempty\"` \n}\n\n\nfunc (q QueueTask) Execute(script string) error {\n\tcmd := utils.ExecCommand(script, q.Args...)\n\n\tcmd.Env = os.Environ()\n\tfor envKey, envVal := range q.Env {\n\t\tcmd.Env = append(cmd.Env, envKey+\"=\"+envVal)\n\t}\n\n\tout, err := cmd.Output()\n\n\tif len(out) != 0 && err == nil {\n\t\terr = fmt.Errorf(\"%s\", out)\n\t}\n\n\treturn err\n}\n\n\n\n\n\nfunc NewQueueTask(redisValue string) (task QueueTask, err error) {\n\treader := strings.NewReader(redisValue)\n\tparser := json.NewDecoder(reader)\n\terr = parser.Decode(&task)\n\treturn\n}\n\nfunc (q QueueTask) GetJSONString() (value string, err error) ", "output": "{\n\tif q.Args == nil {\n\t\tq.Args = make([]string, 0)\n\t}\n\tif q.Env == nil {\n\t\tq.Env = make(map[string]string)\n\t}\n\n\tb, err := json.Marshal(q)\n\tvalue = fmt.Sprintf(\"%s\", b)\n\treturn\n}"} {"input": "package dax\n\n\ntype Grapher interface {\n\tGetParent() Grapher\n\tAddChild(child Grapher)\n\tGetChildren() []Grapher\n}\n\ntype nodeStack struct {\n\tnodes []Grapher\n}\n\nfunc (s *nodeStack) Init() {\n\ts.nodes = make([]Grapher, 0, 16)\n}\n\nfunc (s *nodeStack) Empty() bool {\n\treturn len(s.nodes) == 0\n}\n\nfunc (s *nodeStack) Push(n Grapher) {\n\ts.nodes = append(s.nodes, n)\n}\n\nfunc (s *nodeStack) Pop() Grapher {\n\ti := len(s.nodes) - 1\n\tn := s.nodes[i]\n\ts.nodes[i] = nil\n\ts.nodes = s.nodes[:i]\n\treturn n\n}\n\ntype SceneGraph struct {\n\tNode\n}\n\nfunc NewSceneGraph() *SceneGraph {\n\tsg := new(SceneGraph)\n\tsg.Init()\n\treturn sg\n}\n\nfunc (sg *SceneGraph) Init() {\n\tsg.Node.Init()\n}\n\nfunc (sg *SceneGraph) updateWorldTransform() {\n\tsg.Node.updateWorldTransform(false)\n}\n\nfunc (sg *SceneGraph) Update(time float64) {\n\tsg.updateWorldTransform()\n}\n\n\nfunc (sg *SceneGraph) Traverse() <-chan Grapher {\n\tch := make(chan Grapher)\n\n\tgo func() {\n\t\tvar stack nodeStack\n\n\t\tstack.Init()\n\t\tstack.Push(sg)\n\n\t\tfor !stack.Empty() {\n\t\t\tn := stack.Pop()\n\t\t\tch <- n\n\t\t\tchildren := n.GetChildren()\n\t\t\tfor i := len(children) - 1; i >= 0; i-- {\n\t\t\t\tstack.Push(children[i])\n\t\t\t}\n\t\t}\n\t\tclose(ch)\n\t}()\n\n\treturn ch\n}\n\n\n\nfunc (sg *SceneGraph) Draw(fb Framebuffer) ", "output": "{\n\tfb.render().drawSceneGraph(fb, sg)\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"strconv\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype OpenpitrixDescribeUsersDetailResponseUserDetailSet []*OpenpitrixUserDetail\n\n\n\n\nfunc (m OpenpitrixDescribeUsersDetailResponseUserDetailSet) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tfor i := 0; i < len(m); i++ {\n\n\t\tif swag.IsZero(m[i]) { \n\t\t\tcontinue\n\t\t}\n\n\t\tif m[i] != nil {\n\n\t\t\tif err := m[i].Validate(formats); err != nil {\n\t\t\t\tif ve, ok := err.(*errors.Validation); ok {\n\t\t\t\t\treturn ve.ValidateName(strconv.Itoa(i))\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package libDao\n\nvar (\n\tstorage Storage\n)\n\n\ntype DefaultDao struct {\n}\n\n\nfunc InitDao(sc *StorageConfig, s Storage) (err error) {\n\tif sc == nil {\n\t\terr = ErrStorageConfigIllegal\n\t\treturn\n\t}\n\tif s == nil {\n\t\tdefaultStorage := new(DefaultStorage)\n\t\tstorage = defaultStorage\n\t} else {\n\t\tstorage = s\n\t}\n\tif sc.OpenCache {\n\t\tif err = storage.InitCache(sc.CacheAddr, sc.CacheKeyPrefix); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif sc.OpenPersistence {\n\t\tif err = storage.InitPersistence(sc.PersistenceAddr, sc.PersistenceDbName); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\n\n\n\n\nfunc (this *DefaultDao) Put(key string, value interface{}) (err error) {\n\terr = storage.Put(key, value)\n\treturn\n}\n\n\nfunc (this *DefaultDao) Del(key string, value interface{}) (err error) {\n\terr = storage.Del(key, value)\n\treturn\n}\n\nfunc (this *DefaultDao) Get(key string, value interface{}) (err error) ", "output": "{\n\terr = storage.Get(key, value)\n\treturn\n}"} {"input": "package crypto\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha512\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n)\n\n\nfunc HS512Byte(in, secret []byte) []byte {\n\th := hmac.New(sha512.New, secret)\n\th.Write(in)\n\treturn h.Sum(nil)\n}\n\n\nfunc HS512Base64(in, secret string) string {\n\tkey := []byte(secret)\n\th := hmac.New(sha512.New, key)\n\th.Write([]byte(in))\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil))\n}\n\n\nfunc HS512Hex(in, secret string) string {\n\tkey := []byte(secret)\n\th := hmac.New(sha512.New, key)\n\th.Write([]byte(in))\n\treturn hex.EncodeToString(h.Sum(nil))\n}\n\n\n\n\nfunc CompareHS512Hex(in, secret, hs512Hex string) bool ", "output": "{\n\tif HS512Hex(in, secret) == hs512Hex {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package models\n\nimport (\n\t\"testing\"\n\n\t\"github.com/golib/assert\"\n\tuuid \"github.com/satori/go.uuid\"\n)\n\n\n\nfunc Test_User_FindByEmail(t *testing.T) {\n\tassertion := assert.New(t)\n\n\tvar (\n\t\tusername = uuid.NewV4().String()\n\t\temail = \"test2@test.com\"\n\t\tpassword = uuid.NewV4().String()\n\t\tdesc = uuid.NewV4().String()\n\t)\n\n\tuser := User.NewUserModel(username, email, password, desc)\n\terr := user.Save()\n\tassertion.Nil(err)\n\n\tuser.Save()\n\tassertion.Nil(err)\n\n\tuserNew, err := User.FindByEmail(email)\n\tassertion.Nil(err)\n\tassertion.Equal(user.Id, userNew.Id)\n\n}\n\nfunc Test_User_FindByUsername(t *testing.T) {\n\tassertion := assert.New(t)\n\n\tvar (\n\t\tusername = uuid.NewV4().String()\n\t\temail = \"test3@test.com\"\n\t\tpassword = uuid.NewV4().String()\n\t\tdesc = uuid.NewV4().String()\n\t)\n\n\tuser := User.NewUserModel(username, email, password, desc)\n\terr := user.Save()\n\tassertion.Nil(err)\n\n\tuserNew, err := User.FindByUsername(username)\n\tassertion.Nil(err)\n\tassertion.Equal(user.Id, userNew.Id)\n\n}\n\nfunc Test_NewUserModel(t *testing.T) ", "output": "{\n\tassertion := assert.New(t)\n\n\tvar (\n\t\tusername = uuid.NewV4().String()\n\t\temail = \"tes1@test.com\"\n\t\tpassword = uuid.NewV4().String()\n\t\tdesc = uuid.NewV4().String()\n\t)\n\n\tuser := User.NewUserModel(username, email, password, desc)\n\tassertion.Equal(username, user.Username)\n\tassertion.Equal(email, user.Email)\n\tassertion.Equal(password, user.Password)\n\tassertion.Equal(UserStatusInactive, user.Status)\n\tassertion.Equal(desc, user.Description)\n}"} {"input": "package swagger\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n)\n\nfunc (prop *ModelProperty) setDescription(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"description\"); tag != \"\" {\n\t\tprop.Description = tag\n\t}\n}\n\n\n\nfunc (prop *ModelProperty) setEnumValues(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"enum\"); tag != \"\" {\n\t\tprop.Enum = strings.Split(tag, \"|\")\n\t}\n}\n\nfunc (prop *ModelProperty) setMaximum(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"maximum\"); tag != \"\" {\n\t\tprop.Maximum = tag\n\t}\n}\n\nfunc (prop *ModelProperty) setMinimum(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"minimum\"); tag != \"\" {\n\t\tprop.Minimum = tag\n\t}\n}\n\nfunc (prop *ModelProperty) setUniqueItems(field reflect.StructField) {\n\ttag := field.Tag.Get(\"unique\")\n\tswitch tag {\n\tcase \"true\":\n\t\tv := true\n\t\tprop.UniqueItems = &v\n\tcase \"false\":\n\t\tv := false\n\t\tprop.UniqueItems = &v\n\t}\n}\n\nfunc (prop *ModelProperty) setPropertyMetadata(field reflect.StructField) {\n\tprop.setDescription(field)\n\tprop.setEnumValues(field)\n\tprop.setMinimum(field)\n\tprop.setMaximum(field)\n\tprop.setUniqueItems(field)\n\tprop.setDefaultValue(field)\n}\n\nfunc (prop *ModelProperty) setDefaultValue(field reflect.StructField) ", "output": "{\n\tif tag := field.Tag.Get(\"default\"); tag != \"\" {\n\t\tprop.DefaultValue = Special(tag)\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nvar (\n\tsrv *httptest.Server\n)\n\nfunc mockHandler(w http.ResponseWriter, r *http.Request) {\n}\n\n\n\nfunc teardownServer() {\n\tsrv.Close()\n}\n\nfunc TestRoute(t *testing.T) {\n\tsetupServer()\n\tdefer teardownServer()\n\n\tpath := srv.URL + \"/test/it\"\n\tresp, err := http.DefaultClient.Get(path)\n\n\tassert.Nil(t, err)\n\tassert.Equal(t, 200, resp.StatusCode)\n}\n\nfunc TestCorsRoute(t *testing.T) {\n\tsetupServer()\n\tdefer teardownServer()\n\n\tpath := srv.URL + \"/cors/it\"\n\n\treq, _ := http.NewRequest(\"GET\", path, nil)\n\treq.Header.Add(\"Origin\", srv.URL)\n\tresp, err := http.DefaultClient.Do(req)\n\n\tassert.Nil(t, err)\n\tassert.Equal(t, 200, resp.StatusCode)\n\tassert.Equal(t, srv.URL, resp.Header.Get(\"Access-Control-Allow-Origin\"), \"CORS Allow-Origin not set\")\n}\n\nfunc setupServer() ", "output": "{\n\trouter := Router{mux.NewRouter()}\n\tm := RouteMap{\n\t\t\"GET\": {\n\t\t\t\"/it\": mockHandler,\n\t\t},\n\t}\n\n\trouter.AddRoutes(\"/test\", m)\n\trouter.AddCorsRoutes(\"/cors\", m)\n\tsrv = httptest.NewServer(router)\n}"} {"input": "package rsets\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/pingcap/tidb/context\"\n\t\"github.com/pingcap/tidb/plan\"\n\t\"github.com/pingcap/tidb/plan/plans\"\n)\n\nvar (\n\t_ plan.Planner = (*LimitRset)(nil)\n\t_ plan.Planner = (*OffsetRset)(nil)\n)\n\n\ntype OffsetRset struct {\n\tCount uint64\n\tSrc plan.Plan\n}\n\n\n\n\nfunc (r *OffsetRset) String() string {\n\treturn fmt.Sprintf(\" OFFSET %d\", r.Count)\n}\n\n\ntype LimitRset struct {\n\tCount uint64\n\tSrc plan.Plan\n}\n\n\nfunc (r *LimitRset) Plan(ctx context.Context) (plan.Plan, error) {\n\treturn &plans.LimitDefaultPlan{Count: r.Count, Src: r.Src, Fields: r.Src.GetFields()}, nil\n}\n\nfunc (r *LimitRset) String() string {\n\treturn fmt.Sprintf(\" LIMIT %d\", r.Count)\n}\n\nfunc (r *OffsetRset) Plan(ctx context.Context) (plan.Plan, error) ", "output": "{\n\treturn &plans.OffsetDefaultPlan{Count: r.Count, Src: r.Src, Fields: r.Src.GetFields()}, nil\n}"} {"input": "package stack\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/docker/docker/api/client\"\n\t\"github.com/docker/docker/api/client/idresolver\"\n\t\"github.com/docker/docker/api/client/task\"\n\t\"github.com/docker/docker/cli\"\n\t\"github.com/docker/docker/opts\"\n\t\"github.com/docker/engine-api/types\"\n\t\"github.com/docker/engine-api/types/swarm\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype tasksOptions struct {\n\tall bool\n\tfilter opts.FilterOpt\n\tnamespace string\n\tnoResolve bool\n}\n\n\n\nfunc runTasks(dockerCli *client.DockerCli, opts tasksOptions) error {\n\tclient := dockerCli.Client()\n\tctx := context.Background()\n\n\tfilter := opts.filter.Value()\n\tfilter.Add(\"label\", labelNamespace+\"=\"+opts.namespace)\n\tif !opts.all && !filter.Include(\"desired-state\") {\n\t\tfilter.Add(\"desired-state\", string(swarm.TaskStateRunning))\n\t\tfilter.Add(\"desired-state\", string(swarm.TaskStateAccepted))\n\t}\n\n\ttasks, err := client.TaskList(ctx, types.TaskListOptions{Filter: filter})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn task.Print(dockerCli, ctx, tasks, idresolver.New(client, opts.noResolve))\n}\n\nfunc newTasksCommand(dockerCli *client.DockerCli) *cobra.Command ", "output": "{\n\topts := tasksOptions{filter: opts.NewFilterOpt()}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"tasks [OPTIONS] STACK\",\n\t\tShort: \"List the tasks in the stack\",\n\t\tArgs: cli.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\topts.namespace = args[0]\n\t\t\treturn runTasks(dockerCli, opts)\n\t\t},\n\t}\n\tflags := cmd.Flags()\n\tflags.BoolVarP(&opts.all, \"all\", \"a\", false, \"Display all tasks\")\n\tflags.BoolVarP(&opts.noResolve, \"no-resolve\", \"n\", false, \"Do not map IDs to Names\")\n\tflags.VarP(&opts.filter, \"filter\", \"f\", \"Filter output based on conditions provided\")\n\n\treturn cmd\n}"} {"input": "package utils\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n\n\nfunc GetHostIp() string {\n\tip := \"127.0.0.1\"\n\n\taddrs, _ := net.InterfaceAddrs()\n\tfor _, a := range addrs {\n\t\tipnet := net.ParseIP(a.String())\n\t\tif ipnet == nil {\n\t\t\tipnet, _, _ = net.ParseCIDR(a.String())\n\t\t}\n\t\tif ipnet != nil && !ipnet.IsLoopback() && !ipnet.IsUnspecified() {\n\t\t\tif ipnet.To4() != nil {\n\t\t\t\tip = ipnet.String()\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ip\n}\n\nfunc IsIgnoreRequest(url string, contentType string, statusCode int) bool {\n\tif statusCode != 200 {\n\t\treturn true\n\t}\n\tif !strings.Contains(contentType, \"text\") && !strings.Contains(contentType, \"application\") {\n\t\treturn true\n\t}\n\n\tswitch {\n\tcase strings.Contains(contentType, \"text/css\"):\n\t\tfallthrough\n\tcase strings.Contains(contentType, \"text/javascript\"):\n\t\treturn true\n\tdefault:\n\t\tbreak\n\t}\n\tidx := strings.Index(url, \"?\")\n\tif idx >= 0 {\n\t\turl = url[:idx]\n\t}\n\text := strings.ToLower(filepath.Ext(url))\n\treturn ext == \".js\" || ext == \".css\" ||\n\t\text == \".jpg\" || ext == \".jpeg\" || ext == \".gif\" || ext == \".png\" ||\n\t\text == \".bmp\" || ext == \".ico\" || ext == \".woff\" || ext == \".font\" ||\n\t\text == \".ttf\" || ext == \".svg\" || ext == \".pdf\" || ext == \".txt\"\n}\n\nfunc ToJson(data interface{}) string ", "output": "{\n\tb, err := json.Marshal(data)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\treturn string(b)\n}"} {"input": "package changes\n\nimport \"github.com/m3db/m3metrics/rules/view\"\n\n\ntype MappingRuleChange struct {\n\tOp Op `json:\"op\"`\n\tRuleID *string `json:\"ruleID,omitempty\"`\n\tRuleData *view.MappingRule `json:\"ruleData,omitempty\"`\n}\n\ntype mappingRuleChangesByOpAscNameAscIDAsc []MappingRuleChange\n\n\nfunc (a mappingRuleChangesByOpAscNameAscIDAsc) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a mappingRuleChangesByOpAscNameAscIDAsc) Less(i, j int) bool {\n\tif a[i].Op < a[j].Op {\n\t\treturn true\n\t}\n\tif a[i].Op > a[j].Op {\n\t\treturn false\n\t}\n\tif a[i].RuleData != nil && a[j].RuleData != nil {\n\t\treturn a[i].RuleData.Name < a[j].RuleData.Name\n\t}\n\tif a[i].RuleID != nil && a[j].RuleID != nil {\n\t\treturn *a[i].RuleID < *a[j].RuleID\n\t}\n\treturn false\n}\n\nfunc (a mappingRuleChangesByOpAscNameAscIDAsc) Len() int ", "output": "{ return len(a) }"} {"input": "package writers\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n)\n\n\n\nfunc newWriterForHttpTest() *Http {\n\th := &Http{}\n\n\treadersData := make(map[string][]byte)\n\treadersData[\"/load-avg\"] = jsonReadersDataForHttpTest()\n\n\th.SetReadersDataInBytes(readersData)\n\n\treturn h\n}\n\nfunc TestHeadersAsMap(t *testing.T) {\n\th := newWriterForHttpTest()\n\th.Headers = \"X-Key=test\"\n\n\tasMap := h.headersAsMap()\n\tif asMap[\"X-Key\"] != \"test\" {\n\t\tt.Error(\"headersAsMap did the wrong thing.\")\n\t}\n}\n\nfunc TestNewHttpSetReadersDataInBytes(t *testing.T) {\n\th := newWriterForHttpTest()\n\n\tkey := \"/load-avg\"\n\t_, ok := h.GetReadersData()[key]\n\tif !ok {\n\t\tt.Errorf(\"Key does not exist. Key: %v, Data: %v\", key, h.GetReadersData())\n\t}\n}\n\nfunc TestNewHttpRequest(t *testing.T) {\n\th := newWriterForHttpTest()\n\th.Url = \"http://example.com/\"\n\th.Method = \"POST\"\n\n\treadersData := h.GetReadersData()\n\tdataJson, err := json.Marshal(readersData)\n\n\tif err != nil {\n\t\tt.Errorf(\"Failed to generate readers data. Error: %v\", err)\n\t}\n\n\t_, err = h.NewHttpRequest(dataJson)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create Request struct. Error: %v\", err)\n\t}\n}\n\nfunc jsonReadersDataForHttpTest() []byte ", "output": "{\n\tjsonData := `{\n \"Data\": {\n \"LoadAvg15m\": 1.59375,\n \"LoadAvg1m\": 1.5537109375,\n \"LoadAvg5m\": 1.68798828125\n },\n \"GoStruct\": \"LoadAvg\",\n \"Host\": {\n \"Name\":\"MacBook-Pro.local\",\n \"Tags\":[]\n },\n \"Interval\": \"1s\",\n \"Path\": \"/load-avg\",\n \"Tags\": [ ],\n \"UnixNano\": 1420607791403576000\n}`\n\treturn []byte(jsonData)\n}"} {"input": "package exchange\n\nimport (\n\t\"os\"\n\n\t\"github.com/WICG/webpackage/go/signedexchange\"\n)\n\n\n\n\nfunc ReadExchangeFile(filename string) (*signedexchange.Exchange, error) ", "output": "{\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treturn signedexchange.ReadExchange(f)\n}"} {"input": "package codelocation\n\nimport (\n\t\"regexp\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"strings\"\n\n\t\"github.com/mysza/go-service-template/Godeps/_workspace/src/github.com/onsi/ginkgo/types\"\n)\n\n\n\nfunc PruneStack(fullStackTrace string, skip int) string {\n\tstack := strings.Split(fullStackTrace, \"\\n\")\n\tif len(stack) > 2*(skip+1) {\n\t\tstack = stack[2*(skip+1):]\n\t}\n\tprunedStack := []string{}\n\tre := regexp.MustCompile(`\\/ginkgo\\/|\\/pkg\\/testing\\/|\\/pkg\\/runtime\\/`)\n\tfor i := 0; i < len(stack)/2; i++ {\n\t\tif !re.Match([]byte(stack[i*2])) {\n\t\t\tprunedStack = append(prunedStack, stack[i*2])\n\t\t\tprunedStack = append(prunedStack, stack[i*2+1])\n\t\t}\n\t}\n\treturn strings.Join(prunedStack, \"\\n\")\n}\n\nfunc New(skip int) types.CodeLocation ", "output": "{\n\t_, file, line, _ := runtime.Caller(skip + 1)\n\tstackTrace := PruneStack(string(debug.Stack()), skip)\n\treturn types.CodeLocation{FileName: file, LineNumber: line, FullStackTrace: stackTrace}\n}"} {"input": "package logutils\n\nimport (\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype MockLog struct {\n\tmock.Mock\n}\n\nfunc NewMockLog() *MockLog {\n\treturn &MockLog{}\n}\n\nfunc (m *MockLog) Fatalf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Panicf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Errorf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Warnf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Infof(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\n\n\nfunc (m *MockLog) SetLevel(level LogLevel) {\n\tm.Called(level)\n}\n\nfunc (m *MockLog) Child(name string) Log ", "output": "{\n\tm.Called(name)\n\treturn m\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\ntype ErrNegativeSqrt float64\n\nfunc (e ErrNegativeSqrt) Error() string {\n\treturn fmt.Sprintf(\"cannot Sqrt negative number: %g\\n\", float64(e))\n}\n\n\n\nfunc main() {\n\tfmt.Println(Sqrt(2))\n\tfmt.Println(Sqrt(-2))\n}\n\nfunc Sqrt(x float64) (float64, error) ", "output": "{\n\tz := 1.0\n\tif x >= 0 {\n\t\tfor i := 0; i < 10; i++ {\n\t\t\tz = z - (z*z-x)/(2*z)\n\t\t}\n\t} else {\n\t\treturn 0, ErrNegativeSqrt(x)\n\t}\n\treturn z, nil\n}"} {"input": "package httpserver\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\nfunc TestNewResponseRecorder(t *testing.T) {\n\tw := httptest.NewRecorder()\n\trecordRequest := NewResponseRecorder(w)\n\tif !(recordRequest.ResponseWriter == w) {\n\t\tt.Fatalf(\"Expected Response writer in the Recording to be same as the one sent\\n\")\n\t}\n\tif recordRequest.status != http.StatusOK {\n\t\tt.Fatalf(\"Expected recorded status to be http.StatusOK (%d) , but found %d\\n \", http.StatusOK, recordRequest.status)\n\t}\n}\n\n\nfunc TestWrite(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tresponseTestString := \"test\"\n\trecordRequest := NewResponseRecorder(w)\n\tbuf := []byte(responseTestString)\n\t_, _ = recordRequest.Write(buf)\n\tif recordRequest.size != len(buf) {\n\t\tt.Fatalf(\"Expected the bytes written counter to be %d, but instead found %d\\n\", len(buf), recordRequest.size)\n\t}\n\tif w.Body.String() != responseTestString {\n\t\tt.Fatalf(\"Expected Response Body to be %s , but found %s\\n\", responseTestString, w.Body.String())\n\t}\n}\n\nfunc TestWriteHeader(t *testing.T) ", "output": "{\n\tw := httptest.NewRecorder()\n\trecordRequest := NewResponseRecorder(w)\n\trecordRequest.WriteHeader(401)\n\tif w.Code != 401 || recordRequest.status != 401 {\n\t\tt.Fatalf(\"Expected Response status to be set to 401, but found %d\\n\", recordRequest.status)\n\t}\n}"} {"input": "package migrations\n\nimport (\n\t\"context\"\n\n\t\"github.com/fnproject/fn/api/datastore/sql/migratex\"\n\t\"github.com/jmoiron/sqlx\"\n)\n\nfunc up6(ctx context.Context, tx *sqlx.Tx) error {\n\t_, err := tx.ExecContext(ctx, \"ALTER TABLE apps ADD updated_at VARCHAR(256);\")\n\treturn err\n}\n\n\n\nfunc init() {\n\tMigrations = append(Migrations, &migratex.MigFields{\n\t\tVersionFunc: vfunc(6),\n\t\tUpFunc: up6,\n\t\tDownFunc: down6,\n\t})\n}\n\nfunc down6(ctx context.Context, tx *sqlx.Tx) error ", "output": "{\n\t_, err := tx.ExecContext(ctx, \"ALTER TABLE apps DROP COLUMN updated_at;\")\n\treturn err\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\n\t\"github.com/maraino/go-mock\"\n)\n\ntype Client interface {\n\tRequest(url *url.URL) (int, string, error)\n}\n\ntype MyClient struct {\n\tmock.Mock\n}\n\n\n\nfunc main() {\n\tc := &MyClient{}\n\n\turl, _ := url.Parse(\"http://www.example.org\")\n\tc.When(\"Request\", url).Return(200, \"{result:1}\", nil).Times(1)\n\tc.When(\"Request\", mock.Any).Return(500, \"{result:0}\", fmt.Errorf(\"Internal Server Error\")).Times(1)\n\n\tcode, json, err := c.Request(url)\n\tfmt.Printf(\"Code: %d, JSON: %s, Error: %v\\n\", code, json, err)\n\n\turl, _ = url.Parse(\"http://www.github.com\")\n\tcode, json, err = c.Request(url)\n\tfmt.Printf(\"Code: %d, JSON: %s, Error: %v\\n\", code, json, err)\n\n\tif ok, err := c.Verify(); !ok {\n\t\tfmt.Println(err)\n\t}\n}\n\nfunc (c *MyClient) Request(url *url.URL) (int, string, error) ", "output": "{\n\tret := c.Called(url)\n\treturn ret.Int(0), ret.String(1), ret.Error(2)\n}"} {"input": "package iterfloat32\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"sync\"\n)\n\ntype Slice struct {\n\tSlice []float32\n\terr error\n\tindex int\n\tmutex sync.RWMutex\n\tclosed bool\n\tdatum float32\n}\n\nfunc (receiver *Slice) Close() error {\n\tif nil == receiver {\n\t\treturn errNilReceiver\n\t}\n\n\treceiver.mutex.Lock()\n\tdefer receiver.mutex.Unlock()\n\n\treceiver.closed = true\n\n\treturn nil\n}\n\n\n\n\nfunc (receiver *Slice) Decode(x interface{}) error {\n\tif nil == receiver {\n\t\treturn errNilReceiver\n\t}\n\n\treceiver.mutex.RLock()\n\tdefer receiver.mutex.RUnlock()\n\n\tswitch p := x.(type) {\n\tcase *float32:\n\t\tif nil == p {\n\t\t\treturn nil\n\t\t}\n\n\t\t*p = receiver.datum\n\tcase *interface{}:\n\t\tif nil == p {\n\t\t\treturn nil\n\t\t}\n\n\t\t*p = receiver.datum\n\tcase sql.Scanner:\n\t\treturn p.Scan( float64(receiver.datum) )\n\tdefault:\n\t\treturn &internalBadTypeComplainer{fmt.Sprintf(\"%T\", p)}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (receiver *Slice) Err() error {\n\tif nil == receiver {\n\t\treturn errNilReceiver\n\t}\n\n\treceiver.mutex.RLock()\n\tdefer receiver.mutex.RUnlock()\n\n\treturn receiver.err\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (receiver *Slice) Next() bool ", "output": "{\n\tif nil == receiver {\n\t\treturn false\n\t}\n\n\treceiver.mutex.Lock()\n\tdefer receiver.mutex.Unlock()\n\n\tif nil != receiver.err {\n\t\treturn false\n\t}\n\n\tif receiver.closed {\n\t\treturn false\n\t}\n\n\tslice := receiver.Slice\n\tif nil == slice {\n\t\treturn false\n\t}\n\n\tindex := receiver.index\n\tif len(slice) <= index {\n\t\treturn false\n\t}\n\n\treceiver.datum = slice[index]\n\treceiver.index++\n\n\treturn true\n}"} {"input": "package nanomsg\n\n\nimport \"C\"\n\nimport (\n\t\"time\"\n)\n\nconst (\n\tSURVEYOR = Protocol(C.NN_SURVEYOR)\n\tRESPONDENT = Protocol(C.NN_RESPONDENT)\n)\n\ntype SurveyorSocket struct {\n\t*Socket\n}\n\n\n\n\n\n\n\n\n\nfunc (s *SurveyorSocket) Deadline() (time.Duration, error) {\n\treturn s.Socket.SockOptDuration(C.NN_SURVEYOR, C.NN_SURVEYOR_DEADLINE, time.Millisecond)\n}\n\n\n\n\nfunc (s *SurveyorSocket) SetDeadline(deadline time.Duration) error {\n\treturn s.Socket.SetSockOptDuration(C.NN_SURVEYOR, C.NN_SURVEYOR_DEADLINE, time.Millisecond, deadline)\n}\n\ntype RespondentSocket struct {\n\t*Socket\n}\n\n\n\n\nfunc NewRespondentSocket() (*RespondentSocket, error) {\n\tsocket, err := NewSocket(AF_SP, RESPONDENT)\n\treturn &RespondentSocket{socket}, err\n}\n\nfunc NewSurveyorSocket() (*SurveyorSocket, error) ", "output": "{\n\tsocket, err := NewSocket(AF_SP, SURVEYOR)\n\treturn &SurveyorSocket{socket}, err\n}"} {"input": "package statsd_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\t\"github.com/cv-library/statsd\"\n)\n\nfunc ExampleTiming() {\n\tfor i:=0; i<10; i++ {\n\t\ttimer := statsd.Timer()\n\n\n\t\ttook := timer.Send(\"work.duration\")\n\t\ttimer.SendWithOptions(\n\t\t\t&statsd.Options{ Rate: 0.25 },\n\t\t\t\"work.duration.sampled\",\n\t\t)\n\n\t\tfmt.Printf(\"Took %f seconds\\n\", took.Seconds())\n\t}\n}\n\nfunc ExampleTimer() {\n\ttimer := statsd.Timer()\n\tfor i:=0; i<10; i++ {\n\t\ttimer.Reset()\n\n\n\t\ttook := timer.Send(\"work.duration\")\n\t\ttimer.SendWithOptions(\n\t\t\t&statsd.Options{ Rate: 0.25 },\n\t\t\t\"work.duration.sampled\",\n\t\t)\n\n\t\tfmt.Printf(\"Took %f seconds\\n\", took.Seconds())\n\t}\n}\n\nfunc ExampleTime() {\n\tfor i:=0; i<10; i++ {\n\t\tstart := time.Now()\n\n\n\t\tstatsd.Time(\"work.duration\", time.Since(start))\n\t}\n}\n\n\n\nfunc ExampleInc() {\n\tstatsd.Inc(\"stats.success\")\n}\n\nfunc ExampleIncWithOptions() {\n\tstatsd.IncWithOptions(\n\t\t&statsd.Options{ Rate: 0.5 },\n\t\t\"stats.success\",\n\t)\n}\n\nfunc ExampleGauge() {\n\tstatsd.Gauge(\"page.size\", 10)\n}\n\nfunc ExampleGaugeWithOptions() {\n\tstatsd.GaugeWithOptions(\n\t\t&statsd.Options{ Rate: 0.5 },\n\t\t\"page.size\",\n\t\t10,\n\t)\n}\n\nfunc ExampleTimeWithOptions() ", "output": "{\n\tfor i:=0; i<10; i++ {\n\t\tstart := time.Now()\n\n\n\t\tif i % 2 == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tstatsd.TimeWithOptions(\n\t\t\t&statsd.Options{ Rate: 0.5, AlwaysSend: true },\n\t\t\t\"work.duration.sampled\",\n\t\t\ttime.Since(start),\n\t\t)\n\t}\n}"} {"input": "package rds\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\t\"lib/utils\"\n\t\"fmt\"\n)\n\ntype RdsPuller struct {\n\tactive int32\n\tfire *RdsFire\n\tclient *RdsClient\n\ttopic string\n\twg *sync.WaitGroup\n}\n\nfunc NewRdsPuller(_conf *RdsConfig, _topic string, _on_data OnRdsData) (*RdsPuller) {\n\treturn &RdsPuller{\n\t\ttopic: _topic,\n\t\tfire: NewRdsFire(\"Rdspuller\", _on_data),\n\t\tclient: NewRdsClient(_conf),\n\t}\n}\n\nfunc (p *RdsPuller) IsActive() (bool) {\n\treturn atomic.LoadInt32(&p.active) == 1\n}\n\n\n\nfunc (p *RdsPuller) Start() {\n\tif atomic.CompareAndSwapInt32(&p.active, 0, 1) {\n\t\tp.fire.Start()\n\t\tp.client.Start()\n\n\t\tp.wg = &sync.WaitGroup{}\n\t\tp.wg.Add(1)\n\t\tutils.GoRunAdd(p.loop, \"RdsPuller.loop\")\n\t}\n}\n\nfunc (p *RdsPuller) Stop() {\n\tif atomic.CompareAndSwapInt32(&p.active, 1, 0) {\n\t\tp.wg.Wait()\n\n\t\tp.client.Stop()\n\t\tp.fire.Stop()\n\t}\n}\n\nfunc TestPuller() {\n\tconf := NewRdsConf()\n\tsubs := NewRdsPuller(conf, \"CMDRT\", func(_data *RdsData) {\n\t\tfmt.Printf(\"%s\\r\\n\", _data.String())\n\t})\n\tsubs.Start()\n\ttime.Sleep(time.Hour)\n}\n\nfunc (p *RdsPuller) loop(_arg interface{}) ", "output": "{\n\tdefer func() {\n\t\tp.wg.Done()\n\t}()\n\n\tfor p.IsActive() {\n\t\tary := p.client.BLpop(time.Second, p.topic)\n\t\tif len(ary) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tp.fire.Offer(ary[0], ary[1])\n\t}\n}"} {"input": "package action\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"errors\"\n\n\tboshagentblobstore \"github.com/cloudfoundry/bosh-agent/agent/blobstore\"\n\tboshcrypto \"github.com/cloudfoundry/bosh-utils/crypto\"\n\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n)\n\ntype UploadBlobSpec struct {\n\tBlobID string `json:\"blob_id\"`\n\tChecksum boshcrypto.MultipleDigest `json:\"checksum\"`\n\tPayload string `json:\"payload\"`\n}\n\ntype UploadBlobAction struct {\n\tblobManager boshagentblobstore.BlobManagerInterface\n}\n\nfunc NewUploadBlobAction(blobManager boshagentblobstore.BlobManagerInterface) UploadBlobAction {\n\treturn UploadBlobAction{blobManager: blobManager}\n}\n\nfunc (a UploadBlobAction) IsAsynchronous(_ ProtocolVersion) bool {\n\treturn true\n}\n\nfunc (a UploadBlobAction) IsPersistent() bool {\n\treturn false\n}\n\nfunc (a UploadBlobAction) IsLoggable() bool {\n\treturn false\n}\n\nfunc (a UploadBlobAction) Run(content UploadBlobSpec) (string, error) {\n\n\tdecodedPayload, err := base64.StdEncoding.DecodeString(content.Payload)\n\tif err != nil {\n\t\treturn content.BlobID, err\n\t}\n\n\tif err = a.validatePayload(decodedPayload, content.Checksum); err != nil {\n\t\treturn content.BlobID, err\n\t}\n\n\treader := bytes.NewReader(decodedPayload)\n\n\terr = a.blobManager.Write(content.BlobID, reader)\n\n\treturn content.BlobID, err\n}\n\n\n\nfunc (a UploadBlobAction) Resume() (interface{}, error) {\n\treturn nil, errors.New(\"not supported\")\n}\n\nfunc (a UploadBlobAction) Cancel() error {\n\treturn errors.New(\"not supported\")\n}\n\nfunc (a UploadBlobAction) validatePayload(payload []byte, payloadDigest boshcrypto.Digest) error ", "output": "{\n\terr := payloadDigest.Verify(bytes.NewReader(payload))\n\tif err != nil {\n\t\treturn bosherr.WrapErrorf(err, \"Payload corrupted. Checksum mismatch. Expected '%s'\", payloadDigest.String())\n\t}\n\n\treturn nil\n}"} {"input": "package persistence\n\nimport (\n\t\"strings\"\n\n\t. \"github.com/Masterminds/squirrel\"\n\t\"github.com/navidrome/navidrome/conf\"\n\t\"github.com/navidrome/navidrome/utils\"\n)\n\nfunc getFullText(text ...string) string {\n\tfullText := utils.SanitizeStrings(text...)\n\treturn \" \" + fullText\n}\n\n\n\nfunc fullTextExpr(value string) Sqlizer {\n\tvar sep string\n\tif !conf.Server.SearchFullString {\n\t\tsep = \" \"\n\t}\n\tq := utils.SanitizeStrings(value)\n\tparts := strings.Split(q, \" \")\n\tfilters := And{}\n\tfor _, part := range parts {\n\t\tfilters = append(filters, Like{\"full_text\": \"%\" + sep + part + \"%\"})\n\t}\n\treturn filters\n}\n\nfunc (r sqlRepository) doSearch(q string, offset, size int, results interface{}, orderBys ...string) error ", "output": "{\n\tq = strings.TrimSpace(q)\n\tq = strings.TrimSuffix(q, \"*\")\n\tif len(q) < 2 {\n\t\treturn nil\n\t}\n\n\tsq := r.newSelectWithAnnotation(r.tableName + \".id\").Columns(\"*\")\n\tsq = sq.Limit(uint64(size)).Offset(uint64(offset))\n\tif len(orderBys) > 0 {\n\t\tsq = sq.OrderBy(orderBys...)\n\t}\n\tsq = sq.Where(fullTextExpr(q))\n\terr := r.queryAll(sq, results)\n\treturn err\n}"} {"input": "package main\nimport (\n \"fmt\"\n \"os\"\n \"strings\"\n)\n\nfunc (s *TableStats) init(headers []string) error {\n s.Headers = make([]string, len(headers))\n s.Fields = make(map[string]*FieldStats)\n for i,header := range(headers) {\n header = strings.TrimSpace(header)\n if _,ok := s.Fields[header]; ok {\n fmt.Fprintf(os.Stderr, \"Duplicate header '%s'\\n\", header)\n }\n stats := new(FieldStats)\n stats.init()\n s.Headers[i] = header\n s.Fields[header] = stats\n }\n return nil\n}\n\n\n\nfunc (s *TableStats) String() string {\n tableStr := fmt.Sprintf(\"Table stats - %d columns, %d rows\\n\"+\n \"=================================\",\n len(s.Headers), s.NumRows)\n var fieldStrs []string\n for _,header := range(s.Headers) {\n var headerStr string\n if header == \"\" {\n headerStr = \"(blank header)\"\n } else {\n headerStr = \"'\"+header+\"'\"\n }\n fieldStr := s.Fields[header].String()\n fieldStrs = append(fieldStrs, fmt.Sprintf(\"%s %s\",\n headerStr, fieldStr))\n }\n return tableStr + \"\\n\\n\" + strings.Join(fieldStrs, \"\\n\\n\")\n}\n\nfunc (s *TableStats) update(values []string) error ", "output": "{\n if len(values) != len(s.Headers) {\n return fmt.Errorf(\"Found %d values but %d headers\",\n len(values), len(s.Headers))\n }\n for i,header := range(s.Headers) {\n field := s.Fields[header]\n if field != nil {\n field.update(values[i])\n }\n }\n s.NumRows++\n return nil\n}"} {"input": "package refmt\n\nimport (\n\t\"github.com/polydawn/refmt/obj\"\n\t\"github.com/polydawn/refmt/obj/atlas\"\n\t\"github.com/polydawn/refmt/shared\"\n)\n\n\nfunc MustClone(src, dst interface{}) {\n\tif err := Clone(src, dst); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc CloneAtlased(src, dst interface{}, atl atlas.Atlas) error {\n\treturn NewCloner(atl).Clone(src, dst)\n}\nfunc MustCloneAtlased(src, dst interface{}, atl atlas.Atlas) {\n\tif err := CloneAtlased(src, dst, atl); err != nil {\n\t\tpanic(err)\n\t}\n}\n\ntype Cloner interface {\n\tClone(src, dst interface{}) error\n}\n\nfunc NewCloner(atl atlas.Atlas) Cloner {\n\tx := &cloner{\n\t\tmarshaller: obj.NewMarshaller(atl),\n\t\tunmarshaller: obj.NewUnmarshaller(atl),\n\t}\n\tx.pump = shared.TokenPump{x.marshaller, x.unmarshaller}\n\treturn x\n}\n\ntype cloner struct {\n\tmarshaller *obj.Marshaller\n\tunmarshaller *obj.Unmarshaller\n\tpump shared.TokenPump\n}\n\nfunc (c cloner) Clone(src, dst interface{}) error {\n\tc.marshaller.Bind(src)\n\tc.unmarshaller.Bind(dst)\n\treturn c.pump.Run()\n}\n\nfunc Clone(src, dst interface{}) error ", "output": "{\n\treturn CloneAtlased(src, dst, atlas.MustBuild())\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestFilterList(t *testing.T) {\n\tvar infos = []struct {\n\t\torigin []string\n\t\tcondition []string\n\t\tret []string\n\t}{\n\t\t{\n\t\t\torigin: []string{\"power\", \"audio\", \"dock\"},\n\t\t\tcondition: []string{\"power\", \"dock\"},\n\t\t\tret: []string{\"audio\"},\n\t\t},\n\t\t{\n\t\t\torigin: []string{\"power\", \"audio\", \"dock\"},\n\t\t\tcondition: []string{},\n\t\t\tret: []string{\"power\", \"audio\", \"dock\"},\n\t\t},\n\t\t{\n\t\t\torigin: []string{\"power\", \"audio\", \"dock\"},\n\t\t\tcondition: []string{\"power\", \"dock\", \"audio\"},\n\t\t\tret: []string(nil),\n\t\t},\n\t}\n\n\tfor _, info := range infos {\n\t\tassert.ElementsMatch(t, info.ret, filterList(info.origin, info.condition))\n\t}\n}\n\nfunc TestSessionDaemon_GetInterfaceName(t *testing.T) ", "output": "{\n\ts := SessionDaemon{}\n\tassert.Equal(t, dbusInterface, s.GetInterfaceName())\n}"} {"input": "package query\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/fatih/structs\"\n\t\"github.com/itchyny/gojq\"\n\t\"github.com/jmespath/go-jmespath\"\n)\n\nfunc ByJMESPath(v interface{}, query string, printer func(interface{}) error) (err error) {\n\tdefer func() {\n\t\tret := recover()\n\t\tif ret != nil {\n\t\t\terr = fmt.Errorf(\"jmespath: failed to process query: %s\", ret)\n\t\t}\n\t}()\n\tvar result interface{}\n\tresult, err = jmespath.Search(query, v)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn printer(result)\n}\n\n\n\nfunc convertInputToMap(input interface{}) (interface{}, error) {\n\tvar inputs []interface{}\n\n\tswitch input := input.(type) {\n\tcase map[string]interface{}:\n\t\treturn input, nil \n\tcase []interface{}:\n\t\tinputs = input\n\tdefault:\n\t\tinputs = []interface{}{input}\n\t}\n\n\tfor i, v := range inputs {\n\t\tif !structs.IsStruct(v) {\n\t\t\tcontinue\n\t\t}\n\t\tmv, err := struct2map(v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinputs[i] = mv\n\t}\n\treturn inputs, nil\n}\n\nfunc struct2map(v interface{}) (interface{}, error) {\n\tout := make(map[string]interface{})\n\tdata, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := json.Unmarshal(data, &out); err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}\n\nfunc ByGoJQ(input interface{}, query string, printer func(interface{}) error) (err error) ", "output": "{\n\tq, err := gojq.Parse(query)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"gojq parse failed: %v\", err)\n\t}\n\n\tmv, err := convertInputToMap(input)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to convert to map: %v\", err)\n\t}\n\titer := q.Run(mv)\n\n\tfor {\n\t\tv, ok := iter.Next()\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tif err, ok := v.(error); ok {\n\t\t\treturn fmt.Errorf(\"gojq: %s\", err.Error())\n\t\t}\n\t\tif err := printer(v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package middleware\n\nimport (\n\t\"github.com/drone/drone/shared/model\"\n\t\"github.com/zenazn/goji/web\"\n)\n\n\n\nfunc UserToC(c *web.C, user *model.User) {\n\tc.Env[\"user\"] = user\n}\n\n\n\nfunc RepoToC(c *web.C, repo *model.Repo) {\n\tc.Env[\"repo\"] = repo\n}\n\n\n\n\n\n\n\n\nfunc ToUser(c *web.C) *model.User {\n\tvar v = c.Env[\"user\"]\n\tif v == nil {\n\t\treturn nil\n\t}\n\tu, ok := v.(*model.User)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn u\n}\n\n\n\n\nfunc ToRepo(c *web.C) *model.Repo {\n\tvar v = c.Env[\"repo\"]\n\tif v == nil {\n\t\treturn nil\n\t}\n\tr, ok := v.(*model.Repo)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn r\n}\n\n\n\n\nfunc ToRole(c *web.C) *model.Perm {\n\tvar v = c.Env[\"role\"]\n\tif v == nil {\n\t\treturn nil\n\t}\n\tp, ok := v.(*model.Perm)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn p\n}\n\nfunc RoleToC(c *web.C, role *model.Perm) ", "output": "{\n\tc.Env[\"role\"] = role\n}"} {"input": "package goonix\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\n\n\n\n\nfunc TestFailedPortAvailable(t *testing.T) {\n\tn := Network{}\n\tretval, err := n.CheckPort(\"fuuuuuuu.com\", 99, 2*time.Second)\n\tif retval {\n\t\tt.Fail()\n\t}\n\tif err == nil {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestPortAvailable(t *testing.T) ", "output": "{\n\tn := Network{}\n\tretval, err := n.CheckPort(\"localhost\", 22, 2*time.Second)\n\tif !retval {\n\t\tt.Error(\"Expected true, got false\")\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Expected nil, got %v\", err)\n\t}\n\n}"} {"input": "package rllogger\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n)\n\nconst (\n\tLogDebug = 0\n\tLogInfo = 1\n\tLogWarn = 2\n\tLogError = 3\n\tLogTerminate = 4\n)\n\nvar silentLog bool = false\n\nfunc UseLogDebug() bool {\n\treturn (os.Getenv(\"RLLOG\") == \"DEBUG\")\n}\n\nfunc IsSilent() bool {\n\treturn silentLog || (os.Getenv(\"RLLOG\") == \"SILENT\")\n}\n\nfunc SetSilent(value bool) {\n\tsilentLog = value\n}\n\nfunc getPath() string {\n\tresult := \"\"\n\tif pc, file, line, ok := runtime.Caller(3); ok {\n\t\tname := filepath.Base(runtime.FuncForPC(pc).Name())\n\t\tresult = fmt.Sprintf(\"%s %s:%d\", name, file, line)\n\t}\n\treturn result\n}\n\n\n\nfunc Outputf(level int, format string, a ...interface{}) {\n\tif IsSilent() {\n\t\treturn\n\t}\n\tmsg := fmt.Sprintf(format, a...)\n\tOutput(level, msg)\n}\n\nfunc OutputLines(level int, label string, lines *[]string) {\n\tif IsSilent() {\n\t\treturn\n\t}\n\tmsg := fmt.Sprintf(\"%s:\\n\", label)\n\tfor _, line := range *lines {\n\t\tmsg = fmt.Sprintf(\"%s - %s\\n\", msg, line)\n\t}\n\tOutput(level, msg)\n}\n\nfunc Output(level int, msg string) ", "output": "{\n\tif IsSilent() {\n\t\treturn\n\t}\n\tswitch level {\n\tcase LogDebug:\n\t\t{\n\t\t\tif UseLogDebug() {\n\t\t\t\tlog.Printf(\"DEBUG-> %s - %s\\n\", getPath(), msg)\n\t\t\t}\n\t\t}\n\tcase LogInfo:\n\t\t{\n\t\t\tlog.Printf(\"INFO-> %s\\n\", msg)\n\t\t}\n\tcase LogWarn:\n\t\t{\n\t\t\tlog.Printf(\"WARN-> %s - %s\\n\", getPath(), msg)\n\t\t}\n\tcase LogError:\n\t\t{\n\t\t\tlog.Printf(\"ERROR-> %s - %s\\n\", getPath(), msg)\n\t\t}\n\tcase LogTerminate:\n\t\t{\n\t\t\tlog.Printf(\"FATAL-> %s - %s\\n\", getPath(), msg)\n\t\t\tpanic(\"terminate with fatal error!\")\n\t\t}\n\tdefault:\n\t\t{\n\t\t\tlog.Println(msg)\n\t\t}\n\t}\n}"} {"input": "package dockertools\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\tdocker \"github.com/fsouza/go-dockerclient\"\n\tkubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\"\n)\n\n\n\nconst (\n\tstatusRunningPrefix = \"Up\"\n\tstatusExitedPrefix = \"Exited\"\n)\n\nfunc mapState(state string) kubecontainer.ContainerState {\n\tswitch {\n\tcase strings.HasPrefix(state, statusRunningPrefix):\n\t\treturn kubecontainer.ContainerStateRunning\n\tcase strings.HasPrefix(state, statusExitedPrefix):\n\t\treturn kubecontainer.ContainerStateExited\n\tdefault:\n\t\treturn kubecontainer.ContainerStateUnknown\n\t}\n}\n\n\nfunc toRuntimeContainer(c *docker.APIContainers) (*kubecontainer.Container, error) {\n\tif c == nil {\n\t\treturn nil, fmt.Errorf(\"unable to convert a nil pointer to a runtime container\")\n\t}\n\n\tdockerName, hash, err := getDockerContainerNameInfo(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &kubecontainer.Container{\n\t\tID: kubecontainer.DockerID(c.ID).ContainerID(),\n\t\tName: dockerName.ContainerName,\n\t\tImage: c.Image,\n\t\tHash: hash,\n\t\tCreated: c.Created,\n\t\tState: mapState(c.Status),\n\t}, nil\n}\n\n\n\n\nfunc toRuntimeImage(image *docker.APIImages) (*kubecontainer.Image, error) ", "output": "{\n\tif image == nil {\n\t\treturn nil, fmt.Errorf(\"unable to convert a nil pointer to a runtime image\")\n\t}\n\n\treturn &kubecontainer.Image{\n\t\tID: image.ID,\n\t\tRepoTags: image.RepoTags,\n\t\tSize: image.VirtualSize,\n\t}, nil\n}"} {"input": "package ui\n\nimport (\n\t\"github.com/Bredgren/geo\"\n\t\"github.com/hajimehoshi/ebiten\"\n)\n\n\n\n\ntype VerticalContainer struct {\n\tElements []WeightedDrawer\n\tWt float64\n}\n\n\nfunc (v *VerticalContainer) Draw(dst *ebiten.Image, bounds geo.Rect) {\n\ttotalWeight := 0.0\n\tfor _, e := range v.Elements {\n\t\ttotalWeight += e.Weight()\n\t}\n\theights := make([]float64, len(v.Elements))\n\tfor i, e := range v.Elements {\n\t\theights[i] = e.Weight() / totalWeight * bounds.H\n\t}\n\tsubBounds := bounds\n\tfor i, h := range heights {\n\t\tsubBounds.H = h\n\t\tv.Elements[i].Draw(dst, subBounds)\n\t\tsubBounds.Y += h\n\t}\n}\n\n\nfunc (v *VerticalContainer) Weight() float64 {\n\treturn v.Wt\n}\n\n\n\n\ntype HorizontalContainer struct {\n\tElements []WeightedDrawer\n\tWt float64\n}\n\n\nfunc (h *HorizontalContainer) Draw(dst *ebiten.Image, bounds geo.Rect) {\n\ttotalWeight := 0.0\n\tfor _, e := range h.Elements {\n\t\ttotalWeight += e.Weight()\n\t}\n\twidths := make([]float64, len(h.Elements))\n\tfor i, e := range h.Elements {\n\t\twidths[i] = e.Weight() / totalWeight * bounds.W\n\t}\n\tsubBounds := bounds\n\tfor i, w := range widths {\n\t\tsubBounds.W = w\n\t\th.Elements[i].Draw(dst, subBounds)\n\t\tsubBounds.X += w\n\t}\n}\n\n\n\n\nfunc (h *HorizontalContainer) Weight() float64 ", "output": "{\n\treturn h.Wt\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/pressly/fresh/runner\"\n)\n\ntype flagStringSlice []string\n\n\n\nfunc (f *flagStringSlice) Set(value string) error {\n\t*f = append(*f, value)\n\treturn nil\n}\n\nfunc main() {\n\tvar watchList, excludeList runner.Multiflag\n\n\tconfigPath := flag.String(\"c\", \"\", \"config file path\")\n\tbuildArgs := flag.String(\"b\", \"\", \"build command line arguments\")\n\tvar runArgs flagStringSlice\n\tflag.Var(&runArgs, \"r\", \"run command line arguments\")\n\tbuildPath := flag.String(\"p\", \"\", \"root path - package that will be built & ran\")\n\toutputBinary := flag.String(\"o\", \"\", \"output (built) binary location\")\n\ttmpPath := flag.String(\"t\", \"\", \"tmp path\")\n\tflag.Var(&watchList, \"w\", \"watch path (recursive), repeat multiple times to watch multiple paths\")\n\tflag.Var(&excludeList, \"e\", \"exclude path (recursive), repeat multiple times to exclude multiple paths\")\n\tflag.Parse()\n\n\trunner.Start(configPath, buildArgs, runArgs, buildPath, outputBinary, tmpPath, watchList, excludeList)\n}\n\nfunc (f *flagStringSlice) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%v\", *f)\n}"} {"input": "package exporters\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"k8s.io/node-problem-detector/pkg/types\"\n)\n\n\n\nfunc TestGetExporterHandlerOrDie(t *testing.T) {\n\tfooExporterFactory := func(types.CommandLineOptions) types.Exporter {\n\t\treturn nil\n\t}\n\tfooExporterHandler := types.ExporterHandler{\n\t\tCreateExporterOrDie: fooExporterFactory,\n\t\tOptions: nil,\n\t}\n\n\tRegister(\"foo\", fooExporterHandler)\n\n\tassert.NotPanics(t, func() { GetExporterHandlerOrDie(\"foo\") })\n\tassert.Panics(t, func() { GetExporterHandlerOrDie(\"bar\") })\n\n\thandlers = make(map[types.ExporterType]types.ExporterHandler)\n}\n\nfunc TestRegistration(t *testing.T) ", "output": "{\n\tfooExporterFactory := func(types.CommandLineOptions) types.Exporter {\n\t\treturn nil\n\t}\n\tfooExporterHandler := types.ExporterHandler{\n\t\tCreateExporterOrDie: fooExporterFactory,\n\t\tOptions: nil,\n\t}\n\n\tbarExporterFactory := func(types.CommandLineOptions) types.Exporter {\n\t\treturn nil\n\t}\n\tbarExporterHandler := types.ExporterHandler{\n\t\tCreateExporterOrDie: barExporterFactory,\n\t\tOptions: nil,\n\t}\n\n\tRegister(\"foo\", fooExporterHandler)\n\tRegister(\"bar\", barExporterHandler)\n\n\texpectedExporterNames := []types.ExporterType{\"foo\", \"bar\"}\n\texporterNames := GetExporterNames()\n\tassert.ElementsMatch(t, expectedExporterNames, exporterNames)\n\n\thandlers = make(map[types.ExporterType]types.ExporterHandler)\n}"} {"input": "package server\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n)\n\ntype Rest struct {\n\tchannels map[string]*Channel\n}\n\nfunc NewRestServer(server *Server) *Rest {\n\treturn &Rest{server.channels}\n}\n\n\n\nfunc (self *Rest) restHandler(w http.ResponseWriter, r *http.Request) {\n\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err := r.Body.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\tchannel := r.URL.Query().Get(\"channel\")\n\tsession := r.Header.Get(\"session\");\n\n\tlog.Printf(\"SessionID: %s\", session)\n\n\tmsg := &Message{Channel: channel, Body: string(body), session: session}\n\tif ch, ok := self.channels[channel]; ok {\n\t\tch.sendAll <- msg\n\t}\n\tlog.Printf(\"[REST] body: %s, channel: %s\", body, channel)\n}\n\nfunc (self *Rest) ListenRest() {\n\n\tlog.Println(\"Listening server(REST)...\")\n\n\thttp.HandleFunc(\"/rest\", self.PostOnly(self.restHandler))\n}\n\nfunc (self *Rest) PostOnly(h http.HandlerFunc) http.HandlerFunc ", "output": "{\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == \"POST\" {\n\t\t\th(w, r)\n\t\t\treturn\n\t\t}\n\t\thttp.Error(w, \"post only\", http.StatusMethodNotAllowed)\n\t}\n}"} {"input": "package backingstore\n\nimport (\n\t\"github.com/gostor/gotgt/pkg/api\"\n\t\"github.com/gostor/gotgt/pkg/scsi\"\n)\n\nfunc init() {\n\tscsi.RegisterBackingStore(\"null\", newNull)\n}\n\ntype NullBackingStore struct {\n\tscsi.BaseBackingStore\n}\n\nfunc newNull() (api.BackingStore, error) {\n\treturn &NullBackingStore{\n\t\tBaseBackingStore: scsi.BaseBackingStore{\n\t\t\tName: \"null\",\n\t\t\tDataSize: 0,\n\t\t\tOflagsSupported: 0,\n\t\t},\n\t}, nil\n}\n\n\n\nfunc (bs *NullBackingStore) Close(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Init(dev *api.SCSILu, Opts string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Exit(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Size(dev *api.SCSILu) uint64 {\n\treturn 0\n}\n\nfunc (bs *NullBackingStore) Read(offset, tl int64) ([]byte, error) {\n\treturn nil, nil\n}\n\nfunc (bs *NullBackingStore) Write(wbuf []byte, offset int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataSync(offset, tl int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataAdvise(offset, length int64, advise uint32) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Unmap([]api.UnmapBlockDescriptor) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Open(dev *api.SCSILu, path string) error ", "output": "{\n\treturn nil\n}"} {"input": "package common\n\nimport (\n\t\"testing\"\n\n\t\"github.com/mitchellh/multistep\"\n)\n\nfunc TestStepSuppressMessages_impl(t *testing.T) {\n\tvar _ multistep.Step = new(StepSuppressMessages)\n}\n\n\n\nfunc TestStepSuppressMessages(t *testing.T) ", "output": "{\n\tstate := testState(t)\n\tstep := new(StepSuppressMessages)\n\n\tstate.Put(\"vmx_path\", \"foo\")\n\n\tdriver := state.Get(\"driver\").(*DriverMock)\n\n\tif action := step.Run(state); action != multistep.ActionContinue {\n\t\tt.Fatalf(\"bad action: %#v\", action)\n\t}\n\tif _, ok := state.GetOk(\"error\"); ok {\n\t\tt.Fatal(\"should NOT have error\")\n\t}\n\n\tif !driver.SuppressMessagesCalled {\n\t\tt.Fatal(\"should've called\")\n\t}\n\tif driver.SuppressMessagesPath != \"foo\" {\n\t\tt.Fatal(\"should call with right path\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/rpc\"\n)\n\n\nfunc defaultHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"

Hello %s!

\", r.URL.Path[1:])\n}\n\ntype Args struct {\n\tA, B int\n}\n\n\ntype Arith int\n\n\nfunc (t *Arith) Multiply(args *Args, reply *int) error {\n\t*reply = args.A * args.B\n\treturn nil\n}\n\n\n\nfunc main() {\n\tarith := new(Arith)\n\terr := rpc.Register(arith)\n\tif err != nil {\n\t\tlog.Fatal(\"Service Error: %s\", err)\n\t}\n\trpc.HandleHTTP()\n\n\tl, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", 57439))\n\n\tif err != nil {\n\t\tlog.Fatal(\"TCP Error: %s\", err)\n\t}\n\tlog.Println(\"ok\")\n\thttp.Serve(l, nil)\n}\n\nfunc (t *Arith) Add(args *Args, reply *int) error ", "output": "{\n\t*reply = args.A + args.B\n\treturn nil\n}"} {"input": "package network\n\nimport (\n\t\"context\"\n\t\"sort\"\n\n\t\"github.com/docker/cli/cli\"\n\t\"github.com/docker/cli/cli/command\"\n\t\"github.com/docker/cli/cli/command/formatter\"\n\t\"github.com/docker/cli/opts\"\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/fvbommel/sortorder\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype listOptions struct {\n\tquiet bool\n\tnoTrunc bool\n\tformat string\n\tfilter opts.FilterOpt\n}\n\nfunc newListCommand(dockerCli command.Cli) *cobra.Command {\n\toptions := listOptions{filter: opts.NewFilterOpt()}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"ls [OPTIONS]\",\n\t\tAliases: []string{\"list\"},\n\t\tShort: \"List networks\",\n\t\tArgs: cli.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn runList(dockerCli, options)\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\tflags.BoolVarP(&options.quiet, \"quiet\", \"q\", false, \"Only display network IDs\")\n\tflags.BoolVar(&options.noTrunc, \"no-trunc\", false, \"Do not truncate the output\")\n\tflags.StringVar(&options.format, \"format\", \"\", \"Pretty-print networks using a Go template\")\n\tflags.VarP(&options.filter, \"filter\", \"f\", \"Provide filter values (e.g. 'driver=bridge')\")\n\n\treturn cmd\n}\n\n\n\nfunc runList(dockerCli command.Cli, options listOptions) error ", "output": "{\n\tclient := dockerCli.Client()\n\tlistOptions := types.NetworkListOptions{Filters: options.filter.Value()}\n\tnetworkResources, err := client.NetworkList(context.Background(), listOptions)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tformat := options.format\n\tif len(format) == 0 {\n\t\tif len(dockerCli.ConfigFile().NetworksFormat) > 0 && !options.quiet {\n\t\t\tformat = dockerCli.ConfigFile().NetworksFormat\n\t\t} else {\n\t\t\tformat = formatter.TableFormatKey\n\t\t}\n\t}\n\n\tsort.Slice(networkResources, func(i, j int) bool {\n\t\treturn sortorder.NaturalLess(networkResources[i].Name, networkResources[j].Name)\n\t})\n\n\tnetworksCtx := formatter.Context{\n\t\tOutput: dockerCli.Out(),\n\t\tFormat: NewFormat(format, options.quiet),\n\t\tTrunc: !options.noTrunc,\n\t}\n\treturn FormatWrite(networksCtx, networkResources)\n}"} {"input": "package btcwallet\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/lightningnetwork/lnd/lnwallet\"\n)\n\nconst (\n\twalletType = \"btcwallet\"\n)\n\n\n\n\n\n\n\n\n\nfunc init() {\n\tdriver := &lnwallet.WalletDriver{\n\t\tWalletType: walletType,\n\t\tNew: createNewWallet,\n\t}\n\n\tif err := lnwallet.RegisterWallet(driver); err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to register wallet driver '%s': %v\",\n\t\t\twalletType, err))\n\t}\n}\n\nfunc createNewWallet(args ...interface{}) (lnwallet.WalletController, error) ", "output": "{\n\tif len(args) != 1 {\n\t\treturn nil, fmt.Errorf(\"incorrect number of arguments to .New(...), \"+\n\t\t\t\"expected 1, instead passed %v\", len(args))\n\t}\n\n\tconfig, ok := args[0].(*Config)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"first argument to btcdnotifier.New is \" +\n\t\t\t\"incorrect, expected a *rpcclient.ConnConfig\")\n\t}\n\n\treturn New(*config)\n}"} {"input": "package client\n\nimport (\n\t\"math\"\n\t\"math/rand\"\n\t\"time\"\n\n\t\"github.com/paybyphone/kintail/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype DefaultRetryer struct {\n\tNumMaxRetries int\n}\n\n\n\nfunc (d DefaultRetryer) MaxRetries() int {\n\treturn d.NumMaxRetries\n}\n\n\nfunc (d DefaultRetryer) RetryRules(r *request.Request) time.Duration {\n\tdelay := int(math.Pow(2, float64(r.RetryCount))) * (rand.Intn(30) + 30)\n\treturn time.Duration(delay) * time.Millisecond\n}\n\n\n\n\nfunc (d DefaultRetryer) ShouldRetry(r *request.Request) bool ", "output": "{\n\tif r.HTTPResponse.StatusCode >= 500 {\n\t\treturn true\n\t}\n\treturn r.IsErrorRetryable()\n}"} {"input": "package minicon\n\nimport \"container/ring\"\n\n\n\n\ntype History struct {\n\tr *ring.Ring\n}\n\n\n\n\ntype HistoryMarker *ring.Ring\n\n\n\n\nfunc NewHistory(capacity int) *History {\n\treturn &History{ring.New(capacity)}\n}\n\n\n\n\n\n\nfunc (hs *History) Add(s string, mark HistoryMarker) HistoryMarker {\n\ths.Restore(mark)\n\tif s != \"\" && hs.r.Value != s {\n\t\ths.r.Value = s\n\t\ths.r = hs.r.Next()\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (hs *History) Back() (string, bool) {\n\treturn hs._update(hs.r.Prev())\n}\n\n\n\n\n\n\n\n\n\n\nfunc (hs *History) Mark() HistoryMarker {\n\treturn hs.r\n}\n\n\n\n\nfunc (hs *History) Restore(mark HistoryMarker) {\n\tif mark != nil {\n\t\ths.r = mark\n\t}\n}\n\n\n\n\nfunc (hs *History) _update(r *ring.Ring) (ret string, okay bool) {\n\tif s, ok := r.Value.(string); ok && s != \"\" {\n\t\ths.r = r\n\t\tret, okay = s, ok\n\t}\n\treturn ret, okay\n}\n\nfunc (hs *History) Forward() (string, bool) ", "output": "{\n\treturn hs._update(hs.r.Next())\n}"} {"input": "package types\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"sigs.k8s.io/kustomize/kyaml/resid\"\n)\n\nconst DefaultReplacementFieldPath = \"metadata.name\"\n\n\n\ntype Replacement struct {\n\tSource *SourceSelector `json:\"source\" yaml:\"source\"`\n\n\tTargets []*TargetSelector `json:\"targets\" yaml:\"targets\"`\n}\n\n\ntype SourceSelector struct {\n\tresid.ResId `json:\",inline,omitempty\" yaml:\",inline,omitempty\"`\n\n\tFieldPath string `json:\"fieldPath\" yaml:\"fieldPath\"`\n\n\tOptions *FieldOptions `json:\"options\" yaml:\"options\"`\n}\n\nfunc (s *SourceSelector) String() string {\n\tif s == nil {\n\t\treturn \"\"\n\t}\n\tresult := []string{s.ResId.String()}\n\tif s.FieldPath != \"\" {\n\t\tresult = append(result, s.FieldPath)\n\t}\n\tif opts := s.Options.String(); opts != \"\" {\n\t\tresult = append(result, opts)\n\t}\n\treturn strings.Join(result, \":\")\n}\n\n\ntype TargetSelector struct {\n\tSelect *Selector `json:\"select\" yaml:\"select\"`\n\n\tReject []*Selector `json:\"reject\" yaml:\"reject\"`\n\n\tFieldPaths []string `json:\"fieldPaths\" yaml:\"fieldPaths\"`\n\n\tOptions *FieldOptions `json:\"options\" yaml:\"options\"`\n}\n\n\ntype FieldOptions struct {\n\tDelimiter string `json:\"delimiter\" yaml:\"delimiter\"`\n\n\tIndex int `json:\"index\" yaml:\"index\"`\n\n\tEncoding string `json:\"encoding\" yaml:\"encoding\"`\n\n\tCreate bool `json:\"create\" yaml:\"create\"`\n}\n\n\n\nfunc (fo *FieldOptions) String() string ", "output": "{\n\tif fo == nil || fo.Delimiter == \"\" {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%s(%d)\", fo.Delimiter, fo.Index)\n}"} {"input": "package gospec\n\nimport (\n\t\"fmt\"\n\tfilepath \"path\"\n\t\"runtime\"\n)\n\ntype Location struct {\n\tname string\n\tfile string\n\tline int\n}\n\nfunc currentLocation() *Location {\n\treturn newLocation(1)\n}\n\nfunc callerLocation() *Location {\n\treturn newLocation(2)\n}\n\nfunc newLocation(n int) *Location {\n\tif pc, _, _, ok := runtime.Caller(n + 1); ok {\n\t\treturn locationForPC(pc)\n\t}\n\treturn nil\n}\n\nfunc locationForPC(pc uintptr) *Location {\n\tpc = pcOfWhereCallWasMade(pc)\n\tf := runtime.FuncForPC(pc)\n\tname := f.Name()\n\tfile, line := f.FileLine(pc)\n\treturn &Location{name, file, line}\n}\n\n\n\n\n\n\n\n\nfunc pcOfWhereCallWasMade(pcOfWhereCallReturnsTo uintptr) uintptr {\n\treturn pcOfWhereCallReturnsTo - 1\n}\n\nfunc (this *Location) Name() string { return this.name }\nfunc (this *Location) File() string { return this.file }\nfunc (this *Location) FileName() string { return filename(this.file) }\n\n\nfunc filename(path string) string {\n\t_, file := filepath.Split(path)\n\treturn file\n}\n\nfunc (this *Location) equals(that *Location) bool {\n\treturn this.name == that.name &&\n\t\tthis.file == that.file &&\n\t\tthis.line == that.line\n}\n\nfunc (this *Location) String() string {\n\treturn fmt.Sprintf(\"%v:%v\", this.FileName(), this.Line())\n}\n\nfunc (this *Location) Line() int ", "output": "{ return this.line }"} {"input": "package serial\n\nimport (\n\t\"flag\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"golang.org/x/net/context\"\n)\n\ntype connect struct {\n\t*flags.VirtualMachineFlag\n\n\tdevice string\n\tclient bool\n}\n\nfunc init() {\n\tcli.Register(\"device.serial.connect\", &connect{})\n}\n\nfunc (cmd *connect) Register(f *flag.FlagSet) {\n\tf.StringVar(&cmd.device, \"device\", \"\", \"serial port device name\")\n\tf.BoolVar(&cmd.client, \"client\", false, \"Use client direction\")\n}\n\nfunc (cmd *connect) Process() error { return nil }\n\n\n\nfunc (cmd *connect) Run(f *flag.FlagSet) error ", "output": "{\n\tvm, err := cmd.VirtualMachine()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif vm == nil {\n\t\treturn flag.ErrHelp\n\t}\n\n\tdevices, err := vm.Device(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td, err := devices.FindSerialPort(cmd.device)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn vm.EditDevice(context.TODO(), devices.ConnectSerialPort(d, f.Arg(0), cmd.client))\n}"} {"input": "package loads\n\nimport \"jvmgo/ch09/instructions/base\"\nimport \"jvmgo/ch09/rtda\"\n\n\ntype ILOAD struct{ base.Index8Instruction }\n\nfunc (self *ILOAD) Execute(frame *rtda.Frame) {\n\t_iload(frame, self.Index)\n}\n\ntype ILOAD_0 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_0) Execute(frame *rtda.Frame) {\n\t_iload(frame, 0)\n}\n\ntype ILOAD_1 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_1) Execute(frame *rtda.Frame) {\n\t_iload(frame, 1)\n}\n\ntype ILOAD_2 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_2) Execute(frame *rtda.Frame) {\n\t_iload(frame, 2)\n}\n\ntype ILOAD_3 struct{ base.NoOperandsInstruction }\n\nfunc (self *ILOAD_3) Execute(frame *rtda.Frame) {\n\t_iload(frame, 3)\n}\n\n\n\nfunc _iload(frame *rtda.Frame, index uint) ", "output": "{\n\tval := frame.LocalVars().GetInt(index)\n\tframe.OperandStack().PushInt(val)\n}"} {"input": "package openapi\n\nimport (\n\t\"net/http\"\n)\n\n\ntype APIResponse struct {\n\t*http.Response `json:\"-\"`\n\tMessage string `json:\"message,omitempty\"`\n\tOperation string `json:\"operation,omitempty\"`\n\tRequestURL string `json:\"url,omitempty\"`\n\tMethod string `json:\"method,omitempty\"`\n\tPayload []byte `json:\"-\"`\n}\n\n\nfunc NewAPIResponse(r *http.Response) *APIResponse {\n\n\tresponse := &APIResponse{Response: r}\n\treturn response\n}\n\n\n\n\nfunc NewAPIResponseWithError(errorMessage string) *APIResponse ", "output": "{\n\n\tresponse := &APIResponse{Message: errorMessage}\n\treturn response\n}"} {"input": "package pitchfork\n\n\n\nimport (\n\t\"errors\"\n)\n\ntype OAuth_Auth struct {\n\tClientID string `label:\"Client ID\" pfset:\"nobody\" pfget:\"none\"`\n\tScope string `label:\"Scope\" pfset:\"nobody\" pfget:\"none\"`\n\tRType string `label:\"Request Type\" pfset:\"nobody\" pfget:\"none\"`\n\tRedirect string `label:\"Redirect URL\" pfset:\"nobody\" pfget:\"none\"`\n\tAuth string `label:\"Authorize\" pftype:\"submit\"`\n\tDeny string `label:\"Deny\" pftype:\"submit\" htmlclass:\"deny\"`\n}\n\ntype OAuth2Claims struct {\n\tJWTClaims\n\tClientID string `json:\"oa_client_id\"`\n\tScope string `json:\"oa_scope\"`\n\tRType string `json:\"oa_rtype,omitempty\"`\n\tRedirect string `json:\"oa_redirect,omitempty\"`\n}\n\nfunc OAuth2_AuthToken_New(ctx PfCtx, o OAuth_Auth) (tok string, err error) {\n\tif !ctx.IsLoggedIn() {\n\t\ttok = \"\"\n\t\terr = errors.New(\"Not authenticated\")\n\t\treturn\n\t}\n\n\tclaims := &OAuth2Claims{}\n\tclaims.ClientID = o.ClientID\n\tclaims.Scope = o.Scope\n\tclaims.RType = o.RType\n\tclaims.Redirect = o.Redirect\n\n\tusername := ctx.TheUser().GetUserName()\n\n\ttoken := Token_New(\"oauth_auth\", username, 1, claims)\n\ttok, err = token.Sign()\n\treturn\n}\n\nfunc OAuth2_AuthToken_Check(tok string) (claims *OAuth2Claims, err error) {\n\t_, err = Token_Parse(tok, \"oauth_auth\", claims)\n\treturn\n}\n\n\n\nfunc OAuth2_AccessToken_New(ctx PfCtx, client_id string, scope string) (tok string, err error) ", "output": "{\n\tif !ctx.IsLoggedIn() {\n\t\ttok = \"\"\n\t\terr = errors.New(\"Not authenticated\")\n\t\treturn\n\t}\n\n\tclaims := &OAuth2Claims{}\n\tclaims.ClientID = client_id\n\tclaims.Scope = scope\n\n\tusername := ctx.TheUser().GetUserName()\n\n\ttoken := Token_New(\"oauth_access\", username, TOKEN_EXPIRATIONMINUTES, claims)\n\n\ttok, err = token.Sign()\n\treturn\n}"} {"input": "package console\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"unsafe\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\nconst (\n\tcmdTcGet = unix.TCGETS\n\tcmdTcSet = unix.TCSETS\n)\n\n\n\n\n\nfunc unlockpt(f *os.File) error {\n\tvar u int32\n\treturn ioctl(f.Fd(), unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&u)))\n}\n\n\nfunc ptsname(f *os.File) (string, error) {\n\tn, err := unix.IoctlGetInt(int(f.Fd()), unix.TIOCGPTN)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"/dev/pts/%d\", n), nil\n}\n\nfunc ioctl(fd, flag, data uintptr) error ", "output": "{\n\tif _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, flag, data); err != 0 {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package conversions\n\nimport \"jvmgo/ch11/instructions/base\"\nimport \"jvmgo/ch11/rtda\"\n\n\ntype L2D struct{ base.NoOperandsInstruction }\n\n\n\n\ntype L2F struct{ base.NoOperandsInstruction }\n\nfunc (self *L2F) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tl := stack.PopLong()\n\tf := float32(l)\n\tstack.PushFloat(f)\n}\n\n\ntype L2I struct{ base.NoOperandsInstruction }\n\nfunc (self *L2I) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tl := stack.PopLong()\n\ti := int32(l)\n\tstack.PushInt(i)\n}\n\nfunc (self *L2D) Execute(frame *rtda.Frame) ", "output": "{\n\tstack := frame.OperandStack()\n\tl := stack.PopLong()\n\td := float64(l)\n\tstack.PushDouble(d)\n}"} {"input": "package client\n\nimport \"testing\"\n\nvar emptySyncGroupRequestBytes = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}\nvar goodSyncGroupRequestBytes = []byte{0x00, 0x03, 'f', 'o', 'o', 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 'b', 'a', 'r', 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 'f', 'o', 'o', 0x00, 0x00, 0x00, 0x01, 0x01}\n\nvar errorSyncGroupResponseBytes = []byte{0x00, 27, 0x00, 0x00, 0x00, 0x00}\nvar goodSyncGroupResponseBytes = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01}\n\nfunc TestSyncGroupRequest(t *testing.T) {\n\temptySyncGroupRequest := new(SyncGroupRequest)\n\ttestRequest(t, emptySyncGroupRequest, emptySyncGroupRequestBytes)\n\n\tgoodSyncGroupRequest := new(SyncGroupRequest)\n\tgoodSyncGroupRequest.GroupID = \"foo\"\n\tgoodSyncGroupRequest.GenerationID = 3\n\tgoodSyncGroupRequest.MemberID = \"bar\"\n\tgoodSyncGroupRequest.GroupAssignment = map[string][]byte{\n\t\t\"foo\": {1},\n\t}\n\ttestRequest(t, goodSyncGroupRequest, goodSyncGroupRequestBytes)\n}\n\n\n\nfunc TestSyncGroupResponse(t *testing.T) ", "output": "{\n\terrorSyncGroupResponse := new(SyncGroupResponse)\n\tdecode(t, errorSyncGroupResponse, errorSyncGroupResponseBytes)\n\tassert(t, errorSyncGroupResponse.Error, ErrRebalanceInProgress)\n\n\tgoodSyncGroupResponse := new(SyncGroupResponse)\n\tdecode(t, goodSyncGroupResponse, goodSyncGroupResponseBytes)\n\tassert(t, goodSyncGroupResponse.Error, ErrNoError)\n\tassert(t, goodSyncGroupResponse.MemberAssignment, []byte{1})\n}"} {"input": "package inigo\n\nimport (\n\t\"errors\"\n)\n\n\nfunc (config *Config) GetConfigFilename() string {\n\treturn config.filename\n}\n\n\nfunc (config *Config) GetAllSections() []string {\n\tvar res []string\n\n\tfor key, _ := range config.config {\n\t\tres = append(res, key)\n\t}\n\n\treturn res\n}\n\n\n\n\n\nfunc (config *Config) GetValue(section, key string) (string, error) {\n\tvar processing bool = true\n\tvar currentSection string = section\n\tvar res string\n\n\tfor processing && len(currentSection) > 0 {\n\t\tres = config.config[currentSection].data[key]\n\n\t\tif len(res) > 0 {\n\t\t\tprocessing = false\n\t\t\tbreak\n\t\t} else {\n\t\t\tcurrentSection = config.config[currentSection].inheritSection\n\t\t}\n\t}\n\n\tif len(res) == 0 {\n\t\treturn res, errors.New(\"Has no key\")\n\t}\n\n\treturn res, nil\n}\n\nfunc (config *Config) GetAllKeys() map[string][]string ", "output": "{\n\tvar res map[string][]string = make(map[string][]string)\n\n\tfor section, data := range config.config {\n\t\tfor key, _ := range data.data {\n\t\t\tres[section] = append(res[section], key)\n\t\t}\n\t}\n\n\treturn res\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype geometry interface {\n\tarea() float64\n\tperim() float64\n}\n\ntype square struct {\n\twidth, heigth float64\n}\n\ntype circle struct {\n\tradius float64\n}\n\nfunc (s square) area() float64 {\n\treturn s.width * s.heigth\n}\n\nfunc (s square) perim() float64 {\n\treturn 2*s.width + 2*s.heigth\n}\n\nfunc (c circle) area() float64 {\n\treturn math.Pi * c.radius * c.radius\n}\n\nfunc (c circle) perim() float64 {\n\treturn 2 * math.Pi * c.radius\n}\n\n\n\nfunc main() {\n\ts := square{width: 3, heigth: 4}\n\tc := circle{radius: 5}\n\n\tmeasure(s)\n\tmeasure(c)\n}\n\nfunc measure(g geometry) ", "output": "{\n\tfmt.Println(g)\n\tfmt.Println(g.area())\n\tfmt.Println(g.perim())\n}"} {"input": "package models\n\n\ntype DefaultTrigger struct{}\n\n\n\n\nfunc (dt DefaultTrigger) IsTriggered(times interface{}, user interface{}) bool ", "output": "{\n\treturn true\n}"} {"input": "package main\n\nimport (\n\t\"net\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\ntype UDPScanner struct {\n\tbuf []byte\n\ttext string\n\terr error\n\tsConn *net.UDPConn\n}\n\n\n\nfunc NewUDPScanner(port string) (*UDPScanner, error) {\n\tsAddr, err := net.ResolveUDPAddr(\"udp\", \":\"+port)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"udp scanner\")\n\t}\n\n\tsConn, err := net.ListenUDP(\"udp\", sAddr)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"udp scanner\")\n\t}\n\n\treturn &UDPScanner{\n\t\tbuf: make([]byte, 1024),\n\t\tsConn: sConn,\n\t}, nil\n}\n\n\nfunc (s *UDPScanner) Scan() bool {\n\tn, err := s.sConn.Read(s.buf)\n\tif err != nil {\n\t\ts.err = errors.Wrap(err, \"udp scan\")\n\t\treturn false\n\t}\n\n\ts.text = string(s.buf[0:n])\n\n\treturn true\n}\n\n\n\n\n\nfunc (s *UDPScanner) Err() error {\n\treturn s.err\n}\n\nfunc (s *UDPScanner) Text() string ", "output": "{\n\treturn s.text\n}"} {"input": "package system \n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\nfunc MkdirAllWithACL(path string, perm os.FileMode, sddl string) error {\n\treturn os.MkdirAll(path, perm)\n}\n\n\n\nfunc MkdirAll(path string, perm os.FileMode) error {\n\treturn os.MkdirAll(path, perm)\n}\n\n\nfunc IsAbs(path string) bool {\n\treturn filepath.IsAbs(path)\n}\n\n\n\n\n\n\n\n\n\nfunc CreateSequential(name string) (*os.File, error) {\n\treturn os.Create(name)\n}\n\n\n\n\n\nfunc OpenSequential(name string) (*os.File, error) {\n\treturn os.Open(name)\n}\n\n\n\n\n\n\nfunc OpenFileSequential(name string, flag int, perm os.FileMode) (*os.File, error) {\n\treturn os.OpenFile(name, flag, perm)\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc TempFileSequential(dir, prefix string) (f *os.File, err error) ", "output": "{\n\treturn ioutil.TempFile(dir, prefix)\n}"} {"input": "package model\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/utils\"\n\n\t\"strings\"\n)\n\n\ntype Ipv6Bandwidth struct {\n\n\tId *string `json:\"id,omitempty\"`\n}\n\n\n\nfunc (o Ipv6Bandwidth) String() string ", "output": "{\n\tdata, err := utils.Marshal(o)\n\tif err != nil {\n\t\treturn \"Ipv6Bandwidth struct{}\"\n\t}\n\n\treturn strings.Join([]string{\"Ipv6Bandwidth\", string(data)}, \" \")\n}"} {"input": "package log4me\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n)\n\ntype LoggerI struct {\n\tEnabled bool\n}\n\nfunc (l LoggerI) Info(v ...interface{}) {\n\tif !l.Enabled {\n\t\treturn\n\t}\n\n\tfmt.Fprintln(ioutil.Discard, v...)\n\n}\n\nfunc (l LoggerI) String() string {\n\tif l.Enabled {\n\t\treturn \"LoggerI: Enabled\"\n\t}\n\treturn \"LoggerI: Disabled\"\n}\n\ntype LoggerF struct {\n\tEnabled bool\n}\n\ntype F func()\n\n\n\nfunc (l LoggerF) String() string {\n\tif l.Enabled {\n\t\treturn \"LoggerF: Enabled\"\n\t}\n\treturn \"LoggerF: Disabled\"\n}\n\nfunc (l LoggerF) Info(f F) ", "output": "{\n\tif l.Enabled {\n\t\tf()\n\t}\n}"} {"input": "package iso20022\n\n\ntype AmountAndDirection55 struct {\n\n\tAmount *RestrictedFINActiveOrHistoricCurrencyAndAmount `xml:\"Amt\"`\n\n\tCreditDebitIndicator *CreditDebitCode `xml:\"CdtDbtInd,omitempty\"`\n\n\tOriginalCurrencyAndOrderedAmount *RestrictedFINActiveOrHistoricCurrencyAndAmount `xml:\"OrgnlCcyAndOrdrdAmt,omitempty\"`\n\n\tForeignExchangeDetails *ForeignExchangeTerms23 `xml:\"FXDtls,omitempty\"`\n}\n\nfunc (a *AmountAndDirection55) SetAmount(value, currency string) {\n\ta.Amount = NewRestrictedFINActiveOrHistoricCurrencyAndAmount(value, currency)\n}\n\nfunc (a *AmountAndDirection55) SetCreditDebitIndicator(value string) {\n\ta.CreditDebitIndicator = (*CreditDebitCode)(&value)\n}\n\n\n\nfunc (a *AmountAndDirection55) AddForeignExchangeDetails() *ForeignExchangeTerms23 {\n\ta.ForeignExchangeDetails = new(ForeignExchangeTerms23)\n\treturn a.ForeignExchangeDetails\n}\n\nfunc (a *AmountAndDirection55) SetOriginalCurrencyAndOrderedAmount(value, currency string) ", "output": "{\n\ta.OriginalCurrencyAndOrderedAmount = NewRestrictedFINActiveOrHistoricCurrencyAndAmount(value, currency)\n}"} {"input": "package agentclient_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestAgentclient(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Agent Client Suite\")\n}"} {"input": "package session\n\nimport (\n\t\"github.com/coyim/coyim/xmpp/data\"\n)\n\nconst (\n\tMUCStatusJIDPublic = 100\n\tMUCStatusAffiliationChanged = 101\n\tMUCStatusUnavailableShown = 102\n\tMUCStatusUnavailableNotShown = 103\n\tMUCStatusConfigChanged = 104\n\tMUCStatusSelfPresence = 110\n\tMUCStatusRoomLoggingEnabled = 170\n\tMUCStatusRoomLoggingDisabled = 171\n\tMUCStatusRoomNonAnonymous = 172\n\tMUCStatusRoomSemiAnonymous = 173\n\tMUCStatusRoomFullyAnonymous = 174\n\tMUCStatusRoomCreated = 201\n\tMUCStatusNicknameAssigned = 210\n\tMUCStatusBanned = 301\n\tMUCStatusNewNickname = 303\n\tMUCStatusBecauseKickedFrom = 307\n\tMUCStatusRemovedBecauseAffiliationChanged = 321\n\tMUCStatusRemovedBecauseNotMember = 322\n\tMUCStatusRemovedBecauseShutdown = 332\n)\n\ntype mucUserStatuses []data.MUCUserStatus\n\n\nfunc (mus mucUserStatuses) contains(c ...int) bool {\n\tfor _, cc := range c {\n\t\tif !mus.containsOne(cc) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (mus mucUserStatuses) containsAny(c ...int) bool {\n\tfor _, cc := range c {\n\t\tif mus.containsOne(cc) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (mus mucUserStatuses) containsOne(c int) bool {\n\tfor _, s := range mus {\n\t\tif s.Code == c {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc (mus mucUserStatuses) isEmpty() bool ", "output": "{\n\treturn len(mus) == 0\n}"} {"input": "package runtime\n\nimport \"unsafe\"\n\n\n\n\nfunc readUnaligned64(p unsafe.Pointer) uint64 {\n\tq := (*[8]byte)(p)\n\treturn uint64(q[0]) + uint64(q[1])<<8 + uint64(q[2])<<16 + uint64(q[3])<<24 + uint64(q[4])<<32 + uint64(q[5])<<40 + uint64(q[6])<<48 + uint64(q[7])<<56\n}\n\nfunc readUnaligned32(p unsafe.Pointer) uint32 ", "output": "{\n\tq := (*[4]byte)(p)\n\treturn uint32(q[0]) + uint32(q[1])<<8 + uint32(q[2])<<16 + uint32(q[3])<<24\n}"} {"input": "package metrics\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/bazelbuild/continuous-integration/metrics/data\"\n\t\"github.com/google/go-github/github\"\n\t\"golang.org/x/oauth2\"\n)\n\ntype ReleaseDownloads struct {\n\torg string\n\trepo string\n\tclient *github.Client\n\tminSizeBytes int\n\tcolumns []Column\n}\n\nfunc (rd *ReleaseDownloads) Name() string {\n\treturn \"release_downloads\"\n}\n\nfunc (rd *ReleaseDownloads) Columns() []Column {\n\treturn rd.columns\n}\n\nfunc (rd *ReleaseDownloads) Collect() (data.DataSet, error) {\n\tall_releases, err := rd.getReleases()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to get releases for %s/%s: %v\", rd.org, rd.repo, err)\n\t}\n\n\tresult := data.CreateDataSet(GetColumnNames(rd.columns))\n\tfor _, release := range all_releases {\n\t\tfor _, asset := range release.Assets {\n\t\t\tif *asset.Size >= rd.minSizeBytes {\n\t\t\t\tresult.AddRow(*release.TagName, *asset.Name, *asset.DownloadCount)\n\t\t\t}\n\t\t}\n\t}\n\treturn result, nil\n}\n\n\n\n\nfunc CreateReleaseDownloads(org string, repo string, token string, minSizeBytes int) *ReleaseDownloads {\n\tctx := context.Background()\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: token},\n\t)\n\ttc := oauth2.NewClient(ctx, ts)\n\n\tclient := github.NewClient(tc)\n\tcolumns := []Column{Column{\"release_name\", true}, Column{\"artifact\", true}, Column{\"downloads\", false}}\n\treturn &ReleaseDownloads{org: org, repo: repo, client: client, minSizeBytes: minSizeBytes, columns: columns}\n}\n\nfunc (rd *ReleaseDownloads) getReleases() ([]*github.RepositoryRelease, error) ", "output": "{\n\tall_releases := make([]*github.RepositoryRelease, 0)\n\tctx := context.Background()\n\topt := github.ListOptions{Page: 1, PerPage: 100}\n\tcurrPage := 1\n\tlastPage := 1\n\n\tfor currPage <= lastPage {\n\t\treleases, response, err := rd.client.Repositories.ListReleases(ctx, rd.org, rd.repo, &opt)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Could not get page %d: %v\", currPage, err)\n\t\t}\n\n\t\tall_releases = append(all_releases, releases...)\n\t\tcurrPage += 1\n\t\topt.Page = currPage\n\t\tlastPage = response.LastPage\n\t}\n\n\treturn all_releases, nil\n}"} {"input": "package customer\n\nimport (\n\t\"github.com/corestoreio/csfw/eav\"\n\t\"github.com/corestoreio/csfw/storage/csdb\"\n)\n\ntype (\n\tAddressModel struct {\n\t}\n)\n\nvar (\n\t_ eav.EntityTypeModeller = (*AddressModel)(nil)\n\t_ eav.EntityTypeTabler = (*AddressModel)(nil)\n\t_ eav.EntityTypeAdditionalAttributeTabler = (*AddressModel)(nil)\n\t_ eav.EntityTypeIncrementModeller = (*AddressModel)(nil)\n)\n\nfunc (c *AddressModel) TBD() {\n\n}\n\nfunc (c *AddressModel) TableNameBase() string {\n\treturn TableCollection.Name(TableIndexAddressEntity)\n}\n\nfunc (c *AddressModel) TableNameValue(i eav.ValueIndex) string {\n\ts, err := GetAddressValueStructure(i)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s.Name\n}\n\n\n\n\n\nfunc (c *AddressModel) TableEavWebsite() (*csdb.Table, error) {\n\treturn TableCollection.Structure(TableIndexEAVAttributeWebsite)\n}\n\nfunc Address() *AddressModel {\n\treturn &AddressModel{}\n}\n\nfunc (c *AddressModel) TableAdditionalAttribute() (*csdb.Table, error) ", "output": "{\n\treturn TableCollection.Structure(TableIndexEAVAttribute)\n}"} {"input": "package connect\n\nimport \"io\"\nimport \"github.com/LilyPad/GoLilyPad/packet\"\n\ntype RequestAuthenticate struct {\n\tUsername string\n\tPassword string\n}\n\n\n\nfunc (this *RequestAuthenticate) Id() int {\n\treturn REQUEST_AUTHENTICATE\n}\n\ntype requestAuthenticateCodec struct {\n\n}\n\nfunc (this *requestAuthenticateCodec) Decode(reader io.Reader) (request Request, err error) {\n\trequestAuthenticate := new(RequestAuthenticate)\n\trequestAuthenticate.Username, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\trequestAuthenticate.Password, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\trequest = requestAuthenticate\n\treturn\n}\n\nfunc (this *requestAuthenticateCodec) Encode(writer io.Writer, request Request) (err error) {\n\trequestAuthenticate := request.(*RequestAuthenticate)\n\terr = packet.WriteString(writer, requestAuthenticate.Username)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = packet.WriteString(writer, requestAuthenticate.Password)\n\treturn\n}\n\ntype ResultAuthenticate struct {\n\n}\n\nfunc NewResultAuthenticate() (this *ResultAuthenticate) {\n\tthis = new(ResultAuthenticate)\n\treturn\n}\n\nfunc (this *ResultAuthenticate) Id() int {\n\treturn REQUEST_AUTHENTICATE\n}\n\ntype resultAuthenticateCodec struct {\n\n}\n\nfunc (this *resultAuthenticateCodec) Decode(reader io.Reader) (result Result, err error) {\n\tresult = new(ResultAuthenticate)\n\treturn\n}\n\nfunc (this *resultAuthenticateCodec) Encode(writer io.Writer, result Result) (err error) {\n\treturn\n}\n\nfunc NewRequestAuthenticate(username string, password string) (this *RequestAuthenticate) ", "output": "{\n\tthis = new(RequestAuthenticate)\n\tthis.Username = username\n\tthis.Password = password\n\treturn\n}"} {"input": "package circonusgometrics\n\nimport (\n\t\"sync\"\n\n\t\"github.com/circonus-labs/circonusllhist\"\n)\n\n\ntype Histogram struct {\n\tname string\n\thist *circonusllhist.Histogram\n\trw sync.RWMutex\n}\n\n\n\n\n\nfunc (m *CirconusMetrics) RecordValue(metric string, val float64) {\n\tm.SetHistogramValue(metric, val)\n}\n\n\nfunc (m *CirconusMetrics) SetHistogramValue(metric string, val float64) {\n\tm.NewHistogram(metric)\n\n\tm.histograms[metric].rw.Lock()\n\tdefer m.histograms[metric].rw.Unlock()\n\n\tm.histograms[metric].hist.RecordValue(val)\n}\n\n\nfunc (m *CirconusMetrics) RemoveHistogram(metric string) {\n\tm.hm.Lock()\n\tdefer m.hm.Unlock()\n\tdelete(m.histograms, metric)\n}\n\n\nfunc (m *CirconusMetrics) NewHistogram(metric string) *Histogram {\n\tm.hm.Lock()\n\tdefer m.hm.Unlock()\n\n\tif hist, ok := m.histograms[metric]; ok {\n\t\treturn hist\n\t}\n\n\thist := &Histogram{\n\t\tname: metric,\n\t\thist: circonusllhist.New(),\n\t}\n\n\tm.histograms[metric] = hist\n\n\treturn hist\n}\n\n\nfunc (h *Histogram) Name() string {\n\treturn h.name\n}\n\n\nfunc (h *Histogram) RecordValue(v float64) {\n\th.rw.Lock()\n\tdefer h.rw.Unlock()\n\n\th.hist.RecordValue(v)\n}\n\nfunc (m *CirconusMetrics) Timing(metric string, val float64) ", "output": "{\n\tm.SetHistogramValue(metric, val)\n}"} {"input": "package function\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\n\n\n\nfunc Handle(ctx context.Context, res http.ResponseWriter, req *http.Request) ", "output": "{\n\n\tfmt.Println(\"OK\") \n\tfmt.Fprintln(res, \"OK\") \n}"} {"input": "package lua\n\ntype Metatable struct {\n IndexFunc Function\n NewindexFunc Function\n TostringFunc Function \n GCFunc Function\n}\n\nfunc (this *Metatable) Index() Function {\n return this.IndexFunc\n}\n\nfunc (this *Metatable) Newindex() Function {\n return this.NewindexFunc\n}\n\nfunc (this *Metatable) Tostring() Function {\n return this.TostringFunc\n}\n\n\n\nfunc (this *Metatable) GC() Function ", "output": "{\n return this.GCFunc\n}"} {"input": "package main\n\nimport (\n \"net\"\n _\"fmt\"\n \"os/exec\"\n \"bytes\"\n\t\"io\"\n \"github.com/donomii/svarmrgo\"\n \"bufio\"\n)\n\n\n\nfunc runCommand (cmd *exec.Cmd, stdin io.Reader) bytes.Buffer{\n\tcmd.Stdin = stdin\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\tcmd.Run()\n\treturn out\n}\n\n\ntype NotifyArgs struct {\n Message string\n Title string\n Level string\n Duration string\n}\n\n\n\n\n\n\nfunc main() {\n conn := svarmrgo.CliConnect()\n go svarmrgo.HandleInputs(conn, handleMessage)\n cmd := exec.Command(\"detect/pitchDetect\")\n stdout, _ := cmd.StdoutPipe()\n cmd.Start()\n r := bufio.NewReader(stdout)\n for {\n line, _, _ := r.ReadLine()\n svarmrgo.SendMessage(conn, svarmrgo.Message{Selector: \"pitch-detect\", Arg: string(line)})\n \n }\n}\n\nfunc handleMessage (conn net.Conn, m svarmrgo.Message) ", "output": "{\n switch m.Selector {\n case \"reveal-yourself\" :\n\t\t\t m.Respond(svarmrgo.Message{Selector: \"announce\", Arg: \"user notifier\"})\n }\n }"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"github.com/cross-dev/script-server/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n\t\"strings\"\n)\n\ntype ContainSubstringMatcher struct {\n\tSubstr string\n\tArgs []interface{}\n}\n\nfunc (matcher *ContainSubstringMatcher) Match(actual interface{}) (success bool, err error) {\n\tactualString, ok := toString(actual)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"ContainSubstring matcher requires a string or stringer. Got:\\n%s\", format.Object(actual, 1))\n\t}\n\n\treturn strings.Contains(actualString, matcher.stringToMatch()), nil\n}\n\nfunc (matcher *ContainSubstringMatcher) stringToMatch() string {\n\tstringToMatch := matcher.Substr\n\tif len(matcher.Args) > 0 {\n\t\tstringToMatch = fmt.Sprintf(matcher.Substr, matcher.Args...)\n\t}\n\treturn stringToMatch\n}\n\n\n\nfunc (matcher *ContainSubstringMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"not to contain substring\", matcher.stringToMatch())\n}\n\nfunc (matcher *ContainSubstringMatcher) FailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn format.Message(actual, \"to contain substring\", matcher.stringToMatch())\n}"} {"input": "package restic\n\nimport \"syscall\"\n\nfunc (node Node) restoreSymlinkTimestamps(path string, utimes [2]syscall.Timespec) error {\n\treturn nil\n}\n\n\n\nfunc (s statUnix) atim() syscall.Timespec { return s.Atimespec }\nfunc (s statUnix) mtim() syscall.Timespec { return s.Mtimespec }\nfunc (s statUnix) ctim() syscall.Timespec { return s.Ctimespec }\n\n\nfunc Getxattr(path, name string) ([]byte, error) {\n\treturn nil, nil\n}\n\n\n\nfunc Listxattr(path string) ([]string, error) {\n\treturn nil, nil\n}\n\n\nfunc Setxattr(path, name string, data []byte) error {\n\treturn nil\n}\n\nfunc (node Node) device() int ", "output": "{\n\treturn int(node.Device)\n}"} {"input": "package limiter\n\ntype SimpleLimiter chan struct{}\n\n\nfunc (l SimpleLimiter) Leave() { <-l }\n\nfunc NewSimpleLimiter(l int) SimpleLimiter {\n\treturn make(chan struct{}, l)\n}\n\nfunc (l SimpleLimiter) Enter() ", "output": "{ l <- struct{}{} }"} {"input": "package syscall_test\n\nimport (\n\t\"syscall\"\n\t\"testing\"\n)\n\n\n\n\n\n\n\nfunc TestPlan9Syserr(t *testing.T) {\n\ttestalias(t,\n\t\t\"Syscall\",\n\t\tfunc() error {\n\t\t\treturn syscall.Mkdir(\"/\", 0)\n\t\t},\n\t\tfunc() error {\n\t\t\treturn syscall.Mkdir(\"#\", 0)\n\t\t})\n\ttestalias(t,\n\t\t\"Syscall6\",\n\t\tfunc() error {\n\t\t\treturn syscall.Mount(0, 0, \"\", 0, \"\")\n\t\t},\n\t\tfunc() error {\n\t\t\treturn syscall.Mount(-1, 0, \"\", 0, \"\")\n\t\t})\n\ttestalias(t,\n\t\t\"seek\",\n\t\tfunc() error {\n\t\t\t_, err := syscall.Seek(0, 0, -1)\n\t\t\treturn err\n\t\t},\n\t\tfunc() error {\n\t\t\t_, err := syscall.Seek(-1, 0, 0)\n\t\t\treturn err\n\t\t})\n}\n\nfunc testalias(t *testing.T, fn string, sys1, sys2 func() error) ", "output": "{\n\terr := sys1().Error()\n\terrcopy := string([]byte(err))\n\tsys2()\n\tif err != errcopy {\n\t\tt.Errorf(\"syscall.%s error string changed from %q to %q\\n\", fn, errcopy, err)\n\t}\n}"} {"input": "package partner\n\nimport (\n\t\"github.com/jrsix/gof/web\"\n\t\"github.com/jrsix/gof/web/mvc\"\n\t\"go2o/src/core/domain/interface/partner\"\n\t\"go2o/src/core/service/dps\"\n\t\"net/url\"\n)\n\nfunc chkLogin(ctx *web.Context) (b bool, partnerId int) {\n\tv := ctx.Session().Get(\"partner_id\")\n\tif v == nil {\n\t\treturn false, -1\n\t}\n\treturn true, v.(int)\n}\nfunc redirect(ctx *web.Context) {\n\tr, w := ctx.Request, ctx.Response\n\tw.Write([]byte(\"\"))\n}\n\nvar _ mvc.Filter = new(baseC)\n\ntype baseC struct {\n}\n\n\nfunc (this *baseC) RequestEnd(ctx *web.Context) {\n}\n\n\nfunc (this *baseC) GetPartnerId(ctx *web.Context) int {\n\tv := ctx.Session().Get(\"partner_id\")\n\tif v == nil {\n\t\tthis.Requesting(ctx)\n\t\treturn -1\n\t}\n\treturn v.(int)\n}\n\nfunc (this *baseC) GetPartner(ctx *web.Context) (*partner.ValuePartner, error) {\n\treturn dps.PartnerService.GetPartner(this.GetPartnerId(ctx))\n}\n\n\nfunc (this *baseC) ErrorOutput(ctx *web.Context, err string) {\n\tctx.Response.Write([]byte(\"{error:\\\"\" + err + \"\\\"}\"))\n}\n\nfunc (this *baseC) Requesting(ctx *web.Context) bool ", "output": "{\n\tif b, _ := chkLogin(ctx); !b {\n\t\tredirect(ctx)\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package util\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tprocCgroup = \"/proc/self/cgroup\"\n\tsysPidsMaxFmt = \"/sys/fs/cgroup/pids%s/pids.max\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc GetPIDLimit() (int, error) {\n\tpidsMax, err := getCgroupPidsFile()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tf, err := os.Open(pidsMax) \n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer f.Close() \n\n\tmaxPidsStr, err := bufio.NewReader(f).ReadString('\\n')\n\tif err != nil && !errors.Is(err, io.EOF) {\n\t\treturn 0, err\n\t}\n\tmaxPidsStr = strings.TrimRight(maxPidsStr, \"\\n\")\n\n\tmaxPids := -1\n\tif maxPidsStr != \"max\" {\n\t\tmaxPids, err = strconv.Atoi(maxPidsStr)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\treturn maxPids, nil\n}\n\n\n\nfunc SetPIDLimit(limit int) error {\n\tlimitStr := \"max\"\n\tif limit != -1 {\n\t\tlimitStr = fmt.Sprintf(\"%d\", limit)\n\t}\n\n\tpidsMax, err := getCgroupPidsFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(pidsMax)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = f.WriteString(limitStr)\n\tif err != nil {\n\t\tf.Close() \n\n\t\treturn err\n\t}\n\n\treturn f.Close()\n}\n\nfunc getCgroupPidsFile() (string, error) ", "output": "{\n\tcgroup, err := os.Open(procCgroup)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer cgroup.Close() \n\n\tscanner := bufio.NewScanner(cgroup)\n\tvar slice string\n\tfor scanner.Scan() {\n\t\tparts := strings.SplitN(scanner.Text(), \":\", 3)\n\t\tif parts == nil || len(parts) < 3 {\n\t\t\tcontinue\n\t\t}\n\t\tif parts[1] == \"pids\" {\n\t\t\tslice = parts[2]\n\n\t\t\tbreak\n\t\t}\n\t}\n\tif slice == \"\" {\n\t\treturn \"\", fmt.Errorf(\"could not find a cgroup for 'pids'\")\n\t}\n\n\tpidsMax := fmt.Sprintf(sysPidsMaxFmt, slice)\n\n\treturn pidsMax, nil\n}"} {"input": "package transform\n\nimport (\n\tresourcepb \"go.opentelemetry.io/proto/otlp/resource/v1\"\n\n\t\"go.opentelemetry.io/otel/sdk/resource\"\n)\n\n\n\n\nfunc Resource(r *resource.Resource) *resourcepb.Resource ", "output": "{\n\tif r == nil {\n\t\treturn nil\n\t}\n\treturn &resourcepb.Resource{Attributes: ResourceAttributes(r)}\n}"} {"input": "package mvt\n\nimport (\n\t\"fmt\"\n\n\t\"context\"\n\n\t\"github.com/go-spatial/tegola\"\n\t\"github.com/go-spatial/tegola/mvt/vector_tile\"\n)\n\n\ntype Tile struct {\n\tlayers []Layer\n}\n\n\nfunc (t *Tile) AddLayers(layers ...*Layer) error {\n\tfor i := range layers {\n\t\tnl := layers[i]\n\t\tif nl == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor i, l := range t.layers {\n\t\t\tif l.Name == nl.Name {\n\t\t\t\treturn fmt.Errorf(\"Layer %v, already is named %v, new layer not added.\", i, l.Name)\n\t\t\t}\n\t\t}\n\t\tt.layers = append(t.layers, *nl)\n\t}\n\treturn nil\n}\n\n\nfunc (t *Tile) Layers() (l []Layer) {\n\tl = append(l, t.layers...)\n\treturn l\n}\n\n\n\n\n\nfunc (t *Tile) VTile(ctx context.Context, tile *tegola.Tile) (vt *vectorTile.Tile, err error) ", "output": "{\n\tvt = new(vectorTile.Tile)\n\tfor _, l := range t.layers {\n\t\tvtl, err := l.VTileLayer(ctx, tile)\n\t\tif err != nil {\n\t\t\tswitch err {\n\t\t\tcase context.Canceled:\n\t\t\t\treturn nil, err\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"Error Getting VTileLayer: %v\", err)\n\t\t\t}\n\t\t}\n\t\tvt.Layers = append(vt.Layers, vtl)\n\t}\n\treturn vt, nil\n}"} {"input": "package main\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t)\n\nfunc main() {\n\tkey := \"ba5d1d41f788971f4816f3d7a0e644ff\"\n\turl := fmt.Sprintf(\"http://api.reimaginebanking.com/atms?key=%s\",key)\n res, err := http.Get(url)\n errCheck(err)\n defer res.Body.Close()\n body, err := ioutil.ReadAll(res.Body)\n errCheck(err)\n fmt.Printf(\"%s\\n\", string(body))\n}\n\n\nfunc errCheck(e error) ", "output": "{\n if e != nil {\n panic(e)\n }\n}"} {"input": "package mediaservices\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tAPIVersion = \"2015-10-01\"\n\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype ManagementClient struct {\n\tautorest.Client\n\tBaseURI string\n\tAPIVersion string\n\tSubscriptionID string\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {\n\treturn ManagementClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tAPIVersion: APIVersion,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) ManagementClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package backend\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc BackendInit() {\n}\n\nfunc init() {\n\thttp.HandleFunc(\"/api\", handler)\n}\n\n\n\nfunc handler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tfmt.Fprint(w, \"Hello World from James Scott!\")\n}"} {"input": "package aws\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hashicorp/terraform/helper/schema\"\n)\n\n\nvar redshiftServiceAccountPerRegionMap = map[string]string{\n\t\"us-east-1\": \"193672423079\",\n\t\"us-east-2\": \"391106570357\",\n\t\"us-west-1\": \"262260360010\",\n\t\"us-west-2\": \"902366379725\",\n\t\"ap-south-1\": \"865932855811\",\n\t\"ap-northeast-2\": \"760740231472\",\n\t\"ap-southeast-1\": \"361669875840\",\n\t\"ap-southeast-2\": \"762762565011\",\n\t\"ap-northeast-1\": \"404641285394\",\n\t\"ca-central-1\": \"907379612154\",\n\t\"eu-central-1\": \"053454850223\",\n\t\"eu-west-1\": \"210876761215\",\n\t\"eu-west-2\": \"307160386991\",\n\t\"eu-west-3\": \"915173422425\",\n\t\"sa-east-1\": \"075028567923\",\n}\n\n\n\nfunc dataSourceAwsRedshiftServiceAccountRead(d *schema.ResourceData, meta interface{}) error {\n\tregion := meta.(*AWSClient).region\n\tif v, ok := d.GetOk(\"region\"); ok {\n\t\tregion = v.(string)\n\t}\n\n\tif accid, ok := redshiftServiceAccountPerRegionMap[region]; ok {\n\t\td.SetId(accid)\n\t\td.Set(\"arn\", iamArnString(meta.(*AWSClient).partition, accid, \"user/logs\"))\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"Unknown region (%q)\", region)\n}\n\nfunc dataSourceAwsRedshiftServiceAccount() *schema.Resource ", "output": "{\n\treturn &schema.Resource{\n\t\tRead: dataSourceAwsRedshiftServiceAccountRead,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"region\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"arn\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package eventlistener\n\nimport (\n\t\"testing\"\n\t\"github.com/docker/docker/api/types\"\n\t\"golang.org/x/net/context\"\n\t\"fmt\"\n\t\"time\"\n\t\"github.com/docker/docker/api/types/events\"\n)\n\n\n\n\ntype dockerClientMock struct {}\n\nfunc (d dockerClientMock) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) {\n\teventsChan := make(chan events.Message, 10)\n\terrChan := make(chan error, 10)\n\tevent := events.Message{ Type: \"container\", Action: \"die\", }\n\teventsChan <- event\n\treturn eventsChan, errChan\n}\nfunc (d dockerClientMock) Info(ctx context.Context) (types.Info, error) {\n\tpanic(\"This function not suppose to be called\")\n}\nfunc (d dockerClientMock) RegistryLogin(ctx context.Context, auth types.AuthConfig) (types.AuthResponse, error) {\n\tpanic(\"This function not suppose to be called\")\n}\n\nfunc (d dockerClientMock) DiskUsage(ctx context.Context) (types.DiskUsage, error) {\n\tpanic(\"This function not suppose to be called\")\n}\n\nfunc (d dockerClientMock) Ping(ctx context.Context) (bool, error) {\n\tpanic(\"This function not suppose to be called\")\n}\n\nfunc TestEventListener(t *testing.T) ", "output": "{\n\n\tconst labelToMonitor = \"tugbot-test\"\n\ttsk := make(chan string, 10)\n\n\tRegister(dockerClientMock{}, labelToMonitor, tsk)\n\tselect {\n\tcase res := <-tsk:\n\t\tfmt.Println(\"we recieved the die container id via the tasks chan: \", res)\n\tcase <-time.After(time.Second * 5):\n\t\tt.Error(\"we did not recieved the die container id on the tasks chan after 5 sec!\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/flynn/flynn/Godeps/_workspace/src/github.com/julienschmidt/httprouter\"\n\t\"github.com/flynn/flynn/Godeps/_workspace/src/gopkg.in/inconshreveable/log15.v2\"\n\t\"github.com/flynn/flynn/appliance/postgresql/client\"\n\t\"github.com/flynn/flynn/appliance/postgresql/state\"\n\t\"github.com/flynn/flynn/discoverd/client\"\n\t\"github.com/flynn/flynn/pkg/httphelper\"\n)\n\n\n\ntype HTTP struct {\n\tpg *Postgres\n\tpeer *state.Peer\n\thb discoverd.Heartbeater\n\tlog log15.Logger\n}\n\nfunc (h *HTTP) GetStatus(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tres := &pgmanager.Status{\n\t\tPeer: h.peer.Info(),\n\t}\n\tvar err error\n\tres.Postgres, err = h.pg.Info()\n\tif err != nil {\n\t\th.log.Error(\"error getting postgres info\", \"err\", err)\n\t}\n\thttphelper.JSON(w, 200, res)\n}\n\nfunc (h *HTTP) Stop(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tif err := h.hb.Close(); err != nil {\n\t\thttphelper.Error(w, err)\n\t\treturn\n\t}\n\tif err := h.peer.Stop(); err != nil {\n\t\thttphelper.Error(w, err)\n\t\treturn\n\t}\n\tw.WriteHeader(200)\n}\n\nfunc ServeHTTP(pg *Postgres, peer *state.Peer, hb discoverd.Heartbeater, log log15.Logger) error ", "output": "{\n\tapi := &HTTP{\n\t\tpg: pg,\n\t\tpeer: peer,\n\t\thb: hb,\n\t\tlog: log,\n\t}\n\tr := httprouter.New()\n\tr.GET(\"/status\", api.GetStatus)\n\tr.POST(\"/stop\", api.Stop)\n\treturn http.ListenAndServe(\":5433\", r)\n}"} {"input": "package listener\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc testPTree(t *testing.T, strs ...string) {\n\tpt := newPatriciaTreeString(strs...)\n\tfor _, s := range strs {\n\t\tif !pt.match(strings.NewReader(s)) {\n\t\t\tt.Errorf(\"%s is not matched by %s\", s, s)\n\t\t}\n\n\t\tif !pt.matchPrefix(strings.NewReader(s + s)) {\n\t\t\tt.Errorf(\"%s is not matched as a prefix by %s\", s+s, s)\n\t\t}\n\n\t\tif pt.match(strings.NewReader(s + s)) {\n\t\t\tt.Errorf(\"%s matches %s\", s+s, s)\n\t\t}\n\n\t\tpt.matchPrefix(strings.NewReader(s[:len(s)-1]))\n\t\tpt.match(strings.NewReader(s[:len(s)-1]))\n\t\tpt.matchPrefix(strings.NewReader(s + \"$\"))\n\t\tpt.match(strings.NewReader(s + \"$\"))\n\t}\n}\n\nfunc TestPatriciaOnePrefix(t *testing.T) {\n\ttestPTree(t, \"prefix\")\n}\n\n\n\nfunc TestPatriciaOverlapping(t *testing.T) {\n\ttestPTree(t, \"foo\", \"far\", \"farther\", \"boo\", \"ba\", \"bar\")\n}\n\nfunc TestPatriciaNonOverlapping(t *testing.T) ", "output": "{\n\ttestPTree(t, \"foo\", \"bar\", \"dummy\")\n}"} {"input": "package prometheus\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"text/template\"\n\n\t\"github.com/pkg/errors\"\n\n\ttm \"github.com/supergiant/control/pkg/templatemanager\"\n\t\"github.com/supergiant/control/pkg/workflows/steps\"\n)\n\nconst StepName = \"prometheus\"\n\ntype Config struct {\n\tRBACEnabled bool\n}\n\ntype Step struct {\n\tscript *template.Template\n}\n\nfunc (s *Step) Rollback(context.Context, io.Writer, *steps.Config) error {\n\treturn nil\n}\n\nfunc Init() {\n\ttpl, err := tm.GetTemplate(StepName)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"template %s not found\", StepName))\n\t}\n\n\tsteps.RegisterStep(StepName, New(tpl))\n}\n\nfunc New(script *template.Template) *Step {\n\tt := &Step{\n\t\tscript: script,\n\t}\n\n\treturn t\n}\n\nfunc (s *Step) Run(ctx context.Context, out io.Writer, config *steps.Config) error {\n\terr := steps.RunTemplate(ctx, s.script, config.Runner, out, toStepCfg(config))\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"install prometheus step\")\n\t}\n\n\treturn nil\n}\n\nfunc (s *Step) Name() string {\n\treturn StepName\n}\n\nfunc (s *Step) Description() string {\n\treturn \"Install prometheus\"\n}\n\nfunc (s *Step) Depends() []string {\n\treturn nil\n}\n\n\n\nfunc toStepCfg(c *steps.Config) Config ", "output": "{\n\treturn Config{\n\t\tRBACEnabled: c.Kube.RBACEnabled,\n\t}\n}"} {"input": "package kvm2\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\n\t\"github.com/docker/machine/libmachine/drivers\"\n\tcfg \"k8s.io/minikube/pkg/minikube/config\"\n\t\"k8s.io/minikube/pkg/minikube/constants\"\n\t\"k8s.io/minikube/pkg/minikube/registry\"\n)\n\n\n\n\n\ntype kvmDriver struct {\n\t*drivers.BaseDriver\n\n\tMemory int\n\tDiskSize int\n\tCPU int\n\tNetwork string\n\tPrivateNetwork string\n\tISO string\n\tBoot2DockerURL string\n\tDiskPath string\n\tGPU bool\n}\n\nfunc createKVM2Host(config cfg.MachineConfig) interface{} {\n\treturn &kvmDriver{\n\t\tBaseDriver: &drivers.BaseDriver{\n\t\t\tMachineName: cfg.GetMachineName(),\n\t\t\tStorePath: constants.GetMinipath(),\n\t\t\tSSHUser: \"docker\",\n\t\t},\n\t\tMemory: config.Memory,\n\t\tCPU: config.CPUs,\n\t\tNetwork: config.KvmNetwork,\n\t\tPrivateNetwork: \"minikube-net\",\n\t\tBoot2DockerURL: config.Downloader.GetISOFileURI(config.MinikubeISO),\n\t\tDiskSize: config.DiskSize,\n\t\tDiskPath: filepath.Join(constants.GetMinipath(), \"machines\", cfg.GetMachineName(), fmt.Sprintf(\"%s.rawdisk\", cfg.GetMachineName())),\n\t\tISO: filepath.Join(constants.GetMinipath(), \"machines\", cfg.GetMachineName(), \"boot2docker.iso\"),\n\t\tGPU: config.GPU,\n\t}\n}\n\nfunc init() ", "output": "{\n\tregistry.Register(registry.DriverDef{\n\t\tName: \"kvm2\",\n\t\tBuiltin: false,\n\t\tConfigCreator: createKVM2Host,\n\t})\n}"} {"input": "package httpcache\n\nimport \"log\"\n\nconst (\n\tansiRed = \"\\x1b[31;1m\"\n\tansiReset = \"\\x1b[0m\"\n)\n\nvar DebugLogging = false\n\n\n\nfunc errorf(format string, args ...interface{}) {\n\tlog.Printf(ansiRed+\"✗ \"+format+ansiReset, args)\n}\n\nfunc debugf(format string, args ...interface{}) ", "output": "{\n\tif DebugLogging {\n\t\tlog.Printf(format, args...)\n\t}\n}"} {"input": "package ewma\n\nimport (\n\t\"time\"\n)\n\ntype EwmaRate struct {\n\tEwma\n}\n\n\nconst nanosec = float64(1000000000)\n\n\n\n\nfunc NewEwmaRate(halfLife time.Duration) *EwmaRate {\n\treturn (&EwmaRate{}).Init(halfLife)\n}\n\n\n\n\nfunc (r *EwmaRate) Init(halfLife time.Duration) *EwmaRate {\n\tr.Ewma.Init(halfLife)\n\treturn r\n}\n\n\n\n\n\n\n\n\n\nfunc (r *EwmaRate) Update(now time.Time) float64 {\n\ttimeDelta := now.Sub(r.lastTimestamp)\n\treturn r.Ewma.Update(nanosec/float64(timeDelta.Nanoseconds()), now)\n}\n\n\n\n\nfunc (r *EwmaRate) CurrentNow() float64 {\n\treturn r.Current(time.Now())\n}\n\n\nfunc (r *EwmaRate) Current(now time.Time) float64 {\n\tif r.lastTimestamp.IsZero() || r.lastTimestamp == now || now.Before(r.lastTimestamp) {\n\t\treturn r.Ewma.Current\n\t}\n\n\ttimeDelta := now.Sub(r.lastTimestamp)\n\n\treturn r.count(0, timeDelta)\n}\n\nfunc (r *EwmaRate) UpdateNow() float64 ", "output": "{\n\treturn r.Update(time.Now())\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc main() {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Scan()\n\ttestCases, _ := strconv.Atoi(scanner.Text())\n\tfor i := 0; i < testCases; i++ {\n\t\tfmt.Printf(\"Case #%v: %v\\n\", i+1, solve(parseTestCase(scanner)))\n\t}\n}\n\n\n\nfunc parseTestCase(scanner *bufio.Scanner) (int, []int) {\n\tscanner.Scan()\n\tpair := strings.Split(scanner.Text(), \" \")\n\n\tus, _ := strconv.Atoi(pair[0])\n\tscanner.Scan()\n\tothers := []int{}\n\tfor _, m := range strings.Split(scanner.Text(), \" \") {\n\t\tmote, _ := strconv.Atoi(m)\n\t\tothers = append(others, mote)\n\t}\n\tsort.Ints(others)\n\treturn us, others\n}\n\nfunc solve(us int, others []int) int ", "output": "{\n\tcnt := 0\n\tfmt.Println(us, others)\n\tprobs := make([]int, len(others))\n\tif us > others[0] {\n\t\tprobs[0] = us\n\t}\n\tfor i := 1; i < len(others); i++ {\n\t\tif probs[i-1]+others[i-1] > others[i] {\n\t\t\tprobs[i] = probs[i-1] + others[i-1]\n\t\t}\n\t}\n\tfor i := 0; i < len(probs); i++ {\n\t\tif probs[i] <= others[i] {\n\t\t\tcnt++\n\t\t}\n\t}\n\n\treturn cnt\n}"} {"input": "package networker\n\nimport (\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/names\"\n\n\t\"github.com/juju/juju/api/base\"\n\t\"github.com/juju/juju/api/watcher\"\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/network\"\n)\n\nconst networkerFacade = \"Networker\"\n\n\ntype State struct {\n\tfacade base.FacadeCaller\n}\n\n\nfunc NewState(caller base.APICaller) *State {\n\treturn &State{base.NewFacadeCaller(caller, networkerFacade)}\n}\n\n\nfunc (st *State) MachineNetworkInfo(tag names.MachineTag) ([]network.Info, error) {\n\targs := params.Entities{\n\t\tEntities: []params.Entity{{Tag: tag.String()}},\n\t}\n\tvar results params.MachineNetworkInfoResults\n\terr := st.facade.FacadeCall(\"MachineNetworkInfo\", args, &results)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(results.Results) != 1 {\n\t\terr = errors.Errorf(\"expected one result, got %d\", len(results.Results))\n\t\treturn nil, err\n\t}\n\tresult := results.Results[0]\n\tif result.Error != nil {\n\t\treturn nil, result.Error\n\t}\n\treturn results.Results[0].Info, nil\n}\n\n\n\n\n\nfunc (st *State) WatchInterfaces(tag names.MachineTag) (watcher.NotifyWatcher, error) ", "output": "{\n\targs := params.Entities{\n\t\tEntities: []params.Entity{{Tag: tag.String()}},\n\t}\n\tvar results params.NotifyWatchResults\n\terr := st.facade.FacadeCall(\"WatchInterfaces\", args, &results)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(results.Results) != 1 {\n\t\terr = errors.Errorf(\"expected one result, got %d\", len(results.Results))\n\t\treturn nil, err\n\t}\n\tresult := results.Results[0]\n\tif result.Error != nil {\n\t\treturn nil, result.Error\n\t}\n\tw := watcher.NewNotifyWatcher(st.facade.RawAPICaller(), result)\n\treturn w, nil\n}"} {"input": "package spark\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\nvar httpClient *http.Client\n\nfunc init() {\n\thttpClient = &http.Client{}\n}\n\nfunc (s *Spark) request(req *http.Request) ([]byte, error) {\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", s.token))\n\treq.Header.Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\n\tres, err := httpClient.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer res.Body.Close()\n\tbs, err := ioutil.ReadAll(res.Body)\n\n\tif res.StatusCode != http.StatusOK {\n\t\tif res.StatusCode != 204 {\n\t\t\te := fmt.Sprintf(\"HTTP Status Code: %d\\n%s\", res.StatusCode, string(bs))\n\t\t\treturn nil, errors.New(e)\n\t\t}\n\t}\n\n\treturn bs, err\n}\n\n\n\nfunc (s *Spark) PostRequest(url string, body *bytes.Buffer) ([]byte, error) {\n\treq, err := http.NewRequest(\"POST\", url, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.request(req)\n}\n\nfunc (s *Spark) DeleteRequest(url string) ([]byte, error) {\n\tfmt.Println(\"Delete url: \", url)\n\treq, err := http.NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.request(req)\n}\n\nfunc (s *Spark) GetRequest(url string, uv *url.Values) ([]byte, error) ", "output": "{\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif uv != nil {\n\t\treq.URL.RawQuery = (*uv).Encode()\n\t}\n\treturn s.request(req)\n}"} {"input": "package gorever\n\nimport (\n\t\"fmt\"\n\t\"github.com/inconshreveable/go-update\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype Updater struct {\n\tnewVersion bool\n\tch chan bool\n}\n\nfunc NewUpdater(ch chan bool) (*Updater, error) {\n\tu := &Updater{\n\t\tnewVersion: true,\n\t\tch: ch,\n\t}\n\n\tgo func(updater *Updater) {\n\t\ttime.Sleep(6*time.Second)\n\t\tupdater.ch <- true\n\t}(u)\n\n\treturn u, nil\n}\n\n\n\nfunc (u *Updater) Update() error {\n\tu.newVersion = false\n\turl := \"http://localhost:8078/gorever-poc\" \n\treturn u.doUpdate(url)\n}\n\nfunc (u *Updater) doUpdate(url string) error {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\terr = update.Apply(resp.Body, update.Options{})\n\tif err != nil {\n\t\tif rerr := update.RollbackError(err); rerr != nil {\n\t\t\treturn fmt.Errorf(\"Failed to rollback from bad update: %v\", rerr)\n\t\t}\n\t}\n\treturn err\n}\n\nfunc (u *Updater) HasNewVersion() bool ", "output": "{\n\treturn u.newVersion\n}"} {"input": "package client\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\tkapi \"k8s.io/kubernetes/pkg/api\"\n\n\tquotaapi \"github.com/openshift/origin/pkg/quota/api\"\n)\n\n\ntype AppliedClusterResourceQuotasNamespacer interface {\n\tAppliedClusterResourceQuotas(namespace string) AppliedClusterResourceQuotaInterface\n}\n\n\ntype AppliedClusterResourceQuotaInterface interface {\n\tList(opts metav1.ListOptions) (*quotaapi.AppliedClusterResourceQuotaList, error)\n\tGet(name string, options metav1.GetOptions) (*quotaapi.AppliedClusterResourceQuota, error)\n}\n\n\ntype appliedClusterResourceQuotas struct {\n\tr *Client\n\tns string\n}\n\n\nfunc newAppliedClusterResourceQuotas(c *Client, namespace string) *appliedClusterResourceQuotas {\n\treturn &appliedClusterResourceQuotas{\n\t\tr: c,\n\t\tns: namespace,\n\t}\n}\n\n\n\n\n\nfunc (c *appliedClusterResourceQuotas) Get(name string, options metav1.GetOptions) (result *quotaapi.AppliedClusterResourceQuota, err error) {\n\tresult = "aapi.AppliedClusterResourceQuota{}\n\terr = c.r.Get().Namespace(c.ns).Resource(\"appliedclusterresourcequotas\").Name(name).VersionedParams(&options, kapi.ParameterCodec).Do().Into(result)\n\treturn\n}\n\nfunc (c *appliedClusterResourceQuotas) List(opts metav1.ListOptions) (result *quotaapi.AppliedClusterResourceQuotaList, err error) ", "output": "{\n\tresult = "aapi.AppliedClusterResourceQuotaList{}\n\terr = c.r.Get().Namespace(c.ns).Resource(\"appliedclusterresourcequotas\").VersionedParams(&opts, kapi.ParameterCodec).Do().Into(result)\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc main() {\n\tsc := bufio.NewScanner(os.Stdin)\n\tsc.Split(bufio.ScanWords)\n\tn := nextInt(sc)\n\ta := nextInt(sc)\n\tb := nextInt(sc)\n\n\tanswer := 0\n\tfor i := 1; i <= n; i++ {\n\t\tsum := 0\n\t\tfor _, s := range fmt.Sprintf(\"%d\", i) {\n\t\t\tx, _ := strconv.Atoi(string(s))\n\t\t\tsum = sum + x\n\t\t}\n\t\tif a <= sum && sum <= b {\n\t\t\tanswer = answer + i\n\t\t}\n\t}\n\n\tfmt.Println(answer)\n}\n\n\n\nfunc nextString(sc *bufio.Scanner) string {\n\tsc.Scan()\n\treturn sc.Text()\n}\n\nfunc nextNumber(sc *bufio.Scanner) float64 {\n\tsc.Scan()\n\tf, err := strconv.ParseFloat(sc.Text(), 32)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}\n\nfunc nextInt(sc *bufio.Scanner) int {\n\tsc.Scan()\n\tn, err := strconv.Atoi(sc.Text())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn n\n}\n\n\n\nfunc debugPrintf(format string, a ...interface{}) {\n\tfmt.Fprintf(os.Stderr, format, a...)\n}\n\nfunc printArray(xs []int) ", "output": "{\n\tfmt.Println(strings.Trim(fmt.Sprint(xs), \"[]\"))\n}"} {"input": "package mock\n\nimport (\n\t\"time\"\n)\n\ntype Clock struct {\n\tAdded []uint\n\tRemoved []chan time.Time\n\tEta float64\n}\n\n\n\nfunc (m *Clock) Add(c chan time.Time, t uint, sync bool) {\n\tm.Added = append(m.Added, t)\n}\n\nfunc (m *Clock) Remove(c chan time.Time) {\n\tm.Removed = append(m.Removed, c)\n}\n\nfunc (m *Clock) ETA(c chan time.Time) float64 {\n\treturn m.Eta\n}\n\nfunc NewClock() *Clock ", "output": "{\n\tm := &Clock{\n\t\tAdded: []uint{},\n\t\tRemoved: []chan time.Time{},\n\t}\n\treturn m\n}"} {"input": "package iso20022\n\n\ntype AuthorisationResult5 struct {\n\n\tAuthorisationEntity *GenericIdentification70 `xml:\"AuthstnNtty,omitempty\"`\n\n\tResponseToAuthorisation *ResponseType1 `xml:\"RspnToAuthstn\"`\n\n\tAuthorisationCode *Min6Max8Text `xml:\"AuthstnCd,omitempty\"`\n}\n\nfunc (a *AuthorisationResult5) AddAuthorisationEntity() *GenericIdentification70 {\n\ta.AuthorisationEntity = new(GenericIdentification70)\n\treturn a.AuthorisationEntity\n}\n\n\n\nfunc (a *AuthorisationResult5) SetAuthorisationCode(value string) {\n\ta.AuthorisationCode = (*Min6Max8Text)(&value)\n}\n\nfunc (a *AuthorisationResult5) AddResponseToAuthorisation() *ResponseType1 ", "output": "{\n\ta.ResponseToAuthorisation = new(ResponseType1)\n\treturn a.ResponseToAuthorisation\n}"} {"input": "package logo\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc assertEqual(t *testing.T, actual, expected interface{}, args ...interface{}) {\n\tif actual != expected {\n\t\tmsg := fmt.Sprint(args...)\n\t\tmsg = fmt.Sprintf(\"Not equal(%s)! autual: %#v expected: %#v\", msg, actual, expected)\n\t\tfail(t, msg)\n\t}\n}\n\nfunc assertTrue(t *testing.T, val bool, args ...interface{}) {\n\tif !val {\n\t\tmsg := fmt.Sprint(args...)\n\t\tmsg = fmt.Sprintf(\"Not true(%s)!\", msg)\n\t\tfail(t, msg)\n\t}\n}\n\nfunc assertNotNil(t *testing.T, val interface{}, args ...interface{}) {\n\tif val == nil {\n\t\tmsg := fmt.Sprint(args...)\n\t\tmsg = fmt.Sprintf(\"Nil(%s)!\", msg)\n\t\tfail(t, msg)\n\t}\n}\n\nfunc benchmarkTask(b *testing.B, task func(int)) {\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\ttask(i)\n\t}\n}\n\nfunc fail(t *testing.T, msg string) ", "output": "{\n\tt.Errorf(msg)\n}"} {"input": "package ast\n\nvar _ Action = &PassAfterOrIgnore{}\n\n\ntype PassAfterOrIgnore struct {\n\taccess\n\tLimit *Target\n}\n\nfunc (p *PassAfterOrIgnore) Accept(d ActionDispatcher) error {\n\treturn d.DispatchPassAfterOrIgnore(p)\n}\n\n\n\n\nfunc PassAfterTargetOrIgnore() *PassAfterOrIgnore {\n\treturn &PassAfterOrIgnore{\n\t\tLimit: NewTarget(),\n\t}\n}\n\nfunc (p *PassAfterOrIgnore) String() string ", "output": "{\n\tpu := &PassAfter{\n\t\tLimit: p.Limit,\n\t}\n\tif p.Limit.Lower == p.Limit.Upper && p.Limit.Lower > 0 {\n\t\treturn pu.String() + \" or ignore otherwise\"\n\t} else {\n\t\treturn pu.String() + \" or ignore if not found\"\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strings\"\n)\n\n\n\n\nfunc main() {\n\tfpath := \"testdata/sample.json\"\n\n\tfile, err := os.Open(fpath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\ttbytes, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjsonStream := string(tbytes)\n\tdecodeString(jsonStream)\n\n\tdecodeFile(file)\n\n\tfile2, err := os.Open(fpath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdecodeFile(file2)\n}\n\n\n\nfunc decodeString(jsonStream string) {\n\trmap := map[string]string{}\n\tdec := json.NewDecoder(strings.NewReader(jsonStream))\n\tfor {\n\t\tif err := dec.Decode(&rmap); err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tfmt.Printf(\"%+v\\n\", rmap)\n}\n\nfunc decodeFile(file *os.File) ", "output": "{\n\trmap := map[string]string{}\n\tdec := json.NewDecoder(file)\n\tfor {\n\t\tif err := dec.Decode(&rmap); err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tfmt.Printf(\"%+v\\n\", rmap)\n}"} {"input": "package ai\n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\ntype Loader func(context.Context) (map[int64]int64, error)\n\ntype AI struct {\n\twhites map[int64]int64\n\tsync.RWMutex\n}\n\nfunc New() (a *AI) {\n\treturn &AI{\n\t\twhites: make(map[int64]int64),\n\t}\n}\n\n\n\nfunc (a *AI) LoadWhite(c context.Context, loader Loader) (err error) {\n\tvar (\n\t\twhites map[int64]int64\n\t)\n\tif whites, err = loader(c); err != nil {\n\t\treturn\n\t}\n\ta.Lock()\n\ta.whites = whites\n\ta.Unlock()\n\treturn\n}\n\nfunc (a *AI) White(mid int64) (num int64, ok bool) ", "output": "{\n\ta.RLock()\n\tdefer a.RUnlock()\n\tnum, ok = a.whites[mid]\n\treturn\n}"} {"input": "package terminal\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n)\n\ntype TeePrinter struct {\n\tdisableTerminalOutput bool\n\toutputBucket io.Writer\n}\n\nfunc NewTeePrinter() *TeePrinter {\n\treturn &TeePrinter{\n\t\toutputBucket: ioutil.Discard,\n\t}\n}\n\n\n\nfunc (t *TeePrinter) Print(values ...interface{}) (n int, err error) {\n\tstr := fmt.Sprint(values...)\n\tt.saveOutputToBucket(str)\n\tif !t.disableTerminalOutput {\n\t\treturn fmt.Print(str)\n\t}\n\treturn\n}\n\nfunc (t *TeePrinter) Printf(format string, a ...interface{}) (n int, err error) {\n\tstr := fmt.Sprintf(format, a...)\n\tt.saveOutputToBucket(str)\n\tif !t.disableTerminalOutput {\n\t\treturn fmt.Print(str)\n\t}\n\treturn\n}\n\nfunc (t *TeePrinter) Println(values ...interface{}) (n int, err error) {\n\tstr := fmt.Sprint(values...)\n\tt.saveOutputToBucket(str)\n\tif !t.disableTerminalOutput {\n\t\treturn fmt.Println(str)\n\t}\n\treturn\n}\n\nfunc (t *TeePrinter) DisableTerminalOutput(disable bool) {\n\tt.disableTerminalOutput = disable\n}\n\nfunc (t *TeePrinter) saveOutputToBucket(output string) {\n\tt.outputBucket.Write([]byte(Decolorize(output)))\n}\n\nfunc (t *TeePrinter) SetOutputBucket(bucket io.Writer) ", "output": "{\n\tif bucket == nil {\n\t\tbucket = ioutil.Discard\n\t}\n\n\tt.outputBucket = bucket\n}"} {"input": "package libpod\n\nimport (\n\t\"context\"\n\n\t\"github.com/containers/podman/v3/libpod/define\"\n)\n\n\nfunc (r *Runtime) NewPod(ctx context.Context, options ...PodCreateOption) (*Pod, error) {\n\treturn nil, define.ErrOSNotSupported\n}\n\n\n\nfunc (r *Runtime) removePod(ctx context.Context, p *Pod, removeCtrs, force bool) error ", "output": "{\n\treturn define.ErrOSNotSupported\n}"} {"input": "package protocol\n\nimport (\n\t\"io\"\n\t\"sync/atomic\"\n)\n\ntype countingReader struct {\n\tio.Reader\n\ttot uint64\n}\n\nvar (\n\ttotalIncoming uint64\n\ttotalOutgoing uint64\n)\n\nfunc (c *countingReader) Read(bs []byte) (int, error) {\n\tn, err := c.Reader.Read(bs)\n\tatomic.AddUint64(&c.tot, uint64(n))\n\tatomic.AddUint64(&totalIncoming, uint64(n))\n\treturn n, err\n}\n\nfunc (c *countingReader) Tot() uint64 {\n\treturn atomic.LoadUint64(&c.tot)\n}\n\ntype countingWriter struct {\n\tio.Writer\n\ttot uint64\n}\n\nfunc (c *countingWriter) Write(bs []byte) (int, error) {\n\tn, err := c.Writer.Write(bs)\n\tatomic.AddUint64(&c.tot, uint64(n))\n\tatomic.AddUint64(&totalOutgoing, uint64(n))\n\treturn n, err\n}\n\nfunc (c *countingWriter) Tot() uint64 {\n\treturn atomic.LoadUint64(&c.tot)\n}\n\n\n\nfunc TotalInOut() (uint64, uint64) ", "output": "{\n\treturn atomic.LoadUint64(&totalIncoming), atomic.LoadUint64(&totalOutgoing)\n}"} {"input": "package ewma\n\nimport (\n\t\"time\"\n)\n\ntype EwmaRate struct {\n\tEwma\n}\n\n\nconst nanosec = float64(1000000000)\n\n\n\n\nfunc NewEwmaRate(halfLife time.Duration) *EwmaRate {\n\treturn (&EwmaRate{}).Init(halfLife)\n}\n\n\n\n\nfunc (r *EwmaRate) Init(halfLife time.Duration) *EwmaRate {\n\tr.Ewma.Init(halfLife)\n\treturn r\n}\n\n\n\n\nfunc (r *EwmaRate) UpdateNow() float64 {\n\treturn r.Update(time.Now())\n}\n\n\n\n\nfunc (r *EwmaRate) Update(now time.Time) float64 {\n\ttimeDelta := now.Sub(r.lastTimestamp)\n\treturn r.Ewma.Update(nanosec/float64(timeDelta.Nanoseconds()), now)\n}\n\n\n\n\nfunc (r *EwmaRate) CurrentNow() float64 {\n\treturn r.Current(time.Now())\n}\n\n\n\n\nfunc (r *EwmaRate) Current(now time.Time) float64 ", "output": "{\n\tif r.lastTimestamp.IsZero() || r.lastTimestamp == now || now.Before(r.lastTimestamp) {\n\t\treturn r.Ewma.Current\n\t}\n\n\ttimeDelta := now.Sub(r.lastTimestamp)\n\n\treturn r.count(0, timeDelta)\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc PK2(endpoint, counter string) string {\n\treturn fmt.Sprintf(\"%s/%s\", endpoint, counter)\n}\n\nfunc UUID(endpoint, metric string, tags map[string]string, dstype string, step int) string {\n\tif tags == nil || len(tags) == 0 {\n\t\treturn fmt.Sprintf(\"%s/%s/%s/%d\", endpoint, metric, dstype, step)\n\t}\n\treturn fmt.Sprintf(\"%s/%s/%s/%s/%d\", endpoint, metric, SortedTags(tags), dstype, step)\n}\n\nfunc Checksum(endpoint string, metric string, tags map[string]string) string {\n\tpk := PK(endpoint, metric, tags)\n\treturn Md5(pk)\n}\n\nfunc ChecksumOfUUID(endpoint, metric string, tags map[string]string, dstype string, step int64) string {\n\treturn Md5(UUID(endpoint, metric, tags, dstype, int(step)))\n}\n\nfunc PK(endpoint, metric string, tags map[string]string) string ", "output": "{\n\tif tags == nil || len(tags) == 0 {\n\t\treturn fmt.Sprintf(\"%s/%s\", endpoint, metric)\n\t}\n\treturn fmt.Sprintf(\"%s/%s/%s\", endpoint, metric, SortedTags(tags))\n}"} {"input": "package imath\n\n\n\nfunc Abs(x int) int ", "output": "{\n\tif x < 0 {\n\t\treturn -x\n\t}\n\n\treturn x\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/ant0ine/go-json-rest/rest\"\n\n\t\"github.com/pdxjohnny/s/api\"\n\t\"github.com/pdxjohnny/s/variables\"\n)\n\n\nfunc GetAccount(w rest.ResponseWriter, r *rest.Request) {\n\tid := r.PathParam(\"id\")\n\tdoc, err := api.GetAccount(variables.ServiceDBURL, r.Env[\"JWT_RAW\"].(string), id)\n\tif err != nil {\n\t\trest.Error(w, err.Error(), http.StatusNotFound)\n\t\treturn\n\t}\n\tif doc == nil {\n\t\tw.(http.ResponseWriter).Write(variables.BlankResponse)\n\t\treturn\n\t}\n\tw.WriteJson(doc)\n}\n\n\n\n\nfunc PostAccount(w rest.ResponseWriter, r *rest.Request) ", "output": "{\n\tvar recvDoc map[string]interface{}\n\tid := r.PathParam(\"id\")\n\terr := r.DecodeJsonPayload(&recvDoc)\n\tif err != nil {\n\t\trest.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdoc, err := api.SaveAccount(variables.ServiceDBURL, r.Env[\"JWT_RAW\"].(string), id, recvDoc)\n\tif err != nil {\n\t\trest.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tif doc == nil {\n\t\tw.(http.ResponseWriter).Write(variables.BlankResponse)\n\t\treturn\n\t}\n\tw.WriteJson(doc)\n}"} {"input": "package okta\n\nimport ()\n\ntype SwaApplicationSettingsApplication struct {\n\tButtonField string `json:\"buttonField,omitempty\"`\n\tLoginUrlRegex string `json:\"loginUrlRegex,omitempty\"`\n\tPasswordField string `json:\"passwordField,omitempty\"`\n\tUrl string `json:\"url,omitempty\"`\n\tUsernameField string `json:\"usernameField,omitempty\"`\n}\n\nfunc NewSwaApplicationSettingsApplication() *SwaApplicationSettingsApplication {\n\treturn &SwaApplicationSettingsApplication{}\n}\n\n\n\nfunc (a *SwaApplicationSettingsApplication) IsApplicationInstance() bool ", "output": "{\n\treturn true\n}"} {"input": "package internal\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\ntype ContextKey string\n\nconst userAgent = \"gcloud-golang/0.1\"\n\n\n\n\ntype Transport struct {\n\tBase http.RoundTripper\n}\n\n\n\n\n\n\n\nfunc cloneRequest(r *http.Request) *http.Request {\n\tr2 := new(http.Request)\n\t*r2 = *r\n\tr2.Header = make(http.Header)\n\tfor k, s := range r.Header {\n\t\tr2.Header[k] = s\n\t}\n\treturn r2\n}\n\n\nfunc ProjID(ctx context.Context) string {\n\treturn ctx.Value(ContextKey(\"base\")).(map[string]interface{})[\"project_id\"].(string)\n}\n\n\n\nfunc Namespace(ctx context.Context) string {\n\tv := ctx.Value(ContextKey(\"namespace\"))\n\tif v == nil {\n\t\treturn \"\"\n\t} else {\n\t\treturn v.(string)\n\t}\n}\n\nfunc HttpClient(ctx context.Context) *http.Client {\n\treturn ctx.Value(ContextKey(\"base\")).(map[string]interface{})[\"http_client\"].(*http.Client)\n}\n\nfunc (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) ", "output": "{\n\treq = cloneRequest(req)\n\tua := req.Header.Get(\"User-Agent\")\n\tif ua == \"\" {\n\t\tua = userAgent\n\t} else {\n\t\tua = fmt.Sprintf(\"%s;%s\", ua, userAgent)\n\t}\n\treq.Header.Set(\"User-Agent\", ua)\n\treturn t.Base.RoundTrip(req)\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"github.com/go-swagger/go-swagger/errors\"\n\t\"github.com/go-swagger/go-swagger/strfmt\"\n\t\"github.com/go-swagger/go-swagger/swag\"\n)\n\n\ntype TopicPageableResult struct {\n\n\tContent []Topic `json:\"content,omitempty\"`\n\n\tFirst bool `json:\"first,omitempty\"`\n\n\tLast bool `json:\"last,omitempty\"`\n\n\tNumber int32 `json:\"number,omitempty\"`\n\n\tNumberOfElements int32 `json:\"numberOfElements,omitempty\"`\n\n\tServerTime int64 `json:\"serverTime,omitempty\"`\n\n\tSize int32 `json:\"size,omitempty\"`\n\n\tTotalElements int32 `json:\"totalElements,omitempty\"`\n\n\tTotalPages int32 `json:\"totalPages,omitempty\"`\n}\n\n\nfunc (m *TopicPageableResult) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateContent(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\nfunc (m *TopicPageableResult) validateContent(formats strfmt.Registry) error ", "output": "{\n\n\tif swag.IsZero(m.Content) { \n\t\treturn nil\n\t}\n\n\tfor i := 0; i < len(m.Content); i++ {\n\n\t\tif err := m.Content[i].Validate(formats); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}"} {"input": "package kvstore\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/cilium/cilium/pkg/metrics\"\n\t\"github.com/cilium/cilium/pkg/option\"\n)\n\nconst (\n\tmetricDelete = \"delete\"\n\tmetricRead = \"read\"\n\tmetricSet = \"set\"\n)\n\n\n\nfunc increaseMetric(key, kind, action string, duration time.Duration, err error) {\n\tif !option.Config.MetricsConfig.KVStoreOperationsDurationEnabled {\n\t\treturn\n\t}\n\tnamespace := getScopeFromKey(key)\n\toutcome := metrics.Error2Outcome(err)\n\tmetrics.KVStoreOperationsDuration.\n\t\tWithLabelValues(namespace, kind, action, outcome).Observe(duration.Seconds())\n}\n\nfunc trackEventQueued(key string, typ EventType, duration time.Duration) {\n\tif !option.Config.MetricsConfig.KVStoreEventsQueueDurationEnabled {\n\t\treturn\n\t}\n\tmetrics.KVStoreEventsQueueDuration.WithLabelValues(getScopeFromKey(key), typ.String()).Observe(duration.Seconds())\n}\n\nfunc recordQuorumError(err string) {\n\tif !option.Config.MetricsConfig.KVStoreQuorumErrorsEnabled {\n\t\treturn\n\t}\n\tmetrics.KVStoreQuorumErrors.WithLabelValues(err).Inc()\n}\n\nfunc getScopeFromKey(key string) string ", "output": "{\n\ts := strings.SplitN(key, \"/\", 5)\n\tif len(s) != 5 {\n\t\tif len(key) >= 12 {\n\t\t\treturn key[:12]\n\t\t}\n\t\treturn key\n\t}\n\treturn fmt.Sprintf(\"%s/%s\", s[2], s[3])\n}"} {"input": "package internalversion\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\tapi \"k8s.io/kubernetes/pkg/api\"\n)\n\ntype TestgroupInterface interface {\n\tRESTClient() rest.Interface\n\tTestTypesGetter\n}\n\n\ntype TestgroupClient struct {\n\trestClient rest.Interface\n}\n\nfunc (c *TestgroupClient) TestTypes(namespace string) TestTypeInterface {\n\treturn newTestTypes(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*TestgroupClient, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TestgroupClient{client}, nil\n}\n\n\n\n\n\n\nfunc New(c rest.Interface) *TestgroupClient {\n\treturn &TestgroupClient{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tg, err := api.Registry.Group(\"testgroup.k8s.io\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.APIPath = \"/apis\"\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\tif config.GroupVersion == nil || config.GroupVersion.Group != g.GroupVersion.Group {\n\t\tcopyGroupVersion := g.GroupVersion\n\t\tconfig.GroupVersion = ©GroupVersion\n\t}\n\tconfig.NegotiatedSerializer = api.Codecs\n\n\tif config.QPS == 0 {\n\t\tconfig.QPS = 5\n\t}\n\tif config.Burst == 0 {\n\t\tconfig.Burst = 10\n\t}\n\treturn nil\n}\n\n\n\nfunc (c *TestgroupClient) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfigOrDie(c *rest.Config) *TestgroupClient ", "output": "{\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}"} {"input": "package prometheus_test\n\nimport (\n\t\"runtime\"\n\n\t\"github.com/coreos/etcd/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto\"\n\t\"github.com/coreos/etcd/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus\"\n\tdto \"github.com/coreos/etcd/Godeps/_workspace/src/github.com/prometheus/client_model/go\"\n)\n\nfunc NewCallbackMetric(desc *prometheus.Desc, callback func() float64) *CallbackMetric {\n\tresult := &CallbackMetric{desc: desc, callback: callback}\n\tresult.Init(result) \n\treturn result\n}\n\n\n\n\n\n\n\n\n\n\ntype CallbackMetric struct {\n\tprometheus.SelfCollector\n\n\tdesc *prometheus.Desc\n\tcallback func() float64\n}\n\nfunc (cm *CallbackMetric) Desc() *prometheus.Desc {\n\treturn cm.desc\n}\n\n\n\nfunc ExampleSelfCollector() {\n\tm := NewCallbackMetric(\n\t\tprometheus.NewDesc(\n\t\t\t\"runtime_goroutines_count\",\n\t\t\t\"Total number of goroutines that currently exist.\",\n\t\t\tnil, nil, \n\t\t),\n\t\tfunc() float64 {\n\t\t\treturn float64(runtime.NumGoroutine())\n\t\t},\n\t)\n\tprometheus.MustRegister(m)\n}\n\nfunc (cm *CallbackMetric) Write(m *dto.Metric) error ", "output": "{\n\tm.Untyped = &dto.Untyped{Value: proto.Float64(cm.callback())}\n\treturn nil\n}"} {"input": "package dlp \n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}\n\n\n\n\nfunc DefaultAuthScopes() []string ", "output": "{\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t}\n}"} {"input": "package httphandlers\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\n\t_ \"github.com/jamesrr39/tracks-app/build/client/statik\"\n\t\"github.com/rakyll/statik/fs\"\n)\n\n\n\nfunc NewClientHandler() http.Handler ", "output": "{\n\tstatikFS, err := fs.New()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn http.FileServer(statikFS)\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\n\t. \"github.com/emicklei/go-restful/v3\"\n)\n\n\n\n\n\n\n\n\nfunc main() {\n\tDefaultContainer.Router(CurlyRouter{})\n\tws := new(WebService)\n\n\tws.Route(ws.GET(\"/resource:validate\").To(validateHandler))\n\tws.Route(ws.POST(\"/resource/{resourceId}:init\").To(initHandler))\n\tws.Route(ws.POST(\"/resource/{resourceId}:recycle\").To(recycleHandler))\n\n\tAdd(ws)\n\n\tprintln(\"[go-restful] serve path tails from http:localhost:8080/basepath\")\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\n\n\nfunc initHandler(req *Request, resp *Response) {\n\tio.WriteString(resp, \"init resource completed, resourceId: \"+req.PathParameter(\"resourceId\"))\n}\n\nfunc recycleHandler(req *Request, resp *Response) {\n\tio.WriteString(resp, \"recycle resource completed, resourceId: \"+req.PathParameter(\"resourceId\"))\n}\n\nfunc validateHandler(req *Request, resp *Response) ", "output": "{\n\tio.WriteString(resp, \"validate resource completed\")\n}"} {"input": "package shutdown\n\nimport (\n\t\"log\"\n\t\"os/exec\"\n\t\"strconv\"\n)\n\n\n\nfunc start(sec int) {\n\trun(\"/s\", \"/t\", strconv.Itoa(sec))\n}\n\n\nfunc run(args ...string) {\n\tcmd := exec.Command(\"shutdown\", args...)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Println(\"error: \" + err.Error())\n\t}\n}\n\nfunc abort() ", "output": "{\n\trun(\"/a\")\n}"} {"input": "package cli\n\nimport (\n\t\"os\"\n\t\"fmt\"\n)\n\n\ntype Cmd interface {\n\tKey() string\n\tDescription() string\n\tExecute(args []string) error\n\tPrintUsage()\n}\n\n\n\ntype CmdHandler interface {\n\tRegisterCmd(Cmd)\n\tHandle()\n\tHandleCmd(key string, args []string)\n\tPrintUsage()\n}\n\n\nfunc NewCmdHandler() CmdHandler {\n\th := initCmdHandler()\n\th.RegisterCmd(NewBuildCmd())\n\treturn h\n}\n\nfunc initCmdHandler() *cmdHandler {\n\th := new(cmdHandler)\n\th.cmds = make(map[string]Cmd)\n\treturn h\n}\n\ntype cmdHandler struct {\n\tcmds map[string]Cmd\n}\n\nfunc (h *cmdHandler) RegisterCmd(cmd Cmd) {\n\tkey := cmd.Key()\n\th.cmds[key] = cmd\n}\n\nfunc (h *cmdHandler) Handle() {\n\targs := os.Args\n\tif args == nil || len(args) < 2 {\n\t\th.handleUsageError(\"Insufficient arguments\")\n\t\treturn\n\t} \n\tkey := args[1]\n\tcmdArgs := args[2:]\n\th.HandleCmd(key, cmdArgs)\n}\n\nfunc (h *cmdHandler) PrintUsage() {\n}\n\n\n\n\nfunc (h *cmdHandler) handleUsageError(message string) {\n\tfmt.Println(message)\n\th.PrintUsage()\n}\n\n\nfunc (h *cmdHandler) handleError(err error) {\n\tfmt.Println(err)\n}\n\nfunc (h *cmdHandler) HandleCmd(key string, args []string) ", "output": "{\n\tcmd := h.cmds[key]\n\tif cmd == nil {\n\t\th.handleUsageError(\"Unrecognized command: \" + key)\n\t\treturn\n\t}\n\terr := cmd.Execute(args)\n\tif err != nil {\n\t\th.handleError(err)\n\t}\n}"} {"input": "package zookeeper\n\nimport (\n\t\"os\"\n)\n\n\n\n\n\n\nfunc GetZookeeperEnvHost() string {\n\thost := os.Getenv(\"ZOOKEEPER_HOST\")\n\n\tif len(host) == 0 {\n\t\thost = \"localhost\"\n\t}\n\treturn host\n}\n\n\n\n\n\n\nfunc GetZookeeperEnvPort() string ", "output": "{\n\tport := os.Getenv(\"ZOOKEEPER_PORT\")\n\n\tif len(port) == 0 {\n\t\tport = \"2181\"\n\t}\n\treturn port\n}"} {"input": "package wrappedstreams\n\nimport (\n\t\"os\"\n\t\"sync\"\n)\n\nvar initOnce sync.Once\n\n\n\nfunc initPlatform() ", "output": "{\n\tinitOnce.Do(func() {\n\t\twrappedStdin = os.NewFile(uintptr(3), \"stdin\")\n\t\twrappedStdout = os.NewFile(uintptr(4), \"stdout\")\n\t\twrappedStderr = os.NewFile(uintptr(5), \"stderr\")\n\t})\n}"} {"input": "package service\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/utils/shell\"\n\n\t\"github.com/juju/juju/juju/osenv\"\n\t\"github.com/juju/juju/service/common\"\n)\n\nconst (\n\tmaxAgentFiles = 20000\n\n\tagentServiceTimeout = 300 \n)\n\n\n\nfunc AgentConf(info AgentInfo, renderer shell.Renderer) common.Conf {\n\tconf := common.Conf{\n\t\tDesc: fmt.Sprintf(\"juju agent for %s\", info.name),\n\t\tExecStart: info.cmd(renderer),\n\t\tLogfile: info.logFile(renderer),\n\t\tEnv: osenv.FeatureFlags(),\n\t\tTimeout: agentServiceTimeout,\n\t}\n\n\tswitch info.Kind {\n\tcase AgentKindMachine:\n\t\tconf.Limit = map[string]int{\n\t\t\t\"nofile\": maxAgentFiles,\n\t\t}\n\tcase AgentKindUnit:\n\t\tconf.Desc = \"juju unit agent for \" + info.ID\n\t}\n\n\treturn conf\n}\n\n\n\n\n\n\nfunc ContainerAgentConf(info AgentInfo, renderer shell.Renderer, containerType string) common.Conf {\n\tconf := AgentConf(info, renderer)\n\n\tenvVars := map[string]string{\n\t\tosenv.JujuContainerTypeEnvKey: containerType,\n\t}\n\tosenv.MergeEnvironment(envVars, conf.Env)\n\tconf.Env = envVars\n\n\treturn conf\n}\n\n\n\n\n\nfunc shutdownAfterConf(serviceName, desc string) common.Conf {\n\treturn common.Conf{\n\t\tDesc: desc,\n\t\tTransient: true,\n\t\tAfterStopped: serviceName,\n\t\tExecStart: \"/sbin/shutdown -h now\",\n\t}\n}\n\nfunc ShutdownAfterConf(serviceName string) (common.Conf, error) ", "output": "{\n\tif serviceName == \"\" {\n\t\treturn common.Conf{}, errors.New(`missing \"after\" service name`)\n\t}\n\tdesc := \"juju shutdown job\"\n\treturn shutdownAfterConf(serviceName, desc), nil\n}"} {"input": "package unionfs\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\n\n\n\nfunc Getxattr(path string, attr string, dest []byte) (sz int, err error) ", "output": "{\n\tvar _p0 *byte\n\t_p0, err = syscall.BytePtrFromString(path)\n\tif err != nil {\n\t\treturn\n\t}\n\tvar _p1 *byte\n\t_p1, err = syscall.BytePtrFromString(attr)\n\tif err != nil {\n\t\treturn\n\t}\n\tvar _p2 unsafe.Pointer\n\tif len(dest) > 0 {\n\t\t_p2 = unsafe.Pointer(&dest[0])\n\t} else {\n\t\tvar _zero uintptr\n\t\t_p2 = unsafe.Pointer(&_zero)\n\t}\n\tr0, _, e1 := syscall.Syscall6(syscall.SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0)\n\tsz = int(r0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}"} {"input": "package token\n\nimport (\n\t\"time\"\n\n\t\"github.com/plimble/clover/oauth2\"\n)\n\ntype ClientCredentialsGrantType struct {\n\tAccessTokenLifespan int\n}\n\n\n\nfunc (g *ClientCredentialsGrantType) Name() string {\n\treturn \"client_credentials\"\n}\n\nfunc (g *ClientCredentialsGrantType) CreateToken(grantData *GrantData, client *oauth2.Client, storage oauth2.Storage, tokenGen oauth2.TokenGenerator) (string, string, error) {\n\tatoken, err := tokenGen.CreateAccessToken(&oauth2.CreateAccessTokenRequest{\n\t\tClientID: client.ID,\n\t\tScopes: grantData.Scopes,\n\t\tExpiresIn: grantData.AccessTokenLifespan,\n\t\tExtras: grantData.Extras,\n\t})\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tat := &oauth2.AccessToken{\n\t\tAccessToken: atoken,\n\t\tClientID: client.ID,\n\t\tScopes: grantData.Scopes,\n\t\tExpired: time.Now().UTC().Add(time.Second * time.Duration(grantData.AccessTokenLifespan)).Unix(),\n\t\tExpiresIn: grantData.AccessTokenLifespan,\n\t\tExtras: grantData.Extras,\n\t}\n\n\tif err = storage.SaveAccessToken(at); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\treturn atoken, \"\", nil\n}\n\nfunc (g *ClientCredentialsGrantType) GrantRequest(req *TokenHandlerRequest, client *oauth2.Client, storage oauth2.Storage) (*GrantData, error) ", "output": "{\n\tif client.Public {\n\t\treturn nil, InvalidClient(\"public client is not allowed for client_credential grant type\")\n\t}\n\n\treturn &GrantData{\n\t\tScopes: client.Scopes,\n\t\tAccessTokenLifespan: g.AccessTokenLifespan,\n\t\tIncludeRefreshToken: false,\n\t}, nil\n}"} {"input": "package node\n\nimport (\n\t\"os\"\n\n\t\"github.com/cilium/cilium/pkg/logging/logfields\"\n)\n\nvar (\n\tnodeName = \"localhost\"\n)\n\n\n\n\n\n\n\nfunc SetName(name string) {\n\tnodeName = name\n}\n\n\n\n\nfunc GetName() string {\n\treturn nodeName\n}\n\n\n\nfunc init() ", "output": "{\n\tif h, err := os.Hostname(); err != nil {\n\t\tlog.WithError(err).Warn(\"Unable to retrieve local hostname\")\n\t} else {\n\t\tlog.WithField(logfields.NodeName, h).Debug(\"os.Hostname() returned\")\n\t\tnodeName = h\n\t}\n}"} {"input": "package solid\n\nimport \"github.com/cpmech/gosl/chk\"\n\n\ntype OnedState struct {\n\n\tSig float64 \n\n\tAlp []float64 \n\tDgam float64 \n\tLoading bool \n\n\tPhi []float64 \n\n\tF float64 \n}\n\n\n\nfunc NewOnedState(nalp, nphi int) *OnedState {\n\tvar state OnedState\n\tif nalp > 0 {\n\t\tstate.Alp = make([]float64, nalp)\n\t}\n\tif nphi > 0 {\n\t\tstate.Phi = make([]float64, nphi)\n\t}\n\treturn &state\n}\n\n\n\n\n\n\n\nfunc (o *OnedState) GetCopy() *OnedState {\n\tother := NewOnedState(len(o.Alp), len(o.Phi))\n\tother.Set(o)\n\treturn other\n}\n\nfunc (o *OnedState) Set(other *OnedState) ", "output": "{\n\to.Sig = other.Sig\n\to.Dgam = other.Dgam\n\to.Loading = other.Loading\n\tchk.IntAssert(len(o.Alp), len(other.Alp))\n\tchk.IntAssert(len(o.Phi), len(other.Phi))\n\tcopy(o.Alp, other.Alp)\n\tcopy(o.Phi, other.Phi)\n\to.F = other.F\n}"} {"input": "package packet_proxy\n\nimport (\n\t\"github.com/bettercap/bettercap/session\"\n)\n\ntype PacketProxy struct {\n\tsession.SessionModule\n}\n\nfunc NewPacketProxy(s *session.Session) *PacketProxy {\n\treturn &PacketProxy{\n\t\tSessionModule: session.NewSessionModule(\"packet.proxy\", s),\n\t}\n}\n\nfunc (mod PacketProxy) Name() string {\n\treturn \"packet.proxy\"\n}\n\nfunc (mod PacketProxy) Description() string {\n\treturn \"Not supported on this OS\"\n}\n\nfunc (mod PacketProxy) Author() string {\n\treturn \"Simone Margaritelli \"\n}\n\nfunc (mod *PacketProxy) Configure() (err error) {\n\treturn session.ErrNotSupported\n}\n\nfunc (mod *PacketProxy) Start() error {\n\treturn session.ErrNotSupported\n}\n\n\n\nfunc (mod *PacketProxy) Stop() error ", "output": "{\n\treturn session.ErrNotSupported\n}"} {"input": "package sidekick\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\ntype stringSlice []string\n\n\nfunc (ss *stringSlice) Set(s string) error { *ss = append(*ss, s); return nil }\n\nvar (\n\tDebug bool\n\n\tskips stringSlice\n\tcases stringSlice\n)\n\nfunc init() {\n\tflag.Var(&skips, \"skip\", \"skip test case\")\n\tflag.Var(&cases, \"case\", \"run test case\")\n\tflag.BoolVar(&Debug, \"debug\", false, \"enter debug mode\")\n\n\tlog.SetFlags(log.Lshortfile | log.LstdFlags)\n}\n\n\n\n\nfunc SkipCase(c interface{}) bool {\n\tfor _, item := range skips {\n\t\tif item == fmt.Sprint(c) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tfor _, item := range cases {\n\t\tif item == fmt.Sprint(c) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif len(cases) > 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (ss stringSlice) String() string ", "output": "{ return strings.Join(ss, \",\") }"} {"input": "package keybindings\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/atotto/clipboard\"\n\t\"github.com/dambrisco/bored/layout\"\n\t\"github.com/dambrisco/bored/reddit\"\n\t\"github.com/jroimartin/gocui\"\n\t\"github.com/toqueteos/webbrowser\"\n)\n\n\n\nfunc link(g *gocui.Gui, v *gocui.View) error {\n\tsubmission := reddit.GetCurrentSubmission()\n\twebbrowser.Open(submission.URL)\n\treturn nil\n}\n\nfunc yank(g *gocui.Gui, v *gocui.View) error {\n\tsubmission := reddit.GetCurrentSubmission()\n\tclipboard.WriteAll(submission.URL)\n\treturn nil\n}\n\nfunc comments(g *gocui.Gui, v *gocui.View) error {\n\tlayout.SetPage(layout.Comments)\n\tlayout.Clear(g, v)\n\treturn nil\n}\n\nfunc info(g *gocui.Gui, v *gocui.View) error {\n\tif layout.GetPage() == layout.List {\n\t\ts := reddit.GetCurrentSubmission()\n\t\tb := v.Buffer()\n\t\tv.Clear()\n\t\tif strings.HasPrefix(b, \"S\") {\n\t\t\tfmt.Fprint(v, layout.BuildTitleTag(s))\n\t\t} else {\n\t\t\tfmt.Fprintf(v, \"Score: %d | Subreddit: %s\", s.Score, s.Subreddit)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc enter(g *gocui.Gui, v *gocui.View) error ", "output": "{\n\tsubmission := reddit.GetCurrentSubmission()\n\twebbrowser.Open(\"https://www.reddit.com/\" + submission.Permalink)\n\treturn nil\n}"} {"input": "package container\n\nimport (\n\t\"fmt\"\n\t\"github.com/bunbunjp/gotop/dataservice/memory\"\n\t\"github.com/bunbunjp/gotop/util\"\n\t\"github.com/gizak/termui\"\n)\n\n\ntype VirtualMemoryUsageContainer struct {\n\tvirtualGauge *termui.Gauge\n}\n\n\nfunc (v *VirtualMemoryUsageContainer) Initialize() {\n}\n\n\n\n\n\nfunc (v *VirtualMemoryUsageContainer) CreateUI() termui.GridBufferer {\n\n\tv.virtualGauge = termui.NewGauge()\n\tv.virtualGauge.Width = termui.TermWidth() / 4\n\tv.virtualGauge.Height = 10\n\tv.virtualGauge.LabelAlign = termui.AlignRight\n\n\treturn v.virtualGauge\n}\n\nfunc (v *VirtualMemoryUsageContainer) UpdateRender() ", "output": "{\n\tdata := memory.GetInstance()\n\n\tv.virtualGauge.Percent = int(data.LatestVirtualStat.UsedPercent)\n\tv.virtualGauge.BorderLabel = fmt.Sprintf(\"virtual usage (%.2fGB/%.2fGB)\",\n\t\tutil.Byte2GBi(data.LatestVirtualStat.Used),\n\t\tutil.Byte2GBi(data.LatestVirtualStat.Total))\n}"} {"input": "package ipam\n\nimport (\n\t\"net\"\n\n\t\"github.com/cilium/cilium/pkg/datapath\"\n\t\"github.com/cilium/cilium/pkg/lock\"\n\n\t\"github.com/davecgh/go-spew/spew\"\n)\n\n\ntype AllocationResult struct {\n\tIP net.IP\n\n\tCIDRs []string\n\n\tPrimaryMAC string\n\n\tGatewayIP string\n\n\tExpirationUUID string\n\n\tInterfaceNumber string\n}\n\n\ntype Allocator interface {\n\tAllocate(ip net.IP, owner string) (*AllocationResult, error)\n\n\tAllocateWithoutSyncUpstream(ip net.IP, owner string) (*AllocationResult, error)\n\n\tRelease(ip net.IP) error\n\n\tAllocateNext(owner string) (*AllocationResult, error)\n\n\tAllocateNextWithoutSyncUpstream(owner string) (*AllocationResult, error)\n\n\tDump() (map[string]string, string)\n\n\tRestoreFinished()\n}\n\n\n\ntype IPBlacklist struct {\n\tips map[string]string\n}\n\n\ntype IPAM struct {\n\tnodeAddressing datapath.NodeAddressing\n\tconfig Configuration\n\n\tIPv6Allocator Allocator\n\tIPv4Allocator Allocator\n\n\towner map[string]string\n\n\texpirationTimers map[string]string\n\n\tallocatorMutex lock.RWMutex\n\n\tblacklist IPBlacklist\n}\n\n\n\n\n\nfunc (ipam *IPAM) DebugStatus() string ", "output": "{\n\tif ipam == nil {\n\t\treturn \"\"\n\t}\n\n\tipam.allocatorMutex.RLock()\n\tstr := spew.Sdump(ipam)\n\tipam.allocatorMutex.RUnlock()\n\treturn str\n}"} {"input": "package format\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/types\"\n)\n\ntype podHandler func(*v1.Pod) string\n\n\n\n\n\n\n\nfunc PodDesc(podName, podNamespace string, podUID types.UID) string {\n\treturn fmt.Sprintf(\"%s_%s(%s)\", podName, podNamespace, podUID)\n}\n\n\n\nfunc PodWithDeletionTimestamp(pod *v1.Pod) string {\n\tvar deletionTimestamp string\n\tif pod.DeletionTimestamp != nil {\n\t\tdeletionTimestamp = \":DeletionTimestamp=\" + pod.DeletionTimestamp.UTC().Format(time.RFC3339)\n\t}\n\treturn Pod(pod) + deletionTimestamp\n}\n\n\n\nfunc Pods(pods []*v1.Pod) string {\n\treturn aggregatePods(pods, Pod)\n}\n\n\n\nfunc PodsWithDeletiontimestamps(pods []*v1.Pod) string {\n\treturn aggregatePods(pods, PodWithDeletionTimestamp)\n}\n\nfunc aggregatePods(pods []*v1.Pod, handler podHandler) string {\n\tpodStrings := make([]string, 0, len(pods))\n\tfor _, pod := range pods {\n\t\tpodStrings = append(podStrings, handler(pod))\n\t}\n\treturn fmt.Sprintf(strings.Join(podStrings, \", \"))\n}\n\nfunc Pod(pod *v1.Pod) string ", "output": "{\n\treturn PodDesc(pod.Name, pod.Namespace, pod.UID)\n}"} {"input": "package main\nimport (\n\t\"net/http\"\n\tmv \"github.com/delicb/mezvaro\"\n\t\"log\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc LoggingMiddleware(c *mv.Context) {\n\tlog.Println(\"Simluate real logging here\")\n\tc.Next()\n}\n\nfunc AuthMiddleware(c *mv.Context) {\n\tlog.Println(\"Simulate user authentication.\")\n\trand.Seed(time.Now().Unix())\n\tif rand.Int() % 2 == 0 {\n\t\tc.Response.Write([]byte(\"User authenticated.\\n\"))\n\t\tc.Next()\n\t} else {\n\t\tc.Response.WriteHeader(http.StatusUnauthorized)\n\t\tc.Response.Write([]byte(\"Use not authenticated.\\n\"))\n\t\tc.Abort()\n\t}\n}\n\n\n\nfunc PrivatelyAvailable(c *mv.Context) {\n\tc.Response.Write([]byte(\"This page is only for authorized users.\"))\n}\n\nfunc main() {\n\tm := mv.New(mv.HandlerFunc(LoggingMiddleware)) \n\tauthOnly := m.Fork(mv.HandlerFunc(AuthMiddleware))\n\thttp.Handle(\"/public\", m.HF(PubliclyAvailable))\n\thttp.Handle(\"/auth\", authOnly.HF(PrivatelyAvailable))\n\thttp.ListenAndServe(\":8000\", nil)\n}\n\nfunc PubliclyAvailable(c *mv.Context) ", "output": "{\n\tc.Response.Write([]byte(\"This page is available for all users.\"))\n}"} {"input": "package main\n\n\n\n\n\nfunc collect(c []chan int) int {\n\tr := make(chan int)\n\tintSet := make(map[int]struct{})\n\n\tfor i := range c {\n\t\tgo func(f chan int) {\n\t\t\ttmp := 0\n\t\t\tfor tmp = range f {\n\t\t\t\tr <- tmp\n\t\t\t}\n\t\t\tr <- -1\n\t\t}(c[i])\n\t}\n\n\ti := 0\n\ttmp := 0\n\n\tfor i < len(c) {\n\t\ttmp = <-r\n\t\tif tmp == -1 {\n\t\t\ti++\n\t\t} else {\n\t\t\tintSet[tmp] = struct{}{}\n\t\t}\n\t}\n\n\tsum := 0\n\tfor k, _ := range intSet {\n\t\tsum += k\n\t}\n\n\treturn sum\n}\n\nfunc main() {\n\tr := []chan int{\n\t\tmake(chan int),\n\t\tmake(chan int),\n\t}\n\n\tgo listMultiples(3, 1000, r[0])\n\tgo listMultiples(5, 1000, r[1])\n\n\tprint(collect(r))\n\n}\n\nfunc listMultiples(m, max int, ret chan int) ", "output": "{\n\tif m == 0 {\n\t\treturn\n\t}\n\tcount := 0\n\ttmp := 0\n\tfor {\n\t\ttmp = count * m\n\t\tif tmp >= max {\n\t\t\tbreak\n\t\t}\n\n\t\tcount++\n\n\t\tret <- tmp\n\t}\n\n\tclose(ret)\n\n}"} {"input": "package store\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"launchpad.net/goyaml\"\n)\n\ntype Config struct {\n\tMongoURL string `yaml:\"mongo-url\"`\n\tAPIAddr string `yaml:\"api-addr\"`\n}\n\n\n\nfunc ReadConfig(path string) (*Config, error) ", "output": "{\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"opening config file: %v\", err)\n\t}\n\tdefer f.Close()\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"reading config file: %v\", err)\n\t}\n\tconf := new(Config)\n\terr = goyaml.Unmarshal(data, conf)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"processing config file: %v\", err)\n\t}\n\treturn conf, nil\n}"} {"input": "package dockertools\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\tdocker \"github.com/fsouza/go-dockerclient\"\n\tkubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\"\n)\n\n\n\nconst (\n\tstatusRunningPrefix = \"Up\"\n\tstatusExitedPrefix = \"Exited\"\n)\n\n\n\n\nfunc toRuntimeContainer(c *docker.APIContainers) (*kubecontainer.Container, error) {\n\tif c == nil {\n\t\treturn nil, fmt.Errorf(\"unable to convert a nil pointer to a runtime container\")\n\t}\n\n\tdockerName, hash, err := getDockerContainerNameInfo(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &kubecontainer.Container{\n\t\tID: kubecontainer.DockerID(c.ID).ContainerID(),\n\t\tName: dockerName.ContainerName,\n\t\tImage: c.Image,\n\t\tHash: hash,\n\t\tCreated: c.Created,\n\t\tState: mapState(c.Status),\n\t}, nil\n}\n\n\nfunc toRuntimeImage(image *docker.APIImages) (*kubecontainer.Image, error) {\n\tif image == nil {\n\t\treturn nil, fmt.Errorf(\"unable to convert a nil pointer to a runtime image\")\n\t}\n\n\treturn &kubecontainer.Image{\n\t\tID: image.ID,\n\t\tRepoTags: image.RepoTags,\n\t\tSize: image.VirtualSize,\n\t}, nil\n}\n\nfunc mapState(state string) kubecontainer.ContainerState ", "output": "{\n\tswitch {\n\tcase strings.HasPrefix(state, statusRunningPrefix):\n\t\treturn kubecontainer.ContainerStateRunning\n\tcase strings.HasPrefix(state, statusExitedPrefix):\n\t\treturn kubecontainer.ContainerStateExited\n\tdefault:\n\t\treturn kubecontainer.ContainerStateUnknown\n\t}\n}"} {"input": "package cache\n\nimport (\n\t\"k8s.io/client-go/1.5/pkg/util/clock\"\n\t\"k8s.io/client-go/1.5/pkg/util/sets\"\n)\n\ntype fakeThreadSafeMap struct {\n\tThreadSafeStore\n\tdeletedKeys chan<- string\n}\n\n\n\ntype FakeExpirationPolicy struct {\n\tNeverExpire sets.String\n\tRetrieveKeyFunc KeyFunc\n}\n\nfunc (p *FakeExpirationPolicy) IsExpired(obj *timestampedEntry) bool {\n\tkey, _ := p.RetrieveKeyFunc(obj)\n\treturn !p.NeverExpire.Has(key)\n}\n\nfunc NewFakeExpirationStore(keyFunc KeyFunc, deletedKeys chan<- string, expirationPolicy ExpirationPolicy, cacheClock clock.Clock) Store {\n\tcacheStorage := NewThreadSafeStore(Indexers{}, Indices{})\n\treturn &ExpirationCache{\n\t\tcacheStorage: &fakeThreadSafeMap{cacheStorage, deletedKeys},\n\t\tkeyFunc: keyFunc,\n\t\tclock: cacheClock,\n\t\texpirationPolicy: expirationPolicy,\n\t}\n}\n\nfunc (c *fakeThreadSafeMap) Delete(key string) ", "output": "{\n\tif c.deletedKeys != nil {\n\t\tc.ThreadSafeStore.Delete(key)\n\t\tc.deletedKeys <- key\n\t}\n}"} {"input": "package iso20022\n\n\ntype StandingSettlementInstruction9 struct {\n\n\tSettlementStandingInstructionDatabase *SettlementStandingInstructionDatabase3Choice `xml:\"SttlmStgInstrDB\"`\n\n\tVendor *PartyIdentification32Choice `xml:\"Vndr,omitempty\"`\n\n\tOtherDeliveringSettlementParties *SettlementParties23 `xml:\"OthrDlvrgSttlmPties,omitempty\"`\n\n\tOtherReceivingSettlementParties *SettlementParties23 `xml:\"OthrRcvgSttlmPties,omitempty\"`\n}\n\n\n\nfunc (s *StandingSettlementInstruction9) AddVendor() *PartyIdentification32Choice {\n\ts.Vendor = new(PartyIdentification32Choice)\n\treturn s.Vendor\n}\n\nfunc (s *StandingSettlementInstruction9) AddOtherDeliveringSettlementParties() *SettlementParties23 {\n\ts.OtherDeliveringSettlementParties = new(SettlementParties23)\n\treturn s.OtherDeliveringSettlementParties\n}\n\nfunc (s *StandingSettlementInstruction9) AddOtherReceivingSettlementParties() *SettlementParties23 {\n\ts.OtherReceivingSettlementParties = new(SettlementParties23)\n\treturn s.OtherReceivingSettlementParties\n}\n\nfunc (s *StandingSettlementInstruction9) AddSettlementStandingInstructionDatabase() *SettlementStandingInstructionDatabase3Choice ", "output": "{\n\ts.SettlementStandingInstructionDatabase = new(SettlementStandingInstructionDatabase3Choice)\n\treturn s.SettlementStandingInstructionDatabase\n}"} {"input": "package models\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/dchest/uniuri\"\n\t\"github.com/koding/bongo\"\n\t\"github.com/stvp/slug\"\n)\n\n\nfunc Slugify(message *ChannelMessage) (*ChannelMessage, error) {\n\n\tif message.TypeConstant != ChannelMessage_TYPE_POST {\n\t\treturn message, nil\n\t}\n\n\tslug.Replacement = '-'\n\tres := NewChannelMessage()\n\n\tsuggestedSlug := slug.Clean(message.Body)\n\tif len(suggestedSlug) > 80 {\n\t\tsuggestedSlug = suggestedSlug[:79]\n\t}\n\n\tquery := map[string]interface{}{\n\t\t\"slug\": suggestedSlug,\n\t}\n\n\trand.Seed(time.Now().UnixNano())\n\n\tfor tryCount := 0; tryCount < 10; tryCount++ {\n\t\tif err := res.One(bongo.NewQS(query)); err != nil {\n\t\t\tif err != bongo.RecordNotFound {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tmessage.Slug = suggestedSlug\n\t\t\treturn message, nil\n\t\t}\n\t\tsuggestedSlug = suggestedSlug + \"-\" + strconv.Itoa(rand.Intn(1000000000))\n\t\tquery[\"slug\"] = suggestedSlug\n\t}\n\n\treturn nil, fmt.Errorf(\"couldnt generate unique slug:%s\", message.Slug)\n}\n\n\n\nfunc RandomGroupName() string {\n\trand.Seed(time.Now().UnixNano())\n\treturn \"group\" + strconv.FormatInt(rand.Int63(), 10)\n}\n\nfunc ZeroDate() time.Time {\n\treturn time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC)\n}\n\nfunc RandomName() string ", "output": "{\n\treturn uniuri.New()\n}"} {"input": "import \"sort\"\n\ntype Schedule struct {\n intervals []Interval\n}\n\nfunc (s *Schedule) Len() int {\n return len(s.intervals)\n}\n\nfunc (s *Schedule) Less(i, j int) bool {\n if s.intervals[i].Start < s.intervals[j].Start {\n return true\n }\n return false\n}\n\n\n\nfunc (s *Schedule) Check() bool {\n for i:=0; i s.intervals[i+1].Start {\n return false\n }\n }\n return true\n}\n\nfunc canAttendMeetings(intervals []Interval) bool {\n if len(intervals) <= 1 {\n return true\n }\n s := Schedule{intervals}\n sort.Sort(&s)\n return s.Check()\n}\n\nfunc (s *Schedule) Swap(i, j int) ", "output": "{\n s.intervals[i], s.intervals[j] = s.intervals[j], s.intervals[i]\n}"} {"input": "package wicore\n\nimport \"fmt\"\n\nconst _BorderType_name = \"BorderNoneBorderSingleBorderDouble\"\n\nvar _BorderType_index = [...]uint8{0, 10, 22, 34}\n\nfunc (i BorderType) String() string {\n\tif i < 0 || i+1 >= BorderType(len(_BorderType_index)) {\n\t\treturn fmt.Sprintf(\"BorderType(%d)\", i)\n\t}\n\treturn _BorderType_name[_BorderType_index[i]:_BorderType_index[i+1]]\n}\n\nconst _CommandCategory_name = \"UnknownCategoryWindowCategoryCommandsCategoryEditorCategoryDebugCategory\"\n\nvar _CommandCategory_index = [...]uint8{0, 15, 29, 45, 59, 72}\n\n\n\nconst _DockingType_name = \"DockingUnknownDockingFillDockingFloatingDockingLeftDockingRightDockingTopDockingBottom\"\n\nvar _DockingType_index = [...]uint8{0, 14, 25, 40, 51, 63, 73, 86}\n\nfunc (i DockingType) String() string {\n\tif i < 0 || i+1 >= DockingType(len(_DockingType_index)) {\n\t\treturn fmt.Sprintf(\"DockingType(%d)\", i)\n\t}\n\treturn _DockingType_name[_DockingType_index[i]:_DockingType_index[i+1]]\n}\n\nconst _KeyboardMode_name = \"NormalInsertAllMode\"\n\nvar _KeyboardMode_index = [...]uint8{0, 6, 12, 19}\n\nfunc (i KeyboardMode) String() string {\n\ti -= 1\n\tif i < 0 || i+1 >= KeyboardMode(len(_KeyboardMode_index)) {\n\t\treturn fmt.Sprintf(\"KeyboardMode(%d)\", i+1)\n\t}\n\treturn _KeyboardMode_name[_KeyboardMode_index[i]:_KeyboardMode_index[i+1]]\n}\n\nfunc (i CommandCategory) String() string ", "output": "{\n\tif i < 0 || i+1 >= CommandCategory(len(_CommandCategory_index)) {\n\t\treturn fmt.Sprintf(\"CommandCategory(%d)\", i)\n\t}\n\treturn _CommandCategory_name[_CommandCategory_index[i]:_CommandCategory_index[i+1]]\n}"} {"input": "package datacatalog\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteCustomPropertyRequest struct {\n\n\tCatalogId *string `mandatory:\"true\" contributesTo:\"path\" name:\"catalogId\"`\n\n\tNamespaceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"namespaceId\"`\n\n\tCustomPropertyKey *string `mandatory:\"true\" contributesTo:\"path\" name:\"customPropertyKey\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request DeleteCustomPropertyRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request DeleteCustomPropertyRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request DeleteCustomPropertyRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteCustomPropertyResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteCustomPropertyResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteCustomPropertyResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteCustomPropertyRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package gorm_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/nkovacs/gorm\"\n)\n\ntype CalculateField struct {\n\tgorm.Model\n\tName string\n\tChildren []CalculateFieldChild\n\tCategory CalculateFieldCategory\n\tEmbeddedField\n}\n\ntype EmbeddedField struct {\n\tEmbeddedName string `sql:\"NOT NULL;DEFAULT:'hello'\"`\n}\n\ntype CalculateFieldChild struct {\n\tgorm.Model\n\tCalculateFieldID uint\n\tName string\n}\n\ntype CalculateFieldCategory struct {\n\tgorm.Model\n\tCalculateFieldID uint\n\tName string\n}\n\n\n\nfunc TestCalculateField(t *testing.T) ", "output": "{\n\tvar field CalculateField\n\tvar scope = DB.NewScope(&field)\n\tif field, ok := scope.FieldByName(\"Children\"); !ok || field.Relationship == nil {\n\t\tt.Errorf(\"Should calculate fields correctly for the first time\")\n\t}\n\n\tif field, ok := scope.FieldByName(\"Category\"); !ok || field.Relationship == nil {\n\t\tt.Errorf(\"Should calculate fields correctly for the first time\")\n\t}\n\n\tif field, ok := scope.FieldByName(\"embedded_name\"); !ok {\n\t\tt.Errorf(\"should find embedded field\")\n\t} else if _, ok := field.TagSettings[\"NOT NULL\"]; !ok {\n\t\tt.Errorf(\"should find embedded field's tag settings\")\n\t}\n}"} {"input": "package controller\n\nimport (\n\t\"github.com/tmacychen/UFG/framework\"\n\t\"github.com/tmacychen/UFG/framework/outer\"\n)\n\ntype AttachableOuter interface {\n\touter.Relayouter\n}\n\ntype Attachable struct {\n\touter AttachableOuter\n\tonAttach framework.Event\n\tonDetach framework.Event\n\tattached bool\n}\n\nfunc (a *Attachable) Init(outer AttachableOuter) {\n\ta.outer = outer\n}\n\n\n\nfunc (a *Attachable) Attach() {\n\tif a.attached {\n\t\tpanic(\"Control already attached\")\n\t}\n\ta.attached = true\n\tif a.onAttach != nil {\n\t\ta.onAttach.Fire()\n\t}\n}\n\nfunc (a *Attachable) Detach() {\n\tif !a.attached {\n\t\tpanic(\"Control already detached\")\n\t}\n\ta.attached = false\n\tif a.onDetach != nil {\n\t\ta.onDetach.Fire()\n\t}\n}\n\nfunc (a *Attachable) OnAttach(f func()) framework.EventSubscription {\n\tif a.onAttach == nil {\n\t\ta.onAttach = CreateEvent(func() {})\n\t}\n\treturn a.onAttach.Listen(f)\n}\n\nfunc (a *Attachable) OnDetach(f func()) framework.EventSubscription {\n\tif a.onDetach == nil {\n\t\ta.onDetach = CreateEvent(func() {})\n\t}\n\treturn a.onDetach.Listen(f)\n}\n\nfunc (a *Attachable) Attached() bool ", "output": "{\n\treturn a.attached\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/api/scheduling/v1beta1\"\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\t\"k8s.io/client-go/kubernetes/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype SchedulingV1beta1Interface interface {\n\tRESTClient() rest.Interface\n\tPriorityClassesGetter\n}\n\n\ntype SchedulingV1beta1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *SchedulingV1beta1Client) PriorityClasses() PriorityClassInterface {\n\treturn newPriorityClasses(c)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*SchedulingV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SchedulingV1beta1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *SchedulingV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *SchedulingV1beta1Client {\n\treturn &SchedulingV1beta1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc (c *SchedulingV1beta1Client) RESTClient() rest.Interface ", "output": "{\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}"} {"input": "package testing\n\nimport \"k8s.io/kubernetes/pkg/util/iptables\"\n\n\ntype fake struct{}\n\nfunc NewFake() *fake {\n\treturn &fake{}\n}\n\nfunc (*fake) EnsureChain(table iptables.Table, chain iptables.Chain) (bool, error) {\n\treturn true, nil\n}\n\nfunc (*fake) FlushChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) DeleteChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) EnsureRule(position iptables.RulePosition, table iptables.Table, chain iptables.Chain, args ...string) (bool, error) {\n\treturn true, nil\n}\n\n\n\nfunc (*fake) IsIpv6() bool {\n\treturn false\n}\n\nfunc (*fake) Save(table iptables.Table) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\nfunc (*fake) SaveAll() ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\nfunc (*fake) Restore(table iptables.Table, data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\n\nfunc (*fake) RestoreAll(data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\nfunc (*fake) AddReloadFunc(reloadFunc func()) {}\n\nfunc (*fake) Destroy() {}\n\nvar _ = iptables.Interface(&fake{})\n\nfunc (*fake) DeleteRule(table iptables.Table, chain iptables.Chain, args ...string) error ", "output": "{\n\treturn nil\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/astaxie/beego/context\"\n\t\"github.com/yangji168/omsystem/hauth/hcache\"\n\t\"github.com/yangji168/omsystem/utils/hret\"\n)\n\nfunc IndexPage(ctx *context.Context) {\n\trst, err := hcache.GetStaticFile(\"AsofdateIndexPage\")\n\tif err != nil {\n\t\thret.WriteHttpErrMsgs(ctx.ResponseWriter, 404, \"页面不存在\")\n\t\treturn\n\t}\n\tctx.ResponseWriter.Write(rst)\n}\n\n\n\nfunc init() ", "output": "{\n\thcache.Register(\"AsofdateIndexPage\", \"./views/login.tpl\")\n}"} {"input": "package qrcode\n\ntype Version int8\n\n\n\nfunc (v Version) PatternSize() int ", "output": "{\n\treturn 4*int(v) + 17\n}"} {"input": "package app\n\nimport (\n\t\"net/url\"\n)\n\ntype Service interface {\n\tProxyPath() string\n\tURL() string\n\tBasicAuth() (username, password string, ok bool)\n\tAddSecret(parameters url.Values)\n}\n\ntype basicAuthService struct {\n\tproxyPath, url, clientId, clientSecret string\n}\n\nfunc (s basicAuthService) ProxyPath() string {\n\treturn s.proxyPath\n}\n\nfunc (s basicAuthService) URL() string {\n\treturn s.url\n}\n\nfunc (s basicAuthService) BasicAuth() (string, string, bool) {\n\treturn s.clientId, s.clientSecret, true\n}\n\nfunc (s basicAuthService) AddSecret(parameters url.Values) {\n}\n\ntype addParameterService struct {\n\tproxyPath, url, parameterName, clientSecret string\n}\n\nfunc (s addParameterService) ProxyPath() string {\n\treturn s.proxyPath\n}\n\n\n\nfunc (s addParameterService) BasicAuth() (string, string, bool) {\n\treturn \"\", \"\", false\n}\n\nfunc (s addParameterService) AddSecret(parameters url.Values) {\n\tparameters.Add(s.parameterName, s.clientSecret)\n}\n\nfunc BasicAuthService(proxyPath, url, clientId, clientSecret string) Service {\n\treturn basicAuthService{proxyPath, url, clientId, clientSecret}\n}\n\nfunc AddParameterService(proxyPath, url, parameterName, clientSecret string) Service {\n\treturn addParameterService{proxyPath, url, parameterName, clientSecret}\n}\n\nfunc (s addParameterService) URL() string ", "output": "{\n\treturn s.url\n}"} {"input": "package markdownutils\n\nimport (\n\t\"strings\"\n\t\"unicode\"\n)\n\n\nfunc CreateGitHubAnchor(text string) string {\n\tvar anchorName []rune\n\n\tfor _, r := range []rune(strings.TrimSpace(text)) {\n\t\tswitch {\n\t\tcase r == ' ' || r == '-':\n\t\t\tanchorName = append(anchorName, '-')\n\t\tcase unicode.IsLetter(r) || unicode.IsNumber(r):\n\t\t\tanchorName = append(anchorName, unicode.ToLower(r))\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn string(anchorName)\n}\n\n\n\n\nfunc CreateGitLabAnchor(text string) string ", "output": "{\n\tvar anchorName []rune\n\tvar lastWasDash = false\n\n\tfor _, r := range []rune(strings.TrimSpace(text)) {\n\t\tswitch {\n\t\tcase r == ' ' || r == '-':\n\t\t\tif !lastWasDash {\n\t\t\t\tanchorName = append(anchorName, '-')\n\t\t\t\tlastWasDash = true\n\t\t\t}\n\t\tcase unicode.IsLetter(r) || unicode.IsNumber(r):\n\t\t\tanchorName = append(anchorName, unicode.ToLower(r))\n\t\t\tlastWasDash = false\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn string(anchorName)\n}"} {"input": "package daemon\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime/middleware\"\n)\n\n\ntype GetHealthzHandlerFunc func(GetHealthzParams) middleware.Responder\n\n\n\n\n\ntype GetHealthzHandler interface {\n\tHandle(GetHealthzParams) middleware.Responder\n}\n\n\nfunc NewGetHealthz(ctx *middleware.Context, handler GetHealthzHandler) *GetHealthz {\n\treturn &GetHealthz{Context: ctx, Handler: handler}\n}\n\n\ntype GetHealthz struct {\n\tContext *middleware.Context\n\tHandler GetHealthzHandler\n}\n\nfunc (o *GetHealthz) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\tr = rCtx\n\t}\n\tvar Params = NewGetHealthzParams()\n\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params) \n\n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}\n\nfunc (fn GetHealthzHandlerFunc) Handle(params GetHealthzParams) middleware.Responder ", "output": "{\n\treturn fn(params)\n}"} {"input": "package api\n\nimport (\n\t\"github.com/mattermost/platform/model\"\n)\n\ntype LogoutProvider struct {\n}\n\nconst (\n\tCMD_LOGOUT = \"logout\"\n)\n\nfunc init() {\n\tRegisterCommandProvider(&LogoutProvider{})\n}\n\nfunc (me *LogoutProvider) GetTrigger() string {\n\treturn CMD_LOGOUT\n}\n\nfunc (me *LogoutProvider) GetCommand(c *Context) *model.Command {\n\treturn &model.Command{\n\t\tTrigger: CMD_LOGOUT,\n\t\tAutoComplete: true,\n\t\tAutoCompleteDesc: c.T(\"api.command_logout.desc\"),\n\t\tAutoCompleteHint: \"\",\n\t\tDisplayName: c.T(\"api.command_logout.name\"),\n\t}\n}\n\n\n\nfunc (me *LogoutProvider) DoCommand(c *Context, channelId string, message string) *model.CommandResponse ", "output": "{\n\treturn &model.CommandResponse{GotoLocation: \"/logout\", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: c.T(\"api.command_logout.success_message\")}\n}"} {"input": "package unix\n\nimport \"syscall\"\n\nfunc setTimespec(sec, nsec int64) Timespec {\n\treturn Timespec{Sec: int32(sec), Nsec: int32(nsec)}\n}\n\nfunc setTimeval(sec, usec int64) Timeval {\n\treturn Timeval{Sec: int32(sec), Usec: int32(usec)}\n}\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint32(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint32(length)\n}\n\n\n\nfunc (msghdr *Msghdr) SetIovlen(length int) {\n\tmsghdr.Iovlen = int32(length)\n}\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\nfunc Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)\n\nfunc (msghdr *Msghdr) SetControllen(length int) ", "output": "{\n\tmsghdr.Controllen = uint32(length)\n}"} {"input": "package config\n\nimport (\n\tcb \"github.com/hyperledger/fabric/protos/common\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n\t\"github.com/hyperledger/fabric/protos/utils\"\n)\n\nfunc ordererConfigGroup(key string, value []byte) *cb.ConfigGroup {\n\tresult := cb.NewConfigGroup()\n\tresult.Groups[OrdererGroupKey] = cb.NewConfigGroup()\n\tresult.Groups[OrdererGroupKey].Values[key] = &cb.ConfigValue{\n\t\tValue: value,\n\t}\n\treturn result\n}\n\n\nfunc TemplateConsensusType(typeValue string) *cb.ConfigGroup {\n\treturn ordererConfigGroup(ConsensusTypeKey, utils.MarshalOrPanic(&ab.ConsensusType{Type: typeValue}))\n}\n\n\n\n\n\nfunc TemplateBatchTimeout(batchTimeout string) *cb.ConfigGroup {\n\treturn ordererConfigGroup(BatchTimeoutKey, utils.MarshalOrPanic(&ab.BatchTimeout{Timeout: batchTimeout}))\n}\n\n\nfunc TemplateChannelRestrictions(maxChannels uint64) *cb.ConfigGroup {\n\treturn ordererConfigGroup(ChannelRestrictionsKey, utils.MarshalOrPanic(&ab.ChannelRestrictions{MaxCount: maxChannels}))\n}\n\n\nfunc TemplateKafkaBrokers(brokers []string) *cb.ConfigGroup {\n\treturn ordererConfigGroup(KafkaBrokersKey, utils.MarshalOrPanic(&ab.KafkaBrokers{Brokers: brokers}))\n}\n\nfunc TemplateBatchSize(batchSize *ab.BatchSize) *cb.ConfigGroup ", "output": "{\n\treturn ordererConfigGroup(BatchSizeKey, utils.MarshalOrPanic(batchSize))\n}"} {"input": "package main\n\nimport \"github.com/augustoroman/serial_lcd\"\n\ntype FakeLcd struct{}\n\n\nfunc (f FakeLcd) SetOn(On bool) error { return nil }\nfunc (f FakeLcd) SetBrightness(b uint8) error { return nil }\nfunc (f FakeLcd) SetContrast(c uint8) error { return nil }\nfunc (f FakeLcd) SetAutoscroll(On bool) error { return nil }\nfunc (f FakeLcd) SetSize(cols, rows uint8) error { return nil }\nfunc (f FakeLcd) Clear() error { return nil }\nfunc (f FakeLcd) Home() error { return nil }\nfunc (f FakeLcd) MoveTo(col, row uint8) error { return nil }\nfunc (f FakeLcd) MoveForward() error { return nil }\nfunc (f FakeLcd) MoveBack() error { return nil }\nfunc (f FakeLcd) Write(b []byte) (int, error) { return len(b), nil }\n\nfunc (f FakeLcd) CreateCustomChar(spot uint8, c serial_lcd.Char) error { return nil }\n\nfunc (f FakeLcd) SetBG(r, g, b uint8) error ", "output": "{ return nil }"} {"input": "package kubectl\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n)\n\n\n\n\ntype FilterFunc func(runtime.Object, PrintOptions) bool\n\n\ntype Filters []FilterFunc\n\nfunc NewResourceFilter() Filters {\n\treturn []FilterFunc{\n\t\tfilterPods,\n\t}\n}\n\n\n\nfunc filterPods(obj runtime.Object, options PrintOptions) bool {\n\tswitch p := obj.(type) {\n\tcase *v1.Pod:\n\t\treason := string(p.Status.Phase)\n\t\tif p.Status.Reason != \"\" {\n\t\t\treason = p.Status.Reason\n\t\t}\n\t\treturn !options.ShowAll && (reason == string(v1.PodSucceeded) || reason == string(v1.PodFailed))\n\tcase *api.Pod:\n\t\treason := string(p.Status.Phase)\n\t\tif p.Status.Reason != \"\" {\n\t\t\treason = p.Status.Reason\n\t\t}\n\t\treturn !options.ShowAll && (reason == string(api.PodSucceeded) || reason == string(api.PodFailed))\n\t}\n\treturn false\n}\n\n\n\n\n\nfunc DecodeUnknownObject(obj runtime.Object) (runtime.Object, error) {\n\tvar err error\n\n\tswitch obj.(type) {\n\tcase runtime.Unstructured, *runtime.Unknown:\n\t\tif objBytes, err := runtime.Encode(api.Codecs.LegacyCodec(), obj); err == nil {\n\t\t\tif decodedObj, err := runtime.Decode(api.Codecs.UniversalDecoder(), objBytes); err == nil {\n\t\t\t\tobj = decodedObj\n\t\t\t}\n\t\t}\n\t}\n\n\treturn obj, err\n}\n\nfunc (f Filters) Filter(obj runtime.Object, opts *PrintOptions) (bool, error) ", "output": "{\n\tobj, _ = DecodeUnknownObject(obj)\n\n\tfor _, filter := range f {\n\t\tif ok := filter(obj, *opts); ok {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}"} {"input": "package testing\n\nimport (\n\t\"testing\"\n\n\t\"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/networks\"\n\t\"github.com/gophercloud/gophercloud/pagination\"\n\tth \"github.com/gophercloud/gophercloud/testhelper\"\n\t\"github.com/gophercloud/gophercloud/testhelper/client\"\n)\n\nfunc TestList(t *testing.T) {\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\tHandleListSuccessfully(t)\n\n\tcount := 0\n\terr := networks.List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) {\n\t\tcount++\n\t\tactual, err := networks.ExtractNetworks(page)\n\t\tth.AssertNoErr(t, err)\n\t\tth.CheckDeepEquals(t, ExpectedNetworkSlice, actual)\n\n\t\treturn true, nil\n\t})\n\tth.AssertNoErr(t, err)\n\tth.CheckEquals(t, 1, count)\n}\n\n\n\nfunc TestGet(t *testing.T) ", "output": "{\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\tHandleGetSuccessfully(t)\n\n\tactual, err := networks.Get(client.ServiceClient(), \"20c8acc0-f747-4d71-a389-46d078ebf000\").Extract()\n\tth.AssertNoErr(t, err)\n\tth.CheckDeepEquals(t, &SecondNetwork, actual)\n}"} {"input": "package resources\n\nimport (\n\t\"sort\"\n\n\t\"encoding/json\"\n\n\t\"github.com/mitchellh/mapstructure\"\n)\n\n\ntype AWSServerlessApplication_Location struct {\n\tString *string\n\n\tApplicationLocation *AWSServerlessApplication_ApplicationLocation\n}\n\nfunc (r AWSServerlessApplication_Location) value() interface{} {\n\n\tif r.String != nil {\n\t\treturn r.String\n\t}\n\n\tret := []interface{}{}\n\n\tif r.ApplicationLocation != nil {\n\t\tret = append(ret, *r.ApplicationLocation)\n\t}\n\n\tsort.Sort(byJSONLength(ret))\n\tif len(ret) > 0 {\n\t\treturn ret[0]\n\t}\n\n\treturn nil\n\n}\n\nfunc (r AWSServerlessApplication_Location) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(r.value())\n}\n\n\n\n\nfunc (r *AWSServerlessApplication_Location) UnmarshalJSON(b []byte) error ", "output": "{\n\n\tvar typecheck interface{}\n\tif err := json.Unmarshal(b, &typecheck); err != nil {\n\t\treturn err\n\t}\n\n\tswitch val := typecheck.(type) {\n\n\tcase string:\n\t\tr.String = &val\n\n\tcase map[string]interface{}:\n\n\t\tmapstructure.Decode(val, &r.ApplicationLocation)\n\n\tcase []interface{}:\n\n\t}\n\n\treturn nil\n}"} {"input": "package koalanet\n\nimport \"testing\"\n\nvar t1 *testing.T\n\nvar tkm_arg1 int\n\ntype TestKoalanetMain struct {\n\tActor\n}\n\nfunc (tkm *TestKoalanetMain) Init(args interface{}, reply interface{}) error {\n\ttkm_arg1 = 2\n\treturn nil\n}\n\nfunc (tkm *TestKoalanetMain) SendTest(args interface{}, reply interface{}) error {\n\n\treturn nil\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Benchmark_koalanet_send(b *testing.B) ", "output": "{\n\tRegActor(\"TestKoalanetMain\", func() IActor {\n\t\tactor := &TestKoalanetMain{}\n\t\tactor.InitActor()\n\t\tactor.RegMethod(\"Init\", actor.Init)\n\t\tactor.RegMethod(\"SendTest\", actor.SendTest)\n\t\treturn actor\n\t})\n\n\thTKM := NewActor(\"TestKoalanetMain\", nil)\n\n\tfor i := 0; i < b.N; i++ {\n\t\tSend(hTKM, \"SendTest\", nil)\n\t}\n\n\tKillActor(hTKM, false)\n\n\tWaitActorQuit(hTKM)\n}"} {"input": "package osutil\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\ntype ReplacingWriter struct {\n\tWriter io.Writer\n\tFrom byte\n\tTo []byte\n}\n\n\n\nfunc (w ReplacingWriter) Write(bs []byte) (int, error) ", "output": "{\n\tvar n, written int\n\tvar err error\n\n\tnewlineIdx := bytes.IndexByte(bs, w.From)\n\tfor newlineIdx >= 0 {\n\t\tn, err = w.Writer.Write(bs[:newlineIdx])\n\t\twritten += n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif len(w.To) > 0 {\n\t\t\tn, err := w.Writer.Write(w.To)\n\t\t\tif n == len(w.To) {\n\t\t\t\twritten++\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tbs = bs[newlineIdx+1:]\n\t\tnewlineIdx = bytes.IndexByte(bs, w.From)\n\t}\n\n\tn, err = w.Writer.Write(bs)\n\twritten += n\n\n\treturn written, err\n}"} {"input": "package xtest\n\nimport (\n\t\"sync\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\ntype SC struct {\n\tC\n\tsync.WaitGroup\n\tsync.Mutex\n}\n\nfunc (c *SC) Convey(items ...interface{}) {\n\tpanic(\"Convey in SyncConvey Context not supported\")\n}\n\nfunc (c *SC) So(actual interface{},\n\tassert func(actual interface{}, expected ...interface{}) string, expected ...interface{}) {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.C.So(actual, assert, expected)\n}\n\nfunc (c *SC) SoMsg(msg string, actual interface{},\n\tassert func(actual interface{}, expected ...interface{}) string, expected ...interface{}) {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.C.SoMsg(msg, actual, assert, expected...)\n}\n\nfunc (c *SC) Recover() {\n\tif r := recover(); r != nil {\n\t\tif rString, ok := r.(string); ok && rString == \"___FAILURE_HALT___\" {\n\t\t\treturn\n\t\t}\n\t\tpanic(r)\n\t}\n}\n\n\n\n\n\n\n\nfunc SoMsgError(msg string, err error, shouldBeError bool) {\n\tif shouldBeError == true {\n\t\tSoMsg(msg, err, ShouldNotBeNil)\n\t} else {\n\t\tSoMsg(msg, err, ShouldBeNil)\n\t}\n}\n\nfunc Parallel(f, g func(sc *SC)) func(c C) ", "output": "{\n\treturn func(c C) {\n\t\tsc := &SC{C: c}\n\t\tsc.Add(1)\n\t\tgo func() {\n\t\t\tdefer sc.Done()\n\t\t\tdefer sc.Recover()\n\t\t\tg(sc)\n\t\t}()\n\t\tdefer sc.Wait()\n\t\tdefer sc.Recover()\n\t\tf(sc)\n\t}\n}"} {"input": "package supervisor\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestSupervisor(t *testing.T) {\n\tsv := create()\n\tin := sv.conf.Begin.Add(time.Second * 10)\n\tout := sv.conf.End.Add(time.Second * 10)\n\n\tif sv.forbid(\"GET\", in) {\n\t\tt.Error(\"Request should never be blocked on GET method\")\n\t}\n\n\tif !sv.forbid(\"POST\", in) {\n\t\tt.Errorf(\"Request should be blocked on POST method at %+v\", in)\n\t}\n\n\tif sv.forbid(\"POST\", out) {\n\t\tt.Errorf(\"Request should not be blocked at %+v\", out)\n\t}\n}\n\nfunc TestReload(t *testing.T) {\n\tzero := time.Unix(0, 0)\n\tconf := &Config{\n\t\tOn: false,\n\t\tBegin: zero,\n\t\tEnd: zero,\n\t}\n\tsv := create()\n\n\tsv.Reload(nil)\n\n\tsv.Reload(conf)\n\n\tif sv.conf != conf && sv.on == false {\n\t\tt.Errorf(\"Failed to reload config %+v, current config is %+v\", conf, sv.conf)\n\t}\n}\n\nfunc create() *Supervisor ", "output": "{\n\tnow := time.Now()\n\tend := now.Add(time.Hour * 1)\n\tconf := &Config{\n\t\tOn: true,\n\t\tBegin: now,\n\t\tEnd: end,\n\t}\n\treturn New(conf)\n}"} {"input": "package suggest\n\nimport (\n\t\"github.com/google/btree\"\n\t\"sync\"\n)\n\n\ntype Suggester interface {\n\tSuggest(max int, q string) (result []string)\n}\n\n\ntype Adder interface {\n\tAdd(s string)\n}\n\n\n\ntype Engine struct {\n\tincomingCh chan string\n\tawaitCh chan bool\n\tlock sync.RWMutex\n\tsuggestions *btree.BTree\n}\n\n\nfunc NewEngine() *Engine {\n\treturn newEngine()\n}\n\n\n\n\n\n\nfunc (e *Engine) Add(s string) {\n\te.add(s)\n}\n\n\n\n\n\nfunc (e *Engine) Suggest(max int, q string) (result []string) {\n\treturn e.suggest(max, q)\n}\n\n\n\nfunc NewSuggester(suggestions ...string) Suggester {\n\treturn newSuggester(suggestions)\n}\n\nfunc (e *Engine) Await() ", "output": "{\n\te.await()\n}"} {"input": "package openapi\n\nimport (\n\t\"net/http\"\n)\n\n\ntype APIResponse struct {\n\t*http.Response `json:\"-\"`\n\tMessage string `json:\"message,omitempty\"`\n\tOperation string `json:\"operation,omitempty\"`\n\tRequestURL string `json:\"url,omitempty\"`\n\tMethod string `json:\"method,omitempty\"`\n\tPayload []byte `json:\"-\"`\n}\n\n\n\n\n\nfunc NewAPIResponseWithError(errorMessage string) *APIResponse {\n\n\tresponse := &APIResponse{Message: errorMessage}\n\treturn response\n}\n\nfunc NewAPIResponse(r *http.Response) *APIResponse ", "output": "{\n\n\tresponse := &APIResponse{Response: r}\n\treturn response\n}"} {"input": "package lnwire\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\ntype NeighborAckMessage struct {\n\tRoutingMessageBase\n}\n\nfunc (msg *NeighborAckMessage) String() string {\n\treturn fmt.Sprintf(\"NeighborAckMessage{%v %v}\", msg.SenderID, msg.ReceiverID)\n}\n\nfunc (msg *NeighborAckMessage) Command() uint32{\n\treturn CmdNeighborAckMessage\n}\n\nfunc (msg *NeighborAckMessage) Encode(w io.Writer, pver uint32) error{\n\treturn nil\n}\n\nfunc (msg *NeighborAckMessage) Decode(r io.Reader, pver uint32) error{\n\treturn nil\n}\n\n\n\nfunc (msg *NeighborAckMessage) Validate() error{\n\treturn nil\n}\n\nvar _ Message = (*NeighborAckMessage)(nil)\n\nfunc (msg *NeighborAckMessage) MaxPayloadLength(uint32) uint32", "output": "{\n\treturn 0\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/api/certificates/v1beta1\"\n\t\"k8s.io/client-go/kubernetes/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype CertificatesV1beta1Interface interface {\n\tRESTClient() rest.Interface\n\tCertificateSigningRequestsGetter\n}\n\n\ntype CertificatesV1beta1Client struct {\n\trestClient rest.Interface\n}\n\n\n\n\nfunc NewForConfig(c *rest.Config) (*CertificatesV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &CertificatesV1beta1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *CertificatesV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *CertificatesV1beta1Client {\n\treturn &CertificatesV1beta1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *CertificatesV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc (c *CertificatesV1beta1Client) CertificateSigningRequests() CertificateSigningRequestInterface ", "output": "{\n\treturn newCertificateSigningRequests(c)\n}"} {"input": "package expression\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com/richardwilkes/goblin/ast\"\n)\n\n\ntype Vars struct {\n\tast.PosImpl\n\tLeft []ast.Expr\n\tOperator string\n\tRight []ast.Expr\n}\n\n\n\n\nfunc (expr *Vars) Invoke(scope ast.Scope) (reflect.Value, error) {\n\trv := ast.NilValue\n\tvar err error\n\tvar vs []interface{}\n\tfor _, Right := range expr.Right {\n\t\trv, err = Right.Invoke(scope)\n\t\tif err != nil {\n\t\t\treturn rv, ast.NewError(Right, err)\n\t\t}\n\t\tswitch {\n\t\tcase rv == ast.NilValue:\n\t\t\tvs = append(vs, nil)\n\t\tcase rv.IsValid() && rv.CanInterface():\n\t\t\tvs = append(vs, rv.Interface())\n\t\tdefault:\n\t\t\tvs = append(vs, nil)\n\t\t}\n\t}\n\trvs := reflect.ValueOf(vs)\n\tfor i, Left := range expr.Left {\n\t\tif i >= rvs.Len() {\n\t\t\tbreak\n\t\t}\n\t\tv := rvs.Index(i)\n\t\tif v.Kind() == reflect.Interface {\n\t\t\tv = v.Elem()\n\t\t}\n\t\t_, err = Left.Assign(v, scope)\n\t\tif err != nil {\n\t\t\treturn rvs, ast.NewError(Left, err)\n\t\t}\n\t}\n\treturn rvs, nil\n}\n\n\nfunc (expr *Vars) Assign(rv reflect.Value, scope ast.Scope) (reflect.Value, error) {\n\treturn ast.NilValue, ast.NewInvalidOperationError(expr)\n}\n\nfunc (expr *Vars) String() string ", "output": "{\n\tvar buffer bytes.Buffer\n\tfor i, one := range expr.Left {\n\t\tif i != 0 {\n\t\t\tbuffer.WriteString(\", \")\n\t\t}\n\t\tfmt.Fprintf(&buffer, \"%v\", one)\n\t}\n\tbuffer.WriteString(\" \")\n\tbuffer.WriteString(expr.Operator)\n\tbuffer.WriteString(\" \")\n\tfor i, one := range expr.Right {\n\t\tif i != 0 {\n\t\t\tbuffer.WriteString(\", \")\n\t\t}\n\t\tfmt.Fprintf(&buffer, \"%v\", one)\n\t}\n\treturn buffer.String()\n}"} {"input": "package hashmap\n\n\n\n\n\ntype Map interface {\n\tLen() int\n\tIndex(k interface{}) (interface{}, bool)\n\tAssoc(k, v interface{}) Map\n\tDissoc(k interface{}) Map\n\tIterator() Iterator\n}\n\n\n\n\n\n\n\ntype Iterator interface {\n\tElem() (interface{}, interface{})\n\tHasElem() bool\n\tNext()\n}\n\n\n\n\nfunc HasKey(m Map, k interface{}) bool ", "output": "{\n\t_, ok := m.Index(k)\n\treturn ok\n}"} {"input": "package devices\n\n\n\ntype Device interface {\n\tBind(driver string) error\n\tUnbind() error\n\tCurrentDriver() (string, error)\n\tProbe() error\n\tID() string\n}\n\n\n\n\n\nfunc NewDeviceByPciID(pciID string) (Device, error) {\n\tdevice, err := GetPciDeviceByPciID(pciID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn device, nil\n}\n\n\nfunc NewDeviceByVmbusID(uuid string) (Device, error) {\n\tdevice, err := GetVmbusDeviceByUUID(uuid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn device, nil\n}\n\n\nfunc NewDeviceByNicName(nicName string) (Device, error) {\n\tdevID, err := GetDeviceID(nicName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdevice, err := newDevice(devID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn device, nil\n}\n\nfunc newDevice(id string) (Device, error) {\n\tif IsPciID.Match([]byte(id)) {\n\t\treturn GetPciDeviceByPciID(id)\n\t}\n\treturn GetVmbusDeviceByUUID(id)\n}\n\nfunc New(input string) (Device, error) ", "output": "{\n\tswitch {\n\tcase IsPciID.Match([]byte(input)):\n\t\treturn NewDeviceByPciID(input)\n\tcase IsUUID.Match([]byte(input)):\n\t\treturn NewDeviceByVmbusID(input)\n\tdefault:\n\t\treturn NewDeviceByNicName(input)\n\t}\n}"} {"input": "package simelection\n\nimport \"sync\"\n\n\n\ntype Election struct {\n\tmu sync.RWMutex\n\tmasters []string\n}\n\n\nfunc (e *Election) IsMaster(who string) bool {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tfor _, m := range e.masters {\n\t\tif m == who {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\n\n\nfunc (e *Election) SetMaster(who string) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\te.masters = []string{who}\n}\n\n\nfunc (e *Election) SetMasters(who []string) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\te.masters = who\n}\n\nfunc (e *Election) Masters() []string ", "output": "{\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\treturn e.masters\n}"} {"input": "package v2\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/gophercloud/gophercloud/acceptance/clients\"\n\t\"github.com/gophercloud/gophercloud/acceptance/tools\"\n\t\"github.com/gophercloud/gophercloud/openstack/workflow/v2/crontriggers\"\n\tth \"github.com/gophercloud/gophercloud/testhelper\"\n)\n\n\n\nfunc TestCronTriggersList(t *testing.T) {\n\tclient, err := clients.NewWorkflowV2Client()\n\tth.AssertNoErr(t, err)\n\tworkflow, err := CreateWorkflow(t, client)\n\tth.AssertNoErr(t, err)\n\tdefer DeleteWorkflow(t, client, workflow)\n\ttrigger, err := CreateCronTrigger(t, client, workflow)\n\tth.AssertNoErr(t, err)\n\tdefer DeleteCronTrigger(t, client, trigger)\n\tlist, err := ListCronTriggers(t, client, &crontriggers.ListOpts{\n\t\tName: &crontriggers.ListFilter{\n\t\t\tFilter: crontriggers.FilterEQ,\n\t\t\tValue: trigger.Name,\n\t\t},\n\t\tPattern: &crontriggers.ListFilter{\n\t\t\tValue: \"0 0 1 1 *\",\n\t\t},\n\t\tCreatedAt: &crontriggers.ListDateFilter{\n\t\t\tFilter: crontriggers.FilterGT,\n\t\t\tValue: time.Now().AddDate(-1, 0, 0),\n\t\t},\n\t})\n\tth.AssertNoErr(t, err)\n\tth.AssertEquals(t, 1, len(list))\n\ttools.PrintResource(t, list)\n}\n\nfunc TestCronTriggersCreateGetDelete(t *testing.T) ", "output": "{\n\tclient, err := clients.NewWorkflowV2Client()\n\tth.AssertNoErr(t, err)\n\n\tworkflow, err := CreateWorkflow(t, client)\n\tth.AssertNoErr(t, err)\n\tdefer DeleteWorkflow(t, client, workflow)\n\n\ttrigger, err := CreateCronTrigger(t, client, workflow)\n\tth.AssertNoErr(t, err)\n\tdefer DeleteCronTrigger(t, client, trigger)\n\n\tgettrigger, err := GetCronTrigger(t, client, trigger.ID)\n\tth.AssertNoErr(t, err)\n\n\tth.AssertEquals(t, trigger.ID, gettrigger.ID)\n\n\ttools.PrintResource(t, trigger)\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n)\n\nfunc main() {\n\n\tif len(os.Args) == 1 {\n\t\tfmt.Println(\"Please provide either a file path or a number input\")\n\n\t} else {\n\n\t\tinput := os.Args[1]\n\t\tfile, err := os.Open(input)\n\n\t\tif check(err) == false {\n\t\t\tdefer file.Close()\n\n\t\t\treader := bufio.NewReader(file)\n\t\t\tscanner := bufio.NewScanner(reader)\n\n\t\t\tfor scanner.Scan() {\n\t\t\t\tvalue := scanner.Text()\n\t\t\t\tif value == \"#\" {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tvalue = cleanString(value)\n\n\t\t\t\tnum := stringToInt(value)\n\t\t\t\tif num <= 15 {\n\t\t\t\t\tfmt.Println(factorial(num))\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else if check(err) == true {\n\t\t\tintInput := stringToInt(input)\n\n\t\t\toutput := factorial(intInput)\n\t\t\tfmt.Println(output)\n\n\t\t}\n\n\t}\n\n}\n\nfunc factorial(number int64) (factor int64) {\n\tfactor = 1\n\n\tif number == 1 {\n\t\treturn\n\t} else {\n\n\t\tvar counter int64 = 1\n\n\t\tfor i := counter; i <= number; i++ {\n\t\t\tfactor = factor * i\n\t\t}\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc stringToInt(input string) int64 {\n\tresult, _ := strconv.ParseInt(input, 10, 0)\n\treturn result\n}\n\nfunc check(e error) bool {\n\tif e != nil {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc cleanString(value string) (result string) ", "output": "{\n\n\tr := regexp.MustCompile(`\\d+`)\n\tmatches := r.FindAllString(value, -1)\n\n\tfor _, value := range matches {\n\t\tresult += value\n\t}\n\n\treturn\n}"} {"input": "package log\n\n\nfunc (me *Logging) Prefix() string {\n\treturn me.prefix\n}\n\n\nfunc (me *Logging) SetPrefix(value string) {\n\tme.prefix = value\n\tif me.console != nil {\n\t\tme.console.SetPrefix(me.prefix)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPrefix(me.prefix)\n\t}\n}\n\n\nfunc (me *Logging) Priority() int {\n\treturn me.priority\n}\n\n\nfunc (me *Logging) SetPriority(value int) {\n\tme.setPriority = true\n\tme.priority = value\n\tif me.console != nil {\n\t\tme.console.SetPriority(me.priority)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPriority(me.priority)\n\t}\n}\n\n\nfunc (me *Logging) Layouts() int {\n\treturn me.layouts\n}\n\n\nfunc (me *Logging) SetLayouts(value int) {\n\tme.setLayouts = true\n\tme.layouts = value\n\tif me.console != nil {\n\t\tme.console.SetLayouts(me.layouts)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetLayouts(me.layouts)\n\t}\n}\n\n\n\n\n\nfunc (me *Logging) SetOutputs(value int) {\n\tme.setOutputs = true\n\tme.outputs = value\n}\n\nfunc (me *Logging) Outputs() int ", "output": "{\n\treturn me.outputs\n}"} {"input": "package imagick\n\n\nimport \"C\"\nimport (\n\t\"runtime\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\nvar (\n\tinitOnce sync.Once\n\tterminateOnce *sync.Once\n\n\tcanTerminate = make(chan struct{}, 1)\n\n\tenvSemaphore = make(chan struct{}, 1)\n\n\tmagickWandCounter int64\n\tdrawingWandCounter int64\n\tpixelIteratorCounter int64\n\tpixelWandCounter int64\n)\n\n\n\n\n\n\nfunc Terminate() {\n\tenvSemaphore <- struct{}{}\n\tdefer func() {\n\t\t<-envSemaphore\n\t}()\n\n\tif terminateOnce != nil {\n\t\tterminateOnce.Do(func() {\n\t\t\truntime.GC()\n\t\t\tterminate()\n\t\t})\n\t}\n}\n\n\n\nfunc terminate() {\n\t<-canTerminate\n\tC.MagickWandTerminus()\n\tinitOnce = sync.Once{}\n}\n\n\nfunc setCanTerminate() {\n\tif isImageMagickCleaned() {\n\t\tselect {\n\t\tcase canTerminate <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n}\n\n\nfunc unsetCanTerminate() {\n\tselect {\n\tcase <-canTerminate:\n\tdefault:\n\t}\n}\n\n\nfunc isImageMagickCleaned() bool {\n\tif atomic.LoadInt64(&magickWandCounter) != 0 || atomic.LoadInt64(&drawingWandCounter) != 0 || atomic.LoadInt64(&pixelIteratorCounter) != 0 || atomic.LoadInt64(&pixelWandCounter) != 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc Initialize() ", "output": "{\n\tenvSemaphore <- struct{}{}\n\tdefer func() {\n\t\t<-envSemaphore\n\t}()\n\n\tinitOnce.Do(func() {\n\t\tC.MagickWandGenesis()\n\t\tterminateOnce = &sync.Once{}\n\t\tsetCanTerminate()\n\t})\n}"} {"input": "package main\n\nimport \"testing\"\n\n\n\nfunc TestLoadConfig(t *testing.T) ", "output": "{\n\tcfg, err := LoadConfig(\"config_test.json\")\n\tif err != nil {\n\t\tt.Error(\"Error should be nil\")\n\t}\n\tif cfg == nil {\n\t\tt.Error(\"Config should not be nil\")\n\t}\n}"} {"input": "package g\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/toolkits/file\"\n)\n\n\n\n\n\n\nfunc IsRrdFileExist(filename string) bool {\n\treturn file.IsExist(filename)\n}\n\n\nfunc FormRrdCacheKey(md5 string, dsType string, step int) string {\n\treturn md5 + \"_\" + dsType + \"_\" + strconv.Itoa(step)\n}\nfunc SplitRrdCacheKey(ckey string) (md5 string, dsType string, step int, err error) {\n\tckey_slice := strings.Split(ckey, \"_\")\n\tif len(ckey_slice) != 3 {\n\t\terr = fmt.Errorf(\"bad rrd cache key: %s\", ckey)\n\t\treturn\n\t}\n\n\tmd5 = ckey_slice[0]\n\tdsType = ckey_slice[1]\n\tstepInt64, err := strconv.ParseInt(ckey_slice[2], 10, 32)\n\tif err != nil {\n\t\treturn\n\t}\n\tstep = int(stepInt64)\n\n\terr = nil\n\treturn\n}\n\n\nfunc IsValidString(str string) bool {\n\n\tr := []rune(str)\n\n\tfor _, t := range r {\n\t\tswitch t {\n\t\tcase '\\r':\n\t\t\treturn false\n\t\tcase '\\n':\n\t\t\treturn false\n\t\tcase '\\'':\n\t\t\treturn false\n\t\tcase '\"':\n\t\t\treturn false\n\t\tcase '>':\n\t\t\treturn false\n\t\tcase '\\032':\n\t\t\treturn false\n\t\tdefault:\n\t\t\tif !unicode.IsPrint(t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\nfunc RrdFileName(baseDir string, md5 string, dsType string, step int) string ", "output": "{\n\treturn baseDir + \"/\" + md5[0:2] + \"/\" +\n\t\tmd5 + \"_\" + dsType + \"_\" + strconv.Itoa(step) + \".rrd\"\n}"} {"input": "package ecs\n\ntype EntityID = uint64\n\n\n\ntype Entity interface {\n\tID() EntityID\n}\n\nfunc (e EntityID) ID() EntityID ", "output": "{\n\treturn e\n}"} {"input": "package il\n\n\ntype Type uint32\n\nconst (\n\tUnknown Type = iota\n\n\tVoid\n\n\tString\n\n\tInteger\n\n\tDouble\n\n\tBool\n\n\tDuration\n\n\tInterface\n)\n\nvar typeNames = map[Type]string{\n\tUnknown: \"unknown\",\n\tVoid: \"void\",\n\tString: \"string\",\n\tInteger: \"integer\",\n\tDouble: \"double\",\n\tBool: \"bool\",\n\tDuration: \"duration\",\n\tInterface: \"interface\",\n}\n\nvar typesByName = map[string]Type{\n\t\"void\": Void,\n\t\"string\": String,\n\t\"integer\": Integer,\n\t\"double\": Double,\n\t\"bool\": Bool,\n\t\"duration\": Duration,\n\t\"interface\": Interface,\n}\n\nfunc (t Type) String() string {\n\treturn typeNames[t]\n}\n\n\n\n\nfunc GetType(name string) (Type, bool) ", "output": "{\n\tt, f := typesByName[name]\n\treturn t, f\n}"} {"input": "package images\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\n\tkubeadmapi \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm\"\n)\n\nconst (\n\tKubeEtcdImage = \"etcd\"\n\n\tKubeAPIServerImage = \"apiserver\"\n\tKubeControllerManagerImage = \"controller-manager\"\n\tKubeSchedulerImage = \"scheduler\"\n\tKubeProxyImage = \"proxy\"\n\n\tKubeDNSImage = \"k8s-dns-kube-dns\"\n\tKubeDNSmasqImage = \"k8s-dns-dnsmasq\"\n\tKubeDNSSidecarImage = \"k8s-dns-sidecar\"\n\tPause = \"pause\"\n\n\tgcrPrefix = \"gcr.io/google_containers\"\n\tetcdVersion = \"3.0.14-kubeadm\"\n\n\tkubeDNSVersion = \"1.10.1\"\n\tdnsmasqVersion = \"1.10.1\"\n\tkubeDNSSidecarVersion = \"1.10.1\"\n\tpauseVersion = \"3.0\"\n)\n\n\n\nfunc GetAddonImage(image string) string {\n\trepoPrefix := kubeadmapi.GlobalEnvParams.RepositoryPrefix\n\treturn map[string]string{\n\t\tKubeDNSImage: fmt.Sprintf(\"%s/%s-%s:%s\", repoPrefix, KubeDNSImage, runtime.GOARCH, kubeDNSVersion),\n\t\tKubeDNSmasqImage: fmt.Sprintf(\"%s/%s-%s:%s\", repoPrefix, KubeDNSmasqImage, runtime.GOARCH, dnsmasqVersion),\n\t\tKubeDNSSidecarImage: fmt.Sprintf(\"%s/%s-%s:%s\", repoPrefix, KubeDNSSidecarImage, runtime.GOARCH, kubeDNSSidecarVersion),\n\t\tPause: fmt.Sprintf(\"%s/%s-%s:%s\", repoPrefix, Pause, runtime.GOARCH, pauseVersion),\n\t}[image]\n}\n\nfunc GetCoreImage(image string, cfg *kubeadmapi.MasterConfiguration, overrideImage string) string ", "output": "{\n\tif overrideImage != \"\" {\n\t\treturn overrideImage\n\t}\n\trepoPrefix := kubeadmapi.GlobalEnvParams.RepositoryPrefix\n\treturn map[string]string{\n\t\tKubeEtcdImage: fmt.Sprintf(\"%s/%s-%s:%s\", repoPrefix, \"etcd\", runtime.GOARCH, etcdVersion),\n\t\tKubeAPIServerImage: fmt.Sprintf(\"%s/%s-%s:%s\", repoPrefix, \"kube-apiserver\", runtime.GOARCH, cfg.KubernetesVersion),\n\t\tKubeControllerManagerImage: fmt.Sprintf(\"%s/%s-%s:%s\", repoPrefix, \"kube-controller-manager\", runtime.GOARCH, cfg.KubernetesVersion),\n\t\tKubeSchedulerImage: fmt.Sprintf(\"%s/%s-%s:%s\", repoPrefix, \"kube-scheduler\", runtime.GOARCH, cfg.KubernetesVersion),\n\t\tKubeProxyImage: fmt.Sprintf(\"%s/%s-%s:%s\", repoPrefix, \"kube-proxy\", runtime.GOARCH, cfg.KubernetesVersion),\n\t}[image]\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"k8s.io/client-go/kubernetes/typed/extensions/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeExtensionsV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeExtensionsV1beta1) DaemonSets(namespace string) v1beta1.DaemonSetInterface {\n\treturn &FakeDaemonSets{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) Deployments(namespace string) v1beta1.DeploymentInterface {\n\treturn &FakeDeployments{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) Ingresses(namespace string) v1beta1.IngressInterface {\n\treturn &FakeIngresses{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) PodSecurityPolicies() v1beta1.PodSecurityPolicyInterface {\n\treturn &FakePodSecurityPolicies{c}\n}\n\nfunc (c *FakeExtensionsV1beta1) ReplicaSets(namespace string) v1beta1.ReplicaSetInterface {\n\treturn &FakeReplicaSets{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) Scales(namespace string) v1beta1.ScaleInterface {\n\treturn &FakeScales{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeExtensionsV1beta1) RESTClient() rest.Interface ", "output": "{\n\tvar ret *rest.RESTClient\n\treturn ret\n}"} {"input": "package notary\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"testing\"\n\n\t\"github.com/goharbor/harbor/src/common/utils/test\"\n)\n\ntype simpleModifier struct {\n}\n\n\n\nfunc TestRoundTrip(t *testing.T) {\n\tserver := test.NewServer(\n\t\t&test.RequestHandlerMapping{\n\t\t\tMethod: \"GET\",\n\t\t\tPattern: \"/\",\n\t\t\tHandler: test.Handler(nil),\n\t\t})\n\ttransport := NewTransport(&http.Transport{}, &simpleModifier{})\n\tclient := &http.Client{\n\t\tTransport: transport,\n\t}\n\n\treq, err := http.NewRequest(\"GET\", fmt.Sprintf(\"%s/\", server.URL), nil)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create request: %v\", err)\n\t}\n\n\tif _, err := client.Do(req); err != nil {\n\t\tt.Fatalf(\"failed to send request: %s\", err)\n\t}\n\n\theader := req.Header.Get(\"Authorization\")\n\tif header != \"token\" {\n\t\tt.Errorf(\"unexpected header: %s != %s\", header, \"token\")\n\t}\n\n}\n\nfunc (s *simpleModifier) Modify(req *http.Request) error ", "output": "{\n\treq.Header.Set(\"Authorization\", \"token\")\n\treturn nil\n}"} {"input": "package devices\n\n\n\ntype Device interface {\n\tBind(driver string) error\n\tUnbind() error\n\tCurrentDriver() (string, error)\n\tProbe() error\n\tID() string\n}\n\n\nfunc New(input string) (Device, error) {\n\tswitch {\n\tcase IsPciID.Match([]byte(input)):\n\t\treturn NewDeviceByPciID(input)\n\tcase IsUUID.Match([]byte(input)):\n\t\treturn NewDeviceByVmbusID(input)\n\tdefault:\n\t\treturn NewDeviceByNicName(input)\n\t}\n}\n\n\nfunc NewDeviceByPciID(pciID string) (Device, error) {\n\tdevice, err := GetPciDeviceByPciID(pciID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn device, nil\n}\n\n\nfunc NewDeviceByVmbusID(uuid string) (Device, error) {\n\tdevice, err := GetVmbusDeviceByUUID(uuid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn device, nil\n}\n\n\n\n\nfunc newDevice(id string) (Device, error) {\n\tif IsPciID.Match([]byte(id)) {\n\t\treturn GetPciDeviceByPciID(id)\n\t}\n\treturn GetVmbusDeviceByUUID(id)\n}\n\nfunc NewDeviceByNicName(nicName string) (Device, error) ", "output": "{\n\tdevID, err := GetDeviceID(nicName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdevice, err := newDevice(devID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn device, nil\n}"} {"input": "package decorator\n\nimport (\n\t\"fmt\"\n)\n\ntype DefaultDecorator struct {\n}\n\nfunc (i *DefaultDecorator) ToString(field interface{}) (string, error) {\n\treturn fmt.Sprintf(\"%v\", field), nil\n}\n\n\n\nfunc (i *DefaultDecorator) FromString(field string) (interface{}, error) ", "output": "{\n\treturn field, nil\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nvar (\n\tsrv *httptest.Server\n)\n\nfunc mockHandler(w http.ResponseWriter, r *http.Request) {\n}\n\nfunc setupServer() {\n\trouter := Router{mux.NewRouter()}\n\tm := RouteMap{\n\t\t\"GET\": {\n\t\t\t\"/it\": mockHandler,\n\t\t},\n\t}\n\n\trouter.AddRoutes(\"/test\", m)\n\trouter.AddCorsRoutes(\"/cors\", m)\n\tsrv = httptest.NewServer(router)\n}\n\nfunc teardownServer() {\n\tsrv.Close()\n}\n\nfunc TestRoute(t *testing.T) {\n\tsetupServer()\n\tdefer teardownServer()\n\n\tpath := srv.URL + \"/test/it\"\n\tresp, err := http.DefaultClient.Get(path)\n\n\tassert.Nil(t, err)\n\tassert.Equal(t, 200, resp.StatusCode)\n}\n\n\n\nfunc TestCorsRoute(t *testing.T) ", "output": "{\n\tsetupServer()\n\tdefer teardownServer()\n\n\tpath := srv.URL + \"/cors/it\"\n\n\treq, _ := http.NewRequest(\"GET\", path, nil)\n\treq.Header.Add(\"Origin\", srv.URL)\n\tresp, err := http.DefaultClient.Do(req)\n\n\tassert.Nil(t, err)\n\tassert.Equal(t, 200, resp.StatusCode)\n\tassert.Equal(t, srv.URL, resp.Header.Get(\"Access-Control-Allow-Origin\"), \"CORS Allow-Origin not set\")\n}"} {"input": "package sys\n\nimport \"fmt\"\n\n\n\nfunc SetFDLimits(newLimit uint64) (uint64, error) ", "output": "{\n\treturn 0, fmt.Errorf(\"Not supported\")\n}"} {"input": "package templates\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\n\n\n\n\nfunc NewGetTemplatesLibraryParamsWithTimeout(timeout time.Duration) *GetTemplatesLibraryParams {\n\n\treturn &GetTemplatesLibraryParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype GetTemplatesLibraryParams struct {\n\ttimeout time.Duration\n}\n\n\nfunc (o *GetTemplatesLibraryParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewGetTemplatesLibraryParams() *GetTemplatesLibraryParams ", "output": "{\n\n\treturn &GetTemplatesLibraryParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}"} {"input": "package utils\n\nimport \"sync\"\n\ntype queueNode struct {\n\tdata interface{}\n\tnext *queueNode\n}\n\ntype queue struct {\n\thead *queueNode\n\ttail *queueNode\n\tcount int\n\tlock *sync.Mutex\n}\n\nfunc NewQueue() *queue {\n\treturn &queue{lock: &sync.Mutex{}}\n}\n\nfunc (q *queue) Len() int {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\treturn q.count\n}\n\nfunc (q *queue) Push(v interface{}) {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tnode := &queueNode{data: v}\n\n\tif q.tail == nil {\n\t\tq.tail = node\n\t\tq.head = node\n\t} else {\n\t\tq.tail.next = node\n\t\tq.tail = node\n\t}\n\n\tq.count++\n}\n\nfunc (q *queue) Pop() interface{} {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tif q.head == nil {\n\t\treturn nil\n\t}\n\n\tnode := q.head\n\tq.head = node.next\n\n\tif q.head == nil {\n\t\tq.tail = nil\n\t}\n\n\tq.count--\n\n\treturn node.data\n}\n\n\n\nfunc (q *queue) Peek() interface{} ", "output": "{\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tnode := q.head\n\tif node == nil || node.data == nil {\n\t\treturn nil\n\t}\n\n\treturn node.data\n}"} {"input": "package rate\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestRateLimiter_Wait_noblock(t *testing.T) {\n\tstart := time.Now()\n\tlimit := 5\n\tinterval := time.Second * 3\n\tlimiter := New(limit, interval)\n\tfor i := 0; i < limit; i++ {\n\t\tlimiter.Wait()\n\t}\n\tif time.Now().Sub(start) >= interval {\n\t\tt.Error(\"The limiter blocked when it shouldn't have\")\n\t}\n}\n\n\n\nfunc TestRateLimiter_Try(t *testing.T) {\n\tlimit := 5\n\tinterval := time.Second * 3\n\tlimiter := New(limit, interval)\n\tfor i := 0; i < limit; i++ {\n\t\tif ok, _ := limiter.Try(); !ok {\n\t\t\tt.Fatalf(\"Should have allowed try on attempt %d\", i)\n\t\t}\n\t}\n\tif ok, _ := limiter.Try(); ok {\n\t\tt.Fatal(\"Should have not allowed try on final attempt\")\n\t}\n}\n\nfunc TestRateLimiter_Wait_block(t *testing.T) ", "output": "{\n\tstart := time.Now()\n\tlimit := 5\n\tinterval := time.Second * 3\n\tlimiter := New(limit, interval)\n\tfor i := 0; i < limit+1; i++ {\n\t\tlimiter.Wait()\n\t}\n\tif time.Now().Sub(start) < interval {\n\t\tt.Error(\"The limiter didn't block when it should have\")\n\t}\n}"} {"input": "package fwd\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"path\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Rel(\n\taddr, relPath string, errHandler func(*http.Request, error),\n) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tabsURL := addr + path.Join(relPath, r.URL.Path)\n\t\tparsedURL, err := url.Parse(absURL)\n\t\tif err != nil {\n\t\t\terrHandler(r, err)\n\t\t}\n\t\tparsedURL.RawQuery = r.URL.RawQuery\n\n\t\tdoProxy(parsedURL, w, r, errHandler)\n\t})\n}\n\nfunc doProxy(\n\tu *url.URL, w http.ResponseWriter, r *http.Request,\n\terrHandler func(*http.Request, error),\n) {\n\tr.URL = u\n\tresp, err := http.DefaultClient.Do(r)\n\tif err != nil {\n\t\tif errHandler != nil {\n\t\t\terrHandler(r, err)\n\t\t}\n\t\thttp.Error(w, \"unexpected server-side error\", 500)\n\t}\n\tdefer resp.Body.Close()\n\n\tfor header, vals := range resp.Header {\n\t\tw.Header()[header] = append(w.Header()[header], vals...)\n\t}\n\n\tw.WriteHeader(resp.StatusCode)\n\tio.Copy(w, resp.Body)\n}\n\nfunc Abs(absURL string, errHandler func(*http.Request, error)) http.Handler ", "output": "{\n\tparsedURL, err := url.Parse(absURL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdoProxy(parsedURL, w, r, errHandler)\n\t})\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aptly-dev/aptly/deb\"\n\t\"github.com/smira/commander\"\n)\n\n\n\nfunc makeCmdSnapshotRename() *commander.Command {\n\tcmd := &commander.Command{\n\t\tRun: aptlySnapshotRename,\n\t\tUsageLine: \"rename \",\n\t\tShort: \"renames snapshot\",\n\t\tLong: `\nCommand changes name of the snapshot. Snapshot name should be unique.\n\nExample:\n\n $ aptly snapshot rename wheezy-min wheezy-main\n`,\n\t}\n\n\treturn cmd\n\n}\n\nfunc aptlySnapshotRename(cmd *commander.Command, args []string) error ", "output": "{\n\tvar (\n\t\terr error\n\t\tsnapshot *deb.Snapshot\n\t)\n\n\tif len(args) != 2 {\n\t\tcmd.Usage()\n\t\treturn commander.ErrCommandError\n\t}\n\n\toldName, newName := args[0], args[1]\n\n\tsnapshot, err = context.CollectionFactory().SnapshotCollection().ByName(oldName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to rename: %s\", err)\n\t}\n\n\t_, err = context.CollectionFactory().SnapshotCollection().ByName(newName)\n\tif err == nil {\n\t\treturn fmt.Errorf(\"unable to rename: snapshot %s already exists\", newName)\n\t}\n\n\tsnapshot.Name = newName\n\terr = context.CollectionFactory().SnapshotCollection().Update(snapshot)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to rename: %s\", err)\n\t}\n\n\tfmt.Printf(\"\\nSnapshot %s -> %s has been successfully renamed.\\n\", oldName, newName)\n\n\treturn err\n}"} {"input": "package kafka\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestOption(t *testing.T) {\n\tvar options Options\n\tassert.Equal(t, `default`, options.group())\n\tassert.NotNil(t, options.logger(), `logger`)\n}\n\n\n\nfunc TestOptionWithURL(t *testing.T) ", "output": "{\n\tvar options Options\n\n\tWithTopics(`topic-test1`, `topic-test2`)(&options)\n\tassert.ElementsMatch(t, []string{`topic-test1`, `topic-test2`}, options.Topics)\n\n\tWithKafkaURL(`nats://demo1:8000,demo2:8000/test?topics=topic1,topic2`)(&options)\n\tassert.ElementsMatch(t, []string{`demo1:8000`, `demo2:8000`}, options.Brokers)\n\tassert.ElementsMatch(t, []string{`topic1`, `topic2`}, options.Topics)\n\tassert.Equal(t, `test`, options.group())\n}"} {"input": "package raft\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\tpb \"github.com/coreos/etcd/raft/raftpb\"\n)\n\ntype Status struct {\n\tID uint64\n\n\tpb.HardState\n\tSoftState\n\n\tApplied uint64\n\tProgress map[uint64]Progress\n}\n\n\nfunc getStatus(r *raft) Status {\n\ts := Status{ID: r.id}\n\ts.HardState = r.HardState\n\ts.SoftState = *r.softState()\n\n\ts.Applied = r.raftLog.applied\n\n\tif s.RaftState == StateLeader {\n\t\ts.Progress = make(map[uint64]Progress)\n\t\tfor id, p := range r.prs {\n\t\t\ts.Progress[id] = *p\n\t\t}\n\t}\n\n\treturn s\n}\n\n\n\n\nfunc (s Status) String() string {\n\tb, err := s.MarshalJSON()\n\tif err != nil {\n\t\tlog.Panicf(\"unexpected error: %v\", err)\n\t}\n\treturn string(b)\n}\n\nfunc (s Status) MarshalJSON() ([]byte, error) ", "output": "{\n\tj := fmt.Sprintf(`{\"id\":\"%x\",\"term\":%d,\"vote\":\"%x\",\"commit\":%d,\"lead\":\"%x\",\"raftState\":\"%s\",\"progress\":{`,\n\t\ts.ID, s.Term, s.Vote, s.Commit, s.Lead, s.RaftState)\n\n\tif len(s.Progress) == 0 {\n\t\tj += \"}}\"\n\t} else {\n\t\tfor k, v := range s.Progress {\n\t\t\tsubj := fmt.Sprintf(`\"%x\":{\"match\":%d,\"next\":%d,\"unreachable\":%t},`, k, v.Match, v.Next, v.Unreachable)\n\t\t\tj += subj\n\t\t}\n\t\tj = j[:len(j)-1] + \"}}\"\n\t}\n\treturn []byte(j), nil\n}"} {"input": "package piggybank\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/garyburd/redigo/redis\"\n)\n\n\n\nfunc RedisGetImages(c redis.Conn, a Animal) (Images, error) {\n\timagesKey := fmt.Sprintf(REDIS_IMAGES, a.ShelterId, a.UpdateId, a.Id)\n\tkExists, err := RedisKeyExists(c, imagesKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\timages := Images{}\n\tif kExists {\n\t\timageKeys, err := RedisGetIndexKeys(imagesKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, k := range imageKeys {\n\t\t\tkExists, err := RedisKeyExists(c, k)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif kExists {\n\t\t\t\tv, err := redis.Values(c.Do(\"HGETALL\", k))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tvar i Image\n\t\t\t\tif err := redis.ScanStruct(v, &i); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\timages = append(images, i)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn images, nil\n}\n\nfunc RedisDeleteImages(c redis.Conn, a *Animal) error {\n\timagesKey := fmt.Sprintf(REDIS_IMAGES, a.ShelterId, a.UpdateId, a.Id)\n\timageKeys, err := RedisGetIndexKeys(imagesKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, k := range imageKeys {\n\t\tif err := RedisDeleteKey(c, k); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn RedisDeleteKey(c, imagesKey)\n}\n\nfunc RedisPersistImages(c redis.Conn, a *Animal) error ", "output": "{\n\tif len(a.Images) > 0 {\n\t\tfor _, i := range a.Images {\n\t\t\tk := fmt.Sprintf(REDIS_IMAGE, a.ShelterId, a.UpdateId, a.Id, time.Now().UnixNano())\n\t\t\tif err := RedisPersistStruct(c, k, i); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := RedisAddIndexKey(c, fmt.Sprintf(REDIS_IMAGES, a.ShelterId, a.UpdateId, a.Id), k); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package appdir\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nfunc general(app string) string {\n\tif runtime.GOOS == \"android\" {\n\t\treturn fmt.Sprintf(\".%s\", strings.ToLower(app))\n\t} else {\n\t\treturn InHomeDir(fmt.Sprintf(\".%s\", strings.ToLower(app)))\n\t}\n}\n\n\n\nfunc logs(app string) string ", "output": "{\n\treturn filepath.Join(general(app), \"logs\")\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/engine\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdGetAttributes{\n\t\tname: \"attributes\",\n\t\trpcMethod: utils.APIerSv1GetAttributeProfile,\n\t\trpcParams: &utils.TenantID{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetAttributes struct {\n\tname string\n\trpcMethod string\n\trpcParams *utils.TenantID\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetAttributes) Name() string {\n\treturn self.name\n}\n\n\n\nfunc (self *CmdGetAttributes) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &utils.TenantID{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetAttributes) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetAttributes) RpcResult() interface{} {\n\tvar atr engine.AttributeProfile\n\treturn &atr\n}\n\nfunc (self *CmdGetAttributes) RpcMethod() string ", "output": "{\n\treturn self.rpcMethod\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\nvar configFileOptions map[string]interface{}\n\n\n\nfunc getConfigFileValue(key string) interface{} {\n\tif v, ok := configFileOptions[key]; ok {\n\t\treturn v\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc IsKeyInConfig(key string) bool {\n\t_, ok := configFileOptions[key]\n\treturn ok\n}\n\nfunc getConfigFileValueWithDefault(key string, defaultValue interface{}) interface{} {\n\tif v := getConfigFileValue(key); v != nil {\n\t\treturn v\n\t} else {\n\t\treturn defaultValue\n\t}\n}\n\n\n\nfunc GetConfigFileSlice(key string) []string {\n\tif v, ok := configFileOptions[key].([]interface{}); ok {\n\t\tretVal := []string{}\n\t\tfor _, e := range v {\n\t\t\tif strV, ok := e.(string); ok {\n\t\t\t\tretVal = append(retVal, strV)\n\t\t\t}\n\t\t}\n\t\treturn retVal\n\t} else {\n\t\treturn []string{}\n\t}\n}\n\nfunc GetConfigFileString(key string) string {\n\tv, _ := getConfigFileValue(key).(string)\n\treturn v\n}\n\nfunc GetConfigFileStringWithDefault(key string, defaultValue interface{}) string {\n\tv, _ := getConfigFileValueWithDefault(key, defaultValue).(string)\n\treturn v\n}\n\nfunc LoadConfigFile(file string) error ", "output": "{\n\tconfigFileOptions = nil\n\tif _, err := os.Stat(file); err != nil {\n\t\treturn nil\n\t}\n\tif s, err := ioutil.ReadFile(file); err != nil {\n\t\treturn err\n\t} else if err := yaml.Unmarshal(s, &configFileOptions); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"syscall\"\n)\n\ntype SSHCommand struct{}\n\n\n\nfunc init() {\n\tvar sshCommand SSHCommand\n\tcmd.AddCommand(\"ssh\", \"ssh shortcut\", \"run an ssh client connected to your vm\", &sshCommand)\n}\n\nfunc (c *SSHCommand) Execute(args []string) error ", "output": "{\n\tconfig, err := ReadConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpath, err := exec.LookPath(\"ssh\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\targs = append([]string{\"\", config.Hostname}, args...)\n\treturn syscall.Exec(path, args, os.Environ())\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\n\n\ntype TaskIDRange struct {\n\n\tEnd *int32 `json:\"end\"`\n\n\tStart *int32 `json:\"start\"`\n}\n\n\nfunc (m *TaskIDRange) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateEnd(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStart(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (m *TaskIDRange) validateEnd(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"end\", \"body\", m.End); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (m *TaskIDRange) validateStart(formats strfmt.Registry) error ", "output": "{\n\n\tif err := validate.Required(\"start\", \"body\", m.Start); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package da_griddata\n\nimport (\n\t\"github.com/watermint/toolbox/essentials/io/es_stdout\"\n\t\"github.com/watermint/toolbox/infra/control/app_control\"\n\t\"sync\"\n)\n\nfunc NewConsoleWriter(formatter GridDataFormatter, pw PlainGridDataWriter) GridDataWriter {\n\treturn &consoleWriter{\n\t\tformatter: formatter,\n\t\tpw: pw,\n\t}\n}\n\ntype consoleWriter struct {\n\tctl app_control.Control\n\tname string\n\tformatter GridDataFormatter\n\tpw PlainGridDataWriter\n\trow int\n\tmutex sync.Mutex\n}\n\nfunc (z *consoleWriter) Name() string {\n\treturn z.name\n}\n\nfunc (z *consoleWriter) Row(column []interface{}) {\n\tz.mutex.Lock()\n\tdefer z.mutex.Unlock()\n\tout := es_stdout.NewDefaultOut(z.ctl.Feature())\n\n\t_ = z.pw.WriteRow(z.ctl.Log(), out, z.formatter, z.row, column)\n\tz.row++\n}\n\n\n\nfunc (z *consoleWriter) Close() {\n}\n\nfunc (z *consoleWriter) Open(c app_control.Control) error ", "output": "{\n\tz.ctl = c\n\treturn nil\n}"} {"input": "package windows\n\nimport (\n\t\"github.com/docker/libnetwork/driverapi\"\n\t\"github.com/docker/libnetwork/types\"\n)\n\nconst networkType = \"windows\"\n\n\n\ntype driver struct{}\n\n\nfunc Init(dc driverapi.DriverCallback) error {\n\tc := driverapi.Capability{\n\t\tScope: driverapi.LocalScope,\n\t}\n\treturn dc.RegisterDriver(networkType, &driver{}, c)\n}\n\nfunc (d *driver) Config(option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) DeleteNetwork(nid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) DeleteEndpoint(nid, eid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {\n\treturn make(map[string]interface{}, 0), nil\n}\n\n\n\n\n\nfunc (d *driver) Leave(nid, eid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) Type() string {\n\treturn networkType\n}\n\nfunc (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error ", "output": "{\n\treturn nil\n}"} {"input": "package fdbased\n\nimport (\n\t\"reflect\"\n\t\"unsafe\"\n)\n\nconst virtioNetHdrSize = int(unsafe.Sizeof(virtioNetHdr{}))\n\n\n\nfunc vnetHdrToByteSlice(hdr *virtioNetHdr) (slice []byte) ", "output": "{\n\tsh := (*reflect.SliceHeader)(unsafe.Pointer(&slice))\n\tsh.Data = uintptr(unsafe.Pointer(hdr))\n\tsh.Len = virtioNetHdrSize\n\tsh.Cap = virtioNetHdrSize\n\treturn\n}"} {"input": "package alignmentprofile\n\nimport \"testing\"\n\n\n\nfunc TestInvalidProfile(t *testing.T) {\n\tsrc := `StopCodonPenalty: 0\nGapOpeningPenalty: 0\nGapExtensionPenalty: 0\nIndelCodonOpeningBonus: 0\nIndelCodonExtensionBonus: 0`\n\t_, err := Parse(src)\n\tif err == nil {\n\t\tt.Errorf(\"Expected error when missing ReferenceSequences\")\n\t}\n}\n\nfunc TestUnmarshalEmpty(t *testing.T) ", "output": "{\n\tsrc := \"\"\n\t_, err := Parse(src)\n\tif err == nil {\n\t\tt.Errorf(\"Expected error on empty YAML file\")\n\t}\n}"} {"input": "package response\n\nimport \"warcluster/entities\"\n\ntype OwnerChange struct {\n\tbaseResponse\n\tRawPlanet map[string]*entities.Planet `json:\"-\"`\n\tPlanet map[string]*entities.PlanetPacket `json:\",omitempty\"`\n}\n\n\n\nfunc (o *OwnerChange) Sanitize(player *entities.Player) {\n\to.Planet = SanitizePlanets(player, o.RawPlanet)\n}\n\nfunc NewOwnerChange() *OwnerChange ", "output": "{\n\tr := new(OwnerChange)\n\tr.Command = \"owner_change\"\n\treturn r\n}"} {"input": "package example\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/RangelReale/osin\"\n)\n\nfunc HandleLoginPage(ar *osin.AuthorizeRequest, w http.ResponseWriter, r *http.Request) bool {\n\tr.ParseForm()\n\tif r.Method == \"POST\" && r.Form.Get(\"login\") == \"test\" && r.Form.Get(\"password\") == \"test\" {\n\t\treturn true\n\t}\n\n\tw.Write([]byte(\"\"))\n\n\tw.Write([]byte(fmt.Sprintf(\"LOGIN %s (use test/test)
\", ar.Client.GetId())))\n\tw.Write([]byte(fmt.Sprintf(\"
\", r.URL.RawQuery)))\n\n\tw.Write([]byte(\"Login:
\"))\n\tw.Write([]byte(\"Password:
\"))\n\tw.Write([]byte(\"\"))\n\n\tw.Write([]byte(\"
\"))\n\n\tw.Write([]byte(\"\"))\n\n\treturn false\n}\n\n\n\nfunc DownloadAccessToken(url string, auth *osin.BasicAuth, output map[string]interface{}) error ", "output": "{\n\tpreq, err := http.NewRequest(\"POST\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif auth != nil {\n\t\tpreq.SetBasicAuth(auth.Username, auth.Password)\n\t}\n\n\tpclient := &http.Client{}\n\tpresp, err := pclient.Do(preq)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif presp.StatusCode != 200 {\n\t\treturn errors.New(\"Invalid status code\")\n\t}\n\n\tjdec := json.NewDecoder(presp.Body)\n\terr = jdec.Decode(&output)\n\treturn err\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst version = 74\n\nvar cmdVersion = &Command{\n\tName: \"version\",\n\tShort: \"show version info\",\n\tLong: `\n\nDisplays the version of godep as well as the target OS, architecture and go runtime version.\n`,\n\tRun: runVersion,\n}\n\nfunc versionString() string {\n\treturn fmt.Sprintf(\"godep v%d (%s/%s/%s)\", version, runtime.GOOS, runtime.GOARCH, runtime.Version())\n}\n\nfunc runVersion(cmd *Command, args []string) {\n\tfmt.Printf(\"%s\\n\", versionString())\n}\n\nfunc GoVersionFields(c rune) bool {\n\treturn c == 'g' || c == 'o' || c == '.'\n}\n\n\n\n\n\n\nfunc isSameOrNewer(base, check string) bool ", "output": "{\n\tif base == check {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(check, \"devel-\") {\n\t\treturn true\n\t}\n\tbp := strings.FieldsFunc(base, GoVersionFields)\n\tcp := strings.FieldsFunc(check, GoVersionFields)\n\tif len(bp) < 2 || len(cp) < 2 {\n\t\tlog.Fatalf(\"Error comparing %s to %s\\n\", base, check)\n\t}\n\tif bp[0] == cp[0] { \n\t\tbm, err := strconv.Atoi(bp[1])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tcm, err := strconv.Atoi(cp[1])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn cm >= bm\n\t}\n\treturn false\n}"} {"input": "package messages\n\nimport \"time\"\n\nconst nanosPerSecond = 1000000000\n\nfunc DurationToGoDuration(duration Duration) time.Duration {\n\tsecondNanos := duration.Seconds * nanosPerSecond\n\treturn time.Duration(secondNanos + int64(duration.Nanos))\n}\n\n\n\nfunc TimestampToGoTime(timestamp Timestamp) time.Time {\n\treturn time.Unix(timestamp.Seconds, timestamp.Nanos)\n}\n\nfunc GoTimeToTimestamp(t time.Time) Timestamp {\n\tunixNanos := t.UnixNano()\n\tseconds := unixNanos / nanosPerSecond\n\tnanos := unixNanos % nanosPerSecond\n\n\treturn Timestamp{\n\t\tSeconds: seconds,\n\t\tNanos: nanos,\n\t}\n}\n\nfunc GoDurationToDuration(goDuration time.Duration) Duration ", "output": "{\n\tseconds := int64(goDuration / nanosPerSecond)\n\tnanos := int64(goDuration % nanosPerSecond)\n\treturn Duration{\n\t\tSeconds: seconds,\n\t\tNanos: nanos,\n\t}\n}"} {"input": "package stats\n\nvar (\n\tNoOpStatsFactory StatsFactory\n)\n\ntype noopCounter struct {\n}\n\nfunc (s noopCounter) Inc() {\n}\n\nfunc (s noopCounter) Add(v float64) {\n}\n\ntype noopGauge struct {\n}\n\nfunc (s noopGauge) Inc() {\n}\n\nfunc (s noopGauge) Add(v float64) {\n}\n\nfunc (s noopGauge) Dec() {\n}\n\nfunc (s noopGauge) Sub(v float64) {\n}\n\nfunc (s noopGauge) Set(v float64) {\n}\n\n\n\ntype noopSummary struct {\n}\n\nfunc (s noopSummary) Observe(v float64) {\n}\n\ntype noopStatsFactory struct {\n}\n\nfunc (f noopStatsFactory) NewCounter(\n\tmetric string,\n\ttags map[string]string) CounterStat {\n\n\treturn noopCounter{}\n}\n\nfunc (f noopStatsFactory) NewGauge(\n\tmetric string,\n\ttags map[string]string) GaugeStat {\n\n\treturn noopGauge{}\n}\n\nfunc (f noopStatsFactory) NewSummary(\n\tmetric string,\n\ttags map[string]string) SummaryStat {\n\n\treturn noopSummary{}\n}\n\nfunc init() {\n\tNoOpStatsFactory = noopStatsFactory{}\n}\n\nfunc (s noopGauge) Get() float64 ", "output": "{\n\treturn 0\n}"} {"input": "package app\n\nimport (\n\t\"github.com/mattermost/platform/model\"\n\t\"github.com/mattermost/platform/utils\"\n)\n\ntype AutoChannelCreator struct {\n\tclient *model.Client\n\tteam *model.Team\n\tFuzzy bool\n\tDisplayNameLen utils.Range\n\tDisplayNameCharset string\n\tNameLen utils.Range\n\tNameCharset string\n\tChannelType string\n}\n\nfunc NewAutoChannelCreator(client *model.Client, team *model.Team) *AutoChannelCreator {\n\treturn &AutoChannelCreator{\n\t\tclient: client,\n\t\tteam: team,\n\t\tFuzzy: false,\n\t\tDisplayNameLen: CHANNEL_DISPLAY_NAME_LEN,\n\t\tDisplayNameCharset: utils.ALPHANUMERIC,\n\t\tNameLen: CHANNEL_NAME_LEN,\n\t\tNameCharset: utils.LOWERCASE,\n\t\tChannelType: CHANNEL_TYPE,\n\t}\n}\n\nfunc (cfg *AutoChannelCreator) createRandomChannel() (*model.Channel, bool) {\n\tvar displayName string\n\tif cfg.Fuzzy {\n\t\tdisplayName = utils.FuzzName()\n\t} else {\n\t\tdisplayName = utils.RandomName(cfg.NameLen, cfg.NameCharset)\n\t}\n\tname := utils.RandomName(cfg.NameLen, cfg.NameCharset)\n\n\tchannel := &model.Channel{\n\t\tTeamId: cfg.team.Id,\n\t\tDisplayName: displayName,\n\t\tName: name,\n\t\tType: cfg.ChannelType}\n\n\tprintln(cfg.client.GetTeamRoute())\n\tresult, err := cfg.client.CreateChannel(channel)\n\tif err != nil {\n\t\terr.Translate(utils.T)\n\t\tprintln(err.Error())\n\t\tprintln(err.DetailedError)\n\t\treturn nil, false\n\t}\n\treturn result.Data.(*model.Channel), true\n}\n\n\n\nfunc (cfg *AutoChannelCreator) CreateTestChannels(num utils.Range) ([]*model.Channel, bool) ", "output": "{\n\tnumChannels := utils.RandIntFromRange(num)\n\tchannels := make([]*model.Channel, numChannels)\n\n\tfor i := 0; i < numChannels; i++ {\n\t\tvar err bool\n\t\tchannels[i], err = cfg.createRandomChannel()\n\t\tif err != true {\n\t\t\treturn channels, false\n\t\t}\n\t}\n\n\treturn channels, true\n}"} {"input": "package buckettree\n\nimport (\n\t\"github.com/golang/protobuf/proto\"\n\t\"github.com/hyperledger/fabric/core/ledger/util\"\n\topenchainUtil \"github.com/hyperledger/fabric/core/util\"\n)\n\ntype bucketHashCalculator struct {\n\tbucketKey *bucketKey\n\tcurrentChaincodeID string\n\tdataNodes []*dataNode\n\thashingData []byte\n}\n\nfunc newBucketHashCalculator(bucketKey *bucketKey) *bucketHashCalculator {\n\treturn &bucketHashCalculator{bucketKey, \"\", nil, nil}\n}\n\n\nfunc (c *bucketHashCalculator) addNextNode(dataNode *dataNode) {\n\tchaincodeID, _ := dataNode.getKeyElements()\n\tif chaincodeID != c.currentChaincodeID {\n\t\tc.appendCurrentChaincodeData()\n\t\tc.currentChaincodeID = chaincodeID\n\t\tc.dataNodes = nil\n\t}\n\tc.dataNodes = append(c.dataNodes, dataNode)\n}\n\n\n\nfunc (c *bucketHashCalculator) appendCurrentChaincodeData() {\n\tif c.currentChaincodeID == \"\" {\n\t\treturn\n\t}\n\tc.appendSizeAndData([]byte(c.currentChaincodeID))\n\tc.appendSize(len(c.dataNodes))\n\tfor _, dataNode := range c.dataNodes {\n\t\t_, key := dataNode.getKeyElements()\n\t\tvalue := dataNode.getValue()\n\t\tc.appendSizeAndData([]byte(key))\n\t\tc.appendSizeAndData(value)\n\t}\n}\n\nfunc (c *bucketHashCalculator) appendSizeAndData(b []byte) {\n\tc.appendSize(len(b))\n\tc.hashingData = append(c.hashingData, b...)\n}\n\nfunc (c *bucketHashCalculator) appendSize(size int) {\n\tc.hashingData = append(c.hashingData, proto.EncodeVarint(uint64(size))...)\n}\n\nfunc (c *bucketHashCalculator) computeCryptoHash() []byte ", "output": "{\n\tif c.currentChaincodeID != \"\" {\n\t\tc.appendCurrentChaincodeData()\n\t\tc.currentChaincodeID = \"\"\n\t\tc.dataNodes = nil\n\t}\n\tlogger.Debug(\"Hashable content for bucket [%s]: length=%d, contentInStringForm=[%s]\", c.bucketKey, len(c.hashingData), string(c.hashingData))\n\tif util.IsNil(c.hashingData) {\n\t\treturn nil\n\t}\n\treturn openchainUtil.ComputeCryptoHash(c.hashingData)\n}"} {"input": "package suite_init\n\ntype SuiteData struct {\n\t*StubsData\n\t*SynchronizedSuiteCallbacksData\n\t*WerfBinaryData\n\t*ProjectNameData\n\t*K8sDockerRegistryData\n\t*TmpDirData\n\t*ContainerRegistryPerImplementationData\n}\n\nfunc (data *SuiteData) SetupStubs(setupData *StubsData) bool {\n\tdata.StubsData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupSynchronizedSuiteCallbacks(setupData *SynchronizedSuiteCallbacksData) bool {\n\tdata.SynchronizedSuiteCallbacksData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupWerfBinary(setupData *WerfBinaryData) bool {\n\tdata.WerfBinaryData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupProjectName(setupData *ProjectNameData) bool {\n\tdata.ProjectNameData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupK8sDockerRegistry(setupData *K8sDockerRegistryData) bool {\n\tdata.K8sDockerRegistryData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupTmp(setupData *TmpDirData) bool {\n\tdata.TmpDirData = setupData\n\treturn true\n}\n\n\n\nfunc (data *SuiteData) SetupContainerRegistryPerImplementation(setupData *ContainerRegistryPerImplementationData) bool ", "output": "{\n\tdata.ContainerRegistryPerImplementationData = setupData\n\treturn true\n}"} {"input": "package prometheus\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"text/template\"\n\n\t\"github.com/pkg/errors\"\n\n\ttm \"github.com/supergiant/control/pkg/templatemanager\"\n\t\"github.com/supergiant/control/pkg/workflows/steps\"\n)\n\nconst StepName = \"prometheus\"\n\ntype Config struct {\n\tRBACEnabled bool\n}\n\ntype Step struct {\n\tscript *template.Template\n}\n\nfunc (s *Step) Rollback(context.Context, io.Writer, *steps.Config) error {\n\treturn nil\n}\n\nfunc Init() {\n\ttpl, err := tm.GetTemplate(StepName)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"template %s not found\", StepName))\n\t}\n\n\tsteps.RegisterStep(StepName, New(tpl))\n}\n\nfunc New(script *template.Template) *Step {\n\tt := &Step{\n\t\tscript: script,\n\t}\n\n\treturn t\n}\n\n\n\nfunc (s *Step) Name() string {\n\treturn StepName\n}\n\nfunc (s *Step) Description() string {\n\treturn \"Install prometheus\"\n}\n\nfunc (s *Step) Depends() []string {\n\treturn nil\n}\n\nfunc toStepCfg(c *steps.Config) Config {\n\treturn Config{\n\t\tRBACEnabled: c.Kube.RBACEnabled,\n\t}\n}\n\nfunc (s *Step) Run(ctx context.Context, out io.Writer, config *steps.Config) error ", "output": "{\n\terr := steps.RunTemplate(ctx, s.script, config.Runner, out, toStepCfg(config))\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"install prometheus step\")\n\t}\n\n\treturn nil\n}"} {"input": "package aws\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/service/cloudwatch\"\n)\n\nfunc TestDiffCloudWatchTags(t *testing.T) {\n\tcases := []struct {\n\t\tOld, New map[string]interface{}\n\t\tCreate, Remove map[string]string\n\t}{\n\t\t{\n\t\t\tOld: map[string]interface{}{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t\tNew: map[string]interface{}{\n\t\t\t\t\"bar\": \"baz\",\n\t\t\t},\n\t\t\tCreate: map[string]string{\n\t\t\t\t\"bar\": \"baz\",\n\t\t\t},\n\t\t\tRemove: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tOld: map[string]interface{}{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t\tNew: map[string]interface{}{\n\t\t\t\t\"foo\": \"baz\",\n\t\t\t},\n\t\t\tCreate: map[string]string{\n\t\t\t\t\"foo\": \"baz\",\n\t\t\t},\n\t\t\tRemove: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor i, tc := range cases {\n\t\tc, r := diffTagsCloudWatch(tagsFromMapCloudWatch(tc.Old), tagsFromMapCloudWatch(tc.New))\n\t\tcm := tagsToMapCloudWatch(c)\n\t\trm := tagsToMapCloudWatch(r)\n\t\tif !reflect.DeepEqual(cm, tc.Create) {\n\t\t\tt.Fatalf(\"%d: bad create: %#v\", i, cm)\n\t\t}\n\t\tif !reflect.DeepEqual(rm, tc.Remove) {\n\t\t\tt.Fatalf(\"%d: bad remove: %#v\", i, rm)\n\t\t}\n\t}\n}\n\n\n\nfunc TestIgnoringTagsCloudWatch(t *testing.T) ", "output": "{\n\tvar ignoredTags []*cloudwatch.Tag\n\tignoredTags = append(ignoredTags, &cloudwatch.Tag{\n\t\tKey: aws.String(\"aws:cloudformation:logical-id\"),\n\t\tValue: aws.String(\"foo\"),\n\t})\n\tignoredTags = append(ignoredTags, &cloudwatch.Tag{\n\t\tKey: aws.String(\"aws:foo:bar\"),\n\t\tValue: aws.String(\"baz\"),\n\t})\n\tfor _, tag := range ignoredTags {\n\t\tif !tagIgnoredCloudWatch(tag) {\n\t\t\tt.Fatalf(\"Tag %v with value %v not ignored, but should be!\", *tag.Key, *tag.Value)\n\t\t}\n\t}\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\n\tv1beta1 \"kubevirt.io/client-go/generated/containerized-data-importer/clientset/versioned/typed/core/v1beta1\"\n)\n\ntype FakeCdiV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeCdiV1beta1) CDIs() v1beta1.CDIInterface {\n\treturn &FakeCDIs{c}\n}\n\nfunc (c *FakeCdiV1beta1) CDIConfigs() v1beta1.CDIConfigInterface {\n\treturn &FakeCDIConfigs{c}\n}\n\nfunc (c *FakeCdiV1beta1) DataImportCrons(namespace string) v1beta1.DataImportCronInterface {\n\treturn &FakeDataImportCrons{c, namespace}\n}\n\nfunc (c *FakeCdiV1beta1) DataSources(namespace string) v1beta1.DataSourceInterface {\n\treturn &FakeDataSources{c, namespace}\n}\n\n\n\nfunc (c *FakeCdiV1beta1) ObjectTransfers() v1beta1.ObjectTransferInterface {\n\treturn &FakeObjectTransfers{c}\n}\n\nfunc (c *FakeCdiV1beta1) StorageProfiles() v1beta1.StorageProfileInterface {\n\treturn &FakeStorageProfiles{c}\n}\n\n\n\nfunc (c *FakeCdiV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeCdiV1beta1) DataVolumes(namespace string) v1beta1.DataVolumeInterface ", "output": "{\n\treturn &FakeDataVolumes{c, namespace}\n}"} {"input": "package relation\n\nimport (\n\t\"github.com/juju/names/v4\"\n\n\t\"github.com/juju/juju/api/uniter\"\n)\n\ntype stateTrackerStateShim struct {\n\t*uniter.State\n}\n\n\n\n\nfunc (s *stateTrackerStateShim) RelationById(id int) (Relation, error) {\n\trel, err := s.State.RelationById(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &relationShim{rel}, nil\n}\n\n\nfunc (s *stateTrackerStateShim) Unit(tag names.UnitTag) (Unit, error) {\n\tunit, err := s.State.Unit(tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &unitShim{unit}, nil\n}\n\ntype relationShim struct {\n\t*uniter.Relation\n}\n\nfunc (s *relationShim) Unit(uTag names.UnitTag) (RelationUnit, error) {\n\tu, err := s.Relation.Unit(uTag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RelationUnitShim{u}, nil\n}\n\ntype unitShim struct {\n\t*uniter.Unit\n}\n\nfunc (s *unitShim) Application() (Application, error) {\n\tapp, err := s.Unit.Application()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &applicationShim{app}, nil\n}\n\ntype applicationShim struct {\n\t*uniter.Application\n}\n\ntype RelationUnitShim struct {\n\t*uniter.RelationUnit\n}\n\nfunc (r *RelationUnitShim) Relation() Relation {\n\treturn &relationShim{r.RelationUnit.Relation()}\n}\n\nfunc (s *stateTrackerStateShim) Relation(tag names.RelationTag) (Relation, error) ", "output": "{\n\trel, err := s.State.Relation(tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &relationShim{rel}, nil\n}"} {"input": "package redis\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/deepfabric/elasticell/pkg/pb/raftcmdpb\"\n\t\"github.com/fagongzi/goetty\"\n\tgredis \"github.com/fagongzi/goetty/protocol/redis\"\n\t\"github.com/fagongzi/util/format\"\n\t\"github.com/fagongzi/util/hack\"\n)\n\nconst (\n\tpong = \"PONG\"\n)\n\nvar (\n\tErrNotSupportCommand = []byte(\"command is not support\")\n\tErrInvalidCommandResp = []byte(\"invalid command\")\n\tPongResp = []byte(\"PONG\")\n\tOKStatusResp = []byte(\"OK\")\n)\n\n\nfunc WriteFVPairArray(lst []*raftcmdpb.FVPair, buf *goetty.ByteBuf) {\n\tbuf.WriteByte('*')\n\tif len(lst) == 0 {\n\t\tbuf.Write(gredis.NullArray)\n\t\tbuf.Write(gredis.Delims)\n\t} else {\n\t\tbuf.Write(hack.StringToSlice(strconv.Itoa(len(lst) * 2)))\n\t\tbuf.Write(gredis.Delims)\n\n\t\tfor i := 0; i < len(lst); i++ {\n\t\t\tgredis.WriteBulk(lst[i].Field, buf)\n\t\t\tgredis.WriteBulk(lst[i].Value, buf)\n\t\t}\n\t}\n}\n\n\n\n\nfunc WriteScorePairArray(lst []*raftcmdpb.ScorePair, withScores bool, buf *goetty.ByteBuf) ", "output": "{\n\tbuf.WriteByte('*')\n\tif len(lst) == 0 {\n\t\tbuf.Write(gredis.NullArray)\n\t\tbuf.Write(gredis.Delims)\n\t} else {\n\t\tif withScores {\n\t\t\tbuf.Write(hack.StringToSlice(strconv.Itoa(len(lst) * 2)))\n\t\t\tbuf.Write(gredis.Delims)\n\t\t} else {\n\t\t\tbuf.Write(hack.StringToSlice(strconv.Itoa(len(lst))))\n\t\t\tbuf.Write(gredis.Delims)\n\t\t}\n\n\t\tfor i := 0; i < len(lst); i++ {\n\t\t\tgredis.WriteBulk(lst[i].Member, buf)\n\n\t\t\tif withScores {\n\t\t\t\tgredis.WriteBulk(format.Float64ToString(lst[i].Score), buf)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package text_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/google/gapid/core/assert\"\n\t\"github.com/google/gapid/core/log\"\n\t\"github.com/google/gapid/core/text\"\n)\n\nfunc ExampleSplitArgs() {\n\tfor i, s := range text.SplitArgs(`--cat=meow -dog woof \"fish\"=\"\\\"blub blub\\\"\"`) {\n\t\tfmt.Printf(\"%v: '%v'\\n\", i, s)\n\t}\n}\n\nfunc TestSplitArgs(t *testing.T) {\n\tctx := log.Testing(t)\n\tfor _, test := range []struct {\n\t\tstr string\n\t\texpected []string\n\t}{\n\t\t{`a b c`, []string{`a`, `b`, `c`}},\n\t\t{`\"a b c\"`, []string{`a b c`}},\n\t\t{`\\\"a b c\\\"`, []string{`\"a`, `b`, `c\"`}},\n\t\t{`\\\\a b c\\\\\"`, []string{`\\a`, `b`, `c\\`}},\n\t\t{`\\\\ abc \\\\\"`, []string{`\\`, `abc`, `\\`}},\n\t\t{`\\x abc \\x\"`, []string{`x`, `abc`, `x`}},\n\t\t{`\"meow \\\" woof\"`, []string{`meow \" woof`}},\n\t} {\n\t\tgot := text.SplitArgs(test.str)\n\t\tassert.For(ctx, \"text.SplitArgs(%v)\", test.str).ThatSlice(got).Equals(test.expected)\n\t}\n}\n\n\n\nfunc TestQuote(t *testing.T) ", "output": "{\n\tctx := log.Testing(t)\n\tfor _, test := range []struct {\n\t\tstr []string\n\t\texpected []string\n\t}{\n\t\t{[]string{`a`, `b`, `c`}, []string{`a`, `b`, `c`}},\n\t\t{[]string{`a`, `a b c`}, []string{`a`, `\"a b c\"`}},\n\t\t{[]string{`\\\"a`, `b`, `c\\\"`}, []string{`\\\\\\\\\"a`, `b`, `c\\\\\\\\\"`}},\n\t\t{[]string{`meow \\\" woof`}, []string{`\"meow \\\\\\\\\" woof\"`}},\n\t} {\n\t\tgot := text.Quote(test.str)\n\t\tassert.For(ctx, \"test.Quote(%v)\", test.str).ThatSlice(got).Equals(test.expected)\n\t}\n}"} {"input": "package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/service/apigateway\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema\"\n)\n\n\n\nfunc dataSourceAwsApiGatewayResourceRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).apigatewayconn\n\n\trestApiId := d.Get(\"rest_api_id\").(string)\n\ttarget := d.Get(\"path\").(string)\n\tparams := &apigateway.GetResourcesInput{RestApiId: aws.String(restApiId)}\n\n\tvar match *apigateway.Resource\n\tlog.Printf(\"[DEBUG] Reading API Gateway Resources: %s\", params)\n\terr := conn.GetResourcesPages(params, func(page *apigateway.GetResourcesOutput, lastPage bool) bool {\n\t\tfor _, resource := range page.Items {\n\t\t\tif aws.StringValue(resource.Path) == target {\n\t\t\t\tmatch = resource\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn !lastPage\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error describing API Gateway Resources: %s\", err)\n\t}\n\n\tif match == nil {\n\t\treturn fmt.Errorf(\"no Resources with path %q found for rest api %q\", target, restApiId)\n\t}\n\n\td.SetId(aws.StringValue(match.Id))\n\td.Set(\"path_part\", match.PathPart)\n\td.Set(\"parent_id\", match.ParentId)\n\n\treturn nil\n}\n\nfunc dataSourceAwsApiGatewayResource() *schema.Resource ", "output": "{\n\treturn &schema.Resource{\n\t\tRead: dataSourceAwsApiGatewayResourceRead,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"rest_api_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t\t\"path\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t\t\"path_part\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"parent_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package inject\n\nimport \"fmt\"\n\n\n\n\n\nfunc Rune(old, insert []rune, pos int) ([]rune, error) {\n\tswitch {\n\tcase len(old) == 0:\n\t\tif pos == 0 {\n\t\t\treturn insert, nil\n\t\t}\n\n\t\treturn []rune{}, fmt.Errorf(\"pos cannot be non-zero when old is empty\")\n\n\tcase pos < 0:\n\t\treturn []rune{}, fmt.Errorf(\"pos cannot be less than zero\")\n\n\tcase len(old) < pos:\n\t\treturn []rune{}, fmt.Errorf(\"Len of old is less than pos\")\n\n\tcase pos == 0:\n\t\treturn append(insert, old...), nil\n\n\tcase pos == len(old):\n\t\treturn append(old, insert...), nil\n\n\tdefault:\n\t\tnew := make([]rune, len(old)+len(insert))\n\t\tfor i := 0; i < pos; i++ {\n\t\t\tnew[i] = old[i]\n\t\t}\n\t\tfor i := 0; i < len(insert); i++ {\n\t\t\tnew[pos+i] = insert[i]\n\t\t}\n\t\tl := len(insert)\n\t\tfor i := pos; i < len(old); i++ {\n\t\t\tnew[l+i] = old[i]\n\t\t}\n\n\t\treturn new, nil\n\t}\n}\n\nfunc String(old, insert string, pos int) (string, error) ", "output": "{\n\tswitch {\n\tcase len(old) == 0:\n\t\tif pos == 0 {\n\t\t\treturn insert, nil\n\t\t}\n\n\t\treturn \"\", fmt.Errorf(\"pos cannot be non-zero when old is empty\")\n\n\tcase pos < 0:\n\t\treturn \"\", fmt.Errorf(\"pos cannot be less than zero\")\n\n\tcase len(old) < pos:\n\t\treturn \"\", fmt.Errorf(\"Len of old is less than pos\")\n\n\tcase pos == 0:\n\t\treturn insert + old, nil\n\n\tcase pos == len(old):\n\t\treturn old + insert, nil\n\n\tdefault:\n\t\treturn old[:pos] + insert + old[pos:], nil\n\t}\n}"} {"input": "package main\n\nimport \"strings\"\n\nvar x = make([]byte, 10)\n\nfunc main() {\n\ttest1()\n\ttest2()\n\ttest3()\n\ttest4()\n\ttest5()\n\ttest6()\n\ttest7()\n}\n\nfunc mustRecover(s string) {\n\tv := recover()\n\tif v == nil {\n\t\tpanic(\"expected panic\")\n\t}\n\tif e := v.(error).Error(); strings.Index(e, s) < 0 {\n\t\tpanic(\"want: \" + s + \"; have: \" + e)\n\t}\n}\n\nfunc test1() {\n\tdefer mustRecover(\"index\")\n\tprintln(x[123])\n}\n\nfunc test2() {\n\tdefer mustRecover(\"slice\")\n\tprintln(x[5:15])\n}\n\n\n\nfunc test4() {\n\tdefer mustRecover(\"interface\")\n\tvar x interface{} = 1\n\tprintln(x.(float32))\n}\n\ntype T struct {\n\ta, b int\n\tc []int\n}\n\nfunc test5() {\n\tdefer mustRecover(\"uncomparable\")\n\tvar x T\n\tvar z interface{} = x\n\tprintln(z != z)\n}\n\nfunc test6() {\n\tdefer mustRecover(\"unhashable\")\n\tvar x T\n\tvar z interface{} = x\n\tm := make(map[interface{}]int)\n\tm[z] = 1\n}\n\nfunc test7() {\n\tdefer mustRecover(\"divide by zero\")\n\tvar x, y int\n\tprintln(x / y)\n}\n\nfunc test3() ", "output": "{\n\tdefer mustRecover(\"slice\")\n\tvar lo = 11\n\tvar hi = 9\n\tprintln(x[lo:hi])\n}"} {"input": "package coreosutil\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\n\n\nfunc GetAMIData(channel string) (map[string]map[string]string, error) ", "output": "{\n\tr, err := http.Get(fmt.Sprintf(\"https://coreos.com/dist/aws/aws-%s.json\", channel))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get AMI data: %s: %v\", channel, err)\n\t}\n\n\tif r.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"failed to get AMI data: %s: invalid status code: %d\", channel, r.StatusCode)\n\t}\n\n\toutput := map[string]map[string]string{}\n\n\terr = json.NewDecoder(r.Body).Decode(&output)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse AMI data: %s: %v\", channel, err)\n\t}\n\tr.Body.Close()\n\n\treturn output, nil\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\n\n\nfunc Homedir() (string, error) ", "output": "{\n\thome := os.Getenv(\"HOME\")\n\tif home == \"\" {\n\t\treturn \"\", fmt.Errorf(\"error: Environment variable HOME not set\")\n\t}\n\n\treturn home, nil\n}"} {"input": "package rpc\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\n\t\"github.com/ugorji/go/codec\"\n)\n\ntype packetizer interface {\n\tNextFrame() (rpcMessage, error)\n}\n\ntype packetHandler struct {\n\tdec decoder\n\treader io.Reader\n\tframeDecoder *decoderWrapper\n\tprotocols *protocolHandler\n\tcalls *callContainer\n}\n\nfunc newPacketHandler(reader io.Reader, protocols *protocolHandler, calls *callContainer) *packetHandler {\n\treturn &packetHandler{\n\t\treader: reader,\n\t\tdec: codec.NewDecoder(reader, newCodecMsgpackHandle()),\n\t\tframeDecoder: newDecoderWrapper(),\n\t\tprotocols: protocols,\n\t\tcalls: calls,\n\t}\n}\n\n\n\nfunc (p *packetHandler) loadNextFrame() ([]byte, error) {\n\tvar l int\n\tif err := p.dec.Decode(&l); err != nil {\n\t\tif _, ok := err.(*net.OpError); ok {\n\t\t\treturn nil, io.EOF\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tbytes := make([]byte, l)\n\tlenRead, err := io.ReadFull(p.reader, bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif lenRead != l {\n\t\treturn nil, fmt.Errorf(\"Unable to read desired length. Desired: %d, actual: %d\", l, lenRead)\n\t}\n\treturn bytes, nil\n}\n\nfunc (p *packetHandler) NextFrame() (rpcMessage, error) ", "output": "{\n\tbytes, err := p.loadNextFrame()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(bytes) < 1 {\n\t\treturn nil, NewPacketizerError(\"invalid frame size: %d\", len(bytes))\n\t}\n\n\tnb := int(bytes[0])\n\n\tif nb < 0x91 || nb > 0x9f {\n\t\treturn nil, NewPacketizerError(\"wrong message structure prefix (%d)\", nb)\n\t}\n\tp.frameDecoder.ResetBytes(bytes[1:])\n\n\treturn decodeRPC(nb-0x90, p.frameDecoder, p.protocols, p.calls)\n}"} {"input": "package nclient4\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"time\"\n\n\t\"github.com/insomniacslk/dhcp/dhcpv4\"\n)\n\n\n\ntype Lease struct {\n\tOffer *dhcpv4.DHCPv4\n\tACK *dhcpv4.DHCPv4\n\tCreationTime time.Time\n}\n\n\n\n\n\n\n\nfunc (c *Client) Release(lease *Lease, modifiers ...dhcpv4.Modifier) error ", "output": "{\n\tif lease == nil {\n\t\treturn fmt.Errorf(\"lease is nil\")\n\t}\n\treq, err := dhcpv4.NewReleaseFromACK(lease.ACK, modifiers...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"fail to create release request,%w\", err)\n\t}\n\t_, err = c.conn.WriteTo(req.ToBytes(), &net.UDPAddr{IP: lease.ACK.Options.Get(dhcpv4.OptionServerIdentifier), Port: ServerPort})\n\tif err == nil {\n\t\tc.logger.PrintMessage(\"sent message:\", req)\n\t}\n\treturn err\n}"} {"input": "package simpleSocks5\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n)\n\n\nfunc handleConnect(conn net.Conn, dest *AddrSpec) error {\n\taddr := net.TCPAddr{IP: dest.IP, Port: dest.Port}\n\ttarget, err := net.DialTCP(\"tcp\", nil, &addr)\n\tif err != nil {\n\t\tmsg := err.Error()\n\t\tresp := hostUnreachable\n\t\tif strings.Contains(msg, \"refused\") {\n\t\t\tresp = connectionRefused\n\t\t} else if strings.Contains(msg, \"network is unreachable\") {\n\t\t\tresp = networkUnreachable\n\t\t}\n\t\tif err := sendReply(conn, resp, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to send reply: %v\", err)\n\t\t}\n\t\treturn fmt.Errorf(\"Connect to %v failed: %v\", dest, err)\n\t}\n\ttarget.SetKeepAlive(false)\n\tdefer target.Close()\n\n\tlocal := target.LocalAddr().(*net.TCPAddr)\n\tbind := AddrSpec{IP: local.IP, Port: local.Port}\n\tif err := sendReply(conn, successReply, &bind); err != nil {\n\t\treturn fmt.Errorf(\"Failed to send reply: %v\", err)\n\t}\n\n\tfinish := make(chan bool,2)\n\n\tgo proxy( target, conn, finish)\n\tgo proxy( conn, target, finish)\n\n\tselect{\n\tcase <- finish:\n\t}\n\ttime.Sleep(2*time.Second)\n\n\treturn nil\n}\n\n\n\nfunc proxy(dst io.Writer, src io.Reader, finish chan bool) ", "output": "{\n\tio.Copy(dst,src)\n\n\ttime.Sleep(time.Second)\n\tfinish <- true\n}"} {"input": "package format\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/types\"\n)\n\ntype podHandler func(*v1.Pod) string\n\n\n\nfunc Pod(pod *v1.Pod) string {\n\treturn PodDesc(pod.Name, pod.Namespace, pod.UID)\n}\n\n\n\nfunc PodDesc(podName, podNamespace string, podUID types.UID) string {\n\treturn fmt.Sprintf(\"%s_%s(%s)\", podName, podNamespace, podUID)\n}\n\n\n\nfunc PodWithDeletionTimestamp(pod *v1.Pod) string {\n\tvar deletionTimestamp string\n\tif pod.DeletionTimestamp != nil {\n\t\tdeletionTimestamp = \":DeletionTimestamp=\" + pod.DeletionTimestamp.UTC().Format(time.RFC3339)\n\t}\n\treturn Pod(pod) + deletionTimestamp\n}\n\n\n\nfunc Pods(pods []*v1.Pod) string {\n\treturn aggregatePods(pods, Pod)\n}\n\n\n\n\n\nfunc aggregatePods(pods []*v1.Pod, handler podHandler) string {\n\tpodStrings := make([]string, 0, len(pods))\n\tfor _, pod := range pods {\n\t\tpodStrings = append(podStrings, handler(pod))\n\t}\n\treturn fmt.Sprintf(strings.Join(podStrings, \", \"))\n}\n\nfunc PodsWithDeletiontimestamps(pods []*v1.Pod) string ", "output": "{\n\treturn aggregatePods(pods, PodWithDeletionTimestamp)\n}"} {"input": "package s3util\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n)\n\ntype respError struct {\n\tr *http.Response\n\tb bytes.Buffer\n}\n\n\n\nfunc (e *respError) Error() string {\n\treturn fmt.Sprintf(\n\t\t\"unwanted http status %d: %q\",\n\t\te.r.StatusCode,\n\t\te.b.String(),\n\t)\n}\n\nfunc newRespError(r *http.Response) *respError ", "output": "{\n\te := new(respError)\n\te.r = r\n\tio.Copy(&e.b, r.Body)\n\tr.Body.Close()\n\treturn e\n}"} {"input": "package models\n\nimport (\n\t\"log\"\n\n\t\"github.com/jinzhu/gorm\"\n\t_ \"github.com/lib/pq\"\n)\n\nvar db gorm.DB\n\n\n\nfunc init() ", "output": "{\n\tdatabase, err := gorm.Open(\"postgres\", \"user=postgres dbname=agile_metrics password=Test1234\")\n\tif err != nil {\n\t\tlog.Fatal(\"Cannot find database. Received error: \" + err.Error())\n\t} else {\n\t\tdb = database\n\n\t\tdb.DB()\n\n\t\tdb.DB().SetMaxOpenConns(20)\n\n\t\tdb.SingularTable(true)\n\n\t\tdb.LogMode(true)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", httpHandle)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\n\n\nfunc httpHandle(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tck := http.Cookie{Name: \"username\", Value: \"hahaya\", Path: \"/\", Domain: \"localhost\", MaxAge: 120}\n\thttp.SetCookie(w, &ck)\n\n\t_ck, err := r.Cookie(\"username\")\n\tif err != nil {\n\t\tfmt.Fprintf(w, err.Error())\n\t\treturn\n\t}\n\tfmt.Fprintf(w, _ck.Value)\n}"} {"input": "package helpers\n\nimport (\n \"fmt\"\n\n \"kekocity/data/entities\"\n \"kekocity/data/models\"\n \"kekocity/interfaces\"\n)\n\nvar AuthHelper *authHelper\n\ntype authHelper struct{}\n\nfunc init() {\n\tAuthHelper = &authHelper{}\n}\n\nfunc (a *authHelper) playerEntityToModel(_entity *entities.Player) (*models.Player, error) {\n u := models.NewPlayer(_entity)\n\n return u, nil\n}\n\n\n\nfunc (a *authHelper) AuthenticateUsingCredentials(_token string) (interfaces.IPlayer, error) ", "output": "{\n var players *entities.Player\n var query string = fmt.Sprintf(\"SELECT * FROM user WHERE token = '%v' LIMIT 1\", _token)\n db.Query(query).Rows(&players)\n\n if players == nil {\n\t\treturn nil, fmt.Errorf(\"Player '%s' not found\", _token)\n\t}\n\n\tplayerModel, err := a.playerEntityToModel(players)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn playerModel, nil\n}"} {"input": "package ast\n\nimport (\n\t\"testing\"\n)\n\nvar comments = []struct {\n\tlist []string\n\ttext string\n}{\n\t{[]string{\"\"}, \"\"},\n\t{[]string{\" \"}, \"\"},\n\t{[]string{\"\", \"\", \" \"}, \"\"},\n\t{[]string{\" foo \"}, \"foo\\n\"},\n\t{[]string{\"\", \"\", \" foo\"}, \"foo\\n\"},\n\t{[]string{\" foo bar \"}, \"foo bar\\n\"},\n\t{[]string{\" foo\", \" bar\"}, \"foo\\nbar\\n\"},\n\t{[]string{\" foo\", \"\", \"\", \"\", \" bar\"}, \"foo\\n\\nbar\\n\"},\n\t{[]string{\" foo\", \"/* bar */\"}, \"foo\\n bar\\n\"},\n\t{[]string{\"\", \"\", \"\", \" foo\", \"\", \"\", \"\"}, \"foo\\n\"},\n\n\t{[]string{\"/**/\"}, \"\"},\n\t{[]string{\"/* */\"}, \"\"},\n\t{[]string{\"/**/\", \"/**/\", \"/* */\"}, \"\"},\n\t{[]string{\"/* Foo */\"}, \" Foo\\n\"},\n\t{[]string{\"/* Foo Bar */\"}, \" Foo Bar\\n\"},\n\t{[]string{\"/* Foo*/\", \"/* Bar*/\"}, \" Foo\\n Bar\\n\"},\n\t{[]string{\"/* Foo*/\", \"/**/\", \"/**/\", \"/**/\", \" Bar\"}, \" Foo\\n\\nBar\\n\"},\n\t{[]string{\"/* Foo*/\", \"/*\\n*/\", \"\", \"/*\\n*/\", \" Bar\"}, \" Foo\\n\\nBar\\n\"},\n\t{[]string{\"/* Foo*/\", \" Bar\"}, \" Foo\\nBar\\n\"},\n\t{[]string{\"/* Foo\\n Bar*/\"}, \" Foo\\n Bar\\n\"},\n}\n\n\n\nfunc TestCommentText(t *testing.T) ", "output": "{\n\tfor i, c := range comments {\n\t\tlist := make([]*Comment, len(c.list))\n\t\tfor i, s := range c.list {\n\t\t\tlist[i] = &Comment{Text: s}\n\t\t}\n\n\t\ttext := (&CommentGroup{list}).Text()\n\t\tif text != c.text {\n\t\t\tt.Errorf(\"case %d: got %q; expected %q\", i, text, c.text)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/nlopes/slack\"\n)\n\n\n\nfunc doSlackDM(message string, destination string) error {\n\tvar destID string\n\tslackAPI := slack.New(config.SlackKey)\n\tuserList, err := slackAPI.GetUsers()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, u := range userList {\n\t\tif u.Name == destination {\n\t\t\tdestID = u.ID\n\t\t}\n\t}\n\tif destID == \"\" {\n\t\tif *flagDebug {\n\t\t\tfmt.Printf(\"user %s doesn't appear in Slack, fail silently\\n\", destination)\n\t\t}\n\t\treturn nil\n\t}\n\n\t_, _, channel, err := slackAPI.OpenIMChannel(destID)\n\tif err != nil {\n\t\treturn errors.New(\"Couldn't open IM channel\")\n\t}\n\n\tslackAPI.PostMessage(channel, message, getSlackParams())\n\tif *flagDebug {\n\t\tfmt.Printf(\"Sent DM on channel ID %s to %s\\n\", channel, destID)\n\t}\n\tslackAPI.CloseIMChannel(channel)\n\treturn err\n}\n\nfunc doSlackNotify(message string, destination string) error {\n\n\tslackAPI := slack.New(config.SlackKey)\n\tchannel := config.SlackChannel\n\tif destination != \"\" {\n\t\tchannel = destination\n\t}\n\tif *flagDebug {\n\t\tfmt.Printf(\"Attempting to send %s to %s with token %s\\n\", message, channel, config.SlackKey)\n\t}\n\tc, timestamp, err := slackAPI.PostMessage(channel, message, getSlackParams())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif *flagDebug {\n\t\tfmt.Printf(\"Message sent successfully to channel %s at %s\\n\", c, timestamp)\n\t}\n\treturn err\n}\n\nfunc getSlackParams() slack.PostMessageParameters ", "output": "{\n\tparams := slack.NewPostMessageParameters()\n\tparams.Username = \"rotator\"\n\tparams.IconEmoji = \":umbrella:\"\n\treturn params\n}"} {"input": "package libgogo\n\n\n\n\n\nvar Argv [255]string;\nvar Argc uint64 = 0;\n\n\n\n\n\nfunc GetArgv() {\n var fd uint64;\n var errno uint64; \n var singleChar byte;\n var lastChar byte = 1; \n\n fd = FileOpen(\"/proc/self/cmdline\", 0); \n if fd == 0 { \n ExitError(\"Error opening /proc/self/cmdline. Currently GoGo is only supported on systems with /proc enabled.\", 1);\n } \n\n for singleChar = GetChar(fd);(singleChar != 0) || (lastChar != 0); singleChar = GetChar(fd) {\n if (singleChar == 0) {\n Argc = Argc +1;\n } else {\n CharAppend(&Argv[Argc], singleChar);\n }\n lastChar = singleChar;\n }\n\n errno = FileClose(fd);\n if errno != 0 {\n ExitError(\"Error closing file /proc/self/cmdline\",1);\n }\n}\n\n\n\n\n\nfunc CopyMem(source uint64, dest uint64, size uint64);\n\n\n\n\n\nfunc Exit(code uint64);\n\n\n\n\n\n\nfunc ExitError(msg string, code uint64) ", "output": "{\n PrintString(msg);\n PrintChar(10); \n Exit(code);\n}"} {"input": "package runewidth\n\nimport (\n\t\"testing\"\n\t\"unicode/utf8\"\n)\n\nvar benchSink int\n\nfunc benchTable(b *testing.B, tbl table) int {\n\tn := 0\n\tfor i := 0; i < b.N; i++ {\n\t\tfor r := rune(0); r <= utf8.MaxRune; r++ {\n\t\t\tif inTable(r, tbl) {\n\t\t\t\tn++\n\t\t\t}\n\t\t}\n\t}\n\treturn n\n}\n\nfunc BenchmarkTablePrivate(b *testing.B) {\n\tbenchSink = benchTable(b, private)\n}\n\nfunc BenchmarkTableCombining(b *testing.B) {\n\tbenchSink = benchTable(b, combining)\n}\nfunc BenchmarkTableDoublewidth(b *testing.B) {\n\tbenchSink = benchTable(b, doublewidth)\n}\nfunc BenchmarkTableAmbiguous(b *testing.B) {\n\tbenchSink = benchTable(b, ambiguous)\n}\nfunc BenchmarkTableEmoji(b *testing.B) {\n\tbenchSink = benchTable(b, emoji)\n}\nfunc BenchmarkTableNotassigned(b *testing.B) {\n\tbenchSink = benchTable(b, notassigned)\n}\nfunc BenchmarkTableNeutral(b *testing.B) {\n\tbenchSink = benchTable(b, neutral)\n}\n\nfunc BenchmarkTableNonprint(b *testing.B) ", "output": "{\n\tbenchSink = benchTable(b, nonprint)\n}"} {"input": "package systembanner\n\nimport (\n\t\"net/http\"\n\n\trestful \"github.com/emicklei/go-restful\"\n\t\"github.com/kubernetes/dashboard/src/app/backend/systembanner/api\"\n)\n\n\ntype SystemBannerHandler struct {\n\tmanager SystemBannerManager\n}\n\n\nfunc (self *SystemBannerHandler) Install(ws *restful.WebService) {\n\tws.Route(\n\t\tws.GET(\"/systembanner\").\n\t\t\tTo(self.handleGet).\n\t\t\tWrites(api.SystemBanner{}))\n}\n\n\n\n\nfunc NewSystemBannerHandler(manager SystemBannerManager) SystemBannerHandler {\n\treturn SystemBannerHandler{manager: manager}\n}\n\nfunc (self *SystemBannerHandler) handleGet(request *restful.Request, response *restful.Response) ", "output": "{\n\tresponse.WriteHeaderAndEntity(http.StatusOK, self.manager.Get())\n}"} {"input": "package tweetharvest\n\nimport (\n\t\"time\"\n\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/appengine/datastore\"\n\t\"google.golang.org/appengine/log\"\n)\n\nconst tweetKey string = \"Tweets\"\nconst tweetKeyID string = \"default_tweetstore\"\n\n\n\nfunc GetAllNewTweets(since time.Time, c context.Context) LinkTweets {\n\tlog.Infof(c, \"Getting all tweets newer than: %v\", since)\n\tq := datastore.NewQuery(linkTweetKind).Ancestor(getTweetKey(c)).Filter(\"CreatedTime >\", since)\n\tout := make(LinkTweets, 0, 15)\n\tq.GetAll(c, &out)\n\treturn out\n}\n\nfunc getNewestTweet(c context.Context) time.Time {\n\tvar latest LinkTweet\n\n\tq := datastore.NewQuery(linkTweetKind).Order(\"-CreatedTime\").Project(\"CreatedTime\").Limit(1)\n\tq.GetAll(c, latest)\n\ti := q.Run(c)\n\ti.Next(&latest)\n\ttime, _ := latest.CreatedAtTime()\n\treturn time\n}\n\n\n\n\n\nfunc LinkTweetFromDatastore(tweetID int64, c context.Context) *LinkTweet {\n\tq := datastore.NewQuery(linkTweetKind).\n\t\tFilter(\"TweetID =\", tweetID).\n\t\tLimit(1)\n\n\titerator := q.Run(c)\n\tlinkTweet := &LinkTweet{}\n\t_, err := iterator.Next(linkTweet)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn linkTweet\n}\n\nfunc getTweetKey(c context.Context) *datastore.Key ", "output": "{\n\treturn datastore.NewKey(c, tweetKey, tweetKeyID, 0, nil)\n}"} {"input": "package models\n\nimport (\n\t\"encoding/json\"\n\t\"reflect\"\n)\n\n\n\nfunc ToJSON(v Validator) ([]byte, *Error) {\n\tif !isNil(v) {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn nil, NewError(InvalidRecord, err.Error())\n\t\t}\n\t}\n\n\tbytes, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn nil, NewError(InvalidJSON, err.Error())\n\t}\n\n\treturn bytes, nil\n}\n\nfunc isNil(a interface{}) bool {\n\tif a == nil {\n\t\treturn true\n\t}\n\n\tswitch reflect.TypeOf(a).Kind() {\n\tcase reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:\n\t\treturn reflect.ValueOf(a).IsNil()\n\t}\n\n\treturn false\n}\n\nfunc FromJSON(payload []byte, v Validator) error ", "output": "{\n\terr := json.Unmarshal(payload, v)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn v.Validate()\n}"} {"input": "package flog\n\nimport \"github.com/Sirupsen/logrus\"\n\ntype Parameter interface {\n\tConvert() map[string]interface{}\n}\n\ntype Fields struct {\n\tEvent string\n\tError error\n}\n\nfunc (f Fields) Convert() map[string]interface{} {\n\tfields := map[string]interface{}{}\n\n\tif f.Event != \"\" {\n\t\tfields[\"event\"] = f.Event\n\t}\n\n\tif f.Error != nil {\n\t\tfields[\"error\"] = f.Error\n\t}\n\n\treturn fields\n}\n\ntype Details map[string]interface{}\n\nfunc (d Details) Convert() map[string]interface{} {\n\treturn d\n}\n\ntype DebugFields map[string]interface{}\n\nfunc (d DebugFields) Convert() map[string]interface{} {\n\treturn map[string]interface{}{}\n}\n\nfunc transform(params []Parameter) logrus.Fields {\n\tlogrusFields := logrus.Fields{}\n\n\tfor _, p := range params {\n\t\tfieldMap := p.Convert()\n\n\t\tfor k, v := range fieldMap {\n\t\t\tlogrusFields[k] = v\n\t\t}\n\t}\n\n\treturn logrusFields\n}\n\nfunc Debug(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Debug(msg)\n}\n\nfunc Info(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Info(msg)\n}\n\nfunc Warn(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Warning(msg)\n}\n\n\n\nfunc Fatal(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Fatal(msg)\n}\n\nfunc Panic(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Panic(msg)\n}\n\nfunc Error(msg string, params ...Parameter) ", "output": "{\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Error(msg)\n}"} {"input": "package install\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nvar kubeProxyProtectedOptions = []string{\n\t\"cluster-cidr\",\n\t\"hostname-override\",\n}\n\n\n\nfunc (options *KubeProxyOptions) validate() (bool, []error) ", "output": "{\n\tv := newValidator()\n\toverrides := make([]string, 0)\n\tfor _, protectedOption := range kubeProxyProtectedOptions {\n\t\t_, found := options.Overrides[protectedOption]\n\t\tif found {\n\t\t\toverrides = append(overrides, protectedOption)\n\t\t}\n\t}\n\n\tif len(overrides) > 0 {\n\t\tv.addError(fmt.Errorf(\"Kube Proxy Option(s) [%v] cannot be overridden\", strings.Join(overrides, \", \")))\n\t}\n\n\treturn v.valid()\n}"} {"input": "package jsonfile\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestInvalidJSONFile(t *testing.T) {\n\tprovider := New(\"./invalid\")\n\t_, err := provider.Hosts()\n\tassert.Error(t, err, \"open /invalid: no such file or directory\", \"should fail to open file\")\n}\n\n\n\nfunc TestNiceJSONFile(t *testing.T) {\n\tcontent := []byte(\"[\\\"127.0.0.1:3000\\\", \\\"127.0.0.1:3042\\\"]\")\n\n\ttmpfile, err := ioutil.TempFile(\"\", \"jsonfiletest\")\n\tassert.NoError(t, err, \"failed to create a temp file\")\n\tdefer os.Remove(tmpfile.Name())\n\n\t_, err = tmpfile.Write(content)\n\tassert.NoError(t, err, \"failed to write contents to the temp file\")\n\n\terr = tmpfile.Close()\n\tassert.NoError(t, err, \"failed to write contents to the temp file\")\n\n\tprovider := New(tmpfile.Name())\n\tres, err := provider.Hosts()\n\tassert.NoError(t, err, \"hosts call failed\")\n\tassert.Equal(t, []string{\"127.0.0.1:3000\", \"127.0.0.1:3042\"}, res)\n}\n\nfunc TestMalformedJSONFile(t *testing.T) ", "output": "{\n\tprovider := New(\"../test/invalidhosts.json\")\n\t_, err := provider.Hosts()\n\tassert.Error(t, err, \"invalid character 'T' looking for beginning of value\", \"should fail to unmarhsal JSON\")\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n)\n\ntype SecurityBulletin struct {\n\tId string `json:\"id\"`\n\tAppliesToVersion string `json:\"applies_to_version\"`\n}\n\ntype SecurityBulletins []SecurityBulletin\n\n\n\nfunc SecurityBulletinFromJson(data io.Reader) *SecurityBulletin {\n\tvar o *SecurityBulletin\n\tjson.NewDecoder(data).Decode(&o)\n\treturn o\n}\n\nfunc (sb SecurityBulletins) ToJson() string {\n\tb, err := json.Marshal(sb)\n\tif err != nil {\n\t\treturn \"[]\"\n\t}\n\treturn string(b)\n}\n\nfunc SecurityBulletinsFromJson(data io.Reader) SecurityBulletins {\n\tvar o SecurityBulletins\n\tjson.NewDecoder(data).Decode(&o)\n\treturn o\n}\n\nfunc (sb *SecurityBulletin) ToJson() string ", "output": "{\n\tb, _ := json.Marshal(sb)\n\treturn string(b)\n}"} {"input": "package test_helpers\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\tdatatypes \"github.com/maximilien/softlayer-go/data_types\"\n)\n\ntype MockProductPackageService struct{}\n\nfunc (mock *MockProductPackageService) GetName() string {\n\treturn \"Mock_Product_Package_Service\"\n}\n\n\n\nfunc (mock *MockProductPackageService) GetItemPrices(packageId int) ([]datatypes.SoftLayer_Product_Item_Price, error) {\n\treturn []datatypes.SoftLayer_Product_Item_Price{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetItemPricesBySize(packageId int, size int) ([]datatypes.SoftLayer_Product_Item_Price, error) {\n\treturn []datatypes.SoftLayer_Product_Item_Price{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetItems(packageId int) ([]datatypes.SoftLayer_Product_Item, error) {\n\treturn []datatypes.SoftLayer_Product_Item{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetPackagesByType(packageType string) ([]datatypes.Softlayer_Product_Package, error) {\n\treturn []datatypes.Softlayer_Product_Package{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetOnePackageByType(packageType string) (datatypes.Softlayer_Product_Package, error) {\n\treturn datatypes.Softlayer_Product_Package{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetItemsByType(packageType string) ([]datatypes.SoftLayer_Product_Item, error) ", "output": "{\n\tresponse, _ := ReadJsonTestFixtures(\"services\", \"SoftLayer_Product_Package_getItemsByType_virtual_server.json\")\n\n\tproductItems := []datatypes.SoftLayer_Product_Item{}\n\tjson.Unmarshal(response, &productItems)\n\n\treturn productItems, nil\n}"} {"input": "package config\n\nimport (\n\t\"encoding/xml\"\n)\n\ntype defXMLReader struct {\n\topts ReaderOptions\n}\n\n\nfunc NewXMLReader(opts ...ReaderOptionFunc) Reader {\n\tr := &defXMLReader{}\n\tfor _, o := range opts {\n\t\to(&r.opts)\n\t}\n\treturn r\n}\n\nfunc (p *defXMLReader) Read(model interface{}) error {\n\tdata, err := ReadXMLFile(p.opts.filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ParseXMLConfig(data, model)\n}\n\nfunc (*defXMLReader) Dump(v interface{}) ([]byte, error) {\n\treturn xml.Marshal(v)\n}\n\nfunc (*defXMLReader) ParseData(data []byte, model interface{}) error {\n\treturn ParseXMLConfig(data, model)\n}\n\n\nfunc ReadXMLFile(name string) ([]byte, error) {\n\tdata, _, err := filesRepo.Read(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}\n\n\n\n\nfunc ParseXMLConfig(data []byte, model interface{}) error ", "output": "{\n\treturn xml.Unmarshal(data, model)\n}"} {"input": "package gobrightbox\n\n\n\ntype DatabaseServerType struct {\n\tID string\n\tName string\n\tDescription string\n\tDiskSize int `json:\"disk_size\"`\n\tRAM int\n}\n\n\n\n\n\nfunc (c *Client) DatabaseServerType(identifier string) (*DatabaseServerType, error) {\n\tdatabaseservertype := new(DatabaseServerType)\n\t_, err := c.MakeAPIRequest(\"GET\", \"/1.0/database_types/\"+identifier, nil, databaseservertype)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn databaseservertype, err\n}\n\nfunc (c *Client) DatabaseServerTypes() ([]DatabaseServerType, error) ", "output": "{\n\tvar databaseservertypes []DatabaseServerType\n\t_, err := c.MakeAPIRequest(\"GET\", \"/1.0/database_types\", nil, &databaseservertypes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn databaseservertypes, err\n}"} {"input": "package prometheus\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"istio.io/istio/pkg/test/framework\"\n\t\"istio.io/istio/pkg/test/framework/components/cluster\"\n\t\"istio.io/istio/pkg/test/framework/components/prometheus\"\n\t\"istio.io/istio/pkg/test/util/retry\"\n\tutil \"istio.io/istio/tests/integration/telemetry\"\n)\n\n\n\n\nfunc ValidateMetric(t framework.TestContext, cluster cluster.Cluster, prometheus prometheus.Instance, query prometheus.Query, want float64) {\n\tt.Helper()\n\terr := retry.UntilSuccess(func() error {\n\t\tgot, err := prometheus.QuerySum(cluster, query)\n\t\tt.Logf(\"%s: %f\", query.Metric, got)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif got < want {\n\t\t\treturn fmt.Errorf(\"bad metric value: got %f, want at least %f\", got, want)\n\t\t}\n\t\treturn nil\n\t}, retry.Delay(time.Second), retry.Timeout(time.Second*20))\n\tif err != nil {\n\t\tutil.PromDiff(t, prometheus, cluster, query)\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc QueryPrometheus(t framework.TestContext, cluster cluster.Cluster, query prometheus.Query, promInst prometheus.Instance) (string, error) ", "output": "{\n\tt.Helper()\n\tt.Logf(\"query prometheus with: %v\", query)\n\n\tval, err := promInst.Query(cluster, query)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tgot, err := prometheus.Sum(val)\n\tif err != nil {\n\t\tt.Logf(\"value: %s\", val.String())\n\t\treturn \"\", fmt.Errorf(\"could not find metric value: %v\", err)\n\t}\n\tt.Logf(\"get value %v\", got)\n\treturn val.String(), nil\n}"} {"input": "package restic\n\nimport \"syscall\"\n\n\n\nfunc (node Node) device() int {\n\treturn int(node.Device)\n}\n\nfunc (s statUnix) atim() syscall.Timespec { return s.Atimespec }\nfunc (s statUnix) mtim() syscall.Timespec { return s.Mtimespec }\nfunc (s statUnix) ctim() syscall.Timespec { return s.Ctimespec }\n\n\nfunc Getxattr(path, name string) ([]byte, error) {\n\treturn nil, nil\n}\n\n\n\nfunc Listxattr(path string) ([]string, error) {\n\treturn nil, nil\n}\n\n\nfunc Setxattr(path, name string, data []byte) error {\n\treturn nil\n}\n\nfunc (node Node) restoreSymlinkTimestamps(path string, utimes [2]syscall.Timespec) error ", "output": "{\n\treturn nil\n}"} {"input": "package orm\n\nfunc Delete(db dber, v interface{}) error {\n\tq := NewQuery(db, v)\n\tif q.err != nil {\n\t\treturn q.err\n\t}\n\t_, err := db.ExecOne(deleteQuery{q}, q.model)\n\treturn err\n}\n\ntype deleteQuery struct {\n\t*Query\n}\n\nvar _ QueryAppender = (*deleteQuery)(nil)\n\n\n\nfunc (del deleteQuery) AppendQuery(b []byte, params ...interface{}) ([]byte, error) ", "output": "{\n\tb = append(b, \"DELETE FROM \"...)\n\tb = del.appendTableNameWithAlias(b)\n\treturn del.appendWhere(b)\n}"} {"input": "package raft\n\nimport (\n\t\"github.com/iketheadore/raft/comm\"\n\t\"github.com/iketheadore/raft/logic\"\n)\n\ntype Raft struct {\n\tlocalServ logic.Server\n\tlistener comm.Listener\n\tsender comm.Sender\n\tlogic *logic.Logic\n}\n\nfunc New(addr string) *Raft {\n\tr := &Raft{localServ: logic.Server{Addr: addr, Role: logic.Follower}, listener: comm.NewListener(addr)}\n\tr.listener.Run()\n\tr.logic = logic.New(r.localServ)\n\tr.logic.Subscribe(r.listener)\n\treturn r\n}\n\nfunc (r *Raft) Connect(addr string) error {\n\treturn r.logic.Connect(logic.Server{Addr: addr, Role: logic.Follower})\n}\n\nfunc (r *Raft) Run() {\n\tr.logic.Run()\n}\n\n\n\nfunc (r *Raft) ReplicateCmd(cmd comm.Command) ", "output": "{\n\tr.logic.ReplicateCmd(cmd)\n}"} {"input": "package conn\n\nimport (\n\t\"os\"\n\t\"strings\"\n\n\treuseport \"github.com/djbarber/ipfs-hack/Godeps/_workspace/src/github.com/jbenet/go-reuseport\"\n)\n\n\n\nconst envReuseport = \"IPFS_REUSEPORT\"\n\n\nvar envReuseportVal = true\n\n\n\n\n\n\n\n\n\n\n\nfunc reuseportIsAvailable() bool {\n\treturn envReuseportVal && reuseport.Available()\n}\n\nfunc init() ", "output": "{\n\tv := strings.ToLower(os.Getenv(envReuseport))\n\tif v == \"false\" || v == \"f\" || v == \"0\" {\n\t\tenvReuseportVal = false\n\t\tlog.Infof(\"REUSEPORT disabled (IPFS_REUSEPORT=%s)\", v)\n\t}\n}"} {"input": "package cache\n\nimport \"github.com/lomik/go-carbon/points\"\n\n\ntype Query struct {\n\tMetric string\n\tReplyChan chan *Reply\n}\n\n\n\n\n\ntype Reply struct {\n\tPoints *points.Points\n}\n\n\nfunc NewReply() *Reply {\n\treturn &Reply{}\n}\n\nfunc NewQuery(metric string) *Query ", "output": "{\n\treturn &Query{\n\t\tMetric: metric,\n\t\tReplyChan: make(chan *Reply, 1),\n\t}\n}"} {"input": "package gocrawl\n\n\n\ntype popChannel chan []*URLContext\n\n\n\n\n\n\n\nfunc (pc popChannel) stack(cmd ...*URLContext) {\n\ttoStack := cmd\n\tfor {\n\t\tselect {\n\t\tcase pc <- toStack:\n\t\t\treturn\n\t\tcase old := <-pc:\n\t\t\ttoStack = append(old, toStack...)\n\t\t}\n\t}\n}\n\nfunc newPopChannel() popChannel ", "output": "{\n\treturn make(chan []*URLContext, 1)\n}"} {"input": "package main\n\nimport (\n\t\"code.google.com/p/go.tools/go/gccgoimporter\"\n\t\"code.google.com/p/go.tools/go/types\"\n)\n\nvar (\n\tinitmap = make(map[*types.Package]gccgoimporter.InitData)\n)\n\nfunc init() {\n\tincpaths := []string{\"/\"}\n\n\tvar inst gccgoimporter.GccgoInstallation\n\tinst.InitFromDriver(\"gccgo\")\n\tregister(\"gccgo\", inst.GetImporter(incpaths, initmap))\n}\n\n\n\n\nfunc (p *printer) printGccgoExtra(pkg *types.Package) ", "output": "{\n\tif initdata, ok := initmap[pkg]; ok {\n\t\tp.printf(\"/*\\npriority %d\\n\", initdata.Priority)\n\n\t\tp.printDecl(\"init\", len(initdata.Inits), func() {\n\t\t\tfor _, init := range initdata.Inits {\n\t\t\t\tp.printf(\"%s %s %d\\n\", init.Name, init.InitFunc, init.Priority)\n\t\t\t}\n\t\t})\n\n\t\tp.print(\"*/\\n\")\n\t}\n}"} {"input": "package main\n\nimport (\n \"github.com/gorilla/websocket\"\n \"encoding/json\"\n)\n\n\n\nfunc (c *connection) writer() ", "output": "{\n\n\tfor event := range c.send {\n \n j, _ := json.Marshal(event)\n \n\t\terr := c.ws.WriteMessage(websocket.TextMessage, []byte(j))\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tc.ws.Close()\n}"} {"input": "package nsqd\n\nimport (\n\t\"bytes\"\n\t\"sync\"\n)\n\nvar bp sync.Pool\n\nfunc init() {\n\tbp.New = func() interface{} {\n\t\treturn &bytes.Buffer{}\n\t}\n}\n\nfunc bufferPoolGet() *bytes.Buffer {\n\treturn bp.Get().(*bytes.Buffer)\n}\n\n\n\nfunc bufferPoolPut(b *bytes.Buffer) ", "output": "{\n\tb.Reset()\n\tbp.Put(b)\n}"} {"input": "package thread\n\nimport \"time\"\n\ntype ThreadStatistic struct {\n\tThreadId int `json:\"thread_id\"`\n\tProcessedLines int `json:\"processed_lines\"`\n\tStartTime time.Time `json:\"start_time\"`\n\tEndTime time.Time `json:\"end_time\"`\n\tDeltaTime time.Duration `json:\"delta_time\"`\n}\n\n\n\nfunc (ts *ThreadStatistic) IncreaseProcessedLines() {\n\tts.ProcessedLines += 1\n}\n\nfunc (ts *ThreadStatistic) SetEndTime() {\n\tts.EndTime = time.Now()\n\tts.DeltaTime = ts.EndTime.Sub(ts.StartTime) / time.Millisecond\n}\n\nfunc NewThreadStadistic(threadId int) *ThreadStatistic ", "output": "{\n\tvar ts ThreadStatistic\n\n\tts.ThreadId = threadId\n\tts.ProcessedLines = 0\n\tts.StartTime = time.Now()\n\n\treturn &ts\n}"} {"input": "package jwt_test\n\nimport (\n\t\"log\"\n\t\"testing\"\n\n\t\"github.com/nilslice/jwt\"\n)\n\nfunc TestGrantPasses(t *testing.T) {\n\tclaims := map[string]interface{}{\n\t\t\"testID\": 1,\n\t\t\"name\": \"GrantPasses\",\n\t}\n\n\tgrant, err := jwt.New(claims)\n\tif err != nil {\n\t\tt.Log(claims, grant, err)\n\t\tt.Fail()\n\t}\n\n\tif !jwt.Passes(grant) {\n\t\tt.Fail()\n\t}\n}\n\n\n\nfunc TestGetClaims(t *testing.T) {\n\temail := \"hello@nilslice.xyz\"\n\tauthLevel := float64(7)\n\n\tclaims := map[string]interface{}{\n\t\t\"email\": email,\n\t\t\"auth_level\": authLevel,\n\t}\n\n\ttoken, err := jwt.New(claims)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tt.Fail()\n\t}\n\n\tclaims = jwt.GetClaims(token)\n\tif claims[\"email\"].(string) != email ||\n\t\tclaims[\"auth_level\"].(float64) != authLevel {\n\t\tt.Fail()\n\t}\n\n}\n\nfunc TestGrantFails(t *testing.T) ", "output": "{\n\tclaims := map[string]interface{}{\n\t\t\"testID\": 2,\n\t\t\"name\": \"GrantFails\",\n\t}\n\n\tgrant, err := jwt.New(claims)\n\tif err != nil {\n\t\tt.Log(claims, grant, err)\n\t\tt.Fail()\n\t}\n\n\tjwt.Secret([]byte(\"NotPreviousSecret\"))\n\n\tif jwt.Passes(grant) {\n\t\tt.Fail()\n\t}\n}"} {"input": "package pool\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/credentials\"\n\n\t\"github.com/cilium/cilium/pkg/crypto/certloader\"\n\tpoolTypes \"github.com/cilium/cilium/pkg/hubble/relay/pool/types\"\n\thubbleopts \"github.com/cilium/cilium/pkg/hubble/server/serveroption\"\n)\n\n\ntype GRPCClientConnBuilder struct {\n\tDialTimeout time.Duration\n\tOptions []grpc.DialOption\n\n\tTLSConfig certloader.ClientConfigBuilder\n}\n\n\n\n\nfunc (b GRPCClientConnBuilder) ClientConn(target, hostname string) (poolTypes.ClientConn, error) ", "output": "{\n\tswitch {\n\tcase b.TLSConfig != nil && hostname == \"\":\n\t\treturn nil, fmt.Errorf(\"missing TLS ServerName for %s\", target)\n\tcase b.TLSConfig == nil && hostname != \"\":\n\t\treturn nil, fmt.Errorf(\"unexpected TLS ServerName %s for %s\", hostname, target)\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), b.DialTimeout)\n\tdefer cancel()\n\topts := make([]grpc.DialOption, len(b.Options))\n\tcopy(opts, b.Options)\n\n\tif b.TLSConfig == nil {\n\t\topts = append(opts, grpc.WithInsecure())\n\t} else {\n\t\ttlsConfig := b.TLSConfig.ClientConfig(&tls.Config{\n\t\t\tServerName: hostname,\n\t\t\tMinVersion: hubbleopts.MinTLSVersion,\n\t\t})\n\t\topts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))\n\t}\n\treturn grpc.DialContext(ctx, target, opts...)\n}"} {"input": "package chart\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/golang/protobuf/jsonpb\"\n)\n\n\nfunc (msg *Config) MarshalJSON() ([]byte, error) {\n\tvar buf bytes.Buffer\n\terr := (&jsonpb.Marshaler{\n\t\tEnumsAsInts: false,\n\t\tEmitDefaults: false,\n\t\tOrigName: false,\n\t}).Marshal(&buf, msg)\n\treturn buf.Bytes(), err\n}\n\n\nfunc (msg *Config) UnmarshalJSON(b []byte) error {\n\treturn (&jsonpb.Unmarshaler{\n\t\tAllowUnknownFields: false,\n\t}).Unmarshal(bytes.NewReader(b), msg)\n}\n\n\n\n\n\nfunc (msg *Value) UnmarshalJSON(b []byte) error {\n\treturn (&jsonpb.Unmarshaler{\n\t\tAllowUnknownFields: false,\n\t}).Unmarshal(bytes.NewReader(b), msg)\n}\n\nfunc (msg *Value) MarshalJSON() ([]byte, error) ", "output": "{\n\tvar buf bytes.Buffer\n\terr := (&jsonpb.Marshaler{\n\t\tEnumsAsInts: false,\n\t\tEmitDefaults: false,\n\t\tOrigName: false,\n\t}).Marshal(&buf, msg)\n\treturn buf.Bytes(), err\n}"} {"input": "package handlers\n\nimport (\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/byuoitav/configuration-database-microservice/structs\"\n\t\"github.com/labstack/echo\"\n)\n\nfunc (handlerGroup *HandlerGroup) GetDeviceRoleDefs(context echo.Context) error {\n\tresponse, err := handlerGroup.Accessors.GetDeviceRoleDefs()\n\tif err != nil {\n\t\treturn context.String(http.StatusBadRequest, err.Error())\n\t}\n\n\treturn context.JSON(http.StatusOK, response)\n}\n\n\n\nfunc (handlerGroup *HandlerGroup) GetDeviceRoleDefsById(context echo.Context) error {\n\n\tid, err := strconv.Atoi(context.Param(\"id\"))\n\tif err != nil {\n\t\treturn context.JSON(http.StatusBadRequest, err.Error())\n\t}\n\n\tresponse, err := handlerGroup.Accessors.GetDeviceRoleDefByID(id)\n\tif err != nil {\n\t\treturn context.JSON(http.StatusBadRequest, err.Error())\n\t}\n\n\treturn context.JSON(http.StatusOK, response)\n\n}\n\nfunc (handlerGroup *HandlerGroup) AddDeviceRoleDef(context echo.Context) error ", "output": "{\n\tdrdName := context.Param(\"deviceroledefinition\")\n\tvar drd structs.DeviceRoleDef\n\n\terr := context.Bind(&drd)\n\tif err != nil {\n\t\treturn context.JSON(http.StatusBadRequest, err.Error())\n\t}\n\tif drdName != drd.Name {\n\t\treturn context.JSON(http.StatusBadRequest, \"Endpoint parameter and json name must match!\")\n\t}\n\n\tresponse, err := handlerGroup.Accessors.AddDeviceRoleDef(drd)\n\tif err != nil {\n\t\treturn context.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\n\treturn context.JSON(http.StatusOK, response)\n}"} {"input": "package faregate\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc Must(c <-chan struct{}, err error) <-chan struct{} {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn c\n}\n\n\n\nfunc Example() ", "output": "{\n\trnd := rand.New(rand.NewSource(42))\n\n\tfg, err := New(RefreshInterval(time.Second), TokenCount(100), ConcurrencyLevel(1))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer fg.Close()\n\n\tfor {\n\t\tq := rnd.Intn(10)\n\t\t<-Must(fg.Acquire(uint64(q)))\n\t\tfmt.Println(\"acquired\", q)\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype UpdateDedicatedVmHostRequest struct {\n\n\tDedicatedVmHostId *string `mandatory:\"true\" contributesTo:\"path\" name:\"dedicatedVmHostId\"`\n\n\tUpdateDedicatedVmHostDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateDedicatedVmHostRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request UpdateDedicatedVmHostRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateDedicatedVmHostResponse struct {\n\n\tRawResponse *http.Response\n\n\tDedicatedVmHost `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateDedicatedVmHostResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateDedicatedVmHostResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateDedicatedVmHostRequest) HTTPRequest(method, path string) (http.Request, error) ", "output": "{\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}"} {"input": "package main\n\ntype Human struct {\n\tname string\n\tage int\n\tphone string\n}\n\ntype Student struct {\n\tHuman\n\tschool string\n\tloan float32\n}\n\ntype Employee struct {\n\tHuman\n\tcompany string\n\tmoney float32\n}\n\n\ntype Men interface {\n\tSayHi()\n\tSing(lyrics string)\n\tGuzzle(beerStein string)\n}\n\ntype YoungChap interface {\n\tSayHi()\n\tSing(lyrics string)\n\tBorrowMoney(amount float32)\n}\n\ntype ElderlyGent interface {\n\tSayHi()\n\tSing(song string)\n\tSpendSalary(amount float32)\n}\n\nfunc (h *Human) SayHi() {\n\tfmt.Printf(\"Hi, I am %s you can call me on %s\\n\", h.name, h.phone)\n}\n\nfunc (h *Human) Sing(lyrics string) {\n\tfmt.Println(\"La la, la la la, la la la la...\", lyrics)\n}\n\n\n\n\nfunc (e *Employee) SayHi() {\n\tfmt.Printf(\"Hi, I am %s, I work at %s. Call me on %s\\n\", e.name, e.company, e.phone)\n}\n\nfunc (s *Student) BorrowMoney(amount float32) {\n\ts.loan += amount\n}\n\nfunc (e *Employee) SpendSalary(amount float32) {\n\te.money -= e.amount\n}\n\nfunc (h *Human) Guzzle(beerStein string) ", "output": "{\n\tfmt.Println(\"Guzzle Guzzle Guzzle...\", beerStein)\n}"} {"input": "package cgzip\n\n\nimport \"C\"\n\nimport (\n\t\"hash\"\n\t\"unsafe\"\n)\n\ntype adler32Hash struct {\n\tadler C.uLong\n}\n\n\n\nfunc NewAdler32() hash.Hash32 {\n\ta := &adler32Hash{}\n\ta.Reset()\n\treturn a\n}\n\n\nfunc (a *adler32Hash) Write(p []byte) (n int, err error) {\n\tif len(p) > 0 {\n\t\ta.adler = C.adler32(a.adler, (*C.Bytef)(unsafe.Pointer(&p[0])), (C.uInt)(len(p)))\n\t}\n\treturn len(p), nil\n}\n\n\nfunc (a *adler32Hash) Sum(b []byte) []byte {\n\ts := a.Sum32()\n\tb = append(b, byte(s>>24))\n\tb = append(b, byte(s>>16))\n\tb = append(b, byte(s>>8))\n\tb = append(b, byte(s))\n\treturn b\n}\n\n\n\nfunc (a *adler32Hash) Size() int {\n\treturn 4\n}\n\nfunc (a *adler32Hash) BlockSize() int {\n\treturn 1\n}\n\n\nfunc (a *adler32Hash) Sum32() uint32 {\n\treturn uint32(a.adler)\n}\n\n\n\n\n\n\n\nfunc Adler32Combine(adler1, adler2 uint32, len2 int) uint32 {\n\treturn uint32(C.adler32_combine(C.uLong(adler1), C.uLong(adler2), C.z_off_t(len2)))\n}\n\nfunc (a *adler32Hash) Reset() ", "output": "{\n\ta.adler = C.adler32(0, (*C.Bytef)(unsafe.Pointer(nil)), 0)\n}"} {"input": "package scheduler\n\nimport \"github.com/aosen/robot\"\n\ntype SimpleScheduler struct {\n\tqueue chan *robot.Request\n}\n\nfunc NewSimpleScheduler() *SimpleScheduler {\n\tch := make(chan *robot.Request, 1024)\n\treturn &SimpleScheduler{ch}\n}\n\n\n\nfunc (this *SimpleScheduler) Poll() *robot.Request {\n\tif len(this.queue) == 0 {\n\t\treturn nil\n\t} else {\n\t\treturn <-this.queue\n\t}\n}\n\nfunc (this *SimpleScheduler) Count() int {\n\treturn len(this.queue)\n}\n\nfunc (this *SimpleScheduler) Push(requ *robot.Request) ", "output": "{\n\tthis.queue <- requ\n}"} {"input": "package ansiwriter\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype Modifier func() string\n\nfunc escapeANSI(code int) string {\n\treturn fmt.Sprintf(\"\\033[%dm\", code)\n}\n\nfunc Bold() string { return escapeANSI(1) }\nfunc Black() string { return escapeANSI(30) }\nfunc Red() string { return escapeANSI(31) }\nfunc Green() string { return escapeANSI(32) }\nfunc Yellow() string { return escapeANSI(33) }\nfunc Blue() string { return escapeANSI(34) }\nfunc Magenta() string { return escapeANSI(35) }\nfunc Cyan() string { return escapeANSI(36) }\n\n\ntype awr struct {\n\tio.Writer\n\tmodifiers []Modifier\n}\n\n\n\n\nfunc New(w io.Writer, mods ...Modifier) io.Writer {\n\treturn awr{w, mods}\n}\n\nfunc (a awr) Write(b []byte) (n int, err error) {\n\tfor _, mod := range a.modifiers {\n\t\ta.Writer.Write([]byte(mod()))\n\t}\n\tn, err = a.Writer.Write(b)\n\t_, _ = a.Writer.Write([]byte(\"\\033[0m\"))\n\treturn\n}\n\nfunc White() string ", "output": "{ return escapeANSI(37) }"} {"input": "package types\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v1\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc newLocalDevicesObj() *LocalDevices {\n\treturn &LocalDevices{\n\t\tDriver: \"vfs\",\n\t\tDeviceMap: map[string]string{\n\t\t\t\"vfs-000\": \"/dev/xvda\",\n\t\t\t\"vfs-001\": \"/dev/xvdb\",\n\t\t\t\"vfs-002\": \"/dev/xvdc\",\n\t\t},\n\t}\n}\n\nvar expectedLD1String = \"vfs=vfs-000::/dev/xvda,vfs-001::/dev/xvdb,vfs-002::/dev/xvdc\"\n\nfunc TestLocalDevicesMarshalText(t *testing.T) {\n\n\tld1 := newLocalDevicesObj()\n\tassert.Equal(t, expectedLD1String, ld1.String())\n\tt.Logf(\"localDevices=%s\", ld1)\n\n\tld2 := &LocalDevices{}\n\tassert.NoError(t, ld2.UnmarshalText([]byte(ld1.String())))\n\tassert.EqualValues(t, ld1, ld2)\n}\n\nfunc TestLocalDevicesUnmarshalText(t *testing.T) {\n\n\tld1 := &LocalDevices{}\n\terr := ld1.UnmarshalText([]byte(\"scaleio=\"))\n\tassert.NoError(t, err)\n}\n\nfunc TestLocalDevicesMarshalJSON(t *testing.T) {\n\n\tld1 := newLocalDevicesObj()\n\n\tbuf, err := ld1.MarshalJSON()\n\tassert.NoError(t, err)\n\tt.Logf(\"localDevices=%s\", string(buf))\n\n\tld2 := &LocalDevices{}\n\tassert.NoError(t, ld2.UnmarshalJSON(buf))\n\n\tassert.EqualValues(t, ld1, ld2)\n}\n\n\n\nfunc TestLocalDevicesMarshalToYAML(t *testing.T) ", "output": "{\n\tout, err := yaml.Marshal(newLocalDevicesObj())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfmt.Println(string(out))\n}"} {"input": "package global\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/propagation\"\n)\n\n\n\n\ntype textMapPropagator struct {\n\tmtx sync.Mutex\n\tonce sync.Once\n\tdelegate propagation.TextMapPropagator\n\tnoop propagation.TextMapPropagator\n}\n\n\n\nvar _ propagation.TextMapPropagator = (*textMapPropagator)(nil)\n\nfunc newTextMapPropagator() *textMapPropagator {\n\treturn &textMapPropagator{\n\t\tnoop: propagation.NewCompositeTextMapPropagator(),\n\t}\n}\n\n\n\n\n\n\n\n\n\nfunc (p *textMapPropagator) effectiveDelegate() propagation.TextMapPropagator {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tif p.delegate != nil {\n\t\treturn p.delegate\n\t}\n\treturn p.noop\n}\n\n\nfunc (p *textMapPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) {\n\tp.effectiveDelegate().Inject(ctx, carrier)\n}\n\n\nfunc (p *textMapPropagator) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context {\n\treturn p.effectiveDelegate().Extract(ctx, carrier)\n}\n\n\nfunc (p *textMapPropagator) Fields() []string {\n\treturn p.effectiveDelegate().Fields()\n}\n\nfunc (p *textMapPropagator) SetDelegate(delegate propagation.TextMapPropagator) ", "output": "{\n\tif delegate == nil {\n\t\treturn\n\t}\n\n\tp.mtx.Lock()\n\tp.once.Do(func() { p.delegate = delegate })\n\tp.mtx.Unlock()\n}"} {"input": "package dev\n\nimport \"fmt\"\n\n\n\ntype Configuration struct {\n\tid uint32\n\tnodes []*Node\n\tn int\n\tmgr *Manager\n\tqspec QuorumSpec\n\terrs chan CallGRPCError\n}\n\n\n\n\n\n\nfunc (c *Configuration) ID() uint32 {\n\treturn c.id\n}\n\n\n\n\nfunc (c *Configuration) NodeIDs() []uint32 {\n\tids := make([]uint32, len(c.nodes))\n\tfor i, node := range c.nodes {\n\t\tids[i] = node.ID()\n\t}\n\treturn ids\n}\n\n\n\nfunc (c *Configuration) Nodes() []*Node {\n\treturn c.nodes\n}\n\n\nfunc (c *Configuration) Size() int {\n\treturn c.n\n}\n\nfunc (c *Configuration) String() string {\n\treturn fmt.Sprintf(\"configuration %d\", c.id)\n}\n\nfunc (c *Configuration) tstring() string {\n\treturn fmt.Sprintf(\"config-%d\", c.id)\n}\n\n\n\nfunc Equal(a, b *Configuration) bool { return a.id == b.id }\n\n\n\n\nfunc NewTestConfiguration(q, n int) *Configuration {\n\treturn &Configuration{\n\t\tnodes: make([]*Node, n),\n\t}\n}\n\nfunc (c *Configuration) SubError() <-chan CallGRPCError ", "output": "{\n\treturn c.errs\n}"} {"input": "package models\n\nimport (\n\t\"github.com/go-gorp/gorp\"\n\t\"github.com/skarllot/flogviewer/common\"\n)\n\ntype Host struct {\n\tId int64 `db:\"id\"`\n\tName string `db:\"name\"`\n\tCategoryId *int64 `db:\"category\"`\n\n\tCategory *Category `db:\"-\"`\n}\n\nfunc DefineHostTable(dbm *gorp.DbMap) {\n\tt := dbm.AddTableWithName(Host{}, \"host\")\n\tt.SetKeys(true, \"id\")\n\tt.ColMap(\"name\").\n\t\tSetUnique(true).\n\t\tSetNotNull(true)\n}\n\n\n\nfunc (self *Host) PreUpdate(exe gorp.SqlExecutor) error {\n\treturn self.PreInsert(exe)\n}\n\nfunc (self *Host) PostGet(exe gorp.SqlExecutor) error {\n\tif self.CategoryId != nil {\n\t\tobj, err := exe.Get(Category{}, *self.CategoryId)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tself.Category = obj.(*Category)\n\t}\n\treturn nil\n}\n\nfunc (self *Host) PreInsert(gorp.SqlExecutor) error ", "output": "{\n\tif self.Category != nil {\n\t\tself.CategoryId = common.NInt64(self.Category.Id)\n\t}\n\n\treturn nil\n}"} {"input": "package archive\n\nimport (\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com/containers/storage/pkg/system\"\n\t\"golang.org/x/sys/unix\"\n)\n\nfunc statDifferent(oldStat *system.StatT, newStat *system.StatT) bool {\n\tif oldStat.Mode() != newStat.Mode() ||\n\t\toldStat.UID() != newStat.UID() ||\n\t\toldStat.GID() != newStat.GID() ||\n\t\toldStat.Rdev() != newStat.Rdev() ||\n\t\t(oldStat.Mode()&unix.S_IFDIR != unix.S_IFDIR &&\n\t\t\t(!sameFsTimeSpec(oldStat.Mtim(), newStat.Mtim()) || (oldStat.Size() != newStat.Size()))) {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc getIno(fi os.FileInfo) uint64 {\n\treturn fi.Sys().(*syscall.Stat_t).Ino\n}\n\nfunc hasHardlinks(fi os.FileInfo) bool {\n\treturn fi.Sys().(*syscall.Stat_t).Nlink > 1\n}\n\nfunc (info *FileInfo) isDir() bool ", "output": "{\n\treturn info.parent == nil || info.stat.Mode()&unix.S_IFDIR != 0\n}"} {"input": "package fake\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\n\t. \"github.com/onsi/gomega\"\n\t\"github.com/onsi/gomega/ghttp\"\n)\n\ntype CFAPI struct {\n\tserver *ghttp.Server\n}\n\ntype CFAPIConfig struct {\n\tRoutes map[string]Response\n}\n\ntype Response struct {\n\tCode int\n\tBody interface{}\n}\n\nfunc NewCFAPI() *CFAPI {\n\tserver := ghttp.NewServer()\n\treturn &CFAPI{\n\t\tserver: server,\n\t}\n}\n\n\n\nfunc (a *CFAPI) Close() {\n\ta.server.Close()\n}\n\nfunc (a *CFAPI) URL() string {\n\treturn a.server.URL()\n}\n\nfunc (a *CFAPI) ReceivedRequests() map[string][]*http.Request {\n\tresult := map[string][]*http.Request{}\n\n\tfor _, req := range a.server.ReceivedRequests() {\n\t\tkey := fmt.Sprintf(\"%s %s\", req.Method, req.URL.Path)\n\t\tresult[key] = append(result[key], req)\n\t}\n\n\treturn result\n}\n\nfunc parseRequest(request string) (string, string) {\n\tfields := strings.Split(request, \" \")\n\tExpect(fields).To(HaveLen(2))\n\treturn fields[0], fields[1]\n}\n\nfunc (a *CFAPI) SetConfiguration(config CFAPIConfig) ", "output": "{\n\ta.server.Reset()\n\n\tfor request, response := range config.Routes {\n\t\tmethod, path := parseRequest(request)\n\t\tresponseBytes, err := json.Marshal(response.Body)\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\ta.server.RouteToHandler(method, path, ghttp.RespondWith(response.Code, responseBytes))\n\t}\n}"} {"input": "package b\n\nimport \"a\"\n\nvar N n\n\ntype n struct{}\n\n\nfunc (r n) M2() int { return a.G2 }\nfunc (r n) M3() int { return a.G3 }\nfunc (r n) M4() int { return a.G4 }\nfunc (r n) M5() int { return a.G5 }\nfunc (r n) M6() int { return a.G6 }\nfunc (r n) M7() int { return a.G7 }\nfunc (r n) M8() int { return a.G8 }\nfunc (r n) M9() int { return a.G9 }\nfunc (r n) M10() int { return a.G10 }\n\nfunc (r n) M1() int ", "output": "{ return a.G1 }"} {"input": "package diskmanager\n\nimport (\n\t\"github.com/juju/names\"\n\n\t\"github.com/juju/juju/api/base\"\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/storage\"\n)\n\nconst diskManagerFacade = \"DiskManager\"\n\n\ntype State struct {\n\tfacade base.FacadeCaller\n\ttag names.MachineTag\n}\n\n\nfunc NewState(caller base.APICaller, authTag names.MachineTag) *State {\n\treturn &State{\n\t\tbase.NewFacadeCaller(caller, diskManagerFacade),\n\t\tauthTag,\n\t}\n}\n\n\n\n\n\nfunc (st *State) SetMachineBlockDevices(devices []storage.BlockDevice) error ", "output": "{\n\targs := params.SetMachineBlockDevices{\n\t\tMachineBlockDevices: []params.MachineBlockDevices{{\n\t\t\tMachine: st.tag.String(),\n\t\t\tBlockDevices: devices,\n\t\t}},\n\t}\n\tvar results params.ErrorResults\n\terr := st.facade.FacadeCall(\"SetMachineBlockDevices\", args, &results)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn results.OneError()\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/cihub/seelog\"\n)\n\n\nconst Succeed = \"\\u2713\"\n\n\nconst Failed = \"\\u2717\"\n\nfunc init() {\n\tseelogConfig := \"conf/seelog.xml.test\"\n\tlogger, err := seelog.LoggerFromConfigAsFile(seelogConfig)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"FOO Error creating Logger from seelog file: %s\", seelogConfig)\n\t\tseelog.Error(err)\n\t}\n\tdefer seelog.Flush()\n\tseelog.ReplaceLogger(logger)\n}\n\n\nfunc Context(t *testing.T, msg string, args ...interface{}) {\n\tt.Log(fmt.Sprintf(msg, args...))\n}\n\n\n\n\n\nfunc Error(t *testing.T, msg string, args ...interface{}) {\n\tm := fmt.Sprintf(msg, args...)\n\tt.Error(fmt.Sprintf(\"\\t %-80s\", m), Failed)\n}\n\n\nfunc Success(t *testing.T, msg string, args ...interface{}) {\n\tm := fmt.Sprintf(msg, args...)\n\tt.Log(fmt.Sprintf(\"\\t %-80s\", m), Succeed)\n}\n\nfunc Fatal(t *testing.T, msg string, args ...interface{}) ", "output": "{\n\tm := fmt.Sprintf(msg, args...)\n\tt.Fatal(fmt.Sprintf(\"\\t %-80s\", m), Failed)\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateDbHomeRequest struct {\n\n\tCreateDbHomeWithDbSystemIdDetails CreateDbHomeBase `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateDbHomeRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateDbHomeRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request CreateDbHomeRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateDbHomeResponse struct {\n\n\tRawResponse *http.Response\n\n\tDbHome `presentIn:\"body\"`\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateDbHomeResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateDbHomeResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateDbHomeRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package aws\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/resource\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\n\n\nfunc testAccCheckAWSInspectorResourceGroupExists(name string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\t_, ok := s.RootModule().Resources[name]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", name)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nvar testAccAWSInspectorResourceGroup = `\nresource \"aws_inspector_resource_group\" \"foo\" {\n\ttags = {\n\t Name = \"foo\"\n }\n}`\n\nvar testAccCheckAWSInspectorResourceGroupModified = `\nresource \"aws_inspector_resource_group\" \"foo\" {\n\ttags = {\n\t Name = \"bar\"\n }\n}`\n\nfunc TestAccAWSInspectorResourceGroup_basic(t *testing.T) ", "output": "{\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSInspectorResourceGroup,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSInspectorResourceGroupExists(\"aws_inspector_resource_group.foo\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tConfig: testAccCheckAWSInspectorResourceGroupModified,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSInspectorResourceGroupExists(\"aws_inspector_resource_group.foo\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}"} {"input": "package strreverse\n\nimport \"testing\"\n\n\n\nfunc TestReverse(t *testing.T) ", "output": "{\n original := []string{\"Hello World!\", \"This is the best day of my life\", \"It's a beautiful world\"}\n reverse := []string{\"!dlroW olleH\", \"efil ym fo yad tseb eht si sihT\", \"dlrow lufituaeb a s'tI\"}\n\n for i, s := range original {\n if r := Reverse(s); r != reverse[i] {\n t.Errorf(\"Reverse of %s is not %s, it is %s\", s, r, reverse[i])\n }\n }\n}"} {"input": "package server\n\nimport \"github.com/poy/petasos/router\"\n\ntype RouterFetcher struct {\n\tfs router.FileSystem\n\thasher router.Hasher\n\tmetricsCounter router.MetricsCounter\n}\n\n\n\nfunc (f *RouterFetcher) Writer() (writer func(data []byte) (err error), err error) {\n\treturn router.New(f.fs, f.hasher, f.metricsCounter).Write, nil\n}\n\nfunc NewRouterFetcher(\n\tfs router.FileSystem,\n\thasher router.Hasher,\n\tmetricsCounter router.MetricsCounter,\n) *RouterFetcher ", "output": "{\n\treturn &RouterFetcher{fs: fs, hasher: hasher, metricsCounter: metricsCounter}\n}"} {"input": "package messenger\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/scionproto/scion/go/lib/common\"\n\t\"github.com/scionproto/scion/go/lib/ctrl\"\n\t\"github.com/scionproto/scion/go/lib/infra/disp\"\n\t\"github.com/scionproto/scion/go/lib/log\"\n\t\"github.com/scionproto/scion/go/proto\"\n)\n\nvar _ disp.MessageAdapter = (*Adapter)(nil)\n\n\ntype Adapter struct{}\n\n\nvar DefaultAdapter = &Adapter{}\n\nfunc (a *Adapter) MsgToRaw(msg proto.Cerealizable) (common.RawBytes, error) {\n\tpld, ok := msg.(*ctrl.SignedPld)\n\tif !ok {\n\t\treturn nil, common.NewBasicError(\n\t\t\t\"Unable to type assert proto.Cerealizable to ctrl.SignedPld\",\n\t\t\tnil, \"msg\", msg, \"type\", common.TypeOf(msg))\n\t}\n\treturn pld.PackPld()\n}\n\n\n\nfunc (a *Adapter) MsgKey(msg proto.Cerealizable) string {\n\tsignedCtrlPld, ok := msg.(*ctrl.SignedPld)\n\tif !ok {\n\t\tlog.Warn(\"Unable to type assert disp.Message to ctrl.SignedPld\", \"msg\", msg,\n\t\t\t\"type\", common.TypeOf(msg))\n\t\treturn \"\"\n\t}\n\n\tctrlPld, err := signedCtrlPld.Pld()\n\tif err != nil {\n\t\tlog.Warn(\"Unable to extract CtrlPld from SignedCtrlPld\", \"err\", err)\n\t\treturn \"\"\n\t}\n\treturn strconv.FormatUint(ctrlPld.ReqId, 10)\n}\n\nfunc (a *Adapter) RawToMsg(b common.RawBytes) (proto.Cerealizable, error) ", "output": "{\n\treturn ctrl.NewSignedPldFromRaw(b)\n}"} {"input": "package config\n\nimport (\n\t\"github.com/mitchellh/go-homedir\"\n\t\"os\"\n)\n\nconst DB_FILE = \"davedb.db\"\n\nfunc TimeFormat() string {\n\treturn \"Monday, 2 Jan 2006\"\n}\n\n\n\nfunc DbPath() string ", "output": "{\n\thomeDir, _ := homedir.Dir()\n\treturn homeDir + string(os.PathSeparator) + DB_FILE\n}"} {"input": "package midi\n\nimport \"fmt\"\n\ntype Track struct {\n\tevents []Event\n}\n\nfunc (t *Track) Events() []Event {\n\treturn t.events\n}\n\nfunc (t *Track) String() string {\n\treturn fmt.Sprintf(\n\t\t\"Track [Events=%v]\",\n\t\tt.Events())\n}\n\n\n\nfunc NewTrack(e []Event) *Track ", "output": "{\n\treturn &Track{e}\n}"} {"input": "package keyseq\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestTrie(t *testing.T) {\n\ttrie := NewTrie()\n\tfor i := 1; i <= 5; i++ {\n\t\ttrie.Put(KeyList{Key{0, 0, rune(i)}}, 111*i)\n\t}\n\n\tnodes := Children(trie.Root())\n\tfor i := 0; i < 5; i++ {\n\t\tcheckTrieNode(t, nodes[i], Key{0, 0, rune(i + 1)}, 111*(i+1))\n\t}\n\n\tif s := trie.Size(); s != 5 {\n\t\tt.Errorf(\"trie.Size() returns not 5: %d\", s)\n\t}\n}\n\nfunc TestNotFound(t *testing.T) {\n\ttrie := NewTrie()\n\tif trie.Get(Key{999, 999, 'a'}) != nil {\n\t\tt.Errorf(\"found 'not_exist' in empty trie\")\n\t}\n}\n\nfunc checkTrieNode(t *testing.T, n Node, k Key, value int) ", "output": "{\n\tif n == nil {\n\t\tt.Fatal(\"TrieNode is null\")\n\t}\n\tif l := n.Label(); l != k {\n\t\tt.Errorf(\"TrieNode.Label() expected:'%c' actual:'%c'\", k, l)\n\t}\n\tif v := n.Value().(int); v != value {\n\t\tt.Errorf(\"TrieNode.Value() expected:%d actual:%d\", value, v)\n\t}\n}"} {"input": "package polymorphichelpers\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tapi \"k8s.io/kubernetes/pkg/apis/core\"\n\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n)\n\nfunc portsForObject(object runtime.Object) ([]string, error) {\n\tswitch t := object.(type) {\n\tcase *api.ReplicationController:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\tcase *api.Pod:\n\t\treturn getPorts(t.Spec), nil\n\tcase *api.Service:\n\t\treturn getServicePorts(t.Spec), nil\n\tcase *extensions.Deployment:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\tcase *extensions.ReplicaSet:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"cannot extract ports from %T\", object)\n\t}\n}\n\nfunc getPorts(spec api.PodSpec) []string {\n\tresult := []string{}\n\tfor _, container := range spec.Containers {\n\t\tfor _, port := range container.Ports {\n\t\t\tresult = append(result, strconv.Itoa(int(port.ContainerPort)))\n\t\t}\n\t}\n\treturn result\n}\n\n\n\n\nfunc getServicePorts(spec api.ServiceSpec) []string ", "output": "{\n\tresult := []string{}\n\tfor _, servicePort := range spec.Ports {\n\t\tresult = append(result, strconv.Itoa(int(servicePort.Port)))\n\t}\n\treturn result\n}"} {"input": "package testutil\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\ntype Context struct {\n\tName string `yaml:\"name,omitempty\"`\n\tContext struct {\n\t\tNamespace string `yaml:\"namespace,omitempty\"`\n\t} `yaml:\"context,omitempty\"`\n}\n\n\nfunc (c *Context) Ns(ns string) *Context { c.Context.Namespace = ns; return c }\n\ntype Kubeconfig map[string]interface{}\n\nfunc KC() *Kubeconfig {\n\treturn &Kubeconfig{\n\t\t\"apiVersion\": \"v1\",\n\t\t\"kind\": \"Config\"}\n}\n\nfunc (k *Kubeconfig) Set(key string, v interface{}) *Kubeconfig { (*k)[key] = v; return k }\nfunc (k *Kubeconfig) WithCurrentCtx(s string) *Kubeconfig { (*k)[\"current-context\"] = s; return k }\nfunc (k *Kubeconfig) WithCtxs(c ...*Context) *Kubeconfig { (*k)[\"contexts\"] = c; return k }\n\nfunc (k *Kubeconfig) ToYAML(t *testing.T) string {\n\tt.Helper()\n\tvar v strings.Builder\n\tif err := yaml.NewEncoder(&v).Encode(*k); err != nil {\n\t\tt.Fatalf(\"failed to encode mock kubeconfig: %v\", err)\n\t}\n\treturn v.String()\n}\n\nfunc Ctx(name string) *Context ", "output": "{ return &Context{Name: name} }"} {"input": "package app\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/fragmenta/assets\"\n\t\"github.com/fragmenta/server/config\"\n\t\"github.com/fragmenta/server/log\"\n\t\"github.com/fragmenta/view\"\n\n\t\"github.com/bitcubate/cryptojournal/src/lib/helpers\"\n)\n\n\nfunc SetupAssets() {\n\tdefer log.Time(time.Now(), log.V{\"msg\": \"Finished loading assets\"})\n\n\tassetsCompiled := config.GetBool(\"assets_compiled\")\n\n\tappAssets = assets.New(assetsCompiled)\n\n\tif config.Production() {\n\t\terr := appAssets.Load()\n\t\tif err != nil {\n\t\t\tlog.Info(log.V{\"msg\": \"Compiling Asssets\"})\n\t\t\terr := appAssets.Compile(\"src\", \"public\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(log.V{\"a\": \"unable to compile assets\", \"error\": err})\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlog.Info(log.V{\"msg\": \"Compiling Asssets in dev mode\"})\n\t\terr := appAssets.Compile(\"src\", \"public\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(log.V{\"a\": \"unable to compile assets\", \"error\": err})\n\t\t}\n\t}\n\n\tview.Helpers[\"style\"] = appAssets.StyleLink\n\tview.Helpers[\"script\"] = appAssets.ScriptLink\n\n}\n\n\n\n\nfunc SetupView() ", "output": "{\n\tdefer log.Time(time.Now(), log.V{\"msg\": \"Finished loading templates\"})\n\n\tview.Helpers[\"markup\"] = helpers.Markup\n\tview.Helpers[\"timeago\"] = helpers.TimeAgo\n\tview.Helpers[\"root_url\"] = helpers.RootURL\n\tview.Helpers[\"getimg\"] = helpers.GetImg\n\n\n\tview.Production = config.Production()\n\terr := view.LoadTemplates()\n\tif err != nil {\n\t\tlog.Fatal(log.V{\"msg\": \"unable to read templates\", \"error\": err})\n\t\tos.Exit(1)\n\t}\n\n}"} {"input": "package yaml\n\nimport (\n\t\"fmt\"\n)\n\nfunc (this *Job) Name() JobKey {\n\treturn this.name\n}\n\nfunc (this *Job) Validate(c Context) error {\n\treturn nil\n}\n\nfunc (this *Job) InDesiredState(c Context) (bool, error) {\n\treturn true, nil\n}\n\nfunc (this *Job) Prepare(c Context) error {\n\treturn nil\n}\n\nfunc (this *Job) Execute(c Context) error {\n\tc.log(\"Executing Job %s\", this.name)\n\n\treturn nil\n}\n\nfunc (this *Job) Finish(c Context) error {\n\treturn nil\n}\n\n\n\nfunc (this *Job) get_task() *task ", "output": "{\n\tif this.task == nil {\n\t\tthis.task = alloc_task(this)\n\t\tthis.task.description = fmt.Sprintf(\"Job[%s]\", this.name)\n\n\t\tfor _, container := range this.container_instances {\n\t\t\tthis.task.DependsOn(container.get_task())\n\t\t}\n\t}\n\treturn this.task\n}"} {"input": "package toJson\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc WriteToJson(w http.ResponseWriter, obj interface{}) error {\n\treturn WriteToJsonWithCode(w, obj, http.StatusOK)\n}\n\nfunc WriteToJsonWithCode(w http.ResponseWriter, obj interface{}, code int) error {\n\to, err := ToJson(obj)\n\tif err != nil {\n\t\twriteError(err)\n\t\treturn err\n\t}\n\n\twrapped := map[string]interface{}{\"result\": o}\n\n\treturn WriteJson(w, &wrapped, code)\n}\n\nfunc WriteToJsonNotWrapped(w http.ResponseWriter, obj interface{}) error {\n\treturn WriteToJsonNotWrappedWithCode(w, obj, http.StatusOK)\n}\n\nfunc WriteToJsonNotWrappedWithCode(w http.ResponseWriter, obj interface{}, code int) error {\n\to, err := ToJson(obj)\n\tif err != nil {\n\t\twriteError(err)\n\t\treturn err\n\t}\n\n\treturn WriteJson(w, &o, code)\n}\n\n\n\nfunc WriteJson(w http.ResponseWriter, obj interface{}, code int) error ", "output": "{\n\tmarshalled, err := json.MarshalIndent(obj, \"\", \" \")\n\tif err != nil {\n\t\twriteError(err)\n\t\treturn err\n\t}\n\n\tdata := []byte(fmt.Sprintf(\"%s\\n\", marshalled))\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.Header().Set(\"Content-Length\", fmt.Sprint(len(data)))\n\tw.WriteHeader(code)\n\tw.Write(data)\n\n\treturn nil\n}"} {"input": "package web\n\nimport (\n\t\"net/http\"\n\t\"text/template\"\n\n\t\"github.com/jamiefdhurst/journal/pkg/controller\"\n)\n\n\ntype BadRequest struct {\n\tcontroller.Super\n}\n\n\n\n\n\nfunc RunBadRequest(response http.ResponseWriter, request *http.Request, container interface{}) {\n\terrorController := BadRequest{}\n\terrorController.Init(container, []string{})\n\terrorController.Run(response, request)\n}\n\nfunc (c *BadRequest) Run(response http.ResponseWriter, request *http.Request) ", "output": "{\n\tresponse.WriteHeader(http.StatusNotFound)\n\n\ttemplate, _ := template.ParseFiles(\n\t\t\"./web/templates/_layout/default.tmpl\",\n\t\t\"./web/templates/error.tmpl\")\n\ttemplate.ExecuteTemplate(response, \"layout\", c)\n}"} {"input": "package cbor\n\ntype Encoder struct{}\n\n\n\n\nfunc (e Encoder) AppendKey(dst []byte, key string) []byte ", "output": "{\n\tif len(dst) < 1 {\n\t\tdst = e.AppendBeginMarker(dst)\n\t}\n\treturn e.AppendString(dst, key)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/unrolled/render\"\n)\n\n\nvar Render *render.Render\n\n\n\n\nfunc index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Welcome to the home page!\")\n}\n\nfunc apiHandler(w http.ResponseWriter, r *http.Request) {\n\tRender.JSON(w, http.StatusOK, \"Welcome to the api hander page!\")\n}\n\nfunc apiKeyHandler(w http.ResponseWriter, r *http.Request) {\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the api Key hander page! %s\", id)\n}\n\nfunc apiKeyDetailsHandler(w http.ResponseWriter, r *http.Request) {\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the api Key Details hander page! %s\", id)\n}\n\nfunc webKeyHandler(w http.ResponseWriter, r *http.Request) {\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the web Key hander page! %s\", id)\n}\n\nfunc notFound(w http.ResponseWriter, r *http.Request) {\n\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n}\n\nfunc init() ", "output": "{\n\tRender = render.New(render.Options{\n\t\tIndentJSON: true,\n\t})\n}"} {"input": "package endpoints\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tapierrs \"k8s.io/apimachinery/pkg/api/errors\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\tclientset \"k8s.io/client-go/kubernetes\"\n\t\"k8s.io/kubernetes/test/e2e/framework\"\n\te2elog \"k8s.io/kubernetes/test/e2e/framework/log\"\n)\n\nconst (\n\tregisterTimeout = time.Minute\n)\n\n\n\n\nfunc WaitForEndpoint(c clientset.Interface, ns, name string) error ", "output": "{\n\tfor t := time.Now(); time.Since(t) < registerTimeout; time.Sleep(framework.Poll) {\n\t\tendpoint, err := c.CoreV1().Endpoints(ns).Get(name, metav1.GetOptions{})\n\t\tif apierrs.IsNotFound(err) {\n\t\t\te2elog.Logf(\"Endpoint %s/%s is not ready yet\", ns, name)\n\t\t\tcontinue\n\t\t}\n\t\tframework.ExpectNoError(err, \"Failed to get endpoints for %s/%s\", ns, name)\n\t\tif len(endpoint.Subsets) == 0 || len(endpoint.Subsets[0].Addresses) == 0 {\n\t\t\te2elog.Logf(\"Endpoint %s/%s is not ready yet\", ns, name)\n\t\t\tcontinue\n\t\t}\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"failed to get endpoints for %s/%s\", ns, name)\n}"} {"input": "package rpc\n\nimport (\n\t\"fmt\"\n\t\"github.com/golang/glog\"\n\t\"github.com/nebulaim/telegramd/baselib/grpc_util\"\n\t\"github.com/nebulaim/telegramd/baselib/logger\"\n\t\"github.com/nebulaim/telegramd/proto/mtproto\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\nfunc (s *ChannelsServiceImpl) ChannelsEditAbout(ctx context.Context, request *mtproto.TLChannelsEditAbout) (*mtproto.Bool, error) ", "output": "{\n\tmd := grpc_util.RpcMetadataFromIncoming(ctx)\n\tglog.Infof(\"ChannelsEditAbout - metadata: %s, request: %s\", logger.JsonDebugData(md), logger.JsonDebugData(request))\n\n\n\treturn nil, fmt.Errorf(\"Not impl ChannelsEditAbout\")\n}"} {"input": "package naivecheap\n\nimport \"github.com/ffloyd/evergrid-go/global/types\"\n\ntype byPriceAsc []types.WorkerInfo\n\nfunc (sw byPriceAsc) Len() int {\n\treturn len(sw)\n}\n\nfunc (sw byPriceAsc) Swap(i, j int) {\n\tsw[i], sw[j] = sw[j], sw[i]\n}\n\nfunc (sw byPriceAsc) Less(i, j int) bool {\n\treturn sw[i].PricePerTick < sw[j].PricePerTick \n}\n\ntype byQueueAsc []types.WorkerInfo\n\nfunc (sw byQueueAsc) Len() int {\n\treturn len(sw)\n}\n\nfunc (sw byQueueAsc) Swap(i, j int) {\n\tsw[i], sw[j] = sw[j], sw[i]\n}\n\n\n\nfunc (sw byQueueAsc) Less(i, j int) bool ", "output": "{\n\treturn sw[i].QueueLength < sw[j].QueueLength \n}"} {"input": "package build\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/kubecfg\"\n\t\"github.com/openshift/origin/pkg/build/api\"\n)\n\nvar buildColumns = []string{\"Name\", \"Type\", \"Status\", \"Pod Name\"}\nvar buildConfigColumns = []string{\"Name\", \"Type\", \"SourceURI\"}\n\n\n\nfunc RegisterPrintHandlers(printer *kubecfg.HumanReadablePrinter) {\n\tprinter.Handler(buildColumns, printBuild)\n\tprinter.Handler(buildColumns, printBuildList)\n\tprinter.Handler(buildConfigColumns, printBuildConfig)\n\tprinter.Handler(buildConfigColumns, printBuildConfigList)\n}\n\nfunc printBuild(build *api.Build, w io.Writer) error {\n\t_, err := fmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\\n\", build.Name, build.Parameters.Strategy.Type, build.Status, build.PodName)\n\treturn err\n}\n\n\n\nfunc printBuildConfig(bc *api.BuildConfig, w io.Writer) error {\n\t_, err := fmt.Fprintf(w, \"%s\\t%v\\t%s\\n\", bc.Name, bc.Parameters.Strategy.Type, bc.Parameters.Source.Git.URI)\n\treturn err\n}\n\nfunc printBuildConfigList(buildList *api.BuildConfigList, w io.Writer) error {\n\tfor _, buildConfig := range buildList.Items {\n\t\tif err := printBuildConfig(&buildConfig, w); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc printBuildList(buildList *api.BuildList, w io.Writer) error ", "output": "{\n\tfor _, build := range buildList.Items {\n\t\tif err := printBuild(&build, w); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package req\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n)\n\ntype execChans struct {\n\tOut chan ResponseInfo\n\tErrs chan error\n\tDone chan bool\n}\n\ntype scenarioExecutor interface {\n\texecute(scen RequestScenario, chans execChans)\n}\n\n\n\nfunc execScenario(scen RequestScenario, chans execChans) {\n\tif len(scen.Bots) == 0 {\n\t\texecScenarioLocally(scen, chans)\n\t} else {\n\t\texecScenarioDistributed(scen, chans)\n\t}\n}\n\nfunc explainScenario(scen RequestScenario) error {\n\tvar data []byte\n\tvar err error\n\n\tif options.Pretty {\n\t\tdata, err = json.MarshalIndent(scen, \"\", \" \")\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to format %v to json: %v\", scen, err)\n\t}\n\n\tlog.Printf(\"Executing scenario:\\n%v\\n==================\\n\\n\", string(data))\n\n\treturn nil\n}\n\nfunc printResponse(res ResponseInfo, writer io.Writer) error {\n\tvar data []byte\n\tvar err error\n\n\tif options.Pretty {\n\t\tdata, err = json.MarshalIndent(res, \"\", \" \")\n\t} else {\n\t\tdata, err = json.Marshal(res)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to format %v to json: %v\", res, err)\n\t}\n\t_, err = writer.Write(append(data, '\\n'))\n\treturn err\n}\n\nfunc Execute(scen RequestScenario, writer io.Writer) error ", "output": "{\n\n\tsetOptions(scen.Options)\n\n\texplainScenario(scen)\n\n\tchans := execChans{\n\t\tOut: make(chan ResponseInfo),\n\t\tErrs: make(chan error),\n\t\tDone: make(chan bool),\n\t}\n\texecScenario(scen, chans)\n\n\tfor {\n\t\tselect {\n\t\tcase res := <-chans.Out:\n\t\t\tif err := printResponse(res, writer); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase err := <-chans.Errs:\n\t\t\treturn err\n\t\tcase <-chans.Done:\n\t\t\treturn nil\n\t\t}\n\t}\n}"} {"input": "package aws\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/aws/aws-sdk-go/service/outposts\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/v2/terraform\"\n)\n\nfunc TestAccAWSOutpostsSitesDataSource_basic(t *testing.T) {\n\tdataSourceName := \"data.aws_outposts_sites.test\"\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsSites(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: nil,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSOutpostsSitesDataSourceConfig(),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckOutpostsSitesAttributes(dataSourceName),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckOutpostsSitesAttributes(dataSourceName string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[dataSourceName]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", dataSourceName)\n\t\t}\n\n\t\tif v := rs.Primary.Attributes[\"ids.#\"]; v == \"0\" {\n\t\t\treturn fmt.Errorf(\"expected at least one ids result, got none\")\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\n\n\nfunc testAccAWSOutpostsSitesDataSourceConfig() string {\n\treturn `\ndata \"aws_outposts_sites\" \"test\" {}\n`\n}\n\nfunc testAccPreCheckAWSOutpostsSites(t *testing.T) ", "output": "{\n\tconn := testAccProvider.Meta().(*AWSClient).outpostsconn\n\n\tinput := &outposts.ListSitesInput{}\n\n\toutput, err := conn.ListSites(input)\n\n\tif testAccPreCheckSkipError(err) {\n\t\tt.Skipf(\"skipping acceptance testing: %s\", err)\n\t}\n\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected PreCheck error: %s\", err)\n\t}\n\n\tif output == nil || len(output.Sites) == 0 {\n\t\tt.Skip(\"skipping since no Sites Outpost found\")\n\t}\n}"} {"input": "package spark\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\nvar httpClient *http.Client\n\nfunc init() {\n\thttpClient = &http.Client{}\n}\n\nfunc (s *Spark) request(req *http.Request) ([]byte, error) {\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", s.token))\n\treq.Header.Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\n\tres, err := httpClient.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer res.Body.Close()\n\tbs, err := ioutil.ReadAll(res.Body)\n\n\tif res.StatusCode != http.StatusOK {\n\t\tif res.StatusCode != 204 {\n\t\t\te := fmt.Sprintf(\"HTTP Status Code: %d\\n%s\", res.StatusCode, string(bs))\n\t\t\treturn nil, errors.New(e)\n\t\t}\n\t}\n\n\treturn bs, err\n}\n\nfunc (s *Spark) GetRequest(url string, uv *url.Values) ([]byte, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif uv != nil {\n\t\treq.URL.RawQuery = (*uv).Encode()\n\t}\n\treturn s.request(req)\n}\n\nfunc (s *Spark) PostRequest(url string, body *bytes.Buffer) ([]byte, error) {\n\treq, err := http.NewRequest(\"POST\", url, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.request(req)\n}\n\n\n\nfunc (s *Spark) DeleteRequest(url string) ([]byte, error) ", "output": "{\n\tfmt.Println(\"Delete url: \", url)\n\treq, err := http.NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.request(req)\n}"} {"input": "package v1\n\nimport (\n\t\"testing\"\n\n\t\"github.com/rackspace/gophercloud\"\n\t\"github.com/rackspace/gophercloud/rackspace/lb/v1/lbs\"\n\t\"github.com/rackspace/gophercloud/rackspace/lb/v1/monitors\"\n\tth \"github.com/rackspace/gophercloud/testhelper\"\n)\n\n\n\nfunc getMonitor(t *testing.T, client *gophercloud.ServiceClient, lbID int) {\n\thm, err := monitors.Get(client, lbID).Extract()\n\tth.AssertNoErr(t, err)\n\tt.Logf(\"Health monitor for LB %d: Type [%s] Delay [%d] Timeout [%d] AttemptLimit [%d]\",\n\t\tlbID, hm.Type, hm.Delay, hm.Timeout, hm.AttemptLimit)\n}\n\nfunc updateMonitor(t *testing.T, client *gophercloud.ServiceClient, lbID int) {\n\topts := monitors.UpdateHTTPMonitorOpts{\n\t\tAttemptLimit: 3,\n\t\tDelay: 10,\n\t\tTimeout: 10,\n\t\tBodyRegex: \"hello is it me you're looking for\",\n\t\tPath: \"/foo\",\n\t\tStatusRegex: \"200\",\n\t\tType: monitors.HTTP,\n\t}\n\n\terr := monitors.Update(client, lbID, opts).ExtractErr()\n\tth.AssertNoErr(t, err)\n\n\twaitForLB(client, lbID, lbs.ACTIVE)\n\tt.Logf(\"Updated monitor for LB %d\", lbID)\n}\n\nfunc deleteMonitor(t *testing.T, client *gophercloud.ServiceClient, lbID int) {\n\terr := monitors.Delete(client, lbID).ExtractErr()\n\tth.AssertNoErr(t, err)\n\n\twaitForLB(client, lbID, lbs.ACTIVE)\n\tt.Logf(\"Deleted monitor for LB %d\", lbID)\n}\n\nfunc TestMonitors(t *testing.T) ", "output": "{\n\tclient := setup(t)\n\n\tids := createLB(t, client, 1)\n\tlbID := ids[0]\n\n\tgetMonitor(t, client, lbID)\n\n\tupdateMonitor(t, client, lbID)\n\n\tdeleteMonitor(t, client, lbID)\n\n\tdeleteLB(t, client, lbID)\n}"} {"input": "package config\n\nimport (\n\t\"fmt\"\n\t\"github.com/BurntSushi/toml\"\n\t\"time\"\n)\n\nvar (\n\tConfigFile = \"config/main.toml\"\n\tAppVersion = \"1.0.0\"\n\tCfg = &Config{}\n)\n\nconst (\n\tAB_BENCH = \"/usr/bin/ab\"\n\tWRK_BENCH = \"/usr/bin/wrk\"\n\tSIEGE_BENCH = \"/usr/bin/siege\"\n)\n\n\ntype Config struct {\n\tVerbose bool\n\tHtmlOutput bool\n\tTitle string\n\tVersion string\n\tDelay time.Duration\n\tWaitToRun time.Duration\n\tTry int\n\tAb AbConfig\n\tWrk WrkConfig\n\tSiege SiegeConfig\n\tApp []AppConfig\n}\n\n\ntype AbConfig struct {\n\tBinPath string\n\tConcurency int\n\tKeepalive bool\n\tRequests int\n}\n\n\ntype WrkConfig struct {\n\tBinPath string\n\tConnections int\n\tDuration int\n\tThreads int\n}\n\n\ntype SiegeConfig struct {\n\tBinPath string\n\tConcurrent int\n\tTime int\n}\n\n\n\ntype AppConfig struct {\n\tTitle string\n\tPath string\n\tUrl string\n}\n\n\n\n\nfunc LoadConfig(file string, cliParams *Config) (*Config, error) ", "output": "{\n\tconfig := cliParams\n\tif _, err := toml.DecodeFile(file, &config); err != nil {\n\t\treturn &Config{}, fmt.Errorf(\"Failed to load config: %s\\nReason: %v\", file, err)\n\t}\n\tCfg = config\n\treturn config, nil\n}"} {"input": "package tarjan\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/gyuho/goraph/graph/gsd\"\n)\n\nfunc Test_JSON_SCC(test *testing.T) {\n\tg15 := gsd.JSONGraph(\"../../../example_files/testgraph.json\", \"testgraph.015\")\n\tresult15 := SCC(g15)\n\trc15 := \"[[H] [G F] [D C] [E B A]]\"\n\tif fmt.Sprintf(\"%v\", result15) != rc15 {\n\t\ttest.Errorf(\"Should return \\n%+v\\nbut\\n%+v\", result15, rc15)\n\t}\n\n\tg16 := gsd.JSONGraph(\"../../../example_files/testgraph.json\", \"testgraph.016\")\n\tfmt.Println(SCC(g16))\n}\n\n\n\nfunc Test_JSON_Contains(test *testing.T) ", "output": "{\n\tg15 := gsd.JSONGraph(\"../../../example_files/testgraph.json\", \"testgraph.015\")\n\ta := g15.FindVertexByID(\"A\")\n\tb := g15.FindVertexByID(\"B\")\n\tovs := a.GetOutVertices()\n\tif !Contains(b, ovs) {\n\t\ttest.Errorf(\"Should contain B in OutVertices but %+v\", Contains(b, ovs))\n\t}\n}"} {"input": "package TeleGogo\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n)\n\nfunc responseToError(response *http.Response) error {\n\treturn responseToTgError(response)\n}\n\nfunc responseToTgError(response *http.Response) TelegramError {\n\tdefer response.Body.Close()\n\ttgErr := telegramError{}\n\tjson.NewDecoder(response.Body).Decode(&tgErr)\n\treturn tgErr\n}\n\nfunc errToTelegramErr(err error) TelegramError {\n\treturn telegramError{OK: false, ErrorCode: 0, Description: err.Error()}\n}\n\ntype telegramError struct {\n\tOK bool `json:\"ok\"`\n\tErrorCode int `json:\"error_code\"`\n\tDescription string `json:\"description\"`\n}\n\n\n\nfunc (t telegramError) ErrCode() int {\n\treturn t.ErrorCode\n}\n\nfunc (t telegramError) Error() string {\n\treturn t.Description\n}\n\n\ntype TelegramError interface {\n\tIsOK() bool\n\tErrCode() int\n\tError() string\n}\n\nfunc (t telegramError) IsOK() bool ", "output": "{\n\treturn t.OK\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/kubernetes/pkg/api/validation\"\n)\n\n\n\n\n\n\n\n\nfunc GetFieldLabelConversionFunc(supportedLabels map[string]string, overrideLabels map[string]string) func(label, value string) (string, string, error) {\n\treturn func(label, value string) (string, string, error) {\n\t\tif label, overridden := overrideLabels[label]; overridden {\n\t\t\treturn label, value, nil\n\t\t}\n\t\tif _, supported := supportedLabels[label]; supported {\n\t\t\treturn label, value, nil\n\t\t}\n\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported: %s\", label)\n\t}\n}\n\nfunc GetNameValidationFunc(nameFunc validation.ValidateNameFunc) validation.ValidateNameFunc ", "output": "{\n\treturn func(name string, prefix bool) []string {\n\t\tif reasons := validation.ValidatePathSegmentName(name, prefix); len(reasons) != 0 {\n\t\t\treturn reasons\n\t\t}\n\n\t\treturn nameFunc(name, prefix)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"image\"\n\t\"testing\"\n)\n\nvar cache = NewRGBACache(2)\n\n\n\nfunc TestCache(t *testing.T) ", "output": "{\n\tim1 := image.NewRGBA(image.Rectangle{image.Point{0, 0}, image.Point{10, 10}})\n\tcache.Put(\"1234\", im1)\n\tcache.Put(\"4234\", im1)\n\tcache.Put(\"5234\", im1)\n\tif _, exists := cache.Get(\"1234\"); exists {\n\t\tt.Fatal(\"should not exists 1234\")\n\t}\n\tif im, exists := cache.Get(\"4234\"); !exists || im == nil {\n\t\tt.Fatal(\"get cache failed\")\n\t}\n}"} {"input": "package geth\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/etherite/go-etherite/core\"\n\t\"github.com/etherite/go-etherite/p2p/discv5\"\n\t\"github.com/etherite/go-etherite/params\"\n)\n\n\n\nfunc MainnetGenesis() string {\n\treturn \"\"\n}\n\n\nfunc TestnetGenesis() string {\n\tenc, err := json.Marshal(core.DefaultTestnetGenesisBlock())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(enc)\n}\n\n\nfunc RinkebyGenesis() string {\n\tenc, err := json.Marshal(core.DefaultRinkebyGenesisBlock())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(enc)\n}\n\n\n\n\n\nfunc FoundationBootnodes() *Enodes ", "output": "{\n\tnodes := &Enodes{nodes: make([]*discv5.Node, len(params.DiscoveryV5Bootnodes))}\n\tfor i, url := range params.DiscoveryV5Bootnodes {\n\t\tnodes.nodes[i] = discv5.MustParseNode(url)\n\t}\n\treturn nodes\n}"} {"input": "package leetcode\n\nconst MAX_INT32 = 1<<31 - 1\nconst MIN_INT32 = -1 << 31\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\nfunc maxInt(a, b int) int {\n\tif a < b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}\n\nfunc minInt(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}\n\nfunc absInt(num int) int {\n\tif num > 0 {\n\t\treturn num\n\t} else {\n\t\treturn -num\n\t}\n}\n\n\n\ntype Stack struct {\n\tdata []rune\n}\n\nfunc (s *Stack) push(data rune) {\n\ts.data = append(s.data, data)\n}\n\nfunc (s *Stack) pop() rune {\n\tif len(s.data) == 0 {\n\t\treturn 0\n\t}\n\tret := s.data[len(s.data)-1]\n\ts.data = s.data[:len(s.data)-1]\n\treturn ret\n}\n\nfunc (s Stack) empty() bool {\n\treturn len(s.data) == 0\n}\n\nfunc qsortInt(nums []int) []int ", "output": "{\n\tif len(nums) <= 1 {\n\t\treturn nums\n\t}\n\n\thead, tail := 0, len(nums)-1\n\tidx, mid := 1, nums[0]\n\tfor head < tail {\n\t\tif nums[idx] > mid {\n\t\t\tnums[idx], nums[tail] = nums[tail], nums[idx]\n\t\t\ttail--\n\t\t} else {\n\t\t\tnums[idx], nums[head] = nums[head], nums[idx]\n\t\t\thead++\n\t\t\tidx++\n\t\t}\n\t}\n\tnums[head] = mid\n\tqsortInt(nums[:head])\n\tqsortInt(nums[head+1:])\n\treturn nums\n}"} {"input": "package message\n\nimport \"github.com/cloustone/sentel/pkg/config\"\n\ntype Producer interface {\n\tSendMessage(msg Message) error\n\tSendMessages(msgs []Message) error\n\tClose()\n}\n\n\n\nfunc PostMessage(c config.Config, msg Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", false); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessage(msg)\n\t}\n\treturn\n}\n\nfunc PostMessages(c config.Config, msgs []Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", false); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessages(msgs)\n\t}\n\treturn\n}\n\nfunc SendMessage(c config.Config, msg Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", true); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessage(msg)\n\t}\n\treturn\n}\n\nfunc SendMessages(c config.Config, msgs []Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", true); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessages(msgs)\n\t}\n\treturn\n}\n\nfunc NewProducer(c config.Config, clientID string, sync bool) (Producer, error) ", "output": "{\n\treturn newKafkaProducer(c, clientID, sync)\n}"} {"input": "package api\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/google/gapid/core/data/id\"\n\t\"github.com/google/gapid/core/image\"\n\t\"github.com/google/gapid/gapil/constset\"\n)\n\n\ntype API interface {\n\tName() string\n\n\tIndex() uint8\n\n\tID() ID\n\n\tConstantSets() *constset.Pack\n\n\tGetFramebufferAttachmentInfo(\n\t\tctx context.Context,\n\t\tafter []uint64,\n\t\tstate *GlobalState,\n\t\tthread uint64,\n\t\tattachment FramebufferAttachment) (width, height, index uint32, format *image.Format, err error)\n\n\tContext(state *GlobalState, thread uint64) Context\n\n\tCreateCmd(name string) Cmd\n}\n\n\ntype ID id.ID\n\n\nfunc (i ID) IsValid() bool { return id.ID(i).IsValid() }\n\n\n\ntype APIObject interface {\n\tAPI() API\n}\n\nvar apis = map[ID]API{}\nvar indices = map[uint8]bool{}\n\n\n\nfunc Register(api API) {\n\tid := api.ID()\n\tif _, present := apis[id]; present {\n\t\tpanic(fmt.Errorf(\"API %s registered more than once\", id))\n\t}\n\tapis[id] = api\n\n\tindex := api.Index()\n\tif _, present := indices[index]; present {\n\t\tpanic(fmt.Errorf(\"API %s used an occupied index %d\", id, index))\n\t}\n\tindices[index] = true\n}\n\n\n\nfunc Find(id ID) API {\n\treturn apis[id]\n}\n\nfunc (i ID) String() string ", "output": "{ return id.ID(i).String() }"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification struct {\n\n\tPredefinedScalingMetricType string `json:\"PredefinedScalingMetricType,omitempty\"`\n\n\tResourceLabel string `json:\"ResourceLabel,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) AWSCloudFormationType() string {\n\treturn \"AWS::AutoScalingPlans::ScalingPlan.PredefinedScalingMetricSpecification\"\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\n\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetMetadata(metadata map[string]interface{}) ", "output": "{\n\tr._metadata = metadata\n}"} {"input": "package opts\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype List struct {\n\tArgs []string\n}\n\n\n\nfunc (lo List) Get() []string {\n\treturn lo.Args\n}\n\nfunc (lo List) String() string {\n\treturn fmt.Sprintf(\"[%s]\", strings.Join(lo.Args, \", \"))\n}\n\nfunc (lo *List) Set(arg string) error ", "output": "{\n\tlo.Args = append(lo.Args[:], arg)\n\treturn nil\n}"} {"input": "package filehash\n\nimport (\n\t\"crypto/sha1\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/cloudfoundry/gofileutils/fileutils\"\n)\n\ntype Hash []byte\n\nfunc Zero() Hash {\n\treturn Hash(make([]byte, sha1.Size))\n}\n\n\nfunc New(filePath string) Hash {\n\tfileInfo, err := os.Lstat(filePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif fileInfo.IsDir() {\n\t\tpanic(\"cannot compute hash of directory\")\n\t} else {\n\t\thash := sha1.New()\n\t\terr = fileutils.CopyPathToWriter(filePath, hash)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn Hash(hash.Sum(nil))\n\t}\n}\n\n\n\nfunc StringToHash(s string) Hash {\n\tvar sh string\n\tif _, err := fmt.Sscanf(s, \"%x\", &sh); err != nil {\n\t\tpanic(err)\n\t}\n\treturn Hash(sh)\n}\n\nfunc (h1 Hash) Combine(h2 Hash) {\n\tif len(h1) != len(h2) {\n\t\tpanic(\"Invalid hash length\")\n\t}\n\tfor i, b := range h1 {\n\t\th1[i] = b ^ h2[i]\n\t}\n}\n\nfunc (h1 Hash) Remove(h2 Hash) {\n\th1.Combine(h2)\n}\n\nfunc (k Hash) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%x\", string(k))\n}"} {"input": "package sml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/sml\"\n)\n\nfunc TestCT_WorkbookProtectionConstructor(t *testing.T) {\n\tv := sml.NewCT_WorkbookProtection()\n\tif v == nil {\n\t\tt.Errorf(\"sml.NewCT_WorkbookProtection must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed sml.CT_WorkbookProtection should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestCT_WorkbookProtectionMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := sml.NewCT_WorkbookProtection()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := sml.NewCT_WorkbookProtection()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/config\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdGetJSONConfig{\n\t\tname: \"get_json_section\",\n\t\trpcMethod: utils.ConfigSv1GetConfig,\n\t\trpcParams: &config.SectionWithOpts{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetJSONConfig struct {\n\tname string\n\trpcMethod string\n\trpcParams *config.SectionWithOpts\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetJSONConfig) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdGetJSONConfig) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdGetJSONConfig) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &config.SectionWithOpts{Opts: make(map[string]interface{})}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetJSONConfig) PostprocessRpcParams() error {\n\treturn nil\n}\n\n\n\nfunc (self *CmdGetJSONConfig) RpcResult() interface{} ", "output": "{\n\tvar s map[string]interface{}\n\treturn &s\n}"} {"input": "package llvm\n\n\nimport \"C\"\n\nimport (\n\t\"errors\"\n\t\"unsafe\"\n)\n\n\n\nfunc LoadLibraryPermanently(lib string) error {\n\tvar errstr *C.char\n\tlibstr := C.CString(lib)\n\tdefer C.free(unsafe.Pointer(libstr))\n\tC.LLVMLoadLibraryPermanently2(libstr, &errstr)\n\tif errstr != nil {\n\t\terr := errors.New(C.GoString(errstr))\n\t\tC.LLVMFree(unsafe.Pointer(errstr))\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc ParseCommandLineOptions(args []string, overview string) ", "output": "{\n\targstrs := make([]*C.char, len(args))\n\tfor i, arg := range args {\n\t\targstrs[i] = C.CString(arg)\n\t\tdefer C.free(unsafe.Pointer(argstrs[i]))\n\t}\n\toverviewstr := C.CString(overview)\n\tdefer C.free(unsafe.Pointer(overviewstr))\n\tC.LLVMParseCommandLineOptions(C.int(len(args)), &argstrs[0], overviewstr)\n}"} {"input": "package storage\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"testing\"\n)\n\n\n\nfunc TestResumeUploadPutFile(t *testing.T) ", "output": "{\n\tvar putRet PutRet\n\tctx := context.TODO()\n\tputPolicy := PutPolicy{\n\t\tScope: testBucket,\n\t\tDeleteAfterDays: 7,\n\t}\n\tupToken := putPolicy.UploadToken(mac)\n\ttestKey := fmt.Sprintf(\"testRPutFileKey_%d\", rand.Int())\n\n\terr := resumeUploader.PutFile(ctx, &putRet, upToken, testKey, testLocalFile, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"ResumeUploader#PutFile() error, %s\", err)\n\t}\n\tt.Logf(\"Key: %s, Hash:%s\", putRet.Key, putRet.Hash)\n}"} {"input": "package kegg\n\nimport (\n\t\"fmt\"\n)\n\nfunc ExampleConvert() {\n\tdrugID, err := New().Convert(\"pubchem\", \"drug\", \"313046637\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(drugID)\n}\n\n\n\nfunc ExampleFind() {\n\tmatch, err := New().Find(\"drug\", \"D00341\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(match != \"\")\n}\n\nfunc ExampleLink() {\n\tcompoundID, err := New().Link(\"drug\", \"compound\", \"D00341\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(compoundID)\n}\n\nfunc ExampleGet() ", "output": "{\n\tinfo, err := New().Get(\"drug\", \"D00341\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(info != \"\")\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1beta1 \"k8s.io/metrics/pkg/client/clientset_generated/clientset/typed/metrics/v1beta1\"\n)\n\ntype FakeMetricsV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeMetricsV1beta1) NodeMetricses() v1beta1.NodeMetricsInterface {\n\treturn &FakeNodeMetricses{c}\n}\n\nfunc (c *FakeMetricsV1beta1) PodMetricses(namespace string) v1beta1.PodMetricsInterface {\n\treturn &FakePodMetricses{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeMetricsV1beta1) RESTClient() rest.Interface ", "output": "{\n\tvar ret *rest.RESTClient\n\treturn ret\n}"} {"input": "package controller \n\nimport (\n\t\"net/url\"\n\t\"testing\"\n\n\t\"github.com/docker/infrakit/pkg/spi/stack\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\nfunc fakeLeader(v bool) func() stack.Leadership {\n\treturn func() stack.Leadership { return fakeLeaderT(v) }\n}\n\ntype fakeLeaderT bool\n\n\n\nfunc (f fakeLeaderT) LeaderLocation() (*url.URL, error) {\n\treturn nil, nil\n}\n\nfunc TestSingleton(t *testing.T) {\n\n\tcall1 := make(chan int, 1)\n\tsingleton1 := Singleton(fake(call1), fakeLeader(true))\n\n\t_, err := singleton1.Describe(nil)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, <-call1)\n\n\tcall2 := make(chan int, 1)\n\tsingleton2 := Singleton(fake(call2), fakeLeader(false))\n\n\t_, err = singleton2.Describe(nil)\n\trequire.Error(t, err)\n\trequire.Equal(t, \"not a leader\", err.Error())\n\n\tclose(call1)\n\tclose(call2)\n}\n\nfunc (f fakeLeaderT) IsLeader() (bool, error) ", "output": "{\n\treturn bool(f), nil\n}"} {"input": "package jobs\n\nimport (\n\t\"fmt\"\n\t\"github.com/nubleer/revel\"\n\t\"github.com/nubleer/revel/modules/jobs/app/jobs\"\n\t\"github.com/nubleer/revel/samples/booking/app/controllers\"\n\t\"github.com/nubleer/revel/samples/booking/app/models\"\n)\n\n\ntype BookingCounter struct{}\n\nfunc (c BookingCounter) Run() {\n\tbookings, err := controllers.Dbm.Select(models.Booking{},\n\t\t`select * from Booking`)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"There are %d bookings.\\n\", len(bookings))\n}\n\n\n\nfunc init() ", "output": "{\n\trevel.OnAppStart(func() {\n\t\tjobs.Schedule(\"@every 1m\", BookingCounter{})\n\t})\n}"} {"input": "package client_test\n\nimport (\n\t\"github.com/jdextraze/go-gesclient/client\"\n\t\"testing\"\n)\n\nfunc TestWrongExpectedVersion_Error(t *testing.T) {\n\tif client.WrongExpectedVersion.Error() != \"Wrong expected version\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestStreamDeleted_Error(t *testing.T) {\n\tif client.StreamDeleted.Error() != \"Stream deleted\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestInvalidTransaction_Error(t *testing.T) {\n\tif client.InvalidTransaction.Error() != \"Invalid transaction\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestAccessDenied_Error(t *testing.T) {\n\tif client.AccessDenied.Error() != \"Access denied\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestAuthenticationError_Error(t *testing.T) {\n\tif client.AuthenticationError.Error() != \"Authentication error\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestBadRequest_Error(t *testing.T) {\n\tif client.BadRequest.Error() != \"Bad request\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestServerError_Error(t *testing.T) {\n\terr := client.NewServerError(\"\")\n\tif err.Error() != \"Unexpected error on server: \" {\n\t\tt.FailNow()\n\t}\n\n\terr = client.NewServerError(\"test\")\n\tif err.Error() != \"Unexpected error on server: test\" {\n\t\tt.FailNow()\n\t}\n}\n\n\n\nfunc TestNotModified_Error(t *testing.T) ", "output": "{\n\terr := client.NewNotModified(\"test\")\n\tif err.Error() != \"Stream not modified: test\" {\n\t\tt.FailNow()\n\t}\n}"} {"input": "package digits\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\n\nfunc testServer() (*http.Client, *http.ServeMux, *httptest.Server) {\n\tmux := http.NewServeMux()\n\tserver := httptest.NewServer(mux)\n\ttransport := &RewriteTransport{&http.Transport{\n\t\tProxy: func(req *http.Request) (*url.URL, error) {\n\t\t\treturn url.Parse(server.URL)\n\t\t},\n\t}}\n\tclient := &http.Client{Transport: transport}\n\treturn client, mux, server\n}\n\n\n\ntype RewriteTransport struct {\n\tTransport http.RoundTripper\n}\n\n\n\nfunc (t *RewriteTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq.URL.Scheme = \"http\"\n\tif t.Transport == nil {\n\t\treturn http.DefaultTransport.RoundTrip(req)\n\t}\n\treturn t.Transport.RoundTrip(req)\n}\n\n\nfunc assertMethod(t *testing.T, expectedMethod string, req *http.Request) {\n\tassert.Equal(t, expectedMethod, req.Method)\n}\n\n\n\n\nfunc assertQuery(t *testing.T, expected map[string]string, req *http.Request) ", "output": "{\n\tqueryValues := req.URL.Query()\n\texpectedValues := url.Values{}\n\tfor key, value := range expected {\n\t\texpectedValues.Add(key, value)\n\t}\n\tassert.Equal(t, expectedValues, queryValues)\n}"} {"input": "package remote\n\nimport (\n\t\"github.com/AsynkronIT/protoactor-go/actor\"\n)\n\ntype process struct {\n\tpid *actor.PID\n\tremote *Remote\n}\n\nfunc newProcess(pid *actor.PID, r *Remote) actor.Process {\n\treturn &process{\n\t\tpid: pid,\n\t\tremote: r,\n\t}\n}\n\nfunc (ref *process) SendUserMessage(pid *actor.PID, message interface{}) {\n\theader, msg, sender := actor.UnwrapEnvelope(message)\n\tref.remote.SendMessage(pid, header, msg, sender, -1)\n}\n\nfunc (ref *process) SendSystemMessage(pid *actor.PID, message interface{}) {\n\n\tswitch msg := message.(type) {\n\tcase *actor.Watch:\n\t\trw := &remoteWatch{\n\t\t\tWatcher: msg.Watcher,\n\t\t\tWatchee: pid,\n\t\t}\n\t\tref.remote.edpManager.remoteWatch(rw)\n\tcase *actor.Unwatch:\n\t\truw := &remoteUnwatch{\n\t\t\tWatcher: msg.Watcher,\n\t\t\tWatchee: pid,\n\t\t}\n\t\tref.remote.edpManager.remoteUnwatch(ruw)\n\tdefault:\n\t\tref.remote.SendMessage(pid, nil, message, nil, -1)\n\t}\n}\n\n\n\nfunc (ref *process) Stop(pid *actor.PID) ", "output": "{\n\tref.SendSystemMessage(pid, stopMessage)\n}"} {"input": "package ray\n\nimport (\n\t\"github.com/v2ray/v2ray-core/common/alloc\"\n)\n\nconst (\n\tbufferSize = 128\n)\n\n\nfunc NewRay() Ray {\n\treturn &directRay{\n\t\tInput: make(chan *alloc.Buffer, bufferSize),\n\t\tOutput: make(chan *alloc.Buffer, bufferSize),\n\t}\n}\n\ntype directRay struct {\n\tInput chan *alloc.Buffer\n\tOutput chan *alloc.Buffer\n}\n\nfunc (this *directRay) OutboundInput() <-chan *alloc.Buffer {\n\treturn this.Input\n}\n\nfunc (this *directRay) OutboundOutput() chan<- *alloc.Buffer {\n\treturn this.Output\n}\n\n\n\nfunc (this *directRay) InboundOutput() <-chan *alloc.Buffer {\n\treturn this.Output\n}\n\nfunc (this *directRay) InboundInput() chan<- *alloc.Buffer ", "output": "{\n\treturn this.Input\n}"} {"input": "package testing\n\nimport (\n\t\"time\"\n\n\t\"github.com/zinic/protobus/bus\"\n\t\"github.com/zinic/protobus/concurrent\"\n)\n\n\n\ntype InjectorSource struct {\n\tevent bus.Event\n\trunning concurrent.ReferenceLocker\n\tinterval time.Duration\n}\n\nfunc (injector *InjectorSource) Start(outgoing chan<- bus.Event, actx bus.ActorContext) (err error) {\n\tinjector.running.Set(true)\n\n\tvar elapsedNanos int64 = 0\n\tfor injector.running.Get().(bool) {\n\t\tthen := time.Now()\n\n\t\tif elapsedNanos >= injector.interval.Nanoseconds() {\n\t\t\telapsedNanos = 0\n\t\t\toutgoing <- injector.event\n\t\t}\n\n\t\ttime.Sleep(1 * time.Millisecond)\n\t\telapsedNanos += time.Now().Sub(then).Nanoseconds()\n\t}\n\n\treturn\n}\n\nfunc (injector *InjectorSource) Stop() (err error) {\n\tinjector.running.Set(false)\n\treturn\n}\n\nfunc NewInjector(event bus.Event, interval time.Duration) (injector bus.Source) ", "output": "{\n\treturn &InjectorSource {\n\t\tevent: event,\n\t\trunning: concurrent.NewReferenceLocker(false),\n\t\tinterval: interval,\n\t}\n}"} {"input": "package config\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/THUNDERGROOVE/SDETool/args\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\nvar Conf Config\n\n\ntype Config struct {\n\tVerboseInfo bool \n\tLicenseFlag bool \n\tVersionFlag bool \n\tSlowFlag bool \n\tTimeExecution bool \n\tDebug bool \n}\n\n\n\nfunc fcheck() {\n\tif _, err := os.Stat(\"SDETool.config\"); os.IsNotExist(err) {\n\t\tc := Config{false, false, false, false, false, false}\n\t\tj, err2 := json.Marshal(c)\n\t\tif err2 != nil {\n\t\t\tpanic(err2)\n\t\t}\n\t\tioutil.WriteFile(\"SDETool.config\", j, 0777)\n\t}\n}\n\n\nfunc LoadConfig() {\n\tfcheck()\n\tf, err1 := ioutil.ReadFile(\"SDETool.config\")\n\tif err1 != nil {\n\t\tpanic(err1)\n\t}\n\terr2 := json.Unmarshal(f, &Conf)\n\tif err2 != nil {\n\t\tpanic(err2)\n\t}\n\tif *args.VerboseInfo == false {\n\t\t*args.VerboseInfo = Conf.VerboseInfo\n\t}\n\tif *args.LicenseFlag == false {\n\t\t*args.LicenseFlag = Conf.LicenseFlag\n\t}\n\tif *args.VersionFlag == false {\n\t\t*args.VersionFlag = Conf.VersionFlag\n\t}\n\tif *args.SlowFlag == false {\n\t\t*args.SlowFlag = Conf.SlowFlag\n\t}\n\tif *args.TimeExecution == false {\n\t\t*args.TimeExecution = Conf.TimeExecution\n\t}\n\tif *args.Debug == false {\n\t\t*args.Debug = Conf.Debug\n\t}\n}\n\n\n\n\n\nfunc SaveConfig() ", "output": "{\n\tif _, err := os.Stat(\"SDETool.config\"); os.IsNotExist(err) {\n\t\treturn\n\t}\n\tif err := os.Remove(\"SDETool.config\"); err != nil {\n\t\tfmt.Println(\"Error removing old config while saving\")\n\t\treturn\n\t}\n\tif v, err := json.Marshal(Conf); err != nil {\n\t\tfmt.Println(\"Error Marshaling config\")\n\t} else {\n\t\tif err := ioutil.WriteFile(\"SDETool.config\", v, 0777); err != nil {\n\t\t\tfmt.Println(\"Error saving new config\")\n\t\t}\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"testing\"\n\n\tkubeadmapi \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm\"\n)\n\nfunc TestTokenParseErrors(t *testing.T) {\n\tinvalidTokens := []string{\n\t\t\"1234567890123456789012\",\n\t\t\"12345.1234567890123456\",\n\t\t\".1234567890123456\",\n\t\t\"123456.1234567890.123456\",\n\t}\n\n\tfor _, token := range invalidTokens {\n\t\tif _, _, err := ParseToken(token); err == nil {\n\t\t\tt.Errorf(\"generateTokenIfNeeded did not return an error for this invalid token: [%s]\", token)\n\t\t}\n\t}\n}\n\n\n\nfunc TestRandBytes(t *testing.T) {\n\tvar randTest = []int{\n\t\t0,\n\t\t1,\n\t\t2,\n\t\t3,\n\t\t100,\n\t}\n\n\tfor _, rt := range randTest {\n\t\tactual, err := RandBytes(rt)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed RandBytes: %v\", err)\n\t\t}\n\t\tif len(actual) != rt*2 {\n\t\t\tt.Errorf(\"failed RandBytes:\\n\\texpected: %d\\n\\t actual: %d\\n\", rt*2, len(actual))\n\t\t}\n\t}\n}\n\nfunc TestGenerateToken(t *testing.T) ", "output": "{\n\tvar cfg kubeadmapi.TokenDiscovery\n\n\tGenerateToken(&cfg)\n\tif len(cfg.ID) != 6 {\n\t\tt.Errorf(\"failed GenerateToken first part length:\\n\\texpected: 6\\n\\t actual: %d\", len(cfg.ID))\n\t}\n\tif len(cfg.Secret) != 16 {\n\t\tt.Errorf(\"failed GenerateToken first part length:\\n\\texpected: 16\\n\\t actual: %d\", len(cfg.Secret))\n\t}\n}"} {"input": "package testing\n\nimport (\n\t\"k8s.io/test-infra/velodrome/sql\"\n\n\t\"github.com/jinzhu/gorm\"\n\t_ \"github.com/jinzhu/gorm/dialects/sqlite\"\n)\n\n\ntype SQLiteConfig struct {\n\tFile string\n}\n\n\n\n\nfunc (config *SQLiteConfig) CreateDatabase() (*gorm.DB, error) ", "output": "{\n\tdb, err := gorm.Open(\"sqlite3\", config.File)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = db.AutoMigrate(&sql.Issue{}, &sql.IssueEvent{}, &sql.Label{}, &sql.Comment{}).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}"} {"input": "package seccomp\n\nimport (\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/opencontainers/runtime-spec/specs-go\"\n)\n\n\n\n\nfunc DefaultProfile(rs *specs.Spec) *types.Seccomp ", "output": "{\n\treturn nil\n}"} {"input": "package lib\n\n\n\nfunc M() int ", "output": "{ return 42 }"} {"input": "package graph\n\nimport (\n\t\"github.com/docker/docker/engine\"\n\t\"github.com/docker/docker/pkg/parsers\"\n)\n\n\n\n\n\n\n\nfunc (s *TagStore) CmdTag(job *engine.Job) engine.Status {\n\tif len(job.Args) != 2 {\n\t\treturn job.Errorf(\"usage: %s NEWNAME OLDNAME\", job.Name)\n\t}\n\tvar (\n\t\tnewName = job.Args[0]\n\t\toldName = job.Args[1]\n\t)\n\tnewRepo, newTag := parsers.ParseRepositoryTag(newName)\n\tif err := s.Set(newRepo, newTag, oldName, true); err != nil {\n\t\treturn job.Error(err)\n\t}\n\treturn engine.StatusOK\n}\n\n\n\n\nfunc (s *TagStore) CmdTagLegacy(job *engine.Job) engine.Status ", "output": "{\n\tif len(job.Args) != 2 && len(job.Args) != 3 {\n\t\treturn job.Errorf(\"Usage: %s IMAGE REPOSITORY [TAG]\\n\", job.Name)\n\t}\n\tvar tag string\n\tif len(job.Args) == 3 {\n\t\ttag = job.Args[2]\n\t}\n\tif err := s.Set(job.Args[1], tag, job.Args[0], job.GetenvBool(\"force\")); err != nil {\n\t\treturn job.Error(err)\n\t}\n\treturn engine.StatusOK\n}"} {"input": "package siesta\n\nimport \"testing\"\n\nvar emptyHeartbeatRequestBytes = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}\nvar goodHeartbeatRequestBytes = []byte{0x00, 0x05, 'g', 'r', 'o', 'u', 'p', 0x00, 0x00, 0x00, 0x03, 0x00, 0x06, 'm', 'e', 'm', 'b', 'e', 'r'}\n\nvar errorHeartbeatResponseBytes = []byte{0x00, 25}\nvar goodHeartbeatResponseBytes = []byte{0x00, 0x00}\n\n\n\nfunc TestHeartbeatResponse(t *testing.T) {\n\terrorHeartbeatResponse := new(HeartbeatResponse)\n\tdecode(t, errorHeartbeatResponse, errorHeartbeatResponseBytes)\n\tassert(t, errorHeartbeatResponse.Error, ErrUnknownMemberID)\n\n\tgoodHeartbeatResponse := new(HeartbeatResponse)\n\tdecode(t, goodHeartbeatResponse, goodHeartbeatResponseBytes)\n\tassert(t, goodHeartbeatResponse.Error, ErrNoError)\n}\n\nfunc TestHeartbeatRequest(t *testing.T) ", "output": "{\n\temptyHeartbeatRequest := new(HeartbeatRequest)\n\ttestRequest(t, emptyHeartbeatRequest, emptyHeartbeatRequestBytes)\n\n\tgoodHeartbeatRequest := new(HeartbeatRequest)\n\tgoodHeartbeatRequest.GroupID = \"group\"\n\tgoodHeartbeatRequest.GenerationID = 3\n\tgoodHeartbeatRequest.MemberID = \"member\"\n\ttestRequest(t, goodHeartbeatRequest, goodHeartbeatRequestBytes)\n}"} {"input": "package csi_test\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n\n\tgofigCore \"github.com/akutz/gofig\"\n\tgofig \"github.com/akutz/gofig/types\"\n)\n\n\n\nfunc TestGofigMap(t *testing.T) {\n\tconfig := gofigCore.NewConfig(false, false, \"config\", \"yaml\")\n\tconfig.ReadConfig(strings.NewReader(`\nnfs:\n volumes:\n - name1=uri1\n - name2=uri2\n - name3=uri3\n`))\n\tasSlice := config.GetStringSlice(\"nfs.volumes\")\n\tfmt.Printf(\"GetStringSlice: len=%d, %v\\n\", len(asSlice), asSlice)\n\n\tos.Setenv(\"NFS_VOLUMES\", \"name4=uri4 name5=uri5\")\n\tasSlice = config.GetStringSlice(\"nfs.volumes\")\n\tfmt.Printf(\"GetStringSlice: len=%d, %v\\n\", len(asSlice), asSlice)\n}\n\nfunc init() ", "output": "{\n\tr := gofigCore.NewRegistration(\"MapTest\")\n\tr.Key(gofig.String,\n\t\t\"\", \"\", \"\",\n\t\t\"nfs.volumes\")\n\tgofigCore.Register(r)\n}"} {"input": "package obj\n\n\n\nconst (\n\tLOG = 5\n)\n\n\n\nfunc Appendp(q *Prog, newprog ProgAlloc) *Prog {\n\tp := newprog()\n\tp.Link = q.Link\n\tq.Link = p\n\tp.Pos = q.Pos\n\treturn p\n}\n\nfunc mkfwd(sym *LSym) ", "output": "{\n\tvar dwn [LOG]int32\n\tvar cnt [LOG]int32\n\tvar lst [LOG]*Prog\n\n\tfor i := 0; i < LOG; i++ {\n\t\tif i == 0 {\n\t\t\tcnt[i] = 1\n\t\t} else {\n\t\t\tcnt[i] = LOG * cnt[i-1]\n\t\t}\n\t\tdwn[i] = 1\n\t\tlst[i] = nil\n\t}\n\n\ti := 0\n\tfor p := sym.Func.Text; p != nil && p.Link != nil; p = p.Link {\n\t\ti--\n\t\tif i < 0 {\n\t\t\ti = LOG - 1\n\t\t}\n\t\tp.Forwd = nil\n\t\tdwn[i]--\n\t\tif dwn[i] <= 0 {\n\t\t\tdwn[i] = cnt[i]\n\t\t\tif lst[i] != nil {\n\t\t\t\tlst[i].Forwd = p\n\t\t\t}\n\t\t\tlst[i] = p\n\t\t}\n\t}\n}"} {"input": "package appsetup\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\ntype Cnf struct {\n\tDashboard DashboardCnf `yaml:\"dashboard\"`\n\tStorage StorageCnf `yaml:\"storage\"`\n\tSources []SourceCnf `yaml:\"sources\"`\n\tNotices []NoticeCnf `yaml:\"notices\"`\n}\n\ntype DashboardCnf struct {\n\tPort int `yaml:\"port\"`\n\tIndexHTML string `yaml:\"index\"`\n}\n\ntype SourceCnf struct {\n\tName string `yaml:\"name\"`\n\tParams map[string]string `yaml:\"params\"`\n}\n\ntype NoticeCnf struct {\n\tName string `yaml:\"name\"`\n\tParams map[string]string `yaml:\"params\"`\n}\n\ntype StorageCnf struct {\n\tType string `yaml:\"type\"`\n\tInactivityPeriod int `yaml:\"inactivity_period_in_min\"`\n}\n\n\n\nfunc getConfig(path string) (Cnf, error) ", "output": "{\n\tcnf := Cnf{}\n\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn cnf, err\n\t}\n\n\tdata, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn cnf, err\n\t}\n\n\terr = yaml.Unmarshal(data, &cnf)\n\treturn cnf, err\n}"} {"input": "package syncbase_test\n\nimport (\n\t\"regexp\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"v.io/v23/syncbase\"\n)\n\nconst (\n\tuuidLoopInvocations int = 100\n)\n\nfunc TestUUIDFormat(t *testing.T) {\n\tuuid := syncbase.UUID()\n\tregexp := regexp.MustCompile(\"(?i)^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$\")\n\tif !regexp.MatchString(uuid) {\n\t\tt.Errorf(\"Incorrect UUID format: %v\", uuid)\n\t}\n}\n\n\n\nfunc TestUUIDCollisions(t *testing.T) ", "output": "{\n\tvar mutex sync.Mutex\n\tvar waitGroup sync.WaitGroup\n\tuuidMap := make(map[string]bool)\n\n\tcreateUUID := func() {\n\t\tmutex.Lock()\n\t\tdefer mutex.Unlock()\n\t\tuuidMap[syncbase.UUID()] = true\n\t\twaitGroup.Done()\n\t}\n\n\tfor i := 0; i < uuidLoopInvocations; i++ {\n\t\twaitGroup.Add(1)\n\t\tgo createUUID()\n\t}\n\n\twaitGroup.Wait()\n\n\tif len(uuidMap) != uuidLoopInvocations {\n\t\tt.Errorf(\"UUID collision for %d UUIDs\", uuidLoopInvocations-len(uuidMap))\n\t}\n}"} {"input": "package heap\n\nimport (\n\t\"sync\"\n)\n\ntype Monitor struct {\n\towner interface{} \n\townerLock sync.Locker\n\tlock sync.Locker\n\tentryCount int\n\tcond *sync.Cond\n}\n\nfunc newMonitor() *Monitor {\n\tm := &Monitor{}\n\tm.ownerLock = &sync.Mutex{}\n\tm.lock = &sync.Mutex{}\n\tm.cond = sync.NewCond(m.lock)\n\treturn m\n}\n\nfunc (monitor *Monitor) Enter(thread interface{}) {\n\tmonitor.ownerLock.Lock()\n\tif monitor.owner == thread {\n\t\tmonitor.entryCount++\n\t\tmonitor.ownerLock.Unlock()\n\t\treturn\n\t} else {\n\t\tmonitor.ownerLock.Unlock()\n\t}\n\n\tmonitor.lock.Lock()\n\n\tmonitor.ownerLock.Lock()\n\tmonitor.owner = thread\n\tmonitor.entryCount = 1\n\tmonitor.ownerLock.Unlock()\n}\n\nfunc (monitor *Monitor) Exit(thread interface{}) {\n\tmonitor.ownerLock.Lock()\n\tvar _unlock bool\n\tif monitor.owner == thread {\n\t\tmonitor.entryCount--\n\t\tif monitor.entryCount == 0 {\n\t\t\tmonitor.owner = nil\n\t\t\t_unlock = true\n\t\t}\n\t}\n\tmonitor.ownerLock.Unlock()\n\n\tif _unlock {\n\t\tmonitor.lock.Unlock()\n\t}\n}\n\nfunc (monitor *Monitor) HasOwner(thread interface{}) bool {\n\tmonitor.ownerLock.Lock()\n\tisOwner := monitor.owner == thread\n\tmonitor.ownerLock.Unlock()\n\n\treturn isOwner\n}\n\n\n\nfunc (monitor *Monitor) NotifyAll() {\n\tmonitor.cond.Broadcast()\n}\n\nfunc (monitor *Monitor) Wait() ", "output": "{\n\tmonitor.ownerLock.Lock()\n\toldEntryCount := monitor.entryCount\n\toldOwner := monitor.owner\n\tmonitor.entryCount = 0\n\tmonitor.owner = nil\n\tmonitor.ownerLock.Unlock()\n\n\tmonitor.cond.Wait()\n\n\tmonitor.ownerLock.Lock()\n\tmonitor.entryCount = oldEntryCount\n\tmonitor.owner = oldOwner\n\tmonitor.ownerLock.Unlock()\n}"} {"input": "package sdk\n\nimport (\n\t\"io/ioutil\"\n\t\"net/url\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\ntype hydraConfig struct {\n\tClusterURL string `yaml:\"cluster_url\"`\n\tClientID string `yaml:\"client_id\"`\n\tClientSecret string `yaml:\"client_secret\"`\n}\n\n\n\n\n\n\n\n\n\nfunc ClusterURL(urlStr string) option {\n\treturn func(c *Client) error {\n\t\tvar err error\n\t\tc.clusterURL, err = url.Parse(urlStr)\n\t\treturn err\n\t}\n}\n\n\n\n\n\n\n\nfunc ClientID(id string) option {\n\treturn func(c *Client) error {\n\t\tc.clientID = id\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc ClientSecret(secret string) option {\n\treturn func(c *Client) error {\n\t\tc.clientSecret = secret\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc SkipTLSVerify() option {\n\treturn func(c *Client) error {\n\t\tc.skipTLSVerify = true\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc Scopes(scopes ...string) option {\n\treturn func(c *Client) error {\n\t\tc.scopes = scopes\n\t\treturn nil\n\t}\n}\n\nfunc FromYAML(file string) option ", "output": "{\n\treturn func(c *Client) error {\n\t\tvar err error\n\t\tvar config = hydraConfig{}\n\n\t\tdata, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = yaml.Unmarshal(data, &config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.clusterURL, err = url.Parse(config.ClusterURL)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.clientID = config.ClientID\n\t\tc.clientSecret = config.ClientSecret\n\n\t\treturn nil\n\t}\n}"} {"input": "package ewma\n\nimport (\n\t\"time\"\n)\n\ntype EwmaRate struct {\n\tEwma\n}\n\n\nconst nanosec = float64(1000000000)\n\n\n\n\n\n\n\n\n\nfunc (r *EwmaRate) Init(halfLife time.Duration) *EwmaRate {\n\tr.Ewma.Init(halfLife)\n\treturn r\n}\n\n\n\n\nfunc (r *EwmaRate) UpdateNow() float64 {\n\treturn r.Update(time.Now())\n}\n\n\n\n\nfunc (r *EwmaRate) Update(now time.Time) float64 {\n\ttimeDelta := now.Sub(r.lastTimestamp)\n\treturn r.Ewma.Update(nanosec/float64(timeDelta.Nanoseconds()), now)\n}\n\n\n\n\nfunc (r *EwmaRate) CurrentNow() float64 {\n\treturn r.Current(time.Now())\n}\n\n\nfunc (r *EwmaRate) Current(now time.Time) float64 {\n\tif r.lastTimestamp.IsZero() || r.lastTimestamp == now || now.Before(r.lastTimestamp) {\n\t\treturn r.Ewma.Current\n\t}\n\n\ttimeDelta := now.Sub(r.lastTimestamp)\n\n\treturn r.count(0, timeDelta)\n}\n\nfunc NewEwmaRate(halfLife time.Duration) *EwmaRate ", "output": "{\n\treturn (&EwmaRate{}).Init(halfLife)\n}"} {"input": "package api_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/remind101/empire/pkg/heroku\"\n)\n\nfunc TestFormationBatchUpdate(t *testing.T) {\n\tc, s := NewTestClient(t)\n\tdefer s.Close()\n\n\tmustDeploy(t, c, DefaultImage)\n\n\tq := 2\n\tf := mustFormationBatchUpdate(t, c, \"acme-inc\", []heroku.FormationBatchUpdateOpts{\n\t\t{\n\t\t\tProcess: \"web\",\n\t\t\tQuantity: &q,\n\t\t},\n\t})\n\n\tif got, want := f[0].Quantity, 2; got != want {\n\t\tt.Fatalf(\"Quantity => %d; want %d\", got, want)\n\t}\n}\n\n\n\nfunc mustFormationBatchUpdate(t testing.TB, c *heroku.Client, appName string, updates []heroku.FormationBatchUpdateOpts) []heroku.Formation ", "output": "{\n\tf, err := c.FormationBatchUpdate(appName, updates, \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treturn f\n}"} {"input": "package backup\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\tvelerov1api \"github.com/vmware-tanzu/velero/pkg/apis/velero/v1\"\n\t\"github.com/vmware-tanzu/velero/pkg/util/collections\"\n\t\"github.com/vmware-tanzu/velero/pkg/volume\"\n)\n\ntype itemKey struct {\n\tresource string\n\tnamespace string\n\tname string\n}\n\n\n\ntype Request struct {\n\t*velerov1api.Backup\n\n\tStorageLocation *velerov1api.BackupStorageLocation\n\tSnapshotLocations []*velerov1api.VolumeSnapshotLocation\n\tNamespaceIncludesExcludes *collections.IncludesExcludes\n\tResourceIncludesExcludes *collections.IncludesExcludes\n\tResourceHooks []resourceHook\n\tResolvedActions []resolvedAction\n\n\tVolumeSnapshots []*volume.Snapshot\n\tPodVolumeBackups []*velerov1api.PodVolumeBackup\n\tBackedUpItems map[itemKey]struct{}\n}\n\n\n\n\n\nfunc (r *Request) BackupResourceList() map[string][]string ", "output": "{\n\tresources := map[string][]string{}\n\tfor i := range r.BackedUpItems {\n\t\tentry := i.name\n\t\tif i.namespace != \"\" {\n\t\t\tentry = fmt.Sprintf(\"%s/%s\", i.namespace, i.name)\n\t\t}\n\t\tresources[i.resource] = append(resources[i.resource], entry)\n\t}\n\n\tfor _, v := range resources {\n\t\tsort.Strings(v)\n\t}\n\n\treturn resources\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"layeh.com/gumble/gumble\"\n\t\"time\"\n)\n\nvar connect = &Command{\n\tRun: Lastconnect,\n\tPublicResponse: false,\n\tUsageLine: \"connect [delete]\",\n\tShort: \"Shows last connect info pasted into mumble\",\n\tLong: `\nShows last connect info last pasted into mumbble, you can allso\nuse the \"delete\" arg to remove this from memory.\n\nnote: This will replace the connect string with your user ID!\n`,\n}\n\ntype SourceConnect struct {\n\thostname string\n\tpassword string\n\tUserID uint32\n}\n\n\n\n\n\nfunc (c SourceConnect) ConnectString() string {\n\treturn fmt.Sprintf(\"connect %s; password %s\", c.hostname, c.password)\n}\n\nvar currentConnect = new(SourceConnect)\nvar currentConnectHTML = \"There is not yet a connect!\"\nvar currentConnectString = \"There is not yet a connect!\"\n\nfunc (c SourceConnect) GenConnectString() (string, string) {\n\treturn c.HTMLSteamConnect(), c.ConnectString()\n}\n\nfunc Lastconnect(cmd *Command, args []string, event *gumble.TextMessageEvent) string {\n\tsender := event.Sender\n\tif args[2] != \"\" {\n\t\tswitch args[2] {\n\t\tcase \"delete\":\n\t\t\tvar delMsg = fmt.Sprintf(\"The last connect was deleted by '%s' ID: %d at %s\",\n\t\t\t\tsender.Name, sender.UserID, time.Now().UTC().Format(time.RFC850))\n\n\t\t\tcurrentConnectHTML = delMsg\n\t\t\tcurrentConnectString = delMsg\n\t\t\tcurrentConnect = new(SourceConnect)\n\t\tcase \"raw\":\n\t\t\treturn currentConnectString\n\t\tdefault:\n\t\t\treturn CommandNotFound(args[0])\n\t\t}\n\t}\n\treturn currentConnectHTML\n}\n\nfunc (c SourceConnect) HTMLSteamConnect() string ", "output": "{\n\ttimeStamp := time.Now().UTC().Format(time.RFC850)\n\tbutton := fmt.Sprintf(\"
Here is the last connect posted:
[%s]
%s
CLICK TO CONNECT TO SERVER\",\n\t\ttimeStamp, c.ConnectString(), c.hostname, c.password)\n\tlog.Debug(button)\n\treturn button\n}"} {"input": "package backend\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nconst SHOPPING_CART_TOTAL = 9.94\n\nvar discounts map[string]float32\n\nfunc InitCheckout() {\n\tRegisterHandler(\"/checkout/shopping-cart\", handleShoppingCart)\n\tRegisterHandler(\"/checkout/apply-code\", handleApplyCode)\n\tdiscounts = make(map[string]float32)\n}\n\nfunc handleApplyCode(w http.ResponseWriter, r *http.Request) {\n\tSetMaxAge(w, 0)\n\tif r.Method == \"POST\" {\n\t\tclientId := r.FormValue(\"clientId\")\n\t\tdiscounts[clientId] = 0.2\n\t\twriteShoppingCart(w, r, clientId)\n\t}\n}\n\nfunc handleShoppingCart(w http.ResponseWriter, r *http.Request) {\n\tSetMaxAge(w, 0)\n\tif r.Method == \"GET\" {\n\t\tclientId := r.URL.Query().Get(\"clientId\")\n\t\twriteShoppingCart(w, r, clientId)\n\t}\n}\n\n\n\nfunc createShoppingCart() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"items\": []interface{}{\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"name\": \"Item 1\",\n\t\t\t\t\"price\": \"1.99\",\n\t\t\t\t\"quantity\": \"2\",\n\t\t\t},\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"name\": \"Item 2\",\n\t\t\t\t\"price\": \"2.99\",\n\t\t\t\t\"quantity\": \"1\",\n\t\t\t},\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"name\": \"Item 3\",\n\t\t\t\t\"price\": \"0.99\",\n\t\t\t\t\"quantity\": \"3\",\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc writeShoppingCart(w http.ResponseWriter, r *http.Request, clientId string) ", "output": "{\n\tdiscount := discounts[clientId]\n\ttotal := SHOPPING_CART_TOTAL - SHOPPING_CART_TOTAL*discount\n\tcart := createShoppingCart()\n\tcart[\"total\"] = fmt.Sprintf(\"%.2f\", total)\n\tif discount > 0 {\n\t\tcart[\"discount\"] = fmt.Sprintf(\"%g%%\", (discount * 100))\n\t}\n\tSendJsonResponse(w, cart)\n}"} {"input": "package fingerprint\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hashicorp/nomad/client/config\"\n\t\"github.com/hashicorp/nomad/helper/testlog\"\n\t\"github.com/hashicorp/nomad/nomad/structs\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestMemoryFingerprint(t *testing.T) {\n\trequire := require.New(t)\n\n\tf := NewMemoryFingerprint(testlog.HCLogger(t))\n\tnode := &structs.Node{\n\t\tAttributes: make(map[string]string),\n\t}\n\n\trequest := &FingerprintRequest{Config: &config.Config{}, Node: node}\n\tvar response FingerprintResponse\n\terr := f.Fingerprint(request, &response)\n\trequire.NoError(err)\n\n\tassertNodeAttributeContains(t, response.Attributes, \"memory.totalbytes\")\n\trequire.NotNil(response.Resources, \"expected response Resources to not be nil\")\n\trequire.NotZero(response.Resources.MemoryMB, \"expected memory to be non-zero\")\n\trequire.NotNil(response.NodeResources, \"expected response NodeResources to not be nil\")\n\trequire.NotZero(response.NodeResources.Memory.MemoryMB, \"expected memory to be non-zero\")\n}\n\n\n\nfunc TestMemoryFingerprint_Override(t *testing.T) ", "output": "{\n\tf := NewMemoryFingerprint(testlog.HCLogger(t))\n\tnode := &structs.Node{\n\t\tAttributes: make(map[string]string),\n\t}\n\n\tmemoryMB := 15000\n\trequest := &FingerprintRequest{Config: &config.Config{MemoryMB: memoryMB}, Node: node}\n\tvar response FingerprintResponse\n\terr := f.Fingerprint(request, &response)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tassertNodeAttributeContains(t, response.Attributes, \"memory.totalbytes\")\n\trequire := require.New(t)\n\trequire.NotNil(response.Resources)\n\trequire.EqualValues(response.Resources.MemoryMB, memoryMB)\n\trequire.NotNil(response.NodeResources)\n\trequire.EqualValues(response.NodeResources.Memory.MemoryMB, memoryMB)\n}"} {"input": "package main\n\n\ntype seriesType int\n\nconst (\n\trouterRequest seriesType = iota\n\trouterEvent\n\tdynoMem\n\tdynoLoad\n\tdynoEvents\n\tnumSeries\n)\n\nvar (\n\tseriesColumns = [][]string{\n\t\t[]string{\"time\", \"status\", \"service\"}, \n\t\t[]string{\"time\", \"code\"}, \n\t\t[]string{\"time\", \"source\", \"memory_cache\", \"memory_pgpgin\", \"memory_pgpgout\", \"memory_rss\", \"memory_swap\", \"memory_total\", \"dynoType\"}, \n\t\t[]string{\"time\", \"source\", \"load_avg_1m\", \"load_avg_5m\", \"load_avg_15m\", \"dynoType\"}, \n\t\t[]string{\"time\", \"what\", \"type\", \"code\", \"message\", \"dynoType\"}, \n\t}\n\n\tseriesNames = []string{\"router\", \"events.router\", \"dyno.mem\", \"dyno.load\", \"events.dyno\"}\n)\n\nfunc (st seriesType) Name() string {\n\treturn seriesNames[st]\n}\n\nfunc (st seriesType) Columns() []string {\n\treturn seriesColumns[st]\n}\n\n\ntype point struct {\n\tToken string\n\tType seriesType\n\tPoints []interface{}\n}\n\n\n\nfunc (p point) SeriesName() string ", "output": "{\n\treturn p.Type.Name() + \".\" + p.Token\n}"} {"input": "package systemCall\n\n\nimport \"C\"\n\n\n\n\n\n\nfunc GetClockTicksPerSecond() (ticksPerSecond uint64) ", "output": "{\n\tvar sc_clk_tck C.long\n\tsc_clk_tck = C.sysconf(C._SC_CLK_TCK)\n\tticksPerSecond = uint64(sc_clk_tck)\n\treturn\n}"} {"input": "package via\n\nimport (\n\t\"fmt\"\n\t\"gopkg.in/src-d/go-git.v4\"\n\t\"gopkg.in/src-d/go-git.v4/plumbing\"\n\t\"os\"\n\tgpath \"path\"\n)\n\n\n\n\n\nfunc gitref(branch string) plumbing.ReferenceName {\n\treturn plumbing.ReferenceName(\n\t\tfmt.Sprintf(\"refs/heads/%s\", branch),\n\t)\n}\n\n\nfunc CloneBranch(dir Path, url, branch string) error {\n\t_, err := git.PlainClone(dir.String(), false, &git.CloneOptions{\n\t\tURL: url,\n\t\tProgress: os.Stdout,\n\t\tDepth: 1,\n\t\tReferenceName: gitref(branch),\n\t})\n\treturn err\n}\n\n\n\nfunc Branch(path Path) (string, error) {\n\tr, err := git.PlainOpen(path.String())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\thead, err := r.Head()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn gpath.Base(head.Name().String()), nil\n}\n\nfunc Clone(dir Path, url string) error ", "output": "{\n\t_, err := git.PlainClone(dir.String(), false, &git.CloneOptions{\n\t\tURL: url,\n\t\tProgress: os.Stdout,\n\t\tDepth: 1,\n\t\tRecurseSubmodules: git.DefaultSubmoduleRecursionDepth,\n\t})\n\treturn err\n}"} {"input": "package schema\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\n\n\nfunc TestParseThreadMessage(t *testing.T) {\n\tthreadJsonString, _ := ioutil.ReadFile(\"../../resources/samples/thread.json\")\n\tvar thread MessageBase\n\tjson.Unmarshal(threadJsonString, &thread)\n\tt.Log(\"Thread Id is: \", thread.Id)\n\tt.Log(\"Thread Title is: \", thread.Message.Title)\n\tt.Log(\"Thread Author is: \", thread.Message.Author.User.ScreenName)\n}\n\nfunc TestParsePostMessage(t *testing.T) {\n\tpostJsonString, _ := ioutil.ReadFile(\"../../resources/samples/post.json\")\n\tvar post MessageBase\n\tjson.Unmarshal(postJsonString, &post)\n\tt.Log(\"Post Id is: \", post.Id)\n\tt.Log(\"Post to Thread: \", post.Message.ThreadId)\n\tt.Log(\"Post Content is: \", post.Message.Content)\n}\n\nfunc TestParseGroup(t *testing.T) ", "output": "{\n\tgroupJsonString, _ := ioutil.ReadFile(\"../../resources/samples/group.json\")\n\tvar group GroupBase\n\tjson.Unmarshal(groupJsonString, &group)\n\tt.Log(\"Group ID is: \", group.Id)\n\tt.Log(\"Group Name is: \", group.Group.Name)\n}"} {"input": "package client\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/mesosphere/dcos-commons/cli/config\"\n)\n\n\n\nvar PrintMessage = printMessage\n\n\n\nvar PrintMessageAndExit = printMessageAndExit\n\n\n\nfunc printMessageAndExit(format string, a ...interface{}) (int, error) {\n\tPrintMessage(format, a...)\n\tos.Exit(1)\n\treturn 0, nil\n}\n\n\nfunc PrintVerbose(format string, a ...interface{}) (int, error) {\n\tif config.Verbose {\n\t\treturn PrintMessage(format, a...)\n\t}\n\treturn 0, nil\n}\n\n\n\n\nfunc PrintJSONBytes(responseBytes []byte) {\n\tvar outBuf bytes.Buffer\n\terr := json.Indent(&outBuf, responseBytes, \"\", \" \")\n\tif err != nil {\n\t\tPrintMessage(\"Failed to prettify JSON response data: %s\", err)\n\t\tPrintMessage(\"Original data follows:\")\n\t\toutBuf = *bytes.NewBuffer(responseBytes)\n\t}\n\tPrintMessage(\"%s\", outBuf.String())\n}\n\n\nfunc PrintResponseText(body []byte) {\n\tPrintMessage(\"%s\\n\", string(body))\n}\n\nfunc printMessage(format string, a ...interface{}) (int, error) ", "output": "{\n\treturn fmt.Println(fmt.Sprintf(format, a...))\n}"} {"input": "package nntptest\n\nimport \"bytes\"\n\n\n\ntype ResponseRecorder struct {\n\tCode int\n\tBody *bytes.Buffer\n\twroteHeader bool\n}\n\n\nfunc NewRecorder() *ResponseRecorder {\n\treturn &ResponseRecorder{\n\t\tBody: new(bytes.Buffer),\n\t\tCode: 403,\n\t}\n}\n\n\nfunc (rw *ResponseRecorder) Write(buf []byte) (int, error) {\n\tif !rw.wroteHeader {\n\t\trw.WriteHeader(403)\n\t\treturn 0, nil\n\t}\n\tif rw.Body != nil {\n\t\trw.Body.Write(buf)\n\t}\n\treturn len(buf), nil\n}\n\n\n\n\nfunc (rw *ResponseRecorder) WriteHeader(code int) ", "output": "{\n\tif !rw.wroteHeader {\n\t\trw.Code = code\n\t}\n\trw.wroteHeader = true\n}"} {"input": "package path\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\n\n\n\n\ntype P []string\n\n\nfunc New(path string) P {\n\treturn strings.Split(path, \".\")\n}\n\n\n\n\n\n\nfunc (path P) String() string {\n\tbuffer := new(bytes.Buffer)\n\n\tfor i, item := range path {\n\t\tbuffer.WriteString(item)\n\n\t\tif i < len(path)-1 {\n\t\t\tbuffer.WriteString(\".\")\n\t\t}\n\t}\n\n\treturn buffer.String()\n}\n\n\nfunc (path P) Last() string { return path[len(path)-1] }\n\nfunc Newf(path string, args ...interface{}) P ", "output": "{\n\treturn New(fmt.Sprintf(path, args...))\n}"} {"input": "package protocol\n\nimport (\n\t\"context\"\n\n\t\"github.com/coffeehc/logger\"\n\t\"github.com/coffeehc/netx\"\n\t\"github.com/ugorji/go/codec\"\n)\n\ntype msgpackProtocol struct {\n\thander *codec.MsgpackHandle\n\tinterf func() interface{}\n}\n\n\nfunc NewMsgpackProcotol(interfFunc func() interface{}) netx.Protocol {\n\tp := &msgpackProtocol{hander: new(codec.MsgpackHandle)}\n\tp.interf = interfFunc\n\tif p.interf == nil {\n\t\tp.interf = func() interface{} {\n\t\t\tvar i interface{}\n\t\t\treturn &i\n\t\t}\n\t}\n\treturn p\n}\n\nfunc (mp *msgpackProtocol) Encode(cxt context.Context, connContext netx.ConnContext, chain netx.ProtocolChain, data interface{}) {\n\tvar b []byte\n\tencode := codec.NewEncoderBytes(&b, mp.hander)\n\terr := encode.Encode(data)\n\tif err != nil {\n\t\tlogger.Error(\"Msgpack序列化错误:%s\", err)\n\t\treturn\n\t}\n\tchain.Fire(cxt, connContext, b)\n}\n\n\n\nfunc (mp *msgpackProtocol) EncodeDestroy() {}\n\nfunc (mp *msgpackProtocol) DecodeDestroy() {}\n\nfunc (mp *msgpackProtocol) Decode(cxt context.Context, connContext netx.ConnContext, chain netx.ProtocolChain, data interface{}) ", "output": "{\n\tif v, ok := data.([]byte); ok {\n\t\tobj := mp.interf()\n\t\tdecode := codec.NewDecoderBytes(v, mp.hander)\n\t\terr := decode.Decode(obj)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Msgpack反序列化失败:%s\", err)\n\t\t\treturn\n\t\t}\n\t\tdata = obj\n\t}\n\tchain.Fire(cxt, connContext, data)\n}"} {"input": "package chipmunk\n\nimport (\n\t\"github.com/Dethrail/chipmunk/transform\"\n\t\"github.com/Dethrail/chipmunk/vect\"\n\t\"math\"\n)\n\nconst (\n\tRadianConst = math.Pi / 180\n\tDegreeConst = 180 / math.Pi\n)\n\ntype Group int\ntype Layer int\n\ntype Shape struct {\n\tDefaultHash\n\tShapeClass\n\n\tBody *Body\n\n\tBB AABB\n\n\tIsSensor bool\n\n\te vect.Float\n\tu vect.Float\n\tSurface_v vect.Vect\n\n\tUserData interface{}\n\n\tGroup Group\n\tLayer Layer\n\n\tspace *Space\n\n\tvelocityIndexed bool\n}\n\nfunc newShape() *Shape {\n\treturn &Shape{velocityIndexed: true, e: 0.5, u: 0.5, Layer: -1}\n\n}\n\nfunc (shape *Shape) Velocity() (vect.Vect, bool) {\n\treturn shape.Body.v, shape.velocityIndexed\n}\n\n\n\nfunc (shape *Shape) SetElasticity(e vect.Float) {\n\tshape.e = e\n}\n\nfunc (shape *Shape) Shape() *Shape {\n\treturn shape\n}\n\nfunc (shape *Shape) AABB() AABB {\n\treturn shape.BB\n}\n\nfunc (shape *Shape) Clone() *Shape {\n\tclone := *shape\n\tcc := &clone\n\tcc.space = nil\n\tcc.DefaultHash.Reset()\n\tcc.Body = nil\n\tcc.ShapeClass = cc.ShapeClass.Clone(cc)\n\treturn cc\n}\n\nfunc (shape *Shape) Update() {\n\tshape.BB = shape.ShapeClass.update(transform.NewTransform(shape.Body.p, shape.Body.a))\n}\n\nfunc (shape *Shape) SetFriction(friction vect.Float) ", "output": "{\n\tshape.u = friction\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n)\n\ntype ContentTypeVerifier struct {\n\tContentType string\n\tNext http.Handler\n}\n\n\n\n\n\n\nfunc (h *ContentTypeVerifier) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tcts := req.Header[\"Content-Type\"]\n\tfor _, ct := range cts {\n\t\tif ct != h.ContentType {\n\t\t\th.Fail(rw, req)\n\t\t\treturn\n\t\t}\n\t}\n\n\th.Next.ServeHTTP(rw, req)\n}\n\n\n\nfunc (h *ContentTypeVerifier) Fail(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\trw.Header().Add(\"Content-Type\", \"application/json\")\n\trw.WriteHeader(400)\n\trw.Write([]byte(`{\"error\":\"Invalid content type. Did you forget to set a valid Content-Type header?\"}`))\n\trw.Write([]byte(\"\\n\"))\n}"} {"input": "package disk\n\nimport (\n\t\"testing\"\n\n\t\"github.com/funkygao/assert\"\n)\n\n\n\nfunc TestClusterTopicDir(t *testing.T) ", "output": "{\n\tct := clusterTopic{\"cluster\", \"topic\"}\n\tassert.Equal(t, \"/var/cluster\", ct.ClusterDir(\"/var\"))\n\tassert.Equal(t, \"/cluster/topic\", ct.TopicDir(\"/\"))\n}"} {"input": "package lang\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/mvader/bolt/runtime/errors\"\n\t\"github.com/mvader/bolt/runtime/stack\"\n)\n\nconst PrintlnSymbol = `println`\n\n\n\n\n\n\nconst PrintfSymbol = `printf`\n\n\n\nfunc Printf(s *stack.Stack, args ...interface{}) interface{} {\n\terrors.CheckNumArgsGte(PrintfSymbol, args, 2)\n\tformat, ok := args[0].(string)\n\tif !ok {\n\t\tpanic(errors.NewArgTypeError(PrintfSymbol, 1, args[0], \"string\"))\n\t}\n\tfmt.Printf(format, args[1:]...)\n\treturn nil\n}\n\nfunc Println(s *stack.Stack, args ...interface{}) interface{} ", "output": "{\n\terrors.CheckNumArgsGte(PrintlnSymbol, args, 1)\n\tfmt.Println(args...)\n\treturn nil\n}"} {"input": "package resources\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"mime\"\n\t\"net/http\"\n\n\tcharmresource \"github.com/juju/charm/v9/resource\"\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/names/v4\"\n\n\t\"github.com/juju/juju/resource\"\n)\n\n\ntype UploadRequest struct {\n\tApplication string\n\n\tName string\n\n\tFilename string\n\n\tSize int64\n\n\tFingerprint charmresource.Fingerprint\n\n\tPendingID string\n\n\tContent io.ReadSeeker\n}\n\n\nfunc NewUploadRequest(application, name, filename string, r io.ReadSeeker) (UploadRequest, error) {\n\tif !names.IsValidApplication(application) {\n\t\treturn UploadRequest{}, errors.Errorf(\"invalid application %q\", application)\n\t}\n\n\tcontent, err := resource.GenerateContent(r)\n\tif err != nil {\n\t\treturn UploadRequest{}, errors.Trace(err)\n\t}\n\n\tur := UploadRequest{\n\t\tApplication: application,\n\t\tName: name,\n\t\tFilename: filename,\n\t\tSize: content.Size,\n\t\tFingerprint: content.Fingerprint,\n\t\tContent: r,\n\t}\n\treturn ur, nil\n}\n\nfunc setFilename(filename string, req *http.Request) {\n\tfilename = mime.BEncoding.Encode(\"utf-8\", filename)\n\n\tdisp := mime.FormatMediaType(\n\t\tMediaTypeFormData,\n\t\tmap[string]string{FilenameParamForContentDispositionHeader: filename},\n\t)\n\n\treq.Header.Set(HeaderContentDisposition, disp)\n}\n\n\n\n\n\n\n\n\n\nconst FilenameParamForContentDispositionHeader = \"filename\"\n\n\n\n\nfunc (ur UploadRequest) HTTPRequest() (*http.Request, error) ", "output": "{\n\turlStr := NewEndpointPath(ur.Application, ur.Name)\n\n\treq, err := http.NewRequest(http.MethodPut, urlStr, ur.Content)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treq.Header.Set(HeaderContentType, ContentTypeRaw)\n\treq.Header.Set(HeaderContentSha384, ur.Fingerprint.String())\n\treq.Header.Set(HeaderContentLength, fmt.Sprint(ur.Size))\n\tsetFilename(ur.Filename, req)\n\n\treq.ContentLength = ur.Size\n\n\tif ur.PendingID != \"\" {\n\t\tquery := req.URL.Query()\n\t\tquery.Set(QueryParamPendingID, ur.PendingID)\n\t\treq.URL.RawQuery = query.Encode()\n\t}\n\n\treturn req, nil\n}"} {"input": "package repl\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/magicshui/echo/evaluator\"\n\t\"github.com/magicshui/echo/lexer\"\n\t\"github.com/magicshui/echo/object\"\n\t\"github.com/magicshui/echo/parser\"\n)\n\nconst PROMPT = \">>\"\n\nfunc Start(in io.Reader, out io.Writer) {\n\tscanner := bufio.NewScanner(in)\n\tenv := object.NewEnvironment()\n\n\tfor {\n\t\tfmt.Print(PROMPT)\n\t\tscanned := scanner.Scan()\n\t\tif !scanned {\n\t\t\treturn\n\t\t}\n\t\tline := scanner.Text()\n\t\tl := lexer.New(line)\n\t\tp := parser.New(l)\n\n\t\tprogram := p.ParseProgram()\n\t\tif len(p.Errors()) != 0 {\n\t\t\tprintParserErrors(out, p.Errors())\n\t\t\tcontinue\n\t\t}\n\n\t\tevaluated := evaluator.Eval(program, env)\n\t\tif evaluated != nil {\n\t\t\tio.WriteString(out, evaluated.Inspect())\n\t\t\tio.WriteString(out, \"\\n\")\n\t\t}\n\t}\n}\n\n\n\nfunc printParserErrors(out io.Writer, errors []string) ", "output": "{\n\tfor _, msg := range errors {\n\t\tio.WriteString(out, \"\\t\"+msg+\"\\n\")\n\t}\n}"} {"input": "package certificates\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gophercloud/gophercloud\"\n)\n\n\n\ntype CreateOptsBuilder interface {\n\tToCertificateCreateMap() (map[string]interface{}, error)\n}\n\n\ntype CreateOpts struct {\n\tClusterUUID string `json:\"cluster_uuid,omitempty\" xor:\"BayUUID\"`\n\tBayUUID string `json:\"bay_uuid,omitempty\" xor:\"ClusterUUID\"`\n\tCSR string `json:\"csr\" required:\"true\"`\n}\n\n\nfunc (opts CreateOpts) ToCertificateCreateMap() (map[string]interface{}, error) {\n\treturn gophercloud.BuildRequestBody(opts, \"\")\n}\n\n\nfunc Get(client *gophercloud.ServiceClient, clusterID string) (r GetResult) {\n\turl := getURL(client, clusterID)\n\n\t_, r.Err = client.Get(url, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{200},\n\t})\n\n\treturn\n}\n\n\nfunc Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToCertificateCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\n\tvar result *http.Response\n\tresult, r.Err = client.Post(createURL(client), b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{201},\n\t})\n\n\tif r.Err == nil {\n\t\tr.Header = result.Header\n\t}\n\n\treturn\n}\n\n\n\n\nfunc Update(client *gophercloud.ServiceClient, clusterID string) (r UpdateResult) ", "output": "{\n\t_, r.Err = client.Patch(updateURL(client, clusterID), nil, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{202},\n\t})\n\n\treturn\n}"} {"input": "package record\n\nimport (\n\t\"crypto\"\n\t\"crypto/rsa\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/royvandewater/meshchain/cryptohelpers\"\n\t\"github.com/royvandewater/meshchain/record/encoding\"\n)\n\n\n\n\ntype signedRootRecord struct {\n\tmetadata Metadata\n\tdata []byte\n\tsignature []byte\n}\n\n\n\n\nfunc (record *signedRootRecord) Hash() ([]byte, error) {\n\tunsignedRootRecord, err := NewUnsignedRootRecord(record.metadata, record.data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn unsignedRootRecord.Hash()\n}\n\n\n\n\n\nfunc (record *signedRootRecord) validateSignature() error {\n\tpublicKeys, err := cryptohelpers.BuildRSAPublicKeys(record.metadata.PublicKeys)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thashed, err := record.Hash()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to generate Hash: %v\", err.Error())\n\t}\n\n\tfor _, publicKey := range publicKeys {\n\t\tif nil == rsa.VerifyPSS(publicKey, crypto.SHA256, hashed, record.signature, nil) {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"None of the PublicKeys matches the signature\")\n}\n\nfunc (record *signedRootRecord) JSON() (string, error) ", "output": "{\n\thash, err := record.Hash()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmetadata, err := record.metadata.Proto()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tjsonBytes, err := json.Marshal(&encoding.Record{\n\t\tMetadata: metadata,\n\t\tData: record.data,\n\t\tSeal: &encoding.Seal{\n\t\t\tHash: hash,\n\t\t\tSignature: record.signature,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\treturn string(jsonBytes), nil\n}"} {"input": "package slack\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/nlopes/slack\"\n\t\"strings\"\n)\n\n\n\nfunc parseUsername(name string) (username string, err error) {\n\n\tusername = strings.ToLower(name)\n\n\tif strings.Contains(username, \" \") {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"%s is not a Slack username\", name))\n\t}\n\n\tif strings.Contains(name, \"@\") {\n\t\tusername = strings.Replace(username, \"@\", \"\", 1)\n\t}\n\n\treturn\n}\n\nfunc getUserWithUsername(username string) (user slack.User, err error) ", "output": "{\n\n\tusers, err := slackClient.GetUsers()\n\tif err != nil {\n\t\treturn slack.User{}, err\n\t}\n\n\tfor _, user := range users {\n\t\tif user.Name == username {\n\t\t\treturn user, nil\n\t\t}\n\t}\n\n\treturn slack.User{}, errors.New(fmt.Sprintf(\"No user with username %s\", username))\n}"} {"input": "package convert\n\nimport (\n\t\"strings\"\n\n\t\"code.gitea.io/gitea/modules/setting\"\n\t\"code.gitea.io/gitea/modules/structs\"\n)\n\n\nfunc ToCorrectPageSize(size int) int {\n\tif size <= 0 {\n\t\tsize = setting.API.DefaultPagingNum\n\t} else if size > setting.API.MaxResponseItems {\n\t\tsize = setting.API.MaxResponseItems\n\t}\n\treturn size\n}\n\n\n\n\nfunc ToGitServiceType(value string) structs.GitServiceType ", "output": "{\n\tswitch strings.ToLower(value) {\n\tcase \"github\":\n\t\treturn structs.GithubService\n\tcase \"gitea\":\n\t\treturn structs.GiteaService\n\tcase \"gitlab\":\n\t\treturn structs.GitlabService\n\tcase \"gogs\":\n\t\treturn structs.GogsService\n\tdefault:\n\t\treturn structs.PlainGitService\n\t}\n}"} {"input": "package logrus\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\nvar loggerFields = Fields{\n\t\"foo\": \"bar\",\n\t\"baz\": \"qux\",\n\t\"one\": \"two\",\n\t\"three\": \"four\",\n}\n\nfunc BenchmarkDummyLogger(b *testing.B) {\n\tnullf, err := os.OpenFile(\"/dev/null\", os.O_WRONLY, 0666)\n\tif err != nil {\n\t\tb.Fatalf(\"%v\", err)\n\t}\n\tdefer nullf.Close()\n\tdoLoggerBenchmark(b, nullf, &TextFormatter{DisableColors: true}, smallFields)\n}\n\nfunc BenchmarkDummyLoggerNoLock(b *testing.B) {\n\tnullf, err := os.OpenFile(\"/dev/null\", os.O_WRONLY|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tb.Fatalf(\"%v\", err)\n\t}\n\tdefer nullf.Close()\n\tdoLoggerBenchmarkNoLock(b, nullf, &TextFormatter{DisableColors: true}, smallFields)\n}\n\n\n\nfunc doLoggerBenchmarkNoLock(b *testing.B, out *os.File, formatter Formatter, fields Fields) {\n\tlogger := Logger{\n\t\tOut: out,\n\t\tLevel: InfoLevel,\n\t\tFormatter: formatter,\n\t}\n\tlogger.SetNoLock()\n\tentry := logger.WithFields(fields)\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tentry.Info(\"aaa\")\n\t\t}\n\t})\n}\n\nfunc doLoggerBenchmark(b *testing.B, out *os.File, formatter Formatter, fields Fields) ", "output": "{\n\tlogger := Logger{\n\t\tOut: out,\n\t\tLevel: InfoLevel,\n\t\tFormatter: formatter,\n\t}\n\tentry := logger.WithFields(fields)\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tentry.Info(\"aaa\")\n\t\t}\n\t})\n}"} {"input": "package cases\n\nimport \"gx/ipfs/QmVcxhXDbXjNoAdmYBWbY1eU67kQ8eZUHjG4mAYZUtZZu3/go-text/transform\"\n\ntype caseFolder struct{ transform.NopResetter }\n\n\n\n\nfunc (t *caseFolder) Span(src []byte, atEOF bool) (n int, err error) {\n\tc := context{src: src, atEOF: atEOF}\n\tfor c.next() && isFoldFull(&c) {\n\t\tc.checkpoint()\n\t}\n\treturn c.retSpan()\n}\n\nfunc makeFold(o options) transform.SpanningTransformer {\n\treturn &caseFolder{}\n}\n\nfunc (t *caseFolder) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) ", "output": "{\n\tc := context{dst: dst, src: src, atEOF: atEOF}\n\tfor c.next() {\n\t\tfoldFull(&c)\n\t\tc.checkpoint()\n\t}\n\treturn c.ret()\n}"} {"input": "package rules\nfunc (this piece) getKnightCoverageFrom(from square) (covered []square) {\n\tfor _, offset := range knightMoveOffsets {\n\t\ttarget := from.Offset(offset)\n\t\tcovered = append(covered, target)\n\t}\n\treturn covered\n}\n\n\n\n\nfunc (this piece) calculateKnightMovesFrom(square square, board board) (moves []move) ", "output": "{\n\tfor _, offset := range knightMoveOffsets {\n\t\ttarget := square.Offset(offset)\n\t\tif !target.IsValidSquare() {\n\t\t\tcontinue\n\t\t}\n\t\ttargetPiece := board.GetPieceAt(target)\n\t\tif targetPiece.Player() == this.Player() {\n\t\t\tcontinue\n\t\t}\n\t\tmoves = append(moves, move{\n\t\t\tPiece: this,\n\t\t\tFrom: square,\n\t\t\tTo: target,\n\t\t\tCaptured: targetPiece,\n\t\t\tCapturedOn: target,\n\t\t})\n\t}\n\treturn moves\n}"} {"input": "package main\n\nimport \"log\"\n\n\n\n\n\nfunc square(\n\tx int,\n) int {\n\n\treturn x * x\n}\n\nfunc work() ", "output": "{\n\n\tvar i int\n\tvar x int\n\n\tfor i = 1; i <= 10; i++ {\n\t\tx = square(i)\n\t\tlog.Printf(\n\t\t\t\"i=%v x=%v\",\n\t\t\ti,\n\t\t\tx,\n\t\t)\n\t}\n}"} {"input": "package unversioned\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/testapi\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\ntype HTTPClientFunc func(*http.Request) (*http.Response, error)\n\nfunc (f HTTPClientFunc) Do(req *http.Request) (*http.Response, error) {\n\treturn f(req)\n}\n\n\ntype FakeRESTClient struct {\n\tClient HTTPClient\n\tCodec runtime.Codec\n\tReq *http.Request\n\tResp *http.Response\n\tErr error\n}\n\nfunc (c *FakeRESTClient) Get() *Request {\n\treturn NewRequest(c, \"GET\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Put() *Request {\n\treturn NewRequest(c, \"PUT\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Patch(_ api.PatchType) *Request {\n\treturn NewRequest(c, \"PATCH\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Post() *Request {\n\treturn NewRequest(c, \"POST\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Delete() *Request {\n\treturn NewRequest(c, \"DELETE\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\n\n\nfunc (c *FakeRESTClient) Do(req *http.Request) (*http.Response, error) ", "output": "{\n\tc.Req = req\n\tif c.Client != HTTPClient(nil) {\n\t\treturn c.Client.Do(req)\n\t}\n\treturn c.Resp, c.Err\n}"} {"input": "package bigcache\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc convertMBToBytes(value int) int {\n\treturn value * 1024 * 1024\n}\n\n\n\nfunc isPowerOfTwo(number int) bool ", "output": "{\n\treturn (number & (number - 1)) == 0\n}"} {"input": "package stdlib\n\nimport (\n\t\"compress/bzip2\"\n\t\"reflect\"\n)\n\n\n\nfunc init() ", "output": "{\n\tSymbols[\"compress/bzip2\"] = map[string]reflect.Value{\n\t\t\"NewReader\": reflect.ValueOf(bzip2.NewReader),\n\n\t\t\"StructuralError\": reflect.ValueOf((*bzip2.StructuralError)(nil)),\n\t}\n}"} {"input": "package cachestore\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\n\ntype KVStore struct {\n\tstoreMap map[string]interface{}\n\tmutex sync.RWMutex\n}\n\n\nfunc (store *KVStore) Set(key string, value interface{}) {\n\tstore.mutex.Lock()\n\tstore.storeMap[key] = value\n\tstore.mutex.Unlock()\n}\n\n\n\n\n\nfunc (store *KVStore) Delete(key string) {\n\tstore.mutex.Lock()\n\tdelete(store.storeMap, key)\n\tstore.mutex.Unlock()\n}\n\n\nfunc (store *KVStore) MarshalJSON() ([]byte, error) {\n\tstore.mutex.RLock()\n\tbytes, err := json.Marshal(store.storeMap)\n\tstore.mutex.RUnlock()\n\treturn bytes, err\n}\n\n\nfunc NewKVStore() *KVStore {\n\treturn &KVStore{map[string]interface{}{}, sync.RWMutex{}}\n}\n\nfunc (store *KVStore) Get(key string) interface{} ", "output": "{\n\tstore.mutex.RLock()\n\tval := store.storeMap[key]\n\tstore.mutex.RUnlock()\n\treturn val\n}"} {"input": "package gamejam\n\ntype SceneID int\n\ntype Scene interface {\n\tAddComponent(c Component)\n\tLoad(r Resources) (err error)\n\tUnload(r Resources) (err error)\n\tRender()\n\tUpdate(mgr SceneManager)\n\tSetSceneID(id SceneID)\n\tSceneID() SceneID\n}\n\ntype BaseScene struct {\n\tcomponents map[ComponentID]Component\n\tid SceneID\n}\n\nfunc NewBaseScene() *BaseScene {\n\treturn &BaseScene{\n\t\tcomponents: map[ComponentID]Component{},\n\t}\n}\n\nfunc (s *BaseScene) AddComponent(c Component) {\n\tc.SetScene(s)\n\ts.components[c.GetID()] = c\n}\n\nfunc (s *BaseScene) Load(r Resources) (err error) {\n\treturn\n}\n\nfunc (s *BaseScene) Render() {\n}\n\n\n\nfunc (s *BaseScene) SceneID() SceneID {\n\treturn s.id\n}\n\nfunc (s *BaseScene) Unload(r Resources) (err error) {\n\tvar (\n\t\tid ComponentID\n\t\tc Component\n\t)\n\tfor id, c = range s.components {\n\t\ts.components[id] = nil\n\t\tc.Delete()\n\t}\n\treturn\n}\n\nfunc (s *BaseScene) Update(mgr SceneManager) {\n}\n\nfunc (s *BaseScene) SetSceneID(id SceneID) ", "output": "{\n\ts.id = id\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\t\"github.com/mitchellh/multistep\"\n\t\"github.com/mitchellh/packer/packer\"\n)\n\ntype StepDisableVlan struct {\n}\n\n\n\nfunc (s *StepDisableVlan) Cleanup(state multistep.StateBag) {\n}\n\nfunc (s *StepDisableVlan) Run(state multistep.StateBag) multistep.StepAction ", "output": "{\n\tdriver := state.Get(\"driver\").(Driver)\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\terrorMsg := \"Error disabling vlan: %s\"\n\tvmName := state.Get(\"vmName\").(string)\n\tswitchName := state.Get(\"SwitchName\").(string)\n\n\tui.Say(\"Disabling vlan...\")\n\n\terr := driver.UntagVirtualMachineNetworkAdapterVlan(vmName, switchName)\n\tif err != nil {\n\t\terr := fmt.Errorf(errorMsg, err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\treturn multistep.ActionContinue\n}"} {"input": "package epiutil\n\nimport \"math/rand\"\n\n\n\n\n\n\nfunc RandStr(n int, t string, s rand.Source) string ", "output": "{\n\tl := len(t) - 1\n\tchars := make([]byte, n)\n\tif l > 0 {\n\t\tfor i, p := range rand.New(s).Perm(n) {\n\t\t\tchars[i] = t[p%l]\n\t\t}\n\t}\n\treturn string(chars)\n}"} {"input": "package qtypes\n\nimport (\n\t\"strings\"\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/qnib/qframe-utils\"\n\t\"fmt\"\n)\n\nconst (\n\tMsgCEE = \"cee\"\n\tMsgTCP = \"tcp\"\n\tMsgFile = \"file\"\n\tMsgDLOG = \"docker-log\"\n\tMsgMetric = \"metric\" \n)\n\n\ntype Message struct {\n\tBase\n\tContainer types.ContainerJSON\n\tName \tstring \t`json:\"name\"`\n\tLogLevel string\t\t\t\t`json:\"loglevel\"`\n\tMessageType\tstring \t`json:\"type\"`\n\tMessage string \t`json:\"value\"`\n\tKV\t\t\tmap[string]string \t`json:\"data\"`\n}\n\nfunc NewMessage(base Base, name, mType, msg string) Message {\n\tm := Message{\n\t\tBase: base,\n\t\tName: name,\n\t\tContainer: types.ContainerJSON{},\n\t\tLogLevel: \"INFO\",\n\t\tMessageType: mType,\n\t\tMessage: msg,\n\t\tKV: map[string]string{},\n\t}\n\tm.SourceID = int(qutils.GetGID())\n\treturn m\n}\n\nfunc NewContainerMessage(base Base, cnt types.ContainerJSON, name, mType, msg string) Message {\n\tm := NewMessage(base, name, mType, msg)\n\tm.Container = cnt\n\tm.ID = m.GenContainerMsgID()\n\treturn m\n}\n\n\nfunc (m *Message) GenContainerMsgID() string {\n\ts := fmt.Sprintf(\"%s-%d-%s\", m.Container.ID, m.Time.UnixNano(), m.Message)\n\treturn Sha1HashString(s)\n}\n\n\n\nfunc (m *Message) GetContainerName() string ", "output": "{\n\tif m.Container.Name != \"\" {\n\t\treturn strings.Trim(m.Container.Name, \"/\")\n\t} else {\n\t\treturn \"\"\n\t}\n}"} {"input": "package datastorehandler\n\nimport (\n\t\"net/http\"\n)\n\n\n\nfunc baseHandler(w http.ResponseWriter, r *http.Request) {\n\n}\n\nfunc init() ", "output": "{\n\thttp.HandleFunc(\"/\", baseHandler)\n}"} {"input": "package base\n\nimport (\n\t\"github.com/johnwilson/bytengine\"\n)\n\n\nfunc ServerListDb(cmd bytengine.Command, user *bytengine.User, eng *bytengine.Engine) (interface{}, error) {\n\tfilter := \".\"\n\tval, ok := cmd.Options[\"regex\"]\n\tif ok {\n\t\tfilter = val.(string)\n\t}\n\treturn eng.FileSystem.ListDatabase(filter)\n}\n\n\n\n\n\nfunc ServerInit(cmd bytengine.Command, user *bytengine.User, eng *bytengine.Engine) (interface{}, error) {\n\treturn eng.FileSystem.ClearAll()\n}\n\n\nfunc ServerDropDb(cmd bytengine.Command, user *bytengine.User, eng *bytengine.Engine) (interface{}, error) {\n\tdb := cmd.Args[\"database\"].(string)\n\tif err := eng.FileSystem.DropDatabase(db); err != nil {\n\t\treturn nil, err\n\t}\n\treturn true, nil\n}\n\nfunc init() {\n\tbytengine.RegisterCommandHandler(\"server.listdb\", ServerListDb)\n\tbytengine.RegisterCommandHandler(\"server.newdb\", ServerNewDb)\n\tbytengine.RegisterCommandHandler(\"server.init\", ServerInit)\n\tbytengine.RegisterCommandHandler(\"server.dropdb\", ServerDropDb)\n}\n\nfunc ServerNewDb(cmd bytengine.Command, user *bytengine.User, eng *bytengine.Engine) (interface{}, error) ", "output": "{\n\tdb := cmd.Args[\"database\"].(string)\n\tif err := eng.FileSystem.CreateDatabase(db); err != nil {\n\t\treturn nil, err\n\t}\n\treturn true, nil\n}"} {"input": "package logger\n\nimport (\n\t\"strings\"\n)\n\nfunc hasFlag(has int, flags ...int) bool {\n\tfor _, flag := range flags {\n\t\tif flag&has != 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc KV(k K, v V) KeyVal {\n\treturn KeyVal{k, v}\n}\n\n\n\n\n\n\n\n\nvar tsMap = []string{\"05.000000\", \"Monday\", \"January\", \"2006\", \"-0700\", \"MST\", \"Mon\", \"Jan\", \"02\", \"15\", \"04\", \"05\", \"01\", \"06\", \"03\", \"pm\"}\n\nfunc convertStamp(format string) string ", "output": "{\n\tfor _, k := range tsMap {\n\t\tformat = strings.Replace(format, k, string(tsFmtMap[k]), -1)\n\t}\n\treturn format\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/gorilla/websocket\"\n)\n\ntype Client struct {\n\thub *Hub\n\tws *websocket.Conn\n\totherSide *Client\n\tchannelID uuid.UUID\n\tremoteType string\n\tparams map[string][]string\n\twmu sync.Mutex\n\trmu sync.Mutex\n}\n\nfunc (c *Client) WriteMessage(msgType int, message []byte) (err error) {\n\tc.wmu.Lock()\n\terr = c.ws.WriteMessage(msgType, message)\n\tc.wmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) NextWriter(msgType int) (w io.WriteCloser, err error) {\n\tc.wmu.Lock()\n\tw, err = c.ws.NextWriter(msgType)\n\tc.wmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) ReadMessage() (msgType int, message []byte, err error) {\n\tc.rmu.Lock()\n\tmsgType, message, err = c.ws.ReadMessage()\n\tc.rmu.Unlock()\n\treturn\n}\n\n\n\nfunc (c *Client) SetWriteDeadline(t time.Time) (err error) {\n\tc.wmu.Lock()\n\terr = c.ws.SetWriteDeadline(t)\n\tc.wmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) SetReadDeadline(t time.Time) (err error) {\n\tc.rmu.Lock()\n\terr = c.ws.SetReadDeadline(t)\n\tc.rmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) NextReader() (msgType int, r io.Reader, err error) ", "output": "{\n\tc.rmu.Lock()\n\tmsgType, r, err = c.ws.NextReader()\n\tc.rmu.Unlock()\n\treturn\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/user\"\n\t\"strconv\"\n)\n\nfunc CreateVcapDirs(paths []string, userName string, groupName string) error {\n\terr := mkdir(paths)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = chown(paths, userName, groupName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc mkdir(paths []string) error {\n\tfor _, path := range paths {\n\t\terr := os.MkdirAll(path, os.ModePerm)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Make directory failed: %s\\n\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc chown(paths []string, userName string, groupName string) error {\n\tuserId, err := GetUserId(userName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgroupId, err := getGroupId(groupName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, path := range paths {\n\t\terr := os.Chown(path, userId, groupId)\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Chown failed: %s\\n\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc GetUserId(userName string) (int, error) {\n\tu, err := user.Lookup(userName)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to obtain UID: %s\\n\", err)\n\t\treturn -1, err\n\t}\n\n\tuserId, _ := strconv.Atoi(u.Uid)\n\n\treturn userId, nil\n}\n\n\n\nfunc getGroupId(groupName string) (int, error) ", "output": "{\n\tg, err := user.LookupGroup(groupName)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to obtain GID: %s\\n\", err)\n\t\treturn -1, err\n\t}\n\n\tgroupId, _ := strconv.Atoi(g.Gid)\n\n\treturn groupId, nil\n}"} {"input": "package tty\n\nimport (\n\t\"fmt\"\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/fortytw2/clarent/util\"\n\t\"os\"\n\t\"os/exec\"\n)\n\n\n\n\n\n\n\nfunc getty(c *cli.Context) {\n\n\tif len(c.Args()) < 2 {\n\t\tcli.ShowAppHelp(c)\n\t}\n\n\ttty, err := os.OpenFile(c.Args().Get(0), os.O_RDWR, 0)\n\tif err != nil {\n\t\tfmt.Println(\"unable to obtain tty device, try running as root\")\n\t}\n\n\tos.Stdout = tty\n\tos.Stderr = tty\n\tos.Stdin = tty\n\n\thostname, _ := os.Hostname()\n\n\tfmt.Println(\"Welcome to \", hostname, \"running at \", c.Args().Get(0))\n\tcmd := exec.Command(c.Args().Get(1))\n\tcmd.Stdin = tty\n\tcmd.Stdout = tty\n\tcmd.Stderr = tty\n\tcmd.Run()\n\n}\n\nfunc Getty(args []string) ", "output": "{\n\tapp := cli.NewApp()\n\tcli.AppHelpTemplate = util.AppletHelpTemplate\n\tapp.Name = \"getty\"\n\tapp.Usage = \"getty [/dev/tty*] [command to run]\"\n\tapp.Action = getty\n\n\tapp.Run(args)\n}"} {"input": "package isbn\n\nimport (\n\t\"errors\"\n\t\"math\"\n\t\"strconv\"\n\t\"unicode\"\n)\n\nfunc IsValidISBN(isbn string) bool {\n\n\tisbn = dropHyphen(isbn)\n\n\tary, err := strToSlice(isbn)\n\tif len(ary) != 10 || err != nil {\n\t\treturn false\n\t}\n\n\treturn calcCheckDigit(ary)\n}\n\nfunc dropHyphen(isbn string) string {\n\tvar result string\n\tfor _, char := range isbn {\n\t\tif char == '-' {\n\t\t\tcontinue\n\t\t}\n\t\tresult += string(char)\n\t}\n\treturn result\n}\n\nfunc strToSlice(isbn string) (result []int, err error) {\n\n\tfor pos, char := range isbn {\n\t\tif unicode.IsLetter(char) && (char != 'X' || pos != 9) {\n\t\t\terr = errors.New(\"invalid character\")\n\t\t\treturn\n\t\t} else if char == 'X' {\n\t\t\tresult = append(result, 10)\n\t\t} else {\n\t\t\ti, _ := strconv.Atoi(string(char))\n\t\t\tresult = append(result, i)\n\t\t}\n\t}\n\treturn\n}\n\n\n\nfunc calcCheckDigit(isbn []int) bool ", "output": "{\n\tvar pool int\n\tfor idx, value := range isbn {\n\t\tpool += int(math.Abs(float64(idx)-10)) * value\n\t}\n\tresult := pool % 11\n\n\treturn result == 0\n}"} {"input": "package engine\n\n\ntype Novel struct {\n\tName string \n\tLastUpdateTime string \n\tAuthor string \n\tMenuURL string \n\tIconURL string \n\tNewestLastChapterName string \n\tDescription string \n\tMenus []*Menu \n\tChapters []*Chapter \n}\n\n\ntype Menu struct {\n\tName string \n\tURL string \n}\n\n\ntype Chapter struct {\n\tTitle string \n\tContent string \n}\n\n\n\nfunc (novel *Novel) AddChapter(chapter *Chapter) {\n\tnovel.Chapters = append(novel.Chapters, chapter)\n}\n\nfunc NewMenu(name, url string) *Menu {\n\treturn &Menu{name, url}\n}\n\nfunc NewChapter(title, content string) *Chapter {\n\treturn &Chapter{title, content}\n}\n\nfunc (novel *Novel) AddMenu(menu *Menu) ", "output": "{\n\tnovel.Menus = append(novel.Menus, menu)\n}"} {"input": "package types\n\nimport (\n\t\"net\"\n)\n\n\ntype IPv4 [4]byte\n\nfunc (v4 IPv4) IP() net.IP {\n\treturn v4[:]\n}\n\n\n\n\nfunc (v4 *IPv4) DeepCopyInto(out *IPv4) {\n\tcopy(out[:], v4[:])\n\treturn\n}\n\nfunc (v4 IPv4) String() string ", "output": "{\n\treturn v4.IP().String()\n}"} {"input": "package test\n\nimport (\n\t\"bytes\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc AssertEqual(t *testing.T, a, b interface{}) {\n\tif !reflect.DeepEqual(a, b) {\n\t\tt.Errorf(\"%v != %v\", a, b)\n\t}\n}\n\n\n\nfunc AssertBytesEqual(t *testing.T, a, b []byte) ", "output": "{\n\tif !bytes.Equal(a, b) {\n\t\tt.Errorf(\"%v != %v\", a, b)\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestUrlEncode(t *testing.T) ", "output": "{\n\ttests := map[string]string{\n\t\t\"/cos/hello world\": \"/cos/hello%20world\",\n\t\t\"/cos/hello=world\": \"/cos/hello%3Dworld\",\n\t\t\"/appid/bucketname/测试\": \"/appid/bucketname/%E6%B5%8B%E8%AF%95\",\n\t}\n\n\tfor str, expected := range tests {\n\t\tactual := UrlEncode(str)\n\t\tif expected != actual {\n\t\t\tt.Errorf(\"Should match [EXPECTED:%s]:[ACTUAL:%s]\", expected, actual)\n\t\t}\n\t}\n}"} {"input": "package command\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/hashicorp/nomad/api\"\n\t\"github.com/mitchellh/cli\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar _ cli.Command = &LicenseGetCommand{}\n\n\n\nfunc TestOutputLicenseReply(t *testing.T) {\n\tnow := time.Now()\n\tlic := &api.LicenseReply{\n\t\tLicense: &api.License{\n\t\t\tLicenseID: \"licenseID\",\n\t\t\tCustomerID: \"customerID\",\n\t\t\tInstallationID: \"*\",\n\t\t\tIssueTime: now,\n\t\t\tStartTime: now,\n\t\t\tExpirationTime: now.Add(1 * time.Hour),\n\t\t\tTerminationTime: now,\n\t\t\tProduct: \"nomad\",\n\t\t\tFlags: map[string]interface{}{\n\t\t\t\t\"\": nil,\n\t\t\t},\n\t\t},\n\t}\n\n\tui := cli.NewMockUi()\n\n\trequire.Equal(t, 0, OutputLicenseReply(ui, lic))\n\n\tout := ui.OutputWriter.String()\n\trequire.Contains(t, out, \"Customer ID\")\n\trequire.Contains(t, out, \"License ID\")\n}\n\nfunc TestCommand_LicenseGet_OSSErr(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\tsrv, _, url := testServer(t, false, nil)\n\tdefer srv.Shutdown()\n\n\tui := cli.NewMockUi()\n\tcmd := &LicenseGetCommand{Meta: Meta{Ui: ui}}\n\n\tcode := cmd.Run([]string{\"-address=\" + url})\n\tif srv.Enterprise {\n\t\trequire.Equal(t, 0, code)\n\t} else {\n\t\trequire.Equal(t, 1, code)\n\t\trequire.Contains(t, ui.ErrorWriter.String(), \"Nomad Enterprise only endpoint\")\n\t}\n}"} {"input": "package iso20022\n\n\ntype ProfitAndLoss1Choice struct {\n\n\tProfit *ActiveCurrencyAnd13DecimalAmount `xml:\"Prft\"`\n\n\tLoss *ActiveCurrencyAnd13DecimalAmount `xml:\"Loss\"`\n}\n\nfunc (p *ProfitAndLoss1Choice) SetProfit(value, currency string) {\n\tp.Profit = NewActiveCurrencyAnd13DecimalAmount(value, currency)\n}\n\n\n\nfunc (p *ProfitAndLoss1Choice) SetLoss(value, currency string) ", "output": "{\n\tp.Loss = NewActiveCurrencyAnd13DecimalAmount(value, currency)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSApplicationAutoScalingScalableTarget_ScheduledAction struct {\n\n\tEndTime string `json:\"EndTime,omitempty\"`\n\n\tScalableTargetAction *AWSApplicationAutoScalingScalableTarget_ScalableTargetAction `json:\"ScalableTargetAction,omitempty\"`\n\n\tSchedule string `json:\"Schedule,omitempty\"`\n\n\tScheduledActionName string `json:\"ScheduledActionName,omitempty\"`\n\n\tStartTime string `json:\"StartTime,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) AWSCloudFormationType() string {\n\treturn \"AWS::ApplicationAutoScaling::ScalableTarget.ScheduledAction\"\n}\n\n\n\n\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) DependsOn() []string ", "output": "{\n\treturn r._dependsOn\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/polariseye/polarserver/common\"\n\t\"github.com/polariseye/polarserver/common/errorCode\"\n\t\"github.com/polariseye/polarserver/moduleManage\"\n)\n\ntype testStruct struct {\n\tclassName string\n}\n\nvar TestBLL *testStruct\n\n\n\n\nfunc (this *testStruct) Name() string {\n\treturn this.className\n}\n\nfunc (this *testStruct) InitModule() []error {\n\tfmt.Println(\"初始化\")\n\n\treturn nil\n}\n\nfunc (this *testStruct) CheckModule() []error {\n\tfmt.Println(\"check\")\n\n\treturn nil\n}\n\nfunc (this *testStruct) ConvertModule() []error {\n\tfmt.Println(\"数据转换\")\n\n\treturn nil\n}\n\n\nfunc (this *testStruct) C_Hello(request *common.RequestModel, d int, name string) *common.ResultModel {\n\tresult := common.NewResultModel(errorCode.ClientDataError)\n\n\tresult.Value[\"Hello\"] = name + \"_\" + this.Name()\n\tresult.Value[\"Extra\"] = d\n\n\tresult.SetNormalError(errorCode.Success)\n\treturn result\n}\n\nfunc NewTestStruct() *testStruct {\n\treturn &testStruct{\n\t\tclassName: \"TestBLL\",\n\t}\n}\n\nfunc init() ", "output": "{\n\tTestBLL = NewTestStruct()\n\tmoduleManage.RegisterModule(func() (moduleManage.IModule, moduleManage.ModuleType) {\n\t\treturn NewTestStruct(), moduleManage.NormalModule\n\t})\n}"} {"input": "package bolthold\n\nimport (\n\t\"reflect\"\n\n\t\"github.com/boltdb/bolt\"\n)\n\n\n\nfunc (s *Store) Delete(key, dataType interface{}) error {\n\treturn s.Bolt().Update(func(tx *bolt.Tx) error {\n\t\treturn s.TxDelete(tx, key, dataType)\n\t})\n}\n\n\nfunc (s *Store) TxDelete(tx *bolt.Tx, key, dataType interface{}) error {\n\tif !tx.Writable() {\n\t\treturn bolt.ErrTxNotWritable\n\t}\n\n\tstorer := newStorer(dataType)\n\tgk, err := encode(key)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb := tx.Bucket([]byte(storer.Type()))\n\tif b == nil {\n\t\treturn ErrNotFound\n\t}\n\n\tvalue := reflect.New(reflect.TypeOf(dataType)).Interface()\n\n\tbVal := b.Get(gk)\n\n\terr = decode(bVal, value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = b.Delete(gk)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = indexDelete(storer, tx, gk, value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc (s *Store) TxDeleteMatching(tx *bolt.Tx, dataType interface{}, query *Query) error {\n\treturn deleteQuery(tx, dataType, query)\n}\n\nfunc (s *Store) DeleteMatching(dataType interface{}, query *Query) error ", "output": "{\n\treturn s.Bolt().Update(func(tx *bolt.Tx) error {\n\t\treturn s.TxDeleteMatching(tx, dataType, query)\n\t})\n}"} {"input": "package incoming\n\nimport (\n\t\"github.com/pkg/errors\"\n)\n\ntype ignorableErr struct {\n\terror\n}\n\nfunc (e ignorableErr) Ignorable() bool {\n\treturn true\n}\n\nfunc wrapIgnorable(err error) error {\n\treturn ignorableErr{error: err}\n}\n\nfunc (m *RuleMap) Get(name string) (*Rule, error) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tif m.rules == nil {\n\t\treturn nil, wrapIgnorable(errors.New(\"rule not found: '\" + name + \"'\"))\n\t}\n\n\tr, ok := m.rules[name]\n\tif !ok {\n\t\treturn nil, wrapIgnorable(errors.New(\"rule not found: '\" + name + \"'\"))\n\t}\n\treturn r, nil\n}\n\n\n\nfunc (r Rule) Disabled() bool {\n\treturn false\n}\n\nfunc (r Rule) AggregationWindow() int64 {\n\treturn 300\n}\n\nfunc (m *RuleMap) Set(name string, r *Rule) ", "output": "{\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tif m.rules == nil {\n\t\tm.rules = make(map[string]*Rule)\n\t}\n\n\tm.rules[name] = r\n}"} {"input": "package v1\n\nimport (\n\t\"net/http\"\n\n\t\"facette.io/httputil\"\n)\n\n\n\nvar libraryTypes = []string{\n\t\"collections\",\n\t\"graphs\",\n\t\"sourcegroups\",\n\t\"metricgroups\",\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (a *API) librarySummary(rw http.ResponseWriter, r *http.Request) ", "output": "{\n\tdefer r.Body.Close()\n\n\tresult := map[string]int{}\n\tfor _, typ := range libraryTypes {\n\t\titem, _ := a.storageItem(typ)\n\n\t\tcount, err := a.storage.SQL().Count(item)\n\t\tif err != nil {\n\t\t\ta.logger.Error(\"failed to fetch count: %s\", err)\n\t\t\thttputil.WriteJSON(rw, newMessage(errUnhandledError), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tresult[typ] = count\n\t}\n\n\thttputil.WriteJSON(rw, result, http.StatusOK)\n}"} {"input": "package denypassword\n\nimport (\n\t\"k8s.io/apiserver/pkg/authentication/authenticator\"\n\t\"k8s.io/apiserver/pkg/authentication/user\"\n)\n\n\ntype denyPasswordAuthenticator struct {\n}\n\n\nfunc New() authenticator.Password {\n\treturn &denyPasswordAuthenticator{}\n}\n\n\n\n\nfunc (a denyPasswordAuthenticator) AuthenticatePassword(username, password string) (user.Info, bool, error) ", "output": "{\n\treturn nil, false, nil\n}"} {"input": "package shared\n\ntype RunTaskError struct {\n\tMessage string\n}\n\nfunc (e RunTaskError) Error() string {\n\treturn \"Error running task: {{.CloudControllerMessage}}\"\n}\n\nfunc (e RunTaskError) Translate(translate func(string, ...interface{}) string) string {\n\treturn translate(e.Error(), map[string]interface{}{\n\t\t\"CloudControllerMessage\": e.Message,\n\t})\n}\n\ntype ClientTargetError struct {\n\tMessage string\n}\n\nfunc (e ClientTargetError) Error() string {\n\treturn \"{{.Message}}\\nNote that this command requires CF API version 3.0.0+.\"\n}\n\n\n\nfunc (e ClientTargetError) Translate(translate func(string, ...interface{}) string) string ", "output": "{\n\treturn translate(e.Error(), map[string]interface{}{\n\t\t\"Message\": e.Message,\n\t})\n}"} {"input": "package trueskill\n\nimport (\n\t\"errors\"\n\t\"math\"\n)\n\nconst (\n\tDefMu = 25.0\n\n\tDefSig = DefMu / 3\n\n\tDefBeta = DefSig / 2\n\n\tDefTau = DefSig / 100\n)\n\n\ntype Game struct {\n\tbeta float64\n\ttau float64\n\tpDraw float64\n}\n\n\nfunc NewDefaultGame() Game {\n\treturn NewGame(DefBeta, DefTau, 0)\n}\n\n\n\n\n\n\n\n\n\nfunc NewGame(beta, tau, pDraw float64) Game {\n\treturn Game{\n\t\tbeta: beta,\n\t\ttau: tau,\n\t\tpDraw: pDraw,\n\t}\n}\n\n\n\nfunc (g *Game) CalcNewRatings(teams []Team, ranks []int) (t []Team, err error) {\n\treturn\n}\n\n\n\n\n\nfunc (g *Game) CalcMatchQuality(teams []Team) (result float64, err error) ", "output": "{\n\tif len(teams) > 2 {\n\t\terr = errors.New(\"CalcMatchQuality does not support more than 2 teams yet.\")\n\t\treturn\n\t}\n\n\tnPlayers := float64(teams[0].Size() + teams[1].Size())\n\n\tt1Mean := teams[0].GetMu()\n\tt1Var := teams[0].GetVar()\n\tt2Mean := teams[1].GetMu()\n\tt2Var := teams[1].GetVar()\n\n\tsqrt := math.Sqrt(\n\t\t(nPlayers * g.beta * g.beta) /\n\t\t\t(nPlayers*g.beta*g.beta + t1Var + t2Var))\n\n\texp := math.Exp(\n\t\t-1 * (t1Mean - t2Mean) * (t1Mean - t2Mean) /\n\t\t\t(2 * (nPlayers*g.beta*g.beta + t1Var + t2Var)))\n\n\tresult = sqrt * exp\n\treturn\n}"} {"input": "package goparser\n\nimport (\n\t\"go/ast\"\n\t\"testing\"\n)\n\nfunc testCmtAgainstExpt(t *testing.T, text, expected string) {\n\tcmt := ast.Comment{\n\t\tText: text,\n\t}\n\n\tresult := CmtToStr(&cmt)\n\n\tif expected != result {\n\t\tt.Errorf(\"Result doesn't match expectation\")\n\t\tt.Errorf(\"Expected:\\n%s\", expected)\n\t\tt.Errorf(\"Get:\\n%s\", result)\n\t}\n}\n\n\n\n\n\nfunc TestCmtToStr2(t *testing.T) {\n\ttestCmtAgainstExpt(t,\n\t\t\"/**\\n\"+\n\t\t\t\" * testing line 1\\n\"+\n\t\t\t\"* testing line 2\\n\"+\n\t\t\t\" * testing line 3\\n\"+\n\t\t\t\" */\",\n\t\t\" testing line 1\\n\"+\n\t\t\t\" testing line 2\\n\"+\n\t\t\t\" testing line 3\\n\")\n}\n\n\nfunc TestCmtToStr3(t *testing.T) {\n\ttestCmtAgainstExpt(t,\n\t\t\"/*\\n\"+\n\t\t\t\" testing line 1\\n\"+\n\t\t\t\" testing line 2\\n\"+\n\t\t\t\" testing line 3\\n\"+\n\t\t\t\"*/\",\n\t\t\" testing line 1\\n\"+\n\t\t\t\" testing line 2\\n\"+\n\t\t\t\" testing line 3\\n\")\n}\n\nfunc TestCmtToStr1(t *testing.T) ", "output": "{\n\ttestCmtAgainstExpt(t,\n\t\t\"//\\n\"+\n\t\t\t\" // testing line 1\\n\"+\n\t\t\t\"//testing line 2\\n\"+\n\t\t\t\"// testing line 3\",\n\t\t\"testing line 1\\n\"+\n\t\t\t\"testing line 2\\n\"+\n\t\t\t\"testing line 3\\n\")\n}"} {"input": "package virtcontainers\n\nimport \"fmt\"\n\ntype bridgeType string\n\nconst (\n\tpciBridge bridgeType = \"pci\"\n\tpcieBridge = \"pcie\"\n)\n\nconst pciBridgeMaxCapacity = 30\n\n\ntype Bridge struct {\n\tAddress map[uint32]string\n\n\tType bridgeType\n\n\tID string\n}\n\n\n\n\n\n\n\nfunc (b *Bridge) removeDevice(ID string) error {\n\tfor addr, devID := range b.Address {\n\t\tif devID == ID {\n\t\t\tdelete(b.Address, addr)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"Unable to hot unplug device %s: not present on bridge\", ID)\n}\n\nfunc (b *Bridge) addDevice(ID string) (uint32, error) ", "output": "{\n\tvar addr uint32\n\n\tfor i := uint32(1); i <= pciBridgeMaxCapacity; i++ {\n\t\tif _, ok := b.Address[i]; !ok {\n\t\t\taddr = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif addr == 0 {\n\t\treturn 0, fmt.Errorf(\"Unable to hot plug device on bridge: there are not empty slots\")\n\t}\n\n\tb.Address[addr] = ID\n\treturn addr, nil\n}"} {"input": "package instructions\n\nimport \"github.com/zxh0/jvm.go/jvmgo/jvm/rtda\"\n\n\ntype iand struct{ NoOperandsInstruction }\n\nfunc (self *iand) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tv2 := stack.PopInt()\n\tv1 := stack.PopInt()\n\tresult := v1 & v2\n\tstack.PushInt(result)\n}\n\n\ntype land struct{ NoOperandsInstruction }\n\n\n\nfunc (self *land) Execute(frame *rtda.Frame) ", "output": "{\n\tstack := frame.OperandStack()\n\tv2 := stack.PopLong()\n\tv1 := stack.PopLong()\n\tresult := v1 & v2\n\tstack.PushLong(result)\n}"} {"input": "package kms\n\nimport (\n\t\"encoding/base64\"\n\t\"fmt\"\n\n\t\"github.com/VirgilSecurity/virgil-sdk-go/v6/crypto/wrapper/phe\"\n\t\"github.com/urfave/cli/v2\"\n\n\t\"github.com/VirgilSecurity/virgil-cli/utils\"\n)\n\n\n\n\nfunc KMSPrivateKey() *cli.Command {\n\treturn &cli.Command{\n\t\tName: \"client-private\",\n\t\tAliases: []string{\"pk\"},\n\t\tUsage: \"Generate a new KMS Client Private key\",\n\t\tAction: func(context *cli.Context) error {\n\t\t\terr := printKMSPrivateKey()\n\t\t\tif err != nil {\n\t\t\t\treturn utils.CliExit(err)\n\t\t\t}\n\t\t\treturn err\n\t\t},\n\t}\n}\n\nfunc GenerateKMSPrivateKey() ([]byte, error) {\n\tkmsClient := phe.NewUokmsClient()\n\tif err := kmsClient.SetupDefaults(); err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\treturn kmsClient.GenerateClientPrivateKey()\n}\n\n\n\nfunc printKMSPrivateKey() error ", "output": "{\n\tkey, err := GenerateKMSPrivateKey()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(base64.StdEncoding.EncodeToString(key))\n\treturn nil\n}"} {"input": "package partner\n\nimport (\n\t\"fmt\"\n\t\"github.com/atnet/gof/app\"\n\t\"github.com/atnet/gof/web\"\n\t\"go2o/app/front\"\n\t\"go2o/app/session\"\n\t\"net/http\"\n)\n\ntype mainC struct {\n\tapp.Context\n\t*front.WebCgi\n}\n\n\nfunc (this *mainC) Index(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"\"))\n}\n\nfunc (this *mainC) Logout(w http.ResponseWriter, r *http.Request) {\n\tsession.LSession.PartnerLogout(w, r)\n\tw.Write([]byte(\"\"))\n}\n\n\n\n\n\nfunc (this *mainC) Summary(w http.ResponseWriter, r *http.Request) {\n\tpt, err := session.LSession.GetCurrentSessionFromCookie(r)\n\tif err != nil {\n\t\treturn\n\t}\n\tthis.Context.Template().Render(w,\n\t\t\"views/partner/summary.html\",\n\t\tfunc(m *map[string]interface{}) {\n\t\t\t(*m)[\"partner\"] = pt\n\t\t\t(*m)[\"loginIp\"] = r.Header.Get(\"USER_ADDRESS\")\n\t\t})\n}\n\nfunc (this *mainC) Upload_post(w http.ResponseWriter, r *http.Request) {\n\tptid, _ := session.LSession.GetPartnerIdFromCookie(r)\n\tr.ParseMultipartForm(20 * 1024 * 1024 * 1024) \n\tfor f, _ := range r.MultipartForm.File {\n\t\tw.Write(this.WebCgi.Upload(f, w, r, fmt.Sprintf(\"%d/item_pic/\", ptid)))\n\t\tbreak\n\t}\n}\n\nfunc (this *mainC) Dashboard(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tpt, err := session.LSession.GetCurrentSessionFromCookie(r)\n\tif err != nil {\n\t\tw.Write([]byte(\"\"))\n\t\treturn\n\t}\n\n\tvar mf web.TemplateMapFunc = func(m *map[string]interface{}) {\n\t\t(*m)[\"partner\"] = pt\n\t\t(*m)[\"loginIp\"] = r.Header.Get(\"USER_ADDRESS\")\n\t}\n\tthis.Context.Template().Render(w, \"views/partner/dashboard.html\", mf)\n}"} {"input": "package printers\n\nimport (\n\t\"io\"\n\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\n\n\n\nfunc NewDiscardingPrinter() ResourcePrinterFunc ", "output": "{\n\treturn ResourcePrinterFunc(func(runtime.Object, io.Writer) error {\n\t\treturn nil\n\t})\n}"} {"input": "package main\n\nimport \"github.com/nsf/termbox-go\"\n\ntype Input struct {\n\tendKey termbox.Key\n\teventQ chan termbox.Event\n\tctrl chan bool\n}\n\nfunc NewInput() *Input {\n\treturn &Input{\n\t\tendKey: termbox.KeyCtrlC,\n\t\teventQ: make(chan termbox.Event),\n\t\tctrl: make(chan bool, 2),\n\t}\n}\n\nfunc (i *Input) Start() {\n\tgo poll(i)\n}\n\n\n\nfunc poll(i *Input) {\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-i.ctrl:\n\t\t\tbreak loop\n\t\tdefault:\n\t\t\ti.eventQ <- termbox.PollEvent()\n\t\t}\n\t}\n}\n\nfunc (i *Input) Stop() ", "output": "{\n\ti.ctrl <- true\n}"} {"input": "package server\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\n\n\nfunc ListenAndServe(server *http.Server, logger *logrus.Entry, startupMessage string) ", "output": "{\n\tgo func() {\n\t\tlogger.Info(startupMessage)\n\t\tif err := server.ListenAndServe(); err != nil {\n\t\t\tlogger.WithError(err).Error(\"cannot start HTTP server\")\n\t\t}\n\t}()\n\tsig := make(chan os.Signal, 1)\n\tsignal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)\n\tselect {\n\tcase <-sig:\n\t\tlogger.Info(\"stopping HTTP server\")\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\terr := server.Shutdown(ctx)\n\tif err != nil {\n\t\tlogger.WithError(err).Fatal(\"cannot shutdown server\")\n\t}\n}"} {"input": "package datacatalog\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteCustomPropertyRequest struct {\n\n\tCatalogId *string `mandatory:\"true\" contributesTo:\"path\" name:\"catalogId\"`\n\n\tNamespaceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"namespaceId\"`\n\n\tCustomPropertyKey *string `mandatory:\"true\" contributesTo:\"path\" name:\"customPropertyKey\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteCustomPropertyRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteCustomPropertyRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request DeleteCustomPropertyRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteCustomPropertyResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteCustomPropertyResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteCustomPropertyResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteCustomPropertyRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package fake\n\nimport (\n\tclientset \"github.com/openshift/client-go/oauth/clientset/versioned\"\n\toauthv1 \"github.com/openshift/client-go/oauth/clientset/versioned/typed/oauth/v1\"\n\tfakeoauthv1 \"github.com/openshift/client-go/oauth/clientset/versioned/typed/oauth/v1/fake\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/watch\"\n\t\"k8s.io/client-go/discovery\"\n\tfakediscovery \"k8s.io/client-go/discovery/fake\"\n\t\"k8s.io/client-go/testing\"\n)\n\n\n\n\n\nfunc NewSimpleClientset(objects ...runtime.Object) *Clientset {\n\to := testing.NewObjectTracker(scheme, codecs.UniversalDecoder())\n\tfor _, obj := range objects {\n\t\tif err := o.Add(obj); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tfakePtr := testing.Fake{}\n\tfakePtr.AddReactor(\"*\", \"*\", testing.ObjectReaction(o))\n\tfakePtr.AddWatchReactor(\"*\", testing.DefaultWatchReactor(watch.NewFake(), nil))\n\n\treturn &Clientset{fakePtr, &fakediscovery.FakeDiscovery{Fake: &fakePtr}}\n}\n\n\n\n\ntype Clientset struct {\n\ttesting.Fake\n\tdiscovery *fakediscovery.FakeDiscovery\n}\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\treturn c.discovery\n}\n\nvar _ clientset.Interface = &Clientset{}\n\n\n\n\n\nfunc (c *Clientset) Oauth() oauthv1.OauthV1Interface {\n\treturn &fakeoauthv1.FakeOauthV1{Fake: &c.Fake}\n}\n\nfunc (c *Clientset) OauthV1() oauthv1.OauthV1Interface ", "output": "{\n\treturn &fakeoauthv1.FakeOauthV1{Fake: &c.Fake}\n}"} {"input": "package models\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/hex\"\n\t\"time\"\n)\n\nconst (\n\tNonceBytes = 32\n)\n\ntype Nonce struct {\n\tId string `db:\"id\" json:\"-\"`\n\tExpiresAt time.Time `db:\"expires_at\" json:\"expires_at\"`\n\tNonce string `db:\"nonce\" json:\"nonce\"`\n}\n\nfunc CreateNonce() (*Nonce, error) {\n\tn, err := generate()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := &Nonce{\n\t\tExpiresAt: time.Now().Add(10 * time.Minute),\n\t\tNonce: n,\n\t}\n\terr = Db.Insert(nonce)\n\treturn nonce, err\n}\n\n\n\nfunc NonceValid(nonce string) bool {\n\tid, err := Db.SelectNullStr(\n\t\t\"select id from nonces where nonce = $1 and expires_at > $2 limit 1\",\n\t\tnonce, time.Now(),\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif !id.Valid {\n\t\treturn false\n\t}\n\n\t_, err = Db.Exec(\"delete from nonces where id=$1\", id.String)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn true\n}\n\nfunc generate() (string, error) ", "output": "{\n\tb := make([]byte, NonceBytes)\n\t_, err := rand.Read(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tstr := hex.EncodeToString(b)\n\treturn string(str[:NonceBytes]), nil\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com/onsi/gomega/format\"\n)\n\ntype BeElementOfMatcher struct {\n\tElements []interface{}\n}\n\nfunc (matcher *BeElementOfMatcher) Match(actual interface{}) (success bool, err error) {\n\tif reflect.TypeOf(actual) == nil {\n\t\treturn false, fmt.Errorf(\"BeElement matcher expects actual to be typed\")\n\t}\n\n\tvar lastError error\n\tfor _, m := range flatten(matcher.Elements) {\n\t\tmatcher := &EqualMatcher{Expected: m}\n\t\tsuccess, err := matcher.Match(actual)\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\tcontinue\n\t\t}\n\t\tif success {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, lastError\n}\n\nfunc (matcher *BeElementOfMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"to be an element of\", presentable(matcher.Elements))\n}\n\n\n\nfunc (matcher *BeElementOfMatcher) NegatedFailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn format.Message(actual, \"not to be an element of\", presentable(matcher.Elements))\n}"} {"input": "package gomposer\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nfunc Test_Remove_Deletes_Folder(t *testing.T) {\n\tvendorDir := os.TempDir() + \"/vendors\"\n\tdirName := vendorDir + \"/symfony/symfony\"\n\tos.MkdirAll(dirName, 0744)\n\tv := ComposerPackage{\n\t\tName: \"symfony/symfony\",\n\t}\n\tRemove(vendorDir, v)\n\n\tif _, err := os.Stat(dirName); !os.IsNotExist(err) {\n\t\tt.Errorf(\"Failed to delete %v\", dirName)\n\t}\n}\n\nfunc Test_Remove_Deletes_Parent_Folder(t *testing.T) {\n\tvendorDir := os.TempDir() + \"/vendors\"\n\tdirName := vendorDir + \"/symfony\"\n\tos.MkdirAll(dirName+\"/symfony\", 0744)\n\tv := ComposerPackage{\n\t\tName: \"symfony/symfony\",\n\t}\n\tRemove(vendorDir, v)\n\n\tif _, err := os.Stat(dirName); !os.IsNotExist(err) {\n\t\tt.Errorf(\"Failed to delete %v\", dirName)\n\t}\n}\n\n\n\nfunc Test_Remove_Keeps_Parent_Folder_When_Not_Empty(t *testing.T) ", "output": "{\n\tvendorDir := os.TempDir() + \"/vendors\"\n\tdirName := vendorDir + \"/symfony\"\n\tos.MkdirAll(dirName+\"/symfony\", 0744)\n\tfp, err := os.Create(dirName + \"/remove_deletes_parent_folder\")\n\n\tif err != nil {\n\t\tt.Errorf(\"%v\", err)\n\t}\n\n\tfp.Write([]byte(\"hello world\"))\n\tv := ComposerPackage{\n\t\tName: \"symfony/symfony\",\n\t}\n\tRemove(vendorDir, v)\n\n\tif _, err := os.Stat(dirName); os.IsNotExist(err) {\n\t\tt.Errorf(\"Failed to keep %v when not empty\", dirName)\n\t}\n\tos.Remove(dirName + \"/remove_deletes_parent_folder\")\n}"} {"input": "package speech_test\n\nimport (\n\t\"io\"\n\n\t\"cloud.google.com/go/speech/apiv1beta1\"\n\t\"github.com/golang/protobuf/ptypes\"\n\t\"golang.org/x/net/context\"\n\tspeechpb \"google.golang.org/genproto/googleapis/cloud/speech/v1beta1\"\n)\n\nfunc ExampleNewClient() {\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\nfunc ExampleClient_SyncRecognize() {\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &speechpb.SyncRecognizeRequest{\n\t}\n\tresp, err := c.SyncRecognize(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\n\n\nfunc StreamingRecognize() {\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\tstream, err := c.StreamingRecognize(ctx)\n\tif err != nil {\n\t}\n\tgo func() {\n\t\treqs := []*speechpb.StreamingRecognizeRequest{\n\t\t}\n\t\tfor _, req := range reqs {\n\t\t\tif err := stream.Send(req); err != nil {\n\t\t\t}\n\t\t}\n\t\tstream.CloseSend()\n\t}()\n\tfor {\n\t\tresp, err := stream.Recv()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}\n\nfunc ExampleClient_AsyncRecognize() ", "output": "{\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &speechpb.AsyncRecognizeRequest{\n\t}\n\top, err := c.AsyncRecognize(ctx, req)\n\tif err != nil {\n\t}\n\n\tvar resp ptypes.DynamicAny \n\tif err := op.Wait(ctx, &resp); err != nil {\n\t}\n}"} {"input": "package glib\n\n\n\n\n\nimport \"C\"\nimport \"unsafe\"\n\n\n\ntype IActionMap interface {\n\tNative() uintptr\n\n\tLookupAction(actionName string) *Action\n\tAddAction(action IAction)\n\tRemoveAction(actionName string)\n}\n\n\ntype ActionMap struct {\n\t*Object\n}\n\n\n\n\n\nfunc (v *ActionMap) native() *C.GActionMap {\n\tif v == nil || v.GObject == nil {\n\t\treturn nil\n\t}\n\treturn C.toGActionMap(unsafe.Pointer(v.GObject))\n}\n\nfunc (v *ActionMap) Native() uintptr {\n\treturn uintptr(unsafe.Pointer(v.native()))\n}\n\nfunc marshalActionMap(p uintptr) (interface{}, error) {\n\tc := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))\n\treturn wrapActionMap(wrapObject(unsafe.Pointer(c))), nil\n}\n\nfunc wrapActionMap(obj *Object) *ActionMap {\n\treturn &ActionMap{obj}\n}\n\n\nfunc (v *ActionMap) LookupAction(actionName string) *Action {\n\tc := C.g_action_map_lookup_action(v.native(), (*C.gchar)(C.CString(actionName)))\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn wrapAction(wrapObject(unsafe.Pointer(c)))\n}\n\n\nfunc (v *ActionMap) AddAction(action IAction) {\n\tC.g_action_map_add_action(v.native(), action.toGAction())\n}\n\n\n\n\nfunc (v *ActionMap) RemoveAction(actionName string) ", "output": "{\n\tC.g_action_map_remove_action(v.native(), (*C.gchar)(C.CString(actionName)))\n}"} {"input": "package pathdb\n\nimport (\n\t\"github.com/scionproto/scion/go/lib/common\"\n\t\"github.com/scionproto/scion/go/lib/ctrl/seg\"\n\t\"github.com/scionproto/scion/go/lib/pathdb/conn\"\n\t\"github.com/scionproto/scion/go/lib/pathdb/query\"\n\t\"github.com/scionproto/scion/go/lib/pathdb/sqlite\"\n)\n\ntype DB struct {\n\tconn conn.Conn\n}\n\n\n\nfunc New(path string, backend string) (*DB, error) {\n\tdb := &DB{}\n\tvar err error\n\tswitch backend {\n\tcase \"sqlite\":\n\t\tdb.conn, err = sqlite.New(path)\n\tdefault:\n\t\treturn nil, common.NewBasicError(\"Unknown backend\", nil, \"backend\", backend)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn db, nil\n}\n\n\n\nfunc (db *DB) Insert(pseg *seg.PathSegment, segTypes []seg.Type) (int, error) {\n\treturn db.conn.Insert(pseg, segTypes)\n}\n\n\n\n\n\n\n\nfunc (db *DB) Delete(segID common.RawBytes) (int, error) {\n\treturn db.conn.Delete(segID)\n}\n\n\n\nfunc (db *DB) DeleteWithIntf(intf query.IntfSpec) (int, error) {\n\treturn db.conn.DeleteWithIntf(intf)\n}\n\n\nfunc (db *DB) Get(params *query.Params) ([]*query.Result, error) {\n\treturn db.conn.Get(params)\n}\n\nfunc (db *DB) InsertWithHPCfgIDs(pseg *seg.PathSegment,\n\tsegTypes []seg.Type, hpCfgIDs []*query.HPCfgID) (int, error) ", "output": "{\n\treturn db.conn.InsertWithHPCfgIDs(pseg, segTypes, hpCfgIDs)\n}"} {"input": "package replication\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\tclient \"k8s.io/kubernetes/pkg/client/unversioned\"\n)\n\n\nfunc updateReplicaCount(rcClient client.ReplicationControllerInterface, controller api.ReplicationController, numReplicas int) (updateErr error) {\n\tif controller.Status.Replicas == numReplicas &&\n\t\tcontroller.Generation == controller.Status.ObservedGeneration {\n\t\treturn nil\n\t}\n\tgeneration := controller.Generation\n\n\tvar getErr error\n\tfor i, rc := 0, &controller; ; i++ {\n\t\tglog.V(4).Infof(\"Updating replica count for rc: %v, %d->%d (need %d), sequence No: %v->%v\",\n\t\t\tcontroller.Name, controller.Status.Replicas, numReplicas, controller.Spec.Replicas, controller.Status.ObservedGeneration, generation)\n\n\t\trc.Status = api.ReplicationControllerStatus{Replicas: numReplicas, ObservedGeneration: generation}\n\t\t_, updateErr = rcClient.UpdateStatus(rc)\n\t\tif updateErr == nil || i >= statusUpdateRetries {\n\t\t\treturn updateErr\n\t\t}\n\t\tif rc, getErr = rcClient.Get(controller.Name); getErr != nil {\n\t\t\treturn getErr\n\t\t}\n\t}\n}\n\n\ntype OverlappingControllers []api.ReplicationController\n\nfunc (o OverlappingControllers) Len() int { return len(o) }\nfunc (o OverlappingControllers) Swap(i, j int) { o[i], o[j] = o[j], o[i] }\n\n\n\nfunc (o OverlappingControllers) Less(i, j int) bool ", "output": "{\n\tif o[i].CreationTimestamp.Equal(o[j].CreationTimestamp) {\n\t\treturn o[i].Name < o[j].Name\n\t}\n\treturn o[i].CreationTimestamp.Before(o[j].CreationTimestamp)\n}"} {"input": "package store\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"text/tabwriter\"\n\t\"time\"\n)\n\ntype Metadata map[string]string\n\ntype Entry struct {\n\tName string `json:\"name\"`\n\tPassword []byte `json:\"password\"`\n\tCtime time.Time `json:\"ctime\"` \n\tMtime time.Time `json:\"mtime\"` \n\tMetadata Metadata `json:\"metadata\"` \n}\n\nfunc NewEntry() *Entry {\n\treturn &Entry{\n\t\tMetadata: make(Metadata),\n\t\tCtime: getCurrentTime(),\n\t\tMtime: getCurrentTime(),\n\t}\n}\n\n\n\nfunc (e *Entry) Touch() {\n\te.Mtime = getCurrentTime()\n}\n\nfunc (e Entry) String() string {\n\tb := new(bytes.Buffer)\n\tw := tabwriter.NewWriter(b, 0, 0, 0, ' ', 0)\n\n\tvalof := reflect.ValueOf(e)\n\tfor i := 0; i < valof.NumField(); i++ {\n\t\tswitch val := valof.Field(i).Interface().(type) {\n\t\tdefault:\n\t\t\ttag := valof.Type().Field(i).Tag.Get(\"json\")\n\t\t\tfmt.Fprintf(w, \"%s\\t : %s\\n\", tag, val)\n\t\tcase Metadata:\n\t\t\tfor k, v := range val {\n\t\t\t\tfmt.Fprintf(w, \"%s\\t : %s\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\n\tw.Flush()\n\treturn b.String()\n}\n\nfunc (m Metadata) String() string {\n\tvar b bytes.Buffer\n\tfor k, v := range m {\n\t\tfmt.Fprintf(&b, \"%s:%s\", k, v)\n\t}\n\treturn b.String()\n}\n\nfunc getCurrentTime() time.Time {\n\treturn time.Now().Truncate(time.Second)\n}\n\nfunc (e *Entry) Age() time.Duration ", "output": "{\n\treturn time.Since(e.Mtime)\n}"} {"input": "package quickbooks\n\nimport \"fmt\"\n\n\ntype ErrorObject struct {\n\tFault fault `json:\"Fault\"`\n\tTime string `json:\"time\"`\n}\n\ntype fault struct {\n\tError []faultError `json:\"Error\"`\n\tType string `json:\"type\"`\n}\n\ntype faultError struct {\n\tMessage string `json:\"Message\"`\n\tDetail string `json:\"Detail\"`\n\tCode string `json:\"code\"`\n\tElement string `json:\"element\"`\n}\n\n\nfunc (e ErrorObject) Error() string {\n\terrStr := fmt.Sprintf(\"Type: %s Code: %s Message: %s\", e.Fault.Type, e.Fault.Error[0].Code, e.Fault.Error[0].Message)\n\treturn errStr\n}\n\n\ntype SDKError struct {\n\tType string\n\tCode string\n\tMessage string\n}\n\n\n\n\n\nfunc (e SDKError) New(errorType string, errorCode string, errorMessage string) SDKError {\n\treturn SDKError{errorType, errorCode, errorMessage}\n}\n\nfunc (e SDKError) Error() string ", "output": "{\n\terrStr := fmt.Sprintf(\"Type: %s Code: %s Message: %s\", e.Type, e.Code, e.Message)\n\treturn errStr\n}"} {"input": "package repodelete\n\nvar Usage = []string{\"rt rdel \"}\n\n\n\nfunc GetArguments() string {\n\treturn `\trepository pattern\n\t\tSpecifies the repositories that should be removed. You can use wildcards to specify multiple repositories.`\n}\n\nfunc GetDescription() string ", "output": "{\n\treturn \"Permanently delete repositories with all of their content from Artifactory.\"\n}"} {"input": "package helpers\n\nimport (\n\t\"fmt\"\n\t\"os/user\"\n\t\"os\"\n\t\"runtime\"\n\t\"time\"\n\t\"log\"\n\t\"github.com/joho/godotenv\"\n)\n\nfunc CurrentUser() *user.User {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tSendErrorEmail(\"golang balu\", fmt.Sprintf(\"failed get current user: %s\", err))\n\t\tpanic(err)\n\t}\n\treturn usr\n}\n\nfunc IsDocker() bool {\n\treturn os.Getenv(\"HOME\") == \"/root\"\n}\n\n\n\nfunc LoadEnvFile() {\n\terr := godotenv.Load()\n\tif err != nil {\n\t\tpanic(\"Error loading .env file\" + err.Error())\n\t}\n}\n\nfunc MonitorRuntime() ", "output": "{\n\tlog.Println(\"Number of CPUs:\", runtime.NumCPU())\n\tm := &runtime.MemStats{}\n\tfor {\n\t\tr := runtime.NumGoroutine()\n\t\tlog.Println(\"Number of goroutines\", r)\n\t\truntime.ReadMemStats(m)\n\t\tlog.Println(\"Allocated memory\", m.Alloc)\n\t\ttime.Sleep(10 * time.Second)\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype RemoveNetworkSecurityGroupSecurityRulesRequest struct {\n\n\tNetworkSecurityGroupId *string `mandatory:\"true\" contributesTo:\"path\" name:\"networkSecurityGroupId\"`\n\n\tRemoveNetworkSecurityGroupSecurityRulesDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype RemoveNetworkSecurityGroupSecurityRulesResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response RemoveNetworkSecurityGroupSecurityRulesResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response RemoveNetworkSecurityGroupSecurityRulesResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package testutil\n\nimport (\n\t\"testing\"\n\n\tci \"gx/ipfs/QmP1DfoUjiWH2ZBo1PBH6FupdBucbDepx3HpWmEY6JMUpY/go-libp2p-crypto\"\n\tma \"gx/ipfs/QmcyqRMCAXVtYPS4DiBrA7sezL9rRGfW8Ctx7cywL4TXJj/go-multiaddr\"\n\tpeer \"gx/ipfs/QmdS9KpbDyPrieswibZhkod1oXqRwZJrUPzxCofAMWpFGq/go-libp2p-peer\"\n)\n\ntype Identity interface {\n\tAddress() ma.Multiaddr\n\tID() peer.ID\n\tPrivateKey() ci.PrivKey\n\tPublicKey() ci.PubKey\n}\n\n\n\nfunc RandIdentity() (Identity, error) {\n\tp, err := RandPeerNetParams()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &identity{*p}, nil\n}\n\nfunc RandIdentityOrFatal(t *testing.T) Identity {\n\tp, err := RandPeerNetParams()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn &identity{*p}\n}\n\n\ntype identity struct {\n\tPeerNetParams\n}\n\nfunc (p *identity) ID() peer.ID {\n\treturn p.PeerNetParams.ID\n}\n\nfunc (p *identity) Address() ma.Multiaddr {\n\treturn p.Addr\n}\n\nfunc (p *identity) PrivateKey() ci.PrivKey {\n\treturn p.PrivKey\n}\n\n\n\nfunc (p *identity) PublicKey() ci.PubKey ", "output": "{\n\treturn p.PubKey\n}"} {"input": "package lib\n\nimport (\n\t\"log\"\n\t\"strings\"\n)\n\ntype (\n\tQuestion struct {\n\t\tRelatesTo struct {\n\t\t\tAnswers []string `json:\"answers\"`\n\t\t\tSave bool `json:\"save\"`\n\t\t\tSaveTag string `json:\"saveTag\"`\n\t\t} `json:\"relatesTo\"`\n\t\tContext []string `json:\"context\"`\n\t\tQuestionText string `json:\"question\"`\n\t\tPossibleAnswers []string `json:\"answers\"`\n\t}\n\n\tQuestions []*Question\n)\n\nfunc (this Questions) First() *Question {\n\tif len(this) > 0 {\n\t\treturn this[0]\n\t}\n\treturn nil\n}\n\nfunc (this Questions) next(prevAnswer string) (*Question, bool) {\n\tfor i := range this {\n\t\tfor a := range this[i].RelatesTo.Answers {\n\t\t\tif strings.EqualFold(this[i].RelatesTo.Answers[a], prevAnswer) {\n\t\t\t\treturn this[i], this[i].RelatesTo.Save\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc (this Questions) nextFrom(prevAnswers ...string) (*Question, bool) {\n\tfor i := range prevAnswers {\n\t\tif nxt, sv := this.next(prevAnswers[i]); nxt != nil {\n\t\t\tlog.Println(\"got it from sticker ...\")\n\t\t\treturn nxt, sv\n\t\t}\n\t}\n\treturn nil, false\n}\n\n\n\nfunc (this *Question) makeKeyboard() Keyboard ", "output": "{\n\tkeyboard := Keyboard{}\n\tfor i := range this.PossibleAnswers {\n\t\tkeyboard = append(keyboard, []string{this.PossibleAnswers[i]})\n\t}\n\treturn keyboard\n}"} {"input": "package log\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"sync\"\n)\n\nconst (\n\tSilent int = iota\n\tError\n\tInfo\n\tDebug\n)\n\n\nvar (\n\tlevel = Error\n\tlock sync.Mutex\n)\n\n\nfunc SetLevel(l int) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tlevel = l\n}\n\n\nfunc Infof(format string, args ...interface{}) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif level < Info {\n\t\treturn\n\t}\n\n\tmsg := fmt.Sprintf(\"INFO: %s\", format)\n\tif len(args) > 0 {\n\t\tmsg = fmt.Sprintf(msg, args...)\n\t}\n\n\tlog.Println(msg)\n}\n\n\n\n\n\nfunc Errorf(format string, args ...interface{}) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif level < Error {\n\t\treturn\n\t}\n\n\tmsg := fmt.Sprintf(\"ERROR: %s\", format)\n\tif len(args) > 0 {\n\t\tmsg = fmt.Sprintf(msg, args...)\n\t}\n\n\tlog.Println(msg)\n}\n\nfunc Debugf(format string, args ...interface{}) ", "output": "{\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif level < Debug {\n\t\treturn\n\t}\n\n\tmsg := fmt.Sprintf(\"DEBUG: %s\", format)\n\tif len(args) > 0 {\n\t\tmsg = fmt.Sprintf(msg, args...)\n\t}\n\n\tlog.Println(msg)\n}"} {"input": "package operator\n\nimport (\n\t\"testing\"\n\n\t\"github.com/rook/rook/pkg/operator/test\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\nfunc TestCreateCluster(t *testing.T) {\n\tclientset := test.New(3)\n\to := New(\"foo\", nil, clientset)\n\to.context.RetryDelay = 1\n\n\terr := o.initResources()\n\tassert.NotNil(t, err)\n\n\ttest := &testTPR{}\n\terr = createTPR(o.context, test)\n\tassert.Nil(t, err)\n\ttpr, err := clientset.ExtensionsV1beta1().ThirdPartyResources().List(v1.ListOptions{})\n\tassert.Nil(t, err)\n\tassert.Equal(t, 1, len(tpr.Items))\n\tassert.Equal(t, \"test.rook.io\", tpr.Items[0].Name)\n\tassert.Equal(t, test.Description(), tpr.Items[0].Description)\n\n}\n\ntype testTPR struct {\n}\n\nfunc (t *testTPR) Name() string {\n\treturn \"test\"\n}\nfunc (t *testTPR) Description() string {\n\treturn \"test description\"\n}\nfunc (t *testTPR) Load() error {\n\treturn nil\n}\n\n\nfunc (t *testTPR) Watch() error ", "output": "{\n\treturn nil\n}"} {"input": "package ircbotint\n\nimport (\n \"strings\"\n \"fmt\"\n \"net/http\"\n \"io/ioutil\"\n)\n\nvar httpUrl string\n\n\n\nfunc SetHttpUrl(url string) {\n url = strings.Trim(url, \"/\")\n url = fmt.Sprintf(\"%s/\", url)\n httpUrl = url\n}\n\n\n\n\n\nfunc CallHttp(param1, param2 string) (string, error) ", "output": "{\n var r *http.Response\n var err error\n var s string\n var ba []byte\n\n if len(param2) > 0 {\n s = fmt.Sprintf(\"%s%s/%s\", httpUrl, param1, param2)\n } else {\n s = fmt.Sprintf(\"%s%s\", httpUrl, param1)\n }\n\n r, err = http.Get(s)\n if err != nil {\n return \"\", err\n }\n\n ba, err = ioutil.ReadAll(r.Body)\n r.Body.Close()\n\n if err != nil {\n return \"\", err\n }\n\n s = string(ba)\n\n return s, nil\n}"} {"input": "package operation\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n\n\t\"github.com/cloudspannerecosystem/gcsb/pkg/config\"\n\t\"github.com/cloudspannerecosystem/gcsb/pkg/generator/selector\"\n)\n\ntype (\n\tOperation int\n)\n\nconst (\n\tREAD Operation = 1 + iota\n\tWRITE\n)\n\n\n\nfunc NewOperationSelector(cfg *config.Config) (selector.Selector, error) ", "output": "{\n\treturn selector.NewWeightedRandomSelector(\n\t\trand.New(rand.NewSource(time.Now().UnixNano())),\n\t\tselector.NewWeightedChoice(READ, uint(cfg.Operations.Read)),\n\t\tselector.NewWeightedChoice(WRITE, uint(cfg.Operations.Write)),\n\t)\n}"} {"input": "package disk\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/object\"\n)\n\ntype shrink struct {\n\t*flags.DatastoreFlag\n\n\tcopy *bool\n}\n\nfunc init() {\n\tcli.Register(\"datastore.disk.shrink\", &shrink{})\n}\n\nfunc (cmd *shrink) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)\n\tcmd.DatastoreFlag.Register(ctx, f)\n\n\tf.Var(flags.NewOptionalBool(&cmd.copy), \"copy\", \"Perform shrink in-place mode if false, copy-shrink mode otherwise\")\n}\n\nfunc (cmd *shrink) Process(ctx context.Context) error {\n\treturn cmd.DatastoreFlag.Process(ctx)\n}\n\nfunc (cmd *shrink) Usage() string {\n\treturn \"VMDK\"\n}\n\nfunc (cmd *shrink) Description() string {\n\treturn `Shrink VMDK on DS.\n\nExamples:\n govc datastore.disk.shrink disks/disk1.vmdk`\n}\n\n\n\nfunc (cmd *shrink) Run(ctx context.Context, f *flag.FlagSet) error ", "output": "{\n\tdc, err := cmd.Datacenter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tds, err := cmd.Datastore()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm := object.NewVirtualDiskManager(ds.Client())\n\tpath := ds.Path(f.Arg(0))\n\ttask, err := m.ShrinkVirtualDisk(ctx, path, dc, cmd.copy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger := cmd.ProgressLogger(fmt.Sprintf(\"Shrinking %s...\", path))\n\tdefer logger.Wait()\n\n\t_, err = task.WaitForResult(ctx, logger)\n\treturn err\n}"} {"input": "package dnsrecorder\n\nimport (\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n)\n\n\n\n\n\n\n\ntype Recorder struct {\n\tdns.ResponseWriter\n\tRcode int\n\tSize int\n\tMsg *dns.Msg\n\tStart time.Time\n}\n\n\n\n\nfunc New(w dns.ResponseWriter) *Recorder {\n\treturn &Recorder{\n\t\tResponseWriter: w,\n\t\tRcode: 0,\n\t\tMsg: nil,\n\t\tStart: time.Now(),\n\t}\n}\n\n\n\n\n\n\nfunc (r *Recorder) Write(buf []byte) (int, error) {\n\tn, err := r.ResponseWriter.Write(buf)\n\tif err == nil {\n\t\tr.Size += n\n\t}\n\treturn n, err\n}\n\n\n\nfunc (r *Recorder) Hijack() { r.ResponseWriter.Hijack(); return }\n\nfunc (r *Recorder) WriteMsg(res *dns.Msg) error ", "output": "{\n\tr.Rcode = res.Rcode\n\tr.Size += res.Len()\n\tr.Msg = res\n\treturn r.ResponseWriter.WriteMsg(res)\n}"} {"input": "package util\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/digitalocean/godo\"\n)\n\nconst (\n\tactiveFailure = 3\n)\n\n\n\n\nfunc WaitForActive(ctx context.Context, client *godo.Client, monitorURI string) error ", "output": "{\n\tif len(monitorURI) == 0 {\n\t\treturn fmt.Errorf(\"create had no monitor uri\")\n\t}\n\n\tcompleted := false\n\tfailCount := 0\n\tfor !completed {\n\t\taction, _, err := client.DropletActions.GetByURI(ctx, monitorURI)\n\n\t\tif err != nil {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn err\n\t\t\tdefault:\n\t\t\t}\n\t\t\tif failCount <= activeFailure {\n\t\t\t\tfailCount++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\tswitch action.Status {\n\t\tcase godo.ActionInProgress:\n\t\t\tselect {\n\t\t\tcase <-time.After(5 * time.Second):\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase godo.ActionCompleted:\n\t\t\tcompleted = true\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"unknown status: [%s]\", action.Status)\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package iso20022\n\n\ntype SettlementDateTimeIndication1 struct {\n\n\tDebitDateTime *ISODateTime `xml:\"DbtDtTm,omitempty\"`\n\n\tCreditDateTime *ISODateTime `xml:\"CdtDtTm,omitempty\"`\n}\n\n\n\nfunc (s *SettlementDateTimeIndication1) SetCreditDateTime(value string) {\n\ts.CreditDateTime = (*ISODateTime)(&value)\n}\n\nfunc (s *SettlementDateTimeIndication1) SetDebitDateTime(value string) ", "output": "{\n\ts.DebitDateTime = (*ISODateTime)(&value)\n}"} {"input": "package vauth\n\nimport (\n\t\"crypto/subtle\"\n)\n\n\n\n\nfunc SecureCompare(x string, y string) bool ", "output": "{\n\tif len(x) != len(y) {\n\t\treturn false\n\t}\n\n\treturn subtle.ConstantTimeCompare([]byte(x), []byte(y)) == 1\n}"} {"input": "package master\n\nimport ()\n\n\n\ntype frame struct {\n\tjob *job\n\tslaveName string\n\tframe int\n\tdata []byte\n\tprogress byte\n\tcompleted bool\n}\n\n\n\nfunc NewFrame(job *job, fr int) *frame {\n\treturn &frame{\n\t\tjob: job,\n\t\tslaveName: \"\",\n\t\tframe: fr,\n\t\tdata: nil,\n\t\tprogress: 0,\n\t\tcompleted: false,\n\t}\n}\n\n\n\nfunc (f *frame) Job() *job {\n\treturn f.job\n}\n\nfunc (f *frame) SlaveName() string {\n\treturn f.slaveName\n}\n\n\n\nfunc (f *frame) AlignedFrame() int {\n\treturn f.frame + f.Job().Start()\n}\n\nfunc (f *frame) Data() []byte {\n\treturn f.data\n}\n\nfunc (f *frame) Progress() byte {\n\treturn f.progress\n}\n\nfunc (f *frame) Completed() bool {\n\treturn f.completed\n}\n\nfunc (f *frame) File() []byte {\n\treturn f.Job().File()\n}\n\n\n\nfunc (f *frame) SetSlaveName(slaveName string) {\n\tf.slaveName = slaveName\n}\n\nfunc (f *frame) SetData(data []byte) {\n\tf.data = data\n}\n\nfunc (f *frame) SetProgress(progress byte) {\n\tf.progress = progress\n}\n\nfunc (f *frame) SetCompleted(completed bool) {\n\tf.completed = completed\n\tif completed {\n\t\tf.SetProgress(100)\n\t}\n}\n\n\n\nfunc (f *frame) Reset() {\n\tf.SetSlaveName(\"\")\n\tf.SetData(nil)\n\tf.SetProgress(0)\n\tf.SetCompleted(false)\n}\n\nfunc (f *frame) Frame() int ", "output": "{\n\treturn f.frame\n}"} {"input": "package ui\n\nimport (\n\t\"github.com/studentkittens/eulenfunk/display\"\n)\n\n\n\n\ntype Menu struct {\n\tName string\n\n\tEntries []Entry\n\n\tCursor int\n\n\tlw *display.LineWriter\n}\n\n\n\nfunc NewMenu(name string, lw *display.LineWriter) (*Menu, error) {\n\treturn &Menu{\n\t\tName: name,\n\t\tlw: lw,\n\t}, nil\n}\n\nfunc (mn *Menu) scrollToNextSelectable(up bool) {\n\tfor mn.Cursor >= 0 && mn.Cursor < len(mn.Entries) && !mn.Entries[mn.Cursor].Selectable() {\n\t\tif up {\n\t\t\tmn.Cursor++\n\t\t} else {\n\t\t\tmn.Cursor--\n\t\t}\n\t}\n\n\tif mn.Cursor < 0 {\n\t\tmn.Cursor = 0\n\t}\n\n\tif mn.Cursor >= len(mn.Entries) {\n\t\tmn.Cursor = len(mn.Entries) - 1\n\t}\n}\n\n\nfunc (mn *Menu) Scroll(move int) {\n\tmn.Cursor += move\n\n\tup := move >= 0\n\tmn.scrollToNextSelectable(up)\n\n\tif !mn.Entries[mn.Cursor].Selectable() {\n\t\tmn.scrollToNextSelectable(!up)\n\t}\n}\n\n\n\n\n\nfunc (mn *Menu) Click() error {\n\tif len(mn.Entries) == 0 {\n\t\treturn nil\n\t}\n\n\treturn mn.Entries[mn.Cursor].Action()\n}\n\nfunc (mn *Menu) Display(width int) error ", "output": "{\n\tfor pos, ClickEntry := range mn.Entries {\n\t\tline := ClickEntry.Render(width, pos == mn.Cursor)\n\t\tif err := mn.lw.Line(mn.Name, pos, line); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package redis\n\nimport (\n\t\"github.com/fagongzi/goetty\"\n)\n\ntype redisDecoder struct {\n}\n\n\nfunc NewRedisDecoder() goetty.Decoder {\n\treturn &redisDecoder{}\n}\n\n\nfunc (decoder *redisDecoder) Decode(in *goetty.ByteBuf) (bool, interface{}, error) {\n\tcomplete, cmd, err := ReadCommand(in)\n\tif err != nil {\n\t\treturn true, nil, err\n\t}\n\n\tif !complete {\n\t\treturn false, nil, nil\n\t}\n\n\treturn true, cmd, nil\n}\n\ntype redisReplyDecoder struct {\n}\n\n\n\n\n\nfunc (decoder *redisReplyDecoder) Decode(in *goetty.ByteBuf) (bool, interface{}, error) {\n\tcomplete, cmd, err := readCommandReply(in)\n\tif err != nil {\n\t\treturn true, nil, err\n\t}\n\n\tif !complete {\n\t\treturn false, nil, nil\n\t}\n\n\treturn true, cmd, nil\n}\n\nfunc NewRedisReplyDecoder() goetty.Decoder ", "output": "{\n\treturn &redisReplyDecoder{}\n}"} {"input": "package metrics\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\ntype GaugeMetric struct {\n\tvalue float64\n\tmutex sync.RWMutex\n}\n\nfunc (metric *GaugeMetric) Humanize() string {\n\tformatString := \"[GaugeMetric; value=%f]\"\n\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn fmt.Sprintf(formatString, metric.value)\n}\n\nfunc (metric *GaugeMetric) Set(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value = value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) IncrementBy(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value += value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Increment() float64 {\n\treturn metric.IncrementBy(1)\n}\n\nfunc (metric *GaugeMetric) DecrementBy(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value -= value\n\n\treturn metric.value\n}\n\n\n\nfunc (metric *GaugeMetric) Get() float64 {\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Marshallable() map[string]interface{} {\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\tv := make(map[string]interface{}, 2)\n\n\tv[valueKey] = metric.value\n\tv[typeKey] = gaugeTypeValue\n\n\treturn v\n}\n\nfunc (metric *GaugeMetric) Decrement() float64 ", "output": "{\n\treturn metric.DecrementBy(1)\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestAuthorize(t *testing.T) ", "output": "{\n\tConvey(\"loadConfig errors on empty agent.json\", t, func() {\n\t\t_, err := loadConfig(\"/nonexistent/hologram/agent.json\")\n\t\tSo(err, ShouldNotBeNil)\n\t})\n}"} {"input": "package values\n\nimport \"fmt\"\nimport \"strconv\"\n\n\ntype Int int\n\n\nfunc NewInt(val int, p *int) *Int {\n\t*p = val\n\treturn (*Int)(p)\n}\n\n\n\n\n\nfunc (i *Int) Set(s string) error {\n\tv, err := strconv.ParseInt(s, 0, 64)\n\t*i = Int(v)\n\treturn err\n}\n\n\nfunc (i *Int) String() string {\n\treturn fmt.Sprintf(\"%v\", *i)\n}\n\nfunc (i *Int) Get() interface{} ", "output": "{\n\treturn int(*i)\n}"} {"input": "package samples\n\n\n\nfunc init() ", "output": "{\n\n\tsampleDataAccountUpdateOperation[15] = `{\n \"account\": \"1.2.10091\",\n \"extensions\": {},\n \"fee\": {\n \"amount\": 2005761,\n \"asset_id\": \"1.3.0\"\n },\n \"new_options\": {\n \"extensions\": [],\n \"memo_key\": \"BTS5TuKkiAbEo3ZDxmXYk9DgFMVEwwbMjiAMp63YnbhRVX8Q73UeJ\",\n \"num_committee\": 0,\n \"num_witness\": 0,\n \"votes\": [\n \"1:48\"\n ],\n \"voting_account\": \"1.2.5\"\n }\n}`\n\n}"} {"input": "package goparser\n\nimport (\n\t\"strings\"\n)\n\nfunc isExceptedStatement(name string, prefixs, suffixs, fullnames []string) bool {\n\tname = strings.ToLower(name)\n\tfor _, prefix := range prefixs {\n\t\tif strings.HasPrefix(name, prefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tfor _, suffix := range suffixs {\n\t\tif strings.HasSuffix(name, suffix) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, fullname := range fullnames {\n\t\tif name == fullname {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc isInsertStatement(name string) bool {\n\treturn isExceptedStatement(name, []string{\n\t\t\"insert\",\n\t\t\"upsert\",\n\t\t\"add\",\n\t\t\"create\",\n\t}, nil, nil)\n}\n\nfunc isUpdateStatement(name string) bool {\n\treturn isExceptedStatement(name, []string{\n\t\t\"set\",\n\t\t\"update\",\n\t}, nil, nil)\n}\n\nfunc isSelectStatement(name string) bool {\n\treturn isExceptedStatement(name, []string{\n\t\t\"select\",\n\t\t\"find\",\n\t\t\"get\",\n\t\t\"query\",\n\t\t\"list\",\n\t\t\"count\",\n\t\t\"read\",\n\t\t\"statby\",\n\t\t\"statsby\",\n\t}, []string{\"count\"}, []string{\"id\", \"all\", \"names\", \"titles\"})\n}\n\nfunc isDeleteStatement(name string) bool ", "output": "{\n\treturn isExceptedStatement(name, []string{\n\t\t\"delete\",\n\t\t\"remove\",\n\t\t\"clear\",\n\t}, nil, nil)\n}"} {"input": "package echo\n\ntype (\n\tGroup struct {\n\t\techo Echo\n\t}\n)\n\n\n\nfunc (g *Group) Connect(path string, h Handler) {\n\tg.echo.Connect(path, h)\n}\n\nfunc (g *Group) Delete(path string, h Handler) {\n\tg.echo.Delete(path, h)\n}\n\nfunc (g *Group) Get(path string, h Handler) {\n\tg.echo.Get(path, h)\n}\n\nfunc (g *Group) Head(path string, h Handler) {\n\tg.echo.Head(path, h)\n}\n\nfunc (g *Group) Options(path string, h Handler) {\n\tg.echo.Options(path, h)\n}\n\nfunc (g *Group) Patch(path string, h Handler) {\n\tg.echo.Patch(path, h)\n}\n\nfunc (g *Group) Post(path string, h Handler) {\n\tg.echo.Post(path, h)\n}\n\nfunc (g *Group) Put(path string, h Handler) {\n\tg.echo.Put(path, h)\n}\n\nfunc (g *Group) Trace(path string, h Handler) {\n\tg.echo.Trace(path, h)\n}\n\nfunc (g *Group) WebSocket(path string, h HandlerFunc) {\n\tg.echo.WebSocket(path, h)\n}\n\nfunc (g *Group) Static(path, root string) {\n\tg.echo.Static(path, root)\n}\n\nfunc (g *Group) ServeDir(path, root string) {\n\tg.echo.ServeDir(path, root)\n}\n\nfunc (g *Group) ServeFile(path, file string) {\n\tg.echo.ServeFile(path, file)\n}\n\nfunc (g *Group) Group(prefix string, m ...Middleware) *Group {\n\treturn g.echo.Group(prefix, m...)\n}\n\nfunc (g *Group) Use(m ...Middleware) ", "output": "{\n\tfor _, h := range m {\n\t\tg.echo.middleware = append(g.echo.middleware, wrapMiddleware(h))\n\t}\n}"} {"input": "package errs\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/uther/go-uther/logger\"\n)\n\n\n\nfunc TestErrorMessage(t *testing.T) {\n\terr := testErrors().New(0, \"zero detail %v\", \"available\")\n\tmessage := fmt.Sprintf(\"%v\", err)\n\texp := \"[TEST] ERROR: zero: zero detail available\"\n\tif message != exp {\n\t\tt.Errorf(\"error message incorrect. expected %v, got %v\", exp, message)\n\t}\n}\n\nfunc TestErrorSeverity(t *testing.T) {\n\terr0 := testErrors().New(0, \"zero detail\")\n\tif !err0.Fatal() {\n\t\tt.Errorf(\"error should be fatal\")\n\t}\n\terr1 := testErrors().New(1, \"one detail\")\n\tif err1.Fatal() {\n\t\tt.Errorf(\"error should not be fatal\")\n\t}\n}\n\nfunc testErrors() *Errors ", "output": "{\n\treturn &Errors{\n\t\tPackage: \"TEST\",\n\t\tErrors: map[int]string{\n\t\t\t0: \"zero\",\n\t\t\t1: \"one\",\n\t\t},\n\t\tLevel: func(i int) (l logger.LogLevel) {\n\t\t\tif i == 0 {\n\t\t\t\tl = logger.ErrorLevel\n\t\t\t} else {\n\t\t\t\tl = logger.WarnLevel\n\t\t\t}\n\t\t\treturn\n\t\t},\n\t}\n}"} {"input": "package user\n\nimport (\n\t\"context\"\n\t\"flag\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/ssoadmin\"\n)\n\ntype rm struct {\n\t*flags.ClientFlag\n}\n\nfunc init() {\n\tcli.Register(\"sso.user.rm\", &rm{})\n}\n\nfunc (cmd *rm) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.ClientFlag, ctx = flags.NewClientFlag(ctx)\n\tcmd.ClientFlag.Register(ctx, f)\n}\n\nfunc (cmd *rm) Usage() string {\n\treturn \"NAME\"\n}\n\n\n\nfunc (cmd *rm) Run(ctx context.Context, f *flag.FlagSet) error {\n\treturn withClient(ctx, cmd.ClientFlag, func(c *ssoadmin.Client) error {\n\t\treturn c.DeletePrincipal(ctx, f.Arg(0))\n\t})\n}\n\nfunc (cmd *rm) Description() string ", "output": "{\n\treturn `Remove SSO users.\n\nExamples:\n govc sso.user.rm NAME`\n}"} {"input": "package fhash\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"path/filepath\"\n)\n\nconst (\n\tfhashData = \"fhashdata\"\n)\n\n\ntype Server struct {\n\tserver *http.Server\n\tconf *Config\n\tindex *Index \n\troot string \n}\n\n\nfunc NewServer(config *Config) (*Server, error) {\n\tindex, err := NewIndex(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"index error: %v\", err)\n\t}\n\n\troot := filepath.Join(config.Server.Root, fhashData)\n\tserver := &Server{\n\t\tserver: &http.Server{\n\t\t\tAddr: config.Server.Address,\n\t\t},\n\t\tconf: config,\n\t\tindex: index,\n\t\troot: root,\n\t}\n\treturn server, nil\n}\n\n\n\n\n\nfunc (s *Server) Shutdown() error {\n\terr := s.index.close()\n\treturn err\n}\n\nfunc (s *Server) Serve() ", "output": "{\n\thttp.HandleFunc(\"/putfile\", s.putFile)\n\thttp.HandleFunc(\"/getfile/\", s.getFile)\n\terr := s.server.ListenAndServe()\n\tif err != nil {\n\t\tlog.Printf(\"failed to serve: %v\", err)\n\t}\n}"} {"input": "package funcutils\n\nimport (\n\t\"sync\"\n)\n\ntype AnonymousFunction func()\n\n\n\nfunc ExecuteWithWaitGroup(wg *sync.WaitGroup, f AnonymousFunction) ", "output": "{\n\tdefer wg.Done()\n\tf()\n}"} {"input": "package tick\n\nimport (\n\t\"github.com/influxdata/kapacitor/pipeline\"\n\t\"github.com/influxdata/kapacitor/tick/ast\"\n)\n\n\ntype StatsNode struct {\n\tFunction\n}\n\n\nfunc NewStats(parents []ast.Node) *StatsNode {\n\treturn &StatsNode{\n\t\tFunction{\n\t\t\tParents: parents,\n\t\t},\n\t}\n}\n\n\n\n\nfunc (n *StatsNode) Build(s *pipeline.StatsNode) (ast.Node, error) ", "output": "{\n\tn.Pipe(\"stats\", s.Interval).\n\t\tDotIf(\"align\", s.AlignFlag)\n\treturn n.prev, n.err\n}"} {"input": "package egoscale\n\nimport \"fmt\"\n\n\n\n\n\nfunc (ls *ListAntiAffinityGroups) ListRequest() (ListCommand, error) {\n\tif ls == nil {\n\t\treturn nil, fmt.Errorf(\"%T cannot be nil\", ls)\n\t}\n\treturn ls, nil\n}\n\n\nfunc (ls *ListAntiAffinityGroups) SetPage(page int) {\n\tls.Page = page\n}\n\n\nfunc (ls *ListAntiAffinityGroups) SetPageSize(pageSize int) {\n\tls.PageSize = pageSize\n}\n\n\nfunc (ListAntiAffinityGroups) Each(resp interface{}, callback IterateItemFunc) {\n\titems, ok := resp.(*ListAntiAffinityGroupsResponse)\n\tif !ok {\n\t\tcallback(nil, fmt.Errorf(\"wrong type, ListAntiAffinityGroupsResponse was expected, got %T\", resp))\n\t\treturn\n\t}\n\n\tfor i := range items.AntiAffinityGroup {\n\t\tif !callback(&items.AntiAffinityGroup[i], nil) {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (ListAntiAffinityGroups) Response() interface{} ", "output": "{\n\treturn new(ListAntiAffinityGroupsResponse)\n}"} {"input": "package generic\n\nimport (\n\t\"github.com/actgardner/gogen-avro/v8/schema\"\n\t\"github.com/actgardner/gogen-avro/v8/vm/types\"\n)\n\ntype recordDatum struct {\n\tdef *schema.RecordDefinition\n\tfields []Datum\n}\n\n\n\nfunc (r *recordDatum) Datum() interface{} {\n\tm := make(map[string]interface{})\n\tfor i, f := range r.def.Fields() {\n\t\tm[f.Name()] = r.fields[i].Datum()\n\t}\n\treturn m\n}\n\nfunc (r *recordDatum) SetBoolean(v bool) { panic(\"\") }\nfunc (r *recordDatum) SetInt(v int32) { panic(\"\") }\nfunc (r *recordDatum) SetLong(v int64) { panic(\"\") }\nfunc (r *recordDatum) SetFloat(v float32) { panic(\"\") }\nfunc (r *recordDatum) SetDouble(v float64) { panic(\"\") }\nfunc (r *recordDatum) SetBytes(v []byte) { panic(\"\") }\nfunc (r *recordDatum) SetString(v string) { panic(\"\") }\nfunc (r *recordDatum) Get(i int) types.Field {\n\tfield := r.def.Fields()[i]\n\tr.fields[i] = DatumForType(field.Type())\n\treturn r.fields[i]\n}\nfunc (r *recordDatum) SetDefault(i int) {\n\tfield := r.def.Fields()[i]\n\tr.fields[i] = &primitiveDatum{field.Default()}\n}\nfunc (r *recordDatum) AppendMap(key string) types.Field { panic(\"\") }\nfunc (r *recordDatum) AppendArray() types.Field { panic(\"\") }\nfunc (r *recordDatum) NullField(t int) {\n\tr.fields[t] = &primitiveDatum{nil}\n}\nfunc (r *recordDatum) Finalize() {}\n\nfunc newRecordDatum(def *schema.RecordDefinition) *recordDatum ", "output": "{\n\treturn &recordDatum{\n\t\tdef: def,\n\t\tfields: make([]Datum, len(def.Fields())),\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst letterBytes = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst lenLetters = len(letterBytes)\n\n\n\nfunc randStr(n int) string {\n\tb := make([]byte, n)\n\tfor i := range b {\n\t\tb[i] = letterBytes[rand.Int63()%int64(len(letterBytes))]\n\t}\n\treturn string(b)\n}\n\nfunc sendJson(w http.ResponseWriter, data interface{}) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(data)\n}\n\nfunc sendOk(w http.ResponseWriter, data interface{}) {\n\tjson.NewEncoder(w).Encode(data)\n}\n\nfunc sendError(w http.ResponseWriter, msg string) {\n\tdata := struct {\n\t\tOk bool `json:\"ok\"`\n\t\tMsg string `json:\"msg\"`\n\t}{\n\t\tOk: false,\n\t\tMsg: msg,\n\t}\n\n\tsendJson(w, data)\n}\n\nfunc init() ", "output": "{\n\trand.Seed(time.Now().UnixNano())\n}"} {"input": "package deb\n\nimport (\n\t\"encoding/binary\"\n\t\"github.com/smira/aptly/aptly\"\n\t\"github.com/smira/aptly/utils\"\n\t\"hash/fnv\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n)\n\n\ntype PackageFile struct {\n\tFilename string\n\tChecksums utils.ChecksumInfo\n\tdownloadPath string\n}\n\n\nfunc (f *PackageFile) Verify(packagePool aptly.PackagePool) (bool, error) {\n\tpoolPath, err := packagePool.Path(f.Filename, f.Checksums.MD5)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tst, err := os.Stat(poolPath)\n\tif err != nil {\n\t\treturn false, nil\n\t}\n\n\treturn st.Size() == f.Checksums.Size, nil\n}\n\n\nfunc (f *PackageFile) DownloadURL() string {\n\treturn filepath.Join(f.downloadPath, f.Filename)\n}\n\n\ntype PackageFiles []PackageFile\n\n\nfunc (files PackageFiles) Hash() uint64 {\n\tsort.Sort(files)\n\n\th := fnv.New64a()\n\n\tfor _, f := range files {\n\t\th.Write([]byte(f.Filename))\n\t\tbinary.Write(h, binary.BigEndian, f.Checksums.Size)\n\t\th.Write([]byte(f.Checksums.MD5))\n\t\th.Write([]byte(f.Checksums.SHA1))\n\t\th.Write([]byte(f.Checksums.SHA256))\n\t}\n\n\treturn h.Sum64()\n}\n\n\n\n\n\nfunc (files PackageFiles) Swap(i, j int) {\n\tfiles[i], files[j] = files[j], files[i]\n}\n\n\nfunc (files PackageFiles) Less(i, j int) bool {\n\treturn files[i].Filename < files[j].Filename\n}\n\nfunc (files PackageFiles) Len() int ", "output": "{\n\treturn len(files)\n}"} {"input": "package instagram\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"net/url\"\n\n\t\"github.com/laicosly/goth\"\n\t\"golang.org/x/oauth2\"\n)\n\n\ntype Session struct {\n\tAuthURL string\n\tAccessToken string\n\tState string\n\tParams url.Values\n}\n\n\nfunc (s Session) GetAuthURL() (string, error) {\n\tif s.AuthURL == \"\" {\n\t\treturn \"\", errors.New(\"an AuthURL has not be set\")\n\t}\n\treturn s.AuthURL, nil\n}\n\n\nfunc (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {\n\tp := provider.(*Provider)\n\ttoken, err := p.config.Exchange(oauth2.NoContext, params.Get(\"code\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ts.AccessToken = token.AccessToken\n\treturn token.AccessToken, err\n}\n\n\nfunc (s Session) Marshal() string {\n\tb, _ := json.Marshal(s)\n\treturn string(b)\n}\n\n\n\nfunc (s Session) String() string ", "output": "{\n\treturn s.Marshal()\n}"} {"input": "package category\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/vapi/tags\"\n)\n\ntype ls struct {\n\t*flags.ClientFlag\n\t*flags.OutputFlag\n}\n\nfunc init() {\n\tcli.Register(\"tags.category.ls\", &ls{})\n}\n\nfunc (cmd *ls) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.ClientFlag, ctx = flags.NewClientFlag(ctx)\n\tcmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)\n\tcmd.ClientFlag.Register(ctx, f)\n\tcmd.OutputFlag.Register(ctx, f)\n}\n\n\n\nfunc (cmd *ls) Description() string {\n\treturn `List all categories.\n\nExamples:\n govc tags.category.ls\n govc tags.category.ls -json | jq .`\n}\n\ntype lsResult []tags.Category\n\nfunc (r lsResult) Write(w io.Writer) error {\n\tfor _, c := range r {\n\t\tfmt.Fprintln(w, c.Name)\n\t}\n\treturn nil\n}\n\nfunc (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {\n\tc, err := cmd.RestClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tl, err := tags.NewManager(c).GetCategories(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn cmd.WriteResult(lsResult(l))\n}\n\nfunc (cmd *ls) Process(ctx context.Context) error ", "output": "{\n\tif err := cmd.ClientFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn cmd.OutputFlag.Process(ctx)\n}"} {"input": "package user\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n\ntype RangeList []*Range\n\n\nfunc ParseRangeList(str string) (*RangeList, error) {\n\trl := RangeList{}\n\tif len(str) == 0 {\n\t\treturn &rl, nil\n\t}\n\tparts := strings.Split(str, \",\")\n\tfor _, p := range parts {\n\t\tr, err := ParseRange(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trl = append(rl, r)\n\t}\n\treturn &rl, nil\n}\n\n\nfunc (l *RangeList) Empty() bool {\n\tif len(*l) == 0 {\n\t\treturn true\n\t}\n\tfor _, r := range *l {\n\t\tif !r.Empty() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc (l *RangeList) Contains(uid int) bool {\n\tfor _, r := range *l {\n\t\tif r.Contains(uid) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (l *RangeList) Type() string {\n\treturn \"user.RangeList\"\n}\n\n\nfunc (l *RangeList) Set(value string) error {\n\tnewRangeList, err := ParseRangeList(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*l = *newRangeList\n\treturn nil\n}\n\n\nfunc (l *RangeList) String() string {\n\trangeStrings := []string{}\n\tfor _, r := range *l {\n\t\trangeStrings = append(rangeStrings, r.String())\n\t}\n\treturn strings.Join(rangeStrings, \",\")\n}\n\n\n\n\n\nfunc IsUserAllowed(user string, allowed *RangeList) bool ", "output": "{\n\tuid, err := strconv.Atoi(user)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn allowed.Contains(uid)\n}"} {"input": "package api2go\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\ntype APIContextAllocatorFunc func(*API) APIContexter\n\n\ntype APIContexter interface {\n\tcontext.Context\n\tSet(key string, value interface{})\n\tGet(key string) (interface{}, bool)\n\tReset()\n}\n\n\ntype APIContext struct {\n\tkeys map[string]interface{}\n}\n\n\nfunc (c *APIContext) Set(key string, value interface{}) {\n\tif c.keys == nil {\n\t\tc.keys = make(map[string]interface{})\n\t}\n\tc.keys[key] = value\n}\n\n\nfunc (c *APIContext) Get(key string) (value interface{}, exists bool) {\n\tif c.keys != nil {\n\t\tvalue, exists = c.keys[key]\n\t}\n\treturn\n}\n\n\nfunc (c *APIContext) Reset() {\n\tc.keys = nil\n}\n\n\n\n\n\nfunc (c *APIContext) Done() <-chan struct{} {\n\treturn nil\n}\n\n\nfunc (c *APIContext) Err() error {\n\treturn nil\n}\n\n\nfunc (c *APIContext) Value(key interface{}) interface{} {\n\tif keyAsString, ok := key.(string); ok {\n\t\tval, _ := c.Get(keyAsString)\n\t\treturn val\n\t}\n\treturn nil\n}\n\n\nvar _ APIContexter = &APIContext{}\n\n\nfunc ContextQueryParams(c *APIContext) map[string][]string {\n\tqp, ok := c.Get(\"QueryParams\")\n\tif ok == false {\n\t\tqp = make(map[string][]string)\n\t\tc.Set(\"QueryParams\", qp)\n\t}\n\treturn qp.(map[string][]string)\n}\n\nfunc (c *APIContext) Deadline() (deadline time.Time, ok bool) ", "output": "{\n\treturn\n}"} {"input": "package servicelabel\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/namsral/flag\"\n\n\t\"go.ligato.io/cn-infra/v2/infra\"\n\t\"go.ligato.io/cn-infra/v2/logging/logrus\"\n)\n\nvar microserviceLabelFlag string\n\nfunc init() {\n\tflag.StringVar(µserviceLabelFlag, \"microservice-label\", \"vpp1\", fmt.Sprintf(\"microservice label; also set via '%v' env variable.\", MicroserviceLabelEnvVar))\n}\n\n\ntype Plugin struct {\n\tinfra.PluginName\n\tMicroserviceLabel string\n}\n\n\n\n\n\nfunc (p *Plugin) Close() error {\n\treturn nil\n}\n\n\n\nfunc (p *Plugin) GetAgentLabel() string {\n\treturn p.MicroserviceLabel\n}\n\n\n\nfunc (p *Plugin) GetAgentPrefix() string {\n\treturn agentPrefix + p.MicroserviceLabel + \"/\"\n}\n\n\n\nfunc (p *Plugin) GetDifferentAgentPrefix(microserviceLabel string) string {\n\treturn GetDifferentAgentPrefix(microserviceLabel)\n}\n\n\n\nfunc (p *Plugin) GetAllAgentsPrefix() string {\n\treturn GetAllAgentsPrefix()\n}\n\nfunc (p *Plugin) Init() error ", "output": "{\n\tif p.MicroserviceLabel == \"\" {\n\t\tp.MicroserviceLabel = microserviceLabelFlag\n\t}\n\tlogrus.DefaultLogger().Debugf(\"Microservice label is set to %v\", p.MicroserviceLabel)\n\treturn nil\n}"} {"input": "package iso20022\n\n\ntype OriginalItem4 struct {\n\n\tOriginalItemIdentification *Max35Text `xml:\"OrgnlItmId\"`\n\n\tOriginalEndToEndIdentification *Max35Text `xml:\"OrgnlEndToEndId,omitempty\"`\n\n\tAmount *ActiveOrHistoricCurrencyAndAmount `xml:\"Amt\"`\n\n\tExpectedValueDate *ISODate `xml:\"XpctdValDt,omitempty\"`\n\n\tOriginalItemReference *OriginalItemReference3 `xml:\"OrgnlItmRef,omitempty\"`\n}\n\nfunc (o *OriginalItem4) SetOriginalItemIdentification(value string) {\n\to.OriginalItemIdentification = (*Max35Text)(&value)\n}\n\nfunc (o *OriginalItem4) SetOriginalEndToEndIdentification(value string) {\n\to.OriginalEndToEndIdentification = (*Max35Text)(&value)\n}\n\nfunc (o *OriginalItem4) SetAmount(value, currency string) {\n\to.Amount = NewActiveOrHistoricCurrencyAndAmount(value, currency)\n}\n\nfunc (o *OriginalItem4) SetExpectedValueDate(value string) {\n\to.ExpectedValueDate = (*ISODate)(&value)\n}\n\n\n\nfunc (o *OriginalItem4) AddOriginalItemReference() *OriginalItemReference3 ", "output": "{\n\to.OriginalItemReference = new(OriginalItemReference3)\n\treturn o.OriginalItemReference\n}"} {"input": "package router\n\n\n\n\nimport (\n\t\"github.com/weaveworks/mesh\"\n)\n\n\n\ntype AWSVPCConnection struct {\n\testablishedChan chan struct{}\n\terrorChan chan error\n}\n\nfunc (conn *AWSVPCConnection) Confirm() {\n\tclose(conn.establishedChan)\n}\n\nfunc (conn *AWSVPCConnection) EstablishedChannel() <-chan struct{} {\n\treturn conn.establishedChan\n}\n\nfunc (conn *AWSVPCConnection) ErrorChannel() <-chan error {\n\treturn conn.errorChan\n}\n\nfunc (conn *AWSVPCConnection) Stop() {}\n\nfunc (conn *AWSVPCConnection) ControlMessage(tag byte, msg []byte) {\n}\n\nfunc (conn *AWSVPCConnection) DisplayName() string {\n\treturn \"awsvpc\"\n}\n\n\n\nfunc (conn *AWSVPCConnection) Forward(key ForwardPacketKey) FlowOp {\n\treturn DiscardingFlowOp{}\n}\n\ntype AWSVPC struct{}\n\nfunc NewAWSVPC() AWSVPC {\n\treturn AWSVPC{}\n}\n\n\n\nfunc (vpc AWSVPC) AddFeaturesTo(features map[string]string) {}\n\n\n\nfunc (vpc AWSVPC) Diagnostics() interface{} {\n\treturn nil\n}\n\n\n\nfunc (vpc AWSVPC) InvalidateRoutes() {}\n\nfunc (vpc AWSVPC) InvalidateShortIDs() {}\n\nfunc (vpc AWSVPC) StartConsumingPackets(localPeer *mesh.Peer, peers *mesh.Peers, consumer OverlayConsumer) error {\n\treturn nil\n}\n\nfunc (vpc AWSVPC) PrepareConnection(params mesh.OverlayConnectionParams) (mesh.OverlayConnection, error) ", "output": "{\n\tconn := &AWSVPCConnection{\n\t\testablishedChan: make(chan struct{}),\n\t\terrorChan: make(chan error, 1),\n\t}\n\treturn conn, nil\n}"} {"input": "package markdown\n\nimport (\n\t\"bufio\"\n\t\"io\"\n)\n\ntype writer interface {\n\tWrite([]byte) (int, error)\n\tWriteByte(byte) error\n\tWriteString(string) (int, error)\n\tFlush() error\n}\n\ntype monadicWriter struct {\n\twriter\n\terr error\n}\n\nfunc newMonadicWriter(w io.Writer) *monadicWriter {\n\tif w, ok := w.(writer); ok {\n\t\treturn &monadicWriter{writer: w}\n\t}\n\treturn &monadicWriter{writer: bufio.NewWriter(w)}\n}\n\nfunc (w *monadicWriter) Write(p []byte) (n int, err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\tn, err = w.writer.Write(p)\n\tw.err = err\n\treturn\n}\n\nfunc (w *monadicWriter) WriteByte(b byte) (err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\terr = w.writer.WriteByte(b)\n\tw.err = err\n\treturn\n}\n\n\n\nfunc (w *monadicWriter) Flush() (err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\terr = w.writer.Flush()\n\tw.err = err\n\treturn\n}\n\nfunc (w *monadicWriter) WriteString(s string) (n int, err error) ", "output": "{\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\tn, err = w.writer.WriteString(s)\n\tw.err = err\n\treturn\n}"} {"input": "package lifecycle\n\nimport (\n\t\"encoding/xml\"\n)\n\n\ntype NoncurrentVersionExpiration struct {\n\tXMLName xml.Name `xml:\"NoncurrentVersionExpiration\"`\n\tNoncurrentDays ExpirationDays `xml:\"NoncurrentDays,omitempty\"`\n}\n\n\ntype NoncurrentVersionTransition struct {\n\tNoncurrentDays ExpirationDays `xml:\"NoncurrentDays\"`\n\tStorageClass string `xml:\"StorageClass\"`\n}\n\nvar (\n\terrNoncurrentVersionTransitionUnsupported = Errorf(\"Specifying is not supported\")\n)\n\n\nfunc (n NoncurrentVersionExpiration) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tif n.IsDaysNull() {\n\t\treturn nil\n\t}\n\ttype noncurrentVersionExpirationWrapper NoncurrentVersionExpiration\n\treturn e.EncodeElement(noncurrentVersionExpirationWrapper(n), start)\n}\n\n\n\n\n\n\n\nfunc (n NoncurrentVersionTransition) UnmarshalXML(d *xml.Decoder, startElement xml.StartElement) error {\n\treturn errNoncurrentVersionTransitionUnsupported\n}\n\n\n\nfunc (n NoncurrentVersionTransition) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tif n.NoncurrentDays == ExpirationDays(0) {\n\t\treturn nil\n\t}\n\treturn e.EncodeElement(&n, start)\n}\n\nfunc (n NoncurrentVersionExpiration) IsDaysNull() bool ", "output": "{\n\treturn n.NoncurrentDays == ExpirationDays(0)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tif code, err := execDcmCmd(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"DCM error:\", err)\n\t\tos.Exit(code)\n\t}\n}\n\n\n\nfunc execDcmCmd() (int, error) ", "output": "{\n\tconf, err := NewConfigFile()\n\tif err != nil {\n\t\treturn 1, err\n\t}\n\targs := os.Args[1:]\n\tdcm := NewDcm(conf, args)\n\tcode, err := dcm.Command()\n\tif err != nil {\n\t\treturn code, err\n\t}\n\treturn 0, nil\n}"} {"input": "package hyperkube\n\nimport (\n\t\"io/ioutil\"\n\t\"strings\"\n\n\tutiltemplate \"github.com/kubernetes-sigs/service-catalog/pkg/kubernetes/pkg/util/template\"\n\t\"k8s.io/component-base/cli/flag\"\n\n\t\"github.com/spf13/pflag\"\n)\n\ntype serverRunFunc func(s *Server, args []string, stopCh <-chan struct{}) error\n\n\ntype Server struct {\n\tSimpleUsage string \n\tLong string \n\tRun serverRunFunc \n\tPrimaryName string\n\tAlternativeName string\n\tRespectsStopCh bool\n\n\tflags *pflag.FlagSet \n\thk *HyperKube\n}\n\n\nfunc (s *Server) Usage() error {\n\ttt := `{{if .Long}}{{.Long | trim | wrap \"\"}}\n{{end}}Usage:\n {{.SimpleUsage}} [flags]\n\nAvailable Flags:\n{{.Flags.FlagUsages}}`\n\n\treturn utiltemplate.ExecuteTemplate(s.hk.Out(), tt, s)\n}\n\n\n\n\n\nfunc (s *Server) Flags() *pflag.FlagSet {\n\tif s.flags == nil {\n\t\ts.flags = pflag.NewFlagSet(s.Name(), pflag.ContinueOnError)\n\t\ts.flags.SetOutput(ioutil.Discard)\n\t\ts.flags.SetNormalizeFunc(flag.WordSepNormalizeFunc)\n\t}\n\treturn s.flags\n}\n\nfunc (s *Server) Name() string ", "output": "{\n\tif s.PrimaryName != \"\" {\n\t\treturn s.PrimaryName\n\t}\n\tname := s.SimpleUsage\n\ti := strings.Index(name, \" \")\n\tif i >= 0 {\n\t\tname = name[:i]\n\t}\n\treturn name\n}"} {"input": "package versioned\n\nimport (\n\toauthv1 \"github.com/openshift/client-go/oauth/clientset/versioned/typed/oauth/v1\"\n\tdiscovery \"k8s.io/client-go/discovery\"\n\trest \"k8s.io/client-go/rest\"\n\tflowcontrol \"k8s.io/client-go/util/flowcontrol\"\n)\n\ntype Interface interface {\n\tDiscovery() discovery.DiscoveryInterface\n\tOauthV1() oauthv1.OauthV1Interface\n}\n\n\n\ntype Clientset struct {\n\t*discovery.DiscoveryClient\n\toauthV1 *oauthv1.OauthV1Client\n}\n\n\nfunc (c *Clientset) OauthV1() oauthv1.OauthV1Interface {\n\treturn c.oauthV1\n}\n\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.DiscoveryClient\n}\n\n\nfunc NewForConfig(c *rest.Config) (*Clientset, error) {\n\tconfigShallowCopy := *c\n\tif configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {\n\t\tconfigShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)\n\t}\n\tvar cs Clientset\n\tvar err error\n\tcs.oauthV1, err = oauthv1.NewForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &cs, nil\n}\n\n\n\n\n\n\nfunc New(c rest.Interface) *Clientset {\n\tvar cs Clientset\n\tcs.oauthV1 = oauthv1.New(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClient(c)\n\treturn &cs\n}\n\nfunc NewForConfigOrDie(c *rest.Config) *Clientset ", "output": "{\n\tvar cs Clientset\n\tcs.oauthV1 = oauthv1.NewForConfigOrDie(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)\n\treturn &cs\n}"} {"input": "package schema\n\n\ntype ObjectMapping struct {\n\tRelation string `gorm:\"size:128\"`\n\tID string `gorm:\"size:64\"`\n}\n\n\n\nfunc init() ", "output": "{\n\tAddSchema(&ObjectMapping{})\n}"} {"input": "package user\n\nfunc New(id int, username, password, firstname, lastname, role string) User {\n\treturn User{id, username, password, firstname, lastname, role}\n}\n\n\ntype User struct {\n\tid int\n\tusername string\n\tpassword string\n\tfirstname string\n\tlastname string\n\trole string\n}\n\n\n\nfunc (u User) Username() string {\n\treturn u.username\n}\n\nfunc (u User) Password() string {\n\treturn u.password\n}\n\nfunc (u User) Firstname() string {\n\treturn u.firstname\n}\n\nfunc (u User) Lastname() string {\n\treturn u.lastname\n}\n\nfunc (u User) Role() string {\n\treturn u.role\n}\n\nfunc (u User) Id() int ", "output": "{\n\treturn u.id\n}"} {"input": "package sql\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/cockroachdb/cockroach/pkg/roachpb\"\n\t\"github.com/cockroachdb/cockroach/pkg/sql/parser\"\n\t\"github.com/cockroachdb/cockroach/pkg/sql/sqlbase\"\n)\n\n\n\n\ntype delayedNode struct {\n\tname string\n\tcolumns sqlbase.ResultColumns\n\tconstructor nodeConstructor\n\tplan planNode\n}\n\ntype nodeConstructor func(context.Context, *planner) (planNode, error)\n\nfunc (d *delayedNode) Close(ctx context.Context) {\n\tif d.plan != nil {\n\t\td.plan.Close(ctx)\n\t\td.plan = nil\n\t}\n}\n\nfunc (d *delayedNode) Columns() sqlbase.ResultColumns { return d.columns }\nfunc (d *delayedNode) Ordering() orderingInfo { return orderingInfo{} }\nfunc (d *delayedNode) MarkDebug(_ explainMode) {}\n\nfunc (d *delayedNode) Next(ctx context.Context) (bool, error) { return d.plan.Next(ctx) }\nfunc (d *delayedNode) Values() parser.Datums { return d.plan.Values() }\nfunc (d *delayedNode) DebugValues() debugValues { return d.plan.DebugValues() }\nfunc (d *delayedNode) Spans(ctx context.Context) (_, _ roachpb.Spans, _ error) {\n\treturn d.plan.Spans(ctx)\n}\n\nfunc (d *delayedNode) Start(ctx context.Context) error ", "output": "{ return d.plan.Start(ctx) }"} {"input": "package memcachep\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n)\n\ntype Stats map[string]fmt.Stringer\n\n\ntype FuncStat struct {\n\tCallable func() string\n}\n\nfunc (f *FuncStat) String() string {\n\treturn f.Callable()\n}\n\n\ntype StaticStat struct {\n\tValue string\n}\n\n\n\n\ntype CounterStat struct {\n\tCount int\n\tcalculations chan int\n}\n\nfunc (c *CounterStat) Increment(num int) {\n\tc.calculations <- num\n}\n\nfunc (c *CounterStat) SetCount(num int) {\n\tc.Count = num\n}\n\nfunc (c *CounterStat) Decrement(num int) {\n\tc.calculations <- -num\n}\n\nfunc (c *CounterStat) String() string {\n\treturn strconv.Itoa(c.Count)\n}\n\nfunc (c *CounterStat) work() {\n\tfor num := range c.calculations {\n\t\tc.Count = c.Count + num\n\t}\n}\n\nfunc NewCounterStat() *CounterStat {\n\tc := &CounterStat{}\n\tc.calculations = make(chan int, 100)\n\tgo c.work()\n\treturn c\n}\n\nfunc NewStats() Stats {\n\ts := make(Stats)\n\ts[\"pid\"] = &StaticStat{strconv.Itoa(os.Getpid())}\n\ts[\"version\"] = &StaticStat{VERSION}\n\ts[\"golang\"] = &StaticStat{runtime.Version()}\n\ts[\"goroutines\"] = &FuncStat{func() string { return strconv.Itoa(runtime.NumGoroutine()) }}\n\ts[\"cpu_num\"] = &StaticStat{strconv.Itoa(runtime.NumCPU())}\n\ts[\"total_connections\"] = NewCounterStat()\n\ts[\"curr_connections\"] = NewCounterStat()\n\ts[\"cmd_get\"] = NewCounterStat()\n\treturn s\n}\n\nfunc (s *StaticStat) String() string ", "output": "{\n\treturn s.Value\n}"} {"input": "package locations\n\nimport (\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/flexiant/concerto/cmd\"\n)\n\n\n\nfunc SubCommands() []cli.Command ", "output": "{\n\treturn []cli.Command{\n\t\t{\n\t\t\tName: \"list\",\n\t\t\tUsage: \"Lists the available Locations.\",\n\t\t\tAction: cmd.LocationList,\n\t\t},\n\t}\n}"} {"input": "package cleanpath\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n)\n\n\n\n\ntype longestFirst []string\n\nfunc (strs longestFirst) Len() int { return len(strs) }\nfunc (strs longestFirst) Less(i, j int) bool { return len(strs[i]) > len(strs[j]) }\nfunc (strs longestFirst) Swap(i, j int) { strs[i], strs[j] = strs[j], strs[i] }\n\nfunc RemoveGoPath(path string) string ", "output": "{\n\tdirs := filepath.SplitList(os.Getenv(\"GOPATH\"))\n\tsort.Stable(longestFirst(dirs))\n\tfor _, dir := range dirs {\n\t\tsrcdir := filepath.Join(dir, \"src\")\n\t\trel, err := filepath.Rel(srcdir, path)\n\t\tif err == nil && !strings.HasPrefix(rel, \"..\"+string(filepath.Separator)) {\n\t\t\treturn rel\n\t\t}\n\t}\n\treturn path\n}"} {"input": "package dep\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net/http\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n\n\t\"github.com/micromdm/micromdm/dep\"\n\t\"github.com/micromdm/micromdm/pkg/httputil\"\n)\n\n\n\ntype defineProfileRequest struct{ *dep.Profile }\ntype defineProfileResponse struct {\n\t*dep.ProfileResponse\n\tErr error `json:\"err,omitempty\"`\n}\n\nfunc (r defineProfileResponse) Failed() error { return r.Err }\n\nfunc decodeDefineProfileRequest(ctx context.Context, r *http.Request) (interface{}, error) {\n\tvar req defineProfileRequest\n\terr := httputil.DecodeJSONRequest(r, &req)\n\treturn req, err\n}\n\nfunc decodeDefineProfileResponse(_ context.Context, r *http.Response) (interface{}, error) {\n\tvar resp defineProfileResponse\n\terr := httputil.DecodeJSONResponse(r, &resp)\n\treturn resp, err\n}\n\nfunc MakeDefineProfileEndpoint(svc Service) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (response interface{}, err error) {\n\t\treq := request.(defineProfileRequest)\n\t\tresp, err := svc.DefineProfile(ctx, req.Profile)\n\t\treturn &defineProfileResponse{\n\t\t\tProfileResponse: resp,\n\t\t\tErr: err,\n\t\t}, nil\n\t}\n}\n\nfunc (e Endpoints) DefineProfile(ctx context.Context, p *dep.Profile) (*dep.ProfileResponse, error) {\n\trequest := defineProfileRequest{Profile: p}\n\tresp, err := e.DefineProfileEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponse := resp.(defineProfileResponse)\n\treturn response.ProfileResponse, response.Err\n}\n\nfunc (svc *DEPService) DefineProfile(ctx context.Context, p *dep.Profile) (*dep.ProfileResponse, error) ", "output": "{\n\tif svc.client == nil {\n\t\treturn nil, errors.New(\"DEP not configured yet. add a DEP token to enable DEP\")\n\t}\n\treturn svc.client.DefineProfile(p)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype talker interface {\n\ttalk() string\n}\n\n\n\ntype laser int\n\nfunc (l laser) talk() string {\n\treturn strings.Repeat(\"toot \", int(l))\n}\n\ntype rover string\n\nfunc (r rover) talk() string {\n\treturn string(r)\n}\n\nfunc main() {\n\tr := rover(\"whir whir\")\n\tshout(r)\n}\n\nfunc shout(t talker) ", "output": "{\n\tlouder := strings.ToUpper(t.talk())\n\tfmt.Println(louder)\n}"} {"input": "package transformer\n\nimport (\n\t\"github.com/cloudevents/sdk-go/v2/binding\"\n\t\"github.com/cloudevents/sdk-go/v2/binding/spec\"\n)\n\n\nfunc DeleteAttribute(attributeKind spec.Kind) binding.TransformerFunc {\n\treturn SetAttribute(attributeKind, func(i2 interface{}) (i interface{}, err error) {\n\t\treturn nil, nil\n\t})\n}\n\n\n\n\nfunc DeleteExtension(name string) binding.TransformerFunc ", "output": "{\n\treturn SetExtension(name, func(i2 interface{}) (i interface{}, err error) {\n\t\treturn nil, nil\n\t})\n}"} {"input": "package openweathermap\n\nimport \"testing\"\n\nfunc TestDailyFmtFormatLoc(t *testing.T) {\n\tlat, lon, days, key := 1.0, 2.0, 3, \"4\"\n\n\tvar test dailyFmt = \"%f %f %d %s\"\n\n\texpected := \"1.000000 2.000000 3 4\"\n\n\tif actual := test.FormatLoc(lat, lon, days, key); expected != actual {\n\t\tt.Errorf(\"Expected formatted string to be \\\"%s\\\" but was \\\"%s\\\"\",\n\t\t\texpected, actual)\n\t} \n} \n\n\n\nfunc TestDailyFmtFormatCity(t *testing.T) ", "output": "{\n\tname, country, days, key := \"Name\", \"US\", 3, \"4\"\n\n\tvar test dailyFmt = \"%s %s %d %s\"\n\n\texpected := \"Name US 3 4\"\n\n\tif actual := test.FormatCity(name, country, days, key); expected != actual {\n\t\tt.Errorf(\"Expected formatted string to be \\\"%s\\\" but was \\\"%s\\\"\",\n\t\t\texpected, actual)\n\t} \n}"} {"input": "package timeutil\n\nimport (\n\t\"time\"\n)\n\n\nfunc SetTimeout(t time.Duration, callback func()) {\n\tgo func() {\n\t\ttime.Sleep(t)\n\t\tcallback()\n\t}()\n}\n\n\n\nfunc SetInterval(t time.Duration, callback func() bool) {\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(t)\n\t\t\tif !callback() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\nfunc Nanosecond() int64 {\n\treturn time.Now().UnixNano()\n}\n\n\nfunc Microsecond() int64 {\n\treturn time.Now().UnixNano() / 1e3\n}\n\n\n\n\n\nfunc Second() int64 {\n\treturn time.Now().UnixNano() / 1e9\n}\n\n\nfunc Date() string {\n\treturn time.Now().Format(\"2006-01-02\")\n}\n\n\nfunc Datetime() string {\n\treturn time.Now().Format(\"2006-01-02 15:04:05\")\n}\n\n\n\nfunc Format(format string, timestamps ...int64) string {\n\ttimestamp := Second()\n\tif len(timestamps) > 0 {\n\t\ttimestamp = timestamps[0]\n\t}\n\treturn time.Unix(timestamp, 0).Format(format)\n}\n\n\nfunc StrToTime(format string, timestr string) (int64, error) {\n\tt, err := time.Parse(format, timestr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn t.Unix(), nil\n}\n\nfunc Millisecond() int64 ", "output": "{\n\treturn time.Now().UnixNano() / 1e6\n}"} {"input": "package evoli\n\nimport \"math/rand\"\n\ntype crosserMock struct {\n}\n\nfunc (c crosserMock) Cross(parent1, parent2 Individual) (child1, child2 Individual, err error) {\n\tw := 0.1 + 0.8*rand.Float64()\n\treturn NewIndividual(w*parent1.Fitness() + (1-w)*parent2.Fitness()),\n\t\tNewIndividual((1-w)*parent1.Fitness() + w*parent2.Fitness()),\n\t\tnil\n}\n\ntype evaluaterMock struct {\n}\n\nfunc (e evaluaterMock) Evaluate(individual Individual) (Fitness float64, err error) {\n\treturn individual.Fitness(), nil\n}\n\ntype mutaterMock struct {\n}\n\nfunc (m mutaterMock) Mutate(individual Individual, p float64) (Individual, error) {\n\treturn individual, nil\n}\n\ntype positionerMock struct {\n}\n\n\n\nfunc (p positionerMock) Position(indiv, pBest, gBest Individual, c1, c2 float64) (Individual, error) ", "output": "{\n\treturn NewIndividual((indiv.Fitness() + pBest.Fitness() + gBest.Fitness()) / 3), nil\n}"} {"input": "package gtka\n\nimport (\n\t\"github.com/coyim/gotk3adapter/gtki\"\n\t\"github.com/gotk3/gotk3/gtk\"\n)\n\ntype toolButton struct {\n\t*bin\n\tinternal *gtk.ToolButton\n}\n\n\n\nfunc WrapToolButton(v *gtk.ToolButton, e error) (gtki.ToolButton, error) {\n\treturn WrapToolButtonSimple(v), e\n}\n\nfunc UnwrapToolButton(v gtki.ToolButton) *gtk.ToolButton {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*toolButton).internal\n}\n\nfunc (v *toolButton) Add(v1 gtki.Widget) {\n\tv.internal.Add(UnwrapWidget(v1))\n}\n\nfunc WrapToolButtonSimple(v *gtk.ToolButton) gtki.ToolButton ", "output": "{\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn &toolButton{WrapBinSimple(&v.Bin).(*bin), v}\n}"} {"input": "package informers\n\nimport (\n\t\"fmt\"\n\tv1alpha1 \"github.com/jetstack-experimental/cert-manager/pkg/apis/certmanager/v1alpha1\"\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tcache \"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}\n\n\nfunc (f *genericInformer) Lister() cache.GenericLister {\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}\n\n\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) ", "output": "{\n\tswitch resource {\n\tcase v1alpha1.SchemeGroupVersion.WithResource(\"certificates\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Certmanager().V1alpha1().Certificates().Informer()}, nil\n\tcase v1alpha1.SchemeGroupVersion.WithResource(\"issuers\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Certmanager().V1alpha1().Issuers().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}"} {"input": "package endpointslice\n\n\n\ntype StaleInformerCache struct {\n\tmsg string\n}\n\nfunc (e *StaleInformerCache) Error() string { return e.msg }\n\n\n\nfunc isStaleInformerCacheErr(err error) bool ", "output": "{\n\t_, ok := err.(*StaleInformerCache)\n\treturn ok\n}"} {"input": "package golax\n\nimport \"net/http\"\n\n\n\ntype Context struct {\n\tRequest *http.Request\n\tResponse *ExtendedWriter\n\tParameter string\n\tParameters map[string]string\n\tLastError *ContextError\n\tScope map[string]interface{}\n\tPathHandlers string\n\tafters []Handler\n\tdeepInterceptors []*Interceptor\n}\n\n\n\ntype ContextError struct {\n\tStatusCode int `json:\"status_code\"`\n\tErrorCode int `json:\"error_code\"`\n\tDescription string `json:\"description_code\"`\n}\n\n\nfunc NewContext() *Context {\n\treturn &Context{\n\t\tLastError: nil,\n\t\tParameters: map[string]string{},\n\t\tScope: map[string]interface{}{},\n\t\tafters: []Handler{},\n\t\tdeepInterceptors: []*Interceptor{},\n\t}\n}\n\n\n\n\nfunc (c *Context) Set(k string, v interface{}) {\n\tc.Scope[k] = v\n}\n\n\nfunc (c *Context) Get(k string) (interface{}, bool) {\n\ta, b := c.Scope[k]\n\treturn a, b\n}\n\nfunc (c *Context) Error(s int, d string) *ContextError ", "output": "{\n\tc.Response.WriteHeader(s)\n\te := &ContextError{\n\t\tStatusCode: s,\n\t\tDescription: d,\n\t}\n\tc.LastError = e\n\treturn e\n}"} {"input": "package cli\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/antham/goller/v2/dsl\"\n\t\"github.com/antham/goller/v2/sorter\"\n\t\"gopkg.in/alecthomas/kingpin.v2\"\n)\n\nvar sortersGlobal *sorter.Sorters\n\n\ntype Sorters struct {\n\tsorters *sorter.Sorters\n}\n\n\n\n\n\nfunc (s *Sorters) Set(value string) error {\n\tparser := dsl.NewParser(bytes.NewBufferString(value))\n\n\tstmts, err := parser.ParsePositionsAndFunctions()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t(*s).sorters = sortersGlobal\n\n\tfor _, stmt := range *stmts {\n\t\t(*s).sorters.Append(stmt.Position, stmt.Functions[0].Name, stmt.Functions[0].Args)\n\t}\n\n\treturn nil\n}\n\n\nfunc (s *Sorters) ValidatePositions(positions *[]int) error {\n\tif s.sorters == nil {\n\t\treturn nil\n\t}\n\n\tfor _, sorter := range *s.sorters {\n\t\tpositionMatch := false\n\n\t\tfor _, position := range *positions {\n\t\t\tif sorter.HasPosition(position) {\n\t\t\t\tpositionMatch = true\n\t\t\t}\n\t\t}\n\n\t\tif !positionMatch {\n\t\t\treturn fmt.Errorf(\"Sort is wrong : position %d doesn't exist\", sorter.GetPosition())\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\nfunc (s *Sorters) Get() *sorter.Sorters {\n\treturn s.sorters\n}\n\n\nfunc (s *Sorters) String() string {\n\treturn \"\"\n}\n\n\nfunc SortersWrapper(s kingpin.Settings) (target *Sorters) {\n\ttarget = &Sorters{}\n\ttarget.Init()\n\ts.SetValue(target)\n\treturn\n}\n\nfunc (s *Sorters) Init() ", "output": "{\n\tsortersGlobal = sorter.NewSorters()\n}"} {"input": "package handler\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\n\tgc \"gopkg.in/check.v1\"\n)\n\n\n\nfunc (s *HandlerSuite) TestIndexMustReturnOK(c *gc.C) ", "output": "{\n\tvar (\n\t\tcfg = GetNewTestConfig(c, \"http://10.0.0.1\", \"\")\n\t\tbuildbot = &MockBuildbotApi{url: cfg.BuildBotUrl}\n\t\trouter = GetNewTestRouter(cfg, buildbot)\n\t\thandler = NewIndexHandler()\n\t)\n\n\trouter.Get(\"/foobar\", handler.ServeHTTP)\n\n\tres := httptest.NewRecorder()\n\treq, _ := http.NewRequest(\"GET\", \"/foobar\", nil)\n\n\trouter.ServeHTTP(res, req)\n\tc.Check(res.Code, gc.Equals, http.StatusOK)\n}"} {"input": "package tempconv\n\n\n\n\n\nfunc FToC(f Fahrenheit) Celsius {\n return Celsius((f - 32) * 5 / 9)\n}\n\nfunc CToF(c Celsius) Fahrenheit ", "output": "{\n return Fahrenheit(c * 9 / 5 + 32)\n}"} {"input": "package logger\n\nimport \"github.com/stretchr/testify/suite\"\nimport \"testing\"\n\ntype LoggerSuite struct {\n\tsuite.Suite\n}\n\nfunc (s *LoggerSuite) SetupTest() {\n}\n\n\n\nfunc TestLoggerAllTests(t *testing.T) ", "output": "{\n\tsuite.Run(t, new(LoggerSuite))\n}"} {"input": "package ctxhttp\n\nimport (\n\t\"net/http\"\n\n\t\"fmt\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\n\n\n\ntype Handler interface {\n\tServeHTTPContext(context.Context, http.ResponseWriter, *http.Request) error\n}\n\n\n\ntype HandlerFunc func(context.Context, http.ResponseWriter, *http.Request) error\n\n\n\nfunc (h HandlerFunc) ServeHTTPContext(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\treturn h(ctx, rw, req)\n}\n\nvar _ http.Handler = (*Adapter)(nil)\n\n\n\ntype Adapter struct {\n\tCtx context.Context \n\tHandler Handler \n\tErrorFunc AdapterErrFunc \n}\n\n\n\nfunc (ca *Adapter) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tif err := ca.Handler.ServeHTTPContext(ca.Ctx, rw, req); err != nil {\n\t\tca.ErrorFunc(rw, req, err)\n\t}\n}\n\n\n\n\n\ntype AdapterErrFunc func(http.ResponseWriter, *http.Request, error)\n\n\n\n\nvar DefaultAdapterErrFunc AdapterErrFunc = defaultAdapterErrFunc\n\nfunc defaultAdapterErrFunc(rw http.ResponseWriter, req *http.Request, err error) {\n\tcode := http.StatusBadRequest\n\thttp.Error(rw, fmt.Sprintf(\n\t\t\"%s\\nApp Error: %s\",\n\t\thttp.StatusText(code),\n\t\terr,\n\t), code)\n}\n\nfunc NewAdapter(ctx context.Context, h Handler) *Adapter ", "output": "{\n\treturn &Adapter{\n\t\tCtx: ctx,\n\t\tHandler: h,\n\t\tErrorFunc: DefaultAdapterErrFunc,\n\t}\n}"} {"input": "package nexus\n\nimport (\n\t\"github.com/davyxu/cellnet\"\n\t\"github.com/davyxu/cellnet/socket\"\n)\n\nfunc ConnectSingleton(address string, domain string) {\n\n\tcon(address, domain)\n}\n\n\n\n\nfunc con(address string, domain string) ", "output": "{\n\n\tpeer := socket.NewConnector(nil)\n\tpeer.Start(address)\n\n\tcellnet.RegisterMessage(peer, \"coredef.SessionConnected\", func(ev *cellnet.Event) {\n\n\t\tsendDomains(ev.Ses)\n\t})\n\n\tshareInit(peer)\n}"} {"input": "package decorator\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/helloticket/ffparser/helper\"\n)\n\ntype BrazilMoneyDecorator struct {\n}\n\n\n\nfunc (i *BrazilMoneyDecorator) FromString(field string) (interface{}, error) {\n\tif strings.TrimSpace(field) == \"\" {\n\t\treturn float64(0), nil\n\t}\n\tdecimalPart := field[len(field)-2:]\n\tintegerPart := field[:len(field)-2]\n\tvalue := fmt.Sprintf(\"%s.%s\", integerPart, decimalPart)\n\treturn helper.ToFloat64(value), nil\n}\n\nfunc (i *BrazilMoneyDecorator) ToString(field interface{}) (string, error) ", "output": "{\n\tif value, ok := field.(float64); ok {\n\t\tstrValue := fmt.Sprintf(\"%.2f\", value)\n\t\treturn strings.Replace(strValue, \".\", \"\", -1), nil\n\t}\n\n\treturn \"\", nil\n}"} {"input": "package model\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\ntype Index struct {\n\tFieldName string\n\tType string\n\tOrder Order\n\tUnique bool\n\tStringOrderPadLength int\n\tBase32Encode bool\n\n\tFloatFormat string\n\tFloat64Max float64\n\tFloat32Max float32\n}\n\n\ntype Order struct {\n\tFieldName string\n\tType OrderType\n}\n\nfunc (i Index) ToQuery(value interface{}) Query {\n\treturn Query{\n\t\tIndex: i,\n\t\tValue: value,\n\t\tOrder: i.Order,\n\t}\n}\n\n\nfunc ByEquality(fieldName string) Index {\n\treturn Index{\n\t\tFieldName: fieldName,\n\t\tType: indexTypeEq,\n\t\tOrder: Order{\n\t\t\tType: OrderTypeAsc,\n\t\t\tFieldName: fieldName,\n\t\t},\n\t\tStringOrderPadLength: 16,\n\t\tBase32Encode: false,\n\t\tFloatFormat: \"%019.5f\",\n\t\tFloat64Max: 92233720368547,\n\t\tFloat32Max: 922337,\n\t}\n}\n\nfunc indexMatchesQuery(i Index, q Query) bool {\n\tif strings.ToLower(i.FieldName) == strings.ToLower(q.FieldName) &&\n\t\ti.Type == q.Type &&\n\t\ti.Order.Type == q.Order.Type {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc indexesMatch(i, j Index) bool {\n\tif i.FieldName == j.FieldName &&\n\t\ti.Type == j.Type &&\n\t\ti.Order.Type == j.Order.Type {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\n\nfunc newIndex(v string) Index {\n\tidIndex := ByEquality(v)\n\tidIndex.Order.Type = OrderTypeUnordered\n\treturn idIndex\n}\n\nfunc indexPrefix(i Index) string ", "output": "{\n\tvar ordering string\n\tswitch i.Order.Type {\n\tcase OrderTypeUnordered:\n\t\tordering = \"Unord\"\n\tcase OrderTypeAsc:\n\t\tordering = \"Asc\"\n\tcase OrderTypeDesc:\n\t\tordering = \"Desc\"\n\t}\n\ttyp := i.Type\n\tif i.Type == indexTypeAll {\n\t\ttyp = indexTypeEq\n\t}\n\torderingField := i.Order.FieldName\n\tif len(orderingField) == 0 {\n\t\torderingField = i.FieldName\n\t}\n\tfilterField := i.FieldName\n\treturn fmt.Sprintf(\"%vBy%v%vBy%v\", typ, strings.Title(filterField), ordering, strings.Title(orderingField))\n}"} {"input": "package chipecs\n\nimport (\n\t\"log\"\n\n\t\"engo.io/ecs\"\n\t\"engo.io/engo\"\n\t\"engo.io/engo/common\"\n\t\"github.com/vova616/chipmunk\"\n\t\"github.com/vova616/chipmunk/vect\"\n)\n\n\n\n\n\n\nfunc (ps *PhysicsSystem) New(*ecs.World) {\n\tlog.Println(\"PhyiscsSystem was added to the scene.\")\n\tps.Space = chipmunk.NewSpace()\n\tps.Space.Gravity = vect.Vect{X: 0, Y: 0}\n}\n\n\nfunc (ps *PhysicsSystem) Update(dt float32) {\n\tfor _, e := range ps.entities {\n\t\tpos := e.PhysicsComponent.Shape.Body.Position()\n\t\te.Position = engo.Point{X: float32(pos.X), Y: float32(pos.Y)}\n\t\te.Rotation = 0 \n\t}\n\tps.Space.Step(vect.Float(dt))\n}\n\n\nfunc (ps *PhysicsSystem) Add(basic *ecs.BasicEntity, physics *PhysicsComponent, space *common.SpaceComponent) {\n\tps.entities = append(ps.entities, physicsEntity{basic, physics, space})\n\tps.Space.AddBody(physics.Shape.Body)\n}\n\nfunc (ps *PhysicsSystem) Remove(basic ecs.BasicEntity) ", "output": "{\n\tdelete := -1\n\tfor index, e := range ps.entities {\n\t\tif e.BasicEntity.ID() == basic.ID() {\n\t\t\tdelete = index\n\t\t\tps.Space.RemoveBody(e.Shape.Body)\n\t\t\tbreak\n\t\t}\n\t}\n\tif delete >= 0 {\n\t\tps.entities = append(ps.entities[:delete], ps.entities[delete+1:]...)\n\t}\n}"} {"input": "package redis\n\nimport (\n\t\"github.com/garyburd/redigo/redis\"\n\t\"time\"\n)\n\n\n\nfunc NewPool(server string) *redis.Pool ", "output": "{\n\treturn &redis.Pool{\n\t\tMaxIdle: 3,\n\t\tIdleTimeout: 240 * time.Second,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.Dial(\"tcp\", server)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, err\n\t\t},\n\t\tTestOnBorrow: func(c redis.Conn, t time.Time) error {\n\t\t\t_, err := c.Do(\"PING\")\n\t\t\treturn err\n\t\t},\n\t}\n}"} {"input": "package persistence\n\nimport (\n\t\"log\"\n\n\t\"superstellar/backend/pb\"\n\n\t\"strconv\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/service/dynamodb\"\n)\n\ntype ScoreBoardReader struct {\n\tadapter *DynamoDbAdapter\n}\n\n\n\nfunc (reader *ScoreBoardReader) ReadScoreBoard() *pb.ScoreBoard {\n\tqueryInput := &dynamodb.QueryInput{\n\t\tTableName: aws.String(\"SuperstellarScoreBoard\"),\n\t\tIndexName: aws.String(\"game-score-index\"),\n\t\tKeyConditionExpression: aws.String(\"game = :game AND score > :min_score\"),\n\t\tExpressionAttributeValues: map[string]*dynamodb.AttributeValue{\n\t\t\t\":game\": {S: aws.String(\"superstellar\")},\n\t\t\t\":min_score\": {N: aws.String(\"0\")},\n\t\t},\n\t\tScanIndexForward: aws.Bool(false),\n\t\tLimit: aws.Int64(10),\n\t}\n\n\tresp, error := reader.adapter.dynamodb.Query(queryInput)\n\tif error != nil {\n\t\tlog.Println(\"Cannot get items from DynamoDB\", error)\n\t\treturn nil\n\t}\n\n\tprotoScoreBoardItems := make([]*pb.ScoreBoardItem, 0, *resp.Count)\n\tprotoScoreBoard := &pb.ScoreBoard{Items: protoScoreBoardItems}\n\n\tfor i := range resp.Items {\n\t\titem := resp.Items[i]\n\n\t\tscore, err := strconv.Atoi(*item[\"score\"].N)\n\t\tif err == nil {\n\t\t\tscoreBoardItem := &pb.ScoreBoardItem{Name: *item[\"name\"].S, Score: uint32(score)}\n\t\t\tprotoScoreBoard.Items = append(protoScoreBoard.Items, scoreBoardItem)\n\t\t}\n\t}\n\n\treturn protoScoreBoard\n}\n\nfunc NewScoreBoardReader(adapter *DynamoDbAdapter) *ScoreBoardReader ", "output": "{\n\treturn &ScoreBoardReader{\n\t\tadapter: adapter,\n\t}\n}"} {"input": "package commands\n\nimport (\n\t\"testing\"\n\n\t\"github.com/digitalocean/doctl/do\"\n\t\"github.com/digitalocean/godo\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nvar (\n\ttestSize = do.Size{Size: &godo.Size{Slug: \"small\"}}\n\ttestSizeList = do.Sizes{testSize}\n)\n\nfunc TestSizeCommand(t *testing.T) {\n\tcmd := Size()\n\tassert.NotNil(t, cmd)\n\tassertCommandNames(t, cmd, \"list\")\n}\n\n\n\nfunc TestSizesList(t *testing.T) ", "output": "{\n\twithTestClient(t, func(config *CmdConfig, tm *tcMocks) {\n\t\ttm.sizes.On(\"List\").Return(testSizeList, nil)\n\n\t\terr := RunSizeList(config)\n\t\tassert.NoError(t, err)\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"go.bug.st/serial\"\n)\n\nfunc infoHandler(c *gin.Context) {\n\thost := c.Request.Host\n\tparts := strings.Split(host, \":\")\n\thost = parts[0]\n\n\tc.JSON(200, gin.H{\n\t\t\"version\": version,\n\t\t\"http\": \"http://\" + host + port,\n\t\t\"https\": \"https://localhost\" + portSSL,\n\t\t\"ws\": \"ws://\" + host + port,\n\t\t\"wss\": \"wss://localhost\" + portSSL,\n\t\t\"origins\": origins,\n\t\t\"update_url\": updateUrl,\n\t\t\"os\": runtime.GOOS + \":\" + runtime.GOARCH,\n\t})\n}\n\n\n\nfunc pauseHandler(c *gin.Context) ", "output": "{\n\tgo func() {\n\t\tports, _ := serial.GetPortsList()\n\t\tfor _, element := range ports {\n\t\t\tspClose(element)\n\t\t}\n\t\t*hibernate = true\n\t\tSystray.Pause()\n\t}()\n\tc.JSON(200, nil)\n}"} {"input": "package proj4go\n\nimport (\n\t\"fmt\"\n\n\tgeo \"github.com/terrascope/geometry\"\n)\n\n\ntype Projection interface {\n\tForward([]geo.Point) error\n\tInverse([]geo.Point) error\n}\n\nfunc NewProjection(proj4Str string) (Projection, error) {\n\n\tproj4, err := ParseProj4String(proj4Str)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch proj4.Proj {\n\tcase \"aea\":\n\t\treturn NewAEA(proj4), nil\n\tcase \"merc\":\n\t\treturn NewMerc(proj4), nil\n\tcase \"equi\":\n\t\treturn NewEqui(proj4), nil\n\tcase \"mill\":\n\t\treturn NewMiller(proj4), nil\n\tcase \"sinu\":\n\t\treturn NewSinu(proj4), nil\n\tcase \"longlat\":\n\t\treturn NewLonLat(proj4), nil\n\t}\n\treturn nil, fmt.Errorf(\"could not find projection %s in list\", proj4.Proj)\n}\n\nfunc Forwards(dst string, pts []geo.Point) error {\n\n\tproj, err := NewProjection(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = proj.Forward(pts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc Inverse(dst string, pts []geo.Point) error {\n\n\tproj, err := NewProjection(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = proj.Inverse(pts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc Transform(src, dst string, pts []geo.Point) error ", "output": "{\n\tif src == dst {\n\t\treturn nil\n\t}\n\n\tif err := Inverse(dst, pts); err != nil {\n\t\treturn err\n\t}\n\tif err := Forwards(src, pts); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package command\n\nimport (\n\t\"testing\"\n\n\t\"github.com/funkygao/assert\"\n\t\"github.com/funkygao/gocli\"\n)\n\n\n\nfunc TestValidateLogDirs(t *testing.T) ", "output": "{\n\td := Deploy{Ui: &cli.BasicUi{}}\n\ttype fixture struct {\n\t\tdirs string\n\t\texpected string\n\t}\n\tfixtures := []fixture{\n\t\t{\"/non-exist/kfk_demo\", \"/non-exist/kfk_demo\"},\n\t\t{\"/non-exist/kfk_demo/\", \"/non-exist/kfk_demo/\"},\n\t\t{\"/tmp/kfk_demo\", \"\"},\n\t\t{\"/tmp/kfk_demo/\", \"\"},\n\t\t{\"/kfk_demo1\", \"\"},\n\t\t{\"/kfk_demo1/\", \"\"},\n\t}\n\tfor _, f := range fixtures {\n\t\tassert.Equal(t, f.expected, d.validateLogDirs(f.dirs))\n\t}\n\n}"} {"input": "package helper\n\nimport (\n\t\"bytes\"\n\t\"github.com/alexgula/go-playground/text/template02/model\"\n\t\"github.com/sipin/gorazor/gorazor\"\n)\n\n\n\nfunc Msg(u *model.User) string ", "output": "{\n\tvar _buffer bytes.Buffer\n\n\tusername := u.Name\n\n\tif u.Email != \"\" {\n\n\t\tusername += \"(\" + u.Email + \")\"\n\n\t}\n\n\t_buffer.WriteString(\"\\n\\n
\\n\\n

Hello \")\n\t_buffer.WriteString(gorazor.HTMLEscape(username))\n\t_buffer.WriteString(\"

\\n\\n\\n\\n
\")\n\t_buffer.WriteString((u.Intro))\n\t_buffer.WriteString(\"
\\n\\n
\")\n\n\treturn _buffer.String()\n}"} {"input": "package splitter\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\nfunc NewSplitterItem(name string, conf map[string]interface{}) (Splitter, error) {\n\tswitch {\n\tcase name == \"statsd\":\n\t\treturn NewStatsdSplitter(conf)\n\tcase name == \"graphite\":\n\t\treturn NewGraphiteSplitter(conf)\n\tcase name == \"carbon2\":\n\t\treturn NewCarbonTwoSplitter(conf)\n\tcase name == \"regex\":\n\t\treturn NewRegExSplitter(conf)\n\tcase name == \"opentsdb\":\n\t\treturn NewOpenTSDBSplitter(conf)\n\tcase name == \"json\":\n\t\treturn NewJsonSplitter(conf)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Invalid splitter `%s`\", name)\n\t}\n}\n\nfunc PutSplitItem(item SplitItem) ", "output": "{\n\tswitch item.(type) {\n\tcase *GraphiteSplitItem:\n\t\tputGraphiteItem(item.(*GraphiteSplitItem))\n\tcase *StatsdSplitItem:\n\t\tputStatsdItem(item.(*StatsdSplitItem))\n\tcase *CarbonTwoSplitItem:\n\t\tputCarbonTwoItem(item.(*CarbonTwoSplitItem))\n\tcase *RegexSplitItem:\n\t\tputRegexItem(item.(*RegexSplitItem))\n\tcase *JsonSplitItem:\n\t\tputJsonItem(item.(*JsonSplitItem))\n\t}\n\n}"} {"input": "package pow\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/DanielKrawisz/bmutil\"\n)\n\n\ntype Data struct {\n\tNonceTrialsPerByte uint64\n\tExtraBytes uint64\n}\n\n\nfunc (pd *Data) Encode(w io.Writer) error {\n\tif err := bmutil.WriteVarInt(w, pd.NonceTrialsPerByte); err != nil {\n\t\treturn err\n\t}\n\n\tif err := bmutil.WriteVarInt(w, pd.ExtraBytes); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc (pd *Data) Decode(r io.Reader) (err error) {\n\tpd.NonceTrialsPerByte, err = bmutil.ReadVarInt(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpd.ExtraBytes, err = bmutil.ReadVarInt(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\n\nfunc (pd *Data) String() string ", "output": "{\n\treturn fmt.Sprintf(\"{%d, %d}\", pd.NonceTrialsPerByte, pd.ExtraBytes)\n}"} {"input": "package unibyte\n\nimport \"unicode\"\n\n\n\n\n\nfunc IsUpper(b byte) bool {\n\treturn b >= 'A' && b <= 'Z'\n}\n\n\nfunc IsLetter(b byte) bool {\n\treturn IsLower(b) || IsUpper(b)\n}\n\n\nfunc IsSpaceQuote(b byte) bool {\n\treturn IsSpace(b) || b == '\"' || b == '\\''\n}\n\n\nfunc IsSpace(b byte) bool {\n\treturn unicode.IsSpace(rune(b))\n}\n\n\nfunc ToLower(b byte) byte {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn b\n}\n\n\nfunc ToUpper(b byte) byte {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn b\n}\n\n\nfunc ToLowerString(b byte) string {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn string(b)\n}\n\n\nfunc ToUpperString(b byte) string {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn string(b)\n}\n\nfunc IsLower(b byte) bool ", "output": "{\n\treturn b >= 'a' && b <= 'z'\n}"} {"input": "package main\n\nimport (\n\t\"github.com/aarondl/dbm/config\"\n)\n\nfunc createDatabase(args []string) {\n\tengine, err := NewEngine(config.Current)\n\tif err != nil {\n\t\texitLn(\"Error getting handle to db:\", err)\n\t}\n\tif err = engine.CreateDB(); err != nil {\n\t\texitLn(\"Error creating db:\", err)\n\t}\n\ttrackdbHelper(args, engine)\n}\n\nfunc trackdb(args []string) {\n\tengine, err := NewEngine(config.Current)\n\tif err != nil {\n\t\texitLn(\"Error getting handle to db:\", err)\n\t}\n\ttrackdbHelper(args, engine)\n}\n\n\n\nfunc dropDatabase(args []string) {\n\tengine, err := NewEngine(config.Current)\n\tif err != nil {\n\t\texitLn(\"Error getting handle to db:\", err)\n\t}\n\tif err = engine.DropDB(); err != nil {\n\t\texitLn(\"Error dropping db:\", err)\n\t}\n}\n\nfunc trackdbHelper(args []string, engine SqlEngine) ", "output": "{\n\tif err := engine.Open(); err != nil {\n\t\texitLn(\"Error opening to db:\", err)\n\t}\n\tdefer engine.Close()\n\tif err := engine.CreateMigrationsTable(); err != nil {\n\t\texitLn(\"Error creating migrations table:\", err)\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"github.com/vulcand/oxy/forward\"\n\t\"github.com/vulcand/oxy/roundrobin\"\n\t\"github.com/vulcand/oxy/buffer\"\n\t\"github.com/vulcand/oxy/cbreaker\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\ntype ReverseProxy struct {\n\thandler http.Handler\n}\n\n\n\nfunc (rp *ReverseProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\trp.handler.ServeHTTP(w, r)\n}\n\nfunc NewReverseProxy(backends []string) *ReverseProxy ", "output": "{\n\tfwd, _ := forward.New()\n\tlb, _ := roundrobin.New(fwd)\n\tfor _, backend := range backends {\n\t\ttarget, _ := url.Parse(backend)\n\t\tlb.UpsertServer(target)\n\t}\n\tbuff, _ := buffer.New(lb, buffer.Retry(`(IsNetworkError() || ResponseCode() >= 500) && Attempts() < 2`))\n\tcb, _ := cbreaker.New(buff, `NetworkErrorRatio() > 0.5`)\n\treturn &ReverseProxy{handler: cb}\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSOpsWorksApp_Source struct {\n\n\tPassword string `json:\"Password,omitempty\"`\n\n\tRevision string `json:\"Revision,omitempty\"`\n\n\tSshKey string `json:\"SshKey,omitempty\"`\n\n\tType string `json:\"Type,omitempty\"`\n\n\tUrl string `json:\"Url,omitempty\"`\n\n\tUsername string `json:\"Username,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSOpsWorksApp_Source) AWSCloudFormationType() string {\n\treturn \"AWS::OpsWorks::App.Source\"\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSOpsWorksApp_Source) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\n\n\n\n\nfunc (r *AWSOpsWorksApp_Source) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSOpsWorksApp_Source) SetMetadata(metadata map[string]interface{}) ", "output": "{\n\tr._metadata = metadata\n}"} {"input": "package aes_test\n\nimport (\n\t\"github.com/keep94/vsafe/aes\"\n\t\"testing\"\n)\n\nvar (\n\tsomeKey = []byte(\"12345678901234567890123456789012\")\n)\n\n\n\nfunc TestEncryptsSameTextDifferently(t *testing.T) {\n\tencoded, err := aes.Encrypt(\"aardvark\", someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tencodedAgain, err := aes.Encrypt(\"aardvark\", someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif encoded == encodedAgain {\n\t\tt.Error(\"Expected same text to be encrypted differently every time.\")\n\t}\n}\n\nfunc TestEncryptSecurity(t *testing.T) {\n\tanotherKey := []byte(\"12345678901234567890123456789013\")\n\tencoded, err := aes.Encrypt(\"aardvark\", someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdecoded, _ := aes.Decrypt(encoded, anotherKey)\n\tif decoded == \"aardvark\" {\n\t\tt.Error(\"Expected different decryption with different key\")\n\t}\n}\n\nfunc verifyEncryptDecrypt(t *testing.T, plain string) {\n\tencoded, err := aes.Encrypt(plain, someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdecoded, err := aes.Decrypt(encoded, someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif decoded != plain {\n\t\tt.Errorf(\"Expected to get same thing back: '%s', got '%s' %d %d\", plain, decoded, len(plain), len(decoded))\n\t}\n}\n\nfunc TestEncryptDecrypt(t *testing.T) ", "output": "{\n\tverifyEncryptDecrypt(t, \"aardvark\")\n\tverifyEncryptDecrypt(t, \"1234567890123456\")\n\tverifyEncryptDecrypt(t, \"1234567890123456 \")\n\tverifyEncryptDecrypt(t, \"123456789012345 \")\n\tverifyEncryptDecrypt(t, \" now is the time for all good men to come to the aid of their party \")\n}"} {"input": "package gzip\n\nimport (\n\t\"net/http\"\n\t\"path\"\n\n\t\"github.com/mholt/caddy/middleware\"\n)\n\n\ntype Filter interface {\n\tShouldCompress(*http.Request) bool\n}\n\n\nvar defaultExtensions = []string{\"\", \".txt\", \".htm\", \".html\", \".css\", \".php\", \".js\", \".json\", \".md\", \".xml\"}\n\n\nfunc DefaultExtFilter() ExtFilter {\n\tm := ExtFilter{Exts: make(Set)}\n\tfor _, extension := range defaultExtensions {\n\t\tm.Exts.Add(extension)\n\t}\n\treturn m\n}\n\n\ntype ExtFilter struct {\n\tExts Set\n}\n\n\nconst ExtWildCard = \"*\"\n\n\n\n\nfunc (e ExtFilter) ShouldCompress(r *http.Request) bool {\n\text := path.Ext(r.URL.Path)\n\treturn e.Exts.Contains(ExtWildCard) || e.Exts.Contains(ext)\n}\n\n\ntype PathFilter struct {\n\tIgnoredPaths Set\n}\n\n\n\n\nfunc (p PathFilter) ShouldCompress(r *http.Request) bool {\n\treturn !p.IgnoredPaths.ContainsFunc(func(value string) bool {\n\t\treturn middleware.Path(r.URL.Path).Matches(value)\n\t})\n}\n\n\ntype Set map[string]struct{}\n\n\n\n\n\nfunc (s Set) Remove(value string) {\n\tdelete(s, value)\n}\n\n\nfunc (s Set) Contains(value string) bool {\n\t_, ok := s[value]\n\treturn ok\n}\n\n\n\n\nfunc (s Set) ContainsFunc(f func(string) bool) bool {\n\tfor k, _ := range s {\n\t\tif f(k) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (s Set) Add(value string) ", "output": "{\n\ts[value] = struct{}{}\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"os/user\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"sync\"\n)\n\nfunc panicOnError(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc printError() {\n\tif err := recover(); err != nil {\n\t\tfmt.Printf(\"\\033[0;31m\\033[1mError\\033[0m: %s\\n\", err)\n\t}\n}\n\nfunc printLocation(filename, location string) {\n\tfmt.Printf(\"%s is shared at \\033[1m%s\\033[0m\\n\", filename, location)\n}\n\nvar nextFileNumber = 0\nvar files = make(map[string]string)\nvar filesMutex sync.Mutex\n\n\n\nvar host, port string\n\nfunc main() {\n\tdefer printError()\n\tvar index bool\n\thostname, err := os.Hostname()\n\tpanicOnError(err)\n\tflag.Usage = func() {\n\t\tfmt.Printf(\"Usage: %s [file]...\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\tflag.StringVar(&host, \"host\", hostname, \"the host to bind to\")\n\tflag.StringVar(&port, \"port\", \"8080\", \"the port to bind to\")\n\tflag.BoolVar(&index, \"index\", false, \"show list of all shared files\")\n\tflag.Parse()\n\n\tusername, err := user.Current()\n\tpanicOnError(err)\n\taddr, err := net.ResolveUnixAddr(\"unix\", filepath.Join(os.TempDir(), \"share-\"+username.Username+\".sock\"))\n\tpanicOnError(err)\n\tl, err := net.ListenUnix(\"unix\", addr)\n\tif err == nil {\n\t\tdefer l.Close()\n\t\tserver(l, port, index)\n\t} else {\n\t\tclient(addr)\n\t}\n}\n\nfunc addFile(filename string) string ", "output": "{\n\tfilesMutex.Lock()\n\tdefer filesMutex.Unlock()\n\tnextFileNumber++\n\tfiles[path.Join(strconv.Itoa(nextFileNumber), filepath.Base(filename))] = filename\n\treturn fmt.Sprintf(\"http://%s:%s/%d/%s\", host, port, nextFileNumber, filepath.Base(filename))\n}"} {"input": "package jsonparser\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestJsonParse(t *testing.T) {\n\tparser := NewJsonParser()\n\tline := `{\"time_local\":\"2021-02-03T11:22:33+08:00\",\"request_length\":123,\"request_method\":\"GET\",\"request\":\"GET /order/2145 HTTP/1.1\",\"body_bytes_sent\":518,\"status\": 200,\"request_time\":0.544,\"upstream_response_time\":\"0.543\"}`\n\n\tgot, err := parser.ParseString(line)\n\trequire.NoError(t, err)\n\n\twant := map[string]string{\n\t\t\"time_local\": \"2021-02-03T11:22:33+08:00\",\n\t\t\"request_time\": \"0.544\",\n\t\t\"request_length\": \"123\",\n\t\t\"upstream_response_time\": \"0.543\",\n\t\t\"status\": \"200\",\n\t\t\"body_bytes_sent\": \"518\",\n\t\t\"request\": \"GET /order/2145 HTTP/1.1\",\n\t\t\"request_method\": \"GET\",\n\t}\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"JsonParser.Parse() = %v, want %v\", got, want)\n\t}\n}\n\n\n\nfunc BenchmarkParseJson(b *testing.B) ", "output": "{\n\tparser := NewJsonParser()\n\tline := `{\"time_local\":\"2021-02-03T11:22:33+08:00\",\"request_length\":123,\"request_method\":\"GET\",\"request\":\"GET /order/2145 HTTP/1.1\",\"body_bytes_sent\":518,\"status\": 200,\"request_time\":0.544,\"upstream_response_time\":\"0.543\"}`\n\n\tfor i := 0; i < b.N; i++ {\n\t\tres, err := parser.ParseString(line)\n\t\tif err != nil {\n\t\t\tb.Error(err)\n\t\t}\n\t\t_ = fmt.Sprintf(\"%v\", res)\n\t}\n}"} {"input": "package ipfs\n\n\n\n\nimport (\n\t\"github.com/go-openapi/runtime\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\n\n\ntype Client struct {\n\ttransport runtime.ClientTransport\n\tformats strfmt.Registry\n}\n\n\nfunc (a *Client) ArchiveURL(params *ArchiveURLParams) (*ArchiveURLCreated, error) {\n\tif params == nil {\n\t\tparams = NewArchiveURLParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"archiveUrl\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/archive\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &ArchiveURLReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*ArchiveURLCreated), nil\n\n}\n\n\nfunc (a *Client) SetTransport(transport runtime.ClientTransport) {\n\ta.transport = transport\n}\n\nfunc New(transport runtime.ClientTransport, formats strfmt.Registry) *Client ", "output": "{\n\treturn &Client{transport: transport, formats: formats}\n}"} {"input": "package tests\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"github.com/google/go-github/github\"\n\t\"golang.org/x/oauth2\"\n)\n\nvar (\n\tclient *github.Client\n\n\tauth bool\n)\n\nfunc init() {\n\ttoken := os.Getenv(\"GITHUB_AUTH_TOKEN\")\n\tif token == \"\" {\n\t\tprint(\"!!! No OAuth token. Some tests won't run. !!!\\n\\n\")\n\t\tclient = github.NewClient(nil)\n\t} else {\n\t\ttc := oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(\n\t\t\t&oauth2.Token{AccessToken: token},\n\t\t))\n\t\tclient = github.NewClient(tc)\n\t\tauth = true\n\t}\n\n\tvars := []string{envKeyGitHubUsername, envKeyGitHubPassword, envKeyClientID, envKeyClientSecret}\n\n\tfor _, v := range vars {\n\t\tvalue := os.Getenv(v)\n\t\tif value == \"\" {\n\t\t\tprint(\"!!! \" + fmt.Sprintf(msgEnvMissing, v) + \" !!!\\n\\n\")\n\t\t}\n\t}\n\n}\n\n\n\nfunc createRandomTestRepository(owner string, autoinit bool) (*github.Repository, error) {\n\tvar repoName string\n\tfor {\n\t\trepoName = fmt.Sprintf(\"test-%d\", rand.Int())\n\t\t_, resp, err := client.Repositories.Get(owner, repoName)\n\t\tif err != nil {\n\t\t\tif resp.StatusCode == http.StatusNotFound {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\trepo, _, err := client.Repositories.Create(\"\", &github.Repository{Name: github.String(repoName), AutoInit: github.Bool(autoinit)})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn repo, nil\n}\n\nfunc checkAuth(name string) bool ", "output": "{\n\tif !auth {\n\t\tfmt.Printf(\"No auth - skipping portions of %v\\n\", name)\n\t}\n\treturn auth\n}"} {"input": "package control\n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\nvar (\n\tBuildSessionConfigs = buildSessionConfigs\n\tComputeDiff = computeDiff\n\tNewPathPolForEnteringAS = newPathPolForEnteringAS\n\tNewPrefixWatcher = newPrefixWatcher\n\n\tCopyPathPolicy = copyPathPolicy\n\tBuildRoutingChains = buildRoutingChains\n)\n\ntype ConjunctionPathPol = conjuctionPathPol\ntype Diff = diff\n\nfunc (w *GatewayWatcher) RunOnce(ctx context.Context) {\n\tw.run(ctx)\n}\n\nfunc (w *GatewayWatcher) RunAllPrefixWatchersOnceForTest(ctx context.Context) {\n\tvar wg sync.WaitGroup\n\tfor _, wi := range w.currentWatchers {\n\t\twi := wi\n\t\twi.prefixWatcher.resetRunMarker()\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\twi.prefixWatcher.Run(ctx)\n\t\t}()\n\t}\n\twg.Wait()\n}\n\n\n\nfunc (w *prefixWatcher) resetRunMarker() ", "output": "{\n\tw.runMarkerLock.Lock()\n\tdefer w.runMarkerLock.Unlock()\n\tw.runMarker = false\n}"} {"input": "package server\n\nimport \"github.com/poy/petasos/router\"\n\ntype RouterFetcher struct {\n\tfs router.FileSystem\n\thasher router.Hasher\n\tmetricsCounter router.MetricsCounter\n}\n\nfunc NewRouterFetcher(\n\tfs router.FileSystem,\n\thasher router.Hasher,\n\tmetricsCounter router.MetricsCounter,\n) *RouterFetcher {\n\treturn &RouterFetcher{fs: fs, hasher: hasher, metricsCounter: metricsCounter}\n}\n\n\n\nfunc (f *RouterFetcher) Writer() (writer func(data []byte) (err error), err error) ", "output": "{\n\treturn router.New(f.fs, f.hasher, f.metricsCounter).Write, nil\n}"} {"input": "package test_test\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n\n\t\"github.com/nyaruka/goflow/test\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestJSONReplace(t *testing.T) {\n\tassert.Equal(t, json.RawMessage(`{\"foo\":\"x\",\"bar\":2}`), test.JSONReplace(json.RawMessage(`{\"foo\":1,\"bar\":2}`), []string{\"foo\"}, json.RawMessage(`\"x\"`)))\n}\n\nfunc TestAssertEqualJSON(t *testing.T) ", "output": "{\n\tassert.True(t, test.AssertEqualJSON(t, json.RawMessage(`{\"foo\":1,\"bar\":2}`), json.RawMessage(`{\"bar\": 2, \"foo\": 1}`), \"doh!\"))\n}"} {"input": "package testdata\n\nimport (\n\t\"github.com/semrush/zenrpc/v2\"\n)\n\ntype Group struct {\n\tId int `json:\"id\"`\n\tTitle string `json:\"title\"`\n\tNodes []Group `json:\"nodes\"`\n\tGroups []Group `json:\"group\"`\n\tChildOpt *Group `json:\"child\"`\n\tSub SubGroup `json:\"sub\"`\n}\n\ntype SubGroup struct {\n\tId int `json:\"id\"`\n\tTitle string `json:\"title\"`\n}\n\ntype Campaign struct {\n\tId int `json:\"id\"`\n\tGroups []Group `json:\"group\"`\n}\n\ntype CatalogueService struct{ zenrpc.Service }\n\nfunc (s CatalogueService) First(groups []Group) (bool, error) {\n\treturn true, nil\n}\n\nfunc (s CatalogueService) Second(campaigns []Campaign) (bool, error) {\n\treturn true, nil\n}\n\n\n\nfunc (s CatalogueService) Third() (Campaign, error) ", "output": "{\n\treturn Campaign{}, nil\n}"} {"input": "package flags\n\n\n\n\n\n\n\nimport (\n\t\"strings\"\n\n\t\"github.com/BytemarkHosting/bytemark-client/cmd/bytemark/app\"\n)\n\n\n\n\ntype AccountNameSliceFlag []AccountNameFlag\n\n\nfunc (sf *AccountNameSliceFlag) Preprocess(ctx *app.Context) error {\n\tfor i := range *sf {\n\t\terr := (*sf)[i].Preprocess(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (sf AccountNameSliceFlag) String() string {\n\tstrs := make([]string, len(sf))\n\tfor i, value := range sf {\n\t\tstrs[i] = value.String()\n\t}\n\treturn strings.Join(strs, \", \")\n}\n\n\n\nfunc AccountNameSlice(ctx *app.Context, name string) AccountNameSliceFlag {\n\tif sf, ok := ctx.Context.Generic(name).(*AccountNameSliceFlag); ok {\n\t\treturn *sf\n\t}\n\treturn AccountNameSliceFlag{}\n}\n\nfunc (sf *AccountNameSliceFlag) Set(value string) error ", "output": "{\n\tflag := AccountNameFlag{}\n\terr := flag.Set(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*sf = append(*sf, flag)\n\treturn nil\n}"} {"input": "package core\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype PlatformConfig interface {\n}\n\ntype platformconfig struct {\n\tJsonData []byte\n\tType string `json:\"type\"`\n}\n\n\nfunc (m *platformconfig) UnmarshalJSON(data []byte) error {\n\tm.JsonData = data\n\ttype Unmarshalerplatformconfig platformconfig\n\ts := struct {\n\t\tModel Unmarshalerplatformconfig\n\t}{}\n\terr := json.Unmarshal(data, &s.Model)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Type = s.Model.Type\n\n\treturn err\n}\n\n\n\n\nfunc (m platformconfig) String() string {\n\treturn common.PointerString(m)\n}\n\n\ntype PlatformConfigTypeEnum string\n\n\nconst (\n\tPlatformConfigTypeAmdMilanBm PlatformConfigTypeEnum = \"AMD_MILAN_BM\"\n)\n\nvar mappingPlatformConfigType = map[string]PlatformConfigTypeEnum{\n\t\"AMD_MILAN_BM\": PlatformConfigTypeAmdMilanBm,\n}\n\n\nfunc GetPlatformConfigTypeEnumValues() []PlatformConfigTypeEnum {\n\tvalues := make([]PlatformConfigTypeEnum, 0)\n\tfor _, v := range mappingPlatformConfigType {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}\n\nfunc (m *platformconfig) UnmarshalPolymorphicJSON(data []byte) (interface{}, error) ", "output": "{\n\n\tif data == nil || string(data) == \"null\" {\n\t\treturn nil, nil\n\t}\n\n\tvar err error\n\tswitch m.Type {\n\tcase \"AMD_MILAN_BM\":\n\t\tmm := AmdMilanBmPlatformConfig{}\n\t\terr = json.Unmarshal(data, &mm)\n\t\treturn mm, err\n\tdefault:\n\t\treturn *m, nil\n\t}\n}"} {"input": "package socket\n\nimport \"sync\"\n\n\ntype PacketHandler interface {\n\tOnPacket(Packet)\n}\n\n\n\n\ntype EventHandler interface {\n\tOn(event string, fn interface{}) error\n}\n\n\ntype Handler interface {\n\tEventHandler\n\tPacketHandler\n}\n\ntype handler struct {\n\tmu sync.RWMutex\n\tevents map[string]PacketHandler\n}\n\n\n\nfunc (h *handler) On(event string, fn interface{}) (err error) {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.events[event], err = newPacketHandler(fn)\n\treturn err\n}\n\nfunc (h *handler) OnPacket(p Packet) {\n\th.mu.RLock()\n\tc, ok := h.events[p.Event()]\n\th.mu.RUnlock()\n\n\tif ok {\n\t\tc.OnPacket(p)\n\t}\n}\n\nfunc newHandler() Handler ", "output": "{\n\treturn &handler{\n\t\tevents: make(map[string]PacketHandler),\n\t}\n}"} {"input": "package env\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestEnvGet(t *testing.T) {\n\tgopath := Get(\"GOPATH\", \"\")\n\tif gopath != os.Getenv(\"GOPATH\") {\n\t\tt.Error(\"expected GOPATH not empty.\")\n\t}\n\n\tnoExistVar := Get(\"NOEXISTVAR\", \"foo\")\n\tif noExistVar != \"foo\" {\n\t\tt.Errorf(\"expected NOEXISTVAR to equal foo, got %s.\", noExistVar)\n\t}\n}\n\nfunc TestEnvMustGet(t *testing.T) {\n\tgopath, err := MustGet(\"GOPATH\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif gopath != os.Getenv(\"GOPATH\") {\n\t\tt.Errorf(\"expected GOPATH to be the same, got %s.\", gopath)\n\t}\n\n\t_, err = MustGet(\"NOEXISTVAR\")\n\tif err == nil {\n\t\tt.Error(\"expected error to be non-nil\")\n\t}\n}\n\nfunc TestEnvSet(t *testing.T) {\n\tSet(\"MYVAR\", \"foo\")\n\tmyVar := Get(\"MYVAR\", \"bar\")\n\tif myVar != \"foo\" {\n\t\tt.Errorf(\"expected MYVAR to equal foo, got %s.\", myVar)\n\t}\n}\n\nfunc TestEnvMustSet(t *testing.T) {\n\terr := MustSet(\"FOO\", \"bar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tfooVar := os.Getenv(\"FOO\")\n\tif fooVar != \"bar\" {\n\t\tt.Errorf(\"expected FOO variable to equal bar, got %s.\", fooVar)\n\t}\n}\n\n\n\nfunc TestEnvGetAll(t *testing.T) ", "output": "{\n\tenvMap := GetAll()\n\tif len(envMap) == 0 {\n\t\tt.Error(\"expected environment not empty.\")\n\t}\n}"} {"input": "package generators\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n)\n\n\n\nfunc TestRemoveLastDir(t *testing.T) ", "output": "{\n\ttable := map[string]struct{ newPath, removedDir string }{\n\t\t\"a/b/c\": {\"a/c\", \"b\"},\n\t}\n\tfor slashInput, expect := range table {\n\t\tinput := filepath.FromSlash(slashInput)\n\n\t\tgotPath, gotRemoved := removeLastDir(input)\n\t\tif e, a := filepath.FromSlash(expect.newPath), gotPath; e != a {\n\t\t\tt.Errorf(\"%v: wanted %v, got %v\", input, e, a)\n\t\t}\n\t\tif e, a := filepath.FromSlash(expect.removedDir), gotRemoved; e != a {\n\t\t\tt.Errorf(\"%v: wanted %v, got %v\", input, e, a)\n\t\t}\n\t}\n}"} {"input": "package codec\n\nimport (\n\t\"fmt\"\n\t\"github.com/davyxu/cellnet\"\n)\n\nvar registedCodecs []cellnet.Codec\n\n\nfunc RegisterCodec(c cellnet.Codec) {\n\n\tif GetCodec(c.Name()) != nil {\n\t\tpanic(\"duplicate codec: \" + c.Name())\n\t}\n\n\tregistedCodecs = append(registedCodecs, c)\n}\n\n\n\n\n\nfunc getPackageByCodecName(name string) string {\n\tswitch name {\n\tcase \"binary\":\n\t\treturn \"github.com/davyxu/cellnet/codec/binary\"\n\tcase \"gogopb\":\n\t\treturn \"github.com/davyxu/cellnet/codec/gogopb\"\n\tcase \"httpjson\":\n\t\treturn \"github.com/davyxu/cellnet/codec/httpjson\"\n\tcase \"json\":\n\t\treturn \"github.com/davyxu/cellnet/codec/json\"\n\tcase \"protoplus\":\n\t\treturn \"github.com/davyxu/cellnet/codec/protoplus\"\n\tdefault:\n\t\treturn \"package/to/your/codec\"\n\t}\n}\n\n\nfunc MustGetCodec(name string) cellnet.Codec {\n\tcodec := GetCodec(name)\n\n\tif codec == nil {\n\t\tpanic(fmt.Sprintf(\"codec not found '%s'\\ntry to add code below:\\nimport (\\n _ \\\"%s\\\"\\n)\\n\\n\",\n\t\t\tname,\n\t\t\tgetPackageByCodecName(name)))\n\t}\n\n\treturn codec\n}\n\nfunc GetCodec(name string) cellnet.Codec ", "output": "{\n\n\tfor _, c := range registedCodecs {\n\t\tif c.Name() == name {\n\t\t\treturn c\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package imagemanager\n\nimport (\n\t\"github.com/juju/names/v4\"\n\n\t\"github.com/juju/juju/state\"\n\t\"github.com/juju/juju/state/imagestorage\"\n)\n\ntype stateInterface interface {\n\tImageStorage() imagestorage.Storage\n\tControllerTag() names.ControllerTag\n}\n\ntype stateShim struct {\n\t*state.State\n}\n\n\n\nfunc (s stateShim) ImageStorage() imagestorage.Storage ", "output": "{\n\treturn s.State.ImageStorage()\n}"} {"input": "package credentials\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype stubProvider struct {\n\tcreds Value\n\terr error\n}\n\nfunc (s *stubProvider) Retrieve() (Value, error) {\n\ts.creds.ProviderName = \"stubProvider\"\n\treturn s.creds, s.err\n}\n\n\n\nfunc TestCredentialsGetWithError(t *testing.T) {\n\tc := NewCredentials(&stubProvider{err: errors.New(\"provider error\")})\n\n\t_, err := c.Get()\n\tassert.Equal(t, \"provider error\", err.Error(), \"Expected provider error\")\n}\n\nfunc TestCredentialsGetWithProviderName(t *testing.T) {\n\tstub := &stubProvider{}\n\n\tc := NewCredentials(stub)\n\n\tcreds, err := c.Get()\n\tassert.Nil(t, err, \"Expected no error\")\n\tassert.Equal(t, creds.ProviderName, \"stubProvider\", \"Expected provider name to match\")\n}\n\nfunc TestCredentialsGet(t *testing.T) ", "output": "{\n\tc := NewCredentials(&stubProvider{\n\t\tcreds: Value{\n\t\t\tAccessKeyID: \"AKID\",\n\t\t\tSecretAccessKey: \"SECRET\",\n\t\t},\n\t})\n\n\tcreds, err := c.Get()\n\tassert.Nil(t, err, \"Expected no error\")\n\tassert.Equal(t, \"AKID\", creds.AccessKeyID, \"Expect access key ID to match\")\n\tassert.Equal(t, \"SECRET\", creds.SecretAccessKey, \"Expect secret access key to match\")\n}"} {"input": "package iso20022\n\n\ntype SettlementDetails88 struct {\n\n\tTradeDate *ISODateTime `xml:\"TradDt\"`\n\n\tSettlementParties *SettlementParties3Choice `xml:\"SttlmPties,omitempty\"`\n\n\tCollateralOwnership *CollateralOwnership1 `xml:\"CollOwnrsh\"`\n}\n\n\n\nfunc (s *SettlementDetails88) AddSettlementParties() *SettlementParties3Choice {\n\ts.SettlementParties = new(SettlementParties3Choice)\n\treturn s.SettlementParties\n}\n\nfunc (s *SettlementDetails88) AddCollateralOwnership() *CollateralOwnership1 {\n\ts.CollateralOwnership = new(CollateralOwnership1)\n\treturn s.CollateralOwnership\n}\n\nfunc (s *SettlementDetails88) SetTradeDate(value string) ", "output": "{\n\ts.TradeDate = (*ISODateTime)(&value)\n}"} {"input": "package str\n\nimport (\n\t\"strings\"\n)\n\n\n\nfunc SplitBy(sv string, sep string) []string {\n\tfiltered := make([]string, 0)\n\tfor _, part := range strings.Split(sv, sep) {\n\t\tpart = Trim(part)\n\t\tif part != \"\" {\n\t\t\tfiltered = append(filtered, part)\n\t\t}\n\t}\n\treturn filtered\n}\n\n\n\n\n\nfunc Comma(csv string) []string ", "output": "{\n\treturn SplitBy(csv, \",\")\n}"} {"input": "package resolvers\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/emwalker/digraph/cmd/frontend/loaders\"\n\t\"github.com/emwalker/digraph/cmd/frontend/models\"\n\t\"github.com/volatiletech/sqlboiler/queries/qm\"\n)\n\ntype organizationResolver struct {\n\t*Resolver\n}\n\nfunc getOrganizationLoader(ctx context.Context) *loaders.OrganizationLoader {\n\treturn ctx.Value(loaders.OrganizationLoaderKey).(*loaders.OrganizationLoader)\n}\n\nfunc fetchOrganization(ctx context.Context, organizationID string) (*models.Organization, error) {\n\tloader := getOrganizationLoader(ctx)\n\torg, err := loader.Load(organizationID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn org, nil\n}\n\n\n\n\n\nfunc (r *organizationResolver) DefaultRepository(ctx context.Context, org *models.Organization) (*models.Repository, error) {\n\trepo, err := org.Repositories(qm.Where(\"system\")).One(ctx, r.DB)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn repo, nil\n}\n\n\nfunc (r *organizationResolver) ResourcePath(\n\t_ context.Context, org *models.Organization,\n) (string, error) {\n\treturn \"/organizations/\" + org.ID, nil\n}\n\n\nfunc (r *organizationResolver) UpdatedAt(\n\t_ context.Context, org *models.Organization,\n) (string, error) {\n\treturn org.UpdatedAt.Format(time.RFC3339), nil\n}\n\nfunc (r *organizationResolver) CreatedAt(_ context.Context, org *models.Organization) (string, error) ", "output": "{\n\treturn org.CreatedAt.Format(time.RFC3339), nil\n}"} {"input": "package bootstrap\n\nimport (\n\t\"io/ioutil\"\n\n\t\"github.com/tomogoma/go-api-guard\"\n\t\"github.com/tomogoma/jwt\"\n\t\"github.com/tomogoma/seedms/pkg/config\"\n\t\"github.com/tomogoma/seedms/pkg/db/roach\"\n\t\"github.com/tomogoma/seedms/pkg/logging\"\n\t\"github.com/tomogoma/crdb\"\n)\n\ntype Deps struct {\n\tConfig config.General\n\tGuard *api.Guard\n\tRoach *roach.Roach\n\tJWTEr *jwt.Handler\n}\n\n\n\nfunc InstantiateJWTHandler(lg logging.Logger, tknKyF string) *jwt.Handler {\n\tJWTKey, err := ioutil.ReadFile(tknKyF)\n\tlogging.LogFatalOnError(lg, err, \"Read JWT key file\")\n\tjwter, err := jwt.NewHandler(JWTKey)\n\tlogging.LogFatalOnError(lg, err, \"Instantiate JWT handler\")\n\treturn jwter\n}\n\nfunc Instantiate(confFile string, lg logging.Logger) Deps {\n\n\tconf, err := config.ReadFile(confFile)\n\tlogging.LogFatalOnError(lg, err, \"Read config file\")\n\n\trdb := InstantiateRoach(lg, conf.Database)\n\ttg := InstantiateJWTHandler(lg, conf.Service.AuthTokenKeyFile)\n\n\tg, err := api.NewGuard(rdb, api.WithMasterKey(conf.Service.MasterAPIKey))\n\tlogging.LogFatalOnError(lg, err, \"Instantate API access guard\")\n\n\treturn Deps{Config: conf, Guard: g, Roach: rdb, JWTEr: tg}\n}\n\nfunc InstantiateRoach(lg logging.Logger, conf crdb.Config) *roach.Roach ", "output": "{\n\tvar opts []roach.Option\n\tif dsn := conf.FormatDSN(); dsn != \"\" {\n\t\topts = append(opts, roach.WithDSN(dsn))\n\t}\n\tif dbn := conf.DBName; dbn != \"\" {\n\t\topts = append(opts, roach.WithDBName(dbn))\n\t}\n\trdb := roach.NewRoach(opts...)\n\terr := rdb.InitDBIfNot()\n\tlogging.LogWarnOnError(lg, err, \"Initiate Cockroach DB connection\")\n\treturn rdb\n}"} {"input": "package main\n\nimport (\n\t\"github.com/acmacalister/skittles\"\n\t\"gopkg.in/yaml.v1\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n)\n\ntype Configuration struct {\n\tServers []string `yaml:\"servers\"`\n\tUsername string `yaml:\"username\"`\n\tPassword string `yaml:\"password\"`\n\tPemfile string `yaml:\"pemfile\"`\n\tTaskList []string `yaml:\"task_list\"`\n}\n\n\n\nfunc loadConfig(environment string) Configuration ", "output": "{\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatal(skittles.Red(err))\n\t}\n\tbuffer, err := ioutil.ReadFile(dir + \"/kirk.yml\")\n\n\tif err != nil {\n\t\tlog.Fatal(skittles.Red(err))\n\t}\n\n\tm := make(map[string]Configuration)\n\tif err := yaml.Unmarshal(buffer, &m); err != nil {\n\t\tlog.Fatal(skittles.Red(err))\n\t}\n\n\treturn m[environment]\n}"} {"input": "package dexcom\n\nimport (\n\t\"math\"\n)\n\n\n\nfunc marshalUint16(n uint16) []byte {\n\treturn []byte{byte(n & 0xFF), byte(n >> 8)}\n}\n\n\nfunc marshalInt16(n int16) []byte {\n\treturn marshalUint16(uint16(n))\n}\n\nfunc marshalUint32(n uint32) []byte {\n\treturn append(marshalUint16(uint16(n&0xFFFF)), marshalUint16(uint16(n>>16))...)\n}\n\nfunc marshalInt32(n int32) []byte {\n\treturn marshalUint32(uint32(n))\n}\n\nfunc unmarshalUint16(v []byte) uint16 {\n\treturn uint16(v[0]) | uint16(v[1])<<8\n}\n\n\n\n\nfunc unmarshalUint32(v []byte) uint32 {\n\treturn uint32(unmarshalUint16(v[0:2])) | uint32(unmarshalUint16(v[2:4]))<<16\n}\n\nfunc unmarshalInt32(v []byte) int32 {\n\treturn int32(unmarshalUint32(v))\n}\n\nfunc unmarshalUint64(v []byte) uint64 {\n\treturn uint64(unmarshalUint32(v[0:4])) | uint64(unmarshalUint32(v[4:8]))<<32\n}\n\nfunc unmarshalFloat64(v []byte) float64 {\n\treturn math.Float64frombits(unmarshalUint64(v))\n}\n\nfunc unmarshalInt16(v []byte) int16 ", "output": "{\n\treturn int16(unmarshalUint16(v))\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/taironas/auth\"\n)\n\nfunc main() {\n\thttp.Handle(\"/\", http.FileServer(http.Dir(\".\")))\n\thttp.HandleFunc(\"/api/token\", tokenHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\n\n\nfunc tokenHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tIDToken := r.FormValue(\"id_token\")\n\n\tif user, err := auth.Google(IDToken); err != nil {\n\t\tfmt.Fprintf(w, \"error: %v\", err)\n\t} else {\n\t\tjson.NewEncoder(w).Encode(user)\n\t}\n}"} {"input": "package timer\n\nimport (\n\t\"container/heap\"\n\t\"time\"\n\n\t\"github.com/idealeak/goserver/core\"\n\t\"github.com/idealeak/goserver/core/basic\"\n)\n\ntype startTimerCommand struct {\n\tsrc *basic.Object\n\tta TimerAction\n\tud interface{}\n\tinterval time.Duration\n\ttimes int\n\th TimerHandle\n}\n\nfunc (stc *startTimerCommand) Done(o *basic.Object) error {\n\tdefer o.ProcessSeqnum()\n\n\tte := &TimerEntity{\n\t\tsink: stc.src,\n\t\tud: stc.ud,\n\t\tta: stc.ta,\n\t\tinterval: stc.interval,\n\t\ttimes: stc.times,\n\t\th: stc.h,\n\t\tnext: time.Now().Add(stc.interval),\n\t}\n\n\theap.Push(TimerModule.tq, te)\n\n\treturn nil\n}\n\n\n\nfunc AfterTimer(taw TimerActionWrapper, ud interface{}, interval time.Duration) (TimerHandle, bool) {\n\tvar tac = &TimerActionCommon{\n\t\tTaw: taw,\n\t}\n\treturn StartTimerByObject(core.CoreObject(), tac, ud, interval, 1)\n}\n\nfunc StartTimerByObject(src *basic.Object, ta TimerAction, ud interface{}, interval time.Duration, times int) (TimerHandle, bool) {\n\th := generateTimerHandle()\n\tret := TimerModule.SendCommand(\n\t\t&startTimerCommand{\n\t\t\tsrc: src,\n\t\t\tta: ta,\n\t\t\tud: ud,\n\t\t\tinterval: interval,\n\t\t\ttimes: times,\n\t\t\th: h,\n\t\t},\n\t\ttrue)\n\treturn h, ret\n}\n\nfunc StartTimer(ta TimerAction, ud interface{}, interval time.Duration, times int) (TimerHandle, bool) ", "output": "{\n\treturn StartTimerByObject(core.CoreObject(), ta, ud, interval, times)\n}"} {"input": "package dnsclient\n\nimport (\n\t\"net\"\n\t\"strings\"\n)\n\n\ntype Records []*Record\n\n\nfunc (r Records) ByName(name string) (res Records) {\n\tif name == \"\" {\n\t\treturn r\n\t}\n\tname = strings.ToLower(name)\n\tfor _, record := range r {\n\t\tif strings.ToLower(record.Name) == name {\n\t\t\tres = append(res, record)\n\t\t}\n\t}\n\treturn res\n}\n\n\nfunc (r Records) ByType(typ string) (res Records) {\n\tif typ == \"\" {\n\t\treturn r\n\t}\n\ttyp = strings.ToLower(typ)\n\tfor _, record := range r {\n\t\tif strings.ToLower(record.Type) == typ {\n\t\t\tres = append(res, record)\n\t\t}\n\t}\n\treturn res\n}\n\n\nfunc (r Records) ByValue(value string) (res Records) {\n\tif value == \"\" {\n\t\treturn r\n\t}\n\tfor _, record := range r {\n\t\tif record.IP == value {\n\t\t\tres = append(res, record)\n\t\t}\n\t}\n\treturn res\n}\n\n\nfunc (r Records) User() (res Records) {\n\tfor _, record := range r {\n\t\ttyp := strings.ToLower(record.Type)\n\n\t\tif typ != \"soa\" && typ != \"ns\" {\n\t\t\tres = append(res, record)\n\t\t}\n\t}\n\treturn res\n}\n\n\nfunc (r Records) Filter(f *Record) Records {\n\tif f == nil {\n\t\treturn r\n\t}\n\treturn r.ByValue(f.IP).ByType(f.Type).ByName(f.Name)\n}\n\n\n\n\n\nfunc ParseRecord(domain, address string) *Record ", "output": "{\n\thost, _, err := net.SplitHostPort(address)\n\tif err == nil {\n\t\taddress = host\n\t}\n\n\tif net.ParseIP(address) != nil {\n\t\treturn &Record{\n\t\t\tName: domain,\n\t\t\tType: \"A\",\n\t\t\tIP: address,\n\t\t\tTTL: 30,\n\t\t}\n\t}\n\n\treturn &Record{\n\t\tName: domain,\n\t\tType: \"CNAME\",\n\t\tIP: address,\n\t\tTTL: 30,\n\t}\n}"} {"input": "package github\n\nimport (\n\t\"sync\"\n\n\t\"k8s.io/kubernetes/pkg/util/sets\"\n)\n\n\ntype StatusChange struct {\n\theads map[int]string \n\tpullRequests map[string]sets.Int \n\tchanged sets.String \n\tmutex sync.Mutex\n}\n\n\n\n\n\nfunc (s *StatusChange) UpdatePullRequestHead(pullRequestID int, newHead string) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tif oldHead, has := s.heads[pullRequestID]; has {\n\t\tdelete(s.pullRequests, oldHead)\n\t}\n\ts.heads[pullRequestID] = newHead\n\tif _, has := s.pullRequests[newHead]; !has {\n\t\ts.pullRequests[newHead] = sets.NewInt()\n\t}\n\ts.pullRequests[newHead].Insert(pullRequestID)\n}\n\n\nfunc (s *StatusChange) CommitStatusChanged(commit string) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\ts.changed.Insert(commit)\n}\n\n\nfunc (s *StatusChange) PopChangedPullRequests() []int {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tchangedPullRequests := sets.NewInt()\n\tfor _, commit := range s.changed.List() {\n\t\tif pullRequests, has := s.pullRequests[commit]; has {\n\t\t\tchangedPullRequests = changedPullRequests.Union(pullRequests)\n\t\t}\n\t}\n\ts.changed = sets.NewString()\n\n\treturn changedPullRequests.List()\n}\n\nfunc NewStatusChange() *StatusChange ", "output": "{\n\treturn &StatusChange{\n\t\theads: map[int]string{},\n\t\tpullRequests: map[string]sets.Int{},\n\t\tchanged: sets.NewString(),\n\t}\n}"} {"input": "package helpers\n\nimport (\n\t\"fmt\"\n\t\"os/user\"\n\t\"os\"\n\t\"runtime\"\n\t\"time\"\n\t\"log\"\n\t\"github.com/joho/godotenv\"\n)\n\n\n\nfunc IsDocker() bool {\n\treturn os.Getenv(\"HOME\") == \"/root\"\n}\n\nfunc MonitorRuntime() {\n\tlog.Println(\"Number of CPUs:\", runtime.NumCPU())\n\tm := &runtime.MemStats{}\n\tfor {\n\t\tr := runtime.NumGoroutine()\n\t\tlog.Println(\"Number of goroutines\", r)\n\t\truntime.ReadMemStats(m)\n\t\tlog.Println(\"Allocated memory\", m.Alloc)\n\t\ttime.Sleep(10 * time.Second)\n\t}\n}\n\nfunc LoadEnvFile() {\n\terr := godotenv.Load()\n\tif err != nil {\n\t\tpanic(\"Error loading .env file\" + err.Error())\n\t}\n}\n\nfunc CurrentUser() *user.User ", "output": "{\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tSendErrorEmail(\"golang balu\", fmt.Sprintf(\"failed get current user: %s\", err))\n\t\tpanic(err)\n\t}\n\treturn usr\n}"} {"input": "package internal\n\ntype cacheError string\n\n\n\nconst (\n\tNotFoundError = cacheError(\"key not found\")\n\tNilValueError = cacheError(\"value pointer shouldn`t be nil\")\n\tCloseError = cacheError(\"cache has been closed\")\n\n\tchunksNegativeSliceSize = cacheError(\"sliceLen should be non-negative\")\n\tchunksNegativeSize = cacheError(\"chunkSize should be positive\")\n)\n\nfunc (e cacheError) Error() string ", "output": "{ return string(e) }"} {"input": "package flog\n\nimport \"github.com/Sirupsen/logrus\"\n\ntype Parameter interface {\n\tConvert() map[string]interface{}\n}\n\ntype Fields struct {\n\tEvent string\n\tError error\n}\n\nfunc (f Fields) Convert() map[string]interface{} {\n\tfields := map[string]interface{}{}\n\n\tif f.Event != \"\" {\n\t\tfields[\"event\"] = f.Event\n\t}\n\n\tif f.Error != nil {\n\t\tfields[\"error\"] = f.Error\n\t}\n\n\treturn fields\n}\n\ntype Details map[string]interface{}\n\nfunc (d Details) Convert() map[string]interface{} {\n\treturn d\n}\n\ntype DebugFields map[string]interface{}\n\nfunc (d DebugFields) Convert() map[string]interface{} {\n\treturn map[string]interface{}{}\n}\n\nfunc transform(params []Parameter) logrus.Fields {\n\tlogrusFields := logrus.Fields{}\n\n\tfor _, p := range params {\n\t\tfieldMap := p.Convert()\n\n\t\tfor k, v := range fieldMap {\n\t\t\tlogrusFields[k] = v\n\t\t}\n\t}\n\n\treturn logrusFields\n}\n\n\n\nfunc Info(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Info(msg)\n}\n\nfunc Warn(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Warning(msg)\n}\n\nfunc Error(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Error(msg)\n}\n\nfunc Fatal(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Fatal(msg)\n}\n\nfunc Panic(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Panic(msg)\n}\n\nfunc Debug(msg string, params ...Parameter) ", "output": "{\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Debug(msg)\n}"} {"input": "package plain\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t. \"github.com/SimonRichardson/wishful-route/route\"\n\t. \"github.com/SimonRichardson/wishful/useful\"\n\t. \"github.com/SimonRichardson/wishful/wishful\"\n)\n\nfunc NewPlainResult(statusCode int, body string) Result {\n\treturn NewResult(body, statusCode, NewHeaders(map[string]string{\n\t\t\"Content-Length\": fmt.Sprintf(\"%d\", len(body)),\n\t\t\"Content-Type\": \"text/plain\",\n\t}))\n}\n\nfunc Ok(body string) Promise {\n\treturn NewPromise(func(resolve func(x AnyVal) AnyVal) AnyVal {\n\t\treturn resolve(NewPlainResult(http.StatusOK, body))\n\t})\n}\n\nfunc NotFound(body string) Promise {\n\treturn NewPromise(func(resolve func(x AnyVal) AnyVal) AnyVal {\n\t\treturn resolve(NewPlainResult(http.StatusNotFound, body))\n\t})\n}\n\n\n\nfunc Redirect(url string) Promise {\n\treturn NewPromise(func(resolve func(x AnyVal) AnyVal) AnyVal {\n\t\treturn resolve(NewResult(\"\", http.StatusFound, NewHeaders(map[string]string{\n\t\t\t\"Location\": url,\n\t\t})))\n\t})\n}\n\nfunc InternalServerError(body string) Promise ", "output": "{\n\treturn NewPromise(func(resolve func(x AnyVal) AnyVal) AnyVal {\n\t\treturn resolve(NewPlainResult(http.StatusInternalServerError, body))\n\t})\n}"} {"input": "package api\n\nimport (\n\t\"github.com/lgtmco/lgtm/cache\"\n\t\"github.com/lgtmco/lgtm/model\"\n\t\"github.com/lgtmco/lgtm/router/middleware/session\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/gin-gonic/gin\"\n)\n\n\n\n\nfunc GetTeams(c *gin.Context) ", "output": "{\n\tuser := session.User(c)\n\tteams, err := cache.GetTeams(c, user)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Error getting teams for user %s. %s\", user.Login, err)\n\t\tc.String(500, \"Error getting team list\")\n\t\treturn\n\t}\n\tteams = append(teams, &model.Team{\n\t\tLogin: user.Login,\n\t\tAvatar: user.Avatar,\n\t})\n\tc.JSON(200, teams)\n}"} {"input": "package proj4go\n\nimport (\n\t\"fmt\"\n\n\tgeo \"github.com/terrascope/geometry\"\n)\n\n\ntype Projection interface {\n\tForward([]geo.Point) error\n\tInverse([]geo.Point) error\n}\n\n\n\nfunc Forwards(dst string, pts []geo.Point) error {\n\n\tproj, err := NewProjection(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = proj.Forward(pts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc Inverse(dst string, pts []geo.Point) error {\n\n\tproj, err := NewProjection(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = proj.Inverse(pts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc Transform(src, dst string, pts []geo.Point) error {\n\tif src == dst {\n\t\treturn nil\n\t}\n\n\tif err := Inverse(dst, pts); err != nil {\n\t\treturn err\n\t}\n\tif err := Forwards(src, pts); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc NewProjection(proj4Str string) (Projection, error) ", "output": "{\n\n\tproj4, err := ParseProj4String(proj4Str)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch proj4.Proj {\n\tcase \"aea\":\n\t\treturn NewAEA(proj4), nil\n\tcase \"merc\":\n\t\treturn NewMerc(proj4), nil\n\tcase \"equi\":\n\t\treturn NewEqui(proj4), nil\n\tcase \"mill\":\n\t\treturn NewMiller(proj4), nil\n\tcase \"sinu\":\n\t\treturn NewSinu(proj4), nil\n\tcase \"longlat\":\n\t\treturn NewLonLat(proj4), nil\n\t}\n\treturn nil, fmt.Errorf(\"could not find projection %s in list\", proj4.Proj)\n}"} {"input": "package utils\n\nimport (\n\t\"bufio\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\nfunc Atoi(s string) int {\n\ti, e := strconv.Atoi(s)\n\tif e != nil {\n\t\treturn 0\n\t}\n\treturn i\n}\n\n\nfunc Atoui(s string) uint32 {\n\ti, e := strconv.ParseUint(s, 10, 32)\n\tif e != nil {\n\t\treturn 0\n\t}\n\treturn uint32(i)\n}\n\n\nfunc ReadConfig(path string) map[string]string {\n\n\tconfigMap := make(map[string]string)\n\n\tf, err := os.Open(path)\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tscanner := bufio.NewScanner(f)\n\n\tfor scanner.Scan() {\n\n\t\tline := scanner.Text()\n\n\t\tif !strings.HasPrefix(line, \"//\") {\n\t\t\tfields := strings.SplitN(scanner.Text(), \"=\", 2)\n\n\t\t\tconfigMap[strings.TrimSpace(fields[0])] = strings.TrimSpace(fields[1])\n\t\t}\n\n\t}\n\n\treturn configMap\n}\n\n\n\n\nfunc GotError(err error) ", "output": "{\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"input": "package fakeclock\n\nimport (\n\t\"time\"\n\n\t\"github.com/pivotal-golang/clock\"\n)\n\ntype fakeTicker struct {\n\ttimer clock.Timer\n}\n\nfunc newFakeTicker(timer *fakeTimer) *fakeTicker {\n\treturn &fakeTicker{\n\t\ttimer: timer,\n\t}\n}\n\nfunc (ft *fakeTicker) C() <-chan time.Time {\n\treturn ft.timer.C()\n}\n\n\n\nfunc (ft *fakeTicker) Stop() ", "output": "{\n\tft.timer.Stop()\n}"} {"input": "package leet_20\n\ntype Stack []byte\n\n\n\nfunc (s *Stack) Empty() bool {\n\treturn nil == s || *s == nil || len(*s) == 0\n}\n\nfunc (s *Stack) Push(x byte) {\n\t*s = append(*s, x)\n}\n\nfunc (s *Stack) Top() byte {\n\tlength := len(*s)\n\tif 0 == length {\n\t\treturn 0\n\t}\n\treturn (*s)[length-1]\n}\n\nfunc (s *Stack) String() string {\n\treturn string(*s)\n}\n\nfunc match(a, b byte) bool {\n\tif a == '[' && b == ']' {\n\t\treturn true\n\t}\n\tif a == '(' && b == ')' {\n\t\treturn true\n\t}\n\tif a == '{' && b == '}' {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc isValid(s string) bool {\n\tarr := []byte(s)\n\tstack := new(Stack)\n\tfor _, c := range arr {\n\t\tswitch c {\n\t\tcase '[', '{', '(':\n\t\t\tstack.Push(c)\n\t\t\tcontinue\n\t\t}\n\t\ttop := stack.Top()\n\t\tif match(top, c) {\n\t\t\tstack.Pop()\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn stack.Empty()\n}\n\nfunc (s *Stack) Pop() byte ", "output": "{\n\tc := s.Top()\n\tlength := len(*s)\n\tif length <= 1 {\n\t\t*s = nil\n\t} else {\n\t\t*s = (*s)[:length-1]\n\t}\n\treturn c\n}"} {"input": "package example\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\n\n\nfunc bar() int {\n\treturn 4\n}\n\nfunc statementRemoveStructInitialization() (a http.Header, b error) {\n\tvar err error\n\n\ta, b = http.Header{}, err\n\n\treturn\n}\n\nfunc statementRemoveStringArrayMap() map[string][]string {\n\thash := \"ok\"\n\tvar hdr = make(map[string][]string)\n\n\thdr[\"Hash\"] = []string{hash}\n\n\treturn hdr\n}\n\nfunc foo() int ", "output": "{\n\tn := 1\n\n\tfor i := 0; i < 3; i++ {\n\t\tif i == 0 {\n\t\t\tn++\n\t\t} else if i == 1 {\n\t\t\tn += 2\n\t\t} else {\n\t\t\tn += 3\n\t\t}\n\n\t\tn++\n\t}\n\n\tif n < 0 {\n\t\tn = 0\n\t}\n\n\tn++\n\n\tn += bar()\n\n\tbar()\n\n\tswitch {\n\tcase n < 20:\n\t\tn++\n\tcase n > 20:\n\t\tn--\n\tdefault:\n\t\tn = 0\n\t\tfmt.Println(n)\n\t\tfunc() {}()\n\t}\n\n\tvar x = 0\n\tx++\n\n\treturn n\n}"} {"input": "package http\n\nimport (\n\t\"net/http\"\n\t\"reflect\"\n)\n\n\ntype JSONErrorBuilder interface {\n\tBuild() JSONError\n\n\tCustomError(code int, errorType, msg string) JSONErrorBuilder\n\n\tFromError(e error) JSONErrorBuilder\n\n\tMessage(string) JSONErrorBuilder\n\n\tStatus(int) JSONErrorBuilder\n\n\tURL(string) JSONErrorBuilder\n}\n\ntype jsonErrorBuilder struct {\n\tinstance JSONError\n}\n\n\n\nfunc NewJSONError() JSONErrorBuilder {\n\treturn &jsonErrorBuilder{JSONError{\n\t\tStatus: http.StatusInternalServerError,\n\t}}\n}\n\nfunc (b *jsonErrorBuilder) Build() JSONError {\n\treturn b.instance\n}\n\nfunc (b *jsonErrorBuilder) CustomError(\n\tcode int,\n\terrorType,\n\tmsg string,\n) JSONErrorBuilder {\n\tb.instance.Code = code\n\tb.instance.Type = errorType\n\tb.instance.Message = msg\n\n\treturn b\n}\n\n\n\nfunc (b *jsonErrorBuilder) Message(msg string) JSONErrorBuilder {\n\tb.instance.Message = msg\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) Status(status int) JSONErrorBuilder {\n\tb.instance.Status = status\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) URL(url string) JSONErrorBuilder {\n\tb.instance.MoreInfo = url\n\treturn b\n}\n\nvar _ JSONErrorBuilder = (*jsonErrorBuilder)(nil)\n\nfunc (b *jsonErrorBuilder) FromError(e error) JSONErrorBuilder ", "output": "{\n\terrType := reflect.TypeOf(e)\n\tvar typeName string\n\tif errType.Kind() == reflect.Ptr {\n\t\ttypeName = errType.Elem().Name()\n\t} else {\n\t\ttypeName = errType.Name()\n\t}\n\n\tb.instance.Type = typeName\n\tb.instance.Message = e.Error()\n\treturn b\n}"} {"input": "package service\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"github.com/oikomi/FishChatServer2/http_server/user-api/model\"\n\tauthRpc \"github.com/oikomi/FishChatServer2/http_server/user-api/rpc\"\n\t\"github.com/oikomi/FishChatServer2/protocol/rpc\"\n)\n\ntype Service struct {\n\trpcClient *authRpc.RPCClient\n}\n\n\n\nfunc (s *Service) Auth(uid int64, pw string) (loginModel *model.Login, err error) {\n\trgAuthReq := &rpc.RGAuthReq{\n\t\tUID: uid,\n\t}\n\tres, err := s.rpcClient.Register.Auth(rgAuthReq)\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn\n\t}\n\tloginModel = &model.Login{\n\t\tToken: res.Token,\n\t}\n\treturn\n}\n\nfunc (s *Service) Register(uid int64, userName, pw string) (err error) {\n\trgRegisterReq := &rpc.RGRegisterReq{\n\t\tUID: uid,\n\t\tName: userName,\n\t\tPassword: pw,\n\t}\n\t_, err = s.rpcClient.Register.Register(rgRegisterReq)\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn\n\t}\n\treturn\n}\n\nfunc New() (service *Service, err error) ", "output": "{\n\trpcClient, err := authRpc.NewRPCClient()\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn\n\t}\n\tservice = &Service{\n\t\trpcClient: rpcClient,\n\t}\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cloudfoundry/cli/plugin\"\n)\n\ntype TestWithPush struct {\n}\n\n\n\nfunc (c *TestWithPush) GetMetadata() plugin.PluginMetadata {\n\treturn plugin.PluginMetadata{\n\t\tName: \"TestWithPush\",\n\t\tCommands: []plugin.Command{\n\t\t\t{\n\t\t\t\tName: \"push\",\n\t\t\t\tHelpText: \"push text for test_with_push\",\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc thePushCmd() {\n\tfmt.Println(\"You called push in test_with_push\")\n}\n\nfunc main() {\n\tplugin.Start(new(TestWithPush))\n}\n\nfunc (c *TestWithPush) Run(cliConnection plugin.CliConnection, args []string) ", "output": "{\n\tif args[0] == \"push\" {\n\t\tthePushCmd()\n\t}\n}"} {"input": "package k8s\n\nimport (\n\t\"fmt\"\n\t\"github.com/ghodss/yaml\"\n\n\tapi_core_v1 \"k8s.io/api/core/v1\"\n\tapi_extn_v1beta1 \"k8s.io/api/extensions/v1beta1\"\n)\n\n\n\ntype Deployment struct {\n\tYmlInBytes []byte\n}\n\n\n\n\nfunc (m *Deployment) AsExtnV1B1Deployment() (*api_extn_v1beta1.Deployment, error) {\n\tif m.YmlInBytes == nil {\n\t\treturn nil, fmt.Errorf(\"Missing yaml\")\n\t}\n\n\tdeploy := &api_extn_v1beta1.Deployment{}\n\terr := yaml.Unmarshal(m.YmlInBytes, deploy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn deploy, nil\n}\n\n\ntype Service struct {\n\tYmlInBytes []byte\n}\n\nfunc NewService(b []byte) *Service {\n\treturn &Service{\n\t\tYmlInBytes: b,\n\t}\n}\n\n\nfunc (m *Service) AsCoreV1Service() (*api_core_v1.Service, error) {\n\tif m.YmlInBytes == nil {\n\t\treturn nil, fmt.Errorf(\"Missing yaml\")\n\t}\n\n\tsvc := &api_core_v1.Service{}\n\terr := yaml.Unmarshal(m.YmlInBytes, svc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn svc, nil\n}\n\nfunc NewDeployment(b []byte) *Deployment ", "output": "{\n\treturn &Deployment{\n\t\tYmlInBytes: b,\n\t}\n}"} {"input": "package term \n\nimport \"io\"\n\ntype Db []Term\n\nfunc NewDb(args []Term) Db {\n\treturn Db(args)\n}\n\nfunc (s Db) Format(w io.Writer, style Style) {\n\tisRoot := style.IsRoot\n\tstyle.IsRoot = false \n\n\tprevName := \"#\" \n\tfor _, t := range s {\n\t\tif isRoot {\n\t\t\tname := Name(t)\n\t\t\tif prevName != \"#\" && prevName != name {\n\t\t\t\tio.WriteString(w, \"\\n\")\n\t\t\t}\n\t\t\tprevName = name\n\t\t}\n\n\t\tstyle.WriteIndent(w)\n\t\tt.Format(w, style)\n\t}\n}\n\n\ntype Query struct {\n\tdb Db\n\tname string\n\tarity int\n}\n\n\n\n\nfunc (db Db) NewQuery(t Term) *Query {\n\treturn &Query{\n\t\tdb: db,\n\t\tname: Name(t),\n\t\tarity: Arity(t),\n\t}\n}\n\n\n\n\n\n\ntype Cursor struct {\n\tq *Query\n\ti int\n}\n\nfunc (c *Cursor) Next() (Term, bool) {\n\tfor ; c.i < len(c.q.db); c.i++ {\n\t\tcandidate := c.q.db[c.i]\n\t\tif Arity(candidate) == c.q.arity && Name(candidate) == c.q.name {\n\t\t\tc.i++\n\t\t\treturn candidate, c.i < len(c.q.db)\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc (q *Query) Run() *Cursor ", "output": "{\n\treturn &Cursor{\n\t\tq: q,\n\t\ti: 0,\n\t}\n}"} {"input": "package distribution\n\n\n\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\tgolangswaggerpaths \"path\"\n\t\"strings\"\n\n\t\"github.com/go-openapi/swag\"\n)\n\n\ntype FindDistributionsURL struct {\n\tFlagID int64\n\tSegmentID int64\n\n\t_basePath string\n\t_ struct{}\n}\n\n\n\n\nfunc (o *FindDistributionsURL) WithBasePath(bp string) *FindDistributionsURL {\n\to.SetBasePath(bp)\n\treturn o\n}\n\n\n\n\nfunc (o *FindDistributionsURL) SetBasePath(bp string) {\n\to._basePath = bp\n}\n\n\n\n\n\nfunc (o *FindDistributionsURL) Must(u *url.URL, err error) *url.URL {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif u == nil {\n\t\tpanic(\"url can't be nil\")\n\t}\n\treturn u\n}\n\n\nfunc (o *FindDistributionsURL) String() string {\n\treturn o.Must(o.Build()).String()\n}\n\n\nfunc (o *FindDistributionsURL) BuildFull(scheme, host string) (*url.URL, error) {\n\tif scheme == \"\" {\n\t\treturn nil, errors.New(\"scheme is required for a full url on FindDistributionsURL\")\n\t}\n\tif host == \"\" {\n\t\treturn nil, errors.New(\"host is required for a full url on FindDistributionsURL\")\n\t}\n\n\tbase, err := o.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbase.Scheme = scheme\n\tbase.Host = host\n\treturn base, nil\n}\n\n\nfunc (o *FindDistributionsURL) StringFull(scheme, host string) string {\n\treturn o.Must(o.BuildFull(scheme, host)).String()\n}\n\nfunc (o *FindDistributionsURL) Build() (*url.URL, error) ", "output": "{\n\tvar _result url.URL\n\n\tvar _path = \"/flags/{flagID}/segments/{segmentID}/distributions\"\n\n\tflagID := swag.FormatInt64(o.FlagID)\n\tif flagID != \"\" {\n\t\t_path = strings.Replace(_path, \"{flagID}\", flagID, -1)\n\t} else {\n\t\treturn nil, errors.New(\"flagId is required on FindDistributionsURL\")\n\t}\n\n\tsegmentID := swag.FormatInt64(o.SegmentID)\n\tif segmentID != \"\" {\n\t\t_path = strings.Replace(_path, \"{segmentID}\", segmentID, -1)\n\t} else {\n\t\treturn nil, errors.New(\"segmentId is required on FindDistributionsURL\")\n\t}\n\n\t_basePath := o._basePath\n\tif _basePath == \"\" {\n\t\t_basePath = \"/api/v1\"\n\t}\n\t_result.Path = golangswaggerpaths.Join(_basePath, _path)\n\n\treturn &_result, nil\n}"} {"input": "package nogo\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype mapBackedRoleRepository struct {\n\troleMap map[string]Role\n}\n\nfunc NewMapBackedRoleRepository() RoleRepository {\n\treturn &mapBackedRoleRepository{roleMap: make(map[string]Role)}\n}\n\nfunc (this *mapBackedRoleRepository) FindAll() ([]Role, error) {\n\tret := make([]Role, 0)\n\tfor _, role := range this.roleMap {\n\t\tret = append(ret, role)\n\t}\n\treturn ret, nil\n}\n\nfunc (this *mapBackedRoleRepository) FindRole(roleName string) (Role, error) {\n\tif role, ok := this.roleMap[roleName]; ok {\n\t\treturn role, nil\n\t}\n\treturn nil, errors.New(fmt.Sprintf(\"Could not find role %v\", roleName))\n}\n\n\n\nfunc (this *mapBackedRoleRepository) UpdateRole(role Role) error {\n\tif _, ok := this.roleMap[role.GetName()]; ok {\n\t\tthis.roleMap[role.GetName()] = role\n\t\treturn nil\n\t}\n\treturn errors.New(fmt.Sprintf(\"Error updating role. Role %v does not exist.\", role.GetName()))\n}\n\nfunc (this *mapBackedRoleRepository) DeleteRole(roleName string) error {\n\tif _, ok := this.roleMap[roleName]; ok {\n\t\tdelete(this.roleMap, roleName)\n\t}\n\treturn errors.New(fmt.Sprintf(\"Error deleting role. Role %v does not exist.\", roleName))\n}\n\nfunc (this *mapBackedRoleRepository) CreateRole(role Role) error ", "output": "{\n\tif _, ok := this.roleMap[role.GetName()]; ok {\n\t\treturn errors.New(fmt.Sprintf(\"Error creating role. Role %v already exists\", role.GetName()))\n\t}\n\tthis.roleMap[role.GetName()] = role\n\treturn nil\n}"} {"input": "package routetemplate\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\nvar routeTemplates []RouteTemplate\n\n\n\nfunc GetMatchedTemplateString(url string) (template string, err error) {\n\ttemplate = \"\"\n\n\tfor _, value := range routeTemplates {\n\n\t\twasMatched, _ := IsMatch(url, value)\n\t\tif wasMatched {\n\t\t\ttemplate = value.TemplatePath\n\t\t\tbreak\n\t\t}\n\t}\n\treturn template, nil\n}\n\nfunc GetMatchTemplate(url string) (routeTemplateMatch RouteTemplateMatch, err error) {\n\n\trouteTemplateMatch = RouteTemplateMatch{}\n\tfor _, value := range routeTemplates {\n\t\twasMatched, _ := IsMatch(url, value)\n\t\tif wasMatched {\n\n\t\t\trouteTemplateMatch, _ = BindVariables(url, value)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn routeTemplateMatch, nil\n}\n\nfunc GetMatchedTemplate(url string) (template string, err error) {\n\ttemplate = \"\"\n\n\tfor _, value := range routeTemplates {\n\n\t\twasMatched, _ := IsMatch(url, value)\n\t\tif wasMatched {\n\t\t\ttemplate = value.TemplatePath\n\t\t\tbreak\n\t\t}\n\t}\n\treturn template, nil\n}\n\nfunc AddRoute(name string, method string, urlTemplate string, handler interface{}) {\n\tfmt.Printf(\"%q\\n\", handler)\n\tvar x reflect.Value\n\tif fv, ok := handler.(reflect.Value); ok {\n\t\tx = fv\n\t} else {\n\t\tx = reflect.ValueOf(handler)\n\t}\n\n\targs := make([]reflect.Value, 0, 0)\n\tx.Call(args)\n\tfmt.Printf(\"%q\\n\", x)\n}\n\nfunc GetAllTemplates() (templates []RouteTemplate, err error) {\n\treturn routeTemplates, nil\n}\n\nfunc ClearAllTemplates() (err error) {\n\trouteTemplates = make([]RouteTemplate, 0)\n\treturn nil\n}\n\nfunc Add(template string) (err error) ", "output": "{\n\trouteTemplate, _ := Parse(template)\n\trouteTemplates = append(routeTemplates, routeTemplate)\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"regexp\"\n\t\"testing\"\n)\n\n\n\nfunc Test_GcSuiteReFail(t *testing.T) {\n\tfind_suite := regexp.MustCompile(gc_endRE).FindStringSubmatch\n\ttokens := find_suite(\"FAIL: mmath_test.go:35: MySuite.TestDiv\")\n\n\tfor i, expected := range []string{\"FAIL\", \"MySuite\", \"TestDiv\", \"\"} {\n\t\tcheckExpected(t, expected, tokens[i+1])\n\t}\n}\n\nfunc Test_GcSuiteReSkip(t *testing.T) {\n\tfind_suite := regexp.MustCompile(gc_endRE).FindStringSubmatch\n\ttokens := find_suite(\"SKIP: mmath_test.go:35: MySuite.TestMul (not implemented)\")\n\n\tfor i, expected := range []string{\"SKIP\", \"MySuite\", \"TestMul\", \"\"} {\n\t\tcheckExpected(t, expected, tokens[i+1])\n\t}\n}\n\nfunc checkExpected(t *testing.T, expected string, actual string) {\n\tif actual != expected {\n\t\tt.Fatalf(\"Expected %s but was %s\\n\", expected, actual)\n\t}\n}\n\nfunc Test_GcSuiteRePass(t *testing.T) ", "output": "{\n\tfind_suite := regexp.MustCompile(gc_endRE).FindStringSubmatch\n\ttokens := find_suite(\"PASS: mmath_test.go:16: MySuite.TestAdd\t0.000s\")\n\n\tfor i, expected := range []string{\"PASS\", \"MySuite\", \"TestAdd\", \"0.000\"} {\n\t\tcheckExpected(t, expected, tokens[i+1])\n\t}\n}"} {"input": "package block\n\nimport (\n\t\"github.com/juju/cmd\"\n\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/cmd/envcmd\"\n)\n\nvar (\n\tBlockClient = &getBlockClientAPI\n\tUnblockClient = &getUnblockClientAPI\n\tListClient = &getBlockListAPI\n\n\tNewDestroyCommand = newDestroyCommand\n\tNewRemoveCommand = newRemoveCommand\n\tNewChangeCommand = newChangeCommand\n\tNewListCommand = newListCommand\n)\n\ntype MockBlockClient struct {\n\tBlockType string\n\tMsg string\n}\n\n\n\nfunc (c *MockBlockClient) SwitchBlockOn(blockType, msg string) error {\n\tc.BlockType = blockType\n\tc.Msg = msg\n\treturn nil\n}\n\nfunc (c *MockBlockClient) SwitchBlockOff(blockType string) error {\n\tc.BlockType = blockType\n\tc.Msg = \"\"\n\treturn nil\n}\n\nfunc (c *MockBlockClient) List() ([]params.Block, error) {\n\tif c.BlockType == \"\" {\n\t\treturn []params.Block{}, nil\n\t}\n\n\treturn []params.Block{\n\t\tparams.Block{\n\t\t\tType: c.BlockType,\n\t\t\tMessage: c.Msg,\n\t\t},\n\t}, nil\n}\n\nfunc NewUnblockCommandWithClient(client UnblockClientAPI) cmd.Command {\n\treturn envcmd.Wrap(&unblockCommand{client: client})\n}\n\nfunc (c *MockBlockClient) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"sort\"\n)\n\n\ntype RankedCoordFinder struct {\n\tboard Board\n\tremaining []*Coord\n}\n\nfunc (f *RankedCoordFinder) NextOpenCoordinate(board Board, coord XY) (*Coord, bool) {\n\tf.board = board\n\tf.RefreshCoordinates()\n\n\tif len(f.remaining) == 0 {\n\t\treturn nil, false\n\t}\n\n\tc := f.remaining[0]\n\tf.remaining = f.remaining[0:]\n\n\treturn c, true\n}\n\nfunc (f *RankedCoordFinder) RefreshCoordinates() {\n\tf.remaining = []*Coord{}\n\tfor x := 0; x < len(f.board); x++ {\n\t\tfor y := 0; y < len(f.board); y++ {\n\t\t\tif f.board[x][y] == 0 {\n\t\t\t\tf.remaining = append(f.remaining, &Coord{x, y})\n\t\t\t}\n\t\t}\n\t}\n\tsort.Sort(f)\n}\n\nfunc (f *RankedCoordFinder) Len() int {\n\treturn len(f.remaining)\n}\n\nfunc (f *RankedCoordFinder) Swap(i, j int) {\n\tf.remaining[i], f.remaining[j] = f.remaining[j], f.remaining[i]\n}\n\nfunc (f *RankedCoordFinder) Less(i, j int) bool ", "output": "{\n\treturn len(f.board.AvailableValuesAtCoordinate(f.remaining[i])) <\n\t\tlen(f.board.AvailableValuesAtCoordinate(f.remaining[j]))\n}"} {"input": "package persistence\n\nimport (\n\t\"strings\"\n\n\t. \"github.com/Masterminds/squirrel\"\n\t\"github.com/navidrome/navidrome/conf\"\n\t\"github.com/navidrome/navidrome/utils\"\n)\n\n\n\nfunc (r sqlRepository) doSearch(q string, offset, size int, results interface{}, orderBys ...string) error {\n\tq = strings.TrimSpace(q)\n\tq = strings.TrimSuffix(q, \"*\")\n\tif len(q) < 2 {\n\t\treturn nil\n\t}\n\n\tsq := r.newSelectWithAnnotation(r.tableName + \".id\").Columns(\"*\")\n\tsq = sq.Limit(uint64(size)).Offset(uint64(offset))\n\tif len(orderBys) > 0 {\n\t\tsq = sq.OrderBy(orderBys...)\n\t}\n\tsq = sq.Where(fullTextExpr(q))\n\terr := r.queryAll(sq, results)\n\treturn err\n}\n\nfunc fullTextExpr(value string) Sqlizer {\n\tvar sep string\n\tif !conf.Server.SearchFullString {\n\t\tsep = \" \"\n\t}\n\tq := utils.SanitizeStrings(value)\n\tparts := strings.Split(q, \" \")\n\tfilters := And{}\n\tfor _, part := range parts {\n\t\tfilters = append(filters, Like{\"full_text\": \"%\" + sep + part + \"%\"})\n\t}\n\treturn filters\n}\n\nfunc getFullText(text ...string) string ", "output": "{\n\tfullText := utils.SanitizeStrings(text...)\n\treturn \" \" + fullText\n}"} {"input": "package transport\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"net/http\"\n)\n\n\ntype Config struct {\n\tUserAgent string\n\n\tTLS TLSConfig\n\n\tUsername string\n\tPassword string\n\n\tBearerToken string\n\n\tImpersonate ImpersonationConfig\n\n\tTransport http.RoundTripper\n\n\tWrapTransport func(rt http.RoundTripper) http.RoundTripper\n\n\tDial func(ctx context.Context, network, address string) (net.Conn, error)\n}\n\n\ntype ImpersonationConfig struct {\n\tUserName string\n\tGroups []string\n\tExtra map[string][]string\n}\n\n\nfunc (c *Config) HasCA() bool {\n\treturn len(c.TLS.CAData) > 0 || len(c.TLS.CAFile) > 0\n}\n\n\nfunc (c *Config) HasBasicAuth() bool {\n\treturn len(c.Username) != 0\n}\n\n\n\n\n\nfunc (c *Config) HasCertAuth() bool {\n\treturn len(c.TLS.CertData) != 0 || len(c.TLS.CertFile) != 0\n}\n\n\ntype TLSConfig struct {\n\tCAFile string \n\tCertFile string \n\tKeyFile string \n\n\tInsecure bool \n\tServerName string \n\n\tCAData []byte \n\tCertData []byte \n\tKeyData []byte \n}\n\nfunc (c *Config) HasTokenAuth() bool ", "output": "{\n\treturn len(c.BearerToken) != 0\n}"} {"input": "package version\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/coreos/go-semver/semver\"\n)\n\nvar (\n\tMinClusterVersion = \"3.0.0\"\n\tVersion = \"3.1.0-rc.0+git\"\n\tAPIVersion = \"unknown\"\n\n\tGitSHA = \"Not provided (use ./build instead of go build)\"\n)\n\nfunc init() {\n\tver, err := semver.NewVersion(Version)\n\tif err == nil {\n\t\tAPIVersion = fmt.Sprintf(\"%d.%d\", ver.Major, ver.Minor)\n\t}\n}\n\ntype Versions struct {\n\tServer string `json:\"etcdserver\"`\n\tCluster string `json:\"etcdcluster\"`\n}\n\n\n\n\nfunc Cluster(v string) string ", "output": "{\n\tvs := strings.Split(v, \".\")\n\tif len(vs) <= 2 {\n\t\treturn v\n\t}\n\treturn fmt.Sprintf(\"%s.%s\", vs[0], vs[1])\n}"} {"input": "package gobuddyfs\n\nimport (\n\t\"sync\"\n\n\t\"github.com/golang/glog\"\n)\n\ntype MemStore struct {\n\tlock *sync.RWMutex\n\tstore map[string][]byte\n\n\tKVStore\n}\n\nfunc NewMemStore() *MemStore {\n\treturn &MemStore{store: make(map[string][]byte), lock: &sync.RWMutex{}}\n}\n\nfunc (self *MemStore) Get(key string, retry bool) ([]byte, error) {\n\tif glog.V(2) {\n\t\tglog.Infof(\"Get(%s)\\n\", key)\n\t}\n\tself.lock.RLock()\n\tdefer self.lock.RUnlock()\n\tval, ok := self.store[key]\n\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\n\treturn val, nil\n}\n\n\n\nvar _ KVStore = new(MemStore)\n\nfunc (self *MemStore) Set(key string, value []byte) error ", "output": "{\n\tif glog.V(2) {\n\t\tglog.Infof(\"Set(%s)\\n\", key)\n\t}\n\tself.lock.Lock()\n\tdefer self.lock.Unlock()\n\n\tif value == nil {\n\t\tdelete(self.store, key)\n\t} else {\n\t\tself.store[key] = value\n\t}\n\n\treturn nil\n}"} {"input": "package gq\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nvar count int\n\ntype WorkerTest struct {\n\tDelay time.Duration\n}\n\nfunc (w WorkerTest) Work() {\n\tcount++\n}\n\nfunc (w WorkerTest) Data() string {\n\treturn \"\"\n}\n\nfunc (w WorkerTest) DelayTime() time.Duration {\n\treturn w.Delay\n}\n\nfunc (w WorkerTest) Preprocess() string {\n\treturn \"\"\n}\n\n\n\nfunc nullLogger(...interface{}) {}\n\nfunc init() {\n\tLogger(nullLogger)\n\tStartDispatcher(10)\n\tfor i := 0; i < 10; i++ {\n\t\twork := WorkerTest{Delay: 0 * time.Second}\n\t\tWorkQueue <- work\n\t}\n\ttime.Sleep(1 * time.Second)\n}\n\nfunc TestIncrement(t *testing.T) {\n\tif count != 10 {\n\t\tt.Errorf(\"expected count to be 10, got %d\\n\", count)\n\t}\n}\n\nfunc (w WorkerTest) Postprocess() string ", "output": "{\n\treturn \"\"\n}"} {"input": "package gen\n\nimport (\n\t\"math\"\n\t\"testing\"\n\n\t\"github.com/gonum/graph/simple\"\n)\n\nfunc TestTunableClusteringScaleFree(t *testing.T) {\n\tfor n := 2; n <= 20; n++ {\n\t\tfor m := 0; m < n; m++ {\n\t\t\tfor p := 0.; p <= 1; p += 0.1 {\n\t\t\t\tg := &gnUndirected{UndirectedBuilder: simple.NewUndirectedGraph(0, math.Inf(1))}\n\t\t\t\terr := TunableClusteringScaleFree(g, n, m, p, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatalf(\"unexpected error: n=%d, m=%d, p=%v: %v\", n, m, p, err)\n\t\t\t\t}\n\t\t\t\tif g.addBackwards {\n\t\t\t\t\tt.Errorf(\"edge added with From.ID > To.ID: n=%d, m=%d, p=%v\", n, m, p)\n\t\t\t\t}\n\t\t\t\tif g.addSelfLoop {\n\t\t\t\t\tt.Errorf(\"unexpected self edge: n=%d, m=%d, p=%v\", n, m, p)\n\t\t\t\t}\n\t\t\t\tif g.addMultipleEdge {\n\t\t\t\t\tt.Errorf(\"unexpected multiple edge: n=%d, m=%d, p=%v\", n, m, p)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\nfunc TestPreferentialAttachment(t *testing.T) ", "output": "{\n\tfor n := 2; n <= 20; n++ {\n\t\tfor m := 0; m < n; m++ {\n\t\t\tg := &gnUndirected{UndirectedBuilder: simple.NewUndirectedGraph(0, math.Inf(1))}\n\t\t\terr := PreferentialAttachment(g, n, m, nil)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"unexpected error: n=%d, m=%d: %v\", n, m, err)\n\t\t\t}\n\t\t\tif g.addBackwards {\n\t\t\t\tt.Errorf(\"edge added with From.ID > To.ID: n=%d, m=%d\", n, m)\n\t\t\t}\n\t\t\tif g.addSelfLoop {\n\t\t\t\tt.Errorf(\"unexpected self edge: n=%d, m=%d\", n, m)\n\t\t\t}\n\t\t\tif g.addMultipleEdge {\n\t\t\t\tt.Errorf(\"unexpected multiple edge: n=%d, m=%d\", n, m)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package get\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewGetPollersIdentifierDataParams() *GetPollersIdentifierDataParams {\n\tvar ()\n\treturn &GetPollersIdentifierDataParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\nfunc NewGetPollersIdentifierDataParamsWithTimeout(timeout time.Duration) *GetPollersIdentifierDataParams {\n\tvar ()\n\treturn &GetPollersIdentifierDataParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype GetPollersIdentifierDataParams struct {\n\n\tIdentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *GetPollersIdentifierDataParams) WithIdentifier(identifier string) *GetPollersIdentifierDataParams {\n\to.Identifier = identifier\n\treturn o\n}\n\n\n\n\nfunc (o *GetPollersIdentifierDataParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error ", "output": "{\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"identifier\", o.Identifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package jobs\n\nimport (\n\t\"github.com/simplemvc/gocorelib/cron\"\n\t\"github.com/simplemvc/gocorelib/revel\"\n\t\"strings\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype Func func()\n\nfunc (r Func) Run() { r() }\n\n\n\n\n\n\nfunc Every(duration time.Duration, job cron.Job) {\n\tMainCron.Schedule(cron.Every(duration), New(job))\n}\n\n\nfunc Now(job cron.Job) {\n\tgo New(job).Run()\n}\n\n\nfunc In(duration time.Duration, job cron.Job) {\n\tgo func() {\n\t\ttime.Sleep(duration)\n\t\tNew(job).Run()\n\t}()\n}\n\nfunc Schedule(spec string, job cron.Job) ", "output": "{\n\tif strings.HasPrefix(spec, \"cron.\") {\n\t\tconfSpec, found := revel.Config.String(spec)\n\t\tif !found {\n\t\t\tpanic(\"Cron spec not found: \" + spec)\n\t\t}\n\t\tspec = confSpec\n\t}\n\tMainCron.Schedule(cron.Parse(spec), New(job))\n}"} {"input": "package gossip_test\n\nimport (\n\t\"github.com/cockroachdb/cockroach/pkg/security\"\n\t\"github.com/cockroachdb/cockroach/pkg/security/securitytest\"\n)\n\n\n\nfunc init() ", "output": "{\n\tsecurity.SetReadFileFn(securitytest.Asset)\n}"} {"input": "package hilbert\n\nimport (\n\t\"runtime\"\n\t\"sync\"\n\n\th \"github.com/Workiva/go-datastructures/numerics/hilbert\"\n\t\"github.com/Workiva/go-datastructures/rtree\"\n)\n\nfunc getCenter(rect rtree.Rectangle) (int32, int32) {\n\txlow, ylow := rect.LowerLeft()\n\txhigh, yhigh := rect.UpperRight()\n\n\treturn (xhigh + xlow) / 2, (yhigh + ylow) / 2\n}\n\ntype hilbertBundle struct {\n\thilbert hilbert\n\trect rtree.Rectangle\n}\n\nfunc bundlesFromRects(rects ...rtree.Rectangle) []*hilbertBundle {\n\tchunks := chunkRectangles(rects, int64(runtime.NumCPU()))\n\tbundleChunks := make([][]*hilbertBundle, len(chunks))\n\tvar wg sync.WaitGroup\n\twg.Add(len(chunks))\n\n\tfor i := 0; i < runtime.NumCPU(); i++ {\n\t\tif len(chunks[i]) == 0 {\n\t\t\tbundleChunks[i] = []*hilbertBundle{}\n\t\t\twg.Done()\n\t\t\tcontinue\n\t\t}\n\t\tgo func(i int) {\n\t\t\tbundles := make([]*hilbertBundle, 0, len(chunks[i]))\n\t\t\tfor _, r := range chunks[i] {\n\t\t\t\th := h.Encode(getCenter(r))\n\t\t\t\tbundles = append(bundles, &hilbertBundle{hilbert(h), r})\n\t\t\t}\n\t\t\tbundleChunks[i] = bundles\n\t\t\twg.Done()\n\t\t}(i)\n\t}\n\n\twg.Wait()\n\n\tbundles := make([]*hilbertBundle, 0, len(rects))\n\tfor _, bc := range bundleChunks {\n\t\tbundles = append(bundles, bc...)\n\t}\n\n\treturn bundles\n}\n\n\n\n\nfunc chunkRectangles(slice rtree.Rectangles, numParts int64) []rtree.Rectangles ", "output": "{\n\tparts := make([]rtree.Rectangles, numParts)\n\tfor i := int64(0); i < numParts; i++ {\n\t\tparts[i] = slice[i*int64(len(slice))/numParts : (i+1)*int64(len(slice))/numParts]\n\t}\n\treturn parts\n}"} {"input": "package main\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"syscall\"\n\t\"unsafe\"\n)\n\n\n\nfunc unsafeErr(err error) uintptr {\n\tif err != nil {\n\t\tp1 := (uintptr)(unsafe.Pointer(&err))\n\t\tp2 := (*uintptr)(unsafe.Pointer(p1+8))\n\t\treturn *(*uintptr)(unsafe.Pointer(*p2))\n\t} else {\n\t\treturn 0\n\t}\n}\n\n\n\n\nfunc main() {\n\tnum := uintptr(16)\n\terrn := syscall.Errno(num)\n\terr := error(errn)\n\n\tfmt.Println(\"Num:\", num)\n\tfmt.Println(\"Errno:\", errn)\n\tfmt.Println(\"Error:\", err)\n\n\tfmt.Println(\"Unsafe way:\", unsafeErr(err))\n\tfmt.Println(\"Safe way:\", safeErr(err))\n}\n\nfunc safeErr(err error) uintptr ", "output": "{\n\treturn uintptr(err.(syscall.Errno))\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/TykTechnologies/tyk/apidef\"\n)\n\n\ntype TransformMethod struct {\n\t*BaseMiddleware\n}\n\nfunc (t *TransformMethod) Name() string {\n\treturn \"TransformMethod\"\n}\n\nfunc (t *TransformMethod) IsEnabledForSpec() bool {\n\tfor _, version := range t.Spec.VersionData.Versions {\n\t\tif len(version.ExtendedPaths.MethodTransforms) > 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\nfunc (t *TransformMethod) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) ", "output": "{\n\t_, versionPaths, _, _ := t.Spec.Version(r)\n\tfound, meta := t.Spec.CheckSpecMatchesStatus(r, versionPaths, MethodTransformed)\n\tif !found {\n\t\treturn nil, 200\n\t}\n\tmmeta := meta.(*apidef.MethodTransformMeta)\n\tswitch strings.ToUpper(mmeta.ToMethod) {\n\tcase \"GET\":\n\t\tr.Method = \"GET\"\n\tcase \"POST\":\n\t\tr.Method = \"POST\"\n\tcase \"PUT\":\n\t\tr.Method = \"PUT\"\n\tcase \"DELETE\":\n\t\tr.Method = \"DELETE\"\n\tcase \"OPTIONS\":\n\t\tr.Method = \"OPTIONS\"\n\tcase \"PATCH\":\n\t\tr.Method = \"PATCH\"\n\tdefault:\n\t\treturn errors.New(\"Method not allowed\"), 405\n\t}\n\treturn nil, 200\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\nfunc noKeyErr(key string) error {\n\treturn fmt.Errorf(\"no key %s found\", key)\n}\n\nfunc keyExistsIface(m *map[string]interface{}, key string) bool {\n\t_, ok := (*m)[key]\n\treturn ok\n}\nfunc keyExistsInt(m *map[string]int, key string) bool {\n\t_, ok := (*m)[key]\n\treturn ok\n}\n\n\n\n\n\n\n\nfunc setInMap(m interface{}, path []string, newVal interface{}) (interface{}, error) {\n\tif len(path) == 0 {\n\t\treturn newVal, nil\n\t}\n\n\tkey := path[0]\n\ttermErr := fmt.Errorf(\"path terminates early at %s\", key)\n\trem := path[1:]\n\n\tval := reflect.ValueOf(m)\n\tswitch val.Kind() {\n\tcase reflect.Map:\n\t\tkeys := val.MapKeys()\n\t\tfound := false\n\t\tfor _, k := range keys {\n\t\t\tif reflect.DeepEqual(k.Interface(), key) {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\treturn nil, termErr\n\t\t}\n\t\tsubMap := val.MapIndex(reflect.ValueOf(key))\n\t\tnewSubMap, err := setInMap(subMap.Interface(), rem, newVal)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tval.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(newSubMap))\n\t\treturn val.Interface(), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"value at path %s is unsupported type %T\", key, m)\n\t}\n}\n\nfunc keyExistsStr(m *map[string]string, key string) bool ", "output": "{\n\t_, ok := (*m)[key]\n\treturn ok\n}"} {"input": "package handler\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/dinever/golf\"\n\t\"github.com/dingoblog/dingo/app/model\"\n)\n\n\n\n\nfunc APIUserHandler(ctx *golf.Context) {\n\tid, err := strconv.Atoi(ctx.Param(\"user_id\"))\n\tif err != nil {\n\t\thandleErr(ctx, 500, err)\n\t\treturn\n\t}\n\tuser := &model.User{Id: int64(id)}\n\terr = user.GetUserById()\n\tif err != nil {\n\t\thandleErr(ctx, 404, err)\n\t\treturn\n\t}\n\tctx.JSONIndent(user, \"\", \" \")\n}\n\n\nfunc APIUserSlugHandler(ctx *golf.Context) {\n\tslug := ctx.Param(\"slug\")\n\tuser := &model.User{Slug: slug}\n\terr := user.GetUserBySlug()\n\tif err != nil {\n\t\thandleErr(ctx, 404, err)\n\t\treturn\n\t}\n\tctx.JSONIndent(user, \"\", \" \")\n}\n\n\nfunc APIUserEmailHandler(ctx *golf.Context) {\n\temail := ctx.Param(\"email\")\n\tuser := &model.User{Email: email}\n\terr := user.GetUserByEmail()\n\tif err != nil {\n\t\thandleErr(ctx, 404, err)\n\t\treturn\n\t}\n\tctx.JSONIndent(user, \"\", \" \")\n}\n\n\nfunc APIUsersHandler(ctx *golf.Context) {\n\tctx.JSONIndent(map[string]interface{}{\n\t\t\"message\": \"Not implemented\",\n\t}, \"\", \" \")\n}\n\nfunc registerUserHandlers(app *golf.Application, routes map[string]map[string]interface{}) ", "output": "{\n\tapp.Get(\"/api/users\", APIUsersHandler)\n\troutes[\"GET\"][\"users_url\"] = \"/api/users\"\n\n\tapp.Get(\"/api/users/:user_id\", APIUserHandler)\n\troutes[\"GET\"][\"user_url\"] = \"/api/users/:user_id\"\n\n\tapp.Get(\"/api/users/slug/:slug\", APIUserSlugHandler)\n\troutes[\"GET\"][\"user_slug_url\"] = \"/api/users/slug/:slug\"\n\n\tapp.Get(\"/api/users/email/:email\", APIUserEmailHandler)\n\troutes[\"GET\"][\"user_email_url\"] = \"/api/users/email/:email\"\n}"} {"input": "package schedulercache\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/labels\"\n\t\"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache\"\n)\n\n\ntype FakeCache struct {\n\tAssumeFunc func(*api.Pod)\n}\n\nfunc (f *FakeCache) AssumePod(pod *api.Pod) error {\n\tf.AssumeFunc(pod)\n\treturn nil\n}\n\nfunc (f *FakeCache) AddPod(pod *api.Pod) error { return nil }\n\n\n\nfunc (f *FakeCache) RemovePod(pod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) AddNode(node *api.Node) error { return nil }\n\nfunc (f *FakeCache) UpdateNode(oldNode, newNode *api.Node) error { return nil }\n\nfunc (f *FakeCache) RemoveNode(node *api.Node) error { return nil }\n\nfunc (f *FakeCache) UpdateNodeNameToInfoMap(infoMap map[string]*schedulercache.NodeInfo) error {\n\treturn nil\n}\n\nfunc (f *FakeCache) List(s labels.Selector) ([]*api.Pod, error) { return nil, nil }\n\nfunc (f *FakeCache) UpdatePod(oldPod, newPod *api.Pod) error ", "output": "{ return nil }"} {"input": "package controllers\n\nimport (\n\t\"github.com/VoidArtanis/wallpaper/models\"\n\t\"strings\"\n)\n\ntype WallpaperController struct {\n\tBaseController\n}\n\n\n\nfunc (c *WallpaperController) Get() ", "output": "{\n\tc.TplName = \"wallpaper.tpl\"\n\tq:=c.GetString(\"id\")\n\tobj, _ :=models.GetFromId(q)\n\tc.Data[\"post\"] =obj\n\tc.Data[\"tags\"] =strings.Join(obj.Tags, \", \")\n}"} {"input": "package mongo\n\nimport (\n\t\"context\"\n\n\t\"github.com/cuigh/swirl/dao\"\n\t\"go.mongodb.org/mongo-driver/bson\"\n)\n\nconst Setting = \"setting\"\n\nfunc (d *Dao) SettingGetAll(ctx context.Context) (settings []*dao.Setting, err error) {\n\tsettings = []*dao.Setting{}\n\terr = d.fetch(ctx, Setting, bson.M{}, &settings)\n\treturn\n}\n\n\n\nfunc (d *Dao) SettingUpdate(ctx context.Context, setting *dao.Setting) (err error) {\n\tupdate := bson.M{\n\t\t\"$set\": bson.M{\n\t\t\t\"options\": setting.Options,\n\t\t\t\"updated_at\": setting.UpdatedAt,\n\t\t\t\"updated_by\": setting.UpdatedBy,\n\t\t},\n\t}\n\treturn d.upsert(ctx, Setting, setting.ID, update)\n}\n\nfunc (d *Dao) SettingGet(ctx context.Context, id string) (setting *dao.Setting, err error) ", "output": "{\n\tsetting = &dao.Setting{}\n\tfound, err := d.find(ctx, Setting, id, setting)\n\tif !found {\n\t\treturn nil, err\n\t}\n\treturn\n}"} {"input": "package server\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/localhots/shezmu/stats\"\n)\n\ntype Server struct {\n\tport int\n\tss *stats.Server\n\tmux *http.ServeMux\n}\n\nfunc New(port int, ss *stats.Server) *Server {\n\treturn &Server{\n\t\tport: port,\n\t\tss: ss,\n\t\tmux: http.NewServeMux(),\n\t}\n}\n\n\n\nfunc (s *Server) Start() ", "output": "{\n\taddr := fmt.Sprintf(\":%d\", s.port)\n\ts.mux.HandleFunc(\"/stats.json\", s.ss.History)\n\tgo http.ListenAndServe(addr, s.mux)\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\ntype StorageState struct {\n\tHistoryState HistoryDB `json:\"history,omitempty\"`\n\tTrafficHistoryState map[int]*FlowSummary `json:\"traffichistory,omitempty\"`\n}\n\nfunc save(fp string) bool {\n\tHistory.RLock()\n\tTrafficHistory.RLock()\n\tdefer History.RUnlock()\n\tdefer TrafficHistory.RUnlock()\n\tss := StorageState{History.m, TrafficHistory.h}\n\treturn saveToFile(ss, fp)\n}\n\n\n\nfunc saveToFile(ss StorageState, fp string) bool {\n\tb, err := json.Marshal(ss)\n\tif err != nil {\n\t\tfmt.Println(\"Error on dumping state to json:\", err)\n\t\treturn false\n\t}\n\n\tf, err := os.Create(fp)\n\tif err != nil {\n\t\tfmt.Println(\"Error on opening file\", fp, \":\", err)\n\t\treturn false\n\t}\n\tdefer f.Close()\n\n\tw := bufio.NewWriter(f)\n\tn, err := w.Write(b)\n\tif err != nil {\n\t\tfmt.Println(\"Error on writing file\", fp, \":\", err)\n\t\treturn false\n\t}\n\n\tw.Flush()\n\tfmt.Println(\"Wrote history to file in\", n, \"bytes\")\n\treturn true\n}\n\nfunc load(fp string) (StorageState, error) ", "output": "{\n\tf, err := os.Open(fp)\n\tif err != nil {\n\t\treturn StorageState{}, err\n\t}\n\tdefer f.Close()\n\n\tbbuf, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn StorageState{}, errors.New(\"Error: cannot load from file, failed read\")\n\t}\n\n\tss := StorageState{}\n\terr = json.Unmarshal(bbuf, &ss)\n\tif err != nil {\n\t\treturn StorageState{}, errors.New(\"Error on loading state from json\")\n\t}\n\tfmt.Println(\"Loaded state from disk\", fp)\n\treturn ss, nil\n}"} {"input": "package garden_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestGarden(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Garden Suite\")\n}"} {"input": "package build\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/kubecfg\"\n\t\"github.com/openshift/origin/pkg/build/api\"\n)\n\nvar buildColumns = []string{\"Name\", \"Type\", \"Status\", \"Pod Name\"}\nvar buildConfigColumns = []string{\"Name\", \"Type\", \"SourceURI\"}\n\n\n\nfunc RegisterPrintHandlers(printer *kubecfg.HumanReadablePrinter) {\n\tprinter.Handler(buildColumns, printBuild)\n\tprinter.Handler(buildColumns, printBuildList)\n\tprinter.Handler(buildConfigColumns, printBuildConfig)\n\tprinter.Handler(buildConfigColumns, printBuildConfigList)\n}\n\nfunc printBuild(build *api.Build, w io.Writer) error {\n\t_, err := fmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\\n\", build.Name, build.Parameters.Strategy.Type, build.Status, build.PodName)\n\treturn err\n}\n\nfunc printBuildList(buildList *api.BuildList, w io.Writer) error {\n\tfor _, build := range buildList.Items {\n\t\tif err := printBuild(&build, w); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\nfunc printBuildConfigList(buildList *api.BuildConfigList, w io.Writer) error {\n\tfor _, buildConfig := range buildList.Items {\n\t\tif err := printBuildConfig(&buildConfig, w); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc printBuildConfig(bc *api.BuildConfig, w io.Writer) error ", "output": "{\n\t_, err := fmt.Fprintf(w, \"%s\\t%v\\t%s\\n\", bc.Name, bc.Parameters.Strategy.Type, bc.Parameters.Source.Git.URI)\n\treturn err\n}"} {"input": "package html\n\nimport (\n\t\"golang.org/x/net/html/atom\"\n)\n\n\nfunc (node *Node) FindByAtom(atoms ...atom.Atom) (nodes []*Node) {\n\tnodes = make([]*Node, 1)\n\tnodes[0] = node\n\tfor _, a := range atoms {\n\t\tchildren := make([]*Node, 0)\n\t\tfor _, n := range nodes {\n\t\t\tfor _, c := range n.ElementChildren() {\n\t\t\t\tif c.DataAtom == a {\n\t\t\t\t\tchildren = append(children, c)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tnodes = children\n\t}\n\treturn\n}\n\n\n\n\n\nfunc (node *Node) PrevByAtom(atom atom.Atom) *Node {\n\tfor node = node.PrevElement(); node != nil; node = node.PrevElement() {\n\t\tif node.DataAtom == atom {\n\t\t\treturn node\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (node *Node) NextByAtom(atom atom.Atom) *Node ", "output": "{\n\tfor node = node.NextElement(); node != nil; node = node.NextElement() {\n\t\tif node.DataAtom == atom {\n\t\t\treturn node\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package customresourcedefinition\n\nimport (\n\tcontext \"context\"\n\n\tv1 \"k8s.io/api/core/v1\"\n\tv1beta1 \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1\"\n\tcustomresourcedefinition \"knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition\"\n\treconciler \"knative.dev/pkg/reconciler\"\n)\n\n\n\n\n\nfunc newReconciledNormal(namespace, name string) reconciler.Event {\n\treturn reconciler.NewEvent(v1.EventTypeNormal, \"CustomResourceDefinitionReconciled\", \"CustomResourceDefinition reconciled: \\\"%s/%s\\\"\", namespace, name)\n}\n\n\ntype Reconciler struct {\n}\n\n\nvar _ customresourcedefinition.Interface = (*Reconciler)(nil)\n\n\n\n\n\n\n\nfunc (r *Reconciler) ReconcileKind(ctx context.Context, o *v1beta1.CustomResourceDefinition) reconciler.Event ", "output": "{\n\n\n\treturn newReconciledNormal(o.Namespace, o.Name)\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\n\n\nfunc main() {\n\tin, _ := os.Open(\"161.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"161.out\")\n\tdefer out.Close()\n\n\ts := bufio.NewScanner(in)\n\ts.Split(bufio.ScanLines)\n\n\tvar line string\n\tvar cycle int\n\tvar cycles []int\n\tfor s.Scan() {\n\t\tif line = s.Text(); line == \"0 0 0\" {\n\t\t\tbreak\n\t\t}\n\t\tfor r := strings.NewReader(line); ; {\n\t\t\tif _, err := fmt.Fscanf(r, \"%d\", &cycle); err != nil || cycle == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcycles = append(cycles, cycle)\n\t\t}\n\t\tif cycle == 0 {\n\t\t\tif seconds := solve(cycles); seconds == 0 {\n\t\t\t\tfmt.Fprintln(out, \"Signals fail to synchronise in 5 hours\")\n\t\t\t} else {\n\t\t\t\thours := seconds / 3600\n\t\t\t\tminutes := seconds % 3600 / 60\n\t\t\t\tseconds = seconds % 3600 % 60\n\t\t\t\tfmt.Fprintf(out, \"%02d:%02d:%02d\\n\", hours, minutes, seconds)\n\t\t\t}\n\t\t\tcycles = nil\n\t\t}\n\t}\n}\n\nfunc solve(cycles []int) int ", "output": "{\n\tfirst := true\nhere:\n\tfor i := 1; i <= 18000; i++ {\n\t\tfor _, cycle := range cycles {\n\t\t\tif i%(2*cycle) >= cycle-5 {\n\t\t\t\tif first {\n\t\t\t\t\tfirst = false\n\t\t\t\t}\n\t\t\t\tcontinue here\n\t\t\t}\n\t\t}\n\t\tif !first {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn 0\n}"} {"input": "package daemon\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/docker/docker/api/types/swarm\"\n\t\"gotest.tools/assert\"\n)\n\n\ntype ConfigConstructor func(*swarm.Config)\n\n\nfunc (d *Daemon) CreateConfig(t testing.TB, configSpec swarm.ConfigSpec) string {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tscr, err := cli.ConfigCreate(context.Background(), configSpec)\n\tassert.NilError(t, err)\n\treturn scr.ID\n}\n\n\nfunc (d *Daemon) ListConfigs(t testing.TB) []swarm.Config {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tconfigs, err := cli.ConfigList(context.Background(), types.ConfigListOptions{})\n\tassert.NilError(t, err)\n\treturn configs\n}\n\n\nfunc (d *Daemon) GetConfig(t testing.TB, id string) *swarm.Config {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tconfig, _, err := cli.ConfigInspectWithRaw(context.Background(), id)\n\tassert.NilError(t, err)\n\treturn &config\n}\n\n\nfunc (d *Daemon) DeleteConfig(t testing.TB, id string) {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\terr := cli.ConfigRemove(context.Background(), id)\n\tassert.NilError(t, err)\n}\n\n\n\n\n\nfunc (d *Daemon) UpdateConfig(t testing.TB, id string, f ...ConfigConstructor) ", "output": "{\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tconfig := d.GetConfig(t, id)\n\tfor _, fn := range f {\n\t\tfn(config)\n\t}\n\n\terr := cli.ConfigUpdate(context.Background(), config.ID, config.Version, config.Spec)\n\tassert.NilError(t, err)\n}"} {"input": "package closer\n\nimport (\n\t\"sync\"\n)\n\ntype Closer struct {\n\tIsClosedChan chan struct{}\n\n\tf func()\n\tmutex sync.Mutex\n}\n\n\n\n\n\n\nfunc (c *Closer) Close() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tif c.IsClosed() {\n\t\treturn\n\t}\n\n\tclose(c.IsClosedChan)\n\n\tc.f()\n}\n\n\nfunc (c *Closer) IsClosed() bool {\n\tselect {\n\tcase <-c.IsClosedChan:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc New(f func()) *Closer ", "output": "{\n\treturn &Closer{\n\t\tIsClosedChan: make(chan struct{}),\n\t\tf: f,\n\t}\n}"} {"input": "package layer\n\nimport \"io\"\n\ntype mountedLayer struct {\n\tname string\n\tmountID string\n\tinitID string\n\tparent *roLayer\n\tpath string\n\tlayerStore *layerStore\n\tactivityCount int\n}\n\nfunc (ml *mountedLayer) cacheParent() string {\n\tif ml.initID != \"\" {\n\t\treturn ml.initID\n\t}\n\tif ml.parent != nil {\n\t\treturn ml.parent.cacheID\n\t}\n\treturn \"\"\n}\n\nfunc (ml *mountedLayer) TarStream() (io.ReadCloser, error) {\n\tarchiver, err := ml.layerStore.driver.Diff(ml.mountID, ml.cacheParent())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn archiver, nil\n}\n\nfunc (ml *mountedLayer) Path() (string, error) {\n\tif ml.path == \"\" {\n\t\treturn \"\", ErrNotMounted\n\t}\n\treturn ml.path, nil\n}\n\n\n\nfunc (ml *mountedLayer) Size() (int64, error) {\n\treturn ml.layerStore.driver.DiffSize(ml.mountID, ml.cacheParent())\n}\n\nfunc (ml *mountedLayer) Parent() Layer ", "output": "{\n\tif ml.parent != nil {\n\t\treturn ml.parent\n\t}\n\n\treturn nil\n}"} {"input": "package builtin\n\nimport (\n\t\"testing\"\n\n\t\"time\"\n\n\t\"github.com/fission/fission-workflows/pkg/types\"\n\t\"github.com/fission/fission-workflows/pkg/types/typedvalues\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestSleepFunctionInt(t *testing.T) {\n\tstart := time.Now()\n\tinternalFunctionTest(t,\n\t\t&FunctionSleep{},\n\t\t&types.TaskInvocationSpec{\n\t\t\tInputs: map[string]*typedvalues.TypedValue{\n\t\t\t\tSleepInput: typedvalues.MustWrap(1000),\n\t\t\t},\n\t\t},\n\t\tnil)\n\tend := time.Now()\n\tassert.True(t, (end.UnixNano()-start.UnixNano()) > (time.Duration(900)*time.Millisecond).Nanoseconds())\n}\n\nfunc TestSleepFunctionString(t *testing.T) ", "output": "{\n\tstart := time.Now()\n\tinternalFunctionTest(t,\n\t\t&FunctionSleep{},\n\t\t&types.TaskInvocationSpec{\n\t\t\tInputs: map[string]*typedvalues.TypedValue{\n\t\t\t\tSleepInput: typedvalues.MustWrap(\"1000ms\"),\n\t\t\t},\n\t\t},\n\t\tnil)\n\tend := time.Now()\n\tassert.True(t, (end.UnixNano()-start.UnixNano()) > (time.Duration(900)*time.Millisecond).Nanoseconds())\n}"} {"input": "package provision\n\nimport (\n\t\"github.com/tsuru/tsuru/db\"\n)\n\ntype poolWithTeams struct {\n\tName string `bson:\"_id\"`\n\tTeams []string\n\tPublic bool\n}\n\n\n\nfunc MigratePoolTeamsToPoolConstraints() error ", "output": "{\n\tconn, err := db.Conn()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\tvar pools []poolWithTeams\n\terr = conn.Pools().Find(nil).All(&pools)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, p := range pools {\n\t\tvalues := []string{\"*\"}\n\t\tif !p.Public {\n\t\t\tvalues = p.Teams\n\t\t}\n\t\terr := SetPoolConstraint(&PoolConstraint{PoolExpr: p.Name, Field: \"team\", Values: values})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package etchosts\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestBuildHostnameDomainname(t *testing.T) {\n\tfile, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.Remove(file.Name())\n\n\terr = Build(file.Name(), \"10.11.12.13\", \"testhostname\", \"testdomainname\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcontent, err := ioutil.ReadFile(file.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif expected := \"10.11.12.13\\ttesthostname.testdomainname testhostname\\n\"; !bytes.Contains(content, []byte(expected)) {\n\t\tt.Fatalf(\"Expected to find '%s' got '%s'\", expected, content)\n\t}\n}\n\n\n\nfunc TestBuildNoIP(t *testing.T) {\n\tfile, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.Remove(file.Name())\n\n\terr = Build(file.Name(), \"\", \"testhostname\", \"\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcontent, err := ioutil.ReadFile(file.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif expected := \"\"; !bytes.Contains(content, []byte(expected)) {\n\t\tt.Fatalf(\"Expected to find '%s' got '%s'\", expected, content)\n\t}\n}\n\nfunc TestBuildHostname(t *testing.T) ", "output": "{\n\tfile, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.Remove(file.Name())\n\n\terr = Build(file.Name(), \"10.11.12.13\", \"testhostname\", \"\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcontent, err := ioutil.ReadFile(file.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif expected := \"10.11.12.13\\ttesthostname\\n\"; !bytes.Contains(content, []byte(expected)) {\n\t\tt.Fatalf(\"Expected to find '%s' got '%s'\", expected, content)\n\t}\n}"} {"input": "package stack\n\nconst (\n\tstackPoolSize = 64\n)\n\nvar (\n\tpcStackPool = make(chan []uintptr, stackPoolSize)\n)\n\n\n\nfunc putPoolBuf(p []uintptr) {\n\tselect {\n\tcase pcStackPool <- p:\n\tdefault:\n\t}\n}\n\nfunc poolBuf() []uintptr ", "output": "{\n\tselect {\n\tcase p := <-pcStackPool:\n\t\treturn p\n\tdefault:\n\t\treturn make([]uintptr, 1000)\n\t}\n}"} {"input": "package mutex\n\nimport \"sync\"\n\nfunc Read(x *int, mutex *sync.RWMutex) int {\n\tmutex.RLock()\n\tdefer mutex.RUnlock()\n\n\treturn *x\n}\n\n\n\nfunc Write(x *int, mutex *sync.RWMutex, y int) ", "output": "{\n\tmutex.Lock()\n\tdefer mutex.Unlock()\n\n\t*x = y\n}"} {"input": "package gq\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nvar count int\n\ntype WorkerTest struct {\n\tDelay time.Duration\n}\n\nfunc (w WorkerTest) Work() {\n\tcount++\n}\n\nfunc (w WorkerTest) Data() string {\n\treturn \"\"\n}\n\nfunc (w WorkerTest) DelayTime() time.Duration {\n\treturn w.Delay\n}\n\n\n\nfunc (w WorkerTest) Postprocess() string {\n\treturn \"\"\n}\n\nfunc nullLogger(...interface{}) {}\n\nfunc init() {\n\tLogger(nullLogger)\n\tStartDispatcher(10)\n\tfor i := 0; i < 10; i++ {\n\t\twork := WorkerTest{Delay: 0 * time.Second}\n\t\tWorkQueue <- work\n\t}\n\ttime.Sleep(1 * time.Second)\n}\n\nfunc TestIncrement(t *testing.T) {\n\tif count != 10 {\n\t\tt.Errorf(\"expected count to be 10, got %d\\n\", count)\n\t}\n}\n\nfunc (w WorkerTest) Preprocess() string ", "output": "{\n\treturn \"\"\n}"} {"input": "package main\n\nimport \"strings\"\n\nvar x = make([]byte, 10)\n\nfunc main() {\n\ttest1()\n\ttest2()\n\ttest3()\n\ttest4()\n\ttest5()\n\ttest6()\n\ttest7()\n}\n\nfunc mustRecover(s string) {\n\tv := recover()\n\tif v == nil {\n\t\tpanic(\"expected panic\")\n\t}\n\tif e := v.(error).Error(); strings.Index(e, s) < 0 {\n\t\tpanic(\"want: \" + s + \"; have: \" + e)\n\t}\n}\n\nfunc test1() {\n\tdefer mustRecover(\"index\")\n\tprintln(x[123])\n}\n\nfunc test2() {\n\tdefer mustRecover(\"slice\")\n\tprintln(x[5:15])\n}\n\nfunc test3() {\n\tdefer mustRecover(\"slice\")\n\tvar lo = 11\n\tvar hi = 9\n\tprintln(x[lo:hi])\n}\n\n\n\ntype T struct {\n\ta, b int\n\tc []int\n}\n\nfunc test5() {\n\tdefer mustRecover(\"uncomparable\")\n\tvar x T\n\tvar z interface{} = x\n\tprintln(z != z)\n}\n\nfunc test6() {\n\tdefer mustRecover(\"unhashable\")\n\tvar x T\n\tvar z interface{} = x\n\tm := make(map[interface{}]int)\n\tm[z] = 1\n}\n\nfunc test7() {\n\tdefer mustRecover(\"divide by zero\")\n\tvar x, y int\n\tprintln(x / y)\n}\n\nfunc test4() ", "output": "{\n\tdefer mustRecover(\"interface\")\n\tvar x interface{} = 1\n\tprintln(x.(float32))\n}"} {"input": "package discovery\n\nimport (\n\t\"fmt\"\n\t\"github.com/spencergibb/go-nuvem/util\"\n\t\"github.com/spf13/viper\"\n\t\"net\"\n\t\"strconv\"\n)\n\ntype StaticDiscovery struct {\n\tNamespace string\n\tInstances []string\n}\n\n\n\nfunc (s *StaticDiscovery) GetIntances() []util.Instance {\n\tinstances := make([]util.Instance, len(s.Instances))\n\n\tfor i, config := range s.Instances {\n\t\thost, portStr, err := net.SplitHostPort(config)\n\n\t\tport, err := strconv.Atoi(portStr)\n\n\t\tprint(err) \n\n\t\tinstances[i] = util.Instance{Host: host, Port: port}\n\t}\n\n\treturn instances\n}\n\nfunc (s *StaticDiscovery) GetNamespace() string {\n\treturn s.Namespace\n}\n\nfunc NewStaticDiscovery() Discovery {\n\treturn &StaticDiscovery{}\n}\n\nvar StaticFactoryKey = \"StaticDiscovery\"\n\nfunc init() {\n\tprintln(\"registering static discovery\")\n\tRegister(StaticFactoryKey, NewStaticDiscovery)\n}\n\nfunc (s *StaticDiscovery) Configure(namespace string) ", "output": "{\n\tif s.Namespace != \"\" {\n\t\tfmt.Errorf(\"%s already inited: %s\", StaticFactoryKey, s.Namespace)\n\t\treturn\n\t}\n\ts.Namespace = namespace\n\tinstances := viper.GetStringSlice(util.GetStaticRegistryKey(s))\n\tfmt.Printf(\"instances %+v\\n\", instances)\n\ts.Instances = instances\n}"} {"input": "package tokenauth\n\nimport (\n\t\"time\"\n)\n\n\n\ntype Audience struct {\n\tName string\n\tID string \n\tSecret string \n\tTokenPeriod uint64 \n}\n\n\ntype Token struct {\n\tClientID string \n\tSingleID string \n\tValue string \n\tDeadLine int64 \n}\n\n\n\n\n\n\nfunc (t *Token) IsSingle() bool {\n\treturn len(t.ClientID) == 0 && len(t.SingleID) > 0\n}\n\nfunc (t *Token) Expired() bool ", "output": "{\n\tif t.DeadLine == 0 {\n\t\treturn false\n\t}\n\treturn time.Now().Unix() >= t.DeadLine\n}"} {"input": "package data\n\nimport (\n \"github.com/twitchyliquid64/CNC/registry/syscomponents\"\n)\n\nvar trackerObj DatabaseComponent\n\ntype DatabaseComponent struct{\n err error\n}\n\nfunc (d *DatabaseComponent)Name() string{\n return \"Database\"\n}\nfunc (d *DatabaseComponent)IconStr() string{\n return \"list\"\n}\nfunc (d *DatabaseComponent)IsNominal()bool{\n return d.err == nil\n}\nfunc (d *DatabaseComponent)IsDisabled()bool{\n return false\n}\n\nfunc (d *DatabaseComponent)Error()string{\n if d.err == nil{\n return \"\"\n }\n return d.err.Error()\n}\nfunc (d *DatabaseComponent)SetError(e error){\n d.err = e\n}\n\nfunc trackingSetup(){\n trackerObj = DatabaseComponent{}\n syscomponents.Register(&trackerObj)\n}\n\nfunc tracking_notifyFault(err error){\n syscomponents.SetError(trackerObj.Name(), err)\n}\n\nfunc (d *DatabaseComponent)IsFault()bool", "output": "{\n return d.err != nil\n}"} {"input": "package rest\n\nimport (\n\tnetworkingapiv1 \"k8s.io/api/networking/v1\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\t\"k8s.io/apiserver/pkg/registry/rest\"\n\tgenericapiserver \"k8s.io/apiserver/pkg/server\"\n\tserverstorage \"k8s.io/apiserver/pkg/server/storage\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\t\"k8s.io/kubernetes/pkg/apis/networking\"\n\tnetworkpolicystore \"k8s.io/kubernetes/pkg/registry/networking/networkpolicy/storage\"\n)\n\ntype RESTStorageProvider struct{}\n\n\n\nfunc (p RESTStorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage {\n\tstorage := map[string]rest.Storage{}\n\tnetworkPolicyStorage := networkpolicystore.NewREST(restOptionsGetter)\n\tstorage[\"networkpolicies\"] = networkPolicyStorage\n\n\treturn storage\n}\n\nfunc (p RESTStorageProvider) GroupName() string {\n\treturn networking.GroupName\n}\n\nfunc (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) ", "output": "{\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(networking.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\n\tif apiResourceConfigSource.VersionEnabled(networkingapiv1.SchemeGroupVersion) {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[networkingapiv1.SchemeGroupVersion.Version] = p.v1alpha1Storage(apiResourceConfigSource, restOptionsGetter)\n\t}\n\n\treturn apiGroupInfo, true\n}"} {"input": "package utils\n\nimport \"time\"\n\n\n\n\n\n\nfunc GetUnixEpoch() int64 {\n\treturn GetUnixEpochFrom(time.Now())\n}\n\nfunc GetUnixEpochFrom(now time.Time) int64 ", "output": "{\n\treturn now.UnixNano()\n}"} {"input": "package types\n\nimport \"fmt\"\n\ntype KeywordValue struct {\n\tValue string\n}\n\nfunc (v *KeywordValue) ToString() string {\n\treturn fmt.Sprint(v.Value)\n}\n\nfunc (v *KeywordValue) GetType() string {\n\treturn \"keyword\"\n}\n\n\n\nfunc (v *KeywordValue) ConvertTo(t string) (ValueType, error) {\n\treturn nil, fmt.Errorf(\"cannot convert keyword to %s: does not implement yet\", t)\n}\n\nfunc (v *KeywordValue) EqualTo(t ValueType) bool {\n\tif v2, ok := t.(*KeywordValue); ok {\n\t\tif v2.Value == v.Value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc NewKeywordValue(v string) *KeywordValue {\n\treturn &KeywordValue{Value: v}\n}\n\nfunc (v *KeywordValue) IsValue() bool ", "output": "{\n\treturn false\n}"} {"input": "package db\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/boltdb/bolt\"\n\t\"hawx.me/code/phemera/models\"\n)\n\ntype Db interface {\n\tGet() models.Entries\n\tSave(time.Time, string)\n\tClose()\n}\n\ntype BoltDb struct {\n\tme *bolt.DB\n\thorizon time.Duration\n}\n\nconst bucketName = \"phemera\"\n\nfunc Open(path, horizon string) Db {\n\tdb, err := bolt.Open(path, 0600, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdb.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucket([]byte(bucketName))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"create bucket: %s\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\tho, _ := time.ParseDuration(horizon)\n\n\treturn BoltDb{db, ho}\n}\n\n\n\nfunc (db BoltDb) Save(key time.Time, value string) {\n\tdb.me.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(bucketName))\n\t\terr := b.Put([]byte(timestamp(key)), []byte(value))\n\t\treturn err\n\t})\n}\n\nfunc (db BoltDb) Close() {\n\tdb.me.Close()\n}\n\nfunc timestamp(t time.Time) []byte {\n\treturn []byte(strconv.FormatInt(t.Unix(), 10))\n}\n\nfunc (db BoltDb) Get() models.Entries ", "output": "{\n\tlist := models.Entries{}\n\n\tdb.me.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(bucketName))\n\t\tc := b.Cursor()\n\n\t\tbound := timestamp(time.Now().Add(db.horizon))\n\t\tfor k, v := c.Last(); k != nil && bytes.Compare(k, bound) >= 0; k, v = c.Prev() {\n\t\t\tlist = append(list, models.Entry{string(k), string(v)})\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn list\n}"} {"input": "package expect\n\nimport (\n\t\"testing\"\n)\n\ntype EachTests struct {\n\tcalled bool\n}\n\nfunc Test_Each(t *testing.T) {\n\tExpectify(new(EachTests), t)\n}\n\nfunc (e *EachTests) RunsEach() {\n\tExpect(e.called).To.Equal(true)\n}\n\n\n\nfunc (e *EachTests) Each(f func()) ", "output": "{\n\te.called = true\n\tf()\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/hyperledger/fabric/common/channelconfig\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n)\n\n\ntype Orderer struct {\n\tConsensusTypeVal string\n\tBatchSizeVal *ab.BatchSize\n\tBatchTimeoutVal time.Duration\n\tKafkaBrokersVal []string\n\tMaxChannelsCountVal uint64\n\tOrganizationsVal map[string]channelconfig.Org\n\tCapabilitiesVal channelconfig.OrdererCapabilities\n}\n\n\nfunc (scm *Orderer) ConsensusType() string {\n\treturn scm.ConsensusTypeVal\n}\n\n\nfunc (scm *Orderer) BatchSize() *ab.BatchSize {\n\treturn scm.BatchSizeVal\n}\n\n\nfunc (scm *Orderer) BatchTimeout() time.Duration {\n\treturn scm.BatchTimeoutVal\n}\n\n\nfunc (scm *Orderer) KafkaBrokers() []string {\n\treturn scm.KafkaBrokersVal\n}\n\n\nfunc (scm *Orderer) MaxChannelsCount() uint64 {\n\treturn scm.MaxChannelsCountVal\n}\n\n\nfunc (scm *Orderer) Organizations() map[string]channelconfig.Org {\n\treturn scm.OrganizationsVal\n}\n\n\nfunc (scm *Orderer) Capabilities() channelconfig.OrdererCapabilities {\n\treturn scm.CapabilitiesVal\n}\n\n\ntype OrdererCapabilities struct {\n\tSupportedErr error\n\n\tSetChannelModPolicyDuringCreateVal bool\n\n\tResubmissionVal bool\n}\n\n\nfunc (oc *OrdererCapabilities) Supported() error {\n\treturn oc.SupportedErr\n}\n\n\n\n\n\nfunc (oc *OrdererCapabilities) Resubmission() bool {\n\treturn oc.ResubmissionVal\n}\n\nfunc (oc *OrdererCapabilities) SetChannelModPolicyDuringCreate() bool ", "output": "{\n\treturn oc.SetChannelModPolicyDuringCreateVal\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n)\n\ntype config struct {\n\tPort string\n\tAddr string\n\tDataDir string\n\tContentType string\n}\n\nfunc (c *config) Grok(defaultPort, defaultDatadir string) {\n\tflag.StringVar(&c.DataDir, \"d\", defaultDatadir, \"root directory for files\")\n\tflag.StringVar(&c.Port, \"p\", defaultPort, \"port number on which to listen\")\n\n\tflag.Parse()\n\n\tc.setAddr(defaultPort)\n\tc.setDataDir(defaultDatadir)\n\tc.setContentType()\n}\n\nfunc (c *config) setAddr(defaultPort string) {\n\tif c.Port != \"\" {\n\t\tc.Addr = \":\" + c.Port\n\t}\n\n\tif c.Addr == \"\" {\n\t\tc.Addr = \":\" + os.Getenv(\"PORT\")\n\t}\n\n\tif c.Addr == \":\" {\n\t\tc.Addr = \":\" + defaultPort\n\t}\n}\n\nfunc (c *config) setDataDir(defaultDatadir string) {\n\tvar err error\n\n\tif c.DataDir == \"\" {\n\t\tc.DataDir = os.Getenv(\"DATADIR\")\n\t}\n\n\tif c.DataDir == \"\" {\n\t\tc.DataDir, err = os.Getwd()\n\t\tif err != nil {\n\t\t\tc.DataDir = defaultDatadir\n\t\t}\n\t}\n}\n\n\n\nfunc (c *config) setContentType() ", "output": "{\n\tc.ContentType = os.Getenv(\"CONTENT_TYPE\")\n\tif c.ContentType == \"\" {\n\t\tc.ContentType = \"application/json\"\n\t}\n}"} {"input": "package openpgp\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\ntype recordingHash struct {\n\tbuf *bytes.Buffer\n}\n\nfunc (r recordingHash) Write(b []byte) (n int, err error) {\n\treturn r.buf.Write(b)\n}\n\nfunc (r recordingHash) Sum(in []byte) []byte {\n\treturn append(in, r.buf.Bytes()...)\n}\n\nfunc (r recordingHash) Reset() {\n\tpanic(\"shouldn't be called\")\n}\n\n\n\nfunc (r recordingHash) BlockSize() int {\n\tpanic(\"shouldn't be called\")\n}\n\nfunc testCanonicalText(t *testing.T, input, expected string) {\n\tr := recordingHash{bytes.NewBuffer(nil)}\n\tc := NewCanonicalTextHash(r)\n\tc.Write([]byte(input))\n\tresult := c.Sum(nil)\n\tif expected != string(result) {\n\t\tt.Errorf(\"input: %x got: %x want: %x\", input, result, expected)\n\t}\n}\n\nfunc TestCanonicalText(t *testing.T) {\n\ttestCanonicalText(t, \"foo\\n\", \"foo\\r\\n\")\n\ttestCanonicalText(t, \"foo\", \"foo\")\n\ttestCanonicalText(t, \"foo\\r\\n\", \"foo\\r\\n\")\n\ttestCanonicalText(t, \"foo\\r\\nbar\", \"foo\\r\\nbar\")\n\ttestCanonicalText(t, \"foo\\r\\nbar\\n\\n\", \"foo\\r\\nbar\\r\\n\\r\\n\")\n}\n\nfunc (r recordingHash) Size() int ", "output": "{\n\tpanic(\"shouldn't be called\")\n}"} {"input": "package news\n\nimport (\n\t\"context\"\n\n\t\"github.com/bwmarrin/discordgo\"\n\t\"github.com/fsufitch/tagioalisi-bot/azure\"\n\t\"github.com/fsufitch/tagioalisi-bot/bot/util\"\n\t\"github.com/fsufitch/tagioalisi-bot/log\"\n)\n\n\ntype Module struct {\n\tLog *log.Logger\n\tNews azure.NewsSearch\n\n\tsession *discordgo.Session\n}\n\n\nfunc (m Module) Name() string { return \"news\" }\n\n\nfunc (m *Module) Register(ctx context.Context, session *discordgo.Session) error {\n\tm.session = session\n\n\tcancel := m.session.AddHandler(m.handleCommand)\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tm.Log.Infof(\"news module context done\")\n\t\tcancel()\n\t}()\n\n\treturn nil\n}\n\n\n\n\nfunc (m *Module) DoSearch(\n\tctx context.Context,\n\tsession *discordgo.Session,\n\tchannelID string,\n\tquery string,\n\tcount int,\n\tverbose bool,\n) error ", "output": "{\n\tm.Log.Debugf(\"news: searching for `%s`\", query)\n\n\tif !m.News.Ready() {\n\t\treturn util.DiscordMessageSendRawBlock(session, channelID, \"News API not properly instantiated. Sorry! :(\")\n\t}\n\tm.Log.Debugf(\"news: api ready\")\n\n\tresults, err := m.News.Search(ctx, query, int32(count))\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Log.Debugf(\"news: got %d results for %s\", results.Len(), query)\n\n\tvar f formatter\n\tif verbose {\n\t\tf = verboseFormatter\n\t} else {\n\t\tf = compactFormatter\n\t}\n\n\treturn f(session, channelID, results)\n}"} {"input": "package utils\n\nimport (\n\t\"bufio\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\nfunc Atoi(s string) int {\n\ti, e := strconv.Atoi(s)\n\tif e != nil {\n\t\treturn 0\n\t}\n\treturn i\n}\n\n\n\n\n\nfunc ReadConfig(path string) map[string]string {\n\n\tconfigMap := make(map[string]string)\n\n\tf, err := os.Open(path)\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tscanner := bufio.NewScanner(f)\n\n\tfor scanner.Scan() {\n\n\t\tline := scanner.Text()\n\n\t\tif !strings.HasPrefix(line, \"//\") {\n\t\t\tfields := strings.SplitN(scanner.Text(), \"=\", 2)\n\n\t\t\tconfigMap[strings.TrimSpace(fields[0])] = strings.TrimSpace(fields[1])\n\t\t}\n\n\t}\n\n\treturn configMap\n}\n\n\nfunc GotError(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc Atoui(s string) uint32 ", "output": "{\n\ti, e := strconv.ParseUint(s, 10, 32)\n\tif e != nil {\n\t\treturn 0\n\t}\n\treturn uint32(i)\n}"} {"input": "package leveldb\n\nimport (\n\t\"github.com/pingcap/goleveldb/leveldb/comparer\"\n)\n\ntype iComparer struct {\n\tucmp comparer.Comparer\n}\n\nfunc (icmp *iComparer) uName() string {\n\treturn icmp.ucmp.Name()\n}\n\nfunc (icmp *iComparer) uCompare(a, b []byte) int {\n\treturn icmp.ucmp.Compare(a, b)\n}\n\nfunc (icmp *iComparer) uSeparator(dst, a, b []byte) []byte {\n\treturn icmp.ucmp.Separator(dst, a, b)\n}\n\nfunc (icmp *iComparer) uSuccessor(dst, b []byte) []byte {\n\treturn icmp.ucmp.Successor(dst, b)\n}\n\nfunc (icmp *iComparer) Name() string {\n\treturn icmp.uName()\n}\n\nfunc (icmp *iComparer) Compare(a, b []byte) int {\n\tx := icmp.uCompare(internalKey(a).ukey(), internalKey(b).ukey())\n\tif x == 0 {\n\t\tif m, n := internalKey(a).num(), internalKey(b).num(); m > n {\n\t\t\treturn -1\n\t\t} else if m < n {\n\t\t\treturn 1\n\t\t}\n\t}\n\treturn x\n}\n\nfunc (icmp *iComparer) Separator(dst, a, b []byte) []byte {\n\tua, ub := internalKey(a).ukey(), internalKey(b).ukey()\n\tdst = icmp.uSeparator(dst, ua, ub)\n\tif dst != nil && len(dst) < len(ua) && icmp.uCompare(ua, dst) < 0 {\n\t\treturn append(dst, keyMaxNumBytes...)\n\t}\n\treturn nil\n}\n\n\n\nfunc (icmp *iComparer) Successor(dst, b []byte) []byte ", "output": "{\n\tub := internalKey(b).ukey()\n\tdst = icmp.uSuccessor(dst, ub)\n\tif dst != nil && len(dst) < len(ub) && icmp.uCompare(ub, dst) < 0 {\n\t\treturn append(dst, keyMaxNumBytes...)\n\t}\n\treturn nil\n}"} {"input": "package namespace\n\nimport (\n\t\"github.com/astaxie/beego\"\n\t\"github.com/cloudawan/cloudone_gui/controllers/identity\"\n\t\"github.com/cloudawan/cloudone_gui/controllers/utility/guimessagedisplay\"\n\t\"github.com/cloudawan/cloudone_utility/restclient\"\n)\n\ntype EditController struct {\n\tbeego.Controller\n}\n\n\n\nfunc (c *EditController) Post() {\n\tguimessage := guimessagedisplay.GetGUIMessage(c)\n\n\tcloudoneProtocol := beego.AppConfig.String(\"cloudoneProtocol\")\n\tcloudoneHost := beego.AppConfig.String(\"cloudoneHost\")\n\tcloudonePort := beego.AppConfig.String(\"cloudonePort\")\n\n\tname := c.GetString(\"name\")\n\n\tnamespace := Namespace{name, false, false, \"\", \"\", \"\", \"\"}\n\n\turl := cloudoneProtocol + \":\" + cloudoneHost + \":\" + cloudonePort + \"/api/v1/namespaces\"\n\n\ttokenHeaderMap, _ := c.GetSession(\"tokenHeaderMap\").(map[string]string)\n\n\t_, err := restclient.RequestPostWithStructure(url, namespace, nil, tokenHeaderMap)\n\n\tif identity.IsTokenInvalidAndRedirect(c, c.Ctx, err) {\n\t\treturn\n\t}\n\n\tif err != nil {\n\t\tguimessage.AddDanger(guimessagedisplay.GetErrorMessage(err))\n\t} else {\n\t\tguimessage.AddSuccess(\"Namespace \" + name + \" is edited\")\n\t}\n\n\tc.Ctx.Redirect(302, \"/gui/system/namespace/list\")\n\n\tguimessage.RedirectMessage(c)\n}\n\nfunc (c *EditController) Get() ", "output": "{\n\tc.TplName = \"system/namespace/edit.html\"\n\tguimessage := guimessagedisplay.GetGUIMessage(c)\n\n\tc.Data[\"layoutMenu\"] = c.GetSession(\"layoutMenu\")\n\n\tnamespace := c.GetString(\"namespace\")\n\tif namespace == \"\" {\n\t\tc.Data[\"actionButtonValue\"] = \"Create\"\n\t\tc.Data[\"pageHeader\"] = \"Create Namespace\"\n\t\tc.Data[\"namespace\"] = \"\"\n\t} else {\n\t\tc.Data[\"actionButtonValue\"] = \"Update\"\n\t\tc.Data[\"pageHeader\"] = \"Update Namespace\"\n\t\tc.Data[\"namespace\"] = namespace\n\t}\n\n\tguimessage.OutputMessage(c.Data)\n}"} {"input": "package algorith\n\nimport (\n\t\"bytes\"\n\t\"math/rand\"\n\t\"time\"\n)\n\n\nfunc RandomString(num int) string {\n\tvar result bytes.Buffer\n\tvar temp string\n\tfor i := 0; i < num; {\n\t\tif string(RandomInt64(65, 90)) != temp {\n\t\t\ttemp = string(RandomInt64(65, 90))\n\t\t\tresult.WriteString(temp)\n\t\t\ti++\n\t\t}\n\t}\n\treturn result.String()\n}\n\n\n\n\nfunc RandomInt64(min, max int64) int64 ", "output": "{\n\trand.Seed(time.Now().UTC().UnixNano())\n\treturn min + rand.Int63n(max-min)\n}"} {"input": "package garchive\n\nimport (\n\t\"archive/zip\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestExtractZipFile(t *testing.T) {\n\ttempFile, err := ioutil.TempFile(\"\", \"archive\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tdefer tempFile.Close()\n\tdefer os.Remove(tempFile.Name())\n\twriteArchive(t, tempFile)\n\ttempFile.Close()\n\n\terr = ExtractZipFile(tempFile.Name(), \"\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\n\tstat, err := os.Stat(\"temporary_file.txt\")\n\tassert.False(t, os.IsNotExist(err), \"Expected temporary_file.txt to exist\")\n\tif !os.IsNotExist(err) {\n\t\tassert.NoError(t, err)\n\t}\n\n\tif stat != nil {\n\t\tdefer os.Remove(\"temporary_file.txt\")\n\t\tassert.Equal(t, int64(9), stat.Size())\n\t}\n}\n\nfunc TestExtractZipFileNotFound(t *testing.T) {\n\terr := ExtractZipFile(\"non_existing_zip_file.zip\", \"\")\n\tassert.Error(t, err)\n}\n\nfunc writeArchive(t *testing.T, w io.Writer) ", "output": "{\n\tarchive := zip.NewWriter(w)\n\tdefer archive.Close()\n\n\ttestFile, err := archive.Create(\"temporary_file.txt\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tio.WriteString(testFile, \"test file\")\n}"} {"input": "package auth\n\nimport (\n\t\"encoding/base64\"\n\t\"github.com/outbrain/orchestrator/Godeps/_workspace/src/github.com/go-martini/martini\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n\ntype User string\n\n\nvar BasicRealm = \"Authorization Required\"\n\n\n\nfunc Basic(username string, password string) martini.Handler {\n\tvar siteAuth = base64.StdEncoding.EncodeToString([]byte(username + \":\" + password))\n\treturn func(res http.ResponseWriter, req *http.Request, c martini.Context) {\n\t\tauth := req.Header.Get(\"Authorization\")\n\t\tif !SecureCompare(auth, \"Basic \"+siteAuth) {\n\t\t\tunauthorized(res)\n\t\t\treturn\n\t\t}\n\t\tc.Map(User(username))\n\t}\n}\n\n\n\n\n\nfunc unauthorized(res http.ResponseWriter) {\n\tres.Header().Set(\"WWW-Authenticate\", \"Basic realm=\\\"\"+BasicRealm+\"\\\"\")\n\thttp.Error(res, \"Not Authorized\", http.StatusUnauthorized)\n}\n\nfunc BasicFunc(authfn func(string, string) bool) martini.Handler ", "output": "{\n\treturn func(res http.ResponseWriter, req *http.Request, c martini.Context) {\n\t\tauth := req.Header.Get(\"Authorization\")\n\t\tif len(auth) < 6 || auth[:6] != \"Basic \" {\n\t\t\tunauthorized(res)\n\t\t\treturn\n\t\t}\n\t\tb, err := base64.StdEncoding.DecodeString(auth[6:])\n\t\tif err != nil {\n\t\t\tunauthorized(res)\n\t\t\treturn\n\t\t}\n\t\ttokens := strings.SplitN(string(b), \":\", 2)\n\t\tif len(tokens) != 2 || !authfn(tokens[0], tokens[1]) {\n\t\t\tunauthorized(res)\n\t\t\treturn\n\t\t}\n\t\tc.Map(User(tokens[0]))\n\t}\n}"} {"input": "package broker\n\nimport (\n\troa \"github.com/apache/servicecomb-service-center/pkg/rest\"\n)\n\n\n\nfunc registerREST() {\n\troa.RegisterServant(&Controller{})\n}\n\nfunc init() ", "output": "{\n\tregisterREST()\n}"} {"input": "package telnetmgr\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"sync/atomic\"\n\n\t\"github.com/uol/logh\"\n\t\"github.com/uol/mycenae/lib/constants\"\n\n\t\"github.com/julienschmidt/httprouter\"\n)\n\n\n\n\n\n\n\nconst CountConnsURI string = \"node/connections\"\n\n\nconst HaltConnsURI string = \"node/halt/balancing\"\n\n\nconst HTTPHeaderTotalConnections string = \"X-Total-Connections\"\n\n\n\n\nconst (\n\tcFuncHaltTelnetBalancingProcess string = \"HaltTelnetBalancingProcess\"\n)\n\n\nfunc (manager *Manager) HaltTelnetBalancingProcess(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n\tif atomic.CompareAndSwapUint32(&manager.haltBalancingProcess, 0, 1) {\n\n\t\tif logh.InfoEnabled {\n\t\t\tmanager.logger.Info().Str(constants.StringsFunc, cFuncHaltTelnetBalancingProcess).Msg(\"halting the telnet connections balancing process\")\n\t\t}\n\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn\n\t}\n\n\tif logh.InfoEnabled {\n\t\tmanager.logger.Info().Str(constants.StringsFunc, cFuncHaltTelnetBalancingProcess).Msg(\"telnet connections balancing process is already halted\")\n\t}\n\n\tw.WriteHeader(http.StatusProcessing)\n\n\treturn\n}\n\nfunc (manager *Manager) CountConnections(w http.ResponseWriter, r *http.Request, ps httprouter.Params) ", "output": "{\n\n\tw.Header().Add(HTTPHeaderTotalConnections, fmt.Sprintf(\"%d\", atomic.LoadUint32(&manager.sharedConnectionCounter)))\n\tw.WriteHeader(http.StatusOK)\n\n\treturn\n}"} {"input": "package filter\n\nimport (\n\t\"context\"\n\n\t\"github.com/hyperledger/fabric-protos-go/peer\"\n\t\"github.com/hyperledger/fabric/core/handlers/auth\"\n)\n\n\nfunc NewFilter() auth.Filter {\n\treturn &filter{}\n}\n\ntype filter struct {\n\tnext peer.EndorserServer\n}\n\n\n\n\n\nfunc (f *filter) ProcessProposal(ctx context.Context, signedProp *peer.SignedProposal) (*peer.ProposalResponse, error) {\n\treturn f.next.ProcessProposal(ctx, signedProp)\n}\n\nfunc (f *filter) Init(next peer.EndorserServer) ", "output": "{\n\tf.next = next\n}"} {"input": "package databasemanagement\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ResetDatabaseParametersRequest struct {\n\n\tManagedDatabaseId *string `mandatory:\"true\" contributesTo:\"path\" name:\"managedDatabaseId\"`\n\n\tResetDatabaseParametersDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ResetDatabaseParametersRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ResetDatabaseParametersRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ResetDatabaseParametersRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype ResetDatabaseParametersResponse struct {\n\n\tRawResponse *http.Response\n\n\tUpdateDatabaseParametersResult `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ResetDatabaseParametersResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ResetDatabaseParametersResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ResetDatabaseParametersRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package util\n\ntype Bool struct {\n\tb bool\n}\n\nfunc (b *Bool) Value() bool {\n\treturn b.b\n}\n\nvar True = &Bool{true}\nvar False = &Bool{false}\n\n\n\nfunc BoolFor(val bool) *Bool ", "output": "{\n\tif val {\n\t\treturn True\n\t}\n\treturn False\n}"} {"input": "package cover\n\nimport (\n\t\"flag\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc ParseAndStripTestFlags() {\n\tflag.Parse()\n\n\tvar runtimeArgs []string\n\tfor _, arg := range os.Args {\n\t\tif strings.HasPrefix(arg, \"-test.\") ||\n\t\t\tstrings.HasPrefix(arg, \"-httptest.\") {\n\t\t\tcontinue\n\t\t}\n\t\truntimeArgs = append(runtimeArgs, arg)\n\t}\n\tos.Args = runtimeArgs\n}\n\ntype dummyTestDeps func(pat, str string) (bool, error)\n\nfunc (d dummyTestDeps) MatchString(pat, str string) (bool, error) { return false, nil }\nfunc (d dummyTestDeps) StartCPUProfile(io.Writer) error { return nil }\nfunc (d dummyTestDeps) StopCPUProfile() {}\nfunc (f dummyTestDeps) StartTestLog(w io.Writer) {}\nfunc (f dummyTestDeps) StopTestLog() error { return nil }\nfunc (d dummyTestDeps) WriteHeapProfile(io.Writer) error { return nil }\nfunc (d dummyTestDeps) WriteProfileTo(string, io.Writer, int) error { return nil }\nfunc (f dummyTestDeps) ImportPath() string { return \"\" }\n\n\n\n\n\n\n\nfunc FlushProfiles() ", "output": "{\n\toldstdout := os.Stdout\n\toldstderr := os.Stderr\n\tos.Stdout, _ = os.Open(os.DevNull)\n\tos.Stderr, _ = os.Open(os.DevNull)\n\n\ttests := []testing.InternalTest{}\n\tbenchmarks := []testing.InternalBenchmark{}\n\texamples := []testing.InternalExample{}\n\tvar f dummyTestDeps\n\tdummyM := testing.MainStart(f, tests, benchmarks, examples)\n\tdummyM.Run()\n\n\tos.Stdout = oldstdout\n\tos.Stderr = oldstderr\n}"} {"input": "package main\n\nimport (\n\t\"time\"\n)\n\n\ntype ChessDataBase struct {\n\tDisplayname string `json:\"displayname\"`\n\tFullpath string `json:\"fullpath\"`\n\tKey string `json:\"key\"`\n\tBasename string `json:\"basename\"`\n\tFilemod time.Time `json:\"filemod\"`\n\tFilesize int64 `json:\"filesize\"`\n\tCount int `json:\"count\"`\n\tGameoffsets []int64 `json:\"gameoffsets\"`\n\tGamelengths []int `json:\"gamelengths\"`\n\tNotes string `json:\"notes\"`\n\tInitIndex bool `json:\"initindex\"`\n\tCheckIndex bool `json:\"checkindex\"`\n\tKind string `json:\"kind\"`\n}\n\n\n\n\nfunc NewCDB() *ChessDataBase ", "output": "{\n\treturn &ChessDataBase{}\n}"} {"input": "package workers\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"time\"\n)\n\ntype MiddlewareLogging struct{}\n\n\n\nfunc (l *MiddlewareLogging) Call(queue string, message *Msg, next func() bool) (acknowledge bool) ", "output": "{\n\tprefix := fmt.Sprint(queue, \" JID-\", message.Jid())\n\n\tstart := time.Now()\n\tLogger.Println(prefix, \"start\")\n\tLogger.Println(prefix, \"payload:\", message.ToJson())\n\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tLogger.Println(prefix, \"fail:\", time.Since(start))\n\n\t\t\tbuf := make([]byte, 4096)\n\t\t\tbuf = buf[:runtime.Stack(buf, false)]\n\t\t\tLogger.Printf(\"%s error: %v\\n%s\", prefix, e, buf)\n\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\n\tacknowledge = next()\n\n\tLogger.Println(prefix, \"done:\", time.Since(start))\n\n\treturn\n}"} {"input": "package vm\n\ntype Networks map[string]Network\n\ntype Network struct {\n\tType string `json:\"type\"`\n\n\tIP string `json:\"ip,omitempty\"`\n\tNetmask string `json:\"netmask,omitempty\"`\n\tGateway string `json:\"gateway,omitempty\"`\n\n\tDNS []string `json:\"dns,omitempty\"`\n\tDefault []string `json:\"default,omitempty\"`\n\n\tPreconfigured bool `json:\"preconfigured,omitempty\"`\n\n\tMAC string `json:\"mac,omitempty\"`\n\n\tCloudProperties map[string]interface{} `json:\"cloud_properties,omitempty\"`\n}\n\n\n\nfunc (n Network) IsDynamic() bool { return n.Type == \"dynamic\" }\n\nfunc (n Network) AppendDNS(dns string) Network {\n\tif len(dns) > 0 {\n\t\tn.DNS = append(n.DNS, dns)\n\t\treturn n\n\t}\n\treturn n\n}\n\nfunc (ns Networks) First() Network ", "output": "{\n\tfor _, net := range ns {\n\t\treturn net\n\t}\n\n\treturn Network{}\n}"} {"input": "package storage\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\n\t\"gopkg.in/mgo.v2\"\n)\n\nvar pointerMap = map[string][2048]byte{}\n\n\n\nfunc sessionFinalizer(session *mgo.Session) {\n\tptr := fmt.Sprintf(\"%p\", session)\n\tdefer func() {\n\t\trecover()\n\t\tdelete(pointerMap, ptr)\n\t}()\n\tsession.DB(\"tsuru\").C(\"mycoll\").Find(nil).Count()\n\tbuf := pointerMap[ptr]\n\tfmt.Printf(\"\\n********** LEAK **********\\n%s\\n********** ENDLEAK **********\\n\", string(buf[:]))\n\tsession.Close()\n}\n\nfunc Open(addr, dbname string) (storage *Storage, err error) ", "output": "{\n\tsessionLock.RLock()\n\tif sessions[addr] == nil {\n\t\tsessionLock.RUnlock()\n\t\tsessionLock.Lock()\n\t\tif sessions[addr] == nil {\n\t\t\tsessions[addr], err = open(addr)\n\t\t}\n\t\tsessionLock.Unlock()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tsessionLock.RUnlock()\n\t}\n\tcloned := sessions[addr].Clone()\n\tpointerAddr := fmt.Sprintf(\"%p\", cloned)\n\tbuf := pointerMap[pointerAddr]\n\truntime.Stack(buf[:], false)\n\tpointerMap[pointerAddr] = buf\n\truntime.SetFinalizer(cloned, sessionFinalizer)\n\tstorage = &Storage{\n\t\tsession: cloned,\n\t\tdbname: dbname,\n\t}\n\treturn\n}"} {"input": "package iso20022\n\n\n\ntype RejectionReason26 struct {\n\n\tCode *RejectionReason24Choice `xml:\"Cd\"`\n\n\tAdditionalReasonInformation *Max210Text `xml:\"AddtlRsnInf,omitempty\"`\n}\n\n\n\nfunc (r *RejectionReason26) SetAdditionalReasonInformation(value string) {\n\tr.AdditionalReasonInformation = (*Max210Text)(&value)\n}\n\nfunc (r *RejectionReason26) AddCode() *RejectionReason24Choice ", "output": "{\n\tr.Code = new(RejectionReason24Choice)\n\treturn r.Code\n}"} {"input": "package tcplisten\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nconst (\n\tsoReusePort = 0x0F\n\ttcpFastOpen = 0x17\n)\n\nfunc enableDeferAccept(fd int) error {\n\tif err := syscall.SetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_DEFER_ACCEPT, 1); err != nil {\n\t\treturn fmt.Errorf(\"cannot enable TCP_DEFER_ACCEPT: %s\", err)\n\t}\n\treturn nil\n}\n\nfunc enableFastOpen(fd int) error {\n\tif err := syscall.SetsockoptInt(fd, syscall.SOL_TCP, tcpFastOpen, fastOpenQlen); err != nil {\n\t\treturn fmt.Errorf(\"cannot enable TCP_FASTOPEN(qlen=%d): %s\", fastOpenQlen, err)\n\t}\n\treturn nil\n}\n\nconst fastOpenQlen = 16 * 1024\n\n\n\nconst soMaxConnFilePath = \"/proc/sys/net/core/somaxconn\"\n\nfunc soMaxConn() (int, error) ", "output": "{\n\tdata, err := ioutil.ReadFile(soMaxConnFilePath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn syscall.SOMAXCONN, nil\n\t\t}\n\t\treturn -1, err\n\t}\n\ts := strings.TrimSpace(string(data))\n\tn, err := strconv.Atoi(s)\n\tif err != nil || n <= 0 {\n\t\treturn -1, fmt.Errorf(\"cannot parse somaxconn %q read from %s: %s\", s, soMaxConnFilePath, err)\n\t}\n\n\tif n > 1<<16-1 {\n\t\tn = 1<<16 - 1\n\t}\n\treturn n, nil\n}"} {"input": "package gapbuf\n\nimport \"github.com/millere/jk/line\"\n\ntype GapBuf struct {\n\tbuffer []*line.Line \n\tgapStart int \n\tgapEnd int \n\treadPoint int\n}\n\nfunc New(size int) *GapBuf {\n\ta := GapBuf{\n\t\tbuffer: make([]*line.Line, size),\n\t\tgapStart: 0,\n\t\tgapEnd: size,\n\t}\n\treturn &a\n}\n\n\n\n\n\nfunc (a *GapBuf) At(i int) *line.Line {\n\tif i >= a.gapStart {\n\t\treturn a.buffer[i+a.gapEnd-a.gapStart]\n\t} else {\n\t\treturn a.buffer[i]\n\t}\n}\n\n\nfunc (a *GapBuf) Insert(r rune, i int) {\n}\n\nfunc (a *GapBuf) moveGap(to int) {\n}\n\nfunc (a *GapBuf) Len() int ", "output": "{\n\treturn len(a.buffer) + a.gapStart - a.gapEnd\n}"} {"input": "package example\n\nimport (\n\t\"testing\"\n\t\"github.com/remogatto/prettytest\"\n\t\"launchpad.net/gocheck\"\n)\n\n\n\ntype testSuite struct {\n\tprettytest.Suite\n}\n\nfunc TestRunner(t *testing.T) {\n\tprettytest.Run(\n\t\tt,\n\t\tnew(testSuite),\n\t)\n}\n\n\n\n\n\n\nfunc (t *testSuite) TestTrueIsTrue() {\n\tt.True(true)\n}\n\nfunc (t *testSuite) TestEquality() {\n\tt.Equal(\"awesome\", \"awesome\")\n}\n\nfunc (t *testSuite) TestNot() {\n\tt.Not(t.Path(\"foo\"))\n}\n\nfunc (t *testSuite) TestGoCheck() {\n\tt.Check(\"foo\", gocheck.Equals, \"foo\")\n}\n\n\n\nfunc (t *testSuite) TestMustFail() {\n\tt.Error(\"This test must fail.\")\n\tt.MustFail()\n}\n\n\n\nfunc (t *testSuite) TestInequality() ", "output": "{\n\tt.Equal(\"awesome\", \"ugly\")\n\tt.MustFail()\n}"} {"input": "package bot\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"log\"\n)\n\n\ntype Config struct {\n\tAdmin string `json:\"admin\"`\n\tNotifiers map[string][]string `json:\"notifiers\"`\n\tDebug bool `json:\"debug\"`\n}\n\n\nfunc NewConfig() *Config {\n\tcfg := &Config{\n\t\tNotifiers: make(map[string][]string),\n\t}\n\treturn cfg\n}\n\nfunc (cfg *Config) fromJSON(filename string) error {\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = json.Unmarshal(file, &cfg); err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Loaded config.\")\n\treturn nil\n}\n\n\n\nfunc (cfg *Config) toJSON(filename string) error ", "output": "{\n\tjsonBytes, err := json.MarshalIndent(cfg, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = ioutil.WriteFile(filename, jsonBytes, 0600); err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Saved config.\")\n\treturn nil\n}"} {"input": "package gtreap\n\nimport (\n\t\"math/rand\"\n\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\nfunc (w *Writer) BytesSafeAfterClose() bool {\n\treturn false\n}\n\n\n\nfunc (w *Writer) Iterator(k []byte) store.KVIterator {\n\tw.s.m.Lock()\n\tt := w.s.t\n\tw.s.m.Unlock()\n\n\treturn newIterator(t).restart(&Item{k: k})\n}\n\nfunc (w *Writer) Close() error {\n\tw.s.availableWriters <- true\n\tw.s = nil\n\n\treturn nil\n}\n\nfunc (w *Writer) Set(k, v []byte) (err error) {\n\tw.s.m.Lock()\n\tw.s.t = w.s.t.Upsert(&Item{k: k, v: v}, rand.Int())\n\tw.s.m.Unlock()\n\n\treturn nil\n}\n\nfunc (w *Writer) Delete(k []byte) (err error) {\n\tw.s.m.Lock()\n\tw.s.t = w.s.t.Delete(&Item{k: k})\n\tw.s.m.Unlock()\n\n\treturn nil\n}\n\nfunc (w *Writer) NewBatch() store.KVBatch {\n\treturn store.NewEmulatedBatch(w, w.s.mo)\n}\n\nfunc (w *Writer) Get(k []byte) (v []byte, err error) ", "output": "{\n\tw.s.m.Lock()\n\tt := w.s.t\n\tw.s.m.Unlock()\n\n\titm := t.Get(&Item{k: k})\n\tif itm != nil {\n\t\treturn itm.(*Item).v, nil\n\t}\n\treturn nil, nil\n}"} {"input": "package memory\n\nimport (\n\t\"fmt\"\n)\n\n\ntype RAM struct {\n\tdata []byte\n\twindow []byte\n\taddrOffset uint16\n}\n\n\n\n\n\n\nfunc (r *RAM) SetWindow(offset uint32) error {\n\n\tif uint32(len(r.data)) <= offset {\n\t\treturn fmt.Errorf(\"window offset out of range (%d)\", offset)\n\t}\n\n\tr.window = r.data[offset:]\n\n\treturn nil\n}\n\n\nfunc (r *RAM) Read(addr uint16) (byte, error) {\n\n\tif r.addrOffset > addr {\n\t\treturn 0, ReadOutOfRangeError(addr)\n\t}\n\n\tphysicalAddr := addr - r.addrOffset\n\n\tif uint(len(r.window)) <= uint(physicalAddr) {\n\t\treturn 0, ReadOutOfRangeError(addr)\n\t}\n\n\treturn r.window[physicalAddr], nil\n}\n\n\nfunc (r *RAM) Write(addr uint16, data byte) error {\n\n\tif r.addrOffset > addr {\n\t\treturn WriteOutOfRangeError(addr)\n\t}\n\n\tphysicalAddr := addr - r.addrOffset\n\n\tif uint(len(r.window)) <= uint(physicalAddr) {\n\t\treturn WriteOutOfRangeError(addr)\n\t}\n\n\tr.window[physicalAddr] = data\n\n\treturn nil\n}\n\nfunc NewRAM(data []byte, addrOffset uint16) *RAM ", "output": "{\n\n\tr := RAM{data: data, addrOffset: addrOffset}\n\tr.SetWindow(0)\n\n\treturn &r\n}"} {"input": "package frames\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestGridBasicOutput(t *testing.T) ", "output": "{\n\tx := NewFrame(\"GRID\", \"\", Version3).(*GRID)\n\tif x.GetName() != \"GRID\" {\n\t\tt.Error(\"Invalid name from GRID frame\")\n\t}\n\n\tx.Name = \"BOB\"\n\tif x.GetName() != \"BOB\" {\n\t\tt.Error(\"Invalid GRID Name setting\")\n\t}\n\n\tb := []byte(\"Bob\\x00\\x13\\x06\\x06\\x06\")\n\tx.ProcessData(len(b), b)\n\n\texpected := fmt.Sprintf(\"Group Reg Identifier\\n\\tOwner: Bob\\n\\tSymbol: %b\\n\", '\\x13')\n\tfound := x.DisplayContent()\n\tif found != expected {\n\t\tt.Errorf(\"Got [%s], Expected [%s]\", found, expected)\n\t}\n}"} {"input": "package strings\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\n\n\nfunc FormatTimeShort(t time.Time) string {\n\treturn fmt.Sprintf(\"%d.%d %d %d:%02d\", t.Day(), t.Month(), t.Year(),\n\t\tt.Hour(), t.Minute())\n}\n\nfunc FormatTime(t time.Time) string ", "output": "{\n\treturn fmt.Sprintf(\"%d.%d %d %02d:%02d:%02d\", t.Day(), t.Month(), t.Year(),\n\t\tt.Hour(), t.Minute(), t.Second())\n}"} {"input": "package frames\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\ntype RstStreamFrame struct {\n\tStreamId uint32\n\tErrorCode ErrorCode\n}\n\nfunc NewRstStreamFrame(streamId uint32, errorCode ErrorCode) *RstStreamFrame {\n\treturn &RstStreamFrame{\n\t\tStreamId: streamId,\n\t\tErrorCode: errorCode,\n\t}\n}\n\nfunc DecodeRstStreamFrame(flags byte, streamId uint32, payload []byte, context *DecodingContext) (Frame, error) {\n\tif len(payload) != 4 {\n\t\treturn nil, fmt.Errorf(\"FRAME_SIZE_ERROR: Received RST_STREAM frame of length %v\", len(payload))\n\t}\n\treturn NewRstStreamFrame(streamId, ErrorCode(binary.BigEndian.Uint32(payload))), nil\n}\n\nfunc (f *RstStreamFrame) Type() Type {\n\treturn RST_STREAM_TYPE\n}\n\n\n\nfunc (f *RstStreamFrame) GetStreamId() uint32 {\n\treturn f.StreamId\n}\n\nfunc (f *RstStreamFrame) Encode(context *EncodingContext) ([]byte, error) ", "output": "{\n\tresult := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(result, uint32(f.ErrorCode))\n\treturn result, nil\n}"} {"input": "package gcetasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realAddress Address\n\n\nfunc (o *Address) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realAddress\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = Address(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &Address{}\n\n\nfunc (o *Address) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\n\nfunc (o *Address) SetLifecycle(lifecycle fi.Lifecycle) {\n\to.Lifecycle = &lifecycle\n}\n\nvar _ fi.HasName = &Address{}\n\n\nfunc (o *Address) GetName() *string {\n\treturn o.Name\n}\n\n\nfunc (o *Address) SetName(name string) {\n\to.Name = &name\n}\n\n\n\n\nfunc (o *Address) String() string ", "output": "{\n\treturn fi.TaskAsString(o)\n}"} {"input": "package metrics\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/go-openapi/runtime\"\n\t\"github.com/go-openapi/strfmt\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\ntype GetMetricsReader struct {\n\tformats strfmt.Registry\n}\n\n\n\n\n\nfunc NewGetMetricsOK() *GetMetricsOK {\n\treturn &GetMetricsOK{}\n}\n\n\ntype GetMetricsOK struct {\n\tPayload []*models.Metric\n}\n\nfunc (o *GetMetricsOK) Error() string {\n\treturn fmt.Sprintf(\"[GET /metrics/][%d] getMetricsOK %+v\", 200, o.Payload)\n}\n\nfunc (o *GetMetricsOK) GetPayload() []*models.Metric {\n\treturn o.Payload\n}\n\nfunc (o *GetMetricsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\tif err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc NewGetMetricsInternalServerError() *GetMetricsInternalServerError {\n\treturn &GetMetricsInternalServerError{}\n}\n\n\ntype GetMetricsInternalServerError struct {\n}\n\nfunc (o *GetMetricsInternalServerError) Error() string {\n\treturn fmt.Sprintf(\"[GET /metrics/][%d] getMetricsInternalServerError \", 500)\n}\n\nfunc (o *GetMetricsInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\treturn nil\n}\n\nfunc (o *GetMetricsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) ", "output": "{\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetMetricsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewGetMetricsInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\nfunc Print(format string, params ...interface{}) {\n\tfmt.Fprintf(os.Stderr, format+\"\\n\", params...)\n}\n\nfunc Info(format string, params ...interface{}) {\n\tPrint(\"Info: \" + format, params...)\n}\n\nfunc Error(err error) {\n\tPrint(\"Error: %s\", err)\n}\n\n\n\nfunc main() {\n\tvar config Config\n\tvar err error\n\tif config, err = LoadConfig(); err != nil {\n\t\tFatal(err)\n\t}\n\n\tif err = config.Verify(); err != nil {\n\t\tFatal(err)\n\t}\n\n\tvar svcmon ServiceMonitor\n\tif svcmon, err = NewServiceMonitor(&config); err != nil {\n\t\tFatal(err)\n\t}\n\n\tcleanup := func() {\n\t\tsvcmon.Close()\n\t}\n\n\tdefer cleanup()\n\tsigchan := make(chan os.Signal, 1)\n\tsignal.Notify(sigchan, syscall.SIGINT)\n\tsignal.Notify(sigchan, syscall.SIGTERM)\n\tquit := make(chan bool)\n\n\tgo func() {\n\t\t<-sigchan\n\t\tcleanup()\n\t\tquit <- true\n\t}()\n\n\tgo func() {\n\t\tif err = svcmon.Run(); err != nil {\n\t\t\tFatal(err)\n\t\t}\n\t\tquit <- true\n\t}()\n\n\t<-quit\n}\n\nfunc Fatal(err error) ", "output": "{\n\tPrint(\"Fatal: %s\", err)\n\tos.Exit(1)\n}"} {"input": "package process\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc toHash(input []byte) string {\n\thasher := sha256.New()\n\thasher.Write(input)\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}\n\n\n\nfunc RandomHash() string {\n\treturn toHash(getRandomData())\n}\n\n\ntype Token struct {\n\tHash string\n}\n\nvar ProcessToken *Token = NewToken()\n\nfunc NewToken() *Token {\n\treturn &Token{\n\t\tHash: RandomHash(),\n\t}\n}\n\nfunc PrettyUniqueToken() string {\n\treturn fmt.Sprintf(\"%d:%s\", time.Now().UnixNano(), NewToken().Hash)\n}\n\nfunc getRandomData() []byte ", "output": "{\n\tsize := 64\n\trb := make([]byte, size)\n\t_, _ = rand.Read(rb)\n\treturn rb\n}"} {"input": "package deb\n\nimport (\n\t\"encoding/binary\"\n\t\"github.com/smira/aptly/aptly\"\n\t\"github.com/smira/aptly/utils\"\n\t\"hash/fnv\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n)\n\n\ntype PackageFile struct {\n\tFilename string\n\tChecksums utils.ChecksumInfo\n\tdownloadPath string\n}\n\n\nfunc (f *PackageFile) Verify(packagePool aptly.PackagePool) (bool, error) {\n\tpoolPath, err := packagePool.Path(f.Filename, f.Checksums.MD5)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tst, err := os.Stat(poolPath)\n\tif err != nil {\n\t\treturn false, nil\n\t}\n\n\treturn st.Size() == f.Checksums.Size, nil\n}\n\n\nfunc (f *PackageFile) DownloadURL() string {\n\treturn filepath.Join(f.downloadPath, f.Filename)\n}\n\n\ntype PackageFiles []PackageFile\n\n\n\n\n\nfunc (files PackageFiles) Len() int {\n\treturn len(files)\n}\n\n\nfunc (files PackageFiles) Swap(i, j int) {\n\tfiles[i], files[j] = files[j], files[i]\n}\n\n\nfunc (files PackageFiles) Less(i, j int) bool {\n\treturn files[i].Filename < files[j].Filename\n}\n\nfunc (files PackageFiles) Hash() uint64 ", "output": "{\n\tsort.Sort(files)\n\n\th := fnv.New64a()\n\n\tfor _, f := range files {\n\t\th.Write([]byte(f.Filename))\n\t\tbinary.Write(h, binary.BigEndian, f.Checksums.Size)\n\t\th.Write([]byte(f.Checksums.MD5))\n\t\th.Write([]byte(f.Checksums.SHA1))\n\t\th.Write([]byte(f.Checksums.SHA256))\n\t}\n\n\treturn h.Sum64()\n}"} {"input": "package lessons\n\nimport(\n\t\"fmt\"\n)\n\n\n\nfunc Range() ", "output": "{\n\tnums := []int{2,3,4}\n\tsum := 0\n\tfor _, num := range nums {\n\t\tsum += num\n\t}\n\tfmt.Println(\"sum:\", sum)\n\tfor i, num := range nums {\n\t\tif num ==3 {\n\t\t\tfmt.Println(\"index:\", i)\n\t\t}\n\t}\n\tkvs := map[string]string {\"a\": \"apple\", \"b\": \"banana\"}\n\tfor k, v := range kvs {\n\t\tfmt.Printf(\"%s -> %s\\n\", k, v)\n\t}\n\tfor i, c := range \"go\" {\n\t\tfmt.Println(i, c)\n\t}\n}"} {"input": "package commands\n\nimport (\n\t\"strings\"\n\n\t\"github.com/github/hub/v2/github\"\n\t\"github.com/github/hub/v2/utils\"\n)\n\nvar cmdPush = &Command{\n\tRun: push,\n\tGitExtension: true,\n\tUsage: \"push [,...] []\",\n\tLong: `Push a git branch to each of the listed remotes.\n\n## Examples:\n\t\t$ hub push origin,staging,qa bert_timeout\n\t\t> git push origin bert_timeout\n\t\t> git push staging bert_timeout\n\t\t> git push qa bert_timeout\n\n\t\t$ hub push origin\n\t\t> git push origin HEAD\n\n## See also:\n\nhub(1), git-push(1)\n`,\n}\n\nfunc init() {\n\tCmdRunner.Use(cmdPush)\n}\n\n\n\nfunc transformPushArgs(args *Args) {\n\trefs := []string{}\n\tif args.ParamsSize() > 1 {\n\t\trefs = args.Params[1:]\n\t}\n\n\tremotes := strings.Split(args.FirstParam(), \",\")\n\targs.ReplaceParam(0, remotes[0])\n\n\tif len(refs) == 0 {\n\t\tlocalRepo, err := github.LocalRepo()\n\t\tutils.Check(err)\n\n\t\thead, err := localRepo.CurrentBranch()\n\t\tutils.Check(err)\n\n\t\trefs = []string{head.ShortName()}\n\t\targs.AppendParams(refs...)\n\t}\n\n\tfor _, remote := range remotes[1:] {\n\t\tafterCmd := []string{\"git\", \"push\", remote}\n\t\tafterCmd = append(afterCmd, refs...)\n\t\targs.After(afterCmd...)\n\t}\n}\n\nfunc push(command *Command, args *Args) ", "output": "{\n\tif !args.IsParamsEmpty() && strings.Contains(args.FirstParam(), \",\") {\n\t\ttransformPushArgs(args)\n\t}\n}"} {"input": "package framework\n\ntype SizeMode int\n\nconst (\n\tExpandToContent SizeMode = iota\n\tFill\n)\n\n\n\nfunc (s SizeMode) Fill() bool {\n\treturn s == Fill\n}\n\nfunc (s SizeMode) ExpandToContent() bool ", "output": "{\n\treturn s == ExpandToContent\n}"} {"input": "package models\n\nimport \"github.com/tuxychandru/pubsub\"\n\nvar (\n\tPushCenter *pubsub.PubSub\n)\n\n\n\nfunc PushMessage(channel string, message interface{}) {\n\tPushCenter.Pub(message, channel)\n}\n\nfunc Subscribe(channel string, callback func(message interface{})) {\n\tch := PushCenter.Sub(channel)\n\tfor {\n\t\tout := <-ch\n\t\tcallback(out)\n\t}\n}\n\nfunc initPubsub() ", "output": "{\n\tPushCenter = pubsub.New(100)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/spec/discovery\"\n)\n\nvar (\n\tcmdDiscover = &Command{\n\t\tName: \"discover\",\n\t\tDescription: \"Discover the download URLs for an app\",\n\t\tSummary: \"Discover the download URLs for one or more app container images\",\n\t\tUsage: \"APP...\",\n\t\tRun: runDiscover,\n\t}\n)\n\n\n\nfunc runDiscover(args []string) (exit int) {\n\tif len(args) < 1 {\n\t\tstderr(\"discover: at least one name required\")\n\t}\n\n\tfor _, name := range args {\n\t\tapp, err := discovery.NewAppFromString(name)\n\t\tif app.Labels[\"os\"] == \"\" {\n\t\t\tapp.Labels[\"os\"] = runtime.GOOS\n\t\t}\n\t\tif app.Labels[\"arch\"] == \"\" {\n\t\t\tapp.Labels[\"arch\"] = runtime.GOARCH\n\t\t}\n\t\tif err != nil {\n\t\t\tstderr(\"%s: %s\", name, err)\n\t\t\treturn 1\n\t\t}\n\t\teps, attempts, err := discovery.DiscoverEndpoints(*app, transportFlags.Insecure)\n\t\tif err != nil {\n\t\t\tstderr(\"error fetching %s: %s\", name, err)\n\t\t\treturn 1\n\t\t}\n\t\tfor _, a := range attempts {\n\t\t\tfmt.Printf(\"discover walk: prefix: %s error: %v\\n\", a.Prefix, a.Error)\n\t\t}\n\t\tfor _, aciEndpoint := range eps.ACIEndpoints {\n\t\t\tfmt.Printf(\"ACI: %s, ASC: %s\\n\", aciEndpoint.ACI, aciEndpoint.ASC)\n\t\t}\n\t\tif len(eps.Keys) > 0 {\n\t\t\tfmt.Println(\"Keys: \" + strings.Join(eps.Keys, \",\"))\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc init() ", "output": "{\n\tcmdDiscover.Flags.BoolVar(&transportFlags.Insecure, \"insecure\", false,\n\t\t\"Allow insecure non-TLS downloads over http\")\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype CreateBootVolumeRequest struct {\n\n\tCreateBootVolumeDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateBootVolumeRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request CreateBootVolumeRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateBootVolumeResponse struct {\n\n\tRawResponse *http.Response\n\n\tBootVolume `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateBootVolumeResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateBootVolumeResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateBootVolumeRequest) HTTPRequest(method, path string) (http.Request, error) ", "output": "{\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}"} {"input": "package scheduler\n\nimport (\n\t\"github.com/cnaize/kubernetes/pkg/api\"\n)\n\n\ntype FitPredicate func(pod api.Pod, existingPods []api.Pod, node string) (bool, error)\n\n\ntype HostPriority struct {\n\thost string\n\tscore int\n}\n\ntype HostPriorityList []HostPriority\n\nfunc (h HostPriorityList) Len() int {\n\treturn len(h)\n}\n\n\n\nfunc (h HostPriorityList) Swap(i, j int) {\n\th[i], h[j] = h[j], h[i]\n}\n\ntype PriorityFunction func(pod api.Pod, podLister PodLister, minionLister MinionLister) (HostPriorityList, error)\n\ntype PriorityConfig struct {\n\tFunction PriorityFunction\n\tWeight int\n}\n\nfunc (h HostPriorityList) Less(i, j int) bool ", "output": "{\n\tif h[i].score == h[j].score {\n\t\treturn h[i].host < h[j].host\n\t}\n\treturn h[i].score < h[j].score\n}"} {"input": "package google\n\nimport (\n\t\"fmt\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/terraform\"\n\t\"log\"\n)\n\nfunc resourceContainerNodePoolMigrateState(v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) {\n\tif is.Empty() {\n\t\tlog.Println(\"[DEBUG] Empty InstanceState; nothing to migrate.\")\n\t\treturn is, nil\n\t}\n\n\tswitch v {\n\tcase 0:\n\t\tlog.Println(\"[INFO] Found Container Node Pool State v0; migrating to v1\")\n\t\treturn migrateNodePoolStateV0toV1(is)\n\tdefault:\n\t\treturn is, fmt.Errorf(\"Unexpected schema version: %d\", v)\n\t}\n}\n\n\n\nfunc migrateNodePoolStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) ", "output": "{\n\tlog.Printf(\"[DEBUG] Attributes before migration: %#v\", is.Attributes)\n\tlog.Printf(\"[DEBUG] ID before migration: %s\", is.ID)\n\n\tis.ID = fmt.Sprintf(\"%s/%s/%s\", is.Attributes[\"zone\"], is.Attributes[\"cluster\"], is.Attributes[\"name\"])\n\n\tlog.Printf(\"[DEBUG] ID after migration: %s\", is.ID)\n\treturn is, nil\n}"} {"input": "package internal\n\nimport (\n\t\"log\"\n\t\"os/exec\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\n\nconst KillGrace = 5 * time.Second\n\n\n\n\n\n\nfunc WaitTimeout(c *exec.Cmd, timeout time.Duration) error ", "output": "{\n\tvar kill *time.Timer\n\tterm := time.AfterFunc(timeout, func() {\n\t\terr := c.Process.Signal(syscall.SIGTERM)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"E! [agent] Error terminating process: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tkill = time.AfterFunc(KillGrace, func() {\n\t\t\terr := c.Process.Kill()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"E! [agent] Error killing process: %s\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t})\n\t})\n\n\terr := c.Wait()\n\n\tif kill != nil {\n\t\tkill.Stop()\n\t}\n\ttermSent := !term.Stop()\n\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tif termSent {\n\t\treturn ErrTimeout\n\t}\n\n\treturn err\n}"} {"input": "package sml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/sml\"\n)\n\n\n\nfunc TestCT_GradientFillMarshalUnmarshal(t *testing.T) {\n\tv := sml.NewCT_GradientFill()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := sml.NewCT_GradientFill()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestCT_GradientFillConstructor(t *testing.T) ", "output": "{\n\tv := sml.NewCT_GradientFill()\n\tif v == nil {\n\t\tt.Errorf(\"sml.NewCT_GradientFill must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed sml.CT_GradientFill should validate: %s\", err)\n\t}\n}"} {"input": "package progress\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\n\n\nfunc TestCompleteSilently(t *testing.T) {\n\tcontent := []byte(\"TESTING\")\n\treader := ioutil.NopCloser(bytes.NewReader(content))\n\tprogressChan := make(chan Progress, 10)\n\n\tpr := NewProgressReader(reader, ChanOutput(progressChan), int64(len(content)), \"Test\", \"Read\")\n\n\tout, err := ioutil.ReadAll(pr)\n\tif err != nil {\n\t\tpr.Close()\n\t\tt.Fatal(err)\n\t}\n\tif string(out) != \"TESTING\" {\n\t\tpr.Close()\n\t\tt.Fatalf(\"Unexpected output %q from reader\", string(out))\n\t}\n\ndrainLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-progressChan:\n\t\tdefault:\n\t\t\tbreak drainLoop\n\t\t}\n\t}\n\n\tpr.Close()\n\n\tselect {\n\tcase <-progressChan:\n\t\tt.Fatalf(\"Should have closed silently when read is complete\")\n\tdefault:\n\t}\n}\n\nfunc TestOutputOnPrematureClose(t *testing.T) ", "output": "{\n\tcontent := []byte(\"TESTING\")\n\treader := ioutil.NopCloser(bytes.NewReader(content))\n\tprogressChan := make(chan Progress, 10)\n\n\tpr := NewProgressReader(reader, ChanOutput(progressChan), int64(len(content)), \"Test\", \"Read\")\n\n\tpart := make([]byte, 4, 4)\n\t_, err := io.ReadFull(pr, part)\n\tif err != nil {\n\t\tpr.Close()\n\t\tt.Fatal(err)\n\t}\n\ndrainLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-progressChan:\n\t\tdefault:\n\t\t\tbreak drainLoop\n\t\t}\n\t}\n\n\tpr.Close()\n\n\tselect {\n\tcase <-progressChan:\n\tdefault:\n\t\tt.Fatalf(\"Expected some output when closing prematurely\")\n\t}\n}"} {"input": "package machinelearning\n\nimport (\n\t\"net/url\"\n\n\t\"github.com/gunosy/aws-sdk-go/aws\"\n)\n\n\n\n\n\nfunc updatePredictEndpoint(r *aws.Request) {\n\tif !r.ParamsFilled() {\n\t\treturn\n\t}\n\n\tr.Endpoint = *r.Params.(*PredictInput).PredictEndpoint\n\n\turi, err := url.Parse(r.Endpoint)\n\tif err != nil {\n\t\tr.Error = err\n\t\treturn\n\t}\n\tr.HTTPRequest.URL = uri\n}\n\nfunc init() ", "output": "{\n\tinitRequest = func(r *aws.Request) {\n\t\tswitch r.Operation.Name {\n\t\tcase opPredict:\n\t\t\tr.Handlers.Build.PushBack(updatePredictEndpoint)\n\t\t}\n\t}\n}"} {"input": "package cloudinfo\n\nimport (\n\t\"k8s.io/klog/v2\"\n\n\tinfo \"github.com/google/cadvisor/info/v1\"\n)\n\ntype CloudInfo interface {\n\tGetCloudProvider() info.CloudProvider\n\tGetInstanceType() info.InstanceType\n\tGetInstanceID() info.InstanceID\n}\n\n\ntype CloudProvider interface {\n\tIsActiveProvider() bool\n\tGetInstanceType() info.InstanceType\n\tGetInstanceID() info.InstanceID\n}\n\nvar providers = map[info.CloudProvider]CloudProvider{}\n\n\nfunc RegisterCloudProvider(name info.CloudProvider, provider CloudProvider) {\n\tif _, alreadyRegistered := providers[name]; alreadyRegistered {\n\t\tklog.Warningf(\"Duplicate registration of CloudProvider %s\", name)\n\t}\n\tproviders[name] = provider\n}\n\ntype realCloudInfo struct {\n\tcloudProvider info.CloudProvider\n\tinstanceType info.InstanceType\n\tinstanceID info.InstanceID\n}\n\n\n\nfunc (i *realCloudInfo) GetCloudProvider() info.CloudProvider {\n\treturn i.cloudProvider\n}\n\nfunc (i *realCloudInfo) GetInstanceType() info.InstanceType {\n\treturn i.instanceType\n}\n\nfunc (i *realCloudInfo) GetInstanceID() info.InstanceID {\n\treturn i.instanceID\n}\n\nfunc NewRealCloudInfo() CloudInfo ", "output": "{\n\tfor name, provider := range providers {\n\t\tif provider.IsActiveProvider() {\n\t\t\treturn &realCloudInfo{\n\t\t\t\tcloudProvider: name,\n\t\t\t\tinstanceType: provider.GetInstanceType(),\n\t\t\t\tinstanceID: provider.GetInstanceID(),\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &realCloudInfo{\n\t\tcloudProvider: info.UnknownProvider,\n\t\tinstanceType: info.UnknownInstance,\n\t\tinstanceID: info.UnNamedInstance,\n\t}\n}"} {"input": "package icon\n\nimport (\n\t\"github.com/sacloud/libsacloud/v2/helper/service\"\n\t\"github.com/sacloud/libsacloud/v2/helper/validate\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\ntype UpdateRequest struct {\n\tID types.ID `request:\"-\" validate:\"required\"`\n\n\tName *string `request:\",omitempty\" validate:\"omitempty,min=1\"`\n\tTags *types.Tags `request:\",omitempty\"`\n}\n\nfunc (req *UpdateRequest) Validate() error {\n\treturn validate.Struct(req)\n}\n\n\n\nfunc (req *UpdateRequest) ToRequestParameter(current *sacloud.Icon) (*sacloud.IconUpdateRequest, error) ", "output": "{\n\tr := &sacloud.IconUpdateRequest{}\n\tif err := service.RequestConvertTo(current, r); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := service.RequestConvertTo(req, r); err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}"} {"input": "package v1alpha1\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\tv1alpha1 \"k8s.io/ingress-gce/pkg/experimental/apis/workload/v1alpha1\"\n\t\"k8s.io/ingress-gce/pkg/experimental/workload/client/clientset/versioned/scheme\"\n)\n\ntype NetworkingV1alpha1Interface interface {\n\tRESTClient() rest.Interface\n\tWorkloadsGetter\n}\n\n\ntype NetworkingV1alpha1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *NetworkingV1alpha1Client) Workloads(namespace string) WorkloadInterface {\n\treturn newWorkloads(c, namespace)\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *NetworkingV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *NetworkingV1alpha1Client {\n\treturn &NetworkingV1alpha1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *NetworkingV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfig(c *rest.Config) (*NetworkingV1alpha1Client, error) ", "output": "{\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &NetworkingV1alpha1Client{client}, nil\n}"} {"input": "package main\n\nimport \"log\"\nimport \"time\"\nimport \"fmt\"\nimport \"gopkg.in/project-iris/iris-go.v1\"\n\ntype H struct {}\n\n\nfunc (b *H) HandleTunnel(tun *iris.Tunnel) { }\nfunc (b *H) HandleDrop(reason error) { }\nfunc (b *H) Init(conn *iris.Connection) error { return nil }\n\nfunc (b *H) HandleBroadcast(msg []byte) {\n fmt.Printf(\"message arrived: %v\\n\", string(msg))\n}\n\nfunc main() {\n service, err := iris.Register(55555, \"bcst\", new(H), nil)\n if err != nil {\n log.Fatalf(\"registration to %v failed\", err)\n }\n defer service.Unregister()\n\n log.Printf(\"waiting...\")\n time.Sleep(100 * time.Second)\n}\n\nfunc (b *H) HandleRequest(req []byte) ([]byte, error) ", "output": "{ return req, nil }"} {"input": "package routetable_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n\n\t\"github.com/onsi/ginkgo/reporters\"\n\n\t\"github.com/projectcalico/libcalico-go/lib/testutils\"\n)\n\nfunc init() {\n\ttestutils.HookLogrusForGinkgo()\n}\n\n\n\nfunc TestRules(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tjunitReporter := reporters.NewJUnitReporter(\"../report/routetable_suite.xml\")\n\tRunSpecsWithDefaultAndCustomReporters(t, \"RouteTable Suite\", []Reporter{junitReporter})\n}"} {"input": "package alicloud\n\ntype PrimaryKeyTypeString string\n\nconst (\n\tIntegerType = PrimaryKeyTypeString(\"Integer\")\n\tStringType = PrimaryKeyTypeString(\"String\")\n\tBinaryType = PrimaryKeyTypeString(\"Binary\")\n)\n\ntype InstanceAccessedByType string\n\nconst (\n\tAnyNetwork = InstanceAccessedByType(\"Any\")\n\tVpcOnly = InstanceAccessedByType(\"Vpc\")\n\tVpcOrConsole = InstanceAccessedByType(\"ConsoleOrVpc\")\n)\n\ntype OtsInstanceType string\n\nconst (\n\tOtsCapacity = OtsInstanceType(\"Capacity\")\n\tOtsHighPerformance = OtsInstanceType(\"HighPerformance\")\n)\n\nfunc convertInstanceAccessedBy(accessed InstanceAccessedByType) string {\n\tswitch accessed {\n\tcase VpcOnly:\n\t\treturn \"VPC\"\n\tcase VpcOrConsole:\n\t\treturn \"VPC_CONSOLE\"\n\tdefault:\n\t\treturn \"NORMAL\"\n\t}\n}\n\nfunc convertInstanceAccessedByRevert(network string) InstanceAccessedByType {\n\tswitch network {\n\tcase \"VPC\":\n\t\treturn VpcOnly\n\tcase \"VPC_CONSOLE\":\n\t\treturn VpcOrConsole\n\tdefault:\n\t\treturn AnyNetwork\n\t}\n}\n\nfunc convertInstanceType(instanceType OtsInstanceType) string {\n\tswitch instanceType {\n\tcase OtsHighPerformance:\n\t\treturn \"SSD\"\n\tdefault:\n\t\treturn \"HYBRID\"\n\t}\n}\n\nfunc convertInstanceTypeRevert(instanceType string) OtsInstanceType {\n\tswitch instanceType {\n\tcase \"SSD\":\n\t\treturn OtsHighPerformance\n\tdefault:\n\t\treturn OtsCapacity\n\t}\n}\n\n\n\n\nfunc convertOtsInstanceStatus(status Status) int ", "output": "{\n\tswitch status {\n\tcase Running:\n\t\treturn 1\n\tcase DisabledStatus:\n\t\treturn 2\n\tcase Deleting:\n\t\treturn 3\n\tdefault:\n\t\treturn -1\n\t}\n}"} {"input": "package requirements\n\nimport (\n\t\"github.com/cloudfoundry/cli/cf/api/applications\"\n\t\"github.com/cloudfoundry/cli/cf/models\"\n)\n\n\ntype ApplicationRequirement interface {\n\tRequirement\n\tGetApplication() models.Application\n}\n\ntype applicationApiRequirement struct {\n\tname string\n\tappRepo applications.ApplicationRepository\n\tapplication models.Application\n}\n\nfunc NewApplicationRequirement(name string, aR applications.ApplicationRepository) *applicationApiRequirement {\n\treq := &applicationApiRequirement{}\n\treq.name = name\n\treq.appRepo = aR\n\treturn req\n}\n\n\n\nfunc (req *applicationApiRequirement) GetApplication() models.Application {\n\treturn req.application\n}\n\nfunc (req *applicationApiRequirement) Execute() error ", "output": "{\n\tvar apiErr error\n\treq.application, apiErr = req.appRepo.Read(req.name)\n\n\tif apiErr != nil {\n\t\treturn apiErr\n\t}\n\n\treturn nil\n}"} {"input": "package matchers_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/blevesearch/bleve\"\n\t\"github.com/blevesearch/bleve/search/query\"\n\t\"github.com/nrwiersma/isenzo/matchers\"\n)\n\nfunc TestParallelMatcher(t *testing.T) {\n\tf := matchers.NewParallelMatcherFactory(newWaitMatcherFactory(), 10)\n\tm, err := f.New(map[string]interface{}{})\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected err; got %v\", err)\n\t}\n\n\tfor i := 0; i < 10; i++ {\n\t\tm.Match(\"\", bleve.NewMatchAllQuery())\n\t}\n\n\tids, errs := m.Finish()\n\tif len(errs) != 0 {\n\t\tt.Fatalf(\"expected no errors; got %v\", errs)\n\t}\n\n\tif len(ids) != 10 {\n\t\tt.Fatalf(\"expected %d results; got %v\", 10, len(ids))\n\t}\n}\n\ntype waitMatcherFactory struct {}\n\nfunc newWaitMatcherFactory() matchers.Factory {\n\treturn &waitMatcherFactory{}\n}\n\n\n\nfunc (f waitMatcherFactory) Map(doc interface{}) (interface{}, error) {\n\treturn doc, nil\n}\n\ntype waitMatcher struct {\n\tids []string\n}\n\n\nfunc (m *waitMatcher) Match(id string, q query.Query) {\n\ttime.Sleep(10 * time.Millisecond)\n\n\tm.ids = append(m.ids, id)\n}\n\n\nfunc (m *waitMatcher) Finish() (ids []string, errs []error) {\n\treturn m.ids, []error{}\n}\n\nfunc (f waitMatcherFactory) New(doc interface{}) (matchers.Matcher, error) ", "output": "{\n\treturn &waitMatcher{\n\t\tids: make([]string, 0),\n\t}, nil\n}"} {"input": "package goat\n\nimport \"github.com/julienschmidt/httprouter\"\n\n\ntype Params map[string]string\n\n\n\n\nfunc paramsFromHTTPRouter(hrps httprouter.Params) Params ", "output": "{\n\tvar ps = Params{}\n\n\tfor _, p := range hrps {\n\t\tps[p.Key] = p.Value\n\t}\n\n\treturn ps\n}"} {"input": "package help\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\ntype EvtPool struct {\n\theader DListNode\n}\n\nfunc (this *EvtPool) Init() {\n\tthis.header.Init(nil)\n}\n\n\n\nfunc (this *EvtPool) Post(d IEvent) bool {\n\n\tn := &DListNode{}\n\tn.Init(d)\n\n\tif !d.AddNode(n) {\n\t\treturn false\n\t}\n\n\told_pre := this.header.Pre\n\n\tthis.header.Pre = n\n\tn.Next = &this.header\n\tn.Pre = old_pre\n\told_pre.Next = n\n\n\treturn true\n}\n\nfunc (this *EvtPool) Run() {\n\tfor {\n\t\tif this.header.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\n\t\tn := this.header.Next\n\n\t\tn.Data.(IEvent).Exec(this)\n\n\t\tn.Data.(IEvent).Destroy()\n\t}\n}\n\ntype Evt_eat struct {\n\tEvt_base\n\tFoodName string\n}\n\nfunc (this *Evt_eat) Exec() bool {\n\treturn true\n}\n\nfunc TestDlist(t *testing.T) {\n\n\tvar g_Pool EvtPool\n\tg_Pool.Init()\n\n\tg_Pool.Post(&Evt_eat{FoodName: \"西瓜\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"葡萄\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"黄瓜\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"大蒜\"})\n\n\tg_Pool.Run()\n}\n\nfunc (this *EvtPool) Eat(name string) ", "output": "{\n\tfmt.Printf(\"吃%s\\n\", name)\n}"} {"input": "package testclient\n\nimport (\n\tkapi \"k8s.io/kubernetes/pkg/api\"\n\tktestclient \"k8s.io/kubernetes/pkg/client/unversioned/testclient\"\n\n\t\"github.com/openshift/origin/pkg/client\"\n\timageapi \"github.com/openshift/origin/pkg/image/api\"\n)\n\n\n\n\ntype FakeImages struct {\n\tFake *Fake\n}\n\nvar _ client.ImageInterface = &FakeImages{}\n\n\n\nfunc (c *FakeImages) List(opts kapi.ListOptions) (*imageapi.ImageList, error) {\n\tobj, err := c.Fake.Invokes(ktestclient.NewRootListAction(\"images\", opts), &imageapi.ImageList{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*imageapi.ImageList), err\n}\n\nfunc (c *FakeImages) Create(inObj *imageapi.Image) (*imageapi.Image, error) {\n\tobj, err := c.Fake.Invokes(ktestclient.NewRootCreateAction(\"images\", inObj), inObj)\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*imageapi.Image), err\n}\n\nfunc (c *FakeImages) Delete(name string) error {\n\t_, err := c.Fake.Invokes(ktestclient.NewRootDeleteAction(\"images\", name), &imageapi.Image{})\n\treturn err\n}\n\nfunc (c *FakeImages) Get(name string) (*imageapi.Image, error) ", "output": "{\n\tobj, err := c.Fake.Invokes(ktestclient.NewRootGetAction(\"images\", name), &imageapi.Image{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*imageapi.Image), err\n}"} {"input": "package colorable\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\n\nfunc NewColorable(file *os.File) io.Writer {\n\tif file == nil {\n\t\tpanic(\"nil passed instead of *os.File to NewColorable()\")\n\t}\n\n\treturn file\n}\n\n\n\n\n\nfunc NewColorableStderr() io.Writer {\n\treturn os.Stderr\n}\n\nfunc NewColorableStdout() io.Writer ", "output": "{\n\treturn os.Stdout\n}"} {"input": "package payloads\n\n\n\ntype InstanceStat struct {\n\n\tInstanceUUID string `yaml:\"instance_uuid\"`\n\n\tState string `yaml:\"state\"`\n\n\tSSHIP string `yaml:\"ssh_ip\"`\n\n\tSSHPort int `yaml:\"ssh_port\"`\n\n\tMemoryUsageMB int `yaml:\"memory_usage_mb\"`\n\n\tDiskUsageMB int `yaml:\"disk_usage_mb\"`\n\n\tCPUUsage int `yaml:\"cpu_usage\"`\n\n\tVolumes []string `yaml:\"volumes\"`\n}\n\n\n\ntype NetworkStat struct {\n\tNodeIP string `yaml:\"ip\"`\n\tNodeMAC string `yaml:\"mac\"`\n}\n\n\n\ntype Stat struct {\n\tNodeUUID string `yaml:\"node_uuid\"`\n\n\tStatus string `yaml:\"status\"`\n\n\tMemTotalMB int `yaml:\"mem_total_mb\"`\n\n\tMemAvailableMB int `yaml:\"mem_available_mb\"`\n\n\tDiskTotalMB int `yaml:\"disk_total_mb\"`\n\n\tDiskAvailableMB int `yaml:\"disk_available_mb\"`\n\n\tLoad int `yaml:\"load\"`\n\n\tCpusOnline int `yaml:\"cpus_online\"`\n\n\tNodeHostName string `yaml:\"hostname\"`\n\n\tNetworks []NetworkStat\n\n\tInstances []InstanceStat\n}\n\nconst (\n\tComputeStatusPending = \"pending\"\n\n\tComputeStatusRunning = \"active\"\n\n\tComputeStatusStopped = \"exited\"\n)\n\nconst (\n\tPending = ComputeStatusPending\n\n\tRunning = ComputeStatusRunning\n\n\tStopping = \"stopping\"\n\n\tExited = ComputeStatusStopped\n\tExitFailed = \"exit_failed\"\n\tExitPaused = \"exit_paused\"\n\n\tDeleted = \"deleted\"\n\n\tHung = \"hung\"\n)\n\n\n\n\nfunc (s *Stat) Init() ", "output": "{\n\ts.NodeUUID = \"\"\n\ts.MemTotalMB = -1\n\ts.MemAvailableMB = -1\n\ts.DiskTotalMB = -1\n\ts.DiskAvailableMB = -1\n\ts.Load = -1\n\ts.CpusOnline = -1\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\tmessage := Message{\n\t\tText: os.Args[2],\n\t\tDuration: 15,\n\t}\n\tSendMessage(message, os.Args[1])\n\n}\n\nfunc SendMessage(message Message, URL string) {\n\tb := new(bytes.Buffer)\n\tjson.NewEncoder(b).Encode(message)\n\tresp, err := http.Post(URL, \"application/json\", b)\n\tfailOnError(err, \"Could not send http request.\")\n\tio.Copy(os.Stdout, resp.Body)\n}\n\n\n\ntype Message struct {\n\tText string `json:\"text\"`\n\tDuration float64 `json:\"duration\"`\n}\n\nfunc failOnError(err error, msg string) ", "output": "{\n\tif err != nil {\n\t\tlog.Fatalf(\"%s: %s\", msg, err)\n\t\tpanic(fmt.Sprintf(\"%s: %s\", msg, err))\n\t}\n}"} {"input": "package factory\n\nimport (\n\tcontext \"context\"\n\n\texternalversions \"knative.dev/eventing-kafka-broker/control-plane/pkg/client/informers/externalversions\"\n\tclient \"knative.dev/eventing-kafka-broker/control-plane/pkg/client/injection/client\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Default.RegisterInformerFactory(withInformerFactory)\n}\n\n\ntype Key struct{}\n\n\n\n\nfunc Get(ctx context.Context) externalversions.SharedInformerFactory {\n\tuntyped := ctx.Value(Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch knative.dev/eventing-kafka-broker/control-plane/pkg/client/informers/externalversions.SharedInformerFactory from context.\")\n\t}\n\treturn untyped.(externalversions.SharedInformerFactory)\n}\n\nfunc withInformerFactory(ctx context.Context) context.Context ", "output": "{\n\tc := client.Get(ctx)\n\topts := make([]externalversions.SharedInformerOption, 0, 1)\n\tif injection.HasNamespaceScope(ctx) {\n\t\topts = append(opts, externalversions.WithNamespace(injection.GetNamespaceScope(ctx)))\n\t}\n\treturn context.WithValue(ctx, Key{},\n\t\texternalversions.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...))\n}"} {"input": "package flags\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\ntype Traffic struct {\n\tRevisionsPercentages []string\n\tRevisionsTags []string\n\tUntagRevisions []string\n}\n\nfunc (t *Traffic) Add(cmd *cobra.Command) {\n\tcmd.Flags().StringSliceVar(&t.RevisionsPercentages,\n\t\t\"traffic\",\n\t\tnil,\n\t\t\"Set traffic distribution (format: --traffic revisionRef=percent) where revisionRef can be a revision or a tag or '@latest' string \"+\n\t\t\t\"representing latest ready revision. This flag can be given multiple times with percent summing up to 100%.\")\n\n\tcmd.Flags().StringSliceVar(&t.RevisionsTags,\n\t\t\"tag\",\n\t\tnil,\n\t\t\"Set tag (format: --tag revisionRef=tagName) where revisionRef can be a revision or '@latest' string representing latest ready revision. \"+\n\t\t\t\"This flag can be specified multiple times.\")\n\n\tcmd.Flags().StringSliceVar(&t.UntagRevisions,\n\t\t\"untag\",\n\t\tnil,\n\t\t\"Untag revision (format: --untag tagName). This flag can be specified multiple times.\")\n}\n\n\n\nfunc (t *Traffic) TagsChanged(cmd *cobra.Command) bool {\n\treturn cmd.Flags().Changed(\"tag\") || cmd.Flags().Changed(\"untag\")\n}\n\nfunc (t *Traffic) Changed(cmd *cobra.Command) bool {\n\treturn t.PercentagesChanged(cmd) || t.TagsChanged(cmd)\n}\n\nfunc (t *Traffic) PercentagesChanged(cmd *cobra.Command) bool ", "output": "{\n\treturn cmd.Flags().Changed(\"traffic\")\n}"} {"input": "package nats\n\nimport (\n\t\"github.com/apcera/nats\"\n\t\"github.com/plimble/kuja/broker\"\n)\n\ntype natsBroker struct {\n\turl string\n\tconn *nats.Conn\n}\n\nfunc NewBroker(url string) *natsBroker {\n\treturn &natsBroker{\n\t\turl: url,\n\t}\n}\n\nfunc (n *natsBroker) Connect() error {\n\tvar err error\n\tn.conn, err = nats.Connect(n.url)\n\n\treturn err\n}\n\nfunc (n *natsBroker) Close() {\n\tn.conn.Close()\n}\n\nfunc (n *natsBroker) Publish(topic string, msg *broker.Message) error {\n\tdata, err := msg.Marshal()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn n.conn.Publish(topic, data)\n}\n\n\n\nfunc (n *natsBroker) Subscribe(topic, queue, appId string, size int, h broker.Handler) ", "output": "{\n\tfor i := 0; i < size; i++ {\n\t\tn.conn.QueueSubscribe(topic, queue, func(msg *nats.Msg) {\n\t\t\tbrokerMsg := &broker.Message{}\n\t\t\tbrokerMsg.Unmarshal(msg.Data)\n\t\t\tretryCount, err := h(msg.Subject, brokerMsg)\n\t\t\tif err != nil {\n\t\t\t\tfor i := 0; i < retryCount; i++ {\n\t\t\t\t\tbrokerMsg.Retry++\n\t\t\t\t\t_, err := h(topic, brokerMsg)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}"} {"input": "package fenwick\n\n\n\ntype Fenwick struct {\n\ttree []int\n}\n\n\nfunc NewFenwick(n int) *Fenwick {\n\tfen := &Fenwick{\n\t\ttree: make([]int, n),\n\t}\n\tfor i := range fen.tree {\n\t\tfen.tree[i] = 1\n\t}\n\treturn fen\n}\n\n\nfunc (fen *Fenwick) Sum(index int) int {\n\tsum := 1\n\tindex++\n\tfor index > 0 {\n\t\tsum *= fen.tree[index-1]\n\t\tindex -= lsb(index)\n\t}\n\treturn sum\n}\n\n\n\n\n\nfunc (fen *Fenwick) Update(index, value int) {\n\tindex++\n\tfor index <= fen.Size() {\n\t\tfen.tree[index-1] *= value\n\t\tindex += lsb(index)\n\t}\n}\n\n\nfunc (fen *Fenwick) Size() int {\n\treturn len(fen.tree)\n}\n\nfunc lsb(x int) int ", "output": "{\n\treturn x & -x\n}"} {"input": "package mailgun\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/getfider/fider/app/models/dto\"\n\t\"github.com/getfider/fider/app/pkg/bus\"\n\t\"github.com/getfider/fider/app/pkg/env\"\n\t\"github.com/getfider/fider/app/pkg/log\"\n)\n\n\n\n\nvar baseURLs = map[string]string{\n\t\"US\": \"https://api.mailgun.net/v3/%s\",\n\t\"EU\": \"https://api.eu.mailgun.net/v3/%s\",\n}\n\nfunc init() {\n\tbus.Register(Service{})\n}\n\ntype Service struct{}\n\nfunc (s Service) Name() string {\n\treturn \"Mailgun\"\n}\n\nfunc (s Service) Category() string {\n\treturn \"email\"\n}\n\nfunc (s Service) Enabled() bool {\n\treturn env.Config.Email.Type == \"mailgun\"\n}\n\n\n\n\n\nfunc getEndpoint(ctx context.Context, domain, path string) string {\n\tvar regionCode = env.Config.Email.Mailgun.Region\n\tregionCode = strings.ToUpper(regionCode)\n\n\tif len(regionCode) < 1 {\n\t\tregionCode = \"US\"\n\t} else if len(baseURLs[regionCode]) < 1 {\n\t\tlog.Warnf(ctx,\n\t\t\t\"Unknown Mailgun region code '@{Code}' configured - falling back to 'US'\",\n\t\t\tdto.Props{\n\t\t\t\t\"Code\": env.Config.Email.Mailgun.Region,\n\t\t\t},\n\t\t)\n\n\t\tregionCode = \"US\"\n\t}\n\n\treturn fmt.Sprintf(baseURLs[regionCode], domain) + path\n}\n\nfunc (s Service) Init() ", "output": "{\n\tbus.AddListener(sendMail)\n\tbus.AddHandler(fetchRecentSupressions)\n}"} {"input": "package ansi\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/blevesearch/bleve/registry\"\n\t\"github.com/blevesearch/bleve/search/highlight\"\n\tansiFormatter \"github.com/blevesearch/bleve/search/highlight/format/ansi\"\n\tsimpleFragmenter \"github.com/blevesearch/bleve/search/highlight/fragmenter/simple\"\n\tsimpleHighlighter \"github.com/blevesearch/bleve/search/highlight/highlighter/simple\"\n)\n\nconst Name = \"ansi\"\n\nfunc Constructor(config map[string]interface{}, cache *registry.Cache) (highlight.Highlighter, error) {\n\n\tfragmenter, err := cache.FragmenterNamed(simpleFragmenter.Name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error building fragmenter: %v\", err)\n\t}\n\n\tformatter, err := cache.FragmentFormatterNamed(ansiFormatter.Name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error building fragment formatter: %v\", err)\n\t}\n\n\treturn simpleHighlighter.NewHighlighter(\n\t\t\tfragmenter,\n\t\t\tformatter,\n\t\t\tsimpleHighlighter.DefaultSeparator),\n\t\tnil\n}\n\n\n\nfunc init() ", "output": "{\n\tregistry.RegisterHighlighter(Name, Constructor)\n}"} {"input": "package metrics\n\n\n\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\tgolangswaggerpaths \"path\"\n)\n\n\ntype GetMetricsURL struct {\n\t_basePath string\n}\n\n\n\n\nfunc (o *GetMetricsURL) WithBasePath(bp string) *GetMetricsURL {\n\to.SetBasePath(bp)\n\treturn o\n}\n\n\n\n\nfunc (o *GetMetricsURL) SetBasePath(bp string) {\n\to._basePath = bp\n}\n\n\nfunc (o *GetMetricsURL) Build() (*url.URL, error) {\n\tvar result url.URL\n\n\tvar _path = \"/metrics/\"\n\n\t_basePath := o._basePath\n\tif _basePath == \"\" {\n\t\t_basePath = \"/v1\"\n\t}\n\tresult.Path = golangswaggerpaths.Join(_basePath, _path)\n\n\treturn &result, nil\n}\n\n\nfunc (o *GetMetricsURL) Must(u *url.URL, err error) *url.URL {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif u == nil {\n\t\tpanic(\"url can't be nil\")\n\t}\n\treturn u\n}\n\n\nfunc (o *GetMetricsURL) String() string {\n\treturn o.Must(o.Build()).String()\n}\n\n\nfunc (o *GetMetricsURL) BuildFull(scheme, host string) (*url.URL, error) {\n\tif scheme == \"\" {\n\t\treturn nil, errors.New(\"scheme is required for a full url on GetMetricsURL\")\n\t}\n\tif host == \"\" {\n\t\treturn nil, errors.New(\"host is required for a full url on GetMetricsURL\")\n\t}\n\n\tbase, err := o.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbase.Scheme = scheme\n\tbase.Host = host\n\treturn base, nil\n}\n\n\n\n\nfunc (o *GetMetricsURL) StringFull(scheme, host string) string ", "output": "{\n\treturn o.Must(o.BuildFull(scheme, host)).String()\n}"} {"input": "package main\n\nimport (\n\t\"html/template\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype Page struct {\n\tTitle string\n\tBody []byte\n}\n\nfunc (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}\n\n\n\nfunc editHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/edit/\"):]\n\tp, err := loadPage(title)\n\tif err != nil {\n\t\tp = &Page{Title: title}\n\t}\n\trenderTemplate(w, \"edit\", p)\n}\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/view/\"):]\n\tp, _ := loadPage(title)\n\trenderTemplate(w, \"view\", p)\n}\n\nfunc saveHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/save/\"):]\n\tbody := r.FormValue(\"body\")\n\tp := &Page{Title: title, Body: []byte(body)}\n\tp.save()\n\thttp.Redirect(w, r, \"/view/\"+title, http.StatusFound)\n}\n\nfunc renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {\n\tt, _ := template.ParseFiles(tmpl + \".html\")\n\tt.Execute(w, p)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/view/\", viewHandler)\n\thttp.HandleFunc(\"/edit/\", editHandler)\n\thttp.HandleFunc(\"/save/\", saveHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc loadPage(title string) (*Page, error) ", "output": "{\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Page{Title: title, Body: body}, nil\n}"} {"input": "package proxy\n\nimport (\n\t\"github.com/fatedier/frp/models/config\"\n)\n\ntype StcpProxy struct {\n\t*BaseProxy\n\tcfg *config.StcpProxyConf\n}\n\n\n\nfunc (pxy *StcpProxy) GetConf() config.ProxyConf {\n\treturn pxy.cfg\n}\n\nfunc (pxy *StcpProxy) Close() {\n\tpxy.BaseProxy.Close()\n\tpxy.rc.VisitorManager.CloseListener(pxy.GetName())\n}\n\nfunc (pxy *StcpProxy) Run() (remoteAddr string, err error) ", "output": "{\n\tlistener, errRet := pxy.rc.VisitorManager.Listen(pxy.GetName(), pxy.cfg.Sk)\n\tif errRet != nil {\n\t\terr = errRet\n\t\treturn\n\t}\n\tlistener.AddLogPrefix(pxy.name)\n\tpxy.listeners = append(pxy.listeners, listener)\n\tpxy.Info(\"stcp proxy custom listen success\")\n\n\tpxy.startListenHandler(pxy, HandleUserTcpConnection)\n\treturn\n}"} {"input": "package dynamo\n\nimport (\n\t\"errors\"\n\n\t\"golang.org/x/crypto/acme/autocert\"\n)\n\n\ntype Provider struct {\n\tclient *client\n}\n\n\nfunc NewProvider() *Provider {\n\treturn new(Provider)\n}\n\n\nfunc (p *Provider) Name() string {\n\treturn \"dynamodb\"\n}\n\n\n\n\n\nfunc (p *Provider) GetSecret(secretName string) (string, bool) {\n\tif p.client != nil {\n\t\tif value, err := p.client.Get(secretName); err == nil {\n\t\t\treturn value, true\n\t\t}\n\t}\n\n\treturn \"\", false\n}\n\n\nfunc (p *Provider) GetCache() (autocert.Cache, bool) {\n\tif p.client != nil {\n\t\treturn newCache(p.client), true\n\t}\n\n\treturn nil, false\n}\n\n\nfunc get(config map[string]interface{}, key, defaultValue string) string {\n\tif v, ok := config[key]; ok {\n\t\tif s, ok := v.(string); ok {\n\t\t\treturn s\n\t\t}\n\t}\n\treturn defaultValue\n}\n\nfunc (p *Provider) Configure(config map[string]interface{}) (err error) ", "output": "{\n\tconst prefix = \"unable to configure DynamoDB provider\"\n\tif config == nil {\n\t\treturn errors.New(prefix + \", no configuration provided\")\n\t}\n\n\tregion := get(config, \"region\", \"\")\n\tif region == \"\" {\n\t\treturn errors.New(prefix + \", no AWS Region was specified\")\n\t}\n\n\ttable := get(config, \"table\", \"\")\n\tif table == \"\" {\n\t\treturn errors.New(prefix + \", no Table Name was specified\")\n\t}\n\n\tkeyColumn := get(config, \"keyColumn\", \"key\")\n\tvalColumn := get(config, \"valueColumn\", \"value\")\n\n\tif p.client, err = newClient(region, table, keyColumn, valColumn); err == nil {\n\t\tif _, err := p.client.Get(\"testkey\"); err == nil && err == errKeyNotFound {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn err\n}"} {"input": "package writers\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n)\n\nfunc jsonReadersDataForHttpTest() []byte {\n\tjsonData := `{\n \"Data\": {\n \"LoadAvg15m\": 1.59375,\n \"LoadAvg1m\": 1.5537109375,\n \"LoadAvg5m\": 1.68798828125\n },\n \"GoStruct\": \"LoadAvg\",\n \"Host\": {\n \"Name\":\"MacBook-Pro.local\",\n \"Tags\":[]\n },\n \"Interval\": \"1s\",\n \"Path\": \"/load-avg\",\n \"Tags\": [ ],\n \"UnixNano\": 1420607791403576000\n}`\n\treturn []byte(jsonData)\n}\n\nfunc newWriterForHttpTest() *Http {\n\th := &Http{}\n\n\treadersData := make(map[string][]byte)\n\treadersData[\"/load-avg\"] = jsonReadersDataForHttpTest()\n\n\th.SetReadersDataInBytes(readersData)\n\n\treturn h\n}\n\nfunc TestHeadersAsMap(t *testing.T) {\n\th := newWriterForHttpTest()\n\th.Headers = \"X-Key=test\"\n\n\tasMap := h.headersAsMap()\n\tif asMap[\"X-Key\"] != \"test\" {\n\t\tt.Error(\"headersAsMap did the wrong thing.\")\n\t}\n}\n\nfunc TestNewHttpSetReadersDataInBytes(t *testing.T) {\n\th := newWriterForHttpTest()\n\n\tkey := \"/load-avg\"\n\t_, ok := h.GetReadersData()[key]\n\tif !ok {\n\t\tt.Errorf(\"Key does not exist. Key: %v, Data: %v\", key, h.GetReadersData())\n\t}\n}\n\n\n\nfunc TestNewHttpRequest(t *testing.T) ", "output": "{\n\th := newWriterForHttpTest()\n\th.Url = \"http://example.com/\"\n\th.Method = \"POST\"\n\n\treadersData := h.GetReadersData()\n\tdataJson, err := json.Marshal(readersData)\n\n\tif err != nil {\n\t\tt.Errorf(\"Failed to generate readers data. Error: %v\", err)\n\t}\n\n\t_, err = h.NewHttpRequest(dataJson)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create Request struct. Error: %v\", err)\n\t}\n}"} {"input": "package service\n\nimport (\n\t\"bytes\"\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"errors\"\n\t\"io\"\n)\n\nfunc pad(src []byte) []byte {\n\tpadding := aes.BlockSize - len(src)%aes.BlockSize\n\tpadText := bytes.Repeat([]byte{byte(padding)}, padding)\n\treturn append(src, padText...)\n}\n\nfunc unpad(src []byte) ([]byte, error) {\n\tlength := len(src)\n\tunpadding := int(src[length-1])\n\n\tif unpadding > length {\n\t\treturn nil, errors.New(\"unpad error. This could happen when incorrect encryption key is used\")\n\t}\n\n\treturn src[:(length - unpadding)], nil\n}\n\n\n\nfunc (s *Service) decrypt(text string) (string, error) {\n\tdecodedMsg, err := base64.URLEncoding.DecodeString(text)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif (len(decodedMsg) % aes.BlockSize) != 0 {\n\t\treturn \"\", errors.New(\"blocksize must be multipe of decoded message length\")\n\t}\n\n\tiv := decodedMsg[:aes.BlockSize]\n\tmsg := decodedMsg[aes.BlockSize:]\n\n\tcfb := cipher.NewCFBDecrypter(s.AESBlock, iv)\n\tcfb.XORKeyStream(msg, msg)\n\n\tunpadMsg, err := unpad(msg)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(unpadMsg), nil\n}\n\nfunc (s *Service) encrypt(text string) (string, error) ", "output": "{\n\tmsg := pad([]byte(text))\n\tcipherText := make([]byte, aes.BlockSize+len(msg))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcfb := cipher.NewCFBEncrypter(s.AESBlock, iv)\n\tcfb.XORKeyStream(cipherText[aes.BlockSize:], []byte(msg))\n\tfinalMsg := base64.URLEncoding.EncodeToString(cipherText)\n\treturn finalMsg, nil\n}"} {"input": "package downloader\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/WhaleCoinOrg/WhaleCoin/core/types\"\n)\n\n\ntype peerDropFn func(id string)\n\n\ntype dataPack interface {\n\tPeerId() string\n\tItems() int\n\tStats() string\n}\n\n\ntype headerPack struct {\n\tpeerId string\n\theaders []*types.Header\n}\n\nfunc (p *headerPack) PeerId() string { return p.peerId }\nfunc (p *headerPack) Items() int { return len(p.headers) }\nfunc (p *headerPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.headers)) }\n\n\ntype bodyPack struct {\n\tpeerId string\n\ttransactions [][]*types.Transaction\n\tuncles [][]*types.Header\n}\n\nfunc (p *bodyPack) PeerId() string { return p.peerId }\nfunc (p *bodyPack) Items() int {\n\tif len(p.transactions) <= len(p.uncles) {\n\t\treturn len(p.transactions)\n\t}\n\treturn len(p.uncles)\n}\nfunc (p *bodyPack) Stats() string { return fmt.Sprintf(\"%d:%d\", len(p.transactions), len(p.uncles)) }\n\n\ntype receiptPack struct {\n\tpeerId string\n\treceipts [][]*types.Receipt\n}\n\nfunc (p *receiptPack) PeerId() string { return p.peerId }\nfunc (p *receiptPack) Items() int { return len(p.receipts) }\nfunc (p *receiptPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.receipts)) }\n\n\ntype statePack struct {\n\tpeerId string\n\tstates [][]byte\n}\n\nfunc (p *statePack) PeerId() string { return p.peerId }\n\nfunc (p *statePack) Stats() string { return fmt.Sprintf(\"%d\", len(p.states)) }\n\nfunc (p *statePack) Items() int ", "output": "{ return len(p.states) }"} {"input": "package govpn\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"net\"\n\t\"time\"\n)\n\nconst (\n\tRWTimeout = 10 * time.Second\n)\n\ntype KnownPeers map[string]**Peer\n\n\n\n\n\n\n\n\n\nfunc StatsProcessor(statsPort net.Listener, peers *KnownPeers) ", "output": "{\n\tvar conn net.Conn\n\tvar err error\n\tvar data []byte\n\tbuf := make([]byte, 2<<8)\n\tfor {\n\t\tconn, err = statsPort.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error during accepting connection\", err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tconn.SetDeadline(time.Now().Add(RWTimeout))\n\t\tconn.Read(buf)\n\t\tconn.Write([]byte(\"HTTP/1.0 200 OK\\r\\nContent-Type: application/json\\r\\n\\r\\n\"))\n\t\tvar peersList []*Peer\n\t\tfor _, peer := range *peers {\n\t\t\tpeersList = append(peersList, *peer)\n\t\t}\n\t\tdata, err = json.Marshal(peersList)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tconn.Write(data)\n\t\tconn.Close()\n\t}\n}"} {"input": "package importx\n\nimport (\n\t\"encoding/json\"\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"github.com/vmware/govmomi/ovf\"\n\t\"github.com/vmware/govmomi/vim25/types\"\n)\n\ntype Property struct {\n\ttypes.KeyValue\n\tSpec ovf.Property\n}\n\ntype Options struct {\n\tAllDeploymentOptions []string\n\tDeployment string\n\n\tAllDiskProvisioningOptions []string\n\tDiskProvisioning string\n\n\tAllIPAllocationPolicyOptions []string\n\tIPAllocationPolicy string\n\n\tAllIPProtocolOptions []string\n\tIPProtocol string\n\n\tPropertyMapping []Property\n\n\tPowerOn bool\n\tInjectOvfEnv bool\n\tWaitForIP bool\n}\n\ntype OptionsFlag struct {\n\tOptions Options\n\n\tpath string\n}\n\n\n\nfunc (flag *OptionsFlag) Process() error {\n\tif len(flag.path) > 0 {\n\t\tf, err := os.Open(flag.path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\n\t\to, err := ioutil.ReadAll(f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := json.Unmarshal(o, &flag.Options); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (flag *OptionsFlag) Register(f *flag.FlagSet) ", "output": "{\n\tf.StringVar(&flag.path, \"options\", \"\", \"Options spec file path for VM deployment\")\n}"} {"input": "package apimachinery\n\nimport \"github.com/onsi/ginkgo\"\n\n\n\nfunc SIGDescribe(text string, body func()) bool ", "output": "{\n\treturn ginkgo.Describe(\"[sig-api-machinery] \"+text, body)\n}"} {"input": "package fs\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nvar execExts map[string]bool\n\nfunc init() {\n\tpathext := filepath.SplitList(os.Getenv(\"PATHEXT\"))\n\texecExts = make(map[string]bool, len(pathext))\n\tfor _, ext := range pathext {\n\t\texecExts[strings.ToLower(ext)] = true\n\t}\n}\n\n\n\nfunc isWindowsExecutable(path string) bool {\n\treturn execExts[strings.ToLower(filepath.Ext(path))]\n}\n\nfunc (e basicFileInfo) Mode() FileMode {\n\tm := e.FileInfo.Mode()\n\tif m&os.ModeSymlink != 0 && e.Size() > 0 {\n\t\tm &^= os.ModeSymlink\n\t}\n\tif isWindowsExecutable(e.Name()) {\n\t\tm |= 0111\n\t}\n\tm &^= 0022\n\treturn FileMode(m)\n}\n\nfunc (e basicFileInfo) Owner() int {\n\treturn -1\n}\n\n\n\n\n\nfunc (e *basicFileInfo) osFileInfo() os.FileInfo {\n\tfi := e.FileInfo\n\tif fi, ok := fi.(*dirJunctFileInfo); ok {\n\t\treturn fi.FileInfo\n\t}\n\treturn fi\n}\n\nfunc (e basicFileInfo) Group() int ", "output": "{\n\treturn -1\n}"} {"input": "package x\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/pkg/errors\"\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/ory/x/logrusx\"\n)\n\ntype errStackTracer struct{}\n\nfunc (s *errStackTracer) StackTrace() errors.StackTrace {\n\treturn errors.StackTrace{}\n}\n\nfunc (s *errStackTracer) Error() string {\n\treturn \"foo\"\n}\n\n\n\nfunc TestLogErrorDoesNotPanic(t *testing.T) {\n\tr, err := http.NewRequest(http.MethodGet, \"https://hydra/some/endpoint\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tLogError(r, errors.New(\"asdf\"), nil)\n}\n\nfunc TestLogError(t *testing.T) ", "output": "{\n\tr, err := http.NewRequest(http.MethodGet, \"https://hydra/some/endpoint\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tbuf := bytes.NewBuffer([]byte{})\n\tl := logrusx.New(\"\", \"\", logrusx.ForceLevel(logrus.TraceLevel))\n\tl.Logger.Out = buf\n\tLogError(r, errors.New(\"asdf\"), l)\n\n\tt.Logf(\"%s\", string(buf.Bytes()))\n\n\tassert.True(t, strings.Contains(string(buf.Bytes()), \"trace\"))\n\n\tLogError(r, errors.Wrap(new(errStackTracer), \"\"), l)\n}"} {"input": "package container\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/martin-helmich/distcrond/domain\"\n)\n\ntype JobContainer struct {\n\tjobs []domain.Job\n\tjobsByName map[string]*domain.Job\n}\n\nfunc NewJobContainer(initialCapacity int) *JobContainer {\n\tcontainer := new(JobContainer)\n\tcontainer.jobs = make([]domain.Job, 0, initialCapacity)\n\tcontainer.jobsByName = make(map[string]*domain.Job)\n\treturn container\n}\n\nfunc (c *JobContainer) AddJob(job domain.Job) {\n\tc.jobs = append(c.jobs, job)\n\tc.jobsByName[job.Name] = &c.jobs[len(c.jobs)-1]\n}\n\nfunc (c *JobContainer) Count() int {\n\treturn len(c.jobs)\n}\n\nfunc (c *JobContainer) All() []domain.Job {\n\treturn c.jobs\n}\n\nfunc (c *JobContainer) Get(i int) *domain.Job {\n\treturn &c.jobs[i]\n}\n\n\n\nfunc (c *JobContainer) JobByName(n string) (*domain.Job, error) ", "output": "{\n\tif job, ok := c.jobsByName[n]; !ok {\n\t\treturn nil, errors.New(fmt.Sprintf(\"No job with name '%s' is known\", n))\n\t} else {\n\t\treturn job, nil\n\t}\n}"} {"input": "package machine\n\nimport (\n\t\"github.com/juju/cmd\"\n\n\tjujucmd \"github.com/juju/juju/cmd\"\n\t\"github.com/juju/juju/cmd/modelcmd\"\n)\n\nconst showMachineCommandDoc = `\nShow a specified machine on a model. Default format is in yaml,\nother formats can be specified with the \"--format\" option.\nAvailable formats are yaml, tabular, and json\n\nExamples:\n juju show-machine 0\n juju show-machine 1 2 3\n\n`\n\n\n\n\nfunc newShowMachineCommand(api statusAPI) *showMachineCommand {\n\tshowCmd := &showMachineCommand{}\n\tshowCmd.defaultFormat = \"yaml\"\n\tshowCmd.api = api\n\treturn showCmd\n}\n\n\ntype showMachineCommand struct {\n\tbaselistMachinesCommand\n}\n\n\nfunc (c *showMachineCommand) Info() *cmd.Info {\n\treturn jujucmd.Info(&cmd.Info{\n\t\tName: \"show-machine\",\n\t\tArgs: \" ...\",\n\t\tPurpose: \"Show a machine's status.\",\n\t\tDoc: showMachineCommandDoc,\n\t})\n}\n\n\nfunc (c *showMachineCommand) Init(args []string) error {\n\tc.machineIds = args\n\treturn nil\n}\n\nfunc NewShowMachineCommand() cmd.Command ", "output": "{\n\treturn modelcmd.Wrap(newShowMachineCommand(nil))\n}"} {"input": "package log\n\nimport (\n\t\"testing\"\n)\n\ntype testLogger struct {\n\tkeyvals []interface{}\n}\n\nfunc (tl *testLogger) Log(keyvals ...interface{}) error {\n\ttl.keyvals = keyvals\n\treturn nil\n}\n\ntype testSink struct {\n\tkeyvals []interface{}\n}\n\nfunc (ts *testSink) Receive(keyvals ...interface{}) error {\n\tts.keyvals = keyvals\n\treturn nil\n}\n\nfunc TestLogger_Log(t *testing.T) {\n\ttl := &testLogger{}\n\tl := NewLogger(tl, nil)\n\n\tl.Log(\"message\", \"value\")\n\tif len(tl.keyvals) != 2 {\n\t\tt.Errorf(\"Expected log message with 2 values, got %v\", len(tl.keyvals))\n\t}\n\n\tm1 := tl.keyvals[0]\n\tm2 := tl.keyvals[1]\n\tif m1.(string) != \"message\" || m2.(string) != \"value\" {\n\t\tt.Errorf(\"Expected [message, value] but got %s\", tl.keyvals)\n\t}\n}\n\n\n\nfunc TestLogger_Event(t *testing.T) ", "output": "{\n\tts := &testSink{}\n\ttl := &testLogger{}\n\tl := NewLogger(tl, []EventSink{ts})\n\n\tl.Event(\"important_event\", \"act_on_me\")\n\tif len(ts.keyvals) != 2 {\n\t\tt.Errorf(\"Expected to recieve event with 2 values, got %v\", len(ts.keyvals))\n\t}\n\n\tm1 := ts.keyvals[0]\n\tm2 := ts.keyvals[1]\n\tif m1.(string) != \"important_event\" || m2.(string) != \"act_on_me\" {\n\t\tt.Errorf(\"Expected [important_event, act_on_me] but got %s\", ts.keyvals)\n\t}\n}"} {"input": "package store\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/ngaut/log\"\n\t\"github.com/reborndb/qdb/pkg/engine/rocksdb\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc TestT(t *testing.T) {\n\tTestingT(t)\n}\n\nvar _ = Suite(&testStoreSuite{})\n\ntype testStoreSuite struct {\n\ts *Store\n}\n\nfunc (s *testStoreSuite) SetUpSuite(c *C) {\n\ts.s = testCreateStore(c)\n}\n\nfunc (s *testStoreSuite) TearDownSuite(c *C) {\n\tif s.s != nil {\n\t\ts.s.Close()\n\t\ts = nil\n\t}\n}\n\nfunc (s *testStoreSuite) checkCompact(c *C) {\n\terr := s.s.CompactAll()\n\tc.Assert(err, IsNil)\n}\n\nfunc (s *testStoreSuite) checkEmpty(c *C) {\n\tit := s.s.getIterator()\n\tdefer s.s.putIterator(it)\n\n\tit.SeekToFirst()\n\tc.Assert(it.Error(), IsNil)\n\tc.Assert(it.Valid(), Equals, false)\n}\n\n\n\nfunc init() {\n\tlog.SetLevel(log.LOG_LEVEL_ERROR)\n}\n\nfunc sleepms(n int) {\n\ttime.Sleep(time.Millisecond * time.Duration(n))\n}\n\nfunc testCreateStore(c *C) *Store ", "output": "{\n\tbase := fmt.Sprintf(\"/tmp/test_qdb/test_store\")\n\terr := os.RemoveAll(base)\n\tc.Assert(err, IsNil)\n\n\terr = os.MkdirAll(base, 0700)\n\tc.Assert(err, IsNil)\n\n\tconf := rocksdb.NewDefaultConfig()\n\ttestdb, err := rocksdb.Open(path.Join(base, \"db\"), conf, false)\n\tc.Assert(err, IsNil)\n\n\ts := New(testdb)\n\treturn s\n}"} {"input": "package vm\n\nimport (\n\t\"github.com/expanse-org/go-expanse/common\"\n\t\"github.com/expanse-org/go-expanse/common/math\"\n\t\"github.com/holiman/uint256\"\n)\n\n\n\nfunc calcMemSize64(off, l *uint256.Int) (uint64, bool) {\n\tif !l.IsUint64() {\n\t\treturn 0, true\n\t}\n\treturn calcMemSize64WithUint(off, l.Uint64())\n}\n\n\n\n\n\n\n\n\nfunc getData(data []byte, start uint64, size uint64) []byte {\n\tlength := uint64(len(data))\n\tif start > length {\n\t\tstart = length\n\t}\n\tend := start + size\n\tif end > length {\n\t\tend = length\n\t}\n\treturn common.RightPadBytes(data[start:end], int(size))\n}\n\n\nfunc toWordSize(size uint64) uint64 {\n\tif size > math.MaxUint64-31 {\n\t\treturn math.MaxUint64/32 + 1\n\t}\n\n\treturn (size + 31) / 32\n}\n\nfunc allZero(b []byte) bool {\n\tfor _, byte := range b {\n\t\tif byte != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc calcMemSize64WithUint(off *uint256.Int, length64 uint64) (uint64, bool) ", "output": "{\n\tif length64 == 0 {\n\t\treturn 0, false\n\t}\n\toffset64, overflow := off.Uint64WithOverflow()\n\tif overflow {\n\t\treturn 0, true\n\t}\n\tval := offset64 + length64\n\treturn val, val < offset64\n}"} {"input": "package fever\n\nimport (\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/pkg/errors\"\n\t\"github.com/urandom/readeef/content\"\n\t\"github.com/urandom/readeef/content/repo\"\n\t\"github.com/urandom/readeef/log\"\n\t\"github.com/urandom/readeef/pool\"\n)\n\n\n\nfunc savedItemIDs(\n\tr *http.Request,\n\tresp resp,\n\tuser content.User,\n\tservice repo.Service,\n\tlog log.Log,\n) error {\n\tlog.Infoln(\"Fetching saved fever item ids\")\n\n\tids, err := service.ArticleRepo().IDs(user,\n\t\tcontent.FavoriteOnly, content.Filters(content.GetUserFilters(user)))\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"getting unread ids\")\n\t}\n\n\tbuf := pool.Buffer.Get()\n\tdefer pool.Buffer.Put(buf)\n\n\tfor i := range ids {\n\t\tif i != 0 {\n\t\t\tbuf.WriteString(\",\")\n\t\t}\n\n\t\tbuf.WriteString(strconv.FormatInt(int64(ids[i]), 10))\n\t}\n\n\tresp[\"saved_item_ids\"] = buf.String()\n\n\treturn nil\n}\n\nfunc init() {\n\tactions[\"unread_item_ids\"] = unreadItemIDs\n\tactions[\"saved_item_ids\"] = savedItemIDs\n}\n\nfunc unreadItemIDs(\n\tr *http.Request,\n\tresp resp,\n\tuser content.User,\n\tservice repo.Service,\n\tlog log.Log,\n) error ", "output": "{\n\tlog.Infoln(\"Fetching unread fever item ids\")\n\n\tids, err := service.ArticleRepo().IDs(user,\n\t\tcontent.UnreadOnly, content.Filters(content.GetUserFilters(user)))\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"getting unread ids\")\n\t}\n\n\tbuf := pool.Buffer.Get()\n\tdefer pool.Buffer.Put(buf)\n\n\tfor i := range ids {\n\t\tif i != 0 {\n\t\t\tbuf.WriteString(\",\")\n\t\t}\n\n\t\tbuf.WriteString(strconv.FormatInt(int64(ids[i]), 10))\n\t}\n\n\tresp[\"unread_item_ids\"] = buf.String()\n\n\treturn nil\n}"} {"input": "package description\n\nimport (\n\t\"github.com/dropbox/goprotoc/gogoproto\"\n\t\"github.com/dropbox/goprotoc/plugin/testgen\"\n\t\"github.com/dropbox/goprotoc/protoc-gen-dgo/generator\"\n)\n\ntype test struct {\n\t*generator.Generator\n}\n\nfunc NewTest(g *generator.Generator) testgen.TestPlugin {\n\treturn &test{g}\n}\n\n\n\nfunc init() {\n\ttestgen.RegisterTestPlugin(NewTest)\n}\n\nfunc (p *test) Generate(imports generator.PluginImports, file *generator.FileDescriptor) bool ", "output": "{\n\tused := false\n\ttestingPkg := imports.NewImport(\"testing\")\n\tfor _, message := range file.Messages() {\n\t\tif !gogoproto.HasDescription(file.FileDescriptorProto, message.DescriptorProto) ||\n\t\t\t!gogoproto.HasTestGen(file.FileDescriptorProto, message.DescriptorProto) {\n\t\t\tcontinue\n\t\t}\n\t\tused = true\n\t}\n\n\tif used {\n\t\tlocalName := generator.FileName(file)\n\t\tp.P(`func Test`, localName, `Description(t *`, testingPkg.Use(), `.T) {`)\n\t\tp.In()\n\t\tp.P(localName, `Description()`)\n\t\tp.Out()\n\t\tp.P(`}`)\n\n\t}\n\treturn used\n}"} {"input": "package inmem\n\nimport (\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\ntype Reader struct {\n\tstore *Store\n}\n\nfunc newReader(store *Store) (*Reader, error) {\n\treturn &Reader{\n\t\tstore: store,\n\t}, nil\n}\n\nfunc (r *Reader) BytesSafeAfterClose() bool {\n\treturn false\n}\n\nfunc (r *Reader) Get(key []byte) ([]byte, error) {\n\treturn r.store.get(key)\n}\n\n\n\nfunc (r *Reader) Close() error {\n\treturn nil\n}\n\nfunc (r *Reader) Iterator(key []byte) store.KVIterator ", "output": "{\n\treturn r.store.iterator(key)\n}"} {"input": "package mockhttputil\n\nimport (\n\tgomock \"github.com/golang/mock/gomock\"\n\thttp \"net/http\"\n\treflect \"reflect\"\n)\n\n\ntype MockRoundTripper struct {\n\tctrl *gomock.Controller\n\trecorder *MockRoundTripperMockRecorder\n}\n\n\ntype MockRoundTripperMockRecorder struct {\n\tmock *MockRoundTripper\n}\n\n\n\n\n\nfunc (m *MockRoundTripper) EXPECT() *MockRoundTripperMockRecorder {\n\treturn m.recorder\n}\n\n\nfunc (m *MockRoundTripper) RoundTrip(arg0 *http.Request) (*http.Response, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RoundTrip\", arg0)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}\n\n\nfunc (mr *MockRoundTripperMockRecorder) RoundTrip(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"RoundTrip\", reflect.TypeOf((*MockRoundTripper)(nil).RoundTrip), arg0)\n}\n\nfunc NewMockRoundTripper(ctrl *gomock.Controller) *MockRoundTripper ", "output": "{\n\tmock := &MockRoundTripper{ctrl: ctrl}\n\tmock.recorder = &MockRoundTripperMockRecorder{mock}\n\treturn mock\n}"} {"input": "package gochimp\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype APIError struct {\n\tStatus string `json:\"status\"`\n\tCode int `json:\"code\"`\n\tName string `json:\"name\"`\n\tErr string `json:\"error\"`\n}\n\nfunc (e APIError) Error() string {\n\treturn fmt.Sprintf(\"%v: %v\", e.Code, e.Err)\n}\n\n\n\n\ntype APITime struct {\n\ttime.Time\n}\n\nfunc (t *APITime) UnmarshalJSON(data []byte) (err error) {\n\ts := string(data)\n\tl := len(s)\n\tswitch {\n\tcase l == 12:\n\t\tt.Time, err = time.Parse(`\"2006-01-02\"`, s)\n\tcase l == 21:\n\t\tt.Time, err = time.Parse(`\"2006-01-02 15:04:05\"`, s)\n\tcase l == 27:\n\t\tt.Time, err = time.Parse(`\"2006-01-02 15:04:05.00000\"`, s)\n\tcase l == 9:\n\t\tt.Time, err = time.Parse(`\"2006-01\"`, s)\n\t}\n\treturn\n}\n\n\nconst APITimeFormat = \"2006-01-02 15:04:05\"\n\nfunc apiTime(t interface{}) interface{} {\n\tswitch ti := t.(type) {\n\tcase time.Time:\n\t\treturn ti.Format(APITimeFormat)\n\tcase string:\n\t\treturn ti\n\t}\n\treturn t\n}\n\nfunc chimpErrorCheck(body []byte) error ", "output": "{\n\tvar e APIError\n\tjson.Unmarshal(body, &e)\n\tif e.Err != \"\" || e.Code != 0 {\n\t\treturn e\n\t}\n\treturn nil\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1alpha1 \"k8s.io/kops/pkg/client/clientset_generated/clientset/typed/kops/v1alpha1\"\n)\n\ntype FakeKopsV1alpha1 struct {\n\t*testing.Fake\n}\n\n\n\nfunc (c *FakeKopsV1alpha1) Federations(namespace string) v1alpha1.FederationInterface {\n\treturn &FakeFederations{c, namespace}\n}\n\nfunc (c *FakeKopsV1alpha1) InstanceGroups(namespace string) v1alpha1.InstanceGroupInterface {\n\treturn &FakeInstanceGroups{c, namespace}\n}\n\n\n\nfunc (c *FakeKopsV1alpha1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeKopsV1alpha1) Clusters(namespace string) v1alpha1.ClusterInterface ", "output": "{\n\treturn &FakeClusters{c, namespace}\n}"} {"input": "package controllers\n\nimport (\n\t\"encoding/json\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/astaxie/beego\"\n\t\"github.com/bobliu0909/humpback-agent/config\"\n\t\"github.com/bobliu0909/humpback-agent/models\"\n\t\"github.com/docker/docker/client\"\n)\n\n\ntype baseController struct {\n\tbeego.Controller\n}\n\nvar dockerClient *client.Client\n\n\nfunc Init() {\n\tvar conf = config.GetConfig()\n\tvar err error\n\n\tdefaultHeaders := map[string]string{\"User-Agent\": \"engine-api-cli-1.0\"}\n\tdockerClient, err = client.NewClient(conf.DockerEndPoint, conf.DockerAPIVersion, nil, defaultHeaders)\n\n\tif err != nil {\n\t\tbeego.Critical(\"Cannot connect docker.\\n Endpoint: %s\\n Detail: %v\", conf.DockerEndPoint, err)\n\t\tos.Exit(2)\n\t}\n}\n\n\nfunc (base *baseController) Prepare() {\n}\n\n\nfunc (base *baseController) JSON(data interface{}) {\n\tbase.Data[\"json\"] = data\n\tbase.ServeJSON()\n}\n\n\nfunc (base *baseController) Stream(data string) {\n\tdata = strings.TrimSpace(data)\n\tdata = strings.Replace(data, \"\\r\\n\", \"\", -1)\n\tdata = strings.Replace(data, \"}{\", \"},{\", -1)\n\tres := \"[\" + data + \"]\"\n\tbase.Ctx.ResponseWriter.Header().Set(\"Content-Type\", \"application/json\")\n\tbase.Ctx.ResponseWriter.Write([]byte(res))\n\tbase.StopRun()\n}\n\n\n\n\nfunc (base *baseController) Error(status int, msg ...interface{}) ", "output": "{\n\n\terrData := map[string]interface{}{\n\t\t\"Code\": status,\n\t\t\"Detail\": msg[0],\n\t}\n\tif len(msg) >= 2 && msg[1] != nil {\n\t\terrData[\"Code\"] = msg[1]\n\t\tif models.ErrorMap[msg[1].(int)] != \"\" {\n\t\t\terrData[\"Message\"] = models.ErrorMap[msg[1].(int)]\n\t\t}\n\t}\n\n\tbase.Ctx.ResponseWriter.Header().Set(\"Content-Type\", \"application/json\")\n\tbase.Ctx.ResponseWriter.WriteHeader(status)\n\tbody, _ := json.Marshal(errData)\n\tbase.Ctx.ResponseWriter.Write(body)\n\tbase.StopRun()\n}"} {"input": "package timeconv\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestNow(t *testing.T) {\n\tnow := time.Now()\n\tts := Now()\n\tvar drift int64 = 5\n\tif ts.Seconds < int64(now.Second())-drift {\n\t\tt.Errorf(\"Unexpected time drift: %d\", ts.Seconds)\n\t}\n}\n\nfunc TestTimestamp(t *testing.T) {\n\tnow := time.Now()\n\tts := Timestamp(now)\n\n\tif now.Unix() != ts.Seconds {\n\t\tt.Errorf(\"Unexpected time drift: %d to %d\", now.Second(), ts.Seconds)\n\t}\n\n\tif now.Nanosecond() != int(ts.Nanos) {\n\t\tt.Errorf(\"Unexpected nano drift: %d to %d\", now.Nanosecond(), ts.Nanos)\n\t}\n}\n\nfunc TestTime(t *testing.T) {\n\tnowts := Now()\n\tnow := Time(nowts)\n\n\tif now.Unix() != nowts.Seconds {\n\t\tt.Errorf(\"Unexpected time drift %d\", now.Unix())\n\t}\n}\n\n\n\nfunc TestFormat(t *testing.T) ", "output": "{\n\tnow := time.Now()\n\tnowts := Timestamp(now)\n\n\tif now.Format(time.ANSIC) != Format(nowts, time.ANSIC) {\n\t\tt.Error(\"Format mismatch\")\n\t}\n}"} {"input": "package etude0\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestMoreGetAndPut(t *testing.T) {\n\n\tdb := &DB{}\n\tdb.Open(\"./tmp/bar\")\n\n\tn := 10000\n\n\tfor i := 0; i < n; i++ {\n\t\tkey := fmt.Sprintf(\"%d\", i)\n\t\tvalue := fmt.Sprintf(\"%010d\", i)\n\t\tdb.Put(key, value)\n\t}\n\n\tfor i := 0; i < n; i++ {\n\t\tkey := fmt.Sprintf(\"%d\", i)\n\t\tvalue := fmt.Sprintf(\"%010d\", i)\n\t\ts, err := db.Get(key)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t}\n\t\tif s != value {\n\t\t\tt.Errorf(\"Get(\\\"%s\\\") = \\\"%s\\\", want \\\"%s\\\"\", key, s, value)\n\t\t}\n\t}\n}\n\nfunc TestGetAndPut(t *testing.T) ", "output": "{\n\n\tdb := &DB{}\n\tdb.Open(\"./tmp/foo\")\n\n\terr := db.Put(\"aaa\", \"foo\")\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\terr = db.Put(\"bbb\", \"bar\")\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\ts, err := db.Get(\"aaa\")\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif s != \"foo\" {\n\t\tt.Errorf(\"Get(\\\"aaa\\\") = \\\"%s\\\", want \\\"foo\\\"\", s)\n\t}\n\n\ts, err = db.Get(\"bbb\")\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif s != \"bar\" {\n\t\tt.Errorf(\"Get(\\\"bbb\\\") = \\\"%s\\\", want \\\"bar\\\"\", s)\n\t}\n}"} {"input": "package format\n\nimport (\n\t\"testing\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestSshWithComment(t *testing.T) {\n\tlog.SetLevel(log.DebugLevel)\n\n\tkeys := map[string][]string{\n\t\t\"ernoaapa\": {\n\t\t\t\"ssh-rsa AAAAB3NzsshPublicKeyBlah\",\n\t\t},\n\t}\n\n\tresult := ssh(keys, \"Generated file\")\n\n\tassert.Equal(t, \"# Generated file\\nssh-rsa AAAAB3NzsshPublicKeyBlah ernoaapa\\n# Generated file\\n\", result, \"Returned invalid ssh output\")\n}\n\nfunc TestSshWithoutComment(t *testing.T) ", "output": "{\n\tlog.SetLevel(log.DebugLevel)\n\n\tkeys := map[string][]string{\n\t\t\"ernoaapa\": {\n\t\t\t\"ssh-rsa AAAAB3NzsshPublicKeyBlah\",\n\t\t},\n\t}\n\n\tresult := ssh(keys, \"\")\n\n\tassert.Equal(t, \"ssh-rsa AAAAB3NzsshPublicKeyBlah ernoaapa\\n\", result, \"Returned invalid ssh output\")\n}"} {"input": "package autostart\n\nimport (\n\t\"flag\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/vim25/types\"\n)\n\ntype add struct {\n\t*AutostartFlag\n}\n\nfunc init() {\n\tcli.Register(\"host.autostart.add\", &add{})\n}\n\nfunc (cmd *add) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.AutostartFlag, ctx = newAutostartFlag(ctx)\n\tcmd.AutostartFlag.Register(ctx, f)\n}\n\nfunc (cmd *add) Process(ctx context.Context) error {\n\tif err := cmd.AutostartFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (cmd *add) Usage() string {\n\treturn \"VM...\"\n}\n\n\n\nfunc (cmd *add) Run(ctx context.Context, f *flag.FlagSet) error ", "output": "{\n\tvar powerInfo = types.AutoStartPowerInfo{\n\t\tStartAction: \"powerOn\",\n\t\tStartDelay: -1,\n\t\tStartOrder: -1,\n\t\tStopAction: \"systemDefault\",\n\t\tStopDelay: -1,\n\t\tWaitForHeartbeat: types.AutoStartWaitHeartbeatSettingSystemDefault,\n\t}\n\n\treturn cmd.ReconfigureVMs(f.Args(), powerInfo)\n}"} {"input": "package gcmlib\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nvar messageValidateTests = []struct {\n\tmsg *Message\n\terr error\n}{\n\t{&Message{}, errNoRegID},\n\t{&Message{To: \"foo\", RegistrationIDs: []string{\"id0\"}}, errBothToAndRegID},\n\t{&Message{RegistrationIDs: make([]string, 1001)}, errExceedMaxRegIDs},\n\t{&Message{To: \"foo\", TTL: maxTTL + 1}, errInvalidTTL},\n\t{&Message{To: \"foo\", Priority: maxPriority + 1}, errInvalidPriority},\n\t{&Message{To: \"foo\", Data: map[string]string{\"from\": \"bar\"}}, errReservedDataKey},\n\t{&Message{To: \"foo\", Data: map[string]string{\"google.key\": \"bar\"}}, errReservedDataKeyPrefix},\n\n\t{&Message{To: \"foo\", Data: map[string]string{\"foo\": \"bar\"}}, nil},\n}\n\n\n\nfunc TestValidate(t *testing.T) ", "output": "{\n\tfor _, tt := range messageValidateTests {\n\t\thave, want := tt.msg.Validate(), tt.err\n\t\tif !reflect.DeepEqual(have, want) {\n\t\t\tt.Errorf(\"Message.Validate(%q): have: %#v, want: %#v\\n\", tt.msg, have, want)\n\t\t}\n\t}\n}"} {"input": "package postactions\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/fragmenta/auth/can\"\n\t\"github.com/fragmenta/mux\"\n\t\"github.com/fragmenta/server\"\n\t\"github.com/fragmenta/view\"\n\n\t\"github.com/fragmenta/fragmenta-cms/src/lib/session\"\n\t\"github.com/fragmenta/fragmenta-cms/src/posts\"\n\t\"github.com/fragmenta/fragmenta-cms/src/users\"\n)\n\n\nfunc HandleUpdateShow(w http.ResponseWriter, r *http.Request) error {\n\n\tparams, err := mux.Params(r)\n\tif err != nil {\n\t\treturn server.InternalError(err)\n\t}\n\n\tpost, err := posts.Find(params.GetInt(posts.KeyName))\n\tif err != nil {\n\t\treturn server.NotFoundError(err)\n\t}\n\n\tuser := session.CurrentUser(w, r)\n\terr = can.Update(post, user)\n\tif err != nil {\n\t\treturn server.NotAuthorizedError(err)\n\t}\n\n\tauthors, err := users.FindAll(users.Where(\"role=?\", users.Admin))\n\tif err != nil {\n\t\treturn server.InternalError(err)\n\t}\n\n\tview := view.NewRenderer(w, r)\n\tview.AddKey(\"currentUser\", user)\n\tview.AddKey(\"post\", post)\n\tview.AddKey(\"authors\", authors)\n\treturn view.Render()\n}\n\n\n\n\nfunc HandleUpdate(w http.ResponseWriter, r *http.Request) error ", "output": "{\n\n\tparams, err := mux.Params(r)\n\tif err != nil {\n\t\treturn server.InternalError(err)\n\t}\n\n\tpost, err := posts.Find(params.GetInt(posts.KeyName))\n\tif err != nil {\n\t\treturn server.NotFoundError(err)\n\t}\n\n\terr = session.CheckAuthenticity(w, r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuser := session.CurrentUser(w, r)\n\terr = can.Update(post, user)\n\tif err != nil {\n\t\treturn server.NotAuthorizedError(err)\n\t}\n\n\tpostParams := post.ValidateParams(params.Map(), posts.AllowedParams())\n\n\terr = post.Update(postParams)\n\tif err != nil {\n\t\treturn server.InternalError(err)\n\t}\n\n\treturn server.Redirect(w, r, post.ShowURL())\n}"} {"input": "package google\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hashicorp/terraform-plugin-sdk/helper/schema\"\n)\n\n\n\nfunc datasourceComputeSslPolicyRead(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\tproject, err := getProject(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpolicyName := d.Get(\"name\").(string)\n\n\td.SetId(fmt.Sprintf(\"projects/%s/global/sslPolicies/%s\", project, policyName))\n\n\treturn resourceComputeSslPolicyRead(d, meta)\n}\n\nfunc dataSourceGoogleComputeSslPolicy() *schema.Resource ", "output": "{\n\tdsSchema := datasourceSchemaFromResourceSchema(resourceComputeSslPolicy().Schema)\n\n\taddRequiredFieldsToSchema(dsSchema, \"name\")\n\n\taddOptionalFieldsToSchema(dsSchema, \"project\")\n\n\treturn &schema.Resource{\n\t\tRead: datasourceComputeSslPolicyRead,\n\t\tSchema: dsSchema,\n\t}\n}"} {"input": "package elements\n\nimport \"github.com/fileformats/graphics/jt/model\"\n\n\n\n\ntype LODNode struct {\n\tGroupNode\n\tVersion uint8\n\tReservedRangeField model.VectorF32\n\tReservedField int32\n}\n\nfunc (n LODNode) GUID() model.GUID {\n\treturn model.LodNodeElement\n}\n\n\n\nfunc (n *LODNode) BaseElement() *JTElement {\n\treturn &n.JTElement\n}\n\nfunc (n *LODNode) Read(c *model.Context) error ", "output": "{\n\tc.LogGroup(\"LODNode\")\n\tdefer c.LogGroupEnd()\n\n\tif err := (&n.GroupNode).Read(c); err != nil {\n\t\treturn err\n\t}\n\n\tif c.Version.Equal(model.V10) {\n\t\tn.Version = c.Data.UInt8()\n\t}\n\tif c.Version.Equal(model.V9) {\n\t\tn.Version = uint8(c.Data.UInt16())\n\t}\n\n\tif !c.Version.Equal(model.V10) {\n\t\t(&n.ReservedRangeField).Read(c)\n\t\tn.ReservedField = c.Data.Int32()\n\t}\n\n\treturn c.Data.GetError()\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"net/http\"\n)\n\n\n\nfunc internalServerError(w http.ResponseWriter, r *http.Request) {\n\thttp.Error(w, http.StatusText(http.StatusInternalServerError),\n\t\t\t\thttp.StatusInternalServerError)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/\", internalServerError)\n\thttp.ListenAndServe(\":8000\", nil)\n}\n\nfunc hello(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tio.WriteString(w, \"Fabio rocks!\")\n}"} {"input": "package object\n\nimport (\n\t\"hash/fnv\"\n)\n\n\ntype String struct {\n\tValue string\n}\n\n\nfunc (s *String) Type() ObjectType {\n\treturn STRING_OBJ\n}\n\n\nfunc (s *String) Inspect() string {\n\treturn s.Value\n}\n\n\n\n\nfunc (s *String) HashKey() HashKey ", "output": "{\n\th := fnv.New64a()\n\th.Write([]byte(s.Value))\n\n\treturn HashKey{Type: s.Type(), Value: h.Sum64()}\n}"} {"input": "package kafkasink\n\nimport (\n\tfmt \"fmt\"\n\n\ttypes \"k8s.io/apimachinery/pkg/types\"\n\tcache \"k8s.io/client-go/tools/cache\"\n\tv1alpha1 \"knative.dev/eventing-kafka-broker/control-plane/pkg/apis/eventing/v1alpha1\"\n\treconciler \"knative.dev/pkg/reconciler\"\n)\n\n\ntype state struct {\n\tkey string\n\tnamespace string\n\tname string\n\treconciler Interface\n\troi ReadOnlyInterface\n\tisROI bool\n\tisLeader bool\n}\n\n\n\n\n\n\n\nfunc (s *state) isNotLeaderNorObserver() bool {\n\tif !s.isLeader && !s.isROI {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *state) reconcileMethodFor(o *v1alpha1.KafkaSink) (string, doReconcile) {\n\tif o.GetDeletionTimestamp().IsZero() {\n\t\tif s.isLeader {\n\t\t\treturn reconciler.DoReconcileKind, s.reconciler.ReconcileKind\n\t\t} else if s.isROI {\n\t\t\treturn reconciler.DoObserveKind, s.roi.ObserveKind\n\t\t}\n\t} else if fin, ok := s.reconciler.(Finalizer); s.isLeader && ok {\n\t\treturn reconciler.DoFinalizeKind, fin.FinalizeKind\n\t}\n\treturn \"unknown\", nil\n}\n\nfunc newState(key string, r *reconcilerImpl) (*state, error) ", "output": "{\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid resource key: %s\", key)\n\t}\n\n\troi, isROI := r.reconciler.(ReadOnlyInterface)\n\n\tisLeader := r.IsLeaderFor(types.NamespacedName{\n\t\tNamespace: namespace,\n\t\tName: name,\n\t})\n\n\treturn &state{\n\t\tkey: key,\n\t\tnamespace: namespace,\n\t\tname: name,\n\t\treconciler: r.reconciler,\n\t\troi: roi,\n\t\tisROI: isROI,\n\t\tisLeader: isLeader,\n\t}, nil\n}"} {"input": "package tristate\n\ntype StateValue int\n\nconst (\n\tTRISTATE_SUCCESS StateValue = iota\n\tTRISTATE_FAILRUE\n\tTRISTATE_UNKNOWN\n)\n\ntype TriState struct {\n\tState StateValue\n\tErr error\n}\n\nfunc NewSuccess() *TriState {\n\treturn nil\n}\n\nfunc NewUnknown(err error) *TriState {\n\tif err == nil {\n\t\tpanic(\"error not set\")\n\t}\n\treturn &TriState{TRISTATE_UNKNOWN, err}\n}\n\nfunc NewFailure(err error) *TriState {\n\tif err == nil {\n\t\tpanic(\"error not set\")\n\t}\n\treturn &TriState{TRISTATE_FAILRUE, err}\n}\n\nfunc (state *TriState) Error() string {\n\treturn state.Err.Error()\n}\n\nfunc (state *TriState) IsSuccess() bool {\n\treturn state == nil || state.State == TRISTATE_SUCCESS\n}\n\n\n\nfunc (state *TriState) IsUnknown() bool {\n\treturn state != nil && state.State == TRISTATE_UNKNOWN\n}\n\nfunc (state *TriState) IsFailure() bool ", "output": "{\n\treturn state != nil && state.State == TRISTATE_FAILRUE\n}"} {"input": "package emr\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestListRegions(t *testing.T) ", "output": "{\n\tvar req ListRegionsRequest\n\treq.Init()\n\treq.SetFormat(\"JSON\")\n\treq.SetRegionId(\"cn-shenzhen\")\n\tvar accessId = \"Ie65kUInu5GeAsma\"\n\tvar accessSecret = \"8cCqoxdYU9zKUihwXFXiN1HEACBDwB\"\n\tresp, err := ListRegions(&req, accessId, accessSecret)\n\tif err != nil {\n\t\tt.Errorf(\"Error: %s\", err.Error())\n\t}\n\tfmt.Printf(\"Success: %v\\n\", resp)\n}"} {"input": "package segment\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/checkr/flagr/swagger_gen/models\"\n)\n\n\nconst DeleteSegmentOKCode int = 200\n\n\ntype DeleteSegmentOK struct {\n}\n\n\n\n\n\nfunc (o *DeleteSegmentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(200)\n}\n\n\ntype DeleteSegmentDefault struct {\n\t_statusCode int\n\n\tPayload *models.Error `json:\"body,omitempty\"`\n}\n\n\nfunc NewDeleteSegmentDefault(code int) *DeleteSegmentDefault {\n\tif code <= 0 {\n\t\tcode = 500\n\t}\n\n\treturn &DeleteSegmentDefault{\n\t\t_statusCode: code,\n\t}\n}\n\n\nfunc (o *DeleteSegmentDefault) WithStatusCode(code int) *DeleteSegmentDefault {\n\to._statusCode = code\n\treturn o\n}\n\n\nfunc (o *DeleteSegmentDefault) SetStatusCode(code int) {\n\to._statusCode = code\n}\n\n\nfunc (o *DeleteSegmentDefault) WithPayload(payload *models.Error) *DeleteSegmentDefault {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *DeleteSegmentDefault) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}\n\n\nfunc (o *DeleteSegmentDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(o._statusCode)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\nfunc NewDeleteSegmentOK() *DeleteSegmentOK ", "output": "{\n\n\treturn &DeleteSegmentOK{}\n}"} {"input": "package db\n\ntype DB interface {\n\tClose() error\n\tInit(...Option) error\n\tOptions() Options\n\tRead(id string) (Record, error)\n\tCreate(r Record) error\n\tUpdate(r Record) error\n\tDelete(id string) error\n\tSearch(...SearchOption) ([]Record, error)\n\tString() string\n}\n\ntype Option func(*Options)\n\ntype SearchOption func(*SearchOptions)\n\ntype Metadata map[string]interface{}\n\ntype Record interface {\n\tId() string\n\tCreated() int64\n\tUpdated() int64\n\tMetadata() Metadata\n\tBytes() []byte\n\tScan(v interface{}) error\n}\n\nvar (\n\tDefaultDatabase = \"micro\"\n\tDefaultTable = \"micro\"\n)\n\nfunc NewDB(opts ...Option) DB {\n\treturn newOS(opts...)\n}\n\n\n\nfunc NewRecord(id string, md Metadata, data interface{}) Record ", "output": "{\n\treturn newRecord(id, md, data)\n}"} {"input": "package app\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestAppPgcContCount(t *testing.T) {\n\tvar (\n\t\tc = context.Background()\n\t)\n\tconvey.Convey(\"PgcContCount\", t, func(ctx convey.C) {\n\t\tupCnt, err := d.PgcContCount(c)\n\t\tctx.Convey(\"Then err should be nil.upCnt should not be nil.\", func(ctx convey.C) {\n\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\tctx.So(upCnt, convey.ShouldNotBeNil)\n\t\t})\n\t})\n}\n\nfunc TestAppPgcCont(t *testing.T) ", "output": "{\n\tvar (\n\t\tc = context.Background()\n\t\tid = int(0)\n\t\tlimit = int(10)\n\t)\n\tconvey.Convey(\"PgcCont\", t, func(ctx convey.C) {\n\t\tres, err := d.PgcCont(c, id, limit)\n\t\tctx.Convey(\"Then err should be nil.res should not be nil.\", func(ctx convey.C) {\n\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\tctx.So(res, convey.ShouldNotBeNil)\n\t\t})\n\t})\n}"} {"input": "package util\n\nimport \"testing\"\n\nfunc TestToCharsAscii(t *testing.T) {\n\tchars := ToChars([]byte(\"foobar\"))\n\tif !chars.inBytes || chars.ToString() != \"foobar\" || !chars.inBytes {\n\t\tt.Error()\n\t}\n}\n\nfunc TestCharsLength(t *testing.T) {\n\tchars := ToChars([]byte(\"\\tabc한글 \"))\n\tif chars.inBytes || chars.Length() != 8 || chars.TrimLength() != 5 {\n\t\tt.Error()\n\t}\n}\n\n\n\nfunc TestTrimLength(t *testing.T) {\n\tcheck := func(str string, exp uint16) {\n\t\tchars := ToChars([]byte(str))\n\t\ttrimmed := chars.TrimLength()\n\t\tif trimmed != exp {\n\t\t\tt.Errorf(\"Invalid TrimLength result for '%s': %d (expected %d)\",\n\t\t\t\tstr, trimmed, exp)\n\t\t}\n\t}\n\tcheck(\"hello\", 5)\n\tcheck(\"hello \", 5)\n\tcheck(\"hello \", 5)\n\tcheck(\" hello\", 5)\n\tcheck(\" hello\", 5)\n\tcheck(\" hello \", 5)\n\tcheck(\" hello \", 5)\n\tcheck(\"h o\", 5)\n\tcheck(\" h o \", 5)\n\tcheck(\" \", 0)\n}\n\nfunc TestCharsToString(t *testing.T) ", "output": "{\n\ttext := \"\\tabc한글 \"\n\tchars := ToChars([]byte(text))\n\tif chars.ToString() != text {\n\t\tt.Error()\n\t}\n}"} {"input": "package datastore\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"gopkg.in/gorp.v2\"\n\n\tlogger \"github.com/betchi/zapper\"\n\t\"github.com/pkg/errors\"\n\t\"github.com/swagchat/chat-api/model\"\n\t\"github.com/betchi/tracer\"\n)\n\n\n\nfunc rdbSelectWebhooks(ctx context.Context, dbMap *gorp.DbMap, event model.WebhookEventType, opts ...SelectWebhooksOption) ([]*model.Webhook, error) {\n\tspan := tracer.StartSpan(ctx, \"rdbSelectWebhooks\", \"datastore\")\n\tdefer tracer.Finish(span)\n\n\topt := selectWebhooksOptions{}\n\tfor _, o := range opts {\n\t\to(&opt)\n\t}\n\n\tvar webhooks []*model.Webhook\n\n\tquery := fmt.Sprintf(\"SELECT * FROM %s WHERE event=:event AND deleted=0\", tableNameWebhook)\n\tparams := map[string]interface{}{\n\t\t\"event\": event,\n\t}\n\n\tif opt.roomID != \"\" {\n\t\tquery = fmt.Sprintf(\"%s AND room_id=:roomId\", query)\n\t\tparams[\"roomId\"] = opt.roomID\n\t}\n\n\tif opt.roleID != 0 {\n\t\tquery = fmt.Sprintf(\"%s AND role_id=:roleId\", query)\n\t\tparams[\"roleId\"] = opt.roleID\n\t}\n\n\t_, err := dbMap.Select(&webhooks, query, params)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"An error occurred while getting webhook\")\n\t\tlogger.Error(err.Error())\n\t\ttracer.SetError(span, err)\n\t\treturn nil, err\n\t}\n\n\treturn webhooks, nil\n}\n\nfunc rdbCreateWebhookStore(ctx context.Context, dbMap *gorp.DbMap) ", "output": "{\n\tspan := tracer.StartSpan(ctx, \"rdbCreateWebhookStore\", \"datastore\")\n\tdefer tracer.Finish(span)\n\n\ttableMap := dbMap.AddTableWithName(model.Webhook{}, tableNameWebhook)\n\tfor _, columnMap := range tableMap.Columns {\n\t\tif columnMap.ColumnName == \"webhook_id\" {\n\t\t\tcolumnMap.SetUnique(true)\n\t\t}\n\t}\n\terr := dbMap.CreateTablesIfNotExists()\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"An error occurred while creating webhook table\")\n\t\tlogger.Error(err.Error())\n\t\ttracer.SetError(span, err)\n\t\treturn\n\t}\n}"} {"input": "package rpc\n\nimport (\n\t\"github.com/open-falcon/common/model\"\n\t\"github.com/open-falcon/judge/g\"\n\t\"github.com/open-falcon/judge/store\"\n\t\"time\"\n)\n\ntype Judge int\n\nfunc (this *Judge) Ping(req model.NullRpcRequest, resp *model.SimpleRpcResponse) error {\n\treturn nil\n}\n\n\n\nfunc (this *Judge) Send(items []*model.JudgeItem, resp *model.SimpleRpcResponse) error ", "output": "{\n\tremain := g.Config().Remain\n\tnow := time.Now().Unix()\n\tfor _, item := range items {\n\t\tpk := item.PrimaryKey()\n\n\t\tstore.HistoryBigMap[pk[0:2]].PushFrontAndMaintain(pk, item, remain, now)\n\t}\n\treturn nil\n}"} {"input": "package grpcsync\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"strings\"\n\n\t\"github.com/ligato/cn-infra/datasync/syncbase/msg\"\n\t\"github.com/ligato/cn-infra/logging/logrus\"\n\t\"golang.org/x/net/context\"\n)\n\n\nfunc NewDataMsgServiceServer(adapter *Adapter) *DataMsgServiceServer {\n\treturn &DataMsgServiceServer{adapter: adapter}\n}\n\n\ntype DataMsgServiceServer struct {\n\tadapter *Adapter\n}\n\n\n\n\n\nfunc (s *DataMsgServiceServer) DataResyncs(ctx context.Context, req *msg.DataResyncRequests) (\n\t*msg.DataResyncReplies, error) {\n\tresyncs := req.GetDataResyncs()\n\tif resyncs != nil {\n\n\t\tvar err error\n\t\tif err != nil {\n\t\t\treturn &msg.DataResyncReplies{MsgId: replySeq(), Error: &msg.Error{Message: err.Error()} }, err\n\t\t}\n\n\t\treturn &msg.DataResyncReplies{MsgId: replySeq() }, nil\n\t}\n\n\terr := errors.New(\"unexpected place - nil resyncs\")\n\treturn &msg.DataResyncReplies{MsgId: replySeq(), Error: &msg.Error{Message: err.Error()} }, err\n}\n\nfunc replySeq() *msg.Seq {\n\treturn &msg.Seq{} \n}\n\n\nfunc (s *DataMsgServiceServer) Ping(ctx context.Context, req *msg.PingRequest) (*msg.PingReply, error) {\n\treturn &msg.PingReply{Message: \"it works\"}, nil\n}\n\nfunc (s *DataMsgServiceServer) DataChanges(stream msg.DataMsgService_DataChangesServer) error ", "output": "{\n\tfor {\n\t\tchng, err := stream.Recv()\n\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, sub := range s.adapter.base.Subscriptions() {\n\t\t\tfor _, keyPrefix := range sub.KeyPrefixes {\n\t\t\t\tif strings.HasPrefix(chng.Key, keyPrefix) {\n\t\t\t\t\tsub.ChangeChan <- msg.NewChangeWatchResp(chng, func(err2 error) {\n\t\t\t\t\t\terr = stream.Send(&msg.DataChangeReply{Key: chng.Key, OperationType: chng.OperationType,\n\t\t\t\t\t\t\tResult: 0 })\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlogrus.DefaultLogger().Error(err) \n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package opts\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype List struct {\n\tArgs []string\n}\n\nfunc (lo *List) Set(arg string) error {\n\tlo.Args = append(lo.Args[:], arg)\n\treturn nil\n}\n\nfunc (lo List) Get() []string {\n\treturn lo.Args\n}\n\n\n\nfunc (lo List) String() string ", "output": "{\n\treturn fmt.Sprintf(\"[%s]\", strings.Join(lo.Args, \", \"))\n}"} {"input": "package replay\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/gapid/core/data/search\"\n\t\"github.com/google/gapid/test/robot/job/worker\"\n\t\"google.golang.org/grpc\"\n\n\txctx \"golang.org/x/net/context\"\n)\n\ntype server struct {\n\tmanager Manager\n}\n\n\nfunc Serve(ctx context.Context, grpcServer *grpc.Server, manager Manager) error {\n\tRegisterServiceServer(grpcServer, &server{manager: manager})\n\treturn nil\n}\n\n\n\nfunc (s *server) Search(query *search.Query, stream Service_SearchServer) error {\n\tctx := stream.Context()\n\treturn s.manager.Search(ctx, query, func(ctx context.Context, e *Action) error { return stream.Send(e) })\n}\n\n\n\nfunc (s *server) Register(request *worker.RegisterRequest, stream Service_RegisterServer) error {\n\tctx := stream.Context()\n\treturn s.manager.Register(ctx, request.Host, request.Target, func(ctx context.Context, t *Task) error { return stream.Send(t) })\n}\n\n\n\nfunc (s *server) Do(ctx xctx.Context, request *DoRequest) (*worker.DoResponse, error) {\n\tid, err := s.manager.Do(ctx, request.Device, request.Input)\n\treturn &worker.DoResponse{Id: id}, err\n}\n\n\n\n\n\nfunc (s *server) Update(ctx xctx.Context, request *UpdateRequest) (*worker.UpdateResponse, error) ", "output": "{\n\tif err := s.manager.Update(ctx, request.Action, request.Status, request.Output); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &worker.UpdateResponse{}, nil\n}"} {"input": "package v1\n\n\n\n\n\n\n\n\n\n\n\n\nvar map_TokenReview = map[string]string{\n\t\"\": \"TokenReview attempts to authenticate a token to a known user. Note: TokenReview requests may be cached by the webhook token authenticator plugin in the kube-apiserver.\",\n\t\"spec\": \"Spec holds information about the request being evaluated\",\n\t\"status\": \"Status is filled in by the server and indicates whether the request can be authenticated.\",\n}\n\n\n\nvar map_TokenReviewSpec = map[string]string{\n\t\"\": \"TokenReviewSpec is a description of the token authentication request.\",\n\t\"token\": \"Token is the opaque bearer token.\",\n}\n\nfunc (TokenReviewSpec) SwaggerDoc() map[string]string {\n\treturn map_TokenReviewSpec\n}\n\nvar map_TokenReviewStatus = map[string]string{\n\t\"\": \"TokenReviewStatus is the result of the token authentication request.\",\n\t\"authenticated\": \"Authenticated indicates that the token was associated with a known user.\",\n\t\"user\": \"User is the UserInfo associated with the provided token.\",\n\t\"error\": \"Error indicates that the token couldn't be checked\",\n}\n\nfunc (TokenReviewStatus) SwaggerDoc() map[string]string {\n\treturn map_TokenReviewStatus\n}\n\nvar map_UserInfo = map[string]string{\n\t\"\": \"UserInfo holds the information about the user needed to implement the user.Info interface.\",\n\t\"username\": \"The name that uniquely identifies this user among all active users.\",\n\t\"uid\": \"A unique value that identifies this user across time. If this user is deleted and another user by the same name is added, they will have different UIDs.\",\n\t\"groups\": \"The names of groups this user is a part of.\",\n\t\"extra\": \"Any additional information provided by the authenticator.\",\n}\n\nfunc (UserInfo) SwaggerDoc() map[string]string {\n\treturn map_UserInfo\n}\n\nfunc (TokenReview) SwaggerDoc() map[string]string ", "output": "{\n\treturn map_TokenReview\n}"} {"input": "package labmeasure\n\ntype ImageStat struct {\n\tExamined int\n\tQualified int\n\tCorrect int\n\tIncorrect int\n\tIncorrectRecords []PImageRecord\n\tConfiguration Config\n}\n\n\n\nfunc (o ImageStat) Accuracy() float32 {\n\tif o.Qualified == 0 {\n\t\treturn 0.0\n\t}\n\treturn float32(o.Correct) / float32(o.Qualified)\n}\n\nfunc (o ImageStat) GetIncorrectRecords() interface{} ", "output": "{\n\treturn o.IncorrectRecords\n}"} {"input": "package messagestore\n\nimport (\n\t\"github.com/agl/ed25519\"\n\tlog \"github.com/repbin/repbin/deferconsole\"\n\t\"github.com/repbin/repbin/utils\"\n\t\"github.com/repbin/repbin/utils/keyproof\"\n\t\"github.com/repbin/repbin/utils/repproto/structs\"\n)\n\n\nfunc (store Store) TouchPeer(pubkey *[ed25519.PublicKeySize]byte) {\n\terr := store.db.TouchPeer(pubkey)\n\tif err != nil {\n\t\tlog.Errorf(\"TouchPeer: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t}\n}\n\n\nfunc (store Store) UpdatePeerFetchStat(pubkey *[ed25519.PublicKeySize]byte, lastFetch, lastPos, lastErrors uint64) {\n\terr := store.db.UpdatePeerStats(pubkey, lastFetch, lastPos, lastErrors)\n\tif err != nil {\n\t\tlog.Errorf(\"UpdatePeerStats: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t}\n}\n\n\n\n\n\nfunc (store Store) GetPeerStat(pubkey *[ed25519.PublicKeySize]byte) *structs.PeerStruct {\n\tst, err := store.db.SelectPeer(pubkey)\n\tif err != nil {\n\t\tlog.Errorf(\"GetPeerStat: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t\treturn nil\n\t}\n\treturn st\n}\n\n\nfunc (store Store) UpdatePeerAuthToken(senderPubKey *[ed25519.PublicKeySize]byte, signedToken *[keyproof.ProofTokenSignedSize]byte) {\n\terr := store.db.UpdatePeerToken(senderPubKey, signedToken)\n\tif err != nil {\n\t\tlog.Errorf(\"UpdatePeerAuthToken: %s, %s\\n\", err, utils.B58encode(senderPubKey[:]))\n\t}\n}\n\nfunc (store Store) UpdatePeerNotification(pubkey *[ed25519.PublicKeySize]byte, hasError bool) ", "output": "{\n\terr := store.db.UpdatePeerNotification(pubkey, hasError)\n\tif err != nil {\n\t\tlog.Errorf(\"UpdatePeerNotification: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t}\n}"} {"input": "package types\n\nimport (\n\t\"testing\"\n\n\t\"time\"\n\n\tconsensus_types \"github.com/hyperledger/burrow/consensus/types\"\n\t\"github.com/tendermint/go-wire\"\n\ttendermint_types \"github.com/tendermint/tendermint/types\"\n)\n\n\n\nfunc TestResultDumpConsensusState(t *testing.T) ", "output": "{\n\tresult := ResultDumpConsensusState{\n\t\tConsensusState: &consensus_types.ConsensusState{\n\t\t\tHeight: 3,\n\t\t\tRound: 1,\n\t\t\tStep: uint8(1),\n\t\t\tStartTime: time.Now().Add(-time.Second * 100),\n\t\t\tCommitTime: time.Now().Add(-time.Second * 10),\n\t\t\tValidators: []consensus_types.Validator{\n\t\t\t\t&consensus_types.TendermintValidator{},\n\t\t\t},\n\t\t\tProposal: &tendermint_types.Proposal{},\n\t\t},\n\t\tPeerConsensusStates: []*ResultPeerConsensusState{\n\t\t\t{\n\t\t\t\tPeerKey: \"Foo\",\n\t\t\t\tPeerConsensusState: \"Bar\",\n\t\t\t},\n\t\t},\n\t}\n\twire.JSONBytes(result)\n}"} {"input": "package handlers\n\nimport (\n\t\"time\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/emicklei/go-restful\"\n\t\"github.com/quintilesims/layer0/common/config\"\n)\n\n\n\nfunc AddVersionHeader(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {\n\tresp.AddHeader(\"Version\", config.APIVersion())\n\tchain.ProcessFilter(req, resp)\n}\n\nfunc EnableCORS(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {\n\tif origin := req.Request.Header.Get(\"Origin\"); origin != \"\" {\n\t\tresp.AddHeader(\"Access-Control-Allow-Origin\", origin)\n\t\tresp.AddHeader(\"Access-Control-Allow-Credentials\", \"true\")\n\t\tresp.AddHeader(\"Access-Control-Allow-Headers\", \"Origin, Content-Type, X-Auth-Token, Authorization\")\n\t}\n\n\tchain.ProcessFilter(req, resp)\n}\n\nfunc LogRequest(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) ", "output": "{\n\tstart := time.Now()\n\tchain.ProcessFilter(req, resp)\n\tduration := time.Since(start)\n\n\tif req.Request.URL.String() != \"/health\" {\n\t\tlogrus.Infof(\"request %s %s (%v) %v\", req.Request.Method, req.Request.URL, resp.StatusCode(), duration)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\n\t\"github.com/coreos/fleet/job\"\n)\n\nvar (\n\tcmdStartUnit = &Command{\n\t\tName: \"start\",\n\t\tSummary: \"Instruct systemd to start one or more units in the cluster, first submitting and loading if necessary.\",\n\t\tUsage: \"[--no-block|--block-attempts=N] UNIT...\",\n\t\tDescription: `Start one or many units on the cluster. Select units to start by glob matching\nfor units in the current working directory or matching names of previously\nsubmitted units.\n\nFor units which are not global, start operations are performed synchronously,\nwhich means fleetctl will block until it detects that the unit(s) have\ntransitioned to a started state. This behaviour can be configured with the\nrespective --block-attempts and --no-block options. Start operations on global\nunits are always non-blocking.\n\nStart a single unit:\n\tfleetctl start foo.service\n\nStart an entire directory of units with glob matching:\n\tfleetctl start myservice/*\n\nYou may filter suitable hosts based on metadata provided by the machine.\nMachine metadata is located in the fleet configuration file.`,\n\t\tRun: runStartUnit,\n\t}\n)\n\nfunc init() {\n\tcmdStartUnit.Flags.BoolVar(&sharedFlags.Sign, \"sign\", false, \"DEPRECATED - this option cannot be used\")\n\tcmdStartUnit.Flags.IntVar(&sharedFlags.BlockAttempts, \"block-attempts\", 0, \"Wait until the units are launched, performing up to N attempts before giving up. A value of 0 indicates no limit. Does not apply to global units.\")\n\tcmdStartUnit.Flags.BoolVar(&sharedFlags.NoBlock, \"no-block\", false, \"Do not wait until the units have launched before exiting. Always the case for global units.\")\n}\n\n\n\nfunc runStartUnit(args []string) (exit int) ", "output": "{\n\tif len(args) == 0 {\n\t\tstderr(\"No units given\")\n\t\treturn 0\n\t}\n\n\tif err := lazyCreateUnits(args); err != nil {\n\t\tstderr(\"Error creating units: %v\", err)\n\t\treturn 1\n\t}\n\n\ttriggered, err := lazyStartUnits(args)\n\tif err != nil {\n\t\tstderr(\"Error starting units: %v\", err)\n\t\treturn 1\n\t}\n\n\tvar starting []string\n\tfor _, u := range triggered {\n\t\tif suToGlobal(*u) {\n\t\t\tstdout(\"Triggered global unit %s start\", u.Name)\n\t\t} else {\n\t\t\tstarting = append(starting, u.Name)\n\t\t}\n\t}\n\n\texit = tryWaitForUnitStates(starting, \"start\", job.JobStateLaunched, getBlockAttempts(), os.Stdout)\n\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc createServer() error {\n\tc, err := getClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsb := c.NewServerBuilder()\n\tsb.Addr(\"127.0.0.1:8080\").HTTPBackend().MaxQPS(100)\n\n\tsb.CheckHTTPCode(\"/check/path\", time.Second*10, time.Second*30)\n\n\tsb.CircuitBreakerCheckPeriod(time.Second)\n\tsb.CircuitBreakerCloseToHalfTimeout(time.Second * 60)\n\tsb.CircuitBreakerHalfTrafficRate(10)\n\tsb.CircuitBreakerHalfToCloseCondition(2)\n\tsb.CircuitBreakerHalfToOpenCondition(90)\n\n\tid, err := sb.Commit()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"server id is: %d\", id)\n\n\tc.AddBind(1, id)\n\n\tc.RemoveBind(1, id)\n\n\tc.AddBind(2, id)\n\treturn nil\n}\n\n\n\nfunc deleteServer(id uint64) error {\n\tc, err := getClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.RemoveServer(id)\n}\n\nfunc updateServer(id uint64) error ", "output": "{\n\tc, err := getClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsvr, err := c.GetServer(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsb := c.NewServerBuilder()\n\tsb.Use(*svr)\n\n\tsb.MaxQPS(1000)\n\tsb.NoCircuitBreaker() \n\tsb.NoHeathCheck() \n\n\t_, err = sb.Commit()\n\treturn err\n}"} {"input": "package atomic\n\nimport (\n\t\"unsafe\"\n)\n\n\n\n\n\n\nfunc CompareAndSwapInt32(val *int32, old, new int32) (swapped bool)\n\n\nfunc CompareAndSwapInt64(val *int64, old, new int64) (swapped bool)\n\n\nfunc CompareAndSwapUint32(val *uint32, old, new uint32) (swapped bool)\n\n\nfunc CompareAndSwapUint64(val *uint64, old, new uint64) (swapped bool)\n\n\nfunc CompareAndSwapUintptr(val *uintptr, old, new uintptr) (swapped bool)\n\n\nfunc CompareAndSwapPointer(val *unsafe.Pointer, old, new unsafe.Pointer) (swapped bool)\n\n\nfunc AddInt32(val *int32, delta int32) (new int32)\n\n\nfunc AddUint32(val *uint32, delta uint32) (new uint32)\n\n\nfunc AddInt64(val *int64, delta int64) (new int64)\n\n\nfunc AddUint64(val *uint64, delta uint64) (new uint64)\n\n\nfunc AddUintptr(val *uintptr, delta uintptr) (new uintptr)\n\n\nfunc LoadInt32(addr *int32) (val int32)\n\n\nfunc LoadInt64(addr *int64) (val int64)\n\n\nfunc LoadUint32(addr *uint32) (val uint32)\n\n\nfunc LoadUint64(addr *uint64) (val uint64)\n\n\nfunc LoadUintptr(addr *uintptr) (val uintptr)\n\n\nfunc LoadPointer(addr *unsafe.Pointer) (val unsafe.Pointer)\n\n\nfunc StoreInt32(addr *int32, val int32)\n\n\nfunc StoreInt64(addr *int64, val int64)\n\n\nfunc StoreUint32(addr *uint32, val uint32)\n\n\nfunc StoreUint64(addr *uint64, val uint64)\n\n\nfunc StoreUintptr(addr *uintptr, val uintptr)\n\n\nfunc StorePointer(addr *unsafe.Pointer, val unsafe.Pointer)\n\n\n\n\nfunc panic64() ", "output": "{\n\tpanic(\"sync/atomic: broken 64-bit atomic operations (buggy QEMU)\")\n}"} {"input": "package mos\n\nimport (\n\t\"github.com/atnet/gof/web\"\n\t\"net/http\"\n)\n\nvar (\n\troutes *web.RouteMap = new(web.RouteMap)\n)\n\n\nfunc Handle(ctx *web.Context) {\n\troutes.Handle(ctx)\n}\n\n\n\n\nfunc registerRoutes() {\n\tmc := new(mainC)\n\troutes.Add(\"/\",mc.Index)\n}\n\nfunc init(){\n\tregisterRoutes()\n}\n\nfunc handleError(w http.ResponseWriter, err error) ", "output": "{\n\tw.Write([]byte(`` + err.Error() + ``))\n}"} {"input": "package schema\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\nfunc TestParseGroup(t *testing.T) {\n\tgroupJsonString, _ := ioutil.ReadFile(\"../../resources/samples/group.json\")\n\tvar group GroupBase\n\tjson.Unmarshal(groupJsonString, &group)\n\tt.Log(\"Group ID is: \", group.Id)\n\tt.Log(\"Group Name is: \", group.Group.Name)\n}\n\nfunc TestParseThreadMessage(t *testing.T) {\n\tthreadJsonString, _ := ioutil.ReadFile(\"../../resources/samples/thread.json\")\n\tvar thread MessageBase\n\tjson.Unmarshal(threadJsonString, &thread)\n\tt.Log(\"Thread Id is: \", thread.Id)\n\tt.Log(\"Thread Title is: \", thread.Message.Title)\n\tt.Log(\"Thread Author is: \", thread.Message.Author.User.ScreenName)\n}\n\n\n\nfunc TestParsePostMessage(t *testing.T) ", "output": "{\n\tpostJsonString, _ := ioutil.ReadFile(\"../../resources/samples/post.json\")\n\tvar post MessageBase\n\tjson.Unmarshal(postJsonString, &post)\n\tt.Log(\"Post Id is: \", post.Id)\n\tt.Log(\"Post to Thread: \", post.Message.ThreadId)\n\tt.Log(\"Post Content is: \", post.Message.Content)\n}"} {"input": "package main\n\nimport (\n \"github.com/aws/aws-sdk-go/aws\"\n \"github.com/aws/aws-sdk-go/aws/session\"\n \"github.com/aws/aws-sdk-go/service/ec2\"\n \"fmt\"\n \"os\"\n \"errors\"\n _ \"path\"\n)\n\ntype AmazonMachineImage struct {\n id string\n name string\n sess *session.Session\n svc *ec2.EC2\n}\n\nfunc (a *AmazonMachineImage) CreateFromInstance(i Instance) error {\n var err error\n fmt.Fprintf(os.Stdout, \"> Creating AMI from EC2 instance...\\n\")\n out, err := a.svc.CreateImage(&ec2.CreateImageInput{\n Description: aws.String(\"description\"),\n InstanceId: aws.String(i.GetId()),\n Name: aws.String(a.name),\n })\n\n if err != nil {\n fmt.Fprintf(os.Stderr, \"! \"+err.Error()+\"\\n\")\n return err\n }\n\n a.id = *out.ImageId\n\n fmt.Fprintf(os.Stdout, \"* AMI: \" + a.id + \"\\n\")\n fmt.Fprintf(os.Stdout, \"* Name: \" + a.name + \"\\n\")\n return nil\n}\n\n\n\nfunc NewAmazonMachineImage(name string) (*AmazonMachineImage, error) {\n sess, err := session.NewSession()\n if err != nil {\n fmt.Fprintf(os.Stderr, \"! \"+err.Error()+\"\\n\")\n return nil, err\n }\n\n return &AmazonMachineImage{\n name: name,\n sess: sess,\n svc: ec2.New(sess),\n }, nil\n}\n\nfunc (a *AmazonMachineImage) WaitUntilState(s string) error ", "output": "{\n var err error\n fmt.Fprintf(os.Stdout, \"> Waiting until image is in \"+s+\" state...\\n\")\n if s == \"created\" {\n err := a.svc.WaitUntilImageAvailable(&ec2.DescribeImagesInput{\n ImageIds: []*string{&a.id},\n })\n\n p := AppDir()+\"/images/amazonmachine/\"+a.name+\".ami\"\n f, err := os.OpenFile(p, os.O_RDWR|os.O_CREATE, 0755)\n if err != nil {\n return errors.New(\"Cannnot create metadata file with AMI\")\n }\n defer f.Close()\n f.Write([]byte(a.id))\n fmt.Fprintf(os.Stdout, \"* Image metadata written to:\\n\")\n fmt.Fprintf(os.Stdout, \"* \"+p+\"\\n\")\n }\n\n if err == nil {\n return nil\n } else {\n return errors.New(\"Problem with finding \"+s+\" image\")\n }\n}"} {"input": "package pipelinerun\n\nimport (\n\t\"sort\"\n\n\t\"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1\"\n)\n\nfunc SortByNamespace(prs []v1beta1.PipelineRun) {\n\tsort.Sort(byNamespace(prs))\n}\n\ntype byNamespace []v1beta1.PipelineRun\n\n\n\nfunc (prs byNamespace) Len() int { return len(prs) }\nfunc (prs byNamespace) Swap(i, j int) { prs[i], prs[j] = prs[j], prs[i] }\nfunc (prs byNamespace) Less(i, j int) bool {\n\tvar lt, eq bool\n\tif lt, eq = prs.compareNamespace(prs[i].Namespace, prs[j].Namespace); eq {\n\t\tif prs[j].Status.StartTime == nil {\n\t\t\treturn false\n\t\t}\n\t\tif prs[i].Status.StartTime == nil {\n\t\t\treturn true\n\t\t}\n\t\treturn prs[j].Status.StartTime.Before(prs[i].Status.StartTime)\n\t}\n\treturn lt\n}\n\nfunc (prs byNamespace) compareNamespace(ins, jns string) (lt, eq bool) ", "output": "{\n\tlt, eq = ins < jns, ins == jns\n\treturn lt, eq\n}"} {"input": "package net\n\nimport (\n\t\"context\"\n\t\"testing\"\n)\n\n\n\nfunc TestCgoLookupIP(t *testing.T) ", "output": "{\n\thost := \"localhost\"\n\t_, err, ok := cgoLookupIP(host)\n\tif !ok {\n\t\tt.Errorf(\"cgoLookupIP must not be a placeholder\")\n\t}\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif _, err := goLookupIP(context.Background(), host); err != nil {\n\t\tt.Error(err)\n\t}\n}"} {"input": "package parser\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestContentDispositionParser(t *testing.T) ", "output": "{\n\tvar tvi = []string{\n\t\t\"Content-Disposition: session\\n\",\n\t\t\"Content-Disposition: render;handling=hand;optional=opt\\n\",\n\t}\n\tvar tvo = []string{\n\t\t\"Content-Disposition: session\\n\",\n\t\t\"Content-Disposition: render;handling=hand;optional=opt\\n\",\n\t}\n\n\tfor i := 0; i < len(tvi); i++ {\n\t\tshp := NewContentDispositionParser(tvi[i])\n\t\ttestHeaderParser(t, shp, tvo[i])\n\t}\n}"} {"input": "package goblueboxapi\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"testing\"\n)\n\nconst (\n\tcustomerID = \"customer_id\"\n\tapiKey = \"api_key\"\n)\n\nvar (\n\tmux *http.ServeMux\n\tclient *Client\n\tserver *httptest.Server\n)\n\nfunc setup() {\n\tmux = http.NewServeMux()\n\tserver = httptest.NewServer(mux)\n\n\tclient = NewClient(customerID, apiKey)\n\tclient.BaseURL, _ = url.Parse(server.URL)\n}\n\n\n\nfunc testMethod(t *testing.T, r *http.Request, want string) {\n\tif want != r.Method {\n\t\tt.Errorf(\"Request method = %v, want %v\", r.Method, want)\n\t}\n}\n\nfunc teardown() ", "output": "{\n\tserver.Close()\n}"} {"input": "package pdf\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\n\t\"github.com/jung-kurt/gofpdf\"\n)\n\nconst (\n\tmargin = 0\n)\n\ntype Pdf struct {\n\tdoc pdfDoc\n\tsupportedExtensions map[string]struct{}\n}\n\ntype pdfDoc interface {\n\tAddPageFormat(string, gofpdf.SizeType)\n\tClose()\n\tErr() bool\n\tError() error\n\tImage(string, float64, float64, float64, float64, bool, string, int, string)\n\tOutputFileAndClose(string) error\n\tRegisterImage(string, string) *gofpdf.ImageInfoType\n\tSetMargins(float64, float64, float64)\n}\n\n\n\nfunc (p *Pdf) AddImage(file string) error {\n\timgInfo := p.doc.RegisterImage(file, \"\")\n\tw, h := imgInfo.Extent()\n\n\tp.doc.AddPageFormat(\"Portrait\", gofpdf.SizeType{Wd: w, Ht: h})\n\tp.doc.Image(file, 0, 0, w, h, false, \"\", 0, \"\")\n\n\tif p.doc.Err() {\n\t\tp.doc.Close()\n\t\treturn fmt.Errorf(\"Error adding '%s' to PDF, %v\", file, p.doc.Error())\n\t}\n\n\treturn nil\n}\n\nfunc (p *Pdf) Supports(path string) bool {\n\t_, contains := p.supportedExtensions[filepath.Ext(path)]\n\treturn contains\n}\n\nfunc (p *Pdf) Write(dest string) error {\n\tfmt.Printf(\"Writing PDF to %s\\n\", dest)\n\treturn p.doc.OutputFileAndClose(dest)\n}\n\nfunc New() (p *Pdf) ", "output": "{\n\tp = &Pdf{\n\t\tdoc: gofpdf.NewCustom(&gofpdf.InitType{\n\t\t\tOrientationStr: \"Portrait\",\n\t\t\tUnitStr: \"pt\",\n\t\t}),\n\t\tsupportedExtensions: map[string]struct{}{\n\t\t\t\".png\": {},\n\t\t\t\".jpg\": {},\n\t\t\t\".jpeg\": {},\n\t\t},\n\t}\n\tp.doc.SetMargins(margin, margin, margin)\n\treturn\n}"} {"input": "package eval\n\nimport (\n\t\"dabble/object\"\n\t\"fmt\"\n\t\"strings\"\n)\n\nvar NilFrame *Frame = nil\n\ntype Frame struct {\n\tcaller *Function\n\tsymbol object.Symbol\n\tvalue object.Value\n\tnext *Frame\n}\n\nfunc (f *Frame) Bind(symbol object.Symbol, value object.Value) *Frame {\n\treturn &Frame{\n\t\tsymbol: symbol,\n\t\tvalue: value,\n\t\tnext: f,\n\t}\n}\n\nfunc (f *Frame) Resolve(symbol object.Symbol) object.Value {\n\tif f == nil {\n\t\treturn object.Error(fmt.Sprintf(\"symbol not bound: %q\", symbol))\n\t}\n\tif f.symbol == symbol {\n\t\treturn f.value\n\t}\n\treturn f.next.Resolve(symbol)\n}\n\nfunc (f *Frame) Call(caller *Function) *Frame {\n\treturn &Frame{\n\t\tcaller: caller,\n\t\tnext: f,\n\t}\n}\n\nfunc (f *Frame) LastCaller() *Function {\n\tif f == nil {\n\t\treturn &Function{Fn: func(_ *Frame, _ ...object.Value) object.Value {\n\t\t\treturn object.Error(fmt.Sprintf(\"no caller\"))\n\t\t}}\n\t}\n\tif f.caller != nil {\n\t\treturn f.caller\n\t}\n\treturn f.next.LastCaller()\n}\n\nfunc (f *Frame) BindAll(f2 *Frame) *Frame {\n\tfor f2 != nil {\n\t\tif f2.caller != nil {\n\t\t\tf = f.Call(f2.caller)\n\t\t} else {\n\t\t\tf = f.Bind(f2.symbol, f2.value)\n\t\t}\n\t\tf2 = f2.next\n\t}\n\treturn f\n}\n\n\n\nfunc (f *Frame) String() string ", "output": "{\n\tvar rest bool\n\tvar sb strings.Builder\n\tsb.WriteString(\"(\")\n\tfor f != nil {\n\t\tif f.caller != nil {\n\t\t\tf = f.next\n\t\t\tcontinue\n\t\t}\n\t\tif rest {\n\t\t\tsb.WriteString(\" \")\n\t\t}\n\t\tsb.WriteString(\"(\")\n\t\tsb.WriteString(f.symbol.String())\n\t\tsb.WriteString(\" \")\n\t\tsb.WriteString(f.value.String())\n\t\tsb.WriteString(\")\")\n\t\tf = f.next\n\t\trest = true\n\t}\n\tsb.WriteString(\")\")\n\treturn sb.String()\n}"} {"input": "package b\n\nimport \"a\"\n\nvar N n\n\ntype n struct{}\n\nfunc (r n) M1() int { return a.G1 }\nfunc (r n) M2() int { return a.G2 }\nfunc (r n) M3() int { return a.G3 }\nfunc (r n) M4() int { return a.G4 }\n\nfunc (r n) M6() int { return a.G6 }\nfunc (r n) M7() int { return a.G7 }\nfunc (r n) M8() int { return a.G8 }\nfunc (r n) M9() int { return a.G9 }\nfunc (r n) M10() int { return a.G10 }\n\nfunc (r n) M5() int ", "output": "{ return a.G5 }"} {"input": "package service\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetServiceIDOKCode int = 200\n\n\ntype GetServiceIDOK struct {\n\n\tPayload *models.Service `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetServiceIDOK() *GetServiceIDOK {\n\n\treturn &GetServiceIDOK{}\n}\n\n\nfunc (o *GetServiceIDOK) WithPayload(payload *models.Service) *GetServiceIDOK {\n\to.Payload = payload\n\treturn o\n}\n\n\n\n\n\nfunc (o *GetServiceIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\n\nconst GetServiceIDNotFoundCode int = 404\n\n\ntype GetServiceIDNotFound struct {\n}\n\n\nfunc NewGetServiceIDNotFound() *GetServiceIDNotFound {\n\n\treturn &GetServiceIDNotFound{}\n}\n\n\nfunc (o *GetServiceIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc (o *GetServiceIDOK) SetPayload(payload *models.Service) ", "output": "{\n\to.Payload = payload\n}"} {"input": "package apb\n\nimport (\n\t\"testing\"\n\n\tft \"github.com/openshift/ansible-service-broker/pkg/fusortest\"\n)\n\nfunc TestCreateExtraVarsNilParametersRef(t *testing.T) {\n\tcontext := &Context{Platform: \"kubernetes\", Namespace: \"testing-project\"}\n\n\tt.Log(\"calling createExtraVars\")\n\tvalue, err := createExtraVars(context, nil)\n\tif err != nil {\n\t\tt.Log(\"we have an error\")\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(value)\n\texpected := \"{\\\"namespace\\\":\\\"testing-project\\\"}\"\n\tft.AssertEqual(t, value, expected, \"invalid value on nil parameters ref\")\n}\n\nfunc TestCreateExtraVarsNilParameters(t *testing.T) {\n\tcontext := Context{Platform: \"kubernetes\", Namespace: \"testing-project\"}\n\tparameters := Parameters(nil)\n\n\tt.Log(\"calling createExtraVars\")\n\tvalue, err := createExtraVars(&context, ¶meters)\n\tif err != nil {\n\t\tt.Log(\"we have an error\")\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(value)\n\texpected := \"{\\\"namespace\\\":\\\"testing-project\\\"}\"\n\tft.AssertEqual(t, value, expected, \"invalid value on nil parameters\")\n}\n\nfunc TestCreateExtraVarsNilContextRef(t *testing.T) {\n\tparameters := &Parameters{\"key\": \"param\"}\n\n\tt.Log(\"calling createExtraVars\")\n\tvalue, err := createExtraVars(nil, parameters)\n\tif err != nil {\n\t\tt.Log(\"we have an error\")\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(value)\n\texpected := \"{\\\"key\\\":\\\"param\\\"}\"\n\tft.AssertEqual(t, value, expected, \"invalid value on empty context\")\n}\n\n\n\nfunc TestCreateExtraVars(t *testing.T) ", "output": "{\n\tcontext := &Context{Platform: \"kubernetes\", Namespace: \"testing-project\"}\n\tparameters := &Parameters{\"key\": \"param\"}\n\tvalue, err := createExtraVars(context, parameters)\n\tif err != nil {\n\t\tt.Log(\"we have an error\")\n\t\tt.Fatal(err)\n\t}\n\n\texpected := \"{\\\"key\\\":\\\"param\\\",\\\"namespace\\\":\\\"testing-project\\\"}\"\n\tft.AssertEqual(t, value, expected, \"extravars do not match\")\n}"} {"input": "package internal\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync\"\n)\n\nconst (\n\tmaxAttempts = 4\n\tmaxConcurrents = 64\n)\n\nvar sem = make(chan struct{}, maxConcurrents)\n\nfunc BulkDownload(list []string, output string) error {\n\tvar errFlag bool\n\tvar wg sync.WaitGroup\n\n\tfor _, v := range list {\n\t\twg.Add(1)\n\t\tgo func(link string) {\n\t\t\tdefer wg.Done()\n\n\t\t\tvar err error\n\t\t\tfor i := 0; i < maxAttempts; i++ {\n\t\t\t\tsem <- struct{}{}\n\t\t\t\terr = download(link, output)\n\t\t\t\t<-sem\n\t\t\t\tif err == nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Failed to download: %s\", err)\n\t\t\t\terrFlag = true\n\t\t\t}\n\t\t}(v)\n\t}\n\twg.Wait()\n\n\tif errFlag {\n\t\treturn errors.New(\"Lack of aac files\")\n\t}\n\treturn nil\n}\n\n\n\nfunc download(link, output string) error ", "output": "{\n\tresp, err := http.Get(link)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t_, fileName := filepath.Split(link)\n\tfile, err := os.Create(filepath.Join(output, fileName))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(file, resp.Body)\n\tif closeErr := file.Close(); err == nil {\n\t\terr = closeErr\n\t}\n\treturn err\n}"} {"input": "package wfe\n\nimport (\n\t\"crypto/ecdsa\"\n\t\"crypto/rsa\"\n\t\"fmt\"\n\n\t\"github.com/letsencrypt/boulder/core\"\n\t\"github.com/square/go-jose\"\n)\n\n\n\nconst (\n\tnoAlgorithmForKey = \"WFE.Errors.NoAlgorithmForKey\"\n\tinvalidJWSAlgorithm = \"WFE.Errors.InvalidJWSAlgorithm\"\n\tinvalidAlgorithmOnKey = \"WFE.Errors.InvalidAlgorithmOnKey\"\n)\n\n\n\n\n\n\nfunc checkAlgorithm(key *jose.JsonWebKey, parsedJws *jose.JsonWebSignature) (string, error) {\n\talgorithm, err := algorithmForKey(key)\n\tif err != nil {\n\t\treturn noAlgorithmForKey, err\n\t}\n\tjwsAlgorithm := parsedJws.Signatures[0].Header.Algorithm\n\tif jwsAlgorithm != algorithm {\n\t\treturn invalidJWSAlgorithm,\n\t\t\tcore.SignatureValidationError(fmt.Sprintf(\n\t\t\t\t\"algorithm '%s' in JWS header not acceptable\", jwsAlgorithm))\n\t}\n\tif key.Algorithm != \"\" && key.Algorithm != algorithm {\n\t\treturn invalidAlgorithmOnKey,\n\t\t\tcore.SignatureValidationError(fmt.Sprintf(\n\t\t\t\t\"algorithm '%s' on JWK is unacceptable\", key.Algorithm))\n\t}\n\treturn \"\", nil\n}\n\nfunc algorithmForKey(key *jose.JsonWebKey) (string, error) ", "output": "{\n\tswitch k := key.Key.(type) {\n\tcase *rsa.PublicKey:\n\t\treturn string(jose.RS256), nil\n\tcase *ecdsa.PublicKey:\n\t\tswitch k.Params().Name {\n\t\tcase \"P-256\":\n\t\t\treturn string(jose.ES256), nil\n\t\tcase \"P-384\":\n\t\t\treturn string(jose.ES384), nil\n\t\tcase \"P-521\":\n\t\t\treturn string(jose.ES512), nil\n\t\t}\n\t}\n\treturn \"\", core.SignatureValidationError(\"no signature algorithms suitable for given key type\")\n}"} {"input": "package proxy\n\nimport (\n\t\"log\"\n\t\"strconv\"\n\n\t\"../util\"\n)\n\nfunc (s *ProxyServer) handleGetWorkRPC(cs *Session, diff, id string) (reply []string, errorReply *ErrorReply) {\n\tt := s.currentBlockTemplate()\n\tif len(t.Header) == 0 {\n\t\treturn nil, &ErrorReply{Code: -1, Message: \"Work not ready\"}\n\t}\n\ttargetHex := t.Target\n\n\tif !s.rpc().Pool {\n\t\tminerDifficulty, err := strconv.ParseFloat(diff, 64)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Invalid difficulty %v from %v@%v \", diff, id, cs.ip)\n\t\t\tminerDifficulty = 5\n\t\t}\n\t\ttargetHex = util.MakeTargetHex(minerDifficulty)\n\t}\n\treply = []string{t.Header, t.Seed, targetHex}\n\treturn\n}\n\nfunc (s *ProxyServer) handleSubmitRPC(cs *Session, diff string, id string, params []string) (reply bool, errorReply *ErrorReply) {\n\tminer, ok := s.miners.Get(id)\n\tif !ok {\n\t\tminer = NewMiner(id, cs.ip)\n\t\ts.registerMiner(miner)\n\t}\n\n\tt := s.currentBlockTemplate()\n\treply = miner.processShare(s, t, diff, params)\n\treturn\n}\n\nfunc (s *ProxyServer) handleSubmitHashrate(cs *Session, req *JSONRpcReq) bool {\n\treply, _ := s.rpc().SubmitHashrate(req.Params)\n\treturn reply\n}\n\n\n\nfunc (s *ProxyServer) handleUnknownRPC(cs *Session, req *JSONRpcReq) *ErrorReply ", "output": "{\n\tlog.Printf(\"Unknown RPC method: %v\", req)\n\treturn &ErrorReply{Code: -1, Message: \"Invalid method\"}\n}"} {"input": "package scrapers\n\nimport (\n\t\"golang.org/x/net/html\"\n\t\"golang.org/x/net/html/atom\"\n\t\"io\"\n)\n\n\ntype Parser struct {\n\treader io.Reader\n\tlinks []string\n}\n\n\n\n\n\nfunc (p *Parser) Parse() error {\n\ttokenizer := html.NewTokenizer(p.reader)\n\n\tfor {\n\t\ttokenType := tokenizer.Next()\n\n\t\tswitch tokenType {\n\t\tcase html.ErrorToken:\n\t\t\terr := tokenizer.Err()\n\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\treturn err\n\n\t\tcase html.StartTagToken:\n\t\t\ttoken := tokenizer.Token()\n\n\t\t\tif token.DataAtom == atom.A {\n\t\t\t\tfor _, attribute := range token.Attr {\n\t\t\t\t\tif attribute.Key == \"href\" {\n\t\t\t\t\t\tlink := attribute.Val\n\n\t\t\t\t\t\tp.links = append(p.links, link)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nfunc (p *Parser) Links() []string {\n\treturn p.links\n}\n\nfunc NewParser(reader io.Reader) *Parser ", "output": "{\n\treturn &Parser{\n\t\treader: reader,\n\t\tlinks: make([]string, 0),\n\t}\n}"} {"input": "package proxy\n\nimport (\n\t\"github.com/fatedier/frp/models/config\"\n)\n\ntype StcpProxy struct {\n\t*BaseProxy\n\tcfg *config.StcpProxyConf\n}\n\nfunc (pxy *StcpProxy) Run() (remoteAddr string, err error) {\n\tlistener, errRet := pxy.rc.VisitorManager.Listen(pxy.GetName(), pxy.cfg.Sk)\n\tif errRet != nil {\n\t\terr = errRet\n\t\treturn\n\t}\n\tlistener.AddLogPrefix(pxy.name)\n\tpxy.listeners = append(pxy.listeners, listener)\n\tpxy.Info(\"stcp proxy custom listen success\")\n\n\tpxy.startListenHandler(pxy, HandleUserTcpConnection)\n\treturn\n}\n\nfunc (pxy *StcpProxy) GetConf() config.ProxyConf {\n\treturn pxy.cfg\n}\n\n\n\nfunc (pxy *StcpProxy) Close() ", "output": "{\n\tpxy.BaseProxy.Close()\n\tpxy.rc.VisitorManager.CloseListener(pxy.GetName())\n}"} {"input": "package rpc\n\nimport (\n\t\"testing\"\n\n\t\"github.com/cockroachdb/cockroach/util\"\n\t\"github.com/cockroachdb/cockroach/util/leaktest\"\n)\n\nfunc checkUpdateMatches(t *testing.T, network, oldAddrString, newAddrString, expAddrString string) {\n\toldAddr := util.MakeUnresolvedAddr(network, oldAddrString)\n\tnewAddr := util.MakeUnresolvedAddr(network, newAddrString)\n\texpAddr := util.MakeUnresolvedAddr(network, expAddrString)\n\n\tretAddr, err := updatedAddr(oldAddr, newAddr)\n\tif err != nil {\n\t\tt.Fatalf(\"updatedAddr failed on %v, %v: %v\", oldAddr, newAddr, err)\n\t}\n\n\tif retAddr.String() != expAddrString {\n\t\tt.Fatalf(\"updatedAddr(%v, %v) was %s; expected %s\", oldAddr, newAddr, retAddr, expAddr)\n\t}\n}\n\n\n\nfunc TestUpdatedAddr(t *testing.T) {\n\tdefer leaktest.AfterTest(t)\n\tfor _, network := range []string{\"tcp\", \"tcp4\", \"tcp6\"} {\n\t\tcheckUpdateMatches(t, network, \"localhost:0\", \"127.0.0.1:1234\", \"localhost:1234\")\n\t\tcheckUpdateMatches(t, network, \"localhost:1234\", \"127.0.0.1:1234\", \"localhost:1234\")\n\t\tcheckUpdateMatches(t, network, \"localhost:1234\", \"127.0.0.1:1235\", \"localhost:1235\")\n\t}\n\n\tcheckUpdateMatches(t, \"unix\", \"address\", \"address\", \"address\")\n\tcheckUpdateFails(t, \"unix\", \"address\", \"anotheraddress\")\n}\n\nfunc checkUpdateFails(t *testing.T, network, oldAddrString, newAddrString string) ", "output": "{\n\toldAddr := util.MakeUnresolvedAddr(network, oldAddrString)\n\tnewAddr := util.MakeUnresolvedAddr(network, newAddrString)\n\n\tretAddr, err := updatedAddr(oldAddr, newAddr)\n\tif err == nil {\n\t\tt.Fatalf(\"updatedAddr(%v, %v) should have failed; instead returned %v\", oldAddr, newAddr, retAddr)\n\t}\n}"} {"input": "package routing\n\nimport \"net/http\"\n\n\nfunc Method(method string, handler http.Handler) Matcher {\n\treturn func(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\t\tif req.Method == method {\n\t\t\thandler.ServeHTTP(resp, req)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}\n\n\nfunc GET(handler http.Handler) Matcher {\n\treturn Method(\"GET\", handler)\n}\n\n\nfunc GETFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn GET(http.HandlerFunc(handler))\n}\n\n\nfunc POST(handler http.Handler) Matcher {\n\treturn Method(\"POST\", handler)\n}\n\n\nfunc POSTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn POST(http.HandlerFunc(handler))\n}\n\n\nfunc PUT(handler http.Handler) Matcher {\n\treturn Method(\"PUT\", handler)\n}\n\n\nfunc PUTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PUT(http.HandlerFunc(handler))\n}\n\n\nfunc PATCH(handler http.Handler) Matcher {\n\treturn Method(\"PATCH\", handler)\n}\n\n\nfunc PATCHFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PATCH(http.HandlerFunc(handler))\n}\n\n\n\n\n\nfunc DELETEFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn DELETE(http.HandlerFunc(handler))\n}\n\n\n\nfunc MethodNotAllowed(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\tresp.WriteHeader(405)\n\treturn true\n}\n\nfunc DELETE(handler http.Handler) Matcher ", "output": "{\n\treturn Method(\"DELETE\", handler)\n}"} {"input": "package binmsg\n\nimport (\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/juju/errors\"\n)\n\nvar referenceTime time.Time\n\nconst refTimeString = \"2305-01-01T00:00:00Z\"\n\nfunc init() {\n\tinitBinMsg()\n}\n\n\n\nfunc initBinMsg() ", "output": "{\n\treferenceTime, _ = time.Parse(time.RFC3339, refTimeString)\n\treferenceTime = referenceTime.UTC()\n\tErrPayloadSizeTooSmall = errors.New(\n\t\t\"The payload size is less than \" + strconv.Itoa(PayloadOctets) +\n\t\t\t\" bytes long.\")\n}"} {"input": "package utils\n\nimport \"syscall\"\n\n\n\n\n\n\n\nfunc getFdLimit() (int, error) {\n\tvar limit syscall.Rlimit\n\tif err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {\n\t\treturn 0, err\n\t}\n\treturn int(limit.Cur), nil\n}\n\nfunc raiseFdLimit(max uint64) error ", "output": "{\n\tvar limit syscall.Rlimit\n\tif err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {\n\t\treturn err\n\t}\n\tlimit.Cur = limit.Max\n\tif limit.Cur > max {\n\t\tlimit.Cur = max\n\t}\n\tif err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package exif\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\n\nfunc toUint16(bo binary.ByteOrder, buf []byte) uint16 {\n\tvar i uint16\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}\n\n\n\n\n\nfunc toUint32(bo binary.ByteOrder, buf []byte) uint32 {\n\tvar i uint32\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}\n\n\nfunc toInt32(bo binary.ByteOrder, buf []byte) int32 {\n\tvar i int32\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}\n\nfunc toInt16(bo binary.ByteOrder, buf []byte) int16 ", "output": "{\n\tvar i int16\n\tb := bytes.NewReader(buf)\n\terr := binary.Read(b, bo, &i)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\treturn i\n}"} {"input": "package restinspectorhandler\n\nimport (\n\tlog \"github.com/cihub/seelog\"\n\t. \"github.com/osrg/earthquake/earthquake/entity\"\n\t. \"github.com/osrg/earthquake/earthquake/inspectorhandler/restinspectorhandler/queue\"\n\t. \"github.com/osrg/earthquake/earthquake/signal\"\n)\n\nfunc registerNewEntity(entityID string) (*TransitionEntity, *ActionQueue, error) {\n\tlog.Debugf(\"Registering entity: %s\", entityID)\n\tentity := TransitionEntity{\n\t\tID: entityID,\n\t\tActionFromMain: make(chan Action),\n\t\tEventToMain: make(chan Event),\n\t}\n\tif err := RegisterTransitionEntity(&entity); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tqueue, err := RegisterNewQueue(entityID)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tpropagateActionFromMain(&entity, queue)\n\t\t}\n\t}()\n\tlog.Debugf(\"Registered entity: %s\", entityID)\n\treturn &entity, queue, nil\n}\n\n\n\nfunc propagateActionFromMain(entity *TransitionEntity, queue *ActionQueue) {\n\tlog.Debugf(\"Handler[%s]<-Main: receiving an action\", entity.ID)\n\taction := <-entity.ActionFromMain\n\tlog.Debugf(\"Handler[%s]<-Main: received an action %s\", entity.ID, action)\n\tqueue.Put(action)\n}\n\nfunc sendEventToMain(entity *TransitionEntity, event Event) ", "output": "{\n\tlog.Debugf(\"Handler[%s]->Main: sending an event %s\", entity.ID, event)\n\tsentToEntityCh := make(chan bool)\n\tsentToMainCh := make(chan bool)\n\tgo func() {\n\t\tentity.EventToMain <- event\n\t\tsentToEntityCh <- true\n\t}()\n\tgo func() {\n\t\tmainReadyEntityCh <- entity\n\t\tsentToMainCh <- true\n\t}()\n\t<-sentToEntityCh\n\t<-sentToMainCh\n\tlog.Debugf(\"Handler[%s]->Main: sent event %s\", entity.ID, event)\n}"} {"input": "package dax\n\n\ntype Grapher interface {\n\tGetParent() Grapher\n\tAddChild(child Grapher)\n\tGetChildren() []Grapher\n}\n\ntype nodeStack struct {\n\tnodes []Grapher\n}\n\nfunc (s *nodeStack) Init() {\n\ts.nodes = make([]Grapher, 0, 16)\n}\n\n\n\nfunc (s *nodeStack) Push(n Grapher) {\n\ts.nodes = append(s.nodes, n)\n}\n\nfunc (s *nodeStack) Pop() Grapher {\n\ti := len(s.nodes) - 1\n\tn := s.nodes[i]\n\ts.nodes[i] = nil\n\ts.nodes = s.nodes[:i]\n\treturn n\n}\n\ntype SceneGraph struct {\n\tNode\n}\n\nfunc NewSceneGraph() *SceneGraph {\n\tsg := new(SceneGraph)\n\tsg.Init()\n\treturn sg\n}\n\nfunc (sg *SceneGraph) Init() {\n\tsg.Node.Init()\n}\n\nfunc (sg *SceneGraph) updateWorldTransform() {\n\tsg.Node.updateWorldTransform(false)\n}\n\nfunc (sg *SceneGraph) Update(time float64) {\n\tsg.updateWorldTransform()\n}\n\n\nfunc (sg *SceneGraph) Traverse() <-chan Grapher {\n\tch := make(chan Grapher)\n\n\tgo func() {\n\t\tvar stack nodeStack\n\n\t\tstack.Init()\n\t\tstack.Push(sg)\n\n\t\tfor !stack.Empty() {\n\t\t\tn := stack.Pop()\n\t\t\tch <- n\n\t\t\tchildren := n.GetChildren()\n\t\t\tfor i := len(children) - 1; i >= 0; i-- {\n\t\t\t\tstack.Push(children[i])\n\t\t\t}\n\t\t}\n\t\tclose(ch)\n\t}()\n\n\treturn ch\n}\n\nfunc (sg *SceneGraph) Draw(fb Framebuffer) {\n\tfb.render().drawSceneGraph(fb, sg)\n}\n\nfunc (s *nodeStack) Empty() bool ", "output": "{\n\treturn len(s.nodes) == 0\n}"} {"input": "package factor\n\nimport (\n\t\"github.com/jesand/stats\"\n\t\"github.com/jesand/stats/dist\"\n\t\"github.com/jesand/stats/variable\"\n)\n\n\n\n\ntype Factor interface {\n\n\tAdjacent() []variable.RandomVariable\n\n\tScore() float64\n}\n\n\n\n\nfunc NewDistFactor(vars []variable.RandomVariable, distr dist.Dist) *DistFactor {\n\treturn &DistFactor{\n\t\tVars: vars,\n\t\tDist: distr,\n\t}\n}\n\n\ntype DistFactor struct {\n\tVars []variable.RandomVariable\n\tDist dist.Dist\n}\n\n\nfunc (factor DistFactor) Adjacent() []variable.RandomVariable {\n\treturn factor.Vars\n}\n\n\nfunc (factor DistFactor) Score() float64 {\n\tvar (\n\t\tnumVars = factor.Dist.NumVars()\n\t\tnumParams = factor.Dist.NumParams()\n\t)\n\tif len(factor.Vars) != numVars+numParams {\n\t\tpanic(stats.ErrfFactorVarNum(numVars, numParams, len(factor.Vars)))\n\t}\n\tvar (\n\t\tvars = make([]float64, numVars)\n\t\tparams = make([]float64, numParams)\n\t)\n\tfor i, rv := range factor.Vars {\n\t\tif i < len(vars) {\n\t\t\tvars[i] = rv.Val()\n\t\t} else {\n\t\t\tparams[i-len(vars)] = rv.Val()\n\t\t}\n\t}\n\treturn factor.Dist.Score(vars, params)\n}\n\n\n\n\n\ntype ConstFactor struct {\n\tVars []variable.RandomVariable\n\tValue float64\n}\n\n\nfunc (factor ConstFactor) Adjacent() []variable.RandomVariable {\n\treturn factor.Vars\n}\n\n\nfunc (factor ConstFactor) Score() float64 {\n\treturn factor.Value\n}\n\nfunc NewConstFactor(vars []variable.RandomVariable, value float64) *ConstFactor ", "output": "{\n\treturn &ConstFactor{\n\t\tVars: vars,\n\t\tValue: value,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"path/filepath\"\n\n\t\"github.com/xeipuuv/gojsonschema\"\n)\n\ntype jsonschema map[string]gojsonschema.JSONLoader\n\nvar schemas = []string{\n\t\"notification\",\n}\n\nfunc newJSONSchema() *jsonschema {\n\tjs := &jsonschema{}\n\n\tfor _, name := range schemas {\n\t\tpath, err := filepath.Abs(name)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\t(*js)[name] = gojsonschema.NewReferenceLoader(\"file://\" + path + \".json\")\n\t}\n\n\treturn js\n}\n\n\n\nfunc (js *jsonschema) validateJSON(jsonType, json string) bool ", "output": "{\n\tloader := gojsonschema.NewStringLoader(json)\n\tschemaLoader, ok := (*js)[jsonType]\n\tif !ok {\n\t\treturn false\n\t}\n\n\tresult, err := gojsonschema.Validate(schemaLoader, loader)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn result.Valid()\n}"} {"input": "package nosurf\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\tpathModule \"path\"\n\t\"reflect\"\n\t\"regexp\"\n)\n\n\n\n\n\n\n\n\n\n\nfunc (h *CSRFHandler) ExemptPath(path string) {\n\th.exemptPaths = append(h.exemptPaths, path)\n}\n\n\nfunc (h *CSRFHandler) ExemptPaths(paths ...string) {\n\tfor _, v := range paths {\n\t\th.ExemptPath(v)\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (h *CSRFHandler) ExemptGlob(pattern string) {\n\th.exemptGlobs = append(h.exemptGlobs, pattern)\n}\n\n\nfunc (h *CSRFHandler) ExemptGlobs(patterns ...string) {\n\tfor _, v := range patterns {\n\t\th.ExemptGlob(v)\n\t}\n}\n\n\n\n\n\n\nfunc (h *CSRFHandler) ExemptRegexp(re interface{}) {\n\tvar compiled *regexp.Regexp\n\n\tswitch re.(type) {\n\tcase string:\n\t\tcompiled = regexp.MustCompile(re.(string))\n\tcase *regexp.Regexp:\n\t\tcompiled = re.(*regexp.Regexp)\n\tdefault:\n\t\terr := fmt.Sprintf(\"%v isn't a valid type for ExemptRegexp()\", reflect.TypeOf(re))\n\t\tpanic(err)\n\t}\n\n\th.exemptRegexps = append(h.exemptRegexps, compiled)\n}\n\n\nfunc (h *CSRFHandler) ExemptRegexps(res ...interface{}) {\n\tfor _, v := range res {\n\t\th.ExemptRegexp(v)\n\t}\n}\n\nfunc (h *CSRFHandler) ExemptFunc(fn func(r *http.Request) bool) {\n\th.exemptFunc = fn\n}\n\nfunc (h *CSRFHandler) IsExempt(r *http.Request) bool ", "output": "{\n\tif h.exemptFunc != nil && h.exemptFunc(r) {\n\t\treturn true\n\t}\n\n\tpath := r.URL.Path\n\tif sContains(h.exemptPaths, path) {\n\t\treturn true\n\t}\n\n\tfor _, glob := range h.exemptGlobs {\n\t\tmatched, err := pathModule.Match(glob, path)\n\t\tif matched && err == nil {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tfor _, re := range h.exemptRegexps {\n\t\tif re.MatchString(path) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package todoist\n\nimport \"fmt\"\n\ntype IntBool bool\n\nfunc (i IntBool) Bool() bool {\n\tif i {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\n\n\nfunc (i *IntBool) UnmarshalJSON(b []byte) (err error) {\n\tswitch string(b) {\n\tcase \"1\":\n\t\t*i = true\n\tcase \"0\":\n\t\t*i = false\n\tdefault:\n\t\treturn fmt.Errorf(\"Could not unmarshal into intbool: %s\", string(b))\n\t}\n\treturn nil\n}\n\ntype ColorStringer interface {\n\tString() string\n\tColorString() string\n}\n\ntype NoColorString struct {\n\ts string\n}\n\nfunc NewNoColorString(s string) NoColorString {\n\treturn NoColorString{s}\n}\n\nfunc (n NoColorString) String() string {\n\treturn n.s\n}\n\nfunc (n NoColorString) ColorString() string {\n\treturn n.s\n}\n\nfunc (i IntBool) MarshalJSON() ([]byte, error) ", "output": "{\n\tif i {\n\t\treturn []byte(\"1\"), nil\n\t} else {\n\t\treturn []byte(\"0\"), nil\n\t}\n}"} {"input": "package version\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n)\n\nvar (\n\tVersion = \"Not provided.\"\n\tGitSHA = \"Not provided.\"\n\tBuilt = \"Not provided.\"\n)\n\n\nfunc PrintVersionAndExit(apiVersion string) {\n\tfor _, i := range Info(apiVersion) {\n\t\tfmt.Printf(\"%v\\n\", i)\n\t}\n\tos.Exit(0)\n}\n\n\n\n\nfunc Info(apiVersion string) []string ", "output": "{\n\treturn []string{\n\t\tfmt.Sprintf(\"API Version: %s\", apiVersion),\n\t\tfmt.Sprintf(\"Version: %s\", Version),\n\t\tfmt.Sprintf(\"Git SHA: %s\", GitSHA),\n\t\tfmt.Sprintf(\"Built At: %s\", Built),\n\t\tfmt.Sprintf(\"Go Version: %s\", runtime.Version()),\n\t\tfmt.Sprintf(\"Go OS/Arch: %s/%s\", runtime.GOOS, runtime.GOARCH),\n\t}\n}"} {"input": "package sysinfo\n\nimport (\n\t\"runtime\"\n\t\"unsafe\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\n\n\n\nfunc numCPU() int {\n\tpid, _, _ := unix.RawSyscall(unix.SYS_GETPID, 0, 0, 0)\n\n\tvar mask [1024 / 64]uintptr\n\t_, _, err := unix.RawSyscall(unix.SYS_SCHED_GETAFFINITY, pid, uintptr(len(mask)*8), uintptr(unsafe.Pointer(&mask[0])))\n\tif err != 0 {\n\t\treturn 0\n\t}\n\n\tncpu := 0\n\tfor _, e := range mask {\n\t\tif e == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tncpu += int(popcnt(uint64(e)))\n\t}\n\treturn ncpu\n}\n\n\n\n\nfunc NumCPU() int ", "output": "{\n\tif ncpu := numCPU(); ncpu > 0 {\n\t\treturn ncpu\n\t}\n\treturn runtime.NumCPU()\n}"} {"input": "package whisper\n\nimport \"github.com/Tzunami/go-earthdollar/crypto\"\n\n\n\n\ntype Topic [4]byte\n\n\n\n\n\n\n\n\nfunc NewTopics(data ...[]byte) []Topic {\n\ttopics := make([]Topic, len(data))\n\tfor i, element := range data {\n\t\ttopics[i] = NewTopic(element)\n\t}\n\treturn topics\n}\n\n\nfunc (self *Topic) String() string {\n\treturn string(self[:])\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype topicMatcher struct {\n\tconditions []map[Topic]struct{}\n}\n\n\nfunc newTopicMatcher(topics ...[]Topic) *topicMatcher {\n\tmatcher := make([]map[Topic]struct{}, len(topics))\n\tfor i, condition := range topics {\n\t\tmatcher[i] = make(map[Topic]struct{})\n\t\tfor _, topic := range condition {\n\t\t\tmatcher[i][topic] = struct{}{}\n\t\t}\n\t}\n\treturn &topicMatcher{conditions: matcher}\n}\n\n\nfunc (self *topicMatcher) Matches(topics []Topic) bool {\n\tif len(self.conditions) > len(topics) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(topics) && i < len(self.conditions); i++ {\n\t\tif len(self.conditions[i]) > 0 {\n\t\t\tif _, ok := self.conditions[i][topics[i]]; !ok {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\nfunc NewTopic(data []byte) Topic ", "output": "{\n\tprefix := [4]byte{}\n\tcopy(prefix[:], crypto.Keccak256(data)[:4])\n\treturn Topic(prefix)\n}"} {"input": "package providers\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"net/url\"\n\t\"strings\"\n)\n\ntype GoogleProvider struct {\n\t*ProviderData\n}\n\n\n\nfunc (s *GoogleProvider) GetEmailAddress(body []byte, access_token string) (string, error) {\n\tvar response struct {\n\t\tIdToken string `json:\"id_token\"`\n\t}\n\n\tif err := json.Unmarshal(body, &response); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tjwt := strings.Split(response.IdToken, \".\")\n\tb, err := jwtDecodeSegment(jwt[1])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar email struct {\n\t\tEmail string `json:\"email\"`\n\t}\n\terr = json.Unmarshal(b, &email)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif email.Email == \"\" {\n\t\treturn \"\", errors.New(\"missing email\")\n\t}\n\treturn email.Email, nil\n}\n\nfunc jwtDecodeSegment(seg string) ([]byte, error) {\n\tif l := len(seg) % 4; l > 0 {\n\t\tseg += strings.Repeat(\"=\", 4-l)\n\t}\n\n\treturn base64.URLEncoding.DecodeString(seg)\n}\n\nfunc (p *GoogleProvider) ValidateToken(access_token string) bool {\n\treturn validateToken(p, access_token, nil)\n}\n\nfunc NewGoogleProvider(p *ProviderData) *GoogleProvider ", "output": "{\n\tp.ProviderName = \"Google\"\n\tif p.LoginUrl.String() == \"\" {\n\t\tp.LoginUrl = &url.URL{Scheme: \"https\",\n\t\t\tHost: \"accounts.google.com\",\n\t\t\tPath: \"/o/oauth2/auth\"}\n\t}\n\tif p.RedeemUrl.String() == \"\" {\n\t\tp.RedeemUrl = &url.URL{Scheme: \"https\",\n\t\t\tHost: \"accounts.google.com\",\n\t\t\tPath: \"/o/oauth2/token\"}\n\t}\n\tif p.ValidateUrl.String() == \"\" {\n\t\tp.ValidateUrl = &url.URL{Scheme: \"https\",\n\t\t\tHost: \"www.googleapis.com\",\n\t\t\tPath: \"/oauth2/v1/tokeninfo\"}\n\t}\n\tif p.Scope == \"\" {\n\t\tp.Scope = \"profile email\"\n\t}\n\treturn &GoogleProvider{ProviderData: p}\n}"} {"input": "package openid\n\nimport (\n\t\"testing\"\n\t\"bytes\"\n)\n\n\n\ntype NormalizeIdentifierTest struct {\n\tin, out string\n\tt int\n}\n\nvar NormalizeIdentifierTests = []NormalizeIdentifierTest{\n\tNormalizeIdentifierTest{\"https://example.com/\", \"https://example.com/\", IdentifierURL},\n\tNormalizeIdentifierTest{\"http://example.com/user\", \"http://example.com/user\", IdentifierURL},\n\tNormalizeIdentifierTest{\"http://example.com/user/\", \"http://example.com/user/\", IdentifierURL},\n\tNormalizeIdentifierTest{\"http://example.com/\", \"http://example.com/\", IdentifierURL},\n\tNormalizeIdentifierTest{\"=example\", \"=example\", IdentifierXRI},\n\tNormalizeIdentifierTest{\"xri://=example\", \"=example\", IdentifierXRI},\n}\n\nfunc TestNormalizeIdentifier(testing *testing.T) {\n\tfor _, nit := range NormalizeIdentifierTests {\n\t\tv, t := NormalizeIdentifier(nit.in)\n\t\tif !bytes.Equal([]byte(v), []byte(nit.out)) || t != nit.t {\n\t\t\ttesting.Errorf(\"NormalizeIdentifier(%s) = (%s, %d) want (%s, %d).\", nit.in, v, t, nit.out, nit.t)\n\t\t}\n\t}\n}\n\n\n\nvar Identifiers = []string{\n\t\"https://www.google.com/accounts/o8/id\",\n\t\"orange.fr\",\n\t\"yahoo.com\",\n}\n\n\n\n\nfunc TestGetRedirectURL(t *testing.T) ", "output": "{\n\tfor _, url := range Identifiers {\n\t\t_, err := GetRedirectURL(url, \"http://example.com\", \"/loginCheck\")\n\t\tif err != nil {\n\t\t\tt.Errorf(\"GetRedirectURL() returned the error: %s\", err.String())\n\t\t}\n\t}\n}"} {"input": "package opcodes\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/PMoneda/hub/lang\"\n)\n\n\n\ntype Print struct {\n\tOp interface{}\n}\n\n\nfunc (opcode Print) ToString() string {\n\tswitch v := opcode.Op.(type) {\n\tcase lang.Pointer:\n\t\treturn \"print $\" + v.ToString()\n\tcase lang.Number:\n\t\treturn \"print #\" + v.ToString()\n\tcase string:\n\t\treturn \"print \" + v\n\tdefault:\n\t\treturn \"print\"\n\t}\n}\n\n\n\n\nfunc (opcode Print) Execute() ", "output": "{\n\tfmt.Println(\"Execute Print\")\n}"} {"input": "package insights\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/\" + version.Number + \" insights/2018-09-01\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package cache\n\nimport (\n\t\"k8s.io/client-go/1.5/pkg/util/clock\"\n\t\"k8s.io/client-go/1.5/pkg/util/sets\"\n)\n\ntype fakeThreadSafeMap struct {\n\tThreadSafeStore\n\tdeletedKeys chan<- string\n}\n\nfunc (c *fakeThreadSafeMap) Delete(key string) {\n\tif c.deletedKeys != nil {\n\t\tc.ThreadSafeStore.Delete(key)\n\t\tc.deletedKeys <- key\n\t}\n}\n\ntype FakeExpirationPolicy struct {\n\tNeverExpire sets.String\n\tRetrieveKeyFunc KeyFunc\n}\n\nfunc (p *FakeExpirationPolicy) IsExpired(obj *timestampedEntry) bool {\n\tkey, _ := p.RetrieveKeyFunc(obj)\n\treturn !p.NeverExpire.Has(key)\n}\n\n\n\nfunc NewFakeExpirationStore(keyFunc KeyFunc, deletedKeys chan<- string, expirationPolicy ExpirationPolicy, cacheClock clock.Clock) Store ", "output": "{\n\tcacheStorage := NewThreadSafeStore(Indexers{}, Indices{})\n\treturn &ExpirationCache{\n\t\tcacheStorage: &fakeThreadSafeMap{cacheStorage, deletedKeys},\n\t\tkeyFunc: keyFunc,\n\t\tclock: cacheClock,\n\t\texpirationPolicy: expirationPolicy,\n\t}\n}"} {"input": "package structs\n\nimport \"fmt\"\n\n\ntype Bitmap []byte\n\n\nfunc NewBitmap(size uint) (Bitmap, error) {\n\tif size == 0 {\n\t\treturn nil, fmt.Errorf(\"bitmap must be positive size\")\n\t}\n\tif size&7 != 0 {\n\t\treturn nil, fmt.Errorf(\"bitmap must be byte aligned\")\n\t}\n\tb := make([]byte, size>>3)\n\treturn Bitmap(b), nil\n}\n\n\nfunc (b Bitmap) Copy() (Bitmap, error) {\n\tif b == nil {\n\t\treturn nil, fmt.Errorf(\"can't copy nil Bitmap\")\n\t}\n\n\traw := make([]byte, len(b))\n\tcopy(raw, b)\n\treturn Bitmap(raw), nil\n}\n\n\nfunc (b Bitmap) Size() uint {\n\treturn uint(len(b) << 3)\n}\n\n\n\n\n\nfunc (b Bitmap) Check(idx uint) bool {\n\tbucket := idx >> 3\n\tmask := byte(1 << (idx & 7))\n\treturn (b[bucket] & mask) != 0\n}\n\n\nfunc (b Bitmap) Clear() {\n\tfor i := range b {\n\t\tb[i] = 0\n\t}\n}\n\n\n\nfunc (b Bitmap) IndexesInRange(set bool, from, to uint) []int {\n\tvar indexes []int\n\tfor i := from; i < to; i++ {\n\t\tc := b.Check(i)\n\t\tif c && set || !c && !set {\n\t\t\tindexes = append(indexes, int(i))\n\t\t}\n\t}\n\n\treturn indexes\n}\n\nfunc (b Bitmap) Set(idx uint) ", "output": "{\n\tbucket := idx >> 3\n\tmask := byte(1 << (idx & 7))\n\tb[bucket] |= mask\n}"} {"input": "package geom\n\nimport \"math\"\n\n\ntype MultiLineString []LineString\n\n\n\n\n\nfunc (ml MultiLineString) Length() float64 {\n\tlength := 0.\n\tfor _, l := range ml {\n\t\tlength += l.Length()\n\t}\n\treturn length\n}\n\n\nfunc (ml MultiLineString) Within(p Polygonal) WithinStatus {\n\tfor _, l := range ml {\n\t\tif l.Within(p) == Outside {\n\t\t\treturn Outside\n\t\t}\n\t}\n\treturn Inside\n}\n\n\nfunc (ml MultiLineString) Distance(p Point) float64 {\n\td := math.Inf(1)\n\tfor _, l := range ml {\n\t\tlDist := l.Distance(p)\n\t\td = math.Min(d, lDist)\n\t}\n\treturn d\n}\n\nfunc (ml MultiLineString) Bounds() *Bounds ", "output": "{\n\tb := NewBounds()\n\tfor _, l := range ml {\n\t\tb.Extend(l.Bounds())\n\t}\n\treturn b\n}"} {"input": "package gorequest\n\nimport (\n \"time\"\n \"net/http\"\n)\n\n\n\n\nfunc (s *SuperAgent) safeModifyHttpClient() {\n if !s.isClone {\n return\n }\n oldClient := s.Client\n s.Client = &http.Client{}\n s.Client.Jar = oldClient.Jar\n s.Client.Transport = oldClient.Transport\n s.Client.Timeout = oldClient.Timeout\n s.Client.CheckRedirect = oldClient.CheckRedirect\n}\n\n\n\n\nfunc (s *SuperAgent) Timeout(timeout time.Duration) *SuperAgent ", "output": "{\n s.safeModifyHttpClient()\n s.Client.Timeout = timeout\n return s\n}"} {"input": "package server\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n)\n\ntype Rest struct {\n\tchannels map[string]*Channel\n}\n\nfunc NewRestServer(server *Server) *Rest {\n\treturn &Rest{server.channels}\n}\n\nfunc (self *Rest) PostOnly(h http.HandlerFunc) http.HandlerFunc {\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == \"POST\" {\n\t\t\th(w, r)\n\t\t\treturn\n\t\t}\n\t\thttp.Error(w, \"post only\", http.StatusMethodNotAllowed)\n\t}\n}\n\nfunc (self *Rest) restHandler(w http.ResponseWriter, r *http.Request) {\n\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err := r.Body.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\tchannel := r.URL.Query().Get(\"channel\")\n\tsession := r.Header.Get(\"session\");\n\n\tlog.Printf(\"SessionID: %s\", session)\n\n\tmsg := &Message{Channel: channel, Body: string(body), session: session}\n\tif ch, ok := self.channels[channel]; ok {\n\t\tch.sendAll <- msg\n\t}\n\tlog.Printf(\"[REST] body: %s, channel: %s\", body, channel)\n}\n\n\n\nfunc (self *Rest) ListenRest() ", "output": "{\n\n\tlog.Println(\"Listening server(REST)...\")\n\n\thttp.HandleFunc(\"/rest\", self.PostOnly(self.restHandler))\n}"} {"input": "package gogs\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\nfunc (c *Client) AdminCreateOrg(user string, opt CreateOrgOption) (*Organization, error) {\n\tbody, err := json.Marshal(&opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\torg := new(Organization)\n\treturn org, c.getParsedResponse(\"POST\", fmt.Sprintf(\"/admin/users/%s/orgs\", user),\n\t\tjsonHeader, bytes.NewReader(body), org)\n}\n\nfunc (c *Client) AdminCreateTeam(user string, opt CreateTeamOption) (*Team, error) {\n\tbody, err := json.Marshal(&opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tteam := new(Team)\n\treturn team, c.getParsedResponse(\"POST\", fmt.Sprintf(\"/admin/orgs/%s/teams\", user),\n\t\tjsonHeader, bytes.NewReader(body), team)\n}\n\n\n\nfunc (c *Client) AdminAddTeamRepository(teamID int64, repo string) error {\n\t_, err := c.getResponse(\"PUT\", fmt.Sprintf(\"/admin/teams/%d/repos/%s\", teamID, repo),\n\t\tjsonHeader, nil)\n\treturn err\n}\n\nfunc (c *Client) AdminAddTeamMembership(teamID int64, user string) error ", "output": "{\n\t_, err := c.getResponse(\"PUT\", fmt.Sprintf(\"/admin/teams/%d/members/%s\", teamID, user),\n\t\tjsonHeader, nil)\n\treturn err\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"os\"\n)\n\ntype OutputText struct {\n\tgetText func(string)string \n}\n\nfunc NewOutputText(getText func(string)string) *OutputText { \n\treturn &OutputText{ getText }\n}\n\n\n\nfunc (ot *OutputText) InPort(data string) ", "output": "{\n\tfmt.Fprintln(os.Stderr, ot.getText(data)) \n}"} {"input": "package main\n\nimport (\n\t\"../contrail\"\n\tlog \"../logging\"\n\t\"github.com/containernetworking/cni/pkg/skel\"\n\t\"github.com/containernetworking/cni/pkg/version\"\n)\n\n\nfunc getPodInfo(skelArgs *skel.CmdArgs) (string, string, error) {\n\treturn skelArgs.ContainerID, skelArgs.ContainerID, nil\n}\n\n\n\n\n\nfunc CmdDel(skelArgs *skel.CmdArgs) error {\n\tcni, err := contrailCni.Init(skelArgs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\"Came in Del for container %s\", skelArgs.ContainerID)\n\tcontainerUuid, containerName, err := getPodInfo(skelArgs)\n\tif err != nil {\n\t\tlog.Errorf(\"Error getting UUID/Name for Container\")\n\t\treturn err\n\t}\n\n\tcni.Update(containerName, containerUuid, \"\")\n\tcni.Log()\n\n\terr = cni.CmdDel()\n\tif err != nil {\n\t\tlog.Errorf(\"Failed processing Add command.\")\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\tskel.PluginMain(CmdAdd, CmdDel,\n\t\tversion.PluginSupports(contrailCni.CniVersion))\n}\n\nfunc CmdAdd(skelArgs *skel.CmdArgs) error ", "output": "{\n\tcni, err := contrailCni.Init(skelArgs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\"Came in Add for container %s\", skelArgs.ContainerID)\n\tcontainerUuid, containerName, err := getPodInfo(skelArgs)\n\tif err != nil {\n\t\tlog.Errorf(\"Error getting UUID/Name for Container\")\n\t\treturn err\n\t}\n\n\tcni.Update(containerName, containerUuid, \"\")\n\tcni.Log()\n\n\terr = cni.CmdAdd()\n\tif err != nil {\n\t\tlog.Errorf(\"Failed processing Add command.\")\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package service \nimport (\n\t\"github.com/docker/docker/pkg/idtools\"\n\t\"github.com/docker/docker/volume\"\n\t\"github.com/docker/docker/volume/drivers\"\n\t\"github.com/docker/docker/volume/local\"\n\t\"github.com/pkg/errors\"\n)\n\n\n\nfunc setupDefaultDriver(store *drivers.Store, root string, rootIDs idtools.Identity) error ", "output": "{\n\td, err := local.New(root, rootIDs)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error setting up default driver\")\n\t}\n\tif !store.Register(d, volume.DefaultDriverName) {\n\t\treturn errors.New(\"local volume driver could not be registered\")\n\t}\n\treturn nil\n}"} {"input": "package storage\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n)\n\n\n\nfunc FSIGDescribe(text string, body func()) bool {\n\treturn FDescribe(\"[sig-storage] \"+text, body)\n}\n\nfunc SIGDescribe(text string, body func()) bool ", "output": "{\n\treturn Describe(\"[sig-storage] \"+text, body)\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\n\n\n\ntype MsgFilterClear struct{}\n\n\n\nfunc (msg *MsgFilterClear) MsgDecode(r io.Reader, pver uint32) error {\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filterclear message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterClear.MsgDecode\", str)\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (msg *MsgFilterClear) MsgEncode(w io.Writer, pver uint32) error {\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filterclear message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterClear.MsgEncode\", str)\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (msg *MsgFilterClear) Command() string {\n\treturn CmdFilterClear\n}\n\n\n\n\n\n\n\nfunc NewMsgFilterClear() *MsgFilterClear {\n\treturn &MsgFilterClear{}\n}\n\nfunc (msg *MsgFilterClear) MaxPayloadLength(pver uint32) uint32 ", "output": "{\n\treturn 0\n}"} {"input": "package raft\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\n\n\nfunc mustTemp(pre, body string) string {\n\tf, err := os.CreateTemp(\"\", pre)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, err = io.Copy(f, strings.NewReader(body))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tf.Close()\n\treturn f.Name()\n}\n\nfunc ltoa(l *raftLog) string {\n\ts := fmt.Sprintf(\"committed: %d\\n\", l.committed)\n\ts += fmt.Sprintf(\"applied: %d\\n\", l.applied)\n\tfor i, e := range l.allEntries() {\n\t\ts += fmt.Sprintf(\"#%d: %+v\\n\", i, e)\n\t}\n\treturn s\n}\n\nfunc diffu(a, b string) string ", "output": "{\n\tif a == b {\n\t\treturn \"\"\n\t}\n\taname, bname := mustTemp(\"base\", a), mustTemp(\"other\", b)\n\tdefer os.Remove(aname)\n\tdefer os.Remove(bname)\n\tcmd := exec.Command(\"diff\", \"-u\", aname, bname)\n\tbuf, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tif _, ok := err.(*exec.ExitError); ok {\n\t\t\treturn string(buf)\n\t\t}\n\t\tpanic(err)\n\t}\n\treturn string(buf)\n}"} {"input": "package echo\n\ntype (\n\tGroup struct {\n\t\techo Echo\n\t}\n)\n\nfunc (g *Group) Use(m ...Middleware) {\n\tfor _, h := range m {\n\t\tg.echo.middleware = append(g.echo.middleware, wrapMiddleware(h))\n\t}\n}\n\nfunc (g *Group) Connect(path string, h Handler) {\n\tg.echo.Connect(path, h)\n}\n\nfunc (g *Group) Delete(path string, h Handler) {\n\tg.echo.Delete(path, h)\n}\n\nfunc (g *Group) Get(path string, h Handler) {\n\tg.echo.Get(path, h)\n}\n\nfunc (g *Group) Head(path string, h Handler) {\n\tg.echo.Head(path, h)\n}\n\nfunc (g *Group) Options(path string, h Handler) {\n\tg.echo.Options(path, h)\n}\n\nfunc (g *Group) Patch(path string, h Handler) {\n\tg.echo.Patch(path, h)\n}\n\nfunc (g *Group) Post(path string, h Handler) {\n\tg.echo.Post(path, h)\n}\n\nfunc (g *Group) Put(path string, h Handler) {\n\tg.echo.Put(path, h)\n}\n\nfunc (g *Group) Trace(path string, h Handler) {\n\tg.echo.Trace(path, h)\n}\n\nfunc (g *Group) WebSocket(path string, h HandlerFunc) {\n\tg.echo.WebSocket(path, h)\n}\n\nfunc (g *Group) Static(path, root string) {\n\tg.echo.Static(path, root)\n}\n\nfunc (g *Group) ServeDir(path, root string) {\n\tg.echo.ServeDir(path, root)\n}\n\n\n\nfunc (g *Group) Group(prefix string, m ...Middleware) *Group {\n\treturn g.echo.Group(prefix, m...)\n}\n\nfunc (g *Group) ServeFile(path, file string) ", "output": "{\n\tg.echo.ServeFile(path, file)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n)\n\n\n\n\nvar wait sync.WaitGroup\n\nfunc capitalize(word string) {\n\tdefer wait.Done()\n\tfmt.Println(strings.Title(word))\n}\n\n\n\nfunc add(ch chan string, words []string) {\n\tfor _, word := range words {\n\t\tch <- word\n\t}\n}\n\nfunc main() {\n\twords := []string{\"test1\", \"test2\", \"test3\"}\n\n\tfmt.Println(\"Use go routines to capitalize our words.\")\n\twait.Add(len(words))\n\n\tfor i := 0; i < len(words); i++ {\n\t\tgo capitalize(words[i])\n\t}\n\n\twait.Wait()\n\tfmt.Println()\n\n\n\n\tfmt.Println(\"Use channels to upper case our words.\")\n\n\tword_chan := make(chan string)\n\n\n\tgo upper(word_chan)\n\n\tadd(word_chan, words)\n\n\tclose(word_chan)\n}\n\nfunc upper(ch chan string) ", "output": "{\n\tfor {\n\t\tword := <-ch\n\n\t\tif word == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tfmt.Println(strings.ToUpper(word))\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\nvar rootPath = getCutoRoot()\n\n\n\n\nfunc GetRootPath() string {\n\treturn rootPath\n}\n\n\nfunc GetCurrentPath() string {\n\treturn filepath.Join(rootPath, \"bin\")\n}\n\nfunc getCutoRoot() string ", "output": "{\n\td := os.Getenv(\"CUTOROOT\")\n\tif len(d) == 0 {\n\t\tpanic(\"Not setting environment argument $CUTOROOT\")\n\t}\n\treturn d\n}"} {"input": "package dependency\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hashicorp/consul/api\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestConnectCAQuery_Fetch(t *testing.T) ", "output": "{\n\n\td := NewConnectCAQuery()\n\traw, _, err := d.Fetch(testClients, nil)\n\tassert.NoError(t, err)\n\tact := raw.([]*api.CARoot)\n\tif assert.Len(t, act, 1) {\n\t\troot := act[0]\n\t\tassert.Equal(t, root.Name, \"Consul CA Root Cert\")\n\t\tassert.True(t, root.Active)\n\t\tassert.NotEmpty(t, root.RootCertPEM)\n\t}\n}"} {"input": "package throttled\n\n\ntype WaitGroup struct {\n\tthrottle int\n\tcompleted chan bool\n\toutstanding int\n}\n\n\nfunc NewWaitGroup(throttle int) *WaitGroup {\n\treturn &WaitGroup{\n\t\toutstanding: 0,\n\t\tthrottle: throttle,\n\t\tcompleted: make(chan bool, throttle),\n\t}\n}\n\n\n\n\n\n\nfunc (w *WaitGroup) Add() {\n\tw.outstanding++\n\tif w.outstanding > w.throttle {\n\t\tselect {\n\t\tcase <-w.completed:\n\t\t\tw.outstanding--\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\nfunc (w *WaitGroup) Done() {\n\tw.completed <- true\n}\n\n\nfunc (w *WaitGroup) Wait() {\n\tif w.outstanding == 0 {\n\t\treturn\n\t}\n\tfor w.outstanding > 0 {\n\t\tselect {\n\t\tcase <-w.completed:\n\t\t\tw.outstanding--\n\t\t}\n\t}\n}\n\nfunc (w *WaitGroup) PeekThrottled() bool ", "output": "{\n\treturn w.outstanding+1 > w.throttle\n}"} {"input": "package optimizer\n\n\ntype OperationStatusEnum string\n\n\nconst (\n\tOperationStatusAccepted OperationStatusEnum = \"ACCEPTED\"\n\tOperationStatusInProgress OperationStatusEnum = \"IN_PROGRESS\"\n\tOperationStatusFailed OperationStatusEnum = \"FAILED\"\n\tOperationStatusSucceeded OperationStatusEnum = \"SUCCEEDED\"\n\tOperationStatusCanceling OperationStatusEnum = \"CANCELING\"\n\tOperationStatusCanceled OperationStatusEnum = \"CANCELED\"\n)\n\nvar mappingOperationStatus = map[string]OperationStatusEnum{\n\t\"ACCEPTED\": OperationStatusAccepted,\n\t\"IN_PROGRESS\": OperationStatusInProgress,\n\t\"FAILED\": OperationStatusFailed,\n\t\"SUCCEEDED\": OperationStatusSucceeded,\n\t\"CANCELING\": OperationStatusCanceling,\n\t\"CANCELED\": OperationStatusCanceled,\n}\n\n\n\n\nfunc GetOperationStatusEnumValues() []OperationStatusEnum ", "output": "{\n\tvalues := make([]OperationStatusEnum, 0)\n\tfor _, v := range mappingOperationStatus {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package readline\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"github.com/jcw/flow\"\n\n\t\"bufio\"\n\t\"os\"\n)\n\nfunc init() {\n\tglog.Info(\"ReadlineStdIn Init...\")\n\tflow.Registry[\"ReadlineStdIn\"] = func() flow.Circuitry { return new(ReadlineStdIn) }\n\n}\n\n\n\n\ntype ReadlineStdIn struct {\n\tflow.Gadget\n\n\tOut flow.Output \n}\n\n\n\nfunc (g *ReadlineStdIn) Run() ", "output": "{\n\n\texit := false\n\n\tsin := bufio.NewScanner(os.Stdin)\n\n\tfor exit == false {\n\n\t\tvar line string\n\t\tfor sin.Scan() {\n\t\t\tline = sin.Text()\n\t\t\tg.Out.Send(line)\n\t\t}\n\n\t\terr := sin.Err()\n\n\t\tif err != nil {\n\t\t\tglog.Errorln(\"ReadlineStdIn Error:\", err)\n\t\t}\n\n\t}\n\n}"} {"input": "package network\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/docker/docker/cli\"\n\t\"github.com/docker/docker/cli/command\"\n\t\"github.com/docker/docker/cli/command/inspect\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype inspectOptions struct {\n\tformat string\n\tnames []string\n}\n\n\n\nfunc runInspect(dockerCli *command.DockerCli, opts inspectOptions) error {\n\tclient := dockerCli.Client()\n\n\tctx := context.Background()\n\n\tgetNetFunc := func(name string) (interface{}, []byte, error) {\n\t\treturn client.NetworkInspectWithRaw(ctx, name)\n\t}\n\n\treturn inspect.Inspect(dockerCli.Out(), opts.names, opts.format, getNetFunc)\n}\n\nfunc newInspectCommand(dockerCli *command.DockerCli) *cobra.Command ", "output": "{\n\tvar opts inspectOptions\n\n\tcmd := &cobra.Command{\n\t\tUse: \"inspect [OPTIONS] NETWORK [NETWORK...]\",\n\t\tShort: \"Display detailed information on one or more networks\",\n\t\tArgs: cli.RequiresMinArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\topts.names = args\n\t\t\treturn runInspect(dockerCli, opts)\n\t\t},\n\t}\n\n\tcmd.Flags().StringVarP(&opts.format, \"format\", \"f\", \"\", \"Format the output using the given Go template\")\n\n\treturn cmd\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSEMRCluster_HadoopJarStepConfig struct {\n\n\tArgs []string `json:\"Args,omitempty\"`\n\n\tJar string `json:\"Jar,omitempty\"`\n\n\tMainClass string `json:\"MainClass,omitempty\"`\n\n\tStepProperties []AWSEMRCluster_KeyValue `json:\"StepProperties,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) AWSCloudFormationType() string {\n\treturn \"AWS::EMR::Cluster.HadoopJarStepConfig\"\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\n\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) Metadata() map[string]interface{} ", "output": "{\n\treturn r._metadata\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n\tgoahttp \"goa.design/goa/v3/http\"\n\tcli \"goa.design/plugins/v3/goakit/examples/calc/gen/http/cli/calc\"\n)\n\nfunc doHTTP(scheme, host string, timeout int, debug bool) (endpoint.Endpoint, interface{}, error) {\n\tvar (\n\t\tdoer goahttp.Doer\n\t)\n\t{\n\t\tdoer = &http.Client{Timeout: time.Duration(timeout) * time.Second}\n\t\tif debug {\n\t\t\tdoer = goahttp.NewDebugDoer(doer)\n\t\t}\n\t}\n\n\treturn cli.ParseEndpoint(\n\t\tscheme,\n\t\thost,\n\t\tdoer,\n\t\tgoahttp.RequestEncoder,\n\t\tgoahttp.ResponseDecoder,\n\t\tdebug,\n\t)\n}\n\n\n\nfunc httpUsageExamples() string {\n\treturn cli.UsageExamples()\n}\n\nfunc httpUsageCommands() string ", "output": "{\n\treturn cli.UsageCommands()\n}"} {"input": "package storage\n\nimport (\n\t\"context\"\n)\n\n\n\n\n\n\n\n\n\nfunc ReadOne(ctx context.Context, store Store, path Path) (interface{}, error) {\n\ttxn, err := store.NewTransaction(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer store.Abort(ctx, txn)\n\n\treturn store.Read(ctx, txn, path)\n}\n\n\n\n\nfunc WriteOne(ctx context.Context, store Store, op PatchOp, path Path, value interface{}) error {\n\ttxn, err := store.NewTransaction(ctx, WriteParams)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := store.Write(ctx, txn, op, path, value); err != nil {\n\t\tstore.Abort(ctx, txn)\n\t\treturn err\n\t}\n\n\treturn store.Commit(ctx, txn)\n}\n\n\n\n\n\nfunc Txn(ctx context.Context, store Store, params TransactionParams, f func(Transaction) error) error {\n\n\ttxn, err := store.NewTransaction(ctx, params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := f(txn); err != nil {\n\t\tstore.Abort(ctx, txn)\n\t\treturn err\n\t}\n\n\treturn store.Commit(ctx, txn)\n}\n\nfunc NewTransactionOrDie(ctx context.Context, store Store, params ...TransactionParams) Transaction ", "output": "{\n\ttxn, err := store.NewTransaction(ctx, params...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn txn\n}"} {"input": "package lists\n\n\n\n\nimport (\n\t\"net/url\"\n\n\t\"github.com/kawaken/go-rtm/methods\"\n)\n\n\n\n\nfunc SetDefaultList(timeline string, listID string) *methods.Method ", "output": "{\n\tname := \"rtm.lists.setDefaultList\"\n\n\tp := url.Values{}\n\tp.Add(\"method\", name)\n\tp.Add(\"timeline\", timeline)\n\tp.Add(\"list_id\", listID)\n\treturn &methods.Method{Name: name, Params: p}\n}"} {"input": "package form\n\nimport (\n\t\"io\"\n\n\t\"gnd.la/html\"\n)\n\n\n\n\n\n\ntype Renderer interface {\n\tBeginField(w io.Writer, field *Field) error\n\tBeginLabel(w io.Writer, field *Field, label string, pos int) error\n\tLabelAttributes(field *Field, pos int) (html.Attrs, error)\n\tEndLabel(w io.Writer, field *Field, pos int) error\n\tBeginInput(w io.Writer, field *Field, placeholder string, pos int) error\n\tFieldAttributes(field *Field, pos int) (html.Attrs, error)\n\tEndInput(w io.Writer, field *Field, pos int) error\n\tWriteAddOn(w io.Writer, field *Field, addon *AddOn) error\n\tWriteError(w io.Writer, field *Field, err error) error\n\tWriteHelp(w io.Writer, field *Field, help string) error\n\tEndField(w io.Writer, field *Field) error\n}\n\nvar (\n\trendererFunc func() Renderer\n)\n\n\n\nfunc SetDefaultRenderer(f func() Renderer) {\n\trendererFunc = f\n}\n\n\n\n\nfunc DefaultRenderer() Renderer ", "output": "{\n\tif rendererFunc != nil {\n\t\treturn rendererFunc()\n\t}\n\treturn nil\n}"} {"input": "package database_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestEnforcer(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Database Suite\")\n}"} {"input": "package converters\n\nimport (\n\t\"github.com/open-gtd/server/contract/tags\"\n\t\"github.com/open-gtd/server/tags/domain\"\n)\n\nfunc ConvertAllToTag(t []domain.Tag) ([]tags.Tag, error) {\n\tresult := make([]tags.Tag, len(t))\n\n\tfor i, tag := range t {\n\t\tpTag, err := ConvertToTag(tag)\n\t\tif err != nil {\n\t\t\treturn make([]tags.Tag, 0), err\n\t\t}\n\n\t\tresult[i] = pTag\n\t}\n\n\treturn result, nil\n}\n\n\n\nfunc ConvertToTag(t domain.Tag) (tags.Tag, error) ", "output": "{\n\n\ttypeDescriptor, err := ConvertTypeToPresentation(t.GetType())\n\tif err != nil {\n\t\treturn tags.Tag{}, err\n\t}\n\n\treturn tags.Tag{\n\t\tName: string(t.GetName()),\n\t\tType: typeDescriptor,\n\t}, nil\n}"} {"input": "package tick\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/influxdata/kapacitor/tick/ast\"\n)\n\n\n\n\nfunc Format(script string) (string, error) ", "output": "{\n\troot, err := ast.Parse(script)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar buf bytes.Buffer\n\tbuf.Grow(len(script))\n\troot.Format(&buf, \"\", false)\n\treturn buf.String(), nil\n}"} {"input": "package jwt\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype Token struct {\n\tExpiryDate int64\n\tRawToken string\n}\n\n\n\nconst expirationSkew = 30\n\n\n\n\n\n\nfunc (t *Token) GetAuthenticationHeaderValue() string {\n\treturn fmt.Sprintf(\"Bearer %s\", t.RawToken)\n}\n\n\nfunc (t *Token) String() string {\n\treturn t.RawToken\n}\n\n\ntype tokenPayload struct {\n\tExpirationTime int64 `json:\"exp\"`\n}\n\n\n\n\n\nfunc New(token string) (Token, error) {\n\tif len(token) == 0 {\n\t\treturn Token{}, errors.New(\"no token given, a token should be set\")\n\t}\n\n\ttokenParts := strings.Split(token, \".\")\n\tif len(tokenParts) != 3 {\n\t\treturn Token{}, fmt.Errorf(\"invalid token '%s' given, token should exist at least of 3 parts\", token)\n\t}\n\n\tjsonBody, err := base64.RawStdEncoding.DecodeString(tokenParts[1])\n\tif err != nil {\n\t\treturn Token{}, errors.New(\"could not decode token, invalid base64\")\n\t}\n\n\tvar tokenRequest tokenPayload\n\terr = json.Unmarshal(jsonBody, &tokenRequest)\n\tif err != nil {\n\t\treturn Token{}, errors.New(\"could not read token body, invalid json\")\n\t}\n\n\treturn Token{\n\t\tRawToken: token,\n\t\tExpiryDate: tokenRequest.ExpirationTime,\n\t}, nil\n}\n\nfunc (t *Token) Expired() bool ", "output": "{\n\treturn time.Now().Unix()+expirationSkew > t.ExpiryDate\n}"} {"input": "package resolve\n\nimport (\n\t\"github.com/google/gapid/core/data/id\"\n\t\"github.com/google/gapid/core/memory/arena\"\n\t\"github.com/google/gapid/gapis/api\"\n\t\"github.com/google/gapid/gapis/service\"\n\t\"github.com/google/gapid/gapis/service/box\"\n\t\"github.com/google/gapid/gapis/service/path\"\n)\n\nfunc internalToService(v interface{}) (interface{}, error) {\n\tswitch v := v.(type) {\n\tcase api.Cmd:\n\t\treturn api.CmdToService(v)\n\tcase []*api.ContextInfo:\n\t\tout := &service.Contexts{List: make([]*path.Context, len(v))}\n\t\tfor i, c := range v {\n\t\t\tout.List[i] = c.Path\n\t\t}\n\t\treturn out, nil\n\tcase *api.ContextInfo:\n\t\treturn &service.Context{\n\t\t\tName: v.Name,\n\t\t\tAPI: path.NewAPI(id.ID(v.API)),\n\t\t\tPriority: uint32(v.Priority),\n\t\t}, nil\n\tdefault:\n\t\treturn v, nil\n\t}\n}\n\n\n\nfunc serviceToInternal(a arena.Arena, v interface{}) (interface{}, error) ", "output": "{\n\tswitch v := v.(type) {\n\tcase *api.Command:\n\t\treturn api.ServiceToCmd(a, v)\n\tcase *box.Value:\n\t\treturn v.Get(), nil\n\tdefault:\n\t\treturn v, nil\n\t}\n}"} {"input": "package logutils\n\nimport (\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype MockLog struct {\n\tmock.Mock\n}\n\nfunc NewMockLog() *MockLog {\n\treturn &MockLog{}\n}\n\n\n\nfunc (m *MockLog) Panicf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Errorf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Warnf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Infof(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Child(name string) Log {\n\tm.Called(name)\n\treturn m\n}\n\nfunc (m *MockLog) SetLevel(level LogLevel) {\n\tm.Called(level)\n}\n\nfunc (m *MockLog) Fatalf(format string, args ...interface{}) ", "output": "{\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}"} {"input": "package dashing\n\nimport (\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\n\ntype Event struct {\n\tID string\n\tBody map[string]interface{}\n\tTarget string\n}\n\n\ntype Dashing struct {\n\tstarted bool\n\tBroker *Broker\n\tWorker *Worker\n\tServer *Server\n\tRouter http.Handler\n}\n\n\n\n\n\nfunc (d *Dashing) Start() *Dashing {\n\tif !d.started {\n\t\tif d.Router == nil {\n\t\t\td.Router = d.Server.NewRouter()\n\t\t}\n\t\td.Broker.Start()\n\t\td.Worker.Start()\n\t\td.started = true\n\t}\n\treturn d\n}\n\n\nfunc NewDashing() *Dashing {\n\tbroker := NewBroker()\n\tworker := NewWorker(broker)\n\tserver := NewServer(broker)\n\n\tif os.Getenv(\"WEBROOT\") != \"\" {\n\t\tserver.webroot = filepath.Clean(os.Getenv(\"WEBROOT\")) + \"/\"\n\t}\n\tif os.Getenv(\"DEV\") != \"\" {\n\t\tserver.dev = true\n\t}\n\n\treturn &Dashing{\n\t\tstarted: false,\n\t\tBroker: broker,\n\t\tWorker: worker,\n\t\tServer: server,\n\t}\n}\n\nfunc (d *Dashing) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tif !d.started {\n\t\tpanic(\"dashing.Start() has not been called\")\n\t}\n\td.Router.ServeHTTP(w, r)\n}"} {"input": "package tick\n\nimport (\n\t\"github.com/influxdata/kapacitor/pipeline\"\n\t\"github.com/influxdata/kapacitor/tick/ast\"\n)\n\n\ntype StatsNode struct {\n\tFunction\n}\n\n\n\n\n\nfunc (n *StatsNode) Build(s *pipeline.StatsNode) (ast.Node, error) {\n\tn.Pipe(\"stats\", s.Interval).\n\t\tDotIf(\"align\", s.AlignFlag)\n\treturn n.prev, n.err\n}\n\nfunc NewStats(parents []ast.Node) *StatsNode ", "output": "{\n\treturn &StatsNode{\n\t\tFunction{\n\t\t\tParents: parents,\n\t\t},\n\t}\n}"} {"input": "package app\n\nimport (\n\t. \"strconv\"\n\t\"time\"\n)\n\ntype User struct {\n\tId int64\n\tNom string\n\tPrenom string\n\tEmail string\n\tPassword string\n\tCreatedAt time.Time\n\tUpdatedAt time.Time\n}\n\n\nfunc (u User) Save() {\n\tdb.Save(&u)\n}\n\n\nfunc (u User) Update() {\n\tdb.First(&u, &u.Id).Update(&u)\n}\n\n\nfunc (u User) Delete() {\n\tdb.Delete(&u)\n}\n\n\n\nfunc (u User) GetById() User {\n\tdb.Where(\"id = ?\", Itoa(int(u.Id))).Find(&u)\n\treturn u\n}\n\n\n\n\nfunc (u User) GetList() []User ", "output": "{\n\tvar users []User\n\tdb.Find(&users)\n\treturn users\n}"} {"input": "package message\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"mime\"\n\t\"strings\"\n)\n\ntype UnknownCharsetError struct {\n\te error\n}\n\nfunc (u UnknownCharsetError) Unwrap() error { return u.e }\n\nfunc (u UnknownCharsetError) Error() string {\n\treturn \"unknown charset: \" + u.e.Error()\n}\n\n\n\nfunc IsUnknownCharset(err error) bool {\n\treturn errors.As(err, new(UnknownCharsetError))\n}\n\n\n\n\n\n\n\n\n\nvar CharsetReader func(charset string, input io.Reader) (io.Reader, error)\n\n\nfunc charsetReader(charset string, input io.Reader) (io.Reader, error) {\n\tcharset = strings.ToLower(charset)\n\tif charset == \"utf-8\" || charset == \"us-ascii\" {\n\t\treturn input, nil\n\t}\n\tif CharsetReader != nil {\n\t\tr, err := CharsetReader(charset, input)\n\t\tif err != nil {\n\t\t\treturn r, UnknownCharsetError{err}\n\t\t}\n\t\treturn r, nil\n\t}\n\treturn input, UnknownCharsetError{fmt.Errorf(\"message: unhandled charset %q\", charset)}\n}\n\n\n\nfunc decodeHeader(s string) (string, error) {\n\twordDecoder := mime.WordDecoder{CharsetReader: charsetReader}\n\tdec, err := wordDecoder.DecodeHeader(s)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\treturn dec, nil\n}\n\n\n\nfunc encodeHeader(s string) string ", "output": "{\n\treturn mime.QEncoding.Encode(\"utf-8\", s)\n}"} {"input": "package crypto\n\nimport (\n\t\"crypto\"\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/sha256\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\nfunc Sign(key *rsa.PrivateKey, message []byte) ([]byte, error) {\n\thashed := sha256.Sum256(message)\n\tsignature, err := rsa.SignPKCS1v15(\n\t\trand.Reader, key, crypto.SHA256, hashed[:],\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to sign message: \")\n\t}\n\treturn signature, nil\n}\n\n\n\n\n\n\nfunc EncryptRSA(key *rsa.PublicKey, plaintext []byte) ([]byte, error) {\n\tciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, key, plaintext)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to encrypt plaintext: \")\n\t}\n\treturn ciphertext, nil\n}\n\n\nfunc DecryptRSA(key *rsa.PrivateKey, ciphertext []byte) ([]byte, error) {\n\tsession, err := rsa.DecryptPKCS1v15(rand.Reader, key, ciphertext)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to decrypt ciphertext: \")\n\t}\n\treturn session, nil\n}\n\nfunc Verify(key *rsa.PublicKey, signature, message []byte) error ", "output": "{\n\thashed := sha256.Sum256(message)\n\terr := rsa.VerifyPKCS1v15(key, crypto.SHA256, hashed[:], signature)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to verify message: \")\n\t}\n\treturn nil\n}"} {"input": "package ipv4\n\nconst sizeofICMPFilter = 0x0\n\ntype icmpFilter struct {\n}\n\nfunc (f *icmpFilter) accept(typ ICMPType) {\n}\n\nfunc (f *icmpFilter) block(typ ICMPType) {\n}\n\nfunc (f *icmpFilter) setAll(block bool) {\n}\n\n\n\nfunc (f *icmpFilter) willBlock(typ ICMPType) bool ", "output": "{\n\treturn false\n}"} {"input": "package dnsrecorder\n\nimport (\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n)\n\n\n\n\n\n\n\ntype Recorder struct {\n\tdns.ResponseWriter\n\tRcode int\n\tSize int\n\tMsg *dns.Msg\n\tStart time.Time\n}\n\n\n\n\n\n\n\n\nfunc (r *Recorder) WriteMsg(res *dns.Msg) error {\n\tr.Rcode = res.Rcode\n\tr.Size += res.Len()\n\tr.Msg = res\n\treturn r.ResponseWriter.WriteMsg(res)\n}\n\n\nfunc (r *Recorder) Write(buf []byte) (int, error) {\n\tn, err := r.ResponseWriter.Write(buf)\n\tif err == nil {\n\t\tr.Size += n\n\t}\n\treturn n, err\n}\n\n\n\nfunc (r *Recorder) Hijack() { r.ResponseWriter.Hijack(); return }\n\nfunc New(w dns.ResponseWriter) *Recorder ", "output": "{\n\treturn &Recorder{\n\t\tResponseWriter: w,\n\t\tRcode: 0,\n\t\tMsg: nil,\n\t\tStart: time.Now(),\n\t}\n}"} {"input": "package derive\n\nimport (\n\t\"go/types\"\n\t\"strings\"\n)\n\n\ntype Named struct {\n\tFields []*Field\n\tReflect bool\n}\n\n\ntype Field struct {\n\tname string\n\texternal bool\n\tType types.Type\n\ttypeStr func() string\n}\n\n\nfunc (f *Field) Name(recv string, unsafePkg Import) string {\n\tif !f.Private() || !f.external {\n\t\treturn recv + \".\" + f.name\n\t}\n\treturn `*(*` + f.typeStr() + `)(` + unsafePkg() + `.Pointer(` + recv + `.FieldByName(\"` + f.name + `\").UnsafeAddr()))`\n}\n\n\nfunc (f *Field) DebugName() string {\n\treturn f.name\n}\n\n\n\n\n\nfunc Fields(typesMap TypesMap, typ *types.Struct, external bool) *Named {\n\tnumFields := typ.NumFields()\n\tn := &Named{\n\t\tFields: make([]*Field, numFields),\n\t}\n\tfor i := 0; i < numFields; i++ {\n\t\tfield := typ.Field(i)\n\t\tfieldType := field.Type()\n\t\tfieldName := field.Name()\n\t\tn.Fields[i] = &Field{\n\t\t\tname: fieldName,\n\t\t\texternal: external,\n\t\t\tType: fieldType,\n\t\t\ttypeStr: func() string {\n\t\t\t\treturn typesMap.TypeString(fieldType)\n\t\t\t},\n\t\t}\n\t\tif n.Fields[i].Private() {\n\t\t\tif external {\n\t\t\t\tn.Reflect = true\n\t\t\t}\n\t\t}\n\t}\n\treturn n\n}\n\nfunc GetStructFields(s *types.Struct) []*types.Var {\n\tfields := make([]*types.Var, s.NumFields())\n\tfor i := 0; i < s.NumFields(); i++ {\n\t\tfields[i] = s.Field(i)\n\t}\n\treturn fields\n}\n\nfunc (f *Field) Private() bool ", "output": "{\n\treturn strings.ToLower(f.name[0:1]) == f.name[0:1]\n}"} {"input": "package arm\n\nimport (\n\t\"testing\"\n\n\t\"golang.org/x/crypto/ssh\"\n)\n\nfunc TestAuthorizedKeyShouldParse(t *testing.T) {\n\ttestSubject, err := NewOpenSshKeyPairWithSize(512)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create a new OpenSSH key pair, err=%s.\", err)\n\t}\n\n\tauthorizedKey := testSubject.AuthorizedKey()\n\n\t_, _, _, _, err = ssh.ParseAuthorizedKey([]byte(authorizedKey))\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to parse the authorized key, err=%s\", err)\n\t}\n}\n\n\n\nfunc TestPrivateKeyShouldParse(t *testing.T) ", "output": "{\n\ttestSubject, err := NewOpenSshKeyPairWithSize(512)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create a new OpenSSH key pair, err=%s.\", err)\n\t}\n\n\t_, err = ssh.ParsePrivateKey([]byte(testSubject.PrivateKey()))\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to parse the private key, err=%s\\n\", err)\n\t}\n}"} {"input": "package slack\n\nimport (\n\t\"testing\"\n)\n\nfunc newConfigGood() (config *SlackConfig, err error) {\n\tconfig, err = newSlackConfig(\"testing/slack_good.json\")\n\treturn\n}\n\n\n\nfunc TestNewSlackConfig(t *testing.T) ", "output": "{\n\tconf, err := newConfigGood()\n\n\tif err != nil {\n\t\tt.Log(\"could not load slack config file\")\n\t\tt.Log(err.Error())\n\t\tt.Fail()\n\t}\n\n\tif conf == nil {\n\t\tt.Log(\"conf is nil\")\n\t}\n\n\tif conf.WebhookUrl == \"\" {\n\t\tt.Log(\"conf.WebhookUrl is empty\")\n\t}\n\n\tif conf.WebhookUrl != \"http://test\" {\n\t\tt.Log(\"WebhookUrl was not the expected value: \" + conf.WebhookUrl)\n\t\tt.Fail()\n\t}\n\n\tif conf.BotUsername != \"GoShipit\" {\n\t\tt.Log(\"BotUsername exptected to be . Actual <\" +\n\t\t\tconf.BotUsername + \">.\")\n\t\tt.Fail()\n\t}\n}"} {"input": "package sliceset\n\nimport (\n\t\"sort\"\n\n\t\"github.com/xtgo/set\"\n)\n\ntype Set []int\n\n\nfunc (s Set) Less(i, j int) bool { return s[i] < s[j] }\nfunc (s Set) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s Set) Copy() Set { return append(Set(nil), s...) }\n\nfunc (s Set) Union(t Set) Set { return s.Do(set.Union, t) }\nfunc (s Set) Inter(t Set) Set { return s.Do(set.Inter, t) }\nfunc (s Set) Diff(t Set) Set { return s.Do(set.Diff, t) }\nfunc (s Set) SymDiff(t Set) Set { return s.Do(set.SymDiff, t) }\nfunc (s Set) IsSub(t Set) bool { return s.DoBool(set.IsSub, t) }\nfunc (s Set) IsSuper(t Set) bool { return s.DoBool(set.IsSuper, t) }\nfunc (s Set) IsInter(t Set) bool { return s.DoBool(set.IsInter, t) }\nfunc (s Set) IsEqual(t Set) bool { return s.DoBool(set.IsEqual, t) }\n\nfunc (s Set) Uniq() Set {\n\tn := set.Uniq(s)\n\treturn s[:n]\n}\n\nfunc (s Set) Do(op set.Op, t Set) Set {\n\tdata := append(s, t...)\n\tn := op(data, len(s))\n\treturn data[:n]\n}\n\ntype BoolOp func(sort.Interface, int) bool\n\nfunc (s Set) DoBool(op BoolOp, t Set) bool {\n\tdata := append(s, t...)\n\treturn op(data, len(s))\n}\n\nfunc (s Set) Len() int ", "output": "{ return len(s) }"} {"input": "package main\n\nimport (\n\t\"regexp\"\n\t\"testing\"\n)\n\n\n\nfunc TestVersion(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\targs := []string{\n\t\t\"--version\",\n\t}\n\n\tgopath, cleanFunc, err := tmpGopath()\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\tdefer cleanFunc()\n\n\toutput, err := runGcli(\"./\", gopath, args)\n\tif err != nil {\n\t\tt.Fatalf(\"expects %s to be nil\", err)\n\t}\n\n\texpect := regexp.MustCompile(`gcli version v\\d+\\.\\d+\\.\\d+`)\n\tif !expect.MatchString(output) {\n\t\tt.Fatalf(\"expects output not to contain %q %s\", expect, output)\n\t}\n}"} {"input": "package consul\n\nimport (\n\t\"log\"\n\n\t\"github.com/armon/consul-api\"\n\t\"github.com/hashicorp/terraform/helper/config\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\ntype ResourceProvider struct {\n\tConfig Config\n\tclient *consulapi.Client\n}\n\nfunc (p *ResourceProvider) Validate(c *terraform.ResourceConfig) ([]string, []error) {\n\tv := &config.Validator{\n\t\tOptional: []string{\n\t\t\t\"datacenter\",\n\t\t\t\"address\",\n\t\t},\n\t}\n\treturn v.Validate(c)\n}\n\nfunc (p *ResourceProvider) ValidateResource(\n\tt string, c *terraform.ResourceConfig) ([]string, []error) {\n\treturn resourceMap.Validate(t, c)\n}\n\nfunc (p *ResourceProvider) Configure(c *terraform.ResourceConfig) error {\n\tif _, err := config.Decode(&p.Config, c.Config); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[INFO] Initializing Consul client\")\n\tvar err error\n\tp.client, err = p.Config.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc (p *ResourceProvider) Diff(\n\ts *terraform.ResourceState,\n\tc *terraform.ResourceConfig) (*terraform.ResourceDiff, error) {\n\treturn resourceMap.Diff(s, c, p)\n}\n\nfunc (p *ResourceProvider) Refresh(\n\ts *terraform.ResourceState) (*terraform.ResourceState, error) {\n\treturn resourceMap.Refresh(s, p)\n}\n\nfunc (p *ResourceProvider) Resources() []terraform.ResourceType {\n\treturn resourceMap.Resources()\n}\n\nfunc (p *ResourceProvider) Apply(\n\ts *terraform.ResourceState,\n\td *terraform.ResourceDiff) (*terraform.ResourceState, error) ", "output": "{\n\treturn resourceMap.Apply(s, d, p)\n}"} {"input": "package log\n\n\nfunc (me *Logging) Prefix() string {\n\treturn me.prefix\n}\n\n\nfunc (me *Logging) SetPrefix(value string) {\n\tme.prefix = value\n\tif me.console != nil {\n\t\tme.console.SetPrefix(me.prefix)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPrefix(me.prefix)\n\t}\n}\n\n\nfunc (me *Logging) Priority() int {\n\treturn me.priority\n}\n\n\nfunc (me *Logging) SetPriority(value int) {\n\tme.setPriority = true\n\tme.priority = value\n\tif me.console != nil {\n\t\tme.console.SetPriority(me.priority)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPriority(me.priority)\n\t}\n}\n\n\n\n\n\nfunc (me *Logging) SetLayouts(value int) {\n\tme.setLayouts = true\n\tme.layouts = value\n\tif me.console != nil {\n\t\tme.console.SetLayouts(me.layouts)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetLayouts(me.layouts)\n\t}\n}\n\n\nfunc (me *Logging) Outputs() int {\n\treturn me.outputs\n}\n\n\nfunc (me *Logging) SetOutputs(value int) {\n\tme.setOutputs = true\n\tme.outputs = value\n}\n\nfunc (me *Logging) Layouts() int ", "output": "{\n\treturn me.layouts\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\n\n\nfunc naclClose(fd int) (err error) {\n\t_, _, e1 := Syscall(sys_close, uintptr(fd), 0, 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc Exit(code int) (err error) {\n\t_, _, e1 := Syscall(sys_exit, uintptr(code), 0, 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclFstat(fd int, stat *Stat_t) (err error) {\n\t_, _, e1 := Syscall(sys_fstat, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\n\n\n\n\nfunc naclSeek(fd int, off *int64, whence int) (err error) {\n\t_, _, e1 := Syscall(sys_lseek, uintptr(fd), uintptr(unsafe.Pointer(off)), uintptr(whence))\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclGetRandomBytes(b []byte) (err error) {\n\tvar _p0 unsafe.Pointer\n\tif len(b) > 0 {\n\t\t_p0 = unsafe.Pointer(&b[0])\n\t} else {\n\t\t_p0 = unsafe.Pointer(&_zero)\n\t}\n\t_, _, e1 := Syscall(sys_get_random_bytes, uintptr(_p0), uintptr(len(b)), 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\nfunc naclRead(fd int, b []byte) (n int, err error) ", "output": "{\n\tvar _p0 unsafe.Pointer\n\tif len(b) > 0 {\n\t\t_p0 = unsafe.Pointer(&b[0])\n\t} else {\n\t\t_p0 = unsafe.Pointer(&_zero)\n\t}\n\tr0, _, e1 := Syscall(sys_read, uintptr(fd), uintptr(_p0), uintptr(len(b)))\n\tn = int(r0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}"} {"input": "package iso20022\n\n\ntype LinkageType3Choice struct {\n\n\tCode *LinkageType1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification30 `xml:\"Prtry\"`\n}\n\nfunc (l *LinkageType3Choice) SetCode(value string) {\n\tl.Code = (*LinkageType1Code)(&value)\n}\n\n\n\nfunc (l *LinkageType3Choice) AddProprietary() *GenericIdentification30 ", "output": "{\n\tl.Proprietary = new(GenericIdentification30)\n\treturn l.Proprietary\n}"} {"input": "package main\n\nimport(\"fmt\";\"os\";\"regexp\";\"flag\";\"net/http\";\"log\";\"errors\")\n\ntype HTTPDCmd struct {}\n\nfunc (c *HTTPDCmd) Summary() string {\n return \"Starts small HTTP server\"\n}\n\nfunc (c *HTTPDCmd) Help() string {\n return `Starts small HTTP daemon that can server files from a specific directory\n\nAvailable subcommands:\n httpd serve Serve on 0.0.0.0:\n`\n}\n\n\n\nfunc (c *HTTPDCmd) Run(args[]string, cfg Config) (int, error) {\n if (len(args) == 3 && args[0] == \"serve\") {\n port := flag.String(\"p\", args[1], \"port to serve on\")\n path := flag.String(\"d\", args[2], \"the dir of static file on host\")\n flag.Parse()\n http.Handle(\"/\", http.FileServer(http.Dir(*path)))\n log.Fatal(http.ListenAndServe(\":\"+*port, nil))\n return 1, nil\n }\n fmt.Fprintf(os.Stdout, c.Help())\n return 0, nil\n}\n\nfunc (c *HTTPDCmd) ValidateArgs(args[]string) error ", "output": "{\n re1 := regexp.MustCompile(\"^[0-9]+$\")\n re2 := regexp.MustCompile(\"^/.+$\")\n if (len(args) == 3 && args[0] == \"serve\" && re1.MatchString(args[1]) && re2.MatchString(args[2])) {\n return nil\n }\n return errors.New(\"Invalid args\")\n}"} {"input": "package net\n\nimport (\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\ntype Endpoint interface {\n\tHostName() string\n\tPort() int\n}\n\ntype defaultEndpoint struct {\n\thostname string\n\tport int\n}\n\nfunc (e defaultEndpoint) HostName() string {\n\treturn e.hostname\n}\n\n\nfunc NewEndpoint(hostname string, port int) Endpoint {\n\treturn defaultEndpoint{hostname, port}\n}\n\nfunc FromUrl(u url.URL) Endpoint {\n\tparts := strings.Split(u.Host, \":\")\n\tif len(parts) != 2 {\n\t\treturn nil\n\t}\n\tport, _ := strconv.Atoi(parts[1])\n\treturn NewEndpoint(parts[0], port)\n}\n\nfunc (e defaultEndpoint) Port() int ", "output": "{\n\treturn e.port\n}"} {"input": "package grpc\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"google.golang.org/grpc/balancer\"\n\t\"google.golang.org/grpc/connectivity\"\n\t\"google.golang.org/grpc/resolver\"\n\t\"google.golang.org/grpc/resolver/manual\"\n)\n\nvar _ balancer.V2Balancer = &funcBalancer{}\n\ntype funcBalancer struct {\n\tupdateClientConnState func(s balancer.ClientConnState) error\n}\n\nfunc (*funcBalancer) HandleSubConnStateChange(balancer.SubConn, connectivity.State) {\n\tpanic(\"unimplemented\") \n}\nfunc (*funcBalancer) HandleResolvedAddrs([]resolver.Address, error) {\n\tpanic(\"unimplemented\") \n}\nfunc (b *funcBalancer) UpdateClientConnState(s balancer.ClientConnState) error {\n\treturn b.updateClientConnState(s)\n}\nfunc (*funcBalancer) ResolverError(error) {}\nfunc (*funcBalancer) UpdateSubConnState(balancer.SubConn, balancer.SubConnState) {\n\tpanic(\"unimplemented\") \n}\nfunc (*funcBalancer) Close() {}\n\ntype funcBalancerBuilder struct {\n\tname string\n\tinstance *funcBalancer\n}\n\nfunc (b *funcBalancerBuilder) Build(balancer.ClientConn, balancer.BuildOptions) balancer.Balancer {\n\treturn b.instance\n}\nfunc (b *funcBalancerBuilder) Name() string { return b.name }\n\n\n\n\n\n\nfunc (s) TestBalancerErrorResolverPolling(t *testing.T) ", "output": "{\n\tfb := &funcBalancer{\n\t\tupdateClientConnState: func(s balancer.ClientConnState) error {\n\t\t\tif len(s.ResolverState.Addresses) == 0 {\n\t\t\t\treturn balancer.ErrBadResolverState\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\tconst balName = \"BalancerErrorResolverPolling\"\n\tbalancer.Register(&funcBalancerBuilder{name: balName, instance: fb})\n\n\ttestResolverErrorPolling(t,\n\t\tfunc(r *manual.Resolver) {\n\t\t\tr.CC.UpdateState(resolver.State{})\n\t\t}, func(r *manual.Resolver) {\n\t\t\tgo r.CC.UpdateState(resolver.State{Addresses: []resolver.Address{{Addr: \"x\"}}})\n\t\t},\n\t\tWithDefaultServiceConfig(fmt.Sprintf(`{ \"loadBalancingConfig\": [{\"%v\": {}}] }`, balName)))\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/135yshr/goracom\"\n\t\"github.com/135yshr/goracom/subscriber\"\n)\n\nvar (\n\temail string\n\tpassword string\n\timsi string\n)\n\n\n\nfunc main() {\n\tflag.Parse()\n\n\tif email == \"\" || password == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(-1)\n\t}\n\n\tif 0 < flag.NArg() {\n\t\timsi = flag.Arg(0)\n\t}\n\n\tc, err := goracom.NewClient(email, password)\n\terrToPanic(err)\n\n\ts := c.NewSubscriber()\n\tif imsi != \"\" {\n\t\tsub, err := s.Sim(imsi)\n\t\terrToPanic(err)\n\t\tprintSubscriber(*sub)\n\t} else {\n\t\tss, err := s.FindAll()\n\t\terrToPanic(err)\n\n\t\tfmt.Println(\"===============================\")\n\t\tfor _, sub := range *ss {\n\t\t\tprintSubscriber(sub)\n\t\t\tfmt.Println(\"===============================\")\n\t\t}\n\t}\n}\n\nfunc errToPanic(err error) {\n\tif err != nil {\n\t\tfmt.Printf(\"%s\\n\\n\", err)\n\t\tflag.Usage()\n\t\tos.Exit(-1)\n\t}\n}\n\nfunc printSubscriber(sub subscriber.Subscriber) {\n\tfmt.Println(\"IMSI=\", sub.IMSI)\n\tfmt.Println(\"SpeedClass=\", sub.SpeedClass)\n\tfmt.Println(\"GroupID=\", sub.GroupId)\n\tfmt.Println(\"OperatorID=\", sub.OperatorId)\n\tfmt.Println(\"ModuleType=\", sub.ModuleType)\n\tfmt.Println(\"APN=\", sub.APN)\n}\n\nfunc init() ", "output": "{\n\tflag.Usage = func() {\n\t\tfmt.Println(\"Usage: subscriber \")\n\t\tflag.PrintDefaults()\n\t}\n\tflag.StringVar(&email, \"email\", os.Getenv(\"SORACOM_EMAIL\"), \"Registered E-Mail\")\n\tflag.StringVar(&password, \"pw\", os.Getenv(\"SORACOM_PASSWORD\"), \"Login Password\")\n}"} {"input": "package proxy\n\nimport (\n\t\"store\"\n\t\"utils\"\n)\n\nconst (\n\tEFFICIENT_POOL_KEY = \"EfficientPoolKey\"\n)\n\nvar (\n\tefficientPool = InitEfficientPool()\n)\n\ntype EfficientPool struct {\n\tBasePool\n\tStorage store.SetStringStorer\n}\n\nfunc InitEfficientPool() *EfficientPool {\n\treturn &EfficientPool{BasePool: *InitBasePool(), Storage: store.RedisSet{}}\n}\n\nfunc (pool *EfficientPool) Add(proxy string) {\n\tpool.Storage.Add(EFFICIENT_POOL_KEY, proxy)\n}\n\nfunc (pool *EfficientPool) Remove(proxy string) {\n\tpool.Storage.Remove(EFFICIENT_POOL_KEY, proxy)\n}\n\n\n\nfunc Feedback(proxy string, ok bool, time int) {\n\tstablePool.Add(proxy, utils.EscapeToTime(ok, time))\n\n\tif !ok {\n\t\tefficientPool.Remove(proxy)\n\t}\n}\n\nfunc Rand() (ok bool, proxy string) ", "output": "{\n\treturn efficientPool.Storage.Rand(EFFICIENT_POOL_KEY)\n}"} {"input": "package fake\n\nimport (\n\tv2beta1 \"k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeAutoscalingV2beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeAutoscalingV2beta1) HorizontalPodAutoscalers(namespace string) v2beta1.HorizontalPodAutoscalerInterface {\n\treturn &FakeHorizontalPodAutoscalers{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeAutoscalingV2beta1) RESTClient() rest.Interface ", "output": "{\n\tvar ret *rest.RESTClient\n\treturn ret\n}"} {"input": "package http\n\nimport (\n\t\"net/http\"\n\t\"reflect\"\n)\n\n\ntype JSONErrorBuilder interface {\n\tBuild() JSONError\n\n\tCustomError(code int, errorType, msg string) JSONErrorBuilder\n\n\tFromError(e error) JSONErrorBuilder\n\n\tMessage(string) JSONErrorBuilder\n\n\tStatus(int) JSONErrorBuilder\n\n\tURL(string) JSONErrorBuilder\n}\n\ntype jsonErrorBuilder struct {\n\tinstance JSONError\n}\n\n\n\nfunc NewJSONError() JSONErrorBuilder {\n\treturn &jsonErrorBuilder{JSONError{\n\t\tStatus: http.StatusInternalServerError,\n\t}}\n}\n\nfunc (b *jsonErrorBuilder) Build() JSONError {\n\treturn b.instance\n}\n\n\n\nfunc (b *jsonErrorBuilder) FromError(e error) JSONErrorBuilder {\n\terrType := reflect.TypeOf(e)\n\tvar typeName string\n\tif errType.Kind() == reflect.Ptr {\n\t\ttypeName = errType.Elem().Name()\n\t} else {\n\t\ttypeName = errType.Name()\n\t}\n\n\tb.instance.Type = typeName\n\tb.instance.Message = e.Error()\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) Message(msg string) JSONErrorBuilder {\n\tb.instance.Message = msg\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) Status(status int) JSONErrorBuilder {\n\tb.instance.Status = status\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) URL(url string) JSONErrorBuilder {\n\tb.instance.MoreInfo = url\n\treturn b\n}\n\nvar _ JSONErrorBuilder = (*jsonErrorBuilder)(nil)\n\nfunc (b *jsonErrorBuilder) CustomError(\n\tcode int,\n\terrorType,\n\tmsg string,\n) JSONErrorBuilder ", "output": "{\n\tb.instance.Code = code\n\tb.instance.Type = errorType\n\tb.instance.Message = msg\n\n\treturn b\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n)\n\nfunc main() {\n\ttest(\"internal\")\n\ttest(\"external\")\n}\n\n\n\nfunc test(linkmode string) ", "output": "{\n\tout, err := exec.Command(\"go\", \"run\", \"-ldflags\", \"-B=0x12345678 -linkmode=\"+linkmode, filepath.Join(\"fixedbugs\", \"issue10607a.go\")).CombinedOutput()\n\tif err != nil {\n\t\tfmt.Printf(\"BUG: linkmode=%s %v\\n%s\\n\", linkmode, err, out)\n\t\tos.Exit(1)\n\t}\n}"} {"input": "package nat\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n\n\t\"github.com/cilium/cilium/pkg/byteorder\"\n\t\"github.com/cilium/cilium/pkg/tuple\"\n\t\"github.com/cilium/cilium/pkg/types\"\n)\n\n\n\n\ntype NatEntry4 struct {\n\tCreated uint64 `align:\"created\"`\n\tHostLocal uint64 `align:\"host_local\"`\n\tPad1 uint64 `align:\"pad1\"`\n\tPad2 uint64 `align:\"pad2\"`\n\tAddr types.IPv4 `align:\"to_saddr\"`\n\tPort uint16 `align:\"to_sport\"`\n}\n\n\nconst SizeofNatEntry4 = int(unsafe.Sizeof(NatEntry4{}))\n\n\nfunc (n *NatEntry4) GetValuePtr() unsafe.Pointer { return unsafe.Pointer(n) }\n\n\nfunc (n *NatEntry4) String() string {\n\treturn fmt.Sprintf(\"Addr=%s Port=%d Created=%d HostLocal=%d\\n\",\n\t\tn.Addr,\n\t\tn.Port,\n\t\tn.Created,\n\t\tn.HostLocal)\n}\n\n\n\n\n\nfunc (n *NatEntry4) ToHost() NatEntry {\n\tx := *n\n\tx.Port = byteorder.NetworkToHost16(n.Port)\n\treturn &x\n}\n\nfunc (n *NatEntry4) Dump(key NatKey, start uint64) string ", "output": "{\n\tvar which string\n\n\tif key.GetFlags()&tuple.TUPLE_F_IN != 0 {\n\t\twhich = \"DST\"\n\t} else {\n\t\twhich = \"SRC\"\n\t}\n\treturn fmt.Sprintf(\"XLATE_%s %s:%d Created=%s HostLocal=%d\\n\",\n\t\twhich,\n\t\tn.Addr,\n\t\tn.Port,\n\t\tNatDumpCreated(start, n.Created),\n\t\tn.HostLocal)\n}"} {"input": "package models\n\nimport \"fmt\"\n\n\nvar RoomPool = make([] *Room, 0)\n\n\n\n\n\n\n\nfunc FindRoom(d string) (int, *Room) {\n\tfor i, v := range RoomPool {\n\t\tif v.Name == d {\n\t\t\treturn i, v\n\t\t}\n\t}\n\treturn -1, &Room{}\n}\n\n\nfunc RemoveRoom(r *Room) {\n\n\tindex, _ := FindRoom(r.Name)\n\n\tif index != -1 {\n\t\tRoomPool = append(RoomPool[:index], RoomPool[index + 1:]...)\n\t}\n}\n\n\n\n\nfunc RemoveClient(c *Client) {\n\tfor _, room := range RoomPool{\n\t\tif room.Name == c.Room {\n\t\t\tif room.HasClient(c) {\n\t\t\t\troom.DeleteClient(c)\n\t\t\t\tif room.ClientCount() == 0 {\n\t\t\t\t\tRemoveRoom(room)\n\t\t\t\t\tPoolBroadcast(NewMessage(map[string]string{\n\t\t\t\t\t\t\"connectedClients\": fmt.Sprintf(\"%v\", GetAllClients()),\n\t\t\t\t\t\t\"numberOfRooms\": fmt.Sprintf(\"%v\", GetNumberOfRooms()),\n\t\t\t\t\t}))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\nfunc ListRooms() (int, []string) {\n\tpool := make([]string, 0)\n\tfor _, obj := range RoomPool {\n\t\tpool = append(pool, obj.Name)\n\t}\n\treturn len(RoomPool), pool\n}\n\n\nfunc PoolBroadcast(m Message) {\n\tfor _, room := range RoomPool {\n\t\troom.RoomBroadcast(m)\n\t}\n}\n\n\nfunc GetAllClients() int {\n\n\tclientSum := 0\n\tfor _, room := range RoomPool {\n\t\tclientSum += len(room.ClientPool)\n\t}\n\treturn clientSum\n}\n\n\nfunc GetNumberOfRooms() int{\n\treturn len(RoomPool)\n}\n\nfunc AddRoom(r *Room) ", "output": "{\n\tRoomPool = append(RoomPool, r)\n}"} {"input": "package throttler\n\nimport (\n\t\"vitess.io/vitess/go/sync2\"\n)\n\n\n\ntype MaxRateModule struct {\n\tmaxRate sync2.AtomicInt64\n\trateUpdateChan chan<- struct{}\n}\n\n\n\nfunc NewMaxRateModule(maxRate int64) *MaxRateModule {\n\treturn &MaxRateModule{\n\t\tmaxRate: sync2.NewAtomicInt64(maxRate),\n\t}\n}\n\n\n\n\n\nfunc (m *MaxRateModule) Stop() {}\n\n\nfunc (m *MaxRateModule) MaxRate() int64 {\n\treturn m.maxRate.Get()\n}\n\n\n\nfunc (m *MaxRateModule) SetMaxRate(rate int64) {\n\tm.maxRate.Set(rate)\n\tm.rateUpdateChan <- struct{}{}\n}\n\nfunc (m *MaxRateModule) Start(rateUpdateChan chan<- struct{}) ", "output": "{\n\tm.rateUpdateChan = rateUpdateChan\n}"} {"input": "package macos\n\n\n\nimport (\n\t\"os\"\n\n\t\"github.com/martinlindhe/formats/parse\"\n)\n\n\n\n\nfunc isCodeDirectory(b []byte) bool {\n\n\tif b[0] != 0xfa || b[1] != 0xde || b[2] != 0x0c || (b[3] != 0x01 && b[3] != 0x02) {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc parseCodeDirectory(file *os.File, pl parse.ParsedLayout) (*parse.ParsedLayout, error) {\n\n\n\tpos := int64(0)\n\tpl.FileKind = parse.MacOSResource\n\tpl.Layout = []parse.Layout{{\n\t\tOffset: pos,\n\t\tLength: 4, \n\t\tInfo: \"header\",\n\t\tType: parse.Group,\n\t\tChilds: []parse.Layout{\n\t\t\t{Offset: pos, Length: 4, Info: \"magic\", Type: parse.ASCII},\n\t\t}}}\n\n\treturn &pl, nil\n}\n\nfunc CodeDirectory(c *parse.Checker) (*parse.ParsedLayout, error) ", "output": "{\n\n\tif !isCodeDirectory(c.Header) {\n\t\treturn nil, nil\n\t}\n\treturn parseCodeDirectory(c.File, c.ParsedLayout)\n}"} {"input": "package main\n\n\n\n\n\nfunc injectBaz() (Baz, func(), error) ", "output": "{\n\tfoo, cleanup := provideFoo()\n\tbar, cleanup2, err := provideBar(foo)\n\tif err != nil {\n\t\tcleanup()\n\t\treturn 0, nil, err\n\t}\n\tbaz, err := provideBaz(bar)\n\tif err != nil {\n\t\tcleanup2()\n\t\tcleanup()\n\t\treturn 0, nil, err\n\t}\n\treturn baz, func() {\n\t\tcleanup2()\n\t\tcleanup()\n\t}, nil\n}"} {"input": "package build\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tMaxEncodedVersionLength = 100\n\n\tVersion = \"1.3.1\"\n)\n\n\n\n\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n\n\n\n\n\n\n\n\n\nfunc VersionCmp(a, b string) int {\n\taNums := strings.Split(a, \".\")\n\tbNums := strings.Split(b, \".\")\n\tfor i := 0; i < min(len(aNums), len(bNums)); i++ {\n\t\taInt, _ := strconv.Atoi(aNums[i])\n\t\tbInt, _ := strconv.Atoi(bNums[i])\n\t\tif aInt < bInt {\n\t\t\treturn -1\n\t\t} else if aInt > bInt {\n\t\t\treturn 1\n\t\t}\n\t}\n\tif len(aNums) < len(bNums) {\n\t\treturn -1\n\t} else if len(aNums) > len(bNums) {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\nfunc IsVersion(str string) bool ", "output": "{\n\tfor _, n := range strings.Split(str, \".\") {\n\t\tif _, err := strconv.Atoi(n); err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package demo\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"github.com/google/go-github/github\"\n\t\"golang.org/x/oauth2\"\n\t\"google.golang.org/appengine\"\n\t\"google.golang.org/appengine/log\"\n)\n\n\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"/\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tctx := appengine.NewContext(r)\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: os.Getenv(\"GITHUB_AUTH_TOKEN\")},\n\t)\n\ttc := oauth2.NewClient(ctx, ts)\n\tclient := github.NewClient(tc)\n\n\tcommits, _, err := client.Repositories.ListCommits(ctx, \"google\", \"go-github\", nil)\n\tif err != nil {\n\t\tlog.Errorf(ctx, \"ListCommits: %v\", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text/plain; charset=utf-8\")\n\tfor _, commit := range commits {\n\t\tfmt.Fprintln(w, commit.GetHTMLURL())\n\t}\n}\n\nfunc init() ", "output": "{\n\thttp.HandleFunc(\"/\", handler)\n}"} {"input": "package linebot\n\nimport (\n\t\"context\"\n\t\"fmt\"\n)\n\n\n\nfunc (client *Client) IssueLinkToken(userID string) *IssueLinkTokenCall {\n\treturn &IssueLinkTokenCall{\n\t\tc: client,\n\t\tuserID: userID,\n\t}\n}\n\n\ntype IssueLinkTokenCall struct {\n\tc *Client\n\tctx context.Context\n\n\tuserID string\n}\n\n\n\n\n\nfunc (call *IssueLinkTokenCall) Do() (*LinkTokenResponse, error) {\n\tendpoint := fmt.Sprintf(APIEndpointLinkToken, call.userID)\n\tres, err := call.c.post(call.ctx, endpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer closeResponse(res)\n\treturn decodeToLinkTokenResponse(res)\n}\n\nfunc (call *IssueLinkTokenCall) WithContext(ctx context.Context) *IssueLinkTokenCall ", "output": "{\n\tcall.ctx = ctx\n\treturn call\n}"} {"input": "package main\n\nimport (\n\t\"labix.org/v2/mgo\"\n)\n\n\nfunc DB(cfg *Config) *mgo.Database {\n\treturn cfg.Mongo.session.DB(cfg.Mongo.Database)\n}\n\n\n\n\nfunc C(cfg *Config) *mgo.Collection ", "output": "{\n\treturn cfg.Mongo.session.DB(cfg.Mongo.Database).C(cfg.Mongo.Collection)\n}"} {"input": "package rpcclient\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\n\t\"github.com/decred/dcrd/dcrjson/v4\"\n)\n\n\n\ntype FutureRawResult cmdRes\n\n\n\n\n\n\n\n\n\n\nfunc (c *Client) RawRequestAsync(ctx context.Context, method string, params []json.RawMessage) *FutureRawResult {\n\tif method == \"\" {\n\t\treturn (*FutureRawResult)(newFutureError(ctx, errors.New(\"no method\")))\n\t}\n\n\tif params == nil {\n\t\tparams = []json.RawMessage{}\n\t}\n\n\tid := c.NextID()\n\trawRequest := &dcrjson.Request{\n\t\tJsonrpc: \"1.0\",\n\t\tID: id,\n\t\tMethod: method,\n\t\tParams: params,\n\t}\n\tmarshalledJSON, err := json.Marshal(rawRequest)\n\tif err != nil {\n\t\treturn (*FutureRawResult)(newFutureError(ctx, err))\n\t}\n\n\tresponseChan := make(chan *response, 1)\n\tjReq := &jsonRequest{\n\t\tid: id,\n\t\tmethod: method,\n\t\tcmd: nil,\n\t\tmarshalledJSON: marshalledJSON,\n\t\tresponseChan: responseChan,\n\t}\n\tc.sendRequest(ctx, jReq)\n\n\treturn &FutureRawResult{ctx: ctx, c: responseChan}\n}\n\n\n\n\n\n\nfunc (c *Client) RawRequest(ctx context.Context, method string, params []json.RawMessage) (json.RawMessage, error) {\n\treturn c.RawRequestAsync(ctx, method, params).Receive()\n}\n\nfunc (r *FutureRawResult) Receive() (json.RawMessage, error) ", "output": "{\n\treturn receiveFuture(r.ctx, r.c)\n}"} {"input": "package hostqueue\n\nimport (\n\t\"html/template\"\n\t\"net/http\"\n\t\"regexp\"\n\n\t\"appengine\"\n\n\t\"github.com/gorilla/mux\"\n)\n\ntype Status struct {\n\tName string `json:\"name\"`\n\tHosts []Host `json:\"hosts\"`\n\tNext int `json:\"next\"`\n}\n\n\nfunc DisplayGroupStatus(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tpathVars := mux.Vars(r)\n\n\tuuid := pathVars[\"uuid\"]\n\tctx.Infof(\"UUID: %s\", uuid)\n\n\tif isValidUUID((uuid)) {\n\t\tgroup, err := GetGroupByUUID(ctx, uuid)\n\t\tctx.Infof(\"group: %v\", group)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tstatus := convertToStatus(group)\n\t\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\n\t\tvar tpl = template.Must(template.ParseGlob(\"templates/*.html\"))\n\t\tif err := tpl.ExecuteTemplate(w, \"status.html\", status); err != nil {\n\t\t\tctx.Infof(\"%v\", err)\n\t\t}\n\n\t} else {\n\t\tw.Write([]byte(\"Invalid group\"))\n\t}\n}\n\n\n\nfunc isValidUUID(text string) bool {\n\tr := regexp.MustCompile(\"^[a-z0-9]{8}-[a-z0-9]{4}-[1-5][a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{12}$\")\n\treturn r.MatchString(text)\n}\n\nfunc convertToStatus(group Group) Status ", "output": "{\n\treturn Status{\n\t\tName: group.GroupName,\n\t\tNext: group.Next,\n\t\tHosts: group.Hosts,\n\t\t}\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/utils\"\n\nfunc init() {\n\tc := &ImportTpFromFolder{\n\t\tname: \"import_tp_from_folder\",\n\t\trpcMethod: utils.APIerSv1ImportTariffPlanFromFolder,\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype ImportTpFromFolder struct {\n\tname string\n\trpcMethod string\n\trpcParams *utils.AttrImportTPFromFolder\n\trpcResult string\n\t*CommandExecuter\n}\n\nfunc (self *ImportTpFromFolder) Name() string {\n\treturn self.name\n}\n\nfunc (self *ImportTpFromFolder) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *ImportTpFromFolder) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &utils.AttrImportTPFromFolder{}\n\t}\n\treturn self.rpcParams\n}\n\n\n\nfunc (self *ImportTpFromFolder) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *ImportTpFromFolder) PostprocessRpcParams() error ", "output": "{\n\treturn nil\n}"} {"input": "package v1alpha1\n\nimport (\n\tv1alpha1 \"k8s.io/api/scheduling/v1alpha1\"\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\t\"github.com/hyperhq/client-go/kubernetes/scheme\"\n\trest \"github.com/hyperhq/client-go/rest\"\n)\n\ntype SchedulingV1alpha1Interface interface {\n\tRESTClient() rest.Interface\n\tPriorityClassesGetter\n}\n\n\ntype SchedulingV1alpha1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *SchedulingV1alpha1Client) PriorityClasses() PriorityClassInterface {\n\treturn newPriorityClasses(c)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*SchedulingV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SchedulingV1alpha1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *SchedulingV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *SchedulingV1alpha1Client {\n\treturn &SchedulingV1alpha1Client{c}\n}\n\n\n\n\n\nfunc (c *SchedulingV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc setConfigDefaults(config *rest.Config) error ", "output": "{\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}"} {"input": "package chip8\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc Test0xAnnn(t *testing.T) ", "output": "{\n\tc := New([]byte{\n\t\t0xAF, 0xFF,\n\t})\n\n\tc.Step()\n\n\tif c.i != 0xFFF {\n\t\tt.Error(\"i was not set to 0xFFF as expected\")\n\t}\n}"} {"input": "package gojws\n\nimport (\n\t\"encoding/base64\"\n\t\"strings\"\n)\n\n\n\nfunc safeDecode(str string) ([]byte, error) ", "output": "{\n\tlenMod4 := len(str) % 4\n\tif lenMod4 > 0 {\n\t\tstr = str + strings.Repeat(\"=\", 4-lenMod4)\n\t}\n\n\treturn base64.URLEncoding.DecodeString(str)\n}"} {"input": "package pku_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/applepi-icpc/icarus/client/pku/satellite\"\n)\n\nfunc ensureToken(a string, b string, c int, t *testing.T) {\n\ttoken := pku.EnToken(a, b, c)\n\tt.Logf(\"Token = %s\", token)\n\taa, bb, cc, err := pku.DeToken(token)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to decode token: %s\", err.Error())\n\t}\n\tt.Logf(\"Decoded = %s, %s, %d\", aa, bb, cc)\n\tif a != aa || b != bb || c != cc {\n\t\tt.Fatalf(\"wrong answer\")\n\t}\n}\n\n\n\nfunc TestToken(t *testing.T) ", "output": "{\n\tensureToken(\"13\", \"BKPC001271892\", 17, t)\n\tensureToken(\"13\", \"BKPC$\", 17, t)\n\tensureToken(\"13\", \"BKPC$$\", 17, t)\n\tensureToken(\"13\", \"BKPC#\", 17, t)\n\tensureToken(\"13\", \"BKPC$#\", 17, t)\n\tensureToken(\"13\", \"BKPC$$#\", 17, t)\n}"} {"input": "package thriftclient\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"git.apache.org/thrift.git/lib/go/thrift\"\n)\n\ntype transportFactory struct {\n\tserviceIP string\n\tservicePort int\n\ttimeOut int64\n}\n\nfunc NewTransportFactory(serviceIP string, servicePort int, timeOut int64) *transportFactory {\n\treturn &transportFactory{serviceIP: serviceIP, servicePort: servicePort, timeOut: timeOut}\n}\n\n\nfunc (tf *transportFactory) CreateObj() (interface{}, error) {\n\ttransportFactory := thrift.NewTTransportFactory()\n\tvar err error\n\tvar transport thrift.TTransport\n\taddr := fmt.Sprintf(\"%s:%d\", tf.serviceIP, tf.servicePort)\n\ttransport, err = thrift.NewTSocketTimeout(addr, time.Duration(tf.timeOut)*time.Millisecond)\n\tif err != nil {\n\t\tfmt.Println(\"Error opening socket:\", err)\n\t\treturn nil, err\n\t}\n\ttransport = transportFactory.GetTransport(transport)\n\tif err := transport.Open(); err != nil {\n\t\tfmt.Println(\"Error transport opening:\", err)\n\t\treturn nil, err\n\t}\n\treturn transport, nil\n}\n\n\nfunc (tf *transportFactory) DestroyObj(t interface{}) error {\n\tvalue, ok := t.(thrift.TTransport)\n\tif ok {\n\t\tif value.IsOpen() {\n\t\t\tvalue.Close()\n\t\t}\n\t}\n\treturn nil\n\n}\n\n\n\n\nfunc (tf *transportFactory) ValidateObj(t interface{}) error ", "output": "{\n\tvalue, ok := t.(thrift.TTransport)\n\tif ok {\n\t\tif value.IsOpen() {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn errors.New(\"transport is not validate\")\n}"} {"input": "package profile\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\n\t\"github.com/sirupsen/logrus\"\n\n\t\"github.com/supergiant/control/pkg/storage\"\n)\n\nconst DefaultKubeProfilePreifx = \"/supergiant/profile\"\n\ntype Service struct {\n\tprefix string\n\tkubeProfileStorage storage.Interface\n}\n\nfunc NewService(prefix string, s storage.Interface) *Service {\n\treturn &Service{\n\t\tprefix: prefix,\n\t\tkubeProfileStorage: s,\n\t}\n}\n\nfunc (s *Service) Get(ctx context.Context, profileId string) (*Profile, error) {\n\tlogrus.Debugf(\"get cloud profile by id %s\", profileId)\n\tprofileData, err := s.kubeProfileStorage.Get(ctx, s.prefix, profileId)\n\tprofile := &Profile{}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = json.Unmarshal(profileData, profile)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn profile, nil\n}\n\n\n\nfunc (s *Service) GetAll(ctx context.Context) ([]Profile, error) {\n\tvar (\n\t\tprofiles []Profile\n\t\tprofile Profile\n\t)\n\n\tprofilesData, err := s.kubeProfileStorage.GetAll(ctx, s.prefix)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, profileData := range profilesData {\n\t\terr = json.Unmarshal(profileData, &profile)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tprofiles = append(profiles, profile)\n\t}\n\n\treturn profiles, nil\n}\n\nfunc (s *Service) Create(ctx context.Context, profile *Profile) error ", "output": "{\n\tprofileData, err := json.Marshal(profile)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.kubeProfileStorage.Put(ctx, s.prefix, profile.ID, profileData)\n}"} {"input": "package cloudfoundry_test\n\nimport (\n\t\"github.com/javiermanzano/goth\"\n\t\"github.com/javiermanzano/goth/providers/cloudfoundry\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc Test_New(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\tp := provider()\n\n\ta.Equal(p.ClientKey, os.Getenv(\"UAA_CLIENT_ID\"))\n\ta.Equal(p.Secret, os.Getenv(\"UAA_CLIENT_SECRET\"))\n\ta.Equal(p.CallbackURL, \"/foo\")\n}\n\nfunc Test_Implements_Provider(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\ta.Implements((*goth.Provider)(nil), provider())\n}\n\nfunc Test_BeginAuth(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\tp := provider()\n\tsession, err := p.BeginAuth(\"test_state\")\n\ts := session.(*cloudfoundry.Session)\n\ta.NoError(err)\n\ta.Contains(s.AuthURL, \"https://cf.example.com/oauth/authorize\")\n}\n\n\n\nfunc provider() *cloudfoundry.Provider {\n\treturn cloudfoundry.New(\"https://cf.example.com/\", os.Getenv(\"UAA_CLIENT_ID\"), os.Getenv(\"UAA_CLIENT_SECRET\"), \"/foo\")\n}\n\nfunc Test_SessionFromJSON(t *testing.T) ", "output": "{\n\tt.Parallel()\n\ta := assert.New(t)\n\n\tp := provider()\n\tsession, err := p.UnmarshalSession(`{\"AuthURL\":\"https://cf.example.com/oauth/authorize\",\"AccessToken\":\"1234567890\"}`)\n\ta.NoError(err)\n\n\ts := session.(*cloudfoundry.Session)\n\ta.Equal(s.AuthURL, \"https://cf.example.com/oauth/authorize\")\n\ta.Equal(s.AccessToken, \"1234567890\")\n}"} {"input": "package cryptex\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/sha256\"\n\t\"crypto/x509\"\n\t\"errors\"\n)\n\n\n\nfunc NewRSA(publicKey []byte, comment string) *RSA {\n\treturn &RSA{\n\t\tPublicKey: publicKey,\n\t\tcomment: comment,\n\t}\n}\n\n\nfunc (c *RSA) Comment() string {\n\treturn c.comment\n}\n\n\n\nfunc (c *RSA) Close(inputs, secrets [][]byte) error {\n\tif len(inputs) != 2 {\n\t\treturn errors.New(\"RSA supports exactly 2 inputs\")\n\t}\n\tif len(secrets) != 1 {\n\t\treturn errors.New(\"RSA supports only a single secret\")\n\t}\n\tsecret := secrets[0]\n\n\tpubKey, err := c.publicKey()\n\tif err != nil {\n\t\treturn err\n\t}\n\tct, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pubKey, secret, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tinputs[0] = ct\n\tinputs[1] = nil\n\treturn nil\n}\n\n\n\n\n\nfunc (c *RSA) publicKey() (*rsa.PublicKey, error) {\n\tpubKey, err := x509.ParsePKIXPublicKey(c.PublicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif pubKey, ok := pubKey.(*rsa.PublicKey); ok {\n\t\treturn pubKey, nil\n\t}\n\treturn nil, errors.New(\"invalid RSA public key\")\n}\n\nfunc (c *RSA) Open(secrets, inputs [][]byte) error ", "output": "{\n\tif len(inputs) != 2 {\n\t\treturn errors.New(\"len(inputs) must be 2\")\n\t}\n\tif len(secrets) != 1 {\n\t\treturn errors.New(\"Too many secrets expected\")\n\t}\n\n\tct := inputs[0]\n\tprivKey, err := x509.ParsePKCS1PrivateKey(inputs[1])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsecret, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privKey, ct, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsecrets[0] = secret\n\treturn nil\n}"} {"input": "package connect\n\nimport \"io\"\nimport \"github.com/LilyPad/GoLilyPad/packet\"\n\ntype RequestAuthenticate struct {\n\tUsername string\n\tPassword string\n}\n\nfunc NewRequestAuthenticate(username string, password string) (this *RequestAuthenticate) {\n\tthis = new(RequestAuthenticate)\n\tthis.Username = username\n\tthis.Password = password\n\treturn\n}\n\nfunc (this *RequestAuthenticate) Id() int {\n\treturn REQUEST_AUTHENTICATE\n}\n\ntype requestAuthenticateCodec struct {\n\n}\n\nfunc (this *requestAuthenticateCodec) Decode(reader io.Reader) (request Request, err error) {\n\trequestAuthenticate := new(RequestAuthenticate)\n\trequestAuthenticate.Username, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\trequestAuthenticate.Password, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\trequest = requestAuthenticate\n\treturn\n}\n\nfunc (this *requestAuthenticateCodec) Encode(writer io.Writer, request Request) (err error) {\n\trequestAuthenticate := request.(*RequestAuthenticate)\n\terr = packet.WriteString(writer, requestAuthenticate.Username)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = packet.WriteString(writer, requestAuthenticate.Password)\n\treturn\n}\n\ntype ResultAuthenticate struct {\n\n}\n\nfunc NewResultAuthenticate() (this *ResultAuthenticate) {\n\tthis = new(ResultAuthenticate)\n\treturn\n}\n\nfunc (this *ResultAuthenticate) Id() int {\n\treturn REQUEST_AUTHENTICATE\n}\n\ntype resultAuthenticateCodec struct {\n\n}\n\nfunc (this *resultAuthenticateCodec) Decode(reader io.Reader) (result Result, err error) {\n\tresult = new(ResultAuthenticate)\n\treturn\n}\n\n\n\nfunc (this *resultAuthenticateCodec) Encode(writer io.Writer, result Result) (err error) ", "output": "{\n\treturn\n}"} {"input": "package firestore \n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}\n\n\n\n\nfunc DefaultAuthScopes() []string ", "output": "{\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t\t\"https:www.googleapis.com/auth/datastore\",\n\t}\n}"} {"input": "package fakevtworkerclient\n\nimport (\n\t\"time\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/youtube/vitess/go/vt/logutil\"\n\t\"github.com/youtube/vitess/go/vt/vtctl/fakevtctlclient\"\n\t\"github.com/youtube/vitess/go/vt/worker/vtworkerclient\"\n)\n\n\n\n\ntype FakeVtworkerClient struct {\n\t*fakevtctlclient.FakeLoggerEventStreamingClient\n}\n\n\nfunc NewFakeVtworkerClient() *FakeVtworkerClient {\n\treturn &FakeVtworkerClient{fakevtctlclient.NewFakeLoggerEventStreamingClient()}\n}\n\n\n\n\n\n\n\ntype perAddrFakeVtworkerClient struct {\n\t*FakeVtworkerClient\n\taddr string\n}\n\n\nfunc (c *perAddrFakeVtworkerClient) ExecuteVtworkerCommand(ctx context.Context, args []string) (logutil.EventStream, error) {\n\treturn c.FakeLoggerEventStreamingClient.StreamResult(c.addr, args)\n}\n\n\nfunc (c *perAddrFakeVtworkerClient) Close() {}\n\nfunc (f *FakeVtworkerClient) FakeVtworkerClientFactory(addr string, dialTimeout time.Duration) (vtworkerclient.Client, error) ", "output": "{\n\treturn &perAddrFakeVtworkerClient{f, addr}, nil\n}"} {"input": "package decorators\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t\"github.com/antham/chyle/chyle/convh\"\n)\n\ntype shellConfig map[string]struct {\n\tCOMMAND string\n\tORIGKEY string\n\tDESTKEY string\n}\n\n\n\ntype shell struct {\n\tCOMMAND string\n\tORIGKEY string\n\tDESTKEY string\n}\n\nfunc (s shell) Decorate(commitMap *map[string]interface{}) (*map[string]interface{}, error) {\n\tvar tmp interface{}\n\tvar value string\n\tvar ok bool\n\tvar err error\n\n\tif tmp, ok = (*commitMap)[s.ORIGKEY]; !ok {\n\t\treturn commitMap, nil\n\t}\n\n\tif value, err = convh.ConvertToString(tmp); err != nil {\n\t\treturn commitMap, nil\n\t}\n\n\tif (*commitMap)[s.DESTKEY], err = s.execute(value); err != nil {\n\t\treturn commitMap, err\n\t}\n\n\treturn commitMap, nil\n}\n\n\n\nfunc newShell(configs shellConfig) []Decorater {\n\tresults := []Decorater{}\n\n\tfor _, config := range configs {\n\t\tresults = append(results, shell(config))\n\t}\n\n\treturn results\n}\n\nfunc (s shell) execute(value string) (string, error) ", "output": "{\n\tvar result []byte\n\tvar err error\n\n\tcommand := fmt.Sprintf(`echo \"%s\"|%s`, strings.Replace(value, `\"`, `\\\"`, -1), s.COMMAND)\n\n\tif result, err = exec.Command(\"sh\", \"-c\", command).Output(); err != nil {\n\t\treturn \"\", fmt.Errorf(\"%s : command failed\", command)\n\t}\n\n\treturn string(result[:len(result)-1]), nil\n}"} {"input": "package sdkclientfactory\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\tmock_sdkclient \"github.com/aws/amazon-ecs-agent/agent/dockerclient/sdkclient/mocks\"\n\t\"github.com/golang/mock/gomock\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestFindClientAPIVersion(t *testing.T) ", "output": "{\n\tctx, cancel := context.WithCancel(context.TODO())\n\tdefer cancel()\n\tctrl := gomock.NewController(t)\n\tmockClient := mock_sdkclient.NewMockClient(ctrl)\n\tfactory := NewFactory(ctx, expectedEndpoint)\n\n\tfor _, version := range getAgentSupportedDockerVersions() {\n\t\tmockClient.EXPECT().ClientVersion().Return(string(version))\n\t\tassert.Equal(t, version, factory.FindClientAPIVersion(mockClient))\n\t}\n}"} {"input": "package character\n\ntype Histogram struct {\n\tcounts [256]uint16\n}\n\nfunc StringHistogram(text string) *Histogram {\n\thistogram := &Histogram{}\n\tfor i := 0; i < len(text); i++ {\n\t\thistogram.Add(Char(text[i]))\n\t}\n\treturn histogram\n}\n\n\n\nfunc (h *Histogram) Count(char Char) int {\n\treturn int(h.counts[char])\n}\n\nfunc (h *Histogram) Add(char Char) ", "output": "{\n\th.counts[char]++\n}"} {"input": "package testutil\n\nimport (\n\t\"archive/zip\"\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"strings\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc VerifyZipFileEntry(reader *zip.Reader, expectedFilename string, expectedContent string) {\n\tvar foundEntries []string\n\tfor _, entry := range reader.File {\n\t\tif entry.Name == expectedFilename {\n\t\t\tcontent, e := entry.Open()\n\t\t\tExpect(e).NotTo(HaveOccurred())\n\t\t\tExpect(ioutil.ReadAll(content)).To(MatchRegexp(expectedContent), \"for filename \"+expectedFilename)\n\t\t\treturn\n\t\t}\n\t\tfoundEntries = append(foundEntries, entry.Name)\n\t}\n\tFail(\"Did not find entry with name \" + expectedFilename + \". Found only: \" + strings.Join(foundEntries, \", \"))\n}\n\nfunc CreateZip(contents map[string]string) *bytes.Buffer ", "output": "{\n\tvar result bytes.Buffer\n\tzipWriter := zip.NewWriter(&result)\n\tdefer zipWriter.Close()\n\tfor filename, fileContents := range contents {\n\t\tentryWriter, e := zipWriter.Create(filename)\n\t\tExpect(e).NotTo(HaveOccurred())\n\t\tentryWriter.Write([]byte(fileContents))\n\n\t}\n\te := zipWriter.Close()\n\tExpect(e).NotTo(HaveOccurred())\n\treturn &result\n}"} {"input": "package messages\n\nimport (\n\t\"bytes\"\n\t\"message-delivery-system/src/utils\"\n)\n\n\ntype ListResponse struct {\n\tList []uint64\n\tReceiver uint64\n}\n\n\n\n\n\nfunc (l ListResponse) GetMessageType() MessageType {\n\treturn ListResponseMessage\n}\n\n\nfunc (l ListResponse) GetData() []byte {\n\tbuf := new(bytes.Buffer)\n\tdata, _ := utils.Uint64ListToByteArray(buf, l.List)\n\treturn data\n}\n\n\nfunc (l ListResponse) GetReceiverIds() []uint64 {\n\tvar receivers []uint64\n\treturn append(receivers, l.Receiver)\n}\n\nfunc NewListResponse(data []byte) ListResponse ", "output": "{\n\tbuf := bytes.NewReader(data)\n\tlist, _ := utils.ByteArrayToUint64List(buf, data)\n\treturn ListResponse{List:list}\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\n\n\nfunc PodContainerKey(namespace, podName, containerName string) string {\n\treturn fmt.Sprintf(\"namespace:%s/pod:%s/container:%s\", namespace, podName, containerName)\n}\n\n\n\nfunc NamespaceKey(namespace string) string {\n\treturn fmt.Sprintf(\"namespace:%s\", namespace)\n}\n\nfunc NodeKey(node string) string {\n\treturn fmt.Sprintf(\"node:%s\", node)\n}\n\nfunc NodeContainerKey(node, container string) string {\n\treturn fmt.Sprintf(\"node:%s/container:%s\", node, container)\n}\n\nfunc ClusterKey() string {\n\treturn \"cluster\"\n}\n\nfunc PodKey(namespace, podName string) string ", "output": "{\n\treturn fmt.Sprintf(\"namespace:%s/pod:%s\", namespace, podName)\n}"} {"input": "package elements\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"log\"\n)\n\ntype ElementsGroup struct {\n\tChoice []*ElementsGroupChoice\n}\n\nfunc NewElementsGroup() *ElementsGroup {\n\tret := &ElementsGroup{}\n\treturn ret\n}\n\nfunc (m *ElementsGroup) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tif m.Choice != nil {\n\t\tfor _, c := range m.Choice {\n\t\t\tc.MarshalXML(e, xml.StartElement{})\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\nfunc (m *ElementsGroup) Validate() error {\n\treturn m.ValidateWithPath(\"ElementsGroup\")\n}\n\n\nfunc (m *ElementsGroup) ValidateWithPath(path string) error {\n\tfor i, v := range m.Choice {\n\t\tif err := v.ValidateWithPath(fmt.Sprintf(\"%s/Choice[%d]\", path, i)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *ElementsGroup) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error ", "output": "{\nlElementsGroup:\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch el := tok.(type) {\n\t\tcase xml.StartElement:\n\t\t\tswitch el.Name {\n\t\t\tcase xml.Name{Space: \"http:purl.org/dc/elements/1.1/\", Local: \"any\"}:\n\t\t\t\ttmp := NewElementsGroupChoice()\n\t\t\t\tif err := d.DecodeElement(&tmp.Any, &el); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tm.Choice = append(m.Choice, tmp)\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"skipping unsupported element on ElementsGroup %v\", el.Name)\n\t\t\t\tif err := d.Skip(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\tcase xml.EndElement:\n\t\t\tbreak lElementsGroup\n\t\tcase xml.CharData:\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package users\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime/middleware\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewDeleteUserByIDParams() DeleteUserByIDParams {\n\tvar ()\n\treturn DeleteUserByIDParams{}\n}\n\n\n\n\n\ntype DeleteUserByIDParams struct {\n\n\tHTTPRequest *http.Request `json:\"-\"`\n\n\tUserID string\n}\n\n\n\n\n\nfunc (o *DeleteUserByIDParams) bindUserID(rawData []string, hasKey bool, formats strfmt.Registry) error {\n\tvar raw string\n\tif len(rawData) > 0 {\n\t\traw = rawData[len(rawData)-1]\n\t}\n\n\to.UserID = raw\n\n\treturn nil\n}\n\nfunc (o *DeleteUserByIDParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error ", "output": "{\n\tvar res []error\n\to.HTTPRequest = r\n\n\trUserID, rhkUserID, _ := route.Params.GetOK(\"userID\")\n\tif err := o.bindUserID(rUserID, rhkUserID, route.Formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package core\n\nimport (\n\t\"net\";\n\t\"os\";\n\t\"log\";\n)\n\ntype acceptFunc\tfunc(net.Conn)\ntype errorFunc\tfunc(os.Error)\n\n\ntype listenConn struct {\n\tlisten\tnet.Listener;\n\taccept\tacceptFunc;\n\terror\terrorFunc;\n}\n\nfunc newListenConn(listen net.Listener, accept acceptFunc, error errorFunc) *listenConn {\n\tl := &listenConn{listen, accept, error};\n\tgo l.run();\n\treturn l;\n}\n\n\n\nfunc (l *listenConn) Addr() net.Addr {\n\treturn l.listen.Addr()\n}\n\nfunc (l *listenConn) run() ", "output": "{\n\tlog.Stderrf(\"listening on %s\\n\", l.listen.Addr());\n\tfor {\n\t\tconn, err := l.listen.Accept();\n\t\tif err != nil {\n\t\t\tlog.Stderrf(\"accept failed: %s\\n\", err);\n\t\t\tl.listen.Close();\n\t\t\tif l.error != nil {\n\t\t\t\tl.error(err);\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tl.accept(conn);\n\t}\n}"} {"input": "package testing\n\n\n\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n\tclientset \"k8s.io/kubernetes/pkg/client/clientset_generated/clientset\"\n\tkubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\"\n\tcontainertest \"k8s.io/kubernetes/pkg/kubelet/container/testing\"\n)\n\ntype fakeNetworkHost struct {\n\tfakeNamespaceGetter\n\tkubeClient clientset.Interface\n\tLegacy bool\n\tRuntime *containertest.FakeRuntime\n}\n\nfunc NewFakeHost(kubeClient clientset.Interface) *fakeNetworkHost {\n\thost := &fakeNetworkHost{kubeClient: kubeClient, Legacy: true, Runtime: &containertest.FakeRuntime{}}\n\treturn host\n}\n\n\n\nfunc (fnh *fakeNetworkHost) GetKubeClient() clientset.Interface {\n\treturn nil\n}\n\nfunc (nh *fakeNetworkHost) GetRuntime() kubecontainer.Runtime {\n\treturn nh.Runtime\n}\n\nfunc (nh *fakeNetworkHost) SupportsLegacyFeatures() bool {\n\treturn nh.Legacy\n}\n\ntype fakeNamespaceGetter struct {\n\tns string\n}\n\nfunc (nh *fakeNamespaceGetter) GetNetNS(containerID string) (string, error) {\n\treturn nh.ns, nil\n}\n\nfunc (fnh *fakeNetworkHost) GetPodByName(name, namespace string) (*v1.Pod, bool) ", "output": "{\n\treturn nil, false\n}"} {"input": "package httpserver\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\n\nfunc TestWriteHeader(t *testing.T) {\n\tw := httptest.NewRecorder()\n\trecordRequest := NewResponseRecorder(w)\n\trecordRequest.WriteHeader(401)\n\tif w.Code != 401 || recordRequest.status != 401 {\n\t\tt.Fatalf(\"Expected Response status to be set to 401, but found %d\\n\", recordRequest.status)\n\t}\n}\n\nfunc TestWrite(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tresponseTestString := \"test\"\n\trecordRequest := NewResponseRecorder(w)\n\tbuf := []byte(responseTestString)\n\t_, _ = recordRequest.Write(buf)\n\tif recordRequest.size != len(buf) {\n\t\tt.Fatalf(\"Expected the bytes written counter to be %d, but instead found %d\\n\", len(buf), recordRequest.size)\n\t}\n\tif w.Body.String() != responseTestString {\n\t\tt.Fatalf(\"Expected Response Body to be %s , but found %s\\n\", responseTestString, w.Body.String())\n\t}\n}\n\nfunc TestNewResponseRecorder(t *testing.T) ", "output": "{\n\tw := httptest.NewRecorder()\n\trecordRequest := NewResponseRecorder(w)\n\tif !(recordRequest.ResponseWriter == w) {\n\t\tt.Fatalf(\"Expected Response writer in the Recording to be same as the one sent\\n\")\n\t}\n\tif recordRequest.status != http.StatusOK {\n\t\tt.Fatalf(\"Expected recorded status to be http.StatusOK (%d) , but found %d\\n \", http.StatusOK, recordRequest.status)\n\t}\n}"} {"input": "package kthlargest\n\nimport \"container/heap\"\n\ntype MaxHeap struct {\n\tSize int\n\tNums []int\n}\n\nfunc (h *MaxHeap) Insert(x int) {\n\tif h.Len() < h.Size {\n\t\theap.Push(h, x)\n\t} else if h.Nums[0] < x {\n\t\th.Nums[0] = x\n\t\theap.Fix(h, 0)\n\t}\n}\n\nfunc (h *MaxHeap) Len() int { return len(h.Nums) }\n\n\n\nfunc (h *MaxHeap) Swap(i, j int) {\n\th.Nums[i], h.Nums[j] = h.Nums[j], h.Nums[i]\n}\n\nfunc (h *MaxHeap) Push(x interface{}) {\n\th.Nums = append(h.Nums, x.(int))\n}\n\nfunc (h *MaxHeap) Pop() interface{} {\n\tn := len(h.Nums)\n\tx := h.Nums[n-1]\n\th.Nums = h.Nums[:n-1]\n\treturn x\n}\n\nfunc findKthLargest(nums []int, k int) int {\n\th := &MaxHeap{Size: k}\n\tfor _, num := range nums {\n\t\th.Insert(num)\n\t}\n\treturn h.Nums[0]\n}\n\nfunc (h *MaxHeap) Less(i, j int) bool ", "output": "{\n\treturn h.Nums[i] < h.Nums[j]\n}"} {"input": "package stream_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/synapse-garden/sg-proto/store\"\n\t\"github.com/synapse-garden/sg-proto/stream\"\n\tsgt \"github.com/synapse-garden/sg-proto/testing\"\n\n\t\"github.com/boltdb/bolt\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype StreamSuite struct {\n\tdb *bolt.DB\n\ttmpDir string\n}\n\nvar _ = Suite(&StreamSuite{})\n\nfunc (s *StreamSuite) SetUpTest(c *C) {\n\tdb, tmpDir, err := sgt.TempDB(\"sg-stream-test\")\n\tc.Assert(err, IsNil)\n\tc.Assert(db.Update(store.Wrap(\n\t\tstore.Migrate(store.VerCurrent),\n\t\tstore.SetupBuckets(stream.StreamBucket),\n\t)), IsNil)\n\ts.db, s.tmpDir = db, tmpDir\n}\n\n\n\nfunc (s *StreamSuite) TearDownTest(c *C) ", "output": "{\n\tif db := s.db; db != nil {\n\t\tc.Assert(sgt.CleanupDB(db), IsNil)\n\t\tc.Assert(os.Remove(s.tmpDir), IsNil)\n\t}\n}"} {"input": "package websocket\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/b00lduck/raspberry_soundboard/persistence\"\n)\n\ntype Hub struct {\n\tclients map[*Client]bool\n\tbroadcast chan bool\n\tregister chan *Client\n\tunregister chan *Client\n\tpersistence *persistence.Persistence\n}\n\nfunc NewHub(persistence *persistence.Persistence) *Hub {\n\treturn &Hub{\n\t\tbroadcast: make(chan bool),\n\t\tregister: make(chan *Client),\n\t\tunregister: make(chan *Client),\n\t\tclients: make(map[*Client]bool),\n\t\tpersistence: persistence,\n\t}\n}\n\nfunc (h *Hub) Broadcast() {\n\th.broadcast <- true\n}\n\n\n\nfunc (h *Hub) Run() ", "output": "{\n\tfor {\n\t\tselect {\n\t\tcase client := <-h.register:\n\t\t\tlog.Info(\"register client\")\n\t\t\th.clients[client] = true\n\t\t\tclient.send <- h.persistence.JsonState()\n\t\tcase client := <-h.unregister:\n\t\t\tif _, ok := h.clients[client]; ok {\n\t\t\t\tlog.Info(\"unregister client\")\n\t\t\t\tdelete(h.clients, client)\n\t\t\t\tclose(client.send)\n\t\t\t}\n\t\tcase <-h.broadcast:\n\t\t\tfor client := range h.clients {\n\t\t\t\tselect {\n\t\t\t\tcase client.send <- h.persistence.JsonState():\n\t\t\t\tdefault:\n\t\t\t\t\tclose(client.send)\n\t\t\t\t\tdelete(h.clients, client)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package stager\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/hatofmonkeys/cloudfocker/utils\"\n\n\t\"github.com/cloudfoundry-incubator/linux-circus/buildpackrunner\"\n\t\"github.com/cloudfoundry-incubator/runtime-schema/models\"\n)\n\ntype BuildpackRunner interface {\n\tRun() error\n}\n\nfunc RunBuildpack(writer io.Writer, runner BuildpackRunner) error {\n\tfmt.Fprintln(writer, \"Running Buildpacks...\")\n\treturn runner.Run()\n}\n\nfunc NewBuildpackRunner(buildpackDir string) *buildpackrunner.Runner {\n\tprepareMd5BuildpacksDir(buildpackDir, \"/tmp/buildpacks\")\n\tvar err error\n\tdirs := []string{}\n\tif dirs, err = utils.SubDirs(buildpackDir); err != nil {\n\t\tlog.Fatalf(\" %s\", err)\n\t}\n\tconfig := models.NewCircusTailorConfig(dirs)\n\treturn buildpackrunner.New(&config)\n}\n\n\n\nfunc prepareMd5BuildpacksDir(src string, dst string) {\n\tos.MkdirAll(src, 0755)\n\tos.MkdirAll(dst, 0755)\n\tvar err error\n\tdirs := []string{}\n\tif dirs, err = utils.SubDirs(src); err != nil {\n\t\tlog.Fatalf(\" %s\", err)\n\t}\n\tfor _, dir := range dirs {\n\t\tif err := os.Symlink(src+\"/\"+dir, dst+\"/\"+md5sum(dir)); err != nil {\n\t\t\tlog.Fatalf(\" %s\", err)\n\t\t}\n\t}\n}\n\nfunc md5sum(src string) string {\n\treturn fmt.Sprintf(\"%x\", md5.Sum([]byte(src)))\n}\n\nfunc ValidateStagedApp(cloudfockerHome string) error ", "output": "{\n\tif _, err := os.Stat(cloudfockerHome + \"/droplet/app\"); err != nil {\n\t\treturn fmt.Errorf(\"Staging failed - have you added a buildpack for this type of application?\")\n\t}\n\tif _, err := os.Stat(cloudfockerHome + \"/droplet/staging_info.yml\"); err != nil {\n\t\treturn fmt.Errorf(\"Staging failed - no staging info was produced by the matching buildpack!\")\n\t}\n\treturn nil\n}"} {"input": "package methods\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/barnettzqg/journey/configuration\"\n\t\"github.com/barnettzqg/journey/database\"\n\t\"github.com/barnettzqg/journey/slug\"\n\t\"github.com/barnettzqg/journey/structure\"\n)\n\n\nvar Blog *structure.Blog\n\nvar assetPath = []byte(\"/assets/\")\n\nfunc UpdateBlog(b *structure.Blog, userId int64) error {\n\tnavigation, err := json.Marshal(b.NavigationItems)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = database.UpdateSettings(b.Title, b.Description, b.Logo, b.Cover, b.PostsPerPage, b.ActiveTheme, navigation, time.Now(), userId)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = GenerateBlog()\n\tif err != nil {\n\t\tlog.Panic(\"Error: couldn't generate blog data:\", err)\n\t}\n\treturn nil\n}\n\nfunc UpdateActiveTheme(activeTheme string, userId int64) error {\n\terr := database.UpdateActiveTheme(activeTheme, time.Now(), userId)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = GenerateBlog()\n\tif err != nil {\n\t\tlog.Panic(\"Error: couldn't generate blog data:\", err)\n\t}\n\treturn nil\n}\n\n\n\nfunc GenerateBlog() error ", "output": "{\n\tif Blog != nil {\n\t\tBlog.Lock()\n\t\tdefer Blog.Unlock()\n\t}\n\tblog, err := database.RetrieveBlog()\n\tif err != nil {\n\t\treturn err\n\t}\n\tblog.Url = []byte(configuration.Config.Url)\n\tblog.AssetPath = assetPath\n\tfor index, _ := range blog.NavigationItems {\n\t\tblog.NavigationItems[index].Slug = slug.Generate(blog.NavigationItems[index].Label, \"navigation\")\n\t}\n\tBlog = blog\n\treturn nil\n}"} {"input": "package yaml\n\nimport (\n\t\"fmt\"\n)\n\nfunc (this *Job) Name() JobKey {\n\treturn this.name\n}\n\nfunc (this *Job) Validate(c Context) error {\n\treturn nil\n}\n\nfunc (this *Job) InDesiredState(c Context) (bool, error) {\n\treturn true, nil\n}\n\n\n\nfunc (this *Job) Execute(c Context) error {\n\tc.log(\"Executing Job %s\", this.name)\n\n\treturn nil\n}\n\nfunc (this *Job) Finish(c Context) error {\n\treturn nil\n}\n\nfunc (this *Job) get_task() *task {\n\tif this.task == nil {\n\t\tthis.task = alloc_task(this)\n\t\tthis.task.description = fmt.Sprintf(\"Job[%s]\", this.name)\n\n\t\tfor _, container := range this.container_instances {\n\t\t\tthis.task.DependsOn(container.get_task())\n\t\t}\n\t}\n\treturn this.task\n}\n\nfunc (this *Job) Prepare(c Context) error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/nlopes/slack\"\n)\n\nfunc getSlackParams() slack.PostMessageParameters {\n\tparams := slack.NewPostMessageParameters()\n\tparams.Username = \"rotator\"\n\tparams.IconEmoji = \":umbrella:\"\n\treturn params\n}\n\nfunc doSlackDM(message string, destination string) error {\n\tvar destID string\n\tslackAPI := slack.New(config.SlackKey)\n\tuserList, err := slackAPI.GetUsers()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, u := range userList {\n\t\tif u.Name == destination {\n\t\t\tdestID = u.ID\n\t\t}\n\t}\n\tif destID == \"\" {\n\t\tif *flagDebug {\n\t\t\tfmt.Printf(\"user %s doesn't appear in Slack, fail silently\\n\", destination)\n\t\t}\n\t\treturn nil\n\t}\n\n\t_, _, channel, err := slackAPI.OpenIMChannel(destID)\n\tif err != nil {\n\t\treturn errors.New(\"Couldn't open IM channel\")\n\t}\n\n\tslackAPI.PostMessage(channel, message, getSlackParams())\n\tif *flagDebug {\n\t\tfmt.Printf(\"Sent DM on channel ID %s to %s\\n\", channel, destID)\n\t}\n\tslackAPI.CloseIMChannel(channel)\n\treturn err\n}\n\n\n\nfunc doSlackNotify(message string, destination string) error ", "output": "{\n\n\tslackAPI := slack.New(config.SlackKey)\n\tchannel := config.SlackChannel\n\tif destination != \"\" {\n\t\tchannel = destination\n\t}\n\tif *flagDebug {\n\t\tfmt.Printf(\"Attempting to send %s to %s with token %s\\n\", message, channel, config.SlackKey)\n\t}\n\tc, timestamp, err := slackAPI.PostMessage(channel, message, getSlackParams())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif *flagDebug {\n\t\tfmt.Printf(\"Message sent successfully to channel %s at %s\\n\", c, timestamp)\n\t}\n\treturn err\n}"} {"input": "package agent\n\nimport (\n\t\"github.com/hashicorp/consul/consul/structs\"\n\t\"net/http\"\n\t\"sort\"\n)\n\n\n\nfunc coordinateDisabled(resp http.ResponseWriter, req *http.Request) (interface{}, error) {\n\tresp.WriteHeader(401)\n\tresp.Write([]byte(\"Coordinate support disabled\"))\n\treturn nil, nil\n}\n\n\n\ntype sorter struct {\n\tcoordinates structs.Coordinates\n}\n\n\nfunc (s *sorter) Len() int {\n\treturn len(s.coordinates)\n}\n\n\nfunc (s *sorter) Swap(i, j int) {\n\ts.coordinates[i], s.coordinates[j] = s.coordinates[j], s.coordinates[i]\n}\n\n\nfunc (s *sorter) Less(i, j int) bool {\n\treturn s.coordinates[i].Node < s.coordinates[j].Node\n}\n\n\n\n\n\n\n\nfunc (s *HTTPServer) CoordinateNodes(resp http.ResponseWriter, req *http.Request) (interface{}, error) {\n\targs := structs.DCSpecificRequest{}\n\tif done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {\n\t\treturn nil, nil\n\t}\n\n\tvar out structs.IndexedCoordinates\n\tdefer setMeta(resp, &out.QueryMeta)\n\tif err := s.agent.RPC(\"Coordinate.ListNodes\", &args, &out); err != nil {\n\t\tsort.Sort(&sorter{out.Coordinates})\n\t\treturn nil, err\n\t}\n\n\tif out.Coordinates == nil {\n\t\tout.Coordinates = make(structs.Coordinates, 0)\n\t}\n\treturn out.Coordinates, nil\n}\n\nfunc (s *HTTPServer) CoordinateDatacenters(resp http.ResponseWriter, req *http.Request) (interface{}, error) ", "output": "{\n\tvar out []structs.DatacenterMap\n\tif err := s.agent.RPC(\"Coordinate.ListDatacenters\", struct{}{}, &out); err != nil {\n\t\tfor i := range out {\n\t\t\tsort.Sort(&sorter{out[i].Coordinates})\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tfor i, _ := range out {\n\t\tif out[i].Coordinates == nil {\n\t\t\tout[i].Coordinates = make(structs.Coordinates, 0)\n\t\t}\n\t}\n\tif out == nil {\n\t\tout = make([]structs.DatacenterMap, 0)\n\t}\n\treturn out, nil\n}"} {"input": "package unversioned\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/testapi\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\ntype HTTPClientFunc func(*http.Request) (*http.Response, error)\n\n\n\n\ntype FakeRESTClient struct {\n\tClient HTTPClient\n\tCodec runtime.Codec\n\tReq *http.Request\n\tResp *http.Response\n\tErr error\n}\n\nfunc (c *FakeRESTClient) Get() *Request {\n\treturn NewRequest(c, \"GET\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Put() *Request {\n\treturn NewRequest(c, \"PUT\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Patch(_ api.PatchType) *Request {\n\treturn NewRequest(c, \"PATCH\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Post() *Request {\n\treturn NewRequest(c, \"POST\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Delete() *Request {\n\treturn NewRequest(c, \"DELETE\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Do(req *http.Request) (*http.Response, error) {\n\tc.Req = req\n\tif c.Client != HTTPClient(nil) {\n\t\treturn c.Client.Do(req)\n\t}\n\treturn c.Resp, c.Err\n}\n\nfunc (f HTTPClientFunc) Do(req *http.Request) (*http.Response, error) ", "output": "{\n\treturn f(req)\n}"} {"input": "package util\n\nimport \"os/exec\"\n\n\n\ntype binRunner func(string, ...string) ([]byte, error)\n\n\n\n\n\n\n\ntype Permissions struct {\n\tbinRunner binRunner\n}\n\n\n\nfunc NewPermissions() *Permissions {\n\treturn &Permissions{\n\t\tbinRunner: defaultBinRunner,\n\t}\n}\n\n\n\n\nfunc (p *Permissions) IsAdmin() (bool, error) {\n\treturn p.isAdmin()\n}\n\nfunc defaultBinRunner(bin string, args ...string) ([]byte, error) ", "output": "{\n\treturn exec.Command(bin, args...).CombinedOutput()\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\n\n\n\n\ntype MsgMemPool struct{}\n\n\n\nfunc (msg *MsgMemPool) BtcDecode(r io.Reader, pver uint32) error {\n\tif pver < BIP0035Version {\n\t\tstr := fmt.Sprintf(\"mempool message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgMemPool.BtcDecode\", str)\n\t}\n\n\treturn nil\n}\n\n\n\n\n\n\n\nfunc (msg *MsgMemPool) Command() string {\n\treturn CmdMemPool\n}\n\n\n\nfunc (msg *MsgMemPool) MaxPayloadLength(pver uint32) uint32 {\n\treturn 0\n}\n\n\n\nfunc NewMsgMemPool() *MsgMemPool {\n\treturn &MsgMemPool{}\n}\n\nfunc (msg *MsgMemPool) BtcEncode(w io.Writer, pver uint32) error ", "output": "{\n\tif pver < BIP0035Version {\n\t\tstr := fmt.Sprintf(\"mempool message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgMemPool.BtcEncode\", str)\n\t}\n\n\treturn nil\n}"} {"input": "package controller_test\n\nimport \"testing\"\n\n\n\n\n\nfunc AssertNotNil(t *testing.T, actualValue interface{}) {\n\tif actualValue == nil {\n\t\tt.Errorf(\"\\n got: %v\\ndidn't want: %v\", actualValue, nil)\n\t}\n}\n\nfunc AssertEqual(t *testing.T, actualValue interface{}, expectedValue interface{}) ", "output": "{\n\tif actualValue != expectedValue {\n\t\tt.Errorf(\"\\n got: %v\\nwant: %v\", actualValue, expectedValue)\n\t}\n}"} {"input": "package consul\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/abronan/valkeyrie/store\"\n\t\"github.com/abronan/valkeyrie/store/consul\"\n\t\"github.com/containous/traefik/old/provider\"\n\t\"github.com/containous/traefik/old/provider/kv\"\n\t\"github.com/containous/traefik/old/types\"\n\t\"github.com/containous/traefik/safe\"\n)\n\nvar _ provider.Provider = (*Provider)(nil)\n\n\ntype Provider struct {\n\tkv.Provider `mapstructure:\",squash\" export:\"true\"`\n}\n\n\n\n\n\n\nfunc (p *Provider) Provide(configurationChan chan<- types.ConfigMessage, pool *safe.Pool) error {\n\treturn p.Provider.Provide(configurationChan, pool)\n}\n\n\nfunc (p *Provider) CreateStore() (store.Store, error) {\n\tp.SetStoreType(store.CONSUL)\n\tconsul.Register()\n\treturn p.Provider.CreateStore()\n}\n\nfunc (p *Provider) Init(constraints types.Constraints) error ", "output": "{\n\terr := p.Provider.Init(constraints)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstore, err := p.CreateStore()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to Connect to KV store: %v\", err)\n\t}\n\n\tp.SetKVClient(store)\n\treturn nil\n}"} {"input": "package strings\n\nimport (\n\t\"strings\"\n)\n\n\nfunc RemoveSpace(s string) (d string) {\n\tif IsBlank(s) {\n\t\treturn\n\t}\n\td = s\n\tsps := [...]string{\"\\t\", \"\\n\", \"\\v\", \"\\f\", \"\\r\", \" \"}\n\tfor _, sp := range sps {\n\t\td = strings.Replace(d, sp, \"\", -1)\n\t}\n\treturn\n}\n\n\nfunc RemoveBlank(s string) (d string) {\n\tif IsBlank(s) {\n\t\treturn\n\t}\n\td = strings.TrimSpace(s)\n\tsps := [...]string{\"\\t\", \"\\n\", \"\\v\", \"\\f\", \"\\r\", \" \"}\n\tfor _, sp := range sps {\n\t\td = strings.Replace(d, sp, \"\", -1)\n\t}\n\treturn\n}\n\n\n\nfunc RemoveStart(s, remove string) string {\n\tif IsBlank(s) || IsBlank(remove) {\n\t\treturn s\n\t}\n\tif strings.HasPrefix(s, remove) {\n\t\treturn s[len(remove):]\n\t}\n\treturn s\n}\n\n\n\n\n\n\nfunc Remove(s, remove string) string {\n\tif IsBlank(s) || IsBlank(remove) {\n\t\treturn s\n\t}\n\treturn strings.Replace(s, remove, \"\", -1)\n}\n\nfunc RemoveEnd(s, remove string) string ", "output": "{\n\tif IsBlank(s) || IsBlank(remove) {\n\t\treturn s\n\t}\n\tif strings.HasSuffix(s, remove) {\n\t\treturn s[0 : len(s)-len(remove)]\n\t}\n\treturn s\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/adjust/rmq\"\n)\n\nfunc main() {\n\tconnection := rmq.OpenConnection(\"handler\", \"tcp\", \"localhost:6379\", 2)\n\thttp.Handle(\"/overview\", NewHandler(connection))\n\tfmt.Printf(\"Handler listening on http://localhost:3333/overview\\n\")\n\thttp.ListenAndServe(\":3333\", nil)\n}\n\ntype Handler struct {\n\tconnection rmq.Connection\n}\n\nfunc NewHandler(connection rmq.Connection) *Handler {\n\treturn &Handler{connection: connection}\n}\n\n\n\nfunc (handler *Handler) ServeHTTP(writer http.ResponseWriter, request *http.Request) ", "output": "{\n\tlayout := request.FormValue(\"layout\")\n\trefresh := request.FormValue(\"refresh\")\n\n\tqueues := handler.connection.GetOpenQueues()\n\tstats := handler.connection.CollectStats(queues)\n\tlog.Printf(\"queue stats\\n%s\", stats)\n\tfmt.Fprint(writer, stats.GetHtml(layout, refresh))\n}"} {"input": "package model\n\n\ntype Sample struct {\n\tMetric Metric\n\tValue SampleValue\n\tTimestamp Timestamp\n}\n\n\nfunc (s *Sample) Equal(o *Sample) bool {\n\tif s == o {\n\t\treturn true\n\t}\n\n\tif !s.Metric.Equal(o.Metric) {\n\t\treturn false\n\t}\n\tif !s.Timestamp.Equal(o.Timestamp) {\n\t\treturn false\n\t}\n\tif !s.Value.Equal(o.Value) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\ntype Samples []*Sample\n\nfunc (s Samples) Len() int {\n\treturn len(s)\n}\n\n\n\n\nfunc (s Samples) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\n\nfunc (s Samples) Equal(o Samples) bool {\n\tif len(s) != len(o) {\n\t\treturn false\n\t}\n\n\tfor i, sample := range s {\n\t\tif !sample.Equal(o[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (s Samples) Less(i, j int) bool ", "output": "{\n\tswitch {\n\tcase s[i].Metric.Before(s[j].Metric):\n\t\treturn true\n\tcase s[j].Metric.Before(s[i].Metric):\n\t\treturn false\n\tcase s[i].Timestamp.Before(s[j].Timestamp):\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}"} {"input": "package kubeapiserver\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\tgenericregistry \"k8s.io/apiserver/pkg/registry/generic/registry\"\n\tgenericapiserver \"k8s.io/apiserver/pkg/server\"\n)\n\n\ntype RESTOptionsFactory struct {\n\tDeleteCollectionWorkers int\n\tEnableGarbageCollection bool\n\tEnableWatchCache bool\n\tStorageFactory genericapiserver.StorageFactory\n}\n\n\n\nfunc (f *RESTOptionsFactory) GetRESTOptions(resource schema.GroupResource) (generic.RESTOptions, error) ", "output": "{\n\tstorageConfig, err := f.StorageFactory.NewConfig(resource)\n\tif err != nil {\n\t\treturn generic.RESTOptions{}, fmt.Errorf(\"Unable to find storage destination for %v, due to %v\", resource, err.Error())\n\t}\n\n\tret := generic.RESTOptions{\n\t\tStorageConfig: storageConfig,\n\t\tDecorator: generic.UndecoratedStorage,\n\t\tDeleteCollectionWorkers: f.DeleteCollectionWorkers,\n\t\tEnableGarbageCollection: f.EnableGarbageCollection,\n\t\tResourcePrefix: f.StorageFactory.ResourcePrefix(resource),\n\t}\n\tif f.EnableWatchCache {\n\t\tret.Decorator = genericregistry.StorageWithCacher\n\t}\n\n\treturn ret, nil\n}"} {"input": "package joltDB\n\nimport (\n\t\"github.com/boltdb/bolt\"\n)\n\nvar boltdbr *bolt.DB\nvar dbr = apiConn(boltdbr)\n\nfunc OpenReadOnly(dir string) error {\n\treturn dbr.apiOpenReadOnly(dir)\n}\n\n\n\nfunc ListReadOnly(bucket string) ([]byte, error) {\n\treturn dbr.apiList(bucket)\n}\n\nfunc ListPrefixReadOnly(bucket, prefix string) ([]byte, error) {\n\treturn dbrw.apiListPrefix(bucket, prefix)\n}\n\nfunc ListRangeReadOnly(bucket, start, stop string) ([]byte, error) {\n\treturn dbrw.apiListRange(bucket, start, stop)\n}\n\nfunc GetOneReadOnly(bucket, key string) ([]byte, error) {\n\treturn dbr.apiGetOne(bucket, key)\n}\n\nfunc CloseReadOnly() ", "output": "{\n\tdbr.apiClose()\n}"} {"input": "package embedded\n\nimport (\n\t\"time\"\n)\n\ntype Pollfunc func() interface{}\n\n\n\nfunc Poll(f Pollfunc, period time.Duration, sink chan interface{}) chan bool ", "output": "{\n\tkill := make(chan bool)\n\tgo func(kill chan bool) {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-kill:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tif period > 0 {\n\t\t\t\t\ttime.Sleep(period)\n\t\t\t\t}\n\t\t\t\tsink <- f()\n\t\t\t}\n\t\t}\n\t}(kill)\n\treturn kill\n}"} {"input": "package chunk\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/djbarber/ipfs-hack/blocks\"\n\t\"github.com/djbarber/ipfs-hack/blocks/key\"\n\t\"github.com/djbarber/ipfs-hack/util\"\n\t\"io\"\n\t\"testing\"\n)\n\n\n\nfunc chunkData(t *testing.T, data []byte) map[key.Key]*blocks.Block {\n\tr := NewRabin(bytes.NewReader(data), 1024*256)\n\n\tblkmap := make(map[key.Key]*blocks.Block)\n\n\tfor {\n\t\tblk, err := r.NextBytes()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tb := blocks.NewBlock(blk)\n\t\tblkmap[b.Key()] = b\n\t}\n\n\treturn blkmap\n}\n\nfunc TestRabinChunkReuse(t *testing.T) {\n\tdata := make([]byte, 1024*1024*16)\n\tutil.NewTimeSeededRand().Read(data)\n\n\tch1 := chunkData(t, data[1000:])\n\tch2 := chunkData(t, data)\n\n\tvar extra int\n\tfor k, _ := range ch2 {\n\t\t_, ok := ch1[k]\n\t\tif !ok {\n\t\t\textra++\n\t\t}\n\t}\n\n\tif extra > 2 {\n\t\tt.Log(\"too many spare chunks made\")\n\t}\n}\n\nfunc TestRabinChunking(t *testing.T) ", "output": "{\n\tdata := make([]byte, 1024*1024*16)\n\tutil.NewTimeSeededRand().Read(data)\n\n\tr := NewRabin(bytes.NewReader(data), 1024*256)\n\n\tvar chunks [][]byte\n\n\tfor {\n\t\tchunk, err := r.NextBytes()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tchunks = append(chunks, chunk)\n\t}\n\n\tfmt.Printf(\"average block size: %d\\n\", len(data)/len(chunks))\n\n\tunchunked := bytes.Join(chunks, nil)\n\tif !bytes.Equal(unchunked, data) {\n\t\tfmt.Printf(\"%d %d\\n\", len(unchunked), len(data))\n\t\tt.Fatal(\"data was chunked incorrectly\")\n\t}\n}"} {"input": "package message\n\n\n\ntype PubackMessage struct {\n\tfixedHeader\n\n\tpacketID []byte\n}\n\n\n\n\n\nfunc (p *PubackMessage) PacketID() []byte {\n\treturn p.packetID\n}\n\nfunc (p *PubackMessage) SetPacketID(v []byte) ", "output": "{\n\tp.packetID = v\n}"} {"input": "package argparse\n\n\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\ntype ArgumentParser struct {\n\tStdout io.Writer\n\n\tStderr io.Writer\n\n\tMessages Messages\n\n\tHelpSwitches []string\n\n\tRoot *Command\n\n\tfinalized bool\n}\n\n\nfunc New(cmd *Command) *ArgumentParser {\n\tap := &ArgumentParser{\n\t\tStdout: os.Stdout,\n\t\tStderr: os.Stderr,\n\t\tMessages: DefaultMessages_en,\n\t\tHelpSwitches: []string{\"-h\", \"--help\"},\n\t\tRoot: cmd,\n\t}\n\tcmd.init(nil, ap)\n\tif cmd.Name == \"\" {\n\t\tcmd.Name = os.Args[0]\n\t}\n\treturn ap\n}\n\n\nfunc (self *ArgumentParser) Add(arg *Argument) {\n\tself.Root.Add(arg)\n}\n\n\nfunc (self *ArgumentParser) New(c *Command) *Command {\n\treturn self.Root.New(c)\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (self *ArgumentParser) ParseAndExit() {\n\tself.Parse()\n\tos.Exit(0)\n}\n\nfunc (self *ArgumentParser) parseArgv(argv []string) *parseResults {\n\tparser := parserState{}\n\tresults := parser.runParser(self, argv)\n\treturn results\n}\n\nfunc (self *ArgumentParser) Parse() ", "output": "{\n\tresults := self.parseArgv(os.Args[1:])\n\n\tcmd := results.triggeredCommand\n\n\tif results.helpRequested {\n\t\thelpString := self.helpString(cmd, results.ancestorCommands)\n\t\tfmt.Fprintln(self.Stdout, helpString)\n\t\tos.Exit(0)\n\t} else if results.parseError != nil {\n\t\tfmt.Fprintln(self.Stderr, results.parseError.Error())\n\t\tos.Exit(1)\n\t}\n\n\tif cmd.Function != nil {\n\t\terr := cmd.Function(cmd, cmd.Values)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(self.Stderr, err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}"} {"input": "package main\n\nfunc main() {\n\tpoison()\n\ttest()\n}\n\n\n\n\n\nfunc test() {\n\ta := 2\n\tx := &a\n\tif x != compare(&x) {\n\t\tpanic(\"not possible\")\n\t}\n}\n\n\nfunc compare(x **int) *int {\n\tvar y *int\n\tif x == &y {\n\t\tpanic(\"not possible\")\n\t}\n\tgrow()\n\tif x == &y {\n\t\tpanic(\"not possible\")\n\t}\n\treturn *x\n}\n\n\nfunc grow() {\n\tvar large [1 << 16]uintptr\n\tuse(large[:])\n}\n\n\nfunc use(_ []uintptr) { }\n\nfunc poison() ", "output": "{\n\tvar large [256]uintptr\n\tfor i := range large {\n\t\tlarge[i] = 1\n\t}\n\tuse(large[:])\n}"} {"input": "package http\n\nimport (\n\t\"go-common/library/ecode\"\n\tbm \"go-common/library/net/http/blademaster\"\n\t\"go-common/library/net/metadata\"\n\t\"strconv\"\n)\n\n\n\n\nfunc webAdGameList(c *bm.Context) ", "output": "{\n\tip := metadata.String(c, metadata.RemoteIP)\n\tparams := c.Request.Form\n\t_, ok := c.Get(\"mid\")\n\tif !ok {\n\t\tc.JSON(nil, ecode.NoLogin)\n\t\treturn\n\t}\n\tpnStr := params.Get(\"pn\")\n\tpsStr := params.Get(\"ps\")\n\tpn, err := strconv.Atoi(pnStr)\n\tif err != nil || pn <= 0 {\n\t\tpn = 1\n\t}\n\tps, err := strconv.Atoi(psStr)\n\tif err != nil || ps <= 0 || ps > 20 {\n\t\tps = 20\n\t}\n\tkeywordStr := params.Get(\"keyword\")\n\tletterStr := params.Get(\"letter\")\n\tdata, err := adSvc.GameList(c, keywordStr, letterStr, pn, ps, ip)\n\tif err != nil {\n\t\tc.JSON(nil, err)\n\t\treturn\n\t}\n\tc.JSON(data, nil)\n}"} {"input": "package lang\n\nimport \"math\"\nimport \"gojvm/native\"\nimport \"gojvm/rtda\"\n\nconst jlDouble = \"java/lang/Double\"\n\nfunc init() {\n\tnative.Register(jlDouble, \"doubleToRawLongBits\", \"(D)J\", doubleToRawLongBits)\n\tnative.Register(jlDouble, \"longBitsToDouble\", \"(J)D\", longBitsToDouble)\n}\n\n\n\n\n\n\n\nfunc longBitsToDouble(frame *rtda.Frame) {\n\tbits := frame.LocalVars().GetLong(0)\n\tvalue := math.Float64frombits(uint64(bits)) \n\tframe.OperandStack().PushDouble(value)\n}\n\nfunc doubleToRawLongBits(frame *rtda.Frame) ", "output": "{\n\tvalue := frame.LocalVars().GetDouble(0)\n\tbits := math.Float64bits(value) \n\tframe.OperandStack().PushLong(int64(bits))\n}"} {"input": "package pfilter\n\nimport (\n\t\"net\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\ntype FilteredConn struct {\n\tsource *PacketFilter\n\tpriority int\n\n\trecvBuffer chan packet\n\n\tfilter Filter\n\n\tdeadline atomic.Value\n\tclosed chan struct{}\n}\n\n\nfunc (r *FilteredConn) LocalAddr() net.Addr {\n\treturn r.source.LocalAddr()\n}\n\n\nfunc (r *FilteredConn) SetReadDeadline(t time.Time) error {\n\tr.deadline.Store(t)\n\treturn nil\n}\n\n\nfunc (r *FilteredConn) SetWriteDeadline(t time.Time) error {\n\treturn r.source.SetWriteDeadline(t)\n}\n\n\nfunc (r *FilteredConn) SetDeadline(t time.Time) error {\n\tr.SetReadDeadline(t)\n\treturn r.SetWriteDeadline(t)\n}\n\n\nfunc (r *FilteredConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {\n\tselect {\n\tcase <-r.closed:\n\t\treturn 0, errClosed\n\tdefault:\n\t}\n\n\tif r.filter != nil {\n\t\tr.filter.Outgoing(b, addr)\n\t}\n\treturn r.source.WriteTo(b, addr)\n}\n\n\n\n\n\nfunc (r *FilteredConn) Close() error {\n\tselect {\n\tcase <-r.closed:\n\t\treturn errClosed\n\tdefault:\n\t}\n\tclose(r.closed)\n\tr.source.removeConn(r)\n\treturn nil\n}\n\nfunc (r *FilteredConn) ReadFrom(b []byte) (n int, addr net.Addr, err error) ", "output": "{\n\tselect {\n\tcase <-r.closed:\n\t\treturn 0, nil, errClosed\n\tdefault:\n\t}\n\n\tvar timeout <-chan time.Time\n\n\tif deadline, ok := r.deadline.Load().(time.Time); ok && !deadline.IsZero() {\n\t\ttimer := time.NewTimer(deadline.Sub(time.Now()))\n\t\ttimeout = timer.C\n\t\tdefer timer.Stop()\n\t}\n\n\tselect {\n\tcase <-timeout:\n\t\treturn 0, nil, &timeoutError{}\n\tcase pkt := <-r.recvBuffer:\n\t\tcopy(b[:pkt.n], pkt.buf)\n\t\tbufPool.Put(pkt.buf[:maxPacketSize])\n\t\treturn pkt.n, pkt.addr, pkt.err\n\tcase <-r.closed:\n\t\treturn 0, nil, errClosed\n\t}\n}"} {"input": "package synctest\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nconst (\n\ttimeout = 100 * time.Millisecond\n)\n\n\n\nfunc TestNotifyLockAlreadyLocked(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tnl.Lock()\n\tch := nl.NotifyLock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"received on channel\")\n\tcase <-time.After(timeout):\n\t}\n}\n\nfunc TestNotifyLockOnUnlock(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tnl.Lock()\n\tch := nl.NotifyLock()\n\tnl.Unlock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"got a lock notification on unlock\")\n\tcase <-time.After(timeout):\n\t}\n}\n\nfunc TestNotifyUnlock(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tch := nl.NotifyUnlock()\n\tnl.Lock()\n\tnl.Unlock()\n\tselect {\n\tcase <-ch:\n\tcase <-time.After(timeout):\n\t\tt.Fatalf(\"didn't get unlock notification after %s\", timeout)\n\t}\n}\n\nfunc TestNotifyUnlockAlreadyUnlocked(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tnl.Lock()\n\tnl.Unlock()\n\tch := nl.NotifyUnlock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"got unlock notification\")\n\tcase <-time.After(timeout):\n\t}\n}\n\nfunc TestNofifyUnlockOnLock(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tch := nl.NotifyUnlock()\n\tnl.Lock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"got unlock notification on lock\")\n\tcase <-time.After(timeout):\n\t}\n}\n\nfunc TestNotifyLock(t *testing.T) ", "output": "{\n\tnl := NewNotifyingLocker()\n\tch := nl.NotifyLock()\n\tnl.Lock()\n\tselect {\n\tcase <-ch:\n\tcase <-time.After(timeout):\n\t\tt.Fatalf(\"didn't receive on channel after %s\", timeout)\n\t}\n}"} {"input": "package hugolib\n\nimport (\n\t\"github.com/spf13/hugo/tpl\"\n\t\"testing\"\n)\n\nconst (\n\twin_base = \"c:\\\\a\\\\windows\\\\path\\\\layout\"\n\twin_path = \"c:\\\\a\\\\windows\\\\path\\\\layout\\\\sub1\\\\index.html\"\n)\n\n\n\nfunc TestTemplatePathSeparator(t *testing.T) ", "output": "{\n\ttmpl := new(tpl.GoHTMLTemplate)\n\tif name := tmpl.GenerateTemplateNameFrom(win_base, win_path); name != \"sub1/index.html\" {\n\t\tt.Fatalf(\"Template name incorrect. got %s but expected %s\", name, \"sub1/index.html\")\n\t}\n}"} {"input": "package data\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"v22/waterCart/db\"\n\t\"v22/waterCart/util\"\n\n\t\"gopkg.in/mgo.v2\"\n)\n\nconst (\n\tIMEI_TNS_COLL = \"imeitns\"\n)\n\ntype IMEITNS struct {\n\tImei string `json:\"imei\"`\n\tIp string `json:\"ip\"`\n\tArea string `json:\"area\"`\n\tStatus int `json:\"status\"`\n\tCreate string `json:\"create\"`\n}\n\n\nfunc (i *IMEITNS) InsertITNS() (*mgo.Session, error) {\n\tsession := db.GetMongo()\n\tdefer session.Close()\n\tif session != nil {\n\t\tc := session.DB(os.Getenv(util.TS_DPI_URL_MONGO)).C(IMEI_TNS_COLL)\n\n\t\treturn session, c.Insert(i)\n\t}\n\n\treturn nil, errors.New(\"MONGO SESSION IS NULL\")\n}\n\n\n\nfunc (i *IMEITNS) GetDB() (*mgo.Session, *mgo.Collection) ", "output": "{\n\tsession := db.GetMongo()\n\n\tif session != nil {\n\t\tc := session.DB(os.Getenv(util.TS_DPI_URL_MONGO)).C(IMEI_TNS_COLL)\n\t\treturn session, c\n\t}\n\n\treturn nil, nil\n}"} {"input": "package lg\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Stopwatch struct {\n\tstart, stop time.Time\n\tlogger *Logger\n}\n\nfunc (s *Stopwatch) IsStopped() bool { return s.stop.After(s.start) }\n\n\nfunc (s *Stopwatch) ElapsedTime() time.Duration {\n\tif s.IsStopped() {\n\t\treturn s.stop.Sub(s.start)\n\t}\n\treturn time.Since(s.start)\n}\n\nfunc (s *Stopwatch) Dt() string {\n\treturn fmt.Sprintf(\"%s\", s.ElapsedTime())\n}\n\nfunc (s *Stopwatch) Log(msg string) {\n\ts.logger.Info(\"elapsed\", \"msg\", msg, \"dx\", s.Dt())\n}\n\nfunc (s *Stopwatch) Stop() ", "output": "{\n\ts.stop = time.Now()\n}"} {"input": "package node_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/freeconf/yang/fc\"\n\t\"github.com/freeconf/yang/node\"\n\t\"github.com/freeconf/yang/nodeutil\"\n\t\"github.com/freeconf/yang/parser\"\n)\n\nfunc TestFieldInContainerWithSameName(t *testing.T) {\n\tm, err := parser.LoadModuleFromString(nil, `\nmodule x {\n\tcontainer a {\n\t\tleaf a {\n\t\t\ttype string;\n\t\t}\n\t\tleaf b {\n\t\t\ttype string;\n\t\t}\n\t}\n}\n\t`)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tn := nodeutil.ReadJSON(`\n{\n\t\"a\" : {\n\t\t\"a\": \"A\",\n\t\t\"b\": \"B\"\n \t}\n}`)\n\tb := node.NewBrowser(m, n)\n\tactual, err := nodeutil.WriteJSON(b.Root().Constrain(\"fields=a\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\texpected := `{\"a\":{\"a\":\"A\",\"b\":\"B\"}}`\n\tfc.AssertEqual(t, expected, actual)\n}\n\n\n\nfunc TestFieldsMatcherOnList(t *testing.T) ", "output": "{\n\tm, err := parser.LoadModuleFromString(nil, `\nmodule x {\n list a {\n key \"id\";\n leaf id {\n type string;\n }\n leaf b {\n type string;\n }\n }\n}\n\t`)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tn := nodeutil.ReadJSON(`\n{\n\t\"a\" : [{\n\t \"id\" : \"1\",\n\t \"b\" : \"B1\"\n\t},{\n\t \"id\" : \"2\",\n\t \"b\" : \"B2\"\n\t}]\n}`)\n\tb := node.NewBrowser(m, n)\n\tactual, err := nodeutil.WriteJSON(b.Root().Find(\"a?fields=id\"))\n\tif err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tfc.AssertEqual(t, `{\"a\":[{\"id\":\"1\"},{\"id\":\"2\"}]}`, actual)\n\t}\n}"} {"input": "package sanitize\n\nimport(\n\t\"os\"\n\t\"encoding/json\"\n)\n\n\nfunc WhitelistFromFile(filepath string) (*Whitelist, error) {\n\tbytes, err := readFileToBytes(filepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twhitelist, err := NewWhitelist(bytes)\n\treturn whitelist, nil\n}\n\n\nfunc readFileToBytes(filepath string) ([]byte, error) {\n\tf, err := os.Open(filepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfileInfo, err := f.Stat()\n\tbytes := make([]byte, fileInfo.Size())\n\n\t_, err = f.Read(bytes)\n\treturn bytes, err\n}\n\n\n\n\nfunc NewWhitelist(jsonData []byte) (*Whitelist, error) ", "output": "{\n\tconfiguration := &Whitelist{}\n\terr := json.Unmarshal(jsonData, configuration)\n\n\treturn configuration, err\n}"} {"input": "package postgresql\n\nimport (\n\t\"sql\"\n)\n\ntype Connection struct {\n\thandle *pqConnection;\n}\n\n\n\nfunc (self *Connection) Execute(sql string, params ...interface{}) sql.Error {\n\tstmt, err := self.Prepare(sql)\n\tif err != nil {\n\t\treturn err\t\n\t}\n\n\tdefer stmt.Close()\n\treturn stmt.Execute(params...)\n}\n\nfunc (self *Connection) Prepare(query string) (sql.Statement, sql.Error) {\n\n\tstmt := new(Statement)\n\treturn stmt, nil\n}\n\nfunc (self *Connection) Close() sql.Error {\n\tself.handle.pqClose()\n\treturn nil\n}\n\nfunc (self *Connection) Query(sql string, params ...interface{}) (sql.ResultSet, sql.Error) ", "output": "{\n\tstmt, err := self.Prepare(sql)\n\tif err != nil {\n\t\treturn nil, err\t\n\t}\n\n\treturn stmt.Query(params...)\n}"} {"input": "package database\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\n\t_ \"github.com/lib/pq\"\n)\n\ntype DB struct {\n\tc *sql.DB\n}\n\n\n\n\nfunc (db *DB) Close() {\n\tdb.c.Close()\n}\n\nfunc (db *DB) SetMaxOpenConns(n int) {\n\tdb.c.SetMaxOpenConns(n)\n}\n\nfunc Open(dbname, user, password, host string, port int, sslmode string) (db DB, err error) ", "output": "{\n\turl := fmt.Sprintf(\"postgres:%s:%s@%s:%d/%s?sslmode=%s\",\n\t\tuser, password, host, port, dbname, sslmode)\n\tdb.c, err = sql.Open(\"postgres\", url)\n\treturn\n}"} {"input": "package rpcd\n\nimport (\n\t\"github.com/Cloud-Foundations/Dominator/lib/srpc\"\n\t\"github.com/Cloud-Foundations/Dominator/proto/dominator\"\n)\n\n\n\nfunc (t *rpcType) GetSubsConfiguration(conn *srpc.Conn,\n\trequest dominator.GetSubsConfigurationRequest,\n\treply *dominator.GetSubsConfigurationResponse) error ", "output": "{\n\t*reply = dominator.GetSubsConfigurationResponse(\n\t\tt.herd.GetSubsConfiguration())\n\treturn nil\n}"} {"input": "package string\n\nimport (\n\tdss \"github.com/emirpasic/gods/stacks/arraystack\"\n)\n\n\nfunc Reverse(s string) string {\n\tr := []rune(s) \n\tfor i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n\t\tr[i], r[j] = r[j], r[i]\n\t}\n\treturn string(r)\n}\n\n\n\n\n\n\n\nfunc ReverseNest(s string) string {\n\tr := []rune(s)\n\tif len(r) == 1 || len(r) == 0 {\n\t\treturn s\n\t}\n\tsub := ReverseNest(string(r[1:]))\n\treturn sub + string(r[0:1])\n}\n\n\nfunc ReverseNest1(s string) string {\n\tr := []rune(s)\n\tswitchHeadTail(r)\n\treturn string(r)\n}\n\nfunc switchHeadTail(r []rune) {\n\tif len(r) <= 1 {\n\t\treturn\n\t}\n\tbottom, top := 0, len(r)-1\n\tr[bottom], r[top] = r[top], r[bottom]\n\tswitchHeadTail(r[bottom+1 : top])\n}\n\n\n\n\nfunc ReverseInStack(s string) string ", "output": "{\n\tr := []rune(s)\n\tstack := dss.New()\n\tfor i := 0; i < len(r); i++ {\n\t\tstack.Push(r[i])\n\t}\n\trs := make([]rune, len(r))\n\tfor i := 0; i < len(r); i++ {\n\t\tv, _ := stack.Pop()\n\t\tif v != nil {\n\t\t\trs[i] = v.(rune)\n\t\t}\n\t}\n\treturn string(rs)\n}"} {"input": "package kafka\n\nimport (\n\t\"encoding/binary\"\n\t\"hash/crc32\"\n)\n\ntype crc32Writer struct {\n\ttable *crc32.Table\n\tbuffer [8]byte\n\tcrc32 uint32\n}\n\nfunc (w *crc32Writer) update(b []byte) {\n\tw.crc32 = crc32.Update(w.crc32, w.table, b)\n}\n\nfunc (w *crc32Writer) writeInt8(i int8) {\n\tw.buffer[0] = byte(i)\n\tw.update(w.buffer[:1])\n}\n\nfunc (w *crc32Writer) writeInt16(i int16) {\n\tbinary.BigEndian.PutUint16(w.buffer[:2], uint16(i))\n\tw.update(w.buffer[:2])\n}\n\nfunc (w *crc32Writer) writeInt32(i int32) {\n\tbinary.BigEndian.PutUint32(w.buffer[:4], uint32(i))\n\tw.update(w.buffer[:4])\n}\n\n\n\nfunc (w *crc32Writer) writeBytes(b []byte) {\n\tn := len(b)\n\tif b == nil {\n\t\tn = -1\n\t}\n\tw.writeInt32(int32(n))\n\tw.update(b)\n}\n\nfunc (w *crc32Writer) Write(b []byte) (int, error) {\n\tw.update(b)\n\treturn len(b), nil\n}\n\nfunc (w *crc32Writer) WriteString(s string) (int, error) {\n\tw.update([]byte(s))\n\treturn len(s), nil\n}\n\nfunc (w *crc32Writer) writeInt64(i int64) ", "output": "{\n\tbinary.BigEndian.PutUint64(w.buffer[:8], uint64(i))\n\tw.update(w.buffer[:8])\n}"} {"input": "package main\n\nimport . \"g2d\"\n\nvar arena = NewArena(Point{480, 360})\nvar a1 = NewAlien(arena, Point{40, 40})\nvar a2 = NewAlien(arena, Point{80, 80})\n\ntype Alien struct {\n arena *Arena\n x, y, w, h int\n xmin, xmax int\n dx, dy int\n}\n\nfunc NewAlien(arena *Arena, pos Point) *Alien {\n a := &Alien{arena, pos.X, pos.Y, 20, 20, pos.X, pos.X+150, 5, 5}\n arena.Add(a)\n return a\n}\n\nfunc (a *Alien) Move() {\n if a.xmin <= a.x+a.dx && a.x+a.dx <= a.xmax {\n a.x += a.dx\n } else {\n a.dx = -a.dx\n a.y += a.dy\n }\n}\n\nfunc (a *Alien) Position() Point {\n return Point{a.x, a.y}\n}\n\nfunc (a *Alien) Size() Point {\n return Point{a.w, a.h}\n}\n\n\n\nfunc (a *Alien) Collide(other Actor) {\n}\n\nfunc tick() {\n ClearCanvas()\n arena.MoveAll()\n for _, actor := range arena.Actors() {\n FillRect(actor.Position(), actor.Size())\n }\n}\n\nfunc main() {\n InitCanvas(arena.Size())\n MainLoop(tick)\n}\n\nfunc (a *Alien) Symbol() Point ", "output": "{\n return Point{0, 0}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/gabriel-comeau/SimpleChatCommon\"\n\t\"github.com/gabriel-comeau/tbuikit\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\nfunc createMessageForBroadCast(text string, sender *ChatClient) *tbuikit.ColorizedString {\n\tformatted := formatBroadCastMessage(text, sender)\n\tmsg := SimpleChatCommon.Create(formatted, sender.color)\n\treturn msg\n}\n\n\n\n\n\nfunc formatWhisperMessage(message string, sender *ChatClient) string {\n\tmessage = strings.Trim(message, \" \\n\")\n\tvar output string\n\tif sender.nick != \"\" {\n\t\toutput = fmt.Sprintf(\" %v: %v\", sender.nick, message)\n\t} else {\n\t\toutput = fmt.Sprintf(\" %v: %v\", sender.id, message)\n\t}\n\n\treturn output\n}\n\n\nfunc nickTaken(n string, holder *ClientHolder) bool {\n\tfor _, c := range clientHolder.getClients() {\n\t\tif c.nick == n {\n\t\t\treturn true\n\t\t} else if n == strconv.FormatUint(c.id, 10) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc formatBroadCastMessage(message string, sender *ChatClient) string ", "output": "{\n\tmessage = strings.Trim(message, \" \\n\")\n\tvar output string\n\tif sender.nick != \"\" {\n\t\toutput = fmt.Sprintf(\"%v: %v\", sender.nick, message)\n\t} else {\n\t\toutput = fmt.Sprintf(\"%v: %v\", sender.id, message)\n\t}\n\n\treturn output\n}"} {"input": "package ecommerce\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/arvindkandhare/goamz/aws\"\n)\n\n\ntype ProductAdvertising struct {\n\tservice aws.Service\n\tassociateTag string\n}\n\n\nfunc New(auth aws.Auth, associateTag string) (p *ProductAdvertising, err error) {\n\tserviceInfo := aws.ServiceInfo{Endpoint: \"https://webservices.amazon.com\", Signer: aws.V2Signature}\n\tif service, err := aws.NewService(auth, serviceInfo); err == nil {\n\t\tp = &ProductAdvertising{*service, associateTag}\n\t}\n\treturn\n}\n\n\n\n\nfunc (p *ProductAdvertising) query(params map[string]string) (resp *http.Response, err error) {\n\tparams[\"Service\"] = \"AWSECommerceService\"\n\tparams[\"AssociateTag\"] = p.associateTag\n\treturn p.service.Query(\"GET\", \"/onca/xml\", params)\n}\n\nfunc (p *ProductAdvertising) PerformOperation(operation string, params map[string]string) (resp *http.Response, err error) ", "output": "{\n\tparams[\"Operation\"] = operation\n\treturn p.query(params)\n}"} {"input": "package network\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" network/2020-11-01\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package stats_test\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t. \"v2ray.com/core/app/stats\"\n\t\"v2ray.com/core/common\"\n\t\"v2ray.com/core/features/stats\"\n)\n\nfunc TestInternface(t *testing.T) {\n\t_ = (stats.Manager)(new(Manager))\n}\n\n\n\nfunc TestStatsCounter(t *testing.T) ", "output": "{\n\traw, err := common.CreateObject(context.Background(), &Config{})\n\tcommon.Must(err)\n\n\tm := raw.(stats.Manager)\n\tc, err := m.RegisterCounter(\"test.counter\")\n\tcommon.Must(err)\n\n\tif v := c.Add(1); v != 1 {\n\t\tt.Fatal(\"unpexcted Add(1) return: \", v, \", wanted \", 1)\n\t}\n\n\tif v := c.Set(0); v != 1 {\n\t\tt.Fatal(\"unexpected Set(0) return: \", v, \", wanted \", 1)\n\t}\n\n\tif v := c.Value(); v != 0 {\n\t\tt.Fatal(\"unexpected Value() return: \", v, \", wanted \", 0)\n\t}\n}"} {"input": "package virtconfig\n\nimport (\n\t\"testing\"\n\n\t\"kubevirt.io/client-go/testutils\"\n)\n\n\n\nfunc TestConfig(t *testing.T) ", "output": "{\n\ttestutils.KubeVirtTestSuiteSetup(t)\n}"} {"input": "package utils\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestAtomicBool(t *testing.T) ", "output": "{\n\tb := NewAtomicBool(false)\n\tassert.False(t, b.Bool())\n\n\tb.DoToReverse(false, func() {})\n\tassert.True(t, b.Bool())\n\n\tb.DoToReverse(true, func() {})\n\tassert.False(t, b.Bool())\n\n\tnb := NewAtomicBool(true)\n\tassert.True(t, nb.Bool())\n\n\tnb.DoToReverse(false, func() {})\n\tassert.True(t, nb.Bool())\n\n\tnb.DoToReverse(true, func() {})\n\tassert.False(t, nb.Bool())\n}"} {"input": "package api\n\nimport (\n\t\"io\"\n\t\"net/http\"\n)\n\n\n\n\nfunc latestReleaseHandler(w http.ResponseWriter, req *http.Request, _ *Context) error ", "output": "{\n\tres, err := http.Get(\"https://coreos.com/tectonic/api/releases/latest\")\n\tif err != nil {\n\t\treturn newBadRequestError(\"Failed to get a response from coreos.com: %s\", err)\n\t}\n\tio.Copy(w, res.Body)\n\tres.Body.Close()\n\treturn nil\n}"} {"input": "package text\n\nimport \"fmt\"\n\nconst (\n\tredCode = \"\\x1b[31m\"\n\tgreenCode = \"\\x1b[32m\"\n\tyellowCode = \"\\x1b[33m\"\n\tblueCode = \"\\x1b[34m\"\n\tmagentaCode = \"\\x1b[35m\"\n\tCyanCode = \"\\x1b[36m\"\n\tboldCode = \"\\x1b[1m\"\n\n\tResetCode = \"\\x1b[0m\"\n)\n\n\nvar UseColor = true\n\nfunc stylize(startCode, in string) string {\n\tif UseColor {\n\t\treturn startCode + in + ResetCode\n\t}\n\n\treturn in\n}\n\nfunc Red(in string) string {\n\treturn stylize(redCode, in)\n}\n\nfunc Green(in string) string {\n\treturn stylize(greenCode, in)\n}\n\nfunc yellow(in string) string {\n\treturn stylize(yellowCode, in)\n}\n\nfunc Cyan(in string) string {\n\treturn stylize(CyanCode, in)\n}\n\nfunc Magenta(in string) string {\n\treturn stylize(magentaCode, in)\n}\n\nfunc Blue(in string) string {\n\treturn stylize(blueCode, in)\n}\n\nfunc Bold(in string) string {\n\treturn stylize(boldCode, in)\n}\n\n\n\n\n\nfunc ColorHash(name string) (output string) ", "output": "{\n\tif !UseColor {\n\t\treturn name\n\t}\n\n\tvar hash uint = 5381\n\n\tfor i := 0; i < len(name); i++ {\n\t\thash = uint(name[i]) + ((hash << 5) + (hash))\n\t}\n\n\treturn fmt.Sprintf(\"\\x1b[%dm%s\\x1b[0m\", hash%6+31, name)\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n _ \"github.com/lib/pq\"\n)\n\n\n\nfunc updateReferralTable(referral_id string) string{\n var count int8\n db.QueryRow(\"SELECT referral_count FROM referral WHERE referral_id=$1\",referral_id).Scan(&count)\n count++\n db.QueryRow(\"UPDATE referral SET referral_count=$1 where referral_id=$2\", count, referral_id)\n var wallet_id string\n db.QueryRow(\"SELECT wallet_id FROM referral WHERE referral_id=$1\",referral_id).Scan(&wallet_id)\n return wallet_id\n}\n\nfunc createReferralID(referral_id, wallet_id string) bool{\n fmt.Println(\"Creating ReferralID\",referral_id, wallet_id)\n db.QueryRow(\"INSERT INTO referral(referral_id, referral_count, wallet_id) VALUES($1,$2,$3);\",referral_id, 0, wallet_id)\n return true\n}\n\nfunc checkReferralID(referral_id string) bool ", "output": "{\n fmt.Println(\"Checking for valid referral_id:\", referral_id)\n var count int8\n if referral_id == \"\"{\n return true\n }\n db.QueryRow(\"SELECT COUNT(*) FROM referral WHERE referral_id=$1\",referral_id).Scan(&count)\n if count == 0 {\n return false\n }else{\n return true\n }\n}"} {"input": "package main\n\nimport (\n\t\"../contrail\"\n\tlog \"../logging\"\n\t\"github.com/containernetworking/cni/pkg/skel\"\n\t\"github.com/containernetworking/cni/pkg/version\"\n)\n\n\nfunc getPodInfo(skelArgs *skel.CmdArgs) (string, string, error) {\n\treturn skelArgs.ContainerID, skelArgs.ContainerID, nil\n}\n\n\nfunc CmdAdd(skelArgs *skel.CmdArgs) error {\n\tcni, err := contrailCni.Init(skelArgs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\"Came in Add for container %s\", skelArgs.ContainerID)\n\tcontainerUuid, containerName, err := getPodInfo(skelArgs)\n\tif err != nil {\n\t\tlog.Errorf(\"Error getting UUID/Name for Container\")\n\t\treturn err\n\t}\n\n\tcni.Update(containerName, containerUuid, \"\")\n\tcni.Log()\n\n\terr = cni.CmdAdd()\n\tif err != nil {\n\t\tlog.Errorf(\"Failed processing Add command.\")\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc main() {\n\tskel.PluginMain(CmdAdd, CmdDel,\n\t\tversion.PluginSupports(contrailCni.CniVersion))\n}\n\nfunc CmdDel(skelArgs *skel.CmdArgs) error ", "output": "{\n\tcni, err := contrailCni.Init(skelArgs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\"Came in Del for container %s\", skelArgs.ContainerID)\n\tcontainerUuid, containerName, err := getPodInfo(skelArgs)\n\tif err != nil {\n\t\tlog.Errorf(\"Error getting UUID/Name for Container\")\n\t\treturn err\n\t}\n\n\tcni.Update(containerName, containerUuid, \"\")\n\tcni.Log()\n\n\terr = cni.CmdDel()\n\tif err != nil {\n\t\tlog.Errorf(\"Failed processing Add command.\")\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package facebox_test\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/machinebox/sdk-go/facebox\"\n\t\"github.com/matryer/is\"\n)\n\n\n\nfunc TestInfo(t *testing.T) ", "output": "{\n\tis := is.New(t)\n\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tis.Equal(r.Method, \"GET\")\n\t\tis.Equal(r.URL.Path, \"/info\")\n\t\tis.Equal(r.Header.Get(\"Accept\"), \"application/json; charset=utf-8\")\n\t\tio.WriteString(w, `{\n\t\t\t\"name\": \"facebox\",\n\t\t\t\"version\": 1,\n\t\t\t\"build\": \"abcdefg\",\n\t\t\t\"status\": \"ready\"\n\t\t}`)\n\t}))\n\tdefer srv.Close()\n\tfb := facebox.New(srv.URL)\n\tinfo, err := fb.Info()\n\tis.NoErr(err)\n\tis.Equal(info.Name, \"facebox\")\n\tis.Equal(info.Version, 1)\n\tis.Equal(info.Build, \"abcdefg\")\n\tis.Equal(info.Status, \"ready\")\n}"} {"input": "package cli_test\n\nimport (\n\t\"flag\"\n\t\"testing\"\n\n\t\"github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/codegangsta/cli\"\n)\n\nfunc TestCommandDoNotIgnoreFlags(t *testing.T) {\n\tapp := cli.NewApp()\n\tset := flag.NewFlagSet(\"test\", 0)\n\ttest := []string{\"blah\", \"blah\", \"-break\"}\n\tset.Parse(test)\n\n\tc := cli.NewContext(app, set, set)\n\n\tcommand := cli.Command{\n\t\tName: \"test-cmd\",\n\t\tAliases: []string{\"tc\"},\n\t\tUsage: \"this is for testing\",\n\t\tDescription: \"testing\",\n\t\tAction: func(_ *cli.Context) {},\n\t}\n\terr := command.Run(c)\n\n\texpect(t, err.Error(), \"flag provided but not defined: -break\")\n}\n\n\n\nfunc TestCommandIgnoreFlags(t *testing.T) ", "output": "{\n\tapp := cli.NewApp()\n\tset := flag.NewFlagSet(\"test\", 0)\n\ttest := []string{\"blah\", \"blah\"}\n\tset.Parse(test)\n\n\tc := cli.NewContext(app, set, set)\n\n\tcommand := cli.Command{\n\t\tName: \"test-cmd\",\n\t\tAliases: []string{\"tc\"},\n\t\tUsage: \"this is for testing\",\n\t\tDescription: \"testing\",\n\t\tAction: func(_ *cli.Context) {},\n\t\tSkipFlagParsing: true,\n\t}\n\terr := command.Run(c)\n\n\texpect(t, err, nil)\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\nfunc setTimespec(sec, nsec int64) Timespec {\n\treturn Timespec{Sec: sec, Nsec: nsec}\n}\n\nfunc setTimeval(sec, usec int64) Timeval {\n\treturn Timeval{Sec: sec, Usec: usec}\n}\n\n\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint64(length)\n}\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) ", "output": "{\n\tk.Ident = uint64(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}"} {"input": "package accumulator\n\nimport \"strconv\"\n\ntype Int64 int64\n\n\nfunc (a *Int64) Accumulate(i int, err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t*a += Int64(i)\n}\n\n\nfunc (a *Int64) Accumulate64(i int64, err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t*a += Int64(i)\n}\n\n\n\nfunc (a *Int64) String() string ", "output": "{\n\treturn strconv.FormatInt(int64(*a), 10)\n}"} {"input": "package web\n\nimport (\n\t\"github.com/cleverua/tuna-timer-api/models\"\n)\n\n\ntype ResponseBody struct {\n\tAppInfo map[string]string `json:\"app_info\"`\n\tResponseStatus *ResponseStatus\t `json:\"response_status\"`\n\tResponseData map[string]string `json:\"data\"`\n}\n\n\n\ntype ResponseStatus struct {\n\tStatus\t\t string `json:\"status\"`\n\tDeveloperMessage string `json:\"developer_message\"`\n\tUserMessage\t string `json:\"user_message\"`\n}\n\n\ntype JWTResponse struct {\n\t*ResponseBody\n\tResponseData JwtToken `json:\"data\"`\n}\n\nfunc NewJWTResponse(info map[string]string) *JWTResponse {\n\treturn &JWTResponse{\n\t\tResponseData: JwtToken{},\n\t\tResponseBody: NewResponseBody(info),\n\t}\n}\n\n\ntype TimerResponse struct {\n\t*ResponseBody\n\tResponseData models.Timer\t`json:\"data\"`\n}\n\nfunc NewTimerResponse(info map[string]string) *TimerResponse {\n\treturn &TimerResponse{\n\t\tResponseBody: NewResponseBody(info),\n\t}\n}\n\n\ntype TimersResponse struct {\n\t*ResponseBody\n\tResponseData []*models.Timer `json:\"data\"`\n}\n\nfunc NewTimersResponse(info map[string]string) *TimersResponse {\n\treturn &TimersResponse{\n\t\tResponseBody: NewResponseBody(info),\n\t}\n}\n\n\ntype ProjectsResponse struct {\n\t*ResponseBody\n\tResponseData []*models.Project `json:\"data\"`\n}\n\nfunc NewProjectsResponse(info map[string]string) *ProjectsResponse {\n\treturn &ProjectsResponse{\n\t\tResponseBody: NewResponseBody(info),\n\t}\n}\n\n\ntype UserStatisticsResponse struct {\n\t*ResponseBody\n\tResponseData []*models.UserStatisticsAggregation `json:\"data\"`\n}\n\nfunc NewUserStatisticsResponse(info map[string]string) *UserStatisticsResponse {\n\treturn &UserStatisticsResponse{\n\t\tResponseBody: NewResponseBody(info),\n\t}\n}\n\nfunc NewResponseBody(info map[string]string) *ResponseBody", "output": "{\n\treturn &ResponseBody{\n\t\tResponseStatus: &ResponseStatus{ Status: statusOK },\n\t\tAppInfo: info,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Rectangle struct {\n\twidth, height float64\n}\n\ntype Circle struct {\n\tradius float64\n}\n\n\n\nfunc (c Circle) area() float64 {\n\treturn c.radius * c.radius * math.Pi\n}\n\nfunc main() {\n\tr1 := Rectangle{12, 2}\n\tr2 := Rectangle{9, 4}\n\tc1 := Circle{10}\n\tc2 := Circle{25}\n\n\tfmt.Println(\"Area of r1 is: \", r1.area())\n\tfmt.Println(\"Area of r2 is: \", r2.area())\n\tfmt.Println(\"Area of c1 is: \", c1.area())\n\tfmt.Println(\"Area of c2 is: \", c2.area())\n}\n\nfunc (r Rectangle) area() float64 ", "output": "{\n\treturn r.width * r.height\n}"} {"input": "package features\n\nimport (\n\t\"math\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestTFIDFEncoder_Encode(t *testing.T) ", "output": "{\n\tencoder := TFIDFEncoder{Column: 0, Separator: func(s string) []string {\n\t\treturn strings.Split(s, \" \")\n\t}, Sort: true}\n\ttestData := [][]string{{\"at the office\", \"1\"}, {\"at the house\", \"2\"}}\n\tactual, err := encoder.Encode(testData)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\texpected := &PartialMatrix{\n\t\tMatrix: []float64{math.Log(2. / 3), 0, 0, math.Log(2. / 3), math.Log(2. / 3), 0, 0, math.Log(2. / 3)},\n\t\tColumns: []string{\"at\", \"house\", \"office\", \"the\"}}\n\n\tif !reflect.DeepEqual(expected, actual) {\n\t\tt.Errorf(\"Unexpected PartialMatrix: %v, expected %v\", actual, expected)\n\t}\n}"} {"input": "package config\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"text/template\"\n)\n\nvar (\n\tglbEnvs map[string]string\n)\n\n\n\ntype Values struct {\n\tEnvs map[string]string \n}\n\nfunc GetValues() *Values {\n\treturn &Values{\n\t\tEnvs: glbEnvs,\n\t}\n}\n\nfunc RenderContent(in []byte) (out []byte, err error) {\n\ttmpl, errRet := template.New(\"frp\").Parse(string(in))\n\tif errRet != nil {\n\t\terr = errRet\n\t\treturn\n\t}\n\n\tbuffer := bytes.NewBufferString(\"\")\n\tv := GetValues()\n\terr = tmpl.Execute(buffer, v)\n\tif err != nil {\n\t\treturn\n\t}\n\tout = buffer.Bytes()\n\treturn\n}\n\nfunc GetRenderedConfFromFile(path string) (out []byte, err error) {\n\tvar b []byte\n\tb, err = ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tout, err = RenderContent(b)\n\treturn\n}\n\nfunc init() ", "output": "{\n\tglbEnvs = make(map[string]string)\n\tenvs := os.Environ()\n\tfor _, env := range envs {\n\t\tkv := strings.Split(env, \"=\")\n\t\tif len(kv) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tglbEnvs[kv[0]] = kv[1]\n\t}\n}"} {"input": "package test\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\t\"runtime\"\n\t\"path/filepath\"\n\t_ \"github.com/dvwallin/gopress/routers\"\n\n\t\"github.com/astaxie/beego\"\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\n\n\nfunc TestMain(t *testing.T) {\n\tr, _ := http.NewRequest(\"GET\", \"/\", nil)\n\tw := httptest.NewRecorder()\n\tbeego.BeeApp.Handlers.ServeHTTP(w, r)\n\n\tbeego.Trace(\"testing\", \"TestMain\", \"Code[%d]\\n%s\", w.Code, w.Body.String())\n\n\tConvey(\"Subject: Test Station Endpoint\\n\", t, func() {\n\t Convey(\"Status Code Should Be 200\", func() {\n\t So(w.Code, ShouldEqual, 200)\n\t })\n\t Convey(\"The Result Should Not Be Empty\", func() {\n\t So(w.Body.Len(), ShouldBeGreaterThan, 0)\n\t })\n\t})\n}\n\nfunc init() ", "output": "{\n\t_, file, _, _ := runtime.Caller(1)\n\tapppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, \"..\" + string(filepath.Separator))))\n\tbeego.TestBeegoInit(apppath)\n}"} {"input": "package lib\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype StopChannelContext struct {\n\tStopCh <-chan struct{}\n}\n\nfunc (c *StopChannelContext) Deadline() (deadline time.Time, ok bool) {\n\tok = false\n\treturn\n}\n\nfunc (c *StopChannelContext) Done() <-chan struct{} {\n\treturn c.StopCh\n}\n\nfunc (c *StopChannelContext) Err() error {\n\tselect {\n\tcase <-c.StopCh:\n\t\treturn context.Canceled\n\tdefault:\n\t\treturn nil\n\t}\n}\n\n\n\nfunc (c *StopChannelContext) Value(key interface{}) interface{} ", "output": "{\n\treturn nil\n}"} {"input": "package frames\n\nimport \"testing\"\n\n\n\nfunc TestApicProcess(t *testing.T) {\n\tx := NewFrame(\"APIC\", \"\", Version3).(*APIC)\n\tb := []byte(\"\\x00image/jpeg\\x00\\x03Something\\x00\\x01\\x02\\x00\")\n\n\tx.ProcessData(len(b), b)\n\texpected := 3\n\tfound := x.GetLength()\n\tif found != expected {\n\t\tt.Errorf(\"Got [%d], Expected [%d]\", found, expected)\n\t}\n}\n\nfunc TestApicProcessUtf16(t *testing.T) {\n\tx := NewFrame(\"APIC\", \"\", Version3).(*APIC)\n\tb := []byte(\"\\x01image/png\\x00\\x02\" +\n\t\t\"\\xfe\\xff\\x00B\\x00o\\x00b\\x00 \\x00i\\x00s\\x00 \\x00G\\x00r\\x00e\\x00a\\x00t\\x00\\x00\" +\n\t\t\"\\x01\\x02\\x03\")\n\n\tx.ProcessData(len(b), b)\n\texpected := \"Image (image/png, Other file icon, 3b) Bob is Great\\n\"\n\tfound := x.DisplayContent()\n\tif found != expected {\n\t\tt.Errorf(\"Got [%s], Expected [%s]\", found, expected)\n\t}\n}\n\nfunc TestApicInvalidPicType(t *testing.T) {\n\tx := NewFrame(\"APIC\", \"\", Version3).(*APIC)\n\tb := []byte(\"\\x00image/png\\x00\\x22Hello\\x00\\x01\\x02\\x03\")\n\n\tx.ProcessData(len(b), b)\n\texpected := \"Image (image/png, Other, 3b) Hello\\n\"\n\tfound := x.DisplayContent()\n\tif found != expected {\n\t\tt.Errorf(\"Got [%s], Expected [%s]\", found, expected)\n\t}\n}\n\nfunc TestApicBasicOutput(t *testing.T) ", "output": "{\n\tx := NewFrame(\"APIC\", \"Attached picture\", Version3).(*APIC)\n\tif x.GetName() != \"APIC\" {\n\t\tt.Error(\"Invalid name from APIC frame\")\n\t}\n\n\tif x.GetExplain() != \"Attached picture\" {\n\t\tt.Error(\"Invalid APIC GetExplain() response\")\n\t}\n\n\tx.Name = \"BOB\"\n\tif x.GetName() != \"BOB\" {\n\t\tt.Error(\"Invalid APIC Name setting\")\n\t}\n}"} {"input": "package column\n\nimport (\n\t\"github.com/ClickHouse/clickhouse-go/lib/binary\"\n)\n\ntype Int32 struct{ base }\n\n\n\nfunc (i *Int32) Write(encoder *binary.Encoder, v interface{}) error {\n\tswitch v := v.(type) {\n\tcase int32:\n\t\treturn encoder.Int32(v)\n\tcase int64:\n\t\treturn encoder.Int32(int32(v))\n\tcase int:\n\t\treturn encoder.Int32(int32(v))\n\n\tcase *int32:\n\t\treturn encoder.Int32(*v)\n\tcase *int64:\n\t\treturn encoder.Int32(int32(*v))\n\tcase *int:\n\t\treturn encoder.Int32(int32(*v))\n\t}\n\n\treturn &ErrUnexpectedType{\n\t\tT: v,\n\t\tColumn: i,\n\t}\n}\n\nfunc (Int32) Read(decoder *binary.Decoder, isNull bool) (interface{}, error) ", "output": "{\n\tv, err := decoder.Int32()\n\tif err != nil {\n\t\treturn int32(0), err\n\t}\n\treturn v, nil\n}"} {"input": "package http\n\nimport (\n\t\"net/http\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n)\n\nconst (\n\trootURL = \"http://localhost:2049/\"\n\tpostURL = \"http://localhost:2049/post\"\n\tinvalidPathURL = \"http://localhost:2049/invalid-path\"\n\tinvalidHostURL = \"http://hostlocal:2049/\"\n)\n\ntype testHandler struct{}\n\nfunc (testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tswitch r.URL.Path {\n\tcase \"/\":\n\t\tw.Write(nil)\n\tcase \"/post\":\n\t\tif r.Method != \"POST\" {\n\t\t\tw.WriteHeader(404)\n\t\t}\n\tdefault:\n\t\tw.WriteHeader(404)\n\t}\n}\n\n\n\nfunc TestMain(m *testing.M) ", "output": "{\n\tgo http.ListenAndServe(\":2049\", testHandler{})\n\n\ttime.Sleep(time.Millisecond)\n\n\tos.Exit(m.Run())\n}"} {"input": "package version\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"go-common/app/interface/main/creative/conf\"\n\t\"go-common/app/interface/main/creative/model/version\"\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"go-common/app/interface/main/creative/service\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nvar (\n\ts *Service\n)\n\n\n\nfunc WithService(f func(s *Service)) func() {\n\treturn func() {\n\t\tReset(func() {})\n\t\tf(s)\n\t}\n}\n\nfunc Test_VersionMap(t *testing.T) {\n\tvar (\n\t\tc = context.Background()\n\t\terr error\n\t\tversions = make(map[string][]*version.Version)\n\t)\n\tConvey(\"versionMap\", t, WithService(func(s *Service) {\n\t\tversions, err = s.versionMap(c)\n\t\tSo(err, ShouldBeNil)\n\t\tSo(versions, ShouldNotBeNil)\n\t}))\n}\n\nfunc init() ", "output": "{\n\tdir, _ := filepath.Abs(\"../../cmd/creative.toml\")\n\tflag.Set(\"conf\", dir)\n\tconf.Init()\n\trpcdaos := service.NewRPCDaos(conf.Conf)\n\ts = New(conf.Conf, rpcdaos)\n\ttime.Sleep(time.Second)\n}"} {"input": "package rds\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\t\"lib/utils\"\n\t\"fmt\"\n)\n\ntype RdsPuller struct {\n\tactive int32\n\tfire *RdsFire\n\tclient *RdsClient\n\ttopic string\n\twg *sync.WaitGroup\n}\n\nfunc NewRdsPuller(_conf *RdsConfig, _topic string, _on_data OnRdsData) (*RdsPuller) {\n\treturn &RdsPuller{\n\t\ttopic: _topic,\n\t\tfire: NewRdsFire(\"Rdspuller\", _on_data),\n\t\tclient: NewRdsClient(_conf),\n\t}\n}\n\nfunc (p *RdsPuller) IsActive() (bool) {\n\treturn atomic.LoadInt32(&p.active) == 1\n}\n\nfunc (p *RdsPuller) loop(_arg interface{}) {\n\tdefer func() {\n\t\tp.wg.Done()\n\t}()\n\n\tfor p.IsActive() {\n\t\tary := p.client.BLpop(time.Second, p.topic)\n\t\tif len(ary) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tp.fire.Offer(ary[0], ary[1])\n\t}\n}\n\nfunc (p *RdsPuller) Start() {\n\tif atomic.CompareAndSwapInt32(&p.active, 0, 1) {\n\t\tp.fire.Start()\n\t\tp.client.Start()\n\n\t\tp.wg = &sync.WaitGroup{}\n\t\tp.wg.Add(1)\n\t\tutils.GoRunAdd(p.loop, \"RdsPuller.loop\")\n\t}\n}\n\nfunc (p *RdsPuller) Stop() {\n\tif atomic.CompareAndSwapInt32(&p.active, 1, 0) {\n\t\tp.wg.Wait()\n\n\t\tp.client.Stop()\n\t\tp.fire.Stop()\n\t}\n}\n\n\n\nfunc TestPuller() ", "output": "{\n\tconf := NewRdsConf()\n\tsubs := NewRdsPuller(conf, \"CMDRT\", func(_data *RdsData) {\n\t\tfmt.Printf(\"%s\\r\\n\", _data.String())\n\t})\n\tsubs.Start()\n\ttime.Sleep(time.Hour)\n}"} {"input": "package architecture\n\nimport \"strings\"\n\ntype Architecture struct {\n\tRoot *Directory\n}\n\nfunc NewArchitecture() *Architecture {\n\treturn &Architecture{\n\t\tRoot: NewDirectory(),\n\t}\n}\n\n\n\nfunc (arch *Architecture) FindDirectory(path string) *Directory ", "output": "{\n\tpathSections := strings.Split(path, \"/\")\n\n\tcurrentNode := arch.Root\n\n\tfor _, pathSection := range pathSections {\n\t\tif _, found := currentNode.Directories[pathSection]; !found {\n\t\t\tcurrentNode.Directories[pathSection] = NewDirectory()\n\t\t}\n\n\t\tcurrentNode = currentNode.Directories[pathSection]\n\t}\n\n\treturn currentNode\n}"} {"input": "package errors\n\nimport (\n\t\"net/http\"\n\t\"log\"\n)\n\n\n\n\nfunc PanicWhenError(err error) {\n\tif (err != nil) {\n\t\tpanic(err)\n\t}\n}\n\nfunc PanicHandler(w http.ResponseWriter, r *http.Request, error interface{}) ", "output": "{\n\tlog.Println(error)\n\tw.Write([]byte(\"Unexpected Error\"))\n}"} {"input": "package thiscall\n\n\n\n\n\n\n\nfunc Call(addr uintptr, a ...uintptr) (uintptr, error) ", "output": "{\n\treturn call(addr, a...)\n}"} {"input": "package mock\n\nimport (\n\t\"github.com/fkmhrk/OpenInvoice/v1/model/env\"\n)\n\ntype EnvDAO struct {\n\tCreateResult env.Env\n\tGetResult env.Env\n\tGetListResult []*env.Env\n\tSaveResult error\n\tUpdateResult env.Env\n\tDeleteResult env.Env\n}\n\nfunc (d *EnvDAO) Create(key, value string) (env.Env, error) {\n\treturn d.CreateResult, nil\n}\n\nfunc (d *EnvDAO) Get(key string) (env.Env, error) {\n\treturn d.GetResult, nil\n}\n\n\n\nfunc (d *EnvDAO) Save(list []*env.Env) error {\n\treturn d.SaveResult\n}\n\nfunc (d *EnvDAO) Update(key, value string) (env.Env, error) {\n\treturn d.UpdateResult, nil\n}\n\nfunc (d *EnvDAO) Delete(key string) (env.Env, error) {\n\treturn d.DeleteResult, nil\n}\n\nfunc (d *EnvDAO) GetList() ([]*env.Env, error) ", "output": "{\n\treturn d.GetListResult, nil\n}"} {"input": "package vppcalls\n\nimport (\n\t\"errors\"\n\n\tl2ba \"github.com/ligato/vpp-agent/plugins/vpp/binapi/l2\"\n)\n\n\n\n\n\nfunc (h *XConnectVppHandler) DeleteL2XConnect(rxIface, txIface string) error {\n\treturn h.addDelXConnect(rxIface, txIface, false)\n}\n\nfunc (h *XConnectVppHandler) addDelXConnect(rxIface, txIface string, enable bool) error {\n\trxIfaceMeta, found := h.ifIndexes.LookupByName(rxIface)\n\tif !found {\n\t\treturn errors.New(\"failed to get Rx interface metadata\")\n\t}\n\n\ttxIfaceMeta, found := h.ifIndexes.LookupByName(txIface)\n\tif !found {\n\t\treturn errors.New(\"failed to get Tx interface metadata\")\n\t}\n\n\treq := &l2ba.SwInterfaceSetL2Xconnect{\n\t\tEnable: boolToUint(enable),\n\t\tTxSwIfIndex: txIfaceMeta.GetIndex(),\n\t\tRxSwIfIndex: rxIfaceMeta.GetIndex(),\n\t}\n\treply := &l2ba.SwInterfaceSetL2XconnectReply{}\n\n\tif err := h.callsChannel.SendRequest(req).ReceiveReply(reply); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (h *XConnectVppHandler) AddL2XConnect(rxIface, txIface string) error ", "output": "{\n\treturn h.addDelXConnect(rxIface, txIface, true)\n}"} {"input": "package mock\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/cilium/cilium/pkg/lock\"\n)\n\n\ntype MockMetrics struct {\n\tmutex lock.RWMutex\n\tapiCall map[string]float64\n\trateLimit map[string]time.Duration\n}\n\n\nfunc NewMockMetrics() *MockMetrics {\n\treturn &MockMetrics{\n\t\tapiCall: map[string]float64{},\n\t\trateLimit: map[string]time.Duration{},\n\t}\n}\n\n\n\n\n\n\n\n\n\nfunc (m *MockMetrics) ObserveAPICall(operation, status string, duration float64) {\n\tm.mutex.Lock()\n\tm.apiCall[fmt.Sprintf(\"operation=%s, status=%s\", operation, status)] += duration\n\tm.mutex.Unlock()\n}\n\n\n\nfunc (m *MockMetrics) RateLimit(operation string) time.Duration {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\treturn m.rateLimit[operation]\n}\n\n\n\n\nfunc (m *MockMetrics) ObserveRateLimit(operation string, delay time.Duration) {\n\tm.mutex.Lock()\n\tm.rateLimit[operation] += delay\n\tm.mutex.Unlock()\n}\n\nfunc (m *MockMetrics) APICall(operation, status string) float64 ", "output": "{\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\treturn m.apiCall[fmt.Sprintf(\"operation=%s, status=%s\", operation, status)]\n}"} {"input": "package versioned\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n)\n\n\ntype Convertor struct {\n\tScheme *runtime.Scheme\n}\n\n\n\n\n\nfunc (c *Convertor) Validate() error {\n\tif c.Scheme == nil {\n\t\treturn fmt.Errorf(\"the Convertor requires a scheme\")\n\t}\n\treturn nil\n}\n\nfunc (c Convertor) ConvertToGVK(obj runtime.Object, gvk schema.GroupVersionKind) (runtime.Object, error) ", "output": "{\n\tif obj.GetObjectKind().GroupVersionKind() == gvk {\n\t\treturn obj, nil\n\t}\n\tout, err := c.Scheme.New(gvk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = c.Scheme.Convert(obj, out, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}"} {"input": "package audioplayer\n\nimport (\n \"govkmedia/dialogboxes\"\n \"govkmedia/requestwrapper\"\n \"strconv\"\n \"time\"\n)\n\nfunc (e *Engine) StartPlay() {\n mwroot:=e.mainWindow.Root()\n playerobj:=mwroot.ObjectByName(\"mplayer\")\n curplaying:=e.playlist[e.currentPlaying]\n playerobj.Set(\"source\",curplaying.Url)\n time.Sleep(time.Second) \n context:=e.qmlEngine.Context()\n context.SetVar(\"vkartist\",curplaying.Artist)\n context.SetVar(\"vktitle\",curplaying.Title)\n context.SetVar(\"vkduration\",curplaying.Duration)\n e.LoadLyrics()\n playerobj.Call(\"resetProgress\")\n playerobj.Call(\"play\")\n}\n\nfunc (e *Engine) LoadLyrics() {\n curplaying:=e.playlist[e.currentPlaying]\n if curplaying.LyricsId==0 { return }\n ra:=requestwrapper.RequestAccesser{Token: e.accessToken}\n parms:=map[string]string{\"lyrics_id\":strconv.FormatFloat(curplaying.LyricsId,'f',-1,64)}\n resp,err:=ra.MakeRequest(\"audio.getLyrics\",parms)\n if err!=nil {\n dialogboxes.ShowErrorDialog(err.Error())\n return\n }\n lyricsfield:=e.mainWindow.Root().ObjectByName(\"lyrics\")\n lyrics:=resp[\"response\"].(map[string]interface{})[\"text\"].(string)\n lyricsfield.Set(\"text\",lyrics)\n}\n\n\n\nfunc (e *Engine) Prev() {\n if e.currentPlaying==0 { return }\n e.currentPlaying--\n e.StartPlay()\n}\n\nfunc (e *Engine) Next() ", "output": "{\n if e.currentPlaying+1==len(e.playlist) { return }\n e.currentPlaying++\n e.StartPlay()\n}"} {"input": "package test\n\nimport \"io\"\n\n\ntype PlainReader struct {\n\tr io.Reader\n}\n\n\nfunc NewPlainReader(r io.Reader) *PlainReader {\n\treturn &PlainReader{r}\n}\n\n\nfunc (r *PlainReader) Read(p []byte) (int, error) {\n\treturn r.r.Read(p)\n}\n\n\n\n\ntype ErrorReader struct {\n\tn int\n}\n\n\nfunc NewErrorReader(n int) *ErrorReader {\n\treturn &ErrorReader{n}\n}\n\n\n\n\n\n\n\ntype InfiniteReader struct{}\n\n\nfunc NewInfiniteReader() *InfiniteReader {\n\treturn &InfiniteReader{}\n}\n\n\nfunc (r *InfiniteReader) Read(b []byte) (n int, err error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tb[0] = '.'\n\treturn 1, nil\n}\n\n\n\n\ntype EmptyReader struct {\n}\n\n\nfunc NewEmptyReader() *EmptyReader {\n\treturn &EmptyReader{}\n}\n\n\nfunc (r *EmptyReader) Read(b []byte) (n int, err error) {\n\treturn 0, io.EOF\n}\n\nfunc (r *ErrorReader) Read(b []byte) (n int, err error) ", "output": "{\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tif r.n == 0 {\n\t\treturn 0, ErrPlain\n\t}\n\tr.n--\n\tb[0] = '.'\n\treturn 1, nil\n}"} {"input": "package leetcode\n\n\n\n\n\ntype MyStack struct {\n\telements []int\n}\n\n\nfunc NewMyStack() MyStack {\n\treturn MyStack{}\n}\n\n\nfunc (this *MyStack) Push(x int) {\n\tthis.elements = append(this.elements, x)\n}\n\n\nfunc (this *MyStack) Pop() int {\n\tn := len(this.elements)\n\te := this.elements[n-1]\n\tthis.elements = this.elements[:n-1]\n\treturn e\n}\n\n\nfunc (this *MyStack) Top() int {\n\treturn this.elements[len(this.elements)-1]\n}\n\n\n\n\nfunc (this *MyStack) Empty() bool ", "output": "{\n\treturn len(this.elements) == 0\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\ntype Person struct {\n\tName string\n\tAge int\n}\n\ntype ByName []Person\n\n\n\nfunc (this ByName) Less(i, j int) bool {\n\treturn this[i].Name < this[j].Name\n}\n\nfunc (this ByName) Swap(i, j int) {\n\tthis[i], this[j] = this[j], this[i]\n}\n\nfunc main() {\n\tkids := []Person{\n\t\t{\"Jill\", 9},\n\t\t{\"Jack\", 10},\n\t}\n\tsort.Sort(ByName(kids))\n\tfmt.Println(kids)\n}\n\nfunc (this ByName) Len() int ", "output": "{\n\treturn len(this)\n}"} {"input": "package servenv\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"vitess.io/vitess/go/event\"\n\t\"vitess.io/vitess/go/vt/log\"\n)\n\nvar (\n\tonCloseHooks event.Hooks\n\tExitChan chan os.Signal\n)\n\n\n\nfunc Run(port int) {\n\tpopulateListeningURL(int32(port))\n\tcreateGRPCServer()\n\tonRunHooks.Fire()\n\tserveGRPC()\n\tserveSocketFile()\n\n\tl, err := net.Listen(\"tcp\", fmt.Sprintf(\":%v\", port))\n\tif err != nil {\n\t\tlog.Exit(err)\n\t}\n\tgo http.Serve(l, nil)\n\n\tExitChan = make(chan os.Signal, 1)\n\tsignal.Notify(ExitChan, syscall.SIGTERM, syscall.SIGINT)\n\t<-ExitChan\n\tl.Close()\n\n\tstartTime := time.Now()\n\tlog.Infof(\"Entering lameduck mode for at least %v\", *lameduckPeriod)\n\tlog.Infof(\"Firing asynchronous OnTerm hooks\")\n\tgo onTermHooks.Fire()\n\n\tfireOnTermSyncHooks(*onTermTimeout)\n\tif remain := *lameduckPeriod - time.Since(startTime); remain > 0 {\n\t\tlog.Infof(\"Sleeping an extra %v after OnTermSync to finish lameduck period\", remain)\n\t\ttime.Sleep(remain)\n\t}\n\n\tlog.Info(\"Shutting down gracefully\")\n\tfireOnCloseHooks(*onCloseTimeout)\n}\n\n\n\n\n\n\n\nfunc OnClose(f func()) {\n\tonCloseHooks.Add(f)\n}\n\nfunc Close() ", "output": "{\n\tonCloseHooks.Fire()\n\tListeningURL = url.URL{}\n}"} {"input": "package output\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/jutkko/mindown/util\"\n)\n\nconst DEPTH_LIMIT int = 6\n\nfunc WriteMarkdown(filename string, forceWrite bool, graph *util.Graph) error {\n\tif !forceWrite {\n\t\tif _, err := os.Stat(filename); !os.IsNotExist(err) {\n\t\t\treturn errors.New(\"File exists\")\n\t\t}\n\t}\n\n\tos.Remove(filename)\n\n\tfile, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)\n\tif err != nil {\n\t\treturn errors.New(\"Failed to open file\")\n\t}\n\tdefer file.Close()\n\n\tif graph == nil {\n\t\treturn errors.New(\"Graph is nil\")\n\t}\n\n\tfor _, node := range graph.GetNodes() {\n\t\terr := writeMarkdownRecursively(1, file, node)\n\n\t\tif err != nil {\n\t\t\treturn errors.New(fmt.Sprintf(\"Failed to write file: %s %s\", filename, err.Error()))\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc getHash(level int) (result string) {\n\tresult = \"\"\n\n\tif level <= DEPTH_LIMIT {\n\t\tfor i := 0; i < level; i++ {\n\t\t\tresult += \"#\"\n\t\t}\n\t\tresult += \" \"\n\t}\n\n\treturn\n}\n\nfunc appendToFile(data string, file *os.File) error {\n\tif _, err := file.WriteString(data); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc writeMarkdownRecursively(depth int, file *os.File, node *util.Node) error ", "output": "{\n\terr := appendToFile(fmt.Sprintf(\"%s%s\\n\", getHash(depth), node.GetTitle()), file)\n\n\tif err != nil || len(node.GetChildren()) == 0 {\n\t\treturn err\n\t}\n\n\tfor _, node := range node.GetChildren() {\n\t\terr := writeMarkdownRecursively(depth+1, file, node)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package helpers\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\tginkgoconfig \"github.com/onsi/ginkgo/config\"\n)\n\n\n\nvar UserDefinedScope string\n\n\n\n\n\n\nfunc GetScopeWithVersion() string {\n\tresult, _ := GetScope()\n\tif result != K8s {\n\t\treturn result\n\t}\n\treturn fmt.Sprintf(\"%s-%s\", result, GetCurrentK8SEnv())\n}\n\nfunc GetScope() (string, error) ", "output": "{\n\tif UserDefinedScope != \"\" {\n\t\treturn UserDefinedScope, nil\n\t}\n\n\tfocusString := strings.TrimSpace(strings.ToLower(ginkgoconfig.GinkgoConfig.FocusString))\n\tswitch {\n\tcase strings.HasPrefix(focusString, \"run\"):\n\t\treturn Runtime, nil\n\tcase strings.HasPrefix(focusString, K8s):\n\t\treturn K8s, nil\n\tcase strings.Contains(focusString, \"nightly\"):\n\t\treturn K8s, nil\n\tdefault:\n\t\treturn \"\", errors.New(\"Scope cannot be set\")\n\t}\n}"} {"input": "package main\n\nimport \"strings\"\n\ntype code_section interface {\n\tCode() bool\n}\n\ntype para string\n\nfunc (para) Code() bool {\n\treturn false\n}\n\ntype code string\n\n\n\ntype Article struct {\n\tTitle string\n\tIntro []para\n\tGoCode, ReflectCode []code_section\n\tUses, Tags []string\n\tslug string\n}\n\nfunc (a *Article) Slug() string {\n\tif a.slug == \"\" {\n\t\ta.slug = strings.ToLower(strings.Replace(a.Title, \" \", \"-\", -1))\n\t}\n\treturn a.slug\n}\n\ntype Articles []*Article\n\nfunc (a *Articles) Add(ao *Article) {\n\t*a = append(*a, ao)\n}\n\nfunc (a Articles) Len() int {\n\treturn len(a)\n}\n\nfunc (a Articles) Swap(i, j int) {\n\ta[j], a[i] = a[i], a[j]\n}\n\nfunc (a Articles) Less(i, j int) bool {\n\treturn a[i].Title < a[j].Title\n}\n\nfunc (code) Code() bool ", "output": "{\n\treturn true\n}"} {"input": "package core\n\n\nimport \"C\"\n\n\n\nfunc lwipInit() ", "output": "{\n\tC.sys_init() \n\tC.lwip_init() \n}"} {"input": "package module\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/config\"\n\t\"github.com/hashicorp/terraform/svchost/disco\"\n)\n\nfunc init() {\n\tif os.Getenv(\"TF_LOG\") == \"\" {\n\t\tlog.SetOutput(ioutil.Discard)\n\t}\n}\n\nconst fixtureDir = \"./test-fixtures\"\n\n\n\nfunc testConfig(t *testing.T, n string) *config.Config {\n\tt.Helper()\n\tc, err := config.LoadDir(filepath.Join(fixtureDir, n))\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\treturn c\n}\n\nfunc testStorage(t *testing.T, d *disco.Disco) *Storage {\n\tt.Helper()\n\treturn NewStorage(tempDir(t), d)\n}\n\nfunc tempDir(t *testing.T) string ", "output": "{\n\tt.Helper()\n\tdir, err := ioutil.TempDir(\"\", \"tf\")\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\tif err := os.RemoveAll(dir); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\treturn dir\n}"} {"input": "package msg\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\n\tzmq \"github.com/pebbe/zmq4\"\n)\n\n\ntype Ping struct {\n\troutingId []byte\n}\n\n\nfunc NewPing() *Ping {\n\tping := &Ping{}\n\treturn ping\n}\n\n\nfunc (p *Ping) String() string {\n\tstr := \"ZCCP_MSG_PING:\\n\"\n\treturn str\n}\n\n\nfunc (p *Ping) Marshal() ([]byte, error) {\n\tbufferSize := 2 + 1 \n\n\ttmpBuf := make([]byte, bufferSize)\n\ttmpBuf = tmpBuf[:0]\n\tbuffer := bytes.NewBuffer(tmpBuf)\n\tbinary.Write(buffer, binary.BigEndian, Signature)\n\tbinary.Write(buffer, binary.BigEndian, PingId)\n\n\treturn buffer.Bytes(), nil\n}\n\n\n\n\n\nfunc (p *Ping) Send(socket *zmq.Socket) (err error) {\n\tframe, err := p.Marshal()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsocType, err := socket.GetType()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif socType == zmq.ROUTER {\n\t\t_, err = socket.SendBytes(p.routingId, zmq.SNDMORE)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t_, err = socket.SendBytes(frame, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn err\n}\n\n\n\nfunc (p *Ping) RoutingId() []byte {\n\treturn p.routingId\n}\n\n\n\nfunc (p *Ping) SetRoutingId(routingId []byte) {\n\tp.routingId = routingId\n}\n\nfunc (p *Ping) Unmarshal(frames ...[]byte) error ", "output": "{\n\tif frames == nil {\n\t\treturn errors.New(\"Can't unmarshal empty message\")\n\t}\n\n\tframe := frames[0]\n\tframes = frames[1:]\n\n\tbuffer := bytes.NewBuffer(frame)\n\n\tvar signature uint16\n\tbinary.Read(buffer, binary.BigEndian, &signature)\n\tif signature != Signature {\n\t\treturn errors.New(\"invalid signature\")\n\t}\n\n\tvar id uint8\n\tbinary.Read(buffer, binary.BigEndian, &id)\n\tif id != PingId {\n\t\treturn errors.New(\"malformed Ping message\")\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\ntype closure func(i, j int) ent\n\ntype ent int\n\nfunc (e ent) String() string {\n\treturn fmt.Sprintf(\"%d\", int(e)) \n}\n\n\n\n\nfunc main() {\n\tf := func(i, j int) ent { \n\t\treturn ent(i + j)\n\t}\n\ti := foo(f, 3).(ent)\n\tfmt.Printf(\"foo(f,3)=%d\\n\", int(i)) \n}\n\nfunc foo(ops closure, j int) (err fmt.Stringer) ", "output": "{ \n\tenqueue := func(i int) fmt.Stringer { \n\t\treturn ops(i, j) \n\t}\n\terr = enqueue(4)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn \n}"} {"input": "package iso20022\n\n\ntype ApplicationParameters4 struct {\n\n\tApplicationIdentification *Max35Text `xml:\"ApplId\"`\n\n\tVersion *Max256Text `xml:\"Vrsn\"`\n\n\tParameters []*Max100KBinary `xml:\"Params,omitempty\"`\n\n\tEncryptedParameters *ContentInformationType10 `xml:\"NcrptdParams,omitempty\"`\n}\n\nfunc (a *ApplicationParameters4) SetApplicationIdentification(value string) {\n\ta.ApplicationIdentification = (*Max35Text)(&value)\n}\n\n\n\nfunc (a *ApplicationParameters4) AddParameters(value string) {\n\ta.Parameters = append(a.Parameters, (*Max100KBinary)(&value))\n}\n\nfunc (a *ApplicationParameters4) AddEncryptedParameters() *ContentInformationType10 {\n\ta.EncryptedParameters = new(ContentInformationType10)\n\treturn a.EncryptedParameters\n}\n\nfunc (a *ApplicationParameters4) SetVersion(value string) ", "output": "{\n\ta.Version = (*Max256Text)(&value)\n}"} {"input": "package backingstore\n\nimport (\n\t\"github.com/gostor/gotgt/pkg/api\"\n\t\"github.com/gostor/gotgt/pkg/scsi\"\n)\n\nfunc init() {\n\tscsi.RegisterBackingStore(\"null\", newNull)\n}\n\ntype NullBackingStore struct {\n\tscsi.BaseBackingStore\n}\n\nfunc newNull() (api.BackingStore, error) {\n\treturn &NullBackingStore{\n\t\tBaseBackingStore: scsi.BaseBackingStore{\n\t\t\tName: \"null\",\n\t\t\tDataSize: 0,\n\t\t\tOflagsSupported: 0,\n\t\t},\n\t}, nil\n}\n\nfunc (bs *NullBackingStore) Open(dev *api.SCSILu, path string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Close(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Init(dev *api.SCSILu, Opts string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Exit(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Size(dev *api.SCSILu) uint64 {\n\treturn 0\n}\n\n\n\nfunc (bs *NullBackingStore) Write(wbuf []byte, offset int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataSync(offset, tl int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataAdvise(offset, length int64, advise uint32) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Unmap([]api.UnmapBlockDescriptor) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Read(offset, tl int64) ([]byte, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package seqnum\n\n\ntype Value uint32\n\n\ntype Size uint32\n\n\n\n\n\nfunc (v Value) LessThanEq(w Value) bool {\n\tif v == w {\n\t\treturn true\n\t}\n\treturn v.LessThan(w)\n}\n\n\nfunc (v Value) InRange(a, b Value) bool {\n\treturn v-a < b-a\n}\n\n\n\nfunc (v Value) InWindow(first Value, size Size) bool {\n\treturn v.InRange(first, first.Add(size))\n}\n\n\nfunc Overlap(a Value, b Size, x Value, y Size) bool {\n\treturn a.LessThan(x.Add(y)) && x.LessThan(a.Add(b))\n}\n\n\nfunc (v Value) Add(s Size) Value {\n\treturn v + Value(s)\n}\n\n\nfunc (v Value) Size(w Value) Size {\n\treturn Size(w - v)\n}\n\n\nfunc (v *Value) UpdateForward(s Size) {\n\t*v += Value(s)\n}\n\nfunc (v Value) LessThan(w Value) bool ", "output": "{\n\treturn int32(v-w) < 0\n}"} {"input": "package goose\n\nimport (\n\t\"os\"\n\t\"text/template\"\n)\n\n\n\n\n\nfunc writeTemplateToFile(path string, t *template.Template, data interface{}) (string, error) ", "output": "{\n\tf, e := os.Create(path)\n\tif e != nil {\n\t\treturn \"\", e\n\t}\n\n\tif err := t.Execute(f, data); err != nil {\n\t\treturn \"\", err\n\t}\n\tif err := f.Close(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn f.Name(), nil\n}"} {"input": "package figure\n\nimport (\n \"fmt\"\n \"log\"\n \"net/http\"\n \"strconv\"\n \"strings\"\n)\n\nconst signature = \"flf2\"\nconst reverseFlag = \"1\"\nvar charDelimiters = [3]string{\"@\", \"#\", \"$\"}\nvar hardblanksBlacklist = [2]byte{'a', '2'}\n\n\n\nfunc getHeight(metadata string) int {\n datum := strings.Fields(metadata)[1]\n height, _ := strconv.Atoi(datum)\n return height\n}\n\nfunc getBaseline(metadata string) int {\n datum := strings.Fields(metadata)[2]\n baseline, _ := strconv.Atoi(datum)\n return baseline\n}\n\nfunc getHardblank(metadata string) byte {\n datum := strings.Fields(metadata)[0]\n hardblank := datum[len(datum)-1]\n if hardblank == hardblanksBlacklist[0] || hardblank == hardblanksBlacklist[1] {\n return ' '\n } else {\n return hardblank\n }\n}\n\nfunc getReverse(metadata string) bool {\n data := strings.Fields(metadata)\n return len(data) > 6 && data[6] == reverseFlag\n}\n\nfunc lastCharLine(text string, height int) bool {\n endOfLine, length := \" \", 2\n if height == 1 && len(text) > 0 {\n length = 1\n }\n if len(text) >= length {\n endOfLine = text[len(text)-length:]\n }\n return endOfLine == strings.Repeat(charDelimiters[0], length) ||\n endOfLine == strings.Repeat(charDelimiters[1], length) ||\n endOfLine == strings.Repeat(charDelimiters[2], length)\n}\n\nfunc getFile(name string) (file http.File) ", "output": "{\n filePath := fmt.Sprintf(\"%s.flf\", name)\n file, err := AssetFS().Open(filePath)\n if err != nil {\n log.Fatalf(\"invalid font name:%s.\",err)\n }\n return file\n}"} {"input": "package runtime\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype response struct {\n}\n\nfunc (r response) Code() int {\n\treturn 490\n}\nfunc (r response) Message() string {\n\treturn \"the message\"\n}\nfunc (r response) GetHeader(_ string) string {\n\treturn \"the header\"\n}\n\nfunc (r response) Body() io.ReadCloser {\n\treturn ioutil.NopCloser(bytes.NewBufferString(\"the content\"))\n}\n\nfunc TestResponseReaderFunc(t *testing.T) {\n\tvar actual struct {\n\t\tHeader, Message, Body string\n\t\tCode int\n\t}\n\treader := ClientResponseReaderFunc(func(r ClientResponse, _ Consumer) (interface{}, error) {\n\t\tb, _ := ioutil.ReadAll(r.Body())\n\t\tactual.Body = string(b)\n\t\tactual.Code = r.Code()\n\t\tactual.Message = r.Message()\n\t\tactual.Header = r.GetHeader(\"blah\")\n\t\treturn actual, nil\n\t})\n\t_, _ = reader.ReadResponse(response{}, nil)\n\tassert.Equal(t, \"the content\", actual.Body)\n\tassert.Equal(t, \"the message\", actual.Message)\n\tassert.Equal(t, \"the header\", actual.Header)\n\tassert.Equal(t, 490, actual.Code)\n}\n\nfunc (r response) GetHeaders(_ string) []string ", "output": "{\n\treturn []string{\"the headers\", \"the headers2\"}\n}"} {"input": "package readline\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\n\nfunc goCompletionEntryFunction(text *C.char, state C.int) *C.char {\n\tmatch := completionEntryFunction(C.GoString(text), int(state))\n\tif match == \"\" {\n\t\treturn nil\n\t}\n\treturn C.CString(match) \n}\n\n\n\n\n\n\n\n\n\n\n\ntype CompletionEntryFunction func(text string, state int) string\n\nvar completionEntryFunction CompletionEntryFunction\n\n\n\nfunc SetCompletionEntryFunction(f CompletionEntryFunction) {\n\tif f == nil {\n\t\tif completionEntryFunction != nil {\n\t\t\tC.rl_attempted_completion_function = nil\n\t\t}\n\t} else if completionEntryFunction == nil {\n\t\tC.register_attempted_completion_function()\n\t}\n\tcompletionEntryFunction = f\n}\n\n\n\n\n\nfunc SetAttemptedCompletionOver(b bool) {\n\tif b {\n\t\tC.rl_attempted_completion_over = 1\n\t} else {\n\t\tC.rl_attempted_completion_over = 0\n\t}\n}\n\n\n\n\n\n\n\n\nfunc CompleterWordBreakChars() string {\n\treturn C.GoString(C.rl_completer_word_break_characters)\n}\n\nfunc SetCompleterWordBreakChars(s string) ", "output": "{\n\tcs := C.CString(s)\n\tC.free(unsafe.Pointer(C.rl_completer_word_break_characters))\n\tC.rl_completer_word_break_characters = cs\n}"} {"input": "package libcontainerd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/containerd/containerd\"\n\t\"github.com/containerd/containerd/windows/hcsshimtypes\"\n\tspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n\t\"github.com/pkg/errors\"\n)\n\nfunc summaryFromInterface(i interface{}) (*Summary, error) {\n\tswitch pd := i.(type) {\n\tcase *hcsshimtypes.ProcessDetails:\n\t\treturn &Summary{\n\t\t\tCreateTimestamp: pd.CreatedAt,\n\t\t\tImageName: pd.ImageName,\n\t\t\tKernelTime100ns: pd.KernelTime_100Ns,\n\t\t\tMemoryCommitBytes: pd.MemoryCommitBytes,\n\t\t\tMemoryWorkingSetPrivateBytes: pd.MemoryWorkingSetPrivateBytes,\n\t\t\tMemoryWorkingSetSharedBytes: pd.MemoryWorkingSetSharedBytes,\n\t\t\tProcessId: pd.ProcessID,\n\t\t\tUserTime100ns: pd.UserTime_100Ns,\n\t\t}, nil\n\tdefault:\n\t\treturn nil, errors.Errorf(\"Unknown process details type %T\", pd)\n\t}\n}\n\nfunc prepareBundleDir(bundleDir string, ociSpec *specs.Spec) (string, error) {\n\treturn bundleDir, nil\n}\n\nfunc pipeName(containerID, processID, name string) string {\n\treturn fmt.Sprintf(`\\\\.\\pipe\\containerd-%s-%s-%s`, containerID, processID, name)\n}\n\n\n\nfunc newFIFOSet(bundleDir, containerID, processID string, withStdin, withTerminal bool) *containerd.FIFOSet ", "output": "{\n\tfifos := &containerd.FIFOSet{\n\t\tTerminal: withTerminal,\n\t\tOut: pipeName(containerID, processID, \"stdout\"),\n\t}\n\n\tif withStdin {\n\t\tfifos.In = pipeName(containerID, processID, \"stdin\")\n\t}\n\n\tif !fifos.Terminal {\n\t\tfifos.Err = pipeName(containerID, processID, \"stderr\")\n\t}\n\n\treturn fifos\n}"} {"input": "package goleveldb\n\nimport (\n\tstore \"github.com/blevesearch/upsidedown_store_api\"\n\t\"github.com/syndtr/goleveldb/leveldb\"\n)\n\ntype Batch struct {\n\tstore *Store\n\tmerge *store.EmulatedMerge\n\tbatch *leveldb.Batch\n}\n\nfunc (b *Batch) Set(key, val []byte) {\n\tb.batch.Put(key, val)\n}\n\nfunc (b *Batch) Delete(key []byte) {\n\tb.batch.Delete(key)\n}\n\n\n\nfunc (b *Batch) Reset() {\n\tb.batch.Reset()\n\tb.merge = store.NewEmulatedMerge(b.store.mo)\n}\n\nfunc (b *Batch) Close() error {\n\tb.batch.Reset()\n\tb.batch = nil\n\tb.merge = nil\n\treturn nil\n}\n\nfunc (b *Batch) Merge(key, val []byte) ", "output": "{\n\tb.merge.Merge(key, val)\n}"} {"input": "package main\n\nimport (\n\t\"net\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\ntype UDPScanner struct {\n\tbuf []byte\n\ttext string\n\terr error\n\tsConn *net.UDPConn\n}\n\n\n\nfunc NewUDPScanner(port string) (*UDPScanner, error) {\n\tsAddr, err := net.ResolveUDPAddr(\"udp\", \":\"+port)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"udp scanner\")\n\t}\n\n\tsConn, err := net.ListenUDP(\"udp\", sAddr)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"udp scanner\")\n\t}\n\n\treturn &UDPScanner{\n\t\tbuf: make([]byte, 1024),\n\t\tsConn: sConn,\n\t}, nil\n}\n\n\nfunc (s *UDPScanner) Scan() bool {\n\tn, err := s.sConn.Read(s.buf)\n\tif err != nil {\n\t\ts.err = errors.Wrap(err, \"udp scan\")\n\t\treturn false\n\t}\n\n\ts.text = string(s.buf[0:n])\n\n\treturn true\n}\n\n\nfunc (s *UDPScanner) Text() string {\n\treturn s.text\n}\n\n\n\n\nfunc (s *UDPScanner) Err() error ", "output": "{\n\treturn s.err\n}"} {"input": "package astutils\n\nimport (\n\t\"go/ast\"\n\t\"go/types\"\n)\n\n\nfunc FieldListName(fieldList *ast.FieldList, fieldPosition int, namePosition int) *string {\n\tnames := FieldListNames(fieldList, fieldPosition)\n\n\tif names == nil || len(names) <= namePosition {\n\t\treturn nil\n\t}\n\n\tname := names[namePosition]\n\n\tif name == nil {\n\t\treturn nil\n\t}\n\n\treturn &name.Name\n}\n\n\nfunc FieldListNames(fieldList *ast.FieldList, position int) []*ast.Ident {\n\tif fieldList == nil {\n\t\treturn nil\n\t}\n\n\tif len(fieldList.List) <= position {\n\t\treturn nil\n\t}\n\n\tfield := fieldList.List[position]\n\n\tif field == nil {\n\t\treturn nil\n\t}\n\n\treturn field.Names\n}\n\n\nfunc FieldListType(fieldList *ast.FieldList, position int) *ast.Expr {\n\tif fieldList == nil {\n\t\treturn nil\n\t}\n\n\tif len(fieldList.List) <= position {\n\t\treturn nil\n\t}\n\n\tfield := fieldList.List[position]\n\n\tif field == nil {\n\t\treturn nil\n\t}\n\n\treturn &field.Type\n}\n\n\n\n\n\n\nfunc IsFieldListType(fieldList *ast.FieldList, position int, exprFunc func(ast.Expr) bool) bool {\n\tt := FieldListType(fieldList, position)\n\n\treturn t != nil && exprFunc(*t)\n}\n\n\nfunc IsFieldListTypePackageType(fieldList *ast.FieldList, position int, info *types.Info, packageSuffix string, typeName string) bool {\n\tt := FieldListType(fieldList, position)\n\n\treturn t != nil && IsPackageFunctionFieldListType(*t, info, packageSuffix, typeName)\n}\n\nfunc HasFieldListLength(fieldList *ast.FieldList, expectedLength int) bool ", "output": "{\n\tif fieldList == nil {\n\t\treturn expectedLength == 0\n\t}\n\n\treturn len(fieldList.List) == expectedLength\n}"} {"input": "package windex\n\nimport (\n\t\"time\"\n)\n\ntype Windex struct {\n\tlogfile *LogFile\n\twatcher *Watcher\n\tindexer Indexer\n\tLogData chan []byte\n\tExit chan bool\n}\n\nfunc New(filename string, custom_indexer ...Indexer) (windex *Windex, err error) {\n\tlogfile, err := NewLogFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twatcher, err := NewWatcher()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar indexer Indexer\n\n\tif len(custom_indexer) == 0 {\n\t\tindexer = NewStdoutIndexer()\n\t} else {\n\t\tindexer = custom_indexer[0]\n\t}\n\n\texit := make(chan bool)\n\tlog_data := make(chan []byte, 5)\n\n\twindex = &Windex{\n\t\tlogfile: logfile,\n\t\twatcher: watcher,\n\t\tindexer: indexer,\n\t\tExit: exit,\n\t\tLogData: log_data,\n\t}\n\n\tgo windex.startwatchloop()\n\n\treturn windex, nil\n}\n\nfunc (windex *Windex) Watch() {\n\tfor {\n\t\ttime.Sleep(50 * time.Millisecond)\n\t\twindex.watcher.Watch(windex.logfile.Filename)\n\t}\n}\n\nfunc (windex *Windex) Index() {\n\tfor {\n\t\tparsed_log_data, _ := windex.indexer.Parse(windex.LogData)\n\t\twindex.indexer.Flush(parsed_log_data)\n\t}\n}\n\nfunc (windex *Windex) Filename() (filename string) {\n\treturn windex.logfile.Filename\n}\n\n\n\nfunc (windex *Windex) startwatchloop() ", "output": "{\n\tfor {\n\t\tselect {\n\t\tcase ev := <-windex.watcher.Watcher.Event:\n\t\t\tif ev != nil && ev.IsModify() && ev.Name == windex.logfile.Filename {\n\t\t\t\twindex.logfile.Flush(windex.LogData)\n\t\t\t}\n\t\tcase err := <-windex.watcher.Watcher.Error:\n\t\t\tif err != nil {\n\t\t\t\twindex.Exit <- true\n\t\t\t}\n\t\t}\n\t}\n\n}"} {"input": "package cmd\n\nimport (\n\t\"context\"\n\t\"io\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/GoogleContainerTools/skaffold/cmd/skaffold/app/tips\"\n\t\"github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner\"\n\tlatestV1 \"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1\"\n\t\"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util\"\n)\n\n\nfunc NewCmdTest() *cobra.Command {\n\treturn NewCmd(\"test\").\n\t\tWithDescription(\"Run tests against your built application images\").\n\t\tWithExample(\"Build the artifacts and collect the tags into a file\", \"build --file-output=tags.json\").\n\t\tWithExample(\"Run test against images previously built by Skaffold into a 'tags.json' file\", \"test --build-artifacts=tags.json\").\n\t\tWithCommonFlags().\n\t\tWithHouseKeepingMessages().\n\t\tNoArgs(doTest)\n}\n\n\n\nfunc doTest(ctx context.Context, out io.Writer) error ", "output": "{\n\treturn withRunner(ctx, out, func(r runner.Runner, configs []util.VersionedConfig) error {\n\t\tvar artifacts []*latestV1.Artifact\n\t\tfor _, c := range configs {\n\t\t\tartifacts = append(artifacts, c.(*latestV1.SkaffoldConfig).Build.Artifacts...)\n\t\t}\n\t\tbuildArtifacts, err := getBuildArtifactsAndSetTags(artifacts, r.ApplyDefaultRepo)\n\t\tif err != nil {\n\t\t\ttips.PrintForTest(out)\n\t\t\treturn err\n\t\t}\n\n\t\treturn r.Test(ctx, out, buildArtifacts)\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\ntype FileExistenceTestv1 struct {\n\tName string \n\tPath string \n\tIsDirectory bool \n\tShouldExist bool \n\tPermissions string \n}\n\nfunc validateFileExistenceTestV1(t *testing.T, tt FileExistenceTestv1) {\n\tif tt.Name == \"\" {\n\t\tt.Fatalf(\"Please provide a valid name for every test!\")\n\t}\n\tif tt.Path == \"\" {\n\t\tt.Fatalf(\"Please provide a valid file path for test %s\", tt.Name)\n\t}\n}\n\n\n\nfunc (ft FileExistenceTestv1) LogName() string ", "output": "{\n\treturn fmt.Sprintf(\"File Existence Test: %s\", ft.Name)\n}"} {"input": "package backend\n\nimport (\n\t\"os\"\n\n\t\"github.com/goharbor/harbor/src/lib/log\"\n)\n\n\n\ntype FileLogger struct {\n\tbackendLogger *log.Logger\n\tstreamRef *os.File\n}\n\n\n\n\n\n\n\nfunc (fl *FileLogger) Close() error {\n\tif fl.streamRef != nil {\n\t\treturn fl.streamRef.Close()\n\t}\n\n\treturn nil\n}\n\n\nfunc (fl *FileLogger) Debug(v ...interface{}) {\n\tfl.backendLogger.Debug(v...)\n}\n\n\nfunc (fl *FileLogger) Debugf(format string, v ...interface{}) {\n\tfl.backendLogger.Debugf(format, v...)\n}\n\n\nfunc (fl *FileLogger) Info(v ...interface{}) {\n\tfl.backendLogger.Info(v...)\n}\n\n\nfunc (fl *FileLogger) Infof(format string, v ...interface{}) {\n\tfl.backendLogger.Infof(format, v...)\n}\n\n\nfunc (fl *FileLogger) Warning(v ...interface{}) {\n\tfl.backendLogger.Warning(v...)\n}\n\n\nfunc (fl *FileLogger) Warningf(format string, v ...interface{}) {\n\tfl.backendLogger.Warningf(format, v...)\n}\n\n\nfunc (fl *FileLogger) Error(v ...interface{}) {\n\tfl.backendLogger.Error(v...)\n}\n\n\nfunc (fl *FileLogger) Errorf(format string, v ...interface{}) {\n\tfl.backendLogger.Errorf(format, v...)\n}\n\n\nfunc (fl *FileLogger) Fatal(v ...interface{}) {\n\tfl.backendLogger.Fatal(v...)\n}\n\n\nfunc (fl *FileLogger) Fatalf(format string, v ...interface{}) {\n\tfl.backendLogger.Fatalf(format, v...)\n}\n\nfunc NewFileLogger(level string, logPath string, depth int) (*FileLogger, error) ", "output": "{\n\tf, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY, 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogLevel := parseLevel(level)\n\tbackendLogger := log.New(f, log.NewTextFormatter(), logLevel, depth)\n\n\treturn &FileLogger{\n\t\tbackendLogger: backendLogger,\n\t\tstreamRef: f,\n\t}, nil\n}"} {"input": "package mock\n\nimport (\n\t\"github.com/eventials/goevents/messaging\"\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype Connection struct {\n\tmock.Mock\n}\n\nfunc NewMockConnection() messaging.Connection {\n\treturn &Connection{}\n}\n\nfunc (c *Connection) Consumer(autoAck bool, exchange, queue string) (messaging.Consumer, error) {\n\targs := c.Called(autoAck, exchange, queue)\n\treturn args.Get(0).(messaging.Consumer), args.Error(1)\n}\n\nfunc (c *Connection) Producer(exchange string) (messaging.Producer, error) {\n\targs := c.Called(exchange)\n\treturn args.Get(0).(messaging.Producer), args.Error(1)\n}\n\nfunc (c *Connection) Close() {\n\tc.Called()\n}\n\nfunc (c *Connection) NotifyConnectionClose() <-chan error {\n\targs := c.Called()\n\treturn args.Get(0).(chan error)\n}\n\n\n\nfunc (c *Connection) WaitUntilConnectionCloses() {\n\tc.Called()\n}\n\nfunc (c *Connection) WaitUntilConnectionReestablished() {\n\tc.Called()\n}\n\nfunc (c *Connection) IsConnected() bool {\n\targs := c.Called()\n\treturn args.Get(0).(bool)\n}\n\nfunc (c *Connection) NotifyReestablish() <-chan bool ", "output": "{\n\targs := c.Called()\n\treturn args.Get(0).(chan bool)\n}"} {"input": "package lifegame\n\ntype Universe struct {\n\taliveCells []Cell\n}\n\ntype Cell struct{}\n\nfunc NewUniverse() *Universe {\n\treturn &Universe{}\n}\n\nfunc (u *Universe) HasAliveCell() bool {\n\treturn len(u.AliveCells()) != 0\n}\n\nfunc (u *Universe) AliveCells() []Cell {\n\treturn u.aliveCells\n}\n\n\n\nfunc (u *Universe) BornCellAtLocation(x, y int) {\n\tu.aliveCells = append(u.aliveCells, Cell{})\n}\n\nfunc (c *Cell) Location() (int, int) {\n\treturn 0, 0\n}\n\nfunc (u *Universe) NextGeneration() ", "output": "{\n\tu.aliveCells = []Cell{}\n}"} {"input": "package test\n\nimport (\n\t\"os\"\n\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nvar Tmpdir string\n\n\n\nfunc init() ", "output": "{\n\tvar err error\n\tTmpdir, err = os.MkdirTemp(\"\", \"cilium_envoy_go_test\")\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to create a temporaty directory for testing\")\n\t}\n}"} {"input": "package common\n\nimport (\n\t\"context\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/packer/helper/multistep\"\n)\n\nfunc TestStepCompactDisk_impl(t *testing.T) {\n\tvar _ multistep.Step = new(StepCompactDisk)\n}\n\nfunc TestStepCompactDisk(t *testing.T) {\n\tstate := testState(t)\n\tstep := new(StepCompactDisk)\n\n\tdiskFile, err := ioutil.TempFile(\"\", \"disk.vmdk\")\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating fake vmdk file: %s\", err)\n\t}\n\n\tdiskFullPath := diskFile.Name()\n\tdefer os.Remove(diskFullPath)\n\n\tcontent := []byte(\"I am the fake vmdk's contents\")\n\tif _, err := diskFile.Write(content); err != nil {\n\t\tt.Fatalf(\"Error writing to fake vmdk file: %s\", err)\n\t}\n\tif err := diskFile.Close(); err != nil {\n\t\tt.Fatalf(\"Error closing fake vmdk file: %s\", err)\n\t}\n\n\tstate.Put(\"disk_full_paths\", []string{diskFullPath})\n\n\tdriver := state.Get(\"driver\").(*DriverMock)\n\n\tif action := step.Run(context.Background(), state); action != multistep.ActionContinue {\n\t\tt.Fatalf(\"bad action: %#v\", action)\n\t}\n\tif _, ok := state.GetOk(\"error\"); ok {\n\t\tt.Fatal(\"should NOT have error\")\n\t}\n\n\tif !driver.CompactDiskCalled {\n\t\tt.Fatal(\"should've called\")\n\t}\n\tif driver.CompactDiskPath != diskFullPath {\n\t\tt.Fatal(\"should call with right path\")\n\t}\n}\n\n\n\nfunc TestStepCompactDisk_skip(t *testing.T) ", "output": "{\n\tstate := testState(t)\n\tstep := new(StepCompactDisk)\n\tstep.Skip = true\n\n\tdiskFullPaths := []string{\"foo\"}\n\tstate.Put(\"disk_full_paths\", diskFullPaths)\n\n\tdriver := state.Get(\"driver\").(*DriverMock)\n\n\tif action := step.Run(context.Background(), state); action != multistep.ActionContinue {\n\t\tt.Fatalf(\"bad action: %#v\", action)\n\t}\n\tif _, ok := state.GetOk(\"error\"); ok {\n\t\tt.Fatal(\"should NOT have error\")\n\t}\n\n\tif driver.CompactDiskCalled {\n\t\tt.Fatal(\"should not have called\")\n\t}\n}"} {"input": "package viewer\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\n\t\"github.com/driusan/de/demodel\"\n\t\"github.com/driusan/de/renderer\"\n)\n\ntype offsetImageMap struct {\n\tbuf *demodel.CharBuffer\n\tvisibleViewport image.Rectangle\n\tviewport *Viewport\n}\n\nfunc (v *Viewport) GetImageMap(buf *demodel.CharBuffer, viewport image.Rectangle) demodel.ImageMap {\n\treturn &offsetImageMap{buf, viewport, v}\n}\n\nfunc (i *offsetImageMap) At(x, y int) (uint, error) {\n\tif i == nil || i.viewport == nil || i.viewport.Renderer == nil {\n\t\treturn 0, fmt.Errorf(\"Viewport renderer is nil\")\n\t}\n\tswitch i.viewport.lineNumberMode {\n\tcase NoLineNumbers:\n\t\tim := i.viewport.Renderer.GetImageMap(i.buf, i.visibleViewport)\n\t\tif im == nil {\n\t\t\treturn 0, fmt.Errorf(\"Renderer does not provide an image map.\")\n\t\t}\n\t\treturn im.At(x, y)\n\tdefault:\n\t\tlineNumberOffset := renderer.MonoFontAdvance * 6\n\t\tif x < lineNumberOffset.Ceil() {\n\t\t\timap := i.viewport.Renderer.GetImageMap(i.buf, i.visibleViewport)\n\t\t\tif imap == nil {\n\t\t\t\treturn 0, fmt.Errorf(\"Renderer imagemap is nil\")\n\t\t\t}\n\t\t\treturn imap.At(lineNumberOffset.Ceil(), y)\n\t\t}\n\t\treturn i.viewport.Renderer.GetImageMap(i.buf, i.visibleViewport).At(x-lineNumberOffset.Floor(), y)\n\t}\n\n}\n\n\n\nfunc (i *offsetImageMap) Get(idx uint) (image.Rectangle, error) ", "output": "{\n\tswitch i.viewport.lineNumberMode {\n\tcase NoLineNumbers:\n\t\treturn i.viewport.Renderer.GetImageMap(i.buf, i.visibleViewport).Get(idx)\n\tdefault:\n\t\tlineNumberOffset := renderer.MonoFontAdvance * 6\n\t\tr, err := i.viewport.Renderer.GetImageMap(i.buf, i.visibleViewport).Get(idx)\n\t\tr.Min.X += lineNumberOffset.Floor()\n\t\tr.Max.X += lineNumberOffset.Floor()\n\t\treturn r, err\n\t}\n}"} {"input": "package cpdf\n\nimport (\n\t\"io/ioutil\"\n)\n\n\ntype bookmarkable interface {\n\tCombinedBookmarkList() string\n\tLocalPath() string\n\tDir() string\n}\n\nfunc (c *Cpdf) addBookmarksArgs(job bookmarkable) {\n\tc.addArgs(\"-add-bookmarks\", infoPath(job))\n}\n\nfunc writeBookmarkInfoFile(job bookmarkable) error {\n\treturn ioutil.WriteFile(infoPath(job), []byte(job.CombinedBookmarkList()), 0644)\n}\n\n\n\nfunc infoPath(job bookmarkable) string ", "output": "{\n\treturn job.Dir() + \"bookmarks.info\"\n}"} {"input": "package queue\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Node struct {\n\tvalue interface{}\n\tnext *Node\n}\n\nfunc NewNode(value interface{}) *Node {\n\tnode := new(Node)\n\tnode.value = value\n\n\treturn node\n}\n\ntype Queue struct {\n\thead *Node\n\ttail *Node\n}\n\nfunc NewQueue(args ...interface{}) *Queue {\n\tlist := new(Queue)\n\n\tfor _, v := range args {\n\t\tlist.Enqueue(v)\n\t}\n\n\treturn list\n}\n\nfunc (q *Queue) String() string {\n\tnode := q.head\n\n\tvar values []string\n\n\tif node == nil {\n\t\treturn \"[]\"\n\t}\n\n\tfor node.next != nil {\n\t\tvalues = append(values, fmt.Sprintf(\"%v\", node.value))\n\n\t\tnode = node.next\n\t}\n\tvalues = append(values, fmt.Sprintf(\"%v\", node.value))\n\n\treturn fmt.Sprintf(\"[%s]\", strings.Join(values, \", \"))\n}\n\nfunc (q *Queue) Enqueue(value interface{}) {\n\tnewTail := NewNode(value)\n\n\tif q.head == nil {\n\t\tq.head = newTail\n\t\tq.tail = q.head\n\t} else {\n\t\tq.tail.next = newTail\n\t\tq.tail = newTail\n\t}\n}\n\nfunc (q *Queue) Dequeue() (value interface{}, ok bool) {\n\n\tif q.head == nil {\n\t\treturn 0, false\n\t} else {\n\t\tnode := q.head\n\t\tq.head = node.next\n\t\treturn node.value, true\n\t}\n}\n\n\n\nfunc (q *Queue) Empty() bool {\n\tif q.head == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\nfunc (q *Queue) Peek() (value interface{}, ok bool) ", "output": "{\n\tif q.head == nil {\n\t\treturn 0, false\n\t} else {\n\t\treturn q.head.value, true\n\t}\n}"} {"input": "package canal\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/BurntSushi/toml\"\n\t\"github.com/siddontang/go-mysql/mysql\"\n\t\"github.com/siddontang/go/ioutil2\"\n\t\"github.com/siddontang/go/log\"\n)\n\ntype masterInfo struct {\n\tAddr string `toml:\"addr\"`\n\tName string `toml:\"bin_name\"`\n\tPosition uint32 `toml:\"bin_pos\"`\n\n\tname string\n\n\tl sync.Mutex\n\n\tlastSaveTime time.Time\n}\n\nfunc loadMasterInfo(name string) (*masterInfo, error) {\n\tvar m masterInfo\n\n\tm.name = name\n\n\tf, err := os.Open(name)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn nil, err\n\t} else if os.IsNotExist(err) {\n\t\treturn &m, nil\n\t}\n\tdefer f.Close()\n\n\t_, err = toml.DecodeReader(f, &m)\n\n\treturn &m, err\n}\n\n\n\nfunc (m *masterInfo) Update(name string, pos uint32) {\n\tm.l.Lock()\n\tm.Name = name\n\tm.Position = pos\n\tm.l.Unlock()\n}\n\nfunc (m *masterInfo) Pos() mysql.Position {\n\tvar pos mysql.Position\n\tm.l.Lock()\n\tpos.Name = m.Name\n\tpos.Pos = m.Position\n\tm.l.Unlock()\n\n\treturn pos\n}\n\nfunc (m *masterInfo) Close() {\n\tm.Save(true)\n}\n\nfunc (m *masterInfo) Save(force bool) error ", "output": "{\n\tm.l.Lock()\n\tdefer m.l.Unlock()\n\n\tn := time.Now()\n\tif !force && n.Sub(m.lastSaveTime) < time.Second {\n\t\treturn nil\n\t}\n\n\tvar buf bytes.Buffer\n\te := toml.NewEncoder(&buf)\n\n\te.Encode(m)\n\n\tvar err error\n\tif err = ioutil2.WriteFileAtomic(m.name, buf.Bytes(), 0644); err != nil {\n\t\tlog.Errorf(\"canal save master info to file %s err %v\", m.name, err)\n\t}\n\n\tm.lastSaveTime = n\n\n\treturn err\n}"} {"input": "package profile\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\n\t\"github.com/sirupsen/logrus\"\n\n\t\"github.com/supergiant/control/pkg/storage\"\n)\n\nconst DefaultKubeProfilePreifx = \"/supergiant/profile\"\n\ntype Service struct {\n\tprefix string\n\tkubeProfileStorage storage.Interface\n}\n\nfunc NewService(prefix string, s storage.Interface) *Service {\n\treturn &Service{\n\t\tprefix: prefix,\n\t\tkubeProfileStorage: s,\n\t}\n}\n\n\n\nfunc (s *Service) Create(ctx context.Context, profile *Profile) error {\n\tprofileData, err := json.Marshal(profile)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.kubeProfileStorage.Put(ctx, s.prefix, profile.ID, profileData)\n}\n\nfunc (s *Service) GetAll(ctx context.Context) ([]Profile, error) {\n\tvar (\n\t\tprofiles []Profile\n\t\tprofile Profile\n\t)\n\n\tprofilesData, err := s.kubeProfileStorage.GetAll(ctx, s.prefix)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, profileData := range profilesData {\n\t\terr = json.Unmarshal(profileData, &profile)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tprofiles = append(profiles, profile)\n\t}\n\n\treturn profiles, nil\n}\n\nfunc (s *Service) Get(ctx context.Context, profileId string) (*Profile, error) ", "output": "{\n\tlogrus.Debugf(\"get cloud profile by id %s\", profileId)\n\tprofileData, err := s.kubeProfileStorage.Get(ctx, s.prefix, profileId)\n\tprofile := &Profile{}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = json.Unmarshal(profileData, profile)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn profile, nil\n}"} {"input": "package collector\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\n\nimport \"C\"\n\ntype kvm struct {\n\tmu sync.Mutex\n\thasErr bool\n}\n\n\n\nfunc (k *kvm) SwapUsedPages() (value uint64, err error) ", "output": "{\n\tk.mu.Lock()\n\tdefer k.mu.Unlock()\n\tif C._kvm_swap_used_pages((*C.uint64_t)(&value)) == -1 {\n\t\tk.hasErr = true\n\t\treturn 0, fmt.Errorf(\"couldn't get kvm stats\")\n\t}\n\n\treturn value, nil\n}"} {"input": "package rusage\n\nimport (\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\nfunc get() (Rusage, error) {\n\tvar rusage syscall.Rusage\n\terr := syscall.Getrusage(syscall.RUSAGE_CHILDREN, &rusage)\n\tif err != nil {\n\t\treturn Rusage{}, errors.Wrapf(err, \"error getting resource usage\")\n\t}\n\tr := Rusage{\n\t\tDate: time.Now(),\n\t\tUtime: mkduration(rusage.Utime),\n\t\tStime: mkduration(rusage.Stime),\n\t\tInblock: int64(rusage.Inblock), \n\t\tOutblock: int64(rusage.Oublock), \n\t}\n\treturn r, nil\n}\n\n\nfunc Supported() bool {\n\treturn true\n}\n\nfunc mkduration(tv syscall.Timeval) time.Duration ", "output": "{\n\treturn time.Duration(tv.Sec)*time.Second + time.Duration(tv.Usec)*time.Microsecond\n}"} {"input": "package dma\n\nimport (\n\t\"stm32/hal/raw/rcc\"\n)\n\nfunc (p *DMA) enableClock(_ bool) {\n\tbit := bit(p, &rcc.RCC.AHBENR.U32, rcc.DMA1ENn)\n\tbit.Set()\n\tbit.Load() \n}\n\n\n\nfunc (p *DMA) reset() {}\n\nfunc (p *DMA) disableClock() ", "output": "{\n\tbit(p, &rcc.RCC.AHBENR.U32, rcc.DMA1ENn).Clear()\n}"} {"input": "package lib\n\nimport (\n\t\"github.com/hyperledger/fabric-ca/lib/common\"\n\t\"github.com/hyperledger/fabric-ca/lib/metadata\"\n)\n\n\ntype ServerInfoResponseNet struct {\n\tCAName string\n\tCAChain string\n\tIssuerPublicKey string\n\tVersion string\n}\n\n\n\n\nfunc cainfoHandler(ctx *serverRequestContextImpl) (interface{}, error) {\n\tca, err := ctx.GetCA()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp := &common.CAInfoResponseNet{}\n\terr = ca.fillCAInfo(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Version = metadata.GetVersion()\n\treturn resp, nil\n}\n\nfunc newCAInfoEndpoint(s *Server) *serverEndpoint ", "output": "{\n\treturn &serverEndpoint{\n\t\tMethods: []string{\"GET\", \"POST\", \"HEAD\"},\n\t\tHandler: cainfoHandler,\n\t\tServer: s,\n\t}\n}"} {"input": "package pump\n\nimport (\n\t\"time\"\n\n\t\"github.com/vail130/orinoco/sieve\"\n\t\"github.com/vail130/orinoco/timeutils\"\n)\n\nfunc forkStream(streams [](map[string]string), eventArray []sieve.Event) {\n\tfor i := 0; i < len(streams); i++ {\n\t\tswitch {\n\t\tcase streams[i][\"type\"] == \"stdout\":\n\t\t\tstream := StdoutStream{}\n\t\t\tgo stream.Process(eventArray)\n\t\tcase streams[i][\"type\"] == \"log\":\n\t\t\tstream := LogStream{\n\t\t\t\tstreams[i][\"path\"],\n\t\t\t}\n\t\t\tgo stream.Process(eventArray)\n\t\tcase streams[i][\"type\"] == \"http\":\n\t\t\tstream := HTTPStream{\n\t\t\t\tstreams[i][\"url\"],\n\t\t\t}\n\t\t\tgo stream.Process(eventArray)\n\t\tcase streams[i][\"type\"] == \"s3\":\n\t\t\tstream := S3Stream{\n\t\t\t\tstreams[i][\"region\"],\n\t\t\t\tstreams[i][\"bucket\"],\n\t\t\t\tstreams[i][\"prefix\"],\n\t\t\t}\n\t\t\tgo stream.Process(eventArray)\n\t\t}\n\t}\n}\n\n\n\nfunc Pump(minBatchSize int, maxBatchDelay int, streams [](map[string]string), eventChannel chan *sieve.Event) ", "output": "{\n\tvar start time.Time\n\tvar now time.Time\n\tfor {\n\t\tstart = timeutils.UtcNow()\n\t\teventArray := make([]sieve.Event, 0)\n\t\tfor event := range eventChannel {\n\t\t\teventArray = append(eventArray, *event)\n\t\t\tnow = timeutils.UtcNow()\n\t\t\tif now.Sub(start) >= time.Duration(maxBatchDelay) || len(eventChannel) >= minBatchSize {\n\t\t\t\tforkStream(streams, eventArray)\n\t\t\t\tstart = now\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\n\t\"github.com/PalmStoneGames/polymer\"\n)\n\nfunc init() {\n\tpolymer.Register(\"name-tag\", &NameTag{})\n}\n\ntype NameTag struct {\n\t*polymer.Proto\n\n\tID int64 `polymer:\"bind\"`\n\tName string `polymer:\"bind\"`\n\tNameChange chan *polymer.Event `polymer:\"handler\"`\n}\n\n\n\nfunc (n *NameTag) Ready() {\n\tfmt.Printf(\"%v: Initial Name = %v\\n\", n.ID, n.Name)\n}\n\nfunc main() {}\n\nfunc (n *NameTag) Created() ", "output": "{\n\tn.ID = rand.Int63()\n\n\tgo func() {\n\t\tfor _ = range n.NameChange {\n\t\t\tfmt.Printf(\"%v: HandleNameChange event. Name = %v\\n\", n.ID, n.Name)\n\t\t}\n\t}()\n}"} {"input": "package utils\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/juju/errors\"\n)\n\n\n\n\n\nfunc Respond(w http.ResponseWriter, data interface{}, code int) error {\n\tw.WriteHeader(code)\n\n\tvar resp []byte\n\tvar err error\n\n\tresp, err = json.Marshal(data) \n\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfmt.Fprintln(w, string(resp))\n\n\treturn nil\n}\n\n\nfunc UnmarshalRequest(r *http.Request, v interface{}) error {\n\tbody, err := GetRequestBody(r)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tif err := json.Unmarshal(body, v); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\treturn nil\n}\n\nfunc GetRequestBody(r *http.Request) ([]byte, error) ", "output": "{\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treturn body, nil\n}"} {"input": "package rand\n\n\nimport \"C\"\n\n\n\n\n\nfunc Seed(i int) {\n\tC.srandom(C.uint(i))\n}\n\nfunc Random() int ", "output": "{\n\treturn int(C.random())\n}"} {"input": "package application\n\nimport (\n\t\"encoding/base64\"\n\t\"github.com/gorilla/securecookie\"\n\t\"net/http\"\n\t\"testing\"\n)\n\n\nconst cookieName = \"recaptcha\"\nconst testHashKey = \"RovMQmutMbSogUuGQFZYLb37jwgwFNuMR7wrEz9EILQ9W039UHCFlCfkpX1EbecktHA563XX+7clPRinBPeaeQ==\"\nconst testBlockKey = \"+sSXCAbwswiYNqHx4zCuJJTD3hmRQp4f4uJKy+aFL70=\"\n\nfunc generateGorillaSecureCookie() *securecookie.SecureCookie {\n\thashKey, _ := base64.StdEncoding.DecodeString(testHashKey)\n\tblockKey, _ := base64.StdEncoding.DecodeString(testBlockKey)\n\treturn securecookie.New(hashKey, blockKey)\n}\n\n\n\nfunc TestSecureRecaptchaCookie_Encode(t *testing.T) {\n\tvalidCookie := &http.Cookie{Value: \"Some Value\"}\n\n\tsecureRecaptchaCookie := NewSecureRecaptchaCookie(cookieName, validCookie, generateGorillaSecureCookie())\n\tsecureRecaptchaCookie.Value = secureRecaptchaCookie.Encode(validCookie.Value)\n\n\tif secureRecaptchaCookie.IsValid(validCookie.Value) != true {\n\t\tt.Error(\"The cookie value should have been encoded and decoded correctly\")\n\t}\n}\n\nfunc TestNewSecureRecaptchaCookie(t *testing.T) ", "output": "{\n\tsecureRecaptchaCookie1 := NewSecureRecaptchaCookie(cookieName, nil, generateGorillaSecureCookie())\n\tif secureRecaptchaCookie1.Name != cookieName || len(secureRecaptchaCookie1.Value) != 0 {\n\t\tt.Error(\"The new secure cookie based on an empty cookie should have no value\")\n\t}\n\n\tvalidCookie := &http.Cookie{Value: \"Some Value\"}\n\tsecureRecaptchaCookie2 := NewSecureRecaptchaCookie(cookieName, validCookie, generateGorillaSecureCookie())\n\tif secureRecaptchaCookie2.Name != cookieName || len(secureRecaptchaCookie2.Value) == 0 {\n\t\tt.Error(\"The new secure cookie based on a valid cookie should have a value\")\n\t}\n}"} {"input": "package chaincode\n\nimport (\n\t\"github.com/golang/protobuf/proto\"\n\tpb \"github.com/hyperledger/fabric-protos-go/peer\"\n\tcommonledger \"github.com/hyperledger/fabric/common/ledger\"\n)\n\ntype PendingQueryResult struct {\n\tbatch []*pb.QueryResultBytes\n}\n\nfunc (p *PendingQueryResult) Cut() []*pb.QueryResultBytes {\n\tbatch := p.batch\n\tp.batch = nil\n\treturn batch\n}\n\n\n\nfunc (p *PendingQueryResult) Size() int {\n\treturn len(p.batch)\n}\n\nfunc (p *PendingQueryResult) Add(queryResult commonledger.QueryResult) error ", "output": "{\n\tqueryResultBytes, err := proto.Marshal(queryResult.(proto.Message))\n\tif err != nil {\n\t\tchaincodeLogger.Errorf(\"failed to marshal query result: %s\", err)\n\t\treturn err\n\t}\n\tp.batch = append(p.batch, &pb.QueryResultBytes{ResultBytes: queryResultBytes})\n\treturn nil\n}"} {"input": "package log\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\ntype Exit struct {\n\tCode int\n\tClosure func()\n}\n\nfunc HandleExit() {\n\tif e := recover(); e != nil {\n\t\tif exit, ok := e.(Exit); ok {\n\t\t\texit.Closure()\n\t\t\tos.Exit(exit.Code)\n\t\t}\n\t\tpanic(e)\n\t}\n}\n\nfunc Error(msg string, closure func()) {\n\tfmt.Printf(\"\\033[1;31m[ERROR]\\033[0m %s\\n\", msg)\n\tpanic(Exit{1, closure})\n}\n\nfunc Warn(msg string) {\n\tfmt.Printf(\"\\033[1;33m[WARNING]\\033[0m %s\\n\", msg)\n}\n\n\n\nfunc Succ(msg string) ", "output": "{\n\tfmt.Printf(\"\\033[1;32m[DONE]\\033[0m %s\\n\", msg)\n}"} {"input": "package filtered\n\nimport (\n\tcontext \"context\"\n\n\tv1 \"github.com/google/knative-gcp/pkg/client/informers/externalversions/events/v1\"\n\tfiltered \"github.com/google/knative-gcp/pkg/client/injection/informers/factory/filtered\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\n\n\n\ntype Key struct {\n\tSelector string\n}\n\nfunc withInformer(ctx context.Context) (context.Context, []controller.Informer) {\n\tuntyped := ctx.Value(filtered.LabelKey{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch labelkey from context.\")\n\t}\n\tlabelSelectors := untyped.([]string)\n\tinfs := []controller.Informer{}\n\tfor _, selector := range labelSelectors {\n\t\tf := filtered.Get(ctx, selector)\n\t\tinf := f.Events().V1().CloudStorageSources()\n\t\tctx = context.WithValue(ctx, Key{Selector: selector}, inf)\n\t\tinfs = append(infs, inf.Informer())\n\t}\n\treturn ctx, infs\n}\n\n\nfunc Get(ctx context.Context, selector string) v1.CloudStorageSourceInformer {\n\tuntyped := ctx.Value(Key{Selector: selector})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panicf(\n\t\t\t\"Unable to fetch github.com/google/knative-gcp/pkg/client/informers/externalversions/events/v1.CloudStorageSourceInformer with selector %s from context.\", selector)\n\t}\n\treturn untyped.(v1.CloudStorageSourceInformer)\n}\n\nfunc init() ", "output": "{\n\tinjection.Default.RegisterFilteredInformers(withInformer)\n}"} {"input": "package fileutil\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\ntype unixLock struct {\n\tf *os.File\n}\n\nfunc (l *unixLock) Release() error {\n\tif err := l.set(false); err != nil {\n\t\treturn err\n\t}\n\treturn l.f.Close()\n}\n\n\n\nfunc newLock(fileName string) (Releaser, error) {\n\tf, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tl := &unixLock{f}\n\terr = l.set(true)\n\tif err != nil {\n\t\tf.Close()\n\t\treturn nil, err\n\t}\n\treturn l, nil\n}\n\nfunc (l *unixLock) set(lock bool) error ", "output": "{\n\tflock := syscall.Flock_t{\n\t\tType: syscall.F_UNLCK,\n\t\tStart: 0,\n\t\tLen: 0,\n\t\tWhence: 1,\n\t}\n\tif lock {\n\t\tflock.Type = syscall.F_WRLCK\n\t}\n\treturn syscall.FcntlFlock(l.f.Fd(), syscall.F_SETLK, &flock)\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\n\n\ntype StatsRecorder struct {\n\tmutex sync.RWMutex\n\tnumRecentErrors int\n\trecentErrors []*statsError\n}\n\n\ntype Stats struct {\n\tRecentErrors []*statsError `json:\"recent_errors\"`\n}\n\n\ntype statsError struct {\n\tStatusCode int `json:\"status_code\"`\n\tStatus string `json:\"status\"`\n\tMethod string `json:\"method\"`\n\tHost string `json:\"host\"`\n\tPath string `json:\"path\"`\n\tTime time.Time `json:\"time\"`\n}\n\n\n\ntype responseRecorder struct {\n\thttp.ResponseWriter\n\tstatusCode int\n}\n\n\nfunc (r *responseRecorder) WriteHeader(status int) {\n\tr.ResponseWriter.WriteHeader(status)\n\tr.statusCode = status\n}\n\n\n\n\n\n\n\nfunc (s *StatsRecorder) Data() *Stats {\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\n\trecentErrors := make([]*statsError, len(s.recentErrors))\n\tcopy(recentErrors, s.recentErrors)\n\n\treturn &Stats{\n\t\tRecentErrors: recentErrors,\n\t}\n}\n\nfunc (s *StatsRecorder) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) ", "output": "{\n\trecorder := &responseRecorder{w, http.StatusOK}\n\tnext(recorder, r)\n\tif recorder.statusCode >= 400 {\n\t\ts.mutex.Lock()\n\t\tdefer s.mutex.Unlock()\n\t\ts.recentErrors = append([]*statsError{\n\t\t\t{\n\t\t\t\tStatusCode: recorder.statusCode,\n\t\t\t\tStatus: http.StatusText(recorder.statusCode),\n\t\t\t\tMethod: r.Method,\n\t\t\t\tHost: r.Host,\n\t\t\t\tPath: r.URL.Path,\n\t\t\t\tTime: time.Now(),\n\t\t\t},\n\t\t}, s.recentErrors...)\n\t\tif len(s.recentErrors) > s.numRecentErrors {\n\t\t\ts.recentErrors = s.recentErrors[:s.numRecentErrors]\n\t\t}\n\t}\n}"} {"input": "package kegg\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc ExampleGet() {\n\tinfo, err := New().Get(\"drug\", \"D00341\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(info != \"\")\n}\n\nfunc ExampleFind() {\n\tmatch, err := New().Find(\"drug\", \"D00341\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(match != \"\")\n}\n\nfunc ExampleLink() {\n\tcompoundID, err := New().Link(\"drug\", \"compound\", \"D00341\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(compoundID)\n}\n\nfunc ExampleConvert() ", "output": "{\n\tdrugID, err := New().Convert(\"pubchem\", \"drug\", \"313046637\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(drugID)\n}"} {"input": "package cloudstorage\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n)\n\ntype MockStorage struct {\n\tPutRequest *http.Request\n\tGetURL *url.URL\n\tOriginallySigned bool\n\tListObjectsResponse *ListObjectsResponse\n}\n\nvar _ Storage = &MockStorage{}\n\nfunc (s *MockStorage) PresignPutObject(name string, accessType AccessType, header http.Header) (*http.Request, error) {\n\treturn s.PutRequest, nil\n}\n\nfunc (s *MockStorage) PresignGetObject(name string) (*url.URL, error) {\n\treturn s.GetURL, nil\n}\n\nfunc (s *MockStorage) PresignHeadObject(name string) (*url.URL, error) {\n\treturn s.GetURL, nil\n}\n\nfunc (s *MockStorage) RewriteGetURL(u *url.URL, name string) (*url.URL, bool, error) {\n\treturn s.GetURL, s.OriginallySigned, nil\n}\n\nfunc (s *MockStorage) ListObjects(r *ListObjectsRequest) (*ListObjectsResponse, error) {\n\treturn s.ListObjectsResponse, nil\n}\n\nfunc (s *MockStorage) DeleteObject(name string) error {\n\treturn nil\n}\n\n\n\nfunc (s *MockStorage) StandardToProprietary(header http.Header) http.Header {\n\treturn header\n}\n\nfunc (s *MockStorage) ProprietaryToStandard(header http.Header) http.Header {\n\treturn header\n}\n\nfunc (s *MockStorage) AccessType(header http.Header) AccessType ", "output": "{\n\treturn AccessTypeDefault\n}"} {"input": "package tlsutil\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\t\"io/ioutil\"\n)\n\ntype TLSConfig struct {\n\tConfig *tls.Config\n}\n\n\n\nfunc (tc *TLSConfig) LoadX509KeyPair(cert_filepath, key_filepath string) error {\n\tcert, err := tls.LoadX509KeyPair(cert_filepath, key_filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttc.Config.Certificates = append(tc.Config.Certificates, cert)\n\treturn nil\n}\n\nfunc (tc *TLSConfig) LoadCACert(ca_cert_filepath string) error {\n\tcert, err := ioutil.ReadFile(ca_cert_filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tc.Config.RootCAs == nil {\n\t\ttc.Config.RootCAs = x509.NewCertPool()\n\t}\n\n\tok := tc.Config.RootCAs.AppendCertsFromPEM(cert)\n\tif !ok {\n\t\treturn fmt.Errorf(\"Cannot add Root CA cert %v\", ca_cert_filepath)\n\t}\n\treturn nil\n}\n\nfunc (tc *TLSConfig) Inflate() {\n\ttc.Config.BuildNameToCertificate()\n}\n\nfunc NewTLSConfig() TLSConfig ", "output": "{\n\treturn TLSConfig{\n\t\tConfig: &tls.Config{\n\t\t\tCertificates: []tls.Certificate{},\n\t\t},\n\t}\n}"} {"input": "package fileinterface\n\nimport (\n \"testing\"\n \"errors\"\n )\n\nfunc TestCreate(t *testing.T) {\n\tvar f FID\n\tvar err error\n\tif f, err = Create(\"dummyfile\"); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tif err = Close(f); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n}\n\nfunc TestDelete(t *testing.T) {\n\terr := Delete(\"dummyfile\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestOpen(t *testing.T) {\n\tif f, err := Open(\"sample.database\"); err != nil {\n\t\tt.Error(err)\n\t} else if err = Close(f); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\n\n\nfunc TestLength(t *testing.T) {\n}\n\nfunc TestWrite(t *testing.T) {\n\tvar block Block\n\tfor i:=0; i> 8)\n\tbyte1 := byte(0x00ff & value) \n\treturn [2]byte{byte0, byte1}\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"time\"\n)\n\nvar size int64;\nvar message string = \"X-\"; \nvar separator string = \" \"; \n\nfunc main() {\n start:=int64(0); \n finish:=int64(255); \n width:=int64(16); \n\n now := time.Now(); \n epoch := now.Unix(); \n\n fmt.Printf(\"####################################\\n\");\n fmt.Printf(\"#\\n\");\n fmt.Printf(\"# -- TEXTPATGEN GENERATED FILE --\\n\");\n fmt.Printf(\"#\\n\");\n fmt.Printf(\"# -- Created: %s\\n\", now.Format(time.RFC3339));\n fmt.Printf(\"# -- Epoch Time: %d\\n\", epoch);\n fmt.Printf(\"#\\n\");\n fmt.Printf(\"# Start number: %d ( 0x%X Hex, 0%o Octal )\\n\",start,start,start);\n fmt.Printf(\"# Finish number: %d ( 0x%X Hex, 0%o Octal )\\n\",finish,finish,finish);\n fmt.Printf(\"# Numbers in a line: %d\\n\",width);\n fmt.Printf(\"#\\n\");\n fmt.Printf(\"####################################\\n\");\n numgen(start, finish, size, width);\n fmt.Printf(\"# -- End of file.\\n\");\n}\n\n\n\nfunc numgen(start int64, finish int64, size int64, width int64) ", "output": "{\n for num:=start; num<=finish; num++ {\n for size:=int64(0); size<(width - 1); size++ {\n if (num == finish) {\n break;\n }\n fmt.Printf(\"%s\", message);\n fmt.Printf(\"%04X\", num); \n fmt.Printf(\"%s\", separator);\n num++;\n }\n fmt.Printf(\"%s\", message);\n fmt.Printf(\"%04X\\n\", num); \n }\n}"} {"input": "package factory\n\nimport (\n\tcontext \"context\"\n\n\texternalversions \"knative.dev/eventing-kafka-broker/control-plane/pkg/client/informers/externalversions\"\n\tclient \"knative.dev/eventing-kafka-broker/control-plane/pkg/client/injection/client\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\n\n\n\ntype Key struct{}\n\nfunc withInformerFactory(ctx context.Context) context.Context {\n\tc := client.Get(ctx)\n\topts := make([]externalversions.SharedInformerOption, 0, 1)\n\tif injection.HasNamespaceScope(ctx) {\n\t\topts = append(opts, externalversions.WithNamespace(injection.GetNamespaceScope(ctx)))\n\t}\n\treturn context.WithValue(ctx, Key{},\n\t\texternalversions.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...))\n}\n\n\nfunc Get(ctx context.Context) externalversions.SharedInformerFactory {\n\tuntyped := ctx.Value(Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch knative.dev/eventing-kafka-broker/control-plane/pkg/client/informers/externalversions.SharedInformerFactory from context.\")\n\t}\n\treturn untyped.(externalversions.SharedInformerFactory)\n}\n\nfunc init() ", "output": "{\n\tinjection.Default.RegisterInformerFactory(withInformerFactory)\n}"} {"input": "package opt\n\nimport (\n\t\"github.com/algolia/algoliasearch-client-go/v3/algolia/opt\"\n)\n\n\n\n\n\nfunc ExtractIndexName(opts ...interface{}) *opt.IndexNameOption ", "output": "{\n\tfor _, o := range opts {\n\t\tif v, ok := o.(*opt.IndexNameOption); ok {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package wire_test\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\n\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc (w *fixedWriter) Bytes() []byte ", "output": "{\n\treturn w.b\n}"} {"input": "package arrow\n\nimport (\n\t\"sort\"\n\n\t\"github.com/catorpilor/leetcode/utils\"\n)\n\n\n\n\nfunc useTwoPointers(points [][]int) int {\n\tn := len(points)\n\tif n <= 1 {\n\t\treturn n\n\t}\n\tsort.Slice(points, func(i, j int) bool {\n\t\tif points[i][0] == points[j][0] {\n\t\t\treturn points[i][1] < points[j][1]\n\t\t}\n\t\treturn points[i][0] < points[j][0]\n\t})\n\tleft, right := points[0][0], points[0][1]\n\tans := 1\n\tfor i := 1; i < n; i++ {\n\t\tif points[i][0] > right {\n\t\t\tright = points[i][1]\n\t\t\tans++\n\t\t} else {\n\t\t\tright = utils.Min(right, points[i][1])\n\t\t}\n\t\t_ = left\n\t\tleft = points[i][0]\n\t}\n\treturn ans\n}\n\n\nfunc useBoundary(points [][]int) int {\n\tn := len(points)\n\tif n <= 1 {\n\t\treturn n\n\t}\n\tsort.Slice(points, func(i, j int) bool {\n\t\treturn points[i][1] < points[j][1]\n\t})\n\tcurB := points[0]\n\tans := 1\n\tfor i := 1; i < n; i++ {\n\t\tif points[i][0] > curB[1] {\n\t\t\tans++\n\t\t\tcurB = points[i]\n\t\t}\n\t}\n\treturn ans\n}\n\nfunc minArrows(points [][]int) int ", "output": "{\n\treturn useTwoPointers(points)\n}"} {"input": "package engine\n\nimport (\n\tvtrpcpb \"vitess.io/vitess/go/vt/proto/vtrpc\"\n\t\"vitess.io/vitess/go/vt/vterrors\"\n\n\t\"vitess.io/vitess/go/sqltypes\"\n\t\"vitess.io/vitess/go/vt/proto/query\"\n)\n\nvar _ Primitive = (*UpdateTarget)(nil)\n\n\ntype UpdateTarget struct {\n\tTarget string\n\n\tnoInputs\n\n\tnoTxNeeded\n}\n\n\n\n\nfunc (updTarget *UpdateTarget) RouteType() string {\n\treturn \"UpdateTarget\"\n}\n\n\nfunc (updTarget *UpdateTarget) GetKeyspaceName() string {\n\treturn updTarget.Target\n}\n\n\nfunc (updTarget *UpdateTarget) GetTableName() string {\n\treturn \"\"\n}\n\n\nfunc (updTarget *UpdateTarget) TryExecute(vcursor VCursor, bindVars map[string]*query.BindVariable, wantfields bool) (*sqltypes.Result, error) {\n\terr := vcursor.Session().SetTarget(updTarget.Target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &sqltypes.Result{}, nil\n}\n\n\nfunc (updTarget *UpdateTarget) TryStreamExecute(vcursor VCursor, bindVars map[string]*query.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error {\n\tresult, err := updTarget.TryExecute(vcursor, bindVars, wantfields)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn callback(result)\n}\n\n\nfunc (updTarget *UpdateTarget) GetFields(vcursor VCursor, bindVars map[string]*query.BindVariable) (*sqltypes.Result, error) {\n\treturn nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, \"[BUG] GetFields not reachable for use statement\")\n}\n\nfunc (updTarget *UpdateTarget) description() PrimitiveDescription ", "output": "{\n\treturn PrimitiveDescription{\n\t\tOperatorType: \"UpdateTarget\",\n\t\tOther: map[string]interface{}{\"target\": updTarget.Target},\n\t}\n}"} {"input": "package binary\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/google/gapid/core/math/f16\"\n)\n\n\ntype Writer interface {\n\tData([]byte)\n\tBool(bool)\n\tInt8(int8)\n\tUint8(uint8)\n\tInt16(int16)\n\tUint16(uint16)\n\tInt32(int32)\n\tUint32(uint32)\n\tFloat16(f16.Number)\n\tFloat32(float32)\n\tInt64(int64)\n\tUint64(uint64)\n\tFloat64(float64)\n\tString(string)\n\tSimple(Writable)\n\tError() error\n\tSetError(error)\n}\n\n\n\n\n\nfunc WriteInt(w Writer, bits int32, v int64) {\n\tswitch bits {\n\tcase 8:\n\t\tw.Int8(int8(v))\n\tcase 16:\n\t\tw.Int16(int16(v))\n\tcase 32:\n\t\tw.Int32(int32(v))\n\tcase 64:\n\t\tw.Int64(int64(v))\n\tdefault:\n\t\tw.SetError(fmt.Errorf(\"Unsupported integer bit count %v\", bits))\n\t}\n}\n\n\nfunc WriteBytes(w Writer, v uint8, count int32) {\n\tfor i := int32(0); i < count; i++ {\n\t\tw.Uint8(v)\n\t}\n}\n\nfunc WriteUint(w Writer, bits int32, v uint64) ", "output": "{\n\tswitch bits {\n\tcase 8:\n\t\tw.Uint8(uint8(v))\n\tcase 16:\n\t\tw.Uint16(uint16(v))\n\tcase 32:\n\t\tw.Uint32(uint32(v))\n\tcase 64:\n\t\tw.Uint64(uint64(v))\n\tdefault:\n\t\tw.SetError(fmt.Errorf(\"Unsupported integer bit count %v\", bits))\n\t}\n}"} {"input": "package lapack\n\nimport (\n \n \"fmt\"\n \"github.com/hrautila/linalg\"\n \"github.com/hrautila/matrix\"\n)\n\n\n\n\nfunc PotrfFloat(A *matrix.FloatMatrix, opts ...linalg.Option) error {\n pars, err := linalg.GetParameters(opts...)\n if err != nil {\n return err\n }\n ind := linalg.GetIndexOpts(opts...)\n err = checkPotrf(ind, A)\n if ind.N == 0 {\n return nil\n }\n Aa := A.FloatArray()\n uplo := linalg.ParamString(pars.Uplo)\n info := dpotrf(uplo, ind.N, Aa[ind.OffsetA:], ind.LDa)\n if info != 0 {\n return onError(fmt.Sprintf(\"Potrf: lapack error %d\", info))\n }\n return nil\n}\n\nfunc checkPotrf(ind *linalg.IndexOpts, A matrix.Matrix) error {\n arows := ind.LDa\n if ind.N < 0 {\n ind.N = A.Rows()\n if ind.N != A.Cols() {\n return onError(\"Potrf: not square\")\n }\n }\n if ind.N == 0 {\n return nil\n }\n if ind.LDa == 0 {\n ind.LDa = max(1, A.LeadingIndex())\n arows = max(1, A.Rows())\n }\n if ind.LDa < max(1, ind.N) {\n return onError(\"Potrf: lda\")\n }\n if ind.OffsetA < 0 {\n return onError(\"Potrf: offsetA\")\n }\n if A.NumElements() < ind.OffsetA+(ind.N-1)*arows+ind.N {\n return onError(\"Potrf: sizeA\")\n }\n return nil\n}\n\nfunc Potrf(A matrix.Matrix, opts ...linalg.Option) error ", "output": "{\n switch A.(type) {\n case *matrix.FloatMatrix:\n return PotrfFloat(A.(*matrix.FloatMatrix), opts...)\n case *matrix.ComplexMatrix:\n return onError(\"Potrf: complex not implemented yet\")\n }\n return onError(\"Potrf unknown types\")\n}"} {"input": "package proxy\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype rttGenerator struct {\n\tmin time.Duration\n\tmax time.Duration\n}\n\nfunc newRttGenerator(min, max time.Duration) rttGenerator {\n\trand.Seed(time.Now().UnixNano())\n\treturn rttGenerator{\n\t\tmin: min,\n\t\tmax: max,\n\t}\n}\n\n\n\nfunc (s *rttGenerator) getRTT() time.Duration ", "output": "{\n\tif s.min == s.max {\n\t\treturn s.min\n\t}\n\n\tminns := s.min.Nanoseconds()\n\tmaxns := s.max.Nanoseconds()\n\trttns := rand.Int63n(maxns-minns) + minns\n\n\treturn time.Duration(rttns) * time.Nanosecond\n}"} {"input": "package views\n\nimport \"github.com/cSploit/daemon/models\"\n\ntype networkIdxElem struct {\n\tmodels.Network\n\tHideHosts string `json:\"hosts,omitempty\"`\n}\n\ntype networkShowView struct {\n\tmodels.Network\n\tOverrideHosts interface{} `json:\"hosts,omitempty\"`\n}\n\nfunc NetworkIndex(args interface{}) interface{} {\n\tnets := args.([]models.Network)\n\tres := make([]networkIdxElem, len(nets))\n\n\tfor i, n := range nets {\n\t\tres[i] = networkIdxElem{Network: n}\n\t}\n\n\treturn res\n}\n\n\n\nfunc networkAsChild(arg interface{}) interface{} {\n\tnetwork := arg.(models.Network)\n\treturn networkIdxElem{Network: network}\n}\n\nfunc NetworkShow(arg interface{}) interface{} ", "output": "{\n\tnet := arg.(models.Network)\n\tres := networkShowView{Network: net}\n\n\tif len(net.Hosts) > 0 {\n\t\tres.OverrideHosts = HostsIndex(net.Hosts)\n\t}\n\n\treturn res\n}"} {"input": "package firebirdsql\n\ntype firebirdsqlResult struct {\n\taffectedRows int64\n}\n\nfunc (res *firebirdsqlResult) LastInsertId() (int64, error) {\n\treturn -1, nil\n}\n\n\n\nfunc (res *firebirdsqlResult) RowsAffected() (int64, error) ", "output": "{\n\treturn res.affectedRows, nil\n}"} {"input": "package xeth\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/ethereum/go-ethereum/common\"\n)\n\n\n\ntype whisperFilter struct {\n\tid int \n\tref *Whisper \n\n\tcache []WhisperMessage \n\tskip map[common.Hash]struct{} \n\tupdate time.Time \n\n\tlock sync.RWMutex \n}\n\n\nfunc newWhisperFilter(id int, ref *Whisper) *whisperFilter {\n\treturn &whisperFilter{\n\t\tid: id,\n\t\tref: ref,\n\n\t\tupdate: time.Now(),\n\t\tskip: make(map[common.Hash]struct{}),\n\t}\n}\n\n\n\nfunc (w *whisperFilter) messages() []WhisperMessage {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tw.cache = nil\n\tw.update = time.Now()\n\n\tw.skip = make(map[common.Hash]struct{})\n\tmessages := w.ref.Messages(w.id)\n\tfor _, message := range messages {\n\t\tw.skip[message.ref.Hash] = struct{}{}\n\t}\n\treturn messages\n}\n\n\n\n\n\nfunc (w *whisperFilter) retrieve() (messages []WhisperMessage) {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tmessages, w.cache = w.cache, nil\n\tw.update = time.Now()\n\n\treturn\n}\n\n\n\nfunc (w *whisperFilter) activity() time.Time {\n\tw.lock.RLock()\n\tdefer w.lock.RUnlock()\n\n\treturn w.update\n}\n\nfunc (w *whisperFilter) insert(messages ...WhisperMessage) ", "output": "{\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tfor _, message := range messages {\n\t\tif _, ok := w.skip[message.ref.Hash]; !ok {\n\t\t\tw.cache = append(w.cache, messages...)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport \"code.google.com/p/go-tour/tree\"\nimport \"fmt\"\n\n\n\n\n\nfunc Walk(t *tree.Tree, ch chan int){\n\twalk(t, ch)\n close(ch)\n}\n\n\n\nfunc Same(t1, t2 *tree.Tree) bool {\n ch1 := make(chan int)\n ch2 := make(chan int)\n \n go Walk(t1, ch1)\n go Walk(t2, ch2)\n \n for i := range ch1 { \n\t\tif i != <- ch2 {\n \t\t\treturn false\n }\n }\n return true\n}\n\nfunc main() {\n ch := make(chan int)\n \n go Walk(tree.New(1), ch)\n \n for i := range ch {\n fmt.Println(i)\n }\n \n fmt.Println(Same(tree.New(1), tree.New(1)))\n fmt.Println(Same(tree.New(1), tree.New(2)))\n}\n\nfunc walk(t *tree.Tree, ch chan int)", "output": "{\n if t != nil {\n walk(t.Left, ch)\n ch <- t.Value\n \twalk(t.Right, ch)\n }\n \n}"} {"input": "package outlet\n\nimport (\n\t\"fmt\"\n\t\"l2met/bucket\"\n\t\"l2met/store\"\n\t\"time\"\n)\n\ntype BucketReader struct {\n\tStore store.Store\n\tInterval time.Duration\n\tPartition string\n\tTtl uint64\n\tNumOutlets int\n\tNumScanners int\n\tInbox chan *bucket.Bucket\n\tOutbox chan *bucket.Bucket\n}\n\nfunc NewBucketReader(sz, c int, i time.Duration, st store.Store) *BucketReader {\n\trdr := new(BucketReader)\n\trdr.Partition = \"bucket-reader\"\n\trdr.Inbox = make(chan *bucket.Bucket, sz)\n\trdr.NumScanners = c\n\trdr.NumOutlets = c\n\trdr.Interval = i\n\trdr.Store = st\n\treturn rdr\n}\n\nfunc (r *BucketReader) Start(out chan *bucket.Bucket) {\n\tr.Outbox = out\n\tgo r.scan()\n\tfor i := 0; i < r.NumOutlets; i++ {\n\t\tgo r.outlet()\n\t}\n}\n\nfunc (r *BucketReader) scan() {\n\tfor t := range time.Tick(r.Interval) {\n\t\tbuckets, err := r.Store.Scan(t)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"at=bucket.scan error=%s\\n\", err)\n\t\t\tcontinue\n\t\t}\n\t\tfor bucket := range buckets {\n\t\t\tr.Inbox <- bucket\n\t\t}\n\t}\n}\n\n\n\nfunc (r *BucketReader) outlet() ", "output": "{\n\tfor b := range r.Inbox {\n\t\tr.Store.Get(b)\n\t\tr.Outbox <- b\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/mattimo/fluxtftp\"\n\t\"io\"\n\t\"net\"\n)\n\ntype FluxClient struct {\n\tConn net.Conn\n}\n\nfunc NewFluxClient(dial string) (*FluxClient, error) {\n\tf := &FluxClient{}\n\n\taddr, err := net.ResolveUnixAddr(\"unix\", dial)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn, err := net.DialUnix(\"unix\", nil, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf.Conn = conn\n\n\treturn f, nil\n}\n\nfunc (f *FluxClient) Add(reader io.Reader) error {\n\n\tbuf := &bytes.Buffer{}\n\tbuf.ReadFrom(reader)\n\n\tmessage, err := json.Marshal(&fluxtftp.ControlRequest{\n\t\tVerb: \"Upload\",\n\t\tData: buf.Bytes(),\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = f.Conn.Write(message)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tanswer := &fluxtftp.ControlResponse{}\n\tdec := json.NewDecoder(f.Conn)\n\terr = dec.Decode(answer)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif answer.Error != 0 {\n\t\treturn fmt.Errorf(\"Server Error: %s\", answer.Message)\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (f *FluxClient) Close() error ", "output": "{\n\treturn f.Conn.Close()\n}"} {"input": "package logrus\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\nvar loggerFields = Fields{\n\t\"foo\": \"bar\",\n\t\"baz\": \"qux\",\n\t\"one\": \"two\",\n\t\"three\": \"four\",\n}\n\nfunc BenchmarkDummyLogger(b *testing.B) {\n\tnullf, err := os.OpenFile(\"/dev/null\", os.O_WRONLY, 0666)\n\tif err != nil {\n\t\tb.Fatalf(\"%v\", err)\n\t}\n\tdefer nullf.Close()\n\tdoLoggerBenchmark(b, nullf, &TextFormatter{DisableColors: true}, smallFields)\n}\n\n\n\nfunc doLoggerBenchmark(b *testing.B, out *os.File, formatter Formatter, fields Fields) {\n\tlogger := Logger{\n\t\tOut: out,\n\t\tLevel: InfoLevel,\n\t\tFormatter: formatter,\n\t}\n\tentry := logger.WithFields(fields)\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tentry.Info(\"aaa\")\n\t\t}\n\t})\n}\n\nfunc doLoggerBenchmarkNoLock(b *testing.B, out *os.File, formatter Formatter, fields Fields) {\n\tlogger := Logger{\n\t\tOut: out,\n\t\tLevel: InfoLevel,\n\t\tFormatter: formatter,\n\t}\n\tlogger.SetNoLock()\n\tentry := logger.WithFields(fields)\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tentry.Info(\"aaa\")\n\t\t}\n\t})\n}\n\nfunc BenchmarkDummyLoggerNoLock(b *testing.B) ", "output": "{\n\tnullf, err := os.OpenFile(\"/dev/null\", os.O_WRONLY|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tb.Fatalf(\"%v\", err)\n\t}\n\tdefer nullf.Close()\n\tdoLoggerBenchmarkNoLock(b, nullf, &TextFormatter{DisableColors: true}, smallFields)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\nfunc init() {\n\td1 := &D1{}\n\tchallenges[1] = &challenge{\"Day 01\", \"input/day01.txt\", d1}\n}\n\n\nfunc MFR(mass int) int {\n\treturn (mass / 3) - 2\n}\n\ntype D1 struct {\n\tmodules []int\n}\n\n\n\nfunc (d1 *D1) part1() (string, error) {\n\tsum := 0\n\tfor _, module := range d1.modules {\n\t\tsum += MFR(module)\n\t}\n\treturn fmt.Sprintf(\"Sum of fuel requirements is %d\", sum), nil\n}\n\nfunc TotalMFR(mass int) int {\n\treq := MFR(mass)\n\tif req > 0 {\n\t\treq += TotalMFR(req)\n\t} else {\n\t\treq = 0\n\t}\n\treturn req\n}\n\nfunc (d1 *D1) part2() (string, error) {\n\tsum := 0\n\tfor _, module := range d1.modules {\n\t\tsum += TotalMFR(module)\n\t}\n\treturn fmt.Sprintf(\"Sum of fuel requirements is %d\", sum), nil\n}\n\nfunc (d1 *D1) parse(line string) error ", "output": "{\n\tv, err := strconv.Atoi(line)\n\tif err == nil {\n\t\td1.modules = append(d1.modules, v)\n\t}\n\treturn err\n}"} {"input": "package jsonapi\n\nimport \"fmt\"\n\ntype Cache interface {\n\tAdd(ResourceObject) (bool, ResourceObject)\n}\n\ntype coreCache struct {\n\tstore map[string]ResourceObject\n}\n\nfunc NewCache() Cache {\n\treturn &coreCache{\n\t\tstore: make(map[string]ResourceObject),\n\t}\n}\n\n\n\nfunc (cache *coreCache) Add(n ResourceObject) (bool, ResourceObject) ", "output": "{\n\tkey := fmt.Sprintf(\"%s=>%s\", n.GetType(), n.GetID())\n\tif existing, ok := cache.store[key]; ok {\n\t\treturn false, existing\n\t}\n\tcache.store[key] = n\n\treturn true, n\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestGetName(t *testing.T) ", "output": "{\n\tname, err := getName(true)\n\tif name == \"\" || err != nil {\n\t\tt.Errorf(\"Error retrieving name: %s\", err.Error())\n\t}\n\tif !strings.Contains(name, \"-\") {\n\t\tt.Errorf(\"Name should contain a uuid: %s\", name)\n\t}\n\tif strings.Contains(name, \"/\") {\n\t\tt.Errorf(\"Name should not contain a /: %s\", name)\n\t}\n\n\tuid = false\n\tname, err = getName(false)\n\tif name == \"\" || err != nil {\n\t\tt.Errorf(\"Error retrieving name: %s\", err.Error())\n\t}\n\tif strings.Contains(name, \"-\") {\n\t\tt.Errorf(\"Name should not contain a uuid: %s\", name)\n\t}\n}"} {"input": "package auth\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n\n\t\"github.com/dgrijalva/jwt-go\"\n\t\"github.com/generationtux/brizo/database\"\n\t\"github.com/generationtux/brizo/resources\"\n)\n\n\n\n\n\n\nfunc ValidatePersonalAccessToken(token string) bool {\n\tdb, err := database.Connect()\n\tdefer db.Close()\n\tif err != nil {\n\t\tlog.Printf(\"Database error: '%s'\\n\", err)\n\t\treturn false\n\t}\n\tif resources.HasAccessToken(db, token) {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\n\nfunc validateAuthHeader(header string) bool {\n\tdata := []byte(header)\n\tmatched, _ := regexp.Match(\"^Bearer .*\", data)\n\n\treturn matched\n}\n\n\nfunc ValidateJWTToken(token string) bool {\n\tt, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {\n\t\tif _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", t.Header[\"alg\"])\n\t\t}\n\t\treturn []byte(jwtSecret()), nil\n\t})\n\n\tif err != nil {\n\t\tlog.Println(err.Error()+\":\", token)\n\t\treturn false\n\t}\n\n\treturn t.Valid\n}\n\n\nfunc jwtSecret() string {\n\treturn os.Getenv(\"JWT_SECRET\")\n}\n\n\n\nfunc extractBearerTokenFromHeader(header string) string {\n\treturn header[7:]\n}\n\nfunc APIMiddleware(rw http.ResponseWriter, request *http.Request, next http.HandlerFunc) ", "output": "{\n\tauthHeader := request.Header.Get(\"Authorization\")\n\tif authHeader == \"\" {\n\t\trw.WriteHeader(401)\n\t\trw.Write([]byte(\"not authorized\"))\n\t\treturn\n\t}\n\n\tif !validateAuthHeader(authHeader) {\n\t\tlog.Println(\"Authorization header is invalid:\", authHeader)\n\t\trw.WriteHeader(401)\n\t\trw.Write([]byte(\"invalid authorization header\"))\n\t\treturn\n\t}\n\n\tjwtToken := extractBearerTokenFromHeader(authHeader)\n\tif ValidateJWTToken(jwtToken) || ValidatePersonalAccessToken(jwtToken) {\n\t\tnext(rw, request)\n\t\treturn\n\t}\n\n\trw.WriteHeader(401)\n\trw.Write([]byte(\"not authorized\"))\n}"} {"input": "package events\n\nimport (\n\t\"fmt\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/klog\"\n)\n\ntype LoggingEventRecorder struct {\n\tcomponent string\n}\n\n\nfunc NewLoggingEventRecorder(component string) Recorder {\n\treturn &LoggingEventRecorder{component: component}\n}\n\nfunc (r *LoggingEventRecorder) ComponentName() string {\n\treturn r.component\n}\n\nfunc (r *LoggingEventRecorder) ForComponent(component string) Recorder {\n\tnewRecorder := *r\n\tnewRecorder.component = component\n\treturn &newRecorder\n}\n\n\n\nfunc (r *LoggingEventRecorder) Event(reason, message string) {\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeNormal, reason, message)\n\tklog.Info(event.String())\n}\n\nfunc (r *LoggingEventRecorder) Eventf(reason, messageFmt string, args ...interface{}) {\n\tr.Event(reason, fmt.Sprintf(messageFmt, args...))\n}\n\nfunc (r *LoggingEventRecorder) Warning(reason, message string) {\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeWarning, reason, message)\n\tklog.Warning(event.String())\n}\n\nfunc (r *LoggingEventRecorder) Warningf(reason, messageFmt string, args ...interface{}) {\n\tr.Warning(reason, fmt.Sprintf(messageFmt, args...))\n}\n\nfunc (r *LoggingEventRecorder) WithComponentSuffix(suffix string) Recorder ", "output": "{\n\treturn r.ForComponent(fmt.Sprintf(\"%s-%s\", r.ComponentName(), suffix))\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/docker/docker/api/types/filters\"\n)\n\n\n\nfunc printImages(images []types.ImageSummary) {\n\tsuseImages := make([]types.ImageSummary, 0, len(images))\n\tcache := getCacheFile()\n\tcounter := 0\n\n\tfor _, img := range images {\n\t\tselect {\n\t\tcase <-killChannel:\n\t\t\treturn\n\t\tdefault:\n\t\t\tfmt.Printf(\"Inspecting image %d/%d\\r\", (counter + 1), len(images))\n\t\t\tif cache.isSUSE(img.ID) {\n\t\t\t\tsuseImages = append(suseImages, img)\n\t\t\t}\n\t\t}\n\t\tcounter++\n\t}\n\tformatAndPrint(suseImages)\n\tcache.flush()\n}\n\n\n\n\n\n\nfunc checkImageExists(repo, tag string) (bool, error) {\n\tclient := getDockerClient()\n\n\timages, err := client.ImageList(context.Background(), types.ImageListOptions{\n\t\tAll: false,\n\t\tFilters: filters.NewArgs(filters.Arg(\"reference\", repo)),\n\t})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(images) == 0 {\n\t\treturn false, nil\n\t}\n\n\tref := fmt.Sprintf(\"%s:%s\", repo, tag)\n\tfor _, image := range images {\n\t\tfor _, t := range image.RepoTags {\n\t\t\tif ref == t {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn false, nil\n}\n\nfunc imagesCmd(ctx *cli.Context) ", "output": "{\n\tclient := getDockerClient()\n\n\tif ctx.GlobalBool(\"force\") {\n\t\tcd := getCacheFile()\n\t\tcd.reset()\n\t}\n\n\tif imgs, err := client.ImageList(context.Background(), types.ImageListOptions{}); err != nil {\n\t\tlogAndFatalf(\"Cannot proceed safely: %v.\", err)\n\t} else {\n\t\tprintImages(imgs)\n\t\texitWithCode(0)\n\t}\n}"} {"input": "package mastodon\n\nimport (\n\t\"context\"\n\t\"net/http\"\n)\n\n\ntype Instance struct {\n\tURI string `json:\"uri\"`\n\tTitle string `json:\"title\"`\n\tDescription string `json:\"description\"`\n\tEMail string `json:\"email\"`\n\tVersion string `json:\"version,omitempty\"`\n\tURLs map[string]string `json:\"urls,omitempty\"`\n\tStats *InstanceStats `json:\"stats,omitempty\"`\n\tThumbnail string `json:\"thumbnail,omitempty\"`\n}\n\n\ntype InstanceStats struct {\n\tUserCount int64 `json:\"user_count\"`\n\tStatusCount int64 `json:\"status_count\"`\n\tDomainCount int64 `json:\"domain_count\"`\n}\n\n\nfunc (c *Client) GetInstance(ctx context.Context) (*Instance, error) {\n\tvar instance Instance\n\terr := c.doAPI(ctx, http.MethodGet, \"/api/v1/instance\", nil, &instance, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &instance, nil\n}\n\n\ntype WeeklyActivity struct {\n\tWeek Unixtime `json:\"week\"`\n\tStatuses int64 `json:\"statuses,string\"`\n\tLogins int64 `json:\"logins,string\"`\n\tRegistrations int64 `json:\"registrations,string\"`\n}\n\n\n\n\n\nfunc (c *Client) GetInstancePeers(ctx context.Context) ([]string, error) {\n\tvar peers []string\n\terr := c.doAPI(ctx, http.MethodGet, \"/api/v1/instance/peers\", nil, &peers, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn peers, nil\n}\n\nfunc (c *Client) GetInstanceActivity(ctx context.Context) ([]*WeeklyActivity, error) ", "output": "{\n\tvar activity []*WeeklyActivity\n\terr := c.doAPI(ctx, http.MethodGet, \"/api/v1/instance/activity\", nil, &activity, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn activity, nil\n}"} {"input": "package core\n\nimport (\n\t\"os\";\n\t\"container/list\";\n\t\"net\";\n\t\"log\";\n\t\"irc\";\n\t\"runloop\";\n)\n\ntype Network struct {\n\tname\t\tstring;\n\tserver\t\t*server;\n\tclients\t\t*list.List;\n\tlisten\t\t*listenConn;\n}\n\nfunc newNetwork(name string, serverConn net.Conn, listen net.Listener) *Network {\n\tvar network *Network;\n\n\taccept := func(conn net.Conn) {\n\t\trunloop.CallLater(func() {\n\t\t\tnetwork.addClient(conn)\n\t\t})\n\t};\n\n\terror := func(err os.Error) {\n\t};\n\n\tl := newListenConn(listen, accept, error);\n\tnetwork = &Network{name: name, clients: list.New(), listen: l};\n\tnetwork.server = newServer(serverConn, network);\n\treturn network;\n}\n\nfunc (network *Network) addClient(conn net.Conn) {\n\tclient := newClient(conn, network);\n\tnetwork.clients.PushBack(client);\n\tlog.Stderrf(\"client connected from %s\\n\", conn.RemoteAddr());\n}\n\n\n\nfunc (network *Network) SendToServer(msg *irc.Message) {\n\tif network.server != nil {\n\t\tnetwork.server.Send(msg)\n\t}\n}\n\n\nfunc (network *Network) SendToClients(msg *irc.Message) {\n\tfor c := range network.clients.Iter() {\n\t\tc.(*client).Send(msg)\n\t}\n}\n\n\n\n\nvar networks = make(map[string] *Network);\n\nfunc AddNetwork(name string, server net.Conn, listen net.Listener) *Network {\n\tnetwork := newNetwork(name, server, listen);\n\tnetworks[name] = network;\n\treturn network;\n}\n\nfunc (network *Network) SendNoticeToClient(conn Conn, line string) ", "output": "{\n\tnick := \"bouncin\"; \n\tconn.Send(&irc.Message{Command: \"NOTICE\", Params: []string{nick, line}});\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\n\n\n\n\ntype NamedPorts []*Port\n\n\n\n\nfunc (m NamedPorts) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tfor i := 0; i < len(m); i++ {\n\t\tif swag.IsZero(m[i]) { \n\t\t\tcontinue\n\t\t}\n\n\t\tif m[i] != nil {\n\t\t\tif err := m[i].Validate(formats); err != nil {\n\t\t\t\tif ve, ok := err.(*errors.Validation); ok {\n\t\t\t\t\treturn ve.ValidateName(strconv.Itoa(i))\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package quickfix\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc sessionIDFilenamePrefix(s SessionID) string {\n\tsender := []string{s.SenderCompID}\n\tif s.SenderSubID != \"\" {\n\t\tsender = append(sender, s.SenderSubID)\n\t}\n\tif s.SenderLocationID != \"\" {\n\t\tsender = append(sender, s.SenderLocationID)\n\t}\n\n\ttarget := []string{s.TargetCompID}\n\tif s.TargetSubID != \"\" {\n\t\ttarget = append(target, s.TargetSubID)\n\t}\n\tif s.TargetLocationID != \"\" {\n\t\ttarget = append(target, s.TargetLocationID)\n\t}\n\n\tfname := []string{s.BeginString, strings.Join(sender, \"_\"), strings.Join(target, \"_\")}\n\tif s.Qualifier != \"\" {\n\t\tfname = append(fname, s.Qualifier)\n\t}\n\treturn strings.Join(fname, \"-\")\n}\n\n\n\n\n\nfunc removeFile(fname string) error {\n\terr := os.Remove(fname)\n\tif (err != nil) && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\nfunc openOrCreateFile(fname string, perm os.FileMode) (f *os.File, err error) {\n\tif f, err = os.OpenFile(fname, os.O_RDWR, perm); err != nil {\n\t\tif f, err = os.OpenFile(fname, os.O_RDWR|os.O_CREATE, perm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error opening or creating file: %s: %s\", fname, err.Error())\n\t\t}\n\t}\n\treturn f, nil\n}\n\nfunc closeFile(f *os.File) error ", "output": "{\n\tif f != nil {\n\t\tif err := f.Close(); err != nil {\n\t\t\tif !os.IsNotExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n)\n\nfunc LoadManifest(path string) (manifest map[string]interface{}, err error) {\n\tcontent, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn manifest, err\n\t}\n\n\terr = json.Unmarshal(content, &manifest)\n\tif err != nil {\n\t\treturn manifest, err\n\t}\n\n\treturn manifest, nil\n}\n\nfunc StoreManifest(path string, manifest map[string]interface{}) (err error) {\n\tcontent, err := json.MarshalIndent(manifest, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(path, content, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc ManifestValidateType(value interface{}) error {\n\tswitch value.(type) {\n\tcase string:\n\t\tbreak\n\tdefault:\n\t\treturn errors.New(\"Invalid type for \\\"type\\\"\")\n\t}\n\n\tlegal := []string{\"zone-dataset\", \"lx-dataset\", \"zvol\", \"other\"}\n\tif !stringInSlice(value.(string), legal) {\n\t\treturn errors.New(fmt.Sprintf(\"Invalid value specified for \\\"type\\\": \\\"%v\\\"\", value))\n\t}\n\n\treturn nil\n}\n\nfunc ManifestValidateOs(value interface{}) error {\n\tswitch value.(type) {\n\tcase string:\n\t\tbreak\n\tdefault:\n\t\treturn errors.New(\"Invalid type for \\\"os\\\"\")\n\t}\n\n\tlegal := []string{\"smartos\", \"windows\", \"linux\", \"bsd\"}\n\tif !stringInSlice(value.(string), legal) {\n\t\treturn errors.New(fmt.Sprintf(\"Invalid value specified for \\\"os\\\": \\\"%v\\\"\", value))\n\t}\n\n\treturn nil\n}\n\n\n\nfunc ManifestValidateCompression(value interface{}) error ", "output": "{\n\tswitch value.(type) {\n\tcase string:\n\t\tbreak\n\tdefault:\n\t\treturn errors.New(\"Invalid type for \\\"compression\\\"\")\n\t}\n\n\tlegal := []string{\"bzip2\", \"gzip\", \"none\"}\n\tif !stringInSlice(value.(string), legal) {\n\t\treturn errors.New(fmt.Sprintf(\"Invalid value specified for \\\"compression\\\": \\\"%v\\\"\", value))\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\tyaml \"gopkg.in/yaml.v2\"\n)\n\n\n\n\n\nfunc Respond(res http.ResponseWriter, req *http.Request, code int, data interface{}) ", "output": "{\n\tvar err error\n\tvar errMesg []byte\n\tvar out []byte\n\n\tf := \"json\"\n\tformat := req.URL.Query()[\"f\"]\n\tif len(format) > 0 {\n\t\tf = format[0]\n\t}\n\n\tif f == \"yaml\" {\n\t\tres.Header().Set(\"Content-Type\", \"text/yaml; charset=utf-8\")\n\t\tout, err = yaml.Marshal(data)\n\t\terrMesg = []byte(\"--- error: failed while rendering data to yaml\")\n\t} else {\n\t\tres.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\t\tout, err = json.Marshal(data)\n\t\terrMesg = []byte(\"{ 'error': 'failed while rendering data to json' }\")\n\t}\n\n\tif err != nil {\n\t\tout = errMesg\n\t\tcode = http.StatusInternalServerError\n\t}\n\tres.WriteHeader(code)\n\tres.Write(out)\n}"} {"input": "package error\n\nimport (\n\t\"strconv\"\n)\n\n\n\ntype StructuralError string\n\nfunc (s StructuralError) String() string {\n\treturn \"OpenPGP data invalid: \" + string(s)\n}\n\n\n\ntype UnsupportedError string\n\nfunc (s UnsupportedError) String() string {\n\treturn \"OpenPGP feature unsupported: \" + string(s)\n}\n\n\n\ntype InvalidArgumentError string\n\nfunc (i InvalidArgumentError) String() string {\n\treturn \"OpenPGP argument invalid: \" + string(i)\n}\n\n\n\ntype SignatureError string\n\nfunc (b SignatureError) String() string {\n\treturn \"OpenPGP signature invalid: \" + string(b)\n}\n\ntype keyIncorrect int\n\nfunc (ki keyIncorrect) String() string {\n\treturn \"the given key was incorrect\"\n}\n\nvar KeyIncorrectError = keyIncorrect(0)\n\ntype unknownIssuer int\n\n\n\nvar UnknownIssuerError = unknownIssuer(0)\n\ntype UnknownPacketTypeError uint8\n\nfunc (upte UnknownPacketTypeError) String() string {\n\treturn \"unknown OpenPGP packet type: \" + strconv.Itoa(int(upte))\n}\n\nfunc (unknownIssuer) String() string ", "output": "{\n\treturn \"signature make by unknown entity\"\n}"} {"input": "package docker\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/docker/docker/client\"\n\t\"github.com/geniusrabbit/registry/observer\"\n\t\"github.com/geniusrabbit/registry/service\"\n)\n\n\ntype ServiceContainerEventer interface {\n\tServiceEvent(event string, srv *service.Service)\n\tServiceError(err error)\n}\n\ntype serviceObserver struct {\n\thostIPAddr bool\n\teventer ServiceContainerEventer\n\tobserver *baseObserver\n}\n\n\nfunc NewService(eventer ServiceContainerEventer, host, version string, httpClient *http.Client, httpHeader map[string]string, registerHost bool) (observer.Observer, error) {\n\tvar (\n\t\tself = &serviceObserver{eventer: eventer, hostIPAddr: registerHost}\n\t\tobs, err = New(self, host, version, httpClient, httpHeader)\n\t)\n\tif err == nil {\n\t\tif obs, _ := obs.(*baseObserver); obs != nil {\n\t\t\tself.observer = obs\n\t\t\treturn self, nil\n\t\t}\n\t}\n\treturn nil, err\n}\n\n\nfunc (s *serviceObserver) Run() {\n\ts.observer.Run()\n}\n\n\nfunc (s *serviceObserver) Stop() {\n\ts.observer.Stop()\n}\n\n\nfunc (s *serviceObserver) Docker() *client.Client {\n\treturn s.observer.Docker()\n}\n\n\n\n\n\nfunc (s *serviceObserver) Error(err error) {\n\tif err != nil {\n\t\ts.eventer.ServiceError(err)\n\t}\n}\n\nfunc (s *serviceObserver) Event(containerID, action string) ", "output": "{\n\toptions, err := ServiceInfo(containerID, s.hostIPAddr, s.observer.docker)\n\tif err == nil {\n\t\tvar srv = options.Service()\n\t\tswitch action {\n\t\tcase \"start\", \"unpause\", \"refresh\":\n\t\t\tsrv.Status = service.StatusPassing\n\t\tcase \"stop\", \"pause\":\n\t\t\tsrv.Status = service.StatusWarning\n\t\tcase \"die\", \"kill\", \"oom\":\n\t\t\tsrv.Status = service.StatusCritical\n\t\t}\n\t\ts.eventer.ServiceEvent(action, srv)\n\t} else {\n\t\ts.Error(err)\n\t}\n}"} {"input": "package servicelabel\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/namsral/flag\"\n\n\t\"go.ligato.io/cn-infra/v2/infra\"\n\t\"go.ligato.io/cn-infra/v2/logging/logrus\"\n)\n\nvar microserviceLabelFlag string\n\nfunc init() {\n\tflag.StringVar(µserviceLabelFlag, \"microservice-label\", \"vpp1\", fmt.Sprintf(\"microservice label; also set via '%v' env variable.\", MicroserviceLabelEnvVar))\n}\n\n\ntype Plugin struct {\n\tinfra.PluginName\n\tMicroserviceLabel string\n}\n\n\nfunc (p *Plugin) Init() error {\n\tif p.MicroserviceLabel == \"\" {\n\t\tp.MicroserviceLabel = microserviceLabelFlag\n\t}\n\tlogrus.DefaultLogger().Debugf(\"Microservice label is set to %v\", p.MicroserviceLabel)\n\treturn nil\n}\n\n\nfunc (p *Plugin) Close() error {\n\treturn nil\n}\n\n\n\nfunc (p *Plugin) GetAgentLabel() string {\n\treturn p.MicroserviceLabel\n}\n\n\n\nfunc (p *Plugin) GetAgentPrefix() string {\n\treturn agentPrefix + p.MicroserviceLabel + \"/\"\n}\n\n\n\n\n\n\n\nfunc (p *Plugin) GetAllAgentsPrefix() string {\n\treturn GetAllAgentsPrefix()\n}\n\nfunc (p *Plugin) GetDifferentAgentPrefix(microserviceLabel string) string ", "output": "{\n\treturn GetDifferentAgentPrefix(microserviceLabel)\n}"} {"input": "package tore\n\nimport (\n\t\"github.com/pengfei-xue/tore/libs\"\n)\n\n\nfunc GetText(url string) (string, string) {\n\th := libs.Alg(url)\n\th.RunAlg()\n\treturn h.Title(), h.Text()\n}\n\n\n\nfunc SetAlg(name string) ", "output": "{\n\tlibs.SetAlg(name)\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\nconst (\n\tMaxFilterAddDataSize = 520\n)\n\n\n\n\n\n\ntype MsgFilterAdd struct {\n\tData []byte\n}\n\n\n\nfunc (msg *MsgFilterAdd) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filteradd message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterAdd.BtcDecode\", str)\n\t}\n\n\tvar err error\n\tmsg.Data, err = ReadVarBytes(r, pver, MaxFilterAddDataSize,\n\t\t\"filteradd data\")\n\treturn err\n}\n\n\n\nfunc (msg *MsgFilterAdd) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filteradd message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterAdd.BtcEncode\", str)\n\t}\n\n\tsize := len(msg.Data)\n\tif size > MaxFilterAddDataSize {\n\t\tstr := fmt.Sprintf(\"filteradd size too large for message \"+\n\t\t\t\"[size %v, max %v]\", size, MaxFilterAddDataSize)\n\t\treturn messageError(\"MsgFilterAdd.BtcEncode\", str)\n\t}\n\n\treturn WriteVarBytes(w, pver, msg.Data)\n}\n\n\n\n\n\n\n\nfunc (msg *MsgFilterAdd) MaxPayloadLength(pver uint32) uint32 {\n\treturn uint32(VarIntSerializeSize(MaxFilterAddDataSize)) +\n\t\tMaxFilterAddDataSize\n}\n\n\n\nfunc NewMsgFilterAdd(data []byte) *MsgFilterAdd {\n\treturn &MsgFilterAdd{\n\t\tData: data,\n\t}\n}\n\nfunc (msg *MsgFilterAdd) Command() string ", "output": "{\n\treturn CmdFilterAdd\n}"} {"input": "package msgraph\n\nimport \"context\"\n\n\ntype WorkbookFunctionsRriRequestBuilder struct{ BaseRequestBuilder }\n\n\n\n\n\ntype WorkbookFunctionsRriRequest struct{ BaseRequest }\n\n\nfunc (b *WorkbookFunctionsRriRequestBuilder) Request() *WorkbookFunctionsRriRequest {\n\treturn &WorkbookFunctionsRriRequest{\n\t\tBaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},\n\t}\n}\n\n\nfunc (r *WorkbookFunctionsRriRequest) Post(ctx context.Context) (resObj *WorkbookFunctionResult, err error) {\n\terr = r.JSONRequest(ctx, \"POST\", \"\", r.requestObject, &resObj)\n\treturn\n}\n\nfunc (b *WorkbookFunctionsRequestBuilder) Rri(reqObj *WorkbookFunctionsRriRequestParameter) *WorkbookFunctionsRriRequestBuilder ", "output": "{\n\tbb := &WorkbookFunctionsRriRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.BaseRequestBuilder.baseURL += \"/rri\"\n\tbb.BaseRequestBuilder.requestObject = reqObj\n\treturn bb\n}"} {"input": "package main\n\nimport (\n\t\"../../embedded\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\n\n\n\n\n\n\nfunc main() {\n\tfmt.Printf(\"self tests ...\")\n\tself_tests()\n\tfmt.Printf(\"done!\\n\")\n\n\tfmt.Printf(\"warnings ...\")\n\tself_warnings()\n\tfmt.Printf(\"done!\\n\")\n\n\tfmt.Printf(\"pre-init ...\")\n\tpre_init()\n\tsyscall.Setenv(\"TZ\", \"UTC\")\n\truntime.Booted = 1\n\tfmt.Printf(\"done!\\n\")\n\n\tfmt.Printf(\"user init ...\")\n\tuser_init()\n\tfmt.Printf(\"done!\\n\")\n\n\tfor {\n\t\tuser_loop()\n\t}\n\tpanic(\"user loop broke out\")\n}\n\n\nfunc self_tests() {\n\tfmt.Println(\"Hi from fmt\")\n\tchannel := make(chan string, 1)\n\tchannel <- \"channel test pass\"\n\tval := <-channel\n\tfmt.Println(val)\n\tgo func(resp chan string) {\n\t\tfmt.Println(\"print from inside goroutine\")\n\t\tresp <- \"send channel from inside a goroutine\"\n\t}(channel)\n\tval = <-channel\n\tfmt.Println(val)\n}\n\n\nfunc self_warnings() {\n}\n\n\nfunc pre_init() {\n\tembedded.GIC_init(false)\n\n\truntime.SetIRQcallback(irq)\n\n\truntime.Release(3)\n\n\truntime.Unmap_region(0x0, 0x0, 0x100000)\n}\n\nfunc Entry() ", "output": "{\n\truntime.Armhackmode = 1\n\truntime.Runtime_main()\n}"} {"input": "package highlight\n\nimport (\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com/gogits/gogs/modules/setting\"\n)\n\nvar (\n\tignoreFileNames = map[string]bool{\n\t\t\"license\": true,\n\t\t\"copying\": true,\n\t}\n\n\thighlightFileNames = map[string]bool{\n\t\t\"dockerfile\": true,\n\t\t\"makefile\": true,\n\t}\n\n\thighlightExts = map[string]bool{\n\t\t\".arm\": true,\n\t\t\".as\": true,\n\t\t\".sh\": true,\n\t\t\".cs\": true,\n\t\t\".cpp\": true,\n\t\t\".c\": true,\n\t\t\".css\": true,\n\t\t\".cmake\": true,\n\t\t\".bat\": true,\n\t\t\".dart\": true,\n\t\t\".patch\": true,\n\t\t\".elixir\": true,\n\t\t\".erlang\": true,\n\t\t\".go\": true,\n\t\t\".html\": true,\n\t\t\".xml\": true,\n\t\t\".hs\": true,\n\t\t\".ini\": true,\n\t\t\".json\": true,\n\t\t\".java\": true,\n\t\t\".js\": true,\n\t\t\".less\": true,\n\t\t\".lua\": true,\n\t\t\".php\": true,\n\t\t\".py\": true,\n\t\t\".rb\": true,\n\t\t\".scss\": true,\n\t\t\".sql\": true,\n\t\t\".scala\": true,\n\t\t\".swift\": true,\n\t\t\".ts\": true,\n\t\t\".vb\": true,\n\t}\n\n\thighlightMapping = map[string]string{}\n)\n\nfunc NewContext() {\n\tkeys := setting.Cfg.Section(\"highlight.mapping\").Keys()\n\tfor i := range keys {\n\t\thighlightMapping[keys[i].Name()] = keys[i].Value()\n\t}\n}\n\n\n\n\n\nfunc FileNameToHighlightClass(fname string) string ", "output": "{\n\tfname = strings.ToLower(fname)\n\tif ignoreFileNames[fname] {\n\t\treturn \"nohighlight\"\n\t}\n\n\tif highlightFileNames[fname] {\n\t\treturn fname\n\t}\n\n\text := path.Ext(fname)\n\tif highlightExts[ext] {\n\t\treturn ext[1:]\n\t}\n\n\tname, ok := highlightMapping[ext]\n\tif ok {\n\t\treturn name\n\t}\n\n\treturn \"\"\n}"} {"input": "package v1alpha1\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\tv1alpha1 \"k8s.io/ingress-gce/pkg/experimental/apis/workload/v1alpha1\"\n\t\"k8s.io/ingress-gce/pkg/experimental/workload/client/clientset/versioned/scheme\"\n)\n\ntype NetworkingV1alpha1Interface interface {\n\tRESTClient() rest.Interface\n\tWorkloadsGetter\n}\n\n\ntype NetworkingV1alpha1Client struct {\n\trestClient rest.Interface\n}\n\n\n\n\nfunc NewForConfig(c *rest.Config) (*NetworkingV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &NetworkingV1alpha1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *NetworkingV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *NetworkingV1alpha1Client {\n\treturn &NetworkingV1alpha1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *NetworkingV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc (c *NetworkingV1alpha1Client) Workloads(namespace string) WorkloadInterface ", "output": "{\n\treturn newWorkloads(c, namespace)\n}"} {"input": "package userd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/godbus/dbus\"\n\t\"github.com/godbus/dbus/introspect\"\n\t\"gopkg.in/tomb.v2\"\n\n\t\"github.com/snapcore/snapd/logger\"\n)\n\ntype dbusInterface interface {\n\tName() string\n\tBasePath() dbus.ObjectPath\n\tIntrospectionData() string\n}\n\ntype Userd struct {\n\ttomb tomb.Tomb\n\tconn *dbus.Conn\n\tdbusIfaces []dbusInterface\n}\n\nfunc (ud *Userd) Init() error {\n\tvar err error\n\n\tud.conn, err = dbus.SessionBus()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tud.dbusIfaces = []dbusInterface{\n\t\t&Launcher{ud.conn},\n\t\t&Settings{ud.conn},\n\t}\n\tfor _, iface := range ud.dbusIfaces {\n\t\treply, err := ud.conn.RequestName(iface.Name(), dbus.NameFlagDoNotQueue)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif reply != dbus.RequestNameReplyPrimaryOwner {\n\t\t\treturn fmt.Errorf(\"cannot obtain bus name '%s'\", iface.Name())\n\t\t}\n\n\t\txml := \"\" + iface.IntrospectionData() + introspect.IntrospectDataString + \"\"\n\t\tud.conn.Export(iface, iface.BasePath(), iface.Name())\n\t\tud.conn.Export(introspect.Introspectable(xml), iface.BasePath(), \"org.freedesktop.DBus.Introspectable\")\n\t}\n\treturn nil\n}\n\n\n\nfunc (ud *Userd) Stop() error {\n\tud.tomb.Kill(nil)\n\treturn ud.tomb.Wait()\n}\n\nfunc (ud *Userd) Dying() <-chan struct{} {\n\treturn ud.tomb.Dying()\n}\n\nfunc (ud *Userd) Start() ", "output": "{\n\tlogger.Noticef(\"Starting snap userd\")\n\n\tud.tomb.Go(func() error {\n\t\tselect {\n\t\tcase <-ud.tomb.Dying():\n\t\t\tud.conn.Close()\n\t\t}\n\t\terr := ud.tomb.Err()\n\t\tif err != nil && err != tomb.ErrStillAlive {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n}"} {"input": "package sqltrace\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\nfunc boolToInt64(f bool) int64 {\n\tif f {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\ntype sqlTrace struct {\n\ton int64 \n\n\t*log.Logger\n}\n\nfunc newSQLTrace() *sqlTrace {\n\treturn &sqlTrace{\n\t\tLogger: log.New(os.Stdout, \"hdb \", log.Ldate|log.Ltime|log.Lshortfile),\n\t}\n}\nfunc (t *sqlTrace) On() bool { return atomic.LoadInt64(&t.on) != 0 }\nfunc (t *sqlTrace) SetOn(on bool) { atomic.StoreInt64(&t.on, boolToInt64(on)) }\n\ntype flagValue struct {\n\tt *sqlTrace\n}\n\nfunc (v flagValue) IsBoolFlag() bool { return true }\n\nfunc (v flagValue) String() string {\n\tif v.t == nil {\n\t\treturn \"\"\n\t}\n\treturn strconv.FormatBool(v.t.On())\n}\n\nfunc (v flagValue) Set(s string) error {\n\tf, err := strconv.ParseBool(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.t.SetOn(f)\n\treturn nil\n}\n\nvar tracer = newSQLTrace()\n\nfunc init() {\n\tflag.Var(&flagValue{t: tracer}, \"hdb.sqlTrace\", \"enabling hdb sql trace\")\n}\n\n\nfunc On() bool { return tracer.On() }\n\n\nfunc SetOn(on bool) { tracer.SetOn(on) }\n\n\n\n\n\nfunc Tracef(format string, v ...interface{}) { tracer.Printf(format, v...) }\n\n\nfunc Traceln(v ...interface{}) { tracer.Println(v...) }\n\nfunc Trace(v ...interface{}) ", "output": "{ tracer.Print(v...) }"} {"input": "package dbtest\n\nimport (\n\t\"fmt\"\n\t\"github.com/muesli/cache2go\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar cachegoclient *cache2go.CacheTable\n\nfunc init() {\n\tcachegoclient = cache2go.Cache(\"mycache\")\n}\n\nfunc BenchmarkBSet(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tkey := fmt.Sprintf(\"key%v\", i)\n\t\tvalue := fmt.Sprintf(\"value%v\", i)\n\t\tcachegoclient.Add(key, 5*time.Minute, value)\n\t}\n}\n\n\n\nfunc BenchmarkBGet(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tkey := fmt.Sprintf(\"key%v\", i)\n\t\tcachegoclient.Value(key)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\n\t\"github.com/minio/mc/pkg/console\"\n\t. \"gopkg.in/check.v1\"\n)\n\n\n\nfunc (s *TestSuite) TestShareSuccess(c *C) {\n\tobjectURL := server.URL + \"/bucket/object1\"\n\n\terr := app.Run([]string{os.Args[0], \"share\", \"download\", objectURL})\n\tc.Assert(err, IsNil)\n\tc.Assert(console.IsExited, Equals, false)\n\n\tconsole.IsExited = false\n\n\terr = app.Run([]string{os.Args[0], \"share\", \"download\", objectURL, \"1h\"})\n\tc.Assert(err, IsNil)\n\tc.Assert(console.IsExited, Equals, false)\n\n\tconsole.IsExited = false\n}\n\nfunc (s *TestSuite) TestShareFailure(c *C) ", "output": "{\n\tobjectURL := server.URL + \"/bucket/object1\"\n\n\terr := app.Run([]string{os.Args[0], \"share\", \"download\", objectURL, \"1hr\"})\n\tc.Assert(err, IsNil)\n\tc.Assert(console.IsExited, Equals, true)\n\n\tconsole.IsExited = false\n\n\terr = app.Run([]string{os.Args[0], \"share\", \"download\", objectURL, \"169hr\"})\n\tc.Assert(err, IsNil)\n\tc.Assert(console.IsExited, Equals, true)\n\n\tconsole.IsExited = false\n\n\terr = app.Run([]string{os.Args[0], \"share\", \"download\", objectURL, \"0s\"})\n\tc.Assert(err, IsNil)\n\tc.Assert(console.IsExited, Equals, true)\n\n\tconsole.IsExited = false\n}"} {"input": "package raml\n\n\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc TestParsing(t *testing.T) {\n\n\tfileNames := []string{\"./samples/example.raml\",\n\t\t\"./samples/simple_example.raml\",\n\t\t\"./samples/other_example.raml\",\n\t\t\"./samples/congo/api.raml\",\n\t\t\"./samples/notes/api.raml\",\n\t\t\"./samples/github/github-api-v3.raml\",\n\t\t\"./samples/raml-tutorial-200/jukebox-api.raml\"}\n\n\tfor _, fileName := range fileNames {\n\n\t\tfmt.Printf(\"Attempting to parse RAML file: %s\\n\", fileName)\n\n\t\tapiDefinition, err := ParseFile(fileName)\n\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed parsing file %s:\\n %s\", fileName, err.Error())\n\t\t} else {\n\t\t\tfmt.Printf(\"Successfully parsed file %s!\\n\", fileName)\n\t\t}\n\n\t\tif apiDefinition.RAMLVersion != \"#%RAML 0.8\" {\n\t\t\tt.Fatalf(\"Detected erroneous RAML version: %s\",\n\t\t\t\tapiDefinition.RAMLVersion)\n\t\t}\n\n\t}\n}\n\nfunc TestFailedParsing(t *testing.T) ", "output": "{\n\n\tfileNames := []string{\"./samples/bad_raml.raml\"}\n\n\tfor _, fileName := range fileNames {\n\n\t\tfmt.Printf(\"Attempting to parse RAML file: %s\\n\", fileName)\n\n\t\t_, err := ParseFile(fileName)\n\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"Failed detecting bad RAML file %s\", fileName)\n\t\t} else {\n\t\t\tfmt.Printf(\"Detected bad RAML file %s:\\n%s\", fileName, err.Error())\n\t\t}\n\t}\n}"} {"input": "package iyzipay\n\ntype CreateApprovalRequest struct {\n\tLocale string `json:\"locale,omitempty\"`\n\tConversationId string `json:\"conversationId,omitempty\"`\n\tPaymentTransactionId string `json:\"paymentTransactionId,omitempty\"`\n}\n\n\n\nfunc (request CreateApprovalRequest) toPkiString() string ", "output": "{\n\n\tpkiBuilder := PkiBuilder{}\n\n\tpkiBuilder.append(\"locale\", request.Locale)\n\tpkiBuilder.append(\"conversationId\", request.ConversationId)\n\tpkiBuilder.append(\"paymentTransactionId\", request.PaymentTransactionId)\n\n\treturn pkiBuilder.getRequestString()\n}"} {"input": "package defaults\n\nimport \"time\"\n\n\n\ntype Configuration struct {\n\tConnectTimeout *time.Duration\n\n\tTLSNegotiationTimeout *time.Duration\n}\n\n\n\n\n\nfunc (c *Configuration) GetTLSNegotiationTimeout() (time.Duration, bool) {\n\tif c.TLSNegotiationTimeout == nil {\n\t\treturn 0, false\n\t}\n\treturn *c.TLSNegotiationTimeout, true\n}\n\nfunc (c *Configuration) GetConnectTimeout() (time.Duration, bool) ", "output": "{\n\tif c.ConnectTimeout == nil {\n\t\treturn 0, false\n\t}\n\treturn *c.ConnectTimeout, true\n}"} {"input": "package xy\n\n\n\nfunc (p Point) Extent(e Point) Rectangle ", "output": "{\n\treturn Rectangle{p, e}\n}"} {"input": "package dom\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\ntype Node interface {\n\tString() string\n\tParent() Node\n\tSetParent(node Node)\n\tChildren() []Node\n\tAddChild(child Node)\n\tClone() Node\n}\n\n\ntype Element struct {\n\ttext string\n\tparent Node\n\tchildren []Node\n}\n\n\nfunc NewElement(text string) *Element {\n\treturn &Element{\n\t\ttext: text,\n\t\tparent: nil,\n\t\tchildren: make([]Node, 0),\n\t}\n}\n\n\n\n\n\nfunc (e *Element) SetParent(node Node) {\n\te.parent = node\n}\n\n\nfunc (e *Element) Children() []Node {\n\treturn e.children\n}\n\n\nfunc (e *Element) AddChild(child Node) {\n\tcopy := child.Clone()\n\tcopy.SetParent(e)\n\te.children = append(e.children, copy)\n}\n\n\n\nfunc (e *Element) Clone() Node {\n\tcopy := &Element{\n\t\ttext: e.text,\n\t\tparent: nil,\n\t\tchildren: make([]Node, 0),\n\t}\n\tfor _, child := range e.children {\n\t\tcopy.AddChild(child)\n\t}\n\treturn copy\n}\n\n\nfunc (e *Element) String() string {\n\tbuffer := bytes.NewBufferString(e.text)\n\n\tfor _, c := range e.Children() {\n\t\ttext := c.String()\n\t\tfmt.Fprintf(buffer, \"\\n %s\", text)\n\t}\n\n\treturn buffer.String()\n}\n\nfunc (e *Element) Parent() Node ", "output": "{\n\treturn e.parent\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype Page struct {\n\tTitle string\n\tBody []byte\n}\n\nfunc (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}\n\nfunc loadPage(title string) (*Page, error) {\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\treturn &Page{Title: title, Body: body}, err\n}\n\n\n\n\n\nfunc defaultHandler(w http.ResponseWriter, r *http.Request) {\n\tdump, err := httputil.DumpRequest(r, true)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(string(dump))\n\n\tp, err := loadPage(\"TestPage\") \n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Fprintf(w, \"

%s

%s
\", p.Title, p.Body)\n}\n\n\nfunc main() {\n\tdir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tbody := \"This is a test page under: \" + dir\n\tp1 := &Page{Title: \"TestPage\", Body: []byte(body)}\n\tp1.save()\n\tp2, _ := loadPage(\"TestPage\")\n\tfmt.Println(string(p2.Body))\n\n\thttp.HandleFunc(\"/\", defaultHandler)\n\thttp.ListenAndServe(\":8081\", nil)\n}\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\ttitle := r.URL.Path[len(\"/view/\"):]\n\tp, _ := loadPage(title)\n\tfmt.Fprintf(w, \"

%s

%s
\", p.Title, p.Body)\n}"} {"input": "package op\n\nimport (\n\ttf \"github.com/tensorflow/tensorflow/tensorflow/go\"\n)\n\n\n\n\nfunc Const(scope *Scope, value interface{}) (output tf.Output) ", "output": "{\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tt, ok := value.(*tf.Tensor)\n\tif !ok {\n\t\tvar err error\n\t\tif t, err = tf.NewTensor(value); err != nil {\n\t\t\tscope.UpdateErr(\"Const\", err)\n\t\t\treturn\n\t\t}\n\t}\n\treturn scope.AddOperation(tf.OpSpec{\n\t\tType: \"Const\",\n\t\tAttrs: map[string]interface{}{\n\t\t\t\"dtype\": t.DataType(),\n\t\t\t\"value\": t,\n\t\t}}).Output(0)\n}"} {"input": "package convey\n\nimport (\n\t\"github.com/wallclockbuilder/convey/reporting\"\n)\n\ntype nilReporter struct{}\n\nfunc (self *nilReporter) BeginStory(story *reporting.StoryReport) {}\nfunc (self *nilReporter) Enter(scope *reporting.ScopeReport) {}\nfunc (self *nilReporter) Report(report *reporting.AssertionResult) {}\nfunc (self *nilReporter) Exit() {}\nfunc (self *nilReporter) EndStory() {}\n\nfunc newNilReporter() *nilReporter { return &nilReporter{} }\n\nfunc (self *nilReporter) Write(p []byte) (int, error) ", "output": "{ return len(p), nil }"} {"input": "package sample\n\n\nimport (\n\t\"time\"\n\t\"encoding/json\"\n)\n\ntype Datum struct {\n\tStatus string `json:\"status\"`\n\tTimestamp time.Time `json:\"timestamp\"`\n}\n\ntype Sample struct {\n\tKey string `json:\"key\"`\n\tTyp string `json:\"type\"`\n\tData Datum `json:\"data\"`\n}\n\n\n\nfunc (m *Sample) Json() string {\n\tresult, _ := json.Marshal(m)\n\treturn string(result)\n}\n\nfunc ConvertStatus(value int) string{\n\tswitch value {\n\tcase 1:\n\t\treturn \"ok\"\n\tdefault:\n\t\treturn \"error\"\n\n\t}\n}\n\nfunc Init() Sample ", "output": "{\n\tsample := Sample{\"sample\",\"testing\", Datum{\"ok\", time.Now()}}\n\treturn sample\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"reflect\"\n\n\t\"github.com/mkromkamp/BeaconD/sinks\"\n)\n\n\n\nfunc TestLogLineFromDTO(t *testing.T) {\n\tlogDTO := logDTO{\n\t\tTimestamp: time.Now().UTC().Format(time.RFC3339),\n\t\tData: make(map[string]string),\n\t}\n\n\texpectedLogLine := sinks.LogLine{\n\t\tTimestamp: logDTO.Timestamp,\n\t\tData: logDTO.Data,\n\t}\n\n\tactualLogLine := logDTO.NewLogLine()\n\n\tif !reflect.DeepEqual(expectedLogLine, actualLogLine) {\n\t\tt.Errorf(\"Expected LogLine: %v but got %v\", expectedLogLine, actualLogLine)\n\t}\n}\n\nfunc TestIsLogTags(t *testing.T) ", "output": "{\n\tfor _, tag := range logTags {\n\t\tif !isLogTag(tag) {\n\t\t\tt.Errorf(\"%s should be a tag\", tag)\n\t\t}\n\t}\n}"} {"input": "package lua\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestToBooleanOutOfRange(t *testing.T) {\n\tl := NewState()\n\tl.SetTop(0)\n\tl.PushBoolean(false)\n\tl.PushBoolean(true)\n\n\tfor i, want := range []bool{false, true, false, false} {\n\t\tidx := 1 + i\n\t\tif got := l.ToBoolean(idx); got != want {\n\t\t\tt.Errorf(\"l.ToBoolean(%d) = %t; want %t\", idx, got, want)\n\t\t}\n\t}\n}\n\nfunc TestPushFStringPointer(t *testing.T) ", "output": "{\n\tl := NewState()\n\tl.PushFString(\"%p %s\", l, \"test\")\n\n\texpected := fmt.Sprintf(\"%p %s\", l, \"test\")\n\tactual := CheckString(l, -1)\n\tif expected != actual {\n\t\tt.Errorf(\"PushFString, expected \\\"%s\\\" but found \\\"%s\\\"\", expected, actual)\n\t}\n}"} {"input": "package db\n\nimport (\n\t\"gopkg.in/mgo.v2\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Session struct {\n\tS *mgo.Session\n\tDb *mgo.Database\n\tC *mgo.Collection\n}\n\n\ntype MongoClient struct {\n\tHosts string\n\tDatabase string\n\tCollection string\n\tSession\n}\n\nfunc (m *MongoClient) Connect() error {\n\tdailinfo := &mgo.DialInfo{\n\t\tAddrs: strings.Split(m.Hosts, \",\"),\n\t\tTimeout: 5 * time.Second,\n\t\tDatabase: m.Database,\n\t}\n\tsession, err := mgo.DialWithInfo(dailinfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.S = session\n\tm.S.SetMode(mgo.Monotonic, true)\n\treturn nil\n}\n\nfunc (m *MongoClient) DB() {\n\tdb := m.Session.S.DB(m.Database)\n\tm.Session.Db = db\n}\n\nfunc (m *MongoClient) C() {\n\tc := m.Session.Db.C(m.Collection)\n\tm.Session.C = c\n}\n\nfunc (m *MongoClient) Close() {\n\tif m.S != nil {\n\t\tm.S.LogoutAll()\n\t\tm.S.Close()\n\t}\n}\n\n\n\nfunc (m *MongoClient) GetCollection() *mgo.Collection ", "output": "{\n\treturn m.Session.C\n}"} {"input": "package packr\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\nvar gil = &sync.Mutex{}\nvar data = map[string]map[string][]byte{}\n\n\n\n\n\nfunc PackJSONBytes(box string, name string, jbb string) error {\n\tbb := []byte{}\n\terr := json.Unmarshal([]byte(jbb), &bb)\n\tif err != nil {\n\t\treturn err\n\t}\n\tPackBytes(box, name, bb)\n\treturn nil\n}\n\nfunc PackBytes(box string, name string, bb []byte) ", "output": "{\n\tgil.Lock()\n\tdefer gil.Unlock()\n\tif _, ok := data[box]; !ok {\n\t\tdata[box] = map[string][]byte{}\n\t}\n\tdata[box][name] = bb\n}"} {"input": "package main\n\nimport \"sync\"\n\ntype mLocker struct {\n\tm map[string]*sync.Mutex\n\tmut sync.Mutex\n}\n\n\n\nfunc (l *mLocker) Lock(name string) {\n\tl.mut.Lock()\n\tmutex, ok := l.m[name]\n\tif !ok {\n\t\tmutex = new(sync.Mutex)\n\t\tl.m[name] = mutex\n\t}\n\tl.mut.Unlock()\n\tmutex.Lock()\n}\n\nfunc (l *mLocker) Unlock(name string) {\n\tl.mut.Lock()\n\tmutex := l.m[name]\n\tl.mut.Unlock()\n\tmutex.Unlock()\n}\n\nfunc multiLocker() *mLocker ", "output": "{\n\treturn &mLocker{m: make(map[string]*sync.Mutex)}\n}"} {"input": "package models\n\nimport (\n\t\"github.com/goadesign/goa\"\n\t\"github.com/gopheracademy/congo/app\"\n\t\"github.com/jinzhu/gorm\"\n\t\"golang.org/x/net/context\"\n\t\"time\"\n)\n\n\n\n\nfunc (m *EventDB) ListEvent(ctx context.Context, tenantID int) []*app.Event {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"event\", \"listevent\"}, time.Now())\n\n\tvar native []*Event\n\tvar objs []*app.Event\n\terr := m.Db.Scopes(EventFilterByTenant(tenantID, &m.Db)).Table(m.TableName()).Find(&native).Error\n\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"error listing Event\", \"error\", err.Error())\n\t\treturn objs\n\t}\n\n\tfor _, t := range native {\n\t\tobjs = append(objs, t.EventToEvent())\n\t}\n\n\treturn objs\n}\n\n\nfunc (m *Event) EventToEvent() *app.Event {\n\tevent := &app.Event{}\n\tevent.EndDate = m.EndDate\n\tevent.ID = &m.ID\n\tevent.Name = &m.Name\n\tfor _, k := range m.Presentations {\n\t\tevent.Presentations = append(event.Presentations, k.PresentationToPresentation())\n\t}\n\tfor _, k := range m.Speakers {\n\t\tevent.Speakers = append(event.Speakers, k.SpeakerToSpeaker())\n\t}\n\tevent.StartDate = m.StartDate\n\tevent.URL = m.URL\n\n\treturn event\n}\n\n\n\n\nfunc (m *EventDB) OneEvent(ctx context.Context, id int, tenantID int) (*app.Event, error) ", "output": "{\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"event\", \"oneevent\"}, time.Now())\n\n\tvar native Event\n\terr := m.Db.Scopes(EventFilterByTenant(tenantID, &m.Db)).Table(m.TableName()).Preload(\"Presentations\").Preload(\"Speakers\").Preload(\"Tenant\").Where(\"id = ?\", id).Find(&native).Error\n\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\tgoa.LogError(ctx, \"error getting Event\", \"error\", err.Error())\n\t\treturn nil, err\n\t}\n\n\tview := *native.EventToEvent()\n\treturn &view, err\n}"} {"input": "package tcp\n\nimport (\n\t\"net\"\n\t\"time\"\n\n\t\"github.com/pkg/errors\"\n)\n\ntype Sender struct {\n\tAddress string\n\tSendTimeout int\n\tconn net.Conn\n\terr error\n}\n\n\n\nfunc (s *Sender) Send(data []byte) (err error) {\n\tif s.conn == nil {\n\t\ts.err = nil\n\t\tif s.conn, err = net.DialTimeout(\"tcp\", s.Address, time.Duration(s.SendTimeout)*time.Millisecond); err != nil {\n\t\t\ts.err = errors.Wrap(err, \"creating TCP connection\")\n\t\t\treturn s.err\n\t\t}\n\t}\n\ts.conn.SetDeadline(time.Now().Add(time.Duration(s.SendTimeout) * time.Millisecond))\n\ts.write(data)\n\ts.write([]byte{0})\n\treturn s.err\n}\n\nfunc (s *Sender) write(data []byte) ", "output": "{\n\tif s.err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif s.err != nil && s.conn != nil {\n\t\t\ts.conn.Close()\n\t\t\ts.conn = nil\n\t\t}\n\t}()\n\tvar n int\n\tif n, s.err = s.conn.Write(data); s.err != nil {\n\t\ts.err = errors.Wrap(s.err, \"writing TCP\")\n\t\treturn\n\t}\n\tif n != len(data) {\n\t\ts.err = errors.New(\"short TCP write\")\n\t}\n}"} {"input": "package dns\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\n\n\ntype ExternalMaster struct {\n\n\tAddress *string `mandatory:\"true\" json:\"address\"`\n\n\tPort *int `mandatory:\"false\" json:\"port\"`\n\n\tTsig *Tsig `mandatory:\"false\" json:\"tsig\"`\n\n\tTsigKeyId *string `mandatory:\"false\" json:\"tsigKeyId\"`\n}\n\n\n\nfunc (m ExternalMaster) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package blocker\n\nimport \"sort\"\n\ntype sources []string\n\n\n\nfunc (s *sources) Remove(source string) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tn := sort.SearchStrings(*s, source)\n\n\tif n < len(*s) && (*s)[n] == source {\n\t\t*s = append((*s)[:n], (*s)[n+1:]...)\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (s *sources) Has(source string) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tn := sort.SearchStrings(*s, source)\n\n\tif n < len(*s) && (*s)[n] == source {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (s *sources) Len() int {\n\treturn len(*s)\n}\n\nfunc newSources(s ...string) *sources {\n\tret := sources(s)\n\treturn &ret\n}\n\nfunc (s *sources) Add(source string) ", "output": "{\n\tn := sort.SearchStrings(*s, source)\n\n\tif n < len(*s) && (*s)[n] == source {\n\t\treturn\n\t}\n\n\t*s = append(*s, \"\")\n\tcopy((*s)[n+1:], (*s)[n:])\n\t(*s)[n] = source\n}"} {"input": "package queue\n\nimport \"testing\"\n\nfunc TestQueue(t *testing.T) {\n\tq := New()\n\n\tif !q.IsEmpty() ||\n\t\tq.size != 0 ||\n\t\tq.Size() != 0 {\n\t\tt.Error()\n\t}\n\n\tq.EnQueue(0)\n\tq.EnQueue(1)\n\tq.EnQueue(2)\n\n\tif q.Size() != 3 {\n\t\tt.Error()\n\t}\n\n\te0 := q.DeQueue()\n\n\tif e0 != 0 || q.Size() != 2 {\n\t\tt.Error()\n\t}\n\n\te1 := q.DeQueue()\n\n\tif e1 != 1 {\n\t\tt.Error()\n\t}\n\n\te2 := q.DeQueue()\n\n\tif e2 != 2 || q.Size() != 0 {\n\t\tt.Error()\n\t}\n\n\tee := q.DeQueue()\n\n\tif ee != nil || q.Size() != 0 {\n\t\tt.Error()\n\t}\n}\n\n\n\nfunc TestQueueS(t *testing.T) ", "output": "{\n\tq := NewSQ()\n\n\tif !q.IsEmpty() ||\n\t\tq.size != 0 ||\n\t\tq.Size() != 0 {\n\t\tt.Error()\n\t}\n\n\tq.EnQueue(0)\n\tq.EnQueue(1)\n\tq.EnQueue(2)\n\n\tif q.Size() != 3 {\n\t\tt.Error()\n\t}\n\n\te0 := q.DeQueue()\n\n\tif e0 != 0 || q.Size() != 2 {\n\t\tt.Error()\n\t}\n\n\te1 := q.DeQueue()\n\n\tif e1 != 1 {\n\t\tt.Error()\n\t}\n\n\te2 := q.DeQueue()\n\n\tif e2 != 2 || q.Size() != 0 {\n\t\tt.Error()\n\t}\n\n\tee := q.DeQueue()\n\n\tif ee != nil || q.Size() != 0 {\n\t\tt.Error()\n\t}\n}"} {"input": "package main\n\ntype Human struct {\n\tname string\n\tage int\n\tphone string\n}\n\ntype Student struct {\n\tHuman\n\tschool string\n\tloan float32\n}\n\ntype Employee struct {\n\tHuman\n\tcompany string\n\tmoney float32\n}\n\n\ntype Men interface {\n\tSayHi()\n\tSing(lyrics string)\n\tGuzzle(beerStein string)\n}\n\ntype YoungChap interface {\n\tSayHi()\n\tSing(lyrics string)\n\tBorrowMoney(amount float32)\n}\n\ntype ElderlyGent interface {\n\tSayHi()\n\tSing(song string)\n\tSpendSalary(amount float32)\n}\n\nfunc (h *Human) SayHi() {\n\tfmt.Printf(\"Hi, I am %s you can call me on %s\\n\", h.name, h.phone)\n}\n\n\n\nfunc (h *Human) Guzzle(beerStein string) {\n\tfmt.Println(\"Guzzle Guzzle Guzzle...\", beerStein)\n}\n\n\nfunc (e *Employee) SayHi() {\n\tfmt.Printf(\"Hi, I am %s, I work at %s. Call me on %s\\n\", e.name, e.company, e.phone)\n}\n\nfunc (s *Student) BorrowMoney(amount float32) {\n\ts.loan += amount\n}\n\nfunc (e *Employee) SpendSalary(amount float32) {\n\te.money -= e.amount\n}\n\nfunc (h *Human) Sing(lyrics string) ", "output": "{\n\tfmt.Println(\"La la, la la la, la la la la...\", lyrics)\n}"} {"input": "package egoscale\n\nimport (\n\t\"encoding/json\"\n\t\"net/url\"\n)\n\n\n\nfunc (exo *Client) AsyncToVirtualMachine(resp QueryAsyncJobResultResponse) (*DeployVirtualMachineResponse, error) {\n\tvar r DeployVirtualMachineWrappedResponse\n\n\tif err := json.Unmarshal(resp.Jobresult, &r); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &r.Wrapped, nil\n}\n\nfunc (exo *Client) PollAsyncJob(jobid string) (*QueryAsyncJobResultResponse, error) ", "output": "{\n\tparams := url.Values{}\n\n\tparams.Set(\"jobid\", jobid)\n\n\tresp, err := exo.Request(\"queryAsyncJobResult\", params)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r QueryAsyncJobResultResponse\n\n\tif err := json.Unmarshal(resp, &r); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &r, nil\n}"} {"input": "package gospec\n\nimport (\n\t\"fmt\"\n\tfilepath \"path\"\n\t\"runtime\"\n)\n\ntype Location struct {\n\tname string\n\tfile string\n\tline int\n}\n\nfunc currentLocation() *Location {\n\treturn newLocation(1)\n}\n\nfunc callerLocation() *Location {\n\treturn newLocation(2)\n}\n\nfunc newLocation(n int) *Location {\n\tif pc, _, _, ok := runtime.Caller(n + 1); ok {\n\t\treturn locationForPC(pc)\n\t}\n\treturn nil\n}\n\nfunc locationForPC(pc uintptr) *Location {\n\tpc = pcOfWhereCallWasMade(pc)\n\tf := runtime.FuncForPC(pc)\n\tname := f.Name()\n\tfile, line := f.FileLine(pc)\n\treturn &Location{name, file, line}\n}\n\n\n\n\n\n\n\n\nfunc pcOfWhereCallWasMade(pcOfWhereCallReturnsTo uintptr) uintptr {\n\treturn pcOfWhereCallReturnsTo - 1\n}\n\nfunc (this *Location) Name() string { return this.name }\nfunc (this *Location) File() string { return this.file }\n\nfunc (this *Location) Line() int { return this.line }\n\nfunc filename(path string) string {\n\t_, file := filepath.Split(path)\n\treturn file\n}\n\nfunc (this *Location) equals(that *Location) bool {\n\treturn this.name == that.name &&\n\t\tthis.file == that.file &&\n\t\tthis.line == that.line\n}\n\nfunc (this *Location) String() string {\n\treturn fmt.Sprintf(\"%v:%v\", this.FileName(), this.Line())\n}\n\nfunc (this *Location) FileName() string ", "output": "{ return filename(this.file) }"} {"input": "package cmd\n\nimport \"github.com/spf13/cobra\"\n\n\n\n\nfunc createRootCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"langd\",\n\t\tShort: \"langd exercises a client/server configuration as a single binary\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmd.HelpFunc()(cmd, args)\n\t\t},\n\t}\n\n\treturn cmd\n}\n\nfunc InitializeCommands() *cobra.Command ", "output": "{\n\trootCmd := createRootCommand()\n\n\trootCmd.AddCommand(\n\t\tcreateLoadCommand(),\n\t\tcreateServeCommand(),\n\t\tcreateStartCommand(),\n\t\tcreateStopCommand(),\n\t)\n\n\treturn rootCmd\n}"} {"input": "package push\n\nimport \"fmt\"\n\ntype PushResult struct {\n\tProvider *PushServiceProvider\n\tDestination *DeliveryPoint\n\tContent *Notification\n\tMsgId string\n\tErr error\n}\n\n\n\nfunc (r *PushResult) Error() string {\n\tif !r.IsError() {\n\t\treturn fmt.Sprintf(\"PushServiceProvider=%v DeliveryPoint=%v MsgId=%v Succsess!\",\n\t\t\tr.Provider.Name(),\n\t\t\tr.Destination.Name(),\n\t\t\tr.MsgId)\n\t}\n\n\tret := fmt.Sprintf(\"Failed PushServiceProvider=%s DeliveryPoint=%s %v\",\n\t\tr.Provider.Name(),\n\t\tr.Destination.Name(),\n\t\tr.Err)\n\treturn ret\n}\n\ntype PushServiceType interface {\n\n\tBuildPushServiceProviderFromMap(map[string]string, *PushServiceProvider) error\n\n\tBuildDeliveryPointFromMap(map[string]string, *DeliveryPoint) error\n\tName() string\n\n\tPush(*PushServiceProvider, <-chan *DeliveryPoint, chan<- *PushResult, *Notification)\n\n\tSetErrorReportChan(errChan chan<- error)\n\n\tFinalize()\n}\n\nfunc (r *PushResult) IsError() bool ", "output": "{\n\tif r.Err == nil {\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package qutils\n\nimport \"regexp\"\n\n\n\nfunc GetParams(regEx *regexp.Regexp, str string) (paramsMap map[string]string) ", "output": "{\n\tmatch := regEx.FindStringSubmatch(str)\n\tparamsMap = make(map[string]string)\n\tfor i, name := range regEx.SubexpNames() {\n\t\tif i > 0 && i <= len(match) {\n\t\t\tparamsMap[name] = match[i]\n\t\t}\n\t}\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"labix.org/v2/mgo\"\n)\n\n\n\n\n\nfunc C(cfg *Config) *mgo.Collection {\n\treturn cfg.Mongo.session.DB(cfg.Mongo.Database).C(cfg.Mongo.Collection)\n}\n\nfunc DB(cfg *Config) *mgo.Database ", "output": "{\n\treturn cfg.Mongo.session.DB(cfg.Mongo.Database)\n}"} {"input": "package auto\n\nimport (\n\t\"sync\"\n\n\t\"github.com/miekg/coredns/middleware/file\"\n)\n\n\n\ntype Zones struct {\n\tZ map[string]*file.Zone \n\tnames []string \n\n\torigins []string \n\n\tsync.RWMutex\n}\n\n\nfunc (z *Zones) Names() []string {\n\tz.RLock()\n\tn := z.names\n\tz.RUnlock()\n\treturn n\n}\n\n\n\n\n\nfunc (z *Zones) Zones(name string) *file.Zone {\n\tz.RLock()\n\tzo := z.Z[name]\n\tz.RUnlock()\n\treturn zo\n}\n\n\n\nfunc (z *Zones) Add(zo *file.Zone, name string) {\n\tz.Lock()\n\n\tif z.Z == nil {\n\t\tz.Z = make(map[string]*file.Zone)\n\t}\n\n\tz.Z[name] = zo\n\tz.names = append(z.names, name)\n\tzo.Reload()\n\n\tz.Unlock()\n}\n\n\nfunc (z *Zones) Remove(name string) {\n\tz.Lock()\n\n\tif zo, ok := z.Z[name]; ok && !zo.NoReload {\n\t\tzo.ReloadShutdown <- true\n\t}\n\n\tdelete(z.Z, name)\n\n\tz.names = []string{}\n\tfor n := range z.Z {\n\t\tz.names = append(z.names, n)\n\t}\n\n\tz.Unlock()\n}\n\nfunc (z *Zones) Origins() []string ", "output": "{\n\treturn z.origins\n}"} {"input": "package handlers\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/byuoitav/device-monitoring/actions/gpio\"\n\t\"github.com/labstack/echo\"\n)\n\n\nfunc GetDividerState(ctx echo.Context) error {\n\tv := gpio.GetPins()\n\n\tresp := make(map[string][]string)\n\tfor i := range v {\n\t\tif v[i].Connected {\n\t\t\tresp[\"connected\"] = append(resp[\"connected\"], v[i].BlueberryPresets)\n\t\t} else {\n\t\t\tresp[\"disconnected\"] = append(resp[\"disconnected\"], v[i].BlueberryPresets)\n\t\t}\n\t}\n\n\treturn ctx.JSON(http.StatusOK, resp)\n}\n\n\n\n\nfunc PresetForHostname(ctx echo.Context) error ", "output": "{\n\thostname := ctx.Param(\"hostname\")\n\n\tv := gpio.GetPins()\n\n\tif len(v) == 0 || len(v) > 1 {\n\t\treturn ctx.String(http.StatusBadRequest, fmt.Sprintf(\"not supported in this room\"))\n\t}\n\n\treturn ctx.String(http.StatusOK, v[0].CurrentPreset(hostname))\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\tfmt.Println(maxProfit([]int{1, 9, 6, 9, 1, 7, 1, 1, 5, 9, 9, 9}))\n}\n\nfunc maxProfit(prices []int) int ", "output": "{\n\tif len(prices) <= 1 {\n\t\treturn 0\n\t}\n\n\tret := 0\n\tfor i := 0; i < len(prices)-1; i++ {\n\t\tif (i == 0 && prices[i] < prices[i+1]) || (i > 0 && prices[i] <= prices[i-1] && prices[i] < prices[i+1]) {\n\t\t\tlow := prices[i]\n\t\t\tfor i = i + 1; i < len(prices); i++ {\n\t\t\t\tif (i == len(prices)-1 && prices[i] >= prices[i-1]) || (i < len(prices)-1 && prices[i] >= prices[i-1] && prices[i] > prices[i+1]) {\n\t\t\t\t\tret += (prices[i] - low)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ret\n}"} {"input": "package common\n\nimport (\n\t\"bytes\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n)\n\n\ntype Endpoint struct {\n\tHost string `json:\"host\"`\n\n\tPorts []ServicePort `json:\"ports\"`\n}\n\n\nfunc GetExternalEndpoints(service *api.Service) []Endpoint {\n\tvar externalEndpoints []Endpoint\n\tif service.Spec.Type == api.ServiceTypeLoadBalancer {\n\t\tfor _, ingress := range service.Status.LoadBalancer.Ingress {\n\t\t\texternalEndpoints = append(externalEndpoints, getExternalEndpoint(ingress, service.Spec.Ports))\n\t\t}\n\t}\n\n\tfor _, ip := range service.Spec.ExternalIPs {\n\t\texternalEndpoints = append(externalEndpoints, Endpoint{\n\t\t\tHost: ip,\n\t\t\tPorts: GetServicePorts(service.Spec.Ports),\n\t\t})\n\t}\n\n\treturn externalEndpoints\n}\n\n\n\n\n\n\nfunc getExternalEndpoint(ingress api.LoadBalancerIngress, ports []api.ServicePort) Endpoint {\n\tvar host string\n\tif ingress.Hostname != \"\" {\n\t\thost = ingress.Hostname\n\t} else {\n\t\thost = ingress.IP\n\t}\n\treturn Endpoint{\n\t\tHost: host,\n\t\tPorts: GetServicePorts(ports),\n\t}\n}\n\n\nfunc GetNodeByName(nodes []api.Node, nodeName string) *api.Node {\n\tfor _, node := range nodes {\n\t\tif node.ObjectMeta.Name == nodeName {\n\t\t\treturn &node\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc GetInternalEndpoint(serviceName, namespace string, ports []api.ServicePort) Endpoint ", "output": "{\n\tname := serviceName\n\n\tif namespace != api.NamespaceDefault && len(namespace) > 0 && len(serviceName) > 0 {\n\t\tbufferName := bytes.NewBufferString(name)\n\t\tbufferName.WriteString(\".\")\n\t\tbufferName.WriteString(namespace)\n\t\tname = bufferName.String()\n\t}\n\n\treturn Endpoint{\n\t\tHost: name,\n\t\tPorts: GetServicePorts(ports),\n\t}\n}"} {"input": "package main\n\n\ntype seriesType int\n\nconst (\n\trouterRequest seriesType = iota\n\trouterEvent\n\tdynoMem\n\tdynoLoad\n\tdynoEvents\n\tnumSeries\n)\n\nvar (\n\tseriesColumns = [][]string{\n\t\t[]string{\"time\", \"status\", \"service\"}, \n\t\t[]string{\"time\", \"code\"}, \n\t\t[]string{\"time\", \"source\", \"memory_cache\", \"memory_pgpgin\", \"memory_pgpgout\", \"memory_rss\", \"memory_swap\", \"memory_total\", \"dynoType\"}, \n\t\t[]string{\"time\", \"source\", \"load_avg_1m\", \"load_avg_5m\", \"load_avg_15m\", \"dynoType\"}, \n\t\t[]string{\"time\", \"what\", \"type\", \"code\", \"message\", \"dynoType\"}, \n\t}\n\n\tseriesNames = []string{\"router\", \"events.router\", \"dyno.mem\", \"dyno.load\", \"events.dyno\"}\n)\n\nfunc (st seriesType) Name() string {\n\treturn seriesNames[st]\n}\n\n\n\n\ntype point struct {\n\tToken string\n\tType seriesType\n\tPoints []interface{}\n}\n\nfunc (p point) SeriesName() string {\n\treturn p.Type.Name() + \".\" + p.Token\n}\n\nfunc (st seriesType) Columns() []string ", "output": "{\n\treturn seriesColumns[st]\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\ntype SystemSettings struct {\n\tuserStreamAcl *StreamAcl\n\tsystemStreamAcl *StreamAcl\n}\n\nfunc NewSystemSettings(\n\tuserStreamAcl *StreamAcl,\n\tsystemStreamAcl *StreamAcl,\n) *SystemSettings {\n\treturn &SystemSettings{userStreamAcl, systemStreamAcl}\n}\n\n\n\nfunc (s *SystemSettings) SystemStreamAcl() *StreamAcl { return s.systemStreamAcl }\n\nfunc (s *SystemSettings) String() string {\n\treturn fmt.Sprintf(\"&{userStreamAcl:%+v systemStreamAcl:%+v}\", s.userStreamAcl, s.systemStreamAcl)\n}\n\ntype systemSettingsJson struct {\n\tUserStreamAcl *StreamAcl `json:\"$userStreamAcl,omitempty\"`\n\tSystemStreamAcl *StreamAcl `json:\"$systemStreamAcl,omitempty\"`\n}\n\nfunc (s *SystemSettings) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(systemSettingsJson{\n\t\tUserStreamAcl: s.userStreamAcl,\n\t\tSystemStreamAcl: s.systemStreamAcl,\n\t})\n}\n\nfunc (s *SystemSettings) UnmarshalJSON(data []byte) error {\n\tss := systemSettingsJson{}\n\tif err := json.Unmarshal(data, &ss); err != nil {\n\t\treturn err\n\t}\n\ts.userStreamAcl = ss.UserStreamAcl\n\ts.systemStreamAcl = ss.SystemStreamAcl\n\treturn nil\n}\n\nfunc SystemSettingsFromJsonBytes(data []byte) (*SystemSettings, error) {\n\tsystemSettings := &SystemSettings{}\n\treturn systemSettings, json.Unmarshal(data, systemSettings)\n}\n\nfunc (s *SystemSettings) UserStreamAcl() *StreamAcl ", "output": "{ return s.userStreamAcl }"} {"input": "package main\n\nimport (\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/cobra/doc\"\n\n\tcli \"github.com/lxc/lxd/shared/cmd\"\n\t\"github.com/lxc/lxd/shared/i18n\"\n)\n\ntype cmdManpage struct {\n\tglobal *cmdGlobal\n}\n\n\n\nfunc (c *cmdManpage) Run(cmd *cobra.Command, args []string) error {\n\texit, err := c.global.CheckArgs(cmd, args, 1, 1)\n\tif exit {\n\t\treturn err\n\t}\n\n\theader := &doc.GenManHeader{\n\t\tTitle: i18n.G(\"LXD - Command line client\"),\n\t\tSection: \"1\",\n\t}\n\n\topts := doc.GenManTreeOptions{\n\t\tHeader: header,\n\t\tPath: args[0],\n\t\tCommandSeparator: \".\",\n\t}\n\n\tdoc.GenManTreeFromOpts(c.global.cmd, opts)\n\n\treturn nil\n}\n\nfunc (c *cmdManpage) Command() *cobra.Command ", "output": "{\n\tcmd := &cobra.Command{}\n\tcmd.Use = i18n.G(\"manpage \")\n\tcmd.Short = i18n.G(\"Generate manpages for all commands\")\n\tcmd.Long = cli.FormatSection(i18n.G(\"Description\"), i18n.G(\n\t\t`Generate manpages for all commands`))\n\tcmd.Hidden = true\n\n\tcmd.RunE = c.Run\n\n\treturn cmd\n}"} {"input": "package encoder\n\nimport \"fmt\"\n\ntype Encoder interface {\n\tConfig(opt map[string]interface{}) (err error)\n\tEncode(src []byte) (out string, err error)\n\tDecode(src string) (out []byte, err error)\n}\n\n\n\nfunc NewEncoder(t string, opt map[string]interface{}) (e Encoder, err error) ", "output": "{\n\tswitch t {\n\tcase \"base32\":\n\t\te = NewBase32()\n\tcase \"eui64\":\n\t\te = NewEUI64()\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"No encoder with type %q found\", t)\n\t}\n\n\tif opt != nil {\n\t\terr = e.Config(opt)\n\t}\n\treturn\n}"} {"input": "package gamejam\n\ntype SceneID int\n\ntype Scene interface {\n\tAddComponent(c Component)\n\tLoad(r Resources) (err error)\n\tUnload(r Resources) (err error)\n\tRender()\n\tUpdate(mgr SceneManager)\n\tSetSceneID(id SceneID)\n\tSceneID() SceneID\n}\n\ntype BaseScene struct {\n\tcomponents map[ComponentID]Component\n\tid SceneID\n}\n\nfunc NewBaseScene() *BaseScene {\n\treturn &BaseScene{\n\t\tcomponents: map[ComponentID]Component{},\n\t}\n}\n\nfunc (s *BaseScene) AddComponent(c Component) {\n\tc.SetScene(s)\n\ts.components[c.GetID()] = c\n}\n\n\n\nfunc (s *BaseScene) Render() {\n}\n\nfunc (s *BaseScene) SetSceneID(id SceneID) {\n\ts.id = id\n}\n\nfunc (s *BaseScene) SceneID() SceneID {\n\treturn s.id\n}\n\nfunc (s *BaseScene) Unload(r Resources) (err error) {\n\tvar (\n\t\tid ComponentID\n\t\tc Component\n\t)\n\tfor id, c = range s.components {\n\t\ts.components[id] = nil\n\t\tc.Delete()\n\t}\n\treturn\n}\n\nfunc (s *BaseScene) Update(mgr SceneManager) {\n}\n\nfunc (s *BaseScene) Load(r Resources) (err error) ", "output": "{\n\treturn\n}"} {"input": "package iso20022\n\n\ntype DeliveryReturn4Choice struct {\n\n\tCode *DeliveryReturn1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification47 `xml:\"Prtry\"`\n}\n\n\n\nfunc (d *DeliveryReturn4Choice) AddProprietary() *GenericIdentification47 {\n\td.Proprietary = new(GenericIdentification47)\n\treturn d.Proprietary\n}\n\nfunc (d *DeliveryReturn4Choice) SetCode(value string) ", "output": "{\n\td.Code = (*DeliveryReturn1Code)(&value)\n}"} {"input": "package local\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/apache/beam/sdks/go/pkg/beam/io/textio\"\n)\n\nfunc init() {\n\ttextio.RegisterFileSystem(\"default\", New)\n}\n\ntype fs struct{}\n\n\nfunc New(ctx context.Context) textio.FileSystem {\n\treturn &fs{}\n}\n\nfunc (f *fs) Close() error {\n\treturn nil\n}\n\n\n\nfunc (f *fs) OpenRead(ctx context.Context, filename string) (io.ReadCloser, error) {\n\treturn os.Open(filename)\n}\n\nfunc (f *fs) OpenWrite(ctx context.Context, filename string) (io.WriteCloser, error) {\n\tif err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {\n\t\treturn nil, err\n\t}\n\treturn os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\n}\n\nfunc (f *fs) List(ctx context.Context, glob string) ([]string, error) ", "output": "{\n\treturn filepath.Glob(glob)\n}"} {"input": "package eventlistener\n\nimport (\n\t\"testing\"\n\t\"github.com/docker/docker/api/types\"\n\t\"golang.org/x/net/context\"\n\t\"fmt\"\n\t\"time\"\n\t\"github.com/docker/docker/api/types/events\"\n)\n\n\nfunc TestEventListener(t *testing.T) {\n\n\tconst labelToMonitor = \"tugbot-test\"\n\ttsk := make(chan string, 10)\n\n\tRegister(dockerClientMock{}, labelToMonitor, tsk)\n\tselect {\n\tcase res := <-tsk:\n\t\tfmt.Println(\"we recieved the die container id via the tasks chan: \", res)\n\tcase <-time.After(time.Second * 5):\n\t\tt.Error(\"we did not recieved the die container id on the tasks chan after 5 sec!\")\n\t}\n}\n\ntype dockerClientMock struct {}\n\nfunc (d dockerClientMock) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) {\n\teventsChan := make(chan events.Message, 10)\n\terrChan := make(chan error, 10)\n\tevent := events.Message{ Type: \"container\", Action: \"die\", }\n\teventsChan <- event\n\treturn eventsChan, errChan\n}\nfunc (d dockerClientMock) Info(ctx context.Context) (types.Info, error) {\n\tpanic(\"This function not suppose to be called\")\n}\n\n\nfunc (d dockerClientMock) DiskUsage(ctx context.Context) (types.DiskUsage, error) {\n\tpanic(\"This function not suppose to be called\")\n}\n\nfunc (d dockerClientMock) Ping(ctx context.Context) (bool, error) {\n\tpanic(\"This function not suppose to be called\")\n}\n\nfunc (d dockerClientMock) RegistryLogin(ctx context.Context, auth types.AuthConfig) (types.AuthResponse, error) ", "output": "{\n\tpanic(\"This function not suppose to be called\")\n}"} {"input": "package awsup\n\nimport (\n\t\"github.com/aws/aws-sdk-go/aws/request\"\n\t\"k8s.io/klog\"\n)\n\n\ntype RequestLogger struct {\n\tlogLevel klog.Level\n}\n\n\n\n\nfunc (l *RequestLogger) log(r *request.Request) {\n\tservice := r.ClientInfo.ServiceName\n\tname := \"?\"\n\tif r.Operation != nil {\n\t\tname = r.Operation.Name\n\t}\n\tmethodDescription := service + \"/\" + name\n\n\tklog.V(l.logLevel).Infof(\"AWS request: %s\", methodDescription)\n}\n\nfunc newRequestLogger(logLevel int) func(r *request.Request) ", "output": "{\n\trl := &RequestLogger{\n\t\tlogLevel: klog.Level(logLevel),\n\t}\n\treturn rl.log\n}"} {"input": "package v6\n\nimport (\n\t\"code.cloudfoundry.org/cli/command\"\n\t\"code.cloudfoundry.org/cli/command/flag\"\n\t\"code.cloudfoundry.org/cli/command/translatableerror\"\n)\n\ntype SetOrgRoleCommand struct {\n\tRequiredArgs flag.SetOrgRoleArgs `positional-args:\"yes\"`\n\tusage interface{} `usage:\"CF_NAME set-org-role USERNAME ORG ROLE\\n\\nROLES:\\n 'OrgManager' - Invite and manage users, select and change plans, and set spending limits\\n 'BillingManager' - Create and manage the billing account and payment info\\n 'OrgAuditor' - Read-only access to org info and reports\"`\n\trelatedCommands interface{} `related_commands:\"org-users, set-space-role\"`\n}\n\n\n\nfunc (SetOrgRoleCommand) Execute(args []string) error {\n\treturn translatableerror.UnrefactoredCommandError{}\n}\n\nfunc (SetOrgRoleCommand) Setup(config command.Config, ui command.UI) error ", "output": "{\n\treturn nil\n}"} {"input": "package youtube\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nconst (\n\tsubLang string = \"en\"\n)\n\ntype Settings struct {\n\tytExe string\n\tffmpegExe string\n\tdlPath string\n}\n\nfunc NewSettings(yt, ffmpeg, dl string) (Settings, error) {\n\tif _, err := os.Stat(yt); os.IsNotExist(err) {\n\t\treturn Settings{}, err\n\t}\n\n\tif _, err := os.Stat(ffmpeg); os.IsNotExist(err) {\n\t\treturn Settings{}, err\n\t}\n\n\tif _, err := os.Stat(dl); os.IsNotExist(err) {\n\t\terr = os.MkdirAll(dl, 0755)\n\t\tif err != nil {\n\t\t\treturn Settings{}, err\n\t\t}\n\t}\n\n\tout := Settings {\n\t\tyt,\n\t\tffmpeg,\n\t\tdl,\n\t}\n\treturn out, nil\n}\n\ntype Downloader struct {\n\tlink string\n\tuuid string\n\tsubs bool\n\tsettings Settings\n}\n\nfunc NewDownloader(link, uuid string, subs bool, settings Settings) *Downloader {\n\treturn &Downloader{\n\t\tlink,\n\t\tuuid,\n\t\tsubs,\n\t\tsettings,\n\t}\n}\n\n\nfunc (d *Downloader) Title() (string, error) {\n\targs := []string{\"--get-title\", \"--no-playlist\", d.link}\n\tdl := exec.Command(d.settings.ytExe, args...)\n\toutput, err := dl.Output()\n\ttitle := strings.TrimSpace(string(output))\n\treturn title, err\n}\n\n\n\n\nfunc (d *Downloader) Filepath() (string, error) ", "output": "{\n\toutputPath := d.settings.dlPath + \"/\" + d.uuid + `.%(ext)s`\n\n\targs := []string{\"-o\", outputPath, \"--no-playlist\", \"--ffmpeg-location\", d.settings.ffmpegExe}\n\n\tif d.subs {\n\t\targs = append(args, []string{\"--write-sub\", \"--sub-lang\", subLang, \"--embed-sub\"}...)\n\t}\n\n\targs = append(args, d.link)\n\n\tdl := exec.Command(d.settings.ytExe, args...)\n\terr := dl.Run()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tres, _ := filepath.Glob(d.settings.dlPath + \"/\" + d.uuid + \"*\")\n\n\tif len(res) < 1 {\n\t\treturn \"\", errors.New(\"Cannot find downloaded video file: \" + d.uuid)\n\t}\n\n\treturn res[0], nil\n}"} {"input": "package main\n\n\n\nfunc isPalindrome(n int) bool {\n\treturn n == reverse(n)\n}\n\nfunc p4() int {\n\tvar lp, a, b, db int\n\tlp, a = 0, 999\n\tfor a >= 100 {\n\t\tif a%11 == 0 {\n\t\t\tb, db = 999, 1\n\t\t} else {\n\t\t\tb, db = 990, 11\n\t\t}\n\t\tfor b >= a {\n\t\t\tif a*b <= lp {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif isPalindrome(a * b) {\n\t\t\t\tlp = a * b\n\t\t\t}\n\t\t\tb = b - db\n\t\t}\n\t\ta--\n\t}\n\treturn lp\n}\n\nfunc reverse(n int) int ", "output": "{\n\tr := 0\n\tfor n > 0 {\n\t\tr = 10*r + n%10\n\t\tn /= 10\n\t}\n\treturn r\n}"} {"input": "package fifo\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\n\n\n\nfunc CreateAndRead(path string) (func() (io.ReadCloser, error), error) {\n\tif err := mkfifo(path, 0600); err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating fifo %v: %v\", path, err)\n\t}\n\n\treturn func() (io.ReadCloser, error) {\n\t\treturn OpenReader(path)\n\t}, nil\n}\n\nfunc OpenReader(path string) (io.ReadCloser, error) {\n\treturn os.OpenFile(path, unix.O_RDONLY, os.ModeNamedPipe)\n}\n\n\nfunc OpenWriter(path string) (io.WriteCloser, error) {\n\treturn os.OpenFile(path, unix.O_WRONLY, os.ModeNamedPipe)\n}\n\n\n\n\nfunc IsClosedErr(err error) bool {\n\terr2, ok := err.(*os.PathError)\n\tif ok {\n\t\treturn err2.Err == os.ErrClosed\n\t}\n\treturn false\n}\n\nfunc mkfifo(path string, mode uint32) (err error) {\n\treturn unix.Mkfifo(path, mode)\n}\n\nfunc Remove(path string) error ", "output": "{\n\treturn os.Remove(path)\n}"} {"input": "package requirements\n\nimport (\n\t\"github.com/cloudfoundry/cli/cf/api\"\n\t\"github.com/cloudfoundry/cli/cf/models\"\n)\n\ntype BuildpackRequirement interface {\n\tRequirement\n\tGetBuildpack() models.Buildpack\n}\n\ntype buildpackApiRequirement struct {\n\tname string\n\tbuildpackRepo api.BuildpackRepository\n\tbuildpack models.Buildpack\n}\n\nfunc NewBuildpackRequirement(name string, bR api.BuildpackRepository) (req *buildpackApiRequirement) {\n\treq = new(buildpackApiRequirement)\n\treq.name = name\n\treq.buildpackRepo = bR\n\treturn\n}\n\n\n\nfunc (req *buildpackApiRequirement) GetBuildpack() models.Buildpack {\n\treturn req.buildpack\n}\n\nfunc (req *buildpackApiRequirement) Execute() error ", "output": "{\n\tvar apiErr error\n\treq.buildpack, apiErr = req.buildpackRepo.FindByName(req.name)\n\n\tif apiErr != nil {\n\t\treturn apiErr\n\t}\n\n\treturn nil\n}"} {"input": "package icon\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n)\n\nfunc (s *Service) Update(req *UpdateRequest) (*sacloud.Icon, error) {\n\treturn s.UpdateWithContext(context.Background(), req)\n}\n\n\n\nfunc (s *Service) UpdateWithContext(ctx context.Context, req *UpdateRequest) (*sacloud.Icon, error) ", "output": "{\n\tif err := req.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := sacloud.NewIconOp(s.caller)\n\tcurrent, err := client.Read(ctx, req.ID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"reading Icon[%s] failed: %s\", req.ID, err)\n\t}\n\n\tparams, err := req.ToRequestParameter(current)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"processing request parameter failed: %s\", err)\n\t}\n\n\treturn client.Update(ctx, req.ID, params)\n}"} {"input": "package testing\n\n\n\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n\tclientset \"k8s.io/kubernetes/pkg/client/clientset_generated/clientset\"\n\tkubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\"\n\tcontainertest \"k8s.io/kubernetes/pkg/kubelet/container/testing\"\n)\n\ntype fakeNetworkHost struct {\n\tfakeNamespaceGetter\n\tkubeClient clientset.Interface\n\tLegacy bool\n\tRuntime *containertest.FakeRuntime\n}\n\n\n\nfunc (fnh *fakeNetworkHost) GetPodByName(name, namespace string) (*v1.Pod, bool) {\n\treturn nil, false\n}\n\nfunc (fnh *fakeNetworkHost) GetKubeClient() clientset.Interface {\n\treturn nil\n}\n\nfunc (nh *fakeNetworkHost) GetRuntime() kubecontainer.Runtime {\n\treturn nh.Runtime\n}\n\nfunc (nh *fakeNetworkHost) SupportsLegacyFeatures() bool {\n\treturn nh.Legacy\n}\n\ntype fakeNamespaceGetter struct {\n\tns string\n}\n\nfunc (nh *fakeNamespaceGetter) GetNetNS(containerID string) (string, error) {\n\treturn nh.ns, nil\n}\n\nfunc NewFakeHost(kubeClient clientset.Interface) *fakeNetworkHost ", "output": "{\n\thost := &fakeNetworkHost{kubeClient: kubeClient, Legacy: true, Runtime: &containertest.FakeRuntime{}}\n\treturn host\n}"} {"input": "package resolver\n\nvar (\n\tm = make(map[string]Builder)\n\tdefaultScheme = \"passthrough\"\n)\n\n\n\n\n\nfunc Register(b Builder) {\n\tm[b.Scheme()] = b\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc SetDefaultScheme(scheme string) {\n\tdefaultScheme = scheme\n}\n\n\ntype AddressType uint8\n\nconst (\n\tBackend AddressType = iota\n\tGRPCLB\n)\n\n\n\ntype Address struct {\n\tAddr string\n\tType AddressType\n\tServerName string\n\tMetadata interface{}\n}\n\n\n\ntype BuildOption struct {\n}\n\n\n\ntype ClientConn interface {\n\tNewAddress(addresses []Address)\n\tNewServiceConfig(serviceConfig string)\n}\n\n\n\ntype Target struct {\n\tScheme string\n\tAuthority string\n\tEndpoint string\n}\n\n\ntype Builder interface {\n\tBuild(target Target, cc ClientConn, opts BuildOption) (Resolver, error)\n\tScheme() string\n}\n\n\ntype ResolveNowOption struct{}\n\n\n\ntype Resolver interface {\n\tResolveNow(ResolveNowOption)\n\tClose()\n}\n\n\n\n\nfunc UnregisterForTesting(scheme string) {\n\tdelete(m, scheme)\n}\n\nfunc Get(scheme string) Builder ", "output": "{\n\tif b, ok := m[scheme]; ok {\n\t\treturn b\n\t}\n\tif b, ok := m[defaultScheme]; ok {\n\t\treturn b\n\t}\n\treturn nil\n}"} {"input": "package relay\n\nimport (\n\t\"encoding/gob\"\n\t\"encoding/json\"\n\t\"io\"\n)\n\n\n\n\ntype Serializer interface {\n\tContentType() string\n\tRelayEncode(io.Writer, interface{}) error\n\tRelayDecode(io.Reader, interface{}) error\n}\n\n\ntype GOBSerializer struct{}\n\nfunc (*GOBSerializer) ContentType() string {\n\treturn \"binary/gob\"\n}\nfunc (*GOBSerializer) RelayEncode(w io.Writer, e interface{}) error {\n\tenc := gob.NewEncoder(w)\n\treturn enc.Encode(e)\n}\nfunc (*GOBSerializer) RelayDecode(r io.Reader, o interface{}) error {\n\tdec := gob.NewDecoder(r)\n\treturn dec.Decode(o)\n}\n\n\ntype JSONSerializer struct{}\n\nfunc (*JSONSerializer) ContentType() string {\n\treturn \"text/json\"\n}\n\nfunc (*JSONSerializer) RelayEncode(w io.Writer, e interface{}) error {\n\tenc := json.NewEncoder(w)\n\treturn enc.Encode(e)\n}\n\n\n\nfunc (*JSONSerializer) RelayDecode(r io.Reader, o interface{}) error ", "output": "{\n\tdec := json.NewDecoder(r)\n\treturn dec.Decode(o)\n}"} {"input": "package bce\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n\ntype Response struct {\n\tBodyContent []byte\n\t*http.Response\n}\n\nfunc NewResponse(res *http.Response) *Response {\n\treturn &Response{Response: res}\n}\n\n\n\n\nfunc (res *Response) GetBodyContent() ([]byte, error) ", "output": "{\n\tif res.BodyContent == nil {\n\t\tdefer func() {\n\t\t\tif res.Response != nil {\n\t\t\t\tres.Body.Close()\n\t\t\t}\n\t\t}()\n\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tres.BodyContent = body\n\t}\n\n\treturn res.BodyContent, nil\n}"} {"input": "package context\n\nimport (\n\t\"github.com/gorilla/context\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype RequestParam struct {\n\tRequest *http.Request\n}\n\nfunc Params(req *http.Request) *RequestParam {\n\tif rp, ok := context.Get(req, params).(*RequestParam); ok {\n\t\treturn rp\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (rp *RequestParam) Get(param string) string {\n\tif strings.HasPrefix(param, \":\") {\n\t\treturn rp.Request.URL.Query().Get(param)\n\t}\n\n\treturn rp.Request.Form.Get(param)\n}\n\nfunc (rp *RequestParam) GetInt(param string) (int, error) {\n\treturn strconv.Atoi(rp.Get(param))\n}\n\nfunc InitParams(req *http.Request) error ", "output": "{\n\terr := req.ParseForm()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trp := RequestParam{req}\n\n\tcontext.Set(req, params, &rp)\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n)\n\nfunc main() {\n\ttests := []int{234, 4421}\n\n\tfor _, test := range tests {\n\t\tlog.Printf(\"subtractProductAndSum(%d) = %d\\n\", test, subtractProductAndSum(test))\n\t}\n}\n\nfunc subtractProductAndSum(n int) int {\n\tnDigits := getDecimalDigits(n)\n \n\n \n \n\n \n \n\n\treturn (getProduct(nDigits) - getTotal(nDigits))\n}\n\n\n\nfunc getTotal(nums []int) int {\n\tvar tot int\n\n\tfor _, n := range nums {\n\t\ttot += n\n\t}\n\n\treturn tot\n}\n\nfunc getProduct(nums []int) int {\n\tvar prod int\n\n if len(nums) > 0 {\n prod = 1\n }\n\n\tfor _, n := range nums {\n\t\tprod *= n\n\t}\n\n\treturn prod\n}\n\nfunc getDecimalDigits(n int) []int ", "output": "{\n\tres := []int{}\n\n\trem := n % 10\n\tn = n / 10\n\tres = append(res, rem)\n\n\tfor n > 0 {\n\t\trem = n % 10\n\t\tn = n / 10\n\n\t\tres = append(res, rem)\n\t}\n\n\treturn res\n}"} {"input": "package int64s\n\nimport \"testing\"\n\nfunc TestMaxReturnsZeroWhenGivenZeroArgs(t *testing.T) {\n\texpected := int64(0)\n\tif actual := Max(); expected != actual {\n\t\tt.Error(\"Expected\", expected, \"got\", actual)\n\t}\n}\n\n\n\nfunc TestMaxReturnsLargestArgWhenGivenMultipleArgs(t *testing.T) {\n\texpected := int64(9)\n\tif actual := Max(1, 3, 5, 7, 9); expected != actual {\n\t\tt.Error(\"Expected\", expected, \"got\", actual)\n\t}\n}\n\nfunc TestMaxReturnsInputArgWhenGivenOneArgs(t *testing.T) ", "output": "{\n\texpected := int64(7)\n\tif actual := Max(7); expected != actual {\n\t\tt.Error(\"Expected\", expected, \"got\", actual)\n\t}\n}"} {"input": "package kafka\n\nimport (\n\t\"github.com/hyperledger/fabric/orderer/config\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n)\n\n\ntype Orderer interface {\n\tBroadcast(stream ab.AtomicBroadcast_BroadcastServer) error\n\tDeliver(stream ab.AtomicBroadcast_DeliverServer) error\n\tTeardown() error\n}\n\n\ntype Closeable interface {\n\tClose() error\n}\n\ntype serverImpl struct {\n\tbroadcaster Broadcaster\n\tdeliverer Deliverer\n}\n\n\nfunc New(conf *config.TopLevel) Orderer {\n\treturn &serverImpl{\n\t\tbroadcaster: newBroadcaster(conf),\n\t\tdeliverer: newDeliverer(conf),\n\t}\n}\n\n\nfunc (s *serverImpl) Broadcast(stream ab.AtomicBroadcast_BroadcastServer) error {\n\treturn s.broadcaster.Broadcast(stream)\n}\n\n\nfunc (s *serverImpl) Deliver(stream ab.AtomicBroadcast_DeliverServer) error {\n\treturn s.deliverer.Deliver(stream)\n}\n\n\n\n\nfunc (s *serverImpl) Teardown() error ", "output": "{\n\ts.deliverer.Close()\n\treturn s.broadcaster.Close()\n}"} {"input": "package reconcilers\n\nimport (\n\t\"net\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n)\n\n\ntype noneEndpointReconciler struct{}\n\n\n\nfunc NewNoneEndpointReconciler() EndpointReconciler {\n\treturn &noneEndpointReconciler{}\n}\n\n\nfunc (r *noneEndpointReconciler) ReconcileEndpoints(serviceName string, ip net.IP, endpointPorts []api.EndpointPort, reconcilePorts bool) error {\n\treturn nil\n}\n\n\n\n\nfunc (r *noneEndpointReconciler) StopReconciling(serviceName string, ip net.IP, endpointPorts []api.EndpointPort) error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/WindomZ/go-jwt/jwt\"\n\t\"os\"\n)\n\nconst (\n\tKeyNameHmac string = \"hmac_demo\" \n\tKeyNameRSA = \"rsa_demo\" \n)\n\nfunc main() {\n\tif dir, err := os.Getwd(); err != nil {\n\t\tpanic(err)\n\t} else if err := jwt.NewConfig(dir).Effect(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := demoHmac(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := demoRSA(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(\"Success!\")\n}\n\nfunc sign(keyName string, m interface{}) (token string, err error) {\n\treturn jwt.Sign(keyName, m, 72)\n}\n\nfunc verify(token string) (err error) {\n\t_, err = jwt.Parse(token)\n\treturn\n}\n\nvar test_case = map[string]interface{}{\n\t\"number\": 19,\n\t\"english\": \"This is the English test.\",\n\t\"中文\": \"这是个中文测试。\",\n}\n\nfunc demoHmac() error {\n\tif token, err := sign(KeyNameHmac, test_case); err != nil {\n\t\treturn err\n\t} else if err := verify(token); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc demoRSA() error ", "output": "{\n\tif token, err := sign(KeyNameRSA, test_case); err != nil {\n\t\treturn err\n\t} else if err := verify(token); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package animation\n\nimport (\n\t\"time\"\n)\n\ntype GroupedAnimation struct {\n\tanimators []Animator\n\tcallback AnimatorCallback\n}\n\nfunc NewGroupedAnimation(animators []Animator) *GroupedAnimation {\n\treturn &GroupedAnimation{animators, nil}\n}\n\nfunc (a *GroupedAnimation) SetCallback(callback AnimatorCallback) {\n\ta.callback = callback\n}\n\n\n\nfunc (a *GroupedAnimation) Update(elapsed time.Duration) time.Duration {\n\tvar (\n\t\ttotal time.Duration\n\t\tremainder time.Duration\n\t\tdone = true\n\t)\n\tfor _, animator := range a.animators {\n\t\tremainder = animator.Update(elapsed)\n\t\tif !animator.IsDone() {\n\t\t\tdone = false\n\t\t}\n\t\tif remainder != 0 && (total == 0 || remainder < total) {\n\t\t\ttotal = remainder \n\t\t}\n\t}\n\tif done {\n\t\tif a.callback != nil {\n\t\t\ta.callback()\n\t\t}\n\t\treturn total\n\t}\n\treturn 0\n}\n\nfunc (a *GroupedAnimation) Reset() {\n\tfor _, animator := range a.animators {\n\t\tanimator.Reset()\n\t}\n}\n\nfunc (a *GroupedAnimation) Delete() {\n\tfor _, animator := range a.animators {\n\t\tanimator.Delete()\n\t}\n\ta.animators = []Animator{}\n}\n\nfunc (a *GroupedAnimation) IsDone() bool ", "output": "{\n\tvar done = true\n\tfor _, animator := range a.animators {\n\t\tif !animator.IsDone() {\n\t\t\tdone = false\n\t\t}\n\t}\n\treturn done\n}"} {"input": "package incoming\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\nvar (\n\t_InKindNameToValue = map[string]InKind{\n\t\t\"control\": control,\n\t\t\"state\": state,\n\t\t\"checkForUpdates\": checkForUpdates,\n\t\t\"updateAvailable\": updateAvailable,\n\t\t\"updateBegin\": updateBegin,\n\t\t\"updateApply\": updateApply,\n\t}\n\n\t_InKindValueToName = map[InKind]string{\n\t\tcontrol: \"control\",\n\t\tstate: \"state\",\n\t\tcheckForUpdates: \"checkForUpdates\",\n\t\tupdateAvailable: \"updateAvailable\",\n\t\tupdateBegin: \"updateBegin\",\n\t\tupdateApply: \"updateApply\",\n\t}\n)\n\nfunc init() {\n\tvar v InKind\n\tif _, ok := interface{}(v).(fmt.Stringer); ok {\n\t\t_InKindNameToValue = map[string]InKind{\n\t\t\tinterface{}(control).(fmt.Stringer).String(): control,\n\t\t\tinterface{}(state).(fmt.Stringer).String(): state,\n\t\t\tinterface{}(checkForUpdates).(fmt.Stringer).String(): checkForUpdates,\n\t\t\tinterface{}(updateAvailable).(fmt.Stringer).String(): updateAvailable,\n\t\t\tinterface{}(updateBegin).(fmt.Stringer).String(): updateBegin,\n\t\t\tinterface{}(updateApply).(fmt.Stringer).String(): updateApply,\n\t\t}\n\t}\n}\n\n\n\n\n\nfunc (r *InKind) UnmarshalJSON(data []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\treturn fmt.Errorf(\"InKind should be a string, got %s\", data)\n\t}\n\tv, ok := _InKindNameToValue[s]\n\tif !ok {\n\t\treturn fmt.Errorf(\"invalid InKind %q\", s)\n\t}\n\t*r = v\n\treturn nil\n}\n\nfunc (r InKind) MarshalJSON() ([]byte, error) ", "output": "{\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn json.Marshal(s.String())\n\t}\n\ts, ok := _InKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid InKind: %d\", r)\n\t}\n\treturn json.Marshal(s)\n}"} {"input": "package sorts\n\nimport (\n\t\"testing\"\n)\n\nfunc TestQuickSort(t *testing.T) {\n\tarr := []int{5, 2, 4, 7, 1, 3, 2, 6}\n\tQuickSort(arr, 0, len(arr)-1)\n\tfor i:=0;i arr[i+1] {\n\t\t\tt.Errorf(\"QuickSort order is incorrect, got %v\", arr)\n\t\t}\n\t}\n}\n\n\n\nfunc TestSortK(t *testing.T) ", "output": "{\n\tarr3 := []int{4, 7, 0, 2, 1, 3, 9, 6}\n\tk := SortK(arr3, 5)\n\tif k != 6 {\n\t\tt.Errorf(\"SortK expect 6 , got %d\", k)\n\t}\n}"} {"input": "package runtimeemitter_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestRuntimeemitter(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Runtime Emitter Suite\")\n}"} {"input": "package funcs\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestFuncs(t *testing.T) ", "output": "{\n\tUrlfilter(\"hi\")\n}"} {"input": "package github\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net/url\"\n\n\t\"github.com/google/go-github/github\"\n\t\"golang.org/x/oauth2\"\n)\n\ntype Client struct {\n\tgh *github.Client\n}\n\n\n\nfunc (c *Client) Lookup() (string, string, map[string][]string, error) {\n\tm := make(map[string][]string)\n\n\tuser, _, err := c.gh.Users.Get(\"\")\n\tif err != nil {\n\t\treturn \"\", \"\", nil, err\n\t}\n\tif user.Login == nil {\n\t\treturn \"\", \"\", nil, fmt.Errorf(\"no login name found in Github profile...\")\n\t}\n\n\torgs, _, err := c.gh.Organizations.List(\"\", nil)\n\tif err != nil {\n\t\treturn \"\", \"\", nil, err\n\t}\n\tfor _, org := range orgs {\n\t\tm[*org.Login] = make([]string, 0)\n\t}\n\n\tteams, _, err := c.gh.Organizations.ListUserTeams(nil)\n\tif err != nil {\n\t\treturn \"\", \"\", nil, err\n\t}\n\n\tfor _, team := range teams {\n\t\tm[*team.Organization.Login] = append(m[*team.Organization.Login], *team.Name)\n\t}\n\n\tif user.Name == nil {\n\t\tuser.Name = user.Login\n\t}\n\treturn *user.Login, *user.Name, m, nil\n}\n\nfunc NewClient(api, token string) (*Client, error) ", "output": "{\n\tgh := github.NewClient(\n\t\toauth2.NewClient(context.Background(), oauth2.StaticTokenSource(\n\t\t\t&oauth2.Token{AccessToken: token},\n\t\t)),\n\t)\n\n\tif api != \"\" {\n\t\tu, err := url.Parse(api)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgh.BaseURL = u\n\t}\n\treturn &Client{gh: gh}, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/spf13/cobra\"\n\n\t_ \"github.com/lxc/lxd/lxd/include\"\n)\n\n\nimport \"C\"\n\ntype cmdForksyscall struct {\n\tglobal *cmdGlobal\n}\n\nfunc (c *cmdForksyscall) Command() *cobra.Command {\n\tcmd := &cobra.Command{}\n\tcmd.Use = \"forksyscall [...]\"\n\tcmd.Short = \"Perform syscall operations\"\n\tcmd.Long = `Description:\n Perform syscall operations\n\n This set of internal commands is used for all seccomp-based container syscall\n operations.\n`\n\tcmd.RunE = c.Run\n\tcmd.Hidden = true\n\n\treturn cmd\n}\n\n\n\nfunc (c *cmdForksyscall) Run(cmd *cobra.Command, args []string) error ", "output": "{\n\treturn fmt.Errorf(\"This command should have been intercepted in cgo\")\n}"} {"input": "package util\n\nimport (\n\tkafkav1beta1 \"knative.dev/eventing-kafka/pkg/apis/messaging/v1beta1\"\n\tcommonkafkautil \"knative.dev/eventing-kafka/pkg/channel/distributed/common/kafka/util\"\n)\n\n\n\n\nfunc TopicName(channel *kafkav1beta1.KafkaChannel) string ", "output": "{\n\treturn commonkafkautil.TopicName(channel.Namespace, channel.Name)\n}"} {"input": "package iso20022\n\n\ntype VerificationReason1Choice struct {\n\n\tCode *ExternalVerificationReason1Code `xml:\"Cd\"`\n\n\tProprietary *Max35Text `xml:\"Prtry\"`\n}\n\n\n\nfunc (v *VerificationReason1Choice) SetProprietary(value string) {\n\tv.Proprietary = (*Max35Text)(&value)\n}\n\nfunc (v *VerificationReason1Choice) SetCode(value string) ", "output": "{\n\tv.Code = (*ExternalVerificationReason1Code)(&value)\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/bitly/go-nsq\"\n)\n\n\n\ntype BackendQueue interface {\n\tPut([]byte) error\n\tReadChan() chan []byte \n\tClose() error\n\tDelete() error\n\tDepth() int64\n\tEmpty() error\n}\n\ntype DummyBackendQueue struct {\n\treadChan chan []byte\n}\n\nfunc NewDummyBackendQueue() BackendQueue {\n\treturn &DummyBackendQueue{readChan: make(chan []byte)}\n}\n\nfunc (d *DummyBackendQueue) Put([]byte) error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) ReadChan() chan []byte {\n\treturn d.readChan\n}\n\nfunc (d *DummyBackendQueue) Close() error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Delete() error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Depth() int64 {\n\treturn int64(0)\n}\n\nfunc (d *DummyBackendQueue) Empty() error {\n\treturn nil\n}\n\n\n\nfunc WriteMessageToBackend(buf *bytes.Buffer, msg *nsq.Message, bq BackendQueue) error ", "output": "{\n\tbuf.Reset()\n\terr := msg.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = bq.Put(buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package storage\n\nimport (\n\t\"crypto/rand\"\n\t\"math\"\n\t\"math/big\"\n)\n\n\n\n\nfunc NewTreeID() (int64, error) ", "output": "{\n\tid, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn id.Int64() + 1, nil\n}"} {"input": "package activitypub\n\nvar validLinkTypes = [...]ActivityVocabularyType{\n\tMentionType,\n}\n\n\n\n\n\n\n\ntype Link struct {\n\tID ID `jsonld:\"id,omitempty\"`\n\tType ActivityVocabularyType `jsonld:\"type,omitempty\"`\n\tName NaturalLanguageValues `jsonld:\"name,omitempty,collapsible\"`\n\tRel IRI `jsonld:\"rel,omitempty\"`\n\tMediaType MimeType `jsonld:\"mediaType,omitempty\"`\n\tHeight uint `jsonld:\"height,omitempty\"`\n\tWidth uint `jsonld:\"width,omitempty\"`\n\tPreview Item `jsonld:\"preview,omitempty\"`\n\tHref IRI `jsonld:\"href,omitempty\"`\n\tHrefLang LangRef `jsonld:\"hrefLang,omitempty\"`\n}\n\n\ntype Mention = Link\n\n\nfunc ValidLinkType(typ ActivityVocabularyType) bool {\n\tfor _, v := range validLinkTypes {\n\t\tif v == typ {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc LinkNew(id ID, typ ActivityVocabularyType) *Link {\n\tif !ValidLinkType(typ) {\n\t\ttyp = LinkType\n\t}\n\treturn &Link{ID: id, Type: typ}\n}\n\n\nfunc MentionNew(id ID) *Mention {\n\treturn &Mention{ID: id, Type: MentionType}\n}\n\n\nfunc (l Link) IsLink() bool {\n\treturn l.Type == LinkType || ValidLinkType(l.Type)\n}\n\n\nfunc (l Link) IsObject() bool {\n\treturn l.Type == ObjectType || ObjectTypes.Contains(l.Type)\n}\n\n\nfunc (l Link) IsCollection() bool {\n\treturn false\n}\n\n\nfunc (l Link) GetID() ID {\n\treturn l.ID\n}\n\n\nfunc (l Link) GetLink() IRI {\n\treturn IRI(l.ID)\n}\n\n\nfunc (l Link) GetType() ActivityVocabularyType {\n\treturn l.Type\n}\n\n\n\n\nfunc (l *Link) UnmarshalJSON(data []byte) error ", "output": "{\n\tif ItemTyperFunc == nil {\n\t\tItemTyperFunc = JSONGetItemByType\n\t}\n\tl.ID = JSONGetID(data)\n\tl.Type = JSONGetType(data)\n\tl.MediaType = JSONGetMimeType(data)\n\tl.Preview = JSONGetItem(data, \"preview\")\n\tl.Height = uint(JSONGetInt(data, \"height\"))\n\tl.Width = uint(JSONGetInt(data, \"width\"))\n\tl.Name = JSONGetNaturalLanguageField(data, \"name\")\n\tl.HrefLang = JSONGetLangRefField(data, \"hrefLang\")\n\thref := JSONGetURIItem(data, \"href\")\n\tif href != nil && !href.IsObject() {\n\t\tl.Href = href.GetLink()\n\t}\n\trel := JSONGetURIItem(data, \"rel\")\n\tif rel != nil && !rel.IsObject() {\n\t\tl.Rel = rel.GetLink()\n\t}\n\n\n\treturn nil\n}"} {"input": "package ast\n\n\ntype AsmLabelAttr struct {\n\tAddr Address\n\tPos Position\n\tInherited bool\n\tFunctionName string\n\tChildNodes []Node\n\tIsLiteralLabel bool\n}\n\nfunc parseAsmLabelAttr(line string) *AsmLabelAttr {\n\tgroups := groupsFromRegex(\n\t\t`<(?P.*)>\n\t\t(?P Inherited)?\n\t\t \"(?P.+)\"\n\t\t(?P IsLiteralLabel)?`,\n\t\tline,\n\t)\n\n\treturn &AsmLabelAttr{\n\t\tAddr: ParseAddress(groups[\"address\"]),\n\t\tPos: NewPositionFromString(groups[\"position\"]),\n\t\tInherited: len(groups[\"inherited\"]) > 0,\n\t\tFunctionName: groups[\"function\"],\n\t\tChildNodes: []Node{},\n\t\tIsLiteralLabel: len(groups[\"literal\"]) > 0,\n\t}\n}\n\n\n\n\n\n\n\nfunc (n *AsmLabelAttr) Address() Address {\n\treturn n.Addr\n}\n\n\n\nfunc (n *AsmLabelAttr) Children() []Node {\n\treturn n.ChildNodes\n}\n\n\nfunc (n *AsmLabelAttr) Position() Position {\n\treturn n.Pos\n}\n\nfunc (n *AsmLabelAttr) AddChild(node Node) ", "output": "{\n\tn.ChildNodes = append(n.ChildNodes, node)\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"os\"\n\n\t\"github.com/sim4life/go_hero/Godeps/_workspace/src/github.com/russross/blackfriday\"\n)\n\n\n\nfunc main() {\n\tport := os.Getenv(\"PORT\")\n\tif port == \"\" {\n\t\tport = \"8080\"\n\t}\n\n\thttp.HandleFunc(\"/markdown\", GenerateMarkdown)\n\thttp.Handle(\"/\", http.FileServer(http.Dir(\"public\")))\n\thttp.ListenAndServe(\":\"+port, nil)\n}\n\nfunc GenerateMarkdown(rw http.ResponseWriter, r *http.Request) ", "output": "{\n\tmarkdown := blackfriday.MarkdownCommon([]byte(r.FormValue(\"body\")))\n\trw.Write(markdown)\n}"} {"input": "package goics\n\n\n\n\n\n\nfunc truncateString(s string, length int) string {\n\tif len(s) <= length {\n\t\treturn s\n\t}\n\n\tcutoff := length\n\tfor s[cutoff]&0xc0 == 0x80 {\n\t\tcutoff--\n\t\tif cutoff < 0 {\n\t\t\tcutoff = 0\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn s[0:cutoff]\n}\n\nfunc splitLength(s string, length int) []string ", "output": "{\n\tvar ret []string\n\n\tfor len(s) > 0 {\n\t\ttmp := truncateString(s, length)\n\t\tif len(tmp) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tret = append(ret, tmp)\n\t\ts = s[len(tmp):]\n\t}\n\n\treturn ret\n}"} {"input": "package monator\n\nimport (\n \"time\"\n \"bytes\"\n \"encoding/json\"\n)\n\ntype CheckDuration time.Duration\n\n\n\nfunc (d CheckDuration) Minutes() float64 {\n return time.Duration(d).Minutes()\n}\n\nfunc (d CheckDuration) Nanoseconds() int64 {\n return time.Duration(d).Nanoseconds()\n}\n\nfunc (d CheckDuration) Seconds() float64 {\n return time.Duration(d).Seconds()\n}\n\nfunc (d CheckDuration) Milliseconds() int64 {\n return time.Duration(d).Nanoseconds() / int64(time.Millisecond)\n}\n\nfunc (d CheckDuration) String() string {\n \n rounded := ((time.Duration(d)).Nanoseconds() / int64(time.Millisecond)) * int64(time.Millisecond)\n return time.Duration(rounded).String()\n}\n\n\nfunc (d *CheckDuration) UnmarshalJSON(data []byte) error {\n b := bytes.NewBuffer(data)\n dec := json.NewDecoder(b)\n\n var s string\n\n if err := dec.Decode(&s); err != nil {\n return err\n }\n if duration, err := time.ParseDuration(s); err != nil {\n return err\n } else {\n *d = CheckDuration(duration)\n }\n\n return nil\n}\n\nfunc (d CheckDuration) Hours() float64 ", "output": "{\n return time.Duration(d).Hours()\n}"} {"input": "package indexdb\n\nimport (\n\t\"fmt\"\n\t\"github.com/eleme/banshee/models\"\n\t\"github.com/eleme/banshee/util\"\n)\n\n\n\n\n\nfunc decode(value []byte, idx *models.Index) error {\n\tn, err := fmt.Sscanf(string(value), \"%d:%f:%f\", &idx.Stamp, &idx.Score, &idx.Average)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n != 3 {\n\t\treturn ErrCorrupted\n\t}\n\treturn nil\n}\n\nfunc encode(idx *models.Index) []byte ", "output": "{\n\tscore := util.ToFixed(idx.Score, 5)\n\taverage := util.ToFixed(idx.Average, 5)\n\ts := fmt.Sprintf(\"%d:%s:%s\", idx.Stamp, score, average)\n\treturn []byte(s)\n}"} {"input": "package configtx\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hyperledger/fabric/common/configtx\"\n)\n\n\n\nfunc TestConfigtxManagerInterface(t *testing.T) {\n\t_ = configtx.Manager(&Manager{})\n}\n\nfunc TestConfigtxInitializerInterface(t *testing.T) ", "output": "{\n\t_ = configtx.Initializer(&Initializer{})\n}"} {"input": "package archive\n\nimport (\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com/containers/storage/pkg/system\"\n\t\"golang.org/x/sys/unix\"\n)\n\nfunc statDifferent(oldStat *system.StatT, newStat *system.StatT) bool {\n\tif oldStat.Mode() != newStat.Mode() ||\n\t\toldStat.UID() != newStat.UID() ||\n\t\toldStat.GID() != newStat.GID() ||\n\t\toldStat.Rdev() != newStat.Rdev() ||\n\t\t(oldStat.Mode()&unix.S_IFDIR != unix.S_IFDIR &&\n\t\t\t(!sameFsTimeSpec(oldStat.Mtim(), newStat.Mtim()) || (oldStat.Size() != newStat.Size()))) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (info *FileInfo) isDir() bool {\n\treturn info.parent == nil || info.stat.Mode()&unix.S_IFDIR != 0\n}\n\n\n\nfunc hasHardlinks(fi os.FileInfo) bool {\n\treturn fi.Sys().(*syscall.Stat_t).Nlink > 1\n}\n\nfunc getIno(fi os.FileInfo) uint64 ", "output": "{\n\treturn fi.Sys().(*syscall.Stat_t).Ino\n}"} {"input": "package rng\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\n\ntype CauchyGenerator struct {\n\tuniform *UniformGenerator\n}\n\n\n\n\nfunc NewCauchyGenerator(seed int64) *CauchyGenerator {\n\turng := NewUniformGenerator(seed)\n\treturn &CauchyGenerator{urng}\n}\n\n\n\n\n\nfunc (crng CauchyGenerator) StandardCauchy() float64 {\n\treturn crng.cauchy(0.0, 1.0)\n}\n\nfunc (crng CauchyGenerator) cauchy(x0, gamma float64) float64 {\n\treturn x0 + gamma*math.Tan(math.Pi*(crng.uniform.Float64()-0.5))\n}\n\nfunc (crng CauchyGenerator) Cauchy(x0, gamma float64) float64 ", "output": "{\n\tif !(gamma > 0.0) {\n\t\tpanic(fmt.Sprintf(\"Invalid parameter gamma: %.2f\", gamma))\n\t}\n\treturn crng.cauchy(x0, gamma)\n}"} {"input": "package chunkstore\n\nimport (\n\t\"errors\"\n\n\t. \"github.com/huin/chunkymonkey/types\"\n)\n\n\n\n\n\ntype MultiStore struct {\n\treadStores []IChunkStore\n\twriteStore IChunkStore\n}\n\nfunc NewMultiStore(readStores []IChunkStore, writeStore IChunkStore) *MultiStore {\n\ts := &MultiStore{\n\t\treadStores: readStores,\n\t\twriteStore: writeStore,\n\t}\n\n\treturn s\n}\n\n\n\nfunc (s *MultiStore) SupportsWrite() bool {\n\treturn s.writeStore != nil && s.writeStore.SupportsWrite()\n}\n\nfunc (s *MultiStore) Writer() IChunkWriter {\n\tif s.writeStore != nil {\n\t\treturn s.writeStore.Writer()\n\t}\n\treturn nil\n}\n\nfunc (s *MultiStore) WriteChunk(writer IChunkWriter) error {\n\tif s.writeStore == nil {\n\t\treturn errors.New(\"writes not supported\")\n\t}\n\ts.writeStore.WriteChunk(writer)\n\treturn nil\n}\n\nfunc (s *MultiStore) ReadChunk(chunkLoc ChunkXz) (reader IChunkReader, err error) ", "output": "{\n\tfor _, store := range s.readStores {\n\t\tresult := <-store.ReadChunk(chunkLoc)\n\n\t\tif result.Err == nil {\n\t\t\treturn result.Reader, result.Err\n\t\t} else {\n\t\t\tif _, ok := result.Err.(NoSuchChunkError); ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, result.Err\n\t\t}\n\t}\n\n\treturn nil, NoSuchChunkError(false)\n}"} {"input": "package hdiutil\n\nimport \"os/exec\"\n\n\ntype formatFlag interface {\n\tformatFlag() []string\n}\n\ntype convertFormot int\n\nconst (\n\tConvertUDRW convertFormot = 1 << iota\n\tConvertUDRO\n\tConvertUDCO\n\tConvertUDZO\n\tConvertULFO\n\tConvertUDBZ\n\tConvertUDTO\n\tConvertUDSP\n\tConvertUDSB\n\tConvertUFBI\n\tConvertUDRo\n\tConvertUDCo\n\tConvertRdWr\n\tConvertRdxx\n\tConvertROCo\n\tConvertRken\n\tConvertDC42\n)\n\n\ntype convertFlag interface {\n\tconvertFlag() []string\n}\n\n\ntype ConvertAlign int\n\nfunc (c ConvertAlign) convertFlag() []string { return intFlag(\"align\", int(c)) }\n\ntype convertPmap bool\n\nfunc (c convertPmap) convertFlag() []string { return boolFlag(\"pmap\", bool(c)) }\n\n\n\n\n\n\ntype ConvertSegmentSize string\n\nfunc (c ConvertSegmentSize) convertFlag() []string { return stringFlag(\"segmentSize\", string(c)) }\n\n\n\n\ntype ConvertTasks int\n\nfunc (c ConvertTasks) convertFlag() []string { return intFlag(\"tasks\", int(c)) }\n\nconst (\n\tConvertPmap convertPmap = true\n)\n\n\n\n\nfunc Convert(image string, format formatFlag, outfile string, flags ...convertFlag) error ", "output": "{\n\tcmd := exec.Command(hdiutilPath, \"convert\", image)\n\tcmd.Args = append(cmd.Args, format.formatFlag()...)\n\tcmd.Args = append(cmd.Args, outfile)\n\tif len(flags) > 0 {\n\t\tfor _, flag := range flags {\n\t\t\tcmd.Args = append(cmd.Args, flag.convertFlag()...)\n\t\t}\n\t}\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package transport\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\ntype Config struct {\n\tUserAgent string\n\n\tTLS TLSConfig\n\n\tUsername string\n\tPassword string\n\n\tBearerToken string\n\n\tBearerTokenFile string\n\n\tImpersonate ImpersonationConfig\n\n\tDisableCompression bool\n\n\tTransport http.RoundTripper\n\n\tWrapTransport WrapperFunc\n\n\tDial func(ctx context.Context, network, address string) (net.Conn, error)\n\n\tProxy func(*http.Request) (*url.URL, error)\n}\n\n\ntype ImpersonationConfig struct {\n\tUserName string\n\tGroups []string\n\tExtra map[string][]string\n}\n\n\nfunc (c *Config) HasCA() bool {\n\treturn len(c.TLS.CAData) > 0 || len(c.TLS.CAFile) > 0\n}\n\n\nfunc (c *Config) HasBasicAuth() bool {\n\treturn len(c.Username) != 0\n}\n\n\nfunc (c *Config) HasTokenAuth() bool {\n\treturn len(c.BearerToken) != 0 || len(c.BearerTokenFile) != 0\n}\n\n\n\n\n\nfunc (c *Config) HasCertCallback() bool {\n\treturn c.TLS.GetCert != nil\n}\n\n\n\n\n\nfunc (c *Config) Wrap(fn WrapperFunc) {\n\tc.WrapTransport = Wrappers(c.WrapTransport, fn)\n}\n\n\ntype TLSConfig struct {\n\tCAFile string \n\tCertFile string \n\tKeyFile string \n\tReloadTLSFiles bool \n\n\tInsecure bool \n\tServerName string \n\n\tCAData []byte \n\tCertData []byte \n\tKeyData []byte \n\n\tNextProtos []string\n\n\tGetCert func() (*tls.Certificate, error) \n}\n\nfunc (c *Config) HasCertAuth() bool ", "output": "{\n\treturn (len(c.TLS.CertData) != 0 || len(c.TLS.CertFile) != 0) && (len(c.TLS.KeyData) != 0 || len(c.TLS.KeyFile) != 0)\n}"} {"input": "package test\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/rook/rook/pkg/daemon/ceph/client\"\n)\n\nfunc MonInQuorumResponse() string {\n\tresp := client.MonStatusResponse{Quorum: []int{0}}\n\tresp.MonMap.Mons = []client.MonMapEntry{\n\t\t{\n\t\t\tName: \"a\",\n\t\t\tRank: 0,\n\t\t\tAddress: \"1.2.3.1\",\n\t\t},\n\t}\n\tserialized, _ := json.Marshal(resp)\n\treturn string(serialized)\n}\n\n\n\nfunc MonInQuorumResponseMany(count int) string {\n\tresp := client.MonStatusResponse{Quorum: []int{0}}\n\tresp.MonMap.Mons = []client.MonMapEntry{}\n\tfor i := 0; i <= count; i++ {\n\t\tresp.MonMap.Mons = append(resp.MonMap.Mons, client.MonMapEntry{\n\t\t\tName: fmt.Sprintf(\"rook-ceph-mon%d\", i),\n\t\t\tRank: 0,\n\t\t\tAddress: fmt.Sprintf(\"1.2.3.%d\", i),\n\t\t})\n\t}\n\tserialized, _ := json.Marshal(resp)\n\treturn string(serialized)\n}\n\nfunc MonInQuorumResponseFromMons(mons map[string]*client.MonInfo) string ", "output": "{\n\tresp := client.MonStatusResponse{Quorum: []int{}}\n\ti := 0\n\tfor name := range mons {\n\t\tresp.MonMap.Mons = append(resp.MonMap.Mons, client.MonMapEntry{\n\t\t\tName: name,\n\t\t\tRank: i,\n\t\t\tAddress: fmt.Sprintf(\"1.2.3.%d\", i),\n\t\t})\n\t\tresp.Quorum = append(resp.Quorum, i)\n\t\ti++\n\t}\n\tserialized, _ := json.Marshal(resp)\n\treturn string(serialized)\n}"} {"input": "package main\n\nimport (\n\t\"math\"\n)\n\n\n\nfunc Problem12() interface{} {\n\n\tvar index int = 1\n\tvar triangle int = 0\n\tfor {\n\n\t\ttriangle += index\n\t\tfactors := calculateFactors(triangle)\n\t\tif len(factors) > 500 {\n\t\t\treturn triangle\n\t\t}\n\n\t\tindex++\n\t}\n\treturn 0\n}\n\n\n\nfunc calculateFactors(n int) []int ", "output": "{\n\tvar factors []int\n\n\tfor i := 1; i <= int(math.Sqrt(float64(n))+1); i++ {\n\t\tif n%i == 0 {\n\t\t\tfactors = append(factors, i)\n\t\t\tfactors = append(factors, n/i)\n\t\t}\n\t}\n\n\treturn factors\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/spreadspace/telgo\"\n\t\"os\"\n)\n\nfunc whoami(c *telgo.Client, args []string, hostname string) bool {\n\tc.Sayln(\"%s @ (%s)\", c.UserData.(string), hostname)\n\treturn false\n}\n\n\n\nfunc main() {\n\tglobalUserdata := \"test\"\n\n\tcmdlist := make(telgo.CmdList)\n\tcmdlist[\"whoami\"] = func(c *telgo.Client, args []string) bool { return whoami(c, args, globalUserdata) }\n\tcmdlist[\"setname\"] = func(c *telgo.Client, args []string) bool { return setname(c, args, globalUserdata) }\n\n\ts, err := telgo.NewServer(\":7023\", \"userdata> \", cmdlist, \"anonymous\")\n\tif err != nil {\n\t\tfmt.Println(\"failed to initialize telnet server:\", err)\n\t\tos.Exit(1)\n\t}\n\tif err = s.Run(); err != nil {\n\t\tfmt.Println(\"telnet server returned:\", err)\n\t}\n}\n\nfunc setname(c *telgo.Client, args []string, hostname string) bool ", "output": "{\n\tif len(args) != 2 {\n\t\tc.Sayln(\"invalid number of arguments!\")\n\t\treturn false\n\t}\n\tc.UserData = args[1]\n\treturn false\n}"} {"input": "package HeatersController\n\nimport (\n\t\"errors\"\n\n\t\"github.com/stianeikeland/go-rpio\"\n)\n\nvar heaters [3]rpio.Pin\n\n\n\n\nfunc SetNumberOfWorkingHeaters(num int) error {\n\tif num == 0 {\n\t\theaters[0].High()\n\t\theaters[1].High()\n\t\theaters[2].High()\n\t} else if num == 1 {\n\t\theaters[0].Low()\n\t\theaters[1].High()\n\t\theaters[2].High()\n\t} else if num == 2 {\n\t\theaters[0].Low()\n\t\theaters[1].Low()\n\t\theaters[2].High()\n\t} else if num == 3 {\n\t\theaters[0].Low()\n\t\theaters[1].Low()\n\t\theaters[2].Low()\n\t} else {\n\t\treturn errors.New(\"The num argument should be between 0 and 3 inclusive\")\n\t}\n\n\treturn nil\n}\n\n\nfunc TurnOn(heaterID int) {\n\theaters[heaterID-1].Low()\n}\n\n\nfunc TurnOff(heaterID int) {\n\theaters[heaterID-1].High()\n}\n\n\nfunc GetNumberOfWorkingHeaters() int {\n\tresult := 0\n\tif heaters[0].Read() == rpio.Low {\n\t\tresult++\n\t}\n\n\tif heaters[1].Read() == rpio.Low {\n\t\tresult++\n\t}\n\n\tif heaters[2].Read() == rpio.Low {\n\t\tresult++\n\t}\n\n\treturn result\n}\n\nfunc init() ", "output": "{\n\trpio.Open()\n\n\theaters[0] = rpio.Pin(26)\n\theaters[1] = rpio.Pin(20)\n\theaters[2] = rpio.Pin(21)\n\n\theaters[0].Output()\n\theaters[1].Output()\n\theaters[2].Output()\n\n\theaters[0].High()\n\theaters[1].High()\n\theaters[2].High()\n}"} {"input": "package session\n\nimport (\n\t\"github.com/coyim/coyim/xmpp/data\"\n)\n\nconst (\n\tMUCStatusJIDPublic = 100\n\tMUCStatusAffiliationChanged = 101\n\tMUCStatusUnavailableShown = 102\n\tMUCStatusUnavailableNotShown = 103\n\tMUCStatusConfigChanged = 104\n\tMUCStatusSelfPresence = 110\n\tMUCStatusRoomLoggingEnabled = 170\n\tMUCStatusRoomLoggingDisabled = 171\n\tMUCStatusRoomNonAnonymous = 172\n\tMUCStatusRoomSemiAnonymous = 173\n\tMUCStatusRoomFullyAnonymous = 174\n\tMUCStatusRoomCreated = 201\n\tMUCStatusNicknameAssigned = 210\n\tMUCStatusBanned = 301\n\tMUCStatusNewNickname = 303\n\tMUCStatusBecauseKickedFrom = 307\n\tMUCStatusRemovedBecauseAffiliationChanged = 321\n\tMUCStatusRemovedBecauseNotMember = 322\n\tMUCStatusRemovedBecauseShutdown = 332\n)\n\ntype mucUserStatuses []data.MUCUserStatus\n\n\nfunc (mus mucUserStatuses) contains(c ...int) bool {\n\tfor _, cc := range c {\n\t\tif !mus.containsOne(cc) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc (mus mucUserStatuses) containsOne(c int) bool {\n\tfor _, s := range mus {\n\t\tif s.Code == c {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (mus mucUserStatuses) isEmpty() bool {\n\treturn len(mus) == 0\n}\n\nfunc (mus mucUserStatuses) containsAny(c ...int) bool ", "output": "{\n\tfor _, cc := range c {\n\t\tif mus.containsOne(cc) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package aggregation\n\nimport \"github.com/m3db/m3/src/x/pool\"\n\n\ntype TypesAlloc func() Types\n\n\ntype TypesPool interface {\n\tInit(alloc TypesAlloc)\n\n\tGet() Types\n\n\tPut(value Types)\n}\n\ntype typesPool struct {\n\tpool pool.ObjectPool\n}\n\n\nfunc NewTypesPool(opts pool.ObjectPoolOptions) TypesPool {\n\treturn &typesPool{pool: pool.NewObjectPool(opts)}\n}\n\n\n\nfunc (p *typesPool) Get() Types {\n\treturn p.pool.Get().(Types)\n}\n\nfunc (p *typesPool) Put(value Types) {\n\tp.pool.Put(value[:0])\n}\n\nfunc (p *typesPool) Init(alloc TypesAlloc) ", "output": "{\n\tp.pool.Init(func() interface{} {\n\t\treturn alloc()\n\t})\n}"} {"input": "package schema\n\ntype Type struct {\n\tName string\n\tDescription string\n}\n\n\n\nvar (\n\tBoolean = NewType(\"boolean\", \"\")\n\tInteger = NewType(\"integer\", \"\")\n\tFloat = NewType(\"float\", \"\")\n\tString = NewType(\"string\", \"\")\n\tDate = NewType(\"date\", \"\")\n\tDatetime = NewType(\"datetime\", \"\")\n\tObject = NewType(\"object\", \"\")\n\tCollection = NewType(\"collection\", \"\")\n)\n\ntype Fields map[string]*Field\n\ntype Field struct {\n\tName string\n\tType Type\n\tDescription string\n\tFields Fields\n}\n\nfunc NewType(name string, description string) Type ", "output": "{\n\treturn Type{name, description}\n}"} {"input": "package monebot\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype State struct {\n\tChat int64 `bson:\"chat\"`\n\tUser int `bson:\"user\"`\n\tWaiting WaitingState `bson:\"waiting,omitempty\"`\n\tLastUpdate time.Time `bson:\"lastUpdate\"`\n}\n\n\n\ntype WaitingState struct {\n\tForCommand bool `bson:\"forCommand,omitempty\"`\n\tPack string `bson:\"pack,omitempty\"`\n\tCommand string `bson:\"command,omitempty\"`\n}\n\n\ntype Answer struct {\n\tText string `bson:\"text,omitempty\"`\n\tNumParams int `bson:\"numParams\"`\n\tParse string `bson:\"parseMode,omitempty\"`\n\tSticker string `bson:\"sticker,omitempty\"`\n}\n\nconst (\n\tParseMarkdown = \"Markdown\"\n\tParseHTML = \"HTML\"\n)\n\n\ntype Command struct {\n\tPack string `bson:\"pack\"`\n\tName string `bson:\"name\"`\n\tAnswer Answer `bson:\"answer\"`\n\tTime time.Time `bson:\"time\"`\n\tCreator string `bson:\"creator,omitempty\"`\n\tNumChanged int `bson:\"numChanged,omitempty\"`\n}\n\n\nfunc (c Command) FullName() string {\n\treturn fmt.Sprintf(\"%s.%s\", c.Pack, c.Name)\n}\n\n\ntype Pack struct {\n\tName string `bson:\"name\"`\n\tChats []int64 `bson:\"chats\"`\n}\n\nfunc NewWaitingState(chat int64, user int, w WaitingState) State ", "output": "{\n\treturn State{Chat: chat, User: user, Waiting: w, LastUpdate: time.Now()}\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/api/scheduling/v1beta1\"\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\t\"k8s.io/client-go/kubernetes/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype SchedulingV1beta1Interface interface {\n\tRESTClient() rest.Interface\n\tPriorityClassesGetter\n}\n\n\ntype SchedulingV1beta1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *SchedulingV1beta1Client) PriorityClasses() PriorityClassInterface {\n\treturn newPriorityClasses(c)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*SchedulingV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SchedulingV1beta1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *SchedulingV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *SchedulingV1beta1Client {\n\treturn &SchedulingV1beta1Client{c}\n}\n\n\n\n\n\nfunc (c *SchedulingV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc setConfigDefaults(config *rest.Config) error ", "output": "{\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}"} {"input": "package elements\n\nimport \"github.com/fileformats/graphics/jt/model\"\n\n\n\n\n\n\ntype PropertyTable struct {\n\tVersionNumber int16\n\tPropertiesCount int32\n\tProperties map[int32]ElementPropertyTable\n}\n\nfunc (n *PropertyTable) Read(c *model.Context) error {\n\tc.LogGroup(\"NodePropertyTable\")\n\tdefer c.LogGroupEnd()\n\n\tn.Properties = map[int32]ElementPropertyTable{}\n\n\tn.VersionNumber = c.Data.Int16()\n\tc.Log(\"VersionNumber: %d\", n.VersionNumber)\n\n\tn.PropertiesCount = c.Data.Int32()\n\tc.Log(\"PropertiesCount: %d\", n.PropertiesCount)\n\n\tfor i := 0; i < int(n.PropertiesCount); i++ {\n\t\tobjectId := c.Data.Int32()\n\t\ttable := ElementPropertyTable{map[int32]int32{}}\n\t\t(&table).Read(c)\n\n\t\tn.Properties[objectId] = table\n\t}\n\n\n\treturn c.Data.GetError()\n}\n\n\n\ntype ElementPropertyTable struct {\n\tValues map[int32]int32\n}\n\n\n\nfunc (n *ElementPropertyTable) Read(c *model.Context) error ", "output": "{\n\tif n.Values == nil {\n\t\tn.Values = map[int32]int32{}\n\t}\n\tfor {\n\t\tobjectId := c.Data.Int32()\n\t\tif objectId == 0 || c.Data.GetError() != nil {\n\t\t\tbreak\n\t\t}\n\t\tn.Values[objectId] = c.Data.Int32()\n\t}\n\treturn c.Data.GetError()\n}"} {"input": "package install\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tutilruntime \"k8s.io/apimachinery/pkg/util/runtime\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\t\"k8s.io/kubernetes/pkg/apis/scheduling\"\n\t\"k8s.io/kubernetes/pkg/apis/scheduling/v1\"\n\t\"k8s.io/kubernetes/pkg/apis/scheduling/v1alpha1\"\n\t\"k8s.io/kubernetes/pkg/apis/scheduling/v1beta1\"\n)\n\n\n\n\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(scheduling.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1beta1.SchemeGroupVersion, v1.SchemeGroupVersion, v1alpha1.SchemeGroupVersion))\n}\n\nfunc init() ", "output": "{\n\tInstall(legacyscheme.Scheme)\n}"} {"input": "package positions\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\n\tyaml \"gopkg.in/yaml.v2\"\n)\n\n\n\n\n\nfunc writePositionFile(filename string, positions map[string]string) error ", "output": "{\n\tbuf, err := yaml.Marshal(File{\n\t\tPositions: positions,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttarget := filepath.Clean(filename)\n\ttemp := target + \"-new\"\n\n\terr = ioutil.WriteFile(temp, buf, os.FileMode(positionFileMode))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn os.Rename(temp, target)\n}"} {"input": "package math_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/ofc/math\"\n)\n\nfunc TestCT_MathPrChoiceConstructor(t *testing.T) {\n\tv := math.NewCT_MathPrChoice()\n\tif v == nil {\n\t\tt.Errorf(\"math.NewCT_MathPrChoice must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed math.CT_MathPrChoice should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestCT_MathPrChoiceMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := math.NewCT_MathPrChoice()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := math.NewCT_MathPrChoice()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package middleware\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestTimeout(t *testing.T) {\n\tfor _, timeout := range []time.Duration{-1, 0, 15 * time.Second, 120 * time.Hour} {\n\t\tt.Run(timeout.String(), func(t *testing.T) {\n\t\t\ttestTimeout(t, timeout)\n\t\t})\n\t}\n}\n\nfunc testTimeout(t *testing.T, timeout time.Duration) ", "output": "{\n\tvar (\n\t\tassert = assert.New(t)\n\n\t\texpectedRequest = \"expected request\"\n\t\texpectedResponse = \"expected response\"\n\n\t\tnextCalled = false\n\t\tnext = func(ctx context.Context, value interface{}) (interface{}, error) {\n\t\t\tnextCalled = true\n\n\t\t\tdeadline, ok := ctx.Deadline()\n\t\t\tassert.False(deadline.IsZero())\n\t\t\tassert.True(ok)\n\t\t\tassert.NotNil(ctx.Done())\n\n\t\t\treturn expectedResponse, nil\n\t\t}\n\n\t\tmiddleware = Timeout(timeout)\n\t)\n\n\tactualResponse, err := middleware(next)(context.Background(), expectedRequest)\n\tassert.Equal(expectedResponse, actualResponse)\n\tassert.NoError(err)\n\tassert.True(nextCalled)\n}"} {"input": "package journal\n\nimport (\n\t\"time\"\n\n\t\"nirenjan.org/overlord/database\"\n\t\"nirenjan.org/overlord/util\"\n)\n\n\n\n\n\ntype DBEntry struct {\n\tTitle string\n\tDate time.Time\n\tTags []string\n\tPath string\n}\n\nvar DB = make(map[string]DBEntry)\n\nfunc BuildDb() error {\n\terr := util.FileWalk(\"journal\", \".entry\", func(path string) error {\n\t\tentry, err1 := entryFromFile(path)\n\t\tif err1 != nil {\n\t\t\treturn err1\n\t\t}\n\n\t\tAddDbEntry(entry)\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn SaveDb()\n}\n\nfunc AddDbEntry(entry Entry) {\n\tvar dbEntry = DBEntry{\n\t\tTitle: entry.Title,\n\t\tDate: entry.Date,\n\t\tTags: entry.Tags,\n\t\tPath: entry.Path,\n\t}\n\n\tid := entry.ID\n\n\tDB[id] = dbEntry\n}\n\nfunc DeleteDbEntry(entry Entry) {\n\tdelete(DB, entry.ID)\n}\n\n\n\nfunc LoadDb() error {\n\treturn database.Load(&DB, BuildDb)\n}\n\nfunc SaveDb() error ", "output": "{\n\treturn database.Save(DB)\n}"} {"input": "package mysql\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\n\n\n\n\ntype GTID interface {\n\tString() string\n\n\tFlavor() string\n\n\tSourceServer() interface{}\n\n\tSequenceNumber() interface{}\n\n\tSequenceDomain() interface{}\n\n\tGTIDSet() GTIDSet\n}\n\n\nvar gtidParsers = make(map[string]func(string) (GTID, error))\n\n\n\n\n\nfunc MustParseGTID(flavor, value string) GTID {\n\tgtid, err := ParseGTID(flavor, value)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn gtid\n}\n\n\n\n\nfunc EncodeGTID(gtid GTID) string {\n\tif gtid == nil {\n\t\treturn \"\"\n\t}\n\n\treturn fmt.Sprintf(\"%s/%s\", gtid.Flavor(), gtid.String())\n}\n\n\n\nfunc DecodeGTID(s string) (GTID, error) {\n\tif s == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tparts := strings.SplitN(s, \"/\", 2)\n\tif len(parts) != 2 {\n\t\treturn ParseGTID(\"\", s)\n\t}\n\treturn ParseGTID(parts[0], parts[1])\n}\n\n\nfunc MustDecodeGTID(s string) GTID {\n\tgtid, err := DecodeGTID(s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn gtid\n}\n\nfunc ParseGTID(flavor, value string) (GTID, error) ", "output": "{\n\tparser := gtidParsers[flavor]\n\tif parser == nil {\n\t\treturn nil, fmt.Errorf(\"parse error: unknown GTID flavor %#v\", flavor)\n\t}\n\treturn parser(value)\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/mexisme/go-config/settings\"\n)\n\n\nfunc AddConfigItems(configKeys []string) {\n\tsettings.AddConfigItems(configKeys)\n}\n\n\nfunc AddConfigItemsWithPFlags(configKeys []string) error {\n\treturn settings.AddConfigItemsWithPFlags(configKeys)\n}\n\n\nfunc ApplyWith(key string, f func(interface{})) {\n\tsettings.ApplyWith(key, f)\n}\n\n\nfunc Get(key string) interface{} {\n\treturn settings.Get(key)\n}\n\n\nfunc GetBool(key string) bool {\n\treturn settings.GetBool(key)\n}\n\n\nfunc GetFloat64(key string) float64 {\n\treturn settings.GetFloat64(key)\n}\n\n\nfunc GetInt(key string) int {\n\treturn settings.GetInt(key)\n}\n\n\nfunc GetString(key string) string {\n\treturn settings.GetString(key)\n}\n\n\nfunc GetStringMap(key string) map[string]interface{} {\n\treturn settings.GetStringMap(key)\n}\n\n\nfunc GetStringMapString(key string) map[string]string {\n\treturn settings.GetStringMapString(key)\n}\n\n\nfunc GetStringSlice(key string) []string {\n\treturn settings.GetStringSlice(key)\n}\n\n\nfunc GetTime(key string) time.Time {\n\treturn settings.GetTime(key)\n}\n\n\nfunc GetDuration(key string) time.Duration {\n\treturn settings.GetDuration(key)\n}\n\n\n\n\n\nfunc AllSettings() map[string]interface{} {\n\treturn settings.AllSettings()\n}\n\nfunc IsSet(key string) bool ", "output": "{\n\treturn settings.IsSet(key)\n}"} {"input": "package plAuth\n\nimport (\n\t\"fmt\"\n)\n\n\n\ntype UnsetPassword struct {\n\tuser *User\n}\n\nfunc (e UnsetPassword) Error() string {\n\treturn fmt.Sprintf(\"%s has no password set. Call SetPass() first!\", e.user)\n}\n\n\ntype WrongPassword int\n\n\n\n\ntype ValidationError struct {\n\tReason string\n}\n\nfunc (e ValidationError) Error() string {\n\treturn e.Reason\n}\n\ntype InterfaceConversionError struct {\n\tFailed interface{}\n}\n\nfunc (e InterfaceConversionError) Error() string {\n\treturn fmt.Sprintf(\"Conversition failed %#v\", e.Failed)\n}\n\ntype UserAllreadyExists struct {\n\texistingUser *User\n}\n\nfunc (e UserAllreadyExists) Error() string {\n\treturn fmt.Sprintf(\"A user with this data allreay exists: %v\", e.existingUser)\n}\n\nfunc (e WrongPassword) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"Invalid Password\")\n}"} {"input": "package v1\n\nimport (\n\tv1 \"github.com/openshift/api/console/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype ConsoleYAMLSampleLister interface {\n\tList(selector labels.Selector) (ret []*v1.ConsoleYAMLSample, err error)\n\tGet(name string) (*v1.ConsoleYAMLSample, error)\n\tConsoleYAMLSampleListerExpansion\n}\n\n\ntype consoleYAMLSampleLister struct {\n\tindexer cache.Indexer\n}\n\n\n\n\n\nfunc (s *consoleYAMLSampleLister) List(selector labels.Selector) (ret []*v1.ConsoleYAMLSample, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ConsoleYAMLSample))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *consoleYAMLSampleLister) Get(name string) (*v1.ConsoleYAMLSample, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"consoleyamlsample\"), name)\n\t}\n\treturn obj.(*v1.ConsoleYAMLSample), nil\n}\n\nfunc NewConsoleYAMLSampleLister(indexer cache.Indexer) ConsoleYAMLSampleLister ", "output": "{\n\treturn &consoleYAMLSampleLister{indexer: indexer}\n}"} {"input": "package main\n\nvar (\n\tJsonApiErrAlertNotFound = JsonapiError{\n\t\tStatus: \"404\",\n\t\tCode: \"A404\",\n\t\tDetail: \"The requested alert couldn't be found in database.\",\n\t}\n)\n\n\ntype JsonapiLink struct {\n\tHref string `json:\"href\"`\n\tMeta string `json:\"meta,omitempty\"`\n}\n\n\ntype JsonapiError struct {\n\tId int `json:\"id,omitempty\"` \n\tStatus string `json:\"status,omitempty\"` \n\tLinks []JsonapiLink `json:\"links,omitempty\"` \n\tCode string `json:\"code,omitempty\"` \n\tTitle string `json:\"title,omitempty\"` \n\tDetail string `json:\"detail,omitempty\"` \n\tMeta string `json:\"meta,omitempty\"` \n}\n\ntype JsonapiResponse struct {\n\tData interface{} `json:\"data,omitempty\"`\n\tErrors []string `json:\"errors,omitempty\"`\n}\n\n\n\nfunc JsonapiWrapError(err error) JsonapiResponse {\n\treturn JsonapiResponse{Errors: []string{err.Error()}}\n}\n\nfunc JsonapiWrap(data interface{}) JsonapiResponse ", "output": "{\n\treturn JsonapiResponse{Data: data}\n}"} {"input": "package geo\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\nfunc TestDefineYesHaversine(t *testing.T) {\n\n\tif yesHaversine(make([]bool, 0)) {\n\t\tt.Error(\"define, yesHaversine should be false, got true\")\n\t}\n\n\tif !yesHaversine([]bool{true}) {\n\t\tt.Error(\"define, yesHaversine should be true, got false\")\n\t}\n\n\tif yesHaversine([]bool{false}) {\n\t\tt.Error(\"define, yesHaversine should be false, got true\")\n\t}\n}\n\n\n\nfunc TestDefineRad2Deg(t *testing.T) {\n\tif math.Abs(rad2deg(0.0)-0.0) > epsilon {\n\t\tt.Error(\"define, rad2deg error\")\n\t}\n\n\tif math.Abs(rad2deg(math.Pi)-180.0) > epsilon {\n\t\tt.Error(\"define, rad2deg error\")\n\t}\n\n\tif math.Abs(rad2deg(2*math.Pi)-360.0) > epsilon {\n\t\tt.Error(\"define, rad2deg error\")\n\t}\n}\n\nfunc TestDefineDeg2Rad(t *testing.T) ", "output": "{\n\tif math.Abs(deg2rad(0.0)) > epsilon {\n\t\tt.Error(\"define, deg2rad error\")\n\t}\n\n\tif math.Abs(deg2rad(180.0)-math.Pi) > epsilon {\n\t\tt.Error(\"define, deg2rad error\")\n\t}\n\n\tif math.Abs(deg2rad(360.0)-2*math.Pi) > epsilon {\n\t\tt.Error(\"define, deg2rad error\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gabriel-comeau/tbuikit\"\n\t\"github.com/nsf/termbox-go\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc doDisconnect(uiElement, event interface{}) {\n\tdisconnect()\n}\n\n\nfunc chatEnterHandler(uiElement, event interface{}) {\n\twidget, ok := uiElement.(*tbuikit.TextInputWidget)\n\tif ok {\n\t\tnetChatChan <- widget.GetBuffer().ReturnAndClear() + \"\\n\"\n\t}\n}\n\n\n\n\n\n\nfunc calculateTopTitleBar() (x1, x2, y1, y2 int) {\n\tw := tbuikit.GetTermboxWidth()\n\tx1 = 1\n\tx2 = w - 1\n\ty1 = 1\n\ty2 = TITLE_BAR_HEIGHT\n\treturn\n}\n\n\nfunc calculateChatBufferRect() (x1, x2, y1, y2 int) {\n\tw, h := termbox.Size()\n\tx1 = 1\n\tx2 = w - 1\n\ty1 = (h / 2) + (h / 4)\n\ty2 = h - 2\n\treturn\n}\n\n\nfunc calculateMessageBufferRect() (x1, x2, y1, y2 int) {\n\tw, h := termbox.Size()\n\tx1 = 1\n\tx2 = w - (w / 4)\n\ty1 = TITLE_BAR_HEIGHT + 1\n\ty2 = (h / 2) + (h / 4) - 1\n\treturn\n}\n\n\n\n\n\nfunc calculateWhoLabelRect() (x1, x2, y1, y2 int) {\n\tw := tbuikit.GetTermboxWidth()\n\tx1 = w - (w / 4) + 1\n\tx2 = w - 1\n\ty1 = TITLE_BAR_HEIGHT + 1\n\ty2 = TITLE_BAR_HEIGHT + 5\n\treturn\n}\n\nfunc calculateWhoRect() (x1, x2, y1, y2 int) ", "output": "{\n\tw, h := termbox.Size()\n\tx1 = w - (w / 4) + 1\n\tx2 = w - 1\n\ty1 = TITLE_BAR_HEIGHT + 6\n\ty2 = (h / 2) + (h / 4) - 1\n\treturn\n}"} {"input": "package model\n\ntype User struct {\n\tID string `db:\"id\"`\n\tName string `db:\"name\"`\n\tEmail string `db:\"email\"`\n\tGender string `db:\"gender\"`\n\tTranslationLanguageID *string `db:\"translation_language_id\"`\n}\n\nfunc (c *User) GenerateID() {\n\tc.ID = generateID(10)\n}\n\n\n\ntype UserConnection struct {\n\tUserID string `db:\"user_id\"`\n\tProviderID string `db:\"provider_id\"`\n\tProviderUserID string `db:\"provider_user_id\"`\n\n\tUser *User\n}\n\nfunc (c *User) SetTranslationLanguageID(value string) ", "output": "{\n\tif value == \"\" {\n\t\tc.TranslationLanguageID = nil\n\t} else {\n\t\tc.TranslationLanguageID = &value\n\t}\n}"} {"input": "package signers\n\nimport (\n\t\"crypto\"\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/sha1\"\n\t\"crypto/x509\"\n\t\"encoding/base64\"\n)\n\nfunc ShaHmac1(source, secret string) string {\n\tkey := []byte(secret)\n\thmac := hmac.New(sha1.New, key)\n\thmac.Write([]byte(source))\n\tsignedBytes := hmac.Sum(nil)\n\tsignedString := base64.StdEncoding.EncodeToString(signedBytes)\n\treturn signedString\n}\n\n\n\nfunc Sha256WithRsa(source, secret string) string ", "output": "{\n\tdecodeString, err := base64.StdEncoding.DecodeString(secret)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tprivate, err := x509.ParsePKCS8PrivateKey(decodeString)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\th := crypto.Hash.New(crypto.SHA256)\n\th.Write([]byte(source))\n\thashed := h.Sum(nil)\n\tsignature, err := rsa.SignPKCS1v15(rand.Reader, private.(*rsa.PrivateKey),\n\t\tcrypto.SHA256, hashed)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn base64.StdEncoding.EncodeToString(signature)\n}"} {"input": "package main\n\nimport (\n\tzmq \"github.com/pebbe/zmq3\"\n\t\"github.com/pebbe/zmq3/examples/bstar\"\n\n\t\"fmt\"\n\t\"os\"\n)\n\n\n\n\nfunc main() {\n\tvar bst *bstar.Bstar\n\tif len(os.Args) == 2 && os.Args[1] == \"-p\" {\n\t\tfmt.Println(\"I: Primary active, waiting for backup (passive)\")\n\t\tbst, _ = bstar.New(bstar.PRIMARY, \"tcp:*:5003\", \"tcp:localhost:5004\")\n\t\tbst.Voter(\"tcp:*:5001\", zmq.ROUTER, echo)\n\t} else if len(os.Args) == 2 && os.Args[1] == \"-b\" {\n\t\tfmt.Println(\"I: Backup passive, waiting for primary (active)\")\n\t\tbst, _ = bstar.New(bstar.BACKUP, \"tcp:*:5004\", \"tcp:localhost:5003\")\n\t\tbst.Voter(\"tcp:*:5002\", zmq.ROUTER, echo)\n\t} else {\n\t\tfmt.Println(\"Usage: bstarsrvs { -p | -b }\")\n\t\treturn\n\t}\n\tbst.Start()\n}\n\nfunc echo(socket *zmq.Socket) (err error) ", "output": "{\n\tmsg, err := socket.RecvMessage(0)\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = socket.SendMessage(msg)\n\treturn\n}"} {"input": "package lib\n\n\nimport \"C\"\n\nfunc CheckIsSupported(check int) bool {\n\treturn C.lzma_check_is_supported(C.lzma_check(check)) != 0\n}\n\nfunc CheckSize(check int) int {\n\treturn int(C.lzma_check_size(C.lzma_check(check)))\n}\n\n\n\nfunc CRC64(buf []byte, crc uint64) uint64 {\n\tptr, size := CSlicePtrLen(buf)\n\treturn uint64(C.lzma_crc64(ptr, size, C.uint64_t(crc)))\n}\n\nfunc (z *Stream) GetCheck() int {\n\treturn int(C.lzma_get_check(z.C()))\n}\n\nfunc CRC32(buf []byte, crc uint32) uint32 ", "output": "{\n\tptr, size := CSlicePtrLen(buf)\n\treturn uint32(C.lzma_crc32(ptr, size, C.uint32_t(crc)))\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"github.com/keybase/cli\"\n\t\"github.com/keybase/client/go/libcmdline\"\n\t\"github.com/keybase/client/go/libkb\"\n\tkeybase1 \"github.com/keybase/client/go/protocol/keybase1\"\n\t\"github.com/keybase/go-framed-msgpack-rpc/rpc\"\n\t\"golang.org/x/net/context\"\n)\n\ntype CmdFakeTrackingChanged struct {\n\tlibkb.Contextified\n\targ keybase1.FakeTrackingChangedArg\n}\n\nfunc (c *CmdFakeTrackingChanged) ParseArgv(ctx *cli.Context) error {\n\tif len(ctx.Args()) != 1 {\n\t\treturn fmt.Errorf(\"Must provide exactly one username.\")\n\t}\n\tc.arg.Username = ctx.Args()[0]\n\treturn nil\n}\n\n\n\nfunc NewCmdFakeTrackingChanged(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {\n\treturn cli.Command{\n\t\tName: \"fake-following-changed\",\n\t\tFlags: []cli.Flag{},\n\t\tAction: func(c *cli.Context) {\n\t\t\tcl.ChooseCommand(NewCmdFakeTrackingChangedRunner(g), \"fake-following-changed\", c)\n\t\t},\n\t}\n}\n\nfunc NewCmdFakeTrackingChangedRunner(g *libkb.GlobalContext) *CmdFakeTrackingChanged {\n\treturn &CmdFakeTrackingChanged{Contextified: libkb.NewContextified(g)}\n}\n\nfunc (c *CmdFakeTrackingChanged) GetUsage() libkb.Usage {\n\treturn libkb.Usage{\n\t\tConfig: true,\n\t\tAPI: true,\n\t}\n}\n\nfunc (c *CmdFakeTrackingChanged) Run() (err error) ", "output": "{\n\tcli, err := GetTrackClient(c.G())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprotocols := []rpc.Protocol{}\n\tif err = RegisterProtocolsWithContext(protocols, c.G()); err != nil {\n\t\treturn err\n\t}\n\n\terr = cli.FakeTrackingChanged(context.TODO(), c.arg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package http\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/Cepave/agent/g\"\n\t\"github.com/Cepave/common/model\"\n\t\"net/http\"\n)\n\n\n\nfunc configPushRoutes() ", "output": "{\n\thttp.HandleFunc(\"/v1/push\", func(w http.ResponseWriter, req *http.Request) {\n\t\tif req.ContentLength == 0 {\n\t\t\thttp.Error(w, \"body is blank\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tdecoder := json.NewDecoder(req.Body)\n\t\tvar metrics []*model.MetricValue\n\t\terr := decoder.Decode(&metrics)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"connot decode body\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tg.SendToTransfer(metrics)\n\t\tw.Write([]byte(\"success\"))\n\t})\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype ListFastConnectProviderVirtualCircuitBandwidthShapesRequest struct {\n\n\tProviderServiceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"providerServiceId\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListFastConnectProviderVirtualCircuitBandwidthShapesResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []VirtualCircuitBandwidthShape `presentIn:\"body\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ListFastConnectProviderVirtualCircuitBandwidthShapesResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response ListFastConnectProviderVirtualCircuitBandwidthShapesResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package modules\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n)\n\n\n\nfunc Decode(data []byte, to interface{}) error {\n\tbuf := bytes.NewBuffer(data)\n\tdec := gob.NewDecoder(buf)\n\treturn dec.Decode(to)\n}\n\nfunc Encode(data interface{}) ([]byte, error) ", "output": "{\n\tbuf := bytes.NewBuffer(nil)\n\tenc := gob.NewEncoder(buf)\n\terr := enc.Encode(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}"} {"input": "package pflag\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype boolValue bool\n\nfunc newBoolValue(val bool, p *bool) *boolValue {\n\t*p = val\n\treturn (*boolValue)(p)\n}\n\nfunc (b *boolValue) Set(s string) error {\n\tv, err := strconv.ParseBool(s)\n\t*b = boolValue(v)\n\treturn err\n}\n\nfunc (b *boolValue) String() string { return fmt.Sprintf(\"%v\", *b) }\n\n\n\nfunc (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc BoolVar(p *bool, name string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc (f *FlagSet) Bool(name string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, \"\", value, usage)\n\treturn p\n}\n\n\nfunc (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, shorthand, value, usage)\n\treturn p\n}\n\n\n\nfunc Bool(name string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, \"\", value, usage)\n}\n\n\n\n\nfunc BoolP(name, shorthand string, value bool, usage string) *bool ", "output": "{\n\treturn CommandLine.BoolP(name, shorthand, value, usage)\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/clients/generated/client/clientset/versioned/typed/cloudscheduler/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeCloudschedulerV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeCloudschedulerV1beta1) CloudSchedulerJobs(namespace string) v1beta1.CloudSchedulerJobInterface {\n\treturn &FakeCloudSchedulerJobs{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeCloudschedulerV1beta1) RESTClient() rest.Interface ", "output": "{\n\tvar ret *rest.RESTClient\n\treturn ret\n}"} {"input": "package controller\n\nimport (\n\t\"github.com/webx-top/blog/app/base\"\n\t\"github.com/webx-top/echo\"\n)\n\n\n\ntype Base struct {\n\t*base.Controller\n}\n\nfunc (a *Base) Before() error {\n\treturn nil\n}\n\nfunc New(c echo.Context) *Base ", "output": "{\n\treturn &Base{\n\t\tController: base.NewController(c),\n\t}\n}"} {"input": "package pointer\n\nimport \"time\"\n\nfunc DefaultBool(value *bool, defaultValue bool) *bool {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultDuration(value *time.Duration, defaultValue time.Duration) *time.Duration {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\n\n\nfunc DefaultInt(value *int, defaultValue int) *int {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultString(value *string, defaultValue string) *string {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultStringArray(value *[]string, defaultValue []string) *[]string {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultTime(value *time.Time, defaultValue time.Time) *time.Time {\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}\n\nfunc DefaultFloat64(value *float64, defaultValue float64) *float64 ", "output": "{\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSDynamoDBTable_TimeToLiveSpecification struct {\n\n\tAttributeName string `json:\"AttributeName,omitempty\"`\n\n\tEnabled bool `json:\"Enabled\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\n\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::DynamoDB::Table.TimeToLiveSpecification\"\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n)\n\nfunc PK(endpoint, metric string, tags map[string]string) string {\n\tif tags == nil || len(tags) == 0 {\n\t\treturn fmt.Sprintf(\"%s/%s\", endpoint, metric)\n\t}\n\treturn fmt.Sprintf(\"%s/%s/%s\", endpoint, metric, SortedTags(tags))\n}\n\nfunc PK2(endpoint, counter string) string {\n\treturn fmt.Sprintf(\"%s/%s\", endpoint, counter)\n}\n\nfunc UUID(endpoint, metric string, tags map[string]string, dstype string, step int) string {\n\tif tags == nil || len(tags) == 0 {\n\t\treturn fmt.Sprintf(\"%s/%s/%s/%d\", endpoint, metric, dstype, step)\n\t}\n\treturn fmt.Sprintf(\"%s/%s/%s/%s/%d\", endpoint, metric, SortedTags(tags), dstype, step)\n}\n\nfunc Checksum(endpoint string, metric string, tags map[string]string) string {\n\tpk := PK(endpoint, metric, tags)\n\treturn Md5(pk)\n}\n\n\n\nfunc ChecksumOfUUID(endpoint, metric string, tags map[string]string, dstype string, step int64) string ", "output": "{\n\treturn Md5(UUID(endpoint, metric, tags, dstype, int(step)))\n}"} {"input": "package bigquery\n\nimport (\n\t\"fmt\"\n\t\"github.com/viant/endly\"\n\t\"github.com/viant/endly/system/cloud/gcp\"\n\t\"google.golang.org/api/bigquery/v2\"\n)\n\nvar clientKey = (*CtxClient)(nil)\n\n\ntype CtxClient struct {\n\t*gcp.AbstractClient\n\tservice *bigquery.Service\n}\n\n\n\nfunc (s *CtxClient) Service() interface{} {\n\treturn s.service\n}\n\nfunc InitRequest(context *endly.Context, rawRequest map[string]interface{}) error {\n\tconfig, err := gcp.InitCredentials(context, rawRequest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient, err := getClient(context)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgcp.UpdateActionRequest(rawRequest, config, client)\n\treturn nil\n}\n\nfunc getClient(context *endly.Context) (gcp.CtxClient, error) {\n\treturn GetClient(context)\n}\n\nfunc GetClient(context *endly.Context) (*CtxClient, error) {\n\tclient := &CtxClient{\n\t\tAbstractClient: &gcp.AbstractClient{},\n\t}\n\terr := gcp.GetClient(context, bigquery.New, clientKey, &client, bigquery.CloudPlatformScope, bigquery.BigqueryScope, bigquery.BigqueryInsertdataScope)\n\treturn client, err\n}\n\nfunc (s *CtxClient) SetService(service interface{}) error ", "output": "{\n\tvar ok bool\n\ts.service, ok = service.(*bigquery.Service)\n\tif !ok {\n\t\treturn fmt.Errorf(\"unable to set service: %T\", service)\n\t}\n\treturn nil\n}"} {"input": "package skiplist_test\n\nimport (\n\t\"fmt\"\n\t\"github.com/someonegg/gocontainer/skiplist\"\n)\n\ntype item struct {\n\tscore int\n\n}\n\n\n\nfunc Example() {\n\n\tl := skiplist.NewList(itemCompare)\n\n\te1 := l.Add(&item{score: 4})\n\tfmt.Println(l.Rank(e1))\n\n\te2 := l.Add(&item{score: 1})\n\tfmt.Println(l.Rank(e2))\n\n\te3 := l.Add(&item{score: 3})\n\tfmt.Println(l.Rank(e3))\n\n\te4 := l.Add(&item{score: 2})\n\tfmt.Println(l.Rank(e4))\n\n\te5 := l.Add(&item{score: 4})\n\tfmt.Println(l.Rank(e5))\n\n\te6 := l.Add(&item{score: 6})\n\tfmt.Println(l.Rank(e6))\n\n\tfmt.Println()\n\n\tfor e := l.Front(); e != nil; e = e.Next() {\n\t\tfmt.Println(e.Value.(*item).score)\n\t}\n\n\tfmt.Println()\n\n\tl.Remove(l.Find(6))\n\tl.Remove(l.Get(4))\n\n\tfor e := l.Front(); e != nil; e = e.Next() {\n\t\tfmt.Println(e.Value.(*item).score)\n\t}\n\n}\n\nfunc itemCompare(l, r skiplist.Scorable) int ", "output": "{\n\tscoreL := int(0)\n\tswitch v := l.(type) {\n\tcase int:\n\t\tscoreL = v\n\tcase *item:\n\t\tscoreL = v.score\n\tdefault:\n\t\tpanic(l)\n\t}\n\tscoreR := int(0)\n\tswitch v := r.(type) {\n\tcase int:\n\t\tscoreR = v\n\tcase *item:\n\t\tscoreR = v.score\n\tdefault:\n\t\tpanic(r)\n\t}\n\treturn scoreL - scoreR\n}"} {"input": "package models\n\nimport (\n\t\"github.com/macococo/go-gamereviews/utils\"\n)\n\ntype User struct {\n\tId int\n\tName string\n\tType int\n\tModel\n}\n\ntype UserManager struct {\n}\n\nfunc (this *UserManager) TableName() string {\n\treturn \"t_user\"\n}\n\nfunc (this *UserManager) AddTable() {\n\tDbMap.AddTableWithName(User{}, this.TableName()).SetKeys(true, \"Id\")\n}\n\nfunc (this *UserManager) Count(t int) int64 {\n\tcount, err := DbMap.SelectInt(\"SELECT count(*) FROM \"+this.TableName()+\" WHERE type = ?\", t)\n\tutils.HandleError(err)\n\n\treturn count\n}\n\nfunc (this *UserManager) Find(t int, pagination *Pagination) []*User {\n\tvar users []*User\n\t_, err := DbMap.Select(&users, \"SELECT * FROM \"+this.TableName()+\" WHERE type = ? LIMIT ?, ?\", t, (pagination.Page-1)*pagination.Length, pagination.Length)\n\tutils.HandleError(err)\n\n\treturn users\n}\n\n\n\nfunc (this *UserManager) Create(user *User) *User ", "output": "{\n\tutils.HandleError(DbMap.Insert(user))\n\treturn user\n}"} {"input": "package main\n\nimport \"go/ast\"\n\n\n\n\n\n\nfunc checkRangeLoop(f *File, node ast.Node) {\n\tn := node.(*ast.RangeStmt)\n\tkey, _ := n.Key.(*ast.Ident)\n\tval, _ := n.Value.(*ast.Ident)\n\tif key == nil && val == nil {\n\t\treturn\n\t}\n\tsl := n.Body.List\n\tif len(sl) == 0 {\n\t\treturn\n\t}\n\tvar last *ast.CallExpr\n\tswitch s := sl[len(sl)-1].(type) {\n\tcase *ast.GoStmt:\n\t\tlast = s.Call\n\tcase *ast.DeferStmt:\n\t\tlast = s.Call\n\tdefault:\n\t\treturn\n\t}\n\tlit, ok := last.Fun.(*ast.FuncLit)\n\tif !ok {\n\t\treturn\n\t}\n\tast.Inspect(lit.Body, func(n ast.Node) bool {\n\t\tid, ok := n.(*ast.Ident)\n\t\tif !ok || id.Obj == nil {\n\t\t\treturn true\n\t\t}\n\t\tif key != nil && id.Obj == key.Obj || val != nil && id.Obj == val.Obj {\n\t\t\tf.Bad(id.Pos(), \"range variable\", id.Name, \"enclosed by function\")\n\t\t}\n\t\treturn true\n\t})\n}\n\nfunc init() ", "output": "{\n\tregister(\"rangeloops\",\n\t\t\"check that range loop variables are used correctly\",\n\t\tcheckRangeLoop,\n\t\trangeStmt)\n}"} {"input": "package v1alpha1\n\nimport (\n\truntime \"k8s.io/apimachinery/pkg/runtime\"\n)\n\nvar _ runtime.NestedObjectDecoder = &AdmissionConfiguration{}\n\n\n\nfunc (c *AdmissionConfiguration) DecodeNestedObjects(d runtime.Decoder) error {\n\tfor k, v := range c.Plugins {\n\t\tdecodeNestedRawExtensionOrUnknown(d, &v.Configuration)\n\t\tc.Plugins[k] = v\n\t}\n\treturn nil\n}\n\nvar _ runtime.NestedObjectEncoder = &AdmissionConfiguration{}\n\n\n\n\n\nfunc decodeNestedRawExtensionOrUnknown(d runtime.Decoder, ext *runtime.RawExtension) {\n\tif ext.Raw == nil || ext.Object != nil {\n\t\treturn\n\t}\n\tobj, gvk, err := d.Decode(ext.Raw, nil, nil)\n\tif err != nil {\n\t\tunk := &runtime.Unknown{Raw: ext.Raw}\n\t\tif runtime.IsNotRegisteredError(err) {\n\t\t\tif _, gvk, err := d.Decode(ext.Raw, nil, unk); err == nil {\n\t\t\t\tunk.APIVersion = gvk.GroupVersion().String()\n\t\t\t\tunk.Kind = gvk.Kind\n\t\t\t\text.Object = unk\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif gvk != nil {\n\t\t\tunk.APIVersion = gvk.GroupVersion().String()\n\t\t\tunk.Kind = gvk.Kind\n\t\t}\n\t\tobj = unk\n\t}\n\text.Object = obj\n}\n\nfunc encodeNestedRawExtension(e runtime.Encoder, ext *runtime.RawExtension) error {\n\tif ext.Raw != nil || ext.Object == nil {\n\t\treturn nil\n\t}\n\tdata, err := runtime.Encode(e, ext.Object)\n\tif err != nil {\n\t\treturn err\n\t}\n\text.Raw = data\n\treturn nil\n}\n\nfunc (c *AdmissionConfiguration) EncodeNestedObjects(e runtime.Encoder) error ", "output": "{\n\tfor k, v := range c.Plugins {\n\t\tif err := encodeNestedRawExtension(e, &v.Configuration); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.Plugins[k] = v\n\t}\n\treturn nil\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/apier/v1\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdRemoveBalance{\n\t\tname: \"balance_remove\",\n\t\trpcMethod: \"ApierV1.RemoveBalances\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdRemoveBalance struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrAddBalance\n\t*CommandExecuter\n}\n\nfunc (self *CmdRemoveBalance) Name() string {\n\treturn self.name\n}\n\n\n\nfunc (self *CmdRemoveBalance) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrAddBalance{BalanceType: utils.MONETARY, Overwrite: false}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdRemoveBalance) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdRemoveBalance) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *CmdRemoveBalance) RpcMethod() string ", "output": "{\n\treturn self.rpcMethod\n}"} {"input": "package testing\n\nimport \"k8s.io/kubernetes/pkg/util/iptables\"\n\n\ntype fake struct{}\n\n\n\nfunc (*fake) EnsureChain(table iptables.Table, chain iptables.Chain) (bool, error) {\n\treturn true, nil\n}\n\nfunc (*fake) FlushChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) DeleteChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) EnsureRule(position iptables.RulePosition, table iptables.Table, chain iptables.Chain, args ...string) (bool, error) {\n\treturn true, nil\n}\n\nfunc (*fake) DeleteRule(table iptables.Table, chain iptables.Chain, args ...string) error {\n\treturn nil\n}\n\nfunc (*fake) IsIpv6() bool {\n\treturn false\n}\n\nfunc (*fake) Save(table iptables.Table) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\nfunc (*fake) SaveAll() ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\nfunc (*fake) Restore(table iptables.Table, data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\n\nfunc (*fake) RestoreAll(data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\nfunc (*fake) AddReloadFunc(reloadFunc func()) {}\n\nfunc (*fake) Destroy() {}\n\nvar _ = iptables.Interface(&fake{})\n\nfunc NewFake() *fake ", "output": "{\n\treturn &fake{}\n}"} {"input": "package database\n\nimport (\n\t\"context\"\n\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n)\n\n\n\nfunc (s *Service) ReadWithContext(ctx context.Context, req *ReadRequest) (*sacloud.Database, error) {\n\tif err := req.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tclient := sacloud.NewDatabaseOp(s.caller)\n\treturn client.Read(ctx, req.Zone, req.ID)\n}\n\nfunc (s *Service) Read(req *ReadRequest) (*sacloud.Database, error) ", "output": "{\n\treturn s.ReadWithContext(context.Background(), req)\n}"} {"input": "package cleanhttp\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"runtime\"\n\t\"time\"\n)\n\n\n\nfunc DefaultTransport() *http.Transport {\n\ttransport := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t}\n\tSetTransportFinalizer(transport)\n\treturn transport\n}\n\n\n\n\n\n\n\n\nfunc SetTransportFinalizer(transport *http.Transport) {\n\truntime.SetFinalizer(&transport, func(t **http.Transport) {\n\t\t(*t).CloseIdleConnections()\n\t})\n}\n\nfunc DefaultClient() *http.Client ", "output": "{\n\treturn &http.Client{\n\t\tTransport: DefaultTransport(),\n\t}\n}"} {"input": "package generator\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\tlog \"github.com/sirupsen/logrus\"\n)\n\n\n\nfunc TestCastType(t *testing.T) ", "output": "{\n\n\tlog.SetLevel(log.DebugLevel)\n\n\ttypedef := \"object\"\n\tres := castType(typedef)\n\n\tif res != \"dbus.ObjectPath\" {\n\t\tt.Fatal(fmt.Sprintf(\"%s != %s\", typedef, res))\n\t}\n\n\ttypedef = \"array{objects, properties}\"\n\tres = castType(typedef)\n\n\tif res != \"[]dbus.ObjectPath, string\" {\n\t\tt.Fatal(fmt.Sprintf(\"%s != %s\", typedef, res))\n\t}\n\n}"} {"input": "package hashgraph\n\nimport (\n\t\"bytes\"\n\t\"sort\"\n\n\t\"github.com/mosaicnetworks/babble/src/crypto\"\n\t\"github.com/mosaicnetworks/babble/src/peers\"\n\t\"github.com/ugorji/go/codec\"\n)\n\n\ntype Frame struct {\n\tRound int \n\tPeers []*peers.Peer \n\tRoots map[string]*Root \n\tEvents []*FrameEvent \n\tPeerSets map[int][]*peers.Peer \n\tTimestamp int64 \n}\n\n\n\nfunc (f *Frame) SortedFrameEvents() []*FrameEvent {\n\tsorted := SortedFrameEvents{}\n\tfor _, r := range f.Roots {\n\t\tsorted = append(sorted, r.Events...)\n\t}\n\tsorted = append(sorted, f.Events...)\n\tsort.Sort(sorted)\n\treturn sorted\n}\n\n\nfunc (f *Frame) Marshal() ([]byte, error) {\n\tb := new(bytes.Buffer)\n\tjh := new(codec.JsonHandle)\n\tjh.Canonical = true\n\tenc := codec.NewEncoder(b, jh)\n\n\tif err := enc.Encode(f); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b.Bytes(), nil\n}\n\n\nfunc (f *Frame) Unmarshal(data []byte) error {\n\tb := bytes.NewBuffer(data)\n\tjh := new(codec.JsonHandle)\n\tjh.Canonical = true\n\tdec := codec.NewDecoder(b, jh)\n\n\tif err := dec.Decode(f); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc (f *Frame) Hash() ([]byte, error) ", "output": "{\n\thashBytes, err := f.Marshal()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn crypto.SHA256(hashBytes), nil\n}"} {"input": "package matchers\n\nimport (\n\t\"testing\"\n\n\t_ \"github.com/golang/glog\"\n)\n\n\n\nfunc TestAtLeast(t *testing.T) ", "output": "{\n\ttests := []struct {\n\t\tnum, actual int\n\t\twant bool\n\t}{\n\t\t{num: 5, actual: 3},\n\t\t{num: 5, actual: 5, want: true},\n\t\t{num: 5, actual: 10, want: true},\n\t}\n\tfor _, test := range tests {\n\t\tif got := AtLeast(test.num).Matches(test.actual); got != test.want {\n\t\t\tt.Errorf(\"AtLeast(%v).Matches(%v) = %v, want = %v\", test.num, test.actual, got, test.want)\n\t\t}\n\t}\n}"} {"input": "package mmf\n\nimport (\n\t\"os\"\n\t\"unsafe\"\n\n\tsyscall \"golang.org/x/sys/unix\"\n)\n\n\ntype MappedFile struct {\n\tdata []byte\n\toff int\n\tfile *os.File\n}\n\nfunc (mf *MappedFile) mmap(size int) error {\n\tvar err error\n\tmf.data, err = syscall.Mmap(int(mf.file.Fd()), 0, size, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED)\n\tif err != nil {\n\t\treturn os.NewSyscallError(\"Mmap\", err)\n\t}\n\treturn nil\n}\n\nfunc (mf *MappedFile) munmap() error {\n\tif data := mf.data; data != nil {\n\t\tmf.data = nil\n\t\tif err := syscall.Munmap(data); err != nil {\n\t\t\treturn os.NewSyscallError(\"Munmap\", err)\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\nfunc (mf *MappedFile) sync(async bool) error ", "output": "{\n\tvar flags uintptr\n\tif async {\n\t\tflags = syscall.MS_ASYNC\n\t} else {\n\t\tflags = syscall.MS_SYNC\n\t}\n\t_, _, errno := syscall.Syscall(syscall.SYS_MSYNC, uintptr(unsafe.Pointer(&mf.data[0])), uintptr(len(mf.data)), flags)\n\tif errno != 0 {\n\t\treturn os.NewSyscallError(\"Msync\", errno)\n\t}\n\treturn nil\n}"} {"input": "package test_helpers\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\tdatatypes \"github.com/maximilien/softlayer-go/data_types\"\n)\n\ntype MockProductPackageService struct{}\n\n\n\nfunc (mock *MockProductPackageService) GetItemsByType(packageType string) ([]datatypes.SoftLayer_Product_Item, error) {\n\tresponse, _ := ReadJsonTestFixtures(\"services\", \"SoftLayer_Product_Package_getItemsByType_virtual_server.json\")\n\n\tproductItems := []datatypes.SoftLayer_Product_Item{}\n\tjson.Unmarshal(response, &productItems)\n\n\treturn productItems, nil\n}\n\nfunc (mock *MockProductPackageService) GetItemPrices(packageId int) ([]datatypes.SoftLayer_Product_Item_Price, error) {\n\treturn []datatypes.SoftLayer_Product_Item_Price{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetItemPricesBySize(packageId int, size int) ([]datatypes.SoftLayer_Product_Item_Price, error) {\n\treturn []datatypes.SoftLayer_Product_Item_Price{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetItems(packageId int) ([]datatypes.SoftLayer_Product_Item, error) {\n\treturn []datatypes.SoftLayer_Product_Item{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetPackagesByType(packageType string) ([]datatypes.Softlayer_Product_Package, error) {\n\treturn []datatypes.Softlayer_Product_Package{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetOnePackageByType(packageType string) (datatypes.Softlayer_Product_Package, error) {\n\treturn datatypes.Softlayer_Product_Package{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetName() string ", "output": "{\n\treturn \"Mock_Product_Package_Service\"\n}"} {"input": "package main\nimport \"fmt\";\n\nfunc main() {\n var k int = 23\n var l int = 1\n l = swoosh(k)\n fmt.Println(k)\n fmt.Println(l)\n}\n\n\nfunc swoosh(x int) ", "output": "{\n return 2 + x\n}"} {"input": "package claim\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\nfunc TestPermission_MatchVerb(t *testing.T) {\n\tp := Permission{Verb: []string{\"read\", \"update\", \"create\"}}\n\tassert.True(t, p.MatchVerb(\"read\"))\n\tassert.True(t, p.MatchVerb(\"update\"))\n\tassert.True(t, p.MatchVerb(\"create\"))\n\tassert.False(t, p.MatchVerb(\"invalid\"))\n\tassert.False(t, p.MatchVerb(\"delete\"))\n}\n\nfunc TestPermission_Match(t *testing.T) {\n\tp := Permission{ResourceURN: \"userapi:device:device_id\"}\n\tassert.True(t, p.Match(\"userapi:device:device_id\"))\n\tassert.False(t, p.Match(\"userapi:device:bla\"))\n\tassert.False(t, p.Match(\"userapi:home:bla\"))\n}\n\n\nfunc TestPermissionSet_Match(t *testing.T) {\n\tp := PermissionSet{\n\t\tRules: []Permission{\n\t\t\t{ResourceURN: \"userapi:device:*\", Verb: []string{\"read\", \"update\", \"create\"}},\n\t\t\t{ResourceURN: \"userapi:device:\", Verb: []string{\"create\"}},\n\t\t},\n\t}\n\tassert.True(t, p.Match(\"read\", \"userapi:device:device_id\"))\n\tassert.False(t, p.Match(\"delete\", \"userapi:device:device_id\"))\n\tassert.True(t, p.Match(\"create\", \"userapi:device:\"))\n\n}\n\nfunc TestPermission_MatchWildcard(t *testing.T) ", "output": "{\n\tp := Permission{ResourceURN: \"userapi:device:*\"}\n\tassert.True(t, p.Match(\"userapi:device:device_id\"))\n\tassert.True(t, p.Match(\"userapi:device:bla\"))\n\tassert.False(t, p.Match(\"userapi:home:bla\"))\n}"} {"input": "package evoli\n\nimport \"math/rand\"\n\ntype crosserMock struct {\n}\n\nfunc (c crosserMock) Cross(parent1, parent2 Individual) (child1, child2 Individual, err error) {\n\tw := 0.1 + 0.8*rand.Float64()\n\treturn NewIndividual(w*parent1.Fitness() + (1-w)*parent2.Fitness()),\n\t\tNewIndividual((1-w)*parent1.Fitness() + w*parent2.Fitness()),\n\t\tnil\n}\n\ntype evaluaterMock struct {\n}\n\nfunc (e evaluaterMock) Evaluate(individual Individual) (Fitness float64, err error) {\n\treturn individual.Fitness(), nil\n}\n\ntype mutaterMock struct {\n}\n\n\n\ntype positionerMock struct {\n}\n\nfunc (p positionerMock) Position(indiv, pBest, gBest Individual, c1, c2 float64) (Individual, error) {\n\treturn NewIndividual((indiv.Fitness() + pBest.Fitness() + gBest.Fitness()) / 3), nil\n}\n\nfunc (m mutaterMock) Mutate(individual Individual, p float64) (Individual, error) ", "output": "{\n\treturn individual, nil\n}"} {"input": "package compress_test\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\n\t\"github.com/mkch/burrow/compress\"\n)\n\nfunc ExampleNewHandler() {\n\thttp.ListenAndServe(\":8080\", compress.NewHandler(http.DefaultServeMux, nil))\n}\n\n\n\nfunc ExampleNewResponseWriter() ", "output": "{\n\thandler := func(w http.ResponseWriter, r *http.Request) {\n\t\tcw, _ := compress.NewResponseWriter(w, compress.DefaultGzipWriterFactory)\n\t\tio.WriteString(cw, \"content to write\")\n\t}\n\thttp.ListenAndServe(\":8080\", http.HandlerFunc(handler))\n}"} {"input": "package ambition\n\nimport (\n\tcrand \"crypto/rand\"\n\t\"encoding/base64\"\n\t\"golang.org/x/crypto/bcrypt\"\n\t\"math/rand\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\n\n\nfunc CreateSaltAndHashedPassword(password []byte) ([]byte, []byte, error) {\n\tnano := time.Now().UnixNano()\n\trand.Seed(nano)\n\trandom := rand.Int31()\n\tsalt := strconv.Itoa(int(nano)) + strconv.Itoa(int(random))\n\n\thash, err := bcrypt.GenerateFromPassword([]byte(string(password)+salt), 10)\n\n\treturn []byte(salt), hash, err\n}\n\n\n\nfunc CompareSaltAndPasswordToHash(salt, hashedPassword, password []byte) bool {\n\tsaltedPassword := []byte(string(password) + string(salt))\n\n\terr := bcrypt.CompareHashAndPassword(hashedPassword, saltedPassword)\n\treturn err == nil\n}\n\n\n\n\n\nfunc GenerateRandomBytes(n int) ([]byte, error) {\n\tb := make([]byte, n)\n\t_, err := crand.Read(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}\n\n\n\n\n\n\nfunc GenerateRandomString(s int) (string, error) {\n\tb, err := GenerateRandomBytes(s)\n\treturn base64.URLEncoding.EncodeToString(b), err\n}\n\nfunc HashToken(token string) string {\n\thash, _ := bcrypt.GenerateFromPassword([]byte(token), 10)\n\treturn string(hash)\n}\n\n\n\nfunc LoginUser(username string, password string) {}\n\nfunc CompareHashAndToken(hash string, token string) bool ", "output": "{\n\n\terr := bcrypt.CompareHashAndPassword([]byte(hash), []byte(token))\n\treturn err == nil\n}"} {"input": "package dns\n\nimport (\n\t\"github.com/cilium/cilium/pkg/hubble/metrics/api\"\n)\n\ntype dnsPlugin struct{}\n\n\n\nfunc (p *dnsPlugin) HelpText() string {\n\treturn `dns - DNS related metrics\nReports metrics related to DNS queries and responses\n\nMetrics:\n hubble_dns_queries_total Number of observed TCP queries\n hubble_dns_responses_total Number of observed TCP responses\n\nOptions:\n query - Include query name as label\n ignoreAAAA - Do not include AAAA query & responses in metrics` +\n\t\tapi.ContextOptionsHelp\n}\n\nfunc init() {\n\tapi.DefaultRegistry().Register(\"dns\", &dnsPlugin{})\n}\n\nfunc (p *dnsPlugin) NewHandler() api.Handler ", "output": "{\n\treturn &dnsHandler{}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sync\"\n)\n\n\n\n\n\ntype Stage interface {\n\tInit()\n\tRun(*FileRecord) error\n\tClose()\n}\n\n\n\n\n\n\n\n\n\ntype Pipeline struct {\n\tinput chan *FileRecord\n\toutput chan *FileRecord\n\tlog chan *FileRecord\n\tlogWg sync.WaitGroup\n}\n\n\n\nfunc NewPipeline(inputQueueSize, logQueueSize int) *Pipeline {\n\tvar p Pipeline\n\tp.input = make(chan *FileRecord, inputQueueSize)\n\tp.output = p.input\n\tp.log = make(chan *FileRecord, logQueueSize)\n\n\tp.logWg.Add(1)\n\tgo func() {\n\t\tfor fr := range p.log {\n\t\t\tfmt.Fprint(os.Stderr, fr)\n\t\t}\n\t\tp.logWg.Done()\n\t}()\n\n\treturn &p\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *Pipeline) Close() {\n\tclose(p.log)\n\tp.logWg.Wait()\n}\n\nfunc (p *Pipeline) Add(NewStage func() Stage, routineCount int) ", "output": "{\n\tif routineCount <= 0 {\n\t\treturn\n\t}\n\tvar wg sync.WaitGroup\n\n\tout := make(chan *FileRecord, routineCount)\n\n\twg.Add(routineCount)\n\tfor i := 0; i < routineCount; i++ {\n\t\tgo func(input <-chan *FileRecord) {\n\t\t\ts := NewStage()\n\t\t\ts.Init()\n\t\t\tfor fr := range input {\n\t\t\t\terr := s.Run(fr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tp.log <- fr\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tout <- fr\n\t\t\t}\n\t\t\ts.Close()\n\t\t\twg.Done()\n\t\t}(p.output)\n\t}\n\n\tp.output = out\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(out)\n\t}()\n}"} {"input": "package echo\n\ntype (\n\tGroup struct {\n\t\techo Echo\n\t}\n)\n\nfunc (g *Group) Use(m ...Middleware) {\n\tfor _, h := range m {\n\t\tg.echo.middleware = append(g.echo.middleware, wrapMiddleware(h))\n\t}\n}\n\nfunc (g *Group) Connect(path string, h Handler) {\n\tg.echo.Connect(path, h)\n}\n\nfunc (g *Group) Delete(path string, h Handler) {\n\tg.echo.Delete(path, h)\n}\n\nfunc (g *Group) Get(path string, h Handler) {\n\tg.echo.Get(path, h)\n}\n\nfunc (g *Group) Head(path string, h Handler) {\n\tg.echo.Head(path, h)\n}\n\nfunc (g *Group) Options(path string, h Handler) {\n\tg.echo.Options(path, h)\n}\n\n\n\nfunc (g *Group) Post(path string, h Handler) {\n\tg.echo.Post(path, h)\n}\n\nfunc (g *Group) Put(path string, h Handler) {\n\tg.echo.Put(path, h)\n}\n\nfunc (g *Group) Trace(path string, h Handler) {\n\tg.echo.Trace(path, h)\n}\n\nfunc (g *Group) WebSocket(path string, h HandlerFunc) {\n\tg.echo.WebSocket(path, h)\n}\n\nfunc (g *Group) Static(path, root string) {\n\tg.echo.Static(path, root)\n}\n\nfunc (g *Group) ServeDir(path, root string) {\n\tg.echo.ServeDir(path, root)\n}\n\nfunc (g *Group) ServeFile(path, file string) {\n\tg.echo.ServeFile(path, file)\n}\n\nfunc (g *Group) Group(prefix string, m ...Middleware) *Group {\n\treturn g.echo.Group(prefix, m...)\n}\n\nfunc (g *Group) Patch(path string, h Handler) ", "output": "{\n\tg.echo.Patch(path, h)\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\ntype VersionSuite struct{}\n\nvar _ = Suite(&VersionSuite{})\n\n\n\nfunc (s *VersionSuite) TestVersion(c *C) ", "output": "{\n\t_, err := time.Parse(minioVersion, http.TimeFormat)\n\tc.Assert(err, NotNil)\n}"} {"input": "package inputdockerlog\n\nimport (\n\t\"context\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"github.com/tsaikd/gogstash/config\"\n\t\"github.com/tsaikd/gogstash/config/goglog\"\n)\n\n\n\nfunc Test_input_dockerlog_module(t *testing.T) {\n\tassert := assert.New(t)\n\tassert.NotNil(assert)\n\trequire := require.New(t)\n\trequire.NotNil(require)\n\n\tctx := context.Background()\n\tconf, err := config.LoadFromYAML([]byte(strings.TrimSpace(`\ndebugch: true\ninput:\n - type: dockerlog\n dockerurl: \"unix:///var/run/docker.sock\"\n sincepath: \"sincedb-test\"\n\t`)))\n\trequire.NoError(err)\n\terr = conf.Start(ctx)\n\tif err != nil {\n\t\trequire.True(ErrorPingFailed.In(err))\n\t\tt.Skip(\"skip test input dockerlog module\")\n\t}\n\n\ttime.Sleep(500 * time.Millisecond)\n\tif event, err := conf.TestGetOutputEvent(100 * time.Millisecond); assert.NoError(err) {\n\t\tt.Log(event)\n\t}\n}\n\nfunc init() ", "output": "{\n\tgoglog.Logger.SetLevel(logrus.DebugLevel)\n\tconfig.RegistInputHandler(ModuleName, InitHandler)\n}"} {"input": "package gq\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nvar count int\n\ntype WorkerTest struct {\n\tDelay time.Duration\n}\n\nfunc (w WorkerTest) Work() {\n\tcount++\n}\n\nfunc (w WorkerTest) Data() string {\n\treturn \"\"\n}\n\nfunc (w WorkerTest) DelayTime() time.Duration {\n\treturn w.Delay\n}\n\nfunc (w WorkerTest) Preprocess() string {\n\treturn \"\"\n}\n\nfunc (w WorkerTest) Postprocess() string {\n\treturn \"\"\n}\n\nfunc nullLogger(...interface{}) {}\n\nfunc init() {\n\tLogger(nullLogger)\n\tStartDispatcher(10)\n\tfor i := 0; i < 10; i++ {\n\t\twork := WorkerTest{Delay: 0 * time.Second}\n\t\tWorkQueue <- work\n\t}\n\ttime.Sleep(1 * time.Second)\n}\n\n\n\nfunc TestIncrement(t *testing.T) ", "output": "{\n\tif count != 10 {\n\t\tt.Errorf(\"expected count to be 10, got %d\\n\", count)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"text/template\"\n)\n\n\n\n\nfunc ParseTemplates(templatesDir string) (*template.Template, error) ", "output": "{\n\tt, err := template.ParseGlob(filepath.Join(templatesDir, \"*\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error parsing templates in dir %s: %s\", templatesDir, err)\n\t}\n\treturn t, nil\n}"} {"input": "package iterator_test\n\nimport (\n\t\"testing\"\n\n\t\"bosun.org/_third_party/github.com/syndtr/goleveldb/leveldb/testutil\"\n)\n\n\n\nfunc TestIterator(t *testing.T) ", "output": "{\n\ttestutil.RunSuite(t, \"Iterator Suite\")\n}"} {"input": "package splice\n\nimport ()\n\nfunc (p *Pair) LoadFromAt(fd uintptr, sz int, off int64) (int, error) {\n\tpanic(\"not implemented\")\n\treturn 0, nil\n}\n\n\n\nfunc (p *Pair) WriteTo(fd uintptr, n int) (int, error) {\n\tpanic(\"not implemented\")\n\treturn 0, nil\n}\n\nfunc (p *Pair) LoadFrom(fd uintptr, sz int) (int, error) ", "output": "{\n\tpanic(\"not implemented\")\n\treturn 0, nil\n}"} {"input": "package testing\n\n\n\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n\tclientset \"k8s.io/kubernetes/pkg/client/clientset_generated/clientset\"\n\tkubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\"\n\tcontainertest \"k8s.io/kubernetes/pkg/kubelet/container/testing\"\n)\n\ntype fakeNetworkHost struct {\n\tfakeNamespaceGetter\n\tkubeClient clientset.Interface\n\tLegacy bool\n\tRuntime *containertest.FakeRuntime\n}\n\nfunc NewFakeHost(kubeClient clientset.Interface) *fakeNetworkHost {\n\thost := &fakeNetworkHost{kubeClient: kubeClient, Legacy: true, Runtime: &containertest.FakeRuntime{}}\n\treturn host\n}\n\nfunc (fnh *fakeNetworkHost) GetPodByName(name, namespace string) (*v1.Pod, bool) {\n\treturn nil, false\n}\n\nfunc (fnh *fakeNetworkHost) GetKubeClient() clientset.Interface {\n\treturn nil\n}\n\nfunc (nh *fakeNetworkHost) GetRuntime() kubecontainer.Runtime {\n\treturn nh.Runtime\n}\n\nfunc (nh *fakeNetworkHost) SupportsLegacyFeatures() bool {\n\treturn nh.Legacy\n}\n\ntype fakeNamespaceGetter struct {\n\tns string\n}\n\n\n\nfunc (nh *fakeNamespaceGetter) GetNetNS(containerID string) (string, error) ", "output": "{\n\treturn nh.ns, nil\n}"} {"input": "package pmgo\n\nimport mgo \"gopkg.in/mgo.v2\"\n\ntype IterManager interface {\n\tAll(result interface{}) error\n\tClose() error\n\tDone() bool\n\tErr() error\n\tFor(result interface{}, f func() error) (err error)\n\tNext(result interface{}) bool\n\tTimeout() bool\n}\n\ntype Iter struct {\n\titer *mgo.Iter\n}\n\nfunc NewIter(iter *mgo.Iter) IterManager {\n\treturn &Iter{iter}\n}\n\nfunc (i *Iter) All(result interface{}) error {\n\treturn i.iter.All(result)\n}\n\nfunc (i *Iter) Close() error {\n\treturn i.iter.Close()\n}\n\nfunc (i *Iter) Done() bool {\n\treturn i.iter.Done()\n}\n\n\n\nfunc (i *Iter) For(result interface{}, f func() error) (err error) {\n\treturn i.iter.For(result, f)\n}\n\nfunc (i *Iter) Next(result interface{}) bool {\n\treturn i.iter.Next(result)\n}\n\nfunc (i *Iter) Timeout() bool {\n\treturn i.iter.Timeout()\n}\n\nfunc (i *Iter) Err() error ", "output": "{\n\treturn i.iter.Err()\n}"} {"input": "package model\n\nimport uuidGenerator \"github.com/satori/go.uuid\"\n\n\n\n\ntype Modifier struct {\n\tUuid uuidGenerator.UUID\n\tFirstname string\n\tLastname string\n\tEmail string\n\tPolymorficType string\n\tDeleted bool\n}\n\n\n\n\n\nfunc (m *Modifier) MarkAsDeleted() {\n\tm.Deleted = true\n}\n\n\nfunc (m *Modifier) Update(firstname, lastname, email string) {\n\tm.Firstname = firstname\n\tm.Lastname = lastname\n\tm.Email = email\n}\n\nfunc NewModifier(uuid uuidGenerator.UUID, firstname, lastname, email, polymorficType string, deleted bool) *Modifier ", "output": "{\n\treturn &Modifier{\n\t\tuuid,\n\t\tfirstname,\n\t\tlastname,\n\t\temail,\n\t\tpolymorficType,\n\t\tdeleted,\n\t}\n}"} {"input": "package controller\n\nimport (\n\t\"github.com/op/go-logging\"\n\t\"github.com/spf13/viper\"\n\n\t\"github.com/openblockchain/obc-peer/openchain/consensus\"\n\t\"github.com/openblockchain/obc-peer/openchain/consensus/noops\"\n\t\"github.com/openblockchain/obc-peer/openchain/consensus/obcpbft\"\n)\n\nvar logger *logging.Logger \n\nfunc init() {\n\tlogger = logging.MustGetLogger(\"consensus/controller\")\n}\n\n\n\n\nfunc NewConsenter(stack consensus.Stack) (consenter consensus.Consenter) ", "output": "{\n\tplugin := viper.GetString(\"peer.validator.consensus\")\n\tif plugin == \"obcpbft\" {\n\t\tconsenter = obcpbft.GetPlugin(stack)\n\t} else {\n\t\tconsenter = noops.GetNoops(stack)\n\t}\n\treturn\n}"} {"input": "package command\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/mitchellh/cli\"\n\t\"github.com/sgeb/go-acd\"\n)\n\ntype VersionCommand struct {\n\tAppName string\n\tRevision string\n\tVersion string\n\tVersionPrerelease string\n\tUi cli.Ui\n}\n\nfunc (c *VersionCommand) Help() string {\n\treturn \"\"\n}\n\n\n\nfunc (c *VersionCommand) Synopsis() string {\n\treturn fmt.Sprintf(\"Prints the %s version\", c.AppName)\n}\n\nfunc (c *VersionCommand) Run(_ []string) int ", "output": "{\n\tvar versionString bytes.Buffer\n\n\tfmt.Fprintf(&versionString, \"%s v%s\", c.AppName, c.Version)\n\tif c.VersionPrerelease != \"\" {\n\t\tfmt.Fprintf(&versionString, \"-%s\", c.VersionPrerelease)\n\n\t\tif c.Revision != \"\" {\n\t\t\tfmt.Fprintf(&versionString, \" (%s)\", c.Revision)\n\t\t}\n\t}\n\n\tfmt.Fprintln(&versionString, \"\")\n\tfmt.Fprintf(&versionString, \"using go-acd v%s\", acd.LibraryVersion)\n\n\tc.Ui.Output(versionString.String())\n\treturn 0\n\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"text/tabwriter\"\n)\n\ntype depaccountTableOutput struct{ w *tabwriter.Writer }\n\nfunc (out *depaccountTableOutput) BasicHeader() {\n\tfmt.Fprintf(out.w, \"OrgName\\tOrgPhone\\tOrgEmail\\tServerName\\n\")\n}\n\nfunc (out *depaccountTableOutput) BasicFooter() {\n\tout.w.Flush()\n}\n\n\n\nfunc (cmd *getCommand) getDEPAccount(args []string) error ", "output": "{\n\tflagset := flag.NewFlagSet(\"dep-account\", flag.ExitOnError)\n\tflagset.Usage = usageFor(flagset, \"mdmctl get dep-account [flags]\")\n\tif err := flagset.Parse(args); err != nil {\n\t\treturn err\n\t}\n\tw := tabwriter.NewWriter(os.Stdout, 0, 4, 2, ' ', 0)\n\tout := &depaccountTableOutput{w}\n\tout.BasicHeader()\n\tdefer out.BasicFooter()\n\tctx := context.Background()\n\tresp, err := cmd.depsvc.GetAccountInfo(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(out.w, \"%s\\t%s\\t%s\\t%s\\n\", resp.OrgName, resp.OrgPhone, resp.OrgEmail, resp.ServerName)\n\treturn nil\n}"} {"input": "package fakes\n\nimport (\n\t\"os/exec\"\n\t\"sync\"\n\n\t\"github.com/cloudfoundry-incubator/genclient\"\n)\n\ntype CommandRunner struct {\n\tRunStub func(cmd *exec.Cmd) error\n\trunMutex sync.RWMutex\n\trunArgsForCall []struct {\n\t\tcmd *exec.Cmd\n\t}\n\trunReturns struct {\n\t\tresult1 error\n\t}\n}\n\nfunc (fake *CommandRunner) Run(cmd *exec.Cmd) error {\n\tfake.runMutex.Lock()\n\tfake.runArgsForCall = append(fake.runArgsForCall, struct {\n\t\tcmd *exec.Cmd\n\t}{cmd})\n\tfake.runMutex.Unlock()\n\tif fake.RunStub != nil {\n\t\treturn fake.RunStub(cmd)\n\t} else {\n\t\treturn fake.runReturns.result1\n\t}\n}\n\nfunc (fake *CommandRunner) RunCallCount() int {\n\tfake.runMutex.RLock()\n\tdefer fake.runMutex.RUnlock()\n\treturn len(fake.runArgsForCall)\n}\n\n\n\nfunc (fake *CommandRunner) RunReturns(result1 error) {\n\tfake.RunStub = nil\n\tfake.runReturns = struct {\n\t\tresult1 error\n\t}{result1}\n}\n\nvar _ genclient.CommandRunnerInterface = new(CommandRunner)\n\nfunc (fake *CommandRunner) RunArgsForCall(i int) *exec.Cmd ", "output": "{\n\tfake.runMutex.RLock()\n\tdefer fake.runMutex.RUnlock()\n\treturn fake.runArgsForCall[i].cmd\n}"} {"input": "package main\n\nimport (\n\t\"github.com/robfig/cron\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\nvar (\n\tpid = 0\n\n\thttpPorts = getEnv(\"HTTP_PORTS\", \"80 8080\")\n\ttlsPorts = getEnv(\"TLS_PORTS\", \"443 8443\")\n\n\tswarmRouterPort = getEnv(\"SWARM_ROUTER_PORT\", \"35353\")\n\n\tdefaultBackendPorts = getEnv(\"DEFAULT_BACKEND_PORTS\", \"80 443 8000 8080 8443 9000\")\n\n\toverrideBackendPorts = getEnv(\"OVERRIDE_BACKEND_PORTS\", \"\")\n\n\tbackendsVerifyTLS = getEnv(\"BACKENDS_VERIFY_TLS\", \"\")\n)\n\nfunc getEnv(key, defaultValue string) string {\n\tvalue, exists := os.LookupEnv(key)\n\tif !exists {\n\t\tvalue = defaultValue\n\t\tos.Setenv(key, defaultValue)\n\t}\n\treturn strings.TrimSpace(value)\n}\n\nfunc haproxy(exit chan bool) {\n\tcmd := exec.Command(os.Args[1], os.Args[2:]...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Start(); err != nil {\n\t\tlog.Fatalf(\"Start error: %s\", err.Error())\n\t}\n\tpid = cmd.Process.Pid\n\tlog.Printf(\"Started haproxy master process with pid: %d\", pid)\n\terr := cmd.Wait()\n\tlog.Printf(\"Exit error: %s\", err.Error())\n\texit <- true\n}\n\n\n\nfunc main() {\n\tc := cron.New()\n\tc.AddFunc(\"@daily\", reload)\n\tc.Start()\n\texit := make(chan bool, 1)\n\tgo router(exit, swarmRouterPort)\n\tgo haproxy(exit)\n\t<-exit\n}\n\nfunc init() ", "output": "{\n\texecuteTemplate(\"/usr/local/etc/haproxy/haproxy.tmpl\", \"/usr/local/etc/haproxy/haproxy.cfg\")\n}"} {"input": "package models\n\nimport (\n\t\"github.com/3xxx/engineercms/controllers/tool/result\"\n\t\"github.com/nu7hatch/gouuid\"\n\t\"time\"\n)\n\n\ntype Bridge struct {\n\tId uint `json:\"id\" gorm:\"primary_key\"`\n\tUuid string `json:\"uuid\" gorm:\"type:char(36);index:idx_uuid\"`\n\tCreatedAt time.Time\n\tUpdatedAt time.Time\n\tShareUuid string `json:\"shareUuid\" gorm:\"type:char(36)\"`\n\tProductId int64 `json:\"productid\" gorm:\"type:bigint(20) not null;default:0\"`\n}\n\ntype OrderPair struct {\n\tKey string\n\tValue string\n}\n\ntype WherePair struct {\n\tQuery string\n\tArgs []interface{}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Pager struct {\n\tPage int `json:\"page\"`\n\tPageSize int `json:\"pageSize\"`\n\tTotalItems int `json:\"totalItems\"`\n\tTotalPages int `json:\"totalPages\"`\n\tData interface{} `json:\"data\"`\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc FindByShareUuid(shareUuid string) ([]*Bridge, error) {\n\tif shareUuid == \"\" {\n\t\tpanic(result.BadRequest(\"shareUuid cannot be nil\"))\n\t}\n\tvar bridges []*Bridge\n\tdb := GetDB().Table(\"share_bridge\").\n\t\tWhere(\"share_uuid = ?\", shareUuid).\n\t\tFind(&bridges)\n\treturn bridges, db.Error\n}\n\nfunc CreateBridge(bridge *Bridge) (*Bridge, error) ", "output": "{\n\tdb := GetDB()\n\ttimeUUID, _ := uuid.NewV4()\n\tbridge.Uuid = string(timeUUID.String())\n\tbridge.CreatedAt = time.Now()\n\tbridge.UpdatedAt = time.Now()\n\tdb = db.Table(\"share_bridge\").Create(&bridge)\n\treturn bridge, db.Error\n}"} {"input": "package libchorizo\n\nimport (\n\t\"code.google.com/p/gcfg\"\n\t\"fmt\"\n)\n\ntype ChorizoConfig interface {\n\tInterpolateConfig(config_file_path string) (Config)\n}\n\ntype Config struct {\n\tMain struct {\n\t\tDbfile string\n\t\tDebug bool\n\t\tCronfile string\n\t\tStatefile string\n\t\tLockfile string\n\t\tScriptpath string\n\t\tAPIUrl string\n\t\tLoglevel string\n\t\tExecPath string\n\t\tConfigPath string\n\t\tRabbitmqHost string\n\t\tRabbitmqPort string\n\t\tRabbitmqUser string\n\t\tRabbitmqPass string\n\t\tUseTls bool\n\t}\n}\n\nfunc (cfg Config) NewConfig(exec_path string) (Config){\n\tcfg.Main.ExecPath = exec_path\n\tcfg.Main.ConfigPath = fmt.Sprintf(\"%s/chorizo.gcfg\", cfg.Main.ExecPath)\n\terr := gcfg.ReadFileInto(&cfg, cfg.Main.ConfigPath)\n\tcfg.Main.Dbfile = fmt.Sprintf(\"%s/%s\", exec_path, cfg.Main.Dbfile)\n\tcfg.Main.Cronfile = fmt.Sprintf(\"%s/%s\", exec_path, cfg.Main.Cronfile)\n\tcfg.Main.Scriptpath = fmt.Sprintf(\"%s/%s\", exec_path, cfg.Main.Scriptpath)\n\tcfg.Main.Statefile = fmt.Sprintf(\"%s/%s\", exec_path, cfg.Main.Statefile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn cfg\n\n}\n\ntype inConfig struct{}\n\nfunc (ChorizoConfig inConfig) InterpolateConfig(config_file_path string) (Config) {\n\tvar cfg Config\n\treturn cfg\n}\n\nfunc (ChorizoConfig Config) InterpolateConfig(config_file_path string) (Config) {\n\tvar cfg Config\n\treturn cfg\n}\n\n\n\nfunc ParseConfig(exec_path string) (Config, error) ", "output": "{\n\tvar CONFIGPATH = fmt.Sprintf(\"%s/chorizo.gcfg\", exec_path)\n\tvar cfg Config\n\terr := gcfg.ReadFileInto(&cfg, CONFIGPATH)\n\tcfg.InterpolateConfig(CONFIGPATH)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn cfg, err\n}"} {"input": "package mocks\n\nimport (\n\tcli \"github.com/stackanetes/kubernetes-entrypoint/client\"\n)\n\ntype MockEntrypoint struct {\n\tclient cli.ClientInterface\n\tnamespace string\n}\n\nfunc (m MockEntrypoint) Resolve() {\n}\n\nfunc (m MockEntrypoint) Client() (client cli.ClientInterface) {\n\treturn m.client\n}\n\nfunc (m MockEntrypoint) GetNamespace() (namespace string) {\n\treturn m.namespace\n}\n\nfunc NewEntrypointInNamespace(namespace string) MockEntrypoint {\n\treturn MockEntrypoint{\n\t\tclient: NewClient(),\n\t\tnamespace: namespace,\n\t}\n}\n\n\n\nfunc NewEntrypoint() MockEntrypoint ", "output": "{\n\treturn NewEntrypointInNamespace(\"test\")\n}"} {"input": "package dnsrecorder\n\nimport (\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n)\n\n\n\n\n\n\n\ntype Recorder struct {\n\tdns.ResponseWriter\n\tRcode int\n\tSize int\n\tMsg *dns.Msg\n\tStart time.Time\n}\n\n\n\n\nfunc New(w dns.ResponseWriter) *Recorder {\n\treturn &Recorder{\n\t\tResponseWriter: w,\n\t\tRcode: 0,\n\t\tMsg: nil,\n\t\tStart: time.Now(),\n\t}\n}\n\n\n\nfunc (r *Recorder) WriteMsg(res *dns.Msg) error {\n\tr.Rcode = res.Rcode\n\tr.Size += res.Len()\n\tr.Msg = res\n\treturn r.ResponseWriter.WriteMsg(res)\n}\n\n\n\n\n\n\nfunc (r *Recorder) Hijack() { r.ResponseWriter.Hijack(); return }\n\nfunc (r *Recorder) Write(buf []byte) (int, error) ", "output": "{\n\tn, err := r.ResponseWriter.Write(buf)\n\tif err == nil {\n\t\tr.Size += n\n\t}\n\treturn n, err\n}"} {"input": "package v1alpha1\n\nimport (\n\t\"sort\"\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n)\n\nfunc TestNewVerificationClaims(t *testing.T) {\n\tt.Parallel()\n\n\tgot := NewVerificationClaims()\n\twant := &VerificationClaims{\n\t\tTransmissionRisks: []TransmissionRiskOverride{},\n\t}\n\n\tif diff := cmp.Diff(want, got); diff != \"\" {\n\t\tt.Errorf(\"mismatch (-want +got):\\n%v\", diff)\n\t}\n}\n\n\n\nfunc TestTransmissionRiskVectorSort(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\tgot := TransmissionRiskVector{\n\t\t{0, 0},\n\t\t{3, 100},\n\t\t{5, 200},\n\t}\n\tsort.Sort(got)\n\n\twant := TransmissionRiskVector{{5, 200}, {3, 100}, {0, 0}}\n\n\tif diff := cmp.Diff(want, got); diff != \"\" {\n\t\tt.Errorf(\"sort(TransmissionRiskVector) mismatch (-want +got):\\n%v\", diff)\n\t}\n}"} {"input": "package steps\n\nimport (\n\t\"time\"\n\n\t\"github.com/intel-hpdd/lemur/uat/harness\"\n)\n\n\n\nfunc iConfigureADataMover(dmType string) error {\n\treturn harness.AddConfiguredMover(ctx, harness.HsmPluginPrefix+dmType+\".race\")\n}\n\nfunc theDataMoverShouldBe(dmType, state string) error {\n\ttime.Sleep(1 * time.Second)\n\n\tdmStatus := func() error {\n\t\treturn checkProcessState(harness.HsmPluginPrefix+dmType+\".race\", state, -1)\n\t}\n\treturn waitFor(dmStatus, DefaultTimeout)\n}\n\nfunc init() ", "output": "{\n\taddStep(`^I configure the (posix|s3) data mover$`, iConfigureADataMover)\n\taddStep(`^the (posix|s3) data mover should be (running|stopped)$`, theDataMoverShouldBe)\n}"} {"input": "package conf\n\nimport (\n\t\"github.com/sirupsen/logrus\"\n)\n\n\ntype Logger struct {\n\tLevel string `yaml:\"level\" default:\"info\"`\n\tFormat string `yaml:\"format\" default:\"text\"`\n}\n\n\n\nfunc (c Logger) Configure() {\n\tSetFormatter(c.Format)\n\tSetLogLevel(c.Level)\n}\n\n\n\nfunc SetLogLevel(lvl string) {\n\tl, err := logrus.ParseLevel(lvl)\n\tif err != nil {\n\t\tlogrus.WithField(\"provided\", lvl).Warn(\"Invalid log level, fallback to Info level\")\n\t\tlogrus.SetLevel(logrus.InfoLevel)\n\t} else {\n\t\tlogrus.SetLevel(l)\n\t}\n}\n\n\n\n\nfunc SetFormatter(format string) ", "output": "{\n\tswitch format {\n\tcase \"json\":\n\t\tlogrus.SetFormatter(&logrus.JSONFormatter{})\n\tcase \"text\":\n\t\tlogrus.SetFormatter(&logrus.TextFormatter{})\n\tdefault:\n\t\tlogrus.SetFormatter(&logrus.TextFormatter{})\n\t}\n}"} {"input": "package client \n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/docker/docker/errdefs\"\n\t\"gotest.tools/assert\"\n\tis \"gotest.tools/assert/cmp\"\n)\n\nfunc TestSecretRemoveUnsupported(t *testing.T) {\n\tclient := &Client{\n\t\tversion: \"1.24\",\n\t\tclient: &http.Client{},\n\t}\n\terr := client.SecretRemove(context.Background(), \"secret_id\")\n\tassert.Check(t, is.Error(err, `\"secret remove\" requires API version 1.25, but the Docker daemon API version is 1.24`))\n}\n\n\n\nfunc TestSecretRemove(t *testing.T) {\n\texpectedURL := \"/v1.25/secrets/secret_id\"\n\n\tclient := &Client{\n\t\tversion: \"1.25\",\n\t\tclient: newMockClient(func(req *http.Request) (*http.Response, error) {\n\t\t\tif !strings.HasPrefix(req.URL.Path, expectedURL) {\n\t\t\t\treturn nil, fmt.Errorf(\"Expected URL '%s', got '%s'\", expectedURL, req.URL)\n\t\t\t}\n\t\t\tif req.Method != http.MethodDelete {\n\t\t\t\treturn nil, fmt.Errorf(\"expected DELETE method, got %s\", req.Method)\n\t\t\t}\n\t\t\treturn &http.Response{\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tBody: ioutil.NopCloser(bytes.NewReader([]byte(\"body\"))),\n\t\t\t}, nil\n\t\t}),\n\t}\n\n\terr := client.SecretRemove(context.Background(), \"secret_id\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestSecretRemoveError(t *testing.T) ", "output": "{\n\tclient := &Client{\n\t\tversion: \"1.25\",\n\t\tclient: newMockClient(errorMock(http.StatusInternalServerError, \"Server error\")),\n\t}\n\n\terr := client.SecretRemove(context.Background(), \"secret_id\")\n\tif !errdefs.IsSystem(err) {\n\t\tt.Fatalf(\"expected a Server Error, got %[1]T: %[1]v\", err)\n\t}\n}"} {"input": "package mock\n\nimport (\n\t\"github.com/fkmhrk/OpenInvoice/v1/model/env\"\n)\n\ntype EnvDAO struct {\n\tCreateResult env.Env\n\tGetResult env.Env\n\tGetListResult []*env.Env\n\tSaveResult error\n\tUpdateResult env.Env\n\tDeleteResult env.Env\n}\n\nfunc (d *EnvDAO) Create(key, value string) (env.Env, error) {\n\treturn d.CreateResult, nil\n}\n\nfunc (d *EnvDAO) Get(key string) (env.Env, error) {\n\treturn d.GetResult, nil\n}\n\nfunc (d *EnvDAO) GetList() ([]*env.Env, error) {\n\treturn d.GetListResult, nil\n}\n\nfunc (d *EnvDAO) Save(list []*env.Env) error {\n\treturn d.SaveResult\n}\n\nfunc (d *EnvDAO) Update(key, value string) (env.Env, error) {\n\treturn d.UpdateResult, nil\n}\n\n\n\nfunc (d *EnvDAO) Delete(key string) (env.Env, error) ", "output": "{\n\treturn d.DeleteResult, nil\n}"} {"input": "package mocks\n\nimport \"github.com/myshkin5/jsonstruct\"\n\ntype MockWriter struct {\n\tMessages chan []byte\n}\n\nfunc NewMockWriter() *MockWriter {\n\treturn &MockWriter{\n\t\tMessages: make(chan []byte, 10000),\n\t}\n}\n\nfunc (m *MockWriter) Init(config jsonstruct.JSONStruct) error {\n\treturn nil\n}\n\nfunc (m *MockWriter) Write(message []byte) (int, error) {\n\tm.Messages <- message\n\treturn len(message), nil\n}\n\n\n\nfunc (m *MockWriter) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package gol\n\nimport (\n\t\"errors\"\n\n\t\"github.com/philchia/gol/adapter\"\n)\n\n\n\n\n\nfunc (l *gollog) RemoveAdapter(name string) error {\n\tif _, ok := l.adapters[name]; !ok {\n\t\treturn errors.New(\"Adapter not exists\")\n\t}\n\n\ttmpAdapters := make(map[string]adapter.Adapter, len(l.adapters)-1)\n\n\tfor k, v := range l.adapters {\n\t\tif k != name {\n\t\t\ttmpAdapters[k] = v\n\t\t}\n\t}\n\n\tl.adapters = tmpAdapters\n\n\treturn nil\n}\n\nfunc (l *gollog) AddLogAdapter(name string, adp adapter.Adapter) error ", "output": "{\n\tif adp == nil {\n\t\treturn errors.New(\"nil adapter\")\n\t}\n\tif _, ok := l.adapters[name]; ok {\n\n\t\treturn errors.New(\"Adapter already exists\")\n\t}\n\n\ttmpAdapters := make(map[string]adapter.Adapter, len(l.adapters)+1)\n\n\tfor k, v := range l.adapters {\n\t\ttmpAdapters[k] = v\n\t}\n\n\ttmpAdapters[name] = adp\n\tl.adapters = tmpAdapters\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype dumpXLIFF struct {\n\tinFile string\n}\n\nfunc init() {\n\tregisteredConverters[\"dump\"] = new(dumpXLIFF)\n}\n\nfunc (d *dumpXLIFF) Description() string {\n\treturn \"Dumps XLIFF as parsed\"\n}\n\nfunc (d *dumpXLIFF) ParseArgs(base string, args []string) error {\n\tvar fs = flag.NewFlagSet(base+\" dump\", flag.ExitOnError)\n\tfs.StringVar(&d.inFile, \"in\", \"\", \"infile\")\n\treturn fs.Parse(args)\n}\n\nfunc (d *dumpXLIFF) Prepare() error {\n\treturn nil\n}\n\n\n\nfunc (d *dumpXLIFF) Convert(w io.Writer) error ", "output": "{\n\n\tvar doc, err = xliffFromFile(d.inFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, file := range doc.File {\n\n\t\tfor _, unit := range file.Body.TransUnit {\n\n\t\t\tfmt.Fprintf(w, \"unit %s\\n\", unit.ID)\n\t\t\tfmt.Fprintf(w, \" source: %v\\n\", unit.Source)\n\t\t\tfmt.Fprintf(w, \" target: %v\\n\", unit.Target)\n\n\t\t}\n\t}\n\n\treturn err\n}"} {"input": "package events\n\nimport (\n\t\"github.com/mesos/mesos-go/executor\"\n)\n\ntype (\n\tDecorator func(Handler) Handler\n\n\tDecorators []Decorator\n)\n\nvar noopDecorator = Decorator(func(h Handler) Handler { return h })\n\n\n\nfunc (d Decorator) If(b bool) Decorator {\n\tif d == nil {\n\t\treturn noopDecorator\n\t}\n\tresult := noopDecorator\n\tif b {\n\t\tresult = d\n\t}\n\treturn result\n}\n\n\n\nfunc (d Decorator) When(f func() bool) Decorator {\n\tif d == nil || f == nil {\n\t\treturn noopDecorator\n\t}\n\treturn func(h Handler) Handler {\n\t\tdecorated := d(h)\n\t\treturn HandlerFunc(func(e *executor.Event) (err error) {\n\t\t\tif f() {\n\t\t\t\terr = decorated.HandleEvent(e)\n\t\t\t} else {\n\t\t\t\terr = h.HandleEvent(e)\n\t\t\t}\n\t\t\treturn\n\t\t})\n\t}\n}\n\n\n\n\n\nfunc (d Decorator) Apply(h Handler) Handler {\n\tif d != nil {\n\t\th = d(h)\n\t}\n\treturn h\n}\n\nfunc (ds Decorators) Apply(h Handler) Handler ", "output": "{\n\tfor _, d := range ds {\n\t\th = d.Apply(h)\n\t}\n\treturn h\n}"} {"input": "package testing\n\n\n\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n\tclientset \"k8s.io/kubernetes/pkg/client/clientset_generated/clientset\"\n\tkubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\"\n\tcontainertest \"k8s.io/kubernetes/pkg/kubelet/container/testing\"\n)\n\ntype fakeNetworkHost struct {\n\tfakeNamespaceGetter\n\tkubeClient clientset.Interface\n\tLegacy bool\n\tRuntime *containertest.FakeRuntime\n}\n\nfunc NewFakeHost(kubeClient clientset.Interface) *fakeNetworkHost {\n\thost := &fakeNetworkHost{kubeClient: kubeClient, Legacy: true, Runtime: &containertest.FakeRuntime{}}\n\treturn host\n}\n\nfunc (fnh *fakeNetworkHost) GetPodByName(name, namespace string) (*v1.Pod, bool) {\n\treturn nil, false\n}\n\nfunc (fnh *fakeNetworkHost) GetKubeClient() clientset.Interface {\n\treturn nil\n}\n\n\n\nfunc (nh *fakeNetworkHost) SupportsLegacyFeatures() bool {\n\treturn nh.Legacy\n}\n\ntype fakeNamespaceGetter struct {\n\tns string\n}\n\nfunc (nh *fakeNamespaceGetter) GetNetNS(containerID string) (string, error) {\n\treturn nh.ns, nil\n}\n\nfunc (nh *fakeNetworkHost) GetRuntime() kubecontainer.Runtime ", "output": "{\n\treturn nh.Runtime\n}"} {"input": "package db\n\nimport \"testing\"\n\n\n\nfunc TestObjectToJSON2(t *testing.T) {\n\tvar v *SurveyVar = nil\n\ts := ObjectToJSON(v)\n\tif s != nil {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestObjectToJSON3(t *testing.T) {\n\tv := SurveyVar{\n\t\tName: \"test\",\n\t\tTitle: \"Test\",\n\t}\n\ts := ObjectToJSON(v)\n\tif s == nil || *s != \"{\\\"name\\\":\\\"test\\\",\\\"title\\\":\\\"Test\\\",\\\"required\\\":false,\\\"type\\\":\\\"\\\",\\\"description\\\":\\\"\\\"}\" {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestObjectToJSON(t *testing.T) ", "output": "{\n\tv := &SurveyVar{\n\t\tName: \"test\",\n\t\tTitle: \"Test\",\n\t}\n\ts := ObjectToJSON(v)\n\tif s == nil || *s != \"{\\\"name\\\":\\\"test\\\",\\\"title\\\":\\\"Test\\\",\\\"required\\\":false,\\\"type\\\":\\\"\\\",\\\"description\\\":\\\"\\\"}\" {\n\t\tt.Fail()\n\t}\n}"} {"input": "package shell_local\n\nimport (\n\t\"bytes\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/packer/packer\"\n)\n\n\n\nfunc TestCommunicator(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"windows not supported for this test\")\n\t\treturn\n\t}\n\n\tc := &Communicator{}\n\n\tvar buf bytes.Buffer\n\tcmd := &packer.RemoteCmd{\n\t\tCommand: \"/bin/echo foo\",\n\t\tStdout: &buf,\n\t}\n\n\tif err := c.Start(cmd); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tcmd.Wait()\n\n\tif cmd.ExitStatus != 0 {\n\t\tt.Fatalf(\"err bad exit status: %d\", cmd.ExitStatus)\n\t}\n\n\tif strings.TrimSpace(buf.String()) != \"foo\" {\n\t\tt.Fatalf(\"bad: %s\", buf.String())\n\t}\n}\n\nfunc TestCommunicator_impl(t *testing.T) ", "output": "{\n\tvar _ packer.Communicator = new(Communicator)\n}"} {"input": "package cuckoofilter\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestInsertion(t *testing.T) ", "output": "{\n\n\tcf := NewCuckooFilter(1000000)\n\n\tfd, err := os.Open(\"/usr/share/dict/web2\")\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\tscanner := bufio.NewScanner(fd)\n\n\tvar values [][]byte\n\tfor scanner.Scan() {\n\t\ts := []byte(scanner.Text())\n\t\tcf.InsertUnique(s)\n\t\tvalues = append(values, s)\n\t}\n\n\tcount := cf.Count()\n\tif count != 235081 {\n\t\tt.Errorf(\"Expected count = 235081, instead count = %d\", count)\n\t}\n\n\tfor _, v := range values {\n\t\tcf.Delete(v)\n\t}\n\n\tcount = cf.Count()\n\tif count != 0 {\n\t\tt.Errorf(\"Expected count = 0, instead count == %d\", count)\n\t}\n}"} {"input": "package sync\n\nimport (\n \"ghighlighter/models\"\n \"ghighlighter/readmill/readmillreadings\"\n \"ghighlighter/readmill/readmillhighlights\"\n)\n\n\n\nfunc syncHighlights(accessToken string) {\n highlights := models.Highlights()\n\n tmpItems := make([]models.GhHighlight, len(highlights.Items))\n copy(tmpItems, highlights.Items)\n\n for _, highlight := range tmpItems {\n var highlightComment *readmillhighlights.HighlightComment\n if highlight.Comment != \"\" {\n highlightComment = &readmillhighlights.HighlightComment{highlight.Comment}\n }\n\n readmillHighlight := readmillhighlights.Highlight{highlight.Content,\n highlight.Position, highlight.Timestamp, readmillhighlights.HighlightLocators{}}\n\n success := readmillhighlights.PostHighlight(readmillHighlight, highlightComment, highlight.ReadingReadmillId, accessToken)\n\n if success {\n highlights.Delete(highlight)\n }\n }\n}\n\nfunc syncReadings(userId int, accessToken string) {\n readings := models.Readings()\n readmillReadings := readmillreadings.GetReadings(userId, accessToken)\n\n for _, readmillReading := range readmillReadings {\n title := readmillReading.Book.Title + \" - \" + readmillReading.Book.Author\n reading := models.GhReading{title, readmillReading.Id, 1}\n readings.Add(reading)\n }\n}\n\nfunc Sync() ", "output": "{\n config := models.Config()\n\n syncHighlights(config.AccessToken)\n syncReadings(config.UserId, config.AccessToken)\n}"} {"input": "package texas\n\ntype SeatResultList []*SeatResult\n\ntype SeatResult struct {\n\tm_seat *SeatPlayer\n\tpot_idx int\n\tcard_type int\n\tcard_list CardDataList\n}\n\nfunc NewSeatResult(seat *SeatPlayer, cards []int16) *SeatResult {\n\tthis := new(SeatResult)\n\tthis.m_seat = seat\n\tthis.pot_idx = seat.m_pot_point\n\tthis.card_type, this.card_list = CardTypeOfTexas(cards)\n\treturn this\n}\n\nfunc (this *SeatResult) Trace() {\n\tprintln(\"玩家:\", this.m_seat.m_seat_id, POKER_TYPE_STR[this.card_type], TraceBigCards(this.card_list))\n}\n\n\n\n\n\nfunc (this SeatResultList) Less(i, j int) bool {\n\treturn this[i].card_type > this[j].card_type\n}\n\nfunc (this SeatResultList) Swap(i, j int) {\n\ttemp := this[i]\n\tthis[i] = this[j]\n\tthis[j] = temp\n}\n\nfunc (this SeatResultList) Len() int ", "output": "{\n\treturn len(this)\n}"} {"input": "package cache\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gopkg.in/mgo.v2/bson\"\n\t\"github.com/garyburd/redigo/redis\"\n)\n\nvar (\n\tnewsIndexKeySlice = []string{\"index\", \"ids\", \"jp\"}\n)\n\n\n\n\n\n\nfunc RetrieveCachedNews(key string, redisPool *redis.Pool) ([]bson.ObjectId, error) {\n\tstart := time.Now()\n\tfmt.Println(\"retrieving news index ids from cached news\")\n\tconn := redisPool.Get()\n\tdefer conn.Close()\n\n\tresult, err := redis.Strings(conn.Do(\"LRANGE\", key, 0, -1))\n\tif err != nil {\n\t\tvar x []bson.ObjectId\n\t\treturn x, err\n\t}\n\tfmt.Println(\"indexnewsids took: \", time.Since(start))\n\treversed := ReverseSlice(result...)\n\treturn convStrID(reversed...), nil\n}\n\n\n\nfunc RedisKeyGen(keys ...string) string {\n\treturn strings.Join(keys, \":\")\n}\n\n\nfunc convStrID(IDs ...string) []bson.ObjectId {\n\tvar objID []bson.ObjectId\n\tfor _, i := range IDs {\n\t\tobjID = append(objID, bson.ObjectIdHex(i))\n\t}\n\treturn objID\n}\n\n\nfunc ReverseSlice(s ...string) []string {\n\tfor i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n\t\ts[i], s[j] = s[j], s[i]\n\t}\n\treturn s\n}\n\nfunc IndexNewsIDS(redisPool *redis.Pool, newsIDChan chan []bson.ObjectId) ", "output": "{\n\tstart := time.Now()\n\tfmt.Println(\"retrieving news index ids on TODO\")\n\tconn := redisPool.Get()\n\tdefer conn.Close()\n\n\tkey := RedisKeyGen(newsIndexKeySlice...)\n\tresult, err := redis.Strings(conn.Do(\"LRANGE\", key, 0, -1))\n\tif err != nil {\n\t\tvar x []bson.ObjectId\n\t\tnewsIDChan <- x\n\t}\n\tfmt.Println(\"indexnewsids took: \", time.Since(start))\n\treversed := ReverseSlice(result...)\n\tnewsIDChan <- convStrID(reversed...)\n}"} {"input": "package plugins\n\nimport (\n\t\"../answers\"\n\t\"../ircclient\"\n\t\"strings\"\n)\n\ntype DongPlugin struct {\n\tic *ircclient.IRCClient\n}\n\n\n\nfunc (q *DongPlugin) Info() string {\n\treturn `sends back a dong sound for every \\a`\n}\n\nfunc (q *DongPlugin) Usage(cmd string) string {\n\treturn \"\"\n}\n\nfunc (q *DongPlugin) Register(cl *ircclient.IRCClient) {\n\tq.ic = cl\n}\n\nfunc (q *DongPlugin) Unregister() {\n\treturn\n}\n\nfunc (q *DongPlugin) ProcessLine(msg *ircclient.IRCMessage) {\n\tif msg.Command != \"PRIVMSG\" {\n\t\treturn\n\t}\n\n\tcount := strings.Count(msg.Args[0], `\\a`)\n\tcount -= strings.Count(msg.Args[0], `\\\\a`)\n\tif count < 1 {\n\t\treturn\n\t}\n\n\tstr := answers.RandStr(\"dong\")\n\tmessage := \"\"\n\n\tfor i := 0; i < count; i++ {\n\t\tmessage += str + \" \"\n\t}\n\n\tq.ic.ReplyMsg(msg, message)\n}\n\nfunc (q *DongPlugin) ProcessCommand(cmd *ircclient.IRCCommand) {\n\treturn\n}\n\nfunc (q *DongPlugin) String() string ", "output": "{\n\treturn \"dong\"\n}"} {"input": "package database\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\n\t_ \"github.com/lib/pq\"\n)\n\ntype DB struct {\n\tc *sql.DB\n}\n\n\nfunc Open(dbname, user, password, host string, port int, sslmode string) (db DB, err error) {\n\turl := fmt.Sprintf(\"postgres:%s:%s@%s:%d/%s?sslmode=%s\",\n\t\tuser, password, host, port, dbname, sslmode)\n\tdb.c, err = sql.Open(\"postgres\", url)\n\treturn\n}\n\nfunc (db *DB) Close() {\n\tdb.c.Close()\n}\n\n\n\nfunc (db *DB) SetMaxOpenConns(n int) ", "output": "{\n\tdb.c.SetMaxOpenConns(n)\n}"} {"input": "package config\n\nimport \"github.com/hashicorp/consul/agent/structs\"\n\n\ntype EnterpriseMeta struct{}\n\n\n\ntype EnterpriseDNSConfig struct{}\n\nfunc (_ *EnterpriseMeta) ToStructs() structs.EnterpriseMeta ", "output": "{\n\treturn *structs.DefaultEnterpriseMeta()\n}"} {"input": "package simpleacl\n\nimport \"github.com/youtube/vitess/go/vt/tableacl/acl\"\n\nvar allAcl SimpleAcl\n\nconst all = \"*\"\n\n\ntype SimpleAcl map[string]bool\n\n\nfunc (sacl SimpleAcl) IsMember(principal string) bool {\n\treturn sacl[principal] || sacl[all]\n}\n\n\ntype Factory struct{}\n\n\n\n\n\nfunc (factory *Factory) All() acl.ACL {\n\tif allAcl == nil {\n\t\tallAcl = SimpleAcl(map[string]bool{all: true})\n\t}\n\treturn allAcl\n}\n\n\nfunc (factory *Factory) AllString() string {\n\treturn all\n}\n\n\nvar _ (acl.ACL) = (*SimpleAcl)(nil)\n\n\nvar _ (acl.Factory) = (*Factory)(nil)\n\nfunc (factory *Factory) New(entries []string) (acl.ACL, error) ", "output": "{\n\tacl := SimpleAcl(map[string]bool{})\n\tfor _, e := range entries {\n\t\tacl[e] = true\n\t}\n\treturn acl, nil\n}"} {"input": "package AEDAcrypt\n\nimport \"testing\"\n\nfunc TestEncrypter(t *testing.T) {\n\tvar str string = \"Hello World!\"\n\tstrenc := Encrypter([]byte(str))\n\t_, err := Decrypter(strenc)\n\n\tif err != nil {\n\t\tt.Error(\"Expected 1.5, got \")\n\t}\n}\n\n\n\nfunc TestDecrypter(t *testing.T) ", "output": "{\n\tvar str string = \"Hello World!\"\n\tstrenc := Encrypter([]byte(str))\n\t_, err := Decrypter(strenc)\n\n\tif err != nil {\n\t\tt.Error(\"Expected 1.5, got \")\n\t}\n}"} {"input": "package fate\n\nimport \"testing\"\n\nfunc TestWords(t *testing.T) {\n\tvar tests = []struct {\n\t\tstr string\n\t\texpected []string\n\t}{\n\t\t{\"\", []string{}},\n\t\t{\"one\", []string{\"one\"}},\n\t\t{\"this is a test\", []string{\"this\", \"is\", \"a\", \"test\"}},\n\t\t{\" this is a test \", []string{\"this\", \"is\", \"a\", \"test\"}},\n\t}\n\n\tfor _, tt := range tests {\n\t\tvar words []string\n\n\t\titer := newWords(tt.str)\n\t\tfor iter.Next() {\n\t\t\twords = append(words, iter.Word())\n\t\t}\n\n\t\tif !StrsEqual(words, tt.expected) {\n\t\t\tt.Errorf(\"Words(%v) -> %v, expected %v\", tt.str, words, tt.expected)\n\t\t}\n\t}\n}\n\n\n\nfunc StrsEqual(a []string, b []string) bool ", "output": "{\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}"} {"input": "package archive\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\tmodel \"go-common/app/interface/main/creative/model/archive\"\n\t\"go-common/library/database/sql\"\n\t\"go-common/library/log\"\n)\n\nconst (\n\t_bizsByTimeSQL = \"SELECT aid,type,ctime FROM archive_biz WHERE mtime >= ? AND mtime < ? AND type = ? ORDER BY mtime\"\n)\n\n\n\n\nfunc (d *Dao) BIZsByTime(c context.Context, start, end *time.Time, tp int8) (bizs []*model.BIZ, err error) ", "output": "{\n\tvar rows *sql.Rows\n\tif rows, err = d.db.Query(c, _bizsByTimeSQL, start, end, tp); err != nil {\n\t\tlog.Error(\"d.db.Query error(%v)\", err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\tbizs = []*model.BIZ{}\n\tfor rows.Next() {\n\t\tvar b = new(model.BIZ)\n\t\tif err = rows.Scan(&b.Aid, &b.Type, &b.Ctime); err != nil {\n\t\t\tlog.Error(\"row.Scan error(%v)\", err)\n\t\t\treturn\n\t\t}\n\t\tbizs = append(bizs, b)\n\t}\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"github.com/bfontaine/classy/jvm\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\n\n\nfunc TestStringFlagsEmptyClass(t *testing.T) ", "output": "{\n\tjc := jvm.JClass{}\n\n\tassert.Equal(t, \"\", stringFlags(&jc))\n}"} {"input": "package test\n\nimport \"io\"\n\n\ntype PlainReader struct {\n\tr io.Reader\n}\n\n\n\n\n\nfunc (r *PlainReader) Read(p []byte) (int, error) {\n\treturn r.r.Read(p)\n}\n\n\n\n\ntype ErrorReader struct {\n\tn int\n}\n\n\nfunc NewErrorReader(n int) *ErrorReader {\n\treturn &ErrorReader{n}\n}\n\n\nfunc (r *ErrorReader) Read(b []byte) (n int, err error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tif r.n == 0 {\n\t\treturn 0, ErrPlain\n\t}\n\tr.n--\n\tb[0] = '.'\n\treturn 1, nil\n}\n\n\n\n\ntype InfiniteReader struct{}\n\n\nfunc NewInfiniteReader() *InfiniteReader {\n\treturn &InfiniteReader{}\n}\n\n\nfunc (r *InfiniteReader) Read(b []byte) (n int, err error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tb[0] = '.'\n\treturn 1, nil\n}\n\n\n\n\ntype EmptyReader struct {\n}\n\n\nfunc NewEmptyReader() *EmptyReader {\n\treturn &EmptyReader{}\n}\n\n\nfunc (r *EmptyReader) Read(b []byte) (n int, err error) {\n\treturn 0, io.EOF\n}\n\nfunc NewPlainReader(r io.Reader) *PlainReader ", "output": "{\n\treturn &PlainReader{r}\n}"} {"input": "package runtime_test\n\nimport (\n\t\"runtime\"\n\t\"sync\"\n\t\"testing\"\n)\n\ntype response struct {\n}\n\ntype myError struct {\n}\n\nfunc (myError) Error() string { return \"\" }\n\nfunc doRequest(useSelect bool) (*response, error) {\n\ttype async struct {\n\t\tresp *response\n\t\terr error\n\t}\n\tch := make(chan *async, 0)\n\tdone := make(chan struct{}, 0)\n\n\tif useSelect {\n\t\tgo func() {\n\t\t\tselect {\n\t\t\tcase ch <- &async{resp: nil, err: myError{}}:\n\t\t\tcase <-done:\n\t\t\t}\n\t\t}()\n\t} else {\n\t\tgo func() {\n\t\t\tch <- &async{resp: nil, err: myError{}}\n\t\t}()\n\t}\n\n\tr := <-ch\n\truntime.Gosched()\n\treturn r.resp, r.err\n}\n\nfunc TestChanSendSelectBarrier(t *testing.T) {\n\ttestChanSendBarrier(true)\n}\n\n\n\nfunc testChanSendBarrier(useSelect bool) {\n\tvar wg sync.WaitGroup\n\tvar globalMu sync.Mutex\n\touter := 100\n\tinner := 100000\n\tif testing.Short() {\n\t\touter = 10\n\t\tinner = 1000\n\t}\n\tfor i := 0; i < outer; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tvar garbage []byte\n\t\t\tfor j := 0; j < inner; j++ {\n\t\t\t\t_, err := doRequest(useSelect)\n\t\t\t\t_, ok := err.(myError)\n\t\t\t\tif !ok {\n\t\t\t\t\tpanic(1)\n\t\t\t\t}\n\t\t\t\tgarbage = make([]byte, 1<<10)\n\t\t\t}\n\t\t\tglobalMu.Lock()\n\t\t\tglobal = garbage\n\t\t\tglobalMu.Unlock()\n\t\t}()\n\t}\n\twg.Wait()\n}\n\nfunc TestChanSendBarrier(t *testing.T) ", "output": "{\n\ttestChanSendBarrier(false)\n}"} {"input": "package primes\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc TestGetAllPrimesTo(t *testing.T) ", "output": "{\n\tprimes := getAllPrimesTo(60)\n\texpected := []int{1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59}\n\tif !reflect.DeepEqual(primes, expected) {\n\t\tfmt.Println(primes)\n\t\tt.Error()\n\t}\n}"} {"input": "package cmd\n\n\ntype readDirOpts struct {\n\tcount int\n\tfollowDirSymlink bool\n}\n\n\n\n\n\nfunc readDirN(dirPath string, count int) (entries []string, err error) {\n\treturn readDirWithOpts(dirPath, readDirOpts{count: count})\n}\n\nfunc readDir(dirPath string) (entries []string, err error) ", "output": "{\n\treturn readDirWithOpts(dirPath, readDirOpts{count: -1})\n}"} {"input": "package get\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewGetWorkflowsLibraryParams() *GetWorkflowsLibraryParams {\n\n\treturn &GetWorkflowsLibraryParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\n\n\n\ntype GetWorkflowsLibraryParams struct {\n\ttimeout time.Duration\n}\n\n\nfunc (o *GetWorkflowsLibraryParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewGetWorkflowsLibraryParamsWithTimeout(timeout time.Duration) *GetWorkflowsLibraryParams ", "output": "{\n\n\treturn &GetWorkflowsLibraryParams{\n\n\t\ttimeout: timeout,\n\t}\n}"} {"input": "package b\n\nimport \"a\"\n\nvar N n\n\ntype n struct{}\n\nfunc (r n) M1() int { return a.G1 }\nfunc (r n) M2() int { return a.G2 }\n\nfunc (r n) M4() int { return a.G4 }\nfunc (r n) M5() int { return a.G5 }\nfunc (r n) M6() int { return a.G6 }\nfunc (r n) M7() int { return a.G7 }\nfunc (r n) M8() int { return a.G8 }\nfunc (r n) M9() int { return a.G9 }\nfunc (r n) M10() int { return a.G10 }\n\nfunc (r n) M3() int ", "output": "{ return a.G3 }"} {"input": "package journal\n\nimport (\n\t\"time\"\n\n\t\"nirenjan.org/overlord/database\"\n\t\"nirenjan.org/overlord/util\"\n)\n\n\n\n\n\ntype DBEntry struct {\n\tTitle string\n\tDate time.Time\n\tTags []string\n\tPath string\n}\n\nvar DB = make(map[string]DBEntry)\n\nfunc BuildDb() error {\n\terr := util.FileWalk(\"journal\", \".entry\", func(path string) error {\n\t\tentry, err1 := entryFromFile(path)\n\t\tif err1 != nil {\n\t\t\treturn err1\n\t\t}\n\n\t\tAddDbEntry(entry)\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn SaveDb()\n}\n\nfunc AddDbEntry(entry Entry) {\n\tvar dbEntry = DBEntry{\n\t\tTitle: entry.Title,\n\t\tDate: entry.Date,\n\t\tTags: entry.Tags,\n\t\tPath: entry.Path,\n\t}\n\n\tid := entry.ID\n\n\tDB[id] = dbEntry\n}\n\nfunc DeleteDbEntry(entry Entry) {\n\tdelete(DB, entry.ID)\n}\n\nfunc SaveDb() error {\n\treturn database.Save(DB)\n}\n\n\n\nfunc LoadDb() error ", "output": "{\n\treturn database.Load(&DB, BuildDb)\n}"} {"input": "package rds\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestDescribeFilesForSQLServer(t *testing.T) ", "output": "{\n\tvar req DescribeFilesForSQLServerRequest\n\treq.Init()\n\treq.SetFormat(\"JSON\")\n\treq.SetRegionId(\"cn-shenzhen\")\n\tvar accessId = \"Ie65kUInu5GeAsma\"\n\tvar accessSecret = \"8cCqoxdYU9zKUihwXFXiN1HEACBDwB\"\n\tresp, err := DescribeFilesForSQLServer(&req, accessId, accessSecret)\n\tif err != nil {\n\t\tt.Errorf(\"Error: %s\", err.Error())\n\t}\n\tfmt.Printf(\"Success: %v\\n\", resp)\n}"} {"input": "package api\n\nimport (\n\t\"log\"\n\t\"testing\"\n)\n\nconst exampleCustomHyperkubeImage = `example.azurecr.io/example/hyperkube-amd64:custom`\n\nconst exampleAPIModel = `{\n\t\t\"apiVersion\": \"vlabs\",\n\t\"properties\": {\n\t\t\"orchestratorProfile\": {\n\t\t\t\"orchestratorType\": \"Kubernetes\",\n\t\t\t\"kubernetesConfig\": {\n\t\t\t\t\"customHyperkubeImage\": \"` + exampleCustomHyperkubeImage + `\"\n\t\t\t}\n\t\t},\n\t\t\"masterProfile\": { \"count\": 1, \"dnsPrefix\": \"\", \"vmSize\": \"Standard_D2_v2\" },\n\t\t\"agentPoolProfiles\": [ { \"name\": \"linuxpool1\", \"count\": 2, \"vmSize\": \"Standard_D2_v2\", \"availabilityProfile\": \"AvailabilitySet\" } ],\n\t\t\"windowsProfile\": { \"adminUsername\": \"azureuser\", \"adminPassword\": \"replacepassword1234$\" },\n\t\t\"linuxProfile\": { \"adminUsername\": \"azureuser\", \"ssh\": { \"publicKeys\": [ { \"keyData\": \"\" } ] }\n\t\t},\n\t\t\"servicePrincipalProfile\": { \"clientId\": \"\", \"secret\": \"\" }\n\t}\n}\n`\n\nfunc TestIsDCOS(t *testing.T) {\n\tdCOSProfile := &OrchestratorProfile{\n\t\tOrchestratorType: \"DCOS\",\n\t}\n\tif !dCOSProfile.IsDCOS() {\n\t\tt.Fatalf(\"unable to detect DCOS orchestrator profile from OrchestratorType=%s\", dCOSProfile.OrchestratorType)\n\t}\n\tkubernetesProfile := &OrchestratorProfile{\n\t\tOrchestratorType: \"Kubernetes\",\n\t}\n\tif kubernetesProfile.IsDCOS() {\n\t\tt.Fatalf(\"unexpectedly detected DCOS orchestrator profile from OrchestratorType=%s\", kubernetesProfile.OrchestratorType)\n\t}\n}\n\n\n\nfunc TestCustomHyperkubeImageField(t *testing.T) ", "output": "{\n\tlog.Println(exampleAPIModel)\n\tapiloader := &Apiloader{\n\t\tTranslator: nil,\n\t}\n\tapimodel, _, err := apiloader.DeserializeContainerService([]byte(exampleAPIModel), false, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpectedly error deserializing the example apimodel: %s\", err)\n\t}\n\n\tactualCustomHyperkubeImage := apimodel.Properties.OrchestratorProfile.KubernetesConfig.CustomHyperkubeImage\n\tif actualCustomHyperkubeImage != exampleCustomHyperkubeImage {\n\t\tt.Fatalf(\"kubernetesConfig->customHyperkubeImage field value was unexpected: got(%s), expected(%s)\", actualCustomHyperkubeImage, exampleCustomHyperkubeImage)\n\t}\n}"} {"input": "package thrift\n\nimport (\n\t\"net\"\n)\n\n\ntype socketConn struct {\n\tnet.Conn\n\n\tbuffer [1]byte\n}\n\nvar _ net.Conn = (*socketConn)(nil)\n\n\n\nfunc createSocketConnFromReturn(conn net.Conn, err error) (*socketConn, error) {\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &socketConn{\n\t\tConn: conn,\n\t}, nil\n}\n\n\nfunc wrapSocketConn(conn net.Conn) *socketConn {\n\tif sc, ok := conn.(*socketConn); ok {\n\t\treturn sc\n\t}\n\n\treturn &socketConn{\n\t\tConn: conn,\n\t}\n}\n\n\n\n\n\n\n\n\nfunc (sc *socketConn) isValid() bool {\n\treturn sc != nil && sc.Conn != nil\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (sc *socketConn) Read(p []byte) (n int, err error) {\n\tif len(p) == 0 {\n\t\treturn 0, sc.read0()\n\t}\n\n\treturn sc.Conn.Read(p)\n}\n\nfunc (sc *socketConn) IsOpen() bool ", "output": "{\n\tif !sc.isValid() {\n\t\treturn false\n\t}\n\treturn sc.checkConn() == nil\n}"} {"input": "package btcec\n\nimport (\n\tsecp \"github.com/decred/dcrd/dcrec/secp256k1/v4\"\n)\n\n\n\ntype JacobianPoint = secp.JacobianPoint\n\n\n\n\n\n\n\nfunc AddNonConst(p1, p2, result *JacobianPoint) {\n\tsecp.AddNonConst(p1, p2, result)\n}\n\n\n\n\n\n\n\n\nfunc DecompressY(x *FieldVal, odd bool, resultY *FieldVal) bool {\n\treturn secp.DecompressY(x, odd, resultY)\n}\n\n\n\n\n\n\nfunc DoubleNonConst(p, result *JacobianPoint) {\n\tsecp.DoubleNonConst(p, result)\n}\n\n\n\n\n\n\nfunc ScalarBaseMultNonConst(k *ModNScalar, result *JacobianPoint) {\n\tsecp.ScalarBaseMultNonConst(k, result)\n}\n\n\n\n\n\n\n\nfunc ScalarMultNonConst(k *ModNScalar, point, result *JacobianPoint) {\n\tsecp.ScalarMultNonConst(k, point, result)\n}\n\nfunc MakeJacobianPoint(x, y, z *FieldVal) JacobianPoint ", "output": "{\n\treturn secp.MakeJacobianPoint(x, y, z)\n}"} {"input": "package iso20022\n\n\ntype FinancialInstrumentDetails24 struct {\n\n\tFinancialInstrumentIdentification *SecurityIdentification19 `xml:\"FinInstrmId\"`\n\n\tFinancialInstrumentAttributes *FinancialInstrumentAttributes63 `xml:\"FinInstrmAttrbts,omitempty\"`\n\n\tSubBalance []*IntraPositionDetails40 `xml:\"SubBal\"`\n}\n\n\n\nfunc (f *FinancialInstrumentDetails24) AddFinancialInstrumentAttributes() *FinancialInstrumentAttributes63 {\n\tf.FinancialInstrumentAttributes = new(FinancialInstrumentAttributes63)\n\treturn f.FinancialInstrumentAttributes\n}\n\nfunc (f *FinancialInstrumentDetails24) AddSubBalance() *IntraPositionDetails40 {\n\tnewValue := new(IntraPositionDetails40)\n\tf.SubBalance = append(f.SubBalance, newValue)\n\treturn newValue\n}\n\nfunc (f *FinancialInstrumentDetails24) AddFinancialInstrumentIdentification() *SecurityIdentification19 ", "output": "{\n\tf.FinancialInstrumentIdentification = new(SecurityIdentification19)\n\treturn f.FinancialInstrumentIdentification\n}"} {"input": "package fabric\n\n\nfunc contains(s []DGNode, i DGNode) bool {\n\tfor _, v := range s {\n\t\tif i.ID() == v.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc containsVirtual(s []Virtual, i Virtual) bool {\n\tfor _, v := range s {\n\t\tif i.ID() == v.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc ContainsNode(l NodeList, n Node) bool {\n\tfor _, v := range l {\n\t\tif v.ID() == n.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\nfunc ContainsEdge(l EdgeList, e Edge) bool ", "output": "{\n\tfor _, v := range l {\n\t\tif v.ID() == e.ID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package app\n\nimport (\n\t\"net/url\"\n)\n\ntype Service interface {\n\tProxyPath() string\n\tURL() string\n\tBasicAuth() (username, password string, ok bool)\n\tAddSecret(parameters url.Values)\n}\n\ntype basicAuthService struct {\n\tproxyPath, url, clientId, clientSecret string\n}\n\nfunc (s basicAuthService) ProxyPath() string {\n\treturn s.proxyPath\n}\n\nfunc (s basicAuthService) URL() string {\n\treturn s.url\n}\n\nfunc (s basicAuthService) BasicAuth() (string, string, bool) {\n\treturn s.clientId, s.clientSecret, true\n}\n\nfunc (s basicAuthService) AddSecret(parameters url.Values) {\n}\n\ntype addParameterService struct {\n\tproxyPath, url, parameterName, clientSecret string\n}\n\nfunc (s addParameterService) ProxyPath() string {\n\treturn s.proxyPath\n}\n\nfunc (s addParameterService) URL() string {\n\treturn s.url\n}\n\nfunc (s addParameterService) BasicAuth() (string, string, bool) {\n\treturn \"\", \"\", false\n}\n\n\n\nfunc BasicAuthService(proxyPath, url, clientId, clientSecret string) Service {\n\treturn basicAuthService{proxyPath, url, clientId, clientSecret}\n}\n\nfunc AddParameterService(proxyPath, url, parameterName, clientSecret string) Service {\n\treturn addParameterService{proxyPath, url, parameterName, clientSecret}\n}\n\nfunc (s addParameterService) AddSecret(parameters url.Values) ", "output": "{\n\tparameters.Add(s.parameterName, s.clientSecret)\n}"} {"input": "package install\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tutilruntime \"k8s.io/apimachinery/pkg/util/runtime\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\n\tappsv1 \"github.com/openshift/api/apps/v1\"\n\tappsapiv1 \"github.com/openshift/origin/pkg/apps/apis/apps/v1\"\n)\n\nfunc init() {\n\tInstall(legacyscheme.Scheme)\n}\n\n\n\n\nfunc Install(scheme *runtime.Scheme) ", "output": "{\n\tutilruntime.Must(appsapiv1.Install(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(appsv1.GroupVersion))\n}"} {"input": "package handler\n\nimport (\n \"net/http\"\n \"io/ioutil\"\n \"path/filepath\"\n \"log\"\n\n \"diserve.didactia.org/lib/util\"\n \"diserve.didactia.org/lib/env\"\n)\n\n\ntype Style struct {\n styles map[string][]byte\n}\n\nfunc (h *Style) ServeHTTP(res http.ResponseWriter, req *http.Request) {\n head, _ := util.ShiftPath(req.URL.Path)\n var data []byte\n var ok bool\n if env.Vars.PRELOADSTYLES {\n data, ok = h.styles[head]\n } else {\n data, ok = getStyle(head)\n }\n if ok {\n res.Header().Set(\"Content-Type\", \"text/css; charset=utf-8\")\n res.Write(data)\n } else {\n http.Error(res, \"Not Found\", http.StatusNotFound)\n }\n}\n\n\nfunc NewStyle() *Style {\n h := &Style{\n styles: nil,\n }\n if env.Vars.PRELOADSTYLES {\n h.styles = getStyles()\n }\n return h\n}\n\n\n\nfunc getStyle(filename string) ([]byte, bool) {\n bytes, err := ioutil.ReadFile(filepath.Join(env.Vars.STYLEPATH, filename))\n if err != nil {\n return nil, false\n }\n return bytes, true\n}\n\nfunc getStyles() map[string][]byte ", "output": "{\n styles := make(map[string][]byte)\n paths, err := filepath.Glob(env.Vars.STYLEPATH + \"*.css\")\n if err != nil {\n log.Fatal(err)\n }\n for _, path := range paths {\n filename := filepath.Base(path)\n bytes, err := ioutil.ReadFile(path)\n if err != nil {\n log.Fatal(err)\n }\n styles[filename] = bytes\n }\n return styles\n}"} {"input": "package project\n\nimport (\n\t\"github.com/postgres-ci/app-server/src/app/middleware\"\n\t\"github.com/postgres-ci/http200ok\"\n)\n\n\n\nfunc Route(server *http200ok.Server) ", "output": "{\n\n\tserver.Get(\"/project-:ProjectID/get/\", getHandler)\n\tserver.Get(\"/project-:ProjectID/builds/\", buildsHandler)\n\tserver.Get(\"/project-:ProjectID/builds/branch-:BranchID/\", buildsHandler)\n\tserver.Get(\"/project-:ProjectID/build-:BuildID/\", viewBuildHandler)\n\tserver.Get(\"/project/possible-owners/\", possibleOwnersHendler)\n\n\tserver.Post(\"/project/add/\", addHandler)\n\tserver.Post(\"/project/update/:ProjectID/\", updateHandler)\n\tserver.Post(\"/project/delete/:ProjectID/\", middleware.CheckPassword, deleteHandler)\n}"} {"input": "package sfproto\n\nimport (\n\t\"github.com/sarifsystems/sarif/sarif\"\n)\n\ntype wrappedConn struct {\n\tid string\n\tConn\n}\n\n\n\nfunc (c *wrappedConn) Subscribe(src, action, dest string) error {\n\tmsg := Subscribe(action, dest)\n\tmsg.Source = src\n\treturn c.Publish(msg)\n}\n\nfunc (c *wrappedConn) Consume() (<-chan sarif.Message, error) {\n\tch := make(chan sarif.Message, 10)\n\n\tgo func() {\n\t\tfor {\n\t\t\tmsg, err := c.Read()\n\t\t\tif err != nil {\n\t\t\t\tclose(ch)\n\t\t\t\tc.Close()\n\t\t\t\tc.Conn = nil\n\t\t\t\treturn\n\t\t\t}\n\t\t\tch <- msg\n\t\t}\n\t}()\n\n\treturn (<-chan sarif.Message)(ch), nil\n}\n\nfunc wrap(conn Conn) sarif.Connection {\n\treturn &wrappedConn{sarif.GenerateId(), conn}\n}\n\nfunc (c *wrappedConn) Publish(msg sarif.Message) error ", "output": "{\n\treturn c.Write(msg)\n}"} {"input": "package client\n\nimport (\n\t\"github.com/docker/notary/client/changelist\"\n\t\"github.com/docker/notary/tuf\"\n\t\"github.com/docker/notary/tuf/data\"\n)\n\n\n\nfunc (r *NotaryRepository) Witness(roles ...data.RoleName) ([]data.RoleName, error) {\n\tvar err error\n\tsuccessful := make([]data.RoleName, 0, len(roles))\n\tfor _, role := range roles {\n\t\tc := changelist.NewTUFChange(\n\t\t\tchangelist.ActionUpdate,\n\t\t\trole,\n\t\t\tchangelist.TypeWitness,\n\t\t\t\"\",\n\t\t\tnil,\n\t\t)\n\t\terr = r.changelist.Add(c)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tsuccessful = append(successful, role)\n\t}\n\treturn successful, err\n}\n\n\n\nfunc witnessTargets(repo *tuf.Repo, invalid *tuf.Repo, role data.RoleName) error ", "output": "{\n\tif r, ok := repo.Targets[role]; ok {\n\t\tr.Dirty = true\n\t\treturn nil\n\t}\n\n\tif roleObj, err := repo.GetDelegationRole(role); err == nil && invalid != nil {\n\t\tif roleObj.Threshold > len(roleObj.Keys) {\n\t\t\treturn data.ErrInvalidRole{\n\t\t\t\tRole: role,\n\t\t\t\tReason: \"role does not specify enough valid signing keys to meet its required threshold\",\n\t\t\t}\n\t\t}\n\t\tif r, ok := invalid.Targets[role]; ok {\n\t\t\trepo.Targets[role] = r\n\t\t\tr.Dirty = true\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn data.ErrInvalidRole{\n\t\tRole: role,\n\t\tReason: \"this role is not known\",\n\t}\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/astaxie/beego\"\n\t\"github.com/dyzdyz010/MartianBlog/models\"\n)\n\ntype FrontController struct {\n\tbeego.Controller\n}\n\n\n\nfunc (this *FrontController) Article() {\n\tid := this.GetString(\"id\")\n\n\tthis.Data[\"json\"] = models.ArticleById(id)\n\tthis.ServeJson()\n}\n\nfunc (this *FrontController) BlogInfo() {\n\tthis.Data[\"json\"] = models.BlogInfo\n\tthis.ServeJson()\n}\n\nfunc (this *FrontController) Articles() ", "output": "{\n\tvar articles []models.Article\n\n\tif status := this.GetString(\"status\"); status != \"\" {\n\t\tarticles = models.ArticlesByStatus(status)\n\t} else {\n\t\tarticles = models.AllArticles()\n\t}\n\n\tthis.Data[\"json\"] = articles\n\tthis.ServeJson()\n}"} {"input": "package drive\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"mime\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\ntype ImportArgs struct {\n\tOut io.Writer\n\tMime string\n\tProgress io.Writer\n\tPath string\n\tParents []string\n}\n\nfunc (self *Drive) Import(args ImportArgs) error {\n\tfromMime := args.Mime\n\tif fromMime == \"\" {\n\t\tfromMime = getMimeType(args.Path)\n\t}\n\tif fromMime == \"\" {\n\t\treturn fmt.Errorf(\"Could not determine mime type of file, use --mime\")\n\t}\n\n\tabout, err := self.service.About.Get().Fields(\"importFormats\").Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to get about: %s\", err)\n\t}\n\n\ttoMimes, ok := about.ImportFormats[fromMime]\n\tif !ok || len(toMimes) == 0 {\n\t\treturn fmt.Errorf(\"Mime type '%s' is not supported for import\", fromMime)\n\t}\n\n\tf, _, err := self.uploadFile(UploadArgs{\n\t\tOut: ioutil.Discard,\n\t\tProgress: args.Progress,\n\t\tPath: args.Path,\n\t\tParents: args.Parents,\n\t\tMime: toMimes[0],\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintf(args.Out, \"Imported %s with mime type: '%s'\\n\", f.Id, toMimes[0])\n\treturn nil\n}\n\n\n\nfunc getMimeType(path string) string ", "output": "{\n\tt := mime.TypeByExtension(filepath.Ext(path))\n\treturn strings.Split(t, \";\")[0]\n}"} {"input": "package statement\n\nimport (\n\t\"time\"\n)\n\n\n\ntype ResponseTime struct {\n\tValue int\n\tTime time.Time\n}\n\n\n\nfunc NewResponseTime(v int) ResponseTime {\n\tr := ResponseTime{Value: v, Time: time.Now()}\n\treturn r\n}\n\n\ntype ResponseTimes []ResponseTime\n\n\n\nfunc (rs ResponseTimes) Len() int {\n\treturn len(rs)\n}\n\n\n\nfunc (rs ResponseTimes) Less(i, j int) bool {\n\treturn rs[i].Value < rs[j].Value\n}\n\n\n\n\n\nfunc (rs ResponseTimes) Swap(i, j int) ", "output": "{\n\trs[i], rs[j] = rs[j], rs[i]\n}"} {"input": "package common\n\nimport (\n\t\"encoding/binary\"\n\t\"sort\"\n)\n\n\n\ntype Uint64Slice []uint64\n\nfunc (p Uint64Slice) Len() int { return len(p) }\nfunc (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] }\nfunc (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p Uint64Slice) Sort() { sort.Sort(p) }\n\nfunc SearchUint64s(a []uint64, x uint64) int {\n\treturn sort.Search(len(a), func(i int) bool { return a[i] >= x })\n}\n\nfunc (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) }\n\n\n\nfunc PutUint64LE(dest []byte, i uint64) {\n\tbinary.LittleEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64LE(src []byte) uint64 {\n\treturn binary.LittleEndian.Uint64(src)\n}\n\nfunc PutUint64BE(dest []byte, i uint64) {\n\tbinary.BigEndian.PutUint64(dest, i)\n}\n\n\n\nfunc PutInt64LE(dest []byte, i int64) {\n\tbinary.LittleEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64LE(src []byte) int64 {\n\treturn int64(binary.LittleEndian.Uint64(src))\n}\n\nfunc PutInt64BE(dest []byte, i int64) {\n\tbinary.BigEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64BE(src []byte) int64 {\n\treturn int64(binary.BigEndian.Uint64(src))\n}\n\nfunc GetUint64BE(src []byte) uint64 ", "output": "{\n\treturn binary.BigEndian.Uint64(src)\n}"} {"input": "package airplane_mode\n\nfunc getRadioModule(key RadioType) BaseRadioModule {\n\tvar module BaseRadioModule\n\tswitch key {\n\tcase BluetoothRadioType:\n\t\tmodule = &BluetoothRadio{GeneralRadioModule{typ: BluetoothRadioType, name: \"bluetooth\"}}\n\tcase WlanRadioType:\n\t\tmodule = &WlanRadio{GeneralRadioModule{typ: WlanRadioType, name: \"wlan\"}}\n\tcase AllRadioType:\n\t\tmodule = &AllRadio{GeneralRadioModule{typ: AllRadioType, name: \"all\"}}\n\tdefault:\n\t\tpanic(\"radio type not exist\")\n\t}\n\treturn module\n}\n\ntype GeneralRadioModule struct {\n\ttyp RadioType\n\tname string\n}\n\nfunc (Op *GeneralRadioModule) Type() RadioType {\n\treturn Op.typ\n}\n\nfunc (Op *GeneralRadioModule) Module() string {\n\treturn Op.name\n}\n\nfunc (Op *GeneralRadioModule) Len() int {\n\tstate, err := rfkillState(Op.typ)\n\tif err != nil {\n\t\tlogger.Warningf(\"check rfkill blocked state failed, err: %v\", err)\n\t\tstate.count = 0\n\t}\n\treturn state.count\n}\n\n\n\nfunc (Op *GeneralRadioModule) Unblock() error {\n\treturn rfkillAction(Op.typ, UnblockRadioAction)\n}\n\nfunc (Op *GeneralRadioModule) IsBlocked() bool {\n\tstate, err := rfkillState(Op.typ)\n\tif err != nil {\n\t\tlogger.Warningf(\"check rfkill blocked state failed, err: %v\", err)\n\t\tstate.blocked = false\n\t}\n\treturn state.blocked\n}\n\n\ntype BluetoothRadio struct {\n\tGeneralRadioModule\n}\n\n\ntype WlanRadio struct {\n\tGeneralRadioModule\n}\n\n\ntype AllRadio struct {\n\tGeneralRadioModule\n}\n\nfunc (Op *GeneralRadioModule) Block() error ", "output": "{\n\treturn rfkillAction(Op.typ, BlockRadioAction)\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realInternetGateway InternetGateway\n\n\nfunc (o *InternetGateway) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realInternetGateway\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = InternetGateway(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &InternetGateway{}\n\n\nfunc (o *InternetGateway) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\n\nfunc (o *InternetGateway) SetLifecycle(lifecycle fi.Lifecycle) {\n\to.Lifecycle = &lifecycle\n}\n\nvar _ fi.HasName = &InternetGateway{}\n\n\n\n\n\nfunc (o *InternetGateway) SetName(name string) {\n\to.Name = &name\n}\n\n\nfunc (o *InternetGateway) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *InternetGateway) GetName() *string ", "output": "{\n\treturn o.Name\n}"} {"input": "package atomic\n\nimport (\n\t\"encoding/json\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\n\ntype Uint32 struct {\n\t_ nocmp \n\n\tv uint32\n}\n\n\nfunc NewUint32(val uint32) *Uint32 {\n\treturn &Uint32{v: val}\n}\n\n\nfunc (i *Uint32) Load() uint32 {\n\treturn atomic.LoadUint32(&i.v)\n}\n\n\nfunc (i *Uint32) Add(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, delta)\n}\n\n\nfunc (i *Uint32) Sub(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, ^(delta - 1))\n}\n\n\nfunc (i *Uint32) Inc() uint32 {\n\treturn i.Add(1)\n}\n\n\nfunc (i *Uint32) Dec() uint32 {\n\treturn i.Sub(1)\n}\n\n\nfunc (i *Uint32) CAS(old, new uint32) (swapped bool) {\n\treturn atomic.CompareAndSwapUint32(&i.v, old, new)\n}\n\n\nfunc (i *Uint32) Store(val uint32) {\n\tatomic.StoreUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) Swap(val uint32) (old uint32) {\n\treturn atomic.SwapUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(i.Load())\n}\n\n\n\n\n\nfunc (i *Uint32) String() string {\n\tv := i.Load()\n\treturn strconv.FormatUint(uint64(v), 10)\n}\n\nfunc (i *Uint32) UnmarshalJSON(b []byte) error ", "output": "{\n\tvar v uint32\n\tif err := json.Unmarshal(b, &v); err != nil {\n\t\treturn err\n\t}\n\ti.Store(v)\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/devfeel/dotweb\"\n\t\"github.com/devfeel/dotweb/cache\"\n\t\"github.com/devfeel/dotweb/framework/file\"\n\t\"strconv\"\n)\n\nfunc main() {\n\tapp := dotweb.New()\n\n\tapp.SetLogPath(file.GetCurrentDirectory())\n\n\n\tInitRoute(app.HttpServer)\n\n\n\tapp.SetCache(cache.NewRuntimeCache())\n\n\terr := app.Cache().Set(\"g\", \"gv\", 20)\n\tif err != nil {\n\t\tfmt.Println(\"Cache Set \", err)\n\t}\n\n\tport := 8080\n\tfmt.Println(\"dotweb.StartServer => \" + strconv.Itoa(port))\n\terr = app.StartServer(port)\n\tfmt.Println(\"dotweb.StartServer error => \", err)\n}\n\ntype UserInfo struct {\n\tUserName string\n\tSex int\n}\n\n\n\nfunc Two(ctx dotweb.Context) error {\n\tg, err := ctx.Cache().GetString(\"g\")\n\tif err != nil {\n\t\tg = err.Error()\n\t}\n\t_, err = ctx.Cache().Incr(\"count\")\n\tc, _ := ctx.Cache().GetString(\"count\")\n\treturn ctx.WriteString(\"Two [\" + g + \"] [\" + c + \"] \" + fmt.Sprint(err))\n}\n\nfunc InitRoute(server *dotweb.HttpServer) {\n\tserver.Router().GET(\"/1\", One)\n\tserver.Router().GET(\"/2\", Two)\n}\n\nfunc One(ctx dotweb.Context) error ", "output": "{\n\tg, err := ctx.Cache().GetString(\"g\")\n\tif err != nil {\n\t\tg = err.Error()\n\t}\n\t_, err = ctx.Cache().Incr(\"count\")\n\treturn ctx.WriteString(\"One [\" + g + \"] \" + fmt.Sprint(err))\n}"} {"input": "package context\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\n\n\n\n\n\n\nfunc GetStringValue(ctx context.Context, key interface{}) (value string) {\n\tif valuev, ok := ctx.Value(key).(string); ok {\n\t\tvalue = valuev\n\t}\n\treturn value\n}\n\nfunc Since(ctx context.Context, key interface{}) time.Duration ", "output": "{\n\tif startedAt, ok := ctx.Value(key).(time.Time); ok {\n\t\treturn time.Since(startedAt)\n\t}\n\treturn 0\n}"} {"input": "package driverskeleton\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"periph.io/x/periph\"\n\t\"periph.io/x/periph/conn/i2c/i2ctest\"\n)\n\nfunc TestDriverSkeleton(t *testing.T) {\n\tbus := i2ctest.Playback{\n\t\tOps: []i2ctest.IO{\n\t\t\t{Addr: 42, W: []byte(\"in\"), R: []byte(\"IN\")},\n\t\t\t{Addr: 42, W: []byte(\"what\"), R: []byte(\"Hello world!\")},\n\t\t},\n\t\tDontPanic: true,\n\t}\n\tdev, err := New(&bus)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif data := dev.Read(); data != \"Hello world!\" {\n\t\tt.Fatal(data)\n\t}\n\n\tif data := dev.Read(); !strings.HasPrefix(data, \"i2ctest: unexpected Tx()\") {\n\t\tt.Fatal(data)\n\t}\n}\n\nfunc TestDriverSkeleton_empty(t *testing.T) {\n\tif dev, err := New(&i2ctest.Playback{DontPanic: true}); dev != nil || err == nil {\n\t\tt.Fatal(\"Tx should have failed\")\n\t}\n}\n\n\n\nfunc TestInit(t *testing.T) {\n\tif state, err := periph.Init(); err != nil {\n\t\tt.Fatal(state, err)\n\t}\n}\n\nfunc TestDriverSkeleton_init_failed(t *testing.T) ", "output": "{\n\tbus := i2ctest.Playback{\n\t\tOps: []i2ctest.IO{\n\t\t\t{Addr: 42, W: []byte(\"in\"), R: []byte(\"xx\")},\n\t\t},\n\t}\n\tif dev, err := New(&bus); dev != nil || err == nil {\n\t\tt.Fatal(\"New should have failed\")\n\t}\n}"} {"input": "package test\n\nimport (\n\t\"arduino.cc/builder\"\n\t\"arduino.cc/builder/types\"\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\"\n)\n\nfunc TestFailIfBuildPathEqualsSketchPath(t *testing.T) {\n\tctx := &types.Context{\n\t\tSketchLocation: \"buildPath/sketch.ino\",\n\t\tBuildPath: \"buildPath\",\n\t}\n\n\tcommand := builder.FailIfBuildPathEqualsSketchPath{}\n\trequire.Error(t, command.Run(ctx))\n}\n\n\n\nfunc TestFailIfBuildPathEqualsSketchPathSketchPathDiffers(t *testing.T) ", "output": "{\n\tctx := &types.Context{\n\t\tSketchLocation: \"sketchPath/sketch.ino\",\n\t\tBuildPath: \"buildPath\",\n\t}\n\n\tcommand := builder.FailIfBuildPathEqualsSketchPath{}\n\tNoError(t, command.Run(ctx))\n}"} {"input": "package otlptracegrpc \n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/otel/exporters/otlp/otlptrace\"\n)\n\n\nfunc New(ctx context.Context, opts ...Option) (*otlptrace.Exporter, error) {\n\treturn otlptrace.New(ctx, NewClient(opts...))\n}\n\n\n\n\nfunc NewUnstarted(opts ...Option) *otlptrace.Exporter ", "output": "{\n\treturn otlptrace.NewUnstarted(NewClient(opts...))\n}"} {"input": "package protoio\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\n\t\"github.com/gogo/protobuf/proto\"\n\n\t\"github.com/multiformats/go-varint\"\n)\n\ntype uvarintReader struct {\n\tr *bufio.Reader\n\tbuf []byte\n\tmaxSize int\n\tcloser io.Closer\n}\n\nfunc NewDelimitedReader(r io.Reader, maxSize int) ReadCloser {\n\tvar closer io.Closer\n\tif c, ok := r.(io.Closer); ok {\n\t\tcloser = c\n\t}\n\treturn &uvarintReader{bufio.NewReader(r), nil, maxSize, closer}\n}\n\nfunc (ur *uvarintReader) ReadMsg(msg proto.Message) error {\n\tlength64, err := varint.ReadUvarint(ur.r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlength := int(length64)\n\tif length < 0 || length > ur.maxSize {\n\t\treturn io.ErrShortBuffer\n\t}\n\tif len(ur.buf) < length {\n\t\tur.buf = make([]byte, length)\n\t}\n\tbuf := ur.buf[:length]\n\tif _, err := io.ReadFull(ur.r, buf); err != nil {\n\t\treturn err\n\t}\n\treturn proto.Unmarshal(buf, msg)\n}\n\n\n\nfunc (ur *uvarintReader) Close() error ", "output": "{\n\tif ur.closer != nil {\n\t\treturn ur.closer.Close()\n\t}\n\treturn nil\n}"} {"input": "package wrappers\n\nimport \"github.com/gin-gonic/gin\"\n\n\ntype JSONHandler func(c *gin.Context) (int, interface{})\n\n\ntype StringHandler func(c *gin.Context) (int, string)\n\n\n\n\n\nfunc Text(handler StringHandler) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tstatus, resp := handler(c)\n\t\tc.String(status, resp)\n\t}\n}\n\nfunc JSON(handler JSONHandler) gin.HandlerFunc ", "output": "{\n\treturn func(c *gin.Context) {\n\t\tstatus, resp := handler(c)\n\t\tc.JSON(status, resp)\n\t}\n}"} {"input": "package dexcom\n\nimport (\n\t\"log\"\n\t\"time\"\n)\n\n\n\n\n\nfunc (cgm *CGM) ReadCount(pageType PageType, count int) Records {\n\tfirst, last := cgm.ReadPageRange(pageType)\n\tif cgm.Error() != nil {\n\t\treturn nil\n\t}\n\tresults := make(Records, 0, count)\n\tproc := func(r Record) error {\n\t\tresults = append(results, r)\n\t\tif len(results) == count {\n\t\t\treturn IterationDone\n\t\t}\n\t\treturn nil\n\t}\n\tcgm.IterRecords(pageType, first, last, proc)\n\treturn results\n}\n\n\n\nfunc MergeHistory(slices ...Records) Records {\n\tn := len(slices)\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tif n == 1 {\n\t\treturn slices[0]\n\t}\n\tlength := make([]int, n)\n\ttotal := 0\n\tfor i, v := range slices {\n\t\tlength[i] = len(v)\n\t\ttotal += len(v)\n\t}\n\tresults := make(Records, total)\n\tindex := make([]int, n)\n\tfor next := range results {\n\t\twhich := -1\n\t\tmax := time.Time{}\n\t\tfor i, v := range slices {\n\t\t\tif index[i] < len(v) {\n\t\t\t\tt := v[index[i]].Time()\n\t\t\t\tif t.After(max) {\n\t\t\t\t\twhich = i\n\t\t\t\t\tmax = t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresults[next] = slices[which][index[which]]\n\t\tindex[which]++\n\t}\n\treturn results\n}\n\nfunc (cgm *CGM) ReadHistory(pageType PageType, since time.Time) Records ", "output": "{\n\tfirst, last := cgm.ReadPageRange(pageType)\n\tif cgm.Error() != nil {\n\t\treturn nil\n\t}\n\tvar results Records\n\tproc := func(r Record) error {\n\t\tt := r.Time()\n\t\tif !t.After(since) {\n\t\t\tlog.Printf(\"stopping %v scan at %s\", pageType, t.Format(UserTimeLayout))\n\t\t\treturn IterationDone\n\t\t}\n\t\tresults = append(results, r)\n\t\treturn nil\n\t}\n\tcgm.IterRecords(pageType, first, last, proc)\n\treturn results\n}"} {"input": "package roles\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar TopLevelRoles = map[string]struct{}{\n\t\"root\": {},\n\t\"targets\": {},\n\t\"snapshot\": {},\n\t\"timestamp\": {},\n}\n\nfunc IsTopLevelRole(name string) bool {\n\t_, ok := TopLevelRoles[name]\n\treturn ok\n}\n\nfunc IsDelegatedTargetsRole(name string) bool {\n\treturn !IsTopLevelRole(name)\n}\n\nfunc IsTopLevelManifest(name string) bool {\n\treturn IsTopLevelRole(strings.TrimSuffix(name, \".json\"))\n}\n\n\n\nfunc IsVersionedManifest(name string) bool {\n\tparts := strings.Split(name, \".\")\n\tif len(parts) < 3 {\n\t\treturn false\n\t}\n\n\t_, err := strconv.Atoi(parts[0])\n\treturn err == nil\n}\n\nfunc IsDelegatedTargetsManifest(name string) bool ", "output": "{\n\treturn !IsTopLevelManifest(name)\n}"} {"input": "package backingstore\n\nimport (\n\t\"github.com/gostor/gotgt/pkg/api\"\n\t\"github.com/gostor/gotgt/pkg/scsi\"\n)\n\nfunc init() {\n\tscsi.RegisterBackingStore(\"null\", newNull)\n}\n\ntype NullBackingStore struct {\n\tscsi.BaseBackingStore\n}\n\nfunc newNull() (api.BackingStore, error) {\n\treturn &NullBackingStore{\n\t\tBaseBackingStore: scsi.BaseBackingStore{\n\t\t\tName: \"null\",\n\t\t\tDataSize: 0,\n\t\t\tOflagsSupported: 0,\n\t\t},\n\t}, nil\n}\n\nfunc (bs *NullBackingStore) Open(dev *api.SCSILu, path string) error {\n\treturn nil\n}\n\n\n\nfunc (bs *NullBackingStore) Init(dev *api.SCSILu, Opts string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Exit(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Size(dev *api.SCSILu) uint64 {\n\treturn 0\n}\n\nfunc (bs *NullBackingStore) Read(offset, tl int64) ([]byte, error) {\n\treturn nil, nil\n}\n\nfunc (bs *NullBackingStore) Write(wbuf []byte, offset int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataSync(offset, tl int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataAdvise(offset, length int64, advise uint32) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Unmap([]api.UnmapBlockDescriptor) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Close(dev *api.SCSILu) error ", "output": "{\n\treturn nil\n}"} {"input": "package middleware\n\nimport (\n\t\"testing\"\n\n\t\"net/http\"\n\n\t\"github.com/hellofresh/janus/pkg/test\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestSuccessfulLog(t *testing.T) ", "output": "{\n\tmw := NewLogger()\n\tw, err := test.Record(\n\t\t\"GET\",\n\t\t\"/\",\n\t\tmap[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t},\n\t\tmw.Handler(http.HandlerFunc(test.Ping)),\n\t)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"application/json\", w.Header().Get(\"Content-Type\"))\n}"} {"input": "package model\n\nimport (\n\t\"fmt\"\n\tnative_time \"time\"\n)\n\n\n\n\n\n\n\n\ntype Timestamp int64\n\nconst (\n\tMinimumTick = native_time.Second\n\tsecond = int64(native_time.Second / MinimumTick)\n)\n\n\nfunc (t Timestamp) Equal(o Timestamp) bool {\n\treturn t == o\n}\n\n\nfunc (t Timestamp) Before(o Timestamp) bool {\n\treturn t < o\n}\n\n\nfunc (t Timestamp) After(o Timestamp) bool {\n\treturn t > o\n}\n\n\nfunc (t Timestamp) Add(d native_time.Duration) Timestamp {\n\treturn t + Timestamp(d/MinimumTick)\n}\n\n\nfunc (t Timestamp) Sub(o Timestamp) native_time.Duration {\n\treturn native_time.Duration(t-o) * MinimumTick\n}\n\n\nfunc (t Timestamp) Time() native_time.Time {\n\treturn native_time.Unix(int64(t)/second, (int64(t) % second))\n}\n\n\n\nfunc (t Timestamp) Unix() int64 {\n\treturn int64(t) / second\n}\n\n\nfunc (t Timestamp) String() string {\n\treturn fmt.Sprint(int64(t))\n}\n\n\nfunc Now() Timestamp {\n\treturn TimestampFromTime(native_time.Now())\n}\n\n\n\n\n\nfunc TimestampFromUnix(t int64) Timestamp {\n\treturn Timestamp(t * second)\n}\n\nfunc TimestampFromTime(t native_time.Time) Timestamp ", "output": "{\n\treturn TimestampFromUnix(t.Unix())\n}"} {"input": "package state\n\nimport (\n\t\"strconv\"\n\t. \"bugnuts/maps\"\n\t. \"bugnuts/torus\"\n\t. \"bugnuts/util\"\n)\n\nfunc (s *State) FoodLocations() (l []Location) {\n\tfor loc := range s.Food {\n\t\tl = append(l, Location(loc))\n\t}\n\n\treturn l\n}\n\nfunc (s *State) HillLocations(player int) (l []Location) {\n\tfor loc, hill := range s.Hills {\n\t\tif hill.Player == player && hill.Killed == 0 {\n\t\t\tl = append(l, Location(loc))\n\t\t}\n\t}\n\n\treturn l\n}\n\nfunc (s *State) EnemyHillLocations(player int) (l []Location) {\n\tfor loc, hill := range s.Hills {\n\t\tif hill.Player != player && hill.Killed == 0 {\n\t\t\tl = append(l, Location(loc))\n\t\t}\n\t}\n\n\treturn l\n}\n\nfunc (s *State) ValidStep(loc Location) bool {\n\ti := s.Map.Grid[loc]\n\n\treturn i != WATER && i != BLOCK && i != OCCUPIED && i != FOOD && i != MY_ANT && i != MY_HILLANT\n}\n\nfunc (s *State) Stepable(loc Location) bool {\n\ti := s.Map.Grid[loc]\n\n\treturn i != WATER && i != BLOCK && i != FOOD\n}\n\n\n\nfunc (m *Metrics) DumpSeen() string ", "output": "{\n\tmax := Max(m.Seen)\n\tstr := \"\"\n\n\tfor r := 0; r < m.Rows; r++ {\n\t\tfor c := 0; c < m.Cols; c++ {\n\t\t\tstr += strconv.Itoa(m.Seen[r*m.Cols+c] * 10 / (max + 1))\n\t\t}\n\t\tstr += \"\\n\"\n\t}\n\n\treturn str\n}"} {"input": "package exchange\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\ntype ValidPeriod struct {\n\tdate time.Time\n\texpires time.Time\n}\n\n\n\nfunc NewValidPeriod(date, expires time.Time) ValidPeriod {\n\treturn ValidPeriod{date, expires}\n}\n\n\n\nfunc NewValidPeriodWithLifetime(date time.Time, lifetime time.Duration) ValidPeriod {\n\treturn ValidPeriod{date, date.Add(lifetime)}\n}\n\n\nfunc (vp ValidPeriod) Date() time.Time {\n\treturn vp.date\n}\n\n\nfunc (vp ValidPeriod) Expires() time.Time {\n\treturn vp.expires\n}\n\n\nfunc (vp ValidPeriod) Lifetime() time.Duration {\n\treturn vp.expires.Sub(vp.date)\n}\n\n\n\n\n\n\n\nfunc (vp ValidPeriod) String() string {\n\treturn fmt.Sprintf(\"[%s] to [%s]\", vp.date, vp.expires)\n}\n\nfunc (vp ValidPeriod) Contains(t time.Time) bool ", "output": "{\n\treturn !t.Before(vp.date) && !t.After(vp.expires)\n}"} {"input": "package example\n\nimport (\n\t\"time\"\n\n\t\"github.com/syou6162/go-active-learning/lib/feature\"\n\texample_feature \"github.com/syou6162/go-active-learning/lib/feature/example\"\n\t\"github.com/syou6162/go-active-learning/lib/model\"\n)\n\nfunc NewExample(url string, label model.LabelType) *model.Example {\n\tIsNew := false\n\tif label == model.UNLABELED {\n\t\tIsNew = true\n\t}\n\tnow := time.Now()\n\treturn &model.Example{\n\t\tLabel: label,\n\t\tFv: feature.FeatureVector{},\n\t\tUrl: url,\n\t\tFinalUrl: url,\n\t\tTitle: \"\",\n\t\tDescription: \"\",\n\t\tOgDescription: \"\",\n\t\tOgType: \"\",\n\t\tOgImage: \"\",\n\t\tBody: \"\",\n\t\tScore: 0.0,\n\t\tIsNew: IsNew,\n\t\tStatusCode: 0,\n\t\tFavicon: \"\",\n\t\tErrorCount: 0,\n\t\tCreatedAt: now,\n\t\tUpdatedAt: now,\n\t\tReferringTweets: &model.ReferringTweets{},\n\t\tHatenaBookmark: &model.HatenaBookmark{Bookmarks: make([]*model.Bookmark, 0)},\n\t}\n}\n\nfunc GetStat(examples model.Examples) map[string]int {\n\tstat := make(map[string]int)\n\tfor _, e := range examples {\n\t\tswitch e.Label {\n\t\tcase model.POSITIVE:\n\t\t\tstat[\"positive\"]++\n\t\tcase model.NEGATIVE:\n\t\t\tstat[\"negative\"]++\n\t\tcase model.UNLABELED:\n\t\t\tstat[\"unlabeled\"]++\n\t\t}\n\t}\n\treturn stat\n}\n\n\n\nfunc ExtractFeatures(e model.Example) feature.FeatureVector ", "output": "{\n\tvar fv feature.FeatureVector\n\tfv = append(fv, \"BIAS\")\n\tfv = append(fv, example_feature.ExtractHostFeature(e.FinalUrl))\n\tfv = append(fv, example_feature.ExtractJpnNounFeatures(example_feature.ExtractPath(e.FinalUrl), \"URL\")...)\n\tfv = append(fv, example_feature.ExtractNounFeatures(e.Title, \"TITLE\")...)\n\tfv = append(fv, example_feature.ExtractNounFeatures(e.Description, \"DESCRIPTION\")...)\n\tfv = append(fv, example_feature.ExtractNounFeatures(e.Body, \"BODY\")...)\n\treturn fv\n}"} {"input": "package machine\n\nimport (\n\t\"github.com/juju/cmd\"\n\n\tjujucmd \"github.com/juju/juju/cmd\"\n\t\"github.com/juju/juju/cmd/modelcmd\"\n)\n\nconst showMachineCommandDoc = `\nShow a specified machine on a model. Default format is in yaml,\nother formats can be specified with the \"--format\" option.\nAvailable formats are yaml, tabular, and json\n\nExamples:\n juju show-machine 0\n juju show-machine 1 2 3\n\n`\n\n\nfunc NewShowMachineCommand() cmd.Command {\n\treturn modelcmd.Wrap(newShowMachineCommand(nil))\n}\n\nfunc newShowMachineCommand(api statusAPI) *showMachineCommand {\n\tshowCmd := &showMachineCommand{}\n\tshowCmd.defaultFormat = \"yaml\"\n\tshowCmd.api = api\n\treturn showCmd\n}\n\n\ntype showMachineCommand struct {\n\tbaselistMachinesCommand\n}\n\n\n\n\n\nfunc (c *showMachineCommand) Init(args []string) error {\n\tc.machineIds = args\n\treturn nil\n}\n\nfunc (c *showMachineCommand) Info() *cmd.Info ", "output": "{\n\treturn jujucmd.Info(&cmd.Info{\n\t\tName: \"show-machine\",\n\t\tArgs: \" ...\",\n\t\tPurpose: \"Show a machine's status.\",\n\t\tDoc: showMachineCommandDoc,\n\t})\n}"} {"input": "package ecpedersen\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/xlab-si/emmy/crypto/common\"\n\t\"github.com/xlab-si/emmy/crypto/ec\"\n)\n\n\n\n\nfunc TestPedersenEC(t *testing.T) ", "output": "{\n\treceiver := NewReceiver(ec.P256)\n\tcommitter := NewCommitter(receiver.Params)\n\n\ta := common.GetRandomInt(committer.Params.Group.Q)\n\tc, err := committer.GetCommitMsg(a)\n\tif err != nil {\n\t\tt.Errorf(\"Error in GetCommitMsg: %v\", err)\n\t}\n\n\treceiver.SetCommitment(c)\n\tcommittedVal, r := committer.GetDecommitMsg()\n\tsuccess := receiver.CheckDecommitment(r, committedVal)\n\n\tassert.Equal(t, true, success, \"Pedersen EC commitment failed.\")\n}"} {"input": "package eulerlibs\n\nimport \"testing\"\n\nfunc TestMaxPrimeFactor(t *testing.T) {\n\texpected := 5\n\tactual := MaxPrimeFactor(10)\n\tif expected != actual {\n\t\tt.Errorf(\"(p3) expected:%d - actual:%d\", expected, actual)\n\t}\n}\n\n\n\nfunc BenchmarkPrimeFactor(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tMaxPrimeFactor(600851475143)\n\t}\n}"} {"input": "package console\n\nimport \"github.com/accurateproject/accurate/api/v1\"\n\nfunc init() {\n\tc := &CmdExecuteScheduledActions{\n\t\tname: \"scheduler_execute\",\n\t\trpcMethod: \"ApiV1.ExecuteScheduledActions\",\n\t\trpcParams: &v1.AttrsExecuteScheduledActions{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdExecuteScheduledActions struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrsExecuteScheduledActions\n\t*CommandExecuter\n}\n\nfunc (self *CmdExecuteScheduledActions) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdExecuteScheduledActions) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdExecuteScheduledActions) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrsExecuteScheduledActions{}\n\t}\n\treturn self.rpcParams\n}\n\n\n\nfunc (self *CmdExecuteScheduledActions) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *CmdExecuteScheduledActions) PostprocessRpcParams() error ", "output": "{\n\treturn nil\n}"} {"input": "package playground \n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst baseURL = \"https://play.golang.org\"\n\n\n\nfunc bounce(w http.ResponseWriter, r *http.Request) {\n\tb := new(bytes.Buffer)\n\tif err := passThru(b, r); err != nil {\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treport(r, err)\n\t\treturn\n\t}\n\tio.Copy(w, b)\n}\n\nfunc passThru(w io.Writer, req *http.Request) error {\n\tif req.URL.Path == \"/share\" && !allowShare(req) {\n\t\treturn errors.New(\"Forbidden\")\n\t}\n\tdefer req.Body.Close()\n\turl := baseURL + req.URL.Path\n\tctx, cancel := context.WithTimeout(contextFunc(req), 60*time.Second)\n\tdefer cancel()\n\tr, err := post(ctx, url, req.Header.Get(\"Content-type\"), req.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"making POST request: %v\", err)\n\t}\n\tdefer r.Body.Close()\n\tif _, err := io.Copy(w, r.Body); err != nil {\n\t\treturn fmt.Errorf(\"copying response Body: %v\", err)\n\t}\n\treturn nil\n}\n\nvar onAppengine = false \n\nfunc allowShare(r *http.Request) bool {\n\tif !onAppengine {\n\t\treturn true\n\t}\n\tswitch r.Header.Get(\"X-AppEngine-Country\") {\n\tcase \"\", \"ZZ\", \"CN\":\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc init() ", "output": "{\n\thttp.HandleFunc(\"/compile\", bounce)\n\thttp.HandleFunc(\"/share\", bounce)\n}"} {"input": "package iso20022\n\n\ntype RejectedStatus4 struct {\n\n\tReason *RejectedStatusReason4 `xml:\"Rsn\"`\n\n\tDataSourceScheme *GenericIdentification1 `xml:\"DataSrcSchme\"`\n}\n\n\n\nfunc (r *RejectedStatus4) AddDataSourceScheme() *GenericIdentification1 {\n\tr.DataSourceScheme = new(GenericIdentification1)\n\treturn r.DataSourceScheme\n}\n\nfunc (r *RejectedStatus4) AddReason() *RejectedStatusReason4 ", "output": "{\n\tr.Reason = new(RejectedStatusReason4)\n\treturn r.Reason\n}"} {"input": "package api\n\nimport (\n\t\"bufio\"\n\t\"net/http\"\n\t\"os\"\n\n\tl4g \"code.google.com/p/log4go\"\n\t\"github.com/gorilla/mux\"\n\n\t\"github.com/mattermost/platform/model\"\n\t\"github.com/mattermost/platform/utils\"\n)\n\n\n\nfunc getLogs(c *Context, w http.ResponseWriter, r *http.Request) {\n\n\tif !c.HasSystemAdminPermissions(\"getLogs\") {\n\t\treturn\n\t}\n\n\tvar lines []string\n\n\tif utils.Cfg.LogSettings.FileEnable {\n\n\t\tfile, err := os.Open(utils.Cfg.LogSettings.FileLocation)\n\t\tif err != nil {\n\t\t\tc.Err = model.NewAppError(\"getLogs\", \"Error reading log file\", err.Error())\n\t\t}\n\n\t\tdefer file.Close()\n\n\t\tscanner := bufio.NewScanner(file)\n\t\tfor scanner.Scan() {\n\t\t\tlines = append(lines, scanner.Text())\n\t\t}\n\t} else {\n\t\tlines = append(lines, \"\")\n\t}\n\n\tw.Write([]byte(model.ArrayToJson(lines)))\n}\n\nfunc InitAdmin(r *mux.Router) ", "output": "{\n\tl4g.Debug(\"Initializing admin api routes\")\n\n\tsr := r.PathPrefix(\"/admin\").Subrouter()\n\tsr.Handle(\"/logs\", ApiUserRequired(getLogs)).Methods(\"GET\")\n}"} {"input": "package logs\n\nimport (\n\t\"io\"\n\n\t\"github.com/cloudfoundry/dropsonde/log_sender\"\n\t\"github.com/cloudfoundry/sonde-go/events\"\n)\n\ntype LogSender interface {\n\tSendAppLog(appID, message, sourceType, sourceInstance string) error\n\tSendAppErrorLog(appID, message, sourceType, sourceInstance string) error\n\tScanLogStream(appID, sourceType, sourceInstance string, reader io.Reader)\n\tScanErrorLogStream(appID, sourceType, sourceInstance string, reader io.Reader)\n\tLogMessage(msg []byte, msgType events.LogMessage_MessageType) log_sender.LogChainer\n}\n\nvar logSender LogSender\n\n\n\nfunc Initialize(ls LogSender) {\n\tlogSender = ls\n}\n\n\n\n\nfunc SendAppLog(appID, message, sourceType, sourceInstance string) error {\n\tif logSender == nil {\n\t\treturn nil\n\t}\n\treturn logSender.SendAppLog(appID, message, sourceType, sourceInstance)\n}\n\n\n\n\nfunc SendAppErrorLog(appID, message, sourceType, sourceInstance string) error {\n\tif logSender == nil {\n\t\treturn nil\n\t}\n\treturn logSender.SendAppErrorLog(appID, message, sourceType, sourceInstance)\n}\n\n\n\n\n\n\n\nfunc ScanErrorLogStream(appID, sourceType, sourceInstance string, reader io.Reader) {\n\tif logSender == nil {\n\t\treturn\n\t}\n\tlogSender.ScanErrorLogStream(appID, sourceType, sourceInstance, reader)\n}\n\n\n\nfunc LogMessage(msg []byte, msgType events.LogMessage_MessageType) log_sender.LogChainer {\n\treturn logSender.LogMessage(msg, msgType)\n}\n\nfunc ScanLogStream(appID, sourceType, sourceInstance string, reader io.Reader) ", "output": "{\n\tif logSender == nil {\n\t\treturn\n\t}\n\tlogSender.ScanLogStream(appID, sourceType, sourceInstance, reader)\n}"} {"input": "package customer\n\nimport (\n\t\"github.com/corestoreio/csfw/eav\"\n\t\"github.com/corestoreio/csfw/storage/csdb\"\n)\n\ntype (\n\tAddressModel struct {\n\t}\n)\n\nvar (\n\t_ eav.EntityTypeModeller = (*AddressModel)(nil)\n\t_ eav.EntityTypeTabler = (*AddressModel)(nil)\n\t_ eav.EntityTypeAdditionalAttributeTabler = (*AddressModel)(nil)\n\t_ eav.EntityTypeIncrementModeller = (*AddressModel)(nil)\n)\n\nfunc (c *AddressModel) TBD() {\n\n}\n\n\n\nfunc (c *AddressModel) TableNameValue(i eav.ValueIndex) string {\n\ts, err := GetAddressValueStructure(i)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s.Name\n}\n\n\nfunc (c *AddressModel) TableAdditionalAttribute() (*csdb.Table, error) {\n\treturn TableCollection.Structure(TableIndexEAVAttribute)\n}\n\n\nfunc (c *AddressModel) TableEavWebsite() (*csdb.Table, error) {\n\treturn TableCollection.Structure(TableIndexEAVAttributeWebsite)\n}\n\nfunc Address() *AddressModel {\n\treturn &AddressModel{}\n}\n\nfunc (c *AddressModel) TableNameBase() string ", "output": "{\n\treturn TableCollection.Name(TableIndexAddressEntity)\n}"} {"input": "package bender\n\nimport (\n\t\"log\"\n\n\t\"github.com/pinterest/bender/hist\"\n)\n\n\ntype Recorder func(interface{})\n\n\nfunc Record(c chan interface{}, recorders ...Recorder) {\n\tfor msg := range c {\n\t\tfor _, recorder := range recorders {\n\t\t\trecorder(msg)\n\t\t}\n\t}\n}\n\nfunc logMessage(l *log.Logger, msg interface{}) {\n\tl.Printf(\"%+v\", msg)\n}\n\n\nfunc NewLoggingRecorder(l *log.Logger) Recorder {\n\treturn func(msg interface{}) {\n\t\tlogMessage(l, msg)\n\t}\n}\n\n\n\n\nfunc NewHistogramRecorder(h *hist.Histogram) Recorder ", "output": "{\n\treturn func(msg interface{}) {\n\t\tswitch msg := msg.(type) {\n\t\tcase *StartEvent:\n\t\t\th.Start(int(msg.Start))\n\t\tcase *EndEvent:\n\t\t\th.End(int(msg.End))\n\t\tcase *EndRequestEvent:\n\t\t\telapsed := int(msg.End - msg.Start)\n\t\t\tif msg.Err == nil {\n\t\t\t\th.Add(elapsed)\n\t\t\t} else {\n\t\t\t\th.AddError(elapsed)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package crypto\n\nimport (\n\t\"errors\"\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"encoding/pem\"\n)\n\nfunc LoadRSAPrivateKey(key []byte) (*rsa.PrivateKey, error) {\n\tparsed_key, err := LoadPrivateKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar rsa_private_key *rsa.PrivateKey\n\tvar ok bool = false\n\trsa_private_key, ok = parsed_key.(*rsa.PrivateKey)\n\tif !ok {\n\t\treturn nil, errors.New(\"invalid RSA private key.\")\n\t}\n\n\treturn rsa_private_key, nil\n}\n\n\n\nfunc CreateRSAPrivateKeyPEM(prvkey *rsa.PrivateKey) ([]byte, error) {\n\tder := x509.MarshalPKCS1PrivateKey(prvkey)\n\tdata := pem.EncodeToMemory(\n\t\t&pem.Block{\n\t\t\tType: \"RSA PRIVATE KEY\",\n\t\t\tBytes: der,\n\t\t},\n\t)\n\n\treturn data, nil\n}\n\nfunc CreateRSAPublicKeyPEM(pubkey *rsa.PublicKey) ([]byte, error) {\n\tder, err := x509.MarshalPKIXPublicKey(pubkey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata := pem.EncodeToMemory(\n\t\t&pem.Block{\n\t\t\tType: \"RSA PUBLIC KEY\",\n\t\t\tBytes: der,\n\t\t},\n\t)\n\n\treturn data, nil\n}\n\nfunc LoadRSAPublicKey(key []byte) (*rsa.PublicKey, error) ", "output": "{\n\tparsed_key, err := LoadPublicKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar rsa_public_key *rsa.PublicKey\n\tvar ok bool = false\n\trsa_public_key, ok = parsed_key.(*rsa.PublicKey)\n\tif !ok {\n\t\treturn nil, errors.New(\"invalid RSA public key.\")\n\t}\n\n\treturn rsa_public_key, nil\n}"} {"input": "package file\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\ntype Reader interface {\n\tio.Reader\n\tio.ReaderAt\n\tio.Seeker\n}\n\ntype Writer interface {\n\tio.Writer\n\tio.Seeker\n\tTruncate(size int64) error\n\tSync() error\n}\n\ntype ReadCloser interface {\n\tReader\n\tio.Closer\n}\n\ntype WriteCloser interface {\n\tWriter\n\tio.Closer\n}\n\ntype File interface {\n\tio.Reader\n\tio.Writer\n\tio.Seeker\n\tio.Closer\n\tio.ReaderAt\n\tTruncate(size int64) error\n\tSync() error\n}\n\n\ntype FileSystem interface {\n\tOpen(name string, flag int) (File, error)\n\n\tLock(name string) (io.Closer, error)\n\n\tExists(name string) bool\n\n\tMkdirAll(path string) error\n\n\tList(dir string) ([]string, error)\n\n\tRemove(filename string) error\n\n\tRename(oldpath, newpath string) error\n}\n\ntype osFileSystem struct{}\n\nfunc (osFileSystem) Open(name string, flag int) (File, error) {\n\treturn os.OpenFile(name, flag, 0666)\n}\n\nfunc (osFileSystem) MkdirAll(path string) error {\n\treturn os.MkdirAll(path, 0740)\n}\n\nfunc (osFileSystem) Exists(name string) bool {\n\t_, err := os.Stat(name)\n\treturn err == nil\n}\n\nfunc (osFileSystem) List(dir string) ([]string, error) {\n\tf, err := os.Open(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.Readdirnames(-1)\n}\n\nfunc (osFileSystem) Remove(name string) error {\n\treturn os.Remove(name)\n}\n\n\n\nvar DefaultFileSystem FileSystem = osFileSystem{}\n\nfunc (osFileSystem) Rename(oldpath, newpath string) error ", "output": "{\n\treturn os.Rename(oldpath, newpath)\n}"} {"input": "package errors\n\nimport (\n\t\"sync\"\n)\n\n\n\n\n\n\n\n\n\ntype LazyMultiError interface {\n\tAssign(int, error) bool\n\n\tGetOne(int) error\n\n\tGet() error\n}\n\ntype lazyMultiError struct {\n\tsync.Mutex\n\n\tsize int\n\tme MultiError\n}\n\n\nfunc NewLazyMultiError(size int) LazyMultiError {\n\treturn &lazyMultiError{size: size}\n}\n\nfunc (e *lazyMultiError) Assign(i int, err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\te.Lock()\n\tdefer e.Unlock()\n\tif e.me == nil {\n\t\te.me = make(MultiError, e.size)\n\t}\n\te.me[i] = err\n\treturn true\n}\n\n\n\nfunc (e *lazyMultiError) Get() error {\n\te.Lock()\n\tdefer e.Unlock()\n\tif e.me == nil {\n\t\treturn nil\n\t}\n\treturn e.me\n}\n\nfunc (e *lazyMultiError) GetOne(i int) error ", "output": "{\n\te.Lock()\n\tdefer e.Unlock()\n\tif e.me == nil {\n\t\treturn nil\n\t}\n\treturn e.me[i]\n}"} {"input": "package cloudapi_test\n\nimport (\n\tgc \"launchpad.net/gocheck\"\n\n\t\"github.com/joyent/gosdc/cloudapi\"\n)\n\n\n\nfunc (s *LocalTests) TestGetNetwork(c *gc.C) {\n\tnet, err := s.testClient.GetNetwork(localNetworkID)\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(net, gc.NotNil)\n\tc.Assert(net, gc.DeepEquals, &cloudapi.Network{\n\t\tId: localNetworkID,\n\t\tName: \"Test-Joyent-Public\",\n\t\tPublic: true,\n\t\tDescription: \"\",\n\t})\n}\n\nfunc (s *LocalTests) TestListNetworks(c *gc.C) ", "output": "{\n\tnets, err := s.testClient.ListNetworks()\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(nets, gc.NotNil)\n}"} {"input": "package rubber\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"go.uber.org/zap\"\n)\n\nconst (\n\tConfigWeightedBackend = \"weighted\"\n\n\tConfigSimpleBackend = \"simple\"\n)\n\n\n\nfunc makeBackend(log *zap.Logger, settings Settings) (Backend, error) {\n\tif compare(settings.Type, ConfigWeightedBackend) {\n\t\tlog.Debug(\"Using weighted backend\")\n\t\treturn CreateWeightedBackend(settings, log)\n\t}\n\tif compare(settings.Type, ConfigSimpleBackend) || compare(settings.Type, \"\") {\n\t\tlog.Debug(\"Using simple backend\")\n\t\tnodes := []string{settings.Preferred}\n\t\tnodes = append(nodes, settings.Nodes...)\n\t\treturn &singleServerBackend{\n\t\t\tlog: log,\n\t\t\tnodes: nodes,\n\t\t\ttimeout: settings.Timeout * time.Second,\n\n\t\t\tclient: &http.Client{\n\t\t\t\tTimeout: settings.Timeout * time.Second,\n\t\t\t},\n\t\t}, nil\n\t}\n\treturn nil, errors.New(\"Unknown backend\")\n}\n\n\nfunc Create(backend Backend) *Elastic {\n\treturn &Elastic{Backend: backend}\n}\n\n\nfunc New(log *zap.Logger, settings Settings) (*Elastic, error) {\n\tbackend, err := makeBackend(log, settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn Create(backend), nil\n}\n\nfunc compare(name, constant string) bool ", "output": "{\n\treturn strings.ToLower(name) == strings.ToLower(constant)\n}"} {"input": "package idn_test\n\nimport (\n\t\"fmt\"\n\t\"github.com/socketplane/socketplane/Godeps/_workspace/src/github.com/miekg/dns/idn\"\n)\n\n\n\nfunc ExampleFromPunycode() {\n\tname := \"xn--mgbaja8a1hpac.xn--mgbachtv\"\n\tfmt.Printf(\"%s -> %s\", name, idn.FromPunycode(name))\n}\n\nfunc ExampleToPunycode() ", "output": "{\n\tname := \"インターネット.テスト\"\n\tfmt.Printf(\"%s -> %s\", name, idn.ToPunycode(name))\n}"} {"input": "package cacheprovider\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/docker/distribution/registry/storage/cache\"\n)\n\n\n\ntype InitFunc func(ctx context.Context, options map[string]interface{}) (cache.BlobDescriptorCacheProvider, error)\n\nvar cacheProviders map[string]InitFunc\n\n\n\n\n\n\nfunc Get(ctx context.Context, name string, options map[string]interface{}) (cache.BlobDescriptorCacheProvider, error) {\n\tif initFunc, exists := cacheProviders[name]; exists {\n\t\treturn initFunc(ctx, options)\n\t}\n\treturn nil, fmt.Errorf(\"no cache Provider registered with name: %s\", name)\n}\n\nfunc Register(name string, initFunc InitFunc) error ", "output": "{\n\tif cacheProviders == nil {\n\t\tcacheProviders = make(map[string]InitFunc)\n\t}\n\tif _, exists := cacheProviders[name]; exists {\n\t\treturn fmt.Errorf(\"name already registered: %s\", name)\n\t}\n\n\tcacheProviders[name] = initFunc\n\n\treturn nil\n}"} {"input": "package utils\n\nimport (\n \"github.com/BurntSushi/toml\"\n \"io/ioutil\"\n \"net\"\n \"sync\"\n \"strings\"\n\n log \"github.com/cihub/seelog\"\n)\n\nvar (\n config *Configuration\n configLock = new(sync.RWMutex)\n)\n\n\n\nfunc GetConfig() *Configuration {\n configLock.RLock()\n defer configLock.RUnlock()\n return config\n}\n\nfunc GetLocalIp() string {\n addrs, err := net.InterfaceAddrs()\n if err != nil {\n log.Criticalf(\"No network interfaces found, %s\", err.Error())\n }\n \n var ips []string\n for _, a := range addrs {\n if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {\n if ipnet.IP.To4() != nil {\n ips = append(ips, ipnet.IP.String())\n }\n }\n }\n return strings.Join(ips, \",\")\n}\n\nfunc ReadConfigFromFile(configfile string) ", "output": "{\n config_file, err := ioutil.ReadFile(configfile)\n if err != nil {\n panic(err.Error())\n }\n tempConf := new(Configuration)\n _, err = toml.Decode(string(config_file), &tempConf)\n if err != nil {\n panic(err.Error())\n }\n configLock.Lock()\n config = tempConf\n configLock.Unlock()\n}"} {"input": "package fsrateio\n\nimport (\n\t\"io\"\n\n\t\"github.com/Symantec/Dominator/lib/rateio\"\n\t\"github.com/Symantec/tricorder/go/tricorder\"\n\t\"github.com/Symantec/tricorder/go/tricorder/units\"\n)\n\ntype ReaderContext struct {\n\tmaxBytesPerSecond uint64\n\tmaxBlocksPerSecond uint64\n\tctx *rateio.ReaderContext\n}\n\nfunc NewReaderContext(maxBytesPerSecond uint64,\n\tmaxBlocksPerSecond uint64, speedPercent uint64) *ReaderContext {\n\treturn newReaderContext(maxBytesPerSecond, maxBlocksPerSecond, speedPercent)\n}\n\nfunc (ctx *ReaderContext) GetContext() *rateio.ReaderContext { return ctx.ctx }\n\nfunc (ctx *ReaderContext) NewReader(rd io.Reader) *rateio.Reader {\n\treturn ctx.ctx.NewReader(rd)\n}\n\nfunc (ctx *ReaderContext) RegisterMetrics(dir *tricorder.DirectorySpec) error {\n\tif ctx.maxBlocksPerSecond > 0 {\n\t\treturn ctx.ctx.RegisterMetrics(dir, units.None,\n\t\t\t\"file-system speed in blocks per second\")\n\t}\n\treturn ctx.ctx.RegisterMetrics(dir, units.BytePerSecond,\n\t\t\"file-system speed\")\n}\n\n\n\nfunc (ctx *ReaderContext) String() string ", "output": "{\n\treturn ctx.format()\n}"} {"input": "package arm\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"encoding/base64\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\t\"golang.org/x/crypto/ssh\"\n\t\"time\"\n)\n\nconst (\n\tKeySize = 2048\n)\n\ntype OpenSshKeyPair struct {\n\tprivateKey *rsa.PrivateKey\n\tpublicKey ssh.PublicKey\n}\n\n\n\nfunc NewOpenSshKeyPairWithSize(keySize int) (*OpenSshKeyPair, error) {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, keySize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpublicKey, err := ssh.NewPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &OpenSshKeyPair{\n\t\tprivateKey: privateKey,\n\t\tpublicKey: publicKey,\n\t}, nil\n}\n\nfunc (s *OpenSshKeyPair) AuthorizedKey() string {\n\treturn fmt.Sprintf(\"%s %s packer Azure Deployment%s\",\n\t\ts.publicKey.Type(),\n\t\tbase64.StdEncoding.EncodeToString(s.publicKey.Marshal()),\n\t\ttime.Now().Format(time.RFC3339))\n}\n\nfunc (s *OpenSshKeyPair) PrivateKey() string {\n\tprivateKey := string(pem.EncodeToMemory(&pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(s.privateKey),\n\t}))\n\n\treturn privateKey\n}\n\nfunc NewOpenSshKeyPair() (*OpenSshKeyPair, error) ", "output": "{\n\treturn NewOpenSshKeyPairWithSize(KeySize)\n}"} {"input": "package syscall\n\nvar (\n\tStdin = 0\n\tStdout = 1\n\tStderr = 2\n)\n\nfunc Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr)\nfunc Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr)\nfunc RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr)\nfunc RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr)\n\n\n\nfunc Errstr(errno int) string ", "output": "{\n\tif errno < 0 || errno >= int(len(errors)) {\n\t\treturn \"error \" + itoa(errno)\n\t}\n\treturn errors[errno]\n}"} {"input": "package luhn\n\nimport \"testing\"\n\nvar validTests = []struct {\n\tn string\n\tok bool\n}{\n\t{\"738\", false},\n\t{\"8739567\", true},\n\t{\"1111\", false},\n\t{\"8763\", true},\n\t{\" \", false},\n\t{\"\", false},\n\t{\"2323 2005 7766 3554\", true},\n}\n\nvar addTests = []struct{ raw, luhn string }{\n\t{\"123\", \"1230\"},\n\t{\"873956\", \"8739567\"},\n\t{\"837263756\", \"8372637564\"},\n\t{\"2323 2005 7766 355\", \"2323 2005 7766 3554\"},\n}\n\n\n\nfunc TestAddCheck(t *testing.T) {\n\tfor _, test := range addTests {\n\t\tif luhn := AddCheck(test.raw); luhn != test.luhn {\n\t\t\tt.Fatalf(\"AddCheck(%s) = %s, want %s.\", test.raw, luhn, test.luhn)\n\t\t}\n\t}\n}\n\nfunc BenchmarkValid(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tValid(\"2323 2005 7766 3554\")\n\t}\n}\n\nfunc BenchmarkAddCheck(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tAddCheck(\"2323 2005 7766 355\")\n\t}\n}\n\nfunc TestValid(t *testing.T) ", "output": "{\n\tfor _, test := range validTests {\n\t\tif ok := Valid(test.n); ok != test.ok {\n\t\t\tt.Fatalf(\"Valid(%s) = %t, want %t.\", test.n, ok, test.ok)\n\t\t}\n\t}\n}"} {"input": "package testing\n\n\n\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n\tclientset \"k8s.io/kubernetes/pkg/client/clientset_generated/clientset\"\n\tkubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\"\n\tcontainertest \"k8s.io/kubernetes/pkg/kubelet/container/testing\"\n)\n\ntype fakeNetworkHost struct {\n\tfakeNamespaceGetter\n\tkubeClient clientset.Interface\n\tLegacy bool\n\tRuntime *containertest.FakeRuntime\n}\n\nfunc NewFakeHost(kubeClient clientset.Interface) *fakeNetworkHost {\n\thost := &fakeNetworkHost{kubeClient: kubeClient, Legacy: true, Runtime: &containertest.FakeRuntime{}}\n\treturn host\n}\n\nfunc (fnh *fakeNetworkHost) GetPodByName(name, namespace string) (*v1.Pod, bool) {\n\treturn nil, false\n}\n\nfunc (fnh *fakeNetworkHost) GetKubeClient() clientset.Interface {\n\treturn nil\n}\n\nfunc (nh *fakeNetworkHost) GetRuntime() kubecontainer.Runtime {\n\treturn nh.Runtime\n}\n\n\n\ntype fakeNamespaceGetter struct {\n\tns string\n}\n\nfunc (nh *fakeNamespaceGetter) GetNetNS(containerID string) (string, error) {\n\treturn nh.ns, nil\n}\n\nfunc (nh *fakeNetworkHost) SupportsLegacyFeatures() bool ", "output": "{\n\treturn nh.Legacy\n}"} {"input": "package gtka\n\nimport (\n\t\"github.com/gotk3/gotk3/gtk\"\n\t\"github.com/coyim/gotk3adapter/gliba\"\n\t\"github.com/coyim/gotk3adapter/gtki\"\n)\n\ntype application struct {\n\t*gliba.Application\n\tinternal *gtk.Application\n}\n\nfunc wrapApplicationSimple(v *gtk.Application) *application {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn &application{gliba.WrapApplicationSimple(&v.Application), v}\n}\n\nfunc wrapApplication(v *gtk.Application, e error) (*application, error) {\n\treturn wrapApplicationSimple(v), e\n}\n\nfunc unwrapApplication(v gtki.Application) *gtk.Application {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*application).internal\n}\n\n\n\nfunc (v *application) GetActiveWindow() gtki.Window ", "output": "{\n\tret := wrapWindowSimple(v.internal.GetActiveWindow())\n\tif ret == nil {\n\t\treturn nil\n\t}\n\treturn ret\n}"} {"input": "package vfs\n\nimport (\n\t\"path\"\n\n\tgofig \"github.com/akutz/gofig/types\"\n\n\t\"github.com/rexray/rexray/libstorage/api/context\"\n\t\"github.com/rexray/rexray/libstorage/api/registry\"\n\t\"github.com/rexray/rexray/libstorage/api/types\"\n)\n\nconst (\n\tName = \"vfs\"\n)\n\n\n\n\nfunc RootDir(config gofig.Config) string {\n\treturn config.GetString(\"vfs.root\")\n}\n\n\nfunc DeviceFilePath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"dev\")\n}\n\n\nfunc VolumesDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"vol\")\n}\n\n\nfunc SnapshotsDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"snap\")\n}\n\nfunc init() ", "output": "{\n\tregistry.RegisterConfigReg(\n\t\t\"VFS\",\n\t\tfunc(ctx types.Context, r gofig.ConfigRegistration) {\n\t\t\tvfsRoot := path.Join(context.MustPathConfig(ctx).Lib, \"vfs\")\n\t\t\tr.Key(\n\t\t\t\tgofig.String,\n\t\t\t\t\"\",\n\t\t\t\tvfsRoot,\n\t\t\t\t\"\",\n\t\t\t\t\"vfs.root\")\n\t\t})\n}"} {"input": "package print\n\n\n\nimport \"C\"\nimport \"unsafe\"\n\n\n\nfunc Print(s string) ", "output": "{\n\tcs := C.CString(s)\n\tdefer C.free(unsafe.Pointer(cs))\n\tC.fputs(cs, (*C.FILE)(C.stdout))\n}"} {"input": "package mock\n\nimport (\n\t\"github.com/eventials/goevents/messaging\"\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype Connection struct {\n\tmock.Mock\n}\n\n\n\nfunc (c *Connection) Consumer(autoAck bool, exchange, queue string) (messaging.Consumer, error) {\n\targs := c.Called(autoAck, exchange, queue)\n\treturn args.Get(0).(messaging.Consumer), args.Error(1)\n}\n\nfunc (c *Connection) Producer(exchange string) (messaging.Producer, error) {\n\targs := c.Called(exchange)\n\treturn args.Get(0).(messaging.Producer), args.Error(1)\n}\n\nfunc (c *Connection) Close() {\n\tc.Called()\n}\n\nfunc (c *Connection) NotifyConnectionClose() <-chan error {\n\targs := c.Called()\n\treturn args.Get(0).(chan error)\n}\n\nfunc (c *Connection) NotifyReestablish() <-chan bool {\n\targs := c.Called()\n\treturn args.Get(0).(chan bool)\n}\n\nfunc (c *Connection) WaitUntilConnectionCloses() {\n\tc.Called()\n}\n\nfunc (c *Connection) WaitUntilConnectionReestablished() {\n\tc.Called()\n}\n\nfunc (c *Connection) IsConnected() bool {\n\targs := c.Called()\n\treturn args.Get(0).(bool)\n}\n\nfunc NewMockConnection() messaging.Connection ", "output": "{\n\treturn &Connection{}\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1beta1 \"k8s.io/metrics/pkg/client/clientset_generated/clientset/typed/metrics/v1beta1\"\n)\n\ntype FakeMetricsV1beta1 struct {\n\t*testing.Fake\n}\n\n\n\nfunc (c *FakeMetricsV1beta1) PodMetricses(namespace string) v1beta1.PodMetricsInterface {\n\treturn &FakePodMetricses{c, namespace}\n}\n\n\n\nfunc (c *FakeMetricsV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeMetricsV1beta1) NodeMetricses() v1beta1.NodeMetricsInterface ", "output": "{\n\treturn &FakeNodeMetricses{c}\n}"} {"input": "package json\n\nimport \"fmt\"\n\ntype Serializer struct {\n\tdumper *Dumper\n\tparser *Parser\n}\n\nfunc (serializer *Serializer) String() string {\n\treturn fmt.Sprintf(\"\")\n}\n\n\n\nfunc (serializer *Serializer) Parse(s string) map[interface{}]interface{} {\n\treturn serializer.parser.Parse(s)\n}\n\nfunc (serializer *Serializer) Dump(m *map[interface{}]interface{}) string ", "output": "{\n\treturn serializer.dumper.Dump(m)\n}"} {"input": "package trace \n\nimport (\n\t\"context\"\n\t\"runtime\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}\n\n\n\n\n\n\nfunc versionGo() string {\n\tconst develPrefix = \"devel +\"\n\n\ts := runtime.Version()\n\tif strings.HasPrefix(s, develPrefix) {\n\t\ts = s[len(develPrefix):]\n\t\tif p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 {\n\t\t\ts = s[:p]\n\t\t}\n\t\treturn s\n\t}\n\n\tnotSemverRune := func(r rune) bool {\n\t\treturn strings.IndexRune(\"0123456789.\", r) < 0\n\t}\n\n\tif strings.HasPrefix(s, \"go1\") {\n\t\ts = s[2:]\n\t\tvar prerelease string\n\t\tif p := strings.IndexFunc(s, notSemverRune); p >= 0 {\n\t\t\ts, prerelease = s[:p], s[p:]\n\t\t}\n\t\tif strings.HasSuffix(s, \".\") {\n\t\t\ts += \"0\"\n\t\t} else if strings.Count(s, \".\") < 2 {\n\t\t\ts += \".0\"\n\t\t}\n\t\tif prerelease != \"\" {\n\t\t\ts += \"-\" + prerelease\n\t\t}\n\t\treturn s\n\t}\n\treturn \"UNKNOWN\"\n}\n\nconst versionClient = \"20190306\"\n\nfunc DefaultAuthScopes() []string ", "output": "{\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t\t\"https:www.googleapis.com/auth/trace.append\",\n\t\t\"https:www.googleapis.com/auth/trace.readonly\",\n\t}\n}"} {"input": "package packet\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype PacketCodecVarIntLength struct {\n\tcodec PacketCodec\n}\n\nfunc NewPacketCodecVarIntLength() (this *PacketCodecVarIntLength) {\n\tthis = new(PacketCodecVarIntLength)\n\treturn\n}\n\nfunc (this *PacketCodecVarIntLength) Decode(reader io.Reader) (packet Packet, err error) {\n\tlength, err := ReadVarInt(reader)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Decode, Length read error: %w\", err)\n\t\treturn\n\t}\n\tif length < 0 {\n\t\terr = errors.New(fmt.Sprintf(\"Decode, Packet length is below zero: %d\", length))\n\t\treturn\n\t}\n\tif length > 1048576 { \n\t\terr = errors.New(fmt.Sprintf(\"Decode, Packet length is above maximum: %d\", length))\n\t\treturn\n\t}\n\tpayload := make([]byte, length)\n\t_, err = reader.Read(payload)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Decode, Length buffer error: %w\", err)\n\t\treturn\n\t}\n\tpacket, err = this.codec.Decode(bytes.NewBuffer(payload))\n\treturn\n}\n\n\n\nfunc (this *PacketCodecVarIntLength) SetCodec(codec PacketCodec) {\n\tthis.codec = codec\n}\n\nfunc (this *PacketCodecVarIntLength) Encode(writer io.Writer, packet Packet) (err error) ", "output": "{\n\tbuffer := new(bytes.Buffer)\n\terr = this.codec.Encode(buffer, packet)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = WriteVarInt(writer, buffer.Len())\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = buffer.WriteTo(writer)\n\treturn\n}"} {"input": "package elastic\n\n\n\n\ntype LimitFilter struct {\n Filter\n limit int\n}\n\nfunc NewLimitFilter(limit int) LimitFilter {\n f := LimitFilter{limit: limit}\n return f\n}\n\n\n\nfunc (f LimitFilter) Source() interface{} ", "output": "{\n \n \n \n \n \n source := make(map[string]interface{})\n params := make(map[string]interface{})\n source[\"limit\"] = params\n params[\"value\"] = f.limit\n return source\n}"} {"input": "package main\n\nimport (\n\t\"github.com/kisielk/whisper-go/whisper\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n)\n\nvar from, until uint\n\n\n\nfunc main() {\n\tnow := uint(time.Now().Unix())\n\tyesterday := uint(time.Now().Add(-24 * time.Hour).Unix())\n\tflag.UintVar(&from, \"from\", yesterday, \"Unix epoch time of the beginning of the requested interval. (default: 24 hours ago)\")\n\tflag.UintVar(&until, \"until\", now, \"Unix epoch time of the end of the requested interval. (default: now)\")\n\tflag.Parse()\n\n\tif flag.NArg() != 1 {\n\t\tusage()\n\t}\n\n\tpath := flag.Args()[0]\n\tfromTime := uint32(from)\n\tuntilTime := uint32(until)\n\n\tw, err := whisper.Open(path)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tinterval, points, err := w.FetchUntil(fromTime, untilTime)\n\n\tfmt.Printf(\"Values in interval %+v\\n\", interval)\n\tfor i, p := range points {\n\t\tfmt.Printf(\"%d %v\\n\", i, p)\n\t}\n\treturn\n}\n\nfunc usage() ", "output": "{\n\tlog.Fatal(\"Wrong number of arguments\")\n}"} {"input": "package xeth\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/ethereum/go-ethereum/common\"\n)\n\n\n\ntype whisperFilter struct {\n\tid int \n\tref *Whisper \n\n\tcache []WhisperMessage \n\tskip map[common.Hash]struct{} \n\tupdate time.Time \n\n\tlock sync.RWMutex \n}\n\n\nfunc newWhisperFilter(id int, ref *Whisper) *whisperFilter {\n\treturn &whisperFilter{\n\t\tid: id,\n\t\tref: ref,\n\n\t\tupdate: time.Now(),\n\t\tskip: make(map[common.Hash]struct{}),\n\t}\n}\n\n\n\nfunc (w *whisperFilter) messages() []WhisperMessage {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tw.cache = nil\n\tw.update = time.Now()\n\n\tw.skip = make(map[common.Hash]struct{})\n\tmessages := w.ref.Messages(w.id)\n\tfor _, message := range messages {\n\t\tw.skip[message.ref.Hash] = struct{}{}\n\t}\n\treturn messages\n}\n\n\nfunc (w *whisperFilter) insert(messages ...WhisperMessage) {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tfor _, message := range messages {\n\t\tif _, ok := w.skip[message.ref.Hash]; !ok {\n\t\t\tw.cache = append(w.cache, messages...)\n\t\t}\n\t}\n}\n\n\nfunc (w *whisperFilter) retrieve() (messages []WhisperMessage) {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tmessages, w.cache = w.cache, nil\n\tw.update = time.Now()\n\n\treturn\n}\n\n\n\n\n\nfunc (w *whisperFilter) activity() time.Time ", "output": "{\n\tw.lock.RLock()\n\tdefer w.lock.RUnlock()\n\n\treturn w.update\n}"} {"input": "package subtle \n\nimport \"unsafe\"\n\n\n\nfunc AnyOverlap(x, y []byte) bool {\n\treturn len(x) > 0 && len(y) > 0 &&\n\t\tuintptr(unsafe.Pointer(&x[0])) <= uintptr(unsafe.Pointer(&y[len(y)-1])) &&\n\t\tuintptr(unsafe.Pointer(&y[0])) <= uintptr(unsafe.Pointer(&x[len(x)-1]))\n}\n\n\n\n\n\n\n\n\n\nfunc InexactOverlap(x, y []byte) bool ", "output": "{\n\tif len(x) == 0 || len(y) == 0 || &x[0] == &y[0] {\n\t\treturn false\n\t}\n\treturn AnyOverlap(x, y)\n}"} {"input": "package decorator\n\nimport (\n\t\"fmt\"\n)\n\ntype DefaultDecorator struct {\n}\n\n\n\nfunc (i *DefaultDecorator) FromString(field string) (interface{}, error) {\n\treturn field, nil\n}\n\nfunc (i *DefaultDecorator) ToString(field interface{}) (string, error) ", "output": "{\n\treturn fmt.Sprintf(\"%v\", field), nil\n}"} {"input": "package jpsplus\n\nimport (\n\t\"container/heap\"\n)\n\ntype PriorityQueue struct {\n\tpos int\n\tnode map[int]*Node\n}\n\nfunc newPriorityQueue() *PriorityQueue {\n\tp := new(PriorityQueue)\n\tp.node = make(map[int]*Node)\n\treturn p\n}\n\nfunc (p *PriorityQueue) Len() int {\n\treturn len(p.node)\n}\n\nfunc (p *PriorityQueue) Less(i, j int) bool {\n\treturn p.node[i].finalCost < p.node[j].finalCost\n}\n\nfunc (p *PriorityQueue) Swap(i, j int) {\n\tp.node[i], p.node[j] = p.node[j], p.node[i]\n\tp.node[i].heapIndex = i\n\tp.node[j].heapIndex = j\n}\n\nfunc (p *PriorityQueue) Push(x interface{}) {\n\titem, ok := x.(*Node)\n\tif ok {\n\t\titem.heapIndex = p.pos\n\t\tp.node[p.pos] = item\n\t\tp.pos++\n\t}\n}\n\nfunc (p *PriorityQueue) Pop() interface{} {\n\tp.pos--\n\titem := p.node[p.pos]\n\tdelete(p.node, p.pos)\n\treturn item\n}\n\nfunc (p *PriorityQueue) PushNode(n *Node) {\n\theap.Push(p, n)\n}\n\nfunc (p *PriorityQueue) PopNode() *Node {\n\treturn heap.Pop(p).(*Node)\n}\n\n\n\nfunc (p *PriorityQueue) RemoveNode(n *Node) ", "output": "{\n\theap.Remove(p, n.heapIndex)\n}"} {"input": "package unversioned\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/testapi\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\ntype HTTPClientFunc func(*http.Request) (*http.Response, error)\n\nfunc (f HTTPClientFunc) Do(req *http.Request) (*http.Response, error) {\n\treturn f(req)\n}\n\n\ntype FakeRESTClient struct {\n\tClient HTTPClient\n\tCodec runtime.Codec\n\tReq *http.Request\n\tResp *http.Response\n\tErr error\n}\n\nfunc (c *FakeRESTClient) Get() *Request {\n\treturn NewRequest(c, \"GET\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\n\n\nfunc (c *FakeRESTClient) Patch(_ api.PatchType) *Request {\n\treturn NewRequest(c, \"PATCH\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Post() *Request {\n\treturn NewRequest(c, \"POST\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Delete() *Request {\n\treturn NewRequest(c, \"DELETE\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Do(req *http.Request) (*http.Response, error) {\n\tc.Req = req\n\tif c.Client != HTTPClient(nil) {\n\t\treturn c.Client.Do(req)\n\t}\n\treturn c.Resp, c.Err\n}\n\nfunc (c *FakeRESTClient) Put() *Request ", "output": "{\n\treturn NewRequest(c, \"PUT\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification struct {\n\n\tPredefinedScalingMetricType string `json:\"PredefinedScalingMetricType,omitempty\"`\n\n\tResourceLabel string `json:\"ResourceLabel,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\n\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::AutoScalingPlans::ScalingPlan.PredefinedScalingMetricSpecification\"\n}"} {"input": "package main\n\nimport \"errors\"\nimport \"fmt\"\n\n\n\n\n\n\n\n\n\ntype argError struct {\n\targ int\n\tprob string\n}\n\nfunc (e *argError) Error() string {\n\treturn fmt.Sprintf(\"%d - %s\", e.arg, e.prob)\n}\n\nfunc f2(arg int) (int, error) {\n\tif arg == 42 {\n\n\t\treturn -1, &argError{arg, \"can't work with it\"}\n\t}\n\treturn arg + 3, nil\n}\n\nfunc main() {\n\n\tfor _, i := range []int{7, 42} {\n\t\tif r, e := f1(i); e != nil {\n\t\t\tfmt.Println(\"f1 failed:\", e)\n\t\t} else {\n\t\t\tfmt.Println(\"f1 worked:\", r)\n\t\t}\n\t}\n\n\tfor _, i := range []int{7, 42} {\n\t\tif r, e := f2(i); e != nil {\n\t\t\tfmt.Println(\"f2 failed:\", e)\n\t\t} else {\n\t\t\tfmt.Println(\"f2 worked:\", r)\n\t\t}\n\t}\n\n\t_, e := f2(42)\n\tif ae, ok := e.(*argError); ok {\n\t\tfmt.Println(ae.arg)\n\t\tfmt.Println(ae.prob)\n\t}\n}\n\nfunc f1(arg int) (int, error) ", "output": "{\n\tif arg == 42 {\n\n\t\treturn -1, errors.New(\"can't work with 42\")\n\n\t}\n\n\treturn arg + 3, nil\n}"} {"input": "package iso20022\n\n\ntype CorporateActionEventStageFormat15Choice struct {\n\n\tCode *CorporateActionEventStage4Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification47 `xml:\"Prtry\"`\n}\n\n\n\nfunc (c *CorporateActionEventStageFormat15Choice) AddProprietary() *GenericIdentification47 {\n\tc.Proprietary = new(GenericIdentification47)\n\treturn c.Proprietary\n}\n\nfunc (c *CorporateActionEventStageFormat15Choice) SetCode(value string) ", "output": "{\n\tc.Code = (*CorporateActionEventStage4Code)(&value)\n}"} {"input": "package fake\n\nimport (\n\tclientset \"github.com/kube-node/nodeset/pkg/client/clientset_v1alpha1\"\n\tnodesetv1alpha1 \"github.com/kube-node/nodeset/pkg/client/clientset_v1alpha1/typed/nodeset/v1alpha1\"\n\tfakenodesetv1alpha1 \"github.com/kube-node/nodeset/pkg/client/clientset_v1alpha1/typed/nodeset/v1alpha1/fake\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/watch\"\n\t\"k8s.io/client-go/discovery\"\n\tfakediscovery \"k8s.io/client-go/discovery/fake\"\n\t\"k8s.io/client-go/testing\"\n)\n\n\n\n\n\n\n\n\n\n\ntype Clientset struct {\n\ttesting.Fake\n}\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\treturn &fakediscovery.FakeDiscovery{Fake: &c.Fake}\n}\n\nvar _ clientset.Interface = &Clientset{}\n\n\nfunc (c *Clientset) NodesetV1alpha1() nodesetv1alpha1.NodesetV1alpha1Interface {\n\treturn &fakenodesetv1alpha1.FakeNodesetV1alpha1{Fake: &c.Fake}\n}\n\n\nfunc (c *Clientset) Nodeset() nodesetv1alpha1.NodesetV1alpha1Interface {\n\treturn &fakenodesetv1alpha1.FakeNodesetV1alpha1{Fake: &c.Fake}\n}\n\nfunc NewSimpleClientset(objects ...runtime.Object) *Clientset ", "output": "{\n\to := testing.NewObjectTracker(registry, scheme, codecs.UniversalDecoder())\n\tfor _, obj := range objects {\n\t\tif err := o.Add(obj); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tfakePtr := testing.Fake{}\n\tfakePtr.AddReactor(\"*\", \"*\", testing.ObjectReaction(o, registry.RESTMapper()))\n\n\tfakePtr.AddWatchReactor(\"*\", testing.DefaultWatchReactor(watch.NewFake(), nil))\n\n\treturn &Clientset{fakePtr}\n}"} {"input": "package middleware\n\nimport \"github.com/gin-gonic/gin\"\n\n\n\nfunc CORS() gin.HandlerFunc ", "output": "{\n\treturn func(c *gin.Context) {\n\t\tc.Header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tc.Next()\n\t}\n}"} {"input": "package openid\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha1\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"hash\"\n\t\"log\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\thmacSHA1 = \"HMAC-SHA1\"\n\thmacSHA256 = \"HMAC-SHA256\"\n)\n\n\ntype Association struct {\n\tEndpoint string\n\tHandle string\n\tSecret []byte\n\tType string\n\tExpires time.Time\n}\n\nfunc (a *Association) sign(\n\tparams map[string]string, signed []string) (string, error) {\n\n\tvar h hash.Hash\n\n\tswitch a.Type {\n\tcase hmacSHA1:\n\t\th = hmac.New(sha1.New, a.Secret)\n\tcase hmacSHA256:\n\t\th = hmac.New(sha256.New, a.Secret)\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"unsupported association type %q\", a.Type)\n\t}\n\n\tfor _, k := range signed {\n\t\twriteKeyValuePair(h, k, params[k])\n\t}\n\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil)), nil\n}\n\n\ntype associations struct {\n\tsync.Map\n}\n\n\n\n\n\nfunc (as *associations) set(endpoint string, a *Association) {\n\tas.Store(strings.TrimRight(endpoint, \"/\"), a)\n}\n\n\nfunc (as *associations) gc() (int, int) {\n\tfrom, purged := 0, 0\n\n\tas.Map.Range(func(k, v interface{}) bool {\n\t\ta := v.(*Association)\n\t\tif a.Expires.Before(time.Now()) {\n\t\t\tpurged++\n\t\t\tas.Map.Delete(k)\n\t\t}\n\t\tfrom++\n\t\treturn true\n\t})\n\n\treturn from, from - purged\n}\n\nfunc (as *associations) get(endpoint string) (*Association, bool) ", "output": "{\n\tendpoint = strings.TrimRight(endpoint, \"/\")\n\tvalue, ok := as.Load(endpoint)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tassoc := value.(*Association)\n\tif assoc.Expires.After(time.Now()) {\n\t\treturn assoc, ok\n\t}\n\n\tfrom, to := as.gc()\n\tlog.Printf(\"associates GC from %d to %d\", from, to)\n\n\treturn nil, false\n}"} {"input": "package ini\n\nimport (\n\t\"fmt\"\n\t\"github.com/robfig/config\"\n\t\"github.com/mabetle/mcore\"\n)\n\n\n\n\ntype IniConfig struct {\n\tLocations []string\n\t*config.Config\n}\n\n\n\nfunc NewIniConfig(locations ...string) *IniConfig {\n\tc := &IniConfig{Locations: locations}\n\tconf := config.NewDefault()\n\tfor _, location := range locations {\n\t\tconfItem, err := config.ReadDefault(location)\n\t\tif logger.CheckError(err) {\n\t\t\tcontinue\n\t\t}\n\t\tconf.Merge(confItem)\n\t}\n\tc.Config = conf\n\treturn c\n}\n\n\n\nfunc (c IniConfig) LoadKeyValue() mcore.StringKeyValueMap ", "output": "{\n\tlogger.Debugf(\"load config from %v.\", c.Locations)\n\tskv := mcore.NewStringKeyValueMap()\n\tfor _, section := range c.Sections() {\n\t\toptions, _ := c.Config.Options(section)\n\t\tfor _, option := range options {\n\t\t\tk := \"\"\n\t\t\tif section == \"DEFAULT\" {\n\t\t\t\tk = fmt.Sprintf(\"%s\", option)\n\t\t\t} else {\n\t\t\t\tk = fmt.Sprintf(\"%s@%s\", option, section)\n\t\t\t}\n\t\t\tv, _ := c.Config.String(section, option)\n\t\t\tlogger.Tracef(\"load key:%s value:%s\", k, v)\n\t\t\tskv.Put(k, v)\n\t\t}\n\t}\n\treturn skv\n}"} {"input": "package otel\n\nimport (\n\t\"sync\"\n)\n\nvar initOnce sync.Once\n\n\nfunc Initialize(opts ...Option) {\n\tcnf := newConfig(opts...)\n\tinitOnce.Do(func() {\n\t\tinitialize(cnf)\n\t})\n}\n\n\n\nfunc initialize(cnf *config) ", "output": "{\n\taddClientFactoryHooks(cnf)\n}"} {"input": "package nerd\n\nimport (\n\t\"context\"\n\t\"syscall\"\n\n\t\"code.cloudfoundry.org/lager\"\n\t\"github.com/containerd/containerd\"\n)\n\ntype BackingProcess struct {\n\tlog lager.Logger\n\tcontext context.Context\n\tcontainerdProcess containerd.Process\n}\n\nfunc NewBackingProcess(log lager.Logger, p containerd.Process, ctx context.Context) BackingProcess {\n\treturn BackingProcess{\n\t\tlog: log,\n\t\tcontext: ctx,\n\t\tcontainerdProcess: p,\n\t}\n}\n\n\n\nfunc (p BackingProcess) Wait() (int, error) {\n\texitCh, err := p.containerdProcess.Wait(p.context)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\texitStatus := <-exitCh\n\tif exitStatus.Error() != nil {\n\t\treturn 0, exitStatus.Error()\n\t}\n\n\treturn int(exitStatus.ExitCode()), nil\n}\n\nfunc (p BackingProcess) Signal(signal syscall.Signal) error {\n\treturn p.containerdProcess.Kill(p.context, signal)\n}\n\nfunc (p BackingProcess) Delete() error {\n\t_, err := p.containerdProcess.Delete(p.context)\n\treturn err\n}\n\nfunc (p BackingProcess) ID() string ", "output": "{\n\treturn p.containerdProcess.ID()\n}"} {"input": "package tlv\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\ntype ByteTLV struct {\n\tT uint64\n\tV []byte\n}\n\nfunc readByteTLV(r io.Reader) (ByteTLV, error) {\n\tt, _, err := ReadNumber(r)\n\tif err != nil {\n\t\treturn ByteTLV{}, err\n\t}\n\n\tlength, _, err := ReadNumber(r)\n\tif err != nil {\n\t\treturn ByteTLV{}, err\n\t}\n\n\tvalue := make([]byte, length)\n\tn, err := r.Read(value)\n\tif err != nil {\n\t\treturn ByteTLV{}, err\n\t}\n\n\tif uint64(n) < length {\n\t\treturn ByteTLV{}, io.ErrUnexpectedEOF\n\t}\n\n\treturn ByteTLV{T: t, V: value[0:n]}, nil\n}\n\nfunc (t ByteTLV) Type() uint64 {\n\treturn t.T\n}\n\nfunc (t ByteTLV) WriteTo(w io.Writer) (n int64, err error) {\n\tn, err = WriteNumber(w, t.T)\n\tif err != nil {\n\t\treturn\n\t}\n\n\twritten, err := WriteNumber(w, uint64(len(t.V)))\n\tn += written\n\tif err != nil {\n\t\treturn\n\t}\n\n\twritten2, err := w.Write(t.V)\n\tn += int64(written2)\n\treturn\n}\n\n\n\nfunc (t ByteTLV) MarshalBinary() ([]byte, error) ", "output": "{\n\tbuf := &bytes.Buffer{}\n\t_, err := t.WriteTo(buf)\n\treturn buf.Bytes(), err\n}"} {"input": "package api\n\nimport (\n\t\"log\"\n\t\"net/http\"\n)\n\ntype HttpsRedirectingFileHandler interface {\n\thttp.Handler\n\tfileHandler() http.Handler\n}\n\ntype httpsHandler struct {\n\tinternalHandler http.Handler\n}\n\n\n\nfunc redirect(w http.ResponseWriter, req *http.Request) {\n\ttarget := \"https://\" + req.Host + req.URL.Path\n\tif len(req.URL.RawQuery) > 0 {\n\t\ttarget += \"?\" + req.URL.RawQuery\n\t}\n\tlog.Printf(\"redirect to: %s\", target)\n\thttp.Redirect(w, req, target,\n\t\thttp.StatusTemporaryRedirect)\n}\n\nfunc isXForwardedHTTPS(request *http.Request) bool {\n\txForwardedProto := request.Header.Get(\"X-Forwarded-Proto\")\n\n\treturn len(xForwardedProto) > 0 && xForwardedProto == \"https\"\n}\n\nfunc (h *httpsHandler) fileHandler() http.Handler {\n\treturn h.internalHandler\n}\n\nfunc (h *httpsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tif !isXForwardedHTTPS(req) {\n\t\tredirect(w, req)\n\t} else {\n\t\th.fileHandler().ServeHTTP(w, req)\n\t}\n}\n\nfunc NewHttpsRedirectFileHandler(dir http.Dir) HttpsRedirectingFileHandler ", "output": "{\n\thandler := &httpsHandler{}\n\thandler.internalHandler = http.FileServer(dir)\n\treturn handler\n}"} {"input": "package daemon\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\tbgp \"github.com/gopher-net/gopher-net/third-party/github.com/gobgp/packet\"\n)\n\n\n\n\ntype RibEntry struct {\n\tNextHop net.IP\n\tNetworkSegment int\n\tDestIpPrefix net.IP\n\tLength int\n\tGateway net.IP\n\tInterface net.IP\n\tMetric int\n}\n\n\ntype RoutingTable struct {\n\tRib []RibEntry\n}\n\n\nfunc (r *RoutingTable) Add(entry *RibEntry) {\n\tr.Rib = append(r.Rib, *entry)\n}\n\n\nfunc (r *RoutingTable) Print() string {\n\tresult := fmt.Sprintf(\"%+v\\n\", r.Rib)\n\treturn result\n}\n\nfunc Ipv4PrefixConcat(p *bgp.NLRInfo) string {\n\treturn fmt.Sprintf(\"%v/%v\", p.Prefix.String(), p.Length)\n}\n\nfunc NewRibEntry() RibEntry ", "output": "{\n\trib := RibEntry{\n\t\tNextHop: nil,\n\t\tNetworkSegment: 0,\n\t\tDestIpPrefix: nil,\n\t\tLength: 0,\n\t\tGateway: nil,\n\t}\n\treturn rib\n}"} {"input": "package gooh\n\ntype MemoryContext struct {\n\tdata map[string]interface{}\n}\n\nfunc (c *MemoryContext) Get(k string) (interface{}, error) {\n\treturn c.data[k], nil\n}\n\nfunc (c *MemoryContext) Set(k string, d interface{}) error {\n\tif c.data == nil {\n\t\tc.data = make(map[string]interface{})\n\t}\n\tc.data[k] = d\n\treturn nil\n}\n\n\n\nfunc (c *MemoryContext) Exists(k string) (bool, error) ", "output": "{\n\t_, ok := c.data[k]\n\treturn ok, nil\n}"} {"input": "package osenv_test\n\nimport (\n\t\"testing\"\n\n\tgc \"launchpad.net/gocheck\"\n)\n\n\n\nfunc Test(t *testing.T) ", "output": "{\n\tgc.TestingT(t)\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"runtime\"\n)\n\nvar i *int\n\nfunc f(x int) {\n pc, file, line, ok := runtime.Caller(0)\n if !ok {\n panic(\"runtime.Caller not OK!\")\n }\n fmt.Printf(\"pc = %d, file = %s, line = %d\\n\", pc, file, line)\n fmt.Printf(\"f %d\\n\", x)\n}\n\n\n\nfunc assign() {\n ii := 10\n runtime.SetFinalizer(&ii, final)\n i = &ii\n}\n\nfunc main() {\n assign()\n i = nil\n runtime.GC()\n \n f(1)\n runtime.GC()\n \n}\n\nfunc final(ii *int) ", "output": "{\n fmt.Printf(\"finalizer called on int %d\\n\", *ii)\n}"} {"input": "package fakeclock\n\nimport (\n\t\"time\"\n\n\t\"github.com/pivotal-golang/clock\"\n)\n\ntype fakeTicker struct {\n\ttimer clock.Timer\n}\n\nfunc newFakeTicker(timer *fakeTimer) *fakeTicker {\n\treturn &fakeTicker{\n\t\ttimer: timer,\n\t}\n}\n\n\n\nfunc (ft *fakeTicker) Stop() {\n\tft.timer.Stop()\n}\n\nfunc (ft *fakeTicker) C() <-chan time.Time ", "output": "{\n\treturn ft.timer.C()\n}"} {"input": "package leetcode\n\n\n\n\n\ntype MyStack struct {\n\telements []int\n}\n\n\n\n\n\nfunc (this *MyStack) Push(x int) {\n\tthis.elements = append(this.elements, x)\n}\n\n\nfunc (this *MyStack) Pop() int {\n\tn := len(this.elements)\n\te := this.elements[n-1]\n\tthis.elements = this.elements[:n-1]\n\treturn e\n}\n\n\nfunc (this *MyStack) Top() int {\n\treturn this.elements[len(this.elements)-1]\n}\n\n\nfunc (this *MyStack) Empty() bool {\n\treturn len(this.elements) == 0\n}\n\nfunc NewMyStack() MyStack ", "output": "{\n\treturn MyStack{}\n}"} {"input": "package cni\n\nimport (\n\t\"github.com/lastbackend/lastbackend/pkg/runtime/cni\"\n\t\"github.com/lastbackend/lastbackend/pkg/runtime/cni/local\"\n\t\"github.com/lastbackend/lastbackend/pkg/runtime/cni/vxlan\"\n\t\"github.com/spf13/viper\"\n)\n\n\n\nfunc New(v *viper.Viper) (cni.CNI, error) ", "output": "{\n\tswitch v.GetString(\"network.cni.type\") {\n\tcase \"vxlan\":\n\t\treturn vxlan.New(v.GetString(\"network.interface\"))\n\tdefault:\n\t\treturn local.New()\n\t}\n}"} {"input": "package types\n\nimport (\n\t\"github.com/coreos/ignition/v2/config/shared/errors\"\n\n\t\"github.com/coreos/vcontext/path\"\n\t\"github.com/coreos/vcontext/report\"\n)\n\nfunc (r Raid) Key() string {\n\treturn r.Name\n}\n\nfunc (r Raid) IgnoreDuplicates() map[string]struct{} {\n\treturn map[string]struct{}{\n\t\t\"Options\": {},\n\t}\n}\n\n\n\nfunc (r Raid) validateLevel() error {\n\tswitch r.Level {\n\tcase \"linear\", \"raid0\", \"0\", \"stripe\":\n\t\tif r.Spares != nil && *r.Spares != 0 {\n\t\t\treturn errors.ErrSparesUnsupportedForLevel\n\t\t}\n\tcase \"raid1\", \"1\", \"mirror\":\n\tcase \"raid4\", \"4\":\n\tcase \"raid5\", \"5\":\n\tcase \"raid6\", \"6\":\n\tcase \"raid10\", \"10\":\n\tdefault:\n\t\treturn errors.ErrUnrecognizedRaidLevel\n\t}\n\n\treturn nil\n}\n\nfunc (ra Raid) Validate(c path.ContextPath) (r report.Report) ", "output": "{\n\tr.AddOnError(c.Append(\"level\"), ra.validateLevel())\n\tif len(ra.Devices) == 0 {\n\t\tr.AddOnError(c.Append(\"devices\"), errors.ErrRaidDevicesRequired)\n\t}\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n)\n\nfunc SkipLine(r io.ByteReader) error {\n\tfor {\n\t\tif b, err := r.ReadByte(); err != nil || b == '\\n' {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc ScanLine(r io.ByteReader, target string, ignorespace bool) (scanned string, pos int, err error) {\n\tscanned, pos, err = ScanUntil(r, target, ignorespace)\n\tif pos >= 0 {\n\t\terr = SkipLine(r)\n\t}\n\treturn\n}\n\nfunc Parse(path, name string) (parsed_name, desc string, err error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer file.Close()\n\tr := bufio.NewReader(file)\n\tvar i int\n\tswitch _, i, err = ScanLine(r, \"character file.\", false); {\n\tcase i < 0:\n\t\terr = errors.New(\"Unrecognized morgue format\")\n\t\tfallthrough\n\tcase err != nil:\n\t\treturn\n\t}\n\tfor {\n\t\tif parsed_name, i, err = ScanUntil(r, name, true); i == 0 {\n\t\t\tif _, i, err = ScanUntil(r, \"(\", false); i >= 0 {\n\t\t\t\tvar s string\n\t\t\t\tif s, err = r.ReadString(')'); err == nil {\n\t\t\t\t\tdesc = s[:len(s)-1]\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif i > 0 {\n\t\t\terr = SkipLine(r)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc ScanUntil(r io.ByteReader, target string, ignorespace bool) (scanned string, pos int, err error) ", "output": "{\n\tvar i, j, k int\n\tvar b byte\n\tbuf := make([]byte, 0, len(target))\n\tpos = -1\n\tfor {\n\t\tb, err = r.ReadByte()\n\t\tif err != nil {\n\t\t\treturn\n\t\t} else if b == '\\n' {\n\t\t\treturn\n\t\t}\n\t\tswitch target[j] {\n\t\tcase b:\n\t\t\tbuf = append(buf, b)\n\t\t\tj++\n\t\tdefault:\n\t\t\tif j > 0 && (b == ' ' || b == '\\t') {\n\t\t\t\tbuf = append(buf, b)\n\t\t\t\tk++\n\t\t\t} else {\n\t\t\t\tj = 0\n\t\t\t}\n\t\t}\n\t\tif j >= len(target) {\n\t\t\tscanned = string(buf)\n\t\t\tpos = i - j - k + 1\n\t\t\treturn\n\t\t}\n\t\ti++\n\t}\n\treturn\n}"} {"input": "package systray\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\n\n\nfunc quit() {\n\tC.quit()\n}\n\n\n\n\nfunc SetIcon(iconBytes []byte) {\n\tcstr := (*C.char)(unsafe.Pointer(&iconBytes[0]))\n\tC.setIcon(cstr, (C.int)(len(iconBytes)))\n}\n\n\nfunc SetTitle(title string) {\n\tC.setTitle(C.CString(title))\n}\n\n\n\nfunc SetTooltip(tooltip string) {\n\tC.setTooltip(C.CString(tooltip))\n}\n\nfunc addOrUpdateMenuItem(item *MenuItem) {\n\tvar disabled C.short = 0\n\tif item.disabled {\n\t\tdisabled = 1\n\t}\n\tvar checked C.short = 0\n\tif item.checked {\n\t\tchecked = 1\n\t}\n\tC.add_or_update_menu_item(\n\n\t\tC.int(item.id),\n\t\tC.CString(item.title),\n\t\tC.CString(item.tooltip),\n\t\tdisabled,\n\t\tchecked,\n\t)\n}\n\n\nfunc systray_ready() {\n\tsystrayReady()\n}\n\n\nfunc systray_menu_item_selected(cId C.int) {\n\tsystrayMenuItemSelected(int32(cId))\n}\n\nfunc nativeLoop() ", "output": "{\n\tC.nativeLoop()\n}"} {"input": "package omniscient\n\nimport (\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestHealth(t *testing.T) {\n\tvar mu sync.Mutex\n\thealthStatus := true\n\tcheck := func() bool {\n\t\tmu.Lock()\n\t\tdefer mu.Unlock()\n\t\treturn healthStatus\n\t}\n\n\tupdateCheckInterval := func(h *Health) error {\n\t\th.checkInterval = 1 * time.Millisecond\n\t\treturn nil\n\t}\n\n\th, err := NewHealth(\n\t\tHealthCheckOption(check),\n\t\tupdateCheckInterval)\n\tassert.NoError(t, err)\n\n\th.Start()\n\tdefer h.Stop()\n\n\tassert.True(t, h.IsOK(), \"health check status\")\n\n\tmu.Lock()\n\thealthStatus = false\n\tmu.Unlock()\n\n\t<-h.statusUpdated\n\tassert.False(t, h.IsOK(), \"health check status\")\n}\n\nfunc TestHealthCannotStartIfStarted(t *testing.T) {\n\tupdateCheckInterval := func(h *Health) error {\n\t\th.checkInterval = 1 * time.Millisecond\n\t\treturn nil\n\t}\n\n\th, err := NewHealth(updateCheckInterval)\n\tassert.NoError(t, err)\n\n\terr = h.Start()\n\tassert.NoError(t, err)\n\n\t<-h.stateChange\n\n\terr = h.Start()\n\tassert.Error(t, err)\n}\n\n\n\nfunc TestHealthCannotStopIfNotStarted(t *testing.T) ", "output": "{\n\tupdateCheckInterval := func(h *Health) error {\n\t\th.checkInterval = 1 * time.Millisecond\n\t\treturn nil\n\t}\n\n\th, err := NewHealth(updateCheckInterval)\n\tassert.NoError(t, err)\n\n\terr = h.Stop()\n\tassert.Error(t, err)\n}"} {"input": "package probe\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/FirebaseExtended/fcm-external-prober/Probe/src/utils\"\n)\n\nfunc TestFindDevice(t *testing.T) {\n\tmaker = utils.NewFakeCommandMaker([]string{\"TEST_DEVICE_1\\nTEST_DEVICE_2\\nTEST_DEVICE_3\"}, []bool{false}, false)\n\n\tstr, err := findDevice()\n\n\tif err != nil {\n\t\tt.Log(\"TestFindDevice: error on valid input\")\n\t\tt.Fail()\n\t}\n\tif str != \"TEST_DEVICE_1\" {\n\t\tt.Log(\"TestFindDevice: incorrect device found\")\n\t\tt.Fail()\n\t}\n}\n\nfunc TestConvertTimeExpected(t *testing.T) {\n\ttim, err := convertTime(\"123.456000\")\n\tif err != nil {\n\t\tt.Logf(\"TestConvertTimeExpected: returned error on valid input: %v\", err)\n\t\tt.FailNow()\n\t}\n\texpected := time.Unix(123, 456000000)\n\tif !tim.Equal(expected) {\n\t\tt.Logf(\"TestConvertTimeExpected: incorrect time returned: actual: %v, expected %v\", tim, expected)\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestConvertTimeError(t *testing.T) {\n\t_, err := convertTime(\"1.1.1.1\")\n\tif err == nil {\n\t\tt.Logf(\"TestConvertTimeExpected: no error returned on invalid input\")\n\t\tt.Fail()\n\t}\n}\n\n\n\nfunc TestFindTimeOffset(t *testing.T) ", "output": "{\n\tclock = utils.NewFakeClock([]time.Time{time.Unix(0, 0), time.Unix(1, 0)}, false)\n\tmaker = utils.NewFakeCommandMaker([]string{\"000.500000\"}, []bool{false}, false)\n\toffset, err := findTimeOffset()\n\tif err != nil {\n\t\tt.Logf(\"TestFindTimeOffset: error returned on valid input: %v\", err)\n\t\tt.FailNow()\n\t}\n\tif offset != 0 {\n\t\tt.Logf(\"TestFindTimeOffset: incorrect time offset: actual: %d, expected: 0\", offset)\n\t\tt.Fail()\n\t}\n}"} {"input": "package middleware\n\nimport (\n\t\"testing\"\n\n\t\"net/http\"\n\n\t\"github.com/hellofresh/janus/pkg/test\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestSuccessfulTrace(t *testing.T) ", "output": "{\n\tmw := NewOpenTracing(false)\n\tw, err := test.Record(\n\t\t\"GET\",\n\t\t\"/\",\n\t\tmap[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t},\n\t\tmw.Handler(http.HandlerFunc(test.Ping)),\n\t)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"application/json\", w.Header().Get(\"Content-Type\"))\n}"} {"input": "package native\n\nimport (\n\t\"errors\"\n\n\t\"github.com/CyCoreSystems/ari/v5\"\n)\n\n\ntype Modules struct {\n\tclient *Client\n}\n\n\nfunc (m *Modules) Get(key *ari.Key) *ari.ModuleHandle {\n\treturn ari.NewModuleHandle(m.client.stamp(key), m)\n}\n\n\nfunc (m *Modules) List(filter *ari.Key) (ret []*ari.Key, err error) {\n\tif filter == nil {\n\t\tfilter = ari.NodeKey(m.client.appName, m.client.node)\n\t}\n\n\tmodules := []struct {\n\t\tName string `json:\"name\"`\n\t}{}\n\n\terr = m.client.get(\"/asterisk/modules\", &modules)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, i := range modules {\n\t\tk := m.client.stamp(ari.NewKey(ari.ModuleKey, i.Name))\n\t\tif filter.Match(k) {\n\t\t\tif filter.Dialog != \"\" {\n\t\t\t\tk.Dialog = filter.Dialog\n\t\t\t}\n\n\t\t\tret = append(ret, k)\n\t\t}\n\t}\n\n\treturn\n}\n\n\nfunc (m *Modules) Load(key *ari.Key) error {\n\treturn m.client.post(\"/asterisk/modules/\"+key.ID, nil, nil)\n}\n\n\nfunc (m *Modules) Reload(key *ari.Key) error {\n\treturn m.client.put(\"/asterisk/modules/\"+key.ID, nil, nil)\n}\n\n\nfunc (m *Modules) Unload(key *ari.Key) error {\n\treturn m.client.del(\"/asterisk/modules/\"+key.ID, nil, \"\")\n}\n\n\n\n\nfunc (m *Modules) Data(key *ari.Key) (*ari.ModuleData, error) ", "output": "{\n\tif key == nil || key.ID == \"\" {\n\t\treturn nil, errors.New(\"module key not supplied\")\n\t}\n\n\tdata := new(ari.ModuleData)\n\tif err := m.client.get(\"/asterisk/modules/\"+key.ID, data); err != nil {\n\t\treturn nil, dataGetError(err, \"module\", \"%v\", key.ID)\n\t}\n\n\tdata.Key = m.client.stamp(key)\n\n\treturn data, nil\n}"} {"input": "package models\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestSetServiceState(t *testing.T) {\n\terr := SetServiceState(\"testState\", time.Now().UTC(), 1)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}\n\nfunc TestSetServiceStateByDays(t *testing.T) {\n\terr := SetServiceStateByDays(\"testStateDays\", 0, 1)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}\n\n\n\nfunc TestGetServiceState(t *testing.T) ", "output": "{\n\t_, i, err := GetServiceState(\"testState\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tif i != 1 {\n\t\tt.Error(\"testState incorrect\")\n\t\treturn\n\t}\n\n\t_, i, err = GetServiceState(\"testStateDays\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tif i != 1 {\n\t\tt.Error(\"testStateDays incorrect\")\n\t\treturn\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"golang.org/x/crypto/ssh\"\n)\n\ntype SshClient interface {\n\tClose() error\n\tExecCommand(command string) (string, error)\n}\n\ntype awsSshClient struct {\n\tclient *ssh.Client\n}\n\nfunc GetSshClient(username string, privateKey []byte, ip string) (*awsSshClient, error) {\n\tsigner, err := ssh.ParsePrivateKey(privateKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: username,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t}\n\tclient, err := ssh.Dial(\"tcp\", ip+\":22\", config)\n\n\treturn &awsSshClient{client: client}, err\n}\n\n\n\nfunc (sshClient *awsSshClient) ExecCommand(command string) (string, error) {\n\tsession, err := sshClient.client.NewSession()\n\tif err != nil {\n\t}\n\tdefer session.Close()\n\n\toutput, err := session.Output(command)\n\n\treturn string(output), err\n}\n\nfunc (sshClient *awsSshClient) Close() error ", "output": "{\n\treturn sshClient.client.Close()\n}"} {"input": "package component\n\ntype (\n\toptions struct {\n\t\tname string \n\t\tnameFunc func(string) string \n\t\tschedName string \n\t}\n\n\tOption func(options *options)\n)\n\n\nfunc WithName(name string) Option {\n\treturn func(opt *options) {\n\t\topt.name = name\n\t}\n}\n\n\n\n\n\n\nfunc WithSchedulerName(name string) Option {\n\treturn func(opt *options) {\n\t\topt.schedName = name\n\t}\n}\n\nfunc WithNameFunc(fn func(string) string) Option ", "output": "{\n\treturn func(opt *options) {\n\t\topt.nameFunc = fn\n\t}\n}"} {"input": "package sctp\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\ntype paramHeader struct {\n\ttyp paramType\n\tlen int\n\traw []byte\n}\n\nconst (\n\tparamHeaderLength = 4\n)\n\nfunc (p *paramHeader) marshal() ([]byte, error) {\n\tparamLengthPlusHeader := paramHeaderLength + len(p.raw)\n\n\trawParam := make([]byte, paramLengthPlusHeader)\n\tbinary.BigEndian.PutUint16(rawParam[0:], uint16(p.typ))\n\tbinary.BigEndian.PutUint16(rawParam[2:], uint16(paramLengthPlusHeader))\n\tcopy(rawParam[paramHeaderLength:], p.raw)\n\n\treturn rawParam, nil\n}\n\nfunc (p *paramHeader) unmarshal(raw []byte) {\n\tparamLengthPlusHeader := binary.BigEndian.Uint16(raw[2:])\n\tparamLength := paramLengthPlusHeader - initOptionalVarHeaderLength\n\n\tp.typ = paramType(binary.BigEndian.Uint16(raw[0:]))\n\tp.raw = raw[paramHeaderLength : paramHeaderLength+paramLength]\n\tp.len = int(paramLengthPlusHeader)\n}\n\n\n\n\nfunc (p paramHeader) String() string {\n\treturn fmt.Sprintf(\"%s (%d): %s\", p.typ, p.len, p.raw)\n}\n\nfunc (p *paramHeader) length() int ", "output": "{\n\treturn p.len\n}"} {"input": "package hamt\n\nconst (\n\tm1_32 = 0x55555555\n\tm2_32 = 0x33333333\n\tm4_32 = 0x0f0f0f0f\n)\n\n\n\nfunc popcount32(x uint32) int ", "output": "{\n\tx -= (x >> 1) & m1_32\n\tx = (x & m2_32) + ((x >> 2) & m2_32)\n\tx = (x + (x >> 4)) & m4_32\n\tx += x >> 8\n\tx += x >> 16\n\treturn int(x & 0x3f)\n}"} {"input": "package sounds\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype SimpleSampleMap func(float64) float64\n\n\n\ntype simpleWave struct {\n\thz float64\n\ttimeDelta float64\n\tmapper SimpleSampleMap\n}\n\n\n\nfunc NewSimpleWave(hz float64, mapper SimpleSampleMap) Sound {\n\treturn NewBaseSound(&simpleWave{hz, hz * SecondsPerCycle, mapper}, MaxLength)\n}\n\n\n\n\n\nfunc NewSineWave(hz float64) Sound {\n\treturn NewSimpleWave(hz, SineMap)\n}\n\n\nfunc NewSquareWave(hz float64) Sound {\n\treturn NewSimpleWave(hz, SquareMap)\n}\n\n\nfunc NewSawtoothWave(hz float64) Sound {\n\treturn NewSimpleWave(hz, SawtoothMap)\n}\n\n\nfunc NewTriangleWave(hz float64) Sound {\n\treturn NewSimpleWave(hz, TriangleMap)\n}\n\n\n\n\n\nfunc (s *simpleWave) Stop() {\n}\n\n\nfunc (s *simpleWave) Reset() {\n}\n\n\nfunc (s *simpleWave) String() string {\n\treturn fmt.Sprintf(\"Hz[%.2f]\", s.hz)\n}\n\n\nfunc SineMap(at float64) float64 {\n\treturn math.Sin(at * 2.0 * math.Pi)\n}\nfunc SquareMap(at float64) float64 {\n\tif at < 0.5 {\n\t\treturn -1.0\n\t} else {\n\t\treturn 1.0\n\t}\n}\nfunc SawtoothMap(at float64) float64 {\n\treturn at*2.0 - 1.0\n}\nfunc TriangleMap(at float64) float64 {\n\tif at > 0.5 {\n\t\tat = 1.0 - at\n\t}\n\treturn at*2.0*2.0 - 1.0\n}\n\nfunc (s *simpleWave) Run(base *BaseSound) ", "output": "{\n\tfor timeAt := float64(0); true; _, timeAt = math.Modf(timeAt + s.timeDelta) {\n\t\tif !base.WriteSample(s.mapper(timeAt)) {\n\t\t\treturn\n\t\t}\n\t}\n}"} {"input": "package terraform\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hashicorp/hcl2/hcl\"\n\t\"github.com/hashicorp/terraform/addrs\"\n\t\"github.com/zclconf/go-cty/cty\"\n)\n\n\n\n\ntype EvalLocal struct {\n\tAddr addrs.LocalValue\n\tExpr hcl.Expression\n}\n\nfunc (n *EvalLocal) Eval(ctx EvalContext) (interface{}, error) {\n\tval, diags := ctx.EvaluateExpr(n.Expr, cty.DynamicPseudoType, nil)\n\tif diags.HasErrors() {\n\t\treturn nil, diags.Err()\n\t}\n\n\tstate := ctx.State()\n\tif state == nil {\n\t\treturn nil, fmt.Errorf(\"cannot write local value to nil state\")\n\t}\n\n\tstate.SetLocalValue(n.Addr.Absolute(ctx.Path()), val)\n\n\treturn nil, nil\n}\n\n\n\n\ntype EvalDeleteLocal struct {\n\tAddr addrs.LocalValue\n}\n\n\n\nfunc (n *EvalDeleteLocal) Eval(ctx EvalContext) (interface{}, error) ", "output": "{\n\tstate := ctx.State()\n\tif state == nil {\n\t\treturn nil, nil\n\t}\n\n\tstate.RemoveLocalValue(n.Addr.Absolute(ctx.Path()))\n\treturn nil, nil\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"golang.org/x/sys/unix\"\n\n\t\"github.com/lxc/lxd/client\"\n\t\"github.com/lxc/lxd/lxd/sys\"\n\t\"github.com/lxc/lxd/shared\"\n\t\"github.com/lxc/lxd/shared/logging\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\nfunc TestIntegration_UnixSocket(t *testing.T) {\n\tdaemon, cleanup := newTestDaemon(t)\n\tdefer cleanup()\n\tclient, err := lxd.ConnectLXDUnix(daemon.UnixSocket(), nil)\n\trequire.NoError(t, err)\n\n\tserver, _, err := client.GetServer()\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"trusted\", server.Auth)\n\tassert.False(t, server.Environment.ServerClustered)\n\tassert.False(t, client.IsClustered())\n}\n\n\n\n\nfunc newTestDaemon(t *testing.T) (*Daemon, func()) {\n\tresetLogger := logging.Testing(t)\n\n\tos, osCleanup := sys.NewTestOS(t)\n\n\tdaemon := newDaemon(newConfig(), os)\n\trequire.NoError(t, daemon.Init())\n\n\tcleanup := func() {\n\t\tdaemon.Stop(context.Background(), unix.SIGQUIT)\n\t\tosCleanup()\n\t\tresetLogger()\n\t}\n\n\treturn daemon, cleanup\n}\n\n\n\n\n\n\n\nfunc newConfig() *DaemonConfig {\n\treturn &DaemonConfig{\n\t\tRaftLatency: 0.8,\n\t\tTrace: []string{\"dqlite\"},\n\t\tDqliteSetupTimeout: 10 * time.Second,\n\t}\n}\n\nfunc newDaemons(t *testing.T, n int) ([]*Daemon, func()) ", "output": "{\n\tdaemons := make([]*Daemon, n)\n\tcleanups := make([]func(), n)\n\n\tfor i := 0; i < n; i++ {\n\t\tdaemons[i], cleanups[i] = newTestDaemon(t)\n\t\tif i > 0 {\n\t\t\tcert := shared.TestingAltKeyPair()\n\t\t\tdaemons[i].endpoints.NetworkUpdateCert(cert)\n\t\t}\n\t}\n\n\tcleanup := func() {\n\t\tfor _, cleanup := range cleanups {\n\t\t\tcleanup()\n\t\t}\n\t}\n\n\treturn daemons, cleanup\n}"} {"input": "package server\n\nimport (\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/codahale/hdrhistogram\"\n\t\"github.com/fluxio/metricd/pb\"\n)\n\nconst LOWEST_VALUE = 0\nconst HIGHEST_VALUE = 1e7\n\n\n\nconst DIGITS_OF_PRECISION = 2\n\ntype histAggregator struct {\n\tname string\n\tindexedLabels map[string]string\n\tunindexedLabels map[string]string\n\th *hdrhistogram.Histogram\n\tm sync.Mutex\n}\n\n\n\n\n\n\n\n\n\n\nfunc (a *histAggregator) GetAggregations() []*pb.Metric {\n\ta.m.Lock()\n\tdefer a.m.Unlock()\n\n\tvar res []*pb.Metric\n\tif a.h != nil && a.h.TotalCount() != 0 {\n\t\tfor _, q := range []float64{0, 50, 90, 95, 99, 100} {\n\t\t\tres = append(res, &pb.Metric{\n\t\t\t\tName: a.name + \"_p\" + strconv.Itoa(int(q)),\n\t\t\t\tIndexedLabels: a.indexedLabels,\n\t\t\t\tUnindexedLabels: a.unindexedLabels,\n\t\t\t\tValue: &pb.Metric_DoubleValue{float64(a.h.ValueAtQuantile(q))},\n\t\t\t\tTs: time.Now().UnixNano(),\n\t\t\t})\n\t\t}\n\t\ta.h = nil\n\t}\n\treturn res\n}\n\nfunc NewHistAggregator(name string, indexedLabels, unindexedLabels map[string]string) aggregatorUnit {\n\treturn &histAggregator{\n\t\tname: name,\n\t\tindexedLabels: indexedLabels,\n\t\tunindexedLabels: unindexedLabels,\n\t}\n}\n\nfunc (a *histAggregator) AddValue(value float64, ts int64) ", "output": "{\n\ta.m.Lock()\n\tdefer a.m.Unlock()\n\n\tif a.h == nil {\n\t\ta.h = hdrhistogram.New(LOWEST_VALUE, HIGHEST_VALUE, DIGITS_OF_PRECISION)\n\t}\n\ta.h.RecordValue(int64(value))\n}"} {"input": "package utils\n\nimport \"fmt\"\n\nfunc ExampleStringSet_Add() {\n\tset := NewStringSet()\n\tset.Add(\"a\")\n\tset.Add(\"b\")\n\n\tfmt.Println(set)\n\tset.Add(\"a\")\n\tfmt.Println(set)\n\n}\n\n\n\nfunc ExampleNewStringSetFromStringMapKeys() {\n\tm := map[string]string{\n\t\t\"a\": \"some a value\",\n\t\t\"b\": \"some b value\",\n\t}\n\n\tset := NewStringSetFromStringMapKeys(m)\n\tfmt.Println(set)\n\n}\n\nfunc ExampleStringSet_ToSlice() {\n\ta := NewStringSet()\n\ta.Add(\"z\")\n\ta.Add(\"b\")\n\n\tfmt.Println(a.ToSlice())\n\n}\n\nfunc ExampleStringSet_IsEmpty() {\n\ta := NewStringSet()\n\n\tfmt.Println(a.IsEmpty())\n\ta.Add(\"a\")\n\tfmt.Println(a.IsEmpty())\n\n}\n\nfunc ExampleStringSet_Equals() {\n\ta := NewStringSet(\"a\", \"b\")\n\tb := NewStringSet(\"a\", \"b\", \"c\")\n\tfmt.Println(a.Equals(b))\n\n\ta.Add(\"c\")\n\tfmt.Println(a.Equals(b))\n\n}\n\nfunc ExampleStringSet_Contains() {\n\ta := NewStringSet(\"a\", \"b\")\n\tfmt.Println(a.Contains(\"z\"))\n\tfmt.Println(a.Contains(\"a\"))\n\n}\n\nfunc ExampleStringSet_Minus() {\n\ta := NewStringSet(\"a\", \"b\")\n\tb := NewStringSet(\"b\", \"c\")\n\tdelta := a.Minus(b)\n\n\tfmt.Println(delta)\n}\n\nfunc ExampleNewStringSet() ", "output": "{\n\ta := NewStringSet()\n\ta.Add(\"a\")\n\ta.Add(\"b\")\n\n\tb := NewStringSet(\"b\", \"a\")\n\n\tfmt.Println(a.Equals(b))\n\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/flynn/go-docopt\"\n)\n\nfunc init() {\n\tregister(\"install\", runInstaller, `usage: flynn install`)\n}\n\n\n\nfunc runInstaller(args *docopt.Args) error ", "output": "{\n\tfmt.Printf(\"DEPRECATED: `flynn install` has been deprecated.\\nRefer to https://flynn.io/docs/installation for current installation instructions.\\nAn unsupported and unmaintained snapshot of the installer binaries at the time of deprecation is available at https://dl.flynn.io/flynn-install-deprecated.tar.gz\\n\")\n\treturn nil\n}"} {"input": "package transactions\n\nimport \"github.com/joshheinrichs/httperr\"\n\n\n\nfunc IsAdmin(userID string) (bool, httperr.Error) {\n\treturn false, ErrNotImplemented\n}\n\nfunc RemoveAdmin(requesterID, userID string) httperr.Error {\n\treturn ErrNotImplemented\n}\n\nfunc AddAdmin(requesterID, userID string) httperr.Error ", "output": "{\n\treturn ErrNotImplemented\n}"} {"input": "package transfer\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/inverse-inc/packetfence/go/coredns/plugin/pkg/rcode\"\n\n\t\"github.com/miekg/dns\"\n)\n\n\n\nfunc (t *Transfer) Notify(zone string) error {\n\tif t == nil { \n\t\treturn nil\n\t}\n\n\tm := new(dns.Msg)\n\tm.SetNotify(zone)\n\tc := new(dns.Client)\n\n\tx := longestMatch(t.xfrs, zone)\n\tif x == nil {\n\t\treturn fmt.Errorf(\"no such zone registred in the transfer plugin: %s\", zone)\n\t}\n\n\tvar err1 error\n\tfor _, t := range x.to {\n\t\tif t == \"*\" {\n\t\t\tcontinue\n\t\t}\n\t\tif err := sendNotify(c, m, t); err != nil {\n\t\t\terr1 = err\n\t\t}\n\t}\n\tlog.Debugf(\"Sent notifies for zone %q to %v\", zone, x.to)\n\treturn err1 \n}\n\n\n\nfunc sendNotify(c *dns.Client, m *dns.Msg, s string) error ", "output": "{\n\tvar err error\n\n\tcode := dns.RcodeServerFailure\n\tfor i := 0; i < 3; i++ {\n\t\tret, _, err := c.Exchange(m, s)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tcode = ret.Rcode\n\t\tif code == dns.RcodeSuccess {\n\t\t\treturn nil\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"notify for zone %q was not accepted by %q: %q\", m.Question[0].Name, s, err)\n\t}\n\treturn fmt.Errorf(\"notify for zone %q was not accepted by %q: rcode was %q\", m.Question[0].Name, s, rcode.ToString(code))\n}"} {"input": "package api_auth\n\nimport (\n\t\"golang.org/x/oauth2\"\n\t\"testing\"\n)\n\nfunc TestNoAuth(t *testing.T) {\n\ta := NewNoAuth()\n\tif !a.IsNoAuth() {\n\t\tt.Error(\"invalid\")\n\t}\n\tif a.PeerName() != \"\" || a.Token() == nil || a.PeerName() != \"\" ||\n\t\ta.Description() != \"\" || a.Supplemental() != \"\" || len(a.Scopes()) > 0 {\n\t\tt.Error(\"invalid\")\n\t}\n}\n\n\n\nfunc TestContext(t *testing.T) ", "output": "{\n\tc := NewContext(&oauth2.Token{}, &oauth2.Config{}, \"test-context\", []string{\"test-scope\"})\n\tif c.IsNoAuth() || c.PeerName() != \"test-context\" || c.Scopes()[0] != \"test-scope\" ||\n\t\tc.Description() != \"\" || c.Supplemental() != \"\" || c.Token() == nil {\n\t\tt.Error(\"invalid\")\n\t}\n\n\tc = NewContextWithAttr(c, &oauth2.Config{}, \"test-desc\", \"test-suppl\")\n\tif c.IsNoAuth() || c.PeerName() != \"test-context\" || c.Scopes()[0] != \"test-scope\" ||\n\t\tc.Description() != \"test-desc\" || c.Supplemental() != \"test-suppl\" || c.Token() == nil {\n\t\tt.Error(\"invalid\")\n\t}\n}"} {"input": "package config\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n)\n\ntype Template struct {\n\tFile string\n\tSource string\n}\n\n\n\n\n\nfunc (t Template) Validate() []error {\n\terrors := make([]error, 0, 2)\n\tif fi, err := os.Stat(t.Source); err != nil {\n\t\tvar msg string\n\t\tswitch {\n\t\tcase os.IsNotExist(err):\n\t\t\tmsg = fmt.Sprintf(\"template source not found: %s\", t.Source)\n\t\tcase os.IsPermission(err):\n\t\t\tmsg = fmt.Sprintf(\"template source permission denied: %s\", t.Source)\n\t\tdefault:\n\t\t\tmsg = fmt.Sprintf(\"template source error: %s: %s\", err, t.Source)\n\t\t}\n\t\terrors = append(errors, ValidationError(msg))\n\t} else if !fi.Mode().IsRegular() {\n\t\tmsg := fmt.Sprintf(\"template source is not a file: %s\", t.Source)\n\t\terrors = append(errors, ValidationError(msg))\n\t}\n\n\tdir := path.Dir(t.File)\n\tif fi, err := os.Stat(dir); err != nil {\n\t\tvar msg string\n\t\tswitch {\n\t\tcase os.IsNotExist(err):\n\t\t\tmsg = fmt.Sprintf(\"template file directory not found: %s\", t.File)\n\t\tcase os.IsPermission(err):\n\t\t\tmsg = fmt.Sprintf(\"template file directory permission denied: %s\", t.File)\n\t\tdefault:\n\t\t\tmsg = fmt.Sprintf(\"template file directory error: %s: %s\", err, t.File)\n\t\t}\n\t\terrors = append(errors, ValidationError(msg))\n\t} else if !fi.Mode().IsDir() {\n\t\tmsg := fmt.Sprintf(\"template file directory is not a directory: %s\", t.File)\n\t\terrors = append(errors, ValidationError(msg))\n\t}\n\treturn errors\n}\n\nfunc (t *Template) SetYAML(tag string, value interface{}) bool ", "output": "{\n\tAssertIsMap(\"template\", value)\n\tfor file, source := range value.(map[interface{}](interface{})) {\n\t\tAssertIsString(\"file\", file)\n\t\tAssertIsString(\"source\", source)\n\t\tt.File = file.(string)\n\t\tt.Source = source.(string)\n\t\treturn true\n\t}\n\tpanic(ParseError(fmt.Sprintf(`config template %+v cannot be parsed`, value)))\n}"} {"input": "package engine\n\nimport (\n\tvtrpcpb \"vitess.io/vitess/go/vt/proto/vtrpc\"\n\t\"vitess.io/vitess/go/vt/vterrors\"\n\n\t\"vitess.io/vitess/go/sqltypes\"\n\t\"vitess.io/vitess/go/vt/proto/query\"\n)\n\nvar _ Primitive = (*UpdateTarget)(nil)\n\n\ntype UpdateTarget struct {\n\tTarget string\n\n\tnoInputs\n\n\tnoTxNeeded\n}\n\nfunc (updTarget *UpdateTarget) description() PrimitiveDescription {\n\treturn PrimitiveDescription{\n\t\tOperatorType: \"UpdateTarget\",\n\t\tOther: map[string]interface{}{\"target\": updTarget.Target},\n\t}\n}\n\n\nfunc (updTarget *UpdateTarget) RouteType() string {\n\treturn \"UpdateTarget\"\n}\n\n\n\n\n\nfunc (updTarget *UpdateTarget) GetTableName() string {\n\treturn \"\"\n}\n\n\nfunc (updTarget *UpdateTarget) TryExecute(vcursor VCursor, bindVars map[string]*query.BindVariable, wantfields bool) (*sqltypes.Result, error) {\n\terr := vcursor.Session().SetTarget(updTarget.Target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &sqltypes.Result{}, nil\n}\n\n\nfunc (updTarget *UpdateTarget) TryStreamExecute(vcursor VCursor, bindVars map[string]*query.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error {\n\tresult, err := updTarget.TryExecute(vcursor, bindVars, wantfields)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn callback(result)\n}\n\n\nfunc (updTarget *UpdateTarget) GetFields(vcursor VCursor, bindVars map[string]*query.BindVariable) (*sqltypes.Result, error) {\n\treturn nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, \"[BUG] GetFields not reachable for use statement\")\n}\n\nfunc (updTarget *UpdateTarget) GetKeyspaceName() string ", "output": "{\n\treturn updTarget.Target\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\nconst (\n\tMaxFilterAddDataSize = 520\n)\n\n\n\n\n\n\ntype MsgFilterAdd struct {\n\tData []byte\n}\n\n\n\nfunc (msg *MsgFilterAdd) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filteradd message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterAdd.BtcDecode\", str)\n\t}\n\n\tvar err error\n\tmsg.Data, err = ReadVarBytes(r, pver, MaxFilterAddDataSize,\n\t\t\"filteradd data\")\n\treturn err\n}\n\n\n\nfunc (msg *MsgFilterAdd) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filteradd message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterAdd.BtcEncode\", str)\n\t}\n\n\tsize := len(msg.Data)\n\tif size > MaxFilterAddDataSize {\n\t\tstr := fmt.Sprintf(\"filteradd size too large for message \"+\n\t\t\t\"[size %v, max %v]\", size, MaxFilterAddDataSize)\n\t\treturn messageError(\"MsgFilterAdd.BtcEncode\", str)\n\t}\n\n\treturn WriteVarBytes(w, pver, msg.Data)\n}\n\n\n\nfunc (msg *MsgFilterAdd) Command() string {\n\treturn CmdFilterAdd\n}\n\n\n\nfunc (msg *MsgFilterAdd) MaxPayloadLength(pver uint32) uint32 {\n\treturn uint32(VarIntSerializeSize(MaxFilterAddDataSize)) +\n\t\tMaxFilterAddDataSize\n}\n\n\n\n\n\nfunc NewMsgFilterAdd(data []byte) *MsgFilterAdd ", "output": "{\n\treturn &MsgFilterAdd{\n\t\tData: data,\n\t}\n}"} {"input": "package zip\n\nimport (\n\t\"hash/crc32\"\n\n\t. \"github.com/zxh0/jvm.go/jvmgo/any\"\n\t\"github.com/zxh0/jvm.go/jvmgo/jvm/rtda\"\n\trtc \"github.com/zxh0/jvm.go/jvmgo/jvm/rtda/class\"\n)\n\nfunc init() {\n\t_crc(updateBytes, \"updateBytes\", \"(I[BII)I\")\n}\n\n\n\n\n\nfunc updateBytes(frame *rtda.Frame) {\n\tvars := frame.LocalVars()\n\tcrc := uint32(vars.GetInt(0))\n\tbyteArr := vars.GetRef(1)\n\toff := vars.GetInt(2)\n\t_len := vars.GetInt(3)\n\n\tgoBytes := byteArr.GoBytes()\n\tgoBytes = goBytes[off : off+_len]\n\tcrc = crc32.Update(crc, crc32.IEEETable, goBytes)\n\n\tstack := frame.OperandStack()\n\tstack.PushInt(int32(crc))\n}\n\nfunc _crc(method Any, name, desc string) ", "output": "{\n\trtc.RegisterNativeMethod(\"java/util/zip/CRC32\", name, desc, method)\n}"} {"input": "package suite_init\n\ntype SuiteData struct {\n\t*StubsData\n\t*SynchronizedSuiteCallbacksData\n\t*WerfBinaryData\n\t*ProjectNameData\n\t*K8sDockerRegistryData\n\t*TmpDirData\n\t*ContainerRegistryPerImplementationData\n}\n\n\n\nfunc (data *SuiteData) SetupSynchronizedSuiteCallbacks(setupData *SynchronizedSuiteCallbacksData) bool {\n\tdata.SynchronizedSuiteCallbacksData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupWerfBinary(setupData *WerfBinaryData) bool {\n\tdata.WerfBinaryData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupProjectName(setupData *ProjectNameData) bool {\n\tdata.ProjectNameData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupK8sDockerRegistry(setupData *K8sDockerRegistryData) bool {\n\tdata.K8sDockerRegistryData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupTmp(setupData *TmpDirData) bool {\n\tdata.TmpDirData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupContainerRegistryPerImplementation(setupData *ContainerRegistryPerImplementationData) bool {\n\tdata.ContainerRegistryPerImplementationData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupStubs(setupData *StubsData) bool ", "output": "{\n\tdata.StubsData = setupData\n\treturn true\n}"} {"input": "package pgparser\n\nimport (\n\t\"strings\"\n\n\t\"go.bmatsuo.co/go-lexer\"\n)\n\nconst (\n\titemLeftBrace lexer.ItemType = iota\n\titemRightBrace\n\titemLeftParen\n\titemRightParen\n\titemComma\n\titemQuotedString\n\titemBareString\n)\n\nfunc stateBegin(l *lexer.Lexer) lexer.StateFn {\n\tr, n := l.Advance()\n\n\tswitch r {\n\tcase '{':\n\t\tl.Emit(itemLeftBrace)\n\t\treturn stateBegin\n\tcase '}':\n\t\tl.Emit(itemRightBrace)\n\t\treturn stateBegin\n\tcase '(':\n\t\tl.Emit(itemLeftParen)\n\t\treturn stateBegin\n\tcase ')':\n\t\tl.Emit(itemRightParen)\n\t\treturn stateBegin\n\tcase ',':\n\t\tl.Emit(itemComma)\n\t\treturn stateBegin\n\tcase '\"':\n\t\tl.Backup()\n\t\treturn stateQuotedString\n\tdefault:\n\t\tif n > 0 {\n\t\t\tl.Backup()\n\t\t\treturn stateBareString\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc stateBareString(l *lexer.Lexer) lexer.StateFn {\n\tl.AcceptRunFunc(func(r rune) bool {\n\t\treturn !strings.ContainsRune(`{}(),\"`, r)\n\t})\n\n\tl.Emit(itemBareString)\n\n\treturn stateBegin\n}\n\nfunc stateQuotedString(l *lexer.Lexer) lexer.StateFn ", "output": "{\n\tif !l.Accept(\"\\\"\") {\n\t\tl.Errorf(\"expected an opening quote\")\n\t}\n\n\tfor {\n\t\tif l.Accept(\"\\\\\") {\n\t\t\tl.Advance()\n\t\t}\n\n\t\tn := l.AcceptRunFunc(func(r rune) bool {\n\t\t\treturn r != '\\\\' && r != '\"'\n\t\t})\n\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !l.Accept(\"\\\"\") {\n\t\tl.Errorf(\"expected a closing quote\")\n\t}\n\n\tl.Emit(itemQuotedString)\n\n\treturn stateBegin\n}"} {"input": "package xmlkey\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/xml\"\n\t\"math/big\"\n)\n\ntype (\n\tkeyXML struct {\n\t\tXMLName xml.Name `xml:\"RSAKeyValue\"`\n\t\tpublicKeyXML\n\t\tprivateKeyXML\n\t}\n\n\tpublicKeyXML struct {\n\t\tModulus, Exponent *bigInt\n\t}\n\tprivateKeyXML struct {\n\t\tP, Q, DP, DQ, D, InverseQ *bigInt\n\t}\n\n\tbigInt struct{ *big.Int }\n)\n\nfunc (k keyXML) HasPublicKey() bool {\n\treturn allNotEmpty(k.Exponent, k.Modulus)\n}\n\nfunc (k keyXML) HasPrivateKey() bool {\n\treturn allNotEmpty(k.D, k.DP, k.DQ, k.InverseQ, k.P, k.Q)\n}\n\nfunc allNotEmpty(bis ...*bigInt) bool {\n\tfor _, bi := range bis {\n\t\tif bi == nil || bi.IsEmpty() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (bi *bigInt) UnmarshalText(text []byte) error {\n\tbs := make([]byte, base64.StdEncoding.DecodedLen(len(text)))\n\tif _, err := base64.StdEncoding.Decode(bs, text); err != nil {\n\t\treturn err\n\t}\n\tif bi.Int == nil {\n\t\tbi.Int = new(big.Int)\n\t}\n\tbi.Int.SetBytes(bytes.TrimRight(bs, \"\\x00\"))\n\treturn nil\n}\n\n\n\nfunc (bi bigInt) BigInt() *big.Int {\n\treturn bi.Int\n}\n\nfunc (bi bigInt) Integer() int {\n\treturn int(bi.Int64())\n}\n\nfunc (bi bigInt) IsEmpty() bool {\n\treturn bi.Int == nil\n}\n\nfunc (bi *bigInt) MarshalText() ([]byte, error) ", "output": "{\n\ttext := make([]byte, base64.StdEncoding.EncodedLen(len(bi.Bytes())))\n\tbase64.StdEncoding.Encode(text, bi.Bytes())\n\treturn text, nil\n}"} {"input": "package file\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\n\n\ntype darwinExFileInfo struct {\n\tos.FileInfo\n\tfid FID\n\tpath string\n}\n\n\n\nfunc timespecToTime(ts syscall.Timespec) time.Time {\n\treturn time.Unix(int64(ts.Sec), int64(ts.Nsec))\n}\n\n\nfunc (fi *darwinExFileInfo) CTime() time.Time {\n\treturn timespecToTime(fi.Sys().(*syscall.Stat_t).Ctimespec)\n}\n\n\nfunc (fi *darwinExFileInfo) ATime() time.Time {\n\treturn timespecToTime(fi.Sys().(*syscall.Stat_t).Atimespec)\n}\n\n\n\n\n\nfunc (fi *darwinExFileInfo) Path() string {\n\treturn fi.path\n}\n\n\nfunc systemExFileInfo(fi os.FileInfo, path string) *darwinExFileInfo {\n\tfid := FID{\n\t\tIDLow: fi.Sys().(*syscall.Stat_t).Ino,\n\t}\n\tabsolute, _ := filepath.Abs(path)\n\treturn &darwinExFileInfo{\n\t\tFileInfo: fi,\n\t\tfid: fid,\n\t\tpath: filepath.Clean(absolute),\n\t}\n}\n\nfunc (fi *darwinExFileInfo) FID() FID ", "output": "{\n\treturn fi.fid\n}"} {"input": "package mcquery_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/sean-callahan/mcquery\"\n)\n\nfunc ExampleDial() {\n\t_, err := mcquery.Dial(\"127.0.0.1:25565\", time.Second)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\n\nfunc ExampleMcQuery_GetStatus() ", "output": "{\n\tmcq, err := mcquery.Dial(\"127.0.0.1:25565\", time.Second)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tstatus, _, err := mcq.GetStatus()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(status[\"game_id\"])\n}"} {"input": "package ratecounter\n\nimport \"time\"\n\n\n\ntype RateCounter struct {\n\tcounter Counter\n\tinterval time.Duration\n}\n\n\nfunc NewRateCounter(intrvl time.Duration) *RateCounter {\n\treturn &RateCounter{\n\t\tinterval: intrvl,\n\t}\n}\n\n\nfunc (r *RateCounter) Incr(val int64) {\n\tr.counter.Incr(val)\n\tgo r.scheduleDecrement(val)\n}\n\n\n\n\nfunc (r *RateCounter) Rate() int64 {\n\treturn r.counter.Value()\n}\n\nfunc (r *RateCounter) scheduleDecrement(amount int64) ", "output": "{\n\ttime.Sleep(r.interval)\n\tr.counter.Incr(-1 * amount)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\ttl \"github.com/JoelOtter/termloop\"\n\t\"os\"\n)\n\ntype MovingText struct {\n\ttext *tl.Text\n}\n\nfunc (m *MovingText) Draw(s *tl.Screen) {\n\tm.text.Draw(s)\n}\n\n\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Println(\"Please provide a string as first argument\")\n\t\treturn\n\t}\n\tg := tl.NewGame()\n\tg.Screen().AddEntity(&MovingText{\n\t\ttext: tl.NewText(0, 0, os.Args[1], tl.ColorWhite, tl.ColorBlue),\n\t})\n\tg.Start()\n}\n\nfunc (m *MovingText) Tick(ev tl.Event) ", "output": "{\n\tif ev.Type == tl.EventKey {\n\t\tx, y := m.text.Position()\n\t\tswitch ev.Key {\n\t\tcase tl.KeyArrowRight:\n\t\t\tx += 1\n\t\t\tbreak\n\t\tcase tl.KeyArrowLeft:\n\t\t\tx -= 1\n\t\t\tbreak\n\t\tcase tl.KeyArrowUp:\n\t\t\ty -= 1\n\t\t\tbreak\n\t\tcase tl.KeyArrowDown:\n\t\t\ty += 1\n\t\t\tbreak\n\t\t}\n\t\tm.text.SetPosition(x, y)\n\t}\n}"} {"input": "package replication\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\tclient \"k8s.io/kubernetes/pkg/client/unversioned\"\n)\n\n\n\n\n\ntype OverlappingControllers []api.ReplicationController\n\nfunc (o OverlappingControllers) Len() int { return len(o) }\nfunc (o OverlappingControllers) Swap(i, j int) { o[i], o[j] = o[j], o[i] }\n\nfunc (o OverlappingControllers) Less(i, j int) bool {\n\tif o[i].CreationTimestamp.Equal(o[j].CreationTimestamp) {\n\t\treturn o[i].Name < o[j].Name\n\t}\n\treturn o[i].CreationTimestamp.Before(o[j].CreationTimestamp)\n}\n\nfunc updateReplicaCount(rcClient client.ReplicationControllerInterface, controller api.ReplicationController, numReplicas int) (updateErr error) ", "output": "{\n\tif controller.Status.Replicas == numReplicas &&\n\t\tcontroller.Generation == controller.Status.ObservedGeneration {\n\t\treturn nil\n\t}\n\tgeneration := controller.Generation\n\n\tvar getErr error\n\tfor i, rc := 0, &controller; ; i++ {\n\t\tglog.V(4).Infof(\"Updating replica count for rc: %v, %d->%d (need %d), sequence No: %v->%v\",\n\t\t\tcontroller.Name, controller.Status.Replicas, numReplicas, controller.Spec.Replicas, controller.Status.ObservedGeneration, generation)\n\n\t\trc.Status = api.ReplicationControllerStatus{Replicas: numReplicas, ObservedGeneration: generation}\n\t\t_, updateErr = rcClient.UpdateStatus(rc)\n\t\tif updateErr == nil || i >= statusUpdateRetries {\n\t\t\treturn updateErr\n\t\t}\n\t\tif rc, getErr = rcClient.Get(controller.Name); getErr != nil {\n\t\t\treturn getErr\n\t\t}\n\t}\n}"} {"input": "package expression\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/juju/errors\"\n\t\"github.com/pingcap/tidb/context\"\n)\n\nvar (\n\t_ Expression = (*Position)(nil)\n)\n\n\n\n\ntype Position struct {\n\tN int\n\tName string\n}\n\n\n\n\n\nfunc (p *Position) IsStatic() bool {\n\treturn false\n}\n\n\nfunc (p *Position) String() string {\n\tif len(p.Name) > 0 {\n\t\treturn p.Name\n\t}\n\treturn fmt.Sprintf(\"%d\", p.N)\n}\n\n\nfunc (p *Position) Eval(ctx context.Context, args map[interface{}]interface{}) (v interface{}, err error) {\n\tf, ok := args[ExprEvalPositionFunc]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"no eval position function\")\n\t}\n\tgot, ok := f.(func(int) (interface{}, error))\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"invalid eval position function format\")\n\t}\n\n\treturn got(p.N)\n}\n\n\nfunc (p *Position) Accept(v Visitor) (Expression, error) {\n\treturn v.VisitPosition(p)\n}\n\nfunc (p *Position) Clone() Expression ", "output": "{\n\tnewP := *p\n\treturn &newP\n}"} {"input": "package model\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/utils\"\n\n\t\"strings\"\n)\n\n\ntype DeleteServerMetadataResponse struct {\n\tHttpStatusCode int `json:\"-\"`\n}\n\n\n\nfunc (o DeleteServerMetadataResponse) String() string ", "output": "{\n\tdata, err := utils.Marshal(o)\n\tif err != nil {\n\t\treturn \"DeleteServerMetadataResponse struct{}\"\n\t}\n\n\treturn strings.Join([]string{\"DeleteServerMetadataResponse\", string(data)}, \" \")\n}"} {"input": "package route\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"path\"\n\t\"strings\"\n)\n\n\nvar match matcher = prefixMatcher\n\n\ntype matcher func(uri string, r *Route) bool\n\n\nfunc prefixMatcher(uri string, r *Route) bool {\n\treturn strings.HasPrefix(uri, r.Path)\n}\n\n\nfunc globMatcher(uri string, r *Route) bool {\n\tvar hasMatch, err = path.Match(r.Path, uri)\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] Glob matching error %s for path %s route %s\", err, uri, r.Path)\n\t\treturn false\n\t}\n\treturn hasMatch\n}\n\n\n\n\nfunc SetMatcher(s string) error ", "output": "{\n\tswitch s {\n\tcase \"prefix\":\n\t\tmatch = prefixMatcher\n\tcase \"glob\":\n\t\tmatch = globMatcher\n\tdefault:\n\t\treturn fmt.Errorf(\"route: invalid matcher: %s\", s)\n\t}\n\treturn nil\n}"} {"input": "package logger\n\n\n\ntype options struct {\n\tvalues map[string][]OptionItem\n}\n\n\ntype Option struct {\n\tApply func(op *options)\n}\n\n\n\n\n\nfunc SweeperOption(name string, duration int, settings map[string]interface{}) Option {\n\treturn Option{func(op *options) {\n\t\tvals := make([]OptionItem, 0)\n\t\tvals = append(vals, OptionItem{\"duration\", duration})\n\n\t\tif len(settings) > 0 {\n\t\t\tfor k, v := range settings {\n\t\t\t\tvals = append(vals, OptionItem{k, v})\n\t\t\t}\n\t\t}\n\n\t\top.values[name] = vals\n\t}}\n}\n\n\nfunc GetterOption(name string, settings map[string]interface{}) Option {\n\treturn Option{func(op *options) {\n\t\tvals := make([]OptionItem, 0)\n\t\tif len(settings) > 0 {\n\t\t\tfor k, v := range settings {\n\t\t\t\tvals = append(vals, OptionItem{k, v})\n\t\t\t}\n\t\t}\n\n\t\top.values[name] = vals\n\t}}\n}\n\n\ntype OptionItem struct {\n\tfield string\n\tval interface{}\n}\n\n\nfunc (o *OptionItem) Field() string {\n\treturn o.field\n}\n\n\nfunc (o *OptionItem) Int() int {\n\tif o.val == nil {\n\t\treturn 0\n\t}\n\n\treturn o.val.(int)\n}\n\n\nfunc (o *OptionItem) String() string {\n\tif o.val == nil {\n\t\treturn \"\"\n\t}\n\n\treturn o.val.(string)\n}\n\n\nfunc (o *OptionItem) Raw() interface{} {\n\treturn o.val\n}\n\nfunc BackendOption(name string, level string, settings map[string]interface{}) Option ", "output": "{\n\treturn Option{func(op *options) {\n\t\tvals := make([]OptionItem, 0)\n\t\tvals = append(vals, OptionItem{\"level\", level})\n\n\t\tif len(settings) > 0 {\n\t\t\tfor k, v := range settings {\n\t\t\t\tvals = append(vals, OptionItem{k, v})\n\t\t\t}\n\t\t}\n\n\t\top.values[name] = vals\n\t}}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\nconst (\n\tFileType_File = 1\n\tFileType_Directory = 2\n)\n\nfunc IfString(condition bool, trueVal, falseVal string) string {\n\tif condition {\n\t\treturn trueVal\n\t}\n\treturn falseVal\n}\n\nfunc IfInt(condition bool, trueVal, falseVal int) int {\n\tif condition {\n\t\treturn trueVal\n\t}\n\treturn falseVal\n}\n\n\nfunc ExpandString(s string, data map[string]string) string {\n\treturn os.Expand(s, func(p string) string {\n\t\tv, _ := data[p]\n\t\treturn v\n\t})\n}\n\n\n\n\nfunc CopyFile(src, dest string, mode os.FileMode) error {\n\tdata, err := ioutil.ReadFile(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(dest, data, mode)\n}\n\n\nfunc GetFileType(path string) (fileType int, err error) {\n\tvar fi os.FileInfo\n\n\tfi, err = os.Stat(path)\n\tif err == nil {\n\t\tfileType = IfInt(fi.IsDir(), FileType_Directory, FileType_File)\n\t} else if os.IsNotExist(err) {\n\t\terr = fmt.Errorf(\"can not find directory or file: %s\", path)\n\t}\n\treturn\n}\n\nfunc CreateDir(dir string, mode os.FileMode) error ", "output": "{\n\t_, err := os.Stat(dir)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn os.MkdirAll(dir, mode)\n\t\t}\n\t}\n\treturn err\n}"} {"input": "package providers\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"net/url\"\n\t\"strings\"\n)\n\ntype GoogleProvider struct {\n\t*ProviderData\n}\n\nfunc NewGoogleProvider(p *ProviderData) *GoogleProvider {\n\tp.ProviderName = \"Google\"\n\tif p.LoginUrl.String() == \"\" {\n\t\tp.LoginUrl = &url.URL{Scheme: \"https\",\n\t\t\tHost: \"accounts.google.com\",\n\t\t\tPath: \"/o/oauth2/auth\"}\n\t}\n\tif p.RedeemUrl.String() == \"\" {\n\t\tp.RedeemUrl = &url.URL{Scheme: \"https\",\n\t\t\tHost: \"accounts.google.com\",\n\t\t\tPath: \"/o/oauth2/token\"}\n\t}\n\tif p.ValidateUrl.String() == \"\" {\n\t\tp.ValidateUrl = &url.URL{Scheme: \"https\",\n\t\t\tHost: \"www.googleapis.com\",\n\t\t\tPath: \"/oauth2/v1/tokeninfo\"}\n\t}\n\tif p.Scope == \"\" {\n\t\tp.Scope = \"profile email\"\n\t}\n\treturn &GoogleProvider{ProviderData: p}\n}\n\n\n\nfunc jwtDecodeSegment(seg string) ([]byte, error) {\n\tif l := len(seg) % 4; l > 0 {\n\t\tseg += strings.Repeat(\"=\", 4-l)\n\t}\n\n\treturn base64.URLEncoding.DecodeString(seg)\n}\n\nfunc (p *GoogleProvider) ValidateToken(access_token string) bool {\n\treturn validateToken(p, access_token, nil)\n}\n\nfunc (s *GoogleProvider) GetEmailAddress(body []byte, access_token string) (string, error) ", "output": "{\n\tvar response struct {\n\t\tIdToken string `json:\"id_token\"`\n\t}\n\n\tif err := json.Unmarshal(body, &response); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tjwt := strings.Split(response.IdToken, \".\")\n\tb, err := jwtDecodeSegment(jwt[1])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar email struct {\n\t\tEmail string `json:\"email\"`\n\t}\n\terr = json.Unmarshal(b, &email)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif email.Email == \"\" {\n\t\treturn \"\", errors.New(\"missing email\")\n\t}\n\treturn email.Email, nil\n}"} {"input": "package main\n\ntype T int\n\n\n\nvar invalidT T\n\nfunc main() {\n\tvar err error\n\tif err > invalidT {\n\t\tprintln(\"ok\")\n\t}\n}\n\nfunc (t T) Error() string ", "output": "{ return \"T: error\" }"} {"input": "package main\n\nimport (\n\t\"strings\"\n)\n\nconst etcHostsFile = \"/etc/hosts\"\n\n\n\n\n\n\n\nfunc getDNSServerList() []string {\n\tfileData := readFile(\"/etc/resolv.conf\")\n\tlines := strings.Split(fileData, \"\\n\")\n\tfor _, line := range lines {\n\t\tif strings.HasPrefix(line, \"nameserver\") {\n\t\t\treturn strings.Split(line, \" \")[1:]\n\t\t}\n\t}\n\n\tpanic(\"Could not find DNS search list!\")\n}\n\nfunc getDNSSuffixList() []string ", "output": "{\n\tfileData := readFile(\"/etc/resolv.conf\")\n\tlines := strings.Split(fileData, \"\\n\")\n\tfor _, line := range lines {\n\t\tif strings.HasPrefix(line, \"search\") {\n\t\t\treturn strings.Split(line, \" \")[1:]\n\t\t}\n\t}\n\n\tpanic(\"Could not find DNS search list!\")\n}"} {"input": "package common\n\nimport (\n\t\"encoding/binary\"\n\t\"sort\"\n)\n\n\n\ntype Uint64Slice []uint64\n\n\nfunc (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] }\nfunc (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p Uint64Slice) Sort() { sort.Sort(p) }\n\nfunc SearchUint64s(a []uint64, x uint64) int {\n\treturn sort.Search(len(a), func(i int) bool { return a[i] >= x })\n}\n\nfunc (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) }\n\n\n\nfunc PutUint64LE(dest []byte, i uint64) {\n\tbinary.LittleEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64LE(src []byte) uint64 {\n\treturn binary.LittleEndian.Uint64(src)\n}\n\nfunc PutUint64BE(dest []byte, i uint64) {\n\tbinary.BigEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64BE(src []byte) uint64 {\n\treturn binary.BigEndian.Uint64(src)\n}\n\nfunc PutInt64LE(dest []byte, i int64) {\n\tbinary.LittleEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64LE(src []byte) int64 {\n\treturn int64(binary.LittleEndian.Uint64(src))\n}\n\nfunc PutInt64BE(dest []byte, i int64) {\n\tbinary.BigEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64BE(src []byte) int64 {\n\treturn int64(binary.BigEndian.Uint64(src))\n}\n\nfunc (p Uint64Slice) Len() int ", "output": "{ return len(p) }"} {"input": "package machine\n\nimport (\n\t\"github.com/juju/cmd\"\n\n\tjujucmd \"github.com/juju/juju/cmd\"\n\t\"github.com/juju/juju/cmd/modelcmd\"\n)\n\nconst showMachineCommandDoc = `\nShow a specified machine on a model. Default format is in yaml,\nother formats can be specified with the \"--format\" option.\nAvailable formats are yaml, tabular, and json\n\nExamples:\n juju show-machine 0\n juju show-machine 1 2 3\n\n`\n\n\nfunc NewShowMachineCommand() cmd.Command {\n\treturn modelcmd.Wrap(newShowMachineCommand(nil))\n}\n\n\n\n\ntype showMachineCommand struct {\n\tbaselistMachinesCommand\n}\n\n\nfunc (c *showMachineCommand) Info() *cmd.Info {\n\treturn jujucmd.Info(&cmd.Info{\n\t\tName: \"show-machine\",\n\t\tArgs: \" ...\",\n\t\tPurpose: \"Show a machine's status.\",\n\t\tDoc: showMachineCommandDoc,\n\t})\n}\n\n\nfunc (c *showMachineCommand) Init(args []string) error {\n\tc.machineIds = args\n\treturn nil\n}\n\nfunc newShowMachineCommand(api statusAPI) *showMachineCommand ", "output": "{\n\tshowCmd := &showMachineCommand{}\n\tshowCmd.defaultFormat = \"yaml\"\n\tshowCmd.api = api\n\treturn showCmd\n}"} {"input": "package unit\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestCurrentFormat(t *testing.T) {\n\tt.Parallel()\n\tfor _, test := range []struct {\n\t\tvalue Current\n\t\tformat string\n\t\twant string\n\t}{\n\t\t{1.23456789, \"%v\", \"1.23456789 A\"},\n\t\t{1.23456789, \"%.1v\", \"1 A\"},\n\t\t{1.23456789, \"%20.1v\", \" 1 A\"},\n\t\t{1.23456789, \"%20v\", \" 1.23456789 A\"},\n\t\t{1.23456789, \"%1v\", \"1.23456789 A\"},\n\t\t{1.23456789, \"%#v\", \"unit.Current(1.23456789)\"},\n\t\t{1.23456789, \"%s\", \"%!s(unit.Current=1.23456789 A)\"},\n\t} {\n\t\tgot := fmt.Sprintf(test.format, test.value)\n\t\tif got != test.want {\n\t\t\tt.Errorf(\"Format %q %v: got: %q want: %q\", test.format, test.value, got, test.want)\n\t\t}\n\t}\n}\n\nfunc TestCurrent(t *testing.T) ", "output": "{\n\tt.Parallel()\n\tfor _, value := range []float64{-1, 0, 1} {\n\t\tvar got Current\n\t\terr := got.From(Current(value).Unit())\n\t\tif err != nil {\n\t\t\tt.Errorf(\"unexpected error for %T conversion: %v\", got, err)\n\t\t}\n\t\tif got != Current(value) {\n\t\t\tt.Errorf(\"unexpected result from round trip of %T(%v): got: %v want: %v\", got, value, got, value)\n\t\t}\n\t\tif got != got.Current() {\n\t\t\tt.Errorf(\"unexpected result from self interface method call: got: %#v want: %#v\", got, value)\n\t\t}\n\t\terr = got.From(ether(1))\n\t\tif err == nil {\n\t\t\tt.Errorf(\"expected error for ether to %T conversion\", got)\n\t\t}\n\t}\n}"} {"input": "package dexcom\n\nimport (\n\t\"log\"\n\t\"time\"\n)\n\n\nfunc (cgm *CGM) ReadHistory(pageType PageType, since time.Time) Records {\n\tfirst, last := cgm.ReadPageRange(pageType)\n\tif cgm.Error() != nil {\n\t\treturn nil\n\t}\n\tvar results Records\n\tproc := func(r Record) error {\n\t\tt := r.Time()\n\t\tif !t.After(since) {\n\t\t\tlog.Printf(\"stopping %v scan at %s\", pageType, t.Format(UserTimeLayout))\n\t\t\treturn IterationDone\n\t\t}\n\t\tresults = append(results, r)\n\t\treturn nil\n\t}\n\tcgm.IterRecords(pageType, first, last, proc)\n\treturn results\n}\n\n\nfunc (cgm *CGM) ReadCount(pageType PageType, count int) Records {\n\tfirst, last := cgm.ReadPageRange(pageType)\n\tif cgm.Error() != nil {\n\t\treturn nil\n\t}\n\tresults := make(Records, 0, count)\n\tproc := func(r Record) error {\n\t\tresults = append(results, r)\n\t\tif len(results) == count {\n\t\t\treturn IterationDone\n\t\t}\n\t\treturn nil\n\t}\n\tcgm.IterRecords(pageType, first, last, proc)\n\treturn results\n}\n\n\n\n\n\nfunc MergeHistory(slices ...Records) Records ", "output": "{\n\tn := len(slices)\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tif n == 1 {\n\t\treturn slices[0]\n\t}\n\tlength := make([]int, n)\n\ttotal := 0\n\tfor i, v := range slices {\n\t\tlength[i] = len(v)\n\t\ttotal += len(v)\n\t}\n\tresults := make(Records, total)\n\tindex := make([]int, n)\n\tfor next := range results {\n\t\twhich := -1\n\t\tmax := time.Time{}\n\t\tfor i, v := range slices {\n\t\t\tif index[i] < len(v) {\n\t\t\t\tt := v[index[i]].Time()\n\t\t\t\tif t.After(max) {\n\t\t\t\t\twhich = i\n\t\t\t\t\tmax = t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresults[next] = slices[which][index[which]]\n\t\tindex[which]++\n\t}\n\treturn results\n}"} {"input": "package main_test\n\nimport \"testing\"\n\n\n\nfunc TestRunCommand(t *testing.T) ", "output": "{\n\ttestHelper(t, \"run\", \"Run\")\n}"} {"input": "package customer\n\nimport (\n\t\"testing\"\n\n\tassert \"github.com/stretchr/testify/require\"\n\tstripe \"github.com/stripe/stripe-go\"\n\t_ \"github.com/stripe/stripe-go/testing\"\n)\n\nfunc TestCustomerDel(t *testing.T) {\n\tcustomer, err := Del(\"cus_123\", nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerGet(t *testing.T) {\n\tcustomer, err := Get(\"cus_123\", nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerList(t *testing.T) {\n\ti := List(&stripe.CustomerListParams{})\n\n\tassert.True(t, i.Next())\n\tassert.Nil(t, i.Err())\n\tassert.NotNil(t, i.Customer())\n}\n\nfunc TestCustomerNew(t *testing.T) {\n\tcustomer, err := New(&stripe.CustomerParams{\n\t\tEmail: stripe.String(\"foo@example.com\"),\n\t\tShipping: &stripe.CustomerShippingDetailsParams{\n\t\t\tAddress: &stripe.AddressParams{\n\t\t\t\tLine1: stripe.String(\"line1\"),\n\t\t\t\tCity: stripe.String(\"city\"),\n\t\t\t},\n\t\t\tName: stripe.String(\"name\"),\n\t\t},\n\t})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\n\n\nfunc TestCustomerUpdate(t *testing.T) {\n\tcustomer, err := Update(\"cus_123\", &stripe.CustomerParams{\n\t\tEmail: stripe.String(\"foo@example.com\"),\n\t})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerNew_NilParams(t *testing.T) ", "output": "{\n\tcustomer, err := New(nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}"} {"input": "package goyaml2\n\nimport (\n\t\"io\"\n)\n\n\n\nfunc Write(w io.Writer, v interface{}) error ", "output": "{\n\treturn nil\n}"} {"input": "package dnsresolver\n\n\n\n\n\n\ntype dnsCache map[string]map[string][]string \n\nfunc (c dnsCache) get(label, rtype string) ([]string, bool) {\n\tv1, ok := c[label]\n\tif !ok {\n\t\treturn nil, false\n\t}\n\tv2, ok := v1[rtype]\n\tif !ok {\n\t\treturn nil, false\n\t}\n\treturn v2, true\n}\n\n\n\nfunc (c dnsCache) put(label, rtype string, answers []string) ", "output": "{\n\t_, ok := c[label]\n\tif !ok {\n\t\tc[label] = make(map[string][]string)\n\t}\n\tc[label][rtype] = answers\n}"} {"input": "package fda\n\n\n\ntype FoodService struct {\n\tclient *Client\n}\n\n\nfunc (s *FoodService) EnforcementSearch(search string, limit, skip int) ([]EnforcementReport, *Meta, error) {\n\tdata := []EnforcementReport{}\n\n\tmeta, err := s.client.search(\"/food/enforcement\", search, limit, skip, &data)\n\treturn data, meta, err\n}\n\n\n\n\n\nfunc (s *FoodService) EnforcementCount(search, count string, data interface{}, limit int) (*Meta, error) ", "output": "{\n\tmeta, err := s.client.count(\"/food/enforcement\", search, count, limit, &data)\n\treturn meta, err\n}"} {"input": "package robotname\n\nimport \"testing\"\n\n\n\nfunc TestCollisions(t *testing.T) ", "output": "{\n\tm := map[string]bool{}\n\tfor i := 0; i < (10000); i++ {\n\t\tn := New().Name()\n\t\tif m[n] {\n\t\t\tt.Fatalf(\"Name %s reissued after %d robots.\", n, i)\n\t\t}\n\t\tm[n] = true\n\t}\n\tr := New()\n\tfor i := 0; i < 10000; i++ {\n\t\tr.Reset()\n\t\tn := r.Name()\n\t\tif m[n] {\n\t\t\tt.Fatalf(\"Name %s reissued after Reset.\", n)\n\t\t}\n\t\tm[n] = true\n\t}\n}"} {"input": "package isogram\n\nimport \"unicode\"\n\n\nconst testVersion = 1\n\n\n\n\nfunc IsIsogram(text string) bool ", "output": "{\n\tletters := make(map[rune]bool)\n\n\tfor _, r := range text {\n\t\tr = unicode.ToLower(r)\n\t\tif unicode.IsLetter(r) && letters[r] {\n\t\t\treturn false\n\t\t}\n\t\tletters[r] = true\n\t}\n\n\treturn true\n}"} {"input": "package mock_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/pingcap/check\"\n\t\"github.com/pingcap/tidb/br/pkg/mock\"\n\t\"github.com/pingcap/tidb/util/testleak\"\n)\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\nvar _ = Suite(&testClusterSuite{})\n\ntype testClusterSuite struct {\n\tmock *mock.Cluster\n}\n\nfunc (s *testClusterSuite) SetUpSuite(c *C) {\n\tvar err error\n\ts.mock, err = mock.NewCluster()\n\tc.Assert(err, IsNil)\n}\n\nfunc (s *testClusterSuite) TearDownSuite(c *C) {\n\ttestleak.AfterTest(c)()\n}\n\n\n\nfunc (s *testClusterSuite) TestSmoke(c *C) ", "output": "{\n\tc.Assert(s.mock.Start(), IsNil)\n\ts.mock.Stop()\n}"} {"input": "package godspeed\n\nimport (\n\t\"io\"\n\t\"net/http\"\n)\n\ntype bodyWrapperFactory func(http.ResponseWriter) io.Writer\n\ntype bodyWrapper struct {\n\trespw http.ResponseWriter\n\tw io.Writer\n\tposthandler bodyWrapperFactory\n}\n\nfunc (w *bodyWrapper) Header() http.Header {\n\treturn w.respw.Header()\n}\n\nfunc (w *bodyWrapper) Write(data []byte) (int, error) {\n\tif w.w == nil {\n\t\tw.w = w.posthandler(w.respw)\n\t}\n\treturn w.w.Write(data)\n}\n\n\n\nfunc (w *bodyWrapper) Close() error {\n\tvar err error\n\tif c, ok := w.w.(io.Closer); ok {\n\t\terr = c.Close()\n\t}\n\treturn err\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc wrapBody(respw http.ResponseWriter, writerGen bodyWrapperFactory) *bodyWrapper {\n\treturn &bodyWrapper{\n\t\trespw: respw,\n\t\tposthandler: writerGen,\n\t}\n}\n\nfunc (w *bodyWrapper) WriteHeader(s int) ", "output": "{\n\tw.respw.WriteHeader(s)\n}"} {"input": "package entities\n\nconst (\n\tActionMove = iota + 1\n\n\tActionAttack\n\n\tActionCastSpell\n\n\tActionGather\n\n\tActionLoot\n\n\tActionConsume\n)\n\n\n\n\n\n\n\n\n\n\n\ntype Action interface {\n\tSetTarget(Entity)\n\tSetSelf(Entity)\n\n\tGetTypeAction() uint8\n\tGetSelf() Entity\n\tGetTarget() Entity\n\n\tPlay() error\n}\n\n\ntype SimpleAction struct {\n\tself Entity\n\ttarget Entity\n\ttypeAction uint8\n}\n\n\n\n\n\nfunc (action *SimpleAction) SetTarget(target Entity) {\n\taction.target = target\n}\n\n\nfunc (action *SimpleAction) GetTarget() Entity {\n\treturn action.target\n}\n\n\nfunc (action *SimpleAction) SetSelf(self Entity) {\n\taction.self = self\n}\n\n\nfunc (action *SimpleAction) GetSelf() Entity {\n\treturn action.self\n}\n\n\nfunc (action *SimpleAction) Play() error {\n\treturn nil\n}\n\nfunc (action *SimpleAction) GetTypeAction() uint8 ", "output": "{\n\treturn action.GetTypeAction()\n}"} {"input": "package system\n\nimport (\n\t\"github.com/Graylog2/collector-sidecar/common\"\n\t\"runtime\"\n)\n\ntype Inventory struct {\n}\n\n\n\nfunc (inv *Inventory) Version() string {\n\treturn common.CollectorVersion\n}\n\nfunc (inv *Inventory) Linux() bool {\n\treturn runtime.GOOS == \"linux\"\n}\n\nfunc (inv *Inventory) Darwin() bool {\n\treturn runtime.GOOS == \"darwin\"\n}\n\nfunc (inv *Inventory) Windows() bool {\n\treturn runtime.GOOS == \"windows\"\n}\n\nfunc (inv *Inventory) LinuxPlatform() string {\n\tif runtime.GOOS == \"linux\" {\n\t\treturn common.LinuxPlatformFamily()\n\t} else {\n\t\treturn runtime.GOOS\n\t}\n}\n\nfunc NewInventory() *Inventory ", "output": "{\n\treturn &Inventory{}\n}"} {"input": "package gce\n\nimport (\n\t\"time\"\n\n\tcompute \"google.golang.org/api/compute/v1\"\n)\n\n\n\n\n\n\n\nfunc (gce *GCECloud) ReserveGlobalStaticIP(name, ipAddress string) (address *compute.Address, err error) {\n\tmc := newStaticIPMetricContext(\"reserve\")\n\top, err := gce.service.GlobalAddresses.Insert(gce.projectID, &compute.Address{Name: name, Address: ipAddress}).Do()\n\n\tif err != nil {\n\t\treturn nil, mc.Observe(err)\n\t}\n\n\tif err := gce.waitForGlobalOp(op, mc); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gce.service.GlobalAddresses.Get(gce.projectID, name).Do()\n}\n\n\nfunc (gce *GCECloud) DeleteGlobalStaticIP(name string) error {\n\tmc := newStaticIPMetricContext(\"delete\")\n\top, err := gce.service.GlobalAddresses.Delete(gce.projectID, name).Do()\n\tif err != nil {\n\t\treturn mc.Observe(err)\n\t}\n\treturn gce.waitForGlobalOp(op, mc)\n}\n\n\nfunc (gce *GCECloud) GetGlobalStaticIP(name string) (address *compute.Address, err error) {\n\treturn gce.service.GlobalAddresses.Get(gce.projectID, name).Do()\n}\n\nfunc newStaticIPMetricContext(request string) *metricContext ", "output": "{\n\treturn &metricContext{\n\t\tstart: time.Now(),\n\t\tattributes: []string{\"staticip_\" + request, unusedMetricLabel, unusedMetricLabel},\n\t}\n}"} {"input": "package v1\n\nimport (\n\tv1 \"github.com/openshift/api/oauth/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype OAuthAuthorizeTokenLister interface {\n\tList(selector labels.Selector) (ret []*v1.OAuthAuthorizeToken, err error)\n\tGet(name string) (*v1.OAuthAuthorizeToken, error)\n\tOAuthAuthorizeTokenListerExpansion\n}\n\n\ntype oAuthAuthorizeTokenLister struct {\n\tindexer cache.Indexer\n}\n\n\n\n\n\nfunc (s *oAuthAuthorizeTokenLister) List(selector labels.Selector) (ret []*v1.OAuthAuthorizeToken, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.OAuthAuthorizeToken))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *oAuthAuthorizeTokenLister) Get(name string) (*v1.OAuthAuthorizeToken, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"oauthauthorizetoken\"), name)\n\t}\n\treturn obj.(*v1.OAuthAuthorizeToken), nil\n}\n\nfunc NewOAuthAuthorizeTokenLister(indexer cache.Indexer) OAuthAuthorizeTokenLister ", "output": "{\n\treturn &oAuthAuthorizeTokenLister{indexer: indexer}\n}"} {"input": "package header\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n\n\n\n\n\n\n\nfunc Options(c *gin.Context) {\n\tif c.Request.Method != \"OPTIONS\" {\n\t\tc.Next()\n\t} else {\n\t\tc.Header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tc.Header(\"Access-Control-Allow-Methods\", \"GET,POST,PUT,PATCH,DELETE,OPTIONS\")\n\t\tc.Header(\"Access-Control-Allow-Headers\", \"authorization, origin, content-type, accept\")\n\t\tc.Header(\"Allow\", \"HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS\")\n\t\tc.Header(\"Content-Type\", \"application/json\")\n\t\tc.AbortWithStatus(200)\n\t}\n}\n\n\n\nfunc Secure(c *gin.Context) {\n\tc.Header(\"Access-Control-Allow-Origin\", \"*\")\n\tc.Header(\"X-Frame-Options\", \"DENY\")\n\tc.Header(\"X-Content-Type-Options\", \"nosniff\")\n\tc.Header(\"X-XSS-Protection\", \"1; mode=block\")\n\tif c.Request.TLS != nil {\n\t\tc.Header(\"Strict-Transport-Security\", \"max-age=31536000\")\n\t}\n}\n\nfunc NoCache(c *gin.Context) ", "output": "{\n\tc.Header(\"Cache-Control\", \"no-cache, no-store, max-age=0, must-revalidate, value\")\n\tc.Header(\"Expires\", \"Thu, 01 Jan 1970 00:00:00 GMT\")\n\tc.Header(\"Last-Modified\", time.Now().UTC().Format(http.TimeFormat))\n\tc.Next()\n}"} {"input": "package config\n\nimport \"github.com/corestoreio/csfw/utils\"\n\n\n\ntype ScopePerm uint64\n\n\nvar ScopePermAll = ScopePerm(1< 0\n}\n\n\n\nfunc (user *User) TextureBlobHashBytes() (buf []byte) {\n\tbuf, err := hex.DecodeString(user.TextureBlob)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn buf\n}\n\nfunc (user *User) HasComment() bool ", "output": "{\n\treturn len(user.CommentBlob) > 0\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"sync\"\n)\n\nvar a int = 1\n\nfunc main() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\twg := sync.WaitGroup{}\n\n\twg.Add(10)\n\n\tfor i := 0; i < 10; i++ {\n\t\tgo GO(&wg, i)\n\t}\n\twg.Wait()\n}\n\n\n\nfunc GO(wg *sync.WaitGroup, index int) ", "output": "{\n\tfor i := 0; i < 100000000; i++ {\n\t\ta += i\n\t}\n\tfmt.Println(index, a)\n\twg.Done()\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/hyperledger/fabric/common/channelconfig\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n)\n\n\ntype Orderer struct {\n\tConsensusTypeVal string\n\tBatchSizeVal *ab.BatchSize\n\tBatchTimeoutVal time.Duration\n\tKafkaBrokersVal []string\n\tMaxChannelsCountVal uint64\n\tOrganizationsVal map[string]channelconfig.Org\n\tCapabilitiesVal channelconfig.OrdererCapabilities\n}\n\n\nfunc (scm *Orderer) ConsensusType() string {\n\treturn scm.ConsensusTypeVal\n}\n\n\nfunc (scm *Orderer) BatchSize() *ab.BatchSize {\n\treturn scm.BatchSizeVal\n}\n\n\nfunc (scm *Orderer) BatchTimeout() time.Duration {\n\treturn scm.BatchTimeoutVal\n}\n\n\nfunc (scm *Orderer) KafkaBrokers() []string {\n\treturn scm.KafkaBrokersVal\n}\n\n\nfunc (scm *Orderer) MaxChannelsCount() uint64 {\n\treturn scm.MaxChannelsCountVal\n}\n\n\nfunc (scm *Orderer) Organizations() map[string]channelconfig.Org {\n\treturn scm.OrganizationsVal\n}\n\n\nfunc (scm *Orderer) Capabilities() channelconfig.OrdererCapabilities {\n\treturn scm.CapabilitiesVal\n}\n\n\ntype OrdererCapabilities struct {\n\tSupportedErr error\n\n\tSetChannelModPolicyDuringCreateVal bool\n\n\tResubmissionVal bool\n}\n\n\nfunc (oc *OrdererCapabilities) Supported() error {\n\treturn oc.SupportedErr\n}\n\n\nfunc (oc *OrdererCapabilities) SetChannelModPolicyDuringCreate() bool {\n\treturn oc.SetChannelModPolicyDuringCreateVal\n}\n\n\n\n\nfunc (oc *OrdererCapabilities) Resubmission() bool ", "output": "{\n\treturn oc.ResubmissionVal\n}"} {"input": "package bmore\n\nimport (\n\t\"fmt\"\n)\n\ntype Context struct {\n}\n\n\n\nfunc New() (*Context, error) ", "output": "{\n\tfmt.Println(\"Creating context...\")\n\tcontext := &Context{}\n\treturn context, nil\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSEMRCluster_HadoopJarStepConfig struct {\n\n\tArgs []string `json:\"Args,omitempty\"`\n\n\tJar string `json:\"Jar,omitempty\"`\n\n\tMainClass string `json:\"MainClass,omitempty\"`\n\n\tStepProperties []AWSEMRCluster_KeyValue `json:\"StepProperties,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) AWSCloudFormationType() string {\n\treturn \"AWS::EMR::Cluster.HadoopJarStepConfig\"\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\n\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetDependsOn(dependencies []string) ", "output": "{\n\tr._dependsOn = dependencies\n}"} {"input": "package api\n\nimport (\n\t\"log\"\n\t\"net/http\"\n)\n\ntype HttpsRedirectingFileHandler interface {\n\thttp.Handler\n\tfileHandler() http.Handler\n}\n\ntype httpsHandler struct {\n\tinternalHandler http.Handler\n}\n\nfunc NewHttpsRedirectFileHandler(dir http.Dir) HttpsRedirectingFileHandler {\n\thandler := &httpsHandler{}\n\thandler.internalHandler = http.FileServer(dir)\n\treturn handler\n}\n\nfunc redirect(w http.ResponseWriter, req *http.Request) {\n\ttarget := \"https://\" + req.Host + req.URL.Path\n\tif len(req.URL.RawQuery) > 0 {\n\t\ttarget += \"?\" + req.URL.RawQuery\n\t}\n\tlog.Printf(\"redirect to: %s\", target)\n\thttp.Redirect(w, req, target,\n\t\thttp.StatusTemporaryRedirect)\n}\n\n\n\nfunc (h *httpsHandler) fileHandler() http.Handler {\n\treturn h.internalHandler\n}\n\nfunc (h *httpsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tif !isXForwardedHTTPS(req) {\n\t\tredirect(w, req)\n\t} else {\n\t\th.fileHandler().ServeHTTP(w, req)\n\t}\n}\n\nfunc isXForwardedHTTPS(request *http.Request) bool ", "output": "{\n\txForwardedProto := request.Header.Get(\"X-Forwarded-Proto\")\n\n\treturn len(xForwardedProto) > 0 && xForwardedProto == \"https\"\n}"} {"input": "package minfraud\n\n\n\ntype DeliverySpeed int\n\nconst (\n\tDeliverySpeedUnknown DeliverySpeed = iota\n\n\tDeliverySpeedSameDay\n\n\tDeliverySpeedOvernight\n\n\tDeliverySpeedExpedited\n\n\tDeliverySpeedStandard\n)\n\n\n\n\n\nfunc (d *DeliverySpeed) UnmarshalJSON(data []byte) error {\n\tif len(data) < 3 {\n\t\t*d = DeliverySpeedUnknown\n\t} else {\n\t\tswitch string(data[1 : len(data)-1]) {\n\t\tcase \"same_day\":\n\t\t\t*d = DeliverySpeedSameDay\n\t\tcase \"overnight\":\n\t\t\t*d = DeliverySpeedOvernight\n\t\tcase \"expedited\":\n\t\t\t*d = DeliverySpeedExpedited\n\t\tcase \"standard\":\n\t\t\t*d = DeliverySpeedStandard\n\t\tdefault:\n\t\t\t*d = DeliverySpeedUnknown\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (d DeliverySpeed) MarshalJSON() ([]byte, error) ", "output": "{\n\tswitch d {\n\tcase DeliverySpeedSameDay:\n\t\treturn []byte(`\"same_day\"`), nil\n\tcase DeliverySpeedOvernight:\n\t\treturn []byte(`\"overnight\"`), nil\n\tcase DeliverySpeedExpedited:\n\t\treturn []byte(`\"expedited\"`), nil\n\tcase DeliverySpeedStandard:\n\t\treturn []byte(`\"standard\"`), nil\n\tdefault:\n\t\treturn []byte(`\"unknown_delivery_speed\"`), nil\n\t}\n}"} {"input": "package logs \n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/model/otlpgrpc\"\n\t\"go.opentelemetry.io/collector/obsreport\"\n)\n\nconst (\n\tdataFormatProtobuf = \"protobuf\"\n\treceiverTransport = \"grpc\"\n)\n\n\ntype Receiver struct {\n\tnextConsumer consumer.Logs\n\tobsrecv *obsreport.Receiver\n}\n\n\n\n\n\nfunc (r *Receiver) Export(ctx context.Context, req otlpgrpc.LogsRequest) (otlpgrpc.LogsResponse, error) {\n\tld := req.Logs()\n\tnumSpans := ld.LogRecordCount()\n\tif numSpans == 0 {\n\t\treturn otlpgrpc.NewLogsResponse(), nil\n\t}\n\n\tctx = r.obsrecv.StartLogsOp(ctx)\n\terr := r.nextConsumer.ConsumeLogs(ctx, ld)\n\tr.obsrecv.EndLogsOp(ctx, dataFormatProtobuf, numSpans, err)\n\n\treturn otlpgrpc.NewLogsResponse(), err\n}\n\nfunc New(id config.ComponentID, nextConsumer consumer.Logs, set component.ReceiverCreateSettings) *Receiver ", "output": "{\n\treturn &Receiver{\n\t\tnextConsumer: nextConsumer,\n\t\tobsrecv: obsreport.NewReceiver(obsreport.ReceiverSettings{\n\t\t\tReceiverID: id,\n\t\t\tTransport: receiverTransport,\n\t\t\tReceiverCreateSettings: set,\n\t\t}),\n\t}\n}"} {"input": "package main\n\nimport (\n \"time\"\n \"net/http\"\n \"io/ioutil\"\n \"strings\"\n\n \"launchpad.net/gocheck\"\n \"github.com/mreiferson/go-httpclient\"\n)\n\nconst url string = \"http://127.0.0.1:8080\"\n\nfunc setupHivy() {\n \n go hivy(url, false)\n}\n\nfunc sendHTTPRequest(method, endpoint, user, pass string) (*http.Response, error){\n transport := &httpclient.Transport{\n ConnectTimeout: 1*time.Second,\n RequestTimeout: 10*time.Second,\n ResponseHeaderTimeout: 5*time.Second,\n }\n defer transport.Close()\n\n client := &http.Client{Transport: transport}\n prefix := \"/v0/actions\"\n req, _ := http.NewRequest(method, url + prefix + endpoint, nil)\n req.SetBasicAuth(user, pass)\n\n \n return client.Do(req)\n}\n\n\n\nfunc (t *testSuite) TestBadAuthentification() {\n resp, err := sendHTTPRequest(\"GET\", \"/dummy\", \"wrong\", \"login\")\n defer resp.Body.Close()\n t.Check(err, gocheck.IsNil)\n\n contents, err := ioutil.ReadAll(resp.Body)\n t.Check(err, gocheck.IsNil)\n\n t.True(strings.Contains(string(contents), \"Key Not Found\"))\n \n}\n\nfunc (t *testSuite) TestHivyDummy() ", "output": "{\n resp, err := sendHTTPRequest(\"GET\", \"/dummy\", \"xav\", \"boss\")\n defer resp.Body.Close()\n t.Check(err, gocheck.IsNil)\n\n contents, err := ioutil.ReadAll(resp.Body)\n t.Check(err, gocheck.IsNil)\n\n t.True(strings.Contains(string(contents), \"dummy\"))\n \n}"} {"input": "package guard\n\nimport (\n\t\"time\"\n\n\t\"gopkg.in/workanator/go-floc.v2\"\n\t\"gopkg.in/workanator/go-floc.v2/errors\"\n)\n\n\ntype TimeoutTrigger func(ctx floc.Context, ctrl floc.Control, id interface{})\n\n\n\n\n\n\n\n\n\n\nfunc OnTimeout(when WhenTimeoutFunc, id interface{}, job floc.Job, timeoutTrigger TimeoutTrigger) floc.Job {\n\treturn func(ctx floc.Context, ctrl floc.Control) error {\n\t\tdone := make(chan error)\n\t\tdefer close(done)\n\n\t\ttimer := time.NewTimer(when(ctx, id))\n\t\tdefer timer.Stop()\n\n\t\tgo func() {\n\t\t\tvar err error\n\t\t\tdefer func() { done <- err }()\n\t\t\terr = job(ctx, ctrl)\n\t\t}()\n\n\t\tselect {\n\t\tcase <-ctx.Done():\n\n\t\tcase err := <-done:\n\t\t\treturn err\n\n\t\tcase <-timer.C:\n\t\t\tif timeoutTrigger != nil {\n\t\t\t\ttimeoutTrigger(ctx, ctrl, id)\n\t\t\t} else {\n\t\t\t\tctrl.Fail(id, errors.NewErrTimeout(id, time.Now().UTC()))\n\t\t\t}\n\t\t}\n\n\t\treturn <-done\n\t}\n}\n\nfunc Timeout(when WhenTimeoutFunc, id interface{}, job floc.Job) floc.Job ", "output": "{\n\treturn OnTimeout(when, id, job, nil)\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar t_ipv4 string = \" IPv4 \"\nvar t_ipv6 string = \" IPv6 \"\nvar t_unix string = \" unix \"\n\n\n\n\n\nfunc fetchLSOF(pid string, lsofout string) (nonetconn, nofile, sysnofile string) {\n\ts := lsofout\n\n\tif len(strings.TrimSpace(s)) == 0 {\n\t\treturn \"-2\", \"-2\", \"-2\"\n\t}\n\n\tsysopenfile := -1 \n\topenfile := 0\n\topennetconn := 0\n\n\tlines := strings.Split(s, \"\\n\")\n\tvar nline string\n\tfor _, line := range lines {\n\t\tline = strings.TrimSpace(line)\n\t\tif len(line) > 0 {\n\t\t\tsysopenfile += 1\n\t\t}\n\t\tif strings.Contains(line, \" \"+pid+\" \") {\n\t\t\tnline = line\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\n\t\tfields := strings.Split(nline, \" \")\n\t\tvar newFields []string\n\t\tfor _, field := range fields {\n\t\t\tfield = strings.TrimSpace(field)\n\t\t\tif len(field) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnewFields = append(newFields, field)\n\t\t}\n\n\t\tif len(newFields) > 5 && newFields[1] == pid {\n\t\t\topenfile += 1\n\t\t\tif strings.Count(nline, t_ipv4) > 0 || strings.Count(nline, t_ipv6) > 0 || strings.Count(nline, t_unix) > 0 {\n\t\t\t\topennetconn += 1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn strconv.Itoa(opennetconn), strconv.Itoa(openfile), strconv.Itoa(sysopenfile)\n}\n\nfunc execLSOF(result chan string) ", "output": "{\n\ttop := exec.Command(\"lsof\", \"-bw\")\n\tout, err := top.CombinedOutput()\n\tif err != nil {\n\t\tlog.Println(\"execLSOF\", err)\n\t\tresult <- \"\"\n\t\treturn\n\t}\n\ts := string(out)\n\tresult <- s\n}"} {"input": "package chart\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\ntype CT_Thickness struct {\n\tValAttr ST_Thickness\n}\n\nfunc NewCT_Thickness() *CT_Thickness {\n\tret := &CT_Thickness{}\n\treturn ret\n}\n\nfunc (m *CT_Thickness) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"val\"},\n\t\tValue: fmt.Sprintf(\"%v\", m.ValAttr)})\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}\n\nfunc (m *CT_Thickness) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"val\" {\n\t\t\tparsed, err := ParseUnionST_Thickness(attr.Value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.ValAttr = parsed\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_Thickness: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (m *CT_Thickness) Validate() error {\n\treturn m.ValidateWithPath(\"CT_Thickness\")\n}\n\n\n\n\nfunc (m *CT_Thickness) ValidateWithPath(path string) error ", "output": "{\n\tif err := m.ValAttr.ValidateWithPath(path + \"/ValAttr\"); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\nfunc setupSignalHandlers() {\n\tsignalChan := make(chan os.Signal, 1)\n\tsignal.Notify(signalChan, os.Interrupt, os.Kill, syscall.SIGTERM)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase signal := <-signalChan:\n\t\t\t\tcui.ln(\"Received\", signal, \"- exiting...\")\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\n\nfunc fatal(desc string) {\n\tcui.ln(desc)\n\tcui.ln(\"Bye...\")\n\tcui.ln(\"\")\n\tos.Exit(1)\n}\n\nfunc fatalWithErr(desc string, err error) ", "output": "{\n\tcui.ln(desc)\n\tcui.ln(\"Reason:\", err)\n\tcui.ln(\"Bye...\")\n\tcui.ln(\"\")\n\tos.Exit(1)\n}"} {"input": "package swagger\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n)\n\n\n\nfunc (prop *ModelProperty) setDefaultValue(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"default\"); tag != \"\" {\n\t\tprop.DefaultValue = Special(tag)\n\t}\n}\n\nfunc (prop *ModelProperty) setEnumValues(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"enum\"); tag != \"\" {\n\t\tprop.Enum = strings.Split(tag, \"|\")\n\t}\n}\n\nfunc (prop *ModelProperty) setMaximum(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"maximum\"); tag != \"\" {\n\t\tprop.Maximum = tag\n\t}\n}\n\nfunc (prop *ModelProperty) setMinimum(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"minimum\"); tag != \"\" {\n\t\tprop.Minimum = tag\n\t}\n}\n\nfunc (prop *ModelProperty) setUniqueItems(field reflect.StructField) {\n\ttag := field.Tag.Get(\"unique\")\n\tswitch tag {\n\tcase \"true\":\n\t\tv := true\n\t\tprop.UniqueItems = &v\n\tcase \"false\":\n\t\tv := false\n\t\tprop.UniqueItems = &v\n\t}\n}\n\nfunc (prop *ModelProperty) setPropertyMetadata(field reflect.StructField) {\n\tprop.setDescription(field)\n\tprop.setEnumValues(field)\n\tprop.setMinimum(field)\n\tprop.setMaximum(field)\n\tprop.setUniqueItems(field)\n\tprop.setDefaultValue(field)\n}\n\nfunc (prop *ModelProperty) setDescription(field reflect.StructField) ", "output": "{\n\tif tag := field.Tag.Get(\"description\"); tag != \"\" {\n\t\tprop.Description = tag\n\t}\n}"} {"input": "package journal\n\nimport (\n\t\"time\"\n\n\t\"nirenjan.org/overlord/database\"\n\t\"nirenjan.org/overlord/util\"\n)\n\n\n\n\n\ntype DBEntry struct {\n\tTitle string\n\tDate time.Time\n\tTags []string\n\tPath string\n}\n\nvar DB = make(map[string]DBEntry)\n\nfunc BuildDb() error {\n\terr := util.FileWalk(\"journal\", \".entry\", func(path string) error {\n\t\tentry, err1 := entryFromFile(path)\n\t\tif err1 != nil {\n\t\t\treturn err1\n\t\t}\n\n\t\tAddDbEntry(entry)\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn SaveDb()\n}\n\n\n\nfunc DeleteDbEntry(entry Entry) {\n\tdelete(DB, entry.ID)\n}\n\nfunc SaveDb() error {\n\treturn database.Save(DB)\n}\n\nfunc LoadDb() error {\n\treturn database.Load(&DB, BuildDb)\n}\n\nfunc AddDbEntry(entry Entry) ", "output": "{\n\tvar dbEntry = DBEntry{\n\t\tTitle: entry.Title,\n\t\tDate: entry.Date,\n\t\tTags: entry.Tags,\n\t\tPath: entry.Path,\n\t}\n\n\tid := entry.ID\n\n\tDB[id] = dbEntry\n}"} {"input": "package utils\n\nimport (\n\t\"errors\"\n\t\"github.com/mmcloughlin/geohash\"\n\t\"github.com/whosonfirst/go-whosonfirst-geojson-v2\"\n\t\"github.com/whosonfirst/go-whosonfirst-hash\"\n)\n\nfunc GeohashFeature(f geojson.Feature) (string, error) {\n\n\tbboxes, err := f.BoundingBoxes()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmbr := bboxes.MBR()\n\tcenter := mbr.Center()\n\n\tlat := center.Y\n\tlon := center.X\n\n\tgh := geohash.Encode(lat, lon)\n\treturn gh, nil\n}\n\nfunc HashFeature(f geojson.Feature) (string, error) {\n\n\treturn \"\", errors.New(\"This is not ready to use yet\")\n\n\n\n\n\n}\n\n\n\n\n\n\n\n\n\nfunc HashGeometry(geom []byte) (string, error) ", "output": "{\n\n\th, err := hash.NewWOFHash()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn h.HashFromJSON(geom)\n}"} {"input": "package config\n\ntype Dependencies interface {\n\tConfigurator\n\tInstalls() []string\n\tmerge(other Dependencies)\n}\n\nfunc NewDependencies(deps ...string) Dependencies {\n\ts := make(map[string]bool, len(deps))\n\tfor _, dep := range deps {\n\t\ts[dep] = exists\n\t}\n\treturn dependencies{\n\t\tset: s,\n\t}\n}\n\nconst exists = true\n\ntype dependencies struct {\n\tset map[string]bool\n}\n\nfunc (d dependencies) Installs() []string {\n\tkeys := make([]string, len(d.set))\n\n\ti := 0\n\tfor k := range d.set {\n\t\tkeys[i] = k\n\t\ti++\n\t}\n\n\treturn keys\n}\n\nfunc (d dependencies) Configure(cfg Configurable) {\n\tcfg.Config().Dependencies.merge(d)\n}\n\n\n\nfunc (d dependencies) merge(other Dependencies) ", "output": "{\n\tfor _, dep := range other.Installs() {\n\t\td.set[dep] = exists\n\t}\n}"} {"input": "package universe\n\nimport \"testing\"\n\n\n\nfunc TestOps(t *testing.T) ", "output": "{\n uu := NewUniverse(\"asgard\", 100, 1.0, 1.0)\n if uu == nil {\n t.Error(\"NewUniverse failed.\")\n }\n\n uu.name = \"Asgard\"\n uu.star = 100\n uu.latitude = 1.0\n uu.longtitude = 1.0\n\n uu.Add(100)\n if uu.star != 200 {\n t.Error(\"Universe.Add() failed.\")\n }\n\n uu.Reduce(100)\n if uu.star != 100 {\n t.Error(\"Universe.Reduce() failed.\")\n }\n\n uu.Offset(1.0, 1.0)\n if uu.latitude != 2.0 || uu.longtitude != 2.0 {\n t.Error(\"Universe.Offset() failed.\")\n }\n}"} {"input": "package rand\n\nimport (\n\t\"encoding/hex\"\n\t\"io\"\n)\n\nconst dash byte = '-'\n\n\n\ntype UUIDIdempotencyToken struct {\n\tuuid *UUID\n}\n\n\n\nfunc NewUUIDIdempotencyToken(r io.Reader) *UUIDIdempotencyToken {\n\treturn &UUIDIdempotencyToken{uuid: NewUUID(r)}\n}\n\n\nfunc (u UUIDIdempotencyToken) GetIdempotencyToken() (string, error) {\n\treturn u.uuid.GetUUID()\n}\n\n\n\ntype UUID struct {\n\trandSrc io.Reader\n}\n\n\n\nfunc NewUUID(r io.Reader) *UUID {\n\treturn &UUID{randSrc: r}\n}\n\n\n\nfunc (r *UUID) GetUUID() (string, error) {\n\tvar b [16]byte\n\tif _, err := io.ReadFull(r.randSrc, b[:]); err != nil {\n\t\treturn \"\", err\n\t}\n\tr.makeUUIDv4(b[:])\n\treturn format(b), nil\n}\n\n\n\nfunc (r *UUID) GetBytes() (u []byte, err error) {\n\tu = make([]byte, 16)\n\tif _, err = io.ReadFull(r.randSrc, u); err != nil {\n\t\treturn u, err\n\t}\n\tr.makeUUIDv4(u)\n\treturn u, nil\n}\n\nfunc (r *UUID) makeUUIDv4(u []byte) {\n\tu[6] = (u[6] & 0x0f) | 0x40 \n\tu[8] = (u[8] & 0x3f) | 0x80 \n}\n\n\n\n\n\n\nfunc format(u [16]byte) string ", "output": "{\n\n\tvar scratch [36]byte\n\n\thex.Encode(scratch[:8], u[0:4])\n\tscratch[8] = dash\n\thex.Encode(scratch[9:13], u[4:6])\n\tscratch[13] = dash\n\thex.Encode(scratch[14:18], u[6:8])\n\tscratch[18] = dash\n\thex.Encode(scratch[19:23], u[8:10])\n\tscratch[23] = dash\n\thex.Encode(scratch[24:], u[10:])\n\n\treturn string(scratch[:])\n}"} {"input": "package logging_test\n\nimport (\n\t\"cloud.google.com/go/logging/apiv2\"\n\t\"golang.org/x/net/context\"\n\tloggingpb \"google.golang.org/genproto/googleapis/logging/v2\"\n)\n\nfunc ExampleNewConfigClient() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\nfunc ExampleConfigClient_ListSinks() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.ListSinksRequest{\n\t}\n\tit := c.ListSinks(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t_ = resp\n\t}\n}\n\n\n\nfunc ExampleConfigClient_CreateSink() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.CreateSinkRequest{\n\t}\n\tresp, err := c.CreateSink(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleConfigClient_UpdateSink() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.UpdateSinkRequest{\n\t}\n\tresp, err := c.UpdateSink(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleConfigClient_DeleteSink() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.DeleteSinkRequest{\n\t}\n\terr = c.DeleteSink(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleConfigClient_GetSink() ", "output": "{\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.GetSinkRequest{\n\t}\n\tresp, err := c.GetSink(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}"} {"input": "package models\n\nimport (\n \n \"math/rand\"\n \"time\"\n)\n\ntype Level struct {\n Id int\n Name string\n}\n\n\n\nfunc LevelRoutine(eventChannel chan Event, collisionChannel chan Entity) ", "output": "{\n pop := time.NewTicker(time.Millisecond * 1000)\n\n rand.Seed(time.Now().Unix())\n\n for {\n select {\n case <-pop.C:\n \n peon := NewPeon(350, rand.Int()%150)\n go peon.Live(eventChannel, collisionChannel)\n break\n }\n }\n}"} {"input": "package config\n\nimport (\n\t\"github.com/juju/errors\"\n)\n\n\ntype baseConfigurer struct {\n\tseries string\n\tdefaultPackages []string\n\tcloudArchivePackages map[string]struct{}\n}\n\n\n\n\n\nfunc (c *baseConfigurer) GetPackageNameForSeries(pack, series string) (string, error) {\n\tif c.series == series {\n\t\treturn pack, nil\n\t}\n\n\tswitch series {\n\tcase \"centos7\":\n\t\tres, ok := centOSToUbuntuPackageNameMap[pack]\n\t\tif !ok {\n\t\t\treturn \"\", errors.Errorf(\"no equivalent package found for series %s: %s\", series, pack)\n\t\t}\n\t\treturn res, nil\n\tdefault:\n\t\tres, ok := ubuntuToCentOSPackageNameMap[pack]\n\t\tif !ok {\n\t\t\treturn \"\", errors.Errorf(\"no equivalent package found for series %s: %s\", series, pack)\n\t\t}\n\t\treturn res, nil\n\t}\n}\n\n\nfunc (c *baseConfigurer) IsCloudArchivePackage(pack string) bool {\n\t_, ok := c.cloudArchivePackages[pack]\n\treturn ok\n}\n\nfunc (c *baseConfigurer) DefaultPackages() []string ", "output": "{\n\treturn c.defaultPackages\n}"} {"input": "package secret\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nconst targetTestVersion = 1\n\nvar tests = []struct {\n\tcode uint\n\th []string\n}{\n\t{1, []string{\"wink\"}},\n\t{2, []string{\"double blink\"}},\n\t{4, []string{\"close your eyes\"}},\n\t{8, []string{\"jump\"}},\n\t{3, []string{\"wink\", \"double blink\"}},\n\t{19, []string{\"double blink\", \"wink\"}},\n\t{31, []string{\"jump\", \"close your eyes\", \"double blink\", \"wink\"}},\n\t{0, nil},\n\t{32, nil},\n\t{33, []string{\"wink\"}},\n}\n\n\n\nfunc BenchmarkHandshake(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tHandshake(31)\n\t}\n}\n\nfunc TestHandshake(t *testing.T) ", "output": "{\n\tif testVersion != targetTestVersion {\n\t\tt.Fatalf(\"Found testVersion = %v, want %v\", testVersion, targetTestVersion)\n\t}\n\tfor _, test := range tests {\n\t\th := Handshake(test.code)\n\t\tif len(h) == 0 && len(test.h) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif !reflect.DeepEqual(h, test.h) {\n\t\t\tt.Fatalf(\"Handshake(%d) = %q, want %q.\", test.code, h, test.h)\n\t\t}\n\t}\n}"} {"input": "package memstats\n\nimport (\n\t\"github.com/mono83/slf\"\n\t\"sync\"\n)\n\n\n\nfunc New() *MemStats {\n\treturn &MemStats{\n\t\tvalues: map[string]int64{},\n\t}\n}\n\n\n\ntype MemStats struct {\n\tm sync.Mutex\n\n\tvalues map[string]int64\n}\n\n\nfunc (m *MemStats) Receive(e slf.Event) {\n\tif e.Type == slf.TypeInc {\n\t\tm.m.Lock()\n\t\tprev, _ := m.values[e.Content]\n\t\tm.values[e.Content] = prev + e.I64\n\t\tm.m.Unlock()\n\t} else if e.Type == slf.TypeGauge {\n\t\tm.m.Lock()\n\t\tm.values[e.Content] = e.I64\n\t\tm.m.Unlock()\n\t}\n}\n\n\nfunc (m *MemStats) Get(key string) (value int64, found bool) {\n\tm.m.Lock()\n\tdefer m.m.Unlock()\n\n\tvalue, found = m.values[key]\n\treturn\n}\n\n\n\n\nfunc (m *MemStats) Values() map[string]int64 ", "output": "{\n\tm.m.Lock()\n\tdefer m.m.Unlock()\n\n\tclone := make(map[string]int64, len(m.values))\n\tfor k, v := range m.values {\n\t\tclone[k] = v\n\t}\n\n\treturn clone\n}"} {"input": "package graphdriver \n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\n\t\"github.com/docker/docker/pkg/plugingetter\"\n\t\"github.com/docker/docker/plugin/v2\"\n)\n\nfunc lookupPlugin(name string, pg plugingetter.PluginGetter, config Options) (Driver, error) {\n\tif !config.ExperimentalEnabled {\n\t\treturn nil, fmt.Errorf(\"graphdriver plugins are only supported with experimental mode\")\n\t}\n\tpl, err := pg.Get(name, \"GraphDriver\", plugingetter.Acquire)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error looking up graphdriver plugin %s: %v\", name, err)\n\t}\n\treturn newPluginDriver(name, pl, config)\n}\n\n\n\nfunc newPluginDriver(name string, pl plugingetter.CompatPlugin, config Options) (Driver, error) ", "output": "{\n\thome := config.Root\n\tif !pl.IsV1() {\n\t\tif p, ok := pl.(*v2.Plugin); ok {\n\t\t\tif p.PropagatedMount != \"\" {\n\t\t\t\thome = p.PluginObj.Config.PropagatedMount\n\t\t\t}\n\t\t}\n\t}\n\tproxy := &graphDriverProxy{name, pl, Capabilities{}}\n\treturn proxy, proxy.Init(filepath.Join(home, name), config.DriverOptions, config.UIDMaps, config.GIDMaps)\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc foo() ", "output": "{\n\ttestString1 := \"test\"\n\ttestString2 := \"test\"\n\n\ttestInt1 := 123\n\ttestInt2 := 123\n\n\tfmt.Println(testString1, testString2, testInt1, testInt2)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\nconst (\n\tBLACK\t=0\n\tRED\t\t=1\n\tGREEN\t=2\n\tYELLOW\t=3\n\tBLUE\t=4\n\tMAGENTA\t=5\n\tCYAN\t=6\n\tWHITE\t=7\n\tDEFAULT\t=9\n)\n\n\n\n\n\nfunc main() {\n\tfmt.Println( Colorize(\"Ola\", YELLOW, GREEN) )\n\tfmt.Println( Colorize(\"Ola\", YELLOW, GREEN) )\n\tfmt.Println( Colorize(\"Ola\", YELLOW, GREEN) )\n}\n\nfunc Colorize(text string, foreground, background int) (out string) ", "output": "{\n\tforegroundColor := \"\\033[3\"+strconv.Itoa(foreground)+\"m\"\n\tbackgroundColor := \"\\033[4\"+strconv.Itoa(background)+\"m\"\n\tdef := \"\\033[39m\\033[49m\"\n\tout = foregroundColor+backgroundColor+text+def\n\treturn\n}"} {"input": "package dml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/dml\"\n)\n\n\n\nfunc TestCT_TintEffectMarshalUnmarshal(t *testing.T) {\n\tv := dml.NewCT_TintEffect()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := dml.NewCT_TintEffect()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestCT_TintEffectConstructor(t *testing.T) ", "output": "{\n\tv := dml.NewCT_TintEffect()\n\tif v == nil {\n\t\tt.Errorf(\"dml.NewCT_TintEffect must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed dml.CT_TintEffect should validate: %s\", err)\n\t}\n}"} {"input": "package collectors\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n)\n\n\n\ntype ProcessParams struct{}\n\nfunc WatchProcesses() {}\n\nfunc AddProcessConfig(params ProcessParams) error ", "output": "{\n\treturn fmt.Errorf(\"process monitoring not supported on %s-%s\", runtime.GOOS, runtime.GOARCH)\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype UpdateInternetGatewayRequest struct {\n\n\tIgId *string `mandatory:\"true\" contributesTo:\"path\" name:\"igId\"`\n\n\tUpdateInternetGatewayDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateInternetGatewayRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request UpdateInternetGatewayRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\n\n\n\ntype UpdateInternetGatewayResponse struct {\n\n\tRawResponse *http.Response\n\n\tInternetGateway `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateInternetGatewayResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateInternetGatewayResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateInternetGatewayRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package container\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\ntype ContainerGCPolicy struct {\n\tMinAge time.Duration\n\n\tMaxPerPodContainer int\n\n\tMaxContainers int\n}\n\n\n\n\ntype ContainerGC interface {\n\tGarbageCollect(allSourcesReady bool) error\n}\n\n\ntype realContainerGC struct {\n\truntime Runtime\n\n\tpolicy ContainerGCPolicy\n}\n\n\n\n\nfunc (cgc *realContainerGC) GarbageCollect(allSourcesReady bool) error {\n\treturn cgc.runtime.GarbageCollect(cgc.policy, allSourcesReady)\n}\n\nfunc NewContainerGC(runtime Runtime, policy ContainerGCPolicy) (ContainerGC, error) ", "output": "{\n\tif policy.MinAge < 0 {\n\t\treturn nil, fmt.Errorf(\"invalid minimum garbage collection age: %v\", policy.MinAge)\n\t}\n\n\treturn &realContainerGC{\n\t\truntime: runtime,\n\t\tpolicy: policy,\n\t}, nil\n}"} {"input": "package fixtures\n\nimport \"database/sql/driver\"\n\ntype AliasArray [3]string\ntype AliasSlice []string\ntype AliasString string\ntype AliasInt int\ntype AliasArrAliasSlice []AliasSlice\ntype AliasArrAliasString []AliasString\ntype AliasDummyParam QueryDummy\n\ntype QueryDummy struct {\n\tname string\n}\n\ntype InterfaceImplementation struct {\n\tScannerValuer\n\tStr string\n}\n\ntype ScannerValuer struct{}\n\n\n\nfunc (i ScannerValuer) Scan(src interface{}) error {\n\treturn nil\n}\n\nfunc (i ScannerValuer) Value() (driver.Value, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package daemon\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/docker/docker/api/types/swarm\"\n\t\"gotest.tools/assert\"\n)\n\n\ntype ConfigConstructor func(*swarm.Config)\n\n\nfunc (d *Daemon) CreateConfig(t testing.TB, configSpec swarm.ConfigSpec) string {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tscr, err := cli.ConfigCreate(context.Background(), configSpec)\n\tassert.NilError(t, err)\n\treturn scr.ID\n}\n\n\nfunc (d *Daemon) ListConfigs(t testing.TB) []swarm.Config {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tconfigs, err := cli.ConfigList(context.Background(), types.ConfigListOptions{})\n\tassert.NilError(t, err)\n\treturn configs\n}\n\n\nfunc (d *Daemon) GetConfig(t testing.TB, id string) *swarm.Config {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tconfig, _, err := cli.ConfigInspectWithRaw(context.Background(), id)\n\tassert.NilError(t, err)\n\treturn &config\n}\n\n\n\n\n\n\nfunc (d *Daemon) UpdateConfig(t testing.TB, id string, f ...ConfigConstructor) {\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\tconfig := d.GetConfig(t, id)\n\tfor _, fn := range f {\n\t\tfn(config)\n\t}\n\n\terr := cli.ConfigUpdate(context.Background(), config.ID, config.Version, config.Spec)\n\tassert.NilError(t, err)\n}\n\nfunc (d *Daemon) DeleteConfig(t testing.TB, id string) ", "output": "{\n\tt.Helper()\n\tcli := d.NewClientT(t)\n\tdefer cli.Close()\n\n\terr := cli.ConfigRemove(context.Background(), id)\n\tassert.NilError(t, err)\n}"} {"input": "package header\n\nimport \"sip/core\"\n\n\ntype RecordRouteList struct {\n\tSIPHeaderList\n}\n\n\n\n\nfunc NewRecordRouteList() *RecordRouteList ", "output": "{\n\tthis := &RecordRouteList{}\n\tthis.SIPHeaderList.super(core.SIPHeaderNames_RECORD_ROUTE)\n\treturn this\n}"} {"input": "package route\n\nimport (\n\t\"net/url\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc mustParse(rawurl string) *url.URL {\n\tu, err := url.Parse(rawurl)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn u\n}\n\n\n\nfunc TestAddTarget(t *testing.T) {\n\tu := mustParse(\"http://foo.com/\")\n\n\tr := newRoute(\"www.bar.com\", \"/foo\")\n\tr.addTarget(\"service\", u, 0, nil)\n\n\tif got, want := len(r.Targets), 1; got != want {\n\t\tt.Errorf(\"target length: got %d want %d\", got, want)\n\t}\n\tif got, want := r.Targets[0].URL, u; got != want {\n\t\tt.Errorf(\"target url: got %s want %s\", got, want)\n\t}\n\tconfig := []string{\"route add service www.bar.com/foo http://foo.com/\"}\n\tif got, want := r.config(false), config; !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"config: got %q want %q\", got, want)\n\t}\n}\n\nfunc TestDelService(t *testing.T) {\n\tu1, u2 := mustParse(\"http://foo.com/\"), mustParse(\"http://bar.com/\")\n\n\tr := newRoute(\"www.bar.com\", \"/foo\")\n\tr.addTarget(\"serviceA\", u1, 0, nil)\n\tr.addTarget(\"serviceB\", u2, 0, nil)\n\tr.delService(\"serviceA\")\n\n\tconfig := []string{\"route add serviceB www.bar.com/foo http://bar.com/\"}\n\tif got, want := r.config(false), config; !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"config: got %q want %q\", got, want)\n\t}\n}\n\nfunc TestNewRoute(t *testing.T) ", "output": "{\n\tr := newRoute(\"www.bar.com\", \"/foo\")\n\tif got, want := r.Path, \"/foo\"; got != want {\n\t\tt.Errorf(\"got %q want %q\", got, want)\n\t}\n}"} {"input": "package bone\n\nimport (\n\t\"net/http\"\n\t\"sync\"\n)\n\nvar globalVars = struct {\n\tsync.RWMutex\n\tv map[*http.Request]map[string]string\n}{v: make(map[*http.Request]map[string]string)}\n\n\nfunc GetAllValues(req *http.Request) map[string]string {\n\tglobalVars.RLock()\n\tvalues := globalVars.v[req]\n\tglobalVars.RUnlock()\n\treturn values\n}\n\n\n\n\n\nfunc (r *Route) serveMatchedRequest(rw http.ResponseWriter, req *http.Request, vars map[string]string) ", "output": "{\n\tglobalVars.Lock()\n\tglobalVars.v[req] = vars\n\tglobalVars.Unlock()\n\n\tdefer func() {\n\t\tglobalVars.Lock()\n\t\tdelete(globalVars.v, req)\n\t\tglobalVars.Unlock()\n\t}()\n\tr.Handler.ServeHTTP(rw, req)\n}"} {"input": "package command\n\nimport (\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/hashicorp/go-plugin\"\n\n\t\"github.com/hashicorp/nomad/client/driver\"\n)\n\ntype SyslogPluginCommand struct {\n\tMeta\n}\n\nfunc (e *SyslogPluginCommand) Help() string {\n\thelpText := `\n\tThis is a command used by Nomad internally to launch a syslog collector\"\n\t`\n\treturn strings.TrimSpace(helpText)\n}\n\nfunc (s *SyslogPluginCommand) Synopsis() string {\n\treturn \"internal - lanch a syslog collector plugin\"\n}\n\n\n\nfunc (s *SyslogPluginCommand) Run(args []string) int ", "output": "{\n\tif len(args) == 0 {\n\t\ts.Ui.Error(\"log output file isn't provided\")\n\t}\n\tlogFileName := args[0]\n\tstdo, err := os.OpenFile(logFileName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)\n\tif err != nil {\n\t\ts.Ui.Error(err.Error())\n\t\treturn 1\n\t}\n\tplugin.Serve(&plugin.ServeConfig{\n\t\tHandshakeConfig: driver.HandshakeConfig,\n\t\tPlugins: driver.GetPluginMap(stdo),\n\t})\n\n\treturn 0\n}"} {"input": "package runtime\n\nimport (\n\t\"unsafe\"\n)\n\nfunc RaceRead(addr unsafe.Pointer)\nfunc RaceWrite(addr unsafe.Pointer)\nfunc RaceReadRange(addr unsafe.Pointer, len int)\nfunc RaceWriteRange(addr unsafe.Pointer, len int)\n\nfunc RaceSemacquire(s *uint32)\nfunc RaceSemrelease(s *uint32)\n\n\nconst raceenabled = true\n\n\n\nfunc raceWriteObjectPC(t *_type, addr unsafe.Pointer, callerpc, pc uintptr) {\n\tkind := t.kind & kindMask\n\tif kind == kindArray || kind == kindStruct {\n\t\tracewriterangepc(addr, t.size, callerpc, pc)\n\t} else {\n\t\tracewritepc(addr, callerpc, pc)\n\t}\n}\n\n\nfunc racereadpc(addr unsafe.Pointer, callpc, pc uintptr)\n\n\nfunc racewritepc(addr unsafe.Pointer, callpc, pc uintptr)\n\ntype symbolizeContext struct {\n\tpc uintptr\n\tfn *byte\n\tfile *byte\n\tline uintptr\n\toff uintptr\n\tres uintptr\n}\n\nvar qq = [...]byte{'?', '?', 0}\nvar dash = [...]byte{'-', 0}\n\n\nfunc racesymbolize(ctx *symbolizeContext) {\n\tf := findfunc(ctx.pc)\n\tif f == nil {\n\t\tctx.fn = &qq[0]\n\t\tctx.file = &dash[0]\n\t\tctx.line = 0\n\t\tctx.off = ctx.pc\n\t\tctx.res = 1\n\t\treturn\n\t}\n\n\tctx.fn = funcname(f)\n\tfile, line := funcline(f, ctx.pc)\n\tctx.line = uintptr(line)\n\tctx.file = &bytes(file)[0] \n\tctx.off = ctx.pc - f.entry\n\tctx.res = 1\n\treturn\n}\n\nfunc raceReadObjectPC(t *_type, addr unsafe.Pointer, callerpc, pc uintptr) ", "output": "{\n\tkind := t.kind & kindMask\n\tif kind == kindArray || kind == kindStruct {\n\t\tracereadrangepc(addr, t.size, callerpc, pc)\n\t} else {\n\t\tracereadpc(addr, callerpc, pc)\n\t}\n}"} {"input": "package containerengine\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListWorkRequestLogsRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tWorkRequestId *string `mandatory:\"true\" contributesTo:\"path\" name:\"workRequestId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListWorkRequestLogsRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListWorkRequestLogsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request ListWorkRequestLogsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype ListWorkRequestLogsResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []WorkRequestLogEntry `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ListWorkRequestLogsResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListWorkRequestLogsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListWorkRequestLogsRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package log_test\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n)\n\n\n\nfunc ExampleLogger() ", "output": "{\n\tvar buf bytes.Buffer\n\tlogger := log.New(&buf, \"logger: \", log.Lshortfile)\n\tlogger.Print(\"Hello, log file!\")\n\n\tfmt.Print(&buf)\n}"} {"input": "package checks\n\nimport (\n\t\"testing\"\n\n\t\"github.com/abulimov/haproxy-lint/lib\"\n)\n\n\n\nfunc TestCheckUnknownBackends(t *testing.T) {\n\tlines, err := lib.GetConfig(\"../testdata/haproxy.cfg\", \"\")\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to read test data: %v\", err)\n\t}\n\tsections := lib.GetSections(lines)\n\tproblems := CheckUnknownBackends(sections)\n\n\tif len(problems) != 1 {\n\t\tt.Errorf(\"Expected %d problems, got %d\", 1, len(problems))\n\t}\n}\n\nfunc TestCheckUnusedBackends(t *testing.T) ", "output": "{\n\tlines, err := lib.GetConfig(\"../testdata/haproxy.cfg\", \"\")\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to read test data: %v\", err)\n\t}\n\tsections := lib.GetSections(lines)\n\tproblems := CheckUnusedBackends(sections)\n\n\tif len(problems) != 1 {\n\t\tt.Errorf(\"Expected %d problems, got %d\", 1, len(problems))\n\t}\n}"} {"input": "package remote\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc Test_CalculateSignature(t *testing.T) ", "output": "{\n\tassert.Equal(t, \"tAb/54Rwwcq+pbH8Loi7FWX4QSQ=\",\n\t\tcalculateSignature([]byte(\"Hello RocketMQ Client ACL Feature\"), []byte(\"adiaushdiaushd\")))\n}"} {"input": "package internal\n\nimport \"go.uber.org/zap\"\nimport gokitLog \"github.com/go-kit/kit/log\"\n\n\nfunc NewZapToGokitLogAdapter(logger *zap.Logger) gokitLog.Logger {\n\tlogger = logger.WithOptions(zap.AddCallerSkip(2))\n\treturn &zapToGokitLogAdapter{l: logger.Sugar()}\n}\n\ntype zapToGokitLogAdapter struct {\n\tl *zap.SugaredLogger\n}\n\n\n\nvar _ gokitLog.Logger = (*zapToGokitLogAdapter)(nil)\n\nfunc (w *zapToGokitLogAdapter) Log(keyvals ...interface{}) error ", "output": "{\n\tif len(keyvals)%2 == 0 {\n\t\tw.l.Infow(\"\", keyvals...)\n\t} else {\n\t\tw.l.Info(keyvals...)\n\t}\n\treturn nil\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n\twatchlist \"github.com/macarrie/flemzerd/watchlists\"\n\t\"github.com/macarrie/flemzerd/watchlists/impl/trakt\"\n)\n\nfunc performTraktAuth(c *gin.Context) {\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\tt := w.(*trakt.TraktWatchlist)\n\tif err := t.IsAuthenticated(); err == nil {\n\t\tc.AbortWithStatus(http.StatusNoContent)\n\t\treturn\n\t}\n\n\tgo t.Auth()\n\tc.JSON(http.StatusOK, gin.H{})\n\treturn\n}\n\nfunc getTraktAuthErrors(c *gin.Context) {\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tt := w.(*trakt.TraktWatchlist)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, t.GetAuthErrors())\n}\n\n\n\nfunc getTraktDeviceCode(c *gin.Context) {\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\tt := w.(*trakt.TraktWatchlist)\n\tc.JSON(http.StatusOK, t.DeviceCode)\n\treturn\n}\n\nfunc getTraktToken(c *gin.Context) ", "output": "{\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tt := w.(*trakt.TraktWatchlist)\n\tc.JSON(http.StatusOK, t.Token)\n}"} {"input": "package stree\n\n\n\ntype serial struct {\n\tstree\n}\n\n\nfunc NewSerial() Tree {\n\tt := new(serial)\n\tt.Clear()\n\treturn t\n}\n\nfunc (t *serial) BuildTree() {\n\tpanic(\"BuildTree() not supported for serial data structure\")\n}\n\nfunc (t *serial) Print() {\n\tpanic(\"Print() not supported for serial data structure\")\n}\n\nfunc (t *serial) Tree2Array() []SegmentOverlap {\n\tpanic(\"Tree2Array() not supported for serial data structure\")\n}\n\n\nfunc (t *serial) Query(from, to int) []Interval {\n\tresult := make([]Interval, 0, 10)\n\tfor _, intrvl := range t.base {\n\t\tif !intrvl.Segment.Disjoint(from, to) {\n\t\t\tresult = append(result, intrvl)\n\t\t}\n\t}\n\treturn result\n}\n\n\n\n\nfunc (t *serial) QueryArray(from, to []int) []Interval ", "output": "{\n\tresult := make([]Interval, 0, 10)\n\tfor i, fromvalue := range from {\n\t\tresult = append(result, t.Query(fromvalue, to[i])...)\n\t}\n\treturn result\n}"} {"input": "package service\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc Test_QueryUserInfo(t *testing.T) ", "output": "{\n\tConvey(\"query user or create user\", t, func() {\n\t\t_, err := s.QueryUser(\"zhanglu\")\n\t\tSo(err, ShouldBeNil)\n\t})\n}"} {"input": "package models\n\nimport \"time\"\n\n\ntype KeyType struct {\n\tID int\n\tKey string\n\tCreated time.Time\n\tExpires bool\n}\n\n\ntype Keys []KeyType\n\n\n\nfunc (f Keys) Less(i, j int) bool {\n\treturn f[i].ID < f[j].ID\n}\n\nfunc (f Keys) Swap(i, j int) {\n\tf[i], f[j] = f[j], f[i]\n}\n\nfunc (f Keys) Len() int ", "output": "{\n\treturn len(f)\n}"} {"input": "package iso20022\n\n\ntype AcquirerProtocolParameters5 struct {\n\n\tFinancialCapture *FinancialCapture1Code `xml:\"FinCaptr\"`\n\n\tBatchTransfer *ExchangeConfiguration4 `xml:\"BtchTrf,omitempty\"`\n\n\tCompletionExchange *ExchangeConfiguration5 `xml:\"CmpltnXchg,omitempty\"`\n\n\tCancellationExchange *CancellationProcess1Code `xml:\"CxlXchg,omitempty\"`\n}\n\nfunc (a *AcquirerProtocolParameters5) SetFinancialCapture(value string) {\n\ta.FinancialCapture = (*FinancialCapture1Code)(&value)\n}\n\nfunc (a *AcquirerProtocolParameters5) AddBatchTransfer() *ExchangeConfiguration4 {\n\ta.BatchTransfer = new(ExchangeConfiguration4)\n\treturn a.BatchTransfer\n}\n\nfunc (a *AcquirerProtocolParameters5) AddCompletionExchange() *ExchangeConfiguration5 {\n\ta.CompletionExchange = new(ExchangeConfiguration5)\n\treturn a.CompletionExchange\n}\n\n\n\nfunc (a *AcquirerProtocolParameters5) SetCancellationExchange(value string) ", "output": "{\n\ta.CancellationExchange = (*CancellationProcess1Code)(&value)\n}"} {"input": "package channel\n\nimport (\n\t\"testing\"\n\n\t\"knative.dev/pkg/configmap\"\n\n\t. \"knative.dev/pkg/reconciler/testing\"\n\n\t_ \"knative.dev/eventing/pkg/client/injection/ducks/duck/v1/channelable/fake\"\n\t_ \"knative.dev/eventing/pkg/client/injection/informers/messaging/v1/channel/fake\"\n\t_ \"knative.dev/pkg/client/injection/kube/client/fake\"\n\t_ \"knative.dev/pkg/injection/clients/dynamicclient/fake\"\n)\n\n\n\nfunc TestNew(t *testing.T) ", "output": "{\n\tctx, _ := SetupFakeContext(t)\n\n\tc := NewController(ctx, configmap.NewStaticWatcher())\n\n\tif c == nil {\n\t\tt.Fatal(\"Expected NewController to return a non-nil value\")\n\t}\n}"} {"input": "package swt\n\nimport \"github.com/timob/javabind\"\nimport \"unsafe\"\n\n\n\nimport \"C\"\n\n\n\nvar EventsSegmentListenerNativeMap = make(map[int]EventsSegmentListenerInterface)\n\ntype EventsSegmentListenerNative struct {\n\t*javabind.Callable\n\tEventsSegmentListenerInterface\n}\n\nfunc NewEventsSegmentListenerNative(implementation EventsSegmentListenerInterface) *EventsSegmentListenerNative {\n\n\tobj, err := javabind.GetEnv().NewObject(\"org/eclipse/swt/events/SegmentListenerNative\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tx := &EventsSegmentListenerNative{}\n\tx.Callable = &javabind.Callable{obj}\n\n hash, err := x.Callable.CallMethod(javabind.GetEnv(), \"hashCode\", javabind.Int)\n if err != nil {\n panic(err)\n }\n EventsSegmentListenerNativeMap[hash.(int)] = implementation\n\treturn x\n}\n\n\n func init() {\n javabind.OnJVMStart(func() {\n javabind.GetEnv().RegisterNative(\"org/eclipse/swt/events/SegmentListenerNative\", \"getSegments\", javabind.Void, []interface{}{\"org/eclipse/swt/events/SegmentEvent\"}, C.go_callback_EventsSegmentListenerNative_GetSegments)\n\n })\n }\n\nfunc go_callback_EventsSegmentListenerNative_GetSegments(env unsafe.Pointer, obj uintptr, arg_0 uintptr) ", "output": "{\n rObj := &javabind.Callable{javabind.WrapJObject(obj, \"org/eclipse/swt/events/SegmentListenerNative\", false)}\n hash, err := rObj.CallMethod(javabind.GetEnv(), \"hashCode\", javabind.Int)\n if err != nil {\n panic(err)\n }\n\n i := EventsSegmentListenerNativeMap[hash.(int)]\n \tretcon_a := javabind.NewJavaToGoCallable()\n\tdst_a := &javabind.Callable{}\n\tretcon_a.Dest(dst_a)\n\tif err := retcon_a.Convert(javabind.WrapJObject(arg_0, \"org/eclipse/swt/events/SegmentEvent\", false)); err != nil {\n\t\tpanic(err)\n\t}\n\targ_a := &EventsSegmentEvent{}\n\targ_a.Callable = dst_a\ni.GetSegments(arg_a)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/WindomZ/go-jwt/jwt\"\n\t\"os\"\n)\n\nconst (\n\tKeyNameHmac string = \"hmac_demo\" \n\tKeyNameRSA = \"rsa_demo\" \n)\n\nfunc main() {\n\tif dir, err := os.Getwd(); err != nil {\n\t\tpanic(err)\n\t} else if err := jwt.NewConfig(dir).Effect(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := demoHmac(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := demoRSA(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(\"Success!\")\n}\n\nfunc sign(keyName string, m interface{}) (token string, err error) {\n\treturn jwt.Sign(keyName, m, 72)\n}\n\nfunc verify(token string) (err error) {\n\t_, err = jwt.Parse(token)\n\treturn\n}\n\nvar test_case = map[string]interface{}{\n\t\"number\": 19,\n\t\"english\": \"This is the English test.\",\n\t\"中文\": \"这是个中文测试。\",\n}\n\n\n\nfunc demoRSA() error {\n\tif token, err := sign(KeyNameRSA, test_case); err != nil {\n\t\treturn err\n\t} else if err := verify(token); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc demoHmac() error ", "output": "{\n\tif token, err := sign(KeyNameHmac, test_case); err != nil {\n\t\treturn err\n\t} else if err := verify(token); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package tempconv\n\n\nfunc CToF(c Celsius) Fahrenheit {\n return Fahrenheit(c * 9 / 5 + 32)\n}\n\n\n\n\nfunc FToC(f Fahrenheit) Celsius ", "output": "{\n return Celsius((f - 32) * 5 / 9)\n}"} {"input": "package operations\n\n\n\nimport (\n\t\"github.com/denkhaus/bitshares/types\"\n\t\"github.com/denkhaus/bitshares/util\"\n\t\"github.com/juju/errors\"\n)\n\nfunc init() {\n\ttypes.OperationMap[types.OperationTypeTransferFromBlind] = func() types.Operation {\n\t\top := &TransferFromBlindOperation{}\n\t\treturn op\n\t}\n}\n\ntype TransferFromBlindOperation struct {\n\ttypes.OperationFee\n\tAmount types.AssetAmount `json:\"amount\"`\n\tTo types.AccountID `json:\"to\"`\n\tBlindFactor types.FixedBuffer `json:\"blinding_factor\"`\n\tBlindInputs types.BlindInputs `json:\"inputs\"`\n}\n\nfunc (p TransferFromBlindOperation) Type() types.OperationType {\n\treturn types.OperationTypeTransferFromBlind\n}\n\n\n\nfunc (p TransferFromBlindOperation) Marshal(enc *util.TypeEncoder) error ", "output": "{\n\tif err := enc.Encode(int8(p.Type())); err != nil {\n\t\treturn errors.Annotate(err, \"encode OperationType\")\n\t}\n\tif err := enc.Encode(p.Fee); err != nil {\n\t\treturn errors.Annotate(err, \"encode Fee\")\n\t}\n\tif err := enc.Encode(p.Amount); err != nil {\n\t\treturn errors.Annotate(err, \"encode Amount\")\n\t}\n\tif err := enc.Encode(p.To); err != nil {\n\t\treturn errors.Annotate(err, \"encode To\")\n\t}\n\tif err := enc.Encode(p.BlindFactor); err != nil {\n\t\treturn errors.Annotate(err, \"encode BlindFactor\")\n\t}\n\tif err := enc.Encode(p.BlindInputs); err != nil {\n\t\treturn errors.Annotate(err, \"encode BlindInputs\")\n\t}\n\n\treturn nil\n}"} {"input": "package test_utils\n\nimport (\n\t\"fmt\"\n\t\"simplejsondb/dbio\"\n)\n\n\n\ntype InMemoryDataFile struct {\n\tBlocks [][]byte\n\tCloseFunc func() error\n\tReadBlockFunc func(uint16, []byte) error\n\tWriteBlockFunc func(uint16, []byte) error\n}\n\nfunc NewFakeDataFile(blocksCount int) *InMemoryDataFile {\n\tblocks := [][]byte{}\n\tfor i := 0; i < blocksCount; i++ {\n\t\tblocks = append(blocks, make([]byte, dbio.DATABLOCK_SIZE))\n\t}\n\treturn NewFakeDataFileWithBlocks(blocks)\n}\n\nfunc NewFakeDataFileWithBlocks(blocks [][]byte) *InMemoryDataFile {\n\treturn &InMemoryDataFile{\n\t\tBlocks: blocks,\n\t\tCloseFunc: func() error {\n\t\t\treturn nil \n\t\t},\n\t\tWriteBlockFunc: func(id uint16, data []byte) error {\n\t\t\tblock := blocks[id]\n\t\t\tfor i := range block {\n\t\t\t\tblock[i] = data[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tReadBlockFunc: func(id uint16, data []byte) error {\n\t\t\tif id < 0 || id >= uint16(len(blocks)) {\n\t\t\t\treturn fmt.Errorf(\"Invalid datablock requested: %d\", id)\n\t\t\t}\n\t\t\tblock := blocks[id]\n\t\t\tfor i := 0; i < len(block); i++ {\n\t\t\t\tdata[i] = block[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\nfunc (df *InMemoryDataFile) Close() error {\n\treturn df.CloseFunc()\n}\n\nfunc (df *InMemoryDataFile) WriteBlock(id uint16, data []byte) error {\n\treturn df.WriteBlockFunc(id, data)\n}\n\nfunc (df *InMemoryDataFile) ReadBlock(id uint16, data []byte) error ", "output": "{\n\treturn df.ReadBlockFunc(id, data)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/service/ssm\"\n\n\t\"gopkg.in/alecthomas/kingpin.v2\"\n)\n\ntype readCommand struct {\n\tName string\n\tDecrypt bool\n}\n\n\n\nfunc (rc *readCommand) runRead(ctx *kingpin.ParseContext) error {\n\tconfig := aws.NewConfig().WithRegion(*region)\n\tsess, err := newSession(config, mfaSerial, roleArn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tssmClient := ssm.New(sess, config)\n\n\tgpInput := &ssm.GetParameterInput{\n\t\tName: &rc.Name,\n\t\tWithDecryption: &rc.Decrypt,\n\t}\n\tgpOutput, err := ssmClient.GetParameter(gpInput)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(*gpOutput.Parameter.Value)\n\n\treturn nil\n}\n\nfunc configureReadCommand(app *kingpin.Application) ", "output": "{\n\trc := &readCommand{}\n\tread := app.Command(\"read\", \"Read secret from parameter store\").Action(rc.runRead)\n\tread.Arg(\"name\", \"Secret name\").StringVar(&rc.Name)\n\tread.Flag(\"decrypt\", \"Return decrypted value\").BoolVar(&rc.Decrypt)\n}"} {"input": "package remotecontext \n\nimport (\n\t\"archive/tar\"\n\t\"crypto/sha256\"\n\t\"hash\"\n\t\"os\"\n\n\t\"github.com/tiborvass/docker/pkg/archive\"\n\t\"github.com/tiborvass/docker/pkg/tarsum\"\n)\n\n\n\n\ntype tarsumHash struct {\n\thash.Hash\n\thdr *tar.Header\n}\n\n\nfunc (tsh *tarsumHash) Reset() {\n\ttsh.Hash.Reset()\n\ttarsum.WriteV1Header(tsh.hdr, tsh.Hash)\n}\n\nfunc NewFileHash(path, name string, fi os.FileInfo) (hash.Hash, error) ", "output": "{\n\tvar link string\n\tif fi.Mode()&os.ModeSymlink != 0 {\n\t\tvar err error\n\t\tlink, err = os.Readlink(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\thdr, err := archive.FileInfoHeader(name, fi, link)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := archive.ReadSecurityXattrToTarHeader(path, hdr); err != nil {\n\t\treturn nil, err\n\t}\n\ttsh := &tarsumHash{hdr: hdr, Hash: sha256.New()}\n\ttsh.Reset() \n\treturn tsh, nil\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\n\t\"errors\"\n\n\t\"github.com/kubernetes-sigs/service-catalog/pkg/svcat/service-catalog\"\n\t\"github.com/spf13/pflag\"\n)\n\n\n\ntype HasScopedFlags interface {\n\tApplyScopedFlags(flags *pflag.FlagSet) error\n}\n\n\nvar _ HasScopedFlags = NewScoped()\n\n\n\ntype Scoped struct {\n\tallowAll bool\n\trawScope string\n\tScope servicecatalog.Scope\n}\n\n\nfunc NewScoped() *Scoped {\n\treturn &Scoped{}\n}\n\n\n\nfunc (c *Scoped) AddScopedFlags(flags *pflag.FlagSet, allowAll bool) {\n\tc.allowAll = allowAll\n\tif allowAll {\n\t\tflags.StringVar(&c.rawScope, \"scope\", servicecatalog.AllScope, \"Limit the command to a particular scope: cluster, namespace or all\")\n\t} else {\n\t\tflags.StringVar(&c.rawScope, \"scope\", servicecatalog.NamespaceScope, \"Limit the command to a particular scope: cluster or namespace\")\n\t}\n}\n\n\n\n\n\nfunc (c *Scoped) ApplyScopedFlags(flags *pflag.FlagSet) error ", "output": "{\n\tswitch c.rawScope {\n\tcase servicecatalog.AllScope:\n\t\tif !c.allowAll {\n\t\t\treturn errors.New(\"invalid --scope (all), allowed values are: cluster, namespace\")\n\t\t}\n\t\tc.Scope = servicecatalog.Scope(c.rawScope)\n\t\treturn nil\n\tcase servicecatalog.ClusterScope, servicecatalog.NamespaceScope:\n\t\tc.Scope = servicecatalog.Scope(c.rawScope)\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid --scope (%s), allowed values are: all, cluster, namespace\", c.rawScope)\n\t}\n}"} {"input": "package probe_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/minio/minio/pkg/probe\"\n\t. \"gopkg.in/check.v1\"\n)\n\n\n\ntype MySuite struct{}\n\nvar _ = Suite(&MySuite{})\n\nfunc testDummy0() *probe.Error {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\treturn probe.NewError(e)\n}\n\nfunc testDummy1() *probe.Error {\n\treturn testDummy0().Trace(\"DummyTag1\")\n}\n\nfunc testDummy2() *probe.Error {\n\treturn testDummy1().Trace(\"DummyTag2\")\n}\n\nfunc (s *MySuite) TestProbe(c *C) {\n\tes := testDummy2().Trace(\"TopOfStack\")\n\tc.Assert(es, Not(Equals), nil)\n\n\tnewES := es.Trace()\n\tc.Assert(newES, Not(Equals), nil)\n}\n\nfunc (s *MySuite) TestWrappedError(c *C) {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\tes := probe.NewError(e) \n\te = probe.WrapError(es) \n\t_, ok := probe.UnwrapError(e)\n\tc.Assert(ok, Equals, true)\n}\n\nfunc Test(t *testing.T) ", "output": "{ TestingT(t) }"} {"input": "package tests\n\nimport (\n\t\"go2o/core/infrastructure/domain\"\n\t\"testing\"\n)\n\n\nfunc TestMasterPwd(t *testing.T) {\n\tuser := \"master\"\n\tpwd := \"123456\"\n\tsha1 := domain.Sha1(domain.Md5(pwd) + user + domain.Sha1OffSet)\n\tt.Log(sha1)\n}\n\nfunc TestMasterPwd2(t *testing.T) {\n\tuser := \"master\"\n\tpwd := \"fs888888@txxfmall\"\n\tsha1 := domain.Sha1(domain.Md5(pwd) + user + domain.Sha1OffSet)\n\tt.Log(sha1)\n\tt.Log(domain.Sha1OffSet)\n}\n\n\n\n\nfunc TestMerchantPwd(t *testing.T) {\n\tpwd := \"123456\"\n\tencPwd := domain.MerchantSha1Pwd(pwd)\n\tt.Log(encPwd)\n}\n\nfunc TestMemberPwd(t *testing.T) ", "output": "{\n\tpwd := domain.Md5(\"594488\")\n\tt.Log(\"--pwd=\", pwd, \"\\n\")\n\tpwd = domain.Sha1(pwd)\n\tt.Log(\"--pwd=\", pwd, \"\\n\")\n}"} {"input": "package endpoints\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype Service interface {\n\tServe(path string, w http.ResponseWriter, r *http.Request) bool\n\tClose() error\n}\n\nfunc WriteJSON(data interface{}, w http.ResponseWriter) bool ", "output": "{\n\tbytes, err := json.Marshal(data)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn false\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t_, err = w.Write(bytes)\n\treturn err == nil\n}"} {"input": "package state\n\nimport (\n\t\"github.com/hashicorp/consul/agent/structs\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\ntype Delay struct {\n\tdelay map[string]time.Time\n\n\tlock sync.RWMutex\n}\n\n\nfunc NewDelay() *Delay {\n\treturn &Delay{delay: make(map[string]time.Time)}\n}\n\n\n\n\n\n\n\n\nfunc (d *Delay) SetExpiration(key string, now time.Time, delay time.Duration, entMeta *structs.EnterpriseMeta) {\n\td.lock.Lock()\n\tdefer d.lock.Unlock()\n\n\td.delay[key] = now.Add(delay)\n\ttime.AfterFunc(delay, func() {\n\t\td.lock.Lock()\n\t\tdelete(d.delay, key)\n\t\td.lock.Unlock()\n\t})\n}\n\nfunc (d *Delay) GetExpiration(key string, entMeta *structs.EnterpriseMeta) time.Time ", "output": "{\n\td.lock.RLock()\n\texpires := d.delay[key]\n\td.lock.RUnlock()\n\treturn expires\n}"} {"input": "package mymath\n\n\n\nfunc Add(a, b int) int ", "output": "{\n\treturn (a + b)\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n)\n\n\n\nfunc healthcheck() int ", "output": "{\n\tnetwork := conf.Network\n\tbind := conf.Bind\n\n\tstrEnvConfig(&network, \"IMGPROXY_NETWORK\")\n\tstrEnvConfig(&bind, \"IMGPROXY_BIND\")\n\n\thttpc := http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDialContext: func(_ context.Context, _, _ string) (net.Conn, error) {\n\t\t\t\treturn net.Dial(network, bind)\n\t\t\t},\n\t\t},\n\t}\n\n\tres, err := httpc.Get(\"http://imgproxy/health\")\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err.Error())\n\t\treturn 1\n\t}\n\tdefer res.Body.Close()\n\n\tmsg, _ := ioutil.ReadAll(res.Body)\n\tfmt.Fprintln(os.Stderr, string(msg))\n\n\tif res.StatusCode != 200 {\n\t\treturn 1\n\t}\n\n\treturn 0\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/nanobox-io/nanobox-server/util\"\n)\n\nfunc (api *API) Suspend(rw http.ResponseWriter, req *http.Request) {\n\tif util.LockCount() <= 0 {\n\t\treturn\n\t}\n\n\twriteBody(map[string]string{\"error\": fmt.Sprintf(\"Current lock count: %d\", util.LockCount())}, rw, http.StatusNotAcceptable)\n}\n\n\n\n\n\nfunc (api *API) Lock(rw http.ResponseWriter, req *http.Request) {\n\tutil.Lock()\n\tdefer util.Unlock()\n\n\tcNotify := rw.(http.CloseNotifier)\n\t<-cNotify.CloseNotify()\n}\n\nfunc (api *API) LockCount(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\tfmt.Fprintf(rw, \"%d\", util.LockCount())\n}"} {"input": "package data\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n\n\t\"cloud.google.com/go/spanner/spansql\"\n)\n\n\nvar _ Generator = (*TimestampGenerator)(nil)\n\ntype (\n\tTimestampGenerator struct {\n\t\tsrc rand.Source\n\t\tdelta int64\n\t\tmin int64\n\t\tmax int64\n\t\tr bool\n\t}\n)\n\nfunc NewTimestampGenerator(cfg Config) (Generator, error) {\n\tret := &TimestampGenerator{\n\t\tsrc: cfg.Source(),\n\t}\n\n\tif cfg.Range() {\n\t\tret.r = true\n\n\t\tswitch min := cfg.Minimum().(type) {\n\t\tcase time.Time:\n\t\t\tret.min = min.Unix()\n\t\tcase int64:\n\t\t\tret.min = min\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"minimum '%s' of type '%T' invalid for timestamp generator\", min, min)\n\t\t}\n\n\t\tswitch max := cfg.Maximum().(type) {\n\t\tcase time.Time:\n\t\t\tret.max = max.Unix()\n\t\tcase int64:\n\t\t\tret.max = max\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"maximum '%s' of type '%T' invalid for timestamp generator\", max, max)\n\t\t}\n\t} else {\n\t\tret.min = time.Date(defaultDateMinYear, 1, 0, 0, 0, 0, 0, time.UTC).Unix()\n\t\tret.max = time.Date(defaultDateMaxYear, 1, 0, 0, 0, 0, 0, time.UTC).Unix()\n\t}\n\n\tret.delta = ret.max - ret.min\n\n\treturn ret, nil\n}\n\nfunc (g *TimestampGenerator) Next() interface{} {\n\tsec := rand.Int63n(g.delta) + g.min\n\treturn time.Unix(sec, 0)\n}\n\n\n\nfunc (g *TimestampGenerator) Type() spansql.TypeBase ", "output": "{\n\treturn spansql.Timestamp\n}"} {"input": "package service\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetServiceIDOKCode int = 200\n\n\ntype GetServiceIDOK struct {\n\n\tPayload *models.Service `json:\"body,omitempty\"`\n}\n\n\n\n\n\nfunc (o *GetServiceIDOK) WithPayload(payload *models.Service) *GetServiceIDOK {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *GetServiceIDOK) SetPayload(payload *models.Service) {\n\to.Payload = payload\n}\n\n\nfunc (o *GetServiceIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\n\nconst GetServiceIDNotFoundCode int = 404\n\n\ntype GetServiceIDNotFound struct {\n}\n\n\nfunc NewGetServiceIDNotFound() *GetServiceIDNotFound {\n\n\treturn &GetServiceIDNotFound{}\n}\n\n\nfunc (o *GetServiceIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc NewGetServiceIDOK() *GetServiceIDOK ", "output": "{\n\n\treturn &GetServiceIDOK{}\n}"} {"input": "package bot\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"sync\"\n)\n\ntype WhiteList struct {\n\tpath string\n\tnames map[string]struct{}\n\tlock sync.Mutex\n}\n\n\n\nfunc (whitelist *WhiteList) Write() error {\n\twhitelist.lock.Lock()\n\tdefer whitelist.lock.Unlock()\n\n\treturn whitelist.write()\n}\n\nfunc (whitelist *WhiteList) write() error {\n\tfile, err := os.Create(whitelist.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tw := bufio.NewWriter(file)\n\tfor line := range whitelist.names {\n\t\t_, err = fmt.Fprintln(w, line)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr = w.Flush()\n\treturn err\n}\n\nfunc (whitelist *WhiteList) Add(name string) error {\n\twhitelist.lock.Lock()\n\tdefer whitelist.lock.Unlock()\n\n\twhitelist.names[name] = struct{}{}\n\n\treturn whitelist.write()\n}\n\nfunc (whitelist *WhiteList) Contains(name string) bool {\n\t_, exists := whitelist.names[name]\n\n\treturn exists\n}\n\nfunc (whitelist *WhiteList) Remove(name string) error {\n\twhitelist.lock.Lock()\n\tdefer whitelist.lock.Unlock()\n\n\t_, exists := whitelist.names[name]\n\n\tif !exists {\n\t\treturn nil\n\t}\n\n\tdelete(whitelist.names, name)\n\n\treturn whitelist.write()\n}\n\nfunc LoadWhiteList(path string) (*WhiteList, error) ", "output": "{\n\tfile, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to open file %s: %v\", path, err)\n\t}\n\tdefer file.Close()\n\n\tlist := make(map[string]struct{})\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tlist[scanner.Text()] = struct{}{}\n\t}\n\n\terr = scanner.Err()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinstance := &WhiteList{\n\t\tpath: path,\n\t\tnames: list,\n\t}\n\n\treturn instance, nil\n}"} {"input": "package storage\n\nimport (\n\t\"context\"\n)\n\n\n\n\nfunc NewTransactionOrDie(ctx context.Context, store Store, params ...TransactionParams) Transaction {\n\ttxn, err := store.NewTransaction(ctx, params...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn txn\n}\n\n\n\n\n\n\n\n\n\nfunc WriteOne(ctx context.Context, store Store, op PatchOp, path Path, value interface{}) error {\n\ttxn, err := store.NewTransaction(ctx, WriteParams)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := store.Write(ctx, txn, op, path, value); err != nil {\n\t\tstore.Abort(ctx, txn)\n\t\treturn err\n\t}\n\n\treturn store.Commit(ctx, txn)\n}\n\n\n\n\n\nfunc Txn(ctx context.Context, store Store, params TransactionParams, f func(Transaction) error) error {\n\n\ttxn, err := store.NewTransaction(ctx, params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := f(txn); err != nil {\n\t\tstore.Abort(ctx, txn)\n\t\treturn err\n\t}\n\n\treturn store.Commit(ctx, txn)\n}\n\nfunc ReadOne(ctx context.Context, store Store, path Path) (interface{}, error) ", "output": "{\n\ttxn, err := store.NewTransaction(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer store.Abort(ctx, txn)\n\n\treturn store.Read(ctx, txn, path)\n}"} {"input": "package dockertools\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\tdocker \"github.com/fsouza/go-dockerclient\"\n\tkubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\"\n)\n\n\n\nconst (\n\tstatusRunningPrefix = \"Up\"\n\tstatusExitedPrefix = \"Exited\"\n)\n\nfunc mapState(state string) kubecontainer.ContainerState {\n\tswitch {\n\tcase strings.HasPrefix(state, statusRunningPrefix):\n\t\treturn kubecontainer.ContainerStateRunning\n\tcase strings.HasPrefix(state, statusExitedPrefix):\n\t\treturn kubecontainer.ContainerStateExited\n\tdefault:\n\t\treturn kubecontainer.ContainerStateUnknown\n\t}\n}\n\n\n\n\n\nfunc toRuntimeImage(image *docker.APIImages) (*kubecontainer.Image, error) {\n\tif image == nil {\n\t\treturn nil, fmt.Errorf(\"unable to convert a nil pointer to a runtime image\")\n\t}\n\n\treturn &kubecontainer.Image{\n\t\tID: image.ID,\n\t\tRepoTags: image.RepoTags,\n\t\tSize: image.VirtualSize,\n\t}, nil\n}\n\nfunc toRuntimeContainer(c *docker.APIContainers) (*kubecontainer.Container, error) ", "output": "{\n\tif c == nil {\n\t\treturn nil, fmt.Errorf(\"unable to convert a nil pointer to a runtime container\")\n\t}\n\n\tdockerName, hash, err := getDockerContainerNameInfo(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &kubecontainer.Container{\n\t\tID: kubecontainer.DockerID(c.ID).ContainerID(),\n\t\tName: dockerName.ContainerName,\n\t\tImage: c.Image,\n\t\tHash: hash,\n\t\tCreated: c.Created,\n\t\tState: mapState(c.Status),\n\t}, nil\n}"} {"input": "package app\n\nimport (\n\t\"net/url\"\n)\n\ntype Service interface {\n\tProxyPath() string\n\tURL() string\n\tBasicAuth() (username, password string, ok bool)\n\tAddSecret(parameters url.Values)\n}\n\ntype basicAuthService struct {\n\tproxyPath, url, clientId, clientSecret string\n}\n\nfunc (s basicAuthService) ProxyPath() string {\n\treturn s.proxyPath\n}\n\nfunc (s basicAuthService) URL() string {\n\treturn s.url\n}\n\nfunc (s basicAuthService) BasicAuth() (string, string, bool) {\n\treturn s.clientId, s.clientSecret, true\n}\n\nfunc (s basicAuthService) AddSecret(parameters url.Values) {\n}\n\ntype addParameterService struct {\n\tproxyPath, url, parameterName, clientSecret string\n}\n\nfunc (s addParameterService) ProxyPath() string {\n\treturn s.proxyPath\n}\n\nfunc (s addParameterService) URL() string {\n\treturn s.url\n}\n\nfunc (s addParameterService) BasicAuth() (string, string, bool) {\n\treturn \"\", \"\", false\n}\n\nfunc (s addParameterService) AddSecret(parameters url.Values) {\n\tparameters.Add(s.parameterName, s.clientSecret)\n}\n\nfunc BasicAuthService(proxyPath, url, clientId, clientSecret string) Service {\n\treturn basicAuthService{proxyPath, url, clientId, clientSecret}\n}\n\n\n\nfunc AddParameterService(proxyPath, url, parameterName, clientSecret string) Service ", "output": "{\n\treturn addParameterService{proxyPath, url, parameterName, clientSecret}\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/networking/v1\"\n\t\"k8s.io/client-go/deprecated/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype NetworkingV1Interface interface {\n\tRESTClient() rest.Interface\n\tNetworkPoliciesGetter\n}\n\n\ntype NetworkingV1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *NetworkingV1Client) NetworkPolicies(namespace string) NetworkPolicyInterface {\n\treturn newNetworkPolicies(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*NetworkingV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &NetworkingV1Client{client}, nil\n}\n\n\n\n\n\n\nfunc New(c rest.Interface) *NetworkingV1Client {\n\treturn &NetworkingV1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *NetworkingV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfigOrDie(c *rest.Config) *NetworkingV1Client ", "output": "{\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}"} {"input": "package safetime\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/sirupsen/logrus\"\n\t. \"gopkg.in/check.v1\"\n)\n\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\ntype SafetimeSuite struct {\n\tout *bytes.Buffer \n\tlogger *logrus.Entry\n}\n\nvar _ = Suite(&SafetimeSuite{})\n\nfunc (s *SafetimeSuite) SetUpTest(c *C) {\n\ts.out = &bytes.Buffer{}\n\tlogger := logrus.New()\n\tlogger.Out = s.out\n\ts.logger = logrus.NewEntry(logger)\n}\n\nfunc (s *SafetimeSuite) TestNegativeDuration(c *C) {\n\tfuture := time.Now().Add(time.Second)\n\td, ok := TimeSinceSafe(future, s.logger)\n\n\tc.Assert(ok, Equals, false)\n\tc.Assert(d, Equals, time.Duration(0))\n\tfmt.Println(s.out.String())\n\tc.Assert(strings.Contains(s.out.String(), \"BUG: negative duration\"), Equals, true)\n}\n\n\n\nfunc (s *SafetimeSuite) TestNonNegativeDuration(c *C) ", "output": "{\n\tpast := time.Now().Add(-10 * time.Second)\n\td, ok := TimeSinceSafe(past, s.logger)\n\n\tc.Assert(ok, Equals, true)\n\tc.Assert(d > time.Duration(0), Equals, true)\n\tc.Assert(len(s.out.String()) == 0, Equals, true)\n}"} {"input": "package hashcat3\n\ntype Dictionary struct {\n\tName string\n\tPath string\n}\n\ntype Dictionaries []Dictionary\n\nfunc (d Dictionaries) Len() int {\n\treturn len(d)\n\n}\n\n\nfunc (d Dictionaries) Less(i, j int) bool {\n\treturn d[i].Name < d[j].Name\n}\n\nfunc (d Dictionaries) Swap(i, j int) ", "output": "{\n\td[i], d[j] = d[j], d[i]\n}"} {"input": "package longrunning_test\n\nimport (\n\t\"cloud.google.com/go/longrunning/autogen\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/api/iterator\"\n\tlongrunningpb \"google.golang.org/genproto/googleapis/longrunning\"\n)\n\nfunc ExampleNewOperationsClient() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\n\n\nfunc ExampleOperationsClient_ListOperations() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.ListOperationsRequest{\n\t}\n\tit := c.ListOperations(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}\n\nfunc ExampleOperationsClient_CancelOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.CancelOperationRequest{\n\t}\n\terr = c.CancelOperation(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleOperationsClient_DeleteOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.DeleteOperationRequest{\n\t}\n\terr = c.DeleteOperation(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleOperationsClient_GetOperation() ", "output": "{\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.GetOperationRequest{\n\t}\n\tresp, err := c.GetOperation(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}"} {"input": "package redis\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\n\t\"github.com/iris-framework/iris/adaptors/sessions/sessiondb/redis/service\"\n)\n\n\ntype Database struct {\n\tredis *service.Service\n}\n\n\nfunc New(cfg ...service.Config) *Database {\n\treturn &Database{redis: service.New(cfg...)}\n}\n\n\nfunc (d *Database) Config() *service.Config {\n\treturn d.redis.Config\n}\n\n\nfunc (d *Database) Load(sid string) map[string]interface{} {\n\tvalues := make(map[string]interface{})\n\n\tif !d.redis.Connected { \n\t\td.redis.Connect()\n\t\t_, err := d.redis.PingPong()\n\t\tif err != nil {\n\t\t\tif err != nil {\n\t\t\t}\n\t\t}\n\t}\n\tval, err := d.redis.GetBytes(sid)\n\tif err == nil {\n\t\tDeserializeBytes(val, &values)\n\t}\n\n\treturn values\n\n}\n\n\n\n\n\nfunc (d *Database) Update(sid string, newValues map[string]interface{}) {\n\tif len(newValues) == 0 {\n\t\tgo d.redis.Delete(sid)\n\t} else {\n\t\tgo d.redis.Set(sid, serialize(newValues)) \n\t}\n\n}\n\n\nfunc SerializeBytes(m interface{}) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tenc := gob.NewEncoder(buf)\n\terr := enc.Encode(m)\n\tif err == nil {\n\t\treturn buf.Bytes(), nil\n\t}\n\treturn nil, err\n}\n\n\nfunc DeserializeBytes(b []byte, m interface{}) error {\n\tdec := gob.NewDecoder(bytes.NewBuffer(b))\n\treturn dec.Decode(m) \n}\n\nfunc serialize(values map[string]interface{}) []byte ", "output": "{\n\tval, err := SerializeBytes(values)\n\tif err != nil {\n\t\tprintln(\"On redisstore.serialize: \" + err.Error())\n\t}\n\n\treturn val\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/matcornic/subify/common/config\"\n\tlogger \"github.com/spf13/jwalterweatherman\"\n)\n\n\nfunc VerbosePrintln(logger *log.Logger, log string) {\n\tif config.Verbose && log != \"\" {\n\t\tlogger.Println(log)\n\t}\n}\n\n\nfunc Exit(format string, args ...interface{}) {\n\tExitVerbose(\"\", format, args...)\n}\n\n\n\nfunc ExitPrintError(err error, format string, args ...interface{}) {\n\tExitVerbose(fmt.Sprint(err), format, args...)\n}\n\n\n\n\n\nfunc ExitVerbose(verboseLog string, format string, args ...interface{}) ", "output": "{\n\tlogger.ERROR.Println(verboseLog)\n\tif !config.Verbose {\n\t\tlogger.ERROR.Println(\"Run subify with --verbose option to get more information about the error\")\n\t}\n\tlogger.FATAL.Printf(format)\n\tos.Exit(-1)\n}"} {"input": "package main\n\nimport (\n \"os\"\n \"fmt\"\n \"bufio\"\n \"encoding/hex\"\n)\n\n\n\n\n\nfunc get_hex_data(filename string) [][]byte {\n file, err := os.Open(filename)\n check(err)\n\n var data [][]byte\n scan := bufio.NewScanner(file)\n\n\tfor scan.Scan() {\n temp, err := hex.DecodeString(scan.Text())\n check(err)\n data = append(data, temp)\n }\n\n return data\n}\n\n\nfunc chunk(data []byte, size int) [][]byte {\n var chunks [][]byte\n\n for i:=0; i rsi.lastV {\n\t\tup = v - rsi.lastV\n\t} else if v < rsi.lastV {\n\t\tdown = rsi.lastV - v\n\t}\n\trsi.emaUp.Add(up)\n\trsi.emaDown.Add(down)\n\trsi.lastV = v\n\treturn rsi.Last()\n}\n\nfunc NewRSI(inTimePeriod int, warmType WarmupType) *RSI ", "output": "{\n\tema := NewEMA(inTimePeriod+1, warmType)\n\tema.alpha = float64(1) / float64(inTimePeriod)\n\treturn &RSI{\n\t\temaUp: *ema,\n\t\temaDown: *ema,\n\t}\n}"} {"input": "package windows\n\nimport (\n\t\"github.com/docker/libnetwork/driverapi\"\n\t\"github.com/docker/libnetwork/types\"\n)\n\nconst networkType = \"windows\"\n\n\n\ntype driver struct{}\n\n\nfunc Init(dc driverapi.DriverCallback) error {\n\tc := driverapi.Capability{\n\t\tScope: driverapi.LocalScope,\n\t}\n\treturn dc.RegisterDriver(networkType, &driver{}, c)\n}\n\nfunc (d *driver) Config(option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) DeleteNetwork(nid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {\n\treturn nil\n}\n\n\n\nfunc (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {\n\treturn make(map[string]interface{}, 0), nil\n}\n\n\nfunc (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {\n\treturn nil\n}\n\n\nfunc (d *driver) Leave(nid, eid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) Type() string {\n\treturn networkType\n}\n\nfunc (d *driver) DeleteEndpoint(nid, eid types.UUID) error ", "output": "{\n\treturn nil\n}"} {"input": "package opensimplex\n\nimport (\n\t\"compress/gzip\"\n\t\"encoding/json\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n)\n\n\n\nfunc TestSamplesMatch(t *testing.T) {\n\tsamples := loadSamples()\n\tn := New(0)\n\n\tfor s := range samples {\n\t\tvar expected, actual float64\n\t\tswitch len(s) {\n\t\tcase 3:\n\t\t\texpected = s[2]\n\t\t\tactual = n.Eval2(s[0], s[1])\n\t\tcase 4:\n\t\t\texpected = s[3]\n\t\t\tactual = n.Eval3(s[0], s[1], s[2])\n\t\tcase 5:\n\t\t\texpected = s[4]\n\t\t\tactual = n.Eval4(s[0], s[1], s[2], s[3])\n\t\tdefault:\n\t\t\tt.Fatalf(\"Unexpected size sample: %d\", len(s))\n\t\t}\n\n\t\tif expected != actual {\n\t\t\tt.Fatalf(\"Expected %v, got %v for %dD sample at %v\",\n\t\t\t\texpected, actual, len(s)-1, s[:len(s)-1])\n\t\t}\n\t}\n}\n\nfunc loadSamples() <-chan []float64 ", "output": "{\n\tc := make(chan []float64)\n\tgo func() {\n\t\tf, err := os.Open(path.Join(\"test_files\", \"samples.json.gz\"))\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tdefer f.Close()\n\n\t\tgz, err := gzip.NewReader(f)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\n\t\tdec := json.NewDecoder(gz)\n\t\tfor {\n\t\t\tvar sample []float64\n\t\t\tif err := dec.Decode(&sample); err == io.EOF {\n\t\t\t\tbreak\n\t\t\t} else if err != nil {\n\t\t\t\tpanic(err.Error())\n\t\t\t} else {\n\t\t\t\tc <- sample\n\t\t\t}\n\t\t}\n\t\tclose(c)\n\t}()\n\n\treturn c\n}"} {"input": "package global\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"testing\"\n\n\t\"github.com/mperham/inspeqtor/conf/global/ast\"\n\t\"github.com/mperham/inspeqtor/conf/global/lexer\"\n\t\"github.com/mperham/inspeqtor/conf/global/parser\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestBasicParsing(t *testing.T) ", "output": "{\n\tdata, err := ioutil.ReadFile(\"fixtures/inspeqtor.conf\")\n\tassert.Nil(t, err)\n\n\ts := lexer.NewLexer([]byte(data))\n\tp := parser.NewParser()\n\tobj, err := p.Parse(s)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, obj)\n\n\tconfig := obj.(ast.Config)\n\tassert.Equal(t, \"15\", config.Variables[\"cycle_time\"])\n\tassert.Equal(t, 3, len(config.Routes))\n\tassert.Equal(t, \"b!l$a%rgh^fazz\\\"\", config.Routes[\"analytics\"].Config[\"password\"])\n\tassert.Equal(t, \"smtp.example.com\", config.Routes[\"analytics\"].Config[\"smtp_server\"])\n\tlog.Printf(\"%+v\", config)\n}"} {"input": "package musicserver\n\nimport (\n\t\"net/http\"\n\t\"time\"\n)\n\nfunc adminHandler(w http.ResponseWriter, req *http.Request) {\n\tip := getIPFromRequest(req)\n\n\tif ad.ValidSession(ip) {\n\t\ttl.Render(w, \"admin\", newPlaylistInfo(ip))\n\t} else {\n\t\thttp.Redirect(w, req, url(\"/admin/login\"), http.StatusFound)\n\t}\n}\n\n\n\nfunc adminLogoutHandler(w http.ResponseWriter, req *http.Request) {\n\tip := getIPFromRequest(req)\n\tad.EndSession(ip)\n\thttp.Redirect(w, req, url(\"/\"), http.StatusSeeOther)\n}\n\nfunc adminRemoveHandler(w http.ResponseWriter, req *http.Request) {\n\tip := getIPFromRequest(req)\n\tif req.Method == http.MethodPost && ad.ValidSession(ip) {\n\t\tremUUID := req.PostFormValue(\"video_id\")\n\t\tpl.RemoveVideo(remUUID)\n\t}\n\thttp.Redirect(w, req, url(\"/admin\"), http.StatusSeeOther)\n}\n\nfunc adminKillVideoHandler(w http.ResponseWriter, req *http.Request) {\n\tip := getIPFromRequest(req)\n\tif !ad.ValidSession(ip) {\n\t\thttp.Redirect(w, req, url(\"/admin/login\"), http.StatusFound)\n\t\treturn\n\t}\n\n\tvd.End()\n\ttime.Sleep(500 * time.Millisecond)\n\n\thttp.Redirect(w, req, url(\"/admin\"), http.StatusFound)\n}\n\nfunc adminLoginHandler(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tif req.Method != http.MethodPost {\n\t\ttl.Render(w, \"admin_login\", nil)\n\t\treturn\n\t}\n\n\tip := getIPFromRequest(req)\n\tpwd := req.PostFormValue(\"admin_pwd\")\n\tif ad.ValidPassword(pwd) {\n\t\tad.StartSession(ip)\n\t\thttp.Redirect(w, req, url(\"/admin\"), http.StatusSeeOther)\n\t\treturn\n\t} else {\n\t\ttl.Render(w, \"admin_bad_login\", nil)\n\t\treturn\n\t}\n}"} {"input": "package quantity\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n\ntype Offset Size\n\nconst (\n\tOffsetKiB = Offset(1 << 10)\n\tOffsetMiB = Offset(1 << 20)\n)\n\nfunc (o *Offset) String() string {\n\treturn (*Size)(o).String()\n}\n\n\n\n\n\n\nfunc (o *Offset) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar gs string\n\tif err := unmarshal(&gs); err != nil {\n\t\treturn errors.New(`cannot unmarshal gadget offset`)\n\t}\n\n\tvar err error\n\t*o, err = ParseOffset(gs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot parse offset %q: %v\", gs, err)\n\t}\n\treturn err\n}\n\n\n\nfunc ParseOffset(gs string) (Offset, error) {\n\toffs, err := parseSizeOrOffset(gs)\n\tif offs < 0 {\n\t\treturn 0, errors.New(\"offset cannot be negative\")\n\t}\n\treturn Offset(offs), err\n}\n\nfunc (o *Offset) IECString() string ", "output": "{\n\treturn iecSizeString(int64(*o))\n}"} {"input": "package datastore\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype JSONMessage interface {\n\tBytes() json.RawMessage\n\tVersion() map[string]int\n}\n\n\nfunc NewJSONMessage(data []byte, version map[string]int) JSONMessage {\n\treturn &jsonMessage{data, version}\n}\n\ntype jsonMessage struct {\n\tdata json.RawMessage\n\tvEntity map[string]int\n}\n\nfunc (m *jsonMessage) Bytes() json.RawMessage {\n\treturn m.data\n}\n\n\n\n\nfunc (m *jsonMessage) MarshalJSON() ([]byte, error) {\n\treturn m.data.MarshalJSON()\n}\n\n\nfunc (m *jsonMessage) UnmarshalJSON(data []byte) error {\n\treturn m.data.UnmarshalJSON(data)\n}\n\nfunc (m *jsonMessage) Version() map[string]int ", "output": "{\n\treturn m.vEntity\n}"} {"input": "package main \n\n\n\nfunc f() ", "output": "{\n\tvar a = 'r'-4.5\n\ta += 1\n}"} {"input": "package install\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tutilruntime \"k8s.io/apimachinery/pkg/util/runtime\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\n\tappsv1 \"github.com/openshift/api/apps/v1\"\n\tappsapiv1 \"github.com/openshift/origin/pkg/apps/apis/apps/v1\"\n)\n\n\n\n\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(appsapiv1.Install(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(appsv1.GroupVersion))\n}\n\nfunc init() ", "output": "{\n\tInstall(legacyscheme.Scheme)\n}"} {"input": "package basictypes\n\nconst (\n\tAString = \"a string\"\n\tAnInt = 7\n\tAnInt2 = 1<<63 - 1\n\tAFloat = 0.2015\n\tARune = rune(32)\n\tABool = true\n)\n\nfunc Ints(x int8, y int16, z int32, t int64, u int) {}\n\nfunc Error() error { return nil }\n\nfunc ErrorPair() (int, error) { return 0, nil }\n\nfunc ByteArrays(x []byte) []byte { return nil }\n\n\n\nfunc Bool(bool) bool ", "output": "{ return true }"} {"input": "package main\n\nvar log string\n\ntype T int\n\nfunc (t T) a(s string) T {\n\tlog += \"a(\" + s + \")\"\n\treturn t\n}\n\nfunc (T) b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\ntype F func(s string) F\n\nfunc a(s string) F {\n\tlog += \"a(\" + s + \")\"\n\treturn F(a)\n}\n\nfunc b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\ntype I interface {\n\ta(s string) I\n\tb(s string) string\n}\n\ntype T1 int\n\nfunc (t T1) a(s string) I {\n\tlog += \"a(\" + s + \")\"\n\treturn t\n}\n\n\n\nvar ok = true\n\nfunc bad() {\n\tif !ok {\n\t\tprintln(\"BUG\")\n\t\tok = false\n\t}\n\tprintln(log)\n}\n\nfunc main() {\n\tvar t T\n\tif t.a(\"1\").a(t.b(\"2\")); log != \"a(1)ba(2)\" {\n\t\tbad()\n\t}\n\tlog = \"\"\n\tif a(\"3\")(b(\"4\"))(b(\"5\")); log != \"a(3)ba(4)ba(5)\" {\n\t\tbad()\n\t}\n\tlog = \"\"\n\tvar i I = T1(0)\n\tif i.a(\"6\").a(i.b(\"7\")).a(i.b(\"8\")).a(i.b(\"9\")); log != \"a(6)ba(7)ba(8)ba(9)\" {\n\t\tbad()\n\t}\n}\n\nfunc (T1) b(s string) string ", "output": "{\n\tlog += \"b\"\n\treturn s\n}"} {"input": "package internalversion\n\nimport (\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n\tcore \"k8s.io/kubernetes/pkg/apis/core\"\n)\n\n\ntype ComponentStatusLister interface {\n\tList(selector labels.Selector) (ret []*core.ComponentStatus, err error)\n\tGet(name string) (*core.ComponentStatus, error)\n\tComponentStatusListerExpansion\n}\n\n\ntype componentStatusLister struct {\n\tindexer cache.Indexer\n}\n\n\n\n\n\nfunc (s *componentStatusLister) List(selector labels.Selector) (ret []*core.ComponentStatus, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*core.ComponentStatus))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *componentStatusLister) Get(name string) (*core.ComponentStatus, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(core.Resource(\"componentstatus\"), name)\n\t}\n\treturn obj.(*core.ComponentStatus), nil\n}\n\nfunc NewComponentStatusLister(indexer cache.Indexer) ComponentStatusLister ", "output": "{\n\treturn &componentStatusLister{indexer: indexer}\n}"} {"input": "package ai\n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\ntype Loader func(context.Context) (map[int64]int64, error)\n\ntype AI struct {\n\twhites map[int64]int64\n\tsync.RWMutex\n}\n\n\n\nfunc (a *AI) White(mid int64) (num int64, ok bool) {\n\ta.RLock()\n\tdefer a.RUnlock()\n\tnum, ok = a.whites[mid]\n\treturn\n}\n\nfunc (a *AI) LoadWhite(c context.Context, loader Loader) (err error) {\n\tvar (\n\t\twhites map[int64]int64\n\t)\n\tif whites, err = loader(c); err != nil {\n\t\treturn\n\t}\n\ta.Lock()\n\ta.whites = whites\n\ta.Unlock()\n\treturn\n}\n\nfunc New() (a *AI) ", "output": "{\n\treturn &AI{\n\t\twhites: make(map[int64]int64),\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"net/http\"\n\n\t\"github.com/coreos/fleet/log\"\n)\n\nvar unavailable = &unavailableHdlr{}\n\nfunc NewServer(listeners []net.Listener, hdlr http.Handler) *Server {\n\treturn &Server{\n\t\tlisteners: listeners,\n\t\tapi: hdlr,\n\t\tcur: unavailable,\n\t}\n}\n\ntype Server struct {\n\tlisteners []net.Listener\n\tapi http.Handler\n\tcur http.Handler\n}\n\nfunc (s *Server) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\ts.cur.ServeHTTP(rw, req)\n}\n\nfunc (s *Server) Serve() {\n\tfor i, _ := range s.listeners {\n\t\tl := s.listeners[i]\n\t\tgo func() {\n\t\t\terr := http.Serve(l, s)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed serving HTTP on listener: %s\", l.Addr)\n\t\t\t}\n\t\t}()\n\t}\n}\n\n\n\n\nfunc (s *Server) Available(stop chan bool) {\n\ts.cur = s.api\n\t<-stop\n\ts.cur = unavailable\n}\n\ntype unavailableHdlr struct{}\n\n\n\nfunc (uh *unavailableHdlr) ServeHTTP(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\tsendError(rw, http.StatusServiceUnavailable, errors.New(\"fleet server currently unavailable\"))\n}"} {"input": "package errors\n\nimport \"reflect\"\n\n\nfunc Is(err, target error) bool {\n\tif target == nil {\n\t\treturn err == target\n\t}\n\n\tisComparable := reflect.TypeOf(target).Comparable()\n\tfor {\n\t\tif isComparable && err == target {\n\t\t\treturn true\n\t\t}\n\t\tif x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) {\n\t\t\treturn true\n\t\t}\n\t\tif err = unwrap(err); err == nil {\n\t\t\treturn false\n\t\t}\n\t}\n}\n\n\n\nfunc unwrap(err error) error ", "output": "{\n\tu, ok := err.(interface {\n\t\tUnwrap() error\n\t})\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn u.Unwrap()\n}"} {"input": "package iso20022\n\n\ntype DirectDebitTransaction7 struct {\n\n\tMandateRelatedInformation *MandateRelatedInformation8 `xml:\"MndtRltdInf,omitempty\"`\n\n\tCreditorSchemeIdentification *PartyIdentification43 `xml:\"CdtrSchmeId,omitempty\"`\n\n\tPreNotificationIdentification *Max35Text `xml:\"PreNtfctnId,omitempty\"`\n\n\tPreNotificationDate *ISODate `xml:\"PreNtfctnDt,omitempty\"`\n}\n\nfunc (d *DirectDebitTransaction7) AddMandateRelatedInformation() *MandateRelatedInformation8 {\n\td.MandateRelatedInformation = new(MandateRelatedInformation8)\n\treturn d.MandateRelatedInformation\n}\n\nfunc (d *DirectDebitTransaction7) AddCreditorSchemeIdentification() *PartyIdentification43 {\n\td.CreditorSchemeIdentification = new(PartyIdentification43)\n\treturn d.CreditorSchemeIdentification\n}\n\nfunc (d *DirectDebitTransaction7) SetPreNotificationIdentification(value string) {\n\td.PreNotificationIdentification = (*Max35Text)(&value)\n}\n\n\n\nfunc (d *DirectDebitTransaction7) SetPreNotificationDate(value string) ", "output": "{\n\td.PreNotificationDate = (*ISODate)(&value)\n}"} {"input": "package minecraft\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"github.com/LilyPad/GoLilyPad/packet\"\n)\n\ntype PacketServerPluginMessage struct {\n\tChannel string\n\tData []byte\n}\n\nfunc NewPacketServerPluginMessage(channel string, data []byte) (this *PacketServerPluginMessage) {\n\tthis = new(PacketServerPluginMessage)\n\tthis.Channel = channel\n\tthis.Data = data\n\treturn\n}\n\nfunc (this *PacketServerPluginMessage) Id() int {\n\treturn PACKET_SERVER_PLUGIN_MESSAGE\n}\n\ntype packetServerPluginMessageCodec struct {\n\n}\n\nfunc (this *packetServerPluginMessageCodec) Decode(reader io.Reader) (decode packet.Packet, err error) {\n\tpacketServerPluginMessage := new(PacketServerPluginMessage)\n\tpacketServerPluginMessage.Channel, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\tpacketServerPluginMessage.Data, err = ioutil.ReadAll(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\tdecode = packetServerPluginMessage\n\treturn\n}\n\n\n\nfunc (this *packetServerPluginMessageCodec) Encode(writer io.Writer, encode packet.Packet) (err error) ", "output": "{\n\tpacketServerPluginMessage := encode.(*PacketServerPluginMessage)\n\terr = packet.WriteString(writer, packetServerPluginMessage.Channel)\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = writer.Write(packetServerPluginMessage.Data)\n\treturn\n}"} {"input": "package networkloadbalancer\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ChangeNetworkLoadBalancerCompartmentRequest struct {\n\n\tNetworkLoadBalancerId *string `mandatory:\"true\" contributesTo:\"path\" name:\"networkLoadBalancerId\"`\n\n\tChangeNetworkLoadBalancerCompartmentDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ChangeNetworkLoadBalancerCompartmentResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ChangeNetworkLoadBalancerCompartmentResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ChangeNetworkLoadBalancerCompartmentResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package demo\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/mabetle/mgo/mcore/msdb\"\n)\n\n\n\n\n\nfunc DemoSimpleTable(table msdb.SimpleTable) ", "output": "{\n\n\tvar rows int = table.GetRows()\n\tvar cols int = table.GetCols()\n\n\tfmt.Println(\"Rows:\", rows)\n\tfmt.Println(\"Cols:\", cols)\n\n\n\tfor table.Next() {\n\t\tfor i := 0; i < cols; i++ {\n\t\t\tfmt.Printf(\"%s\\t\", table.GetString(string(i)))\n\t\t}\n\t\tfmt.Println()\n\t}\n}"} {"input": "package awsping\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n)\n\n\ntype RequestType int\n\nconst (\n\tRequestTypeHTTP RequestType = iota\n\tRequestTypeTCP\n)\n\n\ntype Requester interface {\n\tDo(ua, url string, reqType RequestType) (time.Duration, error)\n}\n\n\ntype AWSHTTPRequester interface {\n\tDo(req *http.Request) (*http.Response, error)\n}\n\n\ntype AWSTCPRequester interface {\n\tDial(network, address string) (net.Conn, error)\n}\n\n\ntype AWSRequest struct {\n\thttpClient AWSHTTPRequester\n\ttcpClient AWSTCPRequester\n}\n\n\nfunc NewAWSRequest() *AWSRequest {\n\treturn &AWSRequest{\n\t\thttpClient: &http.Client{},\n\t\ttcpClient: &net.Dialer{},\n\t}\n}\n\n\n\n\n\nfunc (r *AWSRequest) DoTCP(_, addr string) (time.Duration, error) {\n\tstart := time.Now()\n\tconn, err := r.tcpClient.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tl := time.Since(start)\n\tdefer conn.Close()\n\n\treturn l, nil\n}\n\n\nfunc (r *AWSRequest) Do(ua, url string, reqType RequestType) (time.Duration, error) {\n\tif reqType == RequestTypeHTTP {\n\t\treturn r.DoHTTP(ua, url)\n\t}\n\treturn r.DoTCP(ua, url)\n}\n\nfunc (r *AWSRequest) DoHTTP(ua, url string) (time.Duration, error) ", "output": "{\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treq.Header.Set(\"User-Agent\", ua)\n\n\tstart := time.Now()\n\tresp, err := r.httpClient.Do(req)\n\tlatency := time.Since(start)\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn latency, nil\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/apier/v1\"\n\nfunc init() {\n\tc := &CmdAccountAddTriggers{\n\t\tname: \"account_triggers_add\",\n\t\trpcMethod: \"ApierV1.AddAccountActionTriggers\",\n\t\trpcParams: &v1.AttrAddAccountActionTriggers{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdAccountAddTriggers struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrAddAccountActionTriggers\n\t*CommandExecuter\n}\n\n\n\nfunc (self *CmdAccountAddTriggers) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdAccountAddTriggers) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrAddAccountActionTriggers{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdAccountAddTriggers) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdAccountAddTriggers) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *CmdAccountAddTriggers) Name() string ", "output": "{\n\treturn self.name\n}"} {"input": "package plugin\n\nimport (\n\t\"github.com/pkg/errors\"\n\t\"github.com/xeipuuv/gojsonschema\"\n)\n\ntype Container struct {\n\tPlugin Plugin\n\tschema *gojsonschema.Schema\n}\n\ntype ValidationResult struct {\n\tErrors []error\n}\n\nfunc NewContainer(newPlugin NewFunc) (Container, error) {\n\tplugin, err := newPlugin()\n\tif err != nil {\n\t\treturn Container{}, errors.Wrap(err, \"failed to instantiate plugin\")\n\t}\n\tdescription := plugin.Describe()\n\tvar schema *gojsonschema.Schema\n\tif description.SpecSchema != nil {\n\t\tschema, err = gojsonschema.NewSchema(gojsonschema.NewBytesLoader(description.SpecSchema))\n\t\tif err != nil {\n\t\t\treturn Container{}, errors.Wrapf(err, \"can't use plugin %q due to invalid schema\", description.Name)\n\t\t}\n\t}\n\n\treturn Container{\n\t\tPlugin: plugin,\n\t\tschema: schema,\n\t}, nil\n}\n\n\n\nfunc (pc *Container) ValidateSpec(pluginSpec map[string]interface{}) (ValidationResult, error) ", "output": "{\n\tif pc.schema == nil {\n\t\treturn ValidationResult{}, nil\n\t}\n\n\tresult, err := pc.schema.Validate(gojsonschema.NewGoLoader(pluginSpec))\n\tif err != nil {\n\t\treturn ValidationResult{}, errors.Wrap(err, \"error validating plugin spec\")\n\t}\n\n\tif !result.Valid() {\n\t\tvalidationErrors := result.Errors()\n\t\terrs := make([]error, 0, len(validationErrors))\n\n\t\tfor _, validationErr := range validationErrors {\n\t\t\terrs = append(errs, errors.New(validationErr.String()))\n\t\t}\n\n\t\treturn ValidationResult{errs}, nil\n\t}\n\n\treturn ValidationResult{}, nil\n}"} {"input": "package errors\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype MultiError struct {\n\tErrors []error\n}\n\nfunc NewMultiError(errs ...error) error {\n\tnilsRemoved := make([]error, 0, len(errs))\n\tfor _, item := range errs {\n\t\tif item != nil {\n\t\t\tnilsRemoved = append(nilsRemoved, item)\n\t\t}\n\t}\n\n\tif len(nilsRemoved) == 0 {\n\t\treturn nil\n\t}\n\n\treturn MultiError{Errors: nilsRemoved}\n}\n\n\n\nfunc (errs MultiError) Error() string ", "output": "{\n\terrorMessages := []string{}\n\tfor _, err := range errs.Errors {\n\t\tif err != nil {\n\t\t\terrorMessages = append(errorMessages, err.Error())\n\t\t}\n\t}\n\n\treturn fmt.Sprintf(\"Hit multiple errors:\\n%s\", strings.Join(errorMessages, \"\\n\"))\n}"} {"input": "func reversePairs(nums []int) int {\n return mergeSort(nums, 0, len(nums))\n}\n\n\n\nfunc mergeSort(nums []int, start, end int) int ", "output": "{\n if end - start <= 1 {\n return 0\n }\n mid := (start + end) >> 1\n count := mergeSort(nums, start, mid) + mergeSort(nums, mid, end)\n \n buf := make([]int, end-start)\n bufTail := 0\n j, k := mid, mid\n for i := start; i < mid; i++ {\n for k < end && 2*nums[k] < nums[i] {\n k++\n }\n for j < end && nums[j] < nums[i] {\n buf[bufTail] = nums[j]\n bufTail++\n j++\n }\n buf[bufTail] = nums[i]\n bufTail++\n \n count += k - mid\n }\n copy(nums[start:], buf[:bufTail])\n \n return count\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSBatchJobDefinition_NodeRangeProperty struct {\n\n\tContainer *AWSBatchJobDefinition_ContainerProperties `json:\"Container,omitempty\"`\n\n\tTargetNodes string `json:\"TargetNodes,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) AWSCloudFormationType() string {\n\treturn \"AWS::Batch::JobDefinition.NodeRangeProperty\"\n}\n\n\n\n\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) DependsOn() []string ", "output": "{\n\treturn r._dependsOn\n}"} {"input": "package api\n\n\ntype UserInfo interface {\n\tGetName() string\n\tGetUID() string\n\tGetScope() string\n\tGetExtra() map[string]string\n}\n\n\n\ntype UserIdentityInfo interface {\n\tGetUserName() string\n\tGetProviderName() string\n\tGetExtra() map[string]string\n}\n\n\ntype UserIdentityMapper interface {\n\tUserFor(identityInfo UserIdentityInfo) (UserInfo, error)\n}\n\ntype Client interface {\n\tGetId() string\n\tGetSecret() string\n\tGetRedirectUri() string\n\tGetUserData() interface{}\n}\n\ntype Grant struct {\n\tClient Client\n\tScope string\n\tExpiration int64\n\tRedirectURI string\n}\n\ntype DefaultUserInfo struct {\n\tName string\n\tUID string\n\tScope string\n\tExtra map[string]string\n}\n\nfunc (i *DefaultUserInfo) GetName() string {\n\treturn i.Name\n}\n\nfunc (i *DefaultUserInfo) GetUID() string {\n\treturn i.UID\n}\n\nfunc (i *DefaultUserInfo) GetScope() string {\n\treturn i.Scope\n}\n\nfunc (i *DefaultUserInfo) GetExtra() map[string]string {\n\treturn i.Extra\n}\n\ntype DefaultUserIdentityInfo struct {\n\tUserName string\n\tProviderName string\n\tExtra map[string]string\n}\n\n\n\n\nfunc (i *DefaultUserIdentityInfo) GetUserName() string {\n\treturn i.UserName\n}\n\nfunc (i *DefaultUserIdentityInfo) GetProviderName() string {\n\treturn i.ProviderName\n}\n\nfunc (i *DefaultUserIdentityInfo) GetExtra() map[string]string {\n\treturn i.Extra\n}\n\nfunc NewDefaultUserIdentityInfo(username string) DefaultUserIdentityInfo ", "output": "{\n\treturn DefaultUserIdentityInfo{\n\t\tUserName: username,\n\t\tExtra: make(map[string]string),\n\t}\n}"} {"input": "package compute_test\n\nimport (\n\t\"context\"\n\n\tcompute \"cloud.google.com/go/compute/apiv1\"\n\t\"google.golang.org/api/iterator\"\n\tcomputepb \"google.golang.org/genproto/googleapis/cloud/compute/v1\"\n)\n\nfunc ExampleNewAcceleratorTypesRESTClient() {\n\tctx := context.Background()\n\tc, err := compute.NewAcceleratorTypesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\t_ = c\n}\n\nfunc ExampleAcceleratorTypesClient_AggregatedList() {\n\tctx := context.Background()\n\tc, err := compute.NewAcceleratorTypesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\treq := &computepb.AggregatedListAcceleratorTypesRequest{\n\t}\n\tit := c.AggregatedList(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}\n\nfunc ExampleAcceleratorTypesClient_Get() {\n\tctx := context.Background()\n\tc, err := compute.NewAcceleratorTypesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\treq := &computepb.GetAcceleratorTypeRequest{\n\t}\n\tresp, err := c.Get(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\n\n\nfunc ExampleAcceleratorTypesClient_List() ", "output": "{\n\tctx := context.Background()\n\tc, err := compute.NewAcceleratorTypesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\treq := &computepb.ListAcceleratorTypesRequest{\n\t}\n\tit := c.List(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}"} {"input": "package subnets\n\nimport \"net\"\n\nfunc equals(a *net.IPNet, b *net.IPNet) bool {\n\taOnes, aBits := a.Mask.Size()\n\tbOnes, bBits := b.Mask.Size()\n\treturn a.IP.Equal(b.IP) && (aOnes == bOnes) && (aBits == bBits)\n}\n\n\n\nfunc next(ip net.IP) net.IP {\n\tnext := clone(ip)\n\tfor i := len(next) - 1; i >= 0; i-- {\n\t\tnext[i]++\n\t\tif next[i] != 0 {\n\t\t\treturn next\n\t\t}\n\t}\n\n\tpanic(\"overflowed maximum IP\")\n}\n\nfunc clone(ip net.IP) net.IP {\n\tclone := make([]byte, len(ip))\n\tcopy(clone, ip)\n\treturn clone\n}\n\nfunc max(ipn *net.IPNet) net.IP {\n\tmask := ipn.Mask\n\tmin := clone(ipn.IP)\n\n\tif len(mask) != len(min) {\n\t\tpanic(\"length of mask is not compatible with length of network IP\")\n\t}\n\n\tmax := make([]byte, len(min))\n\tfor i, b := range mask {\n\t\tmax[i] = min[i] | ^b\n\t}\n\n\treturn net.IP(max).To16()\n}\n\nfunc overlaps(a *net.IPNet, b *net.IPNet) bool ", "output": "{\n\treturn a.Contains(b.IP) || b.Contains(a.IP)\n}"} {"input": "package session\n\nimport (\n\tgomock \"github.com/golang/mock/gomock\"\n\tanonymous \"github.com/skygeario/skygear-server/pkg/auth/dependency/identity/anonymous\"\n\treflect \"reflect\"\n)\n\n\ntype MockAnonymousIdentityProvider struct {\n\tctrl *gomock.Controller\n\trecorder *MockAnonymousIdentityProviderMockRecorder\n}\n\n\ntype MockAnonymousIdentityProviderMockRecorder struct {\n\tmock *MockAnonymousIdentityProvider\n}\n\n\nfunc NewMockAnonymousIdentityProvider(ctrl *gomock.Controller) *MockAnonymousIdentityProvider {\n\tmock := &MockAnonymousIdentityProvider{ctrl: ctrl}\n\tmock.recorder = &MockAnonymousIdentityProviderMockRecorder{mock}\n\treturn mock\n}\n\n\n\n\n\nfunc (m *MockAnonymousIdentityProvider) List(userID string) ([]*anonymous.Identity, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", userID)\n\tret0, _ := ret[0].([]*anonymous.Identity)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}\n\n\nfunc (mr *MockAnonymousIdentityProviderMockRecorder) List(userID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"List\", reflect.TypeOf((*MockAnonymousIdentityProvider)(nil).List), userID)\n}\n\nfunc (m *MockAnonymousIdentityProvider) EXPECT() *MockAnonymousIdentityProviderMockRecorder ", "output": "{\n\treturn m.recorder\n}"} {"input": "package main\n\n\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"cloud.google.com/go/bigquery\"\n\t\"google.golang.org/api/iterator\"\n)\n\n\n\nfunc main() {\n\tprojectID := os.Getenv(\"GOOGLE_CLOUD_PROJECT\")\n\tif projectID == \"\" {\n\t\tfmt.Println(\"GOOGLE_CLOUD_PROJECT environment variable must be set.\")\n\t\tos.Exit(1)\n\t}\n\n\tctx := context.Background()\n\n\tclient, err := bigquery.NewClient(ctx, projectID)\n\tif err != nil {\n\t\tlog.Fatalf(\"bigquery.NewClient: %v\", err)\n\t}\n\tdefer client.Close()\n\n\trows, err := query(ctx, client)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := printResults(os.Stdout, rows); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\n\n\n\ntype StackOverflowRow struct {\n\tURL string `bigquery:\"url\"`\n\tViewCount int64 `bigquery:\"view_count\"`\n}\n\n\nfunc printResults(w io.Writer, iter *bigquery.RowIterator) error {\n\tfor {\n\t\tvar row StackOverflowRow\n\t\terr := iter.Next(&row)\n\t\tif err == iterator.Done {\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error iterating through results: %v\", err)\n\t\t}\n\n\t\tfmt.Fprintf(w, \"url: %s views: %d\\n\", row.URL, row.ViewCount)\n\t}\n}\n\nfunc query(ctx context.Context, client *bigquery.Client) (*bigquery.RowIterator, error) ", "output": "{\n\n\tquery := client.Query(\n\t\t`SELECT\n\t\t\tCONCAT(\n\t\t\t\t'https:stackoverflow.com/questions/',\n\t\t\t\tCAST(id as STRING)) as url,\n\t\t\tview_count\n\t\tFROM ` + \"`bigquery-public-data.stackoverflow.posts_questions`\" + `\n\t\tWHERE tags like '%google-bigquery%'\n\t\tORDER BY view_count DESC\n\t\tLIMIT 10;`)\n\treturn query.Read(ctx)\n}"} {"input": "package validation\n\nimport (\n\t\"k8s.io/apimachinery/pkg/util/validation/field\"\n\t\"k8s.io/component-base/config\"\n)\n\n\n\n\n\nfunc ValidateLeaderElectionConfiguration(cc *config.LeaderElectionConfiguration, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif !cc.LeaderElect {\n\t\treturn allErrs\n\t}\n\tif cc.LeaseDuration.Duration <= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"leaseDuration\"), cc.LeaseDuration, \"must be greater than zero\"))\n\t}\n\tif cc.RenewDeadline.Duration <= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"renewDeadline\"), cc.LeaseDuration, \"must be greater than zero\"))\n\t}\n\tif cc.RetryPeriod.Duration <= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"retryPeriod\"), cc.RetryPeriod, \"must be greater than zero\"))\n\t}\n\tif cc.LeaseDuration.Duration < cc.RenewDeadline.Duration {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"leaseDuration\"), cc.RenewDeadline, \"LeaseDuration must be greater than RenewDeadline\"))\n\t}\n\tif len(cc.ResourceLock) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"resourceLock\"), cc.RenewDeadline, \"resourceLock is required\"))\n\t}\n\treturn allErrs\n}\n\nfunc ValidateClientConnectionConfiguration(cc *config.ClientConnectionConfiguration, fldPath *field.Path) field.ErrorList ", "output": "{\n\tallErrs := field.ErrorList{}\n\tif cc.Burst < 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"burst\"), cc.Burst, \"must be non-negative\"))\n\t}\n\treturn allErrs\n}"} {"input": "package test\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"runtime\"\n)\n\nvar debug, development, trace, enableStackTrace, disableStackTrace, printStackTrace bool\n\nvar logger log.Logger\n\n\n\nfunc handlePanic(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tbuf := make([]byte, 2<<16)\n\tbuf = buf[:runtime.Stack(buf, true)]\n\tw.Write(buf)\n\tlogger.Printf(\"Panic: %s\", buf)\n\tw.Write([]byte(\"An unexpected runtime error occurred\"))\n\tif debug {\n\t\tw.Write(buf)\n\t}\n\tif development {\n\t\tw.Write(buf)\n\t}\n\tif trace {\n\t\tw.Write(buf)\n\t}\n\tif enableStackTrace {\n\t\tw.Write(buf)\n\t}\n\tif !disableStackTrace {\n\t\tw.Write(buf) \n\t}\n\tif printStackTrace {\n\t\tw.Write(buf)\n\t}\n}"} {"input": "package geddit\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\ntype Submission struct {\n\tAuthor string `json:\"author\"`\n\tTitle string `json:\"title\"`\n\tURL string `json:\"url\"`\n\tDomain string `json:\"domain\"`\n\tSubreddit string `json:\"subreddit\"`\n\tSubredditID string `json:\"subreddit_id\"`\n\tFullID string `json:\"name\"`\n\tID string `json:\"id\"`\n\tPermalink string `json:\"permalink\"`\n\tSelftext string `json:\"selftext\"`\n\tThumbnailURL string `json:\"thumbnail\"`\n\tDateCreated float64 `json:\"created_utc\"`\n\tNumComments int `json:\"num_comments\"`\n\tScore int `json:\"score\"`\n\tUps int `json:\"ups\"`\n\tDowns int `json:\"downs\"`\n\tIsNSFW bool `json:\"over_18\"`\n\tIsSelf bool `json:\"is_self\"`\n\tWasClicked bool `json:\"clicked\"`\n\tIsSaved bool `json:\"saved\"`\n\tBannedBy *string `json:\"banned_by\"`\n}\n\nfunc (h Submission) voteID() string { return h.FullID }\nfunc (h Submission) deleteID() string { return h.FullID }\n\n\n\nfunc (h *Submission) FullPermalink() string {\n\treturn \"https://reddit.com\" + h.Permalink\n}\n\n\nfunc (h *Submission) String() string {\n\tplural := \"\"\n\tif h.NumComments != 1 {\n\t\tplural = \"s\"\n\t}\n\tcomments := fmt.Sprintf(\"%d comment%s\", h.NumComments, plural)\n\treturn fmt.Sprintf(\"%d - %s (%s)\", h.Score, h.Title, comments)\n}\n\nfunc (h Submission) replyID() string ", "output": "{ return h.FullID }"} {"input": "package iso20022\n\n\ntype ApplicationParameters4 struct {\n\n\tApplicationIdentification *Max35Text `xml:\"ApplId\"`\n\n\tVersion *Max256Text `xml:\"Vrsn\"`\n\n\tParameters []*Max100KBinary `xml:\"Params,omitempty\"`\n\n\tEncryptedParameters *ContentInformationType10 `xml:\"NcrptdParams,omitempty\"`\n}\n\n\n\nfunc (a *ApplicationParameters4) SetVersion(value string) {\n\ta.Version = (*Max256Text)(&value)\n}\n\nfunc (a *ApplicationParameters4) AddParameters(value string) {\n\ta.Parameters = append(a.Parameters, (*Max100KBinary)(&value))\n}\n\nfunc (a *ApplicationParameters4) AddEncryptedParameters() *ContentInformationType10 {\n\ta.EncryptedParameters = new(ContentInformationType10)\n\treturn a.EncryptedParameters\n}\n\nfunc (a *ApplicationParameters4) SetApplicationIdentification(value string) ", "output": "{\n\ta.ApplicationIdentification = (*Max35Text)(&value)\n}"} {"input": "package elastic\n\n\n\n\n\n\n\n\n\ntype MissingAggregation struct {\n\tfield string\n\tsubAggregations map[string]Aggregation\n\tmeta map[string]interface{}\n}\n\nfunc NewMissingAggregation() *MissingAggregation {\n\treturn &MissingAggregation{\n\t\tsubAggregations: make(map[string]Aggregation),\n\t}\n}\n\nfunc (a *MissingAggregation) Field(field string) *MissingAggregation {\n\ta.field = field\n\treturn a\n}\n\nfunc (a *MissingAggregation) SubAggregation(name string, subAggregation Aggregation) *MissingAggregation {\n\ta.subAggregations[name] = subAggregation\n\treturn a\n}\n\n\n\n\nfunc (a *MissingAggregation) Source() (interface{}, error) {\n\n\tsource := make(map[string]interface{})\n\topts := make(map[string]interface{})\n\tsource[\"missing\"] = opts\n\n\tif a.field != \"\" {\n\t\topts[\"field\"] = a.field\n\t}\n\n\tif len(a.subAggregations) > 0 {\n\t\taggsMap := make(map[string]interface{})\n\t\tsource[\"aggregations\"] = aggsMap\n\t\tfor name, aggregate := range a.subAggregations {\n\t\t\tsrc, err := aggregate.Source()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\taggsMap[name] = src\n\t\t}\n\t}\n\n\tif len(a.meta) > 0 {\n\t\tsource[\"meta\"] = a.meta\n\t}\n\n\treturn source, nil\n}\n\nfunc (a *MissingAggregation) Meta(metaData map[string]interface{}) *MissingAggregation ", "output": "{\n\ta.meta = metaData\n\treturn a\n}"} {"input": "package scan\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"h12.io/dfa\"\n)\n\ntype Matcher struct {\n\t*dfa.M\n\tEOF int\n\tIllegal int\n\n\tfast *dfa.FastM\n}\ntype MID struct {\n\tM interface{}\n\tID int\n}\n\n\n\nfunc (m *Matcher) Init() *Matcher {\n\tm.fast = m.M.ToFast()\n\treturn m\n}\n\nfunc (m *Matcher) Size() int {\n\treturn m.fast.Size()\n}\n\nfunc (m *Matcher) Count() int {\n\treturn m.fast.Count()\n}\n\nfunc (m *Matcher) WriteGo(w io.Writer, pac string) {\n\tfmt.Fprintln(w, \"&scan.Matcher{\")\n\tfmt.Fprintf(w, \"EOF: %d,\\n\", m.EOF)\n\tfmt.Fprintf(w, \"Illegal: %d,\\n\", m.Illegal)\n\tfmt.Fprint(w, \"M: \")\n\tm.M.WriteGo(w, pac)\n\tfmt.Fprintln(w, \"}\")\n}\n\nfunc or(mids []MID) *dfa.M {\n\tms := make([]interface{}, len(mids))\n\tfor i, mid := range mids {\n\t\tvar m *dfa.M\n\t\tswitch o := mid.M.(type) {\n\t\tcase *dfa.M:\n\t\t\tm = o\n\t\tcase string:\n\t\t\tm = dfa.Str(o)\n\t\tdefault:\n\t\t\tpanic(\"member M of MID should be type of either string or *M\")\n\t\t}\n\t\tms[i] = m.As(mid.ID)\n\t}\n\treturn dfa.Or(ms...)\n}\n\nfunc NewMatcher(eof, illegal int, mids []MID) *Matcher ", "output": "{\n\tm := or(mids)\n\tfast := m.ToFast()\n\treturn &Matcher{\n\t\tEOF: eof,\n\t\tIllegal: illegal,\n\t\tM: m,\n\t\tfast: fast}\n}"} {"input": "package th\n\nimport (\n\t\"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/blevesearch/bleve/analysis\"\n\t\"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/blevesearch/bleve/analysis/token_filters/stop_tokens_filter\"\n\t\"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/blevesearch/bleve/registry\"\n)\n\n\n\nfunc init() {\n\tregistry.RegisterTokenFilter(StopName, StopTokenFilterConstructor)\n}\n\nfunc StopTokenFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) ", "output": "{\n\ttokenMap, err := cache.TokenMapNamed(StopName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn stop_tokens_filter.NewStopTokensFilter(tokenMap), nil\n}"} {"input": "package limiter\n\nimport (\n\t\"math/rand\"\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n)\n\n\n\n\n\nfunc GetIPKey(r *http.Request, trustForwardHeader ...bool) string {\n\treturn GetIP(r, trustForwardHeader...).String()\n}\n\n\nfunc Random(min, max int) int {\n\trand.Seed(time.Now().Unix())\n\treturn rand.Intn(max-min) + min\n}\n\nfunc GetIP(r *http.Request, trustForwardHeader ...bool) net.IP ", "output": "{\n\tif len(trustForwardHeader) >= 1 && trustForwardHeader[0] {\n\t\tip := r.Header.Get(\"X-Forwarded-For\")\n\t\tif ip != \"\" {\n\t\t\tparts := strings.SplitN(ip, \",\", 2)\n\t\t\tpart := strings.TrimSpace(parts[0])\n\t\t\treturn net.ParseIP(part)\n\t\t}\n\n\t\tip = strings.TrimSpace(r.Header.Get(\"X-Real-IP\"))\n\t\tif ip != \"\" {\n\t\t\treturn net.ParseIP(ip)\n\t\t}\n\t}\n\n\tremoteAddr := strings.TrimSpace(r.RemoteAddr)\n\thost, _, err := net.SplitHostPort(remoteAddr)\n\tif err != nil {\n\t\treturn net.ParseIP(remoteAddr)\n\t}\n\n\treturn net.ParseIP(host)\n}"} {"input": "package discovery\n\nimport (\n\t\"encoding/hex\"\n\t\"sync\"\n\n\t\"github.com/hyperledger/fabric/common/util\"\n)\n\n\n\ntype MemoizeSigner struct {\n\tmaxEntries uint\n\tsync.RWMutex\n\tmemory map[string][]byte\n\tsign Signer\n}\n\n\n\nfunc NewMemoizeSigner(signFunc Signer, maxEntries uint) *MemoizeSigner {\n\treturn &MemoizeSigner{\n\t\tmaxEntries: maxEntries,\n\t\tmemory: make(map[string][]byte),\n\t\tsign: signFunc,\n\t}\n}\n\n\n\n\n\n\n\nfunc (ms *MemoizeSigner) lookup(msg []byte) ([]byte, bool) {\n\tms.RLock()\n\tdefer ms.RUnlock()\n\tsig, exists := ms.memory[msgDigest(msg)]\n\treturn sig, exists\n}\n\nfunc (ms *MemoizeSigner) memorize(msg, signature []byte) {\n\tif ms.maxEntries == 0 {\n\t\treturn\n\t}\n\tms.RLock()\n\tshouldShrink := len(ms.memory) >= (int)(ms.maxEntries)\n\tms.RUnlock()\n\n\tif shouldShrink {\n\t\tms.shrinkMemory()\n\t}\n\tms.Lock()\n\tdefer ms.Unlock()\n\tms.memory[msgDigest(msg)] = signature\n}\n\n\n\nfunc (ms *MemoizeSigner) shrinkMemory() {\n\tms.Lock()\n\tdefer ms.Unlock()\n\tfor len(ms.memory) > (int)(ms.maxEntries) {\n\t\tms.evictFromMemory()\n\t}\n}\n\n\nfunc (ms *MemoizeSigner) evictFromMemory() {\n\tfor dig := range ms.memory {\n\t\tdelete(ms.memory, dig)\n\t\treturn\n\t}\n}\n\n\nfunc msgDigest(msg []byte) string {\n\treturn hex.EncodeToString(util.ComputeSHA256(msg))\n}\n\nfunc (ms *MemoizeSigner) Sign(msg []byte) ([]byte, error) ", "output": "{\n\tsig, isInMemory := ms.lookup(msg)\n\tif isInMemory {\n\t\treturn sig, nil\n\t}\n\tsig, err := ms.sign(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tms.memorize(msg, sig)\n\treturn sig, nil\n}"} {"input": "package horizon\n\nimport (\n\t\"github.com/stellar/go-horizon/db\"\n)\n\nfunc initHistoryDb(app *App) {\n\thistoryDb, err := db.Open(app.config.DatabaseUrl)\n\n\tif err != nil {\n\t\tapp.log.Panic(app.ctx, err)\n\t}\n\tapp.historyDb = historyDb\n}\n\nfunc initCoreDb(app *App) {\n\tcoreDb, err := db.Open(app.config.StellarCoreDatabaseUrl)\n\n\tif err != nil {\n\t\tapp.log.Panic(app.ctx, err)\n\t}\n\tapp.coreDb = coreDb\n}\n\n\n\nfunc init() ", "output": "{\n\tappInit.Add(\"history-db\", initHistoryDb, \"app-context\", \"log\")\n\tappInit.Add(\"core-db\", initCoreDb, \"app-context\", \"log\")\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype DeleteVolumeBackupPolicyRequest struct {\n\n\tPolicyId *string `mandatory:\"true\" contributesTo:\"path\" name:\"policyId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteVolumeBackupPolicyRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteVolumeBackupPolicyRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request DeleteVolumeBackupPolicyRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteVolumeBackupPolicyResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteVolumeBackupPolicyResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response DeleteVolumeBackupPolicyResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package provider\n\nimport (\n\t\"strings\"\n)\n\n\ntype DomainFilter struct {\n\tfilters []string\n\texclude []string\n}\n\n\nfunc prepareFilters(filters []string) []string {\n\tfs := make([]string, len(filters))\n\tfor i, domain := range filters {\n\t\tfs[i] = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), \".\"))\n\t}\n\treturn fs\n}\n\n\nfunc NewDomainFilterWithExclusions(domainFilters []string, excludeDomains []string) DomainFilter {\n\treturn DomainFilter{prepareFilters(domainFilters), prepareFilters(excludeDomains)}\n}\n\n\nfunc NewDomainFilter(domainFilters []string) DomainFilter {\n\treturn DomainFilter{prepareFilters(domainFilters), []string{}}\n}\n\n\nfunc (df DomainFilter) Match(domain string) bool {\n\treturn matchFilter(df.filters, domain, true) && !matchFilter(df.exclude, domain, false)\n}\n\n\n\n\n\n\n\nfunc (df DomainFilter) IsConfigured() bool {\n\tif len(df.filters) == 1 {\n\t\treturn df.filters[0] != \"\"\n\t}\n\treturn len(df.filters) > 0\n}\n\nfunc matchFilter(filters []string, domain string, emptyval bool) bool ", "output": "{\n\tif len(filters) == 0 {\n\t\treturn emptyval\n\t}\n\n\tfor _, filter := range filters {\n\t\tstrippedDomain := strings.ToLower(strings.TrimSuffix(domain, \".\"))\n\n\t\tif filter == \"\" {\n\t\t\treturn emptyval\n\t\t} else if strings.HasPrefix(filter, \".\") && strings.HasSuffix(strippedDomain, filter) {\n\t\t\treturn true\n\t\t} else if strings.Count(strippedDomain, \".\") == strings.Count(filter, \".\") {\n\t\t\tif strippedDomain == filter {\n\t\t\t\treturn true\n\t\t\t}\n\t\t} else if strings.HasSuffix(strippedDomain, \".\"+filter) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package supernode\n\nimport (\n\t\"testing\"\n\n\tdhtpb \"gx/ipfs/QmRG9fdibExi5DFy8kzyxF76jvZVUb2mQBUSMNP1YaYn9M/go-libp2p-kad-dht/pb\"\n\tdatastore \"gx/ipfs/QmRWDav6mzWseLWeYfVd5fvUKiVe9xNH29YfMF438fG364/go-datastore\"\n)\n\nfunc TestPutProviderDoesntResultInDuplicates(t *testing.T) {\n\troutingBackend := datastore.NewMapDatastore()\n\tk := \"foo\"\n\tput := []*dhtpb.Message_Peer{\n\t\tconvPeer(\"bob\", \"127.0.0.1/tcp/4001\"),\n\t\tconvPeer(\"alice\", \"10.0.0.10/tcp/4001\"),\n\t}\n\tif err := putRoutingProviders(routingBackend, k, put); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := putRoutingProviders(routingBackend, k, put); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tgot, err := getRoutingProviders(routingBackend, k)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(got) != 2 {\n\t\tt.Fatal(\"should be 2 values, but there are\", len(got))\n\t}\n}\n\n\n\nfunc convPeer(name string, addrs ...string) *dhtpb.Message_Peer ", "output": "{\n\tvar rawAddrs [][]byte\n\tfor _, addr := range addrs {\n\t\trawAddrs = append(rawAddrs, []byte(addr))\n\t}\n\treturn &dhtpb.Message_Peer{Id: &name, Addrs: rawAddrs}\n}"} {"input": "package opentracing\n\nimport (\n\t\"strconv\"\n)\n\n\n\nfunc atouint16(s string) uint16 ", "output": "{\n\tv, _ := strconv.ParseUint(s, 10, 16)\n\treturn uint16(v)\n}"} {"input": "package in\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/blevesearch/bleve/analysis\"\n\t\"github.com/blevesearch/bleve/registry\"\n)\n\nconst NormalizeName = \"normalize_in\"\n\ntype IndicNormalizeFilter struct {\n}\n\nfunc NewIndicNormalizeFilter() *IndicNormalizeFilter {\n\treturn &IndicNormalizeFilter{}\n}\n\n\n\nfunc NormalizerFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) {\n\treturn NewIndicNormalizeFilter(), nil\n}\n\nfunc init() {\n\tregistry.RegisterTokenFilter(NormalizeName, NormalizerFilterConstructor)\n}\n\nfunc (s *IndicNormalizeFilter) Filter(input analysis.TokenStream) analysis.TokenStream ", "output": "{\n\tfor _, token := range input {\n\t\trunes := bytes.Runes(token.Term)\n\t\trunes = normalize(runes)\n\t\ttoken.Term = analysis.BuildTermFromRunes(runes)\n\t}\n\treturn input\n}"} {"input": "package github\n\nimport \"fmt\"\n\n\ntype Key struct {\n\tID *int `json:\"id,omitempty\"`\n\tKey *string `json:\"key,omitempty\"`\n\tURL *string `json:\"url,omitempty\"`\n\tTitle *string `json:\"title,omitempty\"`\n}\n\nfunc (k Key) String() string {\n\treturn Stringify(k)\n}\n\n\n\n\n\n\n\n\n\n\nfunc (s *UsersService) GetKey(id int) (*Key, *Response, error) {\n\tu := fmt.Sprintf(\"user/keys/%v\", id)\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tkey := new(Key)\n\tresp, err := s.client.Do(req, key)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn key, resp, err\n}\n\n\n\n\nfunc (s *UsersService) CreateKey(key *Key) (*Key, *Response, error) {\n\tu := \"user/keys\"\n\n\treq, err := s.client.NewRequest(\"POST\", u, key)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tk := new(Key)\n\tresp, err := s.client.Do(req, k)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn k, resp, err\n}\n\n\n\n\nfunc (s *UsersService) DeleteKey(id int) (*Response, error) {\n\tu := fmt.Sprintf(\"user/keys/%v\", id)\n\n\treq, err := s.client.NewRequest(\"DELETE\", u, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.client.Do(req, nil)\n}\n\nfunc (s *UsersService) ListKeys(user string, opt *ListOptions) ([]*Key, *Response, error) ", "output": "{\n\tvar u string\n\tif user != \"\" {\n\t\tu = fmt.Sprintf(\"users/%v/keys\", user)\n\t} else {\n\t\tu = \"user/keys\"\n\t}\n\tu, err := addOptions(u, opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tkeys := new([]*Key)\n\tresp, err := s.client.Do(req, keys)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn *keys, resp, err\n}"} {"input": "package user\n\nimport (\n\t\"log\"\n\n\t\"github.com/astaxie/beego/validation\"\n\n\t\"github.com/codeshredder/infoboard/models\"\n)\n\n\ntype RegisterForm struct {\n\tUserName string `valid:\"Required;MinSize(5);MaxSize(30)\"`\n\tEmail string `valid:\"Required;Email;MaxSize(80)\"`\n\tPassword string `valid:\"Required;MinSize(4);MaxSize(30)\"`\n\tPasswordRe string `valid:\"Required;MinSize(4);MaxSize(30)\"`\n}\n\n\n\n\ntype LoginForm struct {\n\tUserName string `valid:\"Required; MaxSize(80)`\n\tPassword string `valid:\"Required; MinSize(4);MaxSize(30)\"`\n\tRemember bool\n}\n\nfunc (form *LoginForm) Valid(v *validation.Validation) {\n\n}\n\nfunc (form *RegisterForm) Valid(v *validation.Validation) ", "output": "{\n\n\tlog.Println(\"Valid RegisterForm\")\n\n\tif form.Password != form.PasswordRe {\n\t\tv.SetError(\"PasswordRe\", \"repassword_not_match\")\n\t\treturn\n\t}\n\n\te1, e2, _ := models.CanRegistered(form.UserName, form.Email)\n\tif !e1 {\n\t\tv.SetError(\"UserName\", \"username_already_taken\")\n\t}\n\n\tif !e2 {\n\t\tv.SetError(\"Email\", \"email_already_taken\")\n\t}\n\n}"} {"input": "package permute\n\nimport \"testing\"\n\n\n\nfunc BenchmarkPermGenSJT(b *testing.B) {\n\th := NewPlainChangeGen(20)\n\tvar sw [2]int\n\tfor i := 0; i < b.N; i++ {\n\t\th.Next(&sw)\n\t}\n}\n\nfunc BenchmarkPermGenHeap(b *testing.B) {\n\th := NewHeap(20)\n\tvar sw [2]int\n\tfor i := 0; i < b.N; i++ {\n\t\th.Next(&sw)\n\t}\n}\nfunc BenchmarkPermGenEven(b *testing.B) {\n\th := NewPlainChangeFastGen(20)\n\tvar sw [2]int\n\tfor i := 0; i < b.N; i++ {\n\t\th.Next(&sw)\n\t}\n}\n\nfunc BenchmarkPermGenLex(b *testing.B) ", "output": "{\n\tp := New(20)\n\tfor i := 0; i < b.N; i++ {\n\t\tLexNext(p)\n\t}\n}"} {"input": "package rate\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestRateLimiter_Wait_noblock(t *testing.T) {\n\tstart := time.Now()\n\tlimit := 5\n\tinterval := time.Second * 3\n\tlimiter := New(limit, interval)\n\tfor i := 0; i < limit; i++ {\n\t\tlimiter.Wait()\n\t}\n\tif time.Now().Sub(start) >= interval {\n\t\tt.Error(\"The limiter blocked when it shouldn't have\")\n\t}\n}\n\nfunc TestRateLimiter_Wait_block(t *testing.T) {\n\tstart := time.Now()\n\tlimit := 5\n\tinterval := time.Second * 3\n\tlimiter := New(limit, interval)\n\tfor i := 0; i < limit+1; i++ {\n\t\tlimiter.Wait()\n\t}\n\tif time.Now().Sub(start) < interval {\n\t\tt.Error(\"The limiter didn't block when it should have\")\n\t}\n}\n\n\n\nfunc TestRateLimiter_Try(t *testing.T) ", "output": "{\n\tlimit := 5\n\tinterval := time.Second * 3\n\tlimiter := New(limit, interval)\n\tfor i := 0; i < limit; i++ {\n\t\tif ok, _ := limiter.Try(); !ok {\n\t\t\tt.Fatalf(\"Should have allowed try on attempt %d\", i)\n\t\t}\n\t}\n\tif ok, _ := limiter.Try(); ok {\n\t\tt.Fatal(\"Should have not allowed try on final attempt\")\n\t}\n}"} {"input": "package utils\n\nimport (\n\t. \"github.com/FoxComm/vulcand/Godeps/_workspace/src/gopkg.in/check.v1\"\n)\n\ntype AuthSuite struct {\n}\n\nvar _ = Suite(&AuthSuite{})\n\n\n\n\n\n\n\nfunc (s *AuthSuite) TestParseSuccess(c *C) {\n\theaders := []struct {\n\t\tHeader string\n\t\tExpected BasicAuth\n\t}{\n\t\t{\n\t\t\t\"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\",\n\t\t\tBasicAuth{Username: \"Aladdin\", Password: \"open sesame\"},\n\t\t},\n\t\t{\n\t\t\t(&BasicAuth{Username: \"Alice\", Password: \"Here's bob\"}).String(),\n\t\t\tBasicAuth{Username: \"Alice\", Password: \"Here's bob\"},\n\t\t},\n\t\t{\n\t\t\t\"Basic QWxhZGRpbjo=\",\n\t\t\tBasicAuth{Username: \"Aladdin\", Password: \"\"},\n\t\t},\n\t}\n\tfor _, h := range headers {\n\t\trequest, err := ParseAuthHeader(h.Header)\n\t\tc.Assert(err, IsNil)\n\t\tc.Assert(request.Username, Equals, h.Expected.Username)\n\t\tc.Assert(request.Password, Equals, h.Expected.Password)\n\n\t}\n}\n\nfunc (s *AuthSuite) TestParseBadHeaders(c *C) ", "output": "{\n\theaders := []string{\n\t\t\"\",\n\t\t\"justplainstring\",\n\t\t\"Whut justplainstring\",\n\t\t\"Basic Shmasic\",\n\t\t\"Basic YW55IGNhcm5hbCBwbGVhcw==\",\n\t}\n\tfor _, h := range headers {\n\t\t_, err := ParseAuthHeader(h)\n\t\tc.Assert(err, NotNil)\n\t}\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/apier/v1\"\n\t\"github.com/cgrates/cgrates/engine\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdGetDataCost{\n\t\tname: \"datacost\",\n\t\trpcMethod: \"ApierV1.GetDataCost\",\n\t\tclientArgs: []string{\"Direction\", \"Category\", \"Tenant\", \"Account\", \"Subject\", \"StartTime\", \"Usage\"},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetDataCost struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrGetDataCost\n\tclientArgs []string\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetDataCost) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdGetDataCost) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdGetDataCost) RpcParams() interface{} {\n\tif self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrGetDataCost{Direction: utils.OUT}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetDataCost) PostprocessRpcParams() error {\n\treturn nil\n}\n\n\n\nfunc (self *CmdGetDataCost) ClientArgs() []string {\n\treturn self.clientArgs\n}\n\nfunc (self *CmdGetDataCost) RpcResult() interface{} ", "output": "{\n\treturn &engine.DataCost{}\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\tmessage := Message{\n\t\tText: os.Args[2],\n\t\tDuration: 15,\n\t}\n\tSendMessage(message, os.Args[1])\n\n}\n\n\n\nfunc failOnError(err error, msg string) {\n\tif err != nil {\n\t\tlog.Fatalf(\"%s: %s\", msg, err)\n\t\tpanic(fmt.Sprintf(\"%s: %s\", msg, err))\n\t}\n}\n\ntype Message struct {\n\tText string `json:\"text\"`\n\tDuration float64 `json:\"duration\"`\n}\n\nfunc SendMessage(message Message, URL string) ", "output": "{\n\tb := new(bytes.Buffer)\n\tjson.NewEncoder(b).Encode(message)\n\tresp, err := http.Post(URL, \"application/json\", b)\n\tfailOnError(err, \"Could not send http request.\")\n\tio.Copy(os.Stdout, resp.Body)\n}"} {"input": "package process\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/weaveworks/scope/probe/tag\"\n\t\"github.com/weaveworks/scope/report\"\n)\n\n\nconst (\n\tPID = \"pid\"\n\tComm = \"comm\"\n\tPPID = \"ppid\"\n\tCmdline = \"cmdline\"\n\tThreads = \"threads\"\n)\n\n\ntype reporter struct {\n\tprocRoot string\n\tscope string\n}\n\n\n\n\n\nfunc (r *reporter) Report() (report.Report, error) {\n\tresult := report.MakeReport()\n\tprocesses, err := r.processTopology()\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tresult.Process.Merge(processes)\n\treturn result, nil\n}\n\nfunc (r *reporter) processTopology() (report.Topology, error) {\n\tt := report.NewTopology()\n\terr := Walk(r.procRoot, func(p *Process) {\n\t\tpidstr := strconv.Itoa(p.PID)\n\t\tnodeID := report.MakeProcessNodeID(r.scope, pidstr)\n\t\tt.NodeMetadatas[nodeID] = report.NodeMetadata{\n\t\t\tPID: pidstr,\n\t\t\tComm: p.Comm,\n\t\t\tCmdline: p.Cmdline,\n\t\t\tThreads: strconv.Itoa(p.Threads),\n\t\t}\n\t\tif p.PPID > 0 {\n\t\t\tt.NodeMetadatas[nodeID][PPID] = strconv.Itoa(p.PPID)\n\t\t}\n\t})\n\n\treturn t, err\n}\n\nfunc NewReporter(procRoot, scope string) tag.Reporter ", "output": "{\n\treturn &reporter{\n\t\tprocRoot: procRoot,\n\t\tscope: scope,\n\t}\n}"} {"input": "package libvirtxml\n\ntype StorageVolumeTargetFormat struct {\n\tnode *Node\n}\n\nfunc newStorageVolumeTargetFormat(node *Node) StorageVolumeTargetFormat {\n\treturn StorageVolumeTargetFormat{\n\t\tnode: node,\n\t}\n}\n\nfunc (s StorageVolumeTargetFormat) Type() string {\n\treturn s.node.getAttribute(nameForLocal(\"type\"))\n}\n\n\n\nfunc (s StorageVolumeTargetFormat) SetType(value string) ", "output": "{\n\ts.node.setAttribute(nameForLocal(\"type\"), value)\n}"} {"input": "package cmd\n\nimport (\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n\n\tboshdir \"github.com/cloudfoundry/bosh-init/director\"\n\tboshtpl \"github.com/cloudfoundry/bosh-init/director/template\"\n\tboshui \"github.com/cloudfoundry/bosh-init/ui\"\n)\n\ntype UpdateRuntimeConfigCmd struct {\n\tui boshui.UI\n\tdirector boshdir.Director\n}\n\n\n\nfunc (c UpdateRuntimeConfigCmd) Run(opts UpdateRuntimeConfigOpts) error {\n\ttpl := boshtpl.NewTemplate(opts.Args.RuntimeConfig.Bytes)\n\n\tbytes, err := tpl.Evaluate(opts.VarFlags.AsVariables())\n\tif err != nil {\n\t\treturn bosherr.WrapErrorf(err, \"Evaluating runtime config\")\n\t}\n\n\terr = c.ui.AskForConfirmation()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.director.UpdateRuntimeConfig(bytes)\n}\n\nfunc NewUpdateRuntimeConfigCmd(ui boshui.UI, director boshdir.Director) UpdateRuntimeConfigCmd ", "output": "{\n\treturn UpdateRuntimeConfigCmd{ui: ui, director: director}\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/ParsePlatform/parse-cli/parsecli\"\n\t\"github.com/facebookgo/stackerr\"\n)\n\n\n\nfunc validateURL(urlStr string) error {\n\tnetURL, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn stackerr.Wrap(err)\n\t}\n\n\tif netURL.Scheme != \"https\" {\n\t\treturn errors.New(\"Please enter a valid https url\")\n\t}\n\treturn nil\n}\n\nfunc getConfirmation(message string, e *parsecli.Env) bool ", "output": "{\n\tfmt.Fprintf(e.Out, message)\n\tvar confirm string\n\tfmt.Fscanf(e.In, \"%s\\n\", &confirm)\n\tlower := strings.ToLower(confirm)\n\treturn lower != \"\" && strings.HasPrefix(lower, \"y\")\n}"} {"input": "package internal\n\nimport (\n\t\"encoding/json\"\n)\n\ntype User struct {\n\tGlobalKey string `json:\"global_key\"`\n\tEmail string `json:\"email\"`\n\tAvatar string `json:\"avatar\"`\n}\n\n\n\nfunc (c *Client) GetCurrentUser() (*User, error) ", "output": "{\n\tu := \"/account/current_user\"\n\tresp, err := c.Get(u, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuser := &User{}\n\terr = json.Unmarshal(resp, user)\n\tif err != nil {\n\t\treturn nil, APIClientErr{\"fail to parse current user data\", u, err}\n\t}\n\treturn user, nil\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\n\n\n\ntype MsgPong struct {\n\tNonce uint64\n}\n\n\n\nfunc (msg *MsgPong) BtcDecode(r io.Reader, pver uint32) error {\n\tif pver <= BIP0031Version {\n\t\tstr := fmt.Sprintf(\"pong message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgPong.BtcDecode\", str)\n\t}\n\n\treturn readElement(r, &msg.Nonce)\n}\n\n\n\nfunc (msg *MsgPong) BtcEncode(w io.Writer, pver uint32) error {\n\tif pver <= BIP0031Version {\n\t\tstr := fmt.Sprintf(\"pong message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgPong.BtcEncode\", str)\n\t}\n\n\treturn writeElement(w, msg.Nonce)\n}\n\n\n\nfunc (msg *MsgPong) Command() string {\n\treturn CmdPong\n}\n\n\n\n\n\n\n\nfunc NewMsgPong(nonce uint64) *MsgPong {\n\treturn &MsgPong{\n\t\tNonce: nonce,\n\t}\n}\n\nfunc (msg *MsgPong) MaxPayloadLength(pver uint32) uint32 ", "output": "{\n\tplen := uint32(0)\n\tif pver > BIP0031Version {\n\t\tplen += 8\n\t}\n\n\treturn plen\n}"} {"input": "package cabf_br\n\n\n\nimport (\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/util\"\n)\n\ntype SANEDI struct{}\n\n\n\nfunc init() {\n\tlint.RegisterLint(&lint.Lint{\n\t\tName: \"e_ext_san_edi_party_name_present\",\n\t\tDescription: \"The Subject Alternate Name extension MUST contain only 'dnsName' and 'ipaddress' name types\",\n\t\tCitation: \"BRs: 7.1.4.2.1\",\n\t\tSource: lint.CABFBaselineRequirements,\n\t\tEffectiveDate: util.CABEffectiveDate,\n\t\tLint: &SANEDI{},\n\t})\n}\n\nfunc (l *SANEDI) Initialize() error {\n\treturn nil\n}\n\n\n\nfunc (l *SANEDI) Execute(c *x509.Certificate) *lint.LintResult {\n\tif c.EDIPartyNames != nil {\n\t\treturn &lint.LintResult{Status: lint.Error}\n\t}\n\treturn &lint.LintResult{Status: lint.Pass}\n}\n\nfunc (l *SANEDI) CheckApplies(c *x509.Certificate) bool ", "output": "{\n\treturn util.IsExtInCert(c, util.SubjectAlternateNameOID)\n}"} {"input": "package virtualbox\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n)\n\n\n\nfunc MakeDiskImage(dest string, size uint, r io.Reader) error {\n\tsizeBytes := int64(size) << 20 \n\tcmd := exec.Command(cfg.VBM, \"convertfromraw\", \"stdin\", dest,\n\t\tfmt.Sprintf(\"%d\", sizeBytes), \"--format\", \"VMDK\")\n\n\tif verbose {\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t}\n\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\n\tn, err := io.Copy(stdin, r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif left := sizeBytes - n; left > 0 {\n\t\tif err := ZeroFill(stdin, left); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := stdin.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn cmd.Wait()\n}\n\n\n\n\nfunc ZeroFill(w io.Writer, n int64) error ", "output": "{\n\tconst blocksize = 32 << 10\n\tzeros := make([]byte, blocksize)\n\tvar k int\n\tvar err error\n\tfor n > 0 {\n\t\tif n > blocksize {\n\t\t\tk, err = w.Write(zeros)\n\t\t} else {\n\t\t\tk, err = w.Write(zeros[:n])\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn -= int64(k)\n\t}\n\treturn nil\n}"} {"input": "package cobra\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\nfunc TestCompleteNoDesCmdInFishScript(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse: \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun: emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, false))\n\toutput := buf.String()\n\n\tcheck(t, output, ShellCompNoDescRequestCmd)\n}\n\nfunc TestCompleteCmdInFishScript(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse: \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun: emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, true))\n\toutput := buf.String()\n\n\tcheck(t, output, ShellCompRequestCmd)\n\tcheckOmit(t, output, ShellCompNoDescRequestCmd)\n}\n\nfunc TestProgWithDash(t *testing.T) {\n\trootCmd := &Command{Use: \"root-dash\", Args: NoArgs, Run: emptyRun}\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, false))\n\toutput := buf.String()\n\n\tcheck(t, output, \"__root_dash_perform_completion\")\n\tcheckOmit(t, output, \"__root-dash_perform_completion\")\n\n\tcheck(t, output, \"-c root-dash\")\n\tcheckOmit(t, output, \"-c root_dash\")\n}\n\n\n\nfunc TestProgWithColon(t *testing.T) ", "output": "{\n\trootCmd := &Command{Use: \"root:colon\", Args: NoArgs, Run: emptyRun}\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, false))\n\toutput := buf.String()\n\n\tcheck(t, output, \"__root_colon_perform_completion\")\n\tcheckOmit(t, output, \"__root:colon_perform_completion\")\n\n\tcheck(t, output, \"-c root:colon\")\n\tcheckOmit(t, output, \"-c root_colon\")\n}"} {"input": "package scene\n\nimport \"github.com/thinkofdeath/steven/ui\"\n\n\ntype Type struct {\n\tvisible bool\n\n\tdrawables []ui.Drawable\n\thidding bool\n}\n\n\nfunc New(visible bool) *Type {\n\treturn &Type{\n\t\tvisible: visible,\n\t}\n}\n\n\nfunc (t *Type) Show() {\n\tif t.visible {\n\t\treturn\n\t}\n\tt.visible = true\n\tfor _, d := range t.drawables {\n\t\tui.AddDrawable(d)\n\t}\n}\n\n\nfunc (t *Type) Hide() {\n\tif !t.visible {\n\t\treturn\n\t}\n\tt.visible = false\n\tt.hidding = true\n\tfor _, d := range t.drawables {\n\t\tui.Remove(d)\n\t}\n\tt.hidding = false\n}\n\n\nfunc (t *Type) AddDrawable(d ui.Drawable) {\n\tt.drawables = append(t.drawables, d)\n\tif t.visible {\n\t\tui.AddDrawable(d)\n\t}\n\td.SetRemoveHook(t.removeHook)\n}\n\nfunc (t *Type) removeHook(d ui.Drawable) {\n\tif t.hidding {\n\t\treturn\n\t}\n\tfor i, dd := range t.drawables {\n\t\tif dd == d {\n\t\t\tt.drawables = append(t.drawables[:i], t.drawables[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n\n}\n\n\n\n\nfunc (t *Type) IsVisible() bool ", "output": "{\n\treturn t.visible\n}"} {"input": "package kms\n\nimport (\n\t\"os\"\n\n\t\"github.com/denverdino/aliyungo/common\"\n)\n\nconst (\n\tKMSDefaultEndpoint = \"https://kms.cn-hangzhou.aliyuncs.com\"\n\tKMSAPIVersion = \"2016-01-20\"\n\tKMSServiceCode = \"kms\"\n)\n\ntype Client struct {\n\tcommon.Client\n}\n\n\nfunc NewClient(accessKeyId, accessKeySecret string) *Client {\n\tendpoint := os.Getenv(\"KMS_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = KMSDefaultEndpoint\n\t}\n\treturn NewClientWithEndpoint(endpoint, accessKeyId, accessKeySecret)\n}\n\n\n\nfunc NewClientWithEndpoint(endpoint string, accessKeyId string, accessKeySecret string) *Client {\n\tclient := &Client{}\n\tclient.Init(endpoint, KMSAPIVersion, accessKeyId, accessKeySecret)\n\treturn client\n}\n\nfunc NewECSClientWithSecurityToken(accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client {\n\tendpoint := os.Getenv(\"KMS_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = KMSDefaultEndpoint\n\t}\n\n\treturn NewKMSClientWithEndpointAndSecurityToken(endpoint, accessKeyId, accessKeySecret, securityToken, regionID)\n}\n\nfunc NewKMSClientWithEndpointAndSecurityToken(endpoint string, accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client {\n\tclient := &Client{}\n\tclient.WithEndpoint(endpoint).\n\t\tWithVersion(KMSAPIVersion).\n\t\tWithAccessKeyId(accessKeyId).\n\t\tWithAccessKeySecret(accessKeySecret).\n\t\tWithSecurityToken(securityToken).\n\t\tWithServiceCode(KMSServiceCode).\n\t\tWithRegionID(regionID).\n\t\tInitClient()\n\treturn client\n}\n\nfunc NewClientWithRegion(accessKeyId string, accessKeySecret string, regionID common.Region) *Client ", "output": "{\n\tendpoint := os.Getenv(\"KMS_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = KMSDefaultEndpoint\n\t}\n\tclient := &Client{}\n\tclient.NewInit(endpoint, KMSAPIVersion, accessKeyId, accessKeySecret, KMSServiceCode, regionID)\n\treturn client\n}"} {"input": "package fs\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n)\n\n\ntype VolumeDevSpec struct {\n\tUnit string\n\tControllerPciSlotNumber string\n}\n\n\nfunc Mkdir(path string) error {\n\tstat, err := os.Lstat(path)\n\tif os.IsNotExist(err) {\n\t\tlog.WithField(\"path\", path).Info(\"Directory doesn't exist, creating it \")\n\t\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\t\tlog.WithFields(log.Fields{\"path\": path,\n\t\t\t\t\"err\": err}).Error(\"Failed to create directory \")\n\t\t\treturn err\n\t\t}\n\t} else if err != nil {\n\t\tlog.WithFields(log.Fields{\"path\": path,\n\t\t\t\"err\": err}).Error(\"Failed to test directory existence \")\n\t\treturn err\n\t}\n\n\tif stat != nil && !stat.IsDir() {\n\t\tmsg := fmt.Sprintf(\"%v already exists and it's not a directory\", path)\n\t\tlog.Error(msg)\n\t\treturn fmt.Errorf(msg)\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc GetMountRootEntries(mountRoot string) ([]string, error) {\n\tvar vols []string\n\tvolumes, err := ioutil.ReadDir(mountRoot)\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to read entries from %s (%v)\", mountRoot, err)\n\t\treturn vols, err\n\t}\n\n\tfor _, vol := range volumes {\n\t\tvols = append(vols, vol.Name())\n\t}\n\treturn vols, nil\n}\n\nfunc Rmdir(path string) error ", "output": "{\n\treturn os.Remove(path)\n}"} {"input": "package cli\n\n\ntype Command struct {\n\tName string\n\tDescription string\n\tAction Action\n}\n\n\ntype Commands []*Command\n\n\nfunc (c Commands) Len() int {\n\treturn len(c)\n}\n\n\nfunc (c Commands) Less(i, j int) bool {\n\treturn c[i].Name < c[j].Name\n}\n\n\n\n\nfunc (c Commands) ActionForName(name string) Action {\n\tfor _, command := range c {\n\t\tif name == command.Name {\n\t\t\treturn command.Action\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c Commands) Swap(i, j int) ", "output": "{\n\tc[i], c[j] = c[j], c[i]\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/spf13/pflag\"\n\t\"k8s.io/apiserver/pkg/server/healthz\"\n\t\"k8s.io/kubernetes/federation/cmd/federation-controller-manager/app\"\n\t\"k8s.io/kubernetes/federation/cmd/federation-controller-manager/app/options\"\n\t\"k8s.io/kubernetes/pkg/util/flag\"\n\t\"k8s.io/kubernetes/pkg/util/logs\"\n\t_ \"k8s.io/kubernetes/pkg/util/workqueue/prometheus\" \n\t\"k8s.io/kubernetes/pkg/version/verflag\"\n)\n\n\n\nfunc main() {\n\ts := options.NewCMServer()\n\ts.AddFlags(pflag.CommandLine)\n\n\tflag.InitFlags()\n\tlogs.InitLogs()\n\tdefer logs.FlushLogs()\n\n\tverflag.PrintAndExitIfRequested()\n\n\tif err := app.Run(s); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc init() ", "output": "{\n\thealthz.DefaultHealthz()\n}"} {"input": "package haki\n\nimport (\n\t\"errors\"\n\t\"github.com/rjansen/l\"\n\t\"github.com/rjansen/l/zap\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\nfunc init() {\n\tif setupErr := zap.Setup(new(l.Configuration)); setupErr != nil {\n\t\tpanic(setupErr)\n\t}\n\tl.Info(\"context_test.init\")\n}\n\nfunc TestSetupAll(t *testing.T) {\n\terrs := SetupAll(\n\t\tfunc() error { return nil },\n\t\tfunc() error { return nil },\n\t\tfunc() error { return nil },\n\t\tfunc() error { return nil },\n\t)\n\n\tassert.Nil(t, errs)\n\tassert.Empty(t, errs)\n}\n\n\n\nfunc TestSetup(t *testing.T) {\n\terrs := Setup(\n\t\tfunc() error { return nil },\n\t\tfunc() error { return nil },\n\t\tfunc() error { return nil },\n\t\tfunc() error { return nil },\n\t)\n\n\tassert.Nil(t, errs)\n\tassert.Empty(t, errs)\n}\n\nfunc TestSetupErr(t *testing.T) {\n\tfirstErrMsg := \"context_test.TestSetupErrMock1\"\n\tvar err error\n\tassert.NotPanics(t, func() {\n\t\terr = Setup(\n\t\t\tfunc() error { return errors.New(firstErrMsg) },\n\t\t\tfunc() error { return errors.New(\"context_test.TestSetupErrMock2\") },\n\t\t\tfunc() error { return errors.New(\"context_test.TestSetupErrMock3\") },\n\t\t\tfunc() error { return errors.New(\"context_test.TestSetupErrMock4\") },\n\t\t)\n\t})\n\n\tassert.NotNil(t, err)\n\tassert.Equal(t, firstErrMsg, err.Error())\n}\n\nfunc TestSetupAllErr(t *testing.T) ", "output": "{\n\tvar errs []error\n\tassert.NotPanics(t, func() {\n\t\terrs = SetupAll(\n\t\t\tfunc() error { return errors.New(\"context_test.TestSetupErrMock1\") },\n\t\t\tfunc() error { return errors.New(\"context_test.TestSetupErrMock2\") },\n\t\t\tfunc() error { return errors.New(\"context_test.TestSetupErrMock3\") },\n\t\t\tfunc() error { return errors.New(\"context_test.TestSetupErrMock4\") },\n\t\t)\n\t})\n\n\tassert.NotNil(t, errs)\n\tassert.NotEmpty(t, errs)\n\tassert.Equal(t, 4, len(errs))\n}"} {"input": "package fibonacci_test\n\nimport \"github.com/yon/go-fibonacci\"\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc Example() ", "output": "{\n\tfmt.Printf(\"fibonacci.Iterative(11) == %v\\n\", fibonacci.Iterative(11))\n\n\tfmt.Printf(\"fibonacci.Recursive(11) == %v\\n\", fibonacci.Recursive(11))\n\n\tfmt.Printf(\"fibonacci.TailRecursive(11) == %v\\n\", fibonacci.TailRecursive(11))\n\n}"} {"input": "package stmts_test\n\nimport (\n\t. \"github.com/pingcap/check\"\n\t\"github.com/pingcap/tidb\"\n\t\"github.com/pingcap/tidb/stmt/stmts\"\n)\n\nfunc (s *testStmtSuite) TestDropDatabase(c *C) {\n\ttestSQL := \"drop database if exists drop_test;\"\n\n\tstmtList, err := tidb.Compile(s.ctx, testSQL)\n\tc.Assert(err, IsNil)\n\tc.Assert(stmtList, HasLen, 1)\n\n\ttestStmt, ok := stmtList[0].(*stmts.DropDatabaseStmt)\n\tc.Assert(ok, IsTrue)\n\n\tc.Assert(testStmt.IsDDL(), IsTrue)\n\tc.Assert(len(testStmt.OriginText()), Greater, 0)\n\n\tmf := newMockFormatter()\n\ttestStmt.Explain(nil, mf)\n\tc.Assert(mf.Len(), Greater, 0)\n\n\tmustExec(c, s.testDB, testSQL)\n}\n\n\n\nfunc (s *testStmtSuite) TestDropIndex(c *C) {\n\ttestSQL := \"drop index if exists drop_index on t;\"\n\n\tstmtList, err := tidb.Compile(s.ctx, testSQL)\n\tc.Assert(err, IsNil)\n\tc.Assert(stmtList, HasLen, 1)\n\n\ttestStmt, ok := stmtList[0].(*stmts.DropIndexStmt)\n\tc.Assert(ok, IsTrue)\n\n\tc.Assert(testStmt.IsDDL(), IsTrue)\n\tc.Assert(len(testStmt.OriginText()), Greater, 0)\n\n\tmf := newMockFormatter()\n\ttestStmt.Explain(nil, mf)\n\tc.Assert(mf.Len(), Greater, 0)\n\n\tmustExec(c, s.testDB, testSQL)\n}\n\nfunc (s *testStmtSuite) TestDropTable(c *C) ", "output": "{\n\ttestSQL := \"drop table if exists drop_table;\"\n\n\tstmtList, err := tidb.Compile(s.ctx, testSQL)\n\tc.Assert(err, IsNil)\n\tc.Assert(stmtList, HasLen, 1)\n\n\ttestStmt, ok := stmtList[0].(*stmts.DropTableStmt)\n\tc.Assert(ok, IsTrue)\n\n\tc.Assert(testStmt.IsDDL(), IsTrue)\n\tc.Assert(len(testStmt.OriginText()), Greater, 0)\n\n\tmf := newMockFormatter()\n\ttestStmt.Explain(nil, mf)\n\tc.Assert(mf.Len(), Greater, 0)\n\n\tmustExec(c, s.testDB, testSQL)\n\tmustExec(c, s.testDB, \"create table if not exists t (c int)\")\n\tmustExec(c, s.testDB, \"drop table t\")\n}"} {"input": "package rsets\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/pingcap/tidb/context\"\n\t\"github.com/pingcap/tidb/plan\"\n\t\"github.com/pingcap/tidb/plan/plans\"\n)\n\nvar (\n\t_ plan.Planner = (*LimitRset)(nil)\n\t_ plan.Planner = (*OffsetRset)(nil)\n)\n\n\ntype OffsetRset struct {\n\tCount uint64\n\tSrc plan.Plan\n}\n\n\nfunc (r *OffsetRset) Plan(ctx context.Context) (plan.Plan, error) {\n\treturn &plans.OffsetDefaultPlan{Count: r.Count, Src: r.Src, Fields: r.Src.GetFields()}, nil\n}\n\nfunc (r *OffsetRset) String() string {\n\treturn fmt.Sprintf(\" OFFSET %d\", r.Count)\n}\n\n\ntype LimitRset struct {\n\tCount uint64\n\tSrc plan.Plan\n}\n\n\nfunc (r *LimitRset) Plan(ctx context.Context) (plan.Plan, error) {\n\treturn &plans.LimitDefaultPlan{Count: r.Count, Src: r.Src, Fields: r.Src.GetFields()}, nil\n}\n\n\n\nfunc (r *LimitRset) String() string ", "output": "{\n\treturn fmt.Sprintf(\" LIMIT %d\", r.Count)\n}"} {"input": "package migration\n\nimport \"time\"\n\n\ntype IssueContext interface {\n\tLocalID() int64\n\tForeignID() int64\n}\n\n\ntype BasicIssueContext int64\n\n\nfunc (c BasicIssueContext) LocalID() int64 {\n\treturn int64(c)\n}\n\n\nfunc (c BasicIssueContext) ForeignID() int64 {\n\treturn int64(c)\n}\n\n\ntype Issue struct {\n\tNumber int64 `json:\"number\"`\n\tPosterID int64 `yaml:\"poster_id\" json:\"poster_id\"`\n\tPosterName string `yaml:\"poster_name\" json:\"poster_name\"`\n\tPosterEmail string `yaml:\"poster_email\" json:\"poster_email\"`\n\tTitle string `json:\"title\"`\n\tContent string `json:\"content\"`\n\tRef string `json:\"ref\"`\n\tMilestone string `json:\"milestone\"`\n\tState string `json:\"state\"` \n\tIsLocked bool `yaml:\"is_locked\" json:\"is_locked\"`\n\tCreated time.Time `json:\"created\"`\n\tUpdated time.Time `json:\"updated\"`\n\tClosed *time.Time `json:\"closed\"`\n\tLabels []*Label `json:\"labels\"`\n\tReactions []*Reaction `json:\"reactions\"`\n\tAssignees []string `json:\"assignees\"`\n\tContext IssueContext `yaml:\"-\"`\n}\n\n\nfunc (i *Issue) GetExternalName() string { return i.PosterName }\n\n\n\n\nfunc (i *Issue) GetExternalID() int64 ", "output": "{ return i.PosterID }"} {"input": "package time\n\nimport (\n\t\"time\"\n)\n\nconst (\n\tDateTimeLayout = \"2006-01-02 15:04:05\"\n)\n\n\nfunc DateTimeFormat(t time.Time) string {\n\treturn t.Format(DateTimeLayout)\n}\n\n\nfunc ParseDateTimeFormat(v string) (time.Time, error) {\n\treturn time.Parse(DateTimeLayout, v)\n}\n\n\n\n\nfunc MustParseDateTimeFormat(v string) time.Time ", "output": "{\n\tt, _ := ParseDateTimeFormat(v)\n\treturn t\n}"} {"input": "package domain\n\n\n\n\n\nfunc AndPayMethod(payFlag int, method int) bool {\n\tf := 1 << uint(method-1)\n\treturn payFlag&f == f\n}\n\nfunc MathPaymentMethodFlag(methods []int) int ", "output": "{\n\tf := 0\n\tfor _, v := range methods {\n\t\tf |= 1 << uint(v-1)\n\t}\n\treturn f\n}"} {"input": "package dhcpv6\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/u-root/uio/uio\"\n)\n\n\nfunc OptRelayPort(port uint16) Option {\n\treturn &optRelayPort{DownstreamSourcePort: port}\n}\n\ntype optRelayPort struct {\n\tDownstreamSourcePort uint16\n}\n\nfunc (op *optRelayPort) Code() OptionCode {\n\treturn OptionRelayPort\n}\n\nfunc (op *optRelayPort) ToBytes() []byte {\n\tbuf := uio.NewBigEndianBuffer(nil)\n\tbuf.Write16(op.DownstreamSourcePort)\n\treturn buf.Data()\n}\n\nfunc (op *optRelayPort) String() string {\n\treturn fmt.Sprintf(\"RelayPort: %d\", op.DownstreamSourcePort)\n}\n\n\n\n\n\nfunc parseOptRelayPort(data []byte) (*optRelayPort, error) ", "output": "{\n\tvar opt optRelayPort\n\tbuf := uio.NewBigEndianBuffer(data)\n\topt.DownstreamSourcePort = buf.Read16()\n\treturn &opt, buf.FinError()\n}"} {"input": "package tunnel\n\nimport (\n \"container/list\"\n \"time\"\n)\n\ntype recyclerItem struct {\n when time.Time\n buf []byte\n}\n\ntype recycler struct {\n q *list.List\n takeChan, giveChan chan []byte\n}\n\nfunc NewRecycler(size uint32) *recycler {\n r := &recycler{\n q: new(list.List),\n takeChan: make(chan []byte),\n giveChan: make(chan []byte),\n }\n go r.cycle(size)\n return r\n}\n\n\n\nfunc (r *recycler) take() []byte {\n return <-r.takeChan\n}\n\nfunc (r *recycler) give(b []byte) {\n r.giveChan <- b\n}\n\nfunc (r *recycler) cycle(size uint32) ", "output": "{\n for {\n if r.q.Len() == 0 {\n \n r.q.PushFront(recyclerItem{when: time.Now(), buf: make([]byte, size)})\n }\n i := r.q.Front()\n timeout := time.NewTimer(time.Minute)\n select {\n case b:= <-r.giveChan:\n timeout.Stop()\n r.q.PushFront(recyclerItem{when: time.Now(), buf: b})\n case r.takeChan <- i.Value.(recyclerItem).buf:\n timeout.Stop()\n r.q.Remove(i)\n case <-timeout.C:\n i := r.q.Front()\n for i != nil {\n n := i.Next()\n if time.Since(i.Value.(recyclerItem).when) > time.Minute {\n r.q.Remove(i)\n i.Value = nil\n }\n i = n\n }\n }\n }\n}"} {"input": "package dt\n\nimport (\n\t\"net/http\"\n\t\"path\"\n\n\t\"github.com/julienschmidt/httprouter\"\n)\n\n\ntype HTTPRoute struct {\n\tMethod string\n\tPath string\n}\n\n\n\ntype HandlerMap map[HTTPRoute]http.HandlerFunc\n\n\ntype RouteHandler struct {\n\tMethod string\n\tPath string\n\tHandler http.HandlerFunc\n}\n\n\n\n\n\n\n\n\nfunc NewHandlerMap(rhs []RouteHandler) HandlerMap {\n\thm := HandlerMap{}\n\tfor _, rh := range rhs {\n\t\troute := HTTPRoute{\n\t\t\tPath: rh.Path,\n\t\t\tMethod: rh.Method,\n\t\t}\n\t\thm[route] = rh.Handler\n\t}\n\treturn hm\n}\n\nfunc (hm HandlerMap) AddRoutes(prefix string, r *httprouter.Router) ", "output": "{\n\tfor httpRoute, h := range hm {\n\t\tp := path.Join(\"/\", prefix, httpRoute.Path)\n\t\tr.HandlerFunc(httpRoute.Method, p, h)\n\t}\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"time\"\n \"sync\"\n)\n\n\nfunc workerNoRetrieve(ch chan int) {\n go func(ch chan int) {\n ch <- 23\n }(ch)\n\n \n}\n\n\n\n\n\nfunc main() {\n channel := make(chan int)\n fmt.Println(\"Captured val is: \",workerAct(channel, 10, 10))\n workerNoRetrieve(channel)\n fmt.Println(worker2(channel, 23, 43))\n\n time.Sleep(2000) \n}\n\n\nfunc worker2(ch chan int, x int, y int) int {\n go func(c chan int) {\n sum := x+y\n ch <- sum\n }(ch)\n\n value := <-ch\n return value\n}\n\nfunc workerAct(ch chan int, x int, y int) int ", "output": "{\n go func(c chan int) {\n sum := x+y\n ch <- sum\n }(ch)\n\n value := <-ch\n return value\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\nvar configFileOptions map[string]interface{}\n\nfunc LoadConfigFile(file string) error {\n\tconfigFileOptions = nil\n\tif _, err := os.Stat(file); err != nil {\n\t\treturn nil\n\t}\n\tif s, err := ioutil.ReadFile(file); err != nil {\n\t\treturn err\n\t} else if err := yaml.Unmarshal(s, &configFileOptions); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc getConfigFileValue(key string) interface{} {\n\tif v, ok := configFileOptions[key]; ok {\n\t\treturn v\n\t} else {\n\t\treturn nil\n\t}\n}\n\n\n\nfunc getConfigFileValueWithDefault(key string, defaultValue interface{}) interface{} {\n\tif v := getConfigFileValue(key); v != nil {\n\t\treturn v\n\t} else {\n\t\treturn defaultValue\n\t}\n}\n\n\n\nfunc GetConfigFileSlice(key string) []string {\n\tif v, ok := configFileOptions[key].([]interface{}); ok {\n\t\tretVal := []string{}\n\t\tfor _, e := range v {\n\t\t\tif strV, ok := e.(string); ok {\n\t\t\t\tretVal = append(retVal, strV)\n\t\t\t}\n\t\t}\n\t\treturn retVal\n\t} else {\n\t\treturn []string{}\n\t}\n}\n\nfunc GetConfigFileString(key string) string {\n\tv, _ := getConfigFileValue(key).(string)\n\treturn v\n}\n\nfunc GetConfigFileStringWithDefault(key string, defaultValue interface{}) string {\n\tv, _ := getConfigFileValueWithDefault(key, defaultValue).(string)\n\treturn v\n}\n\nfunc IsKeyInConfig(key string) bool ", "output": "{\n\t_, ok := configFileOptions[key]\n\treturn ok\n}"} {"input": "package docker\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/containers/image/image\"\n\t\"github.com/containers/image/types\"\n\t\"github.com/pkg/errors\"\n)\n\n\n\ntype Image struct {\n\ttypes.Image\n\tsrc *dockerImageSource\n}\n\n\n\n\nfunc newImage(ctx *types.SystemContext, ref dockerReference) (types.Image, error) {\n\ts, err := newImageSource(ctx, ref, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\timg, err := image.FromSource(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Image{Image: img, src: s}, nil\n}\n\n\nfunc (i *Image) SourceRefFullName() string {\n\treturn i.src.ref.ref.FullName()\n}\n\n\n\n\nfunc (i *Image) GetRepositoryTags() ([]string, error) ", "output": "{\n\turl := fmt.Sprintf(tagsURL, i.src.ref.ref.RemoteName())\n\tres, err := i.src.c.makeRequest(\"GET\", url, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != http.StatusOK {\n\t\treturn nil, errors.Errorf(\"Invalid status code returned when fetching tags list %d\", res.StatusCode)\n\t}\n\ttype tagsRes struct {\n\t\tTags []string\n\t}\n\ttags := &tagsRes{}\n\tif err := json.NewDecoder(res.Body).Decode(tags); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tags.Tags, nil\n}"} {"input": "package strategy\n\nimport (\n\t\"fmt\"\n\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n\t\"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache\"\n\n\t\"github.com/kubernetes-incubator/cluster-capacity/pkg/framework/store\"\n)\n\ntype Strategy interface {\n\tAdd(obj interface{}) error\n\n\tUpdate(obj interface{}) error\n\n\tDelete(obj interface{}) error\n}\n\ntype predictiveStrategy struct {\n\tresourceStore store.ResourceStore\n\n\tnodeInfo map[string]*schedulercache.NodeInfo\n}\n\n\n\n\n\n\nfunc (s *predictiveStrategy) Add(obj interface{}) error {\n\tswitch item := obj.(type) {\n\tcase *v1.Pod:\n\t\treturn s.addPod(item)\n\tdefault:\n\t\treturn fmt.Errorf(\"resource kind not recognized\")\n\t}\n}\n\nfunc (s *predictiveStrategy) Update(obj interface{}) error {\n\treturn fmt.Errorf(\"Not implemented yet\")\n}\n\nfunc (s *predictiveStrategy) Delete(obj interface{}) error {\n\treturn fmt.Errorf(\"Not implemented yet\")\n}\n\nfunc NewPredictiveStrategy(resourceStore store.ResourceStore) *predictiveStrategy {\n\treturn &predictiveStrategy{\n\t\tresourceStore: resourceStore,\n\t}\n}\n\nfunc (s *predictiveStrategy) addPod(pod *v1.Pod) error ", "output": "{\n\n\tpod.Status.Phase = v1.PodRunning\n\n\terr := s.resourceStore.Update(\"pods\", metav1.Object(pod))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to add new node: %v\", err)\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\n\t\"gopkg.in/yaml.v1\"\n)\n\nconst (\n\tCONFIG_SUBDIR = \"mcmd\"\n\tDEFAULT_KNOWN_HOSTS_FILE = \"$HOME/.ssh/known_hosts\"\n)\n\ntype HostConfig struct {\n\tUser string\n\tPrivatekey string\n\tHosts []string\n}\n\nfunc loadConfig() HostConfig {\n\trawYaml := readHostfile()\n\tvar result HostConfig\n\terr := yaml.Unmarshal(rawYaml, &result)\n\tif err != nil {\n\t\terrLogger.Fatalln(\"Error parsing hostfile:\", err)\n\t}\n\treturn result\n}\n\nfunc readHostfile() []byte {\n\tconfigFileParam := flag.Arg(0)\n\tfor _, file := range getConfigLocationCandidates(configFileParam) {\n\t\tif exists(file) {\n\t\t\treturn getContents(file)\n\t\t}\n\t}\n\terrLogger.Fatalf(\"hostfile %s not found\", configFileParam)\n\treturn nil\n}\n\n\n\nfunc exists(filename string) bool {\n\t_, err := os.Stat(filename)\n\treturn !os.IsNotExist(err)\n}\n\nfunc getContents(filename string) []byte {\n\tfileContents, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\terrLogger.Fatalln(err)\n\t}\n\treturn fileContents\n}\n\nfunc getConfigLocationCandidates(configFileParam string) []string ", "output": "{\n\tconfigRoot, err := os.UserConfigDir()\n\tif err != nil {\n\t\terrLogger.Fatalf(\"no user config dir found\")\n\t}\n\tconfigDir := path.Join(configRoot, CONFIG_SUBDIR)\n\treturn []string{configFileParam,\n\t\tpath.Join(configDir, configFileParam+\".yml\"),\n\t\tpath.Join(configDir, configFileParam+\".yaml\")}\n}"} {"input": "package wml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/wml\"\n)\n\n\n\nfunc TestEG_RubyContentMarshalUnmarshal(t *testing.T) {\n\tv := wml.NewEG_RubyContent()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := wml.NewEG_RubyContent()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestEG_RubyContentConstructor(t *testing.T) ", "output": "{\n\tv := wml.NewEG_RubyContent()\n\tif v == nil {\n\t\tt.Errorf(\"wml.NewEG_RubyContent must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed wml.EG_RubyContent should validate: %s\", err)\n\t}\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\n\n\nfunc naclClose(fd int) (err error) {\n\t_, _, e1 := Syscall(sys_close, uintptr(fd), 0, 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\n\n\n\n\nfunc naclRead(fd int, b []byte) (n int, err error) {\n\tvar _p0 unsafe.Pointer\n\tif len(b) > 0 {\n\t\t_p0 = unsafe.Pointer(&b[0])\n\t} else {\n\t\t_p0 = unsafe.Pointer(&_zero)\n\t}\n\tr0, _, e1 := Syscall(sys_read, uintptr(fd), uintptr(_p0), uintptr(len(b)))\n\tn = int(r0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclSeek(fd int, off *int64, whence int) (err error) {\n\t_, _, e1 := Syscall(sys_lseek, uintptr(fd), uintptr(unsafe.Pointer(off)), uintptr(whence))\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclGetRandomBytes(b []byte) (err error) {\n\tvar _p0 unsafe.Pointer\n\tif len(b) > 0 {\n\t\t_p0 = unsafe.Pointer(&b[0])\n\t} else {\n\t\t_p0 = unsafe.Pointer(&_zero)\n\t}\n\t_, _, e1 := Syscall(sys_get_random_bytes, uintptr(_p0), uintptr(len(b)), 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\nfunc naclFstat(fd int, stat *Stat_t) (err error) ", "output": "{\n\t_, _, e1 := Syscall(sys_fstat, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}"} {"input": "package iso20022\n\n\ntype TaxDetails struct {\n\n\tCertificateIdentification *Max35Text `xml:\"CertId,omitempty\"`\n\n\tTaxType *TaxType `xml:\"TaxTp,omitempty\"`\n}\n\n\n\nfunc (t *TaxDetails) AddTaxType() *TaxType {\n\tt.TaxType = new(TaxType)\n\treturn t.TaxType\n}\n\nfunc (t *TaxDetails) SetCertificateIdentification(value string) ", "output": "{\n\tt.CertificateIdentification = (*Max35Text)(&value)\n}"} {"input": "package vfs\n\nimport (\n\t\"path\"\n\n\tgofig \"github.com/akutz/gofig/types\"\n\n\t\"github.com/rexray/rexray/libstorage/api/context\"\n\t\"github.com/rexray/rexray/libstorage/api/registry\"\n\t\"github.com/rexray/rexray/libstorage/api/types\"\n)\n\nconst (\n\tName = \"vfs\"\n)\n\nfunc init() {\n\tregistry.RegisterConfigReg(\n\t\t\"VFS\",\n\t\tfunc(ctx types.Context, r gofig.ConfigRegistration) {\n\t\t\tvfsRoot := path.Join(context.MustPathConfig(ctx).Lib, \"vfs\")\n\t\t\tr.Key(\n\t\t\t\tgofig.String,\n\t\t\t\t\"\",\n\t\t\t\tvfsRoot,\n\t\t\t\t\"\",\n\t\t\t\t\"vfs.root\")\n\t\t})\n}\n\n\nfunc RootDir(config gofig.Config) string {\n\treturn config.GetString(\"vfs.root\")\n}\n\n\nfunc DeviceFilePath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"dev\")\n}\n\n\n\n\n\nfunc SnapshotsDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"snap\")\n}\n\nfunc VolumesDirPath(config gofig.Config) string ", "output": "{\n\treturn path.Join(RootDir(config), \"vol\")\n}"} {"input": "package netns\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n)\n\nconst (\n\tnetNsRunDir = \"/var/run/netns/\"\n\tselfNsFile = \"/proc/self/ns/net\"\n)\n\n\n\ntype Callback func() error\n\n\ntype handle interface {\n\tclose() error\n\tfd() int\n}\n\n\ntype nsHandle int\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Do(nsName string, cb Callback) error {\n\tif nsName == \"\" {\n\t\treturn cb()\n\t}\n\n\tcurrNsFd, err := getNs(selfNsFile)\n\tif os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"File descriptor to current namespace does not exist: %s\", err)\n\t} else if err != nil {\n\t\treturn fmt.Errorf(\"Failed to open %s: %s\", selfNsFile, err)\n\t}\n\n\truntime.LockOSThread()\n\n\tif err := setNsByName(nsName); err != nil {\n\t\truntime.UnlockOSThread()\n\t\tcurrNsFd.close()\n\t\treturn fmt.Errorf(\"Failed to set the namespace to %s: %s\", nsName, err)\n\t}\n\n\tcbErr := cb()\n\n\tif err = setNs(currNsFd); err != nil {\n\t\tcbErr = fmt.Errorf(\"Failed to return to the original namespace: %s (callback returned %v)\",\n\t\t\terr, cbErr)\n\t}\n\n\truntime.UnlockOSThread()\n\tcurrNsFd.close()\n\treturn cbErr\n}\n\nfunc setNsByName(nsName string) error ", "output": "{\n\tnetPath := netNsRunDir + nsName\n\thandle, err := getNs(netPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to getNs: %s\", err)\n\t}\n\terr = setNs(handle)\n\thandle.close()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to setNs: %s\", err)\n\t}\n\treturn nil\n}"} {"input": "package eventsd\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n\t\"text/tabwriter\"\n\n\t\"github.com/megamsys/libgo/cmd\"\n\t\"github.com/megamsys/libgo/events\"\n\tconstants \"github.com/megamsys/libgo/utils\"\n\t\"github.com/megamsys/vertice/meta\"\n)\n\ntype Config struct {\n\tEnabled bool `toml:\"enabled\"`\n\tMailer Mailer `toml:\"smtp\"`\n\tSlack Slack `toml:\"slack\"`\n\tInfobip Infobip `toml:\"infobip\"`\n\tBillMgr BillMgr `toml:\"bill\"`\n\tAddons Addons `toml:\"addons\"`\n}\n\nfunc NewConfig() *Config {\n\treturn &Config{\n\t\tEnabled: true,\n\t}\n}\n\nfunc (c Config) String() string {\n\tw := new(tabwriter.Writer)\n\tvar b bytes.Buffer\n\tw.Init(&b, 0, 8, 0, '\\t', 0)\n\tb.Write([]byte(cmd.Colorfy(\"Config:\", \"white\", \"\", \"bold\") + \"\\t\" +\n\t\tcmd.Colorfy(\"Eventsd\", \"cyan\", \"\", \"\") + \"\\n\"))\n\tb.Write([]byte(c.Mailer.String()))\n\tb.Write([]byte(c.Infobip.String()))\n\tb.Write([]byte(c.Slack.String() + \"\\n\"))\n\tb.Write([]byte(c.BillMgr.String() + \"\\n\"))\n\tb.Write([]byte(\"---\\n\"))\n\tfmt.Fprintln(w)\n\tw.Flush()\n\treturn strings.TrimSpace(b.String())\n}\n\n\n\nfunc (c Config) toMap() events.EventsConfigMap ", "output": "{\n\tem := make(events.EventsConfigMap)\n\tem[constants.SMTP] = c.Mailer.toMap()\n\tem[constants.SLACK] = c.Slack.toMap()\n\tem[constants.INFOBIP] = c.Infobip.toMap()\n\tem[constants.BILLMGR] = c.BillMgr.toMap()\n\tem[constants.ADDONS] = c.Addons.toMap()\n\tem[constants.META] = meta.MC.ToMap()\n\treturn em\n}"} {"input": "package cgotest\n\nimport \"testing\"\n\n\n\nfunc TestSetgid(t *testing.T) ", "output": "{ testSetgid(t) }"} {"input": "package lints\n\n\n\n\n\nimport (\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/util\"\n)\n\ntype caKeyCertSignNotSet struct{}\n\nfunc (l *caKeyCertSignNotSet) Initialize() error {\n\treturn nil\n}\n\nfunc (l *caKeyCertSignNotSet) CheckApplies(c *x509.Certificate) bool {\n\treturn c.IsCA && util.IsExtInCert(c, util.KeyUsageOID)\n}\n\n\n\nfunc init() {\n\tRegisterLint(&Lint{\n\t\tName: \"e_ca_key_cert_sign_not_set\",\n\t\tDescription: \"Root CA Certificate: Bit positions for keyCertSign and cRLSign MUST be set.\",\n\t\tCitation: \"BRs: 7.1.2.1\",\n\t\tSource: CABFBaselineRequirements,\n\t\tEffectiveDate: util.CABEffectiveDate,\n\t\tLint: &caKeyCertSignNotSet{},\n\t})\n}\n\nfunc (l *caKeyCertSignNotSet) Execute(c *x509.Certificate) *LintResult ", "output": "{\n\tif c.KeyUsage&x509.KeyUsageCertSign != 0 {\n\t\treturn &LintResult{Status: Pass}\n\t} else {\n\t\treturn &LintResult{Status: Error}\n\t}\n}"} {"input": "package exchange\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\ntype ValidPeriod struct {\n\tdate time.Time\n\texpires time.Time\n}\n\n\n\nfunc NewValidPeriod(date, expires time.Time) ValidPeriod {\n\treturn ValidPeriod{date, expires}\n}\n\n\n\nfunc NewValidPeriodWithLifetime(date time.Time, lifetime time.Duration) ValidPeriod {\n\treturn ValidPeriod{date, date.Add(lifetime)}\n}\n\n\n\n\n\nfunc (vp ValidPeriod) Expires() time.Time {\n\treturn vp.expires\n}\n\n\nfunc (vp ValidPeriod) Lifetime() time.Duration {\n\treturn vp.expires.Sub(vp.date)\n}\n\n\n\n\nfunc (vp ValidPeriod) Contains(t time.Time) bool {\n\treturn !t.Before(vp.date) && !t.After(vp.expires)\n}\n\n\nfunc (vp ValidPeriod) String() string {\n\treturn fmt.Sprintf(\"[%s] to [%s]\", vp.date, vp.expires)\n}\n\nfunc (vp ValidPeriod) Date() time.Time ", "output": "{\n\treturn vp.date\n}"} {"input": "package online\n\nimport (\n\t\"monitor/log\"\n\t\"time\"\n)\n\nvar (\n\tsessions = make(map[string]*Session) \n)\n\nconst Expired = 60 * 30\n\n\nfunc init() {\n\tlog.Info(\"Session is started,expired every %d seconds\", Expired)\n\tgo func() {\n\t\tvar i int\n\t\ttimer := time.Tick(time.Minute)\n\t\tfor t := range timer {\n\t\t\ti = 0\n\t\t\tlock.Lock()\n\t\t\tfor k, s := range sessions {\n\t\t\t\tif s.IsExpired() {\n\t\t\t\t\tdelete(sessions, k)\n\t\t\t\t\ti = i + 1\n\t\t\t\t}\n\t\t\t}\n\t\t\tlock.Unlock()\n\t\t\tlog.Infof(\"clear %d sessions at %v,used %v\", i, t, time.Since(t))\n\t\t}\n\t}()\n}\n\n\ntype Session struct {\n\tUID string\n\tName string\n\tKey string\n\tLastTime time.Time\n}\n\n\nfunc (this *Session) IsExpired() bool {\n\treturn time.Since(this.LastTime).Seconds() > Expired\n}\n\n\nfunc SetSession(uid string, name string, key string) {\n\ts := &Session{UID: uid, Key: key, LastTime: time.Now()}\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tsessions[uid] = s\n}\n\n\nfunc GetSession(id string) (name string, key string, ok bool) {\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\n\tif s, exists := sessions[id]; exists {\n\t\tkey = s.Key\n\t\tname = s.Name\n\t\tok = true\n\t\ts.LastTime = time.Now()\n\t}\n\treturn\n}\n\n\n\n\n\nfunc RemoveSession(id string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tif _, ok := sessions[id]; ok {\n\t\tdelete(sessions, id)\n\t}\n}\n\nfunc FreshSession(id string) ", "output": "{\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tif s, ok := sessions[id]; ok {\n\t\ts.LastTime = time.Now()\n\t}\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/api/certificates/v1beta1\"\n\t\"k8s.io/client-go/kubernetes/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype CertificatesV1beta1Interface interface {\n\tRESTClient() rest.Interface\n\tCertificateSigningRequestsGetter\n}\n\n\ntype CertificatesV1beta1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *CertificatesV1beta1Client) CertificateSigningRequests() CertificateSigningRequestInterface {\n\treturn newCertificateSigningRequests(c)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*CertificatesV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &CertificatesV1beta1Client{client}, nil\n}\n\n\n\n\n\n\nfunc New(c rest.Interface) *CertificatesV1beta1Client {\n\treturn &CertificatesV1beta1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *CertificatesV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfigOrDie(c *rest.Config) *CertificatesV1beta1Client ", "output": "{\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}"} {"input": "package v1alpha1\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestResetOffset_SetDefaults(t *testing.T) ", "output": "{\n\tinitialResetOffset := ResetOffset{}\n\tresultResetOffset := initialResetOffset.DeepCopy()\n\tresultResetOffset.SetDefaults(context.TODO())\n\tassert.Equal(t, initialResetOffset, *resultResetOffset)\n}"} {"input": "package jwt\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype Token struct {\n\tExpiryDate int64\n\tRawToken string\n}\n\n\n\nconst expirationSkew = 30\n\n\nfunc (t *Token) Expired() bool {\n\treturn time.Now().Unix()+expirationSkew > t.ExpiryDate\n}\n\n\n\n\n\n\nfunc (t *Token) String() string {\n\treturn t.RawToken\n}\n\n\ntype tokenPayload struct {\n\tExpirationTime int64 `json:\"exp\"`\n}\n\n\n\n\n\nfunc New(token string) (Token, error) {\n\tif len(token) == 0 {\n\t\treturn Token{}, errors.New(\"no token given, a token should be set\")\n\t}\n\n\ttokenParts := strings.Split(token, \".\")\n\tif len(tokenParts) != 3 {\n\t\treturn Token{}, fmt.Errorf(\"invalid token '%s' given, token should exist at least of 3 parts\", token)\n\t}\n\n\tjsonBody, err := base64.RawStdEncoding.DecodeString(tokenParts[1])\n\tif err != nil {\n\t\treturn Token{}, errors.New(\"could not decode token, invalid base64\")\n\t}\n\n\tvar tokenRequest tokenPayload\n\terr = json.Unmarshal(jsonBody, &tokenRequest)\n\tif err != nil {\n\t\treturn Token{}, errors.New(\"could not read token body, invalid json\")\n\t}\n\n\treturn Token{\n\t\tRawToken: token,\n\t\tExpiryDate: tokenRequest.ExpirationTime,\n\t}, nil\n}\n\nfunc (t *Token) GetAuthenticationHeaderValue() string ", "output": "{\n\treturn fmt.Sprintf(\"Bearer %s\", t.RawToken)\n}"} {"input": "package discogs\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\n\n\nfunc TestGetArtistReleases(t *testing.T) {\n\n\texpectedResult := 1\n\n\tclient := getClient(t)\n\treleases, _, err := client.Database.GetArtistReleases(4130)\n\tcheck(t, err)\n\n\tassert(t, releases.Pagination.Pages == expectedResult, fmt.Sprintf(\"Artist.Pagination.Pages expected %d, received %d\", expectedResult, releases.Pagination.Pages))\n\n}\n\nfunc TestGetArtist(t *testing.T) ", "output": "{\n\n\texpectedResult := \"Blunted Dummies\"\n\n\tclient := getClient(t)\n\tartist, _, err := client.Database.GetArtist(4130)\n\tcheck(t, err)\n\n\tassert(t, artist.Name == expectedResult, fmt.Sprintf(\"Artist.name expected %s, received %s \", expectedResult, artist.Name))\n}"} {"input": "package pathfs\n\nimport (\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/hanwen/go-fuse/fuse\"\n)\n\nfunc (fs *loopbackFileSystem) StatFs(name string) *fuse.StatfsOut {\n\ts := syscall.Statfs_t{}\n\terr := syscall.Statfs(fs.GetPath(name), &s)\n\tif err == nil {\n\t\treturn &fuse.StatfsOut{\n\t\t\tBlocks: s.Blocks,\n\t\t\tBfree: s.Bfree,\n\t\t\tBavail: s.Bavail,\n\t\t\tFiles: s.Files,\n\t\t\tFfree: s.Ffree,\n\t\t\tBsize: uint32(s.Iosize), \n\t\t\tFrsize: s.Bsize, \n\t\t}\n\t}\n\treturn nil\n}\n\nconst _UTIME_NOW = ((1 << 30) - 1)\nconst _UTIME_OMIT = ((1 << 30) - 2)\n\n\n\n\n\n\nfunc timeToTimeval(t *time.Time) syscall.Timeval {\n\tvar tv syscall.Timeval\n\ttv.Usec = int32(t.Nanosecond() / 1000)\n\ttv.Sec = t.Unix()\n\treturn tv\n}\n\n\n\n\n\nfunc (fs *loopbackFileSystem) Utimens(path string, a *time.Time, m *time.Time, context *fuse.Context) fuse.Status ", "output": "{\n\ttv := make([]syscall.Timeval, 2)\n\tif a == nil {\n\t\ttv[0].Usec = _UTIME_OMIT\n\t} else {\n\t\ttv[0] = timeToTimeval(a)\n\t}\n\n\tif m == nil {\n\t\ttv[1].Usec = _UTIME_OMIT\n\t} else {\n\t\ttv[1] = timeToTimeval(m)\n\t}\n\n\terr := syscall.Utimes(fs.GetPath(path), tv)\n\treturn fuse.ToStatus(err)\n}"} {"input": "package plotter\n\nimport (\n\t\"image/color\"\n\n\t\"github.com/gonum/plot\"\n\t\"github.com/gonum/plot/vg\"\n\t\"github.com/gonum/plot/vg/draw\"\n)\n\n\n\n\ntype GlyphBoxes struct {\n\tdraw.LineStyle\n}\n\nfunc NewGlyphBoxes() *GlyphBoxes {\n\tg := new(GlyphBoxes)\n\tg.Color = color.RGBA{R: 255, A: 255}\n\tg.Width = vg.Points(0.25)\n\treturn g\n}\n\n\n\nfunc (g GlyphBoxes) Plot(c draw.Canvas, plt *plot.Plot) ", "output": "{\n\tfor _, b := range plt.GlyphBoxes(plt) {\n\t\tx := c.X(b.X) + b.Rectangle.Min.X\n\t\ty := c.Y(b.Y) + b.Rectangle.Min.Y\n\t\tc.StrokeLines(g.LineStyle, []vg.Point{\n\t\t\t{x, y},\n\t\t\t{x + b.Rectangle.Size().X, y},\n\t\t\t{x + b.Rectangle.Size().X, y + b.Rectangle.Size().Y},\n\t\t\t{x, y + b.Rectangle.Size().Y},\n\t\t\t{x, y},\n\t\t})\n\t}\n}"} {"input": "package main\n\n\nfunc (b bucketPerms) isValidBucketPERM() bool {\n\tswitch true {\n\tcase b.isPrivate():\n\t\tfallthrough\n\tcase b.isReadOnly():\n\t\tfallthrough\n\tcase b.isPublic():\n\t\tfallthrough\n\tcase b.isAuthorized():\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\ntype bucketPerms string\n\n\nconst (\n\tbucketPrivate = bucketPerms(\"private\")\n\tbucketReadOnly = bucketPerms(\"readonly\")\n\tbucketPublic = bucketPerms(\"public\")\n\tbucketAuthorized = bucketPerms(\"authorized\")\n)\n\nfunc (b bucketPerms) String() string {\n\tif !b.isValidBucketPERM() {\n\t\treturn string(b)\n\t}\n\tif b.isReadOnly() {\n\t\treturn \"public-read\"\n\t}\n\tif b.isPublic() {\n\t\treturn \"public-read-write\"\n\t}\n\tif b.isAuthorized() {\n\t\treturn \"authenticated-read\"\n\t}\n\treturn \"private\"\n}\n\nfunc aclToPerms(acl string) bucketPerms {\n\tswitch acl {\n\tcase \"private\":\n\t\treturn bucketPerms(\"private\")\n\tcase \"public-read\":\n\t\treturn bucketPerms(\"readonly\")\n\tcase \"public-read-write\":\n\t\treturn bucketPerms(\"public\")\n\tcase \"authenticated-read\":\n\t\treturn bucketPerms(\"authorized\")\n\tdefault:\n\t\treturn bucketPerms(acl)\n\t}\n}\n\n\nfunc (b bucketPerms) isPrivate() bool {\n\treturn b == bucketPrivate\n}\n\n\nfunc (b bucketPerms) isReadOnly() bool {\n\treturn b == bucketReadOnly\n}\n\n\n\n\n\nfunc (b bucketPerms) isAuthorized() bool {\n\treturn b == bucketAuthorized\n}\n\nfunc (b bucketPerms) isPublic() bool ", "output": "{\n\treturn b == bucketPublic\n}"} {"input": "package minecraft\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"github.com/LilyPad/GoLilyPad/packet\"\n)\n\ntype PacketServerPluginMessage struct {\n\tChannel string\n\tData []byte\n}\n\nfunc NewPacketServerPluginMessage(channel string, data []byte) (this *PacketServerPluginMessage) {\n\tthis = new(PacketServerPluginMessage)\n\tthis.Channel = channel\n\tthis.Data = data\n\treturn\n}\n\n\n\ntype packetServerPluginMessageCodec struct {\n\n}\n\nfunc (this *packetServerPluginMessageCodec) Decode(reader io.Reader) (decode packet.Packet, err error) {\n\tpacketServerPluginMessage := new(PacketServerPluginMessage)\n\tpacketServerPluginMessage.Channel, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\tpacketServerPluginMessage.Data, err = ioutil.ReadAll(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\tdecode = packetServerPluginMessage\n\treturn\n}\n\nfunc (this *packetServerPluginMessageCodec) Encode(writer io.Writer, encode packet.Packet) (err error) {\n\tpacketServerPluginMessage := encode.(*PacketServerPluginMessage)\n\terr = packet.WriteString(writer, packetServerPluginMessage.Channel)\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = writer.Write(packetServerPluginMessage.Data)\n\treturn\n}\n\nfunc (this *PacketServerPluginMessage) Id() int ", "output": "{\n\treturn PACKET_SERVER_PLUGIN_MESSAGE\n}"} {"input": "package env\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestEnvMustGet(t *testing.T) {\n\tgopath, err := MustGet(\"GOPATH\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif gopath != os.Getenv(\"GOPATH\") {\n\t\tt.Errorf(\"expected GOPATH to be the same, got %s.\", gopath)\n\t}\n\n\t_, err = MustGet(\"NOEXISTVAR\")\n\tif err == nil {\n\t\tt.Error(\"expected error to be non-nil\")\n\t}\n}\n\nfunc TestEnvSet(t *testing.T) {\n\tSet(\"MYVAR\", \"foo\")\n\tmyVar := Get(\"MYVAR\", \"bar\")\n\tif myVar != \"foo\" {\n\t\tt.Errorf(\"expected MYVAR to equal foo, got %s.\", myVar)\n\t}\n}\n\nfunc TestEnvMustSet(t *testing.T) {\n\terr := MustSet(\"FOO\", \"bar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tfooVar := os.Getenv(\"FOO\")\n\tif fooVar != \"bar\" {\n\t\tt.Errorf(\"expected FOO variable to equal bar, got %s.\", fooVar)\n\t}\n}\n\nfunc TestEnvGetAll(t *testing.T) {\n\tenvMap := GetAll()\n\tif len(envMap) == 0 {\n\t\tt.Error(\"expected environment not empty.\")\n\t}\n}\n\nfunc TestEnvGet(t *testing.T) ", "output": "{\n\tgopath := Get(\"GOPATH\", \"\")\n\tif gopath != os.Getenv(\"GOPATH\") {\n\t\tt.Error(\"expected GOPATH not empty.\")\n\t}\n\n\tnoExistVar := Get(\"NOEXISTVAR\", \"foo\")\n\tif noExistVar != \"foo\" {\n\t\tt.Errorf(\"expected NOEXISTVAR to equal foo, got %s.\", noExistVar)\n\t}\n}"} {"input": "package main\n\n\ntype I interface { F() int }\n\n\ntype S struct { }\nfunc (s *S) F() int { return 1 }\n\n\n\n\n\nfunc NewI(i int) I {\n\treturn new(S)\n}\n\n\n\n\nfunc main() {\n\ti := NewI(0);\n\tUse(i);\n\n\tUse(NewI(0));\n}\n\nfunc Use(x I) ", "output": "{\n\tx.F()\n}"} {"input": "package middleware\n\nimport (\n\t\"encoding/base64\"\n\n\t\"github.com/labstack/echo\"\n)\n\ntype (\n\tBasicAuthConfig struct {\n\t\tSkipper Skipper\n\n\t\tValidator BasicAuthValidator\n\t}\n\n\tBasicAuthValidator func(string, string) bool\n)\n\nconst (\n\tbasic = \"Basic\"\n)\n\nvar (\n\tDefaultBasicAuthConfig = BasicAuthConfig{\n\t\tSkipper: defaultSkipper,\n\t}\n)\n\n\n\n\n\n\n\n\n\n\nfunc BasicAuthWithConfig(config BasicAuthConfig) echo.MiddlewareFunc {\n\tif config.Validator == nil {\n\t\tpanic(\"basic-auth middleware requires validator function\")\n\t}\n\tif config.Skipper == nil {\n\t\tconfig.Skipper = DefaultBasicAuthConfig.Skipper\n\t}\n\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\tif config.Skipper(c) {\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\tauth := c.Request().Header().Get(echo.HeaderAuthorization)\n\t\t\tl := len(basic)\n\n\t\t\tif len(auth) > l+1 && auth[:l] == basic {\n\t\t\t\tb, err := base64.StdEncoding.DecodeString(auth[l+1:])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tcred := string(b)\n\t\t\t\tfor i := 0; i < len(cred); i++ {\n\t\t\t\t\tif cred[i] == ':' {\n\t\t\t\t\t\tif config.Validator(cred[:i], cred[i+1:]) {\n\t\t\t\t\t\t\treturn next(c)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tc.Response().Header().Set(echo.HeaderWWWAuthenticate, basic+\" realm=Restricted\")\n\t\t\treturn echo.ErrUnauthorized\n\t\t}\n\t}\n}\n\nfunc BasicAuth(fn BasicAuthValidator) echo.MiddlewareFunc ", "output": "{\n\tc := DefaultBasicAuthConfig\n\tc.Validator = fn\n\treturn BasicAuthWithConfig(c)\n}"} {"input": "package tiller\n\nimport (\n\t\"testing\"\n\n\t\"k8s.io/helm/pkg/helm\"\n\t\"k8s.io/helm/pkg/proto/hapi/services\"\n)\n\n\n\nfunc TestGetReleaseContent(t *testing.T) ", "output": "{\n\tc := helm.NewContext()\n\trs := rsFixture()\n\trel := releaseStub()\n\tif err := rs.env.Releases.Create(rel); err != nil {\n\t\tt.Fatalf(\"Could not store mock release: %s\", err)\n\t}\n\n\tres, err := rs.GetReleaseContent(c, &services.GetReleaseContentRequest{Name: rel.Name, Version: 1})\n\tif err != nil {\n\t\tt.Errorf(\"Error getting release content: %s\", err)\n\t}\n\n\tif res.Release.Chart.Metadata.Name != rel.Chart.Metadata.Name {\n\t\tt.Errorf(\"Expected %q, got %q\", rel.Chart.Metadata.Name, res.Release.Chart.Metadata.Name)\n\t}\n}"} {"input": "package uaa\n\nimport (\n\t\"sort\"\n\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n)\n\ntype Prompt struct {\n\tKey string \n\tType string \n\tLabel string \n}\n\ntype PromptAnswer struct {\n\tKey string \n\tValue string\n}\n\nfunc (p Prompt) IsPassword() bool { return p.Type == \"password\" }\n\ntype PromptsResp struct {\n\tPrompts map[string][]string \n}\n\nfunc (u UAAImpl) Prompts() ([]Prompt, error) {\n\tresp, err := u.client.Prompts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar prompts []Prompt\n\n\tfor key, pair := range resp.Prompts {\n\t\tprompts = append(prompts, Prompt{\n\t\t\tKey: key,\n\t\t\tType: pair[0],\n\t\t\tLabel: pair[1],\n\t\t})\n\t}\n\n\tsort.Sort(PromptSorting(prompts))\n\n\treturn prompts, nil\n}\n\nfunc (c Client) Prompts() (PromptsResp, error) {\n\tvar resp PromptsResp\n\n\terr := c.clientRequest.Get(\"/login\", &resp)\n\tif err != nil {\n\t\treturn resp, bosherr.WrapError(err, \"Requesting UAA prompts\")\n\t}\n\n\treturn resp, nil\n}\n\ntype PromptSorting []Prompt\n\nfunc (s PromptSorting) Len() int { return len(s) }\nfunc (s PromptSorting) Less(i, j int) bool { return s[i].Type > s[j].Type }\n\n\nfunc (s PromptSorting) Swap(i, j int) ", "output": "{ s[i], s[j] = s[j], s[i] }"} {"input": "package tree\n\ntype Binary struct {\n\tscore int\n\tvalue interface{}\n\n\tleft, right *Binary\n}\n\nfunc (t *Binary) Search(score int) interface{} {\n\troot := t\n\tfor root != nil {\n\t\tswitch {\n\t\tcase root.score == score:\n\t\t\treturn root.value\n\t\tcase root.score > score:\n\t\t\troot = root.left\n\t\tcase root.score < score:\n\t\t\troot = root.right\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (t *Binary) Add(score int, value interface{}, replace bool) ", "output": "{\n\troot := t\n\tfor {\n\t\tswitch {\n\t\tcase root.score == score:\n\t\t\tif replace {\n\t\t\t\troot.value = value\n\t\t\t}\n\t\t\treturn\n\t\tcase root.score > score:\n\t\t\tif root.left == nil {\n\t\t\t\troot.left = &Binary{score: score, value: value}\n\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\troot = root.left\n\t\t\t}\n\t\tcase root.score < score:\n\t\t\tif root.right == nil {\n\t\t\t\troot.right = &Binary{score: score, value: value}\n\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\troot = root.right\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package treemap\n\nimport \"github.com/emirpasic/gods/containers\"\n\nfunc assertSerializationImplementation() {\n\tvar _ containers.JSONSerializer = (*Map)(nil)\n\tvar _ containers.JSONDeserializer = (*Map)(nil)\n}\n\n\nfunc (m *Map) ToJSON() ([]byte, error) {\n\treturn m.tree.ToJSON()\n}\n\n\n\n\nfunc (m *Map) FromJSON(data []byte) error ", "output": "{\n\treturn m.tree.FromJSON(data)\n}"} {"input": "package leakcheck\n\nimport (\n\t\"runtime\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar goroutinesToIgnore = []string{\n\t\"testing.Main(\",\n\t\"testing.tRunner(\",\n\t\"testing.(*M).\",\n\t\"runtime.goexit\",\n\t\"created by runtime.gc\",\n\t\"created by runtime/trace.Start\",\n\t\"interestingGoroutines\",\n\t\"runtime.MHeap_Scavenger\",\n\t\"signal.signal_recv\",\n\t\"sigterm.handler\",\n\t\"runtime_mcall\",\n\t\"(*loggingT).flushDaemon\",\n\t\"goroutine in C code\",\n\t\"created by net/http.(*Transport).dialConn\",\n}\n\n\n\n\nfunc RegisterIgnoreGoroutine(s string) {\n\tgoroutinesToIgnore = append(goroutinesToIgnore, s)\n}\n\n\n\n\n\nfunc interestingGoroutines() (gs []string) {\n\tbuf := make([]byte, 2<<20)\n\tbuf = buf[:runtime.Stack(buf, true)]\n\tfor _, g := range strings.Split(string(buf), \"\\n\\n\") {\n\t\tif !ignore(g) {\n\t\t\tgs = append(gs, g)\n\t\t}\n\t}\n\tsort.Strings(gs)\n\treturn\n}\n\n\n\ntype Errorfer interface {\n\tErrorf(format string, args ...interface{})\n}\n\nfunc check(efer Errorfer, timeout time.Duration) {\n\tdeadline := time.Now().Add(timeout)\n\tvar leaked []string\n\tfor time.Now().Before(deadline) {\n\t\tif leaked = interestingGoroutines(); len(leaked) == 0 {\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(50 * time.Millisecond)\n\t}\n\tfor _, g := range leaked {\n\t\tefer.Errorf(\"Leaked goroutine: %v\", g)\n\t}\n}\n\n\n\n\nfunc Check(efer Errorfer) {\n\tcheck(efer, 10*time.Second)\n}\n\nfunc ignore(g string) bool ", "output": "{\n\tsl := strings.SplitN(g, \"\\n\", 2)\n\tif len(sl) != 2 {\n\t\treturn true\n\t}\n\tstack := strings.TrimSpace(sl[1])\n\tif strings.HasPrefix(stack, \"testing.RunTests\") {\n\t\treturn true\n\t}\n\n\tif stack == \"\" {\n\t\treturn true\n\t}\n\n\tfor _, s := range goroutinesToIgnore {\n\t\tif strings.Contains(stack, s) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package remote_ip\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\n\t\"github.com/pkg/errors\"\n\n\t\"github.com/dpb587/ssoca/auth\"\n\t\"github.com/dpb587/ssoca/auth/authz\"\n)\n\ntype Requirement struct {\n\tWithinRaw string `yaml:\"within\"`\n\tWithin net.IPNet `yaml:\"-\"`\n}\n\n\n\nfunc (r Requirement) VerifyAuthorization(req *http.Request, _ *auth.Token) error ", "output": "{\n\thost, _, err := net.SplitHostPort(req.RemoteAddr)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"parsing remote address\")\n\t}\n\n\tip := net.ParseIP(host)\n\tif !r.Within.Contains(ip) {\n\t\treturn authz.NewError(errors.New(\"remote IP is not allowed\"))\n\t}\n\n\treturn nil\n}"} {"input": "package cluster\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\n\n\nfunc SetDefaults_InstanceGroup(obj *InstanceGroup) {\n\tif obj.Spec.ProvisionPolicy == \"\" {\n\t\tobj.Spec.ProvisionPolicy = InstanceGroupProvisionDynamicOnly\n\t}\n}\n\nfunc SetDefaults_Instance(obj *Instance) {\n\tif obj.Spec.ReclaimPolicy == \"\" {\n\t\tobj.Spec.ReclaimPolicy = InstanceReclaimDelete\n\t}\n\n\tif obj.Status.Phase == \"\" {\n\t\tobj.Status.Phase = InstancePending\n\t}\n}\n\nfunc SetDefaults_Network(obj *Network) {\n\tif obj.Status.Phase == \"\" {\n\t\tobj.Status.Phase = NetworkPending\n\t}\n}\n\nfunc SetDefaults_ReservedInstance(obj *ReservedInstance) {\n\tif obj.Status.Phase == \"\" {\n\t\tobj.Status.Phase = ReservedInstanceAvailable\n\t}\n}\n\nfunc addDefaultingFuncs(scheme *runtime.Scheme) error ", "output": "{\n\treturn RegisterDefaults(scheme)\n}"} {"input": "package fix\n\nimport (\n\t\"strings\"\n\n\t\"github.com/mitchellh/mapstructure\"\n)\n\n\n\ntype FixerAmazonShutdownBehavior struct{}\n\nfunc (FixerAmazonShutdownBehavior) DeprecatedOptions() map[string][]string {\n\treturn map[string][]string{\n\t\t\"*amazon*\": []string{\"shutdown_behaviour\"},\n\t}\n}\n\nfunc (FixerAmazonShutdownBehavior) Fix(input map[string]interface{}) (map[string]interface{}, error) {\n\ttype template struct {\n\t\tBuilders []map[string]interface{}\n\t}\n\n\tvar tpl template\n\tif err := mapstructure.Decode(input, &tpl); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, builder := range tpl.Builders {\n\t\tbuilderTypeRaw, ok := builder[\"type\"]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tbuilderType, ok := builderTypeRaw.(string)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !strings.HasPrefix(builderType, \"amazon-\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tshutdownBehavior, ok := builder[\"shutdown_behaviour\"]\n\n\t\tif ok {\n\t\t\tbuilder[\"shutdown_behavior\"] = shutdownBehavior\n\t\t\tdelete(builder, \"shutdown_behaviour\")\n\t\t}\n\t}\n\n\tinput[\"builders\"] = tpl.Builders\n\treturn input, nil\n}\n\n\n\nfunc (FixerAmazonShutdownBehavior) Synopsis() string ", "output": "{\n\treturn `Changes \"shutdown_behaviour\" to \"shutdown_behavior\" in Amazon builders.`\n}"} {"input": "package apiserver\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/juju/errors\"\n)\n\nfunc modelFacadesOnly(facadeName, _ string) error {\n\tif !isModelFacade(facadeName) {\n\t\treturn errors.NewNotSupported(nil, fmt.Sprintf(\"facade %q not supported for model API connection\", facadeName))\n\t}\n\treturn nil\n}\n\n\n\nfunc isModelFacade(facadeName string) bool ", "output": "{\n\treturn !controllerFacadeNames.Contains(facadeName)\n}"} {"input": "package install\n\nimport (\n\t\"k8s.io/apimachinery/pkg/apimachinery/announced\"\n\t\"k8s.io/apimachinery/pkg/apimachinery/registered\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/util/sets\"\n\t\"k8s.io/kubernetes/federation/apis/core\"\n\tcorev1 \"k8s.io/kubernetes/federation/apis/core/v1\"\n)\n\nfunc init() {\n\tInstall(core.GroupFactoryRegistry, core.Registry, core.Scheme)\n}\n\n\n\n\nfunc Install(groupFactoryRegistry announced.APIGroupFactoryRegistry, registry *registered.APIRegistrationManager, scheme *runtime.Scheme) ", "output": "{\n\tif err := announced.NewGroupMetaFactory(\n\t\t&announced.GroupMetaFactoryArgs{\n\t\t\tGroupName: core.GroupName,\n\t\t\tVersionPreferenceOrder: []string{corev1.SchemeGroupVersion.Version},\n\t\t\tAddInternalObjectsToScheme: core.AddToScheme,\n\t\t\tRootScopedKinds: sets.NewString(\n\t\t\t\t\"Namespace\",\n\t\t\t),\n\t\t\tIgnoredKinds: sets.NewString(\n\t\t\t\t\"ListOptions\",\n\t\t\t\t\"DeleteOptions\",\n\t\t\t\t\"Status\",\n\t\t\t),\n\t\t},\n\t\tannounced.VersionToSchemeFunc{\n\t\t\tcorev1.SchemeGroupVersion.Version: corev1.AddToScheme,\n\t\t},\n\t).Announce(groupFactoryRegistry).RegisterAndEnable(registry, scheme); err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/julienschmidt/httprouter\"\n\t\"net/http\"\n)\n\ntype Logout struct {\n\t*Controller\n}\n\n\n\nfunc NewLogoutController(c *Controller, router *httprouter.Router) {\n\tlogout := &Logout{\n\t\tc,\n\t}\n\tlogout.Register(router)\n}\n\n\n\nfunc (l *Logout) Register(router *httprouter.Router) {\n\trouter.GET(\"/logout\", l.Get)\n}\n\n\n\n\n\nfunc (l *Logout) Get(res http.ResponseWriter, req *http.Request, _ httprouter.Params) ", "output": "{\n\tl.Authentication.ClearSession(res)\n\thttp.Redirect(res, req, \"/login\", http.StatusFound)\n}"} {"input": "package http\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/Cepave/open-falcon-backend/modules/transfer/g\"\n\tlog \"github.com/sirupsen/logrus\"\n\t\"net/http\"\n\t_ \"net/http/pprof\"\n)\n\ntype Dto struct {\n\tMsg string `json:\"msg\"`\n\tData interface{} `json:\"data\"`\n}\n\nfunc Start() {\n\tgo startHttpServer()\n}\nfunc startHttpServer() {\n\tif !g.Config().Http.Enabled {\n\t\treturn\n\t}\n\n\taddr := g.Config().Http.Listen\n\tif addr == \"\" {\n\t\treturn\n\t}\n\n\tconfigCommonRoutes()\n\tconfigProcHttpRoutes()\n\tconfigDebugHttpRoutes()\n\tconfigApiHttpRoutes()\n\n\ts := &http.Server{\n\t\tAddr: addr,\n\t\tMaxHeaderBytes: 1 << 30,\n\t}\n\n\tlog.Println(\"http.startHttpServer ok, listening\", addr)\n\tlog.Fatalln(s.ListenAndServe())\n}\n\n\n\nfunc RenderDataJson(w http.ResponseWriter, data interface{}) {\n\tRenderJson(w, Dto{Msg: \"success\", Data: data})\n}\n\nfunc RenderMsgJson(w http.ResponseWriter, msg string) {\n\tRenderJson(w, map[string]string{\"msg\": msg})\n}\n\nfunc AutoRender(w http.ResponseWriter, data interface{}, err error) {\n\tif err != nil {\n\t\tRenderMsgJson(w, err.Error())\n\t\treturn\n\t}\n\tRenderDataJson(w, data)\n}\n\nfunc RenderJson(w http.ResponseWriter, v interface{}) ", "output": "{\n\tbs, err := json.Marshal(v)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.Write(bs)\n}"} {"input": "package fuse\n\nimport (\n\t\"runtime\"\n)\n\n\n\nfunc nop(msg interface{}) {}\n\nvar Debug = nop\n\nfunc stack() string ", "output": "{\n\tbuf := make([]byte, 1024)\n\treturn string(buf[:runtime.Stack(buf, false)])\n}"} {"input": "package installer\n\nimport (\n\t\"github.com/wx13/genesis\"\n)\n\n\n\ntype Custom struct {\n\tTask genesis.Doer\n\tS func() (genesis.Status, error)\n\tD func() (bool, error)\n\tU func() (bool, error)\n\tI func() string\n\tF func() []string\n}\n\n\n\nfunc (custom Custom) Status() (genesis.Status, error) {\n\treturn custom.S()\n}\n\nfunc (custom Custom) Do() (bool, error) {\n\treturn custom.D()\n}\n\nfunc (custom Custom) Undo() (bool, error) {\n\treturn custom.U()\n}\n\nfunc (custom Custom) ID() string {\n\treturn custom.I()\n}\n\nfunc (custom Custom) Files() []string {\n\treturn custom.F()\n}\n\nfunc NewCustom(task genesis.Doer) *Custom ", "output": "{\n\tcustom := Custom{\n\t\tTask: task,\n\t\tS: task.Status,\n\t\tD: task.Do,\n\t\tU: task.Undo,\n\t\tI: task.ID,\n\t\tF: task.Files,\n\t}\n\treturn &custom\n}"} {"input": "package common\n\nimport (\n\t\"github.com/spf13/viper\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\ntype Wskprops struct {\n\tAPIHost string\n\tAuthKey string\n}\n\n\n\nfunc GetWskprops() *Wskprops ", "output": "{\n\tvar dep Wskprops\n\tdep.APIHost = \"\"\n\tdep.AuthKey = \"\"\n\n\tviper.SetConfigName(\"whisk\")\n\tviper.AddConfigPath(os.Getenv(\"OPENWHISK_HOME\"))\n\n\terr := viper.ReadInConfig()\n\tif err == nil {\n\t\tauthPath := viper.GetString(\"testing.auth\")\n\n\t\tb, err := ioutil.ReadFile(authPath)\n\t\tif err == nil {\n\t\t\tdep.AuthKey = string(b)\n\t\t}\n\t\tdep.APIHost = viper.GetString(\"router.host\")\n\t}\n\treturn &dep\n}"} {"input": "package socketio\n\nimport \"errors\"\n\n\ntype BroadcastAdaptor interface {\n\n\tJoin(room string, socket Socket) error\n\n\tLeave(room string, socket Socket) error\n\n\tSend(ignore Socket, room, event string, args ...interface{}) error\n\n\tGetAllClients(room string) (map[string]Socket, error)\n}\n\nvar newBroadcast = newBroadcastDefault\n\ntype Broadcast map[string]map[string]Socket\n\nfunc newBroadcastDefault() BroadcastAdaptor {\n\treturn make(Broadcast)\n}\n\nfunc (b Broadcast) Join(room string, socket Socket) error {\n\tsockets, ok := b[room]\n\tif !ok {\n\t\tsockets = make(map[string]Socket)\n\t}\n\tsockets[socket.Id()] = socket\n\tb[room] = sockets\n\treturn nil\n}\n\nfunc (b Broadcast) Leave(room string, socket Socket) error {\n\tsockets, ok := b[room]\n\tif !ok {\n\t\treturn nil\n\t}\n\tdelete(sockets, socket.Id())\n\tif len(sockets) == 0 {\n\t\tdelete(b, room)\n\t\treturn nil\n\t}\n\tb[room] = sockets\n\treturn nil\n}\n\nfunc (b Broadcast) Send(ignore Socket, room, event string, args ...interface{}) error {\n\tsockets := b[room]\n\tfor id, s := range sockets {\n\t\tif ignore != nil && ignore.Id() == id {\n\t\t\tcontinue\n\t\t}\n\t\ts.Emit(event, args...)\n\t}\n\treturn nil\n}\n\n\n\nfunc (b Broadcast) GetAllClients(room string) (map[string]Socket, error) ", "output": "{\n\tsockets, ok := b[room]\n\tif !ok {\n\t\treturn nil, errors.New(\"没有此房间\")\n\t}\n\treturn sockets, nil\n}"} {"input": "package data_table\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/julienschmidt/httprouter\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\nfunc DataStoreHandler(tableStore TableStore) func(http.ResponseWriter, *http.Request, httprouter.Params) {\n\treturn func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\t\trequest := newSearchRequest(r, ps)\n\t\tresult := tableStore.QueryData(request)\n\t\tjsonBytes, _ := json.Marshal(result)\n\t\tfmt.Fprint(w, string(jsonBytes))\n\t}\n}\n\n\n\nfunc ParseKey(key string) []string {\n\tres := make([]string, 0)\n\tvar currKey bytes.Buffer\n\n\tfor _, char := range key {\n\t\tif char == '[' || char == ']' {\n\t\t\tif currKey.Len() > 0 {\n\t\t\t\tres = append(res, currKey.String())\n\t\t\t\tcurrKey.Reset()\n\t\t\t}\n\t\t} else {\n\t\t\tcurrKey.WriteRune(char)\n\t\t}\n\t}\n\n\tif currKey.Len() > 0 {\n\t\tres = append(res, currKey.String())\n\t}\n\n\treturn res\n}\n\nfunc TreePostFormValues(values url.Values) map[string]interface{} ", "output": "{\n\tres := make(map[string]interface{})\n\tvar currValue map[string]interface{}\n\tfor rawKey, value := range values {\n\t\tif vs := value; len(vs) > 0 {\n\t\t\tcurrValue = res\n\t\t\tkeyPath := ParseKey(rawKey)\n\t\t\tlastIndex := len(keyPath) - 1\n\t\t\tfor index, key := range keyPath {\n\t\t\t\tif index == lastIndex {\n\t\t\t\t\tcurrValue[key] = vs[0]\n\t\t\t\t} else {\n\t\t\t\t\tif _, ok := currValue[key]; !ok {\n\t\t\t\t\t\tcurrValue[key] = make(map[string]interface{})\n\t\t\t\t\t}\n\t\t\t\t\tcurrValue = currValue[key].(map[string]interface{})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\treturn res\n}"} {"input": "package libproxy\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\ntype UnixProxy struct {\n\tlistener net.Listener\n\tfrontendAddr net.Addr\n\tbackendAddr *net.UnixAddr\n}\n\n\n\n\n\nfunc HandleUnixConnection(client Conn, backendAddr *net.UnixAddr, quit <-chan struct{}) error {\n\tstart := time.Now()\n\tfor {\n\t\tbackend, err := net.DialUnix(\"unix\", nil, backendAddr)\n\t\tif err != nil {\n\t\t\tif errIsConnectionRefused(err) {\n\t\t\t\tif time.Since(start) > 120*time.Second {\n\t\t\t\t\tlog.Errorf(\"failed to connect to %s after 120s. The server appears to be down.\", backendAddr.String())\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlog.Infof(\"%s appears to not be started yet: will retry in 5s\", backendAddr.String())\n\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"can't forward traffic to backend unix/%v: %s\", backendAddr, err)\n\t\t}\n\t\treturn ProxyStream(client, backend, quit)\n\t}\n}\n\n\nfunc (proxy *UnixProxy) Run() {\n\tquit := make(chan struct{})\n\tdefer close(quit)\n\tfor {\n\t\tclient, err := proxy.listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Stopping proxy on unix/%v for unix/%v (%s)\", proxy.frontendAddr, proxy.backendAddr, err)\n\t\t\treturn\n\t\t}\n\t\tgo HandleUnixConnection(client.(Conn), proxy.backendAddr, quit)\n\t}\n}\n\n\nfunc (proxy *UnixProxy) Close() { proxy.listener.Close() }\n\n\nfunc (proxy *UnixProxy) FrontendAddr() net.Addr { return proxy.frontendAddr }\n\n\nfunc (proxy *UnixProxy) BackendAddr() net.Addr { return proxy.backendAddr }\n\nfunc NewUnixProxy(listener net.Listener, backendAddr *net.UnixAddr) (*UnixProxy, error) ", "output": "{\n\tlog.Printf(\"NewUnixProxy from %s -> %s\\n\", listener.Addr().String(), backendAddr.String())\n\treturn &UnixProxy{\n\t\tlistener: listener,\n\t\tfrontendAddr: listener.Addr(),\n\t\tbackendAddr: backendAddr,\n\t}, nil\n}"} {"input": "package msg\n\nimport (\n \"testing\"\n)\n\n\n\nfunc Test_Analysis(t *testing.T) ", "output": "{\n st := \"HI!\"\n mt, msg := Analysis(st)\n t.Logf(\"msgType = %v\\tcontent = %v\", mt, msg)\n\n st = \":set_name 123\"\n mt, msg = Analysis(st)\n t.Logf(\"msgType = %v\\tcontent = %v\", mt, msg)\n\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/exec\"\n)\n\ntype Repository struct {\n\tName string\n}\n\nfunc getRepositories() *[]Repository {\n\tvar result []Repository\n\tdirs, _ := ioutil.ReadDir(config.RepositoryDir)\n\tfor _, entry := range dirs {\n\t\tif entry.IsDir() {\n\t\t\tresult = append(result, Repository{entry.Name()})\n\t\t}\n\t}\n\treturn &result\n}\n\nfunc (repo *Repository) Create() error {\n\tcmd := exec.Command(\"git\", \"init\", \"--bare\", repo.Name)\n\tcmd.Dir = config.RepositoryDir\n\treturn cmd.Run()\n}\n\nfunc (repo *Repository) Path() string {\n\treturn config.RepositoryDir + \"/\" + repo.Name\n}\n\n\n\nfunc (repo *Repository) Exists() bool ", "output": "{\n\tif _, err := os.Stat(repo.Path()); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package v1alpha1\n\ntype errorList struct {\n\terrors []error\n}\n\n\n\n\n\nfunc (l *errorList) addErrors(errs []error) []error {\n\tfor _, err := range errs {\n\t\tl.addError(err)\n\t}\n\n\treturn l.errors\n}\n\nfunc (l *errorList) addError(err error) []error ", "output": "{\n\tif err == nil {\n\t\treturn l.errors\n\t}\n\n\tl.errors = append(l.errors, err)\n\treturn l.errors\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSGlueCrawler_Schedule struct {\n\n\tScheduleExpression string `json:\"ScheduleExpression,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\n\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSGlueCrawler_Schedule) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::Glue::Crawler.Schedule\"\n}"} {"input": "package wxshield2\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestPacket_InsertNamed(t *testing.T) {\n\tn := Packet{}\n\twant := `INSERT INTO test (timestamp, pressure, tempa, tempb, humidity, ptemp, htemp, battery, indx) VALUES (:timestamp, :pressure, :tempa, :tempb, :humidity, :ptemp, :htemp, :battery, :indx)`\n\tif n.InsertNamed(\"test\") != want {\n\t\tt.Errorf(\"Got %q not %q\", n.InsertNamed(\"test\"), want)\n\t}\n}\n\nfunc TestPacket_Jsonable(t *testing.T) {\n\tn := Packet{}\n\t*n.Jsonable().Battery = 1.0\n\tif n.Battery.Float64 != 1.0 {\n\t\tt.Errorf(\"Should be able to set values\")\n\t}\n}\n\nfunc TestPacket_InsertEroteme(t *testing.T) ", "output": "{\n\tn := Packet{}\n\twant := `INSERT INTO test (timestamp, pressure, tempa, tempb, humidity, ptemp, htemp, battery, indx) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`\n\tif n.InsertEroteme(\"test\") != want {\n\t\tt.Errorf(\"Got %q not %q\", n.InsertEroteme(\"test\"), want)\n\t}\n}"} {"input": "package vanity\n\nimport (\n\t\"github.com/gogo/protobuf/gogoproto\"\n\t\"github.com/gogo/protobuf/proto\"\n\tdescriptor \"github.com/gogo/protobuf/protoc-gen-gogo/descriptor\"\n)\n\n\n\nfunc SetBoolEnumOption(extension *proto.ExtensionDesc, value bool) func(enum *descriptor.EnumDescriptorProto) {\n\treturn func(enum *descriptor.EnumDescriptorProto) {\n\t\tif EnumHasBoolExtension(enum, extension) {\n\t\t\treturn\n\t\t}\n\t\tif enum.Options == nil {\n\t\t\tenum.Options = &descriptor.EnumOptions{}\n\t\t}\n\t\tif err := proto.SetExtension(enum.Options, extension, &value); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\nfunc TurnOffGoEnumPrefix(enum *descriptor.EnumDescriptorProto) {\n\tSetBoolEnumOption(gogoproto.E_GoprotoEnumPrefix, false)(enum)\n}\n\nfunc TurnOffGoEnumStringer(enum *descriptor.EnumDescriptorProto) {\n\tSetBoolEnumOption(gogoproto.E_GoprotoEnumStringer, false)(enum)\n}\n\nfunc TurnOnEnumStringer(enum *descriptor.EnumDescriptorProto) {\n\tSetBoolEnumOption(gogoproto.E_EnumStringer, true)(enum)\n}\n\nfunc EnumHasBoolExtension(enum *descriptor.EnumDescriptorProto, extension *proto.ExtensionDesc) bool ", "output": "{\n\tif enum.Options == nil {\n\t\treturn false\n\t}\n\tvalue, err := proto.GetExtension(enum.Options, extension)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif value == nil {\n\t\treturn false\n\t}\n\tif value.(*bool) == nil {\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package vagrant\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t\"github.com/hashicorp/otto/ui\"\n)\n\n\n\ntype SSHCache struct {\n\tPath string\n\n\tVagrant *Vagrant\n}\n\n\n\n\n\n\nfunc (c *SSHCache) Exec(cacheOkay bool) error {\n\tif _, err := os.Stat(c.Path); err == nil {\n\t\tcmd := exec.Command(\"ssh\", \"-F\", c.Path, \"default\")\n\t\tcmd.Stdin = os.Stdin\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t\tif err := cmd.Start(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := cmd.Wait(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn c.Vagrant.Execute(\"ssh\")\n}\n\n\nfunc (c *SSHCache) Cache() error {\n\tvar mockUi ui.Mock\n\tvagrant := *c.Vagrant\n\tvagrant.Ui = &mockUi\n\tif err := vagrant.Execute(\"ssh-config\"); err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(c.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tfor _, raw := range mockUi.RawBuf {\n\t\tif _, err := io.Copy(f, strings.NewReader(raw)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc (c *SSHCache) Delete() error ", "output": "{\n\tos.Remove(c.Path)\n\treturn nil\n}"} {"input": "package k8s\n\nimport (\n\t\"fmt\"\n\t\"github.com/ghodss/yaml\"\n\n\tapi_core_v1 \"k8s.io/api/core/v1\"\n\tapi_extn_v1beta1 \"k8s.io/api/extensions/v1beta1\"\n)\n\n\n\ntype Deployment struct {\n\tYmlInBytes []byte\n}\n\nfunc NewDeployment(b []byte) *Deployment {\n\treturn &Deployment{\n\t\tYmlInBytes: b,\n\t}\n}\n\n\nfunc (m *Deployment) AsExtnV1B1Deployment() (*api_extn_v1beta1.Deployment, error) {\n\tif m.YmlInBytes == nil {\n\t\treturn nil, fmt.Errorf(\"Missing yaml\")\n\t}\n\n\tdeploy := &api_extn_v1beta1.Deployment{}\n\terr := yaml.Unmarshal(m.YmlInBytes, deploy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn deploy, nil\n}\n\n\ntype Service struct {\n\tYmlInBytes []byte\n}\n\nfunc NewService(b []byte) *Service {\n\treturn &Service{\n\t\tYmlInBytes: b,\n\t}\n}\n\n\n\n\nfunc (m *Service) AsCoreV1Service() (*api_core_v1.Service, error) ", "output": "{\n\tif m.YmlInBytes == nil {\n\t\treturn nil, fmt.Errorf(\"Missing yaml\")\n\t}\n\n\tsvc := &api_core_v1.Service{}\n\terr := yaml.Unmarshal(m.YmlInBytes, svc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn svc, nil\n}"} {"input": "package comment\n\nimport (\n\t\"time\"\n\n\t\"github.com/google/go-github/github\"\n)\n\n\ntype Matcher interface {\n\tMatch(comment *github.IssueComment) bool\n}\n\n\ntype CreatedAfter time.Time\n\n\n\n\n\ntype CreatedBefore time.Time\n\n\nfunc (c CreatedBefore) Match(comment *github.IssueComment) bool {\n\tif comment == nil || comment.CreatedAt == nil {\n\t\treturn false\n\t}\n\treturn comment.CreatedAt.Before(time.Time(c))\n}\n\nfunc (c CreatedAfter) Match(comment *github.IssueComment) bool ", "output": "{\n\tif comment == nil || comment.CreatedAt == nil {\n\t\treturn false\n\t}\n\treturn comment.CreatedAt.After(time.Time(c))\n}"} {"input": "package messengers\n\n\ntype FakeMessenger struct {\n\tBaseMessenger\n}\n\n\n\nfunc (self *FakeMessenger) Post(messege string) bool ", "output": "{\n\treturn true\n}"} {"input": "package clients\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n\n\t\"github.com/VolantMQ/volantmq/subscriber\"\n)\n\nvar subCount int32 = 0\n\n\n\ntype container struct {\n\tlock sync.Mutex\n\trmLock sync.RWMutex\n\tses *session\n\texpiry atomic.Value\n\tsub *subscriber.Type\n\tremovable bool\n\tremoved bool\n}\n\nfunc (s *container) setRemovable(rm bool) {\n\ts.rmLock.Lock()\n\ts.removable = rm\n\ts.rmLock.Unlock()\n}\n\nfunc (s *container) acquire() {\n\ts.lock.Lock()\n}\n\n\n\nfunc (s *container) session() *session {\n\tdefer s.rmLock.Unlock()\n\ts.rmLock.Lock()\n\treturn s.ses\n}\n\nfunc (s *container) swap(from *container) *container {\n\ts.ses = from.ses\n\n\ts.ses.idLock = &s.lock\n\n\treturn s\n}\n\nfunc (s *container) subscriber(cleanStart bool, c subscriber.Config) *subscriber.Type {\n\tif cleanStart && s.sub != nil {\n\t\ts.sub.Offline(true)\n\t\ts.sub = nil\n\t}\n\n\tif s.sub == nil {\n\t\ts.sub = subscriber.New(c)\n\t}\n\n\treturn s.sub\n}\n\nfunc (s *container) release() ", "output": "{\n\ts.lock.Unlock()\n}"} {"input": "package awspublicip\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/dan-v/awslambdaproxy/pkg/server/publicip\"\n\t\"io/ioutil\"\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst (\n\tDefaultHTTPTimeout = time.Second * 10\n\tAWSProviderURL = \"http://checkip.amazonaws.com/\"\n)\n\ntype PublicIPClient struct {\n\tproviderURL string\n\thttpClient *http.Client\n}\n\nfunc New() *PublicIPClient {\n\treturn &PublicIPClient{\n\t\tproviderURL: AWSProviderURL,\n\t\thttpClient: &http.Client{\n\t\t\tTimeout: DefaultHTTPTimeout,\n\t\t},\n\t}\n}\n\n\n\nfunc (p *PublicIPClient) ProviderURL() string {\n\treturn p.providerURL\n}\n\nfunc (p *PublicIPClient) GetIP() (string, error) ", "output": "{\n\tresp, err := p.httpClient.Get(p.providerURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"http request to get ip address from %v failed: %w\", p.providerURL, err)\n\t}\n\tdefer resp.Body.Close()\n\n\tbuf, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"reading response body from %v failed: %w\", p.providerURL, err)\n\t}\n\n\tip := string(bytes.TrimSpace(buf))\n\tif net.ParseIP(ip) == nil {\n\t\treturn \"\", fmt.Errorf(\"unable to parse ip %v: %w\",\n\t\t\tpublicip.ErrInvalidIPAddress, publicip.ErrInvalidIPAddress)\n\t}\n\treturn ip, nil\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/labstack/echo\"\n)\n\n\ntype Error struct {\n\tMessage string `json:\"message\"`\n}\n\n\nfunc OK(c echo.Context, payload interface{}) error {\n\treturn c.JSON(http.StatusOK, payload)\n}\n\n\nfunc Created(c echo.Context, payload interface{}) error {\n\treturn c.JSON(http.StatusCreated, payload)\n}\n\n\nfunc NoContent(c echo.Context) error {\n\treturn c.NoContent(http.StatusNoContent)\n}\n\n\nfunc BadRequest(c echo.Context, msg string) error {\n\treturn c.JSON(http.StatusBadRequest, Error{msg})\n}\n\n\nfunc NotFound(c echo.Context) error {\n\treturn c.JSON(http.StatusNotFound, Error{\"Resource not found\"})\n}\n\n\nfunc Conflict(c echo.Context, msg string) error {\n\treturn c.JSON(http.StatusConflict, Error{msg})\n}\n\n\n\n\n\n\nfunc InternalServerError(c echo.Context, err error) error {\n\tlog.WithFields(log.Fields{\n\t\t\"request_id\": RequestID(c),\n\t}).Error(err)\n\n\treturn c.JSON(http.StatusInternalServerError, Error{\"Oops! Something went wrong\"})\n}\n\nfunc Invalid(c echo.Context, msg string) error ", "output": "{\n\treturn c.JSON(422, Error{msg})\n}"} {"input": "package execcmd\n\nimport (\n\t\"io\"\n\n\t\"github.com/docker/docker/pkg/term\"\n\t\"github.com/sirupsen/logrus\"\n)\n\n\n\ntype OutStream struct {\n\tCommonStream\n\tout io.Writer\n}\n\nfunc (o *OutStream) Write(p []byte) (int, error) {\n\treturn o.out.Write(p)\n}\n\n\n\n\n\nfunc NewOutStream(out io.Writer) io.Writer {\n\tif out == nil {\n\t\treturn nil\n\t}\n\n\tfd, isTerminal := term.GetFdInfo(out)\n\treturn &OutStream{CommonStream: CommonStream{fd: fd, isTerminal: isTerminal}, out: out}\n}\n\nfunc (o *OutStream) GetTtySize() (uint, uint) ", "output": "{\n\tif !o.isTerminal {\n\t\treturn 0, 0\n\t}\n\tws, err := term.GetWinsize(o.fd)\n\tif err != nil {\n\t\tlogrus.Debugf(\"Error getting size: %s\", err)\n\t\tif ws == nil {\n\t\t\treturn 0, 0\n\t\t}\n\t}\n\treturn uint(ws.Height), uint(ws.Width)\n}"} {"input": "package cloudinfo\n\nimport (\n\t\"k8s.io/klog/v2\"\n\n\tinfo \"github.com/google/cadvisor/info/v1\"\n)\n\ntype CloudInfo interface {\n\tGetCloudProvider() info.CloudProvider\n\tGetInstanceType() info.InstanceType\n\tGetInstanceID() info.InstanceID\n}\n\n\ntype CloudProvider interface {\n\tIsActiveProvider() bool\n\tGetInstanceType() info.InstanceType\n\tGetInstanceID() info.InstanceID\n}\n\nvar providers = map[info.CloudProvider]CloudProvider{}\n\n\nfunc RegisterCloudProvider(name info.CloudProvider, provider CloudProvider) {\n\tif _, alreadyRegistered := providers[name]; alreadyRegistered {\n\t\tklog.Warningf(\"Duplicate registration of CloudProvider %s\", name)\n\t}\n\tproviders[name] = provider\n}\n\ntype realCloudInfo struct {\n\tcloudProvider info.CloudProvider\n\tinstanceType info.InstanceType\n\tinstanceID info.InstanceID\n}\n\nfunc NewRealCloudInfo() CloudInfo {\n\tfor name, provider := range providers {\n\t\tif provider.IsActiveProvider() {\n\t\t\treturn &realCloudInfo{\n\t\t\t\tcloudProvider: name,\n\t\t\t\tinstanceType: provider.GetInstanceType(),\n\t\t\t\tinstanceID: provider.GetInstanceID(),\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &realCloudInfo{\n\t\tcloudProvider: info.UnknownProvider,\n\t\tinstanceType: info.UnknownInstance,\n\t\tinstanceID: info.UnNamedInstance,\n\t}\n}\n\nfunc (i *realCloudInfo) GetCloudProvider() info.CloudProvider {\n\treturn i.cloudProvider\n}\n\nfunc (i *realCloudInfo) GetInstanceType() info.InstanceType {\n\treturn i.instanceType\n}\n\n\n\nfunc (i *realCloudInfo) GetInstanceID() info.InstanceID ", "output": "{\n\treturn i.instanceID\n}"} {"input": "package client\n\nimport (\n\trestclient \"k8s.io/client-go/rest\"\n\tkapi \"k8s.io/kubernetes/pkg/api\"\n\n\tdeployapi \"github.com/openshift/origin/pkg/apps/apis/apps\"\n)\n\n\ntype DeploymentLogsNamespacer interface {\n\tDeploymentLogs(namespace string) DeploymentLogInterface\n}\n\n\ntype DeploymentLogInterface interface {\n\tGet(name string, opts deployapi.DeploymentLogOptions) *restclient.Request\n}\n\n\ntype deploymentLogs struct {\n\tr *Client\n\tns string\n}\n\n\nfunc newDeploymentLogs(c *Client, namespace string) *deploymentLogs {\n\treturn &deploymentLogs{\n\t\tr: c,\n\t\tns: namespace,\n\t}\n}\n\n\n\n\nfunc (c *deploymentLogs) Get(name string, opts deployapi.DeploymentLogOptions) *restclient.Request ", "output": "{\n\treturn c.r.Get().Namespace(c.ns).Resource(\"deploymentConfigs\").Name(name).SubResource(\"log\").VersionedParams(&opts, kapi.ParameterCodec)\n}"} {"input": "package macaron\n\nimport (\n\t\"net/http\"\n\t\"reflect\"\n\n\t\"gitea.com/macaron/inject\"\n)\n\n\n\n\n\ntype ReturnHandler func(*Context, []reflect.Value)\n\n\n\nfunc isError(val reflect.Value) bool {\n\t_, ok := val.Interface().(error)\n\treturn ok\n}\n\nfunc isByteSlice(val reflect.Value) bool {\n\treturn val.Kind() == reflect.Slice && val.Type().Elem().Kind() == reflect.Uint8\n}\n\nfunc defaultReturnHandler() ReturnHandler {\n\treturn func(ctx *Context, vals []reflect.Value) {\n\t\trv := ctx.GetVal(inject.InterfaceOf((*http.ResponseWriter)(nil)))\n\t\tresp := rv.Interface().(http.ResponseWriter)\n\t\tvar respVal reflect.Value\n\t\tif len(vals) > 1 && vals[0].Kind() == reflect.Int {\n\t\t\tresp.WriteHeader(int(vals[0].Int()))\n\t\t\trespVal = vals[1]\n\t\t} else if len(vals) > 0 {\n\t\t\trespVal = vals[0]\n\n\t\t\tif isError(respVal) {\n\t\t\t\terr := respVal.Interface().(error)\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx.internalServerError(ctx, err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t} else if canDeref(respVal) {\n\t\t\t\tif respVal.IsNil() {\n\t\t\t\t\treturn \n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif canDeref(respVal) {\n\t\t\trespVal = respVal.Elem()\n\t\t}\n\t\tif isByteSlice(respVal) {\n\t\t\t_, _ = resp.Write(respVal.Bytes())\n\t\t} else {\n\t\t\t_, _ = resp.Write([]byte(respVal.String()))\n\t\t}\n\t}\n}\n\nfunc canDeref(val reflect.Value) bool ", "output": "{\n\treturn val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr\n}"} {"input": "package hashing_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/vlad-doru/experimento/backend/utils/hashing\"\n\t\"github.com/vlad-doru/experimento/backend/utils/test\"\n)\n\n\n\nfunc BenchmarkHash(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\thashing.Hash(\"experimento\")\n\t}\n}\n\nfunc BenchmarkHashFloat(b *testing.B) {\n\tseed := hashing.Hash(\"experimento\")\n\tfor i := 0; i < b.N; i++ {\n\t\thashing.HashFloat(\"hashing_id\", seed)\n\t}\n}\n\nfunc TestHashFloat(t *testing.T) ", "output": "{\n\tseed := hashing.Hash(\"experimento\")\n\ttest.SetSeed(1) \n\tfor i := 0; i < 100000; i++ {\n\t\tid := test.RandString(6, 10)\n\t\tf := hashing.HashFloat(id, seed)\n\t\tassert.True(t, (f >= 0) && (f < 1),\n\t\t\t\"Invariant violation of the hash function for id %s: %v\", id, f)\n\t}\n}"} {"input": "package netx\n\nimport (\n\t\"io\"\n\n\t\"github.com/simia-tech/netx/value\"\n)\n\ntype multicast struct {\n\tlistener io.ReadCloser\n\tconn io.WriteCloser\n}\n\n\n\nfunc ListenAndDialMulticast(network, readAddress, writeAddress string, options ...value.Option) (io.ReadWriteCloser, error) {\n\tlistener, err := ListenMulticast(network, readAddress, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn, err := DialMulticast(network, writeAddress, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &multicast{listener: listener, conn: conn}, nil\n}\n\nfunc (m *multicast) Read(buffer []byte) (int, error) {\n\treturn m.listener.Read(buffer)\n}\n\n\n\nfunc (m *multicast) Close() error {\n\tif err := m.listener.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := m.conn.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (m *multicast) Write(buffer []byte) (int, error) ", "output": "{\n\treturn m.conn.Write(buffer)\n}"} {"input": "package lago\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype ScopedLogger struct {\n\tlog Logger\n\tscp string\n\tfmt string\n}\n\n\n\n\n\nfunc (l *ScopedLogger) Errorf(format string, args ...interface{}) {\n\tl.log.Errorf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\n\nfunc (l *ScopedLogger) Infof(format string, args ...interface{}) {\n\tl.log.Infof(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\n\nfunc (l *ScopedLogger) Warnf(format string, args ...interface{}) {\n\tl.log.Warnf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\n\nfunc (l *ScopedLogger) Fatalf(format string, args ...interface{}) {\n\tl.log.Fatalf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\nfunc intToStringWithSign(i int) string {\n\ta := strconv.Itoa(i)\n\ts := \"+\"\n\tif i < 0 {\n\t\ts = \"-\"\n\t}\n\ta = s + a\n\n\treturn a\n}\n\nfunc NewScopedLogger(log Logger, scope string, padding int) *ScopedLogger ", "output": "{\n\tformat := \"-%\" + intToStringWithSign(padding) + \"s: %s\"\n\n\tl := &ScopedLogger{\n\t\tlog: log,\n\t\tscp: scope,\n\t\tfmt: format,\n\t}\n\n\treturn l\n}"} {"input": "package cluster\n\nimport (\n\t\"errors\"\n\n\t\"github.com/cloustone/sentel/pkg/config\"\n\tsd \"github.com/cloustone/sentel/pkg/service-discovery\"\n)\n\nconst (\n\tServiceStateNone = \"none\"\n\tServiceStateStarted = \"started\"\n\tServiceStateStoped = \"stoped\"\n)\n\nconst (\n\tDeployModeLocal = \"local\"\n\tDeployModeKubernetes = \"kubernetes\"\n\tDeployModeSwarm = \"swarm\"\n)\n\ntype ServiceEndpoint struct {\n\tVirtualIP string\n\tPort uint32\n}\n\ntype ServiceSpec struct {\n\tTenantId string\n\tServiceName string\n\tImage string\n\tNetworkId string\n\tReplicas int32\n\tEnvironment []string\n}\n\ntype ServiceIntrospec struct {\n\tServiceName string\n\tServiceId string\n\tServiceState string\n\tEndpoints []ServiceEndpoint\n}\n\n\ntype ClusterManager interface {\n\tSetServiceDiscovery(sd.ServiceDiscovery)\n\tCreateNetwork(name string) (string, error)\n\tRemoveNetwork(name string) error\n\tCreateService(spec ServiceSpec) (string, error)\n\tRemoveService(serviceId string) error\n\tUpdateService(serviceId string, spec ServiceSpec) error\n\tIntrospectService(serviceId string) (ServiceIntrospec, error)\n}\n\n\n\n\nfunc New(c config.Config) (ClusterManager, error) ", "output": "{\n\tif mode, err := c.String(\"deploy-mode\"); err == nil {\n\t\tswitch mode {\n\t\tcase DeployModeKubernetes:\n\t\t\treturn newK8sCluster(c)\n\t\tcase DeployModeSwarm:\n\t\t\treturn newSwarmCluster(c)\n\t\tcase DeployModeLocal:\n\t\t\treturn newLocalCluster(c)\n\t\t}\n\t}\n\treturn nil, errors.New(\"invalid deploy mode\")\n}"} {"input": "package augeas\n\n\n\nimport \"C\"\nimport (\n\t\"fmt\"\n)\n\n\n\n\ntype ErrorCode int\n\n\nconst (\n\tCouldNotInitialize ErrorCode = -2\n\tNoMatch = -1\n\n\tNoError = 0\n\n\tENOMEM\n\n\tEINTERNAL\n\n\tEPATHX\n\n\tENOMATCH\n\n\tEMMATCH\n\n\tESYNTAX\n\n\tENOLENS\n\n\tEMXFM\n\n\tENOSPAN\n\n\tEMVDESC\n\n\tECMDRUN\n\n\tEBADARG\n)\n\n\ntype Error struct {\n\tCode ErrorCode\n\n\tMessage string\n\n\tMinorMessage string\n\n\tDetails string\n}\n\nfunc (err Error) Error() string {\n\treturn fmt.Sprintf(\"Message: %s - Minor message: %s - Details: %s\",\n\t\terr.Message, err.MinorMessage, err.Details)\n}\n\n\n\nfunc (a Augeas) errorCode() ErrorCode {\n\treturn ErrorCode(C.aug_error(a.handle))\n}\n\nfunc (a Augeas) errorMessage() string {\n\treturn C.GoString(C.aug_error_message(a.handle))\n}\n\nfunc (a Augeas) errorMinorMessage() string {\n\treturn C.GoString(C.aug_error_minor_message(a.handle))\n}\n\nfunc (a Augeas) errorDetails() string {\n\treturn C.GoString(C.aug_error_details(a.handle))\n}\n\nfunc (a Augeas) error() error ", "output": "{\n\tcode := a.errorCode()\n\tif code == NoError {\n\t\treturn nil\n\t}\n\n\treturn Error{code, a.errorMessage(), a.errorMinorMessage(), a.errorDetails()}\n}"} {"input": "package fake\n\nimport (\n\tv2beta1 \"k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeAutoscalingV2beta1 struct {\n\t*testing.Fake\n}\n\n\n\n\n\nfunc (c *FakeAutoscalingV2beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeAutoscalingV2beta1) HorizontalPodAutoscalers(namespace string) v2beta1.HorizontalPodAutoscalerInterface ", "output": "{\n\treturn &FakeHorizontalPodAutoscalers{c, namespace}\n}"} {"input": "package service_test\n\nimport (\n\t\"context\"\n\n\tservice \"cloud.google.com/go/orchestration/airflow/service/apiv1\"\n\t\"google.golang.org/api/iterator\"\n\tservicepb \"google.golang.org/genproto/googleapis/cloud/orchestration/airflow/service/v1\"\n)\n\n\n\nfunc ExampleImageVersionsClient_ListImageVersions() {\n\tctx := context.Background()\n\tc, err := service.NewImageVersionsClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\treq := &servicepb.ListImageVersionsRequest{\n\t}\n\tit := c.ListImageVersions(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}\n\nfunc ExampleNewImageVersionsClient() ", "output": "{\n\tctx := context.Background()\n\tc, err := service.NewImageVersionsClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\t_ = c\n}"} {"input": "package gconv_test\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\ntype testStruct struct {\n\tId int\n\tName string\n}\n\nvar ptr = []*testStruct{\n\t{\n\t\tId: 1,\n\t\tName: \"test1\",\n\t},\n\t{\n\t\tId: 2,\n\t\tName: \"test2\",\n\t},\n}\n\nfunc init() {\n\tfor i := 1; i <= 1000; i++ {\n\t\tptr = append(ptr, &testStruct{\n\t\t\tId: 1,\n\t\t\tName: \"test1\",\n\t\t})\n\t}\n}\n\nfunc Benchmark_Reflect_ValueOf(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr)\n\t}\n}\n\n\n\nfunc Benchmark_Reflect_ValueOf_Interface(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr).Interface()\n\t}\n}\n\nfunc Benchmark_Reflect_ValueOf_Len(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr).Len()\n\t}\n}\n\nfunc Benchmark_Reflect_ValueOf_Kind(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr).Kind()\n\t}\n}"} {"input": "package apn\n\n\ntype ApnEnv int\n\nconst (\n\tTest = iota \n\tSandbox\n\tProduction\n)\n\nfunc envString(env ApnEnv) (envString string) {\n\tif env == Test {\n\t\tenvString = \"test\"\n\t} else if env == Sandbox {\n\t\tenvString = \"sandbox\"\n\t} else if env == Production {\n\t\tenvString = \"production\"\n\t}\n\treturn\n}\n\n\n\n\nvar queues []Queue = make([]Queue, 10)\n\nfunc envObject(envString string) (env ApnEnv) ", "output": "{\n\tif envString == \"test\" {\n\t\tenv = Test\n\t} else if envString == \"sandbox\" {\n\t\tenv = Sandbox\n\t} else if envString == \"production\" {\n\t\tenv = Production\n\t}\n\treturn\n}"} {"input": "package pool\n\nimport (\n\n)\n\ntype ObjPool struct {\n\tobj chan interface{}\n\tNew func() interface{}\n}\n\nfunc NewObjPool() *ObjPool {\n\treturn &ObjPool{\n\t\tobj: make(chan interface{}, 200),\n\t}\n}\n\n\n\nfunc (p *ObjPool) Put(o interface{}) {\n\tselect {\n\tcase p.obj <- o:\n\tdefault:\n\t}\n}\n\nfunc (p *ObjPool) Get() interface{} ", "output": "{\n\tselect {\n\tcase o := <-p.obj:\n\t\treturn o\n\tdefault:\n\t\treturn p.New()\n\t}\n}"} {"input": "package tracing\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"github.com/containous/alice\"\n\t\"github.com/containous/traefik/middlewares\"\n\t\"github.com/containous/traefik/tracing\"\n\t\"github.com/opentracing/opentracing-go\"\n\t\"github.com/opentracing/opentracing-go/ext\"\n)\n\nconst (\n\tentryPointTypeName = \"TracingEntryPoint\"\n)\n\n\nfunc NewEntryPoint(ctx context.Context, t *tracing.Tracing, entryPointName string, next http.Handler) http.Handler {\n\tmiddlewares.GetLogger(ctx, \"tracing\", entryPointTypeName).Debug(\"Creating middleware\")\n\n\treturn &entryPointMiddleware{\n\t\tentryPoint: entryPointName,\n\t\tTracing: t,\n\t\tnext: next,\n\t}\n}\n\ntype entryPointMiddleware struct {\n\t*tracing.Tracing\n\tentryPoint string\n\tnext http.Handler\n}\n\nfunc (e *entryPointMiddleware) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tspanCtx, _ := e.Extract(opentracing.HTTPHeaders, tracing.HTTPHeadersCarrier(req.Header))\n\n\tspan, req, finish := e.StartSpanf(req, ext.SpanKindRPCServerEnum, \"EntryPoint\", []string{e.entryPoint, req.Host}, \" \", ext.RPCServerOption(spanCtx))\n\tdefer finish()\n\n\text.Component.Set(span, e.ServiceName)\n\ttracing.LogRequest(span, req)\n\n\treq = req.WithContext(tracing.WithTracing(req.Context(), e.Tracing))\n\n\trecorder := newStatusCodeRecoder(rw, http.StatusOK)\n\te.next.ServeHTTP(recorder, req)\n\n\ttracing.LogResponseCode(span, recorder.Status())\n}\n\n\n\n\nfunc WrapEntryPointHandler(ctx context.Context, tracer *tracing.Tracing, entryPointName string) alice.Constructor ", "output": "{\n\treturn func(next http.Handler) (http.Handler, error) {\n\t\treturn NewEntryPoint(ctx, tracer, entryPointName, next), nil\n\t}\n}"} {"input": "package main\n\nimport \"testing\"\n\n\n\nfunc TestDistance(t *testing.T) ", "output": "{\n\ttests := []struct {\n\t\tinput string\n\t\tdistance int\n\t}{\n\t\t{\"ne,ne,ne\", 3},\n\t\t{\"ne,ne,sw,sw\", 0},\n\t\t{\"ne,ne,s,s\", 2},\n\t\t{\"se,sw,se,sw,sw\", 3},\n\t}\n\n\tfor i, test := range tests {\n\t\tm, _ := positionChild(test.input)\n\t\tdistance := distance(m)\n\t\tif distance != test.distance {\n\t\t\tt.Errorf(\"tests[%d] expected %d got %d\", i, test.distance, distance)\n\t\t}\n\t}\n}"} {"input": "package metrics\n\nimport (\n\t\"github.com/cloudfoundry/dropsonde/metric_sender\"\n)\n\nvar metricSender metric_sender.MetricSender\nvar metricBatcher MetricBatcher\n\ntype MetricBatcher interface {\n\tBatchIncrementCounter(name string)\n\tBatchAddCounter(name string, delta uint64)\n\tClose()\n}\n\n\nfunc Initialize(ms metric_sender.MetricSender, mb MetricBatcher) {\n\tif metricBatcher != nil {\n\t\tmetricBatcher.Close()\n\t}\n\tmetricSender = ms\n\tmetricBatcher = mb\n}\n\n\nfunc Close() {\n\tmetricBatcher.Close()\n}\n\n\n\nfunc SendValue(name string, value float64, unit string) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.SendValue(name, value, unit)\n}\n\n\n\n\nfunc IncrementCounter(name string) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.IncrementCounter(name)\n}\n\n\n\n\n\n\n\n\n\nfunc AddToCounter(name string, delta uint64) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.AddToCounter(name, delta)\n}\n\n\n\n\nfunc BatchAddCounter(name string, delta uint64) {\n\tif metricBatcher == nil {\n\t\treturn\n\t}\n\tmetricBatcher.BatchAddCounter(name, delta)\n}\n\n\n\n\n\nfunc SendContainerMetric(applicationId string, instanceIndex int32, cpuPercentage float64, memoryBytes uint64, diskBytes uint64) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\n\treturn metricSender.SendContainerMetric(applicationId, instanceIndex, cpuPercentage, memoryBytes, diskBytes)\n}\n\nfunc BatchIncrementCounter(name string) ", "output": "{\n\tif metricBatcher == nil {\n\t\treturn\n\t}\n\tmetricBatcher.BatchIncrementCounter(name)\n}"} {"input": "package resolvers\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/emwalker/digraph/cmd/frontend/loaders\"\n\t\"github.com/emwalker/digraph/cmd/frontend/models\"\n\t\"github.com/volatiletech/sqlboiler/queries/qm\"\n)\n\ntype organizationResolver struct {\n\t*Resolver\n}\n\nfunc getOrganizationLoader(ctx context.Context) *loaders.OrganizationLoader {\n\treturn ctx.Value(loaders.OrganizationLoaderKey).(*loaders.OrganizationLoader)\n}\n\n\n\n\nfunc (r *organizationResolver) CreatedAt(_ context.Context, org *models.Organization) (string, error) {\n\treturn org.CreatedAt.Format(time.RFC3339), nil\n}\n\n\nfunc (r *organizationResolver) DefaultRepository(ctx context.Context, org *models.Organization) (*models.Repository, error) {\n\trepo, err := org.Repositories(qm.Where(\"system\")).One(ctx, r.DB)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn repo, nil\n}\n\n\nfunc (r *organizationResolver) ResourcePath(\n\t_ context.Context, org *models.Organization,\n) (string, error) {\n\treturn \"/organizations/\" + org.ID, nil\n}\n\n\nfunc (r *organizationResolver) UpdatedAt(\n\t_ context.Context, org *models.Organization,\n) (string, error) {\n\treturn org.UpdatedAt.Format(time.RFC3339), nil\n}\n\nfunc fetchOrganization(ctx context.Context, organizationID string) (*models.Organization, error) ", "output": "{\n\tloader := getOrganizationLoader(ctx)\n\torg, err := loader.Load(organizationID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn org, nil\n}"} {"input": "package authmethod\n\nimport (\n\t\"sync\"\n\n\t\"github.com/hashicorp/consul/agent/structs\"\n)\n\ntype syncCache struct {\n\tlock sync.RWMutex\n\tcache authMethodCache\n}\n\nfunc NewCache() Cache {\n\tc := &syncCache{}\n\tc.cache.init()\n\treturn c\n}\n\nfunc (c *syncCache) GetValidator(method *structs.ACLAuthMethod) (uint64, Validator, bool) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\treturn c.cache.GetValidator(method)\n}\n\nfunc (c *syncCache) PutValidatorIfNewer(method *structs.ACLAuthMethod, validator Validator, idx uint64) Validator {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\treturn c.cache.PutValidatorIfNewer(method, validator, idx)\n}\n\n\n\nfunc (c *syncCache) Purge() ", "output": "{\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tc.cache.Purge()\n}"} {"input": "package pools \n\nimport (\n\t\"bytes\"\n\t\"sync\"\n)\n\n\n\nvar bytesBuffer = sync.Pool{\n\tNew: func() interface{} { return new(bytes.Buffer) },\n}\n\n\n\n\n\n\nfunc PutBuffer(buf *bytes.Buffer) {\n\tbytesBuffer.Put(buf)\n}\n\nfunc BytesBuffer() *bytes.Buffer ", "output": "{\n\tbuf := bytesBuffer.Get().(*bytes.Buffer)\n\tbuf.Reset()\n\treturn buf\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"github.com/ghodss/yaml\"\n)\n\nfunc readState(path string) (*Config, error) {\n\tdat, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := new(Config)\n\terr = yaml.Unmarshal(dat, config)\n\treturn config, err\n}\n\n\n\nfunc saveState(path string, config *Config) error ", "output": "{\n\tevents := *config.Thermostat.Events\n\tconfig.Thermostat.Events = nil\n\n\tdat, err := yaml.Marshal(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfig.Thermostat.Events = &events\n\n\treturn ioutil.WriteFile(path, dat, os.FileMode(int(0660)))\n}"} {"input": "package usbid\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestLoaded(t *testing.T) {\n\tif got, min := len(Vendors), 1000; got < min {\n\t\tt.Errorf(\"%d vendors loaded, want at least %d\", got, min)\n\t}\n\tif got, min := len(Classes), 10; got < min {\n\t\tt.Errorf(\"%d classes loaded, want at least %d\", got, min)\n\t}\n}\n\ntype handler struct{}\n\nfunc (handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tf, err := os.Open(testDBPath)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"Open(%q): %v\", testDBPath, err)\n\t\treturn\n\t}\n\tdefer f.Close()\n\tw.Header().Set(\"content-type\", \"text/plain\")\n\tio.Copy(w, f)\n}\n\n\n\nfunc TestLoadFromURLError(t *testing.T) {\n\torigV, origC := Vendors, Classes\n\tdefer func() { Vendors, Classes = origV, origC }()\n\n\ts := httptest.NewServer(http.NotFoundHandler())\n\tdefer s.Close()\n\n\tts := LastUpdate\n\terr := LoadFromURL(s.URL)\n\tif err == nil {\n\t\tt.Fatalf(\"LoadFromURL(%q): err is nil, want not nil\", s.URL)\n\t}\n\tif LastUpdate != ts {\n\t\tt.Errorf(\"LastUpdate was unexpectedly updated when LoadFromURL failed\")\n\t}\n}\n\nfunc TestLoadFromURL(t *testing.T) ", "output": "{\n\torigV, origC := Vendors, Classes\n\tVendors, Classes = nil, nil\n\tdefer func() { Vendors, Classes = origV, origC }()\n\n\ts := httptest.NewServer(handler{})\n\tdefer s.Close()\n\n\terr := LoadFromURL(s.URL)\n\tif err != nil {\n\t\tt.Fatalf(\"LoadFromURL(%q): got unexpected error: %v\", s.URL, err)\n\t}\n\tif !reflect.DeepEqual(Vendors, testDBVendors) {\n\t\tt.Errorf(\"LoadFromURL Vendors:\\ngot: %v\\nwant: %v\", Vendors, testDBVendors)\n\t}\n}"} {"input": "package utils\n\nimport \"bufio\"\nimport \"strings\"\nimport \"os\"\n\n\ntype Hosts map[string]string\n\n\n\nvar HostMap Hosts\n\n\n\nfunc LoadHostsFile(filepath string) (Hosts, error) {\n\tfile, err := os.Open(filepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tscanner := bufio.NewScanner(file)\n\tm := make(Hosts)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tips := strings.Split(line, \" \")\n\t\tm[ips[0]] = ips[1]\n\t}\n\treturn m, nil\n}\n\n\n\nfunc ResolveIp(ip string) string ", "output": "{\n\tfqdn, ok := HostMap[ip]\n\tif ok {\n\t\treturn fqdn\n\t} else {\n\t\treturn ip\n\t}\n}"} {"input": "package pitchfork\n\n\n\nimport (\n\t\"errors\"\n)\n\ntype OAuth_Auth struct {\n\tClientID string `label:\"Client ID\" pfset:\"nobody\" pfget:\"none\"`\n\tScope string `label:\"Scope\" pfset:\"nobody\" pfget:\"none\"`\n\tRType string `label:\"Request Type\" pfset:\"nobody\" pfget:\"none\"`\n\tRedirect string `label:\"Redirect URL\" pfset:\"nobody\" pfget:\"none\"`\n\tAuth string `label:\"Authorize\" pftype:\"submit\"`\n\tDeny string `label:\"Deny\" pftype:\"submit\" htmlclass:\"deny\"`\n}\n\ntype OAuth2Claims struct {\n\tJWTClaims\n\tClientID string `json:\"oa_client_id\"`\n\tScope string `json:\"oa_scope\"`\n\tRType string `json:\"oa_rtype,omitempty\"`\n\tRedirect string `json:\"oa_redirect,omitempty\"`\n}\n\n\n\nfunc OAuth2_AuthToken_Check(tok string) (claims *OAuth2Claims, err error) {\n\t_, err = Token_Parse(tok, \"oauth_auth\", claims)\n\treturn\n}\n\nfunc OAuth2_AccessToken_New(ctx PfCtx, client_id string, scope string) (tok string, err error) {\n\tif !ctx.IsLoggedIn() {\n\t\ttok = \"\"\n\t\terr = errors.New(\"Not authenticated\")\n\t\treturn\n\t}\n\n\tclaims := &OAuth2Claims{}\n\tclaims.ClientID = client_id\n\tclaims.Scope = scope\n\n\tusername := ctx.TheUser().GetUserName()\n\n\ttoken := Token_New(\"oauth_access\", username, TOKEN_EXPIRATIONMINUTES, claims)\n\n\ttok, err = token.Sign()\n\treturn\n}\n\nfunc OAuth2_AuthToken_New(ctx PfCtx, o OAuth_Auth) (tok string, err error) ", "output": "{\n\tif !ctx.IsLoggedIn() {\n\t\ttok = \"\"\n\t\terr = errors.New(\"Not authenticated\")\n\t\treturn\n\t}\n\n\tclaims := &OAuth2Claims{}\n\tclaims.ClientID = o.ClientID\n\tclaims.Scope = o.Scope\n\tclaims.RType = o.RType\n\tclaims.Redirect = o.Redirect\n\n\tusername := ctx.TheUser().GetUserName()\n\n\ttoken := Token_New(\"oauth_auth\", username, 1, claims)\n\ttok, err = token.Sign()\n\treturn\n}"} {"input": "package camelcase\n\nimport (\n\t\"bytes\"\n\t\"unicode/utf8\"\n\n\t\"github.com/blevesearch/bleve/analysis\"\n\t\"github.com/blevesearch/bleve/registry\"\n)\n\nconst Name = \"camelCase\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype CamelCaseFilter struct{}\n\n\n\nfunc (f *CamelCaseFilter) Filter(input analysis.TokenStream) analysis.TokenStream {\n\trv := make(analysis.TokenStream, 0, len(input))\n\n\tnextPosition := 1\n\tfor _, token := range input {\n\t\truneCount := utf8.RuneCount(token.Term)\n\t\trunes := bytes.Runes(token.Term)\n\n\t\tp := NewParser(runeCount, nextPosition, token.Start)\n\t\tfor i := 0; i < runeCount; i++ {\n\t\t\tif i+1 >= runeCount {\n\t\t\t\tp.Push(runes[i], nil)\n\t\t\t} else {\n\t\t\t\tp.Push(runes[i], &runes[i+1])\n\t\t\t}\n\t\t}\n\t\trv = append(rv, p.FlushTokens()...)\n\t\tnextPosition = p.NextPosition()\n\t}\n\treturn rv\n}\n\nfunc CamelCaseFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) {\n\treturn NewCamelCaseFilter(), nil\n}\n\nfunc init() {\n\tregistry.RegisterTokenFilter(Name, CamelCaseFilterConstructor)\n}\n\nfunc NewCamelCaseFilter() *CamelCaseFilter ", "output": "{\n\treturn &CamelCaseFilter{}\n}"} {"input": "package testing\n\n\n\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n\tclientset \"k8s.io/kubernetes/pkg/client/clientset_generated/clientset\"\n\tkubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\"\n\tcontainertest \"k8s.io/kubernetes/pkg/kubelet/container/testing\"\n)\n\ntype fakeNetworkHost struct {\n\tfakeNamespaceGetter\n\tkubeClient clientset.Interface\n\tLegacy bool\n\tRuntime *containertest.FakeRuntime\n}\n\nfunc NewFakeHost(kubeClient clientset.Interface) *fakeNetworkHost {\n\thost := &fakeNetworkHost{kubeClient: kubeClient, Legacy: true, Runtime: &containertest.FakeRuntime{}}\n\treturn host\n}\n\nfunc (fnh *fakeNetworkHost) GetPodByName(name, namespace string) (*v1.Pod, bool) {\n\treturn nil, false\n}\n\n\n\nfunc (nh *fakeNetworkHost) GetRuntime() kubecontainer.Runtime {\n\treturn nh.Runtime\n}\n\nfunc (nh *fakeNetworkHost) SupportsLegacyFeatures() bool {\n\treturn nh.Legacy\n}\n\ntype fakeNamespaceGetter struct {\n\tns string\n}\n\nfunc (nh *fakeNamespaceGetter) GetNetNS(containerID string) (string, error) {\n\treturn nh.ns, nil\n}\n\nfunc (fnh *fakeNetworkHost) GetKubeClient() clientset.Interface ", "output": "{\n\treturn nil\n}"} {"input": "package gmime\n\n\nimport \"C\"\n\ntype GMimeParamsCallback func(name string, value string)\n\ntype Parametrized interface {\n\tSetParameter(name, value string)\n\tParameter(name string) string\n\tForEachParam(callback GMimeParamsCallback)\n}\n\n\n\nfunc forEachParam(params *C.GMimeParam, callback GMimeParamsCallback) ", "output": "{\n\tfor params != nil {\n\t\tcName := C.g_mime_param_get_name(params)\n\t\tname := C.GoString(cName)\n\t\tcValue := C.g_mime_param_get_value(params)\n\t\tvalue := C.GoString(cValue)\n\t\tcallback(name, value)\n\t\tparams = C.g_mime_param_next(params)\n\t}\n}"} {"input": "package cmd\n\nimport (\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/minio/mc/pkg/httptracer\"\n\t\"github.com/minio/pkg/console\"\n)\n\n\ntype traceV4 struct{}\n\n\nfunc newTraceV4() httptracer.HTTPTracer {\n\treturn traceV4{}\n}\n\n\nfunc (t traceV4) Request(req *http.Request) (err error) {\n\torigAuth := req.Header.Get(\"Authorization\")\n\n\tprintTrace := func() error {\n\t\treqTrace, rerr := httputil.DumpRequestOut(req, false) \n\t\tif rerr == nil {\n\t\t\tconsole.Debug(string(reqTrace))\n\t\t}\n\t\treturn rerr\n\t}\n\n\tif strings.TrimSpace(origAuth) != \"\" {\n\n\t\tregCred := regexp.MustCompile(\"Credential=([A-Z0-9]+)/\")\n\t\tnewAuth := regCred.ReplaceAllString(origAuth, \"Credential=**REDACTED**/\")\n\n\t\tregSign := regexp.MustCompile(\"Signature=([[0-9a-f]+)\")\n\t\tnewAuth = regSign.ReplaceAllString(newAuth, \"Signature=**REDACTED**\")\n\n\t\treq.Header.Set(\"Authorization\", newAuth)\n\n\t\terr = printTrace()\n\n\t\treq.Header.Set(\"Authorization\", origAuth)\n\t} else {\n\t\terr = printTrace()\n\t}\n\treturn err\n}\n\n\n\n\nfunc (t traceV4) Response(resp *http.Response) (err error) ", "output": "{\n\tvar respTrace []byte\n\tif resp.StatusCode != http.StatusOK &&\n\t\tresp.StatusCode != http.StatusPartialContent &&\n\t\tresp.StatusCode != http.StatusNoContent {\n\t\trespTrace, err = httputil.DumpResponse(resp, true)\n\t} else {\n\t\trespTrace, err = httputil.DumpResponse(resp, false)\n\t}\n\tif err == nil {\n\t\tconsole.Debug(string(respTrace))\n\t}\n\n\tif resp.TLS != nil {\n\t\tprintTLSCertInfo(resp.TLS)\n\t}\n\n\treturn err\n}"} {"input": "package variant\n\nimport (\n\t\"github.com/go-ole/com/errors\"\n\t\"github.com/go-ole/com/types\"\n)\n\nfunc VariantInit(v *types.Variant) error {\n\treturn errors.NotImplementedError\n}\n\nfunc VariantClear(v *types.Variant) error {\n\treturn errors.NotImplementedError\n}\n\n\n\nfunc VariantChangeTypeEx(source *types.Variant, locale uint32, flags uint16, vt types.VariantType) *types.Variant {\n\treturn source\n}\n\nfunc VariantCopy(source *types.Variant) *types.Variant {\n\treturn source\n}\n\nfunc VariantCopyIndirect(source *types.Variant) *types.Variant {\n\treturn source\n}\n\nfunc VariantChangeType(source *types.Variant, flags uint16, vt types.VariantType) *types.Variant ", "output": "{\n\treturn source\n}"} {"input": "package arangolite\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"net/http\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc longRequest(w http.ResponseWriter, r *http.Request) {\n\tio.WriteString(w, \"Waiting 2 seconds...\")\n\ttime.Sleep(200 * time.Millisecond)\n\tpanic(\"The request was not canceled\")\n}\n\n\n\nfunc TestSendCanBeCanceled(t *testing.T) {\n\trunWebserver()\n\n\tclient := &http.Client{}\n\treq, _ := http.NewRequest(\"GET\", \"http://localhost:9999\", nil)\n\n\tsender := basicSender{}\n\tparent := context.Background()\n\tctx, cancel := context.WithTimeout(parent, 100*time.Millisecond)\n\tdefer cancel()\n\n\tresp, err := sender.Send(ctx, client, req)\n\n\tassertEqual(t, err.Error(), \"the database HTTP request failed: Get http://localhost:9999: context deadline exceeded\")\n\tassertTrue(t, resp == nil, \"The response of a canceled request should be nil\")\n}\n\nfunc runWebserver() ", "output": "{\n\tgo func() {\n\t\thttp.HandleFunc(\"/\", longRequest)\n\t\thttp.ListenAndServe(\":9999\", nil)\n\t}()\n}"} {"input": "package chacha20poly1305\n\n\n\nfunc (c *chacha20poly1305) open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {\n\treturn c.openGeneric(dst, nonce, ciphertext, additionalData)\n}\n\nfunc (c *chacha20poly1305) seal(dst, nonce, plaintext, additionalData []byte) []byte ", "output": "{\n\treturn c.sealGeneric(dst, nonce, plaintext, additionalData)\n}"} {"input": "package client\n\nimport (\n\tatlantis \"atlantis/common\"\n\t. \"atlantis/manager/constant\"\n)\n\ntype ManagerRPCClient struct {\n\tatlantis.RPCClient\n\tUser string\n\tSecrets map[string]string\n}\n\ntype AuthedArg interface {\n\tSetCredentials(string, string)\n}\n\nfunc (r *ManagerRPCClient) CallAuthed(name string, arg AuthedArg, reply interface{}) error {\n\treturn r.CallAuthedMulti(name, arg, 0, reply)\n}\n\n\n\nfunc NewManagerRPCClient(hostAndPort string) *atlantis.RPCClient {\n\treturn atlantis.NewRPCClient(hostAndPort, \"ManagerRPC\", ManagerRPCVersion, true)\n}\n\nfunc NewManagerRPCClientWithConfig(cfg []atlantis.RPCServerOpts) *atlantis.RPCClient {\n\treturn atlantis.NewMultiRPCClientWithConfig(cfg, \"ManagerRPC\", ManagerRPCVersion, true)\n}\n\nfunc (r *ManagerRPCClient) CallAuthedMulti(name string, arg AuthedArg, region int, reply interface{}) error ", "output": "{\n\targ.SetCredentials(r.User, r.Secrets[r.Opts[region].RPCHostAndPort()])\n\n\treturn r.RPCClient.CallMulti(name, arg, region, reply)\n}"} {"input": "package stats\n\nimport (\n\t\"time\"\n\n\t\"sync\"\n\n\t\"github.com/paulbellamy/ratecounter\"\n)\n\nvar lock = sync.RWMutex{}\n\ntype stat struct {\n\treadReq *ratecounter.RateCounter\n\twriteReq *ratecounter.RateCounter\n}\n\n\n\ntype namespaceStatMap map[string]stat\n\nvar golbalNamespaceStat namespaceStatMap\n\nfunc init() {\n\tgolbalNamespaceStat = namespaceStatMap{}\n}\n\n\nfunc AddNamespace(label string) {\n\t_, ok := golbalNamespaceStat[label]\n\tif ok {\n\t\treturn\n\t}\n\n\tgolbalNamespaceStat[label] = newStat()\n\treturn\n}\n\n\nfunc IncrRead(label string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tstat, ok := golbalNamespaceStat[label]\n\tif !ok {\n\t\tAddNamespace(label)\n\t\tstat = golbalNamespaceStat[label]\n\t}\n\n\tstat.readReq.Incr(1)\n}\n\n\nfunc IncrWrite(label string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tstat, ok := golbalNamespaceStat[label]\n\tif !ok {\n\t\tAddNamespace(label)\n\t\tstat = golbalNamespaceStat[label]\n\t}\n\n\tstat.writeReq.Incr(1)\n}\n\n\nfunc Rate(label string) (read, write int64) {\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\tstat, ok := golbalNamespaceStat[label]\n\tif !ok {\n\t\tAddNamespace(label)\n\t\tstat = golbalNamespaceStat[label]\n\t}\n\n\treturn stat.readReq.Rate(), stat.writeReq.Rate()\n}\n\nfunc newStat() stat ", "output": "{\n\treturn stat{\n\t\treadReq: ratecounter.NewRateCounter(time.Hour),\n\t\twriteReq: ratecounter.NewRateCounter(time.Hour),\n\t}\n}"} {"input": "package texas\n\ntype SeatResultList []*SeatResult\n\ntype SeatResult struct {\n\tm_seat *SeatPlayer\n\tpot_idx int\n\tcard_type int\n\tcard_list CardDataList\n}\n\nfunc NewSeatResult(seat *SeatPlayer, cards []int16) *SeatResult {\n\tthis := new(SeatResult)\n\tthis.m_seat = seat\n\tthis.pot_idx = seat.m_pot_point\n\tthis.card_type, this.card_list = CardTypeOfTexas(cards)\n\treturn this\n}\n\n\n\n\nfunc (this SeatResultList) Len() int {\n\treturn len(this)\n}\n\n\nfunc (this SeatResultList) Less(i, j int) bool {\n\treturn this[i].card_type > this[j].card_type\n}\n\nfunc (this SeatResultList) Swap(i, j int) {\n\ttemp := this[i]\n\tthis[i] = this[j]\n\tthis[j] = temp\n}\n\nfunc (this *SeatResult) Trace() ", "output": "{\n\tprintln(\"玩家:\", this.m_seat.m_seat_id, POKER_TYPE_STR[this.card_type], TraceBigCards(this.card_list))\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype OpenpitrixListReleaseResponse struct {\n\n\tReleaseSet OpenpitrixListReleaseResponseReleaseSet `json:\"release_set\"`\n}\n\n\n\n\n\nfunc (m *OpenpitrixListReleaseResponse) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *OpenpitrixListReleaseResponse) UnmarshalBinary(b []byte) error {\n\tvar res OpenpitrixListReleaseResponse\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *OpenpitrixListReleaseResponse) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package gemini\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/thrasher-corp/gocryptotrader/exchanges/request\"\n\t\"golang.org/x/time/rate\"\n)\n\nconst (\n\tgeminiRateInterval = time.Minute\n\tgeminiAuthRate = 600\n\tgeminiUnauthRate = 120\n)\n\n\ntype RateLimit struct {\n\tAuth *rate.Limiter\n\tUnAuth *rate.Limiter\n}\n\n\n\n\n\nfunc SetRateLimit() *RateLimit {\n\treturn &RateLimit{\n\t\tAuth: request.NewRateLimit(geminiRateInterval, geminiAuthRate),\n\t\tUnAuth: request.NewRateLimit(geminiRateInterval, geminiUnauthRate),\n\t}\n}\n\nfunc (r *RateLimit) Limit(ctx context.Context, f request.EndpointLimit) error ", "output": "{\n\tif f == request.Auth {\n\t\treturn r.Auth.Wait(ctx)\n\t}\n\treturn r.UnAuth.Wait(ctx)\n}"} {"input": "package configuration\n\nimport (\n\t\"testing\"\n\n\t\"k8s.io/api/admissionregistration/v1alpha1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n)\n\ntype disabledMutatingWebhookConfigLister struct{}\n\nfunc (l *disabledMutatingWebhookConfigLister) List(options metav1.ListOptions) (*v1alpha1.MutatingWebhookConfigurationList, error) {\n\treturn nil, errors.NewNotFound(schema.GroupResource{Group: \"admissionregistration\", Resource: \"MutatingWebhookConfigurations\"}, \"\")\n}\n\n\nfunc TestMutatingWebhookConfigDisabled(t *testing.T) ", "output": "{\n\tmanager := NewMutatingWebhookConfigurationManager(&disabledMutatingWebhookConfigLister{})\n\tmanager.sync()\n\t_, err := manager.Webhooks()\n\tif err.Error() != ErrDisabled.Error() {\n\t\tt.Errorf(\"expected %v, got %v\", ErrDisabled, err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/gorilla/websocket\"\n)\n\nvar upgrader = websocket.Upgrader{} \n\n\nfunc index(w http.ResponseWriter, res *http.Request) {\n\tt, _ := template.ParseFiles(\"index.html\")\n\tt.Execute(w, nil)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/\", index)\n\thttp.HandleFunc(\"/echo\", Echo)\n\tgo NotifyClient()\n\tif err := http.ListenAndServe(\":1234\", nil); err != nil {\n\t\tlog.Fatal(\"ListenAndServe:\", err)\n\t}\n}\n\nfunc Echo(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Print(\"upgrade:\", err)\n\t\treturn\n\t}\n\tfmt.Println(\"start websocket!\")\n\tsession := NewSession(ws)\n\tdefer func() {\n\t\tDelSession(session)\n\t\tfmt.Println(\"close websocket!\")\n\t}()\n\tgo session.Send()\n\tsession.handler()\n}"} {"input": "package client\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/thecodeteam/rexray/libstorage/api/types\"\n)\n\n\ntype client struct {\n\thttp.Client\n\thost string\n\tlogRequests bool\n\tlogResponses bool\n\tserverName string\n}\n\n\nfunc New(host string, transport *http.Transport) types.APIClient {\n\treturn &client{\n\t\tClient: http.Client{\n\t\t\tTransport: transport,\n\t\t},\n\t\thost: host,\n\t}\n}\n\nfunc (c *client) ServerName() string {\n\treturn c.serverName\n}\n\nfunc (c *client) LogRequests(enabled bool) {\n\tc.logRequests = enabled\n}\n\n\n\nfunc (c *client) LogResponses(enabled bool) ", "output": "{\n\tc.logResponses = enabled\n}"} {"input": "package jaeger_test\n\nimport (\n\t\"log\"\n\n\t\"go.opencensus.io/exporter/jaeger\"\n\t\"go.opencensus.io/trace\"\n)\n\nfunc ExampleNewExporter_collector() {\n\texporter, err := jaeger.NewExporter(jaeger.Options{\n\t\tEndpoint: \"http:localhost:14268\",\n\t\tProcess: jaeger.Process{\n\t\t\tServiceName: \"trace-demo\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttrace.RegisterExporter(exporter)\n}\n\n\n\n\n\n\nfunc ExampleNewExporter_processTags() {\n\texporter, err := jaeger.NewExporter(jaeger.Options{\n\t\tAgentEndpoint: \"localhost:6831\",\n\t\tProcess: jaeger.Process{\n\t\t\tServiceName: \"trace-demo\",\n\t\t\tTags: []jaeger.Tag{\n\t\t\t\tjaeger.StringTag(\"ip\", \"127.0.0.1\"),\n\t\t\t\tjaeger.BoolTag(\"demo\", true),\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttrace.RegisterExporter(exporter)\n}\n\nfunc ExampleNewExporter_agent() ", "output": "{\n\texporter, err := jaeger.NewExporter(jaeger.Options{\n\t\tAgentEndpoint: \"localhost:6831\",\n\t\tProcess: jaeger.Process{\n\t\t\tServiceName: \"trace-demo\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttrace.RegisterExporter(exporter)\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\nconst (\n\tMaxFilterAddDataSize = 520\n)\n\n\n\n\n\n\ntype MsgFilterAdd struct {\n\tData []byte\n}\n\n\n\nfunc (msg *MsgFilterAdd) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filteradd message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterAdd.BtcDecode\", str)\n\t}\n\n\tvar err error\n\tmsg.Data, err = ReadVarBytes(r, pver, MaxFilterAddDataSize,\n\t\t\"filteradd data\")\n\treturn err\n}\n\n\n\n\n\n\n\nfunc (msg *MsgFilterAdd) Command() string {\n\treturn CmdFilterAdd\n}\n\n\n\nfunc (msg *MsgFilterAdd) MaxPayloadLength(pver uint32) uint32 {\n\treturn uint32(VarIntSerializeSize(MaxFilterAddDataSize)) +\n\t\tMaxFilterAddDataSize\n}\n\n\n\nfunc NewMsgFilterAdd(data []byte) *MsgFilterAdd {\n\treturn &MsgFilterAdd{\n\t\tData: data,\n\t}\n}\n\nfunc (msg *MsgFilterAdd) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error ", "output": "{\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filteradd message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterAdd.BtcEncode\", str)\n\t}\n\n\tsize := len(msg.Data)\n\tif size > MaxFilterAddDataSize {\n\t\tstr := fmt.Sprintf(\"filteradd size too large for message \"+\n\t\t\t\"[size %v, max %v]\", size, MaxFilterAddDataSize)\n\t\treturn messageError(\"MsgFilterAdd.BtcEncode\", str)\n\t}\n\n\treturn WriteVarBytes(w, pver, msg.Data)\n}"} {"input": "package certdata\n\nimport (\n\t\"crypto/x509\"\n\t\"fmt\"\n)\n\n\n\ntype Data struct {\n\tCert *x509.Certificate\n\tIssuer *x509.Certificate\n\tType string\n}\n\n\n\n\n\n\nfunc (d *Data) SetIssuer(der []byte) error {\n\tvar err error\n\td.Issuer, err = x509.ParseCertificate(der)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc Load(der []byte) (*Data, error) ", "output": "{\n\tvar err error\n\n\td := new(Data)\n\td.Cert, err = x509.ParseCertificate(der)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = d.setCertificateType(); err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\treturn d, nil\n}"} {"input": "package ubuntu\n\nimport (\n\t\"github.com/megamsys/megdc/templates\"\n\t\"github.com/megamsys/urknall\"\n)\n\nvar ubuntunilavuremove *UbuntuNilavuRemove\n\nfunc init() {\n\tubuntunilavuremove = &UbuntuNilavuRemove{}\n\ttemplates.Register(\"UbuntuNilavuRemove\", ubuntunilavuremove)\n}\n\ntype UbuntuNilavuRemove struct{}\n\nfunc (tpl *UbuntuNilavuRemove) Render(p urknall.Package) {\n\tp.AddTemplate(\"nilavu\", &UbuntuNilavuRemoveTemplate{})\n}\n\nfunc (tpl *UbuntuNilavuRemove) Options(t *templates.Template) {\n}\n\nfunc (tpl *UbuntuNilavuRemove) Run(target urknall.Target) error {\n\treturn urknall.Run(target, &UbuntuNilavuRemove{})\n}\n\ntype UbuntuNilavuRemoveTemplate struct{}\n\n\n\nfunc (m *UbuntuNilavuRemoveTemplate) Render(pkg urknall.Package) ", "output": "{\n\tpkg.AddCommands(\"verticenilavu\",\n\t\tRemovePackage(\"verticenilavu\"),\n\t\tRemovePackages(\"\"),\n\t\tPurgePackages(\"verticenilavu\"),\n\t\tShell(\"dpkg --get-selections megam*\"),\n\t)\n\tpkg.AddCommands(\"nilavu-clean\",\n\t\tShell(\"rm -r /var/lib/urknall/nilavu*\"),\n\t)\n}"} {"input": "package utils\n\nimport (\n\t\"encoding/binary\"\n)\n\nconst (\n\tMaxMsgLen = 65536\n)\n\n\ntype SimpleMsg struct {\n\tMsgSize uint32\n\tMsgSender uint32\n\tMsgReceiver uint32 \n\tMsgBody []byte \n}\n\n\n\n\n\n\nfunc MakeNewSimpleMsg() *SimpleMsg {\n\treturn &SimpleMsg{\n\t\tMsgSize: 0,\n\t\tMsgSender: 0,\n\t\tMsgReceiver: 0,\n\t\tMsgBody: []byte{},\n\t}\n}\n\n\n\n\n\nfunc (this *SimpleMsg) FromString(fromId int, toId int, msg string) *SimpleMsg {\n\tthis.MsgSender = uint32(fromId)\n\tthis.MsgReceiver = uint32(toId)\n\tdataFrom := make([]byte, 4)\n\tdataTo := make([]byte, 4)\n\tdataSize := make([]byte, 4)\n\tdataBody := []byte(msg)\n\tthis.MsgSize = uint32(len(dataBody) + 12)\n\tbinary.LittleEndian.PutUint32(dataFrom, this.MsgSender)\n\tbinary.LittleEndian.PutUint32(dataTo, this.MsgReceiver)\n\tbinary.LittleEndian.PutUint32(dataSize, this.MsgSize)\n\tdata := []byte{}\n\tdata = append(data, dataSize...)\n\tdata = append(data, dataFrom...)\n\tdata = append(data, dataTo...)\n\tdata = append(data, dataBody...)\n\tthis.MsgBody = data\n\treturn this\n}\n\n\nfunc (this *SimpleMsg) ToData() []byte {\n\treturn this.MsgBody\n}\n\n\nfunc (this *SimpleMsg) ToString() string {\n\treturn string(this.MsgBody[12:])\n}\n\n\nfunc (this *SimpleMsg) EnCode() {\n}\n\n\nfunc (this *SimpleMsg) DeCode() {\n}\n\nfunc (this *SimpleMsg) FromBytes(buf []byte) *SimpleMsg ", "output": "{\n\tthis.MsgSize = 0\n\tthis.MsgSender = 0\n\tthis.MsgReceiver = 0\n\tthis.MsgBody = []byte{}\n\tif len(buf) < 12 {\n\t\treturn this\n\t} else {\n\t\tthis.MsgSize = binary.LittleEndian.Uint32(buf[0:4])\n\t\tif int(this.MsgSize) == len(buf) {\n\t\t\tthis.MsgSender = binary.LittleEndian.Uint32(buf[4:8])\n\t\t\tthis.MsgReceiver = binary.LittleEndian.Uint32(buf[8:12])\n\t\t\tthis.MsgBody = append(this.MsgBody, buf...)\n\t\t} else {\n\t\t\tthis.MsgSize = 0\n\t\t}\n\t}\n\treturn this\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\n\n\n\n\ntype MsgMemPool struct{}\n\n\n\nfunc (msg *MsgMemPool) BtcDecode(r io.Reader, pver uint32) error {\n\tif pver < BIP0035Version {\n\t\tstr := fmt.Sprintf(\"mempool message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgMemPool.BtcDecode\", str)\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (msg *MsgMemPool) BtcEncode(w io.Writer, pver uint32) error {\n\tif pver < BIP0035Version {\n\t\tstr := fmt.Sprintf(\"mempool message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgMemPool.BtcEncode\", str)\n\t}\n\n\treturn nil\n}\n\n\n\n\n\n\n\nfunc (msg *MsgMemPool) MaxPayloadLength(pver uint32) uint32 {\n\treturn 0\n}\n\n\n\nfunc NewMsgMemPool() *MsgMemPool {\n\treturn &MsgMemPool{}\n}\n\nfunc (msg *MsgMemPool) Command() string ", "output": "{\n\treturn CmdMemPool\n}"} {"input": "package bytealg\n\n\nfunc Count(b []byte, c byte) int\n\n\nfunc CountString(s string, c byte) int\n\n\nfunc countGeneric(b []byte, c byte) int {\n\tn := 0\n\tfor _, x := range b {\n\t\tif x == c {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n\n\nfunc countGenericString(s string, c byte) int ", "output": "{\n\tn := 0\n\tfor i := 0; i < len(s); i++ {\n\t\tif s[i] == c {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}"} {"input": "package example\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc foo() int {\n\tn := 1\n\n\tfor i := 0; i < 3; i++ {\n\t\tif i == 0 {\n\t\t\tn++\n\t\t} else if i == 1 {\n\t\t\tn += 2\n\t\t} else {\n\t\t\tn += 3\n\t\t}\n\n\t\tn++\n\t}\n\n\tif n < 0 {\n\t\tn = 0\n\t}\n\n\tn++\n\n\tn += bar()\n\n\tbar()\n\n\tswitch {\n\tcase n < 20:\n\t\tn++\n\tcase n > 20:\n\t\tn--\n\tdefault:\n\t\tn = 0\n\t\tfmt.Println(n)\n\t\tfunc() {}()\n\t}\n\n\tvar x = 0\n\tx++\n\n\treturn n\n}\n\n\n\nfunc statementRemoveStructInitialization() (a http.Header, b error) {\n\tvar err error\n\n\ta, b = http.Header{}, err\n\n\treturn\n}\n\nfunc statementRemoveStringArrayMap() map[string][]string {\n\thash := \"ok\"\n\tvar hdr = make(map[string][]string)\n\n\thdr[\"Hash\"] = []string{hash}\n\n\treturn hdr\n}\n\nfunc bar() int ", "output": "{\n\treturn 4\n}"} {"input": "package xray\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"goa.design/goa/v3/middleware\"\n\t\"goa.design/goa/v3/middleware/xray\"\n)\n\n\n\ntype xrayTransport struct {\n\twrapped http.RoundTripper\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc WrapTransport(rt http.RoundTripper) http.RoundTripper {\n\treturn &xrayTransport{rt}\n}\n\n\n\n\n\nfunc (t *xrayTransport) RoundTrip(req *http.Request) (*http.Response, error) ", "output": "{\n\tctx := req.Context()\n\tseg := ctx.Value(xray.SegKey)\n\tif seg == nil {\n\t\treturn t.wrapped.RoundTrip(req)\n\t}\n\n\ts := seg.(*xray.Segment)\n\tsub := s.NewSubsegment(req.URL.Host)\n\ths := &HTTPSegment{Segment: sub}\n\ths.RecordRequest(req, \"remote\")\n\ths.SubmitInProgress()\n\tdefer hs.Close()\n\n\tctx = middleware.WithSpan(ctx, hs.TraceID, hs.ID, hs.ParentID)\n\treq = req.WithContext(context.WithValue(ctx, xray.SegKey, hs.Segment))\n\tresp, err := t.wrapped.RoundTrip(req)\n\tif err != nil {\n\t\ths.RecordError(err)\n\t} else {\n\t\ths.RecordResponse(resp)\n\t}\n\treturn resp, err\n}"} {"input": "package monator\n\nimport (\n \"time\"\n \"bytes\"\n \"encoding/json\"\n)\n\ntype CheckDuration time.Duration\n\nfunc (d CheckDuration) Hours() float64 {\n return time.Duration(d).Hours()\n}\n\nfunc (d CheckDuration) Minutes() float64 {\n return time.Duration(d).Minutes()\n}\n\nfunc (d CheckDuration) Nanoseconds() int64 {\n return time.Duration(d).Nanoseconds()\n}\n\nfunc (d CheckDuration) Seconds() float64 {\n return time.Duration(d).Seconds()\n}\n\nfunc (d CheckDuration) Milliseconds() int64 {\n return time.Duration(d).Nanoseconds() / int64(time.Millisecond)\n}\n\n\n\n\nfunc (d *CheckDuration) UnmarshalJSON(data []byte) error {\n b := bytes.NewBuffer(data)\n dec := json.NewDecoder(b)\n\n var s string\n\n if err := dec.Decode(&s); err != nil {\n return err\n }\n if duration, err := time.ParseDuration(s); err != nil {\n return err\n } else {\n *d = CheckDuration(duration)\n }\n\n return nil\n}\n\nfunc (d CheckDuration) String() string ", "output": "{\n \n rounded := ((time.Duration(d)).Nanoseconds() / int64(time.Millisecond)) * int64(time.Millisecond)\n return time.Duration(rounded).String()\n}"} {"input": "package instance\n\nimport (\n\t\"net\"\n)\n\n\n\ntype AddressType string\n\nconst (\n\tHostName AddressType = \"hostname\"\n\tIpv4Address AddressType = \"ipv4\"\n\tIpv6Address AddressType = \"ipv6\"\n)\n\n\n\n\n\ntype NetworkScope string\n\nconst (\n\tNetworkUnknown NetworkScope = \"\"\n\tNetworkPublic NetworkScope = \"public\"\n\tNetworkCloudLocal NetworkScope = \"local-cloud\"\n\tNetworkMachineLocal NetworkScope = \"local-machine\"\n)\n\n\n\ntype Address struct {\n\tValue string\n\tType AddressType\n\tNetworkName string\n\tNetworkScope\n}\n\n\n\nfunc NewAddress(value string) Address {\n\taddresstype := deriveAddressType(value)\n\treturn Address{value, addresstype, \"\", NetworkUnknown}\n}\n\n\n\n\nfunc SelectPublicAddress(addresses []Address) string {\n\tmostpublic := \"\"\n\tfor _, addr := range addresses {\n\t\tif addr.Type != Ipv6Address {\n\t\t\tswitch addr.NetworkScope {\n\t\t\tcase NetworkPublic:\n\t\t\t\treturn addr.Value\n\t\t\tcase NetworkCloudLocal, NetworkUnknown:\n\t\t\t\tmostpublic = addr.Value\n\t\t\t}\n\t\t}\n\t}\n\treturn mostpublic\n}\n\nfunc deriveAddressType(value string) AddressType ", "output": "{\n\tip := net.ParseIP(value)\n\tif ip != nil {\n\t\tif ip.To4() != nil {\n\t\t\treturn Ipv4Address\n\t\t}\n\t\tif ip.To16() != nil {\n\t\t\treturn Ipv6Address\n\t\t}\n\t\tpanic(\"Unknown form of IP address\")\n\t}\n\treturn HostName\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n)\n\nvar cfgFile string\n\n\nvar RootCmd = &cobra.Command{\n\tUse: \"evergrid-go\",\n\tShort: \"Evergrid infrastructure components and simulator\",\n\tLong: `Evergrid infrastructure components and simulator`,\n}\n\n\n\nfunc Execute() {\n\tif err := RootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}\n\n\n\n\nfunc initConfig() {\n\tif cfgFile != \"\" { \n\t\tviper.SetConfigFile(cfgFile)\n\t}\n\n\tviper.SetConfigName(\".evergrid-go\") \n\tviper.AddConfigPath(\"$HOME\") \n\tviper.AutomaticEnv() \n\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t}\n}\n\nfunc init() ", "output": "{\n\tcobra.OnInitialize(initConfig)\n\n\n\tRootCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n}"} {"input": "package youtube\n\nimport (\n\t\"github.com/Go-Docker-Hackathon/team-iDareX/vendor/db/mongo\"\n\t\"labix.org/v2/mgo/bson\"\n\t\"fmt\"\n)\n\nvar WorkQueue = make(chan WorkRequest, 100)\n\n\n\nfunc Collector(url , formatId string) ", "output": "{\n\tC := mongo.Connect()\n\tC.Update(bson.M{\"fetchurl\": url}, bson.M{\"$set\": bson.M{\"status\": 1}}) \n\tfmt.Println(\"mongodb start download\")\n\twork := WorkRequest{ Url: url, FormatId: formatId}\t\n\tWorkQueue <- work\n\n}"} {"input": "package main\n\nimport \"errors\"\n\n\n\ntype Item struct {\n\tId int\n\tPath string\n}\n\ntype Status struct {\n\tStatus string\n\tList []Item\n\tId int\n}\n\nconst (\n\tStateStopped = iota\n\tStatePlaying\n)\n\n\n\nvar items []Item\nvar nextId int\nvar currentTrack int\nvar currentState int\n\n\n\nfunc addItem(path string) (id int) {\n\tid = nextId\n\titems = append(items, Item{Id: nextId, Path: path})\n\tnextId = nextId + 1\n\treturn\n}\n\n\n\nfunc removeItem(id int) (err error) {\n\ti, err := itemIndex(id)\n\tif err != nil {\n\t\treturn\n\t}\n\titems = append(items[:i], items[i+1:]...)\n\treturn\n}\n\nfunc initialize() {\n\titems = []Item{}\n\tnextId = 1\n\tcurrentTrack = 0\n\tcurrentState = StateStopped\n}\n\nfunc itemIndex(id int) (i int, err error) ", "output": "{\n\tfor i = 0; i < len(items); i++ {\n\t\tif items[i].Id == id {\n\t\t\treturn\n\t\t}\n\t}\n\terr = errors.New(\"no item with that id found\")\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\trice \"github.com/GeertJohan/go.rice\"\n\n\t\"git.timschuster.info/rls.moe/catgi/logger\"\n)\n\ntype handlerServeResources struct {\n\trice *rice.Box\n}\n\n\nfunc (h *handlerServeResources) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\tlog := logger.LogFromCtx(\"serverIndex\", r.Context())\n\tlog.Info(\"Loading file from disk: \", r.RequestURI)\n\tdat, err := h.rice.Bytes(r.URL.String())\n\tif err != nil {\n\t\tlog.Error(\"Could not load file from disk: \", err)\n\t\trw.WriteHeader(404)\n\t\tfmt.Fprint(rw, \"index.html not found\")\n\t\treturn\n\t}\n\trw.WriteHeader(200)\n\trw.Header().Add(\"Content-Type\", \"application/html\")\n\trw.Write(dat)\n}\n\nfunc newHandlerServeResources() http.Handler ", "output": "{\n\treturn &handlerServeResources{\n\t\trice: (&rice.Config{\n\t\t\tLocateOrder: []rice.LocateMethod{\n\t\t\t\trice.LocateWorkingDirectory,\n\t\t\t\trice.LocateFS,\n\t\t\t\trice.LocateEmbedded,\n\t\t\t},\n\t\t}).MustFindBox(\"./resources\"),\n\t}\n}"} {"input": "package command\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype VersionCommand struct {\n\tMeta\n\n\tName string\n\tVersion string\n\tRevision string\n}\n\nfunc (c *VersionCommand) Run(args []string) int {\n\tvar versionString bytes.Buffer\n\n\tfmt.Fprintf(&versionString, \"%s v%s\", c.Name, c.Version)\n\tif c.Revision != \"\" {\n\t\tfmt.Fprintf(&versionString, \" (%s)\", c.Revision)\n\t}\n\n\tc.Ui.Output(versionString.String())\n\treturn 0\n}\n\nfunc (c *VersionCommand) Synopsis() string {\n\treturn fmt.Sprintf(\"Print %s version and quit\", c.Name)\n}\n\n\n\nfunc (c *VersionCommand) Help() string ", "output": "{\n\treturn \"\"\n}"} {"input": "package main\n\nimport(\n \"log\"\n \"net/http\"\n \"os\"\n \"encoding/json\"\n \"fmt\"\n)\n\ntype Response struct {\n RouteDesc string\n StopDesc string\n List []struct {\n Sched string\n Est string\n }\n}\n\nfunc printResults(r Response) {\n fmt.Println(\"Route:\", r.RouteDesc)\n fmt.Println(\"Stop:\", r.StopDesc)\n if len(r.List) > 0 {\n for i, list := range r.List {\n fmt.Printf(\"Trip #%d\\n\", i+1)\n fmt.Printf(\"\\tScheduled Time: %s\\n\", list.Sched)\n fmt.Printf(\"\\tEstimated Time: %s\\n\", list.Est)\n }\n } else {\n fmt.Println(\"No available trips found\")\n }\n}\n\n\n\nfunc main() {\n\n checkArgs(os.Args)\n\n stopID := os.Args[1]\n\n url := \"http://www.capmetro.org/planner/s_nextbus2.asp?stopid=\" + stopID + \"&opt=2\"\n\n resp, err := http.Get(url)\n if err != nil {\n log.Fatal(err)\n }\n\n if resp.StatusCode != http.StatusOK {\n log.Fatal(resp.Status)\n }\n\n r := new(Response)\n err = json.NewDecoder(resp.Body).Decode(r)\n\n if err != nil {\n log.Fatal(err)\n }\n\n printResults(*r)\n}\n\nfunc checkArgs(args []string) ", "output": "{\n if len(args) < 2 {\n log.Fatal(\"Usage: cm-nextbus StopID\")\n }\n}"} {"input": "package b\n\nimport \"./a\"\n\nfunc F() {\n\ta.F()\n\ta.Fi()\n}\n\n\n\nfunc Gp() {\n\ta.Gp()\n\ta.Gip()\n}\n\nfunc Hp() {\n\ta.Hp()\n\ta.Hip()\n}\n\nfunc Fp() ", "output": "{\n\ta.Fp()\n\ta.Fip()\n}"} {"input": "package tesseract\n\n\nimport \"C\"\n\n\n\n\nfunc Simple(imgPath string, whitelist string, languages string) string ", "output": "{\n\tp := C.CString(imgPath)\n\tw := C.CString(whitelist)\n\tl := C.CString(languages)\n\n\ts := C.simple(p, w, l)\n\treturn C.GoString(s)\n}"} {"input": "package values\n\nimport \"fmt\"\nimport \"strconv\"\n\n\ntype Int int\n\n\nfunc NewInt(val int, p *int) *Int {\n\t*p = val\n\treturn (*Int)(p)\n}\n\n\nfunc (i *Int) Get() interface{} {\n\treturn int(*i)\n}\n\n\nfunc (i *Int) Set(s string) error {\n\tv, err := strconv.ParseInt(s, 0, 64)\n\t*i = Int(v)\n\treturn err\n}\n\n\n\n\nfunc (i *Int) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%v\", *i)\n}"} {"input": "package esicache\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/corestoreio/errors\"\n)\n\n\n\n\ntype Cacher interface {\n\tSet(key string, value []byte, expiration time.Duration) error\n\tGet(key string) ([]byte, error)\n}\n\n\n\nfunc NewCacher(url string) (Cacher, error) {\n\n\treturn nil, nil\n}\n\n\ntype Caches []Cacher\n\n\nfunc (c Caches) Set(key string, value []byte, expiration time.Duration) error {\n\treturn nil\n}\n\n\nfunc (c Caches) Get(key string) ([]byte, error) {\n\treturn nil, nil\n}\n\n\nvar MainRegistry = ®istry{\n\tcaches: make(map[string]Caches),\n}\n\ntype registry struct {\n\tmu sync.RWMutex\n\tcaches map[string]Caches\n}\n\n\n\n\n\n\nfunc (r *registry) Register(scope, url string) error {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tc, err := NewCacher(url)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"[esikv] NewCacher URL %q\", url)\n\t}\n\n\tif _, ok := r.caches[scope]; !ok {\n\t\tr.caches[scope] = make(Caches, 0, 2)\n\t}\n\tr.caches[scope] = append(r.caches[scope], c)\n\n\treturn nil\n}\n\n\nfunc (r *registry) Len(scope string) int {\n\tr.mu.RLock()\n\tdefer r.mu.RUnlock()\n\treturn len(r.caches[scope])\n}\n\n\nfunc (r *registry) Clear() {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tr.caches = make(map[string]Caches)\n}\n\nfunc (r *registry) Get(ctx context.Context, scope, alias, key string) error ", "output": "{\n\treturn errors.New(\"TODO IMPLEMENT\")\n}"} {"input": "package backingstore\n\nimport (\n\t\"github.com/gostor/gotgt/pkg/api\"\n\t\"github.com/gostor/gotgt/pkg/scsi\"\n)\n\nfunc init() {\n\tscsi.RegisterBackingStore(\"null\", newNull)\n}\n\ntype NullBackingStore struct {\n\tscsi.BaseBackingStore\n}\n\nfunc newNull() (api.BackingStore, error) {\n\treturn &NullBackingStore{\n\t\tBaseBackingStore: scsi.BaseBackingStore{\n\t\t\tName: \"null\",\n\t\t\tDataSize: 0,\n\t\t\tOflagsSupported: 0,\n\t\t},\n\t}, nil\n}\n\nfunc (bs *NullBackingStore) Open(dev *api.SCSILu, path string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Close(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Init(dev *api.SCSILu, Opts string) error {\n\treturn nil\n}\n\n\n\nfunc (bs *NullBackingStore) Size(dev *api.SCSILu) uint64 {\n\treturn 0\n}\n\nfunc (bs *NullBackingStore) Read(offset, tl int64) ([]byte, error) {\n\treturn nil, nil\n}\n\nfunc (bs *NullBackingStore) Write(wbuf []byte, offset int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataSync(offset, tl int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataAdvise(offset, length int64, advise uint32) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Unmap([]api.UnmapBlockDescriptor) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Exit(dev *api.SCSILu) error ", "output": "{\n\treturn nil\n}"} {"input": "package time\n\nimport (\n\t\"errors\"\n\t\"syscall\"\n)\n\n\nfunc interrupt() {\n}\n\n\n\n\n\n\nfunc open(name string) (uintptr, error) {\n\tfd, err := syscall.Open(name, syscall.O_RDONLY, 0)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn uintptr(fd), nil\n}\n\nfunc closefd(fd uintptr) {\n\tsyscall.Close(syscall.Handle(fd))\n}\n\nfunc preadn(fd uintptr, buf []byte, off int) error {\n\twhence := seekStart\n\tif off < 0 {\n\t\twhence = seekEnd\n\t}\n\tif _, err := syscall.Seek(syscall.Handle(fd), int64(off), whence); err != nil {\n\t\treturn err\n\t}\n\tfor len(buf) > 0 {\n\t\tm, err := syscall.Read(syscall.Handle(fd), buf)\n\t\tif m <= 0 {\n\t\t\tif err == nil {\n\t\t\t\treturn errors.New(\"short read\")\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tbuf = buf[m:]\n\t}\n\treturn nil\n}\n\nfunc readFile(name string) ([]byte, error) ", "output": "{\n\tf, err := syscall.Open(name, syscall.O_RDONLY, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer syscall.Close(f)\n\tvar (\n\t\tbuf [4096]byte\n\t\tret []byte\n\t\tn int\n\t)\n\tfor {\n\t\tn, err = syscall.Read(f, buf[:])\n\t\tif n > 0 {\n\t\t\tret = append(ret, buf[:n]...)\n\t\t}\n\t\tif n == 0 || err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ret, err\n}"} {"input": "package complete\n\nimport (\n\t\"testing\"\n\n\tbooking_handler \"github.com/bborbe/booking/handler\"\n\n\t. \"github.com/bborbe/assert\"\n)\n\n\n\nfunc TestImplementsHttpHandler(t *testing.T) ", "output": "{\n\tr := New(nil, nil)\n\tvar i *booking_handler.Handler\n\terr := AssertThat(r, Implements(i))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package int64s\n\nimport \"testing\"\n\n\n\nfunc TestMaxReturnsInputArgWhenGivenOneArgs(t *testing.T) {\n\texpected := int64(7)\n\tif actual := Max(7); expected != actual {\n\t\tt.Error(\"Expected\", expected, \"got\", actual)\n\t}\n}\n\nfunc TestMaxReturnsLargestArgWhenGivenMultipleArgs(t *testing.T) {\n\texpected := int64(9)\n\tif actual := Max(1, 3, 5, 7, 9); expected != actual {\n\t\tt.Error(\"Expected\", expected, \"got\", actual)\n\t}\n}\n\nfunc TestMaxReturnsZeroWhenGivenZeroArgs(t *testing.T) ", "output": "{\n\texpected := int64(0)\n\tif actual := Max(); expected != actual {\n\t\tt.Error(\"Expected\", expected, \"got\", actual)\n\t}\n}"} {"input": "package adapterManager\n\nimport (\n\t\"istio.io/mixer/pkg/adapter\"\n\t\"istio.io/mixer/pkg/pool\"\n)\n\ntype env struct {\n\tlogger adapter.Logger\n\tgp *pool.GoroutinePool\n}\n\n\n\nfunc (e env) Logger() adapter.Logger {\n\treturn e.logger\n}\n\nfunc (e env) ScheduleWork(fn adapter.WorkFunc) {\n\te.gp.ScheduleWork(func() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\t_ = e.Logger().Errorf(\"Adapter worker failed: %v\", r)\n\n\t\t\t}\n\t\t}()\n\n\t\tfn()\n\t})\n}\n\nfunc (e env) ScheduleDaemon(fn adapter.DaemonFunc) {\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\t_ = e.Logger().Errorf(\"Adapter daemon failed: %v\", r)\n\n\t\t\t}\n\t\t}()\n\n\t\tfn()\n\t}()\n}\n\nfunc newEnv(aspect string, gp *pool.GoroutinePool) adapter.Env ", "output": "{\n\treturn env{\n\t\tlogger: newLogger(aspect),\n\t\tgp: gp,\n\t}\n}"} {"input": "package lg\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Stopwatch struct {\n\tstart, stop time.Time\n\tlogger *Logger\n}\n\nfunc (s *Stopwatch) IsStopped() bool { return s.stop.After(s.start) }\nfunc (s *Stopwatch) Stop() {\n\ts.stop = time.Now()\n}\n\nfunc (s *Stopwatch) ElapsedTime() time.Duration {\n\tif s.IsStopped() {\n\t\treturn s.stop.Sub(s.start)\n\t}\n\treturn time.Since(s.start)\n}\n\n\n\nfunc (s *Stopwatch) Log(msg string) {\n\ts.logger.Info(\"elapsed\", \"msg\", msg, \"dx\", s.Dt())\n}\n\nfunc (s *Stopwatch) Dt() string ", "output": "{\n\treturn fmt.Sprintf(\"%s\", s.ElapsedTime())\n}"} {"input": "package csv_test\n\nimport (\n\t\"io\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\n\tpilosa \"github.com/pilosa/go-pilosa\"\n\t\"github.com/pilosa/go-pilosa/csv\"\n)\n\nfunc TestCSVIterate(t *testing.T) {\n\ttext := `10,7\n\t\t10,5\n\t\t2,3\n\t\t7,1`\n\titerator := csv.NewColumnIterator(csv.RowIDColumnID, strings.NewReader(text))\n\trecs := consumeIterator(t, iterator)\n\ttarget := []pilosa.Record{\n\t\tpilosa.Column{RowID: 10, ColumnID: 7},\n\t\tpilosa.Column{RowID: 10, ColumnID: 5},\n\t\tpilosa.Column{RowID: 2, ColumnID: 3},\n\t\tpilosa.Column{RowID: 7, ColumnID: 1},\n\t}\n\tif !reflect.DeepEqual(target, recs) {\n\t\tt.Fatalf(\"%v != %v\", target, recs)\n\t}\n}\n\n\n\nfunc consumeIterator(t *testing.T, it *csv.Iterator) []pilosa.Record ", "output": "{\n\trecs := []pilosa.Record{}\n\tfor {\n\t\tr, err := it.NextRecord()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\trecs = append(recs, r)\n\t}\n\treturn recs\n}"} {"input": "package sqlmock\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\nvar mock = &sqlmock{}\n\nfunc ExampleNewErrorResult() {\n\tdb, mock, _ := New()\n\tresult := NewErrorResult(fmt.Errorf(\"some error\"))\n\tmock.ExpectExec(\"^INSERT (.+)\").WillReturnResult(result)\n\tres, _ := db.Exec(\"INSERT something\")\n\t_, err := res.LastInsertId()\n\tfmt.Println(err)\n}\n\nfunc ExampleNewResult() {\n\tvar lastInsertID, affected int64\n\tresult := NewResult(lastInsertID, affected)\n\tmock.ExpectExec(\"^INSERT (.+)\").WillReturnResult(result)\n\tfmt.Println(mock.ExpectationsWereMet())\n}\n\nfunc TestShouldReturnValidSqlDriverResult(t *testing.T) {\n\tresult := NewResult(1, 2)\n\tid, err := result.LastInsertId()\n\tif 1 != id {\n\t\tt.Errorf(\"Expected last insert id to be 1, but got: %d\", id)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"expected no error, but got: %s\", err)\n\t}\n\taffected, err := result.RowsAffected()\n\tif 2 != affected {\n\t\tt.Errorf(\"Expected affected rows to be 2, but got: %d\", affected)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"expected no error, but got: %s\", err)\n\t}\n}\n\n\n\nfunc TestShouldReturnErroeSqlDriverResult(t *testing.T) ", "output": "{\n\tresult := NewErrorResult(fmt.Errorf(\"some error\"))\n\t_, err := result.LastInsertId()\n\tif err == nil {\n\t\tt.Error(\"expected error, but got none\")\n\t}\n\t_, err = result.RowsAffected()\n\tif err == nil {\n\t\tt.Error(\"expected error, but got none\")\n\t}\n}"} {"input": "package firestore \n\nimport (\n\t\"context\"\n\t\"runtime\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}\n\n\n\n\n\n\nfunc versionGo() string {\n\tconst develPrefix = \"devel +\"\n\n\ts := runtime.Version()\n\tif strings.HasPrefix(s, develPrefix) {\n\t\ts = s[len(develPrefix):]\n\t\tif p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 {\n\t\t\ts = s[:p]\n\t\t}\n\t\treturn s\n\t}\n\n\tnotSemverRune := func(r rune) bool {\n\t\treturn strings.IndexRune(\"0123456789.\", r) < 0\n\t}\n\n\tif strings.HasPrefix(s, \"go1\") {\n\t\ts = s[2:]\n\t\tvar prerelease string\n\t\tif p := strings.IndexFunc(s, notSemverRune); p >= 0 {\n\t\t\ts, prerelease = s[:p], s[p:]\n\t\t}\n\t\tif strings.HasSuffix(s, \".\") {\n\t\t\ts += \"0\"\n\t\t} else if strings.Count(s, \".\") < 2 {\n\t\t\ts += \".0\"\n\t\t}\n\t\tif prerelease != \"\" {\n\t\t\ts += \"-\" + prerelease\n\t\t}\n\t\treturn s\n\t}\n\treturn \"UNKNOWN\"\n}\n\nconst versionClient = \"20190110\"\n\nfunc DefaultAuthScopes() []string ", "output": "{\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t\t\"https:www.googleapis.com/auth/datastore\",\n\t}\n}"} {"input": "package wafregional_test\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/awserr\"\n\t\"github.com/aws/aws-sdk-go/aws/request\"\n\t\"github.com/aws/aws-sdk-go/awstesting/integration\"\n\t\"github.com/aws/aws-sdk-go/service/waf\"\n\t\"github.com/aws/aws-sdk-go/service/wafregional\"\n)\n\nvar _ aws.Config\nvar _ awserr.Error\nvar _ request.Request\n\n\nfunc TestInteg_01_CreateSqlInjectionMatchSet(t *testing.T) {\n\tctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancelFn()\n\n\tsess := integration.SessionWithDefaultRegion(\"us-east-1\")\n\tsvc := wafregional.New(sess)\n\tparams := &waf.CreateSqlInjectionMatchSetInput{\n\t\tChangeToken: aws.String(\"fake_token\"),\n\t\tName: aws.String(\"fake_name\"),\n\t}\n\t_, err := svc.CreateSqlInjectionMatchSetWithContext(ctx, params, func(r *request.Request) {\n\t\tr.Handlers.Validate.RemoveByName(\"core.ValidateParametersHandler\")\n\t})\n\tif err == nil {\n\t\tt.Fatalf(\"expect request to fail\")\n\t}\n\taerr, ok := err.(awserr.RequestFailure)\n\tif !ok {\n\t\tt.Fatalf(\"expect awserr, was %T\", err)\n\t}\n\tif len(aerr.Code()) == 0 {\n\t\tt.Errorf(\"expect non-empty error code\")\n\t}\n\tif v := aerr.Code(); v == request.ErrCodeSerialization {\n\t\tt.Errorf(\"expect API error code got serialization failure\")\n\t}\n}\n\nfunc TestInteg_00_ListRules(t *testing.T) ", "output": "{\n\tctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancelFn()\n\n\tsess := integration.SessionWithDefaultRegion(\"us-east-1\")\n\tsvc := wafregional.New(sess)\n\tparams := &waf.ListRulesInput{\n\t\tLimit: aws.Int64(20),\n\t}\n\t_, err := svc.ListRulesWithContext(ctx, params, func(r *request.Request) {\n\t\tr.Handlers.Validate.RemoveByName(\"core.ValidateParametersHandler\")\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"expect no error, got %v\", err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"net/http\"\n\t\"net/http/cookiejar\"\n\t\"log\"\n)\n\nfunc main() {\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\n\tcookieJar, _ := cookiejar.New(nil)\n\n\tc := &http.Client{\n\t\tJar: cookieJar,\n\t\tTransport: tr,\n\t}\n\n\tc.Get(\"https://baidu.com\")\n\n}\n\n\n\nfunc https0() ", "output": "{\n\tconf := &tls.Config{\n\t\tInsecureSkipVerify: true,\n\t}\n\tconn, err := tls.Dial(\"tcp\", \"220.181.57.216:443\", conf)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\tn, err := conn.Write([]byte(\"hello\\n\"))\n\tif err != nil {\n\t\tlog.Println(n, err)\n\t\treturn\n\t}\n\tbuf := make([]byte, 100)\n\tn, err = conn.Read(buf)\n\tif err != nil {\n\t\tlog.Println(n, err)\n\t\treturn\n\t}\n\tprintln(string(buf[:n]))\n}"} {"input": "package coderx\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/apache/beam/sdks/go/pkg/beam/core/util/reflectx\"\n)\n\n\n\nfunc TestFloat(t *testing.T) ", "output": "{\n\ttests := []interface{}{\n\t\tfloat32(0.0),\n\t\tfloat32(94.5),\n\t\tfloat64(-127.25),\n\t\tfloat64(8675309.4286),\n\t}\n\n\tfor _, v := range tests {\n\t\ttyp := reflect.ValueOf(v).Type()\n\n\t\tdata := encFloat(v)\n\t\tresult, err := decFloat(typ, data)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"dec(enc(%v)) failed: %v\", v, err)\n\t\t}\n\n\t\tif v != result {\n\t\t\tt.Errorf(\"dec(enc(%v)) = %v, want id\", v, result)\n\t\t}\n\t\tresultT := reflectx.UnderlyingType(reflect.ValueOf(result)).Type()\n\t\tif resultT != typ {\n\t\t\tt.Errorf(\"type(dec(enc(%v))) = %v, want id\", typ, resultT)\n\t\t}\n\t}\n}"} {"input": "package graphql\n\nimport (\n\t\"errors\"\n\n\t\"github.com/equinux/graphql/gqlerrors\"\n\t\"github.com/equinux/graphql/language/ast\"\n)\n\nfunc NewLocatedError(err interface{}, nodes []ast.Node) *gqlerrors.Error {\n\treturn newLocatedError(err, nodes, nil)\n}\n\nfunc NewLocatedErrorWithPath(err interface{}, nodes []ast.Node, path []interface{}) *gqlerrors.Error {\n\treturn newLocatedError(err, nodes, path)\n}\n\nfunc newLocatedError(err interface{}, nodes []ast.Node, path []interface{}) *gqlerrors.Error {\n\tif err, ok := err.(*gqlerrors.Error); ok {\n\t\treturn err\n\t}\n\n\tvar origError error\n\tmessage := \"An unknown error occurred.\"\n\tif err, ok := err.(error); ok {\n\t\tmessage = err.Error()\n\t\torigError = err\n\t}\n\tif err, ok := err.(string); ok {\n\t\tmessage = err\n\t\torigError = errors.New(err)\n\t}\n\tstack := message\n\treturn gqlerrors.NewErrorWithPath(\n\t\tmessage,\n\t\tnodes,\n\t\tstack,\n\t\tnil,\n\t\t[]int{},\n\t\tpath,\n\t\torigError,\n\t)\n}\n\n\n\nfunc FieldASTsToNodeASTs(fieldASTs []*ast.Field) []ast.Node ", "output": "{\n\tnodes := []ast.Node{}\n\tfor _, fieldAST := range fieldASTs {\n\t\tnodes = append(nodes, fieldAST)\n\t}\n\treturn nodes\n}"} {"input": "package linux\n\nimport (\n\t\"testing\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestGetAdapter(t *testing.T) {\n\tlog.SetLevel(log.DebugLevel)\n\t_, err := GetAdapter(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestGetAdapterNotFound(t *testing.T) {\n\t_, err := GetAdapter(\"hci999\")\n\tif err == nil {\n\t\tt.Fatal(\"adapter should not exists\")\n\t}\n}\n\nfunc TestUp(t *testing.T) {\n\terr := Up(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDown(t *testing.T) {\n\terr := Down(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestReset(t *testing.T) {\n\terr := Reset(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestGetAdapters(t *testing.T) ", "output": "{\n\n\tlog.SetLevel(log.DebugLevel)\n\n\tlist, err := GetAdapters()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassert.NotEmpty(t, list)\n}"} {"input": "package keyevent\n\nimport (\n\t\"github.com/linuxdeepin/go-lib/dbusutil\"\n)\n\n\n\nfunc (v *Manager) GetExportedMethods() dbusutil.ExportedMethods ", "output": "{\n\treturn nil\n}"} {"input": "package client\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"golang.org/x/net/context\"\n)\n\n\nfunc (cli *Client) VolumeInspect(ctx context.Context, volumeID string) (types.Volume, error) {\n\tvolume, _, err := cli.VolumeInspectWithRaw(ctx, volumeID)\n\treturn volume, err\n}\n\n\n\n\nfunc (cli *Client) VolumeInspectWithRaw(ctx context.Context, volumeID string) (types.Volume, []byte, error) ", "output": "{\n\tvar volume types.Volume\n\tresp, err := cli.get(ctx, \"/volumes/\"+volumeID, nil, nil)\n\tif err != nil {\n\t\tif resp.statusCode == http.StatusNotFound {\n\t\t\treturn volume, nil, volumeNotFoundError{volumeID}\n\t\t}\n\t\treturn volume, nil, err\n\t}\n\tdefer ensureReaderClosed(resp)\n\n\tbody, err := ioutil.ReadAll(resp.body)\n\tif err != nil {\n\t\treturn volume, nil, err\n\t}\n\trdr := bytes.NewReader(body)\n\terr = json.NewDecoder(rdr).Decode(&volume)\n\treturn volume, body, err\n}"} {"input": "package vsphere\n\nimport (\n\t\"fmt\"\n)\n\nconst BuilderId = \"packer.post-processor.vsphere\"\n\ntype Artifact struct {\n\tfiles []string\n\tdatastore string\n\tvmfolder string\n\tvmname string\n}\n\nfunc NewArtifact(datastore, vmfolder, vmname string, files []string) *Artifact {\n\treturn &Artifact{\n\t\tfiles: files,\n\t\tdatastore: datastore,\n\t\tvmfolder: vmfolder,\n\t\tvmname: vmname,\n\t}\n}\n\nfunc (*Artifact) BuilderId() string {\n\treturn BuilderId\n}\n\nfunc (a *Artifact) Files() []string {\n\treturn a.files\n}\n\nfunc (a *Artifact) Id() string {\n\treturn fmt.Sprintf(\"%s::%s::%s\", a.datastore, a.vmfolder, a.vmname)\n}\n\nfunc (a *Artifact) String() string {\n\treturn fmt.Sprintf(\"VM: %s Folder: %s Datastore: %s\", a.vmname, a.vmfolder, a.datastore)\n}\n\nfunc (*Artifact) State(name string) interface{} {\n\treturn nil\n}\n\n\n\nfunc (a *Artifact) Destroy() error ", "output": "{\n\treturn nil\n}"} {"input": "package utils\n\nimport (\n\t\"github.com/goincremental/negroni-sessions\"\n\t\"net/http\"\n)\n\ntype SessionManager interface {\n\tGet(*http.Request, string) string\n\tSet(*http.Request, string, string)\n\tDelete(*http.Request, string)\n}\n\ntype SessionManagerImpl struct {\n}\n\nfunc NewSessionManager() *SessionManagerImpl {\n\treturn &SessionManagerImpl{}\n}\n\nfunc (sa *SessionManagerImpl) Get(req *http.Request, key string) string {\n\tif val := sessions.GetSession(req).Get(key); val != nil {\n\t\treturn val.(string)\n\t}\n\n\treturn \"\"\n}\n\n\n\nfunc (sa *SessionManagerImpl) Delete(req *http.Request, key string) {\n\tsessions.GetSession(req).Delete(key)\n}\n\nfunc (sa *SessionManagerImpl) Set(req *http.Request, key, value string) ", "output": "{\n\tsessions.GetSession(req).Set(key, value)\n}"} {"input": "package req\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n)\n\ntype execChans struct {\n\tOut chan ResponseInfo\n\tErrs chan error\n\tDone chan bool\n}\n\ntype scenarioExecutor interface {\n\texecute(scen RequestScenario, chans execChans)\n}\n\nfunc Execute(scen RequestScenario, writer io.Writer) error {\n\n\tsetOptions(scen.Options)\n\n\texplainScenario(scen)\n\n\tchans := execChans{\n\t\tOut: make(chan ResponseInfo),\n\t\tErrs: make(chan error),\n\t\tDone: make(chan bool),\n\t}\n\texecScenario(scen, chans)\n\n\tfor {\n\t\tselect {\n\t\tcase res := <-chans.Out:\n\t\t\tif err := printResponse(res, writer); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase err := <-chans.Errs:\n\t\t\treturn err\n\t\tcase <-chans.Done:\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\nfunc execScenario(scen RequestScenario, chans execChans) {\n\tif len(scen.Bots) == 0 {\n\t\texecScenarioLocally(scen, chans)\n\t} else {\n\t\texecScenarioDistributed(scen, chans)\n\t}\n}\n\nfunc explainScenario(scen RequestScenario) error {\n\tvar data []byte\n\tvar err error\n\n\tif options.Pretty {\n\t\tdata, err = json.MarshalIndent(scen, \"\", \" \")\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to format %v to json: %v\", scen, err)\n\t}\n\n\tlog.Printf(\"Executing scenario:\\n%v\\n==================\\n\\n\", string(data))\n\n\treturn nil\n}\n\n\n\nfunc printResponse(res ResponseInfo, writer io.Writer) error ", "output": "{\n\tvar data []byte\n\tvar err error\n\n\tif options.Pretty {\n\t\tdata, err = json.MarshalIndent(res, \"\", \" \")\n\t} else {\n\t\tdata, err = json.Marshal(res)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to format %v to json: %v\", res, err)\n\t}\n\t_, err = writer.Write(append(data, '\\n'))\n\treturn err\n}"} {"input": "package sketchy\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestMultihash(t *testing.T) ", "output": "{\n\tConvey(\"FNV-1\", t, func() {\n\t\tgolden := map[string]uint64{\n\t\t\t\"\": 0xcbf29ce484222325,\n\t\t\t\"a\": 0xaf63bd4c8601b7be,\n\t\t\t\"ab\": 0x08326707b4eb37b8,\n\t\t\t\"abc\": 0xd8dcca186bafadcb,\n\t\t}\n\t\tfor k, v := range golden {\n\t\t\tSo(v, ShouldEqual, multihash([]byte(k)))\n\t\t}\n\t})\n}"} {"input": "package apigateway\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype ExecutionLogPolicy struct {\n\n\tIsEnabled *bool `mandatory:\"false\" json:\"isEnabled\"`\n\n\tLogLevel ExecutionLogPolicyLogLevelEnum `mandatory:\"false\" json:\"logLevel,omitempty\"`\n}\n\nfunc (m ExecutionLogPolicy) String() string {\n\treturn common.PointerString(m)\n}\n\n\ntype ExecutionLogPolicyLogLevelEnum string\n\n\nconst (\n\tExecutionLogPolicyLogLevelInfo ExecutionLogPolicyLogLevelEnum = \"INFO\"\n\tExecutionLogPolicyLogLevelWarn ExecutionLogPolicyLogLevelEnum = \"WARN\"\n\tExecutionLogPolicyLogLevelError ExecutionLogPolicyLogLevelEnum = \"ERROR\"\n)\n\nvar mappingExecutionLogPolicyLogLevel = map[string]ExecutionLogPolicyLogLevelEnum{\n\t\"INFO\": ExecutionLogPolicyLogLevelInfo,\n\t\"WARN\": ExecutionLogPolicyLogLevelWarn,\n\t\"ERROR\": ExecutionLogPolicyLogLevelError,\n}\n\n\n\n\nfunc GetExecutionLogPolicyLogLevelEnumValues() []ExecutionLogPolicyLogLevelEnum ", "output": "{\n\tvalues := make([]ExecutionLogPolicyLogLevelEnum, 0)\n\tfor _, v := range mappingExecutionLogPolicyLogLevel {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package app\n\nimport (\n\t. \"strconv\"\n\t\"time\"\n)\n\ntype User struct {\n\tId int64\n\tNom string\n\tPrenom string\n\tEmail string\n\tPassword string\n\tCreatedAt time.Time\n\tUpdatedAt time.Time\n}\n\n\n\n\n\nfunc (u User) Update() {\n\tdb.First(&u, &u.Id).Update(&u)\n}\n\n\nfunc (u User) Delete() {\n\tdb.Delete(&u)\n}\n\n\n\nfunc (u User) GetById() User {\n\tdb.Where(\"id = ?\", Itoa(int(u.Id))).Find(&u)\n\treturn u\n}\n\n\nfunc (u User) GetList() []User {\n\tvar users []User\n\tdb.Find(&users)\n\treturn users\n}\n\nfunc (u User) Save() ", "output": "{\n\tdb.Save(&u)\n}"} {"input": "package mailru\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/markbates/goth\"\n)\n\n\ntype Session struct {\n\tAuthURL string\n\tAccessToken string\n\tRefreshToken string\n\tExpiresAt time.Time\n}\n\n\n\n\n\nfunc (s *Session) Marshal() string {\n\tb, _ := json.Marshal(s)\n\treturn string(b)\n}\n\n\nfunc (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {\n\tp := provider.(*Provider)\n\ttoken, err := p.oauthConfig.Exchange(goth.ContextForClient(p.Client()), params.Get(\"code\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !token.Valid() {\n\t\treturn \"\", errors.New(\"invalid token received from provider\")\n\t}\n\n\ts.AccessToken = token.AccessToken\n\ts.RefreshToken = token.RefreshToken\n\ts.ExpiresAt = token.Expiry\n\n\treturn s.AccessToken, err\n}\n\n\nfunc (p *Provider) UnmarshalSession(data string) (goth.Session, error) {\n\tsess := new(Session)\n\terr := json.NewDecoder(strings.NewReader(data)).Decode(&sess)\n\treturn sess, err\n}\n\nfunc (s *Session) GetAuthURL() (string, error) ", "output": "{\n\tif s.AuthURL == \"\" {\n\t\treturn \"\", errors.New(goth.NoAuthUrlErrorMessage)\n\t}\n\n\treturn s.AuthURL, nil\n}"} {"input": "package ocvp\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListWorkRequestsRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tResourceId *string `mandatory:\"false\" contributesTo:\"query\" name:\"resourceId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListWorkRequestsRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListWorkRequestsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ListWorkRequestsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ListWorkRequestsRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListWorkRequestsResponse struct {\n\n\tRawResponse *http.Response\n\n\tWorkRequestCollection `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n}\n\n\n\n\nfunc (response ListWorkRequestsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response ListWorkRequestsResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package exec\n\nimport (\n\t\"fmt\"\n\tpb \"github.com/rongyungo/probe/server/proto\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\nfunc ProbeTcp(t *pb.Task) *pb.TaskResult ", "output": "{\n\tstart := time.Now().UnixNano()\n\tres := pb.TaskResult{\n\t\tTaskId: t.BasicInfo.GetId(),\n\t\tType: t.BasicInfo.GetType(),\n\t\tStartMs: start / 1e6}\n\n\tcon, err := net.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", t.TcpSpec.Host, t.TcpSpec.Port))\n\tif res.DelayMs = (time.Now().UnixNano() - start) / 1e6; err != nil {\n\t\tres.Error, res.ErrorCode = err.Error(), pb.TaskResult_ERR_NET_DIAL\n\t} else {\n\t\tdefer con.Close()\n\t\tres.Success, res.ErrorCode = true, pb.TaskResult_OK\n\t}\n\n\treturn &res\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\ntype User struct {\n\tName string `json:\"name\"`\n\tID string `json:\"id\"`\n\tIP string `json:\"ip,omitempty\"`\n\tAdmin bool `json:\"admin\"`\n\tBlocked bool `json:\"block,omitempty\"`\n\tVerified bool `json:\"verified,omitempty\"`\n}\n\ntype contextKey string\n\n\n\n\n\n\nfunc GetUserInfo(r *http.Request) (user User, err error) {\n\n\tctx := r.Context()\n\tif ctx == nil {\n\t\treturn User{}, errors.New(\"no info about user\")\n\t}\n\tif u, ok := ctx.Value(contextKey(\"user\")).(User); ok {\n\t\treturn u, nil\n\t}\n\n\treturn User{}, errors.New(\"user can't be parsed\")\n}\n\n\nfunc SetUserInfo(r *http.Request, user User) *http.Request {\n\tctx := r.Context()\n\tctx = context.WithValue(ctx, contextKey(\"user\"), user)\n\treturn r.WithContext(ctx)\n}\n\nfunc MustGetUserInfo(r *http.Request) User ", "output": "{\n\tuser, err := GetUserInfo(r)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn user\n}"} {"input": "package animation\n\nimport (\n\t\"time\"\n)\n\ntype GroupedAnimation struct {\n\tanimators []Animator\n\tcallback AnimatorCallback\n}\n\n\n\nfunc (a *GroupedAnimation) SetCallback(callback AnimatorCallback) {\n\ta.callback = callback\n}\n\nfunc (a *GroupedAnimation) IsDone() bool {\n\tvar done = true\n\tfor _, animator := range a.animators {\n\t\tif !animator.IsDone() {\n\t\t\tdone = false\n\t\t}\n\t}\n\treturn done\n}\n\nfunc (a *GroupedAnimation) Update(elapsed time.Duration) time.Duration {\n\tvar (\n\t\ttotal time.Duration\n\t\tremainder time.Duration\n\t\tdone = true\n\t)\n\tfor _, animator := range a.animators {\n\t\tremainder = animator.Update(elapsed)\n\t\tif !animator.IsDone() {\n\t\t\tdone = false\n\t\t}\n\t\tif remainder != 0 && (total == 0 || remainder < total) {\n\t\t\ttotal = remainder \n\t\t}\n\t}\n\tif done {\n\t\tif a.callback != nil {\n\t\t\ta.callback()\n\t\t}\n\t\treturn total\n\t}\n\treturn 0\n}\n\nfunc (a *GroupedAnimation) Reset() {\n\tfor _, animator := range a.animators {\n\t\tanimator.Reset()\n\t}\n}\n\nfunc (a *GroupedAnimation) Delete() {\n\tfor _, animator := range a.animators {\n\t\tanimator.Delete()\n\t}\n\ta.animators = []Animator{}\n}\n\nfunc NewGroupedAnimation(animators []Animator) *GroupedAnimation ", "output": "{\n\treturn &GroupedAnimation{animators, nil}\n}"} {"input": "package tbin\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\nfunc (line *Polyline) UnmarshalTBin(dec *Decoder) error {\n\tsignature := polylineSignature\n\trefSig, err := dec.ReadType()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif signature.String() != refSig.String() {\n\t\treturn fmt.Errorf(\"Signature mismatch on decode: %v vs %v\", signature, refSig)\n\t}\n\tsize := dec.ReadSize()\n\tif dec.Error() == nil {\n\t\tproto := Polyline{}\n\t\tproto.Points = make([]*Point, size)\n\t\tfor i := 0; i < size; i++ {\n\t\t\tx := dec.ReadInt32()\n\t\t\ty := dec.ReadInt32()\n\t\t\tproto.Points[i] = &Point{x, y}\n\t\t}\n\t\t*line = proto\n\t\treturn nil\n\t}\n\treturn dec.Error()\n}\n\n\n\nfunc TestTBinMarshallableDecode(test *testing.T) ", "output": "{\n\tvar line Polyline\n\ttdata, err := ioutil.ReadFile(\"../testdata/test.tbin\")\n\terr = Unmarshal(tdata, &line)\n\tif err != nil {\n\t\ttest.Errorf(\"Cannot unmarshal test.tbin: %v\", err)\n\t}\n\tline2 := polyline()\n\tif !Equal(&line, line2) {\n\t\ttest.Errorf(\"unmarshalled value not equal to reference value: %v\\n%v\", line, *line2)\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"reflect\"\n\t\"time\"\n\n\t_ \"github.com/akutz/golf\"\n\n\t\"github.com/thecodeteam/rexray/libstorage/api/context\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/types\"\n)\n\n\n\nfunc GetTypePkgPathAndName(i interface{}) string {\n\tt := reflect.TypeOf(i)\n\tif t.Kind() == reflect.Ptr || t.Kind() == reflect.Interface {\n\t\tt = t.Elem()\n\t}\n\tpkgPath := t.PkgPath()\n\ttypeName := t.Name()\n\tif pkgPath == \"\" {\n\t\treturn typeName\n\t}\n\treturn fmt.Sprintf(\"%s.%s\", pkgPath, typeName)\n}\n\n\nfunc GetTempSockFile(ctx types.Context) string {\n\n\tf, err := ioutil.TempFile(context.MustPathConfig(ctx).Run, \"\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tname := f.Name()\n\tos.RemoveAll(name)\n\treturn fmt.Sprintf(\"%s.sock\", name)\n}\n\n\n\n\nfunc DeviceAttachTimeout(val string) time.Duration ", "output": "{\n\tdur, err := time.ParseDuration(val)\n\tif err != nil {\n\t\treturn time.Duration(30) * time.Second\n\t}\n\treturn dur\n}"} {"input": "package stack\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/docker/docker/cli/command/bundlefile\"\n\t\"github.com/spf13/pflag\"\n)\n\nfunc addComposefileFlag(opt *string, flags *pflag.FlagSet) {\n\tflags.StringVarP(opt, \"compose-file\", \"c\", \"\", \"Path to a Compose file\")\n}\n\nfunc addBundlefileFlag(opt *string, flags *pflag.FlagSet) {\n\tflags.StringVar(opt, \"bundle-file\", \"\", \"Path to a Distributed Application Bundle file\")\n\tflags.SetAnnotation(\"bundle-file\", \"experimental\", nil)\n}\n\nfunc addRegistryAuthFlag(opt *bool, flags *pflag.FlagSet) {\n\tflags.BoolVar(opt, \"with-registry-auth\", false, \"Send registry authentication details to Swarm agents\")\n}\n\n\n\nfunc loadBundlefile(stderr io.Writer, namespace string, path string) (*bundlefile.Bundlefile, error) ", "output": "{\n\tdefaultPath := fmt.Sprintf(\"%s.dab\", namespace)\n\n\tif path == \"\" {\n\t\tpath = defaultPath\n\t}\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"Bundle %s not found. Specify the path with --file\",\n\t\t\tpath)\n\t}\n\n\tfmt.Fprintf(stderr, \"Loading bundle from %s\\n\", path)\n\treader, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer reader.Close()\n\n\tbundle, err := bundlefile.LoadFile(reader)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error reading %s: %v\\n\", path, err)\n\t}\n\treturn bundle, err\n}"} {"input": "package factory\n\nimport (\n\tcontext \"context\"\n\n\texternalversions \"knative.dev/eventing-kafka/pkg/client/informers/externalversions\"\n\tclient \"knative.dev/eventing-kafka/pkg/client/injection/client\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\n\n\n\ntype Key struct{}\n\nfunc withInformerFactory(ctx context.Context) context.Context {\n\tc := client.Get(ctx)\n\topts := make([]externalversions.SharedInformerOption, 0, 1)\n\tif injection.HasNamespaceScope(ctx) {\n\t\topts = append(opts, externalversions.WithNamespace(injection.GetNamespaceScope(ctx)))\n\t}\n\treturn context.WithValue(ctx, Key{},\n\t\texternalversions.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...))\n}\n\n\nfunc Get(ctx context.Context) externalversions.SharedInformerFactory {\n\tuntyped := ctx.Value(Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch knative.dev/eventing-kafka/pkg/client/informers/externalversions.SharedInformerFactory from context.\")\n\t}\n\treturn untyped.(externalversions.SharedInformerFactory)\n}\n\nfunc init() ", "output": "{\n\tinjection.Default.RegisterInformerFactory(withInformerFactory)\n}"} {"input": "package immortal\n\nimport (\n\t\"os/exec\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestWatchPidGetpid(t *testing.T) {\n\tch := make(chan error, 1)\n\td := &Daemon{}\n\tcmd := exec.Command(\"go\", \"version\")\n\tcmd.Start()\n\tpid := cmd.Process.Pid\n\tgo func() {\n\t\td.WatchPid(pid, ch)\n\t\tch <- cmd.Wait()\n\t}()\n\tselect {\n\tcase <-time.After(time.Millisecond):\n\t\tsyscall.Kill(pid, syscall.SIGTERM)\n\tcase err := <-ch:\n\t\tif err != nil {\n\t\t\tif err.Error() != \"EXIT\" {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\nfunc TestWatchPidGetpidKill(t *testing.T) ", "output": "{\n\td := &Daemon{}\n\tch := make(chan error, 1)\n\tcmd := exec.Command(\"sleep\", \"100\")\n\tcmd.Start()\n\tpid := cmd.Process.Pid\n\tgo func() {\n\t\td.WatchPid(pid, ch)\n\t\tch <- cmd.Wait()\n\t}()\n\n\tselect {\n\tcase err := <-ch:\n\t\tif err != nil {\n\t\t\tif err.Error() != \"EXIT\" {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\tcase <-time.After(1 * time.Millisecond):\n\t\tif err := cmd.Process.Kill(); err != nil {\n\t\t\tt.Errorf(\"failed to kill: %s\", err)\n\t\t}\n\t}\n}"} {"input": "package httpserver\n\nimport (\n\t\"fmt\"\n\t\"github.com/devfeel/dotweb\"\n\t\"github.com/devfeel/tokenserver/config\"\n\t\"github.com/devfeel/tokenserver/framework/log\"\n\t\"strconv\"\n)\n\n\n\nfunc ReSetServer() {\n\tfmt.Println(\"ReSetServer\")\n}\n\nfunc StartServer() error ", "output": "{\n\n\tapp := dotweb.New()\n\n\tapp.SetLogPath(config.CurrentConfig.Log.FilePath)\n\n\tInitRoute(app)\n\n\tinnerLogger := logger.GetInnerLogger()\n\n\tpprofport := config.CurrentConfig.HttpServer.PProfPort\n\tapp.SetPProfConfig(true, pprofport)\n\n\tport := config.CurrentConfig.HttpServer.HttpPort\n\tinnerLogger.Debug(\"dotweb.StartServer => \" + strconv.Itoa(port))\n\terr := app.StartServer(port)\n\treturn err\n}"} {"input": "package godo\n\ntype TaskManager struct {\n\tmanager\n}\n\nfunc NewTaskManager() *TaskManager {\n\treturn &TaskManager{}\n}\n\n\n\nfunc (tm *TaskManager) FindTasksOfProject(projectId int, tasks *[]Task) (err error) {\n\terr = Dbmap.Select(tasks, \"select * from tasks where projectID = ? order by id\", projectId)\n\treturn\n}\n\nfunc (tm *TaskManager) FindAll() (tasks []Task, err error) ", "output": "{\n\terr = tm.manager.FindAll(&tasks, \"tasks\")\n\treturn\n}"} {"input": "package challenge25\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"github.com/stripedpajamas/cryptopals/set3/challenge18\"\n)\n\nvar globalPlaintext []byte\n\nfunc init() {\n\tvar err error\n\tglobalPlaintext, err = ioutil.ReadFile(\"25_decoded.txt\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc TestEncryptSecretWithCTR(t *testing.T) {\n\tenc := EncryptSecretWithCTR(globalPlaintext)\n\tdec := challenge18.CTR(enc, globalKey, globalNonce)\n\n\tif !bytes.Equal(dec, globalPlaintext) {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestEdit(t *testing.T) {\n\tinput := []byte(\"HELLO POTATO FACE\")\n\tkey := []byte(\"YELLOW SUBMARINE\")\n\tnonce := []byte{0, 0, 0, 0, 0, 0, 0, 0}\n\tenc := challenge18.CTR(input, key, nonce)\n\tedited := Edit(enc, key, nonce, []byte(\"TOMATO\"), 6)\n\tdec := challenge18.CTR(edited, key, nonce)\n\n\tif string(dec) != \"HELLO TOMATO FACE\" {\n\t\tt.Fail()\n\t}\n}\n\n\n\nfunc TestRecoverPTFromAPI(t *testing.T) {\n\tenc := EncryptSecretWithCTR(globalPlaintext)\n\trecovered := RecoverPTFromAPI(enc)\n\tif !bytes.Equal(recovered, globalPlaintext) {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestEditAPI(t *testing.T) ", "output": "{\n\tinput := []byte(\"HELLO POTATO FACE\")\n\tenc := challenge18.CTR(input, globalKey, globalNonce)\n\tedited := EditAPI(enc, []byte(\"TOMATO\"), 6)\n\tdec := challenge18.CTR(edited, globalKey, globalNonce)\n\n\tif string(dec) != \"HELLO TOMATO FACE\" {\n\t\tt.Fail()\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api\"\n)\n\n\n\nfunc (*DeploymentConfig) IsAnAPIObject() {}\nfunc (*DeploymentConfigList) IsAnAPIObject() {}\nfunc (*DeploymentConfigRollback) IsAnAPIObject() {}\n\nfunc init() ", "output": "{\n\tapi.Scheme.AddKnownTypes(\"\",\n\t\t&DeploymentConfig{},\n\t\t&DeploymentConfigList{},\n\t\t&DeploymentConfigRollback{},\n\t)\n}"} {"input": "package bidirule\n\n\n\nfunc (t *Transformer) isFinal() bool ", "output": "{\n\treturn t.state == ruleLTRFinal || t.state == ruleRTLFinal || t.state == ruleInitial\n}"} {"input": "package handlers\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"io\"\n\t\"net/http\"\n\n\tdcontext \"github.com/docker/distribution/context\"\n)\n\n\n\n\n\n\n\n\n\n\nfunc copyFullPayload(ctx context.Context, responseWriter http.ResponseWriter, r *http.Request, destWriter io.Writer, limit int64, action string) error {\n\tclientClosed := r.Context().Done()\n\tvar body = r.Body\n\tif limit > 0 {\n\t\tbody = http.MaxBytesReader(responseWriter, body, limit)\n\t}\n\n\tcopied, err := io.Copy(destWriter, body)\n\tif clientClosed != nil && (err != nil || (r.ContentLength > 0 && copied < r.ContentLength)) {\n\t\tselect {\n\t\tcase <-clientClosed:\n\t\t\tresponseWriter.WriteHeader(499)\n\n\t\t\tdcontext.GetLoggerWithFields(ctx, map[interface{}]interface{}{\n\t\t\t\t\"error\": err,\n\t\t\t\t\"copied\": copied,\n\t\t\t\t\"contentLength\": r.ContentLength,\n\t\t\t}, \"error\", \"copied\", \"contentLength\").Error(\"client disconnected during \" + action)\n\t\t\treturn errors.New(\"client disconnected\")\n\t\tdefault:\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tdcontext.GetLogger(ctx).Errorf(\"unknown error reading request payload: %v\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc closeResources(handler http.Handler, closers ...io.Closer) http.Handler ", "output": "{\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfor _, closer := range closers {\n\t\t\tdefer closer.Close()\n\t\t}\n\t\thandler.ServeHTTP(w, r)\n\t})\n}"} {"input": "package service\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/BurntSushi/toml\"\n\t\"github.com/nebulaim/telegramd/baselib/grpc_util\"\n\t\"github.com/nebulaim/telegramd/baselib/mysql_client\"\n\t\"github.com/nebulaim/telegramd/baselib/redis_client\"\n)\n\nvar (\n\tconfPath string\n\tConf *documentConfig\n)\n\ntype documentConfig struct {\n\tServerId int32 \n\tDataPath string\n\tRedis []redis_client.RedisConfig\n\tMysql []mysql_client.MySQLConfig\n\tRpcServer *grpc_util.RPCServerConfig\n}\n\nfunc (c *documentConfig) String() string {\n\treturn fmt.Sprintf(\"{server_id: %d, redis: %v. mysql: %v, server: %v}\",\n\t\tc.ServerId,\n\t\tc.Redis,\n\t\tc.Mysql,\n\t\tc.RpcServer)\n}\n\nfunc init() {\n\tflag.StringVar(&confPath, \"conf\", \"./document.toml\", \"config path\")\n}\n\n\n\nfunc InitializeConfig() (err error) ", "output": "{\n\t_, err = toml.DecodeFile(confPath, &Conf)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"decode file %s error: %v\", confPath, err)\n\t}\n\treturn\n}"} {"input": "package block\n\n\ntype NoopLeaseManager struct{}\n\nfunc (n *NoopLeaseManager) RegisterLeaser(leaser Leaser) error {\n\treturn nil\n}\n\nfunc (n *NoopLeaseManager) UnregisterLeaser(leaser Leaser) error {\n\treturn nil\n}\n\nfunc (n *NoopLeaseManager) OpenLease(\n\tleaser Leaser,\n\tdescriptor LeaseDescriptor,\n\tstate LeaseState,\n) error {\n\treturn nil\n}\n\nfunc (n *NoopLeaseManager) OpenLatestLease(\n\tleaser Leaser,\n\tdescriptor LeaseDescriptor,\n) (LeaseState, error) {\n\treturn LeaseState{}, nil\n}\n\nfunc (n *NoopLeaseManager) UpdateOpenLeases(\n\tdescriptor LeaseDescriptor,\n\tstate LeaseState,\n) (UpdateLeasesResult, error) {\n\treturn UpdateLeasesResult{}, nil\n}\n\n\n\nfunc (n *NoopLeaseManager) SetLeaseVerifier(leaseVerifier LeaseVerifier) error ", "output": "{\n\treturn nil\n}"} {"input": "package model\n\nimport \"time\"\n\ntype FlashMessage struct {\n\tID string\n\tValue string\n\tExpiredAt time.Time\n}\n\nfunc (*FlashMessage) TableName() string {\n\treturn \"flash_message\"\n}\n\n\n\nfunc (fm *FlashMessage) IsExpired(now time.Time) bool ", "output": "{\n\tif fm.ExpiredAt.IsZero() {\n\t\treturn false\n\t}\n\treturn fm.ExpiredAt.Before(now)\n}"} {"input": "package ps\n\n\n\ntype Process interface {\n\tPid() int\n\n\tPPid() int\n\n\tCPids() []int\n\n\tExecutable() string\n}\n\n\n\n\n\n\n\nfunc Processes() ([]Process, error) {\n\treturn processes()\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc FindProcessByExecutable(name string) ([]Process, error) {\n\treturn findProcessByExecutable(name)\n}\n\nfunc FindProcessByPid(pid int) (Process, error) ", "output": "{\n\treturn findProcessByPid(pid)\n}"} {"input": "package terminal\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"golang.org/x/crypto/ssh/terminal\"\n)\n\n\n\n\n\n\nfunc IsTerminal(fd int) bool {\n\treturn terminal.IsTerminal(fd)\n}\n\n\n\n\nfunc ReadPassword(fd int) ([]byte, error) {\n\treturn terminal.ReadPassword(fd)\n}\n\n\nfunc WriteTerminalTitle(title string) {\n\tfmt.Printf(ChangeTitle + title + BEL)\n}\n\nfunc GetSize() (w, h int) ", "output": "{\n\tw, h, err := terminal.GetSize(int(os.Stdout.Fd()))\n\tif err != nil {\n\t\tw, h = 80, 25\n\t}\n\treturn w, h\n}"} {"input": "package goapp\n\nimport (\n\t\"testing\"\n)\n\nfunc eqHelper(t *testing.T, expectedEq bool, args ...interface{}) {\n\tif expectedEq {\n\t\tif !eq(args...) {\n\t\t\tt.Errorf(\"Expected %v to be equal, got false\", args)\n\t\t}\n\t} else {\n\t\tif eq(args...) {\n\t\t\tt.Errorf(\"Expected %v to not be equal, got true\", args)\n\t\t}\n\t}\n}\n\n\n\nfunc TestEq(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\teqHelper(t, true, 1, 1)\n\teqHelper(t, true, 1, 1, 1)\n\teqHelper(t, false, 1, 1, 3)\n\teqHelper(t, false, 1, 2)\n\teqHelper(t, false, 1, 2, 3)\n}"} {"input": "package binding\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/kubernetes-incubator/service-catalog/cmd/svcat/command\"\n\t\"github.com/kubernetes-incubator/service-catalog/cmd/svcat/output\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype describeCmd struct {\n\t*command.Context\n\tns string\n\tname string\n\ttraverse bool\n}\n\n\n\n\nfunc (c *describeCmd) Validate(args []string) error {\n\tif len(args) == 0 {\n\t\treturn fmt.Errorf(\"name is required\")\n\t}\n\tc.name = args[0]\n\n\treturn nil\n}\n\nfunc (c *describeCmd) Run() error {\n\treturn c.describe()\n}\n\nfunc (c *describeCmd) describe() error {\n\tbinding, err := c.App.RetrieveBinding(c.ns, c.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toutput.WriteBindingDetails(c.Output, binding)\n\n\tif c.traverse {\n\t\tinstance, class, plan, broker, err := c.App.BindingParentHierarchy(binding)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to traverse up the binding hierarchy (%s)\", err)\n\t\t}\n\t\toutput.WriteParentInstance(c.Output, instance)\n\t\toutput.WriteParentClass(c.Output, class)\n\t\toutput.WriteParentPlan(c.Output, plan)\n\t\toutput.WriteParentBroker(c.Output, broker)\n\t}\n\n\treturn nil\n}\n\nfunc NewDescribeCmd(cxt *command.Context) *cobra.Command ", "output": "{\n\tdescribeCmd := &describeCmd{Context: cxt}\n\tcmd := &cobra.Command{\n\t\tUse: \"binding NAME\",\n\t\tAliases: []string{\"bindings\", \"bnd\"},\n\t\tShort: \"Show details of a specific binding\",\n\t\tExample: `\n svcat describe binding wordpress-mysql-binding\n`,\n\t\tPreRunE: command.PreRunE(describeCmd),\n\t\tRunE: command.RunE(describeCmd),\n\t}\n\tcmd.Flags().StringVarP(\n\t\t&describeCmd.ns,\n\t\t\"namespace\",\n\t\t\"n\",\n\t\t\"default\",\n\t\t\"The namespace in which to get the binding\",\n\t)\n\tcmd.Flags().BoolVarP(\n\t\t&describeCmd.traverse,\n\t\t\"traverse\",\n\t\t\"t\",\n\t\tfalse,\n\t\t\"Whether or not to traverse from binding -> instance -> class/plan -> broker\",\n\t)\n\treturn cmd\n}"} {"input": "package docker\n\nimport (\n\t\"github.com/fsouza/go-dockerclient\"\n\t. \"github.com/weaveworks/weave/common\"\n)\n\n\ntype ContainerObserver interface {\n\tContainerDied(ident string) error\n}\n\ntype Client struct {\n\t*docker.Client\n}\n\n\n\n\n\nfunc (c *Client) AddObserver(ob ContainerObserver) error {\n\tevents := make(chan *docker.APIEvents)\n\tif err := c.AddEventListener(events); err != nil {\n\t\tLog.Errorf(\"[docker] Unable to add listener to Docker API: %s\", err)\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tfor event := range events {\n\t\t\tswitch event.Status {\n\t\t\tcase \"die\":\n\t\t\t\tid := event.ID\n\t\t\t\tob.ContainerDied(id)\n\t\t\t}\n\t\t}\n\t}()\n\treturn nil\n}\n\n\nfunc (c *Client) IsContainerNotRunning(idStr string) bool {\n\tcontainer, err := c.InspectContainer(idStr)\n\tif err == nil {\n\t\treturn !container.State.Running\n\t}\n\tif _, notThere := err.(*docker.NoSuchContainer); notThere {\n\t\treturn true\n\t}\n\tLog.Errorf(\"[docker] Could not check container status: %s\", err)\n\treturn false\n}\n\nfunc NewClient(apiPath string) (*Client, error) ", "output": "{\n\tdc, err := docker.NewClient(apiPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &Client{dc}\n\n\tenv, err := client.Version()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tLog.Infof(\"[docker] Using Docker API on %s: %v\", apiPath, env)\n\treturn client, nil\n}"} {"input": "package sliceset\n\nimport (\n\t\"sort\"\n\n\t\"github.com/xtgo/set\"\n)\n\ntype Set []int\n\nfunc (s Set) Len() int { return len(s) }\nfunc (s Set) Less(i, j int) bool { return s[i] < s[j] }\nfunc (s Set) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s Set) Copy() Set { return append(Set(nil), s...) }\n\nfunc (s Set) Union(t Set) Set { return s.Do(set.Union, t) }\nfunc (s Set) Inter(t Set) Set { return s.Do(set.Inter, t) }\nfunc (s Set) Diff(t Set) Set { return s.Do(set.Diff, t) }\nfunc (s Set) SymDiff(t Set) Set { return s.Do(set.SymDiff, t) }\nfunc (s Set) IsSub(t Set) bool { return s.DoBool(set.IsSub, t) }\n\nfunc (s Set) IsInter(t Set) bool { return s.DoBool(set.IsInter, t) }\nfunc (s Set) IsEqual(t Set) bool { return s.DoBool(set.IsEqual, t) }\n\nfunc (s Set) Uniq() Set {\n\tn := set.Uniq(s)\n\treturn s[:n]\n}\n\nfunc (s Set) Do(op set.Op, t Set) Set {\n\tdata := append(s, t...)\n\tn := op(data, len(s))\n\treturn data[:n]\n}\n\ntype BoolOp func(sort.Interface, int) bool\n\nfunc (s Set) DoBool(op BoolOp, t Set) bool {\n\tdata := append(s, t...)\n\treturn op(data, len(s))\n}\n\nfunc (s Set) IsSuper(t Set) bool ", "output": "{ return s.DoBool(set.IsSuper, t) }"} {"input": "package main\n\nimport (\n\t. \"github.com/smartystreets/goconvey/convey\"\n\t\"testing\"\n)\n\n\n\nfunc Test_Check_New(t *testing.T) ", "output": "{\n\tHeadConvey(\"echo.websocket.org\", t, func() {\n\t\tSo(check(\"ws://echo.websocket.org\"), ShouldEqual, nil)\n\t})\n\tHeadConvey(\"echo.websocket.org ssl\", t, func() {\n\t\tSo(check(\"wss://echo.websocket.org\"), ShouldEqual, nil)\n\t})\n}"} {"input": "package terminal\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n)\n\ntype TeePrinter struct {\n\tdisableTerminalOutput bool\n\toutputBucket io.Writer\n}\n\nfunc NewTeePrinter() *TeePrinter {\n\treturn &TeePrinter{\n\t\toutputBucket: ioutil.Discard,\n\t}\n}\n\nfunc (t *TeePrinter) SetOutputBucket(bucket io.Writer) {\n\tif bucket == nil {\n\t\tbucket = ioutil.Discard\n\t}\n\n\tt.outputBucket = bucket\n}\n\nfunc (t *TeePrinter) Print(values ...interface{}) (n int, err error) {\n\tstr := fmt.Sprint(values...)\n\tt.saveOutputToBucket(str)\n\tif !t.disableTerminalOutput {\n\t\treturn fmt.Print(str)\n\t}\n\treturn\n}\n\nfunc (t *TeePrinter) Printf(format string, a ...interface{}) (n int, err error) {\n\tstr := fmt.Sprintf(format, a...)\n\tt.saveOutputToBucket(str)\n\tif !t.disableTerminalOutput {\n\t\treturn fmt.Print(str)\n\t}\n\treturn\n}\n\n\n\nfunc (t *TeePrinter) DisableTerminalOutput(disable bool) {\n\tt.disableTerminalOutput = disable\n}\n\nfunc (t *TeePrinter) saveOutputToBucket(output string) {\n\tt.outputBucket.Write([]byte(Decolorize(output)))\n}\n\nfunc (t *TeePrinter) Println(values ...interface{}) (n int, err error) ", "output": "{\n\tstr := fmt.Sprint(values...)\n\tt.saveOutputToBucket(str)\n\tif !t.disableTerminalOutput {\n\t\treturn fmt.Println(str)\n\t}\n\treturn\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype ListFastConnectProviderVirtualCircuitBandwidthShapesRequest struct {\n\n\tProviderServiceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"providerServiceId\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListFastConnectProviderVirtualCircuitBandwidthShapesResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []VirtualCircuitBandwidthShape `presentIn:\"body\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ListFastConnectProviderVirtualCircuitBandwidthShapesResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListFastConnectProviderVirtualCircuitBandwidthShapesResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) HTTPRequest(method, path string) (http.Request, error) ", "output": "{\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}"} {"input": "package garchive\n\nimport (\n\t\"archive/zip\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc writeArchive(t *testing.T, w io.Writer) {\n\tarchive := zip.NewWriter(w)\n\tdefer archive.Close()\n\n\ttestFile, err := archive.Create(\"temporary_file.txt\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tio.WriteString(testFile, \"test file\")\n}\n\n\n\nfunc TestExtractZipFileNotFound(t *testing.T) {\n\terr := ExtractZipFile(\"non_existing_zip_file.zip\", \"\")\n\tassert.Error(t, err)\n}\n\nfunc TestExtractZipFile(t *testing.T) ", "output": "{\n\ttempFile, err := ioutil.TempFile(\"\", \"archive\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tdefer tempFile.Close()\n\tdefer os.Remove(tempFile.Name())\n\twriteArchive(t, tempFile)\n\ttempFile.Close()\n\n\terr = ExtractZipFile(tempFile.Name(), \"\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\n\tstat, err := os.Stat(\"temporary_file.txt\")\n\tassert.False(t, os.IsNotExist(err), \"Expected temporary_file.txt to exist\")\n\tif !os.IsNotExist(err) {\n\t\tassert.NoError(t, err)\n\t}\n\n\tif stat != nil {\n\t\tdefer os.Remove(\"temporary_file.txt\")\n\t\tassert.Equal(t, int64(9), stat.Size())\n\t}\n}"} {"input": "package schedulercache\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/labels\"\n\t\"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache\"\n)\n\n\ntype FakeCache struct {\n\tAssumeFunc func(*api.Pod)\n}\n\nfunc (f *FakeCache) AssumePod(pod *api.Pod) error {\n\tf.AssumeFunc(pod)\n\treturn nil\n}\n\nfunc (f *FakeCache) AddPod(pod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) UpdatePod(oldPod, newPod *api.Pod) error { return nil }\n\n\n\nfunc (f *FakeCache) AddNode(node *api.Node) error { return nil }\n\nfunc (f *FakeCache) UpdateNode(oldNode, newNode *api.Node) error { return nil }\n\nfunc (f *FakeCache) RemoveNode(node *api.Node) error { return nil }\n\nfunc (f *FakeCache) UpdateNodeNameToInfoMap(infoMap map[string]*schedulercache.NodeInfo) error {\n\treturn nil\n}\n\nfunc (f *FakeCache) List(s labels.Selector) ([]*api.Pod, error) { return nil, nil }\n\nfunc (f *FakeCache) RemovePod(pod *api.Pod) error ", "output": "{ return nil }"} {"input": "package helpers\n\nimport (\n\t\"fmt\"\n\n\t. \"github.com/onsi/ginkgo\"\n)\n\nconst V7 = true\n\n\n\n\n\n\nfunc SkipIfV7() {\n\tSkip(fmt.Sprintf(\"Not implemented for V7 yet\"))\n}\n\nfunc SkipIfV7AndVersionLessThan(minVersion string) ", "output": "{\n\tSkipIfVersionLessThan(minVersion)\n}"} {"input": "package sarama\n\nimport \"testing\"\n\nvar addPartitionsToTxnRequest = []byte{\n\t0, 3, 't', 'x', 'n',\n\t0, 0, 0, 0, 0, 0, 31, 64, \n\t0, 0, 0, 0, \n\t0, 1, \n\t0, 5, 't', 'o', 'p', 'i', 'c',\n\t0, 0, 0, 1, 0, 0, 0, 1,\n}\n\n\n\nfunc TestAddPartitionsToTxnRequest(t *testing.T) ", "output": "{\n\treq := &AddPartitionsToTxnRequest{\n\t\tTransactionalID: \"txn\",\n\t\tProducerID: 8000,\n\t\tProducerEpoch: 0,\n\t\tTopicPartitions: map[string][]int32{\n\t\t\t\"topic\": {1},\n\t\t},\n\t}\n\n\ttestRequest(t, \"\", req, addPartitionsToTxnRequest)\n}"} {"input": "package handlers\n\nimport (\n\t\"github.com/THUNDERGROOVE/SDETool2/log\"\n\t\"html/template\"\n\t\"path/filepath\"\n)\n\nvar Templates map[string]*template.Template\n\n\n\nfunc LoadTemplates() {\n\tTemplates = make(map[string]*template.Template)\n\n\tglob := []string{\"template/index.tmpl\", \"template/login.tmpl\",\n\t\t\"template/fit.tmpl\", \"template/newfit.tmpl\",\n\t\t\"template/error.tmpl\", \"template/usermanage.tmpl\",\n\t\t\"template/fits.tmpl\"}\n\tincludes := []string{\"template/base.tmpl\"}\n\tfor _, v := range glob {\n\t\tvar err error\n\t\tlog.Info(\"Attempting to load template\", v, \"with index of\", filepath.Base(v))\n\t\tfiles := append(includes, v)\n\t\tTemplates[filepath.Base(v)] = template.Must(template.ParseFiles(files...))\n\t\tif err != nil {\n\t\t\tlog.LogError(err.Error())\n\t\t}\n\t}\n}\n\nfunc init() ", "output": "{\n\tif Templates == nil {\n\t\tTemplates = make(map[string]*template.Template)\n\t}\n}"} {"input": "package handler\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/cosiner/zerver\"\n)\n\ntype MethodHandler interface {\n\tGet(zerver.Request, zerver.Response)\n\tPost(zerver.Request, zerver.Response)\n\tDelete(zerver.Request, zerver.Response)\n\tPut(zerver.Request, zerver.Response)\n\tPatch(zerver.Request, zerver.Response)\n}\n\ntype methodHandler struct {\n\tzerver.Component\n\tMethodHandler\n}\n\nfunc WrapMethodHandler(m MethodHandler) zerver.Handler {\n\treturn &methodHandler{\n\t\tComponent: zerver.NopComponent{},\n\t\tMethodHandler: m,\n\t}\n}\n\nfunc (s methodHandler) Handler(method string) zerver.HandleFunc {\n\tswitch method {\n\tcase zerver.METHOD_GET:\n\t\treturn s.Get\n\tcase zerver.METHOD_POST:\n\t\treturn s.Post\n\tcase zerver.METHOD_DELETE:\n\t\treturn s.Delete\n\tcase zerver.METHOD_PUT:\n\t\treturn s.Put\n\tcase zerver.METHOD_PATCH:\n\t\treturn s.Patch\n\t}\n\n\treturn nil\n}\n\ntype NopMethodHandler struct{}\n\nfunc (NopMethodHandler) Get(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\n\n\nfunc (NopMethodHandler) Delete(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Put(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Patch(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Post(_ zerver.Request, resp zerver.Response) ", "output": "{\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}"} {"input": "package internalversion\n\nimport (\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n\tadmissionregistration \"k8s.io/kubernetes/pkg/apis/admissionregistration\"\n)\n\n\ntype InitializerConfigurationLister interface {\n\tList(selector labels.Selector) (ret []*admissionregistration.InitializerConfiguration, err error)\n\tGet(name string) (*admissionregistration.InitializerConfiguration, error)\n\tInitializerConfigurationListerExpansion\n}\n\n\ntype initializerConfigurationLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewInitializerConfigurationLister(indexer cache.Indexer) InitializerConfigurationLister {\n\treturn &initializerConfigurationLister{indexer: indexer}\n}\n\n\n\n\n\nfunc (s *initializerConfigurationLister) Get(name string) (*admissionregistration.InitializerConfiguration, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(admissionregistration.Resource(\"initializerconfiguration\"), name)\n\t}\n\treturn obj.(*admissionregistration.InitializerConfiguration), nil\n}\n\nfunc (s *initializerConfigurationLister) List(selector labels.Selector) (ret []*admissionregistration.InitializerConfiguration, err error) ", "output": "{\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*admissionregistration.InitializerConfiguration))\n\t})\n\treturn ret, err\n}"} {"input": "package libcontainer\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestCapabilitiesContains(t *testing.T) {\n\tcaps := Capabilities{\n\t\tGetCapability(\"MKNOD\"),\n\t\tGetCapability(\"SETPCAP\"),\n\t}\n\n\tif caps.Contains(\"SYS_ADMIN\") {\n\t\tt.Fatal(\"capabilities should not contain SYS_ADMIN\")\n\t}\n\tif !caps.Contains(\"MKNOD\") {\n\t\tt.Fatal(\"capabilities should contain MKNOD but does not\")\n\t}\n}\n\nfunc TestNamespacesContains(t *testing.T) ", "output": "{\n\tns := Namespaces{\n\t\tGetNamespace(\"NEWPID\"),\n\t\tGetNamespace(\"NEWNS\"),\n\t\tGetNamespace(\"NEWUTS\"),\n\t}\n\n\tif ns.Contains(\"NEWNET\") {\n\t\tt.Fatal(\"namespaces should not contain NEWNET\")\n\t}\n\n\tif !ns.Contains(\"NEWPID\") {\n\t\tt.Fatal(\"namespaces should contain NEWPID but does not\")\n\t}\n\n\twithNil := Namespaces{\n\t\tGetNamespace(\"UNDEFINED\"), \n\t\tGetNamespace(\"NEWPID\"),\n\t}\n\n\tif !withNil.Contains(\"NEWPID\") {\n\t\tt.Fatal(\"namespaces should contain NEWPID but does not\")\n\t}\n}"} {"input": "package browser\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"runtime\"\n)\n\n\nfunc Commands() [][]string {\n\tvar cmds [][]string\n\tif exe := os.Getenv(\"BROWSER\"); exe != \"\" {\n\t\tcmds = append(cmds, []string{exe})\n\t}\n\tswitch runtime.GOOS {\n\tcase \"darwin\":\n\t\tcmds = append(cmds, []string{\"/usr/bin/open\"})\n\tcase \"windows\":\n\t\tcmds = append(cmds, []string{\"cmd\", \"/c\", \"start\"})\n\tdefault:\n\t\tcmds = append(cmds, []string{\"xdg-open\"})\n\t}\n\tcmds = append(cmds,\n\t\t[]string{\"chrome\"},\n\t\t[]string{\"google-chrome\"},\n\t\t[]string{\"chromium\"},\n\t\t[]string{\"firefox\"},\n\t)\n\treturn cmds\n}\n\n\n\n\nfunc Open(url string) bool ", "output": "{\n\tfor _, args := range Commands() {\n\t\tcmd := exec.Command(args[0], append(args[1:], url)...) \n\t\tif cmd.Start() == nil {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package models\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/jinzhu/gorm\"\n)\n\nconst (\n\tMovieTypeYoutube = 1\n)\n\n\ntype UserContributionMovie struct {\n\tBaseModel\n\tUserContributionID int `json:\"user_contribution_id\"`\n\tMovieType int `json:\"movie_type\"`\n\tMovieID string `json:\"movie_id\"`\n\tMovieStatus int `json:\"movie_status\"`\n}\n\n\nfunc (u *UserContributionMovie) Add() error {\n\treturn Create(u)\n}\n\n\nfunc (u *UserContributionMovie) Save() error {\n\treturn Save(u)\n}\n\n\nfunc (u *UserContributionMovie) GetByUserContributionID(uID int, t int) (userContributionMovie UserContributionMovie, db *gorm.DB, err error) {\n\twhereList := []map[string]interface{}{\n\t\t{\"UserContributionID\": uID},\n\t\t{\"MovieType\": t},\n\t}\n\toption := make(map[string]interface{})\n\n\tdb, err = GetWhere(&userContributionMovie, \"User_contribution_ID = :UserContributionID AND movie_type = :MovieType\", whereList, option)\n\n\treturn\n}\n\n\n\n\n\nfunc (u *UserContributionMovie) GetListByMovieStatusPublic() (userContributionMovie []UserContributionMovie, db *gorm.DB, err error) {\n\twhereList := []map[string]interface{}{}\n\toption := make(map[string]interface{})\n\n\tdb, err = GetListWhere(&userContributionMovie, \"movie_status = \"+strconv.Itoa(StatusPublic), whereList, option)\n\n\treturn\n}\n\nfunc (u *UserContributionMovie) GetListByUserContributionIDList(uID []int, t int) (userContributionMovie []UserContributionMovie, db *gorm.DB, err error) ", "output": "{\n\twhereList := []map[string]interface{}{\n\t\t{\"UserContributionID\": uID},\n\t\t{\"MovieType\": t},\n\t}\n\toption := make(map[string]interface{})\n\n\tdb, err = GetListWhere(&userContributionMovie, \"User_contribution_ID IN :UserContributionID AND movie_type = :MovieType AND movie_status = \"+strconv.Itoa(StatusPublic), whereList, option)\n\n\treturn\n}"} {"input": "package rest\n\nimport (\n\t\"time\"\n\n\teventsapiv1beta1 \"k8s.io/api/events/v1beta1\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\t\"k8s.io/apiserver/pkg/registry/rest\"\n\tgenericapiserver \"k8s.io/apiserver/pkg/server\"\n\tserverstorage \"k8s.io/apiserver/pkg/server/storage\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\t\"k8s.io/kubernetes/pkg/apis/events\"\n\teventstore \"k8s.io/kubernetes/pkg/registry/core/event/storage\"\n)\n\ntype RESTStorageProvider struct {\n\tTTL time.Duration\n}\n\n\n\nfunc (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage {\n\tstorage := map[string]rest.Storage{}\n\teventsStorage := eventstore.NewREST(restOptionsGetter, uint64(p.TTL.Seconds()))\n\tstorage[\"events\"] = eventsStorage\n\n\treturn storage\n}\n\nfunc (p RESTStorageProvider) GroupName() string {\n\treturn events.GroupName\n}\n\nfunc (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) ", "output": "{\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(events.GroupName, legacyscheme.Registry, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\n\tif apiResourceConfigSource.VersionEnabled(eventsapiv1beta1.SchemeGroupVersion) {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[eventsapiv1beta1.SchemeGroupVersion.Version] = p.v1beta1Storage(apiResourceConfigSource, restOptionsGetter)\n\t\tapiGroupInfo.GroupMeta.GroupVersion = eventsapiv1beta1.SchemeGroupVersion\n\t}\n\n\treturn apiGroupInfo, true\n}"} {"input": "package agent\n\nimport (\n\t\"github.com/socketplane/socketplane/Godeps/_workspace/src/github.com/hashicorp/logutils\"\n\t\"log\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype MockStreamClient struct {\n\theaders []*responseHeader\n\tobjs []interface{}\n\terr error\n}\n\n\n\nfunc TestRPCLogStream(t *testing.T) {\n\tsc := &MockStreamClient{}\n\tfilter := LevelFilter()\n\tfilter.MinLevel = logutils.LogLevel(\"INFO\")\n\n\tls := newLogStream(sc, filter, 42, log.New(os.Stderr, \"\", log.LstdFlags))\n\tdefer ls.Stop()\n\n\tlog := \"[DEBUG] this is a test log\"\n\tlog2 := \"[INFO] This should pass\"\n\tls.HandleLog(log)\n\tls.HandleLog(log2)\n\n\ttime.Sleep(5 * time.Millisecond)\n\n\tif len(sc.headers) != 1 {\n\t\tt.Fatalf(\"expected 1 messages!\")\n\t}\n\tfor _, h := range sc.headers {\n\t\tif h.Seq != 42 {\n\t\t\tt.Fatalf(\"bad seq\")\n\t\t}\n\t\tif h.Error != \"\" {\n\t\t\tt.Fatalf(\"bad err\")\n\t\t}\n\t}\n\n\tobj1 := sc.objs[0].(*logRecord)\n\tif obj1.Log != log2 {\n\t\tt.Fatalf(\"bad event %#v\", obj1)\n\t}\n}\n\nfunc (m *MockStreamClient) Send(h *responseHeader, o interface{}) error ", "output": "{\n\tm.headers = append(m.headers, h)\n\tm.objs = append(m.objs, o)\n\treturn m.err\n}"} {"input": "package corehttp\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\n\tcore \"github.com/ipfs/go-ipfs/core\"\n\tlogging \"github.com/ipfs/go-ipfs/vendor/QmQg1J6vikuXF9oDvm4wpdeAUvvkVEKW1EYDw9HhTMnP2b/go-log\"\n)\n\ntype writeErrNotifier struct {\n\tw io.Writer\n\terrs chan error\n}\n\n\n\nfunc (w *writeErrNotifier) Write(b []byte) (int, error) {\n\tn, err := w.w.Write(b)\n\tif err != nil {\n\t\tselect {\n\t\tcase w.errs <- err:\n\t\tdefault:\n\t\t}\n\t}\n\tif f, ok := w.w.(http.Flusher); ok {\n\t\tf.Flush()\n\t}\n\treturn n, err\n}\n\nfunc (w *writeErrNotifier) Close() error {\n\tselect {\n\tcase w.errs <- io.EOF:\n\tdefault:\n\t}\n\treturn nil\n}\n\nfunc LogOption() ServeOption {\n\treturn func(n *core.IpfsNode, _ net.Listener, mux *http.ServeMux) (*http.ServeMux, error) {\n\t\tmux.HandleFunc(\"/logs\", func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.WriteHeader(200)\n\t\t\twnf, errs := newWriteErrNotifier(w)\n\t\t\tlogging.WriterGroup.AddWriter(wnf)\n\t\t\tlog.Event(n.Context(), \"log API client connected\")\n\t\t\t<-errs\n\t\t})\n\t\treturn mux, nil\n\t}\n}\n\nfunc newWriteErrNotifier(w io.Writer) (io.WriteCloser, <-chan error) ", "output": "{\n\tch := make(chan error, 1)\n\treturn &writeErrNotifier{\n\t\tw: w,\n\t\terrs: ch,\n\t}, ch\n}"} {"input": "package echo\n\nimport (\n\t\"context\"\n\n\t\"github.com/uber/zanzibar/examples/example-gateway/build/endpoints/tchannel/echo/module\"\n\t\"github.com/uber/zanzibar/examples/example-gateway/build/endpoints/tchannel/echo/workflow\"\n\t\"github.com/uber/zanzibar/examples/example-gateway/build/gen-code/endpoints-idl/endpoints/tchannel/echo/echo\"\n\tzanzibar \"github.com/uber/zanzibar/runtime\"\n)\n\n\nfunc NewEchoEchoWorkflow(deps *module.Dependencies) workflow.EchoEchoWorkflow {\n\treturn &echoWorkflow{}\n}\n\ntype echoWorkflow struct{}\n\n\n\n\nfunc (w echoWorkflow) Handle(\n\tctx context.Context,\n\treqHeaders zanzibar.Header,\n\treq *echo.Echo_Echo_Args,\n) (context.Context, string, zanzibar.Header, error) ", "output": "{\n\treturn ctx, req.Msg, nil, nil\n}"} {"input": "package ssa\n\nimport \"fmt\"\n\nconst _BinOpType_name = \"BinOpAddBinOpSubBinOpMulBinOpSDivBinOpUDivBinOpSRemBinOpURemBinOpFAddBinOpFSubBinOpFMulBinOpFDivBinOpFRemBinOpShlBinOpLShrBinOpRShrBinOpAndBinOpOrBinOpXor\"\n\nvar _BinOpType_index = [...]uint8{8, 16, 24, 33, 42, 51, 60, 69, 78, 87, 96, 105, 113, 122, 131, 139, 146, 154}\n\n\n\nfunc (i BinOpType) String() string ", "output": "{\n\tif i < 0 || i >= BinOpType(len(_BinOpType_index)) {\n\t\treturn fmt.Sprintf(\"BinOpType(%d)\", i)\n\t}\n\thi := _BinOpType_index[i]\n\tlo := uint8(0)\n\tif i > 0 {\n\t\tlo = _BinOpType_index[i-1]\n\t}\n\treturn _BinOpType_name[lo:hi]\n}"} {"input": "package main\n\nimport \"fmt\"\n\nconst (\n\tBig = 1 << 100\n\tSmall = Big >> 99\n)\n\n\n\nfunc needFloat(x float64) float64 {\n\treturn x * 0.1\n}\n\nfunc main() {\n\tfmt.Println(needInt(Small))\n\tfmt.Println(needFloat(Small))\n\tfmt.Println(needFloat(Big))\n}\n\nfunc needInt(x int) int ", "output": "{\n\treturn x*10 + 1\n}"} {"input": "package disk\n\nimport (\n\t\"reflect\"\n\n\tbicloud \"github.com/cloudfoundry/bosh-init/cloud\"\n\tbiconfig \"github.com/cloudfoundry/bosh-init/config\"\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n\tbiproperty \"github.com/cloudfoundry/bosh-utils/property\"\n)\n\ntype Disk interface {\n\tCID() string\n\tNeedsMigration(newSize int, newCloudProperties biproperty.Map) bool\n\tDelete() error\n}\n\ntype disk struct {\n\tcid string\n\tsize int\n\tcloudProperties biproperty.Map\n\n\tcloud bicloud.Cloud\n\trepo biconfig.DiskRepo\n}\n\nfunc NewDisk(\n\tdiskRecord biconfig.DiskRecord,\n\tcloud bicloud.Cloud,\n\trepo biconfig.DiskRepo,\n) Disk {\n\treturn &disk{\n\t\tcid: diskRecord.CID,\n\t\tsize: diskRecord.Size,\n\t\tcloudProperties: diskRecord.CloudProperties,\n\t\tcloud: cloud,\n\t\trepo: repo,\n\t}\n}\n\nfunc (d *disk) CID() string {\n\treturn d.cid\n}\n\nfunc (d *disk) NeedsMigration(newSize int, newCloudProperties biproperty.Map) bool {\n\treturn d.size != newSize || !reflect.DeepEqual(d.cloudProperties, newCloudProperties)\n}\n\n\n\nfunc (d *disk) Delete() error ", "output": "{\n\tdeleteErr := d.cloud.DeleteDisk(d.cid)\n\tif deleteErr != nil {\n\t\tcloudErr, ok := deleteErr.(bicloud.Error)\n\t\tif !ok || cloudErr.Type() != bicloud.DiskNotFoundError {\n\t\t\treturn bosherr.WrapError(deleteErr, \"Deleting disk in the cloud\")\n\t\t}\n\t}\n\n\tdiskRecord, found, err := d.repo.Find(d.cid)\n\tif err != nil {\n\t\treturn bosherr.WrapErrorf(err, \"Finding disk record (cid=%s)\", d.cid)\n\t}\n\n\tif !found {\n\t\treturn nil\n\t}\n\n\terr = d.repo.Delete(diskRecord)\n\tif err != nil {\n\t\treturn bosherr.WrapError(err, \"Deleting disk record\")\n\t}\n\n\treturn deleteErr\n}"} {"input": "package brontidefuzz\n\nimport (\n\t\"bytes\"\n)\n\n\n\n\n\nfunc Fuzz_random_init_decrypt(data []byte) int ", "output": "{\n\tinitiator, responder := getBrontideMachines()\n\n\tcompleteHandshake(initiator, responder)\n\n\tr := bytes.NewReader(data)\n\n\tif _, err := initiator.ReadMessage(r); err == nil {\n\t\tnilAndPanic(initiator, responder, nil)\n\t}\n\n\treturn 1\n}"} {"input": "package main\n\nimport (\n\t\"time\"\n\n\t\"golang.org/x/text/language\"\n)\n\n\n\nconst (\n\tcashShift = 3\n\troundMask = 0x7\n\n\tnonTenderBit = 0x8000\n)\n\n\n\n\ntype currencyInfo byte\n\n\n\n\ntype roundingType struct {\n\tscale, increment uint8\n}\n\n\n\nvar roundings = [...]roundingType{\n\t{2, 1}, \n\t{0, 1},\n\t{1, 1},\n\t{3, 1},\n\t{4, 1},\n\t{2, 5}, \n\t{2, 50},\n}\n\n\n\n\n\nfunc toDate(t time.Time) uint32 {\n\ty := t.Year()\n\tif y == 1 {\n\t\treturn 0\n\t}\n\tdate := uint32(y) << 4\n\tdate |= uint32(t.Month())\n\tdate <<= 5\n\tdate |= uint32(t.Day())\n\treturn date\n}\n\nfunc fromDate(date uint32) time.Time {\n\treturn time.Date(int(date>>9), time.Month((date>>5)&0xf), int(date&0x1f), 0, 0, 0, 0, time.UTC)\n}\n\nfunc regionToCode(r language.Region) uint16 ", "output": "{\n\tif s := r.String(); len(s) == 2 {\n\t\treturn uint16(s[0])<<8 | uint16(s[1])\n\t}\n\treturn 0\n}"} {"input": "package greq\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\nfunc Bytes(res *http.Response, err error) ([]byte, error) {\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn body, nil\n}\n\n\n\nfunc JSON(res *http.Response, err error, ptr interface{}) error {\n\tbody, err := Bytes(res, err)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(body, ptr)\n}\n\nfunc String(res *http.Response, err error) (string, error) ", "output": "{\n\tbody, err := Bytes(res, err)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}"} {"input": "package jujuc\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"launchpad.net/gnuflag\"\n\n\t\"github.com/juju/core/cmd\"\n)\n\n\ntype UnitGetCommand struct {\n\tcmd.CommandBase\n\tctx Context\n\tKey string\n\tout cmd.Output\n}\n\nfunc NewUnitGetCommand(ctx Context) cmd.Command {\n\treturn &UnitGetCommand{ctx: ctx}\n}\n\nfunc (c *UnitGetCommand) Info() *cmd.Info {\n\treturn &cmd.Info{\n\t\tName: \"unit-get\",\n\t\tArgs: \"\",\n\t\tPurpose: \"print public-address or private-address\",\n\t}\n}\n\n\n\nfunc (c *UnitGetCommand) Init(args []string) error {\n\tif args == nil {\n\t\treturn errors.New(\"no setting specified\")\n\t}\n\tif args[0] != \"private-address\" && args[0] != \"public-address\" {\n\t\treturn fmt.Errorf(\"unknown setting %q\", args[0])\n\t}\n\tc.Key = args[0]\n\treturn cmd.CheckEmpty(args[1:])\n}\n\nfunc (c *UnitGetCommand) Run(ctx *cmd.Context) error {\n\tvalue, ok := \"\", false\n\tif c.Key == \"private-address\" {\n\t\tvalue, ok = c.ctx.PrivateAddress()\n\t} else {\n\t\tvalue, ok = c.ctx.PublicAddress()\n\t}\n\tif !ok {\n\t\treturn fmt.Errorf(\"%s not set\", c.Key)\n\t}\n\treturn c.out.Write(ctx, value)\n}\n\nfunc (c *UnitGetCommand) SetFlags(f *gnuflag.FlagSet) ", "output": "{\n\tc.out.AddFlags(f, \"smart\", cmd.DefaultFormatters)\n}"} {"input": "package term\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc IsANSI(f *os.File) bool {\n\treturn IsTerminal(f)\n}\n\n\nfunc IsTerminal(f *os.File) bool {\n\tcmd := exec.Command(\"test\", \"-t\", \"0\")\n\tcmd.Stdin = f\n\treturn cmd.Run() == nil\n}\n\nfunc MakeRaw(f *os.File) error {\n\treturn stty(f, \"-icanon\", \"-echo\").Run()\n}\n\nfunc Restore(f *os.File) error {\n\treturn stty(f, \"icanon\", \"echo\").Run()\n}\n\nfunc Cols() (int, error) {\n\tcols, err := tput(\"cols\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}\n\n\n\n\n\nfunc stty(f *os.File, args ...string) *exec.Cmd {\n\tc := exec.Command(\"stty\", args...)\n\tc.Stdin = f\n\treturn c\n}\n\nfunc tput(what string) (string, error) {\n\tc := exec.Command(\"tput\", what)\n\tc.Stderr = os.Stderr\n\tout, err := c.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.TrimSpace(string(out)), nil\n}\n\nfunc Lines() (int, error) ", "output": "{\n\tcols, err := tput(\"lines\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}"} {"input": "package etcd\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\t\"k8s.io/apiserver/pkg/registry/generic/registry\"\n\tkapi \"k8s.io/kubernetes/pkg/api\"\n\n\t\"github.com/openshift/origin/pkg/sdn/api\"\n\t\"github.com/openshift/origin/pkg/sdn/registry/clusternetwork\"\n\t\"github.com/openshift/origin/pkg/user/registry/user\"\n\t\"github.com/openshift/origin/pkg/util/restoptions\"\n)\n\n\ntype REST struct {\n\t*registry.Store\n}\n\n\n\n\nfunc NewREST(optsGetter restoptions.Getter) (*REST, error) ", "output": "{\n\tstore := ®istry.Store{\n\t\tCopier: kapi.Scheme,\n\t\tNewFunc: func() runtime.Object { return &api.ClusterNetwork{} },\n\t\tNewListFunc: func() runtime.Object { return &api.ClusterNetworkList{} },\n\t\tPredicateFunc: clusternetwork.Matcher,\n\t\tQualifiedResource: api.Resource(\"clusternetworks\"),\n\n\t\tCreateStrategy: clusternetwork.Strategy,\n\t\tUpdateStrategy: clusternetwork.Strategy,\n\t\tDeleteStrategy: clusternetwork.Strategy,\n\t}\n\n\toptions := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: user.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &REST{store}, nil\n}"} {"input": "package vmdk\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"github.com/sisatech/vcli/shared\"\n)\n\ntype builder struct {\n\tenv *Environment\n\tdisk *os.File\n\tfastFilesHeader *os.File\n\tfastFiles *os.File\n\tfiles *os.File\n\targs *BuildArgs\n\tconfig *shared.BuildConfig\n\tdescriptor *bytes.Buffer\n\toverhead overhead\n\tcontent content\n\theader Header\n\tseek int64\n\tsector uint64\n\tgrainCounter uint64\n\tgrains []uint64\n\tfinalGrain []byte\n\tstreamOptimized bool\n\tstreamCurrentTable int\n\tstreamTable []uint32\n\tstreamDirectory []uint32\n}\n\nfunc (env *Environment) newBuilder(args *BuildArgs) *builder {\n\n\tbuild := &builder{\n\t\tenv: env,\n\t\targs: args,\n\t}\n\n\tbuild.streamTable = make([]uint32, 512)\n\n\treturn build\n\n}\n\nfunc (build *builder) log(s string, args ...interface{}) {\n\n\tif build.env.talk {\n\t\tfmt.Printf(s+\"\\n\", args...)\n\t}\n\n}\n\n\n\nfunc (build *builder) newDisk() error ", "output": "{\n\n\tvar err error\n\n\tif build.args.Destination == \"\" {\n\n\n\t\tbuild.disk, err = ioutil.TempFile(\"\", \"vmdk-\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t} else {\n\n\n\t\tvar info os.FileInfo\n\t\tinfo, err = os.Stat(build.args.Destination)\n\t\tif !os.IsNotExist(err) {\n\n\t\t\tif info != nil && info.IsDir() {\n\t\t\t\treturn fmt.Errorf(\"destination '%s' is a directory\",\n\t\t\t\t\tbuild.args.Destination)\n\t\t\t}\n\n\t\t\terr = os.Remove(build.args.Destination)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t}\n\n\t\tbuild.disk, err = os.Create(build.args.Destination)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n\n}"} {"input": "package iso20022\n\n\ntype BillingServicesTax2 struct {\n\n\tNumber *Max35Text `xml:\"Nb\"`\n\n\tDescription *Max40Text `xml:\"Desc,omitempty\"`\n\n\tRate *DecimalNumber `xml:\"Rate\"`\n\n\tPricingAmount *AmountAndDirection34 `xml:\"PricgAmt\"`\n}\n\n\n\nfunc (b *BillingServicesTax2) SetDescription(value string) {\n\tb.Description = (*Max40Text)(&value)\n}\n\nfunc (b *BillingServicesTax2) SetRate(value string) {\n\tb.Rate = (*DecimalNumber)(&value)\n}\n\nfunc (b *BillingServicesTax2) AddPricingAmount() *AmountAndDirection34 {\n\tb.PricingAmount = new(AmountAndDirection34)\n\treturn b.PricingAmount\n}\n\nfunc (b *BillingServicesTax2) SetNumber(value string) ", "output": "{\n\tb.Number = (*Max35Text)(&value)\n}"} {"input": "package main\n\nimport (\n\t. \"launchpad.net/gocheck\"\n\t\"launchpad.net/juju-core/charm\"\n\tjujutesting \"launchpad.net/juju-core/juju/testing\"\n\t\"launchpad.net/juju-core/testing\"\n)\n\ntype ExposeSuite struct {\n\tjujutesting.RepoSuite\n}\n\nvar _ = Suite(&ExposeSuite{})\n\nfunc runExpose(c *C, args ...string) error {\n\t_, err := testing.RunCommand(c, &ExposeCommand{}, args)\n\treturn err\n}\n\nfunc (s *ExposeSuite) assertExposed(c *C, service string) {\n\tsvc, err := s.State.Service(service)\n\tc.Assert(err, IsNil)\n\texposed := svc.IsExposed()\n\tc.Assert(exposed, Equals, true)\n}\n\n\n\nfunc (s *ExposeSuite) TestExpose(c *C) ", "output": "{\n\ttesting.Charms.BundlePath(s.SeriesPath, \"dummy\")\n\terr := runDeploy(c, \"local:dummy\", \"some-service-name\")\n\tc.Assert(err, IsNil)\n\tcurl := charm.MustParseURL(\"local:precise/dummy-1\")\n\ts.AssertService(c, \"some-service-name\", curl, 1, 0)\n\n\terr = runExpose(c, \"some-service-name\")\n\tc.Assert(err, IsNil)\n\ts.assertExposed(c, \"some-service-name\")\n\n\terr = runExpose(c, \"nonexistent-service\")\n\tc.Assert(err, ErrorMatches, `service \"nonexistent-service\" not found`)\n}"} {"input": "package msgpackzip\n\nimport (\n\t\"bytes\"\n\t\"compress/flate\"\n\t\"io/ioutil\"\n)\n\nfunc flateCompress(b []byte) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tzw, err := flate.NewWriter(&buf, flate.DefaultCompression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = zw.Write(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = zw.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}\n\n\n\nfunc flateInflate(b []byte) ([]byte, error) ", "output": "{\n\tbuf := bytes.NewBuffer(b)\n\tzr := flate.NewReader(buf)\n\treturn ioutil.ReadAll(zr)\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime/middleware\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\n\n\n\n\n\n\ntype DownloadImageParams struct {\n\n\tHTTPRequest *http.Request\n\n\tImageID string\n}\n\n\n\nfunc (o *DownloadImageParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {\n\tvar res []error\n\to.HTTPRequest = r\n\n\trImageID, rhkImageID, _ := route.Params.GetOK(\"imageId\")\n\tif err := o.bindImageID(rImageID, rhkImageID, route.Formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (o *DownloadImageParams) bindImageID(rawData []string, hasKey bool, formats strfmt.Registry) error {\n\tvar raw string\n\tif len(rawData) > 0 {\n\t\traw = rawData[len(rawData)-1]\n\t}\n\n\to.ImageID = raw\n\n\treturn nil\n}\n\nfunc NewDownloadImageParams() DownloadImageParams ", "output": "{\n\tvar ()\n\treturn DownloadImageParams{}\n}"} {"input": "package gorilla\n\nimport (\n\t\"net/http\"\n\n\tgcontext \"github.com/gorilla/context\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\nfunc NewContext(parent context.Context, req *http.Request) context.Context {\n\treturn &wrapper{parent, req}\n}\n\ntype wrapper struct {\n\tcontext.Context\n\treq *http.Request\n}\n\ntype key int\n\nconst reqKey key = 0\n\n\n\nfunc (ctx *wrapper) Value(key interface{}) interface{} {\n\tif key == reqKey {\n\t\treturn ctx.req\n\t}\n\tif val, ok := gcontext.GetOk(ctx.req, key); ok {\n\t\treturn val\n\t}\n\treturn ctx.Context.Value(key)\n}\n\n\n\n\n\nfunc HTTPRequest(ctx context.Context) (*http.Request, bool) ", "output": "{\n\treq, ok := ctx.Value(reqKey).(*http.Request)\n\treturn req, ok\n}"} {"input": "package users\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime/middleware\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewDeleteUserByIDParams() DeleteUserByIDParams {\n\tvar ()\n\treturn DeleteUserByIDParams{}\n}\n\n\n\n\n\ntype DeleteUserByIDParams struct {\n\n\tHTTPRequest *http.Request `json:\"-\"`\n\n\tUserID string\n}\n\n\n\nfunc (o *DeleteUserByIDParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {\n\tvar res []error\n\to.HTTPRequest = r\n\n\trUserID, rhkUserID, _ := route.Params.GetOK(\"userID\")\n\tif err := o.bindUserID(rUserID, rhkUserID, route.Formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\nfunc (o *DeleteUserByIDParams) bindUserID(rawData []string, hasKey bool, formats strfmt.Registry) error ", "output": "{\n\tvar raw string\n\tif len(rawData) > 0 {\n\t\traw = rawData[len(rawData)-1]\n\t}\n\n\to.UserID = raw\n\n\treturn nil\n}"} {"input": "package solution\n\n\n\nfunc increasingTriplet(nums []int) bool ", "output": "{\n\tconst unknown = -1\n\ti, j := 0, unknown\n\tfor l := 1; l < len(nums); l++ {\n\t\tswitch {\n\t\tcase j != unknown && nums[l] > nums[j]:\n\t\t\treturn true\n\t\tcase nums[l] < nums[i]:\n\t\t\ti = l\n\t\tcase nums[i] < nums[l] && (j == unknown || nums[l] < nums[j]):\n\t\t\tj = l\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package fetch\n\nimport (\n\t\"github.com/hltcoe/goncrete\"\n\t\"github.com/maxthomas/hardhat/pkg/memory\"\n\t\"go.uber.org/zap\"\n)\n\ntype MemoryFetcher struct {\n\tom *memory.OrderedMap\n\tlogger *zap.Logger\n}\n\nfunc NewMemoryFetcher(om *memory.OrderedMap, logger *zap.Logger) *MemoryFetcher {\n\treturn &MemoryFetcher{om, logger}\n}\n\nvar (\n\t_ goncrete.FetchCommunicationService = (*MemoryFetcher)(nil)\n)\n\nfunc (g *MemoryFetcher) Alive() (bool, error) {\n\tg.logger.Info(\"called\", zap.String(\"method\", \"alive\"))\n\treturn true, nil\n}\n\nfunc (g *MemoryFetcher) About() (*goncrete.ServiceInfo, error) {\n\tg.logger.Info(\"called\", zap.String(\"method\", \"about\"))\n\tsi := goncrete.NewServiceInfo()\n\tsi.Name = \"MemoryFetcher\"\n\tsi.Version = \"0.0.1\"\n\treturn si, nil\n}\n\n\n\nfunc (g *MemoryFetcher) GetCommunicationCount() (int64, error) {\n\tg.logger.Info(\"called\", zap.String(\"method\", \"comms-count\"))\n\treturn int64(g.om.Len()), nil\n}\n\nfunc (g *MemoryFetcher) GetCommunicationIDs(off int64, count int64) ([]string, error) {\n\tg.logger.Info(\"called\",\n\t\tzap.String(\"method\", \"get-comm-ids\"),\n\t\tzap.Int64(\"offset\", off), zap.Int64(\"count\", count),\n\t)\n\tstart, diff := int(off), int(count)\n\tids := g.om.Slice(start, start+diff)\n\tg.logger.Debug(\"returning\", zap.Strings(\"items\", ids))\n\treturn ids, nil\n}\n\nfunc (g *MemoryFetcher) Fetch(req *goncrete.FetchRequest) (*goncrete.FetchResult_, error) ", "output": "{\n\tg.logger.Info(\"called\", zap.String(\"method\", \"fetch\"))\n\tfr := goncrete.NewFetchResult_()\n\tfr.Communications = make([]*goncrete.Communication, 0)\n\tfor _, id := range req.CommunicationIds {\n\t\titem, present := g.om.Get(id)\n\t\tif present {\n\t\t\tfr.Communications = append(fr.Communications, &item)\n\t\t}\n\t}\n\treturn fr, nil\n}"} {"input": "package distribution \n\nimport \"github.com/tiborvass/docker/api/server/router\"\n\n\ntype distributionRouter struct {\n\tbackend Backend\n\troutes []router.Route\n}\n\n\nfunc NewRouter(backend Backend) router.Router {\n\tr := &distributionRouter{\n\t\tbackend: backend,\n\t}\n\tr.initRoutes()\n\treturn r\n}\n\n\nfunc (r *distributionRouter) Routes() []router.Route {\n\treturn r.routes\n}\n\n\n\n\nfunc (r *distributionRouter) initRoutes() ", "output": "{\n\tr.routes = []router.Route{\n\t\trouter.NewGetRoute(\"/distribution/{name:.*}/json\", r.getDistributionInfo),\n\t}\n}"} {"input": "package model\n\nimport \"time\"\n\ntype folder struct {\n\tstateTracker\n\tscan folderscan\n\tmodel *Model\n\tstop chan struct{}\n}\n\nfunc (f *folder) IndexUpdated() {\n}\n\nfunc (f *folder) DelayScan(next time.Duration) {\n\tf.scan.Delay(next)\n}\n\nfunc (f *folder) Scan(subdirs []string) error {\n\treturn f.scan.Scan(subdirs)\n}\nfunc (f *folder) Stop() {\n\tclose(f.stop)\n}\n\n\n\nfunc (f *folder) BringToFront(string) {}\n\nfunc (f *folder) scanSubdirsIfHealthy(subDirs []string) error {\n\tif err := f.model.CheckFolderHealth(f.folderID); err != nil {\n\t\tl.Infoln(\"Skipping folder\", f.folderID, \"scan due to folder error:\", err)\n\t\treturn err\n\t}\n\tl.Debugln(f, \"Scanning subdirectories\")\n\tif err := f.model.internalScanFolderSubdirs(f.folderID, subDirs); err != nil {\n\t\tf.setError(err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (f *folder) Jobs() ([]string, []string) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package tsmt\n\nimport (\n\t\"encoding/xml\"\n\n\t\"github.com/fgrid/iso20022\"\n)\n\ntype Document05500101 struct {\n\tXMLName xml.Name `xml:\"urn:iso:std:iso:20022:tech:xsd:tsmt.055.001.01 Document\"`\n\tMessage *PartyEventAdviceV01 `xml:\"PtyEvtAdvc\"`\n}\n\n\n\n\n\n\n\ntype PartyEventAdviceV01 struct {\n\n\tHeader *iso20022.BusinessLetter1 `xml:\"Hdr\"`\n\n\tEventNotice []*iso20022.EventDescription1 `xml:\"EvtNtce\"`\n\n\tEventCount *iso20022.Max15NumericText `xml:\"EvtCnt,omitempty\"`\n\n\tAttachedMessage []*iso20022.EncapsulatedBusinessMessage1 `xml:\"AttchdMsg,omitempty\"`\n}\n\nfunc (p *PartyEventAdviceV01) AddHeader() *iso20022.BusinessLetter1 {\n\tp.Header = new(iso20022.BusinessLetter1)\n\treturn p.Header\n}\n\nfunc (p *PartyEventAdviceV01) AddEventNotice() *iso20022.EventDescription1 {\n\tnewValue := new(iso20022.EventDescription1)\n\tp.EventNotice = append(p.EventNotice, newValue)\n\treturn newValue\n}\n\nfunc (p *PartyEventAdviceV01) SetEventCount(value string) {\n\tp.EventCount = (*iso20022.Max15NumericText)(&value)\n}\n\nfunc (p *PartyEventAdviceV01) AddAttachedMessage() *iso20022.EncapsulatedBusinessMessage1 {\n\tnewValue := new(iso20022.EncapsulatedBusinessMessage1)\n\tp.AttachedMessage = append(p.AttachedMessage, newValue)\n\treturn newValue\n}\n\nfunc (d *Document05500101) AddMessage() *PartyEventAdviceV01 ", "output": "{\n\td.Message = new(PartyEventAdviceV01)\n\treturn d.Message\n}"} {"input": "package mocks\n\nimport (\n\tcli \"github.com/stackanetes/kubernetes-entrypoint/client\"\n\tv1batch \"k8s.io/client-go/1.5/kubernetes/typed/batch/v1\"\n\tv1core \"k8s.io/client-go/1.5/kubernetes/typed/core/v1\"\n\tv1beta1extensions \"k8s.io/client-go/1.5/kubernetes/typed/extensions/v1beta1\"\n)\n\ntype Client struct {\n\tv1core.PodInterface\n\tv1core.ServiceInterface\n\tv1beta1extensions.DaemonSetInterface\n\tv1core.EndpointsInterface\n\tv1batch.JobInterface\n}\n\nfunc (c Client) Pods(namespace string) v1core.PodInterface {\n\treturn c.PodInterface\n}\n\nfunc (c Client) Services(namespace string) v1core.ServiceInterface {\n\treturn c.ServiceInterface\n}\n\nfunc (c Client) DaemonSets(namespace string) v1beta1extensions.DaemonSetInterface {\n\treturn c.DaemonSetInterface\n}\n\nfunc (c Client) Endpoints(namespace string) v1core.EndpointsInterface {\n\treturn c.EndpointsInterface\n}\nfunc (c Client) Jobs(namespace string) v1batch.JobInterface {\n\treturn c.JobInterface\n}\n\n\n\nfunc NewClient() cli.ClientInterface ", "output": "{\n\treturn Client{\n\t\tNewPClient(),\n\t\tNewSClient(),\n\t\tNewDSClient(),\n\t\tNewEClient(),\n\t\tNewJClient(),\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/astaxie/beego\"\n\t\"github.com/astaxie/beego/context\"\n\t\"github.com/silenceper/wechat\"\n\t\"github.com/silenceper/wechat/message\"\n)\n\n\n\nfunc main() {\n\tbeego.Any(\"/\", hello)\n\tbeego.Run(\":8001\")\n}\n\nfunc hello(ctx *context.Context) ", "output": "{\n\tconfig := &wechat.Config{\n\t\tAppID: \"your app id\",\n\t\tAppSecret: \"your app secret\",\n\t\tToken: \"your token\",\n\t\tEncodingAESKey: \"your encoding aes key\",\n\t}\n\twc := wechat.NewWechat(config)\n\n\tserver := wc.GetServer(ctx.Request, ctx.ResponseWriter)\n\tserver.SetMessageHandler(func(msg message.MixMessage) *message.Reply {\n\n\t\ttext := message.NewText(msg.Content)\n\t\treturn &message.Reply{message.MsgTypeText, text}\n\t})\n\n\terr := server.Serve()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tserver.Send()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\nconst (\n\tFileType_File = 1\n\tFileType_Directory = 2\n)\n\nfunc IfString(condition bool, trueVal, falseVal string) string {\n\tif condition {\n\t\treturn trueVal\n\t}\n\treturn falseVal\n}\n\nfunc IfInt(condition bool, trueVal, falseVal int) int {\n\tif condition {\n\t\treturn trueVal\n\t}\n\treturn falseVal\n}\n\n\nfunc ExpandString(s string, data map[string]string) string {\n\treturn os.Expand(s, func(p string) string {\n\t\tv, _ := data[p]\n\t\treturn v\n\t})\n}\n\n\nfunc CreateDir(dir string, mode os.FileMode) error {\n\t_, err := os.Stat(dir)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn os.MkdirAll(dir, mode)\n\t\t}\n\t}\n\treturn err\n}\n\n\n\n\nfunc GetFileType(path string) (fileType int, err error) {\n\tvar fi os.FileInfo\n\n\tfi, err = os.Stat(path)\n\tif err == nil {\n\t\tfileType = IfInt(fi.IsDir(), FileType_Directory, FileType_File)\n\t} else if os.IsNotExist(err) {\n\t\terr = fmt.Errorf(\"can not find directory or file: %s\", path)\n\t}\n\treturn\n}\n\nfunc CopyFile(src, dest string, mode os.FileMode) error ", "output": "{\n\tdata, err := ioutil.ReadFile(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(dest, data, mode)\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/boltdb/bolt\"\n)\n\n\n\nfunc readValue(bdb *bolt.DB, k []byte) (N int) {\n\tbdb.View(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(\"predicate\"))\n\t\tif bucket == nil {\n\t\t\treturn errors.New(\"Bucket not found\")\n\t\t}\n\t\tval := bucket.Get(k)\n\t\tm := make([]byte, len(val))\n\t\tcopy(m, val)\n\t\tN = len(m)\n\t\treturn nil\n\t})\n\treturn\n}\n\nfunc main() {\n\tdb, err := bolt.Open(\"bolt.db\", 0600, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\tk := []byte(\"key\")\n\tN := 512\n\tif err := writeNBytes(db, k, N); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(readValue(db, k))\n}\n\nfunc writeNBytes(bdb *bolt.DB, k []byte, N int) error ", "output": "{\n\tbuf := make([]byte, N)\n\treturn bdb.Update(func(tx *bolt.Tx) error {\n\t\tbucket, err := tx.CreateBucketIfNotExists([]byte(\"predicate\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn bucket.Put(k, buf)\n\t})\n}"} {"input": "package types\n\nimport (\n\t\"crypto/sha512\"\n\t\"fmt\"\n)\n\n\ntype Packet struct {\n\tDest NodeAddress\n\tAmt int64\n\tData []byte\n}\n\n\n\n\nfunc (p Packet) Hash() PacketHash {\n\to := sha512.Sum512([]byte(string(p.Dest) + string(p.Data)))\n\treturn PacketHash(string(o[0:sha512.Size]))\n}\n\nfunc (p Packet) Amount() int64 {\n\treturn p.Amt\n}\n\nfunc (p Packet) String() string {\n\treturn fmt.Sprintf(\"{%x %v %q}\", p.Dest, p.Amt, p.Data)\n}\n\nfunc (p Packet) Destination() NodeAddress ", "output": "{\n\treturn p.Dest\n}"} {"input": "package watcher\n\nimport (\n\t\"syscall\"\n)\n\n\n\nfunc isHiddenFile(path string) (bool, error) ", "output": "{\n\tpointer, err := syscall.UTF16PtrFromString(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tattributes, err := syscall.GetFileAttributes(pointer)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn attributes&syscall.FILE_ATTRIBUTE_HIDDEN != 0, nil\n}"} {"input": "package core\n\nimport (\n\t\"database/sql\"\n\t\"strconv\"\n)\n\n\ntype Migration struct {\n\tIdentifier int64\n\tName string\n\tUp func(tx *Tx)\n\tDown func(tx *Tx)\n}\n\n\nfunc (m *Migration) GetID() string {\n\treturn strconv.FormatInt(m.Identifier, 10)\n}\n\n\n\nfunc (m *Migration) Pending(db *sql.DB) bool {\n\trows, _ := db.Query(\"Select * from \" + MigrationsTable + \" WHERE identifier =\" + m.GetID())\n\tdefer rows.Close()\n\tcount := 0\n\n\tfor rows.Next() {\n\t\tcount++\n\t}\n\n\treturn count == 0\n}\n\n\ntype ByIdentifier []Migration\n\n\nfunc (a ByIdentifier) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a ByIdentifier) Less(i, j int) bool { return a[i].Identifier < a[j].Identifier }\n\nfunc (a ByIdentifier) Len() int ", "output": "{ return len(a) }"} {"input": "package models\n\n\ntype IssueLockOptions struct {\n\tDoer *User\n\tIssue *Issue\n\tReason string\n}\n\n\n\nfunc LockIssue(opts *IssueLockOptions) error {\n\treturn updateIssueLock(opts, true)\n}\n\n\n\n\nfunc updateIssueLock(opts *IssueLockOptions, lock bool) error {\n\tif opts.Issue.IsLocked == lock {\n\t\treturn nil\n\t}\n\n\topts.Issue.IsLocked = lock\n\tvar commentType CommentType\n\tif opts.Issue.IsLocked {\n\t\tcommentType = CommentTypeLock\n\t} else {\n\t\tcommentType = CommentTypeUnlock\n\t}\n\n\tsess := x.NewSession()\n\tdefer sess.Close()\n\tif err := sess.Begin(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := updateIssueCols(sess, opts.Issue, \"is_locked\"); err != nil {\n\t\treturn err\n\t}\n\n\tvar opt = &CreateCommentOptions{\n\t\tDoer: opts.Doer,\n\t\tIssue: opts.Issue,\n\t\tRepo: opts.Issue.Repo,\n\t\tType: commentType,\n\t\tContent: opts.Reason,\n\t}\n\tif _, err := createComment(sess, opt); err != nil {\n\t\treturn err\n\t}\n\n\treturn sess.Commit()\n}\n\nfunc UnlockIssue(opts *IssueLockOptions) error ", "output": "{\n\treturn updateIssueLock(opts, false)\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetCrossConnectRequest struct {\n\n\tCrossConnectId *string `mandatory:\"true\" contributesTo:\"path\" name:\"crossConnectId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetCrossConnectRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request GetCrossConnectRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetCrossConnectRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetCrossConnectResponse struct {\n\n\tRawResponse *http.Response\n\n\tCrossConnect `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetCrossConnectResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetCrossConnectResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetCrossConnectRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package cluster_health\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\tmbtest \"github.com/elastic/beats/metricbeat/mb/testing\"\n)\n\nfunc TestData(t *testing.T) {\n\tf := mbtest.NewEventFetcher(t, getConfig())\n\terr := mbtest.WriteEvent(f, t)\n\tif err != nil {\n\t\tt.Fatal(\"write\", err)\n\t}\n}\n\nfunc getConfig() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"module\": \"ceph\",\n\t\t\"metricsets\": []string{\"cluster_health\"},\n\t\t\"hosts\": getTestCephHost(),\n\t}\n}\n\nconst (\n\tcephDefaultHost = \"127.0.0.1\"\n\tcephDefaultPort = \"5000\"\n)\n\nfunc getTestCephHost() string {\n\treturn fmt.Sprintf(\"%v:%v\",\n\t\tgetenv(\"CEPH_HOST\", cephDefaultHost),\n\t\tgetenv(\"CEPH_PORT\", cephDefaultPort),\n\t)\n}\n\n\n\nfunc strDefault(a, defaults string) string {\n\tif len(a) == 0 {\n\t\treturn defaults\n\t}\n\treturn a\n}\n\nfunc getenv(name, defaultValue string) string ", "output": "{\n\treturn strDefault(os.Getenv(name), defaultValue)\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype animal struct {\n\tfood string\n\tlocomotion string\n\tnoise string\n}\n\nfunc (a *animal) Eat() {\n\tfmt.Println(a.food)\n}\n\n\n\nfunc (a *animal) Speak() {\n\tfmt.Println(a.noise)\n}\n\nfunc main() {\n\treader := bufio.NewReader(os.Stdin)\n\n\tfor {\n\t\tfmt.Print(\"> \")\n\t\tinput, _ := reader.ReadString('\\n')\n\t\ts := strings.Split(strings.TrimSpace(input), \" \")\n\n\t\ta := new(animal)\n\t\tswitch s[0] {\n\t\tcase \"cow\":\n\t\t\ta.food = \"grass\"\n\t\t\ta.locomotion = \"walk\"\n\t\t\ta.noise = \"moo\"\n\t\tcase \"bird\":\n\t\t\ta.food = \"worms\"\n\t\t\ta.locomotion = \"fly\"\n\t\t\ta.noise = \"poop\"\n\t\tcase \"snake\":\n\t\t\ta.food = \"mice\"\n\t\t\ta.locomotion = \"slither\"\n\t\t\ta.noise = \"hsss\"\n\t\t}\n\n\t\tswitch s[1] {\n\t\tcase \"eat\":\n\t\t\ta.Eat()\n\t\tcase \"speak\":\n\t\t\ta.Speak()\n\t\tcase \"move\":\n\t\t\ta.Move()\n\t\t}\n\t}\n}\n\nfunc (a *animal) Move() ", "output": "{\n\tfmt.Println(a.locomotion)\n}"} {"input": "package topology\n\nimport (\n\t\"github.com/skydive-project/skydive/graffiti/getter\"\n\t\"strings\"\n)\n\nfunc (obj *NextHop) GetFieldBool(key string) (bool, error) {\n\treturn false, getter.ErrFieldNotFound\n}\n\n\n\nfunc (obj *NextHop) GetFieldString(key string) (string, error) {\n\tswitch key {\n\tcase \"IP\":\n\t\treturn obj.IP.String(), nil\n\tcase \"MAC\":\n\t\treturn string(obj.MAC), nil\n\t}\n\treturn \"\", getter.ErrFieldNotFound\n}\n\nfunc (obj *NextHop) GetFieldKeys() []string {\n\treturn []string{\n\t\t\"Priority\",\n\t\t\"IP\",\n\t\t\"MAC\",\n\t\t\"IfIndex\",\n\t}\n}\n\nfunc (obj *NextHop) MatchBool(key string, predicate getter.BoolPredicate) bool {\n\treturn false\n}\n\nfunc (obj *NextHop) MatchInt64(key string, predicate getter.Int64Predicate) bool {\n\tif b, err := obj.GetFieldInt64(key); err == nil {\n\t\treturn predicate(b)\n\t}\n\treturn false\n}\n\nfunc (obj *NextHop) MatchString(key string, predicate getter.StringPredicate) bool {\n\tif b, err := obj.GetFieldString(key); err == nil {\n\t\treturn predicate(b)\n\t}\n\treturn false\n}\n\nfunc (obj *NextHop) GetField(key string) (interface{}, error) {\n\tif s, err := obj.GetFieldString(key); err == nil {\n\t\treturn s, nil\n\t}\n\n\tif i, err := obj.GetFieldInt64(key); err == nil {\n\t\treturn i, nil\n\t}\n\treturn nil, getter.ErrFieldNotFound\n}\n\nfunc init() {\n\tstrings.Index(\"\", \".\")\n}\n\nfunc (obj *NextHop) GetFieldInt64(key string) (int64, error) ", "output": "{\n\tswitch key {\n\tcase \"Priority\":\n\t\treturn int64(obj.Priority), nil\n\tcase \"IfIndex\":\n\t\treturn int64(obj.IfIndex), nil\n\t}\n\treturn 0, getter.ErrFieldNotFound\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/mdlayher/p4/cli\"\n)\n\n\nconst (\n\tcmdPP = \"pp\"\n)\n\nfunc main() {\n\tflag.Parse()\n\tlog.SetFlags(0)\n\tlog.SetOutput(os.Stderr)\n\n\tif len(flag.Args()) == 0 {\n\t\tfatalf(\"no arguments specified\")\n\t}\n\n\tvar exec cli.Executor\n\n\tcmd := flag.Arg(0)\n\tswitch cmd {\n\tcase cmdPP:\n\t\texec = cli.NewPreprocessor()\n\tdefault:\n\t\tfatalf(\"unknown command: %q\", cmd)\n\t}\n\n\tw, r := os.Stdout, os.Stdin\n\n\tif err := exec.Execute(w, r); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\n\n\n\n\nfunc fatalf(format string, a ...interface{}) {\n\tusage()\n\tlog.Fatalf(\"p4: \"+format, a...)\n}\n\nfunc usage() ", "output": "{\n\tlf := log.Printf\n\n\tlf(\"p4 is a tool for managing P4 source code.\")\n\tlf(\"\")\n\tlf(\"Usage:\")\n\tlf(\" p4 command [arguments]\")\n\tlf(\"\")\n\tlf(\"Commands:\")\n\tlf(\" p4 %s invoke a preprocessor on P4 source code read from stdin\", cmdPP)\n\tlf(\"\")\n}"} {"input": "package iso20022\n\n\ntype BasicCollateralValuation1Details struct {\n\n\tValuationHaircut *PercentageRate `xml:\"ValtnHrcut\"`\n\n\tHaircutSource *PartyIdentification15 `xml:\"HrcutSrc,omitempty\"`\n}\n\n\n\nfunc (b *BasicCollateralValuation1Details) AddHaircutSource() *PartyIdentification15 {\n\tb.HaircutSource = new(PartyIdentification15)\n\treturn b.HaircutSource\n}\n\nfunc (b *BasicCollateralValuation1Details) SetValuationHaircut(value string) ", "output": "{\n\tb.ValuationHaircut = (*PercentageRate)(&value)\n}"} {"input": "package util\n\nimport (\n\t\"os\"\n)\n\n\n\nfunc GetFileSize(filename string) (uint64, error) ", "output": "{\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tsize, err := file.Seek(0, os.SEEK_END)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn uint64(size), nil\n}"} {"input": "package iso20022\n\n\ntype PlainCardData4 struct {\n\n\tPAN *Min8Max28NumericText `xml:\"PAN\"`\n\n\tCardSequenceNumber *Min2Max3NumericText `xml:\"CardSeqNb,omitempty\"`\n\n\tEffectiveDate *Max10Text `xml:\"FctvDt,omitempty\"`\n\n\tExpiryDate *Max10Text `xml:\"XpryDt\"`\n\n\tServiceCode *Exact3NumericText `xml:\"SvcCd,omitempty\"`\n\n\tTrackData []*TrackData1 `xml:\"TrckData,omitempty\"`\n\n\tCardSecurityCode *CardSecurityInformation1 `xml:\"CardSctyCd,omitempty\"`\n}\n\nfunc (p *PlainCardData4) SetPAN(value string) {\n\tp.PAN = (*Min8Max28NumericText)(&value)\n}\n\nfunc (p *PlainCardData4) SetCardSequenceNumber(value string) {\n\tp.CardSequenceNumber = (*Min2Max3NumericText)(&value)\n}\n\n\n\nfunc (p *PlainCardData4) SetExpiryDate(value string) {\n\tp.ExpiryDate = (*Max10Text)(&value)\n}\n\nfunc (p *PlainCardData4) SetServiceCode(value string) {\n\tp.ServiceCode = (*Exact3NumericText)(&value)\n}\n\nfunc (p *PlainCardData4) AddTrackData() *TrackData1 {\n\tnewValue := new(TrackData1)\n\tp.TrackData = append(p.TrackData, newValue)\n\treturn newValue\n}\n\nfunc (p *PlainCardData4) AddCardSecurityCode() *CardSecurityInformation1 {\n\tp.CardSecurityCode = new(CardSecurityInformation1)\n\treturn p.CardSecurityCode\n}\n\nfunc (p *PlainCardData4) SetEffectiveDate(value string) ", "output": "{\n\tp.EffectiveDate = (*Max10Text)(&value)\n}"} {"input": "package admission\n\nimport (\n\t\"io\"\n\n\t\"k8s.io/kubernetes/pkg/admission\"\n\tclient \"k8s.io/kubernetes/pkg/client/unversioned\"\n)\n\nfunc init() {\n\tadmission.RegisterPlugin(\"SCCExecRestrictions\", func(client client.Interface, config io.Reader) (admission.Interface, error) {\n\t\treturn NewSCCExecRestrictions(client), nil\n\t})\n}\n\n\n\ntype sccExecRestrictions struct {\n\t*admission.Handler\n\tconstraintAdmission *constraint\n\tclient client.Interface\n}\n\n\n\n\nfunc NewSCCExecRestrictions(client client.Interface) admission.Interface {\n\treturn &sccExecRestrictions{\n\t\tHandler: admission.NewHandler(admission.Connect),\n\t\tconstraintAdmission: NewConstraint(client).(*constraint),\n\t\tclient: client,\n\t}\n}\n\nfunc (d *sccExecRestrictions) Admit(a admission.Attributes) (err error) ", "output": "{\n\tif a.GetOperation() != admission.Connect {\n\t\treturn nil\n\t}\n\tif a.GetResource() != \"pods\" {\n\t\treturn nil\n\t}\n\tif a.GetSubresource() != \"attach\" && a.GetSubresource() != \"exec\" {\n\t\treturn nil\n\t}\n\n\tpod, err := d.client.Pods(a.GetNamespace()).Get(a.GetName())\n\tif err != nil {\n\t\treturn admission.NewForbidden(a, err)\n\t}\n\n\tpod.Spec.ServiceAccountName = \"\"\n\tcreateAttributes := admission.NewAttributesRecord(pod, \"pods\", a.GetNamespace(), a.GetName(), a.GetResource(), a.GetSubresource(), admission.Create, a.GetUserInfo())\n\tif err := d.constraintAdmission.Admit(createAttributes); err != nil {\n\t\treturn admission.NewForbidden(a, err)\n\t}\n\n\treturn nil\n}"} {"input": "package sml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/sml\"\n)\n\n\n\nfunc TestCT_WorkbookProtectionMarshalUnmarshal(t *testing.T) {\n\tv := sml.NewCT_WorkbookProtection()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := sml.NewCT_WorkbookProtection()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestCT_WorkbookProtectionConstructor(t *testing.T) ", "output": "{\n\tv := sml.NewCT_WorkbookProtection()\n\tif v == nil {\n\t\tt.Errorf(\"sml.NewCT_WorkbookProtection must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed sml.CT_WorkbookProtection should validate: %s\", err)\n\t}\n}"} {"input": "package format\n\nimport (\n\t\"reflect\"\n\t\"strconv\"\n)\n\n\n\n\n\nfunc formatAtom(v reflect.Value) string {\n\tswitch v.Kind() {\n\tcase reflect.Invalid:\n\t\treturn \"invalid\"\n\tcase reflect.Int, reflect.Int8, reflect.Int16,\n\t\treflect.Int32, reflect.Int64:\n\t\treturn strconv.FormatInt(v.Int(), 10)\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16,\n\t\treflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\treturn strconv.FormatUint(v.Uint(), 10)\n\tcase reflect.Bool:\n\t\treturn strconv.FormatBool(v.Bool())\n\tcase reflect.String:\n\t\treturn strconv.Quote(v.String())\n\tcase reflect.Chan, reflect.Func, reflect.Ptr, reflect.Slice, reflect.Map:\n\t\treturn v.Type().String() + \" 0x\" +\n\t\t\tstrconv.FormatUint(uint64(v.Pointer()), 16)\n\tdefault: \n\t\treturn v.Type().String() + \" value\"\n\t}\n}\n\nfunc Any(value interface{}) string ", "output": "{\n\treturn formatAtom(reflect.ValueOf(value))\n}"} {"input": "package midi\n\nimport \"fmt\"\n\ntype Track struct {\n\tevents []Event\n}\n\n\n\nfunc (t *Track) String() string {\n\treturn fmt.Sprintf(\n\t\t\"Track [Events=%v]\",\n\t\tt.Events())\n}\n\nfunc NewTrack(e []Event) *Track {\n\treturn &Track{e}\n}\n\nfunc (t *Track) Events() []Event ", "output": "{\n\treturn t.events\n}"} {"input": "package communicator\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/hashicorp/packer/helper/multistep\"\n)\n\n\n\n\nfunc CommHost(host string, statebagKey string) func(multistep.StateBag) (string, error) ", "output": "{\n\treturn func(state multistep.StateBag) (string, error) {\n\t\tif host != \"\" {\n\t\t\tlog.Printf(\"Using ssh_host value: %s\", host)\n\t\t\treturn host, nil\n\t\t}\n\t\tipAddress, hasIP := state.Get(statebagKey).(string)\n\t\tif !hasIP {\n\t\t\treturn \"\", fmt.Errorf(\"Failed to retrieve IP address.\")\n\t\t}\n\t\treturn ipAddress, nil\n\t}\n}"} {"input": "package goarken\n\ntype Broadcaster struct {\n\tlisteners []chan interface{}\n}\n\nfunc NewBroadcaster() *Broadcaster {\n\tb := &Broadcaster{\n\t\tlisteners: []chan interface{}{},\n\t}\n\treturn b\n}\n\nfunc (b *Broadcaster) Write(message interface{}) {\n\tfor _, channel := range b.listeners {\n\t\tchannel <- message\n\t}\n}\n\n\n\nfunc (b *Broadcaster) Listen() chan interface{} ", "output": "{\n\tchannel := make(chan interface{})\n\tb.listeners = append(b.listeners, channel)\n\treturn channel\n\n}"} {"input": "package transpose\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestTranspose(t *testing.T) {\n\tfor _, test := range testCases {\n\t\tactual := Transpose(test.input)\n\t\tif !reflect.DeepEqual(actual, test.expected) {\n\t\t\tif len(actual) == 0 || len(test.expected) == 0 {\n\t\t\t\tt.Fatalf(\"\\n\\tTranspose(%q): %s\\n\\n\\tExpected: %q\\n\\tGot: %q\",\n\t\t\t\t\ttest.input, test.description, test.expected, actual)\n\t\t\t}\n\t\t\tmin := min(len(test.expected), len(actual))\n\t\t\tfor i := 0; i < min; i++ {\n\t\t\t\tif test.expected[i] != actual[i] {\n\t\t\t\t\tt.Fatalf(\"\\n\\tTranspose(%q): %s\\n\\n\\tExpected: %q\\n\\tGot: %q\\n\\n\\tRow %d Expected: %q Got: %q\",\n\t\t\t\t\t\ttest.input, test.description, test.expected, actual, i, test.expected[i], actual[i])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n\n\nfunc BenchmarkTranspose(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, test := range testCases {\n\t\t\tTranspose(test.input)\n\t\t}\n\t}\n}\n\nfunc min(a, b int) int ", "output": "{\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}"} {"input": "package goldengate\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ChangeDeploymentCompartmentRequest struct {\n\n\tDeploymentId *string `mandatory:\"true\" contributesTo:\"path\" name:\"deploymentId\"`\n\n\tChangeDeploymentCompartmentDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ChangeDeploymentCompartmentRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request ChangeDeploymentCompartmentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ChangeDeploymentCompartmentRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ChangeDeploymentCompartmentResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ChangeDeploymentCompartmentResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ChangeDeploymentCompartmentResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ChangeDeploymentCompartmentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package servicecontrol\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\nvar (\n\tsshServiceName = \"ssh\"\n\tdisableSshFilename = \"/etc/ssh/sshd_not_to_be_run\"\n)\n\ntype SshService struct {\n\tdefaults *ServiceControlSettings\n}\n\nfunc getSshSettings() *ServiceControlSettings {\n\tis_enabled := true\n\tinfo, _ := os.Stat(disableSshFilename)\n\tif info != nil {\n\t\tis_enabled = false\n\t}\n\n\treturn &ServiceControlSettings{\n\t\tEnabled: is_enabled,\n\t}\n}\n\nfunc NewSshService() *SshService {\n\treturn &SshService{\n\t\tdefaults: getSshSettings(),\n\t}\n}\n\n\n\nfunc (s *SshService) GetDefaults() *ServiceControlSettings {\n\treturn s.defaults\n}\n\nfunc (s *SshService) ApplySettings(settings *ServiceControlSettings) error {\n\tvar action string\n\trunning, statusErr := isServiceRunning(sshServiceName)\n\tif settings.Enabled {\n\t\tif running && statusErr == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\taction = \"start\"\n\t\tif err := removeFile(disableSshFilename); err != nil {\n\t\t\tlog.Println(\"Could not enable ssh service\", err)\n\t\t}\n\t} else {\n\t\tif !running && statusErr == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\taction = \"stop\"\n\t\tif err := touchFile(disableSshFilename); err != nil {\n\t\t\tlog.Println(\"Could not disable ssh service\", err)\n\t\t}\n\t}\n\n\treturn runServiceCommand(sshServiceName, action)\n}\n\nfunc (s *SshService) QuerySettings() (*ServiceControlSettings, error) {\n\treturn getSshSettings(), nil\n}\n\nfunc init() {\n\tRegisterService(\"ssh\", NewSshService())\n}\n\nfunc (s *SshService) IsAvailable() bool ", "output": "{\n\treturn true\n}"} {"input": "package all\n\nimport (\n\t\"github.com/juju/collections/set\"\n\t\"github.com/juju/errors\"\n)\n\ntype component interface {\n\tregisterForServer() error\n\tregisterForClient() error\n}\n\nvar components = []component{\n\t&payloads{},\n\t&resources{},\n}\n\n\n\n\n\n\n\nfunc RegisterForClient() error {\n\tfor _, c := range components {\n\t\tif err := c.registerForClient(); err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t}\n\treturn nil\n}\n\n\nvar registered = map[string]set.Strings{}\n\n\n\n\n\nfunc markRegistered(component, part string) bool {\n\tparts, ok := registered[component]\n\tif !ok {\n\t\tparts = set.NewStrings()\n\t\tregistered[component] = parts\n\t}\n\tif parts.Contains(part) {\n\t\treturn false\n\t}\n\tparts.Add(part)\n\treturn true\n}\n\nfunc RegisterForServer() error ", "output": "{\n\tfor _, c := range components {\n\t\tif err := c.registerForServer(); err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package lzma\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"unicode\"\n)\n\n\n\ntype operation interface {\n\tLen() int\n}\n\n\ntype match struct {\n\tdistance int64\n\tn int\n}\n\n\n\nfunc (m match) verify() error {\n\tif !(minDistance <= m.distance && m.distance <= maxDistance) {\n\t\treturn errors.New(\"distance out of range\")\n\t}\n\tif !(1 <= m.n && m.n <= maxMatchLen) {\n\t\treturn errors.New(\"length out of range\")\n\t}\n\treturn nil\n}\n\n\n\nfunc (m match) l() uint32 {\n\treturn uint32(m.n - minMatchLen)\n}\n\n\n\n\n\n\nfunc (m match) Len() int {\n\treturn m.n\n}\n\n\nfunc (m match) String() string {\n\treturn fmt.Sprintf(\"M{%d,%d}\", m.distance, m.n)\n}\n\n\ntype lit struct {\n\tb byte\n}\n\n\nfunc (l lit) Len() int {\n\treturn 1\n}\n\n\nfunc (l lit) String() string {\n\tvar c byte\n\tif unicode.IsPrint(rune(l.b)) {\n\t\tc = l.b\n\t} else {\n\t\tc = '.'\n\t}\n\treturn fmt.Sprintf(\"L{%c/%02x}\", c, l.b)\n}\n\nfunc (m match) dist() uint32 ", "output": "{\n\treturn uint32(m.distance - minDistance)\n}"} {"input": "package dbr\n\ntype union struct {\n\tbuilder []Builder\n\tall bool\n}\n\n\nfunc Union(builder ...Builder) interface {\n\tBuilder\n\tAs(string) Builder\n} {\n\treturn &union{\n\t\tbuilder: builder,\n\t}\n}\n\n\nfunc UnionAll(builder ...Builder) interface {\n\tBuilder\n\tAs(string) Builder\n} {\n\treturn &union{\n\t\tbuilder: builder,\n\t\tall: true,\n\t}\n}\n\nfunc (u *union) Build(d Dialect, buf Buffer) error {\n\tfor i, b := range u.builder {\n\t\tif i > 0 {\n\t\t\tbuf.WriteString(\" UNION \")\n\t\t\tif u.all {\n\t\t\t\tbuf.WriteString(\"ALL \")\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(placeholder)\n\t\tbuf.WriteValue(b)\n\t}\n\treturn nil\n}\n\n\n\nfunc (u *union) As(alias string) Builder ", "output": "{\n\treturn as(u, alias)\n}"} {"input": "package x509\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n)\n\n\nvar certFiles = []string{\n\t\"/sys/lib/tls/ca.pem\",\n}\n\n\n\nfunc loadSystemRoots() (*CertPool, error) {\n\troots := NewCertPool()\n\tvar bestErr error\n\tfor _, file := range certFiles {\n\t\tdata, err := ioutil.ReadFile(file)\n\t\tif err == nil {\n\t\t\troots.AppendCertsFromPEM(data)\n\t\t\treturn roots, nil\n\t\t}\n\t\tif bestErr == nil || (os.IsNotExist(bestErr) && !os.IsNotExist(err)) {\n\t\t\tbestErr = err\n\t\t}\n\t}\n\tif bestErr == nil {\n\t\treturn roots, nil\n\t}\n\treturn nil, bestErr\n}\n\nfunc (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package grequests\n\nimport \"testing\"\n\n\n\nfunc TestErrorOpenFile(t *testing.T) ", "output": "{\n\tfd, err := FileUploadFromDisk(\"file\", \"I am Not A File\")\n\tif err == nil {\n\t\tt.Error(\"We are not getting an error back from our non existent file: \")\n\t}\n\n\tif fd != nil {\n\t\tt.Error(\"We actually got back a pointer: \", fd)\n\t}\n}"} {"input": "package events\n\nimport (\n\t\"github.com/mesos/mesos-go/executor\"\n)\n\ntype (\n\tDecorator func(Handler) Handler\n\n\tDecorators []Decorator\n)\n\nvar noopDecorator = Decorator(func(h Handler) Handler { return h })\n\n\n\n\n\n\n\nfunc (d Decorator) When(f func() bool) Decorator {\n\tif d == nil || f == nil {\n\t\treturn noopDecorator\n\t}\n\treturn func(h Handler) Handler {\n\t\tdecorated := d(h)\n\t\treturn HandlerFunc(func(e *executor.Event) (err error) {\n\t\t\tif f() {\n\t\t\t\terr = decorated.HandleEvent(e)\n\t\t\t} else {\n\t\t\t\terr = h.HandleEvent(e)\n\t\t\t}\n\t\t\treturn\n\t\t})\n\t}\n}\n\n\n\nfunc (ds Decorators) Apply(h Handler) Handler {\n\tfor _, d := range ds {\n\t\th = d.Apply(h)\n\t}\n\treturn h\n}\n\nfunc (d Decorator) Apply(h Handler) Handler {\n\tif d != nil {\n\t\th = d(h)\n\t}\n\treturn h\n}\n\nfunc (d Decorator) If(b bool) Decorator ", "output": "{\n\tif d == nil {\n\t\treturn noopDecorator\n\t}\n\tresult := noopDecorator\n\tif b {\n\t\tresult = d\n\t}\n\treturn result\n}"} {"input": "package client\n\nimport (\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\n\n\nfunc (c *Client) GetLRPs() ([]*models.LRPSpec, error) ", "output": "{\n\tresp, err := c.Service.GetLrp(nil)\n\tif err != nil {\n\t\treturn nil, Hint(err)\n\t}\n\treturn resp.Payload, nil\n}"} {"input": "package client\n\nimport \"net\"\n\ntype Request struct {\n\tConn net.Conn\n\tPassword string\n\tNetworkName string\n}\n\ntype Server struct {\n\tAddr string\n\n\tlistener net.Listener\n}\n\nfunc (s *Server) Listen() (chan *Request, error) {\n\tlistener, err := net.Listen(\"tcp\", s.Addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout := make(chan *Request)\n\ts.listener = listener\n\treturn out, nil\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (s *Server) Close() error ", "output": "{\n\tif s.listener == nil {\n\t\treturn nil\n\t}\n\n\treturn s.listener.Close()\n}"} {"input": "package objectstorage\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype ListMultipartUploadsRequest struct {\n\n\tNamespaceName *string `mandatory:\"true\" contributesTo:\"path\" name:\"namespaceName\"`\n\n\tBucketName *string `mandatory:\"true\" contributesTo:\"path\" name:\"bucketName\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tOpcClientRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-client-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListMultipartUploadsRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListMultipartUploadsRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\n\n\n\ntype ListMultipartUploadsResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []MultipartUpload `presentIn:\"body\"`\n\n\tOpcClientRequestId *string `presentIn:\"header\" name:\"opc-client-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n}\n\nfunc (response ListMultipartUploadsResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListMultipartUploadsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListMultipartUploadsRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n)\n\n\n\n\n\n\n\nfunc in_b_test_asset() []byte {\n\treturn bindata_read(\n\t\t\"/a/code/go/src/github.com/jteeuwen/go-bindata/testdata/in/b/test.asset\",\n\t\t\"in/b/test.asset\",\n\t)\n}\n\n\n\nfunc in_test_asset() []byte {\n\treturn bindata_read(\n\t\t\"/a/code/go/src/github.com/jteeuwen/go-bindata/testdata/in/test.asset\",\n\t\t\"in/test.asset\",\n\t)\n}\n\n\n\nfunc in_a_test_asset() []byte {\n\treturn bindata_read(\n\t\t\"/a/code/go/src/github.com/jteeuwen/go-bindata/testdata/in/a/test.asset\",\n\t\t\"in/a/test.asset\",\n\t)\n}\n\n\n\nfunc in_c_test_asset() []byte {\n\treturn bindata_read(\n\t\t\"/a/code/go/src/github.com/jteeuwen/go-bindata/testdata/in/c/test.asset\",\n\t\t\"in/c/test.asset\",\n\t)\n}\n\n\n\nfunc Asset(name string) []byte {\n\tif f, ok := _bindata[name]; ok {\n\t\treturn f()\n\t}\n\treturn nil\n}\n\n\nvar _bindata = map[string]func() []byte{\n\t\"in/b/test.asset\": in_b_test_asset,\n\t\"in/test.asset\": in_test_asset,\n\t\"in/a/test.asset\": in_a_test_asset,\n\t\"in/c/test.asset\": in_c_test_asset,\n}\n\nfunc bindata_read(path, name string) []byte ", "output": "{\n\tfd, err := os.Open(path)\n\tif err != nil {\n\t\tlog.Fatalf(\"Read %s: %v\", name, err)\n\t}\n\n\tdefer fd.Close()\n\n\tvar buf bytes.Buffer\n\t_, err = io.Copy(&buf, fd)\n\tif err != nil {\n\t\tlog.Fatalf(\"Read %s: %v\", name, err)\n\t}\n\n\treturn buf.Bytes()\n}"} {"input": "package datatypes\n\ntype Time int64\n\ntype StreamName string\n\ntype Event struct {\n Time Time;\n Payload EvPayload\n}\n\ntype EvPayload struct {\n IsSet bool;\n Val interface{}\n}\n\ntype MaybeTime struct {\n IsSet bool;\n Val Time\n}\n\nfunc SomeTime(val Time) MaybeTime {\n return MaybeTime{true, val}\n}\n\nvar NothingTime MaybeTime = MaybeTime{false, -100}\n\n\n\nvar NothingPayload EvPayload = EvPayload{false, nil}\n\ntype EpsVal struct {\n Eps Time\n Val interface{}\n}\n\ntype OutStream struct {\n Name StreamName\n TicksDef TickerNode\n ValDef ValNode\n}\n\ntype InStream struct {\n Name StreamName\n StreamDef InStreamDef\n}\n\ntype InStreamDef interface {\n PeekNextTime() MaybeTime\n Exec(t Time) EvPayload\n}\n\ntype FlowingEvent struct {\n Name StreamName\n Event Event\n}\n\nfunc Some(val interface{}) EvPayload ", "output": "{\n return EvPayload{true, val}\n}"} {"input": "package system\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nconst (\n\texecErrorMsgFmt = \"Running command: '%s', stdout: '%s', stderr: '%s'\"\n\texecShortErrorMaxLines = 100\n)\n\ntype ExecError struct {\n\tCommand string\n\tStdOut string\n\tStdErr string\n}\n\nfunc NewExecError(cmd, stdout, stderr string) ExecError {\n\treturn ExecError{\n\t\tCommand: cmd,\n\t\tStdOut: stdout,\n\t\tStdErr: stderr,\n\t}\n}\n\n\n\n\nfunc (e ExecError) ShortError() string {\n\toutStr := e.truncateStr(e.StdOut, execShortErrorMaxLines)\n\terrStr := e.truncateStr(e.StdErr, execShortErrorMaxLines)\n\treturn fmt.Sprintf(execErrorMsgFmt, e.Command, outStr, errStr)\n}\n\nfunc (e ExecError) truncateStr(in string, maxLines int) string {\n\toutLines := strings.Split(in, \"\\n\")\n\tif i := len(outLines); i > maxLines {\n\t\toutLines = outLines[i-maxLines:]\n\t}\n\n\treturn strings.Join(outLines, \"\\n\")\n}\n\nfunc (e ExecError) Error() string ", "output": "{\n\treturn fmt.Sprintf(execErrorMsgFmt, e.Command, e.StdOut, e.StdErr)\n}"} {"input": "package zktopo\n\nimport (\n\t\"sort\"\n\n\t\"github.com/youtube/vitess/go/zk\"\n)\n\n\n\n\n\nfunc (zkts *Server) GetKnownCells() ([]string, error) ", "output": "{\n\tcellsWithGlobal := zk.ZkKnownCells(false)\n\tcells := make([]string, 0, len(cellsWithGlobal))\n\tfor _, cell := range cellsWithGlobal {\n\t\tif cell != \"global\" {\n\t\t\tcells = append(cells, cell)\n\t\t}\n\t}\n\tsort.Strings(cells)\n\treturn cells, nil\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSIoTAnalyticsPipeline_DeviceShadowEnrich struct {\n\n\tAttribute string `json:\"Attribute,omitempty\"`\n\n\tName string `json:\"Name,omitempty\"`\n\n\tNext string `json:\"Next,omitempty\"`\n\n\tRoleArn string `json:\"RoleArn,omitempty\"`\n\n\tThingName string `json:\"ThingName,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\n\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::IoTAnalytics::Pipeline.DeviceShadowEnrich\"\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\n\t\"go-common/app/interface/main/favorite/conf\"\n\t\"go-common/app/interface/main/favorite/http\"\n\t\"go-common/app/interface/main/favorite/service\"\n\tecode \"go-common/library/ecode/tip\"\n\t\"go-common/library/log\"\n\t\"go-common/library/net/trace\"\n)\n\nvar svc *service.Service\n\nfunc main() {\n\tflag.Parse()\n\tif err := conf.Init(); err != nil {\n\t\tlog.Error(\"conf.Init() error(%v)\", err)\n\t\tpanic(err)\n\t}\n\tlog.Init(conf.Conf.Log)\n\ttrace.Init(conf.Conf.Tracer)\n\tdefer trace.Close()\n\tdefer log.Close()\n\tlog.Info(\"favorite start\")\n\tecode.Init(conf.Conf.Ecode)\n\tsvc = service.New(conf.Conf)\n\thttp.Init(conf.Conf, svc)\n\tsignalHandler()\n}\n\n\n\nfunc signalHandler() ", "output": "{\n\tvar (\n\t\terr error\n\t\tch = make(chan os.Signal, 1)\n\t)\n\tsignal.Notify(ch, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)\n\tfor {\n\t\tsi := <-ch\n\t\tswitch si {\n\t\tcase syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:\n\t\t\tlog.Info(\"get a signal %s, stop the consume process\", si.String())\n\t\t\tsvc.Close()\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"svc.Close() error(%v)\", err)\n\t\t\t}\n\t\t\treturn\n\t\tcase syscall.SIGHUP:\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}"} {"input": "package mock\n\nimport (\n\t\"github.com/eventials/goevents/messaging\"\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype Connection struct {\n\tmock.Mock\n}\n\nfunc NewMockConnection() messaging.Connection {\n\treturn &Connection{}\n}\n\nfunc (c *Connection) Consumer(autoAck bool, exchange, queue string) (messaging.Consumer, error) {\n\targs := c.Called(autoAck, exchange, queue)\n\treturn args.Get(0).(messaging.Consumer), args.Error(1)\n}\n\nfunc (c *Connection) Producer(exchange string) (messaging.Producer, error) {\n\targs := c.Called(exchange)\n\treturn args.Get(0).(messaging.Producer), args.Error(1)\n}\n\n\n\nfunc (c *Connection) NotifyConnectionClose() <-chan error {\n\targs := c.Called()\n\treturn args.Get(0).(chan error)\n}\n\nfunc (c *Connection) NotifyReestablish() <-chan bool {\n\targs := c.Called()\n\treturn args.Get(0).(chan bool)\n}\n\nfunc (c *Connection) WaitUntilConnectionCloses() {\n\tc.Called()\n}\n\nfunc (c *Connection) WaitUntilConnectionReestablished() {\n\tc.Called()\n}\n\nfunc (c *Connection) IsConnected() bool {\n\targs := c.Called()\n\treturn args.Get(0).(bool)\n}\n\nfunc (c *Connection) Close() ", "output": "{\n\tc.Called()\n}"} {"input": "package apis\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/go-ozzo/ozzo-routing\"\n\t\"github.com/go-ozzo/ozzo-routing/content\"\n\t\"github.com/Zhanat87/go/app\"\n\t\"github.com/Zhanat87/go/testdata\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype apiTestCase struct {\n\ttag string\n\tmethod string\n\turl string\n\tbody string\n\tstatus int\n\tresponse string\n}\n\nvar router *routing.Router\n\n\n\nfunc testAPI(method, URL, body string) *httptest.ResponseRecorder {\n\treq, _ := http.NewRequest(method, URL, bytes.NewBufferString(body))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tres := httptest.NewRecorder()\n\trouter.ServeHTTP(res, req)\n\treturn res\n}\n\nfunc runAPITests(t *testing.T, tests []apiTestCase) {\n\tfor _, test := range tests {\n\t\tres := testAPI(test.method, test.url, test.body)\n\t\tassert.Equal(t, test.status, res.Code, test.tag + \", \" + res.Body.String())\n\t\tif test.response != \"\" {\n\t\t\tassert.JSONEq(t, test.response, res.Body.String(), test.tag)\n\t\t}\n\t}\n}\n\nfunc init() ", "output": "{\n\tlogger := logrus.New()\n\tlogger.Level = logrus.PanicLevel\n\n\trouter = routing.New()\n\n\trouter.Use(\n\t\tapp.Init(logger),\n\t\tcontent.TypeNegotiator(content.JSON),\n\t\tapp.Transactional(testdata.DB),\n\t)\n}"} {"input": "package storage\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\tgenericregistry \"k8s.io/apiserver/pkg/registry/generic/registry\"\n\t\"k8s.io/apiserver/pkg/registry/rest\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/registry/cachesize\"\n\t\"k8s.io/kubernetes/pkg/registry/core/configmap\"\n)\n\n\ntype REST struct {\n\t*genericregistry.Store\n}\n\n\nfunc NewREST(optsGetter generic.RESTOptionsGetter) *REST {\n\tstore := &genericregistry.Store{\n\t\tCopier: api.Scheme,\n\t\tNewFunc: func() runtime.Object { return &api.ConfigMap{} },\n\t\tNewListFunc: func() runtime.Object { return &api.ConfigMapList{} },\n\t\tPredicateFunc: configmap.MatchConfigMap,\n\t\tQualifiedResource: api.Resource(\"configmaps\"),\n\t\tWatchCacheSize: cachesize.GetWatchCacheSizeByResource(\"configmaps\"),\n\n\t\tCreateStrategy: configmap.Strategy,\n\t\tUpdateStrategy: configmap.Strategy,\n\t\tDeleteStrategy: configmap.Strategy,\n\t}\n\toptions := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: configmap.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\tpanic(err) \n\t}\n\treturn &REST{store}\n}\n\n\nvar _ rest.ShortNamesProvider = &REST{}\n\n\n\n\nfunc (r *REST) ShortNames() []string ", "output": "{\n\treturn []string{\"cm\"}\n}"} {"input": "package enumflag\n\nimport \"fmt\"\n\ntype enumFlag struct {\n\ttarget *string\n\toptions []string\n}\n\n\nfunc New(target *string, options ...string) *enumFlag {\n\treturn &enumFlag{target: target, options: options}\n}\n\nfunc (f *enumFlag) String() string {\n\treturn *f.target\n}\n\n\n\nfunc (f *enumFlag) Set(value string) error ", "output": "{\n\tfor _, v := range f.options {\n\t\tif v == value {\n\t\t\t*f.target = value\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"expected one of %q\", f.options)\n}"} {"input": "package metric\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\ntype (\n\tCollectFnOpts struct {\n\t\tMethod string\n\t\tStart time.Time\n\t\tErr error\n\t\tAdditionalProps map[string]interface{}\n\t}\n\n\tCounterFn func(vec *prometheus.CounterVec, o CollectFnOpts)\n\n\tHistogramFn func(vec *prometheus.HistogramVec, o CollectFnOpts)\n\n\tVecOpts struct {\n\t\tName string\n\t\tHelp string\n\t\tLabelNames []string\n\n\t\tCounterFn CounterFn\n\t\tHistogramFn HistogramFn\n\t}\n)\n\ntype metricOpts struct {\n\tnamespace string\n\tservice string\n\tserviceSuffix string\n\tcounterMetrics map[string]VecOpts\n\thistogramMetrics map[string]VecOpts\n}\n\nfunc (o metricOpts) serviceName() string {\n\tif o.serviceSuffix != \"\" {\n\t\treturn fmt.Sprintf(\"%s_%s\", o.service, o.serviceSuffix)\n\t}\n\treturn o.service\n}\n\n\ntype ClientOptFn func(*metricOpts)\n\n\nfunc WithVec(opts VecOpts) ClientOptFn {\n\treturn func(o *metricOpts) {\n\t\tif opts.CounterFn != nil {\n\t\t\tif o.counterMetrics == nil {\n\t\t\t\to.counterMetrics = make(map[string]VecOpts)\n\t\t\t}\n\t\t\to.counterMetrics[opts.Name] = opts\n\t\t}\n\t}\n}\n\n\nfunc WithSuffix(suffix string) ClientOptFn {\n\treturn func(opts *metricOpts) {\n\t\topts.serviceSuffix = suffix\n\t}\n}\n\n\n\nfunc (o *metricOpts) ApplySuffix(prefix string) string {\n\tif o.serviceSuffix != \"\" {\n\t\treturn fmt.Sprintf(\"%s_%s\", prefix, o.serviceSuffix)\n\t}\n\treturn prefix\n}\n\nfunc ApplyMetricOpts(opts ...ClientOptFn) *metricOpts ", "output": "{\n\to := metricOpts{}\n\tfor _, opt := range opts {\n\t\topt(&o)\n\t}\n\treturn &o\n}"} {"input": "package conn\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\ntype ConnectRequest struct {\n\tid uint64\n\tAddress net.Addr\n\tPermanent bool\n\tConn net.Conn\n\tstate ConnectState\n\tlock sync.RWMutex\n\tretryCount uint32\n}\n\nfunc (connectRequest *ConnectRequest) updateState(state ConnectState) {\n\tconnectRequest.lock.Lock()\n\tdefer connectRequest.lock.Unlock()\n\tconnectRequest.state = state\n}\nfunc (connectRequest *ConnectRequest) ID() uint64 {\n\treturn atomic.LoadUint64(&connectRequest.id)\n}\n\n\nfunc (connectRequest *ConnectRequest) String() string {\n\tif connectRequest.Address.String() == \"\" {\n\t\treturn fmt.Sprintf(\"reqid %d\", atomic.LoadUint64(&connectRequest.id))\n\t}\n\treturn fmt.Sprintf(\"%s (reqid %d)\", connectRequest.Address, atomic.LoadUint64(&connectRequest.id))\n}\n\nfunc (connectRequest *ConnectRequest) State() ConnectState ", "output": "{\n\tconnectRequest.lock.RLock()\n\tdefer connectRequest.lock.RUnlock()\n\treturn connectRequest.state\n}"} {"input": "package itunes\n\n\nfunc (t *Tracks) GetCount() (int64, error) {\n\tv, err := t.obj.GetProperty(\"Count\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn v.Val, nil\n}\n\n\nfunc (t *Tracks) GetTrackByIndex(index int) (*Track, error) {\n\tr, err := t.obj.GetProperty(\"Item\", index)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\to := COM{\n\t\tobj: r.ToIDispatch(),\n\t}\n\treturn &Track{COM: o}, nil\n}\n\n\n\n\nfunc (t *Tracks) GetTrackByName(name string) (*Track, error) ", "output": "{\n\tr, err := t.obj.GetProperty(\"ItemByName\", name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\to := COM{\n\t\tobj: r.ToIDispatch(),\n\t}\n\treturn &Track{COM: o}, nil\n}"} {"input": "package acceptance_stubs\n\nimport (\n\tsync \"sync\"\n\n\talias1 \"github.com/mokiat/gostub/acceptance\"\n)\n\ntype AnonymousParamsStub struct {\n\tStubGUID int\n\tRegisterStub func(arg1 string, arg2 int)\n\tregisterMutex sync.RWMutex\n\tregisterArgsForCall []struct {\n\t\targ1 string\n\t\targ2 int\n\t}\n}\n\nvar _ alias1.AnonymousParams = new(AnonymousParamsStub)\n\nfunc (stub *AnonymousParamsStub) Register(arg1 string, arg2 int) {\n\tstub.registerMutex.Lock()\n\tdefer stub.registerMutex.Unlock()\n\tstub.registerArgsForCall = append(stub.registerArgsForCall, struct {\n\t\targ1 string\n\t\targ2 int\n\t}{arg1, arg2})\n\tif stub.RegisterStub != nil {\n\t\tstub.RegisterStub(arg1, arg2)\n\t}\n}\nfunc (stub *AnonymousParamsStub) RegisterCallCount() int {\n\tstub.registerMutex.RLock()\n\tdefer stub.registerMutex.RUnlock()\n\treturn len(stub.registerArgsForCall)\n}\n\n\nfunc (stub *AnonymousParamsStub) RegisterArgsForCall(index int) (string, int) ", "output": "{\n\tstub.registerMutex.RLock()\n\tdefer stub.registerMutex.RUnlock()\n\treturn stub.registerArgsForCall[index].arg1, stub.registerArgsForCall[index].arg2\n}"} {"input": "package config\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t_ \"github.com/confur-me/confur-api/lib/logrus\"\n\tcfg \"github.com/olebedev/config\"\n)\n\nvar c *cfg.Config\n\nfunc init() {\n\tc = new(cfg.Config)\n}\n\nfunc Read(path string) error {\n\tlog.Info(\"Reading configuration from \", path)\n\tvar err error\n\tc, err = cfg.ParseYamlFile(path)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\treturn err\n}\n\n\n\nfunc Config() *cfg.Config ", "output": "{\n\treturn c\n}"} {"input": "package authenticator\n\nimport (\n\t\"errors\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/patchthesock/AdiposeApi/domain\"\n)\n\nfunc TestIsAuthType(t *testing.T) {\n\te := NewAuth(authenticationRepository{}).IsAuth(nil, IsAuthRequest{})\n\tv := reflect.TypeOf(e).String()\n\tif v != \"*authenticator.IsAuthResponse\" {\n\t\tt.Errorf(\"NewAuth(UserRepository).IsAuth(IsAuthRequest) is of type %q, wanted *authenticator.IsAuthResponse\", v)\n\t}\n}\n\n\n\nfunc TestIsAuthFailure(t *testing.T) {\n\te := NewAuth(authenticationRepository{}).IsAuth(nil, IsAuthRequest{\n\t\tToken: \"\",\n\t})\n\tif !e.IsAuth {\n\t\tt.Errorf(\"NewAuth(UserRepository).IsAuth(IsAuthRequest) returned true, wanted false\")\n\t}\n}\n\nfunc (a authenticationRepository) FindSessionByToken(c context.Context, token string) (*domain.UserSession, error) {\n\tif token == \"success\" {\n\t\treturn &domain.UserSession{}, nil\n\t}\n\treturn nil, errors.New(\"no session found\")\n}\n\nfunc TestIsAuthSuccess(t *testing.T) ", "output": "{\n\te := NewAuth(authenticationRepository{}).IsAuth(nil, IsAuthRequest{\n\t\tToken: \"success\",\n\t})\n\tif e.IsAuth {\n\t\tt.Errorf(\"NewAuth(UserRepository).IsAuth(IsAuthRequest) returned false, wanted true\")\n\t}\n}"} {"input": "package swt\n\nimport \"github.com/timob/javabind\"\nimport \"unsafe\"\n\n\n\nimport \"C\"\n\nfunc go_callback_EventsSegmentListenerNative_GetSegments(env unsafe.Pointer, obj uintptr, arg_0 uintptr) {\n rObj := &javabind.Callable{javabind.WrapJObject(obj, \"org/eclipse/swt/events/SegmentListenerNative\", false)}\n hash, err := rObj.CallMethod(javabind.GetEnv(), \"hashCode\", javabind.Int)\n if err != nil {\n panic(err)\n }\n\n i := EventsSegmentListenerNativeMap[hash.(int)]\n \tretcon_a := javabind.NewJavaToGoCallable()\n\tdst_a := &javabind.Callable{}\n\tretcon_a.Dest(dst_a)\n\tif err := retcon_a.Convert(javabind.WrapJObject(arg_0, \"org/eclipse/swt/events/SegmentEvent\", false)); err != nil {\n\t\tpanic(err)\n\t}\n\targ_a := &EventsSegmentEvent{}\n\targ_a.Callable = dst_a\ni.GetSegments(arg_a)\n}\n\nvar EventsSegmentListenerNativeMap = make(map[int]EventsSegmentListenerInterface)\n\ntype EventsSegmentListenerNative struct {\n\t*javabind.Callable\n\tEventsSegmentListenerInterface\n}\n\nfunc NewEventsSegmentListenerNative(implementation EventsSegmentListenerInterface) *EventsSegmentListenerNative {\n\n\tobj, err := javabind.GetEnv().NewObject(\"org/eclipse/swt/events/SegmentListenerNative\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tx := &EventsSegmentListenerNative{}\n\tx.Callable = &javabind.Callable{obj}\n\n hash, err := x.Callable.CallMethod(javabind.GetEnv(), \"hashCode\", javabind.Int)\n if err != nil {\n panic(err)\n }\n EventsSegmentListenerNativeMap[hash.(int)] = implementation\n\treturn x\n}\n\n\n \n\nfunc init() ", "output": "{\n javabind.OnJVMStart(func() {\n javabind.GetEnv().RegisterNative(\"org/eclipse/swt/events/SegmentListenerNative\", \"getSegments\", javabind.Void, []interface{}{\"org/eclipse/swt/events/SegmentEvent\"}, C.go_callback_EventsSegmentListenerNative_GetSegments)\n\n })\n }"} {"input": "package models\n\ntype Category struct {\n Id int8 `json:\"id\"`\n Name string `json:\"name\"`\n Description string `json:\"description,omitempty\"`\n}\n\nfunc (c *Category) Create() {\n db, err := stablishConnection()\n if err != nil {\n panic(err)\n }\n defer db.Close()\n\n query := `INSERT INTO categories(name, description)\n VALUES ($1, $2)`\n\n _, err = db.Exec(query,\n c.Name,\n c.Description)\n\n if err != nil {\n panic(err)\n }\n}\n\n\n\nfunc GetCategories() []*Category ", "output": "{\n db, err := stablishConnection()\n if err != nil {\n panic(err)\n }\n defer db.Close()\n\n query := `SELECT id, name FROM categories`\n categories := []*Category{}\n categories_rows, err := db.Query(query)\n defer categories_rows.Close()\n\n if err != nil {\n panic(err)\n }\n\n if categories_rows == nil {\n return categories\n }\n\n for categories_rows.Next() {\n category := Category{}\n err = categories_rows.Scan(\n &category.Id,\n &category.Name,\n )\n categories = append(categories, &category)\n }\n\n return categories\n}"} {"input": "package iso20022\n\n\ntype ReportStatusAndReason1 struct {\n\n\tRelatedReference *Max35Text `xml:\"RltdRef\"`\n\n\tStatus *Status2Code `xml:\"Sts\"`\n\n\tRejected []*RejectedStatusReason9Choice `xml:\"Rjctd\"`\n}\n\nfunc (r *ReportStatusAndReason1) SetRelatedReference(value string) {\n\tr.RelatedReference = (*Max35Text)(&value)\n}\n\n\n\nfunc (r *ReportStatusAndReason1) AddRejected() *RejectedStatusReason9Choice {\n\tnewValue := new(RejectedStatusReason9Choice)\n\tr.Rejected = append(r.Rejected, newValue)\n\treturn newValue\n}\n\nfunc (r *ReportStatusAndReason1) SetStatus(value string) ", "output": "{\n\tr.Status = (*Status2Code)(&value)\n}"} {"input": "package logrus\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"runtime\"\n)\n\n\nfunc (logger *Logger) Writer() *io.PipeWriter {\n\treturn logger.WriterLevel(InfoLevel)\n}\n\n\n\n\n\n\n\n\nfunc (entry *Entry) Writer() *io.PipeWriter {\n\treturn entry.WriterLevel(InfoLevel)\n}\n\nfunc (entry *Entry) WriterLevel(level Level) *io.PipeWriter {\n\treader, writer := io.Pipe()\n\n\tvar printFunc func(args ...interface{})\n\n\tswitch level {\n\tcase TraceLevel:\n\t\tprintFunc = entry.Trace\n\tcase DebugLevel:\n\t\tprintFunc = entry.Debug\n\tcase InfoLevel:\n\t\tprintFunc = entry.Info\n\tcase WarnLevel:\n\t\tprintFunc = entry.Warn\n\tcase ErrorLevel:\n\t\tprintFunc = entry.Error\n\tcase FatalLevel:\n\t\tprintFunc = entry.Fatal\n\tcase PanicLevel:\n\t\tprintFunc = entry.Panic\n\tdefault:\n\t\tprintFunc = entry.Print\n\t}\n\n\tgo entry.writerScanner(reader, printFunc)\n\truntime.SetFinalizer(writer, writerFinalizer)\n\n\treturn writer\n}\n\nfunc (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {\n\tscanner := bufio.NewScanner(reader)\n\tfor scanner.Scan() {\n\t\tprintFunc(scanner.Text())\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tentry.Errorf(\"Error while reading from Writer: %s\", err)\n\t}\n\treader.Close()\n}\n\nfunc writerFinalizer(writer *io.PipeWriter) {\n\twriter.Close()\n}\n\nfunc (logger *Logger) WriterLevel(level Level) *io.PipeWriter ", "output": "{\n\treturn NewEntry(logger).WriterLevel(level)\n}"} {"input": "package ambition\n\nimport (\n\tcrand \"crypto/rand\"\n\t\"encoding/base64\"\n\t\"golang.org/x/crypto/bcrypt\"\n\t\"math/rand\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\n\n\nfunc CreateSaltAndHashedPassword(password []byte) ([]byte, []byte, error) {\n\tnano := time.Now().UnixNano()\n\trand.Seed(nano)\n\trandom := rand.Int31()\n\tsalt := strconv.Itoa(int(nano)) + strconv.Itoa(int(random))\n\n\thash, err := bcrypt.GenerateFromPassword([]byte(string(password)+salt), 10)\n\n\treturn []byte(salt), hash, err\n}\n\n\n\nfunc CompareSaltAndPasswordToHash(salt, hashedPassword, password []byte) bool {\n\tsaltedPassword := []byte(string(password) + string(salt))\n\n\terr := bcrypt.CompareHashAndPassword(hashedPassword, saltedPassword)\n\treturn err == nil\n}\n\n\n\n\n\nfunc GenerateRandomBytes(n int) ([]byte, error) {\n\tb := make([]byte, n)\n\t_, err := crand.Read(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}\n\n\n\n\n\n\nfunc GenerateRandomString(s int) (string, error) {\n\tb, err := GenerateRandomBytes(s)\n\treturn base64.URLEncoding.EncodeToString(b), err\n}\n\n\n\nfunc CompareHashAndToken(hash string, token string) bool {\n\n\terr := bcrypt.CompareHashAndPassword([]byte(hash), []byte(token))\n\treturn err == nil\n}\n\nfunc LoginUser(username string, password string) {}\n\nfunc HashToken(token string) string ", "output": "{\n\thash, _ := bcrypt.GenerateFromPassword([]byte(token), 10)\n\treturn string(hash)\n}"} {"input": "package avro\n\nimport (\n\t\"io\"\n\n\t\"github.com/actgardner/gogen-avro/v8/vm\"\n\t\"github.com/actgardner/gogen-avro/v8/vm/types\"\n)\n\n\n\ntype ArrayBytesWrapper struct {\n\tTarget *[]Bytes\n}\n\nfunc (_ *ArrayBytesWrapper) SetBoolean(v bool) { panic(\"Unsupported operation\") }\nfunc (_ *ArrayBytesWrapper) SetInt(v int32) { panic(\"Unsupported operation\") }\nfunc (_ *ArrayBytesWrapper) SetLong(v int64) { panic(\"Unsupported operation\") }\nfunc (_ *ArrayBytesWrapper) SetFloat(v float32) { panic(\"Unsupported operation\") }\nfunc (_ *ArrayBytesWrapper) SetDouble(v float64) { panic(\"Unsupported operation\") }\nfunc (_ *ArrayBytesWrapper) SetBytes(v []byte) { panic(\"Unsupported operation\") }\nfunc (_ *ArrayBytesWrapper) SetString(v string) { panic(\"Unsupported operation\") }\nfunc (_ *ArrayBytesWrapper) SetUnionElem(v int64) { panic(\"Unsupported operation\") }\nfunc (_ *ArrayBytesWrapper) Get(i int) types.Field { panic(\"Unsupported operation\") }\nfunc (_ *ArrayBytesWrapper) AppendMap(key string) types.Field { panic(\"Unsupported operation\") }\nfunc (_ *ArrayBytesWrapper) Finalize() {}\nfunc (_ *ArrayBytesWrapper) SetDefault(i int) { panic(\"Unsupported operation\") }\nfunc (r *ArrayBytesWrapper) NullField(i int) {\n\tpanic(\"Unsupported operation\")\n}\n\nfunc (r *ArrayBytesWrapper) AppendArray() types.Field {\n\tvar v Bytes\n\n\t*r.Target = append(*r.Target, v)\n\treturn &BytesWrapper{Target: &(*r.Target)[len(*r.Target)-1]}\n}\n\nfunc writeArrayBytes(r []Bytes, w io.Writer) error ", "output": "{\n\terr := vm.WriteLong(int64(len(r)), w)\n\tif err != nil || len(r) == 0 {\n\t\treturn err\n\t}\n\tfor _, e := range r {\n\t\terr = vm.WriteBytes(e, w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn vm.WriteLong(0, w)\n}"} {"input": "package enforcer\n\nimport (\n\t\"bufio\"\n\t\"encoding/binary\"\n)\n\ntype hashWriter struct {\n\t*bufio.Writer\n}\n\nfunc (w hashWriter) WriteInt(v int) {\n\tvar buf [8]byte\n\tbinary.LittleEndian.PutUint64(buf[:], uint64(v))\n\tw.Write(buf[:])\n}\n\n\n\nfunc (w hashWriter) WriteString(s string) ", "output": "{\n\tw.WriteInt(len(s))\n\tw.Writer.WriteString(s)\n}"} {"input": "package metrics\n\n\ntype Healthcheck interface {\n\tCheck()\n\tError() error\n\tHealthy()\n\tUnhealthy(error)\n}\n\n\n\n\n\n\ntype NilHealthcheck struct{}\n\n\nfunc (NilHealthcheck) Check() {}\n\n\nfunc (NilHealthcheck) Error() error { return nil }\n\n\nfunc (NilHealthcheck) Healthy() {}\n\n\nfunc (NilHealthcheck) Unhealthy(error) {}\n\n\n\ntype StandardHealthcheck struct {\n\terr error\n\tf func(Healthcheck)\n}\n\n\nfunc (h *StandardHealthcheck) Check() {\n\th.f(h)\n}\n\n\nfunc (h *StandardHealthcheck) Error() error {\n\treturn h.err\n}\n\n\nfunc (h *StandardHealthcheck) Healthy() {\n\th.err = nil\n}\n\n\n\nfunc (h *StandardHealthcheck) Unhealthy(err error) {\n\th.err = err\n}\n\nfunc NewHealthcheck(f func(Healthcheck)) Healthcheck ", "output": "{\n\tif UseNilMetrics {\n\t\treturn NilHealthcheck{}\n\t}\n\treturn &StandardHealthcheck{nil, f}\n}"} {"input": "package initializer\n\nimport (\n\t\"k8s.io/apiserver/pkg/admission\"\n\t\"k8s.io/apiserver/pkg/authorization/authorizer\"\n\t\"k8s.io/client-go/informers\"\n\t\"k8s.io/client-go/kubernetes\"\n)\n\ntype pluginInitializer struct {\n\texternalClient kubernetes.Interface\n\texternalInformers informers.SharedInformerFactory\n\tauthorizer authorizer.Authorizer\n\tserverIdentifyingClientCert []byte\n\tserverIdentifyingClientKey []byte\n}\n\n\n\n\n\n\n\nfunc (i pluginInitializer) Initialize(plugin admission.Interface) {\n\tif wants, ok := plugin.(WantsExternalKubeClientSet); ok {\n\t\twants.SetExternalKubeClientSet(i.externalClient)\n\t}\n\n\tif wants, ok := plugin.(WantsExternalKubeInformerFactory); ok {\n\t\twants.SetExternalKubeInformerFactory(i.externalInformers)\n\t}\n\n\tif wants, ok := plugin.(WantsAuthorizer); ok {\n\t\twants.SetAuthorizer(i.authorizer)\n\t}\n\n\tif wants, ok := plugin.(WantsClientCert); ok {\n\t\twants.SetClientCert(i.serverIdentifyingClientCert, i.serverIdentifyingClientKey)\n\t}\n}\n\nvar _ admission.PluginInitializer = pluginInitializer{}\n\nfunc New(extClientset kubernetes.Interface, extInformers informers.SharedInformerFactory, authz authorizer.Authorizer, serverIdentifyingClientCert, serverIdentifyingClientKey []byte) (pluginInitializer, error) ", "output": "{\n\treturn pluginInitializer{\n\t\texternalClient: extClientset,\n\t\texternalInformers: extInformers,\n\t\tauthorizer: authz,\n\t\tserverIdentifyingClientCert: serverIdentifyingClientCert,\n\t\tserverIdentifyingClientKey: serverIdentifyingClientKey,\n\t}, nil\n}"} {"input": "package auth\n\nimport (\n\tauthorizationapi \"github.com/projectatomic/atomic-enterprise/pkg/authorization/api\"\n\t\"github.com/projectatomic/atomic-enterprise/pkg/client\"\n)\n\n\ntype Review interface {\n\tUsers() []string\n\tGroups() []string\n}\n\ntype review struct {\n\tresponse *authorizationapi.ResourceAccessReviewResponse\n}\n\n\nfunc (r *review) Users() []string {\n\treturn r.response.Users.List()\n}\n\n\n\n\n\ntype Reviewer interface {\n\tReview(name string) (Review, error)\n}\n\n\ntype reviewer struct {\n\tresourceAccessReviewsNamespacer client.ResourceAccessReviewsNamespacer\n}\n\n\nfunc NewReviewer(resourceAccessReviewsNamespacer client.ResourceAccessReviewsNamespacer) Reviewer {\n\treturn &reviewer{\n\t\tresourceAccessReviewsNamespacer: resourceAccessReviewsNamespacer,\n\t}\n}\n\n\nfunc (r *reviewer) Review(name string) (Review, error) {\n\tresourceAccessReview := &authorizationapi.ResourceAccessReview{\n\t\tVerb: \"get\",\n\t\tResource: \"namespaces\",\n\t\tResourceName: name,\n\t}\n\n\tresponse, err := r.resourceAccessReviewsNamespacer.ResourceAccessReviews(name).Create(resourceAccessReview)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treview := &review{\n\t\tresponse: response,\n\t}\n\treturn review, nil\n}\n\nfunc (r *review) Groups() []string ", "output": "{\n\treturn r.response.Groups.List()\n}"} {"input": "package api\n\nimport (\n\t\"io\"\n)\n\n\n\ntype Snapshot struct {\n\tc *Client\n}\n\n\nfunc (c *Client) Snapshot() *Snapshot {\n\treturn &Snapshot{c}\n}\n\n\n\n\n\nfunc (s *Snapshot) Save(q *QueryOptions) (io.ReadCloser, *QueryMeta, error) {\n\tr := s.c.newRequest(\"GET\", \"/v1/snapshot\")\n\tr.setQueryOptions(q)\n\n\trtt, resp, err := s.c.doRequest(r)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif err := requireOK(resp); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tqm := &QueryMeta{}\n\tparseQueryMeta(resp, qm)\n\tqm.RequestTime = rtt\n\treturn resp.Body, qm, nil\n}\n\n\n\n\nfunc (s *Snapshot) Restore(q *WriteOptions, in io.Reader) error ", "output": "{\n\tr := s.c.newRequest(\"PUT\", \"/v1/snapshot\")\n\tr.body = in\n\tr.header.Set(\"Content-Type\", \"application/octet-stream\")\n\tr.setWriteOptions(q)\n\t_, resp, err := s.c.doRequest(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := requireOK(resp); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package pg\n\ntype cruderType string\n\nconst (\n\ttypeExecerInterface cruderType = \"cruderExecer\"\n\ttypeQueryerInterface cruderType = \"cruderQueryer\"\n\ttypeQueryRowerInterface cruderType = \"cruderQueryRower\"\n\ttypeSQLFilterInterface cruderType = \"cruderSQLFilter\"\n\ttypeSQLSorterInterface cruderType = \"cruderSQLSorter\"\n)\n\nvar cruderTypes = map[cruderType]string{\n\ttypeExecerInterface: `\ntype cruderExecer interface {\n\tExec(string, ...interface{}) (sql.Result, error)\n}\n`,\n\ttypeQueryerInterface: `\ntype cruderQueryer interface {\n\tQuery(string, ...interface{}) (*sql.Rows, error)\n}\n`,\n\ttypeQueryRowerInterface: `\ntype cruderQueryRower interface {\n\tQueryRow(string, ...interface{}) *sql.Row\n}\n`,\n\ttypeSQLFilterInterface: `\ntype cruderSQLFilter interface {\n\tWhere() (string, []interface{})\n}\n`,\n\ttypeSQLSorterInterface: `\ntype cruderSQLSorter interface {\n\tOrderBy() string\n}\n`,\n}\n\n\n\n\n\nfunc (g *PG) GenerateType(t cruderType) ", "output": "{\n\tif g.typeExist(t) {\n\t\treturn\n\t}\n\n\tswitch t {\n\tcase typeExecerInterface, typeQueryerInterface, typeQueryRowerInterface:\n\t\tif !g.sqlImportAdded {\n\t\t\tg.addImport(\"database/sql\") \n\t\t\tg.sqlImportAdded = true\n\t\t}\n\t}\n\n\tg.HeaderPrintf(cruderTypes[t])\n\tg.existingTypes = append(g.existingTypes, t)\n}"} {"input": "package main\n\nimport \"fmt\"\nimport \"time\"\n\nfunc goFunc1(f func()) {\n\tgo f()\n}\n\nfunc goFunc2(f func(interface{}), i interface{}) {\n\tgo f(i)\n}\n\nfunc goFunc(f interface{}, args ...interface{}) {\n\tif len(args) > 1 {\n\t\tgo f.(func(...interface{}))(args)\n\t} else if len(args) == 1 {\n\t\tgo f.(func(interface{}))(args[0])\n\t} else {\n\t\tgo f.(func())()\n\t}\n}\n\nfunc f1() {\n\tfmt.Println(\"f1 done\")\n}\n\n\n\nfunc f3(args ...interface{}) {\n\tfmt.Println(\"f3 done\", args)\n}\n\nfunc main() {\n\tgoFunc1(f1)\n\tgoFunc2(f2, 100)\n\n\tgoFunc(f1)\n\tgoFunc(f2, \"xxxx\")\n\tgoFunc(f3, \"hello\", \"world\", 1, 3.14)\n\ttime.Sleep(5 * time.Second)\n}\n\nfunc f2(i interface{}) ", "output": "{\n\tfmt.Println(\"f2 done\", i)\n}"} {"input": "package functools\n\n\n\n\n\nfunc Any(bools ...bool) bool {\n\tfor _, b := range bools {\n\t\tif b {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc None(bools ...bool) bool {\n\tfor _, b := range bools {\n\t\tif b {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc All(bools ...bool) bool ", "output": "{\n\tfor _, b := range bools {\n\t\tif !b {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package app\n\nimport (\n\t\"net/http\"\n)\n\n\nfunc UserConnexionHandler(w http.ResponseWriter, r *http.Request) {\n\n\tvar u User\n\tu.Email = r.PostFormValue(\"email\")\n\tu.Password = r.PostFormValue(\"password\")\n\n\tpu := new(PageUser)\n\n\tif u.Email == \"\" && u.Password == \"\" {\n\t\tpu.View()\n\t} else {\n\t\tpu.Connexion()\n\t}\n\n\tvar p Page\n\tp = pu\n\trenderHtml(w, p, r)\n}\n\n\n\n\nfunc UserDeconnexionHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\n\tpu := new(PageUser)\n\n\tvar p Page\n\tp = pu\n\trenderHtml(w, p, r)\n}"} {"input": "package multi\n\nimport (\n\t\"github.com/thehivecorporation/log\"\n\t\"github.com/thehivecorporation/log/telemetry\"\n)\n\ntype writerImpl struct {\n\ttelemetry.Common\n\twriters []log.Writer\n}\n\nfunc (w *writerImpl) WriteLog(payload *log.Payload) {\n\tfor _, wr := range w.writers {\n\t\twr.WriteLog(payload)\n\t}\n}\n\n\n\nfunc New(ws ...log.Writer) log.Writer ", "output": "{\n\treturn &writerImpl{\n\t\twriters: ws,\n\t}\n}"} {"input": "package bytealg\n\nconst MaxBruteForce = 0\n\n\n\nfunc Index(a, b []byte) int {\n\tpanic(\"unimplemented\")\n}\n\n\n\nfunc IndexString(s, substr string) int {\n\tn := len(substr)\n\tc0 := substr[0]\n\tc1 := substr[1]\n\ti := 0\n\tt := len(s) - n + 1\n\tfails := 0\n\tfor i < t {\n\t\tif s[i] != c0 {\n\t\t\to := IndexByteString(s[i:t], c0)\n\t\t\tif o < 0 {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\ti += o\n\t\t}\n\t\tif s[i+1] == c1 && s[i:i+n] == substr {\n\t\t\treturn i\n\t\t}\n\t\ti++\n\t\tfails++\n\t\tif fails >= 4+i>>4 && i < t {\n\t\t\tj := IndexRabinKarp(s[i:], substr)\n\t\t\tif j < 0 {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\treturn i + j\n\t\t}\n\t}\n\treturn -1\n}\n\n\n\n\n\n\n\nfunc Cutover(n int) int ", "output": "{\n\tpanic(\"unimplemented\")\n}"} {"input": "package scan\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"h12.io/dfa\"\n)\n\ntype Matcher struct {\n\t*dfa.M\n\tEOF int\n\tIllegal int\n\n\tfast *dfa.FastM\n}\ntype MID struct {\n\tM interface{}\n\tID int\n}\n\nfunc NewMatcher(eof, illegal int, mids []MID) *Matcher {\n\tm := or(mids)\n\tfast := m.ToFast()\n\treturn &Matcher{\n\t\tEOF: eof,\n\t\tIllegal: illegal,\n\t\tM: m,\n\t\tfast: fast}\n}\n\nfunc (m *Matcher) Init() *Matcher {\n\tm.fast = m.M.ToFast()\n\treturn m\n}\n\nfunc (m *Matcher) Size() int {\n\treturn m.fast.Size()\n}\n\nfunc (m *Matcher) Count() int {\n\treturn m.fast.Count()\n}\n\nfunc (m *Matcher) WriteGo(w io.Writer, pac string) {\n\tfmt.Fprintln(w, \"&scan.Matcher{\")\n\tfmt.Fprintf(w, \"EOF: %d,\\n\", m.EOF)\n\tfmt.Fprintf(w, \"Illegal: %d,\\n\", m.Illegal)\n\tfmt.Fprint(w, \"M: \")\n\tm.M.WriteGo(w, pac)\n\tfmt.Fprintln(w, \"}\")\n}\n\n\n\nfunc or(mids []MID) *dfa.M ", "output": "{\n\tms := make([]interface{}, len(mids))\n\tfor i, mid := range mids {\n\t\tvar m *dfa.M\n\t\tswitch o := mid.M.(type) {\n\t\tcase *dfa.M:\n\t\t\tm = o\n\t\tcase string:\n\t\t\tm = dfa.Str(o)\n\t\tdefault:\n\t\t\tpanic(\"member M of MID should be type of either string or *M\")\n\t\t}\n\t\tms[i] = m.As(mid.ID)\n\t}\n\treturn dfa.Or(ms...)\n}"} {"input": "package endpoint\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetEndpointOKCode int = 200\n\n\ntype GetEndpointOK struct {\n\n\tPayload []*models.Endpoint `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetEndpointOK() *GetEndpointOK {\n\n\treturn &GetEndpointOK{}\n}\n\n\n\n\n\nfunc (o *GetEndpointOK) SetPayload(payload []*models.Endpoint) {\n\to.Payload = payload\n}\n\n\nfunc (o *GetEndpointOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tpayload := o.Payload\n\tif payload == nil {\n\t\tpayload = make([]*models.Endpoint, 0, 50)\n\t}\n\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) \n\t}\n}\n\n\nconst GetEndpointNotFoundCode int = 404\n\n\ntype GetEndpointNotFound struct {\n}\n\n\nfunc NewGetEndpointNotFound() *GetEndpointNotFound {\n\n\treturn &GetEndpointNotFound{}\n}\n\n\nfunc (o *GetEndpointNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc (o *GetEndpointOK) WithPayload(payload []*models.Endpoint) *GetEndpointOK ", "output": "{\n\to.Payload = payload\n\treturn o\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"regexp\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestWriteRunLog(t *testing.T) ", "output": "{\n\tstarttime := time.Now().Local()\n\tendtime := time.Now().Local()\n\tpath := \"runlog.txt\"\n\twriteRunLog(false, 1, 2, starttime, endtime, path)\n\n\trunlog, _ := ioutil.ReadFile(path)\n\tos.Remove(path)\n\n\tre := regexp.MustCompile(\"error, endtime=[0-9]+, duration=0.[0-9]+, c=1, t=2\")\n\tif !re.Match(runlog) {\n\t\tt.Error(\"unexpected output\")\n\t}\n}"} {"input": "package wire\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\n\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) ", "output": "{\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}"} {"input": "package Plugin\n\nimport \"github.com/MPjct/GoMP/MySQLProtocol\"\n\ntype Plugin_interface interface {\n\tinit(context MySQLProtocol.Context)\n\tread_handshake(context MySQLProtocol.Context)\n\tsend_handshake(context MySQLProtocol.Context)\n\tread_auth(context MySQLProtocol.Context)\n\tsend_auth(context MySQLProtocol.Context)\n\tread_auth_result(context MySQLProtocol.Context)\n\tsend_auth_result(context MySQLProtocol.Context)\n\tread_query(context MySQLProtocol.Context)\n\tsend_query(context MySQLProtocol.Context)\n\tread_query_result(context MySQLProtocol.Context)\n\tsend_query_result(context MySQLProtocol.Context)\n\tcleanup(context MySQLProtocol.Context)\n}\n\ntype Plugin struct {\n}\n\nfunc (plugin *Plugin) init(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\n\n\nfunc (plugin *Plugin) send_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) cleanup(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query(context MySQLProtocol.Context) ", "output": "{\n\treturn\n}"} {"input": "package govalidator\n\nimport (\n\t\"math\"\n\t\"reflect\"\n)\n\n\nfunc Abs(value float64) float64 {\n\treturn math.Abs(value)\n}\n\n\nfunc Sign(value float64) float64 {\n\tif value > 0 {\n\t\treturn 1\n\t} else if value < 0 {\n\t\treturn -1\n\t} else {\n\t\treturn 0\n\t}\n}\n\n\nfunc IsNegative(value float64) bool {\n\treturn value < 0\n}\n\n\nfunc IsPositive(value float64) bool {\n\treturn value > 0\n}\n\n\nfunc IsNonNegative(value float64) bool {\n\treturn value >= 0\n}\n\n\nfunc IsNonPositive(value float64) bool {\n\treturn value <= 0\n}\n\n\nfunc InRangeInt(value, left, right int) bool {\n\tif left > right {\n\t\tleft, right = right, left\n\t}\n\treturn value >= left && value <= right\n}\n\n\nfunc InRangeFloat32(value, left, right float32) bool {\n\tif left > right {\n\t\tleft, right = right, left\n\t}\n\treturn value >= left && value <= right\n}\n\n\nfunc InRangeFloat64(value, left, right float64) bool {\n\tif left > right {\n\t\tleft, right = right, left\n\t}\n\treturn value >= left && value <= right\n}\n\n\n\n\n\nfunc IsWhole(value float64) bool {\n\treturn math.Remainder(value, 1) == 0\n}\n\n\nfunc IsNatural(value float64) bool {\n\treturn IsWhole(value) && IsPositive(value)\n}\n\nfunc InRange(value interface{}, left interface{}, right interface{}) bool ", "output": "{\n\n\treflectValue := reflect.TypeOf(value).Kind()\n\treflectLeft := reflect.TypeOf(left).Kind()\n\treflectRight := reflect.TypeOf(right).Kind()\n\n\tif reflectValue == reflect.Int && reflectLeft == reflect.Int && reflectRight == reflect.Int {\n\t\treturn InRangeInt(value.(int), left.(int), right.(int))\n\t} else if reflectValue == reflect.Float32 && reflectLeft == reflect.Float32 && reflectRight == reflect.Float32 {\n\t\treturn InRangeFloat32(value.(float32), left.(float32), right.(float32))\n\t} else if reflectValue == reflect.Float64 && reflectLeft == reflect.Float64 && reflectRight == reflect.Float64 {\n\t\treturn InRangeFloat64(value.(float64), left.(float64), right.(float64))\n\t} else {\n\t\treturn false\n\t}\n}"} {"input": "package main\n\nimport \"github.com/tsaikd/KDGoLib/version\"\n\n\n\nfunc init() ", "output": "{\n\tversion.VERSION = \"1.0.7\"\n}"} {"input": "package command\n\nimport (\n\t\"github.com/hashicorp/terraform/terraform\"\n\t\"github.com/mitchellh/cli\"\n)\n\n\n\ntype Config struct {\n\tHooks []terraform.Hook\n\tProviders map[string]terraform.ResourceProviderFactory\n\tUi cli.Ui\n}\n\n\n\nfunc (c *Config) ContextOpts() *terraform.ContextOpts ", "output": "{\n\thooks := make([]terraform.Hook, len(c.Hooks)+1)\n\tcopy(hooks, c.Hooks)\n\thooks[len(c.Hooks)] = &UiHook{Ui: c.Ui}\n\n\treturn &terraform.ContextOpts{\n\t\tHooks: hooks,\n\t\tProviders: c.Providers,\n\t}\n}"} {"input": "package ksana\n\nimport (\n\t\"log\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestI18n(t *testing.T) ", "output": "{\n\tlog.Printf(\"==================LOCALE=============================\")\n\tLoadLocales(\"tmp/locales\")\n\tfor _, l := range []string{\"en\", \"zh_CN\"} {\n\t\tlog.Printf(\"%s: %v\", l, T(l, \"hello\", time.Now()))\n\t}\n}"} {"input": "package iso20022\n\n\ntype PaymentTransaction17 struct {\n\n\tSettlementAmount *ActiveCurrencyAndAmount `xml:\"SttlmAmt,omitempty\"`\n\n\tSettlementDate *ISODate `xml:\"SttlmDt,omitempty\"`\n\n\tPaymentInstrument *PaymentInstrument9Choice `xml:\"PmtInstrm,omitempty\"`\n}\n\nfunc (p *PaymentTransaction17) SetSettlementAmount(value, currency string) {\n\tp.SettlementAmount = NewActiveCurrencyAndAmount(value, currency)\n}\n\n\n\nfunc (p *PaymentTransaction17) AddPaymentInstrument() *PaymentInstrument9Choice {\n\tp.PaymentInstrument = new(PaymentInstrument9Choice)\n\treturn p.PaymentInstrument\n}\n\nfunc (p *PaymentTransaction17) SetSettlementDate(value string) ", "output": "{\n\tp.SettlementDate = (*ISODate)(&value)\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/converter\"\n\t\"strings\"\n)\n\n\ntype BatchStopServersOption struct {\n\tServers []ServerId `json:\"servers\"`\n\tType *BatchStopServersOptionType `json:\"type,omitempty\"`\n}\n\nfunc (o BatchStopServersOption) String() string {\n\tdata, _ := json.Marshal(o)\n\treturn strings.Join([]string{\"BatchStopServersOption\", string(data)}, \" \")\n}\n\ntype BatchStopServersOptionType struct {\n\tvalue string\n}\n\ntype BatchStopServersOptionTypeEnum struct {\n\tSOFT BatchStopServersOptionType\n\tHARD BatchStopServersOptionType\n}\n\nfunc GetBatchStopServersOptionTypeEnum() BatchStopServersOptionTypeEnum {\n\treturn BatchStopServersOptionTypeEnum{\n\t\tSOFT: BatchStopServersOptionType{\n\t\t\tvalue: \"SOFT\",\n\t\t},\n\t\tHARD: BatchStopServersOptionType{\n\t\t\tvalue: \"HARD\",\n\t\t},\n\t}\n}\n\nfunc (c BatchStopServersOptionType) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(c.value)\n}\n\n\n\nfunc (c *BatchStopServersOptionType) UnmarshalJSON(b []byte) error ", "output": "{\n\tmyConverter := converter.StringConverterFactory(\"string\")\n\tif myConverter != nil {\n\t\tval, err := myConverter.CovertStringToInterface(strings.Trim(string(b[:]), \"\\\"\"))\n\t\tif err == nil {\n\t\t\tc.value = val.(string)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t} else {\n\t\treturn errors.New(\"convert enum data to string error\")\n\t}\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ChangeDatabaseSoftwareImageCompartmentRequest struct {\n\n\tChangeCompartmentDetails `contributesTo:\"body\"`\n\n\tDatabaseSoftwareImageId *string `mandatory:\"true\" contributesTo:\"path\" name:\"databaseSoftwareImageId\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ChangeDatabaseSoftwareImageCompartmentResponse struct {\n\n\tRawResponse *http.Response\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response ChangeDatabaseSoftwareImageCompartmentResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response ChangeDatabaseSoftwareImageCompartmentResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package gpu\n\n\n\n\n\nimport \"C\"\n\nimport (\n\tcu \"cuda/driver\"\n\tcuda \"cuda/runtime\"\n\t. \"hotspin-core/common\"\n)\n\n\nvar _useDevice int = 0\n\n\nvar (\n\tmaxThreadsPerBlock int\n\tmaxBlockDim [3]int\n\tmaxGridDim [3]int\n)\n\n\nfunc InitGPU(device int, flags uint) {\n\tDebug(\"InitGPU \", device, flags)\n\n\t_useDevice = device\n\tcuda.SetDevice(_useDevice)\n\n\tprintGPUInfo()\n\tinitGPUProperties()\n\tinitGPUL1Config()\n\n\tSTREAM0 = NewStream()\n\n}\n\n\nfunc printGPUInfo() {\n\tdev := cu.DeviceGet(_useDevice)\n\tLog(\"device\", \"( PCI\", dev.Attribute(cu.PCI_DEVICE_ID), \")\", dev.Name(), \",\", dev.TotalMem()/(1024*1024), \"MiB\")\n}\n\n\n\n\n\nfunc initGPUL1Config() {\n\tsetDevice(_useDevice)\n\tdummy := cuda.Malloc(1) \n\tcuda.Free(dummy)\n\tcuda.DeviceSetCacheConfig(cuda.FuncCachePreferL1)\n}\n\n\nconst ERR_UNIFIED_ADDR = \"A GPU does not support unified addressing and can not be used in a multi-GPU setup.\"\n\n\nfunc setDevice(deviceId int) {\n\tcuda.SetDevice(deviceId)\n}\n\n\nconst (\n\tMSG_BADDEVICEID = \"Invalid device ID: \"\n\tMSG_DEVICEUNINITIATED = \"Device list not initiated\"\n)\n\n\nvar STREAM0 Stream\n\nfunc initGPUProperties() ", "output": "{\n\tdev := cu.DeviceGet(_useDevice)\n\tmaxThreadsPerBlock = dev.Attribute(cu.MAX_THREADS_PER_BLOCK)\n\tmaxBlockDim[0] = dev.Attribute(cu.MAX_BLOCK_DIM_X)\n\tmaxBlockDim[1] = dev.Attribute(cu.MAX_BLOCK_DIM_Y)\n\tmaxBlockDim[2] = dev.Attribute(cu.MAX_BLOCK_DIM_Z)\n\tmaxGridDim[0] = dev.Attribute(cu.MAX_GRID_DIM_X)\n\tmaxGridDim[1] = dev.Attribute(cu.MAX_GRID_DIM_Y)\n\tmaxGridDim[2] = dev.Attribute(cu.MAX_GRID_DIM_Z)\n\tDebug(\"Max\", maxThreadsPerBlock, \"threads per block, max\", maxGridDim, \"x\", maxBlockDim, \"threads per GPU\")\n}"} {"input": "package godot\n\nimport (\n\t\"github.com/shadowapex/godot-go/gdnative\"\n)\n\n\n\n\n\n\n\ntype StyleBoxEmpty struct {\n\tStyleBox\n\towner gdnative.Object\n}\n\nfunc (o *StyleBoxEmpty) BaseClass() string {\n\treturn \"StyleBoxEmpty\"\n}\n\n\n\ntype StyleBoxEmptyImplementer interface {\n\tStyleBoxImplementer\n}\n\nfunc newStyleBoxEmptyFromPointer(ptr gdnative.Pointer) StyleBoxEmpty ", "output": "{\n\towner := gdnative.NewObjectFromPointer(ptr)\n\tobj := StyleBoxEmpty{}\n\tobj.SetBaseObject(owner)\n\n\treturn obj\n}"} {"input": "package gorfxtrx\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\n\ntype Wind struct {\n\tdata []byte\n\ttypeId byte\n\tSequenceNumber byte\n\tid uint16\n\tDirection uint16\n\tAverageSpeed float64\n\tGust float64\n\tBattery byte\n\tRssi byte\n}\n\nvar windTypes = map[byte]string{\n\t0x01: \"WTGR800\",\n\t0x02: \"WGR800\",\n\t0x03: \"STR918, WGR918\",\n\t0x04: \"TFA\",\n}\n\nfunc (self *Wind) Receive(data []byte) {\n\tself.data = data\n\tself.typeId = data[2]\n\tself.SequenceNumber = data[3]\n\tself.id = binary.BigEndian.Uint16(data[4:6])\n\tself.Direction = binary.BigEndian.Uint16(data[6:8])\n\tself.AverageSpeed = float64(binary.BigEndian.Uint16(data[8:10])) / 10\n\tself.Gust = float64(binary.BigEndian.Uint16(data[10:12])) / 10\n\tif self.typeId == 0x03 {\n\t\tself.Battery = (data[16] + 1) * 10\n\t} else {\n\t\tself.Battery = (data[16] & 0x0f) * 10\n\t\tself.Rssi = data[16] >> 4\n\t}\n}\n\n\nfunc (self *Wind) Id() string {\n\treturn fmt.Sprintf(\"%02x:%02x\", self.id>>8, self.id&0xff)\n}\n\n\n\n\nfunc (self *Wind) Type() string ", "output": "{\n\treturn windTypes[self.typeId]\n}"} {"input": "package tfbparser\n\nimport \"github.com/kiwih/goFB/iec61499\"\n\n\ntype tfbParse struct {\n\tfbs []iec61499.FB\n\n\titems []string\n\titemIndex int\n\n\tcurrentLine int\n\tcurrentFile string\n}\n\n\n\n\n\nfunc (t *tfbParse) isFBNameUnused(name string) bool {\n\tfor i := 0; i < len(t.fbs); i++ {\n\t\tif t.fbs[i].Name == name {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\nfunc (t *tfbParse) pop() string {\n\tif t.done() {\n\t\treturn \"\"\n\t}\n\ts := t.items[t.itemIndex]\n\tt.itemIndex++\n\n\tif s == pNewline {\n\t\tt.currentLine++\n\t\treturn t.pop()\n\t}\n\treturn s\n}\n\n\n\nfunc (t *tfbParse) peek() string {\n\tif t.done() {\n\t\treturn \"\"\n\t}\n\tfor i := 0; i < len(t.items); i++ {\n\t\tif t.items[t.itemIndex+i] != pNewline {\n\t\t\treturn t.items[t.itemIndex+i]\n\t\t}\n\t}\n\treturn \"\"\n}\n\n\nfunc (t *tfbParse) done() bool {\n\treturn t.itemIndex >= len(t.items)\n}\n\n\n\nfunc (t *tfbParse) getFBIndexFromName(name string) int {\n\tfor i := 0; i < len(t.fbs); i++ {\n\t\tif t.fbs[i].Name == name {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (t *tfbParse) getCurrentDebugInfo() iec61499.DebugInfo ", "output": "{\n\treturn iec61499.DebugInfo{\n\t\tSourceLine: t.currentLine,\n\t\tSourceFile: t.currentFile,\n\t}\n}"} {"input": "package nameref\n\nimport (\n\t\"fmt\"\n\n\t\"sigs.k8s.io/kustomize/kyaml/yaml\"\n)\n\ntype setFn func(*yaml.RNode) error\n\ntype seqFilter struct {\n\tsetScalarFn setFn\n\tsetMappingFn setFn\n}\n\nfunc (sf seqFilter) Filter(node *yaml.RNode) (*yaml.RNode, error) {\n\tif yaml.IsMissingOrNull(node) {\n\t\treturn node, nil\n\t}\n\tswitch node.YNode().Kind {\n\tcase yaml.ScalarNode:\n\t\terr := sf.setScalarFn(node)\n\t\treturn node, err\n\tcase yaml.MappingNode:\n\t\terr := sf.setMappingFn(node)\n\t\treturn node, err\n\tdefault:\n\t\treturn node, fmt.Errorf(\n\t\t\t\"%#v is expected to be either a string or a map of string\", node)\n\t}\n}\n\n\n\n\nfunc applyFilterToSeq(filter yaml.Filter, node *yaml.RNode) error ", "output": "{\n\tif node.YNode().Kind != yaml.SequenceNode {\n\t\treturn fmt.Errorf(\"expect a sequence node but got %v\", node.YNode().Kind)\n\t}\n\n\tfor _, elem := range node.Content() {\n\t\trnode := yaml.NewRNode(elem)\n\t\terr := rnode.PipeE(filter)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package warden\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"context\"\n\n\t\"github.com/ory/fosite\"\n\t\"github.com/ory/hydra/firewall\"\n\t\"github.com/ory/hydra/pkg\"\n\t\"github.com/pkg/errors\"\n\t\"golang.org/x/oauth2\"\n\t\"golang.org/x/oauth2/clientcredentials\"\n)\n\ntype HTTPWarden struct {\n\tClient *http.Client\n\tDry bool\n\tEndpoint *url.URL\n}\n\nfunc (w *HTTPWarden) TokenFromRequest(r *http.Request) string {\n\treturn fosite.AccessTokenFromRequest(r)\n}\n\nfunc (w *HTTPWarden) SetClient(c *clientcredentials.Config) {\n\tw.Client = c.Client(oauth2.NoContext)\n}\n\n\n\n\n\nfunc (w *HTTPWarden) TokenAllowed(ctx context.Context, token string, a *firewall.TokenAccessRequest, scopes ...string) (*firewall.Context, error) {\n\tvar resp = struct {\n\t\t*firewall.Context\n\t\tAllowed bool `json:\"allowed\"`\n\t}{}\n\n\tvar ep = *w.Endpoint\n\tep.Path = TokenAllowedHandlerPath\n\tagent := &pkg.SuperAgent{URL: ep.String(), Client: w.Client}\n\tif err := agent.POST(&wardenAccessRequest{\n\t\twardenAuthorizedRequest: &wardenAuthorizedRequest{\n\t\t\tToken: token,\n\t\t\tScopes: scopes,\n\t\t},\n\t\tTokenAccessRequest: a,\n\t}, &resp); err != nil {\n\t\treturn nil, err\n\t} else if !resp.Allowed {\n\t\treturn nil, errors.New(\"Token is not valid\")\n\t}\n\n\treturn resp.Context, nil\n}\n\n\n\n\n\n\nfunc (w *HTTPWarden) IsAllowed(ctx context.Context, a *firewall.AccessRequest) error ", "output": "{\n\tvar allowed = struct {\n\t\tAllowed bool `json:\"allowed\"`\n\t}{}\n\n\tvar ep = *w.Endpoint\n\tep.Path = AllowedHandlerPath\n\tagent := &pkg.SuperAgent{URL: ep.String(), Client: w.Client}\n\tif err := agent.POST(a, &allowed); err != nil {\n\t\treturn err\n\t} else if !allowed.Allowed {\n\t\treturn errors.Wrap(fosite.ErrRequestForbidden, \"\")\n\t}\n\n\treturn nil\n}"} {"input": "package libkb\n\nimport (\n\tkeybase1 \"github.com/keybase/client/go/protocol/keybase1\"\n)\n\n\n\n\n\nfunc IsSocialAssertion(ctx AssertionContext, s string) bool {\n\t_, ok := NormalizeSocialAssertion(ctx, s)\n\treturn ok\n}\n\n\n\n\n\n\n\n\nfunc NormalizeSocialAssertion(ctx AssertionContext, s string) (keybase1.SocialAssertion, bool) ", "output": "{\n\turl, err := ParseAssertionURL(ctx, s, true)\n\tif err != nil || !url.IsRemote() {\n\t\treturn keybase1.SocialAssertion{}, false\n\t}\n\treturn keybase1.SocialAssertion{\n\t\tUser: url.GetValue(),\n\t\tService: keybase1.SocialAssertionService(url.GetKey()),\n\t}, true\n}"} {"input": "package parser\n\nimport \"bytes\"\n\n\ntype DropBehavior int\n\n\nconst (\n\tDropDefault DropBehavior = iota\n\tDropRestrict\n\tDropCascade\n)\n\nvar dropBehaviorName = [...]string{\n\tDropDefault: \"\",\n\tDropRestrict: \"RESTRICT\",\n\tDropCascade: \"CASCADE\",\n}\n\nfunc (d DropBehavior) String() string {\n\treturn dropBehaviorName[d]\n}\n\n\ntype DropDatabase struct {\n\tName Name\n\tIfExists bool\n}\n\n\n\n\n\ntype DropIndex struct {\n\tIndexList TableNameWithIndexList\n\tIfExists bool\n\tDropBehavior DropBehavior\n}\n\n\nfunc (node *DropIndex) Format(buf *bytes.Buffer, f FmtFlags) {\n\tbuf.WriteString(\"DROP INDEX \")\n\tif node.IfExists {\n\t\tbuf.WriteString(\"IF EXISTS \")\n\t}\n\tFormatNode(buf, f, node.IndexList)\n\tif node.DropBehavior != DropDefault {\n\t\tbuf.WriteByte(' ')\n\t\tbuf.WriteString(node.DropBehavior.String())\n\t}\n}\n\n\ntype DropTable struct {\n\tNames QualifiedNames\n\tIfExists bool\n\tDropBehavior DropBehavior\n}\n\n\nfunc (node *DropTable) Format(buf *bytes.Buffer, f FmtFlags) {\n\tbuf.WriteString(\"DROP TABLE \")\n\tif node.IfExists {\n\t\tbuf.WriteString(\"IF EXISTS \")\n\t}\n\tFormatNode(buf, f, node.Names)\n\tif node.DropBehavior != DropDefault {\n\t\tbuf.WriteByte(' ')\n\t\tbuf.WriteString(node.DropBehavior.String())\n\t}\n}\n\nfunc (node *DropDatabase) Format(buf *bytes.Buffer, f FmtFlags) ", "output": "{\n\tbuf.WriteString(\"DROP DATABASE \")\n\tif node.IfExists {\n\t\tbuf.WriteString(\"IF EXISTS \")\n\t}\n\tFormatNode(buf, f, node.Name)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/antizealot1337/multihost\"\n)\n\nfunc main() {\n\tfilename := flag.String(\"file\", \"\",\n\t\t\"The file name that contains the routes.\")\n\n\tcheckDir := flag.Bool(\"check\", false, \"Will check the path\")\n\n\tflag.Parse()\n\n\tif *filename == \"\" {\n\t\tfmt.Println(\"Expected filename.\")\n\t\tflag.PrintDefaults()\n\t\tos.Exit(-1)\n\t} \n\n\tfile, err := os.Open(*filename)\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(-1)\n\t} \n\n\thostWidth, pathWidth := 20, 20\n\n\troutes := multihost.ReadRoutes(file)\n\n\tif err := file.Close(); err != nil {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(-1)\n\t} \n\n\tfor host, path := range routes {\n\t\tif hostLen := len(host); hostLen > hostWidth {\n\t\t\thostWidth = hostLen + 2\n\t\t} \n\n\t\tif pathLen := len(path); pathLen > pathWidth {\n\t\t\tpathWidth = pathLen + 2\n\t\t} \n\t} \n\n\tfmtStr := fmt.Sprintf(\"%%-%ds %%-%ds\", hostWidth, pathWidth)\n\n\tfmt.Printf(fmtStr, \"Host\", \"Path\")\n\n\tfmt.Println()\n\n\tfor host, path := range routes {\n\t\tfmt.Printf(fmtStr, host, path)\n\n\t\tif *checkDir {\n\t\t\tfmt.Printf(\" (%s)\", checkStatus(path))\n\t\t} \n\n\t\tfmt.Println()\n\t} \n} \n\n\n\nfunc checkStatus(path string) string ", "output": "{\n\tif info, err := os.Stat(path); err != nil {\n\t\treturn \"Does not exist\"\n\t} else if !info.IsDir() {\n\t\treturn \"Not a directory\"\n\t} \n\treturn \"OK\"\n}"} {"input": "package storage\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\tmgo \"github.com/ilius/mgo\"\n\t\"github.com/ilius/mgo/bson\"\n)\n\n\n\nfunc EnsureIndexWithTTL(db mgo.Database, collection string, index mgo.Index) error {\n\terr := db.C(collection).EnsureIndex(index)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"already exists with different options\") {\n\t\t\treturn ModifyIndexTTL(db, collection, index)\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc ModifyIndexTTL(db mgo.Database, collection string, index mgo.Index) error ", "output": "{\n\tkeyInfo, err := mgo.ParseIndexKey(index.Key)\n\tif err != nil {\n\t\treturn err\n\t}\n\texpireAfterSeconds := int(index.ExpireAfter / time.Second)\n\tfmt.Printf(\n\t\t\"Updating TTL on collection %s to expireAfterSeconds=%d\\n\",\n\t\tcollection,\n\t\texpireAfterSeconds,\n\t)\n\terr = db.Run(bson.D{\n\t\t{\"collMod\", collection},\n\t\t{\"index\", bson.M{\n\t\t\t\"keyPattern\": keyInfo.Key,\n\t\t\t\"expireAfterSeconds\": expireAfterSeconds,\n\t\t}},\n\t}, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package vfs\n\nimport (\n\t\"path\"\n\n\tgofig \"github.com/akutz/gofig/types\"\n\n\t\"github.com/rexray/rexray/libstorage/api/context\"\n\t\"github.com/rexray/rexray/libstorage/api/registry\"\n\t\"github.com/rexray/rexray/libstorage/api/types\"\n)\n\nconst (\n\tName = \"vfs\"\n)\n\nfunc init() {\n\tregistry.RegisterConfigReg(\n\t\t\"VFS\",\n\t\tfunc(ctx types.Context, r gofig.ConfigRegistration) {\n\t\t\tvfsRoot := path.Join(context.MustPathConfig(ctx).Lib, \"vfs\")\n\t\t\tr.Key(\n\t\t\t\tgofig.String,\n\t\t\t\t\"\",\n\t\t\t\tvfsRoot,\n\t\t\t\t\"\",\n\t\t\t\t\"vfs.root\")\n\t\t})\n}\n\n\nfunc RootDir(config gofig.Config) string {\n\treturn config.GetString(\"vfs.root\")\n}\n\n\nfunc DeviceFilePath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"dev\")\n}\n\n\nfunc VolumesDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"vol\")\n}\n\n\n\n\nfunc SnapshotsDirPath(config gofig.Config) string ", "output": "{\n\treturn path.Join(RootDir(config), \"snap\")\n}"} {"input": "package conn\n\nimport (\n\t\"log\"\n\t\"time\"\n\n\t\"net/http\"\n\n\t\"github.com/garyburd/redigo/redis\"\n\t\"github.com/jmoiron/sqlx\"\n\t_ \"github.com/lib/pq\"\n\t\"google.golang.org/api/googleapi/transport\"\n\t\"google.golang.org/api/vision/v1\"\n\t\"googlemaps.github.io/maps\"\n)\n\nfunc DialPostgres(postgresURL string) (db *sqlx.DB) {\n\tvar err error\n\n\tdb, err = sqlx.Open(\"postgres\", postgresURL)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}\n\nfunc DialRedis(server string) *redis.Pool {\n\treturn &redis.Pool{\n\t\tMaxActive: 15,\n\t\tWait: true,\n\t\tMaxIdle: 3,\n\t\tIdleTimeout: 240 * time.Second,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.DialURL(server)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif _, err := c.Do(\"PING\"); err != nil {\n\t\t\t\tc.Close()\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, nil\n\t\t},\n\t\tTestOnBorrow: func(c redis.Conn, t time.Time) error {\n\t\t\tif time.Since(t) < time.Minute {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t_, err := c.Do(\"PING\")\n\t\t\treturn err\n\t\t},\n\t}\n}\n\n\n\nfunc DialGoogleServices(apiKey string) (*vision.Service, *maps.Client, error) ", "output": "{\n\tvar err error\n\n\tclient := &http.Client{\n\t\tTransport: &transport.APIKey{Key: apiKey},\n\t}\n\tvisionService, err := vision.New(client)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tmapsClient, err := maps.NewClient(maps.WithAPIKey(apiKey))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn visionService, mapsClient, nil\n}"} {"input": "package HeatersController\n\nimport (\n\t\"errors\"\n\n\t\"github.com/stianeikeland/go-rpio\"\n)\n\nvar heaters [3]rpio.Pin\n\nfunc init() {\n\trpio.Open()\n\n\theaters[0] = rpio.Pin(26)\n\theaters[1] = rpio.Pin(20)\n\theaters[2] = rpio.Pin(21)\n\n\theaters[0].Output()\n\theaters[1].Output()\n\theaters[2].Output()\n\n\theaters[0].High()\n\theaters[1].High()\n\theaters[2].High()\n}\n\n\nfunc SetNumberOfWorkingHeaters(num int) error {\n\tif num == 0 {\n\t\theaters[0].High()\n\t\theaters[1].High()\n\t\theaters[2].High()\n\t} else if num == 1 {\n\t\theaters[0].Low()\n\t\theaters[1].High()\n\t\theaters[2].High()\n\t} else if num == 2 {\n\t\theaters[0].Low()\n\t\theaters[1].Low()\n\t\theaters[2].High()\n\t} else if num == 3 {\n\t\theaters[0].Low()\n\t\theaters[1].Low()\n\t\theaters[2].Low()\n\t} else {\n\t\treturn errors.New(\"The num argument should be between 0 and 3 inclusive\")\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc TurnOff(heaterID int) {\n\theaters[heaterID-1].High()\n}\n\n\nfunc GetNumberOfWorkingHeaters() int {\n\tresult := 0\n\tif heaters[0].Read() == rpio.Low {\n\t\tresult++\n\t}\n\n\tif heaters[1].Read() == rpio.Low {\n\t\tresult++\n\t}\n\n\tif heaters[2].Read() == rpio.Low {\n\t\tresult++\n\t}\n\n\treturn result\n}\n\nfunc TurnOn(heaterID int) ", "output": "{\n\theaters[heaterID-1].Low()\n}"} {"input": "package midi\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype TimeSignature struct {\n\tNumerator uint8\n\tDenominator uint8\n\tClocksPerTick uint8\n\tThirtySecondNotesPerQuarter uint8\n}\n\n\nfunc (ts *TimeSignature) Denum() int {\n\treturn int(math.Exp2(float64(ts.Denominator)))\n}\n\n\n\nfunc (ts *TimeSignature) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%d/%d - %d clocks per tick - %d\", ts.Numerator, ts.Denum(), ts.ClocksPerTick, ts.ThirtySecondNotesPerQuarter)\n}"} {"input": "package itertools\n\nimport (\n\t\"reflect\"\n)\n\ntype Pair struct {\n\tFirst interface{}\n\tSecond interface{}\n}\n\nfunc unpack(pairVal, ptr interface{}) {\n\tptrVal := reflect.ValueOf(ptr)\n\tptrElem := ptrVal.Elem()\n\tptrElem.Set(reflect.ValueOf(pairVal))\n\tptr = ptrElem.Interface()\n}\n\n\n\nfunc PairUnPack(pair Pair, first, second interface{}) ", "output": "{\n\tunpack(pair.First, first)\n\tunpack(pair.Second, second)\n}"} {"input": "package mp\n\ntype MP struct {\n\t*Server\n\t*Client\n\tCorpClient *Client\n}\n\n\n\nfunc New(id, appID, appSecret, token, aesKey string, urlPrefix ...string) *MP ", "output": "{\n\tclient := NewClient(appID, appSecret, true)\n\tserver := NewServer(token, aesKey, urlPrefix...)\n\tserver.SetClient(client)\n\tserver.SetID(id)\n\tserver.SetAppID(appID)\n\treturn &MP{\n\t\tServer: server,\n\t\tClient: client,\n\t}\n}"} {"input": "package mmap\n\nimport \"sync\"\n\ntype tbl struct {\n\tm map[int64][]byte \n\tl sync.RWMutex\n}\n\nfunc newTbl() *tbl {\n\treturn &tbl{m: make(map[int64][]byte)}\n}\n\nfunc (t *tbl) Get(idx int64, f func() ([]byte, error)) (b []byte, err error) {\n\tt.l.RLock()\n\tb, ok := t.m[idx]\n\tt.l.RUnlock()\n\n\tif ok {\n\t\treturn\n\t}\n\n\tt.l.Lock()\n\tdefer t.l.Unlock()\n\n\tb, ok = t.m[idx]\n\tif ok {\n\t\treturn\n\t}\n\n\tb, err = f()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tt.m[idx] = b\n\treturn\n}\n\n\n\nfunc (t *tbl) Values() (res [][]byte) ", "output": "{\n\tt.l.RLock()\n\tfor _, v := range t.m {\n\t\tres = append(res, v)\n\t}\n\tt.l.RUnlock()\n\treturn\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/clcert/mercury/platform/io\"\n\t\"github.com/clcert/mercury/platform/params\"\n\t\"github.com/spf13/cobra\"\n)\n\nconst (\n\tDEFAULT_READER = \"text-reader\"\n\tDEFAULT_WRITER = \"text-writer\"\n)\n\ntype ApplicationParams struct {\n\tReaderParams io.ReaderParams\n\tWriterParams io.WriterParams\n\n\tLogFile string\n\tThreads uint32\n}\n\nfunc (a *ApplicationParams) SetFlagsOptions(command *cobra.Command) {\n\ta.ReaderParams.SetFlagsOptions(command)\n\ta.WriterParams.SetFlagsOptions(command)\n\n\tcommand.PersistentFlags().StringVar(&a.LogFile, \"log-file\", \"mercury.log\", \"Log file name.\")\n\tcommand.PersistentFlags().Uint32Var(&a.Threads, \"threads\", 1, \"Number of threads.\")\n}\n\n\n\nfunc (a *ApplicationParams) Validate() (bool, error) ", "output": "{\n\tif valid, err := a.ReaderParams.Validate(); !valid {\n\t\treturn valid, err\n\t}\n\n\tif valid, err := a.WriterParams.Validate(); !valid {\n\t\treturn valid, err\n\t}\n\n\tif valid, err := params.ValidThreads(a.Threads); !valid {\n\t\treturn valid, err\n\t}\n\n\treturn true, nil\n}"} {"input": "package main\n\nimport \"strings\"\n\ntype code_section interface {\n\tCode() bool\n}\n\ntype para string\n\nfunc (para) Code() bool {\n\treturn false\n}\n\ntype code string\n\nfunc (code) Code() bool {\n\treturn true\n}\n\ntype Article struct {\n\tTitle string\n\tIntro []para\n\tGoCode, ReflectCode []code_section\n\tUses, Tags []string\n\tslug string\n}\n\n\n\ntype Articles []*Article\n\nfunc (a *Articles) Add(ao *Article) {\n\t*a = append(*a, ao)\n}\n\nfunc (a Articles) Len() int {\n\treturn len(a)\n}\n\nfunc (a Articles) Swap(i, j int) {\n\ta[j], a[i] = a[i], a[j]\n}\n\nfunc (a Articles) Less(i, j int) bool {\n\treturn a[i].Title < a[j].Title\n}\n\nfunc (a *Article) Slug() string ", "output": "{\n\tif a.slug == \"\" {\n\t\ta.slug = strings.ToLower(strings.Replace(a.Title, \" \", \"-\", -1))\n\t}\n\treturn a.slug\n}"} {"input": "package validator\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\nfunc IsNull(str string) bool {\n\treturn len(str) == 0\n}\n\nfunc IsWord(str string, params ...int) bool {\n\tif IsNull(str) {\n\t\treturn false\n\t}\n\treturn rxWord.MatchString(str)\n}\n\nfunc IsTime(str string, format string) bool {\n\t_, err := time.Parse(format, str)\n\treturn err == nil\n}\n\nfunc IsDate(str string, format ...string) bool {\n\n\tif len(format) == 0 {\n\n\t\tif len(strings.Split(str, \"/\")) > 1 {\n\t\t\treturn IsTime(str, \"2006/01/02\")\n\t\t}\n\n\t\tif len(strings.Split(str, \"-\")) > 1 {\n\t\t\treturn IsTime(str, \"2006-01-02\")\n\t\t}\n\n\t\treturn false\n\t}\n\n\treturn IsTime(str, format[0])\n}\n\nfunc IsEmpty(str string) bool {\n\treturn len(strings.TrimSpace(str)) == 0\n}\n\n\n\nfunc IsURI(str string) bool {\n\trelation := false\n\tfor idx, val := range str {\n\t\tif val == '.' {\n\t\t\trelation = true\n\t\t\tcontinue\n\t\t}\n\t\tif val == '/' || val == '\\\\' {\n\t\t\tif idx < len(str)-1 {\n\t\t\t\tif str[idx+1] == '.' {\n\t\t\t\t\trelation = true\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif relation && (val != '/' && val != '\\\\') {\n\t\t\treturn false\n\t\t}\n\t\treturn IsRequestURI(str[idx:])\n\t}\n\treturn false\n}\n\nfunc IsMobilePhone(str string) bool {\n\tif IsEmpty(str) {\n\t\treturn false\n\t}\n\treturn rxMobolePhone.MatchString(str)\n}\n\nfunc IsRequestURI(rawurl string) bool ", "output": "{\n\t_, err := url.ParseRequestURI(rawurl)\n\treturn err == nil\n}"} {"input": "package aggregation\n\nimport \"github.com/m3db/m3/src/x/pool\"\n\n\ntype TypesAlloc func() Types\n\n\ntype TypesPool interface {\n\tInit(alloc TypesAlloc)\n\n\tGet() Types\n\n\tPut(value Types)\n}\n\ntype typesPool struct {\n\tpool pool.ObjectPool\n}\n\n\nfunc NewTypesPool(opts pool.ObjectPoolOptions) TypesPool {\n\treturn &typesPool{pool: pool.NewObjectPool(opts)}\n}\n\nfunc (p *typesPool) Init(alloc TypesAlloc) {\n\tp.pool.Init(func() interface{} {\n\t\treturn alloc()\n\t})\n}\n\nfunc (p *typesPool) Get() Types {\n\treturn p.pool.Get().(Types)\n}\n\n\n\nfunc (p *typesPool) Put(value Types) ", "output": "{\n\tp.pool.Put(value[:0])\n}"} {"input": "package util\n\nimport (\n\tauthorizationapi \"k8s.io/kubernetes/pkg/apis/authorization\"\n\t\"k8s.io/kubernetes/pkg/auth/authorizer\"\n\t\"k8s.io/kubernetes/pkg/auth/user\"\n)\n\n\n\n\n\nfunc NonResourceAttributesFrom(user user.Info, in authorizationapi.NonResourceAttributes) authorizer.AttributesRecord {\n\treturn authorizer.AttributesRecord{\n\t\tUser: user,\n\t\tResourceRequest: false,\n\t\tPath: in.Path,\n\t}\n}\n\nfunc ResourceAttributesFrom(user user.Info, in authorizationapi.ResourceAttributes) authorizer.AttributesRecord ", "output": "{\n\treturn authorizer.AttributesRecord{\n\t\tUser: user,\n\t\tVerb: in.Verb,\n\t\tNamespace: in.Namespace,\n\t\tAPIGroup: in.Group,\n\t\tResource: in.Resource,\n\t\tResourceRequest: true,\n\t}\n}"} {"input": "package testutil\n\nimport (\n\t\"testing\"\n\n\tci \"gx/ipfs/QmP1DfoUjiWH2ZBo1PBH6FupdBucbDepx3HpWmEY6JMUpY/go-libp2p-crypto\"\n\tma \"gx/ipfs/QmcyqRMCAXVtYPS4DiBrA7sezL9rRGfW8Ctx7cywL4TXJj/go-multiaddr\"\n\tpeer \"gx/ipfs/QmdS9KpbDyPrieswibZhkod1oXqRwZJrUPzxCofAMWpFGq/go-libp2p-peer\"\n)\n\ntype Identity interface {\n\tAddress() ma.Multiaddr\n\tID() peer.ID\n\tPrivateKey() ci.PrivKey\n\tPublicKey() ci.PubKey\n}\n\n\n\nfunc RandIdentity() (Identity, error) {\n\tp, err := RandPeerNetParams()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &identity{*p}, nil\n}\n\nfunc RandIdentityOrFatal(t *testing.T) Identity {\n\tp, err := RandPeerNetParams()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn &identity{*p}\n}\n\n\ntype identity struct {\n\tPeerNetParams\n}\n\nfunc (p *identity) ID() peer.ID {\n\treturn p.PeerNetParams.ID\n}\n\n\n\nfunc (p *identity) PrivateKey() ci.PrivKey {\n\treturn p.PrivKey\n}\n\nfunc (p *identity) PublicKey() ci.PubKey {\n\treturn p.PubKey\n}\n\nfunc (p *identity) Address() ma.Multiaddr ", "output": "{\n\treturn p.Addr\n}"} {"input": "package main\n\nimport (\n\t\"code.google.com/p/go.crypto/ssh/terminal\"\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc clearscr() {\n\tfmt.Printf(\"%c[2J%c[0;0H\", 27, 27)\n}\n\ntype uterm struct {\n\ts *terminal.State\n\tt *terminal.Terminal\n}\n\n\n\nfunc (u *uterm) Restore() {\n\tterminal.Restore(0, u.s)\n}\n\nfunc (u *uterm) ReadLine() (string, error) {\n\treturn u.t.ReadLine()\n}\n\nfunc newTerm() Term ", "output": "{\n\tu := new(uterm)\n\tvar err error\n\tu.s, err = terminal.MakeRaw(0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tu.t = terminal.NewTerminal(os.Stdin, \"lixian >> \")\n\treturn u\n}"} {"input": "package cmd\n\nimport \"github.com/spf13/cobra\"\n\n\nfunc InitializeCommands() *cobra.Command {\n\trootCmd := createRootCommand()\n\n\trootCmd.AddCommand(\n\t\tcreateLoadCommand(),\n\t\tcreateServeCommand(),\n\t\tcreateStartCommand(),\n\t\tcreateStopCommand(),\n\t)\n\n\treturn rootCmd\n}\n\n\n\nfunc createRootCommand() *cobra.Command ", "output": "{\n\tcmd := &cobra.Command{\n\t\tUse: \"langd\",\n\t\tShort: \"langd exercises a client/server configuration as a single binary\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmd.HelpFunc()(cmd, args)\n\t\t},\n\t}\n\n\treturn cmd\n}"} {"input": "package main\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\n\n\nfunc TestOutputFileName(t *testing.T) ", "output": "{\n\ta := assert.New(t)\n\ta.Equal(\"input.gen.go\", outputFileName(\"input.go\"))\n\ta.Equal(\"input.txt.gen.go\", outputFileName(\"input.txt\"))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc printSearchResult(a []int, key int) {\n\tfmt.Println(\"Binary Search:\")\n\tindex := binSearch(a, key)\n\tif index == -1 {\n\t\tfmt.Println(\"Search Space: \", a)\n\t\tfmt.Println(key, \"was not found\")\n\t} else {\n\t\tfmt.Println(\"Search Space: \", a)\n\t\tfmt.Println(\"a[\", index, \"] = \", a[index])\n\t}\n\tfmt.Println(\"\")\n}\n\nfunc main() {\n\ta := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n\tprintSearchResult(a, 9)\n\tprintSearchResult(a, 2)\n\tprintSearchResult(a, 15)\n\tprintSearchResult(a, 5)\n\tprintSearchResult(a, 10)\n}\n\nfunc binSearch(searchspace []int, key int) int ", "output": "{\n\tvar min, max int\n\tmin = searchspace[0]\n\tmax = searchspace[len(searchspace)-1]\n\tfor {\n\t\tif max < min {\n\t\t\treturn -1\n\t\t}\n\t\tm := (min + max) / 2\n\t\tif searchspace[m] < key {\n\t\t\tmin = m + 1\n\t\t} else if searchspace[m] > key {\n\t\t\tmax = m - 1\n\t\t} else {\n\t\t\treturn m\n\t\t}\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"github.com/mattermost/platform/model\"\n)\n\ntype LogoutProvider struct {\n}\n\nconst (\n\tCMD_LOGOUT = \"logout\"\n)\n\nfunc init() {\n\tRegisterCommandProvider(&LogoutProvider{})\n}\n\nfunc (me *LogoutProvider) GetTrigger() string {\n\treturn CMD_LOGOUT\n}\n\n\n\nfunc (me *LogoutProvider) DoCommand(c *Context, channelId string, message string) *model.CommandResponse {\n\treturn &model.CommandResponse{GotoLocation: \"/logout\", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: c.T(\"api.command_logout.success_message\")}\n}\n\nfunc (me *LogoutProvider) GetCommand(c *Context) *model.Command ", "output": "{\n\treturn &model.Command{\n\t\tTrigger: CMD_LOGOUT,\n\t\tAutoComplete: true,\n\t\tAutoCompleteDesc: c.T(\"api.command_logout.desc\"),\n\t\tAutoCompleteHint: \"\",\n\t\tDisplayName: c.T(\"api.command_logout.name\"),\n\t}\n}"} {"input": "package csl\nimport (\n\t\"github.com/abieberbach/goplane/extra/logging\"\n\t\"fmt\"\n)\n\ntype CslPackage struct {\n\tName string\n\tDependencies []string\n\tBaseDirectory string\n\tAircrafts []*CslAircraft\n\tValid bool\n}\n\n\n\nfunc (self *CslPackage) checkDependencies(allPackages *CslPackages) {\n\tfor _, dep := range self.Dependencies {\n\t\t_, found := allPackages.GetPackage(dep)\n\t\tif !found {\n\t\t\tself.invalidate(\"missing dependency package \\\"%v\\\"\", dep)\n\t\t}\n\t}\n}\n\nfunc (self *CslPackage) checkAircrafts(allPackages *CslPackages) {\n\tfor _, currentAircraft := range self.Aircrafts {\n\t\tok,validationMessage := currentAircraft.validate(allPackages)\n\t\tif !ok {\n\t\t\tself.invalidate(validationMessage)\n\t\t}\n\t}\n}\n\nfunc (self *CslPackage) invalidate(msg string, params... interface{}) {\n\tlogging.Warningf(\"invalid package \\\"%v\\\", reason: %v [base directory: %v]\", self.Name, fmt.Sprintf(msg, params...),self.BaseDirectory)\n\tself.Valid = false\n}\n\nfunc (self *CslPackage) validate(allPackages *CslPackages) ", "output": "{\n\tself.checkDependencies(allPackages)\n\tif !self.Valid {\n\t\treturn\n\t}\n\tself.checkAircrafts(allPackages)\n\tif !self.Valid {\n\t\treturn\n\t}\n\tlogging.Infof(\"package \\\"%v\\\" is valid\", self.Name)\n}"} {"input": "package mixed\n\nimport (\n\t\"net\"\n\t\"net/url\"\n\n\t\"github.com/nadoo/glider/pkg/log\"\n\t\"github.com/nadoo/glider/proxy\"\n\t\"github.com/nadoo/glider/proxy/http\"\n\t\"github.com/nadoo/glider/proxy/socks5\"\n)\n\n\ntype Mixed struct {\n\tproxy proxy.Proxy\n\taddr string\n\n\thttpServer *http.HTTP\n\tsocks5Server *socks5.Socks5\n}\n\nfunc init() {\n\tproxy.RegisterServer(\"mixed\", NewMixedServer)\n}\n\n\n\n\n\nfunc NewMixedServer(s string, p proxy.Proxy) (proxy.Server, error) {\n\treturn NewMixed(s, p)\n}\n\n\nfunc (m *Mixed) ListenAndServe() {\n\tgo m.socks5Server.ListenAndServeUDP()\n\n\tl, err := net.Listen(\"tcp\", m.addr)\n\tif err != nil {\n\t\tlog.Fatalf(\"[mixed] failed to listen on %s: %v\", m.addr, err)\n\t\treturn\n\t}\n\n\tlog.F(\"[mixed] http & socks5 server listening TCP on %s\", m.addr)\n\n\tfor {\n\t\tc, err := l.Accept()\n\t\tif err != nil {\n\t\t\tlog.F(\"[mixed] failed to accept: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgo m.Serve(c)\n\t}\n}\n\n\nfunc (m *Mixed) Serve(c net.Conn) {\n\tconn := proxy.NewConn(c)\n\tif head, err := conn.Peek(1); err == nil {\n\t\tif head[0] == socks5.Version {\n\t\t\tm.socks5Server.Serve(conn)\n\t\t\treturn\n\t\t}\n\t}\n\tm.httpServer.Serve(conn)\n}\n\nfunc NewMixed(s string, p proxy.Proxy) (*Mixed, error) ", "output": "{\n\tu, err := url.Parse(s)\n\tif err != nil {\n\t\tlog.F(\"parse err: %s\", err)\n\t\treturn nil, err\n\t}\n\n\tm := &Mixed{\n\t\tproxy: p,\n\t\taddr: u.Host,\n\t}\n\n\tm.httpServer, err = http.NewHTTP(s, nil, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm.socks5Server, err = socks5.NewSocks5(s, nil, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn m, nil\n}"} {"input": "package primitives\n\nimport (\n\t\"encoding/xml\"\n\t\"github.com/plandem/ooxml/ml\"\n)\n\n\ntype FontFamilyType ml.PropertyInt\n\n\nfunc (t *FontFamilyType) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\treturn (*ml.PropertyInt)(t).MarshalXML(e, start)\n}\n\n\n\n\nfunc (t *FontFamilyType) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error ", "output": "{\n\treturn (*ml.PropertyInt)(t).UnmarshalXML(d, start)\n}"} {"input": "package main\n\n\n\nfunc main() {\n\tprintln(canArrange([]int{1, 2, 3, 4, 5, 10, 6, 7, 8, 9}, 5))\n\tprintln(canArrange([]int{1, 2, 3, 4, 5, 6}, 7))\n\tprintln(canArrange([]int{-10, 10}, 2))\n\tprintln(canArrange([]int{1, 2, 3, 4, 5, 6}, 10))\n\tprintln(canArrange([]int{-1, 1, -2, 2, -3, 3, -4, 4}, 3))\n\tprintln(canArrange([]int{-4, -7, 5, 2, 9, 1, 10, 4, -8, -3}, 3))\n}\n\nfunc canArrange(arr []int, k int) bool ", "output": "{\n\tmodCnt := make(map[int]int)\n\n\tfor _, num := range arr {\n\t\tmod := num % k\n\t\tif modCnt[k-mod] > 0 {\n\t\t\tmodCnt[k-mod]--\n\t\t} else if modCnt[-k-mod] > 0 {\n\t\t\tmodCnt[-k-mod]--\n\t\t} else if modCnt[-mod] > 0 {\n\t\t\tmodCnt[-mod]--\n\t\t} else {\n\t\t\tmodCnt[mod]++\n\t\t}\n\t}\n\n\tif modCnt[0]%2 != 0 {\n\t\treturn false\n\t}\n\n\tfor mod, cnt := range modCnt {\n\t\tif mod != 0 && cnt > 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}"} {"input": "package testing\n\nimport (\n\t\"k8s.io/kubernetes/pkg/util/sysctl\"\n\t\"os\"\n)\n\n\ntype fake struct {\n\tSettings map[string]int\n}\n\nfunc NewFake() *fake {\n\treturn &fake{\n\t\tSettings: make(map[string]int),\n\t}\n}\n\n\n\n\n\nfunc (m *fake) SetSysctl(sysctl string, newVal int) error {\n\tm.Settings[sysctl] = newVal\n\treturn nil\n}\n\nvar _ = sysctl.Interface(&fake{})\n\nfunc (m *fake) GetSysctl(sysctl string) (int, error) ", "output": "{\n\tv, found := m.Settings[sysctl]\n\tif !found {\n\t\treturn -1, os.ErrNotExist\n\t}\n\treturn v, nil\n}"} {"input": "package v1\n\nimport (\n\tv1 \"github.com/openshift/api/oauth/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype OAuthAuthorizeTokenLister interface {\n\tList(selector labels.Selector) (ret []*v1.OAuthAuthorizeToken, err error)\n\tGet(name string) (*v1.OAuthAuthorizeToken, error)\n\tOAuthAuthorizeTokenListerExpansion\n}\n\n\ntype oAuthAuthorizeTokenLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewOAuthAuthorizeTokenLister(indexer cache.Indexer) OAuthAuthorizeTokenLister {\n\treturn &oAuthAuthorizeTokenLister{indexer: indexer}\n}\n\n\nfunc (s *oAuthAuthorizeTokenLister) List(selector labels.Selector) (ret []*v1.OAuthAuthorizeToken, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.OAuthAuthorizeToken))\n\t})\n\treturn ret, err\n}\n\n\n\n\nfunc (s *oAuthAuthorizeTokenLister) Get(name string) (*v1.OAuthAuthorizeToken, error) ", "output": "{\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"oauthauthorizetoken\"), name)\n\t}\n\treturn obj.(*v1.OAuthAuthorizeToken), nil\n}"} {"input": "package leetcode\n\nconst MAX_INT32 = 1<<31 - 1\nconst MIN_INT32 = -1 << 31\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\nfunc maxInt(a, b int) int {\n\tif a < b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}\n\nfunc minInt(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}\n\n\n\nfunc qsortInt(nums []int) []int {\n\tif len(nums) <= 1 {\n\t\treturn nums\n\t}\n\n\thead, tail := 0, len(nums)-1\n\tidx, mid := 1, nums[0]\n\tfor head < tail {\n\t\tif nums[idx] > mid {\n\t\t\tnums[idx], nums[tail] = nums[tail], nums[idx]\n\t\t\ttail--\n\t\t} else {\n\t\t\tnums[idx], nums[head] = nums[head], nums[idx]\n\t\t\thead++\n\t\t\tidx++\n\t\t}\n\t}\n\tnums[head] = mid\n\tqsortInt(nums[:head])\n\tqsortInt(nums[head+1:])\n\treturn nums\n}\n\ntype Stack struct {\n\tdata []rune\n}\n\nfunc (s *Stack) push(data rune) {\n\ts.data = append(s.data, data)\n}\n\nfunc (s *Stack) pop() rune {\n\tif len(s.data) == 0 {\n\t\treturn 0\n\t}\n\tret := s.data[len(s.data)-1]\n\ts.data = s.data[:len(s.data)-1]\n\treturn ret\n}\n\nfunc (s Stack) empty() bool {\n\treturn len(s.data) == 0\n}\n\nfunc absInt(num int) int ", "output": "{\n\tif num > 0 {\n\t\treturn num\n\t} else {\n\t\treturn -num\n\t}\n}"} {"input": "package expvar\n\nimport (\n\t\"expvar\"\n\t\"runtime\"\n\t\"sync\"\n\n\t\"github.com/mholt/caddy\"\n\t\"github.com/mholt/caddy/caddyhttp/httpserver\"\n)\n\n\n\n\nfunc setup(c *caddy.Controller) error {\n\tresource, err := expVarParse(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpublishExtraVars()\n\n\tev := ExpVar{Resource: resource}\n\n\thttpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {\n\t\tev.Next = next\n\t\treturn ev\n\t})\n\n\treturn nil\n}\n\nfunc expVarParse(c *caddy.Controller) (Resource, error) {\n\tvar resource Resource\n\tvar err error\n\n\tfor c.Next() {\n\t\targs := c.RemainingArgs()\n\t\tswitch len(args) {\n\t\tcase 0:\n\t\t\tresource = Resource(defaultExpvarPath)\n\t\tcase 1:\n\t\t\tresource = Resource(args[0])\n\t\tdefault:\n\t\t\treturn resource, c.ArgErr()\n\t\t}\n\t}\n\n\treturn resource, err\n}\n\nfunc publishExtraVars() {\n\tpublishOnce.Do(func() {\n\t\texpvar.Publish(\"Goroutines\", expvar.Func(func() interface{} {\n\t\t\treturn runtime.NumGoroutine()\n\t\t}))\n\t})\n}\n\nvar publishOnce sync.Once \nvar defaultExpvarPath = \"/debug/vars\"\n\nfunc init() ", "output": "{\n\tcaddy.RegisterPlugin(\"expvar\", caddy.Plugin{\n\t\tServerType: \"http\",\n\t\tAction: setup,\n\t})\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realInternetGateway InternetGateway\n\n\nfunc (o *InternetGateway) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realInternetGateway\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = InternetGateway(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &InternetGateway{}\n\n\nfunc (o *InternetGateway) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\n\nfunc (o *InternetGateway) SetLifecycle(lifecycle fi.Lifecycle) {\n\to.Lifecycle = &lifecycle\n}\n\nvar _ fi.HasName = &InternetGateway{}\n\n\nfunc (o *InternetGateway) GetName() *string {\n\treturn o.Name\n}\n\n\n\n\n\nfunc (o *InternetGateway) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *InternetGateway) SetName(name string) ", "output": "{\n\to.Name = &name\n}"} {"input": "package v1\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\ntype staticAsset struct {\n\tasset string\n\tlogger logrus.FieldLogger\n}\n\nvar _ http.Handler = staticAsset{}\n\n\n\nfunc (h staticAsset) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tlogger := h.logger.WithFields(logrus.Fields{\n\t\t\"request.remote_addr\": r.RemoteAddr,\n\t\t\"request.method\": r.Method,\n\t\t\"request.uri\": r.RequestURI,\n\t})\n\n\tif r.Method != \"GET\" {\n\t\tw.WriteHeader(405)\n\t\tw.Write([]byte(\"method not allowed\"))\n\n\t\tlogger.WithField(\"response.status\", 405).Warn(\"method not allowed\")\n\n\t\treturn\n\t}\n\n\thttp.ServeFile(w, r, h.asset)\n\n\tlogger.WithField(\"response.status\", 200).Info(\"served static asset\")\n}\n\nfunc NewStaticAsset(logger logrus.FieldLogger, asset string) http.Handler ", "output": "{\n\treturn staticAsset{\n\t\tasset: asset,\n\t\tlogger: logger,\n\t}\n}"} {"input": "package kms\n\nimport (\n\t\"encoding/base64\"\n\t\"fmt\"\n\n\t\"github.com/VirgilSecurity/virgil-sdk-go/v6/crypto/wrapper/phe\"\n\t\"github.com/urfave/cli/v2\"\n\n\t\"github.com/VirgilSecurity/virgil-cli/utils\"\n)\n\n\n\n\n\n\nfunc GenerateKMSPrivateKey() ([]byte, error) {\n\tkmsClient := phe.NewUokmsClient()\n\tif err := kmsClient.SetupDefaults(); err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\treturn kmsClient.GenerateClientPrivateKey()\n}\n\nfunc printKMSPrivateKey() error {\n\tkey, err := GenerateKMSPrivateKey()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(base64.StdEncoding.EncodeToString(key))\n\treturn nil\n}\n\nfunc KMSPrivateKey() *cli.Command ", "output": "{\n\treturn &cli.Command{\n\t\tName: \"client-private\",\n\t\tAliases: []string{\"pk\"},\n\t\tUsage: \"Generate a new KMS Client Private key\",\n\t\tAction: func(context *cli.Context) error {\n\t\t\terr := printKMSPrivateKey()\n\t\t\tif err != nil {\n\t\t\t\treturn utils.CliExit(err)\n\t\t\t}\n\t\t\treturn err\n\t\t},\n\t}\n}"} {"input": "package packer\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\n\nvar GitCommit string\n\n\nconst Version = \"0.5.3\"\n\n\n\n\nconst VersionPrerelease = \"dev\"\n\ntype versionCommand byte\n\nfunc (versionCommand) Help() string {\n\treturn `usage: packer version\n\nOutputs the version of Packer that is running. There are no additional\ncommand-line flags for this command.`\n}\n\n\n\nfunc (versionCommand) Synopsis() string {\n\treturn \"print Packer version\"\n}\n\n\n\n\nfunc VersionString() string {\n\tvar versionString bytes.Buffer\n\tfmt.Fprintf(&versionString, \"Packer v%s\", Version)\n\tif VersionPrerelease != \"\" {\n\t\tfmt.Fprintf(&versionString, \".%s\", VersionPrerelease)\n\n\t\tif GitCommit != \"\" {\n\t\t\tfmt.Fprintf(&versionString, \" (%s)\", GitCommit)\n\t\t}\n\t}\n\n\treturn versionString.String()\n}\n\nfunc (versionCommand) Run(env Environment, args []string) int ", "output": "{\n\tenv.Ui().Machine(\"version\", Version)\n\tenv.Ui().Machine(\"version-prelease\", VersionPrerelease)\n\tenv.Ui().Machine(\"version-commit\", GitCommit)\n\n\tenv.Ui().Say(VersionString())\n\treturn 0\n}"} {"input": "package C_test\n\nimport (\n\t. \"github.com/onsi/gomega\"\n\t. \"gx/ipfs/QmNuLxhqRhfimRZeLttPe6Sa44MNwuHAdaFFa9TDuNZUmf/ginkgo\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestC(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"C Suite\")\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promhttp\"\n)\n\nfunc main() {\n\tdojoRestarts, err := startCounterVec(\"dojo_restarts_total\", \"Number of restarts\", []string{\"service\"})\n\tif err != nil {\n\t\tlog.Printf(\"start: %v\", err)\n\t\treturn\n\t}\n\n\tgo startService(\"one\", dojoRestarts)\n\n\tgo startService(\"two\", dojoRestarts)\n\n\thttp.Handle(\"/metrics\", promhttp.Handler())\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\n\n\nfunc startService(name string, restarts *prometheus.CounterVec) {\n\tfor {\n\t\tdone := make(chan struct{})\n\t\tt := time.NewTimer(1 * time.Minute)\n\n\t\tgo func() {\n\t\t\t<-t.C\n\t\t\tclose(done)\n\t\t}()\n\n\t\tconst maxSleep = 1000000000\n\t\trestarts.WithLabelValues(name).Inc()\n\t\tfor {\n\t\t\trs := randomNumber(maxSleep)\n\t\t\ttime.Sleep(time.Duration(rs))\n\t\t}\n\n\t\tprintln(\"restart \" + name)\n\t}\n}\n\nfunc randomNumber(max int) int {\n\trand.Seed(time.Now().UnixNano())\n\treturn rand.Intn(max)\n}\n\nfunc startCounterVec(name, help string, labels []string) (*prometheus.CounterVec, error) ", "output": "{\n\tcv := prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tName: name,\n\t\t\tHelp: help,\n\t\t},\n\t\tlabels,\n\t)\n\n\terr := prometheus.Register(cv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cv, nil\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"os/exec\"\n)\n\nfunc panicOn(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc FileExists(name string) bool {\n\tfi, err := os.Stat(name)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif fi.IsDir() {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\n\nfunc Run(dir string, exe string, arg ...string) (stdout *bytes.Buffer, stderr *bytes.Buffer, err error) {\n\tcmd := exec.Command(exe, arg...)\n\tvar errbuf bytes.Buffer\n\tvar outbuf bytes.Buffer\n\tcmd.Dir = dir\n\tcmd.Stderr = &errbuf\n\tcmd.Stdout = &outbuf\n\terr = cmd.Run()\n\treturn &outbuf, &errbuf, err\n}\n\nfunc DirExists(name string) bool ", "output": "{\n\tfi, err := os.Stat(name)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif fi.IsDir() {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package sqltrace\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\nfunc boolToInt64(f bool) int64 {\n\tif f {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\ntype sqlTrace struct {\n\ton int64 \n\n\t*log.Logger\n}\n\nfunc newSQLTrace() *sqlTrace {\n\treturn &sqlTrace{\n\t\tLogger: log.New(os.Stdout, \"hdb \", log.Ldate|log.Ltime|log.Lshortfile),\n\t}\n}\nfunc (t *sqlTrace) On() bool { return atomic.LoadInt64(&t.on) != 0 }\nfunc (t *sqlTrace) SetOn(on bool) { atomic.StoreInt64(&t.on, boolToInt64(on)) }\n\ntype flagValue struct {\n\tt *sqlTrace\n}\n\nfunc (v flagValue) IsBoolFlag() bool { return true }\n\n\n\nfunc (v flagValue) Set(s string) error {\n\tf, err := strconv.ParseBool(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.t.SetOn(f)\n\treturn nil\n}\n\nvar tracer = newSQLTrace()\n\nfunc init() {\n\tflag.Var(&flagValue{t: tracer}, \"hdb.sqlTrace\", \"enabling hdb sql trace\")\n}\n\n\nfunc On() bool { return tracer.On() }\n\n\nfunc SetOn(on bool) { tracer.SetOn(on) }\n\n\nfunc Trace(v ...interface{}) { tracer.Print(v...) }\n\n\nfunc Tracef(format string, v ...interface{}) { tracer.Printf(format, v...) }\n\n\nfunc Traceln(v ...interface{}) { tracer.Println(v...) }\n\nfunc (v flagValue) String() string ", "output": "{\n\tif v.t == nil {\n\t\treturn \"\"\n\t}\n\treturn strconv.FormatBool(v.t.On())\n}"} {"input": "package sqlwire\n\nimport \"strconv\"\n\n\n\nfunc (d Datum) String() string ", "output": "{\n\tif d.BoolVal != nil {\n\t\tif *d.BoolVal {\n\t\t\treturn \"true\"\n\t\t}\n\t\treturn \"false\"\n\t}\n\tif d.IntVal != nil {\n\t\treturn strconv.FormatInt(*d.IntVal, 10)\n\t}\n\tif d.FloatVal != nil {\n\t\treturn strconv.FormatFloat(*d.FloatVal, 'g', -1, 64)\n\t}\n\tif d.BytesVal != nil {\n\t\treturn string(d.BytesVal)\n\t}\n\tif d.StringVal != nil {\n\t\treturn *d.StringVal\n\t}\n\treturn \"NULL\"\n}"} {"input": "package label\n\n\n\n\nfunc InitLabels(mcsdir string, options []string) (string, string, error) {\n\treturn \"\", \"\", nil\n}\n\nfunc FormatMountLabel(src string, mountLabel string) string {\n\treturn src\n}\n\nfunc SetProcessLabel(processLabel string) error {\n\treturn nil\n}\n\nfunc SetFileLabel(path string, fileLabel string) error {\n\treturn nil\n}\n\nfunc SetFileCreateLabel(fileLabel string) error {\n\treturn nil\n}\n\nfunc Relabel(path string, fileLabel string, relabel string) error {\n\treturn nil\n}\n\nfunc GetPidLabel(pid int) (string, error) {\n\treturn \"\", nil\n}\n\nfunc Init() {\n}\n\nfunc ReserveLabel(label string) error {\n\treturn nil\n}\n\nfunc UnreserveLabel(label string) error {\n\treturn nil\n}\n\n\n\n\n\n\n\nfunc DisableSecOpt() []string {\n\treturn nil\n}\n\nfunc DupSecOpt(src string) []string ", "output": "{\n\treturn nil\n}"} {"input": "package bits_test\n\nimport (\n\t\"github.com/twmb/bits\"\n\t\"testing\"\n)\n\nfunc TestSet(t *testing.T) {\n\tfor i := 0; i < 256; i++ {\n\t\tif int(bits.SetU32(uint32(i))) != bits.Hamming(i, 0) {\n\t\t\tt.Errorf(\"Error in set: wanted %v for %v, got %v\",\n\t\t\t\tbits.Hamming(i, 0), i, bits.SetU32(uint32(i)))\n\t\t}\n\t}\n}\n\nfunc BenchmarkSetTable(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetTable(i)\n\t}\n}\n\nfunc BenchmarkSetU32(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetU32(uint32(i))\n\t}\n}\nfunc BenchmarkSetU64(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetU64(uint64(i))\n\t}\n}\n\nfunc BenchmarkSetKernighan(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetKernighan(uint(i))\n\t}\n}"} {"input": "package gcetasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realAddress Address\n\n\nfunc (o *Address) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realAddress\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = Address(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &Address{}\n\n\n\n\n\nfunc (o *Address) SetLifecycle(lifecycle fi.Lifecycle) {\n\to.Lifecycle = &lifecycle\n}\n\nvar _ fi.HasName = &Address{}\n\n\nfunc (o *Address) GetName() *string {\n\treturn o.Name\n}\n\n\nfunc (o *Address) SetName(name string) {\n\to.Name = &name\n}\n\n\nfunc (o *Address) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *Address) GetLifecycle() *fi.Lifecycle ", "output": "{\n\treturn o.Lifecycle\n}"} {"input": "package utils\n\nimport (\n\t\"net\"\n\t\"fmt\"\n\t\"strings\"\n\t\"errors\"\n)\n\ntype Local int\n\nfunc (this *Local) GetMac() {\n\tinterfaces,err := net.Interfaces()\n\tCheckError(err)\n\tfor _,inter :=range interfaces {\n\t\tmac := inter.HardwareAddr\n\t\tname := inter.Name\n\t\tfmt.Printf(\"MAC=%s NAME=%s \\n\",mac,name)\n\t}\n}\n\nfunc (this *Local) GetIps() []string {\n\tresult := []string{}\n\tinterfaces,err := net.Interfaces()\n\tCheckError(err)\n\tfor _,inter :=range interfaces {\n\t\tip,err := inter.Addrs()\n\t\tCheckError(err)\n\t\tfor _,x := range ip {\n\t\t\tresult = append(result,x.String())\n\t\t}\n\t}\n\treturn result\n}\n\n\n\nfunc (this *Local) GiveOneIp() (string,error) ", "output": "{\n\trs := this.GetIps()\n\tfor _,data := range rs {\n\t\tif strings.Contains(data,\"24\") {\n\t\t\treturn strings.Split(data,\"/\")[0],nil\n\t\t}\n\t}\n\treturn \"\",errors.New(\"没有255.255.255.0网段的IP设置\")\n}"} {"input": "package adt\n\ntype Stack struct {\n\ttop *Element\n\tsize int\n}\n \ntype Element struct {\n\tvalue interface{} \n\tnext *Element\n}\n\n\nfunc NewStack() *Stack {\n\treturn new(Stack)\n\n}\n\n\nfunc (s *Stack) Len() int {\n\treturn s.size\n}\n\n\nfunc (s *Stack) IsEmpty() bool {\n\treturn s.Len()==0\n}\n\n\n\n \n\n\nfunc (s *Stack) Pop() (value interface{}) {\n\tif s.size > 0 {\n\t\tvalue, s.top = s.top.value, s.top.next\n\t\ts.size--\n\t\treturn\n\t}\n\treturn nil\n}\n\nfunc (s *Stack) Push(value interface{}) ", "output": "{\n\ts.top = &Element{value, s.top}\n\ts.size++\n}"} {"input": "package iso20022\n\n\ntype GenericIdentification7 struct {\n\n\tIssuer *Max8Text `xml:\"Issr\"`\n\n\tInformation *Max35Text `xml:\"Inf\"`\n}\n\nfunc (g *GenericIdentification7) SetIssuer(value string) {\n\tg.Issuer = (*Max8Text)(&value)\n}\n\n\n\nfunc (g *GenericIdentification7) SetInformation(value string) ", "output": "{\n\tg.Information = (*Max35Text)(&value)\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"github.com/go-swagger/go-swagger/errors\"\n\t\"github.com/go-swagger/go-swagger/strfmt\"\n\t\"github.com/go-swagger/go-swagger/swag\"\n)\n\n\ntype EmployeePageableResult struct {\n\n\tContent []Employee `json:\"content,omitempty\"`\n\n\tFirst bool `json:\"first,omitempty\"`\n\n\tLast bool `json:\"last,omitempty\"`\n\n\tNumber int32 `json:\"number,omitempty\"`\n\n\tNumberOfElements int32 `json:\"numberOfElements,omitempty\"`\n\n\tServerTime int64 `json:\"serverTime,omitempty\"`\n\n\tSize int32 `json:\"size,omitempty\"`\n\n\tTotalElements int32 `json:\"totalElements,omitempty\"`\n\n\tTotalPages int32 `json:\"totalPages,omitempty\"`\n}\n\n\nfunc (m *EmployeePageableResult) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateContent(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\nfunc (m *EmployeePageableResult) validateContent(formats strfmt.Registry) error ", "output": "{\n\n\tif swag.IsZero(m.Content) { \n\t\treturn nil\n\t}\n\n\tfor i := 0; i < len(m.Content); i++ {\n\n\t\tif err := m.Content[i].Validate(formats); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nfunc f1(i int) {\n\tfor j := i - 1; j >= 0; j-- { \n\t}\n}\n\nfunc f2(i int, s string) {\n\tfor j := i + 1; j < len(s); j-- { \n\t}\n}\n\nfunc f3(s string) {\n\tfor i, l := 0, len(s); i > l; i++ { \n\t}\n}\n\nfunc f4(lower int, a []int) {\n\tfor i := lower - 1; i >= 0; i-- { \n\t\ta[i] = 0\n\t}\n}\n\nfunc f5(upper int, a []int) {\n\tfor i := upper + 1; i < len(a); i-- { \n\t\ta[i] = 0\n\t}\n}\n\n\n\nfunc f7(a []int) {\n\tfor i := uint(len(a)) - 1; i < uint(len(a)); i-- { \n\t\ta[i] = 0\n\t}\n}\n\nfunc main() {}\n\nfunc f6(upper uint, a []int) ", "output": "{\n\tfor i := upper + 1; i < uint(len(a)); i-- { \n\t\ta[i] = 0\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/gdamore/mangos\"\n\t\"github.com/gdamore/mangos/protocol/pull\"\n\t\"github.com/gdamore/mangos/protocol/push\"\n\t\"github.com/gdamore/mangos/transport/ipc\"\n\t\"github.com/gdamore/mangos/transport/tcp\"\n\t\"os\"\n)\n\nfunc die(format string, v ...interface{}) {\n\tfmt.Fprintln(os.Stderr, fmt.Sprintf(format, v...))\n\tos.Exit(1)\n}\n\nfunc node0(url string) {\n\tvar sock mangos.Socket\n\tvar err error\n\tvar msg []byte\n\tif sock, err = pull.NewSocket(); err != nil {\n\t\tdie(\"can't get new pull socket: %s\", err)\n\t}\n\tsock.AddTransport(ipc.NewTransport())\n\tsock.AddTransport(tcp.NewTransport())\n\tif err = sock.Listen(url); err != nil {\n\t\tdie(\"can't listen on pull socket: %s\", err.Error())\n\t}\n\tfor {\n\t\tmsg, err = sock.Recv()\n\t\tfmt.Printf(\"NODE0: RECEIVED \\\"%s\\\"\\n\", msg)\n\t}\n}\n\n\n\nfunc main() {\n\tif len(os.Args) > 2 && os.Args[1] == \"node0\" {\n\t\tnode0(os.Args[2])\n\t\tos.Exit(0)\n\t}\n\tif len(os.Args) > 3 && os.Args[1] == \"node1\" {\n\t\tnode1(os.Args[2], os.Args[3])\n\t\tos.Exit(0)\n\t}\n\tfmt.Fprintf(os.Stderr,\n\t\t\"Usage: pipeline node0|node1 ...\\n\")\n\tos.Exit(1)\n}\n\nfunc node1(url string, msg string) ", "output": "{\n\tvar sock mangos.Socket\n\tvar err error\n\n\tif sock, err = push.NewSocket(); err != nil {\n\t\tdie(\"can't get new push socket: %s\", err.Error())\n\t}\n\tsock.AddTransport(ipc.NewTransport())\n\tsock.AddTransport(tcp.NewTransport())\n\tif err = sock.Dial(url); err != nil {\n\t\tdie(\"can't dial on push socket: %s\", err.Error())\n\t}\n\tfmt.Printf(\"NODE1: SENDING \\\"%s\\\"\\n\", msg)\n\tif err = sock.Send([]byte(msg)); err != nil {\n\t\tdie(\"can't send message on push socket: %s\", err.Error())\n\t}\n\tsock.Close()\n}"} {"input": "package files\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewGetFilesFileidentifierParams() *GetFilesFileidentifierParams {\n\tvar ()\n\treturn &GetFilesFileidentifierParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\nfunc NewGetFilesFileidentifierParamsWithTimeout(timeout time.Duration) *GetFilesFileidentifierParams {\n\tvar ()\n\treturn &GetFilesFileidentifierParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype GetFilesFileidentifierParams struct {\n\n\tFileidentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *GetFilesFileidentifierParams) WithFileidentifier(fileidentifier string) *GetFilesFileidentifierParams {\n\to.Fileidentifier = fileidentifier\n\treturn o\n}\n\n\n\n\nfunc (o *GetFilesFileidentifierParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error ", "output": "{\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"fileidentifier\", o.Fileidentifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package extra\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\n\n\ntype namingStrategyExtension struct {\n\tjsoniter.DummyExtension\n\ttranslate func(string) string\n}\n\nfunc (extension *namingStrategyExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) {\n\tfor _, binding := range structDescriptor.Fields {\n\t\tif unicode.IsLower(rune(binding.Field.Name()[0])) || binding.Field.Name()[0] == '_'{\n\t\t\tcontinue\n\t\t}\n\t\ttag, hastag := binding.Field.Tag().Lookup(\"json\")\n\t\tif hastag {\n\t\t\ttagParts := strings.Split(tag, \",\")\n\t\t\tif tagParts[0] == \"-\" {\n\t\t\t\tcontinue \n\t\t\t}\n\t\t\tif tagParts[0] != \"\" {\n\t\t\t\tcontinue \n\t\t\t}\n\t\t}\n\t\tbinding.ToNames = []string{extension.translate(binding.Field.Name())}\n\t\tbinding.FromNames = []string{extension.translate(binding.Field.Name())}\n\t}\n}\n\n\nfunc LowerCaseWithUnderscores(name string) string {\n\tnewName := []rune{}\n\tfor i, c := range name {\n\t\tif i == 0 {\n\t\t\tnewName = append(newName, unicode.ToLower(c))\n\t\t} else {\n\t\t\tif unicode.IsUpper(c) {\n\t\t\t\tnewName = append(newName, '_')\n\t\t\t\tnewName = append(newName, unicode.ToLower(c))\n\t\t\t} else {\n\t\t\t\tnewName = append(newName, c)\n\t\t\t}\n\t\t}\n\t}\n\treturn string(newName)\n}\n\nfunc SetNamingStrategy(translate func(string) string) ", "output": "{\n\tjsoniter.RegisterExtension(&namingStrategyExtension{jsoniter.DummyExtension{}, translate})\n}"} {"input": "package framework\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/util/wait\"\n\t\"k8s.io/apimachinery/pkg/util/yaml\"\n\t\"k8s.io/client-go/kubernetes\"\n)\n\nfunc createReplicationControllerViaYml(kubeClient kubernetes.Interface, namespace string, filepath string) error {\n\tmanifest, err := os.Open(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar rC v1.ReplicationController\n\terr = yaml.NewYAMLOrJSONDecoder(manifest, 100).Decode(&rC)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = kubeClient.CoreV1().ReplicationControllers(namespace).Create(&rC)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc deleteReplicationControllerViaYml(kubeClient kubernetes.Interface, namespace string, filepath string) error {\n\tmanifest, err := os.Open(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar rC v1.ReplicationController\n\terr = yaml.NewYAMLOrJSONDecoder(manifest, 100).Decode(&rC)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := scaleDownReplicationController(kubeClient, namespace, rC); err != nil {\n\t\treturn err\n\t}\n\n\tif err := kubeClient.CoreV1().ReplicationControllers(namespace).Delete(rC.Name, nil); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc scaleDownReplicationController(kubeClient kubernetes.Interface, namespace string, rC v1.ReplicationController) error ", "output": "{\n\t*rC.Spec.Replicas = 0\n\trCAPI := kubeClient.CoreV1().ReplicationControllers(namespace)\n\n\t_, err := kubeClient.CoreV1().ReplicationControllers(namespace).Update(&rC)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn wait.Poll(time.Second, time.Minute*5, func() (bool, error) {\n\t\tcurrentRC, err := rCAPI.Get(rC.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif currentRC.Status.Replicas == 0 {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\n\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\tpath := r.URL.Path\n\n\tif LogLevel() >= LOG_VERBOSE {\n\t\tlog.Printf(\"%v on path %v\", r.Method, path)\n\t}\n\n\tfmt.Fprintf(w, \"Hi there, I love %s!\", r.URL.Path[1:])\n}\n\nfunc ServeHttp() ", "output": "{\n\thttp.HandleFunc(\"/\", handler)\n\thttp.HandleFunc(\"/deploy\", HandleDeploy)\n\n\tport := GoployCtx.Cfg.App.Port\n\tlog.Printf(\"Webserver listening on %v...\", port)\n\terr := http.ListenAndServe(fmt.Sprintf(\":%v\", port), nil)\n\tif err != nil {\n\t\tlog.Fatal(\"ListenAndServe error: \", err)\n\t}\n}"} {"input": "package sw\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\n\t\"github.com/hyperledger/fabric/core/crypto/bccsp\"\n\t\"github.com/hyperledger/fabric/core/crypto/primitives\"\n)\n\ntype rsaPrivateKey struct {\n\tk *rsa.PrivateKey\n}\n\n\n\nfunc (k *rsaPrivateKey) Bytes() (raw []byte, err error) {\n\treturn\n}\n\n\nfunc (k *rsaPrivateKey) SKI() (ski []byte) {\n\traw := x509.MarshalPKCS1PrivateKey(k.k)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\nfunc (k *rsaPrivateKey) Symmetric() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPrivateKey) Private() bool {\n\treturn true\n}\n\n\n\nfunc (k *rsaPrivateKey) PublicKey() (bccsp.Key, error) {\n\treturn &rsaPublicKey{&k.k.PublicKey}, nil\n}\n\ntype rsaPublicKey struct {\n\tk *rsa.PublicKey\n}\n\n\n\nfunc (k *rsaPublicKey) Bytes() (raw []byte, err error) {\n\traw, err = x509.MarshalPKIXPublicKey(k.k)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed marshalling key [%s]\", err)\n\t}\n\treturn\n}\n\n\nfunc (k *rsaPublicKey) SKI() (ski []byte) {\n\traw, _ := primitives.PublicKeyToPEM(k.k, nil)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\n\n\n\n\nfunc (k *rsaPublicKey) Private() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) PublicKey() (bccsp.Key, error) {\n\treturn k, nil\n}\n\nfunc (k *rsaPublicKey) Symmetric() bool ", "output": "{\n\treturn false\n}"} {"input": "package precreator\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com/influxdata/influxdb/toml\"\n)\n\nconst (\n\tDefaultCheckInterval = 10 * time.Minute\n\n\tDefaultAdvancePeriod = 30 * time.Minute\n)\n\n\ntype Config struct {\n\tEnabled bool `toml:\"enabled\"`\n\tCheckInterval toml.Duration `toml:\"check-interval\"`\n\tAdvancePeriod toml.Duration `toml:\"advance-period\"`\n}\n\n\nfunc NewConfig() Config {\n\treturn Config{\n\t\tEnabled: true,\n\t\tCheckInterval: toml.Duration(DefaultCheckInterval),\n\t\tAdvancePeriod: toml.Duration(DefaultAdvancePeriod),\n\t}\n}\n\n\n\n\nfunc (c Config) Validate() error ", "output": "{\n\tif !c.Enabled {\n\t\treturn nil\n\t}\n\n\tif c.CheckInterval <= 0 {\n\t\treturn errors.New(\"check-interval must be positive\")\n\t}\n\tif c.AdvancePeriod <= 0 {\n\t\treturn errors.New(\"advance-period must be positive\")\n\t}\n\n\treturn nil\n}"} {"input": "package assets\n\nimport (\n\t\"fmt\"\n)\n\nconst (\n\tanalyticsScript = ``\n)\n\nfunc googleAnalytics(m *Manager, names []string, options Options) ([]*Asset, error) {\n\tif len(names) != 1 && len(names) != 2 {\n\t\treturn nil, fmt.Errorf(\"analytics requires either 1 or 2 arguments (either \\\"UA-XXXXXX-YY, mysite.com\\\" or just \\\"UA-XXXXXX-YY\\\" - without quotes in both cases\")\n\t}\n\tkey := names[0]\n\tif key == \"\" {\n\t\treturn nil, nil\n\t}\n\tvar arg string\n\tif len(names) == 2 {\n\t\targ = fmt.Sprintf(\"'%s', '%s'\", key, names[1])\n\t} else {\n\t\targ = fmt.Sprintf(\"'%s'\", key)\n\t}\n\treturn []*Asset{\n\t\t&Asset{\n\t\t\tName: \"google-analytics.js\",\n\t\t\tPosition: Bottom,\n\t\t\tHTML: fmt.Sprintf(analyticsScript, arg),\n\t\t},\n\t}, nil\n}\n\n\n\nfunc init() ", "output": "{\n\tRegister(\"analytics\", googleAnalytics)\n}"} {"input": "package srtgears\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\nconst newLine = \"\\r\\n\" \n\n\ntype writer struct {\n\tw io.Writer \n\terr error \n}\n\n\nfunc (w *writer) pr(a ...interface{}) {\n\tif w.err == nil {\n\t\t_, w.err = fmt.Fprint(w.w, a...)\n\t}\n}\n\n\n\n\n\nfunc (w *writer) prf(format string, a ...interface{}) {\n\tif w.err == nil {\n\t\t_, w.err = fmt.Fprintf(w.w, format, a...)\n\t}\n}\n\nfunc (w *writer) prn(a ...interface{}) ", "output": "{\n\tw.pr(a...)\n\tw.pr(newLine)\n}"} {"input": "package refmt\n\nimport (\n\t\"github.com/polydawn/refmt/obj\"\n\t\"github.com/polydawn/refmt/obj/atlas\"\n\t\"github.com/polydawn/refmt/shared\"\n)\n\nfunc Clone(src, dst interface{}) error {\n\treturn CloneAtlased(src, dst, atlas.MustBuild())\n}\nfunc MustClone(src, dst interface{}) {\n\tif err := Clone(src, dst); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc CloneAtlased(src, dst interface{}, atl atlas.Atlas) error {\n\treturn NewCloner(atl).Clone(src, dst)\n}\nfunc MustCloneAtlased(src, dst interface{}, atl atlas.Atlas) {\n\tif err := CloneAtlased(src, dst, atl); err != nil {\n\t\tpanic(err)\n\t}\n}\n\ntype Cloner interface {\n\tClone(src, dst interface{}) error\n}\n\nfunc NewCloner(atl atlas.Atlas) Cloner {\n\tx := &cloner{\n\t\tmarshaller: obj.NewMarshaller(atl),\n\t\tunmarshaller: obj.NewUnmarshaller(atl),\n\t}\n\tx.pump = shared.TokenPump{x.marshaller, x.unmarshaller}\n\treturn x\n}\n\ntype cloner struct {\n\tmarshaller *obj.Marshaller\n\tunmarshaller *obj.Unmarshaller\n\tpump shared.TokenPump\n}\n\n\n\nfunc (c cloner) Clone(src, dst interface{}) error ", "output": "{\n\tc.marshaller.Bind(src)\n\tc.unmarshaller.Bind(dst)\n\treturn c.pump.Run()\n}"} {"input": "package containerinstance\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" containerinstance/2021-03-01\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package module\n\nimport (\n\t\"encoding/gob\"\n\t\"fmt\"\n\t\"github.com/glennyonemitsu/reicon/system/activity\"\n\t\"net\"\n\t\"os\"\n)\n\ntype Module struct {\n\tName string\n\tActivities []*activity.Activity\n\tServerSocket *net.UnixConn\n\tSocketAddr *net.UnixAddr\n\tListener *net.UnixListener\n}\n\nfunc (m *Module) Run() {\n\tsocket_path := os.Getenv(\"REICON_SYSTEM_SOCKET\")\n\tm.SocketAddr = new(net.UnixAddr)\n\tm.SocketAddr.Name = \"unix\"\n\tm.SocketAddr.Net = socket_path\n\tm.Listener, _ = net.ListenUnix(\"unix\", m.SocketAddr)\n\tm.ListenSocket()\n\n}\n\nfunc (m *Module) ListenSocket() {\n\tfor {\n\t\tconn, err := m.Listener.AcceptUnix()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tgo m.handleUnixConnection(conn)\n\t}\n}\n\nfunc (m *Module) handleUnixConnection(conn *net.UnixConn) {\n\tvar msg string\n\tenc := gob.NewEncoder(conn)\n\tdec := gob.NewDecoder(conn)\n\tdec.Decode(&msg)\n\tenc.Encode(fmt.Sprintf(\"your message was: %s\", msg))\n}\n\n\n\nfunc (m *Module) RegisterActivity(name string) *activity.Activity {\n\ta := new(activity.Activity)\n\ta.Name = name\n\tm.Activities = append(m.Activities, a)\n\treturn a\n}\n\nfunc Create(name string) *Module {\n\tm := new(Module)\n\tm.Name = name\n\treturn m\n}\n\nfunc (m *Module) Shutdown() ", "output": "{\n\tm.ServerSocket.Close()\n}"} {"input": "package downloader\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/WhaleCoinOrg/WhaleCoin/core/types\"\n)\n\n\ntype peerDropFn func(id string)\n\n\ntype dataPack interface {\n\tPeerId() string\n\tItems() int\n\tStats() string\n}\n\n\ntype headerPack struct {\n\tpeerId string\n\theaders []*types.Header\n}\n\nfunc (p *headerPack) PeerId() string { return p.peerId }\n\nfunc (p *headerPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.headers)) }\n\n\ntype bodyPack struct {\n\tpeerId string\n\ttransactions [][]*types.Transaction\n\tuncles [][]*types.Header\n}\n\nfunc (p *bodyPack) PeerId() string { return p.peerId }\nfunc (p *bodyPack) Items() int {\n\tif len(p.transactions) <= len(p.uncles) {\n\t\treturn len(p.transactions)\n\t}\n\treturn len(p.uncles)\n}\nfunc (p *bodyPack) Stats() string { return fmt.Sprintf(\"%d:%d\", len(p.transactions), len(p.uncles)) }\n\n\ntype receiptPack struct {\n\tpeerId string\n\treceipts [][]*types.Receipt\n}\n\nfunc (p *receiptPack) PeerId() string { return p.peerId }\nfunc (p *receiptPack) Items() int { return len(p.receipts) }\nfunc (p *receiptPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.receipts)) }\n\n\ntype statePack struct {\n\tpeerId string\n\tstates [][]byte\n}\n\nfunc (p *statePack) PeerId() string { return p.peerId }\nfunc (p *statePack) Items() int { return len(p.states) }\nfunc (p *statePack) Stats() string { return fmt.Sprintf(\"%d\", len(p.states)) }\n\nfunc (p *headerPack) Items() int ", "output": "{ return len(p.headers) }"} {"input": "package redis\n\nimport (\n\t\"github.com/fagongzi/goetty\"\n)\n\ntype redisDecoder struct {\n}\n\n\nfunc NewRedisDecoder() goetty.Decoder {\n\treturn &redisDecoder{}\n}\n\n\nfunc (decoder *redisDecoder) Decode(in *goetty.ByteBuf) (bool, interface{}, error) {\n\tcomplete, cmd, err := ReadCommand(in)\n\tif err != nil {\n\t\treturn true, nil, err\n\t}\n\n\tif !complete {\n\t\treturn false, nil, nil\n\t}\n\n\treturn true, cmd, nil\n}\n\ntype redisReplyDecoder struct {\n}\n\n\nfunc NewRedisReplyDecoder() goetty.Decoder {\n\treturn &redisReplyDecoder{}\n}\n\n\n\n\nfunc (decoder *redisReplyDecoder) Decode(in *goetty.ByteBuf) (bool, interface{}, error) ", "output": "{\n\tcomplete, cmd, err := readCommandReply(in)\n\tif err != nil {\n\t\treturn true, nil, err\n\t}\n\n\tif !complete {\n\t\treturn false, nil, nil\n\t}\n\n\treturn true, cmd, nil\n}"} {"input": "package commands\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype basicHandler struct {\n\thandler func(args ...string) (string, error)\n\thelp func(args ...string) string\n}\n\nvar _ CommandHandler = (*basicHandler)(nil)\n\n\n\nfunc (h *basicHandler) Help(argv ...string) string {\n\treturn h.help(argv...)\n}\n\nfunc Static(response, help string) CommandHandler {\n\treturn &basicHandler{\n\t\thandler: func(argv ...string) (string, error) {\n\t\t\treturn response, nil\n\t\t},\n\t\thelp: func(argv ...string) string {\n\t\t\treturn fmt.Sprintf(\"`!%s` - %s\", strings.Join(argv, \" \"), help)\n\t\t},\n\t}\n}\n\nfunc Simple(responder func(...string) (string, error), help string) CommandHandler {\n\treturn &basicHandler{\n\t\thandler: func(argv ...string) (string, error) {\n\t\t\treturn responder(argv...)\n\t\t},\n\t\thelp: func(argv ...string) string {\n\t\t\treturn fmt.Sprintf(\"`!%s` - %s\", strings.Join(argv, \" \"), help)\n\t\t},\n\t}\n}\n\nfunc (h *basicHandler) Handle(argv ...string) (string, error) ", "output": "{\n\treturn h.handler(argv...)\n}"} {"input": "package mocks\n\nimport common \"github.com/hyperledger/fabric-protos-go/common\"\nimport errors \"github.com/hyperledger/fabric/common/errors\"\nimport mock \"github.com/stretchr/testify/mock\"\nimport peer \"github.com/hyperledger/fabric-protos-go/peer\"\n\n\ntype StateBasedValidator struct {\n\tmock.Mock\n}\n\n\nfunc (_m *StateBasedValidator) PostValidate(cc string, blockNum uint64, txNum uint64, err error) {\n\t_m.Called(cc, blockNum, txNum, err)\n}\n\n\n\n\n\nfunc (_m *StateBasedValidator) Validate(cc string, blockNum uint64, txNum uint64, rwset []byte, prp []byte, ep []byte, endorsements []*peer.Endorsement) errors.TxValidationError {\n\tret := _m.Called(cc, blockNum, txNum, rwset, prp, ep, endorsements)\n\n\tvar r0 errors.TxValidationError\n\tif rf, ok := ret.Get(0).(func(string, uint64, uint64, []byte, []byte, []byte, []*peer.Endorsement) errors.TxValidationError); ok {\n\t\tr0 = rf(cc, blockNum, txNum, rwset, prp, ep, endorsements)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(errors.TxValidationError)\n\t\t}\n\t}\n\n\treturn r0\n}\n\nfunc (_m *StateBasedValidator) PreValidate(txNum uint64, block *common.Block) ", "output": "{\n\t_m.Called(txNum, block)\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/spf13/viper\"\n)\n\nvar DefaultConfPath string\n\n\n\nfunc initConfig() error {\n\tviper.SetDefault(\"bridges.type\", \"linux\")\n\tviper.SetDefault(\"bridges.name\", \"br0\")\n\tviper.SetConfigFile(DefaultConfPath)\n\tviper.SetConfigType(\"toml\")\n\tviper.AutomaticEnv()\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tif viper.ConfigFileUsed() == DefaultConfPath && os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc main() {\n\tif err := initConfig(); err != nil {\n\t\tlog.WithError(err).Fatalf(\"Failed to load config %s\", viper.ConfigFileUsed())\n\t}\n\tconfig := viper.GetViper()\n\tifname := os.Args[1]\n\n\tswitch config.GetString(\"bridges.type\") {\n\tcase \"linux\":\n\t\trunCmd(\"ip\", []string{\"link\", \"set\", \"dev\", ifname, \"master\", config.GetString(\"bridges.name\")})\n\tcase \"ovs\":\n\t\trunCmd(\"ovs-vsctl\", []string{\"add-port\", config.GetString(\"bridges.name\"), ifname})\n\tdefault:\n\t\tlog.Fatalf(\"Unknown bridge type\")\n\t}\n\trunCmd(\"ip\", []string{\"link\", \"set\", ifname, \"up\"})\n}\n\nfunc runCmd(cmd string, args []string) ", "output": "{\n\tc := exec.Command(cmd, args...)\n\tif err := c.Run(); err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"cmd\": cmd,\n\t\t\t\"args\": args,\n\t\t}).Fatal(\"Failed to execute command\")\n\t}\n}"} {"input": "package datacatalog\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteCustomPropertyRequest struct {\n\n\tCatalogId *string `mandatory:\"true\" contributesTo:\"path\" name:\"catalogId\"`\n\n\tNamespaceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"namespaceId\"`\n\n\tCustomPropertyKey *string `mandatory:\"true\" contributesTo:\"path\" name:\"customPropertyKey\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteCustomPropertyRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteCustomPropertyRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request DeleteCustomPropertyRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request DeleteCustomPropertyRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteCustomPropertyResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response DeleteCustomPropertyResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response DeleteCustomPropertyResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/hyperledger/fabric/common/channelconfig\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n)\n\n\ntype Orderer struct {\n\tConsensusTypeVal string\n\tBatchSizeVal *ab.BatchSize\n\tBatchTimeoutVal time.Duration\n\tKafkaBrokersVal []string\n\tMaxChannelsCountVal uint64\n\tOrganizationsVal map[string]channelconfig.Org\n\tCapabilitiesVal channelconfig.OrdererCapabilities\n}\n\n\n\n\n\nfunc (scm *Orderer) BatchSize() *ab.BatchSize {\n\treturn scm.BatchSizeVal\n}\n\n\nfunc (scm *Orderer) BatchTimeout() time.Duration {\n\treturn scm.BatchTimeoutVal\n}\n\n\nfunc (scm *Orderer) KafkaBrokers() []string {\n\treturn scm.KafkaBrokersVal\n}\n\n\nfunc (scm *Orderer) MaxChannelsCount() uint64 {\n\treturn scm.MaxChannelsCountVal\n}\n\n\nfunc (scm *Orderer) Organizations() map[string]channelconfig.Org {\n\treturn scm.OrganizationsVal\n}\n\n\nfunc (scm *Orderer) Capabilities() channelconfig.OrdererCapabilities {\n\treturn scm.CapabilitiesVal\n}\n\n\ntype OrdererCapabilities struct {\n\tSupportedErr error\n\n\tSetChannelModPolicyDuringCreateVal bool\n\n\tResubmissionVal bool\n}\n\n\nfunc (oc *OrdererCapabilities) Supported() error {\n\treturn oc.SupportedErr\n}\n\n\nfunc (oc *OrdererCapabilities) SetChannelModPolicyDuringCreate() bool {\n\treturn oc.SetChannelModPolicyDuringCreateVal\n}\n\n\nfunc (oc *OrdererCapabilities) Resubmission() bool {\n\treturn oc.ResubmissionVal\n}\n\nfunc (scm *Orderer) ConsensusType() string ", "output": "{\n\treturn scm.ConsensusTypeVal\n}"} {"input": "package egoscale\n\nimport \"fmt\"\n\n\nfunc (ListAntiAffinityGroups) Response() interface{} {\n\treturn new(ListAntiAffinityGroupsResponse)\n}\n\n\nfunc (ls *ListAntiAffinityGroups) ListRequest() (ListCommand, error) {\n\tif ls == nil {\n\t\treturn nil, fmt.Errorf(\"%T cannot be nil\", ls)\n\t}\n\treturn ls, nil\n}\n\n\nfunc (ls *ListAntiAffinityGroups) SetPage(page int) {\n\tls.Page = page\n}\n\n\n\n\n\nfunc (ListAntiAffinityGroups) Each(resp interface{}, callback IterateItemFunc) {\n\titems, ok := resp.(*ListAntiAffinityGroupsResponse)\n\tif !ok {\n\t\tcallback(nil, fmt.Errorf(\"wrong type, ListAntiAffinityGroupsResponse was expected, got %T\", resp))\n\t\treturn\n\t}\n\n\tfor i := range items.AntiAffinityGroup {\n\t\tif !callback(&items.AntiAffinityGroup[i], nil) {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (ls *ListAntiAffinityGroups) SetPageSize(pageSize int) ", "output": "{\n\tls.PageSize = pageSize\n}"} {"input": "package noise\n\nimport (\n\t\"errors\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (s *secureSession) encrypt(out, plaintext []byte) ([]byte, error) {\n\tif s.enc == nil {\n\t\treturn nil, errors.New(\"cannot encrypt, handshake incomplete\")\n\t}\n\treturn s.enc.Encrypt(out, nil, plaintext)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (s *secureSession) decrypt(out, ciphertext []byte) ([]byte, error) ", "output": "{\n\tif s.dec == nil {\n\t\treturn nil, errors.New(\"cannot decrypt, handshake incomplete\")\n\t}\n\treturn s.dec.Decrypt(out, nil, ciphertext)\n}"} {"input": "package armpowerbiprivatelinks\n\nimport (\n\t\"context\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azcore\"\n\t\"net/http\"\n)\n\n\ntype PrivateEndpointConnectionsClientDeletePoller struct {\n\tpt *azcore.Poller\n}\n\n\nfunc (p *PrivateEndpointConnectionsClientDeletePoller) Done() bool {\n\treturn p.pt.Done()\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *PrivateEndpointConnectionsClientDeletePoller) Poll(ctx context.Context) (*http.Response, error) {\n\treturn p.pt.Poll(ctx)\n}\n\n\n\n\nfunc (p *PrivateEndpointConnectionsClientDeletePoller) FinalResponse(ctx context.Context) (PrivateEndpointConnectionsClientDeleteResponse, error) {\n\trespType := PrivateEndpointConnectionsClientDeleteResponse{}\n\tresp, err := p.pt.FinalResponse(ctx, nil)\n\tif err != nil {\n\t\treturn PrivateEndpointConnectionsClientDeleteResponse{}, err\n\t}\n\trespType.RawResponse = resp\n\treturn respType, nil\n}\n\n\n\nfunc (p *PrivateEndpointConnectionsClientDeletePoller) ResumeToken() (string, error) {\n\treturn p.pt.ResumeToken()\n}\n\n\ntype PrivateLinkServiceResourceOperationResultsClientGetPoller struct {\n\tpt *azcore.Poller\n}\n\n\nfunc (p *PrivateLinkServiceResourceOperationResultsClientGetPoller) Done() bool {\n\treturn p.pt.Done()\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *PrivateLinkServiceResourceOperationResultsClientGetPoller) Poll(ctx context.Context) (*http.Response, error) {\n\treturn p.pt.Poll(ctx)\n}\n\n\n\n\n\n\n\n\nfunc (p *PrivateLinkServiceResourceOperationResultsClientGetPoller) ResumeToken() (string, error) {\n\treturn p.pt.ResumeToken()\n}\n\nfunc (p *PrivateLinkServiceResourceOperationResultsClientGetPoller) FinalResponse(ctx context.Context) (PrivateLinkServiceResourceOperationResultsClientGetResponse, error) ", "output": "{\n\trespType := PrivateLinkServiceResourceOperationResultsClientGetResponse{}\n\tresp, err := p.pt.FinalResponse(ctx, &respType.AsyncOperationDetail)\n\tif err != nil {\n\t\treturn PrivateLinkServiceResourceOperationResultsClientGetResponse{}, err\n\t}\n\trespType.RawResponse = resp\n\treturn respType, nil\n}"} {"input": "package udt\n\n\n\nimport (\n\t\"io\"\n)\n\ntype ack2Packet struct {\n\th header\n\tackSeqNo uint32 \n}\n\nfunc (p *ack2Packet) socketId() (sockId uint32) {\n\treturn p.h.dstSockId\n}\n\n\n\nfunc (p *ack2Packet) writeTo(w io.Writer) (err error) {\n\tif err := p.h.writeTo(w, ack2, p.ackSeqNo); err != nil {\n\t\treturn err\n\t}\n\treturn\n}\n\nfunc (p *ack2Packet) readFrom(r io.Reader) (err error) {\n\tp.ackSeqNo, err = p.h.readFrom(r)\n\treturn\n}\n\nfunc (p *ack2Packet) sendTime() (ts uint32) ", "output": "{\n\treturn p.h.ts\n}"} {"input": "package iam\n\nimport \"github.com/adobe-platform/porter/cfn\"\n\n\n\n\n\ntype (\n\tRole struct {\n\t\tcfn.Resource\n\n\t\tProperties struct {\n\t\t\tAssumeRolePolicyDocument map[string]interface{} `json:\"AssumeRolePolicyDocument,omitempty\"`\n\t\t\tManagedPolicyArns []string `json:\"ManagedPolicyArns,omitempty\"`\n\t\t\tPath string `json:\"Path,omitempty\"`\n\t\t\tPolicies []Policy `json:\"Policies,omitempty\"`\n\t\t} `json:\"Properties\"`\n\t}\n\n\tPolicy struct {\n\t\tPolicyDocument map[string]interface{} `json:\"PolicyDocument,omitempty\"`\n\t\tPolicyName string `json:\"PolicyName,omitempty\"`\n\t}\n)\n\n\n\nfunc NewRole() Role ", "output": "{\n\treturn Role{\n\t\tResource: cfn.Resource{\n\t\t\tType: \"AWS::IAM::Role\",\n\t\t},\n\t}\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n)\n\n\nconst DeleteDeploymentOKCode int = 200\n\n\ntype DeleteDeploymentOK struct {\n}\n\n\nfunc NewDeleteDeploymentOK() *DeleteDeploymentOK {\n\treturn &DeleteDeploymentOK{}\n}\n\n\nfunc (o *DeleteDeploymentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n}\n\n\nconst DeleteDeploymentUnauthorizedCode int = 401\n\n\ntype DeleteDeploymentUnauthorized struct {\n\tWWWAuthenticate string `json:\"WWW_Authenticate\"`\n}\n\n\nfunc NewDeleteDeploymentUnauthorized() *DeleteDeploymentUnauthorized {\n\treturn &DeleteDeploymentUnauthorized{}\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) WithWWWAuthenticate(wWWAuthenticate string) *DeleteDeploymentUnauthorized {\n\to.WWWAuthenticate = wWWAuthenticate\n\treturn o\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) SetWWWAuthenticate(wWWAuthenticate string) {\n\to.WWWAuthenticate = wWWAuthenticate\n}\n\n\n\n\n\nconst DeleteDeploymentNotFoundCode int = 404\n\n\ntype DeleteDeploymentNotFound struct {\n}\n\n\nfunc NewDeleteDeploymentNotFound() *DeleteDeploymentNotFound {\n\treturn &DeleteDeploymentNotFound{}\n}\n\n\nfunc (o *DeleteDeploymentNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(404)\n}\n\n\nconst DeleteDeploymentInternalServerErrorCode int = 500\n\n\ntype DeleteDeploymentInternalServerError struct {\n}\n\n\nfunc NewDeleteDeploymentInternalServerError() *DeleteDeploymentInternalServerError {\n\treturn &DeleteDeploymentInternalServerError{}\n}\n\n\nfunc (o *DeleteDeploymentInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(500)\n}\n\nfunc (o *DeleteDeploymentUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\n\twWWAuthenticate := o.WWWAuthenticate\n\tif wWWAuthenticate != \"\" {\n\t\trw.Header().Set(\"WWW_Authenticate\", wWWAuthenticate)\n\t}\n\n\trw.WriteHeader(401)\n}"} {"input": "package goku\n\nimport (\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype TestReader struct{}\n\nfunc (self TestReader) Read() ([]Message, error) {\n\ttime.Sleep(10 * time.Millisecond)\n\treturn []Message{\"Hello\"}, nil\n}\n\ntype TestWriter struct {\n\tmsgs []Message\n}\n\nfunc (self *TestWriter) Write(msgs []Message) error {\n\tfor _, msg := range msgs {\n\t\tself.msgs = append(self.msgs, msg)\n\t}\n\treturn nil\n}\n\nfunc TestNewQueueSetupReader(t *testing.T) {\n\tt.Parallel()\n\n\tq := NewQueue(&TestReader{}, nil)\n\n\tselect {\n\tcase <-q.Sender():\n\t\tbreak\n\tcase <-time.After(100 * time.Millisecond):\n\t\tt.Fatal(\"Timeout expired\")\n\t}\n}\n\n\n\nfunc TestNewQueueSetsupWriter(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\twriter := &TestWriter{}\n\tq := NewQueue(nil, writer)\n\n\tq.Receiver() <- \"Hello\"\n\tq.Receiver() <- \"World\"\n\n\truntime.Gosched()\n\n\tif count := len(writer.msgs); count != 2 {\n\t\tt.Errorf(\"messages written == %d, want 2\", count)\n\t}\n}"} {"input": "package s0132\n\nimport (\n\t\"github.com/peterstace/project-euler/number\"\n)\n\nfunc Answer() interface{} {\n\treturn SumPrimeFactors(40, 10e9)\n}\n\nfunc SumPrimeFactors(numFactors int, k int) int {\n\tvar factorsFound int\n\tvar sum int\n\tnthPrime := number.MakeSieveBackedNthPrime()\n\tfor i := 0; factorsFound < numFactors; i++ {\n\t\tp := nthPrime(i)\n\t\tif repunit(k, p) == 0 {\n\t\t\tfactorsFound++\n\t\t\tsum += p\n\t\t}\n\t}\n\treturn sum\n}\n\n\nfunc repunit(k, m int) int {\n\tif k == 1 {\n\t\treturn 1\n\t}\n\tif k%2 == 0 {\n\t\thalf := repunit(k/2, m)\n\t\treturn (tenPow(k/2, m)*half + half) % m\n\t} else {\n\t\treturn (10*repunit(k-1, m) + 1) % m\n\t}\n}\n\n\n\n\nfunc tenPow(k, m int) int ", "output": "{\n\tif k == 0 {\n\t\treturn 1\n\t}\n\tif k%2 == 0 {\n\t\thalf := tenPow(k/2, m)\n\t\treturn (half * half) % m\n\t} else {\n\t\treturn (10 * tenPow(k-1, m)) % m\n\t}\n}"} {"input": "package config\n\nimport \"github.com/yorirou/gotorrent/util\"\n\ntype ClientConfig struct {\n\tPeerID string\n\tPort uint64\n}\n\n\n\nfunc NewClientConfig() *ClientConfig ", "output": "{\n\tcc := new(ClientConfig)\n\tcc.PeerID = util.GeneratePeerID()\n\treturn cc\n}"} {"input": "package arrayUtility\n\nfunc RemoveDuplicatesUnordered(elements []string) []string {\n\tencountered := map[string]bool{}\n\n\tfor v := range elements {\n\t\tencountered[elements[v]] = true\n\t}\n\n\tresult := []string{}\n\tfor key := range encountered {\n\t\tresult = append(result, key)\n\t}\n\treturn result\n}\n\n\n\nfunc Contain(needle string, haystack []string) bool ", "output": "{\n\tfor _, v := range haystack {\n\t\tif v == needle {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package repodelete\n\nvar Usage = []string{\"rt rdel \"}\n\nfunc GetDescription() string {\n\treturn \"Permanently delete repositories with all of their content from Artifactory.\"\n}\n\n\n\nfunc GetArguments() string ", "output": "{\n\treturn `\trepository pattern\n\t\tSpecifies the repositories that should be removed. You can use wildcards to specify multiple repositories.`\n}"} {"input": "package main\n\nimport (\n\t\"html/template\"\n\t\"log\"\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestTemplate(t *testing.T) ", "output": "{\n\ttemp, _ := template.ParseFiles(\"temp/postlist.html\")\n\terr := temp.Execute(os.Stdout, \"\")\n\tif err != nil {\n\t\tlog.Printf(\"execute err : %v\", err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"io\"\n\t\"log\"\n)\n\ntype proxy struct {\n\ttransport *http.Transport\n\taddr string\n}\n\nfunc newProxy(addr string) *proxy {\n\tp := &proxy{addr: addr}\n\tp.transport = &http.Transport{\n\t\tDial: p.dial,\n\t}\n\treturn p\n}\n\n\n\nfunc (p *proxy) proxyPass(w http.ResponseWriter, r *http.Request) {\n\thost, _, _ := net.SplitHostPort(r.RemoteAddr)\n\tr.Header.Add(\"X-Forwarded-For\", host)\n\tr.URL.Scheme = \"http\"\n\tr.URL.Host = r.Host\n\tresp, err := p.transport.RoundTrip(r)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tw.WriteHeader(http.StatusBadGateway)\n\t\tw.Write([]byte(\"

502 Bad Gateway

\"))\n\t\treturn\n\t}\n\theader := w.Header()\n\tfor k, v := range resp.Header {\n\t\tfor _, v1 := range v {\n\t\t\theader.Add(k, v1)\n\t\t}\n\t}\n\tw.WriteHeader(resp.StatusCode)\n\tio.Copy(w, resp.Body)\n\tresp.Body.Close()\n}\n\nfunc (p *proxy) dial(network string, addr string) (conn net.Conn, err error) ", "output": "{\n\treturn net.Dial(\"tcp\", p.addr)\n}"} {"input": "package network\n\nimport (\n\t\"github.com/containerd/containerd/oci\"\n\tspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n)\n\n\n\ntype host struct {\n}\n\nfunc (h *host) New() (Namespace, error) {\n\treturn &hostNS{}, nil\n}\n\ntype hostNS struct {\n}\n\nfunc (h *hostNS) Set(s *specs.Spec) error {\n\treturn oci.WithHostNamespace(specs.NetworkNamespace)(nil, nil, nil, s)\n}\n\nfunc (h *hostNS) Close() error {\n\treturn nil\n}\n\nfunc NewHostProvider() Provider ", "output": "{\n\treturn &host{}\n}"} {"input": "package dummy\n\nimport (\n\t\"log\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/svenwiltink/go-musicbot/pkg/music\"\n)\n\ntype SongPlayer struct {\n\tlock sync.Mutex\n}\n\nfunc (player *SongPlayer) CanPlay(song music.Song) bool {\n\treturn true\n}\n\nfunc (player *SongPlayer) Wait() {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\ttime.Sleep(time.Second * 10)\n}\n\nfunc (player *SongPlayer) PlaySong(song music.Song) error {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\tlog.Printf(\"starting playback of %s\", song.Name)\n\treturn nil\n}\n\nfunc (player *SongPlayer) Play() error {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\tlog.Printf(\"resuming playback\")\n\treturn nil\n}\n\nfunc (player *SongPlayer) Pause() error {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\tlog.Printf(\"pausing playback\")\n\treturn nil\n}\n\n\n\nfunc NewSongPlayer() *SongPlayer ", "output": "{\n\treturn &SongPlayer{}\n}"} {"input": "package main\n\nimport \"strings\"\n\nvar x = make([]byte, 10)\n\nfunc main() {\n\ttest1()\n\ttest2()\n\ttest3()\n\ttest4()\n\ttest5()\n\ttest6()\n\ttest7()\n}\n\nfunc mustRecover(s string) {\n\tv := recover()\n\tif v == nil {\n\t\tpanic(\"expected panic\")\n\t}\n\tif e := v.(error).Error(); strings.Index(e, s) < 0 {\n\t\tpanic(\"want: \" + s + \"; have: \" + e)\n\t}\n}\n\nfunc test1() {\n\tdefer mustRecover(\"index\")\n\tprintln(x[123])\n}\n\nfunc test2() {\n\tdefer mustRecover(\"slice\")\n\tprintln(x[5:15])\n}\n\nfunc test3() {\n\tdefer mustRecover(\"slice\")\n\tvar lo = 11\n\tvar hi = 9\n\tprintln(x[lo:hi])\n}\n\nfunc test4() {\n\tdefer mustRecover(\"interface\")\n\tvar x interface{} = 1\n\tprintln(x.(float32))\n}\n\ntype T struct {\n\ta, b int\n\tc []int\n}\n\nfunc test5() {\n\tdefer mustRecover(\"uncomparable\")\n\tvar x T\n\tvar z interface{} = x\n\tprintln(z != z)\n}\n\nfunc test6() {\n\tdefer mustRecover(\"unhashable\")\n\tvar x T\n\tvar z interface{} = x\n\tm := make(map[interface{}]int)\n\tm[z] = 1\n}\n\n\n\nfunc test7() ", "output": "{\n\tdefer mustRecover(\"divide by zero\")\n\tvar x, y int\n\tprintln(x / y)\n}"} {"input": "package terminal\n\nimport \"fmt\"\n\nvar ColorError int = 167\nvar ColorWarn int = 93\nvar ColorSuccess int = 82\nvar ColorNeutral int = 50\nvar BackgroundColorBlack = \"\\033[30;49m\"\nvar BackgroundColorWhite = \"\\033[30;47m\"\nvar ResetCode string = \"\\033[0m\"\n\n\n\n\n\n\n\n\n\n\nfunc BoldText(msg string) string {\n\tif !stdoutIsTTY {\n\t\treturn msg\n\t}\n\treturn fmt.Sprintf(\"\\033[1m%s\\033[0m\", msg)\n}\n\nfunc Colorize(color int, msg string) string ", "output": "{\n\tif !stdoutIsTTY {\n\t\treturn msg\n\t}\n\treturn fmt.Sprintf(\"\\033[0;1m\\033[38;5;%dm%s%s\", color, msg, ResetCode)\n}"} {"input": "package tchannelthrift\n\nimport (\n\tstdctx \"context\"\n\t\"time\"\n\n\t\"github.com/m3db/m3/src/x/context\"\n\n\tapachethrift \"github.com/apache/thrift/lib/go/thrift\"\n\t\"github.com/uber/tchannel-go\"\n\t\"github.com/uber/tchannel-go/thrift\"\n)\n\nconst (\n\tcontextKey = \"m3dbcontext\"\n)\n\n\nfunc RegisterServer(channel *tchannel.Channel, service thrift.TChanServer, contextPool context.Pool) {\n\tserver := thrift.NewServer(channel)\n\tserver.Register(service, thrift.OptPostResponse(postResponseFn))\n\tserver.SetContextFn(func(ctx stdctx.Context, method string, headers map[string]string) thrift.Context {\n\t\txCtx := contextPool.Get()\n\t\txCtx.SetGoContext(ctx)\n\t\tctxWithValue := stdctx.WithValue(ctx, contextKey, xCtx) \n\t\treturn thrift.WithHeaders(ctxWithValue, headers)\n\t})\n}\n\n\nfunc NewContext(timeout time.Duration) (thrift.Context, stdctx.CancelFunc) {\n\ttctx, cancel := thrift.NewContext(timeout)\n\txCtx := context.NewWithGoContext(tctx)\n\tctxWithValue := stdctx.WithValue(tctx, contextKey, xCtx) \n\treturn thrift.WithHeaders(ctxWithValue, nil), cancel\n}\n\n\n\n\nfunc postResponseFn(ctx stdctx.Context, method string, response apachethrift.TStruct) {\n\tvalue := ctx.Value(contextKey)\n\tinner := value.(context.Context)\n\tinner.Close()\n}\n\nfunc Context(ctx thrift.Context) context.Context ", "output": "{\n\treturn ctx.Value(contextKey).(context.Context)\n}"} {"input": "package stack\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/docker/docker/api/client\"\n\t\"github.com/docker/docker/api/client/idresolver\"\n\t\"github.com/docker/docker/api/client/task\"\n\t\"github.com/docker/docker/cli\"\n\t\"github.com/docker/docker/opts\"\n\t\"github.com/docker/engine-api/types\"\n\t\"github.com/docker/engine-api/types/swarm\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype tasksOptions struct {\n\tall bool\n\tfilter opts.FilterOpt\n\tnamespace string\n\tnoResolve bool\n}\n\nfunc newTasksCommand(dockerCli *client.DockerCli) *cobra.Command {\n\topts := tasksOptions{filter: opts.NewFilterOpt()}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"tasks [OPTIONS] STACK\",\n\t\tShort: \"List the tasks in the stack\",\n\t\tArgs: cli.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\topts.namespace = args[0]\n\t\t\treturn runTasks(dockerCli, opts)\n\t\t},\n\t}\n\tflags := cmd.Flags()\n\tflags.BoolVarP(&opts.all, \"all\", \"a\", false, \"Display all tasks\")\n\tflags.BoolVarP(&opts.noResolve, \"no-resolve\", \"n\", false, \"Do not map IDs to Names\")\n\tflags.VarP(&opts.filter, \"filter\", \"f\", \"Filter output based on conditions provided\")\n\n\treturn cmd\n}\n\n\n\nfunc runTasks(dockerCli *client.DockerCli, opts tasksOptions) error ", "output": "{\n\tclient := dockerCli.Client()\n\tctx := context.Background()\n\n\tfilter := opts.filter.Value()\n\tfilter.Add(\"label\", labelNamespace+\"=\"+opts.namespace)\n\tif !opts.all && !filter.Include(\"desired-state\") {\n\t\tfilter.Add(\"desired-state\", string(swarm.TaskStateRunning))\n\t\tfilter.Add(\"desired-state\", string(swarm.TaskStateAccepted))\n\t}\n\n\ttasks, err := client.TaskList(ctx, types.TaskListOptions{Filter: filter})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn task.Print(dockerCli, ctx, tasks, idresolver.New(client, opts.noResolve))\n}"} {"input": "package iso20022\n\n\ntype CorporateActionOption1FormatChoice struct {\n\n\tCode *CorporateActionOptionType1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification13 `xml:\"Prtry\"`\n}\n\nfunc (c *CorporateActionOption1FormatChoice) SetCode(value string) {\n\tc.Code = (*CorporateActionOptionType1Code)(&value)\n}\n\n\n\nfunc (c *CorporateActionOption1FormatChoice) AddProprietary() *GenericIdentification13 ", "output": "{\n\tc.Proprietary = new(GenericIdentification13)\n\treturn c.Proprietary\n}"} {"input": "package v1alpha1\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\tv1alpha1 \"k8s.io/ingress-gce/pkg/experimental/apis/workload/v1alpha1\"\n\t\"k8s.io/ingress-gce/pkg/experimental/workload/client/clientset/versioned/scheme\"\n)\n\ntype NetworkingV1alpha1Interface interface {\n\tRESTClient() rest.Interface\n\tWorkloadsGetter\n}\n\n\ntype NetworkingV1alpha1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *NetworkingV1alpha1Client) Workloads(namespace string) WorkloadInterface {\n\treturn newWorkloads(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*NetworkingV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &NetworkingV1alpha1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *NetworkingV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\n\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *NetworkingV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc New(c rest.Interface) *NetworkingV1alpha1Client ", "output": "{\n\treturn &NetworkingV1alpha1Client{c}\n}"} {"input": "package ks\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\n\nfunc ReadLines(r io.Reader) []string {\n\n\tbr := bufio.NewReader(r)\n\tvar res []string\n\n\tfor {\n\t\ts, _, err := br.ReadLine()\n\n\t\tif err != nil {\n\t\t\treturn res\n\t\t}\n\n\t\tres = append(res, string(s))\n\n\t}\n\n}\n\nfunc ListFiles(folder string) []string {\n\n\tvar res []string\n\n\tfilepath.Walk(fmt.Sprintf(folder),\n\t\tfunc(path string, info os.FileInfo, err error) error {\n\n\t\t\tif info != nil && !info.IsDir() {\n\t\t\t\tres = append(res, info.Name())\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\treturn res\n}\n\nfunc FileExists(filename string) bool {\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc ReadBytesFromFile(filename string) ([]byte, error) ", "output": "{\n\tfin, err := os.Open(filename)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ioutil.ReadAll(fin)\n}"} {"input": "package iso20022\n\n\ntype PaymentInstrument21Choice struct {\n\n\tCreditTransferDetails *CreditTransfer8 `xml:\"CdtTrfDtls\"`\n\n\tChequeDetails *Cheque9 `xml:\"ChqDtls\"`\n\n\tBankersDraftDetails *Cheque9 `xml:\"BkrsDrftDtls\"`\n\n\tCashAccountDetails *InvestmentAccount60 `xml:\"CshAcctDtls\"`\n}\n\n\n\nfunc (p *PaymentInstrument21Choice) AddChequeDetails() *Cheque9 {\n\tp.ChequeDetails = new(Cheque9)\n\treturn p.ChequeDetails\n}\n\nfunc (p *PaymentInstrument21Choice) AddBankersDraftDetails() *Cheque9 {\n\tp.BankersDraftDetails = new(Cheque9)\n\treturn p.BankersDraftDetails\n}\n\nfunc (p *PaymentInstrument21Choice) AddCashAccountDetails() *InvestmentAccount60 {\n\tp.CashAccountDetails = new(InvestmentAccount60)\n\treturn p.CashAccountDetails\n}\n\nfunc (p *PaymentInstrument21Choice) AddCreditTransferDetails() *CreditTransfer8 ", "output": "{\n\tp.CreditTransferDetails = new(CreditTransfer8)\n\treturn p.CreditTransferDetails\n}"} {"input": "package gftest\n\nimport (\n \"errors\"\n \"reflect\"\n \"encoding/json\"\n)\n\n\n\nfunc (req *Request) NewError(msg string) error {\n\n\terr := errors.New(req.FullPath() + \": \" + msg)\n\treturn err\n}\n\nfunc (req *Request) Error(e error) { req.t.Log(e.Error()) }\n\nfunc (req *Request) Reflect(e interface{}) {\n\tmsg := \"REFLECT VALUE IS NIL\"\n\tif e != nil {\n\t\tmsg = \"REFLECT VALUE IS \"+reflect.TypeOf(e).String()\n\t}\n\treq.NewError(msg)\n}\n\nfunc (req *Request) DebugJSON(i interface{}) {\n\tb, err := json.Marshal(i); if err != nil { req.Error(err); return }\n\treq.Debug(string(b))\n}\n\nfunc (req *Request) Debug(msg string) ", "output": "{ req.t.Log(req.FullPath() + \": %v\", msg) }"} {"input": "package hdiutil\n\nimport \"os/exec\"\n\n\ntype formatFlag interface {\n\tformatFlag() []string\n}\n\ntype convertFormot int\n\nconst (\n\tConvertUDRW convertFormot = 1 << iota\n\tConvertUDRO\n\tConvertUDCO\n\tConvertUDZO\n\tConvertULFO\n\tConvertUDBZ\n\tConvertUDTO\n\tConvertUDSP\n\tConvertUDSB\n\tConvertUFBI\n\tConvertUDRo\n\tConvertUDCo\n\tConvertRdWr\n\tConvertRdxx\n\tConvertROCo\n\tConvertRken\n\tConvertDC42\n)\n\n\ntype convertFlag interface {\n\tconvertFlag() []string\n}\n\n\ntype ConvertAlign int\n\nfunc (c ConvertAlign) convertFlag() []string { return intFlag(\"align\", int(c)) }\n\ntype convertPmap bool\n\n\n\n\n\n\n\n\ntype ConvertSegmentSize string\n\nfunc (c ConvertSegmentSize) convertFlag() []string { return stringFlag(\"segmentSize\", string(c)) }\n\n\n\n\ntype ConvertTasks int\n\nfunc (c ConvertTasks) convertFlag() []string { return intFlag(\"tasks\", int(c)) }\n\nconst (\n\tConvertPmap convertPmap = true\n)\n\n\nfunc Convert(image string, format formatFlag, outfile string, flags ...convertFlag) error {\n\tcmd := exec.Command(hdiutilPath, \"convert\", image)\n\tcmd.Args = append(cmd.Args, format.formatFlag()...)\n\tcmd.Args = append(cmd.Args, outfile)\n\tif len(flags) > 0 {\n\t\tfor _, flag := range flags {\n\t\t\tcmd.Args = append(cmd.Args, flag.convertFlag()...)\n\t\t}\n\t}\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c convertPmap) convertFlag() []string ", "output": "{ return boolFlag(\"pmap\", bool(c)) }"} {"input": "package canopus\n\nimport \"net\"\n\nfunc Dial(address string) (conn Connection, err error) {\n\tudpConn, err := net.Dial(\"udp\", address)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn = &UDPConnection{\n\t\tconn: udpConn,\n\t}\n\n\treturn\n}\n\n\n\nfunc NewObserveMessage(r string, val interface{}, msg Message) ObserveMessage {\n\treturn &CoapObserveMessage{\n\t\tResource: r,\n\t\tValue: val,\n\t\tMsg: msg,\n\t}\n}\n\ntype CoapObserveMessage struct {\n\tCoapMessage\n\tResource string\n\tValue interface{}\n\tMsg Message\n}\n\nfunc (m *CoapObserveMessage) GetResource() string {\n\treturn m.Resource\n}\n\nfunc (m *CoapObserveMessage) GetValue() interface{} {\n\treturn m.Value\n}\n\nfunc (m *CoapObserveMessage) GetMessage() Message {\n\treturn m.GetMessage()\n}\n\nfunc DialDTLS(address, identity, psk string) (conn Connection, err error) ", "output": "{\n\tudpConn, err := net.Dial(\"udp\", address)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn, err = NewDTLSConnection(udpConn, identity, psk)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}"} {"input": "package builtin\n\nconst dvbSummary = `allows access to all DVB (Digital Video Broadcasting) devices and APIs`\n\nconst dvbBaseDeclarationSlots = `\n dvb:\n allow-installation:\n slot-snap-type:\n - core\n deny-auto-connection: true\n`\n\nconst dvbConnectedPlugAppArmor = `\n# Allow access to all DVB devices\n/dev/dvb/adapter[0-9]*/* rw,\n# From https://www.kernel.org/doc/Documentation/admin-guide/devices.txt\n/run/udev/data/c212:[0-9]* r,\n`\n\nvar dvbConnectedPlugUDev = []string{`SUBSYSTEM==\"dvb\"`}\n\n\n\nfunc init() ", "output": "{\n\tregisterIface(&commonInterface{\n\t\tname: \"dvb\",\n\t\tsummary: dvbSummary,\n\t\timplicitOnCore: true,\n\t\timplicitOnClassic: true,\n\t\tbaseDeclarationSlots: dvbBaseDeclarationSlots,\n\t\tconnectedPlugAppArmor: dvbConnectedPlugAppArmor,\n\t\tconnectedPlugUDev: dvbConnectedPlugUDev,\n\t\treservedForOS: true,\n\t})\n}"} {"input": "package sqlite\n\nimport (\n\t\"testing\"\n\n\t\"github.com/anmil/quicknote/test\"\n)\n\nvar tableNames = []string{\n\t\"books\",\n\t\"note_book_tag\",\n\t\"note_tag\",\n\t\"notes\",\n\t\"sqlite_sequence\",\n\t\"tags\",\n}\n\nfunc openDatabase(t *testing.T) *Database {\n\tdb, err := NewDatabase(\"file::memory:?cache=shared\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treturn db\n}\n\nfunc closeDatabase(db *Database, t *testing.T) {\n\tif err := db.Close(); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\n\n\nfunc TestCreateDatabaseSQLite(t *testing.T) ", "output": "{\n\tdb := openDatabase(t)\n\tdefer closeDatabase(db, t)\n\n\tif tables, err := db.GetTableNames(); err != nil {\n\t\tt.Fatal(err)\n\t} else if !test.StringSliceEq(tables, tableNames) {\n\t\tt.Fatal(\"Database either has extra or is missing tables\")\n\t}\n}"} {"input": "package newapp\n\nimport (\n\t\"io/ioutil\"\n\t\"path/filepath\"\n)\n\n\n\nfunc createMain(appPath, appName string) ", "output": "{\n\tdata := []byte(`package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/codegangsta/negroni\"\n)\n\nfunc main() {\n\tvar (\n\t\tportFlag = flag.Int(\"port\", 9090, \"port to serve ` + appName + `.\")\n\t)\n\tflag.Parse()\n\tport := *portFlag\n\taddr := fmt.Sprintf(\":%d\", port)\n\thandler := InitializeRouter()\n\tn := negroni.Classic()\n\tn.UseHandler(handler)\n\tn.Run(addr)\n}`)\n\tmainGoFile := filepath.Join(appPath, \"main.go\")\n\tioutil.WriteFile(mainGoFile, data, filePerm)\n}"} {"input": "package qld\n\ntype config struct {\n}\n\n\n\nfunc newConfig() (*config, error) ", "output": "{\n\tcfg := &config{}\n\n\treturn cfg, nil\n}"} {"input": "package masking\n\nimport (\n\t\"bytes\"\n\t\"github.com/cossacklabs/acra/decryptor/base\"\n\t\"github.com/cossacklabs/acra/encryptor\"\n\t\"github.com/cossacklabs/acra/logging\"\n)\n\n\ntype Processor struct{ decryptor base.ExtendedDataProcessor }\n\n\nfunc NewProcessor(decryptor base.ExtendedDataProcessor) (*Processor, error) {\n\treturn &Processor{decryptor: decryptor}, nil\n}\n\n\n\n\nfunc (processor *Processor) Process(data []byte, context *base.DataProcessorContext) ([]byte, error) ", "output": "{\n\tlogger := logging.GetLoggerFromContext(context.Context).WithField(\"processor\", \"masking\")\n\tlogger.Debugln(\"Processing masking\")\n\tsetting, ok := encryptor.EncryptionSettingFromContext(context.Context)\n\tif ok && setting.GetMaskingPattern() != \"\" {\n\t\tlogger.Debugln(\"Has pattern\")\n\t\tnewData, err := processor.decryptor.Process(data, context)\n\t\tif err != nil || bytes.Equal(newData, data) {\n\t\t\tlogger.Debugln(\"Mask data\")\n\t\t\treturn []byte(setting.GetMaskingPattern()), nil\n\t\t}\n\t\tlogger.Debugln(\"Return decrypted\")\n\t\treturn newData, nil\n\t}\n\treturn processor.decryptor.Process(data, context)\n}"} {"input": "package server\n\nimport (\n\t\"google.golang.org/grpc\"\n\tsdkgrpc \"github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/eventarc/alpha/eventarc_alpha_go_proto\"\n)\n\n\n\n\nfunc RegisterServers(s *grpc.Server) ", "output": "{\n\tsdkgrpc.RegisterEventarcAlphaTriggerServiceServer(s, &TriggerServer{})\n}"} {"input": "package controllers\n\nimport (\n \"fmt\"\n \"strconv\"\n \"encoding/json\"\n \"jostler/models\"\n)\n\n\ntype UserController struct {\n baseController\n}\n\nfunc (this *UserController) AddUser() {\n var user models.User\n err := json.Unmarshal(this.Ctx.Input.RequestBody, &user)\n if err != nil {\n this.Response(ERROR, fmt.Sprintf(\"Incorrect JSON: %v\", err))\n return\n }\n if invalid := this.Validate(&user); invalid != nil {\n this.Response(FAIL, invalid)\n return\n }\n _, err = this.db.Insert(&user)\n if err != nil {\n this.Response(ERROR, err)\n } else {\n this.Response(SUCCESS, map[string]interface{}{\"user\": user})\n }\n}\n\nfunc (this *UserController) UserInfo() {\n id, err := strconv.Atoi(this.Ctx.Input.Param(\":id\"))\n if err != nil {\n this.Response(FAIL, map[string]interface{}{\"id\": \"Must be an integer\"})\n return\n }\n user := models.User{Id: id}\n err = this.db.Read(&user)\n _, err = this.db.LoadRelated(&user, \"Ticks\")\n if err != nil {\n this.Response(FAIL, map[string]interface{}{\"id\": fmt.Sprintf(\"User with id %v not found\", id)})\n } else {\n this.Response(SUCCESS, map[string]interface{}{\"user\": user})\n }\n}\n\n\n\nfunc (this *UserController) UserDelete() {\n id, _ := strconv.Atoi(this.Ctx.Input.Param(\":id\"))\n if _, err := this.db.Delete(&models.User{Id: id}); err == nil {\n this.Response(SUCCESS, nil)\n } else {\n this.Response(ERROR, err)\n }\n}\n\nfunc (this *UserController) UserUpdate() ", "output": "{\n id, _ := strconv.Atoi(this.Ctx.Input.Param(\":id\"))\n user := models.User{Id: id}\n err := this.db.Read(&user)\n if err != nil {\n this.Response(FAIL, map[string]interface{}{\"id\": fmt.Sprintf(\"User with id %v not found\", id)})\n return\n }\n err = json.Unmarshal(this.Ctx.Input.RequestBody, &user)\n if err != nil {\n this.Response(ERROR, fmt.Sprintf(\"Incorrect JSON: %v\", err))\n return\n }\n if invalid := this.Validate(&user); invalid != nil {\n this.Response(FAIL, invalid)\n return\n }\n if _, err = this.db.Update(&user); err == nil {\n this.Response(SUCCESS, map[string]interface{}{\"user\": user})\n } else {\n this.Response(ERROR, err)\n }\n}"} {"input": "package lib\n\nimport \"sync\"\n\n\n\ntype ConcurrentPrinterMap struct {\n\tbyCUPSName map[string]Printer\n\tbyGCPID map[string]Printer\n\tmutex sync.RWMutex\n}\n\n\nfunc NewConcurrentPrinterMap(printers []Printer) *ConcurrentPrinterMap {\n\tcpm := ConcurrentPrinterMap{}\n\tcpm.Refresh(printers)\n\treturn &cpm\n}\n\n\nfunc (cpm *ConcurrentPrinterMap) Refresh(newPrinters []Printer) {\n\tc := make(map[string]Printer, len(newPrinters))\n\tfor _, printer := range newPrinters {\n\t\tc[printer.Name] = printer\n\t}\n\n\tg := make(map[string]Printer, len(newPrinters))\n\tfor _, printer := range newPrinters {\n\t\tif len(printer.GCPID) > 0 {\n\t\t\tg[printer.GCPID] = printer\n\t\t}\n\t}\n\n\tcpm.mutex.Lock()\n\tdefer cpm.mutex.Unlock()\n\n\tcpm.byCUPSName = c\n\tcpm.byGCPID = g\n}\n\n\n\n\nfunc (cpm *ConcurrentPrinterMap) GetByCUPSName(name string) (Printer, bool) {\n\tcpm.mutex.RLock()\n\tdefer cpm.mutex.RUnlock()\n\n\tif p, exists := cpm.byCUPSName[name]; exists {\n\t\treturn p, true\n\t}\n\treturn Printer{}, false\n}\n\n\n\n\nfunc (cpm *ConcurrentPrinterMap) GetByGCPID(gcpID string) (Printer, bool) {\n\tcpm.mutex.RLock()\n\tdefer cpm.mutex.RUnlock()\n\n\tif p, exists := cpm.byGCPID[gcpID]; exists {\n\t\treturn p, true\n\t}\n\treturn Printer{}, false\n}\n\n\n\n\nfunc (cpm *ConcurrentPrinterMap) GetAll() []Printer ", "output": "{\n\tcpm.mutex.RLock()\n\tdefer cpm.mutex.RUnlock()\n\n\tprinters := make([]Printer, len(cpm.byCUPSName))\n\ti := 0\n\tfor _, printer := range cpm.byCUPSName {\n\t\tprinters[i] = printer\n\t\ti++\n\t}\n\n\treturn printers\n}"} {"input": "package handler\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"net/http\"\n)\n\n\nfunc Index(c *gin.Context) {\n\tc.String(http.StatusOK, \"welcome 2 banerwai api\")\n}\n\n\n\n\nfunc Ping(c *gin.Context) ", "output": "{\n\tc.String(http.StatusOK, \"pong\")\n}"} {"input": "package mock\n\nimport (\n\t\"github.com/eventials/goevents/messaging\"\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype Connection struct {\n\tmock.Mock\n}\n\nfunc NewMockConnection() messaging.Connection {\n\treturn &Connection{}\n}\n\nfunc (c *Connection) Consumer(autoAck bool, exchange, queue string) (messaging.Consumer, error) {\n\targs := c.Called(autoAck, exchange, queue)\n\treturn args.Get(0).(messaging.Consumer), args.Error(1)\n}\n\nfunc (c *Connection) Producer(exchange string) (messaging.Producer, error) {\n\targs := c.Called(exchange)\n\treturn args.Get(0).(messaging.Producer), args.Error(1)\n}\n\nfunc (c *Connection) Close() {\n\tc.Called()\n}\n\n\n\nfunc (c *Connection) NotifyReestablish() <-chan bool {\n\targs := c.Called()\n\treturn args.Get(0).(chan bool)\n}\n\nfunc (c *Connection) WaitUntilConnectionCloses() {\n\tc.Called()\n}\n\nfunc (c *Connection) WaitUntilConnectionReestablished() {\n\tc.Called()\n}\n\nfunc (c *Connection) IsConnected() bool {\n\targs := c.Called()\n\treturn args.Get(0).(bool)\n}\n\nfunc (c *Connection) NotifyConnectionClose() <-chan error ", "output": "{\n\targs := c.Called()\n\treturn args.Get(0).(chan error)\n}"} {"input": "package bits_test\n\nimport (\n\t\"github.com/twmb/bits\"\n\t\"testing\"\n)\n\nfunc TestSet(t *testing.T) {\n\tfor i := 0; i < 256; i++ {\n\t\tif int(bits.SetU32(uint32(i))) != bits.Hamming(i, 0) {\n\t\t\tt.Errorf(\"Error in set: wanted %v for %v, got %v\",\n\t\t\t\tbits.Hamming(i, 0), i, bits.SetU32(uint32(i)))\n\t\t}\n\t}\n}\n\nfunc BenchmarkSetTable(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetTable(i)\n\t}\n}\nfunc BenchmarkSetKernighan(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetKernighan(uint(i))\n\t}\n}\nfunc BenchmarkSetU32(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetU32(uint32(i))\n\t}\n}\n\n\nfunc BenchmarkSetU64(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetU64(uint64(i))\n\t}\n}"} {"input": "package manager\n\n\ntype RabbitmqConfig struct {\n\tUri string `json:\"uri\"`\n\tExchange string `json:\"exchange\"`\n\tExchangeType string `json:\"exchange_type\"`\n}\n\n\n\n\nfunc NewRabbitmqConfig(uri, exchange, exchangeType string) *RabbitmqConfig ", "output": "{\n\treturn &RabbitmqConfig{\n\t\tUri: uri,\n\t\tExchange: exchange,\n\t\tExchangeType: exchangeType,\n\t}\n}"} {"input": "package testhelpers\n\nimport \"github.com/go-kit/kit/metrics\"\n\n\ntype CollectingCounter struct {\n\tCounterValue float64\n\tLastLabelValues []string\n}\n\n\nfunc (c *CollectingCounter) With(labelValues ...string) metrics.Counter {\n\tc.LastLabelValues = labelValues\n\treturn c\n}\n\n\nfunc (c *CollectingCounter) Add(delta float64) {\n\tc.CounterValue += delta\n}\n\n\ntype CollectingGauge struct {\n\tGaugeValue float64\n\tLastLabelValues []string\n}\n\n\n\n\n\nfunc (g *CollectingGauge) Set(value float64) {\n\tg.GaugeValue = value\n}\n\n\nfunc (g *CollectingGauge) Add(delta float64) {\n\tg.GaugeValue = delta\n}\n\n\ntype CollectingHealthCheckMetrics struct {\n\tGauge *CollectingGauge\n}\n\n\nfunc (m *CollectingHealthCheckMetrics) BackendServerUpGauge() metrics.Gauge {\n\treturn m.Gauge\n}\n\n\nfunc NewCollectingHealthCheckMetrics() *CollectingHealthCheckMetrics {\n\treturn &CollectingHealthCheckMetrics{&CollectingGauge{}}\n}\n\nfunc (g *CollectingGauge) With(labelValues ...string) metrics.Gauge ", "output": "{\n\tg.LastLabelValues = labelValues\n\treturn g\n}"} {"input": "package metrics\n\nimport (\n\t\"github.com/cloudfoundry/dropsonde/metric_sender\"\n)\n\nvar metricSender metric_sender.MetricSender\nvar metricBatcher MetricBatcher\n\ntype MetricBatcher interface {\n\tBatchIncrementCounter(name string)\n\tBatchAddCounter(name string, delta uint64)\n\tClose()\n}\n\n\nfunc Initialize(ms metric_sender.MetricSender, mb MetricBatcher) {\n\tif metricBatcher != nil {\n\t\tmetricBatcher.Close()\n\t}\n\tmetricSender = ms\n\tmetricBatcher = mb\n}\n\n\nfunc Close() {\n\tmetricBatcher.Close()\n}\n\n\n\nfunc SendValue(name string, value float64, unit string) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.SendValue(name, value, unit)\n}\n\n\n\n\nfunc IncrementCounter(name string) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.IncrementCounter(name)\n}\n\n\n\n\nfunc BatchIncrementCounter(name string) {\n\tif metricBatcher == nil {\n\t\treturn\n\t}\n\tmetricBatcher.BatchIncrementCounter(name)\n}\n\n\n\n\n\n\n\n\n\nfunc BatchAddCounter(name string, delta uint64) {\n\tif metricBatcher == nil {\n\t\treturn\n\t}\n\tmetricBatcher.BatchAddCounter(name, delta)\n}\n\n\n\n\n\nfunc SendContainerMetric(applicationId string, instanceIndex int32, cpuPercentage float64, memoryBytes uint64, diskBytes uint64) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\n\treturn metricSender.SendContainerMetric(applicationId, instanceIndex, cpuPercentage, memoryBytes, diskBytes)\n}\n\nfunc AddToCounter(name string, delta uint64) error ", "output": "{\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.AddToCounter(name, delta)\n}"} {"input": "package enmime\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/cention-sany/mime\"\n)\n\nfunc debug(format string, args ...interface{}) {\n\tif false {\n\t\tfmt.Printf(format, args...)\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\nfunc DecodeHeader(input string) string {\n\tif !strings.Contains(input, \"=?\") {\n\t\treturn input\n\t}\n\n\tdec := new(mime.WordDecoder)\n\tdec.CharsetReader = NewCharsetReader\n\theader, err := dec.DecodeHeader(input)\n\tif err != nil {\n\t\treturn input\n\t}\n\treturn header\n}\n\n\nfunc DecodeToUTF8Base64Header(input string) string {\n\tif !strings.Contains(input, \"=?\") {\n\t\treturn input\n\t}\n\n\tdebug(\"input = %q\", input)\n\ttokens := strings.FieldsFunc(input, isWhiteSpaceRune)\n\toutput := make([]string, len(tokens), len(tokens))\n\tfor i, token := range tokens {\n\t\tif len(token) > 4 && strings.Contains(token, \"=?\") {\n\t\t\tprefix := \"\"\n\t\t\tsuffix := \"\"\n\t\t\tif token[0] == '(' {\n\t\t\t\tprefix = \"(\"\n\t\t\t\ttoken = token[1:]\n\t\t\t}\n\t\t\tif token[len(token)-1] == ')' {\n\t\t\t\tsuffix = \")\"\n\t\t\t\ttoken = token[:len(token)-1]\n\t\t\t}\n\t\t\toutput[i] = prefix + mime.BEncoding.Encode(\"UTF-8\", DecodeHeader(token)) + suffix\n\t\t} else {\n\t\t\toutput[i] = token\n\t\t}\n\t\tdebug(\"%v %q %q\", i, token, output[i])\n\t}\n\n\treturn strings.Join(output, \" \")\n}\n\n\n\n\nfunc isWhiteSpaceRune(r rune) bool ", "output": "{\n\tswitch r {\n\tcase ' ':\n\t\treturn true\n\tcase '\\t':\n\t\treturn true\n\tcase '\\r':\n\t\treturn true\n\tcase '\\n':\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}"} {"input": "package j_kite\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"koding/remoteapi/models\"\n)\n\n\ntype PostRemoteAPIJKiteFetchPlansIDReader struct {\n\tformats strfmt.Registry\n}\n\n\n\n\n\nfunc NewPostRemoteAPIJKiteFetchPlansIDOK() *PostRemoteAPIJKiteFetchPlansIDOK {\n\treturn &PostRemoteAPIJKiteFetchPlansIDOK{}\n}\n\n\ntype PostRemoteAPIJKiteFetchPlansIDOK struct {\n\tPayload *models.JKite\n}\n\nfunc (o *PostRemoteAPIJKiteFetchPlansIDOK) Error() string {\n\treturn fmt.Sprintf(\"[POST /remote.api/JKite.fetchPlans/{id}][%d] postRemoteApiJKiteFetchPlansIdOK %+v\", 200, o.Payload)\n}\n\nfunc (o *PostRemoteAPIJKiteFetchPlansIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\to.Payload = new(models.JKite)\n\n\tif err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (o *PostRemoteAPIJKiteFetchPlansIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) ", "output": "{\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewPostRemoteAPIJKiteFetchPlansIDOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}"} {"input": "package controller\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/pajbot/pajbot2/pkg/web/views\"\n)\n\n\n\nfunc handleProfile(w http.ResponseWriter, r *http.Request) ", "output": "{\n\terr := views.Render(\"profile\", w, r)\n\tif err != nil {\n\t\tlog.Println(\"Error rendering dashboard view:\", err)\n\t}\n}"} {"input": "package config\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"text/template\"\n)\n\nvar (\n\tglbEnvs map[string]string\n)\n\nfunc init() {\n\tglbEnvs = make(map[string]string)\n\tenvs := os.Environ()\n\tfor _, env := range envs {\n\t\tkv := strings.Split(env, \"=\")\n\t\tif len(kv) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tglbEnvs[kv[0]] = kv[1]\n\t}\n}\n\ntype Values struct {\n\tEnvs map[string]string \n}\n\nfunc GetValues() *Values {\n\treturn &Values{\n\t\tEnvs: glbEnvs,\n\t}\n}\n\n\n\nfunc GetRenderedConfFromFile(path string) (out []byte, err error) {\n\tvar b []byte\n\tb, err = ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tout, err = RenderContent(b)\n\treturn\n}\n\nfunc RenderContent(in []byte) (out []byte, err error) ", "output": "{\n\ttmpl, errRet := template.New(\"frp\").Parse(string(in))\n\tif errRet != nil {\n\t\terr = errRet\n\t\treturn\n\t}\n\n\tbuffer := bytes.NewBufferString(\"\")\n\tv := GetValues()\n\terr = tmpl.Execute(buffer, v)\n\tif err != nil {\n\t\treturn\n\t}\n\tout = buffer.Bytes()\n\treturn\n}"} {"input": "package elastic\n\n\n\n\n\ntype GeoPolygonQuery struct {\n\tname string\n\tpoints []*GeoPoint\n\tqueryName string\n}\n\n\nfunc NewGeoPolygonQuery(name string) *GeoPolygonQuery {\n\treturn &GeoPolygonQuery{\n\t\tname: name,\n\t\tpoints: make([]*GeoPoint, 0),\n\t}\n}\n\n\nfunc (q *GeoPolygonQuery) AddPoint(lat, lon float64) *GeoPolygonQuery {\n\tq.points = append(q.points, GeoPointFromLatLon(lat, lon))\n\treturn q\n}\n\n\nfunc (q *GeoPolygonQuery) AddGeoPoint(point *GeoPoint) *GeoPolygonQuery {\n\tq.points = append(q.points, point)\n\treturn q\n}\n\nfunc (q *GeoPolygonQuery) QueryName(queryName string) *GeoPolygonQuery {\n\tq.queryName = queryName\n\treturn q\n}\n\n\n\n\nfunc (q *GeoPolygonQuery) Source() (interface{}, error) ", "output": "{\n\tsource := make(map[string]interface{})\n\n\tparams := make(map[string]interface{})\n\tsource[\"geo_polygon\"] = params\n\n\tpolygon := make(map[string]interface{})\n\tparams[q.name] = polygon\n\n\tpoints := make([]interface{}, 0)\n\tfor _, point := range q.points {\n\t\tpoints = append(points, point.Source())\n\t}\n\tpolygon[\"points\"] = points\n\n\tif q.queryName != \"\" {\n\t\tparams[\"_name\"] = q.queryName\n\t}\n\n\treturn source, nil\n}"} {"input": "package logger\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"gopkg.in/clever/kayvee-go.v2\"\n)\n\n\ntype M map[string]interface{}\n\n\nfunc Info(title string, data M) {\n\tlogWithLevel(title, kayvee.Info, data)\n}\n\n\nfunc Trace(title string, data M) {\n\tlogWithLevel(title, kayvee.Trace, data)\n}\n\n\nfunc Warning(title string, data M) {\n\tlogWithLevel(title, kayvee.Warning, data)\n}\n\n\nfunc Critical(title string, data M) {\n\tlogWithLevel(title, kayvee.Critical, data)\n}\n\n\n\n\n\nfunc ErrorDetailed(title string, err error, extras M) {\n\textras[\"error\"] = fmt.Sprint(err)\n\tlogWithLevel(title, kayvee.Error, extras)\n}\n\nfunc logWithLevel(title string, level kayvee.LogLevel, data M) {\n\tformatted := kayvee.FormatLog(\"moredis\", level, title, data)\n\tlog.Println(formatted)\n}\n\nfunc Error(title string, err error) ", "output": "{\n\tlogWithLevel(title, kayvee.Error, M{\"error\": fmt.Sprint(err)})\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/labstack/echo\"\n)\n\n\ntype Error struct {\n\tMessage string `json:\"message\"`\n}\n\n\n\n\n\nfunc Created(c echo.Context, payload interface{}) error {\n\treturn c.JSON(http.StatusCreated, payload)\n}\n\n\nfunc NoContent(c echo.Context) error {\n\treturn c.NoContent(http.StatusNoContent)\n}\n\n\nfunc BadRequest(c echo.Context, msg string) error {\n\treturn c.JSON(http.StatusBadRequest, Error{msg})\n}\n\n\nfunc NotFound(c echo.Context) error {\n\treturn c.JSON(http.StatusNotFound, Error{\"Resource not found\"})\n}\n\n\nfunc Conflict(c echo.Context, msg string) error {\n\treturn c.JSON(http.StatusConflict, Error{msg})\n}\n\n\nfunc Invalid(c echo.Context, msg string) error {\n\treturn c.JSON(422, Error{msg})\n}\n\n\n\nfunc InternalServerError(c echo.Context, err error) error {\n\tlog.WithFields(log.Fields{\n\t\t\"request_id\": RequestID(c),\n\t}).Error(err)\n\n\treturn c.JSON(http.StatusInternalServerError, Error{\"Oops! Something went wrong\"})\n}\n\nfunc OK(c echo.Context, payload interface{}) error ", "output": "{\n\treturn c.JSON(http.StatusOK, payload)\n}"} {"input": "package token\n\nimport (\n\t\"strings\"\n\n\t\"github.com/carlcui/expressive/locator\"\n)\n\n\ntype Token struct {\n\tTokenType Type\n\tRaw string\n\tLocator locator.Locator\n}\n\nfunc (tok *Token) String() string {\n\treturn tok.TokenType.String() + \": \" + tok.Raw\n}\n\nfunc (tok *Token) GetLocation() string {\n\tif tok.Locator == nil {\n\t\treturn \"unknown location\"\n\t}\n\n\treturn tok.Locator.Locate()\n}\n\n\nfunc IllegalToken(raw string, locator locator.Locator) *Token {\n\treturn &Token{TokenType: ILLEGAL, Raw: raw, Locator: locator}\n}\n\n\nfunc EOFToken(locator locator.Locator) *Token {\n\treturn &Token{TokenType: EOF, Raw: \"\", Locator: locator}\n}\n\n\n\nfunc MatchKeyword(reading string) *Token {\n\tif tokenType, isKeyword := keywords[reading]; isKeyword {\n\t\treturn &Token{TokenType: tokenType, Raw: reading}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc HasOperatorPrefix(reading string) bool {\n\tfor i := operatorStart + 1; i < operatorEnd; i++ {\n\t\tif strings.HasPrefix(tokens[i], reading) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc MatchOperator(reading string) *Token ", "output": "{\n\tif tokenType, isOperator := operators[reading]; isOperator {\n\t\treturn &Token{TokenType: tokenType, Raw: reading}\n\t}\n\n\treturn nil\n}"} {"input": "package channel\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestInitCmdFactory(t *testing.T) ", "output": "{\n\tt.Run(\"InitCmdFactory() with PeerDeliverRequired and OrdererRequired\", func(t *testing.T) {\n\t\tcf, err := InitCmdFactory(EndorserRequired, PeerDeliverRequired, OrdererRequired)\n\t\trequire.Nil(t, cf)\n\t\trequire.Error(t, err)\n\t\trequire.Contains(t, err.Error(), \"ERROR - only a single deliver source is currently supported\")\n\t})\n}"} {"input": "package graphql\n\nimport (\n\t\"errors\"\n\n\t\"github.com/equinux/graphql/gqlerrors\"\n\t\"github.com/equinux/graphql/language/ast\"\n)\n\nfunc NewLocatedError(err interface{}, nodes []ast.Node) *gqlerrors.Error {\n\treturn newLocatedError(err, nodes, nil)\n}\n\nfunc NewLocatedErrorWithPath(err interface{}, nodes []ast.Node, path []interface{}) *gqlerrors.Error {\n\treturn newLocatedError(err, nodes, path)\n}\n\n\n\nfunc FieldASTsToNodeASTs(fieldASTs []*ast.Field) []ast.Node {\n\tnodes := []ast.Node{}\n\tfor _, fieldAST := range fieldASTs {\n\t\tnodes = append(nodes, fieldAST)\n\t}\n\treturn nodes\n}\n\nfunc newLocatedError(err interface{}, nodes []ast.Node, path []interface{}) *gqlerrors.Error ", "output": "{\n\tif err, ok := err.(*gqlerrors.Error); ok {\n\t\treturn err\n\t}\n\n\tvar origError error\n\tmessage := \"An unknown error occurred.\"\n\tif err, ok := err.(error); ok {\n\t\tmessage = err.Error()\n\t\torigError = err\n\t}\n\tif err, ok := err.(string); ok {\n\t\tmessage = err\n\t\torigError = errors.New(err)\n\t}\n\tstack := message\n\treturn gqlerrors.NewErrorWithPath(\n\t\tmessage,\n\t\tnodes,\n\t\tstack,\n\t\tnil,\n\t\t[]int{},\n\t\tpath,\n\t\torigError,\n\t)\n}"} {"input": "package classReader\n\nimport \"math\"\n\ntype ConstantIntegerInfo struct {\n\tval int32\n}\n\nfunc (self *ConstantIntegerInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint32()\n\tself.val = int32(bytes)\n}\n\nfunc (self *ConstantIntegerInfo) Value() int32 {\n\treturn self.val\n}\n\ntype ConstantFloatInfo struct {\n\tval float32\n}\n\nfunc (self *ConstantFloatInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint32()\n\tself.val = math.Float32frombits(bytes)\n}\n\nfunc (self *ConstantFloatInfo) Value() float32 {\n\treturn self.val\n}\n\ntype ConstantLongInfo struct {\n\tval int64\n}\n\n\n\nfunc (self *ConstantLongInfo) Value() int64 {\n\treturn self.val\n}\n\ntype ConstantDoubleInfo struct {\n\tval float64\n}\n\nfunc (self *ConstantDoubleInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint64()\n\tself.val = math.Float64frombits(bytes)\n}\n\nfunc (self *ConstantDoubleInfo) Value() float64 {\n\treturn self.val\n}\n\nfunc (self *ConstantLongInfo) readInfo(reader *ClassReader) ", "output": "{\n\tbytes := reader.readUint64()\n\tself.val = int64(bytes)\n}"} {"input": "package ffdb\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestRecord(t *testing.T) ", "output": "{\n\tdb, err := NewFfdbHeader(\"test.db\", \":\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer db.Close()\n\n\tfor itr := RecordItr(db, Forward); !itr.AtEnd(); itr.Next() {\n\t\tt.Log(itr.Value())\n\t}\n}"} {"input": "package zk\n\nimport \"github.com/go-kit/kit/log\"\n\n\ntype Registrar struct {\n\tclient Client\n\tservice Service\n\tlogger log.Logger\n}\n\n\n\ntype Service struct {\n\tPath string \n\tName string \n\tData []byte \n\tnode string \n}\n\n\n\nfunc NewRegistrar(client Client, service Service, logger log.Logger) *Registrar {\n\treturn &Registrar{\n\t\tclient: client,\n\t\tservice: service,\n\t\tlogger: log.With(logger,\n\t\t\t\"service\", service.Name,\n\t\t\t\"path\", service.Path,\n\t\t\t\"data\", string(service.Data),\n\t\t),\n\t}\n}\n\n\n\n\n\nfunc (r *Registrar) Deregister() {\n\tif err := r.client.Deregister(&r.service); err != nil {\n\t\tr.logger.Log(\"err\", err)\n\t} else {\n\t\tr.logger.Log(\"action\", \"deregister\")\n\t}\n}\n\nfunc (r *Registrar) Register() ", "output": "{\n\tif err := r.client.Register(&r.service); err != nil {\n\t\tr.logger.Log(\"err\", err)\n\t} else {\n\t\tr.logger.Log(\"action\", \"register\")\n\t}\n}"} {"input": "package assertutil\n\n\n\ntype Checker struct {\n\tIsNil func(obtained interface{})\n\tFailNow func()\n}\n\n\nfunc NewChecker(failNow func()) *Checker {\n\treturn &Checker{\n\t\tFailNow: failNow,\n\t}\n}\n\nfunc (c *Checker) failNow() {\n\tc.FailNow()\n}\n\n\n\n\nfunc (c *Checker) AssertNil(obtained interface{}) ", "output": "{\n\tif c.IsNil == nil {\n\t\tc.failNow()\n\t\treturn\n\t}\n\tc.IsNil(obtained)\n}"} {"input": "package predicate\n\nimport (\n\t\"github.com/influxdata/influxdb/v2\"\n\t\"github.com/influxdata/influxdb/v2/kit/platform/errors\"\n\t\"github.com/influxdata/influxdb/v2/storage/reads/datatypes\"\n\t\"github.com/influxdata/influxdb/v2/tsdb/engine/tsm1\"\n)\n\n\ntype Node interface {\n\tToDataType() (*datatypes.Node, error)\n}\n\n\n\n\nfunc New(n Node) (influxdb.Predicate, error) ", "output": "{\n\tif n == nil {\n\t\treturn nil, nil\n\t}\n\n\tdt, err := n.ToDataType()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpred, err := tsm1.NewProtobufPredicate(&datatypes.Predicate{\n\t\tRoot: dt,\n\t})\n\tif err != nil {\n\t\treturn nil, &errors.Error{\n\t\t\tCode: errors.EInvalid,\n\t\t\tErr: err,\n\t\t}\n\t}\n\treturn pred, nil\n}"} {"input": "package node\n\nimport (\n\t\"testing\"\n\n\t\"github.com/freeconf/yang/fc\"\n\t\"github.com/freeconf/yang/meta\"\n)\n\nfunc TestCoerseValue(t *testing.T) {\n\tb := &meta.Builder{}\n\tm := b.Module(\"x\", nil)\n\tl := b.Leaf(m, \"l\")\n\tdt := b.Type(l, \"int32\")\n\tif err := meta.Compile(m); err != nil {\n\t\tt.Error(err)\n\t}\n\tv, err := NewValue(dt, 35)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if v.Value().(int) != 35 {\n\t\tt.Error(\"Coersion error\")\n\t}\n}\n\n\n\nfunc TestToIdentRef(t *testing.T) ", "output": "{\n\tb := &meta.Builder{}\n\tm := b.Module(\"x\", nil)\n\ti0 := b.Identity(m, \"i0\")\n\ti00 := b.Identity(m, \"i00\")\n\tb.Base(i00, \"i0\")\n\tif err := meta.Compile(m); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tref, err := toIdentRef(i0, \"i00\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tfc.AssertEqual(t, \"i00\", ref.Label)\n\tfc.AssertEqual(t, \"i0\", ref.Base)\n}"} {"input": "package chapter5\n\nimport \"testing\"\n\nvar swapbitsTests = []struct {\n\tn uint64\n\ti uint\n\tj uint\n\texpected uint64\n}{\n\t{0, 0, 1, 0},\n\t{2, 0, 1, 1},\n\t{47, 1, 4, 61},\n\t{28, 0, 2, 25},\n}\n\n\n\nfunc TestSwapBits(t *testing.T) ", "output": "{\n\tfor _, tt := range swapbitsTests {\n\t\tactual := SwapBits(tt.n, tt.i, tt.j)\n\t\tif actual != tt.expected {\n\t\t\tt.Errorf(\"SwapBits(%d, %d, %d): expected %d, actual %d\",\n\t\t\t\ttt.n, tt.i, tt.j, tt.expected, actual)\n\t\t}\n\t}\n}"} {"input": "package brdgme\n\n\ntype CommandResponse struct {\n\tLogs []Log\n\tCanUndo bool\n\tRemaining string\n}\n\ntype Status struct {\n\tActive *StatusActive `json:\",omitempty\"`\n\tFinished *StatusFinished `json:\",omitempty\"`\n}\n\ntype StatusActive struct {\n\tWhoseTurn []int `json:\"whose_turn\"`\n\tEliminated []int `json:\"eliminated\"`\n}\n\n\n\ntype StatusFinished struct {\n\tPlacings []int `json:\"placings\"`\n\tStats []interface{} `json:\"stats\"`\n}\n\nfunc (sf StatusFinished) ToStatus() Status {\n\treturn Status{\n\t\tFinished: &sf,\n\t}\n}\n\n\ntype Gamer interface {\n\tNew(players int) ([]Log, error)\n\tPubState() interface{}\n\tPlayerState(player int) interface{}\n\tCommand(\n\t\tplayer int,\n\t\tinput string,\n\t\tplayers []string,\n\t) (CommandResponse, error)\n\tStatus() Status\n\tCommandSpec(player int) *Spec\n\tPlayerCount() int\n\tPlayerCounts() []int\n\tPubRender() string\n\tPlayerRender(player int) string\n\tPoints() []float32\n}\n\nfunc (sa StatusActive) ToStatus() Status ", "output": "{\n\treturn Status{\n\t\tActive: &sa,\n\t}\n}"} {"input": "package chrootarchive\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"github.com/docker/docker/pkg/reexec\"\n)\n\nfunc init() {\n\treexec.Register(\"docker-applyLayer\", applyLayer)\n\treexec.Register(\"docker-untar\", untar)\n}\n\nfunc fatal(err error) {\n\tfmt.Fprint(os.Stderr, err)\n\tos.Exit(1)\n}\n\n\n\n\n\nfunc flush(r io.Reader) ", "output": "{\n\tio.Copy(ioutil.Discard, r)\n}"} {"input": "package linker\n\nimport (\n\t\"errors\"\n\n\tparser \"github.com/moovweb/tritium/parser\"\n\ttp \"github.com/moovweb/tritium/proto\"\n\t. \"github.com/moovweb/tritium/util\"\n)\n\n\n\nfunc RunWithPackage(projectPath, scriptPath, fileName string, pkg *tp.Package, activeLayers []string) (*tp.Transform, error) {\n\tobjs := parser.ParseFileSet(projectPath, scriptPath, fileName, false, activeLayers)\n\treturn runWithObjs(objs, pkg, projectPath, scriptPath)\n}\n\nfunc runWithObjs(objs []*tp.ScriptObject, pkg *tp.Package, projectPath, scriptPath string, ranges ...Range) (*tp.Transform, error) {\n\tctx := NewObjectLinkingContext(pkg, objs, projectPath, scriptPath, ranges...)\n\tctx.Link()\n\tif ctx.HasErrors() {\n\t\tmessage := \"\"\n\t\tfor _, msg := range ctx.Errors {\n\t\t\tmessage = message + \"\\n\" + msg\n\t\t}\n\t\treturn nil, errors.New(message)\n\t}\n\n\treturn ctx.Transform, nil\n}\n\nfunc RunStringWithPackage(src, projectPath, scriptPath, fileName string, pkg *tp.Package, activeLayers []string, ranges ...Range) (*tp.Transform, error) ", "output": "{\n\tobjs := parser.Parse(src, projectPath, scriptPath, fileName, false, activeLayers)\n\treturn runWithObjs(objs, pkg, projectPath, scriptPath, ranges...)\n}"} {"input": "package tfbparser\n\nimport \"github.com/kiwih/goFB/iec61499\"\n\n\ntype tfbParse struct {\n\tfbs []iec61499.FB\n\n\titems []string\n\titemIndex int\n\n\tcurrentLine int\n\tcurrentFile string\n}\n\n\nfunc (t *tfbParse) getCurrentDebugInfo() iec61499.DebugInfo {\n\treturn iec61499.DebugInfo{\n\t\tSourceLine: t.currentLine,\n\t\tSourceFile: t.currentFile,\n\t}\n}\n\n\nfunc (t *tfbParse) isFBNameUnused(name string) bool {\n\tfor i := 0; i < len(t.fbs); i++ {\n\t\tif t.fbs[i].Name == name {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\nfunc (t *tfbParse) pop() string {\n\tif t.done() {\n\t\treturn \"\"\n\t}\n\ts := t.items[t.itemIndex]\n\tt.itemIndex++\n\n\tif s == pNewline {\n\t\tt.currentLine++\n\t\treturn t.pop()\n\t}\n\treturn s\n}\n\n\n\nfunc (t *tfbParse) peek() string {\n\tif t.done() {\n\t\treturn \"\"\n\t}\n\tfor i := 0; i < len(t.items); i++ {\n\t\tif t.items[t.itemIndex+i] != pNewline {\n\t\t\treturn t.items[t.itemIndex+i]\n\t\t}\n\t}\n\treturn \"\"\n}\n\n\n\n\n\n\nfunc (t *tfbParse) getFBIndexFromName(name string) int {\n\tfor i := 0; i < len(t.fbs); i++ {\n\t\tif t.fbs[i].Name == name {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (t *tfbParse) done() bool ", "output": "{\n\treturn t.itemIndex >= len(t.items)\n}"} {"input": "package server\n\nimport (\n\t\"math/rand\"\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n\tlog \"github.com/macarrie/flemzerd/logging\"\n\t\"github.com/macarrie/flemzerd/notifiers\"\n\t\"github.com/macarrie/flemzerd/notifiers/impl/telegram\"\n)\n\nfunc performTelegramAuth(c *gin.Context) {\n\tn, err := notifier.GetNotifier(\"telegram\")\n\tif err != nil || n == nil {\n\t\tlog.Error(\"TELEGRAM NOTIFIER NOT FOUND\")\n\t\tc.JSON(http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\tt := n.(*telegram.TelegramNotifier)\n\tif t.ChatID != 0 {\n\t\tlog.Error(\"CHAT ID NOT ZERO. EXIT STATUS NO CONTENT\")\n\t\tc.AbortWithStatus(http.StatusNoContent)\n\t\treturn\n\t}\n\n\tgo t.Auth()\n\tc.JSON(http.StatusOK, gin.H{})\n\treturn\n}\n\n\n\nfunc getTelegramAuthCode(c *gin.Context) {\n\tn, err := notifier.GetNotifier(\"telegram\")\n\tif err != nil || n == nil {\n\t\tc.JSON(http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\tt := n.(*telegram.TelegramNotifier)\n\tif t.AuthCode == 0 {\n\t\tt.AuthCode = rand.Intn(1000000)\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"auth_code\": t.AuthCode,\n\t})\n}\n\nfunc getTelegramChatID(c *gin.Context) ", "output": "{\n\tn, err := notifier.GetNotifier(\"telegram\")\n\tif err != nil || n == nil {\n\t\tc.JSON(http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\tt := n.(*telegram.TelegramNotifier)\n\tvar chatID int64\n\tif t != nil {\n\t\tchatID = t.ChatID\n\t} else {\n\t\tchatID = 0\n\t}\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"chat_id\": chatID,\n\t})\n}"} {"input": "package fields\n\nimport (\n\t\"regexp\"\n\t\"time\"\n)\n\nfunc UseDefaultKeyIfCustomKeyIsEmpty(defaultKey, customKey string) string {\n\tif \"\" != customKey {\n\t\treturn customKey\n\t}\n\treturn defaultKey\n}\n\nfunc ExecFuncIfErrIsNotNil(err error, fn func()) (b bool) {\n\tif nil != err {\n\t\tfn()\n\t\tb = true\n\t}\n\treturn\n}\n\nfunc getMessageFromError(err error) string {\n\tif nil == err {\n\t\treturn \"\"\n\t}\n\treturn err.Error()\n}\n\nfunc getPatternFromRegExp(re *regexp.Regexp) string {\n\tif nil == re {\n\t\treturn \"\"\n\t}\n\treturn re.String()\n}\n\nfunc execFnIfNotNil(fn func()) {\n\tif nil != fn {\n\t\tfn()\n\t}\n}\n\n\n\nfunc _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) (*time.Location, int) {\n\tif nil == locationByString || \"\" == *locationByString {\n\t\treturn defaultLoc, 1\n\t}\n\n\tif loc, err := time.LoadLocation(*locationByString); nil == err {\n\t\treturn loc, 2\n\t}\n\n\treturn defaultLoc, 0\n}\n\n\nfunc useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) *time.Location {\n\tloc, _ := _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc, locationByString)\n\treturn loc\n}\n\nfunc addSuffix(name string, suffix *string) string ", "output": "{\n\tif nil != suffix {\n\t\treturn name + \"-\" + *suffix\n\t}\n\treturn name\n}"} {"input": "package packr\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/gobuffalo/envy\"\n\t\"github.com/gobuffalo/packr/v2/plog\"\n)\n\nfunc construct(name string, path string) *Box {\n\treturn &Box{\n\t\tPath:\t\tpath,\n\t\tName:\t\tname,\n\t\tResolutionDir:\tresolutionDir(path),\n\t\tresolvers:\tresolversMap{},\n\t\tdirs:\t\tdirsMap{},\n\t}\n}\n\nfunc resolutionDirTestFilename(filename, og string) (string, bool) {\n\tng := filepath.Join(filepath.Dir(filename), og)\n\n\tcov := filepath.Join(\"_test\", \"_obj_test\")\n\tng = strings.Replace(ng, string(filepath.Separator)+cov, \"\", 1)\n\n\tif resolutionDirExists(ng, og) {\n\t\treturn ng, true\n\t}\n\n\tng = filepath.Join(envy.GoPath(), \"src\", ng)\n\tif resolutionDirExists(ng, og) {\n\t\treturn ng, true\n\t}\n\n\treturn og, false\n}\n\nfunc resolutionDirExists(s, og string) bool {\n\t_, err := os.Stat(s)\n\tif err != nil {\n\t\treturn false\n\t}\n\tplog.Debug(\"packr\", \"resolutionDir\", \"original\", og, \"resolved\", s)\n\treturn true\n}\n\n\n\nfunc resolutionDir(og string) string ", "output": "{\n\tng, _ := filepath.Abs(og)\n\n\tif resolutionDirExists(ng, og) {\n\t\treturn ng\n\t}\n\n\t_, filename, _, _ := runtime.Caller(3)\n\tng, ok := resolutionDirTestFilename(filename, og)\n\tif ok {\n\t\treturn ng\n\t}\n\n\t_, filename, _, _ = runtime.Caller(4)\n\tng, ok = resolutionDirTestFilename(filename, og)\n\tif ok {\n\t\treturn ng\n\t}\n\n\treturn og\n}"} {"input": "package http\n\nimport (\n\t\"net/http\"\n\t\"net/http/cookiejar\"\n\t\"net/url\"\n\t\"sync\"\n\n\tc \"github.com/d0ngw/go/common\"\n)\n\n\ntype RetrivedCookieJar struct {\n\tjar *cookiejar.Jar\n\turlCookies map[string][]*http.Cookie\n\tmu sync.Mutex\n}\n\n\n\n\n\nfunc (p *RetrivedCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {\n\tp.jar.SetCookies(u, cookies)\n\tcookieURL := u.String()\n\tif u != nil && cookies != nil {\n\t\tp.mu.Lock()\n\t\tp.urlCookies[cookieURL] = append(p.urlCookies[cookieURL], cookies...)\n\t\tp.mu.Unlock()\n\t}\n}\n\n\nfunc (p *RetrivedCookieJar) Cookies(u *url.URL) []*http.Cookie {\n\treturn p.jar.Cookies(u)\n}\n\n\nfunc (p *RetrivedCookieJar) URLAndCookies() map[string][]*http.Cookie {\n\tall := map[string][]*http.Cookie{}\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tfor k, v := range p.urlCookies {\n\t\tall[k] = v\n\t}\n\treturn all\n}\n\n\nfunc (p *RetrivedCookieJar) SetURLAndCookies(all map[string][]*http.Cookie) error {\n\tif all == nil {\n\t\treturn nil\n\t}\n\n\tfor u, cookies := range all {\n\t\tif cookies == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tcookieURL, err := url.Parse(u)\n\t\tif err != nil {\n\t\t\tc.Errorf(\"parse %s fail,err:%s\", u, err)\n\t\t\tcontinue\n\t\t}\n\t\tp.SetCookies(cookieURL, cookies)\n\t}\n\n\treturn nil\n}\n\nfunc NewRetrivedCookieJar(o *cookiejar.Options) *RetrivedCookieJar ", "output": "{\n\tjar, _ := cookiejar.New(o)\n\treturn &RetrivedCookieJar{\n\t\tjar: jar,\n\t\turlCookies: map[string][]*http.Cookie{},\n\t}\n}"} {"input": "package inst\n\nimport (\n\t\"github.com/github/orchestrator/go/config\"\n)\n\n\ntype Maintenance struct {\n\tMaintenanceId uint\n\tKey InstanceKey\n\tBeginTimestamp string\n\tSecondsElapsed uint\n\tIsActive bool\n\tOwner string\n\tReason string\n}\n\nvar maintenanceOwner string = \"\"\n\n\n\nfunc SetMaintenanceOwner(owner string) {\n\tmaintenanceOwner = owner\n}\n\nfunc GetMaintenanceOwner() string ", "output": "{\n\tif maintenanceOwner != \"\" {\n\t\treturn maintenanceOwner\n\t}\n\treturn config.MaintenanceOwner\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/converter\"\n\t\"strings\"\n)\n\n\ntype CreateScalingTagsRequestBody struct {\n\tTags *[]TagsSingleValue `json:\"tags,omitempty\"`\n\tAction *CreateScalingTagsRequestBodyAction `json:\"action,omitempty\"`\n}\n\n\n\ntype CreateScalingTagsRequestBodyAction struct {\n\tvalue string\n}\n\ntype CreateScalingTagsRequestBodyActionEnum struct {\n\tCREATE CreateScalingTagsRequestBodyAction\n}\n\nfunc GetCreateScalingTagsRequestBodyActionEnum() CreateScalingTagsRequestBodyActionEnum {\n\treturn CreateScalingTagsRequestBodyActionEnum{\n\t\tCREATE: CreateScalingTagsRequestBodyAction{\n\t\t\tvalue: \"create\",\n\t\t},\n\t}\n}\n\nfunc (c CreateScalingTagsRequestBodyAction) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(c.value)\n}\n\nfunc (c *CreateScalingTagsRequestBodyAction) UnmarshalJSON(b []byte) error {\n\tmyConverter := converter.StringConverterFactory(\"string\")\n\tif myConverter != nil {\n\t\tval, err := myConverter.CovertStringToInterface(strings.Trim(string(b[:]), \"\\\"\"))\n\t\tif err == nil {\n\t\t\tc.value = val.(string)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t} else {\n\t\treturn errors.New(\"convert enum data to string error\")\n\t}\n}\n\nfunc (o CreateScalingTagsRequestBody) String() string ", "output": "{\n\tdata, _ := json.Marshal(o)\n\treturn strings.Join([]string{\"CreateScalingTagsRequestBody\", string(data)}, \" \")\n}"} {"input": "package cvv\n\nimport (\n\t\"appengine\"\n\t\"net/http\"\n)\n\n\n\nfunc HandleVoluntarioSave(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tkey := r.URL.Query().Get(\"key\")\n\tv := new(Voluntario)\n\tif parseJsonFromRequest(r, w, v) {\n\t\tctx := appengine.NewContext(r)\n\t\terr := OpVoluntarioSave(ctx, &key, v)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t} else {\n\t\t\tstringifyJsonToResponse(r, w, key)\n\t\t}\n\t}\n\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\n\n\n\n\ntype MsgMemPool struct{}\n\n\n\nfunc (msg *MsgMemPool) BtcDecode(r io.Reader, pver uint32) error {\n\tif pver < BIP0035Version {\n\t\tstr := fmt.Sprintf(\"mempool message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgMemPool.BtcDecode\", str)\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (msg *MsgMemPool) BtcEncode(w io.Writer, pver uint32) error {\n\tif pver < BIP0035Version {\n\t\tstr := fmt.Sprintf(\"mempool message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgMemPool.BtcEncode\", str)\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (msg *MsgMemPool) Command() string {\n\treturn CmdMemPool\n}\n\n\n\n\n\n\n\nfunc NewMsgMemPool() *MsgMemPool {\n\treturn &MsgMemPool{}\n}\n\nfunc (msg *MsgMemPool) MaxPayloadLength(pver uint32) uint32 ", "output": "{\n\treturn 0\n}"} {"input": "package memstats\n\nimport (\n\t\"github.com/mono83/slf\"\n\t\"sync\"\n)\n\n\n\nfunc New() *MemStats {\n\treturn &MemStats{\n\t\tvalues: map[string]int64{},\n\t}\n}\n\n\n\ntype MemStats struct {\n\tm sync.Mutex\n\n\tvalues map[string]int64\n}\n\n\n\n\n\nfunc (m *MemStats) Get(key string) (value int64, found bool) {\n\tm.m.Lock()\n\tdefer m.m.Unlock()\n\n\tvalue, found = m.values[key]\n\treturn\n}\n\n\nfunc (m *MemStats) Values() map[string]int64 {\n\tm.m.Lock()\n\tdefer m.m.Unlock()\n\n\tclone := make(map[string]int64, len(m.values))\n\tfor k, v := range m.values {\n\t\tclone[k] = v\n\t}\n\n\treturn clone\n}\n\nfunc (m *MemStats) Receive(e slf.Event) ", "output": "{\n\tif e.Type == slf.TypeInc {\n\t\tm.m.Lock()\n\t\tprev, _ := m.values[e.Content]\n\t\tm.values[e.Content] = prev + e.I64\n\t\tm.m.Unlock()\n\t} else if e.Type == slf.TypeGauge {\n\t\tm.m.Lock()\n\t\tm.values[e.Content] = e.I64\n\t\tm.m.Unlock()\n\t}\n}"} {"input": "package elements\n\nimport \"github.com/fileformats/graphics/jt/model\"\n\n\n\n\ntype InfiniteLightAttribute struct {\n\tBaseLight\n\tVersionNumber uint8\n\tDirection model.Vector3D\n}\n\nfunc (n InfiniteLightAttribute) GUID() model.GUID {\n\treturn model.InfiniteLightAttributeElement\n}\n\nfunc (n *InfiniteLightAttribute) Read(c *model.Context) error {\n\tc.LogGroup(\"InfiniteLightAttribute\")\n\tdefer c.LogGroupEnd()\n\n\tif err := (&n.BaseLight).Read(c); err != nil {\n\t\treturn err\n\t}\n\n\tif c.Version.Equal(model.V8) {\n\t\tc.Data.Unpack(&n.Direction)\n\t\tn.VersionNumber = uint8(c.Data.Int16())\n\n\t\tif n.VersionNumber == 1 {\n\t\t\tn.CoordSystem = c.Data.Int32()\n\t\t\tc.Log(\"CoordSystem: %d\", n.CoordSystem)\n\t\t}\n\t}\n\n\tif c.Version.Equal(model.V9) {\n\t\tn.VersionNumber = uint8(c.Data.Int16())\n\t\tc.Data.Unpack(&n.Direction)\n\n\t\tif n.VersionNumber == 2 {\n\t\t\tn.ShadowOpacity = c.Data.Float32()\n\t\t\tc.Log(\"ShadowOpacity: %f\", n.ShadowOpacity)\n\t\t}\n\t}\n\n\tif c.Version.GreaterEqThan(model.V10) {\n\t\tn.VersionNumber = c.Data.UInt8()\n\t\tc.Data.Unpack(&n.Direction)\n\t}\n\tc.Log(\"VersionNumber: %d\", n.VersionNumber)\n\tc.Log(\"Direction: %s\", n.Direction)\n\n\n\treturn c.Data.GetError()\n}\n\n\n\nfunc (n *InfiniteLightAttribute) BaseElement() *JTElement {\n\treturn &n.JTElement\n}\n\nfunc (n *InfiniteLightAttribute) GetBaseAttribute() *BaseAttribute ", "output": "{\n\treturn &n.BaseAttribute\n}"} {"input": "package protocol\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc TestTLSProfileValidation(t *testing.T) {\n\n\n\terr := SupportedTLSProfiles.Validate(nil)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected Validate error: %s\", err)\n\t}\n\n\n\tprofiles := TLSProfiles{TLS_PROFILE_RANDOMIZED, \"INVALID-TLS-PROFILE\"}\n\terr = profiles.Validate(nil)\n\tif err == nil {\n\t\tt.Errorf(\"unexpected Validate success\")\n\t}\n\n\n\tcustomProfiles := []string{\"CUSTOM-TLS-PROFILE\"}\n\n\tprofiles = TLSProfiles{TLS_PROFILE_RANDOMIZED, \"CUSTOM-TLS-PROFILE\"}\n\terr = profiles.Validate(customProfiles)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected Validate error: %s\", err)\n\t}\n\n\n\tpruneProfiles := make(TLSProfiles, 0)\n\tfor i, p := range SupportedTLSProfiles {\n\t\tpruneProfiles = append(pruneProfiles, fmt.Sprintf(\"INVALID-PROFILE-%d\", i))\n\t\tpruneProfiles = append(pruneProfiles, p)\n\t}\n\tpruneProfiles = append(pruneProfiles, fmt.Sprintf(\"INVALID-PROFILE-%d\", len(SupportedTLSProfiles)))\n\n\tprunedProfiles := pruneProfiles.PruneInvalid(nil)\n\n\tif !reflect.DeepEqual(prunedProfiles, SupportedTLSProfiles) {\n\t\tt.Errorf(\"unexpected %+v != %+v\", prunedProfiles, SupportedTLSProfiles)\n\t}\n\n\n\tpruneProfiles = TLSProfiles{TLS_PROFILE_RANDOMIZED, \"CUSTOM-TLS-PROFILE\"}\n\n\tprunedProfiles = pruneProfiles.PruneInvalid(customProfiles)\n\n\tif !reflect.DeepEqual(prunedProfiles, pruneProfiles) {\n\t\tt.Errorf(\"unexpected %+v != %+v\", prunedProfiles, pruneProfiles)\n\t}\n}\n\nfunc TestTunnelProtocolValidation(t *testing.T) ", "output": "{\n\n\terr := SupportedTunnelProtocols.Validate()\n\tif err != nil {\n\t\tt.Errorf(\"unexpected Validate error: %s\", err)\n\t}\n\n\tinvalidProtocols := TunnelProtocols{\"OSSH\", \"INVALID-PROTOCOL\"}\n\terr = invalidProtocols.Validate()\n\tif err == nil {\n\t\tt.Errorf(\"unexpected Validate success\")\n\t}\n\n\tpruneProtocols := make(TunnelProtocols, 0)\n\tfor i, p := range SupportedTunnelProtocols {\n\t\tpruneProtocols = append(pruneProtocols, fmt.Sprintf(\"INVALID-PROTOCOL-%d\", i))\n\t\tpruneProtocols = append(pruneProtocols, p)\n\t}\n\tpruneProtocols = append(pruneProtocols, fmt.Sprintf(\"INVALID-PROTOCOL-%d\", len(SupportedTunnelProtocols)))\n\n\tprunedProtocols := pruneProtocols.PruneInvalid()\n\n\tif !reflect.DeepEqual(prunedProtocols, SupportedTunnelProtocols) {\n\t\tt.Errorf(\"unexpected %+v != %+v\", prunedProtocols, SupportedTunnelProtocols)\n\t}\n}"} {"input": "package ladon_test\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sync\"\n\t\"testing\"\n\n\t. \"github.com/ory/ladon\"\n\t\"github.com/ory/ladon/integration\"\n\t. \"github.com/ory/ladon/manager/memory\"\n\t. \"github.com/ory/ladon/manager/sql\"\n)\n\nvar managers = map[string]Manager{}\nvar migrators = map[string]ManagerMigrator{}\n\nfunc TestMain(m *testing.M) {\n\tvar wg sync.WaitGroup\n\twg.Add(3)\n\tconnectMySQL(&wg)\n\tconnectPG(&wg)\n\tconnectMEM(&wg)\n\twg.Wait()\n\n\ts := m.Run()\n\tintegration.KillAll()\n\tos.Exit(s)\n}\n\nfunc connectMEM(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tmanagers[\"memory\"] = NewMemoryManager()\n}\n\n\n\nfunc connectMySQL(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tvar db = integration.ConnectToMySQL()\n\ts := NewSQLManager(db, nil)\n\tif _, err := s.CreateSchemas(\"\", \"\"); err != nil {\n\t\tlog.Fatalf(\"Could not create mysql schema: %v\", err)\n\t}\n\n\tmanagers[\"mysql\"] = s\n\tmigrators[\"mysql\"] = &SQLManagerMigrateFromMajor0Minor6ToMajor0Minor7{\n\t\tDB: db,\n\t\tSQLManager: s,\n\t}\n}\n\nfunc TestGetErrors(t *testing.T) {\n\tfor k, s := range managers {\n\t\tt.Run(\"manager=\"+k, TestHelperGetErrors(s))\n\t}\n}\n\nfunc TestCreateGetDelete(t *testing.T) {\n\tfor k, s := range managers {\n\t\tt.Run(fmt.Sprintf(\"manager=%s\", k), TestHelperCreateGetDelete(s))\n\t}\n}\n\nfunc connectPG(wg *sync.WaitGroup) ", "output": "{\n\tdefer wg.Done()\n\tvar db = integration.ConnectToPostgres(\"ladon\")\n\ts := NewSQLManager(db, nil)\n\tif _, err := s.CreateSchemas(\"\", \"\"); err != nil {\n\t\tlog.Fatalf(\"Could not create postgres schema: %v\", err)\n\t}\n\n\tmanagers[\"postgres\"] = s\n\tmigrators[\"postgres\"] = &SQLManagerMigrateFromMajor0Minor6ToMajor0Minor7{\n\t\tDB: db,\n\t\tSQLManager: s,\n\t}\n}"} {"input": "package sacloud\n\n\ntype propInterfaceDriver struct {\n\tInterfaceDriver EInterfaceDriver `json:\",omitempty\"` \n}\n\n\nfunc (p *propInterfaceDriver) SetInterfaceDriver(v EInterfaceDriver) {\n\tp.InterfaceDriver = v\n}\n\n\nfunc (p *propInterfaceDriver) GetInterfaceDriver() EInterfaceDriver {\n\treturn p.InterfaceDriver\n}\n\n\nfunc (p *propInterfaceDriver) SetInterfaceDriverByString(v string) {\n\tp.InterfaceDriver = EInterfaceDriver(v)\n}\n\n\n\n\nfunc (p *propInterfaceDriver) GetInterfaceDriverString() string ", "output": "{\n\treturn string(p.InterfaceDriver)\n}"} {"input": "package sacloud\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n\ntype AutoBackup struct {\n\t*Resource \n\tpropName \n\tpropDescription \n\tpropServiceClass \n\tpropIcon \n\tpropTags \n\tpropCreatedAt \n\tpropModifiedAt \n\n\tStatus *AutoBackupStatus `json:\",omitempty\"` \n\tProvider *AutoBackupProvider `json:\",omitempty\"` \n\tSettings *AutoBackupSettings `json:\",omitempty\"` \n\n}\n\n\ntype AutoBackupSettings struct {\n\tAccountID json.Number `json:\"AccountId,omitempty\"` \n\tDiskID string `json:\"DiskId,omitempty\"` \n\tZoneID int64 `json:\"ZoneId,omitempty\"` \n\tZoneName string `json:\",omitempty\"` \n\tAutobackup *AutoBackupRecordSets `json:\",omitempty\"` \n\n}\n\n\ntype AutoBackupStatus struct {\n\tAccountID json.Number `json:\"AccountId,omitempty\"` \n\tDiskID string `json:\"DiskId,omitempty\"` \n\tZoneID int64 `json:\"ZoneId,omitempty\"` \n\tZoneName string `json:\",omitempty\"` \n}\n\n\ntype AutoBackupProvider struct {\n\tClass string `json:\",omitempty\"` \n}\n\n\n\n\n\nfunc AllowAutoBackupWeekdays() []string {\n\treturn []string{\"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\", \"sun\"}\n}\n\n\ntype AutoBackupRecordSets struct {\n\tBackupSpanType string \n\tBackupSpanWeekdays []string \n\tMaximumNumberOfArchives int \n\n}\n\n\nfunc (a *AutoBackup) SetBackupSpanWeekdays(weekdays []string) {\n\ta.Settings.Autobackup.BackupSpanWeekdays = weekdays\n}\n\n\nfunc (a *AutoBackup) SetBackupMaximumNumberOfArchives(max int) {\n\ta.Settings.Autobackup.MaximumNumberOfArchives = max\n}\n\nfunc CreateNewAutoBackup(backupName string, diskID int64) *AutoBackup ", "output": "{\n\treturn &AutoBackup{\n\t\tResource: &Resource{},\n\t\tpropName: propName{Name: backupName},\n\t\tStatus: &AutoBackupStatus{\n\t\t\tDiskID: fmt.Sprintf(\"%d\", diskID),\n\t\t},\n\t\tProvider: &AutoBackupProvider{\n\t\t\tClass: \"autobackup\",\n\t\t},\n\t\tSettings: &AutoBackupSettings{\n\t\t\tAutobackup: &AutoBackupRecordSets{\n\t\t\t\tBackupSpanType: \"weekdays\",\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package gluster\n\nimport \"testing\"\n\nfunc init() {\n\tExecRunner = TestRunner{}\n}\n\nfunc TestGetVolumeUsage(t *testing.T) {\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project_pv1\"}\n\n\tvolInfo, _ := getVolumeUsage(\"gl-project-pv1\")\n\n\tequals(t, 49664, volInfo.TotalKiloBytes)\n\tequals(t, 2864, volInfo.UsedKiloBytes)\n}\n\nfunc TestGetVolumeUsage_LongProject(t *testing.T) {\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project--long_pv1\"}\n\n\tvolInfo, _ := getVolumeUsage(\"gl-project-long-pv1\")\n\n\tequals(t, 49664, volInfo.TotalKiloBytes)\n\tequals(t, 2864, volInfo.UsedKiloBytes)\n}\n\nfunc TestGetVolumeUsage_LongProjectHighNumber(t *testing.T) {\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project--very--very--long_pv20\"}\n\n\tvolInfo, _ := getVolumeUsage(\"gl-project-very-very-long-pv20\")\n\n\tequals(t, 49664, volInfo.TotalKiloBytes)\n\tequals(t, 2864, volInfo.UsedKiloBytes)\n}\n\n\n\nfunc TestCheckVolumeUsage_Error(t *testing.T) {\n\toutput = []string{\" 49664 49555 /dev/mapper/vg_mylv_project_pv1\"}\n\n\terr := checkVolumeUsage(\"gl-project-pv1\", \"20\")\n\tassert(t, err != nil, \"Should return error as bigger than threshold\")\n}\n\nfunc TestCheckVolumeUsage_OK(t *testing.T) ", "output": "{\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project_pv1\"}\n\n\terr := checkVolumeUsage(\"gl-project-pv1\", \"20\")\n\tok(t, err)\n}"} {"input": "package tsdb\n\nimport (\n\t\"math/rand\"\n\t\"testing\"\n\n\t\"github.com/influxdata/influxdb/v2/models\"\n)\n\n\n\nfunc TestSeriesID(t *testing.T) ", "output": "{\n\ttypes := []models.FieldType{\n\t\tmodels.Integer,\n\t\tmodels.Float,\n\t\tmodels.Boolean,\n\t\tmodels.String,\n\t\tmodels.Unsigned,\n\t}\n\n\tfor i := 0; i < 1000000; i++ {\n\t\tid := NewSeriesID(uint64(rand.Int31()))\n\t\tfor _, typ := range types {\n\t\t\ttyped := id.WithType(typ)\n\t\t\tif got := typed.Type(); got != typ {\n\t\t\t\tt.Fatalf(\"wanted: %v got: %v\", typ, got)\n\t\t\t}\n\t\t\tif got := typed.SeriesID(); id != got {\n\t\t\t\tt.Fatalf(\"wanted: %016x got: %016x\", id, got)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfmt.Print(\"Enter digits to sum separated by a space:\")\n\tstr, err := getline()\n\tif err == nil {\n\t\tfmt.Println(\"Here is the result:\", sumNumbers(str))\n\t}\n}\n\nfunc getline() (string, error) {\n\treturn bufio.NewReader(os.Stdin).ReadString('\\n')\n}\n\n\n\nfunc sumNumbers(str string) float64 ", "output": "{\n\tvar sum float64\n\tfor _, v := range strings.Fields(str) {\n\t\ti, err := strconv.ParseFloat(v, 64)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t} else {\n\t\t\tsum += i\n\t\t}\n\t}\n\treturn sum\n}"} {"input": "package jaeger\n\nimport \"github.com/containous/traefik/old/log\"\n\n\ntype jaegerLogger struct{}\n\n\n\n\nfunc (l *jaegerLogger) Infof(msg string, args ...interface{}) {\n\tlog.Debugf(msg, args...)\n}\n\nfunc (l *jaegerLogger) Error(msg string) ", "output": "{\n\tlog.Errorf(\"Tracing jaeger error: %s\", msg)\n}"} {"input": "package gopnsconfig\n\nimport (\n\t\"log\"\n)\n\ntype BaseConfigStruct struct {\n\tPortValue string\n\tMetricsServerValue string\n\tMetricsAPIKeyValue string\n\tMetricsPrefixValue string\n}\n\nfunc (this *BaseConfigStruct) Port() string {\n\treturn this.PortValue\n}\n\nfunc (this *BaseConfigStruct) MetricsAPIKey() string {\n\treturn this.MetricsAPIKeyValue\n}\n\nfunc (this *BaseConfigStruct) MetricsServer() string {\n\treturn this.MetricsServerValue\n}\n\nfunc (this *BaseConfigStruct) MetricsPrefix() string {\n\treturn this.MetricsPrefixValue\n}\n\ntype BaseConfig interface {\n\tPort() string\n\tMetricsServer() string\n\tMetricsAPIKey() string\n\tMetricsPrefix() string\n}\n\n\n\nfunc parseBaseConfig(baseConfig *ConfigFile) BaseConfig ", "output": "{\n\tport, err := baseConfig.GetString(\"default\", \"port\")\n\tcheckError(\"Unable to find Server Port\", err)\n\n\tmetricsServer, err := baseConfig.GetString(\"default\", \"metrics-server\")\n\tcheckError(\"Unable to find metrics server\", err)\n\n\tmetricsKey, err := baseConfig.GetString(\"default\", \"metrics-api-key\")\n\tif err != nil {\n\t\tlog.Println(\"Unable to find metrics-api-key using empty string\")\n\t\tmetricsKey = \"\"\n\t}\n\n\tmetricsPrefix, err := baseConfig.GetString(\"default\", \"metrics-prefix\")\n\tif err != nil {\n\t\tlog.Println(\"Unable to find metrics prefix using empty string\")\n\t\tmetricsPrefix = \"\"\n\t}\n\n\tbaseConfigInstance := &BaseConfigStruct{port, metricsServer, metricsKey, metricsPrefix}\n\treturn baseConfigInstance\n\n}"} {"input": "package factor\n\nimport (\n\t\"github.com/jesand/stats\"\n\t\"github.com/jesand/stats/dist\"\n\t\"github.com/jesand/stats/variable\"\n)\n\n\n\n\ntype Factor interface {\n\n\tAdjacent() []variable.RandomVariable\n\n\tScore() float64\n}\n\n\n\n\nfunc NewDistFactor(vars []variable.RandomVariable, distr dist.Dist) *DistFactor {\n\treturn &DistFactor{\n\t\tVars: vars,\n\t\tDist: distr,\n\t}\n}\n\n\ntype DistFactor struct {\n\tVars []variable.RandomVariable\n\tDist dist.Dist\n}\n\n\nfunc (factor DistFactor) Adjacent() []variable.RandomVariable {\n\treturn factor.Vars\n}\n\n\nfunc (factor DistFactor) Score() float64 {\n\tvar (\n\t\tnumVars = factor.Dist.NumVars()\n\t\tnumParams = factor.Dist.NumParams()\n\t)\n\tif len(factor.Vars) != numVars+numParams {\n\t\tpanic(stats.ErrfFactorVarNum(numVars, numParams, len(factor.Vars)))\n\t}\n\tvar (\n\t\tvars = make([]float64, numVars)\n\t\tparams = make([]float64, numParams)\n\t)\n\tfor i, rv := range factor.Vars {\n\t\tif i < len(vars) {\n\t\t\tvars[i] = rv.Val()\n\t\t} else {\n\t\t\tparams[i-len(vars)] = rv.Val()\n\t\t}\n\t}\n\treturn factor.Dist.Score(vars, params)\n}\n\n\nfunc NewConstFactor(vars []variable.RandomVariable, value float64) *ConstFactor {\n\treturn &ConstFactor{\n\t\tVars: vars,\n\t\tValue: value,\n\t}\n}\n\n\ntype ConstFactor struct {\n\tVars []variable.RandomVariable\n\tValue float64\n}\n\n\n\n\n\nfunc (factor ConstFactor) Score() float64 {\n\treturn factor.Value\n}\n\nfunc (factor ConstFactor) Adjacent() []variable.RandomVariable ", "output": "{\n\treturn factor.Vars\n}"} {"input": "package util\n\n\ntype DeviceUtil interface {\n\tFindMultipathDeviceForDevice(disk string) string\n}\n\ntype deviceHandler struct {\n\tget_io IoUtil\n}\n\n\n\n\nfunc NewDeviceHandler(io IoUtil) DeviceUtil ", "output": "{\n\treturn &deviceHandler{get_io: io}\n}"} {"input": "package v1alpha1\n\nimport (\n\tv1alpha1 \"github.com/appscode/searchlight/apis/incidents/v1alpha1\"\n\t\"github.com/appscode/searchlight/client/clientset/versioned/scheme\"\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype IncidentsV1alpha1Interface interface {\n\tRESTClient() rest.Interface\n\tAcknowledgementsGetter\n}\n\n\ntype IncidentsV1alpha1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *IncidentsV1alpha1Client) Acknowledgements(namespace string) AcknowledgementInterface {\n\treturn newAcknowledgements(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*IncidentsV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &IncidentsV1alpha1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *IncidentsV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *IncidentsV1alpha1Client {\n\treturn &IncidentsV1alpha1Client{c}\n}\n\n\n\n\n\nfunc (c *IncidentsV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc setConfigDefaults(config *rest.Config) error ", "output": "{\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\tgolangswaggerpaths \"path\"\n\t\"strings\"\n)\n\n\ntype CommissionSiteURL struct {\n\tID string\n\n\t_basePath string\n\t_ struct{}\n}\n\n\n\n\nfunc (o *CommissionSiteURL) WithBasePath(bp string) *CommissionSiteURL {\n\to.SetBasePath(bp)\n\treturn o\n}\n\n\n\n\nfunc (o *CommissionSiteURL) SetBasePath(bp string) {\n\to._basePath = bp\n}\n\n\n\n\n\nfunc (o *CommissionSiteURL) Must(u *url.URL, err error) *url.URL {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif u == nil {\n\t\tpanic(\"url can't be nil\")\n\t}\n\treturn u\n}\n\n\nfunc (o *CommissionSiteURL) String() string {\n\treturn o.Must(o.Build()).String()\n}\n\n\nfunc (o *CommissionSiteURL) BuildFull(scheme, host string) (*url.URL, error) {\n\tif scheme == \"\" {\n\t\treturn nil, errors.New(\"scheme is required for a full url on CommissionSiteURL\")\n\t}\n\tif host == \"\" {\n\t\treturn nil, errors.New(\"host is required for a full url on CommissionSiteURL\")\n\t}\n\n\tbase, err := o.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbase.Scheme = scheme\n\tbase.Host = host\n\treturn base, nil\n}\n\n\nfunc (o *CommissionSiteURL) StringFull(scheme, host string) string {\n\treturn o.Must(o.BuildFull(scheme, host)).String()\n}\n\nfunc (o *CommissionSiteURL) Build() (*url.URL, error) ", "output": "{\n\tvar result url.URL\n\n\tvar _path = \"/sites/{id}\"\n\n\tid := o.ID\n\tif id != \"\" {\n\t\t_path = strings.Replace(_path, \"{id}\", id, -1)\n\t} else {\n\t\treturn nil, errors.New(\"ID is required on CommissionSiteURL\")\n\t}\n\n\t_basePath := o._basePath\n\tif _basePath == \"\" {\n\t\t_basePath = \"/\"\n\t}\n\tresult.Path = golangswaggerpaths.Join(_basePath, _path)\n\n\treturn &result, nil\n}"} {"input": "package readline\n\nimport \"io\"\n\ntype Instance struct {\n\tt *Terminal\n\to *Operation\n}\n\ntype Config struct {\n\tPrompt string\n\tHistoryFile string\n}\n\nfunc NewEx(cfg *Config) (*Instance, error) {\n\tt, err := NewTerminal(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trl := t.Readline()\n\treturn &Instance{\n\t\tt: t,\n\t\to: rl,\n\t}, nil\n}\n\n\n\nfunc (i *Instance) Stdout() io.Writer {\n\treturn i.o.Stdout()\n}\n\nfunc (i *Instance) Stderr() io.Writer {\n\treturn i.o.Stderr()\n}\n\nfunc (i *Instance) Readline() (string, error) {\n\treturn i.o.String()\n}\n\nfunc (i *Instance) ReadSlice() ([]byte, error) {\n\treturn i.o.Slice()\n}\n\nfunc (i *Instance) Close() error {\n\tif err := i.t.Close(); err != nil {\n\t\treturn err\n\t}\n\ti.o.Close()\n\treturn nil\n}\n\nfunc New(prompt string) (*Instance, error) ", "output": "{\n\treturn NewEx(&Config{Prompt: prompt})\n}"} {"input": "package chshare\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\n\ntype Logger struct {\n\tprefix string\n\tlogger *log.Logger\n\tInfo, Debug bool\n}\n\nfunc NewLogger(prefix string) *Logger {\n\treturn NewLoggerFlag(prefix, log.Ldate|log.Ltime)\n}\n\n\n\nfunc (l *Logger) Infof(f string, args ...interface{}) {\n\tif l.Info {\n\t\tl.logger.Printf(l.prefix+\": \"+f, args...)\n\t}\n}\n\nfunc (l *Logger) Debugf(f string, args ...interface{}) {\n\tif l.Debug {\n\t\tl.logger.Printf(l.prefix+\": \"+f, args...)\n\t}\n}\n\nfunc (l *Logger) Errorf(f string, args ...interface{}) error {\n\treturn fmt.Errorf(l.prefix+\": \"+f, args...)\n}\n\nfunc (l *Logger) Fork(prefix string, args ...interface{}) *Logger {\n\targs = append([]interface{}{l.prefix}, args...)\n\tll := NewLogger(fmt.Sprintf(\"%s: \"+prefix, args...))\n\tll.Info = l.Info\n\tll.Debug = l.Debug\n\treturn ll\n}\n\nfunc (l *Logger) Prefix() string {\n\treturn l.prefix\n}\n\nfunc NewLoggerFlag(prefix string, flag int) *Logger ", "output": "{\n\tl := &Logger{\n\t\tprefix: prefix,\n\t\tlogger: log.New(os.Stdout, \"\", flag),\n\t\tInfo: false,\n\t\tDebug: false,\n\t}\n\treturn l\n}"} {"input": "package labels\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\tnetwork \"knative.dev/networking/pkg\"\n\t\"knative.dev/serving/pkg/apis/serving\"\n)\n\n\n\n\n\nfunc SetVisibility(meta *metav1.ObjectMeta, isClusterLocal bool) {\n\tif isClusterLocal {\n\t\tSetLabel(meta, network.VisibilityLabelKey, serving.VisibilityClusterLocal)\n\t} else {\n\t\tDeleteLabel(meta, network.VisibilityLabelKey)\n\t}\n}\n\n\nfunc SetLabel(meta *metav1.ObjectMeta, key, value string) {\n\tif meta.Labels == nil {\n\t\tmeta.Labels = make(map[string]string, 1)\n\t}\n\n\tmeta.Labels[key] = value\n}\n\n\nfunc DeleteLabel(meta *metav1.ObjectMeta, key string) {\n\tdelete(meta.Labels, key)\n}\n\nfunc IsObjectLocalVisibility(meta *metav1.ObjectMeta) bool ", "output": "{\n\treturn meta.Labels[network.VisibilityLabelKey] != \"\"\n}"} {"input": "package testutil\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\ntype Context struct {\n\tName string `yaml:\"name,omitempty\"`\n\tContext struct {\n\t\tNamespace string `yaml:\"namespace,omitempty\"`\n\t} `yaml:\"context,omitempty\"`\n}\n\nfunc Ctx(name string) *Context { return &Context{Name: name} }\nfunc (c *Context) Ns(ns string) *Context { c.Context.Namespace = ns; return c }\n\ntype Kubeconfig map[string]interface{}\n\nfunc KC() *Kubeconfig {\n\treturn &Kubeconfig{\n\t\t\"apiVersion\": \"v1\",\n\t\t\"kind\": \"Config\"}\n}\n\nfunc (k *Kubeconfig) Set(key string, v interface{}) *Kubeconfig { (*k)[key] = v; return k }\nfunc (k *Kubeconfig) WithCurrentCtx(s string) *Kubeconfig { (*k)[\"current-context\"] = s; return k }\n\n\nfunc (k *Kubeconfig) ToYAML(t *testing.T) string {\n\tt.Helper()\n\tvar v strings.Builder\n\tif err := yaml.NewEncoder(&v).Encode(*k); err != nil {\n\t\tt.Fatalf(\"failed to encode mock kubeconfig: %v\", err)\n\t}\n\treturn v.String()\n}\n\nfunc (k *Kubeconfig) WithCtxs(c ...*Context) *Kubeconfig ", "output": "{ (*k)[\"contexts\"] = c; return k }"} {"input": "package shoauth\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\ntype expectedSuccessHandler struct{}\n\nfunc (s *expectedSuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}\n\ntype expectedFailureHandler struct{}\n\nfunc (s *expectedFailureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}\n\ntype unexpectedSuccessHandler struct {\n\tt *testing.T\n}\n\nfunc (s *unexpectedSuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.t.Errorf(\"Request should have failed, but succeeded instead!\")\n}\n\ntype unexpectedFailureHandler struct {\n\tt *testing.T\n}\n\nfunc (s *unexpectedFailureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.t.Errorf(\"Request should have succeeded, but failed instead!\")\n}\n\ntype testPersistence struct {\n\texists bool\n\tcreate error\n\tsession bool\n}\n\nfunc (t *testPersistence) InstallationExists(shopID string) bool {\n\treturn t.exists\n}\n\nfunc (t *testPersistence) CreateInstallation(shopID string, accessToken string) error {\n\treturn t.create\n}\n\n\n\nfunc TestAlreadyInstalled(t *testing.T) ", "output": "{\n\tp := testPersistence{\n\t\texists: true,\n\t\tcreate: errors.New(\"Installation already exists!\"),\n\t\tsession: false,\n\t}\n\thandler := NewShopifyOauthHandler(&unexpectedSuccessHandler{t: t}, &expectedFailureHandler{}, &p)\n\ttestServer := httptest.NewServer(handler)\n\tdefer testServer.Close()\n\thttp.Get(testServer.URL + \"/install\")\n}"} {"input": "package loganalytics\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype LogAnalyticsParserMetaPluginCollection struct {\n\n\tItems []LogAnalyticsParserMetaPlugin `mandatory:\"false\" json:\"items\"`\n}\n\n\n\nfunc (m LogAnalyticsParserMetaPluginCollection) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package cloudfoundry_test\n\nimport (\n\t\"github.com/javiermanzano/goth\"\n\t\"github.com/javiermanzano/goth/providers/cloudfoundry\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc Test_New(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\tp := provider()\n\n\ta.Equal(p.ClientKey, os.Getenv(\"UAA_CLIENT_ID\"))\n\ta.Equal(p.Secret, os.Getenv(\"UAA_CLIENT_SECRET\"))\n\ta.Equal(p.CallbackURL, \"/foo\")\n}\n\nfunc Test_Implements_Provider(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\ta.Implements((*goth.Provider)(nil), provider())\n}\n\nfunc Test_BeginAuth(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\tp := provider()\n\tsession, err := p.BeginAuth(\"test_state\")\n\ts := session.(*cloudfoundry.Session)\n\ta.NoError(err)\n\ta.Contains(s.AuthURL, \"https://cf.example.com/oauth/authorize\")\n}\n\nfunc Test_SessionFromJSON(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\n\tp := provider()\n\tsession, err := p.UnmarshalSession(`{\"AuthURL\":\"https://cf.example.com/oauth/authorize\",\"AccessToken\":\"1234567890\"}`)\n\ta.NoError(err)\n\n\ts := session.(*cloudfoundry.Session)\n\ta.Equal(s.AuthURL, \"https://cf.example.com/oauth/authorize\")\n\ta.Equal(s.AccessToken, \"1234567890\")\n}\n\n\n\nfunc provider() *cloudfoundry.Provider ", "output": "{\n\treturn cloudfoundry.New(\"https://cf.example.com/\", os.Getenv(\"UAA_CLIENT_ID\"), os.Getenv(\"UAA_CLIENT_SECRET\"), \"/foo\")\n}"} {"input": "package scheduler\n\nimport (\n\t\"fmt\"\n\t\"github.com/jonaz/astrotime\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"time\"\n)\n\nfunc isSunset(latitude float64, longitude float64) bool {\n\tt := astrotime.NextSunset(time.Now(), latitude, longitude)\n\tif t.Hour() == time.Now().Hour() && t.Minute() == time.Now().Minute() {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc Start(intervalInSeconds int, latitude float64, longitude float64, autoNightLights []int64) {\n\tticker := time.NewTicker(time.Millisecond * time.Duration(intervalInSeconds))\n\tgo func() {\n\t\tfor t := range ticker.C {\n\t\t\tvar state string\n\t\t\tvar changeLights bool\n\t\t\tif isSunset(latitude, longitude) {\n\t\t\t\tfmt.Println(\"Sunset\", t)\n\t\t\t\tstate = \"ON\"\n\t\t\t\tchangeLights = true\n\t\t\t} else if isSunrise(latitude, longitude) {\n\t\t\t\tfmt.Println(\"Sunrise\", t)\n\t\t\t\tstate = \"OFF\"\n\t\t\t\tchangeLights = true\n\t\t\t}\n\t\t\tif changeLights == true {\n\t\t\t\tfmt.Println(\"Updating lights\")\n\t\t\t\tfor _, light := range autoNightLights {\n\t\t\t\t\targs := []string{\"-u\", \"-m\" + strconv.FormatInt(light, 10), \"-t1\", \"-v\" + state}\n\t\t\t\t\tcmd := exec.Command(\"/usr/sbin/aprontest\", args...)\n\t\t\t\t\tcmd.Run()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc isSunrise(latitude float64, longitude float64) bool ", "output": "{\n\tt := astrotime.NextSunrise(time.Now(), latitude, longitude)\n\ttzname, _ := t.Zone()\n\tif t.Hour() == time.Now().Hour() && t.Minute() == time.Now().Minute() {\n\t\tfmt.Printf(\"The sunrise is %d:%02d %s on %d/%d/%d.\\n\", t.Hour(), t.Minute(), tzname, t.Month(), t.Day(), t.Year())\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package roles\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestIsTopLevelRole(t *testing.T) {\n\tassert.True(t, IsTopLevelRole(\"root\"))\n\tassert.True(t, IsTopLevelRole(\"targets\"))\n\tassert.True(t, IsTopLevelRole(\"timestamp\"))\n\tassert.True(t, IsTopLevelRole(\"snapshot\"))\n\tassert.False(t, IsTopLevelRole(\"bins\"))\n}\n\n\n\nfunc TestIsTopLevelManifest(t *testing.T) {\n\tassert.True(t, IsTopLevelManifest(\"root.json\"))\n\tassert.True(t, IsTopLevelManifest(\"targets.json\"))\n\tassert.True(t, IsTopLevelManifest(\"timestamp.json\"))\n\tassert.True(t, IsTopLevelManifest(\"snapshot.json\"))\n\tassert.False(t, IsTopLevelManifest(\"bins.json\"))\n}\n\nfunc TestIsDelegatedTargetsManifest(t *testing.T) {\n\tassert.False(t, IsDelegatedTargetsManifest(\"root.json\"))\n\tassert.False(t, IsDelegatedTargetsManifest(\"targets.json\"))\n\tassert.False(t, IsDelegatedTargetsManifest(\"timestamp.json\"))\n\tassert.False(t, IsDelegatedTargetsManifest(\"snapshot.json\"))\n\tassert.True(t, IsDelegatedTargetsManifest(\"bins.json\"))\n}\n\nfunc TestIsVersionedManifest(t *testing.T) {\n\tassert.False(t, IsVersionedManifest(\"a.b\"))\n\tassert.False(t, IsVersionedManifest(\"a.b.c\"))\n\tassert.False(t, IsVersionedManifest(\"a.b.json\"))\n\tassert.False(t, IsVersionedManifest(\"1.a\"))\n\tassert.True(t, IsVersionedManifest(\"1.a.json\"))\n\tassert.True(t, IsVersionedManifest(\"2.a.json\"))\n}\n\nfunc TestIsDelegatedTargetsRole(t *testing.T) ", "output": "{\n\tassert.False(t, IsDelegatedTargetsRole(\"root\"))\n\tassert.False(t, IsDelegatedTargetsRole(\"targets\"))\n\tassert.False(t, IsDelegatedTargetsRole(\"timestamp\"))\n\tassert.False(t, IsDelegatedTargetsRole(\"snapshot\"))\n\tassert.True(t, IsDelegatedTargetsRole(\"deleg\"))\n}"} {"input": "package cdn\n\nimport (\n\t. \"aliyun-openapi-go-sdk/core\"\n\t\"strconv\"\n)\n\ntype OpenCdnServiceRequest struct {\n\tRpcRequest\n\tOwnerId int\n\tResourceOwnerAccount string\n\tResourceOwnerId int\n\tInternetChargeType string\n}\n\nfunc (r *OpenCdnServiceRequest) SetOwnerId(value int) {\n\tr.OwnerId = value\n\tr.QueryParams.Set(\"OwnerId\", strconv.Itoa(value))\n}\nfunc (r *OpenCdnServiceRequest) GetOwnerId() int {\n\treturn r.OwnerId\n}\nfunc (r *OpenCdnServiceRequest) SetResourceOwnerAccount(value string) {\n\tr.ResourceOwnerAccount = value\n\tr.QueryParams.Set(\"ResourceOwnerAccount\", value)\n}\nfunc (r *OpenCdnServiceRequest) GetResourceOwnerAccount() string {\n\treturn r.ResourceOwnerAccount\n}\nfunc (r *OpenCdnServiceRequest) SetResourceOwnerId(value int) {\n\tr.ResourceOwnerId = value\n\tr.QueryParams.Set(\"ResourceOwnerId\", strconv.Itoa(value))\n}\nfunc (r *OpenCdnServiceRequest) GetResourceOwnerId() int {\n\treturn r.ResourceOwnerId\n}\nfunc (r *OpenCdnServiceRequest) SetInternetChargeType(value string) {\n\tr.InternetChargeType = value\n\tr.QueryParams.Set(\"InternetChargeType\", value)\n}\nfunc (r *OpenCdnServiceRequest) GetInternetChargeType() string {\n\treturn r.InternetChargeType\n}\n\nfunc (r *OpenCdnServiceRequest) Init() {\n\tr.RpcRequest.Init()\n\tr.SetVersion(Version)\n\tr.SetAction(\"OpenCdnService\")\n\tr.SetProduct(Product)\n}\n\ntype OpenCdnServiceResponse struct {\n}\n\n\n\nfunc OpenCdnService(req *OpenCdnServiceRequest, accessId, accessSecret string) (*OpenCdnServiceResponse, error) ", "output": "{\n\tvar pResponse OpenCdnServiceResponse\n\tbody, err := ApiHttpRequest(accessId, accessSecret, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tApiUnmarshalResponse(req.GetFormat(), body, &pResponse)\n\treturn &pResponse, err\n}"} {"input": "package sqlbuilder\n\n\ntype DeleteStatement struct {\n\tfrom Table\n\twhere Condition\n\n\terr error\n}\n\n\nfunc Delete(from Table) *DeleteStatement {\n\tif from == nil {\n\t\treturn &DeleteStatement{\n\t\t\terr: newError(\"from is nil.\"),\n\t\t}\n\t}\n\tif _, ok := from.(*table); !ok {\n\t\treturn &DeleteStatement{\n\t\t\terr: newError(\"CreateTable can use only natural table.\"),\n\t\t}\n\t}\n\treturn &DeleteStatement{\n\t\tfrom: from,\n\t}\n}\n\n\nfunc (b *DeleteStatement) Where(cond Condition) *DeleteStatement {\n\tif b.err != nil {\n\t\treturn b\n\t}\n\tfor _, col := range cond.columns() {\n\t\tif !b.from.hasColumn(col) {\n\t\t\tb.err = newError(\"column not found in FROM\")\n\t\t\treturn b\n\t\t}\n\t}\n\tb.where = cond\n\treturn b\n}\n\n\n\n\nfunc (b *DeleteStatement) ToSql() (query string, args []interface{}, err error) ", "output": "{\n\tbldr := newBuilder()\n\tdefer func() {\n\t\tquery, args, err = bldr.Query(), bldr.Args(), bldr.Err()\n\t}()\n\tif b.err != nil {\n\t\tbldr.SetError(b.err)\n\t\treturn\n\t}\n\n\tbldr.Append(\"DELETE FROM \")\n\tbldr.AppendItem(b.from)\n\n\tif b.where != nil {\n\t\tbldr.Append(\" WHERE \")\n\t\tbldr.AppendItem(b.where)\n\t}\n\treturn\n}"} {"input": "package blend_test\n\nimport (\n\t\"image/color\"\n\t\"testing\"\n\n\t\"github.com/tv42/quobar/blend\"\n)\n\nvar (\n\twhite = color.RGBA{R: 255, G: 255, B: 255, A: 255}\n\tgreen = color.RGBA{R: 0, G: 255, B: 0, A: 255}\n\tyellow = color.RGBA{R: 255, G: 255, B: 0, A: 255}\n\tred = color.RGBA{R: 255, G: 0, B: 0, A: 255}\n)\n\nvar trafficLights = []blend.Threshold{\n\t{\n\t\tMax: 1024,\n\t\tColor: white,\n\t},\n\t{\n\t\tMax: 768,\n\t\tColor: green,\n\t},\n\t{\n\t\tMax: 512,\n\t\tColor: yellow,\n\t},\n\t{\n\t\tMax: 256,\n\t\tColor: red,\n\t},\n}\n\nfunc TestPickColorKnown(t *testing.T) {\n\tfor idx, test := range []struct {\n\t\tinput uint64\n\t\texpect color.Color\n\t}{\n\t\t{9000, white},\n\t\t{100, red},\n\t\t{0, red},\n\t\t{1024, white},\n\t\t{768, green},\n\t\t{512, yellow},\n\t\t{256, red},\n\t} {\n\t\tif g, e := blend.PickColor(trafficLights, test.input), color.RGBA64Model.Convert(test.expect); g != e {\n\t\t\tt.Errorf(\"#%d: value %d wrong color: %v != %v\", idx, test.input, g, e)\n\t\t}\n\t}\n}\n\n\n\nfunc TestPickColorEmpty(t *testing.T) ", "output": "{\n\tif g, e := blend.PickColor(nil, 42), color.Black; g != e {\n\t\tt.Errorf(\"wrong color for empty slice: %v != %v\", g, e)\n\t}\n}"} {"input": "package cask\n\nimport (\n\t\"bytes\"\n\t\"unicode\"\n)\n\n\ntype TokenType int\n\n\nconst (\n\tEOF TokenType = iota \n\tILLEGAL \n\n\n\tCONST\n\tGLOBAL\n\tIDENT\n\tINT\n\tSTRING\n\tSYMBOL \n\n\n\tPNREGEXP \n\tPNSTART \n\tPNEND \n\n\n\tHEREDOC\n\tHEREDOCSTART\n\tHEREDOCEND\n\n\n\tASSIGN \n\tASTERISK \n\tBANG \n\tMINUS \n\tPLUS \n\tSLASH \n\tMODULUS \n\n\tEQ \n\tGT \n\tLT \n\tNOTEQ \n\n\n\tCOMMA \n\tNEWLINE \n\tSEMICOLON \n\n\tCOLON \n\tDOT \n\tLBRACE \n\tLBRACKET \n\tLPAREN \n\tPIPE \n\tRBRACE \n\tRBRACKET \n\tRPAREN \n\n\tSCOPE \n\n\n\tREGEXP\n\n\n\tCLASS\n\tDEF\n\tDO\n\tELSE\n\tELSEIF\n\tEND\n\tFALSE\n\tIF\n\tMODULE\n\tNIL\n\tRETURN\n\tSELF\n\tTHEN\n\tTRUE\n\tYIELD\n)\n\nvar keywords = map[string]TokenType{\n\t\"class\": CLASS,\n\t\"def\": DEF,\n\t\"do\": DO,\n\t\"else\": ELSE,\n\t\"end\": END,\n\t\"false\": FALSE,\n\t\"if\": IF,\n\t\"elsif\": ELSEIF,\n\t\"module\": MODULE,\n\t\"nil\": NIL,\n\t\"return\": RETURN,\n\t\"self\": SELF,\n\t\"then\": THEN,\n\t\"true\": TRUE,\n\t\"yield\": YIELD,\n}\n\n\n\n\n\n\nfunc LookupIdent(ident string) TokenType ", "output": "{\n\tif tok, ok := keywords[ident]; ok {\n\t\treturn tok\n\t}\n\n\tif unicode.IsUpper(bytes.Runes([]byte(ident))[0]) {\n\t\treturn CONST\n\t}\n\n\treturn IDENT\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n)\n\n\n\nfunc Handle() {\n\thttp.Handle(\"/\", NewRouter())\n}\n\nfunc Run() ", "output": "{\n\tHandle()\n\thttp.ListenAndServe(\":8080\", nil)\n}"} {"input": "package b\n\nimport \"./a\"\n\nfunc F() {\n\ta.F()\n\ta.Fi()\n}\n\nfunc Fp() {\n\ta.Fp()\n\ta.Fip()\n}\n\n\n\nfunc Hp() {\n\ta.Hp()\n\ta.Hip()\n}\n\nfunc Gp() ", "output": "{\n\ta.Gp()\n\ta.Gip()\n}"} {"input": "package data\n\n\n\n\ntype Material struct {\n\tName string \n\tKd Rgb \n\tKa Rgb \n\tKs Rgb \n\tTr float32 \n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Rgb struct {\n\tR float32 \n\tG float32 \n\tB float32 \n}\n\nfunc newMaterial(name string, kd, ka, ks *Rgb, tr float32) *Material ", "output": "{\n\tif ka == nil {\n\t\tka = &Rgb{}\n\t}\n\tif ks == nil {\n\t\tks = &Rgb{}\n\t}\n\tif kd == nil {\n\t\tkd = &Rgb{}\n\t}\n\treturn &Material{name, *kd, *ka, *ks, tr}\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/NebulousLabs/Sia/build\"\n\t\"github.com/NebulousLabs/Sia/types\"\n)\n\n\n\ntype ConsensusGET struct {\n\tHeight types.BlockHeight `json:\"height\"`\n\tCurrentBlock types.BlockID `json:\"currentblock\"`\n\tTarget types.Target `json:\"target\"`\n}\n\n\nfunc (srv *Server) consensusHandlerGET(w http.ResponseWriter, req *http.Request) {\n\tid := srv.mu.RLock()\n\tdefer srv.mu.RUnlock(id)\n\n\tcurblockID := srv.currentBlock.ID()\n\tcurrentTarget, exists := srv.cs.ChildTarget(curblockID)\n\tif build.DEBUG {\n\t\tif !exists {\n\t\t\tfmt.Printf(\"Could not find block %s\\n\", curblockID)\n\t\t\tpanic(\"server has nonexistent current block\")\n\t\t}\n\t}\n\n\twriteJSON(w, ConsensusGET{\n\t\tHeight: types.BlockHeight(srv.blockchainHeight),\n\t\tCurrentBlock: srv.currentBlock.ID(),\n\t\tTarget: currentTarget,\n\t})\n}\n\n\n\n\nfunc (srv *Server) consensusHandler(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tif req.Method == \"\" || req.Method == \"GET\" {\n\t\tsrv.consensusHandlerGET(w, req)\n\t\treturn\n\t}\n\twriteError(w, \"unrecognized method when calling /consensus\", http.StatusBadRequest)\n}"} {"input": "package sliceset\n\nimport (\n\t\"sort\"\n\n\t\"github.com/xtgo/set\"\n)\n\ntype Set []int\n\nfunc (s Set) Len() int { return len(s) }\nfunc (s Set) Less(i, j int) bool { return s[i] < s[j] }\nfunc (s Set) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s Set) Copy() Set { return append(Set(nil), s...) }\n\nfunc (s Set) Union(t Set) Set { return s.Do(set.Union, t) }\nfunc (s Set) Inter(t Set) Set { return s.Do(set.Inter, t) }\nfunc (s Set) Diff(t Set) Set { return s.Do(set.Diff, t) }\nfunc (s Set) SymDiff(t Set) Set { return s.Do(set.SymDiff, t) }\n\nfunc (s Set) IsSuper(t Set) bool { return s.DoBool(set.IsSuper, t) }\nfunc (s Set) IsInter(t Set) bool { return s.DoBool(set.IsInter, t) }\nfunc (s Set) IsEqual(t Set) bool { return s.DoBool(set.IsEqual, t) }\n\nfunc (s Set) Uniq() Set {\n\tn := set.Uniq(s)\n\treturn s[:n]\n}\n\nfunc (s Set) Do(op set.Op, t Set) Set {\n\tdata := append(s, t...)\n\tn := op(data, len(s))\n\treturn data[:n]\n}\n\ntype BoolOp func(sort.Interface, int) bool\n\nfunc (s Set) DoBool(op BoolOp, t Set) bool {\n\tdata := append(s, t...)\n\treturn op(data, len(s))\n}\n\nfunc (s Set) IsSub(t Set) bool ", "output": "{ return s.DoBool(set.IsSub, t) }"} {"input": "package font\n\nimport (\n\t\"bytes\"\n)\n\nvar alias = map[rune]string{\n\t0x2764: \"\\u2665\", \n\t0x0001f499: \"\\u2665\", \n\t0x0001f49a: \"\\u2665\", \n\t0x0001f49b: \"\\u2665\", \n\t0x0001f49c: \"\\u2665\", \n\t0x0001f49d: \"\\u2665\", \n\t0x0001F601: \":|\", \n\t0x0001F602: \":)\", \n\t0x0001F603: \":D\", \n}\n\ntype Font struct {\n\twidth int\n\theight int\n\tbitmap map[rune][]byte\n}\n\nfunc ExpandAlias(text string) string {\n\tvar f func(b *bytes.Buffer, s string)\n\tf = func(b *bytes.Buffer, s string) {\n\t\tfor _, c := range s {\n\t\t\tm, ok := alias[c]\n\t\t\tif ok {\n\t\t\t\tf(b, m)\n\t\t\t} else {\n\t\t\t\tb.WriteRune(c)\n\t\t\t}\n\t\t}\n\t}\n\tb := new(bytes.Buffer)\n\tf(b, text)\n\treturn b.String()\n}\n\n\n\nfunc (f *Font) Width() int {\n\treturn f.width\n}\n\nfunc (f *Font) Bitmap(c rune) []byte {\n\treturn f.bitmap[c]\n}\n\nfunc (f *Font) Height() int ", "output": "{\n\treturn f.height\n}"} {"input": "package pse\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"sync/atomic\"\n\t\"syscall\"\n\t\"time\"\n)\n\nvar (\n\tprocStatFile string\n\tticks int64\n\tlastTotal int64\n\tlastSeconds int64\n\tipcpu int64\n)\n\nconst (\n\tutimePos = 13\n\tstimePos = 14\n\tstartPos = 21\n\tvssPos = 22\n\trssPos = 23\n)\n\nfunc init() {\n\tticks = 100 \n\tprocStatFile = fmt.Sprintf(\"/proc/%d/stat\", os.Getpid())\n\tperiodic()\n}\n\n\n\n\nfunc ProcUsage(pcpu *float64, rss, vss *int64) error {\n\tcontents, err := ioutil.ReadFile(procStatFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfields := bytes.Fields(contents)\n\n\t*rss = (parseInt64(fields[rssPos])) << 12\n\t*vss = parseInt64(fields[vssPos])\n\n\t*pcpu = float64(atomic.LoadInt64(&ipcpu)) / 10.0\n\n\treturn nil\n}\n\n\nconst (\n\tasciiZero = 48\n\tasciiNine = 57\n)\n\n\n\nfunc parseInt64(d []byte) (n int64) {\n\tif len(d) == 0 {\n\t\treturn -1\n\t}\n\tfor _, dec := range d {\n\t\tif dec < asciiZero || dec > asciiNine {\n\t\t\treturn -1\n\t\t}\n\t\tn = n*10 + (int64(dec) - asciiZero)\n\t}\n\treturn n\n}\n\nfunc periodic() ", "output": "{\n\tcontents, err := ioutil.ReadFile(procStatFile)\n\tif err != nil {\n\t\treturn\n\t}\n\tfields := bytes.Fields(contents)\n\n\tpstart := parseInt64(fields[startPos])\n\tutime := parseInt64(fields[utimePos])\n\tstime := parseInt64(fields[stimePos])\n\ttotal := utime + stime\n\n\tvar sysinfo syscall.Sysinfo_t\n\tif err := syscall.Sysinfo(&sysinfo); err != nil {\n\t\treturn\n\t}\n\n\tseconds := int64(sysinfo.Uptime) - (pstart / ticks)\n\n\tlt := lastTotal\n\tls := lastSeconds\n\n\tlastTotal = total\n\tlastSeconds = seconds\n\n\ttotal -= lt\n\tseconds -= ls\n\n\tif seconds > 0 {\n\t\tatomic.StoreInt64(&ipcpu, (total*1000/ticks)/seconds)\n\t}\n\n\ttime.AfterFunc(1*time.Second, periodic)\n}"} {"input": "package stateful\n\nimport \"sync\"\n\n\n\n\ntype ScopePool interface {\n\tGet() *Scope\n\tPut(scope *Scope)\n\n\tReferenceVariables() []string\n}\n\ntype scopePool struct {\n\treferenceVariables []string\n\tpool sync.Pool\n}\n\n\nfunc NewScopePool(referenceVariables []string) ScopePool {\n\tscopePool := &scopePool{\n\t\treferenceVariables: referenceVariables,\n\t}\n\n\tscopePool.pool = sync.Pool{\n\t\tNew: func() interface{} {\n\t\t\tscope := NewScope()\n\t\t\tfor _, refVariable := range scopePool.referenceVariables {\n\t\t\t\tscope.Set(refVariable, empty)\n\t\t\t}\n\n\t\t\treturn scope\n\t\t},\n\t}\n\n\treturn scopePool\n}\n\n\n\n\n\nfunc (s *scopePool) Get() *Scope {\n\treturn s.pool.Get().(*Scope)\n}\n\n\nfunc (s *scopePool) Put(scope *Scope) {\n\tscope.Reset()\n\ts.pool.Put(scope)\n}\n\nfunc (s *scopePool) ReferenceVariables() []string ", "output": "{\n\treturn s.referenceVariables\n}"} {"input": "package jobs\n\nimport (\n\t\"github.com/cleverua/tuna-timer-api/data\"\n\t\"github.com/cleverua/tuna-timer-api/utils\"\n\t\"gopkg.in/mgo.v2\"\n\t\"log\"\n\t\"time\"\n)\n\ntype StopTimersAtMidnight struct {\n\tenv *utils.Environment\n\tsession *mgo.Session\n}\n\n\n\nfunc (j *StopTimersAtMidnight) Run() {\n\tlog.Println(\"ProlongTimersJob launched!\")\n\n\tnow := time.Now()\n\n\tservice := data.NewTimerService(j.session)\n\tservice.CompleteActiveTimersAtMidnight(&now)\n\n\tlog.Println(\"ProlongTimersJob finished!\")\n}\n\nfunc NewStopTimersAtMidnight(env *utils.Environment, session *mgo.Session) *StopTimersAtMidnight ", "output": "{\n\treturn &StopTimersAtMidnight{\n\t\tenv: env,\n\t\tsession: session,\n\t}\n}"} {"input": "package vminstall\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"io/ioutil\"\n\t\"strings\"\n)\n\ntype Downloader interface{\n\tDownload(url string) ([]byte, error)\n\tMatch() string\n}\n\ntype HTTPDownloader struct {\n\n}\n\nfunc (h HTTPDownloader) Match() string {\n\treturn \"http\"\n}\n\nfunc (h HTTPDownloader) Download(url string) ([]byte,error) {\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\tcontents, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn contents,nil\n\n}\n\ntype DownloadManager struct {\n\tdownloaders []Downloader\n}\n\n\n\n\n\nfunc (manager *DownloadManager) Download(url string) ([]byte,error) {\n\tvar found bool = false\n\tvar d Downloader\n\tfor _,d = range manager.downloaders {\n\t\tif strings.Index(url, d.Match()) == 0 {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif found {\n\t\treturn d.Download(url)\n\t} else {\n\t\treturn nil, errors.New(\"not found matching download\")\n\t}\n\n}\n\nfunc (manager *DownloadManager) Regsiter(d Downloader) ", "output": "{\n\tmanager.downloaders = append(manager.downloaders, d)\n}"} {"input": "package base\n\nimport (\n\t\"time\"\n\n\t\"github.com/google/cadvisor/collector\"\n\t\"github.com/google/cadvisor/info/v2\"\n)\n\ntype Collector struct {\n}\n\nvar _ collector.Collector = &Collector{}\n\n\n\nfunc (c *Collector) Name() string {\n\treturn \"default\"\n}\n\nfunc (c *Collector) Collect() (time.Time, []v2.Metric, error) ", "output": "{\n\treturn time.Now(), []v2.Metrics{}, nil\n}"} {"input": "package credentials\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype stubProvider struct {\n\tcreds Value\n\terr error\n}\n\nfunc (s *stubProvider) Retrieve() (Value, error) {\n\ts.creds.ProviderName = \"stubProvider\"\n\treturn s.creds, s.err\n}\n\nfunc TestCredentialsGet(t *testing.T) {\n\tc := NewCredentials(&stubProvider{\n\t\tcreds: Value{\n\t\t\tAccessKeyID: \"AKID\",\n\t\t\tSecretAccessKey: \"SECRET\",\n\t\t},\n\t})\n\n\tcreds, err := c.Get()\n\tassert.Nil(t, err, \"Expected no error\")\n\tassert.Equal(t, \"AKID\", creds.AccessKeyID, \"Expect access key ID to match\")\n\tassert.Equal(t, \"SECRET\", creds.SecretAccessKey, \"Expect secret access key to match\")\n}\n\n\n\nfunc TestCredentialsGetWithProviderName(t *testing.T) {\n\tstub := &stubProvider{}\n\n\tc := NewCredentials(stub)\n\n\tcreds, err := c.Get()\n\tassert.Nil(t, err, \"Expected no error\")\n\tassert.Equal(t, creds.ProviderName, \"stubProvider\", \"Expected provider name to match\")\n}\n\nfunc TestCredentialsGetWithError(t *testing.T) ", "output": "{\n\tc := NewCredentials(&stubProvider{err: errors.New(\"provider error\")})\n\n\t_, err := c.Get()\n\tassert.Equal(t, \"provider error\", err.Error(), \"Expected provider error\")\n}"} {"input": "package tcpproxy\n\n\n\ntype Process struct{\n\tPid int\n\tPidFile string\n}\n\nfunc(p *Process) kill() error{\n\n\treturn nil\n}\n\nfunc(p *Process) storePidToFile() error{\n\n\treturn nil\n}\n\n\n\nfunc(p *Process) getPidFromFile() int", "output": "{\n\n\treturn nil\n}"} {"input": "package pflag\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype boolValue bool\n\nfunc newBoolValue(val bool, p *bool) *boolValue {\n\t*p = val\n\treturn (*boolValue)(p)\n}\n\nfunc (b *boolValue) Set(s string) error {\n\tv, err := strconv.ParseBool(s)\n\t*b = boolValue(v)\n\treturn err\n}\n\nfunc (b *boolValue) String() string { return fmt.Sprintf(\"%v\", *b) }\n\n\n\nfunc (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\n\n\n\n\nfunc BoolVar(p *bool, name string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc (f *FlagSet) Bool(name string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, \"\", value, usage)\n\treturn p\n}\n\n\nfunc (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, shorthand, value, usage)\n\treturn p\n}\n\n\n\nfunc Bool(name string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, \"\", value, usage)\n}\n\n\nfunc BoolP(name, shorthand string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, shorthand, value, usage)\n}\n\nfunc (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) ", "output": "{\n\tf.VarP(newBoolValue(value, p), name, shorthand, usage)\n}"} {"input": "package dondeestas\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"math/rand\"\n\t\"testing\"\n)\n\ntype dummyStruct struct {\n\tVal1 string `json:\"val1\"`\n\tVal2 int `json:\"val2\"`\n}\n\n\n\nfunc TestReadCloserJsonToStruct(t *testing.T) {\n\texpectedDummy := &dummyStruct{Val1: createRandomString(), Val2: rand.Int()}\n\texpectedDummyJSON, _ := json.Marshal(expectedDummy)\n\texpectedDummyStr := string(expectedDummyJSON)\n\n\tvar dummy dummyStruct\n\tif err := readCloserJSONToStruct(stringToReadCloser(expectedDummyStr), &dummy); err != nil {\n\t\tt.Fatalf(\"Encountered error when retrieving json from string: %s\", err)\n\t}\n\tif expectedDummy.Val1 != dummy.Val1 || expectedDummy.Val2 != dummy.Val2 {\n\t\tt.Fatalf(\"Did not receive expected struct %+v but found %+v\", expectedDummy, dummy)\n\t}\n\n\tif err := readCloserJSONToStruct(stringToReadCloser(`{\"id\":\"foo}`), nil); err == nil {\n\t\tt.Error(\"Did not receive expected error on bad JSON unmarshalling\")\n\t}\n\n\tstrm := ioutil.NopCloser(bytes.NewReader(make([]byte, 0)))\n\tstrm.Close()\n\tif err := readCloserJSONToStruct(strm, nil); err == nil {\n\t\tt.Error(\"Did not receive expected error on attempting to read from closed stream\")\n\t} else {\n\t\tt.Logf(\"ERROR: %s\", err)\n\t}\n\n\tif err := readCloserJSONToStruct(nil, nil); err == nil {\n\t\tt.Error(\"Did not receive expected error on attempting to read from nil stream\")\n\t}\n}\n\nfunc stringToReadCloser(str string) io.ReadCloser ", "output": "{\n\treturn ioutil.NopCloser(bytes.NewReader(bytes.NewBufferString(str).Bytes()))\n}"} {"input": "package controller\n\nimport (\n\tv1 \"k8s.io/api/core/v1\"\n\n\t\"istio.io/istio/pilot/pkg/model\"\n\t\"istio.io/istio/pilot/pkg/serviceregistry/kube\"\n\t\"istio.io/istio/pkg/config/labels\"\n)\n\n\ntype EndpointBuilder struct {\n\tcontroller *Controller\n\n\tlabels labels.Instance\n\tuid string\n\tserviceAccount string\n\tlocality model.Locality\n\ttlsMode string\n}\n\nfunc NewEndpointBuilder(c *Controller, pod *v1.Pod) *EndpointBuilder {\n\tlocality, sa, uid := \"\", \"\", \"\"\n\tvar podLabels labels.Instance\n\tif pod != nil {\n\t\tlocality = c.getPodLocality(pod)\n\t\tsa = kube.SecureNamingSAN(pod)\n\t\tuid = createUID(pod.Name, pod.Namespace)\n\t\tpodLabels = pod.Labels\n\t}\n\n\treturn &EndpointBuilder{\n\t\tcontroller: c,\n\t\tlabels: podLabels,\n\t\tuid: uid,\n\t\tserviceAccount: sa,\n\t\tlocality: model.Locality{\n\t\t\tLabel: locality,\n\t\t\tClusterID: c.clusterID,\n\t\t},\n\t\ttlsMode: kube.PodTLSMode(pod),\n\t}\n}\n\n\n\nfunc (b *EndpointBuilder) buildIstioEndpoint(\n\tendpointAddress string,\n\tendpointPort int32,\n\tsvcPortName string) *model.IstioEndpoint ", "output": "{\n\tif b == nil {\n\t\treturn nil\n\t}\n\n\treturn &model.IstioEndpoint{\n\t\tLabels: b.labels,\n\t\tUID: b.uid,\n\t\tServiceAccount: b.serviceAccount,\n\t\tLocality: b.locality,\n\t\tTLSMode: b.tlsMode,\n\t\tAddress: endpointAddress,\n\t\tEndpointPort: uint32(endpointPort),\n\t\tServicePortName: svcPortName,\n\t\tNetwork: b.controller.endpointNetwork(endpointAddress),\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\nimport \"time\"\n\nfunc goFunc1(f func()) {\n\tgo f()\n}\n\nfunc goFunc2(f func(interface{}), i interface{}) {\n\tgo f(i)\n}\n\n\n\nfunc f1() {\n\tfmt.Println(\"f1 done\")\n}\n\nfunc f2(i interface{}) {\n\tfmt.Println(\"f2 done\", i)\n}\n\nfunc f3(args ...interface{}) {\n\tfmt.Println(\"f3 done\", args)\n}\n\nfunc main() {\n\tgoFunc1(f1)\n\tgoFunc2(f2, 100)\n\n\tgoFunc(f1)\n\tgoFunc(f2, \"xxxx\")\n\tgoFunc(f3, \"hello\", \"world\", 1, 3.14)\n\ttime.Sleep(5 * time.Second)\n}\n\nfunc goFunc(f interface{}, args ...interface{}) ", "output": "{\n\tif len(args) > 1 {\n\t\tgo f.(func(...interface{}))(args)\n\t} else if len(args) == 1 {\n\t\tgo f.(func(interface{}))(args[0])\n\t} else {\n\t\tgo f.(func())()\n\t}\n}"} {"input": "package model\n\ntype (\n\tEvent interface {\n\t\tToPlayerEvent(playerID PlayerID) PlayerEvent\n\t}\n\n\tPlayerEvent interface {\n\t\tPlayerEventMarker()\n\t}\n)\n\n\n\n\nfunc IsGameOverEvent(evt Event) bool ", "output": "{\n\t_, ok := evt.(*EventGameOver)\n\treturn ok\n}"} {"input": "package iso20022\n\n\ntype TotalFeesAndTaxes40 struct {\n\n\tTotalOverheadApplied *ActiveCurrencyAndAmount `xml:\"TtlOvrhdApld,omitempty\"`\n\n\tTotalFees *ActiveCurrencyAndAmount `xml:\"TtlFees,omitempty\"`\n\n\tTotalTaxes *ActiveCurrencyAndAmount `xml:\"TtlTaxs,omitempty\"`\n\n\tCommercialAgreementReference *Max35Text `xml:\"ComrclAgrmtRef,omitempty\"`\n\n\tIndividualFee []*Fee2 `xml:\"IndvFee,omitempty\"`\n\n\tIndividualTax []*Tax31 `xml:\"IndvTax,omitempty\"`\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalOverheadApplied(value, currency string) {\n\tt.TotalOverheadApplied = NewActiveCurrencyAndAmount(value, currency)\n}\n\n\n\nfunc (t *TotalFeesAndTaxes40) SetTotalTaxes(value, currency string) {\n\tt.TotalTaxes = NewActiveCurrencyAndAmount(value, currency)\n}\n\nfunc (t *TotalFeesAndTaxes40) SetCommercialAgreementReference(value string) {\n\tt.CommercialAgreementReference = (*Max35Text)(&value)\n}\n\nfunc (t *TotalFeesAndTaxes40) AddIndividualFee() *Fee2 {\n\tnewValue := new(Fee2)\n\tt.IndividualFee = append(t.IndividualFee, newValue)\n\treturn newValue\n}\n\nfunc (t *TotalFeesAndTaxes40) AddIndividualTax() *Tax31 {\n\tnewValue := new(Tax31)\n\tt.IndividualTax = append(t.IndividualTax, newValue)\n\treturn newValue\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalFees(value, currency string) ", "output": "{\n\tt.TotalFees = NewActiveCurrencyAndAmount(value, currency)\n}"} {"input": "package master\n\nimport ()\n\n\n\ntype frame struct {\n\tjob *job\n\tslaveName string\n\tframe int\n\tdata []byte\n\tprogress byte\n\tcompleted bool\n}\n\n\n\nfunc NewFrame(job *job, fr int) *frame {\n\treturn &frame{\n\t\tjob: job,\n\t\tslaveName: \"\",\n\t\tframe: fr,\n\t\tdata: nil,\n\t\tprogress: 0,\n\t\tcompleted: false,\n\t}\n}\n\n\n\nfunc (f *frame) Job() *job {\n\treturn f.job\n}\n\n\n\nfunc (f *frame) Frame() int {\n\treturn f.frame\n}\n\nfunc (f *frame) AlignedFrame() int {\n\treturn f.frame + f.Job().Start()\n}\n\nfunc (f *frame) Data() []byte {\n\treturn f.data\n}\n\nfunc (f *frame) Progress() byte {\n\treturn f.progress\n}\n\nfunc (f *frame) Completed() bool {\n\treturn f.completed\n}\n\nfunc (f *frame) File() []byte {\n\treturn f.Job().File()\n}\n\n\n\nfunc (f *frame) SetSlaveName(slaveName string) {\n\tf.slaveName = slaveName\n}\n\nfunc (f *frame) SetData(data []byte) {\n\tf.data = data\n}\n\nfunc (f *frame) SetProgress(progress byte) {\n\tf.progress = progress\n}\n\nfunc (f *frame) SetCompleted(completed bool) {\n\tf.completed = completed\n\tif completed {\n\t\tf.SetProgress(100)\n\t}\n}\n\n\n\nfunc (f *frame) Reset() {\n\tf.SetSlaveName(\"\")\n\tf.SetData(nil)\n\tf.SetProgress(0)\n\tf.SetCompleted(false)\n}\n\nfunc (f *frame) SlaveName() string ", "output": "{\n\treturn f.slaveName\n}"} {"input": "package concurrent\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\ntype BackgroundWorker interface {\n\tDo(f func() (interface{}, error)) error\n\tClose() ([]interface{}, error)\n}\n\n\nfunc NewBackgroundWorker() BackgroundWorker {\n\treturn newBackgroundWorker()\n}\n\ntype valueError struct {\n\tvalue interface{}\n\terr error\n}\n\ntype backgroundWorker struct {\n\twg *sync.WaitGroup\n\tvalueErrors chan *valueError\n\tdestroyable Destroyable\n}\n\nfunc newBackgroundWorker() *backgroundWorker {\n\treturn &backgroundWorker{&sync.WaitGroup{}, make(chan *valueError), NewDestroyable(nil)}\n}\n\nfunc (b *backgroundWorker) Do(f func() (interface{}, error)) error {\n\t_, err := b.destroyable.Do(func() (interface{}, error) {\n\t\tb.wg.Add(1)\n\t\tgo func() {\n\t\t\tvalue, err := f()\n\t\t\tb.valueErrors <- &valueError{value, err}\n\t\t\tb.wg.Done()\n\t\t}()\n\t\treturn nil, nil\n\t})\n\treturn err\n}\n\n\n\nfunc (b *backgroundWorker) Close() ([]interface{}, error) ", "output": "{\n\tvar values []interface{}\n\tvar errs []error\n\tif err := b.destroyable.Destroy(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tvalueError, ok := <-b.valueErrors\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tvalues = append(values, valueError.value)\n\t\t\tif valueError.err != nil {\n\t\t\t\terrs = append(errs, valueError.err)\n\t\t\t}\n\t\t}\n\t}()\n\tb.wg.Wait()\n\tclose(b.valueErrors)\n\tif len(errs) == 0 {\n\t\treturn values, nil\n\t}\n\treturn values, fmt.Errorf(\"%v\", errs)\n}"} {"input": "package example\n\nimport (\n\t\"time\"\n\n\t\"github.com/syou6162/go-active-learning/lib/feature\"\n\texample_feature \"github.com/syou6162/go-active-learning/lib/feature/example\"\n\t\"github.com/syou6162/go-active-learning/lib/model\"\n)\n\n\n\nfunc GetStat(examples model.Examples) map[string]int {\n\tstat := make(map[string]int)\n\tfor _, e := range examples {\n\t\tswitch e.Label {\n\t\tcase model.POSITIVE:\n\t\t\tstat[\"positive\"]++\n\t\tcase model.NEGATIVE:\n\t\t\tstat[\"negative\"]++\n\t\tcase model.UNLABELED:\n\t\t\tstat[\"unlabeled\"]++\n\t\t}\n\t}\n\treturn stat\n}\n\nfunc ExtractFeatures(e model.Example) feature.FeatureVector {\n\tvar fv feature.FeatureVector\n\tfv = append(fv, \"BIAS\")\n\tfv = append(fv, example_feature.ExtractHostFeature(e.FinalUrl))\n\tfv = append(fv, example_feature.ExtractJpnNounFeatures(example_feature.ExtractPath(e.FinalUrl), \"URL\")...)\n\tfv = append(fv, example_feature.ExtractNounFeatures(e.Title, \"TITLE\")...)\n\tfv = append(fv, example_feature.ExtractNounFeatures(e.Description, \"DESCRIPTION\")...)\n\tfv = append(fv, example_feature.ExtractNounFeatures(e.Body, \"BODY\")...)\n\treturn fv\n}\n\nfunc NewExample(url string, label model.LabelType) *model.Example ", "output": "{\n\tIsNew := false\n\tif label == model.UNLABELED {\n\t\tIsNew = true\n\t}\n\tnow := time.Now()\n\treturn &model.Example{\n\t\tLabel: label,\n\t\tFv: feature.FeatureVector{},\n\t\tUrl: url,\n\t\tFinalUrl: url,\n\t\tTitle: \"\",\n\t\tDescription: \"\",\n\t\tOgDescription: \"\",\n\t\tOgType: \"\",\n\t\tOgImage: \"\",\n\t\tBody: \"\",\n\t\tScore: 0.0,\n\t\tIsNew: IsNew,\n\t\tStatusCode: 0,\n\t\tFavicon: \"\",\n\t\tErrorCount: 0,\n\t\tCreatedAt: now,\n\t\tUpdatedAt: now,\n\t\tReferringTweets: &model.ReferringTweets{},\n\t\tHatenaBookmark: &model.HatenaBookmark{Bookmarks: make([]*model.Bookmark, 0)},\n\t}\n}"} {"input": "package godo\n\ntype TaskManager struct {\n\tmanager\n}\n\n\n\nfunc (tm *TaskManager) FindAll() (tasks []Task, err error) {\n\terr = tm.manager.FindAll(&tasks, \"tasks\")\n\treturn\n}\n\nfunc (tm *TaskManager) FindTasksOfProject(projectId int, tasks *[]Task) (err error) {\n\terr = Dbmap.Select(tasks, \"select * from tasks where projectID = ? order by id\", projectId)\n\treturn\n}\n\nfunc NewTaskManager() *TaskManager ", "output": "{\n\treturn &TaskManager{}\n}"} {"input": "package digitalocean\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\n\t\"github.com/digitalocean/godo\"\n)\n\ntype Artifact struct {\n\tsnapshotName string\n\n\tsnapshotId int\n\n\tregionName string\n\n\tclient *godo.Client\n}\n\n\n\nfunc (*Artifact) Files() []string {\n\treturn nil\n}\n\nfunc (a *Artifact) Id() string {\n\treturn fmt.Sprintf(\"%s:%s\", a.regionName, strconv.FormatUint(uint64(a.snapshotId), 10))\n}\n\nfunc (a *Artifact) String() string {\n\treturn fmt.Sprintf(\"A snapshot was created: '%v' (ID: %v) in region '%v'\", a.snapshotName, a.snapshotId, a.regionName)\n}\n\nfunc (a *Artifact) State(name string) interface{} {\n\treturn nil\n}\n\nfunc (a *Artifact) Destroy() error {\n\tlog.Printf(\"Destroying image: %d (%s)\", a.snapshotId, a.snapshotName)\n\t_, err := a.client.Images.Delete(context.TODO(), a.snapshotId)\n\treturn err\n}\n\nfunc (*Artifact) BuilderId() string ", "output": "{\n\treturn BuilderId\n}"} {"input": "package render\n\n\ntype Data map[string]interface{}\n\n\nfunc NewData() *Data {\n\treturn &Data{}\n}\n\n\nfunc (d *Data) Set(key string, data interface{}) {\n\tif *d == nil {\n\t\tdata := Data(map[string]interface{}{})\n\t\t*d = data\n\t}\n\t(*d)[key] = data\n}\n\n\n\n\n\nfunc (d *Data) Get(key string) interface{} {\n\tif *d == nil {\n\t\treturn nil\n\t}\n\tdata, ok := (*d)[key]\n\tif ok == false {\n\t\treturn nil\n\t}\n\treturn data\n}\n\n\nfunc (d *Data) Merge(data *Data) {\n\tif *d == nil {\n\t\tdata := Data(map[string]interface{}{})\n\t\t*d = data\n\t}\n\tif data == nil || *data == nil {\n\t\treturn\n\t}\n\tfor k, v := range *data {\n\t\td.Set(k, v)\n\t}\n}\n\nfunc (d *Data) Del(key string) ", "output": "{\n\tif *d == nil {\n\t\treturn\n\t}\n\tdelete(*d, key)\n}"} {"input": "package fork\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n)\n\ntype Field interface {\n\tNamed\n\tNew(...interface{}) Field\n\tGet() *Value\n\tSet(*http.Request)\n\tProcessor\n}\n\ntype Named interface {\n\tName() string\n\tReName(...string) string\n}\n\nfunc newnamed(name string) *named {\n\treturn &named{name: name}\n}\n\ntype named struct {\n\tname string\n}\n\nfunc (n *named) Name() string {\n\treturn n.name\n}\n\nfunc (n *named) ReName(rename ...string) string {\n\tif len(rename) > 0 {\n\t\tn.name = strings.Join(rename, \"-\")\n\t}\n\treturn n.name\n}\n\n\n\ntype Processor interface {\n\tWidget\n\tFilterer\n\tValidater\n}\n\ntype processor struct {\n\tWidget\n\tValidater\n\tFilterer\n}\n\nfunc NewProcessor(w Widget, v Validater, f Filterer) *processor {\n\treturn &processor{w, v, f}\n}\n\nfunc (n *named) Copy() *named ", "output": "{\n\tvar ret named = *n\n\treturn &ret\n}"} {"input": "package readpass\n\n\n\n\nimport (\n\t\"log\"\n\t\"os\"\n\n\t\"golang.org/x/crypto/ssh/terminal\"\n)\n\nfunc SSHPasswordPrompt(prompt string) (password string, err error) {\n\tstate, err := terminal.MakeRaw(0)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer terminal.Restore(0, state)\n\tterm := terminal.NewTerminal(os.Stdout, \">\")\n\tpassword, err = term.ReadPassword(prompt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}\n\n\n\nvar PasswordPrompt func(prompt string) (password string, err error) = DefaultPasswordPrompt\n\n\n\nvar PasswordPromptBytes func(prompt string) (password []byte, err error) = DefaultPasswordPromptBytes\n\n\n\nfunc DefaultPasswordPrompt(prompt string) (password string, err error) {\n\tstate, err := terminal.MakeRaw(0)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer terminal.Restore(0, state)\n\tterm := terminal.NewTerminal(os.Stdout, \">\")\n\tpassword, err = term.ReadPassword(prompt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}\n\n\n\n\n\nfunc DefaultPasswordPromptBytes(prompt string) (password []byte, err error) ", "output": "{\n\tpasswordString, err := PasswordPrompt(prompt)\n\tif err == nil {\n\t\tpassword = []byte(passwordString)\n\t}\n\treturn\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n)\n\nvar cfgFile string\n\n\nvar RootCmd = &cobra.Command{\n\tUse: \"docktor\",\n\tShort: \"Administration & Monitoring Deployment with Docker\",\n\tLong: `Docktor is a web application which aims to make the deployment of docke services easier\nWith it, you can manage several daemons, services and group.\nEach service can be deployed on a daemon for a group.\n\t`,\n}\n\nconst (\n\tconfigPath = \"$HOME\"\n\tconfigFile = \".docktor\"\n\tprefixForEnvVariables = \"docktor\"\n)\n\n\n\n\n\nfunc init() {\n\tcobra.OnInitialize(initConfig)\n\tRootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is $HOME/.docktor.yaml)\")\n}\n\n\nfunc initConfig() {\n\tif cfgFile != \"\" { \n\t\tviper.SetConfigFile(cfgFile)\n\t}\n\n\tviper.SetEnvPrefix(prefixForEnvVariables) \n\tviper.SetConfigName(configFile) \n\tviper.AddConfigPath(configPath) \n\tviper.AutomaticEnv() \n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\", \"-\", \"_\")) \n\n\terr := viper.ReadInConfig()\n\tif err == nil {\n\t\tfmt.Println(\"Using config file:\" + viper.ConfigFileUsed())\n\t} else {\n\t\tfmt.Println(\"Cant read config file:\" + viper.ConfigFileUsed())\n\t}\n}\n\nfunc Execute() ", "output": "{\n\tif err := RootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}"} {"input": "package test_test\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n\n\t\"github.com/nyaruka/goflow/test\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestAssertEqualJSON(t *testing.T) {\n\tassert.True(t, test.AssertEqualJSON(t, json.RawMessage(`{\"foo\":1,\"bar\":2}`), json.RawMessage(`{\"bar\": 2, \"foo\": 1}`), \"doh!\"))\n}\n\n\n\nfunc TestJSONReplace(t *testing.T) ", "output": "{\n\tassert.Equal(t, json.RawMessage(`{\"foo\":\"x\",\"bar\":2}`), test.JSONReplace(json.RawMessage(`{\"foo\":1,\"bar\":2}`), []string{\"foo\"}, json.RawMessage(`\"x\"`)))\n}"} {"input": "package statement\n\nimport (\n\t\"reflect\"\n\n\t\"github.com/richardwilkes/goblin/ast\"\n)\n\n\ntype Continue struct {\n\tast.PosImpl\n}\n\n\n\n\nfunc (stmt *Continue) Execute(scope ast.Scope) (reflect.Value, error) {\n\treturn ast.NilValue, ast.ErrContinue\n}\n\nfunc (stmt *Continue) String() string ", "output": "{\n\treturn \"continue\"\n}"} {"input": "package oci\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/phoenix-io/phoenix-mon/plugins\"\n\tps \"github.com/shirou/gopsutil/process\"\n\t\"io/ioutil\"\n)\n\ntype OCI struct {\n\tprocess []plugin.Process\n\tcount\tint\n}\n\ntype PState struct {\n\tID string `json:\"id\"`\n\tPid int `json:\"init_process_pid\"`\n}\n\n\n\nfunc NewPlugin(pluginName string) (plugin.Plugin, error) {\n\treturn &OCI{}, nil\n}\n\nfunc (p *OCI) GetProcessList() ([]plugin.Process, error) {\n\n\tvar state PState\n\tcontainers, _ := ioutil.ReadDir(\"/run/oci/\")\n\tfor _, c := range containers {\n\t\tdata, err := ioutil.ReadFile(\"/run/oci/\" + c.Name() + \"/state.json\")\n\t\tif err != nil {\n\t\t\treturn p.process, fmt.Errorf(\"Error in reading file\")\n\t\t}\n\n\t\tjson.Unmarshal(data, &state)\n\t\tname := fmt.Sprintf(\"%s %d\",state.ID,p.count)\n\t\tp.count++\n\t\tp.process = append(p.process, plugin.Process{Pid: state.Pid, Name: name})\n\t}\n\n\treturn p.process, nil\n}\n\nfunc (p *OCI) GetProcessStat(process plugin.Process) (plugin.Process, error) {\n\tres, err := ps.NewProcess(int32(process.Pid))\n\tif err != nil {\n\t\tfmt.Println(\"Unable to Create Process Object\")\n\t}\n\tmemInfo, err := res.MemoryInfo()\n\tif err != nil {\n\t\treturn process, fmt.Errorf(\"geting ppid error %v\", err)\n\n\t}\n\tprocess.Memory = memInfo.RSS\n\treturn process, nil\n}\n\nfunc init() ", "output": "{\n\tplugin.Register(\"oci\", &plugin.RegisteredPlugin{New: NewPlugin})\n}"} {"input": "package gin\n\nimport (\n\t\"github.com/gin-gonic/gin/binding\"\n\t\"log\"\n)\n\nfunc (c *Context) GetCookie(name string) (string, error) {\n\tlog.Println(\"GetCookie() method is deprecated. Use Cookie() instead.\")\n\treturn c.Cookie(name)\n}\n\n\n\n\n\nfunc (c *Context) BindWith(obj interface{}, b binding.Binding) error ", "output": "{\n\tlog.Println(`BindWith(\\\"interface{}, binding.Binding\\\") error is going to\n\tbe deprecated, please check issue #662 and either use MustBindWith() if you\n\twant HTTP 400 to be automatically returned if any error occur, of use\n\tShouldBindWith() if you need to manage the error.`)\n\treturn c.MustBindWith(obj, b)\n}"} {"input": "package util\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/registered\"\n\t\"k8s.io/kubernetes/pkg/client\"\n\t\"k8s.io/kubernetes/pkg/client/clientcmd\"\n)\n\nfunc NewClientCache(loader clientcmd.ClientConfig) *clientCache {\n\treturn &clientCache{\n\t\tclients: make(map[string]*client.Client),\n\t\tconfigs: make(map[string]*client.Config),\n\t\tloader: loader,\n\t}\n}\n\n\n\ntype clientCache struct {\n\tloader clientcmd.ClientConfig\n\tclients map[string]*client.Client\n\tconfigs map[string]*client.Config\n\tdefaultConfig *client.Config\n\tdefaultClient *client.Client\n\tmatchVersion bool\n}\n\n\n\n\n\n\nfunc (c *clientCache) ClientForVersion(version string) (*client.Client, error) {\n\tif client, ok := c.clients[version]; ok {\n\t\treturn client, nil\n\t}\n\tconfig, err := c.ClientConfigForVersion(version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := client.New(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.clients[config.Version] = client\n\treturn client, nil\n}\n\nfunc (c *clientCache) ClientConfigForVersion(version string) (*client.Config, error) ", "output": "{\n\tif c.defaultConfig == nil {\n\t\tconfig, err := c.loader.ClientConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tc.defaultConfig = config\n\t\tif c.matchVersion {\n\t\t\tif err := client.MatchesServerVersion(c.defaultClient, config); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\tif config, ok := c.configs[version]; ok {\n\t\treturn config, nil\n\t}\n\tconfig := *c.defaultConfig\n\tnegotiatedVersion, err := client.NegotiateVersion(c.defaultClient, &config, version, registered.RegisteredVersions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig.Version = negotiatedVersion\n\tclient.SetKubernetesDefaults(&config)\n\tc.configs[version] = &config\n\n\treturn &config, nil\n}"} {"input": "package fsutil\n\nimport (\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com/containerd/continuity/sysx\"\n\t\"github.com/pkg/errors\"\n)\n\n\n\n\n\nfunc handleTarTypeBlockCharFifo(path string, stat *Stat) error {\n\tmode := uint32(stat.Mode & 07777)\n\tif os.FileMode(stat.Mode)&os.ModeCharDevice != 0 {\n\t\tmode |= syscall.S_IFCHR\n\t} else if os.FileMode(stat.Mode)&os.ModeNamedPipe != 0 {\n\t\tmode |= syscall.S_IFIFO\n\t} else {\n\t\tmode |= syscall.S_IFBLK\n\t}\n\n\tif err := syscall.Mknod(path, mode, int(mkdev(stat.Devmajor, stat.Devminor))); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc rewriteMetadata(p string, stat *Stat) error ", "output": "{\n\tfor key, value := range stat.Xattrs {\n\t\tsysx.Setxattr(p, key, value, 0)\n\t}\n\n\tif err := os.Lchown(p, int(stat.Uid), int(stat.Gid)); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to lchown %s\", p)\n\t}\n\n\tif os.FileMode(stat.Mode)&os.ModeSymlink == 0 {\n\t\tif err := os.Chmod(p, os.FileMode(stat.Mode)); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to chown %s\", p)\n\t\t}\n\t}\n\n\tif err := chtimes(p, stat.ModTime); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to chtimes %s\", p)\n\t}\n\n\treturn nil\n}"} {"input": "package mdns\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestServer_Lookup(t *testing.T) {\n\tserv, err := NewServer(&Config{Zone: makeServiceWithServiceName(t, \"_foobar._tcp\")})\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\tdefer serv.Shutdown()\n\n\tentries := make(chan *ServiceEntry, 1)\n\tfound := false\n\tdoneCh := make(chan struct{})\n\tgo func() {\n\t\tselect {\n\t\tcase e := <-entries:\n\t\t\tif e.Name != \"hostname._foobar._tcp.local.\" {\n\t\t\t\tt.Fatalf(\"bad: %v\", e)\n\t\t\t}\n\t\t\tif e.Port != 80 {\n\t\t\t\tt.Fatalf(\"bad: %v\", e)\n\t\t\t}\n\t\t\tif e.Info != \"Local web server\" {\n\t\t\t\tt.Fatalf(\"bad: %v\", e)\n\t\t\t}\n\t\t\tfound = true\n\n\t\tcase <-time.After(80 * time.Millisecond):\n\t\t\tt.Fatalf(\"timeout\")\n\t\t}\n\t\tclose(doneCh)\n\t}()\n\n\tparams := &QueryParam{\n\t\tService: \"_foobar._tcp\",\n\t\tDomain: \"local\",\n\t\tTimeout: 50 * time.Millisecond,\n\t\tEntries: entries,\n\t}\n\terr = Query(params)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\t<-doneCh\n\tif !found {\n\t\tt.Fatalf(\"record not found\")\n\t}\n}\n\nfunc TestServer_StartStop(t *testing.T) ", "output": "{\n\ts := makeService(t)\n\tserv, err := NewServer(&Config{Zone: s})\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\tdefer serv.Shutdown()\n}"} {"input": "package internal\n\n\n\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar limitSem = make(chan int, 100) \n\nfunc limitRelease() {\n\tselect {\n\tcase <-limitSem:\n\tdefault:\n\t\tlog.Print(\"appengine: unbalanced limitSem release!\")\n\t}\n}\n\nfunc limitDial(network, addr string) (net.Conn, error) {\n\tlimitSem <- 1\n\n\tconn, err := net.DialTimeout(network, addr, 500*time.Millisecond)\n\tif err != nil {\n\t\tlimitRelease()\n\t\treturn nil, err\n\t}\n\tlc := &limitConn{Conn: conn}\n\truntime.SetFinalizer(lc, (*limitConn).Close) \n\treturn lc, nil\n}\n\ntype limitConn struct {\n\tclose sync.Once\n\tnet.Conn\n}\n\n\n\nfunc (lc *limitConn) Close() error ", "output": "{\n\tdefer lc.close.Do(func() {\n\t\tlimitRelease()\n\t\truntime.SetFinalizer(lc, nil)\n\t})\n\treturn lc.Conn.Close()\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/atlassian/git-lob/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n)\n\ntype BeEmptyMatcher struct {\n}\n\n\n\nfunc (matcher *BeEmptyMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"to be empty\")\n}\n\nfunc (matcher *BeEmptyMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"not to be empty\")\n}\n\nfunc (matcher *BeEmptyMatcher) Match(actual interface{}) (success bool, err error) ", "output": "{\n\tlength, ok := lengthOf(actual)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"BeEmpty matcher expects a string/array/map/channel/slice. Got:\\n%s\", format.Object(actual, 1))\n\t}\n\n\treturn length == 0, nil\n}"} {"input": "package meetup\n\nimport \"testing\"\n\n\n\nconst targetTestVersion = 3\n\nvar weekName = map[WeekSchedule]string{\n\tFirst: \"first\",\n\tSecond: \"second\",\n\tThird: \"third\",\n\tFourth: \"fourth\",\n\tTeenth: \"teenth\",\n\tLast: \"last\",\n}\n\nfunc TestTestVersion(t *testing.T) {\n\tif testVersion != targetTestVersion {\n\t\tt.Fatalf(\"Found testVersion = %v, want %v\", testVersion, targetTestVersion)\n\t}\n}\n\n\n\nfunc TestDay(t *testing.T) ", "output": "{\n\tfor _, test := range testCases {\n\t\tres := Day(test.week, test.weekday, test.month, test.year)\n\t\tif res != test.expDay {\n\t\t\tt.Fatalf(\"For %s %s of %s 2013 got date of %d, want %d\",\n\t\t\t\tweekName[test.week], test.weekday, test.month, res, test.expDay)\n\t\t}\n\t}\n}"} {"input": "package crawlr\n\nimport (\n\t\"bytes\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"golang.org/x/net/html\"\n)\n\n\n\n\ntype Pipe func(<-chan *RewindInputStream, chan<- *RewindInputStream)\n\n\n\n\n\n\nfunc getLink(t html.Token, tokenType html.TokenType) string {\n\tif tokenType == html.StartTagToken && t.Data == \"a\" {\n\t\tfor _, att := range t.Attr {\n\t\t\tif att.Key == \"href\" {\n\t\t\t\treturn att.Val\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}\n\n\n\n\nfunc getImg(t html.Token, tokenType html.TokenType) string {\n\tif tokenType == html.StartTagToken && t.Data == \"img\" {\n\t\tfor _, att := range t.Attr {\n\t\t\tif att.Key == \"src\" {\n\t\t\t\treturn att.Val\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc ExtractLinkPipe(in <-chan *RewindInputStream, out chan<- *RewindInputStream) {\n\tdefer close(out)\n\tfor ris := range in {\n\t\tuniqueLinks := make(map[string]bool)\n\t\ttokenizer := html.NewTokenizer(bytes.NewReader(ris.content))\n\n\t\tfor tokenType := tokenizer.Next(); tokenType != html.ErrorToken; tokenType = tokenizer.Next() {\n\t\t\tt := tokenizer.Token()\n\t\t\tif link := formatLink(ris.URL, getLink(t, tokenType)); link != \"\" {\n\t\t\t\tuniqueLinks[link] = true\n\t\t\t} else if link := formatLink(ris.URL, getImg(t, tokenType)); link != \"\" {\n\t\t\t\tuniqueLinks[link] = true\n\t\t\t}\n\t\t}\n\n\t\tris.msg.Type = REAL\n\t\tfor k := range uniqueLinks {\n\t\t\tris.msg.Msg += \";\" + k\n\t\t}\n\n\t\tout <- ris\n\t}\n}\n\nfunc formatLink(URL, link string) string ", "output": "{\n\tbaseURL, err := url.Parse(URL)\n\tif err != nil || link == \"\" {\n\t\treturn \"\"\n\t}\n\tlinkURL, err := url.Parse(link)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tif len(linkURL.Scheme) >= 4 && linkURL.Scheme[:4] == \"http\" {\n\t\treturn link\n\t}\n\n\tif link[0] == '/' || link[0] == '.' {\n\t\treturn strings.Join([]string{\n\t\t\tbaseURL.Scheme,\n\t\t\t\":\",\n\t\t\tbaseURL.Host,\n\t\t\t\"/\",\n\t\t\tstrings.Trim(link, \"/\"),\n\t\t}, \"\")\n\t}\n\n\tfinalLink := strings.Join([]string{\n\t\tbaseURL.Scheme,\n\t\t\":\",\n\t\tbaseURL.Host,\n\t\tbaseURL.Path,\n\t}, \"\")\n\n\tif baseURL.RawQuery != \"\" {\n\t\tfinalLink += \"?\" + baseURL.RawQuery\n\t}\n\treturn finalLink + link\n}"} {"input": "package systemd\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/google/cadvisor/container\"\n\t\"github.com/google/cadvisor/fs\"\n\tinfo \"github.com/google/cadvisor/info/v1\"\n\t\"github.com/google/cadvisor/watcher\"\n\n\t\"k8s.io/klog/v2\"\n)\n\ntype systemdFactory struct{}\n\nfunc (f *systemdFactory) String() string {\n\treturn \"systemd\"\n}\n\nfunc (f *systemdFactory) NewContainerHandler(name string, inHostNamespace bool) (container.ContainerHandler, error) {\n\treturn nil, fmt.Errorf(\"Not yet supported\")\n}\n\nfunc (f *systemdFactory) CanHandleAndAccept(name string) (bool, bool, error) {\n\tif strings.HasSuffix(name, \".mount\") {\n\t\treturn true, false, nil\n\t}\n\tklog.V(5).Infof(\"%s not handled by systemd handler\", name)\n\treturn false, false, nil\n}\n\nfunc (f *systemdFactory) DebugInfo() map[string][]string {\n\treturn map[string][]string{}\n}\n\n\n\n\nfunc Register(machineInfoFactory info.MachineInfoFactory, fsInfo fs.FsInfo, includedMetrics container.MetricSet) error ", "output": "{\n\tklog.V(1).Infof(\"Registering systemd factory\")\n\tfactory := &systemdFactory{}\n\tcontainer.RegisterContainerHandlerFactory(factory, []watcher.ContainerWatchSource{watcher.Raw})\n\treturn nil\n}"} {"input": "package gamelift\n\nimport (\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/client\"\n\t\"github.com/aws/aws-sdk-go/aws/client/metadata\"\n\t\"github.com/aws/aws-sdk-go/aws/request\"\n\t\"github.com/aws/aws-sdk-go/aws/signer/v4\"\n\t\"github.com/aws/aws-sdk-go/private/protocol/jsonrpc\"\n)\n\n\n\n\n\n\n\ntype GameLift struct {\n\t*client.Client\n}\n\n\nvar initClient func(*client.Client)\n\n\nvar initRequest func(*request.Request)\n\n\nconst (\n\tServiceName = \"gamelift\" \n\tEndpointsID = ServiceName \n)\n\n\n\n\n\n\n\n\n\n\n\nfunc New(p client.ConfigProvider, cfgs ...*aws.Config) *GameLift {\n\tc := p.ClientConfig(EndpointsID, cfgs...)\n\treturn newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName)\n}\n\n\n\n\n\n\nfunc (c *GameLift) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\tif initRequest != nil {\n\t\tinitRequest(req)\n\t}\n\n\treturn req\n}\n\nfunc newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *GameLift ", "output": "{\n\tsvc := &GameLift{\n\t\tClient: client.New(\n\t\t\tcfg,\n\t\t\tmetadata.ClientInfo{\n\t\t\t\tServiceName: ServiceName,\n\t\t\t\tSigningName: signingName,\n\t\t\t\tSigningRegion: signingRegion,\n\t\t\t\tEndpoint: endpoint,\n\t\t\t\tAPIVersion: \"2015-10-01\",\n\t\t\t\tJSONVersion: \"1.1\",\n\t\t\t\tTargetPrefix: \"GameLift\",\n\t\t\t},\n\t\t\thandlers,\n\t\t),\n\t}\n\n\tsvc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)\n\tsvc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)\n\tsvc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)\n\tsvc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)\n\tsvc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)\n\n\tif initClient != nil {\n\t\tinitClient(svc.Client)\n\t}\n\n\treturn svc\n}"} {"input": "package callinfo\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\n\t\"github.com/youtube/vitess/go/rpcwrap/proto\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\nfunc RPCWrapCallInfo(ctx context.Context) context.Context {\n\tremoteAddr, _ := proto.RemoteAddr(ctx)\n\tusername, _ := proto.Username(ctx)\n\treturn NewContext(ctx, &rpcWrapCallInfoImpl{\n\t\tremoteAddr: remoteAddr,\n\t\tusername: username,\n\t})\n}\n\ntype rpcWrapCallInfoImpl struct {\n\tremoteAddr, username string\n}\n\nfunc (rwci *rpcWrapCallInfoImpl) RemoteAddr() string {\n\treturn rwci.remoteAddr\n}\n\nfunc (rwci *rpcWrapCallInfoImpl) Username() string {\n\treturn rwci.username\n}\n\nfunc (rwci *rpcWrapCallInfoImpl) Text() string {\n\treturn fmt.Sprintf(\"%s@%s\", rwci.username, rwci.remoteAddr)\n}\n\n\n\nfunc (rwci *rpcWrapCallInfoImpl) HTML() template.HTML ", "output": "{\n\treturn template.HTML(\"RemoteAddr: \" + rwci.remoteAddr + \"
\\n\" + \"Username: \" + rwci.username + \"
\\n\")\n}"} {"input": "package apiserver_test\n\nimport (\n\t\"testing\"\n\n\tgc \"gopkg.in/check.v1\"\n)\n\n\n\nfunc TestPackage(t *testing.T) ", "output": "{\n\tgc.TestingT(t)\n}"} {"input": "package recovery\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"github.com/containous/traefik/middlewares\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nconst (\n\ttypeName = \"Recovery\"\n)\n\ntype recovery struct {\n\tnext http.Handler\n\tname string\n}\n\n\nfunc New(ctx context.Context, next http.Handler, name string) (http.Handler, error) {\n\tmiddlewares.GetLogger(ctx, name, typeName).Debug(\"Creating middleware\")\n\n\treturn &recovery{\n\t\tnext: next,\n\t\tname: name,\n\t}, nil\n}\n\nfunc (re *recovery) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tdefer recoverFunc(middlewares.GetLogger(req.Context(), re.name, typeName), rw)\n\tre.next.ServeHTTP(rw, req)\n}\n\n\n\nfunc recoverFunc(logger logrus.FieldLogger, rw http.ResponseWriter) ", "output": "{\n\tif err := recover(); err != nil {\n\t\tlogger.Errorf(\"Recovered from panic in http handler: %+v\", err)\n\t\thttp.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t}\n}"} {"input": "package chapter3_cf\n\n\ntype SourceFileAttribute struct {\n\tcp ConstantPool\n\tsourceFileIndex uint16\n}\n\nfunc (self *SourceFileAttribute) readInfo(reader *ClassReader) {\n\tself.sourceFileIndex = reader.readUint16()\n}\n\n\n\nfunc (self *SourceFileAttribute) FileName() string ", "output": "{\n\treturn self.cp.getUtf8(self.sourceFileIndex)\n}"} {"input": "package net\n\nimport (\n\t\"io\"\n)\n\nconst (\n\tbufferSize = 4 * 1024\n)\n\n\n\n\n\nfunc ChanToWriter(writer io.Writer, stream <-chan []byte) error {\n\tfor buffer := range stream {\n\t\t_, err := writer.Write(buffer)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc ReaderToChan(stream chan<- []byte, reader io.Reader) error ", "output": "{\n\tfor {\n\t\tbuffer := make([]byte, bufferSize)\n\t\tnBytes, err := reader.Read(buffer)\n\t\tif nBytes > 0 {\n\t\t\tstream <- buffer[:nBytes]\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}"} {"input": "package trayicon\n\nimport (\n\t\"errors\"\n\n\t\"github.com/godbus/dbus\"\n\t\"github.com/linuxdeepin/go-lib/dbusutil\"\n\tx \"github.com/linuxdeepin/go-x11-client\"\n)\n\nconst (\n\tdbusServiceName = \"com.deepin.dde.TrayManager\"\n\tdbusInterface = dbusServiceName\n\tdbusPath = \"/com/deepin/dde/TrayManager\"\n)\n\nfunc (*TrayManager) GetInterfaceName() string {\n\treturn dbusInterface\n}\n\n\n\n\n\nfunc (m *TrayManager) GetName(win uint32) (name string, busErr *dbus.Error) {\n\tm.mutex.Lock()\n\ticon, ok := m.icons[x.Window(win)]\n\tm.mutex.Unlock()\n\tif !ok {\n\t\treturn \"\", dbusutil.ToError(errors.New(\"icon not found\"))\n\t}\n\treturn icon.getName(), nil\n}\n\n\nfunc (m *TrayManager) EnableNotification(win uint32, enabled bool) *dbus.Error {\n\tm.mutex.Lock()\n\ticon, ok := m.icons[x.Window(win)]\n\tm.mutex.Unlock()\n\tif !ok {\n\t\treturn dbusutil.ToError(errors.New(\"icon not found\"))\n\t}\n\n\ticon.mu.Lock()\n\ticon.notify = enabled\n\ticon.mu.Unlock()\n\treturn nil\n}\n\nfunc (m *TrayManager) Manage() (ok bool, busErr *dbus.Error) ", "output": "{\n\tlogger.Debug(\"call Manage by dbus\")\n\n\terr := m.sendClientMsgMANAGER()\n\tif err != nil {\n\t\tlogger.Warning(err)\n\t\treturn false, dbusutil.ToError(err)\n\t}\n\treturn true, nil\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n)\n\ntype BuiltInClass struct {\n\tname Instance\n\tsupers []Class\n\tslots []Instance\n}\n\nfunc NewBuiltInClass(name string, super Class, slots ...string) Class {\n\tslotNames := []Instance{}\n\tfor _, slot := range slots {\n\t\tslotNames = append(slotNames, NewSymbol(slot))\n\t}\n\treturn BuiltInClass{NewSymbol(name), []Class{super}, slotNames}\n}\n\nfunc (p BuiltInClass) Supers() []Class {\n\treturn p.supers\n}\n\n\n\nfunc (p BuiltInClass) Initform(arg Instance) (v Instance, ok bool) {\n\treturn nil, false\n}\n\nfunc (p BuiltInClass) Initarg(arg Instance) (v Instance, ok bool) {\n\treturn arg, true\n}\n\nfunc (BuiltInClass) Class() Class {\n\treturn BuiltInClassClass\n}\n\nfunc (p BuiltInClass) String() string {\n\treturn fmt.Sprint(p.name)\n}\n\nfunc (p BuiltInClass) Slots() []Instance ", "output": "{\n\treturn p.slots\n}"} {"input": "package main\n\ntype Session struct {\n\tseq int32\n\tservers map[int32]int32 \n}\n\n\nfunc NewSession(server int) *Session {\n\ts := new(Session)\n\ts.servers = make(map[int32]int32, server)\n\ts.seq = 0\n\treturn s\n}\n\n\n\n\nfunc (s *Session) Put(server int32) (seq int32) {\n\tseq = s.nextSeq()\n\ts.servers[seq] = server\n\treturn\n}\n\nfunc (s *Session) Servers() (seqs []int32, servers []int32) {\n\tvar (\n\t\ti = len(s.servers)\n\t\tseq, server int32\n\t)\n\tseqs = make([]int32, i)\n\tservers = make([]int32, i)\n\tfor seq, server = range s.servers {\n\t\ti--\n\t\tseqs[i] = seq\n\t\tservers[i] = server\n\t}\n\treturn\n}\n\n\nfunc (s *Session) Del(seq int32) bool {\n\tdelete(s.servers, seq)\n\treturn (len(s.servers) == 0)\n}\n\nfunc (s *Session) Size() int {\n\treturn len(s.servers)\n}\n\nfunc (s *Session) nextSeq() int32 ", "output": "{\n\ts.seq++\n\treturn s.seq\n}"} {"input": "package trace \n\nimport (\n\t\"context\"\n\t\"runtime\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}\n\n\n\n\n\n\nfunc versionGo() string {\n\tconst develPrefix = \"devel +\"\n\n\ts := runtime.Version()\n\tif strings.HasPrefix(s, develPrefix) {\n\t\ts = s[len(develPrefix):]\n\t\tif p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 {\n\t\t\ts = s[:p]\n\t\t}\n\t\treturn s\n\t}\n\n\tnotSemverRune := func(r rune) bool {\n\t\treturn strings.IndexRune(\"0123456789.\", r) < 0\n\t}\n\n\tif strings.HasPrefix(s, \"go1\") {\n\t\ts = s[2:]\n\t\tvar prerelease string\n\t\tif p := strings.IndexFunc(s, notSemverRune); p >= 0 {\n\t\t\ts, prerelease = s[:p], s[p:]\n\t\t}\n\t\tif strings.HasSuffix(s, \".\") {\n\t\t\ts += \"0\"\n\t\t} else if strings.Count(s, \".\") < 2 {\n\t\t\ts += \".0\"\n\t\t}\n\t\tif prerelease != \"\" {\n\t\t\ts += \"-\" + prerelease\n\t\t}\n\t\treturn s\n\t}\n\treturn \"UNKNOWN\"\n}\n\nconst versionClient = \"20181129\"\n\nfunc DefaultAuthScopes() []string ", "output": "{\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t\t\"https:www.googleapis.com/auth/trace.append\",\n\t\t\"https:www.googleapis.com/auth/trace.readonly\",\n\t}\n}"} {"input": "package orm\n\n\n\ntype deleteQuery struct {\n\t*Query\n}\n\nvar _ QueryAppender = (*deleteQuery)(nil)\n\nfunc (del deleteQuery) AppendQuery(b []byte, params ...interface{}) ([]byte, error) {\n\tb = append(b, \"DELETE FROM \"...)\n\tb = del.appendTableNameWithAlias(b)\n\treturn del.appendWhere(b)\n}\n\nfunc Delete(db dber, v interface{}) error ", "output": "{\n\tq := NewQuery(db, v)\n\tif q.err != nil {\n\t\treturn q.err\n\t}\n\t_, err := db.ExecOne(deleteQuery{q}, q.model)\n\treturn err\n}"} {"input": "package partner\n\nimport (\n\t\"github.com/jrsix/gof/web\"\n\t\"github.com/jrsix/gof/web/mvc\"\n\t\"go2o/src/core/domain/interface/partner\"\n\t\"go2o/src/core/service/dps\"\n\t\"net/url\"\n)\n\nfunc chkLogin(ctx *web.Context) (b bool, partnerId int) {\n\tv := ctx.Session().Get(\"partner_id\")\n\tif v == nil {\n\t\treturn false, -1\n\t}\n\treturn true, v.(int)\n}\n\n\nvar _ mvc.Filter = new(baseC)\n\ntype baseC struct {\n}\n\nfunc (this *baseC) Requesting(ctx *web.Context) bool {\n\tif b, _ := chkLogin(ctx); !b {\n\t\tredirect(ctx)\n\t\treturn false\n\t}\n\treturn true\n}\nfunc (this *baseC) RequestEnd(ctx *web.Context) {\n}\n\n\nfunc (this *baseC) GetPartnerId(ctx *web.Context) int {\n\tv := ctx.Session().Get(\"partner_id\")\n\tif v == nil {\n\t\tthis.Requesting(ctx)\n\t\treturn -1\n\t}\n\treturn v.(int)\n}\n\nfunc (this *baseC) GetPartner(ctx *web.Context) (*partner.ValuePartner, error) {\n\treturn dps.PartnerService.GetPartner(this.GetPartnerId(ctx))\n}\n\n\nfunc (this *baseC) ErrorOutput(ctx *web.Context, err string) {\n\tctx.Response.Write([]byte(\"{error:\\\"\" + err + \"\\\"}\"))\n}\n\nfunc redirect(ctx *web.Context) ", "output": "{\n\tr, w := ctx.Request, ctx.Response\n\tw.Write([]byte(\"\"))\n}"} {"input": "package goque\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"encoding/gob\"\n)\n\n\ntype Item struct {\n\tID uint64\n\tKey []byte\n\tValue []byte\n}\n\n\n\n\n\n\n\n\n\n\nfunc (i *Item) ToObject(value interface{}) error {\n\tbuffer := bytes.NewBuffer(i.Value)\n\tdec := gob.NewDecoder(buffer)\n\treturn dec.Decode(value)\n}\n\n\ntype PriorityItem struct {\n\tID uint64\n\tPriority uint8\n\tKey []byte\n\tValue []byte\n}\n\n\nfunc (pi *PriorityItem) ToString() string {\n\treturn string(pi.Value)\n}\n\n\n\n\n\n\n\nfunc (pi *PriorityItem) ToObject(value interface{}) error {\n\tbuffer := bytes.NewBuffer(pi.Value)\n\tdec := gob.NewDecoder(buffer)\n\treturn dec.Decode(value)\n}\n\n\nfunc idToKey(id uint64) []byte {\n\tkey := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(key, id)\n\treturn key\n}\n\n\nfunc keyToID(key []byte) uint64 {\n\treturn binary.BigEndian.Uint64(key)\n}\n\nfunc (i *Item) ToString() string ", "output": "{\n\treturn string(i.Value)\n}"} {"input": "package builtins\n\nimport (\n\t\"fmt\"\n)\n\ntype loadError struct {\n\tfilename string\n\tcallstack string\n\tvalueStub\n}\n\nfunc NewLoadError(name string, callstack string) *loadError {\n\treturn &loadError{filename: name, callstack: callstack}\n}\n\nfunc (err *loadError) String() string {\n\treturn \"LoadError\"\n}\n\n\n\nfunc (err *loadError) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"LoadError: cannot load such file -- %s\\n%s\", err.filename, err.callstack)\n}"} {"input": "package solution\n\nimport (\n\t\"testing\"\n\t\"testing/quick\"\n)\n\n\n\nfunc TestGetSum(t *testing.T) ", "output": "{\n\texpect := func(a, b int) int { return a + b }\n\tif err := quick.CheckEqual(getSum, expect, nil); err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package repositories\n\nimport (\n\t\"errors\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/jhaldiman/decision-magic/models\"\n\t\"github.com/jhaldiman/decision-magic/services\"\n)\n\ntype (\n\tIUserRepository interface {\n\t\tCreate(user models.User) error\n\t\tAll() ([]models.User, error)\n\t\tExists(email string) (bool, error)\n\t\tGetByEmail(email string) (*models.User, error)\n\t\tDeleteByEmail(email string) error\n\t}\n\n\tuserRepository struct {\n\t\tservice services.IUserService\n\t}\n)\n\nfunc (u userRepository) Create(user models.User) error {\n\texists, err := u.Exists(user.EmailAddress)\n\n\tif err != nil {\n\t\tif err.Error() != \"datastore: no such entity\" {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif exists {\n\t\treturn errors.New(\"That email address is already in use.\")\n\t}\n\n\t_, err = u.service.Upsert(user, nil)\n\n\treturn err\n}\n\nfunc (u userRepository) All() ([]models.User, error) {\n\treturn u.service.All()\n}\n\nfunc (u userRepository) GetByEmail(email string) (*models.User, error) {\n\tkey := u.service.CreateKey(email)\n\treturn u.service.Get(key)\n}\n\n\n\nfunc (u userRepository) DeleteByEmail(email string) error {\n\tkey := u.service.CreateKey(email)\n\treturn u.service.Delete(key)\n}\n\n\nfunc NewUserRepository(ctx context.Context) (IUserRepository, error) {\n\tservice, err := services.NewUserService(ctx)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn userRepository{\n\t\tservice: service,\n\t}, nil\n}\n\nfunc (u userRepository) Exists(email string) (bool, error) ", "output": "{\n\tkey := u.service.CreateKey(email)\n\t_, err := u.service.Get(key)\n\n\tif err == nil {\n\t\treturn true, nil\n\t}\n\n\tif err.Error() == \"datastore: no such entity\" {\n\t\treturn false, nil\n\t}\n\n\treturn false, err\n}"} {"input": "package file\n\nimport \"testing\"\n\n\n\n\n\nfunc TestRead(t *testing.T) ", "output": "{\n\tf := Fopen(\"file_test.go\", \"r\")\n\tif f.Swigcptr() == 0 {\n\t\tt.Fatal(\"fopen failed\")\n\t}\n\tif Fgetc(f) != '/' || Fgetc(f) != '/' || Fgetc(f) != ' ' || Fgetc(f) != 'C' {\n\t\tt.Error(\"read unexpected characters\")\n\t}\n\tif Fclose(f) != 0 {\n\t\tt.Error(\"fclose failed\")\n\t}\n}"} {"input": "package blb\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/baiducloud/baiducloud-sdk-go/bce\"\n)\n\n\nvar Endpoint = map[string]string{\n\t\"bj\": \"blb.bj.baidubce.com\",\n\t\"gz\": \"blb.gz.baidubce.com\",\n\t\"su\": \"blb.su.baidubce.com\",\n\t\"hk\": \"blb.hkg.baidubce.com\",\n\t\"bd\": \"blb.bd.baidubce.com\",\n}\n\n\ntype Client struct {\n\t*bce.Client\n}\n\n\nfunc NewBLBClient(config *bce.Config) *Client {\n\tbceClient := bce.NewClient(config)\n\treturn &Client{bceClient}\n}\n\n\n\n\nfunc (c *Client) GetURL(version string, params map[string]string) string ", "output": "{\n\thost := c.Endpoint\n\tif host == \"\" {\n\t\thost = Endpoint[c.GetRegion()]\n\t}\n\turiPath := version\n\treturn c.Client.GetURL(host, uriPath, params)\n}"} {"input": "package scene\n\nimport \"github.com/thinkofdeath/steven/ui\"\n\n\ntype Type struct {\n\tvisible bool\n\n\tdrawables []ui.Drawable\n\thidding bool\n}\n\n\n\n\n\nfunc (t *Type) Show() {\n\tif t.visible {\n\t\treturn\n\t}\n\tt.visible = true\n\tfor _, d := range t.drawables {\n\t\tui.AddDrawable(d)\n\t}\n}\n\n\nfunc (t *Type) Hide() {\n\tif !t.visible {\n\t\treturn\n\t}\n\tt.visible = false\n\tt.hidding = true\n\tfor _, d := range t.drawables {\n\t\tui.Remove(d)\n\t}\n\tt.hidding = false\n}\n\n\nfunc (t *Type) AddDrawable(d ui.Drawable) {\n\tt.drawables = append(t.drawables, d)\n\tif t.visible {\n\t\tui.AddDrawable(d)\n\t}\n\td.SetRemoveHook(t.removeHook)\n}\n\nfunc (t *Type) removeHook(d ui.Drawable) {\n\tif t.hidding {\n\t\treturn\n\t}\n\tfor i, dd := range t.drawables {\n\t\tif dd == d {\n\t\t\tt.drawables = append(t.drawables[:i], t.drawables[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n\n}\n\n\nfunc (t *Type) IsVisible() bool {\n\treturn t.visible\n}\n\nfunc New(visible bool) *Type ", "output": "{\n\treturn &Type{\n\t\tvisible: visible,\n\t}\n}"} {"input": "package gtk\n\n\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n\n\t\"github.com/untoldwind/amintk/gdk\"\n)\n\n\ntype Image struct {\n\tWidget\n}\n\n\nfunc ImageNew() *Image {\n\tc := C.gtk_image_new()\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\nfunc (v *Image) native() *C.GtkImage {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn (*C.GtkImage)(v.Native())\n}\n\n\nfunc ImageNewFromIconName(iconName string, size IconSize) *Image {\n\tcstr := C.CString(iconName)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_image_new_from_icon_name((*C.gchar)(cstr),\n\t\tC.GtkIconSize(size))\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\n\nfunc ImageNewFromPixbuf(pixbuf *gdk.Pixbuf) *Image {\n\tptr := (*C.GdkPixbuf)(pixbuf.Native())\n\tc := C.gtk_image_new_from_pixbuf(ptr)\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\n\n\n\nfunc (v *Image) Clear() {\n\tC.gtk_image_clear(v.native())\n}\n\n\nfunc (v *Image) SetFromPixbuf(pixbuf *gdk.Pixbuf) {\n\tpbptr := (*C.GdkPixbuf)(pixbuf.Native())\n\tC.gtk_image_set_from_pixbuf(v.native(), pbptr)\n}\n\nfunc wrapImage(p unsafe.Pointer) *Image ", "output": "{\n\tif widget := wrapWidget(p); widget != nil {\n\t\treturn &Image{Widget: *widget}\n\t}\n\treturn nil\n}"} {"input": "package common\n\nimport \"math/big\"\n\ntype _N_ [_S_]byte\n\nfunc BytesTo_N_(b []byte) _N_ {\n\tvar h _N_\n\th.SetBytes(b)\n\treturn h\n}\nfunc StringTo_N_(s string) _N_ { return BytesTo_N_([]byte(s)) }\nfunc BigTo_N_(b *big.Int) _N_ { return BytesTo_N_(b.Bytes()) }\nfunc HexTo_N_(s string) _N_ { return BytesTo_N_(FromHex(s)) }\n\n\n\n\nfunc (h _N_) Str() string { return string(h[:]) }\nfunc (h _N_) Bytes() []byte { return h[:] }\nfunc (h _N_) Big() *big.Int { return Bytes2Big(h[:]) }\nfunc (h _N_) Hex() string { return \"0x\" + Bytes2Hex(h[:]) }\n\n\nfunc (h *_N_) SetBytes(b []byte) {\n\tif len(b) > len(h) {\n\t\tb = b[len(b)-_S_:]\n\t}\n\n\tfor i := len(b) - 1; i >= 0; i-- {\n\t\th[_S_-len(b)+i] = b[i]\n\t}\n}\n\n\nfunc (h *_N_) SetString(s string) { h.SetBytes([]byte(s)) }\n\n\n\n\nfunc (h *_N_) Set(other _N_) ", "output": "{\n\tfor i, v := range other {\n\t\th[i] = v\n\t}\n}"} {"input": "package tristate\n\ntype StateValue int\n\nconst (\n\tTRISTATE_SUCCESS StateValue = iota\n\tTRISTATE_FAILRUE\n\tTRISTATE_UNKNOWN\n)\n\ntype TriState struct {\n\tState StateValue\n\tErr error\n}\n\n\n\nfunc NewUnknown(err error) *TriState {\n\tif err == nil {\n\t\tpanic(\"error not set\")\n\t}\n\treturn &TriState{TRISTATE_UNKNOWN, err}\n}\n\nfunc NewFailure(err error) *TriState {\n\tif err == nil {\n\t\tpanic(\"error not set\")\n\t}\n\treturn &TriState{TRISTATE_FAILRUE, err}\n}\n\nfunc (state *TriState) Error() string {\n\treturn state.Err.Error()\n}\n\nfunc (state *TriState) IsSuccess() bool {\n\treturn state == nil || state.State == TRISTATE_SUCCESS\n}\n\nfunc (state *TriState) IsFailure() bool {\n\treturn state != nil && state.State == TRISTATE_FAILRUE\n}\n\nfunc (state *TriState) IsUnknown() bool {\n\treturn state != nil && state.State == TRISTATE_UNKNOWN\n}\n\nfunc NewSuccess() *TriState ", "output": "{\n\treturn nil\n}"} {"input": "package service\n\nimport \"os\"\n\ntype options struct {\n\tPort string\n}\n\n\n\nfunc getOptions() *options ", "output": "{\n\tport := os.Getenv(\"PORT\")\n\n\tif port == \"\" {\n\t\tport = \"8081\"\n\t}\n\n\treturn &options{port}\n}"} {"input": "package client\n\nimport (\n\t\"encoding/xml\"\n)\n\ntype Frame struct {\n\tID string `xml:\"id,attr\"`\n\tFrameType int\n\tOpMode int\n\tName string\n\tContact string\n\tOSVersion string\n\tVersion string\n\tIsConnected int\n\tSyncedSetting int\n\n}\n\n\ntype FrameCollection map[string]Frame\n\n\n\nfunc (col FrameCollection) MarshalJSON() ([]byte, error) {\n\treturn marshalJSONMap(col)\n}\n\nfunc (col *FrameCollection) UnmarshalXML(d *xml.Decoder, e xml.StartElement) error ", "output": "{\n\treturn unmarshalXMLCol(col, d, e)\n}"} {"input": "package sortedmap\n\nimport (\n\t\"testing\"\n\n\t\"github.com/umpc/go-sortedmap/asc\"\n)\n\nfunc insertRecord(b *testing.B) {\n\trecords := randRecords(1)\n\tsm := New(0, asc.Time)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsm.Insert(records[0].Key, records[0].Val)\n\n\t\tb.StopTimer()\n\t\trecords = randRecords(1)\n\t\tsm = New(0, asc.Time)\n\t\tb.StartTimer()\n\t}\n}\n\nfunc batchInsertRecords(b *testing.B, n int) {\n\trecords := randRecords(n)\n\tsm := New(0, asc.Time)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsm.BatchInsert(records)\n\n\t\tb.StopTimer()\n\t\trecords = randRecords(n)\n\t\tsm = New(0, asc.Time)\n\t\tb.StartTimer()\n\t}\n}\n\n\n\nfunc BenchmarkBatchInsert10Records(b *testing.B) {\n\tbatchInsertRecords(b, 10)\n}\n\nfunc BenchmarkBatchInsert100Records(b *testing.B) {\n\tbatchInsertRecords(b, 100)\n}\n\nfunc BenchmarkBatchInsert1000Records(b *testing.B) {\n\tbatchInsertRecords(b, 1000)\n}\n\nfunc BenchmarkBatchInsert10000Records(b *testing.B) {\n\tbatchInsertRecords(b, 10000)\n}\n\nfunc BenchmarkInsert1Record(b *testing.B) ", "output": "{\n\tinsertRecord(b)\n}"} {"input": "package views\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\tui \"github.com/jroimartin/gocui\"\n)\n\nvar (\n\thelpWidth = 49\n\thelpHeight = 15\n\ttpl = `%s C-x means Control x`\n)\n\ntype help struct {\n\tname string\n\tcoords coords\n\tbody []byte\n}\n\nfunc newHelp(w, h int) *help {\n\treturn &help{\n\t\tname: \"help\",\n\t}\n}\n\nfunc getHelpCoords(g *ui.Gui) coords {\n\tmaxX, maxY := g.Size()\n\tx1 := maxX/2 - helpWidth/2\n\tx2 := maxX/2 + helpWidth/2\n\ty1 := maxY/2 - helpHeight/2\n\ty2 := maxY/2 + helpHeight/2 + helpHeight%2\n\treturn coords{x1: x1, y1: y1, x2: x2, y2: y2}\n}\n\n\n\nfunc (h *help) hide(g *ui.Gui, v *ui.View) error {\n\tv.Clear()\n\treturn g.DeleteView(h.name)\n}\n\nfunc (h *help) getBody(keys []key) []byte {\n\tout := &bytes.Buffer{}\n\tfor _, key := range keys {\n\t\th := key.help\n\t\tif h.key != \"\" {\n\t\t\tfmt.Fprintf(out, fmt.Sprintf(\"%s %s\\n\", c3(h.key), c1(fmt.Sprintf(fmt.Sprintf(\"%%%ds\", helpWidth-len(h.key)-4), h.body))))\n\t\t}\n\t}\n\treturn []byte(fmt.Sprintf(tpl, out.String()))\n}\n\nfunc (h *help) show(g *ui.Gui, v *ui.View, keys []key) error ", "output": "{\n\tv.Editable = false\n\tif h.body == nil {\n\t\th.body = h.getBody(keys)\n\t}\n\n\tvar err error\n\n\tcoords := getHelpCoords(g)\n\n\tv, err = g.SetView(\"help\", coords.x1, coords.y1, coords.x2, coords.y2)\n\tif err != ui.ErrUnknownView {\n\t\treturn err\n\t}\n\n\tv.Title = h.name\n\n\tv.Write([]byte(h.body))\n\t_, err = g.SetCurrentView(\"help\")\n\treturn err\n}"} {"input": "package transport\n\nimport (\n\t\"context\"\n\n\t\"github.com/go-kit/kit/log\"\n)\n\n\n\ntype ErrorHandler interface {\n\tHandle(ctx context.Context, err error)\n}\n\n\ntype LogErrorHandler struct {\n\tlogger log.Logger\n}\n\nfunc NewLogErrorHandler(logger log.Logger) *LogErrorHandler {\n\treturn &LogErrorHandler{\n\t\tlogger: logger,\n\t}\n}\n\n\n\n\n\n\n\ntype ErrorHandlerFunc func(ctx context.Context, err error)\n\n\nfunc (f ErrorHandlerFunc) Handle(ctx context.Context, err error) {\n\tf(ctx, err)\n}\n\nfunc (h *LogErrorHandler) Handle(ctx context.Context, err error) ", "output": "{\n\th.logger.Log(\"err\", err)\n}"} {"input": "package runtime\n\nimport \"unsafe\"\n\n\n\n\n\n\n\n\n\nfunc atomicloadp(ptr unsafe.Pointer) unsafe.Pointer {\n\tnop()\n\treturn *(*unsafe.Pointer)(ptr)\n}\n\n\nfunc xadd64(ptr *uint64, delta int64) uint64 {\n\tfor {\n\t\told := *ptr\n\t\tif cas64(ptr, old, old+uint64(delta)) {\n\t\t\treturn old + uint64(delta)\n\t\t}\n\t}\n}\n\n\nfunc xchg64(ptr *uint64, new uint64) uint64 {\n\tfor {\n\t\told := *ptr\n\t\tif cas64(ptr, old, new) {\n\t\t\treturn old\n\t\t}\n\t}\n}\n\n\nfunc xadd(ptr *uint32, delta int32) uint32\n\n\nfunc xchg(ptr *uint32, new uint32) uint32\n\n\nfunc xchgp1(ptr unsafe.Pointer, new unsafe.Pointer) unsafe.Pointer\n\n\nfunc xchguintptr(ptr *uintptr, new uintptr) uintptr\n\n\nfunc atomicload64(ptr *uint64) uint64\n\n\nfunc atomicand8(ptr *uint8, val uint8)\n\n\nfunc atomicor8(ptr *uint8, val uint8)\n\n\n\n\nfunc cas64(ptr *uint64, old, new uint64) bool\n\n\nfunc atomicstore(ptr *uint32, val uint32)\n\n\nfunc atomicstore64(ptr *uint64, val uint64)\n\n\nfunc atomicstorep1(ptr unsafe.Pointer, val unsafe.Pointer)\n\nfunc atomicload(ptr *uint32) uint32 ", "output": "{\n\tnop()\n\treturn *ptr\n}"} {"input": "package nats\n\nimport (\n\t\"github.com/apcera/nats\"\n\t\"github.com/plimble/kuja/broker\"\n)\n\ntype natsBroker struct {\n\turl string\n\tconn *nats.Conn\n}\n\nfunc NewBroker(url string) *natsBroker {\n\treturn &natsBroker{\n\t\turl: url,\n\t}\n}\n\nfunc (n *natsBroker) Connect() error {\n\tvar err error\n\tn.conn, err = nats.Connect(n.url)\n\n\treturn err\n}\n\n\n\nfunc (n *natsBroker) Publish(topic string, msg *broker.Message) error {\n\tdata, err := msg.Marshal()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn n.conn.Publish(topic, data)\n}\n\nfunc (n *natsBroker) Subscribe(topic, queue, appId string, size int, h broker.Handler) {\n\tfor i := 0; i < size; i++ {\n\t\tn.conn.QueueSubscribe(topic, queue, func(msg *nats.Msg) {\n\t\t\tbrokerMsg := &broker.Message{}\n\t\t\tbrokerMsg.Unmarshal(msg.Data)\n\t\t\tretryCount, err := h(msg.Subject, brokerMsg)\n\t\t\tif err != nil {\n\t\t\t\tfor i := 0; i < retryCount; i++ {\n\t\t\t\t\tbrokerMsg.Retry++\n\t\t\t\t\t_, err := h(topic, brokerMsg)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc (n *natsBroker) Close() ", "output": "{\n\tn.conn.Close()\n}"} {"input": "package gotick\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n\ntype Project struct {\n\tID uint `json:\"id\"`\n\tName string `json:\"name\"`\n\tBudget float32 `json:\"budget\"`\n\tDateClosed string `json:\"date_closed\"`\n\tNotifications bool `json:\"notifications\"`\n\tBillable bool `json:\"billable\"`\n\tRecurring bool `json:\"recurring\"`\n\tClientID uint `json:\"client_id\"`\n\tOwnerID uint `json:\"owner_id\"`\n\tURL string `json:\"url\"`\n\tCreatedAt string `json:\"created_at\"`\n\tUpdatedAt string `json:\"updated_at\"`\n}\n\n\n\ntype Projects []Project\n\nfunc GetOpenProjects(tickData JSONGetter) (Projects, error) {\n\tvar allProjects Projects\n\tfoundLastPage := false\n\tcurrentPage := 1\n\tfor !foundLastPage {\n\t\tprojects, err := GetOpenProjectsOnPage(tickData, currentPage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif projects == Projects(nil) {\n\t\t\tfoundLastPage = true\n\t\t} else {\n\t\t\tallProjects = append(allProjects, projects...)\n\t\t\tcurrentPage++\n\t\t}\n\t}\n\treturn allProjects, nil\n}\n\n\n\nfunc GetProject(tickData JSONGetter, projectID int) (Project, error) {\n\tvar project Project\n\turl := fmt.Sprintf(\"/projects/%d.json\", projectID)\n\tdata, err := tickData.GetJSON(url)\n\tif err != nil {\n\t\treturn Project{}, err\n\t}\n\tif bytes.Equal(data, []byte(\"[]\")) {\n\t\treturn Project{}, nil\n\t}\n\terr = json.Unmarshal(data, &project)\n\tif err != nil {\n\t\treturn Project{}, err\n\t}\n\treturn project, nil\n}\n\nfunc GetOpenProjectsOnPage(tickData JSONGetter, page int) (Projects, error) ", "output": "{\n\tvar projects Projects\n\turl := fmt.Sprintf(\"/projects.json?page=%d\", page)\n\tdata, err := tickData.GetJSON(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif bytes.Equal(data, []byte(\"[]\")) {\n\t\treturn nil, nil\n\t}\n\terr = json.Unmarshal(data, &projects)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn projects, nil\n}"} {"input": "package helper\n\nimport (\n\t\"encoding/base64\"\n\t\"strings\"\n\t\"time\"\n\t\"github.com/insionng/yougam/libraries/flosch/pongo2.v3\"\n)\n\nfunc ConvertToBase64(in string) string {\n\treturn base64.StdEncoding.EncodeToString([]byte(in))\n}\n\nfunc ConvertToBase64ByPongo2(in *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(base64.StdEncoding.EncodeToString([]byte(in.String())))\n}\n\nfunc SplitByPongo2(in *pongo2.Value, splitor *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Split(in.String(), splitor.String()))\n}\n\nfunc MarkdownByPongo2(in *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Markdown(in.String()))\n}\n\n\n\nfunc Cropword(in string, start int, length int, symbol string) string {\n\treturn Substr(in, start, length, symbol)\n}\n\nfunc File(s string) string {\n\tif len(s) > 0 {\n\t\tif strings.HasPrefix(s, \"http\") || strings.HasPrefix(s, \"/identicon\") {\n\t\t\treturn s\n\t\t} else {\n\t\t\treturn \"/file\" + s\n\t\t}\n\t}\n\treturn s\n}\n\nfunc Unix2TimeByPongo2(in *pongo2.Value, timeLayout *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(time.Unix(int64(in.Integer()), 0).Format(timeLayout.String()))\n}\n\nfunc CropwordByPongo2(in *pongo2.Value, start *pongo2.Value, length *pongo2.Value, symbol *pongo2.Value) *pongo2.Value ", "output": "{\n\treturn pongo2.AsValue(Substr(in.String(), start.Integer(), length.Integer(), symbol.String()))\n}"} {"input": "package proj4go\n\nimport (\n\t\"fmt\"\n\n\tgeo \"github.com/terrascope/geometry\"\n)\n\n\ntype Projection interface {\n\tForward([]geo.Point) error\n\tInverse([]geo.Point) error\n}\n\nfunc NewProjection(proj4Str string) (Projection, error) {\n\n\tproj4, err := ParseProj4String(proj4Str)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch proj4.Proj {\n\tcase \"aea\":\n\t\treturn NewAEA(proj4), nil\n\tcase \"merc\":\n\t\treturn NewMerc(proj4), nil\n\tcase \"equi\":\n\t\treturn NewEqui(proj4), nil\n\tcase \"mill\":\n\t\treturn NewMiller(proj4), nil\n\tcase \"sinu\":\n\t\treturn NewSinu(proj4), nil\n\tcase \"longlat\":\n\t\treturn NewLonLat(proj4), nil\n\t}\n\treturn nil, fmt.Errorf(\"could not find projection %s in list\", proj4.Proj)\n}\n\nfunc Forwards(dst string, pts []geo.Point) error {\n\n\tproj, err := NewProjection(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = proj.Forward(pts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc Transform(src, dst string, pts []geo.Point) error {\n\tif src == dst {\n\t\treturn nil\n\t}\n\n\tif err := Inverse(dst, pts); err != nil {\n\t\treturn err\n\t}\n\tif err := Forwards(src, pts); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc Inverse(dst string, pts []geo.Point) error ", "output": "{\n\n\tproj, err := NewProjection(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = proj.Inverse(pts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package sqldimel\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestBuildGenerate(t *testing.T) ", "output": "{\n\tb := NewBuilderProc(\"user\", NewBuildProcessorDefault())\n\tb.Add(\"id\", 1)\n\tb.Add(\"name\", \"Monte Marto\")\n\tb.Add(\"dob\", time.Now())\n\tb.Add(\"optional\", nil)\n\tb.Add(\"weight\", 80.2)\n\n\tb.Where(\"id = ? and weight > ?\", 1, 70.2)\n\n\tif b.Output(UPDATE) != \"UPDATE user SET id=?, name=?, dob=?, optional=?, weight=? WHERE id = ? and weight > ?\" {\n\t\tt.Error(\"Invalid generated SQL\")\n\t}\n\n\tif b.OutputParams(UPDATE)[1] != \"Monte Marto\" {\n\t\tt.Error(\"Invalid parameter order\")\n\t}\n}"} {"input": "package flect\n\nimport (\n\t\"strings\"\n\t\"unicode\"\n)\n\nvar spaces = []rune{'_', ' ', ':', '-', '/'}\n\nfunc isSpace(c rune) bool {\n\tfor _, r := range spaces {\n\t\tif r == c {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn unicode.IsSpace(c)\n}\n\n\n\nfunc abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n\nfunc xappend(a []string, ss ...string) []string ", "output": "{\n\tfor _, s := range ss {\n\t\ts = strings.TrimSpace(s)\n\t\tfor _, x := range spaces {\n\t\t\ts = strings.Trim(s, string(x))\n\t\t}\n\t\tif _, ok := baseAcronyms[strings.ToUpper(s)]; ok {\n\t\t\ts = strings.ToUpper(s)\n\t\t}\n\t\tif s != \"\" {\n\t\t\ta = append(a, s)\n\t\t}\n\t}\n\treturn a\n}"} {"input": "package shasimd\n\nimport (\n\t\"github.com/1lann/krist-miner/deprecated/sha2\"\n\t\"github.com/1lann/sha256-simd\"\n)\n\ntype generator struct{}\n\nfunc (g *generator) Sum256Number(data []byte) int64 {\n\tvar start [64]byte\n\tstart[41] = 128\n\tstart[63] = 72\n\tstart[62] = 1\n\n\tif len(data) != 41 {\n\t\tpanic(\"must be exactly 41 long\")\n\t}\n\tcopy(start[:], data)\n\n\treturn sha256.SumToNum256(start[:])\n}\n\n\n\nfunc init() {\n\tsha2.RegisterAlgorithm(\"simd\", func() sha2.SumNumberAlgorithm {\n\t\treturn &generator{}\n\t})\n}\n\nfunc (g *generator) Sum256NumberCmp(data []byte, work int64) bool ", "output": "{\n\tvar start [64]byte\n\tstart[41] = 128\n\tstart[63] = 72\n\tstart[62] = 1\n\n\tif len(data) != 41 {\n\t\tpanic(\"must be exactly 41 long\")\n\t}\n\tcopy(start[:], data)\n\n\treturn sha256.SumCmp256(start[:], uint32(work))\n}"} {"input": "package util\n\nimport (\n\t\"sort\"\n\n\t\"github.com/prometheus/common/model\"\n\t\"github.com/weaveworks/cortex/pkg/prom1/storage/metric\"\n)\n\n\n\ntype SampleStreamIterator struct {\n\tss *model.SampleStream\n}\n\n\n\n\n\nfunc (it SampleStreamIterator) Metric() metric.Metric {\n\treturn metric.Metric{Metric: it.ss.Metric}\n}\n\n\nfunc (it SampleStreamIterator) ValueAtOrBeforeTime(ts model.Time) model.SamplePair {\n\ti := sort.Search(len(it.ss.Values), func(n int) bool {\n\t\treturn it.ss.Values[n].Timestamp.After(ts)\n\t})\n\tif i == 0 {\n\t\treturn model.SamplePair{Timestamp: model.Earliest}\n\t}\n\treturn it.ss.Values[i-1]\n}\n\n\nfunc (it SampleStreamIterator) RangeValues(in metric.Interval) []model.SamplePair {\n\tn := len(it.ss.Values)\n\tstart := sort.Search(n, func(i int) bool {\n\t\treturn !it.ss.Values[i].Timestamp.Before(in.OldestInclusive)\n\t})\n\tend := sort.Search(n, func(i int) bool {\n\t\treturn it.ss.Values[i].Timestamp.After(in.NewestInclusive)\n\t})\n\n\tif start == n {\n\t\treturn nil\n\t}\n\n\treturn it.ss.Values[start:end]\n}\n\n\nfunc (it SampleStreamIterator) Close() {}\n\nfunc NewSampleStreamIterator(ss *model.SampleStream) SampleStreamIterator ", "output": "{\n\treturn SampleStreamIterator{ss: ss}\n}"} {"input": "package selinux\n\n\n\n\n\ntype realSELinuxRunner struct{}\n\nvar _ SELinuxRunner = &realSELinuxRunner{}\n\nfunc (_ *realSELinuxRunner) Getfilecon(path string) (string, error) {\n\treturn \"\", nil\n}\n\n\nfunc SetFileLabel(path string, label string) error {\n\treturn nil\n}\n\nfunc SELinuxEnabled() bool ", "output": "{\n\treturn false\n}"} {"input": "package decision\n\nimport (\n\t\"time\"\n\n\twl \"github.com/jbenet/go-ipfs/exchange/bitswap/wantlist\"\n\tpeer \"github.com/jbenet/go-ipfs/p2p/peer\"\n\tu \"github.com/jbenet/go-ipfs/util\"\n)\n\n\n\ntype keySet map[u.Key]struct{}\n\n\n\n\n\ntype ledger struct {\n\tPartner peer.ID\n\n\tAccounting debtRatio\n\n\tfirstExchange time.Time\n\n\tlastExchange time.Time\n\n\texchangeCount uint64\n\n\twantList *wl.Wantlist\n\n\tsentToPeer map[u.Key]time.Time\n}\n\ntype debtRatio struct {\n\tBytesSent uint64\n\tBytesRecv uint64\n}\n\nfunc (dr *debtRatio) Value() float64 {\n\treturn float64(dr.BytesSent) / float64(dr.BytesRecv+1)\n}\n\nfunc (l *ledger) SentBytes(n int) {\n\tl.exchangeCount++\n\tl.lastExchange = time.Now()\n\tl.Accounting.BytesSent += uint64(n)\n}\n\nfunc (l *ledger) ReceivedBytes(n int) {\n\tl.exchangeCount++\n\tl.lastExchange = time.Now()\n\tl.Accounting.BytesRecv += uint64(n)\n}\n\n\nfunc (l *ledger) Wants(k u.Key, priority int) {\n\tlog.Debugf(\"peer %s wants %s\", l.Partner, k)\n\tl.wantList.Add(k, priority)\n}\n\nfunc (l *ledger) CancelWant(k u.Key) {\n\tl.wantList.Remove(k)\n}\n\nfunc (l *ledger) WantListContains(k u.Key) (wl.Entry, bool) {\n\treturn l.wantList.Contains(k)\n}\n\nfunc (l *ledger) ExchangeCount() uint64 {\n\treturn l.exchangeCount\n}\n\nfunc newLedger(p peer.ID) *ledger ", "output": "{\n\treturn &ledger{\n\t\twantList: wl.New(),\n\t\tPartner: p,\n\t\tsentToPeer: make(map[u.Key]time.Time),\n\t}\n}"} {"input": "package heap\n\nimport (\n\t\"sync\"\n)\n\ntype Monitor struct {\n\towner interface{} \n\townerLock sync.Locker\n\tlock sync.Locker\n\tentryCount int\n\tcond *sync.Cond\n}\n\n\n\nfunc (monitor *Monitor) Enter(thread interface{}) {\n\tmonitor.ownerLock.Lock()\n\tif monitor.owner == thread {\n\t\tmonitor.entryCount++\n\t\tmonitor.ownerLock.Unlock()\n\t\treturn\n\t} else {\n\t\tmonitor.ownerLock.Unlock()\n\t}\n\n\tmonitor.lock.Lock()\n\n\tmonitor.ownerLock.Lock()\n\tmonitor.owner = thread\n\tmonitor.entryCount = 1\n\tmonitor.ownerLock.Unlock()\n}\n\nfunc (monitor *Monitor) Exit(thread interface{}) {\n\tmonitor.ownerLock.Lock()\n\tvar _unlock bool\n\tif monitor.owner == thread {\n\t\tmonitor.entryCount--\n\t\tif monitor.entryCount == 0 {\n\t\t\tmonitor.owner = nil\n\t\t\t_unlock = true\n\t\t}\n\t}\n\tmonitor.ownerLock.Unlock()\n\n\tif _unlock {\n\t\tmonitor.lock.Unlock()\n\t}\n}\n\nfunc (monitor *Monitor) HasOwner(thread interface{}) bool {\n\tmonitor.ownerLock.Lock()\n\tisOwner := monitor.owner == thread\n\tmonitor.ownerLock.Unlock()\n\n\treturn isOwner\n}\n\nfunc (monitor *Monitor) Wait() {\n\tmonitor.ownerLock.Lock()\n\toldEntryCount := monitor.entryCount\n\toldOwner := monitor.owner\n\tmonitor.entryCount = 0\n\tmonitor.owner = nil\n\tmonitor.ownerLock.Unlock()\n\n\tmonitor.cond.Wait()\n\n\tmonitor.ownerLock.Lock()\n\tmonitor.entryCount = oldEntryCount\n\tmonitor.owner = oldOwner\n\tmonitor.ownerLock.Unlock()\n}\n\nfunc (monitor *Monitor) NotifyAll() {\n\tmonitor.cond.Broadcast()\n}\n\nfunc newMonitor() *Monitor ", "output": "{\n\tm := &Monitor{}\n\tm.ownerLock = &sync.Mutex{}\n\tm.lock = &sync.Mutex{}\n\tm.cond = sync.NewCond(m.lock)\n\treturn m\n}"} {"input": "package netutil\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\n\n\nfunc AwaitReachable(addr string, maxWait time.Duration) error ", "output": "{\n\tdone := time.Now().Add(maxWait)\n\tfor time.Now().Before(done) {\n\t\tc, err := net.Dial(\"tcp\", addr)\n\t\tif err == nil {\n\t\t\tc.Close()\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\treturn errors.New(\"timeout\")\n}"} {"input": "package tc\n\n\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype CRStates struct {\n\tCaches map[CacheName]IsAvailable `json:\"caches\"`\n\tDeliveryService map[DeliveryServiceName]CRStatesDeliveryService `json:\"deliveryServices\"`\n}\n\n\ntype CRStatesDeliveryService struct {\n\tDisabledLocations []CacheGroupName `json:\"disabledLocations\"`\n\tIsAvailable bool `json:\"isAvailable\"`\n}\n\n\ntype IsAvailable struct {\n\tIsAvailable bool `json:\"isAvailable\"`\n}\n\n\nfunc NewCRStates() CRStates {\n\treturn CRStates{\n\t\tCaches: map[CacheName]IsAvailable{},\n\t\tDeliveryService: map[DeliveryServiceName]CRStatesDeliveryService{},\n\t}\n}\n\n\nfunc (a CRStates) Copy() CRStates {\n\tb := NewCRStates()\n\tfor k, v := range a.Caches {\n\t\tb.Caches[k] = v\n\t}\n\tfor k, v := range a.DeliveryService {\n\t\tb.DeliveryService[k] = v\n\t}\n\treturn b\n}\n\n\nfunc (a CRStates) CopyDeliveryServices() map[DeliveryServiceName]CRStatesDeliveryService {\n\tb := map[DeliveryServiceName]CRStatesDeliveryService{}\n\tfor k, v := range a.DeliveryService {\n\t\tb[k] = v\n\t}\n\treturn b\n}\n\n\nfunc (a CRStates) CopyCaches() map[CacheName]IsAvailable {\n\tb := map[CacheName]IsAvailable{}\n\tfor k, v := range a.Caches {\n\t\tb[k] = v\n\t}\n\treturn b\n}\n\n\n\n\n\nfunc CRStatesUnMarshall(body []byte) (CRStates, error) {\n\tvar crStates CRStates\n\terr := json.Unmarshal(body, &crStates)\n\treturn crStates, err\n}\n\nfunc CRStatesMarshall(states CRStates) ([]byte, error) ", "output": "{\n\treturn json.Marshal(states)\n}"} {"input": "package ast\n\nimport (\n \"fmt\"\n \"github.com/kedebug/LispEx/binder\"\n \"github.com/kedebug/LispEx/constants\"\n \"github.com/kedebug/LispEx/scope\"\n . \"github.com/kedebug/LispEx/value\"\n)\n\ntype Set struct {\n Pattern *Name\n Value Node\n}\n\nfunc NewSet(pattern *Name, val Node) *Set {\n return &Set{Pattern: pattern, Value: val}\n}\n\n\n\nfunc (self *Set) String() string {\n return fmt.Sprintf(\"(%s %s %s)\", constants.SET, self.Pattern, self.Value)\n}\n\nfunc (self *Set) Eval(env *scope.Scope) Value ", "output": "{\n val := self.Value.Eval(env)\n binder.Assign(env, self.Pattern.Identifier, val)\n return nil\n}"} {"input": "package resource\n\nimport \"github.com/docker/infrakit/pkg/spi/resource\"\n\n\ntype Plugin struct {\n\n\tDoCommit func(spec resource.Spec, pretend bool) (string, error)\n\n\tDoDestroy func(spec resource.Spec, pretend bool) (string, error)\n\n\tDoDescribeResources func(spec resource.Spec) (string, error)\n}\n\n\n\n\n\nfunc (t *Plugin) Destroy(spec resource.Spec, pretend bool) (string, error) {\n\treturn t.DoDestroy(spec, pretend)\n}\n\n\nfunc (t *Plugin) DescribeResources(spec resource.Spec) (string, error) {\n\treturn t.DoDescribeResources(spec)\n}\n\nfunc (t *Plugin) Commit(spec resource.Spec, pretend bool) (string, error) ", "output": "{\n\treturn t.DoCommit(spec, pretend)\n}"} {"input": "package nes\n\nimport \"log\"\n\ntype Mapper2 struct {\n\t*Cartridge\n\tprgBank1 int\n\tprgBank2 int\n}\n\nfunc NewMapper2(cartridge *Cartridge) Mapper {\n\tprgBanks := len(cartridge.PRG) / 0x4000\n\tprgBank1 := 0\n\tprgBank2 := prgBanks - 1\n\treturn &Mapper2{cartridge, prgBank1, prgBank2}\n}\n\nfunc (m *Mapper2) Step() {\n}\n\nfunc (m *Mapper2) Read(address uint16) byte {\n\tswitch {\n\tcase address < 0x2000:\n\t\treturn m.CHR[address]\n\tcase address >= 0xC000:\n\t\tindex := m.prgBank2*0x4000 + int(address-0xC000)\n\t\treturn m.PRG[index]\n\tcase address >= 0x8000:\n\t\tindex := m.prgBank1*0x4000 + int(address-0x8000)\n\t\treturn m.PRG[index]\n\tcase address >= 0x6000:\n\t\tindex := int(address) - 0x6000\n\t\treturn m.SRAM[index]\n\tdefault:\n\t\tlog.Fatalf(\"unhandled mapper2 read at address: 0x%04X\", address)\n\t}\n\treturn 0\n}\n\n\n\nfunc (m *Mapper2) Write(address uint16, value byte) ", "output": "{\n\tswitch {\n\tcase address < 0x2000:\n\t\tm.CHR[address] = value\n\tcase address >= 0x8000:\n\t\tm.prgBank1 = int(value)\n\tcase address >= 0x6000:\n\t\tindex := int(address) - 0x6000\n\t\tm.SRAM[index] = value\n\tdefault:\n\t\tlog.Fatalf(\"unhandled mapper2 write at address: 0x%04X\", address)\n\t}\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\tgolangswaggerpaths \"path\"\n\t\"strings\"\n)\n\n\ntype GetUserURL struct {\n\tID string\n\n\t_basePath string\n\t_ struct{}\n}\n\n\n\n\nfunc (o *GetUserURL) WithBasePath(bp string) *GetUserURL {\n\to.SetBasePath(bp)\n\treturn o\n}\n\n\n\n\nfunc (o *GetUserURL) SetBasePath(bp string) {\n\to._basePath = bp\n}\n\n\n\n\n\nfunc (o *GetUserURL) Must(u *url.URL, err error) *url.URL {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif u == nil {\n\t\tpanic(\"url can't be nil\")\n\t}\n\treturn u\n}\n\n\nfunc (o *GetUserURL) String() string {\n\treturn o.Must(o.Build()).String()\n}\n\n\nfunc (o *GetUserURL) BuildFull(scheme, host string) (*url.URL, error) {\n\tif scheme == \"\" {\n\t\treturn nil, errors.New(\"scheme is required for a full url on GetUserURL\")\n\t}\n\tif host == \"\" {\n\t\treturn nil, errors.New(\"host is required for a full url on GetUserURL\")\n\t}\n\n\tbase, err := o.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbase.Scheme = scheme\n\tbase.Host = host\n\treturn base, nil\n}\n\n\nfunc (o *GetUserURL) StringFull(scheme, host string) string {\n\treturn o.Must(o.BuildFull(scheme, host)).String()\n}\n\nfunc (o *GetUserURL) Build() (*url.URL, error) ", "output": "{\n\tvar result url.URL\n\n\tvar _path = \"/users/{id}\"\n\n\tid := o.ID\n\tif id != \"\" {\n\t\t_path = strings.Replace(_path, \"{id}\", id, -1)\n\t} else {\n\t\treturn nil, errors.New(\"ID is required on GetUserURL\")\n\t}\n\n\t_basePath := o._basePath\n\tif _basePath == \"\" {\n\t\t_basePath = \"/\"\n\t}\n\tresult.Path = golangswaggerpaths.Join(_basePath, _path)\n\n\treturn &result, nil\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/hyperledger/fabric/common/channelconfig\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n)\n\n\ntype Orderer struct {\n\tConsensusTypeVal string\n\tBatchSizeVal *ab.BatchSize\n\tBatchTimeoutVal time.Duration\n\tKafkaBrokersVal []string\n\tMaxChannelsCountVal uint64\n\tOrganizationsVal map[string]channelconfig.Org\n\tCapabilitiesVal channelconfig.OrdererCapabilities\n}\n\n\nfunc (scm *Orderer) ConsensusType() string {\n\treturn scm.ConsensusTypeVal\n}\n\n\nfunc (scm *Orderer) BatchSize() *ab.BatchSize {\n\treturn scm.BatchSizeVal\n}\n\n\nfunc (scm *Orderer) BatchTimeout() time.Duration {\n\treturn scm.BatchTimeoutVal\n}\n\n\nfunc (scm *Orderer) KafkaBrokers() []string {\n\treturn scm.KafkaBrokersVal\n}\n\n\nfunc (scm *Orderer) MaxChannelsCount() uint64 {\n\treturn scm.MaxChannelsCountVal\n}\n\n\nfunc (scm *Orderer) Organizations() map[string]channelconfig.Org {\n\treturn scm.OrganizationsVal\n}\n\n\n\n\n\ntype OrdererCapabilities struct {\n\tSupportedErr error\n\n\tSetChannelModPolicyDuringCreateVal bool\n\n\tResubmissionVal bool\n}\n\n\nfunc (oc *OrdererCapabilities) Supported() error {\n\treturn oc.SupportedErr\n}\n\n\nfunc (oc *OrdererCapabilities) SetChannelModPolicyDuringCreate() bool {\n\treturn oc.SetChannelModPolicyDuringCreateVal\n}\n\n\nfunc (oc *OrdererCapabilities) Resubmission() bool {\n\treturn oc.ResubmissionVal\n}\n\nfunc (scm *Orderer) Capabilities() channelconfig.OrdererCapabilities ", "output": "{\n\treturn scm.CapabilitiesVal\n}"} {"input": "package datatransfer \n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\n\n\n\nfunc DefaultAuthScopes() []string {\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/bigquery\",\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t\t\"https:www.googleapis.com/auth/cloud-platform.read-only\",\n\t}\n}\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context ", "output": "{\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}"} {"input": "package elements\n\nimport \"github.com/fileformats/graphics/jt/model\"\n\n\n\n\n\n\ntype PropertyTable struct {\n\tVersionNumber int16\n\tPropertiesCount int32\n\tProperties map[int32]ElementPropertyTable\n}\n\n\n\n\n\ntype ElementPropertyTable struct {\n\tValues map[int32]int32\n}\n\nfunc (n *ElementPropertyTable) Read(c *model.Context) error {\n\tif n.Values == nil {\n\t\tn.Values = map[int32]int32{}\n\t}\n\tfor {\n\t\tobjectId := c.Data.Int32()\n\t\tif objectId == 0 || c.Data.GetError() != nil {\n\t\t\tbreak\n\t\t}\n\t\tn.Values[objectId] = c.Data.Int32()\n\t}\n\treturn c.Data.GetError()\n}\n\nfunc (n *PropertyTable) Read(c *model.Context) error ", "output": "{\n\tc.LogGroup(\"NodePropertyTable\")\n\tdefer c.LogGroupEnd()\n\n\tn.Properties = map[int32]ElementPropertyTable{}\n\n\tn.VersionNumber = c.Data.Int16()\n\tc.Log(\"VersionNumber: %d\", n.VersionNumber)\n\n\tn.PropertiesCount = c.Data.Int32()\n\tc.Log(\"PropertiesCount: %d\", n.PropertiesCount)\n\n\tfor i := 0; i < int(n.PropertiesCount); i++ {\n\t\tobjectId := c.Data.Int32()\n\t\ttable := ElementPropertyTable{map[int32]int32{}}\n\t\t(&table).Read(c)\n\n\t\tn.Properties[objectId] = table\n\t}\n\n\n\treturn c.Data.GetError()\n}"} {"input": "package options\n\nimport (\n\t\"github.com/spf13/pflag\"\n\n\tjobconfig \"k8s.io/kubernetes/pkg/controller/job/config\"\n)\n\n\ntype JobControllerOptions struct {\n\t*jobconfig.JobControllerConfiguration\n}\n\n\nfunc (o *JobControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n}\n\n\n\n\n\nfunc (o *JobControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}\n\nfunc (o *JobControllerOptions) ApplyTo(cfg *jobconfig.JobControllerConfiguration) error ", "output": "{\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentJobSyncs = o.ConcurrentJobSyncs\n\n\treturn nil\n}"} {"input": "package utils\n\nimport \"fmt\"\n\nfunc ExampleStringSet_Add() {\n\tset := NewStringSet()\n\tset.Add(\"a\")\n\tset.Add(\"b\")\n\n\tfmt.Println(set)\n\tset.Add(\"a\")\n\tfmt.Println(set)\n\n}\n\nfunc ExampleNewStringSet() {\n\ta := NewStringSet()\n\ta.Add(\"a\")\n\ta.Add(\"b\")\n\n\tb := NewStringSet(\"b\", \"a\")\n\n\tfmt.Println(a.Equals(b))\n\n}\n\nfunc ExampleNewStringSetFromStringMapKeys() {\n\tm := map[string]string{\n\t\t\"a\": \"some a value\",\n\t\t\"b\": \"some b value\",\n\t}\n\n\tset := NewStringSetFromStringMapKeys(m)\n\tfmt.Println(set)\n\n}\n\nfunc ExampleStringSet_ToSlice() {\n\ta := NewStringSet()\n\ta.Add(\"z\")\n\ta.Add(\"b\")\n\n\tfmt.Println(a.ToSlice())\n\n}\n\n\n\nfunc ExampleStringSet_Equals() {\n\ta := NewStringSet(\"a\", \"b\")\n\tb := NewStringSet(\"a\", \"b\", \"c\")\n\tfmt.Println(a.Equals(b))\n\n\ta.Add(\"c\")\n\tfmt.Println(a.Equals(b))\n\n}\n\nfunc ExampleStringSet_Contains() {\n\ta := NewStringSet(\"a\", \"b\")\n\tfmt.Println(a.Contains(\"z\"))\n\tfmt.Println(a.Contains(\"a\"))\n\n}\n\nfunc ExampleStringSet_Minus() {\n\ta := NewStringSet(\"a\", \"b\")\n\tb := NewStringSet(\"b\", \"c\")\n\tdelta := a.Minus(b)\n\n\tfmt.Println(delta)\n}\n\nfunc ExampleStringSet_IsEmpty() ", "output": "{\n\ta := NewStringSet()\n\n\tfmt.Println(a.IsEmpty())\n\ta.Add(\"a\")\n\tfmt.Println(a.IsEmpty())\n\n}"} {"input": "package gpio\n\n\ntype Mode byte\n\nconst (\n\tIn Mode = 0 \n\tOut Mode = out \n\tAlt Mode = alt \n\tAltIn Mode = altIn \n\tAna Mode = ana \n)\n\n\ntype Driver byte\n\nconst (\n\tPushPull Driver = 0\n\tOpenDrain Driver = openDrain\n)\n\n\n\n\n\ntype Speed int8\n\nconst (\n\tVeryLow Speed = veryLow \n\tLow Speed = low \n\tMedium Speed = 0 \n\tHigh Speed = high \n\tVeryHigh Speed = veryHigh \n)\n\n\ntype Pull byte\n\nconst (\n\tNoPull Pull = 0 \n\tPullUp Pull = pullUp \n\tPullDown Pull = pullDown \n)\n\n\ntype Config struct {\n\tMode Mode \n\tDriver Driver \n\tSpeed Speed \n\tPull Pull \n}\n\n\n\n\n\nfunc (p *Port) Setup(pins Pins, cfg *Config) {\n\tfor n := 0; n < 16; n++ {\n\t\tif pins&(1<\", since)\n\tout := make(LinkTweets, 0, 15)\n\tq.GetAll(c, &out)\n\treturn out\n}"} {"input": "package secure\n\nimport (\n\t\"github.com/go-kit/kit/metrics\"\n\tgokitprometheus \"github.com/go-kit/kit/metrics/prometheus\"\n\t\"github.com/xmidt-org/webpa-common/xmetrics\"\n)\n\n\nconst (\n\tJWTValidationReasonCounter = \"jwt_validation_reason\"\n\tNBFHistogram = \"jwt_from_nbf_seconds\"\n\tEXPHistogram = \"jwt_from_exp_seconds\"\n)\n\n\nfunc Metrics() []xmetrics.Metric {\n\treturn []xmetrics.Metric{\n\t\txmetrics.Metric{\n\t\t\tName: JWTValidationReasonCounter,\n\t\t\tType: xmetrics.CounterType,\n\t\t\tHelp: \"Counter for validation resolutions per reason\",\n\t\t\tLabelNames: []string{\"reason\"},\n\t\t},\n\t\txmetrics.Metric{\n\t\t\tName: NBFHistogram,\n\t\t\tType: xmetrics.HistogramType,\n\t\t\tHelp: \"Difference (in seconds) between time of JWT validation and nbf (including leeway)\",\n\t\t\tBuckets: []float64{-61, -11, -2, -1, 0, 9, 60}, \n\t\t},\n\t\txmetrics.Metric{\n\t\t\tName: EXPHistogram,\n\t\t\tType: xmetrics.HistogramType,\n\t\t\tHelp: \"Difference (in seconds) between time of JWT validation and exp (including leeway)\",\n\t\t\tBuckets: []float64{-61, -11, -2, -1, 0, 9, 60},\n\t\t},\n\t}\n}\n\n\ntype JWTValidationMeasures struct {\n\tNBFHistogram *gokitprometheus.Histogram\n\tExpHistogram *gokitprometheus.Histogram\n\tValidationReason metrics.Counter\n}\n\n\n\n\nfunc NewJWTValidationMeasures(r xmetrics.Registry) *JWTValidationMeasures ", "output": "{\n\treturn &JWTValidationMeasures{\n\t\tNBFHistogram: gokitprometheus.NewHistogram(r.NewHistogramVec(NBFHistogram)),\n\t\tExpHistogram: gokitprometheus.NewHistogram(r.NewHistogramVec(EXPHistogram)),\n\t\tValidationReason: r.NewCounter(JWTValidationReasonCounter),\n\t}\n}"} {"input": "package job\n\nimport (\n\tsj \"github.com/bitly/go-simplejson\"\n)\n\ntype Item struct {\n\tCategory string\n\tId string\n\tContent string\n\tRawMsg string\n}\n\ntype Processor interface {\n\tInit(ctx *sj.Json, id int, itemChans [](chan Item)) error\n\tProcess(msg string) error\n\tTick() error\n\tDestory() error\n}\n\ntype Collector interface {\n\tInit(ctx *sj.Json, id int) error\n\tCollect(item Item) error\n\tTick() error\n\tDestory() error\n}\n\n\n\nfunc NewCollector(name string) Collector {\n\tswitch name {\n\tcase \"LogtoHdfsCollector\":\n\t\treturn new(LogtoHdfsCollector)\n\tcase \"TestCollector\":\n\t\treturn new(TestCollector)\n\tdefault:\n\t\treturn nil\n\t}\n\treturn nil\n}\n\nfunc NewProcessor(name string) Processor ", "output": "{\n\tswitch name {\n\tcase \"LogtoHdfsProcessor\":\n\t\treturn new(LogtoHdfsProcessor)\n\tcase \"TestProcessor\":\n\t\treturn new(TestProcessor)\n\tdefault:\n\t\treturn nil\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/russmack/statemachiner\"\n)\n\n\nfunc main() {\n\ts := statemachiner.NewStateMachine()\n\ts.StartState = dispenseDogBiscuits\n\tc := NewHome()\n\ts.Start(c)\n}\n\n\ntype Home struct {\n\tDispenseDogBiscuits int `json:\"dispense_dog_biscuits\"`\n\tTotalDogBiscuits int `json:\"dog_biscuits\"`\n\tLights bool `json:\"lights\"`\n\tKettle bool `json:\"kettle\"`\n\tVacuumRoom string `json:\"vacuum_room\"`\n}\n\n\nfunc NewHome() *Home {\n\treturn &Home{}\n}\n\n\n\nfunc dispenseDogBiscuits(cargo interface{}) statemachiner.StateFn {\n\tcargo.(*Home).DispenseDogBiscuits = 10\n\tcargo.(*Home).TotalDogBiscuits += cargo.(*Home).DispenseDogBiscuits\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn lights\n}\n\n\n\n\n\nfunc kettle(cargo interface{}) statemachiner.StateFn {\n\tcargo.(*Home).Kettle = true\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn vacuumRoom\n}\n\n\nfunc vacuumRoom(cargo interface{}) statemachiner.StateFn {\n\tif cargo.(*Home).TotalDogBiscuits < 20 {\n\t\treturn dispenseDogBiscuits\n\t} else {\n\t\tcargo.(*Home).VacuumRoom = \"kitchen\"\n\t}\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn nil\n}\n\nfunc lights(cargo interface{}) statemachiner.StateFn ", "output": "{\n\tcargo.(*Home).Lights = true\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn kettle\n}"} {"input": "package leetcode\n\nconst MAX_INT32 = 1<<31 - 1\nconst MIN_INT32 = -1 << 31\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\n\n\nfunc minInt(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}\n\nfunc absInt(num int) int {\n\tif num > 0 {\n\t\treturn num\n\t} else {\n\t\treturn -num\n\t}\n}\n\nfunc qsortInt(nums []int) []int {\n\tif len(nums) <= 1 {\n\t\treturn nums\n\t}\n\n\thead, tail := 0, len(nums)-1\n\tidx, mid := 1, nums[0]\n\tfor head < tail {\n\t\tif nums[idx] > mid {\n\t\t\tnums[idx], nums[tail] = nums[tail], nums[idx]\n\t\t\ttail--\n\t\t} else {\n\t\t\tnums[idx], nums[head] = nums[head], nums[idx]\n\t\t\thead++\n\t\t\tidx++\n\t\t}\n\t}\n\tnums[head] = mid\n\tqsortInt(nums[:head])\n\tqsortInt(nums[head+1:])\n\treturn nums\n}\n\ntype Stack struct {\n\tdata []rune\n}\n\nfunc (s *Stack) push(data rune) {\n\ts.data = append(s.data, data)\n}\n\nfunc (s *Stack) pop() rune {\n\tif len(s.data) == 0 {\n\t\treturn 0\n\t}\n\tret := s.data[len(s.data)-1]\n\ts.data = s.data[:len(s.data)-1]\n\treturn ret\n}\n\nfunc (s Stack) empty() bool {\n\treturn len(s.data) == 0\n}\n\nfunc maxInt(a, b int) int ", "output": "{\n\tif a < b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}"} {"input": "package devicemapper\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n)\n\nfunc major(device uint64) uint64 {\n\treturn (device >> 8) & 0xfff\n}\n\n\n\n\nfunc GetDevicePrefix(root string) (string, error) {\n\tst, err := os.Stat(root)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Error looking up dir %s: %s\", root, err)\n\t}\n\tsysSt := st.Sys().(*syscall.Stat_t)\n\treturn fmt.Sprintf(\"docker-%d:%d-%d\", major(sysSt.Dev), minor(sysSt.Dev), sysSt.Ino), nil\n}\n\nfunc minor(device uint64) uint64 ", "output": "{\n\treturn (device & 0xff) | ((device >> 12) & 0xfff00)\n}"} {"input": "package msgraph\n\nimport \"context\"\n\n\ntype WorkbookFunctionsRriRequestBuilder struct{ BaseRequestBuilder }\n\n\nfunc (b *WorkbookFunctionsRequestBuilder) Rri(reqObj *WorkbookFunctionsRriRequestParameter) *WorkbookFunctionsRriRequestBuilder {\n\tbb := &WorkbookFunctionsRriRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.BaseRequestBuilder.baseURL += \"/rri\"\n\tbb.BaseRequestBuilder.requestObject = reqObj\n\treturn bb\n}\n\n\ntype WorkbookFunctionsRriRequest struct{ BaseRequest }\n\n\n\n\n\nfunc (r *WorkbookFunctionsRriRequest) Post(ctx context.Context) (resObj *WorkbookFunctionResult, err error) {\n\terr = r.JSONRequest(ctx, \"POST\", \"\", r.requestObject, &resObj)\n\treturn\n}\n\nfunc (b *WorkbookFunctionsRriRequestBuilder) Request() *WorkbookFunctionsRriRequest ", "output": "{\n\treturn &WorkbookFunctionsRriRequest{\n\t\tBaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},\n\t}\n}"} {"input": "package status\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/cozy/cozy-stack/pkg/config\"\n\t\"github.com/cozy/cozy-stack/web/errors\"\n\t\"github.com/labstack/echo\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc testRequest(t *testing.T, url string) {\n\tres, err := http.Get(url)\n\tassert.NoError(t, err)\n\tdefer res.Body.Close()\n\n\tbody, ioerr := ioutil.ReadAll(res.Body)\n\tassert.NoError(t, ioerr)\n\tassert.Equal(t, \"200 OK\", res.Status, \"should get a 200\")\n\tassert.Equal(t, \"{\\\"couchdb\\\":\\\"healthy\\\",\\\"message\\\":\\\"OK\\\"}\", string(body), \"res body should match\")\n}\n\nfunc TestRoutes(t *testing.T) {\n\thandler := echo.New()\n\thandler.HTTPErrorHandler = errors.ErrorHandler\n\tRoutes(handler.Group(\"/status\"))\n\n\tts := httptest.NewServer(handler)\n\tdefer ts.Close()\n\n\ttestRequest(t, ts.URL+\"/status\")\n}\n\n\n\nfunc TestMain(m *testing.M) ", "output": "{\n\tconfig.UseTestFile()\n\tos.Exit(m.Run())\n}"} {"input": "package path\n\nimport (\n\t\"reflect\"\n)\n\n\n\n\n\n\n\n\n\nfunc (path P) ReadAll(obj, dest interface{}) (interface{}, error) {\n\tvalue := reflect.ValueOf(dest)\n\n\tif value.Kind() != reflect.Slice {\n\t\tpanic(\"can only read slice values\")\n\t}\n\n\telem := value.Type().Elem()\n\n\tfn := func(_ P, ctx *Context) (bool, error) {\n\n\t\tfor result := ctx.Value(); ; result = result.Elem() {\n\n\t\t\tif result.Type().ConvertibleTo(elem) {\n\t\t\t\tresult = result.Convert(elem)\n\t\t\t}\n\n\t\t\tif result.Type().AssignableTo(elem) {\n\t\t\t\tvalue = reflect.Append(value, result)\n\t\t\t\treturn true, nil\n\t\t\t}\n\n\t\t\tif result.Kind() != reflect.Interface && result.Kind() != reflect.Ptr {\n\t\t\t\treturn false, ErrInvalidType\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn value, path.Apply(obj, &Context{Fn: fn})\n}\n\nfunc (path P) Read(obj, dest interface{}) (err error) ", "output": "{\n\tvalue := reflect.ValueOf(dest)\n\n\tif value.Kind() == reflect.Ptr {\n\t\tvalue = value.Elem()\n\t}\n\n\tif !value.CanSet() {\n\t\tpanic(\"dest must be setable\")\n\t}\n\n\tfn := func(_ P, ctx *Context) (bool, error) {\n\n\t\tfor result := ctx.Value(); ; result = result.Elem() {\n\n\t\t\tif result.Type().ConvertibleTo(value.Type()) {\n\t\t\t\tresult = result.Convert(value.Type())\n\t\t\t}\n\n\t\t\tif result.Type().AssignableTo(value.Type()) {\n\t\t\t\tvalue.Set(result)\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tif result.Kind() != reflect.Interface && result.Kind() != reflect.Ptr {\n\t\t\t\treturn false, ErrInvalidType\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn path.Apply(obj, &Context{Fn: fn})\n}"} {"input": "package iso20022\n\n\ntype CorporateActionRate21 struct {\n\n\tAdditionalQuantityForSubscribedResultantSecurities *RatioFormat3Choice `xml:\"AddtlQtyForSbcbdRsltntScties,omitempty\"`\n\n\tAdditionalQuantityForExistingSecurities *RatioFormat3Choice `xml:\"AddtlQtyForExstgScties,omitempty\"`\n\n\tNewToOld *RatioFormat4Choice `xml:\"NewToOd,omitempty\"`\n}\n\n\n\nfunc (c *CorporateActionRate21) AddAdditionalQuantityForExistingSecurities() *RatioFormat3Choice {\n\tc.AdditionalQuantityForExistingSecurities = new(RatioFormat3Choice)\n\treturn c.AdditionalQuantityForExistingSecurities\n}\n\nfunc (c *CorporateActionRate21) AddNewToOld() *RatioFormat4Choice {\n\tc.NewToOld = new(RatioFormat4Choice)\n\treturn c.NewToOld\n}\n\nfunc (c *CorporateActionRate21) AddAdditionalQuantityForSubscribedResultantSecurities() *RatioFormat3Choice ", "output": "{\n\tc.AdditionalQuantityForSubscribedResultantSecurities = new(RatioFormat3Choice)\n\treturn c.AdditionalQuantityForSubscribedResultantSecurities\n}"} {"input": "package hash2\n\nconst (\n\tmaxNumShards = 1<<16 - 1\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ConsistentHash(key uint64, numShards uint16) uint16 {\n\tif numShards < 2 {\n\t\treturn 0\n\t}\n\n\thash := uint32(key) ^ uint32(key>>32)\n\n\tvar lowestPositionShard uint16 = 0\n\tvar minPosition uint16 = maxNumShards\n\n\tselectLowestPositionShard := func(shard, pos uint16) {\n\t\tpos %= (maxNumShards - shard)\n\t\tif pos < minPosition {\n\t\t\tlowestPositionShard = shard\n\t\t\tminPosition = pos\n\t\t}\n\t}\n\n\tnumBlocks := numShards >> 1\n\tfor i := uint16(0); i < numBlocks; i++ {\n\t\thash = simpleMurmur32(hash)\n\n\t\tshard := i << 1\n\n\t\tselectLowestPositionShard(shard, uint16(hash))\n\t\tif minPosition == 0 {\n\t\t\treturn lowestPositionShard\n\t\t}\n\n\t\tselectLowestPositionShard(shard+1, uint16(hash>>16))\n\t\tif minPosition == 0 {\n\t\t\treturn lowestPositionShard\n\t\t}\n\t}\n\n\tif (numShards & 0x1) == 1 {\n\t\thash = simpleMurmur32(hash)\n\t\tselectLowestPositionShard(numShards-1, uint16(hash))\n\t}\n\n\treturn lowestPositionShard\n}\n\nfunc simpleMurmur32(val uint32) uint32 ", "output": "{\n\tk := val * 0xcc9e2d51 \n\tk = (k << 15) | (k >> 17) \n\tk *= 0x1b873593 \n\n\th := 12345 ^ k \n\th = (h << 13) | (h >> 19) \n\th = h*5 + 0xe6546b64\n\n\th = h ^ 4\n\n\th ^= h >> 16\n\th *= 0x85ebca6b\n\th ^= h >> 13\n\th *= 0xc2b2ae35\n\th ^= h >> 16\n\n\treturn h\n}"} {"input": "package tchannelthrift\n\nimport (\n\tstdctx \"context\"\n\t\"time\"\n\n\t\"github.com/m3db/m3/src/x/context\"\n\n\tapachethrift \"github.com/apache/thrift/lib/go/thrift\"\n\t\"github.com/uber/tchannel-go\"\n\t\"github.com/uber/tchannel-go/thrift\"\n)\n\nconst (\n\tcontextKey = \"m3dbcontext\"\n)\n\n\nfunc RegisterServer(channel *tchannel.Channel, service thrift.TChanServer, contextPool context.Pool) {\n\tserver := thrift.NewServer(channel)\n\tserver.Register(service, thrift.OptPostResponse(postResponseFn))\n\tserver.SetContextFn(func(ctx stdctx.Context, method string, headers map[string]string) thrift.Context {\n\t\txCtx := contextPool.Get()\n\t\txCtx.SetGoContext(ctx)\n\t\tctxWithValue := stdctx.WithValue(ctx, contextKey, xCtx) \n\t\treturn thrift.WithHeaders(ctxWithValue, headers)\n\t})\n}\n\n\n\n\n\nfunc Context(ctx thrift.Context) context.Context {\n\treturn ctx.Value(contextKey).(context.Context)\n}\n\nfunc postResponseFn(ctx stdctx.Context, method string, response apachethrift.TStruct) {\n\tvalue := ctx.Value(contextKey)\n\tinner := value.(context.Context)\n\tinner.Close()\n}\n\nfunc NewContext(timeout time.Duration) (thrift.Context, stdctx.CancelFunc) ", "output": "{\n\ttctx, cancel := thrift.NewContext(timeout)\n\txCtx := context.NewWithGoContext(tctx)\n\tctxWithValue := stdctx.WithValue(tctx, contextKey, xCtx) \n\treturn thrift.WithHeaders(ctxWithValue, nil), cancel\n}"} {"input": "package fst\n\nimport (\n\t\"github.com/balzaczyy/golucene/core/util\"\n)\n\n\n\n\n\n\nfunc ToIntsRef(input []byte, scratch *util.IntsRefBuilder) *util.IntsRef ", "output": "{\n\tscratch.Clear()\n\tfor _, v := range input {\n\t\tscratch.Append(int(v))\n\t}\n\treturn scratch.Get()\n}"} {"input": "package iso20022\n\n\ntype AccountManagementConfirmation2 struct {\n\n\tConfirmationType *AccountManagementType2Code `xml:\"ConfTp\"`\n\n\tAccountApplicationIdentification *Max35Text `xml:\"AcctApplId,omitempty\"`\n\n\tClientReference *Max35Text `xml:\"ClntRef,omitempty\"`\n\n\tCounterpartyReference *AdditionalReference2 `xml:\"CtrPtyRef,omitempty\"`\n}\n\nfunc (a *AccountManagementConfirmation2) SetConfirmationType(value string) {\n\ta.ConfirmationType = (*AccountManagementType2Code)(&value)\n}\n\nfunc (a *AccountManagementConfirmation2) SetAccountApplicationIdentification(value string) {\n\ta.AccountApplicationIdentification = (*Max35Text)(&value)\n}\n\nfunc (a *AccountManagementConfirmation2) SetClientReference(value string) {\n\ta.ClientReference = (*Max35Text)(&value)\n}\n\n\n\nfunc (a *AccountManagementConfirmation2) AddCounterpartyReference() *AdditionalReference2 ", "output": "{\n\ta.CounterpartyReference = new(AdditionalReference2)\n\treturn a.CounterpartyReference\n}"} {"input": "package main\n\nimport (\n\t\t\"fmt\";\n)\n\n\n\nfunc main() {\n\tans := fib(40)\n\tfmt.Printf(\"%i\\n\", ans)\n}\n\nfunc fib(n int) int ", "output": "{\n\tif n < 2 {\n\t\treturn n\n\t}\n\tr1 := fib(n - 1)\n\tr2 := fib(n - 2)\n\treturn r1 + r2\n}"} {"input": "package clock\n\nimport (\n\t\"time\"\n)\n\n\n\n\n\ntype Clock interface {\n\tNow() time.Time\n}\n\ntype clock struct{}\n\nfunc (c *clock) Now() time.Time {\n\treturn time.Now()\n}\n\n\ntype Mock struct {\n\tcurrentTime time.Time\n}\n\n\n\n\n\nfunc (c *Mock) Now() time.Time {\n\treturn c.currentTime\n}\n\n\nfunc New() Clock {\n\treturn &clock{}\n}\n\n\nfunc NewMock() *Mock {\n\treturn &Mock{\n\t\tcurrentTime: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),\n\t}\n}\n\nfunc (c *Mock) SetNow(t time.Time) ", "output": "{\n\tc.currentTime = t\n}"} {"input": "package projecteuler\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nvar isPrimeTests = []struct {\n\tinput int\n\texpected bool\n}{\n\t{2, true},\n\t{4, false},\n\t{9, false},\n\t{13, true},\n}\n\nfunc TestIsPrime(t *testing.T) {\n\tfor _, td := range isPrimeTests {\n\t\tactual := IsPrime(td.input)\n\t\tif actual != td.expected {\n\t\t\tt.Errorf(\"IsPrime(%d): exptected %t, actual %t\", td.input, td.expected, actual)\n\t\t}\n\t}\n}\n\nvar findLargestPrimeTests = []struct {\n\tinput int\n\texpected int\n}{\n\t{13195, 29},\n}\n\n\n\nfunc TestFindLargestPrime(t *testing.T) ", "output": "{\n\tfor _, td := range findLargestPrimeTests {\n\t\tactual := FindLargestPrime(td.input)\n\t\tif actual != td.expected {\n\t\t\tt.Errorf(\"FindLargestPrime(%d): expected %d, actual %d\", td.input, td.expected, actual)\n\t\t}\n\t}\n\tfmt.Printf(\"3: FindLargestPrime(600851475143) = %d\\n\", FindLargestPrime(600851475143))\n}"} {"input": "package bender\n\nimport (\n\t\"log\"\n\n\t\"github.com/pinterest/bender/hist\"\n)\n\n\ntype Recorder func(interface{})\n\n\nfunc Record(c chan interface{}, recorders ...Recorder) {\n\tfor msg := range c {\n\t\tfor _, recorder := range recorders {\n\t\t\trecorder(msg)\n\t\t}\n\t}\n}\n\n\n\n\nfunc NewLoggingRecorder(l *log.Logger) Recorder {\n\treturn func(msg interface{}) {\n\t\tlogMessage(l, msg)\n\t}\n}\n\n\nfunc NewHistogramRecorder(h *hist.Histogram) Recorder {\n\treturn func(msg interface{}) {\n\t\tswitch msg := msg.(type) {\n\t\tcase *StartEvent:\n\t\t\th.Start(int(msg.Start))\n\t\tcase *EndEvent:\n\t\t\th.End(int(msg.End))\n\t\tcase *EndRequestEvent:\n\t\t\telapsed := int(msg.End - msg.Start)\n\t\t\tif msg.Err == nil {\n\t\t\t\th.Add(elapsed)\n\t\t\t} else {\n\t\t\t\th.AddError(elapsed)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc logMessage(l *log.Logger, msg interface{}) ", "output": "{\n\tl.Printf(\"%+v\", msg)\n}"} {"input": "package lib\n\nimport \"testing\"\n\n\n\n\nfunc mainStart(tests []testing.InternalTest) *testing.M ", "output": "{\n\treturn testing.MainStart(testDeps{}, tests, nil, nil)\n}"} {"input": "package sign\n\nimport (\n\t\"dfss\"\n\tcAPI \"dfss/dfssc/api\"\n\tpAPI \"dfss/dfssp/api\"\n\t\"dfss/dfsst/entities\"\n\t\"dfss/net\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\ntype clientServer struct {\n\tincomingPromises chan interface{}\n\tincomingSignatures chan interface{}\n}\n\nfunc getServerErrorCode(c chan interface{}, in interface{}) *pAPI.ErrorCode {\n\tif c != nil {\n\t\tc <- in\n\t\treturn &pAPI.ErrorCode{Code: pAPI.ErrorCode_SUCCESS}\n\t}\n\treturn &pAPI.ErrorCode{Code: pAPI.ErrorCode_INTERR} \n}\n\n\n\n\nfunc (s *clientServer) TreatPromise(ctx context.Context, in *cAPI.Promise) (*pAPI.ErrorCode, error) {\n\tvalid, _, _, _ := entities.IsRequestValid(ctx, []*cAPI.Promise{in})\n\tif !valid {\n\t\treturn &pAPI.ErrorCode{Code: pAPI.ErrorCode_SUCCESS}, nil\n\t}\n\treturn getServerErrorCode(s.incomingPromises, in), nil\n}\n\n\n\n\n\n\n\n\n\nfunc (s *clientServer) Discover(ctx context.Context, in *cAPI.Hello) (*cAPI.Hello, error) {\n\treturn &cAPI.Hello{Version: dfss.Version}, nil\n}\n\n\nfunc (m *SignatureManager) GetServer() *grpc.Server {\n\tserver := net.NewServer(m.auth.Cert, m.auth.Key, m.auth.CA)\n\tm.cServerIface = clientServer{}\n\tcAPI.RegisterClientServer(server, &m.cServerIface)\n\treturn server\n}\n\nfunc (s *clientServer) TreatSignature(ctx context.Context, in *cAPI.Signature) (*pAPI.ErrorCode, error) ", "output": "{\n\treturn getServerErrorCode(s.incomingSignatures, in), nil\n}"} {"input": "package buildings\n\ntype store struct {\n\tbasicBuilding\n\timprovementLvl int8\n\tsales int\n\tprice int\n}\n\nfunc (*store) GetType() string { return \"store\" }\nfunc (b *store) GetRevenue() int { return b.sales * b.price }\nfunc (b *store) GetRent() int { return [4]int{1, 2, 3, 5}[b.improvementLvl] }\n\nfunc (b *store) SetInternalInt(name string, val int) {\n\tswitch name {\n\tcase \"improvementLvl\":\n\t\tb.improvementLvl = int8(val)\n\tcase \"sales\":\n\t\tb.sales = val\n\tcase \"price\":\n\t\tb.price = val\n\t}\n}\nfunc (b *store) ToString(x, y int) string {\n\treturn \"store,\" + string(b.improvementLvl) + \",\" + string(b.sales) + \",\" + string(b.price) + \",\" + b.basicBuilding.ToString(x, y)\n}\n\nfunc (b *store) GetInternalInt(name string) int ", "output": "{\n\tswitch name {\n\tcase \"improvementLvl\":\n\t\treturn int(b.improvementLvl)\n\tcase \"sales\":\n\t\treturn b.sales\n\tcase \"price\":\n\t\treturn b.price\n\tdefault:\n\t\treturn 0\n\t}\n}"} {"input": "package vox\n\ntype Block uint8\n\nconst (\n\tBlockNil = 0x00\n\tblockActiveMask = 0x80 \n\tblockTypeMask = 0x7F \n)\n\nfunc (b Block) Active() bool {\n\treturn (blockActiveMask & b) == blockActiveMask\n}\n\nfunc (b Block) Activate(active bool) Block {\n\tif active {\n\t\treturn b | blockActiveMask\n\t}\n\treturn b & blockTypeMask\n}\n\n\n\nfunc (b Block) ChangeType(t *BlockType) Block {\n\treturn Block((uint8(b) & blockActiveMask) | t.ID)\n}\n\ntype BlockType struct {\n\tID uint8\n\tTop *TextureRegion\n\tBottom *TextureRegion\n\tSide *TextureRegion\n}\n\ntype BlockBank struct {\n\tTypes []*BlockType\n\ttypeMap map[uint8]*BlockType\n}\n\nfunc NewBlockBank() *BlockBank {\n\treturn &BlockBank{\n\t\ttypeMap: make(map[uint8]*BlockType),\n\t}\n}\n\nfunc (b *BlockBank) AddType(blockType *BlockType) {\n\tb.typeMap[blockType.ID] = blockType\n\tb.Types = append(b.Types, blockType)\n}\n\nfunc (b *BlockBank) TypeOf(block Block) *BlockType {\n\treturn b.typeMap[block.TypeID()]\n}\n\nfunc (b Block) TypeID() uint8 ", "output": "{\n\treturn uint8(b & blockTypeMask)\n}"} {"input": "package linux\n\nimport (\n\t\"testing\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestGetAdapters(t *testing.T) {\n\n\tlog.SetLevel(log.DebugLevel)\n\n\tlist, err := GetAdapters()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassert.NotEmpty(t, list)\n}\n\nfunc TestGetAdapter(t *testing.T) {\n\tlog.SetLevel(log.DebugLevel)\n\t_, err := GetAdapter(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\n\nfunc TestUp(t *testing.T) {\n\terr := Up(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDown(t *testing.T) {\n\terr := Down(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestReset(t *testing.T) {\n\terr := Reset(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestGetAdapterNotFound(t *testing.T) ", "output": "{\n\t_, err := GetAdapter(\"hci999\")\n\tif err == nil {\n\t\tt.Fatal(\"adapter should not exists\")\n\t}\n}"} {"input": "package supervisor\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc create() *Supervisor {\n\tnow := time.Now()\n\tend := now.Add(time.Hour * 1)\n\tconf := &Config{\n\t\tOn: true,\n\t\tBegin: now,\n\t\tEnd: end,\n\t}\n\treturn New(conf)\n}\n\n\n\nfunc TestReload(t *testing.T) {\n\tzero := time.Unix(0, 0)\n\tconf := &Config{\n\t\tOn: false,\n\t\tBegin: zero,\n\t\tEnd: zero,\n\t}\n\tsv := create()\n\n\tsv.Reload(nil)\n\n\tsv.Reload(conf)\n\n\tif sv.conf != conf && sv.on == false {\n\t\tt.Errorf(\"Failed to reload config %+v, current config is %+v\", conf, sv.conf)\n\t}\n}\n\nfunc TestSupervisor(t *testing.T) ", "output": "{\n\tsv := create()\n\tin := sv.conf.Begin.Add(time.Second * 10)\n\tout := sv.conf.End.Add(time.Second * 10)\n\n\tif sv.forbid(\"GET\", in) {\n\t\tt.Error(\"Request should never be blocked on GET method\")\n\t}\n\n\tif !sv.forbid(\"POST\", in) {\n\t\tt.Errorf(\"Request should be blocked on POST method at %+v\", in)\n\t}\n\n\tif sv.forbid(\"POST\", out) {\n\t\tt.Errorf(\"Request should not be blocked at %+v\", out)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc mapper(f func(interface{}) interface{}, vals []interface{}) []interface{} {\n\tout := make([]interface{}, len(vals))\n\tfor i, val := range vals {\n\t\tout[i] = f(val)\n\t}\n\treturn out\n}\n\n\n\nfunc main() {\n\tarr := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n\tfmt.Println(mapper(square, arr))\n}\n\nfunc square(i interface{}) interface{} ", "output": "{\n\tval, ok := i.(int)\n\tif ok {\n\t\treturn val * val\n\t}\n\tpanic(\"Not a number\")\n}"} {"input": "package plist\n\n\nimport \"C\"\nimport \"reflect\"\nimport \"strconv\"\n\n\n\ntype UnsupportedTypeError struct {\n\tType reflect.Type\n}\n\nfunc (e *UnsupportedTypeError) Error() string {\n\treturn \"plist: unsupported type: \" + e.Type.String()\n}\n\ntype UnsupportedValueError struct {\n\tValue reflect.Value\n\tStr string\n}\n\n\n\ntype UnknownCFTypeError struct {\n\tCFTypeID C.CFTypeID\n}\n\nfunc (e *UnknownCFTypeError) Error() string {\n\tcfStr := C.CFCopyTypeIDDescription(e.CFTypeID)\n\tstr := convertCFStringToString(cfStr)\n\tcfRelease(cfTypeRef(cfStr))\n\treturn \"plist: unknown CFTypeID \" + strconv.Itoa(int(e.CFTypeID)) + \" (\" + str + \")\"\n}\n\n\n\n\n\n\n\ntype UnsupportedKeyTypeError struct {\n\tCFTypeID int\n}\n\nfunc (e *UnsupportedKeyTypeError) Error() string {\n\treturn \"plist: unexpected dictionary key CFTypeID \" + strconv.Itoa(e.CFTypeID)\n}\n\nfunc (e *UnsupportedValueError) Error() string ", "output": "{\n\treturn \"json: unsupported value: \" + e.Str\n}"} {"input": "package mysql\n\nimport (\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"github.com/jmoiron/sqlx\"\n\t\"github.com/stellar/federation/db\"\n)\n\ntype MysqlDriver struct {\n\tdatabase *sqlx.DB\n}\n\nfunc (d *MysqlDriver) Init(url string) (err error) {\n\td.database, err = sqlx.Connect(\"mysql\", url)\n\treturn\n}\n\nfunc (d *MysqlDriver) GetByStellarAddress(name, query string) (*db.FederationRecord, error) {\n\tvar record db.FederationRecord\n\terr := d.database.Get(&record, query, name)\n\tif err != nil {\n\t\tif err.Error() == \"sql: no rows in result set\" {\n\t\t\treturn nil, nil\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &record, nil\n}\n\n\n\nfunc (d *MysqlDriver) GetByAccountId(accountId, query string) (*db.ReverseFederationRecord, error) ", "output": "{\n\tvar record db.ReverseFederationRecord\n\terr := d.database.Get(&record, query, accountId)\n\tif err != nil {\n\t\tif err.Error() == \"sql: no rows in result set\" {\n\t\t\treturn nil, nil\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &record, nil\n}"} {"input": "package sol\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aodin/sol/dialect\"\n)\n\n\ntype DropStmt struct {\n\ttable *TableElem\n\tifExists bool\n}\n\n\nfunc (stmt DropStmt) IfExists() DropStmt {\n\tstmt.ifExists = true\n\treturn stmt\n}\n\n\n\nfunc (stmt DropStmt) String() string {\n\tc, _ := stmt.Compile(&defaultDialect{}, Params())\n\treturn c\n}\n\n\n\n\n\nfunc (stmt DropStmt) Compile(d dialect.Dialect, p *Parameters) (string, error) ", "output": "{\n\tif stmt.ifExists {\n\t\treturn fmt.Sprintf(`DROP TABLE IF EXISTS %s`, stmt.table.Name()), nil\n\t}\n\treturn fmt.Sprintf(`DROP TABLE %s`, stmt.table.Name()), nil\n}"} {"input": "package span\n\nimport (\n\t\"go/token\"\n)\n\n\n\n\n\n\nfunc lineStart(f *token.File, line int) token.Pos ", "output": "{\n\n\tmin := 0 \n\tmax := f.Size() \n\tfor {\n\t\toffset := (min + max) / 2\n\t\tpos := f.Pos(offset)\n\t\tposn := f.Position(pos)\n\t\tif posn.Line == line {\n\t\t\treturn pos - (token.Pos(posn.Column) - 1)\n\t\t}\n\n\t\tif min+1 >= max {\n\t\t\treturn token.NoPos\n\t\t}\n\n\t\tif posn.Line < line {\n\t\t\tmin = offset\n\t\t} else {\n\t\t\tmax = offset\n\t\t}\n\t}\n}"} {"input": "package tworandomchoices\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/yarpc/yarpcconfig\"\n\t\"go.uber.org/yarpc/yarpctest\"\n)\n\ntype attrs map[string]interface{}\n\n\n\nfunc TestConfig(t *testing.T) ", "output": "{\n\tcfg := yarpcconfig.New()\n\tcfg.RegisterPeerList(Spec())\n\tcfg.RegisterTransport(yarpctest.FakeTransportSpec())\n\tconfig, err := cfg.LoadConfig(\"our-service\", attrs{\n\t\t\"outbounds\": attrs{\n\t\t\t\"their-service\": attrs{\n\t\t\t\t\"fake-transport\": attrs{\n\t\t\t\t\t\"two-random-choices\": attrs{\n\t\t\t\t\t\t\"peers\": []string{\n\t\t\t\t\t\t\t\"1.1.1.1:1111\",\n\t\t\t\t\t\t\t\"2.2.2.2:2222\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\trequire.NoError(t, err)\n\trequire.NotNil(t, config.Outbounds)\n\trequire.NotNil(t, config.Outbounds[\"their-service\"])\n\trequire.NotNil(t, config.Outbounds[\"their-service\"].Unary)\n}"} {"input": "package svc\n\nimport (\n\t\"golang.org/x/sys/windows\"\n)\n\n\n\n\n\n\nfunc IsAnInteractiveSession() (bool, error) {\n\tinterSid, err := allocSid(windows.SECURITY_INTERACTIVE_RID)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer windows.FreeSid(interSid)\n\n\tserviceSid, err := allocSid(windows.SECURITY_SERVICE_RID)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer windows.FreeSid(serviceSid)\n\n\tt, err := windows.OpenCurrentProcessToken()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer t.Close()\n\n\tgs, err := t.GetTokenGroups()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, g := range gs.AllGroups() {\n\t\tif windows.EqualSid(g.Sid, interSid) {\n\t\t\treturn true, nil\n\t\t}\n\t\tif windows.EqualSid(g.Sid, serviceSid) {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn false, nil\n}\n\nfunc allocSid(subAuth0 uint32) (*windows.SID, error) ", "output": "{\n\tvar sid *windows.SID\n\terr := windows.AllocateAndInitializeSid(&windows.SECURITY_NT_AUTHORITY,\n\t\t1, subAuth0, 0, 0, 0, 0, 0, 0, 0, &sid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sid, nil\n}"} {"input": "package gohtml\n\nimport \"testing\"\n\nconst (\n\tunformattedHTML = `This is a title.

Line1
Line2


`\n\tformattedHTML = `\n\n \n \n This is a title.\n \n \n \n

\n Line1\n
\n Line2\n

\n
\n \n\n`\n)\n\nfunc TestFormat(t *testing.T) {\n\tactual := Format(unformattedHTML)\n\tif actual != formattedHTML {\n\t\tt.Errorf(\"Invalid result. [expected: %s][actual: %s]\", formattedHTML, actual)\n\t}\n}\n\nfunc TestFormatBytes(t *testing.T) {\n\tactual := string(FormatBytes([]byte(unformattedHTML)))\n\tif actual != formattedHTML {\n\t\tt.Errorf(\"Invalid result. [expected: %s][actual: %s]\", formattedHTML, actual)\n\t}\n}\n\n\n\nfunc TestFormatWithLineNo(t *testing.T) ", "output": "{\n\tactual := FormatWithLineNo(unformattedHTML)\n\texpected := ` 1 \n 2 \n 3 \n 4 \n 5 This is a title.\n 6 \n 7 \n 8 \n 9

\n10 Line1\n11
\n12 Line2\n13

\n14
\n15 \n16 \n17 `\n\tif actual != expected {\n\t\tt.Errorf(\"Invalid result. [expected: %s][actual: %s]\", expected, actual)\n\t}\n}"} {"input": "package cobra\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\nfunc TestCompleteNoDesCmdInFishScript(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse: \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun: emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, false))\n\toutput := buf.String()\n\n\tcheck(t, output, ShellCompNoDescRequestCmd)\n}\n\n\n\nfunc TestProgWithDash(t *testing.T) {\n\trootCmd := &Command{Use: \"root-dash\", Args: NoArgs, Run: emptyRun}\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, false))\n\toutput := buf.String()\n\n\tcheck(t, output, \"__root_dash_perform_completion\")\n\tcheckOmit(t, output, \"__root-dash_perform_completion\")\n\n\tcheck(t, output, \"-c root-dash\")\n\tcheckOmit(t, output, \"-c root_dash\")\n}\n\nfunc TestProgWithColon(t *testing.T) {\n\trootCmd := &Command{Use: \"root:colon\", Args: NoArgs, Run: emptyRun}\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, false))\n\toutput := buf.String()\n\n\tcheck(t, output, \"__root_colon_perform_completion\")\n\tcheckOmit(t, output, \"__root:colon_perform_completion\")\n\n\tcheck(t, output, \"-c root:colon\")\n\tcheckOmit(t, output, \"-c root_colon\")\n}\n\nfunc TestCompleteCmdInFishScript(t *testing.T) ", "output": "{\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse: \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun: emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, true))\n\toutput := buf.String()\n\n\tcheck(t, output, ShellCompRequestCmd)\n\tcheckOmit(t, output, ShellCompNoDescRequestCmd)\n}"} {"input": "package goxpath\n\nimport (\n\txml \"encoding/xml\"\n)\n\ntype FuncOpts func(*Opts)\n\nfunc MustParse(_ string) XPathExec {\n\treturn XPathExec{}\n}\n\ntype Opts struct {\n\tNS map[string]string\n\tFuncs map[xml.Name]interface{}\n\tVars map[string]interface{}\n}\n\nfunc Parse(_ string) (XPathExec, error) {\n\treturn XPathExec{}, nil\n}\n\nfunc ParseExec(_ string, _ interface{}, _ ...FuncOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\ntype XPathExec struct{}\n\n\n\nfunc (_ XPathExec) ExecBool(_ interface{}, _ ...FuncOpts) (bool, error) {\n\treturn false, nil\n}\n\nfunc (_ XPathExec) ExecNode(_ interface{}, _ ...FuncOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\nfunc (_ XPathExec) ExecNum(_ interface{}, _ ...FuncOpts) (float64, error) {\n\treturn 0, nil\n}\n\nfunc (_ XPathExec) MustExec(_ interface{}, _ ...FuncOpts) interface{} {\n\treturn nil\n}\n\nfunc (_ XPathExec) Exec(_ interface{}, _ ...FuncOpts) (interface{}, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package filestore\n\nimport (\n\t\"os\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestUpload(t *testing.T) {\n\tfs := NewFileStore(\"./\")\n\tid := \"yyy\"\n\n\tinfo := &FileInfo{}\n\tinfo.ID = id\n\tinfo.Offset = 0\n\tinfo.Size = 10\n\tinfo.Type = \".jpg\"\n\n\tif offset, isCompleted, _ := fs.NewUpload(info); offset != 0 || isCompleted {\n\t\tt.Fatal()\n\t}\n\n\tif n, isCompleted, _ := fs.WriteChunk(id, 0, strings.NewReader(\"hello\")); n != 5 || isCompleted {\n\t\tt.Fatal()\n\t}\n\n\tif offset, isCompleted, _ := fs.NewUpload(info); offset != 5 || isCompleted {\n\t\tt.Fatal()\n\t}\n\n\tif n, isCompleted, _ := fs.WriteChunk(id, 5, strings.NewReader(\"world\")); n != 5 || !isCompleted {\n\t\tt.Fatal()\n\t}\n\n\tif n, isCompleted, _ := fs.WriteChunk(id, 5, strings.NewReader(\"abc\")); n != 0 || !isCompleted {\n\t\tt.Fatal()\n\t}\n\n\tos.Remove(id + \".bin\")\n\tos.Remove(id + \".info\")\n}\n\nfunc TestInfo(t *testing.T) ", "output": "{\n\tfs := NewFileStore(\"./\")\n\tid := \"xxx\"\n\n\tinfo := &FileInfo{}\n\tinfo.ID = id\n\tinfo.Offset = 0\n\tinfo.Size = 100\n\tinfo.Type = \".txt\"\n\n\tif fs.WriteInfo(id, info) != nil {\n\t\tt.Fatal()\n\t}\n\n\trinfo, err := fs.GetInfo(id)\n\tif err != nil {\n\t\tt.Fatal()\n\t}\n\tif !reflect.DeepEqual(rinfo, info) {\n\t\tt.Fatal()\n\t}\n\n\tos.Remove(id + \".info\")\n}"} {"input": "package service\n\nimport (\n\tgofig \"github.com/akutz/gofig/types\"\n\n\t\"github.com/thecodeteam/rexray/libstorage/api/registry\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/server/handlers\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/server/httputils\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/types\"\n\t\"github.com/thecodeteam/rexray/libstorage/api/utils/schema\"\n)\n\nfunc init() {\n\tregistry.RegisterRouter(&router{})\n}\n\ntype router struct {\n\troutes []types.Route\n}\n\nfunc (r *router) Name() string {\n\treturn \"service-router\"\n}\n\n\n\n\nfunc (r *router) Routes() []types.Route {\n\treturn r.routes\n}\n\nfunc (r *router) initRoutes() {\n\n\tr.routes = []types.Route{\n\n\t\thttputils.NewGetRoute(\n\t\t\t\"services\",\n\t\t\t\"/services\",\n\t\t\tr.servicesList,\n\t\t\thandlers.NewAuthAllSvcsHandler(),\n\t\t\thandlers.NewSchemaValidator(nil, schema.ServiceInfoMapSchema, nil)),\n\n\t\thttputils.NewGetRoute(\n\t\t\t\"serviceInspect\",\n\t\t\t\"/services/{service}\",\n\t\t\tr.serviceInspect,\n\t\t\thandlers.NewServiceValidator(),\n\t\t\thandlers.NewAuthSvcHandler(),\n\t\t\thandlers.NewSchemaValidator(nil, schema.ServiceInfoSchema, nil)),\n\t}\n}\n\nfunc (r *router) Init(config gofig.Config) ", "output": "{\n\tr.initRoutes()\n}"} {"input": "package upgrades\n\nimport (\n\t\"github.com/juju/juju/environs\"\n\t\"github.com/juju/juju/state\"\n)\n\n\nfunc stepsFor126() []Step {\n\treturn []Step{}\n}\n\n\n\n\nfunc stateStepsFor126() []Step ", "output": "{\n\treturn []Step{\n\t\t&upgradeStep{\n\t\t\tdescription: \"add the version field to all settings docs\",\n\t\t\ttargets: []Target{DatabaseMaster},\n\t\t\trun: func(context Context) error {\n\t\t\t\treturn state.MigrateSettingsSchema(context.State())\n\t\t\t},\n\t\t},\n\t\t&upgradeStep{\n\t\t\tdescription: \"add status to filesystem\",\n\t\t\ttargets: []Target{DatabaseMaster},\n\t\t\trun: func(context Context) error {\n\t\t\t\treturn state.AddFilesystemStatus(context.State())\n\t\t\t},\n\t\t},\n\t\t&upgradeStep{\n\t\t\tdescription: \"upgrade environment config\",\n\t\t\ttargets: []Target{DatabaseMaster},\n\t\t\trun: func(context Context) error {\n\t\t\t\tst := context.State()\n\t\t\t\treturn upgradeEnvironConfig(st, st, environs.GlobalProviderRegistry())\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package configuration\nimport (\n \"testing\"\n)\n\n\n\nfunc Test_Initialize(t *testing.T) ", "output": "{\n path := \"./test-configuration.json\"\n Initialize(path)\n t.Log(_config.Database.Kind)\n t.Log(_config.Database.SQLite)\n t.Log(_config.Database.PostgreSQL)\n\n t.Log(_config.Session.Kind)\n t.Log(_config.Session.MaxAge)\n t.Log(_config.Session.Cookie)\n t.Log(_config.Session.SQLite)\n}"} {"input": "package errors_test\n\nimport (\n\t\"io\"\n\t\"testing\"\n\n\t. \"v2ray.com/core/common/errors\"\n\t\"v2ray.com/core/testing/assert\"\n)\n\nfunc TestError(t *testing.T) {\n\tassert := assert.On(t)\n\n\terr := New(\"TestError\")\n\tassert.Bool(GetSeverity(err) == SeverityInfo).IsTrue()\n\n\terr = New(\"TestError2\").Base(io.EOF)\n\tassert.Bool(GetSeverity(err) == SeverityInfo).IsTrue()\n\n\terr = New(\"TestError3\").Base(io.EOF).AtWarning()\n\tassert.Bool(GetSeverity(err) == SeverityWarning).IsTrue()\n\n\terr = New(\"TestError4\").Base(io.EOF).AtWarning()\n\terr = New(\"TestError5\").Base(err)\n\tassert.Bool(GetSeverity(err) == SeverityWarning).IsTrue()\n\tassert.String(err.Error()).Contains(\"EOF\")\n}\n\n\n\nfunc TestErrorMessage(t *testing.T) ", "output": "{\n\tassert := assert.On(t)\n\n\tdata := []struct {\n\t\terr error\n\t\tmsg string\n\t}{\n\t\t{\n\t\t\terr: New(\"a\").Base(New(\"b\")).Path(\"c\", \"d\", \"e\"),\n\t\t\tmsg: \"c|d|e: a > b\",\n\t\t},\n\t\t{\n\t\t\terr: New(\"a\").Base(New(\"b\").Path(\"c\")).Path(\"d\", \"e\"),\n\t\t\tmsg: \"d|e: a > c: b\",\n\t\t},\n\t}\n\n\tfor _, d := range data {\n\t\tassert.String(d.err.Error()).Equals(d.msg)\n\t}\n}"} {"input": "package testclient\n\nimport (\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/fields\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/labels\"\n\n\tauthorizationapi \"github.com/openshift/origin/pkg/authorization/api\"\n)\n\n\n\ntype FakeClusterRoles struct {\n\tFake *Fake\n}\n\nfunc (c *FakeClusterRoles) List(label labels.Selector, field fields.Selector) (*authorizationapi.ClusterRoleList, error) {\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"list-clusterRoles\"}, &authorizationapi.ClusterRoleList{})\n\treturn obj.(*authorizationapi.ClusterRoleList), err\n}\n\nfunc (c *FakeClusterRoles) Get(name string) (*authorizationapi.ClusterRole, error) {\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"get-clusterRole\"}, &authorizationapi.ClusterRole{})\n\treturn obj.(*authorizationapi.ClusterRole), err\n}\n\nfunc (c *FakeClusterRoles) Create(role *authorizationapi.ClusterRole) (*authorizationapi.ClusterRole, error) {\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"create-clusterRole\", Value: role}, &authorizationapi.ClusterRole{})\n\treturn obj.(*authorizationapi.ClusterRole), err\n}\n\nfunc (c *FakeClusterRoles) Update(role *authorizationapi.ClusterRole) (*authorizationapi.ClusterRole, error) {\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"update-clusterRole\"}, &authorizationapi.ClusterRole{})\n\treturn obj.(*authorizationapi.ClusterRole), err\n}\n\n\n\nfunc (c *FakeClusterRoles) Delete(name string) error ", "output": "{\n\tc.Fake.Actions = append(c.Fake.Actions, FakeAction{Action: \"delete-clusterRole\", Value: name})\n\treturn nil\n}"} {"input": "package whoami\n\nimport (\n\t\"net\"\n\t\"strconv\"\n\n\t\"github.com/coredns/coredns/request\"\n\n\t\"github.com/miekg/dns\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\ntype Whoami struct{}\n\n\nfunc (wh Whoami) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {\n\tstate := request.Request{W: w, Req: r}\n\n\ta := new(dns.Msg)\n\ta.SetReply(r)\n\ta.Compress = true\n\ta.Authoritative = true\n\n\tip := state.IP()\n\tvar rr dns.RR\n\n\tswitch state.Family() {\n\tcase 1:\n\t\trr = new(dns.A)\n\t\trr.(*dns.A).Hdr = dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeA, Class: state.QClass()}\n\t\trr.(*dns.A).A = net.ParseIP(ip).To4()\n\tcase 2:\n\t\trr = new(dns.AAAA)\n\t\trr.(*dns.AAAA).Hdr = dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeAAAA, Class: state.QClass()}\n\t\trr.(*dns.AAAA).AAAA = net.ParseIP(ip)\n\t}\n\n\tsrv := new(dns.SRV)\n\tsrv.Hdr = dns.RR_Header{Name: \"_\" + state.Proto() + \".\" + state.QName(), Rrtype: dns.TypeSRV, Class: state.QClass()}\n\tport, _ := strconv.Atoi(state.Port())\n\tsrv.Port = uint16(port)\n\tsrv.Target = \".\"\n\n\ta.Extra = []dns.RR{rr, srv}\n\n\tstate.SizeAndDo(a)\n\tw.WriteMsg(a)\n\n\treturn 0, nil\n}\n\n\n\n\nfunc (wh Whoami) Name() string ", "output": "{ return \"whoami\" }"} {"input": "package protolog \n\nimport (\n\t\"os\"\n\n\t\"go.pedge.io/dlog\"\n\t\"go.pedge.io/protolog\"\n)\n\nfunc init() {\n\tdlog.SetLogger(NewLogger(protolog.NewStandardLogger(protolog.NewFileFlusher(os.Stderr))))\n}\n\ntype logger struct {\n\tprotolog.Logger\n}\n\n\n\n\nfunc (l *logger) Debug(args ...interface{}) {\n\tl.Debugln(args...)\n}\n\nfunc (l *logger) Info(args ...interface{}) {\n\tl.Infoln(args...)\n}\n\nfunc (l *logger) Warn(args ...interface{}) {\n\tl.Warnln(args...)\n}\n\nfunc (l *logger) Error(args ...interface{}) {\n\tl.Errorln(args...)\n}\n\nfunc (l *logger) Fatal(args ...interface{}) {\n\tl.Fatalln(args...)\n}\n\nfunc (l *logger) Panic(args ...interface{}) {\n\tl.Panicln(args...)\n}\n\nfunc (l *logger) Print(args ...interface{}) {\n\tl.Println(args...)\n}\n\nfunc NewLogger(l protolog.Logger) dlog.Logger ", "output": "{\n\treturn &logger{l}\n}"} {"input": "package canopus\n\nimport \"net\"\n\nfunc Dial(address string) (conn Connection, err error) {\n\tudpConn, err := net.Dial(\"udp\", address)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn = &UDPConnection{\n\t\tconn: udpConn,\n\t}\n\n\treturn\n}\n\nfunc DialDTLS(address, identity, psk string) (conn Connection, err error) {\n\tudpConn, err := net.Dial(\"udp\", address)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn, err = NewDTLSConnection(udpConn, identity, psk)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\n\ntype CoapObserveMessage struct {\n\tCoapMessage\n\tResource string\n\tValue interface{}\n\tMsg Message\n}\n\nfunc (m *CoapObserveMessage) GetResource() string {\n\treturn m.Resource\n}\n\nfunc (m *CoapObserveMessage) GetValue() interface{} {\n\treturn m.Value\n}\n\nfunc (m *CoapObserveMessage) GetMessage() Message {\n\treturn m.GetMessage()\n}\n\nfunc NewObserveMessage(r string, val interface{}, msg Message) ObserveMessage ", "output": "{\n\treturn &CoapObserveMessage{\n\t\tResource: r,\n\t\tValue: val,\n\t\tMsg: msg,\n\t}\n}"} {"input": "package daemon\n\nimport \"time\"\n\n\n\nfunc (daemon *Daemon) ContainerWait(name string, timeout time.Duration) (int, error) ", "output": "{\n\tcontainer, err := daemon.Get(name)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\treturn container.WaitStop(timeout)\n}"} {"input": "package binlogplayer\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"vitess.io/vitess/go/sqltypes\"\n)\n\ntype fakeDBClient struct {\n}\n\n\n\nfunc NewFakeDBClient() DBClient {\n\treturn &fakeDBClient{}\n}\n\nfunc (dc *fakeDBClient) DBName() string {\n\treturn \"db\"\n}\n\nfunc (dc *fakeDBClient) Connect() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Begin() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Commit() error {\n\treturn nil\n}\n\n\n\nfunc (dc *fakeDBClient) Close() {\n}\n\nfunc (dc *fakeDBClient) ExecuteFetch(query string, maxrows int) (qr *sqltypes.Result, err error) {\n\tquery = strings.ToLower(query)\n\tswitch {\n\tcase strings.HasPrefix(query, \"insert\"):\n\t\treturn &sqltypes.Result{InsertID: 1}, nil\n\tcase strings.HasPrefix(query, \"update\"):\n\t\treturn &sqltypes.Result{RowsAffected: 1}, nil\n\tcase strings.HasPrefix(query, \"delete\"):\n\t\treturn &sqltypes.Result{RowsAffected: 1}, nil\n\tcase strings.HasPrefix(query, \"select\"):\n\t\tif strings.Contains(query, \"where\") {\n\t\t\treturn sqltypes.MakeTestResult(\n\t\t\t\tsqltypes.MakeTestFields(\n\t\t\t\t\t\"id|state|source\",\n\t\t\t\t\t\"int64|varchar|varchar\",\n\t\t\t\t),\n\t\t\t\t`1|Running|keyspace:\"ks\" shard:\"0\" key_range: `,\n\t\t\t), nil\n\t\t}\n\t\treturn &sqltypes.Result{}, nil\n\tcase strings.HasPrefix(query, \"use\"):\n\t\treturn &sqltypes.Result{}, nil\n\t}\n\treturn nil, fmt.Errorf(\"unexpected: %v\", query)\n}\n\nfunc (dc *fakeDBClient) Rollback() error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/franela/goreq\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype VaultRequest struct {\n\tgoreq.Request\n}\n\nfunc (r VaultRequest) Do() (*goreq.Response, error) {\n\tconfig := goreq.DefaultTransport.(*http.Transport).TLSClientConfig\n\tif config != nil {\n\t\tr.Insecure = config.InsecureSkipVerify\n\t}\n\tresp, err := r.Request.Do()\n\tfor err == nil && resp.StatusCode == 307 {\n\t\tio.Copy(ioutil.Discard, resp.Body)\n\t\tresp.Body.Close()\n\t\tr.Request.Uri = resp.Header.Get(\"Location\")\n\t\tresp, err = r.Request.Do()\n\t}\n\treturn resp, err\n}\n\ntype VaultWrappedResponse struct {\n\tData struct {\n\t\tWrappedSecret string `json:\"response\"`\n\t} `json:\"data\"`\n}\n\n\n\nfunc (vr *VaultWrappedResponse) Unwrap(v interface{}) error ", "output": "{\n\treturn json.Unmarshal([]byte(vr.Data.WrappedSecret), v)\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"sort\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc mkzdefaultcc(dir, file string) {\n\tout := fmt.Sprintf(\n\t\t\" auto generated by go tool dist\\n\"+\n\t\t\t\"\\n\"+\n\t\t\t\"package main\\n\"+\n\t\t\t\"\\n\"+\n\t\t\t\"const defaultCC = `%s`\\n\"+\n\t\t\t\"const defaultCXX = `%s`\\n\",\n\t\tdefaultcctarget, defaultcxxtarget)\n\n\twritefile(out, file, writeSkipSame)\n\n\ti := len(file) - len(\"go/zdefaultcc.go\")\n\tfile = file[:i] + \"c\" + file[i:]\n\twritefile(out, file, writeSkipSame)\n}\n\n\n\n\n\n\n\n\n\n\nfunc mkzcgo(dir, file string) {\n\tvar list []string\n\tfor plat, hasCgo := range cgoEnabled {\n\t\tif hasCgo {\n\t\t\tlist = append(list, plat)\n\t\t}\n\t}\n\tsort.Strings(list)\n\n\tvar buf bytes.Buffer\n\n\tfmt.Fprintf(&buf,\n\t\t\" auto generated by go tool dist\\n\"+\n\t\t\t\"\\n\"+\n\t\t\t\"package build\\n\"+\n\t\t\t\"\\n\"+\n\t\t\t\"var cgoEnabled = map[string]bool{\\n\")\n\tfor _, plat := range list {\n\t\tfmt.Fprintf(&buf, \"\\t%q: true,\\n\", plat)\n\t}\n\tfmt.Fprintf(&buf, \"}\")\n\n\twritefile(buf.String(), file, writeSkipSame)\n}\n\nfunc mkzosarch(dir, file string) ", "output": "{\n\tvar buf bytes.Buffer\n\tbuf.WriteString(\" auto generated by go tool dist\\n\\n\")\n\tbuf.WriteString(\"package main\\n\\n\")\n\tfmt.Fprintf(&buf, \"var osArchSupportsCgo = %#v\", cgoEnabled)\n\twritefile(buf.String(), file, writeSkipSame)\n}"} {"input": "package time\n\nimport (\n\t\"time\"\n)\n\nconst (\n\tDateTimeLayout = \"2006-01-02 15:04:05\"\n)\n\n\n\n\n\nfunc ParseDateTimeFormat(v string) (time.Time, error) {\n\treturn time.Parse(DateTimeLayout, v)\n}\n\n\nfunc MustParseDateTimeFormat(v string) time.Time {\n\tt, _ := ParseDateTimeFormat(v)\n\treturn t\n}\n\nfunc DateTimeFormat(t time.Time) string ", "output": "{\n\treturn t.Format(DateTimeLayout)\n}"} {"input": "package holdem\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"pokersml/cards\"\n\ntype actionType struct {\n id int\n desc string\n}\n\nvar CALL = &actionType{0, \"call\"}\nvar RAISE = &actionType{1, \"raise\"}\nvar FOLD = &actionType{0, \"fold\"}\n\ntype action struct {\n actionType *actionType\n value int\n}\n\ntype bot interface {\n do() action\n}\n\ntype exampleBot struct {}\n\nvar EXAMPLEBOT = &exampleBot{}\n\ntype Player struct {\n Name string\n Bot bot\n}\n\ntype GameSettings struct {\n Speed int\n}\n\ntype game struct {\n players *[]Player\n settings *GameSettings\n deck *cards.Deck\n}\n\nfunc StartGame(players *[]Player, settings *GameSettings) *game {\n game := game{players, settings, cards.NewDeck()}\n rand.Seed(42)\n fmt.Println(\"Game started!\")\n return &game\n}\n\nfunc (b exampleBot) do() action ", "output": "{\n action := action{FOLD, 0}\n return action\n}"} {"input": "package iso20022\n\n\ntype AuthorisationResult5 struct {\n\n\tAuthorisationEntity *GenericIdentification70 `xml:\"AuthstnNtty,omitempty\"`\n\n\tResponseToAuthorisation *ResponseType1 `xml:\"RspnToAuthstn\"`\n\n\tAuthorisationCode *Min6Max8Text `xml:\"AuthstnCd,omitempty\"`\n}\n\n\n\nfunc (a *AuthorisationResult5) AddResponseToAuthorisation() *ResponseType1 {\n\ta.ResponseToAuthorisation = new(ResponseType1)\n\treturn a.ResponseToAuthorisation\n}\n\nfunc (a *AuthorisationResult5) SetAuthorisationCode(value string) {\n\ta.AuthorisationCode = (*Min6Max8Text)(&value)\n}\n\nfunc (a *AuthorisationResult5) AddAuthorisationEntity() *GenericIdentification70 ", "output": "{\n\ta.AuthorisationEntity = new(GenericIdentification70)\n\treturn a.AuthorisationEntity\n}"} {"input": "package iso20022\n\n\ntype CardPaymentTransaction42 struct {\n\n\tSaleReferenceIdentification *Max35Text `xml:\"SaleRefId,omitempty\"`\n\n\tTransactionIdentification *TransactionIdentifier1 `xml:\"TxId\"`\n\n\tRecipientTransactionIdentification *Max35Text `xml:\"RcptTxId,omitempty\"`\n\n\tReconciliationIdentification *Max35Text `xml:\"RcncltnId,omitempty\"`\n\n\tInterchangeData *Max140Text `xml:\"IntrchngData,omitempty\"`\n\n\tTransactionDetails *CardPaymentTransactionDetails22 `xml:\"TxDtls\"`\n}\n\nfunc (c *CardPaymentTransaction42) SetSaleReferenceIdentification(value string) {\n\tc.SaleReferenceIdentification = (*Max35Text)(&value)\n}\n\n\n\nfunc (c *CardPaymentTransaction42) SetRecipientTransactionIdentification(value string) {\n\tc.RecipientTransactionIdentification = (*Max35Text)(&value)\n}\n\nfunc (c *CardPaymentTransaction42) SetReconciliationIdentification(value string) {\n\tc.ReconciliationIdentification = (*Max35Text)(&value)\n}\n\nfunc (c *CardPaymentTransaction42) SetInterchangeData(value string) {\n\tc.InterchangeData = (*Max140Text)(&value)\n}\n\nfunc (c *CardPaymentTransaction42) AddTransactionDetails() *CardPaymentTransactionDetails22 {\n\tc.TransactionDetails = new(CardPaymentTransactionDetails22)\n\treturn c.TransactionDetails\n}\n\nfunc (c *CardPaymentTransaction42) AddTransactionIdentification() *TransactionIdentifier1 ", "output": "{\n\tc.TransactionIdentification = new(TransactionIdentifier1)\n\treturn c.TransactionIdentification\n}"} {"input": "package module\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/config\"\n\t\"github.com/hashicorp/terraform/svchost/disco\"\n)\n\nfunc init() {\n\tif os.Getenv(\"TF_LOG\") == \"\" {\n\t\tlog.SetOutput(ioutil.Discard)\n\t}\n}\n\nconst fixtureDir = \"./test-fixtures\"\n\nfunc tempDir(t *testing.T) string {\n\tt.Helper()\n\tdir, err := ioutil.TempDir(\"\", \"tf\")\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\tif err := os.RemoveAll(dir); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\treturn dir\n}\n\nfunc testConfig(t *testing.T, n string) *config.Config {\n\tt.Helper()\n\tc, err := config.LoadDir(filepath.Join(fixtureDir, n))\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\treturn c\n}\n\n\n\nfunc testStorage(t *testing.T, d *disco.Disco) *Storage ", "output": "{\n\tt.Helper()\n\treturn NewStorage(tempDir(t), d)\n}"} {"input": "package cloudformation\n\n\n\ntype AWSWAFWebACL_ActivatedRule struct {\n\n\tAction *AWSWAFWebACL_WafAction `json:\"Action,omitempty\"`\n\n\tPriority int `json:\"Priority,omitempty\"`\n\n\tRuleId string `json:\"RuleId,omitempty\"`\n}\n\n\n\n\nfunc (r *AWSWAFWebACL_ActivatedRule) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::WAF::WebACL.ActivatedRule\"\n}"} {"input": "package value\n\nimport (\n\t\"bytes\"\n)\n\n\n\n\n\n\n\n\ntype Cell struct {\n\tCar Value\n\tCdr Value\n}\n\n\nfunc (c *Cell) Walk(fn func(Value)) {\n\tcur := c\n\tfor {\n\t\tfn(cur.Car)\n\n\t\tif cur.Cdr == NIL {\n\t\t\treturn\n\t\t}\n\n\t\tnext, ok := cur.Cdr.(*Cell)\n\t\tif !ok {\n\t\t\tErrorf(\"cannot evaluate an improper list: %s\", c)\n\t\t}\n\t\tcur = next\n\t}\n}\n\nfunc (c *Cell) Equal(cmp Value) Value {\n\tx, ok := cmp.(*Cell)\n\tif !ok {\n\t\treturn NIL\n\t}\n\n\tif c.Car.Equal(x.Car) != T {\n\t\treturn NIL\n\t}\n\tif c.Cdr.Equal(x.Cdr) != T {\n\t\treturn NIL\n\t}\n\treturn T\n}\n\nfunc (c *Cell) String() string {\n\tvar buf bytes.Buffer\n\n\tbuf.WriteByte('(')\n\tfor {\n\t\tbuf.WriteString(c.Car.String())\n\n\t\tif c.Cdr == NIL {\n\t\t\tbreak\n\t\t}\n\n\t\tcdr, ok := c.Cdr.(*Cell)\n\t\tif !ok {\n\t\t\tbuf.WriteString(\" . \")\n\t\t\tbuf.WriteString(c.Cdr.String())\n\t\t\tbreak\n\t\t}\n\t\tc = cdr \n\n\t\tbuf.WriteByte(' ')\n\t}\n\tbuf.WriteByte(')')\n\n\treturn buf.String()\n}\n\nfunc Cons(x, y Value) *Cell ", "output": "{\n\treturn &Cell{Car: x, Cdr: y}\n}"} {"input": "package disk\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/vslm\"\n)\n\ntype register struct {\n\t*flags.DatastoreFlag\n}\n\nfunc init() {\n\tcli.Register(\"disk.register\", ®ister{})\n}\n\nfunc (cmd *register) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)\n\tcmd.DatastoreFlag.Register(ctx, f)\n}\n\nfunc (cmd *register) Usage() string {\n\treturn \"PATH [NAME]\"\n}\n\nfunc (cmd *register) Description() string {\n\treturn `Register existing disk on DS.\n\nExamples:\n govc disk.register disks/disk1.vmdk my-disk`\n}\n\n\n\nfunc (cmd *register) Run(ctx context.Context, f *flag.FlagSet) error ", "output": "{\n\tds, err := cmd.Datastore()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm := vslm.NewObjectManager(ds.Client())\n\n\tpath := ds.NewURL(f.Arg(0)).String()\n\n\tobj, err := m.RegisterDisk(ctx, path, f.Arg(1))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(obj.Config.Id.Id)\n\n\treturn nil\n}"} {"input": "package engine\n\nimport (\n\t\"time\"\n\n\t\"github.com/aws/amazon-ecs-agent/agent/api\"\n)\n\n\n\ntype impossibleTransitionError struct {\n\tstate api.ContainerStatus\n}\n\nfunc (err *impossibleTransitionError) Error() string {\n\treturn \"Cannot transition to \" + err.state.String()\n}\nfunc (err *impossibleTransitionError) ErrorName() string { return \"ImpossibleStateTransitionError\" }\n\ntype DockerTimeoutError struct {\n\tduration time.Duration\n\ttransition string\n}\n\n\nfunc (err *DockerTimeoutError) ErrorName() string { return \"DockerTimeoutError\" }\n\ntype ContainerVanishedError struct{}\n\nfunc (err ContainerVanishedError) Error() string { return \"No container matching saved ID found\" }\nfunc (err ContainerVanishedError) ErrorName() string { return \"ContainerVanishedError\" }\n\ntype CannotXContainerError struct {\n\ttransition string\n\tmsg string\n}\n\nfunc (err CannotXContainerError) Error() string { return err.msg }\nfunc (err CannotXContainerError) ErrorName() string {\n\treturn \"Cannot\" + err.transition + \"ContainerError\"\n}\n\ntype OutOfMemoryError struct{}\n\nfunc (err OutOfMemoryError) Error() string { return \"Container killed due to memory usage\" }\nfunc (err OutOfMemoryError) ErrorName() string { return \"OutOfMemoryError\" }\n\n\ntype DockerStateError struct {\n\tdockerError string\n\tname string\n}\n\nfunc NewDockerStateError(err string) DockerStateError {\n\treturn DockerStateError{\n\t\tdockerError: err,\n\t\tname: \"DockerStateError\",\n\t}\n}\n\nfunc (err DockerStateError) Error() string {\n\treturn err.dockerError\n}\nfunc (err DockerStateError) ErrorName() string {\n\treturn err.name\n}\n\nfunc (err *DockerTimeoutError) Error() string ", "output": "{\n\treturn \"Could not transition to \" + err.transition + \"; timed out after waiting \" + err.duration.String()\n}"} {"input": "package dbr\n\ntype union struct {\n\tbuilder []Builder\n\tall bool\n}\n\n\nfunc Union(builder ...Builder) interface {\n\tBuilder\n\tAs(string) Builder\n} {\n\treturn &union{\n\t\tbuilder: builder,\n\t}\n}\n\n\n\n\nfunc (u *union) Build(d Dialect, buf Buffer) error {\n\tfor i, b := range u.builder {\n\t\tif i > 0 {\n\t\t\tbuf.WriteString(\" UNION \")\n\t\t\tif u.all {\n\t\t\t\tbuf.WriteString(\"ALL \")\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(placeholder)\n\t\tbuf.WriteValue(b)\n\t}\n\treturn nil\n}\n\nfunc (u *union) As(alias string) Builder {\n\treturn as(u, alias)\n}\n\nfunc UnionAll(builder ...Builder) interface {\n\tBuilder\n\tAs(string) Builder\n} ", "output": "{\n\treturn &union{\n\t\tbuilder: builder,\n\t\tall: true,\n\t}\n}"} {"input": "package todoist\n\nimport \"fmt\"\n\ntype IntBool bool\n\nfunc (i IntBool) Bool() bool {\n\tif i {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\nfunc (i IntBool) MarshalJSON() ([]byte, error) {\n\tif i {\n\t\treturn []byte(\"1\"), nil\n\t} else {\n\t\treturn []byte(\"0\"), nil\n\t}\n}\n\nfunc (i *IntBool) UnmarshalJSON(b []byte) (err error) {\n\tswitch string(b) {\n\tcase \"1\":\n\t\t*i = true\n\tcase \"0\":\n\t\t*i = false\n\tdefault:\n\t\treturn fmt.Errorf(\"Could not unmarshal into intbool: %s\", string(b))\n\t}\n\treturn nil\n}\n\ntype ColorStringer interface {\n\tString() string\n\tColorString() string\n}\n\ntype NoColorString struct {\n\ts string\n}\n\nfunc NewNoColorString(s string) NoColorString {\n\treturn NoColorString{s}\n}\n\n\n\nfunc (n NoColorString) ColorString() string {\n\treturn n.s\n}\n\nfunc (n NoColorString) String() string ", "output": "{\n\treturn n.s\n}"} {"input": "package signer_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/EscherAuth/escher/config\"\n\t\"github.com/EscherAuth/escher/signer\"\n\t. \"github.com/EscherAuth/escher/testing/cases\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestCanonicalizeRequest(t *testing.T) ", "output": "{\n\tt.Log(\"CanonicalizeRequest should return with a proper string\")\n\tEachTestConfigFor(t, []string{\"signRequest\"}, []string{\"error\"}, func(t *testing.T, c config.Config, testConfig TestConfig) bool {\n\t\tcanonicalizedRequest := signer.New(c).CanonicalizeRequest(&testConfig.Request, testConfig.HeadersToSign)\n\n\t\tif len(testConfig.Expected.CanonicalizedRequest) == 0 {\n\t\t\treturn true\n\t\t}\n\n\t\treturn assert.Equal(t, testConfig.Expected.CanonicalizedRequest, canonicalizedRequest, \"canonicalizedRequest should be eq\")\n\t})\n}"} {"input": "package processors\n\nimport (\n\t\"github.com/golangci/golangci-lint/pkg/config\"\n\t\"github.com/golangci/golangci-lint/pkg/result\"\n)\n\ntype lineToCount map[int]int\ntype fileToLineToCount map[string]lineToCount\n\ntype UniqByLine struct {\n\tflc fileToLineToCount\n\tcfg *config.Config\n}\n\nfunc NewUniqByLine(cfg *config.Config) *UniqByLine {\n\treturn &UniqByLine{\n\t\tflc: fileToLineToCount{},\n\t\tcfg: cfg,\n\t}\n}\n\nvar _ Processor = &UniqByLine{}\n\n\n\nfunc (p *UniqByLine) Process(issues []result.Issue) ([]result.Issue, error) {\n\tif !p.cfg.Output.UniqByLine {\n\t\treturn issues, nil\n\t}\n\n\treturn filterIssues(issues, func(i *result.Issue) bool {\n\t\tif i.Replacement != nil && p.cfg.Issues.NeedFix {\n\t\t\treturn true\n\t\t}\n\n\t\tlc := p.flc[i.FilePath()]\n\t\tif lc == nil {\n\t\t\tlc = lineToCount{}\n\t\t\tp.flc[i.FilePath()] = lc\n\t\t}\n\n\t\tconst limit = 1\n\t\tcount := lc[i.Line()]\n\t\tif count == limit {\n\t\t\treturn false\n\t\t}\n\n\t\tlc[i.Line()]++\n\t\treturn true\n\t}), nil\n}\n\nfunc (p UniqByLine) Finish() {}\n\nfunc (p UniqByLine) Name() string ", "output": "{\n\treturn \"uniq_by_line\"\n}"} {"input": "package tlsutil\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\t\"io/ioutil\"\n)\n\ntype TLSConfig struct {\n\tConfig *tls.Config\n}\n\nfunc NewTLSConfig() TLSConfig {\n\treturn TLSConfig{\n\t\tConfig: &tls.Config{\n\t\t\tCertificates: []tls.Certificate{},\n\t\t},\n\t}\n}\n\nfunc (tc *TLSConfig) LoadX509KeyPair(cert_filepath, key_filepath string) error {\n\tcert, err := tls.LoadX509KeyPair(cert_filepath, key_filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttc.Config.Certificates = append(tc.Config.Certificates, cert)\n\treturn nil\n}\n\n\n\nfunc (tc *TLSConfig) Inflate() {\n\ttc.Config.BuildNameToCertificate()\n}\n\nfunc (tc *TLSConfig) LoadCACert(ca_cert_filepath string) error ", "output": "{\n\tcert, err := ioutil.ReadFile(ca_cert_filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tc.Config.RootCAs == nil {\n\t\ttc.Config.RootCAs = x509.NewCertPool()\n\t}\n\n\tok := tc.Config.RootCAs.AppendCertsFromPEM(cert)\n\tif !ok {\n\t\treturn fmt.Errorf(\"Cannot add Root CA cert %v\", ca_cert_filepath)\n\t}\n\treturn nil\n}"} {"input": "package hash\n\nimport \"crypto/sha512\"\n\n\n\n\nfunc HashSHA512(input string) string ", "output": "{\n\treturn HashWith(sha512.New(), input)\n}"} {"input": "package nanomsg\n\n\nimport \"C\"\n\nimport (\n\t\"time\"\n)\n\nconst (\n\tSURVEYOR = Protocol(C.NN_SURVEYOR)\n\tRESPONDENT = Protocol(C.NN_RESPONDENT)\n)\n\ntype SurveyorSocket struct {\n\t*Socket\n}\n\n\n\n\n\n\nfunc NewSurveyorSocket() (*SurveyorSocket, error) {\n\tsocket, err := NewSocket(AF_SP, SURVEYOR)\n\treturn &SurveyorSocket{socket}, err\n}\n\n\nfunc (s *SurveyorSocket) Deadline() (time.Duration, error) {\n\treturn s.Socket.SockOptDuration(C.NN_SURVEYOR, C.NN_SURVEYOR_DEADLINE, time.Millisecond)\n}\n\n\n\n\n\n\ntype RespondentSocket struct {\n\t*Socket\n}\n\n\n\n\nfunc NewRespondentSocket() (*RespondentSocket, error) {\n\tsocket, err := NewSocket(AF_SP, RESPONDENT)\n\treturn &RespondentSocket{socket}, err\n}\n\nfunc (s *SurveyorSocket) SetDeadline(deadline time.Duration) error ", "output": "{\n\treturn s.Socket.SetSockOptDuration(C.NN_SURVEYOR, C.NN_SURVEYOR_DEADLINE, time.Millisecond, deadline)\n}"} {"input": "package splice\n\nimport ()\n\nfunc (p *Pair) LoadFromAt(fd uintptr, sz int, off int64) (int, error) {\n\tpanic(\"not implemented\")\n\treturn 0, nil\n}\n\nfunc (p *Pair) LoadFrom(fd uintptr, sz int) (int, error) {\n\tpanic(\"not implemented\")\n\treturn 0, nil\n}\n\n\n\nfunc (p *Pair) WriteTo(fd uintptr, n int) (int, error) ", "output": "{\n\tpanic(\"not implemented\")\n\treturn 0, nil\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/alt234/affadmin/db\"\n\t\"github.com/alt234/affadmin/models\"\n\t\"github.com/gorilla/schema\"\n\t\"github.com/unrolled/render\"\n\t\"log\"\n\t\"net/http\"\n)\n\ntype FestivalController struct {\n\tAppController\n\t*render.Render\n\tDB *db.DB\n}\n\n\n\nfunc (c *FestivalController) Create(rw http.ResponseWriter, r *http.Request) error {\n\tr.ParseForm()\n\n\tfestival := new(models.Festival)\n\tdecoder := schema.NewDecoder()\n\terr := decoder.Decode(festival, r.PostForm)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = c.DB.InsertNewFestival(festival)\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n\n\treturn nil\n}\n\nfunc (c *FestivalController) Index(rw http.ResponseWriter, r *http.Request) error ", "output": "{\n\tfestivals, err := c.DB.GetAllFestivals()\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n\n\tdata := struct {\n\t\tTitle string\n\t\tFestivals []*models.Festival\n\t}{\n\t\t\"Festivals\",\n\t\tfestivals,\n\t}\n\n\tc.HTML(rw, http.StatusOK, \"festivals/index\", data)\n\n\treturn nil\n}"} {"input": "package s3afero\n\nimport (\n\t\"github.com/spf13/afero\"\n)\n\ntype MultiOption func(b *MultiBucketBackend) error\n\n\n\ntype SingleOption func(b *SingleBucketBackend) error\n\nfunc MultiWithMetaFs(fs afero.Fs) MultiOption ", "output": "{\n\treturn func(b *MultiBucketBackend) error {\n\t\tif err := ensureNoOsFs(\"MultiWithMetaFs\", fs); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb.configOnly.metaFs = fs\n\t\treturn nil\n\t}\n}"} {"input": "package comm\n\nimport (\n\t\"context\"\n\n\t\"github.com/hyperledger/fabric/common/semaphore\"\n\t\"google.golang.org/grpc\"\n)\n\ntype Semaphore interface {\n\tAcquire(ctx context.Context) error\n\tRelease()\n}\n\ntype Throttle struct {\n\tnewSemaphore NewSemaphoreFunc\n\tsemaphore Semaphore\n}\n\ntype ThrottleOption func(t *Throttle)\ntype NewSemaphoreFunc func(size int) Semaphore\n\nfunc WithNewSemaphore(newSemaphore NewSemaphoreFunc) ThrottleOption {\n\treturn func(t *Throttle) {\n\t\tt.newSemaphore = newSemaphore\n\t}\n}\n\nfunc NewThrottle(maxConcurrency int, options ...ThrottleOption) *Throttle {\n\tt := &Throttle{\n\t\tnewSemaphore: func(count int) Semaphore { return semaphore.New(count) },\n\t}\n\n\tfor _, optionFunc := range options {\n\t\toptionFunc(t)\n\t}\n\n\tt.semaphore = t.newSemaphore(maxConcurrency)\n\treturn t\n}\n\n\n\nfunc (t *Throttle) StreamServerInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {\n\tctx := ss.Context()\n\tif err := t.semaphore.Acquire(ctx); err != nil {\n\t\treturn err\n\t}\n\tdefer t.semaphore.Release()\n\n\treturn handler(srv, ss)\n}\n\nfunc (t *Throttle) UnaryServerIntercptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) ", "output": "{\n\tif err := t.semaphore.Acquire(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer t.semaphore.Release()\n\n\treturn handler(ctx, req)\n}"} {"input": "package changelog\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n)\n\n\n\ntype SectionAliasMap map[string][]string\n\n\nfunc NewSectionAliasMap() SectionAliasMap {\n\tsectionAliasMap := make(SectionAliasMap)\n\tsectionAliasMap[\"Features\"] = []string{\"ft\", \"feat\"}\n\tsectionAliasMap[\"Bug Fixes\"] = []string{\"fx\", \"fix\"}\n\tsectionAliasMap[\"Performance\"] = []string{\"perf\"}\n\tsectionAliasMap[\"Breaking Changes\"] = []string{\"breaks\"}\n\tsectionAliasMap[\"Unknown\"] = []string{\"unk\"}\n\treturn sectionAliasMap\n}\n\n\nfunc (s SectionAliasMap) SectionFor(alias string) string {\n\tfor title, aliases := range s {\n\t\tfor i := range aliases {\n\t\t\tif aliases[i] == alias {\n\t\t\t\treturn strings.Title(title)\n\t\t\t}\n\t\t}\n\t}\n\treturn \"Unknown\"\n}\n\n\nfunc MergeSectionAliasMaps(first SectionAliasMap, additional ...SectionAliasMap) SectionAliasMap {\n\tfor _, successive := range additional {\n\t\tfor title, aliases := range successive {\n\t\t\ttitle = strings.Title(title)\n\t\t\tif _, ok := first[title]; !ok {\n\t\t\t\tfirst[title] = aliases\n\t\t\t}\n\t\t\tfirst[title] = mergeStringSlices(first[title], aliases)\n\t\t}\n\t}\n\treturn first\n}\n\n\n\n\nfunc (s SectionAliasMap) Grep() string {\n\tprefixes := []string{\"BREAKING\"}\n\tfor _, items := range s {\n\t\tfor _, item := range items {\n\t\t\tif item == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tprefixes = append(prefixes, fmt.Sprintf(\"^%s\", item))\n\t\t}\n\t}\n\tsort.Strings(prefixes)\n\treturn strings.Join(prefixes, \"|\")\n}\n\nfunc mergeStringSlices(first []string, successive ...[]string) []string ", "output": "{\n\tvalues := map[string]bool{}\n\tfor _, word := range first {\n\t\tvalues[word] = true\n\t}\n\tfor _, next := range successive {\n\t\tfor _, word := range next {\n\t\t\tvalues[word] = true\n\t\t}\n\t}\n\n\tkeys := make([]string, 0, len(values))\n\tfor k := range values {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\treturn keys\n}"} {"input": "package main\n\nimport \"github.com/augustoroman/serial_lcd\"\n\ntype FakeLcd struct{}\n\nfunc (f FakeLcd) SetBG(r, g, b uint8) error { return nil }\nfunc (f FakeLcd) SetOn(On bool) error { return nil }\nfunc (f FakeLcd) SetBrightness(b uint8) error { return nil }\n\nfunc (f FakeLcd) SetAutoscroll(On bool) error { return nil }\nfunc (f FakeLcd) SetSize(cols, rows uint8) error { return nil }\nfunc (f FakeLcd) Clear() error { return nil }\nfunc (f FakeLcd) Home() error { return nil }\nfunc (f FakeLcd) MoveTo(col, row uint8) error { return nil }\nfunc (f FakeLcd) MoveForward() error { return nil }\nfunc (f FakeLcd) MoveBack() error { return nil }\nfunc (f FakeLcd) Write(b []byte) (int, error) { return len(b), nil }\n\nfunc (f FakeLcd) CreateCustomChar(spot uint8, c serial_lcd.Char) error { return nil }\n\nfunc (f FakeLcd) SetContrast(c uint8) error ", "output": "{ return nil }"} {"input": "package math32\n\nfunc Abs(x float32) float32\n\n\n\nfunc abs(x float32) float32 ", "output": "{\n\tswitch {\n\tcase x < 0:\n\t\treturn -x\n\tcase x == 0:\n\t\treturn 0 \n\t}\n\treturn x\n}"} {"input": "package atomic\n\nimport (\n\t\"encoding/json\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\n\ntype Uint32 struct {\n\t_ nocmp \n\n\tv uint32\n}\n\n\nfunc NewUint32(val uint32) *Uint32 {\n\treturn &Uint32{v: val}\n}\n\n\n\n\n\nfunc (i *Uint32) Add(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, delta)\n}\n\n\nfunc (i *Uint32) Sub(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, ^(delta - 1))\n}\n\n\nfunc (i *Uint32) Inc() uint32 {\n\treturn i.Add(1)\n}\n\n\nfunc (i *Uint32) Dec() uint32 {\n\treturn i.Sub(1)\n}\n\n\nfunc (i *Uint32) CAS(old, new uint32) (swapped bool) {\n\treturn atomic.CompareAndSwapUint32(&i.v, old, new)\n}\n\n\nfunc (i *Uint32) Store(val uint32) {\n\tatomic.StoreUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) Swap(val uint32) (old uint32) {\n\treturn atomic.SwapUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(i.Load())\n}\n\n\nfunc (i *Uint32) UnmarshalJSON(b []byte) error {\n\tvar v uint32\n\tif err := json.Unmarshal(b, &v); err != nil {\n\t\treturn err\n\t}\n\ti.Store(v)\n\treturn nil\n}\n\n\nfunc (i *Uint32) String() string {\n\tv := i.Load()\n\treturn strconv.FormatUint(uint64(v), 10)\n}\n\nfunc (i *Uint32) Load() uint32 ", "output": "{\n\treturn atomic.LoadUint32(&i.v)\n}"} {"input": "package servicelabel\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/namsral/flag\"\n\n\t\"go.ligato.io/cn-infra/v2/infra\"\n\t\"go.ligato.io/cn-infra/v2/logging/logrus\"\n)\n\nvar microserviceLabelFlag string\n\nfunc init() {\n\tflag.StringVar(µserviceLabelFlag, \"microservice-label\", \"vpp1\", fmt.Sprintf(\"microservice label; also set via '%v' env variable.\", MicroserviceLabelEnvVar))\n}\n\n\ntype Plugin struct {\n\tinfra.PluginName\n\tMicroserviceLabel string\n}\n\n\nfunc (p *Plugin) Init() error {\n\tif p.MicroserviceLabel == \"\" {\n\t\tp.MicroserviceLabel = microserviceLabelFlag\n\t}\n\tlogrus.DefaultLogger().Debugf(\"Microservice label is set to %v\", p.MicroserviceLabel)\n\treturn nil\n}\n\n\nfunc (p *Plugin) Close() error {\n\treturn nil\n}\n\n\n\nfunc (p *Plugin) GetAgentLabel() string {\n\treturn p.MicroserviceLabel\n}\n\n\n\nfunc (p *Plugin) GetAgentPrefix() string {\n\treturn agentPrefix + p.MicroserviceLabel + \"/\"\n}\n\n\n\nfunc (p *Plugin) GetDifferentAgentPrefix(microserviceLabel string) string {\n\treturn GetDifferentAgentPrefix(microserviceLabel)\n}\n\n\n\n\n\nfunc (p *Plugin) GetAllAgentsPrefix() string ", "output": "{\n\treturn GetAllAgentsPrefix()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\nfunc init() {\n\td1 := &D1{}\n\tchallenges[1] = &challenge{\"Day 01\", \"input/day01.txt\", d1}\n}\n\n\nfunc MFR(mass int) int {\n\treturn (mass / 3) - 2\n}\n\ntype D1 struct {\n\tmodules []int\n}\n\nfunc (d1 *D1) parse(line string) error {\n\tv, err := strconv.Atoi(line)\n\tif err == nil {\n\t\td1.modules = append(d1.modules, v)\n\t}\n\treturn err\n}\n\nfunc (d1 *D1) part1() (string, error) {\n\tsum := 0\n\tfor _, module := range d1.modules {\n\t\tsum += MFR(module)\n\t}\n\treturn fmt.Sprintf(\"Sum of fuel requirements is %d\", sum), nil\n}\n\nfunc TotalMFR(mass int) int {\n\treq := MFR(mass)\n\tif req > 0 {\n\t\treq += TotalMFR(req)\n\t} else {\n\t\treq = 0\n\t}\n\treturn req\n}\n\n\n\nfunc (d1 *D1) part2() (string, error) ", "output": "{\n\tsum := 0\n\tfor _, module := range d1.modules {\n\t\tsum += TotalMFR(module)\n\t}\n\treturn fmt.Sprintf(\"Sum of fuel requirements is %d\", sum), nil\n}"} {"input": "package bitbucket\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/javiermanzano/goth\"\n)\n\n\ntype Session struct {\n\tAuthURL string\n\tAccessToken string\n\tRefreshToken string\n\tExpiresAt time.Time\n}\n\n\nfunc (s Session) GetAuthURL() (string, error) {\n\tif s.AuthURL == \"\" {\n\t\treturn \"\", errors.New(goth.NoAuthUrlErrorMessage)\n\t}\n\treturn s.AuthURL, nil\n}\n\n\nfunc (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {\n\tp := provider.(*Provider)\n\ttoken, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get(\"code\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !token.Valid() {\n\t\treturn \"\", errors.New(\"Invalid token received from provider\")\n\t}\n\n\ts.AccessToken = token.AccessToken\n\ts.RefreshToken = token.RefreshToken\n\ts.ExpiresAt = token.Expiry\n\treturn token.AccessToken, err\n}\n\n\nfunc (s Session) Marshal() string {\n\tb, _ := json.Marshal(s)\n\treturn string(b)\n}\n\n\n\n\nfunc (s Session) String() string {\n\treturn s.Marshal()\n}\n\nfunc (p *Provider) UnmarshalSession(data string) (goth.Session, error) ", "output": "{\n\tsess := &Session{}\n\terr := json.NewDecoder(strings.NewReader(data)).Decode(sess)\n\treturn sess, err\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nvar (\n\tsrv *httptest.Server\n)\n\nfunc mockHandler(w http.ResponseWriter, r *http.Request) {\n}\n\nfunc setupServer() {\n\trouter := Router{mux.NewRouter()}\n\tm := RouteMap{\n\t\t\"GET\": {\n\t\t\t\"/it\": mockHandler,\n\t\t},\n\t}\n\n\trouter.AddRoutes(\"/test\", m)\n\trouter.AddCorsRoutes(\"/cors\", m)\n\tsrv = httptest.NewServer(router)\n}\n\nfunc teardownServer() {\n\tsrv.Close()\n}\n\n\n\nfunc TestCorsRoute(t *testing.T) {\n\tsetupServer()\n\tdefer teardownServer()\n\n\tpath := srv.URL + \"/cors/it\"\n\n\treq, _ := http.NewRequest(\"GET\", path, nil)\n\treq.Header.Add(\"Origin\", srv.URL)\n\tresp, err := http.DefaultClient.Do(req)\n\n\tassert.Nil(t, err)\n\tassert.Equal(t, 200, resp.StatusCode)\n\tassert.Equal(t, srv.URL, resp.Header.Get(\"Access-Control-Allow-Origin\"), \"CORS Allow-Origin not set\")\n}\n\nfunc TestRoute(t *testing.T) ", "output": "{\n\tsetupServer()\n\tdefer teardownServer()\n\n\tpath := srv.URL + \"/test/it\"\n\tresp, err := http.DefaultClient.Get(path)\n\n\tassert.Nil(t, err)\n\tassert.Equal(t, 200, resp.StatusCode)\n}"} {"input": "package jsonhelper\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"io\"\n)\n\n\nfunc UnmarshalData(r io.Reader, data interface{}) error {\n\td := jsoniter.NewDecoder(r)\n\treturn d.Decode(data)\n}\n\n\n\n\nfunc MarshalData(w io.Writer, data interface{}) error ", "output": "{\n\te := jsoniter.NewEncoder(w)\n\treturn e.Encode(data)\n}"} {"input": "package rest\n\nimport (\n\t\"fmt\"\n)\n\ntype imagecache struct {\n\tca cache\n}\n\ntype pic struct {\n\tpng []byte\n\tpkthsh hashcode\n}\n\nfunc (p pic) hash() hashcode {\n\treturn p.pkthsh\n}\n\n\n\nfunc (ic imagecache) put(hsh hashcode, png []byte) {\n\tsz := 0\n\tif __DEBUG {\n\t\tsz = len(png)\n\t}\n\tdebugf(\"Storing image for %v (length %v)\", hsh, sz)\n\tp := pic{}\n\tp.png = png\n\tp.pkthsh = hsh\n\tic.ca.put(p)\n}\n\nfunc (ic imagecache) get(hsh hashcode) ([]byte, bool) {\n\tdebugf(\"Fetching image for %v\", hsh)\n\tany, present := ic.ca.get(hsh)\n\tif !present {\n\t\treturn nil, false\n\t}\n\tp, ok := any.(pic)\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"Expected type pic received: %v\", any))\n\t}\n\treturn p.png, true\n}\n\nfunc makeImageCache() imagecache ", "output": "{\n\tic := imagecache{}\n\tic.ca = makeCache(pic{})\n\treturn ic\n}"} {"input": "package git\n\nimport \"strings\"\n\n\ntype Reference struct {\n\tName string\n\trepo *Repository\n\tObject SHA1 \n\tType string\n}\n\n\nfunc (ref *Reference) Commit() (*Commit, error) {\n\treturn ref.repo.getCommit(ref.Object)\n}\n\n\n\n\n\nfunc (ref *Reference) RefGroup() string {\n\tif ref == nil {\n\t\treturn \"\"\n\t}\n\tif strings.HasPrefix(ref.Name, \"refs/heads/\") {\n\t\treturn \"heads\"\n\t}\n\tif strings.HasPrefix(ref.Name, \"refs/tags/\") {\n\t\treturn \"tags\"\n\t}\n\tif strings.HasPrefix(ref.Name, \"refs/remotes/\") {\n\t\treturn \"remotes\"\n\t}\n\tif strings.HasPrefix(ref.Name, \"refs/pull/\") && strings.IndexByte(ref.Name[10:], '/') > -1 {\n\t\treturn \"pull\"\n\t}\n\treturn \"\"\n}\n\nfunc (ref *Reference) ShortName() string ", "output": "{\n\tif ref == nil {\n\t\treturn \"\"\n\t}\n\tif strings.HasPrefix(ref.Name, \"refs/heads/\") {\n\t\treturn ref.Name[11:]\n\t}\n\tif strings.HasPrefix(ref.Name, \"refs/tags/\") {\n\t\treturn ref.Name[10:]\n\t}\n\tif strings.HasPrefix(ref.Name, \"refs/remotes/\") {\n\t\treturn ref.Name[13:]\n\t}\n\tif strings.HasPrefix(ref.Name, \"refs/pull/\") && strings.IndexByte(ref.Name[10:], '/') > -1 {\n\t\treturn ref.Name[10 : strings.IndexByte(ref.Name[10:], '/')+10]\n\t}\n\n\treturn ref.Name\n}"} {"input": "package graphite\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n)\n\n\n\nfunc ExampleClient_FindMetrics() {\n\tts := createFindMetricsTestServer()\n\tdefer ts.Close()\n\n\tclient, _ := NewFromString(ts.URL)\n\tres, _ := client.FindMetrics(\n\t\tFindMetricRequest{\n\t\t\tQuery: \"cluster.*\",\n\t\t},\n\t)\n\tfmt.Printf(\"%+v\", res)\n\n}\n\nfunc createExpandMetricsTestServer() *httptest.Server {\n\treturn httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, \"{\\\"results\\\": [\\\"cluster.one\\\", \\\"cluster.two\\\"]}\")\n\t}))\n}\n\nfunc ExampleClient_ExpandMetrics() {\n\tts := createExpandMetricsTestServer()\n\tdefer ts.Close()\n\n\tclient, _ := NewFromString(ts.URL)\n\tres, _ := client.ExpandMetrics(\n\t\tExpandMetricRequest{\n\t\t\tQuery: \"cluster.*\",\n\t\t},\n\t)\n\tfmt.Printf(\"%+v\", res)\n}\n\nfunc createFindMetricsTestServer() *httptest.Server ", "output": "{\n\treturn httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, `[\n\t\t\t{\"text\": \"one\", \"expandable\": 1, \"leaf\": 0, \"id\": \"cluster.one\", \"allowChildren\": 1},\n\t\t\t{\"text\": \"two\", \"expandable\": 1, \"leaf\": 0, \"id\": \"cluster.two\", \"allowChildren\": 1}]`)\n\t}))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Cpu struct {\n\tSeconds time.Duration \n}\n\n\n\nfunc fact(n int) int {\n\tif n == 0 {\n\t\treturn 1\n\t}\n\treturn n * fact(n-1)\n}\n\nfunc (c Cpu) act(dng *danger) error {\n\n\tncpus := runtime.GOMAXPROCS(-1)\n\tngos := 4 * ncpus\n\n\tdone := make(chan struct{})\n\tdefer close(done)\n\n\tburner := func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tfor j := 0; j < 100000; j++ {\n\t\t\t\t\tfor i := range []int{1, 2, 3, 4, 5, 6, 7, 8} {\n\t\t\t\t\t\tfact(i)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := 0; i < ngos; i++ {\n\t\tgo burner()\n\t}\n\n\ttime.Sleep(c.Seconds)\n\treturn nil\n}\n\nfunc newCpu(p Packet) (Action, error) ", "output": "{\n\tc := Cpu{}\n\n\tif p.Cmd != \"cpu\" {\n\t\treturn c, fmt.Errorf(\"wrong command for type MemUp\")\n\t}\n\n\ti, err := strconv.Atoi(p.Arg)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\n\tif i < 1 {\n\t\treturn c, fmt.Errorf(\"cpu seconds argument must be greater than 0\")\n\t}\n\n\tc.Seconds = time.Duration(i) * time.Second\n\n\treturn c, nil\n}"} {"input": "package geddit\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\ntype Submission struct {\n\tAuthor string `json:\"author\"`\n\tTitle string `json:\"title\"`\n\tURL string `json:\"url\"`\n\tDomain string `json:\"domain\"`\n\tSubreddit string `json:\"subreddit\"`\n\tSubredditID string `json:\"subreddit_id\"`\n\tFullID string `json:\"name\"`\n\tID string `json:\"id\"`\n\tPermalink string `json:\"permalink\"`\n\tSelftext string `json:\"selftext\"`\n\tThumbnailURL string `json:\"thumbnail\"`\n\tDateCreated float64 `json:\"created_utc\"`\n\tNumComments int `json:\"num_comments\"`\n\tScore int `json:\"score\"`\n\tUps int `json:\"ups\"`\n\tDowns int `json:\"downs\"`\n\tIsNSFW bool `json:\"over_18\"`\n\tIsSelf bool `json:\"is_self\"`\n\tWasClicked bool `json:\"clicked\"`\n\tIsSaved bool `json:\"saved\"`\n\tBannedBy *string `json:\"banned_by\"`\n}\n\nfunc (h Submission) voteID() string { return h.FullID }\nfunc (h Submission) deleteID() string { return h.FullID }\nfunc (h Submission) replyID() string { return h.FullID }\n\n\nfunc (h *Submission) FullPermalink() string {\n\treturn \"https://reddit.com\" + h.Permalink\n}\n\n\n\n\nfunc (h *Submission) String() string ", "output": "{\n\tplural := \"\"\n\tif h.NumComments != 1 {\n\t\tplural = \"s\"\n\t}\n\tcomments := fmt.Sprintf(\"%d comment%s\", h.NumComments, plural)\n\treturn fmt.Sprintf(\"%d - %s (%s)\", h.Score, h.Title, comments)\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype CreateBootVolumeRequest struct {\n\n\tCreateBootVolumeDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request CreateBootVolumeRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request CreateBootVolumeRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateBootVolumeResponse struct {\n\n\tRawResponse *http.Response\n\n\tBootVolume `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateBootVolumeResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateBootVolumeResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateBootVolumeRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package maker\n\nimport \"cf/models\"\n\nvar routeSummaryGuid func() string\n\nfunc init() {\n\trouteSummaryGuid = guidGenerator(\"route-summary\")\n}\n\n\n\nfunc NewRouteSummary(overrides Overrides) (routeSummary models.RouteSummary) ", "output": "{\n\trouteSummary.Guid = routeSummaryGuid()\n\trouteSummary.Host = \"route-host\"\n\n\tif overrides.Has(\"guid\") {\n\t\trouteSummary.Guid = overrides.Get(\"guid\").(string)\n\t}\n\n\tif overrides.Has(\"host\") {\n\t\trouteSummary.Host = overrides.Get(\"host\").(string)\n\t}\n\n\treturn\n}"} {"input": "package apihelper\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\n\t\"github.com/mediocregopher/mediocre-api/common\"\n\t\"github.com/mediocregopher/mediocre-api/pickyjson\"\n)\n\n\n\n\nfunc ErrUnlessMethod(\n\tw http.ResponseWriter, r *http.Request, methods ...string,\n) bool {\n\tfor i := range methods {\n\t\tif r.Method == methods[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\thttp.Error(w, \"invalid method\", 400)\n\treturn false\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc JSONSuccess(w io.Writer, i interface{}) {\n\tjson.NewEncoder(w).Encode(i)\n\tfmt.Fprintf(w, \"\\n\")\n}\n\nfunc Prepare(\n\tw http.ResponseWriter, r *http.Request, params interface{},\n\tbodySizeLimit int64,\n) bool ", "output": "{\n\tr.Body = http.MaxBytesReader(w, r.Body, bodySizeLimit)\n\tif params != nil {\n\t\tif err := json.NewDecoder(r.Body).Decode(params); err != nil {\n\t\t\thttp.Error(w, err.Error(), 400)\n\t\t\treturn false\n\t\t}\n\t\tif err := pickyjson.CheckRequired(params); err != nil {\n\t\t\tcommon.HTTPError(w, r, err)\n\t\t\treturn false\n\t\t}\n\t\tif err := pickyjson.CheckRequired(¶ms); err != nil {\n\t\t\tcommon.HTTPError(w, r, err)\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}"} {"input": "package imagick\n\n\nimport \"C\"\nimport (\n\t\"runtime\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\nvar (\n\tinitOnce sync.Once\n\tterminateOnce *sync.Once\n\n\tcanTerminate = make(chan struct{}, 1)\n\n\tenvSemaphore = make(chan struct{}, 1)\n\n\tmagickWandCounter int64\n\tdrawingWandCounter int64\n\tpixelIteratorCounter int64\n\tpixelWandCounter int64\n)\n\n\nfunc Initialize() {\n\tenvSemaphore <- struct{}{}\n\tdefer func() {\n\t\t<-envSemaphore\n\t}()\n\n\tinitOnce.Do(func() {\n\t\tC.MagickWandGenesis()\n\t\tterminateOnce = &sync.Once{}\n\t\tsetCanTerminate()\n\t})\n}\n\n\n\nfunc Terminate() {\n\tenvSemaphore <- struct{}{}\n\tdefer func() {\n\t\t<-envSemaphore\n\t}()\n\n\tif terminateOnce != nil {\n\t\tterminateOnce.Do(func() {\n\t\t\truntime.GC()\n\t\t\tterminate()\n\t\t})\n\t}\n}\n\n\n\nfunc terminate() {\n\t<-canTerminate\n\tC.MagickWandTerminus()\n\tinitOnce = sync.Once{}\n}\n\n\nfunc setCanTerminate() {\n\tif isImageMagickCleaned() {\n\t\tselect {\n\t\tcase canTerminate <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n}\n\n\n\n\n\nfunc isImageMagickCleaned() bool {\n\tif atomic.LoadInt64(&magickWandCounter) != 0 || atomic.LoadInt64(&drawingWandCounter) != 0 || atomic.LoadInt64(&pixelIteratorCounter) != 0 || atomic.LoadInt64(&pixelWandCounter) != 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc unsetCanTerminate() ", "output": "{\n\tselect {\n\tcase <-canTerminate:\n\tdefault:\n\t}\n}"} {"input": "package calendar\n\nimport (\n\t\"time\"\n)\n\nvar (\n\tentries = make(map[int]Entry)\n\tindex int\n)\n\ntype Entry struct {\n\tID int\n\tTitle string\n\tStarts time.Time\n\tFinishes time.Time\n}\n\nfunc (e Entry) Duration() time.Duration {\n\treturn e.Finishes.Sub(e.Starts)\n}\n\nfunc Lookup(id int) (Entry, bool) {\n\te, isPresent := entries[id]\n\treturn e, isPresent\n}\n\nfunc Add(e Entry) Entry {\n\tindex++\n\te.ID = index\n\tUpdate(e)\n\treturn e\n}\n\nfunc Update(e Entry) {\n\tentries[e.ID] = e\n}\n\nfunc Remove(id int) {\n\tdelete(entries, id)\n}\n\nfunc Count() int {\n\treturn len(entries)\n}\n\n\n\nfunc All() []Entry ", "output": "{\n\tall := []Entry{}\n\tfor _, e := range entries {\n\t\tall = append(all, e)\n\t}\n\treturn all\n}"} {"input": "package swagger\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n)\n\nfunc (prop *ModelProperty) setDescription(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"description\"); tag != \"\" {\n\t\tprop.Description = tag\n\t}\n}\n\nfunc (prop *ModelProperty) setDefaultValue(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"default\"); tag != \"\" {\n\t\tprop.DefaultValue = Special(tag)\n\t}\n}\n\n\n\nfunc (prop *ModelProperty) setMaximum(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"maximum\"); tag != \"\" {\n\t\tprop.Maximum = tag\n\t}\n}\n\nfunc (prop *ModelProperty) setMinimum(field reflect.StructField) {\n\tif tag := field.Tag.Get(\"minimum\"); tag != \"\" {\n\t\tprop.Minimum = tag\n\t}\n}\n\nfunc (prop *ModelProperty) setUniqueItems(field reflect.StructField) {\n\ttag := field.Tag.Get(\"unique\")\n\tswitch tag {\n\tcase \"true\":\n\t\tv := true\n\t\tprop.UniqueItems = &v\n\tcase \"false\":\n\t\tv := false\n\t\tprop.UniqueItems = &v\n\t}\n}\n\nfunc (prop *ModelProperty) setPropertyMetadata(field reflect.StructField) {\n\tprop.setDescription(field)\n\tprop.setEnumValues(field)\n\tprop.setMinimum(field)\n\tprop.setMaximum(field)\n\tprop.setUniqueItems(field)\n\tprop.setDefaultValue(field)\n}\n\nfunc (prop *ModelProperty) setEnumValues(field reflect.StructField) ", "output": "{\n\tif tag := field.Tag.Get(\"enum\"); tag != \"\" {\n\t\tprop.Enum = strings.Split(tag, \"|\")\n\t}\n}"} {"input": "package protobuf\n\nimport \"github.com/m3db/m3x/pool\"\n\nconst (\n\tdefaultInitBufferSize = 2880\n\n\tdefaultMaxUnaggregatedMessageSize = 50 * 1024 * 1024\n)\n\n\ntype UnaggregatedOptions interface {\n\tSetBytesPool(value pool.BytesPool) UnaggregatedOptions\n\n\tBytesPool() pool.BytesPool\n\n\tSetInitBufferSize(value int) UnaggregatedOptions\n\n\tInitBufferSize() int\n\n\tSetMaxMessageSize(value int) UnaggregatedOptions\n\n\tMaxMessageSize() int\n}\n\ntype unaggregatedOptions struct {\n\tbytesPool pool.BytesPool\n\tinitBufferSize int\n\tmaxMessageSize int\n}\n\n\nfunc NewUnaggregatedOptions() UnaggregatedOptions {\n\tp := pool.NewBytesPool(nil, nil)\n\tp.Init()\n\treturn &unaggregatedOptions{\n\t\tbytesPool: p,\n\t\tinitBufferSize: defaultInitBufferSize,\n\t\tmaxMessageSize: defaultMaxUnaggregatedMessageSize,\n\t}\n}\n\n\n\nfunc (o *unaggregatedOptions) BytesPool() pool.BytesPool {\n\treturn o.bytesPool\n}\n\nfunc (o *unaggregatedOptions) SetInitBufferSize(value int) UnaggregatedOptions {\n\topts := *o\n\topts.initBufferSize = value\n\treturn &opts\n}\n\nfunc (o *unaggregatedOptions) InitBufferSize() int {\n\treturn o.initBufferSize\n}\n\nfunc (o *unaggregatedOptions) SetMaxMessageSize(value int) UnaggregatedOptions {\n\topts := *o\n\topts.maxMessageSize = value\n\treturn &opts\n}\n\nfunc (o *unaggregatedOptions) MaxMessageSize() int {\n\treturn o.maxMessageSize\n}\n\nfunc (o *unaggregatedOptions) SetBytesPool(value pool.BytesPool) UnaggregatedOptions ", "output": "{\n\topts := *o\n\topts.bytesPool = value\n\treturn &opts\n}"} {"input": "package instructions\n\nimport \"github.com/zxh0/jvm.go/jvmgo/jvm/rtda\"\n\n\ntype astore struct{ Index8Instruction }\n\nfunc (self *astore) Execute(frame *rtda.Frame) {\n\t_astore(frame, uint(self.index))\n}\n\ntype astore_0 struct{ NoOperandsInstruction }\n\nfunc (self *astore_0) Execute(frame *rtda.Frame) {\n\t_astore(frame, 0)\n}\n\ntype astore_1 struct{ NoOperandsInstruction }\n\nfunc (self *astore_1) Execute(frame *rtda.Frame) {\n\t_astore(frame, 1)\n}\n\ntype astore_2 struct{ NoOperandsInstruction }\n\nfunc (self *astore_2) Execute(frame *rtda.Frame) {\n\t_astore(frame, 2)\n}\n\ntype astore_3 struct{ NoOperandsInstruction }\n\nfunc (self *astore_3) Execute(frame *rtda.Frame) {\n\t_astore(frame, 3)\n}\n\n\n\nfunc _astore(frame *rtda.Frame, index uint) ", "output": "{\n\tref := frame.OperandStack().PopRef()\n\tframe.LocalVars().SetRef(index, ref)\n}"} {"input": "package nogo\n\n\ntype Permission int\n\n\ntype Principal interface {\n\tGetId() string\n\tGetSid() string\n\tGetRoleNames() []string\n}\n\n\ntype Role interface {\n\tGetName() string\n\tIsAdmin() bool\n\tHasPermission(permission Permission) (bool, error)\n}\n\n\nfunc NewRole(name string, mask Permission) Role {\n\treturn &defaultRole{RoleName: name, PermissionMask: mask, Admin: false}\n}\n\n\nfunc NewAdminRole(name string, mask Permission) Role {\n\treturn &defaultRole{RoleName: name, PermissionMask: mask, Admin: true}\n}\n\ntype defaultRole struct {\n\tRoleName string `db:\"role_name\"`\n\tPermissionMask Permission `db:\"permission_mask\"`\n\tAdmin bool `db:\"is_admin\"`\n}\n\n\n\nfunc (this *defaultRole) IsAdmin() bool {\n\treturn this.Admin\n}\n\nfunc (this *defaultRole) HasPermission(permission Permission) (bool, error) {\n\tval := (this.PermissionMask&permission != 0)\n\treturn val, nil\n}\n\nfunc (this *defaultRole) GetName() string ", "output": "{\n\treturn this.RoleName\n}"} {"input": "package textanalytics\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/cognitiveservices/v2.0/textanalytics\"\n\ntype BaseClient = original.BaseClient\ntype AzureRegions = original.AzureRegions\n\nconst (\n\tAustraliaeast AzureRegions = original.Australiaeast\n\tBrazilsouth AzureRegions = original.Brazilsouth\n\tEastasia AzureRegions = original.Eastasia\n\tEastus AzureRegions = original.Eastus\n\tEastus2 AzureRegions = original.Eastus2\n\tNortheurope AzureRegions = original.Northeurope\n\tSouthcentralus AzureRegions = original.Southcentralus\n\tSoutheastasia AzureRegions = original.Southeastasia\n\tWestcentralus AzureRegions = original.Westcentralus\n\tWesteurope AzureRegions = original.Westeurope\n\tWestus AzureRegions = original.Westus\n\tWestus2 AzureRegions = original.Westus2\n)\n\ntype BatchInput = original.BatchInput\ntype DetectedLanguage = original.DetectedLanguage\ntype ErrorRecord = original.ErrorRecord\ntype ErrorResponse = original.ErrorResponse\ntype Input = original.Input\ntype InternalError = original.InternalError\ntype KeyPhraseBatchResult = original.KeyPhraseBatchResult\ntype KeyPhraseBatchResultItem = original.KeyPhraseBatchResultItem\ntype LanguageBatchResult = original.LanguageBatchResult\ntype LanguageBatchResultItem = original.LanguageBatchResultItem\ntype MultiLanguageBatchInput = original.MultiLanguageBatchInput\ntype MultiLanguageInput = original.MultiLanguageInput\ntype SentimentBatchResult = original.SentimentBatchResult\ntype SentimentBatchResultItem = original.SentimentBatchResultItem\n\nfunc New(azureRegion AzureRegions) BaseClient {\n\treturn original.New(azureRegion)\n}\nfunc NewWithoutDefaults(azureRegion AzureRegions) BaseClient {\n\treturn original.NewWithoutDefaults(azureRegion)\n}\n\nfunc Version() string {\n\treturn original.Version()\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn original.UserAgent() + \" profiles/latest\"\n}"} {"input": "package main\n\nimport (\n\t\"emersyx.net/emersyx/api\"\n\t\"github.com/BurntSushi/toml\"\n\tgoirc \"github.com/fluffle/goirc/client\"\n)\n\n\n\ntype ircGateway struct {\n\tapi.PeripheralBase\n\tapi *goirc.Conn\n\tconfig *goirc.Config\n\tmessages chan api.Event\n}\n\n\nfunc NewPeripheral(opts api.PeripheralOptions) (api.Peripheral, error) {\n\tvar err error\n\n\tgw := new(ircGateway)\n\tgw.InitializeBase(opts)\n\n\tgw.messages = make(chan api.Event)\n\n\tgw.config = goirc.NewConfig(\"placeholder\")\n\n\tgw.config.Me.Ident = \"emersyx\"\n\tgw.config.Me.Name = \"emersyx\"\n\tgw.config.Version = \"emersyx\"\n\tgw.config.SSL = false\n\tgw.config.QuitMessage = \"bye\"\n\n\tgw.config.NewNick = func(n string) string { return n + \"^\" }\n\n\tconfig := new(ircGatewayConfig)\n\tif _, err = toml.DecodeFile(opts.ConfigPath, config); err != nil {\n\t\treturn nil, err\n\t}\n\tif err = config.validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tconfig.apply(gw)\n\n\tgw.api = goirc.Client(gw.config)\n\n\tgw.initCallbacks()\n\n\tgw.connect()\n\n\treturn gw, nil\n}\n\n\n\n\nfunc (gw *ircGateway) initCallbacks() ", "output": "{\n\tgw.api.HandleFunc(goirc.PRIVMSG, channelCallback(gw))\n\tgw.api.HandleFunc(goirc.JOIN, channelCallback(gw))\n\tgw.api.HandleFunc(goirc.QUIT, channelCallback(gw))\n\tgw.api.HandleFunc(goirc.PART, channelCallback(gw))\n}"} {"input": "package client \n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/docker/docker/errdefs\"\n\t\"gotest.tools/assert\"\n\tis \"gotest.tools/assert/cmp\"\n)\n\n\n\nfunc TestSecretRemoveError(t *testing.T) {\n\tclient := &Client{\n\t\tversion: \"1.25\",\n\t\tclient: newMockClient(errorMock(http.StatusInternalServerError, \"Server error\")),\n\t}\n\n\terr := client.SecretRemove(context.Background(), \"secret_id\")\n\tif !errdefs.IsSystem(err) {\n\t\tt.Fatalf(\"expected a Server Error, got %[1]T: %[1]v\", err)\n\t}\n}\n\nfunc TestSecretRemove(t *testing.T) {\n\texpectedURL := \"/v1.25/secrets/secret_id\"\n\n\tclient := &Client{\n\t\tversion: \"1.25\",\n\t\tclient: newMockClient(func(req *http.Request) (*http.Response, error) {\n\t\t\tif !strings.HasPrefix(req.URL.Path, expectedURL) {\n\t\t\t\treturn nil, fmt.Errorf(\"Expected URL '%s', got '%s'\", expectedURL, req.URL)\n\t\t\t}\n\t\t\tif req.Method != http.MethodDelete {\n\t\t\t\treturn nil, fmt.Errorf(\"expected DELETE method, got %s\", req.Method)\n\t\t\t}\n\t\t\treturn &http.Response{\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tBody: ioutil.NopCloser(bytes.NewReader([]byte(\"body\"))),\n\t\t\t}, nil\n\t\t}),\n\t}\n\n\terr := client.SecretRemove(context.Background(), \"secret_id\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestSecretRemoveUnsupported(t *testing.T) ", "output": "{\n\tclient := &Client{\n\t\tversion: \"1.24\",\n\t\tclient: &http.Client{},\n\t}\n\terr := client.SecretRemove(context.Background(), \"secret_id\")\n\tassert.Check(t, is.Error(err, `\"secret remove\" requires API version 1.25, but the Docker daemon API version is 1.24`))\n}"} {"input": "package cmd\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/subcommands\"\n\t\"gvisor.dev/gvisor/runsc/config\"\n\t\"gvisor.dev/gvisor/runsc/container\"\n\t\"gvisor.dev/gvisor/runsc/flag\"\n\t\"gvisor.dev/gvisor/runsc/specutils\"\n)\n\n\ntype Start struct{}\n\n\nfunc (*Start) Name() string {\n\treturn \"start\"\n}\n\n\n\n\n\nfunc (*Start) Usage() string {\n\treturn `start - start a secure container.`\n}\n\n\nfunc (*Start) SetFlags(*flag.FlagSet) {}\n\n\nfunc (*Start) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {\n\tif f.NArg() != 1 {\n\t\tf.Usage()\n\t\treturn subcommands.ExitUsageError\n\t}\n\n\tid := f.Arg(0)\n\tconf := args[0].(*config.Config)\n\n\tc, err := container.Load(conf.RootDir, container.FullID{ContainerID: id}, container.LoadOpts{})\n\tif err != nil {\n\t\tFatalf(\"loading container: %v\", err)\n\t}\n\tif _, err := specutils.ReadSpec(c.BundleDir, conf); err != nil {\n\t\tFatalf(\"reading spec: %v\", err)\n\t}\n\n\tif err := c.Start(conf); err != nil {\n\t\tFatalf(\"starting container: %v\", err)\n\t}\n\treturn subcommands.ExitSuccess\n}\n\nfunc (*Start) Synopsis() string ", "output": "{\n\treturn \"start a secure container\"\n}"} {"input": "package router\n\ntype sortedRoutes struct {\n\troutes Routes\n}\n\nfunc (s sortedRoutes) Len() int {\n\treturn len(s.routes.Routes)\n}\n\n\n\nfunc (s sortedRoutes) Swap(i, j int) {\n\ts.routes.Routes[i], s.routes.Routes[j] = s.routes.Routes[j], s.routes.Routes[i]\n}\n\nfunc (s sortedRoutes) Less(i, j int) bool ", "output": "{\n\treturn s.routes.Routes[i].Priority < s.routes.Routes[j].Priority\n}"} {"input": "package cli\n\n\ntype Command struct {\n\tName string\n\tDescription string\n\tAction Action\n}\n\n\ntype Commands []*Command\n\n\n\n\n\nfunc (c Commands) Less(i, j int) bool {\n\treturn c[i].Name < c[j].Name\n}\n\n\nfunc (c Commands) Swap(i, j int) {\n\tc[i], c[j] = c[j], c[i]\n}\n\nfunc (c Commands) ActionForName(name string) Action {\n\tfor _, command := range c {\n\t\tif name == command.Name {\n\t\t\treturn command.Action\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c Commands) Len() int ", "output": "{\n\treturn len(c)\n}"} {"input": "package client\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/thecodeteam/rexray/libstorage/api/types\"\n)\n\n\ntype client struct {\n\thttp.Client\n\thost string\n\tlogRequests bool\n\tlogResponses bool\n\tserverName string\n}\n\n\nfunc New(host string, transport *http.Transport) types.APIClient {\n\treturn &client{\n\t\tClient: http.Client{\n\t\t\tTransport: transport,\n\t\t},\n\t\thost: host,\n\t}\n}\n\n\n\nfunc (c *client) LogRequests(enabled bool) {\n\tc.logRequests = enabled\n}\n\nfunc (c *client) LogResponses(enabled bool) {\n\tc.logResponses = enabled\n}\n\nfunc (c *client) ServerName() string ", "output": "{\n\treturn c.serverName\n}"} {"input": "package delete\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewDeleteNodesIdentifierParams() *DeleteNodesIdentifierParams {\n\tvar ()\n\treturn &DeleteNodesIdentifierParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\nfunc NewDeleteNodesIdentifierParamsWithTimeout(timeout time.Duration) *DeleteNodesIdentifierParams {\n\tvar ()\n\treturn &DeleteNodesIdentifierParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype DeleteNodesIdentifierParams struct {\n\n\tIdentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *DeleteNodesIdentifierParams) WithIdentifier(identifier string) *DeleteNodesIdentifierParams {\n\to.Identifier = identifier\n\treturn o\n}\n\n\n\n\nfunc (o *DeleteNodesIdentifierParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error ", "output": "{\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"identifier\", o.Identifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package api\n\nimport (\n\t\"log\"\n\t\"net/http\"\n)\n\ntype HttpsRedirectingFileHandler interface {\n\thttp.Handler\n\tfileHandler() http.Handler\n}\n\ntype httpsHandler struct {\n\tinternalHandler http.Handler\n}\n\nfunc NewHttpsRedirectFileHandler(dir http.Dir) HttpsRedirectingFileHandler {\n\thandler := &httpsHandler{}\n\thandler.internalHandler = http.FileServer(dir)\n\treturn handler\n}\n\nfunc redirect(w http.ResponseWriter, req *http.Request) {\n\ttarget := \"https://\" + req.Host + req.URL.Path\n\tif len(req.URL.RawQuery) > 0 {\n\t\ttarget += \"?\" + req.URL.RawQuery\n\t}\n\tlog.Printf(\"redirect to: %s\", target)\n\thttp.Redirect(w, req, target,\n\t\thttp.StatusTemporaryRedirect)\n}\n\nfunc isXForwardedHTTPS(request *http.Request) bool {\n\txForwardedProto := request.Header.Get(\"X-Forwarded-Proto\")\n\n\treturn len(xForwardedProto) > 0 && xForwardedProto == \"https\"\n}\n\n\n\nfunc (h *httpsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tif !isXForwardedHTTPS(req) {\n\t\tredirect(w, req)\n\t} else {\n\t\th.fileHandler().ServeHTTP(w, req)\n\t}\n}\n\nfunc (h *httpsHandler) fileHandler() http.Handler ", "output": "{\n\treturn h.internalHandler\n}"} {"input": "package types\n\nimport (\n\t\"database/sql/driver\"\n\t\"encoding/json\"\n\t\"errors\"\n)\n\n\n\n\ntype JSON json.RawMessage\n\n\nfunc (j JSON) String() string {\n\treturn string(j)\n}\n\n\n\n\n\nfunc (j *JSON) Marshal(obj interface{}) error {\n\tres, err := json.Marshal(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*j = res\n\treturn nil\n}\n\n\nfunc (j *JSON) UnmarshalJSON(data []byte) error {\n\tif j == nil {\n\t\treturn errors.New(\"json: unmarshal json on nil pointer to json\")\n\t}\n\n\t*j = append((*j)[0:0], data...)\n\treturn nil\n}\n\n\nfunc (j JSON) MarshalJSON() ([]byte, error) {\n\treturn j, nil\n}\n\n\n\nfunc (j JSON) Value() (driver.Value, error) {\n\tvar r json.RawMessage\n\tif err := j.Unmarshal(&r); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn []byte(r), nil\n}\n\n\nfunc (j *JSON) Scan(src interface{}) error {\n\tvar source []byte\n\n\tswitch src.(type) {\n\tcase string:\n\t\tsource = []byte(src.(string))\n\tcase []byte:\n\t\tsource = src.([]byte)\n\tdefault:\n\t\treturn errors.New(\"incompatible type for json\")\n\t}\n\n\t*j = JSON(append((*j)[0:0], source...))\n\n\treturn nil\n}\n\nfunc (j JSON) Unmarshal(dest interface{}) error ", "output": "{\n\treturn json.Unmarshal(j, dest)\n}"} {"input": "package apiv1\n\nimport (\n\t\"encoding/json\"\n)\n\ntype DiskHint struct {\n\tval interface{}\n}\n\nvar _ json.Unmarshaler = &DiskHint{}\nvar _ json.Marshaler = DiskHint{}\n\nfunc NewDiskHintFromString(val string) DiskHint {\n\treturn DiskHint{val}\n}\n\nfunc NewDiskHintFromMap(val map[string]interface{}) DiskHint {\n\treturn DiskHint{val}\n}\n\n\n\nfunc (i DiskHint) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(i.val)\n}\n\nfunc (i *DiskHint) UnmarshalJSON(data []byte) error ", "output": "{\n\tvar val interface{}\n\n\terr := json.Unmarshal(data, &val)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*i = DiskHint{val}\n\n\treturn nil\n}"} {"input": "package factories\n\nimport (\n\t\"testing\"\n\n\t\"gotest.tools/v3/assert\"\n\t\"k8s.io/client-go/rest\"\n)\n\n\n\nfunc TestCreateKafkaSourceParams(t *testing.T) {\n\tfactory := NewFakeKafkaSourceFactory(\"fake-namespace\")\n\n\tsourceParams := factory.CreateKafkaSourceParams()\n\tassert.Assert(t, sourceParams != nil)\n\tassert.Equal(t, factory.KafkaSourceParams(), sourceParams)\n}\n\nfunc TestCreateKafkaSourceClient(t *testing.T) {\n\tfactory := NewFakeKafkaSourceFactory(\"fake-namespace\")\n\tclient, _ := factory.CreateKafkaSourceClient(&rest.Config{}, \"fake-namespace\")\n\n\tassert.Assert(t, client != nil)\n\tassert.Equal(t, factory.KafkaSourceClient(), client)\n\tassert.Equal(t, factory.CreateKnSourceClient(&rest.Config{}, \"fake-namespace\"), client)\n\tassert.Equal(t, client.Namespace(), \"fake-namespace\")\n}\n\nfunc TestNewKafkaSourceFactory(t *testing.T) ", "output": "{\n\tfactory := NewFakeKafkaSourceFactory(\"fake-namespace\")\n\n\tassert.Assert(t, factory != nil)\n}"} {"input": "package graph\n\ntype vertexDistance struct {\n\tvertex string\n\tdistance float64\n}\n\n\n\n\ntype vertexDistanceHeap []vertexDistance\n\nfunc (h vertexDistanceHeap) Len() int { return len(h) }\nfunc (h vertexDistanceHeap) Less(i, j int) bool { return h[i].distance < h[j].distance } \nfunc (h vertexDistanceHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }\n\n\n\nfunc (h *vertexDistanceHeap) Pop() interface{} {\n\theapSize := len(*h)\n\tlastVertex := (*h)[heapSize-1]\n\t*h = (*h)[0 : heapSize-1]\n\treturn lastVertex\n}\n\nfunc (h *vertexDistanceHeap) updateDistance(vtx string, val float64) {\n\tfor i := 0; i < len(*h); i++ {\n\t\tif (*h)[i].vertex == vtx {\n\t\t\t(*h)[i].distance = val\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (h *vertexDistanceHeap) Push(x interface{}) ", "output": "{\n\t*h = append(*h, x.(vertexDistance))\n}"} {"input": "package models\n\nimport (\n\t\"time\"\n)\n\n\nconst (\n\tVolumePaper = \"paperbook\"\n\tVolumeElectro = \"ebook\"\n\tVolumeAudio = \"audiobook\"\n)\n\n\nfunc GetVolumes() []string {\n\tvolumes := []string{VolumeAudio, VolumeElectro, VolumePaper}\n\treturn volumes\n}\n\n\n\n\n\n\n\n\ntype Volume struct {\n\tID int32 `reform:\"id,pk\"`\n\tBookID int32 `reform:\"book_id\"`\n\tType string `reform:\"type\"`\n\tCreatedAt time.Time `reform:\"created_at\"`\n\tUpdatedAt time.Time `reform:\"updated_at\"`\n}\n\n\nfunc (v *Volume) BeforeInsert() error {\n\tv.CreatedAt = time.Now().UTC().Truncate(time.Second)\n\tv.UpdatedAt = v.CreatedAt\n\treturn nil\n}\n\n\nfunc (v *Volume) BeforeUpdate() error {\n\tv.UpdatedAt = time.Now().UTC().Truncate(time.Second)\n\treturn nil\n}\n\nfunc CheckVolume(volume string) bool ", "output": "{\n\tswitch volume {\n\tcase VolumePaper:\n\tcase VolumeElectro:\n\tcase VolumeAudio:\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package mountinfo\n\nimport \"strings\"\n\n\n\n\n\n\n\n\n\n\n\ntype FilterFunc func(*Info) (skip, stop bool)\n\n\n\n\n\n\n\n\nfunc PrefixFilter(prefix string) FilterFunc {\n\treturn func(m *Info) (bool, bool) {\n\t\tskip := !strings.HasPrefix(m.Mountpoint+\"/\", prefix+\"/\")\n\t\treturn skip, false\n\t}\n}\n\n\nfunc SingleEntryFilter(mp string) FilterFunc {\n\treturn func(m *Info) (bool, bool) {\n\t\tif m.Mountpoint == mp {\n\t\t\treturn false, true \n\t\t}\n\t\treturn true, false \n\t}\n}\n\n\n\n\n\n\n\n\n\nfunc FSTypeFilter(fstype ...string) FilterFunc {\n\treturn func(m *Info) (bool, bool) {\n\t\tfor _, t := range fstype {\n\t\t\tif m.FSType == t {\n\t\t\t\treturn false, false \n\t\t\t}\n\t\t}\n\t\treturn true, false \n\t}\n}\n\nfunc ParentsFilter(path string) FilterFunc ", "output": "{\n\treturn func(m *Info) (bool, bool) {\n\t\tskip := !strings.HasPrefix(path, m.Mountpoint)\n\t\treturn skip, false\n\t}\n}"} {"input": "package metrics\n\n\n\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\tgolangswaggerpaths \"path\"\n)\n\n\ntype GetMetricsURL struct {\n\t_basePath string\n}\n\n\n\n\nfunc (o *GetMetricsURL) WithBasePath(bp string) *GetMetricsURL {\n\to.SetBasePath(bp)\n\treturn o\n}\n\n\n\n\n\n\n\nfunc (o *GetMetricsURL) Build() (*url.URL, error) {\n\tvar result url.URL\n\n\tvar _path = \"/metrics/\"\n\n\t_basePath := o._basePath\n\tif _basePath == \"\" {\n\t\t_basePath = \"/v1\"\n\t}\n\tresult.Path = golangswaggerpaths.Join(_basePath, _path)\n\n\treturn &result, nil\n}\n\n\nfunc (o *GetMetricsURL) Must(u *url.URL, err error) *url.URL {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif u == nil {\n\t\tpanic(\"url can't be nil\")\n\t}\n\treturn u\n}\n\n\nfunc (o *GetMetricsURL) String() string {\n\treturn o.Must(o.Build()).String()\n}\n\n\nfunc (o *GetMetricsURL) BuildFull(scheme, host string) (*url.URL, error) {\n\tif scheme == \"\" {\n\t\treturn nil, errors.New(\"scheme is required for a full url on GetMetricsURL\")\n\t}\n\tif host == \"\" {\n\t\treturn nil, errors.New(\"host is required for a full url on GetMetricsURL\")\n\t}\n\n\tbase, err := o.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbase.Scheme = scheme\n\tbase.Host = host\n\treturn base, nil\n}\n\n\nfunc (o *GetMetricsURL) StringFull(scheme, host string) string {\n\treturn o.Must(o.BuildFull(scheme, host)).String()\n}\n\nfunc (o *GetMetricsURL) SetBasePath(bp string) ", "output": "{\n\to._basePath = bp\n}"} {"input": "package main\n\nimport (\n\t\"github.com/banerwai/gommon/crypto\"\n\t\"github.com/banerwai/micros/query/auth/service\"\n\t\"gopkg.in/mgo.v2/bson\"\n)\n\ntype inmemService struct {\n}\n\nfunc newInmemService() service.AuthService {\n\treturn &inmemService{}\n}\n\n\n\nfunc (ims *inmemService) Login(email string, pwd string) (r string) {\n\tvar _bsonM bson.M\n\terr := UsersCollection.Find(bson.M{\"email\": email}).One(&_bsonM)\n\n\tif err != nil {\n\t\treturn \"error:\" + err.Error()\n\t}\n\n\t_active := _bsonM[\"actived\"].(bool)\n\tif !_active {\n\t\treturn \"error: user email need active\"\n\t}\n\n\t_pwd := _bsonM[\"pwd\"].(string)\n\n\t_is := crypto.CompareHash([]byte(_pwd), pwd)\n\tif !_is {\n\t\treturn \"error: compare false\"\n\t}\n\n\t_data, _err := bson.Marshal(_bsonM)\n\tif _err != nil {\n\t\treturn \"error: bson.Marshal error\"\n\t}\n\n\tr = string(_data)\n\treturn\n}\n\nfunc (ims *inmemService) Ping() (r string) ", "output": "{\n\tr = \"pong\"\n\treturn\n}"} {"input": "package schedule\n\nimport (\n \"fmt\"\n\n \"github.com/headmade/backuper/hmutil\"\n)\n\n\n\nfunc (m *Manager) writeCrontab(schedule string, cmd string) error ", "output": "{\n taskFormat := `crontab -l\\\n | ( grep -v 'gobackuper %s' ; echo '%s %s %s gobackuper %s >> /var/log/gobackuper_cron.log 2>&1' )\\\n | crontab`\n task := fmt.Sprintf(taskFormat, cmd, schedule, CRON_PATH, CRON_GOTRACEBACK, cmd)\n _, err := hmutil.System(task)\n return err\n}"} {"input": "package balanced_brackets\n\nimport \"testing\"\n\nfunc TestStackBalanced(t *testing.T) {\n\n\tgot := Balance(\"{[]}()\")\n\n\twant := true\n\n\tif got != want {\n\n\t\tt.Errorf(\"Should be %v but is %v\", want, got)\n\n\t}\n\n}\n\nfunc TestStackUnbalanced(t *testing.T) {\n\n\tgot := Balance(\"{(])}\")\n\n\twant := false\n\n\tif got != want {\n\n\t\tt.Errorf(\"Should be %v but is %v\", want, got)\n\n\t}\n}\n\n\n\nfunc TestOpenStack(t *testing.T) ", "output": "{\n\n\tgot := Balance(\"(\")\n\n\twant := false\n\n\tif got != want {\n\n\t\tt.Errorf(\"Should be %v but is %v\", want, got)\n\n\t}\n}"} {"input": "package helper\n\nimport (\n\t\"encoding/base64\"\n\t\"strings\"\n\t\"time\"\n\t\"github.com/insionng/yougam/libraries/flosch/pongo2.v3\"\n)\n\n\n\nfunc ConvertToBase64ByPongo2(in *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(base64.StdEncoding.EncodeToString([]byte(in.String())))\n}\n\nfunc SplitByPongo2(in *pongo2.Value, splitor *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Split(in.String(), splitor.String()))\n}\n\nfunc MarkdownByPongo2(in *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Markdown(in.String()))\n}\n\nfunc CropwordByPongo2(in *pongo2.Value, start *pongo2.Value, length *pongo2.Value, symbol *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Substr(in.String(), start.Integer(), length.Integer(), symbol.String()))\n}\n\nfunc Cropword(in string, start int, length int, symbol string) string {\n\treturn Substr(in, start, length, symbol)\n}\n\nfunc File(s string) string {\n\tif len(s) > 0 {\n\t\tif strings.HasPrefix(s, \"http\") || strings.HasPrefix(s, \"/identicon\") {\n\t\t\treturn s\n\t\t} else {\n\t\t\treturn \"/file\" + s\n\t\t}\n\t}\n\treturn s\n}\n\nfunc Unix2TimeByPongo2(in *pongo2.Value, timeLayout *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(time.Unix(int64(in.Integer()), 0).Format(timeLayout.String()))\n}\n\nfunc ConvertToBase64(in string) string ", "output": "{\n\treturn base64.StdEncoding.EncodeToString([]byte(in))\n}"} {"input": "package factual\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestToken(t *testing.T) ", "output": "{\n\tfR := NewToken(\"Pbu7jRdBErgLW07g9c25JtGcwwt1KmpoxRTfFL3x\", \"vC4AgocPBhxe0GFkTsetoiuEAJEgqz6MCbAnXEoO\")\n\n\tnR, err := NewRead(fR, \"restaurants-us\")\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tnR.AddQuery(\"pizza\")\n\tnR.AddLimit(5)\n\tnR.AddSelect(\"factual_id\")\n\n\n\ts, err := nR.Get()\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tt.Error(err)\n\t}\n\n\tif strings.Contains(s, \"error\") {\n\t\tt.Error(\"response returned an error\")\n\t}\n\n\n}"} {"input": "package partner\nimport (\n \"go2o/src/core/domain/interface/sale\"\n \"bytes\"\n \"fmt\"\n)\n\n\n\nfunc getSaleTagsCheckBoxHtml(tags []*sale.ValueSaleTag) string ", "output": "{\n if len(tags) == 0 || tags== nil {\n return `
没有找到任何销售标签!
`\n }\n buf := bytes.NewBufferString(`
    `)\n for i, v := range tags {\n buf.WriteString(fmt.Sprintf(`
  • \n
  • `, i,i, v.Id, i, v.TagName))\n }\n buf.WriteString(\"
\")\n return buf.String()\n}"} {"input": "package internalversion\n\nimport (\n\tauthorization \"github.com/openshift/origin/pkg/authorization/apis/authorization\"\n\trest \"k8s.io/client-go/rest\"\n)\n\n\n\ntype SubjectRulesReviewsGetter interface {\n\tSubjectRulesReviews(namespace string) SubjectRulesReviewInterface\n}\n\n\ntype SubjectRulesReviewInterface interface {\n\tCreate(*authorization.SubjectRulesReview) (*authorization.SubjectRulesReview, error)\n\tSubjectRulesReviewExpansion\n}\n\n\ntype subjectRulesReviews struct {\n\tclient rest.Interface\n\tns string\n}\n\n\n\n\n\nfunc (c *subjectRulesReviews) Create(subjectRulesReview *authorization.SubjectRulesReview) (result *authorization.SubjectRulesReview, err error) {\n\tresult = &authorization.SubjectRulesReview{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"subjectrulesreviews\").\n\t\tBody(subjectRulesReview).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}\n\nfunc newSubjectRulesReviews(c *AuthorizationClient, namespace string) *subjectRulesReviews ", "output": "{\n\treturn &subjectRulesReviews{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}"} {"input": "package validator\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\nfunc IsNull(str string) bool {\n\treturn len(str) == 0\n}\n\nfunc IsWord(str string, params ...int) bool {\n\tif IsNull(str) {\n\t\treturn false\n\t}\n\treturn rxWord.MatchString(str)\n}\n\n\n\nfunc IsDate(str string, format ...string) bool {\n\n\tif len(format) == 0 {\n\n\t\tif len(strings.Split(str, \"/\")) > 1 {\n\t\t\treturn IsTime(str, \"2006/01/02\")\n\t\t}\n\n\t\tif len(strings.Split(str, \"-\")) > 1 {\n\t\t\treturn IsTime(str, \"2006-01-02\")\n\t\t}\n\n\t\treturn false\n\t}\n\n\treturn IsTime(str, format[0])\n}\n\nfunc IsEmpty(str string) bool {\n\treturn len(strings.TrimSpace(str)) == 0\n}\n\nfunc IsRequestURI(rawurl string) bool {\n\t_, err := url.ParseRequestURI(rawurl)\n\treturn err == nil\n}\n\nfunc IsURI(str string) bool {\n\trelation := false\n\tfor idx, val := range str {\n\t\tif val == '.' {\n\t\t\trelation = true\n\t\t\tcontinue\n\t\t}\n\t\tif val == '/' || val == '\\\\' {\n\t\t\tif idx < len(str)-1 {\n\t\t\t\tif str[idx+1] == '.' {\n\t\t\t\t\trelation = true\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif relation && (val != '/' && val != '\\\\') {\n\t\t\treturn false\n\t\t}\n\t\treturn IsRequestURI(str[idx:])\n\t}\n\treturn false\n}\n\nfunc IsMobilePhone(str string) bool {\n\tif IsEmpty(str) {\n\t\treturn false\n\t}\n\treturn rxMobolePhone.MatchString(str)\n}\n\nfunc IsTime(str string, format string) bool ", "output": "{\n\t_, err := time.Parse(format, str)\n\treturn err == nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\nconst (\n\tFileType_File = 1\n\tFileType_Directory = 2\n)\n\nfunc IfString(condition bool, trueVal, falseVal string) string {\n\tif condition {\n\t\treturn trueVal\n\t}\n\treturn falseVal\n}\n\n\n\n\nfunc ExpandString(s string, data map[string]string) string {\n\treturn os.Expand(s, func(p string) string {\n\t\tv, _ := data[p]\n\t\treturn v\n\t})\n}\n\n\nfunc CreateDir(dir string, mode os.FileMode) error {\n\t_, err := os.Stat(dir)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn os.MkdirAll(dir, mode)\n\t\t}\n\t}\n\treturn err\n}\n\nfunc CopyFile(src, dest string, mode os.FileMode) error {\n\tdata, err := ioutil.ReadFile(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(dest, data, mode)\n}\n\n\nfunc GetFileType(path string) (fileType int, err error) {\n\tvar fi os.FileInfo\n\n\tfi, err = os.Stat(path)\n\tif err == nil {\n\t\tfileType = IfInt(fi.IsDir(), FileType_Directory, FileType_File)\n\t} else if os.IsNotExist(err) {\n\t\terr = fmt.Errorf(\"can not find directory or file: %s\", path)\n\t}\n\treturn\n}\n\nfunc IfInt(condition bool, trueVal, falseVal int) int ", "output": "{\n\tif condition {\n\t\treturn trueVal\n\t}\n\treturn falseVal\n}"} {"input": "package tpl\n\nimport (\n\t\"html/template\"\n\t\"sync\"\n)\n\n\n\n\nfunc NewCachingContext(baseDir string, funcs template.FuncMap) Context {\n\treturn &cachingContext{\n\t\tbaseDir: baseDir,\n\t\tmut: new(sync.Mutex),\n\t\tcache: make(map[filesMapKey]*template.Template),\n\t\tfuncs: funcs,\n\t}\n}\n\ntype cachingContext struct {\n\tbaseDir string\n\tmut *sync.Mutex\n\tcache map[filesMapKey]*template.Template\n\tfuncs template.FuncMap\n}\n\n\n\nfunc (c *cachingContext) Prepare(tplFiles Files) (*template.Template, error) ", "output": "{\n\tc.mut.Lock()\n\tdefer c.mut.Unlock()\n\tmk := tplFiles.mapKey()\n\ttpl, ok := c.cache[mk]\n\tif !ok {\n\t\tabsPaths := tplFiles.absPaths(c.baseDir)\n\t\tt, err := template.New(tplFiles.First()).Funcs(c.funcs).ParseFiles(absPaths...)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttpl = t\n\t}\n\treturn tpl, nil\n}"} {"input": "package zip\n\nimport (\n\t\"archive/zip\"\n\t\"io\"\n\t\"os\"\n)\n\n\ntype Reader struct {\n\tzip.Reader\n\tunread []*zip.File\n\trc io.ReadCloser\n}\n\n\n\nfunc NewReader(r io.ReaderAt, size int64) (*Reader, error) {\n\tzr, err := zip.NewReader(r, size)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Reader{Reader: *zr}, nil\n}\n\n\nfunc (r *Reader) NextFile() (name string, err error) {\n\tif r.unread == nil {\n\t\tr.unread = r.Files()[:]\n\t}\n\n\tif r.rc != nil {\n\t\tr.rc.Close() \n\t}\n\n\tif len(r.unread) == 0 {\n\t\treturn \"\", io.EOF\n\t}\n\n\tf := r.unread[0]\n\tname, r.unread = f.Name, r.unread[1:]\n\tr.rc, err = f.Open()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn name, nil\n}\n\nfunc (r *Reader) Read(p []byte) (n int, err error) {\n\treturn r.rc.Read(p)\n}\n\n\nfunc (r *Reader) Files() []*zip.File {\n\treturn r.File\n}\n\n\ntype Writer struct {\n\tzip.Writer\n\tw io.Writer\n}\n\n\nfunc NewWriter(w io.Writer) *Writer {\n\treturn &Writer{Writer: *zip.NewWriter(w)}\n}\n\n\n\n\n\nfunc (w *Writer) Write(p []byte) (n int, err error) {\n\treturn w.w.Write(p)\n}\n\nfunc (w *Writer) NextFile(name string, fi os.FileInfo) error ", "output": "{\n\tif name == \"\" {\n\t\tname = fi.Name()\n\t}\n\thdr, err := zip.FileInfoHeader(fi)\n\tif err != nil {\n\t\treturn err\n\t}\n\thdr.Name = name\n\tw.w, err = w.CreateHeader(hdr)\n\treturn err\n}"} {"input": "package frame\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/go-git/go-git/v5/utils/merkletrie/noder\"\n)\n\n\n\ntype Frame struct {\n\tstack []noder.Noder\n}\n\ntype byName []noder.Noder\n\nfunc (a byName) Len() int { return len(a) }\nfunc (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a byName) Less(i, j int) bool {\n\treturn strings.Compare(a[i].Name(), a[j].Name()) < 0\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (f *Frame) String() string {\n\tvar buf bytes.Buffer\n\t_ = buf.WriteByte('[')\n\n\tsep := \"\"\n\tfor i := f.Len() - 1; i >= 0; i-- {\n\t\t_, _ = buf.WriteString(sep)\n\t\tsep = \", \"\n\t\t_, _ = buf.WriteString(fmt.Sprintf(\"%q\", f.stack[i].Name()))\n\t}\n\n\t_ = buf.WriteByte(']')\n\n\treturn buf.String()\n}\n\n\n\n\nfunc (f *Frame) First() (noder.Noder, bool) {\n\tif f.Len() == 0 {\n\t\treturn nil, false\n\t}\n\n\ttop := f.Len() - 1\n\n\treturn f.stack[top], true\n}\n\n\n\nfunc (f *Frame) Drop() {\n\tif f.Len() == 0 {\n\t\treturn\n\t}\n\n\ttop := f.Len() - 1\n\tf.stack[top] = nil\n\tf.stack = f.stack[:top]\n}\n\n\nfunc (f *Frame) Len() int {\n\treturn len(f.stack)\n}\n\nfunc New(n noder.Noder) (*Frame, error) ", "output": "{\n\tchildren, err := n.Children()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsort.Sort(sort.Reverse(byName(children)))\n\treturn &Frame{\n\t\tstack: children,\n\t}, nil\n}"} {"input": "package auth\n\nimport (\n\t\"github.com/Unknwon/macaron\"\n\t\"github.com/macaron-contrib/i18n\"\n\n\t\"github.com/gogits/gogs/modules/middleware/binding\"\n)\n\ntype AddSSHKeyForm struct {\n\tSSHTitle string `form:\"title\" binding:\"Required\"`\n\tContent string `form:\"content\" binding:\"Required\"`\n}\n\n\n\nfunc (f *AddSSHKeyForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) ", "output": "{\n\tvalidate(errs, ctx.Data, f, l)\n}"} {"input": "package common\n\nimport (\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/instance\"\n\t\"github.com/juju/juju/state\"\n\t\"github.com/juju/names\"\n)\n\n\n\ntype InstanceIdGetter struct {\n\tst state.EntityFinder\n\tgetCanRead GetAuthFunc\n}\n\n\n\n\nfunc NewInstanceIdGetter(st state.EntityFinder, getCanRead GetAuthFunc) *InstanceIdGetter {\n\treturn &InstanceIdGetter{\n\t\tst: st,\n\t\tgetCanRead: getCanRead,\n\t}\n}\n\nfunc (ig *InstanceIdGetter) getInstanceId(tag names.Tag) (instance.Id, error) {\n\tentity0, err := ig.st.FindEntity(tag)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tentity, ok := entity0.(state.InstanceIdGetter)\n\tif !ok {\n\t\treturn \"\", NotSupportedError(tag, \"instance id\")\n\t}\n\treturn entity.InstanceId()\n}\n\n\n\n\n\nfunc (ig *InstanceIdGetter) InstanceId(args params.Entities) (params.StringResults, error) ", "output": "{\n\tresult := params.StringResults{\n\t\tResults: make([]params.StringResult, len(args.Entities)),\n\t}\n\tcanRead, err := ig.getCanRead()\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tfor i, entity := range args.Entities {\n\t\ttag, err := names.ParseTag(entity.Tag)\n\t\tif err != nil {\n\t\t\tresult.Results[i].Error = ServerError(ErrPerm)\n\t\t\tcontinue\n\t\t}\n\t\terr = ErrPerm\n\t\tif canRead(tag) {\n\t\t\tvar instanceId instance.Id\n\t\t\tinstanceId, err = ig.getInstanceId(tag)\n\t\t\tif err == nil {\n\t\t\t\tresult.Results[i].Result = string(instanceId)\n\t\t\t}\n\t\t}\n\t\tresult.Results[i].Error = ServerError(err)\n\t}\n\treturn result, nil\n}"} {"input": "package quote\n\nimport (\n\t\"testing\"\n)\n\nfunc TestCodeQuote(t *testing.T) {\n\tresult := codeQuote()\n\tif len(result) == 0 {\n\t\tt.Errorf(\"No valid quote returned.\")\n\t}\n}\n\n\n\nfunc TestAdminQuote(t *testing.T) {\n\tresult := integrationQuote()\n\tif len(result) == 0 {\n\t\tt.Errorf(\"No valid integration quote returned.\")\n\t}\n}\n\nfunc TestIntegrationQuote(t *testing.T) ", "output": "{\n\tresult := integrationQuote()\n\tif len(result) == 0 {\n\t\tt.Errorf(\"No valid integration quote returned.\")\n\t}\n}"} {"input": "package dockerfile\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/docker/docker/pkg/system\"\n)\n\n\n\nfunc normaliseWorkdir(current string, requested string) (string, error) {\n\tif requested == \"\" {\n\t\treturn \"\", fmt.Errorf(\"cannot normalise nothing\")\n\t}\n\n\tcurrent = filepath.FromSlash(current)\n\trequested = filepath.FromSlash(requested)\n\n\tif len(current) == 0 || system.IsAbs(requested) {\n\t\tif (requested[0] == os.PathSeparator) ||\n\t\t\t(len(requested) > 1 && string(requested[1]) != \":\") ||\n\t\t\t(len(requested) == 1) {\n\t\t\trequested = filepath.Join(`C:\\`, requested)\n\t\t}\n\t} else {\n\t\trequested = filepath.Join(current, requested)\n\t}\n\treturn (strings.ToUpper(string(requested[0])) + requested[1:]), nil\n}\n\n\n\nfunc errNotJSON(command, original string) error ", "output": "{\n\textra := \"\"\n\toriginal = filepath.FromSlash(strings.ToLower(strings.Replace(strings.ToLower(original), strings.ToLower(command)+\" \", \"\", -1)))\n\tif len(regexp.MustCompile(`\"[a-z]:\\\\.*`).FindStringSubmatch(original)) > 0 &&\n\t\t!strings.Contains(original, `\\\\`) &&\n\t\tstrings.Contains(original, \"[\") &&\n\t\tstrings.Contains(original, \"]\") {\n\t\textra = fmt.Sprintf(`. It looks like '%s' includes a file path without an escaped back-slash. JSON requires back-slashes to be escaped such as [\"c:\\\\path\\\\to\\\\file.exe\", \"/parameter\"]`, original)\n\t}\n\treturn fmt.Errorf(\"%s requires the arguments to be in JSON form%s\", command, extra)\n}"} {"input": "package commands\n\nimport (\n\n\n\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/hofstadter-io/geb/commands/view\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar ViewLong = `View information known to the geb tool.`\n\nvar ViewCmd = &cobra.Command{\n\n\tUse: \"view\",\n\n\tAliases: []string{\n\t\t\"v\",\n\t},\n\n\tShort: \"View information known to the geb tool.\",\n\n\tLong: ViewLong,\n}\n\n\n\nfunc init() {\n\n\tViewCmd.AddCommand(view.SystemCmd)\n\tViewCmd.AddCommand(view.DslCmd)\n\tViewCmd.AddCommand(view.GenCmd)\n\tViewCmd.AddCommand(view.ProjectCmd)\n\tViewCmd.AddCommand(view.DesignCmd)\n\tViewCmd.AddCommand(view.PlansCmd)\n}\n\nfunc init() ", "output": "{\n\tRootCmd.AddCommand(ViewCmd)\n}"} {"input": "package core\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype PlatformConfig interface {\n}\n\ntype platformconfig struct {\n\tJsonData []byte\n\tType string `json:\"type\"`\n}\n\n\nfunc (m *platformconfig) UnmarshalJSON(data []byte) error {\n\tm.JsonData = data\n\ttype Unmarshalerplatformconfig platformconfig\n\ts := struct {\n\t\tModel Unmarshalerplatformconfig\n\t}{}\n\terr := json.Unmarshal(data, &s.Model)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Type = s.Model.Type\n\n\treturn err\n}\n\n\nfunc (m *platformconfig) UnmarshalPolymorphicJSON(data []byte) (interface{}, error) {\n\n\tif data == nil || string(data) == \"null\" {\n\t\treturn nil, nil\n\t}\n\n\tvar err error\n\tswitch m.Type {\n\tcase \"AMD_MILAN_BM\":\n\t\tmm := AmdMilanBmPlatformConfig{}\n\t\terr = json.Unmarshal(data, &mm)\n\t\treturn mm, err\n\tdefault:\n\t\treturn *m, nil\n\t}\n}\n\n\n\n\ntype PlatformConfigTypeEnum string\n\n\nconst (\n\tPlatformConfigTypeAmdMilanBm PlatformConfigTypeEnum = \"AMD_MILAN_BM\"\n)\n\nvar mappingPlatformConfigType = map[string]PlatformConfigTypeEnum{\n\t\"AMD_MILAN_BM\": PlatformConfigTypeAmdMilanBm,\n}\n\n\nfunc GetPlatformConfigTypeEnumValues() []PlatformConfigTypeEnum {\n\tvalues := make([]PlatformConfigTypeEnum, 0)\n\tfor _, v := range mappingPlatformConfigType {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}\n\nfunc (m platformconfig) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package wicore\n\nimport \"fmt\"\n\nconst _BorderType_name = \"BorderNoneBorderSingleBorderDouble\"\n\nvar _BorderType_index = [...]uint8{0, 10, 22, 34}\n\nfunc (i BorderType) String() string {\n\tif i < 0 || i+1 >= BorderType(len(_BorderType_index)) {\n\t\treturn fmt.Sprintf(\"BorderType(%d)\", i)\n\t}\n\treturn _BorderType_name[_BorderType_index[i]:_BorderType_index[i+1]]\n}\n\nconst _CommandCategory_name = \"UnknownCategoryWindowCategoryCommandsCategoryEditorCategoryDebugCategory\"\n\nvar _CommandCategory_index = [...]uint8{0, 15, 29, 45, 59, 72}\n\nfunc (i CommandCategory) String() string {\n\tif i < 0 || i+1 >= CommandCategory(len(_CommandCategory_index)) {\n\t\treturn fmt.Sprintf(\"CommandCategory(%d)\", i)\n\t}\n\treturn _CommandCategory_name[_CommandCategory_index[i]:_CommandCategory_index[i+1]]\n}\n\nconst _DockingType_name = \"DockingUnknownDockingFillDockingFloatingDockingLeftDockingRightDockingTopDockingBottom\"\n\nvar _DockingType_index = [...]uint8{0, 14, 25, 40, 51, 63, 73, 86}\n\n\n\nconst _KeyboardMode_name = \"NormalInsertAllMode\"\n\nvar _KeyboardMode_index = [...]uint8{0, 6, 12, 19}\n\nfunc (i KeyboardMode) String() string {\n\ti -= 1\n\tif i < 0 || i+1 >= KeyboardMode(len(_KeyboardMode_index)) {\n\t\treturn fmt.Sprintf(\"KeyboardMode(%d)\", i+1)\n\t}\n\treturn _KeyboardMode_name[_KeyboardMode_index[i]:_KeyboardMode_index[i+1]]\n}\n\nfunc (i DockingType) String() string ", "output": "{\n\tif i < 0 || i+1 >= DockingType(len(_DockingType_index)) {\n\t\treturn fmt.Sprintf(\"DockingType(%d)\", i)\n\t}\n\treturn _DockingType_name[_DockingType_index[i]:_DockingType_index[i+1]]\n}"} {"input": "package errors\n\n\n\ntype EmptyResourceError struct{}\n\nfunc (e *EmptyResourceError) Error() string {\n\treturn \"EmptyResourceError\"\n}\n\nfunc NewEmptyResourceError() *EmptyResourceError ", "output": "{\n\treturn &EmptyResourceError{}\n}"} {"input": "package oci\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\n\n\nfunc (i *Image) SetUser(user string) error ", "output": "{\n\tif user == \"\" {\n\t\treturn fmt.Errorf(\"user cannot be empty\")\n\t}\n\tif strings.Contains(user, \":\") {\n\t\treturn fmt.Errorf(\"user cannot contain a ':' character\")\n\t}\n\tif !strings.Contains(i.config.Config.User, \":\") {\n\t\ti.config.Config.User = user\n\t} else {\n\t\ttokens := strings.Split(i.config.Config.User, \":\")\n\t\tif len(tokens) != 2 {\n\t\t\treturn fmt.Errorf(\"something has gone horribly wrong setting the user\")\n\t\t}\n\t\ti.config.Config.User = user + \":\" + tokens[1]\n\t}\n\treturn i.save()\n}"} {"input": "package imaging\n\nimport (\n\t\"runtime\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\n\n\n\nfunc parallel(dataSize int, fn func(partStart, partEnd int)) {\n\tnumGoroutines := 1\n\tpartSize := dataSize\n\n\tnumProcs := runtime.GOMAXPROCS(0)\n\tif numProcs > 1 {\n\t\tnumGoroutines = numProcs\n\t\tpartSize = dataSize / (numGoroutines * 10)\n\t\tif partSize < 1 {\n\t\t\tpartSize = 1\n\t\t}\n\t}\n\n\tif numGoroutines == 1 {\n\t\tfn(0, dataSize)\n\t} else {\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(numGoroutines)\n\t\tidx := uint64(0)\n\n\t\tfor p := 0; p < numGoroutines; p++ {\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tfor {\n\t\t\t\t\tpartStart := int(atomic.AddUint64(&idx, uint64(partSize))) - partSize\n\t\t\t\t\tif partStart >= dataSize {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tpartEnd := partStart + partSize\n\t\t\t\t\tif partEnd > dataSize {\n\t\t\t\t\t\tpartEnd = dataSize\n\t\t\t\t\t}\n\t\t\t\t\tfn(partStart, partEnd)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\n\t\twg.Wait()\n\t}\n}\n\n\n\n\n\nfunc clamp(x float64) uint8 {\n\tv := int64(x + 0.5)\n\tif v > 255 {\n\t\treturn 255\n\t}\n\tif v > 0 {\n\t\treturn uint8(v)\n\t}\n\treturn 0\n}\n\nfunc absint(i int) int ", "output": "{\n\tif i < 0 {\n\t\treturn -i\n\t}\n\treturn i\n}"} {"input": "package okta\n\nimport ()\n\ntype OpenIdConnectApplicationSettingsClient struct {\n\tApplicationType string `json:\"application_type,omitempty\"`\n\tClientUri string `json:\"client_uri,omitempty\"`\n\tConsentMethod string `json:\"consent_method,omitempty\"`\n\tGrantTypes []*OAuthGrantType `json:\"grant_types,omitempty\"`\n\tLogoUri string `json:\"logo_uri,omitempty\"`\n\tPolicyUri string `json:\"policy_uri,omitempty\"`\n\tPostLogoutRedirectUris []string `json:\"post_logout_redirect_uris,omitempty\"`\n\tRedirectUris []string `json:\"redirect_uris,omitempty\"`\n\tResponseTypes []*OAuthResponseType `json:\"response_types,omitempty\"`\n\tTosUri string `json:\"tos_uri,omitempty\"`\n}\n\n\n\nfunc (a *OpenIdConnectApplicationSettingsClient) IsApplicationInstance() bool {\n\treturn true\n}\n\nfunc NewOpenIdConnectApplicationSettingsClient() *OpenIdConnectApplicationSettingsClient ", "output": "{\n\treturn &OpenIdConnectApplicationSettingsClient{}\n}"} {"input": "package plugin\n\n\ntype Kind uint8\n\nconst (\n\tAudit Kind = 1 + iota\n\tAuthentication\n\tSchema\n\tDaemon\n)\n\nfunc (k Kind) String() (str string) {\n\tswitch k {\n\tcase Audit:\n\t\tstr = \"Audit\"\n\tcase Authentication:\n\t\tstr = \"Authentication\"\n\tcase Schema:\n\t\tstr = \"Schema\"\n\tcase Daemon:\n\t\tstr = \"Daemon\"\n\t}\n\treturn\n}\n\n\ntype State uint8\n\nconst (\n\tUninitialized State = iota\n\tReady\n\tDying\n\tDisable\n)\n\n\n\nfunc (s State) String() (str string) ", "output": "{\n\tswitch s {\n\tcase Uninitialized:\n\t\tstr = \"Uninitialized\"\n\tcase Ready:\n\t\tstr = \"Ready\"\n\tcase Dying:\n\t\tstr = \"Dying\"\n\tcase Disable:\n\t\tstr = \"Disable\"\n\t}\n\treturn\n}"} {"input": "package remote\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"math\"\n\tpb \"rcs/proto\"\n)\n\ntype GrpcHandler func(s *remoteServer, in *pb.GrpcRequest, out *pb.GrpcReply) error\n\nvar grpcRouter map[string]GrpcHandler = map[string]GrpcHandler{\n\t\"online_list\": onlineList,\n}\n\nfunc handleGrpc(s *remoteServer, in *pb.GrpcRequest) (*pb.GrpcReply, error) {\n\tvar grpcReply pb.GrpcReply\n\tvar err error = nil\n\n\tif len(in.Action) < 1 {\n\t\terr = errors.New(\"handleGrpc input Action err\")\n\t\treturn &grpcReply, err\n\t}\n\thandle := grpcRouter[in.Action]\n\tif handle == nil {\n\t\terr = errors.New(\"handleGrpc input Action no find\")\n\t\treturn &grpcReply, err\n\t}\n\terr = handle(s, in, &grpcReply)\n\treturn &grpcReply, err\n}\n\n\nfunc onlineList(s *remoteServer, in *pb.GrpcRequest, out *pb.GrpcReply) error {\n\n\tlog.Println(\"handleGrpc input Action no find.......\")\n\terr := checkPage(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdatajson, counts := s.model.GetPageRec()\n\tout.Data = datajson\n\tout.TotalResults = counts\n\tpages := math.Ceil(float64(counts / in.PageSize))\n\tif float64(in.PageNo) < pages {\n\t\tout.HasNext = true\n\t}\n\treturn nil\n}\n\nfunc checkPage(in *pb.GrpcRequest) error ", "output": "{\n\tif in.PageNo < 1 {\n\t\tlog.Println(\"checkPage PageNo =\", in.PageNo)\n\t\tin.PageNo = 1\n\t}\n\tif in.PageSize < 1 {\n\t\treturn errors.New(\"PageSize value error\")\n\t}\n\treturn nil\n}"} {"input": "package internal\n\nimport (\n\t\"net/http\"\n\t\"os\"\n)\n\nconst (\n\tdefaultAddr = \"http://localhost:8983\"\n\taddrEnvName = \"GO_SOLR_ADDR\"\n)\n\nfunc NewInternalClient() (*Client, error) {\n\tvar addr string\n\tif addr = os.Getenv(addrEnvName); addr == \"\" {\n\t\taddr = defaultAddr\n\t}\n\tlog.Infof(\"use solr %s\", addr)\n\ttr := &http.Transport{}\n\tc := &http.Client{Transport: tr}\n\treturn NewClient(c, BaseURL(addr))\n}\n\n\n\nfunc MustNewInternalClient() *Client ", "output": "{\n\tc, err := NewInternalClient()\n\tif err != nil {\n\t\tlog.Error(\"can't create internal client for test\")\n\t\tpanic(err)\n\t}\n\treturn c\n}"} {"input": "package dsutil\n\nimport (\n\t\"appengine\"\n\t\"appengine/datastore\"\n)\n\nfunc RootKey(key *datastore.Key) *datastore.Key {\n\tfor parent := key; parent != nil; {\n\t\tkey = parent\n\t\tparent = key.Parent()\n\t}\n\treturn key\n}\n\n\n\nfunc EntityExists(ctx appengine.Context, key *datastore.Key) (bool, error) ", "output": "{\n\tq := datastore.NewQuery(key.Kind()).\n\t\tAncestor(key).\n\t\tFilter(\"__key__=\", key)\n\n\tn, err := q.Count(ctx)\n\treturn n > 0, err\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/rpc\"\n\t\"net/rpc/jsonrpc\"\n\t\"os\"\n\t\"strings\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\ntype litAfClient struct {\n\tremote string\n\tport uint16\n\trpccon *rpc.Client\n}\n\n\n\n\nfunc main() {\n\n\tlc := new(litAfClient)\n\tsetConfig(lc)\n\n\tdialString := fmt.Sprintf(\"%s:%d\", lc.remote, lc.port)\n\n\tclient, err := net.Dial(\"tcp\", dialString)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer client.Close()\n\n\tlc.rpccon = jsonrpc.NewClient(client)\n\n\tgo lc.RequestAsync()\n\n\tfor {\n\t\treader := bufio.NewReaderSize(os.Stdin, 4000)\n\t\tfmt.Printf(\"lit-af# \") \n\t\tmsg, err := reader.ReadString('\\n') \n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tcmdslice := strings.Fields(msg) \n\t\tif len(cmdslice) < 1 {\n\t\t\tcontinue \n\t\t}\n\t\tfmt.Printf(\"entered command: %s\\n\", msg) \n\t\terr = lc.Shellparse(cmdslice)\n\t\tif err != nil { \n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n}\n\nfunc setConfig(lc *litAfClient) ", "output": "{\n\thostptr := flag.String(\"node\", \"127.0.0.1\", \"host to connect to\")\n\tportptr := flag.Int(\"p\", 9750, \"port to connect to\")\n\n\n\tflag.Parse()\n\n\tlc.remote = *hostptr\n\tlc.port = uint16(*portptr)\n}"} {"input": "package authy\n\nimport (\n\t\"github.com/tg123/sshpiper/sshpiperd/challenger\"\n)\n\n\n\nfunc (a *authyClient) GetOpts() interface{} {\n\treturn &a.Config\n}\n\nfunc (a *authyClient) GetHandler() challenger.Handler {\n\treturn a.challenge\n}\n\nfunc init() {\n\tchallenger.Register(\"authy\", &authyClient{})\n}\n\nfunc (authyClient) GetName() string ", "output": "{\n\treturn \"authy\"\n}"} {"input": "package google\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hashicorp/terraform-plugin-sdk/helper/schema\"\n)\n\nfunc dataSourceGoogleComputeSslPolicy() *schema.Resource {\n\tdsSchema := datasourceSchemaFromResourceSchema(resourceComputeSslPolicy().Schema)\n\n\taddRequiredFieldsToSchema(dsSchema, \"name\")\n\n\taddOptionalFieldsToSchema(dsSchema, \"project\")\n\n\treturn &schema.Resource{\n\t\tRead: datasourceComputeSslPolicyRead,\n\t\tSchema: dsSchema,\n\t}\n}\n\n\n\nfunc datasourceComputeSslPolicyRead(d *schema.ResourceData, meta interface{}) error ", "output": "{\n\tconfig := meta.(*Config)\n\n\tproject, err := getProject(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpolicyName := d.Get(\"name\").(string)\n\n\td.SetId(fmt.Sprintf(\"projects/%s/global/sslPolicies/%s\", project, policyName))\n\n\treturn resourceComputeSslPolicyRead(d, meta)\n}"} {"input": "package types\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"path\"\n\t\"strings\"\n)\n\n\ntype Resource string\n\nfunc (res Resource) String() string {\n\treturn string(res)\n}\n\n\nfunc (res Resource) RelativeTo(other Resource) (Resource, error) {\n\tprefix := other.String()\n\tstr := res.String()\n\n\tif !strings.HasPrefix(str, prefix) {\n\t\treturn Resource(\"\"), errors.New(\"value error\")\n\t}\n\n\trelative := strings.TrimPrefix(strings.TrimPrefix(str, prefix), \"/\")\n\tif relative == \"\" {\n\t\trelative = \".\"\n\t}\n\n\treturn Resource(relative), nil\n}\n\n\nfunc (res Resource) Subresource(resources ...Resource) Resource {\n\telements := []string{res.String()}\n\n\tfor _, resource := range resources {\n\t\telements = append(elements, resource.String())\n\t}\n\n\treturn Resource(path.Join(elements...))\n}\n\n\n\n\nfunc (res Resource) GetNamespace() (Namespace, error) ", "output": "{\n\treturn nil, fmt.Errorf(\"no namespace found for %s\", res)\n}"} {"input": "package loadbalancer\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateListenerRequest struct {\n\n\tCreateListenerDetails `contributesTo:\"body\"`\n\n\tLoadBalancerId *string `mandatory:\"true\" contributesTo:\"path\" name:\"loadBalancerId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateListenerRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateListenerRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request CreateListenerRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateListenerResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateListenerResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateListenerResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateListenerRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\n\n\n\ntype ClusterMeshStatus struct {\n\n\tClusters []*RemoteCluster `json:\"clusters\"`\n\n\tNumGlobalServices int64 `json:\"num-global-services,omitempty\"`\n}\n\n\n\n\nfunc (m *ClusterMeshStatus) validateClusters(formats strfmt.Registry) error {\n\n\tif swag.IsZero(m.Clusters) { \n\t\treturn nil\n\t}\n\n\tfor i := 0; i < len(m.Clusters); i++ {\n\t\tif swag.IsZero(m.Clusters[i]) { \n\t\t\tcontinue\n\t\t}\n\n\t\tif m.Clusters[i] != nil {\n\t\t\tif err := m.Clusters[i].Validate(formats); err != nil {\n\t\t\t\tif ve, ok := err.(*errors.Validation); ok {\n\t\t\t\t\treturn ve.ValidateName(\"clusters\" + \".\" + strconv.Itoa(i))\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\n\nfunc (m *ClusterMeshStatus) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *ClusterMeshStatus) UnmarshalBinary(b []byte) error {\n\tvar res ClusterMeshStatus\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *ClusterMeshStatus) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateClusters(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package linode\n\nimport \"errors\"\nimport \"fmt\"\n\n\n\n\n\nfunc (client *Client) GetImage(imageID int) (*Image, error) {\n\tparams := map[string]string{\n\t\t\"ImageID\": fmt.Sprintf(\"%d\", imageID),\n\t}\n\tvar images []*Image\n\terr := client.request(\"image.list\", params, &images)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if len(images) != 1 {\n\t\treturn nil, errors.New(\"expected one image in response\")\n\t} else {\n\t\treturn images[0], nil\n\t}\n}\n\nfunc (client *Client) DeleteImage(imageID int) error {\n\tparams := map[string]string{\n\t\t\"ImageID\": fmt.Sprintf(\"%d\", imageID),\n\t}\n\treturn client.request(\"image.delete\", params, nil)\n}\n\nfunc (client *Client) ListImages(pendingOnly bool) ([]*Image, error) ", "output": "{\n\tparams := make(map[string]string)\n\tif pendingOnly {\n\t\tparams[\"pending\"] = \"1\"\n\t}\n\tvar images []*Image\n\terr := client.request(\"image.list\", params, &images)\n\treturn images, err\n}"} {"input": "package experiments\n\nimport (\n\t\"context\"\n\n\t\"go.chromium.org/luci/common/errors\"\n\n\tbbpb \"go.chromium.org/luci/buildbucket/proto\"\n\tswarmingpb \"go.chromium.org/luci/swarming/proto/api\"\n)\n\nvar knownExperiments = map[string]Experiment{}\n\n\ntype Experiment func(ctx context.Context, b *bbpb.Build, task *swarmingpb.TaskRequest) error\n\n\n\n\n\nfunc Apply(ctx context.Context, b *bbpb.Build, task *swarmingpb.TaskRequest) error {\n\tfor _, name := range b.GetInput().GetExperiments() {\n\t\tif exp, ok := knownExperiments[name]; ok {\n\t\t\tif err := exp(ctx, b, task); err != nil {\n\t\t\t\treturn errors.Annotate(err, \"experiment %q\", name).Err()\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc Register(key string, exp Experiment) ", "output": "{\n\tknownExperiments[key] = exp\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realIAMInstanceProfile IAMInstanceProfile\n\nfunc (o *IAMInstanceProfile) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realIAMInstanceProfile\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = IAMInstanceProfile(r)\n\treturn nil\n}\n\nvar _ fi.HasName = &IAMInstanceProfile{}\n\n\n\nfunc (e *IAMInstanceProfile) SetName(name string) {\n\te.Name = &name\n}\n\nfunc (e *IAMInstanceProfile) String() string {\n\treturn fi.TaskAsString(e)\n}\n\nfunc (e *IAMInstanceProfile) GetName() *string ", "output": "{\n\treturn e.Name\n}"} {"input": "package markdown\n\nimport (\n\t\"testing\"\n)\n\nvar skypeToMarkdownTests = []struct {\n\tv string\n\twant string\n}{\n\t{\"``````\", \"```https://github.com/grokify```\"},\n\t{``, `[Grokify](https://github.com/grokify)`},\n\t{`ABC `, `ABC [Grokify](https://github.com/grokify)`},\n}\n\n\n\nfunc TestSkypeToMarkdown(t *testing.T) ", "output": "{\n\tfor _, tt := range skypeToMarkdownTests {\n\t\tgot := SkypeToMarkdown(tt.v, true)\n\t\tif got != tt.want {\n\t\t\tt.Errorf(\"markdown.SkypeToMarkdown(\\\"%v\\\") Mismatch: want [%v] got [%v]\", tt.v, tt.want, got)\n\t\t}\n\t}\n}"} {"input": "package cluster_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/influxdb/influxdb/cluster\"\n\t\"github.com/influxdb/influxdb/services/meta\"\n)\n\n\n\nfunc TestBalancerEmptyNodes(t *testing.T) {\n\tb := cluster.NewNodeBalancer([]meta.NodeInfo{})\n\tgot := b.Next()\n\tif got != nil {\n\t\tt.Errorf(\"expected nil, got %v\", got)\n\t}\n}\n\nfunc TestBalancerUp(t *testing.T) {\n\tnodes := NewNodes()\n\tb := cluster.NewNodeBalancer(nodes)\n\n\tfirst := b.Next()\n\tif first == nil {\n\t\tt.Errorf(\"expected datanode, got %v\", first)\n\t}\n\n\tsecond := b.Next()\n\tif second == nil {\n\t\tt.Errorf(\"expected datanode, got %v\", second)\n\t}\n\n\tif first.ID == second.ID {\n\t\tt.Errorf(\"expected first != second. got %v = %v\", first.ID, second.ID)\n\t}\n}\n\nfunc NewNodes() []meta.NodeInfo ", "output": "{\n\tvar nodes []meta.NodeInfo\n\tfor i := 1; i <= 2; i++ {\n\t\tnodes = append(nodes, meta.NodeInfo{\n\t\t\tID: uint64(i),\n\t\t\tHost: fmt.Sprintf(\"localhost:999%d\", i),\n\t\t})\n\t}\n\treturn nodes\n}"} {"input": "package mount\n\n\nfunc GetMounts() ([]*Info, error) {\n\treturn parseMountTable()\n}\n\n\n\nfunc Mounted(mountpoint string) (bool, error) {\n\tentries, err := parseMountTable()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, e := range entries {\n\t\tif e.Mountpoint == mountpoint {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}\n\n\n\n\n\nfunc Mount(device, target, mType, options string) error {\n\tflag, _ := parseOptions(options)\n\tif flag&REMOUNT != REMOUNT {\n\t\tif mounted, err := Mounted(target); err != nil || mounted {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn ForceMount(device, target, mType, options)\n}\n\n\n\n\n\nfunc ForceMount(device, target, mType, options string) error {\n\tflag, data := parseOptions(options)\n\treturn mount(device, target, mType, uintptr(flag), data)\n}\n\n\n\n\n\nfunc Unmount(target string) error ", "output": "{\n\tif mounted, err := Mounted(target); err != nil || !mounted {\n\t\treturn err\n\t}\n\treturn unmount(target, mntDetach)\n}"} {"input": "package vml\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\ntype CT_F struct {\n\tEqnAttr *string\n}\n\nfunc NewCT_F() *CT_F {\n\tret := &CT_F{}\n\treturn ret\n}\n\n\n\nfunc (m *CT_F) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"eqn\" {\n\t\t\tparsed, err := attr.Value, error(nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.EqnAttr = &parsed\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_F: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (m *CT_F) Validate() error {\n\treturn m.ValidateWithPath(\"CT_F\")\n}\n\n\nfunc (m *CT_F) ValidateWithPath(path string) error {\n\treturn nil\n}\n\nfunc (m *CT_F) MarshalXML(e *xml.Encoder, start xml.StartElement) error ", "output": "{\n\tif m.EqnAttr != nil {\n\t\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"eqn\"},\n\t\t\tValue: fmt.Sprintf(\"%v\", *m.EqnAttr)})\n\t}\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}"} {"input": "package blocks\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\tmh \"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash\"\n\tu \"github.com/ipfs/go-ipfs/util\"\n)\n\n\ntype Block struct {\n\tMultihash mh.Multihash\n\tData []byte\n}\n\n\nfunc NewBlock(data []byte) *Block {\n\treturn &Block{Data: data, Multihash: u.Hash(data)}\n}\n\n\n\n\nfunc NewBlockWithHash(data []byte, h mh.Multihash) (*Block, error) {\n\tif u.Debug {\n\t\tchk := u.Hash(data)\n\t\tif string(chk) != string(h) {\n\t\t\treturn nil, errors.New(\"Data did not match given hash!\")\n\t\t}\n\t}\n\treturn &Block{Data: data, Multihash: h}, nil\n}\n\n\nfunc (b *Block) Key() u.Key {\n\treturn u.Key(b.Multihash)\n}\n\n\n\nfunc (b *Block) Loggable() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"block\": b.Key().String(),\n\t}\n}\n\nfunc (b *Block) String() string ", "output": "{\n\treturn fmt.Sprintf(\"[Block %s]\", b.Key())\n}"} {"input": "package quotedprintable\n\nimport (\n\t\"bytes\"\n\t\"sync\"\n)\n\nvar bufPool = sync.Pool{\n\tNew: func() interface{} {\n\t\treturn new(bytes.Buffer)\n\t},\n}\n\nfunc getBuffer() *bytes.Buffer {\n\treturn bufPool.Get().(*bytes.Buffer)\n}\n\n\n\nfunc putBuffer(buf *bytes.Buffer) ", "output": "{\n\tif buf.Len() > 1024 {\n\t\treturn\n\t}\n\tbuf.Reset()\n\tbufPool.Put(buf)\n}"} {"input": "package armmanagedservices\n\nconst (\n\tmoduleName = \"armmanagedservices\"\n\tmoduleVersion = \"v0.2.1\"\n)\n\n\ntype MultiFactorAuthProvider string\n\nconst (\n\tMultiFactorAuthProviderAzure MultiFactorAuthProvider = \"Azure\"\n\tMultiFactorAuthProviderNone MultiFactorAuthProvider = \"None\"\n)\n\n\nfunc PossibleMultiFactorAuthProviderValues() []MultiFactorAuthProvider {\n\treturn []MultiFactorAuthProvider{\n\t\tMultiFactorAuthProviderAzure,\n\t\tMultiFactorAuthProviderNone,\n\t}\n}\n\n\nfunc (c MultiFactorAuthProvider) ToPtr() *MultiFactorAuthProvider {\n\treturn &c\n}\n\n\ntype ProvisioningState string\n\nconst (\n\tProvisioningStateAccepted ProvisioningState = \"Accepted\"\n\tProvisioningStateCanceled ProvisioningState = \"Canceled\"\n\tProvisioningStateCreated ProvisioningState = \"Created\"\n\tProvisioningStateCreating ProvisioningState = \"Creating\"\n\tProvisioningStateDeleted ProvisioningState = \"Deleted\"\n\tProvisioningStateDeleting ProvisioningState = \"Deleting\"\n\tProvisioningStateFailed ProvisioningState = \"Failed\"\n\tProvisioningStateNotSpecified ProvisioningState = \"NotSpecified\"\n\tProvisioningStateReady ProvisioningState = \"Ready\"\n\tProvisioningStateRunning ProvisioningState = \"Running\"\n\tProvisioningStateSucceeded ProvisioningState = \"Succeeded\"\n\tProvisioningStateUpdating ProvisioningState = \"Updating\"\n)\n\n\nfunc PossibleProvisioningStateValues() []ProvisioningState {\n\treturn []ProvisioningState{\n\t\tProvisioningStateAccepted,\n\t\tProvisioningStateCanceled,\n\t\tProvisioningStateCreated,\n\t\tProvisioningStateCreating,\n\t\tProvisioningStateDeleted,\n\t\tProvisioningStateDeleting,\n\t\tProvisioningStateFailed,\n\t\tProvisioningStateNotSpecified,\n\t\tProvisioningStateReady,\n\t\tProvisioningStateRunning,\n\t\tProvisioningStateSucceeded,\n\t\tProvisioningStateUpdating,\n\t}\n}\n\n\n\n\nfunc (c ProvisioningState) ToPtr() *ProvisioningState ", "output": "{\n\treturn &c\n}"} {"input": "package kubernetes\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/weaveworks/scope/report\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/unversioned\"\n\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n\t\"k8s.io/kubernetes/pkg/labels\"\n)\n\n\nconst (\n\tUpdatedReplicas = \"kubernetes_updated_replicas\"\n\tAvailableReplicas = \"kubernetes_available_replicas\"\n\tUnavailableReplicas = \"kubernetes_unavailable_replicas\"\n\tStrategy = \"kubernetes_strategy\"\n)\n\n\ntype Deployment interface {\n\tMeta\n\tSelector() labels.Selector\n\tGetNode(probeID string) report.Node\n}\n\ntype deployment struct {\n\t*extensions.Deployment\n\tMeta\n\tNode *api.Node\n}\n\n\nfunc NewDeployment(d *extensions.Deployment) Deployment {\n\treturn &deployment{Deployment: d, Meta: meta{d.ObjectMeta}}\n}\n\n\n\nfunc (d *deployment) GetNode(probeID string) report.Node {\n\treturn d.MetaNode(report.MakeDeploymentNodeID(d.UID())).WithLatests(map[string]string{\n\t\tObservedGeneration: fmt.Sprint(d.Status.ObservedGeneration),\n\t\tDesiredReplicas: fmt.Sprint(d.Spec.Replicas),\n\t\tReplicas: fmt.Sprint(d.Status.Replicas),\n\t\tUpdatedReplicas: fmt.Sprint(d.Status.UpdatedReplicas),\n\t\tAvailableReplicas: fmt.Sprint(d.Status.AvailableReplicas),\n\t\tUnavailableReplicas: fmt.Sprint(d.Status.UnavailableReplicas),\n\t\tStrategy: string(d.Spec.Strategy.Type),\n\t\treport.ControlProbeID: probeID,\n\t}).WithLatestActiveControls(ScaleUp, ScaleDown)\n}\n\nfunc (d *deployment) Selector() labels.Selector ", "output": "{\n\tselector, err := unversioned.LabelSelectorAsSelector(d.Spec.Selector)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn selector\n}"} {"input": "package types\n\nimport \"fmt\"\n\ntype IntegerValue struct {\n\tValue int64\n}\n\nfunc (v *IntegerValue) ToString() string {\n\treturn fmt.Sprint(v.Value)\n}\n\nfunc (v *IntegerValue) GetType() string {\n\treturn \"integer\"\n}\n\nfunc (v *IntegerValue) IsValue() bool {\n\treturn true\n}\n\n\n\nfunc (v *IntegerValue) EqualTo(t ValueType) bool {\n\tif v2, ok := t.(*IntegerValue); ok {\n\t\tif v2.Value == v.Value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc NewIntegerValue(v int64) *IntegerValue {\n\treturn &IntegerValue{Value: v}\n}\n\nfunc (v *IntegerValue) ConvertTo(t string) (ValueType, error) ", "output": "{\n\treturn nil, fmt.Errorf(\"cannot convert integer to %s: does not implement yet\", t)\n}"} {"input": "package tfbparser\n\nimport \"github.com/kiwih/goFB/iec61499\"\n\n\ntype tfbParse struct {\n\tfbs []iec61499.FB\n\n\titems []string\n\titemIndex int\n\n\tcurrentLine int\n\tcurrentFile string\n}\n\n\nfunc (t *tfbParse) getCurrentDebugInfo() iec61499.DebugInfo {\n\treturn iec61499.DebugInfo{\n\t\tSourceLine: t.currentLine,\n\t\tSourceFile: t.currentFile,\n\t}\n}\n\n\nfunc (t *tfbParse) isFBNameUnused(name string) bool {\n\tfor i := 0; i < len(t.fbs); i++ {\n\t\tif t.fbs[i].Name == name {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\nfunc (t *tfbParse) pop() string {\n\tif t.done() {\n\t\treturn \"\"\n\t}\n\ts := t.items[t.itemIndex]\n\tt.itemIndex++\n\n\tif s == pNewline {\n\t\tt.currentLine++\n\t\treturn t.pop()\n\t}\n\treturn s\n}\n\n\n\nfunc (t *tfbParse) peek() string {\n\tif t.done() {\n\t\treturn \"\"\n\t}\n\tfor i := 0; i < len(t.items); i++ {\n\t\tif t.items[t.itemIndex+i] != pNewline {\n\t\t\treturn t.items[t.itemIndex+i]\n\t\t}\n\t}\n\treturn \"\"\n}\n\n\nfunc (t *tfbParse) done() bool {\n\treturn t.itemIndex >= len(t.items)\n}\n\n\n\n\n\nfunc (t *tfbParse) getFBIndexFromName(name string) int ", "output": "{\n\tfor i := 0; i < len(t.fbs); i++ {\n\t\tif t.fbs[i].Name == name {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}"} {"input": "package dshelp\n\nimport (\n\tcid \"gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid\"\n\t\"gx/ipfs/QmaRb5yNXKonhbkpNxNawoydk4N6es6b4fPj19sjEKsh5D/go-datastore\"\n\t\"gx/ipfs/QmfVj3x4D6Jkq9SEoi5n2NmoUomLwoeiwnYz2KQa15wRw6/base32\"\n)\n\n\nfunc NewKeyFromBinary(rawKey []byte) datastore.Key {\n\tbuf := make([]byte, 1+base32.RawStdEncoding.EncodedLen(len(rawKey)))\n\tbuf[0] = '/'\n\tbase32.RawStdEncoding.Encode(buf[1:], rawKey)\n\treturn datastore.RawKey(string(buf))\n}\n\n\nfunc BinaryFromDsKey(k datastore.Key) ([]byte, error) {\n\treturn base32.RawStdEncoding.DecodeString(k.String()[1:])\n}\n\n\n\n\n\nfunc DsKeyToCid(dsKey datastore.Key) (cid.Cid, error) {\n\tkb, err := BinaryFromDsKey(dsKey)\n\tif err != nil {\n\t\treturn cid.Cid{}, err\n\t}\n\treturn cid.Cast(kb)\n}\n\nfunc CidToDsKey(k cid.Cid) datastore.Key ", "output": "{\n\treturn NewKeyFromBinary(k.Bytes())\n}"} {"input": "package grpclog \n\nimport \"os\"\n\nvar logger = newLoggerV2()\n\n\nfunc V(l int) bool {\n\treturn logger.V(l)\n}\n\n\nfunc Info(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\nfunc Infof(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\nfunc Infoln(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\n\nfunc Warning(args ...interface{}) {\n\tlogger.Warning(args...)\n}\n\n\nfunc Warningf(format string, args ...interface{}) {\n\tlogger.Warningf(format, args...)\n}\n\n\nfunc Warningln(args ...interface{}) {\n\tlogger.Warningln(args...)\n}\n\n\n\n\n\nfunc Errorf(format string, args ...interface{}) {\n\tlogger.Errorf(format, args...)\n}\n\n\nfunc Errorln(args ...interface{}) {\n\tlogger.Errorln(args...)\n}\n\n\n\nfunc Fatal(args ...interface{}) {\n\tlogger.Fatal(args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalf(format string, args ...interface{}) {\n\tlogger.Fatalf(format, args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalln(args ...interface{}) {\n\tlogger.Fatalln(args...)\n\tos.Exit(1)\n}\n\n\n\n\nfunc Print(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\n\n\nfunc Printf(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\n\n\nfunc Println(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\nfunc Error(args ...interface{}) ", "output": "{\n\tlogger.Error(args...)\n}"} {"input": "package git\n\nimport (\n\t\"encoding/hex\"\n)\n\n\ntype Hash [20]byte\n\n\nvar ZeroHash Hash\n\n\nfunc NewHash(s string) Hash {\n\tb, _ := hex.DecodeString(s)\n\n\tvar h Hash\n\tcopy(h[:], b)\n\n\treturn h\n}\n\n\n\n\nfunc (h Hash) String() string {\n\treturn hex.EncodeToString(h[:])\n}\n\nfunc (h Hash) IsZero() bool ", "output": "{\n\tvar empty Hash\n\treturn h == empty\n}"} {"input": "package tagquery\n\nimport (\n\t\"io\"\n\n\t\"github.com/grafana/metrictank/schema\"\n)\n\ntype expressionMatchNone struct {\n\texpressionCommon\n\toriginalOperator ExpressionOperator\n}\n\nfunc (e *expressionMatchNone) Equals(other Expression) bool {\n\treturn e.key == other.GetKey() && e.GetOperator() == other.GetOperator() && e.value == other.GetValue()\n}\n\nfunc (e *expressionMatchNone) GetDefaultDecision() FilterDecision {\n\treturn Fail\n}\n\nfunc (e *expressionMatchNone) GetKey() string {\n\treturn e.key\n}\n\n\n\nfunc (e *expressionMatchNone) GetOperator() ExpressionOperator {\n\treturn MATCH_NONE\n}\n\nfunc (e *expressionMatchNone) GetOperatorCost() uint32 {\n\treturn 0\n}\n\nfunc (e *expressionMatchNone) RequiresNonEmptyValue() bool {\n\treturn true\n}\n\nfunc (e *expressionMatchNone) Matches(value string) bool {\n\treturn false\n}\n\nfunc (e *expressionMatchNone) GetMetricDefinitionFilter(_ IdTagLookup) MetricDefinitionFilter {\n\treturn func(_ schema.MKey, _ string, _ []string) FilterDecision { return Fail }\n}\n\nfunc (e *expressionMatchNone) StringIntoWriter(writer io.Writer) {\n\twriter.Write([]byte(e.key))\n\te.originalOperator.StringIntoWriter(writer)\n\twriter.Write([]byte(e.value))\n}\n\nfunc (e *expressionMatchNone) GetValue() string ", "output": "{\n\treturn e.value\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\tcv \"github.com/glycerine/goconvey/convey\"\n)\n\n\n\nfunc TestReplicaJob(t *testing.T) ", "output": "{\n\n\tcv.Convey(\"If we start a job with a replication factor of 2\", t, func() {\n\t\tcv.Convey(\"then the first job to finish should notify and cancel the other workers on that job\", func() {\n\t\t})\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/url\"\n\t\"sync\"\n\n\t\"github.com/gorilla/websocket\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar rootCmd *cobra.Command\n\n\n\nfunc run(cmd *cobra.Command, args []string) {\n\taddress, err := cmd.Flags().GetString(\"address\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tu := url.URL{Scheme: \"ws\", Host: address, Path: \"/publish\"}\n\tlog.Printf(\"connecting to %s\", u.String())\n\n\tc, _, err := websocket.DefaultDialer.Dial(u.String(), nil)\n\tif err != nil {\n\t\tlog.Fatal(\"dial:\", err)\n\t}\n\tdefer c.Close()\n\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tdefer close(done)\n\t\tfor {\n\t\t\t_, message, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"read:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Printf(\"recv: %s\", message)\n\t\t\tbreak\n\t\t}\n\t\twg.Done()\n\t}()\n\n\terr = c.WriteMessage(websocket.TextMessage, []byte(\"hello\"))\n\tif err != nil {\n\t\tlog.Println(\"write:\", err)\n\t\treturn\n\t}\n\n\twg.Wait()\n}\n\nfunc main() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc init() ", "output": "{\n\trootCmd = &cobra.Command{\n\t\tUse: \"ws-client\",\n\t\tShort: \"demo for websocket client\",\n\t\tLong: \"demo for websocket client\",\n\t\tRun: run,\n\t}\n\n\trootCmd.Flags().StringP(\"address\", \"a\", \"127.0.0.1:8080\", \"server listening address\")\n}"} {"input": "package implementation\n\nimport (\n\t\"crypto/tls\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/go-openapi/swag\"\n\t\"github.com/go-swagger/go-swagger/examples/auto-configure/restapi/operations\"\n)\n\ntype ConfigureImpl struct {\n\tflags Flags\n}\n\ntype Flags struct {\n\tExample1 string `long:\"example1\" description:\"Sample for showing how to configure cmd-line flags\"`\n\tExample2 string `long:\"example2\" description:\"Further info at https://github.com/jessevdk/go-flags\"`\n}\n\nfunc (i *ConfigureImpl) ConfigureFlags(api *operations.AToDoListApplicationAPI) {\n\tapi.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{\n\t\t{\n\t\t\tShortDescription: \"Example Flags\",\n\t\t\tLongDescription: \"\",\n\t\t\tOptions: &i.flags,\n\t\t},\n\t}\n}\n\nfunc (i *ConfigureImpl) ConfigureTLS(tlsConfig *tls.Config) {\n}\n\n\n\nfunc (i *ConfigureImpl) SetupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}\n\nfunc (i *ConfigureImpl) SetupGlobalMiddleware(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tlog.Printf(\"Recieved request on path: %v\", req.URL.String())\n\t\thandler.ServeHTTP(w, req)\n\t})\n}\n\nfunc (i *ConfigureImpl) CustomConfigure(api *operations.AToDoListApplicationAPI) {\n\tapi.Logger = log.Printf\n\tapi.ServerShutdown = func() {\n\t\tlog.Printf(\"Running ServerShutdown function\")\n\t}\n}\n\nfunc (i *ConfigureImpl) ConfigureServer(s *http.Server, scheme, addr string) ", "output": "{\n\tif i.flags.Example1 != \"something\" {\n\t\tlog.Println(\"example1 argument is not something\")\n\t}\n}"} {"input": "package nat\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n\n\t\"github.com/cilium/cilium/pkg/byteorder\"\n\t\"github.com/cilium/cilium/pkg/tuple\"\n\t\"github.com/cilium/cilium/pkg/types\"\n)\n\n\n\n\ntype NatEntry4 struct {\n\tCreated uint64 `align:\"created\"`\n\tHostLocal uint64 `align:\"host_local\"`\n\tPad1 uint64 `align:\"pad1\"`\n\tPad2 uint64 `align:\"pad2\"`\n\tAddr types.IPv4 `align:\"to_saddr\"`\n\tPort uint16 `align:\"to_sport\"`\n}\n\n\nconst SizeofNatEntry4 = int(unsafe.Sizeof(NatEntry4{}))\n\n\nfunc (n *NatEntry4) GetValuePtr() unsafe.Pointer { return unsafe.Pointer(n) }\n\n\nfunc (n *NatEntry4) String() string {\n\treturn fmt.Sprintf(\"Addr=%s Port=%d Created=%d HostLocal=%d\\n\",\n\t\tn.Addr,\n\t\tn.Port,\n\t\tn.Created,\n\t\tn.HostLocal)\n}\n\n\nfunc (n *NatEntry4) Dump(key NatKey, start uint64) string {\n\tvar which string\n\n\tif key.GetFlags()&tuple.TUPLE_F_IN != 0 {\n\t\twhich = \"DST\"\n\t} else {\n\t\twhich = \"SRC\"\n\t}\n\treturn fmt.Sprintf(\"XLATE_%s %s:%d Created=%s HostLocal=%d\\n\",\n\t\twhich,\n\t\tn.Addr,\n\t\tn.Port,\n\t\tNatDumpCreated(start, n.Created),\n\t\tn.HostLocal)\n}\n\n\n\n\nfunc (n *NatEntry4) ToHost() NatEntry ", "output": "{\n\tx := *n\n\tx.Port = byteorder.NetworkToHost16(n.Port)\n\treturn &x\n}"} {"input": "package models\n\n\n\n\nimport (\n\tciliumModels \"github.com/cilium/cilium/api/v1/models\"\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\n\ntype HealthResponse struct {\n\n\tCilium ciliumModels.StatusResponse `json:\"cilium,omitempty\"`\n\n\tSystemLoad *LoadResponse `json:\"system-load,omitempty\"`\n\n\tUptime string `json:\"uptime,omitempty\"`\n}\n\n\n\n\nfunc (m *HealthResponse) validateSystemLoad(formats strfmt.Registry) error {\n\n\tif swag.IsZero(m.SystemLoad) { \n\t\treturn nil\n\t}\n\n\tif m.SystemLoad != nil {\n\t\tif err := m.SystemLoad.Validate(formats); err != nil {\n\t\t\tif ve, ok := err.(*errors.Validation); ok {\n\t\t\t\treturn ve.ValidateName(\"system-load\")\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\nfunc (m *HealthResponse) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *HealthResponse) UnmarshalBinary(b []byte) error {\n\tvar res HealthResponse\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *HealthResponse) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateSystemLoad(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gabriel-comeau/tbuikit\"\n\t\"github.com/nsf/termbox-go\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc doDisconnect(uiElement, event interface{}) {\n\tdisconnect()\n}\n\n\nfunc chatEnterHandler(uiElement, event interface{}) {\n\twidget, ok := uiElement.(*tbuikit.TextInputWidget)\n\tif ok {\n\t\tnetChatChan <- widget.GetBuffer().ReturnAndClear() + \"\\n\"\n\t}\n}\n\n\n\n\n\n\nfunc calculateTopTitleBar() (x1, x2, y1, y2 int) {\n\tw := tbuikit.GetTermboxWidth()\n\tx1 = 1\n\tx2 = w - 1\n\ty1 = 1\n\ty2 = TITLE_BAR_HEIGHT\n\treturn\n}\n\n\nfunc calculateChatBufferRect() (x1, x2, y1, y2 int) {\n\tw, h := termbox.Size()\n\tx1 = 1\n\tx2 = w - 1\n\ty1 = (h / 2) + (h / 4)\n\ty2 = h - 2\n\treturn\n}\n\n\n\n\n\nfunc calculateWhoRect() (x1, x2, y1, y2 int) {\n\tw, h := termbox.Size()\n\tx1 = w - (w / 4) + 1\n\tx2 = w - 1\n\ty1 = TITLE_BAR_HEIGHT + 6\n\ty2 = (h / 2) + (h / 4) - 1\n\treturn\n}\n\n\nfunc calculateWhoLabelRect() (x1, x2, y1, y2 int) {\n\tw := tbuikit.GetTermboxWidth()\n\tx1 = w - (w / 4) + 1\n\tx2 = w - 1\n\ty1 = TITLE_BAR_HEIGHT + 1\n\ty2 = TITLE_BAR_HEIGHT + 5\n\treturn\n}\n\nfunc calculateMessageBufferRect() (x1, x2, y1, y2 int) ", "output": "{\n\tw, h := termbox.Size()\n\tx1 = 1\n\tx2 = w - (w / 4)\n\ty1 = TITLE_BAR_HEIGHT + 1\n\ty2 = (h / 2) + (h / 4) - 1\n\treturn\n}"} {"input": "package iso20022\n\n\ntype TaxVoucher3 struct {\n\n\tIdentification *RestrictedFINXMax16Text `xml:\"Id\"`\n\n\tBargainDate *DateAndDateTimeChoice `xml:\"BrgnDt,omitempty\"`\n\n\tBargainSettlementDate *DateAndDateTimeChoice `xml:\"BrgnSttlmDt,omitempty\"`\n}\n\nfunc (t *TaxVoucher3) SetIdentification(value string) {\n\tt.Identification = (*RestrictedFINXMax16Text)(&value)\n}\n\n\n\nfunc (t *TaxVoucher3) AddBargainSettlementDate() *DateAndDateTimeChoice {\n\tt.BargainSettlementDate = new(DateAndDateTimeChoice)\n\treturn t.BargainSettlementDate\n}\n\nfunc (t *TaxVoucher3) AddBargainDate() *DateAndDateTimeChoice ", "output": "{\n\tt.BargainDate = new(DateAndDateTimeChoice)\n\treturn t.BargainDate\n}"} {"input": "package jobs\n\nimport (\n\t\"github.com/robfig/cron\"\n)\n\nconst DEFAULT_JOB_POOL_SIZE = 10\n\nvar (\n\tMainCron *cron.Cron\n\n\tworkPermits chan struct{}\n\n\tselfConcurrent bool\n)\n\n\n\nfunc init() ", "output": "{\n\tMainCron = cron.New()\n\tworkPermits = make(chan struct{}, DEFAULT_JOB_POOL_SIZE)\n\tMainCron.Start()\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\n\n\nfunc direntReclen(buf []byte) (uint64, bool) {\n\treturn readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))\n}\n\nfunc direntNamlen(buf []byte) (uint64, bool) {\n\treturn readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen))\n}\n\nfunc direntIno(buf []byte) (uint64, bool) ", "output": "{\n\treturn readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino))\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/client-go/applyconfigurations/meta/v1\"\n)\n\n\n\ntype TopologySpreadConstraintApplyConfiguration struct {\n\tMaxSkew *int32 `json:\"maxSkew,omitempty\"`\n\tTopologyKey *string `json:\"topologyKey,omitempty\"`\n\tWhenUnsatisfiable *v1.UnsatisfiableConstraintAction `json:\"whenUnsatisfiable,omitempty\"`\n\tLabelSelector *metav1.LabelSelectorApplyConfiguration `json:\"labelSelector,omitempty\"`\n}\n\n\n\nfunc TopologySpreadConstraint() *TopologySpreadConstraintApplyConfiguration {\n\treturn &TopologySpreadConstraintApplyConfiguration{}\n}\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithMaxSkew(value int32) *TopologySpreadConstraintApplyConfiguration {\n\tb.MaxSkew = &value\n\treturn b\n}\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithTopologyKey(value string) *TopologySpreadConstraintApplyConfiguration {\n\tb.TopologyKey = &value\n\treturn b\n}\n\n\n\n\n\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithLabelSelector(value *metav1.LabelSelectorApplyConfiguration) *TopologySpreadConstraintApplyConfiguration {\n\tb.LabelSelector = value\n\treturn b\n}\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithWhenUnsatisfiable(value v1.UnsatisfiableConstraintAction) *TopologySpreadConstraintApplyConfiguration ", "output": "{\n\tb.WhenUnsatisfiable = &value\n\treturn b\n}"} {"input": "package pubsub_test\n\nimport (\n\t\"testing\"\n\n\t. \"v2ray.com/core/common/signal/pubsub\"\n)\n\n\n\nfunc TestPubsub(t *testing.T) ", "output": "{\n\tservice := NewService()\n\n\tsub := service.Subscribe(\"a\")\n\tservice.Publish(\"a\", 1)\n\n\tselect {\n\tcase v := <-sub.Wait():\n\t\tif v != 1 {\n\t\t\tt.Error(\"expected subscribed value 1, but got \", v)\n\t\t}\n\tdefault:\n\t\tt.Fail()\n\t}\n\n\tsub.Close()\n\tservice.Publish(\"a\", 2)\n\n\tselect {\n\tcase <-sub.Wait():\n\t\tt.Fail()\n\tdefault:\n\t}\n\n\tservice.Cleanup()\n}"} {"input": "package stdlib\n\nimport (\n\t\"container/heap\"\n\t\"reflect\"\n)\n\n\n\n\ntype _container_heap_Interface struct {\n\tWLen func() int\n\tWLess func(i int, j int) bool\n\tWPop func() interface{}\n\tWPush func(x interface{})\n\tWSwap func(i int, j int)\n}\n\nfunc (W _container_heap_Interface) Len() int { return W.WLen() }\nfunc (W _container_heap_Interface) Less(i int, j int) bool { return W.WLess(i, j) }\nfunc (W _container_heap_Interface) Pop() interface{} { return W.WPop() }\nfunc (W _container_heap_Interface) Push(x interface{}) { W.WPush(x) }\nfunc (W _container_heap_Interface) Swap(i int, j int) { W.WSwap(i, j) }\n\nfunc init() ", "output": "{\n\tSymbols[\"container/heap\"] = map[string]reflect.Value{\n\t\t\"Fix\": reflect.ValueOf(heap.Fix),\n\t\t\"Init\": reflect.ValueOf(heap.Init),\n\t\t\"Pop\": reflect.ValueOf(heap.Pop),\n\t\t\"Push\": reflect.ValueOf(heap.Push),\n\t\t\"Remove\": reflect.ValueOf(heap.Remove),\n\n\t\t\"Interface\": reflect.ValueOf((*heap.Interface)(nil)),\n\n\t\t\"_Interface\": reflect.ValueOf((*_container_heap_Interface)(nil)),\n\t}\n}"} {"input": "package plugins\n\nimport (\n\t\"errors\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nfunc init() {\n\tplugins = make(map[string]Plugin)\n}\n\ntype backupFunc func()\ntype restoreFunc func()\ntype commandOb *cobra.Command\n\n\ntype Plugin struct {\n\tName string\n\tRestore restoreFunc\n\tBackup backupFunc\n\tCommand commandOb\n}\n\nvar plugins map[string]Plugin\n\n\nfunc Register(name string, restore restoreFunc, backup backupFunc, command commandOb) {\n\tplugins[name] = Plugin{name, restore, backup, command}\n}\n\n\nfunc Get(name string) (Plugin, error) {\n\tp, ok := plugins[name]\n\tif !ok {\n\t\treturn Plugin{}, errors.New(\"no plugin found\")\n\t}\n\treturn p, nil\n}\n\n\n\n\nfunc GetAll() map[string]Plugin ", "output": "{\n\treturn plugins\n}"} {"input": "package search\n\nimport (\n\t\"strconv\"\n)\n\n\ntype Statistics struct {\n\tNodesExplored int\n\tNodesDuplicated int\n\tMaxDepth int\n\tSolutions int\n}\n\n\n\n\nfunc (stats Statistics) String() string ", "output": "{\n\n\treturn \"[\" +\n\t\t\"NodesExplored: \" + strconv.Itoa(stats.NodesExplored) + \", \" +\n\t\t\"NodesDuplicated: \" + strconv.Itoa(stats.NodesDuplicated) + \", \" +\n\t\t\"MaxDepth: \" + strconv.Itoa(stats.MaxDepth) + \", \" +\n\t\t\"Solutions: \" + strconv.Itoa(stats.Solutions) +\n\t\t\"]\"\n\n}"} {"input": "package model\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestFormat(t *testing.T) ", "output": "{\n\tConvey(\"TestFormatExtension\", t, func() {\n\t\tsuffixData := ShouldFormatExtension()\n\t\tSo(suffixData, ShouldHaveLength, 2)\n\t\tfor t, suffix := range suffixData {\n\t\t\tif t == FormatTOML {\n\t\t\t\tSo(suffix, ShouldEqual, \".toml\")\n\t\t\t}\n\t\t\tif t == FormatINI {\n\t\t\t\tSo(suffix, ShouldEqual, \".ini\")\n\t\t\t}\n\t\t}\n\t})\n\tConvey(\"TestThemeMetaFiles\", t, func() {\n\t\tsuffixData := ShouldThemeMetaFiles()\n\t\tSo(suffixData, ShouldHaveLength, 2)\n\t\tfor t, suffix := range suffixData {\n\t\t\tif t == FormatTOML {\n\t\t\t\tSo(suffix, ShouldEqual, \"theme.toml\")\n\t\t\t}\n\t\t\tif t == FormatINI {\n\t\t\t\tSo(suffix, ShouldEqual, \"theme.ini\")\n\t\t\t}\n\t\t}\n\t})\n}"} {"input": "package fields\n\nimport \"testing\"\n\n\n\nfunc TestFieldSchemaDefaultOrZero(t *testing.T) ", "output": "{\n\tfs := &FieldSchema{\n\t\tType: TypeString,\n\t\tDefault: \"default\",\n\t}\n\n\tif d := fs.DefaultOrZero(); d != \"default\" {\n\t\tt.Fatalf(\"bad: Expected: default Got: %s\", d)\n\t}\n\n\tfs = &FieldSchema{\n\t\tType: TypeString,\n\t}\n\n\tif d := fs.DefaultOrZero(); d != \"\" {\n\t\tt.Fatalf(\"bad: Expected: \\\"\\\" Got: %s\", d)\n\t}\n}"} {"input": "package rd2wgs84\n\nimport (\n\t\"testing\"\n)\n\nvar parseTests = []struct {\n\tin RD\n\tout *WGS84\n}{\n\t{RD{163835.370083, 446830.763585}, &WGS84{52.00977421758342, 5.515894213047998}},\n}\n\n\n\nfunc TestConvert(t *testing.T) ", "output": "{\n\tfor i, tt := range parseTests {\n\t\twgs := Convert(tt.in.X, tt.in.Y)\n\t\tif wgs.Latitude != tt.out.Latitude || wgs.Longitude != tt.out.Longitude {\n\t\t\tt.Errorf(\"%d. Convert(%f, %f) => %+v returned, expected %+v\", i, tt.in.X, tt.in.Y, wgs, tt.out)\n\t\t}\n\t}\n}"} {"input": "package containerregistry\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" containerregistry/2018-09-01\"\n}"} {"input": "package sctp\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\ntype paramHeader struct {\n\ttyp paramType\n\tlen int\n\traw []byte\n}\n\nconst (\n\tparamHeaderLength = 4\n)\n\n\n\nfunc (p *paramHeader) unmarshal(raw []byte) {\n\tparamLengthPlusHeader := binary.BigEndian.Uint16(raw[2:])\n\tparamLength := paramLengthPlusHeader - initOptionalVarHeaderLength\n\n\tp.typ = paramType(binary.BigEndian.Uint16(raw[0:]))\n\tp.raw = raw[paramHeaderLength : paramHeaderLength+paramLength]\n\tp.len = int(paramLengthPlusHeader)\n}\n\nfunc (p *paramHeader) length() int {\n\treturn p.len\n}\n\n\nfunc (p paramHeader) String() string {\n\treturn fmt.Sprintf(\"%s (%d): %s\", p.typ, p.len, p.raw)\n}\n\nfunc (p *paramHeader) marshal() ([]byte, error) ", "output": "{\n\tparamLengthPlusHeader := paramHeaderLength + len(p.raw)\n\n\trawParam := make([]byte, paramLengthPlusHeader)\n\tbinary.BigEndian.PutUint16(rawParam[0:], uint16(p.typ))\n\tbinary.BigEndian.PutUint16(rawParam[2:], uint16(paramLengthPlusHeader))\n\tcopy(rawParam[paramHeaderLength:], p.raw)\n\n\treturn rawParam, nil\n}"} {"input": "package controller\n\nimport (\n\t\"global\"\n\t\"net/http\"\n\t\"route\"\n\t\"strings\"\n)\n\n\ntype StaticController struct{}\n\nfunc (self StaticController) RegisterRoutes() {\n\troute.HandleFunc(\"/static/\", self.static)\n}\n\n\n\n\nfunc (StaticController) static(w http.ResponseWriter, r *http.Request) ", "output": "{\n\treqURI := r.RequestURI\n\tif strings.HasSuffix(reqURI, \"/\") {\n\t\thttp.NotFound(w, r)\n\t} else {\n\t\tfileHandler := http.StripPrefix(\"/static/\", http.FileServer(http.Dir(global.App.ProjectRoot+\"/static\")))\n\t\tfileHandler.ServeHTTP(w, r)\n\t}\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/astaxie/beego\"\n\t\"github.com/RayFantasyStudio/blog/models\"\n\t\"fmt\"\n)\n\nvar owner string\n\nfunc init() {\n\towner = beego.AppConfig.String(\"owner\")\n}\n\n\n\nfunc NewNoticeFlash(c *beego.Controller, msg string, args ...interface{}) {\n\tvar data string\n\tif len(args) == 0 {\n\t\tdata = msg\n\t} else {\n\t\tdata = fmt.Sprintf(msg, args...)\n\t}\n\tflash := beego.NewFlash()\n\tflash.Notice(data)\n\tflash.Store(c)\n}\n\nfunc initHeaderFooterData(c *beego.Controller, title string) (user *models.User, err error) ", "output": "{\n\tc.Data[\"Owner\"] = owner\n\n\tc.Data[\"Title\"] = title\n\n\tif token := c.Ctx.GetCookie(\"token\"); len(token) != 0 {\n\t\tif user, err = models.GetUserByToken(token); err != nil {\n\t\t\tbeego.Error(err)\n\t\t} else {\n\t\t\tc.Data[\"IsLogin\"] = true\n\t\t\tc.Data[\"User\"] = user\n\t\t\tvar avatar_path string\n\t\t\tavatar_path, err = models.GetUserAvatar(int64(user.Id))\n\t\t\tc.Data[\"avatar_path\"] = avatar_path\n\t\t\tbeego.Info(avatar_path)\n\t\t}\n\t}\n\n\tflash := beego.ReadFromRequest(c)\n\tif n, ok := flash.Data[\"notice\"]; ok {\n\t\tc.Data[\"Message\"] = n\n\t}\n\treturn\n}"} {"input": "package hilbert\n\ntype mockRectangle struct {\n\txlow, ylow, xhigh, yhigh int32\n}\n\nfunc (mr *mockRectangle) LowerLeft() (int32, int32) {\n\treturn mr.xlow, mr.ylow\n}\n\nfunc (mr *mockRectangle) UpperRight() (int32, int32) {\n\treturn mr.xhigh, mr.yhigh\n}\n\n\n\nfunc newMockRectangle(xlow, ylow, xhigh, yhigh int32) *mockRectangle ", "output": "{\n\treturn &mockRectangle{\n\t\txlow: xlow,\n\t\tylow: ylow,\n\t\txhigh: xhigh,\n\t\tyhigh: yhigh,\n\t}\n}"} {"input": "package cache\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"time\"\n)\n\ntype Cache struct {\n\tmemoryCache map[string][]byte\n\trefreshTime int\n}\n\n\n\nfunc (c *Cache) SetCache(name string, data []byte) error {\n\terr := ioutil.WriteFile(\"/tmp/\"+name, data, 0644)\n\tif err == nil {\n\t\tc.memoryCache[name] = data\n\t}\n\treturn err\n}\n\nfunc (c *Cache) GetCache(name string) ([]byte, error) {\n\tif dat, ok := c.memoryCache[name]; ok {\n\t\treturn dat, nil\n\t}\n\n\tf, err := os.Stat(\"/tmp/\" + name)\n\tif os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\n\tif time.Since(f.ModTime()).Minutes() > float64(c.refreshTime) {\n\t\treturn nil, fmt.Errorf(\"[GetCache] %s\", \"cache invalidate\")\n\t}\n\n\tdat, err := ioutil.ReadFile(\"/tmp/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dat, nil\n}\n\nfunc NewCache(t int) *Cache ", "output": "{\n\treturn &Cache{\n\t\tmemoryCache: make(map[string][]byte),\n\t\trefreshTime: t,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/stripe/smokescreen/cmd\"\n\t\"github.com/stripe/smokescreen/pkg/smokescreen\"\n)\n\n\n\n\n\n\n\nfunc main() {\n\tconf, err := cmd.NewConfiguration(nil, nil)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Could not create configuration: %v\", err)\n\t} else if conf != nil {\n\t\tconf.RoleFromRequest = defaultRoleFromRequest\n\n\t\tconf.Log.Formatter = &logrus.JSONFormatter{}\n\n\t\tadapter := &smokescreen.Log2LogrusWriter{\n\t\t\tEntry: conf.Log.WithField(\"stdlog\", \"1\"),\n\t\t}\n\n\t\tlog.SetOutput(adapter)\n\t\tlog.SetFlags(0)\n\t\tsmokescreen.StartWithConfig(conf, nil)\n\t}\n}\n\nfunc defaultRoleFromRequest(req *http.Request) (string, error) ", "output": "{\n\tif req.TLS == nil {\n\t\treturn \"\", smokescreen.MissingRoleError(\"defaultRoleFromRequest requires TLS\")\n\t}\n\tif len(req.TLS.PeerCertificates) == 0 {\n\t\treturn \"\", smokescreen.MissingRoleError(\"client did not provide certificate\")\n\t}\n\treturn req.TLS.PeerCertificates[0].Subject.CommonName, nil\n}"} {"input": "package credential\n\nimport (\n\t\"pharmer.dev/cloud/apis\"\n\tv1 \"pharmer.dev/cloud/apis/cloud/v1\"\n\n\t\"github.com/spf13/pflag\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\ntype Linode struct {\n\tCommonSpec\n\n\ttoken string\n}\n\n\n\nfunc (c *Linode) LoadFromEnv() {\n\tc.CommonSpec.LoadFromEnv(c.Format())\n}\n\nfunc (c Linode) IsValid() (bool, error) {\n\treturn c.CommonSpec.IsValid(c.Format())\n}\n\nfunc (c *Linode) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(&c.token, apis.Linode+\".\"+LinodeAPIToken, c.token, \"Linode api token\")\n}\n\nfunc (_ Linode) RequiredFlags() []string {\n\treturn []string{apis.Linode + \".\" + LinodeAPIToken}\n}\n\nfunc (_ Linode) Format() v1.CredentialFormat {\n\treturn v1.CredentialFormat{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: apis.Linode,\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tapis.KeyClusterCredential: \"\",\n\t\t\t\tapis.KeyDNSCredential: \"\",\n\t\t\t},\n\t\t},\n\t\tSpec: v1.CredentialFormatSpec{\n\t\t\tProvider: apis.Linode,\n\t\t\tDisplayFormat: \"field\",\n\t\t\tFields: []v1.CredentialField{\n\t\t\t\t{\n\t\t\t\t\tEnvconfig: \"LINODE_TOKEN\",\n\t\t\t\t\tForm: \"linode_token\",\n\t\t\t\t\tJSON: LinodeAPIToken,\n\t\t\t\t\tLabel: \"Token\",\n\t\t\t\t\tInput: \"password\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (c Linode) APIToken() string ", "output": "{ return get(c.Data, LinodeAPIToken, c.token) }"} {"input": "package cmd\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/subcommands\"\n\t\"gvisor.dev/gvisor/runsc/config\"\n\t\"gvisor.dev/gvisor/runsc/container\"\n\t\"gvisor.dev/gvisor/runsc/flag\"\n\t\"gvisor.dev/gvisor/runsc/specutils\"\n)\n\n\ntype Start struct{}\n\n\n\n\n\nfunc (*Start) Synopsis() string {\n\treturn \"start a secure container\"\n}\n\n\nfunc (*Start) Usage() string {\n\treturn `start - start a secure container.`\n}\n\n\nfunc (*Start) SetFlags(*flag.FlagSet) {}\n\n\nfunc (*Start) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {\n\tif f.NArg() != 1 {\n\t\tf.Usage()\n\t\treturn subcommands.ExitUsageError\n\t}\n\n\tid := f.Arg(0)\n\tconf := args[0].(*config.Config)\n\n\tc, err := container.Load(conf.RootDir, container.FullID{ContainerID: id}, container.LoadOpts{})\n\tif err != nil {\n\t\tFatalf(\"loading container: %v\", err)\n\t}\n\tif _, err := specutils.ReadSpec(c.BundleDir, conf); err != nil {\n\t\tFatalf(\"reading spec: %v\", err)\n\t}\n\n\tif err := c.Start(conf); err != nil {\n\t\tFatalf(\"starting container: %v\", err)\n\t}\n\treturn subcommands.ExitSuccess\n}\n\nfunc (*Start) Name() string ", "output": "{\n\treturn \"start\"\n}"} {"input": "package vision_test\n\nimport (\n\t\"context\"\n\n\tvision \"cloud.google.com/go/vision/apiv1\"\n\tvisionpb \"google.golang.org/genproto/googleapis/cloud/vision/v1\"\n)\n\nfunc ExampleNewImageAnnotatorClient() {\n\tctx := context.Background()\n\tc, err := vision.NewImageAnnotatorClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\nfunc ExampleImageAnnotatorClient_BatchAnnotateImages() {\n\tctx := context.Background()\n\tc, err := vision.NewImageAnnotatorClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &visionpb.BatchAnnotateImagesRequest{\n\t}\n\tresp, err := c.BatchAnnotateImages(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\n\n\nfunc ExampleImageAnnotatorClient_AsyncBatchAnnotateImages() {\n\tctx := context.Background()\n\tc, err := vision.NewImageAnnotatorClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &visionpb.AsyncBatchAnnotateImagesRequest{\n\t}\n\top, err := c.AsyncBatchAnnotateImages(ctx, req)\n\tif err != nil {\n\t}\n\n\tresp, err := op.Wait(ctx)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleImageAnnotatorClient_AsyncBatchAnnotateFiles() {\n\tctx := context.Background()\n\tc, err := vision.NewImageAnnotatorClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &visionpb.AsyncBatchAnnotateFilesRequest{\n\t}\n\top, err := c.AsyncBatchAnnotateFiles(ctx, req)\n\tif err != nil {\n\t}\n\n\tresp, err := op.Wait(ctx)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleImageAnnotatorClient_BatchAnnotateFiles() ", "output": "{\n\tctx := context.Background()\n\tc, err := vision.NewImageAnnotatorClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &visionpb.BatchAnnotateFilesRequest{\n\t}\n\tresp, err := c.BatchAnnotateFiles(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}"} {"input": "package v1beta1\n\nimport (\n\t\"context\"\n\n\t\"knative.dev/pkg/apis\"\n\t\"knative.dev/pkg/kmp\"\n)\n\nfunc (et *EventType) Validate(ctx context.Context) *apis.FieldError {\n\treturn et.Spec.Validate(ctx).ViaField(\"spec\")\n}\n\nfunc (ets *EventTypeSpec) Validate(ctx context.Context) *apis.FieldError {\n\tvar errs *apis.FieldError\n\tif ets.Type == \"\" {\n\t\tfe := apis.ErrMissingField(\"type\")\n\t\terrs = errs.Also(fe)\n\t}\n\treturn errs\n}\n\n\n\nfunc (et *EventType) CheckImmutableFields(ctx context.Context, original *EventType) *apis.FieldError ", "output": "{\n\tif original == nil {\n\t\treturn nil\n\t}\n\n\tif diff, err := kmp.ShortDiff(original.Spec, et.Spec); err != nil {\n\t\treturn &apis.FieldError{\n\t\t\tMessage: \"Failed to diff EventType\",\n\t\t\tPaths: []string{\"spec\"},\n\t\t\tDetails: err.Error(),\n\t\t}\n\t} else if diff != \"\" {\n\t\treturn &apis.FieldError{\n\t\t\tMessage: \"Immutable fields changed (-old +new)\",\n\t\t\tPaths: []string{\"spec\"},\n\t\t\tDetails: diff,\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package gcetasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realAddress Address\n\n\nfunc (o *Address) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realAddress\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = Address(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &Address{}\n\n\nfunc (o *Address) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\n\n\n\nvar _ fi.HasName = &Address{}\n\n\nfunc (o *Address) GetName() *string {\n\treturn o.Name\n}\n\n\nfunc (o *Address) SetName(name string) {\n\to.Name = &name\n}\n\n\nfunc (o *Address) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *Address) SetLifecycle(lifecycle fi.Lifecycle) ", "output": "{\n\to.Lifecycle = &lifecycle\n}"} {"input": "package godspeed\n\nimport (\n\t\"io\"\n\t\"net/http\"\n)\n\ntype bodyWrapperFactory func(http.ResponseWriter) io.Writer\n\ntype bodyWrapper struct {\n\trespw http.ResponseWriter\n\tw io.Writer\n\tposthandler bodyWrapperFactory\n}\n\nfunc (w *bodyWrapper) Header() http.Header {\n\treturn w.respw.Header()\n}\n\nfunc (w *bodyWrapper) Write(data []byte) (int, error) {\n\tif w.w == nil {\n\t\tw.w = w.posthandler(w.respw)\n\t}\n\treturn w.w.Write(data)\n}\n\nfunc (w *bodyWrapper) WriteHeader(s int) {\n\tw.respw.WriteHeader(s)\n}\n\nfunc (w *bodyWrapper) Close() error {\n\tvar err error\n\tif c, ok := w.w.(io.Closer); ok {\n\t\terr = c.Close()\n\t}\n\treturn err\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc wrapBody(respw http.ResponseWriter, writerGen bodyWrapperFactory) *bodyWrapper ", "output": "{\n\treturn &bodyWrapper{\n\t\trespw: respw,\n\t\tposthandler: writerGen,\n\t}\n}"} {"input": "package term\n\nimport \"github.com/Azure/go-ansiterm/winterm\"\n\n\n\n\nfunc GetWinsize(fd uintptr) (*Winsize, error) ", "output": "{\n\tinfo, err := winterm.GetConsoleScreenBufferInfo(fd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twinsize := &Winsize{\n\t\tWidth: uint16(info.Window.Right - info.Window.Left + 1),\n\t\tHeight: uint16(info.Window.Bottom - info.Window.Top + 1),\n\t}\n\n\treturn winsize, nil\n}"} {"input": "package etsi\n\nimport (\n\t\"encoding/asn1\"\n\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/util\"\n)\n\ntype qcStatemQcSscdValid struct{}\n\nfunc init() {\n\tlint.RegisterLint(&lint.Lint{\n\t\tName: \"e_qcstatem_qcsscd_valid\",\n\t\tDescription: \"Checks that a QC Statement of the type id-etsi-qcs-QcSSCD has the correct form\",\n\t\tCitation: \"ETSI EN 319 412 - 5 V2.2.1 (2017 - 11) / Section 4.2.2\",\n\t\tSource: lint.EtsiEsi,\n\t\tEffectiveDate: util.EtsiEn319_412_5_V2_2_1_Date,\n\t\tLint: &qcStatemQcSscdValid{},\n\t})\n}\n\nfunc (this *qcStatemQcSscdValid) getStatementOid() *asn1.ObjectIdentifier {\n\treturn &util.IdEtsiQcsQcSSCD\n}\n\nfunc (l *qcStatemQcSscdValid) Initialize() error {\n\treturn nil\n}\n\nfunc (l *qcStatemQcSscdValid) CheckApplies(c *x509.Certificate) bool {\n\tif !util.IsExtInCert(c, util.QcStateOid) {\n\t\treturn false\n\t}\n\tif util.ParseQcStatem(util.GetExtFromCert(c, util.QcStateOid).Value, *l.getStatementOid()).IsPresent() {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc (l *qcStatemQcSscdValid) Execute(c *x509.Certificate) *lint.LintResult ", "output": "{\n\n\terrString := \"\"\n\text := util.GetExtFromCert(c, util.QcStateOid)\n\ts := util.ParseQcStatem(ext.Value, *l.getStatementOid())\n\terrString += s.GetErrorInfo()\n\n\tif len(errString) == 0 {\n\t\treturn &lint.LintResult{Status: lint.Pass}\n\t} else {\n\t\treturn &lint.LintResult{Status: lint.Error, Details: errString}\n\t}\n}"} {"input": "package vfs\n\nimport (\n\t\"path\"\n\n\tgofig \"github.com/akutz/gofig/types\"\n\n\t\"github.com/rexray/rexray/libstorage/api/context\"\n\t\"github.com/rexray/rexray/libstorage/api/registry\"\n\t\"github.com/rexray/rexray/libstorage/api/types\"\n)\n\nconst (\n\tName = \"vfs\"\n)\n\nfunc init() {\n\tregistry.RegisterConfigReg(\n\t\t\"VFS\",\n\t\tfunc(ctx types.Context, r gofig.ConfigRegistration) {\n\t\t\tvfsRoot := path.Join(context.MustPathConfig(ctx).Lib, \"vfs\")\n\t\t\tr.Key(\n\t\t\t\tgofig.String,\n\t\t\t\t\"\",\n\t\t\t\tvfsRoot,\n\t\t\t\t\"\",\n\t\t\t\t\"vfs.root\")\n\t\t})\n}\n\n\nfunc RootDir(config gofig.Config) string {\n\treturn config.GetString(\"vfs.root\")\n}\n\n\n\n\n\nfunc VolumesDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"vol\")\n}\n\n\nfunc SnapshotsDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"snap\")\n}\n\nfunc DeviceFilePath(config gofig.Config) string ", "output": "{\n\treturn path.Join(RootDir(config), \"dev\")\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n\t\"github.com/zvelo/envetcd\"\n\t\"github.com/zvelo/zvelo-services/util\"\n)\n\nfunc init() {\n\tconfig.EnvEtcd = &envetcd.Config{\n\t\tEtcd: &util.EtcdConfig{\n\t\t\tPeers: []string{\"127.0.0.1:4001\"},\n\t\t},\n\t}\n}\n\n\n\nfunc TestCLI(t *testing.T) ", "output": "{\n\tConvey(\"cli should work\", t, func() {\n\t\tConvey(\"start should execute and not panic\", func() {\n\t\t\tSo(func() { start(\"echo\", \"-n\") }, ShouldNotPanic)\n\t\t})\n\t})\n}"} {"input": "package events\n\nimport (\n\t\"errors\"\n\n\t\"github.com/miketheprogrammer/go-thrust/lib/commands\"\n\t\"github.com/miketheprogrammer/go-thrust/lib/dispatcher\"\n)\n\n\nfunc NewHandler(event string, fn interface{}) (ThrustEventHandler, error) {\n\th := ThrustEventHandler{}\n\th.Event = event\n\th.Type = \"event\"\n\terr := h.SetHandleFunc(fn)\n\tdispatcher.RegisterHandler(h)\n\treturn h, err\n}\n\n\ntype Handler interface {\n\tHandle(cr commands.CommandResponse)\n\tRegister()\n\tSetHandleFunc(fn interface{})\n}\n\ntype ThrustEventHandler struct {\n\tType string\n\tEvent string\n\tHandler interface{}\n}\n\nfunc (teh ThrustEventHandler) Handle(cr commands.CommandResponse) {\n\tif cr.Action != \"event\" {\n\t\treturn\n\t}\n\tif cr.Type != teh.Event && teh.Event != \"*\" {\n\t\treturn\n\t}\n\tcr.Event.Type = cr.Type\n\tif fn, ok := teh.Handler.(func(commands.CommandResponse)); ok == true {\n\t\tfn(cr)\n\t\treturn\n\t}\n\tif fn, ok := teh.Handler.(func(commands.EventResult)); ok == true {\n\t\tfn(cr.Event)\n\t\treturn\n\t}\n}\n\n\n\nfunc (teh *ThrustEventHandler) SetHandleFunc(fn interface{}) error ", "output": "{\n\tif fn, ok := fn.(func(commands.CommandResponse)); ok == true {\n\t\tteh.Handler = fn\n\t\treturn nil\n\t}\n\tif fn, ok := fn.(func(commands.EventResult)); ok == true {\n\t\tteh.Handler = fn\n\t\treturn nil\n\t}\n\n\treturn errors.New(\"Invalid Handler Definition\")\n}"} {"input": "package recovery\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"github.com/containous/traefik/middlewares\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nconst (\n\ttypeName = \"Recovery\"\n)\n\ntype recovery struct {\n\tnext http.Handler\n\tname string\n}\n\n\nfunc New(ctx context.Context, next http.Handler, name string) (http.Handler, error) {\n\tmiddlewares.GetLogger(ctx, name, typeName).Debug(\"Creating middleware\")\n\n\treturn &recovery{\n\t\tnext: next,\n\t\tname: name,\n\t}, nil\n}\n\n\n\nfunc recoverFunc(logger logrus.FieldLogger, rw http.ResponseWriter) {\n\tif err := recover(); err != nil {\n\t\tlogger.Errorf(\"Recovered from panic in http handler: %+v\", err)\n\t\thttp.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t}\n}\n\nfunc (re *recovery) ServeHTTP(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\tdefer recoverFunc(middlewares.GetLogger(req.Context(), re.name, typeName), rw)\n\tre.next.ServeHTTP(rw, req)\n}"} {"input": "package plugins\n\nimport (\n\t\"errors\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nfunc init() {\n\tplugins = make(map[string]Plugin)\n}\n\ntype backupFunc func()\ntype restoreFunc func()\ntype commandOb *cobra.Command\n\n\ntype Plugin struct {\n\tName string\n\tRestore restoreFunc\n\tBackup backupFunc\n\tCommand commandOb\n}\n\nvar plugins map[string]Plugin\n\n\n\n\n\nfunc Get(name string) (Plugin, error) {\n\tp, ok := plugins[name]\n\tif !ok {\n\t\treturn Plugin{}, errors.New(\"no plugin found\")\n\t}\n\treturn p, nil\n}\n\n\nfunc GetAll() map[string]Plugin {\n\treturn plugins\n}\n\nfunc Register(name string, restore restoreFunc, backup backupFunc, command commandOb) ", "output": "{\n\tplugins[name] = Plugin{name, restore, backup, command}\n}"} {"input": "package flog\n\nimport \"github.com/Sirupsen/logrus\"\n\ntype Parameter interface {\n\tConvert() map[string]interface{}\n}\n\ntype Fields struct {\n\tEvent string\n\tError error\n}\n\nfunc (f Fields) Convert() map[string]interface{} {\n\tfields := map[string]interface{}{}\n\n\tif f.Event != \"\" {\n\t\tfields[\"event\"] = f.Event\n\t}\n\n\tif f.Error != nil {\n\t\tfields[\"error\"] = f.Error\n\t}\n\n\treturn fields\n}\n\ntype Details map[string]interface{}\n\nfunc (d Details) Convert() map[string]interface{} {\n\treturn d\n}\n\ntype DebugFields map[string]interface{}\n\nfunc (d DebugFields) Convert() map[string]interface{} {\n\treturn map[string]interface{}{}\n}\n\n\n\nfunc Debug(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Debug(msg)\n}\n\nfunc Info(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Info(msg)\n}\n\nfunc Warn(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Warning(msg)\n}\n\nfunc Error(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Error(msg)\n}\n\nfunc Fatal(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Fatal(msg)\n}\n\nfunc Panic(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Panic(msg)\n}\n\nfunc transform(params []Parameter) logrus.Fields ", "output": "{\n\tlogrusFields := logrus.Fields{}\n\n\tfor _, p := range params {\n\t\tfieldMap := p.Convert()\n\n\t\tfor k, v := range fieldMap {\n\t\t\tlogrusFields[k] = v\n\t\t}\n\t}\n\n\treturn logrusFields\n}"} {"input": "package plugins\n\nimport (\n\t\"../answers\"\n\t\"../ircclient\"\n\t\"strings\"\n)\n\ntype DongPlugin struct {\n\tic *ircclient.IRCClient\n}\n\nfunc (q *DongPlugin) String() string {\n\treturn \"dong\"\n}\n\nfunc (q *DongPlugin) Info() string {\n\treturn `sends back a dong sound for every \\a`\n}\n\nfunc (q *DongPlugin) Usage(cmd string) string {\n\treturn \"\"\n}\n\nfunc (q *DongPlugin) Register(cl *ircclient.IRCClient) {\n\tq.ic = cl\n}\n\nfunc (q *DongPlugin) Unregister() {\n\treturn\n}\n\nfunc (q *DongPlugin) ProcessLine(msg *ircclient.IRCMessage) {\n\tif msg.Command != \"PRIVMSG\" {\n\t\treturn\n\t}\n\n\tcount := strings.Count(msg.Args[0], `\\a`)\n\tcount -= strings.Count(msg.Args[0], `\\\\a`)\n\tif count < 1 {\n\t\treturn\n\t}\n\n\tstr := answers.RandStr(\"dong\")\n\tmessage := \"\"\n\n\tfor i := 0; i < count; i++ {\n\t\tmessage += str + \" \"\n\t}\n\n\tq.ic.ReplyMsg(msg, message)\n}\n\n\n\nfunc (q *DongPlugin) ProcessCommand(cmd *ircclient.IRCCommand) ", "output": "{\n\treturn\n}"} {"input": "package filters\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"k8s.io/kubernetes/pkg/auth/authorizer\"\n\t\"k8s.io/kubernetes/pkg/util/runtime\"\n)\n\n\nfunc badGatewayError(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.WriteHeader(http.StatusBadGateway)\n\tfmt.Fprintf(w, \"Bad Gateway: %#v\", req.RequestURI)\n}\n\n\nfunc forbidden(attributes authorizer.Attributes, w http.ResponseWriter, req *http.Request, reason string) {\n\tmsg := forbiddenMessage(attributes)\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.WriteHeader(http.StatusForbidden)\n\tfmt.Fprintf(w, \"%s: %q\", msg, reason)\n}\n\nfunc forbiddenMessage(attributes authorizer.Attributes) string {\n\tusername := \"\"\n\tif user := attributes.GetUser(); user != nil {\n\t\tusername = user.GetName()\n\t}\n\n\tresource := attributes.GetResource()\n\tif group := attributes.GetAPIGroup(); len(group) > 0 {\n\t\tresource = resource + \".\" + group\n\t}\n\n\tif ns := attributes.GetNamespace(); len(ns) > 0 {\n\t\treturn fmt.Sprintf(\"User %q cannot %s %s in the namespace %q.\", username, attributes.GetVerb(), resource, ns)\n\t}\n\n\treturn fmt.Sprintf(\"User %q cannot %s %s at the cluster scope.\", username, attributes.GetVerb(), resource)\n}\n\n\n\n\nfunc internalError(w http.ResponseWriter, req *http.Request, err error) ", "output": "{\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.WriteHeader(http.StatusInternalServerError)\n\tfmt.Fprintf(w, \"Internal Server Error: %#v: %v\", req.RequestURI, err)\n\truntime.HandleError(err)\n}"} {"input": "package getmodules\n\nimport (\n\t\"path\"\n\n\tgetter \"github.com/hashicorp/go-getter\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ExpandSubdirGlobs(instDir string, subDir string) (string, error) {\n\treturn getter.SubdirGlob(instDir, subDir)\n}\n\nfunc SplitPackageSubdir(given string) (packageAddr, subDir string) ", "output": "{\n\tpackageAddr, subDir = getter.SourceDirSubdir(given)\n\tif subDir != \"\" {\n\t\tsubDir = path.Clean(subDir)\n\t}\n\treturn packageAddr, subDir\n}"} {"input": "package v1\n\nimport (\n\t\"testing\"\n\n\t\"github.com/gophercloud/gophercloud/acceptance/clients\"\n\t\"github.com/gophercloud/gophercloud/acceptance/tools\"\n\t\"github.com/gophercloud/gophercloud/openstack/db/v1/flavors\"\n)\n\n\n\nfunc TestFlavorsGet(t *testing.T) {\n\tclient, err := clients.NewDBV1Client()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create a DB client: %v\", err)\n\t}\n\n\tallPages, err := flavors.List(client).AllPages()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to retrieve flavors: %v\", err)\n\t}\n\n\tallFlavors, err := flavors.ExtractFlavors(allPages)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to extract flavors: %v\", err)\n\t}\n\n\tif len(allFlavors) > 0 {\n\t\tflavor, err := flavors.Get(client, allFlavors[0].StrID).Extract()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unable to get flavor: %v\", err)\n\t\t}\n\n\t\ttools.PrintResource(t, flavor)\n\t}\n}\n\nfunc TestFlavorsList(t *testing.T) ", "output": "{\n\tclient, err := clients.NewDBV1Client()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create a DB client: %v\", err)\n\t}\n\n\tallPages, err := flavors.List(client).AllPages()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to retrieve flavors: %v\", err)\n\t}\n\n\tallFlavors, err := flavors.ExtractFlavors(allPages)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to extract flavors: %v\", err)\n\t}\n\n\tfor _, flavor := range allFlavors {\n\t\ttools.PrintResource(t, &flavor)\n\t}\n}"} {"input": "package osin\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestURIValidate(t *testing.T) ", "output": "{\n\tif err := ValidateUri(\"http://localhost:14000/appauth\", \"http://localhost:14000/appauth\"); err != nil {\n\t\tt.Errorf(\"V1: %s\", err)\n\t}\n\n\tif err := ValidateUri(\"http://localhost:14000/appauth\", \"http://localhost:14000/app\"); err == nil {\n\t\tt.Error(\"V2 should have failed\")\n\t}\n\n\tif err := ValidateUri(\"http://www.google.com/myapp\", \"http://www.google.com/myapp/interface/implementation\"); err != nil {\n\t\tt.Errorf(\"V3: %s\", err)\n\t}\n\n\tif err := ValidateUri(\"http://www.google.com/myapp\", \"http://www2.google.com/myapp\"); err == nil {\n\t\tt.Error(\"V4 should have failed\")\n\t}\n}"} {"input": "package restic\n\nimport \"syscall\"\n\nfunc (node Node) restoreSymlinkTimestamps(path string, utimes [2]syscall.Timespec) error {\n\treturn nil\n}\n\nfunc (node Node) device() int {\n\treturn int(node.Device)\n}\n\n\nfunc (s statUnix) mtim() syscall.Timespec { return s.Mtimespec }\nfunc (s statUnix) ctim() syscall.Timespec { return s.Ctimespec }\n\n\nfunc Getxattr(path, name string) ([]byte, error) {\n\treturn nil, nil\n}\n\n\n\nfunc Listxattr(path string) ([]string, error) {\n\treturn nil, nil\n}\n\n\nfunc Setxattr(path, name string, data []byte) error {\n\treturn nil\n}\n\nfunc (s statUnix) atim() syscall.Timespec ", "output": "{ return s.Atimespec }"} {"input": "package goxpath\n\nimport (\n\txml \"encoding/xml\"\n)\n\ntype FuncOpts func(*Opts)\n\nfunc MustParse(_ string) XPathExec {\n\treturn XPathExec{}\n}\n\ntype Opts struct {\n\tNS map[string]string\n\tFuncs map[xml.Name]interface{}\n\tVars map[string]interface{}\n}\n\nfunc Parse(_ string) (XPathExec, error) {\n\treturn XPathExec{}, nil\n}\n\nfunc ParseExec(_ string, _ interface{}, _ ...FuncOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\ntype XPathExec struct{}\n\nfunc (_ XPathExec) Exec(_ interface{}, _ ...FuncOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\n\n\nfunc (_ XPathExec) ExecNode(_ interface{}, _ ...FuncOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\nfunc (_ XPathExec) ExecNum(_ interface{}, _ ...FuncOpts) (float64, error) {\n\treturn 0, nil\n}\n\nfunc (_ XPathExec) MustExec(_ interface{}, _ ...FuncOpts) interface{} {\n\treturn nil\n}\n\nfunc (_ XPathExec) ExecBool(_ interface{}, _ ...FuncOpts) (bool, error) ", "output": "{\n\treturn false, nil\n}"} {"input": "package chshare\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\n\ntype Logger struct {\n\tprefix string\n\tlogger *log.Logger\n\tInfo, Debug bool\n}\n\nfunc NewLogger(prefix string) *Logger {\n\treturn NewLoggerFlag(prefix, log.Ldate|log.Ltime)\n}\n\nfunc NewLoggerFlag(prefix string, flag int) *Logger {\n\tl := &Logger{\n\t\tprefix: prefix,\n\t\tlogger: log.New(os.Stdout, \"\", flag),\n\t\tInfo: false,\n\t\tDebug: false,\n\t}\n\treturn l\n}\n\nfunc (l *Logger) Infof(f string, args ...interface{}) {\n\tif l.Info {\n\t\tl.logger.Printf(l.prefix+\": \"+f, args...)\n\t}\n}\n\nfunc (l *Logger) Debugf(f string, args ...interface{}) {\n\tif l.Debug {\n\t\tl.logger.Printf(l.prefix+\": \"+f, args...)\n\t}\n}\n\n\n\nfunc (l *Logger) Fork(prefix string, args ...interface{}) *Logger {\n\targs = append([]interface{}{l.prefix}, args...)\n\tll := NewLogger(fmt.Sprintf(\"%s: \"+prefix, args...))\n\tll.Info = l.Info\n\tll.Debug = l.Debug\n\treturn ll\n}\n\nfunc (l *Logger) Prefix() string {\n\treturn l.prefix\n}\n\nfunc (l *Logger) Errorf(f string, args ...interface{}) error ", "output": "{\n\treturn fmt.Errorf(l.prefix+\": \"+f, args...)\n}"} {"input": "package gtimer\n\n\nfunc (h *priorityQueueHeap) Len() int {\n\treturn len(h.array)\n}\n\n\n\nfunc (h *priorityQueueHeap) Less(i, j int) bool {\n\treturn h.array[i].priority < h.array[j].priority\n}\n\n\nfunc (h *priorityQueueHeap) Swap(i, j int) {\n\tif len(h.array) == 0 {\n\t\treturn\n\t}\n\th.array[i], h.array[j] = h.array[j], h.array[i]\n}\n\n\nfunc (h *priorityQueueHeap) Push(x interface{}) {\n\th.array = append(h.array, x.(priorityQueueItem))\n}\n\n\n\n\nfunc (h *priorityQueueHeap) Pop() interface{} ", "output": "{\n\tlength := len(h.array)\n\tif length == 0 {\n\t\treturn nil\n\t}\n\titem := h.array[length-1]\n\th.array = h.array[0 : length-1]\n\treturn item\n}"} {"input": "package data\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com/go-ini/ini\"\n\t\"gopkg.in/mgo.v2\"\n)\n\n\ntype MongoConnection struct {\n\thost string\n\tport int\n\tuser string\n\tpass string\n\tname string\n}\n\n\n\n\n\nfunc (connection *MongoConnection) Connect() (*mgo.Session, error) {\n\n\tconnectionURL := connection.host + \":\" + strconv.Itoa(connection.port)\n\n\tdialInfo := new(mgo.DialInfo)\n\tdialInfo.Username = connection.user\n\tdialInfo.Password = connection.pass\n\tdialInfo.Addrs = []string{connectionURL}\n\tdialInfo.Database = connection.name\n\n\tsession, err := mgo.DialWithInfo(dialInfo)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsession.SetMode(mgo.Monotonic, true)\n\n\treturn session, nil\n}\n\nfunc NewMongoConnection() *MongoConnection ", "output": "{\n\n\tfileReader, err := ini.InsensitiveLoad(\"database.conf\")\n\tif err != nil {\n\t\tfmt.Println(\"database.conf not found\")\n\t\treturn nil\n\t}\n\n\tsection := fileReader.Section(\"MONGO\")\n\n\thost := section.Key(\"database.host\").Value()\n\tport := section.Key(\"database.port\").Value()\n\tuser := section.Key(\"database.user\").Value()\n\tpass := section.Key(\"database.pass\").Value()\n\tname := section.Key(\"database.name\").Value()\n\n\tmongoConn := new(MongoConnection)\n\n\tmongoConn.host = host\n\tmongoConn.port, _ = strconv.Atoi(port)\n\tmongoConn.user = user\n\tmongoConn.pass = pass\n\tmongoConn.name = name\n\n\treturn mongoConn\n\n}"} {"input": "package ini\n\nimport (\n\t\"fmt\"\n\t\"github.com/robfig/config\"\n\t\"github.com/mabetle/mcore\"\n)\n\n\n\n\ntype IniConfig struct {\n\tLocations []string\n\t*config.Config\n}\n\n\n\n\n\nfunc (c IniConfig) LoadKeyValue() mcore.StringKeyValueMap {\n\tlogger.Debugf(\"load config from %v.\", c.Locations)\n\tskv := mcore.NewStringKeyValueMap()\n\tfor _, section := range c.Sections() {\n\t\toptions, _ := c.Config.Options(section)\n\t\tfor _, option := range options {\n\t\t\tk := \"\"\n\t\t\tif section == \"DEFAULT\" {\n\t\t\t\tk = fmt.Sprintf(\"%s\", option)\n\t\t\t} else {\n\t\t\t\tk = fmt.Sprintf(\"%s@%s\", option, section)\n\t\t\t}\n\t\t\tv, _ := c.Config.String(section, option)\n\t\t\tlogger.Tracef(\"load key:%s value:%s\", k, v)\n\t\t\tskv.Put(k, v)\n\t\t}\n\t}\n\treturn skv\n}\n\nfunc NewIniConfig(locations ...string) *IniConfig ", "output": "{\n\tc := &IniConfig{Locations: locations}\n\tconf := config.NewDefault()\n\tfor _, location := range locations {\n\t\tconfItem, err := config.ReadDefault(location)\n\t\tif logger.CheckError(err) {\n\t\t\tcontinue\n\t\t}\n\t\tconf.Merge(confItem)\n\t}\n\tc.Config = conf\n\treturn c\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\ntype EnumFlag struct {\n\tdefaultValue string\n\tvs []string\n\ti int\n}\n\n\n\nfunc NewEnumFlag(defaultValue string, vs []string) *EnumFlag {\n\tf := &EnumFlag{\n\t\ti: -1,\n\t\tvs: vs,\n\t\tdefaultValue: defaultValue,\n\t}\n\treturn f\n}\n\n\nfunc (f *EnumFlag) Type() string {\n\treturn \"{\" + strings.Join(f.vs, \",\") + \"}\"\n}\n\n\nfunc (f *EnumFlag) String() string {\n\tif f.i == -1 {\n\t\treturn f.defaultValue\n\t}\n\treturn f.vs[f.i]\n}\n\n\n\n\n\n\nfunc (f *EnumFlag) Set(s string) error {\n\tfor i := range f.vs {\n\t\tif f.vs[i] == s {\n\t\t\tf.i = i\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"must be one of %v\", f.Type())\n}\n\nfunc (f *EnumFlag) IsSet() bool ", "output": "{\n\treturn f.i != -1\n}"} {"input": "package resourcemanager\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteTemplateRequest struct {\n\n\tTemplateId *string `mandatory:\"true\" contributesTo:\"path\" name:\"templateId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteTemplateRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteTemplateRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request DeleteTemplateRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request DeleteTemplateRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteTemplateResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteTemplateResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response DeleteTemplateResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package factory\n\nimport (\n\t\"encoding/json\"\n\t\"path/filepath\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/hyperhq/runv/factory/base\"\n\t\"github.com/hyperhq/runv/factory/cache\"\n\t\"github.com/hyperhq/runv/factory/direct\"\n\t\"github.com/hyperhq/runv/factory/multi\"\n\t\"github.com/hyperhq/runv/factory/single\"\n\t\"github.com/hyperhq/runv/factory/template\"\n\t\"github.com/hyperhq/runv/hypervisor\"\n)\n\ntype Factory interface {\n\tGetVm(cpu, mem int) (*hypervisor.Vm, error)\n\tCloseFactory()\n}\n\ntype FactoryConfig struct {\n\tCache int `json:\"cache\"`\n\tTemplate bool `json:\"template\"`\n\tCpu int `json:\"cpu\"`\n\tMemory int `json:\"memory\"`\n}\n\nfunc NewFromConfigs(bootConfig hypervisor.BootConfig, configs []FactoryConfig) Factory {\n\tbases := make([]base.Factory, len(configs))\n\tfor i, c := range configs {\n\t\tvar b base.Factory\n\t\tboot := bootConfig\n\t\tboot.CPU = c.Cpu\n\t\tboot.Memory = c.Memory\n\t\tif c.Template {\n\t\t\tb = template.New(filepath.Join(hypervisor.BaseDir, \"template\"), boot)\n\t\t} else {\n\t\t\tb = direct.New(boot)\n\t\t}\n\t\tbases[i] = cache.New(c.Cache, b)\n\t}\n\n\tif len(bases) == 0 {\n\t\treturn single.Dummy(bootConfig)\n\t} else if len(bases) == 1 {\n\t\treturn single.New(bases[0])\n\t} else {\n\t\treturn multi.New(bases)\n\t}\n}\n\n\n\n\n\nfunc NewFromPolicy(bootConfig hypervisor.BootConfig, policy string) Factory ", "output": "{\n\tvar configs []FactoryConfig\n\tjsonString := \"[\" + policy + \"]\"\n\terr := json.Unmarshal([]byte(jsonString), &configs)\n\tif err != nil && policy != \"none\" {\n\t\tglog.Errorf(\"Incorrect policy: %s\", policy)\n\t}\n\treturn NewFromConfigs(bootConfig, configs)\n}"} {"input": "package push\n\nimport \"fmt\"\n\ntype PushResult struct {\n\tProvider *PushServiceProvider\n\tDestination *DeliveryPoint\n\tContent *Notification\n\tMsgId string\n\tErr error\n}\n\nfunc (r *PushResult) IsError() bool {\n\tif r.Err == nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\n\ntype PushServiceType interface {\n\n\tBuildPushServiceProviderFromMap(map[string]string, *PushServiceProvider) error\n\n\tBuildDeliveryPointFromMap(map[string]string, *DeliveryPoint) error\n\tName() string\n\n\tPush(*PushServiceProvider, <-chan *DeliveryPoint, chan<- *PushResult, *Notification)\n\n\tSetErrorReportChan(errChan chan<- error)\n\n\tFinalize()\n}\n\nfunc (r *PushResult) Error() string ", "output": "{\n\tif !r.IsError() {\n\t\treturn fmt.Sprintf(\"PushServiceProvider=%v DeliveryPoint=%v MsgId=%v Succsess!\",\n\t\t\tr.Provider.Name(),\n\t\t\tr.Destination.Name(),\n\t\t\tr.MsgId)\n\t}\n\n\tret := fmt.Sprintf(\"Failed PushServiceProvider=%s DeliveryPoint=%s %v\",\n\t\tr.Provider.Name(),\n\t\tr.Destination.Name(),\n\t\tr.Err)\n\treturn ret\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/ChuckHa/grout\"\n\t\"net/http\"\n)\n\ntype Blog struct {\n}\n\n\n\nfunc BlogByName(name string) *Blog {\n\treturn &Blog{}\n}\n\nfunc blogsHandler(w http.ResponseWriter, r *http.Request, data map[string]string) {\n\ttheBlog := BlogByName(data[\"name\"])\n\tpost := theBlog.PostById(data[\"othername\"])\n\tfmt.Fprintf(w, post)\n}\n\nfunc main() {\n\tmux := grout.NewRouteMux()\n\tmux.Route(`/blogs/(?P[a-z][a-z_-]+[a-z])/(?P[0-9]+)`, blogsHandler)\n\tfmt.Println(\"Listening on port 8080\")\n\thttp.ListenAndServe(\":8080\", mux)\n}\n\nfunc (b *Blog) PostById(id string) string ", "output": "{\n\treturn \"a blog post\"\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\n\n\nfunc fatalWithErr(desc string, err error) {\n\tcui.ln(desc)\n\tcui.ln(\"Reason:\", err)\n\tcui.ln(\"Bye...\")\n\tcui.ln(\"\")\n\tos.Exit(1)\n}\n\nfunc fatal(desc string) {\n\tcui.ln(desc)\n\tcui.ln(\"Bye...\")\n\tcui.ln(\"\")\n\tos.Exit(1)\n}\n\nfunc setupSignalHandlers() ", "output": "{\n\tsignalChan := make(chan os.Signal, 1)\n\tsignal.Notify(signalChan, os.Interrupt, os.Kill, syscall.SIGTERM)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase signal := <-signalChan:\n\t\t\t\tcui.ln(\"Received\", signal, \"- exiting...\")\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t}\n\t}()\n}"} {"input": "package clubaux\n\n\n\nfunc init() ", "output": "{\n\tprintln(\"deprecated\")\n}"} {"input": "package iso20022\n\n\ntype CashAccountType2Choice struct {\n\n\tCode *ExternalCashAccountType1Code `xml:\"Cd\"`\n\n\tProprietary *Max35Text `xml:\"Prtry\"`\n}\n\nfunc (c *CashAccountType2Choice) SetCode(value string) {\n\tc.Code = (*ExternalCashAccountType1Code)(&value)\n}\n\n\n\nfunc (c *CashAccountType2Choice) SetProprietary(value string) ", "output": "{\n\tc.Proprietary = (*Max35Text)(&value)\n}"} {"input": "package raft\n\nimport (\n\t\"github.com/iketheadore/raft/comm\"\n\t\"github.com/iketheadore/raft/logic\"\n)\n\ntype Raft struct {\n\tlocalServ logic.Server\n\tlistener comm.Listener\n\tsender comm.Sender\n\tlogic *logic.Logic\n}\n\n\n\nfunc (r *Raft) Connect(addr string) error {\n\treturn r.logic.Connect(logic.Server{Addr: addr, Role: logic.Follower})\n}\n\nfunc (r *Raft) Run() {\n\tr.logic.Run()\n}\n\nfunc (r *Raft) ReplicateCmd(cmd comm.Command) {\n\tr.logic.ReplicateCmd(cmd)\n}\n\nfunc New(addr string) *Raft ", "output": "{\n\tr := &Raft{localServ: logic.Server{Addr: addr, Role: logic.Follower}, listener: comm.NewListener(addr)}\n\tr.listener.Run()\n\tr.logic = logic.New(r.localServ)\n\tr.logic.Subscribe(r.listener)\n\treturn r\n}"} {"input": "package user\n\nimport (\n\t\"github.com/google/exposure-notifications-verification-server/pkg/observability\"\n\n\tenobs \"github.com/google/exposure-notifications-server/pkg/observability\"\n\n\t\"go.opencensus.io/stats\"\n\t\"go.opencensus.io/stats/view\"\n)\n\nvar mUpstreamUserRecreates *stats.Int64Measure\n\n\n\nfunc init() ", "output": "{\n\t{\n\t\tname := observability.MetricRoot + \"/user/upstream_user_recreate\"\n\t\tmUpstreamUserRecreates = stats.Int64(name, \"user was re-created in auth provider\", stats.UnitDimensionless)\n\t\tenobs.CollectViews([]*view.View{\n\t\t\t{\n\t\t\t\tName: name + \"_count\",\n\t\t\t\tMeasure: mUpstreamUserRecreates,\n\t\t\t\tDescription: \"Count of users that were re-created in the upstream auth provider\",\n\t\t\t\tTagKeys: observability.CommonTagKeys(),\n\t\t\t\tAggregation: view.Count(),\n\t\t\t},\n\t\t}...)\n\t}\n}"} {"input": "package runner\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"os/exec\"\n\t\"syscall\"\n)\n\ntype Runner struct {\n\toutStream, errStream io.Writer\n}\n\nfunc New(out, err io.Writer) *Runner {\n\treturn &Runner{out, err}\n}\n\n\n\nfunc (r *Runner) echoStdout(reader io.Reader) {\n\tscanner := bufio.NewScanner(reader)\n\tfor scanner.Scan() {\n\t\tfmt.Fprintf(r.outStream, \"%s\\n\", scanner.Text())\n\t}\n}\n\nfunc (r *Runner) echoStderr(reader io.Reader) {\n\tscanner := bufio.NewScanner(reader)\n\tfor scanner.Scan() {\n\t\tfmt.Fprintf(r.errStream, \"%s\\n\", scanner.Text())\n\t}\n}\n\nfunc (r *Runner) Run(command string) error ", "output": "{\n\tcmd := exec.Command(\"cmd\")\n\tcmd.SysProcAttr = &syscall.SysProcAttr{}\n\tcmd.SysProcAttr.CmdLine = \"/C \" + command\n\n\tout_reader, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr_reader, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\n\tgo r.echoStdout(out_reader)\n\tgo r.echoStderr(err_reader)\n\n\terr = cmd.Wait()\n\treturn err\n}"} {"input": "package canopus\n\nimport \"net\"\n\nfunc Dial(address string) (conn Connection, err error) {\n\tudpConn, err := net.Dial(\"udp\", address)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn = &UDPConnection{\n\t\tconn: udpConn,\n\t}\n\n\treturn\n}\n\nfunc DialDTLS(address, identity, psk string) (conn Connection, err error) {\n\tudpConn, err := net.Dial(\"udp\", address)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn, err = NewDTLSConnection(udpConn, identity, psk)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc NewObserveMessage(r string, val interface{}, msg Message) ObserveMessage {\n\treturn &CoapObserveMessage{\n\t\tResource: r,\n\t\tValue: val,\n\t\tMsg: msg,\n\t}\n}\n\ntype CoapObserveMessage struct {\n\tCoapMessage\n\tResource string\n\tValue interface{}\n\tMsg Message\n}\n\n\n\nfunc (m *CoapObserveMessage) GetValue() interface{} {\n\treturn m.Value\n}\n\nfunc (m *CoapObserveMessage) GetMessage() Message {\n\treturn m.GetMessage()\n}\n\nfunc (m *CoapObserveMessage) GetResource() string ", "output": "{\n\treturn m.Resource\n}"} {"input": "package comm\n\nimport (\n\t\"context\"\n\n\t\"github.com/hyperledger/fabric/common/semaphore\"\n\t\"google.golang.org/grpc\"\n)\n\ntype Semaphore interface {\n\tAcquire(ctx context.Context) error\n\tRelease()\n}\n\ntype Throttle struct {\n\tnewSemaphore NewSemaphoreFunc\n\tsemaphore Semaphore\n}\n\ntype ThrottleOption func(t *Throttle)\ntype NewSemaphoreFunc func(size int) Semaphore\n\nfunc WithNewSemaphore(newSemaphore NewSemaphoreFunc) ThrottleOption {\n\treturn func(t *Throttle) {\n\t\tt.newSemaphore = newSemaphore\n\t}\n}\n\nfunc NewThrottle(maxConcurrency int, options ...ThrottleOption) *Throttle {\n\tt := &Throttle{\n\t\tnewSemaphore: func(count int) Semaphore { return semaphore.New(count) },\n\t}\n\n\tfor _, optionFunc := range options {\n\t\toptionFunc(t)\n\t}\n\n\tt.semaphore = t.newSemaphore(maxConcurrency)\n\treturn t\n}\n\nfunc (t *Throttle) UnaryServerIntercptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {\n\tif err := t.semaphore.Acquire(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer t.semaphore.Release()\n\n\treturn handler(ctx, req)\n}\n\n\n\nfunc (t *Throttle) StreamServerInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error ", "output": "{\n\tctx := ss.Context()\n\tif err := t.semaphore.Acquire(ctx); err != nil {\n\t\treturn err\n\t}\n\tdefer t.semaphore.Release()\n\n\treturn handler(srv, ss)\n}"} {"input": "package main\n\nvar log string\n\ntype T int\n\nfunc (t T) a(s string) T {\n\tlog += \"a(\" + s + \")\"\n\treturn t\n}\n\nfunc (T) b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\ntype F func(s string) F\n\nfunc a(s string) F {\n\tlog += \"a(\" + s + \")\"\n\treturn F(a)\n}\n\nfunc b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\ntype I interface {\n\ta(s string) I\n\tb(s string) string\n}\n\ntype T1 int\n\nfunc (t T1) a(s string) I {\n\tlog += \"a(\" + s + \")\"\n\treturn t\n}\n\nfunc (T1) b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\nvar ok = true\n\n\n\nfunc main() {\n\tvar t T\n\tif t.a(\"1\").a(t.b(\"2\")); log != \"a(1)ba(2)\" {\n\t\tbad()\n\t}\n\tlog = \"\"\n\tif a(\"3\")(b(\"4\"))(b(\"5\")); log != \"a(3)ba(4)ba(5)\" {\n\t\tbad()\n\t}\n\tlog = \"\"\n\tvar i I = T1(0)\n\tif i.a(\"6\").a(i.b(\"7\")).a(i.b(\"8\")).a(i.b(\"9\")); log != \"a(6)ba(7)ba(8)ba(9)\" {\n\t\tbad()\n\t}\n}\n\nfunc bad() ", "output": "{\n\tif !ok {\n\t\tprintln(\"BUG\")\n\t\tok = false\n\t}\n\tprintln(log)\n}"} {"input": "package iso20022\n\n\ntype TerminationDate4Choice struct {\n\n\tDate *DateAndDateTimeChoice `xml:\"Dt\"`\n\n\tCode *DateCode18Choice `xml:\"Cd\"`\n}\n\nfunc (t *TerminationDate4Choice) AddDate() *DateAndDateTimeChoice {\n\tt.Date = new(DateAndDateTimeChoice)\n\treturn t.Date\n}\n\n\n\nfunc (t *TerminationDate4Choice) AddCode() *DateCode18Choice ", "output": "{\n\tt.Code = new(DateCode18Choice)\n\treturn t.Code\n}"} {"input": "package build\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tMaxEncodedVersionLength = 100\n\n\tVersion = \"1.3.1\"\n)\n\n\nfunc IsVersion(str string) bool {\n\tfor _, n := range strings.Split(str, \".\") {\n\t\tif _, err := strconv.Atoi(n); err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc VersionCmp(a, b string) int {\n\taNums := strings.Split(a, \".\")\n\tbNums := strings.Split(b, \".\")\n\tfor i := 0; i < min(len(aNums), len(bNums)); i++ {\n\t\taInt, _ := strconv.Atoi(aNums[i])\n\t\tbInt, _ := strconv.Atoi(bNums[i])\n\t\tif aInt < bInt {\n\t\t\treturn -1\n\t\t} else if aInt > bInt {\n\t\t\treturn 1\n\t\t}\n\t}\n\tif len(aNums) < len(bNums) {\n\t\treturn -1\n\t} else if len(aNums) > len(bNums) {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\nfunc min(a, b int) int ", "output": "{\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}"} {"input": "package metrics\n\nimport (\n\t\"sync\"\n\n\tprom \"github.com/prometheus/client_golang/prometheus\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tsandboxGuageName = \"bundlelib_sandbox\"\n)\n\nvar (\n\tonce sync.Once\n\tcollector *Collector\n)\n\n\ntype Collector struct {\n\tSandbox prom.Gauge\n}\n\n\n\n\n\n\n\n\nfunc RegisterCollector() {\n\tonce.Do(func() {\n\t\tcollector = &Collector{\n\t\t\tSandbox: prom.NewGauge(prom.GaugeOpts{\n\t\t\t\tName: sandboxGuageName,\n\t\t\t\tHelp: \"Guage of all sandbox namespaces that are active.\",\n\t\t\t}),\n\t\t}\n\n\t\terr := prom.Register(collector)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"unable to register collector with prometheus: %v\", err)\n\t\t}\n\t})\n}\n\n\nfunc SandboxCreated() {\n\tdefer recoverMetricPanic()\n\tcollector.Sandbox.Inc()\n}\n\n\nfunc SandboxDeleted() {\n\tdefer recoverMetricPanic()\n\tcollector.Sandbox.Dec()\n}\n\n\nfunc (c Collector) Describe(ch chan<- *prom.Desc) {\n\tc.Sandbox.Describe(ch)\n}\n\n\nfunc (c Collector) Collect(ch chan<- prom.Metric) {\n\tc.Sandbox.Collect(ch)\n}\n\nfunc recoverMetricPanic() ", "output": "{\n\tif r := recover(); r != nil {\n\t\tlog.Errorf(\"Recovering from metric function - %v\", r)\n\t}\n}"} {"input": "package geo\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\n\n\nfunc TestDefineDeg2Rad(t *testing.T) {\n\tif math.Abs(deg2rad(0.0)) > epsilon {\n\t\tt.Error(\"define, deg2rad error\")\n\t}\n\n\tif math.Abs(deg2rad(180.0)-math.Pi) > epsilon {\n\t\tt.Error(\"define, deg2rad error\")\n\t}\n\n\tif math.Abs(deg2rad(360.0)-2*math.Pi) > epsilon {\n\t\tt.Error(\"define, deg2rad error\")\n\t}\n}\n\nfunc TestDefineRad2Deg(t *testing.T) {\n\tif math.Abs(rad2deg(0.0)-0.0) > epsilon {\n\t\tt.Error(\"define, rad2deg error\")\n\t}\n\n\tif math.Abs(rad2deg(math.Pi)-180.0) > epsilon {\n\t\tt.Error(\"define, rad2deg error\")\n\t}\n\n\tif math.Abs(rad2deg(2*math.Pi)-360.0) > epsilon {\n\t\tt.Error(\"define, rad2deg error\")\n\t}\n}\n\nfunc TestDefineYesHaversine(t *testing.T) ", "output": "{\n\n\tif yesHaversine(make([]bool, 0)) {\n\t\tt.Error(\"define, yesHaversine should be false, got true\")\n\t}\n\n\tif !yesHaversine([]bool{true}) {\n\t\tt.Error(\"define, yesHaversine should be true, got false\")\n\t}\n\n\tif yesHaversine([]bool{false}) {\n\t\tt.Error(\"define, yesHaversine should be false, got true\")\n\t}\n}"} {"input": "package account\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn \"v10.0.2-beta\"\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/v10.0.2-beta arm-account/2016-11-01\"\n}"} {"input": "package frames\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\ntype RstStreamFrame struct {\n\tStreamId uint32\n\tErrorCode ErrorCode\n}\n\nfunc NewRstStreamFrame(streamId uint32, errorCode ErrorCode) *RstStreamFrame {\n\treturn &RstStreamFrame{\n\t\tStreamId: streamId,\n\t\tErrorCode: errorCode,\n\t}\n}\n\n\n\nfunc (f *RstStreamFrame) Type() Type {\n\treturn RST_STREAM_TYPE\n}\n\nfunc (f *RstStreamFrame) Encode(context *EncodingContext) ([]byte, error) {\n\tresult := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(result, uint32(f.ErrorCode))\n\treturn result, nil\n}\n\nfunc (f *RstStreamFrame) GetStreamId() uint32 {\n\treturn f.StreamId\n}\n\nfunc DecodeRstStreamFrame(flags byte, streamId uint32, payload []byte, context *DecodingContext) (Frame, error) ", "output": "{\n\tif len(payload) != 4 {\n\t\treturn nil, fmt.Errorf(\"FRAME_SIZE_ERROR: Received RST_STREAM frame of length %v\", len(payload))\n\t}\n\treturn NewRstStreamFrame(streamId, ErrorCode(binary.BigEndian.Uint32(payload))), nil\n}"} {"input": "package players\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestRepo_Pick(t *testing.T) {\n\tp := Player{ID: 1}\n\tr := &Repo{\n\t\tAvailable: []Player{{ID: 1, ADP: 45}},\n\t}\n\tvar err error\n\n\tp.ID = 2\n\terr = r.Pick(p)\n\trequire.Error(t, err)\n\n\trequire.Equal(t, 0, len(r.Claimed))\n\trequire.Equal(t, 1, len(r.Available))\n\trequire.Equal(t, 0, r.Position)\n\n\tp.ID = 1\n\terr = r.Pick(p)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 0, len(r.Available))\n\trequire.Equal(t, 1, len(r.Claimed))\n\trequire.Equal(t, 1, r.Position)\n}\n\n\n\nfunc TestRepo_UnPick(t *testing.T) ", "output": "{\n\tp := Player{ID: 1}\n\tr := &Repo{\n\t\tPosition: 3,\n\t\tClaimed: []Player{{ID: 1, ADP: 45}},\n\t}\n\n\tvar err error\n\n\tp.ID = 2\n\terr = r.UnPick(p)\n\n\trequire.Error(t, err)\n\trequire.Equal(t, 1, len(r.Claimed))\n\trequire.Equal(t, 0, len(r.Available))\n\trequire.Equal(t, 3, r.Position)\n\n\tp.ID = 1\n\terr = r.UnPick(p)\n\n\trequire.NoError(t, err)\n\trequire.Equal(t, 0, len(r.Claimed))\n\trequire.Equal(t, 1, len(r.Available))\n\trequire.Equal(t, 2, r.Position)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSOpsWorksStack_ElasticIp struct {\n\n\tIp string `json:\"Ip,omitempty\"`\n\n\tName string `json:\"Name,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) AWSCloudFormationType() string {\n\treturn \"AWS::OpsWorks::Stack.ElasticIp\"\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\n\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSOpsWorksStack_ElasticIp) SetDependsOn(dependencies []string) ", "output": "{\n\tr._dependsOn = dependencies\n}"} {"input": "package v1\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\n\n\nfunc addDefaultingFuncs(scheme *runtime.Scheme) error ", "output": "{\n\tv1.RegisterDefaults(scheme)\n\treturn scheme.AddDefaultingFuncs(\n\t\tv1.SetDefaults_Secret,\n\t\tv1.SetDefaults_ServiceSpec,\n\t\tv1.SetDefaults_NamespaceStatus,\n\t)\n}"} {"input": "package syswrap\n\nimport (\n\t\"os\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\nvar fileCount uint64\n\n\n\nvar maxFileCount uint64 = 500000\nvar fileMu sync.RWMutex\n\n\n\n\n\n\n\n\nfunc OpenFile(name string, flag int, perm os.FileMode) (file *os.File, mustClose bool, err error) {\n\tfile, err = os.OpenFile(name, flag, perm)\n\tfileMu.RLock()\n\tdefer fileMu.RUnlock()\n\tif newCount := atomic.AddUint64(&fileCount, 1); newCount > maxFileCount {\n\t\tmustClose = true\n\t}\n\treturn file, mustClose, err\n}\n\n\nfunc CloseFile(f *os.File) error {\n\tatomic.AddUint64(&fileCount, ^uint64(0)) \n\treturn f.Close()\n}\n\nfunc SetMaxFileCount(max uint64) ", "output": "{\n\tfileMu.Lock()\n\tmaxFileCount = max\n\tfileMu.Unlock()\n}"} {"input": "package types\n\nimport (\n\t\"math\"\n)\n\n\n\n\n\nfunc RoundFloat(val float64) float64 {\n\tv, frac := math.Modf(val)\n\tif val >= 0.0 {\n\t\tif frac > 0.5 || (frac == 0.5 && uint64(v)%2 != 0) {\n\t\t\tv += 1.0\n\t\t}\n\t} else {\n\t\tif frac < -0.5 || (frac == -0.5 && uint64(v)%2 != 0) {\n\t\t\tv -= 1.0\n\t\t}\n\t}\n\n\treturn v\n}\n\n\n\nfunc truncateFloat(f float64, decimal int) float64 {\n\tpow := math.Pow10(decimal)\n\tt := (f - math.Floor(f)) * pow\n\n\tround := RoundFloat(t)\n\n\tf = math.Floor(f) + round/pow\n\treturn f\n}\n\n\n\nfunc TruncateFloat(f float64, flen int, decimal int) (float64, error) {\n\tif math.IsNaN(f) {\n\t\treturn 0, nil\n\t}\n\n\tmaxF := getMaxFloat(flen, decimal)\n\n\tif !math.IsInf(f, 0) {\n\t\tf = truncateFloat(f, decimal)\n\t}\n\n\tif f > maxF {\n\t\tf = maxF\n\t} else if f < -maxF {\n\t\tf = -maxF\n\t}\n\n\treturn f, nil\n}\n\nfunc getMaxFloat(flen int, decimal int) float64 ", "output": "{\n\tintPartLen := flen - decimal\n\tf := math.Pow10(intPartLen)\n\tf -= math.Pow10(-decimal)\n\treturn f\n}"} {"input": "package launchdarkly\n\nimport (\n\t\"errors\"\n\t\"os\"\n\n\t\"github.com/GoogleCloudPlatform/terraformer/terraformutils\"\n)\n\ntype LaunchDarklyProvider struct { \n\tterraformutils.Provider\n\tapiKey string\n}\n\nconst (\n\tbasePath = \"https:app.launchdarkly.com/api/v2\"\n\tversion = \"0.0.1\"\n\tAPIVersion = \"20191212\"\n)\n\nfunc (p *LaunchDarklyProvider) Init(args []string) error {\n\tif os.Getenv(\"LAUNCHDARKLY_ACCESS_TOKEN\") == \"\" {\n\t\treturn errors.New(\"set LAUNCHDARKLY_ACCESS_TOKEN env var\")\n\t}\n\tp.apiKey = os.Getenv(\"LAUNCHDARKLY_ACCESS_TOKEN\")\n\n\treturn nil\n}\n\nfunc (p *LaunchDarklyProvider) GetName() string {\n\treturn \"launchdarkly\"\n}\n\nfunc (p *LaunchDarklyProvider) GetProviderData(arg ...string) map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"provider\": map[string]interface{}{\n\t\t\t\"launchdarkly\": map[string]interface{}{\n\t\t\t\t\"api_key\": p.apiKey,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (LaunchDarklyProvider) GetResourceConnections() map[string]map[string][]string {\n\treturn map[string]map[string][]string{}\n}\n\nfunc (p *LaunchDarklyProvider) GetSupportedService() map[string]terraformutils.ServiceGenerator {\n\treturn map[string]terraformutils.ServiceGenerator{\n\t\t\"project\": &ProjectGenerator{},\n\t}\n}\n\n\n\nfunc (p *LaunchDarklyProvider) InitService(serviceName string, verbose bool) error ", "output": "{\n\tvar isSupported bool\n\tif _, isSupported = p.GetSupportedService()[serviceName]; !isSupported {\n\t\treturn errors.New(\"launchdarkly: \" + serviceName + \" not supported service\")\n\t}\n\tp.Service = p.GetSupportedService()[serviceName]\n\tp.Service.SetName(serviceName)\n\tp.Service.SetVerbose(verbose)\n\tp.Service.SetProviderName(p.GetName())\n\tp.Service.SetArgs(map[string]interface{}{\n\t\t\"api_key\": p.apiKey,\n\t})\n\treturn nil\n}"} {"input": "package update\n\nimport (\n\t\"github.com/andreaskoch/allmark/common/route\"\n\t\"fmt\"\n\t\"golang.org/x/net/websocket\"\n)\n\nfunc NewConnection(hub *Hub, ws *websocket.Conn, route route.Route) *connection {\n\treturn &connection{\n\t\tRoute: route,\n\n\t\thub: hub,\n\t\tsend: make(chan Message, 10),\n\t\tws: ws,\n\t}\n}\n\ntype connection struct {\n\tRoute route.Route\n\n\thub *Hub\n\n\tws *websocket.Conn\n\n\tsend chan Message\n}\n\nfunc (c *connection) String() string {\n\treturn fmt.Sprintf(\"Connection (Route: %s, IP: %s)\", c.Route.String(), c.ws.Request().RemoteAddr)\n}\n\nfunc (c *connection) Send(msg Message) {\n\tc.send <- msg\n}\n\nfunc (c *connection) Reader() {\n\tfor {\n\t\tvar message Message\n\t\terr := websocket.JSON.Receive(c.ws, &message)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tc.hub.broadcast <- message\n\t}\n\n\tc.ws.Close()\n\tc.hub.Unsubscribe(c)\n}\n\n\n\nfunc (c *connection) Writer() ", "output": "{\n\tfor message := range c.send {\n\t\terr := websocket.JSON.Send(c.ws, message)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tc.ws.Close()\n\tc.hub.Unsubscribe(c)\n}"} {"input": "package aesample\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/mzimmerman/aesample/subpkga\"\n\t\"github.com/mzimmerman/aesample/util\"\n)\n\n\n\nfunc root(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Hello, you've reached aesample, the root package does nothing\")\n}\n\nfunc init() ", "output": "{\n\thttp.HandleFunc(\"/\", root)\n\thttp.HandleFunc(\"/subpkga\", subpkga.Root)\n\tutil.Log(\"aesample init()\")\n}"} {"input": "package circuitbreaker\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/mailgun/log\"\n\t\"github.com/mailgun/vulcan/netutils\"\n)\n\ntype SideEffect interface {\n\tExec() error\n}\n\ntype Webhook struct {\n\tURL string\n\tMethod string\n\tHeaders http.Header\n\tForm url.Values\n\tBody []byte\n}\n\ntype WebhookSideEffect struct {\n\tw Webhook\n}\n\n\n\nfunc (w *WebhookSideEffect) getBody() io.Reader {\n\tif len(w.w.Form) != 0 {\n\t\treturn strings.NewReader(w.w.Form.Encode())\n\t}\n\tif len(w.w.Body) != 0 {\n\t\treturn bytes.NewBuffer(w.w.Body)\n\t}\n\treturn nil\n}\n\nfunc (w *WebhookSideEffect) Exec() error {\n\tr, err := http.NewRequest(w.w.Method, w.w.URL, w.getBody())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(w.w.Headers) != 0 {\n\t\tnetutils.CopyHeaders(r.Header, w.w.Headers)\n\t}\n\tif len(w.w.Form) != 0 {\n\t\tr.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t}\n\tre, err := http.DefaultClient.Do(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif re.Body != nil {\n\t\tdefer re.Body.Close()\n\t}\n\tbody, err := ioutil.ReadAll(re.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Infof(\"%v got response: (%s): %s\", w, re.Status, string(body))\n\treturn nil\n}\n\nfunc NewWebhookSideEffect(w Webhook) (*WebhookSideEffect, error) ", "output": "{\n\tif w.Method == \"\" {\n\t\treturn nil, fmt.Errorf(\"Supply method\")\n\t}\n\t_, err := netutils.ParseUrl(w.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &WebhookSideEffect{w: w}, nil\n}"} {"input": "package twitch\n\nimport (\n\t\"net/http\"\n\t\"testing\"\n)\n\nfunc TestTeamsTeam(t *testing.T) {\n\ttc := NewClient(&http.Client{})\n\n\t_, err := tc.Teams.Team(\"testteam\")\n\n\tif err != nil {\n\t\tt.Errorf(\"error not nil: %+v\", err)\n\t}\n\n}\n\n\n\nfunc TestTeamsList(t *testing.T) ", "output": "{\n\ttc := NewClient(&http.Client{})\n\n\topt := &ListOptions{\n\t\tLimit: 1,\n\t\tOffset: 0,\n\t}\n\n\t_, err := tc.Teams.List(opt)\n\n\tif err != nil {\n\t\tt.Errorf(\"error not nil: %+v\", err)\n\t}\n\n}"} {"input": "package auth\n\nimport (\n\t\"encoding/base64\"\n\t\"github.com/outbrain/orchestrator/Godeps/_workspace/src/github.com/go-martini/martini\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n\ntype User string\n\n\nvar BasicRealm = \"Authorization Required\"\n\n\n\n\n\n\n\nfunc BasicFunc(authfn func(string, string) bool) martini.Handler {\n\treturn func(res http.ResponseWriter, req *http.Request, c martini.Context) {\n\t\tauth := req.Header.Get(\"Authorization\")\n\t\tif len(auth) < 6 || auth[:6] != \"Basic \" {\n\t\t\tunauthorized(res)\n\t\t\treturn\n\t\t}\n\t\tb, err := base64.StdEncoding.DecodeString(auth[6:])\n\t\tif err != nil {\n\t\t\tunauthorized(res)\n\t\t\treturn\n\t\t}\n\t\ttokens := strings.SplitN(string(b), \":\", 2)\n\t\tif len(tokens) != 2 || !authfn(tokens[0], tokens[1]) {\n\t\t\tunauthorized(res)\n\t\t\treturn\n\t\t}\n\t\tc.Map(User(tokens[0]))\n\t}\n}\n\nfunc unauthorized(res http.ResponseWriter) {\n\tres.Header().Set(\"WWW-Authenticate\", \"Basic realm=\\\"\"+BasicRealm+\"\\\"\")\n\thttp.Error(res, \"Not Authorized\", http.StatusUnauthorized)\n}\n\nfunc Basic(username string, password string) martini.Handler ", "output": "{\n\tvar siteAuth = base64.StdEncoding.EncodeToString([]byte(username + \":\" + password))\n\treturn func(res http.ResponseWriter, req *http.Request, c martini.Context) {\n\t\tauth := req.Header.Get(\"Authorization\")\n\t\tif !SecureCompare(auth, \"Basic \"+siteAuth) {\n\t\t\tunauthorized(res)\n\t\t\treturn\n\t\t}\n\t\tc.Map(User(username))\n\t}\n}"} {"input": "package convert\n\nfunc Add(s []string, a string) []string {\n\tfor _, existing := range s {\n\t\tif a == existing {\n\t\t\treturn s\n\t\t}\n\t}\n\treturn append(s, a)\n}\n\n\n\nfunc Uniq(s []string) (r []string) {\n\tfor _, entry := range s {\n\t\tfound := false\n\t\tfor _, existing := range r {\n\t\t\tif existing == entry {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tr = append(r, entry)\n\t\t}\n\t}\n\treturn\n}\n\nfunc Union(s []string, a []string) []string ", "output": "{\n\tfor _, entry := range a {\n\t\tfound := false\n\t\tfor _, existing := range s {\n\t\t\tif entry == existing {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\ts = append(s, entry)\n\t\t}\n\t}\n\treturn s\n}"} {"input": "package resttk\n\ntype ResourceInterface interface {\n\tFindAllResources(v interface{}) interface{}\n\tFindResource(key string, value string, v interface{}) interface{}\n\tSaveResource(key string, value string, v interface{}) interface{}\n\tUpdateResource(key string, value string, v interface{}) interface{}\n\tDeleteResource(key string, value string) bool\n}\n\ntype BaseResource struct {\n\tparent ResourceInterface\n}\n\n\n\nfunc (r *BaseResource) FindAllResources(v interface{}) interface{} {\n\tresources := r.parent.FindAllResources(v)\n\tif resources != nil {\n\t\treturn resources\n\t}\n\n\treturn nil\n}\n\nfunc (r *BaseResource) FindResource(key string, value string, v interface{}) interface{} {\n\tresource := r.parent.FindResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn nil\n}\n\nfunc (r *BaseResource) SaveResource(key string, value string, v interface{}) interface{} {\n\tresource := r.parent.FindResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn nil\n}\n\nfunc (r *BaseResource) UpdateResource(key string, value string, v interface{}) interface{} {\n\tresource := r.parent.UpdateResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn nil\n}\n\nfunc (r *BaseResource) DeleteResource(key string, value string) bool {\n\treturn r.parent.DeleteResource(key, value)\n}\n\nfunc (r *BaseResource) Init(p ResourceInterface) ", "output": "{\n\tr.parent = p\n}"} {"input": "package daemon\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/docker/docker/container\"\n)\n\n\n\n\nfunc checkIfPathIsInAVolume(container *container.Container, absPath string) (bool, error) {\n\tvar toVolume bool\n\tfor _, mnt := range container.MountPoints {\n\t\tif toVolume = mnt.HasResource(absPath); toVolume {\n\t\t\tif mnt.RW {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn false, ErrVolumeReadonly\n\t\t}\n\t}\n\treturn toVolume, nil\n}\n\n\n\nfunc fixPermissions(source, destination string, uid, gid int, destExisted bool) error ", "output": "{\n\tdestStat, err := os.Stat(destination)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdoChownDestination := !destExisted || !destStat.IsDir()\n\n\treturn filepath.Walk(source, func(fullpath string, info os.FileInfo, err error) error {\n\t\tif !doChownDestination && (source == fullpath) {\n\t\t\treturn nil\n\t\t}\n\n\t\tcleaned, err := filepath.Rel(source, fullpath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfullpath = filepath.Join(destination, cleaned)\n\t\treturn os.Lchown(fullpath, uid, gid)\n\t})\n}"} {"input": "package bot\n\nimport \"fmt\"\n\ntype ErrorLevel int\n\n\nconst (\n\tError ErrorLevel = iota\n\tInfo\n\tWarn\n\tDebug\n)\n\ntype LogRecord struct {\n\tMessage string\n\tLevel ErrorLevel\n}\n\n\n\n\n\nvar Log = func(record LogRecord) {}\n\nfunc log(level ErrorLevel, msg string) {\n\tLog(LogRecord{Level: level, Message: msg})\n}\n\nfunc (l LogRecord) String() string ", "output": "{\n\tvar levelStr string\n\tswitch l.Level {\n\tcase Error:\n\t\tlevelStr = \"ERROR\"\n\tcase Info:\n\t\tlevelStr = \"INFO\"\n\tcase Warn:\n\t\tlevelStr = \"WARN\"\n\tcase Debug:\n\t\tlevelStr = \"DEBUG\"\n\t}\n\n\treturn fmt.Sprintf(\"[%s][bot] %s\", levelStr, l.Message)\n}"} {"input": "package topology\n\nimport (\n\t\"github.com/skydive-project/skydive/graffiti/getter\"\n\t\"strings\"\n)\n\nfunc (obj *NextHop) GetFieldBool(key string) (bool, error) {\n\treturn false, getter.ErrFieldNotFound\n}\n\nfunc (obj *NextHop) GetFieldInt64(key string) (int64, error) {\n\tswitch key {\n\tcase \"Priority\":\n\t\treturn int64(obj.Priority), nil\n\tcase \"IfIndex\":\n\t\treturn int64(obj.IfIndex), nil\n\t}\n\treturn 0, getter.ErrFieldNotFound\n}\n\n\n\nfunc (obj *NextHop) GetFieldKeys() []string {\n\treturn []string{\n\t\t\"Priority\",\n\t\t\"IP\",\n\t\t\"MAC\",\n\t\t\"IfIndex\",\n\t}\n}\n\nfunc (obj *NextHop) MatchBool(key string, predicate getter.BoolPredicate) bool {\n\treturn false\n}\n\nfunc (obj *NextHop) MatchInt64(key string, predicate getter.Int64Predicate) bool {\n\tif b, err := obj.GetFieldInt64(key); err == nil {\n\t\treturn predicate(b)\n\t}\n\treturn false\n}\n\nfunc (obj *NextHop) MatchString(key string, predicate getter.StringPredicate) bool {\n\tif b, err := obj.GetFieldString(key); err == nil {\n\t\treturn predicate(b)\n\t}\n\treturn false\n}\n\nfunc (obj *NextHop) GetField(key string) (interface{}, error) {\n\tif s, err := obj.GetFieldString(key); err == nil {\n\t\treturn s, nil\n\t}\n\n\tif i, err := obj.GetFieldInt64(key); err == nil {\n\t\treturn i, nil\n\t}\n\treturn nil, getter.ErrFieldNotFound\n}\n\nfunc init() {\n\tstrings.Index(\"\", \".\")\n}\n\nfunc (obj *NextHop) GetFieldString(key string) (string, error) ", "output": "{\n\tswitch key {\n\tcase \"IP\":\n\t\treturn obj.IP.String(), nil\n\tcase \"MAC\":\n\t\treturn string(obj.MAC), nil\n\t}\n\treturn \"\", getter.ErrFieldNotFound\n}"} {"input": "package interfaces\n\nimport (\n\n\t. \"gopkg.in/check.v1\"\n\t\"testing\"\n)\n\n\n\ntype TheSuite struct {\n\n}\n\nvar _ = Suite(&TheSuite{})\n\n\nfunc (suite *TheSuite) SetUpTest(c *C) {\n\n}\n\nfunc (suite *TheSuite) TestWebServer(c *C) {}\n\nfunc Test(t *testing.T) ", "output": "{ TestingT(t) }"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realVPCDHCPOptionsAssociation VPCDHCPOptionsAssociation\n\n\nfunc (o *VPCDHCPOptionsAssociation) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realVPCDHCPOptionsAssociation\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = VPCDHCPOptionsAssociation(r)\n\treturn nil\n}\n\nvar _ fi.HasName = &VPCDHCPOptionsAssociation{}\n\n\nfunc (o *VPCDHCPOptionsAssociation) GetName() *string {\n\treturn o.Name\n}\n\n\n\n\n\nfunc (o *VPCDHCPOptionsAssociation) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *VPCDHCPOptionsAssociation) SetName(name string) ", "output": "{\n\to.Name = &name\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n)\n\n\ntype Address struct {\n\tStreet, City string\n}\n\ntype Person struct {\n\tFirstName, LastName string\n}\n\ntype T1 string\ntype T2 string\ntype T3 string\n\nvar logger *log.Logger\n\nfunc main() {\n\tmyAddress := Address{\n\t\tStreet: \"Trimveien 6\",\n\t\tCity: \"Oslo\",\n\t}\n\tlog.Println(myAddress)\n\n\tme := Person{\n\t\tFirstName: \"Christian\",\n\t\tLastName: \"Bergum Bergersen\",\n\t}\n\tlog.Println(me)\n\n\tvar foo T1\n\tfoo = \"foo\"\n\tlog.Println(foo)\n\n\tvar bar T3\n\tbar = \"bar\"\n\tlog.Println(bar)\n}\n\n\nfunc (address Address) String() string {\n\treturn fmt.Sprintf(\"%s\", address)\n}\n\n\nfunc (person Person) String() string {\n\treturn fmt.Sprintf(\"%s %s\", person.FirstName, person.LastName)\n}\n\n\nfunc (t1 T1) String() string {\n\treturn fmt.Sprint(t1)\n}\n\n\n\n\n\nfunc (bar T3) String() string {\n\tvar buf bytes.Buffer\n\tlogger = log.New(&buf, \"logger: \", log.Lshortfile)\n\tlogger.Printf(\"Calling String() for %+v\", bar)\n\treturn fmt.Sprintf(\"Bar\")\n}\n\nfunc (t2 T2) String() string ", "output": "{\n\tlog.Print(\"Calling String() for : %v\", t2)\n\treturn fmt.Sprintln(t2)\n}"} {"input": "package plugins\n\nimport (\n\t\"errors\"\n\n\t\"github.com/spf13/cobra\"\n)\n\n\n\ntype backupFunc func()\ntype restoreFunc func()\ntype commandOb *cobra.Command\n\n\ntype Plugin struct {\n\tName string\n\tRestore restoreFunc\n\tBackup backupFunc\n\tCommand commandOb\n}\n\nvar plugins map[string]Plugin\n\n\nfunc Register(name string, restore restoreFunc, backup backupFunc, command commandOb) {\n\tplugins[name] = Plugin{name, restore, backup, command}\n}\n\n\nfunc Get(name string) (Plugin, error) {\n\tp, ok := plugins[name]\n\tif !ok {\n\t\treturn Plugin{}, errors.New(\"no plugin found\")\n\t}\n\treturn p, nil\n}\n\n\nfunc GetAll() map[string]Plugin {\n\treturn plugins\n}\n\nfunc init() ", "output": "{\n\tplugins = make(map[string]Plugin)\n}"} {"input": "package ansiwriter\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype Modifier func() string\n\nfunc escapeANSI(code int) string {\n\treturn fmt.Sprintf(\"\\033[%dm\", code)\n}\n\nfunc Bold() string { return escapeANSI(1) }\nfunc Black() string { return escapeANSI(30) }\nfunc Red() string { return escapeANSI(31) }\n\nfunc Yellow() string { return escapeANSI(33) }\nfunc Blue() string { return escapeANSI(34) }\nfunc Magenta() string { return escapeANSI(35) }\nfunc Cyan() string { return escapeANSI(36) }\nfunc White() string { return escapeANSI(37) }\n\ntype awr struct {\n\tio.Writer\n\tmodifiers []Modifier\n}\n\n\n\n\nfunc New(w io.Writer, mods ...Modifier) io.Writer {\n\treturn awr{w, mods}\n}\n\nfunc (a awr) Write(b []byte) (n int, err error) {\n\tfor _, mod := range a.modifiers {\n\t\ta.Writer.Write([]byte(mod()))\n\t}\n\tn, err = a.Writer.Write(b)\n\t_, _ = a.Writer.Write([]byte(\"\\033[0m\"))\n\treturn\n}\n\nfunc Green() string ", "output": "{ return escapeANSI(32) }"} {"input": "package auth\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n\n\t\"github.com/dgrijalva/jwt-go\"\n\t\"github.com/generationtux/brizo/database\"\n\t\"github.com/generationtux/brizo/resources\"\n)\n\n\nfunc APIMiddleware(rw http.ResponseWriter, request *http.Request, next http.HandlerFunc) {\n\tauthHeader := request.Header.Get(\"Authorization\")\n\tif authHeader == \"\" {\n\t\trw.WriteHeader(401)\n\t\trw.Write([]byte(\"not authorized\"))\n\t\treturn\n\t}\n\n\tif !validateAuthHeader(authHeader) {\n\t\tlog.Println(\"Authorization header is invalid:\", authHeader)\n\t\trw.WriteHeader(401)\n\t\trw.Write([]byte(\"invalid authorization header\"))\n\t\treturn\n\t}\n\n\tjwtToken := extractBearerTokenFromHeader(authHeader)\n\tif ValidateJWTToken(jwtToken) || ValidatePersonalAccessToken(jwtToken) {\n\t\tnext(rw, request)\n\t\treturn\n\t}\n\n\trw.WriteHeader(401)\n\trw.Write([]byte(\"not authorized\"))\n}\n\n\n\nfunc ValidatePersonalAccessToken(token string) bool {\n\tdb, err := database.Connect()\n\tdefer db.Close()\n\tif err != nil {\n\t\tlog.Printf(\"Database error: '%s'\\n\", err)\n\t\treturn false\n\t}\n\tif resources.HasAccessToken(db, token) {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\n\nfunc validateAuthHeader(header string) bool {\n\tdata := []byte(header)\n\tmatched, _ := regexp.Match(\"^Bearer .*\", data)\n\n\treturn matched\n}\n\n\n\n\n\nfunc jwtSecret() string {\n\treturn os.Getenv(\"JWT_SECRET\")\n}\n\n\n\nfunc extractBearerTokenFromHeader(header string) string {\n\treturn header[7:]\n}\n\nfunc ValidateJWTToken(token string) bool ", "output": "{\n\tt, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {\n\t\tif _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", t.Header[\"alg\"])\n\t\t}\n\t\treturn []byte(jwtSecret()), nil\n\t})\n\n\tif err != nil {\n\t\tlog.Println(err.Error()+\":\", token)\n\t\treturn false\n\t}\n\n\treturn t.Valid\n}"} {"input": "package mount\n\nimport (\n\t\"context\"\n\t\"io\"\n\n\t\"bazil.org/fuse\"\n\tfusefs \"bazil.org/fuse/fs\"\n\t\"github.com/rclone/rclone/fs/log\"\n\t\"github.com/rclone/rclone/vfs\"\n)\n\n\ntype FileHandle struct {\n\tvfs.Handle\n}\n\n\nvar _ fusefs.HandleReader = (*FileHandle)(nil)\n\n\n\n\n\nvar _ fusefs.HandleWriter = (*FileHandle)(nil)\n\n\nfunc (fh *FileHandle) Write(ctx context.Context, req *fuse.WriteRequest, resp *fuse.WriteResponse) (err error) {\n\tdefer log.Trace(fh, \"len=%d, offset=%d\", len(req.Data), req.Offset)(\"written=%d, err=%v\", &resp.Size, &err)\n\tn, err := fh.Handle.WriteAt(req.Data, req.Offset)\n\tif err != nil {\n\t\treturn translateError(err)\n\t}\n\tresp.Size = n\n\treturn nil\n}\n\n\nvar _ fusefs.HandleFlusher = (*FileHandle)(nil)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (fh *FileHandle) Flush(ctx context.Context, req *fuse.FlushRequest) (err error) {\n\tdefer log.Trace(fh, \"\")(\"err=%v\", &err)\n\treturn translateError(fh.Handle.Flush())\n}\n\nvar _ fusefs.HandleReleaser = (*FileHandle)(nil)\n\n\n\n\n\nfunc (fh *FileHandle) Release(ctx context.Context, req *fuse.ReleaseRequest) (err error) {\n\tdefer log.Trace(fh, \"\")(\"err=%v\", &err)\n\treturn translateError(fh.Handle.Release())\n}\n\nfunc (fh *FileHandle) Read(ctx context.Context, req *fuse.ReadRequest, resp *fuse.ReadResponse) (err error) ", "output": "{\n\tvar n int\n\tdefer log.Trace(fh, \"len=%d, offset=%d\", req.Size, req.Offset)(\"read=%d, err=%v\", &n, &err)\n\tdata := make([]byte, req.Size)\n\tn, err = fh.Handle.ReadAt(data, req.Offset)\n\tif err == io.EOF {\n\t\terr = nil\n\t} else if err != nil {\n\t\treturn translateError(err)\n\t}\n\tresp.Data = data[:n]\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sync\"\n)\n\n\n\n\n\ntype Stage interface {\n\tInit()\n\tRun(*FileRecord) error\n\tClose()\n}\n\n\n\n\n\n\n\n\n\ntype Pipeline struct {\n\tinput chan *FileRecord\n\toutput chan *FileRecord\n\tlog chan *FileRecord\n\tlogWg sync.WaitGroup\n}\n\n\n\nfunc NewPipeline(inputQueueSize, logQueueSize int) *Pipeline {\n\tvar p Pipeline\n\tp.input = make(chan *FileRecord, inputQueueSize)\n\tp.output = p.input\n\tp.log = make(chan *FileRecord, logQueueSize)\n\n\tp.logWg.Add(1)\n\tgo func() {\n\t\tfor fr := range p.log {\n\t\t\tfmt.Fprint(os.Stderr, fr)\n\t\t}\n\t\tp.logWg.Done()\n\t}()\n\n\treturn &p\n}\n\n\n\n\n\n\n\nfunc (p *Pipeline) Add(NewStage func() Stage, routineCount int) {\n\tif routineCount <= 0 {\n\t\treturn\n\t}\n\tvar wg sync.WaitGroup\n\n\tout := make(chan *FileRecord, routineCount)\n\n\twg.Add(routineCount)\n\tfor i := 0; i < routineCount; i++ {\n\t\tgo func(input <-chan *FileRecord) {\n\t\t\ts := NewStage()\n\t\t\ts.Init()\n\t\t\tfor fr := range input {\n\t\t\t\terr := s.Run(fr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tp.log <- fr\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tout <- fr\n\t\t\t}\n\t\t\ts.Close()\n\t\t\twg.Done()\n\t\t}(p.output)\n\t}\n\n\tp.output = out\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(out)\n\t}()\n}\n\n\n\n\n\nfunc (p *Pipeline) Close() ", "output": "{\n\tclose(p.log)\n\tp.logWg.Wait()\n}"} {"input": "package msgraph\n\nimport \"context\"\n\n\ntype WorkbookFunctionsRriRequestBuilder struct{ BaseRequestBuilder }\n\n\nfunc (b *WorkbookFunctionsRequestBuilder) Rri(reqObj *WorkbookFunctionsRriRequestParameter) *WorkbookFunctionsRriRequestBuilder {\n\tbb := &WorkbookFunctionsRriRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.BaseRequestBuilder.baseURL += \"/rri\"\n\tbb.BaseRequestBuilder.requestObject = reqObj\n\treturn bb\n}\n\n\ntype WorkbookFunctionsRriRequest struct{ BaseRequest }\n\n\nfunc (b *WorkbookFunctionsRriRequestBuilder) Request() *WorkbookFunctionsRriRequest {\n\treturn &WorkbookFunctionsRriRequest{\n\t\tBaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},\n\t}\n}\n\n\n\n\nfunc (r *WorkbookFunctionsRriRequest) Post(ctx context.Context) (resObj *WorkbookFunctionResult, err error) ", "output": "{\n\terr = r.JSONRequest(ctx, \"POST\", \"\", r.requestObject, &resObj)\n\treturn\n}"} {"input": "package vanity\n\nimport (\n\t\"github.com/gogo/protobuf/gogoproto\"\n\t\"github.com/gogo/protobuf/proto\"\n\tdescriptor \"github.com/gogo/protobuf/protoc-gen-gogo/descriptor\"\n)\n\nfunc EnumHasBoolExtension(enum *descriptor.EnumDescriptorProto, extension *proto.ExtensionDesc) bool {\n\tif enum.Options == nil {\n\t\treturn false\n\t}\n\tvalue, err := proto.GetExtension(enum.Options, extension)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif value == nil {\n\t\treturn false\n\t}\n\tif value.(*bool) == nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc SetBoolEnumOption(extension *proto.ExtensionDesc, value bool) func(enum *descriptor.EnumDescriptorProto) {\n\treturn func(enum *descriptor.EnumDescriptorProto) {\n\t\tif EnumHasBoolExtension(enum, extension) {\n\t\t\treturn\n\t\t}\n\t\tif enum.Options == nil {\n\t\t\tenum.Options = &descriptor.EnumOptions{}\n\t\t}\n\t\tif err := proto.SetExtension(enum.Options, extension, &value); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\nfunc TurnOffGoEnumPrefix(enum *descriptor.EnumDescriptorProto) {\n\tSetBoolEnumOption(gogoproto.E_GoprotoEnumPrefix, false)(enum)\n}\n\n\n\nfunc TurnOnEnumStringer(enum *descriptor.EnumDescriptorProto) {\n\tSetBoolEnumOption(gogoproto.E_EnumStringer, true)(enum)\n}\n\nfunc TurnOffGoEnumStringer(enum *descriptor.EnumDescriptorProto) ", "output": "{\n\tSetBoolEnumOption(gogoproto.E_GoprotoEnumStringer, false)(enum)\n}"} {"input": "package mocks\n\nimport mock \"github.com/stretchr/testify/mock\"\n\n\ntype XcconfigWriter struct {\n\tmock.Mock\n}\n\n\n\n\nfunc (_m *XcconfigWriter) Write(content string) (string, error) ", "output": "{\n\tret := _m.Called(content)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string) string); ok {\n\t\tr0 = rf(content)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(content)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}"} {"input": "package logs\n\nimport (\n\t\"io\"\n)\n\ntype stdoutWriter struct {\n\twriter io.Writer\n}\n\ntype stderrorWriter struct {\n\twriter io.Writer\n}\ntype stdbothWriter struct {\n\twriter io.Writer\n}\n\n\n\nfunc (w stderrorWriter) Write(message []byte) (n int, err error) {\n\tn, err = w.writer.Write(append([]byte(\"02 \"), message...))\n\treturn n - 3, err\n}\n\nfunc (w stdbothWriter) Write(message []byte) (n int, err error) {\n\tn, err = w.writer.Write(append([]byte(\"00 \"), message...))\n\treturn n - 3, err\n}\n\nfunc (w stdoutWriter) Write(message []byte) (n int, err error) ", "output": "{\n\tn, err = w.writer.Write(append([]byte(\"01 \"), message...))\n\treturn n - 3, err\n}"} {"input": "package metrics\n\nimport (\n\t\"expvar\"\n\t\"runtime\"\n\t\"sync\"\n)\n\nvar (\n\tm *expvar.Map\n\tonce sync.Once\n)\n\n\n\n\n\nfunc APIError() {\n\tm.Add(\"APIErrors\", 1)\n}\n\n\nfunc RESTError() {\n\tm.Add(\"RESTErrors\", 1)\n}\n\nfunc goroutines() interface{} {\n\treturn runtime.NumGoroutine()\n}\n\nfunc init() ", "output": "{\n\tonce.Do(func() {\n\t\tm = expvar.NewMap(\"errors\")\n\t\tm.Add(\"APIErrors\", 0)\n\t\tm.Add(\"RESTErrors\", 0)\n\t})\n\texpvar.Publish(\"goroutines\", expvar.Func(goroutines))\n}"} {"input": "package internal\n\nimport (\n\t\"bufio\"\n\t\"compress/gzip\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc NewBufferedSectionReader(ra io.ReaderAt, off, n int64) io.Reader {\n\tbuf := n\n\tif ps := int64(os.Getpagesize()); n > ps {\n\t\tbuf = ps\n\t}\n\n\treturn bufio.NewReaderSize(io.NewSectionReader(ra, off, n), int(buf))\n}\n\n\n\ntype DiscardZeroes struct{}\n\nfunc (DiscardZeroes) Write(p []byte) (int, error) {\n\tfor _, b := range p {\n\t\tif b != 0 {\n\t\t\treturn 0, errors.New(\"encountered non-zero byte\")\n\t\t}\n\t}\n\treturn len(p), nil\n}\n\n\n\n\nfunc ReadAllCompressed(file string) ([]byte, error) ", "output": "{\n\tfh, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer fh.Close()\n\n\tgz, err := gzip.NewReader(fh)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer gz.Close()\n\n\treturn io.ReadAll(gz)\n}"} {"input": "package update\n\nimport (\n\t\"github.com/andreaskoch/allmark/common/route\"\n\t\"fmt\"\n\t\"golang.org/x/net/websocket\"\n)\n\nfunc NewConnection(hub *Hub, ws *websocket.Conn, route route.Route) *connection {\n\treturn &connection{\n\t\tRoute: route,\n\n\t\thub: hub,\n\t\tsend: make(chan Message, 10),\n\t\tws: ws,\n\t}\n}\n\ntype connection struct {\n\tRoute route.Route\n\n\thub *Hub\n\n\tws *websocket.Conn\n\n\tsend chan Message\n}\n\n\n\nfunc (c *connection) Send(msg Message) {\n\tc.send <- msg\n}\n\nfunc (c *connection) Reader() {\n\tfor {\n\t\tvar message Message\n\t\terr := websocket.JSON.Receive(c.ws, &message)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tc.hub.broadcast <- message\n\t}\n\n\tc.ws.Close()\n\tc.hub.Unsubscribe(c)\n}\n\nfunc (c *connection) Writer() {\n\tfor message := range c.send {\n\t\terr := websocket.JSON.Send(c.ws, message)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tc.ws.Close()\n\tc.hub.Unsubscribe(c)\n}\n\nfunc (c *connection) String() string ", "output": "{\n\treturn fmt.Sprintf(\"Connection (Route: %s, IP: %s)\", c.Route.String(), c.ws.Request().RemoteAddr)\n}"} {"input": "package native\n\nimport (\n\t\"errors\"\n\n\t\"github.com/CyCoreSystems/ari/v5\"\n)\n\n\ntype Modules struct {\n\tclient *Client\n}\n\n\nfunc (m *Modules) Get(key *ari.Key) *ari.ModuleHandle {\n\treturn ari.NewModuleHandle(m.client.stamp(key), m)\n}\n\n\n\n\n\nfunc (m *Modules) Load(key *ari.Key) error {\n\treturn m.client.post(\"/asterisk/modules/\"+key.ID, nil, nil)\n}\n\n\nfunc (m *Modules) Reload(key *ari.Key) error {\n\treturn m.client.put(\"/asterisk/modules/\"+key.ID, nil, nil)\n}\n\n\nfunc (m *Modules) Unload(key *ari.Key) error {\n\treturn m.client.del(\"/asterisk/modules/\"+key.ID, nil, \"\")\n}\n\n\nfunc (m *Modules) Data(key *ari.Key) (*ari.ModuleData, error) {\n\tif key == nil || key.ID == \"\" {\n\t\treturn nil, errors.New(\"module key not supplied\")\n\t}\n\n\tdata := new(ari.ModuleData)\n\tif err := m.client.get(\"/asterisk/modules/\"+key.ID, data); err != nil {\n\t\treturn nil, dataGetError(err, \"module\", \"%v\", key.ID)\n\t}\n\n\tdata.Key = m.client.stamp(key)\n\n\treturn data, nil\n}\n\nfunc (m *Modules) List(filter *ari.Key) (ret []*ari.Key, err error) ", "output": "{\n\tif filter == nil {\n\t\tfilter = ari.NodeKey(m.client.appName, m.client.node)\n\t}\n\n\tmodules := []struct {\n\t\tName string `json:\"name\"`\n\t}{}\n\n\terr = m.client.get(\"/asterisk/modules\", &modules)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, i := range modules {\n\t\tk := m.client.stamp(ari.NewKey(ari.ModuleKey, i.Name))\n\t\tif filter.Match(k) {\n\t\t\tif filter.Dialog != \"\" {\n\t\t\t\tk.Dialog = filter.Dialog\n\t\t\t}\n\n\t\t\tret = append(ret, k)\n\t\t}\n\t}\n\n\treturn\n}"} {"input": "package database\n\nimport (\n\t\"context\"\n\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n)\n\nfunc (s *Service) Read(req *ReadRequest) (*sacloud.Database, error) {\n\treturn s.ReadWithContext(context.Background(), req)\n}\n\n\n\nfunc (s *Service) ReadWithContext(ctx context.Context, req *ReadRequest) (*sacloud.Database, error) ", "output": "{\n\tif err := req.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tclient := sacloud.NewDatabaseOp(s.caller)\n\treturn client.Read(ctx, req.Zone, req.ID)\n}"} {"input": "package term \n\nimport \"io\"\n\ntype Db []Term\n\n\n\nfunc (s Db) Format(w io.Writer, style Style) {\n\tisRoot := style.IsRoot\n\tstyle.IsRoot = false \n\n\tprevName := \"#\" \n\tfor _, t := range s {\n\t\tif isRoot {\n\t\t\tname := Name(t)\n\t\t\tif prevName != \"#\" && prevName != name {\n\t\t\t\tio.WriteString(w, \"\\n\")\n\t\t\t}\n\t\t\tprevName = name\n\t\t}\n\n\t\tstyle.WriteIndent(w)\n\t\tt.Format(w, style)\n\t}\n}\n\n\ntype Query struct {\n\tdb Db\n\tname string\n\tarity int\n}\n\n\n\n\nfunc (db Db) NewQuery(t Term) *Query {\n\treturn &Query{\n\t\tdb: db,\n\t\tname: Name(t),\n\t\tarity: Arity(t),\n\t}\n}\n\n\n\nfunc (q *Query) Run() *Cursor {\n\treturn &Cursor{\n\t\tq: q,\n\t\ti: 0,\n\t}\n}\n\n\ntype Cursor struct {\n\tq *Query\n\ti int\n}\n\nfunc (c *Cursor) Next() (Term, bool) {\n\tfor ; c.i < len(c.q.db); c.i++ {\n\t\tcandidate := c.q.db[c.i]\n\t\tif Arity(candidate) == c.q.arity && Name(candidate) == c.q.name {\n\t\t\tc.i++\n\t\t\treturn candidate, c.i < len(c.q.db)\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc NewDb(args []Term) Db ", "output": "{\n\treturn Db(args)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"koding/klientctl/config\"\n\t\"koding/klientctl/ctlcli\"\n\n\t\"github.com/koding/logging\"\n\tcli \"gopkg.in/urfave/cli.v1\"\n)\n\nfunc init() {\n\trand.Seed(time.Now().Unix())\n}\n\n\n\n\n\nfunc CheckUpdateFirst(f ctlcli.ExitingCommand, log logging.Logger, cmd string) (ctlcli.ExitingCommand, logging.Logger, string) {\n\n\texitCmd := func(c *cli.Context, log logging.Logger, cmd string) int {\n\t\tif !c.Bool(\"json\") {\n\t\t\tu := NewCheckUpdate()\n\t\t\tif y, err := u.IsUpdateAvailable(); y && err == nil {\n\t\t\t\tfmt.Printf(\"A newer version of %s is available. Please do `sudo %s update`.\\n\", config.Name, config.Name)\n\t\t\t}\n\t\t}\n\n\t\treturn f(c, log, cmd)\n\t}\n\n\treturn exitCmd, log, cmd\n}\n\n\ntype CheckUpdate struct {\n\tLocation string\n\n\tRandomSeededNumber int\n\n\tForceCheck bool\n\n\tLocalVersion int\n}\n\n\n\n\n\nfunc (c *CheckUpdate) IsUpdateAvailable() (bool, error) {\n\tresp, err := http.Get(c.Location)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar newVersion int\n\n\t_, err = fmt.Fscanf(resp.Body, \"%d\", &newVersion)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn newVersion > c.LocalVersion, nil\n}\n\nfunc NewCheckUpdate() *CheckUpdate ", "output": "{\n\treturn &CheckUpdate{\n\t\tLocalVersion: config.VersionNum(),\n\t\tLocation: config.Konfig.Endpoints.KDLatest.Public.String(),\n\t\tRandomSeededNumber: rand.Intn(3),\n\t\tForceCheck: false,\n\t}\n}"} {"input": "package tagquery\n\nimport (\n\t\"io\"\n\n\t\"github.com/grafana/metrictank/schema\"\n)\n\ntype expressionMatchNone struct {\n\texpressionCommon\n\toriginalOperator ExpressionOperator\n}\n\nfunc (e *expressionMatchNone) Equals(other Expression) bool {\n\treturn e.key == other.GetKey() && e.GetOperator() == other.GetOperator() && e.value == other.GetValue()\n}\n\nfunc (e *expressionMatchNone) GetDefaultDecision() FilterDecision {\n\treturn Fail\n}\n\nfunc (e *expressionMatchNone) GetKey() string {\n\treturn e.key\n}\n\nfunc (e *expressionMatchNone) GetValue() string {\n\treturn e.value\n}\n\nfunc (e *expressionMatchNone) GetOperator() ExpressionOperator {\n\treturn MATCH_NONE\n}\n\nfunc (e *expressionMatchNone) GetOperatorCost() uint32 {\n\treturn 0\n}\n\nfunc (e *expressionMatchNone) RequiresNonEmptyValue() bool {\n\treturn true\n}\n\nfunc (e *expressionMatchNone) Matches(value string) bool {\n\treturn false\n}\n\nfunc (e *expressionMatchNone) GetMetricDefinitionFilter(_ IdTagLookup) MetricDefinitionFilter {\n\treturn func(_ schema.MKey, _ string, _ []string) FilterDecision { return Fail }\n}\n\n\n\nfunc (e *expressionMatchNone) StringIntoWriter(writer io.Writer) ", "output": "{\n\twriter.Write([]byte(e.key))\n\te.originalOperator.StringIntoWriter(writer)\n\twriter.Write([]byte(e.value))\n}"} {"input": "package printer\n\nimport (\n\t\"bytes\"\n\t\"k8s.io/kubernetes/third_party/golang/go/ast\"\n\t\"k8s.io/kubernetes/third_party/golang/go/parser\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"testing\"\n)\n\nvar testfile *ast.File\n\n\n\n\nfunc initialize() {\n\tconst filename = \"testdata/parser.go\"\n\n\tsrc, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\n\tfile, err := parser.ParseFile(fset, filename, src, parser.ParseComments)\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\n\tvar buf bytes.Buffer\n\ttestprint(&buf, file)\n\tif !bytes.Equal(buf.Bytes(), src) {\n\t\tlog.Fatalf(\"print error: %s not idempotent\", filename)\n\t}\n\n\ttestfile = file\n}\n\nfunc BenchmarkPrint(b *testing.B) {\n\tif testfile == nil {\n\t\tinitialize()\n\t}\n\tfor i := 0; i < b.N; i++ {\n\t\ttestprint(ioutil.Discard, testfile)\n\t}\n}\n\nfunc testprint(out io.Writer, file *ast.File) ", "output": "{\n\tif err := (&Config{TabIndent | UseSpaces, 8, 0}).Fprint(out, fset, file); err != nil {\n\t\tlog.Fatalf(\"print error: %s\", err)\n\t}\n}"} {"input": "package kvledger\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestCreate(t *testing.T) ", "output": "{\n\tlpath := \"/tmp/ledgerstest\"\n\tos.RemoveAll(lpath)\n\n\tInitialize(lpath)\n\n\tif lgr := GetLedger(\"test\"); lgr == nil {\n\t\tt.FailNow()\n\t}\n\n\tif lgr := GetLedger(\"test\"); lgr == nil {\n\t\tt.FailNow()\n\t}\n}"} {"input": "package disjointset\n\nimport ()\n\ntype QuickUnion struct {\n\tdisjointset\n}\n\n\n\nfunc (this *QuickUnion) Find(p int) int {\n\tfor p != this.id[p] {\n\t\tp = this.id[p]\n\t}\n\treturn p\n}\n\nfunc (this *QuickUnion) Union(p, q int) {\n\tpRoot := this.Find(p)\n\tqRoot := this.Find(q)\n\n\tif pRoot == qRoot {\n\t\treturn\n\t}\n\n\tthis.id[pRoot] = qRoot\n\n\tthis.count--\n}\n\nfunc NewQuickUnion(N int) *QuickUnion ", "output": "{\n\tthis := &QuickUnion{}\n\tthis.UnionFind = this\n\tthis.Init(N)\n\treturn this\n}"} {"input": "package jsons\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\n\ntype FileReader struct {\n\tfilename string\n\tf io.WriteCloser\n\tr *Reader\n}\n\n\n\nfunc NewFileReader(filename string) *FileReader {\n\treturn &FileReader{filename: filename}\n}\n\n\n\n\n\n\nfunc (fr *FileReader) Close() error {\n\treturn fr.f.Close()\n}\n\n\n\nfunc (fr *FileReader) Next(v interface{}) error {\n\treturn fr.r.Next(v)\n}\n\nfunc (fr *FileReader) Open() error ", "output": "{\n\tf, err := os.Open(fr.filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfr.f = f\n\tfr.r = NewReader(f)\n\treturn nil\n}"} {"input": "package openweathermap\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\n\nvar StationDataParameters = []string{\n\t\"wind_dir\", \n\t\"wind_speed\", \n\t\"wind_gust\", \n\t\"temp\", \n\t\"humidity\", \n\t\"pressure\", \n\t\"rain_1h\", \n\t\"rain_24h\", \n\t\"rain_today\", \n\t\"snow\", \n\t\"lum\", \n\t\"lat\", \n\t\"long\", \n\t\"alt\", \n\t\"radiation\", \n\t\"dewpoint\", \n\t\"uv\", \n\t\"name\", \n}\n\n\n\nfunc ValidateStationDataParameter(param string) bool {\n\tfor _, p := range StationDataParameters {\n\t\tif param == p {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\n\n\nfunc ConvertToURLValues(data map[string]string) string {\n\tv := url.Values{}\n\n\tfor key, val := range data {\n\t\tv.Set(key, val)\n\t}\n\n\treturn v.Encode()\n}\n\n\n\n\n\nfunc SendStationData(data url.Values) ", "output": "{\n\tresp, err := http.PostForm(dataPostURL, data)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tfmt.Println(resp.Body)\n}"} {"input": "package types\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"sigs.k8s.io/kustomize/kyaml/resid\"\n)\n\nconst DefaultReplacementFieldPath = \"metadata.name\"\n\n\n\ntype Replacement struct {\n\tSource *SourceSelector `json:\"source\" yaml:\"source\"`\n\n\tTargets []*TargetSelector `json:\"targets\" yaml:\"targets\"`\n}\n\n\ntype SourceSelector struct {\n\tresid.ResId `json:\",inline,omitempty\" yaml:\",inline,omitempty\"`\n\n\tFieldPath string `json:\"fieldPath\" yaml:\"fieldPath\"`\n\n\tOptions *FieldOptions `json:\"options\" yaml:\"options\"`\n}\n\n\n\n\ntype TargetSelector struct {\n\tSelect *Selector `json:\"select\" yaml:\"select\"`\n\n\tReject []*Selector `json:\"reject\" yaml:\"reject\"`\n\n\tFieldPaths []string `json:\"fieldPaths\" yaml:\"fieldPaths\"`\n\n\tOptions *FieldOptions `json:\"options\" yaml:\"options\"`\n}\n\n\ntype FieldOptions struct {\n\tDelimiter string `json:\"delimiter\" yaml:\"delimiter\"`\n\n\tIndex int `json:\"index\" yaml:\"index\"`\n\n\tEncoding string `json:\"encoding\" yaml:\"encoding\"`\n\n\tCreate bool `json:\"create\" yaml:\"create\"`\n}\n\nfunc (fo *FieldOptions) String() string {\n\tif fo == nil || fo.Delimiter == \"\" {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%s(%d)\", fo.Delimiter, fo.Index)\n}\n\nfunc (s *SourceSelector) String() string ", "output": "{\n\tif s == nil {\n\t\treturn \"\"\n\t}\n\tresult := []string{s.ResId.String()}\n\tif s.FieldPath != \"\" {\n\t\tresult = append(result, s.FieldPath)\n\t}\n\tif opts := s.Options.String(); opts != \"\" {\n\t\tresult = append(result, opts)\n\t}\n\treturn strings.Join(result, \":\")\n}"} {"input": "package server\n\nimport (\n\t\"testing\"\n\n\t\"github.com/quaponatech/golang-extensions/test\"\n)\n\nfunc TestSuccessNewLogger(t *testing.T) {\n\tt.Run(\"Succeeds\", func(t *testing.T) {\n\t\ttest.AssertThat(t, New(), nil, \"not\")\n\n\t\tlogger := NewLogger(\n\t\t\t\"serverName\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\tmake(chan Status),\n\t\t\tmake(chan error),\n\t\t\tmake(chan string),\n\t\t\tmake(chan string),\n\t\t\tmake(chan string),\n\t\t\t0)\n\t\ttest.AssertThat(t, logger.StartLogger(), nil)\n\t\tlogger.StopLogger()\n\t\tlogger.WaitGroup.Wait()\n\n\t\tlogger = NewLogger(\n\t\t\t\"serverName\",\n\t\t\t\"test\",\n\t\t\t\"test\",\n\t\t\tnil,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\t0)\n\t\ttest.AssertThat(t, logger, nil, \"not\")\n\t\ttest.AssertThat(t, logger.StartLogger(), nil)\n\t\tlogger.StopLogger()\n\t\tlogger.WaitGroup.Wait()\n\t})\n}\n\n\n\nfunc TestFailureNewLogger(t *testing.T) ", "output": "{\n\tt.Run(\"Succeeds\", func(t *testing.T) {\n\t\tlogger := NewLogger(\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\tnil,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\t0)\n\t\ttest.AssertThat(t, logger, nil, \"not\")\n\n\t\tlogger = NewLogger(\n\t\t\t\"name\",\n\t\t\t\"/this_dir_is_not_writeable\",\n\t\t\t\"/this_dir_is_not_writeable\",\n\t\t\tnil,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\t0)\n\t\ttest.AssertThat(t, logger, nil, \"not\")\n\t})\n}"} {"input": "package vm\n\nimport (\n\t\"github.com/rancher/wrangler/pkg/generic\"\n\t\"k8s.io/client-go/rest\"\n)\n\ntype Factory struct {\n\t*generic.Factory\n}\n\nfunc NewFactoryFromConfigOrDie(config *rest.Config) *Factory {\n\tf, err := NewFactoryFromConfig(config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}\n\nfunc NewFactoryFromConfig(config *rest.Config) (*Factory, error) {\n\treturn NewFactoryFromConfigWithOptions(config, nil)\n}\n\n\n\ntype FactoryOptions = generic.FactoryOptions\n\nfunc NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) {\n\tf, err := generic.NewFactoryFromConfigWithOptions(config, opts)\n\treturn &Factory{\n\t\tFactory: f,\n\t}, err\n}\n\nfunc (c *Factory) Vm() Interface {\n\treturn New(c.ControllerFactory())\n}\n\nfunc NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (*Factory, error) ", "output": "{\n\treturn NewFactoryFromConfigWithOptions(config, &FactoryOptions{\n\t\tNamespace: namespace,\n\t})\n}"} {"input": "package binary\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/google/gapid/core/math/f16\"\n)\n\n\ntype Writer interface {\n\tData([]byte)\n\tBool(bool)\n\tInt8(int8)\n\tUint8(uint8)\n\tInt16(int16)\n\tUint16(uint16)\n\tInt32(int32)\n\tUint32(uint32)\n\tFloat16(f16.Number)\n\tFloat32(float32)\n\tInt64(int64)\n\tUint64(uint64)\n\tFloat64(float64)\n\tString(string)\n\tSimple(Writable)\n\tError() error\n\tSetError(error)\n}\n\n\nfunc WriteUint(w Writer, bits int32, v uint64) {\n\tswitch bits {\n\tcase 8:\n\t\tw.Uint8(uint8(v))\n\tcase 16:\n\t\tw.Uint16(uint16(v))\n\tcase 32:\n\t\tw.Uint32(uint32(v))\n\tcase 64:\n\t\tw.Uint64(uint64(v))\n\tdefault:\n\t\tw.SetError(fmt.Errorf(\"Unsupported integer bit count %v\", bits))\n\t}\n}\n\n\n\n\n\nfunc WriteBytes(w Writer, v uint8, count int32) {\n\tfor i := int32(0); i < count; i++ {\n\t\tw.Uint8(v)\n\t}\n}\n\nfunc WriteInt(w Writer, bits int32, v int64) ", "output": "{\n\tswitch bits {\n\tcase 8:\n\t\tw.Int8(int8(v))\n\tcase 16:\n\t\tw.Int16(int16(v))\n\tcase 32:\n\t\tw.Int32(int32(v))\n\tcase 64:\n\t\tw.Int64(int64(v))\n\tdefault:\n\t\tw.SetError(fmt.Errorf(\"Unsupported integer bit count %v\", bits))\n\t}\n}"} {"input": "package protocol\n\nimport (\n\t\"context\"\n\n\t\"github.com/coffeehc/logger\"\n\t\"github.com/coffeehc/netx\"\n\t\"github.com/ugorji/go/codec\"\n)\n\ntype msgpackProtocol struct {\n\thander *codec.MsgpackHandle\n\tinterf func() interface{}\n}\n\n\nfunc NewMsgpackProcotol(interfFunc func() interface{}) netx.Protocol {\n\tp := &msgpackProtocol{hander: new(codec.MsgpackHandle)}\n\tp.interf = interfFunc\n\tif p.interf == nil {\n\t\tp.interf = func() interface{} {\n\t\t\tvar i interface{}\n\t\t\treturn &i\n\t\t}\n\t}\n\treturn p\n}\n\n\n\nfunc (mp *msgpackProtocol) Decode(cxt context.Context, connContext netx.ConnContext, chain netx.ProtocolChain, data interface{}) {\n\tif v, ok := data.([]byte); ok {\n\t\tobj := mp.interf()\n\t\tdecode := codec.NewDecoderBytes(v, mp.hander)\n\t\terr := decode.Decode(obj)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Msgpack反序列化失败:%s\", err)\n\t\t\treturn\n\t\t}\n\t\tdata = obj\n\t}\n\tchain.Fire(cxt, connContext, data)\n}\n\nfunc (mp *msgpackProtocol) EncodeDestroy() {}\n\nfunc (mp *msgpackProtocol) DecodeDestroy() {}\n\nfunc (mp *msgpackProtocol) Encode(cxt context.Context, connContext netx.ConnContext, chain netx.ProtocolChain, data interface{}) ", "output": "{\n\tvar b []byte\n\tencode := codec.NewEncoderBytes(&b, mp.hander)\n\terr := encode.Encode(data)\n\tif err != nil {\n\t\tlogger.Error(\"Msgpack序列化错误:%s\", err)\n\t\treturn\n\t}\n\tchain.Fire(cxt, connContext, b)\n}"} {"input": "package docker\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/megamsys/vertice/provision/docker\"\n\t\"strings\"\n\t\"text/tabwriter\"\n\n\t\"github.com/megamsys/libgo/cmd\"\n)\n\ntype Bridges map[string]DockerBridge\n\ntype DockerBridge struct {\n\tName string\n\tNetwork string\n\tGateway string\n}\n\nfunc (d DockerBridge) String() string {\n\tw := new(tabwriter.Writer)\n\tvar b bytes.Buffer\n\tw.Init(&b, 1, 8, 0, '\\t', 0)\n\tb.Write([]byte(cmd.Colorfy(\"Bridge\", \"white\", \"\", \"\") + \"\\t\" +\n\t\tcmd.Colorfy(d.Name, \"blue\", \"\", \"\") + \"\\n\"))\n\tb.Write([]byte(\"network\" + \"\\t\" + d.Network + \"\\n\"))\n\tb.Write([]byte(\"gateway\" + \"\\t\" + d.Gateway + \"\\n\"))\n\tb.Write([]byte(\"---\\n\"))\n\tfmt.Fprintln(w)\n\tw.Flush()\n\treturn strings.TrimSpace(b.String())\n}\n\nfunc NewBridgeConfig() *Bridges {\n\tbr := make(Bridges)\n\treturn &br\n}\n\nfunc (c Bridges) ConvertToMap() map[string]string {\n\tvar x map[string]string\n\tfor _, v := range c {\n\t\tx = v.toMap()\n\t}\n\treturn x\n}\n\nfunc (c DockerBridge) toMap() map[string]string {\n\tm := make(map[string]string)\n\tm[docker.BRIDGE_NAME] = c.Name\n\tm[docker.BRIDGE_NETWORK] = c.Network\n\tm[docker.BRIDGE_GATEWAY] = c.Gateway\n\n\treturn m\n}\n\n\n\nfunc (c Bridges) String() string ", "output": "{\n\tbs := make([]string, len(c))\n\tfor _, v := range c {\n\t\tbs = append(bs, v.String(), \"\\n\")\n\t}\n\n\tw := new(tabwriter.Writer)\n\tvar b bytes.Buffer\n\tw.Init(&b, 0, 8, 0, '\\t', 0)\n\tb.Write([]byte(cmd.Colorfy(\"Config:\", \"white\", \"\", \"bold\") + \"\\t\" +\n\t\tcmd.Colorfy(\"bridges\", \"green\", \"\", \"\") + \"\\n\"))\n\tb.Write([]byte(strings.Join(bs, \"\\n\")))\n\tfmt.Fprintln(w)\n\tw.Flush()\n\treturn strings.TrimSpace(b.String())\n\n}"} {"input": "package system\n\nimport (\n\t\"github.com/Graylog2/collector-sidecar/common\"\n\t\"runtime\"\n)\n\ntype Inventory struct {\n}\n\nfunc NewInventory() *Inventory {\n\treturn &Inventory{}\n}\n\nfunc (inv *Inventory) Version() string {\n\treturn common.CollectorVersion\n}\n\nfunc (inv *Inventory) Linux() bool {\n\treturn runtime.GOOS == \"linux\"\n}\n\n\n\nfunc (inv *Inventory) Windows() bool {\n\treturn runtime.GOOS == \"windows\"\n}\n\nfunc (inv *Inventory) LinuxPlatform() string {\n\tif runtime.GOOS == \"linux\" {\n\t\treturn common.LinuxPlatformFamily()\n\t} else {\n\t\treturn runtime.GOOS\n\t}\n}\n\nfunc (inv *Inventory) Darwin() bool ", "output": "{\n\treturn runtime.GOOS == \"darwin\"\n}"} {"input": "package message\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"mime\"\n\t\"strings\"\n)\n\ntype UnknownCharsetError struct {\n\te error\n}\n\nfunc (u UnknownCharsetError) Unwrap() error { return u.e }\n\nfunc (u UnknownCharsetError) Error() string {\n\treturn \"unknown charset: \" + u.e.Error()\n}\n\n\n\nfunc IsUnknownCharset(err error) bool {\n\treturn errors.As(err, new(UnknownCharsetError))\n}\n\n\n\n\n\n\n\n\n\nvar CharsetReader func(charset string, input io.Reader) (io.Reader, error)\n\n\n\n\n\n\nfunc decodeHeader(s string) (string, error) {\n\twordDecoder := mime.WordDecoder{CharsetReader: charsetReader}\n\tdec, err := wordDecoder.DecodeHeader(s)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\treturn dec, nil\n}\n\nfunc encodeHeader(s string) string {\n\treturn mime.QEncoding.Encode(\"utf-8\", s)\n}\n\nfunc charsetReader(charset string, input io.Reader) (io.Reader, error) ", "output": "{\n\tcharset = strings.ToLower(charset)\n\tif charset == \"utf-8\" || charset == \"us-ascii\" {\n\t\treturn input, nil\n\t}\n\tif CharsetReader != nil {\n\t\tr, err := CharsetReader(charset, input)\n\t\tif err != nil {\n\t\t\treturn r, UnknownCharsetError{err}\n\t\t}\n\t\treturn r, nil\n\t}\n\treturn input, UnknownCharsetError{fmt.Errorf(\"message: unhandled charset %q\", charset)}\n}"} {"input": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"os\"\n \"math/rand\"\n \"strconv\"\n)\n\n\n\nfunc evaluation(computer_choice int, human_choice int, resultChannel chan string){\n\tswitch human_choice {\n\tcase 0:\n\t\tswitch computer_choice {\n\t\tcase 0:\n\t\t\tresultChannel <- \"draw\"\n\t\tcase 1:\n\t\t\tresultChannel <- \"loss\"\n\t\tcase 2:\n\t\t\tresultChannel <- \"win\"\n\t\t}\n\tcase 1:\n\t\tswitch computer_choice {\n\t\tcase 0:\n\t\t\tresultChannel <- \"win\"\n\t\tcase 1:\n\t\t\tresultChannel <- \"draw\"\n\t\tcase 2:\n\t\t\tresultChannel <- \"loss\"\n\t\t}\n\tcase 2:\n\t\tswitch computer_choice {\n\t\tcase 0:\n\t\t\tresultChannel <- \"loss\"\n\t\tcase 1:\n\t\t\tresultChannel <- \"win\"\n\t\tcase 2:\n\t\t\tresultChannel <- \"draw\"\n\t\t}\n\tdefault:\n\t\tresultChannel <- \"Only numbers between 0 and 2 are valid!\"\n\t}\n\tclose(resultChannel)\n}\n\nfunc main() {\n\tcomputerChannel := make(chan int)\n\tresultChannel := make(chan string)\n\tgo computer(computerChannel, resultChannel)\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Println(\"Choose: \\n 0 = rock\\n 1 = paper\\n 2 = scissors\")\n\ttext, _ := reader.ReadString('\\n')\n\tchoice, _ := strconv.Atoi(text)\n\tcomputerChannel <- choice\n\tclose(computerChannel)\n\tfor message := range resultChannel {\n fmt.Println(\"Result:\", message)\n }\n}\n\nfunc computer(inputChannel chan int, resultChannel chan string)", "output": "{\n for human_choice := range inputChannel {\n \tcomputer_choice := rand.Intn(3)\n \tevaluation(computer_choice, human_choice, resultChannel)\n }\n}"} {"input": "package vm\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\n\n\ntype stack struct {\n\tdata []*big.Int\n\tptr int\n}\n\nfunc (st *stack) push(d *big.Int) {\n\tstackItem := new(big.Int).Set(d)\n\tif len(st.data) > st.ptr {\n\t\tst.data[st.ptr] = stackItem\n\t} else {\n\t\tst.data = append(st.data, stackItem)\n\t}\n\tst.ptr++\n}\n\nfunc (st *stack) pop() (ret *big.Int) {\n\tst.ptr--\n\tret = st.data[st.ptr]\n\treturn\n}\n\nfunc (st *stack) len() int {\n\treturn st.ptr\n}\n\nfunc (st *stack) swap(n int) {\n\tst.data[st.len()-n], st.data[st.len()-1] = st.data[st.len()-1], st.data[st.len()-n]\n}\n\nfunc (st *stack) dup(n int) {\n\tst.push(st.data[st.len()-n])\n}\n\nfunc (st *stack) peek() *big.Int {\n\treturn st.data[st.len()-1]\n}\n\nfunc (st *stack) require(n int) error {\n\tif st.len() < n {\n\t\treturn fmt.Errorf(\"stack underflow (%d <=> %d)\", len(st.data), n)\n\t}\n\treturn nil\n}\n\nfunc (st *stack) Print() {\n\tfmt.Println(\"### stack ###\")\n\tif len(st.data) > 0 {\n\t\tfor i, val := range st.data {\n\t\t\tfmt.Printf(\"%-3d %v\\n\", i, val)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"-- empty --\")\n\t}\n\tfmt.Println(\"#############\")\n}\n\nfunc newStack() *stack ", "output": "{\n\treturn &stack{}\n}"} {"input": "package object\n\nimport (\n\t\"hash/fnv\"\n)\n\n\ntype String struct {\n\tValue string\n}\n\n\nfunc (s *String) Type() ObjectType {\n\treturn STRING_OBJ\n}\n\n\n\n\n\nfunc (s *String) HashKey() HashKey {\n\th := fnv.New64a()\n\th.Write([]byte(s.Value))\n\n\treturn HashKey{Type: s.Type(), Value: h.Sum64()}\n}\n\nfunc (s *String) Inspect() string ", "output": "{\n\treturn s.Value\n}"} {"input": "package kafka\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestOptionWithURL(t *testing.T) {\n\tvar options Options\n\n\tWithTopics(`topic-test1`, `topic-test2`)(&options)\n\tassert.ElementsMatch(t, []string{`topic-test1`, `topic-test2`}, options.Topics)\n\n\tWithKafkaURL(`nats://demo1:8000,demo2:8000/test?topics=topic1,topic2`)(&options)\n\tassert.ElementsMatch(t, []string{`demo1:8000`, `demo2:8000`}, options.Brokers)\n\tassert.ElementsMatch(t, []string{`topic1`, `topic2`}, options.Topics)\n\tassert.Equal(t, `test`, options.group())\n}\n\nfunc TestOption(t *testing.T) ", "output": "{\n\tvar options Options\n\tassert.Equal(t, `default`, options.group())\n\tassert.NotNil(t, options.logger(), `logger`)\n}"} {"input": "package spi\n\n\nfunc NewGroup(group *GroupInfo) Group {\n\treturn group\n}\n\n\nfunc (g *GroupInfo) GetName() string {\n\treturn g.Name\n}\n\n\n\n\n\nfunc (g *GroupInfo) GetParent() string {\n\treturn g.ParentID\n}\n\nfunc (g *GroupInfo) GetChildren() ([]Group, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\t\"github.com/akaspin/bar/client/lists\"\n\t\"github.com/akaspin/bar/client/model\"\n\t\"github.com/akaspin/bar/client/transport\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype DownCmd struct {\n\t*Environment\n\t*CommonOptions\n\n\tUseGit bool\n}\n\n\n\nfunc (c *DownCmd) Run(args ...string) (err error) {\n\tvar mod *model.Model\n\n\tif mod, err = model.New(c.WD, c.UseGit, c.ChunkSize, c.PoolSize); err != nil {\n\t\treturn\n\t}\n\n\tfeed := lists.NewFileList(args...).ListDir(c.WD)\n\n\tisDirty, dirty, err := mod.Check(feed...)\n\tif err != nil {\n\t\treturn\n\t}\n\tif isDirty {\n\t\terr = fmt.Errorf(\"dirty files in working tree %s\", dirty)\n\t\treturn\n\t}\n\n\tif c.UseGit {\n\t\tfeed, err = mod.Git.FilterByAttr(\"bar\", feed...)\n\t}\n\n\tblobs, err := mod.FeedManifests(false, true, true, feed...)\n\tif err != nil {\n\t\treturn\n\t}\n\n\ttrans := transport.NewTransport(mod, \"\", c.Endpoint, c.PoolSize)\n\tif err = trans.Download(blobs); err != nil {\n\t\treturn\n\t}\n\n\tif c.UseGit {\n\t\terr = mod.Git.UpdateIndex(blobs.Names()...)\n\t}\n\n\treturn\n}\n\nfunc (c *DownCmd) Init(cc *cobra.Command) ", "output": "{\n\tcc.Use = \"down [# path]\"\n\tcc.Short = \"download BLOBs from bar server\"\n\n\tcc.Flags().BoolVarP(&c.UseGit, \"git\", \"\", false, \"use git infrastructure\")\n}"} {"input": "package permute\n\nimport \"testing\"\n\nfunc BenchmarkPermGenLex(b *testing.B) {\n\tp := New(20)\n\tfor i := 0; i < b.N; i++ {\n\t\tLexNext(p)\n\t}\n}\n\nfunc BenchmarkPermGenSJT(b *testing.B) {\n\th := NewPlainChangeGen(20)\n\tvar sw [2]int\n\tfor i := 0; i < b.N; i++ {\n\t\th.Next(&sw)\n\t}\n}\n\nfunc BenchmarkPermGenHeap(b *testing.B) {\n\th := NewHeap(20)\n\tvar sw [2]int\n\tfor i := 0; i < b.N; i++ {\n\t\th.Next(&sw)\n\t}\n}\n\n\nfunc BenchmarkPermGenEven(b *testing.B) ", "output": "{\n\th := NewPlainChangeFastGen(20)\n\tvar sw [2]int\n\tfor i := 0; i < b.N; i++ {\n\t\th.Next(&sw)\n\t}\n}"} {"input": "package mytime\n\nimport (\n\t\"cloud.google.com/go/spanner\"\n\t\"github.com/tcncloud/protoc-gen-persist/examples/test\"\n)\n\ntype MyEnum struct {\n\tStatus int32\n}\n\nfunc (t MyEnum) ToSpanner(src test.TestEnum) *MyEnum{\n\tt.Status = int32(src)\n\n\treturn &t\n}\n\n\n\nfunc (t *MyEnum) SpannerScan(src *spanner.GenericColumnValue) error {\n\tvar lt int64\n\n\terr := src.Decode(<)\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.Status = int32(lt)\n\n\treturn nil\n}\n\nfunc (t *MyEnum) SpannerValue() (interface{}, error) {\n\treturn int64(t.Status), nil\n}\n\nfunc (t MyEnum) ToProto() test.TestEnum ", "output": "{\n\treturn test.TestEnum(t.Status)\n}"} {"input": "package policy\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\nfunc New(subscriptionID string) BaseClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient ", "output": "{\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package Filter\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/reactivego/scheduler\"\n\t\"github.com/reactivego/subscriber\"\n)\n\n\n\n\ntype Scheduler = scheduler.Scheduler\n\n\n\n\n\n\ntype Subscriber = subscriber.Subscriber\n\n\n\n\n\n\n\n\n\ntype IntObserver func(next int, err error, done bool)\n\n\n\n\n\ntype ObservableInt func(IntObserver, Scheduler, Subscriber)\n\n\n\n\nfunc FromInt(slice ...int) ObservableInt {\n\tobservable := func(observe IntObserver, scheduler Scheduler, subscriber Subscriber) {\n\t\ti := 0\n\t\trunner := scheduler.ScheduleRecursive(func(self func()) {\n\t\t\tif subscriber.Subscribed() {\n\t\t\t\tif i < len(slice) {\n\t\t\t\t\tobserve(slice[i], nil, false)\n\t\t\t\t\tif subscriber.Subscribed() {\n\t\t\t\t\t\ti++\n\t\t\t\t\t\tself()\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tvar zero int\n\t\t\t\t\tobserve(zero, nil, true)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\tsubscriber.OnUnsubscribe(runner.Cancel)\n\t}\n\treturn observable\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (o ObservableInt) Println(a ...interface{}) error {\n\tsubscriber := subscriber.New()\n\tscheduler := scheduler.MakeTrampoline()\n\tobserver := func(next int, err error, done bool) {\n\t\tif !done {\n\t\t\tfmt.Println(append(a, next)...)\n\t\t} else {\n\t\t\tsubscriber.Done(err)\n\t\t}\n\t}\n\tsubscriber.OnWait(scheduler.Wait)\n\to(observer, scheduler, subscriber)\n\treturn subscriber.Wait()\n}\n\nfunc (o ObservableInt) Filter(predicate func(next int) bool) ObservableInt ", "output": "{\n\tobservable := func(observe IntObserver, subscribeOn Scheduler, subscriber Subscriber) {\n\t\tobserver := func(next int, err error, done bool) {\n\t\t\tif done || predicate(next) {\n\t\t\t\tobserve(next, err, done)\n\t\t\t}\n\t\t}\n\t\to(observer, subscribeOn, subscriber)\n\t}\n\treturn observable\n}"} {"input": "package soundcloud\n\nimport (\n\t\"net/url\"\n)\n\ntype PlaylistApi struct {\n\tplaylistEndpoint\n}\n\n\n\nfunc (api *Api) Playlist(id uint64) *PlaylistApi {\n\treturn &PlaylistApi{*api.newPlaylistEndpoint(\"playlists\", id)}\n}\n\nfunc (api *Api) Playlists(params url.Values) ([]*Playlist, error) ", "output": "{\n\tret := make([]*Playlist, 0)\n\terr := api.get(\"/playlists\", params, &ret)\n\treturn ret, err\n}"} {"input": "package gostatic\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n)\n\nconst (\n\tPre = 1 << iota\n\tHidden\n\tPost\n)\n\ntype Processor interface {\n\tProcess(page *Page, args []string) error\n\tDescription() string\n\tMode() int\n}\n\n\n\n\n\nfunc (s *Site) InitProcessors(m map[string]Processor) {\n\ts.Processors = m\n}\n\n\n\nfunc (s *Site) ProcessCommand(page *Page, cmd *Command, pre bool) error {\n\tc := string(*cmd)\n\tif strings.HasPrefix(c, \":\") {\n\t\tc = \"external \" + c[1:]\n\t}\n\tbits := strings.Split(c, \" \")\n\n\tprocessor := s.Processors[bits[0]]\n\tif processor == nil {\n\t\treturn fmt.Errorf(\"Processor is nil\")\n\t}\n\tif (processor.Mode()&Pre != 0) != pre {\n\t\treturn nil\n\t}\n\tif processor == nil {\n\t\treturn fmt.Errorf(\"processor '%s' not found\", bits[0])\n\t}\n\treturn processor.Process(page, bits[1:])\n}\n\nfunc (s *Site) ProcessorSummary() ", "output": "{\n\tkeys := make([]string, 0, len(s.Processors))\n\tfor k := range s.Processors {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\n\tfor _, k := range keys {\n\t\tp := s.Processors[k]\n\t\tif p.Mode()&Hidden != 0 {\n\t\t\tcontinue\n\t\t}\n\t\tpre := \"\"\n\t\tif p.Mode()&Pre != 0 {\n\t\t\tpre = \"(preprocessor)\"\n\t\t}\n\t\tfmt.Printf(\"- %s %s\\n\\t%s\\n\", k, pre, p.Description())\n\t}\n}"} {"input": "package image\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestMain(m *testing.M) ", "output": "{\n\tos.Exit(m.Run())\n}"} {"input": "package mongo\n\nimport (\n\t\"github.com/peteraba/d5/lib/util\"\n\t\"gopkg.in/mgo.v2\"\n)\n\nvar (\n\tsession *mgo.Session\n\tdb *mgo.Database\n)\n\nfunc SetMgoSession(mgoSession *mgo.Session) {\n\tsession = mgoSession\n}\n\nfunc SetMgoDb(mgoDatabase *mgo.Database) {\n\tdb = mgoDatabase\n}\n\nfunc CreateMgoDbFromEnvs() *mgo.Database {\n\tdbHost, dbName := ParseDbEnvs()\n\n\tmgoDb, err := CreateMgoDb(dbHost, dbName)\n\n\tif err != nil {\n\t\tutil.LogFatalfMsg(err, \"MongoDB database could not be created: %v\", true)\n\t}\n\n\treturn mgoDb\n}\n\nfunc CreateMgoDb(dbHost, dbName string) (*mgo.Database, error) {\n\tsession, err := getMgoSession(dbHost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn getMgoDb(session, dbName), nil\n}\n\nfunc getMgoSession(dbHost string) (*mgo.Session, error) {\n\tvar (\n\t\terr error\n\t)\n\n\tif session != nil {\n\t\treturn session, nil\n\t}\n\n\tsession, err = mgo.Dial(dbHost)\n\n\treturn session, err\n}\n\n\n\nfunc getMgoDb(mgoSession *mgo.Session, dbName string) *mgo.Database ", "output": "{\n\tif db != nil {\n\t\treturn db\n\t}\n\n\tmgoSession = mgoSession.Clone()\n\n\tdb = mgoSession.DB(dbName)\n\n\treturn db\n}"} {"input": "package basename_test\n\nimport (\n\t\"testing\"\n\n\t\".\"\n)\n\nconst (\n\tpath = \"/very/long/path/to/a/file/with.some.extension.hello\"\n)\n\nfunc TestLoop(t *testing.T) {\n\texpected := \"with.some.extension\"\n\tif actual := basename.Loop(path); actual != expected {\n\t\tt.Errorf(\"actual: %s\", actual)\n\t\tt.Errorf(\"expected: %s\", expected)\n\t}\n}\n\nfunc TestLastIndex(t *testing.T) {\n\texpected := \"with.some.extension\"\n\tif actual := basename.LastIndex(path); actual != expected {\n\t\tt.Errorf(\"actual: %s\", actual)\n\t\tt.Errorf(\"expected: %s\", expected)\n\t}\n}\n\nfunc BenchmarkLoop(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbasename.Loop(path)\n\t}\n}\n\n\n\nfunc BenchmarkLastIndex(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tbasename.LastIndex(path)\n\t}\n}"} {"input": "package influxdb\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"testing\"\n\t\"time\"\n\n\t\"go.k6.io/k6/stats\"\n)\n\nfunc benchmarkInfluxdb(b *testing.B, t time.Duration) {\n\ttestOutputCycle(b, func(rw http.ResponseWriter, r *http.Request) {\n\t\tfor {\n\t\t\ttime.Sleep(t)\n\t\t\tm, _ := io.CopyN(ioutil.Discard, r.Body, 1<<18) \n\t\t\tif m == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\trw.WriteHeader(204)\n\t}, func(tb testing.TB, c *Output) {\n\t\tb = tb.(*testing.B)\n\t\tb.ResetTimer()\n\n\t\tsamples := make(stats.Samples, 10)\n\t\tfor i := 0; i < len(samples); i++ {\n\t\t\tsamples[i] = stats.Sample{\n\t\t\t\tMetric: stats.New(\"testGauge\", stats.Gauge),\n\t\t\t\tTime: time.Now(),\n\t\t\t\tTags: stats.NewSampleTags(map[string]string{\n\t\t\t\t\t\"something\": \"else\",\n\t\t\t\t\t\"VU\": \"21\",\n\t\t\t\t\t\"else\": \"something\",\n\t\t\t\t}),\n\t\t\t\tValue: 2.0,\n\t\t\t}\n\t\t}\n\n\t\tb.ResetTimer()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tc.AddMetricSamples([]stats.SampleContainer{samples})\n\t\t\ttime.Sleep(time.Nanosecond * 20)\n\t\t}\n\t})\n}\n\n\n\nfunc BenchmarkInfluxdb2Second(b *testing.B) {\n\tbenchmarkInfluxdb(b, 2*time.Second)\n}\n\nfunc BenchmarkInfluxdb100Milliseconds(b *testing.B) {\n\tbenchmarkInfluxdb(b, 100*time.Millisecond)\n}\n\nfunc BenchmarkInfluxdb1Second(b *testing.B) ", "output": "{\n\tbenchmarkInfluxdb(b, time.Second)\n}"} {"input": "package stats\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/go-webpack/webpack/util\"\n\t\"github.com/pkg/errors\"\n)\n\ntype assetList map[string][]string\n\n\nfunc Read(isDev bool, host, fsPath, webPath string) (assetList, error) {\n\tvar data []byte\n\tvar err error\n\n\tif isDev {\n\t\tdata, err = devManifest(host, webPath)\n\t} else {\n\t\tdata, err = prodManifest(fsPath)\n\t}\n\n\tif err != nil {\n\t\treturn assetList{}, errors.Wrap(err, \"go-webpack: Error reading manifest\")\n\t}\n\n\treturn parseManifest(data)\n}\n\n\n\n\nfunc parseManifest(data []byte) (assetList, error) {\n\tvar err error\n\n\tresp := statsResponse{}\n\terr = json.Unmarshal(data, &resp)\n\tif err != nil {\n\t\treturn assetList{}, errors.Wrap(err, \"go-webpack: Error parsing manifest - json decode\")\n\t}\n\twebpackBase := resp.PublicPath\n\n\tassets := make(assetList, len(resp.AssetsByChunkName))\n\n\tfor akey, aval := range resp.AssetsByChunkName {\n\t\tvar d []string\n\t\terr = json.Unmarshal(*aval, &d)\n\t\tif err != nil {\n\t\t\treturn assets, errors.Wrap(err, fmt.Sprintf(\"go-webpack: Error when parsing manifest for %s: %s %s\", akey, err, string(*aval)))\n\t\t}\n\t\tfor i, v := range d {\n\t\t\td[i] = webpackBase + v\n\t\t}\n\n\t\tparseChunk(d, akey, &assets)\n\t}\n\treturn assets, nil\n}\n\nfunc parseChunk(d []string, akey string, assets *assetList) ", "output": "{\n\t(*assets)[akey+\".js\"] = util.Filter(d, func(v string) bool {\n\t\treturn strings.HasSuffix(v, \".js\")\n\t})\n\n\t(*assets)[akey+\".css\"] = util.Filter(d, func(v string) bool {\n\t\treturn strings.HasSuffix(v, \".css\")\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-chi/chi\"\n)\n\ntype todosResource struct{}\n\n\nfunc (rs todosResource) Routes() chi.Router {\n\tr := chi.NewRouter()\n\n\tr.Get(\"/\", rs.List) \n\tr.Post(\"/\", rs.Create) \n\tr.Put(\"/\", rs.Delete)\n\n\tr.Route(\"/{id}\", func(r chi.Router) {\n\t\tr.Get(\"/\", rs.Get) \n\t\tr.Put(\"/\", rs.Update) \n\t\tr.Delete(\"/\", rs.Delete) \n\t\tr.Get(\"/sync\", rs.Sync)\n\t})\n\n\treturn r\n}\n\nfunc (rs todosResource) List(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todos list of stuff..\"))\n}\n\nfunc (rs todosResource) Create(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todos create\"))\n}\n\n\n\nfunc (rs todosResource) Update(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo update\"))\n}\n\nfunc (rs todosResource) Delete(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo delete\"))\n}\n\nfunc (rs todosResource) Sync(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo sync\"))\n}\n\nfunc (rs todosResource) Get(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tw.Write([]byte(\"todo get\"))\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype dumpXLIFF struct {\n\tinFile string\n}\n\n\n\nfunc (d *dumpXLIFF) Description() string {\n\treturn \"Dumps XLIFF as parsed\"\n}\n\nfunc (d *dumpXLIFF) ParseArgs(base string, args []string) error {\n\tvar fs = flag.NewFlagSet(base+\" dump\", flag.ExitOnError)\n\tfs.StringVar(&d.inFile, \"in\", \"\", \"infile\")\n\treturn fs.Parse(args)\n}\n\nfunc (d *dumpXLIFF) Prepare() error {\n\treturn nil\n}\n\nfunc (d *dumpXLIFF) Convert(w io.Writer) error {\n\n\tvar doc, err = xliffFromFile(d.inFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, file := range doc.File {\n\n\t\tfor _, unit := range file.Body.TransUnit {\n\n\t\t\tfmt.Fprintf(w, \"unit %s\\n\", unit.ID)\n\t\t\tfmt.Fprintf(w, \" source: %v\\n\", unit.Source)\n\t\t\tfmt.Fprintf(w, \" target: %v\\n\", unit.Target)\n\n\t\t}\n\t}\n\n\treturn err\n}\n\nfunc init() ", "output": "{\n\tregisteredConverters[\"dump\"] = new(dumpXLIFF)\n}"} {"input": "package router\n\n\n\n\nimport (\n\t\"github.com/weaveworks/mesh\"\n)\n\n\n\ntype AWSVPCConnection struct {\n\testablishedChan chan struct{}\n\terrorChan chan error\n}\n\nfunc (conn *AWSVPCConnection) Confirm() {\n\tclose(conn.establishedChan)\n}\n\nfunc (conn *AWSVPCConnection) EstablishedChannel() <-chan struct{} {\n\treturn conn.establishedChan\n}\n\nfunc (conn *AWSVPCConnection) ErrorChannel() <-chan error {\n\treturn conn.errorChan\n}\n\nfunc (conn *AWSVPCConnection) Stop() {}\n\nfunc (conn *AWSVPCConnection) ControlMessage(tag byte, msg []byte) {\n}\n\nfunc (conn *AWSVPCConnection) DisplayName() string {\n\treturn \"awsvpc\"\n}\n\n\n\n\n\ntype AWSVPC struct{}\n\nfunc NewAWSVPC() AWSVPC {\n\treturn AWSVPC{}\n}\n\n\n\nfunc (vpc AWSVPC) AddFeaturesTo(features map[string]string) {}\n\nfunc (vpc AWSVPC) PrepareConnection(params mesh.OverlayConnectionParams) (mesh.OverlayConnection, error) {\n\tconn := &AWSVPCConnection{\n\t\testablishedChan: make(chan struct{}),\n\t\terrorChan: make(chan error, 1),\n\t}\n\treturn conn, nil\n}\n\nfunc (vpc AWSVPC) Diagnostics() interface{} {\n\treturn nil\n}\n\n\n\nfunc (vpc AWSVPC) InvalidateRoutes() {}\n\nfunc (vpc AWSVPC) InvalidateShortIDs() {}\n\nfunc (vpc AWSVPC) StartConsumingPackets(localPeer *mesh.Peer, peers *mesh.Peers, consumer OverlayConsumer) error {\n\treturn nil\n}\n\nfunc (conn *AWSVPCConnection) Forward(key ForwardPacketKey) FlowOp ", "output": "{\n\treturn DiscardingFlowOp{}\n}"} {"input": "package mysql\n\nimport (\n\t\"encoding/binary\"\n\n\t\"github.com/berkaroad/saashard/errors\"\n)\n\n\n\n\nfunc (p *PacketIO) handleErrorPacket(capability uint32, data []byte) error {\n\tif data[0] != ERR_HEADER {\n\t\treturn nil\n\t}\n\n\te := new(errors.SqlError)\n\tvar pos = 1\n\n\te.Code = binary.LittleEndian.Uint16(data[pos:])\n\tpos += 2\n\n\tif capability&CLIENT_PROTOCOL_41 > 0 {\n\t\tpos++\n\t\te.State = string(data[pos : pos+5])\n\t\tpos += 5\n\t}\n\n\te.Message = string(data[pos:])\n\treturn e\n}\n\nfunc (p *PacketIO) WriteError(capability uint32, e error) error ", "output": "{\n\tvar m *errors.SqlError\n\tvar ok bool\n\tif m, ok = e.(*errors.SqlError); !ok {\n\t\tm = NewError(ER_UNKNOWN_ERROR, e.Error())\n\t}\n\n\tdata := make([]byte, 4, 16+len(m.Message))\n\n\tdata = append(data, ERR_HEADER)\n\tdata = append(data, byte(m.Code), byte(m.Code>>8))\n\n\tif capability&CLIENT_PROTOCOL_41 > 0 {\n\t\tdata = append(data, '#')\n\t\tdata = append(data, m.State...)\n\t}\n\n\tdata = append(data, m.Message...)\n\n\treturn p.WritePacket(data)\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype UpdateDedicatedVmHostRequest struct {\n\n\tDedicatedVmHostId *string `mandatory:\"true\" contributesTo:\"path\" name:\"dedicatedVmHostId\"`\n\n\tUpdateDedicatedVmHostDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateDedicatedVmHostRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request UpdateDedicatedVmHostRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\n\n\n\ntype UpdateDedicatedVmHostResponse struct {\n\n\tRawResponse *http.Response\n\n\tDedicatedVmHost `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateDedicatedVmHostResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateDedicatedVmHostResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateDedicatedVmHostRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package atomic\n\nimport (\n\t\"encoding/json\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\n\ntype Uint32 struct {\n\t_ nocmp \n\n\tv uint32\n}\n\n\nfunc NewUint32(val uint32) *Uint32 {\n\treturn &Uint32{v: val}\n}\n\n\nfunc (i *Uint32) Load() uint32 {\n\treturn atomic.LoadUint32(&i.v)\n}\n\n\nfunc (i *Uint32) Add(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, delta)\n}\n\n\nfunc (i *Uint32) Sub(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, ^(delta - 1))\n}\n\n\n\n\n\nfunc (i *Uint32) Dec() uint32 {\n\treturn i.Sub(1)\n}\n\n\nfunc (i *Uint32) CAS(old, new uint32) (swapped bool) {\n\treturn atomic.CompareAndSwapUint32(&i.v, old, new)\n}\n\n\nfunc (i *Uint32) Store(val uint32) {\n\tatomic.StoreUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) Swap(val uint32) (old uint32) {\n\treturn atomic.SwapUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(i.Load())\n}\n\n\nfunc (i *Uint32) UnmarshalJSON(b []byte) error {\n\tvar v uint32\n\tif err := json.Unmarshal(b, &v); err != nil {\n\t\treturn err\n\t}\n\ti.Store(v)\n\treturn nil\n}\n\n\nfunc (i *Uint32) String() string {\n\tv := i.Load()\n\treturn strconv.FormatUint(uint64(v), 10)\n}\n\nfunc (i *Uint32) Inc() uint32 ", "output": "{\n\treturn i.Add(1)\n}"} {"input": "package cryptex\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/sha256\"\n\t\"crypto/x509\"\n\t\"errors\"\n)\n\n\n\nfunc NewRSA(publicKey []byte, comment string) *RSA {\n\treturn &RSA{\n\t\tPublicKey: publicKey,\n\t\tcomment: comment,\n\t}\n}\n\n\nfunc (c *RSA) Comment() string {\n\treturn c.comment\n}\n\n\n\nfunc (c *RSA) Close(inputs, secrets [][]byte) error {\n\tif len(inputs) != 2 {\n\t\treturn errors.New(\"RSA supports exactly 2 inputs\")\n\t}\n\tif len(secrets) != 1 {\n\t\treturn errors.New(\"RSA supports only a single secret\")\n\t}\n\tsecret := secrets[0]\n\n\tpubKey, err := c.publicKey()\n\tif err != nil {\n\t\treturn err\n\t}\n\tct, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pubKey, secret, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tinputs[0] = ct\n\tinputs[1] = nil\n\treturn nil\n}\n\n\n\nfunc (c *RSA) Open(secrets, inputs [][]byte) error {\n\tif len(inputs) != 2 {\n\t\treturn errors.New(\"len(inputs) must be 2\")\n\t}\n\tif len(secrets) != 1 {\n\t\treturn errors.New(\"Too many secrets expected\")\n\t}\n\n\tct := inputs[0]\n\tprivKey, err := x509.ParsePKCS1PrivateKey(inputs[1])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsecret, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privKey, ct, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsecrets[0] = secret\n\treturn nil\n}\n\n\n\nfunc (c *RSA) publicKey() (*rsa.PublicKey, error) ", "output": "{\n\tpubKey, err := x509.ParsePKIXPublicKey(c.PublicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif pubKey, ok := pubKey.(*rsa.PublicKey); ok {\n\t\treturn pubKey, nil\n\t}\n\treturn nil, errors.New(\"invalid RSA public key\")\n}"} {"input": "package sshConfig\n\n\nfunc ValidAddressFamilyAnswers() []string {\n\treturn []string{\"\", \"any\", \"inet\", \"inet6\"}\n}\n\n\n\n\n\n\n\n\nfunc ValidStringArgs(possibilities []string, received string) bool {\n\tfor _, possible := range possibilities {\n\t\tif possible == received {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc ValidYesOrNo() []string ", "output": "{\n\treturn []string{\"\", \"yes\", \"no\"}\n}"} {"input": "package netlink\n\nimport (\n\t\"fmt\"\n\t\"net\"\n)\n\n\ntype Rule struct {\n\tPriority int\n\tFamily int\n\tTable int\n\tMark int\n\tMask int\n\tTunID uint\n\tGoto int\n\tSrc *net.IPNet\n\tDst *net.IPNet\n\tFlow int\n\tIifName string\n\tOifName string\n\tSuppressIfgroup int\n\tSuppressPrefixlen int\n}\n\n\n\n\nfunc NewRule() *Rule {\n\treturn &Rule{\n\t\tSuppressIfgroup: -1,\n\t\tSuppressPrefixlen: -1,\n\t\tPriority: -1,\n\t\tMark: -1,\n\t\tMask: -1,\n\t\tGoto: -1,\n\t\tFlow: -1,\n\t}\n}\n\nfunc (r Rule) String() string ", "output": "{\n\treturn fmt.Sprintf(\"ip rule %d: from %s table %d\", r.Priority, r.Src, r.Table)\n}"} {"input": "package redis\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\n\t\"github.com/iris-framework/iris/adaptors/sessions/sessiondb/redis/service\"\n)\n\n\ntype Database struct {\n\tredis *service.Service\n}\n\n\nfunc New(cfg ...service.Config) *Database {\n\treturn &Database{redis: service.New(cfg...)}\n}\n\n\nfunc (d *Database) Config() *service.Config {\n\treturn d.redis.Config\n}\n\n\n\n\n\nfunc serialize(values map[string]interface{}) []byte {\n\tval, err := SerializeBytes(values)\n\tif err != nil {\n\t\tprintln(\"On redisstore.serialize: \" + err.Error())\n\t}\n\n\treturn val\n}\n\n\nfunc (d *Database) Update(sid string, newValues map[string]interface{}) {\n\tif len(newValues) == 0 {\n\t\tgo d.redis.Delete(sid)\n\t} else {\n\t\tgo d.redis.Set(sid, serialize(newValues)) \n\t}\n\n}\n\n\nfunc SerializeBytes(m interface{}) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tenc := gob.NewEncoder(buf)\n\terr := enc.Encode(m)\n\tif err == nil {\n\t\treturn buf.Bytes(), nil\n\t}\n\treturn nil, err\n}\n\n\nfunc DeserializeBytes(b []byte, m interface{}) error {\n\tdec := gob.NewDecoder(bytes.NewBuffer(b))\n\treturn dec.Decode(m) \n}\n\nfunc (d *Database) Load(sid string) map[string]interface{} ", "output": "{\n\tvalues := make(map[string]interface{})\n\n\tif !d.redis.Connected { \n\t\td.redis.Connect()\n\t\t_, err := d.redis.PingPong()\n\t\tif err != nil {\n\t\t\tif err != nil {\n\t\t\t}\n\t\t}\n\t}\n\tval, err := d.redis.GetBytes(sid)\n\tif err == nil {\n\t\tDeserializeBytes(val, &values)\n\t}\n\n\treturn values\n\n}"} {"input": "package validator\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\n\n\nfunc IsWord(str string, params ...int) bool {\n\tif IsNull(str) {\n\t\treturn false\n\t}\n\treturn rxWord.MatchString(str)\n}\n\nfunc IsTime(str string, format string) bool {\n\t_, err := time.Parse(format, str)\n\treturn err == nil\n}\n\nfunc IsDate(str string, format ...string) bool {\n\n\tif len(format) == 0 {\n\n\t\tif len(strings.Split(str, \"/\")) > 1 {\n\t\t\treturn IsTime(str, \"2006/01/02\")\n\t\t}\n\n\t\tif len(strings.Split(str, \"-\")) > 1 {\n\t\t\treturn IsTime(str, \"2006-01-02\")\n\t\t}\n\n\t\treturn false\n\t}\n\n\treturn IsTime(str, format[0])\n}\n\nfunc IsEmpty(str string) bool {\n\treturn len(strings.TrimSpace(str)) == 0\n}\n\nfunc IsRequestURI(rawurl string) bool {\n\t_, err := url.ParseRequestURI(rawurl)\n\treturn err == nil\n}\n\nfunc IsURI(str string) bool {\n\trelation := false\n\tfor idx, val := range str {\n\t\tif val == '.' {\n\t\t\trelation = true\n\t\t\tcontinue\n\t\t}\n\t\tif val == '/' || val == '\\\\' {\n\t\t\tif idx < len(str)-1 {\n\t\t\t\tif str[idx+1] == '.' {\n\t\t\t\t\trelation = true\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif relation && (val != '/' && val != '\\\\') {\n\t\t\treturn false\n\t\t}\n\t\treturn IsRequestURI(str[idx:])\n\t}\n\treturn false\n}\n\nfunc IsMobilePhone(str string) bool {\n\tif IsEmpty(str) {\n\t\treturn false\n\t}\n\treturn rxMobolePhone.MatchString(str)\n}\n\nfunc IsNull(str string) bool ", "output": "{\n\treturn len(str) == 0\n}"} {"input": "package reaperlog\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/rifflock/lfshook\"\n\t\"go.mozilla.org/mozlogrus\"\n)\n\nvar config LogConfig\n\ntype LogConfig struct {\n\tExtras bool\n}\n\nfunc EnableExtras() {\n\tconfig.Extras = true\n}\n\nfunc EnableMozlog() {\n\tmozlogrus.Enable(\"Reaper\")\n}\n\nfunc Extras() bool {\n\treturn config.Extras\n}\n\nfunc SetConfig(c *LogConfig) {\n\tconfig = *c\n}\n\nfunc AddLogFile(filename string) {\n\tlog.AddHook(lfshook.NewHook(lfshook.PathMap{\n\t\tlog.DebugLevel: filename,\n\t\tlog.InfoLevel: filename,\n\t\tlog.WarnLevel: filename,\n\t\tlog.ErrorLevel: filename,\n\t\tlog.FatalLevel: filename,\n\t\tlog.PanicLevel: filename,\n\t}))\n}\n\nfunc Debug(format string, args ...interface{}) {\n\tlog.Debugf(format, args...)\n}\n\nfunc Info(format string, args ...interface{}) {\n\tlog.Infof(format, args...)\n}\n\nfunc Warning(format string, args ...interface{}) {\n\tlog.Warningf(format, args...)\n}\n\nfunc Fatal(format string, args ...interface{}) {\n\tlog.Fatalf(format, args...)\n}\n\nfunc Panic(format string, args ...interface{}) {\n\tlog.Panicf(format, args...)\n}\n\n\n\nfunc Error(format string, args ...interface{}) ", "output": "{\n\tlog.Errorf(format, args...)\n}"} {"input": "package transport\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestSessions(t *testing.T) ", "output": "{\n\tsession := NewSession()\n\tchOut := session.Add(10)\n\trequire.NotNil(t, chOut)\n\n\tchIn := session.Pick(10)\n\trequire.NotNil(t, chIn)\n\trequire.NotEqual(t, chIn, chOut)\n\n\tmsg := &Message{}\n\n\tchIn <- msg\n\trequire.Equal(t, msg, <-chOut)\n\n\tchIn = session.Pick(10)\n\trequire.Nil(t, chIn)\n}"} {"input": "package configdump\n\nimport (\n\t\"sort\"\n\n\tadminapi \"github.com/envoyproxy/go-control-plane/envoy/admin/v3\"\n\tcluster \"github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3\"\n\n\tv3 \"istio.io/istio/pilot/pkg/xds/v3\"\n)\n\n\nfunc (w *Wrapper) GetDynamicClusterDump(stripVersions bool) (*adminapi.ClustersConfigDump, error) {\n\tclusterDump, err := w.GetClusterConfigDump()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdac := clusterDump.GetDynamicActiveClusters()\n\tfor i := range dac {\n\t\tdac[i].Cluster.TypeUrl = v3.ClusterType\n\t}\n\tsort.Slice(dac, func(i, j int) bool {\n\t\tcluster := &cluster.Cluster{}\n\t\terr = dac[i].Cluster.UnmarshalTo(cluster)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tname := cluster.Name\n\t\terr = dac[j].Cluster.UnmarshalTo(cluster)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn name < cluster.Name\n\t})\n\tif stripVersions {\n\t\tfor i := range dac {\n\t\t\tdac[i].VersionInfo = \"\"\n\t\t\tdac[i].LastUpdated = nil\n\t\t}\n\t}\n\treturn &adminapi.ClustersConfigDump{DynamicActiveClusters: dac}, nil\n}\n\n\n\n\nfunc (w *Wrapper) GetClusterConfigDump() (*adminapi.ClustersConfigDump, error) ", "output": "{\n\tclusterDumpAny, err := w.getSection(clusters)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclusterDump := &adminapi.ClustersConfigDump{}\n\terr = clusterDumpAny.UnmarshalTo(clusterDump)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clusterDump, nil\n}"} {"input": "package settings\n\nimport (\n\t\"sync/atomic\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\n\ntype IntSetting struct {\n\tdefaultValue int64\n\tv int64\n\tvalidateFn func(int64) error\n}\n\nvar _ Setting = &IntSetting{}\n\n\nfunc (i *IntSetting) Get() int64 {\n\treturn atomic.LoadInt64(&i.v)\n}\n\nfunc (i *IntSetting) String() string {\n\treturn EncodeInt(i.Get())\n}\n\n\nfunc (*IntSetting) Typ() string {\n\treturn \"i\"\n}\n\n\nfunc (i *IntSetting) Validate(v int64) error {\n\tif i.validateFn != nil {\n\t\tif err := i.validateFn(v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (i *IntSetting) set(v int64) error {\n\tif err := i.Validate(v); err != nil {\n\t\treturn err\n\t}\n\tatomic.StoreInt64(&i.v, v)\n\treturn nil\n}\n\nfunc (i *IntSetting) setToDefault() {\n\tif err := i.set(i.defaultValue); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\nfunc RegisterIntSetting(key, desc string, defaultValue int64) *IntSetting {\n\treturn RegisterValidatedIntSetting(key, desc, defaultValue, nil)\n}\n\n\n\nfunc RegisterValidatedIntSetting(\n\tkey, desc string, defaultValue int64, validateFn func(int64) error,\n) *IntSetting {\n\tif validateFn != nil {\n\t\tif err := validateFn(defaultValue); err != nil {\n\t\t\tpanic(errors.Wrap(err, \"invalid default\"))\n\t\t}\n\t}\n\tsetting := &IntSetting{\n\t\tdefaultValue: defaultValue,\n\t\tvalidateFn: validateFn,\n\t}\n\tregister(key, desc, setting)\n\treturn setting\n}\n\n\n\n\n\nfunc TestingSetInt(s **IntSetting, v int64) func() ", "output": "{\n\tsaved := *s\n\t*s = &IntSetting{v: v}\n\treturn func() {\n\t\t*s = saved\n\t}\n}"} {"input": "package mdt\n\nimport \"bytes\"\n\ntype rows []row\n\nfunc (r rows) colNum() int {\n\tvar max int\n\tfor _, row := range r {\n\t\tif n := row.colNum(); n > max {\n\t\t\tmax = n\n\t\t}\n\t}\n\treturn max\n}\n\nfunc (r rows) lengthAt(index int) int {\n\tvar max int\n\tfor _, row := range r {\n\t\tif n := row.lengthAt(index); n > max {\n\t\t\tmax = n\n\t\t}\n\t}\n\tif max < 3 {\n\t\tmax = 3\n\t}\n\treturn max\n}\n\n\n\nfunc (r rows) toMarkdown() string ", "output": "{\n\tcolNum := r.colNum()\n\tlens := []int{}\n\tfor i := 0; i < colNum; i++ {\n\t\tlens = append(lens, r.lengthAt(i))\n\t}\n\n\tvar buf bytes.Buffer\n\tfor _, row := range r {\n\t\tbuf.WriteString(row.toMarkdown(colNum, lens) + \"\\n\")\n\t}\n\treturn buf.String()\n}"} {"input": "package size\n\nimport (\n\t\"math\"\n\t\"time\"\n)\n\n\n\nfunc Size(bytesPerSecond int64, dur time.Duration) (numBytes int64) {\n\treturn bytesPerSecond * int64(dur/time.Second)\n}\n\n\n\n\n\n\nfunc Duration(numBytes, bytesPerSecond int64) time.Duration {\n\tr := time.Duration(bytesPerSecond)\n\ts := time.Duration(numBytes)\n\tif s > math.MaxInt64/time.Second {\n\t\treturn s / r * time.Second\n\t}\n\treturn s * time.Second / r\n}\n\nfunc Rate(numBytes int64, dur time.Duration) (bytesPerSecond int64) ", "output": "{\n\treturn numBytes / int64(dur/time.Second)\n}"} {"input": "package exchange\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\ntype ValidPeriod struct {\n\tdate time.Time\n\texpires time.Time\n}\n\n\n\nfunc NewValidPeriod(date, expires time.Time) ValidPeriod {\n\treturn ValidPeriod{date, expires}\n}\n\n\n\n\n\n\nfunc (vp ValidPeriod) Date() time.Time {\n\treturn vp.date\n}\n\n\nfunc (vp ValidPeriod) Expires() time.Time {\n\treturn vp.expires\n}\n\n\nfunc (vp ValidPeriod) Lifetime() time.Duration {\n\treturn vp.expires.Sub(vp.date)\n}\n\n\n\n\nfunc (vp ValidPeriod) Contains(t time.Time) bool {\n\treturn !t.Before(vp.date) && !t.After(vp.expires)\n}\n\n\nfunc (vp ValidPeriod) String() string {\n\treturn fmt.Sprintf(\"[%s] to [%s]\", vp.date, vp.expires)\n}\n\nfunc NewValidPeriodWithLifetime(date time.Time, lifetime time.Duration) ValidPeriod ", "output": "{\n\treturn ValidPeriod{date, date.Add(lifetime)}\n}"} {"input": "package actions\n\n\n\n\nimport (\n\t\"net/http\"\n\n\tmiddleware \"github.com/go-openapi/runtime/middleware\"\n\n\tmodels \"github.com/semi-technologies/weaviate/entities/models\"\n)\n\n\ntype ActionsDeleteHandlerFunc func(ActionsDeleteParams, *models.Principal) middleware.Responder\n\n\n\n\n\ntype ActionsDeleteHandler interface {\n\tHandle(ActionsDeleteParams, *models.Principal) middleware.Responder\n}\n\n\nfunc NewActionsDelete(ctx *middleware.Context, handler ActionsDeleteHandler) *ActionsDelete {\n\treturn &ActionsDelete{Context: ctx, Handler: handler}\n}\n\n\ntype ActionsDelete struct {\n\tContext *middleware.Context\n\tHandler ActionsDeleteHandler\n}\n\nfunc (o *ActionsDelete) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\tr = rCtx\n\t}\n\tvar Params = NewActionsDeleteParams()\n\n\tuprinc, aCtx, err := o.Context.Authorize(r, route)\n\tif err != nil {\n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\tif aCtx != nil {\n\t\tr = aCtx\n\t}\n\tvar principal *models.Principal\n\tif uprinc != nil {\n\t\tprincipal = uprinc.(*models.Principal) \n\t}\n\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params, principal) \n\n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}\n\nfunc (fn ActionsDeleteHandlerFunc) Handle(params ActionsDeleteParams, principal *models.Principal) middleware.Responder ", "output": "{\n\treturn fn(params, principal)\n}"} {"input": "package helpers\n\n\n\nfunc isBlacklisted(resourceData *ResourceData, driver string) bool {\n\tfor _, disallowedDriver := range resourceData.Blacklist {\n\t\tif disallowedDriver == driver {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc getWhitelistedDrivers(resourceData *ResourceData) []string ", "output": "{\n\ttempMap := make(map[string]string)\n\tfor _, driver := range resourceData.Blacklist {\n\t\ttempMap[driver] = \"\"\n\t}\n\twhitelist := []string{}\n\tfor _, driver := range resourceData.Drivers {\n\t\tif _, ok := tempMap[driver]; !ok {\n\t\t\twhitelist = append(whitelist, driver)\n\t\t}\n\t}\n\treturn whitelist\n}"} {"input": "package routes\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\n\tapiservermetrics \"k8s.io/kubernetes/pkg/apiserver/metrics\"\n\t\"k8s.io/kubernetes/pkg/genericapiserver/mux\"\n\tetcdmetrics \"k8s.io/kubernetes/pkg/storage/etcd/metrics\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\n\ntype DefaultMetrics struct{}\n\nfunc (m DefaultMetrics) Install(c *mux.APIContainer) {\n\tc.NonSwaggerRoutes.Handle(\"/metrics\", prometheus.Handler())\n}\n\n\n\ntype MetricsWithReset struct{}\n\n\n\nfunc (m MetricsWithReset) Install(c *mux.APIContainer) ", "output": "{\n\tdefaultMetricsHandler := prometheus.Handler().ServeHTTP\n\tc.NonSwaggerRoutes.HandleFunc(\"/metrics\", func(w http.ResponseWriter, req *http.Request) {\n\t\tif req.Method == \"DELETE\" {\n\t\t\tapiservermetrics.Reset()\n\t\t\tetcdmetrics.Reset()\n\t\t\tio.WriteString(w, \"metrics reset\\n\")\n\t\t\treturn\n\t\t}\n\t\tdefaultMetricsHandler(w, req)\n\t})\n}"} {"input": "package imagick\n\n\nimport \"C\"\nimport (\n\t\"runtime\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\nvar (\n\tinitOnce sync.Once\n\tterminateOnce *sync.Once\n\n\tcanTerminate = make(chan struct{}, 1)\n\n\tenvSemaphore = make(chan struct{}, 1)\n\n\tmagickWandCounter int64\n\tdrawingWandCounter int64\n\tpixelIteratorCounter int64\n\tpixelWandCounter int64\n)\n\n\nfunc Initialize() {\n\tenvSemaphore <- struct{}{}\n\tdefer func() {\n\t\t<-envSemaphore\n\t}()\n\n\tinitOnce.Do(func() {\n\t\tC.MagickWandGenesis()\n\t\tterminateOnce = &sync.Once{}\n\t\tsetCanTerminate()\n\t})\n}\n\n\n\nfunc Terminate() {\n\tenvSemaphore <- struct{}{}\n\tdefer func() {\n\t\t<-envSemaphore\n\t}()\n\n\tif terminateOnce != nil {\n\t\tterminateOnce.Do(func() {\n\t\t\truntime.GC()\n\t\t\tterminate()\n\t\t})\n\t}\n}\n\n\n\nfunc terminate() {\n\t<-canTerminate\n\tC.MagickWandTerminus()\n\tinitOnce = sync.Once{}\n}\n\n\nfunc setCanTerminate() {\n\tif isImageMagickCleaned() {\n\t\tselect {\n\t\tcase canTerminate <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n}\n\n\nfunc unsetCanTerminate() {\n\tselect {\n\tcase <-canTerminate:\n\tdefault:\n\t}\n}\n\n\n\n\nfunc isImageMagickCleaned() bool ", "output": "{\n\tif atomic.LoadInt64(&magickWandCounter) != 0 || atomic.LoadInt64(&drawingWandCounter) != 0 || atomic.LoadInt64(&pixelIteratorCounter) != 0 || atomic.LoadInt64(&pixelWandCounter) != 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}"} {"input": "package tendermint\n\nimport (\n\tlog \"github.com/sirupsen/logrus\"\n\t\"github.com/stratumn/go-core/monitoring\"\n\tabci \"github.com/tendermint/abci/types\"\n\tcfg \"github.com/tendermint/tendermint/config\"\n\t\"github.com/tendermint/tendermint/node\"\n\t\"github.com/tendermint/tendermint/proxy\"\n\t\"github.com/tendermint/tendermint/types\"\n\t\"github.com/tendermint/tmlibs/cli/flags\"\n\ttmlog \"github.com/tendermint/tmlibs/log\"\n)\n\n\nfunc RunNodeForever(config *cfg.Config, app abci.Application) {\n\tnode := NewNode(config, app)\n\terr := node.Start()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tnode.RunForever()\n}\n\n\n\n\nfunc NewNode(config *cfg.Config, app abci.Application) *node.Node ", "output": "{\n\tlogger := tmlog.NewTMLogger(log.StandardLogger().Out)\n\tlogger, _ = flags.ParseLogLevel(config.BaseConfig.LogLevel, logger, \"info\")\n\n\tprivValidator := types.LoadOrGenPrivValidatorFS(config.PrivValidatorFile())\n\tret, err := node.NewNode(config,\n\t\tprivValidator,\n\t\tproxy.NewLocalClientCreator(app),\n\t\tnode.DefaultGenesisDocProviderFunc(config),\n\t\tnode.DefaultDBProvider,\n\t\tlogger)\n\tif err != nil {\n\t\tmonitoring.LogEntry().WithError(err).Error(\"Error on new node creation\")\n\t}\n\n\treturn ret\n}"} {"input": "package drone\n\nimport (\n\t\"fmt\"\n)\n\ntype UserService struct {\n\t*Client\n}\n\n\nfunc (s *UserService) Get(remote, login string) (*User, error) {\n\tvar path = fmt.Sprintf(\"/api/users/%s/%s\", remote, login)\n\tvar user = User{}\n\tvar err = s.run(\"GET\", path, nil, &user)\n\treturn &user, err\n}\n\n\nfunc (s *UserService) GetCurrent() (*User, error) {\n\tvar user = User{}\n\tvar err = s.run(\"GET\", \"/api/user\", nil, &user)\n\treturn &user, err\n}\n\n\nfunc (s *UserService) Create(remote, login string) (*User, error) {\n\tvar path = fmt.Sprintf(\"/api/users/%s/%s\", remote, login)\n\tvar user = User{}\n\tvar err = s.run(\"POST\", path, nil, &user)\n\treturn &user, err\n}\n\n\n\n\n\nfunc (s *UserService) List() ([]*User, error) {\n\tvar users []*User\n\tvar err = s.run(\"GET\", \"/api/users\", nil, &users)\n\treturn users, err\n}\n\nfunc (s *UserService) Delete(remote, login string) error ", "output": "{\n\tvar path = fmt.Sprintf(\"/api/users/%s/%s\", remote, login)\n\treturn s.run(\"DELETE\", path, nil, nil)\n}"} {"input": "package sched\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"bosun.org/cmd/bosun/cache\"\n\t\"bosun.org/cmd/bosun/conf\"\n\t\"bosun.org/slog\"\n)\n\n\n\n\nfunc (s *Schedule) updateCheckContext() {\n\tfor {\n\t\tctx := &checkContext{utcNow(), cache.New(0)}\n\t\ts.ctx = ctx\n\t\ttime.Sleep(s.SystemConf.GetCheckFrequency())\n\t\ts.Lock(\"CollectStates\")\n\t\ts.CollectStates()\n\t\ts.Unlock()\n\t}\n}\n\nfunc (s *Schedule) RunAlert(a *conf.Alert) {\n\ts.checksRunning.Add(1)\n\tdefer s.checksRunning.Done()\n\tfor {\n\t\trunEvery := s.SystemConf.GetDefaultRunEvery()\n\t\tif a.RunEvery != 0 {\n\t\t\trunEvery = a.RunEvery\n\t\t}\n\t\twait := time.After(s.SystemConf.GetCheckFrequency() * time.Duration(runEvery))\n\t\ts.checkAlert(a)\n\t\ts.LastCheck = utcNow()\n\t\tselect {\n\t\tcase <-wait:\n\t\tcase <-s.runnerContext.Done():\n\t\t\tslog.Infof(\"Stopping alert routine for %v\\n\", a.Name)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (s *Schedule) checkAlert(a *conf.Alert) {\n\tcheckTime := s.ctx.runTime\n\tcheckCache := s.ctx.checkCache\n\trh := s.NewRunHistory(checkTime, checkCache)\n\tcancelled := s.CheckAlert(nil, rh, a)\n\tif cancelled {\n\t\treturn\n\t}\n\tstart := utcNow()\n\ts.RunHistory(rh)\n\tslog.Infof(\"runHistory on %s took %v\\n\", a.Name, time.Since(start))\n}\n\nfunc (s *Schedule) Run() error ", "output": "{\n\tif s.RuleConf == nil || s.SystemConf == nil {\n\t\treturn fmt.Errorf(\"sched: nil configuration\")\n\t}\n\ts.nc = make(chan interface{}, 1)\n\tif s.SystemConf.GetPing() {\n\t\tgo s.PingHosts()\n\t}\n\tgo s.dispatchNotifications()\n\tgo s.updateCheckContext()\n\tfor _, a := range s.RuleConf.GetAlerts() {\n\t\tgo s.RunAlert(a)\n\t}\n\treturn nil\n}"} {"input": "package vml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/urn/schemas_microsoft_com/vml\"\n)\n\nfunc TestRoundrectConstructor(t *testing.T) {\n\tv := vml.NewRoundrect()\n\tif v == nil {\n\t\tt.Errorf(\"vml.NewRoundrect must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed vml.Roundrect should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestRoundrectMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := vml.NewRoundrect()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := vml.NewRoundrect()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package config\n\nimport (\n\t\"testing\"\n)\n\nfunc TestRebootWindowStart(t *testing.T) {\n\ttests := []struct {\n\t\tvalue string\n\n\t\tisValid bool\n\t}{\n\t\t{value: \"Sun 0:0\", isValid: true},\n\t\t{value: \"Sun 00:00\", isValid: true},\n\t\t{value: \"sUn 23:59\", isValid: true},\n\t\t{value: \"mon 0:0\", isValid: true},\n\t\t{value: \"tue 0:0\", isValid: true},\n\t\t{value: \"tues 0:0\", isValid: false},\n\t\t{value: \"wed 0:0\", isValid: true},\n\t\t{value: \"thu 0:0\", isValid: true},\n\t\t{value: \"thur 0:0\", isValid: false},\n\t\t{value: \"fri 0:0\", isValid: true},\n\t\t{value: \"sat 0:0\", isValid: true},\n\t\t{value: \"sat00:00\", isValid: false},\n\t\t{value: \"00:00\", isValid: true},\n\t\t{value: \"10:10\", isValid: true},\n\t\t{value: \"20:20\", isValid: true},\n\t\t{value: \"20:30\", isValid: true},\n\t\t{value: \"20:40\", isValid: true},\n\t\t{value: \"20:50\", isValid: true},\n\t\t{value: \"20:60\", isValid: false},\n\t\t{value: \"24:00\", isValid: false},\n\t}\n\n\tfor _, tt := range tests {\n\t\tisValid := (nil == AssertStructValid(Locksmith{RebootWindowStart: tt.value}))\n\t\tif tt.isValid != isValid {\n\t\t\tt.Errorf(\"bad assert (%s): want %t, got %t\", tt.value, tt.isValid, isValid)\n\t\t}\n\t}\n}\n\n\n\nfunc TestRebootWindowLength(t *testing.T) ", "output": "{\n\ttests := []struct {\n\t\tvalue string\n\n\t\tisValid bool\n\t}{\n\t\t{value: \"1h\", isValid: true},\n\t\t{value: \"1d\", isValid: true},\n\t\t{value: \"0d\", isValid: true},\n\t\t{value: \"0.5h\", isValid: true},\n\t\t{value: \"0.5.0h\", isValid: false},\n\t}\n\n\tfor _, tt := range tests {\n\t\tisValid := (nil == AssertStructValid(Locksmith{RebootWindowLength: tt.value}))\n\t\tif tt.isValid != isValid {\n\t\t\tt.Errorf(\"bad assert (%s): want %t, got %t\", tt.value, tt.isValid, isValid)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\n\nvar NodeCmd = &cobra.Command{\n\tUse: \"node\",\n\tShort: \"Node operations\",\n\tLong: `Manage node-related operations.`,\n\tPersistentPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn nil\n\t},\n}\n\n\n\nfunc init() ", "output": "{\n\tRootCmd.AddCommand(NodeCmd)\n}"} {"input": "package types\n\nimport \"testing\"\n\n\n\nfunc TestJSONText(t *testing.T) {\n\tj := JSONText(`{\"foo\": 1, \"bar\": 2}`)\n\tv, err := j.Value()\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\terr = (&j).Scan(v)\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\tm := map[string]interface{}{}\n\tj.Unmarshal(&m)\n\n\tif m[\"foo\"].(float64) != 1 || m[\"bar\"].(float64) != 2 {\n\t\tt.Errorf(\"Expected valid json but got some garbage instead? %#v\", m)\n\t}\n\n\tj = JSONText(`{\"foo\": 1, invalid, false}`)\n\tv, err = j.Value()\n\tif err == nil {\n\t\tt.Errorf(\"Was expecting invalid json to fail!\")\n\t}\n}\n\nfunc TestBitBool(t *testing.T) {\n\tvar b BitBool = true\n\n\tv, err := b.Value()\n\tif err != nil {\n\t\tt.Errorf(\"Cannot return error\")\n\t}\n\terr = (&b).Scan(v)\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\tif !b {\n\t\tt.Errorf(\"Was expecting the bool we sent in (true), got %b\", b)\n\t}\n\n\tb = false\n\n\tv, err = b.Value()\n\tif err != nil {\n\t\tt.Errorf(\"Cannot return error\")\n\t}\n\terr = (&b).Scan(v)\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\tif b {\n\t\tt.Errorf(\"Was expecting the bool we sent in (false), got %b\", b)\n\t}\n}\n\nfunc TestGzipText(t *testing.T) ", "output": "{\n\tg := GzippedText(\"Hello, world\")\n\tv, err := g.Value()\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\terr = (&g).Scan(v)\n\tif err != nil {\n\t\tt.Errorf(\"Was not expecting an error\")\n\t}\n\tif string(g) != \"Hello, world\" {\n\t\tt.Errorf(\"Was expecting the string we sent in (Hello World), got %s\", string(g))\n\t}\n}"} {"input": "package sysfs\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n)\n\nfunc TestGetRaplZones(t *testing.T) {\n\tfs, err := NewFS(sysTestFixtures)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tzones, err := GetRaplZones(fs)\n\tif err != nil || zones == nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\n\nfunc TestNewRaplValues(t *testing.T) {\n\tfs, err := NewFS(sysTestFixtures)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tzones, err := GetRaplZones(fs)\n\tif err != nil || zones == nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif len(zones) != 3 {\n\t\tt.Fatal(\"wrong number of RAPL values\")\n\t}\n\tmicrojoules, err := zones[0].GetEnergyMicrojoules()\n\tif err != nil {\n\t\tt.Fatal(\"couldn't read microjoules\")\n\t}\n\tif microjoules != 240422366267 {\n\t\tt.Fatal(\"wrong microjoule number\")\n\t}\n\tif zones[2].Index != 10 {\n\t\tt.Fatal(\"wrong index number\")\n\t}\n}\n\nfunc TestNoRaplFiles(t *testing.T) ", "output": "{\n\tfs, err := NewFS(filepath.Join(sysTestFixtures, \"class\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tzones, err := GetRaplZones(fs)\n\tif err == nil || zones != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package helpers\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"runtime\"\n)\n\n\n\nfunc BytesToUint16(field [2]byte) uint16 {\n\treturn uint16(field[0])<<8 | uint16(field[1])\n}\n\n\n\nfunc Uint16ToBytes(value uint16) [2]byte {\n\tbyte0 := byte(value >> 8)\n\tbyte1 := byte(0x00ff & value) \n\treturn [2]byte{byte0, byte1}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc GetByte(b *bytes.Buffer) byte {\n\tbyte, err := b.ReadByte()\n\tif err != nil {\n\t\tpanic(errors.New(\"Unexpected end of data\"))\n\t}\n\treturn byte\n}\n\n\n\n\nfunc HandleErrorPanic(err *error, functionName string) {\n\tif r := recover(); r != nil {\n\t\tif _, ok := r.(runtime.Error); ok {\n\t\t\tpanic(r)\n\t\t}\n\t\tperr := r.(error)\n\t\t*err = errors.New(functionName + \": \" + perr.Error())\n\t}\n}\n\nfunc GetBytes(b *bytes.Buffer, n int) []byte ", "output": "{\n\tslice := make([]byte, n)\n\tnread, err := b.Read(slice)\n\tif err != nil || nread != n {\n\t\tpanic(errors.New(\"Unexpected end of data.\"))\n\t}\n\treturn slice\n}"} {"input": "package servo_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n\t\"github.com/fgrosse/servo\"\n\t\"fmt\"\n)\n\nfunc TestServo(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Servo Test Suite\")\n}\n\ntype TestBundle struct {}\n\nfunc (b *TestBundle) Boot(kernel *servo.Kernel) {\n\tkernel.RegisterType(\"test_bundle.my_type\", NewService)\n}\n\ntype SomeService struct {}\n\nfunc NewRecursiveService(*SomeService) *SomeService {\n\treturn &SomeService{}\n}\n\nfunc NewService() *SomeService {\n\treturn &SomeService{}\n}\n\nfunc NewServiceWithParam(param interface{}) *SomeService {\n\tpanic(param)\n\treturn &SomeService{}\n}\n\n\ntype ServerMock struct {\n\tRunHasBeenCalled bool\n\tReturnError bool\n\n\tParameter1, Parameter2 string\n}\n\n\n\nfunc (s *ServerMock) Run() error {\n\ts.RunHasBeenCalled = true\n\tif s.ReturnError {\n\t\treturn fmt.Errorf(\"ServerMock was told to return an error!\")\n\t}\n\n\treturn nil\n}\n\nfunc NewServerMockWithParams(param1, param2 string) *ServerMock ", "output": "{\n\tExpect(param1).To(Equal(\"foo\"), `NewServerMockWithParams should always be called with the values \"foo\" and \"bar\"`)\n\tExpect(param2).To(Equal(\"bar\"), `NewServerMockWithParams should always be called with the values \"foo\" and \"bar\"`)\n\n\treturn &ServerMock{\n\t\tParameter1: param1,\n\t\tParameter2: param2,\n\t}\n}"} {"input": "package unix\n\nimport \"unsafe\"\n\n\n\nvar fcntl64Syscall uintptr = SYS_FCNTL\n\nfunc fcntl(fd int, cmd, arg int) (int, error) {\n\tvalptr, _, errno := Syscall(fcntl64Syscall, uintptr(fd), uintptr(cmd), uintptr(arg))\n\tvar err error\n\tif errno != 0 {\n\t\terr = errno\n\t}\n\treturn int(valptr), err\n}\n\n\nfunc FcntlInt(fd uintptr, cmd, arg int) (int, error) {\n\treturn fcntl(int(fd), cmd, arg)\n}\n\n\n\n\nfunc FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error ", "output": "{\n\t_, _, errno := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(unsafe.Pointer(lk)))\n\tif errno == 0 {\n\t\treturn nil\n\t}\n\treturn errno\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/astaxie/beego\"\n\t\"github.com/RayFantasyStudio/blog/models\"\n\t\"fmt\"\n)\n\nvar owner string\n\n\n\nfunc initHeaderFooterData(c *beego.Controller, title string) (user *models.User, err error) {\n\tc.Data[\"Owner\"] = owner\n\n\tc.Data[\"Title\"] = title\n\n\tif token := c.Ctx.GetCookie(\"token\"); len(token) != 0 {\n\t\tif user, err = models.GetUserByToken(token); err != nil {\n\t\t\tbeego.Error(err)\n\t\t} else {\n\t\t\tc.Data[\"IsLogin\"] = true\n\t\t\tc.Data[\"User\"] = user\n\t\t\tvar avatar_path string\n\t\t\tavatar_path, err = models.GetUserAvatar(int64(user.Id))\n\t\t\tc.Data[\"avatar_path\"] = avatar_path\n\t\t\tbeego.Info(avatar_path)\n\t\t}\n\t}\n\n\tflash := beego.ReadFromRequest(c)\n\tif n, ok := flash.Data[\"notice\"]; ok {\n\t\tc.Data[\"Message\"] = n\n\t}\n\treturn\n}\n\nfunc NewNoticeFlash(c *beego.Controller, msg string, args ...interface{}) {\n\tvar data string\n\tif len(args) == 0 {\n\t\tdata = msg\n\t} else {\n\t\tdata = fmt.Sprintf(msg, args...)\n\t}\n\tflash := beego.NewFlash()\n\tflash.Notice(data)\n\tflash.Store(c)\n}\n\nfunc init() ", "output": "{\n\towner = beego.AppConfig.String(\"owner\")\n}"} {"input": "package modules\n\nimport (\n\t\"testing\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestIsInfoUrl(t *testing.T) {\n\tassert.Equal(t, IsInfoUrl(\"/admin/info/user?id=asfas\"), true)\n}\n\nfunc TestInArray(t *testing.T) ", "output": "{\n\tassert.Equal(t, InArray([]string{\"2\"}, \"2\"), true)\n}"} {"input": "package state\n\nimport (\n\t\"sync\"\n)\n\n\n\n\n\ntype NotifyGroup struct {\n\tl sync.Mutex\n\tnotify map[chan struct{}]struct{}\n}\n\n\n\nfunc (n *NotifyGroup) Notify() {\n\tn.l.Lock()\n\tdefer n.l.Unlock()\n\tfor ch, _ := range n.notify {\n\t\tselect {\n\t\tcase ch <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n\tn.notify = nil\n}\n\n\n\n\n\nfunc (n *NotifyGroup) Clear(ch chan struct{}) {\n\tn.l.Lock()\n\tdefer n.l.Unlock()\n\tif n.notify == nil {\n\t\treturn\n\t}\n\tdelete(n.notify, ch)\n}\n\n\nfunc (n *NotifyGroup) WaitCh() chan struct{} {\n\tch := make(chan struct{}, 1)\n\tn.Wait(ch)\n\treturn ch\n}\n\n\nfunc (n *NotifyGroup) Empty() bool {\n\tn.l.Lock()\n\tdefer n.l.Unlock()\n\treturn len(n.notify) == 0\n}\n\nfunc (n *NotifyGroup) Wait(ch chan struct{}) ", "output": "{\n\tn.l.Lock()\n\tdefer n.l.Unlock()\n\tif n.notify == nil {\n\t\tn.notify = make(map[chan struct{}]struct{})\n\t}\n\tn.notify[ch] = struct{}{}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\n\t\"google.golang.org/grpc\"\n\n\t_ \"github.com/joho/godotenv/autoload\"\n\t\"github.com/marc-gr/fry/pb\"\n)\n\nconst (\n\tfryPortEnv = \"FRY_PORT\"\n)\n\nfunc main() {\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\":%s\", getPort()))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\tgrpcServer := grpc.NewServer()\n\tpb.RegisterFryServer(grpcServer, &Fry{})\n\n\tlog.Fatal(grpcServer.Serve(lis))\n}\n\n\n\nfunc getPort() string ", "output": "{\n\treturn os.Getenv(fryPortEnv)\n}"} {"input": "package credentials\n\ntype BearerTokenCredential struct {\n\tBearerToken string\n}\n\n\n\n\nfunc NewBearerTokenCredential(token string) *BearerTokenCredential ", "output": "{\n\treturn &BearerTokenCredential{\n\t\tBearerToken: token,\n\t}\n}"} {"input": "package websocket\n\nimport(\n \"net/http\"\n \"log\"\n \"github.com/gorilla/websocket\"\n wss \"github.com/ipastushenko/simple-chat/server/services/websocket\"\n \"github.com/ipastushenko/simple-chat/server/services/token\"\n)\n\nvar upgrader = websocket.Upgrader{\n CheckOrigin: func(r *http.Request) bool {\n return true\n },\n}\n\ntype WebSocketHandler struct {\n webSocketService wss.IWebSocketService\n tokenService token.ITokenService\n}\n\nfunc NewWebSocketHandler() *WebSocketHandler {\n return &WebSocketHandler{\n webSocketService: wss.NewWebSocketService(),\n tokenService: token.NewJWTService(),\n }\n}\n\n\n\nfunc (handler *WebSocketHandler) ServeHTTP(\n responseWriter http.ResponseWriter,\n request *http.Request,\n) ", "output": "{\n connection, err := upgrader.Upgrade(responseWriter, request, nil)\n if err != nil {\n log.Println(err.Error())\n responseWriter.WriteHeader(http.StatusInternalServerError)\n return\n }\n info := handler.tokenService.GetRequestContextInfo(request)\n handler.webSocketService.InitConnection(connection, info)\n}"} {"input": "package builders\n\nimport (\n\t\"time\"\n\n\t\"github.com/docker/docker/api/types\"\n)\n\n\n\nfunc Container(name string, builders ...func(container *types.Container)) *types.Container {\n\tcontainer := &types.Container{\n\t\tID: \"container_id\",\n\t\tNames: []string{\"/\" + name},\n\t\tCommand: \"top\",\n\t\tImage: \"busybox:latest\",\n\t\tStatus: \"Up 1 second\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tfor _, builder := range builders {\n\t\tbuilder(container)\n\t}\n\n\treturn container\n}\n\n\nfunc WithLabel(key, value string) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tif c.Labels == nil {\n\t\t\tc.Labels = map[string]string{}\n\t\t}\n\t\tc.Labels[key] = value\n\t}\n}\n\n\nfunc WithName(name string) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tc.Names = append(c.Names, \"/\"+name)\n\t}\n}\n\n\n\n\n\nfunc IP(ip string) func(*types.Port) {\n\treturn func(p *types.Port) {\n\t\tp.IP = ip\n\t}\n}\n\n\nfunc TCP(p *types.Port) {\n\tp.Type = \"tcp\"\n}\n\n\nfunc UDP(p *types.Port) {\n\tp.Type = \"udp\"\n}\n\nfunc WithPort(privateport, publicport uint16, builders ...func(*types.Port)) func(*types.Container) ", "output": "{\n\treturn func(c *types.Container) {\n\t\tif c.Ports == nil {\n\t\t\tc.Ports = []types.Port{}\n\t\t}\n\t\tport := &types.Port{\n\t\t\tPrivatePort: privateport,\n\t\t\tPublicPort: publicport,\n\t\t}\n\t\tfor _, builder := range builders {\n\t\t\tbuilder(port)\n\t\t}\n\t\tc.Ports = append(c.Ports, *port)\n\t}\n}"} {"input": "package parser\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n)\n\nfunc normalizePath(path string) string {\n\treturn strings.Replace(path, \"\\\\\", \"/\", -1)\n}\n\n\n\nfunc getPkgPath(fname string, isDir bool) (string, error) ", "output": "{\n\tif !path.IsAbs(fname) {\n\t\tpwd, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tfname = path.Join(pwd, fname)\n\t}\n\n\tfname = normalizePath(fname)\n\n\tfor _, p := range strings.Split(os.Getenv(\"GOPATH\"), \";\") {\n\t\tprefix := path.Join(normalizePath(p), \"src\") + \"/\"\n\t\tif rel := strings.TrimPrefix(fname, prefix); rel != fname {\n\t\t\tif !isDir {\n\t\t\t\treturn path.Dir(rel), nil\n\t\t\t} else {\n\t\t\t\treturn path.Clean(rel), nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"file '%v' is not in GOPATH\", fname)\n}"} {"input": "package url\n\nimport (\n\t\"github.com/dpb587/metalink\"\n\t\"github.com/dpb587/metalink/file\"\n)\n\ntype MultiLoader struct {\n\tloaders []Loader\n}\n\nvar _ Loader = &MultiLoader{}\n\nfunc NewMultiLoader(loaders ...Loader) *MultiLoader {\n\treturn &MultiLoader{\n\t\tloaders: loaders,\n\t}\n}\n\nfunc (l *MultiLoader) SupportsURL(source metalink.URL) bool {\n\tfor _, loader := range l.loaders {\n\t\tif loader.SupportsURL(source) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\n\nfunc (l *MultiLoader) Add(add Loader) {\n\tl.loaders = append(l.loaders, add)\n}\n\nfunc (l *MultiLoader) LoadURL(source metalink.URL) (file.Reference, error) ", "output": "{\n\tfor _, loader := range l.loaders {\n\t\tif !loader.SupportsURL(source) {\n\t\t\tcontinue\n\t\t}\n\n\t\tref, err := loader.LoadURL(source)\n\t\tif err == UnsupportedURLError {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn ref, err\n\t}\n\n\treturn nil, UnsupportedURLError\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"github.com/keybase/cli\"\n\t\"github.com/keybase/client/go/libcmdline\"\n\t\"github.com/keybase/client/go/libkb\"\n\tkeybase1 \"github.com/keybase/client/go/protocol/keybase1\"\n\t\"github.com/keybase/go-framed-msgpack-rpc/rpc\"\n\t\"golang.org/x/net/context\"\n)\n\ntype CmdFakeTrackingChanged struct {\n\tlibkb.Contextified\n\targ keybase1.FakeTrackingChangedArg\n}\n\nfunc (c *CmdFakeTrackingChanged) ParseArgv(ctx *cli.Context) error {\n\tif len(ctx.Args()) != 1 {\n\t\treturn fmt.Errorf(\"Must provide exactly one username.\")\n\t}\n\tc.arg.Username = ctx.Args()[0]\n\treturn nil\n}\n\nfunc (c *CmdFakeTrackingChanged) Run() (err error) {\n\tcli, err := GetTrackClient(c.G())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprotocols := []rpc.Protocol{}\n\tif err = RegisterProtocolsWithContext(protocols, c.G()); err != nil {\n\t\treturn err\n\t}\n\n\terr = cli.FakeTrackingChanged(context.TODO(), c.arg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc NewCmdFakeTrackingChangedRunner(g *libkb.GlobalContext) *CmdFakeTrackingChanged {\n\treturn &CmdFakeTrackingChanged{Contextified: libkb.NewContextified(g)}\n}\n\nfunc (c *CmdFakeTrackingChanged) GetUsage() libkb.Usage {\n\treturn libkb.Usage{\n\t\tConfig: true,\n\t\tAPI: true,\n\t}\n}\n\nfunc NewCmdFakeTrackingChanged(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command ", "output": "{\n\treturn cli.Command{\n\t\tName: \"fake-following-changed\",\n\t\tFlags: []cli.Flag{},\n\t\tAction: func(c *cli.Context) {\n\t\t\tcl.ChooseCommand(NewCmdFakeTrackingChangedRunner(g), \"fake-following-changed\", c)\n\t\t},\n\t}\n}"} {"input": "package socket\n\nimport \"sync\"\n\n\ntype PacketHandler interface {\n\tOnPacket(Packet)\n}\n\n\n\n\ntype EventHandler interface {\n\tOn(event string, fn interface{}) error\n}\n\n\ntype Handler interface {\n\tEventHandler\n\tPacketHandler\n}\n\ntype handler struct {\n\tmu sync.RWMutex\n\tevents map[string]PacketHandler\n}\n\nfunc newHandler() Handler {\n\treturn &handler{\n\t\tevents: make(map[string]PacketHandler),\n\t}\n}\n\nfunc (h *handler) On(event string, fn interface{}) (err error) {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.events[event], err = newPacketHandler(fn)\n\treturn err\n}\n\n\n\nfunc (h *handler) OnPacket(p Packet) ", "output": "{\n\th.mu.RLock()\n\tc, ok := h.events[p.Event()]\n\th.mu.RUnlock()\n\n\tif ok {\n\t\tc.OnPacket(p)\n\t}\n}"} {"input": "package flatmap\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\n\n\nfunc expandArray(m map[string]string, prefix string) []interface{} {\n\tnum, err := strconv.ParseInt(m[prefix+\".#\"], 0, 0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tresult := make([]interface{}, num)\n\tfor i := 0; i < int(num); i++ {\n\t\tresult[i] = Expand(m, fmt.Sprintf(\"%s.%d\", prefix, i))\n\t}\n\n\treturn result\n}\n\nfunc expandMap(m map[string]string, prefix string) map[string]interface{} {\n\tresult := make(map[string]interface{})\n\tfor k, _ := range m {\n\t\tif !strings.HasPrefix(k, prefix) {\n\t\t\tcontinue\n\t\t}\n\n\t\tkey := k[len(prefix):]\n\t\tidx := strings.Index(key, \".\")\n\t\tif idx != -1 {\n\t\t\tkey = key[:idx]\n\t\t}\n\t\tif _, ok := result[key]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tresult[key] = Expand(m, k[:len(prefix)+len(key)])\n\t}\n\n\treturn result\n}\n\nfunc Expand(m map[string]string, key string) interface{} ", "output": "{\n\tif v, ok := m[key]; ok {\n\t\tif v == \"true\" {\n\t\t\treturn true\n\t\t} else if v == \"false\" {\n\t\t\treturn false\n\t\t}\n\n\t\treturn v\n\t}\n\n\tif _, ok := m[key+\".#\"]; ok {\n\t\treturn expandArray(m, key)\n\t}\n\n\tprefix := key + \".\"\n\tfor k, _ := range m {\n\t\tif strings.HasPrefix(k, prefix) {\n\t\t\treturn expandMap(m, prefix)\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package hijackhelpers\n\nimport (\n\t\"strings\"\n\n\t\"github.com/concourse/atc\"\n)\n\ntype ContainerSorter []atc.Container\n\nfunc (sorter ContainerSorter) Len() int {\n\treturn len(sorter)\n}\n\nfunc (sorter ContainerSorter) Swap(i, j int) {\n\tsorter[i], sorter[j] = sorter[j], sorter[i]\n}\n\n\n\nfunc (sorter ContainerSorter) Less(i, j int) bool ", "output": "{\n\tswitch {\n\tcase sorter[i].BuildID < sorter[j].BuildID:\n\t\treturn true\n\tcase sorter[i].BuildID > sorter[j].BuildID:\n\t\treturn false\n\tcase strings.Compare(sorter[i].ResourceName, sorter[j].ResourceName) == -1:\n\t\treturn true\n\tcase strings.Compare(sorter[i].ResourceName, sorter[j].ResourceName) == 1:\n\t\treturn false\n\tcase strings.Compare(sorter[i].StepName, sorter[j].StepName) == -1:\n\t\treturn true\n\tcase strings.Compare(sorter[i].StepName, sorter[j].StepName) == 1:\n\t\treturn false\n\tcase strings.Compare(sorter[i].Type, sorter[j].Type) == -1:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}"} {"input": "package layer\n\nimport \"io\"\n\ntype mountedLayer struct {\n\tname string\n\tmountID string\n\tinitID string\n\tparent *roLayer\n\tpath string\n\tlayerStore *layerStore\n\tactivityCount int\n}\n\nfunc (ml *mountedLayer) cacheParent() string {\n\tif ml.initID != \"\" {\n\t\treturn ml.initID\n\t}\n\tif ml.parent != nil {\n\t\treturn ml.parent.cacheID\n\t}\n\treturn \"\"\n}\n\nfunc (ml *mountedLayer) TarStream() (io.ReadCloser, error) {\n\tarchiver, err := ml.layerStore.driver.Diff(ml.mountID, ml.cacheParent())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn archiver, nil\n}\n\nfunc (ml *mountedLayer) Path() (string, error) {\n\tif ml.path == \"\" {\n\t\treturn \"\", ErrNotMounted\n\t}\n\treturn ml.path, nil\n}\n\nfunc (ml *mountedLayer) Parent() Layer {\n\tif ml.parent != nil {\n\t\treturn ml.parent\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (ml *mountedLayer) Size() (int64, error) ", "output": "{\n\treturn ml.layerStore.driver.DiffSize(ml.mountID, ml.cacheParent())\n}"} {"input": "package ui\n\nimport (\n\t\"github.com/studentkittens/eulenfunk/display\"\n)\n\n\n\n\ntype Menu struct {\n\tName string\n\n\tEntries []Entry\n\n\tCursor int\n\n\tlw *display.LineWriter\n}\n\n\n\nfunc NewMenu(name string, lw *display.LineWriter) (*Menu, error) {\n\treturn &Menu{\n\t\tName: name,\n\t\tlw: lw,\n\t}, nil\n}\n\nfunc (mn *Menu) scrollToNextSelectable(up bool) {\n\tfor mn.Cursor >= 0 && mn.Cursor < len(mn.Entries) && !mn.Entries[mn.Cursor].Selectable() {\n\t\tif up {\n\t\t\tmn.Cursor++\n\t\t} else {\n\t\t\tmn.Cursor--\n\t\t}\n\t}\n\n\tif mn.Cursor < 0 {\n\t\tmn.Cursor = 0\n\t}\n\n\tif mn.Cursor >= len(mn.Entries) {\n\t\tmn.Cursor = len(mn.Entries) - 1\n\t}\n}\n\n\n\n\n\nfunc (mn *Menu) Display(width int) error {\n\tfor pos, ClickEntry := range mn.Entries {\n\t\tline := ClickEntry.Render(width, pos == mn.Cursor)\n\t\tif err := mn.lw.Line(mn.Name, pos, line); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\nfunc (mn *Menu) Click() error {\n\tif len(mn.Entries) == 0 {\n\t\treturn nil\n\t}\n\n\treturn mn.Entries[mn.Cursor].Action()\n}\n\nfunc (mn *Menu) Scroll(move int) ", "output": "{\n\tmn.Cursor += move\n\n\tup := move >= 0\n\tmn.scrollToNextSelectable(up)\n\n\tif !mn.Entries[mn.Cursor].Selectable() {\n\t\tmn.scrollToNextSelectable(!up)\n\t}\n}"} {"input": "package gin\n\nimport (\n\t\"github.com/gin-gonic/gin/binding\"\n\t\"log\"\n)\n\n\n\n\n\nfunc (c *Context) BindWith(obj interface{}, b binding.Binding) error {\n\tlog.Println(`BindWith(\\\"interface{}, binding.Binding\\\") error is going to\n\tbe deprecated, please check issue #662 and either use MustBindWith() if you\n\twant HTTP 400 to be automatically returned if any error occur, of use\n\tShouldBindWith() if you need to manage the error.`)\n\treturn c.MustBindWith(obj, b)\n}\n\nfunc (c *Context) GetCookie(name string) (string, error) ", "output": "{\n\tlog.Println(\"GetCookie() method is deprecated. Use Cookie() instead.\")\n\treturn c.Cookie(name)\n}"} {"input": "package acme\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestWaitForTimeout(t *testing.T) ", "output": "{\n\tc := make(chan error)\n\tgo func() {\n\t\terr := WaitFor(3*time.Second, 1*time.Second, func() (bool, error) {\n\t\t\treturn false, nil\n\t\t})\n\t\tc <- err\n\t}()\n\n\ttimeout := time.After(4 * time.Second)\n\tselect {\n\tcase <-timeout:\n\t\tt.Fatal(\"timeout exceeded\")\n\tcase err := <-c:\n\t\tif err == nil {\n\t\t\tt.Errorf(\"expected timeout error; got %v\", err)\n\t\t}\n\t}\n}"} {"input": "package vfsclientset\n\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/kops/pkg/apis/kops\"\n\n\t_ \"k8s.io/kops/pkg/apis/kops/install\"\n)\n\n\n\nfunc init() ", "output": "{\n\tif missingVersions := kops.Registry.ValidateEnvRequestedVersions(); len(missingVersions) != 0 {\n\t\tpanic(fmt.Sprintf(\"KUBE_API_VERSIONS contains versions that are not installed: %q.\", missingVersions))\n\t}\n}"} {"input": "package format\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/types\"\n)\n\ntype podHandler func(*v1.Pod) string\n\n\n\nfunc Pod(pod *v1.Pod) string {\n\treturn PodDesc(pod.Name, pod.Namespace, pod.UID)\n}\n\n\n\nfunc PodDesc(podName, podNamespace string, podUID types.UID) string {\n\treturn fmt.Sprintf(\"%s_%s(%s)\", podName, podNamespace, podUID)\n}\n\n\n\nfunc PodWithDeletionTimestamp(pod *v1.Pod) string {\n\tvar deletionTimestamp string\n\tif pod.DeletionTimestamp != nil {\n\t\tdeletionTimestamp = \":DeletionTimestamp=\" + pod.DeletionTimestamp.UTC().Format(time.RFC3339)\n\t}\n\treturn Pod(pod) + deletionTimestamp\n}\n\n\n\n\n\n\n\nfunc PodsWithDeletiontimestamps(pods []*v1.Pod) string {\n\treturn aggregatePods(pods, PodWithDeletionTimestamp)\n}\n\nfunc aggregatePods(pods []*v1.Pod, handler podHandler) string {\n\tpodStrings := make([]string, 0, len(pods))\n\tfor _, pod := range pods {\n\t\tpodStrings = append(podStrings, handler(pod))\n\t}\n\treturn fmt.Sprintf(strings.Join(podStrings, \", \"))\n}\n\nfunc Pods(pods []*v1.Pod) string ", "output": "{\n\treturn aggregatePods(pods, Pod)\n}"} {"input": "package http\n\nimport (\n\t\"go-common/app/admin/main/tv/model\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\nfunc mangoList(c *bm.Context) {\n\tc.JSON(tvSrv.MangoList(c))\n}\n\nfunc mangoAdd(c *bm.Context) {\n\tparam := new(struct {\n\t\tIDs []int64 `form:\"rids,split\" validate:\"required,min=1,dive,gt=0\"`\n\t\tRType int `form:\"rtype\" validate:\"required,min=1,max=2\"` \n\t})\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(tvSrv.MangoAdd(c, param.RType, param.IDs))\n}\n\nfunc mangoEdit(c *bm.Context) {\n\tparam := new(model.ReqMangoEdit)\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(nil, tvSrv.MangoEdit(c, param))\n}\n\nfunc mangoDel(c *bm.Context) {\n\tparam := new(struct {\n\t\tID int64 `form:\"id\" validate:\"required,min=1,gt=0\"`\n\t})\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(nil, tvSrv.MangoDel(c, param.ID))\n}\n\n\n\nfunc mangoPub(c *bm.Context) ", "output": "{\n\tparam := new(struct {\n\t\tIDs []int64 `form:\"ids,split\" validate:\"required,min=1,dive,gt=0\"`\n\t})\n\tif err := c.Bind(param); err != nil {\n\t\treturn\n\t}\n\tc.JSON(nil, tvSrv.MangoPub(c, param.IDs))\n}"} {"input": "package main\n\nimport \"fmt\"\n\nconst (\n\ta = iota\n\tb\n\tc\n\td\n\te\n)\n\nvar x = []int{1, 2, 3}\n\nfunc f(x int, len *byte) {\n\t*len = byte(x)\n}\n\nfunc whatis(x interface{}) string {\n\tswitch xx := x.(type) {\n\tdefault:\n\t\treturn fmt.Sprint(\"default \", xx)\n\tcase int, int8, int16, int32:\n\t\treturn fmt.Sprint(\"signed \", xx)\n\tcase int64:\n\t\treturn fmt.Sprint(\"signed64 \", int64(xx))\n\tcase uint, uint8, uint16, uint32:\n\t\treturn fmt.Sprint(\"unsigned \", xx)\n\tcase uint64:\n\t\treturn fmt.Sprint(\"unsigned64 \", uint64(xx))\n\tcase nil:\n\t\treturn fmt.Sprint(\"nil \", xx)\n\t}\n\tpanic(\"not reached\")\n}\n\n\n\nfunc check(x interface{}, s string) {\n\tw := whatis(x)\n\tif w != s {\n\t\tfmt.Println(\"whatis\", x, \"=>\", w, \"!=\", s)\n\t\tpanic(\"fail\")\n\t}\n\n\tw = whatis1(x)\n\tif w != s {\n\t\tfmt.Println(\"whatis1\", x, \"=>\", w, \"!=\", s)\n\t\tpanic(\"fail\")\n\t}\n}\n\nfunc main() {\n\tcheck(1, \"signed 1\")\n\tcheck(uint(1), \"unsigned 1\")\n\tcheck(int64(1), \"signed64 1\")\n\tcheck(uint64(1), \"unsigned64 1\")\n\tcheck(1.5, \"default 1.5\")\n\tcheck(nil, \"nil \")\n}\n\nfunc whatis1(x interface{}) string ", "output": "{\n\txx := x\n\tswitch xx.(type) {\n\tdefault:\n\t\treturn fmt.Sprint(\"default \", xx)\n\tcase int, int8, int16, int32:\n\t\treturn fmt.Sprint(\"signed \", xx)\n\tcase int64:\n\t\treturn fmt.Sprint(\"signed64 \", xx.(int64))\n\tcase uint, uint8, uint16, uint32:\n\t\treturn fmt.Sprint(\"unsigned \", xx)\n\tcase uint64:\n\t\treturn fmt.Sprint(\"unsigned64 \", xx.(uint64))\n\tcase nil:\n\t\treturn fmt.Sprint(\"nil \", xx)\n\t}\n\tpanic(\"not reached\")\n}"} {"input": "package jujuc\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"launchpad.net/gnuflag\"\n\n\t\"github.com/juju/core/cmd\"\n)\n\n\ntype UnitGetCommand struct {\n\tcmd.CommandBase\n\tctx Context\n\tKey string\n\tout cmd.Output\n}\n\nfunc NewUnitGetCommand(ctx Context) cmd.Command {\n\treturn &UnitGetCommand{ctx: ctx}\n}\n\n\n\nfunc (c *UnitGetCommand) SetFlags(f *gnuflag.FlagSet) {\n\tc.out.AddFlags(f, \"smart\", cmd.DefaultFormatters)\n}\n\nfunc (c *UnitGetCommand) Init(args []string) error {\n\tif args == nil {\n\t\treturn errors.New(\"no setting specified\")\n\t}\n\tif args[0] != \"private-address\" && args[0] != \"public-address\" {\n\t\treturn fmt.Errorf(\"unknown setting %q\", args[0])\n\t}\n\tc.Key = args[0]\n\treturn cmd.CheckEmpty(args[1:])\n}\n\nfunc (c *UnitGetCommand) Run(ctx *cmd.Context) error {\n\tvalue, ok := \"\", false\n\tif c.Key == \"private-address\" {\n\t\tvalue, ok = c.ctx.PrivateAddress()\n\t} else {\n\t\tvalue, ok = c.ctx.PublicAddress()\n\t}\n\tif !ok {\n\t\treturn fmt.Errorf(\"%s not set\", c.Key)\n\t}\n\treturn c.out.Write(ctx, value)\n}\n\nfunc (c *UnitGetCommand) Info() *cmd.Info ", "output": "{\n\treturn &cmd.Info{\n\t\tName: \"unit-get\",\n\t\tArgs: \"\",\n\t\tPurpose: \"print public-address or private-address\",\n\t}\n}"} {"input": "package user\n\nimport (\n\t\"github.com/AitorGuerrero/UserGo/user\"\n)\n\ntype User struct {\n\tId string\n\tPasskey string\n\tToken string\n\tNamespaces []string\n}\n\n\n\nfunc FromMngUser(mngu User) user.User {\n\tu = user.New(user.ParseId(mngu.Id), user.Passkey(mngu.Passkey))\n\n\treturn u\n}\n\nfunc FromDomainUser(u user.User) User ", "output": "{\n\treturn User {\n\t\tu.Id().Serialize(),\n\t\tstring(u.Passkey()),\n\t\tu.Token.Serialize(),\n\t\t[]string{},\n\t}\n}"} {"input": "package shared\n\ntype RunTaskError struct {\n\tMessage string\n}\n\nfunc (e RunTaskError) Error() string {\n\treturn \"Error running task: {{.CloudControllerMessage}}\"\n}\n\nfunc (e RunTaskError) Translate(translate func(string, ...interface{}) string) string {\n\treturn translate(e.Error(), map[string]interface{}{\n\t\t\"CloudControllerMessage\": e.Message,\n\t})\n}\n\ntype ClientTargetError struct {\n\tMessage string\n}\n\n\n\nfunc (e ClientTargetError) Translate(translate func(string, ...interface{}) string) string {\n\treturn translate(e.Error(), map[string]interface{}{\n\t\t\"Message\": e.Message,\n\t})\n}\n\nfunc (e ClientTargetError) Error() string ", "output": "{\n\treturn \"{{.Message}}\\nNote that this command requires CF API version 3.0.0+.\"\n}"} {"input": "package qln\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/btcsuite/btcd/chaincfg/chainhash\"\n\t\"github.com/mit-dci/lit/lnutil\"\n)\n\n\n\n\nfunc (q *Qchan) NextElkPointForThem() (p [33]byte, err error) {\n\treturn q.ElkPoint(false, q.State.StateIdx+1)\n}\n\n\n\n\n\n\n\nfunc (q *Qchan) ElkPoint(mine bool, idx uint64) (p [33]byte, err error) {\n\tif q == nil || q.ElkSnd == nil { \n\t\terr = fmt.Errorf(\"can't access elkrem sender\")\n\t\treturn\n\t}\n\tif mine && q.ElkRcv == nil { \n\t\terr = fmt.Errorf(\"can't access elkrem receiver\")\n\t\treturn\n\t}\n\n\telk := new(chainhash.Hash)\n\n\tif mine { \n\t\telk, err = q.ElkRcv.AtIndex(idx)\n\t} else { \n\t\telk, err = q.ElkSnd.AtIndex(idx)\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\tp = lnutil.ElkPointFromHash(elk)\n\n\treturn\n}\n\nfunc (q *Qchan) AdvanceElkrem(elk *chainhash.Hash, nextElk [33]byte) error {\n\terr := q.IngestElkrem(elk)\n\tif err != nil {\n\t\treturn err\n\t}\n\tq.State.ElkPoint = q.State.NextElkPoint\n\tq.State.NextElkPoint = nextElk\n\treturn nil\n}\n\n\n\n\n\n\n\nfunc (q *Qchan) IngestElkrem(elk *chainhash.Hash) error ", "output": "{\n\tif elk == nil {\n\t\treturn fmt.Errorf(\"IngestElkrem: nil hash\")\n\t}\n\n\terr := q.ElkRcv.AddNext(elk)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"ingested hash, receiver now has up to %d\\n\", q.ElkRcv.UpTo())\n\n\tif q.State.StateIdx == 0 {\n\t\treturn nil\n\t}\n\n\n\tpoint := lnutil.ElkPointFromHash(elk)\n\n\tif point != q.State.ElkPoint {\n\t\treturn fmt.Errorf(\"hash %x (index %d) fits tree but creates wrong elkpoint!\",\n\t\t\telk[:8], q.State.ElkPoint)\n\t}\n\n\n\treturn nil\n}"} {"input": "package v1alpha1\n\n\n\n\n\n\n\n\n\n\n\n\nvar map_CertificateSigningRequest = map[string]string{\n\t\"\": \"Describes a certificate signing request\",\n\t\"spec\": \"The certificate request itself and any additional information.\",\n\t\"status\": \"Derived information about the request.\",\n}\n\n\n\nvar map_CertificateSigningRequestCondition = map[string]string{\n\t\"type\": \"request approval state, currently Approved or Denied.\",\n\t\"reason\": \"brief reason for the request state\",\n\t\"message\": \"human readable message with details about the request state\",\n\t\"lastUpdateTime\": \"timestamp for the last update to this condition\",\n}\n\nfunc (CertificateSigningRequestCondition) SwaggerDoc() map[string]string {\n\treturn map_CertificateSigningRequestCondition\n}\n\nvar map_CertificateSigningRequestSpec = map[string]string{\n\t\"\": \"This information is immutable after the request is created. Only the Request and ExtraInfo fields can be set on creation, other fields are derived by Kubernetes and cannot be modified by users.\",\n\t\"request\": \"Base64-encoded PKCS#10 CSR data\",\n\t\"usages\": \"allowedUsages specifies a set of usage contexts the key will be valid for. See: https:tools.ietf.org/html/rfc5280#section-4.2.1.3\\n https:tools.ietf.org/html/rfc5280#section-4.2.1.12\",\n\t\"username\": \"Information about the requesting user (if relevant) See user.Info interface for details\",\n}\n\nfunc (CertificateSigningRequestSpec) SwaggerDoc() map[string]string {\n\treturn map_CertificateSigningRequestSpec\n}\n\nvar map_CertificateSigningRequestStatus = map[string]string{\n\t\"conditions\": \"Conditions applied to the request, such as approval or denial.\",\n\t\"certificate\": \"If request was approved, the controller will place the issued certificate here.\",\n}\n\nfunc (CertificateSigningRequestStatus) SwaggerDoc() map[string]string {\n\treturn map_CertificateSigningRequestStatus\n}\n\nfunc (CertificateSigningRequest) SwaggerDoc() map[string]string ", "output": "{\n\treturn map_CertificateSigningRequest\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\ntype SCmd struct {\n\tm_chanStringCmd chan string\n\tm_chanWaitCmdComplete chan bool\n\tm_bHadStop bool\n\tm_funcDoCmd func(string)\n\tm_mutex sync.Mutex\n}\n\nfunc NewSCmd(funcDoCmd func(string)) *SCmd {\n\tif funcDoCmd == nil {\n\t\treturn nil\n\t}\n\n\tvar pSCmd = &SCmd{\n\t\tm_bHadStop: false,\n\t\tm_chanStringCmd: make(chan string, 0),\n\t\tm_chanWaitCmdComplete: make(chan bool, 0),\n\t\tm_funcDoCmd: funcDoCmd,\n\t}\n\tgo pSCmd.mainWorker()\n\treturn pSCmd\n}\n\nfunc (this *SCmd) Cmd(strCmd string) {\n\tfmt.Println(\"Cmd\", strCmd)\n\n\tif this.m_bHadStop {\n\t\tfmt.Println(\"had stop\")\n\t\treturn\n\t}\n\n\tthis.m_chanStringCmd <- strCmd\n}\n\n\n\nfunc (this *SCmd) mainWorker() {\n\tfor strCmd := range this.m_chanStringCmd {\n\t\tthis.m_funcDoCmd(strCmd)\n\t}\n}\n\nfunc (this *SCmd) Quit() ", "output": "{\n\tclose(this.m_chanStringCmd)\n}"} {"input": "package deadlockhistory\n\nimport (\n\t\"testing\"\n\n\t\"github.com/pingcap/tidb/util/testbridge\"\n\t\"go.uber.org/goleak\"\n)\n\n\n\nfunc TestMain(m *testing.M) ", "output": "{\n\ttestbridge.SetupForCommonTest()\n\tgoleak.VerifyTestMain(m)\n}"} {"input": "package suite_init\n\ntype SuiteData struct {\n\t*StubsData\n\t*SynchronizedSuiteCallbacksData\n\t*WerfBinaryData\n\t*ProjectNameData\n\t*K8sDockerRegistryData\n\t*TmpDirData\n\t*ContainerRegistryPerImplementationData\n}\n\nfunc (data *SuiteData) SetupStubs(setupData *StubsData) bool {\n\tdata.StubsData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupSynchronizedSuiteCallbacks(setupData *SynchronizedSuiteCallbacksData) bool {\n\tdata.SynchronizedSuiteCallbacksData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupWerfBinary(setupData *WerfBinaryData) bool {\n\tdata.WerfBinaryData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupProjectName(setupData *ProjectNameData) bool {\n\tdata.ProjectNameData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupK8sDockerRegistry(setupData *K8sDockerRegistryData) bool {\n\tdata.K8sDockerRegistryData = setupData\n\treturn true\n}\n\n\n\nfunc (data *SuiteData) SetupContainerRegistryPerImplementation(setupData *ContainerRegistryPerImplementationData) bool {\n\tdata.ContainerRegistryPerImplementationData = setupData\n\treturn true\n}\n\nfunc (data *SuiteData) SetupTmp(setupData *TmpDirData) bool ", "output": "{\n\tdata.TmpDirData = setupData\n\treturn true\n}"} {"input": "package mlib\n\nimport (\n\t\"io\"\n)\n\ntype reader struct {\n\tinner io.Reader\n}\n\n\nfunc NewCrRemovingReader(inner io.Reader) io.ReadCloser {\n\tr := reader{inner: inner}\n\treturn &r\n}\n\n\n\nfunc (r *reader) Close() error {\n\tDebug(\"close...\\n\")\n\tswitch r.inner.(type) {\n\tcase io.Closer:\n\t\treturn r.inner.(io.Closer).Close()\n\t}\n\treturn nil\n}\n\nfunc (r *reader) Read(p []byte) (int, error) ", "output": "{\n\tread, err := r.inner.Read(p)\n\tretLen := 0\n\tfor i := 0; i < read; i++ {\n\t\tif p[i] != '\\r' {\n\t\t\tp[retLen] = p[i]\n\t\t\tretLen++\n\t\t}\n\t}\n\n\treturn retLen, err\n}"} {"input": "package storage\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) BaseClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient ", "output": "{\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package types\n\nimport (\n\t\"crypto/sha512\"\n\t\"fmt\"\n)\n\n\ntype Packet struct {\n\tDest NodeAddress\n\tAmt int64\n\tData []byte\n}\n\nfunc (p Packet) Destination() NodeAddress {\n\treturn p.Dest\n}\n\n\n\n\nfunc (p Packet) Amount() int64 {\n\treturn p.Amt\n}\n\nfunc (p Packet) String() string {\n\treturn fmt.Sprintf(\"{%x %v %q}\", p.Dest, p.Amt, p.Data)\n}\n\nfunc (p Packet) Hash() PacketHash ", "output": "{\n\to := sha512.Sum512([]byte(string(p.Dest) + string(p.Data)))\n\treturn PacketHash(string(o[0:sha512.Size]))\n}"} {"input": "package save\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"encoding/pem\"\n\t\"io/ioutil\"\n\t\"log\"\n)\n\n\n\nfunc SaveKey(priv *rsa.PrivateKey, o string) ", "output": "{\n\tblock := pem.EncodeToMemory(&pem.Block{Type: \"RSA PRIVATE KEY\", Bytes: x509.MarshalPKCS1PrivateKey(priv)})\n\tif e := ioutil.WriteFile(o+\".onion\", block, 0600); e != nil {\n\t\tlog.Print(\"failed to save \"+o+\".onion to file:\", e)\n\t\tlog.Print(o+\"\\n\", string(block))\n\t}\n}"} {"input": "package v1alpha1\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\tv1alpha1 \"k8s.io/ingress-gce/pkg/experimental/apis/workload/v1alpha1\"\n\t\"k8s.io/ingress-gce/pkg/experimental/workload/client/clientset/versioned/scheme\"\n)\n\ntype NetworkingV1alpha1Interface interface {\n\tRESTClient() rest.Interface\n\tWorkloadsGetter\n}\n\n\ntype NetworkingV1alpha1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *NetworkingV1alpha1Client) Workloads(namespace string) WorkloadInterface {\n\treturn newWorkloads(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*NetworkingV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &NetworkingV1alpha1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *NetworkingV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *NetworkingV1alpha1Client {\n\treturn &NetworkingV1alpha1Client{c}\n}\n\n\n\n\n\nfunc (c *NetworkingV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc setConfigDefaults(config *rest.Config) error ", "output": "{\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}"} {"input": "package cachestore\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\n\ntype KVStore struct {\n\tstoreMap map[string]interface{}\n\tmutex sync.RWMutex\n}\n\n\nfunc (store *KVStore) Set(key string, value interface{}) {\n\tstore.mutex.Lock()\n\tstore.storeMap[key] = value\n\tstore.mutex.Unlock()\n}\n\n\nfunc (store *KVStore) Get(key string) interface{} {\n\tstore.mutex.RLock()\n\tval := store.storeMap[key]\n\tstore.mutex.RUnlock()\n\treturn val\n}\n\n\nfunc (store *KVStore) Delete(key string) {\n\tstore.mutex.Lock()\n\tdelete(store.storeMap, key)\n\tstore.mutex.Unlock()\n}\n\n\n\n\n\nfunc NewKVStore() *KVStore {\n\treturn &KVStore{map[string]interface{}{}, sync.RWMutex{}}\n}\n\nfunc (store *KVStore) MarshalJSON() ([]byte, error) ", "output": "{\n\tstore.mutex.RLock()\n\tbytes, err := json.Marshal(store.storeMap)\n\tstore.mutex.RUnlock()\n\treturn bytes, err\n}"} {"input": "package drain\n\nimport (\n\t\"fmt\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n\tutilerrors \"k8s.io/apimachinery/pkg/util/errors\"\n)\n\n\n\n\n\n\n\n\nfunc RunNodeDrain(drainer *Helper, nodeName string) error {\n\tlist, errs := drainer.GetPodsForDeletion(nodeName)\n\tif errs != nil {\n\t\treturn utilerrors.NewAggregate(errs)\n\t}\n\tif warnings := list.Warnings(); warnings != \"\" {\n\t\tfmt.Fprintf(drainer.ErrOut, \"WARNING: %s\\n\", warnings)\n\t}\n\n\tif err := drainer.DeleteOrEvictPods(list.Pods()); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\n\nfunc RunCordonOrUncordon(drainer *Helper, node *corev1.Node, desired bool) error ", "output": "{\n\tc := NewCordonHelper(node)\n\n\tif updateRequired := c.UpdateIfRequired(desired); !updateRequired {\n\t\treturn nil\n\t}\n\n\terr, patchErr := c.PatchOrReplace(drainer.Client, false)\n\tif patchErr != nil {\n\t\treturn patchErr\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package ubuntu\n\nimport (\n\t\"github.com/megamsys/megdc/templates\"\n\t\"github.com/megamsys/urknall\"\n)\n\nvar ubuntunilavuremove *UbuntuNilavuRemove\n\n\n\ntype UbuntuNilavuRemove struct{}\n\nfunc (tpl *UbuntuNilavuRemove) Render(p urknall.Package) {\n\tp.AddTemplate(\"nilavu\", &UbuntuNilavuRemoveTemplate{})\n}\n\nfunc (tpl *UbuntuNilavuRemove) Options(t *templates.Template) {\n}\n\nfunc (tpl *UbuntuNilavuRemove) Run(target urknall.Target) error {\n\treturn urknall.Run(target, &UbuntuNilavuRemove{})\n}\n\ntype UbuntuNilavuRemoveTemplate struct{}\n\nfunc (m *UbuntuNilavuRemoveTemplate) Render(pkg urknall.Package) {\n\tpkg.AddCommands(\"verticenilavu\",\n\t\tRemovePackage(\"verticenilavu\"),\n\t\tRemovePackages(\"\"),\n\t\tPurgePackages(\"verticenilavu\"),\n\t\tShell(\"dpkg --get-selections megam*\"),\n\t)\n\tpkg.AddCommands(\"nilavu-clean\",\n\t\tShell(\"rm -r /var/lib/urknall/nilavu*\"),\n\t)\n}\n\nfunc init() ", "output": "{\n\tubuntunilavuremove = &UbuntuNilavuRemove{}\n\ttemplates.Register(\"UbuntuNilavuRemove\", ubuntunilavuremove)\n}"} {"input": "package wiringpi\n\n\n\n\n\n\n\n\n\n\n\nimport \"C\"\nimport (\n\t\"sync\"\n\n\t\"github.com/yroffin/jarvis-go-ext/logger\"\n)\n\n\ntype WiringPiDriver struct {\n}\n\nvar instance *WiringPiDriver\nvar once sync.Once\n\n\nfunc GetInstance() *WiringPiDriver {\n\tonce.Do(func() {\n\t\tinstance = new(WiringPiDriver)\n\t\tinstance.init()\n\t})\n\treturn instance\n}\n\n\n\n\n\nfunc PinMode(pin int, value int) {\n\tC.pinMode(C.int(pin), C.int(value))\n}\n\n\nfunc DigitalWrite(pin int, value int) {\n\tC.digitalWrite(C.int(pin), C.int(value))\n}\n\n\nfunc DelayMicroseconds(delay uint) {\n\tC.delayMicroseconds(C.uint(delay))\n}\n\n\nfunc Delay(delay uint) {\n\tC.delay(C.uint(delay))\n}\n\nfunc (wiringPi *WiringPiDriver) init() int ", "output": "{\n\tvar res = int(C.wiringPiSetupInit())\n\tlogger.Default.Info(\"WiringPiDriver\", logger.Fields{\n\t\t\"Init\": \"on\",\n\t})\n\treturn res\n}"} {"input": "package chart_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/dml/chart\"\n)\n\nfunc TestCT_NumDataSourceConstructor(t *testing.T) {\n\tv := chart.NewCT_NumDataSource()\n\tif v == nil {\n\t\tt.Errorf(\"chart.NewCT_NumDataSource must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed chart.CT_NumDataSource should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestCT_NumDataSourceMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := chart.NewCT_NumDataSource()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := chart.NewCT_NumDataSource()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package instana\n\nimport (\n\t\"time\"\n)\n\n\ntype EventData struct {\n\tTitle string `json:\"title\"`\n\tText string `json:\"text\"`\n\tDuration int `json:\"duration\"`\n\tSeverity int `json:\"severity\"`\n\tPlugin string `json:\"plugin,omitempty\"`\n\tID string `json:\"id,omitempty\"`\n\tHost string `json:\"host\"`\n}\n\ntype severity int\n\n\nconst (\n\tSeverityChange severity = -1\n\tSeverityWarning severity = 5\n\tSeverityCritical severity = 10\n)\n\n\nconst (\n\tServicePlugin = \"com.instana.forge.connection.http.logical.LogicalWebApp\"\n\tServiceHost = \"\"\n)\n\n\nfunc SendDefaultServiceEvent(title string, text string, sev severity, duration time.Duration) {\n\tif sensor == nil {\n\t\tSendServiceEvent(\"\", title, text, sev, duration)\n\t} else {\n\t\tSendServiceEvent(sensor.serviceName, title, text, sev, duration)\n\t}\n}\n\n\nfunc SendServiceEvent(service string, title string, text string, sev severity, duration time.Duration) {\n\tsendEvent(&EventData{\n\t\tTitle: title,\n\t\tText: text,\n\t\tSeverity: int(sev),\n\t\tPlugin: ServicePlugin,\n\t\tID: service,\n\t\tHost: ServiceHost,\n\t\tDuration: int(duration / time.Millisecond),\n\t})\n}\n\n\nfunc SendHostEvent(title string, text string, sev severity, duration time.Duration) {\n\tsendEvent(&EventData{\n\t\tTitle: title,\n\t\tText: text,\n\t\tDuration: int(duration / time.Millisecond),\n\t\tSeverity: int(sev),\n\t})\n}\n\n\n\nfunc sendEvent(event *EventData) ", "output": "{\n\tif sensor == nil {\n\t\tInitSensor(&Options{})\n\t}\n\tgo sensor.agent.request(sensor.agent.makeURL(agentEventURL), \"POST\", event)\n}"} {"input": "package main\n\nimport \"sort\"\n\ntype Node struct {\n\tLeft *Node\n\tRight *Node\n\tParent *Node\n\tValue uint\n\tFactor int\n}\n\nfunc GetHuffmanTree(arr []uint) *Node {\n\tm := make(map[uint]int)\n\tfor _, v := range arr {\n\t\tm[v]++\n\t}\n\tvar nodes []*Node\n\tfor k, v := range m {\n\t\tnodes = append(nodes, &Node{Value: k, Factor: v})\n\t}\n\tfor len(nodes) > 1 {\n\t\tsort.Slice(nodes, func(i, j int) bool {\n\t\t\treturn nodes[i].Factor < nodes[j].Factor\n\t\t})\n\t\tnewNode := &Node{Left: nodes[0], Right: nodes[1], Factor: nodes[0].Factor + nodes[1].Factor}\n\t\tnodes[0].Parent, nodes[1].Parent = newNode, newNode\n\t\tnodes = append(nodes[2:], newNode)\n\t}\n\tif len(nodes) == 1 {\n\t\treturn nodes[0]\n\t}\n\treturn nil\n}\n\n\n\nfunc scan(root *Node, prefix string, table *map[uint]string) {\n\tif root.Left == nil || root.Right == nil {\n\t\t(*table)[root.Value] = prefix\n\t}\n\tif root.Left != nil {\n\t\tscan(root.Left, prefix + \"0\", table)\n\t}\n\tif root.Right != nil {\n\t\tscan(root.Right, prefix + \"1\", table)\n\t}\n}\n\nfunc GetHuffmanTableMap(root *Node) map[uint]string ", "output": "{\n\ttable := make(map[uint]string)\n\tscan(root, \"\", &table)\n\treturn table\n}"} {"input": "package misc\n\nimport \"errors\"\n\n\n\n\nfunc Mksocket(path string) (err error) {\n\treturn errors.New(\"not supported\")\n}\n\nfunc Mkfifo(path string, mode uint32) (err error) ", "output": "{\n\treturn errors.New(\"not supported\")\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/robfig/cron\"\n)\n\ntype Sync struct{}\n\nfunc (s *Sync) Help() string {\n\treturn \"glr sync Help\"\n}\n\nfunc (s *Sync) Run(args []string) int {\n\t_, err := SyncRepository()\n\n\tif err != nil {\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n\nfunc (s *Sync) Synopsis() string {\n\treturn \"Synchronize local git repository with remote at once\"\n}\n\n\ntype status struct {\n\tc *cron.Cron\n\trepositories []string\n\tschedules []string\n}\n\nvar sharedStatus *status = newStatus()\n\nfunc newStatus() *status {\n\treturn &status{\n\t\tc: cron.New(),\n\t}\n}\n\n\nfunc GetStatus() *status {\n\treturn sharedStatus\n}\n\ntype StatusStart struct{}\n\n\n\nfunc (s *StatusStart) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.AddFunc(\"@hourly\", func() {\n\t\tSyncRepository()\n\t})\n\tfmt.Println(\"set job schedule\")\n\tstatus.c.Start()\n\n\treturn 0\n}\n\nfunc (s *StatusStart) Synopsis() string {\n\treturn \"Synchronize local git repository with remote\"\n}\n\ntype StatusStop struct{}\n\nfunc (s *StatusStop) Help() string {\n\treturn \"glr status stop Help\"\n}\n\nfunc (s *StatusStop) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.Stop()\n\tfmt.Println(\"stop job scheduler\")\n\n\treturn 0\n}\n\nfunc (s *StatusStop) Synopsis() string {\n\treturn \"Stop cron scheduler\"\n}\n\nfunc (s *StatusStart) Help() string ", "output": "{\n\treturn \"glr status start Help\"\n}"} {"input": "package space\n\n\ntype Planet string\n\nconst secondsInEarthYear = 31557600\n\nvar orbitalPeriods = map[Planet]float64{\n\t\"Mercury\": 0.2408467,\n\t\"Venus\": 0.61519726,\n\t\"Earth\": 1,\n\t\"Mars\": 1.8808158,\n\t\"Jupiter\": 11.862615,\n\t\"Saturn\": 29.447498,\n\t\"Uranus\": 84.016846,\n\t\"Neptune\": 164.79132,\n}\n\n\n\n\n\nfunc ageOnEarth(ageInSeconds float64) float64 {\n\treturn ageInSeconds / secondsInEarthYear\n}\n\nfunc Age(ageInSeconds float64, planet Planet) float64 ", "output": "{\n\treturn ageOnEarth(ageInSeconds) / orbitalPeriods[planet]\n}"} {"input": "package google\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/v2/terraform\"\n)\n\n\n\nfunc testAccFirestoreIndex_firestoreIndexBasicExample(context map[string]interface{}) string {\n\treturn Nprintf(`\nresource \"google_firestore_index\" \"my-index\" {\n project = \"%{project_id}\"\n\n collection = \"chatrooms\"\n\n fields {\n field_path = \"name\"\n order = \"ASCENDING\"\n }\n\n fields {\n field_path = \"description\"\n order = \"DESCENDING\"\n }\n\n}\n`, context)\n}\n\nfunc testAccCheckFirestoreIndexDestroyProducer(t *testing.T) func(s *terraform.State) error {\n\treturn func(s *terraform.State) error {\n\t\tfor name, rs := range s.RootModule().Resources {\n\t\t\tif rs.Type != \"google_firestore_index\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.HasPrefix(name, \"data.\") {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconfig := googleProviderConfig(t)\n\n\t\t\turl, err := replaceVarsForTest(config, rs, \"{{FirestoreBasePath}}{{name}}\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbillingProject := \"\"\n\n\t\t\tif config.BillingProject != \"\" {\n\t\t\t\tbillingProject = config.BillingProject\n\t\t\t}\n\n\t\t\t_, err = sendRequest(config, \"GET\", billingProject, url, config.userAgent, nil)\n\t\t\tif err == nil {\n\t\t\t\treturn fmt.Errorf(\"FirestoreIndex still exists at %s\", url)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc TestAccFirestoreIndex_firestoreIndexBasicExample(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\tcontext := map[string]interface{}{\n\t\t\"project_id\": getTestFirestoreProjectFromEnv(t),\n\t\t\"random_suffix\": randString(t, 10),\n\t}\n\n\tvcrTest(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testAccCheckFirestoreIndexDestroyProducer(t),\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccFirestoreIndex_firestoreIndexBasicExample(context),\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName: \"google_firestore_index.my-index\",\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t\tImportStateVerifyIgnore: []string{\"database\", \"collection\"},\n\t\t\t},\n\t\t},\n\t})\n}"} {"input": "package datastore\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n)\n\n\ntype Posix struct {\n\tMountPoint string\n}\n\n\nfunc (p *Posix) Write(ID string, body io.Reader) (err error) {\n\timageName := path.Join(p.MountPoint, ID)\n\tif _, err := os.Stat(imageName); !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"image already uploaded with that ID\")\n\t}\n\n\timage, err := os.Create(imageName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuf := make([]byte, 1<<16)\n\n\t_, err = io.CopyBuffer(image, body, buf)\n\tdefer func() {\n\t\terr1 := image.Close()\n\t\tif err == nil {\n\t\t\terr = err1\n\t\t}\n\t}()\n\n\treturn err\n}\n\n\n\n\n\nfunc (p *Posix) GetImageSize(ID string) (uint64, error) {\n\timageName := path.Join(p.MountPoint, ID)\n\n\tfi, err := os.Stat(imageName)\n\timageSize := uint64(fi.Size())\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"Error getting image size: %v\", err)\n\t}\n\treturn imageSize, nil\n}\n\nfunc (p *Posix) Delete(ID string) error ", "output": "{\n\timageName := path.Join(p.MountPoint, ID)\n\n\t_, err := os.Stat(imageName)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\terr = nil\n\t\t}\n\t\treturn err\n\t}\n\n\terr = os.Remove(imageName)\n\n\treturn err\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\n\tthings := map[string]interface{}{\n\t\t\"string\": \"stringval\",\n\t\t\"bool\": true,\n\t\t\"int\": 5,\n\t\t\"struct\": struct{}{}, \n\t}\n\n\tfor k, v := range things {\n\t\tthingType(k, v)\n\t}\n\n}\n\n\n\nfunc thingType(k string, v interface{}) ", "output": "{\n\n\tswitch t := v.(type) {\n\tdefault:\n\t\tfmt.Printf(\"unexpected type %T\\n\", t) \n\tcase bool:\n\t\tfmt.Printf(\"boolean %t\\n\", t) \n\tcase int:\n\t\tfmt.Printf(\"integer %d\\n\", t) \n\tcase string:\n\t\tfmt.Printf(\"string %s\\n\", t) \n\t}\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\n\t\"go-common/app/job/openplatform/article/conf\"\n\t\"go-common/app/job/openplatform/article/http\"\n\t\"go-common/app/job/openplatform/article/service\"\n\t\"go-common/library/log\"\n\t\"go-common/library/net/trace\"\n)\n\nfunc main() {\n\tflag.Parse()\n\tinitConf()\n\tinitLog()\n\tdefer log.Close()\n\tlog.Info(\"article-job start\")\n\tsrv := service.New(conf.Conf)\n\thttp.Init(conf.Conf, srv)\n\tinitSignal(srv)\n}\n\nfunc initConf() {\n\tif err := conf.Init(); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc initLog() {\n\tlog.Init(conf.Conf.Xlog)\n\ttrace.Init(conf.Conf.Tracer)\n\tdefer trace.Close()\n}\n\n\n\nfunc initSignal(srv *service.Service) ", "output": "{\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)\n\tfor {\n\t\ts := <-c\n\t\tlog.Info(\"article-job get a signal: %s\", s.String())\n\t\tswitch s {\n\t\tcase syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:\n\t\t\tif err := srv.Close(); err != nil {\n\t\t\t\tlog.Error(\"srv close consumer error(%+v)\", err)\n\t\t\t}\n\t\t\treturn\n\t\tcase syscall.SIGHUP:\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}"} {"input": "package elasticsearch_test\n\nimport (\n\t\"crypto/tls\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/elastic/go-elasticsearch/v7\"\n\t\"github.com/elastic/go-elasticsearch/v7/estransport\"\n)\n\n\n\nfunc ExampleNewDefaultClient() {\n\tes, err := elasticsearch.NewDefaultClient()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error creating the client: %s\\n\", err)\n\t}\n\n\tres, err := es.Info()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error getting the response: %s\\n\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tlog.Print(es.Transport.(*estransport.Client).URLs())\n}\n\nfunc ExampleNewClient() {\n\tcfg := elasticsearch.Config{\n\t\tAddresses: []string{\n\t\t\t\"http:localhost:9200\",\n\t\t},\n\t\tUsername: \"foo\",\n\t\tPassword: \"bar\",\n\t\tTransport: &http.Transport{\n\t\t\tMaxIdleConnsPerHost: 10,\n\t\t\tResponseHeaderTimeout: time.Second,\n\t\t\tDialContext: (&net.Dialer{Timeout: time.Second}).DialContext,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tMinVersion: tls.VersionTLS11,\n\t\t\t},\n\t\t},\n\t}\n\n\tes, _ := elasticsearch.NewClient(cfg)\n\tlog.Print(es.Transport.(*estransport.Client).URLs())\n}\n\nfunc ExampleNewClient_logger() {\n\n\n\tcfg := elasticsearch.Config{\n\t\tLogger: &estransport.ColorLogger{Output: os.Stdout},\n\t}\n\n\telasticsearch.NewClient(cfg)\n}\n\nfunc init() ", "output": "{\n\tlog.SetFlags(0)\n}"} {"input": "package dao\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestDaoTypeMapping(t *testing.T) {\n\tconvey.Convey(\"TypeMapping\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\trmap, err := testDao.TypeMapping(c)\n\t\t\tctx.Convey(\"Then err should be nil.rmap should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t\tctx.So(rmap, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestDaotypesURI(t *testing.T) ", "output": "{\n\tconvey.Convey(\"typesURI\", t, func(ctx convey.C) {\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\tp1 := testDao.typesURI()\n\t\t\tctx.Convey(\"Then p1 should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(p1, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package service\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"net/http\"\n)\n\n\ntype StandardErrorRespModel struct {\n\tErrorMessage string `json:\"error\"`\n}\n\n\n\n\n\nfunc RespondWith(w http.ResponseWriter, httpStatusCode int, respModel interface{}) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(httpStatusCode)\n\tif err := json.NewEncoder(w).Encode(&respModel); err != nil {\n\t\tlog.Println(\" [!] Exception: RespondWith: Error: \", err)\n\t}\n}\n\n\n\n\n\nfunc RespondWithSuccessOK(w http.ResponseWriter, respModel interface{}) {\n\tRespondWith(w, http.StatusOK, respModel)\n}\n\n\n\n\n\nfunc RespondWithBadRequestError(w http.ResponseWriter, errMsg string) {\n\tRespondWithError(w, http.StatusBadRequest, errMsg)\n}\n\n\nfunc RespondWithNotFoundError(w http.ResponseWriter, errMsg string) {\n\tRespondWithError(w, http.StatusNotFound, errMsg)\n}\n\n\nfunc RespondWithError(w http.ResponseWriter, httpErrCode int, errMsg string) {\n\tresp := StandardErrorRespModel{\n\t\tErrorMessage: errMsg,\n\t}\n\tRespondWithErrorJSON(w, httpErrCode, resp)\n}\n\n\n\n\nfunc RespondWithErrorJSON(w http.ResponseWriter, httpErrCode int, respModel interface{}) ", "output": "{\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(httpErrCode)\n\tif err := json.NewEncoder(w).Encode(&respModel); err != nil {\n\t\tlog.Println(\" [!] Exception: RespondWithErrorJSON: Error: \", err)\n\t}\n}"} {"input": "package credentials\n\nimport (\n\t\"errors\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\nfunc TestChainProviderGet(t *testing.T) {\n\tp := &ChainProvider{\n\t\tProviders: []Provider{\n\t\t\t&stubProvider{err: errors.New(\"first provider error\")},\n\t\t\t&stubProvider{err: errors.New(\"second provider error\")},\n\t\t\t&stubProvider{\n\t\t\t\tcreds: Value{\n\t\t\t\t\tAccessKeyID: \"AKID\",\n\t\t\t\t\tSecretAccessKey: \"SECRET\",\n\t\t\t\t\tSessionToken: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tcreds, err := p.Retrieve()\n\tassert.Nil(t, err, \"Expect no error\")\n\tassert.Equal(t, \"AKID\", creds.AccessKeyID, \"Expect access key ID to match\")\n\tassert.Equal(t, \"SECRET\", creds.SecretAccessKey, \"Expect secret access key to match\")\n\tassert.Empty(t, creds.SessionToken, \"Expect session token to be empty\")\n}\n\n\n\nfunc TestChainProviderWithNoProvider(t *testing.T) {\n\tp := &ChainProvider{\n\t\tProviders: []Provider{},\n\t}\n\n\tassert.True(t, p.IsExpired(), \"Expect expired with no providers\")\n\t_, err := p.Retrieve()\n\tassert.Equal(t, ErrNoValidProvidersFoundInChain, err, \"Expect no providers error returned\")\n}\n\nfunc TestChainProviderWithNoValidProvider(t *testing.T) {\n\tp := &ChainProvider{\n\t\tProviders: []Provider{\n\t\t\t&stubProvider{err: errors.New(\"first provider error\")},\n\t\t\t&stubProvider{err: errors.New(\"second provider error\")},\n\t\t},\n\t}\n\n\tassert.True(t, p.IsExpired(), \"Expect expired with no providers\")\n\t_, err := p.Retrieve()\n\tassert.Contains(t, \"no valid providers in chain\", err.Error(), \"Expect no providers error returned\")\n}\n\nfunc TestChainProviderIsExpired(t *testing.T) ", "output": "{\n\tstubProvider := &stubProvider{expired: true}\n\tp := &ChainProvider{\n\t\tProviders: []Provider{\n\t\t\tstubProvider,\n\t\t},\n\t}\n\n\tassert.True(t, p.IsExpired(), \"Expect expired to be true before any Retrieve\")\n\t_, err := p.Retrieve()\n\tassert.Nil(t, err, \"Expect no error\")\n\tassert.False(t, p.IsExpired(), \"Expect not expired after retrieve\")\n\n\tstubProvider.expired = true\n\tassert.True(t, p.IsExpired(), \"Expect return of expired provider\")\n\n\t_, err = p.Retrieve()\n\tassert.False(t, p.IsExpired(), \"Expect not expired after retrieve\")\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc assertEqual(t *testing.T, a, b string) {\n\tif a != b {\n\t\tt.Errorf(\"Expected \\\"%v\\\" to equal \\\"%v\\\"\", b, a)\n\t}\n}\n\nfunc TestShellEscape(t *testing.T) ", "output": "{\n\tassertEqual(t, `''`, ShellEscape(\"\"))\n\tassertEqual(t, `$'escape\\'quote'`, ShellEscape(\"escape'quote\"))\n\tassertEqual(t, `$'foo\\r\\n\\tbar'`, ShellEscape(\"foo\\r\\n\\tbar\"))\n\tassertEqual(t, `$'foo bar'`, ShellEscape(\"foo bar\"))\n\tassertEqual(t, `$'\\xc3\\xa9'`, ShellEscape(\"é\"))\n}"} {"input": "package tests\n\n\n\nimport (\n\t\"testing\"\n)\n\n\n\n\nfunc TestInboxGETRequest(t *testing.T) {\n\tdesc := `\nServer: Fetching the inbox\n Try retrieving the actor's inbox of an actor.\n\n Server responds to GET request at inbox URL\n`\n\tt.Skip(desc)\n}\n\n\n\n\n\n\n\n\n\nfunc TestInboxFilteringBasedOnPermissions(t *testing.T) {\n\tdesc := `\nServer: Fetching the inbox\n Try retrieving the actor's inbox of an actor.\n\n Server filters inbox content according to the requester's permission\n`\n\tt.Skip(desc)\n}\n\nfunc TestInboxIsOrderedCollection(t *testing.T) ", "output": "{\n\tdesc := `\nServer: Fetching the inbox\n Try retrieving the actor's inbox of an actor.\n\n inbox is an OrderedCollection\n`\n\tt.Skip(desc)\n}"} {"input": "package nl\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\ntype RtMsg struct {\n\tsyscall.RtMsg\n}\n\n\n\nfunc NewRtDelMsg() *RtMsg {\n\treturn &RtMsg{\n\t\tRtMsg: syscall.RtMsg{\n\t\t\tTable: syscall.RT_TABLE_MAIN,\n\t\t\tScope: syscall.RT_SCOPE_NOWHERE,\n\t\t},\n\t}\n}\n\nfunc (msg *RtMsg) Len() int {\n\treturn syscall.SizeofRtMsg\n}\n\nfunc DeserializeRtMsg(b []byte) *RtMsg {\n\treturn (*RtMsg)(unsafe.Pointer(&b[0:syscall.SizeofRtMsg][0]))\n}\n\nfunc (msg *RtMsg) Serialize() []byte {\n\treturn (*(*[syscall.SizeofRtMsg]byte)(unsafe.Pointer(msg)))[:]\n}\n\ntype RtNexthop struct {\n\tsyscall.RtNexthop\n}\n\nfunc DeserializeRtNexthop(b []byte) *RtNexthop {\n\treturn (*RtNexthop)(unsafe.Pointer(&b[0:syscall.SizeofRtNexthop][0]))\n}\n\nfunc (msg *RtNexthop) Serialize() []byte {\n\treturn (*(*[syscall.SizeofRtNexthop]byte)(unsafe.Pointer(msg)))[:]\n}\n\nfunc NewRtMsg() *RtMsg ", "output": "{\n\treturn &RtMsg{\n\t\tRtMsg: syscall.RtMsg{\n\t\t\tTable: syscall.RT_TABLE_MAIN,\n\t\t\tScope: syscall.RT_SCOPE_UNIVERSE,\n\t\t\tProtocol: syscall.RTPROT_BOOT,\n\t\t\tType: syscall.RTN_UNICAST,\n\t\t},\n\t}\n}"} {"input": "package sync\n\nimport (\n\t\"sync/atomic\"\n\t\"unsafe\"\n)\n\n\n\n\n\n\ntype WaitGroup struct {\n\tm Mutex\n\tcounter int32\n\twaiters int32\n\tsema *uint32\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (wg *WaitGroup) Done() {\n\twg.Add(-1)\n}\n\n\nfunc (wg *WaitGroup) Wait() {\n\tif raceenabled {\n\t\t_ = wg.m.state \n\t\traceDisable()\n\t}\n\tif atomic.LoadInt32(&wg.counter) == 0 {\n\t\tif raceenabled {\n\t\t\traceEnable()\n\t\t\traceAcquire(unsafe.Pointer(wg))\n\t\t}\n\t\treturn\n\t}\n\twg.m.Lock()\n\tw := atomic.AddInt32(&wg.waiters, 1)\n\tif atomic.LoadInt32(&wg.counter) == 0 {\n\t\tatomic.AddInt32(&wg.waiters, -1)\n\t\tif raceenabled {\n\t\t\traceEnable()\n\t\t\traceAcquire(unsafe.Pointer(wg))\n\t\t\traceDisable()\n\t\t}\n\t\twg.m.Unlock()\n\t\tif raceenabled {\n\t\t\traceEnable()\n\t\t}\n\t\treturn\n\t}\n\tif raceenabled && w == 1 {\n\t\traceWrite(unsafe.Pointer(&wg.sema))\n\t}\n\tif wg.sema == nil {\n\t\twg.sema = new(uint32)\n\t}\n\ts := wg.sema\n\twg.m.Unlock()\n\truntime_Semacquire(s)\n\tif raceenabled {\n\t\traceEnable()\n\t\traceAcquire(unsafe.Pointer(wg))\n\t}\n}\n\nfunc (wg *WaitGroup) Add(delta int) ", "output": "{\n\tif raceenabled {\n\t\t_ = wg.m.state \n\t\tif delta < 0 {\n\t\t\traceReleaseMerge(unsafe.Pointer(wg))\n\t\t}\n\t\traceDisable()\n\t\tdefer raceEnable()\n\t}\n\tv := atomic.AddInt32(&wg.counter, int32(delta))\n\tif raceenabled {\n\t\tif delta > 0 && v == int32(delta) {\n\t\t\traceRead(unsafe.Pointer(&wg.sema))\n\t\t}\n\t}\n\tif v < 0 {\n\t\tpanic(\"sync: negative WaitGroup counter\")\n\t}\n\tif v > 0 || atomic.LoadInt32(&wg.waiters) == 0 {\n\t\treturn\n\t}\n\twg.m.Lock()\n\tfor i := int32(0); i < wg.waiters; i++ {\n\t\truntime_Semrelease(wg.sema)\n\t}\n\twg.waiters = 0\n\twg.sema = nil\n\twg.m.Unlock()\n}"} {"input": "package client_test\n\nimport (\n\t\"github.com/jdextraze/go-gesclient/client\"\n\t\"testing\"\n)\n\nfunc TestWrongExpectedVersion_Error(t *testing.T) {\n\tif client.WrongExpectedVersion.Error() != \"Wrong expected version\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestStreamDeleted_Error(t *testing.T) {\n\tif client.StreamDeleted.Error() != \"Stream deleted\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestInvalidTransaction_Error(t *testing.T) {\n\tif client.InvalidTransaction.Error() != \"Invalid transaction\" {\n\t\tt.FailNow()\n\t}\n}\n\n\n\nfunc TestAuthenticationError_Error(t *testing.T) {\n\tif client.AuthenticationError.Error() != \"Authentication error\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestBadRequest_Error(t *testing.T) {\n\tif client.BadRequest.Error() != \"Bad request\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestServerError_Error(t *testing.T) {\n\terr := client.NewServerError(\"\")\n\tif err.Error() != \"Unexpected error on server: \" {\n\t\tt.FailNow()\n\t}\n\n\terr = client.NewServerError(\"test\")\n\tif err.Error() != \"Unexpected error on server: test\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestNotModified_Error(t *testing.T) {\n\terr := client.NewNotModified(\"test\")\n\tif err.Error() != \"Stream not modified: test\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestAccessDenied_Error(t *testing.T) ", "output": "{\n\tif client.AccessDenied.Error() != \"Access denied\" {\n\t\tt.FailNow()\n\t}\n}"} {"input": "package requirements\n\nimport (\n\t\"github.com/cloudfoundry/cli/cf/api\"\n\t\"github.com/cloudfoundry/cli/cf/models\"\n)\n\ntype BuildpackRequirement interface {\n\tRequirement\n\tGetBuildpack() models.Buildpack\n}\n\ntype buildpackApiRequirement struct {\n\tname string\n\tbuildpackRepo api.BuildpackRepository\n\tbuildpack models.Buildpack\n}\n\nfunc NewBuildpackRequirement(name string, bR api.BuildpackRepository) (req *buildpackApiRequirement) {\n\treq = new(buildpackApiRequirement)\n\treq.name = name\n\treq.buildpackRepo = bR\n\treturn\n}\n\nfunc (req *buildpackApiRequirement) Execute() error {\n\tvar apiErr error\n\treq.buildpack, apiErr = req.buildpackRepo.FindByName(req.name)\n\n\tif apiErr != nil {\n\t\treturn apiErr\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (req *buildpackApiRequirement) GetBuildpack() models.Buildpack ", "output": "{\n\treturn req.buildpack\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"github.com/bfontaine/go-tchoutchou/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n\t\"reflect\"\n)\n\ntype BeEquivalentToMatcher struct {\n\tExpected interface{}\n}\n\nfunc (matcher *BeEquivalentToMatcher) Match(actual interface{}) (success bool, err error) {\n\tif actual == nil && matcher.Expected == nil {\n\t\treturn false, fmt.Errorf(\"Both actual and expected must not be nil.\")\n\t}\n\n\tconvertedActual := actual\n\n\tif actual != nil && matcher.Expected != nil && reflect.TypeOf(actual).ConvertibleTo(reflect.TypeOf(matcher.Expected)) {\n\t\tconvertedActual = reflect.ValueOf(actual).Convert(reflect.TypeOf(matcher.Expected)).Interface()\n\t}\n\n\treturn reflect.DeepEqual(convertedActual, matcher.Expected), nil\n}\n\nfunc (matcher *BeEquivalentToMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"to be equivalent to\", matcher.Expected)\n}\n\n\n\nfunc (matcher *BeEquivalentToMatcher) NegatedFailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn format.Message(actual, \"not to be equivalent to\", matcher.Expected)\n}"} {"input": "package routes\n\nimport (\n\t\"github.com/kataras/iris\"\n)\n\n\n\n\nfunc GetFollowingHandler(ctx iris.Context) ", "output": "{\n\tid, _ := ctx.Params().GetInt64(\"id\")\n\tctx.Writef(\"from \"+ctx.GetCurrentRoute().Path()+\" with ID: %d\", id)\n}"} {"input": "package vml\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\ntype CT_F struct {\n\tEqnAttr *string\n}\n\nfunc NewCT_F() *CT_F {\n\tret := &CT_F{}\n\treturn ret\n}\n\nfunc (m *CT_F) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tif m.EqnAttr != nil {\n\t\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"eqn\"},\n\t\t\tValue: fmt.Sprintf(\"%v\", *m.EqnAttr)})\n\t}\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}\n\nfunc (m *CT_F) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"eqn\" {\n\t\t\tparsed, err := attr.Value, error(nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.EqnAttr = &parsed\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_F: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (m *CT_F) ValidateWithPath(path string) error {\n\treturn nil\n}\n\nfunc (m *CT_F) Validate() error ", "output": "{\n\treturn m.ValidateWithPath(\"CT_F\")\n}"} {"input": "package rsync\n\nimport (\n\t\"os\"\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc TestParseProgressLine(t *testing.T) {\n\t_, err := ParseProgressLine(\"\")\n\tif err != NotProgressableErr {\n\t\tt.Errorf(\"Expected an empty input to be NotProgressableErr. got:%s\", err)\n\t}\n\n\tp, err := ParseProgressLine(\n\t\t\" 40984576 100% 2.44MB/s 0:00:15 (xfer#1, to-check=5/7)\",\n\t)\n\tif err != nil {\n\t\tt.Errorf(\"Encountered unexpected error. err:%s\", err)\n\t}\n\n\tif p != 40984576 {\n\t\tt.Errorf(\"Unexpected progress result. wanted:%d, got:%d\", 40984576, p)\n\t}\n\n\t_, err = ParseProgressLine(\"7 files to consider\")\n\tif err != NotProgressableErr {\n\t\tt.Errorf(\"Expected an empty input to be NotProgressableErr. got:%s\", err)\n\t}\n}\n\nfunc TestParseProgress(t *testing.T) ", "output": "{\n\ttestDir := \"testdata/download1.txt\"\n\tdownload1, err := os.Open(testDir)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to open test file, err:%s\", err)\n\t}\n\tdefer download1.Close()\n\n\tprogresses := []int{}\n\tfor p := range ParseProgress(download1) {\n\t\tprogresses = append(progresses, p)\n\t}\n\n\texpectedProgresses := []int{\n\t\t14647296,\n\t\t34242560,\n\t\t40984576,\n\t\t40986547,\n\t\t40988167,\n\t\t40989739,\n\t\t40999633,\n\t\t41001295,\n\t}\n\n\tif !reflect.DeepEqual(progresses, expectedProgresses) {\n\t\tt.Errorf(\n\t\t\t\"Progresses from download1.txt did not parse properly. expected:%q, got:%q\",\n\t\t\texpectedProgresses, progresses,\n\t\t)\n\t}\n}"} {"input": "package iso20022\n\n\ntype SettlementDetails88 struct {\n\n\tTradeDate *ISODateTime `xml:\"TradDt\"`\n\n\tSettlementParties *SettlementParties3Choice `xml:\"SttlmPties,omitempty\"`\n\n\tCollateralOwnership *CollateralOwnership1 `xml:\"CollOwnrsh\"`\n}\n\nfunc (s *SettlementDetails88) SetTradeDate(value string) {\n\ts.TradeDate = (*ISODateTime)(&value)\n}\n\n\n\nfunc (s *SettlementDetails88) AddCollateralOwnership() *CollateralOwnership1 {\n\ts.CollateralOwnership = new(CollateralOwnership1)\n\treturn s.CollateralOwnership\n}\n\nfunc (s *SettlementDetails88) AddSettlementParties() *SettlementParties3Choice ", "output": "{\n\ts.SettlementParties = new(SettlementParties3Choice)\n\treturn s.SettlementParties\n}"} {"input": "package clientv3\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/coreos/etcd/etcdserver\"\n\t\"github.com/coreos/etcd/pkg/testutil\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\nfunc TestDialTimeout(t *testing.T) {\n\tdefer testutil.AfterTest(t)\n\n\tdonec := make(chan error)\n\tgo func() {\n\t\tcfg := Config{\n\t\t\tEndpoints: []string{\"localhost:12345\"},\n\t\t\tDialTimeout: 2 * time.Second}\n\t\tc, err := New(cfg)\n\t\tif c != nil || err == nil {\n\t\t\tt.Errorf(\"new client should fail\")\n\t\t}\n\t\tdonec <- err\n\t}()\n\n\ttime.Sleep(10 * time.Millisecond)\n\n\tselect {\n\tcase err := <-donec:\n\t\tt.Errorf(\"dial didn't wait (%v)\", err)\n\tdefault:\n\t}\n\n\tselect {\n\tcase <-time.After(5 * time.Second):\n\t\tt.Errorf(\"failed to timeout dial on time\")\n\tcase err := <-donec:\n\t\tif err != grpc.ErrClientConnTimeout {\n\t\t\tt.Errorf(\"unexpected error %v, want %v\", err, grpc.ErrClientConnTimeout)\n\t\t}\n\t}\n}\n\nfunc TestDialNoTimeout(t *testing.T) {\n\tcfg := Config{Endpoints: []string{\"127.0.0.1:12345\"}}\n\tc, err := New(cfg)\n\tif c == nil || err != nil {\n\t\tt.Fatalf(\"new client with DialNoWait should succeed, got %v\", err)\n\t}\n\tc.Close()\n}\n\n\n\nfunc TestIsHaltErr(t *testing.T) ", "output": "{\n\tif !isHaltErr(nil, fmt.Errorf(\"etcdserver: some etcdserver error\")) {\n\t\tt.Errorf(`error prefixed with \"etcdserver: \" should be Halted by default`)\n\t}\n\tif isHaltErr(nil, etcdserver.ErrStopped) {\n\t\tt.Errorf(\"error %v should not halt\", etcdserver.ErrStopped)\n\t}\n\tif isHaltErr(nil, etcdserver.ErrNoLeader) {\n\t\tt.Errorf(\"error %v should not halt\", etcdserver.ErrNoLeader)\n\t}\n\tctx, cancel := context.WithCancel(context.TODO())\n\tif isHaltErr(ctx, nil) {\n\t\tt.Errorf(\"no error and active context should not be Halted\")\n\t}\n\tcancel()\n\tif !isHaltErr(ctx, nil) {\n\t\tt.Errorf(\"cancel on context should be Halted\")\n\t}\n}"} {"input": "package token\n\nimport (\n\t\"strings\"\n\n\t\"github.com/carlcui/expressive/locator\"\n)\n\n\ntype Token struct {\n\tTokenType Type\n\tRaw string\n\tLocator locator.Locator\n}\n\nfunc (tok *Token) String() string {\n\treturn tok.TokenType.String() + \": \" + tok.Raw\n}\n\nfunc (tok *Token) GetLocation() string {\n\tif tok.Locator == nil {\n\t\treturn \"unknown location\"\n\t}\n\n\treturn tok.Locator.Locate()\n}\n\n\nfunc IllegalToken(raw string, locator locator.Locator) *Token {\n\treturn &Token{TokenType: ILLEGAL, Raw: raw, Locator: locator}\n}\n\n\n\n\n\n\nfunc MatchKeyword(reading string) *Token {\n\tif tokenType, isKeyword := keywords[reading]; isKeyword {\n\t\treturn &Token{TokenType: tokenType, Raw: reading}\n\t}\n\n\treturn nil\n}\n\nfunc MatchOperator(reading string) *Token {\n\tif tokenType, isOperator := operators[reading]; isOperator {\n\t\treturn &Token{TokenType: tokenType, Raw: reading}\n\t}\n\n\treturn nil\n}\n\nfunc HasOperatorPrefix(reading string) bool {\n\tfor i := operatorStart + 1; i < operatorEnd; i++ {\n\t\tif strings.HasPrefix(tokens[i], reading) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc EOFToken(locator locator.Locator) *Token ", "output": "{\n\treturn &Token{TokenType: EOF, Raw: \"\", Locator: locator}\n}"} {"input": "package dml\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\n\ntype ST_AnimationDgmBuildType struct {\n\tST_AnimationBuildType ST_AnimationBuildType\n\tST_AnimationDgmOnlyBuildType ST_AnimationDgmOnlyBuildType\n}\n\n\n\nfunc (m ST_AnimationDgmBuildType) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\te.EncodeToken(start)\n\tif m.ST_AnimationBuildType != ST_AnimationBuildTypeUnset {\n\t\te.EncodeToken(xml.CharData(m.ST_AnimationBuildType.String()))\n\t}\n\tif m.ST_AnimationDgmOnlyBuildType != ST_AnimationDgmOnlyBuildTypeUnset {\n\t\te.EncodeToken(xml.CharData(m.ST_AnimationDgmOnlyBuildType.String()))\n\t}\n\treturn e.EncodeToken(xml.EndElement{Name: start.Name})\n}\n\nfunc (m *ST_AnimationDgmBuildType) ValidateWithPath(path string) error {\n\tmems := []string{}\n\tif m.ST_AnimationBuildType != ST_AnimationBuildTypeUnset {\n\t\tmems = append(mems, \"ST_AnimationBuildType\")\n\t}\n\tif m.ST_AnimationDgmOnlyBuildType != ST_AnimationDgmOnlyBuildTypeUnset {\n\t\tmems = append(mems, \"ST_AnimationDgmOnlyBuildType\")\n\t}\n\tif len(mems) > 1 {\n\t\treturn fmt.Errorf(\"%s too many members set: %v\", path, mems)\n\t}\n\treturn nil\n}\n\nfunc (m ST_AnimationDgmBuildType) String() string {\n\tif m.ST_AnimationBuildType != ST_AnimationBuildTypeUnset {\n\t\treturn m.ST_AnimationBuildType.String()\n\t}\n\tif m.ST_AnimationDgmOnlyBuildType != ST_AnimationDgmOnlyBuildTypeUnset {\n\t\treturn m.ST_AnimationDgmOnlyBuildType.String()\n\t}\n\treturn \"\"\n}\n\nfunc (m *ST_AnimationDgmBuildType) Validate() error ", "output": "{\n\treturn m.ValidateWithPath(\"\")\n}"} {"input": "package cmd_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestCmd(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Cmd Suite\")\n}"} {"input": "package hash\n\nimport \"unsafe\"\n\nconst DJBInit uint32 = 5381\n\nfunc DJBCombine(acc, h uint32) uint32 {\n\treturn mul33(acc) + h\n}\n\n\n\nfunc UInt32(u uint32) uint32 {\n\treturn u\n}\n\nfunc UInt64(u uint64) uint32 {\n\treturn mul33(uint32(u>>32)) + uint32(u&0xffffffff)\n}\n\nfunc Pointer(p unsafe.Pointer) uint32 {\n\tswitch unsafe.Sizeof(p) {\n\tcase 4:\n\t\treturn UInt32(uint32(uintptr(p)))\n\tcase 8:\n\t\treturn UInt64(uint64(uintptr(p)))\n\tdefault:\n\t\tpanic(\"unhandled pointer size\")\n\t}\n}\n\nfunc UIntPtr(p uintptr) uint32 {\n\tswitch unsafe.Sizeof(p) {\n\tcase 4:\n\t\treturn UInt32(uint32(p))\n\tcase 8:\n\t\treturn UInt64(uint64(p))\n\tdefault:\n\t\tpanic(\"unhandled pointer size\")\n\t}\n}\n\nfunc String(s string) uint32 {\n\th := DJBInit\n\tfor i := 0; i < len(s); i++ {\n\t\th = DJBCombine(h, uint32(s[i]))\n\t}\n\treturn h\n}\n\nfunc mul33(u uint32) uint32 {\n\treturn u<<5 + u\n}\n\nfunc DJB(hs ...uint32) uint32 ", "output": "{\n\tacc := DJBInit\n\tfor _, h := range hs {\n\t\tacc = DJBCombine(acc, h)\n\t}\n\treturn acc\n}"} {"input": "package password\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"time\"\n\n\tjwt \"github.com/dgrijalva/jwt-go\"\n)\n\nvar signingKey = genRandBytes()\n\n\n\n\n\n\n\n\n\n\nfunc SetSigningKey(key []byte) {\n\tsigningKey = key\n}\n\n\n\nfunc genRandBytes() []byte {\n\tb := make([]byte, 24)\n\t_, err := rand.Read(b)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []byte(base64.URLEncoding.EncodeToString(b))\n}\n\nfunc GenToken(id string) (string, error) ", "output": "{\n\tjwt := jwt.New(jwt.SigningMethodHS256)\n\texpTime := time.Now().Add(time.Hour * 72).Unix()\n\n\tjwt.Claims[\"sub\"] = id\n\tjwt.Claims[\"exp\"] = expTime\n\tjwt.Claims[\"iat\"] = time.Now().Unix()\n\n\ttokStr, err := jwt.SignedString(signingKey)\n\tif err != nil {\n\t\treturn \"\", err \n\t}\n\n\treturn tokStr, nil\n}"} {"input": "package utf8\n\nimport (\n\t\"bytes\"\n\t\"unicode/utf8\"\n)\n\n\n\n\n\nfunc Scrub(in string) string ", "output": "{\n\n\tif utf8.ValidString(in) {\n\t\treturn in\n\t}\n\n\tleft := []byte(in)\n\tvar result bytes.Buffer\n\n\tfor len(left) > 0 {\n\t\tr, n := utf8.DecodeRune(left)\n\n\t\t_, err := result.WriteRune(r)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tleft = left[n:]\n\t}\n\n\treturn result.String()\n}"} {"input": "package storage\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tgenericapirequest \"k8s.io/apiserver/pkg/endpoints/request\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\tgenericregistry \"k8s.io/apiserver/pkg/registry/generic/registry\"\n\t\"k8s.io/apiserver/pkg/registry/rest\"\n\tapi \"k8s.io/kubernetes/pkg/apis/core\"\n\t\"k8s.io/kubernetes/pkg/registry/core/persistentvolume\"\n)\n\ntype REST struct {\n\t*genericregistry.Store\n}\n\n\n\n\n\nvar _ rest.ShortNamesProvider = &REST{}\n\n\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"pv\"}\n}\n\n\ntype StatusREST struct {\n\tstore *genericregistry.Store\n}\n\nfunc (r *StatusREST) New() runtime.Object {\n\treturn &api.PersistentVolume{}\n}\n\n\nfunc (r *StatusREST) Get(ctx genericapirequest.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}\n\n\nfunc (r *StatusREST) Update(ctx genericapirequest.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc) (runtime.Object, bool, error) {\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation)\n}\n\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST) ", "output": "{\n\tstore := &genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return &api.PersistentVolume{} },\n\t\tNewListFunc: func() runtime.Object { return &api.PersistentVolumeList{} },\n\t\tPredicateFunc: persistentvolume.MatchPersistentVolumes,\n\t\tDefaultQualifiedResource: api.Resource(\"persistentvolumes\"),\n\n\t\tCreateStrategy: persistentvolume.Strategy,\n\t\tUpdateStrategy: persistentvolume.Strategy,\n\t\tDeleteStrategy: persistentvolume.Strategy,\n\t\tReturnDeletedObject: true,\n\t}\n\toptions := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: persistentvolume.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\tpanic(err) \n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = persistentvolume.StatusStrategy\n\n\treturn &REST{store}, &StatusREST{store: &statusStore}\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\ts1 := []string{\"a\", \"\", \"b\", \"\", \"c\", \"\"}\n\ts2 := []string{\"a\", \"\", \"b\", \"\", \"c\", \"\"}\n\ts3 := nonempty(s1)\n\ts4 := nonempty2(s2)\n\tfmt.Printf(\"%q\\n\", s3) \n\tfmt.Printf(\"%q\\n\", s4) \n}\n\n\n\nfunc nonempty2(strings []string) []string {\n\tout := strings[:0]\n\tfor _, s := range strings {\n\t\tif s != \"\" {\n\t\t\tout = append(out, s)\n\t\t}\n\t}\n\treturn out\n}\n\nfunc nonempty(strings []string) []string ", "output": "{\n\ti := 0\n\tfor _, s := range strings {\n\t\tif s != \"\" {\n\t\t\tstrings[i] = s\n\t\t\ti++\n\t\t}\n\t}\n\treturn strings[:i]\n}"} {"input": "package gzip\n\nimport (\n\t\"net/http\"\n\t\"path\"\n\n\t\"github.com/mholt/caddy/middleware\"\n)\n\n\ntype Filter interface {\n\tShouldCompress(*http.Request) bool\n}\n\n\nvar defaultExtensions = []string{\"\", \".txt\", \".htm\", \".html\", \".css\", \".php\", \".js\", \".json\", \".md\", \".xml\"}\n\n\nfunc DefaultExtFilter() ExtFilter {\n\tm := ExtFilter{Exts: make(Set)}\n\tfor _, extension := range defaultExtensions {\n\t\tm.Exts.Add(extension)\n\t}\n\treturn m\n}\n\n\ntype ExtFilter struct {\n\tExts Set\n}\n\n\nconst ExtWildCard = \"*\"\n\n\n\n\n\n\n\ntype PathFilter struct {\n\tIgnoredPaths Set\n}\n\n\n\n\nfunc (p PathFilter) ShouldCompress(r *http.Request) bool {\n\treturn !p.IgnoredPaths.ContainsFunc(func(value string) bool {\n\t\treturn middleware.Path(r.URL.Path).Matches(value)\n\t})\n}\n\n\ntype Set map[string]struct{}\n\n\nfunc (s Set) Add(value string) {\n\ts[value] = struct{}{}\n}\n\n\nfunc (s Set) Remove(value string) {\n\tdelete(s, value)\n}\n\n\nfunc (s Set) Contains(value string) bool {\n\t_, ok := s[value]\n\treturn ok\n}\n\n\n\n\nfunc (s Set) ContainsFunc(f func(string) bool) bool {\n\tfor k, _ := range s {\n\t\tif f(k) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (e ExtFilter) ShouldCompress(r *http.Request) bool ", "output": "{\n\text := path.Ext(r.URL.Path)\n\treturn e.Exts.Contains(ExtWildCard) || e.Exts.Contains(ext)\n}"} {"input": "package gch\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/Tondorf/tppdr/net\"\n)\n\n\n\ntype Anarchist struct {\n}\n\n\n\nfunc (a *Anarchist) Proc(in <-chan net.Key, out chan<- net.Key) ", "output": "{\n\tfmt.Println(\"ANARCHY!!!\")\n\tfor {\n\t\tb := <-in \n\t\tout <- b \n\t}\n}"} {"input": "package ttlru\n\ntype ttlHeap []*entry\n\nfunc (h ttlHeap) Len() int {\n\treturn len(h)\n}\n\nfunc (h ttlHeap) Less(i, j int) bool {\n\tif i == j || i < 0 || j < 0 {\n\t\treturn false\n\t}\n\treturn h[i].expires.Before(h[j].expires)\n}\n\nfunc (h ttlHeap) Swap(i, j int) {\n\tif i == j || i < 0 || j < 0 {\n\t\treturn\n\t}\n\th[i], h[j] = h[j], h[i]\n\th[i].index, h[j].index = i, j\n}\n\n\n\nfunc (h *ttlHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tif n == 0 {\n\t\treturn nil\n\t}\n\titem := old[n-1]\n\titem.index = -1 \n\t*h = old[0 : n-1]\n\treturn item\n}\n\nfunc (h *ttlHeap) Push(x interface{}) ", "output": "{\n\tn := len(*h)\n\titem := x.(*entry)\n\titem.index = n\n\t*h = append(*h, item)\n}"} {"input": "package apiv1\n\nimport (\n\t\"github.com/Unknwon/gowalker/modules/middleware\"\n)\n\n\n\nfunc Badge(ctx *middleware.Context) ", "output": "{\n\tctx.Redirect(\"https:img.shields.io/badge/Go%20Walker-API%20Documentation-green.svg?style=flat-square\")\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Player struct {\n\tID string\n\tName string\n\tHealth int\n\tHunger int\n\tCriticalHunger bool\n\tNextAction int\n\tDead bool\n}\n\n\nfunc NewPlayer(ID, name string) *Player {\n\treturn &Player{ID, name, 100, 0, false, 0, false}\n}\n\nfunc (p *Player) String() string {\n\treturn fmt.Sprintf(\"[%-12s](HP: %3d)\", p.Name, p.Health, p.Hunger)\n}\n\n\nfunc (p *Player) AddHealth(amount int) bool {\n\tp.Health += amount\n\tif p.Health > 100 {\n\t\tp.Health = 100\n\t}\n\tif p.Health <= 0 {\n\t\tp.Health = 0\n\t\tp.Dead = true\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\n\nfunc (p *Player) AddHunger(amount int) int ", "output": "{\n\tp.Hunger += amount\n\tif p.Hunger >= 100 {\n\t\tp.Hunger = 100\n\t\tif p.CriticalHunger {\n\t\t\treturn 2\n\t\t}\n\t\tp.CriticalHunger = true\n\t\treturn 1\n\t}\n\tif p.Hunger <= 0 {\n\t\tp.Hunger = 0\n\t}\n\treturn 0\n}"} {"input": "package process\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/weaveworks/scope/probe/tag\"\n\t\"github.com/weaveworks/scope/report\"\n)\n\n\nconst (\n\tPID = \"pid\"\n\tComm = \"comm\"\n\tPPID = \"ppid\"\n\tCmdline = \"cmdline\"\n\tThreads = \"threads\"\n)\n\n\ntype reporter struct {\n\tprocRoot string\n\tscope string\n}\n\n\nfunc NewReporter(procRoot, scope string) tag.Reporter {\n\treturn &reporter{\n\t\tprocRoot: procRoot,\n\t\tscope: scope,\n\t}\n}\n\n\n\n\nfunc (r *reporter) processTopology() (report.Topology, error) {\n\tt := report.NewTopology()\n\terr := Walk(r.procRoot, func(p *Process) {\n\t\tpidstr := strconv.Itoa(p.PID)\n\t\tnodeID := report.MakeProcessNodeID(r.scope, pidstr)\n\t\tt.NodeMetadatas[nodeID] = report.NodeMetadata{\n\t\t\tPID: pidstr,\n\t\t\tComm: p.Comm,\n\t\t\tCmdline: p.Cmdline,\n\t\t\tThreads: strconv.Itoa(p.Threads),\n\t\t}\n\t\tif p.PPID > 0 {\n\t\t\tt.NodeMetadatas[nodeID][PPID] = strconv.Itoa(p.PPID)\n\t\t}\n\t})\n\n\treturn t, err\n}\n\nfunc (r *reporter) Report() (report.Report, error) ", "output": "{\n\tresult := report.MakeReport()\n\tprocesses, err := r.processTopology()\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tresult.Process.Merge(processes)\n\treturn result, nil\n}"} {"input": "package chipmunk\n\nimport \"github.com/dataarts/chipmunk/vect\"\n\nconst (\n\terrorBias = 0.00179701029991443 \n)\n\ntype ConstraintCallback interface {\n\tCollisionPreSolve(constraint Constraint)\n\tCollisionPostSolve(constraint Constraint)\n}\n\ntype Constraint interface {\n\tConstraint() *BasicConstraint\n\tPreSolve()\n\tPostSolve()\n\tPreStep(dt vect.Float)\n\tApplyCachedImpulse(dt_coef vect.Float)\n\tApplyImpulse()\n\tImpulse() vect.Float\n}\n\ntype BasicConstraint struct {\n\tBodyA, BodyB *Body\n\tspace *Space\n\tMaxForce vect.Float\n\tErrorBias vect.Float\n\tMaxBias vect.Float\n\tCallbackHandler ConstraintCallback\n\tUserData Data\n}\n\nfunc NewConstraint(a, b *Body) BasicConstraint {\n\treturn BasicConstraint{BodyA: a, BodyB: b, MaxForce: Inf, MaxBias: Inf, ErrorBias: errorBias}\n}\n\nfunc (this *BasicConstraint) Constraint() *BasicConstraint {\n\treturn this\n}\n\nfunc (this *BasicConstraint) PreStep(dt vect.Float) {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) ApplyCachedImpulse(dt_coef vect.Float) {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) ApplyImpulse() {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) Impulse() vect.Float {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) PreSolve() {\n\tif this.CallbackHandler != nil {\n\t\tthis.CallbackHandler.CollisionPreSolve(this)\n\t}\n}\n\n\n\nfunc (this *BasicConstraint) PostSolve() ", "output": "{\n\tif this.CallbackHandler != nil {\n\t\tthis.CallbackHandler.CollisionPostSolve(this)\n\t}\n}"} {"input": "package image\n\nimport (\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/docker/cli/cli\"\n\t\"github.com/docker/cli/cli/command\"\n)\n\n\n\n\n\nfunc NewImageCommand(dockerCli *command.DockerCli) *cobra.Command ", "output": "{\n\tcmd := &cobra.Command{\n\t\tUse: \"image\",\n\t\tShort: \"Manage images\",\n\t\tArgs: cli.NoArgs,\n\t\tRunE: command.ShowHelp(dockerCli.Err()),\n\t}\n\tcmd.AddCommand(\n\t\tNewBuildCommand(dockerCli),\n\t\tNewHistoryCommand(dockerCli),\n\t\tNewImportCommand(dockerCli),\n\t\tNewLoadCommand(dockerCli),\n\t\tNewPullCommand(dockerCli),\n\t\tNewPushCommand(dockerCli),\n\t\tNewSaveCommand(dockerCli),\n\t\tNewTagCommand(dockerCli),\n\t\tnewListCommand(dockerCli),\n\t\tnewRemoveCommand(dockerCli),\n\t\tnewInspectCommand(dockerCli),\n\t\tNewPruneCommand(dockerCli),\n\t)\n\treturn cmd\n}"} {"input": "package console\n\nimport (\n\t\"os\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\nimport \"C\"\n\nconst (\n\tcmdTcGet = unix.TCGETS\n\tcmdTcSet = unix.TCSETS\n)\n\n\nfunc ptsname(f *os.File) (string, error) {\n\tptspath, err := C.ptsname(C.int(f.Fd()))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn C.GoString(ptspath), nil\n}\n\n\n\n\n\nfunc unlockpt(f *os.File) error ", "output": "{\n\tif _, err := C.grantpt(C.int(f.Fd())); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package graph_test\n\nimport (\n\t\"testing\"\n\t\"github.com/filwisher/algo/graph\"\n\t\"github.com/filwisher/algo/set\"\n)\n\n\n\nfunc TestGraph(t *testing.T) ", "output": "{\n\n\tconn := 1\n\tg := graph.NewGraph()\n\tfor i := 2; i < 6; i++ {\n\t\tg.AddEdge(conn, i)\n\t}\n\n\ts := set.NewSet()\n\tfor e := range g.Adjacent(conn) {\n\t\ts.Add(e)\t\n\t}\n\tfor i := 2; i < 6; i++ {\n\t\tif !s.Contains(i) {\n\t\t\tt.Errorf(\"graph does not contain edge between %d and %d\", conn, i)\n\t\t}\n\t\tfor e := range g.Adjacent(i) {\n\t\t\tif e != conn {\n\t\t\t\tt.Errorf(\"edges are not bidirectional\")\t\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package gsh\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"gopkg.in/pipe.v2\"\n)\n\ntype HeadCmd struct {\n\tChars int\n\tLines int\n}\n\n\n\nfunc (cmd *HeadCmd) Name() string {\n\treturn \"head\"\n}\n\nfunc (cmd *HeadCmd) Run(s *pipe.State, argv []string) error {\n\tfs := cmd.Flags()\n\terr := fs.Parse(argv)\n\tif err != nil {\n\t\treturn err\n\t}\n\targs := fs.Args()\n\tif len(args) > 0 {\n\t\tfor _, fname := range args {\n\t\t\tfh, err := os.Open(fname)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%s 1: %s\", cmd.Name(), err)\n\t\t\t}\n\t\t\t_, err = io.Copy(s.Stdout, fh)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%s 2: %s\", cmd.Name(), err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\tif cmd.Chars >= 0 {\n\t\t_, err = io.CopyN(s.Stdout, s.Stdin, int64(cmd.Chars))\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: %s\", cmd.Name(), err)\n\t}\n\treturn nil\n}\n\nfunc Head(argv ...string) pipe.Pipe {\n\tcmd := HeadCmd{}\n\treturn pipe.TaskFunc(func(s *pipe.State) error {\n\t\treturn cmd.Run(s, argv)\n\t})\n}\n\nfunc (cmd *HeadCmd) Flags() *flag.FlagSet ", "output": "{\n\tf := flag.NewFlagSet(cmd.Name(), flag.ExitOnError)\n\tf.IntVar(&cmd.Chars, \"c\", -1, \"Take first N characters\")\n\tf.IntVar(&cmd.Chars, \"n\", 10, \"Take first N lines\")\n\treturn f\n}"} {"input": "package main\n\nimport (\n \"container/list\"\n \"log\"\n \"sync\"\n \"time\"\n)\n\ntype ThreadPool struct {\n size, running int\n list *list.List\n m sync.Mutex\n}\n\nfunc NewThreadPool(size int) *ThreadPool {\n tp := &ThreadPool{\n size: size,\n list: list.New(),\n }\n return tp\n}\n\nfunc (tp *ThreadPool) onStop() {\n tp.m.Lock()\n tp.running--\n tp.m.Unlock()\n tp.run()\n}\n\n\n\nfunc (tp *ThreadPool) Submit(f func()) {\n tp.list.PushBack(f)\n tp.run()\n}\n\nfunc main() {\n var wg sync.WaitGroup\n tp := NewThreadPool(4)\n for i := 0; i < 16; i++ {\n wg.Add(1)\n (func(id int) {\n log.Printf(\"Subtmitted job %d\", id)\n tp.Submit(func() {\n time.Sleep(3 * time.Second)\n log.Printf(\"Hello from job %d\", id)\n wg.Done()\n })\n })(i)\n }\n wg.Wait()\n}\n\nfunc (tp *ThreadPool) run() ", "output": "{\n tp.m.Lock()\n defer tp.m.Unlock()\n if tp.list.Len() > 0 && tp.running < tp.size {\n f := tp.list.Remove(tp.list.Front()).(func())\n tp.running++\n go func() {\n f()\n tp.onStop()\n }()\n }\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\n\n\n\ntype MsgFilterClear struct{}\n\n\n\n\n\n\n\nfunc (msg *MsgFilterClear) MsgEncode(w io.Writer, pver uint32) error {\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filterclear message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterClear.MsgEncode\", str)\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (msg *MsgFilterClear) Command() string {\n\treturn CmdFilterClear\n}\n\n\n\nfunc (msg *MsgFilterClear) MaxPayloadLength(pver uint32) uint32 {\n\treturn 0\n}\n\n\n\nfunc NewMsgFilterClear() *MsgFilterClear {\n\treturn &MsgFilterClear{}\n}\n\nfunc (msg *MsgFilterClear) MsgDecode(r io.Reader, pver uint32) error ", "output": "{\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filterclear message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterClear.MsgDecode\", str)\n\t}\n\n\treturn nil\n}"} {"input": "package initializer\n\nimport (\n\t\"k8s.io/apiserver/pkg/admission\"\n\t\"k8s.io/apiserver/pkg/authorization/authorizer\"\n\t\"k8s.io/client-go/informers\"\n\t\"k8s.io/client-go/kubernetes\"\n\t\"k8s.io/component-base/featuregate\"\n)\n\ntype pluginInitializer struct {\n\texternalClient kubernetes.Interface\n\texternalInformers informers.SharedInformerFactory\n\tauthorizer authorizer.Authorizer\n\tfeatureGates featuregate.FeatureGate\n}\n\n\n\n\n\n\n\n\nfunc (i pluginInitializer) Initialize(plugin admission.Interface) {\n\tif wants, ok := plugin.(WantsFeatures); ok {\n\t\twants.InspectFeatureGates(i.featureGates)\n\t}\n\n\tif wants, ok := plugin.(WantsExternalKubeClientSet); ok {\n\t\twants.SetExternalKubeClientSet(i.externalClient)\n\t}\n\n\tif wants, ok := plugin.(WantsExternalKubeInformerFactory); ok {\n\t\twants.SetExternalKubeInformerFactory(i.externalInformers)\n\t}\n\n\tif wants, ok := plugin.(WantsAuthorizer); ok {\n\t\twants.SetAuthorizer(i.authorizer)\n\t}\n}\n\nvar _ admission.PluginInitializer = pluginInitializer{}\n\nfunc New(\n\textClientset kubernetes.Interface,\n\textInformers informers.SharedInformerFactory,\n\tauthz authorizer.Authorizer,\n\tfeatureGates featuregate.FeatureGate,\n) pluginInitializer ", "output": "{\n\treturn pluginInitializer{\n\t\texternalClient: extClientset,\n\t\texternalInformers: extInformers,\n\t\tauthorizer: authz,\n\t\tfeatureGates: featureGates,\n\t}\n}"} {"input": "package daemon\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/docker/docker/nat\"\n\t\"github.com/docker/docker/runconfig\"\n)\n\nfunc migratePortMappings(config *runconfig.Config, hostConfig *runconfig.HostConfig) error {\n\tif config.PortSpecs != nil {\n\t\tports, bindings, err := nat.ParsePortSpecs(config.PortSpecs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tconfig.PortSpecs = nil\n\t\tif len(bindings) > 0 {\n\t\t\tif hostConfig == nil {\n\t\t\t\thostConfig = &runconfig.HostConfig{}\n\t\t\t}\n\t\t\thostConfig.PortBindings = bindings\n\t\t}\n\n\t\tif config.ExposedPorts == nil {\n\t\t\tconfig.ExposedPorts = make(nat.PortSet, len(ports))\n\t\t}\n\t\tfor k, v := range ports {\n\t\t\tconfig.ExposedPorts[k] = v\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\nfunc mergeLxcConfIntoOptions(hostConfig *runconfig.HostConfig) ([]string, error) ", "output": "{\n\tif hostConfig == nil {\n\t\treturn nil, nil\n\t}\n\n\tout := []string{}\n\n\tif lxcConf := hostConfig.LxcConf; lxcConf != nil {\n\t\tlxSlice := lxcConf.Slice()\n\t\tfor _, pair := range lxSlice {\n\t\t\tif !strings.Contains(pair.Key, \".\") {\n\t\t\t\treturn nil, errors.New(\"Illegal Key passed into LXC Configurations\")\n\t\t\t}\n\t\t\tparts := strings.SplitN(pair.Key, \".\", 2)\n\t\t\tout = append(out, fmt.Sprintf(\"%s=%s\", parts[1], pair.Value))\n\t\t}\n\t}\n\n\treturn out, nil\n}"} {"input": "package ipamutils\n\nimport (\n\t\"net\"\n\n\t\"github.com/docker/libnetwork/types\"\n)\n\n\n\n\n\n\n\n\n\nfunc FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error) {\n\treturn nil, types.NotImplementedErrorf(\"not supported on windows\")\n}\n\nfunc ElectInterfaceAddresses(name string) (*net.IPNet, []*net.IPNet, error) ", "output": "{\n\treturn nil, nil, types.NotImplementedErrorf(\"not supported on windows\")\n}"} {"input": "package input\n\nimport (\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com/elastic/beats/libbeat/logp\"\n)\n\ntype FileStateOS struct {\n\tInode uint64 `json:\"inode,omitempty\"`\n\tDevice uint64 `json:\"device,omitempty\"`\n}\n\n\n\n\n\nfunc (fs *FileStateOS) IsSame(state *FileStateOS) bool {\n\treturn fs.Inode == state.Inode && fs.Device == state.Device\n}\n\n\nfunc SafeFileRotate(path, tempfile string) error {\n\tif e := os.Rename(tempfile, path); e != nil {\n\t\tlogp.Err(\"Rotate error: %s\", e)\n\t\treturn e\n\t}\n\treturn nil\n}\n\n\nfunc ReadOpen(path string) (*os.File, error) {\n\n\tflag := os.O_RDONLY\n\tvar perm os.FileMode = 0\n\n\treturn os.OpenFile(path, flag, perm)\n}\n\nfunc GetOSFileState(info *os.FileInfo) *FileStateOS ", "output": "{\n\n\tstat := (*(info)).Sys().(*syscall.Stat_t)\n\n\tfileState := &FileStateOS{\n\t\tInode: uint64(stat.Ino),\n\t\tDevice: uint64(stat.Dev),\n\t}\n\n\treturn fileState\n}"} {"input": "package raft\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\nfunc diffu(a, b string) string {\n\tif a == b {\n\t\treturn \"\"\n\t}\n\taname, bname := mustTemp(\"base\", a), mustTemp(\"other\", b)\n\tdefer os.Remove(aname)\n\tdefer os.Remove(bname)\n\tcmd := exec.Command(\"diff\", \"-u\", aname, bname)\n\tbuf, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tif _, ok := err.(*exec.ExitError); ok {\n\t\t\treturn string(buf)\n\t\t}\n\t\tpanic(err)\n\t}\n\treturn string(buf)\n}\n\nfunc mustTemp(pre, body string) string {\n\tf, err := os.CreateTemp(\"\", pre)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, err = io.Copy(f, strings.NewReader(body))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tf.Close()\n\treturn f.Name()\n}\n\n\n\nfunc ltoa(l *raftLog) string ", "output": "{\n\ts := fmt.Sprintf(\"committed: %d\\n\", l.committed)\n\ts += fmt.Sprintf(\"applied: %d\\n\", l.applied)\n\tfor i, e := range l.allEntries() {\n\t\ts += fmt.Sprintf(\"#%d: %+v\\n\", i, e)\n\t}\n\treturn s\n}"} {"input": "package builder\n\nimport (\n\t\"sync\"\n\n\t\"github.com/rikvdh/ci/lib/config\"\n)\n\ntype jobCounter struct {\n\tmu sync.RWMutex\n\tjobCounter uint\n\tjobLimit uint\n\teventCh chan uint\n}\n\nfunc newJobCounter() *jobCounter {\n\treturn &jobCounter{\n\t\tjobCounter: 0,\n\t\tjobLimit: config.Get().ConcurrentBuilds,\n\t\teventCh: make(chan uint),\n\t}\n}\n\nfunc (j *jobCounter) Increment() {\n\tj.mu.Lock()\n\tj.jobCounter++\n\tj.mu.Unlock()\n\tj.publishEvent()\n}\n\n\n\nfunc (j *jobCounter) CanStartJob() bool {\n\tj.mu.RLock()\n\tdefer j.mu.RUnlock()\n\treturn (j.jobCounter < j.jobLimit)\n}\n\nfunc (j *jobCounter) publishEvent() {\n\tj.mu.RLock()\n\tj.eventCh <- j.jobCounter\n\tj.mu.RUnlock()\n}\n\nfunc (j *jobCounter) GetEventChannel() <-chan uint {\n\tj.mu.RLock()\n\tdefer j.mu.RUnlock()\n\treturn j.eventCh\n}\n\nfunc (j *jobCounter) Decrement() ", "output": "{\n\tj.mu.Lock()\n\tj.jobCounter--\n\tj.mu.Unlock()\n\tj.publishEvent()\n}"} {"input": "package cvv\n\nimport (\n\t\"net/http\"\n)\n\n\n\nfunc init() ", "output": "{\n\thttp.HandleFunc(\"/api/hw\", handleHello)\n\thttp.HandleFunc(\"/api/hw2\", handleHello2)\n\n\n\thttp.HandleFunc(\"/api/user/porId\", HandleQryUserPorId)\n\n\thttp.HandleFunc(\"/api/user/signupWithPassword\", HandleUserSignupWithPassword)\n\thttp.HandleFunc(\"/api/user/loginWithPassword\", HandleUserLoginWithPassword)\n\thttp.HandleFunc(\"/api/user/logout\", HandleUserLogout)\n\n\n\n}"} {"input": "package middleware\n\nimport \"gopkg.in/macaron.v1\"\n\n\n\nfunc SetMiddlewares(m *macaron.Macaron) ", "output": "{\n\n\tm.Use(macaron.Recovery())\n}"} {"input": "package lang\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"syscall\"\n)\n\n\n\nfunc osSyscalls(cmd *exec.Cmd) {\n\tcmd.SysProcAttr = &syscall.SysProcAttr{\n\t\tCtty: int(os.Stdout.Fd()),\n\t}\n}\n\nfunc getCmdTokens(p *Process) (exe string, parameters []string, err error) ", "output": "{\n\texe, err = p.Parameters.String(0)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tparameters = p.Parameters.StringArray()[1:]\n\n\treturn\n}"} {"input": "package stats_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/montanaflynn/stats\"\n)\n\nfunc ExampleSigmoid() {\n\ts, _ := stats.Sigmoid([]float64{3.0, 1.0, 2.1})\n\tfmt.Println(s)\n}\n\n\n\nfunc TestSigmoid(t *testing.T) {\n\tsm, err := stats.Sigmoid([]float64{-0.54761371, 17.04850603, 4.86054302})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\ta := 0.3664182235138545\n\tif sm[0] != a {\n\t\tt.Errorf(\"%v != %v\", sm[0], a)\n\t}\n\n\ta = 0.9999999605608187\n\tif sm[1] != a {\n\t\tt.Errorf(\"%v != %v\", sm[1], a)\n\t}\n\n\ta = 0.9923132671908277\n\tif sm[2] != a {\n\t\tt.Errorf(\"%v != %v\", sm[2], a)\n\t}\n}\n\nfunc TestSigmoidEmptyInput(t *testing.T) ", "output": "{\n\t_, err := stats.Sigmoid([]float64{})\n\tif err != stats.EmptyInputErr {\n\t\tt.Errorf(\"Should have returned empty input error\")\n\t}\n}"} {"input": "package markdown\n\nimport (\n\t\"strings\"\n)\n\nfunc newEscaper(chars ...string) *strings.Replacer {\n\treplacements := []string{}\n\n\tfor _, char := range chars {\n\t\treplacements = append(replacements, char, \"\\\\\"+char)\n\t}\n\n\treturn strings.NewReplacer(replacements...)\n}\n\nvar escaper = newEscaper(\n\t\"*\", \"_\", \"~\", \n\t\"`\", \n\t\"<\", \">\", \"@\", \"#\", \n\t\":\", \n)\n\n\n\n\nfunc Escape(s string) string ", "output": "{\n\treturn escaper.Replace(s)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSOpsWorksStack_ElasticIp struct {\n\n\tIp string `json:\"Ip,omitempty\"`\n\n\tName string `json:\"Name,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) AWSCloudFormationType() string {\n\treturn \"AWS::OpsWorks::Stack.ElasticIp\"\n}\n\n\n\n\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSOpsWorksStack_ElasticIp) DependsOn() []string ", "output": "{\n\treturn r._dependsOn\n}"} {"input": "package blobstore\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync\"\n)\n\ntype localStore struct {\n\tsync.Mutex\n\troot string\n}\n\n\nfunc NewLocalStore(root string) (Store, error) {\n\treturn newLocalStore(root)\n}\n\n\n\nfunc (ls *localStore) blobFilename(digest string) string {\n\treturn filepath.Join(ls.blobDirname(digest), \"blob\")\n}\n\nfunc (ls *localStore) blobInfoFilename(digest string) string {\n\treturn filepath.Join(ls.blobDirname(digest), \"info.json\")\n}\n\n\n\nfunc newLocalStore(root string) (*localStore, error) {\n\tls := &localStore{root: root}\n\n\tblobsDirname := ls.blobDirname(\"\")\n\tif err := os.MkdirAll(blobsDirname, os.FileMode(0755)); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create local blob store directory %q: %s\", blobsDirname, err)\n\t}\n\n\treturn ls, nil\n}\n\nfunc (ls *localStore) blobDirname(digest string) string ", "output": "{\n\treturn filepath.Join(ls.root, \"blobs\", digest)\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"os/exec\"\n)\n\nfunc split(x int) (a, b int){\n a := 1\n b := 2\n return\n}\n\n\n\n\nfunc main(){\n \n fmt.Println(\"Simple Shell\")\n fmt.Println(\"---------------------\")\n \n execute() \n fmt.Println(split(5))\n}\n\nfunc execute() ", "output": "{\n out, err := exec.Command(\"pwd\").Output()\n \n if err != nil {\n fmt.Printf(\"%s\", err)\n }\n fmt.Println(\"Command Successfully Executed\")\n fmt.Println(out)\n}"} {"input": "package dosingdecision\n\nimport (\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tRecommendedBasalDurationMaximum = 86400000\n\tRecommendedBasalDurationMinimum = 0\n\tRecommendedBasalRateMaximum = 100\n\tRecommendedBasalRateMinimum = 0\n)\n\ntype RecommendedBasal struct {\n\tRate *float64 `json:\"rate,omitempty\" bson:\"rate,omitempty\"`\n\tDuration *int `json:\"duration,omitempty\" bson:\"duration,omitempty\"`\n}\n\nfunc ParseRecommendedBasal(parser structure.ObjectParser) *RecommendedBasal {\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewRecommendedBasal()\n\tparser.Parse(datum)\n\treturn datum\n}\n\nfunc NewRecommendedBasal() *RecommendedBasal {\n\treturn &RecommendedBasal{}\n}\n\nfunc (r *RecommendedBasal) Parse(parser structure.ObjectParser) {\n\tr.Rate = parser.Float64(\"rate\")\n\tr.Duration = parser.Int(\"duration\")\n}\n\n\n\nfunc (r *RecommendedBasal) Validate(validator structure.Validator) ", "output": "{\n\tvalidator.Float64(\"rate\", r.Rate).Exists().InRange(RecommendedBasalRateMinimum, RecommendedBasalRateMaximum)\n\tvalidator.Int(\"duration\", r.Duration).InRange(RecommendedBasalDurationMinimum, RecommendedBasalDurationMaximum)\n}"} {"input": "package logs\n\nconst (\n\tErrorLevel = iota\n\tWarnLevel\n\tInfoLevel\n\tDebugLevel\n)\n\ntype Level uint32\n\nfunc (l Level) EQ(lv Level) bool {\n\tif l == lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) LTE(lv Level) bool {\n\tif l <= lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) LT(lv Level) bool {\n\tif l < lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) GTE(lv Level) bool {\n\tif l >= lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) GT(lv Level) bool {\n\tif l > lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) Color() int {\n\tvar levelColor int\n\tswitch l {\n\tcase DebugLevel:\n\t\tlevelColor = 32\n\tcase InfoLevel:\n\t\tlevelColor = 36\n\tcase WarnLevel:\n\t\tlevelColor = 33\n\tcase ErrorLevel:\n\t\tlevelColor = 31\n\tdefault:\n\t\tlevelColor = 0\n\t}\n\treturn levelColor\n}\n\n\n\nfunc (l Level) String() string ", "output": "{\n\tswitch l {\n\tcase DebugLevel:\n\t\treturn \"DEBU\"\n\tcase InfoLevel:\n\t\treturn \"INFO\"\n\tcase WarnLevel:\n\t\treturn \"WARN\"\n\tcase ErrorLevel:\n\t\treturn \"ERRO\"\n\t}\n\treturn \" \"\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n)\n\nfunc main() {\n\ttests := []int{234, 4421}\n\n\tfor _, test := range tests {\n\t\tlog.Printf(\"subtractProductAndSum(%d) = %d\\n\", test, subtractProductAndSum(test))\n\t}\n}\n\nfunc subtractProductAndSum(n int) int {\n\tnDigits := getDecimalDigits(n)\n \n\n \n \n\n \n \n\n\treturn (getProduct(nDigits) - getTotal(nDigits))\n}\n\nfunc getDecimalDigits(n int) []int {\n\tres := []int{}\n\n\trem := n % 10\n\tn = n / 10\n\tres = append(res, rem)\n\n\tfor n > 0 {\n\t\trem = n % 10\n\t\tn = n / 10\n\n\t\tres = append(res, rem)\n\t}\n\n\treturn res\n}\n\n\n\nfunc getProduct(nums []int) int {\n\tvar prod int\n\n if len(nums) > 0 {\n prod = 1\n }\n\n\tfor _, n := range nums {\n\t\tprod *= n\n\t}\n\n\treturn prod\n}\n\nfunc getTotal(nums []int) int ", "output": "{\n\tvar tot int\n\n\tfor _, n := range nums {\n\t\ttot += n\n\t}\n\n\treturn tot\n}"} {"input": "package nat\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n\n\t\"github.com/cilium/cilium/pkg/byteorder\"\n\t\"github.com/cilium/cilium/pkg/tuple\"\n\t\"github.com/cilium/cilium/pkg/types\"\n)\n\n\n\n\ntype NatEntry4 struct {\n\tCreated uint64 `align:\"created\"`\n\tHostLocal uint64 `align:\"host_local\"`\n\tPad1 uint64 `align:\"pad1\"`\n\tPad2 uint64 `align:\"pad2\"`\n\tAddr types.IPv4 `align:\"to_saddr\"`\n\tPort uint16 `align:\"to_sport\"`\n}\n\n\nconst SizeofNatEntry4 = int(unsafe.Sizeof(NatEntry4{}))\n\n\n\n\n\nfunc (n *NatEntry4) String() string {\n\treturn fmt.Sprintf(\"Addr=%s Port=%d Created=%d HostLocal=%d\\n\",\n\t\tn.Addr,\n\t\tn.Port,\n\t\tn.Created,\n\t\tn.HostLocal)\n}\n\n\nfunc (n *NatEntry4) Dump(key NatKey, start uint64) string {\n\tvar which string\n\n\tif key.GetFlags()&tuple.TUPLE_F_IN != 0 {\n\t\twhich = \"DST\"\n\t} else {\n\t\twhich = \"SRC\"\n\t}\n\treturn fmt.Sprintf(\"XLATE_%s %s:%d Created=%s HostLocal=%d\\n\",\n\t\twhich,\n\t\tn.Addr,\n\t\tn.Port,\n\t\tNatDumpCreated(start, n.Created),\n\t\tn.HostLocal)\n}\n\n\nfunc (n *NatEntry4) ToHost() NatEntry {\n\tx := *n\n\tx.Port = byteorder.NetworkToHost16(n.Port)\n\treturn &x\n}\n\nfunc (n *NatEntry4) GetValuePtr() unsafe.Pointer ", "output": "{ return unsafe.Pointer(n) }"} {"input": "package blocks\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\tmh \"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash\"\n\tu \"github.com/ipfs/go-ipfs/util\"\n)\n\n\ntype Block struct {\n\tMultihash mh.Multihash\n\tData []byte\n}\n\n\nfunc NewBlock(data []byte) *Block {\n\treturn &Block{Data: data, Multihash: u.Hash(data)}\n}\n\n\n\n\nfunc NewBlockWithHash(data []byte, h mh.Multihash) (*Block, error) {\n\tif u.Debug {\n\t\tchk := u.Hash(data)\n\t\tif string(chk) != string(h) {\n\t\t\treturn nil, errors.New(\"Data did not match given hash!\")\n\t\t}\n\t}\n\treturn &Block{Data: data, Multihash: h}, nil\n}\n\n\n\n\nfunc (b *Block) String() string {\n\treturn fmt.Sprintf(\"[Block %s]\", b.Key())\n}\n\nfunc (b *Block) Loggable() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"block\": b.Key().String(),\n\t}\n}\n\nfunc (b *Block) Key() u.Key ", "output": "{\n\treturn u.Key(b.Multihash)\n}"} {"input": "package utub\n\nimport (\n\t\"strings\"\n\n\t\"gopkg.in/olebedev/go-duktape.v2\"\n)\n\ntype duktapeJSEngine struct{}\n\n\n\nfunc (js duktapeJSEngine) Available() bool {\n\treturn true\n}\n\nfunc (js duktapeJSEngine) Exec(code string) (string, error) {\n\tctx := duktape.New()\n\tdefer ctx.DestroyHeap()\n\n\terr := ctx.PevalString(code)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn ctx.SafeToString(-1), nil\n}\n\nfunc (js duktapeJSEngine) sanitizeJSPlayerCode(code string) string {\n\tcode = strings.Replace(code, `(?=:|,|]|}|$)`, `(?=:|,|\\]|\\}|$)`, 1)\n\treturn code\n}\n\nfunc (js duktapeJSEngine) Name() string ", "output": "{\n\treturn \"Duktape\"\n}"} {"input": "package internalversion\n\nimport (\n\t\"github.com/openshift/origin/pkg/template/api\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n)\n\n\n\ntype TemplateListerExpansion interface {\n\tGetByUID(uid string) (*api.Template, error)\n}\n\n\n\ntype TemplateNamespaceListerExpansion interface{}\n\n\n\nfunc (s templateLister) GetByUID(uid string) (*api.Template, error) ", "output": "{\n\ttemplates, err := s.indexer.ByIndex(api.TemplateUIDIndex, uid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(templates) == 0 {\n\t\treturn nil, errors.NewNotFound(api.Resource(\"template\"), uid)\n\t}\n\treturn templates[0].(*api.Template), nil\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListLocalPeeringGatewaysRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tVcnId *string `mandatory:\"false\" contributesTo:\"query\" name:\"vcnId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListLocalPeeringGatewaysRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListLocalPeeringGatewaysRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request ListLocalPeeringGatewaysRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype ListLocalPeeringGatewaysResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []LocalPeeringGateway `presentIn:\"body\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ListLocalPeeringGatewaysResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListLocalPeeringGatewaysResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListLocalPeeringGatewaysRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package version\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype Command struct {\n\tName string\n\tW io.Writer\n\tWErr io.Writer\n\tAppName string\n\tAppVersion string\n\tGitCommit string\n}\n\n\nfunc (c *Command) Run(args []string) (int, error) {\n\tfmt.Fprintln(c.W, c.AppName, c.AppVersion, c.GitCommit)\n\treturn 0, nil\n}\n\n\nfunc (c *Command) Key() string {\n\treturn c.Name\n}\n\n\n\n\n\n\nfunc (c *Command) Description() string {\n\treturn \"Print the version.\"\n}\n\nfunc (c *Command) Aliases() map[string]struct{} ", "output": "{\n\treturn map[string]struct{}{\n\t\t\"version\": struct{}{},\n\t}\n}"} {"input": "package relay\n\nimport (\n\t\"encoding/gob\"\n\t\"encoding/json\"\n\t\"io\"\n)\n\n\n\n\ntype Serializer interface {\n\tContentType() string\n\tRelayEncode(io.Writer, interface{}) error\n\tRelayDecode(io.Reader, interface{}) error\n}\n\n\ntype GOBSerializer struct{}\n\n\nfunc (*GOBSerializer) RelayEncode(w io.Writer, e interface{}) error {\n\tenc := gob.NewEncoder(w)\n\treturn enc.Encode(e)\n}\nfunc (*GOBSerializer) RelayDecode(r io.Reader, o interface{}) error {\n\tdec := gob.NewDecoder(r)\n\treturn dec.Decode(o)\n}\n\n\ntype JSONSerializer struct{}\n\nfunc (*JSONSerializer) ContentType() string {\n\treturn \"text/json\"\n}\n\nfunc (*JSONSerializer) RelayEncode(w io.Writer, e interface{}) error {\n\tenc := json.NewEncoder(w)\n\treturn enc.Encode(e)\n}\n\nfunc (*JSONSerializer) RelayDecode(r io.Reader, o interface{}) error {\n\tdec := json.NewDecoder(r)\n\treturn dec.Decode(o)\n}\n\nfunc (*GOBSerializer) ContentType() string ", "output": "{\n\treturn \"binary/gob\"\n}"} {"input": "package siesta\n\nimport \"testing\"\n\nvar emptyHeartbeatRequestBytes = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}\nvar goodHeartbeatRequestBytes = []byte{0x00, 0x05, 'g', 'r', 'o', 'u', 'p', 0x00, 0x00, 0x00, 0x03, 0x00, 0x06, 'm', 'e', 'm', 'b', 'e', 'r'}\n\nvar errorHeartbeatResponseBytes = []byte{0x00, 25}\nvar goodHeartbeatResponseBytes = []byte{0x00, 0x00}\n\nfunc TestHeartbeatRequest(t *testing.T) {\n\temptyHeartbeatRequest := new(HeartbeatRequest)\n\ttestRequest(t, emptyHeartbeatRequest, emptyHeartbeatRequestBytes)\n\n\tgoodHeartbeatRequest := new(HeartbeatRequest)\n\tgoodHeartbeatRequest.GroupID = \"group\"\n\tgoodHeartbeatRequest.GenerationID = 3\n\tgoodHeartbeatRequest.MemberID = \"member\"\n\ttestRequest(t, goodHeartbeatRequest, goodHeartbeatRequestBytes)\n}\n\n\n\nfunc TestHeartbeatResponse(t *testing.T) ", "output": "{\n\terrorHeartbeatResponse := new(HeartbeatResponse)\n\tdecode(t, errorHeartbeatResponse, errorHeartbeatResponseBytes)\n\tassert(t, errorHeartbeatResponse.Error, ErrUnknownMemberID)\n\n\tgoodHeartbeatResponse := new(HeartbeatResponse)\n\tdecode(t, goodHeartbeatResponse, goodHeartbeatResponseBytes)\n\tassert(t, goodHeartbeatResponse.Error, ErrNoError)\n}"} {"input": "package minecraft\n\nimport (\n\t\"io\"\n\t\"github.com/LilyPad/GoLilyPad/packet\"\n)\n\ntype packetServerPluginMessageCodec17 struct {\n\n}\n\nfunc (this *packetServerPluginMessageCodec17) Decode(reader io.Reader) (decode packet.Packet, err error) {\n\tpacketServerPluginMessage := new(PacketServerPluginMessage)\n\tpacketServerPluginMessage.Channel, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\tdataLength, err := packet.ReadUint16(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\tpacketServerPluginMessage.Data = make([]byte, dataLength)\n\t_, err = reader.Read(packetServerPluginMessage.Data)\n\tif err != nil {\n\t\treturn\n\t}\n\tdecode = packetServerPluginMessage\n\treturn\n}\n\n\n\nfunc (this *packetServerPluginMessageCodec17) Encode(writer io.Writer, encode packet.Packet) (err error) ", "output": "{\n\tpacketServerPluginMessage := encode.(*PacketServerPluginMessage)\n\terr = packet.WriteString(writer, packetServerPluginMessage.Channel)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = packet.WriteUint16(writer, uint16(len(packetServerPluginMessage.Data)))\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = writer.Write(packetServerPluginMessage.Data)\n\treturn\n}"} {"input": "package ctxhttp\n\nimport (\n\t\"net/http\"\n\n\t\"fmt\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\n\n\n\ntype Handler interface {\n\tServeHTTPContext(context.Context, http.ResponseWriter, *http.Request) error\n}\n\n\n\ntype HandlerFunc func(context.Context, http.ResponseWriter, *http.Request) error\n\n\n\nfunc (h HandlerFunc) ServeHTTPContext(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\treturn h(ctx, rw, req)\n}\n\nvar _ http.Handler = (*Adapter)(nil)\n\n\n\ntype Adapter struct {\n\tCtx context.Context \n\tHandler Handler \n\tErrorFunc AdapterErrFunc \n}\n\n\n\n\n\n\nfunc NewAdapter(ctx context.Context, h Handler) *Adapter {\n\treturn &Adapter{\n\t\tCtx: ctx,\n\t\tHandler: h,\n\t\tErrorFunc: DefaultAdapterErrFunc,\n\t}\n}\n\n\ntype AdapterErrFunc func(http.ResponseWriter, *http.Request, error)\n\n\n\n\nvar DefaultAdapterErrFunc AdapterErrFunc = defaultAdapterErrFunc\n\nfunc defaultAdapterErrFunc(rw http.ResponseWriter, req *http.Request, err error) {\n\tcode := http.StatusBadRequest\n\thttp.Error(rw, fmt.Sprintf(\n\t\t\"%s\\nApp Error: %s\",\n\t\thttp.StatusText(code),\n\t\terr,\n\t), code)\n}\n\nfunc (ca *Adapter) ServeHTTP(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\tif err := ca.Handler.ServeHTTPContext(ca.Ctx, rw, req); err != nil {\n\t\tca.ErrorFunc(rw, req, err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/mkrautz/objc\"\n\t. \"github.com/mkrautz/objc/AppKit\"\n\t\"log\"\n\t\"runtime\"\n)\n\nfunc init() {\n\tdefer runtime.LockOSThread()\n\n\tc := objc.NewClass(AppDelegate{})\n\tc.AddMethod(\"applicationDidFinishLaunching:\", (*AppDelegate).ApplicationDidFinishLaunching)\n\tobjc.RegisterClass(c)\n}\n\ntype AppDelegate struct {\n\tobjc.Object `objc:\"GOAppDelegate : NSObject\"`\n\tWindow objc.Object `objc:\"IBOutlet\"`\n}\n\n\n\nfunc main() {\n\tNSApplicationMain()\n}\n\nfunc (delegate *AppDelegate) ApplicationDidFinishLaunching(notification objc.Object) ", "output": "{\n\tlog.Printf(\"applicationDidFinishLaunching! %v\", notification)\n\n\tlog.Printf(\"Object: %v\", delegate.Object)\n\tlog.Printf(\"Window: %v\", delegate.Window)\n\n\tmainMenu := NSSharedApplication().MainMenu()\n\tlog.Printf(\"%v\", mainMenu)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\nconst (\n\tFileType_File = 1\n\tFileType_Directory = 2\n)\n\nfunc IfString(condition bool, trueVal, falseVal string) string {\n\tif condition {\n\t\treturn trueVal\n\t}\n\treturn falseVal\n}\n\nfunc IfInt(condition bool, trueVal, falseVal int) int {\n\tif condition {\n\t\treturn trueVal\n\t}\n\treturn falseVal\n}\n\n\nfunc ExpandString(s string, data map[string]string) string {\n\treturn os.Expand(s, func(p string) string {\n\t\tv, _ := data[p]\n\t\treturn v\n\t})\n}\n\n\nfunc CreateDir(dir string, mode os.FileMode) error {\n\t_, err := os.Stat(dir)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn os.MkdirAll(dir, mode)\n\t\t}\n\t}\n\treturn err\n}\n\nfunc CopyFile(src, dest string, mode os.FileMode) error {\n\tdata, err := ioutil.ReadFile(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(dest, data, mode)\n}\n\n\n\n\nfunc GetFileType(path string) (fileType int, err error) ", "output": "{\n\tvar fi os.FileInfo\n\n\tfi, err = os.Stat(path)\n\tif err == nil {\n\t\tfileType = IfInt(fi.IsDir(), FileType_Directory, FileType_File)\n\t} else if os.IsNotExist(err) {\n\t\terr = fmt.Errorf(\"can not find directory or file: %s\", path)\n\t}\n\treturn\n}"} {"input": "package sidekick\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\ntype stringSlice []string\n\nfunc (ss stringSlice) String() string { return strings.Join(ss, \",\") }\n\n\nvar (\n\tDebug bool\n\n\tskips stringSlice\n\tcases stringSlice\n)\n\nfunc init() {\n\tflag.Var(&skips, \"skip\", \"skip test case\")\n\tflag.Var(&cases, \"case\", \"run test case\")\n\tflag.BoolVar(&Debug, \"debug\", false, \"enter debug mode\")\n\n\tlog.SetFlags(log.Lshortfile | log.LstdFlags)\n}\n\n\n\n\nfunc SkipCase(c interface{}) bool {\n\tfor _, item := range skips {\n\t\tif item == fmt.Sprint(c) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tfor _, item := range cases {\n\t\tif item == fmt.Sprint(c) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif len(cases) > 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (ss *stringSlice) Set(s string) error ", "output": "{ *ss = append(*ss, s); return nil }"} {"input": "package files\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\n\n\n\n\nfunc NewGetFilesFileidentifierParamsWithTimeout(timeout time.Duration) *GetFilesFileidentifierParams {\n\tvar ()\n\treturn &GetFilesFileidentifierParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype GetFilesFileidentifierParams struct {\n\n\tFileidentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *GetFilesFileidentifierParams) WithFileidentifier(fileidentifier string) *GetFilesFileidentifierParams {\n\to.Fileidentifier = fileidentifier\n\treturn o\n}\n\n\nfunc (o *GetFilesFileidentifierParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"fileidentifier\", o.Fileidentifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewGetFilesFileidentifierParams() *GetFilesFileidentifierParams ", "output": "{\n\tvar ()\n\treturn &GetFilesFileidentifierParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}"} {"input": "package unit\n\nimport (\n\t\"github.com/juju/cmd\"\n\t\"github.com/juju/names/v4\"\n\t\"github.com/juju/utils/v2/voyeur\"\n\n\t\"github.com/juju/juju/agent\"\n\t\"github.com/juju/juju/cmd/containeragent/utils\"\n\t\"github.com/juju/juju/cmd/jujud/agent/agentconf\"\n\t\"github.com/juju/juju/worker/logsender\"\n)\n\ntype (\n\tManifoldsConfig = manifoldsConfig\n\tContainerUnitAgent = containerUnitAgent\n)\n\ntype ContainerUnitAgentTest interface {\n\tcmd.Command\n\tDataDir() string\n\tSetAgentConf(cfg agentconf.AgentConf)\n\tChangeConfig(change agent.ConfigMutator) error\n\tCurrentConfig() agent.Config\n\tTag() names.UnitTag\n\tCharmModifiedVersion() int\n\tGetContainerNames() []string\n}\n\n\n\nfunc (c *containerUnitAgent) SetAgentConf(cfg agentconf.AgentConf) {\n\tc.AgentConf = cfg\n}\n\nfunc (c *containerUnitAgent) GetContainerNames() []string {\n\treturn c.containerNames\n}\n\nfunc (c *containerUnitAgent) DataDir() string {\n\treturn c.AgentConf.DataDir()\n}\n\nfunc NewForTest(\n\tctx *cmd.Context,\n\tbufferedLogger *logsender.BufferedLogWriter,\n\tconfigChangedVal *voyeur.Value,\n\tfileReaderWriter utils.FileReaderWriter,\n\tenvironment utils.Environment,\n) ContainerUnitAgentTest ", "output": "{\n\treturn &containerUnitAgent{\n\t\tctx: ctx,\n\t\tAgentConf: agentconf.NewAgentConf(\"\"),\n\t\tbufferedLogger: bufferedLogger,\n\t\tconfigChangedVal: configChangedVal,\n\t\tfileReaderWriter: fileReaderWriter,\n\t\tenvironment: environment,\n\t}\n}"} {"input": "package tools\n\nimport (\n\t\"github.com/chanxuehong/wechat.v2/mch/core\"\n\t\"github.com/chanxuehong/wechat.v2/util\"\n)\n\n\n\n\ntype AuthCodeToOpenIdRequest struct {\n\tXMLName struct{} `xml:\"xml\" json:\"-\"`\n\n\tAuthCode string `xml:\"auth_code\"` \n\n\tNonceStr string `xml:\"nonce_str\"` \n\tSignType string `xml:\"sign_type\"` \n}\n\ntype AuthCodeToOpenIdResponse struct {\n\tXMLName struct{} `xml:\"xml\" json:\"-\"`\n\n\tOpenId string `xml:\"openid\"` \n\n\tSubOpenId string `xml:\"sub_openid\"` \n}\n\n\nfunc AuthCodeToOpenId2(clt *core.Client, req *AuthCodeToOpenIdRequest) (resp *AuthCodeToOpenIdResponse, err error) {\n\tm1 := make(map[string]string, 8)\n\tm1[\"auth_code\"] = req.AuthCode\n\tif req.NonceStr != \"\" {\n\t\tm1[\"nonce_str\"] = req.NonceStr\n\t} else {\n\t\tm1[\"nonce_str\"] = util.NonceStr()\n\t}\n\tif req.SignType != \"\" {\n\t\tm1[\"sign_type\"] = req.SignType\n\t}\n\n\tm2, err := AuthCodeToOpenId(clt, m1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp = &AuthCodeToOpenIdResponse{\n\t\tOpenId: m2[\"openid\"],\n\t\tSubOpenId: m2[\"sub_openid\"],\n\t}\n\treturn resp, nil\n}\n\nfunc AuthCodeToOpenId(clt *core.Client, req map[string]string) (resp map[string]string, err error) ", "output": "{\n\treturn clt.PostXML(core.APIBaseURL()+\"/tools/authcodetoopenid\", req)\n}"} {"input": "package main\n\nimport (\n\t\"euler/tools\"\n\t\"fmt\"\n\t\"math/big\"\n)\n\n\n\n\nfunc problem57() int {\n\tsum := 0 \n\tconst limit = 1000 \n\tone := new(big.Rat).SetInt64(1)\n\ttwo := new(big.Rat).SetInt64(2)\n\n\tresult := new(big.Rat)\n\ttail := new(big.Rat).SetInt64(2)\n\n\tfor i := 0; i < limit; i++ {\n\t\ttemp := new(big.Rat)\n\t\ttail.Add(two, temp.Inv(tail)) \n\t\tresult.Add(one, temp.Inv(tail)) \n\t\tif checkNumerator(result) {\n\t\t\tsum++\n\t\t}\n\t}\n\treturn sum\n}\n\nfunc main() {\n\tfmt.Println(problem57())\n}\n\nfunc checkNumerator(x *big.Rat) bool ", "output": "{\n\tnum, denom := x.Num(), x.Denom()\n\treturn tools.NumDigits(num) > tools.NumDigits(denom)\n}"} {"input": "package backingstore\n\nimport (\n\t\"github.com/gostor/gotgt/pkg/api\"\n\t\"github.com/gostor/gotgt/pkg/scsi\"\n)\n\nfunc init() {\n\tscsi.RegisterBackingStore(\"null\", newNull)\n}\n\ntype NullBackingStore struct {\n\tscsi.BaseBackingStore\n}\n\nfunc newNull() (api.BackingStore, error) {\n\treturn &NullBackingStore{\n\t\tBaseBackingStore: scsi.BaseBackingStore{\n\t\t\tName: \"null\",\n\t\t\tDataSize: 0,\n\t\t\tOflagsSupported: 0,\n\t\t},\n\t}, nil\n}\n\nfunc (bs *NullBackingStore) Open(dev *api.SCSILu, path string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Close(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Init(dev *api.SCSILu, Opts string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Exit(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Size(dev *api.SCSILu) uint64 {\n\treturn 0\n}\n\nfunc (bs *NullBackingStore) Read(offset, tl int64) ([]byte, error) {\n\treturn nil, nil\n}\n\nfunc (bs *NullBackingStore) Write(wbuf []byte, offset int64) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataSync(offset, tl int64) error {\n\treturn nil\n}\n\n\n\nfunc (bs *NullBackingStore) Unmap([]api.UnmapBlockDescriptor) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataAdvise(offset, length int64, advise uint32) error ", "output": "{\n\treturn nil\n}"} {"input": "package thrift\n\nimport (\n\t\"net\"\n)\n\n\ntype socketConn struct {\n\tnet.Conn\n\n\tbuffer [1]byte\n}\n\nvar _ net.Conn = (*socketConn)(nil)\n\n\n\nfunc createSocketConnFromReturn(conn net.Conn, err error) (*socketConn, error) {\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &socketConn{\n\t\tConn: conn,\n\t}, nil\n}\n\n\nfunc wrapSocketConn(conn net.Conn) *socketConn {\n\tif sc, ok := conn.(*socketConn); ok {\n\t\treturn sc\n\t}\n\n\treturn &socketConn{\n\t\tConn: conn,\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (sc *socketConn) IsOpen() bool {\n\tif !sc.isValid() {\n\t\treturn false\n\t}\n\treturn sc.checkConn() == nil\n}\n\n\n\n\n\n\n\n\n\n\nfunc (sc *socketConn) Read(p []byte) (n int, err error) {\n\tif len(p) == 0 {\n\t\treturn 0, sc.read0()\n\t}\n\n\treturn sc.Conn.Read(p)\n}\n\nfunc (sc *socketConn) isValid() bool ", "output": "{\n\treturn sc != nil && sc.Conn != nil\n}"} {"input": "package pflag\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype boolValue bool\n\nfunc newBoolValue(val bool, p *bool) *boolValue {\n\t*p = val\n\treturn (*boolValue)(p)\n}\n\nfunc (b *boolValue) Set(s string) error {\n\tv, err := strconv.ParseBool(s)\n\t*b = boolValue(v)\n\treturn err\n}\n\nfunc (b *boolValue) String() string { return fmt.Sprintf(\"%v\", *b) }\n\n\n\nfunc (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc BoolVar(p *bool, name string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc (f *FlagSet) Bool(name string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, \"\", value, usage)\n\treturn p\n}\n\n\n\n\n\n\nfunc Bool(name string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, \"\", value, usage)\n}\n\n\nfunc BoolP(name, shorthand string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, shorthand, value, usage)\n}\n\nfunc (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool ", "output": "{\n\tp := new(bool)\n\tf.BoolVarP(p, name, shorthand, value, usage)\n\treturn p\n}"} {"input": "package net\n\nimport (\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\ntype Endpoint interface {\n\tHostName() string\n\tPort() int\n}\n\ntype defaultEndpoint struct {\n\thostname string\n\tport int\n}\n\nfunc (e defaultEndpoint) HostName() string {\n\treturn e.hostname\n}\nfunc (e defaultEndpoint) Port() int {\n\treturn e.port\n}\n\n\n\nfunc FromUrl(u url.URL) Endpoint {\n\tparts := strings.Split(u.Host, \":\")\n\tif len(parts) != 2 {\n\t\treturn nil\n\t}\n\tport, _ := strconv.Atoi(parts[1])\n\treturn NewEndpoint(parts[0], port)\n}\n\nfunc NewEndpoint(hostname string, port int) Endpoint ", "output": "{\n\treturn defaultEndpoint{hostname, port}\n}"} {"input": "package chipmunk\n\nimport (\n\t\"github.com/vova616/chipmunk/transform\"\n\t\"github.com/vova616/chipmunk/vect\"\n)\n\n\ntype BoxShape struct {\n\tShape *Shape\n\tPolygon *PolygonShape\n\tverts [4]vect.Vect\n\tWidth vect.Float\n\tHeight vect.Float\n\tPosition vect.Vect\n}\n\n\n\n\nfunc (box *BoxShape) Moment(mass float32) vect.Float {\n\treturn (vect.Float(mass) * (box.Width*box.Width + box.Height*box.Height) / 12.0)\n}\n\n\nfunc (box *BoxShape) UpdatePoly() {\n\thw := box.Width / 2.0\n\thh := box.Height / 2.0\n\n\tif hw < 0 {\n\t\thw = -hw\n\t}\n\tif hh < 0 {\n\t\thh = -hh\n\t}\n\n\tbox.verts = [4]vect.Vect{\n\t\t{-hw, -hh},\n\t\t{-hw, hh},\n\t\t{hw, hh},\n\t\t{hw, -hh},\n\t}\n\n\tpoly := box.Polygon\n\tpoly.SetVerts(box.verts[:], box.Position)\n}\n\n\nfunc (box *BoxShape) ShapeType() ShapeType {\n\treturn ShapeType_Box\n}\n\n\nfunc (box *BoxShape) Clone(s *Shape) ShapeClass {\n\tclone := *box\n\tclone.Polygon = &PolygonShape{Shape: s}\n\tclone.Shape = s\n\tclone.UpdatePoly()\n\treturn &clone\n}\n\n\nfunc (box *BoxShape) update(xf transform.Transform) AABB {\n\treturn box.Polygon.update(xf)\n}\n\n\nfunc (box *BoxShape) TestPoint(point vect.Vect) bool {\n\treturn box.Polygon.TestPoint(point)\n}\n\nfunc NewBox(pos vect.Vect, w, h vect.Float) *Shape ", "output": "{\n\tshape := newShape()\n\n\tbox := &BoxShape{\n\t\tPolygon: &PolygonShape{Shape: shape},\n\t\tWidth: w,\n\t\tHeight: h,\n\t\tPosition: pos,\n\t\tShape: shape,\n\t}\n\n\thw := w / 2.0\n\thh := h / 2.0\n\n\tif hw < 0 {\n\t\thw = -hw\n\t}\n\tif hh < 0 {\n\t\thh = -hh\n\t}\n\n\tbox.verts = [4]vect.Vect{\n\t\t{-hw, -hh},\n\t\t{-hw, hh},\n\t\t{hw, hh},\n\t\t{hw, -hh},\n\t}\n\n\tpoly := box.Polygon\n\tpoly.SetVerts(box.verts[:], box.Position)\n\n\tshape.ShapeClass = box\n\treturn shape\n}"} {"input": "package db\n\nimport (\n\t\"github.com/globalsign/mgo\"\n\t\"github.com/tsuru/config\"\n\t\"github.com/tsuru/tsuru/db/storage\"\n)\n\nconst (\n\tDefaultDatabaseURL = \"127.0.0.1:27017\"\n\tDefaultDatabaseName = \"gandalf\"\n)\n\ntype Storage struct {\n\t*storage.Storage\n}\n\n\n\n\n\nfunc conn() (*storage.Storage, error) {\n\turl, dbname := DbConfig()\n\treturn storage.Open(url, dbname)\n}\n\nfunc Conn() (*Storage, error) {\n\tvar (\n\t\tstrg Storage\n\t\terr error\n\t)\n\tstrg.Storage, err = conn()\n\treturn &strg, err\n}\n\nfunc DbConfig() (string, string) {\n\turl, _ := config.GetString(\"database:url\")\n\tif url == \"\" {\n\t\turl = DefaultDatabaseURL\n\t}\n\tdbname, _ := config.GetString(\"database:name\")\n\tif dbname == \"\" {\n\t\tdbname = DefaultDatabaseName\n\t}\n\treturn url, dbname\n}\n\n\n\n\n\nfunc (s *Storage) User() *storage.Collection {\n\treturn s.Collection(\"user\")\n}\n\nfunc (s *Storage) Key() *storage.Collection {\n\tbodyIndex := mgo.Index{Key: []string{\"body\"}, Unique: true}\n\tnameIndex := mgo.Index{Key: []string{\"username\", \"name\"}, Unique: true}\n\tc := s.Collection(\"key\")\n\tc.EnsureIndex(bodyIndex)\n\tc.EnsureIndex(nameIndex)\n\treturn c\n}\n\nfunc (s *Storage) Repository() *storage.Collection ", "output": "{\n\treturn s.Collection(\"repository\")\n}"} {"input": "package codegen\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"text/template\"\n)\n\nconst (\n\tcommentLinePrefix = \" \"\n)\n\nfunc applyTemplate(tmpl string, i interface{}) (string, error) {\n\tt := template.New(\"tmpl\").Funcs(template.FuncMap{\n\t\t\"wordWrap\": wordWrap,\n\t\t\"commentBlock\": commentBlock,\n\t\t\"hasPrefix\": strings.HasPrefix,\n\t})\n\n\tt2 := template.Must(t.Parse(tmpl))\n\n\tvar b bytes.Buffer\n\tif err := t2.Execute(&b, i); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn b.String(), nil\n}\n\nfunc commentBlock(in []string, indentTabs int) string {\n\tin = append([]string{}, in...)\n\n\tfor lineIndex := range in {\n\t\tprefix := \"\"\n\t\tfor tabIndex := 0; lineIndex > 0 && tabIndex < indentTabs; tabIndex++ {\n\t\t\tprefix += \"\\t\"\n\t\t}\n\t\tprefix += commentLinePrefix\n\t\tin[lineIndex] = prefix + in[lineIndex]\n\t}\n\n\treturn strings.Join(in, \"\\n\")\n}\n\n\n\nfunc wordWrap(in string, maxLineLength int) []string ", "output": "{\n\tinputLines := strings.Split(in, \"\\n\")\n\toutputLines := make([]string, 0)\n\n\tline := \"\"\n\tfor i, inputLine := range inputLines {\n\t\tif i > 0 {\n\t\t\toutputLines = append(outputLines, line)\n\t\t\tline = \"\"\n\t\t}\n\n\t\twords := strings.Split(inputLine, \" \")\n\n\t\tfor len(words) > 0 {\n\t\t\tword := words[0]\n\t\t\twords = words[1:]\n\n\t\t\tif len(line)+len(word) > maxLineLength {\n\t\t\t\toutputLines = append(outputLines, line)\n\t\t\t\tline = \"\"\n\t\t\t}\n\n\t\t\tif len(line) > 0 {\n\t\t\t\tline += \" \"\n\t\t\t}\n\t\t\tline += word\n\t\t}\n\t}\n\n\toutputLines = append(outputLines, line)\n\n\treturn outputLines\n}"} {"input": "package datascience\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype UpdateModelRequest struct {\n\n\tModelId *string `mandatory:\"true\" contributesTo:\"path\" name:\"modelId\"`\n\n\tUpdateModelDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateModelRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request UpdateModelRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request UpdateModelRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request UpdateModelRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateModelResponse struct {\n\n\tRawResponse *http.Response\n\n\tModel `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateModelResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response UpdateModelResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package overcurrent\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\ntype (\n\tNoopBreaker struct{}\n\n\tNoopCollector struct{}\n)\n\nvar defaultCollector = NewNoopCollector()\n\n\nfunc NewNoopBreaker() CircuitBreaker {\n\treturn &NoopBreaker{}\n}\n\nfunc (b *NoopBreaker) Trip() {}\nfunc (b *NoopBreaker) Reset() {}\nfunc (b *NoopBreaker) ShouldTry() bool { return true }\n\nfunc (b *NoopBreaker) Call(f BreakerFunc) error { return f(context.Background()) }\nfunc (b *NoopBreaker) CallAsync(f BreakerFunc) <-chan error { return nil }\n\n\nfunc NewNoopCollector() MetricCollector {\n\treturn &NoopCollector{}\n}\n\nfunc (c *NoopCollector) ReportNew(BreakerConfig) {}\nfunc (c *NoopCollector) ReportCount(EventType) {}\nfunc (c *NoopCollector) ReportDuration(EventType, time.Duration) {}\nfunc (c *NoopCollector) ReportState(CircuitState) {}\n\nfunc (b *NoopBreaker) MarkResult(err error) bool ", "output": "{ return true }"} {"input": "package storage\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tgenericapirequest \"k8s.io/apiserver/pkg/endpoints/request\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\tgenericregistry \"k8s.io/apiserver/pkg/registry/generic/registry\"\n\t\"k8s.io/apiserver/pkg/registry/rest\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n\t\"k8s.io/kubernetes/pkg/registry/extensions/ingress\"\n)\n\n\ntype REST struct {\n\t*genericregistry.Store\n}\n\n\n\n\n\nvar _ rest.ShortNamesProvider = &REST{}\n\n\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"ing\"}\n}\n\n\ntype StatusREST struct {\n\tstore *genericregistry.Store\n}\n\nfunc (r *StatusREST) New() runtime.Object {\n\treturn &extensions.Ingress{}\n}\n\n\nfunc (r *StatusREST) Get(ctx genericapirequest.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}\n\n\nfunc (r *StatusREST) Update(ctx genericapirequest.Context, name string, objInfo rest.UpdatedObjectInfo) (runtime.Object, bool, error) {\n\treturn r.store.Update(ctx, name, objInfo)\n}\n\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST) ", "output": "{\n\tstore := &genericregistry.Store{\n\t\tCopier: api.Scheme,\n\t\tNewFunc: func() runtime.Object { return &extensions.Ingress{} },\n\t\tNewListFunc: func() runtime.Object { return &extensions.IngressList{} },\n\t\tPredicateFunc: ingress.MatchIngress,\n\t\tDefaultQualifiedResource: extensions.Resource(\"ingresses\"),\n\n\t\tCreateStrategy: ingress.Strategy,\n\t\tUpdateStrategy: ingress.Strategy,\n\t\tDeleteStrategy: ingress.Strategy,\n\t}\n\toptions := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: ingress.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\tpanic(err) \n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = ingress.StatusStrategy\n\treturn &REST{store}, &StatusREST{store: &statusStore}\n}"} {"input": "package label\n\n\n\n\nfunc InitLabels(mcsdir string, options []string) (string, string, error) {\n\treturn \"\", \"\", nil\n}\n\nfunc FormatMountLabel(src string, mountLabel string) string {\n\treturn src\n}\n\nfunc SetProcessLabel(processLabel string) error {\n\treturn nil\n}\n\nfunc SetFileLabel(path string, fileLabel string) error {\n\treturn nil\n}\n\nfunc SetFileCreateLabel(fileLabel string) error {\n\treturn nil\n}\n\n\n\nfunc GetPidLabel(pid int) (string, error) {\n\treturn \"\", nil\n}\n\nfunc Init() {\n}\n\nfunc ReserveLabel(label string) error {\n\treturn nil\n}\n\nfunc UnreserveLabel(label string) error {\n\treturn nil\n}\n\n\n\nfunc DupSecOpt(src string) []string {\n\treturn nil\n}\n\n\n\nfunc DisableSecOpt() []string {\n\treturn nil\n}\n\nfunc Relabel(path string, fileLabel string, relabel string) error ", "output": "{\n\treturn nil\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/converter\"\n\t\"strings\"\n)\n\n\ntype BatchStopServersOption struct {\n\tServers []ServerId `json:\"servers\"`\n\tType *BatchStopServersOptionType `json:\"type,omitempty\"`\n}\n\n\n\ntype BatchStopServersOptionType struct {\n\tvalue string\n}\n\ntype BatchStopServersOptionTypeEnum struct {\n\tSOFT BatchStopServersOptionType\n\tHARD BatchStopServersOptionType\n}\n\nfunc GetBatchStopServersOptionTypeEnum() BatchStopServersOptionTypeEnum {\n\treturn BatchStopServersOptionTypeEnum{\n\t\tSOFT: BatchStopServersOptionType{\n\t\t\tvalue: \"SOFT\",\n\t\t},\n\t\tHARD: BatchStopServersOptionType{\n\t\t\tvalue: \"HARD\",\n\t\t},\n\t}\n}\n\nfunc (c BatchStopServersOptionType) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(c.value)\n}\n\nfunc (c *BatchStopServersOptionType) UnmarshalJSON(b []byte) error {\n\tmyConverter := converter.StringConverterFactory(\"string\")\n\tif myConverter != nil {\n\t\tval, err := myConverter.CovertStringToInterface(strings.Trim(string(b[:]), \"\\\"\"))\n\t\tif err == nil {\n\t\t\tc.value = val.(string)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t} else {\n\t\treturn errors.New(\"convert enum data to string error\")\n\t}\n}\n\nfunc (o BatchStopServersOption) String() string ", "output": "{\n\tdata, _ := json.Marshal(o)\n\treturn strings.Join([]string{\"BatchStopServersOption\", string(data)}, \" \")\n}"} {"input": "package options\n\nimport (\n\t\"github.com/spf13/pflag\"\n\t\"k8s.io/kubernetes/pkg/apis/componentconfig\"\n)\n\n\ntype DaemonSetControllerOptions struct {\n\tConcurrentDaemonSetSyncs int32\n}\n\n\nfunc (o *DaemonSetControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n}\n\n\n\n\n\nfunc (o *DaemonSetControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}\n\nfunc (o *DaemonSetControllerOptions) ApplyTo(cfg *componentconfig.DaemonSetControllerConfiguration) error ", "output": "{\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentDaemonSetSyncs = o.ConcurrentDaemonSetSyncs\n\n\treturn nil\n}"} {"input": "package ubuntu\n\nimport (\n\t\"github.com/megamsys/megdc/templates\"\n\t\"github.com/megamsys/urknall\"\n)\n\nvar ubuntunilavuremove *UbuntuNilavuRemove\n\nfunc init() {\n\tubuntunilavuremove = &UbuntuNilavuRemove{}\n\ttemplates.Register(\"UbuntuNilavuRemove\", ubuntunilavuremove)\n}\n\ntype UbuntuNilavuRemove struct{}\n\n\n\nfunc (tpl *UbuntuNilavuRemove) Options(t *templates.Template) {\n}\n\nfunc (tpl *UbuntuNilavuRemove) Run(target urknall.Target) error {\n\treturn urknall.Run(target, &UbuntuNilavuRemove{})\n}\n\ntype UbuntuNilavuRemoveTemplate struct{}\n\nfunc (m *UbuntuNilavuRemoveTemplate) Render(pkg urknall.Package) {\n\tpkg.AddCommands(\"verticenilavu\",\n\t\tRemovePackage(\"verticenilavu\"),\n\t\tRemovePackages(\"\"),\n\t\tPurgePackages(\"verticenilavu\"),\n\t\tShell(\"dpkg --get-selections megam*\"),\n\t)\n\tpkg.AddCommands(\"nilavu-clean\",\n\t\tShell(\"rm -r /var/lib/urknall/nilavu*\"),\n\t)\n}\n\nfunc (tpl *UbuntuNilavuRemove) Render(p urknall.Package) ", "output": "{\n\tp.AddTemplate(\"nilavu\", &UbuntuNilavuRemoveTemplate{})\n}"} {"input": "package json\n\nimport \"fmt\"\n\ntype Serializer struct {\n\tdumper *Dumper\n\tparser *Parser\n}\n\nfunc (serializer *Serializer) String() string {\n\treturn fmt.Sprintf(\"\")\n}\n\nfunc (serializer *Serializer) Dump(m *map[interface{}]interface{}) string {\n\treturn serializer.dumper.Dump(m)\n}\n\n\n\nfunc (serializer *Serializer) Parse(s string) map[interface{}]interface{} ", "output": "{\n\treturn serializer.parser.Parse(s)\n}"} {"input": "package cloudcontroller\n\nimport (\n\t\"code.cloudfoundry.org/cli/api/cloudcontroller/ccerror\"\n\t\"github.com/blang/semver\"\n)\n\n\n\n\n\nfunc MinimumAPIVersionCheck(current string, minimum string) error ", "output": "{\n\tif minimum == \"\" {\n\t\treturn nil\n\t}\n\n\tcurrentSemver, err := semver.Make(current)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tminimumSemver, err := semver.Make(minimum)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif currentSemver.Compare(minimumSemver) == -1 {\n\t\treturn ccerror.MinimumAPIVersionNotMetError{\n\t\t\tCurrentVersion: current,\n\t\t\tMinimumVersion: minimum,\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package pigsty\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\ntype BootstrapAction struct {\n\tName string\n\tPath string\n\tArgs []*string\n}\n\n\n\nfunc NewBootstrapActions(jsonBlob []byte) (bootstrap []BootstrapAction) ", "output": "{\n\tvar bootstrapActions []BootstrapAction\n\terr := json.Unmarshal(jsonBlob, &bootstrapActions)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\treturn bootstrapActions\n}"} {"input": "package arg2\n\nimport (\n\t\"encoding/binary\"\n\t\"io\"\n\n\t\"github.com/uber/tchannel-go/typed\"\n)\n\n\n\n\n\ntype KeyValIterator struct {\n\tremaining []byte\n\tleftPairCount int\n\tkey []byte\n\tval []byte\n}\n\n\n\n\nfunc NewKeyValIterator(arg2Payload []byte) (KeyValIterator, error) {\n\tif len(arg2Payload) < 2 {\n\t\treturn KeyValIterator{}, io.EOF\n\t}\n\n\tleftPairCount := binary.BigEndian.Uint16(arg2Payload[0:2])\n\treturn KeyValIterator{\n\t\tleftPairCount: int(leftPairCount),\n\t\tremaining: arg2Payload[2:],\n\t}.Next()\n}\n\n\nfunc (i KeyValIterator) Key() []byte {\n\treturn i.key\n}\n\n\nfunc (i KeyValIterator) Value() []byte {\n\treturn i.val\n}\n\n\nfunc (i KeyValIterator) Remaining() bool {\n\treturn i.leftPairCount > 0\n}\n\n\n\n\n\n\n\n\nfunc (i KeyValIterator) Next() (kv KeyValIterator, _ error) ", "output": "{\n\tif i.leftPairCount <= 0 {\n\t\treturn KeyValIterator{}, io.EOF\n\t}\n\n\trbuf := typed.NewReadBuffer(i.remaining)\n\tkeyLen := int(rbuf.ReadUint16())\n\tkey := rbuf.ReadBytes(keyLen)\n\tvalLen := int(rbuf.ReadUint16())\n\tval := rbuf.ReadBytes(valLen)\n\tif rbuf.Err() != nil {\n\t\treturn KeyValIterator{}, rbuf.Err()\n\t}\n\n\tleftPairCount := i.leftPairCount - 1\n\n\tkv = KeyValIterator{\n\t\tremaining: rbuf.Remaining(),\n\t\tleftPairCount: leftPairCount,\n\t\tkey: key,\n\t\tval: val,\n\t}\n\treturn kv, nil\n}"} {"input": "package trivette\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n)\n\ntype Credentials struct {\n\tUser, Token string\n}\n\nfunc e(err error) {\n\tif nil != err {\n\t\tpanic(err)\n\t}\n}\n\n\n\nfunc ReadCredentials(path string) *Credentials ", "output": "{\n\traw, err := ioutil.ReadFile(path)\n\tvar credentials Credentials\n\terr = json.Unmarshal(raw, &credentials)\n\te(err)\n\treturn &credentials\n}"} {"input": "package victor\n\nimport (\n\t\"github.com/FogCreek/victor/pkg/chat\"\n)\n\n\ntype Handler interface {\n\tHandle(State)\n}\n\n\ntype HandlerFunc func(State)\n\n\n\nfunc (f HandlerFunc) Handle(s State) {\n\tf(s)\n}\n\n\n\ntype State interface {\n\tRobot() Robot\n\tChat() chat.Adapter\n\tMessage() chat.Message\n\tFields() []string\n\tReply(string)\n}\n\ntype state struct {\n\trobot Robot\n\tmessage chat.Message\n\tfields []string\n}\n\n\n\n\n\nfunc (s *state) Reply(msg string) {\n\ts.robot.Chat().Send(s.message.Channel().ID(), msg)\n}\n\n\nfunc (s *state) Robot() Robot {\n\treturn s.robot\n}\n\n\n\n\n\nfunc (s *state) Message() chat.Message {\n\treturn s.message\n}\n\nfunc (s *state) Fields() []string {\n\treturn s.fields\n}\n\nfunc (s *state) Chat() chat.Adapter ", "output": "{\n\treturn s.robot.Chat()\n}"} {"input": "package do\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\n\n\n\n\n\nfunc WaitForErrorChannels(ctx Context, channels ...<-chan error) (err error) {\n\tcases := make([]reflect.SelectCase, len(channels)+1)\n\tctxDoneCaseIndex := len(channels)\n\tfor i, ch := range channels {\n\t\tcases[i] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ch)}\n\t}\n\tif ctx != nil {\n\t\tcases[ctxDoneCaseIndex] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ctx.Done())}\n\t}\n\n\tremaining := len(channels)\n\tfor remaining > 0 {\n\t\ti, value, ok := reflect.Select(cases)\n\n\t\tif i == ctxDoneCaseIndex {\n\t\t\treturn ctx.Err()\n\n\t\t} else if !value.IsNil() {\n\t\t\treturn value.Interface().(error)\n\n\t\t} else if !ok {\n\t\t\treturn fmt.Errorf(\"WaitForErrorChannels attempted read from closed channel #%d\", i)\n\t\t}\n\n\t\tcases[i].Chan = reflect.ValueOf(nil)\n\t\tremaining--\n\t}\n\treturn nil\n}\n\n\n\nfunc CheckChan(channel chan interface{}) (didRead bool, item interface{}) {\n\treturn nonBlockingChannelRead(channel)\n}\n\n\n\nfunc CheckErrChan(errChan chan error) (didRead bool, err error) {\n\tdidRead, val := nonBlockingChannelRead(errChan)\n\treturn didRead, val.(error)\n}\n\n\n\nfunc CheckStructChan(channel chan struct{}) (didRead bool) {\n\tdidRead, _ = nonBlockingChannelRead(channel)\n\treturn didRead\n}\n\n\n\nfunc nonBlockingChannelRead(channel interface{}) (didRead bool, item interface{}) ", "output": "{\n\trCase := reflect.SelectCase{\n\t\tChan: reflect.ValueOf(channel),\n\t\tDir: reflect.SelectRecv,\n\t}\n\t_, value, didRead := reflect.Select([]reflect.SelectCase{rCase})\n\treturn didRead, value.Interface()\n}"} {"input": "package json\n\nimport (\n\t\"testing\"\n\n\tch \"gopkg.in/check.v1\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestByCheck(t *testing.T) {\n\tch.TestingT(t)\n}\n\nfunc TestByGinkgo(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Base Suite\")\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"testing\"\n)\n\n\n\n\n\n\n\n\nfunc approx(t testing.TB, got, want float64) {\n\tf1 := got\n\tf2 := want\n\tif f1 == f2 {\n\t\treturn\n\t} else if f1 > f2 {\n\t\tf1, f2 = f2, f1\n\t}\n\tdelta := (f2 - f1) / f1\n\tif delta > 0.0001 { \n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\t%s:%d: got %v; want %v\\n\", filepath.Base(file), line, got, want)\n\t\tt.FailNow()\n\t}\n}\n\nfunc equals(t testing.TB, got, want interface{}) ", "output": "{\n\tif want == nil && (got == nil || reflect.ValueOf(got).IsNil()) {\n\t\treturn\n\t}\n\tif !reflect.DeepEqual(got, want) {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\t%s:%d: got: %#v; want: %#v\\n\", filepath.Base(file), line, got, want)\n\t\tt.FailNow()\n\t}\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"k8s.io/client-go/kubernetes/typed/extensions/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeExtensionsV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeExtensionsV1beta1) DaemonSets(namespace string) v1beta1.DaemonSetInterface {\n\treturn &FakeDaemonSets{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) Deployments(namespace string) v1beta1.DeploymentInterface {\n\treturn &FakeDeployments{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) Ingresses(namespace string) v1beta1.IngressInterface {\n\treturn &FakeIngresses{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) PodSecurityPolicies() v1beta1.PodSecurityPolicyInterface {\n\treturn &FakePodSecurityPolicies{c}\n}\n\n\n\nfunc (c *FakeExtensionsV1beta1) Scales(namespace string) v1beta1.ScaleInterface {\n\treturn &FakeScales{c, namespace}\n}\n\n\n\nfunc (c *FakeExtensionsV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeExtensionsV1beta1) ReplicaSets(namespace string) v1beta1.ReplicaSetInterface ", "output": "{\n\treturn &FakeReplicaSets{c, namespace}\n}"} {"input": "package error\n\nimport \"google.golang.org/grpc/codes\"\n\n\ntype ErrType int\n\nconst (\n\tCANotReady ErrType = iota\n\tCSRError\n\tTTLError\n\tCertGenError\n)\n\n\ntype Error struct {\n\tt ErrType\n\terr error\n}\n\n\n\n\n\nfunc (e Error) ErrorType() string {\n\tswitch e.t {\n\tcase CANotReady:\n\t\treturn \"CA_NOT_READY\"\n\tcase CSRError:\n\t\treturn \"CSR_ERROR\"\n\tcase TTLError:\n\t\treturn \"TTL_ERROR\"\n\tcase CertGenError:\n\t\treturn \"CERT_GEN_ERROR\"\n\t}\n\treturn \"UNKNOWN\"\n}\n\n\nfunc (e Error) HTTPErrorCode() codes.Code {\n\tswitch e.t {\n\tcase CANotReady:\n\t\treturn codes.Internal\n\tcase CertGenError:\n\t\treturn codes.Internal\n\tcase CSRError:\n\t\treturn codes.InvalidArgument\n\tcase TTLError:\n\t\treturn codes.InvalidArgument\n\t}\n\treturn codes.Internal\n}\n\n\nfunc NewError(t ErrType, err error) *Error {\n\treturn &Error{\n\t\tt: t,\n\t\terr: err,\n\t}\n}\n\nfunc (e Error) Error() string ", "output": "{\n\treturn e.err.Error()\n}"} {"input": "package resolvers\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/emwalker/digraph/cmd/frontend/loaders\"\n\t\"github.com/emwalker/digraph/cmd/frontend/models\"\n\t\"github.com/volatiletech/sqlboiler/queries/qm\"\n)\n\ntype organizationResolver struct {\n\t*Resolver\n}\n\nfunc getOrganizationLoader(ctx context.Context) *loaders.OrganizationLoader {\n\treturn ctx.Value(loaders.OrganizationLoaderKey).(*loaders.OrganizationLoader)\n}\n\nfunc fetchOrganization(ctx context.Context, organizationID string) (*models.Organization, error) {\n\tloader := getOrganizationLoader(ctx)\n\torg, err := loader.Load(organizationID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn org, nil\n}\n\n\nfunc (r *organizationResolver) CreatedAt(_ context.Context, org *models.Organization) (string, error) {\n\treturn org.CreatedAt.Format(time.RFC3339), nil\n}\n\n\nfunc (r *organizationResolver) DefaultRepository(ctx context.Context, org *models.Organization) (*models.Repository, error) {\n\trepo, err := org.Repositories(qm.Where(\"system\")).One(ctx, r.DB)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn repo, nil\n}\n\n\nfunc (r *organizationResolver) ResourcePath(\n\t_ context.Context, org *models.Organization,\n) (string, error) {\n\treturn \"/organizations/\" + org.ID, nil\n}\n\n\n\n\nfunc (r *organizationResolver) UpdatedAt(\n\t_ context.Context, org *models.Organization,\n) (string, error) ", "output": "{\n\treturn org.UpdatedAt.Format(time.RFC3339), nil\n}"} {"input": "package fs\n\nimport (\n\t\"syscall\"\n)\n\n\n\nfunc MountAdditional(source, dest, t string) error {\n\treturn syscall.Mount(source, dest, t, syscall.MS_BIND, \"\")\n}\n\nfunc MountDevFS() error {\n\treturn syscall.Mount(\"tmpfs\", \"/dev\", \"tmpfs\", syscall.MS_BIND, \"\")\n}\n\nfunc MountProcFS() error {\n\treturn syscall.Mount(\"proc\", \"/proc\", \"proc\", syscall.MS_BIND, \"\")\n}\n\nfunc MountSysFS() error {\n\treturn syscall.Mount(\"sysfs\", \"/sys\", \"sysfs\", syscall.MS_BIND, \"\")\n}\n\nfunc MountRootFS(path string) error ", "output": "{\n\treturn syscall.Mount(path, \"rootfs\", \"\", syscall.MS_BIND, \"\")\n}"} {"input": "package cmd\n\nimport (\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/minio/mc/pkg/httptracer\"\n\t\"github.com/minio/pkg/console\"\n)\n\n\ntype traceV4 struct{}\n\n\nfunc newTraceV4() httptracer.HTTPTracer {\n\treturn traceV4{}\n}\n\n\n\n\n\nfunc (t traceV4) Response(resp *http.Response) (err error) {\n\tvar respTrace []byte\n\tif resp.StatusCode != http.StatusOK &&\n\t\tresp.StatusCode != http.StatusPartialContent &&\n\t\tresp.StatusCode != http.StatusNoContent {\n\t\trespTrace, err = httputil.DumpResponse(resp, true)\n\t} else {\n\t\trespTrace, err = httputil.DumpResponse(resp, false)\n\t}\n\tif err == nil {\n\t\tconsole.Debug(string(respTrace))\n\t}\n\n\tif resp.TLS != nil {\n\t\tprintTLSCertInfo(resp.TLS)\n\t}\n\n\treturn err\n}\n\nfunc (t traceV4) Request(req *http.Request) (err error) ", "output": "{\n\torigAuth := req.Header.Get(\"Authorization\")\n\n\tprintTrace := func() error {\n\t\treqTrace, rerr := httputil.DumpRequestOut(req, false) \n\t\tif rerr == nil {\n\t\t\tconsole.Debug(string(reqTrace))\n\t\t}\n\t\treturn rerr\n\t}\n\n\tif strings.TrimSpace(origAuth) != \"\" {\n\n\t\tregCred := regexp.MustCompile(\"Credential=([A-Z0-9]+)/\")\n\t\tnewAuth := regCred.ReplaceAllString(origAuth, \"Credential=**REDACTED**/\")\n\n\t\tregSign := regexp.MustCompile(\"Signature=([[0-9a-f]+)\")\n\t\tnewAuth = regSign.ReplaceAllString(newAuth, \"Signature=**REDACTED**\")\n\n\t\treq.Header.Set(\"Authorization\", newAuth)\n\n\t\terr = printTrace()\n\n\t\treq.Header.Set(\"Authorization\", origAuth)\n\t} else {\n\t\terr = printTrace()\n\t}\n\treturn err\n}"} {"input": "package metrics\n\nimport \"time\"\n\n\ntype TimeHistogram interface {\n\tWith(Field) TimeHistogram\n\tObserve(time.Duration)\n}\n\ntype timeHistogram struct {\n\tHistogram\n\tunit time.Duration\n}\n\n\n\nfunc NewTimeHistogram(h Histogram, unit time.Duration) TimeHistogram {\n\treturn &timeHistogram{\n\t\tHistogram: h,\n\t\tunit: unit,\n\t}\n}\n\n\n\nfunc (h *timeHistogram) Observe(d time.Duration) {\n\th.Histogram.Observe(int64(d / h.unit))\n}\n\nfunc (h *timeHistogram) With(f Field) TimeHistogram ", "output": "{\n\treturn &timeHistogram{\n\t\tHistogram: h.Histogram.With(f),\n\t\tunit: h.unit,\n\t}\n}"} {"input": "package net\n\nimport \"net\"\nimport \"golang.org/x/net/context\"\n\n\ntype Dialer interface {\n\tDial(net, addr string, ctx context.Context) (net.Conn, error)\n}\n\n\ntype DialerFunc func(net, addr string, ctx context.Context) (net.Conn, error)\n\n\n\n\ntype netDialer struct{}\n\nfunc (netDialer) Dial(n, addr string, ctx context.Context) (net.Conn, error) {\n\tdeadline, _ := ctx.Deadline()\n\n\td := net.Dialer{\n\t\tDeadline: deadline,\n\t}\n\treturn d.Dial(n, addr)\n}\n\n\nvar NetDialer netDialer\n\n\nvar DefaultDialer = NetDialer\n\nfunc (df DialerFunc) Dial(net, addr string, ctx context.Context) (net.Conn, error) ", "output": "{\n\treturn df(net, addr, ctx)\n}"} {"input": "package client\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest/adal\"\n\t\"github.com/Azure/go-autorest/autorest/azure\"\n)\n\n\ntype msiOAuthTokenProvider struct {\n\tenv azure.Environment\n}\n\nfunc NewMSIOAuthTokenProvider(env azure.Environment) oAuthTokenProvider {\n\treturn &msiOAuthTokenProvider{env}\n}\n\n\n\nfunc (tp *msiOAuthTokenProvider) getServicePrincipalTokenWithResource(resource string) (*adal.ServicePrincipalToken, error) {\n\treturn adal.NewServicePrincipalTokenFromMSI(\"http://169.254.169.254/metadata/identity/oauth2/token\", resource)\n}\n\nfunc (tp *msiOAuthTokenProvider) getServicePrincipalToken() (*adal.ServicePrincipalToken, error) ", "output": "{\n\treturn tp.getServicePrincipalTokenWithResource(tp.env.ResourceManagerEndpoint)\n}"} {"input": "package ovs\n\nimport (\n\t\"time\"\n\n\tovs \"github.com/docker/libnetwork/drivers/ovs/ovsdbdriver\"\n\t\"github.com/vishvananda/netlink\"\n)\n\n\n\n\nfunc setupVerifyInterface(_ *ovs.OvsdbDriver, config *networkConfiguration) error ", "output": "{\n\tvar (\n\t\tmaxRetry int = 3\n\t\tfound = false\n\t)\n\n\tfor retry := 1; retry <= maxRetry; retry++ {\n\t\t_, err := netlink.LinkByName(config.BridgeName)\n\t\tif err == nil {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(2 * time.Second)\n\t}\n\tif !found {\n\t\treturn &ErrNotFoundAfterMaxRetry{maxRetry: maxRetry}\n\t}\n\treturn nil\n}"} {"input": "package keymanagement\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ImportKeyVersionRequest struct {\n\n\tKeyId *string `mandatory:\"true\" contributesTo:\"path\" name:\"keyId\"`\n\n\tImportKeyVersionDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ImportKeyVersionRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ImportKeyVersionRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ImportKeyVersionRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ImportKeyVersionRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ImportKeyVersionResponse struct {\n\n\tRawResponse *http.Response\n\n\tKeyVersion `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ImportKeyVersionResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response ImportKeyVersionResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\n\t_ \"github.com/etcd-io/gofail/runtime\"\n\t\"go.etcd.io/etcd/tests/v3/functional/tester\"\n\t\"go.uber.org/zap\"\n)\n\nvar logger *zap.Logger\n\n\n\nfunc main() {\n\tconfig := flag.String(\"config\", \"\", \"path to tester configuration\")\n\tflag.Parse()\n\n\tdefer logger.Sync()\n\n\tclus, err := tester.NewCluster(logger, *config)\n\tif err != nil {\n\t\tlogger.Fatal(\"failed to create a cluster\", zap.Error(err))\n\t}\n\n\terr = clus.Send_INITIAL_START_ETCD()\n\tif err != nil {\n\t\tlogger.Fatal(\"Bootstrap failed\", zap.Error(err))\n\t}\n\tdefer clus.Send_SIGQUIT_ETCD_AND_REMOVE_DATA_AND_STOP_AGENT()\n\n\tlogger.Info(\"wait health after bootstrap\")\n\terr = clus.WaitHealth()\n\tif err != nil {\n\t\tlogger.Fatal(\"WaitHealth failed\", zap.Error(err))\n\t}\n\n\tclus.Run()\n}\n\nfunc init() ", "output": "{\n\tvar err error\n\tlogger, err = zap.NewProduction()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package task\n\nimport (\n\t\"context\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/docker/docker/api/types/swarm\"\n\t\"github.com/docker/docker/client\"\n)\n\ntype fakeClient struct {\n\tclient.APIClient\n\tnodeInspectWithRaw func(ref string) (swarm.Node, []byte, error)\n\tserviceInspectWithRaw func(ref string, options types.ServiceInspectOptions) (swarm.Service, []byte, error)\n}\n\nfunc (cli *fakeClient) NodeInspectWithRaw(ctx context.Context, ref string) (swarm.Node, []byte, error) {\n\tif cli.nodeInspectWithRaw != nil {\n\t\treturn cli.nodeInspectWithRaw(ref)\n\t}\n\treturn swarm.Node{}, nil, nil\n}\n\n\n\nfunc (cli *fakeClient) ServiceInspectWithRaw(ctx context.Context, ref string, options types.ServiceInspectOptions) (swarm.Service, []byte, error) ", "output": "{\n\tif cli.serviceInspectWithRaw != nil {\n\t\treturn cli.serviceInspectWithRaw(ref, options)\n\t}\n\treturn swarm.Service{}, nil, nil\n}"} {"input": "package server\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"net/http\"\n\n\t\"github.com/docker/docker/daemon\"\n)\n\n\nfunc (s *Server) newServer(proto, addr string) (serverCloser, error) {\n\tvar (\n\t\terr error\n\t\tl net.Listener\n\t)\n\tswitch proto {\n\tcase \"tcp\":\n\t\tl, err = s.initTcpSocket(addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\tdefault:\n\t\treturn nil, errors.New(\"Invalid protocol format. Windows only supports tcp.\")\n\t}\n\treturn &HttpServer{\n\t\t&http.Server{\n\t\t\tAddr: addr,\n\t\t\tHandler: s.router,\n\t\t},\n\t\tl,\n\t}, nil\n}\n\n\n\nfunc allocateDaemonPort(addr string) error {\n\treturn nil\n}\n\nfunc (s *Server) AcceptConnections(d *daemon.Daemon) ", "output": "{\n\ts.daemon = d\n\tselect {\n\tcase <-s.start:\n\tdefault:\n\t\tclose(s.start)\n\t}\n}"} {"input": "package service\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/mysteriumnetwork/node/identity\"\n\t\"github.com/mysteriumnetwork/node/market\"\n)\n\nvar (\n\tserviceType = \"the-very-awesome-test-service-type\"\n)\n\nfunc TestManager_StartRemovesServiceFromPoolIfServiceCrashes(t *testing.T) {\n\tregistry := NewRegistry()\n\tmockCopy := *serviceMock\n\tmockCopy.onStartReturnError = errors.New(\"some error\")\n\tregistry.Register(serviceType, func(options Options) (Service, market.ServiceProposal, error) {\n\t\treturn &mockCopy, proposalMock, nil\n\t})\n\n\tdiscovery := mockDiscovery{}\n\tdiscoveryFactory := MockDiscoveryFactoryFunc(&discovery)\n\tmanager := NewManager(\n\t\tregistry,\n\t\tMockDialogWaiterFactory,\n\t\tMockDialogHandlerFactory,\n\t\tdiscoveryFactory,\n\t)\n\t_, err := manager.Start(identity.FromAddress(proposalMock.ProviderID), serviceType, struct{}{})\n\tassert.Nil(t, err)\n\n\tdiscovery.Wait()\n\tassert.Len(t, manager.servicePool.List(), 0)\n}\n\n\n\nfunc TestManager_StartDoesNotCrashIfStoppedByUser(t *testing.T) ", "output": "{\n\tregistry := NewRegistry()\n\tmockCopy := *serviceMock\n\tmockCopy.mockProcess = make(chan struct{})\n\tregistry.Register(serviceType, func(options Options) (Service, market.ServiceProposal, error) {\n\t\treturn &mockCopy, proposalMock, nil\n\t})\n\n\tdiscovery := mockDiscovery{}\n\tdiscoveryFactory := MockDiscoveryFactoryFunc(&discovery)\n\tmanager := NewManager(\n\t\tregistry,\n\t\tMockDialogWaiterFactory,\n\t\tMockDialogHandlerFactory,\n\t\tdiscoveryFactory,\n\t)\n\tid, err := manager.Start(identity.FromAddress(proposalMock.ProviderID), serviceType, struct{}{})\n\tassert.Nil(t, err)\n\terr = manager.Stop(id)\n\tassert.Nil(t, err)\n\tdiscovery.Wait()\n\tassert.Len(t, manager.servicePool.List(), 0)\n}"} {"input": "package target\n\nimport (\n\t\"os\"\n)\n\n\n\n\n\n\n\nfunc Path(dst string, sources ...string) (bool, error) {\n\tstat, err := os.Stat(os.ExpandEnv(dst))\n\tif os.IsNotExist(err) {\n\t\treturn true, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn PathNewer(stat.ModTime(), sources...)\n}\n\n\n\n\n\n\n\nfunc Glob(dst string, globs ...string) (bool, error) {\n\tstat, err := os.Stat(os.ExpandEnv(dst))\n\tif os.IsNotExist(err) {\n\t\treturn true, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn GlobNewer(stat.ModTime(), globs...)\n}\n\n\n\n\n\n\n\n\n\nfunc Dir(dst string, sources ...string) (bool, error) ", "output": "{\n\tdst = os.ExpandEnv(dst)\n\tstat, err := os.Stat(dst)\n\tif os.IsNotExist(err) {\n\t\treturn true, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdestTime := stat.ModTime()\n\tif stat.IsDir() {\n\t\tdestTime, err = NewestModTime(dst)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\treturn DirNewer(destTime, sources...)\n}"} {"input": "package connector\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"runtime\"\n\n\t\"github.com/datawire/dlib/dexec\"\n\t\"github.com/datawire/dlib/dlog\"\n)\n\nvar (\n\tnotifyEnabled = false\n)\n\n\n\n\nfunc Notify(c context.Context, message string) ", "output": "{\n\tdlog.Info(c, \"----------------------------------------------------------------------\")\n\tdlog.Infof(c, \"NOTIFY: %s\", message)\n\tdlog.Info(c, \"----------------------------------------------------------------------\")\n\n\tif !notifyEnabled {\n\t\treturn\n\t}\n\n\tvar exe string\n\tvar args []string\n\tswitch runtime.GOOS {\n\tcase \"darwin\":\n\t\tscript := fmt.Sprintf(\"display notification \\\"Telepresence Daemon\\\" with title \\\"%s\\\"\", message)\n\t\texe = \"osascript\"\n\t\targs = []string{\"-e\", script}\n\tcase \"linux\":\n\t\texe = \"notify-send\"\n\t\targs = []string{\"Telepresence Daemon\", message}\n\tdefault:\n\t\treturn\n\t}\n\n\tcmd := dexec.CommandContext(c, exe, args...)\n\tif err := cmd.Run(); err != nil {\n\t\tdlog.Errorf(c, \"ERROR while notifying: %v\", err)\n\t}\n}"} {"input": "package deref\n\n\n\n\n\n\n\nfunc Float32(np *float32) float32 ", "output": "{\n\tif np == nil {\n\t\treturn 0\n\t}\n\treturn *np\n}"} {"input": "package dockerfile2llb\n\nimport (\n\t\"github.com/moby/buildkit/client/llb\"\n\t\"github.com/moby/buildkit/frontend/dockerfile/instructions\"\n\t\"github.com/pkg/errors\"\n)\n\n\n\nfunc dispatchSSH(m *instructions.Mount) (llb.RunOption, error) ", "output": "{\n\tif m.Source != \"\" {\n\t\treturn nil, errors.Errorf(\"ssh does not support source\")\n\t}\n\topts := []llb.SSHOption{llb.SSHID(m.CacheID)}\n\n\tif m.Target != \"\" {\n\t\topts = append(opts, llb.SSHSocketTarget(m.Target))\n\t}\n\n\tif !m.Required {\n\t\topts = append(opts, llb.SSHOptional)\n\t}\n\n\treturn llb.AddSSHSocket(opts...), nil\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc main() {\n\tsc := bufio.NewScanner(os.Stdin)\n\tsc.Split(bufio.ScanWords)\n\tn := nextInt(sc)\n\ta := nextInt(sc)\n\tb := nextInt(sc)\n\n\tanswer := 0\n\tfor i := 1; i <= n; i++ {\n\t\tsum := 0\n\t\tfor _, s := range fmt.Sprintf(\"%d\", i) {\n\t\t\tx, _ := strconv.Atoi(string(s))\n\t\t\tsum = sum + x\n\t\t}\n\t\tif a <= sum && sum <= b {\n\t\t\tanswer = answer + i\n\t\t}\n\t}\n\n\tfmt.Println(answer)\n}\n\n\n\nfunc nextString(sc *bufio.Scanner) string {\n\tsc.Scan()\n\treturn sc.Text()\n}\n\nfunc nextNumber(sc *bufio.Scanner) float64 {\n\tsc.Scan()\n\tf, err := strconv.ParseFloat(sc.Text(), 32)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}\n\n\n\nfunc printArray(xs []int) {\n\tfmt.Println(strings.Trim(fmt.Sprint(xs), \"[]\"))\n}\n\nfunc debugPrintf(format string, a ...interface{}) {\n\tfmt.Fprintf(os.Stderr, format, a...)\n}\n\nfunc nextInt(sc *bufio.Scanner) int ", "output": "{\n\tsc.Scan()\n\tn, err := strconv.Atoi(sc.Text())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn n\n}"} {"input": "package sdl\n\n\nimport \"C\"\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"unsafe\"\n)\n\nconst SamplingRate = 11025\n\nfunc initAudio() {\n\tvar spec C.SDL_AudioSpec\n\tspec.freq = C.int(SamplingRate)\n\tspec.format = C.AUDIO_S8\n\tspec.channels = 1\n\tspec.samples = 512\n\tspec.userdata = nil\n\tC.openAudio(&spec)\n}\n\n\nfunc BufferAudio(sound []int8) {\n\tif len(sound) == 0 {\n\t\treturn\n\t}\n\tmutex.Lock()\n\tC.play((*C.Uint8)(unsafe.Pointer(&sound[0])), C.int(len(sound)))\n\tmutex.Unlock()\n}\n\n\n\nfunc ClearAudioBuffer() {\n\tmutex.Lock()\n\tC.stop()\n\tmutex.Unlock()\n}\n\nfunc Play(input io.Reader) error ", "output": "{\n\tbuf, err := ioutil.ReadAll(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmutex.Lock()\n\tC.play((*C.Uint8)(unsafe.Pointer(&buf[0])), C.int(len(buf)))\n\tmutex.Unlock()\n\treturn nil\n}"} {"input": "package main\n\nimport \"log\"\nimport \"time\"\nimport \"fmt\"\nimport \"gopkg.in/project-iris/iris-go.v1\"\n\ntype H struct {}\n\nfunc (b *H) HandleRequest(req []byte) ([]byte, error) { return req, nil }\nfunc (b *H) HandleTunnel(tun *iris.Tunnel) { }\nfunc (b *H) HandleDrop(reason error) { }\nfunc (b *H) Init(conn *iris.Connection) error { return nil }\n\n\n\nfunc main() {\n service, err := iris.Register(55555, \"bcst\", new(H), nil)\n if err != nil {\n log.Fatalf(\"registration to %v failed\", err)\n }\n defer service.Unregister()\n\n log.Printf(\"waiting...\")\n time.Sleep(100 * time.Second)\n}\n\nfunc (b *H) HandleBroadcast(msg []byte) ", "output": "{\n fmt.Printf(\"message arrived: %v\\n\", string(msg))\n}"} {"input": "package service\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/syncloud/redirect/model\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype ActionsDbStub struct {\n\taction *model.Action\n}\n\nfunc (db *ActionsDbStub) GetAction(_ int64, _ uint64) (*model.Action, error) {\n\treturn db.action, nil\n}\nfunc (db *ActionsDbStub) GetActionByToken(_ string, _ uint64) (*model.Action, error) {\n\treturn db.action, nil\n}\n\nfunc (db *ActionsDbStub) InsertAction(action *model.Action) error {\n\tdb.action = action\n\treturn nil\n}\n\n\n\nfunc (db *ActionsDbStub) DeleteActions(_ int64) error {\n\tdb.action = nil\n\treturn nil\n}\n\nfunc (db *ActionsDbStub) DeleteAction(actionId uint64) error {\n\tdb.action = nil\n\treturn nil\n}\n\nfunc TestUpsert(t *testing.T) {\n\n\tdb := &ActionsDbStub{nil}\n\tactions := NewActions(db)\n\n\tuser := &model.User{Id: 1, Email: \"test@example.com\", PasswordHash: \"pass\", Active: true, UpdateToken: \"token\", Timestamp: time.Now()}\n\taction, err := actions.UpsertActivateAction(user.Id)\n\n\tassert.Nil(t, err)\n\tassert.NotNil(t, action)\n\tassert.NotNil(t, db.action)\n}\n\nfunc (db *ActionsDbStub) UpdateAction(action *model.Action) error ", "output": "{\n\tif db.action != nil {\n\t\tdb.action = action\n\t}\n\treturn nil\n}"} {"input": "package server_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/nanopack/mist/auth\"\n\t\"github.com/nanopack/mist/server\"\n)\n\n\nfunc TestWSStart(t *testing.T) {\n\tfmt.Println(\"Starting WS test...\")\n\n\tauth.Start(\"\")\n\n\tgo func() {\n\t\tif err := server.Start([]string{\"ws://127.0.0.1:8888\"}, \"\"); err != nil {\n\t\t\tt.Fatalf(\"Unexpected error - %s\", err.Error())\n\t\t}\n\t}()\n\t<-time.After(time.Second)\n}\n\n\n\n\nfunc TestWSSStart(t *testing.T) ", "output": "{\n\tfmt.Println(\"Starting WSS test...\")\n\n\tauth.Start(\"\")\n\n\tgo func() {\n\t\tif err := server.Start([]string{\"wss://127.0.0.1:8988\"}, \"\"); err != nil {\n\t\t\tt.Fatalf(\"Unexpected error - %s\", err.Error())\n\t\t}\n\t}()\n\t<-time.After(time.Second)\n}"} {"input": "package geth\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n\ntype Strings struct{ strs []string }\n\n\nfunc (s *Strings) Size() int {\n\treturn len(s.strs)\n}\n\n\n\n\n\nfunc (s *Strings) Set(index int, str string) error {\n\tif index < 0 || index >= len(s.strs) {\n\t\treturn errors.New(\"index out of bounds\")\n\t}\n\ts.strs[index] = str\n\treturn nil\n}\n\n\nfunc (s *Strings) String() string {\n\treturn fmt.Sprintf(\"%v\", s.strs)\n}\n\nfunc (s *Strings) Get(index int) (str string, _ error) ", "output": "{\n\tif index < 0 || index >= len(s.strs) {\n\t\treturn \"\", errors.New(\"index out of bounds\")\n\t}\n\treturn s.strs[index], nil\n}"} {"input": "package templating\n\nimport (\n\t\"bones/config\"\n\t\"bones/web/handlers\"\n\t\"html/template\"\n\t\"io\"\n\t\"log\"\n)\n\nvar templates *template.Template\n\nfunc NewTemplateRenderer() handlers.TemplateRenderer {\n\tif config.Env().IsProduction() {\n\t\treturn &cachingTemplateRenderer{templates}\n\t}\n\n\tlog.Println(\"Using reloading template renderer\")\n\n\treturn &reloadingTemplateRenderer{}\n}\n\ntype cachingTemplateRenderer struct {\n\ttemplates *template.Template\n}\n\n\n\ntype reloadingTemplateRenderer struct{}\n\nfunc (r reloadingTemplateRenderer) RenderTemplate(wr io.Writer, ctx handlers.TemplateContext) error {\n\ttemplates, err := template.ParseGlob(\"./templates/*.html\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn renderWithLayout(templates, wr, ctx.Name(), ctx)\n}\n\nfunc renderWithLayout(t *template.Template, wr io.Writer, name string, data interface{}) error {\n\tfor _, templateName := range []string{\"header.html\", name, \"footer.html\"} {\n\t\terr := t.ExecuteTemplate(wr, templateName, data)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (r cachingTemplateRenderer) RenderTemplate(wr io.Writer, ctx handlers.TemplateContext) error ", "output": "{\n\tif r.templates == nil {\n\t\tvar err error\n\t\tr.templates, err = template.ParseGlob(\"./templates/*.html\")\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn renderWithLayout(r.templates, wr, ctx.Name(), ctx)\n}"} {"input": "package smpeer\n\nimport (\n\t\"testing\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/fiorix/go-diameter/diam/datatype\"\n\t\"github.com/fiorix/go-diameter/diam/sm/smparser\"\n)\n\n\n\nfunc TestFromCEA(t *testing.T) {\n\tcer := &smparser.CEA{\n\t\tOriginHost: datatype.DiameterIdentity(\"foobar\"),\n\t\tOriginRealm: datatype.DiameterIdentity(\"test\"),\n\t}\n\tmeta := FromCEA(cer)\n\tif meta.OriginHost != cer.OriginHost {\n\t\tt.Fatalf(\"Unexpected OriginHost. Want %q, have %q\",\n\t\t\tcer.OriginHost, meta.OriginHost)\n\t}\n\tif meta.OriginRealm != cer.OriginRealm {\n\t\tt.Fatalf(\"Unexpected OriginRealm. Want %q, have %q\",\n\t\t\tcer.OriginRealm, meta.OriginRealm)\n\t}\n\tctx := NewContext(context.Background(), meta)\n\tdata, ok := FromContext(ctx)\n\tif !ok {\n\t\tt.Fatal(\"Metadata not present in this context\")\n\t}\n\tif data != meta {\n\t\tt.Fatalf(\"Unexpected Metadata. Want %#v, have %#v\", meta, data)\n\t}\n}\n\nfunc TestFromCER(t *testing.T) ", "output": "{\n\tcer := &smparser.CER{\n\t\tOriginHost: datatype.DiameterIdentity(\"foobar\"),\n\t\tOriginRealm: datatype.DiameterIdentity(\"test\"),\n\t}\n\tmeta := FromCER(cer)\n\tif meta.OriginHost != cer.OriginHost {\n\t\tt.Fatalf(\"Unexpected OriginHost. Want %q, have %q\",\n\t\t\tcer.OriginHost, meta.OriginHost)\n\t}\n\tif meta.OriginRealm != cer.OriginRealm {\n\t\tt.Fatalf(\"Unexpected OriginRealm. Want %q, have %q\",\n\t\t\tcer.OriginRealm, meta.OriginRealm)\n\t}\n\tctx := NewContext(context.Background(), meta)\n\tdata, ok := FromContext(ctx)\n\tif !ok {\n\t\tt.Fatal(\"Metadata not present in this context\")\n\t}\n\tif data != meta {\n\t\tt.Fatalf(\"Unexpected Metadata. Want %#v, have %#v\", meta, data)\n\t}\n}"} {"input": "package braille\n\n\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestDot(t *testing.T) {\n\tfmt.Println(\"0x28C1 =\", Dot(0x28c1))\n\tfmt.Println(\"0x282D =\", Dot(0x282D))\n\tfmt.Println(\"0x28BF =\", Dot(0x28BF))\n\tfmt.Println(\"0x28FF =\", Dot(0x28FF))\n\n}\n\nfunc TestCode(t *testing.T) {\n\tfmt.Printf(\"1-5-6-7 -> %c\\n\", Rune(1, 5, 6, 7))\n\tfmt.Printf(\"1-2-3-4-5-6-7-8 -> %c\\n\", Rune(1, 2, 3, 4, 5, 6, 7, 8))\n}\n\n\n\nfunc TestAlphabet(t *testing.T) {\n\ts := \"HackTime for Google Hackfair 2012-09-01\"\n\tfmt.Println(s)\n\tfmt.Println(Encode(s))\n}\n\nfunc TestNumber(t *testing.T) ", "output": "{\n\tfor _, c := range \"1234567890\" {\n\t\tfmt.Printf(\"%c : %c\\n\", c, Alphabet(c))\n\t}\n}"} {"input": "package xtest\n\nimport (\n\t\"sync\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\ntype SC struct {\n\tC\n\tsync.WaitGroup\n\tsync.Mutex\n}\n\nfunc (c *SC) Convey(items ...interface{}) {\n\tpanic(\"Convey in SyncConvey Context not supported\")\n}\n\nfunc (c *SC) So(actual interface{},\n\tassert func(actual interface{}, expected ...interface{}) string, expected ...interface{}) {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.C.So(actual, assert, expected)\n}\n\nfunc (c *SC) SoMsg(msg string, actual interface{},\n\tassert func(actual interface{}, expected ...interface{}) string, expected ...interface{}) {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.C.SoMsg(msg, actual, assert, expected...)\n}\n\nfunc (c *SC) Recover() {\n\tif r := recover(); r != nil {\n\t\tif rString, ok := r.(string); ok && rString == \"___FAILURE_HALT___\" {\n\t\t\treturn\n\t\t}\n\t\tpanic(r)\n\t}\n}\n\nfunc Parallel(f, g func(sc *SC)) func(c C) {\n\treturn func(c C) {\n\t\tsc := &SC{C: c}\n\t\tsc.Add(1)\n\t\tgo func() {\n\t\t\tdefer sc.Done()\n\t\t\tdefer sc.Recover()\n\t\t\tg(sc)\n\t\t}()\n\t\tdefer sc.Wait()\n\t\tdefer sc.Recover()\n\t\tf(sc)\n\t}\n}\n\n\n\n\n\n\n\nfunc SoMsgError(msg string, err error, shouldBeError bool) ", "output": "{\n\tif shouldBeError == true {\n\t\tSoMsg(msg, err, ShouldNotBeNil)\n\t} else {\n\t\tSoMsg(msg, err, ShouldBeNil)\n\t}\n}"} {"input": "package repositories\n\n\n\n\nimport (\n\t\"net/http\"\n\n\tmiddleware \"github.com/go-openapi/runtime/middleware\"\n)\n\n\ntype GetOwnerRepositoriesHandlerFunc func(GetOwnerRepositoriesParams) middleware.Responder\n\n\nfunc (fn GetOwnerRepositoriesHandlerFunc) Handle(params GetOwnerRepositoriesParams) middleware.Responder {\n\treturn fn(params)\n}\n\n\ntype GetOwnerRepositoriesHandler interface {\n\tHandle(GetOwnerRepositoriesParams) middleware.Responder\n}\n\n\nfunc NewGetOwnerRepositories(ctx *middleware.Context, handler GetOwnerRepositoriesHandler) *GetOwnerRepositories {\n\treturn &GetOwnerRepositories{Context: ctx, Handler: handler}\n}\n\n\ntype GetOwnerRepositories struct {\n\tContext *middleware.Context\n\tHandler GetOwnerRepositoriesHandler\n}\n\n\n\nfunc (o *GetOwnerRepositories) ServeHTTP(rw http.ResponseWriter, r *http.Request) ", "output": "{\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\tr = rCtx\n\t}\n\tvar Params = NewGetOwnerRepositoriesParams()\n\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params) \n\n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}"} {"input": "package stree\n\n\n\ntype serial struct {\n\tstree\n}\n\n\n\n\nfunc (t *serial) BuildTree() {\n\tpanic(\"BuildTree() not supported for serial data structure\")\n}\n\nfunc (t *serial) Print() {\n\tpanic(\"Print() not supported for serial data structure\")\n}\n\nfunc (t *serial) Tree2Array() []SegmentOverlap {\n\tpanic(\"Tree2Array() not supported for serial data structure\")\n}\n\n\nfunc (t *serial) Query(from, to int) []Interval {\n\tresult := make([]Interval, 0, 10)\n\tfor _, intrvl := range t.base {\n\t\tif !intrvl.Segment.Disjoint(from, to) {\n\t\t\tresult = append(result, intrvl)\n\t\t}\n\t}\n\treturn result\n}\n\n\nfunc (t *serial) QueryArray(from, to []int) []Interval {\n\tresult := make([]Interval, 0, 10)\n\tfor i, fromvalue := range from {\n\t\tresult = append(result, t.Query(fromvalue, to[i])...)\n\t}\n\treturn result\n}\n\nfunc NewSerial() Tree ", "output": "{\n\tt := new(serial)\n\tt.Clear()\n\treturn t\n}"} {"input": "package externalversions\n\nimport (\n\t\"fmt\"\n\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tcache \"k8s.io/client-go/tools/cache\"\n\tv1beta1 \"k8s.io/kube-aggregator/pkg/apis/apiregistration/v1beta1\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}\n\n\nfunc (f *genericInformer) Lister() cache.GenericLister {\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}\n\n\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) ", "output": "{\n\tswitch resource {\n\tcase v1beta1.SchemeGroupVersion.WithResource(\"apiservices\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Apiregistration().V1beta1().APIServices().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}"} {"input": "package logger\n\nimport (\n\t\"testing\"\n\n\t\"github.com/golib/assert\"\n)\n\n\n\nfunc Test_Level_ResolveLevelByName(t *testing.T) {\n\tassertion := assert.New(t)\n\n\tfor level, name := range levels {\n\t\tassertion.Equal(level, ResolveLevelByName(name))\n\t}\n\n\tassertion.Equal(lmin, ResolveLevelByName(\"UNKNOWN\"))\n}\n\nfunc Test_Level_String(t *testing.T) ", "output": "{\n\tassertion := assert.New(t)\n\n\tfor level, s := range levels {\n\t\tassertion.Equal(s, level.String())\n\t}\n\n\tassertion.Equal(\"UNKNOWN\", lmin.String())\n\tassertion.Equal(\"UNKNOWN\", lmax.String())\n}"} {"input": "package core\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype PlatformConfig interface {\n}\n\ntype platformconfig struct {\n\tJsonData []byte\n\tType string `json:\"type\"`\n}\n\n\nfunc (m *platformconfig) UnmarshalJSON(data []byte) error {\n\tm.JsonData = data\n\ttype Unmarshalerplatformconfig platformconfig\n\ts := struct {\n\t\tModel Unmarshalerplatformconfig\n\t}{}\n\terr := json.Unmarshal(data, &s.Model)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Type = s.Model.Type\n\n\treturn err\n}\n\n\nfunc (m *platformconfig) UnmarshalPolymorphicJSON(data []byte) (interface{}, error) {\n\n\tif data == nil || string(data) == \"null\" {\n\t\treturn nil, nil\n\t}\n\n\tvar err error\n\tswitch m.Type {\n\tcase \"AMD_MILAN_BM\":\n\t\tmm := AmdMilanBmPlatformConfig{}\n\t\terr = json.Unmarshal(data, &mm)\n\t\treturn mm, err\n\tdefault:\n\t\treturn *m, nil\n\t}\n}\n\nfunc (m platformconfig) String() string {\n\treturn common.PointerString(m)\n}\n\n\ntype PlatformConfigTypeEnum string\n\n\nconst (\n\tPlatformConfigTypeAmdMilanBm PlatformConfigTypeEnum = \"AMD_MILAN_BM\"\n)\n\nvar mappingPlatformConfigType = map[string]PlatformConfigTypeEnum{\n\t\"AMD_MILAN_BM\": PlatformConfigTypeAmdMilanBm,\n}\n\n\n\n\nfunc GetPlatformConfigTypeEnumValues() []PlatformConfigTypeEnum ", "output": "{\n\tvalues := make([]PlatformConfigTypeEnum, 0)\n\tfor _, v := range mappingPlatformConfigType {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package sliceset\n\nimport (\n\t\"sort\"\n\n\t\"github.com/xtgo/set\"\n)\n\ntype Set []int\n\nfunc (s Set) Len() int { return len(s) }\nfunc (s Set) Less(i, j int) bool { return s[i] < s[j] }\nfunc (s Set) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s Set) Copy() Set { return append(Set(nil), s...) }\n\nfunc (s Set) Union(t Set) Set { return s.Do(set.Union, t) }\nfunc (s Set) Inter(t Set) Set { return s.Do(set.Inter, t) }\n\nfunc (s Set) SymDiff(t Set) Set { return s.Do(set.SymDiff, t) }\nfunc (s Set) IsSub(t Set) bool { return s.DoBool(set.IsSub, t) }\nfunc (s Set) IsSuper(t Set) bool { return s.DoBool(set.IsSuper, t) }\nfunc (s Set) IsInter(t Set) bool { return s.DoBool(set.IsInter, t) }\nfunc (s Set) IsEqual(t Set) bool { return s.DoBool(set.IsEqual, t) }\n\nfunc (s Set) Uniq() Set {\n\tn := set.Uniq(s)\n\treturn s[:n]\n}\n\nfunc (s Set) Do(op set.Op, t Set) Set {\n\tdata := append(s, t...)\n\tn := op(data, len(s))\n\treturn data[:n]\n}\n\ntype BoolOp func(sort.Interface, int) bool\n\nfunc (s Set) DoBool(op BoolOp, t Set) bool {\n\tdata := append(s, t...)\n\treturn op(data, len(s))\n}\n\nfunc (s Set) Diff(t Set) Set ", "output": "{ return s.Do(set.Diff, t) }"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", mainHandle)\n\tif err := http.ListenAndServe(\":8080\", nil); err != nil {\n\t\tlog.Fatal(\"Listen and serve:\", err)\n\t}\n}\n\n\ntype reply struct {\n\tLanguage string `json:\"language\"`\n\tOs string `json:\"software\"`\n\tIP string `json:\"ipaddress\"`\n}\n\n\n\n\n\n\n\n\n\nfunc parseIP(addr string) string {\n\tip := strings.Split(addr, \":\")[0]\n\treturn ip\n}\n\n\nfunc parseLang(h string) string {\n\ttag := strings.Index(h, \"Accept-Language:\")\n\tstart := strings.Index(h[tag:], \"[\")\n\tstart += tag + 1\n\n\tend := strings.Index(h[start:], \"]\")\n\tend += start\n\n\tl := h[start:end]\n\n\treturn strings.Split(l, \";\")[0]\n}\n\n\nfunc parseOs(h string) string {\n\ttag := strings.Index(h, \"User-Agent\")\n\tstart := strings.Index(h[tag:], \"(\")\n\tstart += tag + 1 \n\n\tend := strings.Index(h[start:], \")\")\n\tend += start\n\n\treturn h[start:end]\n}\n\nfunc mainHandle(w http.ResponseWriter, r *http.Request) ", "output": "{\n\theader := r.Header\n\th := fmt.Sprintf(\"%v\", header)\n\taddr := r.RemoteAddr\n\n\tos := parseOs(h)\n\tl := parseLang(h)\n\tip := parseIP(addr)\n\n\treply := reply{Language: l, Os: os, IP: ip}\n\n\tout, err := json.MarshalIndent(reply, \"\", \" \")\n\tif err != nil {\n\t\tfmt.Println(\"Cannot produce json\", err)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"%s\\n\", out)\n}"} {"input": "package bind\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/energicryptocurrency/energi/common\"\n\t\"github.com/energicryptocurrency/energi/core/types\"\n\t\"github.com/energicryptocurrency/energi/log\"\n)\n\n\n\n\n\n\n\nfunc WaitDeployed(ctx context.Context, b DeployBackend, tx *types.Transaction) (common.Address, error) {\n\tif tx.To() != nil {\n\t\treturn common.Address{}, fmt.Errorf(\"tx is not contract creation\")\n\t}\n\treceipt, err := WaitMined(ctx, b, tx)\n\tif err != nil {\n\t\treturn common.Address{}, err\n\t}\n\tif receipt.ContractAddress == (common.Address{}) {\n\t\treturn common.Address{}, fmt.Errorf(\"zero address\")\n\t}\n\tcode, err := b.CodeAt(ctx, receipt.ContractAddress, nil)\n\tif err == nil && len(code) == 0 {\n\t\terr = ErrNoCodeAfterDeploy\n\t}\n\treturn receipt.ContractAddress, err\n}\n\nfunc WaitMined(ctx context.Context, b DeployBackend, tx *types.Transaction) (*types.Receipt, error) ", "output": "{\n\tqueryTicker := time.NewTicker(time.Second)\n\tdefer queryTicker.Stop()\n\n\tlogger := log.New(\"hash\", tx.Hash())\n\tfor {\n\t\treceipt, err := b.TransactionReceipt(ctx, tx.Hash())\n\t\tif receipt != nil {\n\t\t\treturn receipt, nil\n\t\t}\n\t\tif err != nil {\n\t\t\tlogger.Trace(\"Receipt retrieval failed\", \"err\", err)\n\t\t} else {\n\t\t\tlogger.Trace(\"Transaction not yet mined\")\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tcase <-queryTicker.C:\n\t\t}\n\t}\n}"} {"input": "package overcurrent\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\ntype (\n\tNoopBreaker struct{}\n\n\tNoopCollector struct{}\n)\n\nvar defaultCollector = NewNoopCollector()\n\n\nfunc NewNoopBreaker() CircuitBreaker {\n\treturn &NoopBreaker{}\n}\n\nfunc (b *NoopBreaker) Trip() {}\nfunc (b *NoopBreaker) Reset() {}\nfunc (b *NoopBreaker) ShouldTry() bool { return true }\nfunc (b *NoopBreaker) MarkResult(err error) bool { return true }\nfunc (b *NoopBreaker) Call(f BreakerFunc) error { return f(context.Background()) }\n\n\n\nfunc NewNoopCollector() MetricCollector {\n\treturn &NoopCollector{}\n}\n\nfunc (c *NoopCollector) ReportNew(BreakerConfig) {}\nfunc (c *NoopCollector) ReportCount(EventType) {}\nfunc (c *NoopCollector) ReportDuration(EventType, time.Duration) {}\nfunc (c *NoopCollector) ReportState(CircuitState) {}\n\nfunc (b *NoopBreaker) CallAsync(f BreakerFunc) <-chan error ", "output": "{ return nil }"} {"input": "package lsp\n\nimport \"fmt\"\n\n\nconst (\n\tDefaultEpochLimit = 5\n\tDefaultEpochMillis = 2000\n\tDefaultWindowSize = 1\n)\n\n\ntype Params struct {\n\tEpochLimit int\n\n\tEpochMillis int\n\n\tWindowSize int\n}\n\n\nfunc NewParams() *Params {\n\treturn &Params{\n\t\tEpochLimit: DefaultEpochLimit,\n\t\tEpochMillis: DefaultEpochMillis,\n\t\tWindowSize: DefaultWindowSize,\n\t}\n}\n\n\n\n\n\n\n\nfunc (p *Params) String() string ", "output": "{\n\treturn fmt.Sprintf(\"[EpochLimit: %d, EpochMillis: %d, WindowSize: %d]\",\n\t\tp.EpochLimit, p.EpochMillis, p.WindowSize)\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"launchpad.net/gnuflag\"\n\n\t\"launchpad.net/juju-core/cmd\"\n\t\"launchpad.net/juju-core/environs\"\n)\n\n\ntype DestroyEnvironmentCommand struct {\n\tcmd.EnvCommandBase\n\tassumeYes bool\n}\n\n\n\nfunc (c *DestroyEnvironmentCommand) SetFlags(f *gnuflag.FlagSet) {\n\tc.EnvCommandBase.SetFlags(f)\n\tf.BoolVar(&c.assumeYes, \"y\", false, \"Do not ask for confirmation\")\n\tf.BoolVar(&c.assumeYes, \"yes\", false, \"\")\n}\n\nfunc (c *DestroyEnvironmentCommand) Run(ctx *cmd.Context) error {\n\tenviron, err := environs.NewFromName(c.EnvName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !c.assumeYes {\n\t\tvar answer string\n\t\tfmt.Fprintf(ctx.Stdout, destroyEnvMsg[1:], environ.Name(), environ.Config().Type())\n\t\tfmt.Fscanln(ctx.Stdin, &answer) \n\t\tanswer = strings.ToLower(answer)\n\t\tif answer != \"y\" && answer != \"yes\" {\n\t\t\treturn errors.New(\"Environment destruction aborted\")\n\t\t}\n\t}\n\n\treturn environ.Destroy(nil)\n}\n\nconst destroyEnvMsg = `\nWARNING: this command will destroy the %q environment (type: %s)\nThis includes all machines, services, data and other resources.\n\nContinue [y/N]? `\n\nfunc (c *DestroyEnvironmentCommand) Info() *cmd.Info ", "output": "{\n\treturn &cmd.Info{\n\t\tName: \"destroy-environment\",\n\t\tPurpose: \"terminate all machines and other associated resources for an environment\",\n\t}\n}"} {"input": "package pools\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestRPCPool(t *testing.T) {\n\tt.Parallel()\n\n\tpool := NewRPCPool(1, time.Millisecond*100, nil)\n\n\terr := pool.Acquire(context.Background())\n\trequire.NoError(t, err)\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*5)\n\terr = pool.Acquire(ctx)\n\tcancel()\n\tassert.Error(t, err)\n\n\tpool.Release()\n\terr = pool.Acquire(context.Background())\n\trequire.NoError(t, err)\n\n\tt.Run(\"context timeout exceeded\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)\n\t\tdefer cancel()\n\n\t\terr := pool.Acquire(ctx)\n\t\tassert.Error(t, err)\n\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\tdefault:\n\t\t\tassert.Fail(t, \"calling context should be done after failed Acquire\")\n\t\t}\n\t})\n\n\tt.Run(\"pool timeout exceeded\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*500)\n\t\tdefer cancel()\n\n\t\terr := pool.Acquire(ctx)\n\t\tassert.Error(t, err)\n\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tassert.Fail(t, \"calling context should not be done after failed Acquire\")\n\t\tdefault:\n\t\t}\n\t})\n}\n\n\n\nfunc BenchmarkRPCPoolAllocs(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tNewRPCPool(1000, 0, nil)\n\t}\n}"} {"input": "package plugin\n\nimport \"github.com/docker/docker/api/server/router\"\n\n\ntype pluginRouter struct {\n\tbackend Backend\n\troutes []router.Route\n}\n\n\n\n\n\nfunc (r *pluginRouter) Routes() []router.Route {\n\treturn r.routes\n}\n\nfunc (r *pluginRouter) initRoutes() {\n\tr.routes = []router.Route{\n\t\trouter.NewGetRoute(\"/plugins\", r.listPlugins),\n\t\trouter.NewGetRoute(\"/plugins/{name:.*}/json\", r.inspectPlugin),\n\t\trouter.NewGetRoute(\"/plugins/privileges\", r.getPrivileges),\n\t\trouter.NewDeleteRoute(\"/plugins/{name:.*}\", r.removePlugin),\n\t\trouter.NewPostRoute(\"/plugins/{name:.*}/enable\", r.enablePlugin), \n\t\trouter.NewPostRoute(\"/plugins/{name:.*}/disable\", r.disablePlugin),\n\t\trouter.NewPostRoute(\"/plugins/pull\", r.pullPlugin),\n\t\trouter.NewPostRoute(\"/plugins/{name:.*}/push\", r.pushPlugin),\n\t\trouter.NewPostRoute(\"/plugins/{name:.*}/set\", r.setPlugin),\n\t\trouter.NewPostRoute(\"/plugins/create\", r.createPlugin),\n\t}\n}\n\nfunc NewRouter(b Backend) router.Router ", "output": "{\n\tr := &pluginRouter{\n\t\tbackend: b,\n\t}\n\tr.initRoutes()\n\treturn r\n}"} {"input": "package gamejam\n\ntype SceneID int\n\ntype Scene interface {\n\tAddComponent(c Component)\n\tLoad(r Resources) (err error)\n\tUnload(r Resources) (err error)\n\tRender()\n\tUpdate(mgr SceneManager)\n\tSetSceneID(id SceneID)\n\tSceneID() SceneID\n}\n\ntype BaseScene struct {\n\tcomponents map[ComponentID]Component\n\tid SceneID\n}\n\nfunc NewBaseScene() *BaseScene {\n\treturn &BaseScene{\n\t\tcomponents: map[ComponentID]Component{},\n\t}\n}\n\n\n\nfunc (s *BaseScene) Load(r Resources) (err error) {\n\treturn\n}\n\nfunc (s *BaseScene) Render() {\n}\n\nfunc (s *BaseScene) SetSceneID(id SceneID) {\n\ts.id = id\n}\n\nfunc (s *BaseScene) SceneID() SceneID {\n\treturn s.id\n}\n\nfunc (s *BaseScene) Unload(r Resources) (err error) {\n\tvar (\n\t\tid ComponentID\n\t\tc Component\n\t)\n\tfor id, c = range s.components {\n\t\ts.components[id] = nil\n\t\tc.Delete()\n\t}\n\treturn\n}\n\nfunc (s *BaseScene) Update(mgr SceneManager) {\n}\n\nfunc (s *BaseScene) AddComponent(c Component) ", "output": "{\n\tc.SetScene(s)\n\ts.components[c.GetID()] = c\n}"} {"input": "package slapi_test\n\nimport (\n\t\"log\"\n\n\tsoftlayer_account \"github.com/sudorandom/softlayer-go-gen/methods/softlayer_account\"\n\tgentypes \"github.com/sudorandom/softlayer-go-gen/types\"\n\tslapi \"github.com/sudorandom/softlayer-go/slapi\"\n)\n\nvar (\n\tusername = \"INSERT_USERNAME\"\n\tapiKey = \"INSERT_API_KEY\"\n)\n\n\nfunc ExampleClient_Call_basicAPICall() {\n\tclient := slapi.Client{\n\t\tEndpoint: \"https://api.softlayer.com/rest/v3.1/\",\n\t\tAuth: slapi.BasicAuth{Username: username, APIKey: apiKey},\n\t}\n\n\treq := softlayer_account.GetObject()\n\treq.Mask = `mask[id,companyName]`\n\n\tbasicAccount := &gentypes.SoftLayer_Account{}\n\terr := client.Call(req, basicAccount)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Println(\"Basic:\")\n\tlog.Println(basicAccount.Id)\n\tlog.Println(basicAccount.CompanyName)\n}\n\n\n\n\nfunc ExampleClient_Call_customAPICall() ", "output": "{\n\tclient := slapi.Client{\n\t\tEndpoint: \"https://api.softlayer.com/rest/v3.1/\",\n\t\tAuth: slapi.BasicAuth{Username: username, APIKey: apiKey},\n\t}\n\n\treq := softlayer_account.GetObject()\n\treq.Mask = `mask[id,virtualGuests,companyName]`\n\n\ttype myCustomAccount struct {\n\t\tID int64 `json:\"id\"`\n\t\tCompanyName string `json:\"companyName\"`\n\n\t\tVirtualGuests []*gentypes.SoftLayer_Virtual_Guest `json:\"virtualGuests\"`\n\t}\n\n\tcustomAccount := &myCustomAccount{}\n\terr := client.Call(req, customAccount)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Println(\"Custom Extended:\")\n\tlog.Println(customAccount.ID)\n\tlog.Println(customAccount.CompanyName)\n\tlog.Println(customAccount.VirtualGuests)\n}"} {"input": "package endpoints\n\nimport \"context\"\n\nimport \"github.com/go-kit/kit/endpoint\"\n\nimport \"github.com/go-kit/kit/cmd/kitgen/testdata/foo/default/service\"\n\ntype BarRequest struct {\n\tI int\n\tS string\n}\ntype BarResponse struct {\n\tS string\n\tErr error\n}\n\n\n\ntype Endpoints struct {\n\tBar endpoint.Endpoint\n}\n\nfunc MakeBarEndpoint(f service.FooService) endpoint.Endpoint ", "output": "{\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\treq := request.(BarRequest)\n\t\ts, err := f.Bar(ctx, req.I, req.S)\n\t\treturn BarResponse{S: s, Err: err}, nil\n\t}\n}"} {"input": "package etcd2\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/coreos/etcd/client\"\n\t\"golang.org/x/net/context\"\n)\n\n\ntype Etcd2Connect struct {\n\tetcd2 client.Client\n}\n\n\nfunc NewEtcd2Connect(etcd2EndPoint string) (*Etcd2Connect, error) {\n\tc, err := client.New(client.Config{\n\t\tEndpoints: []string{fmt.Sprintf(\"http://%s\", etcd2EndPoint)},\n\t\tTransport: client.DefaultTransport,\n\t\tHeaderTimeoutPerRequest: time.Second,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Etcd2Connect{etcd2: c}, nil\n}\n\n\nfunc (e *Etcd2Connect) Set(data map[string]string) error {\n\tkapi := client.NewKeysAPI(e.etcd2)\n\tfor k, v := range data {\n\t\tif _, err := kapi.Set(context.Background(), k, v, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (e *Etcd2Connect) Make(data map[string]string) error {\n\tkapi := client.NewKeysAPI(e.etcd2)\n\topts := &client.SetOptions{PrevExist: client.PrevNoExist}\n\tfor k, v := range data {\n\t\tif _, err := kapi.Set(context.Background(), k, v, opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\nfunc (e *Etcd2Connect) Get(data map[string]string) (map[string]string, error) ", "output": "{\n\tkapi := client.NewKeysAPI(e.etcd2)\n\tresult := make(map[string]string)\n\tfor k := range data {\n\t\tresp, err := kapi.Get(context.Background(), k, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult[k] = resp.Node.Value\n\t}\n\treturn result, nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/kataras/iris\"\n\t\"github.com/kataras/iris/mvc\"\n)\n\nfunc main() {\n\tapp := iris.New()\n\tapp.Get(\"/\", func(ctx iris.Context) { ctx.Redirect(\"/example\") })\n\n\tm := mvc.New(app.Party(\"/example\"))\n\n\tm.Router.SetExecutionRules(iris.ExecutionRules{\n\t\tDone: iris.ExecutionOptions{Force: true}, \n\t})\n\tm.Router.Done(doneHandler)\n\n\tm.Handle(&exampleController{})\n\n\tapp.Run(iris.Addr(\":8080\"))\n}\n\nfunc doneHandler(ctx iris.Context) {\n\tctx.WriteString(\"\\nFrom Done Handler\")\n}\n\ntype exampleController struct{}\n\n\n\nfunc (c *exampleController) Get() string ", "output": "{\n\treturn \"From Main Handler\"\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/client-go/informers\"\n\tclientset \"k8s.io/client-go/kubernetes\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/quota\"\n\t\"k8s.io/kubernetes/pkg/quota/generic\"\n)\n\n\nfunc listConfigMapsByNamespaceFuncUsingClient(kubeClient clientset.Interface) generic.ListFuncByNamespace {\n\treturn func(namespace string, options metav1.ListOptions) ([]runtime.Object, error) {\n\t\titemList, err := kubeClient.CoreV1().ConfigMaps(namespace).List(options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresults := make([]runtime.Object, 0, len(itemList.Items))\n\t\tfor i := range itemList.Items {\n\t\t\tresults = append(results, &itemList.Items[i])\n\t\t}\n\t\treturn results, nil\n\t}\n}\n\n\n\n\n\nfunc NewConfigMapEvaluator(kubeClient clientset.Interface, f informers.SharedInformerFactory) quota.Evaluator ", "output": "{\n\tlistFuncByNamespace := listConfigMapsByNamespaceFuncUsingClient(kubeClient)\n\tif f != nil {\n\t\tlistFuncByNamespace = generic.ListResourceUsingInformerFunc(f, v1.SchemeGroupVersion.WithResource(\"configmaps\"))\n\t}\n\treturn &generic.ObjectCountEvaluator{\n\t\tAllowCreateOnUpdate: false,\n\t\tInternalGroupKind: api.Kind(\"ConfigMap\"),\n\t\tResourceName: api.ResourceConfigMaps,\n\t\tListFuncByNamespace: listFuncByNamespace,\n\t}\n}"} {"input": "package income\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc Test_Blacklist(t *testing.T) ", "output": "{\n\tConvey(\"Blacklist\", t, func() {\n\t\t_, _, err := d.Blacklist(context.Background(), 0, 2000)\n\t\tSo(err, ShouldBeNil)\n\t})\n}"} {"input": "package daemon\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\tbgp \"github.com/gopher-net/gopher-net/third-party/github.com/gobgp/packet\"\n)\n\nfunc NewRibEntry() RibEntry {\n\trib := RibEntry{\n\t\tNextHop: nil,\n\t\tNetworkSegment: 0,\n\t\tDestIpPrefix: nil,\n\t\tLength: 0,\n\t\tGateway: nil,\n\t}\n\treturn rib\n}\n\n\ntype RibEntry struct {\n\tNextHop net.IP\n\tNetworkSegment int\n\tDestIpPrefix net.IP\n\tLength int\n\tGateway net.IP\n\tInterface net.IP\n\tMetric int\n}\n\n\ntype RoutingTable struct {\n\tRib []RibEntry\n}\n\n\nfunc (r *RoutingTable) Add(entry *RibEntry) {\n\tr.Rib = append(r.Rib, *entry)\n}\n\n\nfunc (r *RoutingTable) Print() string {\n\tresult := fmt.Sprintf(\"%+v\\n\", r.Rib)\n\treturn result\n}\n\n\n\nfunc Ipv4PrefixConcat(p *bgp.NLRInfo) string ", "output": "{\n\treturn fmt.Sprintf(\"%v/%v\", p.Prefix.String(), p.Length)\n}"} {"input": "package cmd\n\nimport (\n\t\"time\"\n\n\t\"github.com/codegangsta/cli\"\n)\n\nfunc stringFlag(name, value, usage string) cli.StringFlag {\n\treturn cli.StringFlag{\n\t\tName: name,\n\t\tValue: value,\n\t\tUsage: usage,\n\t}\n}\n\nfunc boolFlag(name, usage string) cli.BoolFlag {\n\treturn cli.BoolFlag{\n\t\tName: name,\n\t\tUsage: usage,\n\t}\n}\n\n\n\nfunc durationFlag(name string, value time.Duration, usage string) cli.DurationFlag {\n\treturn cli.DurationFlag{\n\t\tName: name,\n\t\tValue: value,\n\t\tUsage: usage,\n\t}\n}\n\nfunc intFlag(name string, value int, usage string) cli.IntFlag ", "output": "{\n\treturn cli.IntFlag{\n\t\tName: name,\n\t\tValue: value,\n\t\tUsage: usage,\n\t}\n}"} {"input": "package veneur\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/hashicorp/consul/api\"\n)\n\n\n\ntype Consul struct {\n\tConsulHealth *api.Health\n}\n\n\n\n\n\n\nfunc (c *Consul) GetDestinationsForService(serviceName string) ([]string, error) {\n\tserviceEntries, _, err := c.ConsulHealth.Service(serviceName, \"\", true, &api.QueryOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnumHosts := len(serviceEntries)\n\tif numHosts < 1 {\n\t\treturn nil, errors.New(\"Received no hosts from Consul\")\n\t}\n\thosts := make([]string, numHosts)\n\tfor index, se := range serviceEntries {\n\t\thosts[index] = fmt.Sprintf(\"%s:%d\", se.Node.Address, se.Service.Port)\n\t}\n\n\treturn hosts, nil\n}\n\nfunc NewConsul(config *api.Config) (*Consul, error) ", "output": "{\n\tconsulClient, err := api.NewClient(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Consul{\n\t\tConsulHealth: consulClient.Health(),\n\t}, nil\n}"} {"input": "package host\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/object\"\n\t\"github.com/vmware/govmomi/vim25/mo\"\n)\n\ntype remove struct {\n\t*flags.HostSystemFlag\n}\n\nfunc init() {\n\tcli.Register(\"host.remove\", &remove{})\n}\n\nfunc (cmd *remove) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)\n\tcmd.HostSystemFlag.Register(ctx, f)\n}\n\nfunc (cmd *remove) Process(ctx context.Context) error {\n\tif err := cmd.HostSystemFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (cmd *remove) Usage() string {\n\treturn \"HOST...\"\n}\n\nfunc (cmd *remove) Description() string {\n\treturn `Remove hosts from vCenter.`\n}\n\n\n\nfunc (cmd *remove) Run(ctx context.Context, f *flag.FlagSet) error {\n\thosts, err := cmd.HostSystems(f.Args())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, host := range hosts {\n\t\terr = cmd.Remove(ctx, host)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (cmd *remove) Remove(ctx context.Context, host *object.HostSystem) error ", "output": "{\n\tvar h mo.HostSystem\n\terr := host.Properties(ctx, host.Reference(), []string{\"parent\"}, &h)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tremove := host.Destroy\n\n\tif h.Parent.Type == \"ComputeResource\" {\n\t\tremove = object.NewComputeResource(host.Client(), *h.Parent).Destroy\n\t}\n\n\ttask, err := remove(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger := cmd.ProgressLogger(fmt.Sprintf(\"%s removing... \", host.InventoryPath))\n\tdefer logger.Wait()\n\n\t_, err = task.WaitForResult(ctx, logger)\n\treturn err\n}"} {"input": "package tasks\n\nimport (\n\t\"strings\"\n\t\"os/exec\"\n\t\"log\"\n)\n\n\nconst (\n\tPYTHON_COMMAND_ARG = \"command\"\n\tPYTHON_ARGS_ARG = \"args\"\n)\n\ntype Python struct {\n\targs\t\t[]string\n}\n\nfunc (t *Python) Configure(args map[string]string) statusCode {\n\tval, ok := args[PYTHON_COMMAND_ARG]\n\n\tif !ok {\n\t\treturn StatusConfigurationError\n\t}\n\tt.args = make([]string, 0)\n\tt.args = append(t.args, val)\n\n\tval, ok = args[PYTHON_ARGS_ARG]\n\tif !ok {\n\t\treturn StatusConfigurationError\n\t}\n\tt.args = append(t.args, strings.Split(val, \" \")...)\n\n\treturn StatusOk\n}\n\n\n\nfunc (t *Python) GetName() string {\n\treturn \"python\"\n}\n\nfunc (t *Python) Execute() statusCode ", "output": "{\n\terr := exec.Command(\"python2.7\", t.args...).Run()\n\n\tif err != nil {\n\t\tlog.Printf(\"execute error: %s\\n\", err.Error())\n\t\treturn StatusExecutionError\n\t}\n\n\treturn StatusOk\n}"} {"input": "package cli\n\nimport \"github.com/scaleway/scaleway-cli/pkg/commands\"\n\nvar cmdStop = &Command{\n\tExec: runStop,\n\tUsageLine: \"stop [OPTIONS] SERVER [SERVER...]\",\n\tDescription: \"Stop a running server\",\n\tHelp: \"Stop a running server.\",\n\tExamples: `\n $ scw stop my-running-server my-second-running-server\n $ scw stop -t my-running-server my-second-running-server\n $ scw stop $(scw ps -q)\n $ scw stop $(scw ps | grep mysql | awk '{print $1}')\n $ scw stop server && stop wait server\n $ scw stop -w server\n`,\n}\n\n\n\n\nvar stopT bool \nvar stopHelp bool \nvar stopW bool \n\nfunc runStop(cmd *Command, rawArgs []string) error {\n\tif stopHelp {\n\t\treturn cmd.PrintUsage()\n\t}\n\tif len(rawArgs) < 1 {\n\t\treturn cmd.PrintShortUsage()\n\t}\n\n\targs := commands.StopArgs{\n\t\tTerminate: stopT,\n\t\tWait: stopW,\n\t\tServers: rawArgs,\n\t}\n\tctx := cmd.GetContext(rawArgs)\n\treturn commands.RunStop(ctx, args)\n}\n\nfunc init() ", "output": "{\n\tcmdStop.Flag.BoolVar(&stopT, []string{\"t\", \"-terminate\"}, false, \"Stop and trash a server with its volumes\")\n\tcmdStop.Flag.BoolVar(&stopHelp, []string{\"h\", \"-help\"}, false, \"Print usage\")\n\tcmdStop.Flag.BoolVar(&stopW, []string{\"w\", \"-wait\"}, false, \"Synchronous stop. Wait for SSH to be ready\")\n}"} {"input": "package ip\n\n\ntype Veth struct {\n\tLink\n\tPeerName string\n}\n\n\n\n\n\nfunc (veth *Veth) Add() error {\n\treturn veth.Link.add(\"veth\", veth.additionalArgs())\n}\n\nfunc (veth *Veth) additionalArgs() []string ", "output": "{\n\targs := []string{}\n\tif veth.PeerName != \"\" {\n\t\targs = append(args, \"peer\", \"name\", veth.PeerName)\n\t}\n\treturn args\n}"} {"input": "package transport \n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\n\n\ntype MockReporter struct {\n\twgMetricsProcessed sync.WaitGroup\n}\n\nvar _ Reporter = (*MockReporter)(nil)\n\n\nfunc NewMockReporter(expectedOnMetricsProcessedCalls int) *MockReporter {\n\tm := MockReporter{}\n\tm.wgMetricsProcessed.Add(expectedOnMetricsProcessedCalls)\n\treturn &m\n}\n\nfunc (m *MockReporter) OnDataReceived(ctx context.Context) context.Context {\n\treturn ctx\n}\n\nfunc (m *MockReporter) OnTranslationError(ctx context.Context, err error) {\n}\n\nfunc (m *MockReporter) OnMetricsProcessed(ctx context.Context, numReceivedMetricPoints int, err error) {\n\tm.wgMetricsProcessed.Done()\n}\n\nfunc (m *MockReporter) OnDebugf(template string, args ...interface{}) {\n}\n\n\n\n\n\nfunc (m *MockReporter) WaitAllOnMetricsProcessedCalls() ", "output": "{\n\tm.wgMetricsProcessed.Wait()\n}"} {"input": "package polly\n\nimport (\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/client\"\n\t\"github.com/aws/aws-sdk-go/aws/client/metadata\"\n\t\"github.com/aws/aws-sdk-go/aws/request\"\n\t\"github.com/aws/aws-sdk-go/aws/signer/v4\"\n\t\"github.com/aws/aws-sdk-go/private/protocol/restjson\"\n)\n\n\n\n\n\n\n\ntype Polly struct {\n\t*client.Client\n}\n\n\nvar initClient func(*client.Client)\n\n\nvar initRequest func(*request.Request)\n\n\nconst (\n\tServiceName = \"polly\" \n\tEndpointsID = ServiceName \n)\n\n\n\n\n\n\n\n\n\n\n\nfunc New(p client.ConfigProvider, cfgs ...*aws.Config) *Polly {\n\tc := p.ClientConfig(EndpointsID, cfgs...)\n\treturn newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName)\n}\n\n\n\n\n\n\nfunc (c *Polly) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\tif initRequest != nil {\n\t\tinitRequest(req)\n\t}\n\n\treturn req\n}\n\nfunc newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *Polly ", "output": "{\n\tsvc := &Polly{\n\t\tClient: client.New(\n\t\t\tcfg,\n\t\t\tmetadata.ClientInfo{\n\t\t\t\tServiceName: ServiceName,\n\t\t\t\tSigningName: signingName,\n\t\t\t\tSigningRegion: signingRegion,\n\t\t\t\tEndpoint: endpoint,\n\t\t\t\tAPIVersion: \"2016-06-10\",\n\t\t\t},\n\t\t\thandlers,\n\t\t),\n\t}\n\n\tsvc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)\n\tsvc.Handlers.Build.PushBackNamed(restjson.BuildHandler)\n\tsvc.Handlers.Unmarshal.PushBackNamed(restjson.UnmarshalHandler)\n\tsvc.Handlers.UnmarshalMeta.PushBackNamed(restjson.UnmarshalMetaHandler)\n\tsvc.Handlers.UnmarshalError.PushBackNamed(restjson.UnmarshalErrorHandler)\n\n\tif initClient != nil {\n\t\tinitClient(svc.Client)\n\t}\n\n\treturn svc\n}"} {"input": "package main\n\nimport \"C\"\nimport \"fmt\"\n\n\n\n\nfunc main() {}\n\nfunc dict_input(dict map[string]string) ", "output": "{\n\tfor key, value := range dict {\n\t\tfmt.Printf(\"Key is %s -- Value is %s\\n\", key, value)\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/codahale/hdrhistogram\"\n\t\"github.com/fluxio/metricd/pb\"\n)\n\nconst LOWEST_VALUE = 0\nconst HIGHEST_VALUE = 1e7\n\n\n\nconst DIGITS_OF_PRECISION = 2\n\ntype histAggregator struct {\n\tname string\n\tindexedLabels map[string]string\n\tunindexedLabels map[string]string\n\th *hdrhistogram.Histogram\n\tm sync.Mutex\n}\n\nfunc (a *histAggregator) AddValue(value float64, ts int64) {\n\ta.m.Lock()\n\tdefer a.m.Unlock()\n\n\tif a.h == nil {\n\t\ta.h = hdrhistogram.New(LOWEST_VALUE, HIGHEST_VALUE, DIGITS_OF_PRECISION)\n\t}\n\ta.h.RecordValue(int64(value))\n}\n\n\n\n\n\n\n\n\nfunc (a *histAggregator) GetAggregations() []*pb.Metric {\n\ta.m.Lock()\n\tdefer a.m.Unlock()\n\n\tvar res []*pb.Metric\n\tif a.h != nil && a.h.TotalCount() != 0 {\n\t\tfor _, q := range []float64{0, 50, 90, 95, 99, 100} {\n\t\t\tres = append(res, &pb.Metric{\n\t\t\t\tName: a.name + \"_p\" + strconv.Itoa(int(q)),\n\t\t\t\tIndexedLabels: a.indexedLabels,\n\t\t\t\tUnindexedLabels: a.unindexedLabels,\n\t\t\t\tValue: &pb.Metric_DoubleValue{float64(a.h.ValueAtQuantile(q))},\n\t\t\t\tTs: time.Now().UnixNano(),\n\t\t\t})\n\t\t}\n\t\ta.h = nil\n\t}\n\treturn res\n}\n\n\n\nfunc NewHistAggregator(name string, indexedLabels, unindexedLabels map[string]string) aggregatorUnit ", "output": "{\n\treturn &histAggregator{\n\t\tname: name,\n\t\tindexedLabels: indexedLabels,\n\t\tunindexedLabels: unindexedLabels,\n\t}\n}"} {"input": "package transport\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n\tboshlog \"github.com/cloudfoundry/bosh-utils/logger\"\n\n\tbslcdisp \"bosh-softlayer-cpi/api/dispatcher\"\n)\n\nconst cliLogTag = \"CLI\"\n\ntype CLI struct {\n\tin io.Reader\n\tout io.Writer\n\tdispatcher bslcdisp.Dispatcher\n\tlogger boshlog.Logger\n}\n\n\n\nfunc (t CLI) ServeOnce() error {\n\treqBytes, err := ioutil.ReadAll(t.in)\n\tif err != nil {\n\t\tt.logger.Error(cliLogTag, \"Failed reading from IN: %s\", err)\n\t\treturn bosherr.WrapError(err, \"Reading from IN\")\n\t}\n\n\trespBytes := t.dispatcher.Dispatch(reqBytes)\n\n\t_, err = t.out.Write(respBytes)\n\tif err != nil {\n\t\tt.logger.Error(cliLogTag, \"Failed writing to OUT: %s\", err)\n\t\treturn bosherr.WrapError(err, \"Writing to OUT\")\n\t}\n\n\treturn nil\n}\n\nfunc NewCLI(\n\tin io.Reader,\n\tout io.Writer,\n\tdispatcher bslcdisp.Dispatcher,\n\tlogger boshlog.Logger,\n) CLI ", "output": "{\n\treturn CLI{\n\t\tin: in,\n\t\tout: out,\n\t\tdispatcher: dispatcher,\n\t\tlogger: logger,\n\t}\n}"} {"input": "package ulule\n\nimport (\n\t\"crypto/tls\"\n\t\"net/http\"\n)\n\n\n\ntype Client struct {\n\tusername string\n\tuserid string\n\tapikey string\n\taccessToken string\n\tpassword string\n\n\thttpClient *http.Client\n}\n\n\n\nfunc ClientWithUsernameAndApiKey(username, apikey string) *Client {\n\tclientAPI := &Client{\n\t\tusername: username,\n\t\tapikey: apikey,\n\t}\n\tclientAPI.initHttpClient()\n\treturn clientAPI\n}\n\n\nfunc ClientWithToken(accessToken string) *Client {\n\tclientAPI := &Client{\n\t\taccessToken: accessToken,\n\t}\n\tclientAPI.initHttpClient()\n\treturn clientAPI\n}\n\n\n\n\n\nfunc (c *Client) initHttpClient() ", "output": "{\n\ttransport := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tc.httpClient = &http.Client{Transport: transport}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"time\"\n)\n\nvar ACTION_POTENTIAL_THRESHOLD int = 30\nvar DELAY_BETWEEN_FIRINGS time.Duration = 10\nvar SIGNAL_BUFFER_SIZE = 2048\n\ntype Neuron struct {\n\ttag string\n\tdendrite chan int \n\tsynapses []Synapse \n\tpotential int\n}\n\nfunc (n *Neuron) Fire() {\n\tlog.Println(n.tag, \"Fired\")\n\tn.potential = 0\n\tfor _, synapse := range n.synapses {\n\t\tselect {\n\t\tcase synapse.channel <- synapse.weight:\n\t\tdefault:\n\t\t\tlog.Println(\"Signal from\", n.tag, \"dropped\")\n\t\t}\n\t\ttime.Sleep(DELAY_BETWEEN_FIRINGS * time.Millisecond)\n\t}\n}\n\nfunc (n *Neuron) HasReachedThreshold() bool {\n\treturn n.potential > ACTION_POTENTIAL_THRESHOLD\n}\n\nfunc (n *Neuron) Listen() {\n\tfor actionPotential := range n.dendrite {\n\t\tn.potential += actionPotential\n\t\tif n.HasReachedThreshold() {\n\t\t\tn.Fire()\n\t\t}\n\t}\n}\n\n\n\nfunc NewNeuron(tag string) Neuron {\n\treturn Neuron{tag, make(chan int, SIGNAL_BUFFER_SIZE), []Synapse{}, 0}\n}\n\nfunc (n *Neuron) AddSynapse(destination *Neuron, weight int) ", "output": "{\n\tn.synapses = append(n.synapses, Synapse{destination.dendrite, weight})\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n)\n\ntype SecurityBulletin struct {\n\tId string `json:\"id\"`\n\tAppliesToVersion string `json:\"applies_to_version\"`\n}\n\ntype SecurityBulletins []SecurityBulletin\n\nfunc (sb *SecurityBulletin) ToJson() string {\n\tb, _ := json.Marshal(sb)\n\treturn string(b)\n}\n\n\n\nfunc (sb SecurityBulletins) ToJson() string {\n\tb, err := json.Marshal(sb)\n\tif err != nil {\n\t\treturn \"[]\"\n\t}\n\treturn string(b)\n}\n\nfunc SecurityBulletinsFromJson(data io.Reader) SecurityBulletins {\n\tvar o SecurityBulletins\n\tjson.NewDecoder(data).Decode(&o)\n\treturn o\n}\n\nfunc SecurityBulletinFromJson(data io.Reader) *SecurityBulletin ", "output": "{\n\tvar o *SecurityBulletin\n\tjson.NewDecoder(data).Decode(&o)\n\treturn o\n}"} {"input": "package endpoints\n\nimport (\n\t\"net\"\n)\n\n\nfunc localCreateListener(path string, group string) (net.Listener, error) {\n\terr := CheckAlreadyRunning(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = socketUnixRemoveStale(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlistener, err := socketUnixListen(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = localSetAccess(path, group)\n\tif err != nil {\n\t\tlistener.Close()\n\t\treturn nil, err\n\t}\n\n\treturn listener, nil\n}\n\n\n\n\n\n\nfunc localSetAccess(path string, group string) error ", "output": "{\n\terr := socketUnixSetPermissions(path, 0660)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = socketUnixSetOwnership(path, group)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package runtime\n\nimport (\n\t\"encoding/gob\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\nvar (\n\tgoatsSettings *GoatsSettings\n)\n\n\n\nfunc InitGoats(settings *GoatsSettings) {\n\tif settings == nil {\n\t\tgoatsSettings = NewGoatsSettings()\n\t} else {\n\t\tgoatsSettings = settings\n\t}\n}\n\nfunc DecodeRpcRequestOrFail(input io.Reader, settings *TemplateSettings, args interface{}) {\n\tdecoder := gob.NewDecoder(input)\n\terr := decoder.Decode(settings)\n\tif err == nil {\n\t\terr = decoder.Decode(args)\n\t}\n\tif err != nil {\n\t\tfmt.Fprint(os.Stderr, err)\n\t\tos.Exit(2)\n\t}\n}\n\nfunc NewGoatsSettings() *GoatsSettings ", "output": "{\n\treturn &GoatsSettings{}\n}"} {"input": "package mock\n\nimport (\n\t\"crypto/rand\"\n\t\"fmt\"\n)\n\ntype constReader struct {\n\tnonce string\n}\n\n\n\n\n\nfunc WithConstRandReader(testNonce string, f func()) {\n\n\toriginal := rand.Reader\n\trand.Reader = &constReader{nonce: testNonce}\n\n\tf()\n\n\trand.Reader = original\n\n}\n\ntype errorReader struct {\n\terr string\n}\n\nfunc (r *errorReader) Read(p []byte) (n int, err error) {\n\treturn 0, fmt.Errorf(r.err)\n}\n\n\n\nfunc WithErrorRandReader(testError string, f func()) {\n\n\toriginal := rand.Reader\n\trand.Reader = &errorReader{err: testError}\n\n\tf()\n\n\trand.Reader = original\n\n}\n\nfunc (r *constReader) Read(p []byte) (n int, err error) ", "output": "{\n\tcopy(p[:], []byte(r.nonce))\n\treturn len(r.nonce), nil\n}"} {"input": "package imagick\n\n\nimport \"C\"\nimport (\n\t\"runtime\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\nvar (\n\tinitOnce sync.Once\n\tterminateOnce *sync.Once\n\n\tcanTerminate = make(chan struct{}, 1)\n\n\tenvSemaphore = make(chan struct{}, 1)\n\n\tmagickWandCounter int64\n\tdrawingWandCounter int64\n\tpixelIteratorCounter int64\n\tpixelWandCounter int64\n)\n\n\nfunc Initialize() {\n\tenvSemaphore <- struct{}{}\n\tdefer func() {\n\t\t<-envSemaphore\n\t}()\n\n\tinitOnce.Do(func() {\n\t\tC.MagickWandGenesis()\n\t\tterminateOnce = &sync.Once{}\n\t\tsetCanTerminate()\n\t})\n}\n\n\n\nfunc Terminate() {\n\tenvSemaphore <- struct{}{}\n\tdefer func() {\n\t\t<-envSemaphore\n\t}()\n\n\tif terminateOnce != nil {\n\t\tterminateOnce.Do(func() {\n\t\t\truntime.GC()\n\t\t\tterminate()\n\t\t})\n\t}\n}\n\n\n\n\n\n\nfunc setCanTerminate() {\n\tif isImageMagickCleaned() {\n\t\tselect {\n\t\tcase canTerminate <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n}\n\n\nfunc unsetCanTerminate() {\n\tselect {\n\tcase <-canTerminate:\n\tdefault:\n\t}\n}\n\n\nfunc isImageMagickCleaned() bool {\n\tif atomic.LoadInt64(&magickWandCounter) != 0 || atomic.LoadInt64(&drawingWandCounter) != 0 || atomic.LoadInt64(&pixelIteratorCounter) != 0 || atomic.LoadInt64(&pixelWandCounter) != 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc terminate() ", "output": "{\n\t<-canTerminate\n\tC.MagickWandTerminus()\n\tinitOnce = sync.Once{}\n}"} {"input": "package views\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/martini-contrib/sessions\"\n)\n\ntype Views struct {\n\tIndex string\n\ts http.Handler\n}\n\nfunc New(fallback string) *Views {\n\tv := &Views{\n\t\tIndex: fallback,\n\t\ts: http.FileServer(http.Dir(\"manager/views/assets\")),\n\t}\n\treturn v\n}\n\n\n\nfunc (v *Views) ServeHTTP(w http.ResponseWriter, r *http.Request, ss sessions.Session) ", "output": "{\n\tif v.Rewrite(w, r, ss) {\n\t\treturn\n\t}\n\tv.s.ServeHTTP(w, r)\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\n\n\n\nvar DataCmd = &cobra.Command{\n\tUse: \"data\",\n\tShort: TRCLI(\"cli.data.summary\"),\n\tLong: TRCLI(`cli.data.description`),\n}\n\nfunc init() ", "output": "{\n\tRootCmd.AddCommand(DataCmd)\n}"} {"input": "package main\n\n\nfunc (b bucketPerms) isValidBucketPERM() bool {\n\tswitch true {\n\tcase b.isPrivate():\n\t\tfallthrough\n\tcase b.isReadOnly():\n\t\tfallthrough\n\tcase b.isPublic():\n\t\tfallthrough\n\tcase b.isAuthorized():\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\ntype bucketPerms string\n\n\nconst (\n\tbucketPrivate = bucketPerms(\"private\")\n\tbucketReadOnly = bucketPerms(\"readonly\")\n\tbucketPublic = bucketPerms(\"public\")\n\tbucketAuthorized = bucketPerms(\"authorized\")\n)\n\nfunc (b bucketPerms) String() string {\n\tif !b.isValidBucketPERM() {\n\t\treturn string(b)\n\t}\n\tif b.isReadOnly() {\n\t\treturn \"public-read\"\n\t}\n\tif b.isPublic() {\n\t\treturn \"public-read-write\"\n\t}\n\tif b.isAuthorized() {\n\t\treturn \"authenticated-read\"\n\t}\n\treturn \"private\"\n}\n\n\n\n\nfunc (b bucketPerms) isPrivate() bool {\n\treturn b == bucketPrivate\n}\n\n\nfunc (b bucketPerms) isReadOnly() bool {\n\treturn b == bucketReadOnly\n}\n\n\nfunc (b bucketPerms) isPublic() bool {\n\treturn b == bucketPublic\n}\n\n\nfunc (b bucketPerms) isAuthorized() bool {\n\treturn b == bucketAuthorized\n}\n\nfunc aclToPerms(acl string) bucketPerms ", "output": "{\n\tswitch acl {\n\tcase \"private\":\n\t\treturn bucketPerms(\"private\")\n\tcase \"public-read\":\n\t\treturn bucketPerms(\"readonly\")\n\tcase \"public-read-write\":\n\t\treturn bucketPerms(\"public\")\n\tcase \"authenticated-read\":\n\t\treturn bucketPerms(\"authorized\")\n\tdefault:\n\t\treturn bucketPerms(acl)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype Dashy struct {\n\tURL string `json:\"url\"`\n\tInterests Interests `json:\"interests\"`\n}\n\n\n\nfunc NewDashy(request *http.Request) (*Dashy, error) ", "output": "{\n\tbody, err := ioutil.ReadAll(request.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read request body: %s\", err)\n\t}\n\tdefer request.Body.Close()\n\n\td := &Dashy{}\n\terr = json.Unmarshal(body, &d)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse JSON: %s\", err)\n\t}\n\n\treturn d, nil\n}"} {"input": "package handlers\n\nimport (\n \"encoding/json\"\n \"github.com/sescobb27/proyecto2-travisci/models\"\n \"net/http\"\n)\n\n\n\nfunc GetLocations(res http.ResponseWriter, req *http.Request) {\n res.Header().Set(\"Content-Type\", \"application/json\")\n locations := models.GetLocations()\n json_locations, err := json.Marshal(locations)\n\n if err != nil {\n panic(err)\n }\n\n res.Write(json_locations)\n}\n\nfunc GetCategories(res http.ResponseWriter, req *http.Request) ", "output": "{\n res.Header().Set(\"Content-Type\", \"application/json\")\n categories := models.GetCategories()\n json_categories, err := json.Marshal(categories)\n\n if err != nil {\n panic(err)\n }\n\n res.Write(json_categories)\n}"} {"input": "package gobacktest\n\nimport (\n\n)\n\n\ntype ExchangeFeeHandler interface {\n\tFee() (float64, error)\n}\n\n\ntype FixedExchangeFee struct {\n\tExchangeFee float64\n}\n\n\n\n\nfunc (e *FixedExchangeFee) Fee() (float64, error) ", "output": "{\n\treturn e.ExchangeFee, nil\n}"} {"input": "package command\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/mitchellh/cli\"\n)\n\nfunc TestOperator_Raft_ListPeers_Implements(t *testing.T) {\n\tvar _ cli.Command = &OperatorRaftListCommand{}\n}\n\n\n\nfunc TestOperator_Raft_ListPeers(t *testing.T) ", "output": "{\n\ts, _, addr := testServer(t, nil)\n\tdefer s.Stop()\n\n\tui := new(cli.MockUi)\n\tc := &OperatorRaftListCommand{Meta: Meta{Ui: ui}}\n\targs := []string{\"-address=\" + addr}\n\n\tcode := c.Run(args)\n\tif code != 0 {\n\t\tt.Fatalf(\"bad: %d. %#v\", code, ui.ErrorWriter.String())\n\t}\n\toutput := strings.TrimSpace(ui.OutputWriter.String())\n\tif !strings.Contains(output, \"leader\") {\n\t\tt.Fatalf(\"bad: %s\", output)\n\t}\n}"} {"input": "package syscall_test\n\nimport (\n\t\"syscall\"\n\t\"testing\"\n)\n\n\n\nfunc testalias(t *testing.T, fn string, sys1, sys2 func() error) {\n\terr := sys1().Error()\n\terrcopy := string([]byte(err))\n\tsys2()\n\tif err != errcopy {\n\t\tt.Errorf(\"syscall.%s error string changed from %q to %q\\n\", fn, errcopy, err)\n\t}\n}\n\n\n\n\n\nfunc TestPlan9Syserr(t *testing.T) ", "output": "{\n\ttestalias(t,\n\t\t\"Syscall\",\n\t\tfunc() error {\n\t\t\treturn syscall.Mkdir(\"/\", 0)\n\t\t},\n\t\tfunc() error {\n\t\t\treturn syscall.Mkdir(\"#\", 0)\n\t\t})\n\ttestalias(t,\n\t\t\"Syscall6\",\n\t\tfunc() error {\n\t\t\treturn syscall.Mount(0, 0, \"\", 0, \"\")\n\t\t},\n\t\tfunc() error {\n\t\t\treturn syscall.Mount(-1, 0, \"\", 0, \"\")\n\t\t})\n\ttestalias(t,\n\t\t\"seek\",\n\t\tfunc() error {\n\t\t\t_, err := syscall.Seek(0, 0, -1)\n\t\t\treturn err\n\t\t},\n\t\tfunc() error {\n\t\t\t_, err := syscall.Seek(-1, 0, 0)\n\t\t\treturn err\n\t\t})\n}"} {"input": "package main\n\nimport \"strings\"\n\nvar x = make([]byte, 10)\n\nfunc main() {\n\ttest1()\n\ttest2()\n\ttest3()\n\ttest4()\n\ttest5()\n\ttest6()\n\ttest7()\n}\n\n\n\nfunc test1() {\n\tdefer mustRecover(\"index\")\n\tprintln(x[123])\n}\n\nfunc test2() {\n\tdefer mustRecover(\"slice\")\n\tprintln(x[5:15])\n}\n\nfunc test3() {\n\tdefer mustRecover(\"slice\")\n\tvar lo = 11\n\tvar hi = 9\n\tprintln(x[lo:hi])\n}\n\nfunc test4() {\n\tdefer mustRecover(\"interface\")\n\tvar x interface{} = 1\n\tprintln(x.(float32))\n}\n\ntype T struct {\n\ta, b int\n\tc []int\n}\n\nfunc test5() {\n\tdefer mustRecover(\"uncomparable\")\n\tvar x T\n\tvar z interface{} = x\n\tprintln(z != z)\n}\n\nfunc test6() {\n\tdefer mustRecover(\"unhashable\")\n\tvar x T\n\tvar z interface{} = x\n\tm := make(map[interface{}]int)\n\tm[z] = 1\n}\n\nfunc test7() {\n\tdefer mustRecover(\"divide by zero\")\n\tvar x, y int\n\tprintln(x / y)\n}\n\nfunc mustRecover(s string) ", "output": "{\n\tv := recover()\n\tif v == nil {\n\t\tpanic(\"expected panic\")\n\t}\n\tif e := v.(error).Error(); strings.Index(e, s) < 0 {\n\t\tpanic(\"want: \" + s + \"; have: \" + e)\n\t}\n}"} {"input": "package rotaryLogger\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\nvar Logger *log.Logger\n\nvar file os.File\n\n\n\n\n\nfunc StartLoggerWRotation(logAmount int, logLocation string, rotationPeriod time.Duration) {\n\tlogRotator(logAmount, logLocation)\n\n\tStartLogger(logLocation)\n\n\tticker := time.NewTicker(rotationPeriod)\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tLogger.Println(\"Rotating Logs\")\n\n\t\t\tLogger = log.New(os.Stdout,\n\t\t\t\t\"\", \n\t\t\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n\n\t\t\tlogRotator(logAmount, logLocation)\n\n\t\t\tStartLogger(logLocation)\n\n\t\t}\n\t}()\n}\n\n\n\nfunc StartLogger(logLocation string) {\n\tfile, err := os.OpenFile(logLocation+\"0.log\", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to open Logger file\", err)\n\t}\n\n\tmulti := io.MultiWriter(file, os.Stdout)\n\n\tLogger = log.New(multi,\n\t\t\"\", \n\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n}\n\n\n\n\n\nfunc logRotator(logAmount int, logLocation string) ", "output": "{\n\tif _, err := os.Stat(logLocation + strconv.Itoa(logAmount) + \".log\"); os.IsNotExist(err) {\n\t\tos.Remove(logLocation + strconv.Itoa(logAmount) + \".log\")\n\t}\n\n\tfor i := 2; i != -1; i-- {\n\t\tfmt.Println(logLocation + strconv.Itoa(i) + \".log\")\n\t\tif _, err := os.Stat(logLocation + strconv.Itoa(i) + \".log\"); err == nil {\n\t\t\tos.Rename(logLocation+strconv.Itoa(i)+\".log\", logLocation+strconv.Itoa(i+1)+\".log\")\n\t\t}\n\t}\n}"} {"input": "package bind\n\nimport (\n\t\"crypto/rand\"\n\t\"fmt\"\n\tmrand \"math/rand\"\n\t\"strconv\"\n\n\t\"github.com/skriptble/nine/element\"\n\t\"github.com/skriptble/nine/element/stanza\"\n\t\"github.com/skriptble/nine/jid\"\n\t\"github.com/skriptble/nine/stream\"\n)\n\ntype Handler struct {\n}\n\nfunc NewHandler() Handler {\n\treturn Handler{}\n}\n\nfunc (h Handler) GenerateFeature(props stream.Properties) stream.Properties {\n\tif props.Status&stream.Bind != 0 || props.Status&stream.Auth == 0 {\n\t\treturn props\n\t}\n\n\tprops.Features = append(props.Features, element.Bind)\n\treturn props\n}\n\n\n\nfunc genResourceID() string {\n\tid := make([]byte, 16)\n\t_, err := rand.Read(id)\n\tif err != nil {\n\t\treturn strconv.FormatInt(mrand.Int63(), 10)\n\t}\n\n\tid[8] = (id[8] | 0x80) & 0xBF\n\tid[6] = (id[6] | 0x40) & 0x4F\n\n\treturn fmt.Sprintf(\"%x-%x-%x-%x-%x\", id[:4], id[4:6], id[6:8], id[8:10], id[10:])\n}\n\nfunc (h Handler) HandleIQ(iq stanza.IQ, props stream.Properties) ([]stanza.Stanza, stream.Properties) ", "output": "{\n\tvar sts []stanza.Stanza\n\treq, err := stanza.TransformBindRequest(iq)\n\tif err != nil {\n\t\treturn sts, props\n\t}\n\tif req.Resource == \"\" {\n\t\treq.Resource = genResourceID()\n\t}\n\n\tprops.Header.To += \"/\" + req.Resource\n\n\tj := jid.New(props.Header.To)\n\tres := stanza.NewBindResult(iq, j)\n\tsts = append(sts, res.TransformStanza())\n\n\tprops.Status = props.Status | stream.Bind\n\treturn sts, props\n}"} {"input": "package iso20022\n\n\ntype Tax13 struct {\n\n\tType *TaxType9Code `xml:\"Tp\"`\n\n\tOtherTaxType *Max35Text `xml:\"OthrTaxTp\"`\n\n\tAmount *CurrencyAndAmount `xml:\"Amt\"`\n\n\tRate *PercentageRate `xml:\"Rate\"`\n}\n\nfunc (t *Tax13) SetType(value string) {\n\tt.Type = (*TaxType9Code)(&value)\n}\n\nfunc (t *Tax13) SetOtherTaxType(value string) {\n\tt.OtherTaxType = (*Max35Text)(&value)\n}\n\nfunc (t *Tax13) SetAmount(value, currency string) {\n\tt.Amount = NewCurrencyAndAmount(value, currency)\n}\n\n\n\nfunc (t *Tax13) SetRate(value string) ", "output": "{\n\tt.Rate = (*PercentageRate)(&value)\n}"} {"input": "package migrations_test\n\nimport (\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\nfunc assertCorrectRepoVer(t *testing.T, verPath, expectedRepoVer string) {\n\trepoVer, err := ioutil.ReadFile(verPath)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif string(repoVer) != expectedRepoVer {\n\t\tt.Fatal(\"Failed to write new repo version\")\n\t}\n}\n\n\n\nfunc assertCorrectFileContents(t *testing.T, filePath string, expectedFileContents string) ", "output": "{\n\tfileContents, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif string(fileContents) != expectedFileContents {\n\t\tt.Fatal(\"Incorrect file content:\", filePath)\n\t}\n}"} {"input": "package goarken\n\ntype Broadcaster struct {\n\tlisteners []chan interface{}\n}\n\nfunc NewBroadcaster() *Broadcaster {\n\tb := &Broadcaster{\n\t\tlisteners: []chan interface{}{},\n\t}\n\treturn b\n}\n\n\n\nfunc (b *Broadcaster) Listen() chan interface{} {\n\tchannel := make(chan interface{})\n\tb.listeners = append(b.listeners, channel)\n\treturn channel\n\n}\n\nfunc (b *Broadcaster) Write(message interface{}) ", "output": "{\n\tfor _, channel := range b.listeners {\n\t\tchannel <- message\n\t}\n}"} {"input": "package raw\n\nimport (\n\t\"fmt\"\n\t\"../../platforms/common\"\n)\n\ntype FieldMacros struct {}\n\n\n\nfunc (FieldMacros) DecodeDW1() {\n\tmacro := common.GetMacro()\n\tmacro.Add(fmt.Sprintf(\"0x%0.8x\", macro.Register(common.PAD_CFG_DW1).ValueGet()))\n}\n\n\nfunc (bitfields FieldMacros) GenerateString() {\n\tmacro := common.GetMacro()\n\tmacro.Add(\"_PAD_CFG_STRUCT(\").Id().Add(\", \")\n\tbitfields.DecodeDW0()\n\tmacro.Add(\", \")\n\tbitfields.DecodeDW1()\n\tmacro.Add(\"),\")\n}\n\nfunc (FieldMacros) DecodeDW0() ", "output": "{\n\tmacro := common.GetMacro()\n\tmacro.Add(fmt.Sprintf(\"0x%0.8x\", macro.Register(common.PAD_CFG_DW0).ValueGet()))\n}"} {"input": "package es_terminfo\n\nimport (\n\t\"golang.org/x/crypto/ssh/terminal\"\n\t\"os\"\n)\n\nfunc IsInTerminal() bool {\n\treturn terminal.IsTerminal(int(os.Stdin.Fd()))\n}\n\nfunc IsOutTerminal() bool {\n\treturn terminal.IsTerminal(int(os.Stdout.Fd()))\n}\n\n\n\n\nfunc IsOutColorTerminal() bool ", "output": "{\n\tif !IsOutTerminal() {\n\t\treturn false\n\t}\n\n\treturn true\n}"} {"input": "package gorocksdb\n\n\nimport \"C\"\n\n\ntype Cache struct {\n\tc *C.rocksdb_cache_t\n}\n\n\n\n\n\nfunc NewNativeCache(c *C.rocksdb_cache_t) *Cache {\n\treturn &Cache{c}\n}\n\n\nfunc (c *Cache) Destroy() {\n\tC.rocksdb_cache_destroy(c.c)\n\tc.c = nil\n}\n\nfunc NewLRUCache(capacity int) *Cache ", "output": "{\n\treturn NewNativeCache(C.rocksdb_cache_create_lru(C.size_t(capacity)))\n}"} {"input": "package graphdriver\n\n\nimport \"C\"\nimport (\n\t\"path/filepath\"\n\t\"unsafe\"\n\n\t\"github.com/docker/docker/pkg/mount\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tFsMagicZfs = FsMagic(0x2fc12fc1)\n)\n\nvar (\n\tpriority = []string{\n\t\t\"zfs\",\n\t}\n\n\tFsNames = map[FsMagic]string{\n\t\tFsMagicZfs: \"zfs\",\n\t}\n)\n\n\nfunc GetFSMagic(rootpath string) (FsMagic, error) {\n\treturn 0, nil\n}\n\ntype fsChecker struct {\n\tt FsMagic\n}\n\nfunc (c *fsChecker) IsMounted(path string) bool {\n\tm, _ := Mounted(c.t, path)\n\treturn m\n}\n\n\nfunc NewFsChecker(t FsMagic) Checker {\n\treturn &fsChecker{\n\t\tt: t,\n\t}\n}\n\n\n\n\nfunc NewDefaultChecker() Checker {\n\treturn &defaultChecker{}\n}\n\ntype defaultChecker struct {\n}\n\n\n\n\n\nfunc Mounted(fsType FsMagic, mountPath string) (bool, error) {\n\n\tcs := C.CString(filepath.Dir(mountPath))\n\tdefer C.free(unsafe.Pointer(cs))\n\tbuf := C.getstatfs(cs)\n\tdefer C.free(unsafe.Pointer(buf))\n\n\tif (buf.f_basetype[0] != 122) || (buf.f_basetype[1] != 102) || (buf.f_basetype[2] != 115) ||\n\t\t(buf.f_basetype[3] != 0) {\n\t\tlogrus.Debugf(\"[zfs] no zfs dataset found for rootdir '%s'\", mountPath)\n\t\treturn false, ErrPrerequisites\n\t}\n\n\treturn true, nil\n}\n\nfunc (c *defaultChecker) IsMounted(path string) bool ", "output": "{\n\tm, _ := mount.Mounted(path)\n\treturn m\n}"} {"input": "package util\n\nimport (\n\t\"github.com/revel/revel\"\n\t\"github.com/telrikk/lol-go-api/util\"\n)\n\n\n\n\n\nfunc HandleError(c revel.Controller, err error) revel.Result ", "output": "{\n\triotError, isRiotError := err.(util.APIError)\n\tif isRiotError && riotError.Status.StatusCode == 404 {\n\t\treturn c.NotFound(riotError.Status.Message)\n\t}\n\treturn c.RenderError(err)\n}"} {"input": "package context\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\n\tjujuos \"github.com/juju/utils/os\"\n)\n\n\n\nfunc OSDependentEnvVars(paths Paths) []string {\n\tswitch jujuos.HostOS() {\n\tcase jujuos.Windows:\n\t\treturn windowsEnv(paths)\n\tcase jujuos.Ubuntu:\n\t\treturn ubuntuEnv(paths)\n\tcase jujuos.CentOS:\n\t\treturn centosEnv(paths)\n\t}\n\treturn nil\n}\n\n\n\nfunc ubuntuEnv(paths Paths) []string {\n\tpath := appendPath(paths)\n\tenv := []string{\n\t\t\"APT_LISTCHANGES_FRONTEND=none\",\n\t\t\"DEBIAN_FRONTEND=noninteractive\",\n\t}\n\tenv = append(env, path...)\n\treturn env\n}\n\nfunc centosEnv(paths Paths) []string {\n\treturn appendPath(paths)\n}\n\n\n\n\n\nfunc windowsEnv(paths Paths) []string {\n\tcharmDir := paths.GetCharmDir()\n\tcharmModules := filepath.Join(charmDir, \"lib\", \"Modules\")\n\treturn []string{\n\t\t\"Path=\" + paths.GetToolsDir() + \";\" + os.Getenv(\"Path\"),\n\t\t\"PSModulePath=\" + os.Getenv(\"PSModulePath\") + \";\" + charmModules,\n\t}\n}\n\nfunc appendPath(paths Paths) []string ", "output": "{\n\treturn []string{\n\t\t\"PATH=\" + paths.GetToolsDir() + \":\" + os.Getenv(\"PATH\"),\n\t}\n}"} {"input": "package tristate\n\ntype StateValue int\n\nconst (\n\tTRISTATE_SUCCESS StateValue = iota\n\tTRISTATE_FAILRUE\n\tTRISTATE_UNKNOWN\n)\n\ntype TriState struct {\n\tState StateValue\n\tErr error\n}\n\nfunc NewSuccess() *TriState {\n\treturn nil\n}\n\nfunc NewUnknown(err error) *TriState {\n\tif err == nil {\n\t\tpanic(\"error not set\")\n\t}\n\treturn &TriState{TRISTATE_UNKNOWN, err}\n}\n\nfunc NewFailure(err error) *TriState {\n\tif err == nil {\n\t\tpanic(\"error not set\")\n\t}\n\treturn &TriState{TRISTATE_FAILRUE, err}\n}\n\n\n\nfunc (state *TriState) IsSuccess() bool {\n\treturn state == nil || state.State == TRISTATE_SUCCESS\n}\n\nfunc (state *TriState) IsFailure() bool {\n\treturn state != nil && state.State == TRISTATE_FAILRUE\n}\n\nfunc (state *TriState) IsUnknown() bool {\n\treturn state != nil && state.State == TRISTATE_UNKNOWN\n}\n\nfunc (state *TriState) Error() string ", "output": "{\n\treturn state.Err.Error()\n}"} {"input": "package kiwitaxi\n\ntype UrlDomain struct {\n\tId int `csv:\"id\" json:\"id\" bson:\"id\"`\n\tLocale string `csv:\"locale\" json:\"locale\" bson:\"locale\"`\n\tValue string `csv:\"value\" json:\"value\" bson:\"value\"`\n}\n\n\n\nfunc (a *KiwitaxiApi) UrlDomains() (urlDomains []*UrlDomain, err error) ", "output": "{\n\terr = a.getCsv(\"services/data/csv/url_domains\", &urlDomains)\n\treturn\n}"} {"input": "package cmd\n\nimport (\n\t\"testing\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n\t\"github.com/jamesnetherton/homehub-cli/service\"\n)\n\n\n\nfunc TestSambaIPCommand(t *testing.T) ", "output": "{\n\tctrl := gomock.NewController(t)\n\tdefer ctrl.Finish()\n\n\thub := NewMockHub(ctrl)\n\tservice.SetHub(hub)\n\tservice.AuthenticationComplete()\n\n\thub.EXPECT().SambaIP().Return(\"192.168.1.254\", nil)\n\n\tAssertCommandOutput(t, NewSambaIPCommand(NewLoginCommand()))\n}"} {"input": "package main\n\nimport \"github.com/augustoroman/serial_lcd\"\n\ntype FakeLcd struct{}\n\nfunc (f FakeLcd) SetBG(r, g, b uint8) error { return nil }\nfunc (f FakeLcd) SetOn(On bool) error { return nil }\n\nfunc (f FakeLcd) SetContrast(c uint8) error { return nil }\nfunc (f FakeLcd) SetAutoscroll(On bool) error { return nil }\nfunc (f FakeLcd) SetSize(cols, rows uint8) error { return nil }\nfunc (f FakeLcd) Clear() error { return nil }\nfunc (f FakeLcd) Home() error { return nil }\nfunc (f FakeLcd) MoveTo(col, row uint8) error { return nil }\nfunc (f FakeLcd) MoveForward() error { return nil }\nfunc (f FakeLcd) MoveBack() error { return nil }\nfunc (f FakeLcd) Write(b []byte) (int, error) { return len(b), nil }\n\nfunc (f FakeLcd) CreateCustomChar(spot uint8, c serial_lcd.Char) error { return nil }\n\nfunc (f FakeLcd) SetBrightness(b uint8) error ", "output": "{ return nil }"} {"input": "package messenger\n\nimport (\n\t. \"github.com/andrew-suprun/envoy\"\n\t\"log\"\n\t\"testing\"\n)\n\n\n\nfunc panicingHandler(topic string, body []byte, _ MessageId) []byte {\n\tpanic(\"foo\")\n}\n\nfunc TestPanic(t *testing.T) ", "output": "{\n\tlog.Println(\"---------------- TestPanic ----------------\")\n\n\tserver, err := NewMessenger(\"localhost:50000\")\n\tif err != nil {\n\t\tt.FailNow()\n\t}\n\tdefer server.Leave()\n\tserver.Subscribe(\"job\", panicingHandler)\n\tserver.Join()\n\n\tclient, err := NewMessenger(\"localhost:40000\")\n\tif err != nil {\n\t\tt.FailNow()\n\t}\n\tdefer client.Leave()\n\tclient.Join(\"localhost:50000\")\n\n\treply, _, err := client.Request(\"job\", []byte(\"Hello\"))\n\tlog.Printf(\"TestPanic: reply = %s; err = %v\", string(reply), err)\n\tif err != PanicError {\n\t\tt.Fatalf(\"Server didn't panic\")\n\t}\n}"} {"input": "package bot\n\nimport \"strings\"\n\n\n\nfunc isYoutubeSource(url string) bool ", "output": "{\n\tvalidPrefixes := []string{\n\t\t\"http://www.youtube.com\",\n\t\t\"https://www.youtube.com\",\n\t\t\"http://m.youtube.com\",\n\t\t\"https://m.youtube.com\",\n\t\t\"http://youtu.be\",\n\t\t\"https://youtu.be\",\n\t\t\"http://vimeo.com\",\n\t\t\"https://vimeo.com\",\n\t\t\"http://player.vimeo.com\",\n\t\t\"https://player.vimeo.com\",\n\t}\n\n\tfor _, prefix := range validPrefixes {\n\t\tif strings.HasPrefix(url, prefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package schedulercache\n\nimport (\n\tutilfeature \"k8s.io/apiserver/pkg/util/feature\"\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n\t\"k8s.io/kubernetes/pkg/features\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ReconcileAffinity(pod *v1.Pod) *v1.Affinity ", "output": "{\n\taffinity := pod.Spec.Affinity\n\tif utilfeature.DefaultFeatureGate.Enabled(features.AffinityInAnnotations) {\n\t\tannotationsAffinity, _ := v1.GetAffinityFromPodAnnotations(pod.Annotations)\n\t\tif affinity == nil && annotationsAffinity != nil {\n\t\t\taffinity = annotationsAffinity\n\t\t} else if annotationsAffinity != nil {\n\t\t\tif affinity != nil && affinity.NodeAffinity == nil && annotationsAffinity.NodeAffinity != nil {\n\t\t\t\taffinity.NodeAffinity = annotationsAffinity.NodeAffinity\n\t\t\t}\n\t\t\tif affinity != nil && affinity.PodAffinity == nil && annotationsAffinity.PodAffinity != nil {\n\t\t\t\taffinity.PodAffinity = annotationsAffinity.PodAffinity\n\t\t\t}\n\t\t\tif affinity != nil && affinity.PodAntiAffinity == nil && annotationsAffinity.PodAntiAffinity != nil {\n\t\t\t\taffinity.PodAntiAffinity = annotationsAffinity.PodAntiAffinity\n\t\t\t}\n\t\t}\n\t}\n\treturn affinity\n}"} {"input": "package test\n\nimport (\n\t\"github.com/stellar/go/support/db\"\n\t\"github.com/stellar/horizon/ledger\"\n)\n\n\nfunc (t *T) CoreRepo() *db.Repo {\n\treturn &db.Repo{\n\t\tDB: t.CoreDB,\n\t\tCtx: t.Ctx,\n\t}\n}\n\n\n\nfunc (t *T) Finish() {\n\tRestoreLogger()\n\tledger.SetState(ledger.State{})\n\n\tif t.LogBuffer.Len() > 0 {\n\t\tt.T.Log(\"\\n\" + t.LogBuffer.String())\n\t}\n}\n\n\nfunc (t *T) HorizonRepo() *db.Repo {\n\treturn &db.Repo{\n\t\tDB: t.HorizonDB,\n\t\tCtx: t.Ctx,\n\t}\n}\n\n\nfunc (t *T) Scenario(name string) *T {\n\tLoadScenario(name)\n\tt.UpdateLedgerState()\n\treturn t\n}\n\n\nfunc (t *T) ScenarioWithoutHorizon(name string) *T {\n\tLoadScenarioWithoutHorizon(name)\n\tt.UpdateLedgerState()\n\treturn t\n}\n\n\n\n\nfunc (t *T) UpdateLedgerState() ", "output": "{\n\tvar next ledger.State\n\n\terr := t.CoreRepo().GetRaw(&next, `\n\t\tSELECT\n\t\t\tCOALESCE(MIN(ledgerseq), 0) as core_elder,\n\t\t\tCOALESCE(MAX(ledgerseq), 0) as core_latest\n\t\tFROM ledgerheaders\n\t`)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = t.HorizonRepo().GetRaw(&next, `\n\t\t\tSELECT\n\t\t\t\tCOALESCE(MIN(sequence), 0) as history_elder,\n\t\t\t\tCOALESCE(MAX(sequence), 0) as history_latest\n\t\t\tFROM history_ledgers\n\t\t`)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tledger.SetState(next)\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc capitalizedWord(word string) (capitalized string) {\n\tswitch len(word) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\tcapitalized = strings.ToUpper(string(word[0]))\n\tdefault:\n\t\tcapitalized = strings.ToUpper(string(word[0])) + string(word[1:])\n\t}\n\treturn capitalized\n}\n\n\n\nfunc camelcaseToAbbreviation(camel string) (abbr string) {\n\tif len(camel) == 0 {\n\t\treturn \"\"\n\t}\n\n\tabbr = strings.ToLower(string(camel[0])) \n\n\tremainingRunes := []rune(camel[1:])\n\tfor _, r := range remainingRunes {\n\t\tif unicode.IsUpper(r) {\n\t\t\tabbr += strings.ToLower(string(r))\n\t\t}\n\t}\n\treturn abbr\n}\n\nfunc lowerCasedWord(word string) (lowerCased string) ", "output": "{\n\tswitch len(word) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\tlowerCased = strings.ToLower(string(word[0]))\n\tdefault:\n\t\tlowerCased = strings.ToLower(string(word[0])) + string(word[1:])\n\t}\n\treturn lowerCased\n}"} {"input": "package iso20022\n\n\ntype RemittanceInformation8 struct {\n\n\tRemittanceIdentification *Max35Text `xml:\"RmtId,omitempty\"`\n\n\tUnstructured []*Max140Text `xml:\"Ustrd,omitempty\"`\n\n\tStructured []*StructuredRemittanceInformation10 `xml:\"Strd,omitempty\"`\n\n\tOriginalPaymentInformation *OriginalPaymentInformation6 `xml:\"OrgnlPmtInf\"`\n}\n\nfunc (r *RemittanceInformation8) SetRemittanceIdentification(value string) {\n\tr.RemittanceIdentification = (*Max35Text)(&value)\n}\n\nfunc (r *RemittanceInformation8) AddUnstructured(value string) {\n\tr.Unstructured = append(r.Unstructured, (*Max140Text)(&value))\n}\n\n\n\nfunc (r *RemittanceInformation8) AddOriginalPaymentInformation() *OriginalPaymentInformation6 {\n\tr.OriginalPaymentInformation = new(OriginalPaymentInformation6)\n\treturn r.OriginalPaymentInformation\n}\n\nfunc (r *RemittanceInformation8) AddStructured() *StructuredRemittanceInformation10 ", "output": "{\n\tnewValue := new(StructuredRemittanceInformation10)\n\tr.Structured = append(r.Structured, newValue)\n\treturn newValue\n}"} {"input": "package repos\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\tdb \"github.com/antoineaugusti/feature-flags/db\"\n\tm \"github.com/antoineaugusti/feature-flags/models\"\n\t\"github.com/boltdb/bolt\"\n)\n\n\nfunc PutFeature(tx *bolt.Tx, feature m.FeatureFlag) error {\n\tfeatures := tx.Bucket([]byte(db.GetBucketName()))\n\n\tbytes, err := json.Marshal(feature)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = features.Put([]byte(feature.Key), bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc FeatureExists(tx *bolt.Tx, featureKey string) bool {\n\tfeatures := tx.Bucket([]byte(db.GetBucketName()))\n\tbytes := features.Get([]byte(featureKey))\n\treturn bytes != nil\n}\n\n\nfunc GetFeature(tx *bolt.Tx, featureKey string) (m.FeatureFlag, error) {\n\tfeatures := tx.Bucket([]byte(db.GetBucketName()))\n\n\tbytes := features.Get([]byte(featureKey))\n\tif bytes == nil {\n\t\treturn m.FeatureFlag{}, fmt.Errorf(\"Unable to find feature\")\n\t}\n\n\tfeature := m.FeatureFlag{}\n\n\terr := json.Unmarshal(bytes, &feature)\n\tif err != nil {\n\t\treturn m.FeatureFlag{}, err\n\t}\n\n\treturn feature, nil\n}\n\n\nfunc RemoveFeature(tx *bolt.Tx, featureKey string) error {\n\tfeatures := tx.Bucket([]byte(db.GetBucketName()))\n\treturn features.Delete([]byte(featureKey))\n}\n\nfunc GetFeatures(tx *bolt.Tx) (m.FeatureFlags, error) ", "output": "{\n\tfeaturesBucket := tx.Bucket([]byte(db.GetBucketName()))\n\tcursor := featuresBucket.Cursor()\n\n\tfeatures := make(m.FeatureFlags, 0)\n\n\tfor key, value := cursor.First(); key != nil; key, value = cursor.Next() {\n\t\tfeature := m.FeatureFlag{}\n\n\t\terr := json.Unmarshal(value, &feature)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfeatures = append(features, feature)\n\t}\n\n\treturn features, nil\n}"} {"input": "package iris2\n\nimport (\n\t\"fmt\"\n)\n\ntype Mux struct {\n\trunning bool\n\tsources []<-chan interface{}\n\tselector chan Word\n\tdestination chan interface{}\n\terr chan error\n\n\tControl <-chan Word\n\tSelect chan<- Word\n\tDestination <-chan interface{}\n\tError <-chan error\n}\n\nfunc NewMux(control chan<- Word) *Mux {\n\tvar mux Mux\n\tmux.err = make(chan error)\n\tmux.destination = make(chan interface{})\n\tmux.selector = make(chan Word)\n\tmux.Error = mux.err\n\tmux.Destination = mux.destination\n\tmux.Control = control\n\tmux.Select = mux.selector\n\treturn &mux\n}\nfunc (this *Mux) AddSource(src <-chan interface{}) {\n\tthis.sources = append(this.sources, src)\n}\nfunc (this *Mux) body() {\n\tfor this.running {\n\t\tselect {\n\t\tcase index, more := <-this.selector:\n\t\t\tif more {\n\t\t\t\tif index >= Word(len(this.sources)) {\n\t\t\t\t\tthis.err <- fmt.Errorf(\"Selected non existent source: %d\", index)\n\t\t\t\t} else if index < 0 {\n\t\t\t\t\tthis.err <- fmt.Errorf(\"Select source %d is less than zero!\", index)\n\t\t\t\t} else {\n\t\t\t\t\tthis.destination <- <-this.sources[index]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (this *Mux) queryControl() {\n\t<-this.Control\n\tif err := this.shutdown(); err != nil {\n\t\tthis.err <- err\n\t}\n}\n\nfunc (this *Mux) shutdown() error {\n\tif !this.running {\n\t\treturn fmt.Errorf(\"Attempted to shutdown a multiplexer which isn't running\")\n\t} else {\n\t\tthis.running = false\n\t\tclose(this.selector)\n\t\treturn nil\n\t}\n}\n\n\n\nfunc (this *Mux) Startup() error ", "output": "{\n\tif this.running {\n\t\treturn fmt.Errorf(\"Given multiplexer is already running!\")\n\t} else {\n\t\tthis.running = true\n\t\tgo this.body()\n\t\tgo this.queryControl()\n\t\treturn nil\n\t}\n}"} {"input": "package cephaloutils\n\nimport (\n\t\"time\"\n\n\t\"github.com/paulidealiste/Cephalopod/cephalobjects\"\n)\n\n\n\n\n\nfunc CTSListMap(cts cephalobjects.CephaloTimeSeries) map[int]cephalobjects.TimeSeriesDataLike {\n\ttsdl := CTSListForm(cts)\n\ttsdlm := make(map[int]cephalobjects.TimeSeriesDataLike)\n\ttsdlm[tsdl.ID] = tsdl\n\treturn tsdlm\n}\n\n\nfunc TSListsFromTSTrees(ctss []cephalobjects.CephaloTimeSeries) map[int]cephalobjects.TimeSeriesDataLike {\n\ttsdlsm := make(map[int]cephalobjects.TimeSeriesDataLike)\n\tjobs := make(chan cephalobjects.CephaloTimeSeries, 100)\n\tresults := make(chan cephalobjects.TimeSeriesDataLike, 100)\n\tfor w := 1; w <= 3; w++ {\n\t\tgo tslistworker(w, jobs, results)\n\t}\n\tfor _, cts := range ctss {\n\t\tjobs <- cts\n\t}\n\tclose(jobs)\n\tfor i := 0; i < len(ctss); i++ {\n\t\ttemplistform := <-results\n\t\ttsdlsm[templistform.ID] = templistform\n\t}\n\treturn tsdlsm\n}\n\nfunc tslistworker(id int, jobs <-chan cephalobjects.CephaloTimeSeries, results chan<- cephalobjects.TimeSeriesDataLike) {\n\tfor cts := range jobs {\n\t\ttsdl := CTSListForm(cts)\n\t\tresults <- tsdl\n\t}\n}\n\nfunc CTSListForm(cts cephalobjects.CephaloTimeSeries) cephalobjects.TimeSeriesDataLike ", "output": "{\n\tvar tslist []cephalobjects.TimeSeriesDataPoint\n\tpointcount := 0\n\tcts.TraversalMap(cts.Root, func(current *cephalobjects.CephaloTimeNode) {\n\t\ttspoint := cephalobjects.TimeSeriesDataPoint{ID: pointcount, Data: current.Data, Datetime: current.Datetime.Format(time.RFC3339)}\n\t\ttslist = append(tslist, tspoint)\n\t\tpointcount++\n\t})\n\ttsdl := cephalobjects.TimeSeriesDataLike{ID: cts.ID, Data: tslist}\n\treturn tsdl\n}"} {"input": "package acsengine\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/Azure/acs-engine/pkg/i18n\"\n\tlog \"github.com/sirupsen/logrus\"\n\t\"golang.org/x/crypto/ssh\"\n)\n\n\ntype SSHCreator struct {\n\tTranslator *i18n.Translator\n}\n\nconst (\n\tSSHKeySize = 4096\n)\n\n\n\n\n\nfunc (s *SSHCreator) CreateSSH(rg io.Reader) (privateKey *rsa.PrivateKey, publicKeyString string, err error) {\n\tlog.Debugf(\"ssh: generating %dbit rsa key\", SSHKeySize)\n\tprivateKey, err = rsa.GenerateKey(rg, SSHKeySize)\n\tif err != nil {\n\t\treturn nil, \"\", s.Translator.Errorf(\"failed to generate private key for ssh: %q\", err)\n\t}\n\n\tpublicKey := privateKey.PublicKey\n\tsshPublicKey, err := ssh.NewPublicKey(&publicKey)\n\tif err != nil {\n\t\treturn nil, \"\", s.Translator.Errorf(\"failed to create openssh public key string: %q\", err)\n\t}\n\tauthorizedKeyBytes := ssh.MarshalAuthorizedKey(sshPublicKey)\n\tauthorizedKey := string(authorizedKeyBytes)\n\n\treturn privateKey, authorizedKey, nil\n}\n\nfunc (s *SSHCreator) CreateSaveSSH(username, outputDirectory string) (privateKey *rsa.PrivateKey, publicKeyString string, err error) ", "output": "{\n\tprivateKey, publicKeyString, err = s.CreateSSH(rand.Reader)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tprivateKeyPem := privateKeyToPem(privateKey)\n\n\tf := &FileSaver{\n\t\tTranslator: s.Translator,\n\t}\n\n\terr = f.SaveFile(outputDirectory, fmt.Sprintf(\"%s_rsa\", username), privateKeyPem)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\treturn privateKey, publicKeyString, nil\n}"} {"input": "package simulatorsetup\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc ApplyDataToSim(deviceName string, deviceVersion string) {\n\tdeviceList, _ := getDevices()\n\n\tfmt.Println(\"Apply Device: \" + deviceName)\n\n\tif deviceVersion == \"latest\" {\n\t\tlatestIosVersion := deviceList.getLatestIOS()\n\t\tdeviceList = deviceList.filterByIOS(latestIosVersion, true)\n\t}\n\n\tdeviceList = deviceList.filterByName(deviceName)\n\tfor _, device := range deviceList.Devices {\n\t\tfmt.Println(device)\n\t\tdevice.applySimulatorData(true)\n\t}\n}\n\n\n\nfunc (deviceList DeviceList) printDeviceList() {\n\tfor _, device := range deviceList.Devices {\n\t\tfmt.Println(device.Name)\n\t}\n}\n\nfunc DumpSimData(deviceName string) ", "output": "{\n\tdeviceList, _ := getDevices()\n\tlatestIosVersion := deviceList.getLatestIOS()\n\n\tdeviceList = deviceList.filterByIOS(latestIosVersion, true)\n\tdeviceList = deviceList.filterByName(deviceName)\n\n\tdeviceCount := len(deviceList.Devices)\n\tif deviceCount == 0 {\n\t\tfmt.Println(\"Device \", deviceName, \" not found\")\n\t\tfmt.Println(\"Available devices:\")\n\t\tdeviceList, _ = getDevices()\n\t\tdeviceList.filterByIOS(latestIosVersion, true).printDeviceList()\n\t\tos.Exit(1)\n\t} else if deviceCount != 1 {\n\t\tfmt.Println(\"Can only dump one device, matched \", deviceCount, \" devices\")\n\t\tdeviceList.printDeviceList()\n\t\tos.Exit(1)\n\t} else {\n\t\tdeviceList.Devices[0].dumpSimulatorData([]string{\"Containers\", \"Documents\", \"Downloads\", \"Library\", \"Media\"})\n\t}\n}"} {"input": "package version\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n)\n\nconst Version = \"2020.1.3\"\n\n\n\nfunc version() (string, bool) {\n\tif Version != \"devel\" {\n\t\treturn Version, true\n\t}\n\tv, ok := buildInfoVersion()\n\tif ok {\n\t\treturn v, false\n\t}\n\treturn \"devel\", false\n}\n\n\n\nfunc Verbose() {\n\tPrint()\n\tfmt.Println()\n\tfmt.Println(\"Compiled with Go version:\", runtime.Version())\n\tprintBuildInfo()\n}\n\nfunc Print() ", "output": "{\n\tv, release := version()\n\n\tif release {\n\t\tfmt.Printf(\"%s %s\\n\", filepath.Base(os.Args[0]), v)\n\t} else if v == \"devel\" {\n\t\tfmt.Printf(\"%s (no version)\\n\", filepath.Base(os.Args[0]))\n\t} else {\n\t\tfmt.Printf(\"%s (devel, %s)\\n\", filepath.Base(os.Args[0]), v)\n\t}\n}"} {"input": "package field\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype Path struct {\n\tname string \n\tindex string \n\tparent *Path \n}\n\n\nfunc NewPath(name string, moreNames ...string) *Path {\n\tr := &Path{name: name, parent: nil}\n\tfor _, anotherName := range moreNames {\n\t\tr = &Path{name: anotherName, parent: r}\n\t}\n\treturn r\n}\n\n\nfunc (p *Path) Root() *Path {\n\tfor ; p.parent != nil; p = p.parent {\n\t}\n\treturn p\n}\n\n\n\n\n\n\nfunc (p *Path) Index(index int) *Path {\n\treturn &Path{index: strconv.Itoa(index), parent: p}\n}\n\n\n\nfunc (p *Path) Key(key string) *Path {\n\treturn &Path{index: key, parent: p}\n}\n\n\nfunc (p *Path) String() string {\n\tif p == nil {\n\t\treturn \"\"\n\t}\n\telems := []*Path{}\n\tfor ; p != nil; p = p.parent {\n\t\telems = append(elems, p)\n\t}\n\n\tbuf := bytes.NewBuffer(nil)\n\tfor i := range elems {\n\t\tp := elems[len(elems)-1-i]\n\t\tif p.parent != nil && len(p.name) > 0 {\n\t\t\tbuf.WriteString(\".\")\n\t\t}\n\t\tif len(p.name) > 0 {\n\t\t\tbuf.WriteString(p.name)\n\t\t} else {\n\t\t\tfmt.Fprintf(buf, \"[%s]\", p.index)\n\t\t}\n\t}\n\treturn buf.String()\n}\n\nfunc (p *Path) Child(name string, moreNames ...string) *Path ", "output": "{\n\tr := NewPath(name, moreNames...)\n\tr.Root().parent = p\n\treturn r\n}"} {"input": "package cmd\n\nimport (\n\tboshdir \"github.com/cloudfoundry/bosh-cli/director\"\n\tboshui \"github.com/cloudfoundry/bosh-cli/ui\"\n)\n\ntype ManifestCmd struct {\n\tui boshui.UI\n\tdeployment boshdir.Deployment\n}\n\nfunc NewManifestCmd(ui boshui.UI, deployment boshdir.Deployment) ManifestCmd {\n\treturn ManifestCmd{ui: ui, deployment: deployment}\n}\n\n\n\nfunc (c ManifestCmd) Run() error ", "output": "{\n\tmanifest, err := c.deployment.Manifest()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.ui.PrintBlock(manifest)\n\n\treturn nil\n}"} {"input": "package vagrant\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t\"github.com/hashicorp/otto/ui\"\n)\n\n\n\ntype SSHCache struct {\n\tPath string\n\n\tVagrant *Vagrant\n}\n\n\n\n\n\n\n\n\n\nfunc (c *SSHCache) Cache() error {\n\tvar mockUi ui.Mock\n\tvagrant := *c.Vagrant\n\tvagrant.Ui = &mockUi\n\tif err := vagrant.Execute(\"ssh-config\"); err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(c.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tfor _, raw := range mockUi.RawBuf {\n\t\tif _, err := io.Copy(f, strings.NewReader(raw)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\nfunc (c *SSHCache) Delete() error {\n\tos.Remove(c.Path)\n\treturn nil\n}\n\nfunc (c *SSHCache) Exec(cacheOkay bool) error ", "output": "{\n\tif _, err := os.Stat(c.Path); err == nil {\n\t\tcmd := exec.Command(\"ssh\", \"-F\", c.Path, \"default\")\n\t\tcmd.Stdin = os.Stdin\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t\tif err := cmd.Start(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := cmd.Wait(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn c.Vagrant.Execute(\"ssh\")\n}"} {"input": "package model\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestNode_String(t *testing.T) ", "output": "{\n\tname := \"node-name\"\n\tid := \"id\"\n\tsize := \"node-size\"\n\n\tn := &Machine{\n\t\tID: id,\n\t\tName: name,\n\t\tSize: size,\n\t}\n\n\ts := n.String()\n\n\tif !strings.Contains(s, name) {\n\t\tt.Errorf(\"name %s not found in %s\", name, n.String())\n\t}\n\n\tif !strings.Contains(s, size) {\n\t\tt.Errorf(\"size %s not found in %s\", size, n.String())\n\t}\n\n\tif !strings.Contains(s, id) {\n\t\tt.Errorf(\"id %s not found in %s\", id, n.String())\n\t}\n}"} {"input": "package configmap\n\nimport (\n\t\"sync\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n)\n\n\ntype ManualWatcher struct {\n\tNamespace string\n\n\tsync.RWMutex\n\tobservers map[string][]Observer\n}\n\nvar _ Watcher = (*ManualWatcher)(nil)\n\n\nfunc (w *ManualWatcher) Watch(name string, o ...Observer) {\n\tw.Lock()\n\tdefer w.Unlock()\n\n\tif w.observers == nil {\n\t\tw.observers = make(map[string][]Observer, 1)\n\t}\n\tw.observers[name] = append(w.observers[name], o...)\n}\n\n\nfunc (w *ManualWatcher) ForEach(f func(string, []Observer) error) error {\n\tfor k, v := range w.observers {\n\t\tif err := f(k, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (w *ManualWatcher) OnChange(configMap *corev1.ConfigMap) {\n\tif configMap.Namespace != w.Namespace {\n\t\treturn\n\t}\n\tw.RLock()\n\tdefer w.RUnlock()\n\tfor _, o := range w.observers[configMap.Name] {\n\t\to(configMap)\n\t}\n}\n\nfunc (w *ManualWatcher) Start(<-chan struct{}) error ", "output": "{\n\treturn nil\n}"} {"input": "package time\n\nimport (\n\t\"errors\"\n\t\"syscall\"\n)\n\n\nfunc interrupt() {\n}\n\n\n\n\nfunc readFile(name string) ([]byte, error) {\n\tf, err := syscall.Open(name, syscall.O_RDONLY, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer syscall.Close(f)\n\tvar (\n\t\tbuf [4096]byte\n\t\tret []byte\n\t\tn int\n\t)\n\tfor {\n\t\tn, err = syscall.Read(f, buf[:])\n\t\tif n > 0 {\n\t\t\tret = append(ret, buf[:n]...)\n\t\t}\n\t\tif n == 0 || err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ret, err\n}\n\nfunc open(name string) (uintptr, error) {\n\tfd, err := syscall.Open(name, syscall.O_RDONLY, 0)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn uintptr(fd), nil\n}\n\nfunc closefd(fd uintptr) {\n\tsyscall.Close(syscall.Handle(fd))\n}\n\n\n\nfunc preadn(fd uintptr, buf []byte, off int) error ", "output": "{\n\twhence := seekStart\n\tif off < 0 {\n\t\twhence = seekEnd\n\t}\n\tif _, err := syscall.Seek(syscall.Handle(fd), int64(off), whence); err != nil {\n\t\treturn err\n\t}\n\tfor len(buf) > 0 {\n\t\tm, err := syscall.Read(syscall.Handle(fd), buf)\n\t\tif m <= 0 {\n\t\t\tif err == nil {\n\t\t\t\treturn errors.New(\"short read\")\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tbuf = buf[m:]\n\t}\n\treturn nil\n}"} {"input": "package commands\n\nimport (\n\t\"github.com/brooklyncentral/brooklyn-cli/net\"\n)\n\ntype AddLocation struct {\n\tnetwork *net.Network\n}\n\n\n\nfunc NewAddLocation(network *net.Network) (cmd *AddLocation) ", "output": "{\n\tcmd = new(AddLocation)\n\tcmd.network = network\n\treturn\n}"} {"input": "package slack\n\nimport (\n\t\"net/url\"\n\t\"time\"\n)\n\nconst (\n\tInitialReplyTimeout = 2 * time.Second\n\tMaxDelayedReplies = 5\n\tDelayedReplyTimeout = 28 * time.Minute\n)\n\ntype Command struct {\n\tToken string\n\tCommand string\n\tText string\n\tResponseURL string\n\tUser User\n\tChannel Channel\n\tTeam Team\n\tReceived time.Time\n}\n\ntype Team struct {\n\tID string\n\tDomain string\n}\n\ntype Channel struct {\n\tTeam Team\n\tID string\n\tName string\n}\n\ntype User struct {\n\tTeam Team\n\tID string\n\tName string\n}\n\n\n\nfunc ParseCommand(values url.Values) (Command, error) ", "output": "{\n\tteam := Team{\n\t\tID: values.Get(\"team_id\"),\n\t\tDomain: values.Get(\"team_domain\"),\n\t}\n\tchannel := Channel{\n\t\tTeam: team,\n\t\tID: values.Get(\"channel_id\"),\n\t\tName: values.Get(\"channel_name\"),\n\t}\n\tuser := User{\n\t\tTeam: team,\n\t\tID: values.Get(\"user_id\"),\n\t\tName: values.Get(\"user_name\"),\n\t}\n\tcommand := Command{\n\t\tToken: values.Get(\"token\"),\n\t\tCommand: values.Get(\"command\"),\n\t\tText: values.Get(\"text\"),\n\t\tResponseURL: values.Get(\"response_url\"),\n\t\tUser: user,\n\t\tChannel: channel,\n\t\tTeam: team,\n\t\tReceived: time.Now(),\n\t}\n\treturn command, nil\n}"} {"input": "package simple\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/spencergibb/go-nuvem/loadbalancer\"\n\t\"github.com/spencergibb/go-nuvem/loadbalancer/rule\"\n\t\"github.com/spencergibb/go-nuvem/loadbalancer/serverlist\"\n\t\"github.com/spf13/viper\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\"\n)\n\nfunc TestFactory(t *testing.T) {\n\tviper.SetConfigType(\"yaml\")\n\tyaml := []byte(`\nnuvem.loadbalancer.test.serverlist.static.servers:\n- localhost:8080\n- 127.0.0.1:9080\n`)\n\terr := viper.ReadConfig(bytes.NewBuffer(yaml))\n\tviper.SetDefault(\"nuvem.loadbalancer.test.factory\", FactoryKey)\n\n\tif err != nil { \n\t\tpanic(fmt.Errorf(\"Fatal error config file: %s \\n\", err))\n\t}\n\n\tlb := loadbalancer.Create(\"test\")\n\tassertLoadBalancer(t, lb)\n}\n\nfunc TestBuilder(t *testing.T) {\n\tprintln(\"\\nTestBuilder\")\n\tlb := NewBuilder().\n\t\tNamespace(\"test\").\n\t\tServerList(serverlist.NewStaticBuilder(\"test\").Servers(\"10.0.0.1:80\").Build()).\n\t\tRule(rule.NewRandomRule()).\n\t\tBuild()\n\n\tassertLoadBalancer(t, lb)\n}\n\n\n\nfunc assertLoadBalancer(t *testing.T, lb loadbalancer.LoadBalancer) ", "output": "{\n\trequire.NotNil(t, lb, \"lb was nil\")\n\n\tserver := lb.Choose()\n\tassert.NotNil(t, server, \"server was nil\")\n}"} {"input": "package provider\n\nimport (\n\t\"strings\"\n)\n\n\ntype DomainFilter struct {\n\tfilters []string\n\texclude []string\n}\n\n\nfunc prepareFilters(filters []string) []string {\n\tfs := make([]string, len(filters))\n\tfor i, domain := range filters {\n\t\tfs[i] = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), \".\"))\n\t}\n\treturn fs\n}\n\n\n\n\n\nfunc NewDomainFilter(domainFilters []string) DomainFilter {\n\treturn DomainFilter{prepareFilters(domainFilters), []string{}}\n}\n\n\nfunc (df DomainFilter) Match(domain string) bool {\n\treturn matchFilter(df.filters, domain, true) && !matchFilter(df.exclude, domain, false)\n}\n\n\n\n\nfunc matchFilter(filters []string, domain string, emptyval bool) bool {\n\tif len(filters) == 0 {\n\t\treturn emptyval\n\t}\n\n\tfor _, filter := range filters {\n\t\tstrippedDomain := strings.ToLower(strings.TrimSuffix(domain, \".\"))\n\n\t\tif filter == \"\" {\n\t\t\treturn emptyval\n\t\t} else if strings.HasPrefix(filter, \".\") && strings.HasSuffix(strippedDomain, filter) {\n\t\t\treturn true\n\t\t} else if strings.Count(strippedDomain, \".\") == strings.Count(filter, \".\") {\n\t\t\tif strippedDomain == filter {\n\t\t\t\treturn true\n\t\t\t}\n\t\t} else if strings.HasSuffix(strippedDomain, \".\"+filter) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (df DomainFilter) IsConfigured() bool {\n\tif len(df.filters) == 1 {\n\t\treturn df.filters[0] != \"\"\n\t}\n\treturn len(df.filters) > 0\n}\n\nfunc NewDomainFilterWithExclusions(domainFilters []string, excludeDomains []string) DomainFilter ", "output": "{\n\treturn DomainFilter{prepareFilters(domainFilters), prepareFilters(excludeDomains)}\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/pingcap/tidb\"\n\t\"github.com/pingcap/tidb/domain\"\n\t\"github.com/pingcap/tidb/model\"\n)\n\n\ntype StatsHandler struct {\n\tdo *domain.Domain\n}\n\n\n\nfunc (sh StatsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tparams := mux.Vars(req)\n\n\tis := sh.do.InfoSchema()\n\th := sh.do.StatsHandle()\n\ttbl, err := is.TableByName(model.NewCIStr(params[pDBName]), model.NewCIStr(params[pTableName]))\n\tif err != nil {\n\t\twriteError(w, err)\n\t} else {\n\t\tjs, err := h.DumpStatsToJSON(params[pDBName], tbl.Meta())\n\t\tif err != nil {\n\t\t\twriteError(w, err)\n\t\t} else {\n\t\t\twriteData(w, js)\n\t\t}\n\t}\n}\n\nfunc (s *Server) newStatsHandler() *StatsHandler ", "output": "{\n\tstore, ok := s.driver.(*TiDBDriver)\n\tif !ok {\n\t\tpanic(\"Illegal driver\")\n\t}\n\n\tdo, err := tidb.GetDomain(store.store)\n\tif err != nil {\n\t\tpanic(\"Failed to get domain\")\n\t}\n\treturn &StatsHandler{do}\n}"} {"input": "package retry\n\nimport (\n\t\"time\"\n)\n\ntype strategyFunc func(now time.Time) Timer\n\n\nfunc (f strategyFunc) NewTimer(now time.Time) Timer {\n\treturn f(now)\n}\n\n\n\n\nfunc LimitCount(n int, strategy Strategy) Strategy {\n\treturn strategyFunc(func(now time.Time) Timer {\n\t\treturn &countLimitTimer{\n\t\t\ttimer: strategy.NewTimer(now),\n\t\t\tremain: n,\n\t\t}\n\t})\n}\n\ntype countLimitTimer struct {\n\ttimer Timer\n\tremain int\n}\n\nfunc (t *countLimitTimer) NextSleep(now time.Time) (time.Duration, bool) {\n\tif t.remain--; t.remain <= 0 {\n\t\treturn 0, false\n\t}\n\treturn t.timer.NextSleep(now)\n}\n\n\n\nfunc LimitTime(limit time.Duration, strategy Strategy) Strategy {\n\treturn strategyFunc(func(now time.Time) Timer {\n\t\treturn &timeLimitTimer{\n\t\t\ttimer: strategy.NewTimer(now),\n\t\t\tend: now.Add(limit),\n\t\t}\n\t})\n}\n\ntype timeLimitTimer struct {\n\ttimer Timer\n\tend time.Time\n}\n\n\n\nfunc (t *timeLimitTimer) NextSleep(now time.Time) (time.Duration, bool) ", "output": "{\n\tsleep, ok := t.timer.NextSleep(now)\n\tif ok && now.Add(sleep).After(t.end) {\n\t\treturn 0, false\n\t}\n\treturn sleep, ok\n}"} {"input": "package atom\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestNewAtom(t *testing.T) ", "output": "{\n\n\ta := NewAtom(\"CA\", 1)\n\tif a.Name() != \"CA\" || a.Serial() != 1 {\n\t\tt.Error(\"wrong atom info\")\n\t}\n\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1alpha1 \"k8s.io/kops/pkg/client/clientset_generated/clientset/typed/kops/v1alpha1\"\n)\n\ntype FakeKopsV1alpha1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeKopsV1alpha1) Clusters(namespace string) v1alpha1.ClusterInterface {\n\treturn &FakeClusters{c, namespace}\n}\n\n\n\nfunc (c *FakeKopsV1alpha1) InstanceGroups(namespace string) v1alpha1.InstanceGroupInterface {\n\treturn &FakeInstanceGroups{c, namespace}\n}\n\n\n\nfunc (c *FakeKopsV1alpha1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeKopsV1alpha1) Federations(namespace string) v1alpha1.FederationInterface ", "output": "{\n\treturn &FakeFederations{c, namespace}\n}"} {"input": "package apiserver\n\nimport (\n\t\"net/http\"\n)\n\n\ntype MuxHelper struct {\n\tMux Mux\n\tRegisteredPaths []string\n}\n\nfunc (m *MuxHelper) Handle(path string, handler http.Handler) {\n\tm.RegisteredPaths = append(m.RegisteredPaths, path)\n\tm.Mux.Handle(path, handler)\n}\n\n\n\nfunc (m *MuxHelper) HandleFunc(path string, handler func(http.ResponseWriter, *http.Request)) ", "output": "{\n\tm.RegisteredPaths = append(m.RegisteredPaths, path)\n\tm.Mux.HandleFunc(path, handler)\n}"} {"input": "package protocol\n\nimport (\n\t\"context\"\n\n\t\"github.com/coffeehc/logger\"\n\t\"github.com/coffeehc/netx\"\n\t\"github.com/ugorji/go/codec\"\n)\n\ntype msgpackProtocol struct {\n\thander *codec.MsgpackHandle\n\tinterf func() interface{}\n}\n\n\n\n\nfunc (mp *msgpackProtocol) Encode(cxt context.Context, connContext netx.ConnContext, chain netx.ProtocolChain, data interface{}) {\n\tvar b []byte\n\tencode := codec.NewEncoderBytes(&b, mp.hander)\n\terr := encode.Encode(data)\n\tif err != nil {\n\t\tlogger.Error(\"Msgpack序列化错误:%s\", err)\n\t\treturn\n\t}\n\tchain.Fire(cxt, connContext, b)\n}\n\nfunc (mp *msgpackProtocol) Decode(cxt context.Context, connContext netx.ConnContext, chain netx.ProtocolChain, data interface{}) {\n\tif v, ok := data.([]byte); ok {\n\t\tobj := mp.interf()\n\t\tdecode := codec.NewDecoderBytes(v, mp.hander)\n\t\terr := decode.Decode(obj)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Msgpack反序列化失败:%s\", err)\n\t\t\treturn\n\t\t}\n\t\tdata = obj\n\t}\n\tchain.Fire(cxt, connContext, data)\n}\n\nfunc (mp *msgpackProtocol) EncodeDestroy() {}\n\nfunc (mp *msgpackProtocol) DecodeDestroy() {}\n\nfunc NewMsgpackProcotol(interfFunc func() interface{}) netx.Protocol ", "output": "{\n\tp := &msgpackProtocol{hander: new(codec.MsgpackHandle)}\n\tp.interf = interfFunc\n\tif p.interf == nil {\n\t\tp.interf = func() interface{} {\n\t\t\tvar i interface{}\n\t\t\treturn &i\n\t\t}\n\t}\n\treturn p\n}"} {"input": "package gtk\n\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (v *FileChooserButton) GetFocusOnClick() bool {\n\treturn gobool(C.gtk_file_chooser_button_get_focus_on_click(v.native()))\n}\n\n\n\n\n\n\n\nfunc (v *Button) GetFocusOnClick() bool {\n\tc := C.gtk_button_get_focus_on_click(v.native())\n\treturn gobool(c)\n}\n\n\nfunc (v *Button) SetFocusOnClick(focusOnClick bool) {\n\tC.gtk_button_set_focus_on_click(v.native(), gbool(focusOnClick))\n}\n\n\n\n\nfunc (v *TextIter) BeginsTag(v1 *TextTag) bool {\n\treturn gobool(C.gtk_text_iter_begins_tag(v.native(), v1.native()))\n}\n\n\n\n\nfunc (v *Window) ParseGeometry(geometry string) bool {\n\tcstr := C.CString(geometry)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_window_parse_geometry(v.native(), (*C.gchar)(cstr))\n\treturn gobool(c)\n}\n\n\nfunc (v *Window) ResizeToGeometry(width, height int) {\n\tC.gtk_window_resize_to_geometry(v.native(), C.gint(width), C.gint(height))\n}\n\n\nfunc (v *Window) SetDefaultGeometry(width, height int) {\n\tC.gtk_window_set_default_geometry(v.native(), C.gint(width),\n\t\tC.gint(height))\n}\n\nfunc (v *FileChooserButton) SetFocusOnClick(grabFocus bool) ", "output": "{\n\tC.gtk_file_chooser_button_set_focus_on_click(v.native(), gbool(grabFocus))\n}"} {"input": "package simelection\n\nimport \"sync\"\n\n\n\ntype Election struct {\n\tmu sync.RWMutex\n\tmasters []string\n}\n\n\n\n\n\n\nfunc (e *Election) Masters() []string {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\treturn e.masters\n}\n\n\nfunc (e *Election) SetMaster(who string) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\te.masters = []string{who}\n}\n\n\nfunc (e *Election) SetMasters(who []string) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\te.masters = who\n}\n\nfunc (e *Election) IsMaster(who string) bool ", "output": "{\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tfor _, m := range e.masters {\n\t\tif m == who {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package opt\n\nimport (\n\t\"encoding/json\"\n\t\"reflect\"\n)\n\n\n\ntype DisableTypoToleranceOnAttributesOption struct {\n\tvalue []string\n}\n\n\nfunc DisableTypoToleranceOnAttributes(v ...string) *DisableTypoToleranceOnAttributesOption {\n\treturn &DisableTypoToleranceOnAttributesOption{v}\n}\n\n\nfunc (o *DisableTypoToleranceOnAttributesOption) Get() []string {\n\tif o == nil {\n\t\treturn []string{}\n\t}\n\treturn o.value\n}\n\n\n\nfunc (o DisableTypoToleranceOnAttributesOption) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(o.value)\n}\n\n\n\nfunc (o *DisableTypoToleranceOnAttributesOption) UnmarshalJSON(data []byte) error {\n\tif string(data) == \"null\" {\n\t\to.value = []string{}\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(data, &o.value)\n}\n\n\n\n\n\n\n\n\n\nfunc DisableTypoToleranceOnAttributesEqual(o1, o2 *DisableTypoToleranceOnAttributesOption) bool {\n\treturn o1.Equal(o2)\n}\n\nfunc (o *DisableTypoToleranceOnAttributesOption) Equal(o2 *DisableTypoToleranceOnAttributesOption) bool ", "output": "{\n\tif o == nil {\n\t\treturn o2 == nil || reflect.DeepEqual(o2.value, []string{})\n\t}\n\tif o2 == nil {\n\t\treturn o == nil || reflect.DeepEqual(o.value, []string{})\n\t}\n\treturn reflect.DeepEqual(o.value, o2.value)\n}"} {"input": "package gamejam\n\ntype SceneID int\n\ntype Scene interface {\n\tAddComponent(c Component)\n\tLoad(r Resources) (err error)\n\tUnload(r Resources) (err error)\n\tRender()\n\tUpdate(mgr SceneManager)\n\tSetSceneID(id SceneID)\n\tSceneID() SceneID\n}\n\ntype BaseScene struct {\n\tcomponents map[ComponentID]Component\n\tid SceneID\n}\n\nfunc NewBaseScene() *BaseScene {\n\treturn &BaseScene{\n\t\tcomponents: map[ComponentID]Component{},\n\t}\n}\n\nfunc (s *BaseScene) AddComponent(c Component) {\n\tc.SetScene(s)\n\ts.components[c.GetID()] = c\n}\n\nfunc (s *BaseScene) Load(r Resources) (err error) {\n\treturn\n}\n\nfunc (s *BaseScene) Render() {\n}\n\nfunc (s *BaseScene) SetSceneID(id SceneID) {\n\ts.id = id\n}\n\n\n\nfunc (s *BaseScene) Unload(r Resources) (err error) {\n\tvar (\n\t\tid ComponentID\n\t\tc Component\n\t)\n\tfor id, c = range s.components {\n\t\ts.components[id] = nil\n\t\tc.Delete()\n\t}\n\treturn\n}\n\nfunc (s *BaseScene) Update(mgr SceneManager) {\n}\n\nfunc (s *BaseScene) SceneID() SceneID ", "output": "{\n\treturn s.id\n}"} {"input": "package main\n\nimport (\n\t\"encoding/base32\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/url\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc escape(encoding string) {\n\tswitch {\n\tcase strings.HasPrefix(\"query\", encoding):\n\t\tb, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tos.Stdout.Write([]byte(url.QueryEscape(string(b))))\n\tcase strings.HasPrefix(\"hex\", encoding):\n\t\tb, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tos.Stdout.Write([]byte(hex.EncodeToString(b)))\n\tdefault:\n\t\tfmt.Fprintf(os.Stderr, \"unknown escape encoding: %q\\n\", encoding)\n\t\tos.Exit(2)\n\t}\n}\n\n\n\nfunc main() {\n\tif len(os.Args) != 3 {\n\t\tfmt.Fprintf(os.Stderr, \"expected two arguments: : got %d\\n\", len(os.Args)-1)\n\t\tos.Exit(2)\n\t}\n\tmode := os.Args[1]\n\tswitch {\n\tcase strings.HasPrefix(\"escape\", mode):\n\t\tescape(os.Args[2])\n\tcase strings.HasPrefix(\"unescape\", mode) || strings.HasPrefix(\"decode\", mode):\n\t\tunescape(os.Args[2])\n\tdefault:\n\t\tfmt.Fprintf(os.Stderr, \"unknown mode: %q\\n\", mode)\n\t\tos.Exit(2)\n\t}\n}\n\nfunc unescape(encoding string) ", "output": "{\n\tswitch {\n\tcase strings.HasPrefix(\"query\", encoding):\n\t\tb, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\ts, err := url.QueryUnescape(string(b))\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tos.Stdout.Write([]byte(s))\n\tcase strings.HasPrefix(\"b32\", encoding):\n\t\td := base32.NewDecoder(base32.StdEncoding, os.Stdin)\n\t\tio.Copy(os.Stdout, d)\n\tdefault:\n\t\tfmt.Fprintf(os.Stderr, \"unknown unescape encoding: %q\\n\", encoding)\n\t}\n}"} {"input": "package user\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n\ntype RangeList []*Range\n\n\nfunc ParseRangeList(str string) (*RangeList, error) {\n\trl := RangeList{}\n\tif len(str) == 0 {\n\t\treturn &rl, nil\n\t}\n\tparts := strings.Split(str, \",\")\n\tfor _, p := range parts {\n\t\tr, err := ParseRange(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trl = append(rl, r)\n\t}\n\treturn &rl, nil\n}\n\n\n\n\n\nfunc (l *RangeList) Contains(uid int) bool {\n\tfor _, r := range *l {\n\t\tif r.Contains(uid) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (l *RangeList) Type() string {\n\treturn \"user.RangeList\"\n}\n\n\nfunc (l *RangeList) Set(value string) error {\n\tnewRangeList, err := ParseRangeList(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*l = *newRangeList\n\treturn nil\n}\n\n\nfunc (l *RangeList) String() string {\n\trangeStrings := []string{}\n\tfor _, r := range *l {\n\t\trangeStrings = append(rangeStrings, r.String())\n\t}\n\treturn strings.Join(rangeStrings, \",\")\n}\n\n\n\nfunc IsUserAllowed(user string, allowed *RangeList) bool {\n\tuid, err := strconv.Atoi(user)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn allowed.Contains(uid)\n}\n\nfunc (l *RangeList) Empty() bool ", "output": "{\n\tif len(*l) == 0 {\n\t\treturn true\n\t}\n\tfor _, r := range *l {\n\t\tif !r.Empty() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package telemetry\n\nimport \"time\"\n\n\ntype Config struct {\n\tPollingInterval time.Duration `json:\"polling-interval\"`\n\tDisabled bool `json:\"disabled\"`\n}\n\n\n\n\nfunc (p *Plugin) getConfig() (*Config, error) ", "output": "{\n\tconfig := &Config{}\n\tfound, err := p.Cfg.LoadValue(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !found {\n\t\tp.Log.Debug(\"Telemetry config not found\")\n\t\treturn nil, nil\n\t}\n\tp.Log.Debug(\"Telemetry config found\")\n\treturn config, err\n}"} {"input": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"time\"\n)\n\ntype TLSConnection struct {\n\thost string\n\tcertPool *x509.CertPool\n\tconn *tls.Conn\n}\n\nfunc NewTLSConnection(host string) (*TLSConnection, error) {\n\tc := &TLSConnection{}\n\tc.host = host\n\tc.getCerts()\n\terr := c.Connect()\n\treturn c, err\n}\n\n\n\nfunc (c *TLSConnection) WriteString(s string) (n int, err error) {\n\treturn io.WriteString(c.conn, s)\n}\n\nfunc (c *TLSConnection) Write(p []byte) (n int, err error) {\n\treturn c.conn.Write(p)\n}\n\nfunc (c *TLSConnection) Close() error {\n\treturn c.conn.Close()\n}\n\nfunc (c *TLSConnection) getCerts() {\n\tc.certPool = x509.NewCertPool()\n\tcert, err := ioutil.ReadFile(certsPemFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif !c.certPool.AppendCertsFromPEM(cert) {\n\t\tlog.Fatal(\"Failed parsing root certificate\")\n\t}\n}\n\nfunc (c *TLSConnection) Connect() (err error) ", "output": "{\n\tc.conn, err = tls.Dial(\"tcp\", c.host, &tls.Config{\n\t\tRootCAs: c.certPool,\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\tc.conn.SetWriteDeadline(time.Time{})\n\treturn\n}"} {"input": "package event_test\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/etherite/go-etherite/event\"\n)\n\n\n\nfunc ExampleNewSubscription() ", "output": "{\n\tch := make(chan int)\n\tsub := event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tfor i := 0; i < 10; i++ {\n\t\t\tselect {\n\t\t\tcase ch <- i:\n\t\t\tcase <-quit:\n\t\t\t\tfmt.Println(\"unsubscribed\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\tfor i := range ch {\n\t\tfmt.Println(i)\n\t\tif i == 4 {\n\t\t\tsub.Unsubscribe()\n\t\t\tbreak\n\t\t}\n\t}\n}"} {"input": "package stop\n\nimport (\n\t\"github.com/seehuhn/classification/data\"\n)\n\n\n\n\n\ntype Function func(data.Histogram) bool\n\n\n\n\n\n\nfunc IfAtMost(n float64) Function {\n\treturn func(hist data.Histogram) bool {\n\t\treturn hist.Sum() <= n\n\t}\n}\n\n\n\n\n\n\n\n\nfunc IfPureOrAtMost(n float64) Function {\n\treturn func(hist data.Histogram) bool {\n\t\ttotal := 0.0\n\t\tk := 0\n\t\tfor _, ni := range hist {\n\t\t\ttotal += ni\n\t\t\tif ni > 0 {\n\t\t\t\tk++\n\t\t\t}\n\t\t\tif k > 1 && total > n {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n}\n\nfunc IfPure(hist data.Histogram) bool ", "output": "{\n\tk := 0\n\tfor _, ni := range hist {\n\t\tif ni > 0 {\n\t\t\tk++\n\t\t\tif k > 1 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package utilmocks\n\nimport (\n\tcontext \"context\"\n\tgomock \"github.com/golang/mock/gomock\"\n\texec \"os/exec\"\n\treflect \"reflect\"\n)\n\n\ntype MockCommandRunner struct {\n\tctrl *gomock.Controller\n\trecorder *MockCommandRunnerMockRecorder\n}\n\n\ntype MockCommandRunnerMockRecorder struct {\n\tmock *MockCommandRunner\n}\n\n\nfunc NewMockCommandRunner(ctrl *gomock.Controller) *MockCommandRunner {\n\tmock := &MockCommandRunner{ctrl: ctrl}\n\tmock.recorder = &MockCommandRunnerMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockCommandRunner) EXPECT() *MockCommandRunnerMockRecorder {\n\treturn m.recorder\n}\n\n\nfunc (m *MockCommandRunner) Run(ctx context.Context, command *exec.Cmd) ([]byte, []byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Run\", ctx, command)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].([]byte)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}\n\n\n\n\nfunc (mr *MockCommandRunnerMockRecorder) Run(ctx, command interface{}) *gomock.Call ", "output": "{\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Run\", reflect.TypeOf((*MockCommandRunner)(nil).Run), ctx, command)\n}"} {"input": "package source\n\n\n\n\ntype AssertionStatement struct {\n\tfields AssertionFields\n\tsource Code\n}\n\ntype AssertionFields struct {\n\tOwner string \n\tCalled string \n\tOptions \n}\n\n\n\n\n\nfunc (ts AssertionStatement) Source() Code {\n\treturn ts.source\n}\n\nfunc (ts AssertionStatement) Fields() AssertionFields ", "output": "{\n\treturn ts.fields\n}"} {"input": "package vm\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc newStack() *stack {\n\treturn &stack{}\n}\n\ntype stack struct {\n\tdata []*big.Int\n\tptr int\n}\n\nfunc (st *stack) push(d *big.Int) {\n\tstackItem := new(big.Int).Set(d)\n\tif len(st.data) > st.ptr {\n\t\tst.data[st.ptr] = stackItem\n\t} else {\n\t\tst.data = append(st.data, stackItem)\n\t}\n\tst.ptr++\n}\n\nfunc (st *stack) pop() (ret *big.Int) {\n\tst.ptr--\n\tret = st.data[st.ptr]\n\treturn\n}\n\nfunc (st *stack) len() int {\n\treturn st.ptr\n}\n\nfunc (st *stack) swap(n int) {\n\tst.data[st.len()-n], st.data[st.len()-1] = st.data[st.len()-1], st.data[st.len()-n]\n}\n\nfunc (st *stack) dup(n int) {\n\tst.push(st.data[st.len()-n])\n}\n\n\n\nfunc (st *stack) require(n int) error {\n\tif st.len() < n {\n\t\treturn fmt.Errorf(\"stack underflow (%d <=> %d)\", len(st.data), n)\n\t}\n\treturn nil\n}\n\nfunc (st *stack) Print() {\n\tfmt.Println(\"### stack ###\")\n\tif len(st.data) > 0 {\n\t\tfor i, val := range st.data {\n\t\t\tfmt.Printf(\"%-3d %v\\n\", i, val)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"-- empty --\")\n\t}\n\tfmt.Println(\"#############\")\n}\n\nfunc (st *stack) peek() *big.Int ", "output": "{\n\treturn st.data[st.len()-1]\n}"} {"input": "package backups\n\nimport (\n\t\"github.com/juju/errors\"\n\n\t\"github.com/juju/juju/apiserver/params\"\n)\n\n\n\n\nfunc (a *API) List(args params.BackupsListArgs) (params.BackupsListResult, error) ", "output": "{\n\tvar result params.BackupsListResult\n\n\tbackups, closer := newBackups(a.backend)\n\tdefer closer.Close()\n\n\tmetaList, err := backups.List()\n\tif err != nil {\n\t\treturn result, errors.Trace(err)\n\t}\n\n\tresult.List = make([]params.BackupsMetadataResult, len(metaList))\n\tfor i, meta := range metaList {\n\t\tresult.List[i] = ResultFromMetadata(meta)\n\t}\n\n\treturn result, nil\n}"} {"input": "package rackspace\n\nimport (\n\t\"gopkg.in/goose.v2/nova\"\n\n\t\"github.com/juju/juju/provider/openstack\"\n)\n\ntype rackspaceNetworkingDecorator struct{}\n\n\n\n\ntype rackspaceNetworking struct {\n\topenstack.Networking\n}\n\n\nfunc (rackspaceNetworking) DefaultNetworks() ([]nova.ServerNetworks, error) {\n\treturn []nova.ServerNetworks{\n\t\t{NetworkId: \"00000000-0000-0000-0000-000000000000\"}, \n\t\t{NetworkId: \"11111111-1111-1111-1111-111111111111\"}, \n\t}, nil\n}\n\nfunc (d rackspaceNetworkingDecorator) DecorateNetworking(n openstack.Networking) (openstack.Networking, error) ", "output": "{\n\treturn rackspaceNetworking{n}, nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n)\n\ntype configRepo struct {\n\tUrl string `json:\"url\"`\n\tDirectory string `json:\"directory\"`\n\tHidden bool `json:\"hidden\"`\n\tType string `json:\"type\"`\n\tCommand CommandInfo `json:\"command\"`\n}\n\ntype Config struct {\n\tRepos map[string]Repo\n}\n\n\n\nfunc ParseConfig(file string) (*Config, error) ", "output": "{\n\tdata, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := Config{Repos: make(map[string]Repo)}\n\n\tvar c struct {\n\t\tRepos []configRepo `json:\"repos\"`\n\t}\n\n\tif err = json.Unmarshal(data, &c); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, repo := range c.Repos {\n\t\tr := Git{\n\t\t\tUrl: repo.Url,\n\t\t\tdirectory: repo.Directory,\n\t\t\tHidden: repo.Hidden,\n\t\t\tCommand: repo.Command,\n\t\t}\n\n\t\towner, name := r.Name()\n\t\tconfig.Repos[owner+\"/\"+name] = r\n\t}\n\n\treturn &config, nil\n}"} {"input": "package internal\n\nvar _ TerminateFile = &terminateFile{}\n\ntype terminateFile struct {\n\tname string\n\tpath string\n}\n\nfunc newTerminateFile(name string, path string) TerminateFile {\n\treturn &terminateFile{\n\t\tname: name,\n\t\tpath: path,\n\t}\n}\n\n\n\n\n\nfunc (t *terminateFile) Path() string {\n\treturn t.path\n}\n\nfunc (t *terminateFile) Name() string ", "output": "{\n\treturn t.name\n}"} {"input": "package utils\n\nimport \"fmt\"\n\nfunc ExampleStringSet_Add() {\n\tset := NewStringSet()\n\tset.Add(\"a\")\n\tset.Add(\"b\")\n\n\tfmt.Println(set)\n\tset.Add(\"a\")\n\tfmt.Println(set)\n\n}\n\nfunc ExampleNewStringSet() {\n\ta := NewStringSet()\n\ta.Add(\"a\")\n\ta.Add(\"b\")\n\n\tb := NewStringSet(\"b\", \"a\")\n\n\tfmt.Println(a.Equals(b))\n\n}\n\nfunc ExampleNewStringSetFromStringMapKeys() {\n\tm := map[string]string{\n\t\t\"a\": \"some a value\",\n\t\t\"b\": \"some b value\",\n\t}\n\n\tset := NewStringSetFromStringMapKeys(m)\n\tfmt.Println(set)\n\n}\n\nfunc ExampleStringSet_ToSlice() {\n\ta := NewStringSet()\n\ta.Add(\"z\")\n\ta.Add(\"b\")\n\n\tfmt.Println(a.ToSlice())\n\n}\n\nfunc ExampleStringSet_IsEmpty() {\n\ta := NewStringSet()\n\n\tfmt.Println(a.IsEmpty())\n\ta.Add(\"a\")\n\tfmt.Println(a.IsEmpty())\n\n}\n\nfunc ExampleStringSet_Equals() {\n\ta := NewStringSet(\"a\", \"b\")\n\tb := NewStringSet(\"a\", \"b\", \"c\")\n\tfmt.Println(a.Equals(b))\n\n\ta.Add(\"c\")\n\tfmt.Println(a.Equals(b))\n\n}\n\nfunc ExampleStringSet_Contains() {\n\ta := NewStringSet(\"a\", \"b\")\n\tfmt.Println(a.Contains(\"z\"))\n\tfmt.Println(a.Contains(\"a\"))\n\n}\n\n\n\nfunc ExampleStringSet_Minus() ", "output": "{\n\ta := NewStringSet(\"a\", \"b\")\n\tb := NewStringSet(\"b\", \"c\")\n\tdelta := a.Minus(b)\n\n\tfmt.Println(delta)\n}"} {"input": "package api\n\nimport (\n\t\"testing\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc getDefaultService() *Service {\n\treturn &Service{\n\t\tHealthy: true,\n\t}\n}\n\n\n\nfunc TestService_RootHandler(t *testing.T) {\n\tgin.SetMode(gin.ReleaseMode)\n\tctx, w, router := gin.CreateTestContext()\n\tsvc := getDefaultService()\n\n\tsvc.RootHandler(ctx)\n\n\tif ctx.Writer.Status() != 200 {\n\t\tt.Fatal(\"Wrong status code\")\n\t}\n\t_ = w\n\t_ = router\n}\n\nfunc TestService_IsHealthy(t *testing.T) {\n\tsvc := getDefaultService()\n\tif !svc.IsHealthy() {\n\t\tt.Fatal(\"err: Service is not healthy\")\n\t}\n}\n\nfunc Benchmark_IsHealthy(b *testing.B) {\n\tgin.SetMode(gin.ReleaseMode)\n\tsvc := getDefaultService()\n\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tsvc.IsHealthy()\n\t}\n}\n\nfunc Benchmark_RootHandler(b *testing.B) {\n\tgin.SetMode(gin.ReleaseMode)\n\tsvc := getDefaultService()\n\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tctx, _, _ := gin.CreateTestContext()\n\t\tsvc.RootHandler(ctx)\n\t}\n}\n\nfunc Benchmark_HealthHandler(b *testing.B) {\n\tgin.SetMode(gin.ReleaseMode)\n\tsvc := getDefaultService()\n\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tb.StopTimer()\n\t\tctx, _, _ := gin.CreateTestContext()\n\t\tb.StartTimer()\n\t\tsvc.HealthHandler(ctx)\n\t}\n}\n\nfunc TestService_HealthHandler(t *testing.T) ", "output": "{\n\tgin.SetMode(gin.ReleaseMode)\n\tctx, _, _ := gin.CreateTestContext()\n\tsvc := getDefaultService()\n\n\tsvc.HealthHandler(ctx)\n\n\tif ctx.Writer.Status() != 200 {\n\t\tt.Fatal(\"Wrong status code\")\n\t}\n\n\tsvc.Healthy = false\n\tsvc.HealthHandler(ctx)\n\tif ctx.Writer.Status() == 200 {\n\t\tt.Fatal(\"Wrong status code\")\n\t}\n}"} {"input": "package builtin\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestUnix2Windows(t *testing.T) ", "output": "{\n\tAssert(windowsPath(\"foo\"), `foo`, t)\n\tAssert(windowsPath(\"foo/bar\"), `foo\\bar`, t)\n\tAssert(windowsPath(\"/foo/bar\"), `\\foo\\bar`, t)\n\tAssert(windowsPath(\"/c/foo/bar\"), `c:\\foo\\bar`, t)\n}"} {"input": "package thrift\n\nimport (\n\t\"net\"\n)\n\n\ntype socketConn struct {\n\tnet.Conn\n\n\tbuffer [1]byte\n}\n\nvar _ net.Conn = (*socketConn)(nil)\n\n\n\nfunc createSocketConnFromReturn(conn net.Conn, err error) (*socketConn, error) {\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &socketConn{\n\t\tConn: conn,\n\t}, nil\n}\n\n\nfunc wrapSocketConn(conn net.Conn) *socketConn {\n\tif sc, ok := conn.(*socketConn); ok {\n\t\treturn sc\n\t}\n\n\treturn &socketConn{\n\t\tConn: conn,\n\t}\n}\n\n\n\n\n\n\n\n\nfunc (sc *socketConn) isValid() bool {\n\treturn sc != nil && sc.Conn != nil\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (sc *socketConn) IsOpen() bool {\n\tif !sc.isValid() {\n\t\treturn false\n\t}\n\treturn sc.checkConn() == nil\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (sc *socketConn) Read(p []byte) (n int, err error) ", "output": "{\n\tif len(p) == 0 {\n\t\treturn 0, sc.read0()\n\t}\n\n\treturn sc.Conn.Read(p)\n}"} {"input": "package layers\n\nimport (\n\t\"math\"\n\n\t\"github.com/gerardabello/weight\"\n\t\"github.com/gerardabello/weight/tensor\"\n)\n\ntype SigmoidLayer struct {\n\tBaseLayer\n}\n\n\n\nfunc (l *SigmoidLayer) CreateSlave() weight.Layer {\n\tnl := NewSigmoidLayer(l.GetInputSize()...)\n\tnl.id = l.ID()\n\n\treturn nl\n}\n\nfunc (l *SigmoidLayer) Activate(input *tensor.Tensor) (*tensor.Tensor, error) {\n\tl.mutex.Lock()\n\terr := l.BaseLayer.Activate(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinputs := input.Values\n\n\tfor i := range l.output.Values {\n\t\tl.output.Values[i] = 1 / (1 + math.Exp(-inputs[i]))\n\t}\n\n\tl.mutex.Unlock()\n\treturn &l.output, nil\n}\n\nfunc (l *SigmoidLayer) BackPropagate(err *tensor.Tensor) (*tensor.Tensor, error) {\n\tl.mutex.Lock()\n\te := l.BaseLayer.BackPropagate(err)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\n\terrs := err.Values\n\tinputs := l.lastInput.Values\n\n\tfor i := range l.propagation.Values {\n\t\tl.propagation.Values[i] = math.Exp(-inputs[i]) / math.Pow(1+math.Exp(-inputs[i]), 2) * errs[i]\n\t}\n\n\tl.mutex.Unlock()\n\treturn &l.propagation, nil\n}\n\nfunc NewSigmoidLayer(size ...int) *SigmoidLayer ", "output": "{\n\tlayer := &SigmoidLayer{}\n\tlayer.BaseLayer.Init(size, size)\n\treturn layer\n}"} {"input": "package boom\n\nimport (\n\t\"github.com/efritz/glock\"\n)\n\ntype TaskConfig func(*taskConfig)\n\ntype taskConfig struct {\n\tclock glock.Clock\n}\n\nfunc newTaskConfig() *taskConfig {\n\treturn &taskConfig{\n\t\tclock: glock.NewRealClock(),\n\t}\n}\n\n\n\nfunc WithClock(clock glock.Clock) TaskConfig {\n\treturn func(cfg *taskConfig) {\n\t\tcfg.clock = clock\n\t}\n}\n\nfunc (tc *taskConfig) ApplyConfigs(configs []TaskConfig) ", "output": "{\n\tfor _, f := range configs {\n\t\tf(tc)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc square(i interface{}) interface{} {\n\tval, ok := i.(int)\n\tif ok {\n\t\treturn val * val\n\t}\n\tpanic(\"Not a number\")\n}\n\nfunc main() {\n\tarr := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n\tfmt.Println(mapper(square, arr))\n}\n\nfunc mapper(f func(interface{}) interface{}, vals []interface{}) []interface{} ", "output": "{\n\tout := make([]interface{}, len(vals))\n\tfor i, val := range vals {\n\t\tout[i] = f(val)\n\t}\n\treturn out\n}"} {"input": "package gotify\n\nimport (\n\t\"github.com/antonholmquist/jason\"\n)\n\nfunc parseAlbum(o *jason.Object) Album {\n\talbumName, _ := o.GetString(\"name\")\n\talbumUri, _ := o.GetString(\"uri\")\n\n\talbum := Album{albumName, albumUri}\n\n\treturn album\n}\n\nfunc parseArtist(o *jason.Object) Artist {\n\tartistName, _ := o.GetString(\"name\")\n\tartistUri, _ := o.GetString(\"uri\")\n\n\tartist := Artist{artistName, artistUri}\n\n\treturn artist\n}\n\n\n\nfunc parseTracks(o []*jason.Object) []Track {\n\ttracks := []Track{}\n\n\tfor _, jsonTrack := range o {\n\t\ttracks = append(tracks, parseTrack(jsonTrack))\n\t}\n\n\treturn tracks\n}\n\nfunc parseAlbums(o []*jason.Object) []Album {\n\talbums := []Album{}\n\n\tfor _, jsonAlbum := range o {\n\t\talbums = append(albums, parseAlbum(jsonAlbum))\n\t}\n\n\treturn albums\n}\n\nfunc parseArtists(o []*jason.Object) []Artist {\n\tartists := []Artist{}\n\n\tfor _, jsonArtist := range o {\n\t\tartists = append(artists, parseArtist(jsonArtist))\n\t}\n\n\treturn artists\n}\n\nfunc parsePlaylist(o *jason.Object) SpotifyPlaylist {\n\treturn SpotifyPlaylist{}\n}\n\nfunc parseTrack(o *jason.Object) Track ", "output": "{\n\ttrackName, _ := o.GetString(\"name\")\n\ttrackUri, _ := o.GetString(\"uri\")\n\n\tjsonAlbum, err := o.GetObject(\"album\")\n\n\tvar album Album\n\tif err == nil {\n\t\talbum = parseAlbum(jsonAlbum)\n\t}\n\n\tjsonArtists, err := o.GetObjectArray(\"artists\")\n\n\tvar artists []Artist\n\tif err == nil {\n\t\tartists = parseArtists(jsonArtists)\n\t}\n\n\ttrack := Track{trackName, trackUri, album, artists}\n\n\treturn track\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/shaunmza/coinmarketcap\"\n)\n\nfunc main() {\n\n\tvar r coinmarketcap.Ticker\n\tvar err error\n\n\tt := make([]string, 0)\n\tt = append(t, \"bitcoin\")\n\tt = append(t, \"litecoin\")\n\tt = append(t, \"steem\")\n\tt = append(t, \"steem-dollars\")\n\n\tperiod := 60 * 5\n\tticker := time.NewTicker(time.Second * time.Duration(period))\n\n\tr, err = coinmarketcap.GetData(t)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error! %s, Last Updated: %s\\n\", err, r.LastUpdate)\n\t}\n\n\tprintData(r)\n\n\tfor _ = range ticker.C {\n\t\tr, err = coinmarketcap.GetData(t)\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error! %s, Last Updated: %s\\n\", err, r.LastUpdate)\n\t\t}\n\t\tprintData(r)\n\n\t}\n\n}\n\n\n\nfunc printData(r coinmarketcap.Ticker) ", "output": "{\n\tfor _, coin := range r.Coins {\n\t\tfmt.Println(\"Symbol: '\" + coin.Symbol + \"', Name: '\" +\n\t\t\tcoin.Name + \"', Price Bitcoin: '\" +\n\t\t\tcoin.PriceBtc + \"', Price USD: '\" + coin.PriceUsd + \"'\")\n\t}\n}"} {"input": "package crypto\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"io\"\n\t\"time\"\n)\n\n\n\n\n\n\n\nfunc Timestamp() int64 {\n\treturn time.Now().UTC().Unix()\n}\n\n\nfunc Base64Encode(value []byte) []byte {\n\tenc := make([]byte, base64.RawURLEncoding.EncodedLen(len(value)))\n\tbase64.RawURLEncoding.Encode(enc, value)\n\treturn enc\n}\n\n\nfunc Base64Decode(value []byte) ([]byte, error) {\n\tdec := make([]byte, base64.RawURLEncoding.DecodedLen(len(value)))\n\tb, err := base64.RawURLEncoding.Decode(dec, value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dec[:b], nil\n}\n\nfunc GenerateRandomBytes(n int) []byte ", "output": "{\n\tb := make([]byte, n)\n\tif _, err := io.ReadFull(rand.Reader, b); err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}"} {"input": "package fix\n\nimport (\n\t\"strings\"\n\n\t\"github.com/mitchellh/mapstructure\"\n)\n\n\n\ntype FixerAmazonShutdownBehavior struct{}\n\n\n\nfunc (FixerAmazonShutdownBehavior) Fix(input map[string]interface{}) (map[string]interface{}, error) {\n\ttype template struct {\n\t\tBuilders []map[string]interface{}\n\t}\n\n\tvar tpl template\n\tif err := mapstructure.Decode(input, &tpl); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, builder := range tpl.Builders {\n\t\tbuilderTypeRaw, ok := builder[\"type\"]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tbuilderType, ok := builderTypeRaw.(string)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !strings.HasPrefix(builderType, \"amazon-\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tshutdownBehavior, ok := builder[\"shutdown_behaviour\"]\n\n\t\tif ok {\n\t\t\tbuilder[\"shutdown_behavior\"] = shutdownBehavior\n\t\t\tdelete(builder, \"shutdown_behaviour\")\n\t\t}\n\t}\n\n\tinput[\"builders\"] = tpl.Builders\n\treturn input, nil\n}\n\nfunc (FixerAmazonShutdownBehavior) Synopsis() string {\n\treturn `Changes \"shutdown_behaviour\" to \"shutdown_behavior\" in Amazon builders.`\n}\n\nfunc (FixerAmazonShutdownBehavior) DeprecatedOptions() map[string][]string ", "output": "{\n\treturn map[string][]string{\n\t\t\"*amazon*\": []string{\"shutdown_behaviour\"},\n\t}\n}"} {"input": "package validating\n\nimport (\n\t\"io\"\n\n\t\"k8s.io/apiserver/pkg/admission\"\n\t\"k8s.io/apiserver/pkg/admission/configuration\"\n\t\"k8s.io/apiserver/pkg/admission/plugin/webhook/generic\"\n)\n\nconst (\n\tPluginName = \"ValidatingAdmissionWebhook\"\n)\n\n\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(configFile io.Reader) (admission.Interface, error) {\n\t\tplugin, err := NewValidatingAdmissionWebhook(configFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn plugin, nil\n\t})\n}\n\n\ntype Plugin struct {\n\t*generic.Webhook\n}\n\nvar _ admission.ValidationInterface = &Plugin{}\n\n\n\n\n\nfunc (a *Plugin) Validate(attr admission.Attributes) error {\n\treturn a.Webhook.Dispatch(attr)\n}\n\nfunc NewValidatingAdmissionWebhook(configFile io.Reader) (*Plugin, error) ", "output": "{\n\thandler := admission.NewHandler(admission.Connect, admission.Create, admission.Delete, admission.Update)\n\twebhook, err := generic.NewWebhook(handler, configFile, configuration.NewValidatingWebhookConfigurationManager, newValidatingDispatcher)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Plugin{webhook}, nil\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/golang/glog\"\n)\n\n\n\nvar heapster_url string\n\n\nfunc setupHandlers(url string) *gin.Engine {\n\theapster_url = url\n\tr := gin.Default()\n\tr.Static(\"/static\", \"./static\")\n\tr.Static(\"/pages\", \"./pages\")\n\n\tr.LoadHTMLGlob(\"pages/index.html\")\n\n\tr.GET(\"/\", indexHandler)\n r.GET(\"/api/*uri\", apiHandler)\n\treturn r\n}\n\n\n\n\n\nfunc apiHandler(c *gin.Context) {\n\turi := c.Request.RequestURI\n\tmetric_url := heapster_url + uri\n\tresp, err := http.Get(metric_url)\n\tif err != nil {\n\t\tglog.Fatalf(\"unable to GET %s\", metric_url)\n\t}\n\tif resp.StatusCode != 200 {\n\t\tglog.Errorf(\"GET %s responded with status code: %d\", metric_url, resp.StatusCode)\n\t\treturn\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tglog.Errorf(\"unable to read response body from %s\", metric_url)\n\t\treturn\n\t}\n\n\t_, err = c.Writer.Write(body)\n\tif err != nil {\n\t\tglog.Errorf(\"unable to write body to response for %s\", uri)\n\t}\n}\n\nfunc indexHandler(c *gin.Context) ", "output": "{\n\tvars := gin.H{}\n\tc.HTML(200, \"index.html\", vars)\n}"} {"input": "package v1\n\nimport (\n\tcommon \"github.com/kubeflow/common/pkg/apis/common/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\n\n\nfunc Int32(v int32) *int32 {\n\treturn &v\n}\n\nfunc addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}\n\n\n\n\n\nfunc setDefaultsTypeWorker(spec *common.ReplicaSpec) {\n\tif spec != nil && spec.RestartPolicy == \"\" {\n\t\tspec.RestartPolicy = DefaultRestartPolicy\n\t}\n}\n\nfunc SetDefaults_MPIJob(mpiJob *MPIJob) {\n\tif mpiJob.Spec.CleanPodPolicy == nil {\n\t\tnone := common.CleanPodPolicyNone\n\t\tmpiJob.Spec.CleanPodPolicy = &none\n\t}\n\n\tsetDefaultsTypeLauncher(mpiJob.Spec.MPIReplicaSpecs[MPIReplicaTypeLauncher])\n\n\tsetDefaultsTypeWorker(mpiJob.Spec.MPIReplicaSpecs[MPIReplicaTypeWorker])\n}\n\nfunc setDefaultsTypeLauncher(spec *common.ReplicaSpec) ", "output": "{\n\tif spec != nil && spec.RestartPolicy == \"\" {\n\t\tspec.RestartPolicy = DefaultRestartPolicy\n\t}\n}"} {"input": "package vcl\n\n\n\n\nimport (\n\t. \"github.com/ying32/govcl/vcl/api\"\n\t. \"github.com/ying32/govcl/vcl/types\"\n)\n\ntype (\n\tNSObject uintptr\n\n\tNSWindow uintptr\n\n\tNSURL uintptr\n)\n\n\nfunc HandleToPlatformHandle(h HWND) NSObject {\n\treturn NSObject(h)\n}\n\nfunc (f *TForm) PlatformWindow() NSWindow {\n\tr, _, _ := NSWindow_FromForm.Call(f.instance)\n\treturn NSWindow(r)\n}\n\n\n\nfunc (n NSWindow) SetTitleVisibility(flag NSWindowTitleVisibility) {\n\tNSWindow_setTitleVisibility.Call(uintptr(n), uintptr(flag))\n}\n\nfunc (n NSWindow) TitleBarAppearsTransparent() bool {\n\tr, _, _ := NSWindow_titlebarAppearsTransparent.Call(uintptr(n))\n\treturn DBoolToGoBool(r)\n}\n\nfunc (n NSWindow) SetTitleBarAppearsTransparent(flag bool) {\n\tNSWindow_setTitlebarAppearsTransparent.Call(uintptr(n), GoBoolToDBool(flag))\n}\n\nfunc (n NSWindow) SetRepresentedURL(url NSURL) {\n\tNSWindow_setRepresentedURL.Call(uintptr(n), uintptr(url))\n}\n\nfunc (n NSWindow) StyleMask() uint {\n\tr, _, _ := NSWindow_styleMask.Call(uintptr(n))\n\treturn uint(r)\n}\n\nfunc (n NSWindow) SetStyleMask(mask uint) {\n\tNSWindow_setStyleMask.Call(uintptr(n), uintptr(mask))\n}\n\nfunc (n NSWindow) TitleVisibility() NSWindowTitleVisibility ", "output": "{\n\tr, _, _ := NSWindow_titleVisibility.Call(uintptr(n))\n\treturn NSWindowTitleVisibility(r)\n}"} {"input": "package MySQLProtocol\n\nimport \"testing\"\nimport \"github.com/stretchr/testify/assert\"\n\nvar LOCAL_INFILE_Request_test_packets = []struct {\n\tpacket Proto\n\tcontext Context\n}{\n\t{packet: Proto{data: StringToPacket(`\n0c 00 00 01 fb 2f 65 74 63 2f 70 61 73 73 77 64 ...../etc/passwd\n`)}, context: Context{}},\n}\n\n\n\nfunc Benchmark_Packet_LOCAL_INFILE_Request_FromPacket(b *testing.B) {\n\tcontext := Context{capability: CLIENT_PROTOCOL_41}\n\tvar pkt Packet_LOCAL_INFILE_Request\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt = Packet_LOCAL_INFILE_Request{}\n\t\tLOCAL_INFILE_Request_test_packets[0].packet.offset = 0\n\t\tpkt.FromPacket(context, LOCAL_INFILE_Request_test_packets[0].packet)\n\t}\n}\n\nfunc Benchmark_Packet_LOCAL_INFILE_Request_GetPacketSize(b *testing.B) {\n\tcontext := Context{capability: CLIENT_PROTOCOL_41}\n\tpkt := Packet_LOCAL_INFILE_Request{}\n\tpkt.FromPacket(context, LOCAL_INFILE_Request_test_packets[0].packet)\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt.GetPacketSize(context)\n\t}\n}\n\nfunc Benchmark_Packet_LOCAL_INFILE_Request_ToPacket(b *testing.B) {\n\tcontext := Context{capability: CLIENT_PROTOCOL_41}\n\tpkt := Packet_LOCAL_INFILE_Request{}\n\tpkt.FromPacket(context, LOCAL_INFILE_Request_test_packets[0].packet)\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt.ToPacket(context)\n\t}\n}\n\nfunc Test_Packet_LOCAL_INFILE_Request(t *testing.T) ", "output": "{\n\tvar pkt Packet_LOCAL_INFILE_Request\n\tfor _, value := range LOCAL_INFILE_Request_test_packets {\n\t\tpkt = Packet_LOCAL_INFILE_Request{}\n\t\tpkt.FromPacket(value.context, value.packet)\n\t\tassert.Equal(t, pkt.ToPacket(value.context), value.packet.data, \"\")\n\t}\n}"} {"input": "package fake\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\n\t. \"github.com/onsi/gomega\"\n\t\"github.com/onsi/gomega/ghttp\"\n)\n\ntype CFAPI struct {\n\tserver *ghttp.Server\n}\n\ntype CFAPIConfig struct {\n\tRoutes map[string]Response\n}\n\ntype Response struct {\n\tCode int\n\tBody interface{}\n}\n\n\n\nfunc (a *CFAPI) SetConfiguration(config CFAPIConfig) {\n\ta.server.Reset()\n\n\tfor request, response := range config.Routes {\n\t\tmethod, path := parseRequest(request)\n\t\tresponseBytes, err := json.Marshal(response.Body)\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\ta.server.RouteToHandler(method, path, ghttp.RespondWith(response.Code, responseBytes))\n\t}\n}\n\nfunc (a *CFAPI) Close() {\n\ta.server.Close()\n}\n\nfunc (a *CFAPI) URL() string {\n\treturn a.server.URL()\n}\n\nfunc (a *CFAPI) ReceivedRequests() map[string][]*http.Request {\n\tresult := map[string][]*http.Request{}\n\n\tfor _, req := range a.server.ReceivedRequests() {\n\t\tkey := fmt.Sprintf(\"%s %s\", req.Method, req.URL.Path)\n\t\tresult[key] = append(result[key], req)\n\t}\n\n\treturn result\n}\n\nfunc parseRequest(request string) (string, string) {\n\tfields := strings.Split(request, \" \")\n\tExpect(fields).To(HaveLen(2))\n\treturn fields[0], fields[1]\n}\n\nfunc NewCFAPI() *CFAPI ", "output": "{\n\tserver := ghttp.NewServer()\n\treturn &CFAPI{\n\t\tserver: server,\n\t}\n}"} {"input": "package app\n\nimport (\n\t. \"strconv\"\n\t\"time\"\n)\n\ntype User struct {\n\tId int64\n\tNom string\n\tPrenom string\n\tEmail string\n\tPassword string\n\tCreatedAt time.Time\n\tUpdatedAt time.Time\n}\n\n\nfunc (u User) Save() {\n\tdb.Save(&u)\n}\n\n\n\n\n\nfunc (u User) Delete() {\n\tdb.Delete(&u)\n}\n\n\n\nfunc (u User) GetById() User {\n\tdb.Where(\"id = ?\", Itoa(int(u.Id))).Find(&u)\n\treturn u\n}\n\n\nfunc (u User) GetList() []User {\n\tvar users []User\n\tdb.Find(&users)\n\treturn users\n}\n\nfunc (u User) Update() ", "output": "{\n\tdb.First(&u, &u.Id).Update(&u)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\nvar (\n\tnames = []string{\n\t\t\"Pepe\",\n\t\t\"Gozalo\",\n\t\t\"Juan\",\n\t\t\"Carolina\",\n\t}\n\tlastNames = []string{\n\t\t\"Escobar\",\n\t\t\"Sierra\",\n\t\t\"Velez\",\n\t\t\"Mejia\",\n\t}\n\tusernames = []string{\n\t\t\"pep66\",\n\t\t\"jsi3rra\",\n\t\t\"jvlez8\",\n\t\t\"caro27\",\n\t}\n\temails = []string{\n\t\t\"pepe27@gmail.com\",\n\t\t\"gozalosierra@gmail.com\",\n\t\t\"juanv@gmail.com\",\n\t\t\"carolina@gmail.com\",\n\t}\n\tpasswords = []string{\n\t\t\"qwerty\",\n\t\t\"123456\",\n\t\t\"AeIoU!@\",\n\t\t\"S3CUR3P455W0RD!\\\"#$%&/()=\",\n\t}\n)\n\n\ntype User struct {\n\tUsername string\n\tEmail string\n\tLastName string\n\tName string\n\tPasswordHash string\n}\n\n\n\n\nfunc parallelLoop() {\n\tusers := makeUsers()\n\tvar wg sync.WaitGroup\n\tfor _, u := range users {\n\t\twg.Add(1)\n\t\tgo func(u User) {\n\t\t\tfmt.Printf(\"%s: (%s)\\n\", u.Email, u.Username)\n\t\t\twg.Done()\n\t\t}(u)\n\t}\n\twg.Wait()\n}\n\n\nfunc main() {\n\tparallelLoop()\n}\n\nfunc makeUsers() []User ", "output": "{\n\tusers := []User{}\n\tfor i := 0; i < 10; i++ {\n\t\tu := User{\n\t\t\tUsername: usernames[i%4],\n\t\t\tEmail: emails[i%4],\n\t\t\tLastName: lastNames[i%4],\n\t\t\tName: names[i%4],\n\t\t\tPasswordHash: passwords[i%4],\n\t\t}\n\t\tusers = append(users, u)\n\t}\n\treturn users\n}"} {"input": "package gwf\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n)\n\n\ntype Context struct {\n\tw http.ResponseWriter\n\tr *http.Request\n\n\tpath []string\n}\n\ntype Module interface {\n\tAction(*Context)\n}\n\ntype Dispatcher struct {\n\tmodules map[string]Module\n}\n\nfunc (c *Context) Request() *http.Request {\n\treturn c.r\n}\n\nfunc (c *Context) Writer() http.ResponseWriter {\n\treturn c.w\n}\n\n\n\nfunc (c *Context) Path(index int) (string, bool) {\n\tif index < 0 || index >= len(c.path) {\n\t\treturn \"\", false\n\t} else {\n\t\treturn c.path[index], true\n\t}\n}\n\nfunc (c *Context) Depth() int {\n\treturn len(c.path)\n}\n\n\nfunc (d *Dispatcher) AddModule(name string, m Module) {\n\tif nil == d.modules {\n\t\td.modules = make(map[string]Module)\n\t}\n\td.modules[name] = m\n}\n\nfunc (d *Dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\n\tvar c Context\n\tc.Init(w, r)\n\n\tif name, ok := c.Path(0); ok {\n\t\tif module, ok := d.modules[name]; ok && module != nil {\n\t\t\t(module).Action(&c)\n\t\t\treturn\n\t\t}\n\t}\n\tw.WriteHeader(http.StatusNotFound)\n}\n\nfunc (c *Context) Init(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tc.w, c.r = w, r\n\n\tpath := strings.Split(r.URL.Path, \"/\")\n\tc.path = path[1:]\n}"} {"input": "package proxy\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/AaronO/gogo-proxy\"\n)\n\nfunc TestRoundrobinEmpty(t *testing.T) {\n\tbalancer := proxy.Roundrobin()\n\n\tif _, err := balancer(nil); err == nil {\n\t\tt.Fatalf(\"Roundrobin should fail when given no hosts\")\n\t}\n}\n\n\n\nfunc TestRoundrobin(t *testing.T) {\n\tbalancer := proxy.Roundrobin(\"1\", \"2\", \"3\")\n\n\thosts := []string{}\n\n\tfor i := 0; i < 7; i++ {\n\t\thost, err := balancer(nil)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\thosts = append(hosts, host)\n\t}\n\n\tequal := reflect.DeepEqual(\n\t\thosts,\n\t\t[]string{\"1\", \"2\", \"3\", \"1\", \"2\", \"3\", \"1\"},\n\t)\n\n\tif !equal {\n\t\tt.Fatalf(\"Roundrobin did not generate expected hosts\")\n\t}\n}\n\nfunc TestRandomEmpty(t *testing.T) ", "output": "{\n\tbalancer := proxy.Random()\n\n\tif _, err := balancer(nil); err == nil {\n\t\tt.Fatalf(\"Random should fail when given no hosts\")\n\t}\n}"} {"input": "package file\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\ntype Reader interface {\n\tio.Reader\n\tio.ReaderAt\n\tio.Seeker\n}\n\ntype Writer interface {\n\tio.Writer\n\tio.Seeker\n\tTruncate(size int64) error\n\tSync() error\n}\n\ntype ReadCloser interface {\n\tReader\n\tio.Closer\n}\n\ntype WriteCloser interface {\n\tWriter\n\tio.Closer\n}\n\ntype File interface {\n\tio.Reader\n\tio.Writer\n\tio.Seeker\n\tio.Closer\n\tio.ReaderAt\n\tTruncate(size int64) error\n\tSync() error\n}\n\n\ntype FileSystem interface {\n\tOpen(name string, flag int) (File, error)\n\n\tLock(name string) (io.Closer, error)\n\n\tExists(name string) bool\n\n\tMkdirAll(path string) error\n\n\tList(dir string) ([]string, error)\n\n\tRemove(filename string) error\n\n\tRename(oldpath, newpath string) error\n}\n\ntype osFileSystem struct{}\n\nfunc (osFileSystem) Open(name string, flag int) (File, error) {\n\treturn os.OpenFile(name, flag, 0666)\n}\n\n\n\nfunc (osFileSystem) Exists(name string) bool {\n\t_, err := os.Stat(name)\n\treturn err == nil\n}\n\nfunc (osFileSystem) List(dir string) ([]string, error) {\n\tf, err := os.Open(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.Readdirnames(-1)\n}\n\nfunc (osFileSystem) Remove(name string) error {\n\treturn os.Remove(name)\n}\n\nfunc (osFileSystem) Rename(oldpath, newpath string) error {\n\treturn os.Rename(oldpath, newpath)\n}\n\nvar DefaultFileSystem FileSystem = osFileSystem{}\n\nfunc (osFileSystem) MkdirAll(path string) error ", "output": "{\n\treturn os.MkdirAll(path, 0740)\n}"} {"input": "package eval_test\n\nimport (\n\t\"fmt\"\n\t\"github.com/mailgun/godebug/Godeps/_workspace/src/github.com/0xfaded/eval\" \n\t\"go/parser\"\n\t\"reflect\"\n)\n\nconst constant1 = \"A constant\"\n\nfunc makeEnv() *eval.SimpleEnv {\n\tenv := eval.MakeSimpleEnv()\n\tenv.Consts[\"constant1\"] = reflect.ValueOf(constant1)\n\tvar1 := 1\n\tenv.Vars[\"var1\"] = reflect.ValueOf(&var1)\n\tenv.Funcs[\"add\"] = reflect.ValueOf(func(a, b int) int { return a + b })\n\tfmtPkg := eval.MakeSimpleEnv()\n\tfmtPkg.Funcs[\"Sprintf\"] = reflect.ValueOf(fmt.Sprintf)\n\tenv.Pkgs[\"fmt\"] = fmtPkg\n\treturn env\n\n}\n\nfunc ExampleSimple() {\n\tresult, panik, compileErrs := eval.Eval(`append([]int{1,2}[:1], map[int]int{1:2}[1])[1]`)\n\t_ = panik\n\t_ = compileErrs\n\tfmt.Printf(\"%+v\\n\", result[0].Interface())\n}\n\nfunc ExampleWithEnvironment() {\n\tenv := makeEnv() \n\tresult, panik, compileErrs := eval.EvalEnv(`fmt.Sprintf(\"%s %d\", constant1, add(var1, 1) + 1)`, env)\n\t_ = panik\n\t_ = compileErrs\n\tfmt.Printf(\"%+v\\n\", result[0].Interface())\n}\n\n\n\n\n\n\n\n\nfunc ExampleFullApi() ", "output": "{\n\texpr := `fmt.Sprintf(\"%s %d\", constant1, add(var1, 1) + 1)`\n\tenv := makeEnv() \n\tif e, err := parser.ParseExpr(expr); err != nil {\n\t\tfmt.Printf(\"Failed to parse expression '%s' (%v)\\n\", expr, err)\n\t} else if cexpr, errs := eval.CheckExpr(e, env); len(errs) != 0 {\n\t\tfmt.Printf(\"Error checking expression '%s' (%v)\\n\", expr, errs)\n\t} else if results, err := eval.EvalExpr(cexpr, env); err != nil {\n\t\tfmt.Printf(\"Panic evaluating expression '%s' (%v)\\n\", expr, err)\n\t} else {\n\t\tfmt.Printf(\"Expression '%s' yielded '%+v'\\n\", expr, results[0].Interface())\n\t}\n}"} {"input": "package main\n\nimport \"errors\"\nimport \"fmt\"\n\n\n\nfunc f1(arg int) (int, error) {\n\tif arg == 42 {\n\n\t\treturn -1, errors.New(\"can't work with 42\")\n\n\t}\n\n\treturn arg + 3, nil\n}\n\n\n\n\n\ntype argError struct {\n\targ int\n\tprob string\n}\n\nfunc (e *argError) Error() string {\n\treturn fmt.Sprintf(\"%d - %s\", e.arg, e.prob)\n}\n\n\n\nfunc main() {\n\n\tfor _, i := range []int{7, 42} {\n\t\tif r, e := f1(i); e != nil {\n\t\t\tfmt.Println(\"f1 failed:\", e)\n\t\t} else {\n\t\t\tfmt.Println(\"f1 worked:\", r)\n\t\t}\n\t}\n\n\tfor _, i := range []int{7, 42} {\n\t\tif r, e := f2(i); e != nil {\n\t\t\tfmt.Println(\"f2 failed:\", e)\n\t\t} else {\n\t\t\tfmt.Println(\"f2 worked:\", r)\n\t\t}\n\t}\n\n\t_, e := f2(42)\n\tif ae, ok := e.(*argError); ok {\n\t\tfmt.Println(ae.arg)\n\t\tfmt.Println(ae.prob)\n\t}\n}\n\nfunc f2(arg int) (int, error) ", "output": "{\n\tif arg == 42 {\n\n\t\treturn -1, &argError{arg, \"can't work with it\"}\n\t}\n\treturn arg + 3, nil\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"k8s.io/client-go/kubernetes/typed/batch/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeBatchV1beta1 struct {\n\t*testing.Fake\n}\n\n\n\n\n\nfunc (c *FakeBatchV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeBatchV1beta1) CronJobs(namespace string) v1beta1.CronJobInterface ", "output": "{\n\treturn &FakeCronJobs{c, namespace}\n}"} {"input": "package sacloud\n\n\ntype IPv6Addr struct {\n\tHostName string `json:\",omitempty\"` \n\tIPv6Addr string `json:\",omitempty\"` \n\tInterface *Interface `json:\",omitempty\"` \n\tIPv6Net *IPv6Net `json:\",omitempty\"` \n\n}\n\n\nfunc (a *IPv6Addr) GetIPv6NetID() int64 {\n\tif a.IPv6Net != nil {\n\t\treturn a.IPv6Net.ID\n\t}\n\treturn 0\n}\n\n\nfunc (a *IPv6Addr) GetInternetID() int64 {\n\tif a.IPv6Net != nil && a.IPv6Net.Switch != nil && a.IPv6Net.Switch.Internet != nil {\n\t\treturn a.IPv6Net.Switch.Internet.ID\n\t}\n\treturn 0\n}\n\n\n\n\nfunc CreateNewIPv6Addr() *IPv6Addr ", "output": "{\n\treturn &IPv6Addr{\n\t\tIPv6Net: &IPv6Net{\n\t\t\tResource: &Resource{},\n\t\t},\n\t}\n}"} {"input": "package oom\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"k8s.io/api/core/v1\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\t_ \"k8s.io/kubernetes/pkg/apis/core/install\" \n\t_ \"k8s.io/kubernetes/pkg/apis/extensions/install\" \n)\n\nconst pod1Yaml = `\napiVersion: v1\nkind: Pod\nmetadata:\n name: Pod1\n namespace: mockNamespace\nspec:\n containers:\n - name: Name11\n resources:\n requests:\n memory: \"1024\"\nstatus:\n containerStatuses:\n - name: Name11\n restartCount: 0\n`\n\nconst pod2Yaml = `\napiVersion: v1\nkind: Pod\nmetadata:\n name: Pod1\n namespace: mockNamespace\nspec:\n containers:\n - name: Name11\n resources:\n requests:\n memory: \"1024\"\nstatus:\n containerStatuses:\n - name: Name11\n restartCount: 1\n lastState:\n terminated:\n finishedAt: 2018-02-23T13:38:48Z\n reason: OOMKilled\n`\n\nfunc newPod(yaml string) (*v1.Pod, error) {\n\tdecode := legacyscheme.Codecs.UniversalDeserializer().Decode\n\tobj, _, err := decode([]byte(yaml), nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*v1.Pod), nil\n}\n\n\n\nfunc TestOOMReceived(t *testing.T) ", "output": "{\n\tp1, err := newPod(pod1Yaml)\n\tassert.NoError(t, err)\n\tp2, err := newPod(pod2Yaml)\n\tassert.NoError(t, err)\n\tobserver := NewObserver()\n\tgo observer.OnUpdate(p1, p2)\n\n\tinfo := <-observer.ObservedOomsChannel\n\tassert.Equal(t, \"mockNamespace\", info.Namespace)\n\tassert.Equal(t, \"Pod1\", info.Pod)\n\tassert.Equal(t, \"Name11\", info.Container)\n\tassert.Equal(t, int64(1024), info.MemoryRequest.Value())\n\ttimestamp, err := time.Parse(time.RFC3339, \"2018-02-23T13:38:48Z\")\n\tassert.NoError(t, err)\n\tassert.Equal(t, timestamp.Unix(), info.Timestamp.Unix())\n}"} {"input": "package testclient\n\nimport (\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/fields\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/labels\"\n\n\tauthorizationapi \"github.com/openshift/origin/pkg/authorization/api\"\n)\n\n\n\ntype FakeClusterRoles struct {\n\tFake *Fake\n}\n\nfunc (c *FakeClusterRoles) List(label labels.Selector, field fields.Selector) (*authorizationapi.ClusterRoleList, error) {\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"list-clusterRoles\"}, &authorizationapi.ClusterRoleList{})\n\treturn obj.(*authorizationapi.ClusterRoleList), err\n}\n\n\n\nfunc (c *FakeClusterRoles) Create(role *authorizationapi.ClusterRole) (*authorizationapi.ClusterRole, error) {\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"create-clusterRole\", Value: role}, &authorizationapi.ClusterRole{})\n\treturn obj.(*authorizationapi.ClusterRole), err\n}\n\nfunc (c *FakeClusterRoles) Update(role *authorizationapi.ClusterRole) (*authorizationapi.ClusterRole, error) {\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"update-clusterRole\"}, &authorizationapi.ClusterRole{})\n\treturn obj.(*authorizationapi.ClusterRole), err\n}\n\nfunc (c *FakeClusterRoles) Delete(name string) error {\n\tc.Fake.Actions = append(c.Fake.Actions, FakeAction{Action: \"delete-clusterRole\", Value: name})\n\treturn nil\n}\n\nfunc (c *FakeClusterRoles) Get(name string) (*authorizationapi.ClusterRole, error) ", "output": "{\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"get-clusterRole\"}, &authorizationapi.ClusterRole{})\n\treturn obj.(*authorizationapi.ClusterRole), err\n}"} {"input": "package gc\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestTricolorBasic(t *testing.T) {\n\troots := []string{\"A\", \"C\"}\n\tall := []string{\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"}\n\trefs := map[string][]string{\n\t\t\"A\": {\"B\"},\n\t\t\"B\": {\"A\"},\n\t\t\"C\": {\"D\", \"F\", \"B\"},\n\t\t\"E\": {\"F\", \"G\"},\n\t}\n\n\tunreachable := Tricolor(roots, all, lookup(refs))\n\texpected := []string{\"E\", \"G\"}\n\n\tif !reflect.DeepEqual(unreachable, expected) {\n\t\tt.Fatalf(\"incorrect unreachable set: %v != %v\", unreachable, expected)\n\t}\n}\n\n\n\nfunc lookup(refs map[string][]string) func(id string) []string ", "output": "{\n\treturn func(ref string) []string {\n\t\treturn refs[ref]\n\t}\n}"} {"input": "package state\n\nimport (\n\t\"github.com/hashicorp/consul/agent/structs\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\ntype Delay struct {\n\tdelay map[string]time.Time\n\n\tlock sync.RWMutex\n}\n\n\n\n\n\n\n\nfunc (d *Delay) GetExpiration(key string, entMeta *structs.EnterpriseMeta) time.Time {\n\td.lock.RLock()\n\texpires := d.delay[key]\n\td.lock.RUnlock()\n\treturn expires\n}\n\n\n\nfunc (d *Delay) SetExpiration(key string, now time.Time, delay time.Duration, entMeta *structs.EnterpriseMeta) {\n\td.lock.Lock()\n\tdefer d.lock.Unlock()\n\n\td.delay[key] = now.Add(delay)\n\ttime.AfterFunc(delay, func() {\n\t\td.lock.Lock()\n\t\tdelete(d.delay, key)\n\t\td.lock.Unlock()\n\t})\n}\n\nfunc NewDelay() *Delay ", "output": "{\n\treturn &Delay{delay: make(map[string]time.Time)}\n}"} {"input": "package go_rps_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestGoRps(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"GoRps Suite\")\n}"} {"input": "package control\n\nimport (\n\tyaml \"github.com/cloudfoundry-incubator/candiedyaml\"\n\t\"github.com/dansteen/controlled-compose/types\"\n\t\"github.com/docker/libcompose/config\"\n\t\"github.com/docker/libcompose/utils\"\n\t\"github.com/imdario/mergo.git\"\n\t\"io/ioutil\"\n\t\"path/filepath\"\n)\n\n\n\n\n\n\n\nfunc consumeConfigs(files []string) ([]byte, error) {\n\n\tvar configContent config.Config\n\tvar mergedConfig config.Config\n\tfor _, file := range files {\n\t\tcontent, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = yaml.Unmarshal(content, &configContent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = mergo.Merge(&mergedConfig, configContent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tyamlConfig, err := yaml.Marshal(mergedConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn []byte(yamlConfig), nil\n}\n\nfunc processRequires(file string, configFiles []string) ([]string, error) ", "output": "{\n\tcontent, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar requires types.Requires\n\terr = yaml.Unmarshal(content, &requires)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnewFiles := append(configFiles, file)\n\n\tfor _, require := range requires.Require {\n\t\trequire = filepath.Join(filepath.Dir(file), require)\n\n\t\tif !utils.Contains(configFiles, require) {\n\t\t\tnewFiles, err = processRequires(require, newFiles)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\treturn newFiles, nil\n}"} {"input": "package nacos\n\nimport (\n\t\"context\"\n\n\t\"github.com/asim/go-micro/v3/config/source\"\n\t\"github.com/nacos-group/nacos-sdk-go/v2/common/constant\"\n)\n\ntype addressKey struct{}\ntype configKey struct{}\ntype groupKey struct{}\ntype dataIdKey struct{}\ntype encoderKey struct{}\n\n\nfunc WithAddress(addrs []string) source.Option {\n\treturn func(o *source.Options) {\n\t\tif o.Context == nil {\n\t\t\to.Context = context.Background()\n\t\t}\n\t\to.Context = context.WithValue(o.Context, addressKey{}, addrs)\n\t}\n}\n\n\nfunc WithClientConfig(cc constant.ClientConfig) source.Option {\n\treturn func(o *source.Options) {\n\t\tif o.Context == nil {\n\t\t\to.Context = context.Background()\n\t\t}\n\t\to.Context = context.WithValue(o.Context, configKey{}, cc)\n\t}\n}\n\n\nfunc WithGroup(g string) source.Option {\n\treturn func(o *source.Options) {\n\t\tif o.Context == nil {\n\t\t\to.Context = context.Background()\n\t\t}\n\t\to.Context = context.WithValue(o.Context, groupKey{}, g)\n\t}\n}\n\n\n\n\nfunc WithDataId(id string) source.Option ", "output": "{\n\treturn func(o *source.Options) {\n\t\tif o.Context == nil {\n\t\t\to.Context = context.Background()\n\t\t}\n\t\to.Context = context.WithValue(o.Context, dataIdKey{}, id)\n\t}\n}"} {"input": "package libgogo\n\n\n\n\n\nvar Argv [255]string;\nvar Argc uint64 = 0;\n\n\n\n\n\n\n\n\n\n\n\nfunc CopyMem(source uint64, dest uint64, size uint64);\n\n\n\n\n\nfunc Exit(code uint64);\n\n\n\n\nfunc ExitError(msg string, code uint64) {\n PrintString(msg);\n PrintChar(10); \n Exit(code);\n}\n\nfunc GetArgv() ", "output": "{\n var fd uint64;\n var errno uint64; \n var singleChar byte;\n var lastChar byte = 1; \n\n fd = FileOpen(\"/proc/self/cmdline\", 0); \n if fd == 0 { \n ExitError(\"Error opening /proc/self/cmdline. Currently GoGo is only supported on systems with /proc enabled.\", 1);\n } \n\n for singleChar = GetChar(fd);(singleChar != 0) || (lastChar != 0); singleChar = GetChar(fd) {\n if (singleChar == 0) {\n Argc = Argc +1;\n } else {\n CharAppend(&Argv[Argc], singleChar);\n }\n lastChar = singleChar;\n }\n\n errno = FileClose(fd);\n if errno != 0 {\n ExitError(\"Error closing file /proc/self/cmdline\",1);\n }\n}"} {"input": "package acsengine\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/Azure/acs-engine/pkg/i18n\"\n\tlog \"github.com/sirupsen/logrus\"\n\t\"golang.org/x/crypto/ssh\"\n)\n\n\ntype SSHCreator struct {\n\tTranslator *i18n.Translator\n}\n\nconst (\n\tSSHKeySize = 4096\n)\n\n\nfunc (s *SSHCreator) CreateSaveSSH(username, outputDirectory string) (privateKey *rsa.PrivateKey, publicKeyString string, err error) {\n\tprivateKey, publicKeyString, err = s.CreateSSH(rand.Reader)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tprivateKeyPem := privateKeyToPem(privateKey)\n\n\tf := &FileSaver{\n\t\tTranslator: s.Translator,\n\t}\n\n\terr = f.SaveFile(outputDirectory, fmt.Sprintf(\"%s_rsa\", username), privateKeyPem)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\treturn privateKey, publicKeyString, nil\n}\n\n\n\n\nfunc (s *SSHCreator) CreateSSH(rg io.Reader) (privateKey *rsa.PrivateKey, publicKeyString string, err error) ", "output": "{\n\tlog.Debugf(\"ssh: generating %dbit rsa key\", SSHKeySize)\n\tprivateKey, err = rsa.GenerateKey(rg, SSHKeySize)\n\tif err != nil {\n\t\treturn nil, \"\", s.Translator.Errorf(\"failed to generate private key for ssh: %q\", err)\n\t}\n\n\tpublicKey := privateKey.PublicKey\n\tsshPublicKey, err := ssh.NewPublicKey(&publicKey)\n\tif err != nil {\n\t\treturn nil, \"\", s.Translator.Errorf(\"failed to create openssh public key string: %q\", err)\n\t}\n\tauthorizedKeyBytes := ssh.MarshalAuthorizedKey(sshPublicKey)\n\tauthorizedKey := string(authorizedKeyBytes)\n\n\treturn privateKey, authorizedKey, nil\n}"} {"input": "package utilities\n\nimport (\n\t\"testing\"\n)\n\n\nfunc AssertPanic(t *testing.T, f func()) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"The code did not panic\")\n\t\t}\n\t}()\n\tf()\n}\n\n\n\n\nfunc AssertNoPanic(t *testing.T, f func()) ", "output": "{\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tt.Errorf(\"The code did panic\")\n\t\t}\n\t}()\n\tf()\n}"} {"input": "package naive\n\nimport (\n\n\t\"bytes\"\n\t\"encoding/gob\"\n\t\"fmt\"\n\t\"os\"\n)\n\n\n\n\n\nfunc (n *Naive) CreateStorage() ", "output": "{\n\tvar infoBuf bytes.Buffer\n\tenc := gob.NewEncoder(&infoBuf)\n\n\tinfo := searchModeInfo{\n\t\t0,\n\t}\n\n\terr := enc.Encode(&info)\n\tif err != nil {\n\t\tfmt.Printf(\"failed to encode search mode information: %s\\n\", err)\n\t\treturn\n\t}\n\n\tfile, oerr := os.Create(n.dir + \"/\" + searchModeInfoPath)\n\tif oerr != nil {\n\t\tfmt.Printf(\"failed to open file for search mode info: %s\\n\", oerr)\n\t\treturn\n\t}\n\n\t_, werr := file.Write(infoBuf.Bytes())\n\tif werr != nil {\n\t\tfmt.Printf(\"failed to write search mode info: %s\\n\", werr)\n\t\treturn\n\t}\n}"} {"input": "package crypto\n\nimport (\n\t\"crypto\"\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/sha256\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\nfunc Sign(key *rsa.PrivateKey, message []byte) ([]byte, error) {\n\thashed := sha256.Sum256(message)\n\tsignature, err := rsa.SignPKCS1v15(\n\t\trand.Reader, key, crypto.SHA256, hashed[:],\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to sign message: \")\n\t}\n\treturn signature, nil\n}\n\n\n\nfunc Verify(key *rsa.PublicKey, signature, message []byte) error {\n\thashed := sha256.Sum256(message)\n\terr := rsa.VerifyPKCS1v15(key, crypto.SHA256, hashed[:], signature)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to verify message: \")\n\t}\n\treturn nil\n}\n\n\nfunc EncryptRSA(key *rsa.PublicKey, plaintext []byte) ([]byte, error) {\n\tciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, key, plaintext)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to encrypt plaintext: \")\n\t}\n\treturn ciphertext, nil\n}\n\n\n\n\nfunc DecryptRSA(key *rsa.PrivateKey, ciphertext []byte) ([]byte, error) ", "output": "{\n\tsession, err := rsa.DecryptPKCS1v15(rand.Reader, key, ciphertext)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to decrypt ciphertext: \")\n\t}\n\treturn session, nil\n}"} {"input": "package chipmunk\n\nimport \"github.com/dataarts/chipmunk/vect\"\n\nconst (\n\terrorBias = 0.00179701029991443 \n)\n\ntype ConstraintCallback interface {\n\tCollisionPreSolve(constraint Constraint)\n\tCollisionPostSolve(constraint Constraint)\n}\n\ntype Constraint interface {\n\tConstraint() *BasicConstraint\n\tPreSolve()\n\tPostSolve()\n\tPreStep(dt vect.Float)\n\tApplyCachedImpulse(dt_coef vect.Float)\n\tApplyImpulse()\n\tImpulse() vect.Float\n}\n\ntype BasicConstraint struct {\n\tBodyA, BodyB *Body\n\tspace *Space\n\tMaxForce vect.Float\n\tErrorBias vect.Float\n\tMaxBias vect.Float\n\tCallbackHandler ConstraintCallback\n\tUserData Data\n}\n\nfunc NewConstraint(a, b *Body) BasicConstraint {\n\treturn BasicConstraint{BodyA: a, BodyB: b, MaxForce: Inf, MaxBias: Inf, ErrorBias: errorBias}\n}\n\n\n\nfunc (this *BasicConstraint) PreStep(dt vect.Float) {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) ApplyCachedImpulse(dt_coef vect.Float) {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) ApplyImpulse() {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) Impulse() vect.Float {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) PreSolve() {\n\tif this.CallbackHandler != nil {\n\t\tthis.CallbackHandler.CollisionPreSolve(this)\n\t}\n}\n\nfunc (this *BasicConstraint) PostSolve() {\n\tif this.CallbackHandler != nil {\n\t\tthis.CallbackHandler.CollisionPostSolve(this)\n\t}\n}\n\nfunc (this *BasicConstraint) Constraint() *BasicConstraint ", "output": "{\n\treturn this\n}"} {"input": "package sqlbuilder\n\ntype Dialect interface {\n\tEscapeCharacter() rune\n\tInsertReturningClause() string\n\tKind() string\n\tName() *string\n}\n\ntype genericDialect struct {\n\tescapeChar rune\n\treturningClause string\n\tkind string\n\tname *string\n}\n\nfunc (db *genericDialect) EscapeCharacter() rune {\n\treturn db.escapeChar\n}\n\n\n\nfunc (db *genericDialect) Kind() string {\n\treturn db.kind\n}\n\nfunc (db *genericDialect) Name() *string {\n\treturn db.name\n}\n\nfunc NewMySQLDialect(dbName *string) Dialect {\n\treturn &genericDialect{\n\t\tescapeChar: '`',\n\t\tkind: \"mysql\",\n\t\tname: dbName,\n\t}\n}\n\nfunc NewPostgresDialect(dbName *string) Dialect {\n\treturn &genericDialect{\n\t\tescapeChar: '\"',\n\t\treturningClause: \" RETURNING *\",\n\t\tkind: \"postgres\",\n\t\tname: dbName,\n\t}\n}\n\nfunc NewSQLiteDialect() Dialect {\n\tdefaultName := \"main\"\n\treturn &genericDialect{\n\t\tescapeChar: '\"',\n\t\tkind: \"sqlite\",\n\t\tname: &defaultName,\n\t}\n}\n\nfunc (db *genericDialect) InsertReturningClause() string ", "output": "{\n\treturn db.returningClause\n}"} {"input": "package buildpack_test\n\nimport (\n\t\"github.com/nttlabs/cli/cf/i18n\"\n\t\"github.com/nttlabs/cli/testhelpers/configuration\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestBuildpack(t *testing.T) ", "output": "{\n\tconfig := configuration.NewRepositoryWithDefaults()\n\ti18n.T = i18n.Init(config)\n\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Buildpack Suite\")\n}"} {"input": "package MySQLProtocol\n\nimport \"testing\"\nimport \"github.com/stretchr/testify/assert\"\n\nvar LOCAL_INFILE_Request_test_packets = []struct {\n\tpacket Proto\n\tcontext Context\n}{\n\t{packet: Proto{data: StringToPacket(`\n0c 00 00 01 fb 2f 65 74 63 2f 70 61 73 73 77 64 ...../etc/passwd\n`)}, context: Context{}},\n}\n\nfunc Test_Packet_LOCAL_INFILE_Request(t *testing.T) {\n\tvar pkt Packet_LOCAL_INFILE_Request\n\tfor _, value := range LOCAL_INFILE_Request_test_packets {\n\t\tpkt = Packet_LOCAL_INFILE_Request{}\n\t\tpkt.FromPacket(value.context, value.packet)\n\t\tassert.Equal(t, pkt.ToPacket(value.context), value.packet.data, \"\")\n\t}\n}\n\nfunc Benchmark_Packet_LOCAL_INFILE_Request_FromPacket(b *testing.B) {\n\tcontext := Context{capability: CLIENT_PROTOCOL_41}\n\tvar pkt Packet_LOCAL_INFILE_Request\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt = Packet_LOCAL_INFILE_Request{}\n\t\tLOCAL_INFILE_Request_test_packets[0].packet.offset = 0\n\t\tpkt.FromPacket(context, LOCAL_INFILE_Request_test_packets[0].packet)\n\t}\n}\n\n\n\nfunc Benchmark_Packet_LOCAL_INFILE_Request_ToPacket(b *testing.B) {\n\tcontext := Context{capability: CLIENT_PROTOCOL_41}\n\tpkt := Packet_LOCAL_INFILE_Request{}\n\tpkt.FromPacket(context, LOCAL_INFILE_Request_test_packets[0].packet)\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt.ToPacket(context)\n\t}\n}\n\nfunc Benchmark_Packet_LOCAL_INFILE_Request_GetPacketSize(b *testing.B) ", "output": "{\n\tcontext := Context{capability: CLIENT_PROTOCOL_41}\n\tpkt := Packet_LOCAL_INFILE_Request{}\n\tpkt.FromPacket(context, LOCAL_INFILE_Request_test_packets[0].packet)\n\tfor i := 0; i < b.N; i++ {\n\t\tpkt.GetPacketSize(context)\n\t}\n}"} {"input": "package rest\n\nimport (\n\t\"testing\"\n\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\tgenericapirequest \"k8s.io/apiserver/pkg/endpoints/request\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\tgenericregistry \"k8s.io/apiserver/pkg/registry/generic/registry\"\n\tapi \"k8s.io/kubernetes/pkg/apis/core\"\n\t\"k8s.io/kubernetes/pkg/registry/registrytest\"\n)\n\n\n\nfunc TestPodLogValidates(t *testing.T) ", "output": "{\n\tconfig, server := registrytest.NewEtcdStorage(t, \"\")\n\tdefer server.Terminate(t)\n\ts, destroyFunc, err := generic.NewRawStorage(config)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t}\n\tdefer destroyFunc()\n\tstore := &genericregistry.Store{\n\t\tStorage: genericregistry.DryRunnableStorage{Storage: s},\n\t}\n\tlogRest := &LogREST{Store: store, KubeletConn: nil}\n\n\tnegativeOne := int64(-1)\n\ttestCases := []*api.PodLogOptions{\n\t\t{SinceSeconds: &negativeOne},\n\t\t{TailLines: &negativeOne},\n\t}\n\n\tfor _, tc := range testCases {\n\t\t_, err := logRest.Get(genericapirequest.NewDefaultContext(), \"test\", tc)\n\t\tif !errors.IsInvalid(err) {\n\t\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t\t}\n\t}\n}"} {"input": "package helloplugin\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cafxx/pluggo\"\n)\n\n\n\ntype hello struct {\n}\n\nfunc (*hello) Say() {\n\tfmt.Println(\"Hello pluggo\")\n}\n\nfunc init() ", "output": "{\n\tpluggo.Register(\"hello\", func() interface{} {\n\t\treturn &hello{}\n\t})\n}"} {"input": "package algorithms\n\n\n\nfunc sortedListToBST(head *ListNode) *TreeNode ", "output": "{\n\tif head == nil {\n\t\treturn nil\n\t}\n\tif head.Next == nil {\n\t\treturn &TreeNode{Val: head.Val}\n\t}\n\n\tprev, slow, fast := head, head.Next, head.Next\n\tfor fast.Next != nil && fast.Next.Next != nil {\n\t\tprev = prev.Next\n\t\tslow = slow.Next\n\t\tfast = fast.Next.Next\n\t}\n\tprev.Next = nil\n\n\troot := &TreeNode{Val: slow.Val}\n\n\troot.Left = sortedListToBST(head)\n\troot.Right = sortedListToBST(slow.Next)\n\n\treturn root\n}"} {"input": "package main\n\nimport (\n\t\"github.com/asteris-llc/mantl-bootstrap/bootstrap\"\n\t\"github.com/asteris-llc/mantl-bootstrap/listen\"\n\t\"github.com/asteris-llc/mantl-bootstrap/vault\"\n\n\t\"github.com/spf13/cobra\"\n)\n\n\n\nfunc initCommand(name, version string) *cobra.Command ", "output": "{\n\troot := &cobra.Command{\n\t\tUse: \"mantl-bootstrap\",\n\t\tShort: \"Bootstrap a list of nodes with mantl\",\n\t\tLong: \"Bootstrap a list of nodes with mantl\",\n\t\tSilenceUsage: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcmd.Help()\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tbootstrap.Init(root)\n\tlisten.Init(root)\n\tvault.Init(root)\n\n\treturn root\n}"} {"input": "package internal\n\n\n\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar limitSem = make(chan int, 100) \n\n\n\nfunc limitDial(network, addr string) (net.Conn, error) {\n\tlimitSem <- 1\n\n\tconn, err := net.DialTimeout(network, addr, 500*time.Millisecond)\n\tif err != nil {\n\t\tlimitRelease()\n\t\treturn nil, err\n\t}\n\tlc := &limitConn{Conn: conn}\n\truntime.SetFinalizer(lc, (*limitConn).Close) \n\treturn lc, nil\n}\n\ntype limitConn struct {\n\tclose sync.Once\n\tnet.Conn\n}\n\nfunc (lc *limitConn) Close() error {\n\tdefer lc.close.Do(func() {\n\t\tlimitRelease()\n\t\truntime.SetFinalizer(lc, nil)\n\t})\n\treturn lc.Conn.Close()\n}\n\nfunc limitRelease() ", "output": "{\n\tselect {\n\tcase <-limitSem:\n\tdefault:\n\t\tlog.Print(\"appengine: unbalanced limitSem release!\")\n\t}\n}"} {"input": "package marks\n\nimport (\n\t\"strings\"\n\n\t\"github.com/zclconf/go-cty/cty\"\n)\n\n\n\n\ntype valueMark string\n\nfunc (m valueMark) GoString() string {\n\treturn \"marks.\" + strings.Title(string(m))\n}\n\n\n\n\n\n\nfunc Contains(val cty.Value, mark valueMark) bool {\n\tret := false\n\tcty.Walk(val, func(_ cty.Path, v cty.Value) (bool, error) {\n\t\tif v.HasMark(mark) {\n\t\t\tret = true\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\treturn ret\n}\n\n\n\nvar Sensitive = valueMark(\"sensitive\")\n\n\n\n\nvar TypeType = valueMark(\"typeType\")\n\nfunc Has(val cty.Value, mark valueMark) bool ", "output": "{\n\treturn val.HasMark(mark)\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\ntype SystemSettings struct {\n\tuserStreamAcl *StreamAcl\n\tsystemStreamAcl *StreamAcl\n}\n\n\n\nfunc (s *SystemSettings) UserStreamAcl() *StreamAcl { return s.userStreamAcl }\n\nfunc (s *SystemSettings) SystemStreamAcl() *StreamAcl { return s.systemStreamAcl }\n\nfunc (s *SystemSettings) String() string {\n\treturn fmt.Sprintf(\"&{userStreamAcl:%+v systemStreamAcl:%+v}\", s.userStreamAcl, s.systemStreamAcl)\n}\n\ntype systemSettingsJson struct {\n\tUserStreamAcl *StreamAcl `json:\"$userStreamAcl,omitempty\"`\n\tSystemStreamAcl *StreamAcl `json:\"$systemStreamAcl,omitempty\"`\n}\n\nfunc (s *SystemSettings) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(systemSettingsJson{\n\t\tUserStreamAcl: s.userStreamAcl,\n\t\tSystemStreamAcl: s.systemStreamAcl,\n\t})\n}\n\nfunc (s *SystemSettings) UnmarshalJSON(data []byte) error {\n\tss := systemSettingsJson{}\n\tif err := json.Unmarshal(data, &ss); err != nil {\n\t\treturn err\n\t}\n\ts.userStreamAcl = ss.UserStreamAcl\n\ts.systemStreamAcl = ss.SystemStreamAcl\n\treturn nil\n}\n\nfunc SystemSettingsFromJsonBytes(data []byte) (*SystemSettings, error) {\n\tsystemSettings := &SystemSettings{}\n\treturn systemSettings, json.Unmarshal(data, systemSettings)\n}\n\nfunc NewSystemSettings(\n\tuserStreamAcl *StreamAcl,\n\tsystemStreamAcl *StreamAcl,\n) *SystemSettings ", "output": "{\n\treturn &SystemSettings{userStreamAcl, systemStreamAcl}\n}"} {"input": "package datastore\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hellodudu/Ultimate/iface\"\n\t\"github.com/hellodudu/Ultimate/utils/global\"\n)\n\nvar ds iface.IDatastore\n\nfunc init() {\n\tglobal.Debugging = false\n\tglobal.MysqlUser = \"root\"\n\tglobal.MysqlPwd = \"\"\n\tglobal.MysqlAddr = \"127.0.0.1\"\n\tglobal.MysqlPort = \"3306\"\n\tglobal.MysqlDB = \"db_ultimate\"\n\tglobal.UltimateID = 110\n}\n\nfunc TestNewDatastore(t *testing.T) {\n\n\tvar err error\n\tds, err = NewDatastore()\n\tif err != nil {\n\t\tt.Error(\"NewDatastore error:\", err)\n\t}\n\n}\n\n\n\nfunc TestTableGlobal(t *testing.T) ", "output": "{\n\ttbl := ds.TableGlobal()\n\tif tbl == nil {\n\t\tt.Error(\"Init table global error\")\n\t}\n\n\tif tbl.Id != 110 {\n\t\tt.Error(\"Init table global ultimate_id error\")\n\t}\n}"} {"input": "package wiringpi\n\n\n\n\n\n\n\n\n\n\n\nimport \"C\"\nimport (\n\t\"sync\"\n\n\t\"github.com/yroffin/jarvis-go-ext/logger\"\n)\n\n\ntype WiringPiDriver struct {\n}\n\nvar instance *WiringPiDriver\nvar once sync.Once\n\n\nfunc GetInstance() *WiringPiDriver {\n\tonce.Do(func() {\n\t\tinstance = new(WiringPiDriver)\n\t\tinstance.init()\n\t})\n\treturn instance\n}\n\n\nfunc (wiringPi *WiringPiDriver) init() int {\n\tvar res = int(C.wiringPiSetupInit())\n\tlogger.Default.Info(\"WiringPiDriver\", logger.Fields{\n\t\t\"Init\": \"on\",\n\t})\n\treturn res\n}\n\n\n\n\n\nfunc DigitalWrite(pin int, value int) {\n\tC.digitalWrite(C.int(pin), C.int(value))\n}\n\n\nfunc DelayMicroseconds(delay uint) {\n\tC.delayMicroseconds(C.uint(delay))\n}\n\n\nfunc Delay(delay uint) {\n\tC.delay(C.uint(delay))\n}\n\nfunc PinMode(pin int, value int) ", "output": "{\n\tC.pinMode(C.int(pin), C.int(value))\n}"} {"input": "package fabenc\n\nimport (\n\t\"io\"\n\n\t\"go.uber.org/zap/buffer\"\n\t\"go.uber.org/zap/zapcore\"\n)\n\n\n\ntype FormatEncoder struct {\n\tzapcore.Encoder\n\tformatters []Formatter\n\tpool buffer.Pool\n\tconsoleEncoder zapcore.Encoder\n}\n\n\ntype Formatter interface {\n\tFormat(w io.Writer, entry zapcore.Entry, fields []zapcore.Field)\n}\n\n\n\n\nfunc (f *FormatEncoder) Clone() zapcore.Encoder {\n\treturn &FormatEncoder{\n\t\tEncoder: f.Encoder.Clone(),\n\t\tformatters: f.formatters,\n\t\tpool: f.pool,\n\t}\n}\n\n\n\n\nfunc (f *FormatEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {\n\tline := f.pool.Get()\n\tfor _, f := range f.formatters {\n\t\tf.Format(line, entry, fields)\n\t}\n\n\tencodedFields, err := f.Encoder.EncodeEntry(entry, fields)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif line.Len() > 0 && encodedFields.Len() != 1 {\n\t\tline.AppendString(\" \")\n\t}\n\tline.AppendString(encodedFields.String())\n\tencodedFields.Free()\n\n\treturn line, nil\n}\n\nfunc NewFormatEncoder(formatters ...Formatter) *FormatEncoder ", "output": "{\n\treturn &FormatEncoder{\n\t\tEncoder: zapcore.NewConsoleEncoder(zapcore.EncoderConfig{LineEnding: \"\\n\"}),\n\t\tformatters: formatters,\n\t\tpool: buffer.NewPool(),\n\t}\n}"} {"input": "package domain\n\nimport (\n\t\"flag\"\n)\n\ntype Config struct {\n\tDockerAPIEndpoint string\n\tVulcandAPIEndpoint string\n\tHostIP string\n}\n\n\n\nfunc (config *Config) InstallFlags() ", "output": "{\n\tflag.StringVar(&config.DockerAPIEndpoint, \"d\", \"/var/run/docker.sock\", \"Docker API endpoint\")\n\tflag.StringVar(&config.VulcandAPIEndpoint, \"v\", \"172.17.8.101:8182\", \"Vulcand API endpoint\")\n\tflag.StringVar(&config.HostIP, \"h\", \"172.17.8.101\", \"Host's external facing ip\")\n}"} {"input": "package tests\n\nimport (\n\t\"fmt\"\n\t\"github.com/xrash/smetrics\"\n\t\"testing\"\n)\n\n\n\nfunc TestUkkonen(t *testing.T) ", "output": "{\n\tcases := []levenshteincase{\n\t\t{\"RASH\", \"RASH\", 1, 1, 2, 0},\n\t\t{\"POTATO\", \"POTTATO\", 1, 1, 2, 1},\n\t\t{\"POTTATO\", \"POTATO\", 1, 1, 2, 1},\n\t\t{\"HOUSE\", \"MOUSE\", 1, 1, 2, 2},\n\t\t{\"MOUSE\", \"HOUSE\", 2, 2, 4, 4},\n\t\t{\"abc\", \"xy\", 2, 3, 5, 13},\n\t\t{\"xy\", \"abc\", 2, 3, 5, 12},\n\t}\n\n\tfor _, c := range cases {\n\t\tif r := smetrics.Ukkonen(c.s, c.t, c.icost, c.dcost, c.scost); r != c.r {\n\t\t\tfmt.Println(r, \"instead of\", c.r)\n\t\t\tt.Fail()\n\t\t}\n\t}\n}"} {"input": "package travis\n\nimport (\n\tservices \"github.com/de1ux/prowler/services/v1\"\n\tvcs \"github.com/de1ux/prowler/vcs/v1\"\n)\n\nfunc NewClient(config *Config) services.Client {\n\treturn &Client{config: config}\n}\n\ntype Client struct {\n\tconfig *Config\n}\n\n\n\nfunc (c *Client) GetStatusByPullRequest(pr *vcs.PullRequest) (*services.Status, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package route53\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/trackit/jsonlog\"\n\n\t\"github.com/trackit/trackit/es\"\n)\n\nconst TypeRoute53Report = \"route53-report\"\nconst IndexPrefixRoute53Report = \"route53-reports\"\nconst TemplateNameRoute53Report = \"route53-reports\"\n\n\n\n\nconst TemplateRoute53Report = `\n{\n\t\"template\": \"*-route53-reports\",\n\t\"version\": 2,\n\t\"mappings\": {\n\t\t\"route53-report\": {\n\t\t\t\"properties\": {\n\t\t\t\t\"account\": {\n\t\t\t\t\t\"type\": \"keyword\"\n\t\t\t\t},\n\t\t\t\t\"reportDate\": {\n\t\t\t\t\t\"type\": \"date\"\n\t\t\t\t},\n\t\t\t\t\"reportType\": {\n\t\t\t\t\t\"type\": \"keyword\"\n\t\t\t\t},\n\t\t\t\t\"hostedZone\": {\n\t\t\t\t\t\"properties\": {\n\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\t\"type\": \"keyword\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"id\": {\n\t\t\t\t\t\t\t\"type\": \"keyword\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"region\": {\n\t\t\t\t\t\t\t\"type\": \"keyword\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"tags\": {\n\t\t\t\t\t\t\t\"type\": \"nested\",\n\t\t\t\t\t\t\t\"properties\": {\n\t\t\t\t\t\t\t\t\"key\": {\n\t\t\t\t\t\t\t\t\t\"type\": \"keyword\"\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\"value\": {\n\t\t\t\t\t\t\t\t\t\"type\": \"keyword\"\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\t\"_all\": {\n\t\t\t\t\"enabled\": false\n\t\t\t},\n\t\t\t\"numeric_detection\": false,\n\t\t\t\"date_detection\": false\n\t\t}\n\t}\n}\n`\n\nfunc init() ", "output": "{\n\tctx, ctxCancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer ctxCancel()\n\tres, err := es.Client.IndexPutTemplate(TemplateNameRoute53Report).BodyString(TemplateRoute53Report).Do(ctx)\n\tif err != nil {\n\t\tjsonlog.DefaultLogger.Error(\"Failed to put ES index route53-reports.\", err)\n\t} else {\n\t\tjsonlog.DefaultLogger.Info(\"Put ES index route53-reports.\", res)\n\t}\n}"} {"input": "package mocks\n\nimport (\n\t\"crypto/x509\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\n\t\"github.com/letsencrypt/boulder/core\"\n)\n\n\n\ntype MockCA struct {\n\tPEM []byte\n}\n\n\n\n\n\nfunc (ca *MockCA) GenerateOCSP(xferObj core.OCSPSigningRequest) (ocsp []byte, err error) {\n\treturn\n}\n\n\nfunc (ca *MockCA) RevokeCertificate(serial string, reasonCode core.RevocationCode) (err error) {\n\treturn\n}\n\nfunc (ca *MockCA) IssueCertificate(csr x509.CertificateRequest, regID int64) (core.Certificate, error) ", "output": "{\n\tif ca.PEM == nil {\n\t\treturn core.Certificate{}, fmt.Errorf(\"MockCA's PEM field must be set before calling IssueCertificate\")\n\t}\n\tblock, _ := pem.Decode(ca.PEM)\n\tcert, err := x509.ParseCertificate(block.Bytes)\n\tif err != nil {\n\t\treturn core.Certificate{}, err\n\t}\n\treturn core.Certificate{\n\t\tDER: cert.Raw,\n\t}, nil\n}"} {"input": "package bmp280\n\nimport \"encoding/binary\"\nimport \"bytes\"\n\n\n\nfunc convert(b []byte, data interface{}) error ", "output": "{\n\tbuf := bytes.NewReader(b)\n\treturn binary.Read(buf, binary.LittleEndian, data)\n}"} {"input": "package file\n\nimport (\n\t\"github.com/moby/buildkit/solver/llbsolver/ops/fileoptypes\"\n\t\"github.com/moby/buildkit/solver/pb\"\n\t\"github.com/pkg/errors\"\n\tcopy \"github.com/tonistiigi/fsutil/copy\"\n)\n\n\n\nfunc readUser(chopt *pb.ChownOpt, mu, mg fileoptypes.Mount) (*copy.ChownOpt, error) ", "output": "{\n\treturn nil, errors.New(\"only implemented in linux\")\n}"} {"input": "package manifestparser\n\nimport (\n\t\"errors\"\n\t\"io/ioutil\"\n\n\tyaml \"gopkg.in/yaml.v2\"\n)\n\ntype Application struct {\n\tName string `yaml:\"name\"`\n}\n\ntype Parser struct {\n\tPathToManifest string\n\n\tApplications []Application\n\n\trawManifest []byte\n}\n\nfunc NewParser() *Parser {\n\treturn new(Parser)\n}\n\nfunc (parser *Parser) Parse(manifestPath string) error {\n\tbytes, err := ioutil.ReadFile(manifestPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparser.rawManifest = bytes\n\n\tvar raw struct {\n\t\tApplications []Application `yaml:\"applications\"`\n\t}\n\n\terr = yaml.Unmarshal(bytes, &raw)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tparser.Applications = raw.Applications\n\n\tif len(parser.Applications) == 0 {\n\t\treturn errors.New(\"must have at least one application\")\n\t}\n\n\tfor _, application := range parser.Applications {\n\t\tif application.Name == \"\" {\n\t\t\treturn errors.New(\"Found an application with no name specified\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (parser Parser) RawManifest(_ string) ([]byte, error) {\n\treturn parser.rawManifest, nil\n}\n\nfunc (parser Parser) AppNames() []string ", "output": "{\n\tvar names []string\n\tfor _, app := range parser.Applications {\n\t\tnames = append(names, app.Name)\n\t}\n\treturn names\n}"} {"input": "package grpc_ctxtags_test\n\nimport (\n\t\"github.com/grpc-ecosystem/go-grpc-middleware/tags\"\n\t\"google.golang.org/grpc\"\n)\n\n\n\n\n\nfunc Example_initialisationWithOptions() {\n\topts := []grpc_ctxtags.Option{\n\t\tgrpc_ctxtags.WithFieldExtractorForInitialReq(grpc_ctxtags.TagBasedRequestFieldExtractor(\"log_fields\")),\n\t}\n\t_ = grpc.NewServer(\n\t\tgrpc.StreamInterceptor(grpc_ctxtags.StreamServerInterceptor(opts...)),\n\t\tgrpc.UnaryInterceptor(grpc_ctxtags.UnaryServerInterceptor(opts...)),\n\t)\n}\n\nfunc Example_initialization() ", "output": "{\n\topts := []grpc_ctxtags.Option{\n\t\tgrpc_ctxtags.WithFieldExtractor(grpc_ctxtags.TagBasedRequestFieldExtractor(\"log_fields\")),\n\t}\n\t_ = grpc.NewServer(\n\t\tgrpc.StreamInterceptor(grpc_ctxtags.StreamServerInterceptor(opts...)),\n\t\tgrpc.UnaryInterceptor(grpc_ctxtags.UnaryServerInterceptor(opts...)),\n\t)\n}"} {"input": "package utils\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"os\"\n\t\"strconv\"\n)\n\nvar path string\n\nfunc init() {\n\tflag.StringVar(&path, \"path\", \"\", \"Path to the inputfile\")\n\tflag.Parse()\n}\n\ntype Input struct {\n\t*bufio.Scanner\n}\n\n\nfunc GetInput() (*Input, error) {\n\tif len(path) > 0 {\n\t\tfile, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn &Input{}, err\n\t\t}\n\n\t\treturn &Input{bufio.NewScanner(file)}, nil\n\t}\n\treturn &Input{bufio.NewScanner(os.Stdin)}, nil\n}\n\nfunc (input *Input) ReadInt() int {\n\tinput.Split(bufio.ScanWords)\n\n\tif input.Scan() {\n\t\tresult, err := strconv.Atoi(input.Text())\n\t\tif err == nil {\n\t\t\treturn result\n\t\t}\n\t}\n\n\treturn 3\n}\n\n\n\nfunc (input *Input) ReadString() string {\n\tinput.Split(bufio.ScanWords)\n\n\tif input.Scan() {\n\t\treturn input.Text()\n\t}\n\n\treturn \"\"\n}\n\nfunc (input *Input) ReadStrings(size int) []string {\n\tinput.Split(bufio.ScanWords)\n\n\tstrings := make([]string, size)\n\n\tfor i := 0; i < size && input.Scan(); i++ {\n\t\tstrings[i] = input.Text()\n\t}\n\n\treturn strings\n}\n\nfunc (input *Input) ReadInts(size int) []int ", "output": "{\n\tinput.Split(bufio.ScanWords)\n\tints := make([]int, size)\n\n\tfor i := 0; i < size && input.Scan(); i++ {\n\t\tresult, err := strconv.Atoi(input.Text())\n\t\tif err == nil {\n\t\t\tints[i] = result\n\t\t}\n\t}\n\n\treturn ints\n}"} {"input": "package errors2\n\nimport (\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tlvldbug = iota\n\tlvlinfo\n\tlvlerr\n\tlvlcrit\n)\n\ntype logMessage struct {\n\ttime time.Time\n\tlevel int\n\tmessage string\n}\n\ntype Logger struct {\n\tmessages []*logMessage\n\tTimer Timer\n}\n\nfunc (l *Logger) Debug(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvldbug, message: message})\n}\n\n\n\nfunc (l *Logger) Error(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvlerr, message: message})\n}\n\nfunc (l *Logger) Critical(message string) {\n\tl.log(&logMessage{time: time.Now(), level: lvlcrit, message: message})\n}\n\nvar lock = &sync.Mutex{}\n\nfunc (l *Logger) log(message *logMessage) {\n\tlock.Lock()\n\tl.messages = append(l.messages, message)\n\tlock.Unlock()\n}\n\nfunc (l *Logger) Info(message string) ", "output": "{\n\tl.log(&logMessage{time: time.Now(), level: lvlinfo, message: message})\n}"} {"input": "package roletemplate\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/rancher/norman/httperror\"\n\t\"github.com/rancher/norman/types\"\n\t\"github.com/rancher/norman/types/values\"\n\tv3 \"github.com/rancher/types/apis/management.cattle.io/v3\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n)\n\nconst (\n\tRTVersion = \"cleanup.cattle.io/rtUpgradeCluster\"\n\tOldRTVersion = \"field.cattle.io/rtUpgrade\"\n)\n\nfunc Wrap(store types.Store, rtLister v3.RoleTemplateLister) types.Store {\n\treturn &rtStore{\n\t\tStore: store,\n\t\trtLister: rtLister,\n\t}\n}\n\ntype rtStore struct {\n\ttypes.Store\n\n\trtLister v3.RoleTemplateLister\n}\n\nfunc (s *rtStore) Delete(apiContext *types.APIContext, schema *types.Schema, id string) (map[string]interface{}, error) {\n\troleTemplates, err := s.rtLister.List(\"\", labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, rt := range roleTemplates {\n\t\tfor _, parent := range rt.RoleTemplateNames {\n\t\t\tif parent == id {\n\t\t\t\treturn nil, httperror.NewAPIError(httperror.Conflict, fmt.Sprintf(\"roletemplate [%s] cannot be deleted because roletemplate [%s] inherits from it\", id, rt.Name))\n\t\t\t}\n\t\t}\n\t}\n\treturn s.Store.Delete(apiContext, schema, id)\n}\n\n\n\nfunc (s *rtStore) Create(apiContext *types.APIContext, schema *types.Schema, data map[string]interface{}) (map[string]interface{}, error) ", "output": "{\n\n\tvalues.PutValue(data, \"true\", \"metadata\", \"annotations\", RTVersion)\n\n\treturn s.Store.Create(apiContext, schema, data)\n}"} {"input": "package credential\n\nimport (\n\t\"pharmer.dev/cloud/apis\"\n\tv1 \"pharmer.dev/cloud/apis/cloud/v1\"\n\n\t\"github.com/spf13/pflag\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\ntype Linode struct {\n\tCommonSpec\n\n\ttoken string\n}\n\nfunc (c Linode) APIToken() string { return get(c.Data, LinodeAPIToken, c.token) }\n\nfunc (c *Linode) LoadFromEnv() {\n\tc.CommonSpec.LoadFromEnv(c.Format())\n}\n\n\n\nfunc (c *Linode) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(&c.token, apis.Linode+\".\"+LinodeAPIToken, c.token, \"Linode api token\")\n}\n\nfunc (_ Linode) RequiredFlags() []string {\n\treturn []string{apis.Linode + \".\" + LinodeAPIToken}\n}\n\nfunc (_ Linode) Format() v1.CredentialFormat {\n\treturn v1.CredentialFormat{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: apis.Linode,\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tapis.KeyClusterCredential: \"\",\n\t\t\t\tapis.KeyDNSCredential: \"\",\n\t\t\t},\n\t\t},\n\t\tSpec: v1.CredentialFormatSpec{\n\t\t\tProvider: apis.Linode,\n\t\t\tDisplayFormat: \"field\",\n\t\t\tFields: []v1.CredentialField{\n\t\t\t\t{\n\t\t\t\t\tEnvconfig: \"LINODE_TOKEN\",\n\t\t\t\t\tForm: \"linode_token\",\n\t\t\t\t\tJSON: LinodeAPIToken,\n\t\t\t\t\tLabel: \"Token\",\n\t\t\t\t\tInput: \"password\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (c Linode) IsValid() (bool, error) ", "output": "{\n\treturn c.CommonSpec.IsValid(c.Format())\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/gorilla/mux\"\n\t\"net/http\"\n)\n\nfunc Index(w http.ResponseWriter, r *http.Request) {\n\n\tfmt.Fprintln(w, \"Welcome!\")\n}\n\n\n\nfunc TestShow(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\ttestId := vars[\"testId\"]\n\tfmt.Fprintln(w, \"Test show:\", testId)\n}\n\nfunc TestIndex(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tfmt.Fprintln(w, \"Test Index!\")\n\n\ttodos := Todos{\n\t\tTodo{Name: \"Write presentation\"},\n\t\tTodo{Name: \"Host meetup\"},\n\t}\n\n\tif err := json.NewEncoder(w).Encode(todos); err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package townsita\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"os\"\n)\n\nconst defaultConfigFile = \"./config/townsita.json\"\n\ntype Config struct{}\n\nfunc NewConfig() *Config {\n\treturn &Config{}\n}\n\nfunc (c *Config) Load(args []string) error {\n\tfileName := defaultConfigFile\n\tif len(args) > 1 {\n\t\tfileName = args[1]\n\t}\n\tlog.Printf(\"Loading config from %s\", fileName)\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdecoder := json.NewDecoder(file)\n\tif err := decoder.Decode(c); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc (c *Config) templatePath(templateName string) string ", "output": "{\n\treturn \"./templates/\" + templateName\n}"} {"input": "package netutil\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype ConnWrapper struct {\n\tio.Reader\n\tio.Writer\n\tUnderlyingConn net.Conn\n\tReadCloser io.Closer\n\tWriteCloser io.Closer\n}\n\nvar _ net.Conn = new(ConnWrapper)\n\nfunc (c *ConnWrapper) Close() error {\n\tvar multiErr MultiError\n\tif c.ReadCloser != nil {\n\t\tmultiErr.RecordError(c.ReadCloser.Close())\n\t}\n\tif c.WriteCloser != nil {\n\t\tmultiErr.RecordError(c.WriteCloser.Close())\n\t}\n\tmultiErr.RecordError(c.UnderlyingConn.Close())\n\treturn multiErr.ToError()\n}\n\nfunc (c *ConnWrapper) LocalAddr() net.Addr { return c.UnderlyingConn.LocalAddr() }\n\nfunc (c *ConnWrapper) SetDeadline(t time.Time) error { return c.UnderlyingConn.SetDeadline(t) }\nfunc (c *ConnWrapper) SetReadDeadline(t time.Time) error { return c.UnderlyingConn.SetReadDeadline(t) }\nfunc (c *ConnWrapper) SetWriteDeadline(t time.Time) error { return c.UnderlyingConn.SetWriteDeadline(t) }\n\nfunc (c *ConnWrapper) RemoteAddr() net.Addr ", "output": "{ return c.UnderlyingConn.RemoteAddr() }"} {"input": "package partner\n\nimport (\n\t\"github.com/jrsix/gof/web\"\n\t\"github.com/jrsix/gof/web/mvc\"\n\t\"go2o/src/core/domain/interface/partner\"\n\t\"go2o/src/core/service/dps\"\n\t\"net/url\"\n)\n\nfunc chkLogin(ctx *web.Context) (b bool, partnerId int) {\n\tv := ctx.Session().Get(\"partner_id\")\n\tif v == nil {\n\t\treturn false, -1\n\t}\n\treturn true, v.(int)\n}\nfunc redirect(ctx *web.Context) {\n\tr, w := ctx.Request, ctx.Response\n\tw.Write([]byte(\"\"))\n}\n\nvar _ mvc.Filter = new(baseC)\n\ntype baseC struct {\n}\n\nfunc (this *baseC) Requesting(ctx *web.Context) bool {\n\tif b, _ := chkLogin(ctx); !b {\n\t\tredirect(ctx)\n\t\treturn false\n\t}\n\treturn true\n}\nfunc (this *baseC) RequestEnd(ctx *web.Context) {\n}\n\n\n\n\nfunc (this *baseC) GetPartner(ctx *web.Context) (*partner.ValuePartner, error) {\n\treturn dps.PartnerService.GetPartner(this.GetPartnerId(ctx))\n}\n\n\nfunc (this *baseC) ErrorOutput(ctx *web.Context, err string) {\n\tctx.Response.Write([]byte(\"{error:\\\"\" + err + \"\\\"}\"))\n}\n\nfunc (this *baseC) GetPartnerId(ctx *web.Context) int ", "output": "{\n\tv := ctx.Session().Get(\"partner_id\")\n\tif v == nil {\n\t\tthis.Requesting(ctx)\n\t\treturn -1\n\t}\n\treturn v.(int)\n}"} {"input": "package blanket_emulator\n\nimport (\n\t\"fmt\"\n)\n\ntype Event interface {\n\tHash() uint64\n\tInspect() string\n}\n\ntype ReturnEvent uint64\ntype ReadEvent uint64\ntype WriteEvent struct {\n\tAddr uint64\n\tValue uint64\n}\ntype SyscallEvent uint64\ntype InvalidInstructionEvent uint64\n\nfunc (addr ReadEvent) Hash() uint64 {\n\treturn ReadEventHash(uint64(addr))\n}\n\nfunc (s WriteEvent) Hash() uint64 {\n\treturn WriteEventHash(s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Hash() uint64 {\n\treturn SysEventHash(uint64(s))\n}\n\n\n\nfunc (s InvalidInstructionEvent) Hash() uint64 {\n\treturn InvalidInstructionEventHash(uint64(s))\n}\n\nfunc (addr ReadEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Read([%x])\", addr)\n}\n\nfunc (addr ReturnEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Return([%x])\", addr)\n}\n\nfunc (s WriteEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Write([%x]=%x)\", s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Sys(%x)\", s)\n}\n\nfunc (s InvalidInstructionEvent) Inspect() string {\n\treturn fmt.Sprintf(\"InvalidOpcode([%x])\", s)\n}\n\nfunc (s ReturnEvent) Hash() uint64 ", "output": "{\n\treturn ReturnEventHash(uint64(s))\n}"} {"input": "package unittest\n\nimport (\n\t\"io/ioutil\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/Huawei/dockyard/utils\"\n)\n\n\nfunc TestMetaEncrypt(t *testing.T) {\n\tvar item utils.MetaItem\n\n\titem.SetEncryption(utils.EncryptRSA)\n\tassert.Equal(t, true, item.GetEncryption() == utils.EncryptRSA, \"Fail to set/get entrypt method\")\n}\n\n\nfunc TestMetaItemGenerate(t *testing.T) {\n\t_, path, _, _ := runtime.Caller(0)\n\tdir := filepath.Join(filepath.Dir(path), \"testdata\")\n\n\ttestContentFile := filepath.Join(dir, \"hello.txt\")\n\ttestHashFile := filepath.Join(dir, \"hello.hash\")\n\tcontentByte, _ := ioutil.ReadFile(testContentFile)\n\thashByte, _ := ioutil.ReadFile(testHashFile)\n\tmetaItem := utils.GenerateMetaItem(\"hello.txt\", contentByte)\n\tassert.Equal(t, metaItem.GetHash(), strings.TrimSpace(string(hashByte)), \"Fail to get correct hash value\")\n}\n\n\n\n\nfunc TestMetaTime(t *testing.T) ", "output": "{\n\ttest1 := \"test1\"\n\ttest1Byte := []byte(\"test1 byte\")\n\tmetaItem1 := utils.GenerateMetaItem(test1, test1Byte)\n\tmetaItem2 := metaItem1\n\tassert.Equal(t, metaItem1, metaItem2, \"Fail to compare metaItem, should be the same\")\n\n\tmetaItem2.SetCreated(metaItem2.GetCreated().Add(time.Hour * 1))\n\tcmp := metaItem1.Compare(metaItem2)\n\tassert.Equal(t, cmp < 0, true, \"Fail to compare metaItem, should be smaller\")\n\n\tassert.Equal(t, metaItem2.IsExpired(), false, \"Fail to get expired information\")\n\tmetaItem2.SetExpired(time.Now().Add(time.Hour * (-1)))\n\tassert.Equal(t, metaItem2.IsExpired(), true, \"Fail to get expired information\")\n}"} {"input": "package main\n\nimport (\n\traw \"github.com/buger/gor/raw_socket_listener\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\n\ntype RAWInput struct {\n\tdata chan *raw.TCPMessage\n\taddress string\n\texpire time.Duration\n\tquit chan bool\n\tlistener *raw.Listener\n}\n\n\nfunc NewRAWInput(address string, expire time.Duration) (i *RAWInput) {\n\ti = new(RAWInput)\n\ti.data = make(chan *raw.TCPMessage)\n\ti.address = address\n\ti.expire = expire\n\ti.quit = make(chan bool)\n\n\tgo i.listen(address)\n\n\treturn\n}\n\nfunc (i *RAWInput) Read(data []byte) (int, error) {\n\tmsg := <-i.data\n\tbuf := msg.Bytes()\n\n\tvar header []byte\n\n\tif msg.IsIncoming {\n\t\theader = payloadHeader(RequestPayload, msg.UUID(), msg.Start.UnixNano())\n\t} else {\n\t\theader = payloadHeader(ResponsePayload, msg.UUID(), msg.End.UnixNano()-msg.RequestStart.UnixNano())\n\t}\n\n\tcopy(data[0:len(header)], header)\n\tcopy(data[len(header):], buf)\n\n\treturn len(buf) + len(header), nil\n}\n\n\n\nfunc (i *RAWInput) String() string {\n\treturn \"RAW Socket input: \" + i.address\n}\n\nfunc (i *RAWInput) Close() {\n\ti.listener.Close()\n\tclose(i.quit)\n}\n\nfunc (i *RAWInput) listen(address string) ", "output": "{\n\taddress = strings.Replace(address, \"[::]\", \"127.0.0.1\", -1)\n\n\tDebug(\"Listening for traffic on: \" + address)\n\n\thost, port, err := net.SplitHostPort(address)\n\n\tif err != nil {\n\t\tlog.Fatal(\"input-raw: error while parsing address\", err)\n\t}\n\n\ti.listener = raw.NewListener(host, port, i.expire, true)\n\n\tfor {\n\t\tselect {\n\t\tcase <-i.quit:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tm := i.listener.Receive()\n\n\t\ti.data <- m\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/coscms/xweb\"\n)\n\ntype MainAction struct {\n\t*xweb.Action\n\n\thello xweb.Mapper `xweb:\"/(.*)\"`\n}\n\n\n\nfunc main() {\n\tmc := &MainAction{}\n\n\tserver1 := xweb.NewServer()\n\tserver1.AddRouter(\"/\", mc)\n\tgo server1.Run(\"0.0.0.0:9999\")\n\n\tserver2 := xweb.NewServer()\n\tserver2.AddRouter(\"/\", mc)\n\tgo server2.Run(\"0.0.0.0:8999\")\n\n\t<-make(chan int)\n}\n\nfunc (c *MainAction) Hello(world string) ", "output": "{\n\tc.Write(\"hello %v\", world)\n}"} {"input": "package integration\n\nimport (\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/containous/traefik/integration/try\"\n\t\"github.com/go-check/check\"\n\tchecker \"github.com/vdemeester/shakers\"\n)\n\n\ntype ErrorPagesSuite struct {\n\tBaseSuite\n\tErrorPageIP string\n\tBackendIP string\n}\n\nfunc (s *ErrorPagesSuite) SetUpSuite(c *check.C) {\n\ts.createComposeProject(c, \"error_pages\")\n\ts.composeProject.Start(c)\n\n\ts.ErrorPageIP = s.composeProject.Container(c, \"nginx2\").NetworkSettings.IPAddress\n\ts.BackendIP = s.composeProject.Container(c, \"nginx1\").NetworkSettings.IPAddress\n}\n\nfunc (s *ErrorPagesSuite) TestSimpleConfiguration(c *check.C) {\n\n\tfile := s.adaptFile(c, \"fixtures/error_pages/simple.toml\", struct {\n\t\tServer1 string\n\t\tServer2 string\n\t}{s.BackendIP, s.ErrorPageIP})\n\tdefer os.Remove(file)\n\n\tcmd, display := s.traefikCmd(withConfigFile(file))\n\tdefer display(c)\n\terr := cmd.Start()\n\tc.Assert(err, checker.IsNil)\n\tdefer cmd.Process.Kill()\n\n\tfrontendReq, err := http.NewRequest(http.MethodGet, \"http://127.0.0.1:8080\", nil)\n\tc.Assert(err, checker.IsNil)\n\tfrontendReq.Host = \"test.local\"\n\n\terr = try.Request(frontendReq, 2*time.Second, try.BodyContains(\"nginx\"))\n\tc.Assert(err, checker.IsNil)\n}\n\n\n\nfunc (s *ErrorPagesSuite) TestErrorPage(c *check.C) ", "output": "{\n\n\tfile := s.adaptFile(c, \"fixtures/error_pages/error.toml\", struct {\n\t\tServer1 string\n\t\tServer2 string\n\t}{s.BackendIP, s.ErrorPageIP})\n\tdefer os.Remove(file)\n\n\tcmd, display := s.traefikCmd(withConfigFile(file))\n\tdefer display(c)\n\terr := cmd.Start()\n\tc.Assert(err, checker.IsNil)\n\tdefer cmd.Process.Kill()\n\n\tfrontendReq, err := http.NewRequest(http.MethodGet, \"http://127.0.0.1:8080\", nil)\n\tc.Assert(err, checker.IsNil)\n\tfrontendReq.Host = \"test.local\"\n\n\terr = try.Request(frontendReq, 2*time.Second, try.BodyContains(\"An error occurred.\"))\n\tc.Assert(err, checker.IsNil)\n}"} {"input": "package sampler\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n)\n\ntype Target struct {\n\tURL JsonURL\n\tName string\n\tInterval int\n\tTags []string\n\tAttributes map[string]string\n\tHash string\n\tRequestHeaders map[string]string\n\tInsecureSkipVerify bool\n}\n\n\n\nfunc (t *Target) SetHash() ", "output": "{\n\tjsonTarget, _ := json.Marshal(t)\n\thasher := md5.New()\n\thasher.Write(jsonTarget)\n\tt.Hash = hex.EncodeToString(hasher.Sum(nil))\n}"} {"input": "package iso20022\n\n\ntype PartyIdentificationAndAccount77 struct {\n\n\tIdentification *PartyIdentification32Choice `xml:\"Id\"`\n\n\tAlternateIdentification *AlternatePartyIdentification5 `xml:\"AltrnId,omitempty\"`\n\n\tSafekeepingAccount *Max35Text `xml:\"SfkpgAcct,omitempty\"`\n\n\tProcessingIdentification *Max35Text `xml:\"PrcgId,omitempty\"`\n\n\tAdditionalInformation *PartyTextInformation1 `xml:\"AddtlInf,omitempty\"`\n}\n\n\n\nfunc (p *PartyIdentificationAndAccount77) AddAlternateIdentification() *AlternatePartyIdentification5 {\n\tp.AlternateIdentification = new(AlternatePartyIdentification5)\n\treturn p.AlternateIdentification\n}\n\nfunc (p *PartyIdentificationAndAccount77) SetSafekeepingAccount(value string) {\n\tp.SafekeepingAccount = (*Max35Text)(&value)\n}\n\nfunc (p *PartyIdentificationAndAccount77) SetProcessingIdentification(value string) {\n\tp.ProcessingIdentification = (*Max35Text)(&value)\n}\n\nfunc (p *PartyIdentificationAndAccount77) AddAdditionalInformation() *PartyTextInformation1 {\n\tp.AdditionalInformation = new(PartyTextInformation1)\n\treturn p.AdditionalInformation\n}\n\nfunc (p *PartyIdentificationAndAccount77) AddIdentification() *PartyIdentification32Choice ", "output": "{\n\tp.Identification = new(PartyIdentification32Choice)\n\treturn p.Identification\n}"} {"input": "package displayers\n\nimport (\n\t\"io\"\n\t\"strings\"\n\n\t\"github.com/digitalocean/doctl/do\"\n)\n\ntype Certificate struct {\n\tCertificates do.Certificates\n}\n\nvar _ Displayable = &Certificate{}\n\n\n\nfunc (c *Certificate) Cols() []string {\n\treturn []string{\n\t\t\"ID\",\n\t\t\"Name\",\n\t\t\"DNSNames\",\n\t\t\"SHA1Fingerprint\",\n\t\t\"NotAfter\",\n\t\t\"Created\",\n\t\t\"Type\",\n\t\t\"State\",\n\t}\n}\n\nfunc (c *Certificate) ColMap() map[string]string {\n\treturn map[string]string{\n\t\t\"ID\": \"ID\",\n\t\t\"Name\": \"Name\",\n\t\t\"DNSNames\": \"DNS Names\",\n\t\t\"SHA1Fingerprint\": \"SHA-1 Fingerprint\",\n\t\t\"NotAfter\": \"Expiration Date\",\n\t\t\"Created\": \"Created At\",\n\t\t\"Type\": \"Type\",\n\t\t\"State\": \"State\",\n\t}\n}\n\nfunc (c *Certificate) KV() []map[string]interface{} {\n\tout := []map[string]interface{}{}\n\n\tfor _, c := range c.Certificates {\n\t\to := map[string]interface{}{\n\t\t\t\"ID\": c.ID,\n\t\t\t\"Name\": c.Name,\n\t\t\t\"DNSNames\": strings.Join(c.DNSNames, \",\"),\n\t\t\t\"SHA1Fingerprint\": c.SHA1Fingerprint,\n\t\t\t\"NotAfter\": c.NotAfter,\n\t\t\t\"Created\": c.Created,\n\t\t\t\"Type\": c.Type,\n\t\t\t\"State\": c.State,\n\t\t}\n\t\tout = append(out, o)\n\t}\n\n\treturn out\n}\n\nfunc (c *Certificate) JSON(out io.Writer) error ", "output": "{\n\treturn writeJSON(c.Certificates, out)\n}"} {"input": "package main\n\n\n\n\n\n\n\nimport \"C\"\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"runtime/pprof\"\n\t\"unsafe\"\n)\n\n\n\nfunc CgoRaceprof() {\n\truntime.SetCgoTraceback(0, unsafe.Pointer(C.raceprofTraceback), nil, nil)\n\n\tvar buf bytes.Buffer\n\tpprof.StartCPUProfile(&buf)\n\n\tC.runRaceprofThread()\n\tfmt.Println(\"OK\")\n}\n\nfunc init() ", "output": "{\n\tregister(\"CgoRaceprof\", CgoRaceprof)\n}"} {"input": "package service\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetServiceIDOKCode int = 200\n\n\ntype GetServiceIDOK struct {\n\n\tPayload *models.Service `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetServiceIDOK() *GetServiceIDOK {\n\n\treturn &GetServiceIDOK{}\n}\n\n\nfunc (o *GetServiceIDOK) WithPayload(payload *models.Service) *GetServiceIDOK {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *GetServiceIDOK) SetPayload(payload *models.Service) {\n\to.Payload = payload\n}\n\n\n\n\n\nconst GetServiceIDNotFoundCode int = 404\n\n\ntype GetServiceIDNotFound struct {\n}\n\n\nfunc NewGetServiceIDNotFound() *GetServiceIDNotFound {\n\n\treturn &GetServiceIDNotFound{}\n}\n\n\nfunc (o *GetServiceIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc (o *GetServiceIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}"} {"input": "package fake\n\nimport (\n\tclientset \"github.com/openshift/client-go/oauth/clientset/versioned\"\n\toauthv1 \"github.com/openshift/client-go/oauth/clientset/versioned/typed/oauth/v1\"\n\tfakeoauthv1 \"github.com/openshift/client-go/oauth/clientset/versioned/typed/oauth/v1/fake\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/watch\"\n\t\"k8s.io/client-go/discovery\"\n\tfakediscovery \"k8s.io/client-go/discovery/fake\"\n\t\"k8s.io/client-go/testing\"\n)\n\n\n\n\n\nfunc NewSimpleClientset(objects ...runtime.Object) *Clientset {\n\to := testing.NewObjectTracker(scheme, codecs.UniversalDecoder())\n\tfor _, obj := range objects {\n\t\tif err := o.Add(obj); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tfakePtr := testing.Fake{}\n\tfakePtr.AddReactor(\"*\", \"*\", testing.ObjectReaction(o))\n\tfakePtr.AddWatchReactor(\"*\", testing.DefaultWatchReactor(watch.NewFake(), nil))\n\n\treturn &Clientset{fakePtr, &fakediscovery.FakeDiscovery{Fake: &fakePtr}}\n}\n\n\n\n\ntype Clientset struct {\n\ttesting.Fake\n\tdiscovery *fakediscovery.FakeDiscovery\n}\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\treturn c.discovery\n}\n\nvar _ clientset.Interface = &Clientset{}\n\n\nfunc (c *Clientset) OauthV1() oauthv1.OauthV1Interface {\n\treturn &fakeoauthv1.FakeOauthV1{Fake: &c.Fake}\n}\n\n\n\n\nfunc (c *Clientset) Oauth() oauthv1.OauthV1Interface ", "output": "{\n\treturn &fakeoauthv1.FakeOauthV1{Fake: &c.Fake}\n}"} {"input": "package api\n\nimport (\n\t\"io\"\n)\n\n\n\ntype Snapshot struct {\n\tc *Client\n}\n\n\n\n\n\n\n\n\nfunc (s *Snapshot) Save(q *QueryOptions) (io.ReadCloser, *QueryMeta, error) {\n\tr := s.c.newRequest(\"GET\", \"/v1/snapshot\")\n\tr.setQueryOptions(q)\n\n\trtt, resp, err := s.c.doRequest(r)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif err := requireOK(resp); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tqm := &QueryMeta{}\n\tparseQueryMeta(resp, qm)\n\tqm.RequestTime = rtt\n\treturn resp.Body, qm, nil\n}\n\n\nfunc (s *Snapshot) Restore(q *WriteOptions, in io.Reader) error {\n\tr := s.c.newRequest(\"PUT\", \"/v1/snapshot\")\n\tr.body = in\n\tr.header.Set(\"Content-Type\", \"application/octet-stream\")\n\tr.setWriteOptions(q)\n\t_, resp, err := s.c.doRequest(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := requireOK(resp); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *Client) Snapshot() *Snapshot ", "output": "{\n\treturn &Snapshot{c}\n}"} {"input": "package pet\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-swagger/go-swagger/httpkit\"\n)\n\n\ntype DeletePetBadRequest struct {\n}\n\n\n\n\nfunc (o *DeletePetBadRequest) WriteResponse(rw http.ResponseWriter, producer httpkit.Producer) ", "output": "{\n\n\trw.WriteHeader(400)\n}"} {"input": "package factory\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/juju/core/container\"\n\t\"github.com/juju/core/container/kvm\"\n\t\"github.com/juju/core/container/lxc\"\n\t\"github.com/juju/core/instance\"\n)\n\n\n\n\n\nfunc NewContainerManager(forType instance.ContainerType, conf container.ManagerConfig) (container.Manager, error) ", "output": "{\n\tswitch forType {\n\tcase instance.LXC:\n\t\treturn lxc.NewContainerManager(conf)\n\tcase instance.KVM:\n\t\treturn kvm.NewContainerManager(conf)\n\t}\n\treturn nil, fmt.Errorf(\"unknown container type: %q\", forType)\n}"} {"input": "package station\n\nimport (\n\t\"github.com/moryg/eve_analyst/apiqueue/ratelimit\"\n\t\"github.com/moryg/eve_analyst/database/station\"\n\t\"log\"\n\t\"net/http\"\n)\n\n\n\nfunc (r *request) execute() ", "output": "{\n\tratelimit.Add()\n\tres, err := http.Get(r.url)\n\tratelimit.Sub()\n\n\tif err != nil {\n\t\tlog.Println(\"station.execute: \" + err.Error())\n\t\treturn\n\t}\n\n\trsp, err := parseResBody(res)\n\tif err != nil {\n\t\tlog.Println(\"station.execute parse:\" + err.Error())\n\t\treturn\n\t}\n\n\tstation.Update(r.stationId, rsp.SystemID, rsp.Name)\n\tlog.Printf(\"Updated station %d\\n\", r.stationId)\n}"} {"input": "package internal\n\nimport (\n\t. \"github.com/signal18/replication-manager/goofys/api/common\"\n\t. \"gopkg.in/check.v1\"\n\n\t\"github.com/jacobsa/fuse\"\n)\n\ntype AwsTest struct {\n\ts3 *S3Backend\n}\n\nvar _ = Suite(&AwsTest{})\n\nfunc (s *AwsTest) SetUpSuite(t *C) {\n\tvar err error\n\ts.s3, err = NewS3(\"\", &FlagStorage{}, &S3Config{\n\t\tRegion: \"us-east-1\",\n\t})\n\tt.Assert(err, IsNil)\n}\n\nfunc (s *AwsTest) TestRegionDetection(t *C) {\n\ts.s3.bucket = \"goofys-eu-west-1.signal18/replication-manager.xyz\"\n\n\terr, isAws := s.s3.detectBucketLocationByHEAD()\n\tt.Assert(err, IsNil)\n\tt.Assert(*s.s3.awsConfig.Region, Equals, \"eu-west-1\")\n\tt.Assert(isAws, Equals, true)\n}\n\n\n\nfunc (s *AwsTest) TestBucket404(t *C) ", "output": "{\n\ts.s3.bucket = RandStringBytesMaskImprSrc(64)\n\n\terr, isAws := s.s3.detectBucketLocationByHEAD()\n\tt.Assert(err, Equals, fuse.ENOENT)\n\tt.Assert(isAws, Equals, true)\n}"} {"input": "package v1\n\nimport context \"context\"\n\nimport proto \"github.com/golang/protobuf/proto\"\nimport \"go-common/library/net/rpc/liverpc\"\n\nvar _ proto.Message \n\n\n\n\n\n\ntype CaptchaRPCClient interface {\n\tCreate(ctx context.Context, req *CaptchaCreateReq, opts ...liverpc.CallOption) (resp *CaptchaCreateResp, err error)\n}\n\n\n\n\n\ntype captchaRPCClient struct {\n\tclient *liverpc.Client\n}\n\n\nfunc NewCaptchaRPCClient(client *liverpc.Client) CaptchaRPCClient {\n\treturn &captchaRPCClient{\n\t\tclient: client,\n\t}\n}\n\nfunc (c *captchaRPCClient) Create(ctx context.Context, in *CaptchaCreateReq, opts ...liverpc.CallOption) (*CaptchaCreateResp, error) {\n\tout := new(CaptchaCreateResp)\n\terr := doRPCRequest(ctx, c.client, 1, \"Captcha.create\", in, out, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}\n\n\n\n\n\n\n\nfunc doRPCRequest(ctx context.Context, client *liverpc.Client, version int, method string, in, out proto.Message, opts []liverpc.CallOption) (err error) ", "output": "{\n\terr = client.Call(ctx, version, method, in, out, opts...)\n\treturn\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/labstack/echo\"\n)\n\n\ntype Error struct {\n\tMessage string `json:\"message\"`\n}\n\n\nfunc OK(c echo.Context, payload interface{}) error {\n\treturn c.JSON(http.StatusOK, payload)\n}\n\n\nfunc Created(c echo.Context, payload interface{}) error {\n\treturn c.JSON(http.StatusCreated, payload)\n}\n\n\nfunc NoContent(c echo.Context) error {\n\treturn c.NoContent(http.StatusNoContent)\n}\n\n\nfunc BadRequest(c echo.Context, msg string) error {\n\treturn c.JSON(http.StatusBadRequest, Error{msg})\n}\n\n\nfunc NotFound(c echo.Context) error {\n\treturn c.JSON(http.StatusNotFound, Error{\"Resource not found\"})\n}\n\n\nfunc Conflict(c echo.Context, msg string) error {\n\treturn c.JSON(http.StatusConflict, Error{msg})\n}\n\n\nfunc Invalid(c echo.Context, msg string) error {\n\treturn c.JSON(422, Error{msg})\n}\n\n\n\n\n\nfunc InternalServerError(c echo.Context, err error) error ", "output": "{\n\tlog.WithFields(log.Fields{\n\t\t\"request_id\": RequestID(c),\n\t}).Error(err)\n\n\treturn c.JSON(http.StatusInternalServerError, Error{\"Oops! Something went wrong\"})\n}"} {"input": "package http2\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestGoroutineLock(t *testing.T) ", "output": "{\n\toldDebug := DebugGoroutines\n\tDebugGoroutines = true\n\tdefer func() { DebugGoroutines = oldDebug }()\n\n\tg := newGoroutineLock()\n\tg.check()\n\n\tsawPanic := make(chan interface{})\n\tgo func() {\n\t\tdefer func() { sawPanic <- recover() }()\n\t\tg.check() \n\t}()\n\te := <-sawPanic\n\tif e == nil {\n\t\tt.Fatal(\"did not see panic from check in other goroutine\")\n\t}\n\tif !strings.Contains(fmt.Sprint(e), \"wrong goroutine\") {\n\t\tt.Errorf(\"expected on see panic about running on the wrong goroutine; got %v\", e)\n\t}\n}"} {"input": "package storageimportexport\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" storageimportexport/2016-11-01\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package iso20022\n\n\ntype FinancialInstrument11 struct {\n\n\tIdentification *SecurityIdentification3Choice `xml:\"Id\"`\n\n\tName *Max350Text `xml:\"Nm,omitempty\"`\n\n\tTransferType *TransferType1Code `xml:\"TrfTp\"`\n}\n\n\n\nfunc (f *FinancialInstrument11) SetName(value string) {\n\tf.Name = (*Max350Text)(&value)\n}\n\nfunc (f *FinancialInstrument11) SetTransferType(value string) {\n\tf.TransferType = (*TransferType1Code)(&value)\n}\n\nfunc (f *FinancialInstrument11) AddIdentification() *SecurityIdentification3Choice ", "output": "{\n\tf.Identification = new(SecurityIdentification3Choice)\n\treturn f.Identification\n}"} {"input": "package server\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/cockroachdb/cockroach/gossip/resolver\"\n\t\"github.com/cockroachdb/cockroach/util/leaktest\"\n)\n\n\n\n\n\nfunc TestParseGossipBootstrapAddrs(t *testing.T) {\n\tdefer leaktest.AfterTest(t)\n\tctx := NewContext()\n\tctx.GossipBootstrap = \"localhost:12345,,localhost:23456\"\n\tctx.Stores = \"mem=1\"\n\tif err := ctx.Init(\"start\"); err != nil {\n\t\tt.Fatalf(\"Failed to initialize the context: %v\", err)\n\t}\n\tr1, err := resolver.NewResolver(&ctx.Context, \"tcp=localhost:12345\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tr2, err := resolver.NewResolver(&ctx.Context, \"tcp=localhost:23456\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\texpected := []resolver.Resolver{r1, r2}\n\tif !reflect.DeepEqual(ctx.GossipBootstrapResolvers, expected) {\n\t\tt.Fatalf(\"Unexpected bootstrap addresses: %v, expected: %v\", ctx.GossipBootstrapResolvers, expected)\n\t}\n}\n\nfunc TestParseNodeAttributes(t *testing.T) ", "output": "{\n\tdefer leaktest.AfterTest(t)\n\tctx := NewContext()\n\tctx.Attrs = \"attr1=val1::attr2=val2\"\n\tctx.Stores = \"mem=1\"\n\tctx.GossipBootstrap = \"self=\"\n\tif err := ctx.Init(\"start\"); err != nil {\n\t\tt.Fatalf(\"Failed to initialize the context: %v\", err)\n\t}\n\texpected := []string{\"attr1=val1\", \"attr2=val2\"}\n\tif !reflect.DeepEqual(ctx.NodeAttributes.GetAttrs(), expected) {\n\t\tt.Fatalf(\"Unexpected attributes: %v\", ctx.NodeAttributes.GetAttrs())\n\t}\n}"} {"input": "package processors\n\nimport \"github.com/dailyburn/ratchet/data\"\n\n\n\n\n\ntype Passthrough struct {\n\ti int\n}\n\n\nfunc NewPassthrough() *Passthrough {\n\treturn &Passthrough{}\n}\n\n\nfunc (r *Passthrough) ProcessData(d data.JSON, outputChan chan data.JSON, killChan chan error) {\n\toutputChan <- d\n}\n\n\nfunc (r *Passthrough) Finish(outputChan chan data.JSON, killChan chan error) {\n}\n\n\n\nfunc (r *Passthrough) String() string ", "output": "{\n\treturn \"Passthrough\"\n}"} {"input": "package Plugin\n\nimport \"github.com/MPjct/GoMP/MySQLProtocol\"\n\ntype Plugin_interface interface {\n\tinit(context MySQLProtocol.Context)\n\tread_handshake(context MySQLProtocol.Context)\n\tsend_handshake(context MySQLProtocol.Context)\n\tread_auth(context MySQLProtocol.Context)\n\tsend_auth(context MySQLProtocol.Context)\n\tread_auth_result(context MySQLProtocol.Context)\n\tsend_auth_result(context MySQLProtocol.Context)\n\tread_query(context MySQLProtocol.Context)\n\tsend_query(context MySQLProtocol.Context)\n\tread_query_result(context MySQLProtocol.Context)\n\tsend_query_result(context MySQLProtocol.Context)\n\tcleanup(context MySQLProtocol.Context)\n}\n\ntype Plugin struct {\n}\n\nfunc (plugin *Plugin) init(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\n\n\nfunc (plugin *Plugin) send_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) cleanup(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth(context MySQLProtocol.Context) ", "output": "{\n\treturn\n}"} {"input": "package retry\n\nimport (\n\t\"time\"\n)\n\ntype strategyFunc func(now time.Time) Timer\n\n\nfunc (f strategyFunc) NewTimer(now time.Time) Timer {\n\treturn f(now)\n}\n\n\n\n\nfunc LimitCount(n int, strategy Strategy) Strategy {\n\treturn strategyFunc(func(now time.Time) Timer {\n\t\treturn &countLimitTimer{\n\t\t\ttimer: strategy.NewTimer(now),\n\t\t\tremain: n,\n\t\t}\n\t})\n}\n\ntype countLimitTimer struct {\n\ttimer Timer\n\tremain int\n}\n\nfunc (t *countLimitTimer) NextSleep(now time.Time) (time.Duration, bool) {\n\tif t.remain--; t.remain <= 0 {\n\t\treturn 0, false\n\t}\n\treturn t.timer.NextSleep(now)\n}\n\n\n\n\n\ntype timeLimitTimer struct {\n\ttimer Timer\n\tend time.Time\n}\n\nfunc (t *timeLimitTimer) NextSleep(now time.Time) (time.Duration, bool) {\n\tsleep, ok := t.timer.NextSleep(now)\n\tif ok && now.Add(sleep).After(t.end) {\n\t\treturn 0, false\n\t}\n\treturn sleep, ok\n}\n\nfunc LimitTime(limit time.Duration, strategy Strategy) Strategy ", "output": "{\n\treturn strategyFunc(func(now time.Time) Timer {\n\t\treturn &timeLimitTimer{\n\t\t\ttimer: strategy.NewTimer(now),\n\t\t\tend: now.Add(limit),\n\t\t}\n\t})\n}"} {"input": "package tpu\n\nimport (\n\t\"strings\"\n\n\tapiv1 \"k8s.io/api/core/v1\"\n)\n\nconst (\n\tResourceTPUPrefix = \"cloud-tpus.google.com/\"\n)\n\nfunc hasTPURequest(pod *apiv1.Pod) bool {\n\tfor _, container := range pod.Spec.Containers {\n\t\tfor name := range container.Resources.Requests {\n\t\t\tif strings.HasPrefix(string(name), ResourceTPUPrefix) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc clearTPURequest(pod *apiv1.Pod) *apiv1.Pod {\n\tsanitized := pod.DeepCopy()\n\tfor _, container := range sanitized.Spec.Containers {\n\t\tfor name := range container.Resources.Requests {\n\t\t\tif strings.HasPrefix(string(name), ResourceTPUPrefix) {\n\t\t\t\tdelete(container.Resources.Requests, name)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn sanitized\n}\n\n\n\n\n\nfunc ClearTPURequests(pods []*apiv1.Pod) []*apiv1.Pod ", "output": "{\n\tpodsWithTPU := make(map[int]*apiv1.Pod)\n\tfor i, pod := range pods {\n\t\tif hasTPURequest(pod) {\n\t\t\tpodsWithTPU[i] = clearTPURequest(pod)\n\t\t}\n\t}\n\n\tif len(podsWithTPU) == 0 {\n\t\treturn pods\n\t}\n\n\tsanitizedPods := make([]*apiv1.Pod, len(pods))\n\tfor i, pod := range pods {\n\t\tif sanitized, found := podsWithTPU[i]; found {\n\t\t\tsanitizedPods[i] = sanitized\n\t\t} else {\n\t\t\tsanitizedPods[i] = pod\n\t\t}\n\t}\n\treturn sanitizedPods\n}"} {"input": "package marks\n\nimport (\n\t\"strings\"\n\n\t\"github.com/zclconf/go-cty/cty\"\n)\n\n\n\n\ntype valueMark string\n\n\n\n\nfunc Has(val cty.Value, mark valueMark) bool {\n\treturn val.HasMark(mark)\n}\n\n\n\nfunc Contains(val cty.Value, mark valueMark) bool {\n\tret := false\n\tcty.Walk(val, func(_ cty.Path, v cty.Value) (bool, error) {\n\t\tif v.HasMark(mark) {\n\t\t\tret = true\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\treturn ret\n}\n\n\n\nvar Sensitive = valueMark(\"sensitive\")\n\n\n\n\nvar TypeType = valueMark(\"typeType\")\n\nfunc (m valueMark) GoString() string ", "output": "{\n\treturn \"marks.\" + strings.Title(string(m))\n}"} {"input": "package externalversions\n\nimport (\n\t\"fmt\"\n\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tcache \"k8s.io/client-go/tools/cache\"\n\tv1 \"k8s.io/code-generator/examples/HyphenGroup/apis/example/v1\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}\n\n\n\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {\n\tswitch resource {\n\tcase v1.SchemeGroupVersion.WithResource(\"clustertesttypes\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.ExampleGroup().V1().ClusterTestTypes().Informer()}, nil\n\tcase v1.SchemeGroupVersion.WithResource(\"testtypes\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.ExampleGroup().V1().TestTypes().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}\n\nfunc (f *genericInformer) Lister() cache.GenericLister ", "output": "{\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}"} {"input": "package accounts\n\nimport (\n\t\"testing\"\n\n\tos \"github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts\"\n\tth \"github.com/rackspace/gophercloud/testhelper\"\n\tfake \"github.com/rackspace/gophercloud/testhelper/client\"\n)\n\nfunc TestUpdateAccounts(t *testing.T) {\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\n\tos.HandleUpdateAccountSuccessfully(t)\n\n\toptions := &UpdateOpts{Metadata: map[string]string{\"gophercloud-test\": \"accounts\"}}\n\tres := Update(fake.ServiceClient(), options)\n\tth.CheckNoErr(t, res.Err)\n}\n\n\n\nfunc TestGetAccounts(t *testing.T) ", "output": "{\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\n\tos.HandleGetAccountSuccessfully(t)\n\n\texpected := map[string]string{\"Foo\": \"bar\"}\n\tactual, err := Get(fake.ServiceClient()).ExtractMetadata()\n\tth.CheckNoErr(t, err)\n\tth.CheckDeepEquals(t, expected, actual)\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype OpenpitrixLeaveGroupResponse struct {\n\n\tGroupID []string `json:\"group_id\"`\n\n\tUserID []string `json:\"user_id\"`\n}\n\n\nfunc (m *OpenpitrixLeaveGroupResponse) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateGroupID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateUserID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (m *OpenpitrixLeaveGroupResponse) validateGroupID(formats strfmt.Registry) error {\n\n\tif swag.IsZero(m.GroupID) { \n\t\treturn nil\n\t}\n\n\treturn nil\n}\n\nfunc (m *OpenpitrixLeaveGroupResponse) validateUserID(formats strfmt.Registry) error {\n\n\tif swag.IsZero(m.UserID) { \n\t\treturn nil\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc (m *OpenpitrixLeaveGroupResponse) UnmarshalBinary(b []byte) error {\n\tvar res OpenpitrixLeaveGroupResponse\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *OpenpitrixLeaveGroupResponse) MarshalBinary() ([]byte, error) ", "output": "{\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}"} {"input": "package source\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\nfunc Goroutines() {\n\n\tf(\"direct\")\n\n\tgo f(\"goroutine\")\n\n\tgo func(msg string) {\n\t\tfmt.Println(msg)\n\t}(\"going\")\n\n\ttime.Sleep(time.Second*5)\n\n}\n\nfunc f(from string) ", "output": "{\n\tfor i := 0; i<3; i++ {\n\t\tfmt.Println(from, \":\", i)\n\t\ttime.Sleep(time.Second)\n\t}\n}"} {"input": "package v1beta1\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n)\n\n\n\ntype EvictionsGetter interface {\n\tEvictions(namespace string) EvictionInterface\n}\n\n\ntype EvictionInterface interface {\n\tEvictionExpansion\n}\n\n\ntype evictions struct {\n\tclient rest.Interface\n\tns string\n}\n\n\n\n\nfunc newEvictions(c *PolicyV1beta1Client, namespace string) *evictions ", "output": "{\n\treturn &evictions{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}"} {"input": "package esicache\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/corestoreio/errors\"\n)\n\n\n\n\ntype Cacher interface {\n\tSet(key string, value []byte, expiration time.Duration) error\n\tGet(key string) ([]byte, error)\n}\n\n\n\nfunc NewCacher(url string) (Cacher, error) {\n\n\treturn nil, nil\n}\n\n\ntype Caches []Cacher\n\n\nfunc (c Caches) Set(key string, value []byte, expiration time.Duration) error {\n\treturn nil\n}\n\n\nfunc (c Caches) Get(key string) ([]byte, error) {\n\treturn nil, nil\n}\n\n\nvar MainRegistry = ®istry{\n\tcaches: make(map[string]Caches),\n}\n\ntype registry struct {\n\tmu sync.RWMutex\n\tcaches map[string]Caches\n}\n\nfunc (r *registry) Get(ctx context.Context, scope, alias, key string) error {\n\treturn errors.New(\"TODO IMPLEMENT\")\n}\n\n\n\n\nfunc (r *registry) Register(scope, url string) error {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tc, err := NewCacher(url)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"[esikv] NewCacher URL %q\", url)\n\t}\n\n\tif _, ok := r.caches[scope]; !ok {\n\t\tr.caches[scope] = make(Caches, 0, 2)\n\t}\n\tr.caches[scope] = append(r.caches[scope], c)\n\n\treturn nil\n}\n\n\n\n\n\nfunc (r *registry) Clear() {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tr.caches = make(map[string]Caches)\n}\n\nfunc (r *registry) Len(scope string) int ", "output": "{\n\tr.mu.RLock()\n\tdefer r.mu.RUnlock()\n\treturn len(r.caches[scope])\n}"} {"input": "package network\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + version.Number + \" network/2019-08-01\"\n}"} {"input": "package logical\n\nimport (\n\t\"context\"\n\n\tlog \"github.com/hashicorp/go-hclog\"\n)\n\n\ntype BackendType uint32\n\n\n\nconst (\n\tTypeUnknown BackendType = 0 \n\tTypeLogical BackendType = 1\n\tTypeCredential BackendType = 2\n)\n\n\n\n\n\n\n\n\n\n\n\n\ntype Backend interface {\n\tHandleRequest(context.Context, *Request) (*Response, error)\n\n\tSpecialPaths() *Paths\n\n\tSystem() SystemView\n\n\tLogger() log.Logger\n\n\tHandleExistenceCheck(context.Context, *Request) (bool, bool, error)\n\n\tCleanup(context.Context)\n\n\tInvalidateKey(context.Context, string)\n\n\tSetup(context.Context, *BackendConfig) error\n\n\tType() BackendType\n}\n\n\ntype BackendConfig struct {\n\tStorageView Storage\n\n\tLogger log.Logger\n\n\tSystem SystemView\n\n\tBackendUUID string\n\n\tConfig map[string]string\n}\n\n\ntype Factory func(context.Context, *BackendConfig) (Backend, error)\n\n\ntype Paths struct {\n\tRoot []string\n\n\tUnauthenticated []string\n\n\tLocalStorage []string\n\n\tSealWrapStorage []string\n}\n\nfunc (b BackendType) String() string ", "output": "{\n\tswitch b {\n\tcase TypeLogical:\n\t\treturn \"secret\"\n\tcase TypeCredential:\n\t\treturn \"auth\"\n\t}\n\n\treturn \"unknown\"\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/xeb/etcdrepl/third_party/github.com/codegangsta/cli\"\n\t\"github.com/xeb/etcdrepl/third_party/github.com/coreos/go-etcd/etcd\"\n)\n\nfunc NewLsCommand() cli.Command {\n\treturn cli.Command{\n\t\tName:\t\"ls\",\n\t\tUsage:\t\"retrieve a directory\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.BoolFlag{\"recursive\", \"returns all values for key and child keys\"},\n\t\t},\n\t\tAction: func(c *cli.Context) {\n\t\t\thandleLs(c, lsCommandFunc)\n\t\t},\n\t}\n}\n\n\nfunc handleLs(c *cli.Context, fn handlerFunc) {\n\thandlePrint(c, fn, printLs)\n}\n\n\n\nfunc printLs(resp *etcd.Response, format string) {\n\tif !resp.Node.Dir {\n\t\tfmt.Println(resp.Node.Key)\n\t}\n\tfor _, node := range resp.Node.Nodes {\n\t\trPrint(&node)\n\t}\n}\n\n\nfunc lsCommandFunc(c *cli.Context, client *etcd.Client) (*etcd.Response, error) {\n\tkey := \"/\"\n\tif len(c.Args()) != 0 {\n\t\tkey = c.Args()[0]\n\t}\n\trecursive := c.Bool(\"recursive\")\n\n\treturn client.Get(key, false, recursive)\n}\n\n\n\n\nfunc rPrint(n *etcd.Node) ", "output": "{\n\tfmt.Println(n.Key)\n\tfor _, node := range n.Nodes {\n\t\trPrint(&node)\n\t}\n}"} {"input": "package main\n\ntype OffState struct {\n\tstatusLed Output\n}\n\n\n\nfunc (s *OffState) Enter(m StateMachine) {\n\ts.statusLed.Low()\n}\n\nfunc (s *OffState) Event(m StateMachine, pin uint, value uint) {\n\tif pin == GPIO_SWITCH_PIN && value == GPIO_SWITCH_ON {\n\t\tm.Transit(STATE_WAITING)\n\t}\n}\n\nfunc (s *OffState) Leave(m StateMachine) {}\n\nfunc (s *OffState) String() string {\n\treturn \"Off\"\n}\n\nfunc NewOffState(statusLed Output) State ", "output": "{\n\ts := OffState{statusLed: statusLed}\n\treturn &s\n}"} {"input": "package delete\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\n\n\n\n\nfunc NewDeleteNodesIdentifierParamsWithTimeout(timeout time.Duration) *DeleteNodesIdentifierParams {\n\tvar ()\n\treturn &DeleteNodesIdentifierParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype DeleteNodesIdentifierParams struct {\n\n\tIdentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *DeleteNodesIdentifierParams) WithIdentifier(identifier string) *DeleteNodesIdentifierParams {\n\to.Identifier = identifier\n\treturn o\n}\n\n\nfunc (o *DeleteNodesIdentifierParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"identifier\", o.Identifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewDeleteNodesIdentifierParams() *DeleteNodesIdentifierParams ", "output": "{\n\tvar ()\n\treturn &DeleteNodesIdentifierParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}"} {"input": "package controller\n\nimport (\n\t\"github.com/webx-top/blog/app/base\"\n\t\"github.com/webx-top/echo\"\n)\n\nfunc New(c echo.Context) *Base {\n\treturn &Base{\n\t\tController: base.NewController(c),\n\t}\n}\n\ntype Base struct {\n\t*base.Controller\n}\n\n\n\nfunc (a *Base) Before() error ", "output": "{\n\treturn nil\n}"} {"input": "package iso20022\n\n\ntype ATMTransactionAmounts6 struct {\n\n\tCurrency *ActiveCurrencyCode `xml:\"Ccy,omitempty\"`\n\n\tMaximumPossibleAmount *ImpliedCurrencyAndAmount `xml:\"MaxPssblAmt,omitempty\"`\n\n\tMinimumPossibleAmount *ImpliedCurrencyAndAmount `xml:\"MinPssblAmt,omitempty\"`\n\n\tAdditionalAmount []*ATMTransactionAmounts7 `xml:\"AddtlAmt,omitempty\"`\n}\n\nfunc (a *ATMTransactionAmounts6) SetCurrency(value string) {\n\ta.Currency = (*ActiveCurrencyCode)(&value)\n}\n\nfunc (a *ATMTransactionAmounts6) SetMaximumPossibleAmount(value, currency string) {\n\ta.MaximumPossibleAmount = NewImpliedCurrencyAndAmount(value, currency)\n}\n\nfunc (a *ATMTransactionAmounts6) SetMinimumPossibleAmount(value, currency string) {\n\ta.MinimumPossibleAmount = NewImpliedCurrencyAndAmount(value, currency)\n}\n\n\n\nfunc (a *ATMTransactionAmounts6) AddAdditionalAmount() *ATMTransactionAmounts7 ", "output": "{\n\tnewValue := new(ATMTransactionAmounts7)\n\ta.AdditionalAmount = append(a.AdditionalAmount, newValue)\n\treturn newValue\n}"} {"input": "package memcachep\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n)\n\ntype Stats map[string]fmt.Stringer\n\n\ntype FuncStat struct {\n\tCallable func() string\n}\n\n\n\n\ntype StaticStat struct {\n\tValue string\n}\n\nfunc (s *StaticStat) String() string {\n\treturn s.Value\n}\n\n\ntype CounterStat struct {\n\tCount int\n\tcalculations chan int\n}\n\nfunc (c *CounterStat) Increment(num int) {\n\tc.calculations <- num\n}\n\nfunc (c *CounterStat) SetCount(num int) {\n\tc.Count = num\n}\n\nfunc (c *CounterStat) Decrement(num int) {\n\tc.calculations <- -num\n}\n\nfunc (c *CounterStat) String() string {\n\treturn strconv.Itoa(c.Count)\n}\n\nfunc (c *CounterStat) work() {\n\tfor num := range c.calculations {\n\t\tc.Count = c.Count + num\n\t}\n}\n\nfunc NewCounterStat() *CounterStat {\n\tc := &CounterStat{}\n\tc.calculations = make(chan int, 100)\n\tgo c.work()\n\treturn c\n}\n\nfunc NewStats() Stats {\n\ts := make(Stats)\n\ts[\"pid\"] = &StaticStat{strconv.Itoa(os.Getpid())}\n\ts[\"version\"] = &StaticStat{VERSION}\n\ts[\"golang\"] = &StaticStat{runtime.Version()}\n\ts[\"goroutines\"] = &FuncStat{func() string { return strconv.Itoa(runtime.NumGoroutine()) }}\n\ts[\"cpu_num\"] = &StaticStat{strconv.Itoa(runtime.NumCPU())}\n\ts[\"total_connections\"] = NewCounterStat()\n\ts[\"curr_connections\"] = NewCounterStat()\n\ts[\"cmd_get\"] = NewCounterStat()\n\treturn s\n}\n\nfunc (f *FuncStat) String() string ", "output": "{\n\treturn f.Callable()\n}"} {"input": "package ast\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/suite\"\n)\n\ntype StructTypeSpecTestSuite struct {\n\tsuite.Suite\n}\n\n\n\nfunc (s *StructTypeSpecTestSuite) TestName() {\n\tspec, err := FindJSONStructFor(\"github.com/marcel/jitjson/fixtures/media\", \"Album\")\n\ts.Nil(err)\n\n\ts.Equal(\"Album\", spec.Name())\n}\n\nfunc TestStructTypeSpecTestSuite(t *testing.T) ", "output": "{\n\tsuite.Run(t, new(StructTypeSpecTestSuite))\n}"} {"input": "package pump\n\nimport (\n\t\"time\"\n\n\t\"github.com/vail130/orinoco/sieve\"\n\t\"github.com/vail130/orinoco/timeutils\"\n)\n\n\n\nfunc Pump(minBatchSize int, maxBatchDelay int, streams [](map[string]string), eventChannel chan *sieve.Event) {\n\tvar start time.Time\n\tvar now time.Time\n\tfor {\n\t\tstart = timeutils.UtcNow()\n\t\teventArray := make([]sieve.Event, 0)\n\t\tfor event := range eventChannel {\n\t\t\teventArray = append(eventArray, *event)\n\t\t\tnow = timeutils.UtcNow()\n\t\t\tif now.Sub(start) >= time.Duration(maxBatchDelay) || len(eventChannel) >= minBatchSize {\n\t\t\t\tforkStream(streams, eventArray)\n\t\t\t\tstart = now\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc forkStream(streams [](map[string]string), eventArray []sieve.Event) ", "output": "{\n\tfor i := 0; i < len(streams); i++ {\n\t\tswitch {\n\t\tcase streams[i][\"type\"] == \"stdout\":\n\t\t\tstream := StdoutStream{}\n\t\t\tgo stream.Process(eventArray)\n\t\tcase streams[i][\"type\"] == \"log\":\n\t\t\tstream := LogStream{\n\t\t\t\tstreams[i][\"path\"],\n\t\t\t}\n\t\t\tgo stream.Process(eventArray)\n\t\tcase streams[i][\"type\"] == \"http\":\n\t\t\tstream := HTTPStream{\n\t\t\t\tstreams[i][\"url\"],\n\t\t\t}\n\t\t\tgo stream.Process(eventArray)\n\t\tcase streams[i][\"type\"] == \"s3\":\n\t\t\tstream := S3Stream{\n\t\t\t\tstreams[i][\"region\"],\n\t\t\t\tstreams[i][\"bucket\"],\n\t\t\t\tstreams[i][\"prefix\"],\n\t\t\t}\n\t\t\tgo stream.Process(eventArray)\n\t\t}\n\t}\n}"} {"input": "package nogo\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype mapBackedRoleRepository struct {\n\troleMap map[string]Role\n}\n\n\n\nfunc (this *mapBackedRoleRepository) FindAll() ([]Role, error) {\n\tret := make([]Role, 0)\n\tfor _, role := range this.roleMap {\n\t\tret = append(ret, role)\n\t}\n\treturn ret, nil\n}\n\nfunc (this *mapBackedRoleRepository) FindRole(roleName string) (Role, error) {\n\tif role, ok := this.roleMap[roleName]; ok {\n\t\treturn role, nil\n\t}\n\treturn nil, errors.New(fmt.Sprintf(\"Could not find role %v\", roleName))\n}\n\nfunc (this *mapBackedRoleRepository) CreateRole(role Role) error {\n\tif _, ok := this.roleMap[role.GetName()]; ok {\n\t\treturn errors.New(fmt.Sprintf(\"Error creating role. Role %v already exists\", role.GetName()))\n\t}\n\tthis.roleMap[role.GetName()] = role\n\treturn nil\n}\n\nfunc (this *mapBackedRoleRepository) UpdateRole(role Role) error {\n\tif _, ok := this.roleMap[role.GetName()]; ok {\n\t\tthis.roleMap[role.GetName()] = role\n\t\treturn nil\n\t}\n\treturn errors.New(fmt.Sprintf(\"Error updating role. Role %v does not exist.\", role.GetName()))\n}\n\nfunc (this *mapBackedRoleRepository) DeleteRole(roleName string) error {\n\tif _, ok := this.roleMap[roleName]; ok {\n\t\tdelete(this.roleMap, roleName)\n\t}\n\treturn errors.New(fmt.Sprintf(\"Error deleting role. Role %v does not exist.\", roleName))\n}\n\nfunc NewMapBackedRoleRepository() RoleRepository ", "output": "{\n\treturn &mapBackedRoleRepository{roleMap: make(map[string]Role)}\n}"} {"input": "package authorization\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/ransoni/uchiwa/uchiwa/authentication\"\n\t\"github.com/ransoni/uchiwa/uchiwa/logger\"\n)\n\n\n\ntype Authorization interface {\n\tHandler(http.Handler) http.Handler\n}\n\n\ntype Uchiwa struct{}\n\n\nfunc (u *Uchiwa) Handler(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\treadonly := isReadOnly(r)\n\t\tauthorized := isAuthorized(readonly, r.Method)\n\t\tif !authorized {\n\t\t\thttp.Error(w, \"Request forbidden\", http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\nfunc isAuthorized(isReadOnly bool, method string) bool {\n\tif (method != http.MethodHead && method != http.MethodGet) && isReadOnly {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc isReadOnly(r *http.Request) bool ", "output": "{\n\tvar role *authentication.Role\n\n\ttoken := authentication.GetJWTFromContext(r)\n\tif token == nil { \n\t\tlogger.Debug(\"No JWT found in context\")\n\t\treturn false\n\t}\n\n\trole, err := authentication.GetRoleFromToken(token)\n\tif err != nil {\n\t\tlogger.Debug(\"Invalid token: %s\", err)\n\t\treturn true\n\t}\n\n\treturn role.Readonly\n}"} {"input": "package common\n\nimport (\n\t\"encoding/binary\"\n\t\"sort\"\n)\n\n\n\ntype Uint64Slice []uint64\n\nfunc (p Uint64Slice) Len() int { return len(p) }\nfunc (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] }\n\nfunc (p Uint64Slice) Sort() { sort.Sort(p) }\n\nfunc SearchUint64s(a []uint64, x uint64) int {\n\treturn sort.Search(len(a), func(i int) bool { return a[i] >= x })\n}\n\nfunc (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) }\n\n\n\nfunc PutUint64LE(dest []byte, i uint64) {\n\tbinary.LittleEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64LE(src []byte) uint64 {\n\treturn binary.LittleEndian.Uint64(src)\n}\n\nfunc PutUint64BE(dest []byte, i uint64) {\n\tbinary.BigEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64BE(src []byte) uint64 {\n\treturn binary.BigEndian.Uint64(src)\n}\n\nfunc PutInt64LE(dest []byte, i int64) {\n\tbinary.LittleEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64LE(src []byte) int64 {\n\treturn int64(binary.LittleEndian.Uint64(src))\n}\n\nfunc PutInt64BE(dest []byte, i int64) {\n\tbinary.BigEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64BE(src []byte) int64 {\n\treturn int64(binary.BigEndian.Uint64(src))\n}\n\nfunc (p Uint64Slice) Swap(i, j int) ", "output": "{ p[i], p[j] = p[j], p[i] }"} {"input": "package demo_server\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/http/cookiejar\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"testing\"\n)\n\n\nfunc TestServer(t *testing.T) {\n\tf, err := ioutil.TempFile(\"/tmp\", \"hijinks\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.Remove(f.Name())\n\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\thandler := NewRootHandler(wd+\"/..\", []byte(\"12345678901234567890123456789012\"))\n\n\tserver := httptest.NewUnstartedServer(handler)\n\tserver.Start()\n\tdefer server.Close()\n\n\t*handler.URL = server.URL\n\turl := server.URL\n\n\tclient := newClient(t, url)\n\tread(t, client, url)\n}\n\nfunc newClient(t *testing.T, host string) *http.Client {\n\tjar, err := cookiejar.New(nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttransport := http.DefaultTransport.(*http.Transport)\n\tc := &http.Client{Jar: jar, Transport: transport}\n\n\treturn c\n}\n\n\n\nfunc read(t *testing.T, client *http.Client, url string) []byte ", "output": "{\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(body) == 0 {\n\t\tt.Error(\"empty response\")\n\t}\n\treturn body\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"k8s.io/kubernetes/pkg/client/clientset_generated/clientset/typed/policy/v1beta1\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n\tcore \"k8s.io/kubernetes/pkg/client/testing/core\"\n)\n\ntype FakePolicyV1beta1 struct {\n\t*core.Fake\n}\n\nfunc (c *FakePolicyV1beta1) Evictions(namespace string) v1beta1.EvictionInterface {\n\treturn &FakeEvictions{c, namespace}\n}\n\nfunc (c *FakePolicyV1beta1) PodDisruptionBudgets(namespace string) v1beta1.PodDisruptionBudgetInterface {\n\treturn &FakePodDisruptionBudgets{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakePolicyV1beta1) RESTClient() restclient.Interface ", "output": "{\n\tvar ret *restclient.RESTClient\n\treturn ret\n}"} {"input": "package gtreap\n\nimport (\n\t\"math/rand\"\n\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\nfunc (w *Writer) BytesSafeAfterClose() bool {\n\treturn false\n}\n\nfunc (w *Writer) Get(k []byte) (v []byte, err error) {\n\tw.s.m.Lock()\n\tt := w.s.t\n\tw.s.m.Unlock()\n\n\titm := t.Get(&Item{k: k})\n\tif itm != nil {\n\t\treturn itm.(*Item).v, nil\n\t}\n\treturn nil, nil\n}\n\nfunc (w *Writer) Iterator(k []byte) store.KVIterator {\n\tw.s.m.Lock()\n\tt := w.s.t\n\tw.s.m.Unlock()\n\n\treturn newIterator(t).restart(&Item{k: k})\n}\n\nfunc (w *Writer) Close() error {\n\tw.s.availableWriters <- true\n\tw.s = nil\n\n\treturn nil\n}\n\nfunc (w *Writer) Set(k, v []byte) (err error) {\n\tw.s.m.Lock()\n\tw.s.t = w.s.t.Upsert(&Item{k: k, v: v}, rand.Int())\n\tw.s.m.Unlock()\n\n\treturn nil\n}\n\n\n\nfunc (w *Writer) NewBatch() store.KVBatch {\n\treturn store.NewEmulatedBatch(w, w.s.mo)\n}\n\nfunc (w *Writer) Delete(k []byte) (err error) ", "output": "{\n\tw.s.m.Lock()\n\tw.s.t = w.s.t.Delete(&Item{k: k})\n\tw.s.m.Unlock()\n\n\treturn nil\n}"} {"input": "package main\n\nimport(\"fmt\";\"os\";\"regexp\";\"flag\";\"net/http\";\"log\";\"errors\")\n\ntype HTTPDCmd struct {}\n\nfunc (c *HTTPDCmd) Summary() string {\n return \"Starts small HTTP server\"\n}\n\nfunc (c *HTTPDCmd) Help() string {\n return `Starts small HTTP daemon that can server files from a specific directory\n\nAvailable subcommands:\n httpd serve Serve on 0.0.0.0:\n`\n}\n\nfunc (c *HTTPDCmd) ValidateArgs(args[]string) error {\n re1 := regexp.MustCompile(\"^[0-9]+$\")\n re2 := regexp.MustCompile(\"^/.+$\")\n if (len(args) == 3 && args[0] == \"serve\" && re1.MatchString(args[1]) && re2.MatchString(args[2])) {\n return nil\n }\n return errors.New(\"Invalid args\")\n}\n\n\n\nfunc (c *HTTPDCmd) Run(args[]string, cfg Config) (int, error) ", "output": "{\n if (len(args) == 3 && args[0] == \"serve\") {\n port := flag.String(\"p\", args[1], \"port to serve on\")\n path := flag.String(\"d\", args[2], \"the dir of static file on host\")\n flag.Parse()\n http.Handle(\"/\", http.FileServer(http.Dir(*path)))\n log.Fatal(http.ListenAndServe(\":\"+*port, nil))\n return 1, nil\n }\n fmt.Fprintf(os.Stdout, c.Help())\n return 0, nil\n}"} {"input": "package next\n\nimport (\n \"gopkg.in/mgo.v2\"\n \"gopkg.in/mgo.v2/bson\"\n)\n\ntype MongoDB struct {\n session *mgo.Session\n db string\n}\n\nfunc NewMongoDB() *MongoDB {\n return &MongoDB{}\n}\n\nfunc (mongo *MongoDB) Open(url string, db string) {\n s, err := mgo.Dial(url)\n if err != nil {\n panic(err.Error())\n }\n\n mongo.session = s\n mongo.db = db\n}\n\nfunc (mongo *MongoDB) Close() {\n mongo.session.Close()\n}\n\nfunc (mongo *MongoDB) Session() *mgo.Session {\n s := mongo.session.Copy()\n s.SetMode(mgo.Strong, true)\n return s\n}\n\n\n\nfunc (mongo *MongoDB) InsertOrUpdate(collection string, buziKey string, buziValue interface{}, d interface{}, result interface{}) (error) ", "output": "{\n s := mongo.Session()\n defer s.Close()\n\n c := s.DB(mongo.db).C(collection)\n\n change := mgo.Change{\n Update: bson.M{\"$set\": d},\n Upsert: true,\n Remove: false,\n ReturnNew: true,\n }\n\n _, err := c.Find(bson.M{buziKey: buziValue}).Apply(change, result)\n return err\n}"} {"input": "package integration\n\nimport (\n\t\"github.com/trivago/tgo/ttesting\"\n\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\n\n\n\nfunc TestFileConsumerWatchWithMove(t *testing.T) ", "output": "{\n\tsetup()\n\texpect := ttesting.NewExpect(t)\n\n\tresultFile, out, err := executeFileRotationTest(tmpTestFilePathBar, tmpTestFilePathDefault)\n\texpect.NoError(err)\n\n\texpect.Contains(out, \"(startup)\")\n\n\texpect.True(strings.Contains(resultFile.content, \"foo\"))\n\texpect.True(strings.Contains(resultFile.content, \"bar\"))\n\texpect.True(strings.Contains(resultFile.content, \"test\"))\n\texpect.Equal(1, resultFile.lines)\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc merge_sort1(a, b []int) {\n n := len(a)\n if n == 1 {\n b[0] = a[0]\n return\n }\n merge_sort1(a[:n/2], b[:n/2])\n merge_sort1(a[n/2:], b[n/2:])\n merge(b[:n/2], b[n/2:], a)\n copy(b,a)\n}\n\nfunc merge_sort(a []int) {\n n := len(a)\n if n <= 1 {\n return\n }\n b := make([]int, n)\n merge_sort1(a[:n/2], b[:n/2])\n merge_sort1(a[n/2:], b[n/2:])\n merge(b[:n/2], b[n/2:], a)\n}\n\nfunc main() {\n a := []int{3,4,178,642,85,3,45,78,5,976,34,51,65,761,414,1,87,612,53,14,550}\n merge_sort(a)\n fmt.Println(a)\n}\n\nfunc merge(a, b, d []int) ", "output": "{\n i, j, k := 0, 0, 0\n na, nb := len(a), len(b)\n for i < na && j < nb {\n if a[i] < b[j] {\n d[k] = a[i]\n i++\n } else {\n d[k] = b[j]\n j++;\n }\n k++;\n }\n for i < na {\n d[k] = a[i]\n k++\n i++\n }\n for j < nb {\n d[k] = b[j]\n k++\n j++\n }\n}"} {"input": "package dbr\n\ntype union struct {\n\tbuilder []Builder\n\tall bool\n}\n\n\n\n\n\nfunc UnionAll(builder ...Builder) interface {\n\tBuilder\n\tAs(string) Builder\n} {\n\treturn &union{\n\t\tbuilder: builder,\n\t\tall: true,\n\t}\n}\n\nfunc (u *union) Build(d Dialect, buf Buffer) error {\n\tfor i, b := range u.builder {\n\t\tif i > 0 {\n\t\t\tbuf.WriteString(\" UNION \")\n\t\t\tif u.all {\n\t\t\t\tbuf.WriteString(\"ALL \")\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(placeholder)\n\t\tbuf.WriteValue(b)\n\t}\n\treturn nil\n}\n\nfunc (u *union) As(alias string) Builder {\n\treturn as(u, alias)\n}\n\nfunc Union(builder ...Builder) interface {\n\tBuilder\n\tAs(string) Builder\n} ", "output": "{\n\treturn &union{\n\t\tbuilder: builder,\n\t}\n}"} {"input": "package errors_test\n\nimport (\n\t\"io\"\n\t\"testing\"\n\n\t. \"v2ray.com/core/common/errors\"\n\t\"v2ray.com/core/testing/assert\"\n)\n\n\n\nfunc TestErrorMessage(t *testing.T) {\n\tassert := assert.On(t)\n\n\tdata := []struct {\n\t\terr error\n\t\tmsg string\n\t}{\n\t\t{\n\t\t\terr: New(\"a\").Base(New(\"b\")).Path(\"c\", \"d\", \"e\"),\n\t\t\tmsg: \"c|d|e: a > b\",\n\t\t},\n\t\t{\n\t\t\terr: New(\"a\").Base(New(\"b\").Path(\"c\")).Path(\"d\", \"e\"),\n\t\t\tmsg: \"d|e: a > c: b\",\n\t\t},\n\t}\n\n\tfor _, d := range data {\n\t\tassert.String(d.err.Error()).Equals(d.msg)\n\t}\n}\n\nfunc TestError(t *testing.T) ", "output": "{\n\tassert := assert.On(t)\n\n\terr := New(\"TestError\")\n\tassert.Bool(GetSeverity(err) == SeverityInfo).IsTrue()\n\n\terr = New(\"TestError2\").Base(io.EOF)\n\tassert.Bool(GetSeverity(err) == SeverityInfo).IsTrue()\n\n\terr = New(\"TestError3\").Base(io.EOF).AtWarning()\n\tassert.Bool(GetSeverity(err) == SeverityWarning).IsTrue()\n\n\terr = New(\"TestError4\").Base(io.EOF).AtWarning()\n\terr = New(\"TestError5\").Base(err)\n\tassert.Bool(GetSeverity(err) == SeverityWarning).IsTrue()\n\tassert.String(err.Error()).Contains(\"EOF\")\n}"} {"input": "package metrics\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestTDigestArrayUsage(t *testing.T) {\n\tr := NewNamespaceRegistry(\"\")\n\n\tm := Metric{\n\t\tName: \"tdigest_vector\",\n\t\tLabels: map[string]string{\n\t\t\t\"top\": \"true\",\n\t\t},\n\t}\n\n\tarr := NewCollectableArray(m, NewTDigestCreator([]float64{1, 0.5, 0.75}), []string{\"handler\", \"code\"})\n\n\tr.Register(arr)\n\n\tarr.ObserveWithValues(\"/foo\", \"200\").Observe(1)\n\tarr.ObserveWithValues(\"/foo\", \"500\").Observe(2)\n\tarr.ObserveWithValues(\"/foo\", \"502\").Observe(3)\n\n\tprintCollectable(r)\n\n}\n\nfunc TestTDigestUsage(t *testing.T) ", "output": "{\n\tr := NewNamespaceRegistry(\"\")\n\n\ttdigest := NewTDigest([]float64{1, 0.5, 0.75})\n\n\tr.Register(&SingleCollectable{\n\t\tMetric: Metric{\n\t\t\tName: \"topname\",\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"test\": \"true\",\n\t\t\t},\n\t\t},\n\t\tCollectable: tdigest,\n\t})\n\n\ttdigest.Observe(float64(time.Second))\n\n\tprintCollectable(r)\n\n}"} {"input": "package firebirdsql\n\ntype firebirdsqlResult struct {\n\taffectedRows int64\n}\n\n\n\nfunc (res *firebirdsqlResult) RowsAffected() (int64, error) {\n\treturn res.affectedRows, nil\n}\n\nfunc (res *firebirdsqlResult) LastInsertId() (int64, error) ", "output": "{\n\treturn -1, nil\n}"} {"input": "package singularity\n\nimport \"github.com/opentable/go-singularity/dtos\"\n\n\n\nfunc (client *Client) DeleteExpiringSkipHealthchecks(requestId string) (response *dtos.SingularityRequestParent, err error) {\n\tpathParamMap := map[string]interface{}{\n\t\t\"requestId\": requestId,\n\t}\n\n\tqueryParamMap := map[string]interface{}{}\n\n\tresponse = new(dtos.SingularityRequestParent)\n\terr = client.DTORequest(response, \"DELETE\", \"/api/requests/request/{requestId}/skip-healthchecks\", pathParamMap, queryParamMap)\n\n\treturn\n}\n\nfunc (client *Client) SkipHealthchecks(requestId string, body *dtos.SingularitySkipHealthchecksRequest) (response *dtos.SingularityRequestParent, err error) ", "output": "{\n\tpathParamMap := map[string]interface{}{\n\t\t\"requestId\": requestId,\n\t}\n\n\tqueryParamMap := map[string]interface{}{}\n\n\tresponse = new(dtos.SingularityRequestParent)\n\terr = client.DTORequest(response, \"PUT\", \"/api/requests/request/{requestId}/skip-healthchecks\", pathParamMap, queryParamMap, body)\n\n\treturn\n}"} {"input": "package customer\n\nimport (\n\t\"github.com/corestoreio/csfw/eav\"\n\t\"github.com/corestoreio/csfw/storage/csdb\"\n)\n\ntype (\n\tAddressModel struct {\n\t}\n)\n\nvar (\n\t_ eav.EntityTypeModeller = (*AddressModel)(nil)\n\t_ eav.EntityTypeTabler = (*AddressModel)(nil)\n\t_ eav.EntityTypeAdditionalAttributeTabler = (*AddressModel)(nil)\n\t_ eav.EntityTypeIncrementModeller = (*AddressModel)(nil)\n)\n\nfunc (c *AddressModel) TBD() {\n\n}\n\nfunc (c *AddressModel) TableNameBase() string {\n\treturn TableCollection.Name(TableIndexAddressEntity)\n}\n\nfunc (c *AddressModel) TableNameValue(i eav.ValueIndex) string {\n\ts, err := GetAddressValueStructure(i)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s.Name\n}\n\n\nfunc (c *AddressModel) TableAdditionalAttribute() (*csdb.Table, error) {\n\treturn TableCollection.Structure(TableIndexEAVAttribute)\n}\n\n\n\n\nfunc Address() *AddressModel {\n\treturn &AddressModel{}\n}\n\nfunc (c *AddressModel) TableEavWebsite() (*csdb.Table, error) ", "output": "{\n\treturn TableCollection.Structure(TableIndexEAVAttributeWebsite)\n}"} {"input": "package fuzzer\n\nimport (\n\t\"testing\"\n\n\t\"k8s.io/apimachinery/pkg/api/apitesting/roundtrip\"\n\n\t\"k8s.io/kubernetes/cmd/kubeadm/app/apis/output/scheme\"\n)\n\n\n\nfunc TestRoundTripTypes(t *testing.T) ", "output": "{\n\troundtrip.RoundTripTestForAPIGroup(t, scheme.AddToScheme, Funcs)\n}"} {"input": "package cplusplus\n\nimport \"testing\"\n\n\n\nfunc TestFoo(t *testing.T) ", "output": "{\n\tfoo := New()\n\tfoo.Bar()\n\tfoo.Free()\n}"} {"input": "package rtda\n\nimport (\n\t\"github.com/zxh0/jvm.go/rtda/heap\"\n)\n\ntype FrameCache struct {\n\tthread *Thread\n\tcachedFrames []*Frame\n\tframeCount uint\n\tmaxFrame uint\n}\n\nfunc newFrameCache(thread *Thread, maxFrame uint) *FrameCache {\n\treturn &FrameCache{\n\t\tthread: thread,\n\t\tmaxFrame: maxFrame,\n\t\tcachedFrames: make([]*Frame, maxFrame),\n\t}\n}\n\n\n\nfunc (cache *FrameCache) returnFrame(frame *Frame) {\n\tif cache.frameCount < cache.maxFrame {\n\t\tfor i, cachedFrame := range cache.cachedFrames {\n\t\t\tif cachedFrame == nil {\n\t\t\t\tcache.cachedFrames[i] = frame\n\t\t\t\tcache.frameCount++\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor _, cachedFrame := range cache.cachedFrames {\n\t\t\tif frame.maxLocals > cachedFrame.maxLocals {\n\t\t\t\tcachedFrame.maxLocals = frame.maxLocals\n\t\t\t\tcachedFrame.LocalVars = frame.LocalVars\n\t\t\t\tframe.maxLocals = 0\n\t\t\t}\n\t\t\tif frame.maxStack > cachedFrame.maxStack {\n\t\t\t\tcachedFrame.maxStack = frame.maxStack\n\t\t\t\tcachedFrame.OperandStack = frame.OperandStack\n\t\t\t\tframe.maxStack = 0\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (cache *FrameCache) borrowFrame(method *heap.Method) *Frame ", "output": "{\n\tif cache.frameCount > 0 {\n\t\tfor i, frame := range cache.cachedFrames {\n\t\t\tif frame != nil &&\n\t\t\t\tframe.maxLocals >= method.MaxLocals &&\n\t\t\t\tframe.maxStack >= method.MaxStack {\n\n\t\t\t\tcache.frameCount--\n\t\t\t\tcache.cachedFrames[i] = nil\n\t\t\t\tframe.reset(method)\n\t\t\t\treturn frame\n\t\t\t}\n\t\t}\n\t}\n\treturn newFrame(cache.thread, method)\n}"} {"input": "package ui\n\nimport (\n\t\"github.com/studentkittens/eulenfunk/display\"\n)\n\n\n\n\ntype Menu struct {\n\tName string\n\n\tEntries []Entry\n\n\tCursor int\n\n\tlw *display.LineWriter\n}\n\n\n\nfunc NewMenu(name string, lw *display.LineWriter) (*Menu, error) {\n\treturn &Menu{\n\t\tName: name,\n\t\tlw: lw,\n\t}, nil\n}\n\n\n\n\nfunc (mn *Menu) Scroll(move int) {\n\tmn.Cursor += move\n\n\tup := move >= 0\n\tmn.scrollToNextSelectable(up)\n\n\tif !mn.Entries[mn.Cursor].Selectable() {\n\t\tmn.scrollToNextSelectable(!up)\n\t}\n}\n\n\nfunc (mn *Menu) Display(width int) error {\n\tfor pos, ClickEntry := range mn.Entries {\n\t\tline := ClickEntry.Render(width, pos == mn.Cursor)\n\t\tif err := mn.lw.Line(mn.Name, pos, line); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\nfunc (mn *Menu) Click() error {\n\tif len(mn.Entries) == 0 {\n\t\treturn nil\n\t}\n\n\treturn mn.Entries[mn.Cursor].Action()\n}\n\nfunc (mn *Menu) scrollToNextSelectable(up bool) ", "output": "{\n\tfor mn.Cursor >= 0 && mn.Cursor < len(mn.Entries) && !mn.Entries[mn.Cursor].Selectable() {\n\t\tif up {\n\t\t\tmn.Cursor++\n\t\t} else {\n\t\t\tmn.Cursor--\n\t\t}\n\t}\n\n\tif mn.Cursor < 0 {\n\t\tmn.Cursor = 0\n\t}\n\n\tif mn.Cursor >= len(mn.Entries) {\n\t\tmn.Cursor = len(mn.Entries) - 1\n\t}\n}"} {"input": "package dhcpv6\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/u-root/uio/uio\"\n)\n\n\nfunc OptRelayPort(port uint16) Option {\n\treturn &optRelayPort{DownstreamSourcePort: port}\n}\n\ntype optRelayPort struct {\n\tDownstreamSourcePort uint16\n}\n\nfunc (op *optRelayPort) Code() OptionCode {\n\treturn OptionRelayPort\n}\n\n\n\nfunc (op *optRelayPort) String() string {\n\treturn fmt.Sprintf(\"RelayPort: %d\", op.DownstreamSourcePort)\n}\n\n\n\nfunc parseOptRelayPort(data []byte) (*optRelayPort, error) {\n\tvar opt optRelayPort\n\tbuf := uio.NewBigEndianBuffer(data)\n\topt.DownstreamSourcePort = buf.Read16()\n\treturn &opt, buf.FinError()\n}\n\nfunc (op *optRelayPort) ToBytes() []byte ", "output": "{\n\tbuf := uio.NewBigEndianBuffer(nil)\n\tbuf.Write16(op.DownstreamSourcePort)\n\treturn buf.Data()\n}"} {"input": "package hostqueue\n\nimport (\n\t\"html/template\"\n\t\"net/http\"\n\t\"regexp\"\n\n\t\"appengine\"\n\n\t\"github.com/gorilla/mux\"\n)\n\ntype Status struct {\n\tName string `json:\"name\"`\n\tHosts []Host `json:\"hosts\"`\n\tNext int `json:\"next\"`\n}\n\n\n\n\nfunc convertToStatus(group Group) Status {\n\treturn Status{\n\t\tName: group.GroupName,\n\t\tNext: group.Next,\n\t\tHosts: group.Hosts,\n\t\t}\n}\n\nfunc isValidUUID(text string) bool {\n\tr := regexp.MustCompile(\"^[a-z0-9]{8}-[a-z0-9]{4}-[1-5][a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{12}$\")\n\treturn r.MatchString(text)\n}\n\nfunc DisplayGroupStatus(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tctx := appengine.NewContext(r)\n\tpathVars := mux.Vars(r)\n\n\tuuid := pathVars[\"uuid\"]\n\tctx.Infof(\"UUID: %s\", uuid)\n\n\tif isValidUUID((uuid)) {\n\t\tgroup, err := GetGroupByUUID(ctx, uuid)\n\t\tctx.Infof(\"group: %v\", group)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tstatus := convertToStatus(group)\n\t\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\n\t\tvar tpl = template.Must(template.ParseGlob(\"templates/*.html\"))\n\t\tif err := tpl.ExecuteTemplate(w, \"status.html\", status); err != nil {\n\t\t\tctx.Infof(\"%v\", err)\n\t\t}\n\n\t} else {\n\t\tw.Write([]byte(\"Invalid group\"))\n\t}\n}"} {"input": "package mos\n\nimport (\n\t\"github.com/atnet/gof/web\"\n\t\"net/http\"\n)\n\nvar (\n\troutes *web.RouteMap = new(web.RouteMap)\n)\n\n\nfunc Handle(ctx *web.Context) {\n\troutes.Handle(ctx)\n}\n\nfunc handleError(w http.ResponseWriter, err error) {\n\tw.Write([]byte(`` + err.Error() + ``))\n}\n\n\nfunc registerRoutes() {\n\tmc := new(mainC)\n\troutes.Add(\"/\",mc.Index)\n}\n\n\n\nfunc init()", "output": "{\n\tregisterRoutes()\n}"} {"input": "package local\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/apache/beam/sdks/go/pkg/beam/io/textio\"\n)\n\nfunc init() {\n\ttextio.RegisterFileSystem(\"default\", New)\n}\n\ntype fs struct{}\n\n\nfunc New(ctx context.Context) textio.FileSystem {\n\treturn &fs{}\n}\n\nfunc (f *fs) Close() error {\n\treturn nil\n}\n\nfunc (f *fs) List(ctx context.Context, glob string) ([]string, error) {\n\treturn filepath.Glob(glob)\n}\n\nfunc (f *fs) OpenRead(ctx context.Context, filename string) (io.ReadCloser, error) {\n\treturn os.Open(filename)\n}\n\n\n\nfunc (f *fs) OpenWrite(ctx context.Context, filename string) (io.WriteCloser, error) ", "output": "{\n\tif err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {\n\t\treturn nil, err\n\t}\n\treturn os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\n}"} {"input": "package state\n\nimport (\n\t\"sync\"\n)\n\n\n\n\n\ntype NotifyGroup struct {\n\tl sync.Mutex\n\tnotify map[chan struct{}]struct{}\n}\n\n\n\nfunc (n *NotifyGroup) Notify() {\n\tn.l.Lock()\n\tdefer n.l.Unlock()\n\tfor ch, _ := range n.notify {\n\t\tselect {\n\t\tcase ch <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n\tn.notify = nil\n}\n\n\nfunc (n *NotifyGroup) Wait(ch chan struct{}) {\n\tn.l.Lock()\n\tdefer n.l.Unlock()\n\tif n.notify == nil {\n\t\tn.notify = make(map[chan struct{}]struct{})\n\t}\n\tn.notify[ch] = struct{}{}\n}\n\n\nfunc (n *NotifyGroup) Clear(ch chan struct{}) {\n\tn.l.Lock()\n\tdefer n.l.Unlock()\n\tif n.notify == nil {\n\t\treturn\n\t}\n\tdelete(n.notify, ch)\n}\n\n\nfunc (n *NotifyGroup) WaitCh() chan struct{} {\n\tch := make(chan struct{}, 1)\n\tn.Wait(ch)\n\treturn ch\n}\n\n\n\n\nfunc (n *NotifyGroup) Empty() bool ", "output": "{\n\tn.l.Lock()\n\tdefer n.l.Unlock()\n\treturn len(n.notify) == 0\n}"} {"input": "package ratecounter\n\nimport \"time\"\n\n\n\ntype RateCounter struct {\n\tcounter Counter\n\tinterval time.Duration\n}\n\n\nfunc NewRateCounter(intrvl time.Duration) *RateCounter {\n\treturn &RateCounter{\n\t\tinterval: intrvl,\n\t}\n}\n\n\n\n\nfunc (r *RateCounter) scheduleDecrement(amount int64) {\n\ttime.Sleep(r.interval)\n\tr.counter.Incr(-1 * amount)\n}\n\n\nfunc (r *RateCounter) Rate() int64 {\n\treturn r.counter.Value()\n}\n\nfunc (r *RateCounter) Incr(val int64) ", "output": "{\n\tr.counter.Incr(val)\n\tgo r.scheduleDecrement(val)\n}"} {"input": "package stree\n\n\n\ntype serial struct {\n\tstree\n}\n\n\nfunc NewSerial() Tree {\n\tt := new(serial)\n\tt.Clear()\n\treturn t\n}\n\nfunc (t *serial) BuildTree() {\n\tpanic(\"BuildTree() not supported for serial data structure\")\n}\n\nfunc (t *serial) Print() {\n\tpanic(\"Print() not supported for serial data structure\")\n}\n\nfunc (t *serial) Tree2Array() []SegmentOverlap {\n\tpanic(\"Tree2Array() not supported for serial data structure\")\n}\n\n\n\n\n\nfunc (t *serial) QueryArray(from, to []int) []Interval {\n\tresult := make([]Interval, 0, 10)\n\tfor i, fromvalue := range from {\n\t\tresult = append(result, t.Query(fromvalue, to[i])...)\n\t}\n\treturn result\n}\n\nfunc (t *serial) Query(from, to int) []Interval ", "output": "{\n\tresult := make([]Interval, 0, 10)\n\tfor _, intrvl := range t.base {\n\t\tif !intrvl.Segment.Disjoint(from, to) {\n\t\t\tresult = append(result, intrvl)\n\t\t}\n\t}\n\treturn result\n}"} {"input": "package fifo\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\n\n\n\n\n\nfunc OpenReader(path string) (io.ReadCloser, error) {\n\treturn os.OpenFile(path, unix.O_RDONLY, os.ModeNamedPipe)\n}\n\n\nfunc OpenWriter(path string) (io.WriteCloser, error) {\n\treturn os.OpenFile(path, unix.O_WRONLY, os.ModeNamedPipe)\n}\n\n\nfunc Remove(path string) error {\n\treturn os.Remove(path)\n}\n\nfunc IsClosedErr(err error) bool {\n\terr2, ok := err.(*os.PathError)\n\tif ok {\n\t\treturn err2.Err == os.ErrClosed\n\t}\n\treturn false\n}\n\nfunc mkfifo(path string, mode uint32) (err error) {\n\treturn unix.Mkfifo(path, mode)\n}\n\nfunc CreateAndRead(path string) (func() (io.ReadCloser, error), error) ", "output": "{\n\tif err := mkfifo(path, 0600); err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating fifo %v: %v\", path, err)\n\t}\n\n\treturn func() (io.ReadCloser, error) {\n\t\treturn OpenReader(path)\n\t}, nil\n}"} {"input": "package sqlbuilder\n\n\ntype DeleteStatement struct {\n\tfrom Table\n\twhere Condition\n\n\terr error\n}\n\n\n\n\n\nfunc (b *DeleteStatement) Where(cond Condition) *DeleteStatement {\n\tif b.err != nil {\n\t\treturn b\n\t}\n\tfor _, col := range cond.columns() {\n\t\tif !b.from.hasColumn(col) {\n\t\t\tb.err = newError(\"column not found in FROM\")\n\t\t\treturn b\n\t\t}\n\t}\n\tb.where = cond\n\treturn b\n}\n\n\nfunc (b *DeleteStatement) ToSql() (query string, args []interface{}, err error) {\n\tbldr := newBuilder()\n\tdefer func() {\n\t\tquery, args, err = bldr.Query(), bldr.Args(), bldr.Err()\n\t}()\n\tif b.err != nil {\n\t\tbldr.SetError(b.err)\n\t\treturn\n\t}\n\n\tbldr.Append(\"DELETE FROM \")\n\tbldr.AppendItem(b.from)\n\n\tif b.where != nil {\n\t\tbldr.Append(\" WHERE \")\n\t\tbldr.AppendItem(b.where)\n\t}\n\treturn\n}\n\nfunc Delete(from Table) *DeleteStatement ", "output": "{\n\tif from == nil {\n\t\treturn &DeleteStatement{\n\t\t\terr: newError(\"from is nil.\"),\n\t\t}\n\t}\n\tif _, ok := from.(*table); !ok {\n\t\treturn &DeleteStatement{\n\t\t\terr: newError(\"CreateTable can use only natural table.\"),\n\t\t}\n\t}\n\treturn &DeleteStatement{\n\t\tfrom: from,\n\t}\n}"} {"input": "package common\n\nimport (\n\t\"io/ioutil\"\n\n\t\"github.com/hyperledger/fabric/cmd/common/comm\"\n\t\"github.com/hyperledger/fabric/cmd/common/signer\"\n\t\"github.com/pkg/errors\"\n\tyaml \"gopkg.in/yaml.v2\"\n)\n\n\ntype Config struct {\n\tVersion int\n\tTLSConfig comm.Config\n\tSignerConfig signer.Config\n}\n\n\n\n\n\nfunc (c Config) ToFile(file string) error {\n\tif err := validateConfig(c); err != nil {\n\t\treturn errors.Wrap(err, \"config isn't valid\")\n\t}\n\tb, _ := yaml.Marshal(c)\n\tif err := ioutil.WriteFile(file, b, 0o600); err != nil {\n\t\treturn errors.Errorf(\"failed writing file %s: %v\", file, err)\n\t}\n\treturn nil\n}\n\nfunc validateConfig(conf Config) error {\n\tnonEmptyStrings := []string{\n\t\tconf.SignerConfig.MSPID,\n\t\tconf.SignerConfig.IdentityPath,\n\t\tconf.SignerConfig.KeyPath,\n\t}\n\n\tfor _, s := range nonEmptyStrings {\n\t\tif s == \"\" {\n\t\t\treturn errors.New(\"empty string that is mandatory\")\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc ConfigFromFile(file string) (Config, error) ", "output": "{\n\tconfigData, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn Config{}, errors.WithStack(err)\n\t}\n\tconfig := Config{}\n\n\tif err := yaml.Unmarshal([]byte(configData), &config); err != nil {\n\t\treturn Config{}, errors.Errorf(\"error unmarshaling YAML file %s: %s\", file, err)\n\t}\n\n\treturn config, validateConfig(config)\n}"} {"input": "package fields\n\nimport (\n\t\"io\"\n\t\"strconv\"\n)\n\ntype IntField struct {\n\t*BaseField\n\tstep int\n\tmin *int\n\tmax *int\n}\n\nfunc (i *IntField) Configure(tagMap map[string]string) error {\n\tstep := 1\n\tif str, ok := tagMap[\"step\"]; ok {\n\t\tvar err error\n\t\tstep64, err := strconv.ParseInt(str, 10, 64)\n\t\tstep = int(step64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif str, ok := tagMap[\"min\"]; ok {\n\t\tmin64, err := strconv.ParseInt(str, 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmin := int(min64)\n\t\ti.min = &min\n\t}\n\tif str, ok := tagMap[\"max\"]; ok {\n\t\tmax64, err := strconv.ParseInt(str, 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmax := int(max64)\n\t\ti.max = &max\n\t}\n\ti.step = step\n\treturn nil\n}\n\nfunc (i *IntField) Render(w io.Writer, val interface{}, err string, startRow bool) {\n\ti.BaseRender(w, numberTemplate, val, err, startRow, map[string]interface{}{\n\t\t\"step\": i.step,\n\t})\n}\n\n\nfunc (i *IntField) Validate(val string) (interface{}, error) ", "output": "{\n\tnum, err := strconv.ParseInt(val, 10, 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn num, nil\n}"} {"input": "package mountinfo\n\nimport \"strings\"\n\n\n\n\n\n\n\n\n\n\n\ntype FilterFunc func(*Info) (skip, stop bool)\n\n\n\n\n\n\n\n\nfunc PrefixFilter(prefix string) FilterFunc {\n\treturn func(m *Info) (bool, bool) {\n\t\tskip := !strings.HasPrefix(m.Mountpoint+\"/\", prefix+\"/\")\n\t\treturn skip, false\n\t}\n}\n\n\n\n\n\n\n\n\n\nfunc ParentsFilter(path string) FilterFunc {\n\treturn func(m *Info) (bool, bool) {\n\t\tskip := !strings.HasPrefix(path, m.Mountpoint)\n\t\treturn skip, false\n\t}\n}\n\n\nfunc FSTypeFilter(fstype ...string) FilterFunc {\n\treturn func(m *Info) (bool, bool) {\n\t\tfor _, t := range fstype {\n\t\t\tif m.FSType == t {\n\t\t\t\treturn false, false \n\t\t\t}\n\t\t}\n\t\treturn true, false \n\t}\n}\n\nfunc SingleEntryFilter(mp string) FilterFunc ", "output": "{\n\treturn func(m *Info) (bool, bool) {\n\t\tif m.Mountpoint == mp {\n\t\t\treturn false, true \n\t\t}\n\t\treturn true, false \n\t}\n}"} {"input": "package routing\n\nimport \"net/http\"\n\n\nfunc Method(method string, handler http.Handler) Matcher {\n\treturn func(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\t\tif req.Method == method {\n\t\t\thandler.ServeHTTP(resp, req)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}\n\n\nfunc GET(handler http.Handler) Matcher {\n\treturn Method(\"GET\", handler)\n}\n\n\nfunc GETFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn GET(http.HandlerFunc(handler))\n}\n\n\nfunc POST(handler http.Handler) Matcher {\n\treturn Method(\"POST\", handler)\n}\n\n\n\n\n\nfunc PUT(handler http.Handler) Matcher {\n\treturn Method(\"PUT\", handler)\n}\n\n\nfunc PUTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PUT(http.HandlerFunc(handler))\n}\n\n\nfunc PATCH(handler http.Handler) Matcher {\n\treturn Method(\"PATCH\", handler)\n}\n\n\nfunc PATCHFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PATCH(http.HandlerFunc(handler))\n}\n\n\nfunc DELETE(handler http.Handler) Matcher {\n\treturn Method(\"DELETE\", handler)\n}\n\n\nfunc DELETEFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn DELETE(http.HandlerFunc(handler))\n}\n\n\n\nfunc MethodNotAllowed(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\tresp.WriteHeader(405)\n\treturn true\n}\n\nfunc POSTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher ", "output": "{\n\treturn POST(http.HandlerFunc(handler))\n}"} {"input": "package resource\n\nimport (\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"github.com/pkg/errors\"\n\t\"io\"\n)\n\n\n\n\n\nfunc Decrypt(key []byte, cryptoText string) (string, error) {\n\tciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(ciphertext) < aes.BlockSize {\n\t\treturn \"\", errors.New(\"Chipher text too short\")\n\t}\n\tiv := ciphertext[:aes.BlockSize]\n\tciphertext = ciphertext[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\n\tstream.XORKeyStream(ciphertext, ciphertext)\n\n\treturn fmt.Sprintf(\"%s\", ciphertext), nil\n}\n\nfunc Encrypt(key []byte, text string) (string, error) ", "output": "{\n\tplaintext := []byte(text)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\n\treturn base64.URLEncoding.EncodeToString(ciphertext), nil\n}"} {"input": "package http\n\nimport (\n\t\"strconv\"\n\n\t\"go-common/app/service/main/archive/api\"\n\t\"go-common/library/ecode\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\nfunc pageList(c *bm.Context) {\n\tvar (\n\t\taid int64\n\t\terr error\n\t\tpages []*api.Page\n\t)\n\taidStr := c.Request.Form.Get(\"aid\")\n\tif aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil || aid <= 0 {\n\t\tc.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\tif pages, err = playSvr.PageList(c, aid); err != nil {\n\t\tc.JSON(nil, err)\n\t\treturn\n\t}\n\tif len(pages) == 0 {\n\t\tc.JSON(nil, ecode.NothingFound)\n\t\treturn\n\t}\n\tc.JSON(pages, nil)\n}\n\nfunc videoShot(c *bm.Context) {\n\tv := new(struct {\n\t\tAid int64 `form:\"aid\" validate:\"min=1\"`\n\t\tCid int64 `form:\"cid\"`\n\t\tIndex bool `form:\"index\"`\n\t})\n\tif err := c.Bind(v); err != nil {\n\t\treturn\n\t}\n\tc.JSON(playSvr.VideoShot(c, v.Aid, v.Cid, v.Index))\n}\n\n\n\nfunc playURLToken(c *bm.Context) ", "output": "{\n\tvar (\n\t\taid, cid, mid int64\n\t\terr error\n\t)\n\tparams := c.Request.Form\n\taidStr := params.Get(\"aid\")\n\tif aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil {\n\t\tc.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\tcid, _ = strconv.ParseInt(params.Get(\"cid\"), 10, 64)\n\tmidStr, _ := c.Get(\"mid\")\n\tmid = midStr.(int64)\n\tc.JSON(playSvr.PlayURLToken(c, mid, aid, cid))\n}"} {"input": "package structs\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nconst (\n\tDefaultUnpriviledgedUser = \"nobody\"\n\n\tCheckBufSize = 4 * 1024\n)\n\n\ntype WaitResult struct {\n\tExitCode int\n\tSignal int\n\tErr error\n}\n\nfunc NewWaitResult(code, signal int, err error) *WaitResult {\n\treturn &WaitResult{\n\t\tExitCode: code,\n\t\tSignal: signal,\n\t\tErr: err,\n\t}\n}\n\nfunc (r *WaitResult) Successful() bool {\n\treturn r.ExitCode == 0 && r.Signal == 0 && r.Err == nil\n}\n\n\n\n\n\ntype RecoverableError struct {\n\tErr error\n\tRecoverable bool\n}\n\n\n\nfunc NewRecoverableError(e error, recoverable bool) *RecoverableError {\n\treturn &RecoverableError{\n\t\tErr: e,\n\t\tRecoverable: recoverable,\n\t}\n}\n\nfunc (r *RecoverableError) Error() string {\n\treturn r.Err.Error()\n}\n\n\ntype CheckResult struct {\n\n\tExitCode int\n\n\tOutput string\n\n\tTimestamp time.Time\n\n\tDuration time.Duration\n\n\tErr error\n}\n\nfunc (r *WaitResult) String() string ", "output": "{\n\treturn fmt.Sprintf(\"Wait returned exit code %v, signal %v, and error %v\",\n\t\tr.ExitCode, r.Signal, r.Err)\n}"} {"input": "package client\n\nimport (\n\trestclient \"k8s.io/client-go/rest\"\n\tkapi \"k8s.io/kubernetes/pkg/api\"\n\n\tdeployapi \"github.com/openshift/origin/pkg/apps/apis/apps\"\n)\n\n\ntype DeploymentLogsNamespacer interface {\n\tDeploymentLogs(namespace string) DeploymentLogInterface\n}\n\n\ntype DeploymentLogInterface interface {\n\tGet(name string, opts deployapi.DeploymentLogOptions) *restclient.Request\n}\n\n\ntype deploymentLogs struct {\n\tr *Client\n\tns string\n}\n\n\n\n\n\nfunc (c *deploymentLogs) Get(name string, opts deployapi.DeploymentLogOptions) *restclient.Request {\n\treturn c.r.Get().Namespace(c.ns).Resource(\"deploymentConfigs\").Name(name).SubResource(\"log\").VersionedParams(&opts, kapi.ParameterCodec)\n}\n\nfunc newDeploymentLogs(c *Client, namespace string) *deploymentLogs ", "output": "{\n\treturn &deploymentLogs{\n\t\tr: c,\n\t\tns: namespace,\n\t}\n}"} {"input": "package controller\n\nimport (\n\t\"github.com/tmacychen/UFG/framework\"\n\t\"github.com/tmacychen/UFG/framework/outer\"\n)\n\ntype AttachableOuter interface {\n\touter.Relayouter\n}\n\ntype Attachable struct {\n\touter AttachableOuter\n\tonAttach framework.Event\n\tonDetach framework.Event\n\tattached bool\n}\n\nfunc (a *Attachable) Init(outer AttachableOuter) {\n\ta.outer = outer\n}\n\nfunc (a *Attachable) Attached() bool {\n\treturn a.attached\n}\n\nfunc (a *Attachable) Attach() {\n\tif a.attached {\n\t\tpanic(\"Control already attached\")\n\t}\n\ta.attached = true\n\tif a.onAttach != nil {\n\t\ta.onAttach.Fire()\n\t}\n}\n\nfunc (a *Attachable) Detach() {\n\tif !a.attached {\n\t\tpanic(\"Control already detached\")\n\t}\n\ta.attached = false\n\tif a.onDetach != nil {\n\t\ta.onDetach.Fire()\n\t}\n}\n\nfunc (a *Attachable) OnAttach(f func()) framework.EventSubscription {\n\tif a.onAttach == nil {\n\t\ta.onAttach = CreateEvent(func() {})\n\t}\n\treturn a.onAttach.Listen(f)\n}\n\n\n\nfunc (a *Attachable) OnDetach(f func()) framework.EventSubscription ", "output": "{\n\tif a.onDetach == nil {\n\t\ta.onDetach = CreateEvent(func() {})\n\t}\n\treturn a.onDetach.Listen(f)\n}"} {"input": "package core\n\nimport (\n\tabci \"github.com/tendermint/abci/types\"\n\tdata \"github.com/tendermint/go-wire/data\"\n\tctypes \"github.com/tendermint/tendermint/rpc/core/types\"\n)\n\n\n\n\n\nfunc ABCIInfo() (*ctypes.ResultABCIInfo, error) {\n\tresInfo, err := proxyAppQuery.InfoSync()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ctypes.ResultABCIInfo{resInfo}, nil\n}\n\nfunc ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuery, error) ", "output": "{\n\tresQuery, err := proxyAppQuery.QuerySync(abci.RequestQuery{\n\t\tPath: path,\n\t\tData: data,\n\t\tProve: prove,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogger.Info(\"ABCIQuery\", \"path\", path, \"data\", data, \"result\", resQuery)\n\treturn &ctypes.ResultABCIQuery{\n\t\tresQuery.Result(),\n\t}, nil\n}"} {"input": "package sardata\n\nimport (\n\t\"io\"\n\n\t\"github.com/luci/luci-go/common/errors\"\n)\n\n\nconst Magic = \"SAR\"\n\n\nconst Version byte = 1\n\nvar magicVer []byte\n\n\n\n\nfunc WriteMagic(w io.Writer) error {\n\t_, err := w.Write(magicVer)\n\treturn err\n}\n\n\n\nfunc ReadMagic(r io.Reader) (version byte, err error) {\n\tbuf := make([]byte, 4)\n\tif _, err = io.ReadFull(r, buf); err != nil {\n\t\treturn\n\t}\n\n\tsBuf := string(buf[:3])\n\tif Magic != sBuf {\n\t\terr = errors.Reason(\"bad magic: %(magic)q\").D(\"magic\", sBuf).Err()\n\t\treturn\n\t}\n\n\tversion = buf[3]\n\tif version > Version {\n\t\terr = errors.Reason(\"bad version: %(ver)d > %(ours)d\").\n\t\t\tD(\"ver\", version).D(\"ours\", Version).Err()\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc init() ", "output": "{\n\tmagicVer = []byte(Magic + string(Version))\n}"} {"input": "package nogo\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype mapBackedRoleRepository struct {\n\troleMap map[string]Role\n}\n\nfunc NewMapBackedRoleRepository() RoleRepository {\n\treturn &mapBackedRoleRepository{roleMap: make(map[string]Role)}\n}\n\nfunc (this *mapBackedRoleRepository) FindAll() ([]Role, error) {\n\tret := make([]Role, 0)\n\tfor _, role := range this.roleMap {\n\t\tret = append(ret, role)\n\t}\n\treturn ret, nil\n}\n\nfunc (this *mapBackedRoleRepository) FindRole(roleName string) (Role, error) {\n\tif role, ok := this.roleMap[roleName]; ok {\n\t\treturn role, nil\n\t}\n\treturn nil, errors.New(fmt.Sprintf(\"Could not find role %v\", roleName))\n}\n\nfunc (this *mapBackedRoleRepository) CreateRole(role Role) error {\n\tif _, ok := this.roleMap[role.GetName()]; ok {\n\t\treturn errors.New(fmt.Sprintf(\"Error creating role. Role %v already exists\", role.GetName()))\n\t}\n\tthis.roleMap[role.GetName()] = role\n\treturn nil\n}\n\n\n\nfunc (this *mapBackedRoleRepository) DeleteRole(roleName string) error {\n\tif _, ok := this.roleMap[roleName]; ok {\n\t\tdelete(this.roleMap, roleName)\n\t}\n\treturn errors.New(fmt.Sprintf(\"Error deleting role. Role %v does not exist.\", roleName))\n}\n\nfunc (this *mapBackedRoleRepository) UpdateRole(role Role) error ", "output": "{\n\tif _, ok := this.roleMap[role.GetName()]; ok {\n\t\tthis.roleMap[role.GetName()] = role\n\t\treturn nil\n\t}\n\treturn errors.New(fmt.Sprintf(\"Error updating role. Role %v does not exist.\", role.GetName()))\n}"} {"input": "package google\n\nimport (\n\t\"google.golang.org/api/cloudkms/v1\"\n\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema\"\n\t\"log\"\n)\n\n\n\nfunc dataSourceGoogleKmsSecretRead(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\tuserAgent, err := generateUserAgentString(d, config.userAgent)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcryptoKeyId, err := parseKmsCryptoKeyId(d.Get(\"crypto_key\").(string), config)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tciphertext := d.Get(\"ciphertext\").(string)\n\n\tkmsDecryptRequest := &cloudkms.DecryptRequest{\n\t\tCiphertext: ciphertext,\n\t}\n\n\tif aad, ok := d.GetOk(\"additional_authenticated_data\"); ok {\n\t\tkmsDecryptRequest.AdditionalAuthenticatedData = aad.(string)\n\t}\n\n\tdecryptResponse, err := config.NewKmsClient(userAgent).Projects.Locations.KeyRings.CryptoKeys.Decrypt(cryptoKeyId.cryptoKeyId(), kmsDecryptRequest).Do()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error decrypting ciphertext: %s\", err)\n\t}\n\n\tplaintext, err := base64.StdEncoding.DecodeString(decryptResponse.Plaintext)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error decoding base64 response: %s\", err)\n\t}\n\n\tlog.Printf(\"[INFO] Successfully decrypted ciphertext: %s\", ciphertext)\n\n\tif err := d.Set(\"plaintext\", string(plaintext[:])); err != nil {\n\t\treturn fmt.Errorf(\"Error setting plaintext: %s\", err)\n\t}\n\td.SetId(fmt.Sprintf(\"%s:%s\", d.Get(\"crypto_key\").(string), ciphertext))\n\n\treturn nil\n}\n\nfunc dataSourceGoogleKmsSecret() *schema.Resource ", "output": "{\n\treturn &schema.Resource{\n\t\tRead: dataSourceGoogleKmsSecretRead,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"crypto_key\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t\t\"ciphertext\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t\t\"plaintext\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t\tSensitive: true,\n\t\t\t},\n\t\t\t\"additional_authenticated_data\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package tools\n\nimport (\n\t\"github.com/chanxuehong/wechat.v2/mch/core\"\n\t\"github.com/chanxuehong/wechat.v2/util\"\n)\n\n\nfunc AuthCodeToOpenId(clt *core.Client, req map[string]string) (resp map[string]string, err error) {\n\treturn clt.PostXML(core.APIBaseURL()+\"/tools/authcodetoopenid\", req)\n}\n\ntype AuthCodeToOpenIdRequest struct {\n\tXMLName struct{} `xml:\"xml\" json:\"-\"`\n\n\tAuthCode string `xml:\"auth_code\"` \n\n\tNonceStr string `xml:\"nonce_str\"` \n\tSignType string `xml:\"sign_type\"` \n}\n\ntype AuthCodeToOpenIdResponse struct {\n\tXMLName struct{} `xml:\"xml\" json:\"-\"`\n\n\tOpenId string `xml:\"openid\"` \n\n\tSubOpenId string `xml:\"sub_openid\"` \n}\n\n\n\n\nfunc AuthCodeToOpenId2(clt *core.Client, req *AuthCodeToOpenIdRequest) (resp *AuthCodeToOpenIdResponse, err error) ", "output": "{\n\tm1 := make(map[string]string, 8)\n\tm1[\"auth_code\"] = req.AuthCode\n\tif req.NonceStr != \"\" {\n\t\tm1[\"nonce_str\"] = req.NonceStr\n\t} else {\n\t\tm1[\"nonce_str\"] = util.NonceStr()\n\t}\n\tif req.SignType != \"\" {\n\t\tm1[\"sign_type\"] = req.SignType\n\t}\n\n\tm2, err := AuthCodeToOpenId(clt, m1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp = &AuthCodeToOpenIdResponse{\n\t\tOpenId: m2[\"openid\"],\n\t\tSubOpenId: m2[\"sub_openid\"],\n\t}\n\treturn resp, nil\n}"} {"input": "package thread\n\nimport \"time\"\n\ntype ThreadStatistic struct {\n\tThreadId int `json:\"thread_id\"`\n\tProcessedLines int `json:\"processed_lines\"`\n\tStartTime time.Time `json:\"start_time\"`\n\tEndTime time.Time `json:\"end_time\"`\n\tDeltaTime time.Duration `json:\"delta_time\"`\n}\n\nfunc NewThreadStadistic(threadId int) *ThreadStatistic {\n\tvar ts ThreadStatistic\n\n\tts.ThreadId = threadId\n\tts.ProcessedLines = 0\n\tts.StartTime = time.Now()\n\n\treturn &ts\n}\n\nfunc (ts *ThreadStatistic) IncreaseProcessedLines() {\n\tts.ProcessedLines += 1\n}\n\n\n\nfunc (ts *ThreadStatistic) SetEndTime() ", "output": "{\n\tts.EndTime = time.Now()\n\tts.DeltaTime = ts.EndTime.Sub(ts.StartTime) / time.Millisecond\n}"} {"input": "package sync2\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestSemaTimeout(t *testing.T) {\n\ts := NewSemaphore(1)\n\ts.Acquire()\n\tgo func() {\n\t\ttime.Sleep(10 * time.Millisecond)\n\t\ts.Release()\n\t}()\n\tif ok := s.AcquireTimeout(5 * time.Millisecond); ok {\n\t\tt.Errorf(\"want false, got true\")\n\t}\n\ttime.Sleep(10 * time.Millisecond)\n\tif ok := s.AcquireTimeout(5 * time.Millisecond); !ok {\n\t\tt.Errorf(\"want true, got false\")\n\t}\n}\n\nfunc TestSemaNoTimeout(t *testing.T) ", "output": "{\n\ts := NewSemaphore(1)\n\ts.Acquire()\n\treleased := false\n\tgo func() {\n\t\ttime.Sleep(10 * time.Millisecond)\n\t\treleased = true\n\t\ts.Release()\n\t}()\n\ts.Acquire()\n\tif !released {\n\t\tt.Errorf(\"want true, got false\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"math/rand\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/aws/amazon-ecs-agent/agent/app\"\n\t\"github.com/aws/amazon-ecs-agent/agent/logger\"\n)\n\n\n\nfunc main() {\n\tlogger.InitSeelog()\n\tos.Exit(app.Run(os.Args[1:]))\n}\n\nfunc init() ", "output": "{\n\trand.Seed(time.Now().UnixNano())\n}"} {"input": "package gin\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\nconst GIN_MODE = \"GIN_MODE\"\n\nconst (\n\tDebugMode string = \"debug\"\n\tReleaseMode string = \"release\"\n\tTestMode string = \"test\"\n)\nconst (\n\tdebugCode = iota\n\treleaseCode = iota\n\ttestCode = iota\n)\n\nvar gin_mode int = debugCode\nvar mode_name string = DebugMode\n\nfunc init() {\n\tvalue := os.Getenv(GIN_MODE)\n\tif len(value) == 0 {\n\t\tSetMode(DebugMode)\n\t} else {\n\t\tSetMode(value)\n\t}\n}\n\nfunc SetMode(value string) {\n\tswitch value {\n\tcase DebugMode:\n\t\tgin_mode = debugCode\n\tcase ReleaseMode:\n\t\tgin_mode = releaseCode\n\tcase TestMode:\n\t\tgin_mode = testCode\n\tdefault:\n\t\tlog.Panic(\"gin mode unknown: \" + value)\n\t}\n\tmode_name = value\n}\n\n\n\nfunc Mode() string ", "output": "{\n\treturn mode_name\n}"} {"input": "package master\n\nimport ()\n\n\n\ntype frame struct {\n\tjob *job\n\tslaveName string\n\tframe int\n\tdata []byte\n\tprogress byte\n\tcompleted bool\n}\n\n\n\nfunc NewFrame(job *job, fr int) *frame {\n\treturn &frame{\n\t\tjob: job,\n\t\tslaveName: \"\",\n\t\tframe: fr,\n\t\tdata: nil,\n\t\tprogress: 0,\n\t\tcompleted: false,\n\t}\n}\n\n\n\nfunc (f *frame) Job() *job {\n\treturn f.job\n}\n\nfunc (f *frame) SlaveName() string {\n\treturn f.slaveName\n}\n\nfunc (f *frame) Frame() int {\n\treturn f.frame\n}\n\nfunc (f *frame) AlignedFrame() int {\n\treturn f.frame + f.Job().Start()\n}\n\nfunc (f *frame) Data() []byte {\n\treturn f.data\n}\n\nfunc (f *frame) Progress() byte {\n\treturn f.progress\n}\n\nfunc (f *frame) Completed() bool {\n\treturn f.completed\n}\n\nfunc (f *frame) File() []byte {\n\treturn f.Job().File()\n}\n\n\n\nfunc (f *frame) SetSlaveName(slaveName string) {\n\tf.slaveName = slaveName\n}\n\nfunc (f *frame) SetData(data []byte) {\n\tf.data = data\n}\n\n\n\nfunc (f *frame) SetCompleted(completed bool) {\n\tf.completed = completed\n\tif completed {\n\t\tf.SetProgress(100)\n\t}\n}\n\n\n\nfunc (f *frame) Reset() {\n\tf.SetSlaveName(\"\")\n\tf.SetData(nil)\n\tf.SetProgress(0)\n\tf.SetCompleted(false)\n}\n\nfunc (f *frame) SetProgress(progress byte) ", "output": "{\n\tf.progress = progress\n}"} {"input": "package models\n\nimport (\n\t\"github.com/go-gorp/gorp\"\n\t\"github.com/skarllot/flogviewer/common\"\n)\n\ntype Host struct {\n\tId int64 `db:\"id\"`\n\tName string `db:\"name\"`\n\tCategoryId *int64 `db:\"category\"`\n\n\tCategory *Category `db:\"-\"`\n}\n\nfunc DefineHostTable(dbm *gorp.DbMap) {\n\tt := dbm.AddTableWithName(Host{}, \"host\")\n\tt.SetKeys(true, \"id\")\n\tt.ColMap(\"name\").\n\t\tSetUnique(true).\n\t\tSetNotNull(true)\n}\n\nfunc (self *Host) PreInsert(gorp.SqlExecutor) error {\n\tif self.Category != nil {\n\t\tself.CategoryId = common.NInt64(self.Category.Id)\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (self *Host) PostGet(exe gorp.SqlExecutor) error {\n\tif self.CategoryId != nil {\n\t\tobj, err := exe.Get(Category{}, *self.CategoryId)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tself.Category = obj.(*Category)\n\t}\n\treturn nil\n}\n\nfunc (self *Host) PreUpdate(exe gorp.SqlExecutor) error ", "output": "{\n\treturn self.PreInsert(exe)\n}"} {"input": "package iso20022\n\n\ntype PaymentInstrument21Choice struct {\n\n\tCreditTransferDetails *CreditTransfer8 `xml:\"CdtTrfDtls\"`\n\n\tChequeDetails *Cheque9 `xml:\"ChqDtls\"`\n\n\tBankersDraftDetails *Cheque9 `xml:\"BkrsDrftDtls\"`\n\n\tCashAccountDetails *InvestmentAccount60 `xml:\"CshAcctDtls\"`\n}\n\nfunc (p *PaymentInstrument21Choice) AddCreditTransferDetails() *CreditTransfer8 {\n\tp.CreditTransferDetails = new(CreditTransfer8)\n\treturn p.CreditTransferDetails\n}\n\nfunc (p *PaymentInstrument21Choice) AddChequeDetails() *Cheque9 {\n\tp.ChequeDetails = new(Cheque9)\n\treturn p.ChequeDetails\n}\n\nfunc (p *PaymentInstrument21Choice) AddBankersDraftDetails() *Cheque9 {\n\tp.BankersDraftDetails = new(Cheque9)\n\treturn p.BankersDraftDetails\n}\n\n\n\nfunc (p *PaymentInstrument21Choice) AddCashAccountDetails() *InvestmentAccount60 ", "output": "{\n\tp.CashAccountDetails = new(InvestmentAccount60)\n\treturn p.CashAccountDetails\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/mysza/go-service-template/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert\"\n\t\"os\"\n)\n\nfunc BuildConvertCommand() *Command {\n\treturn &Command{\n\t\tName: \"convert\",\n\t\tFlagSet: flag.NewFlagSet(\"convert\", flag.ExitOnError),\n\t\tUsageCommand: \"ginkgo convert /path/to/package\",\n\t\tUsage: []string{\n\t\t\t\"Convert the package at the passed in path from an XUnit-style test to a Ginkgo-style test\",\n\t\t},\n\t\tCommand: convertPackage,\n\t}\n}\n\n\n\nfunc convertPackage(args []string, additionalArgs []string) ", "output": "{\n\tif len(args) != 1 {\n\t\tprintln(fmt.Sprintf(\"usage: ginkgo convert /path/to/your/package\"))\n\t\tos.Exit(1)\n\t}\n\n\tdefer func() {\n\t\terr := recover()\n\t\tif err != nil {\n\t\t\tswitch err := err.(type) {\n\t\t\tcase error:\n\t\t\t\tprintln(err.Error())\n\t\t\tcase string:\n\t\t\t\tprintln(err)\n\t\t\tdefault:\n\t\t\t\tprintln(fmt.Sprintf(\"unexpected error: %#v\", err))\n\t\t\t}\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\tconvert.RewritePackage(args[0])\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n\n\t\"github.com/boltdb/bolt\"\n)\n\nfunc MemoryLocalStore() LocalStore {\n\treturn make(memoryLocalStore)\n}\n\ntype memoryLocalStore map[string]json.RawMessage\n\nfunc (m memoryLocalStore) GetMeta() (map[string]json.RawMessage, error) {\n\treturn m, nil\n}\n\nfunc (m memoryLocalStore) SetMeta(name string, meta json.RawMessage) error {\n\tm[name] = meta\n\treturn nil\n}\n\nconst dbBucket = \"tuf-client\"\n\nfunc FileLocalStore(path string) (LocalStore, error) {\n\tdb, err := bolt.Open(path, 0600, &bolt.Options{Timeout: time.Second})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := db.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucketIfNotExists([]byte(dbBucket))\n\t\treturn err\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &fileLocalStore{db: db}, nil\n}\n\ntype fileLocalStore struct {\n\tdb *bolt.DB\n}\n\nfunc (f *fileLocalStore) GetMeta() (map[string]json.RawMessage, error) {\n\tmeta := make(map[string]json.RawMessage)\n\tif err := f.db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(dbBucket))\n\t\tb.ForEach(func(k, v []byte) error {\n\t\t\tvcopy := make([]byte, len(v))\n\t\t\tcopy(vcopy, v)\n\t\t\tmeta[string(k)] = vcopy\n\t\t\treturn nil\n\t\t})\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn meta, nil\n}\n\n\n\nfunc (f *fileLocalStore) SetMeta(name string, meta json.RawMessage) error ", "output": "{\n\treturn f.db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(dbBucket))\n\t\treturn b.Put([]byte(name), meta)\n\t})\n}"} {"input": "package main\n\nfunc reverse(n int) int {\n\tr := 0\n\tfor n > 0 {\n\t\tr = 10*r + n%10\n\t\tn /= 10\n\t}\n\treturn r\n}\n\n\n\nfunc p4() int {\n\tvar lp, a, b, db int\n\tlp, a = 0, 999\n\tfor a >= 100 {\n\t\tif a%11 == 0 {\n\t\t\tb, db = 999, 1\n\t\t} else {\n\t\t\tb, db = 990, 11\n\t\t}\n\t\tfor b >= a {\n\t\t\tif a*b <= lp {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif isPalindrome(a * b) {\n\t\t\t\tlp = a * b\n\t\t\t}\n\t\t\tb = b - db\n\t\t}\n\t\ta--\n\t}\n\treturn lp\n}\n\nfunc isPalindrome(n int) bool ", "output": "{\n\treturn n == reverse(n)\n}"} {"input": "package subnets\n\nimport \"net\"\n\n\n\nfunc overlaps(a *net.IPNet, b *net.IPNet) bool {\n\treturn a.Contains(b.IP) || b.Contains(a.IP)\n}\n\nfunc next(ip net.IP) net.IP {\n\tnext := clone(ip)\n\tfor i := len(next) - 1; i >= 0; i-- {\n\t\tnext[i]++\n\t\tif next[i] != 0 {\n\t\t\treturn next\n\t\t}\n\t}\n\n\tpanic(\"overflowed maximum IP\")\n}\n\nfunc clone(ip net.IP) net.IP {\n\tclone := make([]byte, len(ip))\n\tcopy(clone, ip)\n\treturn clone\n}\n\nfunc max(ipn *net.IPNet) net.IP {\n\tmask := ipn.Mask\n\tmin := clone(ipn.IP)\n\n\tif len(mask) != len(min) {\n\t\tpanic(\"length of mask is not compatible with length of network IP\")\n\t}\n\n\tmax := make([]byte, len(min))\n\tfor i, b := range mask {\n\t\tmax[i] = min[i] | ^b\n\t}\n\n\treturn net.IP(max).To16()\n}\n\nfunc equals(a *net.IPNet, b *net.IPNet) bool ", "output": "{\n\taOnes, aBits := a.Mask.Size()\n\tbOnes, bBits := b.Mask.Size()\n\treturn a.IP.Equal(b.IP) && (aOnes == bOnes) && (aBits == bBits)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sync\"\n)\n\n\n\n\n\ntype Stage interface {\n\tInit()\n\tRun(*FileRecord) error\n\tClose()\n}\n\n\n\n\n\n\n\n\n\ntype Pipeline struct {\n\tinput chan *FileRecord\n\toutput chan *FileRecord\n\tlog chan *FileRecord\n\tlogWg sync.WaitGroup\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *Pipeline) Add(NewStage func() Stage, routineCount int) {\n\tif routineCount <= 0 {\n\t\treturn\n\t}\n\tvar wg sync.WaitGroup\n\n\tout := make(chan *FileRecord, routineCount)\n\n\twg.Add(routineCount)\n\tfor i := 0; i < routineCount; i++ {\n\t\tgo func(input <-chan *FileRecord) {\n\t\t\ts := NewStage()\n\t\t\ts.Init()\n\t\t\tfor fr := range input {\n\t\t\t\terr := s.Run(fr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tp.log <- fr\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tout <- fr\n\t\t\t}\n\t\t\ts.Close()\n\t\t\twg.Done()\n\t\t}(p.output)\n\t}\n\n\tp.output = out\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(out)\n\t}()\n}\n\n\n\nfunc (p *Pipeline) Close() {\n\tclose(p.log)\n\tp.logWg.Wait()\n}\n\nfunc NewPipeline(inputQueueSize, logQueueSize int) *Pipeline ", "output": "{\n\tvar p Pipeline\n\tp.input = make(chan *FileRecord, inputQueueSize)\n\tp.output = p.input\n\tp.log = make(chan *FileRecord, logQueueSize)\n\n\tp.logWg.Add(1)\n\tgo func() {\n\t\tfor fr := range p.log {\n\t\t\tfmt.Fprint(os.Stderr, fr)\n\t\t}\n\t\tp.logWg.Done()\n\t}()\n\n\treturn &p\n}"} {"input": "package layers\n\nimport (\n\t\"math\"\n\n\t\"github.com/gerardabello/weight\"\n\t\"github.com/gerardabello/weight/tensor\"\n)\n\ntype SigmoidLayer struct {\n\tBaseLayer\n}\n\nfunc NewSigmoidLayer(size ...int) *SigmoidLayer {\n\tlayer := &SigmoidLayer{}\n\tlayer.BaseLayer.Init(size, size)\n\treturn layer\n}\n\nfunc (l *SigmoidLayer) CreateSlave() weight.Layer {\n\tnl := NewSigmoidLayer(l.GetInputSize()...)\n\tnl.id = l.ID()\n\n\treturn nl\n}\n\nfunc (l *SigmoidLayer) Activate(input *tensor.Tensor) (*tensor.Tensor, error) {\n\tl.mutex.Lock()\n\terr := l.BaseLayer.Activate(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinputs := input.Values\n\n\tfor i := range l.output.Values {\n\t\tl.output.Values[i] = 1 / (1 + math.Exp(-inputs[i]))\n\t}\n\n\tl.mutex.Unlock()\n\treturn &l.output, nil\n}\n\n\n\nfunc (l *SigmoidLayer) BackPropagate(err *tensor.Tensor) (*tensor.Tensor, error) ", "output": "{\n\tl.mutex.Lock()\n\te := l.BaseLayer.BackPropagate(err)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\n\terrs := err.Values\n\tinputs := l.lastInput.Values\n\n\tfor i := range l.propagation.Values {\n\t\tl.propagation.Values[i] = math.Exp(-inputs[i]) / math.Pow(1+math.Exp(-inputs[i]), 2) * errs[i]\n\t}\n\n\tl.mutex.Unlock()\n\treturn &l.propagation, nil\n}"} {"input": "package minus\n\nimport (\n \"RETIA/unit\"\n \"RETIA/messages\"\n)\n\n\nfunc Create(lrelation, rrelation *unit.Relation) *unit.MinusStatement {\n if lrelation != nil && rrelation != nil && relationsTypeMatches(lrelation, rrelation) {\n statement := new(unit.MinusStatement)\n\n statement.Lrelation = lrelation\n statement.Rrelation = rrelation\n\n return statement\n } else {\n return nil\n }\n}\n\n\nfunc Eval(statement *unit.MinusStatement) *unit.Relation {\n if statement != nil {\n relation := new(unit.Relation)\n\n relation.Tname = statement.Lrelation.Tname\n\n for _, l_tuple := range statement.Lrelation.Tuples {\n present := false\n\n for _, r_tuple := range statement.Rrelation.Tuples {\n if l_tuple.Hash == r_tuple.Hash {\n present = true\n break\n }\n }\n\n if !present {\n relation.Tuples = append(relation.Tuples, l_tuple)\n }\n }\n\n return relation\n } else {\n return nil\n }\n}\n\n\n\n\nfunc relationsTypeMatches(lrelation, rrelation *unit.Relation) bool ", "output": "{\n if lrelation.Tname == rrelation.Tname {\n return true\n } else {\n messages.TypesMismatch()\n return true\n }\n}"} {"input": "package commands\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\tcmds \"gx/ipfs/QmSXUokcP4TJpFfqozT69AVAYRtzXVMUjzQVkYX41R9Svs/go-ipfs-cmds\"\n)\n\n\n\nfunc TestHelptexts(t *testing.T) {\n\tt.Skip(\"sill isn't 100%\")\n\tRoot.ProcessHelp()\n\tcheckHelptextRecursive(t, []string{\"ipfs\"}, Root)\n}\n\nfunc checkHelptextRecursive(t *testing.T, name []string, c *cmds.Command) ", "output": "{\n\tif c.Helptext.Tagline == \"\" {\n\t\tt.Errorf(\"%s has no tagline!\", strings.Join(name, \" \"))\n\t}\n\n\tif c.Helptext.LongDescription == \"\" {\n\t\tt.Errorf(\"%s has no long description!\", strings.Join(name, \" \"))\n\t}\n\n\tif c.Helptext.ShortDescription == \"\" {\n\t\tt.Errorf(\"%s has no short description!\", strings.Join(name, \" \"))\n\t}\n\n\tif c.Helptext.Synopsis == \"\" {\n\t\tt.Errorf(\"%s has no synopsis!\", strings.Join(name, \" \"))\n\t}\n\n\tfor subname, sub := range c.Subcommands {\n\t\tcheckHelptextRecursive(t, append(name, subname), sub)\n\t}\n}"} {"input": "package gftest\n\nimport (\n \"errors\"\n \"reflect\"\n \"encoding/json\"\n)\n\nfunc (req *Request) Debug(msg string) { req.t.Log(req.FullPath() + \": %v\", msg) }\n\n\n\nfunc (req *Request) Error(e error) { req.t.Log(e.Error()) }\n\nfunc (req *Request) Reflect(e interface{}) {\n\tmsg := \"REFLECT VALUE IS NIL\"\n\tif e != nil {\n\t\tmsg = \"REFLECT VALUE IS \"+reflect.TypeOf(e).String()\n\t}\n\treq.NewError(msg)\n}\n\nfunc (req *Request) DebugJSON(i interface{}) {\n\tb, err := json.Marshal(i); if err != nil { req.Error(err); return }\n\treq.Debug(string(b))\n}\n\nfunc (req *Request) NewError(msg string) error ", "output": "{\n\n\terr := errors.New(req.FullPath() + \": \" + msg)\n\treturn err\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nvar (\n\tsrv *httptest.Server\n)\n\nfunc mockHandler(w http.ResponseWriter, r *http.Request) {\n}\n\nfunc setupServer() {\n\trouter := Router{mux.NewRouter()}\n\tm := RouteMap{\n\t\t\"GET\": {\n\t\t\t\"/it\": mockHandler,\n\t\t},\n\t}\n\n\trouter.AddRoutes(\"/test\", m)\n\trouter.AddCorsRoutes(\"/cors\", m)\n\tsrv = httptest.NewServer(router)\n}\n\n\n\nfunc TestRoute(t *testing.T) {\n\tsetupServer()\n\tdefer teardownServer()\n\n\tpath := srv.URL + \"/test/it\"\n\tresp, err := http.DefaultClient.Get(path)\n\n\tassert.Nil(t, err)\n\tassert.Equal(t, 200, resp.StatusCode)\n}\n\nfunc TestCorsRoute(t *testing.T) {\n\tsetupServer()\n\tdefer teardownServer()\n\n\tpath := srv.URL + \"/cors/it\"\n\n\treq, _ := http.NewRequest(\"GET\", path, nil)\n\treq.Header.Add(\"Origin\", srv.URL)\n\tresp, err := http.DefaultClient.Do(req)\n\n\tassert.Nil(t, err)\n\tassert.Equal(t, 200, resp.StatusCode)\n\tassert.Equal(t, srv.URL, resp.Header.Get(\"Access-Control-Allow-Origin\"), \"CORS Allow-Origin not set\")\n}\n\nfunc teardownServer() ", "output": "{\n\tsrv.Close()\n}"} {"input": "package admin\n\nimport (\n\t\"github.com/astaxie/beego\"\n\t\"os\"\n\t\"runtime\"\n)\n\ntype IndexController struct {\n\tbaseController\n}\n\n\n\nfunc (this *IndexController) Info() {\n\tthis.Redirect(\"/admin/main\", 302)\n}\n\nfunc (this *IndexController) Main() ", "output": "{\n\tthis.Data[\"hostname\"], _ = os.Hostname()\n\tthis.Data[\"goversion\"] = runtime.Version()\n\tthis.Data[\"os\"] = runtime.GOOS\n\tthis.Data[\"cpunum\"] = runtime.NumCPU()\n\tthis.Data[\"arch\"] = runtime.GOARCH\n\tthis.Data[\"beegoversion\"] = beego.VERSION\n\tthis.Data[\"version\"] = beego.AppConfig.String(\"version\")\n\tthis.TplNames = \"admin/main.tpl\"\n\tthis.Layout = \"admin/layout.tpl\"\n\tthis.LayoutSections = make(map[string]string)\n\tthis.LayoutSections[\"Sidebar\"] = \"admin/layout_sidebar.tpl\"\n}"} {"input": "package openstack\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gophercloud/gophercloud\"\n\ttokens2 \"github.com/gophercloud/gophercloud/openstack/identity/v2/tokens\"\n\ttokens3 \"github.com/gophercloud/gophercloud/openstack/identity/v3/tokens\"\n)\n\n\n\ntype ErrEndpointNotFound struct{ gophercloud.BaseError }\n\nfunc (e ErrEndpointNotFound) Error() string {\n\treturn \"No suitable endpoint could be found in the service catalog.\"\n}\n\n\n\ntype ErrInvalidAvailabilityProvided struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrInvalidAvailabilityProvided) Error() string {\n\treturn fmt.Sprintf(\"Unexpected availability in endpoint query: %s\", e.Value)\n}\n\n\n\ntype ErrMultipleMatchingEndpointsV2 struct {\n\tgophercloud.BaseError\n\tEndpoints []tokens2.Endpoint\n}\n\nfunc (e ErrMultipleMatchingEndpointsV2) Error() string {\n\treturn fmt.Sprintf(\"Discovered %d matching endpoints: %#v\", len(e.Endpoints), e.Endpoints)\n}\n\n\n\ntype ErrMultipleMatchingEndpointsV3 struct {\n\tgophercloud.BaseError\n\tEndpoints []tokens3.Endpoint\n}\n\n\n\n\n\ntype ErrNoAuthURL struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoAuthURL) Error() string {\n\treturn \"Environment variable OS_AUTH_URL needs to be set.\"\n}\n\n\n\ntype ErrNoUsername struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoUsername) Error() string {\n\treturn \"Environment variable OS_USERNAME needs to be set.\"\n}\n\n\n\ntype ErrNoPassword struct{ gophercloud.ErrInvalidInput }\n\nfunc (e ErrNoPassword) Error() string {\n\treturn \"Environment variable OS_PASSWORD needs to be set.\"\n}\n\nfunc (e ErrMultipleMatchingEndpointsV3) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"Discovered %d matching endpoints: %#v\", len(e.Endpoints), e.Endpoints)\n}"} {"input": "package cachestore\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\ntype CacheStore struct {\n\tstores map[string]*KVStore\n\tmutex sync.RWMutex\n}\n\n\n\nfunc (c *CacheStore) GetStore(svcName string) *KVStore {\n\tc.mutex.RLock()\n\tkvstore := c.stores[svcName]\n\tc.mutex.RUnlock()\n\n\treturn kvstore\n}\n\n\n\n\n\n\nfunc (c *CacheStore) DeleteStore(svcName string) {\n\tc.mutex.Lock()\n\tdelete(c.stores, svcName)\n\tc.mutex.Unlock()\n}\n\n\nfunc (c *CacheStore) SetCache(svcName string, key string, value interface{}) {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore == nil {\n\t\tsvcStore = c.CreateStore(svcName)\n\t}\n\n\tsvcStore.Set(key, value)\n}\n\n\n\nfunc (c *CacheStore) GetCache(svcName string, key string) interface{} {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore == nil {\n\t\treturn nil\n\t}\n\treturn svcStore.Get(key)\n}\n\n\nfunc (c *CacheStore) DeleteCache(svcName string, key string) {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore != nil {\n\t\tsvcStore.Delete(key)\n\t}\n}\n\n\nfunc (c *CacheStore) MarshalJSON() ([]byte, error) {\n\tc.mutex.RLock()\n\tbytes, err := json.Marshal(&c.stores)\n\tc.mutex.RUnlock()\n\treturn bytes, err\n}\n\n\nfunc NewCacheStore() *CacheStore {\n\treturn &CacheStore{map[string]*KVStore{}, sync.RWMutex{}}\n}\n\nfunc (c *CacheStore) CreateStore(svcName string) *KVStore ", "output": "{\n\tkvstore := NewKVStore()\n\tc.mutex.Lock()\n\tc.stores[svcName] = kvstore\n\tc.mutex.Unlock()\n\n\treturn kvstore\n}"} {"input": "package goldprice\n\nimport \"testing\"\n\nfunc TestUpdateYear(t *testing.T) {\n\tdateArray, yearPrice := GetYearFromTaiwanBank()\n\tif true {\n\t\treturn\n\t}\n\tresult := UpdateYear(dateArray, yearPrice)\n\tif result == false {\n\t\tt.Errorf(\"result incorrect\")\n\t}\n}\n\n\n\nfunc TestUpdateToday(t *testing.T) ", "output": "{\n\tcases := []struct {\n\t\tin Date\n\t}{\n\t\t{Date{2015, 7, 24}},\n\t}\n\tif true {\n\t\treturn\n\t}\n\tfor _, c := range cases {\n\t\ttoday := c.in\n\t\ttimeArray, dayPrice := GetDayFromTaiwanBank(today)\n\t\tresult := UpdateToday(today, timeArray, dayPrice)\n\t\tif result == false {\n\t\t\tt.Errorf(\"result incorrect\")\n\t\t}\n\t}\n}"} {"input": "package harlog\n\nimport (\n \"net/http\"\n \"testing\"\n)\n\nfunc makerr() (*http.Request, *http.Response) {\n\n req, _ := http.NewRequest(\"GET\", \"http://www.example.com/path/?param=value\", nil)\n resp := &http.Response{\n Status: \"200 OK\",\n StatusCode: 200,\n Proto: \"HTTP/1.0\",\n ProtoMajor: 1,\n ProtoMinor: 0,\n Request: req,\n Header: http.Header{\n \"Connection\": {\"close\"},\n },\n Close: true,\n ContentLength: -1,\n }\n\n return req, resp\n}\n\n\n\nfunc TestAddEntry(t *testing.T) {\n\n req, resp := makerr()\n har := NewHARLog()\n har.Entries.Add(req, resp)\n}\n\nfunc TestDump(t *testing.T) {\n\n req, resp := makerr()\n har := NewHARLog()\n har.Entries.Add(req, resp)\n har.Dump()\n}\n\nfunc TestNewLog(t *testing.T) ", "output": "{\n\n har := NewHARLog()\n har.Dump()\n}"} {"input": "package libFileSwarm\n\nimport (\n\t\"encoding/json\"\n\t\"libytc\"\n\t\"log\"\n)\n\ntype Encoder struct {\n}\n\nfunc (e Encoder) EncodeBlock(b libytc.Block) []byte {\n\tblock := b.(*Block)\n\n\tencodedBlock, err := json.Marshal(block)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn encodedBlock\n}\n\n\n\nfunc (e Encoder) DecodeBlock(b []byte) libytc.Block ", "output": "{\n\tblock := new(Block)\n\tjson.Unmarshal(b, block)\n\treturn block\n}"} {"input": "package utils\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n)\n\n\n\n\n\n\n\nconst (\n\twriteExec = 1 << iota\n\twriteSkipSame\n)\n\n\n\n\n\n\n\n\nfunc WriteFile(b, file string, flag int) {\n\tnew := []byte(b)\n\tif flag&writeSkipSame != 0 {\n\t\told, err := ioutil.ReadFile(file)\n\t\tif err == nil && bytes.Equal(old, new) {\n\t\t\treturn\n\t\t}\n\t}\n\tmode := os.FileMode(0666)\n\tif flag&writeExec != 0 {\n\t\tmode = 0777\n\t}\n\terr := ioutil.WriteFile(file, new, mode)\n\tif err != nil {\n\t\tlog.Fatalf(\"WriteFile: %v\", err)\n\t}\n}\n\n\nfunc CopyFile(dst, src string, flag int) {\n\tWriteFile(ReadFile(src), dst, flag)\n}\n\nfunc ReadFile(file string) string ", "output": "{\n\tdata, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tlog.Fatalf(\"ReadFile: %v\", err)\n\t}\n\treturn string(data)\n}"} {"input": "package amber\n\nimport (\n\t\"errors\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/kotfalya/amber/utils\"\n)\n\ntype DB struct {\n\tconfig *Config\n\tname string\n\trootPage *Page\n\treq chan *Req\n\tstop chan struct{}\n}\n\nfunc NewDB(name string, config *Config) *DB {\n\tdb := &DB{\n\t\tconfig: config,\n\t\tname: name,\n\t\trootPage: createRootPage(),\n\t\treq: make(chan *Req, 10),\n\t\tstop: make(chan struct{}),\n\t}\n\tgo db.start()\n\n\treturn db\n}\n\nfunc (db *DB) start() {\n\tsem := utils.NewSemaphore(10)\n\tfor {\n\t\tselect {\n\t\tcase req := <-db.req:\n\t\t\treq.master = db.name\n\t\t\tsem.Acquire()\n\t\t\tgo func(req *Req) {\n\t\t\t\tdefer sem.Release()\n\t\t\t\tswitch req.handler {\n\t\t\t\tcase RequestDBHandler:\n\t\t\t\t\tDBHandle(db, req)\n\t\t\t\tcase RequestKeyHandler:\n\t\t\t\t\tKeyHandler(db, req)\n\t\t\t\tcase RequestNetHandler:\n\t\t\t\t\tNetHandler(db, req)\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(errors.New(ErrInvalidReqHandler))\n\t\t\t\t}\n\n\t\t\t}(req)\n\n\t\tcase <-db.stop:\n\t\t\tglog.V(1).Infoln(\"db:stop\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\nfunc (db *DB) add(keyName string, key Key, level int) (err error) {\n\terr = db.rootPage.add(keyName, key)\n\n\treturn\n}\n\nfunc DBHandle(db *DB, req *Req) {\n\n}\n\nfunc (db *DB) load(keyName string, level int) (Key, error) ", "output": "{\n\tkey, err := db.rootPage.load(keyName)\n\tif err != nil {\n\t\treturn nil, errors.New(ErrUndefinedKey)\n\t}\n\treturn key, nil\n}"} {"input": "package v2\n\nimport (\n\t\"code.cloudfoundry.org/cli/command\"\n\t\"code.cloudfoundry.org/cli/command/translatableerror\"\n)\n\ntype QuotasCommand struct {\n\tusage interface{} `usage:\"CF_NAME quotas\"`\n}\n\n\n\nfunc (QuotasCommand) Execute(args []string) error {\n\treturn translatableerror.UnrefactoredCommandError{}\n}\n\nfunc (QuotasCommand) Setup(config command.Config, ui command.UI) error ", "output": "{\n\treturn nil\n}"} {"input": "package authenticator\n\nimport (\n\t\"k8s.io/apiserver/pkg/authentication/authenticator\"\n\t\"k8s.io/apiserver/pkg/authentication/user\"\n\t\"k8s.io/kubernetes/pkg/auth/authenticator/bearertoken\"\n\t\"k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/tokenfile\"\n)\n\n\n\n\nfunc NewAuthenticatorFromTokens(tokens map[string]*user.DefaultInfo) authenticator.Request ", "output": "{\n\treturn bearertoken.New(tokenfile.New(tokens))\n}"} {"input": "package derive\n\nimport (\n\t\"go/types\"\n\t\"strings\"\n)\n\n\ntype Named struct {\n\tFields []*Field\n\tReflect bool\n}\n\n\ntype Field struct {\n\tname string\n\texternal bool\n\tType types.Type\n\ttypeStr func() string\n}\n\n\n\n\n\nfunc (f *Field) DebugName() string {\n\treturn f.name\n}\n\n\nfunc (f *Field) Private() bool {\n\treturn strings.ToLower(f.name[0:1]) == f.name[0:1]\n}\n\n\nfunc Fields(typesMap TypesMap, typ *types.Struct, external bool) *Named {\n\tnumFields := typ.NumFields()\n\tn := &Named{\n\t\tFields: make([]*Field, numFields),\n\t}\n\tfor i := 0; i < numFields; i++ {\n\t\tfield := typ.Field(i)\n\t\tfieldType := field.Type()\n\t\tfieldName := field.Name()\n\t\tn.Fields[i] = &Field{\n\t\t\tname: fieldName,\n\t\t\texternal: external,\n\t\t\tType: fieldType,\n\t\t\ttypeStr: func() string {\n\t\t\t\treturn typesMap.TypeString(fieldType)\n\t\t\t},\n\t\t}\n\t\tif n.Fields[i].Private() {\n\t\t\tif external {\n\t\t\t\tn.Reflect = true\n\t\t\t}\n\t\t}\n\t}\n\treturn n\n}\n\nfunc GetStructFields(s *types.Struct) []*types.Var {\n\tfields := make([]*types.Var, s.NumFields())\n\tfor i := 0; i < s.NumFields(); i++ {\n\t\tfields[i] = s.Field(i)\n\t}\n\treturn fields\n}\n\nfunc (f *Field) Name(recv string, unsafePkg Import) string ", "output": "{\n\tif !f.Private() || !f.external {\n\t\treturn recv + \".\" + f.name\n\t}\n\treturn `*(*` + f.typeStr() + `)(` + unsafePkg() + `.Pointer(` + recv + `.FieldByName(\"` + f.name + `\").UnsafeAddr()))`\n}"} {"input": "package v1\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"github.com/hashicorp/nomad/api\"\n\t\"github.com/openebs/maya/types/v1\"\n)\n\n\n\ntype NomadUtilInterface interface {\n\n\tName() string\n\n\tNomadClients() (NomadClients, bool)\n}\n\n\n\n\n\n\n\n\n\n\ntype NomadClients interface {\n\tHttp(profileMap map[string]string) (*api.Client, error)\n}\n\n\n\n\n\ntype nomadUtil struct {\n\tprofileMap map[string]string\n\n\tcaCert string\n\tcaPath string\n\tclientCert string\n\tclientKey string\n\tinsecure bool\n}\n\n\nfunc newNomadUtil() (*nomadUtil, error) {\n\treturn &nomadUtil{}, nil\n}\n\n\nfunc (m *nomadUtil) Name() string {\n\treturn \"nomadutil\"\n}\n\n\n\nfunc (m *nomadUtil) NomadClients() (NomadClients, bool) {\n\treturn m, true\n}\n\n\n\n\n\nfunc (m *nomadUtil) Http(profileMap map[string]string) (*api.Client, error) ", "output": "{\n\tapiCConf := api.DefaultConfig()\n\n\treg := v1.GetOrchestratorRegion(profileMap)\n\tapiCConf.Region = reg\n\n\taddr := v1.GetOrchestratorAddress(profileMap)\n\tapiCConf.Address = addr\n\n\tglog.Infof(\"Nomad will be reached at 'region: %s' 'address: %s'\", apiCConf.Region, apiCConf.Address)\n\n\tif m.caCert != \"\" || m.caPath != \"\" || m.clientCert != \"\" || m.clientKey != \"\" || m.insecure {\n\t\tt := &api.TLSConfig{\n\t\t\tCACert: m.caCert,\n\t\t\tCAPath: m.caPath,\n\t\t\tClientCert: m.clientCert,\n\t\t\tClientKey: m.clientKey,\n\t\t\tInsecure: m.insecure,\n\t\t}\n\t\tapiCConf.TLSConfig = t\n\t}\n\n\treturn api.NewClient(apiCConf)\n}"} {"input": "package restful\n\nimport (\n\t\"github.com/Cepave/open-falcon-backend/common/gin/mvc\"\n\t\"github.com/Cepave/open-falcon-backend/common/model\"\n\n\tdbOwl \"github.com/Cepave/open-falcon-backend/common/db/owl\"\n)\n\nfunc listNameTags(\n\tp *struct {\n\t\tValue string `mvc:\"query[value]\"`\n\t\tPaging *model.Paging `mvc:\"pageSize[100] pageOrderBy[value#asc]\"`\n\t},\n) (*model.Paging, mvc.OutputBody) {\n\treturn p.Paging,\n\t\tmvc.JsonOutputBody(\n\t\t\tdbOwl.ListNameTags(p.Value, p.Paging),\n\t\t)\n}\n\n\n\nfunc getNameTagById(\n\tp *struct {\n\t\tNameTagId int16 `mvc:\"param[name_tag_id]\"`\n\t},\n) mvc.OutputBody ", "output": "{\n\treturn mvc.JsonOutputOrNotFound(\n\t\tdbOwl.GetNameTagById(p.NameTagId),\n\t)\n}"} {"input": "package iso20022\n\n\ntype StandingSettlementInstruction9 struct {\n\n\tSettlementStandingInstructionDatabase *SettlementStandingInstructionDatabase3Choice `xml:\"SttlmStgInstrDB\"`\n\n\tVendor *PartyIdentification32Choice `xml:\"Vndr,omitempty\"`\n\n\tOtherDeliveringSettlementParties *SettlementParties23 `xml:\"OthrDlvrgSttlmPties,omitempty\"`\n\n\tOtherReceivingSettlementParties *SettlementParties23 `xml:\"OthrRcvgSttlmPties,omitempty\"`\n}\n\nfunc (s *StandingSettlementInstruction9) AddSettlementStandingInstructionDatabase() *SettlementStandingInstructionDatabase3Choice {\n\ts.SettlementStandingInstructionDatabase = new(SettlementStandingInstructionDatabase3Choice)\n\treturn s.SettlementStandingInstructionDatabase\n}\n\nfunc (s *StandingSettlementInstruction9) AddVendor() *PartyIdentification32Choice {\n\ts.Vendor = new(PartyIdentification32Choice)\n\treturn s.Vendor\n}\n\nfunc (s *StandingSettlementInstruction9) AddOtherDeliveringSettlementParties() *SettlementParties23 {\n\ts.OtherDeliveringSettlementParties = new(SettlementParties23)\n\treturn s.OtherDeliveringSettlementParties\n}\n\n\n\nfunc (s *StandingSettlementInstruction9) AddOtherReceivingSettlementParties() *SettlementParties23 ", "output": "{\n\ts.OtherReceivingSettlementParties = new(SettlementParties23)\n\treturn s.OtherReceivingSettlementParties\n}"} {"input": "package nes\n\nimport \"math\"\n\ntype Filter interface {\n\tStep(x float32) float32\n}\n\n\n\ntype FirstOrderFilter struct {\n\tB0 float32\n\tB1 float32\n\tA1 float32\n\tprevX float32\n\tprevY float32\n}\n\nfunc (f *FirstOrderFilter) Step(x float32) float32 {\n\ty := f.B0*x + f.B1*f.prevX - f.A1*f.prevY\n\tf.prevY = y\n\tf.prevX = x\n\treturn y\n}\n\n\n\n\n\nfunc HighPassFilter(sampleRate float32, cutoffFreq float32) Filter {\n\tc := sampleRate / math.Pi / cutoffFreq\n\ta0i := 1 / (1 + c)\n\treturn &FirstOrderFilter{\n\t\tB0: c * a0i,\n\t\tB1: -c * a0i,\n\t\tA1: (1 - c) * a0i,\n\t}\n}\n\ntype FilterChain []Filter\n\nfunc (fc FilterChain) Step(x float32) float32 {\n\tif fc != nil {\n\t\tfor i := range fc {\n\t\t\tx = fc[i].Step(x)\n\t\t}\n\t}\n\treturn x\n}\n\nfunc LowPassFilter(sampleRate float32, cutoffFreq float32) Filter ", "output": "{\n\tc := sampleRate / math.Pi / cutoffFreq\n\ta0i := 1 / (1 + c)\n\treturn &FirstOrderFilter{\n\t\tB0: a0i,\n\t\tB1: a0i,\n\t\tA1: (1 - c) * a0i,\n\t}\n}"} {"input": "package base64\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc must(r interface{}, err error) interface{} {\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn r\n}\n\n\n\nfunc TestDecode(t *testing.T) {\n\tassert.Equal(t, []byte(\"\"), must(Decode(\"\")))\n\tassert.Equal(t, []byte(\"f\"), must(Decode(\"Zg==\")))\n\tassert.Equal(t, []byte(\"fo\"), must(Decode(\"Zm8=\")))\n\tassert.Equal(t, []byte(\"foo\"), must(Decode(\"Zm9v\")))\n\tassert.Equal(t, []byte(\"foob\"), must(Decode(\"Zm9vYg==\")))\n\tassert.Equal(t, []byte(\"fooba\"), must(Decode(\"Zm9vYmE=\")))\n\tassert.Equal(t, []byte(\"foobar\"), must(Decode(\"Zm9vYmFy\")))\n\tassert.Equal(t, []byte{0x03, 0xe0, 0x7f}, must(Decode(\"A+B/\")))\n\tassert.Equal(t, []byte{0x03, 0xe0, 0x7f}, must(Decode(\"A-B_\")))\n\n\t_, err := Decode(\"b.o.g.u.s\")\n\tassert.Error(t, err)\n}\n\nfunc TestEncode(t *testing.T) ", "output": "{\n\tassert.Equal(t, \"\", must(Encode([]byte(\"\"))))\n\tassert.Equal(t, \"Zg==\", must(Encode([]byte(\"f\"))))\n\tassert.Equal(t, \"Zm8=\", must(Encode([]byte(\"fo\"))))\n\tassert.Equal(t, \"Zm9v\", must(Encode([]byte(\"foo\"))))\n\tassert.Equal(t, \"Zm9vYg==\", must(Encode([]byte(\"foob\"))))\n\tassert.Equal(t, \"Zm9vYmE=\", must(Encode([]byte(\"fooba\"))))\n\tassert.Equal(t, \"Zm9vYmFy\", must(Encode([]byte(\"foobar\"))))\n\tassert.Equal(t, \"A+B/\", must(Encode([]byte{0x03, 0xe0, 0x7f})))\n}"} {"input": "package internal\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\ntype ContextKey string\n\nconst userAgent = \"gcloud-golang/0.1\"\n\n\n\n\ntype Transport struct {\n\tBase http.RoundTripper\n}\n\n\n\nfunc (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq = cloneRequest(req)\n\tua := req.Header.Get(\"User-Agent\")\n\tif ua == \"\" {\n\t\tua = userAgent\n\t} else {\n\t\tua = fmt.Sprintf(\"%s;%s\", ua, userAgent)\n\t}\n\treq.Header.Set(\"User-Agent\", ua)\n\treturn t.Base.RoundTrip(req)\n}\n\n\n\nfunc cloneRequest(r *http.Request) *http.Request {\n\tr2 := new(http.Request)\n\t*r2 = *r\n\tr2.Header = make(http.Header)\n\tfor k, s := range r.Header {\n\t\tr2.Header[k] = s\n\t}\n\treturn r2\n}\n\n\nfunc ProjID(ctx context.Context) string {\n\treturn ctx.Value(ContextKey(\"base\")).(map[string]interface{})[\"project_id\"].(string)\n}\n\n\n\nfunc Namespace(ctx context.Context) string {\n\tv := ctx.Value(ContextKey(\"namespace\"))\n\tif v == nil {\n\t\treturn \"\"\n\t} else {\n\t\treturn v.(string)\n\t}\n}\n\n\n\nfunc HttpClient(ctx context.Context) *http.Client ", "output": "{\n\treturn ctx.Value(ContextKey(\"base\")).(map[string]interface{})[\"http_client\"].(*http.Client)\n}"} {"input": "package tasks\n\n\n\n\nimport (\n\t\"net/url\"\n\n\t\"github.com/kawaken/go-rtm/methods\"\n)\n\n\n\n\nfunc Postpone(timeline string, listID string, taskseriesID string, taskID string) *methods.Method ", "output": "{\n\tname := \"rtm.tasks.postpone\"\n\n\tp := url.Values{}\n\tp.Add(\"method\", name)\n\tp.Add(\"timeline\", timeline)\n\tp.Add(\"list_id\", listID)\n\tp.Add(\"taskseries_id\", taskseriesID)\n\tp.Add(\"task_id\", taskID)\n\treturn &methods.Method{Name: name, Params: p}\n}"} {"input": "package status\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/cozy/cozy-stack/pkg/config\"\n\t\"github.com/cozy/cozy-stack/web/errors\"\n\t\"github.com/labstack/echo\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc testRequest(t *testing.T, url string) {\n\tres, err := http.Get(url)\n\tassert.NoError(t, err)\n\tdefer res.Body.Close()\n\n\tbody, ioerr := ioutil.ReadAll(res.Body)\n\tassert.NoError(t, ioerr)\n\tassert.Equal(t, \"200 OK\", res.Status, \"should get a 200\")\n\tassert.Equal(t, \"{\\\"couchdb\\\":\\\"healthy\\\",\\\"message\\\":\\\"OK\\\"}\", string(body), \"res body should match\")\n}\n\n\n\nfunc TestMain(m *testing.M) {\n\tconfig.UseTestFile()\n\tos.Exit(m.Run())\n}\n\nfunc TestRoutes(t *testing.T) ", "output": "{\n\thandler := echo.New()\n\thandler.HTTPErrorHandler = errors.ErrorHandler\n\tRoutes(handler.Group(\"/status\"))\n\n\tts := httptest.NewServer(handler)\n\tdefer ts.Close()\n\n\ttestRequest(t, ts.URL+\"/status\")\n}"} {"input": "package iso20022\n\n\ntype BillingServicesTax2 struct {\n\n\tNumber *Max35Text `xml:\"Nb\"`\n\n\tDescription *Max40Text `xml:\"Desc,omitempty\"`\n\n\tRate *DecimalNumber `xml:\"Rate\"`\n\n\tPricingAmount *AmountAndDirection34 `xml:\"PricgAmt\"`\n}\n\nfunc (b *BillingServicesTax2) SetNumber(value string) {\n\tb.Number = (*Max35Text)(&value)\n}\n\n\n\nfunc (b *BillingServicesTax2) SetRate(value string) {\n\tb.Rate = (*DecimalNumber)(&value)\n}\n\nfunc (b *BillingServicesTax2) AddPricingAmount() *AmountAndDirection34 {\n\tb.PricingAmount = new(AmountAndDirection34)\n\treturn b.PricingAmount\n}\n\nfunc (b *BillingServicesTax2) SetDescription(value string) ", "output": "{\n\tb.Description = (*Max40Text)(&value)\n}"} {"input": "package incoming\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\nvar (\n\t_InKindNameToValue = map[string]InKind{\n\t\t\"control\": control,\n\t\t\"state\": state,\n\t\t\"checkForUpdates\": checkForUpdates,\n\t\t\"updateAvailable\": updateAvailable,\n\t\t\"updateBegin\": updateBegin,\n\t\t\"updateApply\": updateApply,\n\t}\n\n\t_InKindValueToName = map[InKind]string{\n\t\tcontrol: \"control\",\n\t\tstate: \"state\",\n\t\tcheckForUpdates: \"checkForUpdates\",\n\t\tupdateAvailable: \"updateAvailable\",\n\t\tupdateBegin: \"updateBegin\",\n\t\tupdateApply: \"updateApply\",\n\t}\n)\n\nfunc init() {\n\tvar v InKind\n\tif _, ok := interface{}(v).(fmt.Stringer); ok {\n\t\t_InKindNameToValue = map[string]InKind{\n\t\t\tinterface{}(control).(fmt.Stringer).String(): control,\n\t\t\tinterface{}(state).(fmt.Stringer).String(): state,\n\t\t\tinterface{}(checkForUpdates).(fmt.Stringer).String(): checkForUpdates,\n\t\t\tinterface{}(updateAvailable).(fmt.Stringer).String(): updateAvailable,\n\t\t\tinterface{}(updateBegin).(fmt.Stringer).String(): updateBegin,\n\t\t\tinterface{}(updateApply).(fmt.Stringer).String(): updateApply,\n\t\t}\n\t}\n}\n\n\nfunc (r InKind) MarshalJSON() ([]byte, error) {\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn json.Marshal(s.String())\n\t}\n\ts, ok := _InKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid InKind: %d\", r)\n\t}\n\treturn json.Marshal(s)\n}\n\n\n\n\nfunc (r *InKind) UnmarshalJSON(data []byte) error ", "output": "{\n\tvar s string\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\treturn fmt.Errorf(\"InKind should be a string, got %s\", data)\n\t}\n\tv, ok := _InKindNameToValue[s]\n\tif !ok {\n\t\treturn fmt.Errorf(\"invalid InKind %q\", s)\n\t}\n\t*r = v\n\treturn nil\n}"} {"input": "package lib\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc benchmarkReduceToDiff(modulesCount, deltaCount int, b *testing.B) {\n\tclean()\n\tdefer clean()\n\n\trepo := NewTestRepoForBench(b, \".tmp/repo\")\n\n\tfor i := 0; i < modulesCount; i++ {\n\t\terr := repo.InitModule(fmt.Sprintf(\"app-%v\", i))\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"%v\", err)\n\t\t}\n\t}\n\n\terr := repo.Commit(\"first\")\n\tif err != nil {\n\t\tb.Fatalf(\"%v\", err)\n\t}\n\n\tc1 := repo.LastCommit\n\n\tfor i := 0; i < deltaCount; i++ {\n\t\terr = repo.WriteContent(fmt.Sprintf(\"content/file-%v\", i), \"sample content\")\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"%v\", err)\n\t\t}\n\t}\n\n\trepo.Commit(\"second\")\n\tc2 := repo.LastCommit\n\n\tworld := NewBenchmarkWorld(b, \".tmp/repo\")\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, err = world.System.ManifestByDiff(c1.String(), c2.String())\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"%v\", err)\n\t\t}\n\n\t}\n\n\tb.StopTimer()\n}\nfunc BenchmarkReduceToDiff10(b *testing.B) {\n\tbenchmarkReduceToDiff(10, 10, b)\n}\n\nfunc BenchmarkReduceToDiff100(b *testing.B) {\n\tbenchmarkReduceToDiff(100, 100, b)\n}\n\n\n\nfunc BenchmarkReduceToDiff10000(b *testing.B) {\n\tbenchmarkReduceToDiff(10000, 10000, b)\n}\n\nfunc BenchmarkReduceToDiff1000(b *testing.B) ", "output": "{\n\tbenchmarkReduceToDiff(1000, 1000, b)\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestCountWords(t *testing.T) ", "output": "{\n\tcases := []struct {\n\t\ts string\n\t\tcount int\n\t}{\n\t\t{\"saveChangesInTheEditor\", 5},\n\t\t{\"save\", 1},\n\t\t{\"\", 0},\n\t}\n\tfor _, c := range cases {\n\t\tif got := CountWords(c.s); got != c.count {\n\t\t\tt.Errorf(\"Expected %d, got %d\", c.count, got)\n\t\t}\n\t}\n\n}"} {"input": "package log5go\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype jsonFormatter struct {\n\ttimeFormat string\n\tlines bool\n}\n\ntype jsonLog struct {\n\tTime string `json:\"time\"`\n\tLevel string `json:\"level\"`\n\tPrefix string `json:\"prefix,omitempty\"`\n\tLine string `json:\"line,omitempty\"`\n\tMsg string `json:\"msg\"`\n\tData map[string]interface{} `json:\"data,omitempty\"`\n}\n\nfunc (f *jsonFormatter) Format(tstamp time.Time, level LogLevel, prefix, caller string, line uint, msg string, data Data, out *[]byte) {\n\toutput := jsonLog{\n\t\tTime: tstamp.Format(f.timeFormat),\n\t\tLevel: GetLogLevelString(level),\n\t\tPrefix: prefix,\n\t\tLine: f.formatLine(caller, line),\n\t\tMsg: msg,\n\t\tData: data,\n\t}\n\n\tserialized, err := json.Marshal(output)\n\tif err == nil {\n\t\t*out = append(*out, serialized...)\n\t}\n}\n\nfunc (f *jsonFormatter) SetTimeFormat(timeFormat string) {\n\tf.timeFormat = timeFormat\n}\n\nfunc (f *jsonFormatter) SetLines(lines bool) {\n\tf.lines = lines\n}\n\n\n\nfunc (f *jsonFormatter) formatLine(caller string, line uint) string ", "output": "{\n\tif !f.lines || caller == \"\" {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%s:%d\", caller, line)\n}"} {"input": "package drone\n\nimport (\n\t\"fmt\"\n)\n\ntype UserService struct {\n\t*Client\n}\n\n\n\n\n\nfunc (s *UserService) GetCurrent() (*User, error) {\n\tvar user = User{}\n\tvar err = s.run(\"GET\", \"/api/user\", nil, &user)\n\treturn &user, err\n}\n\n\nfunc (s *UserService) Create(remote, login string) (*User, error) {\n\tvar path = fmt.Sprintf(\"/api/users/%s/%s\", remote, login)\n\tvar user = User{}\n\tvar err = s.run(\"POST\", path, nil, &user)\n\treturn &user, err\n}\n\n\nfunc (s *UserService) Delete(remote, login string) error {\n\tvar path = fmt.Sprintf(\"/api/users/%s/%s\", remote, login)\n\treturn s.run(\"DELETE\", path, nil, nil)\n}\n\n\nfunc (s *UserService) List() ([]*User, error) {\n\tvar users []*User\n\tvar err = s.run(\"GET\", \"/api/users\", nil, &users)\n\treturn users, err\n}\n\nfunc (s *UserService) Get(remote, login string) (*User, error) ", "output": "{\n\tvar path = fmt.Sprintf(\"/api/users/%s/%s\", remote, login)\n\tvar user = User{}\n\tvar err = s.run(\"GET\", path, nil, &user)\n\treturn &user, err\n}"} {"input": "package auth\n\nimport (\n\t\"sync\"\n\n\t\"github.com/google/martian/session\"\n)\n\nconst key = \"auth.Context\"\n\n\ntype Context struct {\n\tmu sync.RWMutex\n\tid string\n\terr error\n}\n\n\nfunc FromContext(ctx *session.Context) *Context {\n\tif v, ok := ctx.GetSession().Get(key); ok {\n\t\treturn v.(*Context)\n\t}\n\n\tactx := &Context{}\n\tctx.GetSession().Set(key, actx)\n\n\treturn actx\n}\n\n\nfunc (ctx *Context) ID() string {\n\tctx.mu.RLock()\n\tctx.mu.RUnlock()\n\n\treturn ctx.id\n}\n\n\n\n\n\nfunc (ctx *Context) SetError(err error) {\n\tctx.mu.Lock()\n\tdefer ctx.mu.Unlock()\n\n\tctx.id = \"\"\n\tctx.err = err\n}\n\n\nfunc (ctx *Context) Error() error {\n\tctx.mu.RLock()\n\tdefer ctx.mu.RUnlock()\n\n\treturn ctx.err\n}\n\nfunc (ctx *Context) SetID(id string) ", "output": "{\n\tctx.mu.Lock()\n\tctx.mu.Unlock()\n\n\tctx.err = nil\n\n\tif id == \"\" {\n\t\treturn\n\t}\n\n\tctx.id = id\n}"} {"input": "package cmd\n\nimport (\n\t\"context\"\n\t\"io\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/GoogleContainerTools/skaffold/cmd/skaffold/app/tips\"\n\t\"github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner\"\n\tlatestV1 \"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1\"\n\t\"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util\"\n)\n\n\n\n\nfunc doTest(ctx context.Context, out io.Writer) error {\n\treturn withRunner(ctx, out, func(r runner.Runner, configs []util.VersionedConfig) error {\n\t\tvar artifacts []*latestV1.Artifact\n\t\tfor _, c := range configs {\n\t\t\tartifacts = append(artifacts, c.(*latestV1.SkaffoldConfig).Build.Artifacts...)\n\t\t}\n\t\tbuildArtifacts, err := getBuildArtifactsAndSetTags(artifacts, r.ApplyDefaultRepo)\n\t\tif err != nil {\n\t\t\ttips.PrintForTest(out)\n\t\t\treturn err\n\t\t}\n\n\t\treturn r.Test(ctx, out, buildArtifacts)\n\t})\n}\n\nfunc NewCmdTest() *cobra.Command ", "output": "{\n\treturn NewCmd(\"test\").\n\t\tWithDescription(\"Run tests against your built application images\").\n\t\tWithExample(\"Build the artifacts and collect the tags into a file\", \"build --file-output=tags.json\").\n\t\tWithExample(\"Run test against images previously built by Skaffold into a 'tags.json' file\", \"test --build-artifacts=tags.json\").\n\t\tWithCommonFlags().\n\t\tWithHouseKeepingMessages().\n\t\tNoArgs(doTest)\n}"} {"input": "package metrics\n\nimport (\n\t\"github.com/cloudfoundry/dropsonde/metric_sender\"\n)\n\nvar metricSender metric_sender.MetricSender\nvar metricBatcher MetricBatcher\n\ntype MetricBatcher interface {\n\tBatchIncrementCounter(name string)\n\tBatchAddCounter(name string, delta uint64)\n\tClose()\n}\n\n\n\n\n\nfunc Close() {\n\tmetricBatcher.Close()\n}\n\n\n\nfunc SendValue(name string, value float64, unit string) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.SendValue(name, value, unit)\n}\n\n\n\n\nfunc IncrementCounter(name string) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.IncrementCounter(name)\n}\n\n\n\n\nfunc BatchIncrementCounter(name string) {\n\tif metricBatcher == nil {\n\t\treturn\n\t}\n\tmetricBatcher.BatchIncrementCounter(name)\n}\n\n\n\n\nfunc AddToCounter(name string, delta uint64) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.AddToCounter(name, delta)\n}\n\n\n\n\nfunc BatchAddCounter(name string, delta uint64) {\n\tif metricBatcher == nil {\n\t\treturn\n\t}\n\tmetricBatcher.BatchAddCounter(name, delta)\n}\n\n\n\n\n\nfunc SendContainerMetric(applicationId string, instanceIndex int32, cpuPercentage float64, memoryBytes uint64, diskBytes uint64) error {\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\n\treturn metricSender.SendContainerMetric(applicationId, instanceIndex, cpuPercentage, memoryBytes, diskBytes)\n}\n\nfunc Initialize(ms metric_sender.MetricSender, mb MetricBatcher) ", "output": "{\n\tif metricBatcher != nil {\n\t\tmetricBatcher.Close()\n\t}\n\tmetricSender = ms\n\tmetricBatcher = mb\n}"} {"input": "package output\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/jutkko/mindown/util\"\n)\n\nconst DEPTH_LIMIT int = 6\n\nfunc WriteMarkdown(filename string, forceWrite bool, graph *util.Graph) error {\n\tif !forceWrite {\n\t\tif _, err := os.Stat(filename); !os.IsNotExist(err) {\n\t\t\treturn errors.New(\"File exists\")\n\t\t}\n\t}\n\n\tos.Remove(filename)\n\n\tfile, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)\n\tif err != nil {\n\t\treturn errors.New(\"Failed to open file\")\n\t}\n\tdefer file.Close()\n\n\tif graph == nil {\n\t\treturn errors.New(\"Graph is nil\")\n\t}\n\n\tfor _, node := range graph.GetNodes() {\n\t\terr := writeMarkdownRecursively(1, file, node)\n\n\t\tif err != nil {\n\t\t\treturn errors.New(fmt.Sprintf(\"Failed to write file: %s %s\", filename, err.Error()))\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc writeMarkdownRecursively(depth int, file *os.File, node *util.Node) error {\n\terr := appendToFile(fmt.Sprintf(\"%s%s\\n\", getHash(depth), node.GetTitle()), file)\n\n\tif err != nil || len(node.GetChildren()) == 0 {\n\t\treturn err\n\t}\n\n\tfor _, node := range node.GetChildren() {\n\t\terr := writeMarkdownRecursively(depth+1, file, node)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc appendToFile(data string, file *os.File) error {\n\tif _, err := file.WriteString(data); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc getHash(level int) (result string) ", "output": "{\n\tresult = \"\"\n\n\tif level <= DEPTH_LIMIT {\n\t\tfor i := 0; i < level; i++ {\n\t\t\tresult += \"#\"\n\t\t}\n\t\tresult += \" \"\n\t}\n\n\treturn\n}"} {"input": "package ignition\n\nimport (\n\t\"github.com/coreos/ignition/config/types\"\n\t\"github.com/hashicorp/terraform/helper/schema\"\n)\n\n\n\nfunc resourceGroupCreate(d *schema.ResourceData, meta interface{}) error {\n\tid, err := buildGroup(d, meta.(*cache))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.SetId(id)\n\treturn nil\n}\n\nfunc resourceGroupDelete(d *schema.ResourceData, meta interface{}) error {\n\td.SetId(\"\")\n\treturn nil\n}\n\nfunc resourceGroupExists(d *schema.ResourceData, meta interface{}) (bool, error) {\n\tid, err := buildGroup(d, meta.(*cache))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn id == d.Id(), nil\n}\n\nfunc resourceGroupRead(d *schema.ResourceData, meta interface{}) error {\n\treturn nil\n}\n\nfunc buildGroup(d *schema.ResourceData, c *cache) (string, error) {\n\treturn c.addGroup(&types.Group{\n\t\tName: d.Get(\"name\").(string),\n\t\tPasswordHash: d.Get(\"password_hash\").(string),\n\t\tGid: getUInt(d, \"gid\"),\n\t}), nil\n}\n\nfunc resourceGroup() *schema.Resource ", "output": "{\n\treturn &schema.Resource{\n\t\tCreate: resourceGroupCreate,\n\t\tDelete: resourceGroupDelete,\n\t\tExists: resourceGroupExists,\n\t\tRead: resourceGroupRead,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"name\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"gid\": &schema.Schema{\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"password_hash\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package factor\n\nimport (\n\t\"github.com/jesand/stats\"\n\t\"github.com/jesand/stats/dist\"\n\t\"github.com/jesand/stats/variable\"\n)\n\n\n\n\ntype Factor interface {\n\n\tAdjacent() []variable.RandomVariable\n\n\tScore() float64\n}\n\n\n\n\nfunc NewDistFactor(vars []variable.RandomVariable, distr dist.Dist) *DistFactor {\n\treturn &DistFactor{\n\t\tVars: vars,\n\t\tDist: distr,\n\t}\n}\n\n\ntype DistFactor struct {\n\tVars []variable.RandomVariable\n\tDist dist.Dist\n}\n\n\nfunc (factor DistFactor) Adjacent() []variable.RandomVariable {\n\treturn factor.Vars\n}\n\n\nfunc (factor DistFactor) Score() float64 {\n\tvar (\n\t\tnumVars = factor.Dist.NumVars()\n\t\tnumParams = factor.Dist.NumParams()\n\t)\n\tif len(factor.Vars) != numVars+numParams {\n\t\tpanic(stats.ErrfFactorVarNum(numVars, numParams, len(factor.Vars)))\n\t}\n\tvar (\n\t\tvars = make([]float64, numVars)\n\t\tparams = make([]float64, numParams)\n\t)\n\tfor i, rv := range factor.Vars {\n\t\tif i < len(vars) {\n\t\t\tvars[i] = rv.Val()\n\t\t} else {\n\t\t\tparams[i-len(vars)] = rv.Val()\n\t\t}\n\t}\n\treturn factor.Dist.Score(vars, params)\n}\n\n\nfunc NewConstFactor(vars []variable.RandomVariable, value float64) *ConstFactor {\n\treturn &ConstFactor{\n\t\tVars: vars,\n\t\tValue: value,\n\t}\n}\n\n\ntype ConstFactor struct {\n\tVars []variable.RandomVariable\n\tValue float64\n}\n\n\nfunc (factor ConstFactor) Adjacent() []variable.RandomVariable {\n\treturn factor.Vars\n}\n\n\n\n\nfunc (factor ConstFactor) Score() float64 ", "output": "{\n\treturn factor.Value\n}"} {"input": "package setdockergroup\n\nimport (\n\t\"log\"\n\t\"os/user\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"syscall\"\n)\n\n\n\nfunc SetDockerGroup() ", "output": "{\n\tdockerGroup, err := user.LookupGroup(\"docker\")\n\tif err != nil {\n\t\tlog.Println(\"I couldn't lookup the group 'docker', error: \" + err.Error())\n\t\treturn\n\t}\n\tgid, err := strconv.Atoi(dockerGroup.Gid)\n\tif err != nil {\n\t\tpanic(\"I couldn't convert '\" + dockerGroup.Gid + \"' to integer, error: \" + err.Error())\n\t}\n\tif runtime.GOOS != \"windows\" {\n\t\terr = syscall.Setgroups([]int{gid})\n\t\tif err != nil {\n\t\t\tpanic(\"I couldn't setGroups() to 'docker', make sure I'm in the docker group in /etc/group, error: \" + err.Error())\n\t\t}\n\t}\n}"} {"input": "package toJson\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\n\n\nfunc WriteToJsonWithCode(w http.ResponseWriter, obj interface{}, code int) error {\n\to, err := ToJson(obj)\n\tif err != nil {\n\t\twriteError(err)\n\t\treturn err\n\t}\n\n\twrapped := map[string]interface{}{\"result\": o}\n\n\treturn WriteJson(w, &wrapped, code)\n}\n\nfunc WriteToJsonNotWrapped(w http.ResponseWriter, obj interface{}) error {\n\treturn WriteToJsonNotWrappedWithCode(w, obj, http.StatusOK)\n}\n\nfunc WriteToJsonNotWrappedWithCode(w http.ResponseWriter, obj interface{}, code int) error {\n\to, err := ToJson(obj)\n\tif err != nil {\n\t\twriteError(err)\n\t\treturn err\n\t}\n\n\treturn WriteJson(w, &o, code)\n}\n\nfunc WriteJson(w http.ResponseWriter, obj interface{}, code int) error {\n\tmarshalled, err := json.MarshalIndent(obj, \"\", \" \")\n\tif err != nil {\n\t\twriteError(err)\n\t\treturn err\n\t}\n\n\tdata := []byte(fmt.Sprintf(\"%s\\n\", marshalled))\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.Header().Set(\"Content-Length\", fmt.Sprint(len(data)))\n\tw.WriteHeader(code)\n\tw.Write(data)\n\n\treturn nil\n}\n\nfunc WriteToJson(w http.ResponseWriter, obj interface{}) error ", "output": "{\n\treturn WriteToJsonWithCode(w, obj, http.StatusOK)\n}"} {"input": "package git\n\nimport (\n\t\"encoding/hex\"\n)\n\n\ntype Hash [20]byte\n\n\nvar ZeroHash Hash\n\n\n\n\n\nfunc (h Hash) IsZero() bool {\n\tvar empty Hash\n\treturn h == empty\n}\n\nfunc (h Hash) String() string {\n\treturn hex.EncodeToString(h[:])\n}\n\nfunc NewHash(s string) Hash ", "output": "{\n\tb, _ := hex.DecodeString(s)\n\n\tvar h Hash\n\tcopy(h[:], b)\n\n\treturn h\n}"} {"input": "package openpgp\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\ntype recordingHash struct {\n\tbuf *bytes.Buffer\n}\n\nfunc (r recordingHash) Write(b []byte) (n int, err error) {\n\treturn r.buf.Write(b)\n}\n\n\n\nfunc (r recordingHash) Reset() {\n\tpanic(\"shouldn't be called\")\n}\n\nfunc (r recordingHash) Size() int {\n\tpanic(\"shouldn't be called\")\n}\n\nfunc (r recordingHash) BlockSize() int {\n\tpanic(\"shouldn't be called\")\n}\n\nfunc testCanonicalText(t *testing.T, input, expected string) {\n\tr := recordingHash{bytes.NewBuffer(nil)}\n\tc := NewCanonicalTextHash(r)\n\tc.Write([]byte(input))\n\tresult := c.Sum(nil)\n\tif expected != string(result) {\n\t\tt.Errorf(\"input: %x got: %x want: %x\", input, result, expected)\n\t}\n}\n\nfunc TestCanonicalText(t *testing.T) {\n\ttestCanonicalText(t, \"foo\\n\", \"foo\\r\\n\")\n\ttestCanonicalText(t, \"foo\", \"foo\")\n\ttestCanonicalText(t, \"foo\\r\\n\", \"foo\\r\\n\")\n\ttestCanonicalText(t, \"foo\\r\\nbar\", \"foo\\r\\nbar\")\n\ttestCanonicalText(t, \"foo\\r\\nbar\\n\\n\", \"foo\\r\\nbar\\r\\n\\r\\n\")\n}\n\nfunc (r recordingHash) Sum(in []byte) []byte ", "output": "{\n\treturn append(in, r.buf.Bytes()...)\n}"} {"input": "package async\n\nimport (\n\t\"reflect\"\n)\n\n\nfunc Filter(data interface{}, routine Routine, callbacks ...Done) {\n\tvar (\n\t\troutines []Routine\n\t\tresults []interface{}\n\t)\n\n\td := reflect.ValueOf(data)\n\n\tfor i := 0; i < d.Len(); i++ {\n\t\tv := d.Index(i).Interface()\n\t\troutines = append(routines, func(id int) Routine {\n\t\t\treturn func(done Done, args ...interface{}) {\n\t\t\t\tdone = func(original Done) Done {\n\t\t\t\t\treturn func(err error, args ...interface{}) {\n\t\t\t\t\t\tif args[0] != false {\n\t\t\t\t\t\t\tresults = append(results, v)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif id == (d.Len() - 1) {\n\t\t\t\t\t\t\toriginal(err, results...)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\toriginal(err, args...)\n\t\t\t\t\t}\n\t\t\t\t}(done)\n\n\t\t\t\troutine(done, v, id)\n\t\t\t}\n\t\t}(i))\n\t}\n\n\tWaterfall(routines, callbacks...)\n}\n\n\n\n\nfunc FilterParallel(data interface{}, routine Routine, callbacks ...Done) ", "output": "{\n\tvar routines []Routine\n\n\td := reflect.ValueOf(data)\n\n\tfor i := 0; i < d.Len(); i++ {\n\t\tv := d.Index(i).Interface()\n\t\troutines = append(routines, func(id int) Routine {\n\t\t\treturn func(done Done, args ...interface{}) {\n\t\t\t\tdone = func(original Done) Done {\n\t\t\t\t\treturn func(err error, args ...interface{}) {\n\t\t\t\t\t\tif args[0] != false {\n\t\t\t\t\t\t\toriginal(err, v)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\toriginal(err)\n\t\t\t\t\t}\n\t\t\t\t}(done)\n\n\t\t\t\troutine(done, v, id)\n\t\t\t}\n\t\t}(i))\n\t}\n\n\tParallel(routines, callbacks...)\n}"} {"input": "package cmd\n\nimport (\n\t\"time\"\n\n\t\"github.com/codegangsta/cli\"\n)\n\nfunc stringFlag(name, value, usage string) cli.StringFlag {\n\treturn cli.StringFlag{\n\t\tName: name,\n\t\tValue: value,\n\t\tUsage: usage,\n\t}\n}\n\nfunc boolFlag(name, usage string) cli.BoolFlag {\n\treturn cli.BoolFlag{\n\t\tName: name,\n\t\tUsage: usage,\n\t}\n}\n\nfunc intFlag(name string, value int, usage string) cli.IntFlag {\n\treturn cli.IntFlag{\n\t\tName: name,\n\t\tValue: value,\n\t\tUsage: usage,\n\t}\n}\n\n\n\nfunc durationFlag(name string, value time.Duration, usage string) cli.DurationFlag ", "output": "{\n\treturn cli.DurationFlag{\n\t\tName: name,\n\t\tValue: value,\n\t\tUsage: usage,\n\t}\n}"} {"input": "package resolver\n\nvar (\n\tm = make(map[string]Builder)\n\tdefaultScheme = \"passthrough\"\n)\n\n\n\n\n\nfunc Register(b Builder) {\n\tm[b.Scheme()] = b\n}\n\n\n\n\n\n\n\n\n\n\nfunc Get(scheme string) Builder {\n\tif b, ok := m[scheme]; ok {\n\t\treturn b\n\t}\n\tif b, ok := m[defaultScheme]; ok {\n\t\treturn b\n\t}\n\treturn nil\n}\n\n\n\n\n\n\ntype AddressType uint8\n\nconst (\n\tBackend AddressType = iota\n\tGRPCLB\n)\n\n\n\ntype Address struct {\n\tAddr string\n\tType AddressType\n\tServerName string\n\tMetadata interface{}\n}\n\n\n\ntype BuildOption struct {\n}\n\n\n\ntype ClientConn interface {\n\tNewAddress(addresses []Address)\n\tNewServiceConfig(serviceConfig string)\n}\n\n\n\ntype Target struct {\n\tScheme string\n\tAuthority string\n\tEndpoint string\n}\n\n\ntype Builder interface {\n\tBuild(target Target, cc ClientConn, opts BuildOption) (Resolver, error)\n\tScheme() string\n}\n\n\ntype ResolveNowOption struct{}\n\n\n\ntype Resolver interface {\n\tResolveNow(ResolveNowOption)\n\tClose()\n}\n\n\n\n\nfunc UnregisterForTesting(scheme string) {\n\tdelete(m, scheme)\n}\n\nfunc SetDefaultScheme(scheme string) ", "output": "{\n\tdefaultScheme = scheme\n}"} {"input": "package queue\n\nimport \"fmt\"\n\ntype Queue struct {\n\tElems []interface{}\n\tTop int\n\tBottom int\n\tMaxlen int\n\tFull bool\n}\n\n\nfunc New(maxLen int) *Queue {\n\tq := &Queue{\n\t\tElems: make([]interface{}, maxLen),\n\t\tTop: 0,\n\t\tBottom: 0,\n\t\tMaxlen: maxLen,\n\t}\n\n\tfmt.Printf(\"Queue: %d\\n\", q.Maxlen)\n\treturn q\n}\n\n\n\nfunc (q *Queue) DeQueue() {\n\n\tif q.Bottom > q.Top {\n\t\tq.Top++\n\t}\n\n}\n\nfunc (q *Queue) Len() int {\n\treturn len(q.Elems)\n}\n\nfunc (q *Queue) EnQueue(e interface{}) ", "output": "{\n\n\tif q.Maxlen == q.Bottom - q.Top {\n\t\tq.Bottom = q.Top\n\t\tq.Full = true\n\t}\n\tq.Elems[q.Bottom] = e\n\tq.Bottom++\n\n}"} {"input": "package fmath\n\nimport \"math\"\n\n\n\n\nfunc Atan2(x, y float32) float32 ", "output": "{\n\treturn float32(math.Atan2(float64(x), float64(y)))\n}"} {"input": "package utils\n\nimport (\n\t\"sync\"\n)\n\ntype BeeMap struct {\n\tlock *sync.RWMutex\n\tbm map[interface{}]interface{}\n}\n\n\nfunc NewBeeMap() *BeeMap {\n\treturn &BeeMap{\n\t\tlock: new(sync.RWMutex),\n\t\tbm: make(map[interface{}]interface{}),\n\t}\n}\n\n\nfunc (m *BeeMap) Get(k interface{}) interface{} {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\tif val, ok := m.bm[k]; ok {\n\t\treturn val\n\t}\n\treturn nil\n}\n\n\n\nfunc (m *BeeMap) Set(k interface{}, v interface{}) bool {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tif val, ok := m.bm[k]; !ok {\n\t\tm.bm[k] = v\n\t} else if val != v {\n\t\tm.bm[k] = v\n\t} else {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc (m *BeeMap) Delete(k interface{}) {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tdelete(m.bm, k)\n}\n\n\nfunc (m *BeeMap) Items() map[interface{}]interface{} {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\treturn m.bm\n}\n\nfunc (m *BeeMap) Check(k interface{}) bool ", "output": "{\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\tif _, ok := m.bm[k]; !ok {\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package kthlargest\n\nimport \"container/heap\"\n\ntype MaxHeap struct {\n\tSize int\n\tNums []int\n}\n\nfunc (h *MaxHeap) Insert(x int) {\n\tif h.Len() < h.Size {\n\t\theap.Push(h, x)\n\t} else if h.Nums[0] < x {\n\t\th.Nums[0] = x\n\t\theap.Fix(h, 0)\n\t}\n}\n\n\n\nfunc (h *MaxHeap) Less(i, j int) bool {\n\treturn h.Nums[i] < h.Nums[j]\n}\n\nfunc (h *MaxHeap) Swap(i, j int) {\n\th.Nums[i], h.Nums[j] = h.Nums[j], h.Nums[i]\n}\n\nfunc (h *MaxHeap) Push(x interface{}) {\n\th.Nums = append(h.Nums, x.(int))\n}\n\nfunc (h *MaxHeap) Pop() interface{} {\n\tn := len(h.Nums)\n\tx := h.Nums[n-1]\n\th.Nums = h.Nums[:n-1]\n\treturn x\n}\n\nfunc findKthLargest(nums []int, k int) int {\n\th := &MaxHeap{Size: k}\n\tfor _, num := range nums {\n\t\th.Insert(num)\n\t}\n\treturn h.Nums[0]\n}\n\nfunc (h *MaxHeap) Len() int ", "output": "{ return len(h.Nums) }"} {"input": "package main\n\nimport (\n\t. \"github.com/conclave/pcduino/core\"\n)\n\n\n\nfunc main() {\n\tfor {\n\t\tloop()\n\t}\n}\n\nfunc setup() {\n}\n\nfunc loop() {\n\tDelay(100)\n}\n\nfunc init() ", "output": "{\n\tInit()\n\tsetup()\n}"} {"input": "package imagestreamtag\n\nimport (\n\tkapi \"github.com/GoogleCloudPlatform/kubernetes/pkg/api\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/api/rest\"\n\t\"github.com/projectatomic/atomic-enterprise/pkg/image/api\"\n)\n\n\ntype Registry interface {\n\tGetImageStreamTag(ctx kapi.Context, nameAndTag string) (*api.ImageStreamTag, error)\n\tDeleteImageStreamTag(ctx kapi.Context, nameAndTag string) (*kapi.Status, error)\n}\n\n\ntype Storage interface {\n\trest.Deleter\n\trest.Getter\n}\n\n\ntype storage struct {\n\tStorage\n}\n\n\n\nfunc NewRegistry(s Storage) Registry {\n\treturn &storage{s}\n}\n\n\n\nfunc (s *storage) DeleteImageStreamTag(ctx kapi.Context, nameAndTag string) (*kapi.Status, error) {\n\tobj, err := s.Delete(ctx, nameAndTag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*kapi.Status), err\n}\n\nfunc (s *storage) GetImageStreamTag(ctx kapi.Context, nameAndTag string) (*api.ImageStreamTag, error) ", "output": "{\n\tobj, err := s.Get(ctx, nameAndTag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*api.ImageStreamTag), nil\n}"} {"input": "package iso20022\n\n\ntype ATMTransactionAmounts6 struct {\n\n\tCurrency *ActiveCurrencyCode `xml:\"Ccy,omitempty\"`\n\n\tMaximumPossibleAmount *ImpliedCurrencyAndAmount `xml:\"MaxPssblAmt,omitempty\"`\n\n\tMinimumPossibleAmount *ImpliedCurrencyAndAmount `xml:\"MinPssblAmt,omitempty\"`\n\n\tAdditionalAmount []*ATMTransactionAmounts7 `xml:\"AddtlAmt,omitempty\"`\n}\n\nfunc (a *ATMTransactionAmounts6) SetCurrency(value string) {\n\ta.Currency = (*ActiveCurrencyCode)(&value)\n}\n\n\n\nfunc (a *ATMTransactionAmounts6) SetMinimumPossibleAmount(value, currency string) {\n\ta.MinimumPossibleAmount = NewImpliedCurrencyAndAmount(value, currency)\n}\n\nfunc (a *ATMTransactionAmounts6) AddAdditionalAmount() *ATMTransactionAmounts7 {\n\tnewValue := new(ATMTransactionAmounts7)\n\ta.AdditionalAmount = append(a.AdditionalAmount, newValue)\n\treturn newValue\n}\n\nfunc (a *ATMTransactionAmounts6) SetMaximumPossibleAmount(value, currency string) ", "output": "{\n\ta.MaximumPossibleAmount = NewImpliedCurrencyAndAmount(value, currency)\n}"} {"input": "package handler\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/cosiner/zerver\"\n)\n\ntype MethodHandler interface {\n\tGet(zerver.Request, zerver.Response)\n\tPost(zerver.Request, zerver.Response)\n\tDelete(zerver.Request, zerver.Response)\n\tPut(zerver.Request, zerver.Response)\n\tPatch(zerver.Request, zerver.Response)\n}\n\ntype methodHandler struct {\n\tzerver.Component\n\tMethodHandler\n}\n\nfunc WrapMethodHandler(m MethodHandler) zerver.Handler {\n\treturn &methodHandler{\n\t\tComponent: zerver.NopComponent{},\n\t\tMethodHandler: m,\n\t}\n}\n\nfunc (s methodHandler) Handler(method string) zerver.HandleFunc {\n\tswitch method {\n\tcase zerver.METHOD_GET:\n\t\treturn s.Get\n\tcase zerver.METHOD_POST:\n\t\treturn s.Post\n\tcase zerver.METHOD_DELETE:\n\t\treturn s.Delete\n\tcase zerver.METHOD_PUT:\n\t\treturn s.Put\n\tcase zerver.METHOD_PATCH:\n\t\treturn s.Patch\n\t}\n\n\treturn nil\n}\n\ntype NopMethodHandler struct{}\n\nfunc (NopMethodHandler) Get(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Post(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\n\n\nfunc (NopMethodHandler) Put(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Patch(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Delete(_ zerver.Request, resp zerver.Response) ", "output": "{\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}"} {"input": "package util\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\n\tapi \"github.com/appscode/searchlight/apis/monitoring/v1alpha1\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"kmodules.xyz/client-go/meta\"\n)\n\n\n\nfunc AssignTypeKind(v interface{}) error {\n\tif reflect.ValueOf(v).Kind() != reflect.Ptr {\n\t\treturn fmt.Errorf(\"%v must be a pointer\", v)\n\t}\n\n\tswitch u := v.(type) {\n\tcase *api.ClusterAlert:\n\t\tu.APIVersion = api.SchemeGroupVersion.String()\n\t\tu.Kind = meta.GetKind(v)\n\t\treturn nil\n\tcase *api.NodeAlert:\n\t\tu.APIVersion = api.SchemeGroupVersion.String()\n\t\tu.Kind = meta.GetKind(v)\n\t\treturn nil\n\tcase *api.PodAlert:\n\t\tu.APIVersion = api.SchemeGroupVersion.String()\n\t\tu.Kind = meta.GetKind(v)\n\t\treturn nil\n\t}\n\treturn errors.New(\"unknown api object type\")\n}\n\nfunc GetGroupVersionKind(v interface{}) schema.GroupVersionKind ", "output": "{\n\treturn api.SchemeGroupVersion.WithKind(meta.GetKind(v))\n}"} {"input": "package greeter\n\nimport \"fmt\"\n\n\ntype Greeter interface {\n\tGreet() string\n}\n\ntype lobby struct {\n\ttext string\n}\n\n\n\n\nfunc New(s string) Greeter {\n\tif s == \"\" {\n\t\ts = \"You did not specify me :(\"\n\t}\n\treturn &lobby{\n\t\ttext: s,\n\t}\n}\n\nfunc (l lobby) Greet() string ", "output": "{\n\treturn fmt.Sprintf(\"Greeting with %q\", l.text)\n}"} {"input": "package miner\n\nimport \"net/http\"\n\nconst (\n\tWaitTime = 5\n\n\n\tGET = \"GET\"\n\tPOST = \"POST\"\n\tPOSTJSON = \"POSTJSON\"\n\tPOSTXML = \"POSTXML\"\n\tPOSTFILE = \"POSTFILE\"\n\tPUT = \"PUT\"\n\tPUTJSON = \"PUTJSON\"\n\tPUTXML = \"PUTXML\"\n\tPUTFILE = \"PUTFILE\"\n\tDELETE = \"DELETE\"\n\tOTHER = \"OTHER\" \n\n\n\tHTTPFORMContentType = \"application/x-www-form-urlencoded\"\n\tHTTPJSONContentType = \"application/json\"\n\tHTTPXMLContentType = \"text/xml\"\n\tHTTPFILEContentType = \"multipart/form-data\"\n)\n\nvar (\n\tdefaultUserAgent = \"Marmot\"\n\n\tDefaultHeader = map[string][]string{\n\t\t\"User-Agent\": {\n\t\t\tdefaultUserAgent,\n\t\t},\n\t}\n\n\tDefaultTimeOut = 30\n)\n\n\nfunc SetGlobalTimeout(num int) {\n\tDefaultTimeOut = num\n}\n\n\n\n\n\nfunc CloneHeader(h map[string][]string) map[string][]string {\n\tif h == nil || len(h) == 0 {\n\t\th = DefaultHeader\n\t\treturn h\n\t}\n\n\tif len(h[\"User-Agent\"]) == 0 {\n\t\th[\"User-Agent\"] = []string{defaultUserAgent}\n\t}\n\treturn CopyM(h)\n}\n\nfunc MergeCookie(before []*http.Cookie, after []*http.Cookie) []*http.Cookie ", "output": "{\n\tcs := make(map[string]*http.Cookie)\n\n\tfor _, b := range before {\n\t\tcs[b.Name] = b\n\t}\n\n\tfor _, a := range after {\n\t\tif len(a.Value) > 0 {\n\t\t\tcs[a.Name] = a\n\t\t}\n\t}\n\n\tres := make([]*http.Cookie, 0, len(cs))\n\n\tfor _, q := range cs {\n\t\tres = append(res, q)\n\t}\n\n\treturn res\n\n}"} {"input": "package hr\n\nimport (\n\t\"github.com/blevesearch/bleve/v2/analysis\"\n\t\"github.com/blevesearch/bleve/v2/registry\"\n\n\t\"github.com/blevesearch/bleve/v2/analysis/token/lowercase\"\n\t\"github.com/blevesearch/bleve/v2/analysis/tokenizer/unicode\"\n)\n\n\n\nconst AnalyzerName = \"hr\"\n\n\n\nfunc init() {\n\tregistry.RegisterAnalyzer(AnalyzerName, AnalyzerConstructor)\n}\n\nfunc AnalyzerConstructor(config map[string]interface{}, cache *registry.Cache) (*analysis.Analyzer, error) ", "output": "{\n\tunicodeTokenizer, err := cache.TokenizerNamed(unicode.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttoLowerFilter, err := cache.TokenFilterNamed(lowercase.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstopFilter, err := cache.TokenFilterNamed(StopName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuffixFilter, err := cache.TokenFilterNamed(SuffixTransformationFilterName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstemmerFilter, err := cache.TokenFilterNamed(StemmerName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trv := analysis.Analyzer{\n\t\tTokenizer: unicodeTokenizer,\n\t\tTokenFilters: []analysis.TokenFilter{\n\t\t\ttoLowerFilter,\n\t\t\tstopFilter,\n\t\t\tsuffixFilter,\n\t\t\tstemmerFilter,\n\t\t},\n\t}\n\treturn &rv, nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/aarondl/dbm/config\"\n)\n\nfunc createDatabase(args []string) {\n\tengine, err := NewEngine(config.Current)\n\tif err != nil {\n\t\texitLn(\"Error getting handle to db:\", err)\n\t}\n\tif err = engine.CreateDB(); err != nil {\n\t\texitLn(\"Error creating db:\", err)\n\t}\n\ttrackdbHelper(args, engine)\n}\n\nfunc trackdb(args []string) {\n\tengine, err := NewEngine(config.Current)\n\tif err != nil {\n\t\texitLn(\"Error getting handle to db:\", err)\n\t}\n\ttrackdbHelper(args, engine)\n}\n\nfunc trackdbHelper(args []string, engine SqlEngine) {\n\tif err := engine.Open(); err != nil {\n\t\texitLn(\"Error opening to db:\", err)\n\t}\n\tdefer engine.Close()\n\tif err := engine.CreateMigrationsTable(); err != nil {\n\t\texitLn(\"Error creating migrations table:\", err)\n\t}\n}\n\n\n\nfunc dropDatabase(args []string) ", "output": "{\n\tengine, err := NewEngine(config.Current)\n\tif err != nil {\n\t\texitLn(\"Error getting handle to db:\", err)\n\t}\n\tif err = engine.DropDB(); err != nil {\n\t\texitLn(\"Error dropping db:\", err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"testing\"\n)\n\n\n\nfunc TestAddAll(t *testing.T) ", "output": "{\n\ttests := []struct {\n\t\tinputs []int\n\t}{\n\t\t{inputs: []int{1, 2, 3, 4, 5, 6, 100}},\n\t\t{inputs: []int{100, 131314124, 31231, 1313213, 213231231, 123123131, 123131231}},\n\t}\n\tfor _, test := range tests {\n\t\tvar set IntSet\n\t\tset.AddAll(test.inputs...)\n\t\tfor _, has := range test.inputs {\n\t\t\tif !set.Has(has) {\n\t\t\t\tlog.Fatalf(\"Set does't have %v \\n\", has)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package single\n\nimport (\n\t\"io\"\n\n\t\"github.com/ondrej-smola/mesos-go-http/lib/codec/framing\"\n)\n\ntype Reader struct {\n\tr io.Reader\n}\n\nfunc New(r io.Reader) *Reader {\n\treturn &Reader{r: r}\n}\n\n\n\nfunc NewProvider() framing.Provider {\n\treturn func(r io.Reader) framing.Reader {\n\t\treturn New(r)\n\t}\n}\n\n\n\nfunc (rr *Reader) Read(p []byte) (int, error) {\n\treturn rr.r.Read(p)\n}\n\nfunc (rr *Reader) ReadFrame(p []byte) (endOfFrame bool, n int, err error) ", "output": "{\n\tn, err = rr.r.Read(p)\n\n\tif err == io.EOF {\n\t\tendOfFrame = true\n\t}\n\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype animal struct {\n\tfood string\n\tlocomotion string\n\tnoise string\n}\n\nfunc (a *animal) Eat() {\n\tfmt.Println(a.food)\n}\n\nfunc (a *animal) Move() {\n\tfmt.Println(a.locomotion)\n}\n\n\n\nfunc main() {\n\treader := bufio.NewReader(os.Stdin)\n\n\tfor {\n\t\tfmt.Print(\"> \")\n\t\tinput, _ := reader.ReadString('\\n')\n\t\ts := strings.Split(strings.TrimSpace(input), \" \")\n\n\t\ta := new(animal)\n\t\tswitch s[0] {\n\t\tcase \"cow\":\n\t\t\ta.food = \"grass\"\n\t\t\ta.locomotion = \"walk\"\n\t\t\ta.noise = \"moo\"\n\t\tcase \"bird\":\n\t\t\ta.food = \"worms\"\n\t\t\ta.locomotion = \"fly\"\n\t\t\ta.noise = \"poop\"\n\t\tcase \"snake\":\n\t\t\ta.food = \"mice\"\n\t\t\ta.locomotion = \"slither\"\n\t\t\ta.noise = \"hsss\"\n\t\t}\n\n\t\tswitch s[1] {\n\t\tcase \"eat\":\n\t\t\ta.Eat()\n\t\tcase \"speak\":\n\t\t\ta.Speak()\n\t\tcase \"move\":\n\t\t\ta.Move()\n\t\t}\n\t}\n}\n\nfunc (a *animal) Speak() ", "output": "{\n\tfmt.Println(a.noise)\n}"} {"input": "package mongo\n\nimport (\n\t\"context\"\n\n\t\"github.com/cuigh/swirl/dao\"\n\t\"go.mongodb.org/mongo-driver/bson\"\n)\n\nconst Setting = \"setting\"\n\n\n\nfunc (d *Dao) SettingGet(ctx context.Context, id string) (setting *dao.Setting, err error) {\n\tsetting = &dao.Setting{}\n\tfound, err := d.find(ctx, Setting, id, setting)\n\tif !found {\n\t\treturn nil, err\n\t}\n\treturn\n}\n\nfunc (d *Dao) SettingUpdate(ctx context.Context, setting *dao.Setting) (err error) {\n\tupdate := bson.M{\n\t\t\"$set\": bson.M{\n\t\t\t\"options\": setting.Options,\n\t\t\t\"updated_at\": setting.UpdatedAt,\n\t\t\t\"updated_by\": setting.UpdatedBy,\n\t\t},\n\t}\n\treturn d.upsert(ctx, Setting, setting.ID, update)\n}\n\nfunc (d *Dao) SettingGetAll(ctx context.Context) (settings []*dao.Setting, err error) ", "output": "{\n\tsettings = []*dao.Setting{}\n\terr = d.fetch(ctx, Setting, bson.M{}, &settings)\n\treturn\n}"} {"input": "package queue\n\nimport (\n\t\"fmt\"\n\t\"github.com/apache/servicecomb-service-center/pkg/log\"\n\t\"golang.org/x/net/context\"\n)\n\ntype UniQueue struct {\n\tqueue chan interface{}\n}\n\nfunc (uq *UniQueue) Get(ctx context.Context) interface{} {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil\n\tcase item := <-uq.queue:\n\t\treturn item\n\t}\n}\n\nfunc (uq *UniQueue) Chan() <-chan interface{} {\n\treturn uq.queue\n}\n\nfunc (uq *UniQueue) Put(value interface{}) (e error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.LogPanic(r)\n\n\t\t\te = fmt.Errorf(\"%v\", r)\n\t\t}\n\t}()\n\n\tselect {\n\tcase _, ok := <-uq.queue:\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"channel is closed\")\n\t\t}\n\tdefault:\n\t}\n\n\tselect {\n\tcase uq.queue <- value:\n\tdefault:\n\t}\n\treturn\n}\n\nfunc (uq *UniQueue) Close() {\n\tselect {\n\tcase _, ok := <-uq.queue:\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\tdefault:\n\t}\n\tclose(uq.queue)\n}\n\n\n\nfunc NewUniQueue() (uq *UniQueue) ", "output": "{\n\treturn &UniQueue{\n\t\tqueue: make(chan interface{}, 1),\n\t}\n}"} {"input": "package isolation\n\n\ntype Decorator interface {\n\tDecorate(string) string\n}\n\n\ntype Decorators []Decorator\n\n\n\n\n\nfunc (d Decorators) Decorate(command string) string ", "output": "{\n\tfor _, decorator := range d {\n\t\tcommand = decorator.Decorate(command)\n\t}\n\treturn command\n}"} {"input": "package api\n\nimport (\n\t\"log\"\n)\n\nfunc check(reqs string, client *Client) bool {\n\n\tvar res bool\n\tswitch reqs {\n\n\tcase \"stkpush\":\n\t\tres = checkStkPushRequirements(client)\n\tdefault:\n\t\tres = false\n\t}\n\n\treturn res\n\n}\n\n\n\nfunc checkStkPushRequirements(client *Client) bool ", "output": "{\n\n\tif client.Key == \"\" ||\n\t\tclient.PassKey == \"\" ||\n\t\tclient.TransactionCallback == \"\" ||\n\t\tclient.ShortCode == 0 ||\n\t\tclient.MSISDN == \"\" {\n\t\tlog.Println(`Please make sure you have instantiated the client with the following properties\\n\n\t\t\t\t\t\t 1. Key (Consumer Key)\\n\n\t\t\t\t\t\t 2. TransactionCallback (Callback URL for STK push)\\n\n\t\t\t\t\t\t 3. ShortCode (Lipa Na M-Pesa ShortCode)\\n\n\t\t\t\t\t\t 4. MSISDN (MSISDN - phone number provided for initiating transactions)`)\n\t\treturn false\n\t}\n\n\treturn true\n}"} {"input": "package texture\n\nimport (\n\t. \"github.com/barnex/bruteray/geom\"\n\t. \"github.com/barnex/bruteray/imagef/colorf\"\n)\n\n\ntype Func2D func(u, v float64) Color\n\n\n\n\n\nfunc (f Func2D) At(p Vec) Color {\n\treturn f(p[0], p[1])\n}\n\ntype Func func(p Vec) Color\n\nfunc (f Func) At(p Vec) Color {\n\treturn f(p)\n}\n\nfunc (f Func2D) AtUV(u, v float64) Color ", "output": "{\n\treturn f(u, v)\n}"} {"input": "package ghalloc\n\nimport \"unsafe\"\n\ntype slab struct {\n\tslabClass *slabClass \n\tmemory []byte \n\tfull bool \n\tallocated uint64 \n\tchunkMap uint64 \n}\n\nfunc newSlab(sc *slabClass) *slab {\n\ts := &slab{\n\t\tslabClass: sc,\n\t\tmemory: make([]byte, sc.SlabSize),\n\t\tfull: false,\n\t\tallocated: 0,\n\t}\n\n\treturn s\n}\n\n\n\n\n\nfunc (s *slab) freeChunk(ptr unsafe.Pointer) {\n\tuptr := uintptr(ptr)\n\tbegin := uintptr(unsafe.Pointer(&s.memory[0]))\n\n\tif uptr >= begin && uptr <= uintptr(unsafe.Pointer(&s.memory[0]))+uintptr(s.slabClass.SlabSize) {\n\t\ts.chunkMap &^= 1 << uint64(uptr-begin) % uint64(s.slabClass.SlabSize)\n\n\t\ts.allocated--\n\t\tif s.full {\n\t\t\ts.full = false\n\t\t}\n\t}\n}\n\nfunc (s *slab) getUnusedChunkIndex() uint64 {\n\tvar i uint64\n\n\tfor i = 0; i < s.slabClass.Capacity; i++ {\n\t\tif s.chunkMap&(1<= s.slabClass.Capacity {\n\t\ts.full = true\n\t}\n\n\treturn ptr\n}"} {"input": "package model\n\ntype Interface interface {\n\tVisitString(name string, resume func())\n\tVisitInt(name string, resume func())\n\tVisitFloat(name string, resume func())\n\tVisitBool(name string, resume func())\n\tVisitPtr(name string, resume func())\n\tVisitBytes(name string, resume func())\n\tVisitSlice(name string, resume func())\n\tVisitStruct(name string, fields []Field, resume func())\n\tVisitStructField(field Field, resume func())\n\tVisitMap(name string, resume func())\n\tVisitCustom(name string, resume func())\n\tVisitReference(name string, resume func())\n}\n\ntype Visitor struct{}\n\nfunc (self *Visitor) VisitString(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitInt(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitFloat(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBool(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitPtr(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBytes(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitSlice(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStructField(field Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitMap(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitCustom(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitReference(name string, resume func()) {\n\tresume()\n}\n\ntype EmbeddedStructVisitor struct {\n\tInterface\n}\n\n\n\nfunc (self *EmbeddedStructVisitor) VisitStruct(name string, fields []Field, resume func()) ", "output": "{\n\tresume()\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/minio/cli\"\n\t\"github.com/minio/mc/pkg/probe\"\n)\n\nvar adminUserSvcAcctRemoveCmd = cli.Command{\n\tName: \"rm\",\n\tUsage: \"Remove a service account\",\n\tAction: mainAdminUserSvcAcctRemove,\n\tOnUsageError: onUsageError,\n\tBefore: setGlobalsFromContext,\n\tFlags: globalFlags,\n\tCustomHelpTemplate: `NAME:\n {{.HelpName}} - {{.Usage}}\n\nUSAGE:\n {{.HelpName}} ALIAS SERVICE-ACCOUNT\n\nFLAGS:\n {{range .VisibleFlags}}{{.}}\n {{end}}\nEXAMPLES:\n 1. Remove the service account 'J123C4ZXEQN8RK6ND35I' from MinIO server.\n {{.Prompt}} {{.HelpName}} myminio/ J123C4ZXEQN8RK6ND35I\n`,\n}\n\n\nfunc checkAdminUserSvcAcctRemoveSyntax(ctx *cli.Context) {\n\tif len(ctx.Args()) != 2 {\n\t\tfatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),\n\t\t\t\"Incorrect number of arguments for user svcacct rm command.\")\n\t}\n}\n\n\n\n\nfunc mainAdminUserSvcAcctRemove(ctx *cli.Context) error ", "output": "{\n\tcheckAdminUserSvcAcctRemoveSyntax(ctx)\n\n\targs := ctx.Args()\n\taliasedURL := args.Get(0)\n\tsvcAccount := args.Get(1)\n\n\tclient, err := newAdminClient(aliasedURL)\n\tfatalIf(err, \"Unable to initialize admin connection.\")\n\n\te := client.DeleteServiceAccount(globalContext, svcAccount)\n\tfatalIf(probe.NewError(e).Trace(args...), \"Unable to remove a new service account\")\n\n\tprintMsg(svcAcctMessage{\n\t\top: \"ls\",\n\t\tAccessKey: svcAccount,\n\t})\n\n\treturn nil\n}"} {"input": "package models\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\nfunc TestFixturesAreConsistent(t *testing.T) {\n\tassert.NoError(t, PrepareTestDatabase())\n\tCheckConsistencyForAll(t)\n}\n\n\n\nfunc TestMain(m *testing.M) ", "output": "{\n\tMainTest(m, \"..\")\n}"} {"input": "package comparisons\n\nimport \"jvmgo/ch05/instructions/base\"\nimport \"jvmgo/ch05/rtda\"\n\n\ntype IF_ACMPEQ struct{ base.BranchInstruction }\n\n\n\ntype IF_ACMPNE struct{ base.BranchInstruction }\n\nfunc (self *IF_ACMPNE) Execute(frame *rtda.Frame) {\n\tif !_acmp(frame) {\n\t\tbase.Branch(frame, self.Offset)\n\t}\n}\n\nfunc _acmp(frame *rtda.Frame) bool {\n\tstack := frame.OperandStack()\n\tref2 := stack.PopRef()\n\tref1 := stack.PopRef()\n\treturn ref1 == ref2 \n}\n\nfunc (self *IF_ACMPEQ) Execute(frame *rtda.Frame) ", "output": "{\n\tif _acmp(frame) {\n\t\tbase.Branch(frame, self.Offset)\n\t}\n}"} {"input": "package os\n\nimport \"syscall\"\n\nfunc isSymlink(stat *syscall.Stat_t) bool {\n\treturn stat.Mode&syscall.S_IFMT == syscall.S_IFLNK\n}\n\n\n\nfunc fileInfoFromStat(name string, fi *FileInfo, lstat, stat *syscall.Stat_t) *FileInfo ", "output": "{\n\tfi.Dev = stat.Dev\n\tfi.Ino = stat.Ino\n\tfi.Nlink = uint64(stat.Nlink)\n\tfi.Mode = stat.Mode\n\tfi.Uid = int(stat.Uid)\n\tfi.Gid = int(stat.Gid)\n\tfi.Rdev = stat.Rdev\n\tfi.Size = stat.Size\n\tfi.Blksize = int64(stat.Blksize)\n\tfi.Blocks = stat.Blocks\n\tfi.Atime_ns = syscall.TimespecToNsec(stat.Atim)\n\tfi.Mtime_ns = syscall.TimespecToNsec(stat.Mtim)\n\tfi.Ctime_ns = syscall.TimespecToNsec(stat.Ctim)\n\tfi.Name = basename(name)\n\tif isSymlink(lstat) && !isSymlink(stat) {\n\t\tfi.FollowedSymlink = true\n\t}\n\treturn fi\n}"} {"input": "package web\n\nfunc SetBaseUrl(baseUrl string) {\n\tclient.setBaseUrl(baseUrl)\n}\n\n\n\nfunc SetNodeId(nodeId int) {\n\tclient.setNodeId(nodeId)\n}\n\nfunc SetKey(key string) ", "output": "{\n\tclient.setKey(key)\n}"} {"input": "package file\n\nimport \"github.com/sandreas/graft/designpattern/observer\"\n\ntype WalkObserver struct {\n\tdesignpattern.ObserverInterface\n\titemCount int64\n\tmatchCount int64\n\terrorCount int64\n\tforceShow bool\n\toutputCallback func(format string, a ...interface{}) (int, error)\n\tInterval int64\n}\n\nfunc NewWalkObserver(handle func(format string, a ...interface{}) (int, error)) *WalkObserver {\n\treturn &WalkObserver{\n\t\tInterval: 100,\n\t\toutputCallback: handle,\n\t}\n}\n\nfunc (ph *WalkObserver) Notify(a ...interface{}) {\n\tif a[0] == LocatorIncreaseItems {\n\t\tph.forceShow = ph.itemCount == 0\n\t\tph.itemCount++\n\t}\n\n\tif a[0] == LocatorIncreaseErrors {\n\t\tph.forceShow = ph.errorCount == 0\n\t\tph.errorCount++\n\t}\n\n\tif a[0] == LocatorIncreaseMatches {\n\t\tph.forceShow = ph.matchCount == 0\n\t\tph.itemCount++\n\t\tph.matchCount++\n\t}\n\n\tif a[0] == LocatorFinish {\n\t\tph.forceShow = true\n\t}\n\n\tph.showProgress()\n\n\tif a[0] == LocatorFinish {\n\t\tph.outputCallback(\"\\n\")\n\t}\n}\n\n\n\nfunc (ph *WalkObserver) showProgress() ", "output": "{\n\tif !ph.forceShow && ph.itemCount%ph.Interval != 0 {\n\t\treturn\n\t}\n\n\tif ph.errorCount == 0 {\n\t\tph.outputCallback(\"\\rscanning - total: %d, matches: %d\", ph.itemCount, ph.matchCount)\n\t} else {\n\t\tph.outputCallback(\"\\rscanning - total: %d, matches: %d, errors: %d\", ph.itemCount, ph.matchCount, ph.errorCount)\n\t}\n\n\tif ph.itemCount > ph.Interval*10 {\n\t\tph.Interval = 500\n\t}\n}"} {"input": "package v1beta1\n\nimport (\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\trest \"github.com/hyperhq/client-go/rest\"\n\tv1beta1 \"k8s.io/metrics/pkg/apis/metrics/v1beta1\"\n\t\"k8s.io/metrics/pkg/client/clientset_generated/clientset/scheme\"\n)\n\ntype MetricsV1beta1Interface interface {\n\tRESTClient() rest.Interface\n\tNodeMetricsesGetter\n\tPodMetricsesGetter\n}\n\n\ntype MetricsV1beta1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *MetricsV1beta1Client) NodeMetricses() NodeMetricsInterface {\n\treturn newNodeMetricses(c)\n}\n\nfunc (c *MetricsV1beta1Client) PodMetricses(namespace string) PodMetricsInterface {\n\treturn newPodMetricses(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*MetricsV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &MetricsV1beta1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *MetricsV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *MetricsV1beta1Client {\n\treturn &MetricsV1beta1Client{c}\n}\n\n\n\n\n\nfunc (c *MetricsV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc setConfigDefaults(config *rest.Config) error ", "output": "{\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/apier/v1\"\n\nfunc init() {\n\tc := &CmdRemoveActions{\n\t\tname: \"actions_remove\",\n\t\trpcMethod: \"ApierV1.RemoveActions\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdRemoveActions struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrRemoveActions\n\t*CommandExecuter\n}\n\nfunc (self *CmdRemoveActions) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdRemoveActions) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\n\n\nfunc (self *CmdRemoveActions) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdRemoveActions) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *CmdRemoveActions) RpcParams(reset bool) interface{} ", "output": "{\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrRemoveActions{}\n\t}\n\treturn self.rpcParams\n}"} {"input": "package wraps\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-on/wrap\"\n)\n\ntype first []http.Handler\n\nfunc (f first) ServeHTTPNext(inner http.Handler, wr http.ResponseWriter, req *http.Request) {\n\tchecked := wrap.NewPeek(wr, func(ck *wrap.Peek) bool {\n\t\tck.FlushHeaders()\n\t\tck.FlushCode()\n\t\treturn true\n\t})\n\n\tfor _, h := range f {\n\t\th.ServeHTTP(checked, req)\n\t\tif checked.HasChanged() {\n\t\t\tchecked.FlushMissing()\n\t\t\treturn\n\t\t}\n\t}\n\tinner.ServeHTTP(wr, req)\n}\n\n\n\n\n\nfunc First(handler ...http.Handler) wrap.Wrapper { return first(handler) }\n\n\nfunc FirstFunc(handlerFn ...func(w http.ResponseWriter, r *http.Request)) wrap.Wrapper {\n\th := make([]http.Handler, len(handlerFn))\n\tfor i, fn := range handlerFn {\n\t\th[i] = http.HandlerFunc(fn)\n\t}\n\treturn first(h)\n}\n\nfunc (f first) Wrap(next http.Handler) http.Handler ", "output": "{\n\treturn wrap.NextHandler(f).Wrap(next)\n}"} {"input": "package plugins\n\nimport (\n\t\"../answers\"\n\t\"../ircclient\"\n\t\"strings\"\n)\n\ntype DongPlugin struct {\n\tic *ircclient.IRCClient\n}\n\nfunc (q *DongPlugin) String() string {\n\treturn \"dong\"\n}\n\nfunc (q *DongPlugin) Info() string {\n\treturn `sends back a dong sound for every \\a`\n}\n\nfunc (q *DongPlugin) Usage(cmd string) string {\n\treturn \"\"\n}\n\n\n\nfunc (q *DongPlugin) Unregister() {\n\treturn\n}\n\nfunc (q *DongPlugin) ProcessLine(msg *ircclient.IRCMessage) {\n\tif msg.Command != \"PRIVMSG\" {\n\t\treturn\n\t}\n\n\tcount := strings.Count(msg.Args[0], `\\a`)\n\tcount -= strings.Count(msg.Args[0], `\\\\a`)\n\tif count < 1 {\n\t\treturn\n\t}\n\n\tstr := answers.RandStr(\"dong\")\n\tmessage := \"\"\n\n\tfor i := 0; i < count; i++ {\n\t\tmessage += str + \" \"\n\t}\n\n\tq.ic.ReplyMsg(msg, message)\n}\n\nfunc (q *DongPlugin) ProcessCommand(cmd *ircclient.IRCCommand) {\n\treturn\n}\n\nfunc (q *DongPlugin) Register(cl *ircclient.IRCClient) ", "output": "{\n\tq.ic = cl\n}"} {"input": "package api\n\ntype Memstore map[string]*Collection\n\nfunc (m Memstore) Init(dbName string) error {\n\treturn nil\n}\n\nfunc (m Memstore) CreateCollection(slug, name string) (Collection, error) {\n\tm[slug] = &Collection{Name: name,\n\t\tSlug: slug,\n\t\tItems: map[string]Item{},\n\t}\n\treturn *m[slug], nil\n}\n\nfunc (m Memstore) UpdateCollection(slug, name string) error {\n\tif c, ok := m[slug]; !ok {\n\t\treturn CollectionNotFoundError\n\t} else {\n\t\tc.Name = name\n\t}\n\treturn nil\n}\n\nfunc (m Memstore) GetCollectionData(slug string) (Collection, error) {\n\tif c, ok := m[slug]; ok {\n\t\t(*c).Items = nil\n\t\treturn *c, nil\n\t}\n\treturn Collection{}, CollectionNotFoundError\n}\n\n\n\nfunc (m Memstore) AddItemToCollection(slug string, item Item) error {\n\tif c, ok := m[slug]; ok {\n\t\tc.Items[item.Tag] = item\n\t\treturn nil\n\t}\n\treturn CollectionNotFoundError\n}\n\nfunc (m Memstore) GetItemFromCollection(slug, tag string) (Item, error) {\n\tif _, ok := m[slug]; !ok {\n\t\treturn Item{}, CollectionNotFoundError\n\t}\n\tif _, ok := m[slug].Items[tag]; !ok {\n\t\treturn Item{}, BlobNotFoundError\n\t}\n\treturn m[slug].Items[tag], nil\n}\n\nfunc (m Memstore) GetCollectionItems(slug string) (map[string]Item, error) ", "output": "{\n\tif c, ok := m[slug]; ok {\n\t\treturn c.Items, nil\n\t}\n\treturn map[string]Item{}, CollectionNotFoundError\n}"} {"input": "package main\n\nimport . \"g2d\"\n\nvar arena = NewArena(Point{480, 360})\nvar a1 = NewAlien(arena, Point{40, 40})\nvar a2 = NewAlien(arena, Point{80, 80})\n\ntype Alien struct {\n arena *Arena\n x, y, w, h int\n xmin, xmax int\n dx, dy int\n}\n\nfunc NewAlien(arena *Arena, pos Point) *Alien {\n a := &Alien{arena, pos.X, pos.Y, 20, 20, pos.X, pos.X+150, 5, 5}\n arena.Add(a)\n return a\n}\n\n\n\nfunc (a *Alien) Position() Point {\n return Point{a.x, a.y}\n}\n\nfunc (a *Alien) Size() Point {\n return Point{a.w, a.h}\n}\n\nfunc (a *Alien) Symbol() Point {\n return Point{0, 0}\n}\n\nfunc (a *Alien) Collide(other Actor) {\n}\n\nfunc tick() {\n ClearCanvas()\n arena.MoveAll()\n for _, actor := range arena.Actors() {\n FillRect(actor.Position(), actor.Size())\n }\n}\n\nfunc main() {\n InitCanvas(arena.Size())\n MainLoop(tick)\n}\n\nfunc (a *Alien) Move() ", "output": "{\n if a.xmin <= a.x+a.dx && a.x+a.dx <= a.xmax {\n a.x += a.dx\n } else {\n a.dx = -a.dx\n a.y += a.dy\n }\n}"} {"input": "package main\n\nimport (\n\t\"crypto/rand\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc newSecret(size int) *[]byte {\n\tbytes := make([]byte, size)\n\n\t_, err := io.ReadFull(rand.Reader, bytes)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn &bytes\n}\n\n\n\nfunc readSecretFrom(fname string) (*[]byte, error) {\n\tbytes, err := ioutil.ReadFile(fname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &bytes, nil\n}\n\nfunc saveSecretTo(fname string, s *[]byte) error ", "output": "{\n\terr := ioutil.WriteFile(fname, *s, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.Chmod(fname, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\nfunc main() {\n\tvar count uint64\n\tfmt.Scan(&count)\n\tarray := make([]uint64, count)\n\tfor i := range array {\n\t\tfmt.Scan(&array[i])\n\t}\n\tfmt.Println(SumArray(array))\n}\n\nfunc SumArray(arr []uint64) uint64 ", "output": "{\n\tvar sum uint64\n\tfor _, i := range arr {\n\t\tsum += i\n\t}\n\treturn sum\n}"} {"input": "package test\n\nimport (\n\t\"debug/macho\"\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/bazelbuild/rules_go/go/tools/bazel\"\n)\n\n\n\nfunc TestPIE(t *testing.T) {\n\tm, err := openMachO(\"tests/core/go_binary\", \"hello_pie_bin\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif m.Flags&macho.FlagPIE == 0 {\n\t\tt.Error(\"ELF binary is not position-independent.\")\n\t}\n}\n\nfunc openMachO(dir, bin string) (*macho.File, error) ", "output": "{\n\tbin, ok := bazel.FindBinary(dir, bin)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"could not find binary: %s\", bin)\n\t}\n\n\tf, err := os.Open(bin)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn macho.NewFile(f)\n}"} {"input": "package reflect\n\nimport (\n\t\"unsafe\"\n)\n\n\n\ntype makeFuncImpl struct {\n\tcode uintptr\n\tstack *bitVector \n\ttyp *funcType\n\tfn func([]Value) []Value\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc MakeFunc(typ Type, fn func(args []Value) (results []Value)) Value {\n\tif typ.Kind() != Func {\n\t\tpanic(\"reflect: call of MakeFunc with non-Func type\")\n\t}\n\n\tt := typ.common()\n\tftyp := (*funcType)(unsafe.Pointer(t))\n\n\tdummy := makeFuncStub\n\tcode := **(**uintptr)(unsafe.Pointer(&dummy))\n\n\t_, _, _, stack, _ := funcLayout(t, nil)\n\n\timpl := &makeFuncImpl{code: code, stack: stack, typ: ftyp, fn: fn}\n\n\treturn Value{t, unsafe.Pointer(impl), flag(Func)}\n}\n\n\n\n\n\n\nfunc makeFuncStub()\n\ntype methodValue struct {\n\tfn uintptr\n\tstack *bitVector \n\tmethod int\n\trcvr Value\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc methodValueCall()\n\nfunc makeMethodValue(op string, v Value) Value ", "output": "{\n\tif v.flag&flagMethod == 0 {\n\t\tpanic(\"reflect: internal error: invalid use of makeMethodValue\")\n\t}\n\n\tfl := v.flag & (flagRO | flagAddr | flagIndir)\n\tfl |= flag(v.typ.Kind())\n\trcvr := Value{v.typ, v.ptr, fl}\n\n\tfuncType := v.Type().(*rtype)\n\n\tdummy := methodValueCall\n\tcode := **(**uintptr)(unsafe.Pointer(&dummy))\n\n\t_, _, _, stack, _ := funcLayout(funcType, nil)\n\n\tfv := &methodValue{\n\t\tfn: code,\n\t\tstack: stack,\n\t\tmethod: int(v.flag) >> flagMethodShift,\n\t\trcvr: rcvr,\n\t}\n\n\tmethodReceiver(op, fv.rcvr, fv.method)\n\n\treturn Value{funcType, unsafe.Pointer(fv), v.flag&flagRO | flag(Func)}\n}"} {"input": "package utils\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n\n\t\"github.com/astaxie/beego\"\n)\n\nvar testRandNum int\nvar testRandString string\n\n\nfunc SetTestRandNum(n int) {\n\tif !IsTest() {\n\t\treturn\n\t}\n\n\ttestRandNum = n\n}\n\n\n\n\n\nfunc SetTestRandString(s string) {\n\tif !IsTest() {\n\t\treturn\n\t}\n\n\ttestRandString = s\n}\n\n\nfunc GetRandString(n int) string {\n\tif IsTest() {\n\t\treturn testRandString\n\t}\n\n\trs2Letters := beego.AppConfig.String(\"randKey\")\n\n\tb := make([]byte, n)\n\tfor i := range b {\n\t\tb[i] = rs2Letters[rand.Intn(len(rs2Letters))]\n\t}\n\n\treturn string(b)\n}\n\nfunc GetRandNum(n int) int ", "output": "{\n\tif IsTest() {\n\t\treturn testRandNum\n\t}\n\n\trand.Seed(time.Now().UnixNano())\n\n\treturn rand.Intn(n)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\tlog \"github.com/lxc/lxd/shared/log15\"\n\n\t\"github.com/lxc/lxd/shared\"\n\t\"github.com/lxc/lxd/shared/cmd\"\n\t\"github.com/lxc/lxd/shared/logger\"\n\t\"github.com/lxc/lxd/shared/logging\"\n\t\"github.com/lxc/lxd/shared/version\"\n)\n\n\ntype SubCommand func(*Args) error\n\n\n\n\ntype SubCommandError struct {\n\tCode int\n\tMessage string\n}\n\nfunc (e *SubCommandError) Error() string {\n\treturn e.Message\n}\n\n\n\nfunc SubCommandErrorf(code int, format string, a ...interface{}) *SubCommandError {\n\treturn &SubCommandError{\n\t\tCode: code,\n\t\tMessage: fmt.Sprintf(format, a...),\n\t}\n}\n\n\n\n\n\n\n\n\n\nfunc RunSubCommand(command SubCommand, ctx *cmd.Context, args *Args, handler log.Handler) int {\n\tif args.Help {\n\t\tctx.Output(usage)\n\t\treturn 0\n\t}\n\tif args.Version {\n\t\tctx.Output(\"%s\\n\", version.Version)\n\t\treturn 0\n\t}\n\n\terr := setupSubCommand(ctx, args, handler)\n\tif err == nil {\n\t\terr = command(args)\n\t}\n\tif err != nil {\n\t\tcode := 1\n\t\tmessage := err.Error()\n\t\tsubCommandError, ok := err.(*SubCommandError)\n\t\tif ok {\n\t\t\tcode = subCommandError.Code\n\t\t}\n\t\tif message != \"\" {\n\t\t\tctx.Error(fmt.Sprintf(\"error: %s\\n\", message))\n\t\t}\n\t\treturn code\n\t}\n\treturn 0\n}\n\n\n\n\nfunc setupSubCommand(context *cmd.Context, args *Args, handler log.Handler) error ", "output": "{\n\tif len(shared.VarPath(\"unix.sock\")) > 107 {\n\t\treturn fmt.Errorf(\"LXD_DIR is too long, must be < %d\", 107-len(\"unix.sock\"))\n\t}\n\n\tsyslog := \"\"\n\tif args.Syslog {\n\t\tsyslog = \"lxd\"\n\t}\n\n\tvar err error\n\tlogger.Log, err = logging.GetLogger(syslog, args.Logfile, args.Verbose, args.Debug, handler)\n\tif err != nil {\n\t\tcontext.Output(\"%v\\n\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package viewmodel\n\nimport \"github.com/airlingo/airlingo/model\"\n\ntype Settings struct {\n\tCurrentUser *model.User\n\tName string\n\tTranslationLanguage *model.Language\n\tTranslationLanguages []*model.Language\n}\n\n\n\nfunc (c *Settings) GetTranslationLanguageID() string {\n\tif c.TranslationLanguage == nil {\n\t\treturn \"\"\n\t}\n\n\treturn c.TranslationLanguage.ID\n}\n\nfunc NewSettings(currentUser *model.User, name string, translationLanguageID *string, translationLanguages []*model.Language) *Settings ", "output": "{\n\tsettings := &Settings{\n\t\tCurrentUser: currentUser,\n\t\tName: name,\n\t\tTranslationLanguages: translationLanguages,\n\t}\n\n\tif translationLanguageID != nil {\n\t\tfor _, language := range translationLanguages {\n\t\t\tif language.ID == *translationLanguageID {\n\t\t\t\tsettings.TranslationLanguage = language\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn settings\n}"} {"input": "package quit\n\nimport (\n\t\"fmt\"\n\t\"github.com/talpah/cortana/plugins\"\n\t\"regexp\"\n\t\"os\"\n)\n\nvar (\n\tcanonicalCommand = \"quit\"\n\tcommand = `(Q|q)uit`\n\taliases map[string]*regexp.Regexp\n)\n\nfunc isAlias(cmd string) bool {\n\tfor _, alias := range aliases {\n\t\tif alias.MatchString(cmd) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\n\nfunc Initialize(pins plugins.PluginManager) {\n\taliases = map[string]*regexp.Regexp{\n\t\t\"Exit\": regexp.MustCompile(`(E|e)xit`),\n\n\t}\n\n\tpins.Register(\n\t\tcanonicalCommand,\n\t\tcommand,\n\t\tQuit,\n\t\tHelp,\n\t\taliases,\n\t)\n}\n\nfunc Help(cmd string) (string, error) {\n\treturn `Quit command help\n\nQuit will... quit\n\nUsage example:\nquit\nQuit\nexit\nExit\n`, nil\n}\n\nfunc Quit(cmd string) (string, error) {\n\tif !canHandle(cmd) {\n\t\treturn \"\", fmt.Errorf(\"Can't handle command %s\", cmd)\n\t}\n\tos.Exit(0)\n\treturn \"\", nil\n}\n\nfunc canHandle(cmd string) bool ", "output": "{\n\tif regexp.MustCompile(command).MatchString(cmd) {\n\t\treturn true\n\t}\n\n\treturn isAlias(cmd)\n}"} {"input": "package wml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/wml\"\n)\n\nfunc TestEG_RubyContentConstructor(t *testing.T) {\n\tv := wml.NewEG_RubyContent()\n\tif v == nil {\n\t\tt.Errorf(\"wml.NewEG_RubyContent must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed wml.EG_RubyContent should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestEG_RubyContentMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := wml.NewEG_RubyContent()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := wml.NewEG_RubyContent()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package firestore \n\nimport (\n\t\"context\"\n\t\"runtime\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"google.golang.org/grpc/metadata\"\n)\n\n\n\n\nfunc DefaultAuthScopes() []string {\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t\t\"https:www.googleapis.com/auth/datastore\",\n\t}\n}\n\n\n\nfunc versionGo() string {\n\tconst develPrefix = \"devel +\"\n\n\ts := runtime.Version()\n\tif strings.HasPrefix(s, develPrefix) {\n\t\ts = s[len(develPrefix):]\n\t\tif p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 {\n\t\t\ts = s[:p]\n\t\t}\n\t\treturn s\n\t}\n\n\tnotSemverRune := func(r rune) bool {\n\t\treturn strings.IndexRune(\"0123456789.\", r) < 0\n\t}\n\n\tif strings.HasPrefix(s, \"go1\") {\n\t\ts = s[2:]\n\t\tvar prerelease string\n\t\tif p := strings.IndexFunc(s, notSemverRune); p >= 0 {\n\t\t\ts, prerelease = s[:p], s[p:]\n\t\t}\n\t\tif strings.HasSuffix(s, \".\") {\n\t\t\ts += \"0\"\n\t\t} else if strings.Count(s, \".\") < 2 {\n\t\t\ts += \".0\"\n\t\t}\n\t\tif prerelease != \"\" {\n\t\t\ts += \"-\" + prerelease\n\t\t}\n\t\treturn s\n\t}\n\treturn \"UNKNOWN\"\n}\n\nconst versionClient = \"20190110\"\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context ", "output": "{\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}"} {"input": "package output\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"log\"\n\n\t\"github.com/mesilliac/pulse-simple\"\n)\n\ntype output struct {\n\tst *pulse.Stream\n}\n\nfunc get(sampleRate, channels int) (Output, error) {\n\to := new(output)\n\tvar err error\n\tss := pulse.SampleSpec{pulse.SAMPLE_FLOAT32LE, uint32(sampleRate), uint8(channels)}\n\to.st, err = pulse.Playback(\"moggio\", \"moggio\", &ss)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn o, nil\n}\n\n\n\nfunc (o *output) Start() {\n}\n\nfunc (o *output) Stop() {\n}\n\nfunc (o *output) Push(samples []float32) ", "output": "{\n\tbuf := new(bytes.Buffer)\n\tfor _, s := range samples {\n\t\t_ = binary.Write(buf, binary.LittleEndian, s)\n\t}\n\t_, err := o.st.Write(buf.Bytes())\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}"} {"input": "package operations\n\nimport (\n\t\"github.com/asuleymanov/golos-go/encoding/transaction\"\n)\n\n\ntype BreakFreeReferralOperation struct {\n\tReferral string `json:\"referral\"`\n\tExtensions []interface{} `json:\"extensions\"`\n}\n\n\nfunc (op *BreakFreeReferralOperation) Type() OpType {\n\treturn TypeBreakFreeReferral\n}\n\n\n\n\n\nfunc (op *BreakFreeReferralOperation) MarshalTransaction(encoder *transaction.Encoder) error {\n\tenc := transaction.NewRollingEncoder(encoder)\n\tenc.EncodeUVarint(uint64(TypeBreakFreeReferral.Code()))\n\tenc.Encode(op.Referral)\n\tenc.Encode(byte(0))\n\treturn enc.Err()\n}\n\nfunc (op *BreakFreeReferralOperation) Data() interface{} ", "output": "{\n\treturn op\n}"} {"input": "package upcrmmodel\n\nimport (\n\t\"encoding/json\"\n\t. \"github.com/smartystreets/goconvey/convey\"\n\t\"go-common/library/time\"\n\t\"testing\"\n\txtime \"time\"\n)\n\n\n\nfunc Test_Orm(t *testing.T) ", "output": "{\n\tvar (\n\t\targ = ArgCreditLogAdd{\n\t\t\tBusinessType: 1,\n\t\t\tType: 1,\n\t\t\tOpType: 2,\n\t\t\tReason: 101,\n\t\t\tMid: 12345,\n\t\t\tOid: 13021,\n\t\t\tUID: 1,\n\t\t\tContent: \"稿件打回\",\n\t\t\tCTime: time.Time(xtime.Now().Unix()),\n\t\t\tExtra: []byte(\"{ \\\"key\\\" : \\\"value\\\"}\"),\n\t\t}\n\t)\n\tConvey(\"orm\", t, func() {\n\t\tConvey(\"connect\", func() {\n\t\t\tvar js, _ = json.Marshal(arg)\n\t\t\tt.Log(string(js))\n\t\t})\n\t})\n}"} {"input": "package http_test\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"testing\"\n\n\thttpFetcher \"github.com/wanelo/image-server/fetcher/http\"\n\n\t. \"github.com/wanelo/image-server/test\"\n)\n\n\n\nfunc TestUniqueFetcherOnEmptyFiles(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"image/jpeg\")\n\t\tfmt.Fprintf(w, ``)\n\t}))\n\tdefer ts.Close()\n\n\tf := &httpFetcher.Fetcher{}\n\n\tdefer os.Remove(\"blank.jpg\")\n\terr := f.Fetch(ts.URL, \"blank.jpg\")\n\n\tEquals(t, \"File is empty\", fmt.Sprintf(\"%s\", err))\n}\n\nfunc TestURLEscaping(t *testing.T) {\n\tpath := \"//hell[o]/(x)//two%20words/boo.jpg?something=fo(o)\"\n\texpectedPath := \"/hell[o]/(x)//two%20words/boo.jpg?something=fo(o)\"\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.RequestURI != expectedPath {\n\t\t\tt.Fail()\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"image/jpeg\")\n\t\tfmt.Fprintln(w, `there is some content`)\n\t}))\n\tdefer ts.Close()\n\n\tf := &httpFetcher.Fetcher{}\n\tdefer os.Remove(\"valid\")\n\terr := f.Fetch(ts.URL+path, \"valid\")\n\n\tOk(t, err)\n}\n\nfunc TestUniqueFetcher(t *testing.T) ", "output": "{\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"image/jpeg\")\n\t\tfmt.Fprintln(w, `there is some content`)\n\t}))\n\tdefer ts.Close()\n\n\tf := &httpFetcher.Fetcher{}\n\n\tdefer os.Remove(\"valid\")\n\terr := f.Fetch(ts.URL, \"valid\")\n\n\tOk(t, err)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/zlowram/gocli\"\n)\n\n\n\nfunc main() {\n\tflag.Parse()\n\tc := gocli.NewCli(\n\t\t\"TestCli\",\n\t\t\"Short description for this cli\",\n\t\tflag.Args(),\n\t)\n\tcmd1 := gocli.Command{\n\t\tName: \"subcmd1\",\n\t\tShortName: \"s1\",\n\t\tDescription: \"short description of the subcmd1\",\n\t\tUsageLine: `TestCli subcmd1 [options] {args}\n\n The options are:\n -f\n string flag f default value\n -s\n bool flag s\n\n `,\n\t}\n\tflag1 := cmd1.Flag.String(\"f\", \"default\", \"\")\n\tflag2 := cmd1.Flag.Bool(\"s\", false, \"\")\n\tcmd1.Run = func(c gocli.Command) error {\n\t\treturn testCmd1Run(c, *flag1, *flag2, \"String test for Cmd1\")\n\t}\n\n\tcmd2 := gocli.Command{\n\t\tName: \"subcmd2\",\n\t\tShortName: \"s2\",\n\t\tDescription: \"short description of the subcmd2\",\n\t\tUsageLine: `TestCli subcmd2 [options] {args}\n `,\n\t\tRun: func(tc gocli.Command) error {\n\t\t\tfmt.Println(\"This is the Run method for the subcmd2 command, with no flags and no args\")\n\t\t\treturn nil\n\t\t},\n\t}\n\tc.Commands = []gocli.Command{cmd1, cmd2}\n\tif err := c.Handle(); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc testCmd1Run(tc gocli.Command, flag1 string, flag2 bool, str string) error ", "output": "{\n\tif tc.Flag.NArg() < 2 {\n\t\ttc.Usage()\n\t\treturn nil\n\t}\n\n\tfmt.Println(\"This is the Run method for the subcmd1 command, with flags and args\")\n\n\tfmt.Println(\"The value of the flag -f is:\", flag1)\n\tif flag2 {\n\t\tfmt.Println(\"The bool flag -s is set\")\n\t} else {\n\t\tfmt.Println(\"The bool flag -s is not set\")\n\t}\n\tfmt.Println(\"The str value is:\", str)\n\tfmt.Println(\"The first argument value is:\", tc.Flag.Arg(0))\n\tfmt.Println(\"The second argument value is:\", tc.Flag.Arg(1))\n\treturn nil\n}"} {"input": "package ginkgoext\n\nimport (\n\t\"github.com/onsi/gomega/types\"\n)\n\ntype anythingMatcher struct{}\n\nfunc (matcher *anythingMatcher) Match(actual interface{}) (success bool, err error) {\n\treturn true, nil\n}\n\nfunc (matcher *anythingMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn \"\"\n}\n\n\n\n\nfunc BeAnything() types.GomegaMatcher {\n\treturn &anythingMatcher{}\n}\n\nfunc (matcher *anythingMatcher) NegatedFailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn \"\"\n}"} {"input": "package fritz\n\nimport (\n\t\"unicode/utf16\"\n\t\"unicode/utf8\"\n)\n\n\n\nfunc consumeNextRune(p []byte) ([]byte, int) {\n\tr, size := utf8.DecodeRune(p)\n\tif r <= 0xffff {\n\t\treturn []byte{uint8(r), uint8(r >> 8)}, size\n\t}\n\tr1, r2 := utf16.EncodeRune(r)\n\treturn []byte{uint8(r1), uint8(r1 >> 8), uint8(r2), uint8(r2 >> 8)}, size\n}\n\nfunc utf8To16LE(p []byte) []byte ", "output": "{\n\tbs := make([]byte, 0, 2*len(p))\n\tpos := 0\n\tfor pos < len(p) {\n\t\tbytes, size := consumeNextRune(p[pos:])\n\t\tpos += size\n\t\tbs = append(bs, bytes...)\n\t}\n\treturn bs\n}"} {"input": "package jsonutil\n\nimport (\n\t\"github.com/buger/jsonparser\"\n\t\"strconv\"\n)\n\nfunc GetString(data []byte, keys ...string) (string, error) {\n\treturn jsonparser.GetString(data, keys...)\n}\n\nfunc MustGetString(data []byte, keys ...string) string {\n\ts, err := GetString(data, keys...)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s\n}\n\nfunc GetFloat(data []byte, keys ...string) (float64, error) {\n\treturn jsonparser.GetFloat(data, keys...)\n}\n\nfunc MustGetFloat(data []byte, keys ...string) float64 {\n\tf, err := GetFloat(data, keys...)\n\tif err != nil {\n\t\treturn 0.0\n\t}\n\treturn f\n}\n\nfunc GetInt(data []byte, keys ...string) (int64, error) {\n\treturn jsonparser.GetInt(data, keys...)\n}\n\n\n\nfunc GetBoolean(data []byte, keys ...string) (bool, error) {\n\treturn jsonparser.GetBoolean(data, keys...)\n}\n\nfunc MustGetBoolean(data []byte, keys ...string) bool {\n\tb, err := GetBoolean(data, keys...)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn b\n}\n\nfunc MustGetInt(data []byte, keys ...string) int64 ", "output": "{\n\ti, err := GetInt(data, keys...)\n\tif err != nil {\n\t\tif s := MustGetString(data, keys...); len(s) == 0 {\n\t\t\treturn 0\n\t\t} else if i, err = strconv.ParseInt(s, 10, 64); err != nil {\n\t\t\treturn 0\n\t\t}\n\t}\n\treturn i\n}"} {"input": "package testing\n\nimport (\n\tv2net \"github.com/v2ray/v2ray-core/common/net\"\n\t\"github.com/v2ray/v2ray-core/transport/ray\"\n)\n\ntype TestPacketDispatcher struct {\n\tLastPacket chan v2net.Packet\n\tHandler func(packet v2net.Packet, traffic ray.OutboundRay)\n}\n\nfunc NewTestPacketDispatcher(handler func(packet v2net.Packet, traffic ray.OutboundRay)) *TestPacketDispatcher {\n\tif handler == nil {\n\t\thandler = func(packet v2net.Packet, traffic ray.OutboundRay) {\n\t\t\tfor payload := range traffic.OutboundInput() {\n\t\t\t\ttraffic.OutboundOutput() <- payload.Prepend([]byte(\"Processed: \"))\n\t\t\t}\n\t\t\tclose(traffic.OutboundOutput())\n\t\t}\n\t}\n\treturn &TestPacketDispatcher{\n\t\tLastPacket: make(chan v2net.Packet, 16),\n\t\tHandler: handler,\n\t}\n}\n\n\n\nfunc (this *TestPacketDispatcher) DispatchToOutbound(packet v2net.Packet) ray.InboundRay ", "output": "{\n\ttraffic := ray.NewRay()\n\tthis.LastPacket <- packet\n\tgo this.Handler(packet, traffic)\n\n\treturn traffic\n}"} {"input": "package gotify\n\nimport (\n\t\"github.com/antonholmquist/jason\"\n)\n\nfunc parseAlbum(o *jason.Object) Album {\n\talbumName, _ := o.GetString(\"name\")\n\talbumUri, _ := o.GetString(\"uri\")\n\n\talbum := Album{albumName, albumUri}\n\n\treturn album\n}\n\n\n\nfunc parseTrack(o *jason.Object) Track {\n\ttrackName, _ := o.GetString(\"name\")\n\ttrackUri, _ := o.GetString(\"uri\")\n\n\tjsonAlbum, err := o.GetObject(\"album\")\n\n\tvar album Album\n\tif err == nil {\n\t\talbum = parseAlbum(jsonAlbum)\n\t}\n\n\tjsonArtists, err := o.GetObjectArray(\"artists\")\n\n\tvar artists []Artist\n\tif err == nil {\n\t\tartists = parseArtists(jsonArtists)\n\t}\n\n\ttrack := Track{trackName, trackUri, album, artists}\n\n\treturn track\n}\n\nfunc parseTracks(o []*jason.Object) []Track {\n\ttracks := []Track{}\n\n\tfor _, jsonTrack := range o {\n\t\ttracks = append(tracks, parseTrack(jsonTrack))\n\t}\n\n\treturn tracks\n}\n\nfunc parseAlbums(o []*jason.Object) []Album {\n\talbums := []Album{}\n\n\tfor _, jsonAlbum := range o {\n\t\talbums = append(albums, parseAlbum(jsonAlbum))\n\t}\n\n\treturn albums\n}\n\nfunc parseArtists(o []*jason.Object) []Artist {\n\tartists := []Artist{}\n\n\tfor _, jsonArtist := range o {\n\t\tartists = append(artists, parseArtist(jsonArtist))\n\t}\n\n\treturn artists\n}\n\nfunc parsePlaylist(o *jason.Object) SpotifyPlaylist {\n\treturn SpotifyPlaylist{}\n}\n\nfunc parseArtist(o *jason.Object) Artist ", "output": "{\n\tartistName, _ := o.GetString(\"name\")\n\tartistUri, _ := o.GetString(\"uri\")\n\n\tartist := Artist{artistName, artistUri}\n\n\treturn artist\n}"} {"input": "package generic\n\nimport (\n\t\"github.com/actgardner/gogen-avro/v8/schema\"\n\t\"github.com/actgardner/gogen-avro/v8/vm/types\"\n)\n\ntype recordDatum struct {\n\tdef *schema.RecordDefinition\n\tfields []Datum\n}\n\nfunc newRecordDatum(def *schema.RecordDefinition) *recordDatum {\n\treturn &recordDatum{\n\t\tdef: def,\n\t\tfields: make([]Datum, len(def.Fields())),\n\t}\n}\n\n\n\nfunc (r *recordDatum) SetBoolean(v bool) { panic(\"\") }\nfunc (r *recordDatum) SetInt(v int32) { panic(\"\") }\nfunc (r *recordDatum) SetLong(v int64) { panic(\"\") }\nfunc (r *recordDatum) SetFloat(v float32) { panic(\"\") }\nfunc (r *recordDatum) SetDouble(v float64) { panic(\"\") }\nfunc (r *recordDatum) SetBytes(v []byte) { panic(\"\") }\nfunc (r *recordDatum) SetString(v string) { panic(\"\") }\nfunc (r *recordDatum) Get(i int) types.Field {\n\tfield := r.def.Fields()[i]\n\tr.fields[i] = DatumForType(field.Type())\n\treturn r.fields[i]\n}\nfunc (r *recordDatum) SetDefault(i int) {\n\tfield := r.def.Fields()[i]\n\tr.fields[i] = &primitiveDatum{field.Default()}\n}\nfunc (r *recordDatum) AppendMap(key string) types.Field { panic(\"\") }\nfunc (r *recordDatum) AppendArray() types.Field { panic(\"\") }\nfunc (r *recordDatum) NullField(t int) {\n\tr.fields[t] = &primitiveDatum{nil}\n}\nfunc (r *recordDatum) Finalize() {}\n\nfunc (r *recordDatum) Datum() interface{} ", "output": "{\n\tm := make(map[string]interface{})\n\tfor i, f := range r.def.Fields() {\n\t\tm[f.Name()] = r.fields[i].Datum()\n\t}\n\treturn m\n}"} {"input": "package hashcash\n\nimport (\n\t\"encoding/hex\"\n\t\"testing\"\n)\n\nfunc TestBitCount(t *testing.T) {\n\tc := BitCount([32]byte{0x00, 0x00, 0x08, 0x02})\n\tif c != 20 {\n\t\tt.Error(\"Count error\")\n\t}\n}\n\nfunc TestHashCash(t *testing.T) {\n\td := []byte(\"abcefghi\")\n\tn, ok := ComputeNonce(d, 10, 0, 0)\n\tif !ok {\n\t\tt.Error(\"No match found\")\n\t}\n\tif hex.EncodeToString(n) != \"b301000000000000\" {\n\t\tt.Errorf(\"Nonce error b301000000000000 != %s\", hex.EncodeToString(n))\n\t}\n}\n\n\n\nfunc TestTestNonce(t *testing.T) {\n\td := []byte(\"abcefghi\")\n\tn := []byte{0x09, 0x0e, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00}\n\tok, _ := TestNonce(d, n, 20)\n\tif !ok {\n\t\tt.Error(\"Nonce verification failed\")\n\t}\n\tn = []byte{0x09, 0x0e, 0x28, 0x00, 0x00, 0x00, 0x00, 0x01}\n\tok, c := TestNonce(d, n, 20)\n\tif ok {\n\t\tt.Errorf(\"Nonce verification MUST fail: %d < 20\", c)\n\t}\n}\n\nfunc TestComputeParallel(t *testing.T) ", "output": "{\n\td := []byte(\"abcefghi\")\n\tbits := byte(21)\n\tnonce, _ := ComputeNonceSelect(d, bits, 0, 0) \n\tok, _ := TestNonce(d, nonce, bits)\n\tif !ok {\n\t\tt.Error(\"No Nonce found\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t. \"github.com/Deleplace/programming-idioms/pig\"\n)\n\n\ntype AllIdiomsFacade struct {\n\tPageMeta PageMeta\n\tUserProfile UserProfile\n\tAllIdioms []*Idiom\n}\n\n\n\nfunc retrieveAllIdioms(r *http.Request, orderByFav bool) ([]*Idiom, error) {\n\tctx := r.Context()\n\n\t_, idioms, err := dao.getAllIdioms(ctx, 0, \"Id\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif orderByFav {\n\t\tfavlangs := lookForFavoriteLanguages(r)\n\t\tincludeNonFav := seeNonFavorite(r)\n\t\tfor _, idiom := range idioms {\n\t\t\timplFavoriteLanguagesFirstWithOrder(idiom, favlangs, \"\", includeNonFav)\n\t\t}\n\t}\n\n\treturn idioms, nil\n}\n\nfunc allIdioms(w http.ResponseWriter, r *http.Request) error ", "output": "{\n\n\tidioms, err := retrieveAllIdioms(r, true)\n\tif err != nil {\n\t\treturn PiErrorf(http.StatusInternalServerError, \"%v\", err)\n\t}\n\n\tdata := AllIdiomsFacade{\n\t\tPageMeta: PageMeta{\n\t\t\tPageTitle: \"All idioms\",\n\t\t\tToggles: toggles,\n\t\t},\n\t\tUserProfile: readUserProfile(r),\n\t\tAllIdioms: idioms,\n\t}\n\n\tif err := templates.ExecuteTemplate(w, \"page-all-idioms\", data); err != nil {\n\t\treturn PiErrorf(http.StatusInternalServerError, \"%v\", err)\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype geometry interface {\n\tarea() float64\n\tperim() float64\n}\n\ntype square struct {\n\twidth, heigth float64\n}\n\ntype circle struct {\n\tradius float64\n}\n\nfunc (s square) area() float64 {\n\treturn s.width * s.heigth\n}\n\n\n\nfunc (c circle) area() float64 {\n\treturn math.Pi * c.radius * c.radius\n}\n\nfunc (c circle) perim() float64 {\n\treturn 2 * math.Pi * c.radius\n}\n\nfunc measure(g geometry) {\n\tfmt.Println(g)\n\tfmt.Println(g.area())\n\tfmt.Println(g.perim())\n}\n\nfunc main() {\n\ts := square{width: 3, heigth: 4}\n\tc := circle{radius: 5}\n\n\tmeasure(s)\n\tmeasure(c)\n}\n\nfunc (s square) perim() float64 ", "output": "{\n\treturn 2*s.width + 2*s.heigth\n}"} {"input": "package displayers\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/digitalocean/doctl/do\"\n)\n\ntype Size struct {\n\tSizes do.Sizes\n}\n\nvar _ Displayable = &Size{}\n\n\n\nfunc (si *Size) Cols() []string {\n\treturn []string{\n\t\t\"Slug\", \"Memory\", \"VCPUs\", \"Disk\", \"PriceMonthly\", \"PriceHourly\",\n\t}\n}\n\nfunc (si *Size) ColMap() map[string]string {\n\treturn map[string]string{\n\t\t\"Slug\": \"Slug\", \"Memory\": \"Memory\", \"VCPUs\": \"VCPUs\",\n\t\t\"Disk\": \"Disk\", \"PriceMonthly\": \"Price Monthly\",\n\t\t\"PriceHourly\": \"Price Hourly\",\n\t}\n}\n\nfunc (si *Size) KV() []map[string]interface{} {\n\tout := []map[string]interface{}{}\n\n\tfor _, s := range si.Sizes {\n\t\to := map[string]interface{}{\n\t\t\t\"Slug\": s.Slug, \"Memory\": s.Memory, \"VCPUs\": s.Vcpus,\n\t\t\t\"Disk\": s.Disk, \"PriceMonthly\": fmt.Sprintf(\"%0.2f\", s.PriceMonthly),\n\t\t\t\"PriceHourly\": s.PriceHourly,\n\t\t}\n\n\t\tout = append(out, o)\n\t}\n\n\treturn out\n}\n\nfunc (si *Size) JSON(out io.Writer) error ", "output": "{\n\treturn writeJSON(si.Sizes, out)\n}"} {"input": "package main\n\nimport \"github.com/augustoroman/serial_lcd\"\n\ntype FakeLcd struct{}\n\nfunc (f FakeLcd) SetBG(r, g, b uint8) error { return nil }\nfunc (f FakeLcd) SetOn(On bool) error { return nil }\nfunc (f FakeLcd) SetBrightness(b uint8) error { return nil }\nfunc (f FakeLcd) SetContrast(c uint8) error { return nil }\nfunc (f FakeLcd) SetAutoscroll(On bool) error { return nil }\nfunc (f FakeLcd) SetSize(cols, rows uint8) error { return nil }\nfunc (f FakeLcd) Clear() error { return nil }\nfunc (f FakeLcd) Home() error { return nil }\nfunc (f FakeLcd) MoveTo(col, row uint8) error { return nil }\n\nfunc (f FakeLcd) MoveBack() error { return nil }\nfunc (f FakeLcd) Write(b []byte) (int, error) { return len(b), nil }\n\nfunc (f FakeLcd) CreateCustomChar(spot uint8, c serial_lcd.Char) error { return nil }\n\nfunc (f FakeLcd) MoveForward() error ", "output": "{ return nil }"} {"input": "package ginkgoext\n\nimport (\n\t\"github.com/onsi/gomega/types\"\n)\n\ntype anythingMatcher struct{}\n\nfunc (matcher *anythingMatcher) Match(actual interface{}) (success bool, err error) {\n\treturn true, nil\n}\n\n\n\nfunc (matcher *anythingMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn \"\"\n}\n\n\nfunc BeAnything() types.GomegaMatcher {\n\treturn &anythingMatcher{}\n}\n\nfunc (matcher *anythingMatcher) FailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn \"\"\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"time\"\n)\n\n\nvar TopicCache = make([]*Topic, 0, 16)\n\ntype Topic struct {\n\tId int `json:\"id\"`\n\tTitle string `json:\"title\"`\n\tContent string `json:\"content\"`\n\tCreatedAt time.Time `json:\"created_at\"`\n}\n\nfunc FindTopic(id int) (*Topic, error) {\n\tif err := checkIndex(id); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn TopicCache[id-1], nil\n}\n\nfunc (t *Topic) Create() error {\n\tt.Id = len(TopicCache) + 1\n\tt.CreatedAt = time.Now()\n\tTopicCache = append(TopicCache, t)\n\treturn nil\n}\n\nfunc (t *Topic) Update() error {\n\tif err := checkIndex(t.Id); err != nil {\n\t\treturn err\n\t}\n\tTopicCache[t.Id-1] = t\n\treturn nil\n}\n\n\nfunc (t *Topic) Delete() error {\n\tif err := checkIndex(t.Id); err != nil {\n\t\treturn err\n\t}\n\tTopicCache[t.Id-1] = nil\n\treturn nil\n}\n\n\n\nfunc checkIndex(id int) error ", "output": "{\n\tif id > 0 && len(TopicCache) <= id-1 {\n\t\treturn errors.New(\"The topic is not exists!\")\n\t}\n\n\treturn nil\n}"} {"input": "package object\n\ntype Error string\n\n\n\nfunc (e Error) Rest() Value {\n\treturn e\n}\n\nfunc (e Error) Type() Type {\n\treturn ERROR\n}\n\nfunc (e Error) String() string {\n\treturn string(\"\")\n}\n\nfunc (e Error) First() Value ", "output": "{\n\treturn e\n}"} {"input": "package expression_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/pingcap/tidb/expression\"\n\t\"github.com/pingcap/tidb/testkit\"\n\t\"github.com/pingcap/tidb/testkit/testdata\"\n)\n\n\n\nfunc TestSimplifyExpressionByFlag(t *testing.T) ", "output": "{\n\tstore, clean := testkit.CreateMockStore(t)\n\tdefer clean()\n\n\ttk := testkit.NewTestKit(t, store)\n\ttk.MustExec(\"use test\")\n\ttk.MustExec(\"drop table if exists t\")\n\ttk.MustExec(\"create table t(id int primary key, a bigint unsigned not null, b bigint unsigned)\")\n\n\tvar input []string\n\tvar output []struct {\n\t\tSQL string\n\t\tPlan []string\n\t}\n\tflagSimplifyData := expression.GetFlagSimplifyData()\n\tflagSimplifyData.GetTestCases(t, &input, &output)\n\tfor i, tt := range input {\n\t\ttestdata.OnRecord(func() {\n\t\t\toutput[i].SQL = tt\n\t\t\toutput[i].Plan = testdata.ConvertRowsToStrings(tk.MustQuery(tt).Rows())\n\t\t})\n\t\ttk.MustQuery(tt).Check(testkit.Rows(output[i].Plan...))\n\t}\n}"} {"input": "package networkcontainers\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com/Azure/azure-container-networking/cns\"\n\t\"github.com/Azure/azure-container-networking/log\"\n)\n\n\ntype NetworkContainers struct {\n\tlogpath string\n}\n\nfunc interfaceExists(iFaceName string) (bool, error) {\n\t_, err := net.InterfaceByName(iFaceName)\n\n\tif err != nil {\n\t\terrMsg := fmt.Sprintf(\"[Azure CNS] Unable to get interface by name %v, %v\", iFaceName, err)\n\t\tlog.Printf(errMsg)\n\t\treturn false, errors.New(errMsg)\n\t}\n\n\treturn true, nil\n}\n\n\n\n\n\nfunc (cn *NetworkContainers) Update(createNetworkContainerRequest cns.CreateNetworkContainerRequest) error {\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Update called\")\n\terr := createOrUpdateInterface(createNetworkContainerRequest)\n\tif err == nil {\n\t\terr = setWeakHostOnInterface(createNetworkContainerRequest.PrimaryInterfaceIdentifier)\n\t}\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Update finished.\")\n\treturn err\n}\n\n\nfunc (cn *NetworkContainers) Delete(networkContainerID string) error {\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Delete called\")\n\terr := deleteInterface(networkContainerID)\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Delete finished.\")\n\treturn err\n}\n\nfunc (cn *NetworkContainers) Create(createNetworkContainerRequest cns.CreateNetworkContainerRequest) error ", "output": "{\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Create called\")\n\terr := createOrUpdateInterface(createNetworkContainerRequest)\n\tif err == nil {\n\t\terr = setWeakHostOnInterface(createNetworkContainerRequest.PrimaryInterfaceIdentifier)\n\t}\n\tlog.Printf(\"[Azure CNS] NetworkContainers.Create finished.\")\n\treturn err\n}"} {"input": "package helper\n\nimport (\n\t\"encoding/base64\"\n\t\"strings\"\n\t\"time\"\n\t\"github.com/insionng/yougam/libraries/flosch/pongo2.v3\"\n)\n\nfunc ConvertToBase64(in string) string {\n\treturn base64.StdEncoding.EncodeToString([]byte(in))\n}\n\nfunc ConvertToBase64ByPongo2(in *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(base64.StdEncoding.EncodeToString([]byte(in.String())))\n}\n\n\n\nfunc MarkdownByPongo2(in *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Markdown(in.String()))\n}\n\nfunc CropwordByPongo2(in *pongo2.Value, start *pongo2.Value, length *pongo2.Value, symbol *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Substr(in.String(), start.Integer(), length.Integer(), symbol.String()))\n}\n\nfunc Cropword(in string, start int, length int, symbol string) string {\n\treturn Substr(in, start, length, symbol)\n}\n\nfunc File(s string) string {\n\tif len(s) > 0 {\n\t\tif strings.HasPrefix(s, \"http\") || strings.HasPrefix(s, \"/identicon\") {\n\t\t\treturn s\n\t\t} else {\n\t\t\treturn \"/file\" + s\n\t\t}\n\t}\n\treturn s\n}\n\nfunc Unix2TimeByPongo2(in *pongo2.Value, timeLayout *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(time.Unix(int64(in.Integer()), 0).Format(timeLayout.String()))\n}\n\nfunc SplitByPongo2(in *pongo2.Value, splitor *pongo2.Value) *pongo2.Value ", "output": "{\n\treturn pongo2.AsValue(Split(in.String(), splitor.String()))\n}"} {"input": "package elasticsearch\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/elastic/beats/libbeat/outputs/outil\"\n)\n\nconst ElasticsearchDefaultHost = \"localhost\"\nconst ElasticsearchDefaultPort = \"9200\"\n\nfunc GetEsPort() string {\n\tport := os.Getenv(\"ES_PORT\")\n\n\tif len(port) == 0 {\n\t\tport = ElasticsearchDefaultPort\n\t}\n\treturn port\n}\n\n\nfunc GetEsHost() string {\n\n\thost := os.Getenv(\"ES_HOST\")\n\n\tif len(host) == 0 {\n\t\thost = ElasticsearchDefaultHost\n\t}\n\n\treturn host\n}\n\nfunc GetTestingElasticsearch() *Client {\n\tvar address = \"http://\" + GetEsHost() + \":\" + GetEsPort()\n\tusername := os.Getenv(\"ES_USER\")\n\tpass := os.Getenv(\"ES_PASS\")\n\tclient := newTestClientAuth(address, username, pass)\n\n\tclient.Connect(3 * time.Second)\n\treturn client\n}\n\n\n\nfunc newTestClientAuth(url, user, pass string) *Client ", "output": "{\n\tclient, err := NewClient(ClientSettings{\n\t\tURL: url,\n\t\tIndex: outil.MakeSelector(),\n\t\tUsername: user,\n\t\tPassword: pass,\n\t\tTimeout: 60 * time.Second,\n\t\tCompressionLevel: 3,\n\t}, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}"} {"input": "package commands\n\nimport (\n\n\n\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/hofstadter-io/geb/commands/view\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar ViewLong = `View information known to the geb tool.`\n\nvar ViewCmd = &cobra.Command{\n\n\tUse: \"view\",\n\n\tAliases: []string{\n\t\t\"v\",\n\t},\n\n\tShort: \"View information known to the geb tool.\",\n\n\tLong: ViewLong,\n}\n\nfunc init() {\n\tRootCmd.AddCommand(ViewCmd)\n}\n\n\n\nfunc init() ", "output": "{\n\n\tViewCmd.AddCommand(view.SystemCmd)\n\tViewCmd.AddCommand(view.DslCmd)\n\tViewCmd.AddCommand(view.GenCmd)\n\tViewCmd.AddCommand(view.ProjectCmd)\n\tViewCmd.AddCommand(view.DesignCmd)\n\tViewCmd.AddCommand(view.PlansCmd)\n}"} {"input": "package org\n\nimport (\n\t\"errors\"\n\n\t\"github.com/appcelerator/amp/api/rpc/account\"\n\t\"github.com/appcelerator/amp/cli\"\n\t\"github.com/spf13/cobra\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/status\"\n)\n\ntype createOrgOptions struct {\n\tname string\n\temail string\n}\n\n\n\n\nfunc createOrg(c cli.Interface, cmd *cobra.Command, opts createOrgOptions) error {\n\tif !cmd.Flag(\"org\").Changed {\n\t\topts.name = c.Console().GetInput(\"organization name\")\n\t}\n\tif !cmd.Flag(\"email\").Changed {\n\t\topts.email = c.Console().GetInput(\"email\")\n\t}\n\tconn := c.ClientConn()\n\tclient := account.NewAccountClient(conn)\n\trequest := &account.CreateOrganizationRequest{\n\t\tName: opts.name,\n\t\tEmail: opts.email,\n\t}\n\tif _, err := client.CreateOrganization(context.Background(), request); err != nil {\n\t\tif s, ok := status.FromError(err); ok {\n\t\t\treturn errors.New(s.Message())\n\t\t}\n\t}\n\tif err := cli.SaveOrg(opts.name, c.Server()); err != nil {\n\t\treturn err\n\t}\n\tc.Console().Println(\"Organization has been created.\")\n\treturn nil\n}\n\nfunc NewOrgCreateCommand(c cli.Interface) *cobra.Command ", "output": "{\n\topts := createOrgOptions{}\n\tcmd := &cobra.Command{\n\t\tUse: \"create [OPTIONS]\",\n\t\tShort: \"Create organization\",\n\t\tPreRunE: cli.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn createOrg(c, cmd, opts)\n\t\t},\n\t}\n\tflags := cmd.Flags()\n\tflags.StringVar(&opts.name, \"org\", \"\", \"Organization name\")\n\tflags.StringVar(&opts.email, \"email\", \"\", \"Email address\")\n\treturn cmd\n}"} {"input": "package types\n\nimport (\n\t\"github.com/coreos/ignition/config/shared/errors\"\n\t\"github.com/coreos/ignition/config/validate/report\"\n)\n\ntype Filesystem struct {\n\tName string `json:\"name,omitempty\"`\n\tMount *FilesystemMount `json:\"mount,omitempty\"`\n\tPath *Path `json:\"path,omitempty\"`\n}\n\ntype FilesystemMount struct {\n\tDevice Path `json:\"device,omitempty\"`\n\tFormat FilesystemFormat `json:\"format,omitempty\"`\n\tCreate *FilesystemCreate `json:\"create,omitempty\"`\n}\n\ntype FilesystemCreate struct {\n\tForce bool `json:\"force,omitempty\"`\n\tOptions MkfsOptions `json:\"options,omitempty\"`\n}\n\nfunc (f Filesystem) Validate() report.Report {\n\tif f.Mount == nil && f.Path == nil {\n\t\treturn report.ReportFromError(errors.ErrFilesystemNoMountPath, report.EntryError)\n\t}\n\tif f.Mount != nil && f.Path != nil {\n\t\treturn report.ReportFromError(errors.ErrFilesystemMountAndPath, report.EntryError)\n\t}\n\treturn report.Report{}\n}\n\ntype FilesystemFormat string\n\n\n\ntype MkfsOptions []string\n\nfunc (f FilesystemFormat) Validate() report.Report ", "output": "{\n\tswitch f {\n\tcase \"ext4\", \"btrfs\", \"xfs\":\n\t\treturn report.Report{}\n\tdefault:\n\t\treturn report.ReportFromError(errors.ErrFilesystemInvalidFormat, report.EntryError)\n\t}\n}"} {"input": "package utils\n\nimport \"sync\"\n\ntype queueNode struct {\n\tdata interface{}\n\tnext *queueNode\n}\n\ntype queue struct {\n\thead *queueNode\n\ttail *queueNode\n\tcount int\n\tlock *sync.Mutex\n}\n\nfunc NewQueue() *queue {\n\treturn &queue{lock: &sync.Mutex{}}\n}\n\nfunc (q *queue) Len() int {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\treturn q.count\n}\n\n\n\nfunc (q *queue) Pop() interface{} {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tif q.head == nil {\n\t\treturn nil\n\t}\n\n\tnode := q.head\n\tq.head = node.next\n\n\tif q.head == nil {\n\t\tq.tail = nil\n\t}\n\n\tq.count--\n\n\treturn node.data\n}\n\nfunc (q *queue) Peek() interface{} {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tnode := q.head\n\tif node == nil || node.data == nil {\n\t\treturn nil\n\t}\n\n\treturn node.data\n}\n\nfunc (q *queue) Push(v interface{}) ", "output": "{\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tnode := &queueNode{data: v}\n\n\tif q.tail == nil {\n\t\tq.tail = node\n\t\tq.head = node\n\t} else {\n\t\tq.tail.next = node\n\t\tq.tail = node\n\t}\n\n\tq.count++\n}"} {"input": "package audio\n\nimport (\n\t\"github.com/oakmound/oak/v3/audio/klang\"\n\t\"github.com/oakmound/oak/v3/audio/klang/filter\"\n\t\"github.com/oakmound/oak/v3/audio/klang/filter/supports\"\n\t\"github.com/oakmound/oak/v3/physics\"\n)\n\n\n\ntype SupportsPos interface {\n\tsupports.Encoding\n\tXp() *float64\n\tYp() *float64\n}\n\nvar (\n\t_ klang.Filter = Pos(func(SupportsPos) {})\n)\n\n\ntype Pos func(SupportsPos)\n\n\n\nfunc (xp Pos) Apply(a klang.Audio) (klang.Audio, error) {\n\tif sxp, ok := a.(SupportsPos); ok {\n\t\txp(sxp)\n\t\treturn a, nil\n\t}\n\treturn a, nil \n}\n\n\n\n\n\n\nfunc PosFilter(e *Ears) Pos ", "output": "{\n\treturn func(sp SupportsPos) {\n\t\tfilter.AssertStereo()(sp)\n\t\tx := sp.Xp()\n\t\tif x != nil {\n\t\t\tp := e.CalculatePan(*x)\n\t\t\tfilter.Pan(p)(sp)\n\t\t\ty := sp.Yp()\n\t\t\tif y != nil {\n\t\t\t\tv := e.CalculateVolume(physics.NewVector(*x, *y))\n\t\t\t\tfilter.Volume(v)(sp)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package model\n\nimport (\n\t\"fmt\"\n\tnative_time \"time\"\n)\n\n\n\n\n\n\n\n\ntype Timestamp int64\n\nconst (\n\tMinimumTick = native_time.Second\n\tsecond = int64(native_time.Second / MinimumTick)\n)\n\n\nfunc (t Timestamp) Equal(o Timestamp) bool {\n\treturn t == o\n}\n\n\nfunc (t Timestamp) Before(o Timestamp) bool {\n\treturn t < o\n}\n\n\nfunc (t Timestamp) After(o Timestamp) bool {\n\treturn t > o\n}\n\n\nfunc (t Timestamp) Add(d native_time.Duration) Timestamp {\n\treturn t + Timestamp(d/MinimumTick)\n}\n\n\nfunc (t Timestamp) Sub(o Timestamp) native_time.Duration {\n\treturn native_time.Duration(t-o) * MinimumTick\n}\n\n\nfunc (t Timestamp) Time() native_time.Time {\n\treturn native_time.Unix(int64(t)/second, (int64(t) % second))\n}\n\n\n\nfunc (t Timestamp) Unix() int64 {\n\treturn int64(t) / second\n}\n\n\n\n\n\nfunc Now() Timestamp {\n\treturn TimestampFromTime(native_time.Now())\n}\n\n\nfunc TimestampFromTime(t native_time.Time) Timestamp {\n\treturn TimestampFromUnix(t.Unix())\n}\n\n\nfunc TimestampFromUnix(t int64) Timestamp {\n\treturn Timestamp(t * second)\n}\n\nfunc (t Timestamp) String() string ", "output": "{\n\treturn fmt.Sprint(int64(t))\n}"} {"input": "package engine\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestJobErr(t *testing.T) {\n\teng := New()\n\teng.Register(\"return_err\", func(job *Job) error { return errors.New(\"return_err\") })\n\terr := eng.Job(\"return_err\").Run()\n\tif err == nil {\n\t\tt.Fatalf(\"When a job returns error, Run() should return an error\")\n\t}\n}\n\nfunc TestJobStdoutString(t *testing.T) {\n\teng := New()\n\teng.Register(\"say_something_in_stdout\", func(job *Job) error {\n\t\tjob.Printf(\"Hello world\\n\")\n\t\treturn nil\n\t})\n\n\tjob := eng.Job(\"say_something_in_stdout\")\n\tvar outputBuffer = bytes.NewBuffer(nil)\n\tjob.Stdout.Add(outputBuffer)\n\tif err := job.Run(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfmt.Println(outputBuffer)\n\tvar output = Tail(outputBuffer, 1)\n\tif expectedOutput := \"Hello world\"; output != expectedOutput {\n\t\tt.Fatalf(\"Stdout last line:\\nExpected: %v\\nReceived: %v\", expectedOutput, output)\n\t}\n}\n\nfunc TestJobOK(t *testing.T) ", "output": "{\n\teng := New()\n\teng.Register(\"return_ok\", func(job *Job) error { return nil })\n\terr := eng.Job(\"return_ok\").Run()\n\tif err != nil {\n\t\tt.Fatalf(\"Expected: err=%v\\nReceived: err=%v\", nil, err)\n\t}\n}"} {"input": "package mcore\n\nimport (\n\t\"log\"\n)\n\ntype StringKeyValueMap map[string]string\n\n\n\n\nfunc (c StringKeyValueMap) Put(key, value string) {\n\tc[key] = value\n}\n\nfunc (c StringKeyValueMap) IsContain(key string) bool {\n\t_, ok := c[key]\n\treturn ok\n}\n\nfunc (c StringKeyValueMap) GetString(key string) string {\n\treturn c.GetStringWithDefault(key, \"\")\n}\n\nfunc (c StringKeyValueMap) GetStringWithDefault(key, defaultValue string) string {\n\tif c.IsContain(key) {\n\t\treturn c[key]\n\t}\n\tlog.Printf(\"Error: not contains key: %s\", key)\n\treturn defaultValue\n}\n\nfunc (c StringKeyValueMap) GetInt(key string) int {\n\treturn String(c.GetString(key)).ToIntNoError()\n}\n\nfunc (c StringKeyValueMap) GetBool(key string) bool {\n\treturn String(c.GetString(key)).ToBool()\n}\n\nfunc NewStringKeyValueMap() StringKeyValueMap ", "output": "{\n\treturn make(map[string]string)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\ntype myStruct struct {\n\tintField int\n}\n\n\n\nfunc (ms *myStruct) addByReference(x int) {\n\tms.intField += x\n\tfmt.Println(\"ByReference internal value \", ms.intField)\n}\n\nfunc main() {\n\tmyVar := myStruct{1}\n\tmyPtr := &myStruct{2}\n\n\tmyVar.addByValue(3)\n\tfmt.Println(\"main func myVar value \", myVar)\n\tmyVar.addByReference(3)\n\tfmt.Println(\"main func myVar value \", myVar)\n\tfmt.Println(\"\\n\")\n\n\tmyPtr.addByValue(3)\n\tfmt.Println(\"main func myPtr value \", myPtr)\n\tmyPtr.addByReference(3)\n\tfmt.Println(\"main func myPtr value \", myPtr)\n\n}\n\nfunc (ms myStruct) addByValue(x int) ", "output": "{\n\tms.intField += x\n\tfmt.Println(\"ByValue internal value \", ms.intField)\n}"} {"input": "package swg\n\nconst (\n\tGWSRPCRR = iota\n\tGWSRPCRS\n\tGWSRPCSR\n\tGWSRPCSS\n)\n\n\ntype RPCData struct {\n\tGwstype int\n\tIndex int\n\tName string\n\tIn string\n\tOut string\n\tComment string\n\tGwsrpcode string\n}\n\n\ntype PackageData struct {\n\tPackageName string\n\tPbJSONbackquote string\n\tPbPROTObackquote string\n\tRPCDatas []RPCData\n}\n\n\ntype TopClass struct {\n\tGatewayName string\n\tLocalport string\n\tSuffix string\n\n\tGoimportpath string\n\n\tJs94Char string\n\n\tFileDatas map[string]*PackageData\n}\n\n\nvar Top TopClass\n\n\nvar Makemain bool\n\n\nvar IsGWSRPCSELF bool\n\n\n\nfunc init() ", "output": "{\n\tTop.FileDatas = make(map[string]*PackageData)\n\tTop.Js94Char = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!\\\"#$%&()*+,-./:;<=>?@[]^_`{|}~\\\\'\\\\\\\\\"\n}"} {"input": "package opts \n\n\n\ntype QuotedString struct {\n\tvalue *string\n}\n\n\nfunc (s *QuotedString) Set(val string) error {\n\t*s.value = trimQuotes(val)\n\treturn nil\n}\n\n\nfunc (s *QuotedString) Type() string {\n\treturn \"string\"\n}\n\n\n\nfunc trimQuotes(value string) string {\n\tlastIndex := len(value) - 1\n\tfor _, char := range []byte{'\\'', '\"'} {\n\t\tif value[0] == char && value[lastIndex] == char {\n\t\t\treturn value[1:lastIndex]\n\t\t}\n\t}\n\treturn value\n}\n\n\nfunc NewQuotedString(value *string) *QuotedString {\n\treturn &QuotedString{value: value}\n}\n\nfunc (s *QuotedString) String() string ", "output": "{\n\treturn *s.value\n}"} {"input": "package lease\n\n\n\ntype block struct {\n\tleaseName string\n\tunblock chan struct{}\n\tabort <-chan struct{}\n}\n\n\n\nfunc (b block) invoke(ch chan<- block) error {\n\tfor {\n\t\tselect {\n\t\tcase <-b.abort:\n\t\t\treturn errStopped\n\t\tcase ch <- b:\n\t\t\tch = nil\n\t\tcase <-b.unblock:\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\n\n\ntype blocks map[string][]chan struct{}\n\n\n\n\n\n\nfunc (b blocks) unblock(leaseName string) {\n\tunblocks := b[leaseName]\n\tdelete(b, leaseName)\n\tfor _, unblock := range unblocks {\n\t\tclose(unblock)\n\t}\n}\n\nfunc (b blocks) add(block block) ", "output": "{\n\tb[block.leaseName] = append(b[block.leaseName], block.unblock)\n}"} {"input": "package music\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc TestMusicCategorys(t *testing.T) {\n\tvar (\n\t\tc = context.TODO()\n\t\tids = []int64{10, 11, 12}\n\t)\n\tconvey.Convey(\"Categorys\", t, func(ctx convey.C) {\n\t\tres, resMap, err := d.Categorys(c, ids)\n\t\tctx.Convey(\"Then err should be nil.res,resMap should not be nil.\", func(ctx convey.C) {\n\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\tctx.So(resMap, convey.ShouldNotBeNil)\n\t\t\tctx.So(res, convey.ShouldNotBeNil)\n\t\t})\n\t})\n}\n\n\n\nfunc TestMusicMusic(t *testing.T) {\n\tvar (\n\t\tc = context.TODO()\n\t\tsids = []int64{1, 2, 3, 4, 5, 6}\n\t)\n\tconvey.Convey(\"Music\", t, func(ctx convey.C) {\n\t\tres, err := d.Music(c, sids)\n\t\tctx.Convey(\"Then err should be nil.res should not be nil.\", func(ctx convey.C) {\n\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\tctx.So(res, convey.ShouldNotBeNil)\n\t\t})\n\t})\n}\n\nfunc TestMusicMCategorys(t *testing.T) ", "output": "{\n\tvar (\n\t\tc = context.TODO()\n\t)\n\tconvey.Convey(\"MCategorys\", t, func(ctx convey.C) {\n\t\tres, err := d.MCategorys(c)\n\t\tctx.Convey(\"Then err should be nil.res should not be nil.\", func(ctx convey.C) {\n\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\tctx.So(res, convey.ShouldNotBeNil)\n\t\t})\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/rpc\"\n)\n\n\n\n\ntype Args struct {\n\tA, B int\n}\n\n\ntype Arith int\n\n\nfunc (t *Arith) Multiply(args *Args, reply *int) error {\n\t*reply = args.A * args.B\n\treturn nil\n}\n\nfunc (t *Arith) Add(args *Args, reply *int) error {\n\t*reply = args.A + args.B\n\treturn nil\n}\n\nfunc main() {\n\tarith := new(Arith)\n\terr := rpc.Register(arith)\n\tif err != nil {\n\t\tlog.Fatal(\"Service Error: %s\", err)\n\t}\n\trpc.HandleHTTP()\n\n\tl, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", 57439))\n\n\tif err != nil {\n\t\tlog.Fatal(\"TCP Error: %s\", err)\n\t}\n\tlog.Println(\"ok\")\n\thttp.Serve(l, nil)\n}\n\nfunc defaultHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tfmt.Fprintf(w, \"

Hello %s!

\", r.URL.Path[1:])\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\n\t\"github.com/levigross/grequests\"\n)\n\n\ntype aiReply struct {\n\tcode int\n\tText string `json:\"text\"`\n}\n\n\n\n\nfunc tlAI(info string) string ", "output": "{\n\ttlURL := config.Ai.ApiUrl\n\tro := &grequests.RequestOptions{\n\t\tParams: map[string]string{\n\t\t\t\"key\": config.Ai.ApiKey,\n\t\t\t\"info\": info,\n\t\t},\n\t}\n\n\tr, err := grequests.Get(tlURL, ro)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn \"\"\n\t}\n\n\tdefer r.Close()\n\treply := new(aiReply)\n\tjson.Unmarshal([]byte(r.String()), reply)\n\treturn reply.Text\n}"} {"input": "package packages\n\nimport (\n\t\"fmt\"\n\t\"github.com/alexandrecarlton/gogurt\"\n)\n\ntype PkgConfig struct{}\n\nfunc (pkgconfig PkgConfig) Name() string {\n\treturn \"pkg-config\"\n}\n\nfunc (pkgconfig PkgConfig) URL(version string) string {\n\treturn fmt.Sprintf(\"https://pkgconfig.freedesktop.org/releases/pkg-config-%s.tar.gz\", version)\n}\n\nfunc (pkgconfig PkgConfig) Build(config gogurt.Config) error {\n\tconfigure := gogurt.ConfigureCmd{\n\t\tPrefix: config.InstallDir(pkgconfig),\n\t\tArgs: []string{\n\t\t\t\"--disable-shared\",\n\t\t\t\"--enable-static\",\n\t\t\t\"--with-internal-glib\",\n\t\t},\n\t}.Cmd()\n\tif err := configure.Run(); err != nil {\n\t\treturn err\n\t}\n\tmake := gogurt.MakeCmd{\n\t\tJobs: config.NumCores,\n\t}.Cmd()\n\treturn make.Run()\n}\n\nfunc (pkgconfig PkgConfig) Install(config gogurt.Config) error {\n\tmakeInstall := gogurt.MakeCmd{\n\t\tArgs: []string{\n\t\t\t\"install\",\n\t\t},\n\t}.Cmd()\n\treturn makeInstall.Run()\n}\n\n\n\nfunc (pkgconfig PkgConfig) Dependencies() []gogurt.Package ", "output": "{\n\treturn []gogurt.Package{}\n}"} {"input": "package subscriber\n\n\ntype Config struct {\n\tEnabled bool `toml:\"enabled\"`\n}\n\n\n\n\nfunc NewConfig() Config ", "output": "{\n\treturn Config{Enabled: true}\n}"} {"input": "package sqlite3\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/gonuts/binary\"\n)\n\nfunc min(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}\n\nfunc unmarshal(buf []byte, ptr interface{}) (int64, error) {\n\tr := bytes.NewReader(buf)\n\tmax := r.Len()\n\tdec := binary.NewDecoder(r)\n\tdec.Order = binary.BigEndian\n\terr := dec.Decode(ptr)\n\tn := max - r.Len()\n\treturn int64(n), err\n}\n\n\n\nfunc varint(data []byte) (int64, int) ", "output": "{\n\tvar val uint64\n\tfor i := 0; i < 8; i++ {\n\t\tif i > len(data)-1 {\n\t\t\treturn 0, 0\n\t\t}\n\t\tval = (val << 7) | uint64(data[i]&0x7f)\n\t\tif data[i] < 0x80 {\n\t\t\treturn int64(val), i + 1\n\t\t}\n\t}\n\tif len(data) < 9 {\n\t\treturn 0, 0\n\t}\n\treturn int64((val << 8) | uint64(data[8])), 9\n}"} {"input": "package terminationworker\n\nimport (\n\tworker \"gopkg.in/juju/worker.v1\"\n\n\t\"github.com/juju/juju/worker/dependency\"\n)\n\n\n\n\n\nfunc Manifold() dependency.Manifold ", "output": "{\n\treturn dependency.Manifold{\n\t\tStart: func(_ dependency.Context) (worker.Worker, error) {\n\t\t\treturn NewWorker(), nil\n\t\t},\n\t}\n}"} {"input": "package permissions\n\nimport (\n\t\"path/filepath\"\n\t\"util\"\n)\n\n\nvar globalPermissions *PermissionsLoader\n\n\nfunc Get() *Permissions {\n\tif globalPermissions == nil {\n\t\treturn &Default\n\t}\n\treturn globalPermissions.Get()\n}\n\n\n\n\n\ntype PermissionsLoader struct {\n\tPermissions *Permissions \n\tWatcher *util.FileWatcher \n}\n\n\nfunc (pl *PermissionsLoader) Get() *Permissions {\n\tif pl == nil {\n\t\treturn &Default\n\t}\n\n\tpl.Watcher.RLock()\n\tdefer pl.Watcher.RUnlock()\n\treturn pl.Permissions\n}\n\n\n\nfunc NewPermissionsLoader(filename string) (*PermissionsLoader, error) {\n\tfilename, err := filepath.Abs(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp, err := Load(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpl := &PermissionsLoader{\n\t\tPermissions: p,\n\t}\n\tpl.Watcher, err = util.NewFileWatcher(filename, pl)\n\treturn pl, err\n}\n\n\nfunc (pl *PermissionsLoader) Reload() error {\n\tp, err := Load(pl.Watcher.FileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpl.Watcher.Lock()\n\tpl.Permissions = p\n\tpl.Watcher.Unlock()\n\n\tif !p.Watch {\n\t\tpl.Close() \n\t}\n\n\treturn nil\n}\n\n\nfunc (pl *PermissionsLoader) Close() {\n\tpl.Watcher.Close()\n}\n\nfunc SetPath(permissions string) error ", "output": "{\n\tif permissions != \"default\" {\n\t\tpl, err := NewPermissionsLoader(permissions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = pl\n\t\tif !pl.Get().Watch {\n\t\t\tglobalPermissions.Close() \n\t\t}\n\n\t} else {\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = nil\n\t}\n\treturn nil\n}"} {"input": "package v1\n\nimport (\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\trest \"k8s.io/client-go/rest\"\n\tv1 \"k8s.io/code-generator/_examples/crd/apis/example/v1\"\n\t\"k8s.io/code-generator/_examples/crd/clientset/versioned/scheme\"\n)\n\ntype ExampleV1Interface interface {\n\tRESTClient() rest.Interface\n\tTestTypesGetter\n}\n\n\ntype ExampleV1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *ExampleV1Client) TestTypes(namespace string) TestTypeInterface {\n\treturn newTestTypes(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*ExampleV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ExampleV1Client{client}, nil\n}\n\n\n\n\n\n\nfunc New(c rest.Interface) *ExampleV1Client {\n\treturn &ExampleV1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *ExampleV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfigOrDie(c *rest.Config) *ExampleV1Client ", "output": "{\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}"} {"input": "package plugin\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestApp(t *testing.T) ", "output": "{\n\tc := NewClient(&ClientConfig{Cmd: helperProcess(\"app\")})\n\tdefer c.Kill()\n\n\t_, err := c.Client()\n\tif err != nil {\n\t\tt.Fatalf(\"should not have error: %s\", err)\n\t}\n}"} {"input": "package models\n\nimport (\n\t\"github.com/astaxie/beego/orm\"\n)\n\ntype PmpCampaignCreative struct {\n\tId int `orm:\"column(id);auto\"`\n\tCampaignId int `orm:\"column(campaign_id)\"`\n\tName string `orm:\"column(name);size(45);null\"`\n\tWidth int `orm:\"column(width);null\"`\n\tHeight int `orm:\"column(height);null\"`\n\tCreativeUrl string `orm:\"column(creative_url);size(255);null\"`\n\tCreativeStatus int `orm:\"column(creative_status);null\"`\n\tLandingUrl string `orm:\"column(landing_url);size(500);null\"`\n\tImpTrackingUrl string `orm:\"column(imp_tracking_url);size(1000);null\"`\n\tClkTrackingUrl string `orm:\"column(clk_tracking_url);size(1000)\"`\n\tDisplayTitle string `orm:\"column(display_title);size(200);null\"`\n\tDisplayText string `orm:\"column(display_text);size(1000);null\"`\n}\n\nfunc (t *PmpCampaignCreative) TableName() string {\n\treturn \"pmp_campaign_creative\"\n}\n\nfunc init() {\n\torm.RegisterModel(new(PmpCampaignCreative))\n}\n\n\n\nfunc AddPmpCampaignCreative(v *PmpCampaignCreative) (err error) ", "output": "{\n\to := orm.NewOrm()\n\n\t_, err = o.Insert(v)\n\treturn err\n\n}"} {"input": "package transport \n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\n\n\ntype MockReporter struct {\n\twgMetricsProcessed sync.WaitGroup\n}\n\nvar _ Reporter = (*MockReporter)(nil)\n\n\nfunc NewMockReporter(expectedOnMetricsProcessedCalls int) *MockReporter {\n\tm := MockReporter{}\n\tm.wgMetricsProcessed.Add(expectedOnMetricsProcessedCalls)\n\treturn &m\n}\n\n\n\nfunc (m *MockReporter) OnTranslationError(ctx context.Context, err error) {\n}\n\nfunc (m *MockReporter) OnMetricsProcessed(ctx context.Context, numReceivedMetricPoints int, err error) {\n\tm.wgMetricsProcessed.Done()\n}\n\nfunc (m *MockReporter) OnDebugf(template string, args ...interface{}) {\n}\n\n\n\nfunc (m *MockReporter) WaitAllOnMetricsProcessedCalls() {\n\tm.wgMetricsProcessed.Wait()\n}\n\nfunc (m *MockReporter) OnDataReceived(ctx context.Context) context.Context ", "output": "{\n\treturn ctx\n}"} {"input": "package cli\n\nimport \"github.com/scaleway/scaleway-cli/pkg/commands\"\n\nvar cmdExec = &Command{\n\tExec: runExec,\n\tUsageLine: \"exec [OPTIONS] SERVER [COMMAND] [ARGS...]\",\n\tDescription: \"Run a command on a running server\",\n\tHelp: \"Run a command on a running server.\",\n\tExamples: `\n $ scw exec myserver\n $ scw exec myserver bash\n $ scw exec --gateway=myotherserver myserver bash\n $ scw exec myserver 'tmux a -t joe || tmux new -s joe || bash'\n $ exec_secure=1 scw exec myserver bash\n $ scw exec -w $(scw start $(scw create ubuntu-trusty)) bash\n $ scw exec $(scw start -w $(scw create ubuntu-trusty)) bash\n $ scw exec myserver tmux new -d sleep 10\n $ scw exec myserver ls -la | grep password\n $ cat local-file | scw exec myserver 'cat > remote/path'\n`,\n}\n\n\n\n\nvar execW bool \nvar execTimeout float64 \nvar execHelp bool \nvar execGateway string \n\nfunc runExec(cmd *Command, rawArgs []string) error {\n\tif execHelp {\n\t\treturn cmd.PrintUsage()\n\t}\n\tif len(rawArgs) < 1 {\n\t\treturn cmd.PrintShortUsage()\n\t}\n\n\targs := commands.ExecArgs{\n\t\tTimeout: execTimeout,\n\t\tWait: execW,\n\t\tGateway: execGateway,\n\t\tServer: rawArgs[0],\n\t\tCommand: rawArgs[1:],\n\t}\n\tctx := cmd.GetContext(rawArgs)\n\treturn commands.RunExec(ctx, args)\n}\n\nfunc init() ", "output": "{\n\tcmdExec.Flag.BoolVar(&execHelp, []string{\"h\", \"-help\"}, false, \"Print usage\")\n\tcmdExec.Flag.Float64Var(&execTimeout, []string{\"T\", \"-timeout\"}, 0, \"Set timeout values to seconds\")\n\tcmdExec.Flag.BoolVar(&execW, []string{\"w\", \"-wait\"}, false, \"Wait for SSH to be ready\")\n\tcmdExec.Flag.StringVar(&execGateway, []string{\"g\", \"-gateway\"}, \"\", \"Use a SSH gateway\")\n}"} {"input": "package errbag\n\nimport (\n\t\"errors\"\n\t\"time\"\n)\n\n\n\ntype ErrBag struct {\n\twaitTime uint\n\tleakInterval uint\n\terrChan chan struct{}\n\tdone chan struct{}\n}\n\n\n\ntype Status struct {\n\tState int\n\n\tWaitTime uint\n}\n\n\ntype CallbackFunc func(status Status)\n\nconst (\n\tStatusThrottling = iota\n\n\tStatusOK\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (eb ErrBag) Inflate() {\n\tready := make(chan bool)\n\tgo func() {\n\t\tready <- true\n\t\teb.errLeak()\n\t}()\n\t<-ready\n\tclose(ready)\n}\n\n\n\nfunc (eb ErrBag) Deflate() {\n\teb.done <- struct{}{}\n\tclose(eb.done)\n\tclose(eb.errChan)\n}\n\n\n\n\n\n\n\n\n\nfunc (eb ErrBag) Record(err error, callback CallbackFunc) {\n\tif err != nil {\n\t\tselect {\n\t\tcase eb.errChan <- struct{}{}:\n\t\t\tif callback != nil {\n\t\t\t\tcallback(Status{State: StatusOK})\n\t\t\t}\n\t\tdefault:\n\t\t\tif callback != nil {\n\t\t\t\tcallback(Status{State: StatusThrottling, WaitTime: eb.waitTime})\n\t\t\t}\n\t\t\ttime.Sleep(time.Second * time.Duration(eb.waitTime))\n\t\t}\n\t}\n}\n\n\n\nfunc (eb ErrBag) errLeak() {\n\tfor {\n\t\tselect {\n\t\tcase <-eb.done:\n\t\t\treturn\n\t\tcase <-eb.errChan:\n\t\t\ttime.Sleep(time.Millisecond * time.Duration(eb.leakInterval))\n\t\t}\n\t}\n}\n\nfunc New(waitTime, errBagSize, leakInterval uint) (*ErrBag, error) ", "output": "{\n\tif waitTime == 0 {\n\t\treturn nil, errors.New(\"setting waitTime to 0 would prevent throttling\")\n\t}\n\tif errBagSize == 0 {\n\t\treturn nil, errors.New(\"setting errBagSize to 0 would prevent throttling\")\n\t}\n\tif leakInterval < 100 {\n\t\treturn nil, errors.New(\"leakInterval must be greater than 100\")\n\t}\n\n\terrChan := make(chan struct{}, errBagSize)\n\tdone := make(chan struct{}, 1)\n\treturn &ErrBag{waitTime: waitTime, leakInterval: leakInterval, errChan: errChan, done: done}, nil\n}"} {"input": "package build\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/kubecfg\"\n\t\"github.com/openshift/origin/pkg/build/api\"\n)\n\nvar buildColumns = []string{\"Name\", \"Type\", \"Status\", \"Pod Name\"}\nvar buildConfigColumns = []string{\"Name\", \"Type\", \"SourceURI\"}\n\n\n\n\n\nfunc printBuild(build *api.Build, w io.Writer) error {\n\t_, err := fmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\\n\", build.Name, build.Parameters.Strategy.Type, build.Status, build.PodName)\n\treturn err\n}\n\nfunc printBuildList(buildList *api.BuildList, w io.Writer) error {\n\tfor _, build := range buildList.Items {\n\t\tif err := printBuild(&build, w); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc printBuildConfig(bc *api.BuildConfig, w io.Writer) error {\n\t_, err := fmt.Fprintf(w, \"%s\\t%v\\t%s\\n\", bc.Name, bc.Parameters.Strategy.Type, bc.Parameters.Source.Git.URI)\n\treturn err\n}\n\nfunc printBuildConfigList(buildList *api.BuildConfigList, w io.Writer) error {\n\tfor _, buildConfig := range buildList.Items {\n\t\tif err := printBuildConfig(&buildConfig, w); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc RegisterPrintHandlers(printer *kubecfg.HumanReadablePrinter) ", "output": "{\n\tprinter.Handler(buildColumns, printBuild)\n\tprinter.Handler(buildColumns, printBuildList)\n\tprinter.Handler(buildConfigColumns, printBuildConfig)\n\tprinter.Handler(buildConfigColumns, printBuildConfigList)\n}"} {"input": "package http_auth\n\nimport \"crypto/rand\"\nimport \"fmt\"\nimport \"sync\"\nimport \"time\"\n\ntype Server struct {\n\tsync.Mutex\n\tAuthFun func(user, realm string) string\n\topaque string\n\tRealm string\n\tReaperWaitSeconds, ReapTTLSeconds int\n\trequests map[string]*reqState\n}\ntype reqState struct {\n\tnreq int\n\tsectime int64\n}\n\nfunc newServer(realm string, authfun func(user, realm string) string) *Server {\n\ts := new(Server)\n\ts.Realm = realm\n\ts.opaque = newNonce()\n\ts.AuthFun = authfun\n\ts.requests = map[string]*reqState{}\n\ts.ReaperWaitSeconds = 600\n\ts.ReapTTLSeconds = 3600\n\tgo reaper(s)\n\n\treturn s\n}\n\n\n\nfunc reaper(s *Server) {\n\tfor {\n\t\ttime.Sleep(time.Duration(s.ReaperWaitSeconds) * time.Second)\n\t\tdo_reap(s)\n\t}\n}\n\nfunc do_reap(s *Server) {\n\tnow := time.Now().UnixNano()\n\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tfor k, v := range s.requests {\n\t\tif v.sectime+int64(s.ReapTTLSeconds) < now {\n\t\t\tdelete(s.requests, k)\n\t\t}\n\t}\n}\n\nfunc newNonce() string ", "output": "{\n\tb := make([]byte, 8)\n\tn, e := rand.Read(b)\n\tif n != 8 || e != nil {\n\t\tpanic(\"rand.Reader failed!\")\n\t}\n\treturn fmt.Sprintf(\"%x\", b)\n}"} {"input": "package stores\n\nimport \"jvmgo/ch06/instructions/base\"\nimport \"jvmgo/ch06/rtda\"\n\n\ntype ISTORE struct{ base.Index8Instruction }\n\nfunc (self *ISTORE) Execute(frame *rtda.Frame) {\n\t_istore(frame, uint(self.Index))\n}\n\ntype ISTORE_0 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_0) Execute(frame *rtda.Frame) {\n\t_istore(frame, 0)\n}\n\ntype ISTORE_1 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_1) Execute(frame *rtda.Frame) {\n\t_istore(frame, 1)\n}\n\ntype ISTORE_2 struct{ base.NoOperandsInstruction }\n\n\n\ntype ISTORE_3 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_3) Execute(frame *rtda.Frame) {\n\t_istore(frame, 3)\n}\n\nfunc _istore(frame *rtda.Frame, index uint) {\n\tval := frame.OperandStack().PopInt()\n\tframe.LocalVars().SetInt(index, val)\n}\n\nfunc (self *ISTORE_2) Execute(frame *rtda.Frame) ", "output": "{\n\t_istore(frame, 2)\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/utils\"\n\nfunc init() {\n\tc := &ImportTpFromFolder{\n\t\tname: \"import_tp_from_folder\",\n\t\trpcMethod: utils.APIerSv1ImportTariffPlanFromFolder,\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype ImportTpFromFolder struct {\n\tname string\n\trpcMethod string\n\trpcParams *utils.AttrImportTPFromFolder\n\trpcResult string\n\t*CommandExecuter\n}\n\nfunc (self *ImportTpFromFolder) Name() string {\n\treturn self.name\n}\n\nfunc (self *ImportTpFromFolder) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\n\n\nfunc (self *ImportTpFromFolder) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *ImportTpFromFolder) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *ImportTpFromFolder) RpcParams(reset bool) interface{} ", "output": "{\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &utils.AttrImportTPFromFolder{}\n\t}\n\treturn self.rpcParams\n}"} {"input": "package expect\n\nimport (\n\t\"testing\"\n)\n\ntype EachTests struct {\n\tcalled bool\n}\n\nfunc Test_Each(t *testing.T) {\n\tExpectify(new(EachTests), t)\n}\n\n\n\nfunc (e *EachTests) Each(f func()) {\n\te.called = true\n\tf()\n}\n\nfunc (e *EachTests) RunsEach() ", "output": "{\n\tExpect(e.called).To.Equal(true)\n}"} {"input": "package main\n\nimport (\n\t\"sort\"\n)\n\n\ntype RankedCoordFinder struct {\n\tboard Board\n\tremaining []*Coord\n}\n\nfunc (f *RankedCoordFinder) NextOpenCoordinate(board Board, coord XY) (*Coord, bool) {\n\tf.board = board\n\tf.RefreshCoordinates()\n\n\tif len(f.remaining) == 0 {\n\t\treturn nil, false\n\t}\n\n\tc := f.remaining[0]\n\tf.remaining = f.remaining[0:]\n\n\treturn c, true\n}\n\nfunc (f *RankedCoordFinder) RefreshCoordinates() {\n\tf.remaining = []*Coord{}\n\tfor x := 0; x < len(f.board); x++ {\n\t\tfor y := 0; y < len(f.board); y++ {\n\t\t\tif f.board[x][y] == 0 {\n\t\t\t\tf.remaining = append(f.remaining, &Coord{x, y})\n\t\t\t}\n\t\t}\n\t}\n\tsort.Sort(f)\n}\n\nfunc (f *RankedCoordFinder) Len() int {\n\treturn len(f.remaining)\n}\nfunc (f *RankedCoordFinder) Less(i, j int) bool {\n\treturn len(f.board.AvailableValuesAtCoordinate(f.remaining[i])) <\n\t\tlen(f.board.AvailableValuesAtCoordinate(f.remaining[j]))\n}\n\n\nfunc (f *RankedCoordFinder) Swap(i, j int) ", "output": "{\n\tf.remaining[i], f.remaining[j] = f.remaining[j], f.remaining[i]\n}"} {"input": "package gomniauth\n\nimport (\n\t\"github.com/outrightmental/go-omniauth/test\"\n\t\"github.com/outrightmental/go-objx\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\n\n\nfunc TestProviderPublicData(t *testing.T) ", "output": "{\n\n\tprovider := new(test.TestProvider)\n\n\tprovider.On(\"Name\").Return(\"TestName\")\n\tprovider.On(\"DisplayName\").Return(\"TestDisplayName\")\n\n\tpublicData, _ := ProviderPublicData(provider, objx.MSI(\"loginpathFormat\", \"~auth/%s/login\"))\n\tpublicDataMap := publicData.(map[string]interface{})\n\n\tassert.Equal(t, publicDataMap[\"name\"], \"TestName\")\n\tassert.Equal(t, publicDataMap[\"display\"], \"TestDisplayName\")\n\tassert.Equal(t, publicDataMap[\"loginpath\"], \"~auth/TestName/login\")\n\n}"} {"input": "package firestore \n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\n\n\n\nfunc DefaultAuthScopes() []string {\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t\t\"https:www.googleapis.com/auth/datastore\",\n\t}\n}\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context ", "output": "{\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}"} {"input": "package transport\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\ntype Config struct {\n\tUserAgent string\n\n\tTLS TLSConfig\n\n\tUsername string\n\tPassword string\n\n\tBearerToken string\n\n\tBearerTokenFile string\n\n\tImpersonate ImpersonationConfig\n\n\tDisableCompression bool\n\n\tTransport http.RoundTripper\n\n\tWrapTransport WrapperFunc\n\n\tDial func(ctx context.Context, network, address string) (net.Conn, error)\n\n\tProxy func(*http.Request) (*url.URL, error)\n}\n\n\ntype ImpersonationConfig struct {\n\tUserName string\n\tGroups []string\n\tExtra map[string][]string\n}\n\n\nfunc (c *Config) HasCA() bool {\n\treturn len(c.TLS.CAData) > 0 || len(c.TLS.CAFile) > 0\n}\n\n\nfunc (c *Config) HasBasicAuth() bool {\n\treturn len(c.Username) != 0\n}\n\n\nfunc (c *Config) HasTokenAuth() bool {\n\treturn len(c.BearerToken) != 0 || len(c.BearerTokenFile) != 0\n}\n\n\nfunc (c *Config) HasCertAuth() bool {\n\treturn (len(c.TLS.CertData) != 0 || len(c.TLS.CertFile) != 0) && (len(c.TLS.KeyData) != 0 || len(c.TLS.KeyFile) != 0)\n}\n\n\n\n\n\n\n\n\nfunc (c *Config) Wrap(fn WrapperFunc) {\n\tc.WrapTransport = Wrappers(c.WrapTransport, fn)\n}\n\n\ntype TLSConfig struct {\n\tCAFile string \n\tCertFile string \n\tKeyFile string \n\tReloadTLSFiles bool \n\n\tInsecure bool \n\tServerName string \n\n\tCAData []byte \n\tCertData []byte \n\tKeyData []byte \n\n\tNextProtos []string\n\n\tGetCert func() (*tls.Certificate, error) \n}\n\nfunc (c *Config) HasCertCallback() bool ", "output": "{\n\treturn c.TLS.GetCert != nil\n}"} {"input": "package parsex\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype ParsexError struct {\n\tPos int\n\tMessage string\n}\n\nfunc (err ParsexError) Error() string {\n\treturn fmt.Sprintf(\"pos %d :\\n%s\",\n\t\terr.Pos, err.Message)\n}\n\ntype ParsexState interface {\n\tNext(pred func(int, interface{}) (interface{}, error)) (x interface{}, err error)\n\tPos() int\n\tSeekTo(int)\n\tTrap(message string, args ...interface{}) error\n}\n\ntype StateInMemory struct {\n\tbuffer []interface{}\n\tpos int\n}\n\nfunc NewStateInMemory(buffer []interface{}) *StateInMemory {\n\treturn &StateInMemory{buffer, 0}\n}\n\nfunc (this *StateInMemory) Next(pred func(int, interface{}) (interface{}, error)) (x interface{}, err error) {\n\tbuffer := (*this).buffer\n\tif (*this).pos < len(buffer) {\n\t\tx := buffer[(*this).pos]\n\t\toutput, err := pred((*this).pos, x)\n\t\tif err == nil {\n\t\t\t(*this).pos++\n\t\t\treturn output, nil\n\t\t} else {\n\t\t\treturn x, err\n\t\t}\n\t} else {\n\t\treturn nil, io.EOF\n\t}\n}\n\nfunc (this *StateInMemory) Pos() int {\n\treturn (*this).pos\n}\n\n\n\nfunc (this *StateInMemory) Trap(message string, args ...interface{}) error {\n\treturn ParsexError{(*this).pos,\n\t\tfmt.Sprintf(message, args...)}\n}\n\nfunc (this *StateInMemory) SeekTo(pos int) ", "output": "{\n\tend := len((*this).buffer)\n\tif pos < 0 || pos > end {\n\t\tmessage := fmt.Sprintf(\"%d out range [0, %d]\", pos, end)\n\t\tpanic(errors.New(message))\n\t}\n\t(*this).pos = pos\n}"} {"input": "package batch\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype ManagementClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) ManagementClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient ", "output": "{\n\treturn ManagementClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package heroku\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/bgentry/heroku-go\"\n\t\"github.com/remind101/empire\"\n\t\"golang.org/x/net/context\"\n)\n\ntype Formation heroku.Formation\n\ntype PatchFormation struct {\n\t*empire.Empire\n}\n\ntype PatchFormationForm struct {\n\tUpdates []struct {\n\t\tProcess empire.ProcessType `json:\"process\"` \n\t\tQuantity int `json:\"quantity\"`\n\t\tSize *empire.Constraints `json:\"size\"`\n\t} `json:\"updates\"`\n}\n\n\n\nfunc (h *PatchFormation) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error ", "output": "{\n\tvar form PatchFormationForm\n\n\tif err := Decode(r, &form); err != nil {\n\t\treturn err\n\t}\n\n\tapp, err := findApp(ctx, h)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar resp []*Formation\n\tfor _, up := range form.Updates {\n\t\tp, err := h.AppsScale(ctx, app, up.Process, up.Quantity, up.Size)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp = append(resp, &Formation{\n\t\t\tType: string(p.Type),\n\t\t\tQuantity: p.Quantity,\n\t\t\tSize: p.Constraints.String(),\n\t\t})\n\t}\n\n\tw.WriteHeader(200)\n\treturn Encode(w, resp)\n}"} {"input": "package store\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/ngaut/log\"\n\t\"github.com/reborndb/qdb/pkg/engine/rocksdb\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc TestT(t *testing.T) {\n\tTestingT(t)\n}\n\nvar _ = Suite(&testStoreSuite{})\n\ntype testStoreSuite struct {\n\ts *Store\n}\n\nfunc (s *testStoreSuite) SetUpSuite(c *C) {\n\ts.s = testCreateStore(c)\n}\n\n\n\nfunc (s *testStoreSuite) checkCompact(c *C) {\n\terr := s.s.CompactAll()\n\tc.Assert(err, IsNil)\n}\n\nfunc (s *testStoreSuite) checkEmpty(c *C) {\n\tit := s.s.getIterator()\n\tdefer s.s.putIterator(it)\n\n\tit.SeekToFirst()\n\tc.Assert(it.Error(), IsNil)\n\tc.Assert(it.Valid(), Equals, false)\n}\n\nfunc testCreateStore(c *C) *Store {\n\tbase := fmt.Sprintf(\"/tmp/test_qdb/test_store\")\n\terr := os.RemoveAll(base)\n\tc.Assert(err, IsNil)\n\n\terr = os.MkdirAll(base, 0700)\n\tc.Assert(err, IsNil)\n\n\tconf := rocksdb.NewDefaultConfig()\n\ttestdb, err := rocksdb.Open(path.Join(base, \"db\"), conf, false)\n\tc.Assert(err, IsNil)\n\n\ts := New(testdb)\n\treturn s\n}\n\nfunc init() {\n\tlog.SetLevel(log.LOG_LEVEL_ERROR)\n}\n\nfunc sleepms(n int) {\n\ttime.Sleep(time.Millisecond * time.Duration(n))\n}\n\nfunc (s *testStoreSuite) TearDownSuite(c *C) ", "output": "{\n\tif s.s != nil {\n\t\ts.s.Close()\n\t\ts = nil\n\t}\n}"} {"input": "package trust\n\nimport (\n\t\"context\"\n\t\"crypto/sha256\"\n\t\"crypto/x509\"\n\n\t\"github.com/scionproto/scion/go/lib/addr\"\n\t\"github.com/scionproto/scion/go/lib/scrypto/cppki\"\n)\n\n\ntype TRCsQuery struct {\n\tISD []addr.ISD\n\tLatest bool\n}\n\n\ntype TrustAPI interface {\n\tSignedTRCs(context.Context, TRCsQuery) (cppki.SignedTRCs, error)\n\tChain(context.Context, []byte) ([]*x509.Certificate, error)\n}\n\n\n\n\nfunc ChainID(chain []*x509.Certificate) []byte ", "output": "{\n\th := sha256.New()\n\th.Write(chain[0].Raw)\n\th.Write(chain[1].Raw)\n\treturn h.Sum(nil)\n}"} {"input": "package encode\n\nimport \"testing\"\n\n\nfunc TestRunLengthDecode(t *testing.T) {\n\tfor _, test := range decodeTests {\n\t\tif actual := RunLengthDecode(test.input); actual != test.expected {\n\t\t\tt.Errorf(\"FAIL %s - RunLengthDecode(%s) = %q, expected %q.\",\n\t\t\t\ttest.description, test.input, actual, test.expected)\n\t\t}\n\t\tt.Logf(\"PASS RunLengthDecode - %s\", test.description)\n\t}\n}\nfunc TestRunLengthEncodeDecode(t *testing.T) {\n\tfor _, test := range encodeDecodeTests {\n\t\tif actual := RunLengthDecode(RunLengthEncode(test.input)); actual != test.expected {\n\t\t\tt.Errorf(\"FAIL %s - RunLengthDecode(RunLengthEncode(%s)) = %q, expected %q.\",\n\t\t\t\ttest.description, test.input, actual, test.expected)\n\t\t}\n\t\tt.Logf(\"PASS %s\", test.description)\n\t}\n}\n\nfunc TestRunLengthEncode(t *testing.T) ", "output": "{\n\tfor _, test := range encodeTests {\n\t\tif actual := RunLengthEncode(test.input); actual != test.expected {\n\t\t\tt.Errorf(\"FAIL %s - RunLengthEncode(%s) = %q, expected %q.\",\n\t\t\t\ttest.description, test.input, actual, test.expected)\n\t\t}\n\t\tt.Logf(\"PASS RunLengthEncode - %s\", test.description)\n\t}\n}"} {"input": "package probe_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/minio/minio/pkg/probe\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype MySuite struct{}\n\nvar _ = Suite(&MySuite{})\n\n\n\nfunc testDummy1() *probe.Error {\n\treturn testDummy0().Trace(\"DummyTag1\")\n}\n\nfunc testDummy2() *probe.Error {\n\treturn testDummy1().Trace(\"DummyTag2\")\n}\n\nfunc (s *MySuite) TestProbe(c *C) {\n\tes := testDummy2().Trace(\"TopOfStack\")\n\tc.Assert(es, Not(Equals), nil)\n\n\tnewES := es.Trace()\n\tc.Assert(newES, Not(Equals), nil)\n}\n\nfunc (s *MySuite) TestWrappedError(c *C) {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\tes := probe.NewError(e) \n\te = probe.WrapError(es) \n\t_, ok := probe.UnwrapError(e)\n\tc.Assert(ok, Equals, true)\n}\n\nfunc testDummy0() *probe.Error ", "output": "{\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\treturn probe.NewError(e)\n}"} {"input": "package test\n\nimport \"github.com/tidepool-org/platform/test\"\n\nfunc NewServiceSecret() string {\n\treturn test.RandomStringFromRangeAndCharset(128, 128, test.CharsetAlphaNumeric)\n}\n\n\n\nfunc NewSessionToken() string {\n\treturn test.RandomStringFromRangeAndCharset(256, 256, test.CharsetAlphaNumeric)\n}\n\nfunc NewRestrictedToken() string {\n\treturn test.RandomStringFromRangeAndCharset(40, 40, test.CharsetAlphaNumeric)\n}\n\nfunc NewAccessToken() string ", "output": "{\n\treturn test.RandomStringFromRangeAndCharset(256, 256, test.CharsetAlphaNumeric)\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/hyperledger/fabric/common/channelconfig\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n)\n\n\ntype Orderer struct {\n\tConsensusTypeVal string\n\tBatchSizeVal *ab.BatchSize\n\tBatchTimeoutVal time.Duration\n\tKafkaBrokersVal []string\n\tMaxChannelsCountVal uint64\n\tOrganizationsVal map[string]channelconfig.Org\n\tCapabilitiesVal channelconfig.OrdererCapabilities\n}\n\n\nfunc (scm *Orderer) ConsensusType() string {\n\treturn scm.ConsensusTypeVal\n}\n\n\nfunc (scm *Orderer) BatchSize() *ab.BatchSize {\n\treturn scm.BatchSizeVal\n}\n\n\nfunc (scm *Orderer) BatchTimeout() time.Duration {\n\treturn scm.BatchTimeoutVal\n}\n\n\nfunc (scm *Orderer) KafkaBrokers() []string {\n\treturn scm.KafkaBrokersVal\n}\n\n\nfunc (scm *Orderer) MaxChannelsCount() uint64 {\n\treturn scm.MaxChannelsCountVal\n}\n\n\n\n\n\nfunc (scm *Orderer) Capabilities() channelconfig.OrdererCapabilities {\n\treturn scm.CapabilitiesVal\n}\n\n\ntype OrdererCapabilities struct {\n\tSupportedErr error\n\n\tSetChannelModPolicyDuringCreateVal bool\n\n\tResubmissionVal bool\n}\n\n\nfunc (oc *OrdererCapabilities) Supported() error {\n\treturn oc.SupportedErr\n}\n\n\nfunc (oc *OrdererCapabilities) SetChannelModPolicyDuringCreate() bool {\n\treturn oc.SetChannelModPolicyDuringCreateVal\n}\n\n\nfunc (oc *OrdererCapabilities) Resubmission() bool {\n\treturn oc.ResubmissionVal\n}\n\nfunc (scm *Orderer) Organizations() map[string]channelconfig.Org ", "output": "{\n\treturn scm.OrganizationsVal\n}"} {"input": "package config\n\nimport (\n\t\"github.com/juju/errors\"\n)\n\n\ntype baseConfigurer struct {\n\tseries string\n\tdefaultPackages []string\n\tcloudArchivePackages map[string]struct{}\n}\n\n\nfunc (c *baseConfigurer) DefaultPackages() []string {\n\treturn c.defaultPackages\n}\n\n\n\n\n\nfunc (c *baseConfigurer) IsCloudArchivePackage(pack string) bool {\n\t_, ok := c.cloudArchivePackages[pack]\n\treturn ok\n}\n\nfunc (c *baseConfigurer) GetPackageNameForSeries(pack, series string) (string, error) ", "output": "{\n\tif c.series == series {\n\t\treturn pack, nil\n\t}\n\n\tswitch series {\n\tcase \"centos7\":\n\t\tres, ok := centOSToUbuntuPackageNameMap[pack]\n\t\tif !ok {\n\t\t\treturn \"\", errors.Errorf(\"no equivalent package found for series %s: %s\", series, pack)\n\t\t}\n\t\treturn res, nil\n\tdefault:\n\t\tres, ok := ubuntuToCentOSPackageNameMap[pack]\n\t\tif !ok {\n\t\t\treturn \"\", errors.Errorf(\"no equivalent package found for series %s: %s\", series, pack)\n\t\t}\n\t\treturn res, nil\n\t}\n}"} {"input": "package cloud\n\nimport (\n\t\"context\"\n\n\t\"k8s.io/kubernetes/pkg/cloudprovider/providers/gce/cloud/meta\"\n)\n\n\ntype ProjectRouter interface {\n\tProjectID(ctx context.Context, version meta.Version, service string) string\n}\n\n\ntype SingleProjectRouter struct {\n\tID string\n}\n\n\n\n\nfunc (r *SingleProjectRouter) ProjectID(ctx context.Context, version meta.Version, service string) string ", "output": "{\n\treturn r.ID\n}"} {"input": "package numwords\n\nimport \"fmt\"\n\n\n\nfunc ExampleParseString() {\n\ts := \"I've got three apples and two and a half bananas\"\n\tfmt.Println(ParseString(s))\n\n}\n\nfunc ExampleParseFloat() {\n\tf, _ := ParseFloat(\"eight and three quarters\")\n\tfmt.Println(f)\n\n}\n\nfunc ExampleParseInt() {\n\ti, _ := ParseInt(\"fourteen ninety two\")\n\tfmt.Println(i)\n\n}\n\nfunc ExampleIncludeSecond() {\n\ts := \"My chili won second place at the county fair\"\n\tfmt.Println(ParseString(s))\n\n\ts = \"One second ago\"\n\tIncludeSecond(false)\n\tfmt.Println(ParseString(s))\n\n}\n\nfunc Example() ", "output": "{\n\ts := \"I've got three apples and two and a half bananas\"\n\tfmt.Println(ParseString(s))\n\n\ts = \"My chili won second place at the county fair\"\n\tfmt.Println(ParseString(s))\n\n\ti, _ := ParseInt(\"fourteen ninety two\")\n\tfmt.Println(i)\n\n\tf, _ := ParseFloat(\"eight and three quarters\")\n\tfmt.Println(f)\n\n}"} {"input": "package dockershim\n\nimport (\n\t\"fmt\"\n\n\truntimeapi \"k8s.io/cri-api/pkg/apis/runtime/v1alpha2\"\n)\n\n\n\nfunc (ds *dockerService) getContainerStats(c *runtimeapi.Container) (*runtimeapi.ContainerStats, error) ", "output": "{\n\treturn nil, fmt.Errorf(\"not implemented\")\n}"} {"input": "package procfs\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\nfunc GetFullContainerName(pid int) (string, error) ", "output": "{\n\treturn \"\", fmt.Errorf(\"GetFullContainerName is unsupported in this build\")\n}"} {"input": "package main\n\nimport (\n\t\"gomage/controllers\"\n\t_ \"gomage/routers\"\n\n\t\"github.com/astaxie/beego\"\n\t_ \"github.com/astaxie/beego/session/redis\"\n)\n\n\n\nfunc main() {\n\tbeego.Run()\n}\n\nfunc init() ", "output": "{\n\n\tbeego.AddFuncMap(\"Option\", controllers.MethodName)\n\n\tbeego.AddFuncMap(\"i18n\", controllers.I18n)\n\n}"} {"input": "package internalversion\n\nimport (\n\tapi \"k8s.io/kubernetes/pkg/api\"\n\tregistered \"k8s.io/kubernetes/pkg/apimachinery/registered\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n)\n\ntype QuotaInterface interface {\n\tRESTClient() restclient.Interface\n\tClusterResourceQuotasGetter\n}\n\n\ntype QuotaClient struct {\n\trestClient restclient.Interface\n}\n\nfunc (c *QuotaClient) ClusterResourceQuotas() ClusterResourceQuotaInterface {\n\treturn newClusterResourceQuotas(c)\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *restclient.Config) *QuotaClient {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c restclient.Interface) *QuotaClient {\n\treturn &QuotaClient{c}\n}\n\nfunc setConfigDefaults(config *restclient.Config) error {\n\tg, err := registered.Group(\"quota.openshift.io\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.APIPath = \"/apis\"\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = restclient.DefaultKubernetesUserAgent()\n\t}\n\tif config.GroupVersion == nil || config.GroupVersion.Group != g.GroupVersion.Group {\n\t\tcopyGroupVersion := g.GroupVersion\n\t\tconfig.GroupVersion = ©GroupVersion\n\t}\n\tconfig.NegotiatedSerializer = api.Codecs\n\n\tif config.QPS == 0 {\n\t\tconfig.QPS = 5\n\t}\n\tif config.Burst == 0 {\n\t\tconfig.Burst = 10\n\t}\n\treturn nil\n}\n\n\n\nfunc (c *QuotaClient) RESTClient() restclient.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfig(c *restclient.Config) (*QuotaClient, error) ", "output": "{\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := restclient.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &QuotaClient{client}, nil\n}"} {"input": "package apn\n\n\ntype ApnEnv int\n\nconst (\n\tTest = iota \n\tSandbox\n\tProduction\n)\n\n\n\nfunc envObject(envString string) (env ApnEnv) {\n\tif envString == \"test\" {\n\t\tenv = Test\n\t} else if envString == \"sandbox\" {\n\t\tenv = Sandbox\n\t} else if envString == \"production\" {\n\t\tenv = Production\n\t}\n\treturn\n}\n\n\nvar queues []Queue = make([]Queue, 10)\n\nfunc envString(env ApnEnv) (envString string) ", "output": "{\n\tif env == Test {\n\t\tenvString = \"test\"\n\t} else if env == Sandbox {\n\t\tenvString = \"sandbox\"\n\t} else if env == Production {\n\t\tenvString = \"production\"\n\t}\n\treturn\n}"} {"input": "package iso20022\n\n\ntype RepoCallRequestStatus8Choice struct {\n\n\tCode *RepoCallRequestStatus1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification30 `xml:\"Prtry\"`\n}\n\n\n\nfunc (r *RepoCallRequestStatus8Choice) AddProprietary() *GenericIdentification30 {\n\tr.Proprietary = new(GenericIdentification30)\n\treturn r.Proprietary\n}\n\nfunc (r *RepoCallRequestStatus8Choice) SetCode(value string) ", "output": "{\n\tr.Code = (*RepoCallRequestStatus1Code)(&value)\n}"} {"input": "package iso20022\n\n\ntype VerificationReason1Choice struct {\n\n\tCode *ExternalVerificationReason1Code `xml:\"Cd\"`\n\n\tProprietary *Max35Text `xml:\"Prtry\"`\n}\n\nfunc (v *VerificationReason1Choice) SetCode(value string) {\n\tv.Code = (*ExternalVerificationReason1Code)(&value)\n}\n\n\n\nfunc (v *VerificationReason1Choice) SetProprietary(value string) ", "output": "{\n\tv.Proprietary = (*Max35Text)(&value)\n}"} {"input": "package internalversion\n\nimport (\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"github.com/hyperhq/client-go/tools/cache\"\n\tcore \"k8s.io/kubernetes/pkg/apis/core\"\n)\n\n\ntype PodTemplateLister interface {\n\tList(selector labels.Selector) (ret []*core.PodTemplate, err error)\n\tPodTemplates(namespace string) PodTemplateNamespaceLister\n\tPodTemplateListerExpansion\n}\n\n\ntype podTemplateLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewPodTemplateLister(indexer cache.Indexer) PodTemplateLister {\n\treturn &podTemplateLister{indexer: indexer}\n}\n\n\nfunc (s *podTemplateLister) List(selector labels.Selector) (ret []*core.PodTemplate, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*core.PodTemplate))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *podTemplateLister) PodTemplates(namespace string) PodTemplateNamespaceLister {\n\treturn podTemplateNamespaceLister{indexer: s.indexer, namespace: namespace}\n}\n\n\ntype PodTemplateNamespaceLister interface {\n\tList(selector labels.Selector) (ret []*core.PodTemplate, err error)\n\tGet(name string) (*core.PodTemplate, error)\n\tPodTemplateNamespaceListerExpansion\n}\n\n\n\ntype podTemplateNamespaceLister struct {\n\tindexer cache.Indexer\n\tnamespace string\n}\n\n\nfunc (s podTemplateNamespaceLister) List(selector labels.Selector) (ret []*core.PodTemplate, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*core.PodTemplate))\n\t})\n\treturn ret, err\n}\n\n\n\n\nfunc (s podTemplateNamespaceLister) Get(name string) (*core.PodTemplate, error) ", "output": "{\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(core.Resource(\"podtemplate\"), name)\n\t}\n\treturn obj.(*core.PodTemplate), nil\n}"} {"input": "package transport\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\ntype Config struct {\n\tUserAgent string\n\n\tTLS TLSConfig\n\n\tUsername string\n\tPassword string\n\n\tBearerToken string\n\n\tBearerTokenFile string\n\n\tImpersonate ImpersonationConfig\n\n\tDisableCompression bool\n\n\tTransport http.RoundTripper\n\n\tWrapTransport WrapperFunc\n\n\tDial func(ctx context.Context, network, address string) (net.Conn, error)\n\n\tProxy func(*http.Request) (*url.URL, error)\n}\n\n\ntype ImpersonationConfig struct {\n\tUserName string\n\tGroups []string\n\tExtra map[string][]string\n}\n\n\nfunc (c *Config) HasCA() bool {\n\treturn len(c.TLS.CAData) > 0 || len(c.TLS.CAFile) > 0\n}\n\n\n\n\n\nfunc (c *Config) HasTokenAuth() bool {\n\treturn len(c.BearerToken) != 0 || len(c.BearerTokenFile) != 0\n}\n\n\nfunc (c *Config) HasCertAuth() bool {\n\treturn (len(c.TLS.CertData) != 0 || len(c.TLS.CertFile) != 0) && (len(c.TLS.KeyData) != 0 || len(c.TLS.KeyFile) != 0)\n}\n\n\nfunc (c *Config) HasCertCallback() bool {\n\treturn c.TLS.GetCert != nil\n}\n\n\n\n\n\nfunc (c *Config) Wrap(fn WrapperFunc) {\n\tc.WrapTransport = Wrappers(c.WrapTransport, fn)\n}\n\n\ntype TLSConfig struct {\n\tCAFile string \n\tCertFile string \n\tKeyFile string \n\tReloadTLSFiles bool \n\n\tInsecure bool \n\tServerName string \n\n\tCAData []byte \n\tCertData []byte \n\tKeyData []byte \n\n\tNextProtos []string\n\n\tGetCert func() (*tls.Certificate, error) \n}\n\nfunc (c *Config) HasBasicAuth() bool ", "output": "{\n\treturn len(c.Username) != 0\n}"} {"input": "package log\n\ntype logLevel struct {\n\tLevel int\n\tPrefix string\n\tColorFunc func(...interface{}) string\n}\n\ntype logLevels []*logLevel\n\nfunc (l *logLevels) getFunc(Level int) func(...interface{}) string {\n\tlevel := l.getLevel(Level)\n\tif level != nil {\n\t\treturn level.ColorFunc\n\t}\n\treturn nil\n}\n\n\n\nfunc (l *logLevels) getLevel(Level int) *logLevel ", "output": "{\n\tfor _, item := range *l {\n\t\tif item.Level == Level {\n\t\t\treturn item\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package message\n\nimport (\n\t\"github.com/pinfake/pes6go/data/block\"\n)\n\ntype PlayerFriends struct {\n\t*block.PlayerFriends\n}\n\nfunc (PlayerFriends) GetBlocks() []*block.Block {\n\tvar blocks []*block.Block\n\n\tblocks = append(blocks, block.GetBlocks(0x3082, block.Uint32{0})...)\n\tblocks = append(blocks, block.GetBlocks(0x3086, block.Void{})...)\n\treturn blocks\n}\n\n\n\nfunc NewPlayerFriends(info *block.PlayerFriends) PlayerFriends ", "output": "{\n\treturn PlayerFriends{info}\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc foo(x int) bool {\n\treturn x == x \n}\n\nfunc isNaN(x float32) bool {\n\treturn x != x \n}\n\nfunc main() {\n\tfoo(42)\n}\n\nconst mode = \"Debug\"\n\nfunc log(msg string) {\n\tif mode == \"Debug\" {\n\t\tfmt.Println(msg)\n\t}\n}\n\nfunc bar() {\n\tif ptrsize == 8 { \n\t\tfmt.Println()\n\t}\n}\n\nfunc bump(x *int) {\n\t*x++\n}\n\n\n\ntype counter int\n\nfunc (x *counter) bump() {\n\t*x++\n}\n\nfunc (x counter) bimp() {\n\tx++\n}\n\nfunc baz2() bool {\n\tvar x counter\n\tx.bump()\n\treturn x == 0 \n}\n\nfunc baz3() bool {\n\tvar y counter\n\ty.bimp()\n\treturn y == 0 \n}\n\nfunc baz() bool ", "output": "{\n\tvar x = 0\n\tbump(&x)\n\treturn x == 0\n}"} {"input": "package main\n\nimport \"fmt\"\n\nconst target int = 200 \nvar coins = []int{1, 2, 5, 10, 20, 50, 100, 200} \n\n\nfunc recursion(aTarget int, aCoins []int, size int) int {\n\n\tif aTarget < 0 {\n\t\treturn 0\n\t}\n\tif aTarget == 0 {\n\t\treturn 1\n\t}\n\tif size == 1 {\n\t\treturn 1\n\t}\n\treturn recursion(aTarget, aCoins, size-1) + recursion(aTarget-aCoins[size-1], aCoins, size)\n\n}\n\n\n\n\n\n\nfunc main() {\n\tfmt.Println(\"Recursion Way:\", recursion(target, coins, len(coins)))\n\tfmt.Print(\"Dynamic Way : \")\n\tdynamic()\n\n}\n\nfunc dynamic() ", "output": "{\n\tways := make([]int, target+1)\n\tways[0] = 1 \n\n\tfor _, v := range coins {\n\t\tfor x := v; x <= (target); x++ {\n\t\t\tways[x] += ways[x-v]\n\t\t}\n\t}\n\tfmt.Println(ways[target])\n}"} {"input": "package web\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"path\"\n\n\t\"github.com/cafebazaar/blacksmith/templating\"\n)\n\nconst (\n\ttemplatesDebugTag = \"WEB-T\"\n)\n\nfunc (ws *webServer) generateTemplateForMachine(templateName string, w http.ResponseWriter, r *http.Request) string {\n\t_, macStr := path.Split(r.URL.Path)\n\n\tmac, err := net.ParseMAC(macStr)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(`Error while parsing the mac: %q`, err), 500)\n\t\treturn \"\"\n\t}\n\n\tmachineInterface := ws.ds.MachineInterface(mac)\n\t_, err = machineInterface.Machine(false, nil)\n\tif err != nil {\n\t\thttp.Error(w, \"Machine not found\", 404)\n\t\treturn \"\"\n\t}\n\n\tcc, err := templating.ExecuteTemplateFolder(\n\t\tpath.Join(ws.ds.WorkspacePath(), \"config\", templateName), ws.ds, machineInterface, r.Host)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(`Error while executing the template: %q`, err), 500)\n\t\treturn \"\"\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Write([]byte(cc))\n\n\treturn cc\n}\n\n\n\n\n\n\n\nfunc (ws *webServer) Ignition(w http.ResponseWriter, r *http.Request) {\n\tws.generateTemplateForMachine(\"ignition\", w, r)\n}\n\n\n\nfunc (ws *webServer) Bootparams(w http.ResponseWriter, r *http.Request) {\n\tws.generateTemplateForMachine(\"bootparams\", w, r)\n}\n\nfunc (ws *webServer) Cloudconfig(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tconfig := ws.generateTemplateForMachine(\"cloudconfig\", w, r)\n\n\tif config != \"\" && r.FormValue(\"validate\") != \"\" {\n\t\tw.Write([]byte(templating.ValidateCloudConfig(config)))\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nfunc NashPath() (string, error) {\n\tnashpath := os.Getenv(\"NASHPATH\")\n\tif nashpath != \"\" {\n\t\treturn nashpath, nil\n\t}\n\th, err := home()\n\treturn filepath.Join(h, \"nash\"), err\n}\n\n\n\nfunc home() (string, error) {\n\thomedir, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif homedir == \"\" {\n\t\treturn \"\", errors.New(\"invalid empty home dir\")\n\t}\n\treturn homedir, nil\n}\n\nfunc NashRoot() (string, error) ", "output": "{\n\tnashroot, ok := os.LookupEnv(\"NASHROOT\")\n\tif ok {\n\t\treturn nashroot, nil\n\t}\n\n\th, err := home()\n\treturn filepath.Join(h, \"nashroot\"), err\n}"} {"input": "package precis\n\nimport (\n\t\"unicode\"\n\t\"unicode/utf8\"\n\n\t\"golang.org/x/text/transform\"\n)\n\ntype nickAdditionalMapping struct {\n\tnotStart bool\n\tprevSpace bool\n}\n\nfunc (t *nickAdditionalMapping) Reset() {\n\tt.prevSpace = false\n\tt.notStart = false\n}\n\n\n\nfunc (t *nickAdditionalMapping) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) ", "output": "{\n\tfor nSrc < len(src) {\n\t\tr, size := utf8.DecodeRune(src[nSrc:])\n\t\tif size == 0 { \n\t\t\tif !atEOF {\n\t\t\t\treturn nDst, nSrc, transform.ErrShortSrc\n\t\t\t}\n\t\t\tsize = 1\n\t\t}\n\t\tif unicode.Is(unicode.Zs, r) {\n\t\t\tt.prevSpace = true\n\t\t} else {\n\t\t\tif t.prevSpace && t.notStart {\n\t\t\t\tdst[nDst] = ' '\n\t\t\t\tnDst += 1\n\t\t\t}\n\t\t\tif size != copy(dst[nDst:], src[nSrc:nSrc+size]) {\n\t\t\t\tnDst += size\n\t\t\t\treturn nDst, nSrc, transform.ErrShortDst\n\t\t\t}\n\t\t\tnDst += size\n\t\t\tt.prevSpace = false\n\t\t\tt.notStart = true\n\t\t}\n\t\tnSrc += size\n\t}\n\treturn nDst, nSrc, nil\n}"} {"input": "package tfs\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/richardwilkes/toolbox/errs\"\n)\n\ntype vfs struct {\n\tstorage string\n\tname string\n\toffset int64\n\tlength int64\n\tmode os.FileMode\n\tmodTime time.Time\n\tchildren []*vfs\n}\n\nfunc (v *vfs) Name() string {\n\treturn v.name\n}\n\nfunc (v *vfs) Size() int64 {\n\treturn v.length\n}\n\nfunc (v *vfs) Mode() os.FileMode {\n\treturn v.mode\n}\n\nfunc (v *vfs) ModTime() time.Time {\n\treturn v.modTime\n}\n\nfunc (v *vfs) IsDir() bool {\n\treturn (v.mode & os.ModeDir) == os.ModeDir\n}\n\n\n\nfunc (v *vfs) open() (http.File, error) {\n\tif v.IsDir() {\n\t\treturn &vdir{owner: v}, nil\n\t}\n\tf, err := os.Open(v.storage)\n\tif err != nil {\n\t\treturn nil, errs.NewWithCausef(err, \"Unable to open %s\", v.name)\n\t}\n\treturn &vfile{\n\t\towner: v,\n\t\tfile: f,\n\t\tsr: io.NewSectionReader(f, v.offset, v.length),\n\t}, nil\n}\n\nfunc (v *vfs) Sys() interface{} ", "output": "{\n\treturn nil\n}"} {"input": "package api\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/google/gapid/core/data/id\"\n\t\"github.com/google/gapid/core/image\"\n\t\"github.com/google/gapid/gapil/constset\"\n)\n\n\ntype API interface {\n\tName() string\n\n\tIndex() uint8\n\n\tID() ID\n\n\tConstantSets() *constset.Pack\n\n\tGetFramebufferAttachmentInfo(\n\t\tctx context.Context,\n\t\tafter []uint64,\n\t\tstate *GlobalState,\n\t\tthread uint64,\n\t\tattachment FramebufferAttachment) (width, height, index uint32, format *image.Format, err error)\n\n\tContext(state *GlobalState, thread uint64) Context\n\n\tCreateCmd(name string) Cmd\n}\n\n\ntype ID id.ID\n\n\n\nfunc (i ID) String() string { return id.ID(i).String() }\n\n\ntype APIObject interface {\n\tAPI() API\n}\n\nvar apis = map[ID]API{}\nvar indices = map[uint8]bool{}\n\n\n\nfunc Register(api API) {\n\tid := api.ID()\n\tif _, present := apis[id]; present {\n\t\tpanic(fmt.Errorf(\"API %s registered more than once\", id))\n\t}\n\tapis[id] = api\n\n\tindex := api.Index()\n\tif _, present := indices[index]; present {\n\t\tpanic(fmt.Errorf(\"API %s used an occupied index %d\", id, index))\n\t}\n\tindices[index] = true\n}\n\n\n\nfunc Find(id ID) API {\n\treturn apis[id]\n}\n\nfunc (i ID) IsValid() bool ", "output": "{ return id.ID(i).IsValid() }"} {"input": "package x509\n\nimport (\n\t\"encoding/pem\"\n)\n\n\ntype CertPool struct {\n\tbySubjectKeyId map[string][]int\n\tbyName map[string][]int\n\tcerts []*Certificate\n}\n\n\nfunc NewCertPool() *CertPool {\n\treturn &CertPool{\n\t\tmake(map[string][]int),\n\t\tmake(map[string][]int),\n\t\tnil,\n\t}\n}\n\n\n\n\nfunc (s *CertPool) findVerifiedParents(cert *Certificate) (parents []int) {\n\tif s == nil {\n\t\treturn\n\t}\n\tvar candidates []int\n\n\tif len(cert.AuthorityKeyId) > 0 {\n\t\tcandidates = s.bySubjectKeyId[string(cert.AuthorityKeyId)]\n\t}\n\tif len(candidates) == 0 {\n\t\tcandidates = s.byName[string(cert.RawIssuer)]\n\t}\n\n\tfor _, c := range candidates {\n\t\tif cert.CheckSignatureFrom(s.certs[c]) == nil {\n\t\t\tparents = append(parents, c)\n\t\t}\n\t}\n\n\treturn\n}\n\n\nfunc (s *CertPool) AddCert(cert *Certificate) {\n\tif cert == nil {\n\t\tpanic(\"adding nil Certificate to CertPool\")\n\t}\n\n\tfor _, c := range s.certs {\n\t\tif c.Equal(cert) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tn := len(s.certs)\n\ts.certs = append(s.certs, cert)\n\n\tif len(cert.SubjectKeyId) > 0 {\n\t\tkeyId := string(cert.SubjectKeyId)\n\t\ts.bySubjectKeyId[keyId] = append(s.bySubjectKeyId[keyId], n)\n\t}\n\tname := string(cert.RawSubject)\n\ts.byName[name] = append(s.byName[name], n)\n}\n\n\n\n\n\n\n\n\n\nfunc (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool) ", "output": "{\n\tfor len(pemCerts) > 0 {\n\t\tvar block *pem.Block\n\t\tblock, pemCerts = pem.Decode(pemCerts)\n\t\tif block == nil {\n\t\t\tbreak\n\t\t}\n\t\tif block.Type != \"CERTIFICATE\" || len(block.Headers) != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tcert, err := ParseCertificate(block.Bytes)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\ts.AddCert(cert)\n\t\tok = true\n\t}\n\n\treturn\n}"} {"input": "package build\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/kubecfg\"\n\t\"github.com/openshift/origin/pkg/build/api\"\n)\n\nvar buildColumns = []string{\"Name\", \"Type\", \"Status\", \"Pod Name\"}\nvar buildConfigColumns = []string{\"Name\", \"Type\", \"SourceURI\"}\n\n\n\nfunc RegisterPrintHandlers(printer *kubecfg.HumanReadablePrinter) {\n\tprinter.Handler(buildColumns, printBuild)\n\tprinter.Handler(buildColumns, printBuildList)\n\tprinter.Handler(buildConfigColumns, printBuildConfig)\n\tprinter.Handler(buildConfigColumns, printBuildConfigList)\n}\n\nfunc printBuild(build *api.Build, w io.Writer) error {\n\t_, err := fmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\\n\", build.Name, build.Parameters.Strategy.Type, build.Status, build.PodName)\n\treturn err\n}\n\nfunc printBuildList(buildList *api.BuildList, w io.Writer) error {\n\tfor _, build := range buildList.Items {\n\t\tif err := printBuild(&build, w); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc printBuildConfig(bc *api.BuildConfig, w io.Writer) error {\n\t_, err := fmt.Fprintf(w, \"%s\\t%v\\t%s\\n\", bc.Name, bc.Parameters.Strategy.Type, bc.Parameters.Source.Git.URI)\n\treturn err\n}\n\n\n\nfunc printBuildConfigList(buildList *api.BuildConfigList, w io.Writer) error ", "output": "{\n\tfor _, buildConfig := range buildList.Items {\n\t\tif err := printBuildConfig(&buildConfig, w); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package job\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/dokkur/swanager/api/common\"\n\t\"github.com/dokkur/swanager/core/entities\"\n\t\"github.com/gin-gonic/gin\"\n)\n\n\nfunc GetRoutesForRouter(router *gin.RouterGroup) {\n\tapps := router.Group(\"/jobs/:job_id\", common.Auth(true))\n\t{\n\t\tapps.GET(\"\", show)\n\t}\n}\n\n\n\nfunc show(c *gin.Context) ", "output": "{\n\tjob, err := entities.GetJob(c.Param(\"job_id\"))\n\tif err != nil {\n\t\tcommon.RenderError(c, http.StatusNotFound, \"not found\")\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\"job\": job})\n}"} {"input": "package framework\n\nimport \"sync\"\n\ntype CleanupActionHandle *int\n\nvar cleanupActionsLock sync.Mutex\nvar cleanupActions = map[CleanupActionHandle]func(){}\n\n\n\n\n\n\n\n\nfunc RemoveCleanupAction(p CleanupActionHandle) {\n\tcleanupActionsLock.Lock()\n\tdefer cleanupActionsLock.Unlock()\n\tdelete(cleanupActions, p)\n}\n\n\n\n\nfunc RunCleanupActions() {\n\tlist := []func(){}\n\tfunc() {\n\t\tcleanupActionsLock.Lock()\n\t\tdefer cleanupActionsLock.Unlock()\n\t\tfor _, fn := range cleanupActions {\n\t\t\tlist = append(list, fn)\n\t\t}\n\t}()\n\tfor _, fn := range list {\n\t\tfn()\n\t}\n}\n\nfunc AddCleanupAction(fn func()) CleanupActionHandle ", "output": "{\n\tp := CleanupActionHandle(new(int))\n\tcleanupActionsLock.Lock()\n\tdefer cleanupActionsLock.Unlock()\n\tcleanupActions[p] = fn\n\treturn p\n}"} {"input": "func convertToTitle(n int) string {\n execl := []string{\"A\", \"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\", \"I\", \"J\",\"K\",\"L\",\"M\",\"N\",\"O\", \"P\", \"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\"}\n var temp string\n for n >0 {\n temp = execl[(n-1)%26] +temp\n n = (n-1) /26\n }\n return temp\n}\n\n\n\nfunc convertToTitle(n int) string ", "output": "{\n var res []byte\n for n > 0 {\n n--\n k := n % 26\n res = append(res, byte('A') + byte(k))\n n /= 26\n }\n for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {\n res[i], res[j] = res[j], res[i]\n }\n return string(res)\n}"} {"input": "package internal\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\ntype ContextKey string\n\nconst userAgent = \"gcloud-golang/0.1\"\n\n\n\n\ntype Transport struct {\n\tBase http.RoundTripper\n}\n\n\n\nfunc (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq = cloneRequest(req)\n\tua := req.Header.Get(\"User-Agent\")\n\tif ua == \"\" {\n\t\tua = userAgent\n\t} else {\n\t\tua = fmt.Sprintf(\"%s;%s\", ua, userAgent)\n\t}\n\treq.Header.Set(\"User-Agent\", ua)\n\treturn t.Base.RoundTrip(req)\n}\n\n\n\nfunc cloneRequest(r *http.Request) *http.Request {\n\tr2 := new(http.Request)\n\t*r2 = *r\n\tr2.Header = make(http.Header)\n\tfor k, s := range r.Header {\n\t\tr2.Header[k] = s\n\t}\n\treturn r2\n}\n\n\n\n\n\n\nfunc Namespace(ctx context.Context) string {\n\tv := ctx.Value(ContextKey(\"namespace\"))\n\tif v == nil {\n\t\treturn \"\"\n\t} else {\n\t\treturn v.(string)\n\t}\n}\n\nfunc HttpClient(ctx context.Context) *http.Client {\n\treturn ctx.Value(ContextKey(\"base\")).(map[string]interface{})[\"http_client\"].(*http.Client)\n}\n\nfunc ProjID(ctx context.Context) string ", "output": "{\n\treturn ctx.Value(ContextKey(\"base\")).(map[string]interface{})[\"project_id\"].(string)\n}"} {"input": "package math\n\nimport \"jvmgo/ch07/instructions/base\"\nimport \"jvmgo/ch07/rtda\"\n\n\ntype DSUB struct{ base.NoOperandsInstruction }\n\nfunc (self *DSUB) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tv2 := stack.PopDouble()\n\tv1 := stack.PopDouble()\n\tresult := v1 - v2\n\tstack.PushDouble(result)\n}\n\n\ntype FSUB struct{ base.NoOperandsInstruction }\n\nfunc (self *FSUB) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tv2 := stack.PopFloat()\n\tv1 := stack.PopFloat()\n\tresult := v1 - v2\n\tstack.PushFloat(result)\n}\n\n\ntype ISUB struct{ base.NoOperandsInstruction }\n\nfunc (self *ISUB) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tv2 := stack.PopInt()\n\tv1 := stack.PopInt()\n\tresult := v1 - v2\n\tstack.PushInt(result)\n}\n\n\ntype LSUB struct{ base.NoOperandsInstruction }\n\n\n\nfunc (self *LSUB) Execute(frame *rtda.Frame) ", "output": "{\n\tstack := frame.OperandStack()\n\tv2 := stack.PopLong()\n\tv1 := stack.PopLong()\n\tresult := v1 - v2\n\tstack.PushLong(result)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"launchpad.net/gnuflag\"\n\n\t\"launchpad.net/juju-core/cmd\"\n\t\"launchpad.net/juju-core/store\"\n)\n\n\ntype ConfigCommand struct {\n\tcmd.CommandBase\n\tConfigPath string\n\tConfig *store.Config\n}\n\ntype CharmdConfig struct {\n\tMongoUrl string `yaml:\"mongo-url\"`\n}\n\nfunc (c *ConfigCommand) SetFlags(f *gnuflag.FlagSet) {\n\tf.StringVar(&c.ConfigPath, \"config\", \"\", \"charmd configuration file\")\n}\n\n\n\nfunc (c *ConfigCommand) ReadConfig(ctx *cmd.Context) (err error) {\n\tc.Config, err = store.ReadConfig(ctx.AbsPath(c.ConfigPath))\n\treturn err\n}\n\nfunc (c *ConfigCommand) Init(args []string) error ", "output": "{\n\tif c.ConfigPath == \"\" {\n\t\treturn fmt.Errorf(\"--config is required\")\n\t}\n\treturn nil\n}"} {"input": "package braille\n\n\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestCode(t *testing.T) {\n\tfmt.Printf(\"1-5-6-7 -> %c\\n\", Rune(1, 5, 6, 7))\n\tfmt.Printf(\"1-2-3-4-5-6-7-8 -> %c\\n\", Rune(1, 2, 3, 4, 5, 6, 7, 8))\n}\n\nfunc TestNumber(t *testing.T) {\n\tfor _, c := range \"1234567890\" {\n\t\tfmt.Printf(\"%c : %c\\n\", c, Alphabet(c))\n\t}\n}\n\nfunc TestAlphabet(t *testing.T) {\n\ts := \"HackTime for Google Hackfair 2012-09-01\"\n\tfmt.Println(s)\n\tfmt.Println(Encode(s))\n}\n\nfunc TestDot(t *testing.T) ", "output": "{\n\tfmt.Println(\"0x28C1 =\", Dot(0x28c1))\n\tfmt.Println(\"0x282D =\", Dot(0x282D))\n\tfmt.Println(\"0x28BF =\", Dot(0x28BF))\n\tfmt.Println(\"0x28FF =\", Dot(0x28FF))\n\n}"} {"input": "package tooltip\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/richardwilkes/toolbox/xmath/geom\"\n\t\"github.com/richardwilkes/ui\"\n\t\"github.com/richardwilkes/ui/event\"\n)\n\n\ntype Event struct {\n\ttarget ui.Widget\n\twhere geom.Point\n\tavoid geom.Rect\n\ttooltip ui.Widget\n\tfinished bool\n}\n\n\n\n\n\nfunc NewEvent(target ui.Widget, where geom.Point, avoid geom.Rect) *Event {\n\treturn &Event{target: target, where: where, avoid: avoid}\n}\n\n\nfunc (e *Event) Type() event.Type {\n\treturn event.ToolTipType\n}\n\n\nfunc (e *Event) Target() event.Target {\n\treturn e.target\n}\n\n\nfunc (e *Event) Cascade() bool {\n\treturn false\n}\n\n\nfunc (e *Event) Where() geom.Point {\n\treturn e.where\n}\n\n\nfunc (e *Event) Avoid() geom.Rect {\n\treturn e.avoid\n}\n\n\nfunc (e *Event) SetAvoid(avoid geom.Rect) {\n\te.avoid = avoid\n}\n\n\nfunc (e *Event) ToolTip() ui.Widget {\n\treturn e.tooltip\n}\n\n\nfunc (e *Event) SetToolTip(tooltip ui.Widget) {\n\te.tooltip = tooltip\n}\n\n\nfunc (e *Event) Finished() bool {\n\treturn e.finished\n}\n\n\nfunc (e *Event) Finish() {\n\te.finished = true\n}\n\n\n\n\nfunc (e *Event) String() string ", "output": "{\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(fmt.Sprintf(\"Event[Where: [%v], Avoid: [%v], Target: %v\", e.where, e.avoid, e.target))\n\tif e.tooltip != nil {\n\t\tbuffer.WriteString(fmt.Sprintf(\", Tooltip: [%v]\", e.tooltip))\n\t}\n\tif e.finished {\n\t\tbuffer.WriteString(\", Finished\")\n\t}\n\tbuffer.WriteString(\"]\")\n\treturn buffer.String()\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype ListFastConnectProviderVirtualCircuitBandwidthShapesRequest struct {\n\n\tProviderServiceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"providerServiceId\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\n\n\n\ntype ListFastConnectProviderVirtualCircuitBandwidthShapesResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []VirtualCircuitBandwidthShape `presentIn:\"body\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ListFastConnectProviderVirtualCircuitBandwidthShapesResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListFastConnectProviderVirtualCircuitBandwidthShapesResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package consul\n\nimport (\n\t\"log\"\n\n\t\"github.com/armon/consul-api\"\n\t\"github.com/hashicorp/terraform/helper/config\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\ntype ResourceProvider struct {\n\tConfig Config\n\tclient *consulapi.Client\n}\n\nfunc (p *ResourceProvider) Validate(c *terraform.ResourceConfig) ([]string, []error) {\n\tv := &config.Validator{\n\t\tOptional: []string{\n\t\t\t\"datacenter\",\n\t\t\t\"address\",\n\t\t},\n\t}\n\treturn v.Validate(c)\n}\n\n\n\nfunc (p *ResourceProvider) Configure(c *terraform.ResourceConfig) error {\n\tif _, err := config.Decode(&p.Config, c.Config); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[INFO] Initializing Consul client\")\n\tvar err error\n\tp.client, err = p.Config.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (p *ResourceProvider) Apply(\n\ts *terraform.ResourceState,\n\td *terraform.ResourceDiff) (*terraform.ResourceState, error) {\n\treturn resourceMap.Apply(s, d, p)\n}\n\nfunc (p *ResourceProvider) Diff(\n\ts *terraform.ResourceState,\n\tc *terraform.ResourceConfig) (*terraform.ResourceDiff, error) {\n\treturn resourceMap.Diff(s, c, p)\n}\n\nfunc (p *ResourceProvider) Refresh(\n\ts *terraform.ResourceState) (*terraform.ResourceState, error) {\n\treturn resourceMap.Refresh(s, p)\n}\n\nfunc (p *ResourceProvider) Resources() []terraform.ResourceType {\n\treturn resourceMap.Resources()\n}\n\nfunc (p *ResourceProvider) ValidateResource(\n\tt string, c *terraform.ResourceConfig) ([]string, []error) ", "output": "{\n\treturn resourceMap.Validate(t, c)\n}"} {"input": "package hitGox\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strconv\"\n\n\tjust \"github.com/toby3d/hitGox/tools\"\n\tf \"github.com/valyala/fasthttp\"\n)\n\n\n\n\n\n\nfunc (account *Account) FollowAChannel(id interface{}) (*just.Status, error) ", "output": "{\n\tvar changes = struct {\n\t\tType string `json:\"type\"`\n\t\tFollowID string `json:\"follow_id\"`\n\t}{Type: \"user\"}\n\n\tswitch i := id.(type) {\n\tcase int:\n\t\tchanges.FollowID = strconv.Itoa(i)\n\tcase string:\n\t\tchanges.FollowID = i\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"id can be only as string or int\")\n\t}\n\n\tdst, err := json.Marshal(changes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar args f.Args\n\targs.Add(\"authToken\", account.AuthToken)\n\n\turl := fmt.Sprintf(APIEndpoint, \"follow\")\n\tresp, err := just.POST(dst, url, &args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn just.FixStatus(resp), nil\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n\n\t\"github.com/codegangsta/cli\"\n)\n\nvar gitDbranchCmd = cli.Command{\n\tName: \"git-dbranch\",\n\tShortName: \"gd\",\n\tUsage: \"Deletes local and remote branches\",\n\tDescription: `Delete local and remote branches. For example,\n\n $ odt git-dbranch branch1 branch2 ...`,\n\tAction: gitDbranchAction,\n}\n\n\n\nfunc deleteBranch(branch string) {\n\texecCmd(\"git branch -D \" + branch)\n\texecCmd(\"git push origin :\" + branch)\n}\n\nfunc gitDbranchAction(c *cli.Context) ", "output": "{\n\targs := c.Args()\n\tif len(args) == 0 {\n\t\tcli.ShowCommandHelp(c, \"gd\")\n\t\treturn\n\t}\n\n\tfor _, arg := range args {\n\t\tbranch := strings.TrimSpace(arg)\n\t\tdeleteBranch(branch)\n\t}\n}"} {"input": "package vm\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc newStack() *stack {\n\treturn &stack{}\n}\n\ntype stack struct {\n\tdata []*big.Int\n\tptr int\n}\n\nfunc (st *stack) push(d *big.Int) {\n\tstackItem := new(big.Int).Set(d)\n\tif len(st.data) > st.ptr {\n\t\tst.data[st.ptr] = stackItem\n\t} else {\n\t\tst.data = append(st.data, stackItem)\n\t}\n\tst.ptr++\n}\n\nfunc (st *stack) pop() (ret *big.Int) {\n\tst.ptr--\n\tret = st.data[st.ptr]\n\treturn\n}\n\nfunc (st *stack) len() int {\n\treturn st.ptr\n}\n\nfunc (st *stack) swap(n int) {\n\tst.data[st.len()-n], st.data[st.len()-1] = st.data[st.len()-1], st.data[st.len()-n]\n}\n\nfunc (st *stack) dup(n int) {\n\tst.push(st.data[st.len()-n])\n}\n\nfunc (st *stack) peek() *big.Int {\n\treturn st.data[st.len()-1]\n}\n\nfunc (st *stack) require(n int) error {\n\tif st.len() < n {\n\t\treturn fmt.Errorf(\"stack underflow (%d <=> %d)\", len(st.data), n)\n\t}\n\treturn nil\n}\n\n\n\nfunc (st *stack) Print() ", "output": "{\n\tfmt.Println(\"### stack ###\")\n\tif len(st.data) > 0 {\n\t\tfor i, val := range st.data {\n\t\t\tfmt.Printf(\"%-3d %v\\n\", i, val)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"-- empty --\")\n\t}\n\tfmt.Println(\"#############\")\n}"} {"input": "package addrs\n\nimport \"fmt\"\n\n\n\n\n\n\n\n\n\n\n\ntype ResourceInstancePhase struct {\n\treferenceable\n\tResourceInstance ResourceInstance\n\tPhase ResourceInstancePhaseType\n}\n\nvar _ Referenceable = ResourceInstancePhase{}\n\n\n\n\n\n\n\n\nfunc (rp ResourceInstancePhase) ContainingResource() ResourcePhase {\n\treturn rp.ResourceInstance.Resource.Phase(rp.Phase)\n}\n\nfunc (rp ResourceInstancePhase) String() string {\n\treturn fmt.Sprintf(\"%s#%s\", rp.ResourceInstance, rp.Phase)\n}\n\n\ntype ResourceInstancePhaseType string\n\nconst (\n\tResourceInstancePhaseDestroy ResourceInstancePhaseType = \"destroy\"\n\n\tResourceInstancePhaseDestroyCBD ResourceInstancePhaseType = \"destroy-cbd\"\n)\n\nfunc (rpt ResourceInstancePhaseType) String() string {\n\treturn string(rpt)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype ResourcePhase struct {\n\treferenceable\n\tResource Resource\n\tPhase ResourceInstancePhaseType\n}\n\nvar _ Referenceable = ResourcePhase{}\n\n\n\n\nfunc (r Resource) Phase(rpt ResourceInstancePhaseType) ResourcePhase {\n\treturn ResourcePhase{\n\t\tResource: r,\n\t\tPhase: rpt,\n\t}\n}\n\nfunc (rp ResourcePhase) String() string {\n\treturn fmt.Sprintf(\"%s#%s\", rp.Resource, rp.Phase)\n}\n\nfunc (r ResourceInstance) Phase(rpt ResourceInstancePhaseType) ResourceInstancePhase ", "output": "{\n\treturn ResourceInstancePhase{\n\t\tResourceInstance: r,\n\t\tPhase: rpt,\n\t}\n}"} {"input": "package externalversions\n\nimport (\n\t\"fmt\"\n\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tcache \"k8s.io/client-go/tools/cache\"\n\tv1beta1 \"k8s.io/kube-aggregator/pkg/apis/apiregistration/v1beta1\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}\n\n\n\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {\n\tswitch resource {\n\tcase v1beta1.SchemeGroupVersion.WithResource(\"apiservices\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Apiregistration().V1beta1().APIServices().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}\n\nfunc (f *genericInformer) Lister() cache.GenericLister ", "output": "{\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}"} {"input": "package upside_down\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/blevesearch/bleve/index\"\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\ntype UpsideDownCouchFieldDict struct {\n\tindexReader *IndexReader\n\titerator store.KVIterator\n\tendKey []byte\n\tfield uint16\n}\n\nfunc newUpsideDownCouchFieldDict(indexReader *IndexReader, field uint16, startTerm, endTerm []byte) (*UpsideDownCouchFieldDict, error) {\n\n\tstartKey := NewDictionaryRow(startTerm, field, 0).Key()\n\tif endTerm == nil {\n\t\tendTerm = []byte{ByteSeparator}\n\t}\n\tendKey := NewDictionaryRow(endTerm, field, 0).Key()\n\n\tit := indexReader.kvreader.Iterator(startKey)\n\n\treturn &UpsideDownCouchFieldDict{\n\t\tindexReader: indexReader,\n\t\titerator: it,\n\t\tfield: field,\n\t\tendKey: endKey,\n\t}, nil\n\n}\n\n\n\nfunc (r *UpsideDownCouchFieldDict) Close() error {\n\treturn r.iterator.Close()\n}\n\nfunc incrementBytes(in []byte) []byte {\n\trv := make([]byte, len(in))\n\tcopy(rv, in)\n\tfor i := len(rv) - 1; i >= 0; i-- {\n\t\trv[i] = rv[i] + 1\n\t\tif rv[i] != 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn rv\n}\n\nfunc (r *UpsideDownCouchFieldDict) Next() (*index.DictEntry, error) ", "output": "{\n\tkey, val, valid := r.iterator.Current()\n\tif !valid {\n\t\treturn nil, nil\n\t}\n\n\tif bytes.Compare(key, r.endKey) > 0 {\n\t\treturn nil, nil\n\t}\n\n\tcurrRow, err := NewDictionaryRowKV(key, val)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unexpected error parsing dictionary row kv: %v\", err)\n\t}\n\trv := index.DictEntry{\n\t\tTerm: string(currRow.term),\n\t\tCount: currRow.count,\n\t}\n\tr.iterator.Next()\n\treturn &rv, nil\n\n}"} {"input": "package message\n\n\n\ntype PubackMessage struct {\n\tfixedHeader\n\n\tpacketID []byte\n}\n\n\nfunc (p *PubackMessage) SetPacketID(v []byte) {\n\tp.packetID = v\n}\n\n\n\n\nfunc (p *PubackMessage) PacketID() []byte ", "output": "{\n\treturn p.packetID\n}"} {"input": "package u\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync/atomic\"\n)\n\n\ntype FileWalkEntry struct {\n\tDir string\n\tFileInfo os.FileInfo\n}\n\n\nfunc (e *FileWalkEntry) Path() string {\n\treturn filepath.Join(e.Dir, e.FileInfo.Name())\n}\n\n\ntype FileWalk struct {\n\tstartDir string\n\tFilesChan chan *FileWalkEntry\n\taskedToStop int32\n}\n\n\nfunc (ft *FileWalk) Stop() {\n\tatomic.StoreInt32(&ft.askedToStop, 1)\n\tfor range ft.FilesChan {\n\t}\n}\n\nfunc fileWalkWorker(ft *FileWalk) {\n\ttoVisit := []string{ft.startDir}\n\tdefer close(ft.FilesChan)\n\n\tfor len(toVisit) > 0 {\n\t\tshouldStop := atomic.LoadInt32(&ft.askedToStop)\n\t\tif shouldStop > 0 {\n\t\t\treturn\n\t\t}\n\t\tdir := toVisit[0]\n\t\ttoVisit = StringsRemoveFirst(toVisit)\n\n\t\tfiles, err := ioutil.ReadDir(dir)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, fi := range files {\n\t\t\tpath := filepath.Join(dir, fi.Name())\n\t\t\tmode := fi.Mode()\n\t\t\tif mode.IsDir() {\n\t\t\t\ttoVisit = append(toVisit, path)\n\t\t\t} else if mode.IsRegular() {\n\t\t\t\tfte := &FileWalkEntry{\n\t\t\t\t\tDir: dir,\n\t\t\t\t\tFileInfo: fi,\n\t\t\t\t}\n\t\t\t\tft.FilesChan <- fte\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n\nfunc StartFileWalk(startDir string) *FileWalk ", "output": "{\n\tch := make(chan *FileWalkEntry, 1024*64)\n\tft := &FileWalk{\n\t\tstartDir: startDir,\n\t\tFilesChan: ch,\n\t}\n\tgo fileWalkWorker(ft)\n\treturn ft\n}"} {"input": "package lzma\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"unicode\"\n)\n\n\n\ntype operation interface {\n\tLen() int\n}\n\n\ntype match struct {\n\tdistance int64\n\tn int\n}\n\n\n\nfunc (m match) verify() error {\n\tif !(minDistance <= m.distance && m.distance <= maxDistance) {\n\t\treturn errors.New(\"distance out of range\")\n\t}\n\tif !(1 <= m.n && m.n <= maxMatchLen) {\n\t\treturn errors.New(\"length out of range\")\n\t}\n\treturn nil\n}\n\n\n\n\n\n\n\nfunc (m match) dist() uint32 {\n\treturn uint32(m.distance - minDistance)\n}\n\n\nfunc (m match) Len() int {\n\treturn m.n\n}\n\n\nfunc (m match) String() string {\n\treturn fmt.Sprintf(\"M{%d,%d}\", m.distance, m.n)\n}\n\n\ntype lit struct {\n\tb byte\n}\n\n\nfunc (l lit) Len() int {\n\treturn 1\n}\n\n\nfunc (l lit) String() string {\n\tvar c byte\n\tif unicode.IsPrint(rune(l.b)) {\n\t\tc = l.b\n\t} else {\n\t\tc = '.'\n\t}\n\treturn fmt.Sprintf(\"L{%c/%02x}\", c, l.b)\n}\n\nfunc (m match) l() uint32 ", "output": "{\n\treturn uint32(m.n - minMatchLen)\n}"} {"input": "package goldprice\n\nimport \"testing\"\n\n\n\nfunc TestUpdateToday(t *testing.T) {\n\tcases := []struct {\n\t\tin Date\n\t}{\n\t\t{Date{2015, 7, 24}},\n\t}\n\tif true {\n\t\treturn\n\t}\n\tfor _, c := range cases {\n\t\ttoday := c.in\n\t\ttimeArray, dayPrice := GetDayFromTaiwanBank(today)\n\t\tresult := UpdateToday(today, timeArray, dayPrice)\n\t\tif result == false {\n\t\t\tt.Errorf(\"result incorrect\")\n\t\t}\n\t}\n}\n\nfunc TestUpdateYear(t *testing.T) ", "output": "{\n\tdateArray, yearPrice := GetYearFromTaiwanBank()\n\tif true {\n\t\treturn\n\t}\n\tresult := UpdateYear(dateArray, yearPrice)\n\tif result == false {\n\t\tt.Errorf(\"result incorrect\")\n\t}\n}"} {"input": "package roles\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestIsTopLevelRole(t *testing.T) {\n\tassert.True(t, IsTopLevelRole(\"root\"))\n\tassert.True(t, IsTopLevelRole(\"targets\"))\n\tassert.True(t, IsTopLevelRole(\"timestamp\"))\n\tassert.True(t, IsTopLevelRole(\"snapshot\"))\n\tassert.False(t, IsTopLevelRole(\"bins\"))\n}\n\nfunc TestIsDelegatedTargetsRole(t *testing.T) {\n\tassert.False(t, IsDelegatedTargetsRole(\"root\"))\n\tassert.False(t, IsDelegatedTargetsRole(\"targets\"))\n\tassert.False(t, IsDelegatedTargetsRole(\"timestamp\"))\n\tassert.False(t, IsDelegatedTargetsRole(\"snapshot\"))\n\tassert.True(t, IsDelegatedTargetsRole(\"deleg\"))\n}\n\nfunc TestIsTopLevelManifest(t *testing.T) {\n\tassert.True(t, IsTopLevelManifest(\"root.json\"))\n\tassert.True(t, IsTopLevelManifest(\"targets.json\"))\n\tassert.True(t, IsTopLevelManifest(\"timestamp.json\"))\n\tassert.True(t, IsTopLevelManifest(\"snapshot.json\"))\n\tassert.False(t, IsTopLevelManifest(\"bins.json\"))\n}\n\nfunc TestIsDelegatedTargetsManifest(t *testing.T) {\n\tassert.False(t, IsDelegatedTargetsManifest(\"root.json\"))\n\tassert.False(t, IsDelegatedTargetsManifest(\"targets.json\"))\n\tassert.False(t, IsDelegatedTargetsManifest(\"timestamp.json\"))\n\tassert.False(t, IsDelegatedTargetsManifest(\"snapshot.json\"))\n\tassert.True(t, IsDelegatedTargetsManifest(\"bins.json\"))\n}\n\n\n\nfunc TestIsVersionedManifest(t *testing.T) ", "output": "{\n\tassert.False(t, IsVersionedManifest(\"a.b\"))\n\tassert.False(t, IsVersionedManifest(\"a.b.c\"))\n\tassert.False(t, IsVersionedManifest(\"a.b.json\"))\n\tassert.False(t, IsVersionedManifest(\"1.a\"))\n\tassert.True(t, IsVersionedManifest(\"1.a.json\"))\n\tassert.True(t, IsVersionedManifest(\"2.a.json\"))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"github.com/docker/go-connections/sockets\"\n\t\"github.com/gostor/gotgt/cmd\"\n\t\"github.com/gostor/gotgt/pkg/api/client\"\n\t\"github.com/gostor/gotgt/pkg/version\"\n)\n\nfunc main() {\n\n\thost := \"tcp://127.0.0.1:23457\"\n\thttpClient, err := newHTTPClient(host)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\", err)\n\t\tos.Exit(1)\n\t}\n\n\tcli, err := client.NewClient(host, version.Version, httpClient, nil)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\", err)\n\t\tos.Exit(1)\n\t}\n\tif err := cmd.NewCommand(cli).Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}\n\n\n\nfunc newHTTPClient(host string) (*http.Client, error) ", "output": "{\n\ttr := &http.Transport{\n\t\tTLSClientConfig: nil,\n\t}\n\tproto, addr, _, err := client.ParseHost(host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsockets.ConfigureTransport(tr, proto, addr)\n\n\treturn &http.Client{\n\t\tTransport: tr,\n\t}, nil\n}"} {"input": "package installer\n\nimport (\n\t\"github.com/wx13/genesis\"\n)\n\n\n\ntype Custom struct {\n\tTask genesis.Doer\n\tS func() (genesis.Status, error)\n\tD func() (bool, error)\n\tU func() (bool, error)\n\tI func() string\n\tF func() []string\n}\n\nfunc NewCustom(task genesis.Doer) *Custom {\n\tcustom := Custom{\n\t\tTask: task,\n\t\tS: task.Status,\n\t\tD: task.Do,\n\t\tU: task.Undo,\n\t\tI: task.ID,\n\t\tF: task.Files,\n\t}\n\treturn &custom\n}\n\n\n\nfunc (custom Custom) Do() (bool, error) {\n\treturn custom.D()\n}\n\nfunc (custom Custom) Undo() (bool, error) {\n\treturn custom.U()\n}\n\nfunc (custom Custom) ID() string {\n\treturn custom.I()\n}\n\nfunc (custom Custom) Files() []string {\n\treturn custom.F()\n}\n\nfunc (custom Custom) Status() (genesis.Status, error) ", "output": "{\n\treturn custom.S()\n}"} {"input": "package username\n\nimport (\n\t\"net/url\"\n\t\"testing\"\n)\n\nvar u url.URL\nvar usernameTest, suffixTest string\n\n\n\nfunc TestUsernameWithPrefix(t *testing.T) {\n\tu, _ := url.Parse(\"http://example.com/username.prefix\")\n\tusernameTest, suffixTest = WithSuffix(u.Path)\n\n\tif usernameTest != \"username\" {\n\t\tt.Error(\"Expected username to be 'username' got: \", usernameTest)\n\t}\n\n\tif suffixTest != \"prefix\" {\n\t\tt.Error(\"Expected suffix to be 'prefix' got: \", suffixTest)\n\t}\n}\n\nfunc TestUsernameWithoutPrefix(t *testing.T) ", "output": "{\n\tu, _ := url.Parse(\"http://example.com/username\")\n\tusernameTest, suffixTest = WithSuffix(u.Path)\n\n\tif usernameTest != \"username\" {\n\t\tt.Error(\"Expected username to be 'username' got: \", usernameTest)\n\t}\n\n\tif suffixTest != \"\" {\n\t\tt.Error(\"Expected suffix to be empty \", suffixTest)\n\t}\n}"} {"input": "package sprig\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestFail(t *testing.T) ", "output": "{\n\tconst msg = \"This is an error!\"\n\ttpl := fmt.Sprintf(`{{fail \"%s\"}}`, msg)\n\t_, err := runRaw(tpl, nil)\n\tassert.Error(t, err)\n\tassert.Contains(t, err.Error(), msg)\n}"} {"input": "package main\n\nimport (\n\t\"../../embedded\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\n\n\n\nfunc Entry() {\n\truntime.Armhackmode = 1\n\truntime.Runtime_main()\n}\n\n\nfunc main() {\n\tfmt.Printf(\"self tests ...\")\n\tself_tests()\n\tfmt.Printf(\"done!\\n\")\n\n\tfmt.Printf(\"warnings ...\")\n\tself_warnings()\n\tfmt.Printf(\"done!\\n\")\n\n\tfmt.Printf(\"pre-init ...\")\n\tpre_init()\n\tsyscall.Setenv(\"TZ\", \"UTC\")\n\truntime.Booted = 1\n\tfmt.Printf(\"done!\\n\")\n\n\tfmt.Printf(\"user init ...\")\n\tuser_init()\n\tfmt.Printf(\"done!\\n\")\n\n\tfor {\n\t\tuser_loop()\n\t}\n\tpanic(\"user loop broke out\")\n}\n\n\nfunc self_tests() {\n\tfmt.Println(\"Hi from fmt\")\n\tchannel := make(chan string, 1)\n\tchannel <- \"channel test pass\"\n\tval := <-channel\n\tfmt.Println(val)\n\tgo func(resp chan string) {\n\t\tfmt.Println(\"print from inside goroutine\")\n\t\tresp <- \"send channel from inside a goroutine\"\n\t}(channel)\n\tval = <-channel\n\tfmt.Println(val)\n}\n\n\nfunc self_warnings() {\n}\n\n\n\n\nfunc pre_init() ", "output": "{\n\tembedded.GIC_init(false)\n\n\truntime.SetIRQcallback(irq)\n\n\truntime.Release(3)\n\n\truntime.Unmap_region(0x0, 0x0, 0x100000)\n}"} {"input": "package s2\n\n\nvar (\n\t_ Shape = (*PointVector)(nil)\n)\n\n\n\n\n\n\n\n\ntype PointVector []Point\n\nfunc (p *PointVector) NumEdges() int { return len(*p) }\nfunc (p *PointVector) Edge(i int) Edge { return Edge{(*p)[i], (*p)[i]} }\n\nfunc (p *PointVector) NumChains() int { return len(*p) }\nfunc (p *PointVector) Chain(i int) Chain { return Chain{i, 1} }\nfunc (p *PointVector) ChainEdge(i, j int) Edge { return Edge{(*p)[i], (*p)[j]} }\nfunc (p *PointVector) ChainPosition(e int) ChainPosition { return ChainPosition{e, 0} }\nfunc (p *PointVector) Dimension() int { return 0 }\nfunc (p *PointVector) IsEmpty() bool { return defaultShapeIsEmpty(p) }\nfunc (p *PointVector) IsFull() bool { return defaultShapeIsFull(p) }\nfunc (p *PointVector) typeTag() typeTag { return typeTagPointVector }\nfunc (p *PointVector) privateInterface() {}\n\nfunc (p *PointVector) ReferencePoint() ReferencePoint ", "output": "{ return OriginReferencePoint(false) }"} {"input": "package ec2\n\nimport (\n\t\"github.com/crowdmob/goamz/aws\"\n\t\"time\"\n)\n\nfunc Sign(auth aws.Auth, method, path string, params map[string]string, host string) {\n\tsign(auth, method, path, params, host)\n}\n\n\n\nfunc FakeTime(fakeIt bool) {\n\tif fakeIt {\n\t\ttimeNow = fixedTime\n\t} else {\n\t\ttimeNow = time.Now\n\t}\n}\n\nfunc fixedTime() time.Time ", "output": "{\n\treturn time.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC)\n}"} {"input": "package eav\n\ntype (\n\tAttributeFrontendModeller interface {\n\t\tInputRenderer() FrontendInputRendererIFace\n\t\tGetValue()\n\t\tGetInputType() string\n\n\t\tConfig(...AttributeFrontendConfig) AttributeFrontendModeller\n\t}\n\tFrontendInputRendererIFace interface {\n\t}\n\tAttributeFrontend struct {\n\t\ta *Attribute\n\t\tidx AttributeIndex\n\t}\n\tAttributeFrontendConfig func(*AttributeFrontend)\n)\n\nvar _ AttributeFrontendModeller = (*AttributeFrontend)(nil)\n\n\n\n\n\nfunc AttributeFrontendIdx(i AttributeIndex) AttributeFrontendConfig {\n\treturn func(as *AttributeFrontend) {\n\t\tas.idx = i\n\t}\n}\n\n\nfunc (af *AttributeFrontend) Config(configs ...AttributeFrontendConfig) AttributeFrontendModeller {\n\tfor _, cfg := range configs {\n\t\tcfg(af)\n\t}\n\treturn af\n}\n\nfunc (af *AttributeFrontend) InputRenderer() FrontendInputRendererIFace { return nil }\nfunc (af *AttributeFrontend) GetValue() {}\nfunc (af *AttributeFrontend) GetInputType() string {\n\treturn af.a.FrontendInput()\n}\n\nfunc NewAttributeFrontend(cfgs ...AttributeFrontendConfig) *AttributeFrontend ", "output": "{\n\tas := &AttributeFrontend{\n\t\ta: nil,\n\t}\n\tas.Config(cfgs...)\n\treturn as\n}"} {"input": "package target\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"testing\"\n)\n\nvar (\n\twrkdir string\n)\n\nfunc init() {\n\tlog.SetOutput(ioutil.Discard)\n\twrkdir, _ = os.Getwd()\n}\n\ntype badWriter struct {\n}\n\nfunc (bw badWriter) Write(p []byte) (n int, err error) {\n\treturn 0, fmt.Errorf(\"bad\")\n}\n\nfunc TestNewMake(t *testing.T) {\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\t_, err := NewMake(tc)\n\tok(t, err)\n}\n\nfunc TestMakeRun(t *testing.T) {\n\ttc, tcW, _ := createTestConfigs(t, nil, nil)\n\tm, _ := NewMake(tc)\n\terr := m.Run(\"ron:prep\")\n\tok(t, err)\n\twant := \"hello\\nprep1\\nprep2\\nprep3\\nprep4\\ngoodbye\\n\"\n\tequals(t, want, tcW.String())\n}\n\n\n\nfunc TestMakeRunNoTarget(t *testing.T) {\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\tm, _ := NewMake(tc)\n\terr := m.Run(\"prop\")\n\tif err == nil {\n\t\tt.Fatal(\"expected target not found\")\n\t}\n}\n\nfunc TestMakeRunErr(t *testing.T) ", "output": "{\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\tm, _ := NewMake(tc)\n\terr := m.Run(\"err\")\n\tif err == nil {\n\t\tt.Fatal(\"expected target not found\")\n\t}\n}"} {"input": "package stats\n\nimport (\n\t\"code.google.com/p/probab/dst\"\n\t\"math\"\n\t\"math/rand\"\n)\n\nfunc Sample(n, k int, idx []int) []int {\n\tidx = use_int_slice(idx, k)\n\tfor i := 0; i < k; i++ {\n\t\tidx[i] = rand.Intn(n)\n\t}\n\treturn idx\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc LogweightedSample(logw []float64, n int, idx []int) []int {\n\tw := make([]float64, len(logw))\n\tmax, _ := FloatMax(logw)\n\tvar sum float64\n\tfor i, lw := range logw {\n\t\tw[i] = math.Exp(lw - max)\n\t\tsum += w[i]\n\t}\n\tFloatScale(w, 1/sum, w)\n\n\treturn WeightedSample(w, n, idx)\n}\n\nfunc WeightedSample(w []float64, n int, idx []int) []int ", "output": "{\n\tidx = use_int_slice(idx, n)\n\tfor i := 0; i < n; i++ {\n\t\tidx[i] = int(dst.ChoiceNext(w))\n\t}\n\treturn idx\n}"} {"input": "package Plugin\n\nimport \"github.com/MPjct/GoMP/MySQLProtocol\"\n\ntype Plugin_interface interface {\n\tinit(context MySQLProtocol.Context)\n\tread_handshake(context MySQLProtocol.Context)\n\tsend_handshake(context MySQLProtocol.Context)\n\tread_auth(context MySQLProtocol.Context)\n\tsend_auth(context MySQLProtocol.Context)\n\tread_auth_result(context MySQLProtocol.Context)\n\tsend_auth_result(context MySQLProtocol.Context)\n\tread_query(context MySQLProtocol.Context)\n\tsend_query(context MySQLProtocol.Context)\n\tread_query_result(context MySQLProtocol.Context)\n\tsend_query_result(context MySQLProtocol.Context)\n\tcleanup(context MySQLProtocol.Context)\n}\n\ntype Plugin struct {\n}\n\nfunc (plugin *Plugin) init(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query(context MySQLProtocol.Context) {\n\treturn\n}\n\n\n\nfunc (plugin *Plugin) send_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) cleanup(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query_result(context MySQLProtocol.Context) ", "output": "{\n\treturn\n}"} {"input": "package types\n\nimport (\n\t\"database/sql/driver\"\n\t\"encoding/json\"\n\t\"errors\"\n)\n\n\n\n\ntype JSON json.RawMessage\n\n\nfunc (j JSON) String() string {\n\treturn string(j)\n}\n\n\nfunc (j JSON) Unmarshal(dest interface{}) error {\n\treturn json.Unmarshal(j, dest)\n}\n\n\nfunc (j *JSON) Marshal(obj interface{}) error {\n\tres, err := json.Marshal(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*j = res\n\treturn nil\n}\n\n\nfunc (j *JSON) UnmarshalJSON(data []byte) error {\n\tif j == nil {\n\t\treturn errors.New(\"json: unmarshal json on nil pointer to json\")\n\t}\n\n\t*j = append((*j)[0:0], data...)\n\treturn nil\n}\n\n\nfunc (j JSON) MarshalJSON() ([]byte, error) {\n\treturn j, nil\n}\n\n\n\nfunc (j JSON) Value() (driver.Value, error) {\n\tvar r json.RawMessage\n\tif err := j.Unmarshal(&r); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn []byte(r), nil\n}\n\n\n\n\nfunc (j *JSON) Scan(src interface{}) error ", "output": "{\n\tvar source []byte\n\n\tswitch src.(type) {\n\tcase string:\n\t\tsource = []byte(src.(string))\n\tcase []byte:\n\t\tsource = src.([]byte)\n\tdefault:\n\t\treturn errors.New(\"incompatible type for json\")\n\t}\n\n\t*j = JSON(append((*j)[0:0], source...))\n\n\treturn nil\n}"} {"input": "package sw\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\n\t\"github.com/hyperledger/fabric/core/crypto/bccsp\"\n\t\"github.com/hyperledger/fabric/core/crypto/primitives\"\n)\n\ntype rsaPrivateKey struct {\n\tk *rsa.PrivateKey\n}\n\n\n\nfunc (k *rsaPrivateKey) Bytes() (raw []byte, err error) {\n\treturn\n}\n\n\nfunc (k *rsaPrivateKey) SKI() (ski []byte) {\n\traw := x509.MarshalPKCS1PrivateKey(k.k)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\nfunc (k *rsaPrivateKey) Symmetric() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPrivateKey) Private() bool {\n\treturn true\n}\n\n\n\nfunc (k *rsaPrivateKey) PublicKey() (bccsp.Key, error) {\n\treturn &rsaPublicKey{&k.k.PublicKey}, nil\n}\n\ntype rsaPublicKey struct {\n\tk *rsa.PublicKey\n}\n\n\n\nfunc (k *rsaPublicKey) Bytes() (raw []byte, err error) {\n\traw, err = x509.MarshalPKIXPublicKey(k.k)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed marshalling key [%s]\", err)\n\t}\n\treturn\n}\n\n\nfunc (k *rsaPublicKey) SKI() (ski []byte) {\n\traw, _ := primitives.PublicKeyToPEM(k.k, nil)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\nfunc (k *rsaPublicKey) Symmetric() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) Private() bool {\n\treturn false\n}\n\n\n\n\n\nfunc (k *rsaPublicKey) PublicKey() (bccsp.Key, error) ", "output": "{\n\treturn k, nil\n}"} {"input": "package main\n\ntype instanceGroupManagers struct {\n\tbasicGCPResource\n}\n\n\n\nfunc (b instanceGroupManagers) ifIDWithZone(zoneInParameters bool) bool {\n\treturn false\n}\nfunc (b instanceGroupManagers) ifNeedRegion() bool {\n\treturn false\n}\n\nfunc (b instanceGroupManagers) ifNeedZone(zoneInParameters bool) bool ", "output": "{\n\treturn true\n}"} {"input": "package models\n\nimport (\n\t\"koding/db/mongodb/modelhelper\"\n\t\"net\"\n\t\"socialapi/config\"\n\t\"socialapi/request\"\n\n\t\"github.com/koding/logging\"\n)\n\n\ntype Client struct {\n\tAccount *Account\n\n\tIP net.IP\n\n\tSessionID string\n}\n\n\ntype Context struct {\n\tGroupName string\n\tClient *Client\n\tlog logging.Logger\n}\n\n\nfunc NewContext(log logging.Logger) *Context {\n\treturn &Context{\n\t\tlog: log,\n\t}\n}\n\n\n\n\n\nfunc (c *Context) IsLoggedIn() bool {\n\tif c.Client == nil {\n\t\treturn false\n\t}\n\n\tif c.Client.Account == nil {\n\t\treturn false\n\t}\n\n\tif c.Client.Account.Id == 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\n\n\nfunc (c *Context) IsAdmin() bool {\n\tif !c.IsLoggedIn() {\n\t\treturn false\n\t}\n\n\tsuperAdmins := config.MustGet().DummyAdmins\n\treturn IsIn(c.Client.Account.Nick, superAdmins...)\n}\n\n\n\n\nfunc (c *Context) CanManage() error {\n\tif !c.IsLoggedIn() {\n\t\treturn ErrNotLoggedIn\n\t}\n\n\tcanManage, err := modelhelper.CanManage(c.Client.Account.Nick, c.GroupName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !canManage {\n\t\treturn ErrCannotManageGroup\n\t}\n\n\treturn nil\n}\n\n\nfunc (c *Context) MustGetLogger() logging.Logger {\n\tif c.log == nil {\n\t\tpanic(ErrLoggerNotExist)\n\t}\n\n\treturn c.log\n}\n\nfunc (c *Context) OverrideQuery(q *request.Query) *request.Query ", "output": "{\n\tq.GroupName = c.GroupName\n\tif c.IsLoggedIn() {\n\t\tq.AccountId = c.Client.Account.Id\n\t} else {\n\t\tq.AccountId = 0\n\t}\n\n\treturn q\n}"} {"input": "package model\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/utils\"\n\n\t\"strings\"\n)\n\n\ntype RegisterServerAutoRecoveryRequest struct {\n\n\tServerId string `json:\"server_id\"`\n\n\tBody *RegisterServerAutoRecoveryRequestBody `json:\"body,omitempty\"`\n}\n\n\n\nfunc (o RegisterServerAutoRecoveryRequest) String() string ", "output": "{\n\tdata, err := utils.Marshal(o)\n\tif err != nil {\n\t\treturn \"RegisterServerAutoRecoveryRequest struct{}\"\n\t}\n\n\treturn strings.Join([]string{\"RegisterServerAutoRecoveryRequest\", string(data)}, \" \")\n}"} {"input": "package timer\n\nimport \"time\"\nimport \"Kari/lib/logger\"\n\nvar Tickers map[int]*Ticker = make(map[int]*Ticker)\n\ntype Ticker struct {\n\tduration *int\n\tticker *time.Ticker\n\tquit chan struct{}\n\tevents []*TickerEvent\n}\n\ntype TickerEvent struct {\n\thandle string\n\tcallback func()\n}\n\nfunc AddEvent(handle string, ticker int, callback func()) {\n\tif !tickerExists(&ticker) {\n\t\tStartTicker(ticker)\n\t}\n\tTickers[ticker].events = append(Tickers[ticker].events, &TickerEvent{handle, callback})\n\n}\n\nfunc RemoveEvent(handle string, ticker int) {\n\tfor i, event := range Tickers[ticker].events {\n\t\tif event.handle == handle {\n\t\t\tevents := Tickers[ticker].events\n\t\t\tevents = append(events[:i], events[i+1:]...)\n\t\t\tTickers[ticker].events = events\n\t\t}\n\t}\n}\n\nfunc eventExists(ticker *int, handle *string) bool {\n\tif tickerExists(ticker) {\n\t\tfor _, event := range Tickers[*ticker].events {\n\t\t\tif event.handle == *handle {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc tickerExists(ticker *int) bool {\n\t_, ok := Tickers[*ticker]\n\treturn ok\n}\n\n\n\nfunc StopTicker(ticker int) {\n\tif !tickerExists(&ticker) {\n\t\tlogger.Debug(\"Tried to stop non-existant \" + string(ticker) + \"s ticker.\")\n\t\treturn\n\t}\n\tclose(Tickers[ticker].quit)\n\tlogger.Debug(\"Stopped \" + string(ticker) + \"s ticker.\")\n}\n\nfunc StartTicker(seconds int) ", "output": "{\n\tif tickerExists(&seconds) {\n\t\tlogger.Debug(\"Not starting another \" + string(seconds) + \"s ticker.\")\n\t\treturn\n\t}\n\tTickers[seconds] = &Ticker{\n\t\tduration: &seconds,\n\t\tticker: time.NewTicker(time.Duration(seconds) * time.Second),\n\t\tquit: make(chan struct{}),\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-Tickers[seconds].ticker.C:\n\t\t\t\tfor _, event := range Tickers[seconds].events {\n\t\t\t\t\tevent.callback()\n\t\t\t\t}\n\t\t\tcase <-Tickers[seconds].quit:\n\t\t\t\tTickers[seconds].ticker.Stop()\n\t\t\t\tlogger.Debug(\"Stopped \" + string(seconds) + \"s ticker.\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}"} {"input": "package model\n\ntype Interface interface {\n\tVisitString(name string, resume func())\n\tVisitInt(name string, resume func())\n\tVisitFloat(name string, resume func())\n\tVisitBool(name string, resume func())\n\tVisitPtr(name string, resume func())\n\tVisitBytes(name string, resume func())\n\tVisitSlice(name string, resume func())\n\tVisitStruct(name string, fields []Field, resume func())\n\tVisitStructField(field Field, resume func())\n\tVisitMap(name string, resume func())\n\tVisitCustom(name string, resume func())\n\tVisitReference(name string, resume func())\n}\n\ntype Visitor struct{}\n\nfunc (self *Visitor) VisitString(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitInt(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitFloat(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBool(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitPtr(name string, resume func()) {\n\tresume()\n}\n\n\n\nfunc (self *Visitor) VisitSlice(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStructField(field Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitMap(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitCustom(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitReference(name string, resume func()) {\n\tresume()\n}\n\ntype EmbeddedStructVisitor struct {\n\tInterface\n}\n\nfunc (self *EmbeddedStructVisitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBytes(name string, resume func()) ", "output": "{\n\tresume()\n}"} {"input": "package discovery\n\nimport (\n\t\"encoding/hex\"\n\t\"sync\"\n\n\t\"github.com/hyperledger/fabric/common/util\"\n)\n\n\n\ntype MemoizeSigner struct {\n\tmaxEntries uint\n\tsync.RWMutex\n\tmemory map[string][]byte\n\tsign Signer\n}\n\n\n\nfunc NewMemoizeSigner(signFunc Signer, maxEntries uint) *MemoizeSigner {\n\treturn &MemoizeSigner{\n\t\tmaxEntries: maxEntries,\n\t\tmemory: make(map[string][]byte),\n\t\tsign: signFunc,\n\t}\n}\n\n\n\nfunc (ms *MemoizeSigner) Sign(msg []byte) ([]byte, error) {\n\tsig, isInMemory := ms.lookup(msg)\n\tif isInMemory {\n\t\treturn sig, nil\n\t}\n\tsig, err := ms.sign(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tms.memorize(msg, sig)\n\treturn sig, nil\n}\n\n\n\nfunc (ms *MemoizeSigner) lookup(msg []byte) ([]byte, bool) {\n\tms.RLock()\n\tdefer ms.RUnlock()\n\tsig, exists := ms.memory[msgDigest(msg)]\n\treturn sig, exists\n}\n\n\n\n\n\nfunc (ms *MemoizeSigner) shrinkMemory() {\n\tms.Lock()\n\tdefer ms.Unlock()\n\tfor len(ms.memory) > (int)(ms.maxEntries) {\n\t\tms.evictFromMemory()\n\t}\n}\n\n\nfunc (ms *MemoizeSigner) evictFromMemory() {\n\tfor dig := range ms.memory {\n\t\tdelete(ms.memory, dig)\n\t\treturn\n\t}\n}\n\n\nfunc msgDigest(msg []byte) string {\n\treturn hex.EncodeToString(util.ComputeSHA256(msg))\n}\n\nfunc (ms *MemoizeSigner) memorize(msg, signature []byte) ", "output": "{\n\tif ms.maxEntries == 0 {\n\t\treturn\n\t}\n\tms.RLock()\n\tshouldShrink := len(ms.memory) >= (int)(ms.maxEntries)\n\tms.RUnlock()\n\n\tif shouldShrink {\n\t\tms.shrinkMemory()\n\t}\n\tms.Lock()\n\tdefer ms.Unlock()\n\tms.memory[msgDigest(msg)] = signature\n}"} {"input": "package atc\n\nimport (\n\t\"errors\"\n\n\tmultierror \"github.com/hashicorp/go-multierror\"\n)\n\ntype AuthFlags struct {\n\tNoAuth bool `long:\"no-really-i-dont-want-any-auth\" description:\"Ignore warnings about not configuring auth\"`\n\n\tBasicAuth BasicAuthFlag `group:\"Basic Authentication\" namespace:\"basic-auth\"`\n}\n\ntype BasicAuthFlag struct {\n\tUsername string `long:\"username\" description:\"Username to use for basic auth.\"`\n\tPassword string `long:\"password\" description:\"Password to use for basic auth.\"`\n}\n\n\n\nfunc (auth *BasicAuthFlag) Validate() error {\n\tvar errs *multierror.Error\n\tif auth.Username == \"\" {\n\t\terrs = multierror.Append(\n\t\t\terrs,\n\t\t\terrors.New(\"must specify --basic-auth-username to use basic auth.\"),\n\t\t)\n\t}\n\tif auth.Password == \"\" {\n\t\terrs = multierror.Append(\n\t\t\terrs,\n\t\t\terrors.New(\"must specify --basic-auth-password to use basic auth.\"),\n\t\t)\n\t}\n\treturn errs.ErrorOrNil()\n}\n\nfunc (auth *BasicAuthFlag) IsConfigured() bool ", "output": "{\n\treturn auth.Username != \"\" || auth.Password != \"\"\n}"} {"input": "package segment\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/checkr/flagr/swagger_gen/models\"\n)\n\n\nconst DeleteSegmentOKCode int = 200\n\n\ntype DeleteSegmentOK struct {\n}\n\n\nfunc NewDeleteSegmentOK() *DeleteSegmentOK {\n\n\treturn &DeleteSegmentOK{}\n}\n\n\nfunc (o *DeleteSegmentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(200)\n}\n\n\ntype DeleteSegmentDefault struct {\n\t_statusCode int\n\n\tPayload *models.Error `json:\"body,omitempty\"`\n}\n\n\nfunc NewDeleteSegmentDefault(code int) *DeleteSegmentDefault {\n\tif code <= 0 {\n\t\tcode = 500\n\t}\n\n\treturn &DeleteSegmentDefault{\n\t\t_statusCode: code,\n\t}\n}\n\n\nfunc (o *DeleteSegmentDefault) WithStatusCode(code int) *DeleteSegmentDefault {\n\to._statusCode = code\n\treturn o\n}\n\n\nfunc (o *DeleteSegmentDefault) SetStatusCode(code int) {\n\to._statusCode = code\n}\n\n\nfunc (o *DeleteSegmentDefault) WithPayload(payload *models.Error) *DeleteSegmentDefault {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *DeleteSegmentDefault) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}\n\n\n\n\nfunc (o *DeleteSegmentDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\trw.WriteHeader(o._statusCode)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}"} {"input": "package stager\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/hatofmonkeys/cloudfocker/utils\"\n\n\t\"github.com/cloudfoundry-incubator/linux-circus/buildpackrunner\"\n\t\"github.com/cloudfoundry-incubator/runtime-schema/models\"\n)\n\ntype BuildpackRunner interface {\n\tRun() error\n}\n\nfunc RunBuildpack(writer io.Writer, runner BuildpackRunner) error {\n\tfmt.Fprintln(writer, \"Running Buildpacks...\")\n\treturn runner.Run()\n}\n\nfunc NewBuildpackRunner(buildpackDir string) *buildpackrunner.Runner {\n\tprepareMd5BuildpacksDir(buildpackDir, \"/tmp/buildpacks\")\n\tvar err error\n\tdirs := []string{}\n\tif dirs, err = utils.SubDirs(buildpackDir); err != nil {\n\t\tlog.Fatalf(\" %s\", err)\n\t}\n\tconfig := models.NewCircusTailorConfig(dirs)\n\treturn buildpackrunner.New(&config)\n}\n\nfunc ValidateStagedApp(cloudfockerHome string) error {\n\tif _, err := os.Stat(cloudfockerHome + \"/droplet/app\"); err != nil {\n\t\treturn fmt.Errorf(\"Staging failed - have you added a buildpack for this type of application?\")\n\t}\n\tif _, err := os.Stat(cloudfockerHome + \"/droplet/staging_info.yml\"); err != nil {\n\t\treturn fmt.Errorf(\"Staging failed - no staging info was produced by the matching buildpack!\")\n\t}\n\treturn nil\n}\n\n\n\nfunc md5sum(src string) string {\n\treturn fmt.Sprintf(\"%x\", md5.Sum([]byte(src)))\n}\n\nfunc prepareMd5BuildpacksDir(src string, dst string) ", "output": "{\n\tos.MkdirAll(src, 0755)\n\tos.MkdirAll(dst, 0755)\n\tvar err error\n\tdirs := []string{}\n\tif dirs, err = utils.SubDirs(src); err != nil {\n\t\tlog.Fatalf(\" %s\", err)\n\t}\n\tfor _, dir := range dirs {\n\t\tif err := os.Symlink(src+\"/\"+dir, dst+\"/\"+md5sum(dir)); err != nil {\n\t\t\tlog.Fatalf(\" %s\", err)\n\t\t}\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\n\n\nfunc HandleErr(err error) ", "output": "{\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}"} {"input": "package classfile\n\nimport \"encoding/binary\"\n\ntype ClassReader struct {\n\tdata []byte \n}\n\nfunc (self *ClassReader) readUint8() uint8 {\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}\n\n\n\nfunc (self *ClassReader) readUint32() uint32 {\n\tval := binary.BigEndian.Uint32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint64() uint64 {\n\tval := binary.BigEndian.Uint64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16s() []uint16 {\n\tn := self.readUint16()\n\ts := make([]uint16, n)\n\tfor i := range s {\n\t\ts[i] = self.readUint16()\n\t}\n\treturn s\n}\n\nfunc (self *ClassReader) readBytes(n uint32) []byte {\n\tbytes := self.data[:n]\n\tself.data = self.data[n:]\n\treturn bytes\n}\n\nfunc (self *ClassReader) readUint16() uint16 ", "output": "{\n\tval := binary.BigEndian.Uint16(self.data)\n\tself.data = self.data[2:]\n\treturn val\n}"} {"input": "package subscriptions\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/status-im/status-go/rpc\"\n)\n\ntype ethFilter struct {\n\tid string\n\trpcClient *rpc.Client\n}\n\n\n\nfunc (ef *ethFilter) getID() string {\n\treturn ef.id\n}\n\nfunc (ef *ethFilter) getChanges() ([]interface{}, error) {\n\tvar result []interface{}\n\n\terr := ef.rpcClient.Call(&result, ef.rpcClient.UpstreamChainID, \"eth_getFilterChanges\", ef.getID())\n\n\treturn result, err\n}\n\nfunc (ef *ethFilter) uninstall() error {\n\treturn ef.rpcClient.Call(nil, ef.rpcClient.UpstreamChainID, \"eth_uninstallFilter\", ef.getID())\n}\n\nfunc validateEthMethod(method string) error {\n\tfor _, allowedMethod := range []string{\n\t\t\"eth_newFilter\",\n\t\t\"eth_newBlockFilter\",\n\t\t\"eth_newPendingTransactionFilter\",\n\t} {\n\t\tif method == allowedMethod {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"unexpected filter method: %s\", method)\n}\n\nfunc installEthFilter(rpcClient *rpc.Client, method string, args []interface{}) (*ethFilter, error) ", "output": "{\n\n\tif err := validateEthMethod(method); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result string\n\n\terr := rpcClient.Call(&result, rpcClient.UpstreamChainID, method, args...)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilter := ðFilter{\n\t\tid: result,\n\t\trpcClient: rpcClient,\n\t}\n\n\treturn filter, nil\n\n}"} {"input": "package format\n\nimport (\n\t\"testing\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestSshWithoutComment(t *testing.T) {\n\tlog.SetLevel(log.DebugLevel)\n\n\tkeys := map[string][]string{\n\t\t\"ernoaapa\": {\n\t\t\t\"ssh-rsa AAAAB3NzsshPublicKeyBlah\",\n\t\t},\n\t}\n\n\tresult := ssh(keys, \"\")\n\n\tassert.Equal(t, \"ssh-rsa AAAAB3NzsshPublicKeyBlah ernoaapa\\n\", result, \"Returned invalid ssh output\")\n}\n\n\n\nfunc TestSshWithComment(t *testing.T) ", "output": "{\n\tlog.SetLevel(log.DebugLevel)\n\n\tkeys := map[string][]string{\n\t\t\"ernoaapa\": {\n\t\t\t\"ssh-rsa AAAAB3NzsshPublicKeyBlah\",\n\t\t},\n\t}\n\n\tresult := ssh(keys, \"Generated file\")\n\n\tassert.Equal(t, \"# Generated file\\nssh-rsa AAAAB3NzsshPublicKeyBlah ernoaapa\\n# Generated file\\n\", result, \"Returned invalid ssh output\")\n}"} {"input": "package crypto\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha512\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n)\n\n\nfunc HS512Byte(in, secret []byte) []byte {\n\th := hmac.New(sha512.New, secret)\n\th.Write(in)\n\treturn h.Sum(nil)\n}\n\n\nfunc HS512Base64(in, secret string) string {\n\tkey := []byte(secret)\n\th := hmac.New(sha512.New, key)\n\th.Write([]byte(in))\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil))\n}\n\n\n\n\n\nfunc CompareHS512Hex(in, secret, hs512Hex string) bool {\n\tif HS512Hex(in, secret) == hs512Hex {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc HS512Hex(in, secret string) string ", "output": "{\n\tkey := []byte(secret)\n\th := hmac.New(sha512.New, key)\n\th.Write([]byte(in))\n\treturn hex.EncodeToString(h.Sum(nil))\n}"} {"input": "package calicoclient\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/projectcalico/libcalico-go/lib/apiconfig\"\n\tclient \"github.com/projectcalico/libcalico-go/lib/clientv3\"\n)\n\n\n\n\n\nfunc CreateClient() (*apiconfig.CalicoAPIConfig, client.Interface) ", "output": "{\n\tcfg, err := apiconfig.LoadClientConfig(\"\")\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: Error loading datastore config: %s\", err)\n\t\tos.Exit(1)\n\t}\n\tc, err := client.New(*cfg)\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: Error accessing the Calico datastore: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\treturn cfg, c\n}"} {"input": "package models\n\ntype Checksum struct {\n ContentHash string\n Type ChecksumType\n}\n\n\n\nfunc NewNoneChecksum() Checksum ", "output": "{\n return Checksum{\n Type: NONE,\n ContentHash: \"\" }\n}"} {"input": "package hashcash\n\nimport (\n\t\"encoding/hex\"\n\t\"testing\"\n)\n\n\n\nfunc TestHashCash(t *testing.T) {\n\td := []byte(\"abcefghi\")\n\tn, ok := ComputeNonce(d, 10, 0, 0)\n\tif !ok {\n\t\tt.Error(\"No match found\")\n\t}\n\tif hex.EncodeToString(n) != \"b301000000000000\" {\n\t\tt.Errorf(\"Nonce error b301000000000000 != %s\", hex.EncodeToString(n))\n\t}\n}\n\nfunc TestComputeParallel(t *testing.T) {\n\td := []byte(\"abcefghi\")\n\tbits := byte(21)\n\tnonce, _ := ComputeNonceSelect(d, bits, 0, 0) \n\tok, _ := TestNonce(d, nonce, bits)\n\tif !ok {\n\t\tt.Error(\"No Nonce found\")\n\t}\n}\n\nfunc TestTestNonce(t *testing.T) {\n\td := []byte(\"abcefghi\")\n\tn := []byte{0x09, 0x0e, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00}\n\tok, _ := TestNonce(d, n, 20)\n\tif !ok {\n\t\tt.Error(\"Nonce verification failed\")\n\t}\n\tn = []byte{0x09, 0x0e, 0x28, 0x00, 0x00, 0x00, 0x00, 0x01}\n\tok, c := TestNonce(d, n, 20)\n\tif ok {\n\t\tt.Errorf(\"Nonce verification MUST fail: %d < 20\", c)\n\t}\n}\n\nfunc TestBitCount(t *testing.T) ", "output": "{\n\tc := BitCount([32]byte{0x00, 0x00, 0x08, 0x02})\n\tif c != 20 {\n\t\tt.Error(\"Count error\")\n\t}\n}"} {"input": "package protocol\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestProtocol(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Protocol Suite\")\n}"} {"input": "package conn\n\nimport (\n\t\"log\"\n\t\"time\"\n\n\t\"net/http\"\n\n\t\"github.com/garyburd/redigo/redis\"\n\t\"github.com/jmoiron/sqlx\"\n\t_ \"github.com/lib/pq\"\n\t\"google.golang.org/api/googleapi/transport\"\n\t\"google.golang.org/api/vision/v1\"\n\t\"googlemaps.github.io/maps\"\n)\n\nfunc DialPostgres(postgresURL string) (db *sqlx.DB) {\n\tvar err error\n\n\tdb, err = sqlx.Open(\"postgres\", postgresURL)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}\n\n\n\nfunc DialGoogleServices(apiKey string) (*vision.Service, *maps.Client, error) {\n\tvar err error\n\n\tclient := &http.Client{\n\t\tTransport: &transport.APIKey{Key: apiKey},\n\t}\n\tvisionService, err := vision.New(client)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tmapsClient, err := maps.NewClient(maps.WithAPIKey(apiKey))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn visionService, mapsClient, nil\n}\n\nfunc DialRedis(server string) *redis.Pool ", "output": "{\n\treturn &redis.Pool{\n\t\tMaxActive: 15,\n\t\tWait: true,\n\t\tMaxIdle: 3,\n\t\tIdleTimeout: 240 * time.Second,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.DialURL(server)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif _, err := c.Do(\"PING\"); err != nil {\n\t\t\t\tc.Close()\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, nil\n\t\t},\n\t\tTestOnBorrow: func(c redis.Conn, t time.Time) error {\n\t\t\tif time.Since(t) < time.Minute {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t_, err := c.Do(\"PING\")\n\t\t\treturn err\n\t\t},\n\t}\n}"} {"input": "package tcpproxy\n\n\n\ntype Process struct{\n\tPid int\n\tPidFile string\n}\n\nfunc(p *Process) kill() error{\n\n\treturn nil\n}\n\n\n\nfunc(p *Process) getPidFromFile() int{\n\n\treturn nil\n}\n\nfunc(p *Process) storePidToFile() error", "output": "{\n\n\treturn nil\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/spf13/cobra\"\n\n\t\"k8s.io/cli-runtime/pkg/genericclioptions\"\n\t\"k8s.io/kubectl/pkg/util/templates\"\n\tcmdutil \"k8s.io/kubernetes/pkg/kubectl/cmd/util\"\n\t\"k8s.io/kubernetes/pkg/kubectl/util/i18n\"\n)\n\n\n\n\nfunc NewCmdAlpha(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command ", "output": "{\n\tcmd := &cobra.Command{\n\t\tUse: \"alpha\",\n\t\tShort: i18n.T(\"Commands for features in alpha\"),\n\t\tLong: templates.LongDesc(i18n.T(\"These commands correspond to alpha features that are not enabled in Kubernetes clusters by default.\")),\n\t}\n\n\n\tif !cmd.HasSubCommands() {\n\t\tcmd.SetHelpFunc(func(*cobra.Command, []string) {\n\t\t\tcmd.Println(i18n.T(\"No alpha commands are available in this version of kubectl\"))\n\t\t})\n\t}\n\n\treturn cmd\n}"} {"input": "package camelcase\n\nimport (\n\t\"bytes\"\n\t\"unicode/utf8\"\n\n\t\"github.com/blevesearch/bleve/analysis\"\n\t\"github.com/blevesearch/bleve/registry\"\n)\n\nconst Name = \"camelCase\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype CamelCaseFilter struct{}\n\nfunc NewCamelCaseFilter() *CamelCaseFilter {\n\treturn &CamelCaseFilter{}\n}\n\nfunc (f *CamelCaseFilter) Filter(input analysis.TokenStream) analysis.TokenStream {\n\trv := make(analysis.TokenStream, 0, len(input))\n\n\tnextPosition := 1\n\tfor _, token := range input {\n\t\truneCount := utf8.RuneCount(token.Term)\n\t\trunes := bytes.Runes(token.Term)\n\n\t\tp := NewParser(runeCount, nextPosition, token.Start)\n\t\tfor i := 0; i < runeCount; i++ {\n\t\t\tif i+1 >= runeCount {\n\t\t\t\tp.Push(runes[i], nil)\n\t\t\t} else {\n\t\t\t\tp.Push(runes[i], &runes[i+1])\n\t\t\t}\n\t\t}\n\t\trv = append(rv, p.FlushTokens()...)\n\t\tnextPosition = p.NextPosition()\n\t}\n\treturn rv\n}\n\n\n\nfunc init() {\n\tregistry.RegisterTokenFilter(Name, CamelCaseFilterConstructor)\n}\n\nfunc CamelCaseFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) ", "output": "{\n\treturn NewCamelCaseFilter(), nil\n}"} {"input": "package versions\n\nimport (\n\t\"fmt\"\n)\n\ntype setBound struct {\n\tv Version\n\top setBoundOp\n}\n\nfunc (s setBound) Has(v Version) bool {\n\tswitch s.op {\n\tcase setBoundGT:\n\t\treturn v.GreaterThan(s.v)\n\tcase setBoundGTE:\n\t\treturn v.GreaterThan(s.v) || v.Same(s.v)\n\tcase setBoundLT:\n\t\treturn v.LessThan(s.v)\n\tcase setBoundLTE:\n\t\treturn v.LessThan(s.v) || v.Same(s.v)\n\tdefault:\n\t\tpanic(\"invalid setBound operator\")\n\t}\n}\n\nfunc (s setBound) AllRequested() Set {\n\treturn None\n}\n\n\n\n\n\nfunc NewerThan(v Version) Set {\n\treturn Set{\n\t\tsetI: setBound{\n\t\t\tv: v,\n\t\t\top: setBoundGT,\n\t\t},\n\t}\n}\n\n\n\nfunc OlderThan(v Version) Set {\n\treturn Set{\n\t\tsetI: setBound{\n\t\t\tv: v,\n\t\t\top: setBoundLT,\n\t\t},\n\t}\n}\n\n\n\nfunc AtLeast(v Version) Set {\n\treturn Set{\n\t\tsetI: setBound{\n\t\t\tv: v,\n\t\t\top: setBoundGTE,\n\t\t},\n\t}\n}\n\n\n\nfunc AtMost(v Version) Set {\n\treturn Set{\n\t\tsetI: setBound{\n\t\t\tv: v,\n\t\t\top: setBoundLTE,\n\t\t},\n\t}\n}\n\ntype setBoundOp rune\n\nconst setBoundGT = '>'\nconst setBoundGTE = '≥'\nconst setBoundLT = '<'\nconst setBoundLTE = '≤'\n\nfunc (s setBound) GoString() string ", "output": "{\n\tswitch s.op {\n\tcase setBoundGT:\n\t\treturn fmt.Sprintf(\"versions.NewerThan(%#v)\", s.v)\n\tcase setBoundGTE:\n\t\treturn fmt.Sprintf(\"versions.AtLeast(%#v)\", s.v)\n\tcase setBoundLT:\n\t\treturn fmt.Sprintf(\"versions.OlderThan(%#v)\", s.v)\n\tcase setBoundLTE:\n\t\treturn fmt.Sprintf(\"versions.AtMost(%#v)\", s.v)\n\tdefault:\n\t\treturn fmt.Sprintf(\"versions.Set{versions.setBound{v:%#v,op:%#v}}\", s.v, s.op)\n\t}\n}"} {"input": "package namespace\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/containerum/chkit/pkg/model\"\n)\n\nvar (\n\t_ model.JSONrenderer = new(NamespaceList)\n)\n\n\n\nfunc (list NamespaceList) RenderJSON() (string, error) ", "output": "{\n\tdata, err := json.MarshalIndent(list.ToKube(), \"\", model.Indent)\n\treturn string(data), err\n}"} {"input": "package k1\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t\"github.com/songgao/water\"\n)\n\nfunc execCommand(name, sargs string) error {\n\targs := strings.Split(sargs, \" \")\n\tcmd := exec.Command(name, args...)\n\tlogger.Infof(\"exec command: %s %s\", name, sargs)\n\treturn cmd.Run()\n}\n\n\n\nfunc addRoute(tun string, subnet *net.IPNet) error {\n\tip := subnet.IP\n\tmaskIP := net.IP(subnet.Mask)\n\tsargs := fmt.Sprintf(\"-n add -net %s -netmask %s -interface %s\", ip.String(), maskIP.String(), tun)\n\treturn execCommand(\"route\", sargs)\n}\n\nfunc createTun(ip net.IP, mask net.IPMask) (*water.Interface, error) {\n\tifce, err := water.New(water.Config{\n\t\tDeviceType: water.TUN,\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger.Infof(\"create %s\", ifce.Name())\n\n\tipNet := &net.IPNet{\n\t\tIP: ip,\n\t\tMask: mask,\n\t}\n\n\tif err := initTun(ifce.Name(), ipNet, MTU); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ifce, nil\n}\n\n\nfunc fixTunIP(ip net.IP) net.IP {\n\treturn net.IPv4zero\n}\n\nfunc initTun(tun string, ipNet *net.IPNet, mtu int) error ", "output": "{\n\tip := ipNet.IP\n\tmaskIP := net.IP(ipNet.Mask)\n\tsargs := fmt.Sprintf(\"%s %s %s mtu %d netmask %s up\", tun, ip.String(), ip.String(), mtu, maskIP.String())\n\tif err := execCommand(\"ifconfig\", sargs); err != nil {\n\t\treturn err\n\t}\n\treturn addRoute(tun, ipNet)\n}"} {"input": "package user\n\nimport (\n\t\"context\"\n\t\"flag\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/ssoadmin\"\n)\n\ntype rm struct {\n\t*flags.ClientFlag\n}\n\n\n\nfunc (cmd *rm) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.ClientFlag, ctx = flags.NewClientFlag(ctx)\n\tcmd.ClientFlag.Register(ctx, f)\n}\n\nfunc (cmd *rm) Usage() string {\n\treturn \"NAME\"\n}\n\nfunc (cmd *rm) Description() string {\n\treturn `Remove SSO users.\n\nExamples:\n govc sso.user.rm NAME`\n}\n\nfunc (cmd *rm) Run(ctx context.Context, f *flag.FlagSet) error {\n\treturn withClient(ctx, cmd.ClientFlag, func(c *ssoadmin.Client) error {\n\t\treturn c.DeletePrincipal(ctx, f.Arg(0))\n\t})\n}\n\nfunc init() ", "output": "{\n\tcli.Register(\"sso.user.rm\", &rm{})\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"github.com/gin-gonic/gin\"\n \"github.com/dgrijalva/jwt-go\"\n)\n\n\n\nfunc getDetailsfromToken(tokenString string) (string, string, string) {\n vertoken, _ := jwt.Parse(tokenString, func (token *jwt.Token) (interface{}, error) {\n if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\n return nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n }\n return mySigningKey, nil\n })\n if claims, _ := vertoken.Claims.(jwt.MapClaims); !vertoken.Valid {\n id := claims[\"id\"].(string)\n email_id := claims[\"email_id\"].(string)\n client_id := claims[\"client_id\"].(string)\n fmt.Println(\"Resending email for :\", id, email_id, client_id)\n return id, client_id, email_id\n }\n return \"\",\"\",\"\"\n}\n\nfunc resendEmailVerificationHandler(c *gin.Context)", "output": "{\n var request struct{\n Token string `form:\"token\" binding:\"required\"`\n }\n if c.Bind(&request) == nil{\n if mobileno, client_id, email_id := getDetailsfromToken(request.Token); mobileno != \"\" || client_id != \"\" || email_id != \"\"{\n sendEmailVerification(mobileno, client_id, email_id)\n c.JSON(200, gin.H{\n \"status\" : \"success\",\n })\n }else{\n c.JSON(200, gin.H{\n \"status\" : \"failed\",\n \"message\" : \"Failed to Send Verification Email! Please try again\",\n })\n }\n }\n}"} {"input": "package common\n\nimport \"github.com/juju/juju/state\"\n\nvar (\n\tMachineJobFromParams = machineJobFromParams\n\tValidateNewFacade = validateNewFacade\n\tWrapNewFacade = wrapNewFacade\n\tNilFacadeRecord = facadeRecord{}\n\tEnvtoolsFindTools = &envtoolsFindTools\n)\n\ntype Patcher interface {\n\tPatchValue(dest, value interface{})\n}\n\n\n\n\nfunc SanitizeFacades(patcher Patcher) {\n\temptyFacades := &FacadeRegistry{}\n\tpatcher.PatchValue(&Facades, emptyFacades)\n}\n\ntype Versions versions\n\nfunc DescriptionFromVersions(name string, vers Versions) FacadeDescription {\n\treturn descriptionFromVersions(name, versions(vers))\n}\n\n\n\nfunc NewMultiNotifyWatcher(w ...state.NotifyWatcher) state.NotifyWatcher ", "output": "{\n\tmw := newMultiNotifyWatcher(w...)\n\treturn mw\n}"} {"input": "package coproto\n\nimport \"sync\"\n\n\n\n\n\ntype Client struct {\n\tmutex sync.Mutex\n\tgroup *ClientGroup\n}\n\n\n\n\n\n\n\nfunc (c *Client) Group() *ClientGroup {\n\treturn c.group\n}\n\nfunc (c *Client) Close() ", "output": "{\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tif c.group == nil {\n\t\treturn \n\t}\n\tc.group.remove(c)\n}"} {"input": "package bunyan\n\nimport \"os\"\n\n\n\ntype Sink interface {\n\tWrite(record Record) error\n}\n\ntype funcSink struct {\n\twrite func(record Record) error\n}\n\n\n\n\n\nfunc SinkFunc(write func(record Record) error) Sink {\n\treturn &funcSink{write}\n}\n\n\n\nfunc NilSink() Sink {\n\treturn SinkFunc(func(record Record) error {\n\t\treturn nil \n\t})\n}\n\nfunc InfoSink(target Sink, info Info) Sink {\n\treturn SinkFunc(func(record Record) error {\n\t\trecord.SetIfNot(info.Key(), info.Value())\n\t\treturn target.Write(record)\n\t})\n}\n\n\nfunc StdoutSink() Sink {\n\treturn NewJsonSink(os.Stdout)\n}\n\n\nfunc FileSink(path string) Sink {\n\tconst flags = os.O_CREATE | os.O_APPEND | os.O_WRONLY\n\tfile, e := os.OpenFile(path, flags, 0666)\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\n\treturn NewJsonSink(file)\n}\n\nfunc (sink *funcSink) Write(record Record) error ", "output": "{\n\treturn sink.write(record)\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/mexisme/go-config/settings\"\n)\n\n\nfunc AddConfigItems(configKeys []string) {\n\tsettings.AddConfigItems(configKeys)\n}\n\n\nfunc AddConfigItemsWithPFlags(configKeys []string) error {\n\treturn settings.AddConfigItemsWithPFlags(configKeys)\n}\n\n\nfunc ApplyWith(key string, f func(interface{})) {\n\tsettings.ApplyWith(key, f)\n}\n\n\nfunc Get(key string) interface{} {\n\treturn settings.Get(key)\n}\n\n\nfunc GetBool(key string) bool {\n\treturn settings.GetBool(key)\n}\n\n\nfunc GetFloat64(key string) float64 {\n\treturn settings.GetFloat64(key)\n}\n\n\nfunc GetInt(key string) int {\n\treturn settings.GetInt(key)\n}\n\n\nfunc GetString(key string) string {\n\treturn settings.GetString(key)\n}\n\n\nfunc GetStringMap(key string) map[string]interface{} {\n\treturn settings.GetStringMap(key)\n}\n\n\nfunc GetStringMapString(key string) map[string]string {\n\treturn settings.GetStringMapString(key)\n}\n\n\nfunc GetStringSlice(key string) []string {\n\treturn settings.GetStringSlice(key)\n}\n\n\n\n\n\nfunc GetDuration(key string) time.Duration {\n\treturn settings.GetDuration(key)\n}\n\n\nfunc IsSet(key string) bool {\n\treturn settings.IsSet(key)\n}\n\n\nfunc AllSettings() map[string]interface{} {\n\treturn settings.AllSettings()\n}\n\nfunc GetTime(key string) time.Time ", "output": "{\n\treturn settings.GetTime(key)\n}"} {"input": "package kubectl\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n)\n\n\n\n\ntype FilterFunc func(runtime.Object, PrintOptions) bool\n\n\ntype Filters []FilterFunc\n\nfunc NewResourceFilter() Filters {\n\treturn []FilterFunc{\n\t\tfilterPods,\n\t}\n}\n\n\n\n\n\n\nfunc (f Filters) Filter(obj runtime.Object, opts *PrintOptions) (bool, error) {\n\tobj, _ = DecodeUnknownObject(obj)\n\n\tfor _, filter := range f {\n\t\tif ok := filter(obj, *opts); ok {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}\n\n\nfunc DecodeUnknownObject(obj runtime.Object) (runtime.Object, error) {\n\tvar err error\n\n\tswitch obj.(type) {\n\tcase runtime.Unstructured, *runtime.Unknown:\n\t\tif objBytes, err := runtime.Encode(api.Codecs.LegacyCodec(), obj); err == nil {\n\t\t\tif decodedObj, err := runtime.Decode(api.Codecs.UniversalDecoder(), objBytes); err == nil {\n\t\t\t\tobj = decodedObj\n\t\t\t}\n\t\t}\n\t}\n\n\treturn obj, err\n}\n\nfunc filterPods(obj runtime.Object, options PrintOptions) bool ", "output": "{\n\tswitch p := obj.(type) {\n\tcase *v1.Pod:\n\t\treason := string(p.Status.Phase)\n\t\tif p.Status.Reason != \"\" {\n\t\t\treason = p.Status.Reason\n\t\t}\n\t\treturn !options.ShowAll && (reason == string(v1.PodSucceeded) || reason == string(v1.PodFailed))\n\tcase *api.Pod:\n\t\treason := string(p.Status.Phase)\n\t\tif p.Status.Reason != \"\" {\n\t\t\treason = p.Status.Reason\n\t\t}\n\t\treturn !options.ShowAll && (reason == string(api.PodSucceeded) || reason == string(api.PodFailed))\n\t}\n\treturn false\n}"} {"input": "package engine\n\nimport (\n\tvtrpcpb \"vitess.io/vitess/go/vt/proto/vtrpc\"\n\t\"vitess.io/vitess/go/vt/vterrors\"\n\n\t\"vitess.io/vitess/go/sqltypes\"\n\t\"vitess.io/vitess/go/vt/proto/query\"\n)\n\nvar _ Primitive = (*UpdateTarget)(nil)\n\n\ntype UpdateTarget struct {\n\tTarget string\n\n\tnoInputs\n\n\tnoTxNeeded\n}\n\nfunc (updTarget *UpdateTarget) description() PrimitiveDescription {\n\treturn PrimitiveDescription{\n\t\tOperatorType: \"UpdateTarget\",\n\t\tOther: map[string]interface{}{\"target\": updTarget.Target},\n\t}\n}\n\n\nfunc (updTarget *UpdateTarget) RouteType() string {\n\treturn \"UpdateTarget\"\n}\n\n\nfunc (updTarget *UpdateTarget) GetKeyspaceName() string {\n\treturn updTarget.Target\n}\n\n\nfunc (updTarget *UpdateTarget) GetTableName() string {\n\treturn \"\"\n}\n\n\n\n\n\nfunc (updTarget *UpdateTarget) TryStreamExecute(vcursor VCursor, bindVars map[string]*query.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error {\n\tresult, err := updTarget.TryExecute(vcursor, bindVars, wantfields)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn callback(result)\n}\n\n\nfunc (updTarget *UpdateTarget) GetFields(vcursor VCursor, bindVars map[string]*query.BindVariable) (*sqltypes.Result, error) {\n\treturn nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, \"[BUG] GetFields not reachable for use statement\")\n}\n\nfunc (updTarget *UpdateTarget) TryExecute(vcursor VCursor, bindVars map[string]*query.BindVariable, wantfields bool) (*sqltypes.Result, error) ", "output": "{\n\terr := vcursor.Session().SetTarget(updTarget.Target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &sqltypes.Result{}, nil\n}"} {"input": "package policy\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"fmt\"\n)\n\nconst (\n\tmajor = \"7\"\n\tminor = \"0\"\n\tpatch = \"1\"\n\ttag = \"-beta\"\n\tsemVerFormat = \"%s.%s.%s%s\"\n\tuserAgentFormat = \"Azure-SDK-for-Go/%s arm-%s/%s\"\n)\n\n\n\n\n\nfunc Version() string {\n\treturn fmt.Sprintf(semVerFormat, major, minor, patch, tag)\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn fmt.Sprintf(userAgentFormat, Version(), \"policy\", \"2016-04-01\")\n}"} {"input": "package glu\n\nvar _Perspective func(fovy, aspect, near, far float64)\nvar _LookAt func(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ float64)\n\n\n\nfunc RegisterLookAt(fn func(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ float64)) {\n\t_LookAt = fn\n}\n\nfunc Perspective(fovy, aspect, near, far float64) {\n\tif _Perspective == nil {\n\t\tpanic(\"Please register a Perspective with glu.RegisterPespective\")\n\t}\n\n\t_Perspective(fovy, aspect, near, far)\n}\n\nfunc LookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ float64) {\n\tif _LookAt == nil {\n\t\tpanic(\"Please register a LookAt with glu.RegisterLookAt\")\n\t}\n\n\t_LookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ)\n}\n\nfunc RegisterPerspective(fn func(fovy, aspect, near, far float64)) ", "output": "{\n\t_Perspective = fn\n}"} {"input": "package next_permutation\n\n\n\n\nfunc reverseSort(nums []int, start, end int) {\n\tif start > end {\n\t\treturn\n\t}\n\tfor i := start; i <= (end+start)/2; i++ {\n\t\tnums[i], nums[start+end-i] = nums[start+end-i], nums[i]\n\t}\n}\n\nfunc nextPermutation(nums []int) ", "output": "{\n\tn := len(nums)\n\tif n < 2 {\n\t\treturn\n\t}\n\tindex := n - 1\n\tfor ; index > 0; index-- {\n\t\tif nums[index-1] < nums[index] {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif index == 0 {\n\t\treverseSort(nums, 0, n-1)\n\t\treturn\n\t}\n\n\tval := nums[index-1]\n\tj := n - 1\n\tfor ; j >= index && nums[j] <= val; j-- {\n\t}\n\tnums[j], nums[index-1] = val, nums[j]\n\n\treverseSort(nums, index, n-1)\n}"} {"input": "package gluster\n\nimport \"testing\"\n\nfunc init() {\n\tExecRunner = TestRunner{}\n}\n\n\n\nfunc TestGetVolumeUsage_LongProject(t *testing.T) {\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project--long_pv1\"}\n\n\tvolInfo, _ := getVolumeUsage(\"gl-project-long-pv1\")\n\n\tequals(t, 49664, volInfo.TotalKiloBytes)\n\tequals(t, 2864, volInfo.UsedKiloBytes)\n}\n\nfunc TestGetVolumeUsage_LongProjectHighNumber(t *testing.T) {\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project--very--very--long_pv20\"}\n\n\tvolInfo, _ := getVolumeUsage(\"gl-project-very-very-long-pv20\")\n\n\tequals(t, 49664, volInfo.TotalKiloBytes)\n\tequals(t, 2864, volInfo.UsedKiloBytes)\n}\n\nfunc TestCheckVolumeUsage_OK(t *testing.T) {\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project_pv1\"}\n\n\terr := checkVolumeUsage(\"gl-project-pv1\", \"20\")\n\tok(t, err)\n}\n\nfunc TestCheckVolumeUsage_Error(t *testing.T) {\n\toutput = []string{\" 49664 49555 /dev/mapper/vg_mylv_project_pv1\"}\n\n\terr := checkVolumeUsage(\"gl-project-pv1\", \"20\")\n\tassert(t, err != nil, \"Should return error as bigger than threshold\")\n}\n\nfunc TestGetVolumeUsage(t *testing.T) ", "output": "{\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project_pv1\"}\n\n\tvolInfo, _ := getVolumeUsage(\"gl-project-pv1\")\n\n\tequals(t, 49664, volInfo.TotalKiloBytes)\n\tequals(t, 2864, volInfo.UsedKiloBytes)\n}"} {"input": "package service\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetServiceIDOKCode int = 200\n\n\ntype GetServiceIDOK struct {\n\n\tPayload *models.Service `json:\"body,omitempty\"`\n}\n\n\n\n\n\nfunc (o *GetServiceIDOK) WithPayload(payload *models.Service) *GetServiceIDOK {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *GetServiceIDOK) SetPayload(payload *models.Service) {\n\to.Payload = payload\n}\n\n\nfunc (o *GetServiceIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\n\nconst GetServiceIDNotFoundCode int = 404\n\n\ntype GetServiceIDNotFound struct {\n}\n\n\nfunc NewGetServiceIDNotFound() *GetServiceIDNotFound {\n\n\treturn &GetServiceIDNotFound{}\n}\n\n\nfunc (o *GetServiceIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc NewGetServiceIDOK() *GetServiceIDOK ", "output": "{\n\n\treturn &GetServiceIDOK{}\n}"} {"input": "package lock\n\nimport (\n\t\"testing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\n\n\n\ntype LockSuite struct{}\n\nvar _ = Suite(&LockSuite{})\n\nfunc (s *LockSuite) TestLock(c *C) {\n\tvar lock1 RWMutex\n\tlock1.Lock()\n\tlock1.Unlock()\n\n\tlock1.RLock()\n\tlock1.RLock()\n\tlock1.RUnlock()\n\tlock1.RUnlock()\n\n\tvar lock2 Mutex\n\tlock2.Lock()\n\tlock2.Unlock()\n}\n\nfunc (s *LockSuite) TestDebugLock(c *C) {\n\tvar lock1 RWMutexDebug\n\tlock1.Lock()\n\tlock1.Unlock()\n\n\tlock1.RLock()\n\tlock1.RLock()\n\tlock1.RUnlock()\n\tlock1.RUnlock()\n\n\tvar lock2 MutexDebug\n\tlock2.Lock()\n\tlock2.Unlock()\n}\n\nfunc Test(t *testing.T) ", "output": "{\n\tTestingT(t)\n}"} {"input": "package cgotest\n\n\nimport \"C\"\nimport \"testing\"\n\n\n\nfunc test5740(t *testing.T) ", "output": "{\n\tif v := C.test5740a() + C.test5740b(); v != 5 {\n\t\tt.Errorf(\"expected 5, got %v\", v)\n\t}\n}"} {"input": "package networkloadbalancer\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ChangeNetworkLoadBalancerCompartmentRequest struct {\n\n\tNetworkLoadBalancerId *string `mandatory:\"true\" contributesTo:\"path\" name:\"networkLoadBalancerId\"`\n\n\tChangeNetworkLoadBalancerCompartmentDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype ChangeNetworkLoadBalancerCompartmentResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ChangeNetworkLoadBalancerCompartmentResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ChangeNetworkLoadBalancerCompartmentResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/kelda/kelda/db\"\n\ttesterUtil \"github.com/kelda/kelda/integration-tester/util\"\n\t\"github.com/kelda/kelda/util\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\n\n\n\nfunc TestInfrastructureSetup(t *testing.T) ", "output": "{\n\tclnt, err := testerUtil.GetDefaultDaemonClient()\n\tassert.NoError(t, err)\n\n\tbp, err := testerUtil.GetCurrentBlueprint(clnt)\n\tassert.NoError(t, err)\n\n\tmachinesReady := func() bool {\n\t\tmachines, err := clnt.QueryMachines()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Failed to list machines:\", err)\n\t\t\treturn false\n\t\t}\n\n\t\tfor _, m := range machines {\n\t\t\tif m.Status != db.Connected {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn len(machines) == len(bp.Machines)\n\t}\n\terr = util.BackoffWaitFor(machinesReady, 30*time.Second, 10*time.Minute)\n\tassert.NoError(t, err, \"Not all machines in the infrastructure connected \"+\n\t\t\"back to the daemon. Any tests relying on all the machines will \"+\n\t\t\"likely fail\")\n}"} {"input": "package protocol\n\nimport (\n\t\"encoding/binary\"\n\t\"io\"\n)\n\n\n\ntype Floor struct {\n\tProtocolIdentifier []byte\n\tAddressData []byte\n}\n\n\nfunc (f Floor) WriteTo(w io.Writer) (n int64, err error) {\n\tbuf := make([]byte, f.EncodedLength())\n\tf.Marshal(buf)\n\tn32, err := w.Write(buf)\n\treturn int64(n32), err\n}\n\n\n\nfunc (f Floor) Marshal(p []byte) {\n\tcopyWithLength(f.ProtocolIdentifier, p) \n\tp = p[2+len(f.ProtocolIdentifier):]\n\tcopyWithLength(f.AddressData, p) \n}\n\n\nfunc (f Floor) EncodedLength() int {\n\treturn 4 + len(f.ProtocolIdentifier) + len(f.AddressData)\n}\n\n\n\nfunc copyWithLength(from []byte, to []byte) ", "output": "{\n\tbinary.LittleEndian.PutUint16(to[0:2], uint16(len(from)))\n\tcopy(to[2:], from)\n}"} {"input": "package api\n\ntype Capture struct {\n\tProbePath string `json:\"ProbePath,omitempty\"`\n\tBPFFilter string `json:\"BPFFilter,omitempty\"`\n}\n\ntype CaptureHandler struct {\n}\n\n\n\nfunc (c *CaptureHandler) New() ApiResource {\n\treturn &Capture{}\n}\n\nfunc (c *CaptureHandler) Name() string {\n\treturn \"capture\"\n}\n\nfunc (c *Capture) ID() string {\n\treturn c.ProbePath\n}\n\nfunc NewCapture(probePath string, bpfFilter string) *Capture ", "output": "{\n\treturn &Capture{\n\t\tProbePath: probePath,\n\t\tBPFFilter: bpfFilter,\n\t}\n}"} {"input": "package jsonutil\n\nimport (\n\t\"github.com/buger/jsonparser\"\n\t\"strconv\"\n)\n\nfunc GetString(data []byte, keys ...string) (string, error) {\n\treturn jsonparser.GetString(data, keys...)\n}\n\nfunc MustGetString(data []byte, keys ...string) string {\n\ts, err := GetString(data, keys...)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s\n}\n\n\n\nfunc MustGetFloat(data []byte, keys ...string) float64 {\n\tf, err := GetFloat(data, keys...)\n\tif err != nil {\n\t\treturn 0.0\n\t}\n\treturn f\n}\n\nfunc GetInt(data []byte, keys ...string) (int64, error) {\n\treturn jsonparser.GetInt(data, keys...)\n}\n\nfunc MustGetInt(data []byte, keys ...string) int64 {\n\ti, err := GetInt(data, keys...)\n\tif err != nil {\n\t\tif s := MustGetString(data, keys...); len(s) == 0 {\n\t\t\treturn 0\n\t\t} else if i, err = strconv.ParseInt(s, 10, 64); err != nil {\n\t\t\treturn 0\n\t\t}\n\t}\n\treturn i\n}\n\nfunc GetBoolean(data []byte, keys ...string) (bool, error) {\n\treturn jsonparser.GetBoolean(data, keys...)\n}\n\nfunc MustGetBoolean(data []byte, keys ...string) bool {\n\tb, err := GetBoolean(data, keys...)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn b\n}\n\nfunc GetFloat(data []byte, keys ...string) (float64, error) ", "output": "{\n\treturn jsonparser.GetFloat(data, keys...)\n}"} {"input": "package devutils\n\n\n\n\nfunc GetMessage() string ", "output": "{\n\treturn `{\n\t\t\t\"id\":\"58dc12e993179a0012a592dc\",\n\t\t\t\"project\":\"RepoSizeTest\",\n\t\t\t\"enginename\":\"Godot\",\n\t\t\t\"engineversion\":\"2.1\",\n\t\t\t\"engineplatform\":\"PC\",\n\t\t\t\"repotype\":\"Git\",\n\t\t\t\"repourl\":\n\t\t\t\"https://github.com/dirty-casuals/Calamity.git\",\n\t\t\t\"buildowner\":\"herman.rogers@gmail.com\"\n\t\t}`\n}"} {"input": "package constants\n\nimport (\n\t\"GoVM/chapter5-instructions/base\"\n\t\"GoVM/chapter4-rtdt\"\n)\n\n\ntype BIPUSH struct {\n\tval int8\n}\n\nfunc (self *BIPUSH) FetchOperands(reader *base.BytecodeReader) {\n\tself.val = reader.ReadInt8()\n}\n\nfunc (self *BIPUSH) Execute(frame *chapter4_rtdt.Frame) {\n\ti := int32(self.val)\n\tframe.OperandStack().PushInt(i)\n}\n\n\ntype SIPUSH struct {\n\tval int16\n}\n\nfunc (self *SIPUSH) FetchOperands(reader *base.BytecodeReader) {\n\tself.val = reader.ReadInt16()\n}\n\n\n\nfunc (self *SIPUSH) Execute(frame *chapter4_rtdt.Frame) ", "output": "{\n\ti := int32(self.val)\n\tframe.OperandStack().PushInt(i)\n}"} {"input": "package filesystem\n\nimport (\n\t\"net/http\"\n\t\"path/filepath\"\n)\n\n\n\nfunc newNative(directory string) (http.Handler, error) ", "output": "{\n\tdir, err := filepath.Abs(directory)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn http.FileServer(http.Dir(dirPath(dir))), nil\n}"} {"input": "package keytransform\n\nimport ds \"github.com/ipfs/go-datastore\"\n\n\ntype Pair struct {\n\tConvert KeyMapping\n\tInvert KeyMapping\n}\n\nfunc (t *Pair) ConvertKey(k ds.Key) ds.Key {\n\treturn t.Convert(k)\n}\n\n\n\nvar _ KeyTransform = (*Pair)(nil)\n\n\n\n\n\n\ntype PrefixTransform struct {\n\tPrefix ds.Key\n}\n\n\nfunc (p PrefixTransform) ConvertKey(k ds.Key) ds.Key {\n\treturn p.Prefix.Child(k)\n}\n\n\nfunc (p PrefixTransform) InvertKey(k ds.Key) ds.Key {\n\tif p.Prefix.String() == \"/\" {\n\t\treturn k\n\t}\n\n\tif !p.Prefix.IsAncestorOf(k) {\n\t\tpanic(\"expected prefix not found\")\n\t}\n\n\ts := k.String()[len(p.Prefix.String()):]\n\treturn ds.RawKey(s)\n}\n\nvar _ KeyTransform = (*PrefixTransform)(nil)\n\nfunc (t *Pair) InvertKey(k ds.Key) ds.Key ", "output": "{\n\treturn t.Invert(k)\n}"} {"input": "package dfa\n\nimport (\n\t\"fmt\"\n\t\"unicode\"\n)\n\nfunc charClass(name string) (m *M, err error) {\n\tms := []*M{}\n\terr = eachRangeInCharClass(name, func(lo, hi rune) {\n\t\tms = append(ms, Between(lo, hi))\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm, err = orMany(ms)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn m.minimize()\n}\n\n\nfunc eachRangeWithStride(lo, hi, stride rune, visit func(lo, hi rune)) {\n\tif stride == 1 {\n\t\tvisit(lo, hi)\n\t} else {\n\t\tfor c := lo; c <= hi; c += stride {\n\t\t\tvisit(c, c)\n\t\t}\n\t}\n}\n\nfunc eachRangeInCharClass(name string, visit func(lo, hi rune)) error ", "output": "{\n\ttable := unicode.Categories[name]\n\tif table == nil {\n\t\ttable = unicode.Scripts[name]\n\t\tif table == nil {\n\t\t\treturn fmt.Errorf(\"character class %s not exists\", name)\n\t\t}\n\t}\n\n\tfor _, xr := range table.R16 {\n\t\teachRangeWithStride(rune(xr.Lo), rune(xr.Hi), rune(xr.Stride), visit)\n\t}\n\tfor _, xr := range table.R32 {\n\t\teachRangeWithStride(rune(xr.Lo), rune(xr.Hi), rune(xr.Stride), visit)\n\t}\n\treturn nil\n}"} {"input": "package data\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\n\ntype Art struct {\n\tID int\n\tFileSize int64 `db:\"file_size\"`\n\tFileName string `db:\"file_name\"`\n\tLastModified int64 `db:\"last_modified\"`\n}\n\n\nfunc (a *Art) Delete() error {\n\treturn DB.DeleteArt(a)\n}\n\n\nfunc (a *Art) Load() error {\n\treturn DB.LoadArt(a)\n}\n\n\nfunc (a *Art) Save() error {\n\treturn DB.SaveArt(a)\n}\n\n\n\n\nfunc (a Art) Stream() (io.ReadSeeker, error) ", "output": "{\n\treturn os.Open(a.FileName)\n}"} {"input": "package comment\n\nimport (\n\t\"time\"\n\n\t\"github.com/google/go-github/github\"\n)\n\n\n\ntype Pinger struct {\n\tkeyword string \n\tdescription string \n\ttimePeriod time.Duration \n\tmaxCount int \n}\n\n\nfunc NewPinger(keyword string) *Pinger {\n\treturn &Pinger{\n\t\tkeyword: keyword,\n\t}\n}\n\n\nfunc (p *Pinger) SetDescription(description string) *Pinger {\n\tp.description = description\n\n\treturn p\n}\n\n\nfunc (p *Pinger) SetTimePeriod(timePeriod time.Duration) *Pinger {\n\tp.timePeriod = timePeriod\n\n\treturn p\n}\n\n\nfunc (p *Pinger) SetMaxCount(maxCount int) *Pinger {\n\tp.maxCount = maxCount\n\n\treturn p\n}\n\n\n\n\n\nfunc (p *Pinger) IsMaxReached(comments []*github.IssueComment, startDate *time.Time) bool {\n\tif startDate == nil {\n\t\tstartDate = &time.Time{}\n\t}\n\treturn p.isMaxReached(FilterComments(\n\t\tcomments,\n\t\tAnd([]Matcher{\n\t\t\tCreatedAfter(*startDate),\n\t\t\tMungerNotificationName(p.keyword),\n\t\t}),\n\t))\n}\n\nfunc (p *Pinger) isMaxReached(pings FilteredComments) bool {\n\treturn p.maxCount != 0 && len(pings) >= p.maxCount\n}\n\nfunc (p *Pinger) shouldPingNow(pings FilteredComments, startDate *time.Time) bool {\n\tlastEvent := startDate\n\n\tif len(pings) != 0 {\n\t\tlastEvent = pings[len(pings)-1].CreatedAt\n\t}\n\n\treturn time.Since(*lastEvent) > p.timePeriod\n}\n\nfunc (p *Pinger) PingNotification(comments []*github.IssueComment, who string, startDate *time.Time) *Notification ", "output": "{\n\tif startDate == nil {\n\t\tstartDate = &time.Time{}\n\t}\n\n\tpings := FilterComments(\n\t\tcomments,\n\t\tAnd([]Matcher{\n\t\t\tCreatedAfter(*startDate),\n\t\t\tMungerNotificationName(p.keyword),\n\t\t}),\n\t)\n\n\tif p.isMaxReached(pings) {\n\t\treturn nil\n\t}\n\n\tif !p.shouldPingNow(pings, startDate) {\n\t\treturn nil\n\t}\n\n\treturn &Notification{\n\t\tName: p.keyword,\n\t\tArguments: who,\n\t\tContext: p.description,\n\t}\n}"} {"input": "package main\n\nimport ()\n\ntype channel struct {\n\tpath string\n\tqueue queue\n\tconnections connections\n\th *hub\n}\n\ntype connections map[*connection]interface {\n}\n\nfunc (c *channel) run() {\n\tincr(\"channels\", 1)\n\tdefer c.stop()\n\tfor cmd := range c.queue {\n\t\tswitch cmd.cmd {\n\t\tcase SUBSCRIBE:\n\t\t\tc.subscribe(cmd.conn)\n\t\tcase UNSUBSCRIBE:\n\t\t\tc.unsubscribe(cmd.conn)\n\t\t\tif len(c.connections) == 0 {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase PUBLISH:\n\t\t\tc.publish(cmd.text)\n\t\tcase BROADCAST:\n\t\t\tc.broadcast(cmd.text)\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (c *channel) stop() {\n\tclose(c.queue)\n\tc.h.queue <- command{cmd: REMOVE, path: c.path}\n\tdecr(\"channels\", 1)\n}\n\n\n\nfunc (c *channel) unsubscribe(conn *connection) {\n\tif _, ok := c.connections[conn]; ok {\n\t\tclose(conn.send)\n\t\tdelete(c.connections, conn)\n\t}\n}\n\nfunc (c *channel) publish(text []byte) {\n\tif len(text) == 0 {\n\t\treturn\n\t}\n\tc.h.queue <- command{cmd: PUBLISH, path: c.path, text: text}\n}\n\nfunc (c *channel) broadcast(text []byte) {\n\tif len(text) == 0 {\n\t\treturn\n\t}\n\tfor conn := range c.connections {\n\t\tselect {\n\t\tcase conn.send <- text:\n\t\tdefault:\n\t\t\tc.unsubscribe(conn)\n\t\t}\n\t}\n}\n\nfunc (c *channel) subscribe(conn *connection) ", "output": "{\n\tc.connections[conn] = nil\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/mdlayher/p4/cli\"\n)\n\n\nconst (\n\tcmdPP = \"pp\"\n)\n\nfunc main() {\n\tflag.Parse()\n\tlog.SetFlags(0)\n\tlog.SetOutput(os.Stderr)\n\n\tif len(flag.Args()) == 0 {\n\t\tfatalf(\"no arguments specified\")\n\t}\n\n\tvar exec cli.Executor\n\n\tcmd := flag.Arg(0)\n\tswitch cmd {\n\tcase cmdPP:\n\t\texec = cli.NewPreprocessor()\n\tdefault:\n\t\tfatalf(\"unknown command: %q\", cmd)\n\t}\n\n\tw, r := os.Stdout, os.Stdin\n\n\tif err := exec.Execute(w, r); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\nfunc usage() {\n\tlf := log.Printf\n\n\tlf(\"p4 is a tool for managing P4 source code.\")\n\tlf(\"\")\n\tlf(\"Usage:\")\n\tlf(\" p4 command [arguments]\")\n\tlf(\"\")\n\tlf(\"Commands:\")\n\tlf(\" p4 %s invoke a preprocessor on P4 source code read from stdin\", cmdPP)\n\tlf(\"\")\n}\n\n\n\n\n\nfunc fatalf(format string, a ...interface{}) ", "output": "{\n\tusage()\n\tlog.Fatalf(\"p4: \"+format, a...)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype dumpXLIFF struct {\n\tinFile string\n}\n\nfunc init() {\n\tregisteredConverters[\"dump\"] = new(dumpXLIFF)\n}\n\n\n\nfunc (d *dumpXLIFF) ParseArgs(base string, args []string) error {\n\tvar fs = flag.NewFlagSet(base+\" dump\", flag.ExitOnError)\n\tfs.StringVar(&d.inFile, \"in\", \"\", \"infile\")\n\treturn fs.Parse(args)\n}\n\nfunc (d *dumpXLIFF) Prepare() error {\n\treturn nil\n}\n\nfunc (d *dumpXLIFF) Convert(w io.Writer) error {\n\n\tvar doc, err = xliffFromFile(d.inFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, file := range doc.File {\n\n\t\tfor _, unit := range file.Body.TransUnit {\n\n\t\t\tfmt.Fprintf(w, \"unit %s\\n\", unit.ID)\n\t\t\tfmt.Fprintf(w, \" source: %v\\n\", unit.Source)\n\t\t\tfmt.Fprintf(w, \" target: %v\\n\", unit.Target)\n\n\t\t}\n\t}\n\n\treturn err\n}\n\nfunc (d *dumpXLIFF) Description() string ", "output": "{\n\treturn \"Dumps XLIFF as parsed\"\n}"} {"input": "package apmsynthetics\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetMonitorRequest struct {\n\n\tApmDomainId *string `mandatory:\"true\" contributesTo:\"query\" name:\"apmDomainId\"`\n\n\tMonitorId *string `mandatory:\"true\" contributesTo:\"path\" name:\"monitorId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetMonitorRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request GetMonitorRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request GetMonitorRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetMonitorRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetMonitorResponse struct {\n\n\tRawResponse *http.Response\n\n\tMonitor `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetMonitorResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response GetMonitorResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package reaperlog\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/rifflock/lfshook\"\n\t\"go.mozilla.org/mozlogrus\"\n)\n\nvar config LogConfig\n\ntype LogConfig struct {\n\tExtras bool\n}\n\nfunc EnableExtras() {\n\tconfig.Extras = true\n}\n\nfunc EnableMozlog() {\n\tmozlogrus.Enable(\"Reaper\")\n}\n\nfunc Extras() bool {\n\treturn config.Extras\n}\n\nfunc SetConfig(c *LogConfig) {\n\tconfig = *c\n}\n\nfunc AddLogFile(filename string) {\n\tlog.AddHook(lfshook.NewHook(lfshook.PathMap{\n\t\tlog.DebugLevel: filename,\n\t\tlog.InfoLevel: filename,\n\t\tlog.WarnLevel: filename,\n\t\tlog.ErrorLevel: filename,\n\t\tlog.FatalLevel: filename,\n\t\tlog.PanicLevel: filename,\n\t}))\n}\n\n\n\nfunc Info(format string, args ...interface{}) {\n\tlog.Infof(format, args...)\n}\n\nfunc Warning(format string, args ...interface{}) {\n\tlog.Warningf(format, args...)\n}\n\nfunc Fatal(format string, args ...interface{}) {\n\tlog.Fatalf(format, args...)\n}\n\nfunc Panic(format string, args ...interface{}) {\n\tlog.Panicf(format, args...)\n}\n\nfunc Error(format string, args ...interface{}) {\n\tlog.Errorf(format, args...)\n}\n\nfunc Debug(format string, args ...interface{}) ", "output": "{\n\tlog.Debugf(format, args...)\n}"} {"input": "package application\n\nimport (\n\t\"encoding/base64\"\n\t\"github.com/gorilla/securecookie\"\n\t\"net/http\"\n\t\"testing\"\n)\n\n\nconst cookieName = \"recaptcha\"\nconst testHashKey = \"RovMQmutMbSogUuGQFZYLb37jwgwFNuMR7wrEz9EILQ9W039UHCFlCfkpX1EbecktHA563XX+7clPRinBPeaeQ==\"\nconst testBlockKey = \"+sSXCAbwswiYNqHx4zCuJJTD3hmRQp4f4uJKy+aFL70=\"\n\n\n\nfunc TestNewSecureRecaptchaCookie(t *testing.T) {\n\tsecureRecaptchaCookie1 := NewSecureRecaptchaCookie(cookieName, nil, generateGorillaSecureCookie())\n\tif secureRecaptchaCookie1.Name != cookieName || len(secureRecaptchaCookie1.Value) != 0 {\n\t\tt.Error(\"The new secure cookie based on an empty cookie should have no value\")\n\t}\n\n\tvalidCookie := &http.Cookie{Value: \"Some Value\"}\n\tsecureRecaptchaCookie2 := NewSecureRecaptchaCookie(cookieName, validCookie, generateGorillaSecureCookie())\n\tif secureRecaptchaCookie2.Name != cookieName || len(secureRecaptchaCookie2.Value) == 0 {\n\t\tt.Error(\"The new secure cookie based on a valid cookie should have a value\")\n\t}\n}\n\nfunc TestSecureRecaptchaCookie_Encode(t *testing.T) {\n\tvalidCookie := &http.Cookie{Value: \"Some Value\"}\n\n\tsecureRecaptchaCookie := NewSecureRecaptchaCookie(cookieName, validCookie, generateGorillaSecureCookie())\n\tsecureRecaptchaCookie.Value = secureRecaptchaCookie.Encode(validCookie.Value)\n\n\tif secureRecaptchaCookie.IsValid(validCookie.Value) != true {\n\t\tt.Error(\"The cookie value should have been encoded and decoded correctly\")\n\t}\n}\n\nfunc generateGorillaSecureCookie() *securecookie.SecureCookie ", "output": "{\n\thashKey, _ := base64.StdEncoding.DecodeString(testHashKey)\n\tblockKey, _ := base64.StdEncoding.DecodeString(testBlockKey)\n\treturn securecookie.New(hashKey, blockKey)\n}"} {"input": "package framework\n\n\ntype FieldType uint\n\nconst (\n\tTypeInvalid FieldType = 0\n\tTypeString FieldType = iota\n\tTypeInt\n\tTypeBool\n\tTypeMap\n\n\tTypeDurationSecond\n\n\tTypeSlice\n\n\tTypeStringSlice\n\n\tTypeCommaStringSlice\n\n\tTypeNameString\n)\n\n\n\nfunc (t FieldType) String() string ", "output": "{\n\tswitch t {\n\tcase TypeString:\n\t\treturn \"string\"\n\tcase TypeNameString:\n\t\treturn \"name string\"\n\tcase TypeInt:\n\t\treturn \"int\"\n\tcase TypeBool:\n\t\treturn \"bool\"\n\tcase TypeMap:\n\t\treturn \"map\"\n\tcase TypeDurationSecond:\n\t\treturn \"duration (sec)\"\n\tcase TypeSlice, TypeStringSlice, TypeCommaStringSlice:\n\t\treturn \"slice\"\n\tdefault:\n\t\treturn \"unknown type\"\n\t}\n}"} {"input": "package events\n\nimport (\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/gravitational/teleport/lib/session\"\n)\n\n\n\ntype DiscardAuditLog struct {\n}\n\nfunc (d *DiscardAuditLog) Close() error {\n\treturn nil\n}\n\nfunc (d *DiscardAuditLog) EmitAuditEvent(eventType string, fields EventFields) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionChunk(namespace string, sid session.ID, reader io.Reader) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionSlice(SessionSlice) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\nfunc (d *DiscardAuditLog) GetSessionEvents(namespace string, sid session.ID, after int) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchEvents(fromUTC, toUTC time.Time, query string) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\n\n\n\n\n\ntype discardSessionLogger struct {\n}\n\nfunc (d *discardSessionLogger) LogEvent(fields EventFields) {\n\treturn\n}\n\nfunc (d *discardSessionLogger) Close() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) Finalize() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) WriteChunk(chunk *SessionChunk) (written int, err error) {\n\treturn 0, nil\n}\n\nfunc (d *DiscardAuditLog) SearchSessionEvents(fromUTC time.Time, toUTC time.Time) ([]EventFields, error) ", "output": "{\n\treturn make([]EventFields, 0), nil\n}"} {"input": "package common\n\nimport (\n . \"launchpad.net/gocheck\"\n \"sync\"\n)\n\ntype HealthzSuite struct {\n}\n\nvar _ = Suite(&HealthzSuite{})\n\nfunc (s *HealthzSuite) SetUpTest(c *C) {\n Component = VcapComponent{\n Config: map[string]interface{}{\"ip\": \"localhost\", \"port\": 8080},\n }\n}\n\nfunc (s *HealthzSuite) TearDownTest(c *C) {\n Component = VcapComponent{}\n}\n\n\n\nfunc (s *HealthzSuite) TestJsonMarshal(c *C) ", "output": "{\n healthz := &Healthz{\n LockableObject: &sync.Mutex{},\n }\n bytes, _ := healthz.MarshalJSON()\n c.Assert(string(bytes), Equals, \"{\\\"health\\\":\\\"ok\\\"}\")\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/utils\"\n\nfunc init() {\n\tc := &CmdGetCacheAge{\n\t\tname: \"cache_age\",\n\t\trpcMethod: \"ApierV1.GetCachedItemAge\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetCacheAge struct {\n\tname string\n\trpcMethod string\n\trpcParams *StringWrapper\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetCacheAge) Name() string {\n\treturn self.name\n}\n\n\n\nfunc (self *CmdGetCacheAge) RpcParams() interface{} {\n\tif self.rpcParams == nil {\n\t\tself.rpcParams = &StringWrapper{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetCacheAge) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetCacheAge) RpcResult() interface{} {\n\treturn &utils.CachedItemAge{}\n}\n\nfunc (self *CmdGetCacheAge) RpcMethod() string ", "output": "{\n\treturn self.rpcMethod\n}"} {"input": "package singularity\n\nimport \"github.com/opentable/go-singularity/dtos\"\n\nfunc (client *Client) SkipHealthchecks(requestId string, body *dtos.SingularitySkipHealthchecksRequest) (response *dtos.SingularityRequestParent, err error) {\n\tpathParamMap := map[string]interface{}{\n\t\t\"requestId\": requestId,\n\t}\n\n\tqueryParamMap := map[string]interface{}{}\n\n\tresponse = new(dtos.SingularityRequestParent)\n\terr = client.DTORequest(response, \"PUT\", \"/api/requests/request/{requestId}/skip-healthchecks\", pathParamMap, queryParamMap, body)\n\n\treturn\n}\n\n\n\nfunc (client *Client) DeleteExpiringSkipHealthchecks(requestId string) (response *dtos.SingularityRequestParent, err error) ", "output": "{\n\tpathParamMap := map[string]interface{}{\n\t\t\"requestId\": requestId,\n\t}\n\n\tqueryParamMap := map[string]interface{}{}\n\n\tresponse = new(dtos.SingularityRequestParent)\n\terr = client.DTORequest(response, \"DELETE\", \"/api/requests/request/{requestId}/skip-healthchecks\", pathParamMap, queryParamMap)\n\n\treturn\n}"} {"input": "package validation\n\nimport (\n\t\"strings\"\n\n\t\"github.com/rantuttl/cloudops/apimachinery/pkg/util/validation\"\n\t\"github.com/rantuttl/cloudops/apimachinery/pkg/util/validation/field\"\n)\n\nconst IsNegativeErrorMsg string = `must be greater than or equal to 0`\n\n\n\n\n\n\ntype ValidateNameFunc func(name string, prefix bool) []string\n\n\nfunc NameIsDNSSubdomain(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1123Subdomain(name)\n}\n\n\nfunc NameIsDNSLabel(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1123Label(name)\n}\n\n\n\n\n\n\n\nvar ValidateNamespaceName = NameIsDNSLabel\n\n\n\n\nvar ValidateServiceAccountName = NameIsDNSSubdomain\n\n\n\nfunc maskTrailingDash(name string) string {\n\tif strings.HasSuffix(name, \"-\") {\n\t\treturn name[:len(name)-2] + \"a\"\n\t}\n\treturn name\n}\n\n\nfunc ValidateNonnegativeField(value int64, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif value < 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, value, IsNegativeErrorMsg))\n\t}\n\treturn allErrs\n}\n\nfunc NameIsDNS1035Label(name string, prefix bool) []string ", "output": "{\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1035Label(name)\n}"} {"input": "package rules\n\nimport (\n\t\"regexp\"\n\t\"strings\"\n)\n\n\ntype Checker interface {\n\tCheck(path string) bool\n}\n\n\ntype Rule struct {\n\tRegex bool `json:\"regex\"`\n\tAllow bool `json:\"allow\"`\n\tPath string `json:\"path\"`\n\tRegexp *Regexp `json:\"regexp\"`\n}\n\n\n\n\n\n\ntype Regexp struct {\n\tRaw string `json:\"raw\"`\n\tregexp *regexp.Regexp\n}\n\n\nfunc (r *Regexp) MatchString(s string) bool {\n\tif r.regexp == nil {\n\t\tr.regexp = regexp.MustCompile(r.Raw)\n\t}\n\n\treturn r.regexp.MatchString(s)\n}\n\nfunc (r *Rule) Matches(path string) bool ", "output": "{\n\tif r.Regex {\n\t\treturn r.Regexp.MatchString(path)\n\t}\n\n\treturn strings.HasPrefix(path, r.Path)\n}"} {"input": "package wca\n\nimport (\n\t\"unsafe\"\n)\n\n\n\n\ntype IAudioClient2 struct {\n\tIAudioClient\n}\n\ntype IAudioClient2Vtbl struct {\n\tIAudioClientVtbl\n\tIsOffloadCapable uintptr\n\tSetClientProperties uintptr\n\tGetBufferSizeLimits uintptr\n}\n\nfunc (v *IAudioClient2) VTable() *IAudioClient2Vtbl {\n\treturn (*IAudioClient2Vtbl)(unsafe.Pointer(v.RawVTable))\n}\n\nfunc (v *IAudioClient2) IsOffloadCapable(category uint32, isOffloadCapable *bool) (err error) {\n\terr = ac2IsOffloadCapable(v, category, isOffloadCapable)\n\treturn\n}\n\n\n\nfunc (v *IAudioClient2) GetBufferSizeLimits(wfx *WAVEFORMATEX, isEventDriven bool, minBufferDuration, maxBufferDuration *uint32) (err error) {\n\terr = ac2GetBufferSizeLimits(v, wfx, isEventDriven, minBufferDuration, maxBufferDuration)\n\treturn\n}\n\nfunc (v *IAudioClient2) SetClientProperties(properties *AudioClientProperties) (err error) ", "output": "{\n\terr = ac2SetClientProperties(v, properties)\n\treturn\n}"} {"input": "package asm\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc TestLexer(t *testing.T) {\n\ttests := []struct {\n\t\tinput string\n\t\ttokens []token\n\t}{\n\t\t{\n\t\t\tinput: \";; this is a comment\",\n\t\t\ttokens: []token{{typ: lineStart}, {typ: eof}},\n\t\t},\n\t\t{\n\t\t\tinput: \"0x12345678\",\n\t\t\ttokens: []token{{typ: lineStart}, {typ: number, text: \"0x12345678\"}, {typ: eof}},\n\t\t},\n\t\t{\n\t\t\tinput: \"0x123ggg\",\n\t\t\ttokens: []token{{typ: lineStart}, {typ: number, text: \"0x123\"}, {typ: element, text: \"ggg\"}, {typ: eof}},\n\t\t},\n\t\t{\n\t\t\tinput: \"12345678\",\n\t\t\ttokens: []token{{typ: lineStart}, {typ: number, text: \"12345678\"}, {typ: eof}},\n\t\t},\n\t\t{\n\t\t\tinput: \"123abc\",\n\t\t\ttokens: []token{{typ: lineStart}, {typ: number, text: \"123\"}, {typ: element, text: \"abc\"}, {typ: eof}},\n\t\t},\n\t\t{\n\t\t\tinput: \"0123abc\",\n\t\t\ttokens: []token{{typ: lineStart}, {typ: number, text: \"0123\"}, {typ: element, text: \"abc\"}, {typ: eof}},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\ttokens := lexAll(test.input)\n\t\tif !reflect.DeepEqual(tokens, test.tokens) {\n\t\t\tt.Errorf(\"input %q\\ngot: %+v\\nwant: %+v\", test.input, tokens, test.tokens)\n\t\t}\n\t}\n}\n\nfunc lexAll(src string) []token ", "output": "{\n\tch := Lex(\"test.asm\", []byte(src), false)\n\n\tvar tokens []token\n\tfor i := range ch {\n\t\ttokens = append(tokens, i)\n\t}\n\treturn tokens\n}"} {"input": "package mongo\n\nimport (\n\t\"fmt\"\n\t\"labix.org/v2/mgo\"\n\t\"testing\"\n)\n\nvar (\n\ttaro = &User{Name: \"Taro\", Age: 20}\n\thanako = &User{Name: \"Hanako\", Age: 22}\n)\n\n\nfunc init() {\n\tsession, err := mgo.Dial(\"localhost\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\tc := session.DB(\"droneTest\").C(\"users\")\n\tc.DropCollection()\n\terr = c.Insert(taro)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = c.Insert(hanako)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\n\n\nfunc TestFind(t *testing.T) ", "output": "{\n\tuser, err := Find(taro.Name)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif user.Name != taro.Name || user.Age != taro.Age {\n\t\tt.Error(fmt.Sprintf(\"検索結果が不正です。[期待値: %+v][実際: %+v]\", taro, user))\n\t}\n\n\tuser, err = Find(\"X\")\n\tif err == nil || err.Error() != \"not found\" {\n\t\tt.Error(\"検索結果が不正です。検索結果が存在します。\")\n\t}\n}"} {"input": "package email\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"io\"\n\t\"net/textproto\"\n)\n\n\n\n\n\n\n\n\nfunc (m *Message) DeliveryStatusMessageDNS() (Header, error) {\n\tif !m.HasDeliveryStatusMessage() {\n\t\treturn Header{}, errors.New(\"Message does not have media content of type message/delivery-status\")\n\t}\n\treturn m.SubMessage.Header, nil\n}\n\n\n\nfunc (m *Message) DeliveryStatusRecipientDNS() ([]Header, error) {\n\trecipientDNS := make([]Header, 0, 1)\n\tif !m.HasDeliveryStatusMessage() {\n\t\treturn recipientDNS, errors.New(\"Message does not have media content of type message/delivery-status\")\n\t}\n\tvar err error\n\tvar recipientHeaders textproto.MIMEHeader\n\ttp := textproto.NewReader(bufio.NewReader(bytes.NewReader(m.SubMessage.Body)))\n\tfor err != io.EOF {\n\t\trecipientHeaders, err = tp.ReadMIMEHeader()\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, err\n\t\t}\n\t\trecipientDNS = append(recipientDNS, Header(recipientHeaders))\n\t}\n\treturn recipientDNS, nil\n}\n\nfunc (m *Message) HasDeliveryStatusMessage() bool ", "output": "{\n\tcontentType, _, err := m.Header.ContentType()\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn contentType == \"message/delivery-status\" && m.SubMessage != nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\n\n\nfunc NewWorker(id int, workerQueue chan chan WorkRequest) Worker {\n\tworker := Worker{\n\t\tID: id,\n\t\tWork: make(chan WorkRequest),\n\t\tWorkerQueue: workerQueue,\n\t\tQuitChan: make(chan bool)}\n\n\treturn worker\n}\n\ntype Worker struct {\n\tID int\n\tWork chan WorkRequest\n\tWorkerQueue chan chan WorkRequest\n\tQuitChan chan bool\n}\n\n\n\n\n\n\n\n\nfunc (w *Worker) Stop() {\n\tgo func() {\n\t\tw.QuitChan <- true\n\t}()\n}\n\nfunc Workers(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"POST\" {\n\t\tw.Header().Set(\"Allow\", \"POST\")\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\tworkerCount := r.FormValue(\"workers\")\n\n\ti, err := strconv.Atoi(workerCount)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t} else if i > 0 {\n\t\tfmt.Println(\"Adjusting worker count\")\n\t\tAdjustWorkers(i)\n\t\tw.WriteHeader(http.StatusOK)\n\t} else {\n\t\thttp.Error(w, \"Worker Count must be positive\", http.StatusBadRequest)\n\t}\n\n\treturn\n}\n\nfunc (w *Worker) Start() ", "output": "{\n\tgo func() {\n\t\tfor {\n\t\t\tw.WorkerQueue <- w.Work\n\n\t\t\tselect {\n\t\t\tcase work := <-w.Work:\n\t\t\t\tfmt.Printf(\"worker%d: Received work request %s\\n\", w.ID, work.URL)\n\n\t\t\t\tstatus, err := MakeRequest(work)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Printf(\"%s: %s\\n\", work.URL, err.Error())\n\t\t\t\t}\n\n\t\t\t\tfmt.Printf(\"worker%d: %s: %s\\n\", w.ID, status, work.URL)\n\n\t\t\t\tfmt.Println(\"removing from wait group\")\n\t\t\t\tBatchWaitGroup.Done()\n\t\t\t\ttime.Sleep(time.Duration(*PostRequestPause) * time.Second)\n\n\t\t\tcase <-w.QuitChan:\n\t\t\t\tfmt.Printf(\"worker%d stopping\\n\", w.ID)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}()\n}"} {"input": "package shared\n\ntype RunTaskError struct {\n\tMessage string\n}\n\n\n\nfunc (e RunTaskError) Translate(translate func(string, ...interface{}) string) string {\n\treturn translate(e.Error(), map[string]interface{}{\n\t\t\"CloudControllerMessage\": e.Message,\n\t})\n}\n\ntype ClientTargetError struct {\n\tMessage string\n}\n\nfunc (e ClientTargetError) Error() string {\n\treturn \"{{.Message}}\\nNote that this command requires CF API version 3.0.0+.\"\n}\n\nfunc (e ClientTargetError) Translate(translate func(string, ...interface{}) string) string {\n\treturn translate(e.Error(), map[string]interface{}{\n\t\t\"Message\": e.Message,\n\t})\n}\n\nfunc (e RunTaskError) Error() string ", "output": "{\n\treturn \"Error running task: {{.CloudControllerMessage}}\"\n}"} {"input": "package disk\n\n\n\n\n\n\n\ntype Info struct {\n\tTotal uint64\n\tFree uint64\n\tUsed uint64\n\tFiles uint64\n\tFfree uint64\n\tFSType string\n}\n\n\n\n\nfunc SameDisk(di1, di2 Info) bool ", "output": "{\n\tif di1.Total != di2.Total {\n\t\treturn false\n\t}\n\n\tif di1.Files != di2.Files {\n\t\treturn false\n\t}\n\n\treturn di1.Used == di2.Used && di1.Free == di2.Free\n}"} {"input": "package web\n\nimport (\n\t\"strings\"\n\n\t\"github.com/gopherjs/gopherjs/js\"\n)\n\nfunc IsNodeJS() bool {\n\treturn js.Global.Get(\"require\") != js.Undefined\n}\n\nfunc IsBrowser() bool {\n\treturn !IsNodeJS()\n}\n\n\n\nfunc IsAndroidChrome() bool {\n\tua := js.Global.Get(\"navigator\").Get(\"userAgent\").String()\n\tif !strings.Contains(ua, \"Android\") {\n\t\treturn false\n\t}\n\tif !strings.Contains(ua, \"Chrome\") {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc IsMobileBrowser() bool {\n\treturn IsIOSSafari() || IsAndroidChrome()\n}\n\nfunc IsIOSSafari() bool ", "output": "{\n\tua := js.Global.Get(\"navigator\").Get(\"userAgent\").String()\n\tif !strings.Contains(ua, \"iPhone\") {\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\ntype MockConn struct {\n\tServerReader *io.PipeReader\n\tServerWriter *io.PipeWriter\n\tClientReader *io.PipeReader\n\tClientWriter *io.PipeWriter\n}\n\nfunc (c MockConn) Close() error {\n\tif err := c.ServerWriter.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := c.ServerReader.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc (c MockConn) Read(data []byte) (n int, err error) { return c.ServerReader.Read(data) }\nfunc (c MockConn) Write(data []byte) (n int, err error) { return c.ServerWriter.Write(data) }\n\nfunc (c MockConn) LocalAddr() net.Addr {\n\treturn &net.TCPAddr{\n\t\tIP: net.ParseIP(\"127.0.0.1:2342\"),\n\t\tPort: 2342,\n\t\tZone: \"\",\n\t}\n}\n\nfunc (c MockConn) RemoteAddr() net.Addr {\n\treturn &net.TCPAddr{\n\t\tIP: net.ParseIP(\"127.0.0.1:2342\"),\n\t\tPort: 2342,\n\t\tZone: \"\",\n\t}\n}\n\nfunc (c MockConn) SetDeadline(t time.Time) error { return nil }\nfunc (c MockConn) SetReadDeadline(t time.Time) error { return nil }\nfunc (c MockConn) SetWriteDeadline(t time.Time) error { return nil }\n\nfunc NewMockConn() MockConn {\n\tserverRead, clientWrite := io.Pipe()\n\tclientRead, serverWrite := io.Pipe()\n\n\treturn MockConn{\n\t\tServerReader: serverRead,\n\t\tServerWriter: serverWrite,\n\t\tClientReader: clientRead,\n\t\tClientWriter: clientWrite,\n\t}\n}\n\nfunc (c MockConn) CloseClient() error ", "output": "{\n\tif err := c.ClientWriter.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := c.ClientReader.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package intsort\n\ntype Uints []uint\n\nfunc (s Uints) Len() int {\n\treturn len(s)\n}\n\n\n\nfunc (s Uints) Swap(i int, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\nfunc (s Uints) Less(i int, j int) bool ", "output": "{\n\treturn s[i] < s[j]\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\nfunc main() {\n\tt := time.Now()\n\tlinks := make([]string, 50)\n\tfor i := 0; i < 50; i++ {\n\t\tlinks[i] = fmt.Sprintf(\"%d\", i+1)\n\t}\n\n\tlinkChan := make(chan string, 10) \n\twg := new(sync.WaitGroup)\n\n\tfor i := 0; i < 10; i++ {\n\t\twg.Add(1)\n\t\tgo worker(linkChan, wg)\n\t}\n\n\tfor _, link := range links {\n\t\tlinkChan <- link\n\t}\n\n\tclose(linkChan)\n\tfmt.Println(\"Waiting\")\n\twg.Wait()\n\tfmt.Println(\"Total time\", time.Since(t))\n}\n\nfunc worker(linkChan chan string, wg *sync.WaitGroup) ", "output": "{\n\tdefer wg.Done()\n\n\tfor url := range linkChan {\n\t\ttime.Sleep(1 * time.Second)\n\t\tfmt.Printf(\"Done processing link #%s\\n\", url)\n\t}\n\n}"} {"input": "package fileutil\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\ntype unixLock struct {\n\tf *os.File\n}\n\nfunc (l *unixLock) Release() error {\n\tif err := l.set(false); err != nil {\n\t\treturn err\n\t}\n\treturn l.f.Close()\n}\n\nfunc (l *unixLock) set(lock bool) error {\n\tflock := syscall.Flock_t{\n\t\tType: syscall.F_UNLCK,\n\t\tStart: 0,\n\t\tLen: 0,\n\t\tWhence: 1,\n\t}\n\tif lock {\n\t\tflock.Type = syscall.F_WRLCK\n\t}\n\treturn syscall.FcntlFlock(l.f.Fd(), syscall.F_SETLK, &flock)\n}\n\n\n\nfunc newLock(fileName string) (Releaser, error) ", "output": "{\n\tf, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tl := &unixLock{f}\n\terr = l.set(true)\n\tif err != nil {\n\t\tf.Close()\n\t\treturn nil, err\n\t}\n\treturn l, nil\n}"} {"input": "package operations\n\n\n\nimport (\n\t\"github.com/denkhaus/bitshares/types\"\n\t\"github.com/denkhaus/bitshares/util\"\n\t\"github.com/juju/errors\"\n)\n\nfunc init() {\n\ttypes.OperationMap[types.OperationTypeCommitteeMemberCreate] = func() types.Operation {\n\t\top := &CommitteeMemberCreateOperation{}\n\t\treturn op\n\t}\n}\n\ntype CommitteeMemberCreateOperation struct {\n\ttypes.OperationFee\n\tCommitteeMemberAccount types.AccountID `json:\"committee_member_account\"`\n\tURL types.String `json:\"url\"`\n}\n\nfunc (p CommitteeMemberCreateOperation) Type() types.OperationType {\n\treturn types.OperationTypeCommitteeMemberCreate\n}\n\n\n\nfunc (p CommitteeMemberCreateOperation) Marshal(enc *util.TypeEncoder) error ", "output": "{\n\tif err := enc.Encode(int8(p.Type())); err != nil {\n\t\treturn errors.Annotate(err, \"encode OperationType\")\n\t}\n\tif err := enc.Encode(p.Fee); err != nil {\n\t\treturn errors.Annotate(err, \"encode Fee\")\n\t}\n\tif err := enc.Encode(p.CommitteeMemberAccount); err != nil {\n\t\treturn errors.Annotate(err, \"encode CommitteeMemberAccount\")\n\t}\n\tif err := enc.Encode(p.URL); err != nil {\n\t\treturn errors.Annotate(err, \"encode URL\")\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/ying32/govcl/vcl\"\n\t\"github.com/ying32/govcl/vcl/rtl\"\n\t\"github.com/ying32/govcl/vcl/types\"\n\t\"github.com/ying32/govcl/vcl/types/keys\"\n\t\"github.com/ying32/govcl/vcl/types/messages\"\n\t\"github.com/ying32/govcl/vcl/win\"\n)\n\n\ntype TForm1Fields struct {\n\thotKeyId types.ATOM\n}\n\nfunc (f *TForm1) OnFormCreate(sender vcl.IObject) {\n\tf.SetCaption(\"Press Ctrl+F1\")\n\tf.ScreenCenter()\n\tf.hotKeyId = win.GlobalAddAtom(\"HotKeyId\") - 0xC000\n\tshift := types.NewSet(types.SsCtrl)\n\tif !win.RegisterHotKey(f.Handle(), int32(f.hotKeyId), rtl.ShiftStateToWord(shift), keys.VkF1) {\n\t\tvcl.ShowMessage(\"注册热键失败。\")\n\t}\n\n}\n\nfunc (f *TForm1) OnFormDestroy(sender vcl.IObject) {\n\tif f.hotKeyId > 0 {\n\t\twin.UnregisterHotKey(f.Handle(), int32(f.hotKeyId))\n\t\twin.GlobalDeleteAtom(f.hotKeyId)\n\t}\n}\n\n\n\nfunc (f *TForm1) OnFormWndProc(msg *types.TMessage) ", "output": "{\n\n\tf.InheritedWndProc(msg)\n\tif msg.Msg == messages.WM_HOTKEY {\n\t\tif msg.WParam == types.WPARAM(f.hotKeyId) {\n\t\t\tvcl.ShowMessage(\"按下了Ctrl+F1\")\n\t\t}\n\t}\n}"} {"input": "package log\n\nimport \"gopkg.in/inconshreveable/log15.v2\"\n\nvar (\n\tLogger log15.Logger\n)\n\nfunc init() {\n\tLogger = log15.New()\n\tLogger.SetHandler(log15.DiscardHandler())\n}\n\n\n\nfunc Interactive() {\n\tLogger.SetHandler(log15.MultiHandler(\n\t\tlog15.LvlFilterHandler(\n\t\t\tlog15.LvlError,\n\t\t\tlog15.StderrHandler)))\n}\n\n\n\nfunc Info(msg string, ctx ...interface{}) { Logger.Info(msg, ctx...) }\nfunc Warn(msg string, ctx ...interface{}) { Logger.Warn(msg, ctx...) }\nfunc Error(msg string, ctx ...interface{}) { Logger.Error(msg, ctx...) }\nfunc Crit(msg string, ctx ...interface{}) { Logger.Crit(msg, ctx...) }\n\nfunc Debug(msg string, ctx ...interface{}) ", "output": "{ Logger.Debug(msg, ctx...) }"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n\tgoahttp \"goa.design/goa/v3/http\"\n\tcli \"goa.design/plugins/v3/goakit/examples/calc/gen/http/cli/calc\"\n)\n\nfunc doHTTP(scheme, host string, timeout int, debug bool) (endpoint.Endpoint, interface{}, error) {\n\tvar (\n\t\tdoer goahttp.Doer\n\t)\n\t{\n\t\tdoer = &http.Client{Timeout: time.Duration(timeout) * time.Second}\n\t\tif debug {\n\t\t\tdoer = goahttp.NewDebugDoer(doer)\n\t\t}\n\t}\n\n\treturn cli.ParseEndpoint(\n\t\tscheme,\n\t\thost,\n\t\tdoer,\n\t\tgoahttp.RequestEncoder,\n\t\tgoahttp.ResponseDecoder,\n\t\tdebug,\n\t)\n}\n\nfunc httpUsageCommands() string {\n\treturn cli.UsageCommands()\n}\n\n\n\nfunc httpUsageExamples() string ", "output": "{\n\treturn cli.UsageExamples()\n}"} {"input": "package v6\n\nimport (\n\t\"code.cloudfoundry.org/cli/command\"\n\t\"code.cloudfoundry.org/cli/command/flag\"\n\t\"code.cloudfoundry.org/cli/command/translatableerror\"\n)\n\ntype UnsetOrgRoleCommand struct {\n\tRequiredArgs flag.SetOrgRoleArgs `positional-args:\"yes\"`\n\tusage interface{} `usage:\"CF_NAME unset-org-role USERNAME ORG ROLE\\n\\nROLES:\\n 'OrgManager' - Invite and manage users, select and change plans, and set spending limits\\n 'BillingManager' - Create and manage the billing account and payment info\\n 'OrgAuditor' - Read-only access to org info and reports\"`\n\trelatedCommands interface{} `related_commands:\"org-users, delete-user\"`\n}\n\nfunc (UnsetOrgRoleCommand) Setup(config command.Config, ui command.UI) error {\n\treturn nil\n}\n\n\n\nfunc (UnsetOrgRoleCommand) Execute(args []string) error ", "output": "{\n\treturn translatableerror.UnrefactoredCommandError{}\n}"} {"input": "package signature\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha256\"\n\t\"log\"\n\n\t\"github.com/cloudfoundry/dropsonde/metrics\"\n)\n\nconst SIGNATURE_LENGTH = 32\n\n\n\ntype Verifier struct {\n\tsharedSecret string\n}\n\n\n\nfunc NewVerifier(sharedSecret string) *Verifier {\n\treturn &Verifier{\n\t\tsharedSecret: sharedSecret,\n\t}\n}\n\n\n\n\n\n\n\n\n\n\nfunc (v *Verifier) verifyMessage(message, signature []byte) bool {\n\texpectedMAC := generateSignature(message, []byte(v.sharedSecret))\n\treturn hmac.Equal(signature, expectedMAC)\n}\n\n\n\nfunc SignMessage(message, secret []byte) []byte {\n\tsignature := generateSignature(message, secret)\n\treturn append(signature, message...)\n}\n\nfunc generateSignature(message, secret []byte) []byte {\n\tmac := hmac.New(sha256.New, secret)\n\tmac.Write(message)\n\treturn mac.Sum(nil)\n}\n\nfunc (v *Verifier) Run(inputChan <-chan []byte, outputChan chan<- []byte) ", "output": "{\n\tfor signedMessage := range inputChan {\n\t\tif len(signedMessage) < SIGNATURE_LENGTH {\n\t\t\tlog.Print(\"signatureVerifier: missing signature\")\n\t\t\tcontinue\n\t\t}\n\n\t\tsignature, message := signedMessage[:SIGNATURE_LENGTH], signedMessage[SIGNATURE_LENGTH:]\n\t\tif v.verifyMessage(message, signature) {\n\t\t\toutputChan <- message\n\t\t\tmetrics.BatchIncrementCounter(\"signatureVerifier.validSignatures\")\n\t\t} else {\n\t\t\tlog.Print(\"signatureVerifier: invalid signature\")\n\t\t}\n\t}\n}"} {"input": "package framework\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/util/wait\"\n\t\"k8s.io/apimachinery/pkg/util/yaml\"\n\t\"k8s.io/client-go/kubernetes\"\n)\n\nfunc createReplicationControllerViaYml(kubeClient kubernetes.Interface, namespace string, filepath string) error {\n\tmanifest, err := os.Open(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar rC v1.ReplicationController\n\terr = yaml.NewYAMLOrJSONDecoder(manifest, 100).Decode(&rC)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = kubeClient.CoreV1().ReplicationControllers(namespace).Create(&rC)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc scaleDownReplicationController(kubeClient kubernetes.Interface, namespace string, rC v1.ReplicationController) error {\n\t*rC.Spec.Replicas = 0\n\trCAPI := kubeClient.CoreV1().ReplicationControllers(namespace)\n\n\t_, err := kubeClient.CoreV1().ReplicationControllers(namespace).Update(&rC)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn wait.Poll(time.Second, time.Minute*5, func() (bool, error) {\n\t\tcurrentRC, err := rCAPI.Get(rC.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif currentRC.Status.Replicas == 0 {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n}\n\nfunc deleteReplicationControllerViaYml(kubeClient kubernetes.Interface, namespace string, filepath string) error ", "output": "{\n\tmanifest, err := os.Open(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar rC v1.ReplicationController\n\terr = yaml.NewYAMLOrJSONDecoder(manifest, 100).Decode(&rC)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := scaleDownReplicationController(kubeClient, namespace, rC); err != nil {\n\t\treturn err\n\t}\n\n\tif err := kubeClient.CoreV1().ReplicationControllers(namespace).Delete(rC.Name, nil); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package modules\n\nimport (\n\t\"io\"\n\n\t\"github.com/kylelemons/go-gypsy/yaml\"\n)\n\ntype Node interface{}\ntype Scalar string\ntype Map map[string]Node\ntype List []Node\n\n\n\nfunc Parse(r io.Reader) (Node, error) {\n\tn, err := yaml.Parse(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn YamlNodeToNode(n), err\n}\n\nfunc Child(root Node, spec string) (Node, error) {\n\treturn nil, nil\n}\n\nfunc (s Scalar) String() string {\n\treturn string(s)\n}\n\nfunc (s Scalar) GetBool() bool {\n\tif s == \"true\" || s == \"yes\" || s == \"1\" {\n\t\treturn true\n\t} else if s == \"false\" || s == \"no\" || s == \"0\" {\n\t\treturn false\n\t}\n\tpanic(\"Invalid bool value:\" + s.String())\n}\n\nfunc (m Map) Keys() []string {\n\tkeys := make([]string, 0, len(m))\n\tfor key := range m {\n\t\tkeys = append(keys, key)\n\t}\n\treturn keys\n}\n\nfunc (m Map) Key(key string) Node {\n\treturn m[key]\n}\n\nfunc (l List) Item(idx int) Node {\n\treturn l[idx]\n}\n\nfunc (l List) Len() int {\n\treturn len(l)\n}\n\nfunc YamlNodeToNode(node yaml.Node) Node ", "output": "{\n\tscalar, ok := node.(yaml.Scalar)\n\tif ok {\n\t\treturn Scalar(scalar.String())\n\t}\n\tlist, ok := node.(yaml.List)\n\tif ok {\n\t\tresult := make(List, list.Len())\n\t\tfor i, n := range list {\n\t\t\tresult[i] = YamlNodeToNode(n)\n\t\t}\n\t\treturn result\n\t}\n\tmp, ok := node.(yaml.Map)\n\tif ok {\n\t\tresult := make(Map)\n\t\tfor k, v := range mp {\n\t\t\tresult[k] = YamlNodeToNode(v)\n\t\t}\n\t\treturn result\n\t}\n\treturn nil\n}"} {"input": "package producer\n\nimport (\n\t\"fmt\"\n\t\"github.com/elodina/siesta\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype Metadata struct {\n\tconnector siesta.Connector\n\tmetadataExpire time.Duration\n\tcache map[string]*metadataEntry\n\tmetadataLock sync.RWMutex\n}\n\nfunc NewMetadata(connector siesta.Connector, metadataExpire time.Duration) *Metadata {\n\treturn &Metadata{\n\t\tconnector: connector,\n\t\tmetadataExpire: metadataExpire,\n\t\tcache: make(map[string]*metadataEntry),\n\t}\n}\n\nfunc (tmc *Metadata) Get(topic string) ([]int32, error) {\n\ttmc.metadataLock.RLock()\n\tcache := tmc.cache[topic]\n\ttmc.metadataLock.RUnlock()\n\n\tif cache == nil || cache.timestamp.Add(tmc.metadataExpire).Before(time.Now()) {\n\t\terr := tmc.Refresh([]string{topic})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttmc.metadataLock.RLock()\n\t\tcache = tmc.cache[topic]\n\t\ttmc.metadataLock.RUnlock()\n\n\t\tif cache != nil {\n\t\t\treturn cache.partitions, nil\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Could not get topic metadata for topic %s\", topic)\n\t}\n\n\treturn cache.partitions, nil\n}\n\n\n\ntype metadataEntry struct {\n\tpartitions []int32\n\ttimestamp time.Time\n}\n\nfunc newMetadataEntry(partitions []int32) *metadataEntry {\n\treturn &metadataEntry{\n\t\tpartitions: partitions,\n\t\ttimestamp: time.Now(),\n\t}\n}\n\nfunc (tmc *Metadata) Refresh(topics []string) error ", "output": "{\n\ttmc.metadataLock.Lock()\n\tdefer tmc.metadataLock.Unlock()\n\tLogger.Info(\"Refreshing metadata for topics %v\", topics)\n\n\ttopicMetadataResponse, err := tmc.connector.GetTopicMetadata(topics)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, topicMetadata := range topicMetadataResponse.TopicsMetadata {\n\t\tpartitions := make([]int32, 0)\n\t\tfor _, partitionMetadata := range topicMetadata.PartitionsMetadata {\n\t\t\tpartitions = append(partitions, partitionMetadata.PartitionID)\n\t\t}\n\t\ttmc.cache[topicMetadata.Topic] = newMetadataEntry(partitions)\n\t\tLogger.Debug(\"Received metadata: partitions %v for topic %s\", partitions, topicMetadata.Topic)\n\t}\n\n\treturn nil\n}"} {"input": "package leetcode\n\nimport \"testing\"\n\n\n\nfunc TestMinCostClimbingStairs(t *testing.T) ", "output": "{\n\tif minCostClimbingStairs([]int{10, 15, 20}) != 15 {\n\t\tt.Fatal()\n\t}\n\tif minCostClimbingStairs([]int{1, 100, 1, 1, 1, 100, 1, 1, 100, 1}) != 6 {\n\t\tt.Fatal()\n\t}\n}"} {"input": "package v3\n\nimport (\n\tv3 \"github.com/projectcalico/api/pkg/apis/projectcalico/v3\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype BGPPeerLister interface {\n\tList(selector labels.Selector) (ret []*v3.BGPPeer, err error)\n\tGet(name string) (*v3.BGPPeer, error)\n\tBGPPeerListerExpansion\n}\n\n\ntype bGPPeerLister struct {\n\tindexer cache.Indexer\n}\n\n\n\n\n\nfunc (s *bGPPeerLister) List(selector labels.Selector) (ret []*v3.BGPPeer, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v3.BGPPeer))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *bGPPeerLister) Get(name string) (*v3.BGPPeer, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v3.Resource(\"bgppeer\"), name)\n\t}\n\treturn obj.(*v3.BGPPeer), nil\n}\n\nfunc NewBGPPeerLister(indexer cache.Indexer) BGPPeerLister ", "output": "{\n\treturn &bGPPeerLister{indexer: indexer}\n}"} {"input": "package update\n\nimport (\n\t\"github.com/andreaskoch/allmark/common/route\"\n\t\"fmt\"\n\t\"golang.org/x/net/websocket\"\n)\n\nfunc NewConnection(hub *Hub, ws *websocket.Conn, route route.Route) *connection {\n\treturn &connection{\n\t\tRoute: route,\n\n\t\thub: hub,\n\t\tsend: make(chan Message, 10),\n\t\tws: ws,\n\t}\n}\n\ntype connection struct {\n\tRoute route.Route\n\n\thub *Hub\n\n\tws *websocket.Conn\n\n\tsend chan Message\n}\n\nfunc (c *connection) String() string {\n\treturn fmt.Sprintf(\"Connection (Route: %s, IP: %s)\", c.Route.String(), c.ws.Request().RemoteAddr)\n}\n\nfunc (c *connection) Send(msg Message) {\n\tc.send <- msg\n}\n\n\n\nfunc (c *connection) Writer() {\n\tfor message := range c.send {\n\t\terr := websocket.JSON.Send(c.ws, message)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tc.ws.Close()\n\tc.hub.Unsubscribe(c)\n}\n\nfunc (c *connection) Reader() ", "output": "{\n\tfor {\n\t\tvar message Message\n\t\terr := websocket.JSON.Receive(c.ws, &message)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tc.hub.broadcast <- message\n\t}\n\n\tc.ws.Close()\n\tc.hub.Unsubscribe(c)\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar x Animal = Dog{\"Rosie\"}\n\n\tif x, ok := x.(Human); ok {\n\t\tfmt.Println(x.lastName, \"doesn't want to be treated like dogs and cats.\")\n\t} else {\n\t\tfmt.Println(x.Say())\n\t}\n}\n\ntype Animal interface {\n\tSay() string\n}\n\ntype Dog struct {\n\tname string\n}\n\n\n\ntype Cat struct {\n\tname string\n}\n\nfunc (c Cat) Say() string {\n\treturn fmt.Sprintf(\"%v meows\", c.name)\n}\n\ntype Human struct {\n\tfirstName string\n\tlastName string\n}\n\n\nfunc (h Human) Say() string {\n\treturn fmt.Sprintf(\"%v %v speaks\", h.firstName, h.lastName)\n}\n\nfunc (d Dog) Say() string ", "output": "{\n\treturn fmt.Sprintf(\"%v barks\", d.name)\n}"} {"input": "package goFrontEnd\n\nimport (\n \"fmt\"\n \"net/http\"\n \"math/rand\"\n \"strconv\"\n)\n\n\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n wHeader := w.Header()\n wHeader.Set(\"Content-Type\",\"application/json\")\n fmt.Fprint(w, \"{\\\"a\\\":\\\"beetle\\\",\\\"b\\\":\\\"juice\\\"}\")\n}\n\nfunc handler2(w http.ResponseWriter, r *http.Request) {\n wHeader := w.Header()\n x := rand.Intn(18)\n y := rand.Intn(18)\n xx := strconv.Itoa(x)\n yy := strconv.Itoa(y)\n wHeader.Set(\"Content-Type\",\"application/json\")\n fmt.Fprint(w, \"{\\\"x\\\":\\\"\" + xx + \"\\\",\\\"y\\\":\\\"\" + yy + \"\\\"}\")\n \n}\n\nfunc init() ", "output": "{\n http.HandleFunc(\"/\", handler)\n http.HandleFunc(\"/abc\", handler2)\n}"} {"input": "package main\n\nimport \"fmt\"\nimport \"time\"\n\n\n\nfunc goFunc2(f func(interface{}), i interface{}) {\n\tgo f(i)\n}\n\nfunc goFunc(f interface{}, args ...interface{}) {\n\tif len(args) > 1 {\n\t\tgo f.(func(...interface{}))(args)\n\t} else if len(args) == 1 {\n\t\tgo f.(func(interface{}))(args[0])\n\t} else {\n\t\tgo f.(func())()\n\t}\n}\n\nfunc f1() {\n\tfmt.Println(\"f1 done\")\n}\n\nfunc f2(i interface{}) {\n\tfmt.Println(\"f2 done\", i)\n}\n\nfunc f3(args ...interface{}) {\n\tfmt.Println(\"f3 done\", args)\n}\n\nfunc main() {\n\tgoFunc1(f1)\n\tgoFunc2(f2, 100)\n\n\tgoFunc(f1)\n\tgoFunc(f2, \"xxxx\")\n\tgoFunc(f3, \"hello\", \"world\", 1, 3.14)\n\ttime.Sleep(5 * time.Second)\n}\n\nfunc goFunc1(f func()) ", "output": "{\n\tgo f()\n}"} {"input": "package console\n\nimport (\n\t\"fmt\"\n\t\"github.com/serainville/gologger/logger\"\n\t\"time\"\n)\n\nfunc ConsolePrinter(log logger.LogInstance, packageName string, fileName string, lineNumber int, funcName string, time time.Time) {\n\tcolor := getColor(log)\n\tcolor.Set()\n\tfmt.Printf(\"[%s] [%s] [%s::%s::%s] [%d] %s\\n\", log.LogType, time.Format(\"2006-01-02 15:04:05\"), packageName, fileName, funcName, lineNumber, log.Message)\n\tUnset()\n}\n\n\n\nfunc getColor(log logger.LogInstance) *Color {\n\tvar color *Color\n\n\tif log.LoggerInit.Location == \"simple\" {\n\t\tcolor = New(Reset)\n\t\treturn color\n\t}\n\n\tswitch log.LogType {\n\tcase \"LOG\":\n\t\tcolor = New(Reset)\n\t\tbreak\n\tcase \"MSG\":\n\t\tcolor = New(FgBlue)\n\t\tbreak\n\tcase \"INF\":\n\t\tcolor = New(FgGreen)\n\t\tbreak\n\tcase \"WRN\":\n\t\tcolor = New(FgMagenta)\n\t\tbreak\n\tcase \"DBG\":\n\t\tcolor = New(FgYellow)\n\t\tbreak\n\tcase \"ERR\":\n\t\tcolor = New(FgRed)\n\t\tbreak\n\tcase \"RSS\":\n\t\tcolor = New(Reset)\n\t\tbreak\n\tdefault:\n\t\tcolor = New(Reset)\n\t\tbreak\n\t}\n\treturn color\n}\n\nfunc ConsoleBasicPrinter(log logger.LogInstance, time time.Time) ", "output": "{\n\tcolor := getColor(log)\n\tcolor.Set()\n\tfmt.Printf(\"[%s] [%s] %s\\n\", log.LogType, time.Format(\"2006-01-02 15:04:05\"), log.Message)\n\tUnset()\n}"} {"input": "package acceptance_stubs\n\nimport (\n\tsync \"sync\"\n\n\talias1 \"github.com/mokiat/gostub/acceptance\"\n)\n\ntype AnonymousParamsStub struct {\n\tStubGUID int\n\tRegisterStub func(arg1 string, arg2 int)\n\tregisterMutex sync.RWMutex\n\tregisterArgsForCall []struct {\n\t\targ1 string\n\t\targ2 int\n\t}\n}\n\nvar _ alias1.AnonymousParams = new(AnonymousParamsStub)\n\nfunc (stub *AnonymousParamsStub) Register(arg1 string, arg2 int) {\n\tstub.registerMutex.Lock()\n\tdefer stub.registerMutex.Unlock()\n\tstub.registerArgsForCall = append(stub.registerArgsForCall, struct {\n\t\targ1 string\n\t\targ2 int\n\t}{arg1, arg2})\n\tif stub.RegisterStub != nil {\n\t\tstub.RegisterStub(arg1, arg2)\n\t}\n}\n\nfunc (stub *AnonymousParamsStub) RegisterArgsForCall(index int) (string, int) {\n\tstub.registerMutex.RLock()\n\tdefer stub.registerMutex.RUnlock()\n\treturn stub.registerArgsForCall[index].arg1, stub.registerArgsForCall[index].arg2\n}\n\nfunc (stub *AnonymousParamsStub) RegisterCallCount() int ", "output": "{\n\tstub.registerMutex.RLock()\n\tdefer stub.registerMutex.RUnlock()\n\treturn len(stub.registerArgsForCall)\n}"} {"input": "package test\n\nimport (\n\t\"github.com/stellar/go/support/db\"\n\t\"github.com/stellar/horizon/ledger\"\n)\n\n\nfunc (t *T) CoreRepo() *db.Repo {\n\treturn &db.Repo{\n\t\tDB: t.CoreDB,\n\t\tCtx: t.Ctx,\n\t}\n}\n\n\n\nfunc (t *T) Finish() {\n\tRestoreLogger()\n\tledger.SetState(ledger.State{})\n\n\tif t.LogBuffer.Len() > 0 {\n\t\tt.T.Log(\"\\n\" + t.LogBuffer.String())\n\t}\n}\n\n\nfunc (t *T) HorizonRepo() *db.Repo {\n\treturn &db.Repo{\n\t\tDB: t.HorizonDB,\n\t\tCtx: t.Ctx,\n\t}\n}\n\n\nfunc (t *T) Scenario(name string) *T {\n\tLoadScenario(name)\n\tt.UpdateLedgerState()\n\treturn t\n}\n\n\n\n\n\nfunc (t *T) UpdateLedgerState() {\n\tvar next ledger.State\n\n\terr := t.CoreRepo().GetRaw(&next, `\n\t\tSELECT\n\t\t\tCOALESCE(MIN(ledgerseq), 0) as core_elder,\n\t\t\tCOALESCE(MAX(ledgerseq), 0) as core_latest\n\t\tFROM ledgerheaders\n\t`)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = t.HorizonRepo().GetRaw(&next, `\n\t\t\tSELECT\n\t\t\t\tCOALESCE(MIN(sequence), 0) as history_elder,\n\t\t\t\tCOALESCE(MAX(sequence), 0) as history_latest\n\t\t\tFROM history_ledgers\n\t\t`)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tledger.SetState(next)\n\treturn\n}\n\nfunc (t *T) ScenarioWithoutHorizon(name string) *T ", "output": "{\n\tLoadScenarioWithoutHorizon(name)\n\tt.UpdateLedgerState()\n\treturn t\n}"} {"input": "package models\n\nimport \"github.com/tuxychandru/pubsub\"\n\nvar (\n\tPushCenter *pubsub.PubSub\n)\n\nfunc initPubsub() {\n\tPushCenter = pubsub.New(100)\n}\n\n\n\nfunc Subscribe(channel string, callback func(message interface{})) {\n\tch := PushCenter.Sub(channel)\n\tfor {\n\t\tout := <-ch\n\t\tcallback(out)\n\t}\n}\n\nfunc PushMessage(channel string, message interface{}) ", "output": "{\n\tPushCenter.Pub(message, channel)\n}"} {"input": "package credential\n\nimport (\n\t\"pharmer.dev/cloud/apis\"\n\tv1 \"pharmer.dev/cloud/apis/cloud/v1\"\n\n\t\"github.com/spf13/pflag\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\ntype Linode struct {\n\tCommonSpec\n\n\ttoken string\n}\n\nfunc (c Linode) APIToken() string { return get(c.Data, LinodeAPIToken, c.token) }\n\nfunc (c *Linode) LoadFromEnv() {\n\tc.CommonSpec.LoadFromEnv(c.Format())\n}\n\nfunc (c Linode) IsValid() (bool, error) {\n\treturn c.CommonSpec.IsValid(c.Format())\n}\n\n\n\nfunc (_ Linode) RequiredFlags() []string {\n\treturn []string{apis.Linode + \".\" + LinodeAPIToken}\n}\n\nfunc (_ Linode) Format() v1.CredentialFormat {\n\treturn v1.CredentialFormat{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: apis.Linode,\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tapis.KeyClusterCredential: \"\",\n\t\t\t\tapis.KeyDNSCredential: \"\",\n\t\t\t},\n\t\t},\n\t\tSpec: v1.CredentialFormatSpec{\n\t\t\tProvider: apis.Linode,\n\t\t\tDisplayFormat: \"field\",\n\t\t\tFields: []v1.CredentialField{\n\t\t\t\t{\n\t\t\t\t\tEnvconfig: \"LINODE_TOKEN\",\n\t\t\t\t\tForm: \"linode_token\",\n\t\t\t\t\tJSON: LinodeAPIToken,\n\t\t\t\t\tLabel: \"Token\",\n\t\t\t\t\tInput: \"password\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (c *Linode) AddFlags(fs *pflag.FlagSet) ", "output": "{\n\tfs.StringVar(&c.token, apis.Linode+\".\"+LinodeAPIToken, c.token, \"Linode api token\")\n}"} {"input": "package core\n\nimport (\n\t\"database/sql\"\n\t\"strconv\"\n)\n\n\ntype Migration struct {\n\tIdentifier int64\n\tName string\n\tUp func(tx *Tx)\n\tDown func(tx *Tx)\n}\n\n\n\n\n\n\nfunc (m *Migration) Pending(db *sql.DB) bool {\n\trows, _ := db.Query(\"Select * from \" + MigrationsTable + \" WHERE identifier =\" + m.GetID())\n\tdefer rows.Close()\n\tcount := 0\n\n\tfor rows.Next() {\n\t\tcount++\n\t}\n\n\treturn count == 0\n}\n\n\ntype ByIdentifier []Migration\n\nfunc (a ByIdentifier) Len() int { return len(a) }\nfunc (a ByIdentifier) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a ByIdentifier) Less(i, j int) bool { return a[i].Identifier < a[j].Identifier }\n\nfunc (m *Migration) GetID() string ", "output": "{\n\treturn strconv.FormatInt(m.Identifier, 10)\n}"} {"input": "package etcd\n\nimport (\n\t\"testing\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/api\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/api/rest/resttest\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/api/testapi\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/storage\"\n\tetcdstorage \"github.com/GoogleCloudPlatform/kubernetes/pkg/storage/etcd\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/tools\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/tools/etcdtest\"\n)\n\nfunc newEtcdStorage(t *testing.T) (*tools.FakeEtcdClient, storage.Interface) {\n\tfakeEtcdClient := tools.NewFakeEtcdClient(t)\n\tfakeEtcdClient.TestIndex = true\n\tetcdStorage := etcdstorage.NewEtcdStorage(fakeEtcdClient, testapi.Codec(), etcdtest.PathPrefix())\n\treturn fakeEtcdClient, etcdStorage\n}\n\nfunc validNewServiceAccount(name string) *api.ServiceAccount {\n\treturn &api.ServiceAccount{\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: api.NamespaceDefault,\n\t\t},\n\t\tSecrets: []api.ObjectReference{},\n\t}\n}\n\nfunc TestCreate(t *testing.T) {\n\tfakeEtcdClient, etcdStorage := newEtcdStorage(t)\n\tstorage := NewStorage(etcdStorage)\n\ttest := resttest.New(t, storage, fakeEtcdClient.SetError)\n\tserviceAccount := validNewServiceAccount(\"foo\")\n\tserviceAccount.ObjectMeta = api.ObjectMeta{GenerateName: \"foo-\"}\n\ttest.TestCreate(\n\t\tserviceAccount,\n\t\t&api.ServiceAccount{},\n\t\t&api.ServiceAccount{\n\t\t\tObjectMeta: api.ObjectMeta{Name: \"name with spaces\"},\n\t\t},\n\t)\n}\n\n\n\nfunc TestUpdate(t *testing.T) ", "output": "{\n\tfakeEtcdClient, etcdStorage := newEtcdStorage(t)\n\tstorage := NewStorage(etcdStorage)\n\ttest := resttest.New(t, storage, fakeEtcdClient.SetError)\n\tkey, err := storage.KeyFunc(test.TestContext(), \"foo\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tkey = etcdtest.AddPrefix(key)\n\n\tfakeEtcdClient.ExpectNotFoundGet(key)\n\tfakeEtcdClient.ChangeIndex = 2\n\tserviceAccount := validNewServiceAccount(\"foo\")\n\texisting := validNewServiceAccount(\"exists\")\n\texisting.Namespace = test.TestNamespace()\n\tobj, err := storage.Create(test.TestContext(), existing)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to create object: %v\", err)\n\t}\n\tolder := obj.(*api.ServiceAccount)\n\tolder.ResourceVersion = \"1\"\n\n\ttest.TestUpdate(\n\t\tserviceAccount,\n\t\texisting,\n\t\tolder,\n\t)\n}"} {"input": "package reaperlog\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/rifflock/lfshook\"\n\t\"go.mozilla.org/mozlogrus\"\n)\n\nvar config LogConfig\n\ntype LogConfig struct {\n\tExtras bool\n}\n\nfunc EnableExtras() {\n\tconfig.Extras = true\n}\n\nfunc EnableMozlog() {\n\tmozlogrus.Enable(\"Reaper\")\n}\n\nfunc Extras() bool {\n\treturn config.Extras\n}\n\nfunc SetConfig(c *LogConfig) {\n\tconfig = *c\n}\n\nfunc AddLogFile(filename string) {\n\tlog.AddHook(lfshook.NewHook(lfshook.PathMap{\n\t\tlog.DebugLevel: filename,\n\t\tlog.InfoLevel: filename,\n\t\tlog.WarnLevel: filename,\n\t\tlog.ErrorLevel: filename,\n\t\tlog.FatalLevel: filename,\n\t\tlog.PanicLevel: filename,\n\t}))\n}\n\nfunc Debug(format string, args ...interface{}) {\n\tlog.Debugf(format, args...)\n}\n\nfunc Info(format string, args ...interface{}) {\n\tlog.Infof(format, args...)\n}\n\n\n\nfunc Fatal(format string, args ...interface{}) {\n\tlog.Fatalf(format, args...)\n}\n\nfunc Panic(format string, args ...interface{}) {\n\tlog.Panicf(format, args...)\n}\n\nfunc Error(format string, args ...interface{}) {\n\tlog.Errorf(format, args...)\n}\n\nfunc Warning(format string, args ...interface{}) ", "output": "{\n\tlog.Warningf(format, args...)\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/docker/docker/integration-cli/checker\"\n\t\"github.com/docker/docker/integration-cli/cli\"\n\t\"github.com/go-check/check\"\n\t\"github.com/gotestyourself/gotestyourself/icmd\"\n)\n\n\n\nfunc (s *DockerSuite) TestUpdateRestartWithAutoRemoveFlag(c *check.C) {\n\tout := runSleepingContainer(c, \"--rm\")\n\tid := strings.TrimSpace(out)\n\n\tcli.Docker(cli.Args(\"update\", \"--restart=always\", id)).Assert(c, icmd.Expected{\n\t\tExitCode: 1,\n\t\tErr: \"Restart policy cannot be updated because AutoRemove is enabled for the container\",\n\t})\n}\n\nfunc (s *DockerSuite) TestUpdateRestartPolicy(c *check.C) ", "output": "{\n\tout := cli.DockerCmd(c, \"run\", \"-d\", \"--restart=on-failure:3\", \"busybox\", \"sh\", \"-c\", \"sleep 1 && false\").Combined()\n\ttimeout := 60 * time.Second\n\tif testEnv.DaemonPlatform() == \"windows\" {\n\t\ttimeout = 180 * time.Second\n\t}\n\n\tid := strings.TrimSpace(string(out))\n\n\tcli.DockerCmd(c, \"update\", \"--restart=on-failure:5\", id)\n\n\tcli.WaitExited(c, id, timeout)\n\n\tcount := inspectField(c, id, \"RestartCount\")\n\tc.Assert(count, checker.Equals, \"5\")\n\n\tmaximumRetryCount := inspectField(c, id, \"HostConfig.RestartPolicy.MaximumRetryCount\")\n\tc.Assert(maximumRetryCount, checker.Equals, \"5\")\n}"} {"input": "package v1\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\ntype staticAsset struct {\n\tasset string\n\tlogger logrus.FieldLogger\n}\n\nvar _ http.Handler = staticAsset{}\n\nfunc NewStaticAsset(logger logrus.FieldLogger, asset string) http.Handler {\n\treturn staticAsset{\n\t\tasset: asset,\n\t\tlogger: logger,\n\t}\n}\n\n\n\nfunc (h staticAsset) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tlogger := h.logger.WithFields(logrus.Fields{\n\t\t\"request.remote_addr\": r.RemoteAddr,\n\t\t\"request.method\": r.Method,\n\t\t\"request.uri\": r.RequestURI,\n\t})\n\n\tif r.Method != \"GET\" {\n\t\tw.WriteHeader(405)\n\t\tw.Write([]byte(\"method not allowed\"))\n\n\t\tlogger.WithField(\"response.status\", 405).Warn(\"method not allowed\")\n\n\t\treturn\n\t}\n\n\thttp.ServeFile(w, r, h.asset)\n\n\tlogger.WithField(\"response.status\", 200).Info(\"served static asset\")\n}"} {"input": "package lifegame\n\ntype Universe struct {\n\taliveCells []Cell\n}\n\ntype Cell struct{}\n\nfunc NewUniverse() *Universe {\n\treturn &Universe{}\n}\n\nfunc (u *Universe) HasAliveCell() bool {\n\treturn len(u.AliveCells()) != 0\n}\n\nfunc (u *Universe) AliveCells() []Cell {\n\treturn u.aliveCells\n}\n\nfunc (u *Universe) NextGeneration() {\n\tu.aliveCells = []Cell{}\n}\n\n\n\nfunc (c *Cell) Location() (int, int) {\n\treturn 0, 0\n}\n\nfunc (u *Universe) BornCellAtLocation(x, y int) ", "output": "{\n\tu.aliveCells = append(u.aliveCells, Cell{})\n}"} {"input": "package gogs\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\nfunc (c *Client) AdminCreateOrg(user string, opt CreateOrgOption) (*Organization, error) {\n\tbody, err := json.Marshal(&opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\torg := new(Organization)\n\treturn org, c.getParsedResponse(\"POST\", fmt.Sprintf(\"/admin/users/%s/orgs\", user),\n\t\tjsonHeader, bytes.NewReader(body), org)\n}\n\n\n\nfunc (c *Client) AdminAddTeamMembership(teamID int64, user string) error {\n\t_, err := c.getResponse(\"PUT\", fmt.Sprintf(\"/admin/teams/%d/members/%s\", teamID, user),\n\t\tjsonHeader, nil)\n\treturn err\n}\n\nfunc (c *Client) AdminAddTeamRepository(teamID int64, repo string) error {\n\t_, err := c.getResponse(\"PUT\", fmt.Sprintf(\"/admin/teams/%d/repos/%s\", teamID, repo),\n\t\tjsonHeader, nil)\n\treturn err\n}\n\nfunc (c *Client) AdminCreateTeam(user string, opt CreateTeamOption) (*Team, error) ", "output": "{\n\tbody, err := json.Marshal(&opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tteam := new(Team)\n\treturn team, c.getParsedResponse(\"POST\", fmt.Sprintf(\"/admin/orgs/%s/teams\", user),\n\t\tjsonHeader, bytes.NewReader(body), team)\n}"} {"input": "package golbStoreIpsum\n\nimport (\n\t\"github.com/cryptix/golbStore\"\n)\n\n\n\nfunc (b IpsumBlog) Get(id string) (*golbStore.Entry, error) {\n\te, found := b.store[id]\n\tif !found {\n\t\treturn nil, golbStore.ErrEntryNotFound\n\t}\n\n\treturn e, nil\n}\n\nfunc (b IpsumBlog) Delete(id string) error {\n\treturn nil\n}\n\nfunc (b IpsumBlog) Save(e *golbStore.Entry) error {\n\tb.store[e.ID] = e\n\n\treturn nil\n}\n\nfunc (b IpsumBlog) Latest(n int, withText bool) ([]*golbStore.Entry, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package chart\n\nimport (\n\t\"testing\"\n\n\t\"github.com/wcharczuk/go-chart/v2/testutil\"\n)\n\n\n\nfunc TestLastValueAnnotationSeries(t *testing.T) ", "output": "{\n\n\tseries := ContinuousSeries{\n\t\tXValues: []float64{1.0, 2.0, 3.0, 4.0, 5.0},\n\t\tYValues: []float64{5.0, 3.0, 3.0, 2.0, 1.0},\n\t}\n\n\tlva := LastValueAnnotationSeries(series)\n\ttestutil.AssertNotEmpty(t, lva.Annotations)\n\tlvaa := lva.Annotations[0]\n\ttestutil.AssertEqual(t, 5, lvaa.XValue)\n\ttestutil.AssertEqual(t, 1, lvaa.YValue)\n}"} {"input": "package log\n\nimport (\n\t\"github.com/fcavani/e\"\n)\n\ntype StoreFake struct{}\n\nfunc (s StoreFake) SupportTx() bool {\n\treturn false\n}\n\n\n\nfunc (s StoreFake) Tx(write bool, f func(tx Transaction) error) error ", "output": "{\n\treturn e.New(\"store not implemented\")\n}"} {"input": "package plugin\n\nimport (\n\t\"github.com/pkg/errors\"\n\t\"github.com/xeipuuv/gojsonschema\"\n)\n\ntype Container struct {\n\tPlugin Plugin\n\tschema *gojsonschema.Schema\n}\n\ntype ValidationResult struct {\n\tErrors []error\n}\n\n\n\nfunc (pc *Container) ValidateSpec(pluginSpec map[string]interface{}) (ValidationResult, error) {\n\tif pc.schema == nil {\n\t\treturn ValidationResult{}, nil\n\t}\n\n\tresult, err := pc.schema.Validate(gojsonschema.NewGoLoader(pluginSpec))\n\tif err != nil {\n\t\treturn ValidationResult{}, errors.Wrap(err, \"error validating plugin spec\")\n\t}\n\n\tif !result.Valid() {\n\t\tvalidationErrors := result.Errors()\n\t\terrs := make([]error, 0, len(validationErrors))\n\n\t\tfor _, validationErr := range validationErrors {\n\t\t\terrs = append(errs, errors.New(validationErr.String()))\n\t\t}\n\n\t\treturn ValidationResult{errs}, nil\n\t}\n\n\treturn ValidationResult{}, nil\n}\n\nfunc NewContainer(newPlugin NewFunc) (Container, error) ", "output": "{\n\tplugin, err := newPlugin()\n\tif err != nil {\n\t\treturn Container{}, errors.Wrap(err, \"failed to instantiate plugin\")\n\t}\n\tdescription := plugin.Describe()\n\tvar schema *gojsonschema.Schema\n\tif description.SpecSchema != nil {\n\t\tschema, err = gojsonschema.NewSchema(gojsonschema.NewBytesLoader(description.SpecSchema))\n\t\tif err != nil {\n\t\t\treturn Container{}, errors.Wrapf(err, \"can't use plugin %q due to invalid schema\", description.Name)\n\t\t}\n\t}\n\n\treturn Container{\n\t\tPlugin: plugin,\n\t\tschema: schema,\n\t}, nil\n}"} {"input": "package schedulercache\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/labels\"\n\t\"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache\"\n)\n\n\ntype FakeCache struct {\n\tAssumeFunc func(*api.Pod)\n}\n\n\n\nfunc (f *FakeCache) AddPod(pod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) UpdatePod(oldPod, newPod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) RemovePod(pod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) AddNode(node *api.Node) error { return nil }\n\nfunc (f *FakeCache) UpdateNode(oldNode, newNode *api.Node) error { return nil }\n\nfunc (f *FakeCache) RemoveNode(node *api.Node) error { return nil }\n\nfunc (f *FakeCache) UpdateNodeNameToInfoMap(infoMap map[string]*schedulercache.NodeInfo) error {\n\treturn nil\n}\n\nfunc (f *FakeCache) List(s labels.Selector) ([]*api.Pod, error) { return nil, nil }\n\nfunc (f *FakeCache) AssumePod(pod *api.Pod) error ", "output": "{\n\tf.AssumeFunc(pod)\n\treturn nil\n}"} {"input": "package hiveConfig\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"log\"\n)\n\n\ntype HiveConfig struct {\n\tServerURL string `json:\"server\"`\n\tTokensPath string `json:\"token_file_path\"`\n\tDeviceCodes string `json:\"device_codes_file_path\"`\n\tSecondsDelay int64 `json:\"delay\"`\n\tEndpoints map[string]Endpoints `json:\"endpoints\"`\n}\n\n\ntype Endpoints struct {\n\tURL string `json:\"url\"`\n\tDelay int `json:\"delay\"`\n}\n\n\ntype Authtokens struct {\n\tTokens []string `json:\"tokens\"`\n}\n\n\ntype SadirLogins struct {\n\tLogins []string `json:\"sadira_logins\"`\n}\n\n\nfunc GetConfigJSON(jsonFile string) (cfg HiveConfig, err error) {\n\tjsonDoc, err := ioutil.ReadFile(jsonFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not read config file: %s \", err)\n\t\treturn\n\t}\n\terr = json.Unmarshal(jsonDoc, &cfg)\n\treturn cfg, err\n}\n\n\n\n\nfunc GetLogins(loginsFile string) (logins SadirLogins, err error) ", "output": "{\n\tjsonDoc, err := ioutil.ReadFile(loginsFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not read config file: %s \", err)\n\t\treturn\n\t}\n\terr = json.Unmarshal(jsonDoc, &logins)\n\treturn\n}"} {"input": "package arbitrage\n\nimport \"time\"\n\ntype Info struct {\n\tVersion int `yaml:\"version\"`\n\tFileHash string `yaml:\"file_hash\"`\n\tLastUpdated time.Time `yaml:\"last_updated\"`\n\tReleases map[string]InfoRelease `yaml:\"releases,omitempty\"`\n}\n\ntype InfoRelease struct {\n\tTorrentId int `yaml:\"torrent_id\"`\n\tFormat string `yaml:\"format\"`\n\tFilePath string `yaml:\"file_path\"`\n\n\tName string `yaml:\"name\"`\n\tYear int `yaml:\"year\"`\n\tRecordLabel string `yaml:\"record_label\"`\n\tCatalogueNumber string `yaml:\"catalogue_number\"`\n\tEdition string `yaml:\"edition\"`\n\n\tComposers []string `yaml:\"composers,omitempty,flow\"`\n\tArtists []string `yaml:\"artists\"`\n\tWith []string `yaml:\"with,omitempty,flow\"`\n\tDJ []string `yaml:\"dj,omitempty,flow\"`\n\tRemixedBy []string `yaml:\"remixed_by,omitempty,flow\"`\n\tProducer []string `yaml:\"producer,omitempty,flow\"`\n\n\tTags []string `yaml:\"tags,flow\"`\n\tDescription string `yaml:\"description,omitempty\"`\n\tImage string `yaml:\"image,omitempty\"`\n}\n\n\n\nfunc (i InfoRelease) String() string {\n\tstr := \"\"\n\tif len(i.Artists) == 1 {\n\t\tstr = i.Artists[0]\n\t} else if len(i.Artists) > 1 {\n\t\tstr = \"Various Artists\"\n\t} else {\n\t\tstr = \"Unknown Artist\"\n\t}\n\n\tstr = concat(str, \" - \", i.Name, \"\", \"\")\n\tstr = concat(str, \" \", i.Format, \"[\", \"]\")\n\tstr = concat(str, \" \", i.CatalogueNumber, \"{\", \"}\")\n\treturn str\n}\n\nfunc concat(s, del, extra, pre, suf string) string ", "output": "{\n\tif extra == \"\" {\n\t\treturn s\n\t}\n\tif s != \"\" {\n\t\ts += del\n\t}\n\treturn s + pre + extra + suf\n}"} {"input": "package vcr_test\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/dnaeon/go-vcr/recorder\"\n)\n\n\n\nfunc TestSimple(t *testing.T) ", "output": "{\n\tr, err := recorder.New(\"fixtures/golang-org\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer r.Stop() \n\n\tclient := &http.Client{\n\t\tTransport: r, \n\t}\n\n\turl := \"http:golang.org/\"\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to get url %s: %s\", url, err)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to read response body: %s\", err)\n\t}\n\n\twantTitle := \"The Go Programming Language\"\n\tbodyContent := string(body)\n\n\tif !strings.Contains(bodyContent, wantTitle) {\n\t\tt.Errorf(\"Title %s not found in response\", wantTitle)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/lmorg/murex/lang\"\n\t\"github.com/lmorg/murex/test/count\"\n)\n\n\n\nfunc TestMurex(t *testing.T) {\n\tcount.Tests(t, 1)\n\n\tlang.InitEnv()\n\n\tblock := []rune(\"a [Mon..Fri]->regexp m/^T/\")\n\n\t_, err := lang.ShellProcess.Fork(lang.F_NO_STDIN | lang.F_NO_STDOUT | lang.F_NO_STDERR).Execute(block)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n}\n\n\n\nfunc TestRunSource(t *testing.T) {\n\tcount.Tests(t, 1)\n\n\tfile := \"test/source.mx\"\n\trunSource(file)\n}\n\nfunc TestRunSourceGzMods(t *testing.T) {\n\tcount.Tests(t, 1)\n\n\tfile := \"test/source.mx.gz\"\n\trunSource(file)\n}\n\nfunc TestRunCommandLine(t *testing.T) ", "output": "{\n\tcount.Tests(t, 1)\n\n\trunCommandLine(`out: \"testing\" -> null`)\n}"} {"input": "package unibyte\n\nimport \"unicode\"\n\n\nfunc IsLower(b byte) bool {\n\treturn b >= 'a' && b <= 'z'\n}\n\n\nfunc IsUpper(b byte) bool {\n\treturn b >= 'A' && b <= 'Z'\n}\n\n\nfunc IsLetter(b byte) bool {\n\treturn IsLower(b) || IsUpper(b)\n}\n\n\nfunc IsSpaceQuote(b byte) bool {\n\treturn IsSpace(b) || b == '\"' || b == '\\''\n}\n\n\nfunc IsSpace(b byte) bool {\n\treturn unicode.IsSpace(rune(b))\n}\n\n\nfunc ToLower(b byte) byte {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn b\n}\n\n\nfunc ToUpper(b byte) byte {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn b\n}\n\n\n\n\n\nfunc ToUpperString(b byte) string {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn string(b)\n}\n\nfunc ToLowerString(b byte) string ", "output": "{\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn string(b)\n}"} {"input": "package main\n\nimport \"testing\"\n\n\n\nfunc TestLoadJSONFile(t *testing.T) ", "output": "{\n\tcases := []struct {\n\t\tfile string\n\t\tcnt int\n\t\terr string\n\t}{\n\t\t{\"../../fixtures/cmd-single-get.json\", 1, \"\"},\n\t}\n\tfor i, c := range cases {\n\t\tjf, err := loadJSONFile(c.file)\n\t\tif (err == nil) != (c.err == \"\") {\n\t\t\tt.Errorf(\"%d: expected err? to be %t, got %v\", i, (c.err != \"\"), err)\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil && err.Error() != c.err {\n\t\t\tt.Errorf(\"%d: expected error %q, got %q\", i, c.err, err)\n\t\t\tcontinue\n\t\t}\n\t\tif jf.cmds != c.cnt {\n\t\t\tt.Errorf(\"%d: expected %d commands, got %d\", i, c.cnt, jf.cmds)\n\t\t}\n\t}\n}"} {"input": "package deploymentmanager\n\n\n\n\n\n\n\n\ntype DeploymentMode string\n\nconst (\n\tComplete DeploymentMode = \"Complete\"\n\tIncremental DeploymentMode = \"Incremental\"\n)\n\n\nfunc PossibleDeploymentModeValues() []DeploymentMode {\n\treturn []DeploymentMode{Complete, Incremental}\n}\n\n\ntype StepType string\n\nconst (\n\tStepTypeStepProperties StepType = \"StepProperties\"\n\tStepTypeWait StepType = \"Wait\"\n)\n\n\nfunc PossibleStepTypeValues() []StepType {\n\treturn []StepType{StepTypeStepProperties, StepTypeWait}\n}\n\n\ntype Type string\n\nconst (\n\tTypeAuthentication Type = \"Authentication\"\n\tTypeSas Type = \"Sas\"\n)\n\n\n\n\nfunc PossibleTypeValues() []Type ", "output": "{\n\treturn []Type{TypeAuthentication, TypeSas}\n}"} {"input": "package generator\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\n\t\"k8s.io/kubernetes/cmd/libs/go2idl/namer\"\n\t\"k8s.io/kubernetes/cmd/libs/go2idl/parser\"\n\t\"k8s.io/kubernetes/cmd/libs/go2idl/types\"\n)\n\n\ntype Package interface {\n\tName() string\n\tPath() string\n\n\tFilter(*Context, *types.Type) bool\n\n\tHeader(filename string) []byte\n\n\tGenerators(*Context) []Generator\n}\n\ntype File struct {\n\tName string\n\tFileType string\n\tPackageName string\n\tHeader []byte\n\tImports map[string]struct{}\n\tVars bytes.Buffer\n\tConsts bytes.Buffer\n\tBody bytes.Buffer\n}\n\ntype FileType interface {\n\tAssembleFile(f *File, path string) error\n\tVerifyFile(f *File, path string) error\n}\n\n\ntype Packages []Package\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Generator interface {\n\tName() string\n\n\tFilter(*Context, *types.Type) bool\n\n\tNamers(*Context) namer.NameSystems\n\n\tInit(*Context, io.Writer) error\n\n\tPackageVars(*Context) []string\n\n\tPackageConsts(*Context) []string\n\n\tGenerateType(*Context, *types.Type, io.Writer) error\n\n\tImports(*Context) []string\n\n\tFilename() string\n\n\tFileType() string\n}\n\n\ntype Context struct {\n\tNamers namer.NameSystems\n\n\tUniverse types.Universe\n\n\tInputs []string\n\n\tOrder []*types.Type\n\n\tFileTypes map[string]FileType\n\n\tVerify bool\n\n\tbuilder *parser.Builder\n}\n\n\n\n\n\n\n\n\nfunc (ctxt *Context) AddDir(path string) error {\n\treturn ctxt.builder.AddDirTo(path, &ctxt.Universe)\n}\n\nfunc NewContext(b *parser.Builder, nameSystems namer.NameSystems, canonicalOrderName string) (*Context, error) ", "output": "{\n\tuniverse, err := b.FindTypes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := &Context{\n\t\tNamers: namer.NameSystems{},\n\t\tUniverse: universe,\n\t\tInputs: b.FindPackages(),\n\t\tFileTypes: map[string]FileType{\n\t\t\tGolangFileType: NewGolangFile(),\n\t\t},\n\t\tbuilder: b,\n\t}\n\n\tfor name, systemNamer := range nameSystems {\n\t\tc.Namers[name] = systemNamer\n\t\tif name == canonicalOrderName {\n\t\t\torderer := namer.Orderer{Namer: systemNamer}\n\t\t\tc.Order = orderer.OrderUniverse(universe)\n\t\t}\n\t}\n\treturn c, nil\n}"} {"input": "package api\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/mozilla/doorman/doorman\"\n)\n\n\n\n\nfunc SetupRoutes(r *gin.Engine, d doorman.Doorman) ", "output": "{\n\tr.Use(ContextMiddleware(d))\n\n\ta := r.Group(\"\")\n\ta.Use(AuthnMiddleware(d))\n\ta.POST(\"/allowed\", allowedHandler)\n\n\tsources := d.ConfigSources()\n\tr.POST(\"/__reload__\", reloadHandler(sources))\n\n\tr.GET(\"/__lbheartbeat__\", lbHeartbeatHandler)\n\tr.GET(\"/__heartbeat__\", heartbeatHandler)\n\tr.GET(\"/__version__\", versionHandler)\n\tr.GET(\"/__api__\", YAMLAsJSONHandler(\"api/openapi.yaml\"))\n\tr.GET(\"/contribute.json\", YAMLAsJSONHandler(\"api/contribute.yaml\"))\n}"} {"input": "package keymanager\n\nimport (\n\t\"launchpad.net/juju-core/state/api\"\n\t\"launchpad.net/juju-core/state/api/params\"\n\t\"launchpad.net/juju-core/utils/ssh\"\n)\n\n\ntype Client struct {\n\tst *api.State\n}\n\n\nfunc NewClient(st *api.State) *Client {\n\treturn &Client{st}\n}\n\n\nfunc (c *Client) Close() error {\n\treturn c.st.Close()\n}\n\n\nfunc (c *Client) ListKeys(mode ssh.ListMode, users ...string) ([]params.StringsResult, error) {\n\tp := params.ListSSHKeys{Mode: mode}\n\tp.Entities.Entities = make([]params.Entity, len(users))\n\tfor i, userName := range users {\n\t\tp.Entities.Entities[i] = params.Entity{Tag: userName}\n\t}\n\tresults := new(params.StringsResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"ListKeys\", p, results)\n\treturn results.Results, err\n}\n\n\n\n\n\nfunc (c *Client) DeleteKeys(user string, keys ...string) ([]params.ErrorResult, error) {\n\tp := params.ModifyUserSSHKeys{User: user, Keys: keys}\n\tresults := new(params.ErrorResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"DeleteKeys\", p, results)\n\treturn results.Results, err\n}\n\n\nfunc (c *Client) ImportKeys(user string, keyIds ...string) ([]params.ErrorResult, error) {\n\tp := params.ModifyUserSSHKeys{User: user, Keys: keyIds}\n\tresults := new(params.ErrorResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"ImportKeys\", p, results)\n\treturn results.Results, err\n}\n\nfunc (c *Client) AddKeys(user string, keys ...string) ([]params.ErrorResult, error) ", "output": "{\n\tp := params.ModifyUserSSHKeys{User: user, Keys: keys}\n\tresults := new(params.ErrorResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"AddKeys\", p, results)\n\treturn results.Results, err\n}"} {"input": "package mqtt\n\n\n\n\n\n\ntype PingreqMessage struct {\n\tfixedHeader\n}\n\nvar _ Message = (*PingreqMessage)(nil)\n\n\n\n\nfunc NewPingreqMessage() *PingreqMessage ", "output": "{\n\tmsg := &PingreqMessage{}\n\tmsg.SetType(PINGREQ)\n\n\treturn msg\n}"} {"input": "package utils\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com/golang/glog\"\n)\n\nfunc Attempt(method func() (interface {}, error), attempts, interval int) (interface {},error) {\n\tfor i := 0; i < attempts; i++ {\n\t\tresult, err := method()\n\t\tif err != nil {\n\t\t\ttime.Sleep(interval * time.Second)\n\t\t} else {\n\t\t\treturn result, nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"Failed to implement the method\")\n}\n\n\n\nfunc Forever(method func() error) error ", "output": "{\n\tgo func() {\n\t\tfor {\n\t\t\tif err := method(); err != nil {\n\t\t\t\tglog.Errorf(\"Method failed to execute, error: %s, restarting now\", err)\n\t\t\t}\n\t\t}\n\t}()\n}"} {"input": "package scanner\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestScanner(t *testing.T) ", "output": "{\n\ts := \"teste1234234\"\n\ts1 := s[3:6]\n\ts1[3] = 'q'\n\tt.Logf(\"3 of s is: %T, s1 is: %s\", s[3])\n\tfmt.Printf(\"test\")\n\n}"} {"input": "package chart\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/golang/protobuf/jsonpb\"\n)\n\n\n\n\n\nfunc (msg *Config) UnmarshalJSON(b []byte) error {\n\treturn (&jsonpb.Unmarshaler{\n\t\tAllowUnknownFields: false,\n\t}).Unmarshal(bytes.NewReader(b), msg)\n}\n\n\nfunc (msg *Value) MarshalJSON() ([]byte, error) {\n\tvar buf bytes.Buffer\n\terr := (&jsonpb.Marshaler{\n\t\tEnumsAsInts: false,\n\t\tEmitDefaults: false,\n\t\tOrigName: false,\n\t}).Marshal(&buf, msg)\n\treturn buf.Bytes(), err\n}\n\n\nfunc (msg *Value) UnmarshalJSON(b []byte) error {\n\treturn (&jsonpb.Unmarshaler{\n\t\tAllowUnknownFields: false,\n\t}).Unmarshal(bytes.NewReader(b), msg)\n}\n\nfunc (msg *Config) MarshalJSON() ([]byte, error) ", "output": "{\n\tvar buf bytes.Buffer\n\terr := (&jsonpb.Marshaler{\n\t\tEnumsAsInts: false,\n\t\tEmitDefaults: false,\n\t\tOrigName: false,\n\t}).Marshal(&buf, msg)\n\treturn buf.Bytes(), err\n}"} {"input": "package brackets\n\nimport (\n\t\"testing\"\n)\n\nfunc TestBracket(t *testing.T) {\n\tfor _, tt := range testCases {\n\t\tactual := Bracket(tt.input)\n\t\tif actual != tt.expected {\n\t\t\tt.Fatalf(\"Bracket(%q) was expected to return %v but returned %v.\",\n\t\t\t\ttt.input, tt.expected, actual)\n\t\t}\n\t}\n}\n\n\n\nfunc BenchmarkBracket(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, tt := range testCases {\n\t\t\tBracket(tt.input)\n\t\t}\n\t}\n}"} {"input": "package db\n\nimport (\n\t\"database/sql\"\n\t\"math\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/karolhrdina/misc/hw/pkg/env\"\n\t\"github.com/pkg/errors\"\n\t\"github.com/volatiletech/sqlboiler/drivers/sqlboiler-psql/driver\"\n)\n\ntype User struct {\n\tName string\n\tPassword string\n}\n\n\nfunc UserFromEnv(prefix string) *User {\n\tdefaultUser := \"postgres\"\n\tdefaultPass := \"\"\n\tname := env.GetVar(prefix+\"_USER\", defaultUser)\n\tpass := env.GetVar(prefix+\"_PASS\", defaultPass)\n\treturn &User{Name: name, Password: pass}\n}\n\n\ntype Connection struct {\n\tUser User\n\tDBName string\n\tHost string\n\tPort int\n\tSSLMode string\n\tMaxConns int\n}\n\n\n\n\nfunc (c *Connection) String() string {\n\tconnstring := driver.PSQLBuildQueryString(\n\t\tc.User.Name,\n\t\tc.User.Password,\n\t\tc.DBName,\n\t\tc.Host,\n\t\tc.Port,\n\t\tc.SSLMode,\n\t)\n\treturn connstring\n}\n\n\nfunc (c *Connection) Connect() (*sql.DB, error) {\n\ttimeout := 1 * time.Second\n\tvar db *sql.DB\n\tvar err error\n\n\tfor {\n\t\tdb, err = sql.Open(\"postgres\", c.String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = db.Ping()\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(timeout)\n\t\ttimeout = timeout + (time.Duration(math.Log(float64(timeout))) * time.Second)\n\t}\n\n\tdb.SetMaxOpenConns(c.MaxConns)\n\treturn db, nil\n}\n\nfunc ConnectionFromEnv(prefix string) (Connection, error) ", "output": "{\n\tpgPort := prefix + \"_PORT\"\n\n\tport, err := strconv.Atoi(env.GetVar(pgPort, \"5432\"))\n\tif err != nil {\n\t\treturn Connection{}, errors.Errorf(\"error parsing %s as integer\", pgPort)\n\t}\n\n\tpgMaxConns := prefix + \"_MAX_CONNS\"\n\tmaxConns, err := strconv.Atoi(env.GetVar(pgMaxConns, \"10\"))\n\tif err != nil {\n\t\treturn Connection{}, errors.Errorf(\"error parsing %s as integer\", pgMaxConns)\n\t}\n\tc := Connection{\n\t\tUser: *UserFromEnv(prefix),\n\t\tDBName: env.GetVar(prefix+\"_NAME\", \"\"),\n\t\tHost: env.GetVar(prefix+\"_HOST\", \"localhost\"),\n\t\tPort: port,\n\t\tSSLMode: env.GetVar(prefix+\"_SSL_MODE\", \"disable\"),\n\t\tMaxConns: maxConns,\n\t}\n\treturn c, nil\n}"} {"input": "package logging\n\nimport (\n\t\"time\"\n\n\t\"github.com/urandom/readeef/content\"\n\t\"github.com/urandom/readeef/content/repo\"\n\t\"github.com/urandom/readeef/log\"\n)\n\ntype tagRepo struct {\n\trepo.Tag\n\n\tlog log.Log\n}\n\nfunc (r tagRepo) Get(id content.TagID, user content.User) (content.Tag, error) {\n\tstart := time.Now()\n\n\ttag, err := r.Tag.Get(id, user)\n\n\tr.log.Infof(\"repo.Tag.Get took %s\", time.Now().Sub(start))\n\n\treturn tag, err\n}\n\nfunc (r tagRepo) ForUser(user content.User) ([]content.Tag, error) {\n\tstart := time.Now()\n\n\ttags, err := r.Tag.ForUser(user)\n\n\tr.log.Infof(\"repo.Tag.ForUser took %s\", time.Now().Sub(start))\n\n\treturn tags, err\n}\n\n\n\nfunc (r tagRepo) FeedIDs(tag content.Tag, user content.User) ([]content.FeedID, error) {\n\tstart := time.Now()\n\n\tids, err := r.Tag.FeedIDs(tag, user)\n\n\tr.log.Infof(\"repo.Tag.FeedIDs took %s\", time.Now().Sub(start))\n\n\treturn ids, err\n}\n\nfunc (r tagRepo) ForFeed(feed content.Feed, user content.User) ([]content.Tag, error) ", "output": "{\n\tstart := time.Now()\n\n\ttags, err := r.Tag.ForFeed(feed, user)\n\n\tr.log.Infof(\"repo.Tag.ForFeed took %s\", time.Now().Sub(start))\n\n\treturn tags, err\n}"} {"input": "package raw\n\nimport (\n\t\"fmt\"\n\t\"../../platforms/common\"\n)\n\ntype FieldMacros struct {}\n\nfunc (FieldMacros) DecodeDW0() {\n\tmacro := common.GetMacro()\n\tmacro.Add(fmt.Sprintf(\"0x%0.8x\", macro.Register(common.PAD_CFG_DW0).ValueGet()))\n}\n\nfunc (FieldMacros) DecodeDW1() {\n\tmacro := common.GetMacro()\n\tmacro.Add(fmt.Sprintf(\"0x%0.8x\", macro.Register(common.PAD_CFG_DW1).ValueGet()))\n}\n\n\n\n\nfunc (bitfields FieldMacros) GenerateString() ", "output": "{\n\tmacro := common.GetMacro()\n\tmacro.Add(\"_PAD_CFG_STRUCT(\").Id().Add(\", \")\n\tbitfields.DecodeDW0()\n\tmacro.Add(\", \")\n\tbitfields.DecodeDW1()\n\tmacro.Add(\"),\")\n}"} {"input": "package mock\n\nimport (\n\t\"github.com/fkmhrk/OpenInvoice/v1/model/env\"\n)\n\ntype EnvDAO struct {\n\tCreateResult env.Env\n\tGetResult env.Env\n\tGetListResult []*env.Env\n\tSaveResult error\n\tUpdateResult env.Env\n\tDeleteResult env.Env\n}\n\nfunc (d *EnvDAO) Create(key, value string) (env.Env, error) {\n\treturn d.CreateResult, nil\n}\n\nfunc (d *EnvDAO) Get(key string) (env.Env, error) {\n\treturn d.GetResult, nil\n}\n\nfunc (d *EnvDAO) GetList() ([]*env.Env, error) {\n\treturn d.GetListResult, nil\n}\n\n\n\nfunc (d *EnvDAO) Update(key, value string) (env.Env, error) {\n\treturn d.UpdateResult, nil\n}\n\nfunc (d *EnvDAO) Delete(key string) (env.Env, error) {\n\treturn d.DeleteResult, nil\n}\n\nfunc (d *EnvDAO) Save(list []*env.Env) error ", "output": "{\n\treturn d.SaveResult\n}"} {"input": "package elasticsearch_test\n\nimport (\n\t\"crypto/tls\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/elastic/go-elasticsearch/v7\"\n\t\"github.com/elastic/go-elasticsearch/v7/estransport\"\n)\n\nfunc init() {\n\tlog.SetFlags(0)\n}\n\nfunc ExampleNewDefaultClient() {\n\tes, err := elasticsearch.NewDefaultClient()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error creating the client: %s\\n\", err)\n\t}\n\n\tres, err := es.Info()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error getting the response: %s\\n\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tlog.Print(es.Transport.(*estransport.Client).URLs())\n}\n\nfunc ExampleNewClient() {\n\tcfg := elasticsearch.Config{\n\t\tAddresses: []string{\n\t\t\t\"http:localhost:9200\",\n\t\t},\n\t\tUsername: \"foo\",\n\t\tPassword: \"bar\",\n\t\tTransport: &http.Transport{\n\t\t\tMaxIdleConnsPerHost: 10,\n\t\t\tResponseHeaderTimeout: time.Second,\n\t\t\tDialContext: (&net.Dialer{Timeout: time.Second}).DialContext,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tMinVersion: tls.VersionTLS11,\n\t\t\t},\n\t\t},\n\t}\n\n\tes, _ := elasticsearch.NewClient(cfg)\n\tlog.Print(es.Transport.(*estransport.Client).URLs())\n}\n\n\n\nfunc ExampleNewClient_logger() ", "output": "{\n\n\n\tcfg := elasticsearch.Config{\n\t\tLogger: &estransport.ColorLogger{Output: os.Stdout},\n\t}\n\n\telasticsearch.NewClient(cfg)\n}"} {"input": "package random\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/google/uuid\"\n)\n\nconst (\n\tmaxNameLength = 63\n)\n\ntype Interface interface {\n\tName() (string, error)\n}\n\ntype impl struct {\n\tsslCertificateNamePrefix string\n}\n\nfunc New(sslCertificateNamePrefix string) Interface {\n\treturn impl{sslCertificateNamePrefix: sslCertificateNamePrefix}\n}\n\n\n\n\nfunc (r impl) Name() (string, error) ", "output": "{\n\tif uid, err := uuid.NewRandom(); err != nil {\n\t\treturn \"\", err\n\t} else {\n\t\tgeneratedName := fmt.Sprintf(\"%s%s\", r.sslCertificateNamePrefix, uid.String())\n\t\tmaxLength := maxNameLength\n\t\tif len(generatedName) < maxLength {\n\t\t\tmaxLength = len(generatedName)\n\t\t}\n\n\t\treturn generatedName[:maxLength], nil\n\t}\n}"} {"input": "package wml\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\ntype CT_Markup struct {\n\tIdAttr int64\n}\n\nfunc NewCT_Markup() *CT_Markup {\n\tret := &CT_Markup{}\n\treturn ret\n}\n\n\n\nfunc (m *CT_Markup) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"id\" {\n\t\t\tparsed, err := strconv.ParseInt(attr.Value, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.IdAttr = parsed\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_Markup: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (m *CT_Markup) Validate() error {\n\treturn m.ValidateWithPath(\"CT_Markup\")\n}\n\n\nfunc (m *CT_Markup) ValidateWithPath(path string) error {\n\treturn nil\n}\n\nfunc (m *CT_Markup) MarshalXML(e *xml.Encoder, start xml.StartElement) error ", "output": "{\n\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"w:id\"},\n\t\tValue: fmt.Sprintf(\"%v\", m.IdAttr)})\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}"} {"input": "package registry\n\nimport (\n\t\"time\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors\"\n\n\t\"github.com/openshift/origin/pkg/auth/api\"\n\t\"github.com/openshift/origin/pkg/oauth/registry/accesstoken\"\n\t\"github.com/openshift/origin/pkg/oauth/scope\"\n)\n\ntype TokenAuthenticator struct {\n\tregistry accesstoken.Registry\n}\n\nfunc NewTokenAuthenticator(registry accesstoken.Registry) *TokenAuthenticator {\n\treturn &TokenAuthenticator{\n\t\tregistry: registry,\n\t}\n}\n\n\n\nfunc (a *TokenAuthenticator) AuthenticateToken(value string) (api.UserInfo, bool, error) ", "output": "{\n\ttoken, err := a.registry.GetAccessToken(value)\n\tif errors.IsNotFound(err) {\n\t\treturn nil, false, nil\n\t}\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tif token.CreationTimestamp.Time.Add(time.Duration(token.AuthorizeToken.ExpiresIn) * time.Second).Before(time.Now()) {\n\t\treturn nil, false, nil\n\t}\n\treturn &api.DefaultUserInfo{\n\t\tName: token.AuthorizeToken.UserName,\n\t\tUID: token.AuthorizeToken.UserUID,\n\t\tScope: scope.Join(token.AuthorizeToken.Scopes),\n\t}, true, nil\n}"} {"input": "package doctor\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestOk(t *testing.T) {\n\tinitializingStatus := HealthcheckStatusInitializing\n\tokStatus := HealthcheckStatusOk\n\timpairedStatus := HealthcheckStatusImpaired\n\tassert.True(t, initializingStatus.Ok())\n\tassert.True(t, okStatus.Ok())\n\tassert.False(t, impairedStatus.Ok())\n}\n\ntype testHealthcheckStatus struct {\n\tSomeStatus HealthcheckStatus `json:\"status\"`\n}\n\n\n\nfunc TestUnmarshalHealthcheckStatus(t *testing.T) ", "output": "{\n\tstatus := HealthcheckStatusInitializing\n\n\terr := json.Unmarshal([]byte(`\"INITIALIZING\"`), &status)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif status != HealthcheckStatusInitializing {\n\t\tt.Error(\"INITIALIZING should unmarshal to INITIALIZING, not \" + status.String())\n\t}\n\n\tvar test testHealthcheckStatus\n\terr = json.Unmarshal([]byte(`{\"status\":\"IMPAIRED\"}`), &test)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif test.SomeStatus != HealthcheckStatusImpaired {\n\t\tt.Error(\"IMPAIRED should unmarshal to IMPAIRED, not \" + test.SomeStatus.String())\n\t}\n}"} {"input": "package metrics\n\nimport \"testing\"\n\n\n\nfunc TestGenerateMetricNamesMap(t *testing.T) ", "output": "{\n\n\tmetricNamesMap := generateMetricNamesMap()\n\n\tif len(metricNamesMap) != 93 {\n\t\tt.Errorf(\"Expected mapping-size=%d; actual %d\", 93, len(metricNamesMap))\n\t}\n\n\tactual, ok := metricNamesMap[testKey1]\n\n\tif !ok {\n\t\tt.Errorf(\"No metric name mapping found for %s\", testKey1)\n\t} else {\n\t\tif actual.name != testElement1Name {\n\t\t\tt.Errorf(\"Expected metric name=%s; actual %s\", testElement1Name, actual.name)\n\t\t}\n\t}\n}"} {"input": "package additional\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\n\n\nfunc Test_NewArtboard_2(t *testing.T) {\n\tdata, err := ioutil.ReadFile(\"./testdata/artb_2\")\n\trequire.NoError(t, err)\n\tartboard, err := NewArtboard(data)\n\trequire.NoError(t, err)\n\tassert.Equal(t, &Artboard{\n\t\tText: \"\\x00\",\n\t\tType: 1,\n\t\tColor: &ArtboardColor{\n\t\t\tRed: 255,\n\t\t\tGreen: 255,\n\t\t\tBlue: 255,\n\t\t},\n\t\tRect: &ArtboardRect{\n\t\t\tTop: 0,\n\t\t\tLeft: 1570,\n\t\t\tBottom: 1068,\n\t\t\tRight: 2627,\n\t\t},\n\t}, artboard)\n}\n\nfunc Test_NewArtboard_1(t *testing.T) ", "output": "{\n\tdata, err := ioutil.ReadFile(\"./testdata/artb_1\")\n\trequire.NoError(t, err)\n\tartboard, err := NewArtboard(data)\n\trequire.NoError(t, err)\n\tassert.Equal(t, &Artboard{\n\t\tText: \"iPhone 6\\x00\",\n\t\tType: 1,\n\t\tColor: &ArtboardColor{\n\t\t\tRed: 255,\n\t\t\tGreen: 255,\n\t\t\tBlue: 255,\n\t\t},\n\t\tRect: &ArtboardRect{\n\t\t\tTop: 0,\n\t\t\tLeft: 750,\n\t\t\tBottom: 1334,\n\t\t\tRight: 1500,\n\t\t},\n\t}, artboard)\n}"} {"input": "package util\n\ntype Progress struct {\n\terrs chan error\n\tdone chan struct{}\n}\n\nfunc NewProgress(total int) *Progress {\n\tp := &Progress{make(chan error), make(chan struct{})}\n\tgo func() {\n\t\tcompleted := 0\n\t\terrorCount := 0\n\t\tfor err := range p.errs {\n\t\t\tif err == nil {\n\t\t\t\tcompleted += 1\n\t\t\t} else {\n\t\t\t\terrorCount += 1\n\t\t\t\tif FlagQuiet {\n\t\t\t\t\tWarnf(\"%s\", err)\n\t\t\t\t} else {\n\t\t\t\t\tWarnf(\"\\r%s \\n\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tratio := 100.0 * (float64(completed) / float64(total))\n\t\t\tVerbosef(\"\\r%d of %d jobs complete (%0.2f%% done, %d errors)\",\n\t\t\t\tcompleted, total, ratio, errorCount)\n\t\t}\n\t\tVerbosef(\"\\n\")\n\t\tp.done <- struct{}{}\n\t}()\n\treturn p\n}\n\nfunc (p *Progress) JobDone(err error) {\n\tif p == nil {\n\t\treturn\n\t}\n\tp.errs <- err\n}\n\n\n\nfunc (p *Progress) Close() ", "output": "{\n\tif p == nil {\n\t\treturn\n\t}\n\tclose(p.errs)\n\t<-p.done\n}"} {"input": "package main\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestHostLocal(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"plugins/ipam/host-local\")\n}"} {"input": "package envelope_extensions\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\n\t\"github.com/cloudfoundry/sonde-go/events\"\n)\n\nconst SystemAppId = \"system\"\n\ntype hasAppId interface {\n\tGetApplicationId() *events.UUID\n}\n\n\n\nfunc formatUUID(uuid *events.UUID) string {\n\tvar uuidBytes [16]byte\n\tbinary.LittleEndian.PutUint64(uuidBytes[:8], uuid.GetLow())\n\tbinary.LittleEndian.PutUint64(uuidBytes[8:], uuid.GetHigh())\n\treturn fmt.Sprintf(\"%x-%x-%x-%x-%x\", uuidBytes[0:4], uuidBytes[4:6], uuidBytes[6:8], uuidBytes[8:10], uuidBytes[10:])\n}\n\nfunc GetAppId(envelope *events.Envelope) string ", "output": "{\n\tif envelope.GetEventType() == events.Envelope_LogMessage {\n\t\treturn envelope.GetLogMessage().GetAppId()\n\t}\n\n\tif envelope.GetEventType() == events.Envelope_ContainerMetric {\n\t\treturn envelope.GetContainerMetric().GetApplicationId()\n\t}\n\n\tvar event hasAppId\n\tswitch envelope.GetEventType() {\n\tcase events.Envelope_HttpStart:\n\t\tevent = envelope.GetHttpStart()\n\tcase events.Envelope_HttpStop:\n\t\tevent = envelope.GetHttpStop()\n\tcase events.Envelope_HttpStartStop:\n\t\tevent = envelope.GetHttpStartStop()\n\tdefault:\n\t\treturn SystemAppId\n\t}\n\n\tuuid := event.GetApplicationId()\n\tif uuid != nil {\n\t\treturn formatUUID(uuid)\n\t}\n\treturn SystemAppId\n}"} {"input": "package gsf\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n)\n\nfunc ConvertStruct(src, dest interface{}) error {\n\tt1, err := typeOf(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tt2, err := typeOf(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv1, err := valueOf(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv2, err := valueOf(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor i := 0; i < t1.NumField(); i++ {\n\t\tf1 := t1.Field(i)\n\t\tif f1.Anonymous {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := 0; j < t2.NumField(); j++ {\n\t\t\tf2 := t2.Field(j)\n\t\t\tif f2.Anonymous {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif f1.Type.Kind() != f2.Type.Kind() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.EqualFold(f1.Name, f2.Name) {\n\t\t\t\tv2.Field(j).Set(v1.Field(i))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\nfunc typeOf(s interface{}) (reflect.Type, error) {\n\terr := mustPtr(s)\n\tif err != nil {\n\t\treturn reflect.TypeOf(s), err\n\t}\n\treturn reflect.TypeOf(s).Elem(), nil\n}\n\nfunc valueOf(s interface{}) (reflect.Value, error) {\n\terr := mustPtr(s)\n\tif err != nil {\n\t\treturn reflect.Value{}, err\n\t}\n\treturn reflect.ValueOf(s).Elem(), nil\n}\n\nfunc mustPtr(s interface{}) error ", "output": "{\n\tif s == nil {\n\t\treturn errors.New(\"gsf: cannot copy nil pointer\")\n\t}\n\tv := reflect.ValueOf(s)\n\tif v.Kind() != reflect.Ptr {\n\t\treturn errors.New(fmt.Sprintf(\"gsf: %v must be reflect.Ptr\", v.Type().Name()))\n\t}\n\tif v.IsNil() {\n\t\treturn errors.New(\"gsf: cannot copy nil pointer\")\n\t}\n\treturn nil\n}"} {"input": "package stats\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"sync\"\n\n\tmultierror \"github.com/hashicorp/go-multierror\"\n\t\"github.com/shirou/gopsutil/cpu\"\n)\n\nvar (\n\tcpuMhzPerCore float64\n\tcpuModelName string\n\tcpuNumCores int\n\tcpuTotalTicks float64\n\n\tinitErr error\n\tonceLer sync.Once\n)\n\nfunc Init() error {\n\tonceLer.Do(func() {\n\t\tvar merrs *multierror.Error\n\t\tvar err error\n\t\tif cpuNumCores, err = cpu.Counts(true); err != nil {\n\t\t\tmerrs = multierror.Append(merrs, fmt.Errorf(\"Unable to determine the number of CPU cores available: %v\", err))\n\t\t}\n\n\t\tvar cpuInfo []cpu.InfoStat\n\t\tif cpuInfo, err = cpu.Info(); err != nil {\n\t\t\tmerrs = multierror.Append(merrs, fmt.Errorf(\"Unable to obtain CPU information: %v\", initErr))\n\t\t}\n\n\t\tfor _, cpu := range cpuInfo {\n\t\t\tcpuModelName = cpu.ModelName\n\t\t\tcpuMhzPerCore = cpu.Mhz\n\t\t\tbreak\n\t\t}\n\n\t\tcpuMhzPerCore = math.Floor(cpuMhzPerCore)\n\t\tcpuTotalTicks = math.Floor(float64(cpuNumCores) * cpuMhzPerCore)\n\n\t\tinitErr = merrs.ErrorOrNil()\n\t})\n\treturn initErr\n}\n\n\nfunc CPUNumCores() int {\n\treturn cpuNumCores\n}\n\n\n\n\n\nfunc CPUModelName() string {\n\treturn cpuModelName\n}\n\n\nfunc TotalTicksAvailable() float64 {\n\treturn cpuTotalTicks\n}\n\nfunc CPUMHzPerCore() float64 ", "output": "{\n\treturn cpuMhzPerCore\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/bitly/go-nsq\"\n\t\"log\"\n\t\"time\"\n)\n\nvar (\n\tPublisher *MsgPublisher\n)\n\ntype MsgPublisher struct {\n\tusr User\n\twriter *nsq.Writer\n}\n\n\n\nfunc (publisher *MsgPublisher) SetLoginUsr(_usr User) error {\n\tif Publisher == nil {\n\t\tPublisher = &MsgPublisher{\n\t\t\twriter: nsq.NewWriter(\"106.186.31.48:4150\"),\n\t\t}\n\t}\n\tPublisher.usr = _usr\n\tPublisher.usr.Pwd = \"xxxx\"\n\treturn nil\n}\n\nfunc (mp *MsgPublisher) Write(topic, msg string) (int32, []byte, error) {\n\tm := Message{\n\t\tTopic: topic,\n\t\tType: MSG_TYPE_CHAT,\n\t\tTime: time.Now().Format(\"2006-01-02 15:04:05\"),\n\t\tBody: MessageBody{\n\t\t\tFrom: mp.usr,\n\t\t\tMsg: msg,\n\t\t},\n\t}\n\tmsgBytes, _ := json.Marshal(m)\n\tlog.Println(\"Publish.msg = \", string(msgBytes))\n\treturn mp.writer.Publish(topic, msgBytes)\n}\n\nfunc (mp *MsgPublisher) WriteAsync(topic, msg string, responseChan chan *nsq.WriterTransaction) error {\n\tm := Message{\n\t\tTopic: topic,\n\t\tType: MSG_TYPE_CHAT,\n\t\tBody: MessageBody{\n\t\t\tFrom: mp.usr,\n\t\t\tMsg: msg,\n\t\t},\n\t}\n\tmsgBytes, _ := json.Marshal(m)\n\tlog.Println(\"PublishAsync.msg = \", string(msgBytes))\n\treturn mp.writer.PublishAsync(topic, msgBytes, responseChan, \"\")\n}\n\nfunc (mp *MsgPublisher) Stop() {\n\tmp.writer.Stop()\n}\n\nfunc init() ", "output": "{\n\tPublisher = &MsgPublisher{\n\t\twriter: nsq.NewWriter(\"106.186.31.48:4150\"),\n\t}\n}"} {"input": "package validator\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\nfunc IsNull(str string) bool {\n\treturn len(str) == 0\n}\n\nfunc IsWord(str string, params ...int) bool {\n\tif IsNull(str) {\n\t\treturn false\n\t}\n\treturn rxWord.MatchString(str)\n}\n\nfunc IsTime(str string, format string) bool {\n\t_, err := time.Parse(format, str)\n\treturn err == nil\n}\n\nfunc IsDate(str string, format ...string) bool {\n\n\tif len(format) == 0 {\n\n\t\tif len(strings.Split(str, \"/\")) > 1 {\n\t\t\treturn IsTime(str, \"2006/01/02\")\n\t\t}\n\n\t\tif len(strings.Split(str, \"-\")) > 1 {\n\t\t\treturn IsTime(str, \"2006-01-02\")\n\t\t}\n\n\t\treturn false\n\t}\n\n\treturn IsTime(str, format[0])\n}\n\n\n\nfunc IsRequestURI(rawurl string) bool {\n\t_, err := url.ParseRequestURI(rawurl)\n\treturn err == nil\n}\n\nfunc IsURI(str string) bool {\n\trelation := false\n\tfor idx, val := range str {\n\t\tif val == '.' {\n\t\t\trelation = true\n\t\t\tcontinue\n\t\t}\n\t\tif val == '/' || val == '\\\\' {\n\t\t\tif idx < len(str)-1 {\n\t\t\t\tif str[idx+1] == '.' {\n\t\t\t\t\trelation = true\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif relation && (val != '/' && val != '\\\\') {\n\t\t\treturn false\n\t\t}\n\t\treturn IsRequestURI(str[idx:])\n\t}\n\treturn false\n}\n\nfunc IsMobilePhone(str string) bool {\n\tif IsEmpty(str) {\n\t\treturn false\n\t}\n\treturn rxMobolePhone.MatchString(str)\n}\n\nfunc IsEmpty(str string) bool ", "output": "{\n\treturn len(strings.TrimSpace(str)) == 0\n}"} {"input": "package filter\n\nimport (\n\t\"github.com/m3db/m3/src/aggregator/sharding\"\n\t\"github.com/m3db/m3/src/msg/producer\"\n)\n\ntype shardSetFilter struct {\n\tshardSet sharding.ShardSet\n}\n\n\n\n\nfunc (f shardSetFilter) Filter(m producer.Message) bool {\n\t_, ok := f.shardSet[m.Shard()]\n\treturn ok\n}\n\nfunc NewShardSetFilter(shardSet sharding.ShardSet) producer.FilterFunc ", "output": "{\n\tf := shardSetFilter{shardSet: shardSet}\n\treturn f.Filter\n}"} {"input": "package stop\n\nimport (\n\t\"github.com/seehuhn/classification/data\"\n)\n\n\n\n\n\ntype Function func(data.Histogram) bool\n\n\n\n\n\n\nfunc IfAtMost(n float64) Function {\n\treturn func(hist data.Histogram) bool {\n\t\treturn hist.Sum() <= n\n\t}\n}\n\n\n\nfunc IfPure(hist data.Histogram) bool {\n\tk := 0\n\tfor _, ni := range hist {\n\t\tif ni > 0 {\n\t\t\tk++\n\t\t\tif k > 1 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\n\nfunc IfPureOrAtMost(n float64) Function ", "output": "{\n\treturn func(hist data.Histogram) bool {\n\t\ttotal := 0.0\n\t\tk := 0\n\t\tfor _, ni := range hist {\n\t\t\ttotal += ni\n\t\t\tif ni > 0 {\n\t\t\t\tk++\n\t\t\t}\n\t\t\tif k > 1 && total > n {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\nfunc init() {\n\td1 := &D1{}\n\tchallenges[1] = &challenge{\"Day 01\", \"input/day01.txt\", d1}\n}\n\n\nfunc MFR(mass int) int {\n\treturn (mass / 3) - 2\n}\n\ntype D1 struct {\n\tmodules []int\n}\n\nfunc (d1 *D1) parse(line string) error {\n\tv, err := strconv.Atoi(line)\n\tif err == nil {\n\t\td1.modules = append(d1.modules, v)\n\t}\n\treturn err\n}\n\n\n\nfunc TotalMFR(mass int) int {\n\treq := MFR(mass)\n\tif req > 0 {\n\t\treq += TotalMFR(req)\n\t} else {\n\t\treq = 0\n\t}\n\treturn req\n}\n\nfunc (d1 *D1) part2() (string, error) {\n\tsum := 0\n\tfor _, module := range d1.modules {\n\t\tsum += TotalMFR(module)\n\t}\n\treturn fmt.Sprintf(\"Sum of fuel requirements is %d\", sum), nil\n}\n\nfunc (d1 *D1) part1() (string, error) ", "output": "{\n\tsum := 0\n\tfor _, module := range d1.modules {\n\t\tsum += MFR(module)\n\t}\n\treturn fmt.Sprintf(\"Sum of fuel requirements is %d\", sum), nil\n}"} {"input": "package factory\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/testapi\"\n\t\"k8s.io/kubernetes/pkg/storage/etcd/testing/testingcert\"\n\t\"k8s.io/kubernetes/pkg/storage/storagebackend\"\n\n\t\"github.com/coreos/etcd/integration\"\n\t\"github.com/coreos/etcd/pkg/transport\"\n)\n\nfunc TestTLSConnection(t *testing.T) {\n\tcertFile, keyFile, caFile := configureTLSCerts(t)\n\n\ttlsInfo := &transport.TLSInfo{\n\t\tCertFile: certFile,\n\t\tKeyFile: keyFile,\n\t\tCAFile: caFile,\n\t}\n\n\tcluster := integration.NewClusterV3(t, &integration.ClusterConfig{\n\t\tSize: 1,\n\t\tClientTLS: tlsInfo,\n\t})\n\tdefer cluster.Terminate(t)\n\n\tcfg := storagebackend.Config{\n\t\tType: storagebackend.StorageTypeETCD3,\n\t\tServerList: []string{cluster.Members[0].GRPCAddr()},\n\t\tCertFile: certFile,\n\t\tKeyFile: keyFile,\n\t\tCAFile: caFile,\n\t\tCodec: testapi.Default.Codec(),\n\t}\n\tstorage, destroyFunc, err := newETCD3Storage(cfg)\n\tdefer destroyFunc()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = storage.Create(context.TODO(), \"/abc\", &api.Pod{}, nil, 0)\n\tif err != nil {\n\t\tt.Fatalf(\"Create failed: %v\", err)\n\t}\n}\n\n\n\nfunc configureTLSCerts(t *testing.T) (certFile, keyFile, caFile string) ", "output": "{\n\tbaseDir := os.TempDir()\n\ttempDir, err := ioutil.TempDir(baseDir, \"etcd_certificates\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcertFile = path.Join(tempDir, \"etcdcert.pem\")\n\tif err := ioutil.WriteFile(certFile, []byte(testingcert.CertFileContent), 0644); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tkeyFile = path.Join(tempDir, \"etcdkey.pem\")\n\tif err := ioutil.WriteFile(keyFile, []byte(testingcert.KeyFileContent), 0644); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcaFile = path.Join(tempDir, \"ca.pem\")\n\tif err := ioutil.WriteFile(caFile, []byte(testingcert.CAFileContent), 0644); err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn certFile, keyFile, caFile\n}"} {"input": "package gorocksdb\n\nimport (\n\t\"testing\"\n\n\t\"github.com/facebookgo/ensure\"\n)\n\nfunc TestSliceTransform(t *testing.T) {\n\tdb := newTestDB(t, \"TestSliceTransform\", func(opts *Options) {\n\t\topts.SetPrefixExtractor(&testSliceTransform{})\n\t})\n\tdefer db.Close()\n\n\two := NewDefaultWriteOptions()\n\tensure.Nil(t, db.Put(wo, []byte(\"foo1\"), []byte(\"foo\")))\n\tensure.Nil(t, db.Put(wo, []byte(\"foo2\"), []byte(\"foo\")))\n\tensure.Nil(t, db.Put(wo, []byte(\"bar1\"), []byte(\"bar\")))\n\n\titer := db.NewIterator(NewDefaultReadOptions())\n\tdefer iter.Close()\n\tprefix := []byte(\"foo\")\n\tnumFound := 0\n\tfor iter.Seek(prefix); iter.ValidForPrefix(prefix); iter.Next() {\n\t\tnumFound++\n\t}\n\tensure.Nil(t, iter.Err())\n\tensure.DeepEqual(t, numFound, 2)\n}\n\nfunc TestFixedPrefixTransformOpen(t *testing.T) {\n\tdb := newTestDB(t, \"TestFixedPrefixTransformOpen\", func(opts *Options) {\n\t\topts.SetPrefixExtractor(NewFixedPrefixTransform(3))\n\t})\n\tdefer db.Close()\n}\n\n\n\ntype testSliceTransform struct {\n\tinitiated bool\n}\n\nfunc (st *testSliceTransform) Name() string { return \"gorocksdb.test\" }\nfunc (st *testSliceTransform) Transform(src []byte) []byte { return src[0:3] }\nfunc (st *testSliceTransform) InDomain(src []byte) bool { return len(src) >= 3 }\nfunc (st *testSliceTransform) InRange(src []byte) bool { return len(src) == 3 }\n\nfunc TestNewNoopPrefixTransform(t *testing.T) ", "output": "{\n\tdb := newTestDB(t, \"TestNewNoopPrefixTransform\", func(opts *Options) {\n\t\topts.SetPrefixExtractor(NewNoopPrefixTransform())\n\t})\n\tdefer db.Close()\n}"} {"input": "package lnwire\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\ntype NeighborAckMessage struct {\n\tRoutingMessageBase\n}\n\n\n\nfunc (msg *NeighborAckMessage) Command() uint32{\n\treturn CmdNeighborAckMessage\n}\n\nfunc (msg *NeighborAckMessage) Encode(w io.Writer, pver uint32) error{\n\treturn nil\n}\n\nfunc (msg *NeighborAckMessage) Decode(r io.Reader, pver uint32) error{\n\treturn nil\n}\n\nfunc (msg *NeighborAckMessage) MaxPayloadLength(uint32) uint32{\n\treturn 0\n}\n\nfunc (msg *NeighborAckMessage) Validate() error{\n\treturn nil\n}\n\nvar _ Message = (*NeighborAckMessage)(nil)\n\nfunc (msg *NeighborAckMessage) String() string ", "output": "{\n\treturn fmt.Sprintf(\"NeighborAckMessage{%v %v}\", msg.SenderID, msg.ReceiverID)\n}"} {"input": "package animation\n\nimport (\n\t\"time\"\n)\n\ntype GroupedAnimation struct {\n\tanimators []Animator\n\tcallback AnimatorCallback\n}\n\nfunc NewGroupedAnimation(animators []Animator) *GroupedAnimation {\n\treturn &GroupedAnimation{animators, nil}\n}\n\nfunc (a *GroupedAnimation) SetCallback(callback AnimatorCallback) {\n\ta.callback = callback\n}\n\nfunc (a *GroupedAnimation) IsDone() bool {\n\tvar done = true\n\tfor _, animator := range a.animators {\n\t\tif !animator.IsDone() {\n\t\t\tdone = false\n\t\t}\n\t}\n\treturn done\n}\n\nfunc (a *GroupedAnimation) Update(elapsed time.Duration) time.Duration {\n\tvar (\n\t\ttotal time.Duration\n\t\tremainder time.Duration\n\t\tdone = true\n\t)\n\tfor _, animator := range a.animators {\n\t\tremainder = animator.Update(elapsed)\n\t\tif !animator.IsDone() {\n\t\t\tdone = false\n\t\t}\n\t\tif remainder != 0 && (total == 0 || remainder < total) {\n\t\t\ttotal = remainder \n\t\t}\n\t}\n\tif done {\n\t\tif a.callback != nil {\n\t\t\ta.callback()\n\t\t}\n\t\treturn total\n\t}\n\treturn 0\n}\n\n\n\nfunc (a *GroupedAnimation) Delete() {\n\tfor _, animator := range a.animators {\n\t\tanimator.Delete()\n\t}\n\ta.animators = []Animator{}\n}\n\nfunc (a *GroupedAnimation) Reset() ", "output": "{\n\tfor _, animator := range a.animators {\n\t\tanimator.Reset()\n\t}\n}"} {"input": "package eureka\n\nimport (\n\t\"io/ioutil\"\n\t\"strconv\"\n\t\"text/template\"\n\n\t\"github.com/ArthurHlt/go-eureka-client/eureka\"\n\t\"github.com/containous/traefik/log\"\n\t\"github.com/containous/traefik/provider\"\n\t\"github.com/containous/traefik/provider/label\"\n\t\"github.com/containous/traefik/types\"\n)\n\n\n\n\nfunc getInstanceID(instance eureka.InstanceInfo) string {\n\tdefaultID := provider.Normalize(instance.IpAddr) + \"-\" + getPort(instance)\n\treturn label.GetStringValue(instance.Metadata.Map, label.TraefikBackendID, defaultID)\n}\n\nfunc getPort(instance eureka.InstanceInfo) string {\n\tif instance.SecurePort.Enabled {\n\t\treturn strconv.Itoa(instance.SecurePort.Port)\n\t}\n\treturn strconv.Itoa(instance.Port.Port)\n}\n\nfunc getProtocol(instance eureka.InstanceInfo) string {\n\tif instance.SecurePort.Enabled {\n\t\treturn \"https\"\n\t}\n\treturn label.DefaultProtocol\n}\n\nfunc getWeight(instance eureka.InstanceInfo) string {\n\treturn label.GetStringValue(instance.Metadata.Map, label.TraefikWeight, label.DefaultWeight)\n}\n\nfunc (p *Provider) buildConfiguration() (*types.Configuration, error) ", "output": "{\n\tvar EurekaFuncMap = template.FuncMap{\n\t\t\"getPort\": getPort,\n\t\t\"getProtocol\": getProtocol,\n\t\t\"getWeight\": getWeight,\n\t\t\"getInstanceID\": getInstanceID,\n\t}\n\n\teureka.GetLogger().SetOutput(ioutil.Discard)\n\n\tclient := eureka.NewClient([]string{\n\t\tp.Endpoint,\n\t})\n\n\tapplications, err := client.GetApplications()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttemplateObjects := struct {\n\t\tApplications []eureka.Application\n\t}{\n\t\tapplications.Applications,\n\t}\n\n\tconfiguration, err := p.GetConfiguration(\"templates/eureka.tmpl\", EurekaFuncMap, templateObjects)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\treturn configuration, nil\n}"} {"input": "package models\n\nimport \"github.com/nvellon/hal\"\n\ntype Port struct {\n\tId int\n\tCurrentState int\n\tDefaultState int\n\tName string\n}\n\n\n\nfunc (a Port) GetMap() hal.Entry ", "output": "{\n\treturn hal.Entry{\n\t\t\"id\": a.Id,\n\t\t\"current_state\": a.CurrentState,\n\t\t\"default_state\": a.DefaultState,\n\t\t\"name\": a.Name,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path\"\n)\n\nvar pkgloc string\nvar apiFile string\nvar ctxFile string\n\nfunc init() {\n\tgopath := os.Getenv(\"GOPATH\")\n\tpkgloc = path.Join(gopath, \"src/gorgonia.org/cu\")\n\tapiFile = path.Join(pkgloc, \"api.go\")\n\tctxFile = path.Join(pkgloc, \"ctx_api.go\")\n}\n\n\n\nfunc generateContextFile(gss []*GoSignature) {\n\tg, err := os.Create(ctxFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer g.Close()\n\tg.WriteString(header)\n\tgenerateContextAPI(g, gss)\n}\n\nfunc main() {\n\tsigs := Parse()\n\n\tvar gss []*GoSignature\n\tsigs = filterCSigs(sigs)\n\tfor _, sig := range sigs {\n\t\tgs := sig.GoSig()\n\t\tgss = append(gss, gs)\n\t}\n\n\tgenerateAPIFile(gss)\n\tgenerateContextFile(gss)\n\n\tvar err error\n\tfilename := apiFile\n\tcmd := exec.Command(\"goimports\", \"-w\", filename)\n\tif err = cmd.Run(); err != nil {\n\t\tlog.Fatalf(\"Go imports failed with %v for %q\", err, filename)\n\t}\n\n\tfilename = ctxFile\n\tcmd = exec.Command(\"goimports\", \"-w\", filename)\n\tif err = cmd.Run(); err != nil {\n\t\tlog.Fatalf(\"Go imports failed with %v for %q\", err, filename)\n\t}\n}\n\nfunc generateAPIFile(gss []*GoSignature) ", "output": "{\n\tf, err := os.Create(apiFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\n\tf.WriteString(header)\n\tgenerateAPI(f, gss)\n}"} {"input": "package channelling\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"log\"\n\n\t\"github.com/strukturag/spreed-webrtc/go/buffercache\"\n)\n\ntype IncomingDecoder interface {\n\tDecodeIncoming(buffercache.Buffer) (*DataIncoming, error)\n}\n\ntype OutgoingEncoder interface {\n\tEncodeOutgoing(*DataOutgoing) (buffercache.Buffer, error)\n}\n\ntype Codec interface {\n\tNewBuffer() buffercache.Buffer\n\tIncomingDecoder\n\tOutgoingEncoder\n}\n\ntype incomingCodec struct {\n\tbuffers buffercache.BufferCache\n\tincomingLimit int\n}\n\nfunc NewCodec(incomingLimit int) Codec {\n\treturn &incomingCodec{buffercache.NewBufferCache(1024, bytes.MinRead), incomingLimit}\n}\n\nfunc (codec incomingCodec) NewBuffer() buffercache.Buffer {\n\treturn codec.buffers.New()\n}\n\n\n\nfunc (codec incomingCodec) EncodeOutgoing(outgoing *DataOutgoing) (buffercache.Buffer, error) {\n\tb := codec.NewBuffer()\n\tif err := json.NewEncoder(b).Encode(outgoing); err != nil {\n\t\tlog.Println(\"Error while encoding JSON\", err)\n\t\tb.Decref()\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}\n\nfunc (codec incomingCodec) DecodeIncoming(b buffercache.Buffer) (*DataIncoming, error) ", "output": "{\n\tlength := b.GetBuffer().Len()\n\tif length > codec.incomingLimit {\n\t\treturn nil, errors.New(\"Incoming message size limit exceeded\")\n\t}\n\tincoming := &DataIncoming{}\n\treturn incoming, json.Unmarshal(b.Bytes(), incoming)\n}"} {"input": "package cu\n\nimport \"testing\"\n\n\n\nfunc TestMultipleContext(t *testing.T) {\n\td := Device(0)\n\tctx0 := NewManuallyManagedContext(d, SchedAuto)\n\tctx1 := NewManuallyManagedContext(d, SchedAuto)\n\n\terrChan0 := make(chan error)\n\terrChan1 := make(chan error)\n\tgo ctx0.Run(errChan0)\n\tgo ctx1.Run(errChan1)\n\n\tif err := <-errChan0; err != nil {\n\t\tt.Fatalf(\"err while initializing run of ctx0 %v\", err)\n\t}\n\tif err := <-errChan1; err != nil {\n\t\tt.Fatalf(\"err while initializing run of ctx1 %v\", err)\n\t}\n\n\tvar mem0, mem1 DevicePtr\n\tvar err error\n\tif mem0, err = ctx0.MemAlloc(1024); err != nil {\n\t\tt.Errorf(\"Err while alloc in ctx0: %v\", err)\n\t}\n\n\tif mem1, err = ctx1.MemAlloc(1024); err != nil {\n\t\tt.Errorf(\"Err while alloc in ctx1: %v\", err)\n\t}\n\n\tt.Logf(\"Mem0: %v\", mem0)\n\tt.Logf(\"Mem1: %v\", mem1)\n\tctx0.MemFree(mem0)\n\tctx1.MemFree(mem1)\n\n\tif err = ctx0.Error(); err != nil {\n\t\tt.Errorf(\"Error while freeing %v\", err)\n\t}\n\tif err = ctx1.Error(); err != nil {\n\t\tt.Errorf(\"Error while freeing %v\", err)\n\t}\n\n}\n\nfunc TestContext(t *testing.T) ", "output": "{\n\tctx := NewContext(Device(0), SchedAuto)\n\tmem, err := ctx.MemAlloc(24)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Logf(\"%v\", mem)\n}"} {"input": "package maintenance\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" maintenance/2018-06-01-preview\"\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSApplicationAutoScalingScalableTarget_ScheduledAction struct {\n\n\tEndTime string `json:\"EndTime,omitempty\"`\n\n\tScalableTargetAction *AWSApplicationAutoScalingScalableTarget_ScalableTargetAction `json:\"ScalableTargetAction,omitempty\"`\n\n\tSchedule string `json:\"Schedule,omitempty\"`\n\n\tScheduledActionName string `json:\"ScheduledActionName,omitempty\"`\n\n\tStartTime string `json:\"StartTime,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\n\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::ApplicationAutoScaling::ScalableTarget.ScheduledAction\"\n}"} {"input": "package assertstate\n\nimport (\n\t\"github.com/snapcore/snapd/asserts\"\n\t\"github.com/snapcore/snapd/logger\"\n\t\"github.com/snapcore/snapd/overlord/auth\"\n\t\"github.com/snapcore/snapd/overlord/snapstate\"\n\t\"github.com/snapcore/snapd/overlord/state\"\n)\n\n\n\n\nfunc doFetch(s *state.State, userID int, deviceCtx snapstate.DeviceContext, fetching func(asserts.Fetcher) error) error {\n\n\tdb := cachedDB(s)\n\n\tunsupported := func(ref *asserts.Ref, unsupportedErr error) error {\n\t\tif _, err := ref.Resolve(db.Find); err != nil {\n\t\t\treturn unsupportedErr\n\t\t}\n\t\tlogger.Noticef(\"Cannot update assertion %v: %v\", ref, unsupportedErr)\n\t\treturn nil\n\t}\n\n\tb := asserts.NewBatch(unsupported)\n\n\tuser, err := userFromUserID(s, userID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsto := snapstate.Store(s, deviceCtx)\n\n\tretrieve := func(ref *asserts.Ref) (asserts.Assertion, error) {\n\t\treturn sto.Assertion(ref.Type, ref.PrimaryKey, user)\n\t}\n\n\ts.Unlock()\n\terr = b.Fetch(db, retrieve, fetching)\n\ts.Lock()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn b.CommitTo(db, nil)\n}\n\nfunc userFromUserID(st *state.State, userID int) (*auth.UserState, error) ", "output": "{\n\tif userID == 0 {\n\t\treturn nil, nil\n\t}\n\treturn auth.User(st, userID)\n}"} {"input": "package prime\n\nimport \"math\"\n\n\nfunc Nth(n int) (int, bool) {\n\tif n < 1 {\n\t\treturn 0, false\n\t}\n\n\tfoundPrimes := 0\n\tcandidate := 1\n\n\tfor foundPrimes < n {\n\t\tcandidate++\n\t\tif isPrime(candidate) {\n\t\t\tfoundPrimes++\n\t\t}\n\t}\n\n\treturn candidate, true\n}\n\n\n\nfunc isPrime(candidate int) bool ", "output": "{\n\tfor i := 2; i <= int(math.Sqrt(float64(candidate))); i++ {\n\t\tif candidate%i == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn candidate > 1\n}"} {"input": "package perfcounters\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\ntype CountPerTimeInterval32 struct {\n\tlastCount int32\n\tlastTime *time.Time\n\tcurrentCount int32\n\tmu sync.Mutex\n}\n\nfunc NewCountPerTimeInterval32() *CountPerTimeInterval32 {\n\n\treturn &CountPerTimeInterval32{\n\t\tlastTime: nil,\n\t\tlastCount: 0,\n\t\tcurrentCount: 0,\n\t}\n}\n\nfunc (self *CountPerTimeInterval32) Increment() {\n\tself.Add(1)\n}\n\n\n\nfunc (self *CountPerTimeInterval32) CalculatedValue() float64 {\n\tself.mu.Lock()\n\tdefer self.mu.Unlock()\n\n\tcurrentTime := time.Now()\n\n\tif self.lastTime == nil {\n\t\tself.lastTime = ¤tTime\n\t\treturn 0\n\t}\n\n\tlastTime := *self.lastTime\n\tlastCount := self.lastCount\n\tcurrentCount := self.currentCount\n\n\tcalculatedValue := float64(int64(currentCount-lastCount) / (currentTime.Sub(lastTime).Nanoseconds() / 1e6))\n\n\tself.lastTime = ¤tTime\n\tself.lastCount = currentCount\n\n\treturn calculatedValue\n}\n\nfunc (self *CountPerTimeInterval32) String() string {\n\treturn fmt.Sprintf(\"%.3f\", self.CalculatedValue())\n}\n\nfunc (self *CountPerTimeInterval32) Add(value int32) ", "output": "{\n\tself.mu.Lock()\n\tdefer self.mu.Unlock()\n\n\tself.currentCount += value\n\n\tif self.lastTime == nil {\n\t\tnow := time.Now()\n\t\tself.lastTime = &now\n\t}\n}"} {"input": "package services\n\nimport (\n \"github.com/nlopes/slack\"\n \"fmt\"\n)\n\ntype slackService struct {\n token string\n channel string\n channelId string\n serviceName string\n api *slack.Client\n rtm *slack.RTM\n userCache map[string]*slack.User\n sent map[string]bool\n}\n\nfunc NewSlack(token, channel, channelId string) slackService {\n api := slack.New(token)\n rtm := api.NewRTM()\n go rtm.ManageConnection()\n cache := make(map[string]*slack.User)\n return slackService{token, channel, channelId, \"slack\", api, rtm, cache, make(map[string]bool)}\n}\n\n\n\nfunc (sl slackService) listenToMessages(msg PortalMessage) {\n if (msg.Kind == PORTAL_MESSAGE) {\n params := slack.PostMessageParameters{}\n params.Username = msg.Author\n _, time, err := sl.api.PostMessage(sl.channel, msg.Data, params)\n if err != nil {\n fmt.Println(err)\n }\n sl.sent[time] = true\n }\n}\n\nfunc (sl slackService) triggerMessages(msg slack.RTMEvent, channel string) PortalMessage {\n switch ev := msg.Data.(type) {\n case *slack.MessageEvent:\n _, hasMessage := sl.sent[ev.Timestamp]\n if channel == ev.Channel && !hasMessage {\n user, ok := sl.userCache[ev.User]\n if !ok {\n info, err := sl.api.GetUserInfo(ev.User)\n if err != nil {\n fmt.Println(err)\n }\n sl.userCache[ev.User] = info\n user = info\n }\n return PortalMessage{ev.Text, user.Name, sl.serviceName, PORTAL_MESSAGE}\n }\n }\n return PortalMessage{\"\", \"\", \"\", PORTAL_NOOP}\n}\n\nfunc (sl slackService) ExposePortal() Portal ", "output": "{\n in := make(chan PortalMessage)\n out := make(chan PortalMessage)\n go func() {\n for {\n select {\n case msg := <-sl.rtm.IncomingEvents:\n sending := sl.triggerMessages(msg, sl.channelId)\n if sending.Kind == PORTAL_MESSAGE {\n out <- sending\n }\n case msg := <-in:\n sl.listenToMessages(msg)\n }\n }\n }()\n return Portal{in, out}\n}"} {"input": "package metadata\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/docker/infrakit/pkg/types\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc first(a, b interface{}) interface{} {\n\treturn a\n}\n\n\n\nfunc TestPluginSerializedReadWrites(t *testing.T) {\n\n\tc := make(chan func(map[string]interface{}))\n\tp := NewPluginFromChannel(c)\n\n\tvar wait sync.WaitGroup\n\n\tstart := make(chan struct{})\n\tfor i := range []int{0, 1, 2, 3} {\n\t\tk := fmt.Sprintf(\"namespace/%d/value\", i)\n\t\tv := i * 100\n\t\tgo func() {\n\t\t\t<-start\n\t\t\tc <- func(m map[string]interface{}) {\n\t\t\t\ttypes.Put(types.PathFromString(k), v, m)\n\t\t\t\twait.Add(1)\n\t\t\t}\n\t\t}()\n\t}\n\n\tclose(start) \n\n\ttime.Sleep(10 * time.Millisecond)\n\n\tresults := []string{}\n\tfor i := range []int{0, 1, 2, 3} {\n\n\t\tk := fmt.Sprintf(\"namespace/%d/value\", i)\n\t\tval, err := p.Get(types.PathFromString(k))\n\t\trequire.NoError(t, err)\n\n\t\tif val != nil {\n\t\t\tresults = append(results, val.String())\n\t\t}\n\n\t\twait.Done()\n\t}\n\n\tclose(c)\n\n\twait.Wait()\n\n\trequire.Equal(t, []string{\"0\", \"100\", \"200\", \"300\"}, results)\n}\n\nfunc TestPluginUnserializedReadWrites(t *testing.T) ", "output": "{\n\n\tm := map[string]interface{}{}\n\n\trequire.True(t, types.Put(types.PathFromString(\"us-west-1/metrics/instances/count\"), 2000, m))\n\trequire.True(t, types.Put(types.PathFromString(\"us-west-2/metrics/instances/count\"), 1000, m))\n\n\tp := NewPluginFromData(m)\n\n\trequire.Equal(t, []string{\"us-west-1\", \"us-west-2\"}, first(p.Keys(types.PathFromString(\"/\"))))\n\trequire.Nil(t, first(p.Get(types.PathFromString(\"us-west-1/metrics/instances/foo\"))))\n\trequire.Equal(t, \"2000\", first(p.Get(types.PathFromString(\"us-west-1/metrics/instances/count\"))).(*types.Any).String())\n\n}"} {"input": "package iconv\n\n\n\n\n\nfunc ConvertString(input string, fromEncoding string, toEncoding string) (output string, err error) {\n\tconverter, err := NewConverter(fromEncoding, toEncoding)\n\n\tif err == nil {\n\t\toutput, err = converter.ConvertString(input)\n\n\t\tconverter.Close()\n\t}\n\n\treturn\n}\n\nfunc Convert(input []byte, output []byte, fromEncoding string, toEncoding string) (bytesRead int, bytesWritten int, err error) ", "output": "{\n\tconverter, err := NewConverter(fromEncoding, toEncoding)\n\n\tif err == nil {\n\t\tbytesRead, bytesWritten, err = converter.Convert(input, output)\n\n\t\tif err == nil {\n\t\t\tvar shiftBytesWritten int\n\n\t\t\t_, shiftBytesWritten, err = converter.Convert(nil, output[bytesWritten:])\n\n\t\t\tbytesWritten += shiftBytesWritten\n\t\t}\n\n\t\tconverter.Close()\n\t}\n\n\treturn\n}"} {"input": "package vox\n\ntype Block uint8\n\nconst (\n\tBlockNil = 0x00\n\tblockActiveMask = 0x80 \n\tblockTypeMask = 0x7F \n)\n\nfunc (b Block) Active() bool {\n\treturn (blockActiveMask & b) == blockActiveMask\n}\n\nfunc (b Block) Activate(active bool) Block {\n\tif active {\n\t\treturn b | blockActiveMask\n\t}\n\treturn b & blockTypeMask\n}\n\nfunc (b Block) TypeID() uint8 {\n\treturn uint8(b & blockTypeMask)\n}\n\nfunc (b Block) ChangeType(t *BlockType) Block {\n\treturn Block((uint8(b) & blockActiveMask) | t.ID)\n}\n\ntype BlockType struct {\n\tID uint8\n\tTop *TextureRegion\n\tBottom *TextureRegion\n\tSide *TextureRegion\n}\n\ntype BlockBank struct {\n\tTypes []*BlockType\n\ttypeMap map[uint8]*BlockType\n}\n\nfunc NewBlockBank() *BlockBank {\n\treturn &BlockBank{\n\t\ttypeMap: make(map[uint8]*BlockType),\n\t}\n}\n\n\n\nfunc (b *BlockBank) TypeOf(block Block) *BlockType {\n\treturn b.typeMap[block.TypeID()]\n}\n\nfunc (b *BlockBank) AddType(blockType *BlockType) ", "output": "{\n\tb.typeMap[blockType.ID] = blockType\n\tb.Types = append(b.Types, blockType)\n}"} {"input": "package message\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"mime\"\n\t\"strings\"\n)\n\ntype UnknownCharsetError struct {\n\te error\n}\n\n\n\nfunc (u UnknownCharsetError) Error() string {\n\treturn \"unknown charset: \" + u.e.Error()\n}\n\n\n\nfunc IsUnknownCharset(err error) bool {\n\treturn errors.As(err, new(UnknownCharsetError))\n}\n\n\n\n\n\n\n\n\n\nvar CharsetReader func(charset string, input io.Reader) (io.Reader, error)\n\n\nfunc charsetReader(charset string, input io.Reader) (io.Reader, error) {\n\tcharset = strings.ToLower(charset)\n\tif charset == \"utf-8\" || charset == \"us-ascii\" {\n\t\treturn input, nil\n\t}\n\tif CharsetReader != nil {\n\t\tr, err := CharsetReader(charset, input)\n\t\tif err != nil {\n\t\t\treturn r, UnknownCharsetError{err}\n\t\t}\n\t\treturn r, nil\n\t}\n\treturn input, UnknownCharsetError{fmt.Errorf(\"message: unhandled charset %q\", charset)}\n}\n\n\n\nfunc decodeHeader(s string) (string, error) {\n\twordDecoder := mime.WordDecoder{CharsetReader: charsetReader}\n\tdec, err := wordDecoder.DecodeHeader(s)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\treturn dec, nil\n}\n\nfunc encodeHeader(s string) string {\n\treturn mime.QEncoding.Encode(\"utf-8\", s)\n}\n\nfunc (u UnknownCharsetError) Unwrap() error ", "output": "{ return u.e }"} {"input": "package ioctl\n\nimport \"golang.org/x/sys/unix\"\n\nconst (\n\ttypeBits = 8\n\tnumberBits = 8\n\tsizeBits = 14\n\tdirectionBits = 2\n\n\ttypeMask = (1 << typeBits) - 1\n\tnumberMask = (1 << numberBits) - 1\n\tsizeMask = (1 << sizeBits) - 1\n\tdirectionMask = (1 << directionBits) - 1\n\n\tdirectionNone = 0\n\tdirectionWrite = 1\n\tdirectionRead = 2\n\n\tnumberShift = 0\n\ttypeShift = numberShift + numberBits\n\tsizeShift = typeShift + typeBits\n\tdirectionShift = sizeShift + sizeBits\n)\n\nfunc ioc(dir, t, nr, size uintptr) uintptr {\n\treturn (dir << directionShift) | (t << typeShift) | (nr << numberShift) | (size << sizeShift)\n}\n\n\nfunc Io(t, nr uintptr) uintptr {\n\treturn ioc(directionNone, t, nr, 0)\n}\n\n\nfunc IoR(t, nr, size uintptr) uintptr {\n\treturn ioc(directionRead, t, nr, size)\n}\n\n\nfunc IoW(t, nr, size uintptr) uintptr {\n\treturn ioc(directionWrite, t, nr, size)\n}\n\n\nfunc IoRW(t, nr, size uintptr) uintptr {\n\treturn ioc(directionRead|directionWrite, t, nr, size)\n}\n\n\n\n\nfunc Ioctl(fd, op, arg uintptr) error ", "output": "{\n\t_, _, ep := unix.Syscall(unix.SYS_IOCTL, fd, op, arg)\n\tif ep != 0 {\n\t\treturn ep\n\t}\n\treturn nil\n}"} {"input": "package exec\n\nimport (\n\t\"bytes\"\n\t\"os/exec\"\n\t\"runtime\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/otto/ui\"\n)\n\n\n\nfunc TestRun(t *testing.T) ", "output": "{\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"Windows. Not running this test.\")\n\t}\n\n\tif _, err := exec.LookPath(\"echo\"); err != nil {\n\t\tt.Skipf(\"echo not found, skipping test: %s\", err)\n\t}\n\n\tcmd := exec.Command(\"echo\", \"-n\", \"hello world\")\n\tui := new(ui.Mock)\n\n\terr := Run(ui, cmd)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tvar output bytes.Buffer\n\tfor _, v := range ui.RawBuf {\n\t\toutput.WriteString(v)\n\t}\n\n\tif output.String() != \"hello world\" {\n\t\tt.Fatalf(\"bad: %s\", output.String())\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"net\"\n\t\"strconv\"\n)\n\nconst (\n\tAddrTypeIP = byte(0x01)\n\tAddrTypeDomain = byte(0x03)\n)\n\ntype VAddress struct {\n\tType byte\n\tIP net.IP\n\tDomain string\n\tPort uint16\n}\n\n\n\nfunc DomainAddress(domain string, port uint16) VAddress {\n\treturn VAddress{\n\t\tAddrTypeDomain,\n\t\tnil,\n\t\tdomain,\n\t\tport}\n}\n\nfunc (addr VAddress) IsIPv4() bool {\n\treturn addr.Type == AddrTypeIP && len(addr.IP) == net.IPv4len\n}\n\nfunc (addr VAddress) IsIPv6() bool {\n\treturn addr.Type == AddrTypeIP && len(addr.IP) == net.IPv6len\n}\n\nfunc (addr VAddress) IsDomain() bool {\n\treturn addr.Type == AddrTypeDomain\n}\n\nfunc (addr VAddress) String() string {\n\tvar host string\n\tswitch addr.Type {\n\tcase AddrTypeIP:\n\t\thost = addr.IP.String()\n\t\tif len(addr.IP) == net.IPv6len {\n\t\t\thost = \"[\" + host + \"]\"\n\t\t}\n\n\tcase AddrTypeDomain:\n\t\thost = addr.Domain\n\tdefault:\n\t\tpanic(\"Unknown Address Type \" + strconv.Itoa(int(addr.Type)))\n\t}\n\treturn host + \":\" + strconv.Itoa(int(addr.Port))\n}\n\nfunc IPAddress(ip []byte, port uint16) VAddress ", "output": "{\n\treturn VAddress{\n\t\tAddrTypeIP,\n\t\tnet.IP(ip),\n\t\t\"\",\n\t\tport}\n}"} {"input": "package match\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\nfunc Match(t *testing.T, value interface{}) *Matcher {\n\treturn &Matcher{\n\t\tt: t,\n\t\tvalue: value,\n\t}\n}\n\n\nfunc IsNil(t *testing.T, value interface{}) *Matcher {\n\treturn Match(t, value).IsNil()\n}\n\n\nfunc IsNotNil(t *testing.T, value interface{}) *Matcher {\n\treturn Match(t, value).IsNotNil()\n}\n\n\nfunc Equals(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).Equals(other)\n}\n\n\n\n\n\nfunc LessThan(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).LessThan(other)\n}\n\n\nfunc GreaterThan(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).GreaterThan(other)\n}\n\n\nfunc Contains(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).Contains(other)\n}\n\n\nfunc Matches(t *testing.T, value interface{}, pattern string) *Matcher {\n\treturn Match(t, value).Matches(pattern)\n}\n\n\nfunc KindOf(t *testing.T, value interface{}, kind reflect.Kind) *Matcher {\n\treturn Match(t, value).KindOf(kind)\n}\n\nfunc NotEquals(t *testing.T, value, other interface{}) *Matcher ", "output": "{\n\treturn Match(t, value).NotEquals(other)\n}"} {"input": "package fake\n\nimport (\n\tv1 \"github.com/openshift/origin/pkg/authorization/client/clientset_generated/release_v1_4/typed/core/v1\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n\tcore \"k8s.io/kubernetes/pkg/client/testing/core\"\n)\n\ntype FakeCore struct {\n\t*core.Fake\n}\n\n\n\n\n\nfunc (c *FakeCore) GetRESTClient() *restclient.RESTClient {\n\treturn nil\n}\n\nfunc (c *FakeCore) Policies(namespace string) v1.PolicyInterface ", "output": "{\n\treturn &FakePolicies{c, namespace}\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"os/exec\"\n)\n\n\n\nfunc FileExists(name string) bool {\n\tfi, err := os.Stat(name)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif fi.IsDir() {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc DirExists(name string) bool {\n\tfi, err := os.Stat(name)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif fi.IsDir() {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc Run(dir string, exe string, arg ...string) (stdout *bytes.Buffer, stderr *bytes.Buffer, err error) {\n\tcmd := exec.Command(exe, arg...)\n\tvar errbuf bytes.Buffer\n\tvar outbuf bytes.Buffer\n\tcmd.Dir = dir\n\tcmd.Stderr = &errbuf\n\tcmd.Stdout = &outbuf\n\terr = cmd.Run()\n\treturn &outbuf, &errbuf, err\n}\n\nfunc panicOn(err error) ", "output": "{\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package errors\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n)\n\n\ntype HTTPError struct {\n\tStatusCode int\n\terror\n}\n\n\nfunc (e *HTTPError) Error() string {\n\treturn e.error.Error()\n}\n\n\n\n\nfunc NewMethodNotAllowed(method string) *HTTPError {\n\treturn &HTTPError{http.StatusMethodNotAllowed, errors.New(`Method is not allowed:\"` + method + `\"`)}\n}\n\n\nfunc NewBadRequest(err error) *HTTPError {\n\treturn &HTTPError{http.StatusBadRequest, err}\n}\n\n\n\nfunc NewBadRequestString(s string) *HTTPError {\n\treturn NewBadRequest(errors.New(s))\n}\n\n\n\n\n\n\n\nfunc NewBadRequestUnwantedParameter(s string) *HTTPError {\n\treturn NewBadRequestString(`Unwanted parameter \"` + s + `\"`)\n}\n\nfunc NewBadRequestMissingParameter(s string) *HTTPError ", "output": "{\n\treturn NewBadRequestString(`Missing parameter \"` + s + `\"`)\n}"} {"input": "package settings\n\nimport (\n\t\"sync/atomic\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\n\ntype IntSetting struct {\n\tdefaultValue int64\n\tv int64\n\tvalidateFn func(int64) error\n}\n\nvar _ Setting = &IntSetting{}\n\n\nfunc (i *IntSetting) Get() int64 {\n\treturn atomic.LoadInt64(&i.v)\n}\n\nfunc (i *IntSetting) String() string {\n\treturn EncodeInt(i.Get())\n}\n\n\nfunc (*IntSetting) Typ() string {\n\treturn \"i\"\n}\n\n\nfunc (i *IntSetting) Validate(v int64) error {\n\tif i.validateFn != nil {\n\t\tif err := i.validateFn(v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\nfunc (i *IntSetting) setToDefault() {\n\tif err := i.set(i.defaultValue); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\nfunc RegisterIntSetting(key, desc string, defaultValue int64) *IntSetting {\n\treturn RegisterValidatedIntSetting(key, desc, defaultValue, nil)\n}\n\n\n\nfunc RegisterValidatedIntSetting(\n\tkey, desc string, defaultValue int64, validateFn func(int64) error,\n) *IntSetting {\n\tif validateFn != nil {\n\t\tif err := validateFn(defaultValue); err != nil {\n\t\t\tpanic(errors.Wrap(err, \"invalid default\"))\n\t\t}\n\t}\n\tsetting := &IntSetting{\n\t\tdefaultValue: defaultValue,\n\t\tvalidateFn: validateFn,\n\t}\n\tregister(key, desc, setting)\n\treturn setting\n}\n\n\n\nfunc TestingSetInt(s **IntSetting, v int64) func() {\n\tsaved := *s\n\t*s = &IntSetting{v: v}\n\treturn func() {\n\t\t*s = saved\n\t}\n}\n\nfunc (i *IntSetting) set(v int64) error ", "output": "{\n\tif err := i.Validate(v); err != nil {\n\t\treturn err\n\t}\n\tatomic.StoreInt64(&i.v, v)\n\treturn nil\n}"} {"input": "package middlewares\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n\ntype CoreQuery struct {\n\tskip int\n\tlimit int\n\tsort string\n\tdatefrom string\n\tdateto string\n}\n\n\n\n\nfunc toInt(s string, defValue int) int {\n\tnum, err := strconv.Atoi(s)\n\n\tif err != nil {\n\t\treturn defValue\n\t}\n\n\treturn num\n}\n\nfunc Query() gin.HandlerFunc ", "output": "{\n\treturn func(c *gin.Context) {\n\t\tq := CoreQuery{}\n\t\tq.skip = toInt(c.Query(\"skip\"), 0)\n\t\tq.limit = toInt(c.Query(\"limit\"), 20)\n\t\tq.sort = c.Query(\"sort\")\n\t\tq.datefrom = c.Query(\"datefrom\")\n\t\tq.dateto = c.Query(\"dateto\")\n\t\tc.Set(\"Query\", q)\n\t\tc.Next()\n\t}\n}"} {"input": "package cloudstorage\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n)\n\ntype MockStorage struct {\n\tPutRequest *http.Request\n\tGetURL *url.URL\n\tOriginallySigned bool\n\tListObjectsResponse *ListObjectsResponse\n}\n\nvar _ Storage = &MockStorage{}\n\n\n\nfunc (s *MockStorage) PresignGetObject(name string) (*url.URL, error) {\n\treturn s.GetURL, nil\n}\n\nfunc (s *MockStorage) PresignHeadObject(name string) (*url.URL, error) {\n\treturn s.GetURL, nil\n}\n\nfunc (s *MockStorage) RewriteGetURL(u *url.URL, name string) (*url.URL, bool, error) {\n\treturn s.GetURL, s.OriginallySigned, nil\n}\n\nfunc (s *MockStorage) ListObjects(r *ListObjectsRequest) (*ListObjectsResponse, error) {\n\treturn s.ListObjectsResponse, nil\n}\n\nfunc (s *MockStorage) DeleteObject(name string) error {\n\treturn nil\n}\n\nfunc (s *MockStorage) AccessType(header http.Header) AccessType {\n\treturn AccessTypeDefault\n}\n\nfunc (s *MockStorage) StandardToProprietary(header http.Header) http.Header {\n\treturn header\n}\n\nfunc (s *MockStorage) ProprietaryToStandard(header http.Header) http.Header {\n\treturn header\n}\n\nfunc (s *MockStorage) PresignPutObject(name string, accessType AccessType, header http.Header) (*http.Request, error) ", "output": "{\n\treturn s.PutRequest, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\tfmt.Printf(\"I am started\\r\\n\")\n\tfor {\n\t\tgo LeakAway()\n\t}\n\tfmt.Printf(\"I am done, finally!!!!\\r\\n\")\n}\n\n\n\nfunc LeakAway() ", "output": "{\n\tnum := 1\n\tfor {\n\t\tnum++\n\t}\n}"} {"input": "package debugtools\n\nimport (\n\t\"github.com/oakmound/oak/v3/render\"\n\t\"golang.org/x/sync/syncmap\"\n)\n\nvar (\n\tdebugMap syncmap.Map\n)\n\n\n\nfunc SetDebugRenderable(rName string, r render.Renderable) {\n\tdebugMap.Store(rName, r)\n}\n\n\n\n\n\n\n\nfunc EnumerateDebugRenderableKeys() []string {\n\tkeys := []string{}\n\tdebugMap.Range(func(k, v interface{}) bool {\n\t\tkey, ok := k.(string)\n\t\tif ok {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t\treturn true\n\t})\n\treturn keys\n}\n\nfunc GetDebugRenderable(rName string) (render.Renderable, bool) ", "output": "{\n\tr, ok := debugMap.Load(rName)\n\tif r == nil {\n\t\treturn nil, false\n\t}\n\treturn r.(render.Renderable), ok\n}"} {"input": "package field\n\nimport (\n\t\"sync\"\n\n\t\"github.com/elemchat/elemchat/wizard\"\n)\n\ntype Field struct {\n\tsync.Mutex\n\tWizards map[*wizard.Wizard]struct{}\n\trecv chan wizard.Message\n\tclosed bool\n}\n\ntype HandleFunc func(wizard.Message)\n\nfunc New(handle HandleFunc) *Field {\n\tf := &Field{\n\t\tMutex: sync.Mutex{},\n\t\tWizards: make(map[*wizard.Wizard]struct{}),\n\t\trecv: make(chan wizard.Message),\n\t\tclosed: false,\n\t}\n\n\tgo f.loop(handle)\n\treturn f\n}\n\n\n\n\nfunc (f *Field) Close() {\n\tf.WithLock(func(f *Field) {\n\t\tif f.closed {\n\t\t\treturn\n\t\t}\n\n\t\tgo func() {\n\t\t\tfor _ = range f.recv {\n\t\t\t}\n\t\t}()\n\n\t\tfor w, _ := range f.Wizards {\n\t\t\tw.Close(true)\n\t\t\tdelete(f.Wizards, w)\n\t\t}\n\t\tclose(f.recv)\n\t\tf.closed = true\n\t})\n}\n\nfunc (f *Field) Enter(fn func(recv chan<- wizard.Message) *wizard.Wizard) {\n\tf.WithLock(func(f *Field) {\n\t\tif f.closed {\n\t\t\treturn\n\t\t}\n\n\t\tw := fn(f.recv)\n\t\tif w != nil {\n\t\t\tf.Wizards[w] = struct{}{}\n\t\t}\n\t})\n}\n\nfunc (f *Field) loop(handle HandleFunc) {\n\tif handle == nil {\n\t\tf.Close()\n\t\treturn\n\t}\n\tfor message := range f.recv {\n\t\tif message.Msg() == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\thandle(message)\n\t}\n}\n\nfunc (f *Field) WithLock(fn func(*Field)) ", "output": "{\n\tf.Lock()\n\tfn(f)\n\tf.Unlock()\n}"} {"input": "package ha\n\nimport (\n\tlog \"github.com/golang/glog\"\n\t\"k8s.io/kubernetes/contrib/mesos/pkg/election\"\n)\n\ntype roleType int\n\nconst (\n\tfollowerRole roleType = iota\n\tmasterRole\n\tretiredRole\n)\n\ntype candidateService struct {\n\tsched *SchedulerProcess\n\tnewDriver DriverFactory\n\trole roleType\n\tvalid ValidationFunc\n}\n\ntype ValidationFunc func(desiredUid, currentUid string)\n\nfunc NewCandidate(s *SchedulerProcess, f DriverFactory, v ValidationFunc) election.Service {\n\treturn &candidateService{\n\t\tsched: s,\n\t\tnewDriver: f,\n\t\trole: followerRole,\n\t\tvalid: v,\n\t}\n}\n\n\n\nfunc (self *candidateService) Start() {\n\tif self.role == followerRole {\n\t\tlog.Info(\"elected as master\")\n\t\tself.role = masterRole\n\t\tself.sched.Elect(self.newDriver)\n\t}\n}\n\nfunc (self *candidateService) Stop() {\n\tif self.role == masterRole {\n\t\tlog.Info(\"retiring from master\")\n\t\tself.role = retiredRole\n\t\tclose(self.sched.failover)\n\t\tself.sched.End()\n\t}\n}\n\nfunc (self *candidateService) Validate(desired, current election.Master) ", "output": "{\n\tif self.valid != nil {\n\t\tself.valid(string(desired), string(current))\n\t}\n}"} {"input": "package plugin_server\n\nimport (\n\t\"github.com/pivotal-golang/lager\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/rpc\"\n)\n\ntype PluginServer interface {\n\tStart() error\n\tTest(string, *StringResponse) error\n}\n\ntype pluginServer struct {\n\tlogger lager.Logger\n}\n\ntype StringResponse struct {\n\tStringResponse string\n}\n\nfunc NewPluginServer(logger lager.Logger) PluginServer {\n\treturn &pluginServer{\n\t\tlogger: logger,\n\t}\n}\n\n\n\nfunc (p *pluginServer) Test(request string, response *StringResponse) error {\n\tp.logger.Debug(\"Plugin server received Test call: \" + request)\n\n\tresponse.StringResponse = \"Hello from GoHome!\"\n\treturn nil\n}\n\nfunc (p *pluginServer) Start() error ", "output": "{\n\tp.logger.Debug(\"Starting plugin server...\")\n\n\trpc.Register(p)\n\trpc.HandleHTTP()\n\tlistener, err := net.Listen(\"tcp\", \":4249\")\n\tif err != nil {\n\t\tp.logger.Error(\"Error starting RPC client\", err)\n\t\treturn err\n\t}\n\n\tgo http.Serve(listener, nil)\n\n\tp.logger.Debug(\"Plugin server started\")\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/robfig/cron\"\n)\n\ntype Sync struct{}\n\nfunc (s *Sync) Help() string {\n\treturn \"glr sync Help\"\n}\n\nfunc (s *Sync) Run(args []string) int {\n\t_, err := SyncRepository()\n\n\tif err != nil {\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n\nfunc (s *Sync) Synopsis() string {\n\treturn \"Synchronize local git repository with remote at once\"\n}\n\n\ntype status struct {\n\tc *cron.Cron\n\trepositories []string\n\tschedules []string\n}\n\nvar sharedStatus *status = newStatus()\n\nfunc newStatus() *status {\n\treturn &status{\n\t\tc: cron.New(),\n\t}\n}\n\n\nfunc GetStatus() *status {\n\treturn sharedStatus\n}\n\ntype StatusStart struct{}\n\nfunc (s *StatusStart) Help() string {\n\treturn \"glr status start Help\"\n}\n\nfunc (s *StatusStart) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.AddFunc(\"@hourly\", func() {\n\t\tSyncRepository()\n\t})\n\tfmt.Println(\"set job schedule\")\n\tstatus.c.Start()\n\n\treturn 0\n}\n\nfunc (s *StatusStart) Synopsis() string {\n\treturn \"Synchronize local git repository with remote\"\n}\n\ntype StatusStop struct{}\n\nfunc (s *StatusStop) Help() string {\n\treturn \"glr status stop Help\"\n}\n\n\n\nfunc (s *StatusStop) Synopsis() string {\n\treturn \"Stop cron scheduler\"\n}\n\nfunc (s *StatusStop) Run(args []string) int ", "output": "{\n\n\tstatus := GetStatus()\n\tstatus.c.Stop()\n\tfmt.Println(\"stop job scheduler\")\n\n\treturn 0\n}"} {"input": "package tokenauth\n\nimport (\n\t\"time\"\n)\n\n\n\ntype Audience struct {\n\tName string\n\tID string \n\tSecret string \n\tTokenPeriod uint64 \n}\n\n\ntype Token struct {\n\tClientID string \n\tSingleID string \n\tValue string \n\tDeadLine int64 \n}\n\n\n\nfunc (t *Token) Expired() bool {\n\tif t.DeadLine == 0 {\n\t\treturn false\n\t}\n\treturn time.Now().Unix() >= t.DeadLine\n}\n\n\n\n\nfunc (t *Token) IsSingle() bool ", "output": "{\n\treturn len(t.ClientID) == 0 && len(t.SingleID) > 0\n}"} {"input": "package horizon\n\nimport (\n\t\"github.com/stellar/go-horizon/db\"\n)\n\nfunc initHistoryDb(app *App) {\n\thistoryDb, err := db.Open(app.config.DatabaseUrl)\n\n\tif err != nil {\n\t\tapp.log.Panic(app.ctx, err)\n\t}\n\tapp.historyDb = historyDb\n}\n\n\n\nfunc init() {\n\tappInit.Add(\"history-db\", initHistoryDb, \"app-context\", \"log\")\n\tappInit.Add(\"core-db\", initCoreDb, \"app-context\", \"log\")\n}\n\nfunc initCoreDb(app *App) ", "output": "{\n\tcoreDb, err := db.Open(app.config.StellarCoreDatabaseUrl)\n\n\tif err != nil {\n\t\tapp.log.Panic(app.ctx, err)\n\t}\n\tapp.coreDb = coreDb\n}"} {"input": "package consul\n\nimport (\n\t\"log\"\n\n\t\"github.com/armon/consul-api\"\n\t\"github.com/hashicorp/terraform/helper/config\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\ntype ResourceProvider struct {\n\tConfig Config\n\tclient *consulapi.Client\n}\n\nfunc (p *ResourceProvider) Validate(c *terraform.ResourceConfig) ([]string, []error) {\n\tv := &config.Validator{\n\t\tOptional: []string{\n\t\t\t\"datacenter\",\n\t\t\t\"address\",\n\t\t},\n\t}\n\treturn v.Validate(c)\n}\n\nfunc (p *ResourceProvider) ValidateResource(\n\tt string, c *terraform.ResourceConfig) ([]string, []error) {\n\treturn resourceMap.Validate(t, c)\n}\n\n\n\nfunc (p *ResourceProvider) Apply(\n\ts *terraform.ResourceState,\n\td *terraform.ResourceDiff) (*terraform.ResourceState, error) {\n\treturn resourceMap.Apply(s, d, p)\n}\n\nfunc (p *ResourceProvider) Diff(\n\ts *terraform.ResourceState,\n\tc *terraform.ResourceConfig) (*terraform.ResourceDiff, error) {\n\treturn resourceMap.Diff(s, c, p)\n}\n\nfunc (p *ResourceProvider) Refresh(\n\ts *terraform.ResourceState) (*terraform.ResourceState, error) {\n\treturn resourceMap.Refresh(s, p)\n}\n\nfunc (p *ResourceProvider) Resources() []terraform.ResourceType {\n\treturn resourceMap.Resources()\n}\n\nfunc (p *ResourceProvider) Configure(c *terraform.ResourceConfig) error ", "output": "{\n\tif _, err := config.Decode(&p.Config, c.Config); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[INFO] Initializing Consul client\")\n\tvar err error\n\tp.client, err = p.Config.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package v1\n\nimport (\n\t\"gopkg.in/guregu/null.v3\"\n\n\t\"go.k6.io/k6/core\"\n\t\"go.k6.io/k6/lib\"\n)\n\ntype Status struct {\n\tStatus lib.ExecutionStatus `json:\"status\" yaml:\"status\"`\n\n\tPaused null.Bool `json:\"paused\" yaml:\"paused\"`\n\tVUs null.Int `json:\"vus\" yaml:\"vus\"`\n\tVUsMax null.Int `json:\"vus-max\" yaml:\"vus-max\"`\n\tStopped bool `json:\"stopped\" yaml:\"stopped\"`\n\tRunning bool `json:\"running\" yaml:\"running\"`\n\tTainted bool `json:\"tainted\" yaml:\"tainted\"`\n}\n\nfunc NewStatus(engine *core.Engine) Status {\n\texecutionState := engine.ExecutionScheduler.GetState()\n\treturn Status{\n\t\tStatus: executionState.GetCurrentExecutionStatus(),\n\t\tRunning: executionState.HasStarted() && !executionState.HasEnded(),\n\t\tPaused: null.BoolFrom(executionState.IsPaused()),\n\t\tStopped: engine.IsStopped(),\n\t\tVUs: null.IntFrom(executionState.GetCurrentlyActiveVUsCount()),\n\t\tVUsMax: null.IntFrom(executionState.GetInitializedVUsCount()),\n\t\tTainted: engine.IsTainted(),\n\t}\n}\n\n\n\nfunc (s Status) GetID() string {\n\treturn \"default\"\n}\n\nfunc (s Status) SetID(id string) error {\n\treturn nil\n}\n\nfunc (s Status) GetName() string ", "output": "{\n\treturn \"status\"\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\ntype String string\n\ntype Struct struct {\n\tGreeting string\n\tPunct string\n\tWho string\n}\n\nfunc (h String) ServeHTTP(\n\tw http.ResponseWriter,\n\tr *http.Request) {\n\tfmt.Fprint(w, h)\n}\n\n\n\nfunc main() {\n\thttp.Handle(\"/string\", String(\"I'm a frayed knot.\"))\n\thttp.Handle(\"/struct\", &Struct{\"Hello\", \":\", \"Gophers!\"})\n\thttp.ListenAndServe(\"localhost:4000\", nil)\n}\n\nfunc (h Struct) ServeHTTP(\n\tw http.ResponseWriter,\n\tr *http.Request) ", "output": "{\n\tfmt.Fprint(w, fmt.Sprintf(\"%s%s%s\", h.Greeting, h.Punct, h.Who))\n}"} {"input": "package models\n\n\n\n\nfunc AwsAccountsByParentId(db DB, parentID int) (res []*AwsAccount, err error) {\n\tconst sqlstr = `SELECT ` +\n\t\t`id, user_id, pretty, role_arn, external, next_update, aws_identity, last_spreadsheet_report_generation ` +\n\t\t`FROM trackit.aws_account ` +\n\t\t`WHERE parent_id = ?`\n\tlogf(sqlstr)\n\tq, err := db.Query(sqlstr, parentID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif closeErr := q.Close(); err == nil {\n\t\t\terr = closeErr\n\t\t}\n\t}()\n\tfor q.Next() {\n\t\taa := AwsAccount{\n\t\t\t_exists: true,\n\t\t}\n\t\terr = q.Scan(&aa.ID, &aa.UserID, &aa.Pretty, &aa.RoleArn, &aa.External, &aa.NextUpdate, &aa.AwsIdentity, &aa.LastSpreadsheetReportGeneration)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tres = append(res, &aa)\n\t}\n\treturn res, nil\n}\n\nfunc AwsAccounts(db DB) (res []*AwsAccount, err error) ", "output": "{\n\tconst sqlstr = `SELECT ` +\n\t\t`id, user_id, pretty, role_arn, external, next_update, aws_identity ` +\n\t\t`FROM trackit.aws_account`\n\tlogf(sqlstr)\n\tq, err := db.Query(sqlstr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif closeErr := q.Close(); err == nil {\n\t\t\terr = closeErr\n\t\t}\n\t}()\n\tfor q.Next() {\n\t\taa := AwsAccount{\n\t\t\t_exists: true,\n\t\t}\n\t\terr = q.Scan(&aa.ID, &aa.UserID, &aa.Pretty, &aa.RoleArn, &aa.External, &aa.NextUpdate, &aa.AwsIdentity)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tres = append(res, &aa)\n\t}\n\treturn res, nil\n}"} {"input": "package svc\n\nimport (\n\t\"golang.org/x/sys/windows\"\n)\n\nfunc allocSid(subAuth0 uint32) (*windows.SID, error) {\n\tvar sid *windows.SID\n\terr := windows.AllocateAndInitializeSid(&windows.SECURITY_NT_AUTHORITY,\n\t\t1, subAuth0, 0, 0, 0, 0, 0, 0, 0, &sid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sid, nil\n}\n\n\n\n\n\n\nfunc IsAnInteractiveSession() (bool, error) ", "output": "{\n\tinterSid, err := allocSid(windows.SECURITY_INTERACTIVE_RID)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer windows.FreeSid(interSid)\n\n\tserviceSid, err := allocSid(windows.SECURITY_SERVICE_RID)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer windows.FreeSid(serviceSid)\n\n\tt, err := windows.OpenCurrentProcessToken()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer t.Close()\n\n\tgs, err := t.GetTokenGroups()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, g := range gs.AllGroups() {\n\t\tif windows.EqualSid(g.Sid, interSid) {\n\t\t\treturn true, nil\n\t\t}\n\t\tif windows.EqualSid(g.Sid, serviceSid) {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn false, nil\n}"} {"input": "package handler\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"net/http\"\n\t\"text/template\"\n\t\"time\"\n)\n\n\ntype AppHandler func(http.ResponseWriter, *http.Request) (int, error)\n\n\ntype AppConfig struct {\n\tServerTime int64 `json:\"serverTime\"`\n}\n\nconst (\n\tConfigTemplateName string = \"appConfig\"\n\tConfigTemplate string = \"var appConfig_DO_NOT_USE_DIRECTLY = {{.}}\"\n)\n\n\nfunc (fn AppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif _, err := fn(w, r); err != nil {\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError),\n\t\t\thttp.StatusInternalServerError)\n\t}\n}\n\n\n\nfunc ConfigHandler(w http.ResponseWriter, r *http.Request) (int, error) {\n\ttemplate, err := template.New(ConfigTemplateName).Parse(ConfigTemplate)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn http.StatusInternalServerError, err\n\t}\n\treturn http.StatusOK, template.Execute(w, getAppConfigJSON())\n}\n\nfunc getAppConfigJSON() string ", "output": "{\n\tlog.Printf(\"Getting application global configuration\")\n\n\tconfig := &AppConfig{\n\t\tServerTime: time.Now().UTC().UnixNano() / 1e6,\n\t}\n\n\tjson, _ := json.Marshal(config)\n\tlog.Printf(\"Application configuration %s\", json)\n\treturn string(json)\n}"} {"input": "package refund\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/issue9/wechat/pay\"\n)\n\n\ntype Refund struct {\n\tPay *pay.Pay\n\tDeviceInfo string \n\tSignType string \n\tRefundFeeType string \n\tOpUserID string \n\tRefundAccount string \n}\n\nfunc (r *Refund) params(outRefundNO, outTradeNO, transactionID string, totalFee, refundFee int) map[string]string {\n\treturn map[string]string{\n\t\t\"device_info\": r.DeviceInfo,\n\t\t\"sign_type\": r.SignType,\n\t\t\"out_trade_no\": outTradeNO,\n\t\t\"transaction_id\": transactionID,\n\t\t\"out_refund_no\": outRefundNO,\n\t\t\"total_fee\": strconv.Itoa(totalFee),\n\t\t\"refund_fee\": strconv.Itoa(refundFee),\n\t\t\"refund_fee_type\": r.RefundFeeType,\n\t\t\"op_user_id\": r.OpUserID,\n\t\t\"refund_account\": r.RefundAccount,\n\t}\n}\n\n\nfunc (r *Refund) OutTradeNO(outRefundNO, outTradeNO string, totalFee, refundFee int) (*Return, error) {\n\tparams := r.params(outRefundNO, outTradeNO, \"\", totalFee, refundFee)\n\treturn r.refund(params)\n}\n\n\n\n\nfunc (r *Refund) refund(params map[string]string) (*Return, error) {\n\tmaps, err := r.Pay.Refund(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = r.Pay.ValidateAll(r.SignType, maps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newReturn(maps)\n}\n\nfunc (r *Refund) TransactionID(outRefundNO, transactionID string, totalFee, refundFee int) (*Return, error) ", "output": "{\n\tparams := r.params(outRefundNO, \"\", transactionID, totalFee, refundFee)\n\treturn r.refund(params)\n}"} {"input": "package delegatednetwork\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) BaseClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package bitbucket\n\ntype Downloads struct {\n\tc *Client\n}\n\n\n\nfunc (dl *Downloads) List(do *DownloadsOptions) (interface{}, error) {\n\turlStr := dl.c.requestUrl(\"/repositories/%s/%s/downloads\", do.Owner, do.RepoSlug)\n\treturn dl.c.execute(\"GET\", urlStr, \"\")\n}\n\nfunc (dl *Downloads) Create(do *DownloadsOptions) (interface{}, error) ", "output": "{\n\turlStr := dl.c.requestUrl(\"/repositories/%s/%s/downloads\", do.Owner, do.RepoSlug)\n\treturn dl.c.executeFileUpload(\"POST\", urlStr, do.FilePath, do.FileName, \"files\", make(map[string]string))\n}"} {"input": "package libwebsocketd\n\nimport (\n\t\"io\"\n\t\"os/exec\"\n)\n\ntype LaunchedProcess struct {\n\tcmd *exec.Cmd\n\tstdin io.WriteCloser\n\tstdout io.ReadCloser\n\tstderr io.ReadCloser\n}\n\n\n\nfunc launchCmd(commandName string, commandArgs []string, env []string) (*LaunchedProcess, error) ", "output": "{\n\tcmd := exec.Command(commandName, commandArgs...)\n\tcmd.Env = env\n\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstderr, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &LaunchedProcess{cmd, stdin, stdout, stderr}, err\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype DNSDomains []string\n\n\n\n\n\nfunc (m DNSDomains) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}\n\nfunc (m DNSDomains) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tiDNSDomainsSize := int64(len(m))\n\n\tif err := validate.MaxItems(\"\", \"body\", iDNSDomainsSize, 6); err != nil {\n\t\treturn err\n\t}\n\n\tfor i := 0; i < len(m); i++ {\n\n\t\tif err := validate.MinLength(strconv.Itoa(i), \"body\", m[i], 1); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := validate.MaxLength(strconv.Itoa(i), \"body\", m[i], 255); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"net/http\"\n)\n\nfunc PingHandler(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"PONG!\"})\n}\n\nfunc GetAllStats(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"statistics go here\"})\n}\n\n\n\nfunc GetImage(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"one image goes here\"})\n}\n\nfunc CreateImage(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"ID of the image we created goes here\"})\n}\n\nfunc UpdateImage(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"ID of the image we updated goes here\"})\n}\n\nfunc GetAllImages(c *gin.Context) ", "output": "{\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"all images go here\"})\n}"} {"input": "package tlv\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\ntype ByteTLV struct {\n\tT uint64\n\tV []byte\n}\n\nfunc readByteTLV(r io.Reader) (ByteTLV, error) {\n\tt, _, err := ReadNumber(r)\n\tif err != nil {\n\t\treturn ByteTLV{}, err\n\t}\n\n\tlength, _, err := ReadNumber(r)\n\tif err != nil {\n\t\treturn ByteTLV{}, err\n\t}\n\n\tvalue := make([]byte, length)\n\tn, err := r.Read(value)\n\tif err != nil {\n\t\treturn ByteTLV{}, err\n\t}\n\n\tif uint64(n) < length {\n\t\treturn ByteTLV{}, io.ErrUnexpectedEOF\n\t}\n\n\treturn ByteTLV{T: t, V: value[0:n]}, nil\n}\n\nfunc (t ByteTLV) Type() uint64 {\n\treturn t.T\n}\n\n\n\nfunc (t ByteTLV) MarshalBinary() ([]byte, error) {\n\tbuf := &bytes.Buffer{}\n\t_, err := t.WriteTo(buf)\n\treturn buf.Bytes(), err\n}\n\nfunc (t ByteTLV) WriteTo(w io.Writer) (n int64, err error) ", "output": "{\n\tn, err = WriteNumber(w, t.T)\n\tif err != nil {\n\t\treturn\n\t}\n\n\twritten, err := WriteNumber(w, uint64(len(t.V)))\n\tn += written\n\tif err != nil {\n\t\treturn\n\t}\n\n\twritten2, err := w.Write(t.V)\n\tn += int64(written2)\n\treturn\n}"} {"input": "package worker\n\nimport (\n\t\"github.com/gopherjs/gopherjs/js\"\n\t\"github.com/flimzy/goweb/event\"\n)\n\ntype Worker struct {\n\tjs.Object\n\tOnError event.EventHandlerFunc `js:\"onerror\"`\n\tOnMessage event.EventHandlerFunc `js:\"onmessage\"`\n}\n\n\n\nfunc (w *Worker) PostMessage(msg interface{}) {\n\tw.Call(\"postMessage\", msg)\n}\n\nfunc (w *Worker) Terminate() {\n\tw.Call(\"terminate\")\n}\n\nfunc New(url string) (w *Worker, e error) ", "output": "{\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\te = r.(*js.Error)\n\t\t}\n\t}()\n\to := js.Global.Get(\"Worker\").New(url)\n\tw = &Worker{Object: *o}\n\treturn\n}"} {"input": "package tartest\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\tupTar \"archive/tar\"\n\n\tourTar \"github.com/vbatts/tar-split/archive/tar\"\n)\n\nvar testfile = \"./archive/tar/testdata/sparse-formats.tar\"\n\n\n\nfunc BenchmarkOurTarNoAccounting(b *testing.B) {\n\tfor n := 0; n < b.N; n++ {\n\t\tfh, err := os.Open(testfile)\n\t\tif err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t\ttr := ourTar.NewReader(fh)\n\t\ttr.RawAccounting = false \n\t\tfor {\n\t\t\t_, err := tr.Next()\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfh.Close()\n\t\t\t\tb.Fatal(err)\n\t\t\t}\n\t\t\tio.Copy(ioutil.Discard, tr)\n\t\t}\n\t\tfh.Close()\n\t}\n}\nfunc BenchmarkOurTarYesAccounting(b *testing.B) {\n\tfor n := 0; n < b.N; n++ {\n\t\tfh, err := os.Open(testfile)\n\t\tif err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t\ttr := ourTar.NewReader(fh)\n\t\ttr.RawAccounting = true \n\t\tfor {\n\t\t\t_ = tr.RawBytes()\n\t\t\t_, err := tr.Next()\n\t\t\t_ = tr.RawBytes()\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfh.Close()\n\t\t\t\tb.Fatal(err)\n\t\t\t}\n\t\t\tio.Copy(ioutil.Discard, tr)\n\t\t\t_ = tr.RawBytes()\n\t\t}\n\t\tfh.Close()\n\t}\n}\n\nfunc BenchmarkUpstreamTar(b *testing.B) ", "output": "{\n\tfor n := 0; n < b.N; n++ {\n\t\tfh, err := os.Open(testfile)\n\t\tif err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t\ttr := upTar.NewReader(fh)\n\t\tfor {\n\t\t\t_, err := tr.Next()\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfh.Close()\n\t\t\t\tb.Fatal(err)\n\t\t\t}\n\t\t\tio.Copy(ioutil.Discard, tr)\n\t\t}\n\t\tfh.Close()\n\t}\n}"} {"input": "package utils\n\n\n\n\nfunc ParseGitCommand(command string) (typ string, repo string) ", "output": "{\n\tresult := gitCmdRx.FindStringSubmatch(command)\n\n\tif len(result) == 3 {\n\t\tif result[1] == \"git-receive-pack\" {\n\t\t\ttyp = \"push\"\n\t\t} else {\n\t\t\ttyp = \"fetch\"\n\t\t}\n\t\treturn typ, result[2]\n\t}\n\n\treturn \"\", \"\"\n}"} {"input": "package fakes\n\nimport (\n\tboshas \"github.com/cloudfoundry/bosh-agent/agent/applier/applyspec\"\n\t\"github.com/cloudfoundry/bosh-agent/agent/applier/models\"\n)\n\ntype FakeApplier struct {\n\tPrepared bool\n\tPrepareDesiredApplySpec boshas.ApplySpec\n\tPrepareError error\n\n\tApplied bool\n\tApplyCurrentApplySpec boshas.ApplySpec\n\tApplyDesiredApplySpec boshas.ApplySpec\n\tApplyError error\n\n\tConfigured bool\n\tConfiguredDesiredApplySpec boshas.ApplySpec\n\tConfiguredJobs []models.Job\n\tConfiguredError error\n}\n\nfunc NewFakeApplier() *FakeApplier {\n\treturn &FakeApplier{}\n}\n\n\n\nfunc (s *FakeApplier) ConfigureJobs(desiredApplySpec boshas.ApplySpec) error {\n\ts.Configured = true\n\ts.ConfiguredDesiredApplySpec = desiredApplySpec\n\treturn s.ConfiguredError\n}\n\nfunc (s *FakeApplier) Apply(currentApplySpec, desiredApplySpec boshas.ApplySpec) error {\n\ts.Applied = true\n\ts.ApplyCurrentApplySpec = currentApplySpec\n\ts.ApplyDesiredApplySpec = desiredApplySpec\n\treturn s.ApplyError\n}\n\nfunc (s *FakeApplier) Prepare(desiredApplySpec boshas.ApplySpec) error ", "output": "{\n\ts.Prepared = true\n\ts.PrepareDesiredApplySpec = desiredApplySpec\n\treturn s.PrepareError\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gogf/gf/v2/errors/gerror\"\n)\n\nfunc OpenFile() error {\n\treturn gerror.New(\"permission denied\")\n}\n\n\n\nfunc ReadConfig() error {\n\treturn gerror.Wrap(OpenConfig(), \"reading configuration failed\")\n}\n\nfunc main() {\n\tfmt.Println(gerror.Cause(ReadConfig()))\n}\n\nfunc OpenConfig() error ", "output": "{\n\treturn gerror.Wrap(OpenFile(), \"configuration file opening failed\")\n}"} {"input": "package govppmux\n\nimport \"time\"\n\n\ntype Config struct {\n\tReconnectResync bool `json:\"resync-after-reconnect\"`\n\n\tReplyTimeout time.Duration `json:\"reply-timeout\"`\n\n\tConnectViaShm bool `json:\"connect-via-shm\"`\n\n\tShmPrefix string `json:\"shm-prefix\"`\n\n\tBinAPISocketPath string `json:\"binapi-socket-path\"`\n\n\tStatsSocketPath string `json:\"stats-socket-path\"`\n\n\tRetryRequestCount int `json:\"retry-request-count\"`\n\n\tRetryRequestTimeout time.Duration `json:\"retry-request-timeout\"`\n\n\tRetryConnectCount int `json:\"retry-connect-count\"`\n\n\tRetryConnectTimeout time.Duration `json:\"retry-connect-timeout\"`\n\n\tProxyEnabled bool `json:\"proxy-enabled\"`\n\n\tHealthCheckProbeInterval time.Duration `json:\"health-check-probe-interval\"`\n\tHealthCheckReplyTimeout time.Duration `json:\"health-check-reply-timeout\"`\n\tHealthCheckThreshold int `json:\"health-check-threshold\"`\n\n\tTraceEnabled bool `json:\"trace-enabled\"`\n}\n\n\n\nfunc (p *Plugin) loadConfig() (*Config, error) {\n\tcfg := DefaultConfig()\n\tfound, err := p.Cfg.LoadValue(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if found {\n\t\tp.Log.Debugf(\"config loaded from file %q\", p.Cfg.GetConfigName())\n\t} else {\n\t\tp.Log.Debugf(\"config file %q not found, using default config\", p.Cfg.GetConfigName())\n\t}\n\treturn cfg, nil\n}\n\nfunc DefaultConfig() *Config ", "output": "{\n\treturn &Config{\n\t\tReconnectResync: true,\n\t\tHealthCheckProbeInterval: time.Second,\n\t\tHealthCheckReplyTimeout: 250 * time.Millisecond,\n\t\tHealthCheckThreshold: 1,\n\t\tReplyTimeout: time.Second,\n\t\tRetryRequestTimeout: 500 * time.Millisecond,\n\t\tRetryConnectTimeout: time.Second,\n\t\tProxyEnabled: true,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"crypto/rsa\"\n)\n\n\n\nfunc (h *handler) checkPubKeyAllowed(pubKey *rsa.PublicKey) bool ", "output": "{\n\tisAllowed, warnings := allowedKeysStore.CheckAllowed(pubKey)\n\tfor _, warn := range warnings {\n\t\th.logger.Warning(warn)\n\t}\n\treturn isAllowed\n}"} {"input": "package dockershim\n\nimport (\n\t\"context\"\n\n\truntimeapi \"k8s.io/cri-api/pkg/apis/runtime/v1alpha2\"\n)\n\n\nfunc (ds *dockerService) ContainerStats(_ context.Context, r *runtimeapi.ContainerStatsRequest) (*runtimeapi.ContainerStatsResponse, error) {\n\tstats, err := ds.getContainerStats(r.ContainerId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &runtimeapi.ContainerStatsResponse{Stats: stats}, nil\n}\n\n\n\n\nfunc (ds *dockerService) ListContainerStats(ctx context.Context, r *runtimeapi.ListContainerStatsRequest) (*runtimeapi.ListContainerStatsResponse, error) ", "output": "{\n\tcontainerStatsFilter := r.GetFilter()\n\tfilter := &runtimeapi.ContainerFilter{}\n\n\tif containerStatsFilter != nil {\n\t\tfilter.Id = containerStatsFilter.Id\n\t\tfilter.PodSandboxId = containerStatsFilter.PodSandboxId\n\t\tfilter.LabelSelector = containerStatsFilter.LabelSelector\n\t}\n\n\tlistResp, err := ds.ListContainers(ctx, &runtimeapi.ListContainersRequest{Filter: filter})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar stats []*runtimeapi.ContainerStats\n\tfor _, container := range listResp.Containers {\n\t\tcontainerStats, err := ds.getContainerStats(container.Id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif containerStats != nil {\n\t\t\tstats = append(stats, containerStats)\n\t\t}\n\t}\n\n\treturn &runtimeapi.ListContainerStatsResponse{Stats: stats}, nil\n}"} {"input": "package tparallel\n\nimport (\n\t\"go/types\"\n\t\"strings\"\n\n\t\"github.com/gostaticanalysis/analysisutil\"\n\t\"golang.org/x/tools/go/analysis/passes/buildssa\"\n\t\"golang.org/x/tools/go/ssa\"\n\n\t\"github.com/moricho/tparallel/pkg/ssainstr\"\n)\n\n\nfunc getTestMap(ssaanalyzer *buildssa.SSA, testTyp types.Type) map[*ssa.Function][]*ssa.Function {\n\ttestMap := map[*ssa.Function][]*ssa.Function{}\n\n\ttrun := analysisutil.MethodOf(testTyp, \"Run\")\n\tfor _, f := range ssaanalyzer.SrcFuncs {\n\t\tif !strings.HasPrefix(f.Name(), \"Test\") || !(f.Parent() == (*ssa.Function)(nil)) {\n\t\t\tcontinue\n\t\t}\n\t\ttestMap[f] = []*ssa.Function{}\n\t\tfor _, block := range f.Blocks {\n\t\t\tfor _, instr := range block.Instrs {\n\t\t\t\tcalled := analysisutil.Called(instr, nil, trun)\n\n\t\t\t\tif !called && ssainstr.HasArgs(instr, types.NewPointer(testTyp)) {\n\t\t\t\t\tif instrs, ok := ssainstr.LookupCalled(instr, trun); ok {\n\t\t\t\t\t\tfor _, v := range instrs {\n\t\t\t\t\t\t\ttestMap[f] = appendTestMap(testMap[f], v)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if called {\n\t\t\t\t\ttestMap[f] = appendTestMap(testMap[f], instr)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn testMap\n}\n\n\n\n\nfunc appendTestMap(subtests []*ssa.Function, instr ssa.Instruction) []*ssa.Function ", "output": "{\n\tcall, ok := instr.(ssa.CallInstruction)\n\tif !ok {\n\t\treturn subtests\n\t}\n\n\tssaCall := call.Value()\n\tfor _, arg := range ssaCall.Call.Args {\n\t\tswitch arg := arg.(type) {\n\t\tcase *ssa.Function:\n\t\t\tsubtests = append(subtests, arg)\n\t\tcase *ssa.MakeClosure:\n\t\t\tfn, _ := arg.Fn.(*ssa.Function)\n\t\t\tsubtests = append(subtests, fn)\n\t\t}\n\t}\n\n\treturn subtests\n}"} {"input": "package storage\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\tmgo \"github.com/ilius/mgo\"\n\t\"github.com/ilius/mgo/bson\"\n)\n\nfunc ModifyIndexTTL(db mgo.Database, collection string, index mgo.Index) error {\n\tkeyInfo, err := mgo.ParseIndexKey(index.Key)\n\tif err != nil {\n\t\treturn err\n\t}\n\texpireAfterSeconds := int(index.ExpireAfter / time.Second)\n\tfmt.Printf(\n\t\t\"Updating TTL on collection %s to expireAfterSeconds=%d\\n\",\n\t\tcollection,\n\t\texpireAfterSeconds,\n\t)\n\terr = db.Run(bson.D{\n\t\t{\"collMod\", collection},\n\t\t{\"index\", bson.M{\n\t\t\t\"keyPattern\": keyInfo.Key,\n\t\t\t\"expireAfterSeconds\": expireAfterSeconds,\n\t\t}},\n\t}, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc EnsureIndexWithTTL(db mgo.Database, collection string, index mgo.Index) error ", "output": "{\n\terr := db.C(collection).EnsureIndex(index)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"already exists with different options\") {\n\t\t\treturn ModifyIndexTTL(db, collection, index)\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package tests\n\n\n\nimport (\n\t\"testing\"\n)\n\n\n\n\nfunc TestInboxGETRequest(t *testing.T) {\n\tdesc := `\nServer: Fetching the inbox\n Try retrieving the actor's inbox of an actor.\n\n Server responds to GET request at inbox URL\n`\n\tt.Skip(desc)\n}\n\n\n\n\nfunc TestInboxIsOrderedCollection(t *testing.T) {\n\tdesc := `\nServer: Fetching the inbox\n Try retrieving the actor's inbox of an actor.\n\n inbox is an OrderedCollection\n`\n\tt.Skip(desc)\n}\n\n\n\n\n\n\nfunc TestInboxFilteringBasedOnPermissions(t *testing.T) ", "output": "{\n\tdesc := `\nServer: Fetching the inbox\n Try retrieving the actor's inbox of an actor.\n\n Server filters inbox content according to the requester's permission\n`\n\tt.Skip(desc)\n}"} {"input": "package migrationmaster_test\n\nimport (\n\t\"testing\"\n\n\tgc \"gopkg.in/check.v1\"\n)\n\n\n\nfunc Test(t *testing.T) ", "output": "{\n\tgc.TestingT(t)\n}"} {"input": "package dep\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net/http\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n\n\t\"github.com/micromdm/micromdm/dep\"\n\t\"github.com/micromdm/micromdm/pkg/httputil\"\n)\n\nfunc (svc *DEPService) DefineProfile(ctx context.Context, p *dep.Profile) (*dep.ProfileResponse, error) {\n\tif svc.client == nil {\n\t\treturn nil, errors.New(\"DEP not configured yet. add a DEP token to enable DEP\")\n\t}\n\treturn svc.client.DefineProfile(p)\n}\n\ntype defineProfileRequest struct{ *dep.Profile }\ntype defineProfileResponse struct {\n\t*dep.ProfileResponse\n\tErr error `json:\"err,omitempty\"`\n}\n\nfunc (r defineProfileResponse) Failed() error { return r.Err }\n\nfunc decodeDefineProfileRequest(ctx context.Context, r *http.Request) (interface{}, error) {\n\tvar req defineProfileRequest\n\terr := httputil.DecodeJSONRequest(r, &req)\n\treturn req, err\n}\n\nfunc decodeDefineProfileResponse(_ context.Context, r *http.Response) (interface{}, error) {\n\tvar resp defineProfileResponse\n\terr := httputil.DecodeJSONResponse(r, &resp)\n\treturn resp, err\n}\n\n\n\nfunc (e Endpoints) DefineProfile(ctx context.Context, p *dep.Profile) (*dep.ProfileResponse, error) {\n\trequest := defineProfileRequest{Profile: p}\n\tresp, err := e.DefineProfileEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponse := resp.(defineProfileResponse)\n\treturn response.ProfileResponse, response.Err\n}\n\nfunc MakeDefineProfileEndpoint(svc Service) endpoint.Endpoint ", "output": "{\n\treturn func(ctx context.Context, request interface{}) (response interface{}, err error) {\n\t\treq := request.(defineProfileRequest)\n\t\tresp, err := svc.DefineProfile(ctx, req.Profile)\n\t\treturn &defineProfileResponse{\n\t\t\tProfileResponse: resp,\n\t\t\tErr: err,\n\t\t}, nil\n\t}\n}"} {"input": "package memorytopo\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/youtube/vitess/go/vt/topo\"\n)\n\n\n\n\nfunc (mt *MemoryTopo) ListDir(ctx context.Context, cell, dirPath string) ([]string, error) ", "output": "{\n\tmt.mu.Lock()\n\tdefer mt.mu.Unlock()\n\n\tn := mt.nodeByPath(cell, dirPath)\n\tif n == nil {\n\t\treturn nil, topo.ErrNoNode\n\t}\n\n\tif !n.isDirectory() {\n\t\treturn nil, fmt.Errorf(\"node %v in cell %v is not a directory\", dirPath, cell)\n\t}\n\n\tvar result []string\n\tfor n := range n.children {\n\t\tresult = append(result, n)\n\t}\n\tsort.Strings(result)\n\treturn result, nil\n}"} {"input": "package proj4go\n\nimport (\n\t\"fmt\"\n\n\tgeo \"github.com/terrascope/geometry\"\n)\n\n\ntype Projection interface {\n\tForward([]geo.Point) error\n\tInverse([]geo.Point) error\n}\n\nfunc NewProjection(proj4Str string) (Projection, error) {\n\n\tproj4, err := ParseProj4String(proj4Str)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch proj4.Proj {\n\tcase \"aea\":\n\t\treturn NewAEA(proj4), nil\n\tcase \"merc\":\n\t\treturn NewMerc(proj4), nil\n\tcase \"equi\":\n\t\treturn NewEqui(proj4), nil\n\tcase \"mill\":\n\t\treturn NewMiller(proj4), nil\n\tcase \"sinu\":\n\t\treturn NewSinu(proj4), nil\n\tcase \"longlat\":\n\t\treturn NewLonLat(proj4), nil\n\t}\n\treturn nil, fmt.Errorf(\"could not find projection %s in list\", proj4.Proj)\n}\n\n\n\nfunc Inverse(dst string, pts []geo.Point) error {\n\n\tproj, err := NewProjection(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = proj.Inverse(pts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc Transform(src, dst string, pts []geo.Point) error {\n\tif src == dst {\n\t\treturn nil\n\t}\n\n\tif err := Inverse(dst, pts); err != nil {\n\t\treturn err\n\t}\n\tif err := Forwards(src, pts); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc Forwards(dst string, pts []geo.Point) error ", "output": "{\n\n\tproj, err := NewProjection(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = proj.Forward(pts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package coap\n\nimport (\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"io\"\n)\n\n\n\ntype TcpMessage struct {\n\tMessage\n}\n\nfunc (m *TcpMessage) MarshalBinary() ([]byte, error) {\n\tbin, err := m.Message.MarshalBinary()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\n\tl := []byte{0, 0}\n\tbinary.BigEndian.PutUint16(l, uint16(len(bin)))\n\n\treturn append(l, bin...), nil\n}\n\n\n\n\nfunc Decode(r io.Reader) (*TcpMessage, error) {\n\tvar ln uint16\n\terr := binary.Read(r, binary.BigEndian, &ln)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpacket := make([]byte, ln)\n\t_, err = io.ReadFull(r, packet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm := TcpMessage{}\n\n\terr = m.UnmarshalBinary(packet)\n\treturn &m, err\n}\n\nfunc (m *TcpMessage) UnmarshalBinary(data []byte) error ", "output": "{\n\tif len(data) < 4 {\n\t\treturn errors.New(\"short packet\")\n\t}\n\n\treturn m.Message.UnmarshalBinary(data)\n}"} {"input": "package demo\n\nimport (\n\t\"fmt\"\n\t\"github.com/mabetle/mcore/mconf\"\n)\n\n\n\n\nfunc DemoConfig(mconf mconf.Config) ", "output": "{\n\tfmt.Println(\"IsContain('no-exist'):\", mconf.IsContain(\"no-exist\"))\n\tfmt.Println(\"GetString('db.spec'):\", mconf.GetString(\"db.spec\"))\n\tfmt.Println(\"GetString('db2.spec'):\", mconf.GetString(\"db2.spec\"))\n}"} {"input": "package plugin\n\n\n\nimport (\n\t\"github.com/apache/trafficcontrol/traffic_ops_ort/atstccfg/config\"\n)\n\nfunc init() {\n}\n\nconst HelloPath = \"/_hello_world\"\n\n\n\n\nfunc hello(d ModifyFilesData) []config.ATSConfigFile ", "output": "{\n\thasHelloParam := false\n\tfor _, param := range d.TOData.ServerParams {\n\t\tif param.Name == \"enable_hello_world\" && param.ConfigFile == \"hello_world\" && param.Value == \"true\" {\n\t\t\thasHelloParam = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !hasHelloParam {\n\t\treturn d.Files\n\t}\n\n\tfi := config.ATSConfigFile{}\n\n\tfi.Text = \"Hello, World!\\n\"\n\tfi.ContentType = \"text/plain\"\n\tfi.LineComment = \"\"\n\tfi.Name = \"hello.txt\"\n\tfi.Path = \"/opt/trafficserver/etc/trafficserver/\"\n\n\td.Files = append(d.Files, fi)\n\treturn d.Files\n}"} {"input": "package main\n\nimport \"testing\"\n\n\n\nfunc TestStartPortNumber(t *testing.T) ", "output": "{\n\n\ttype assert struct {\n\t\tcurrentProcs []*Proc\n\t\texpect int\n\t}\n\n\tasserts := []assert{\n\t\tassert{\n\t\t\tcurrentProcs: nil,\n\t\t\texpect: 8000,\n\t\t},\n\t\tassert{\n\t\t\tcurrentProcs: []*Proc{&Proc{Port: 8000}},\n\t\t\texpect: 9000,\n\t\t},\n\t\tassert{\n\t\t\tcurrentProcs: []*Proc{&Proc{Port: 9000}},\n\t\t\texpect: 8000,\n\t\t},\n\t}\n\n\tfor _, a := range asserts {\n\t\tport := Service{OldProcs: a.currentProcs}.startPortNumber()\n\t\tif port != a.expect {\n\t\t\tt.Errorf(\"port should be %d, but %d\", a.expect, port)\n\t\t}\n\t}\n\n}"} {"input": "package metrics\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestTDigestUsage(t *testing.T) {\n\tr := NewNamespaceRegistry(\"\")\n\n\ttdigest := NewTDigest([]float64{1, 0.5, 0.75})\n\n\tr.Register(&SingleCollectable{\n\t\tMetric: Metric{\n\t\t\tName: \"topname\",\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"test\": \"true\",\n\t\t\t},\n\t\t},\n\t\tCollectable: tdigest,\n\t})\n\n\ttdigest.Observe(float64(time.Second))\n\n\tprintCollectable(r)\n\n}\n\n\n\nfunc TestTDigestArrayUsage(t *testing.T) ", "output": "{\n\tr := NewNamespaceRegistry(\"\")\n\n\tm := Metric{\n\t\tName: \"tdigest_vector\",\n\t\tLabels: map[string]string{\n\t\t\t\"top\": \"true\",\n\t\t},\n\t}\n\n\tarr := NewCollectableArray(m, NewTDigestCreator([]float64{1, 0.5, 0.75}), []string{\"handler\", \"code\"})\n\n\tr.Register(arr)\n\n\tarr.ObserveWithValues(\"/foo\", \"200\").Observe(1)\n\tarr.ObserveWithValues(\"/foo\", \"500\").Observe(2)\n\tarr.ObserveWithValues(\"/foo\", \"502\").Observe(3)\n\n\tprintCollectable(r)\n\n}"} {"input": "package minicon\n\nimport \"container/ring\"\n\n\n\n\ntype History struct {\n\tr *ring.Ring\n}\n\n\n\n\ntype HistoryMarker *ring.Ring\n\n\n\n\nfunc NewHistory(capacity int) *History {\n\treturn &History{ring.New(capacity)}\n}\n\n\n\n\n\n\nfunc (hs *History) Add(s string, mark HistoryMarker) HistoryMarker {\n\ths.Restore(mark)\n\tif s != \"\" && hs.r.Value != s {\n\t\ths.r.Value = s\n\t\ths.r = hs.r.Next()\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (hs *History) Back() (string, bool) {\n\treturn hs._update(hs.r.Prev())\n}\n\n\n\n\n\nfunc (hs *History) Forward() (string, bool) {\n\treturn hs._update(hs.r.Next())\n}\n\n\n\n\nfunc (hs *History) Mark() HistoryMarker {\n\treturn hs.r\n}\n\n\n\n\nfunc (hs *History) Restore(mark HistoryMarker) {\n\tif mark != nil {\n\t\ths.r = mark\n\t}\n}\n\n\n\n\n\n\nfunc (hs *History) _update(r *ring.Ring) (ret string, okay bool) ", "output": "{\n\tif s, ok := r.Value.(string); ok && s != \"\" {\n\t\ths.r = r\n\t\tret, okay = s, ok\n\t}\n\treturn ret, okay\n}"} {"input": "package models\n\nimport (\n\t\"html/template\"\n\t\"time\"\n\n\t\"github.com/NyaaPantsu/nyaa/config\"\n)\n\n\ntype Comment struct {\n\tID uint `gorm:\"column:comment_id;primary_key\"`\n\tTorrentID uint `gorm:\"column:torrent_id\"`\n\tUserID uint `gorm:\"column:user_id\"`\n\tContent string `gorm:\"column:content\"`\n\tCreatedAt time.Time `gorm:\"column:created_at\"`\n\tUpdatedAt time.Time `gorm:\"column:updated_at\"`\n\tDeletedAt *time.Time\n\n\tTorrent *Torrent `gorm:\"AssociationForeignKey:TorrentID;ForeignKey:torrent_id\"`\n\tUser *User `gorm:\"AssociationForeignKey:UserID;ForeignKey:user_id\"`\n}\n\n\ntype CommentJSON struct {\n\tUsername string `json:\"username\"`\n\tUserID int `json:\"user_id\"`\n\tUserAvatar string `json:\"user_avatar\"`\n\tContent template.HTML `json:\"content\"`\n\tDate time.Time `json:\"date\"`\n}\n\n\nfunc (c Comment) Size() int {\n\treturn (3 + 3*3 + 2 + 2 + len(c.Content)) * 8\n}\n\n\nfunc (c Comment) TableName() string {\n\treturn config.Get().Models.CommentsTableName\n}\n\n\n\n\nfunc (c *Comment) Identifier() string ", "output": "{ \n\treturn c.Torrent.Identifier()\n}"} {"input": "package codename_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/jgautheron/codename-generator\"\n)\n\n\n\nfunc TestCodenameGeneration(t *testing.T) ", "output": "{\n\tvar cn string\n\tvar err error\n\n\tcn, err = codename.Get(codename.Sanitized)\n\tif err != nil {\n\t\tt.Error(\"The codename was not generated\")\n\t}\n\tif len(cn) < 3 {\n\t\tt.Error(\"The codename generated is invalid\")\n\t}\n\n\tcn, err = codename.Get(codename.SpacedString)\n\tif err != nil {\n\t\tt.Error(\"The codename was not generated\")\n\t}\n\tif len(cn) < 3 {\n\t\tt.Error(\"The codename generated is invalid\")\n\t}\n}"} {"input": "package gluster\n\nimport \"testing\"\n\nfunc init() {\n\tExecRunner = TestRunner{}\n}\n\nfunc TestGetVolumeUsage(t *testing.T) {\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project_pv1\"}\n\n\tvolInfo, _ := getVolumeUsage(\"gl-project-pv1\")\n\n\tequals(t, 49664, volInfo.TotalKiloBytes)\n\tequals(t, 2864, volInfo.UsedKiloBytes)\n}\n\nfunc TestGetVolumeUsage_LongProject(t *testing.T) {\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project--long_pv1\"}\n\n\tvolInfo, _ := getVolumeUsage(\"gl-project-long-pv1\")\n\n\tequals(t, 49664, volInfo.TotalKiloBytes)\n\tequals(t, 2864, volInfo.UsedKiloBytes)\n}\n\n\n\nfunc TestCheckVolumeUsage_OK(t *testing.T) {\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project_pv1\"}\n\n\terr := checkVolumeUsage(\"gl-project-pv1\", \"20\")\n\tok(t, err)\n}\n\nfunc TestCheckVolumeUsage_Error(t *testing.T) {\n\toutput = []string{\" 49664 49555 /dev/mapper/vg_mylv_project_pv1\"}\n\n\terr := checkVolumeUsage(\"gl-project-pv1\", \"20\")\n\tassert(t, err != nil, \"Should return error as bigger than threshold\")\n}\n\nfunc TestGetVolumeUsage_LongProjectHighNumber(t *testing.T) ", "output": "{\n\toutput = []string{\" 49664 2864 /dev/mapper/vg_mylv_project--very--very--long_pv20\"}\n\n\tvolInfo, _ := getVolumeUsage(\"gl-project-very-very-long-pv20\")\n\n\tequals(t, 49664, volInfo.TotalKiloBytes)\n\tequals(t, 2864, volInfo.UsedKiloBytes)\n}"} {"input": "package v1\n\n\n\n\n\n\n\n\n\n\n\n\nvar map_PriorityClass = map[string]string{\n\t\"\": \"PriorityClass defines mapping from a priority class name to the priority integer value. The value can be any valid integer.\",\n\t\"metadata\": \"Standard object's metadata. More info: https:git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata\",\n\t\"value\": \"The value of this priority class. This is the actual priority that pods receive when they have the name of this class in their pod spec.\",\n\t\"globalDefault\": \"globalDefault specifies whether this PriorityClass should be considered as the default priority for pods that do not have any priority class. Only one PriorityClass can be marked as `globalDefault`. However, if more than one PriorityClasses exists with their `globalDefault` field set to true, the smallest value of such global default PriorityClasses will be used as the default priority.\",\n\t\"description\": \"description is an arbitrary string that usually provides guidelines on when this priority class should be used.\",\n\t\"preemptionPolicy\": \"PreemptionPolicy is the Policy for preempting pods with lower priority. One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset.\",\n}\n\n\n\nvar map_PriorityClassList = map[string]string{\n\t\"\": \"PriorityClassList is a collection of priority classes.\",\n\t\"metadata\": \"Standard list metadata More info: https:git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata\",\n\t\"items\": \"items is the list of PriorityClasses\",\n}\n\nfunc (PriorityClassList) SwaggerDoc() map[string]string {\n\treturn map_PriorityClassList\n}\n\nfunc (PriorityClass) SwaggerDoc() map[string]string ", "output": "{\n\treturn map_PriorityClass\n}"} {"input": "package iso20022\n\n\ntype SettlementDetails88 struct {\n\n\tTradeDate *ISODateTime `xml:\"TradDt\"`\n\n\tSettlementParties *SettlementParties3Choice `xml:\"SttlmPties,omitempty\"`\n\n\tCollateralOwnership *CollateralOwnership1 `xml:\"CollOwnrsh\"`\n}\n\nfunc (s *SettlementDetails88) SetTradeDate(value string) {\n\ts.TradeDate = (*ISODateTime)(&value)\n}\n\nfunc (s *SettlementDetails88) AddSettlementParties() *SettlementParties3Choice {\n\ts.SettlementParties = new(SettlementParties3Choice)\n\treturn s.SettlementParties\n}\n\n\n\nfunc (s *SettlementDetails88) AddCollateralOwnership() *CollateralOwnership1 ", "output": "{\n\ts.CollateralOwnership = new(CollateralOwnership1)\n\treturn s.CollateralOwnership\n}"} {"input": "package datascience\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype UpdateModelRequest struct {\n\n\tModelId *string `mandatory:\"true\" contributesTo:\"path\" name:\"modelId\"`\n\n\tUpdateModelDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateModelRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request UpdateModelRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request UpdateModelRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request UpdateModelRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateModelResponse struct {\n\n\tRawResponse *http.Response\n\n\tModel `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response UpdateModelResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response UpdateModelResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package version\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"go-common/app/interface/main/creative/conf\"\n\t\"go-common/app/interface/main/creative/model/version\"\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"go-common/app/interface/main/creative/service\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nvar (\n\ts *Service\n)\n\nfunc init() {\n\tdir, _ := filepath.Abs(\"../../cmd/creative.toml\")\n\tflag.Set(\"conf\", dir)\n\tconf.Init()\n\trpcdaos := service.NewRPCDaos(conf.Conf)\n\ts = New(conf.Conf, rpcdaos)\n\ttime.Sleep(time.Second)\n}\n\n\n\nfunc Test_VersionMap(t *testing.T) {\n\tvar (\n\t\tc = context.Background()\n\t\terr error\n\t\tversions = make(map[string][]*version.Version)\n\t)\n\tConvey(\"versionMap\", t, WithService(func(s *Service) {\n\t\tversions, err = s.versionMap(c)\n\t\tSo(err, ShouldBeNil)\n\t\tSo(versions, ShouldNotBeNil)\n\t}))\n}\n\nfunc WithService(f func(s *Service)) func() ", "output": "{\n\treturn func() {\n\t\tReset(func() {})\n\t\tf(s)\n\t}\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realIAMInstanceProfile IAMInstanceProfile\n\n\n\nvar _ fi.HasName = &IAMInstanceProfile{}\n\nfunc (e *IAMInstanceProfile) GetName() *string {\n\treturn e.Name\n}\n\nfunc (e *IAMInstanceProfile) SetName(name string) {\n\te.Name = &name\n}\n\nfunc (e *IAMInstanceProfile) String() string {\n\treturn fi.TaskAsString(e)\n}\n\nfunc (o *IAMInstanceProfile) UnmarshalJSON(data []byte) error ", "output": "{\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realIAMInstanceProfile\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = IAMInstanceProfile(r)\n\treturn nil\n}"} {"input": "package batch\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype ManagementClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {\n\treturn ManagementClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) ManagementClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package myfunc\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"rsc.io/quote\"\n)\n\n\n\n\nfunc Func(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tif quote.Hello() == \"Hello, world.\" {\n\t\tfmt.Fprintf(w, \"PASS\")\n\t} else {\n\t\tfmt.Fprintln(w, \"FAIL\")\n\t}\n}"} {"input": "package nats\n\nimport (\n\t\"github.com/apcera/nats\"\n\t\"github.com/plimble/kuja/broker\"\n)\n\ntype natsBroker struct {\n\turl string\n\tconn *nats.Conn\n}\n\nfunc NewBroker(url string) *natsBroker {\n\treturn &natsBroker{\n\t\turl: url,\n\t}\n}\n\n\n\nfunc (n *natsBroker) Close() {\n\tn.conn.Close()\n}\n\nfunc (n *natsBroker) Publish(topic string, msg *broker.Message) error {\n\tdata, err := msg.Marshal()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn n.conn.Publish(topic, data)\n}\n\nfunc (n *natsBroker) Subscribe(topic, queue, appId string, size int, h broker.Handler) {\n\tfor i := 0; i < size; i++ {\n\t\tn.conn.QueueSubscribe(topic, queue, func(msg *nats.Msg) {\n\t\t\tbrokerMsg := &broker.Message{}\n\t\t\tbrokerMsg.Unmarshal(msg.Data)\n\t\t\tretryCount, err := h(msg.Subject, brokerMsg)\n\t\t\tif err != nil {\n\t\t\t\tfor i := 0; i < retryCount; i++ {\n\t\t\t\t\tbrokerMsg.Retry++\n\t\t\t\t\t_, err := h(topic, brokerMsg)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc (n *natsBroker) Connect() error ", "output": "{\n\tvar err error\n\tn.conn, err = nats.Connect(n.url)\n\n\treturn err\n}"} {"input": "package lnwire\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\ntype NeighborAckMessage struct {\n\tRoutingMessageBase\n}\n\nfunc (msg *NeighborAckMessage) String() string {\n\treturn fmt.Sprintf(\"NeighborAckMessage{%v %v}\", msg.SenderID, msg.ReceiverID)\n}\n\nfunc (msg *NeighborAckMessage) Command() uint32{\n\treturn CmdNeighborAckMessage\n}\n\n\n\nfunc (msg *NeighborAckMessage) Decode(r io.Reader, pver uint32) error{\n\treturn nil\n}\n\nfunc (msg *NeighborAckMessage) MaxPayloadLength(uint32) uint32{\n\treturn 0\n}\n\nfunc (msg *NeighborAckMessage) Validate() error{\n\treturn nil\n}\n\nvar _ Message = (*NeighborAckMessage)(nil)\n\nfunc (msg *NeighborAckMessage) Encode(w io.Writer, pver uint32) error", "output": "{\n\treturn nil\n}"} {"input": "package dynaml\n\nimport (\n\t\"fmt\"\n)\n\ntype ModuloExpr struct {\n\tA Expression\n\tB Expression\n}\n\n\n\nfunc (e ModuloExpr) String() string {\n\treturn fmt.Sprintf(\"%s %% %s\", e.A, e.B)\n}\n\nfunc (e ModuloExpr) Evaluate(binding Binding, locally bool) (interface{}, EvaluationInfo, bool) ", "output": "{\n\tresolved := true\n\n\taint, info, ok := ResolveIntegerExpressionOrPushEvaluation(&e.A, &resolved, nil, binding, false)\n\tif !ok {\n\t\treturn nil, info, false\n\t}\n\n\tbint, info, ok := ResolveIntegerExpressionOrPushEvaluation(&e.B, &resolved, &info, binding, false)\n\tif !ok {\n\t\treturn nil, info, false\n\t}\n\n\tif !resolved {\n\t\treturn e, info, true\n\t}\n\n\tif bint == 0 {\n\t\treturn info.Error(\"division by zero\")\n\t}\n\treturn aint % bint, info, true\n}"} {"input": "package rorm\n\ntype rorm struct {\n\tredisQuerier *RedisQuerier\n}\n\nfunc NewROrm() ROrmer {\n\treturn new(rorm).Using(\"default\")\n}\n\nfunc (r *rorm) QueryHash(key string) HashQuerySeter {\n\treturn &hashQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QueryKeys(key string) KeysQuerySeter {\n\treturn &keysQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QueryString(key string) StringQuerySeter {\n\treturn &stringQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\n\n\nfunc (r *rorm) QuerySet(key string) SetQuerySeter {\n\treturn &setQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r rorm) Using(alias string) ROrmer {\n\tclient, ok := redisRegistry[alias]\n\tif !ok {\n\t\tpanic(\"using reids '\" + alias + \"' not exist.\")\n\t}\n\tr.redisQuerier = &RedisQuerier{\n\t\tClient: client,\n\t}\n\treturn &r\n}\n\nfunc (r *rorm) Querier() Querier {\n\treturn r.redisQuerier\n}\n\nfunc (r *rorm) QueryZSet(key string) ZSetQuerySeter ", "output": "{\n\treturn &zsetQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"github.com/kubeflow/pipelines/backend/src/common/util\"\n\t\"github.com/kubeflow/pipelines/backend/src/crd/pkg/client/informers/externalversions/scheduledworkflow/v1beta1\"\n\t_ \"k8s.io/client-go/plugin/pkg/client/auth/gcp\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\ntype ScheduledWorkflowClientInterface interface {\n\tGet(namespace string, name string) (swf *util.ScheduledWorkflow, err error)\n}\n\n\ntype ScheduledWorkflowClient struct {\n\tinformer v1beta1.ScheduledWorkflowInformer\n}\n\n\n\n\n\nfunc (c *ScheduledWorkflowClient) AddEventHandler(funcs *cache.ResourceEventHandlerFuncs) {\n\tc.informer.Informer().AddEventHandler(funcs)\n}\n\n\nfunc (c *ScheduledWorkflowClient) HasSynced() func() bool {\n\treturn c.informer.Informer().HasSynced\n}\n\n\nfunc (c *ScheduledWorkflowClient) Get(namespace string, name string) (\n\tswf *util.ScheduledWorkflow, err error) {\n\tschedule, err := c.informer.Lister().ScheduledWorkflows(namespace).Get(name)\n\tif err != nil {\n\t\tvar code util.CustomCode\n\t\tif util.IsNotFound(err) {\n\t\t\tcode = util.CUSTOM_CODE_NOT_FOUND\n\t\t} else {\n\t\t\tcode = util.CUSTOM_CODE_GENERIC\n\t\t}\n\t\treturn nil, util.NewCustomError(err, code,\n\t\t\t\"Error retrieving scheduled workflow (%v) in namespace (%v): %v\", name, namespace, err)\n\t}\n\n\treturn util.NewScheduledWorkflow(schedule), nil\n}\n\nfunc NewScheduledWorkflowClient(informer v1beta1.ScheduledWorkflowInformer) *ScheduledWorkflowClient ", "output": "{\n\treturn &ScheduledWorkflowClient{\n\t\tinformer: informer,\n\t}\n}"} {"input": "package otel \n\n\n\n\nfunc Version() string ", "output": "{\n\treturn \"0.15.0\"\n}"} {"input": "package main\n\n\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/mediocregopher/seq\"\n)\n\n\n\nfunc seqIoThunk(reader *bufio.Reader, delim byte) seq.Thunk {\n\treturn func() (interface{}, seq.Thunk, bool) {\n\t\tdata, err := reader.ReadString(delim)\n\t\tif err != nil {\n\t\t\treturn nil, nil, false\n\t\t}\n\t\ttdata := strings.TrimRight(data, \"\\n\")\n\t\treturn tdata, seqIoThunk(reader, delim), true\n\t}\n}\n\n\n\nfunc main() {\n\tfile, err := os.Open(\"/tmp/numbers\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsir := NewSeqIoReader(file, '\\n')\n\n\tfmt.Println(sir)\n\tfmt.Println(sir)\n}\n\nfunc NewSeqIoReader(read io.Reader, delim byte) *seq.Lazy ", "output": "{\n\tthunk := seqIoThunk(bufio.NewReader(read), delim)\n\treturn seq.NewLazy(thunk)\n}"} {"input": "package template\n\nimport (\n\t\"io\"\n)\n\ntype astImport struct {\n\talias string\n\tpkgName string\n}\n\n\n\nfunc (*astImport) GetStrings() []string { return []string{} }\n\nfunc (n *astImport) WriteGo(w io.Writer, opts *GenGoOpts) {\n\tif n.alias != \"\" {\n\t\tio.WriteString(w, n.alias+\" \")\n\t}\n\tio.WriteString(w, n.pkgName+\"\\n\")\n}\n\nfunc (*astImport) GetImports() []string ", "output": "{ return []string{} }"} {"input": "package ctxhttp_test\n\nimport (\n\t\"net/http\"\n\t\"testing\"\n\n\t\"errors\"\n\t\"github.com/corestoreio/csfw/net/ctxhttp\"\n\t\"github.com/juju/errgo\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestNewError(t *testing.T) {\n\ttests := []struct {\n\t\tcode int\n\t\tmsg []string\n\t\twantError string\n\t}{\n\t\t{http.StatusBadGateway, nil, http.StatusText(http.StatusBadGateway)},\n\t\t{http.StatusTeapot, []string{\"No coffee pot\", \"ignored\"}, \"No coffee pot\"},\n\t}\n\tfor _, test := range tests {\n\t\the := ctxhttp.NewError(test.code, test.msg...)\n\t\tassert.Exactly(t, test.code, he.Code)\n\t\tassert.Exactly(t, test.wantError, he.Error())\n\t}\n}\n\n\n\nfunc TestNewErrorFromErrors(t *testing.T) ", "output": "{\n\ttests := []struct {\n\t\tcode int\n\t\terrs []error\n\t\twantError string\n\t}{\n\t\t{http.StatusBadGateway, nil, http.StatusText(http.StatusBadGateway)},\n\t\t{http.StatusTeapot, []error{errors.New(\"No coffee pot\"), errors.New(\"Not even a milk pot\")}, \"No coffee pot\\nNot even a milk pot\"},\n\t\t{http.StatusConflict, []error{errgo.New(\"Now a coffee pot\"), errgo.New(\"Not even close to a milk pot\")}, \"error_test.go\"},\n\t}\n\tfor _, test := range tests {\n\t\the := ctxhttp.NewErrorFromErrors(test.code, test.errs...)\n\t\tassert.Exactly(t, test.code, he.Code)\n\t\tassert.Contains(t, he.Error(), test.wantError)\n\t}\n}"} {"input": "package k8sutil\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"k8s.io/client-go/1.5/pkg/api/errors\"\n\t\"k8s.io/client-go/1.5/pkg/api/v1\"\n\t\"k8s.io/client-go/1.5/pkg/util/wait\"\n\t\"k8s.io/client-go/1.5/rest\"\n)\n\n\n\n\n\n\n\nfunc PodRunningAndReady(pod v1.Pod) (bool, error) {\n\tswitch pod.Status.Phase {\n\tcase v1.PodFailed, v1.PodSucceeded:\n\t\treturn false, fmt.Errorf(\"pod completed\")\n\tcase v1.PodRunning:\n\t\tfor _, cond := range pod.Status.Conditions {\n\t\t\tif cond.Type != v1.PodReady {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn cond.Status == v1.ConditionTrue, nil\n\t\t}\n\t\treturn false, fmt.Errorf(\"pod ready condition not found\")\n\t}\n\treturn false, nil\n}\n\nfunc WaitForTPRReady(restClient *rest.RESTClient, tprGroup, tprVersion, tprName string) error ", "output": "{\n\treturn wait.Poll(3*time.Second, 30*time.Second, func() (bool, error) {\n\t\treq := restClient.Get().AbsPath(\"apis\", tprGroup, tprVersion, tprName)\n\t\tres := req.Do()\n\t\terr := res.Error()\n\t\tif err != nil {\n\t\t\tif se, ok := err.(*errors.StatusError); ok {\n\t\t\t\tif se.Status().Code == http.StatusNotFound {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar statusCode int\n\t\tres.StatusCode(&statusCode)\n\t\tif statusCode != http.StatusOK {\n\t\t\treturn false, fmt.Errorf(\"invalid status code: %v\", statusCode)\n\t\t}\n\n\t\treturn true, nil\n\t})\n}"} {"input": "package worker_test\n\nimport (\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/ffloyd/evergrid-go/simenv\"\n\t\"github.com/ffloyd/evergrid-go/simulator/comm\"\n)\n\ntype SenderAgent struct {\n\tname string\n\tfsm simenv.AgentFSM\n\tsimenv *simenv.SimEnv\n\n\tworkerName string\n\trequests []interface{}\n\n\tlog *logrus.Entry\n}\n\nfunc NewSenderAgent(name string, worker string, requests []interface{}, logContext *logrus.Entry) *SenderAgent {\n\treturn &SenderAgent{\n\t\tname: name,\n\t\trequests: requests,\n\t\tworkerName: worker,\n\t\tlog: logContext,\n\t}\n}\n\nfunc (sa *SenderAgent) Name() string {\n\treturn sa.name\n}\n\nfunc (sa *SenderAgent) Run(env *simenv.SimEnv) simenv.AgentChans {\n\tsa.simenv = env\n\tsa.fsm = *simenv.NewAgentFSM(sa.log.WithFields(logrus.Fields{\n\t\t\"agent\": sa.Name(),\n\t\t\"tick\": env.CurrentTick(),\n\t}))\n\tgo sa.work()\n\treturn sa.fsm.Chans()\n}\n\nfunc (sa *SenderAgent) Send(msg interface{}) chan interface{} {\n\tpanic(\"No implementation\")\n}\n\n\n\nfunc (sa *SenderAgent) work() ", "output": "{\n\treqIndex := 0\n\tworker := sa.simenv.Find(sa.workerName)\n\n\tfor {\n\t\tsa.fsm.ToReady()\n\t\tsa.fsm.ToWorking()\n\t\tif reqIndex < len(sa.requests) {\n\t\t\tbusyStatus := <-worker.Send(comm.WorkerBusy{})\n\t\t\tswitch value := busyStatus.(type) {\n\t\t\tcase bool:\n\t\t\t\tif !value {\n\t\t\t\t\t<-worker.Send(sa.requests[reqIndex])\n\t\t\t\t\treqIndex++\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tsa.log.Panic(\"Invalid worker response\")\n\t\t\t}\n\t\t} else {\n\t\t\tsa.fsm.SetStopFlag(true)\n\t\t}\n\t\tsa.fsm.ToIdle()\n\t\t<-sa.fsm.ToDoneChan()\n\t}\n}"} {"input": "package cli\n\nimport (\n\t\"fmt\"\n\n\t\"go.uber.org/zap\"\n\n\t\"github.com/pingcap/tidb/dumpling/log\"\n)\n\nvar (\n\tReleaseVersion = \"Unknown\"\n\tBuildTimestamp = \"Unknown\"\n\tGitHash = \"Unknown\"\n\tGitBranch = \"Unknown\"\n\tGoVersion = \"Unknown\"\n)\n\n\nfunc LongVersion() string {\n\treturn fmt.Sprintf(\n\t\t\"Release version: %s\\n\"+\n\t\t\t\"Git commit hash: %s\\n\"+\n\t\t\t\"Git branch: %s\\n\"+\n\t\t\t\"Build timestamp: %sZ\\n\"+\n\t\t\t\"Go version: %s\\n\",\n\t\tReleaseVersion,\n\t\tGitHash,\n\t\tGitBranch,\n\t\tBuildTimestamp,\n\t\tGoVersion,\n\t)\n}\n\n\n\n\nfunc LogLongVersion(logger log.Logger) ", "output": "{\n\tlogger.Info(\"Welcome to dumpling\",\n\t\tzap.String(\"Release Version\", ReleaseVersion),\n\t\tzap.String(\"Git Commit Hash\", GitHash),\n\t\tzap.String(\"Git Branch\", GitBranch),\n\t\tzap.String(\"Build timestamp\", BuildTimestamp),\n\t\tzap.String(\"Go Version\", GoVersion))\n}"} {"input": "package httpware\n\nimport \"strings\"\n\nvar contentTypeStrings = []string{\"json\", \"xml\"}\n\nconst (\n\tJSON = iota\n\tXML\n)\n\n\ntype ContentType uint32\n\n\n\n\n\nfunc ContentTypeFromHeader(header string) ContentType ", "output": "{\n\tfor i, s := range contentTypeStrings {\n\t\tif strings.Contains(header, s) {\n\t\t\treturn ContentType(i)\n\t\t}\n\t}\n\treturn JSON\n}"} {"input": "package log\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n)\n\nvar (\n\tinternalLog *logMux\n\tdebugMode bool\n)\n\n\nfunc init() {\n\tinternalLog = NewMux()\n\tinternalLog.Add(NewSyslogSink())\n\tinternalLog.Add(NewColourisedTerminalSink())\n}\n\n\ntype Sink interface {\n\tInfo(message string)\n\tWarning(message string)\n\tError(message string)\n\tDebug(message string)\n}\n\n\n\nfunc Info(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Info(fileMessage, v...)\n}\n\nfunc Warning(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Warning(fileMessage, v...)\n}\n\nfunc Errorf(message string, v ...interface{}) {\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Error(fileMessage, v...)\n}\n\n\n\n\nfunc DebugMode(status bool) {\n\tinternalLog.DebugMode(status)\n\tdebugMode = status\n}\n\nfunc Debug(message string, v ...interface{}) ", "output": "{\n\tvar fileMessage string\n\tif debugMode {\n\t\t_, f, l, _ := runtime.Caller(1)\n\t\tfileMessage = fmt.Sprintf(\"(%s:%d) %s\", f, l, message)\n\t} else {\n\t\tfileMessage = message\n\t}\n\tinternalLog.Debug(fileMessage, v...)\n}"} {"input": "package pointer\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestGeneric(t *testing.T) ", "output": "{\n\tvar x time.Time\n\tif *To(x) != x {\n\t\tt.Errorf(\"*To(%v)\", x)\n\t}\n\tif ToOrNil(x) != nil {\n\t\tt.Errorf(\"ToOrNil(%v)\", x)\n\t}\n\tif Get((*time.Time)(nil)) != x {\n\t\tt.Errorf(\"Time(%v)\", nil)\n\t}\n\n\tx = time.Date(2014, 6, 25, 12, 24, 40, 0, time.UTC)\n\tif *To(x) != x {\n\t\tt.Errorf(\"*To(%v)\", x)\n\t}\n\tif *ToOrNil(x) != x {\n\t\tt.Errorf(\"*ToOrNil(%v)\", x)\n\t}\n\tif Get(&x) != x {\n\t\tt.Errorf(\"Get(%v)\", &x)\n\t}\n}"} {"input": "package web\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/hellofresh/janus/pkg/render\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\n\nfunc Home() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\trender.JSON(w, http.StatusOK, \"Welcome to Janus\")\n\t}\n}\n\n\n\n\nfunc RedirectHTTPS(port int) http.HandlerFunc ", "output": "{\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\thost, _, _ := net.SplitHostPort(req.Host)\n\n\t\ttarget := url.URL{\n\t\t\tScheme: \"https\",\n\t\t\tHost: fmt.Sprintf(\"%s:%v\", host, port),\n\t\t\tPath: req.URL.Path,\n\t\t}\n\t\tif len(req.URL.RawQuery) > 0 {\n\t\t\ttarget.RawQuery += \"?\" + req.URL.RawQuery\n\t\t}\n\t\tlog.Printf(\"redirect to: %s\", target.String())\n\t\thttp.Redirect(w, req, target.String(), http.StatusTemporaryRedirect)\n\t})\n}"} {"input": "package daemon\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetMapNameOKCode int = 200\n\n\ntype GetMapNameOK struct {\n\n\tPayload *models.BPFMap `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetMapNameOK() *GetMapNameOK {\n\n\treturn &GetMapNameOK{}\n}\n\n\n\n\n\nfunc (o *GetMapNameOK) SetPayload(payload *models.BPFMap) {\n\to.Payload = payload\n}\n\n\nfunc (o *GetMapNameOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\n\nconst GetMapNameNotFoundCode int = 404\n\n\ntype GetMapNameNotFound struct {\n}\n\n\nfunc NewGetMapNameNotFound() *GetMapNameNotFound {\n\n\treturn &GetMapNameNotFound{}\n}\n\n\nfunc (o *GetMapNameNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc (o *GetMapNameOK) WithPayload(payload *models.BPFMap) *GetMapNameOK ", "output": "{\n\to.Payload = payload\n\treturn o\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\ntype SendPhotoLinkBody struct {\n\n\tCaption string `json:\"caption,omitempty\"`\n\n\tChatID interface{} `json:\"chat_id\"`\n\n\tDisableNotification bool `json:\"disable_notification,omitempty\"`\n\n\tPhoto *string `json:\"photo\"`\n\n\tReplyMarkup interface{} `json:\"reply_markup,omitempty\"`\n\n\tReplyToMessageID int64 `json:\"reply_to_message_id,omitempty\"`\n}\n\n\nfunc (m *SendPhotoLinkBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateChatID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePhoto(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (m *SendPhotoLinkBody) validateChatID(formats strfmt.Registry) error {\n\n\treturn nil\n}\n\nfunc (m *SendPhotoLinkBody) validatePhoto(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"photo\", \"body\", m.Photo); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc (m *SendPhotoLinkBody) UnmarshalBinary(b []byte) error {\n\tvar res SendPhotoLinkBody\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *SendPhotoLinkBody) MarshalBinary() ([]byte, error) ", "output": "{\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}"} {"input": "package leader\n\nimport (\n\t\"time\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n)\n\ntype poller struct {\n\tleaderChan chan Leadership\n\tpollInterval time.Duration\n\ttick <-chan time.Time\n\tstop chan struct{}\n\tpollFunc CheckLeaderFunc\n}\n\n\nfunc NewPoller(pollInterval time.Duration, f CheckLeaderFunc) Detector {\n\treturn &poller{\n\t\tpollInterval: pollInterval,\n\t\ttick: time.Tick(pollInterval),\n\t\tpollFunc: f,\n\t}\n}\n\n\nfunc (l *poller) Start() (<-chan Leadership, error) {\n\tif l.leaderChan != nil {\n\t\treturn l.leaderChan, nil\n\t}\n\n\tl.leaderChan = make(chan Leadership)\n\tl.stop = make(chan struct{})\n\n\tgo l.poll()\n\treturn l.leaderChan, nil\n}\n\n\nfunc (l *poller) Stop() {\n\tif l.stop != nil {\n\t\tclose(l.stop)\n\t}\n}\n\n\n\nfunc (l *poller) poll() ", "output": "{\n\tfor {\n\t\tselect {\n\n\t\tcase <-l.tick:\n\n\t\t\tisLeader, err := l.pollFunc()\n\t\t\tevent := Leadership{}\n\t\t\tif err != nil {\n\t\t\t\tevent.Status = Unknown\n\t\t\t\tevent.Error = err\n\t\t\t} else {\n\t\t\t\tif isLeader {\n\t\t\t\t\tevent.Status = Leader\n\t\t\t\t} else {\n\t\t\t\t\tevent.Status = NotLeader\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tl.leaderChan <- event\n\n\t\tcase <-l.stop:\n\t\t\tlog.Infoln(\"Stopping leadership check\")\n\t\t\tclose(l.leaderChan)\n\t\t\tl.leaderChan = nil\n\t\t\tl.stop = nil\n\t\t\treturn\n\t\t}\n\t}\n}"} {"input": "package graphdriver\n\nimport (\n\t_ \"github.com/docker/docker/daemon/graphdriver/vfs\"\n\n)\n\ntype DiffDiskDriver interface {\n\tDriver\n\tCopyDiff(id, sourceId string) error\n}\n\nvar (\n\tpriority = []string{\n\t\t\"windows\",\n\t\t\"vfs\",\n\t}\n)\n\n\n\nfunc GetFSMagic(rootpath string) (FsMagic, error) ", "output": "{\n\treturn FsMagicUnsupported, nil\n}"} {"input": "package ehttp\n\nimport (\n\t\"encoding/json\"\n\t\"path\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc getCallstack(skip int) (string, string, int) {\n\tvar name string\n\tpc, file, line, ok := runtime.Caller(1 + skip)\n\tif !ok {\n\t\tname, file, line = \"\", \"\", -1\n\t} else {\n\t\tname = runtime.FuncForPC(pc).Name()\n\t\tname = path.Base(name)\n\t\tfile = path.Base(file)\n\t}\n\treturn name, file, line\n}\n\nfunc assertInt(t *testing.T, expect, got int) {\n\t_, file, line := getCallstack(1)\n\tif expect != got {\n\t\tt.Errorf(\"[%s:%d] Unexpected result.\\nExpect:\\t%d\\nGot:\\t%d\\n\", file, line, expect, got)\n\t}\n}\n\n\n\nfunc assertJSONError(t *testing.T, expect, got string) {\n\t_, file, line := getCallstack(1)\n\texpect, got = strings.TrimSpace(expect), strings.TrimSpace(got)\n\n\tjErr := JSONError{}\n\tif err := json.Unmarshal([]byte(got), &jErr); err != nil {\n\t\tt.Errorf(\"[%s:%d] Error parsing json error: %s\\n\", file, line, expect)\n\t}\n\tfor _, errStr := range jErr.Errors {\n\t\tif errStr == expect {\n\t\t\treturn\n\t\t}\n\t}\n\tt.Errorf(\"[%s:%d] Unexpected error.\\nExpect:\\t%s\\nGot:\\t%s\\n\", file, line, expect, got)\n}\n\nfunc assertString(t *testing.T, expect, got string) ", "output": "{\n\t_, file, line := getCallstack(1)\n\texpect, got = strings.TrimSpace(expect), strings.TrimSpace(got)\n\tif expect != got {\n\t\tt.Errorf(\"[%s:%d] Unexpected result.\\nExpect:\\t%s\\nGot:\\t%s\\n\", file, line, expect, got)\n\t}\n}"} {"input": "package v1\n\n\n\ntype ConfigMapProjectionApplyConfiguration struct {\n\tLocalObjectReferenceApplyConfiguration `json:\",inline\"`\n\tItems []KeyToPathApplyConfiguration `json:\"items,omitempty\"`\n\tOptional *bool `json:\"optional,omitempty\"`\n}\n\n\n\n\n\n\n\n\nfunc (b *ConfigMapProjectionApplyConfiguration) WithName(value string) *ConfigMapProjectionApplyConfiguration {\n\tb.Name = &value\n\treturn b\n}\n\n\n\n\nfunc (b *ConfigMapProjectionApplyConfiguration) WithItems(values ...*KeyToPathApplyConfiguration) *ConfigMapProjectionApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithItems\")\n\t\t}\n\t\tb.Items = append(b.Items, *values[i])\n\t}\n\treturn b\n}\n\n\n\n\nfunc (b *ConfigMapProjectionApplyConfiguration) WithOptional(value bool) *ConfigMapProjectionApplyConfiguration {\n\tb.Optional = &value\n\treturn b\n}\n\nfunc ConfigMapProjection() *ConfigMapProjectionApplyConfiguration ", "output": "{\n\treturn &ConfigMapProjectionApplyConfiguration{}\n}"} {"input": "package autositespeed\n\nimport (\n\t\"log\"\n\n\t\"gopkg.in/natefinch/lumberjack.v2\"\n)\n\ntype LogOptions struct {\n\tEnabled bool\n\tFilePath string\n\tMaxSize int\n\tMaxBackups int\n\tMaxAge int\n}\n\nfunc initLogging(options *LogOptions) {\n\tlog.SetOutput(&lumberjack.Logger{\n\t\tFilename: options.FilePath,\n\t\tMaxSize: options.MaxSize,\n\t\tMaxAge: options.MaxAge,\n\t\tMaxBackups: options.MaxBackups,\n\t})\n}\n\ntype logWriter struct {\n}\n\n\n\nfunc (lw *logWriter) Write(p []byte) (n int, err error) ", "output": "{\n\tlog.Println(string(p))\n\n\treturn len(p), nil\n}"} {"input": "package richtext\n\nimport (\n\t\"fmt\"\n)\n\ntype AnsiFormat8 struct{ ansiFormat }\n\nvar _ Format = &AnsiFormat8{}\n\nvar ansiFormat8 *AnsiFormat8\n\nfunc init() {\n\tansiFormat8 = &AnsiFormat8{}\n\tansiFormat8.init(ansiFormat8)\n}\n\nfunc Ansi8() *AnsiFormat8 { return ansiFormat8 }\n\n\n\nfunc (a *AnsiFormat8) MakePrintf(fg, bg Color, flags ...Flag) func(format string, a ...interface{}) (int, error) {\n\tenc := []string{}\n\tif fg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 30+rgbTo8(fg)))\n\t}\n\tif bg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 40+rgbTo8(bg)))\n\t}\n\n\treturn ansiPrinter(enc, flags)\n}\n\nfunc (a *AnsiFormat8) MakeSprintf(fg, bg Color, flags ...Flag) func(format string, a ...interface{}) string {\n\tenc := []string{}\n\tif fg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 30+rgbTo8(fg)))\n\t}\n\tif bg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 40+rgbTo8(bg)))\n\t}\n\n\treturn ansiSPrinter(enc, flags)\n}\n\nfunc rgbTo8(c Color) uint8 ", "output": "{\n\tr, g, b := rgb(c)\n\tr1 := r >> 7\n\tg1 := g >> 7\n\tb1 := b >> 7\n\treturn b1<<2 + g1<<1 + r1\n}"} {"input": "package gota\n\n\ntype RSI struct {\n\temaUp EMA\n\temaDown EMA\n\tlastV float64\n}\n\n\nfunc NewRSI(inTimePeriod int, warmType WarmupType) *RSI {\n\tema := NewEMA(inTimePeriod+1, warmType)\n\tema.alpha = float64(1) / float64(inTimePeriod)\n\treturn &RSI{\n\t\temaUp: *ema,\n\t\temaDown: *ema,\n\t}\n}\n\n\nfunc (rsi RSI) WarmCount() int {\n\treturn rsi.emaUp.WarmCount()\n}\n\n\n\n\n\nfunc (rsi RSI) Last() float64 {\n\treturn 100 - (100 / (1 + rsi.emaUp.Last()/rsi.emaDown.Last()))\n}\n\n\nfunc (rsi *RSI) Add(v float64) float64 {\n\tvar up float64\n\tvar down float64\n\tif v > rsi.lastV {\n\t\tup = v - rsi.lastV\n\t} else if v < rsi.lastV {\n\t\tdown = rsi.lastV - v\n\t}\n\trsi.emaUp.Add(up)\n\trsi.emaDown.Add(down)\n\trsi.lastV = v\n\treturn rsi.Last()\n}\n\nfunc (rsi RSI) Warmed() bool ", "output": "{\n\treturn rsi.emaUp.Warmed()\n}"} {"input": "package iso20022\n\n\ntype StatisticsByPredefinedTimePeriods2 struct {\n\n\tHighestPriceValue12Months *PriceValue5 `xml:\"HghstPricVal12Mnths,omitempty\"`\n\n\tLowestPriceValue12Months *PriceValue5 `xml:\"LwstPricVal12Mnths,omitempty\"`\n\n\tOneYearPriceChange *PriceValueChange1 `xml:\"OneYrPricChng,omitempty\"`\n\n\tThreeYearPriceChange *PriceValueChange1 `xml:\"ThreeYrPricChng,omitempty\"`\n\n\tFiveYearPriceChange *PriceValueChange1 `xml:\"FiveYrPricChng,omitempty\"`\n}\n\n\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddLowestPriceValue12Months() *PriceValue5 {\n\ts.LowestPriceValue12Months = new(PriceValue5)\n\treturn s.LowestPriceValue12Months\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddOneYearPriceChange() *PriceValueChange1 {\n\ts.OneYearPriceChange = new(PriceValueChange1)\n\treturn s.OneYearPriceChange\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddThreeYearPriceChange() *PriceValueChange1 {\n\ts.ThreeYearPriceChange = new(PriceValueChange1)\n\treturn s.ThreeYearPriceChange\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddFiveYearPriceChange() *PriceValueChange1 {\n\ts.FiveYearPriceChange = new(PriceValueChange1)\n\treturn s.FiveYearPriceChange\n}\n\nfunc (s *StatisticsByPredefinedTimePeriods2) AddHighestPriceValue12Months() *PriceValue5 ", "output": "{\n\ts.HighestPriceValue12Months = new(PriceValue5)\n\treturn s.HighestPriceValue12Months\n}"} {"input": "package client\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/thecodeteam/rexray/libstorage/api/types\"\n)\n\n\ntype client struct {\n\thttp.Client\n\thost string\n\tlogRequests bool\n\tlogResponses bool\n\tserverName string\n}\n\n\nfunc New(host string, transport *http.Transport) types.APIClient {\n\treturn &client{\n\t\tClient: http.Client{\n\t\t\tTransport: transport,\n\t\t},\n\t\thost: host,\n\t}\n}\n\nfunc (c *client) ServerName() string {\n\treturn c.serverName\n}\n\n\n\nfunc (c *client) LogResponses(enabled bool) {\n\tc.logResponses = enabled\n}\n\nfunc (c *client) LogRequests(enabled bool) ", "output": "{\n\tc.logRequests = enabled\n}"} {"input": "package phaul\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype images struct {\n\tcursor int\n\tdir string\n}\n\nfunc preparePhaulImages(wdir string) (*images, error) {\n\treturn &images{dir: wdir}, nil\n}\n\nfunc (i *images) getPath(idx int) string {\n\treturn fmt.Sprintf(i.dir+\"/%d\", idx)\n}\n\nfunc (i *images) openNextDir() (*os.File, error) {\n\tipath := i.getPath(i.cursor)\n\terr := os.Mkdir(ipath, 0700)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ti.cursor++\n\treturn os.Open(ipath)\n}\n\n\n\nfunc (i *images) lastImagesDir() string ", "output": "{\n\tvar ret string\n\tif i.cursor == 0 {\n\t\tret = \"\"\n\t} else {\n\t\tret, _ = filepath.Abs(i.getPath(i.cursor - 1))\n\t}\n\treturn ret\n}"} {"input": "package console\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"unsafe\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\nconst (\n\tcmdTcGet = unix.TCGETS\n\tcmdTcSet = unix.TCSETS\n)\n\nfunc ioctl(fd, flag, data uintptr) error {\n\tif _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, flag, data); err != 0 {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\n\n\n\nfunc ptsname(f *os.File) (string, error) {\n\tn, err := unix.IoctlGetInt(int(f.Fd()), unix.TIOCGPTN)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"/dev/pts/%d\", n), nil\n}\n\nfunc unlockpt(f *os.File) error ", "output": "{\n\tvar u int32\n\treturn ioctl(f.Fd(), unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&u)))\n}"} {"input": "package payload\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hyperledger/burrow/acm/acmstate\"\n\t\"github.com/hyperledger/burrow/crypto\"\n)\n\nfunc NewBondTx(address crypto.Address, amount uint64) *BondTx {\n\treturn &BondTx{\n\t\tInput: &TxInput{\n\t\t\tAddress: address,\n\t\t\tAmount: amount,\n\t\t},\n\t}\n}\n\n\n\nfunc (tx *BondTx) GetInputs() []*TxInput {\n\treturn []*TxInput{tx.Input}\n}\n\nfunc (tx *BondTx) String() string {\n\treturn fmt.Sprintf(\"BondTx{%v}\", tx.Input)\n}\n\nfunc (tx *BondTx) AddInput(st acmstate.AccountGetter, pubkey *crypto.PublicKey, amt uint64) error {\n\taddr := pubkey.GetAddress()\n\tacc, err := st.GetAccount(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif acc == nil {\n\t\treturn fmt.Errorf(\"invalid address %s from pubkey %s\", addr, pubkey)\n\t}\n\treturn tx.AddInputWithSequence(pubkey, amt, acc.Sequence+uint64(1))\n}\n\nfunc (tx *BondTx) AddInputWithSequence(pubkey *crypto.PublicKey, amt uint64, sequence uint64) error {\n\ttx.Input = &TxInput{\n\t\tAddress: pubkey.GetAddress(),\n\t\tAmount: amt,\n\t\tSequence: sequence,\n\t}\n\treturn nil\n}\n\nfunc (tx *BondTx) Any() *Any {\n\treturn &Any{\n\t\tBondTx: tx,\n\t}\n}\n\nfunc (tx *BondTx) Type() Type ", "output": "{\n\treturn TypeBond\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"github.com/jonasi/baller\"\n\t\"os\"\n)\n\nfunc cmd_boxscore_advanced_v2(cl *baller.Client) (interface{}, error) {\n\tvar (\n\t\tfs = flag.NewFlagSet(\"boxscore_advanced_v2\", flag.ExitOnError)\n\t\tverbose = fs.Bool(\"verbose\", false, \"\")\n\t\toptions baller.BoxscoreAdvancedV2Options\n\t)\n\n\tfs.StringVar(&options.GameID, \"GameID\", \"\", \"\")\n\tfs.IntVar(&options.StartPeriod, \"StartPeriod\", 0, \"\")\n\tfs.IntVar(&options.EndPeriod, \"EndPeriod\", 0, \"\")\n\tfs.IntVar(&options.StartRange, \"StartRange\", 0, \"\")\n\tfs.IntVar(&options.EndRange, \"EndRange\", 0, \"\")\n\tfs.IntVar(&options.RangeType, \"RangeType\", 0, \"\")\n\n\tfs.Parse(os.Args[2:])\n\n\tif *verbose {\n\t\tcl.Logger = os.Stderr\n\t}\n\n\treturn cl.BoxscoreAdvancedV2(&options)\n}\n\n\n\nfunc init() ", "output": "{\n\tmethods[\"boxscore_advanced_v2\"] = cmd_boxscore_advanced_v2\n}"} {"input": "package iso20022\n\n\ntype Header12 struct {\n\n\tDownloadTransfer *TrueFalseIndicator `xml:\"DwnldTrf\"`\n\n\tFormatVersion *Max6Text `xml:\"FrmtVrsn\"`\n\n\tExchangeIdentification *Max3NumericText `xml:\"XchgId\"`\n\n\tCreationDateTime *ISODateTime `xml:\"CreDtTm\"`\n\n\tInitiatingParty *GenericIdentification53 `xml:\"InitgPty\"`\n\n\tRecipientParty *GenericIdentification53 `xml:\"RcptPty,omitempty\"`\n}\n\n\n\nfunc (h *Header12) SetFormatVersion(value string) {\n\th.FormatVersion = (*Max6Text)(&value)\n}\n\nfunc (h *Header12) SetExchangeIdentification(value string) {\n\th.ExchangeIdentification = (*Max3NumericText)(&value)\n}\n\nfunc (h *Header12) SetCreationDateTime(value string) {\n\th.CreationDateTime = (*ISODateTime)(&value)\n}\n\nfunc (h *Header12) AddInitiatingParty() *GenericIdentification53 {\n\th.InitiatingParty = new(GenericIdentification53)\n\treturn h.InitiatingParty\n}\n\nfunc (h *Header12) AddRecipientParty() *GenericIdentification53 {\n\th.RecipientParty = new(GenericIdentification53)\n\treturn h.RecipientParty\n}\n\nfunc (h *Header12) SetDownloadTransfer(value string) ", "output": "{\n\th.DownloadTransfer = (*TrueFalseIndicator)(&value)\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype TerminateDbSystemRequest struct {\n\n\tDbSystemId *string `mandatory:\"true\" contributesTo:\"path\" name:\"dbSystemId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request TerminateDbSystemRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request TerminateDbSystemRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype TerminateDbSystemResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response TerminateDbSystemResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response TerminateDbSystemResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request TerminateDbSystemRequest) HTTPRequest(method, path string) (http.Request, error) ", "output": "{\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}"} {"input": "package main\n\nimport \"testing\"\n\nfunc TestPerimeter(t *testing.T) {\n\trectangle := Rectangle{10.0, 10.0}\n\tgot := Perimeter(rectangle)\n\twant := 40.0\n\n\tif got != want {\n\t\tt.Errorf(\"got %.2f want %.2f\", got, want)\n\t}\n}\n\n\n\nfunc TestArea(t *testing.T) ", "output": "{\n\trectangle := Rectangle{12.0, 6.0}\n\tgot := Area(rectangle)\n\twant := 72.0\n\n\tif got != want {\n\t\tt.Errorf(\"got %.2f want %.2f\", got, want)\n\t}\n}"} {"input": "package bench\n\nimport (\n\t\"fmt\"\n\t\"github.com/satori/go.uuid\"\n\t. \"github.com/topfreegames/offers/testing\"\n\t\"net/http\"\n\t\"testing\"\n)\n\nvar gameResult *http.Response\n\nfunc BenchmarkListGames(b *testing.B) {\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\troute := getRoute(\"/games\")\n\t\tres, err := get(route)\n\t\tvalidateResp(res, err)\n\t\tres.Body.Close()\n\n\t\tgameResult = res\n\t}\n}\n\nfunc BenchmarkInsertGame(b *testing.B) {\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\troute := getRoute(fmt.Sprintf(\"/games/%s\", uuid.NewV4().String()))\n\t\tres, err := putTo(route, map[string]interface{}{\n\t\t\t\"name\": fmt.Sprintf(\"game-%d\", i),\n\t\t})\n\t\tvalidateResp(res, err)\n\t\tres.Body.Close()\n\n\t\tgameResult = res\n\t}\n}\n\n\n\nfunc BenchmarkUpdateGame(b *testing.B) ", "output": "{\n\tdb, err := GetPerfDB()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tgames, err := getGames(&db)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tlength := len(games)\n\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tgame := games[i%length]\n\t\troute := getRoute(fmt.Sprintf(\"/games/%s\", game.ID))\n\t\tres, err := putTo(route, map[string]interface{}{\n\t\t\t\"name\": fmt.Sprintf(\"%s-%d\", game.Name, i),\n\t\t})\n\t\tvalidateResp(res, err)\n\t\tres.Body.Close()\n\n\t\tgameResult = res\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"syscall\"\n\t\"time\"\n\t\"unicode/utf16\"\n\t\"unsafe\"\n\n\t\"github.com/tinycedar/lily/common\"\n)\n\nfunc GetProcessNameMap() map[uint32]string {\n\tdefer metrics(\"GetProcessNameMap\")(time.Now())\n\tsnapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)\n\tif err != nil {\n\t\tcommon.Error(\"Fail to syscall CreateToolhelp32Snapshot: %v\", err)\n\t\treturn nil\n\t}\n\tdefer syscall.CloseHandle(snapshot)\n\tvar procEntry syscall.ProcessEntry32\n\tprocEntry.Size = uint32(unsafe.Sizeof(procEntry))\n\tif err = syscall.Process32First(snapshot, &procEntry); err != nil {\n\t\tcommon.Error(\"Fail to syscall Process32First: %v\", err)\n\t\treturn nil\n\t}\n\tprocessNameMap := make(map[uint32]string)\n\tfor {\n\t\tprocessNameMap[procEntry.ProcessID] = parseProcessName(procEntry.ExeFile)\n\t\tif err = syscall.Process32Next(snapshot, &procEntry); err != nil {\n\t\t\tif err == syscall.ERROR_NO_MORE_FILES {\n\t\t\t\treturn processNameMap\n\t\t\t}\n\t\t\tcommon.Error(\"Fail to syscall Process32Next: %v\", err)\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\n\n\nfunc metrics(funcName string) func(now time.Time) {\n\treturn func(now time.Time) {\n\t\tcommon.Info(\"Processing [%v] costs %v\", funcName, time.Since(now))\n\t}\n}\n\nfunc parseProcessName(exeFile [syscall.MAX_PATH]uint16) string ", "output": "{\n\tfor i, v := range exeFile {\n\t\tif v <= 0 {\n\t\t\treturn string(utf16.Decode(exeFile[:i]))\n\t\t}\n\t}\n\treturn \"\"\n}"} {"input": "package dml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/dml\"\n)\n\nfunc TestCT_ColorMappingOverrideChoiceConstructor(t *testing.T) {\n\tv := dml.NewCT_ColorMappingOverrideChoice()\n\tif v == nil {\n\t\tt.Errorf(\"dml.NewCT_ColorMappingOverrideChoice must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed dml.CT_ColorMappingOverrideChoice should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestCT_ColorMappingOverrideChoiceMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := dml.NewCT_ColorMappingOverrideChoice()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := dml.NewCT_ColorMappingOverrideChoice()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package core \n\n\nfunc IsUserInAdminGroup() int {\n\treturn 0\n}\n\n\nfunc IsRunAsAdmin() int {\n\treturn 0\n}\n\n\n\n\nfunc RelaunchAsAdmin() int ", "output": "{\n\treturn 0\n}"} {"input": "package transport\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\ntype Config struct {\n\tUserAgent string\n\n\tTLS TLSConfig\n\n\tUsername string\n\tPassword string\n\n\tBearerToken string\n\n\tBearerTokenFile string\n\n\tImpersonate ImpersonationConfig\n\n\tDisableCompression bool\n\n\tTransport http.RoundTripper\n\n\tWrapTransport WrapperFunc\n\n\tDial func(ctx context.Context, network, address string) (net.Conn, error)\n\n\tProxy func(*http.Request) (*url.URL, error)\n}\n\n\ntype ImpersonationConfig struct {\n\tUserName string\n\tGroups []string\n\tExtra map[string][]string\n}\n\n\nfunc (c *Config) HasCA() bool {\n\treturn len(c.TLS.CAData) > 0 || len(c.TLS.CAFile) > 0\n}\n\n\nfunc (c *Config) HasBasicAuth() bool {\n\treturn len(c.Username) != 0\n}\n\n\nfunc (c *Config) HasTokenAuth() bool {\n\treturn len(c.BearerToken) != 0 || len(c.BearerTokenFile) != 0\n}\n\n\nfunc (c *Config) HasCertAuth() bool {\n\treturn (len(c.TLS.CertData) != 0 || len(c.TLS.CertFile) != 0) && (len(c.TLS.KeyData) != 0 || len(c.TLS.KeyFile) != 0)\n}\n\n\nfunc (c *Config) HasCertCallback() bool {\n\treturn c.TLS.GetCert != nil\n}\n\n\n\n\n\n\n\n\ntype TLSConfig struct {\n\tCAFile string \n\tCertFile string \n\tKeyFile string \n\tReloadTLSFiles bool \n\n\tInsecure bool \n\tServerName string \n\n\tCAData []byte \n\tCertData []byte \n\tKeyData []byte \n\n\tNextProtos []string\n\n\tGetCert func() (*tls.Certificate, error) \n}\n\nfunc (c *Config) Wrap(fn WrapperFunc) ", "output": "{\n\tc.WrapTransport = Wrappers(c.WrapTransport, fn)\n}"} {"input": "package store\n\nimport (\n\t\"github.com/snapcore/snapd/testutil\"\n\n\t\"gopkg.in/retry.v1\"\n)\n\n\nfunc MockDefaultRetryStrategy(t *testutil.BaseTest, strategy retry.Strategy) {\n\toriginalDefaultRetryStrategy := defaultRetryStrategy\n\tdefaultRetryStrategy = strategy\n\tt.AddCleanup(func() {\n\t\tdefaultRetryStrategy = originalDefaultRetryStrategy\n\t})\n}\n\n\n\nfunc (cm *CacheManager) CacheDir() string ", "output": "{\n\treturn cm.cacheDir\n}"} {"input": "package cancel\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/coredns/coredns/plugin\"\n\t\"github.com/coredns/coredns/plugin/pkg/dnstest\"\n\t\"github.com/coredns/coredns/plugin/test\"\n\n\t\"github.com/miekg/dns\"\n)\n\ntype sleepPlugin struct{}\n\nfunc (s sleepPlugin) Name() string { return \"sleep\" }\n\n\n\nfunc TestCancel(t *testing.T) {\n\tca := Cancel{Next: sleepPlugin{}, timeout: 20 * time.Millisecond}\n\tctx := context.Background()\n\n\tw := dnstest.NewRecorder(&test.ResponseWriter{})\n\tm := new(dns.Msg)\n\tm.SetQuestion(\"aaa.example.com.\", dns.TypeTXT)\n\n\tca.ServeDNS(ctx, w, m)\n\tif w.Rcode != dns.RcodeBadTime {\n\t\tt.Error(\"Expected ServeDNS to be canceled by context\")\n\t}\n}\n\nfunc (s sleepPlugin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) ", "output": "{\n\ti := 0\n\tm := new(dns.Msg)\n\tm.SetReply(r)\n\tfor {\n\t\tif plugin.Done(ctx) {\n\t\t\tm.Rcode = dns.RcodeBadTime \n\t\t\tw.WriteMsg(m)\n\t\t\treturn 0, nil\n\t\t}\n\t\ttime.Sleep(20 * time.Millisecond)\n\t\ti++\n\t\tif i > 2 {\n\t\t\tm.Rcode = dns.RcodeServerFailure\n\t\t\tw.WriteMsg(m)\n\t\t\treturn 0, nil\n\t\t}\n\t}\n\treturn 0, nil\n}"} {"input": "package dynaml\n\n\n\nfunc func_eval(arguments []interface{}, binding Binding, locally bool) (interface{}, EvaluationInfo, bool) ", "output": "{\n\tinfo := DefaultInfo()\n\n\tif len(arguments) != 1 {\n\t\treturn info.Error(\"one argument required for 'eval'\")\n\t}\n\n\tstr, ok := arguments[0].(string)\n\tif !ok {\n\t\treturn info.Error(\"string argument required for 'eval'\")\n\t}\n\n\texpr, err := Parse(str, binding.Path(), binding.StubPath())\n\tif err != nil {\n\t\treturn info.Error(\"(%s)\\t %s\", str, err)\n\t}\n\treturn expr.Evaluate(binding, locally)\n}"} {"input": "package pid\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"reflect\"\n)\n\n\ntype Statm struct {\n\tSize uint \n\tResident uint \n\tShare uint \n\tText uint \n\tLib uint \n\tData uint \n\tDt uint \n}\n\n\n\n\nfunc NewStatm(pid int) (*Statm, error) {\n\tfn := filepath.Join(Dir(pid), \"statm\")\n\n\tf, err := os.Open(fn)\n\n\tif err != nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to read %s [%s]\", fn, err))\n\t}\n\n\tdefer f.Close()\n\n\treturn NewStatmFromReader(f)\n}\n\n\n\n\n\n\nfunc NewStatmFromReader(reader io.Reader) (*Statm, error) ", "output": "{\n\tstatm := Statm{}\n\n\tv := reflect.ValueOf(&statm).Elem()\n\n\tt := reflect.TypeOf(statm)\n\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tfield := v.Field(i).Addr()\n\t\tif _, err := fmt.Fscan(reader, field.Interface()); err != nil {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to parse field %s [%v]\", t.Field(i).Name, err))\n\t\t}\n\t}\n\n\treturn &statm, nil\n}"} {"input": "package exec\n\nimport \"fmt\"\n\nvar (\n\tExecTypeOs ExecType = 0\n\n\texecTypeToString = map[ExecType]string{\n\t\tExecTypeOs: \"os\",\n\t}\n\tlenExecTypeToString = len(execTypeToString)\n\tstringToExecType = map[string]ExecType{\n\t\t\"os\": ExecTypeOs,\n\t}\n)\n\ntype ExecType uint\n\nfunc AllExecTypes() []ExecType {\n\treturn []ExecType{\n\t\tExecTypeOs,\n\t}\n}\n\nfunc ExecTypeOf(s string) (ExecType, error) {\n\texecType, ok := stringToExecType[s]\n\tif !ok {\n\t\treturn 0, UnknownExecType(s)\n\t}\n\treturn execType, nil\n}\n\nfunc (e ExecType) String() string {\n\tif int(e) < lenExecTypeToString {\n\t\treturn execTypeToString[e]\n\t}\n\tpanic(UnknownExecType(e).Error())\n}\n\n\n\nfunc UnknownExecType(unknownExecType interface{}) error ", "output": "{\n\treturn fmt.Errorf(\"exec: unknown ExecType: %v\", unknownExecType)\n}"} {"input": "package goquery\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\ntype document struct {\n\turl url.URL\n\theaders http.Header\n\tbody []byte\n\twrapper\n}\n\n\nfunc (d document) GetHeaders() http.Header { return d.headers }\nfunc (d document) GetBody() []byte { return d.body }\n\nfunc (d document) GetURL() url.URL ", "output": "{ return d.url }"} {"input": "package golang\n\nimport (\n\t\"bldy.build/build/executor\"\n\t\"bldy.build/build/label\"\n)\n\ntype Go struct {\n\tname string `group:\"name\"`\n\tdependencies []label.Label `group:\"deps\"`\n}\n\n\n\nfunc (g *Go) Dependencies() []label.Label {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Outputs() []string {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Hash() []byte {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Build(*executor.Executor) error {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Name() string ", "output": "{\n\tpanic(\"not implemented\")\n}"} {"input": "package cluster\n\nimport (\n\t\"encoding/binary\"\n\t\"os\"\n)\n\ntype stateFile struct {\n\tHandle *os.File\n\tName string\n\tCount int32\n\tTimestamp int64\n}\n\n\n\nfunc (sf *stateFile) access() error {\n\tvar err error\n\tsf.Handle, err = os.OpenFile(sf.Name, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (sf *stateFile) write() error {\n\terr := sf.Handle.Truncate(0)\n\tsf.Handle.Seek(0, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = binary.Write(sf.Handle, binary.LittleEndian, sf.Count)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = binary.Write(sf.Handle, binary.LittleEndian, sf.Timestamp)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (sf *stateFile) read() error {\n\tsf.Handle.Seek(0, 0)\n\terr := binary.Read(sf.Handle, binary.LittleEndian, &sf.Count)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = binary.Read(sf.Handle, binary.LittleEndian, &sf.Timestamp)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc newStateFile(name string) *stateFile ", "output": "{\n\tsf := new(stateFile)\n\tsf.Name = name\n\treturn sf\n}"} {"input": "package cache\n\nimport (\n\t\"context\"\n\n\t\"github.com/go-kit/log\"\n\t\"github.com/go-kit/log/level\"\n\n\tutil_log \"github.com/grafana/loki/pkg/util/log\"\n)\n\n\ntype RedisCache struct {\n\tname string\n\tredis *RedisClient\n\tlogger log.Logger\n}\n\n\nfunc NewRedisCache(name string, redisClient *RedisClient, logger log.Logger) *RedisCache {\n\tutil_log.WarnExperimentalUse(\"Redis cache\", logger)\n\tcache := &RedisCache{\n\t\tname: name,\n\t\tredis: redisClient,\n\t\tlogger: logger,\n\t}\n\tif err := cache.redis.Ping(context.Background()); err != nil {\n\t\tlevel.Error(logger).Log(\"msg\", \"error connecting to redis\", \"name\", name, \"err\", err)\n\t}\n\treturn cache\n}\n\n\n\n\n\nfunc (c *RedisCache) Store(ctx context.Context, keys []string, bufs [][]byte) error {\n\terr := c.redis.MSet(ctx, keys, bufs)\n\tif err != nil {\n\t\tlevel.Error(c.logger).Log(\"msg\", \"failed to put to redis\", \"name\", c.name, \"err\", err)\n\t}\n\treturn err\n}\n\n\nfunc (c *RedisCache) Stop() {\n\t_ = c.redis.Close()\n}\n\nfunc (c *RedisCache) Fetch(ctx context.Context, keys []string) (found []string, bufs [][]byte, missed []string, err error) ", "output": "{\n\tdata, err := c.redis.MGet(ctx, keys)\n\tif err != nil {\n\t\tlevel.Error(c.logger).Log(\"msg\", \"failed to get from redis\", \"name\", c.name, \"err\", err)\n\t\tmissed = make([]string, len(keys))\n\t\tcopy(missed, keys)\n\t\treturn\n\t}\n\tfor i, key := range keys {\n\t\tif data[i] != nil {\n\t\t\tfound = append(found, key)\n\t\t\tbufs = append(bufs, data[i])\n\t\t} else {\n\t\t\tmissed = append(missed, key)\n\t\t}\n\t}\n\treturn\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/rbac/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"github.com/hyperhq/client-go/tools/cache\"\n)\n\n\ntype ClusterRoleBindingLister interface {\n\tList(selector labels.Selector) (ret []*v1.ClusterRoleBinding, err error)\n\tGet(name string) (*v1.ClusterRoleBinding, error)\n\tClusterRoleBindingListerExpansion\n}\n\n\ntype clusterRoleBindingLister struct {\n\tindexer cache.Indexer\n}\n\n\n\n\n\nfunc (s *clusterRoleBindingLister) List(selector labels.Selector) (ret []*v1.ClusterRoleBinding, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ClusterRoleBinding))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *clusterRoleBindingLister) Get(name string) (*v1.ClusterRoleBinding, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"clusterrolebinding\"), name)\n\t}\n\treturn obj.(*v1.ClusterRoleBinding), nil\n}\n\nfunc NewClusterRoleBindingLister(indexer cache.Indexer) ClusterRoleBindingLister ", "output": "{\n\treturn &clusterRoleBindingLister{indexer: indexer}\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\n\tresCh := make(chan float64)\n\terrCh := make(chan error)\n\n\tgo divide(2, 1, resCh, errCh)\n\n\tr := <-resCh\n\terr := <-errCh\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfmt.Println(r)\n}\n\n\n\nfunc divide(a, b float64, resCh chan float64, errCh chan error) ", "output": "{\n\tif b == 0 {\n\t\tresCh <- 0\n\t\terrCh <- fmt.Errorf(\"divide by zero error\")\n\t\treturn\n\t}\n\tresCh <- a / b\n\terrCh <- nil\n\treturn\n}"} {"input": "package addrs\n\nimport \"fmt\"\n\n\n\n\n\n\n\n\n\n\n\ntype ResourceInstancePhase struct {\n\treferenceable\n\tResourceInstance ResourceInstance\n\tPhase ResourceInstancePhaseType\n}\n\nvar _ Referenceable = ResourceInstancePhase{}\n\n\n\n\nfunc (r ResourceInstance) Phase(rpt ResourceInstancePhaseType) ResourceInstancePhase {\n\treturn ResourceInstancePhase{\n\t\tResourceInstance: r,\n\t\tPhase: rpt,\n\t}\n}\n\n\n\nfunc (rp ResourceInstancePhase) ContainingResource() ResourcePhase {\n\treturn rp.ResourceInstance.Resource.Phase(rp.Phase)\n}\n\nfunc (rp ResourceInstancePhase) String() string {\n\treturn fmt.Sprintf(\"%s#%s\", rp.ResourceInstance, rp.Phase)\n}\n\n\ntype ResourceInstancePhaseType string\n\nconst (\n\tResourceInstancePhaseDestroy ResourceInstancePhaseType = \"destroy\"\n\n\tResourceInstancePhaseDestroyCBD ResourceInstancePhaseType = \"destroy-cbd\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype ResourcePhase struct {\n\treferenceable\n\tResource Resource\n\tPhase ResourceInstancePhaseType\n}\n\nvar _ Referenceable = ResourcePhase{}\n\n\n\n\nfunc (r Resource) Phase(rpt ResourceInstancePhaseType) ResourcePhase {\n\treturn ResourcePhase{\n\t\tResource: r,\n\t\tPhase: rpt,\n\t}\n}\n\nfunc (rp ResourcePhase) String() string {\n\treturn fmt.Sprintf(\"%s#%s\", rp.Resource, rp.Phase)\n}\n\nfunc (rpt ResourceInstancePhaseType) String() string ", "output": "{\n\treturn string(rpt)\n}"} {"input": "package csv\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestParseFileDoesNotExists(t *testing.T) {\n\t_, err := ParseFile(\"nosuchfilehere\")\n\tif err == nil {\n\t\tt.Error(\"Should have thrown an error due to missing file\")\n\t}\n}\n\nfunc TestParseFile(t *testing.T) ", "output": "{\n\tresults, err := ParseFile(\"test_scan_900z53.csv\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif len(results) != 46 {\n\t\tt.Errorf(\"Should have parsed 46 records, was %v\", len(results))\n\t}\n}"} {"input": "package jail\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n)\n\ntype logReader struct {\n\tfilename string\n\tfile *os.File\n\treader *bufio.Reader\n\tlines chan string\n\terrors chan error\n}\n\n\n\nfunc (l *logReader) readLine() {\n\tline, err := l.reader.ReadString('\\n')\n\tif err != nil {\n\t\tgo func() {\n\t\t\tl.errors <- err\n\t\t}()\n\t}\n\n\tif line != \"\" {\n\t\tgo func() {\n\t\t\tl.lines <- line\n\t\t}()\n\t}\n}\nfunc (l *logReader) reset() {\n\tf, err := os.Open(l.filename)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tr := bufio.NewReader(f)\n\tl.reader.Reset(r)\n}\n\nfunc newLogReader(filename string) *logReader ", "output": "{\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil\n\t}\n\n\tr := bufio.NewReader(f)\n\n\treturn &logReader{\n\t\tfilename: filename,\n\t\tfile: f,\n\t\treader: r,\n\t\tlines: make(chan string),\n\t\terrors: make(chan error),\n\t}\n}"} {"input": "package watch\n\n\n\ntype FilterFunc func(in Event) (out Event, keep bool)\n\n\n\n\n\n\n\n\n\n\nfunc Filter(w Interface, f FilterFunc) Interface {\n\tfw := &filteredWatch{\n\t\tincoming: w,\n\t\tresult: make(chan Event),\n\t\tf: f,\n\t}\n\tgo fw.loop()\n\treturn fw\n}\n\ntype filteredWatch struct {\n\tincoming Interface\n\tresult chan Event\n\tf FilterFunc\n}\n\n\nfunc (fw *filteredWatch) ResultChan() <-chan Event {\n\treturn fw.result\n}\n\n\n\n\n\nfunc (fw *filteredWatch) loop() {\n\tdefer close(fw.result)\n\tfor {\n\t\tevent, ok := <-fw.incoming.ResultChan()\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tfiltered, keep := fw.f(event)\n\t\tif keep {\n\t\t\tfw.result <- filtered\n\t\t}\n\t}\n}\n\nfunc (fw *filteredWatch) Stop() ", "output": "{\n\tfw.incoming.Stop()\n}"} {"input": "package commons\n\nimport (\n\t\"fmt\"\n\t\"go/build\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n\nfunc FileExists(filename string) bool {\n\tif _, err := os.Stat(filename); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc GetGoFiles(filenames ...string) ([]string, error) {\n\tfiles := []string{}\n\n\tfor _, filename := range filenames {\n\t\tif strings.HasSuffix(filename, \".go\") {\n\t\t\tfiles = append(files, filename)\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"'%s' is not a Go file\", filename)\n\t\t}\n\t}\n\n\treturn files, nil\n}\n\n\nfunc GetGoFilesFromCurrentDir() ([]string, error) {\n\treturn GetGoFilesFromDir(\".\")\n}\n\n\nfunc GetGoFilesFromDir(dirname string) ([]string, error) {\n\tpkg, err := build.ImportDir(dirname, 0)\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\treturn getGoFilesFromPackage(pkg, err)\n}\n\n\nfunc GetGoFilesFromDirectoryRecursive(dirname string) ([]string, error) {\n\tfiles := []string{}\n\n\tif !strings.HasSuffix(dirname, \"...\") {\n\t\tdirname += \"...\"\n\t}\n\n\tpackages := GetAllPackagesUnderDirectory(dirname)\n\tif len(packages) == 0 {\n\t\treturn files, fmt.Errorf(\"no go files found in dir '%s'\", dirname)\n\t}\n\n\tfor _, dirname := range packages {\n\t\ttheseFiles, err := GetGoFilesFromDir(dirname)\n\t\tif err != nil {\n\t\t\treturn []string{}, err\n\t\t}\n\t\tfiles = append(files, theseFiles...)\n\t}\n\n\treturn files, nil\n}\n\n\n\n\nfunc getGoFilesFromPackage(pkg *build.Package, err error) ([]string, error) ", "output": "{\n\tfiles := []string{}\n\n\tif err != nil {\n\t\tif _, nogo := err.(*build.NoGoError); nogo {\n\t\t\treturn files, nil\n\t\t}\n\t\treturn files, err\n\t}\n\n\tfiles = append(files, pkg.GoFiles...)\n\tfiles = append(files, pkg.TestGoFiles...)\n\tfiles = append(files, pkg.XTestGoFiles...)\n\tif pkg.Dir != \".\" {\n\t\tfor i, f := range files {\n\t\t\tfiles[i] = filepath.Join(pkg.Dir, f)\n\t\t}\n\t}\n\n\treturn files, nil\n}"} {"input": "package changelog\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n)\n\n\n\ntype SectionAliasMap map[string][]string\n\n\n\n\n\nfunc (s SectionAliasMap) SectionFor(alias string) string {\n\tfor title, aliases := range s {\n\t\tfor i := range aliases {\n\t\t\tif aliases[i] == alias {\n\t\t\t\treturn strings.Title(title)\n\t\t\t}\n\t\t}\n\t}\n\treturn \"Unknown\"\n}\n\n\nfunc MergeSectionAliasMaps(first SectionAliasMap, additional ...SectionAliasMap) SectionAliasMap {\n\tfor _, successive := range additional {\n\t\tfor title, aliases := range successive {\n\t\t\ttitle = strings.Title(title)\n\t\t\tif _, ok := first[title]; !ok {\n\t\t\t\tfirst[title] = aliases\n\t\t\t}\n\t\t\tfirst[title] = mergeStringSlices(first[title], aliases)\n\t\t}\n\t}\n\treturn first\n}\n\nfunc mergeStringSlices(first []string, successive ...[]string) []string {\n\tvalues := map[string]bool{}\n\tfor _, word := range first {\n\t\tvalues[word] = true\n\t}\n\tfor _, next := range successive {\n\t\tfor _, word := range next {\n\t\t\tvalues[word] = true\n\t\t}\n\t}\n\n\tkeys := make([]string, 0, len(values))\n\tfor k := range values {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\treturn keys\n}\n\n\nfunc (s SectionAliasMap) Grep() string {\n\tprefixes := []string{\"BREAKING\"}\n\tfor _, items := range s {\n\t\tfor _, item := range items {\n\t\t\tif item == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tprefixes = append(prefixes, fmt.Sprintf(\"^%s\", item))\n\t\t}\n\t}\n\tsort.Strings(prefixes)\n\treturn strings.Join(prefixes, \"|\")\n}\n\nfunc NewSectionAliasMap() SectionAliasMap ", "output": "{\n\tsectionAliasMap := make(SectionAliasMap)\n\tsectionAliasMap[\"Features\"] = []string{\"ft\", \"feat\"}\n\tsectionAliasMap[\"Bug Fixes\"] = []string{\"fx\", \"fix\"}\n\tsectionAliasMap[\"Performance\"] = []string{\"perf\"}\n\tsectionAliasMap[\"Breaking Changes\"] = []string{\"breaks\"}\n\tsectionAliasMap[\"Unknown\"] = []string{\"unk\"}\n\treturn sectionAliasMap\n}"} {"input": "package manifestparser\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype Locator struct {\n\tFilesToCheckFor []string\n}\n\n\n\nfunc (loc Locator) Path(filepathOrDirectory string) (string, bool, error) {\n\tinfo, err := os.Stat(filepathOrDirectory)\n\tif os.IsNotExist(err) {\n\t\treturn \"\", false, nil\n\t} else if err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tresolvedFilepathOrDirectory, err := filepath.EvalSymlinks(filepathOrDirectory)\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tif info.IsDir() {\n\t\treturn loc.handleDir(resolvedFilepathOrDirectory)\n\t}\n\n\treturn loc.handleFilepath(resolvedFilepathOrDirectory)\n}\n\nfunc (loc Locator) handleDir(dir string) (string, bool, error) {\n\tfor _, filename := range loc.FilesToCheckFor {\n\t\tfullPath := filepath.Join(dir, filename)\n\t\tif _, err := os.Stat(fullPath); err == nil {\n\t\t\treturn fullPath, true, nil\n\t\t} else if !os.IsNotExist(err) {\n\t\t\treturn \"\", false, err\n\t\t}\n\t}\n\n\treturn \"\", false, nil\n}\n\nfunc (Locator) handleFilepath(filepath string) (string, bool, error) {\n\treturn filepath, true, nil\n}\n\nfunc NewLocator() *Locator ", "output": "{\n\treturn &Locator{\n\t\tFilesToCheckFor: []string{\n\t\t\t\"manifest.yml\",\n\t\t\t\"manifest.yaml\",\n\t\t},\n\t}\n}"} {"input": "package action\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n)\n\ntype catalogNode struct {\n\t*config\n}\n\nfunc CatalogNodeAction() Action {\n\treturn &catalogNode{\n\t\tconfig: &gConfig,\n\t}\n}\n\nfunc (c *catalogNode) CommandFlags() *flag.FlagSet {\n\treturn c.newFlagSet(FLAG_DATACENTER, FLAG_CONSISTENCY, FLAG_OUTPUT, FLAG_BLOCKING)\n}\n\n\n\nfunc (c *catalogNode) Run(args []string) error ", "output": "{\n\tswitch {\n\tcase len(args) == 0:\n\t\treturn fmt.Errorf(\"Node name must be specified\")\n\tcase len(args) > 1:\n\t\treturn fmt.Errorf(\"Only one node allowed\")\n\t}\n\n\tclient, err := c.newCatalog()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tqueryOpts := c.queryOptions()\n\tconfig, _, err := client.Node(args[0], queryOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.Output(config)\n}"} {"input": "package resolvers\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/emwalker/digraph/cmd/frontend/loaders\"\n\t\"github.com/emwalker/digraph/cmd/frontend/models\"\n\t\"github.com/volatiletech/sqlboiler/queries/qm\"\n)\n\ntype organizationResolver struct {\n\t*Resolver\n}\n\nfunc getOrganizationLoader(ctx context.Context) *loaders.OrganizationLoader {\n\treturn ctx.Value(loaders.OrganizationLoaderKey).(*loaders.OrganizationLoader)\n}\n\nfunc fetchOrganization(ctx context.Context, organizationID string) (*models.Organization, error) {\n\tloader := getOrganizationLoader(ctx)\n\torg, err := loader.Load(organizationID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn org, nil\n}\n\n\nfunc (r *organizationResolver) CreatedAt(_ context.Context, org *models.Organization) (string, error) {\n\treturn org.CreatedAt.Format(time.RFC3339), nil\n}\n\n\nfunc (r *organizationResolver) DefaultRepository(ctx context.Context, org *models.Organization) (*models.Repository, error) {\n\trepo, err := org.Repositories(qm.Where(\"system\")).One(ctx, r.DB)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn repo, nil\n}\n\n\n\n\n\nfunc (r *organizationResolver) UpdatedAt(\n\t_ context.Context, org *models.Organization,\n) (string, error) {\n\treturn org.UpdatedAt.Format(time.RFC3339), nil\n}\n\nfunc (r *organizationResolver) ResourcePath(\n\t_ context.Context, org *models.Organization,\n) (string, error) ", "output": "{\n\treturn \"/organizations/\" + org.ID, nil\n}"} {"input": "package backingstore\n\nimport (\n\t\"github.com/gostor/gotgt/pkg/api\"\n\t\"github.com/gostor/gotgt/pkg/scsi\"\n)\n\nfunc init() {\n\tscsi.RegisterBackingStore(\"null\", newNull)\n}\n\ntype NullBackingStore struct {\n\tscsi.BaseBackingStore\n}\n\nfunc newNull() (api.BackingStore, error) {\n\treturn &NullBackingStore{\n\t\tBaseBackingStore: scsi.BaseBackingStore{\n\t\t\tName: \"null\",\n\t\t\tDataSize: 0,\n\t\t\tOflagsSupported: 0,\n\t\t},\n\t}, nil\n}\n\nfunc (bs *NullBackingStore) Open(dev *api.SCSILu, path string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Close(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Init(dev *api.SCSILu, Opts string) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Exit(dev *api.SCSILu) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Size(dev *api.SCSILu) uint64 {\n\treturn 0\n}\n\nfunc (bs *NullBackingStore) Read(offset, tl int64) ([]byte, error) {\n\treturn nil, nil\n}\n\nfunc (bs *NullBackingStore) Write(wbuf []byte, offset int64) error {\n\treturn nil\n}\n\n\n\nfunc (bs *NullBackingStore) DataAdvise(offset, length int64, advise uint32) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) Unmap([]api.UnmapBlockDescriptor) error {\n\treturn nil\n}\n\nfunc (bs *NullBackingStore) DataSync(offset, tl int64) error ", "output": "{\n\treturn nil\n}"} {"input": "package unix\n\nimport \"syscall\"\n\nfunc setTimespec(sec, nsec int64) Timespec {\n\treturn Timespec{Sec: int32(sec), Nsec: int32(nsec)}\n}\n\nfunc setTimeval(sec, usec int64) Timeval {\n\treturn Timeval{Sec: int32(sec), Usec: int32(usec)}\n}\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint32(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint32(length)\n}\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\nfunc (msghdr *Msghdr) SetIovlen(length int) {\n\tmsghdr.Iovlen = int32(length)\n}\n\n\n\nfunc Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)\n\nfunc (cmsg *Cmsghdr) SetLen(length int) ", "output": "{\n\tcmsg.Len = uint32(length)\n}"} {"input": "package endpoints\n\nimport (\n\t\"github.com/lxc/lxd/lxd/util\"\n\t\"github.com/lxc/lxd/shared\"\n)\n\n\nfunc Unstarted() *Endpoints {\n\treturn &Endpoints{\n\t\tsystemdListenFDsStart: util.SystemdListenFDsStart,\n\t}\n}\n\n\n\n\nfunc (e *Endpoints) DevLxdSocketPath() string {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tlistener := e.listeners[devlxd]\n\treturn listener.Addr().String()\n}\n\nfunc (e *Endpoints) LocalSocketPath() string {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tlistener := e.listeners[local]\n\treturn listener.Addr().String()\n}\n\n\n\n\nfunc (e *Endpoints) NetworkAddressAndCert() (string, *shared.CertInfo) {\n\treturn e.NetworkAddress(), e.cert\n}\n\n\n\n\nfunc (e *Endpoints) SystemdListenFDsStart(start int) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\te.systemdListenFDsStart = start\n}\n\nfunc (e *Endpoints) Up(config *Config) error ", "output": "{\n\treturn e.up(config)\n}"} {"input": "package mocks\n\nimport (\n\tcli \"github.com/stackanetes/kubernetes-entrypoint/client\"\n)\n\ntype MockEntrypoint struct {\n\tclient cli.ClientInterface\n\tnamespace string\n}\n\nfunc (m MockEntrypoint) Resolve() {\n}\n\nfunc (m MockEntrypoint) Client() (client cli.ClientInterface) {\n\treturn m.client\n}\n\nfunc (m MockEntrypoint) GetNamespace() (namespace string) {\n\treturn m.namespace\n}\n\n\n\nfunc NewEntrypoint() MockEntrypoint {\n\treturn NewEntrypointInNamespace(\"test\")\n}\n\nfunc NewEntrypointInNamespace(namespace string) MockEntrypoint ", "output": "{\n\treturn MockEntrypoint{\n\t\tclient: NewClient(),\n\t\tnamespace: namespace,\n\t}\n}"} {"input": "package net\n\n\nimport \"C\"\n\n\n\nfunc cgoAddrInfoFlags() C.int ", "output": "{\n\treturn (C.AI_CANONNAME | C.AI_V4MAPPED | C.AI_ALL) & C.AI_MASK\n}"} {"input": "package silverback_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestSilverback(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Silverback Suite\")\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar xhrOutput *Json\nvar lfgOutput *Json\n\n\n\ntype Json struct {\n\tdata map[string]interface{}\n\tupdatedAt string\n\tcache []byte\n\tcond *sync.WaitGroup\n\tlock sync.RWMutex\n}\n\nfunc (j *Json) send(w http.ResponseWriter) error {\n\tj.lock.RLock()\n\t_, err := w.Write(j.cache)\n\tj.lock.RUnlock()\n\treturn err\n}\n\nfunc (j *Json) set(key string, value interface{}) error {\n\tj.lock.Lock()\n\tj.updatedAt = fmt.Sprintf(\"%d\", time.Now().Unix())\n\tj.data[\"updated_at\"] = j.updatedAt\n\tj.data[key] = value\n\tcache, err := json.Marshal(j.data)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\tj.lock.Unlock()\n\t\treturn err\n\t}\n\tj.cache = cache\n\tnewCond := &sync.WaitGroup{}\n\tnewCond.Add(1)\n\tj.cond.Done()\n\tj.cond = newCond\n\tj.lock.Unlock()\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\txhrOutput = &Json{\n\t\tdata: map[string]interface{}{\n\t\t\t\"channels\": []string{},\n\t\t},\n\t\tcond: &sync.WaitGroup{},\n\t}\n\txhrOutput.cond.Add(1)\n\txhrOutput.set(\"updated_at\", time.Now().Unix())\n\n\tlfgOutput = &Json{\n\t\tdata: map[string]interface{}{\n\t\t\t\"lfg\": []string{},\n\t\t},\n\t\tcond: &sync.WaitGroup{},\n\t}\n\tlfgOutput.cond.Add(1)\n\tlfgOutput.set(\"updated_at\", time.Now().Unix())\n}"} {"input": "package dao\n\nimport (\n\t\"context\"\n\n\t\"go-common/library/cache/redis\"\n\t\"go-common/library/log\"\n)\n\nconst (\n\t_taskJobKey = \"task_job\"\n)\n\n\n\n\n\nfunc (d *Dao) GetTaskJob(c context.Context) (value string, err error) {\n\tvar (\n\t\tconn = d.dmRds.Get(c)\n\t)\n\tdefer conn.Close()\n\tif value, err = redis.String(conn.Do(\"GET\", _taskJobKey)); err != nil {\n\t\tlog.Error(\"d.GetMaskJob,error(%v)\", err)\n\t\treturn\n\t}\n\treturn\n}\n\n\nfunc (d *Dao) GetSetTaskJob(c context.Context, value string) (old string, err error) {\n\tvar (\n\t\tconn = d.dmRds.Get(c)\n\t)\n\tdefer conn.Close()\n\tif old, err = redis.String(conn.Do(\"GETSET\", _taskJobKey, value)); err != nil {\n\t\tlog.Error(\"d.GetSetTaskJob(value:%s),error(%v)\", value, err)\n\t\treturn\n\t}\n\treturn\n}\n\n\nfunc (d *Dao) DelTaskJob(c context.Context) (err error) {\n\tvar (\n\t\tconn = d.dmRds.Get(c)\n\t)\n\tdefer conn.Close()\n\tif _, err = conn.Do(\"DEL\", _taskJobKey); err != nil {\n\t\tlog.Error(\"d.DelTaskJob,error(%v)\", err)\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (d *Dao) SetnxTaskJob(c context.Context, value string) (ok bool, err error) ", "output": "{\n\tvar (\n\t\tconn = d.dmRds.Get(c)\n\t)\n\tdefer conn.Close()\n\tif ok, err = redis.Bool(conn.Do(\"SETNX\", _taskJobKey, value)); err != nil {\n\t\tlog.Error(\"d.SetnxMask(value:%s),error(%v)\", value, err)\n\t\treturn\n\t}\n\treturn\n}"} {"input": "package http\n\nimport (\n\t\"net/http\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n)\n\nconst (\n\trootURL = \"http://localhost:2049/\"\n\tpostURL = \"http://localhost:2049/post\"\n\tinvalidPathURL = \"http://localhost:2049/invalid-path\"\n\tinvalidHostURL = \"http://hostlocal:2049/\"\n)\n\ntype testHandler struct{}\n\n\n\nfunc TestMain(m *testing.M) {\n\tgo http.ListenAndServe(\":2049\", testHandler{})\n\n\ttime.Sleep(time.Millisecond)\n\n\tos.Exit(m.Run())\n}\n\nfunc (testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tswitch r.URL.Path {\n\tcase \"/\":\n\t\tw.Write(nil)\n\tcase \"/post\":\n\t\tif r.Method != \"POST\" {\n\t\t\tw.WriteHeader(404)\n\t\t}\n\tdefault:\n\t\tw.WriteHeader(404)\n\t}\n}"} {"input": "package j_user\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"koding/remoteapi/models\"\n)\n\n\ntype JUserConvertReader struct {\n\tformats strfmt.Registry\n}\n\n\n\n\n\nfunc NewJUserConvertOK() *JUserConvertOK {\n\treturn &JUserConvertOK{}\n}\n\n\ntype JUserConvertOK struct {\n\tPayload *models.DefaultResponse\n}\n\nfunc (o *JUserConvertOK) Error() string {\n\treturn fmt.Sprintf(\"[POST /remote.api/JUser.convert][%d] jUserConvertOK %+v\", 200, o.Payload)\n}\n\nfunc (o *JUserConvertOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\to.Payload = new(models.DefaultResponse)\n\n\tif err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc NewJUserConvertUnauthorized() *JUserConvertUnauthorized {\n\treturn &JUserConvertUnauthorized{}\n}\n\n\ntype JUserConvertUnauthorized struct {\n\tPayload *models.UnauthorizedRequest\n}\n\nfunc (o *JUserConvertUnauthorized) Error() string {\n\treturn fmt.Sprintf(\"[POST /remote.api/JUser.convert][%d] jUserConvertUnauthorized %+v\", 401, o.Payload)\n}\n\nfunc (o *JUserConvertUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\to.Payload = new(models.UnauthorizedRequest)\n\n\tif err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (o *JUserConvertReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) ", "output": "{\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewJUserConvertOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 401:\n\t\tresult := NewJUserConvertUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com/mholt/archiver/v3\"\n\t\"github.com/nuclio/errors\"\n\t\"github.com/nuclio/logger\"\n)\n\ntype Decompressor struct {\n\tlogger logger.Logger\n}\n\nfunc NewDecompressor(parentLogger logger.Logger) (*Decompressor, error) {\n\tnewDecompressor := &Decompressor{\n\t\tlogger: parentLogger,\n\t}\n\n\treturn newDecompressor, nil\n}\n\n\n\nfunc IsCompressed(source string) bool {\n\n\tif IsJar(source) {\n\t\treturn false\n\t}\n\n\tunarchiver, err := archiver.ByExtension(source)\n\tif err != nil {\n\t\treturn false\n\t}\n\tu, ok := unarchiver.(archiver.Unarchiver)\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn u != nil\n}\n\nfunc IsJar(source string) bool {\n\treturn strings.ToLower(path.Ext(source)) == \".jar\"\n}\n\nfunc (d *Decompressor) Decompress(source string, target string) error ", "output": "{\n\tif err := archiver.Unarchive(source, target); err != nil {\n\t\treturn errors.Wrapf(err, \"Failed to decompress file %s\", source)\n\t}\n\n\treturn nil\n}"} {"input": "package character\n\ntype Histogram struct {\n\tcounts [256]uint16\n}\n\n\n\nfunc (h *Histogram) Add(char Char) {\n\th.counts[char]++\n}\n\nfunc (h *Histogram) Count(char Char) int {\n\treturn int(h.counts[char])\n}\n\nfunc StringHistogram(text string) *Histogram ", "output": "{\n\thistogram := &Histogram{}\n\tfor i := 0; i < len(text); i++ {\n\t\thistogram.Add(Char(text[i]))\n\t}\n\treturn histogram\n}"} {"input": "package vagrant\n\nimport (\n\t\"github.com/mitchellh/packer/packer\"\n\t\"testing\"\n)\n\nfunc testConfig() map[string]interface{} {\n\treturn map[string]interface{}{}\n}\n\nfunc TestPostProcessor_ImplementsPostProcessor(t *testing.T) {\n\tvar raw interface{}\n\traw = &PostProcessor{}\n\tif _, ok := raw.(packer.PostProcessor); !ok {\n\t\tt.Fatalf(\"AWS PostProcessor should be a PostProcessor\")\n\t}\n}\n\nfunc TestBuilderPrepare_OutputPath(t *testing.T) {\n\tvar p PostProcessor\n\n\tc := testConfig()\n\tdelete(c, \"output\")\n\terr := p.Configure(c)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tc[\"output\"] = \"bad {{{{.Template}}}}\"\n\terr = p.Configure(c)\n\tif err == nil {\n\t\tt.Fatal(\"should have error\")\n\t}\n}\n\n\n\nfunc TestBuilderPrepare_PPConfig(t *testing.T) ", "output": "{\n\tvar p PostProcessor\n\n\tc := testConfig()\n\tc[\"aws\"] = map[string]interface{}{}\n\terr := p.Configure(c)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n}"} {"input": "package tristate\n\ntype StateValue int\n\nconst (\n\tTRISTATE_SUCCESS StateValue = iota\n\tTRISTATE_FAILRUE\n\tTRISTATE_UNKNOWN\n)\n\ntype TriState struct {\n\tState StateValue\n\tErr error\n}\n\nfunc NewSuccess() *TriState {\n\treturn nil\n}\n\nfunc NewUnknown(err error) *TriState {\n\tif err == nil {\n\t\tpanic(\"error not set\")\n\t}\n\treturn &TriState{TRISTATE_UNKNOWN, err}\n}\n\nfunc NewFailure(err error) *TriState {\n\tif err == nil {\n\t\tpanic(\"error not set\")\n\t}\n\treturn &TriState{TRISTATE_FAILRUE, err}\n}\n\nfunc (state *TriState) Error() string {\n\treturn state.Err.Error()\n}\n\nfunc (state *TriState) IsSuccess() bool {\n\treturn state == nil || state.State == TRISTATE_SUCCESS\n}\n\nfunc (state *TriState) IsFailure() bool {\n\treturn state != nil && state.State == TRISTATE_FAILRUE\n}\n\n\n\nfunc (state *TriState) IsUnknown() bool ", "output": "{\n\treturn state != nil && state.State == TRISTATE_UNKNOWN\n}"} {"input": "package stashkins\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/user\"\n\t\"testing\"\n)\n\n\n\nfunc TestDirNotExists(t *testing.T) {\n\tname, err := ioutil.TempDir(\"\", \"tmp-\")\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot create temp dir. Unexpected error: %v\\n\", err)\n\t}\n\tdefer os.RemoveAll(name)\n\n\texists, err := dirExists(name + \"/foo\")\n\tif err != nil {\n\t\tos.RemoveAll(name)\n\t\tt.Fatalf(\"Unexpected error: %v\\n\", err)\n\t}\n\n\tif exists {\n\t\tos.RemoveAll(name)\n\t\tt.Fatalf(\"Want true\\n\")\n\t}\n}\n\nfunc TestDirExists(t *testing.T) ", "output": "{\n\tcurrentUser, err := user.Current()\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot get current user: %v\\n\", err)\n\t}\n\n\texists, err := dirExists(currentUser.HomeDir)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error: %v\\n\", err)\n\t}\n\n\tif !exists {\n\t\tt.Fatalf(\"Want true\\n\")\n\t}\n}"} {"input": "package wait\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tpb \"github.com/chai2010/qingcloud-go/pkg/api\"\n\tstatuspkg \"github.com/chai2010/qingcloud-go/pkg/status\"\n)\n\n\n\nfunc waitJob(server *pb.ServerInfo, jobId string) (done bool, err error) {\n\treply, err := pb.NewJobService(server).DescribeJobs(&pb.DescribeJobsInput{\n\t\tJobs: []string{jobId},\n\t})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif len(reply.GetJobSet()) != 1 {\n\t\treturn false, fmt.Errorf(\"can not find job [%s]\", jobId)\n\t}\n\n\tstatus := statuspkg.JobStatus(reply.GetJobSet()[0].GetStatus())\n\tswitch status {\n\tcase statuspkg.JobStatus_Successful:\n\t\treturn true, nil \n\tcase statuspkg.JobStatus_Pending, statuspkg.JobStatus_Working:\n\t\treturn false, nil\n\tcase statuspkg.JobStatus_Failed:\n\t\treturn false, fmt.Errorf(\"job [%s] failed\", jobId)\n\tdefault:\n\t\treturn false, fmt.Errorf(\"unknow status [%s] for job [%s]\", status, jobId)\n\t}\n}\n\nfunc WaitJob(server *pb.ServerInfo, jobId string, timeout time.Duration) error ", "output": "{\n\treturn WaitForIntervalWorkDone(\n\t\tfmt.Sprintf(\"job:%v\", jobId), timeout, func() (done bool, err error) {\n\t\t\treturn waitJob(server, jobId)\n\t\t},\n\t)\n}"} {"input": "package tracing\n\nimport (\n\t\"crypto/sha256\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/containous/traefik/log\"\n)\n\n\nconst TraceNameHashLength = 8\n\n\n\nconst OperationNameMaxLengthNumber = 10\n\nfunc generateOperationName(prefix string, parts []string, sep string, spanLimit int) string {\n\tname := prefix + \" \" + strings.Join(parts, sep)\n\n\tmaxLength := OperationNameMaxLengthNumber + len(prefix) + 1\n\n\tif spanLimit > 0 && len(name) > spanLimit {\n\t\tif spanLimit < maxLength {\n\t\t\tlog.WithoutContext().Warnf(\"SpanNameLimit cannot be lesser than %d: falling back on %d, maxLength, maxLength+3\", maxLength)\n\t\t\tspanLimit = maxLength + 3\n\t\t}\n\n\t\tlimit := (spanLimit - maxLength) / 2\n\n\t\tvar fragments []string\n\t\tfor _, value := range parts {\n\t\t\tfragments = append(fragments, truncateString(value, limit))\n\t\t}\n\t\tfragments = append(fragments, computeHash(name))\n\n\t\tname = prefix + \" \" + strings.Join(fragments, sep)\n\t}\n\n\treturn name\n}\n\n\n\n\n\nfunc computeHash(name string) string {\n\tdata := []byte(name)\n\thash := sha256.New()\n\tif _, err := hash.Write(data); err != nil {\n\t\tlog.WithoutContext().WithField(\"OperationName\", name).Errorf(\"Failed to create Span name hash for %s: %v\", name, err)\n\t}\n\n\treturn fmt.Sprintf(\"%x\", hash.Sum(nil))[:TraceNameHashLength]\n}\n\nfunc truncateString(str string, num int) string ", "output": "{\n\ttext := str\n\tif len(str) > num {\n\t\tif num > 3 {\n\t\t\tnum -= 3\n\t\t}\n\t\ttext = str[0:num] + \"...\"\n\t}\n\treturn text\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/config\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdGetJSONConfig{\n\t\tname: \"get_json_section\",\n\t\trpcMethod: utils.ConfigSv1GetConfig,\n\t\trpcParams: &config.SectionWithOpts{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetJSONConfig struct {\n\tname string\n\trpcMethod string\n\trpcParams *config.SectionWithOpts\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetJSONConfig) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdGetJSONConfig) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdGetJSONConfig) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &config.SectionWithOpts{Opts: make(map[string]interface{})}\n\t}\n\treturn self.rpcParams\n}\n\n\n\nfunc (self *CmdGetJSONConfig) RpcResult() interface{} {\n\tvar s map[string]interface{}\n\treturn &s\n}\n\nfunc (self *CmdGetJSONConfig) PostprocessRpcParams() error ", "output": "{\n\treturn nil\n}"} {"input": "package printer\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/resoursea/api\"\n)\n\nfunc Router(rt api.Router) {\n\tfmt.Println(\"\\n--- PRINT ROUTER ---\\n\")\n\trouter(rt, 0)\n\tfmt.Println(\"\\n--- END PRINT ---\\n\")\n}\n\n\n\nfunc handler(m api.Method, lvl int) {\n\tfmt.Printf(\"%s- Method: %s\\n\", strings.Repeat(\"\t\", lvl), m)\n}\n\nfunc router(r api.Router, lvl int) ", "output": "{\n\tfmt.Printf(\"%sRoute: %s\\n\", strings.Repeat(\"\t\", lvl), r)\n\n\tfor _, m := range r.Methods() {\n\t\thandler(m, lvl)\n\t}\n\n\tfor _, c := range r.Children() {\n\t\tif r.IsSlice() {\n\t\t\trouter(c, lvl)\n\t\t} else {\n\t\t\trouter(c, lvl+1)\n\t\t}\n\t}\n}"} {"input": "package dbfiles\n\nimport (\n\t\"encoding/csv\"\n\t\"io\"\n\n\t\"github.com/juju/errgo\"\n)\n\ntype Driver interface {\n\tExtention() string\n\tWrite(io.Writer, []string) error\n\tRead(io.Reader) ([][]string, error)\n}\n\ntype CSV struct{}\n\n\n\nfunc (driver CSV) Write(writer io.Writer, values []string) error {\n\tcsvwriter := csv.NewWriter(writer)\n\n\terr := csvwriter.WriteAll([][]string{values})\n\tif err != nil {\n\t\treturn errgo.Notef(err, \"can not write to csv writer\")\n\t}\n\n\treturn nil\n}\n\nfunc (driver CSV) Read(reader io.Reader) ([][]string, error) {\n\tcsvreader := csv.NewReader(reader)\n\tcsvreader.FieldsPerRecord = -1\n\n\tvar values [][]string\n\n\tvalues, err := csvreader.ReadAll()\n\tif err != nil {\n\t\treturn nil, errgo.Notef(err, \"can not read all records from file\")\n\t}\n\n\treturn values, nil\n}\n\nfunc (driver CSV) Extention() string ", "output": "{\n\treturn \"csv\"\n}"} {"input": "package datastore\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype JSONMessage interface {\n\tBytes() json.RawMessage\n\tVersion() map[string]int\n}\n\n\n\n\ntype jsonMessage struct {\n\tdata json.RawMessage\n\tvEntity map[string]int\n}\n\nfunc (m *jsonMessage) Bytes() json.RawMessage {\n\treturn m.data\n}\n\nfunc (m *jsonMessage) Version() map[string]int {\n\treturn m.vEntity\n}\n\n\nfunc (m *jsonMessage) MarshalJSON() ([]byte, error) {\n\treturn m.data.MarshalJSON()\n}\n\n\nfunc (m *jsonMessage) UnmarshalJSON(data []byte) error {\n\treturn m.data.UnmarshalJSON(data)\n}\n\nfunc NewJSONMessage(data []byte, version map[string]int) JSONMessage ", "output": "{\n\treturn &jsonMessage{data, version}\n}"} {"input": "package npm\n\nimport \"github.com/node4j/node-repo-proxy/util\"\n\nfunc GetMetaData(name string) ([]byte, error) {\n\tkey := \"npm.\" + name\n\tdata, found := util.GetFromCache(key)\n\tif found {\n\t\treturn data.([]byte), nil\n\t}\n\n\tdata, err := loadMetaData(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tutil.PutInCache(key, data)\n\treturn data.([]byte), nil\n}\n\n\n\nfunc loadMetaData(name string) ([]byte, error) ", "output": "{\n\tindex, err := fetchIndex(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif index == nil {\n\t\treturn nil, nil\n\t}\n\n\tdata, err := indexToMaven(*index)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}"} {"input": "package platform\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os/user\"\n\t\"testing\"\n\n\t\"github.com/jmoiron/sqlx\"\n\n\t\"github.com/tapglue/snaas/platform/pg\"\n)\n\nvar pgTestURL string\n\nfunc TestPostgresPut(t *testing.T) {\n\ttestServicePut(t, preparePostgres)\n}\n\nfunc TestPostgresQuery(t *testing.T) {\n\ttestServiceQuery(t, preparePostgres)\n}\n\nfunc preparePostgres(t *testing.T, namespace string) Service {\n\tdb, err := sqlx.Connect(\"postgres\", pgTestURL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ts := PostgresService(db)\n\n\tif err := s.Teardown(namespace); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treturn s\n}\n\n\n\nfunc init() ", "output": "{\n\tu, err := user.Current()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\td := fmt.Sprintf(pg.URLTest, u.Username)\n\n\turl := flag.String(\"postgres.url\", d, \"Postgres test connection URL\")\n\tflag.Parse()\n\n\tpgTestURL = *url\n}"} {"input": "package template\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n)\n\ntype TemplateType string\n\ntype Template interface {\n\tType() TemplateType\n\tSupportsButtons() bool\n}\n\ntype Payload struct {\n\tElements []Template `json:\"elements\"`\n}\n\ntype rawPayload struct {\n\tType TemplateType `json:\"template_type\"`\n\tElements []Template `json:\"elements\"`\n}\n\n\n\nfunc (p *Payload) MarshalJSON() ([]byte, error) ", "output": "{\n\trp := &rawPayload{}\n\tif len(p.Elements) < 1 {\n\t\treturn []byte{}, errors.New(\"Elements slice cannot be empty\")\n\t}\n\trp.Elements = p.Elements\n\trp.Type = p.Elements[0].Type()\n\treturn json.Marshal(rp)\n}"} {"input": "package filtered\n\nimport (\n\tcontext \"context\"\n\n\tv1 \"github.com/google/knative-gcp/pkg/client/informers/externalversions/events/v1\"\n\tfiltered \"github.com/google/knative-gcp/pkg/client/injection/informers/factory/filtered\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Default.RegisterFilteredInformers(withInformer)\n}\n\n\ntype Key struct {\n\tSelector string\n}\n\nfunc withInformer(ctx context.Context) (context.Context, []controller.Informer) {\n\tuntyped := ctx.Value(filtered.LabelKey{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch labelkey from context.\")\n\t}\n\tlabelSelectors := untyped.([]string)\n\tinfs := []controller.Informer{}\n\tfor _, selector := range labelSelectors {\n\t\tf := filtered.Get(ctx, selector)\n\t\tinf := f.Events().V1().CloudStorageSources()\n\t\tctx = context.WithValue(ctx, Key{Selector: selector}, inf)\n\t\tinfs = append(infs, inf.Informer())\n\t}\n\treturn ctx, infs\n}\n\n\n\n\nfunc Get(ctx context.Context, selector string) v1.CloudStorageSourceInformer ", "output": "{\n\tuntyped := ctx.Value(Key{Selector: selector})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panicf(\n\t\t\t\"Unable to fetch github.com/google/knative-gcp/pkg/client/informers/externalversions/events/v1.CloudStorageSourceInformer with selector %s from context.\", selector)\n\t}\n\treturn untyped.(v1.CloudStorageSourceInformer)\n}"} {"input": "package commands\n\nimport (\n\t\"github.com/limetext/lime/backend\"\n)\n\ntype (\n\tUndoCommand struct {\n\t\tbackend.BypassUndoCommand\n\t\thard bool\n\t}\n\tRedoCommand struct {\n\t\tbackend.BypassUndoCommand\n\t\thard bool\n\t}\n)\n\nfunc (c *UndoCommand) Run(v *backend.View, e *backend.Edit) error {\n\tv.UndoStack().Undo(c.hard)\n\treturn nil\n}\n\nfunc (c *RedoCommand) Run(v *backend.View, e *backend.Edit) error {\n\tv.UndoStack().Redo(c.hard)\n\treturn nil\n}\n\n\n\nfunc init() ", "output": "{\n\tregister([]cmd{\n\t\t{\"undo\", &UndoCommand{hard: true}},\n\t\t{\"redo\", &RedoCommand{hard: true}},\n\t\t{\"soft_undo\", &UndoCommand{}},\n\t\t{\"soft_redo\", &RedoCommand{}},\n\t})\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc dummy() (n int, err string) {\n return 1, \"Error message\"\n}\n\n\n\nfunc main() {\n\tfmt.Println(\"Hello, This is GO here!\")\n n, err := dummy()\n fmt.Printf(\"n: %v, err: %v\", n, err)\n\n n1 := 1\n n2 := 2\n n3 := 3\n print(n1, n2, n3) \n}\n\nfunc print(numbers ...int) ", "output": "{\n\n for _, value := range(numbers) {\n fmt.Println(value)\n }\n}"} {"input": "package networks\n\nimport (\n\t\"github.com/gophercloud/gophercloud\"\n\t\"github.com/gophercloud/gophercloud/pagination\"\n)\n\n\nfunc List(client *gophercloud.ServiceClient) pagination.Pager {\n\treturn pagination.NewPager(client, listURL(client), func(r pagination.PageResult) pagination.Page {\n\t\treturn NetworkPage{pagination.SinglePageBase(r)}\n\t})\n}\n\n\n\n\nfunc Get(client *gophercloud.ServiceClient, id string) (r GetResult) ", "output": "{\n\t_, r.Err = client.Get(getURL(client, id), &r.Body, nil)\n\treturn\n}"} {"input": "package quicktest\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\n\nfunc BadCheckf(format string, a ...interface{}) error {\n\te := badCheck(fmt.Sprintf(format, a...))\n\treturn &e\n}\n\n\n\nfunc IsBadCheck(err error) bool {\n\t_, ok := err.(*badCheck)\n\treturn ok\n}\n\ntype badCheck string\n\n\n\n\n\n\n\nvar ErrSilent = fmt.Errorf(\"silent failure\")\n\nfunc (e *badCheck) Error() string ", "output": "{\n\treturn \"bad check: \" + string(*e)\n}"} {"input": "package displayers\n\nimport (\n\t\"io\"\n\t\"strings\"\n\n\t\"github.com/digitalocean/doctl/do\"\n)\n\ntype Certificate struct {\n\tCertificates do.Certificates\n}\n\nvar _ Displayable = &Certificate{}\n\nfunc (c *Certificate) JSON(out io.Writer) error {\n\treturn writeJSON(c.Certificates, out)\n}\n\nfunc (c *Certificate) Cols() []string {\n\treturn []string{\n\t\t\"ID\",\n\t\t\"Name\",\n\t\t\"DNSNames\",\n\t\t\"SHA1Fingerprint\",\n\t\t\"NotAfter\",\n\t\t\"Created\",\n\t\t\"Type\",\n\t\t\"State\",\n\t}\n}\n\nfunc (c *Certificate) ColMap() map[string]string {\n\treturn map[string]string{\n\t\t\"ID\": \"ID\",\n\t\t\"Name\": \"Name\",\n\t\t\"DNSNames\": \"DNS Names\",\n\t\t\"SHA1Fingerprint\": \"SHA-1 Fingerprint\",\n\t\t\"NotAfter\": \"Expiration Date\",\n\t\t\"Created\": \"Created At\",\n\t\t\"Type\": \"Type\",\n\t\t\"State\": \"State\",\n\t}\n}\n\n\n\nfunc (c *Certificate) KV() []map[string]interface{} ", "output": "{\n\tout := []map[string]interface{}{}\n\n\tfor _, c := range c.Certificates {\n\t\to := map[string]interface{}{\n\t\t\t\"ID\": c.ID,\n\t\t\t\"Name\": c.Name,\n\t\t\t\"DNSNames\": strings.Join(c.DNSNames, \",\"),\n\t\t\t\"SHA1Fingerprint\": c.SHA1Fingerprint,\n\t\t\t\"NotAfter\": c.NotAfter,\n\t\t\t\"Created\": c.Created,\n\t\t\t\"Type\": c.Type,\n\t\t\t\"State\": c.State,\n\t\t}\n\t\tout = append(out, o)\n\t}\n\n\treturn out\n}"} {"input": "package termhook\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\n\n\nfunc addTerminatingSignals(c chan<- os.Signal) ", "output": "{\n\tsignal.Notify(c, os.Interrupt)\n\tsignal.Notify(c, syscall.SIGTERM)\n}"} {"input": "package cmd\n\nimport (\n\t\"time\"\n\n\t\"github.com/codegangsta/cli\"\n)\n\nfunc stringFlag(name, value, usage string) cli.StringFlag {\n\treturn cli.StringFlag{\n\t\tName: name,\n\t\tValue: value,\n\t\tUsage: usage,\n\t}\n}\n\n\n\nfunc intFlag(name string, value int, usage string) cli.IntFlag {\n\treturn cli.IntFlag{\n\t\tName: name,\n\t\tValue: value,\n\t\tUsage: usage,\n\t}\n}\n\nfunc durationFlag(name string, value time.Duration, usage string) cli.DurationFlag {\n\treturn cli.DurationFlag{\n\t\tName: name,\n\t\tValue: value,\n\t\tUsage: usage,\n\t}\n}\n\nfunc boolFlag(name, usage string) cli.BoolFlag ", "output": "{\n\treturn cli.BoolFlag{\n\t\tName: name,\n\t\tUsage: usage,\n\t}\n}"} {"input": "package fsutil\n\nimport (\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com/containerd/continuity/sysx\"\n\t\"github.com/pkg/errors\"\n)\n\nfunc rewriteMetadata(p string, stat *Stat) error {\n\tfor key, value := range stat.Xattrs {\n\t\tsysx.Setxattr(p, key, value, 0)\n\t}\n\n\tif err := os.Lchown(p, int(stat.Uid), int(stat.Gid)); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to lchown %s\", p)\n\t}\n\n\tif os.FileMode(stat.Mode)&os.ModeSymlink == 0 {\n\t\tif err := os.Chmod(p, os.FileMode(stat.Mode)); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to chown %s\", p)\n\t\t}\n\t}\n\n\tif err := chtimes(p, stat.ModTime); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to chtimes %s\", p)\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc handleTarTypeBlockCharFifo(path string, stat *Stat) error ", "output": "{\n\tmode := uint32(stat.Mode & 07777)\n\tif os.FileMode(stat.Mode)&os.ModeCharDevice != 0 {\n\t\tmode |= syscall.S_IFCHR\n\t} else if os.FileMode(stat.Mode)&os.ModeNamedPipe != 0 {\n\t\tmode |= syscall.S_IFIFO\n\t} else {\n\t\tmode |= syscall.S_IFBLK\n\t}\n\n\tif err := syscall.Mknod(path, mode, int(mkdev(stat.Devmajor, stat.Devminor))); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package transport\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\tma \"gx/ipfs/QmSWLfmj5frN9xVLMMN846dMDriy5wN5jeghUm7aTW3DAG/go-multiaddr\"\n\tmanet \"gx/ipfs/QmVCNGTyD4EkvNYaAp253uMQ9Rjsjy2oGMvcdJJUoVRfja/go-multiaddr-net\"\n\tmafmt \"gx/ipfs/QmYjJnSTfXWhYL2cV1xFphPqjqowJqH7ZKLA1As8QrPHbn/mafmt\"\n)\n\ntype FallbackDialer struct {\n\tmadialer manet.Dialer\n}\n\n\n\nfunc (fbd *FallbackDialer) Dial(a ma.Multiaddr) (Conn, error) {\n\treturn fbd.DialContext(context.Background(), a)\n}\n\nfunc (fbd *FallbackDialer) DialContext(ctx context.Context, a ma.Multiaddr) (Conn, error) {\n\tif mafmt.TCP.Matches(a) {\n\t\treturn fbd.tcpDial(ctx, a)\n\t}\n\treturn nil, fmt.Errorf(\"cannot dial %s with fallback dialer\", a)\n}\n\nfunc (fbd *FallbackDialer) tcpDial(ctx context.Context, raddr ma.Multiaddr) (Conn, error) {\n\tvar c manet.Conn\n\tvar err error\n\tc, err = fbd.madialer.DialContext(ctx, raddr)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ConnWrap{\n\t\tConn: c,\n\t}, nil\n}\n\nvar _ Dialer = (*FallbackDialer)(nil)\n\nfunc (fbd *FallbackDialer) Matches(a ma.Multiaddr) bool ", "output": "{\n\treturn mafmt.TCP.Matches(a)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/coscms/webx\"\n)\n\ntype MainAction struct {\n\t*webx.Action\n\n\thello webx.Mapper `webx:\"/(.*)\"`\n}\n\n\n\nfunc main() {\n\tapp1 := webx.NewApp(\"/\")\n\tapp1.AddAction(&MainAction{})\n\twebx.AddApp(app1)\n\n\tapp2 := webx.NewApp(\"/user/\")\n\tapp2.AddAction(&MainAction{})\n\twebx.AddApp(app2)\n\n\twebx.Run(\"0.0.0.0:9999\")\n}\n\nfunc (c *MainAction) Hello(world string) ", "output": "{\n\tc.Write(\"hello %v\", world)\n}"} {"input": "package present\n\nimport (\n\t\"github.com/concourse/atc\"\n\t\"github.com/concourse/atc/db\"\n)\n\n\n\nfunc Pipelines(savedPipelines []db.SavedPipeline) []atc.Pipeline ", "output": "{\n\tpipelines := make([]atc.Pipeline, len(savedPipelines))\n\n\tfor i := range savedPipelines {\n\t\tpipelines[i] = Pipeline(savedPipelines[i])\n\t}\n\n\treturn pipelines\n}"} {"input": "package foursum\n\nimport \"sort\"\n\n\n\nfunc threeSum(r *[][]int, nums []int, base, target int) {\n\tfor i, l := 0, len(nums); i < l-2; i++ { \n\t\tif i == 0 || nums[i] != nums[i-1] { \n\t\t\tfor n, j, k := nums[i], i+1, l-1; j < k; {\n\t\t\t\tif sum := n + nums[j] + nums[k]; sum == target {\n\t\t\t\t\t*r = append(*r, []int{base, n, nums[j], nums[k]}) \n\t\t\t\t\tfor k--; k > j && nums[k] == nums[k+1]; k-- { \n\t\t\t\t\t}\n\t\t\t\t\tfor j++; j < k && nums[j] == nums[j-1]; j++ { \n\t\t\t\t\t}\n\t\t\t\t} else if sum > target {\n\t\t\t\t\tk-- \n\t\t\t\t} else {\n\t\t\t\t\tj++ \n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc fourSum(nums []int, target int) [][]int ", "output": "{\n\tif l := len(nums); l >= 4 {\n\t\tsort.Ints(nums) \n\n\t\tr := make([][]int, 0, l)\n\t\tfor i := 0; i < l-3; i++ {\n\t\t\tif i == 0 || nums[i] != nums[i-1] { \n\t\t\t\tthreeSum(&r, nums[i+1:], nums[i], target-nums[i])\n\t\t\t}\n\t\t}\n\t\treturn r\n\t}\n\treturn [][]int{}\n}"} {"input": "package mem\n\nimport (\n\t\"runtime\"\n\t\"time\"\n)\n\n\n\nvar historicUsage *Usage\n\n\n\nconst memUsageMeasureInterval = 5 * time.Second\n\n\n\n\n\n\ntype Usage struct {\n\tMem uint64 `json:\"mem\"`\n\tError string `json:\"error,omitempty\"`\n}\n\n\n\nfunc GetHistoricUsage() Usage {\n\treturn *historicUsage\n}\n\n\n\nfunc GetUsage() Usage {\n\tmemStats := new(runtime.MemStats)\n\truntime.ReadMemStats(memStats)\n\treturn Usage{\n\t\tMem: memStats.Sys,\n\t}\n}\n\nfunc init() ", "output": "{\n\thistoricUsage = &Usage{}\n\tvar cycles uint64\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(memUsageMeasureInterval)\n\t\t\tcurrUsage := GetUsage()\n\t\t\tcurrSum := cycles * historicUsage.Mem\n\t\t\tcycles = cycles + 1\n\t\t\thistoricUsage.Mem = (currSum + currUsage.Mem) / cycles\n\t\t}\n\t}()\n}"} {"input": "package log\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"sync\"\n)\n\nconst (\n\tSilent int = iota\n\tError\n\tInfo\n\tDebug\n)\n\n\nvar (\n\tlevel = Error\n\tlock sync.Mutex\n)\n\n\nfunc SetLevel(l int) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tlevel = l\n}\n\n\nfunc Infof(format string, args ...interface{}) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif level < Info {\n\t\treturn\n\t}\n\n\tmsg := fmt.Sprintf(\"INFO: %s\", format)\n\tif len(args) > 0 {\n\t\tmsg = fmt.Sprintf(msg, args...)\n\t}\n\n\tlog.Println(msg)\n}\n\n\nfunc Debugf(format string, args ...interface{}) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif level < Debug {\n\t\treturn\n\t}\n\n\tmsg := fmt.Sprintf(\"DEBUG: %s\", format)\n\tif len(args) > 0 {\n\t\tmsg = fmt.Sprintf(msg, args...)\n\t}\n\n\tlog.Println(msg)\n}\n\n\n\n\nfunc Errorf(format string, args ...interface{}) ", "output": "{\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif level < Error {\n\t\treturn\n\t}\n\n\tmsg := fmt.Sprintf(\"ERROR: %s\", format)\n\tif len(args) > 0 {\n\t\tmsg = fmt.Sprintf(msg, args...)\n\t}\n\n\tlog.Println(msg)\n}"} {"input": "package communication\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) BaseClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package elasticsearch_test\n\nimport (\n\t\"crypto/tls\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/elastic/go-elasticsearch/v7\"\n\t\"github.com/elastic/go-elasticsearch/v7/estransport\"\n)\n\nfunc init() {\n\tlog.SetFlags(0)\n}\n\n\n\nfunc ExampleNewClient() {\n\tcfg := elasticsearch.Config{\n\t\tAddresses: []string{\n\t\t\t\"http:localhost:9200\",\n\t\t},\n\t\tUsername: \"foo\",\n\t\tPassword: \"bar\",\n\t\tTransport: &http.Transport{\n\t\t\tMaxIdleConnsPerHost: 10,\n\t\t\tResponseHeaderTimeout: time.Second,\n\t\t\tDialContext: (&net.Dialer{Timeout: time.Second}).DialContext,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tMinVersion: tls.VersionTLS11,\n\t\t\t},\n\t\t},\n\t}\n\n\tes, _ := elasticsearch.NewClient(cfg)\n\tlog.Print(es.Transport.(*estransport.Client).URLs())\n}\n\nfunc ExampleNewClient_logger() {\n\n\n\tcfg := elasticsearch.Config{\n\t\tLogger: &estransport.ColorLogger{Output: os.Stdout},\n\t}\n\n\telasticsearch.NewClient(cfg)\n}\n\nfunc ExampleNewDefaultClient() ", "output": "{\n\tes, err := elasticsearch.NewDefaultClient()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error creating the client: %s\\n\", err)\n\t}\n\n\tres, err := es.Info()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error getting the response: %s\\n\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tlog.Print(es.Transport.(*estransport.Client).URLs())\n}"} {"input": "package client\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/alexhokl/go-bb-pr/models\"\n)\n\n\n\n\nfunc (client *Client) DeclineRequest(cred *models.UserCredential, repo *models.Repository, id int) error ", "output": "{\n\tpath := fmt.Sprintf(\"%s/%d/decline\", getBasePath(repo), id)\n\treq := newRequest(cred, \"POST\", path)\n\tresp, err := client.do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != 200 {\n\t\tmsg := getErrorResponseMessage(resp)\n\t\treturn errors.New(msg)\n\t}\n\treturn nil\n}"} {"input": "package info\n\nimport (\n\t\"github.com/elastic/beats/libbeat/common\"\n\t\"github.com/elastic/beats/libbeat/logp\"\n\t\"github.com/elastic/beats/metricbeat/mb\"\n\t\"github.com/elastic/beats/metricbeat/module/docker\"\n\n\tdc \"github.com/fsouza/go-dockerclient\"\n)\n\nfunc init() {\n\tif err := mb.Registry.AddMetricSet(\"docker\", \"info\", New, docker.HostParser); err != nil {\n\t\tpanic(err)\n\t}\n}\n\ntype MetricSet struct {\n\tmb.BaseMetricSet\n\tdockerClient *dc.Client\n}\n\n\n\n\n\n\nfunc (m *MetricSet) Fetch() (common.MapStr, error) {\n\tinfo, err := m.dockerClient.Info()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn eventMapping(info), nil\n}\n\nfunc New(base mb.BaseMetricSet) (mb.MetricSet, error) ", "output": "{\n\tlogp.Warn(\"EXPERIMENTAL: The docker info metricset is experimental\")\n\n\tconfig := docker.Config{}\n\tif err := base.Module().UnpackConfig(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient, err := docker.NewDockerClient(base.HostData().URI, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &MetricSet{\n\t\tBaseMetricSet: base,\n\t\tdockerClient: client,\n\t}, nil\n}"} {"input": "package httpmux\n\nimport \"net/http\"\n\n\ntype ConfigOption interface {\n\tSet(c *Config)\n}\n\n\ntype ConfigOptionFunc func(c *Config)\n\n\nfunc (f ConfigOptionFunc) Set(c *Config) { f(c) }\n\n\nfunc WithPrefix(prefix string) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Prefix = prefix })\n}\n\n\nfunc WithMiddleware(mw ...Middleware) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Middleware = mw })\n}\n\n\nfunc WithMiddlewareFunc(mw ...MiddlewareFunc) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.UseFunc(mw...) })\n}\n\n\nfunc WithRedirectTrailingSlash(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectTrailingSlash = v })\n}\n\n\nfunc WithRedirectFixedPath(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectFixedPath = v })\n}\n\n\nfunc WithHandleMethodNotAllowed(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.HandleMethodNotAllowed = v })\n}\n\n\nfunc WithNotFound(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.NotFound = f })\n}\n\n\nfunc WithMethodNotAllowed(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.MethodNotAllowed = f })\n}\n\n\n\n\nfunc WithPanicHandler(f func(http.ResponseWriter, *http.Request, interface{})) ConfigOption ", "output": "{\n\treturn ConfigOptionFunc(func(c *Config) { c.PanicHandler = f })\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestMainDotJava(t *testing.T) ", "output": "{\n\tpkgName = \"testapp\"\n\tpkgPath = \"com.example.testapp\"\n\tret, _ := mainDotJava(nil)\n\tif !strings.Contains(string(ret), \"package com.example.testapp\") {\n\t\tt.Error(\"Error in package statement\")\n\t}\n\n\tif !strings.Contains(string(ret), \"import go.testapp.Testapp\") {\n\t\tt.Error(\"Error in import statement\")\n\t}\n\n\tif !strings.Contains(string(ret), \"Testapp.Start()\") {\n\t\tt.Error(\"Error in webapp start\")\n\t}\n\n\tif !strings.Contains(string(ret), \"Testapp.Stop()\") {\n\t\tt.Error(\"Error in webapp stop\")\n\t}\n}"} {"input": "package assert\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"runtime\"\n)\n\nconst windows = runtime.GOOS == \"windows\"\n\n\n\n\n\ntype MatchPath string\n\nfunc isSlash(c byte) bool { return c == '\\\\' || c == '/' }\n\nfunc (m MatchPath) isAbs(path string) bool {\n\treturn filepath.IsAbs(path) || (windows && len(path) != 0 && isSlash(path[0]))\n}\n\nfunc (m MatchPath) cleanPath(s string) string {\n\tif !windows || !m.isAbs(s) {\n\t\treturn s\n\t}\n\ta, err := filepath.Abs(s)\n\tif err != nil {\n\t\treturn s\n\t}\n\treturn a\n}\n\n\n\nfunc (m MatchPath) FailureMessage(actual interface{}) string {\n\tif windows {\n\t\tif s, ok := actual.(string); ok {\n\t\t\treturn fmt.Sprintf(\"Expected\\n\\t%v\\n\\t%v (clean)\\nto match file\\n\\t%v\\n\\t%v (clean)\",\n\t\t\t\tactual, m.cleanPath(s), m, m.cleanPath(string(m)))\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"Expected\\n\\t%v\\nto match file\\n\\t%v\", actual, m)\n}\n\nfunc (m MatchPath) NegatedFailureMessage(actual interface{}) string {\n\tif windows {\n\t\tif s, ok := actual.(string); ok {\n\t\t\treturn fmt.Sprintf(\"Expected\\n\\t%v\\n\\t%v (clean)\\nnot to match file\\n\\t%v\\n\\t%v (clean)\",\n\t\t\t\tactual, m.cleanPath(s), m, m.cleanPath(string(m)))\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"Expected\\n\\t%v\\nnot to match file\\n\\t%v\", actual, m)\n}\n\nfunc (m MatchPath) Match(actual interface{}) (bool, error) ", "output": "{\n\tpath, ok := actual.(string)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"MatchPath: expects a string got: %T\", actual)\n\t}\n\tif path == string(m) || (filepath.Clean(path) == filepath.Clean(string(m))) {\n\t\treturn true, nil\n\t}\n\treturn m.cleanPath(path) == m.cleanPath(string(m)), nil\n}"} {"input": "package cephaloutils\n\nimport (\n\t\"time\"\n\n\t\"github.com/paulidealiste/Cephalopod/cephalobjects\"\n)\n\n\nfunc CTSListForm(cts cephalobjects.CephaloTimeSeries) cephalobjects.TimeSeriesDataLike {\n\tvar tslist []cephalobjects.TimeSeriesDataPoint\n\tpointcount := 0\n\tcts.TraversalMap(cts.Root, func(current *cephalobjects.CephaloTimeNode) {\n\t\ttspoint := cephalobjects.TimeSeriesDataPoint{ID: pointcount, Data: current.Data, Datetime: current.Datetime.Format(time.RFC3339)}\n\t\ttslist = append(tslist, tspoint)\n\t\tpointcount++\n\t})\n\ttsdl := cephalobjects.TimeSeriesDataLike{ID: cts.ID, Data: tslist}\n\treturn tsdl\n}\n\n\nfunc CTSListMap(cts cephalobjects.CephaloTimeSeries) map[int]cephalobjects.TimeSeriesDataLike {\n\ttsdl := CTSListForm(cts)\n\ttsdlm := make(map[int]cephalobjects.TimeSeriesDataLike)\n\ttsdlm[tsdl.ID] = tsdl\n\treturn tsdlm\n}\n\n\n\n\nfunc tslistworker(id int, jobs <-chan cephalobjects.CephaloTimeSeries, results chan<- cephalobjects.TimeSeriesDataLike) {\n\tfor cts := range jobs {\n\t\ttsdl := CTSListForm(cts)\n\t\tresults <- tsdl\n\t}\n}\n\nfunc TSListsFromTSTrees(ctss []cephalobjects.CephaloTimeSeries) map[int]cephalobjects.TimeSeriesDataLike ", "output": "{\n\ttsdlsm := make(map[int]cephalobjects.TimeSeriesDataLike)\n\tjobs := make(chan cephalobjects.CephaloTimeSeries, 100)\n\tresults := make(chan cephalobjects.TimeSeriesDataLike, 100)\n\tfor w := 1; w <= 3; w++ {\n\t\tgo tslistworker(w, jobs, results)\n\t}\n\tfor _, cts := range ctss {\n\t\tjobs <- cts\n\t}\n\tclose(jobs)\n\tfor i := 0; i < len(ctss); i++ {\n\t\ttemplistform := <-results\n\t\ttsdlsm[templistform.ID] = templistform\n\t}\n\treturn tsdlsm\n}"} {"input": "package rand\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\nfunc init() {\n\tisEAGAIN = unixIsEAGAIN\n}\n\n\n\n\n\nfunc unixIsEAGAIN(err error) bool ", "output": "{\n\tif pe, ok := err.(*os.PathError); ok {\n\t\tif errno, ok := pe.Err.(syscall.Errno); ok && errno == syscall.EAGAIN {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package servicecontrol\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\nvar (\n\tsshServiceName = \"ssh\"\n\tdisableSshFilename = \"/etc/ssh/sshd_not_to_be_run\"\n)\n\ntype SshService struct {\n\tdefaults *ServiceControlSettings\n}\n\n\n\nfunc NewSshService() *SshService {\n\treturn &SshService{\n\t\tdefaults: getSshSettings(),\n\t}\n}\n\nfunc (s *SshService) IsAvailable() bool {\n\treturn true\n}\n\nfunc (s *SshService) GetDefaults() *ServiceControlSettings {\n\treturn s.defaults\n}\n\nfunc (s *SshService) ApplySettings(settings *ServiceControlSettings) error {\n\tvar action string\n\trunning, statusErr := isServiceRunning(sshServiceName)\n\tif settings.Enabled {\n\t\tif running && statusErr == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\taction = \"start\"\n\t\tif err := removeFile(disableSshFilename); err != nil {\n\t\t\tlog.Println(\"Could not enable ssh service\", err)\n\t\t}\n\t} else {\n\t\tif !running && statusErr == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\taction = \"stop\"\n\t\tif err := touchFile(disableSshFilename); err != nil {\n\t\t\tlog.Println(\"Could not disable ssh service\", err)\n\t\t}\n\t}\n\n\treturn runServiceCommand(sshServiceName, action)\n}\n\nfunc (s *SshService) QuerySettings() (*ServiceControlSettings, error) {\n\treturn getSshSettings(), nil\n}\n\nfunc init() {\n\tRegisterService(\"ssh\", NewSshService())\n}\n\nfunc getSshSettings() *ServiceControlSettings ", "output": "{\n\tis_enabled := true\n\tinfo, _ := os.Stat(disableSshFilename)\n\tif info != nil {\n\t\tis_enabled = false\n\t}\n\n\treturn &ServiceControlSettings{\n\t\tEnabled: is_enabled,\n\t}\n}"} {"input": "package fields\n\nimport (\n\t\"regexp\"\n\t\"time\"\n)\n\nfunc UseDefaultKeyIfCustomKeyIsEmpty(defaultKey, customKey string) string {\n\tif \"\" != customKey {\n\t\treturn customKey\n\t}\n\treturn defaultKey\n}\n\nfunc ExecFuncIfErrIsNotNil(err error, fn func()) (b bool) {\n\tif nil != err {\n\t\tfn()\n\t\tb = true\n\t}\n\treturn\n}\n\nfunc getMessageFromError(err error) string {\n\tif nil == err {\n\t\treturn \"\"\n\t}\n\treturn err.Error()\n}\n\nfunc getPatternFromRegExp(re *regexp.Regexp) string {\n\tif nil == re {\n\t\treturn \"\"\n\t}\n\treturn re.String()\n}\n\nfunc execFnIfNotNil(fn func()) {\n\tif nil != fn {\n\t\tfn()\n\t}\n}\n\nfunc addSuffix(name string, suffix *string) string {\n\tif nil != suffix {\n\t\treturn name + \"-\" + *suffix\n\t}\n\treturn name\n}\n\nfunc _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) (*time.Location, int) {\n\tif nil == locationByString || \"\" == *locationByString {\n\t\treturn defaultLoc, 1\n\t}\n\n\tif loc, err := time.LoadLocation(*locationByString); nil == err {\n\t\treturn loc, 2\n\t}\n\n\treturn defaultLoc, 0\n}\n\n\n\n\nfunc useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) *time.Location ", "output": "{\n\tloc, _ := _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc, locationByString)\n\treturn loc\n}"} {"input": "package logrustash\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\n\n\ntype LogstashFormatter struct {\n\tType string \n\n\tTimestampFormat string\n}\n\n\n\nfunc (f *LogstashFormatter) FormatWithPrefix(entry *logrus.Entry, prefix string) ([]byte, error) {\n\tfields := make(logrus.Fields)\n\tfor k, v := range entry.Data {\n\t\tif prefix != \"\" && strings.HasPrefix(k, prefix) {\n\t\t\tk = strings.TrimPrefix(k, prefix)\n\t\t}\n\n\t\tswitch v := v.(type) {\n\t\tcase error:\n\t\t\tfields[k] = v.Error()\n\t\tdefault:\n\t\t\tfields[k] = v\n\t\t}\n\t}\n\n\tfields[\"@version\"] = \"1\"\n\n\ttimeStampFormat := f.TimestampFormat\n\n\tif timeStampFormat == \"\" {\n\t\ttimeStampFormat = time.RFC3339\n\t}\n\n\tfields[\"@timestamp\"] = entry.Time.Format(timeStampFormat)\n\n\tv, ok := entry.Data[\"message\"]\n\tif ok {\n\t\tfields[\"fields.message\"] = v\n\t}\n\tfields[\"message\"] = entry.Message\n\n\tv, ok = entry.Data[\"level\"]\n\tif ok {\n\t\tfields[\"fields.level\"] = v\n\t}\n\tfields[\"level\"] = entry.Level.String()\n\n\tif f.Type != \"\" {\n\t\tv, ok = entry.Data[\"type\"]\n\t\tif ok {\n\t\t\tfields[\"fields.type\"] = v\n\t\t}\n\t\tfields[\"type\"] = f.Type\n\t}\n\n\tserialized, err := json.Marshal(fields)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to marshal fields to JSON, %v\", err)\n\t}\n\treturn append(serialized, '\\n'), nil\n}\n\nfunc (f *LogstashFormatter) Format(entry *logrus.Entry) ([]byte, error) ", "output": "{\n\treturn f.FormatWithPrefix(entry, \"\")\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"github.com/endophage/gotuf\"\n\t\"github.com/endophage/gotuf/data\"\n\t\"github.com/flynn/go-docopt\"\n)\n\nfunc init() {\n\tregister(\"meta\", cmdMeta, `\nusage: tuftools meta [...]\n\nGenerate sample metadata for file(s) given by path.\n\n`)\n}\n\n\n\nfunc cmdMeta(args *docopt.Args, repo *tuf.Repo) error ", "output": "{\n\tpaths := args.All[\"\"].([]string)\n\tfor _, file := range paths {\n\t\treader, _ := os.Open(file)\n\t\tmeta, _ := data.NewFileMeta(reader, \"sha256\")\n\t\tjsonBytes, err := json.Marshal(meta)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfilename := fmt.Sprintf(\"%s.meta.json\", file)\n\t\terr = ioutil.WriteFile(filename, jsonBytes, 0644)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package lib\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype StopChannelContext struct {\n\tStopCh <-chan struct{}\n}\n\n\n\nfunc (c *StopChannelContext) Done() <-chan struct{} {\n\treturn c.StopCh\n}\n\nfunc (c *StopChannelContext) Err() error {\n\tselect {\n\tcase <-c.StopCh:\n\t\treturn context.Canceled\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (c *StopChannelContext) Value(key interface{}) interface{} {\n\treturn nil\n}\n\nfunc (c *StopChannelContext) Deadline() (deadline time.Time, ok bool) ", "output": "{\n\tok = false\n\treturn\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/protobuf/encoding/prototext\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t_ \"google.golang.org/genproto/googleapis/rpc/errdetails\" \n)\n\n\ntype StatusError struct {\n\tst *status.Status\n\tdetails string\n}\n\n\nfunc StatusDetailedError(st *status.Status) *StatusError {\n\tvar details []string\n\tfor _, d := range st.Details() {\n\t\ts := fmt.Sprintf(\"%+v\", d)\n\t\tif pb, ok := d.(proto.Message); ok {\n\t\t\ts = prototext.Format(pb)\n\t\t}\n\t\tdetails = append(details, s)\n\t}\n\treturn &StatusError{st, strings.Join(details, \"; \")}\n}\n\nfunc (e *StatusError) Error() string {\n\tmsg := fmt.Sprintf(\"rpc error: code = %s desc = %s\", e.st.Code(), e.st.Message())\n\tif e.details != \"\" {\n\t\tmsg += \" details = \" + e.details\n\t}\n\treturn msg\n}\n\n\nfunc (e *StatusError) GRPCStatus() *status.Status {\n\treturn e.st\n}\n\n\n\n\n\nfunc (e *StatusError) Is(target error) bool ", "output": "{\n\tif tse, ok := target.(*StatusError); ok {\n\t\treturn proto.Equal(e.st.Proto(), tse.st.Proto())\n\t}\n\tif tst, ok := status.FromError(target); ok {\n\t\treturn proto.Equal(e.st.Proto(), tst.Proto())\n\t}\n\treturn false\n}"} {"input": "package libvirtxml\n\ntype StorageVolumeTargetFormat struct {\n\tnode *Node\n}\n\n\n\nfunc (s StorageVolumeTargetFormat) Type() string {\n\treturn s.node.getAttribute(nameForLocal(\"type\"))\n}\n\nfunc (s StorageVolumeTargetFormat) SetType(value string) {\n\ts.node.setAttribute(nameForLocal(\"type\"), value)\n}\n\nfunc newStorageVolumeTargetFormat(node *Node) StorageVolumeTargetFormat ", "output": "{\n\treturn StorageVolumeTargetFormat{\n\t\tnode: node,\n\t}\n}"} {"input": "package leader\n\nimport (\n\t\"time\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n)\n\ntype poller struct {\n\tleaderChan chan Leadership\n\tpollInterval time.Duration\n\ttick <-chan time.Time\n\tstop chan struct{}\n\tpollFunc CheckLeaderFunc\n}\n\n\n\n\n\nfunc (l *poller) Start() (<-chan Leadership, error) {\n\tif l.leaderChan != nil {\n\t\treturn l.leaderChan, nil\n\t}\n\n\tl.leaderChan = make(chan Leadership)\n\tl.stop = make(chan struct{})\n\n\tgo l.poll()\n\treturn l.leaderChan, nil\n}\n\n\nfunc (l *poller) Stop() {\n\tif l.stop != nil {\n\t\tclose(l.stop)\n\t}\n}\n\nfunc (l *poller) poll() {\n\tfor {\n\t\tselect {\n\n\t\tcase <-l.tick:\n\n\t\t\tisLeader, err := l.pollFunc()\n\t\t\tevent := Leadership{}\n\t\t\tif err != nil {\n\t\t\t\tevent.Status = Unknown\n\t\t\t\tevent.Error = err\n\t\t\t} else {\n\t\t\t\tif isLeader {\n\t\t\t\t\tevent.Status = Leader\n\t\t\t\t} else {\n\t\t\t\t\tevent.Status = NotLeader\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tl.leaderChan <- event\n\n\t\tcase <-l.stop:\n\t\t\tlog.Infoln(\"Stopping leadership check\")\n\t\t\tclose(l.leaderChan)\n\t\t\tl.leaderChan = nil\n\t\t\tl.stop = nil\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc NewPoller(pollInterval time.Duration, f CheckLeaderFunc) Detector ", "output": "{\n\treturn &poller{\n\t\tpollInterval: pollInterval,\n\t\ttick: time.Tick(pollInterval),\n\t\tpollFunc: f,\n\t}\n}"} {"input": "package blocksutil\n\nimport \"gx/ipfs/Qmej7nf81hi2x2tvjRBF3mcp74sQyuDH4VMYDGd1YtXjb2/go-block-format\"\n\n\n\nfunc NewBlockGenerator() BlockGenerator {\n\treturn BlockGenerator{}\n}\n\n\n\n\n\ntype BlockGenerator struct {\n\tseq int\n}\n\n\n\n\n\nfunc (bg *BlockGenerator) Blocks(n int) []blocks.Block {\n\tblocks := make([]blocks.Block, 0, n)\n\tfor i := 0; i < n; i++ {\n\t\tb := bg.Next()\n\t\tblocks = append(blocks, b)\n\t}\n\treturn blocks\n}\n\nfunc (bg *BlockGenerator) Next() *blocks.BasicBlock ", "output": "{\n\tbg.seq++\n\treturn blocks.NewBlock([]byte(string(bg.seq)))\n}"} {"input": "package iso20022\n\n\ntype CorporateActionElection1 struct {\n\n\tOptionType *CorporateActionOption1FormatChoice `xml:\"OptnTp\"`\n\n\tOptionNumber *Exact3NumericText `xml:\"OptnNb\"`\n\n\tOriginalInstructedQuantity *UnitOrFaceAmount1Choice `xml:\"OrgnlInstdQty\"`\n\n\tRemainingQuantity *UnitOrFaceAmount1Choice `xml:\"RmngQty\"`\n}\n\nfunc (c *CorporateActionElection1) AddOptionType() *CorporateActionOption1FormatChoice {\n\tc.OptionType = new(CorporateActionOption1FormatChoice)\n\treturn c.OptionType\n}\n\nfunc (c *CorporateActionElection1) SetOptionNumber(value string) {\n\tc.OptionNumber = (*Exact3NumericText)(&value)\n}\n\nfunc (c *CorporateActionElection1) AddOriginalInstructedQuantity() *UnitOrFaceAmount1Choice {\n\tc.OriginalInstructedQuantity = new(UnitOrFaceAmount1Choice)\n\treturn c.OriginalInstructedQuantity\n}\n\n\n\nfunc (c *CorporateActionElection1) AddRemainingQuantity() *UnitOrFaceAmount1Choice ", "output": "{\n\tc.RemainingQuantity = new(UnitOrFaceAmount1Choice)\n\treturn c.RemainingQuantity\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetVolumeKmsKeyRequest struct {\n\n\tVolumeId *string `mandatory:\"true\" contributesTo:\"path\" name:\"volumeId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetVolumeKmsKeyRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request GetVolumeKmsKeyRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request GetVolumeKmsKeyRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype GetVolumeKmsKeyResponse struct {\n\n\tRawResponse *http.Response\n\n\tVolumeKmsKey `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetVolumeKmsKeyResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetVolumeKmsKeyResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetVolumeKmsKeyRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package fake\n\nimport (\n\tv1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\tlabels \"k8s.io/apimachinery/pkg/labels\"\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\twatch \"k8s.io/apimachinery/pkg/watch\"\n\ttesting \"github.com/hyperhq/client-go/testing\"\n\tv1beta1 \"k8s.io/metrics/pkg/apis/metrics/v1beta1\"\n)\n\n\ntype FakeNodeMetricses struct {\n\tFake *FakeMetricsV1beta1\n}\n\nvar nodemetricsesResource = schema.GroupVersionResource{Group: \"metrics\", Version: \"v1beta1\", Resource: \"nodes\"}\n\nvar nodemetricsesKind = schema.GroupVersionKind{Group: \"metrics\", Version: \"v1beta1\", Kind: \"NodeMetrics\"}\n\n\nfunc (c *FakeNodeMetricses) Get(name string, options v1.GetOptions) (result *v1beta1.NodeMetrics, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewRootGetAction(nodemetricsesResource, name), &v1beta1.NodeMetrics{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*v1beta1.NodeMetrics), err\n}\n\n\n\n\n\nfunc (c *FakeNodeMetricses) Watch(opts v1.ListOptions) (watch.Interface, error) {\n\treturn c.Fake.\n\t\tInvokesWatch(testing.NewRootWatchAction(nodemetricsesResource, opts))\n}\n\nfunc (c *FakeNodeMetricses) List(opts v1.ListOptions) (result *v1beta1.NodeMetricsList, err error) ", "output": "{\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewRootListAction(nodemetricsesResource, nodemetricsesKind, opts), &v1beta1.NodeMetricsList{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\tlabel, _, _ := testing.ExtractFromListOptions(opts)\n\tif label == nil {\n\t\tlabel = labels.Everything()\n\t}\n\tlist := &v1beta1.NodeMetricsList{}\n\tfor _, item := range obj.(*v1beta1.NodeMetricsList).Items {\n\t\tif label.Matches(labels.Set(item.Labels)) {\n\t\t\tlist.Items = append(list.Items, item)\n\t\t}\n\t}\n\treturn list, err\n}"} {"input": "package dom\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\ntype Node interface {\n\tString() string\n\tParent() Node\n\tSetParent(node Node)\n\tChildren() []Node\n\tAddChild(child Node)\n\tClone() Node\n}\n\n\ntype Element struct {\n\ttext string\n\tparent Node\n\tchildren []Node\n}\n\n\nfunc NewElement(text string) *Element {\n\treturn &Element{\n\t\ttext: text,\n\t\tparent: nil,\n\t\tchildren: make([]Node, 0),\n\t}\n}\n\n\nfunc (e *Element) Parent() Node {\n\treturn e.parent\n}\n\n\n\n\n\nfunc (e *Element) Children() []Node {\n\treturn e.children\n}\n\n\nfunc (e *Element) AddChild(child Node) {\n\tcopy := child.Clone()\n\tcopy.SetParent(e)\n\te.children = append(e.children, copy)\n}\n\n\n\nfunc (e *Element) Clone() Node {\n\tcopy := &Element{\n\t\ttext: e.text,\n\t\tparent: nil,\n\t\tchildren: make([]Node, 0),\n\t}\n\tfor _, child := range e.children {\n\t\tcopy.AddChild(child)\n\t}\n\treturn copy\n}\n\n\nfunc (e *Element) String() string {\n\tbuffer := bytes.NewBufferString(e.text)\n\n\tfor _, c := range e.Children() {\n\t\ttext := c.String()\n\t\tfmt.Fprintf(buffer, \"\\n %s\", text)\n\t}\n\n\treturn buffer.String()\n}\n\nfunc (e *Element) SetParent(node Node) ", "output": "{\n\te.parent = node\n}"} {"input": "package payload_test\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/RobotsAndPencils/buford/payload\"\n)\n\nfunc ExampleBrowser() {\n\tp := payload.Browser{\n\t\tAlert: payload.BrowserAlert{\n\t\t\tTitle: \"Flight A998 Now Boarding\",\n\t\t\tBody: \"Boarding has begun for Flight A998.\",\n\t\t\tAction: \"View\",\n\t\t},\n\t\tURLArgs: []string{\"boarding\", \"A998\"},\n\t}\n\n\tb, err := json.Marshal(p)\n\tif err != nil {\n\t}\n\tfmt.Printf(\"%s\", b)\n}\n\n\n\nfunc TestValidBrowser(t *testing.T) {\n\tp := payload.Browser{\n\t\tAlert: payload.BrowserAlert{\n\t\t\tTitle: \"Flight A998 Now Boarding\",\n\t\t\tBody: \"Boarding has begun for Flight A998.\",\n\t\t},\n\t}\n\tif err := p.Validate(); err != nil {\n\t\tt.Errorf(\"Expected no error, got %v.\", err)\n\t}\n}\n\nfunc TestInvalidBrowser(t *testing.T) {\n\ttests := []*payload.Browser{\n\t\t{\n\t\t\tAlert: payload.BrowserAlert{Action: \"View\"},\n\t\t},\n\t\t{},\n\t\tnil,\n\t}\n\n\tfor _, p := range tests {\n\t\tif err := p.Validate(); err != payload.ErrIncomplete {\n\t\t\tt.Errorf(\"Expected err %v, got %v.\", payload.ErrIncomplete, err)\n\t\t}\n\t}\n}\n\nfunc TestBrowser(t *testing.T) ", "output": "{\n\tp := payload.Browser{\n\t\tAlert: payload.BrowserAlert{\n\t\t\tTitle: \"Flight A998 Now Boarding\",\n\t\t\tBody: \"Boarding has begun for Flight A998.\",\n\t\t\tAction: \"View\",\n\t\t},\n\t\tURLArgs: []string{\"boarding\", \"A998\"},\n\t}\n\texpected := []byte(`{\"aps\":{\"alert\":{\"title\":\"Flight A998 Now Boarding\",\"body\":\"Boarding has begun for Flight A998.\",\"action\":\"View\"},\"url-args\":[\"boarding\",\"A998\"]}}`)\n\ttestPayload(t, p, expected)\n}"} {"input": "package engine\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestJobOK(t *testing.T) {\n\teng := New()\n\teng.Register(\"return_ok\", func(job *Job) error { return nil })\n\terr := eng.Job(\"return_ok\").Run()\n\tif err != nil {\n\t\tt.Fatalf(\"Expected: err=%v\\nReceived: err=%v\", nil, err)\n\t}\n}\n\n\n\nfunc TestJobStdoutString(t *testing.T) {\n\teng := New()\n\teng.Register(\"say_something_in_stdout\", func(job *Job) error {\n\t\tjob.Printf(\"Hello world\\n\")\n\t\treturn nil\n\t})\n\n\tjob := eng.Job(\"say_something_in_stdout\")\n\tvar outputBuffer = bytes.NewBuffer(nil)\n\tjob.Stdout.Add(outputBuffer)\n\tif err := job.Run(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfmt.Println(outputBuffer)\n\tvar output = Tail(outputBuffer, 1)\n\tif expectedOutput := \"Hello world\"; output != expectedOutput {\n\t\tt.Fatalf(\"Stdout last line:\\nExpected: %v\\nReceived: %v\", expectedOutput, output)\n\t}\n}\n\nfunc TestJobErr(t *testing.T) ", "output": "{\n\teng := New()\n\teng.Register(\"return_err\", func(job *Job) error { return errors.New(\"return_err\") })\n\terr := eng.Job(\"return_err\").Run()\n\tif err == nil {\n\t\tt.Fatalf(\"When a job returns error, Run() should return an error\")\n\t}\n}"} {"input": "package restutil\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/eclipse/che/agents/go-agents/core/rest\"\n)\n\n\nfunc WriteJSON(w http.ResponseWriter, body interface{}) error {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\treturn json.NewEncoder(w).Encode(body)\n}\n\n\nfunc ReadJSON(r *http.Request, v interface{}) error {\n\treturn json.NewDecoder(r.Body).Decode(v)\n}\n\n\n\n\n\n\nfunc OKRespondingFunc(w http.ResponseWriter, r *http.Request, _ rest.Params) error {\n\tw.WriteHeader(http.StatusOK)\n\treturn nil\n}\n\nfunc IntQueryParam(r *http.Request, name string, defaultValue int) int ", "output": "{\n\tqp := r.URL.Query().Get(name)\n\tif qp == \"\" {\n\t\treturn defaultValue\n\t}\n\tv, err := strconv.Atoi(qp)\n\tif err != nil {\n\t\treturn defaultValue\n\t}\n\tif v < 0 {\n\t\treturn defaultValue\n\t}\n\treturn v\n}"} {"input": "package exec\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\tosexec \"os/exec\"\n\t\"strings\"\n\n\t\"github.com/zimmski/backup\"\n)\n\n\nfunc Combined(name string, args ...string) (string, error) {\n\tif backup.Verbose {\n\t\tfmt.Fprintln(os.Stderr, \"Execute: \", name, strings.Join(args, \" \"))\n\t}\n\n\tcmd := osexec.Command(name, args...)\n\n\tout, err := cmd.CombinedOutput()\n\n\treturn string(out), err\n}\n\n\n\n\n\nfunc Command(name string, args ...string) *osexec.Cmd {\n\tif backup.Verbose {\n\t\tfmt.Fprintln(os.Stderr, \"Execute: \", name, strings.Join(args, \" \"))\n\t}\n\n\treturn osexec.Command(name, args...)\n}\n\nfunc CombinedWithDirectOutput(name string, args ...string) (string, error) ", "output": "{\n\tif backup.Verbose {\n\t\tfmt.Fprintln(os.Stderr, \"Execute: \", name, strings.Join(args, \" \"))\n\t}\n\n\tcmd := osexec.Command(name, args...)\n\n\tvar buf bytes.Buffer\n\n\tout := io.MultiWriter(os.Stdout, &buf)\n\n\tcmd.Stderr = out\n\tcmd.Stdout = out\n\n\terr := cmd.Run()\n\n\treturn buf.String(), err\n}"} {"input": "package naming\n\nimport (\n\t\"github.com/snapcore/snapd/snapdenv\"\n)\n\nvar (\n\tprodWellKnownSnapIDs = map[string]string{\n\t\t\"core\": \"99T7MUlRhtI3U0QFgl5mXXESAiSwt776\",\n\t\t\"snapd\": \"PMrrV4ml8uWuEUDBT8dSGnKUYbevVhc4\",\n\t\t\"core18\": \"CSO04Jhav2yK0uz97cr0ipQRyqg0qQL6\",\n\t\t\"core20\": \"DLqre5XGLbDqg9jPtiAhRRjDuPVa5X1q\",\n\t}\n\n\tstagingWellKnownSnapIDs = map[string]string{\n\t\t\"core\": \"xMNMpEm0COPZy7jq9YRwWVLCD9q5peow\",\n\t\t\"snapd\": \"Z44rtQD1v4r1LXGPCDZAJO3AOw1EDGqy\",\n\t\t\"core18\": \"NhSvwckvNdvgdiVGlsO1vYmi3FPdTZ9U\",\n\t\t\"core20\": \"\",\n\t}\n)\n\nvar wellKnownSnapIDs = prodWellKnownSnapIDs\n\nfunc init() {\n\tif snapdenv.UseStagingStore() {\n\t\twellKnownSnapIDs = stagingWellKnownSnapIDs\n\t}\n}\n\n\n\nfunc WellKnownSnapID(snapName string) string {\n\treturn wellKnownSnapIDs[snapName]\n}\n\n\n\nfunc UseStagingIDs(staging bool) (restore func()) ", "output": "{\n\told := wellKnownSnapIDs\n\tif staging {\n\t\twellKnownSnapIDs = stagingWellKnownSnapIDs\n\t} else {\n\t\twellKnownSnapIDs = prodWellKnownSnapIDs\n\t}\n\treturn func() {\n\t\twellKnownSnapIDs = old\n\t}\n}"} {"input": "package dos\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n\n\n\n\nfunc ReplaceHomeToTilde(wd string) string {\n\thome := GetHome()\n\thomeLen := len(home)\n\tif len(wd) >= homeLen && strings.EqualFold(home, wd[0:homeLen]) {\n\t\twd = \"~\" + wd[homeLen:]\n\t}\n\treturn wd\n}\n\n\nfunc ReplaceHomeToTildeSlash(wd string) string {\n\treturn filepath.ToSlash(ReplaceHomeToTilde(wd))\n}\n\nfunc GetHome() string ", "output": "{\n\thome := os.Getenv(\"HOME\")\n\tif home == \"\" {\n\t\thome = os.Getenv(\"USERPROFILE\")\n\t}\n\treturn home\n}"} {"input": "package image\n\nimport (\n\t\"github.com/containers/image/types\"\n)\n\n\n\n\ntype imageCloser struct {\n\ttypes.Image\n\tsrc types.ImageSource\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc FromSource(ctx *types.SystemContext, src types.ImageSource) (types.ImageCloser, error) {\n\timg, err := FromUnparsedImage(ctx, UnparsedInstance(src, nil))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &imageCloser{\n\t\tImage: img,\n\t\tsrc: src,\n\t}, nil\n}\n\nfunc (ic *imageCloser) Close() error {\n\treturn ic.src.Close()\n}\n\n\n\n\n\n\ntype sourcedImage struct {\n\t*UnparsedImage\n\tmanifestBlob []byte\n\tmanifestMIMEType string\n\tgenericManifest\n}\n\n\n\n\n\n\nfunc FromUnparsedImage(ctx *types.SystemContext, unparsed *UnparsedImage) (types.Image, error) {\n\n\tmanifestBlob, manifestMIMEType, err := unparsed.Manifest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparsedManifest, err := manifestInstanceFromBlob(ctx, unparsed.src, manifestBlob, manifestMIMEType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &sourcedImage{\n\t\tUnparsedImage: unparsed,\n\t\tmanifestBlob: manifestBlob,\n\t\tmanifestMIMEType: manifestMIMEType,\n\t\tgenericManifest: parsedManifest,\n\t}, nil\n}\n\n\nfunc (i *sourcedImage) Size() (int64, error) {\n\treturn -1, nil\n}\n\n\n\n\nfunc (i *sourcedImage) Inspect() (*types.ImageInspectInfo, error) {\n\treturn inspectManifest(i.genericManifest)\n}\n\nfunc (i *sourcedImage) LayerInfosForCopy() []types.BlobInfo {\n\treturn i.UnparsedImage.LayerInfosForCopy()\n}\n\nfunc (i *sourcedImage) Manifest() ([]byte, string, error) ", "output": "{\n\treturn i.manifestBlob, i.manifestMIMEType, nil\n}"} {"input": "package github\n\nimport (\n . \"github.com/ErintLabs/trellohub/genapi\"\n \"log\"\n)\n\ntype Label struct {\n Name string `json:\"name\"`\n}\n\ntype GitUser struct {\n Name string `json:\"login\"`\n}\n\nfunc (issue *Issue) SetLabels(lbls []Label) {\n lst := make([]string, len(lbls))\n for i, v := range lbls {\n lst[i] = v.Name\n }\n issue.Labels.SetNameable(lst)\n}\n\nfunc (issue *Issue) SetMembers(mbmrs []GitUser) {\n lst := make([]string, len(mbmrs))\n for i, v := range mbmrs {\n lst[i] = v.Name\n }\n issue.Members.SetNameable(lst)\n}\n\n\n\n\nfunc (issue *Issue) AddLabel(label string) {\n log.Printf(\"Adding label %s to %s\", label, issue.String())\n lbls := [...]string { label }\n GenPOSTJSON(issue.github, issue.ApiURL() + \"/labels\", nil, &lbls)\n}\n\n\nfunc (issue *Issue) DelLabel(label string) {\n log.Printf(\"Removing label %s from %s\", label, issue.String())\n GenDEL(issue.github, issue.ApiURL() + \"/labels/\" + label) \n}\n\n\ntype userAssignRequest struct {\n Assigs []string `json:\"assignees\"`\n}\n\nfunc (issue *Issue) AddUser(user string) {\n log.Printf(\"Adding user %s to %s\", user, issue.String())\n payload := userAssignRequest{ []string{ user } }\n GenPOSTJSON(issue.github, issue.ApiURL() + \"/assignees\", nil, &payload)\n}\n\n\n\n\nfunc (issue *Issue) DelUser(user string) ", "output": "{\n log.Printf(\"Removing user %s from %s\", user, issue.String())\n payload := userAssignRequest{ []string{ user } }\n GenDELJSON(issue.github, issue.ApiURL() + \"/assignees\", &payload)\n}"} {"input": "package bridge\n\ntype setupStep func(*networkConfiguration, *bridgeInterface) error\n\ntype bridgeSetup struct {\n\tconfig *networkConfiguration\n\tbridge *bridgeInterface\n\tsteps []setupStep\n}\n\nfunc newBridgeSetup(c *networkConfiguration, i *bridgeInterface) *bridgeSetup {\n\treturn &bridgeSetup{config: c, bridge: i}\n}\n\n\n\nfunc (b *bridgeSetup) queueStep(step setupStep) {\n\tb.steps = append(b.steps, step)\n}\n\nfunc (b *bridgeSetup) apply() error ", "output": "{\n\tfor _, fn := range b.steps {\n\t\tif err := fn(b.config, b.bridge); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package container\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/martin-helmich/distcrond/domain\"\n)\n\ntype JobContainer struct {\n\tjobs []domain.Job\n\tjobsByName map[string]*domain.Job\n}\n\nfunc NewJobContainer(initialCapacity int) *JobContainer {\n\tcontainer := new(JobContainer)\n\tcontainer.jobs = make([]domain.Job, 0, initialCapacity)\n\tcontainer.jobsByName = make(map[string]*domain.Job)\n\treturn container\n}\n\nfunc (c *JobContainer) AddJob(job domain.Job) {\n\tc.jobs = append(c.jobs, job)\n\tc.jobsByName[job.Name] = &c.jobs[len(c.jobs)-1]\n}\n\nfunc (c *JobContainer) Count() int {\n\treturn len(c.jobs)\n}\n\nfunc (c *JobContainer) All() []domain.Job {\n\treturn c.jobs\n}\n\n\n\nfunc (c *JobContainer) JobByName(n string) (*domain.Job, error) {\n\tif job, ok := c.jobsByName[n]; !ok {\n\t\treturn nil, errors.New(fmt.Sprintf(\"No job with name '%s' is known\", n))\n\t} else {\n\t\treturn job, nil\n\t}\n}\n\nfunc (c *JobContainer) Get(i int) *domain.Job ", "output": "{\n\treturn &c.jobs[i]\n}"} {"input": "package graph\n\nimport (\n\t\"github.com/filwisher/algo/set\"\n)\n\ntype Graph struct {\n\tEdges map[int] *set.Set\n}\n\nfunc NewGraph() Graph {\n\treturn Graph{\n\t\tEdges: make(map[int] *set.Set),\n\t}\n}\n\n\n\nfunc (g *Graph) AddEdge(u, v int) {\n\tg.addSingleEdge(u, v)\n\tg.addSingleEdge(v, u)\n}\n\nfunc (g *Graph) Adjacent(u int) <-chan int {\n\tch := make(chan int)\n\tgo func() {\n\t\tif set, ok := g.Edges[u]; ok {\n\t\t\tfor e := range set.Each() {\n\t\t\t\tch <- e.(int)\n\t\t\t}\t\n\t\t\tclose(ch)\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc (g *Graph) addSingleEdge(u, v int) ", "output": "{\n\tif _, ok := g.Edges[u]; !ok {\n\t\tg.Edges[u] = set.NewSet()\n\t}\n\tg.Edges[u].Add(v)\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n)\n\n\n\nfunc ForceHTTPS(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\turl := r.URL\n\t\tif !isHTTPS(r) {\n\t\t\turl.Scheme = \"https\"\n\t\t\turl.Host = r.Host\n\t\t\thttp.Redirect(w, r, url.String(), http.StatusMovedPermanently)\n\t\t\treturn\n\t\t}\n\n\t\th.ServeHTTP(w, r)\n\t})\n}\n\nfunc isHTTPS(r *http.Request) bool ", "output": "{\n\tif r.URL.Scheme == \"https\" {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(r.Proto, \"HTTPS\") {\n\t\treturn true\n\t}\n\tif r.Header.Get(\"X-Forwarded-Proto\") == \"https\" {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package main\n\nimport (\n\t\"github.com/trasa/watchmud-message\"\n)\n\nfunc (c *Client) handleSayResponse(resp *message.SayResponse) {\n\tif resp.Success {\n\t\tUIPrintf(\"You say '%s'\\n\", resp.Value)\n\t} else {\n\t\tif resp.GetResultCode() == \"NOT_IN_A_ROOM\" {\n\t\t\tUIPrintln(\"You yell into the darkness.\")\n\t\t} else {\n\t\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t\t}\n\t}\n}\n\nfunc (c *Client) handleSayNotification(note *message.SayNotification) {\n\tif note.Success {\n\t\tUIPrintf(\"%s says '%s'.\\n\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellNotification(note *message.TellNotification) {\n\tif note.GetSuccess() {\n\t\tUIPrintf(\"%s tells you '%s'.\\n\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}\n\n\n\nfunc (c *Client) handleTellAllResponse(resp *message.TellAllResponse) {\n\tif resp.GetSuccess() {\n\t\tUIPrintln(\"sent.\")\n\t} else {\n\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellAllNotification(note *message.TellAllNotification) {\n\tif note.GetSuccess() {\n\t\tUIPrintf(\"tell_all %s> %s\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellResponse(resp *message.TellResponse) ", "output": "{\n\tif resp.GetSuccess() {\n\t\tUIPrintln(\"sent.\")\n\t} else if resp.GetResultCode() == \"TO_PLAYER_NOT_FOUND\" {\n\t\tUIPrintln(\"Nobody here by that name.\")\n\t} else {\n\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t}\n}"} {"input": "package cli\n\nimport \"errors\"\nimport \"fmt\"\nimport \"strconv\"\n\nfunc IsArgExist(args []string, s string)(bool) {\n pos, err := getArgPos(args, s)\n if nil == err && pos > 0 {\n return true\n }\n\n return false\n}\n\n\n\nfunc GetArgInt(args []string, s string)(int, error) {\n \n pos, err := getArgPos(args, s)\n if nil != err || pos <= 0{\n return pos, err\n }\n\n \n if pos + 1 >= len(args) {\n return 0, errors.New(fmt.Sprintf(\"no number fallows '%s'\", s))\n }\n\n \n a := args[pos + 1]\n if regd == true && On != RegArgsStat(a) {\n return 0, errors.New(fmt.Sprintf(\"no number fallows '%s'\", s))\n }\n\n return strconv.Atoi(a)\n}\n\nfunc GetArgInts(args []string, s string)([]int, error) {\n pos, err := getArgPos(args, s)\n if err != nil || pos <= 0{\n return nil, err\n }\n if pos + 1 >= len(args) {\n return nil, errors.New(fmt.Sprintf(\"no number fllows '%s'\", s))\n }\n var list []int\n for i := pos + 1; i < len(args); i++ {\n if On == argmp[args[i]] {\n break\n }\n n, err := strconv.Atoi(args[i])\n if nil == err {\n list = append(list, n)\n } else {\n break\n }\n }\n if len(list) < 1 {\n return nil, errors.New(fmt.Sprintf(\"no number fllows '%s'\", s))\n }\n\n return list, nil\n}\n\nfunc GetArgBool(args []string, s string)(bool) ", "output": "{\n pos, err := getArgPos(args, s)\n if nil == err && pos > 0 {\n return true\n }\n\n return false\n}"} {"input": "package esbuilder\n\nimport \"github.com/serulian/compiler/sourcemap\"\n\n\ntype StatementBuilder interface {\n\tWithMapping(mapping sourcemap.SourceMapping) SourceBuilder\n\n\tmapping() (sourcemap.SourceMapping, bool)\n\n\temitSource(sb *sourceBuilder)\n}\n\n\ntype statementNode interface {\n\temit(sb *sourceBuilder)\n}\n\n\ntype statementBuilder struct {\n\tstatement statementNode\n\n\tsourceMapping *sourcemap.SourceMapping\n}\n\nfunc (builder statementBuilder) mapping() (sourcemap.SourceMapping, bool) {\n\tif builder.sourceMapping == nil {\n\t\treturn sourcemap.SourceMapping{}, false\n\t}\n\n\treturn *builder.sourceMapping, true\n}\n\nfunc (builder statementBuilder) emitSource(sb *sourceBuilder) {\n\tbuilder.statement.emit(sb)\n}\n\n\n\n\nfunc (builder statementBuilder) WithMapping(mapping sourcemap.SourceMapping) SourceBuilder ", "output": "{\n\tbuilder.sourceMapping = &mapping\n\treturn builder\n}"} {"input": "package utils\n\nimport (\n\t\"path/filepath\"\n\n\tv32 \"github.com/rancher/rancher/pkg/apis/project.cattle.io/v3\"\n\tv3 \"github.com/rancher/rancher/pkg/generated/norman/project.cattle.io/v3\"\n)\n\nfunc MatchAll(cs *v32.Constraints, execution *v3.PipelineExecution) bool {\n\tif cs == nil {\n\t\treturn true\n\t}\n\n\tm := GetEnvVarMap(execution)\n\n\treturn Match(cs.Branch, m[EnvGitBranch]) &&\n\t\tMatch(cs.Event, m[EnvEvent])\n}\n\nfunc Match(c *v32.Constraint, v string) bool {\n\tif c == nil {\n\t\treturn true\n\t}\n\n\tif Excludes(c, v) {\n\t\treturn false\n\t}\n\tif Includes(c, v) {\n\t\treturn true\n\t}\n\tif len(c.Include) == 0 {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\nfunc Includes(c *v32.Constraint, v string) bool {\n\tfor _, pattern := range c.Include {\n\t\tif ok, _ := filepath.Match(pattern, v); ok {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\nfunc Excludes(c *v32.Constraint, v string) bool ", "output": "{\n\tfor _, pattern := range c.Exclude {\n\t\tif ok, _ := filepath.Match(pattern, v); ok {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package system \n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\n\n\nfunc KillProcess(pid int) {\n\tunix.Kill(pid, unix.SIGKILL)\n}\n\n\n\nfunc IsProcessZombie(pid int) (bool, error) {\n\tstatPath := fmt.Sprintf(\"/proc/%d/stat\", pid)\n\tdataBytes, err := ioutil.ReadFile(statPath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdata := string(dataBytes)\n\tsdata := strings.SplitN(data, \" \", 4)\n\tif len(sdata) >= 3 && sdata[2] == \"Z\" {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc IsProcessAlive(pid int) bool ", "output": "{\n\terr := unix.Kill(pid, syscall.Signal(0))\n\tif err == nil || err == unix.EPERM {\n\t\treturn true\n\t}\n\n\treturn false\n}"} {"input": "package bce\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n\ntype Response struct {\n\tBodyContent []byte\n\t*http.Response\n}\n\n\n\n\nfunc (res *Response) GetBodyContent() ([]byte, error) {\n\tif res.BodyContent == nil {\n\t\tdefer func() {\n\t\t\tif res.Response != nil {\n\t\t\t\tres.Body.Close()\n\t\t\t}\n\t\t}()\n\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tres.BodyContent = body\n\t}\n\n\treturn res.BodyContent, nil\n}\n\nfunc NewResponse(res *http.Response) *Response ", "output": "{\n\treturn &Response{Response: res}\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestIsBlank(t *testing.T) {\n\tif !IsBlank(\"\") {\n\t\tt.FailNow()\n\t}\n\n\tif !IsBlank(`\n\t`) {\n\t\tt.FailNow()\n\t}\n\n}\n\n\n\nfunc TestHashPassword(t *testing.T) ", "output": "{\n\tfmt.Println(HashAndSalt(\"123456\", \"245accec-3c12-4642-967f-e476cef558c0\"))\n}"} {"input": "package google\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/hashicorp/terraform/helper/schema\"\n)\n\nfunc dataSourceGoogleServiceAccount() *schema.Resource {\n\treturn &schema.Resource{\n\t\tRead: dataSourceGoogleServiceAccountRead,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"account_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tValidateFunc: validateRFC1035Name(6, 30),\n\t\t\t},\n\t\t\t\"project\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"email\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"unique_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"name\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"display_name\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\n\n\nfunc dataSourceGoogleServiceAccountRead(d *schema.ResourceData, meta interface{}) error ", "output": "{\n\tconfig := meta.(*Config)\n\n\tserviceAccountName, err := serviceAccountFQN(d.Get(\"account_id\").(string), d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsa, err := config.clientIAM.Projects.ServiceAccounts.Get(serviceAccountName).Do()\n\tif err != nil {\n\t\treturn handleNotFoundError(err, d, fmt.Sprintf(\"Service Account %q\", serviceAccountName))\n\t}\n\n\td.SetId(sa.Name)\n\td.Set(\"email\", sa.Email)\n\td.Set(\"unique_id\", sa.UniqueId)\n\td.Set(\"project\", sa.ProjectId)\n\td.Set(\"account_id\", strings.Split(sa.Email, \"@\")[0])\n\td.Set(\"name\", sa.Name)\n\td.Set(\"display_name\", sa.DisplayName)\n\n\treturn nil\n}"} {"input": "package datatypes\n\ntype Time int64\n\ntype StreamName string\n\ntype Event struct {\n Time Time;\n Payload EvPayload\n}\n\ntype EvPayload struct {\n IsSet bool;\n Val interface{}\n}\n\ntype MaybeTime struct {\n IsSet bool;\n Val Time\n}\n\n\n\nvar NothingTime MaybeTime = MaybeTime{false, -100}\n\nfunc Some(val interface{}) EvPayload {\n return EvPayload{true, val}\n}\n\nvar NothingPayload EvPayload = EvPayload{false, nil}\n\ntype EpsVal struct {\n Eps Time\n Val interface{}\n}\n\ntype OutStream struct {\n Name StreamName\n TicksDef TickerNode\n ValDef ValNode\n}\n\ntype InStream struct {\n Name StreamName\n StreamDef InStreamDef\n}\n\ntype InStreamDef interface {\n PeekNextTime() MaybeTime\n Exec(t Time) EvPayload\n}\n\ntype FlowingEvent struct {\n Name StreamName\n Event Event\n}\n\nfunc SomeTime(val Time) MaybeTime ", "output": "{\n return MaybeTime{true, val}\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\ntype ChangeBootVolumeCompartmentDetails struct {\n\n\tCompartmentId *string `mandatory:\"true\" json:\"compartmentId\"`\n}\n\n\n\nfunc (m ChangeBootVolumeCompartmentDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package metrics\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\ntype GaugeMetric struct {\n\tvalue float64\n\tmutex sync.RWMutex\n}\n\nfunc (metric *GaugeMetric) Humanize() string {\n\tformatString := \"[GaugeMetric; value=%f]\"\n\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn fmt.Sprintf(formatString, metric.value)\n}\n\nfunc (metric *GaugeMetric) Set(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value = value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) IncrementBy(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value += value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Increment() float64 {\n\treturn metric.IncrementBy(1)\n}\n\nfunc (metric *GaugeMetric) DecrementBy(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value -= value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Decrement() float64 {\n\treturn metric.DecrementBy(1)\n}\n\nfunc (metric *GaugeMetric) Get() float64 {\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn metric.value\n}\n\n\n\nfunc (metric *GaugeMetric) Marshallable() map[string]interface{} ", "output": "{\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\tv := make(map[string]interface{}, 2)\n\n\tv[valueKey] = metric.value\n\tv[typeKey] = gaugeTypeValue\n\n\treturn v\n}"} {"input": "package schedule\n\nimport (\n\t\"context\"\n\t\"os\"\n)\n\nfunc (c *Client) GetOnCalls(context context.Context, request *GetOnCallsRequest) (*GetOnCallsResult, error) {\n\tresult := &GetOnCallsResult{}\n\terr := c.client.Exec(context, request, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}\n\n\n\nfunc (c *Client) ExportOnCallUser(context context.Context, request *ExportOnCallUserRequest) (*os.File, error) {\n\tresult := &exportOncallUserResult{}\n\n\tfile, err := os.Create(request.ExportedFilePath + request.getFileName())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer file.Close()\n\n\terr = c.client.Exec(context, request, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = file.Write(result.FileContent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn file, nil\n}\n\nfunc (c *Client) GetNextOnCall(context context.Context, request *GetNextOnCallsRequest) (*GetNextOnCallsResult, error) ", "output": "{\n\tresult := &GetNextOnCallsResult{}\n\terr := c.client.Exec(context, request, result)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"bufio\"\n\t\"os\"\n)\n\ntype Node struct {\n\tdata interface{}\n\tnext *Node\n}\n\nvar lengthOfStack = 0\nvar top *Node\n\nfunc main() {\n\tscanner := bufio.NewScanner(os.Stdin)\n\n\tfor true {\n\t\tfmt.Println(\"Select one of the following options:\")\n\t\tfmt.Println(\"1. Push\")\n\t\tfmt.Println(\"2. Pop\")\n\t\tfmt.Println(\"3. Length of stack\")\n\t\tfmt.Println(\"4. Exit\")\n\n\t\tscanner.Scan()\n\t\tfmt.Println(\"\")\n\t\tswitch scanner.Text() {\n\t\t\tcase \"1\":\n\t\t\t\tpush(scanner)\n\t\t\tcase \"2\":\n\t\t\t\tpop()\n\n\t\t\tcase \"3\":\n\t\t\t\tfmt.Println(\"The length of the stack is:\", lengthOfStack)\n\t\t\t\tfmt.Println(\"\")\t\n\t\t\tcase \"4\":\n\t\t\t\tos.Exit(0)\n\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Please, select a valid option.\")\n\t\t}\n\t}\n}\n\n\n\nfunc pop() {\n\tif(top == nil) {\n\t\tfmt.Println(\"Empty stack\")\n\t\tfmt.Println(\"\")\t\t\n\t\treturn\n\t}\n\n\tfmt.Println(\"Element to pop:\", top.data)\n\tfmt.Println(\"\")\t\n\n\ttop = top.next\n\n\tlengthOfStack -= 1\n}\n\nfunc push(scanner *bufio.Scanner) ", "output": "{\n\tfmt.Println(\"Type the number you want to push into the stack\")\n\tscanner.Scan()\n\tfmt.Println(\"\")\t\n\n\tlengthOfStack += 1\n\tif(top == nil) {\n\t\ttop = &Node{scanner.Text(), nil}\n\t\treturn\n\t}\n\n\tnewNode := &Node{scanner.Text(), top}\n\ttop = newNode\n}"} {"input": "package v1\n\nimport (\n\t\"gopkg.in/guregu/null.v3\"\n\n\t\"go.k6.io/k6/core\"\n\t\"go.k6.io/k6/lib\"\n)\n\ntype Status struct {\n\tStatus lib.ExecutionStatus `json:\"status\" yaml:\"status\"`\n\n\tPaused null.Bool `json:\"paused\" yaml:\"paused\"`\n\tVUs null.Int `json:\"vus\" yaml:\"vus\"`\n\tVUsMax null.Int `json:\"vus-max\" yaml:\"vus-max\"`\n\tStopped bool `json:\"stopped\" yaml:\"stopped\"`\n\tRunning bool `json:\"running\" yaml:\"running\"`\n\tTainted bool `json:\"tainted\" yaml:\"tainted\"`\n}\n\n\n\nfunc (s Status) GetName() string {\n\treturn \"status\"\n}\n\nfunc (s Status) GetID() string {\n\treturn \"default\"\n}\n\nfunc (s Status) SetID(id string) error {\n\treturn nil\n}\n\nfunc NewStatus(engine *core.Engine) Status ", "output": "{\n\texecutionState := engine.ExecutionScheduler.GetState()\n\treturn Status{\n\t\tStatus: executionState.GetCurrentExecutionStatus(),\n\t\tRunning: executionState.HasStarted() && !executionState.HasEnded(),\n\t\tPaused: null.BoolFrom(executionState.IsPaused()),\n\t\tStopped: engine.IsStopped(),\n\t\tVUs: null.IntFrom(executionState.GetCurrentlyActiveVUsCount()),\n\t\tVUsMax: null.IntFrom(executionState.GetInitializedVUsCount()),\n\t\tTainted: engine.IsTainted(),\n\t}\n}"} {"input": "package texas\n\ntype SeatResultList []*SeatResult\n\ntype SeatResult struct {\n\tm_seat *SeatPlayer\n\tpot_idx int\n\tcard_type int\n\tcard_list CardDataList\n}\n\nfunc NewSeatResult(seat *SeatPlayer, cards []int16) *SeatResult {\n\tthis := new(SeatResult)\n\tthis.m_seat = seat\n\tthis.pot_idx = seat.m_pot_point\n\tthis.card_type, this.card_list = CardTypeOfTexas(cards)\n\treturn this\n}\n\nfunc (this *SeatResult) Trace() {\n\tprintln(\"玩家:\", this.m_seat.m_seat_id, POKER_TYPE_STR[this.card_type], TraceBigCards(this.card_list))\n}\n\n\nfunc (this SeatResultList) Len() int {\n\treturn len(this)\n}\n\n\nfunc (this SeatResultList) Less(i, j int) bool {\n\treturn this[i].card_type > this[j].card_type\n}\n\n\n\nfunc (this SeatResultList) Swap(i, j int) ", "output": "{\n\ttemp := this[i]\n\tthis[i] = this[j]\n\tthis[j] = temp\n}"} {"input": "package bst\n\nimport (\n\t\"math\"\n\n\t\"github.com/catorpilor/leetcode/utils\"\n)\n\nfunc IsValidBST(root *utils.TreeNode) bool {\n\treturn helper(root, math.MinInt64, math.MaxInt64)\n\n}\n\n\n\nfunc helper(node *utils.TreeNode, min, max int) bool ", "output": "{\n\tif node == nil {\n\t\treturn true\n\t}\n\tif node.Val <= min || node.Val >= max {\n\t\treturn false\n\t}\n\treturn helper(node.Left, min, node.Val) && helper(node.Right, node.Val, max)\n}"} {"input": "package systray\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\nfunc nativeLoop() {\n\tC.nativeLoop()\n}\n\nfunc quit() {\n\tC.quit()\n}\n\n\n\n\n\n\n\nfunc SetTitle(title string) {\n\tC.setTitle(C.CString(title))\n}\n\n\n\nfunc SetTooltip(tooltip string) {\n\tC.setTooltip(C.CString(tooltip))\n}\n\nfunc addOrUpdateMenuItem(item *MenuItem) {\n\tvar disabled C.short = 0\n\tif item.disabled {\n\t\tdisabled = 1\n\t}\n\tvar checked C.short = 0\n\tif item.checked {\n\t\tchecked = 1\n\t}\n\tC.add_or_update_menu_item(\n\n\t\tC.int(item.id),\n\t\tC.CString(item.title),\n\t\tC.CString(item.tooltip),\n\t\tdisabled,\n\t\tchecked,\n\t)\n}\n\n\nfunc systray_ready() {\n\tsystrayReady()\n}\n\n\nfunc systray_menu_item_selected(cId C.int) {\n\tsystrayMenuItemSelected(int32(cId))\n}\n\nfunc SetIcon(iconBytes []byte) ", "output": "{\n\tcstr := (*C.char)(unsafe.Pointer(&iconBytes[0]))\n\tC.setIcon(cstr, (C.int)(len(iconBytes)))\n}"} {"input": "package rpcclientpool\n\nimport (\n\tgonet \"net\"\n\tgorpc \"net/rpc\"\n\n\t\"github.com/Cloud-Foundations/Dominator/lib/connpool\"\n\t\"github.com/Cloud-Foundations/Dominator/lib/net\"\n\t\"github.com/Cloud-Foundations/Dominator/lib/net/rpc\"\n)\n\nvar (\n\tdefaultDialer = &gonet.Dialer{}\n)\n\n\n\nfunc (cr *ClientResource) get(cancelChannel <-chan struct{}) (*Client, error) {\n\tif err := cr.resource.Get(cancelChannel); err != nil {\n\t\treturn nil, err\n\t}\n\tcr.client.rpcClient = cr.rpcClient\n\treturn cr.client, nil\n}\n\nfunc (pcr *privateClientResource) Allocate() error {\n\tcr := pcr.clientResource\n\tvar rpcClient *gorpc.Client\n\tvar err error\n\tif cr.http {\n\t\trpcClient, err = rpc.DialHTTPPath(\n\t\t\tcr.dialer, cr.network, cr.address, cr.path)\n\t} else {\n\t\trpcClient, err = rpc.Dial(cr.dialer, cr.network, cr.address)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient := &Client{resource: cr}\n\tcr.client = client\n\tcr.rpcClient = rpcClient\n\treturn nil\n}\n\nfunc (pcr *privateClientResource) Release() error {\n\tcr := pcr.clientResource\n\terr := cr.client.rpcClient.Close()\n\tcr.client.rpcClient = nil\n\tcr.client = nil\n\treturn err\n}\n\nfunc (client *Client) close() error {\n\treturn client.resource.resource.Release()\n}\n\nfunc (client *Client) put() {\n\tclient.rpcClient = nil\n\tclient.resource.resource.Put()\n}\n\nfunc newClientResource(network, address string, http bool,\n\tpath string, dialer net.Dialer) *ClientResource ", "output": "{\n\tif path == \"\" {\n\t\tpath = gorpc.DefaultRPCPath\n\t}\n\tclientResource := &ClientResource{\n\t\tnetwork: network,\n\t\taddress: address,\n\t\thttp: http,\n\t\tpath: path,\n\t\tdialer: dialer,\n\t}\n\tclientResource.privateClientResource.clientResource = clientResource\n\trp := connpool.GetResourcePool()\n\tclientResource.resource = rp.Create(&clientResource.privateClientResource)\n\treturn clientResource\n}"} {"input": "package main\n\ntype set struct {\n\tels map[string]interface{}\n}\n\n\n\nfunc (s *set) add(element string) {\n\ts.els[element] = nil\n}\n\nfunc (s *set) elements() []string {\n\tels := make([]string, len(s.els))\n\n\ti := 0\n\tfor k := range s.els {\n\t\tels[i] = k\n\t\ti++\n\t}\n\treturn els\n}\n\nfunc newSet() *set ", "output": "{\n\treturn &set{\n\t\tels: map[string]interface{}{},\n\t}\n}"} {"input": "package crdt\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/mediocregopher/radix.v2/redis\"\n\t\"log\"\n)\n\nvar redisPort int\nvar zset string\nvar client *redis.Client\nvar err error\n\nfunc Add(value int, elemName string) string {\n\tresp := client.Cmd(fmt.Sprintf(\"ZADD\"), zset, value, elemName)\n\tif resp.Err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Command failed: %s\\n\", resp.Err))\n\t} else {\n\t\tfmt.Printf(\"%s\\n\", resp.String())\n\t}\n\treturn resp.String()\n}\n\nfunc Remove(value int, elemName string) string {\n\tresp := client.Cmd(fmt.Sprintf(\"ZREM\"), zset, value, elemName)\n\tif resp.Err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Command failed: %s\\n\", resp.Err))\n\t} else {\n\t\tfmt.Printf(\"%s\\n\", resp.String())\n\t}\n\treturn resp.String()\n}\n\nfunc PrintAll(minValue int, maxValue int, constraints string) string {\n\tresp := client.Cmd(fmt.Sprintf(\"ZRANGE\"), zset, minValue, maxValue, constraints)\n\tif resp.Err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Command failed: %s\\n\", resp.Err))\n\t} else {\n\t\tfmt.Printf(\"%s\\n\", resp.String())\n\t}\n\n\treturn resp.String()\n}\n\n\n\nfunc main() {\n\tflag.Parse()\n\n\tcheckInput()\n}\n\nfunc checkInput() ", "output": "{\n\tif redisPort == 0 {\n\t\tlog.Fatal(\"Please specify the port at which the redis server is running using --port option.\")\n\t} else if zset == \"\" {\n\t\tlog.Fatal(\"Please specify the name of the ZSET to store using the --zset option.\")\n\t}\n}"} {"input": "package commands\n\nimport (\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/fatih/color\"\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/golangci/golangci-lint/pkg/lint/linter\"\n)\n\n\n\nfunc (e *Executor) executeLinters(_ *cobra.Command, args []string) {\n\tif len(args) != 0 {\n\t\te.log.Fatalf(\"Usage: golangci-lint linters\")\n\t}\n\n\tenabledLintersMap, err := e.EnabledLintersSet.GetEnabledLintersMap()\n\tif err != nil {\n\t\tlog.Fatalf(\"Can't get enabled linters: %s\", err)\n\t}\n\n\tcolor.Green(\"Enabled by your configuration linters:\\n\")\n\tenabledLinters := make([]*linter.Config, 0, len(enabledLintersMap))\n\tfor _, linter := range enabledLintersMap {\n\t\tenabledLinters = append(enabledLinters, linter)\n\t}\n\tprintLinterConfigs(enabledLinters)\n\n\tvar disabledLCs []*linter.Config\n\tfor _, lc := range e.DBManager.GetAllSupportedLinterConfigs() {\n\t\tif enabledLintersMap[lc.Name()] == nil {\n\t\t\tdisabledLCs = append(disabledLCs, lc)\n\t\t}\n\t}\n\n\tcolor.Red(\"\\nDisabled by your configuration linters:\\n\")\n\tprintLinterConfigs(disabledLCs)\n\n\tos.Exit(0)\n}\n\nfunc (e *Executor) initLinters() ", "output": "{\n\te.lintersCmd = &cobra.Command{\n\t\tUse: \"linters\",\n\t\tShort: \"List current linters configuration\",\n\t\tRun: e.executeLinters,\n\t}\n\te.rootCmd.AddCommand(e.lintersCmd)\n\te.initRunConfiguration(e.lintersCmd)\n}"} {"input": "package glw\n\nimport \"golang.org/x/mobile/gl\"\n\ntype A2fv gl.Attrib\n\nfunc (a A2fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A2fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A2fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 2, gl.FLOAT, false, 0, 0)\n}\n\ntype A3fv gl.Attrib\n\nfunc (a A3fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\n\nfunc (a A3fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 3, gl.FLOAT, false, 0, 0)\n}\n\ntype A4fv gl.Attrib\n\nfunc (a A4fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A4fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A4fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 4, gl.FLOAT, false, 0, 0)\n}\n\nfunc (a A3fv) Disable() ", "output": "{ ctx.DisableVertexAttribArray(gl.Attrib(a)) }"} {"input": "package remote\n\nimport (\n\t\"errors\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\nfunc NewOutputInterceptor() OutputInterceptor {\n\treturn &outputInterceptor{}\n}\n\ntype outputInterceptor struct {\n\tredirectFile *os.File\n\tintercepting bool\n}\n\nfunc (interceptor *outputInterceptor) StartInterceptingOutput() error {\n\tif interceptor.intercepting {\n\t\treturn errors.New(\"Already intercepting output!\")\n\t}\n\tinterceptor.intercepting = true\n\n\tvar err error\n\n\tinterceptor.redirectFile, err = ioutil.TempFile(\"\", \"ginkgo-output\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsyscallDup(int(interceptor.redirectFile.Fd()), 1)\n\tsyscallDup(int(interceptor.redirectFile.Fd()), 2)\n\n\treturn nil\n}\n\n\n\nfunc (interceptor *outputInterceptor) StopInterceptingAndReturnOutput() (string, error) ", "output": "{\n\tif !interceptor.intercepting {\n\t\treturn \"\", errors.New(\"Not intercepting output!\")\n\t}\n\n\tinterceptor.redirectFile.Close()\n\toutput, err := ioutil.ReadFile(interceptor.redirectFile.Name())\n\tos.Remove(interceptor.redirectFile.Name())\n\n\tinterceptor.intercepting = false\n\n\treturn string(output), err\n}"} {"input": "package bindata\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"regexp\"\n)\n\n\ntype InputConfig struct {\n\tPath string\n\n\tRecursive bool\n}\n\n\ntype Config struct {\n\tPackage string\n\n\tTags string\n\n\tInput []InputConfig\n\n\tOutput string\n\n\tPrefix string\n\n\tNoMemCopy bool\n\n\tNoCompress bool\n\n\tDebug bool\n\n\tDev bool\n\n\tNoMetadata bool\n\tMode uint\n\tModTime int64\n\n\tIgnore []*regexp.Regexp\n}\n\n\n\n\n\n\nfunc (c *Config) validate() error {\n\tif len(c.Package) == 0 {\n\t\treturn fmt.Errorf(\"missing package name\")\n\t}\n\n\tfor _, input := range c.Input {\n\t\t_, err := os.Lstat(input.Path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to stat input path '%s': %v\", input.Path, err)\n\t\t}\n\t}\n\n\tif len(c.Output) == 0 {\n\t\tcwd, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to determine current working directory\")\n\t\t}\n\n\t\tc.Output = filepath.Join(cwd, \"bindata.go\")\n\t}\n\n\tstat, err := os.Lstat(c.Output)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn fmt.Errorf(\"output path: %v\", err)\n\t\t}\n\n\t\tdir, _ := filepath.Split(c.Output)\n\t\tif dir != \"\" {\n\t\t\terr = os.MkdirAll(dir, 0744)\n\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"create output directory: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif stat != nil && stat.IsDir() {\n\t\treturn fmt.Errorf(\"output path %q is a directory\", c.Output)\n\t}\n\n\treturn nil\n}\n\nfunc NewConfig() *Config ", "output": "{\n\tc := new(Config)\n\tc.Package = \"main\"\n\tc.NoMemCopy = false\n\tc.NoCompress = false\n\tc.Debug = false\n\tc.Output = \"./bindata.go\"\n\tc.Ignore = make([]*regexp.Regexp, 0)\n\treturn c\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"runtime\"\n\t\"time\"\n)\n\nfunc main() {\n\n\n\tsida1 := \"1 1 1 \\n1 1 1\\n1 1 1\\n\"\n\tsida2 := \"2 2 2 \\n2 2 2\\n2 2 2\\n\"\n\tsida3 := \"3 3 3 \\n3 3 3\\n3 3 3\\n\"\n\tsida4 := \"4 4 4 \\n4 4 4\\n4 4 4\\n\"\n\n\n\tCallClear()\n\tfmt.Printf(sida1)\n\tCallClear()\n\tfmt.Printf(sida2)\n\tCallClear()\n\tfmt.Printf(sida3)\n\tCallClear()\n\tfmt.Printf(sida4)\n\tCallClear()\n\n}\n\nvar clear map[string]func() \n\nfunc init() {\n\tclear = make(map[string]func()) \n\n\tclear[\"linux\"] = func() {\n\t\ttime.Sleep(1 * time.Second)\n\t\tcmd := exec.Command(\"clear\") \n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Run()\n\t}\n}\n\n\n\nfunc CallClear() ", "output": "{\n\tvalue, ok := clear[runtime.GOOS] \n\tif ok { \n\t\tvalue() \n\t} else { \n\t\tpanic(\"Your platform is unsupported! I can't clear terminal screen :(\")\n\t}\n}"} {"input": "package goodhosts\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestItemInSlice(t *testing.T) ", "output": "{\n\titem := \"this\"\n\tlist := []string{\"hello\", \"brah\"}\n\tresult := itemInSlice(\"goodbye\", list)\n\tif result {\n\t\tt.Error(fmt.Sprintf(\"'%' should not have been found in slice.\", item))\n\t}\n\n\titem = \"hello\"\n\tresult = itemInSlice(item, list)\n\tif !result {\n\t\tt.Error(fmt.Sprintf(\"'%' should have been found in slice.\", item))\n\t}\n}"} {"input": "package sortedmap\n\nimport (\n\t\"testing\"\n\n\t\"github.com/umpc/go-sortedmap/asc\"\n)\n\nfunc insertRecord(b *testing.B) {\n\trecords := randRecords(1)\n\tsm := New(0, asc.Time)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsm.Insert(records[0].Key, records[0].Val)\n\n\t\tb.StopTimer()\n\t\trecords = randRecords(1)\n\t\tsm = New(0, asc.Time)\n\t\tb.StartTimer()\n\t}\n}\n\nfunc batchInsertRecords(b *testing.B, n int) {\n\trecords := randRecords(n)\n\tsm := New(0, asc.Time)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsm.BatchInsert(records)\n\n\t\tb.StopTimer()\n\t\trecords = randRecords(n)\n\t\tsm = New(0, asc.Time)\n\t\tb.StartTimer()\n\t}\n}\n\nfunc BenchmarkInsert1Record(b *testing.B) {\n\tinsertRecord(b)\n}\n\n\n\nfunc BenchmarkBatchInsert100Records(b *testing.B) {\n\tbatchInsertRecords(b, 100)\n}\n\nfunc BenchmarkBatchInsert1000Records(b *testing.B) {\n\tbatchInsertRecords(b, 1000)\n}\n\nfunc BenchmarkBatchInsert10000Records(b *testing.B) {\n\tbatchInsertRecords(b, 10000)\n}\n\nfunc BenchmarkBatchInsert10Records(b *testing.B) ", "output": "{\n\tbatchInsertRecords(b, 10)\n}"} {"input": "package restful\n\nimport (\n\t\"github.com/Cepave/open-falcon-backend/common/gin/mvc\"\n\t\"github.com/Cepave/open-falcon-backend/common/model\"\n\n\tdbOwl \"github.com/Cepave/open-falcon-backend/common/db/owl\"\n)\n\n\n\nfunc getGroupTagById(\n\tp *struct {\n\t\tGroupTagId int32 `mvc:\"param[group_tag_id]\"`\n\t},\n) mvc.OutputBody {\n\treturn mvc.JsonOutputOrNotFound(\n\t\tdbOwl.GetGroupTagById(p.GroupTagId),\n\t)\n}\n\nfunc listGroupTags(\n\tp *struct {\n\t\tName string `mvc:\"query[name]\"`\n\t\tPaging *model.Paging `mvc:\"pageSize[100] pageOrderBy[name#asc]\"`\n\t},\n) (*model.Paging, mvc.OutputBody) ", "output": "{\n\treturn p.Paging,\n\t\tmvc.JsonOutputBody(\n\t\t\tdbOwl.ListGroupTags(p.Name, p.Paging),\n\t\t)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype helloTransport interface {\n\tConnect(addr string) error\n\tClose() error\n\tRequest(req string) (reply string, err error)\n}\n\ntype transGenerator func() (helloTransport, error)\n\nvar transporter map[string]transGenerator = make(map[string]transGenerator)\n\nfunc registerTransport(id string, gen transGenerator) {\n\ttransporter[id] = gen\n}\n\n\n\nfunc availableTransports() string {\n\tvar transports = transportList()\n\treturn strings.Join(transports, \",\")\n}\n\nfunc firstTransport() string {\n\tvar transports = transportList()\n\treturn transports[0]\n}\n\nfunc defaultAddr(addr string) string {\n\treturn fmt.Sprintf(\"%s://%s\", firstTransport(), addr)\n}\n\nfunc newTransport(addr string) (helloTransport, error) {\n\tvar uri, err = url.Parse(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif generate, ok := transporter[uri.Scheme]; ok {\n\t\treturn generate()\n\t}\n\treturn nil, fmt.Errorf(\"invalid transport %q\", uri.Scheme)\n}\n\nfunc transportList() []string ", "output": "{\n\tvar transports = make([]string, 0, len(transporter))\n\tfor id := range transporter {\n\t\ttransports = append(transports, id)\n\t}\n\tsort.StringSlice(transports).Sort()\n\treturn transports\n}"} {"input": "package testclient\n\nimport (\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/fields\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/labels\"\n\n\tauthorizationapi \"github.com/openshift/origin/pkg/authorization/api\"\n)\n\n\n\ntype FakeClusterRoles struct {\n\tFake *Fake\n}\n\nfunc (c *FakeClusterRoles) List(label labels.Selector, field fields.Selector) (*authorizationapi.ClusterRoleList, error) {\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"list-clusterRoles\"}, &authorizationapi.ClusterRoleList{})\n\treturn obj.(*authorizationapi.ClusterRoleList), err\n}\n\nfunc (c *FakeClusterRoles) Get(name string) (*authorizationapi.ClusterRole, error) {\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"get-clusterRole\"}, &authorizationapi.ClusterRole{})\n\treturn obj.(*authorizationapi.ClusterRole), err\n}\n\nfunc (c *FakeClusterRoles) Create(role *authorizationapi.ClusterRole) (*authorizationapi.ClusterRole, error) {\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"create-clusterRole\", Value: role}, &authorizationapi.ClusterRole{})\n\treturn obj.(*authorizationapi.ClusterRole), err\n}\n\n\n\nfunc (c *FakeClusterRoles) Delete(name string) error {\n\tc.Fake.Actions = append(c.Fake.Actions, FakeAction{Action: \"delete-clusterRole\", Value: name})\n\treturn nil\n}\n\nfunc (c *FakeClusterRoles) Update(role *authorizationapi.ClusterRole) (*authorizationapi.ClusterRole, error) ", "output": "{\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"update-clusterRole\"}, &authorizationapi.ClusterRole{})\n\treturn obj.(*authorizationapi.ClusterRole), err\n}"} {"input": "package gumble\n\nimport (\n\t\"net\"\n\t\"time\"\n\n\t\"github.com/golang/protobuf/proto\"\n\t\"github.com/layeh/gumble/gumble/MumbleProto\"\n)\n\n\n\n\n\ntype BanList []*Ban\n\n\nfunc (bl *BanList) Add(address net.IP, mask net.IPMask, reason string, duration time.Duration) *Ban {\n\tban := &Ban{\n\t\tAddress: address,\n\t\tMask: mask,\n\t\tReason: reason,\n\t\tDuration: duration,\n\t}\n\t*bl = append(*bl, ban)\n\treturn ban\n}\n\n\n\n\n\ntype Ban struct {\n\tAddress net.IP\n\tMask net.IPMask\n\tName string\n\tHash string\n\tReason string\n\tStart time.Time\n\tDuration time.Duration\n\n\tunban bool\n}\n\n\nfunc (b *Ban) SetAddress(address net.IP) {\n\tb.Address = address\n}\n\n\nfunc (b *Ban) SetMask(mask net.IPMask) {\n\tb.Mask = mask\n}\n\n\nfunc (b *Ban) SetReason(reason string) {\n\tb.Reason = reason\n}\n\n\nfunc (b *Ban) SetDuration(duration time.Duration) {\n\tb.Duration = duration\n}\n\n\nfunc (b *Ban) Unban() {\n\tb.unban = true\n}\n\n\n\nfunc (b *Ban) Ban() {\n\tb.unban = false\n}\n\n\n\nfunc (bl BanList) writeMessage(client *Client) error ", "output": "{\n\tpacket := MumbleProto.BanList{\n\t\tQuery: proto.Bool(false),\n\t}\n\n\tfor _, ban := range bl {\n\t\tif !ban.unban {\n\t\t\tmaskSize, _ := ban.Mask.Size()\n\t\t\tpacket.Bans = append(packet.Bans, &MumbleProto.BanList_BanEntry{\n\t\t\t\tAddress: ban.Address,\n\t\t\t\tMask: proto.Uint32(uint32(maskSize)),\n\t\t\t\tReason: &ban.Reason,\n\t\t\t\tDuration: proto.Uint32(uint32(ban.Duration / time.Second)),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn client.Conn.WriteProto(&packet)\n}"} {"input": "package routing\n\nimport \"net/http\"\n\n\nfunc Method(method string, handler http.Handler) Matcher {\n\treturn func(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\t\tif req.Method == method {\n\t\t\thandler.ServeHTTP(resp, req)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}\n\n\nfunc GET(handler http.Handler) Matcher {\n\treturn Method(\"GET\", handler)\n}\n\n\nfunc GETFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn GET(http.HandlerFunc(handler))\n}\n\n\nfunc POST(handler http.Handler) Matcher {\n\treturn Method(\"POST\", handler)\n}\n\n\nfunc POSTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn POST(http.HandlerFunc(handler))\n}\n\n\nfunc PUT(handler http.Handler) Matcher {\n\treturn Method(\"PUT\", handler)\n}\n\n\nfunc PUTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PUT(http.HandlerFunc(handler))\n}\n\n\nfunc PATCH(handler http.Handler) Matcher {\n\treturn Method(\"PATCH\", handler)\n}\n\n\n\n\n\nfunc DELETE(handler http.Handler) Matcher {\n\treturn Method(\"DELETE\", handler)\n}\n\n\nfunc DELETEFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn DELETE(http.HandlerFunc(handler))\n}\n\n\n\nfunc MethodNotAllowed(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\tresp.WriteHeader(405)\n\treturn true\n}\n\nfunc PATCHFunc(handler func(http.ResponseWriter, *http.Request)) Matcher ", "output": "{\n\treturn PATCH(http.HandlerFunc(handler))\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realSecurityGroupRule SecurityGroupRule\n\nfunc (o *SecurityGroupRule) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realSecurityGroupRule\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = SecurityGroupRule(r)\n\treturn nil\n}\n\nvar _ fi.HasName = &SecurityGroupRule{}\n\nfunc (e *SecurityGroupRule) GetName() *string {\n\treturn e.Name\n}\n\nfunc (e *SecurityGroupRule) SetName(name string) {\n\te.Name = &name\n}\n\n\n\nfunc (e *SecurityGroupRule) String() string ", "output": "{\n\treturn fi.TaskAsString(e)\n}"} {"input": "package common\n\nimport (\n\t\"encoding/binary\"\n\t\"sort\"\n)\n\n\n\ntype Uint64Slice []uint64\n\nfunc (p Uint64Slice) Len() int { return len(p) }\nfunc (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] }\nfunc (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p Uint64Slice) Sort() { sort.Sort(p) }\n\nfunc SearchUint64s(a []uint64, x uint64) int {\n\treturn sort.Search(len(a), func(i int) bool { return a[i] >= x })\n}\n\nfunc (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) }\n\n\n\nfunc PutUint64LE(dest []byte, i uint64) {\n\tbinary.LittleEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64LE(src []byte) uint64 {\n\treturn binary.LittleEndian.Uint64(src)\n}\n\n\n\nfunc GetUint64BE(src []byte) uint64 {\n\treturn binary.BigEndian.Uint64(src)\n}\n\nfunc PutInt64LE(dest []byte, i int64) {\n\tbinary.LittleEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64LE(src []byte) int64 {\n\treturn int64(binary.LittleEndian.Uint64(src))\n}\n\nfunc PutInt64BE(dest []byte, i int64) {\n\tbinary.BigEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64BE(src []byte) int64 {\n\treturn int64(binary.BigEndian.Uint64(src))\n}\n\nfunc PutUint64BE(dest []byte, i uint64) ", "output": "{\n\tbinary.BigEndian.PutUint64(dest, i)\n}"} {"input": "package influxdbclient\n\nimport \"github.com/influxdata/influxdb1-client/v2\"\nimport \"time\"\nimport \"encoding/json\"\n\n\n\n\n\ntype DataSet struct {\n\tName string\n\tTimeStamps []time.Time\n\tTags map[string]string\n\tDatas map[string][]float64\n}\n\n\n\n\n\nfunc ConvertToDataSet(res []client.Result) (dsets []*DataSet) {\n\tif len(res[0].Series) == 0 {\n\t\treturn\n\t}\n\n\tfor _, serie := range res[0].Series {\n\t\tds := NewDataSet(len(serie.Values), serie.Columns[1:])\n\n\t\tds.Name = serie.Name\n\t\tds.Tags = serie.Tags\n\t\tfor i, row := range serie.Values {\n\n\t\t\tt, _ := time.Parse(time.RFC3339, row[0].(string))\n\n\t\t\tds.TimeStamps[i] = t\n\n\t\t\tfor j, field := range row {\n\t\t\t\tif j == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tfieldname := serie.Columns[j]\n\t\t\t\tif field != nil {\n\t\t\t\t\tval, _ := field.(json.Number).Float64()\n\t\t\t\t\tds.Datas[fieldname][i] = val\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdsets = append(dsets, ds)\n\t}\n\treturn\n}\n\nfunc NewDataSet(length int, fields []string) *DataSet ", "output": "{\n\tds := DataSet{TimeStamps: make([]time.Time, length), Datas: make(map[string][]float64)}\n\n\tfor _, fieldname := range fields {\n\t\tds.Datas[fieldname] = make([]float64, length)\n\t}\n\treturn &ds\n}"} {"input": "package blocks\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\tmh \"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash\"\n\tu \"github.com/ipfs/go-ipfs/util\"\n)\n\n\ntype Block struct {\n\tMultihash mh.Multihash\n\tData []byte\n}\n\n\n\n\n\n\n\nfunc NewBlockWithHash(data []byte, h mh.Multihash) (*Block, error) {\n\tif u.Debug {\n\t\tchk := u.Hash(data)\n\t\tif string(chk) != string(h) {\n\t\t\treturn nil, errors.New(\"Data did not match given hash!\")\n\t\t}\n\t}\n\treturn &Block{Data: data, Multihash: h}, nil\n}\n\n\nfunc (b *Block) Key() u.Key {\n\treturn u.Key(b.Multihash)\n}\n\nfunc (b *Block) String() string {\n\treturn fmt.Sprintf(\"[Block %s]\", b.Key())\n}\n\nfunc (b *Block) Loggable() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"block\": b.Key().String(),\n\t}\n}\n\nfunc NewBlock(data []byte) *Block ", "output": "{\n\treturn &Block{Data: data, Multihash: u.Hash(data)}\n}"} {"input": "package main\n\nimport \"sort\"\nimport \"fmt\"\n\ntype ByLength []string\n\nfunc (s ByLength) Len() int {\n\treturn len(s)\n}\n\nfunc (s ByLength) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\n\n\nfunc main() {\n\tfruits := []string{\"peach\", \"banana\",\"kiwi\"}\n\tsort.Sort(ByLength(fruits))\n\tfmt.Println(fruits)\n}\n\nfunc (s ByLength) Less(i, j int) bool ", "output": "{\n\treturn len(s[i]) < len(s[j])\n}"} {"input": "package payments\n\nimport (\n \"net/http\"\n \"github.com/upwork/golang-upwork/api\"\n)\n\nconst (\n EntryPoint = \"api\"\n)\n\ntype a struct {\n client api.ApiClient\n}\n\n\nfunc New(c api.ApiClient) (a) {\n var r a\n c.SetEntryPoint(EntryPoint)\n r.client = c\n\n return r\n}\n\n\n\n\nfunc (r a) SubmitBonus(teamReference string, params map[string]string) (*http.Response, []byte) ", "output": "{\n return r.client.Post(\"/hr/v2/teams/\" + teamReference + \"/adjustments\", params)\n}"} {"input": "package bunyan\n\nimport \"fmt\"\n\n\ntype Logger struct {\n\tsink Sink\n\trecord Record\n}\n\n\nfunc NewLogger(target Sink) *Logger {\n\treturn &Logger{target, NewRecord()}\n}\n\n\n\nfunc (l *Logger) Write(record Record) error {\n\trecord.TemplateMerge(l.record)\n\treturn l.sink.Write(record)\n}\n\n\n\nfunc (l *Logger) Include(info Info) Log {\n\treturn NewLogger(InfoSink(l, info))\n}\n\n\n\nfunc (l *Logger) Record(key string, value interface{}) Log {\n\tbuilder := NewLogger(l)\n\tbuilder.record[key] = value\n\treturn builder\n}\n\n\n\nfunc (l *Logger) Recordf(key, value string, args ...interface{}) Log {\n\treturn l.Record(key, fmt.Sprintf(value, args...))\n}\n\n\n\nfunc (l *Logger) Child() Log {\n\treturn NewLogger(l)\n}\n\nfunc (l *Logger) Tracef(msg string, args ...interface{}) { l.send(TRACE, msg, args...) }\nfunc (l *Logger) Debugf(msg string, args ...interface{}) { l.send(DEBUG, msg, args...) }\nfunc (l *Logger) Infof(msg string, args ...interface{}) { l.send(INFO, msg, args...) }\nfunc (l *Logger) Warnf(msg string, args ...interface{}) { l.send(WARN, msg, args...) }\n\nfunc (l *Logger) Fatalf(msg string, args ...interface{}) { l.send(FATAL, msg, args...) }\n\nfunc (l *Logger) send(level Level, msg string, args ...interface{}) {\n\trecord := NewRecord()\n\trecord.SetMessagef(level, msg, args...)\n\te := l.Write(record)\n\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc (l *Logger) Errorf(msg string, args ...interface{}) ", "output": "{ l.send(ERROR, msg, args...) }"} {"input": "package main\n\nimport (\n\t\"os\"\n\n\t\"github.com/olekukonko/tablewriter\"\n)\n\ntype tblWriter struct {\n\t*tablewriter.Table\n}\n\n\n\nfunc (table *tblWriter) WriteData(header []string, data [][]string) error {\n\ttable.SetHeader(header)\n\ttable.AppendBulk(data)\n\ttable.Render()\n\treturn nil\n}\n\nfunc NewTableWriter() *tblWriter ", "output": "{\n\treturn &tblWriter{tablewriter.NewWriter(os.Stdout)}\n}"} {"input": "package pump\n\nimport (\n\t\"math\"\n\n\t\"github.com/tidepool-org/platform/data\"\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tBolusAmountMaximumUnitsUnits = \"Units\"\n\tBolusAmountMaximumValueUnitsMaximum = 100.0\n\tBolusAmountMaximumValueUnitsMinimum = 0.0\n)\n\n\n\ntype BolusAmountMaximum struct {\n\tUnits *string `json:\"units,omitempty\" bson:\"units,omitempty\"`\n\tValue *float64 `json:\"value,omitempty\" bson:\"value,omitempty\"`\n}\n\nfunc ParseBolusAmountMaximum(parser structure.ObjectParser) *BolusAmountMaximum {\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewBolusAmountMaximum()\n\tparser.Parse(datum)\n\treturn datum\n}\n\nfunc NewBolusAmountMaximum() *BolusAmountMaximum {\n\treturn &BolusAmountMaximum{}\n}\n\nfunc (b *BolusAmountMaximum) Parse(parser structure.ObjectParser) {\n\tb.Units = parser.String(\"units\")\n\tb.Value = parser.Float64(\"value\")\n}\n\nfunc (b *BolusAmountMaximum) Validate(validator structure.Validator) {\n\tvalidator.String(\"units\", b.Units).Exists().OneOf(BolusAmountMaximumUnits()...)\n\tvalidator.Float64(\"value\", b.Value).Exists().InRange(BolusAmountMaximumValueRangeForUnits(b.Units))\n}\n\nfunc (b *BolusAmountMaximum) Normalize(normalizer data.Normalizer) {}\n\nfunc BolusAmountMaximumValueRangeForUnits(units *string) (float64, float64) {\n\tif units != nil {\n\t\tswitch *units {\n\t\tcase BolusAmountMaximumUnitsUnits:\n\t\t\treturn BolusAmountMaximumValueUnitsMinimum, BolusAmountMaximumValueUnitsMaximum\n\t\t}\n\t}\n\treturn -math.MaxFloat64, math.MaxFloat64\n}\n\nfunc BolusAmountMaximumUnits() []string ", "output": "{\n\treturn []string{\n\t\tBolusAmountMaximumUnitsUnits,\n\t}\n}"} {"input": "package jsonutil\n\nimport (\n\t\"github.com/buger/jsonparser\"\n\t\"strconv\"\n)\n\nfunc GetString(data []byte, keys ...string) (string, error) {\n\treturn jsonparser.GetString(data, keys...)\n}\n\nfunc MustGetString(data []byte, keys ...string) string {\n\ts, err := GetString(data, keys...)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s\n}\n\nfunc GetFloat(data []byte, keys ...string) (float64, error) {\n\treturn jsonparser.GetFloat(data, keys...)\n}\n\n\n\nfunc GetInt(data []byte, keys ...string) (int64, error) {\n\treturn jsonparser.GetInt(data, keys...)\n}\n\nfunc MustGetInt(data []byte, keys ...string) int64 {\n\ti, err := GetInt(data, keys...)\n\tif err != nil {\n\t\tif s := MustGetString(data, keys...); len(s) == 0 {\n\t\t\treturn 0\n\t\t} else if i, err = strconv.ParseInt(s, 10, 64); err != nil {\n\t\t\treturn 0\n\t\t}\n\t}\n\treturn i\n}\n\nfunc GetBoolean(data []byte, keys ...string) (bool, error) {\n\treturn jsonparser.GetBoolean(data, keys...)\n}\n\nfunc MustGetBoolean(data []byte, keys ...string) bool {\n\tb, err := GetBoolean(data, keys...)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn b\n}\n\nfunc MustGetFloat(data []byte, keys ...string) float64 ", "output": "{\n\tf, err := GetFloat(data, keys...)\n\tif err != nil {\n\t\treturn 0.0\n\t}\n\treturn f\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/user\"\n)\n\nfunc main() {\n\tstartServer()\n}\n\nfunc isRoot() bool {\n\tusr, _ := user.Current()\n\treturn usr.Uid == \"0\"\n}\n\n\n\nfunc findPort(ssl bool) string {\n\tport := os.Getenv(\"PORT\")\n\tif len(port) == 0 {\n\t\tuser := !isRoot()\n\t\tif ssl {\n\t\t\tif user {\n\t\t\t\tport = \"4443\"\n\t\t\t} else {\n\t\t\t\tport = \"443\"\n\t\t\t}\n\t\t} else {\n\t\t\tif user {\n\t\t\t\tport = \"8080\"\n\t\t\t} else {\n\t\t\t\tport = \"80\"\n\t\t\t}\n\t\t}\n\t}\n\n\treturn port\n}\n\nfunc startServer() {\n\tcertFile := \"certs/server.pem\"\n\tkeyFile := \"certs/server.key\"\n\tssl := certsExists(certFile, keyFile)\n\tport := findPort(ssl)\n\trouter := NewRouter()\n\n\tlog.Printf(\"start listening on port %s\", port)\n\n\tvar err error\n\tif ssl {\n\t\terr = http.ListenAndServeTLS(\":\"+port, certFile, keyFile, router)\n\t} else {\n\t\terr = http.ListenAndServe(\":\"+port, router)\n\t}\n\n\tlog.Fatal(err)\n}\n\nfunc certsExists(certFile string, keyFile string) bool ", "output": "{\n\tfor _, file := range []string{certFile, keyFile} {\n\t\t_, err := os.Stat(file)\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}"} {"input": "package learn\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc unknownTypeErr(a interface{}) error {\n\treturn fmt.Errorf(\"learn: type of \\\"%v\\\" must be float or string not %T\", a, a)\n}\n\n\nfunc typeMismatchErr(a, b interface{}) error ", "output": "{\n\treturn fmt.Errorf(\"learn: type mismatch in features \\\"v\\\" \\\"v\\\"\\n\", a, b)\n}"} {"input": "package file\n\nimport \"github.com/sandreas/graft/designpattern/observer\"\n\ntype WalkObserver struct {\n\tdesignpattern.ObserverInterface\n\titemCount int64\n\tmatchCount int64\n\terrorCount int64\n\tforceShow bool\n\toutputCallback func(format string, a ...interface{}) (int, error)\n\tInterval int64\n}\n\nfunc NewWalkObserver(handle func(format string, a ...interface{}) (int, error)) *WalkObserver {\n\treturn &WalkObserver{\n\t\tInterval: 100,\n\t\toutputCallback: handle,\n\t}\n}\n\n\n\nfunc (ph *WalkObserver) showProgress() {\n\tif !ph.forceShow && ph.itemCount%ph.Interval != 0 {\n\t\treturn\n\t}\n\n\tif ph.errorCount == 0 {\n\t\tph.outputCallback(\"\\rscanning - total: %d, matches: %d\", ph.itemCount, ph.matchCount)\n\t} else {\n\t\tph.outputCallback(\"\\rscanning - total: %d, matches: %d, errors: %d\", ph.itemCount, ph.matchCount, ph.errorCount)\n\t}\n\n\tif ph.itemCount > ph.Interval*10 {\n\t\tph.Interval = 500\n\t}\n}\n\nfunc (ph *WalkObserver) Notify(a ...interface{}) ", "output": "{\n\tif a[0] == LocatorIncreaseItems {\n\t\tph.forceShow = ph.itemCount == 0\n\t\tph.itemCount++\n\t}\n\n\tif a[0] == LocatorIncreaseErrors {\n\t\tph.forceShow = ph.errorCount == 0\n\t\tph.errorCount++\n\t}\n\n\tif a[0] == LocatorIncreaseMatches {\n\t\tph.forceShow = ph.matchCount == 0\n\t\tph.itemCount++\n\t\tph.matchCount++\n\t}\n\n\tif a[0] == LocatorFinish {\n\t\tph.forceShow = true\n\t}\n\n\tph.showProgress()\n\n\tif a[0] == LocatorFinish {\n\t\tph.outputCallback(\"\\n\")\n\t}\n}"} {"input": "package solution\n\nimport (\n\t\"github.com/containerum/chkit/pkg/model\"\n\t\"gopkg.in/yaml.v2\"\n)\n\nvar (\n\t_ model.YAMLrenderer = SolutionEnv{}\n)\n\n\n\nfunc (envs SolutionEnv) RenderYAML() (string, error) ", "output": "{\n\tdata, err := yaml.Marshal(envs)\n\treturn string(data), err\n}"} {"input": "package dbtest\n\nimport (\n\t\"fmt\"\n\t\"github.com/muesli/cache2go\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar cachegoclient *cache2go.CacheTable\n\n\n\nfunc BenchmarkBSet(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tkey := fmt.Sprintf(\"key%v\", i)\n\t\tvalue := fmt.Sprintf(\"value%v\", i)\n\t\tcachegoclient.Add(key, 5*time.Minute, value)\n\t}\n}\n\nfunc BenchmarkBGet(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tkey := fmt.Sprintf(\"key%v\", i)\n\t\tcachegoclient.Value(key)\n\t}\n}\n\nfunc init() ", "output": "{\n\tcachegoclient = cache2go.Cache(\"mycache\")\n}"} {"input": "package appclient\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"github.com/weaveworks/scope/report\"\n)\n\n\n\ntype ReportPublisher struct {\n\tpublisher Publisher\n\tnoControls bool\n}\n\n\n\n\n\nfunc (p *ReportPublisher) Publish(r report.Report) error {\n\tif p.noControls {\n\t\tr.WalkTopologies(func(t *report.Topology) {\n\t\t\tt.Controls = report.Controls{}\n\t\t})\n\t}\n\tbuf := &bytes.Buffer{}\n\tr.WriteBinary(buf, gzip.DefaultCompression)\n\treturn p.publisher.Publish(buf, r.Shortcut)\n}\n\nfunc NewReportPublisher(publisher Publisher, noControls bool) *ReportPublisher ", "output": "{\n\treturn &ReportPublisher{\n\t\tpublisher: publisher,\n\t\tnoControls: noControls,\n\t}\n}"} {"input": "package native\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\n\t\"github.com/docker/docker/pkg/reexec\"\n\t\"github.com/docker/libcontainer\"\n)\n\nfunc init() {\n\treexec.Register(DriverName, initializer)\n}\n\n\n\nfunc initializer() {\n\truntime.GOMAXPROCS(1)\n\truntime.LockOSThread()\n\tfactory, err := libcontainer.New(\"\")\n\tif err != nil {\n\t\tfatal(err)\n\t}\n\tif err := factory.StartInitialization(); err != nil {\n\t\tfatal(err)\n\t}\n\n\tpanic(\"unreachable\")\n}\n\nfunc writeError(err error) {\n\tfmt.Fprint(os.Stderr, err)\n\tos.Exit(1)\n}\n\nfunc fatal(err error) ", "output": "{\n\tif lerr, ok := err.(libcontainer.Error); ok {\n\t\tlerr.Detail(os.Stderr)\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Fprintln(os.Stderr, err)\n\tos.Exit(1)\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/signal\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n)\n\ntype threadSafePrintliner struct {\n\tl sync.Mutex\n\tw io.Writer\n}\n\nfunc newThreadSafePrintliner(w io.Writer) *threadSafePrintliner {\n\treturn &threadSafePrintliner{w: w}\n}\n\nfunc (p *threadSafePrintliner) println(s string) {\n\tp.l.Lock()\n\tfmt.Fprintln(p.w, s)\n\tp.l.Unlock()\n}\n\nfunc readQuery(r io.Reader) string {\n\ts, _ := ioutil.ReadAll(r) \n\treturn strings.TrimSpace(strings.Replace(string(s), \"\\n\", \" \", -1))\n}\n\nfunc trimEmpty(s []string) []string {\n\tvar r = make([]string, 0)\n\tfor _, str := range s {\n\t\tif str != \"\" {\n\t\t\tr = append(r, str)\n\t\t}\n\t}\n\treturn r\n}\n\n\n\nfunc awaitSignal(cancel context.CancelFunc) ", "output": "{\n\tsignals := make(chan os.Signal)\n\tsignal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)\n\t<-signals\n\tcancel()\n}"} {"input": "package ora\n\nimport \"github.com/rainycape/dl\"\n\nvar (\n\tociLibrary = NewLazyDLL(\"libclntsh.so\")\n)\n\n\ntype Library struct {\n\tdll *dl.DL\n}\n\n\nfunc NewLazyDLL(name string) (dll *Library) {\n\tdll = new(Library)\n\tvar err error\n\tif dll.dll, err = dl.Open(name, dl.RTLD_LAZY); err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}\n\n\nfunc (lib *Library) NewProc(name string) *LibraryProc {\n\tcallee := new(LibraryProc)\n\tcallee.err = lib.dll.Sym(name, &callee.fn)\n\treturn callee\n}\n\n\ntype LibraryProc struct {\n\terr error\n\tfn func(...uintptr) uintptr\n}\n\n\n\n\nfunc (lib LibraryProc) Call(args ...uintptr) (r1 uintptr, r2 uintptr, err error) ", "output": "{\n\terr = lib.err\n\tr1 = lib.fn(args...)\n\treturn\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetServiceRequest struct {\n\n\tServiceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"serviceId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetServiceRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request GetServiceRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request GetServiceRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype GetServiceResponse struct {\n\n\tRawResponse *http.Response\n\n\tService `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetServiceResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetServiceResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetServiceRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package subject\n\nimport (\n\t\"testing\"\n\t\"reflect\"\n)\n\n\n\nfunc TestLoadSubject_LoadError(t *testing.T) {\n\tpath := \"/path/to/nowhere.csv\"\n\n\tres, err := LoadSubject(path)\n\n\tif !(res == nil && err != nil) {\n\t\tt.Errorf(\"Failed to raise error properly. result: %s, error: %s\", res, err)\n\t}\n}\n\nfunc TestLoadSubject_ParseError(t *testing.T) {\n\tpath := \"/tmp/\"\n\n\tres, err := LoadSubject(path)\n\n\tif !(res == nil && err != nil) {\n\t\tt.Errorf(\"Failed to raise error properly. result: %s, error: %s\", res, err)\n\t}\n}\n\nfunc TestLoadSubject(t *testing.T) ", "output": "{\n\tpath := \"../../example/subject.csv\"\n\texpect := [][]string{{\"A01\", \"Shibuya Rin\", \"100\"}, {\"A02\", \"\", \"200\"}}\n\n\tres, err := LoadSubject(path)\n\n\tif !(reflect.DeepEqual(res, expect) && err == nil) {\n\t\tt.Errorf(\"Failed to load and parse csv. result: %s, error: %s\", res, err)\n\t}\n}"} {"input": "package network\n\nimport (\n\tspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n)\n\n\n\ntype none struct {\n}\n\nfunc (h *none) New() (Namespace, error) {\n\treturn &noneNS{}, nil\n}\n\ntype noneNS struct {\n}\n\nfunc (h *noneNS) Set(s *specs.Spec) {\n}\n\nfunc (h *noneNS) Close() error {\n\treturn nil\n}\n\nfunc NewNoneProvider() Provider ", "output": "{\n\treturn &none{}\n}"} {"input": "package aws\n\nimport (\n\t\"github.com/emc-advanced-dev/unik/pkg/providers/common\"\n\t\"github.com/emc-advanced-dev/unik/pkg/types\"\n)\n\n\n\nfunc (p *AwsProvider) GetImage(nameOrIdPrefix string) (*types.Image, error) ", "output": "{\n\treturn common.GetImage(p, nameOrIdPrefix)\n}"} {"input": "package bridge\n\nimport \"github.com/docker/libnetwork/iptables\"\n\n\n\nfunc (n *bridgeNetwork) setupFirewalld(config *networkConfiguration, i *bridgeInterface) error ", "output": "{\n\tif config.EnableIPTables == false {\n\t\treturn IPTableCfgError(config.BridgeName)\n\t}\n\n\tiptables.OnReloaded(func() { n.setupIPTables(config, i) })\n\tiptables.OnReloaded(n.portMapper.ReMapAll)\n\n\treturn nil\n}"} {"input": "package sarama\n\n\ntype ApiVersionsRequest struct{}\n\nfunc (a *ApiVersionsRequest) encode(pe packetEncoder) error {\n\treturn nil\n}\n\n\n\nfunc (a *ApiVersionsRequest) key() int16 {\n\treturn 18\n}\n\nfunc (a *ApiVersionsRequest) version() int16 {\n\treturn 0\n}\n\nfunc (a *ApiVersionsRequest) headerVersion() int16 {\n\treturn 1\n}\n\nfunc (a *ApiVersionsRequest) requiredVersion() KafkaVersion {\n\treturn V0_10_0_0\n}\n\nfunc (a *ApiVersionsRequest) decode(pd packetDecoder, version int16) (err error) ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n)\n\ntype Config struct {\n\tCloudflare Cloudflare\n\tRecords []Record\n}\n\ntype Cloudflare struct {\n\tToken string\n\tEmail string\n\tDomain string\n}\n\ntype Record struct {\n\tZone string\n\tCnames []string\n}\n\n\n\nfunc initConfig() Config ", "output": "{\n\tvar config Config\n\tcdata, err := ioutil.ReadFile(\"config.json\")\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: %s\\n\", err.Error())\n\t\treturn Config{}\n\t}\n\n\terr = json.Unmarshal(cdata, &config)\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: %s\\n\", err.Error())\n\t\treturn Config{}\n\t}\n\n\treturn config\n}"} {"input": "package main\n\ntype Element struct {\n\tValue interface{}\n\tnext *Element\n}\n\ntype List struct {\n\te Element\n\tsize int\n}\n\n\nfunc New() *List {\n\tl := new(List)\n l.e.next = &l.e\n l.size = 0\n\treturn l\n}\n\nfunc (l *List) Add(e, at *Element) *Element {\n l.e.Value == at.Value\n}\n\nfunc (l *List) Remove() *Element {\n\n}\n\n\n\nfunc main() {\n}\n\nfunc (l *List) Size() int ", "output": "{\n\treturn l.size\n}"} {"input": "package sut\n\n\n\n\nfunc NewDefault() SystemUnderTest ", "output": "{\n\treturn NewBrokerAndTriggers()\n}"} {"input": "package stats\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/kubernetes/pkg/volume\"\n)\n\ntype fakeLogMetrics struct {\n\tfakeStats map[string]*volume.Metrics\n}\n\nfunc NewFakeLogMetricsService(stats map[string]*volume.Metrics) LogMetricsService {\n\treturn &fakeLogMetrics{fakeStats: stats}\n}\n\nfunc (l *fakeLogMetrics) createLogMetricsProvider(path string) volume.MetricsProvider {\n\treturn NewFakeMetricsDu(path, l.fakeStats[path])\n}\n\ntype fakeMetricsDu struct {\n\tfakeStats *volume.Metrics\n}\n\nfunc NewFakeMetricsDu(path string, stats *volume.Metrics) volume.MetricsProvider {\n\treturn &fakeMetricsDu{fakeStats: stats}\n}\n\n\n\nfunc (f *fakeMetricsDu) GetMetrics() (*volume.Metrics, error) ", "output": "{\n\tif f.fakeStats == nil {\n\t\treturn nil, fmt.Errorf(\"no stats provided\")\n\t}\n\treturn f.fakeStats, nil\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestSemverParse(t *testing.T) ", "output": "{\n\tvar versionsTest = []struct {\n\t\tversionInput string\n\t\texpected string\n\t}{\n\t\t{\"1.0\", \"1.0.0\"},\n\t\t{\"1.0.0\", \"1.0.0\"},\n\t\t{\"17.12.0-ce\", \"17.12.0-ce\"},\n\t}\n\tfor _, versionTest := range versionsTest {\n\t\tv, err := semverParse(versionTest.versionInput)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Cannot parse %s: %v\", versionTest.versionInput, err)\n\t\t}\n\t\tif v.String() != versionTest.expected {\n\t\t\tt.Errorf(\"want %s, got %s\", versionTest.expected, v)\n\t\t}\n\t}\n\n}"} {"input": "package configparser\n\nimport (\n\t\"github.com/bigkevmcd/go-configparser/chainmap\"\n\n\t\"strings\"\n)\n\nfunc (p *ConfigParser) getInterpolated(section, option string, c *chainmap.ChainMap) (string, error) {\n\tval, err := p.Get(section, option)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn p.interpolate(val, c), nil\n}\n\n\n\n\n\nfunc (p *ConfigParser) GetInterpolated(section, option string) (string, error) {\n\to, err := p.Items(section)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tc := chainmap.New(chainmap.Dict(p.Defaults()), chainmap.Dict(o))\n\treturn p.getInterpolated(section, option, c)\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (p *ConfigParser) interpolate(value string, options *chainmap.ChainMap) string {\n\n\tfor i := 0; i < maxInterpolationDepth; i++ {\n\t\tif strings.Contains(value, \"%(\") {\n\t\t\tvalue = interpolater.ReplaceAllStringFunc(value, func(m string) string {\n\t\t\t\tmatch := interpolater.FindAllStringSubmatch(m, 1)[0][1]\n\t\t\t\treplacement := options.Get(match)\n\t\t\t\treturn replacement\n\t\t\t})\n\t\t}\n\t}\n\treturn value\n}\n\n\nfunc (p *ConfigParser) ItemsWithDefaultsInterpolated(section string) (Dict, error) {\n\ts, err := p.ItemsWithDefaults(section)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range s {\n\t\tv, err = p.GetInterpolated(section, k)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts[k] = v\n\t}\n\treturn s, nil\n}\n\nfunc (p *ConfigParser) GetInterpolatedWithVars(section, option string, v Dict) (string, error) ", "output": "{\n\to, err := p.Items(section)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tc := chainmap.New(chainmap.Dict(p.Defaults()), chainmap.Dict(o), chainmap.Dict(v))\n\treturn p.getInterpolated(section, option, c)\n\n}"} {"input": "package model\n\n\n\ntype ResourceAssignment struct {\n\t*Record\n}\n\nfunc (ra *ResourceAssignment) Resource() string {\n\treturn ra.ID\n}\n\n\nfunc (ra *ResourceAssignment) MappedPartitions() []string {\n\treturn nil\n}\n\n\n\n\n\nfunc (ra *ResourceAssignment) ReplicaMap(partition string) map[string]string ", "output": "{\n\treturn nil\n}"} {"input": "package data\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\ntype Data struct {\n\tKey string\n\tValue interface{}\n\tTimestamp time.Time\n}\n\n\n\n\n\n\n\nfunc (d *Data) String() string {\n\treturn fmt.Sprintf(\"%s/%v\", d.Key, d.Value)\n}\n\n\n\nfunc New(key string, value interface{}) *Data {\n\treturn &Data{key, value, time.Now()}\n}\n\nfunc (d *Data) IsLater(other *Data) bool ", "output": "{\n\treturn d.Timestamp.After(other.Timestamp)\n}"} {"input": "package command\n\nimport (\n\t\"github.com/mitchellh/cli\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestSubCommand_implements(t *testing.T) {\n\tvar _ cli.Command = &SubCommand{}\n}\n\n\n\nfunc TestSubCommandRun(t *testing.T) ", "output": "{\n\n\tui := new(cli.MockUi)\n\tc := &SubCommand{UI: ui}\n\targs := []string{\"key=val\"}\n\n\tcode := c.Run(args)\n\tif code != 0 {\n\t\tt.Fatalf(\"bad: %d. %#v\", code, ui.ErrorWriter.String())\n\t}\n\n\tif !strings.Contains(ui.OutputWriter.String(), \"Subcommand Complete\") {\n\t\tt.Fatalf(\"bad: %#v\", ui.OutputWriter.String())\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"log\"\n\t\"net/http\"\n)\n\ntype HttpsRedirectingFileHandler interface {\n\thttp.Handler\n\tfileHandler() http.Handler\n}\n\ntype httpsHandler struct {\n\tinternalHandler http.Handler\n}\n\nfunc NewHttpsRedirectFileHandler(dir http.Dir) HttpsRedirectingFileHandler {\n\thandler := &httpsHandler{}\n\thandler.internalHandler = http.FileServer(dir)\n\treturn handler\n}\n\n\n\nfunc isXForwardedHTTPS(request *http.Request) bool {\n\txForwardedProto := request.Header.Get(\"X-Forwarded-Proto\")\n\n\treturn len(xForwardedProto) > 0 && xForwardedProto == \"https\"\n}\n\nfunc (h *httpsHandler) fileHandler() http.Handler {\n\treturn h.internalHandler\n}\n\nfunc (h *httpsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tif !isXForwardedHTTPS(req) {\n\t\tredirect(w, req)\n\t} else {\n\t\th.fileHandler().ServeHTTP(w, req)\n\t}\n}\n\nfunc redirect(w http.ResponseWriter, req *http.Request) ", "output": "{\n\ttarget := \"https://\" + req.Host + req.URL.Path\n\tif len(req.URL.RawQuery) > 0 {\n\t\ttarget += \"?\" + req.URL.RawQuery\n\t}\n\tlog.Printf(\"redirect to: %s\", target)\n\thttp.Redirect(w, req, target,\n\t\thttp.StatusTemporaryRedirect)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSAmazonMQBroker_MaintenanceWindow struct {\n\n\tDayOfWeek string `json:\"DayOfWeek,omitempty\"`\n\n\tTimeOfDay string `json:\"TimeOfDay,omitempty\"`\n\n\tTimeZone string `json:\"TimeZone,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) AWSCloudFormationType() string {\n\treturn \"AWS::AmazonMQ::Broker.MaintenanceWindow\"\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\n\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetMetadata(metadata map[string]interface{}) ", "output": "{\n\tr._metadata = metadata\n}"} {"input": "package otelhttp\n\n\n\n\n\nfunc SemVersion() string {\n\treturn \"semver:\" + Version()\n}\n\nfunc Version() string ", "output": "{\n\treturn \"0.29.0\"\n}"} {"input": "package reconcile\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"k8s.io/apimachinery/pkg/types\"\n)\n\n\ntype Result struct {\n\tRequeue bool\n\n\tRequeueAfter time.Duration\n}\n\n\n\n\n\n\n\ntype Request struct {\n\ttypes.NamespacedName\n}\n\n\ntype Reconciler interface {\n\tReconcile(context.Context, Request) (Result, error)\n}\n\n\ntype Func func(context.Context, Request) (Result, error)\n\nvar _ Reconciler = Func(nil)\n\n\nfunc (r Func) Reconcile(ctx context.Context, o Request) (Result, error) { return r(ctx, o) }\n\nfunc (r *Result) IsZero() bool ", "output": "{\n\tif r == nil {\n\t\treturn true\n\t}\n\treturn *r == Result{}\n}"} {"input": "package quantity\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n\ntype Offset Size\n\nconst (\n\tOffsetKiB = Offset(1 << 10)\n\tOffsetMiB = Offset(1 << 20)\n)\n\n\n\n\n\n\nfunc (o *Offset) IECString() string {\n\treturn iecSizeString(int64(*o))\n}\n\nfunc (o *Offset) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar gs string\n\tif err := unmarshal(&gs); err != nil {\n\t\treturn errors.New(`cannot unmarshal gadget offset`)\n\t}\n\n\tvar err error\n\t*o, err = ParseOffset(gs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot parse offset %q: %v\", gs, err)\n\t}\n\treturn err\n}\n\n\n\nfunc ParseOffset(gs string) (Offset, error) {\n\toffs, err := parseSizeOrOffset(gs)\n\tif offs < 0 {\n\t\treturn 0, errors.New(\"offset cannot be negative\")\n\t}\n\treturn Offset(offs), err\n}\n\nfunc (o *Offset) String() string ", "output": "{\n\treturn (*Size)(o).String()\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListLocalPeeringGatewaysRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tVcnId *string `mandatory:\"false\" contributesTo:\"query\" name:\"vcnId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request ListLocalPeeringGatewaysRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request ListLocalPeeringGatewaysRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ListLocalPeeringGatewaysRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListLocalPeeringGatewaysResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []LocalPeeringGateway `presentIn:\"body\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ListLocalPeeringGatewaysResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListLocalPeeringGatewaysResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListLocalPeeringGatewaysRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package s2\n\n\nvar (\n\t_ Shape = (*PointVector)(nil)\n)\n\n\n\n\n\n\n\n\ntype PointVector []Point\n\nfunc (p *PointVector) NumEdges() int { return len(*p) }\nfunc (p *PointVector) Edge(i int) Edge { return Edge{(*p)[i], (*p)[i]} }\nfunc (p *PointVector) ReferencePoint() ReferencePoint { return OriginReferencePoint(false) }\nfunc (p *PointVector) NumChains() int { return len(*p) }\nfunc (p *PointVector) Chain(i int) Chain { return Chain{i, 1} }\nfunc (p *PointVector) ChainEdge(i, j int) Edge { return Edge{(*p)[i], (*p)[j]} }\nfunc (p *PointVector) ChainPosition(e int) ChainPosition { return ChainPosition{e, 0} }\n\nfunc (p *PointVector) IsEmpty() bool { return defaultShapeIsEmpty(p) }\nfunc (p *PointVector) IsFull() bool { return defaultShapeIsFull(p) }\nfunc (p *PointVector) typeTag() typeTag { return typeTagPointVector }\nfunc (p *PointVector) privateInterface() {}\n\nfunc (p *PointVector) Dimension() int ", "output": "{ return 0 }"} {"input": "package controller\n\nimport (\n\t\"global\"\n\t\"net/http\"\n\t\"route\"\n\t\"strings\"\n)\n\n\ntype StaticController struct{}\n\n\n\n\nfunc (StaticController) static(w http.ResponseWriter, r *http.Request) {\n\treqURI := r.RequestURI\n\tif strings.HasSuffix(reqURI, \"/\") {\n\t\thttp.NotFound(w, r)\n\t} else {\n\t\tfileHandler := http.StripPrefix(\"/static/\", http.FileServer(http.Dir(global.App.ProjectRoot+\"/static\")))\n\t\tfileHandler.ServeHTTP(w, r)\n\t}\n}\n\nfunc (self StaticController) RegisterRoutes() ", "output": "{\n\troute.HandleFunc(\"/static/\", self.static)\n}"} {"input": "package commands\n\nimport (\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nfunc Execute() {\n\trootCmd := &cobra.Command{Use: \"htflood\"}\n\tsetupCommands(rootCmd)\n\trootCmd.Execute()\n}\n\n\n\nfunc checkedRun(run func(cmd *cobra.Command, args []string) error) func(cmd *cobra.Command, args []string) {\n\n\treturn func(cmd *cobra.Command, args []string) {\n\t\tif err := run(cmd, args); err != nil {\n\t\t\tlog.Fatalf(\"%v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}\n\nfunc setupCommands(rootCmd *cobra.Command) ", "output": "{\n\trootCmd.AddCommand(botCommand)\n\trootCmd.AddCommand(statsCommand)\n\trootCmd.AddCommand(reqCommand)\n}"} {"input": "package log\n\nimport (\n\t\"log\"\n)\n\nfunc Debugf(fmt string, args ...interface{}) {\n\tlog.Printf(fmt, args...)\n}\n\n\n\nfunc Debugln(args ...interface{}) ", "output": "{\n\tlog.Println(args...)\n}"} {"input": "package server\n\nimport (\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/codahale/hdrhistogram\"\n\t\"github.com/fluxio/metricd/pb\"\n)\n\nconst LOWEST_VALUE = 0\nconst HIGHEST_VALUE = 1e7\n\n\n\nconst DIGITS_OF_PRECISION = 2\n\ntype histAggregator struct {\n\tname string\n\tindexedLabels map[string]string\n\tunindexedLabels map[string]string\n\th *hdrhistogram.Histogram\n\tm sync.Mutex\n}\n\nfunc (a *histAggregator) AddValue(value float64, ts int64) {\n\ta.m.Lock()\n\tdefer a.m.Unlock()\n\n\tif a.h == nil {\n\t\ta.h = hdrhistogram.New(LOWEST_VALUE, HIGHEST_VALUE, DIGITS_OF_PRECISION)\n\t}\n\ta.h.RecordValue(int64(value))\n}\n\n\n\n\n\n\n\n\n\n\nfunc NewHistAggregator(name string, indexedLabels, unindexedLabels map[string]string) aggregatorUnit {\n\treturn &histAggregator{\n\t\tname: name,\n\t\tindexedLabels: indexedLabels,\n\t\tunindexedLabels: unindexedLabels,\n\t}\n}\n\nfunc (a *histAggregator) GetAggregations() []*pb.Metric ", "output": "{\n\ta.m.Lock()\n\tdefer a.m.Unlock()\n\n\tvar res []*pb.Metric\n\tif a.h != nil && a.h.TotalCount() != 0 {\n\t\tfor _, q := range []float64{0, 50, 90, 95, 99, 100} {\n\t\t\tres = append(res, &pb.Metric{\n\t\t\t\tName: a.name + \"_p\" + strconv.Itoa(int(q)),\n\t\t\t\tIndexedLabels: a.indexedLabels,\n\t\t\t\tUnindexedLabels: a.unindexedLabels,\n\t\t\t\tValue: &pb.Metric_DoubleValue{float64(a.h.ValueAtQuantile(q))},\n\t\t\t\tTs: time.Now().UnixNano(),\n\t\t\t})\n\t\t}\n\t\ta.h = nil\n\t}\n\treturn res\n}"} {"input": "package notify\n\nimport \"github.com/crocos/rds-testrunner/config\"\n\n\n\ntype NotifierInterface interface {\n\tInfo(string) error\n\tWarning(string) error\n\tError(string) error\n}\n\ntype DummyNotifier struct {\n\tConfig config.NotifyConfig\n}\n\nfunc NewDummyNotifier(notifyConfig config.NotifyConfig) (notify NotifierInterface) {\n\treturn &DummyNotifier{Config: notifyConfig}\n}\n\nfunc (n *DummyNotifier) Info(message string) (err error) {\n\treturn\n}\n\nfunc (n *DummyNotifier) Warning(message string) (err error) {\n\treturn\n}\n\nfunc (n *DummyNotifier) Error(message string) (err error) {\n\treturn\n}\n\nfunc NewNotifier(notifyConfig config.NotifyConfig) NotifierInterface ", "output": "{\n\tif notifyConfig.Type == \"hipchat\" {\n\t\treturn NewHipChatNotifier(notifyConfig)\n\t} else {\n\t\treturn NewDummyNotifier(notifyConfig)\n\t}\n}"} {"input": "package ans\n\nimport (\n\t\"time\"\n)\n\n\n\n\ntype Response struct {\n\tID string `json:\"id\"`\n\tStatusCode int `json:\"status_code\"`\n\tBody ResponseBody `json:\"body\"`\n}\n\n\n\ntype ResponseBody struct {\n\tReason string `json:\"reason\"`\n\tTimestamp int64 `json:\"timestamp\"`\n}\n\nfunc NewResponse(id string, statusCode int) *Response {\n\treturn &Response{\n\t\tID: id,\n\t\tStatusCode: statusCode,\n\t}\n}\n\n\n\nfunc (r *ResponseBody) GetTimestamp() time.Time ", "output": "{\n\n\tif r == nil || r.Timestamp == 0 {\n\t\treturn time.Time{}\n\t}\n\n\tms := time.Millisecond * time.Duration(r.Timestamp)\n\n\treturn time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC).Add(ms)\n}"} {"input": "package chipmunk\n\nimport \"github.com/dataarts/chipmunk/vect\"\n\nconst (\n\terrorBias = 0.00179701029991443 \n)\n\ntype ConstraintCallback interface {\n\tCollisionPreSolve(constraint Constraint)\n\tCollisionPostSolve(constraint Constraint)\n}\n\ntype Constraint interface {\n\tConstraint() *BasicConstraint\n\tPreSolve()\n\tPostSolve()\n\tPreStep(dt vect.Float)\n\tApplyCachedImpulse(dt_coef vect.Float)\n\tApplyImpulse()\n\tImpulse() vect.Float\n}\n\ntype BasicConstraint struct {\n\tBodyA, BodyB *Body\n\tspace *Space\n\tMaxForce vect.Float\n\tErrorBias vect.Float\n\tMaxBias vect.Float\n\tCallbackHandler ConstraintCallback\n\tUserData Data\n}\n\nfunc NewConstraint(a, b *Body) BasicConstraint {\n\treturn BasicConstraint{BodyA: a, BodyB: b, MaxForce: Inf, MaxBias: Inf, ErrorBias: errorBias}\n}\n\nfunc (this *BasicConstraint) Constraint() *BasicConstraint {\n\treturn this\n}\n\nfunc (this *BasicConstraint) PreStep(dt vect.Float) {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) ApplyCachedImpulse(dt_coef vect.Float) {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) ApplyImpulse() {\n\tpanic(\"empty constraint\")\n}\n\n\n\nfunc (this *BasicConstraint) PreSolve() {\n\tif this.CallbackHandler != nil {\n\t\tthis.CallbackHandler.CollisionPreSolve(this)\n\t}\n}\n\nfunc (this *BasicConstraint) PostSolve() {\n\tif this.CallbackHandler != nil {\n\t\tthis.CallbackHandler.CollisionPostSolve(this)\n\t}\n}\n\nfunc (this *BasicConstraint) Impulse() vect.Float ", "output": "{\n\tpanic(\"empty constraint\")\n}"} {"input": "package ansiwriter\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype Modifier func() string\n\nfunc escapeANSI(code int) string {\n\treturn fmt.Sprintf(\"\\033[%dm\", code)\n}\n\nfunc Bold() string { return escapeANSI(1) }\nfunc Black() string { return escapeANSI(30) }\nfunc Red() string { return escapeANSI(31) }\nfunc Green() string { return escapeANSI(32) }\nfunc Yellow() string { return escapeANSI(33) }\nfunc Blue() string { return escapeANSI(34) }\nfunc Magenta() string { return escapeANSI(35) }\nfunc Cyan() string { return escapeANSI(36) }\nfunc White() string { return escapeANSI(37) }\n\ntype awr struct {\n\tio.Writer\n\tmodifiers []Modifier\n}\n\n\n\n\n\n\nfunc (a awr) Write(b []byte) (n int, err error) {\n\tfor _, mod := range a.modifiers {\n\t\ta.Writer.Write([]byte(mod()))\n\t}\n\tn, err = a.Writer.Write(b)\n\t_, _ = a.Writer.Write([]byte(\"\\033[0m\"))\n\treturn\n}\n\nfunc New(w io.Writer, mods ...Modifier) io.Writer ", "output": "{\n\treturn awr{w, mods}\n}"} {"input": "package okta\n\nimport ()\n\ntype ApplicationSettingsNotificationsVpn struct {\n\tHelpUrl string `json:\"helpUrl,omitempty\"`\n\tMessage string `json:\"message,omitempty\"`\n\tNetwork *ApplicationSettingsNotificationsVpnNetwork `json:\"network,omitempty\"`\n}\n\n\n\nfunc (a *ApplicationSettingsNotificationsVpn) IsApplicationInstance() bool {\n\treturn true\n}\n\nfunc NewApplicationSettingsNotificationsVpn() *ApplicationSettingsNotificationsVpn ", "output": "{\n\treturn &ApplicationSettingsNotificationsVpn{}\n}"} {"input": "package filter\n\nimport (\n\t\"github.com/m3db/m3/src/aggregator/sharding\"\n\t\"github.com/m3db/m3/src/msg/producer\"\n)\n\ntype shardSetFilter struct {\n\tshardSet sharding.ShardSet\n}\n\n\nfunc NewShardSetFilter(shardSet sharding.ShardSet) producer.FilterFunc {\n\tf := shardSetFilter{shardSet: shardSet}\n\treturn f.Filter\n}\n\n\n\nfunc (f shardSetFilter) Filter(m producer.Message) bool ", "output": "{\n\t_, ok := f.shardSet[m.Shard()]\n\treturn ok\n}"} {"input": "package gogs\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\nfunc (c *Client) AdminCreateOrg(user string, opt CreateOrgOption) (*Organization, error) {\n\tbody, err := json.Marshal(&opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\torg := new(Organization)\n\treturn org, c.getParsedResponse(\"POST\", fmt.Sprintf(\"/admin/users/%s/orgs\", user),\n\t\tjsonHeader, bytes.NewReader(body), org)\n}\n\nfunc (c *Client) AdminCreateTeam(user string, opt CreateTeamOption) (*Team, error) {\n\tbody, err := json.Marshal(&opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tteam := new(Team)\n\treturn team, c.getParsedResponse(\"POST\", fmt.Sprintf(\"/admin/orgs/%s/teams\", user),\n\t\tjsonHeader, bytes.NewReader(body), team)\n}\n\nfunc (c *Client) AdminAddTeamMembership(teamID int64, user string) error {\n\t_, err := c.getResponse(\"PUT\", fmt.Sprintf(\"/admin/teams/%d/members/%s\", teamID, user),\n\t\tjsonHeader, nil)\n\treturn err\n}\n\n\n\nfunc (c *Client) AdminAddTeamRepository(teamID int64, repo string) error ", "output": "{\n\t_, err := c.getResponse(\"PUT\", fmt.Sprintf(\"/admin/teams/%d/repos/%s\", teamID, repo),\n\t\tjsonHeader, nil)\n\treturn err\n}"} {"input": "package data\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\n\ntype Art struct {\n\tID int\n\tFileSize int64 `db:\"file_size\"`\n\tFileName string `db:\"file_name\"`\n\tLastModified int64 `db:\"last_modified\"`\n}\n\n\n\n\n\nfunc (a *Art) Load() error {\n\treturn DB.LoadArt(a)\n}\n\n\nfunc (a *Art) Save() error {\n\treturn DB.SaveArt(a)\n}\n\n\nfunc (a Art) Stream() (io.ReadSeeker, error) {\n\treturn os.Open(a.FileName)\n}\n\nfunc (a *Art) Delete() error ", "output": "{\n\treturn DB.DeleteArt(a)\n}"} {"input": "package private\n\nimport (\n\t\"net/http\"\n\n\t\"code.gitea.io/gitea/modules/context\"\n\t\"code.gitea.io/gitea/modules/graceful\"\n)\n\n\nfunc Restart(ctx *context.PrivateContext) {\n\tgraceful.GetManager().DoGracefulRestart()\n\tctx.PlainText(http.StatusOK, \"success\")\n}\n\n\n\n\nfunc Shutdown(ctx *context.PrivateContext) ", "output": "{\n\tgraceful.GetManager().DoGracefulShutdown()\n\tctx.PlainText(http.StatusOK, \"success\")\n}"} {"input": "package owl\n\nimport (\n\t\"time\"\n\n\towlc \"github.com/Cepave/open-falcon-backend/common/ccache\"\n\tmodel \"github.com/Cepave/open-falcon-backend/common/model/owl\"\n\towlDb \"github.com/Cepave/open-falcon-backend/modules/mysqlapi/rdb/owl\"\n\tc \"github.com/karlseguin/ccache\"\n\t\"github.com/satori/go.uuid\"\n)\n\ntype QueryObjectServiceConfig struct {\n\tCacheSize int64\n\tCacheDuration time.Duration\n}\n\nvar QueryObjectService *queryObjectService\n\nfunc InitQueryObjectService(config QueryObjectServiceConfig) {\n\tQueryObjectService = newQueryObjectService(&config)\n}\nfunc StopQueryObjectService() {\n\tif QueryObjectService != nil {\n\t\tQueryObjectService.cache.Stop()\n\t}\n\n\tQueryObjectService = nil\n}\n\ntype queryObjectService struct {\n\tconfig *QueryObjectServiceConfig\n\tcache *c.Cache\n}\n\nfunc newQueryObjectService(config *QueryObjectServiceConfig) *queryObjectService {\n\tcacheObject := owlc.NewDataCache(\n\t\towlc.DataCacheConfig{\n\t\t\tMaxSize: config.CacheSize,\n\t\t\tDuration: config.CacheDuration,\n\t\t},\n\t)\n\n\treturn &queryObjectService{\n\t\tconfig, cacheObject,\n\t}\n}\n\n\n\n\nfunc (s *queryObjectService) CreateOrLoadQuery(query *model.Query) {\n\tnow := time.Now()\n\n\towlDb.AddOrRefreshQuery(query, now)\n\n\ts.cache.Set(\n\t\tquery.Uuid.ToUuid().String(),\n\t\tquery,\n\t\ts.config.CacheDuration,\n\t)\n}\n\nfunc (s *queryObjectService) LoadQueryByUuid(uuid uuid.UUID) *model.Query ", "output": "{\n\tnow := time.Now()\n\tstringUuid := uuid.String()\n\n\titemInCache := s.cache.Get(stringUuid)\n\tif itemInCache != nil {\n\t\tquery := itemInCache.Value().(*model.Query)\n\t\towlDb.UpdateAccessTimeOrAddNewOne(query, now)\n\n\t\treturn query\n\t}\n\n\tqueryFromDatabase := owlDb.LoadQueryByUuidAndUpdateAccessTime(\n\t\tuuid, now,\n\t)\n\tif queryFromDatabase == nil {\n\t\treturn nil\n\t}\n\n\ts.cache.Set(stringUuid, queryFromDatabase, s.config.CacheDuration)\n\treturn s.cache.Get(stringUuid).Value().(*model.Query)\n}"} {"input": "package internal\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\tgax \"github.com/googleapis/gax-go/v2\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n)\n\nfunc TestRetry(t *testing.T) {\n\tctx := context.Background()\n\tn := 0\n\tendRetry := errors.New(\"end retry\")\n\terr := retry(ctx, gax.Backoff{},\n\t\tfunc() (bool, error) {\n\t\t\tn++\n\t\t\tif n < 10 {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn true, endRetry\n\t\t},\n\t\tfunc(context.Context, time.Duration) error { return nil })\n\tif got, want := err, endRetry; got != want {\n\t\tt.Errorf(\"got %v, want %v\", err, endRetry)\n\t}\n\tif n != 10 {\n\t\tt.Errorf(\"n: got %d, want %d\", n, 10)\n\t}\n\n\tn = 0\n\terr = retry(ctx, gax.Backoff{},\n\t\tfunc() (bool, error) { return false, nil },\n\t\tfunc(context.Context, time.Duration) error {\n\t\t\tn++\n\t\t\tif n < 10 {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn context.DeadlineExceeded\n\t\t})\n\tif err == nil {\n\t\tt.Error(\"got nil, want error\")\n\t}\n}\n\n\n\nfunc TestRetryPreserveError(t *testing.T) ", "output": "{\n\terr := retry(context.Background(), gax.Backoff{},\n\t\tfunc() (bool, error) {\n\t\t\treturn false, status.Error(codes.NotFound, \"not found\")\n\t\t},\n\t\tfunc(context.Context, time.Duration) error {\n\t\t\treturn context.DeadlineExceeded\n\t\t})\n\tgot, ok := status.FromError(err)\n\tif !ok {\n\t\tt.Fatalf(\"got %T, wanted a status\", got)\n\t}\n\tif g, w := got.Code(), codes.NotFound; g != w {\n\t\tt.Errorf(\"got code %v, want %v\", g, w)\n\t}\n\twantMessage := fmt.Sprintf(\"retry failed with %v; last error: not found\", context.DeadlineExceeded)\n\tif g, w := got.Message(), wantMessage; g != w {\n\t\tt.Errorf(\"got message %q, want %q\", g, w)\n\t}\n}"} {"input": "package jms\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype UpdateFleetAgentConfigurationRequest struct {\n\n\tFleetId *string `mandatory:\"true\" contributesTo:\"path\" name:\"fleetId\"`\n\n\tUpdateFleetAgentConfigurationDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateFleetAgentConfigurationRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request UpdateFleetAgentConfigurationRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request UpdateFleetAgentConfigurationRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype UpdateFleetAgentConfigurationResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateFleetAgentConfigurationResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateFleetAgentConfigurationResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateFleetAgentConfigurationRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package expr\n\ntype (\n\tGRPCExpr struct {\n\t\tServices []*GRPCServiceExpr\n\t\tErrors []*GRPCErrorExpr\n\t}\n)\n\n\n\n\n\n\nfunc (g *GRPCExpr) ServiceFor(s *ServiceExpr) *GRPCServiceExpr {\n\tif res := g.Service(s.Name); res != nil {\n\t\treturn res\n\t}\n\tres := &GRPCServiceExpr{\n\t\tServiceExpr: s,\n\t}\n\tg.Services = append(g.Services, res)\n\treturn res\n}\n\n\nfunc (g *GRPCExpr) EvalName() string {\n\treturn \"API GRPC\"\n}\n\nfunc (g *GRPCExpr) Service(name string) *GRPCServiceExpr ", "output": "{\n\tfor _, res := range g.Services {\n\t\tif res.Name() == name {\n\t\t\treturn res\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package rusage\n\nimport (\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/pkg/errors\"\n)\n\nfunc mkduration(tv syscall.Timeval) time.Duration {\n\treturn time.Duration(tv.Sec)*time.Second + time.Duration(tv.Usec)*time.Microsecond\n}\n\n\n\n\nfunc Supported() bool {\n\treturn true\n}\n\nfunc get() (Rusage, error) ", "output": "{\n\tvar rusage syscall.Rusage\n\terr := syscall.Getrusage(syscall.RUSAGE_CHILDREN, &rusage)\n\tif err != nil {\n\t\treturn Rusage{}, errors.Wrapf(err, \"error getting resource usage\")\n\t}\n\tr := Rusage{\n\t\tDate: time.Now(),\n\t\tUtime: mkduration(rusage.Utime),\n\t\tStime: mkduration(rusage.Stime),\n\t\tInblock: int64(rusage.Inblock), \n\t\tOutblock: int64(rusage.Oublock), \n\t}\n\treturn r, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype helloTransport interface {\n\tConnect(addr string) error\n\tClose() error\n\tRequest(req string) (reply string, err error)\n}\n\ntype transGenerator func() (helloTransport, error)\n\nvar transporter map[string]transGenerator = make(map[string]transGenerator)\n\n\n\nfunc transportList() []string {\n\tvar transports = make([]string, 0, len(transporter))\n\tfor id := range transporter {\n\t\ttransports = append(transports, id)\n\t}\n\tsort.StringSlice(transports).Sort()\n\treturn transports\n}\n\nfunc availableTransports() string {\n\tvar transports = transportList()\n\treturn strings.Join(transports, \",\")\n}\n\nfunc firstTransport() string {\n\tvar transports = transportList()\n\treturn transports[0]\n}\n\nfunc defaultAddr(addr string) string {\n\treturn fmt.Sprintf(\"%s://%s\", firstTransport(), addr)\n}\n\nfunc newTransport(addr string) (helloTransport, error) {\n\tvar uri, err = url.Parse(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif generate, ok := transporter[uri.Scheme]; ok {\n\t\treturn generate()\n\t}\n\treturn nil, fmt.Errorf(\"invalid transport %q\", uri.Scheme)\n}\n\nfunc registerTransport(id string, gen transGenerator) ", "output": "{\n\ttransporter[id] = gen\n}"} {"input": "package main\n\nimport \"testing\"\n\n\n\nfunc TestArea(t *testing.T) {\n\trectangle := Rectangle{12.0, 6.0}\n\tgot := Area(rectangle)\n\twant := 72.0\n\n\tif got != want {\n\t\tt.Errorf(\"got %.2f want %.2f\", got, want)\n\t}\n}\n\nfunc TestPerimeter(t *testing.T) ", "output": "{\n\trectangle := Rectangle{10.0, 10.0}\n\tgot := Perimeter(rectangle)\n\twant := 40.0\n\n\tif got != want {\n\t\tt.Errorf(\"got %.2f want %.2f\", got, want)\n\t}\n}"} {"input": "package couchdb\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\tkivik \"github.com/go-kivik/kivik/v3\"\n)\n\n\n\n\nvar jsonKeys = []string{\"endkey\", \"end_key\", \"key\", \"startkey\", \"start_key\", \"keys\", \"doc_ids\"}\n\nfunc encodeKeys(opts map[string]interface{}) error {\n\tfor _, key := range jsonKeys {\n\t\tif v, ok := opts[key]; ok {\n\t\t\tnew, err := encodeKey(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\topts[key] = new\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc encodeKey(i interface{}) (string, error) ", "output": "{\n\tif raw, ok := i.(json.RawMessage); ok {\n\t\treturn string(raw), nil\n\t}\n\traw, err := json.Marshal(i)\n\tif err != nil {\n\t\terr = &kivik.Error{HTTPStatus: http.StatusBadRequest, Err: err}\n\t}\n\treturn string(raw), err\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/protobuf/encoding/prototext\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t_ \"google.golang.org/genproto/googleapis/rpc/errdetails\" \n)\n\n\ntype StatusError struct {\n\tst *status.Status\n\tdetails string\n}\n\n\nfunc StatusDetailedError(st *status.Status) *StatusError {\n\tvar details []string\n\tfor _, d := range st.Details() {\n\t\ts := fmt.Sprintf(\"%+v\", d)\n\t\tif pb, ok := d.(proto.Message); ok {\n\t\t\ts = prototext.Format(pb)\n\t\t}\n\t\tdetails = append(details, s)\n\t}\n\treturn &StatusError{st, strings.Join(details, \"; \")}\n}\n\nfunc (e *StatusError) Error() string {\n\tmsg := fmt.Sprintf(\"rpc error: code = %s desc = %s\", e.st.Code(), e.st.Message())\n\tif e.details != \"\" {\n\t\tmsg += \" details = \" + e.details\n\t}\n\treturn msg\n}\n\n\n\n\n\n\nfunc (e *StatusError) Is(target error) bool {\n\tif tse, ok := target.(*StatusError); ok {\n\t\treturn proto.Equal(e.st.Proto(), tse.st.Proto())\n\t}\n\tif tst, ok := status.FromError(target); ok {\n\t\treturn proto.Equal(e.st.Proto(), tst.Proto())\n\t}\n\treturn false\n}\n\nfunc (e *StatusError) GRPCStatus() *status.Status ", "output": "{\n\treturn e.st\n}"} {"input": "package trie\n\nimport \"fmt\"\n\ntype FullNode struct {\n\ttrie *Trie\n\tnodes [17]Node\n}\n\nfunc NewFullNode(t *Trie) *FullNode {\n\treturn &FullNode{trie: t}\n}\n\nfunc (self *FullNode) Dirty() bool { return true }\nfunc (self *FullNode) Value() Node {\n\tself.nodes[16] = self.trie.trans(self.nodes[16])\n\treturn self.nodes[16]\n}\nfunc (self *FullNode) Branches() []Node {\n\treturn self.nodes[:16]\n}\n\nfunc (self *FullNode) Copy(t *Trie) Node {\n\tnnode := NewFullNode(t)\n\tfor i, node := range self.nodes {\n\t\tif node != nil {\n\t\t\tnnode.nodes[i] = node.Copy(t)\n\t\t}\n\t}\n\n\treturn nnode\n}\n\n\nfunc (self *FullNode) Len() (amount int) {\n\tfor _, node := range self.nodes {\n\t\tif node != nil {\n\t\t\tamount++\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (self *FullNode) Hash() interface{} {\n\treturn self.trie.store(self)\n}\n\nfunc (self *FullNode) RlpData() interface{} {\n\tt := make([]interface{}, 17)\n\tfor i, node := range self.nodes {\n\t\tif node != nil {\n\t\t\tt[i] = node.Hash()\n\t\t} else {\n\t\t\tt[i] = \"\"\n\t\t}\n\t}\n\n\treturn t\n}\n\n\n\nfunc (self *FullNode) branch(i byte) Node {\n\tif self.nodes[int(i)] != nil {\n\t\tself.nodes[int(i)] = self.trie.trans(self.nodes[int(i)])\n\n\t\treturn self.nodes[int(i)]\n\t}\n\treturn nil\n}\n\nfunc (self *FullNode) set(k byte, value Node) ", "output": "{\n\tif _, ok := value.(*ValueNode); ok && k != 16 {\n\t\tfmt.Println(value, k)\n\t}\n\n\tself.nodes[int(k)] = value\n}"} {"input": "package grpc\n\nimport (\n\t\"github.com/micro/go-micro/v3/client\"\n)\n\ntype grpcEvent struct {\n\ttopic string\n\tcontentType string\n\tpayload interface{}\n}\n\nfunc newGRPCEvent(topic string, payload interface{}, contentType string, opts ...client.MessageOption) client.Message {\n\tvar options client.MessageOptions\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\tif len(options.ContentType) > 0 {\n\t\tcontentType = options.ContentType\n\t}\n\n\treturn &grpcEvent{\n\t\tpayload: payload,\n\t\ttopic: topic,\n\t\tcontentType: contentType,\n\t}\n}\n\nfunc (g *grpcEvent) ContentType() string {\n\treturn g.contentType\n}\n\nfunc (g *grpcEvent) Topic() string {\n\treturn g.topic\n}\n\n\n\nfunc (g *grpcEvent) Payload() interface{} ", "output": "{\n\treturn g.payload\n}"} {"input": "package scope_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"euphoria.io/scope\"\n)\n\n\n\nfunc ExampleContext_cancellation() {\n\tctx := scope.New()\n\n\tgo func() {\n\t\ttime.Sleep(50 * time.Millisecond)\n\t\tctx.Cancel()\n\t}()\n\nloop:\n\tfor {\n\t\tt := time.After(10 * time.Millisecond)\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tbreak loop\n\t\tcase <-t:\n\t\t\tfmt.Println(\"tick\")\n\t\t}\n\t}\n\tfmt.Println(\"finished with\", ctx.Err())\n}\n\nfunc ExampleBreakpointer() ", "output": "{\n\troot := scope.New()\n\n\toutput := func(arg string) error {\n\t\t_, err := fmt.Println(arg)\n\t\treturn err\n\t}\n\n\tverifyOutput := func(ctx scope.Context, arg string) error {\n\t\tif err := ctx.Check(\"output()\", arg); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn output(arg)\n\t}\n\n\tctrl := root.Breakpoint(\"output()\", \"fail\")\n\n\terr := verifyOutput(root, \"normal behavior\")\n\tfmt.Println(\"verifyOutput returned\", err)\n\n\tgo func() {\n\t\t<-ctrl \n\t\tctrl <- fmt.Errorf(\"test error\")\n\t}()\n\n\terr = verifyOutput(root, \"fail\")\n\tfmt.Println(\"verifyOutput returned\", err)\n\n\tgo func() {\n\t\t<-ctrl\n\t\troot.Cancel()\n\t}()\n\n\terr = verifyOutput(root, \"fail\")\n\tfmt.Println(\"verifyOutput returned\", err)\n\n}"} {"input": "package buildings\n\ntype store struct {\n\tbasicBuilding\n\timprovementLvl int8\n\tsales int\n\tprice int\n}\n\nfunc (*store) GetType() string { return \"store\" }\nfunc (b *store) GetRevenue() int { return b.sales * b.price }\n\nfunc (b *store) GetInternalInt(name string) int {\n\tswitch name {\n\tcase \"improvementLvl\":\n\t\treturn int(b.improvementLvl)\n\tcase \"sales\":\n\t\treturn b.sales\n\tcase \"price\":\n\t\treturn b.price\n\tdefault:\n\t\treturn 0\n\t}\n}\nfunc (b *store) SetInternalInt(name string, val int) {\n\tswitch name {\n\tcase \"improvementLvl\":\n\t\tb.improvementLvl = int8(val)\n\tcase \"sales\":\n\t\tb.sales = val\n\tcase \"price\":\n\t\tb.price = val\n\t}\n}\nfunc (b *store) ToString(x, y int) string {\n\treturn \"store,\" + string(b.improvementLvl) + \",\" + string(b.sales) + \",\" + string(b.price) + \",\" + b.basicBuilding.ToString(x, y)\n}\n\nfunc (b *store) GetRent() int ", "output": "{ return [4]int{1, 2, 3, 5}[b.improvementLvl] }"} {"input": "package gfile\n\nimport (\n\t\"bytes\"\n\t\"github.com/gogf/gf/v2/errors/gcode\"\n\t\"github.com/gogf/gf/v2/errors/gerror\"\n\t\"os\"\n\t\"os/exec\"\n\t\"os/user\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n\n\n\n\n\n\nfunc getHomePath() (string, error) {\n\tu, err := user.Current()\n\tif nil == err {\n\t\treturn u.HomeDir, nil\n\t}\n\tif \"windows\" == runtime.GOOS {\n\t\treturn homeWindows()\n\t}\n\treturn homeUnix()\n}\n\n\nfunc homeUnix() (string, error) {\n\tif home := os.Getenv(\"HOME\"); home != \"\" {\n\t\treturn home, nil\n\t}\n\tvar stdout bytes.Buffer\n\tcmd := exec.Command(\"sh\", \"-c\", \"eval echo ~$USER\")\n\tcmd.Stdout = &stdout\n\tif err := cmd.Run(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresult := strings.TrimSpace(stdout.String())\n\tif result == \"\" {\n\t\treturn \"\", gerror.NewCode(gcode.CodeInternalError, \"blank output when reading home directory\")\n\t}\n\n\treturn result, nil\n}\n\n\nfunc homeWindows() (string, error) {\n\tvar (\n\t\tdrive = os.Getenv(\"HOMEDRIVE\")\n\t\tpath = os.Getenv(\"HOMEPATH\")\n\t\thome = drive + path\n\t)\n\tif drive == \"\" || path == \"\" {\n\t\thome = os.Getenv(\"USERPROFILE\")\n\t}\n\tif home == \"\" {\n\t\treturn \"\", gerror.NewCode(gcode.CodeOperationFailed, \"HOMEDRIVE, HOMEPATH, and USERPROFILE are blank\")\n\t}\n\n\treturn home, nil\n}\n\nfunc Home(names ...string) (string, error) ", "output": "{\n\tpath, err := getHomePath()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfor _, name := range names {\n\t\tpath += Separator + name\n\t}\n\treturn path, nil\n}"} {"input": "package commands_test\n\nimport (\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/zetamatta/nyagos/commands\"\n)\n\nfunc testFixPathCase(t *testing.T, path string) string {\n\tnewpath, err := commands.CorrectCase(path)\n\tif err != nil {\n\t\tt.Fatalf(\"CorrectCase: %v\", err.Error())\n\t}\n\treturn newpath\n}\n\n\n\nfunc TestFixPathCase(t *testing.T) ", "output": "{\n\torgPath, err := os.Getwd()\n\tif err != nil {\n\t\tt.Errorf(\"os.Getwd(): %v\", err)\n\t}\n\tchgPath := strings.ToUpper(orgPath)\n\tactPath := testFixPathCase(t, chgPath)\n\tif actPath != orgPath {\n\t\tt.Fatalf(\"CorrectCase('%s') == %s\", chgPath, actPath)\n\t}\n\tactPath = testFixPathCase(t, \"c:\\\\\")\n\tif actPath != `C:\\` {\n\t\tt.Fatalf(\"CorrectCase('c:\\\\') == '%s'\", actPath)\n\t}\n}"} {"input": "package iso20022\n\n\ntype PaymentInstrument21Choice struct {\n\n\tCreditTransferDetails *CreditTransfer8 `xml:\"CdtTrfDtls\"`\n\n\tChequeDetails *Cheque9 `xml:\"ChqDtls\"`\n\n\tBankersDraftDetails *Cheque9 `xml:\"BkrsDrftDtls\"`\n\n\tCashAccountDetails *InvestmentAccount60 `xml:\"CshAcctDtls\"`\n}\n\nfunc (p *PaymentInstrument21Choice) AddCreditTransferDetails() *CreditTransfer8 {\n\tp.CreditTransferDetails = new(CreditTransfer8)\n\treturn p.CreditTransferDetails\n}\n\n\n\nfunc (p *PaymentInstrument21Choice) AddBankersDraftDetails() *Cheque9 {\n\tp.BankersDraftDetails = new(Cheque9)\n\treturn p.BankersDraftDetails\n}\n\nfunc (p *PaymentInstrument21Choice) AddCashAccountDetails() *InvestmentAccount60 {\n\tp.CashAccountDetails = new(InvestmentAccount60)\n\treturn p.CashAccountDetails\n}\n\nfunc (p *PaymentInstrument21Choice) AddChequeDetails() *Cheque9 ", "output": "{\n\tp.ChequeDetails = new(Cheque9)\n\treturn p.ChequeDetails\n}"} {"input": "package gtka\n\nimport (\n\t\"github.com/coyim/gotk3adapter/gtki\"\n\t\"github.com/gotk3/gotk3/gtk\"\n)\n\ntype toolButton struct {\n\t*bin\n\tinternal *gtk.ToolButton\n}\n\nfunc WrapToolButtonSimple(v *gtk.ToolButton) gtki.ToolButton {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn &toolButton{WrapBinSimple(&v.Bin).(*bin), v}\n}\n\n\n\nfunc UnwrapToolButton(v gtki.ToolButton) *gtk.ToolButton {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*toolButton).internal\n}\n\nfunc (v *toolButton) Add(v1 gtki.Widget) {\n\tv.internal.Add(UnwrapWidget(v1))\n}\n\nfunc WrapToolButton(v *gtk.ToolButton, e error) (gtki.ToolButton, error) ", "output": "{\n\treturn WrapToolButtonSimple(v), e\n}"} {"input": "package data\n\nimport (\n \"github.com/twitchyliquid64/CNC/registry/syscomponents\"\n)\n\nvar trackerObj DatabaseComponent\n\ntype DatabaseComponent struct{\n err error\n}\n\nfunc (d *DatabaseComponent)Name() string{\n return \"Database\"\n}\nfunc (d *DatabaseComponent)IconStr() string{\n return \"list\"\n}\nfunc (d *DatabaseComponent)IsNominal()bool{\n return d.err == nil\n}\n\nfunc (d *DatabaseComponent)IsFault()bool{\n return d.err != nil\n}\nfunc (d *DatabaseComponent)Error()string{\n if d.err == nil{\n return \"\"\n }\n return d.err.Error()\n}\nfunc (d *DatabaseComponent)SetError(e error){\n d.err = e\n}\n\nfunc trackingSetup(){\n trackerObj = DatabaseComponent{}\n syscomponents.Register(&trackerObj)\n}\n\nfunc tracking_notifyFault(err error){\n syscomponents.SetError(trackerObj.Name(), err)\n}\n\nfunc (d *DatabaseComponent)IsDisabled()bool", "output": "{\n return false\n}"} {"input": "package artifacts\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype RepositoryCollection struct {\n\n\tItems []RepositorySummary `mandatory:\"true\" json:\"items\"`\n}\n\n\n\n\nfunc (m *RepositoryCollection) UnmarshalJSON(data []byte) (e error) {\n\tmodel := struct {\n\t\tItems []repositorysummary `json:\"items\"`\n\t}{}\n\n\te = json.Unmarshal(data, &model)\n\tif e != nil {\n\t\treturn\n\t}\n\tvar nn interface{}\n\tm.Items = make([]RepositorySummary, len(model.Items))\n\tfor i, n := range model.Items {\n\t\tnn, e = n.UnmarshalPolymorphicJSON(n.JsonData)\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\t\tif nn != nil {\n\t\t\tm.Items[i] = nn.(RepositorySummary)\n\t\t} else {\n\t\t\tm.Items[i] = nil\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (m RepositoryCollection) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package replay\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/gapid/core/data/search\"\n\t\"github.com/google/gapid/test/robot/job/worker\"\n\t\"google.golang.org/grpc\"\n\n\txctx \"golang.org/x/net/context\"\n)\n\ntype server struct {\n\tmanager Manager\n}\n\n\nfunc Serve(ctx context.Context, grpcServer *grpc.Server, manager Manager) error {\n\tRegisterServiceServer(grpcServer, &server{manager: manager})\n\treturn nil\n}\n\n\n\n\n\n\n\nfunc (s *server) Register(request *worker.RegisterRequest, stream Service_RegisterServer) error {\n\tctx := stream.Context()\n\treturn s.manager.Register(ctx, request.Host, request.Target, func(ctx context.Context, t *Task) error { return stream.Send(t) })\n}\n\n\n\nfunc (s *server) Do(ctx xctx.Context, request *DoRequest) (*worker.DoResponse, error) {\n\tid, err := s.manager.Do(ctx, request.Device, request.Input)\n\treturn &worker.DoResponse{Id: id}, err\n}\n\n\n\nfunc (s *server) Update(ctx xctx.Context, request *UpdateRequest) (*worker.UpdateResponse, error) {\n\tif err := s.manager.Update(ctx, request.Action, request.Status, request.Output); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &worker.UpdateResponse{}, nil\n}\n\nfunc (s *server) Search(query *search.Query, stream Service_SearchServer) error ", "output": "{\n\tctx := stream.Context()\n\treturn s.manager.Search(ctx, query, func(ctx context.Context, e *Action) error { return stream.Send(e) })\n}"} {"input": "package limiter\n\nimport (\n\t\"math/rand\"\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n)\n\n\nfunc GetIP(r *http.Request, trustForwardHeader ...bool) net.IP {\n\tif len(trustForwardHeader) >= 1 && trustForwardHeader[0] {\n\t\tip := r.Header.Get(\"X-Forwarded-For\")\n\t\tif ip != \"\" {\n\t\t\tparts := strings.SplitN(ip, \",\", 2)\n\t\t\tpart := strings.TrimSpace(parts[0])\n\t\t\treturn net.ParseIP(part)\n\t\t}\n\n\t\tip = strings.TrimSpace(r.Header.Get(\"X-Real-IP\"))\n\t\tif ip != \"\" {\n\t\t\treturn net.ParseIP(ip)\n\t\t}\n\t}\n\n\tremoteAddr := strings.TrimSpace(r.RemoteAddr)\n\thost, _, err := net.SplitHostPort(remoteAddr)\n\tif err != nil {\n\t\treturn net.ParseIP(remoteAddr)\n\t}\n\n\treturn net.ParseIP(host)\n}\n\n\nfunc GetIPKey(r *http.Request, trustForwardHeader ...bool) string {\n\treturn GetIP(r, trustForwardHeader...).String()\n}\n\n\n\n\nfunc Random(min, max int) int ", "output": "{\n\trand.Seed(time.Now().Unix())\n\treturn rand.Intn(max-min) + min\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\n\tv3 \"github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3\"\n\t\"github.com/rancher/rancher/pkg/ref\"\n\t\"github.com/sirupsen/logrus\"\n)\n\n\n\nfunc GetGroupID(namespace, name string) string {\n\treturn fmt.Sprintf(\"%s:%s\", namespace, name)\n}\n\nfunc GetAlertManagerSecretName(appName string) string {\n\treturn fmt.Sprintf(\"alertmanager-%s\", appName)\n}\n\nfunc GetAlertManagerDaemonsetName(appName string) string {\n\treturn fmt.Sprintf(\"alertmanager-%s\", appName)\n}\n\nfunc formatProjectDisplayName(projectDisplayName, projectID string) string {\n\treturn fmt.Sprintf(\"%s (ID: %s)\", projectDisplayName, projectID)\n}\n\nfunc formatClusterDisplayName(clusterDisplayName, clusterID string) string {\n\treturn fmt.Sprintf(\"%s (ID: %s)\", clusterDisplayName, clusterID)\n}\n\nfunc GetClusterDisplayName(clusterName string, clusterLister v3.ClusterLister) string {\n\tcluster, err := clusterLister.Get(\"\", clusterName)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to get cluster for %s: %v\", clusterName, err)\n\t\treturn clusterName\n\t}\n\n\treturn formatClusterDisplayName(cluster.Spec.DisplayName, clusterName)\n}\n\nfunc GetProjectDisplayName(projectID string, projectLister v3.ProjectLister) string {\n\tclusterName, projectName := ref.Parse(projectID)\n\tproject, err := projectLister.Get(clusterName, projectName)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to get project %s: %v\", projectID, err)\n\t\treturn projectID\n\t}\n\n\treturn formatProjectDisplayName(project.Spec.DisplayName, projectID)\n}\n\nfunc GetRuleID(groupID string, ruleName string) string ", "output": "{\n\treturn fmt.Sprintf(\"%s_%s\", groupID, ruleName)\n}"} {"input": "package kafkasink\n\nimport (\n\tfmt \"fmt\"\n\n\ttypes \"k8s.io/apimachinery/pkg/types\"\n\tcache \"k8s.io/client-go/tools/cache\"\n\tv1alpha1 \"knative.dev/eventing-kafka-broker/control-plane/pkg/apis/eventing/v1alpha1\"\n\treconciler \"knative.dev/pkg/reconciler\"\n)\n\n\ntype state struct {\n\tkey string\n\tnamespace string\n\tname string\n\treconciler Interface\n\troi ReadOnlyInterface\n\tisROI bool\n\tisLeader bool\n}\n\nfunc newState(key string, r *reconcilerImpl) (*state, error) {\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid resource key: %s\", key)\n\t}\n\n\troi, isROI := r.reconciler.(ReadOnlyInterface)\n\n\tisLeader := r.IsLeaderFor(types.NamespacedName{\n\t\tNamespace: namespace,\n\t\tName: name,\n\t})\n\n\treturn &state{\n\t\tkey: key,\n\t\tnamespace: namespace,\n\t\tname: name,\n\t\treconciler: r.reconciler,\n\t\troi: roi,\n\t\tisROI: isROI,\n\t\tisLeader: isLeader,\n\t}, nil\n}\n\n\n\n\n\nfunc (s *state) isNotLeaderNorObserver() bool {\n\tif !s.isLeader && !s.isROI {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc (s *state) reconcileMethodFor(o *v1alpha1.KafkaSink) (string, doReconcile) ", "output": "{\n\tif o.GetDeletionTimestamp().IsZero() {\n\t\tif s.isLeader {\n\t\t\treturn reconciler.DoReconcileKind, s.reconciler.ReconcileKind\n\t\t} else if s.isROI {\n\t\t\treturn reconciler.DoObserveKind, s.roi.ObserveKind\n\t\t}\n\t} else if fin, ok := s.reconciler.(Finalizer); s.isLeader && ok {\n\t\treturn reconciler.DoFinalizeKind, fin.FinalizeKind\n\t}\n\treturn \"unknown\", nil\n}"} {"input": "package policy\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/rightscale/rsc/rsapi\"\n)\n\nconst (\n\tAPIName = \"RightScale Policy API 1.0\"\n)\n\n\nvar commandValues rsapi.ActionCommands\n\n\nfunc RegisterCommands(registrar rsapi.APICommandRegistrar) {\n\tcommandValues = rsapi.ActionCommands{}\n\tregistrar.RegisterActionCommands(APIName, GenMetadata, commandValues)\n}\n\n\n\n\n\nfunc (a *API) ShowCommandHelp(cmd string) error {\n\treturn a.ShowHelp(cmd, \"/api\", commandValues)\n}\n\n\nfunc (a *API) ShowAPIActions(cmd string) error {\n\treturn a.ShowActions(cmd, \"/api\", commandValues)\n}\n\nfunc (a *API) RunCommand(cmd string) (*http.Response, error) ", "output": "{\n\tc, err := a.ParseCommand(cmd, \"/api\", commandValues)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := a.BuildHTTPRequest(c.HTTPMethod, c.URI, \"1.0\", c.QueryParams, c.PayloadParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn a.PerformRequest(req)\n}"} {"input": "package api2go\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\ntype APIContextAllocatorFunc func(*API) APIContexter\n\n\ntype APIContexter interface {\n\tcontext.Context\n\tSet(key string, value interface{})\n\tGet(key string) (interface{}, bool)\n\tReset()\n}\n\n\ntype APIContext struct {\n\tkeys map[string]interface{}\n}\n\n\nfunc (c *APIContext) Set(key string, value interface{}) {\n\tif c.keys == nil {\n\t\tc.keys = make(map[string]interface{})\n\t}\n\tc.keys[key] = value\n}\n\n\nfunc (c *APIContext) Get(key string) (value interface{}, exists bool) {\n\tif c.keys != nil {\n\t\tvalue, exists = c.keys[key]\n\t}\n\treturn\n}\n\n\nfunc (c *APIContext) Reset() {\n\tc.keys = nil\n}\n\n\nfunc (c *APIContext) Deadline() (deadline time.Time, ok bool) {\n\treturn\n}\n\n\nfunc (c *APIContext) Done() <-chan struct{} {\n\treturn nil\n}\n\n\nfunc (c *APIContext) Err() error {\n\treturn nil\n}\n\n\n\n\n\nvar _ APIContexter = &APIContext{}\n\n\nfunc ContextQueryParams(c *APIContext) map[string][]string {\n\tqp, ok := c.Get(\"QueryParams\")\n\tif ok == false {\n\t\tqp = make(map[string][]string)\n\t\tc.Set(\"QueryParams\", qp)\n\t}\n\treturn qp.(map[string][]string)\n}\n\nfunc (c *APIContext) Value(key interface{}) interface{} ", "output": "{\n\tif keyAsString, ok := key.(string); ok {\n\t\tval, _ := c.Get(keyAsString)\n\t\treturn val\n\t}\n\treturn nil\n}"} {"input": "package sample\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n)\n\ntype sampleState struct {\n\trate uint64\n\tseed int64\n\tsampleCount uint64\n\ttrueCount uint64\n\trnd *rand.Rand\n}\n\n\ntype Sampler interface {\n\tSample() bool\n\tSampleFrom(probe uint64) bool\n\tState\n}\n\n\ntype State interface {\n\tReset()\n\tString() string\n\tRate() uint64\n\tCalls() uint64\n\tCount() uint64\n}\n\nfunc (state *sampleState) Rate() uint64 {\n\tif state != nil {\n\t\treturn state.rate\n\t}\n\treturn 0\n}\n\nfunc (state *sampleState) Calls() uint64 {\n\tif state != nil {\n\t\treturn state.sampleCount\n\t}\n\treturn 0\n}\n\nfunc (state *sampleState) Count() uint64 {\n\tif state != nil {\n\t\treturn state.trueCount\n\t}\n\treturn 0\n}\n\n\n\nfunc (state *sampleState) String() string {\n\ttype X *sampleState\n\tx := X(state)\n\treturn fmt.Sprintf(\"%+v\", x)\n}\n\n\nfunc Deviation(state State) (deviation float64) {\n\tif state != nil && state.Count() > 0 {\n\t\tdeviation = 1.0 - 1.0/float64(state.Rate())*(float64(state.Calls())/float64(state.Count()))\n\t} else {\n\t\tdeviation = 1.0\n\t}\n\n\treturn\n}\n\n\nfunc Stats(state State) string {\n\tif state != nil {\n\t\treturn fmt.Sprintf(\"Rate: %d, SampleCount: %d, TrueCount: %d, Deviation: %.4f%%\", state.Rate(), state.Calls(), state.Count(), Deviation(state)*100.0)\n\t}\n\treturn \"No state provided\"\n}\n\nfunc (state *sampleState) Reset() ", "output": "{\n\tstate.rnd.Seed(state.seed)\n\tstate.sampleCount = 0\n\tstate.trueCount = 0\n}"} {"input": "package fgae\n\nimport(\n\t\"golang.org/x/net/context\"\n\t\"github.com/skypies/util/gcp/ds\"\n\tfdb \"github.com/skypies/flightdb\"\n)\n\n\ntype FlightIterator ds.Iterator\n\nfunc NewFlightIterator(ctx context.Context, p ds.DatastoreProvider, fq *FQuery) *FlightIterator {\n\tit := ds.NewIterator(ctx, p, (*ds.Query)(fq), fdb.IndexedFlightBlob{})\n\treturn (*FlightIterator)(it)\n}\n\nfunc (fi *FlightIterator)Iterate(ctx context.Context) bool {\n\tit := (*ds.Iterator)(fi)\n\treturn it.Iterate(ctx)\n}\n\nfunc (fi *FlightIterator)Err() error {\n\tit := (*ds.Iterator)(fi)\n\treturn it.Err()\n}\n\n\n\nfunc (fi *FlightIterator)Flight() *fdb.Flight ", "output": "{\n\tblob := fdb.IndexedFlightBlob{}\n\n\tit := (*ds.Iterator)(fi)\n\tkeyer := it.Val(&blob)\n\n\tf, err := blob.ToFlight(keyer.Encode())\n\tif err != nil {\n\t\tit.SetErr(err)\n\t\treturn nil\n\t}\n\n\treturn f\n}"} {"input": "package strings\n\nimport (\n\t\"strings\"\n)\n\n\nfunc RemoveSpace(s string) (d string) {\n\tif IsBlank(s) {\n\t\treturn\n\t}\n\td = s\n\tsps := [...]string{\"\\t\", \"\\n\", \"\\v\", \"\\f\", \"\\r\", \" \"}\n\tfor _, sp := range sps {\n\t\td = strings.Replace(d, sp, \"\", -1)\n\t}\n\treturn\n}\n\n\nfunc RemoveBlank(s string) (d string) {\n\tif IsBlank(s) {\n\t\treturn\n\t}\n\td = strings.TrimSpace(s)\n\tsps := [...]string{\"\\t\", \"\\n\", \"\\v\", \"\\f\", \"\\r\", \" \"}\n\tfor _, sp := range sps {\n\t\td = strings.Replace(d, sp, \"\", -1)\n\t}\n\treturn\n}\n\n\n\nfunc RemoveStart(s, remove string) string {\n\tif IsBlank(s) || IsBlank(remove) {\n\t\treturn s\n\t}\n\tif strings.HasPrefix(s, remove) {\n\t\treturn s[len(remove):]\n\t}\n\treturn s\n}\n\n\n\nfunc RemoveEnd(s, remove string) string {\n\tif IsBlank(s) || IsBlank(remove) {\n\t\treturn s\n\t}\n\tif strings.HasSuffix(s, remove) {\n\t\treturn s[0 : len(s)-len(remove)]\n\t}\n\treturn s\n}\n\n\n\n\nfunc Remove(s, remove string) string ", "output": "{\n\tif IsBlank(s) || IsBlank(remove) {\n\t\treturn s\n\t}\n\treturn strings.Replace(s, remove, \"\", -1)\n}"} {"input": "package textanalytics\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/cognitiveservices/v2.0/textanalytics\"\n\ntype BaseClient = original.BaseClient\ntype AzureRegions = original.AzureRegions\n\nconst (\n\tAustraliaeast AzureRegions = original.Australiaeast\n\tBrazilsouth AzureRegions = original.Brazilsouth\n\tEastasia AzureRegions = original.Eastasia\n\tEastus AzureRegions = original.Eastus\n\tEastus2 AzureRegions = original.Eastus2\n\tNortheurope AzureRegions = original.Northeurope\n\tSouthcentralus AzureRegions = original.Southcentralus\n\tSoutheastasia AzureRegions = original.Southeastasia\n\tWestcentralus AzureRegions = original.Westcentralus\n\tWesteurope AzureRegions = original.Westeurope\n\tWestus AzureRegions = original.Westus\n\tWestus2 AzureRegions = original.Westus2\n)\n\ntype BatchInput = original.BatchInput\ntype DetectedLanguage = original.DetectedLanguage\ntype ErrorRecord = original.ErrorRecord\ntype ErrorResponse = original.ErrorResponse\ntype Input = original.Input\ntype InternalError = original.InternalError\ntype KeyPhraseBatchResult = original.KeyPhraseBatchResult\ntype KeyPhraseBatchResultItem = original.KeyPhraseBatchResultItem\ntype LanguageBatchResult = original.LanguageBatchResult\ntype LanguageBatchResultItem = original.LanguageBatchResultItem\ntype MultiLanguageBatchInput = original.MultiLanguageBatchInput\ntype MultiLanguageInput = original.MultiLanguageInput\ntype SentimentBatchResult = original.SentimentBatchResult\ntype SentimentBatchResultItem = original.SentimentBatchResultItem\n\nfunc New(azureRegion AzureRegions) BaseClient {\n\treturn original.New(azureRegion)\n}\n\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/latest\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\n\nfunc NewWithoutDefaults(azureRegion AzureRegions) BaseClient ", "output": "{\n\treturn original.NewWithoutDefaults(azureRegion)\n}"} {"input": "package handlers\n\nimport (\n\t\"github.com/bbiskup/edify-web/defs\"\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n)\n\nvar indexTemplates *template.Template\n\n\n\nfunc Index(w http.ResponseWriter, r *http.Request) {\n\terr := indexTemplates.ExecuteTemplate(w, \"layout\", nil)\n\tif err != nil {\n\t\tlog.Printf(\"Error executing template: %s\", err)\n\t}\n}\n\nfunc init() ", "output": "{\n\tindexTemplates = template.Must(template.ParseFiles(\n\t\tdefs.TemplatePaths(\"layout.html\", \"navbar.html\", \"index.html\")...,\n\t))\n}"} {"input": "package errors\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\n\t\"github.com/openshift/origin/pkg/cmd/errors\"\n)\n\nconst (\n\tKubeConfigFileSolutionWindows = `\nMake sure that the value of the --config flag passed contains a valid path:\n --config=c:\\path\\to\\valid\\file\n`\n\tKubeConfigFileSolutionUnix = `\nMake sure that the value of the --config flag passed contains a valid path:\n --config=/path/to/valid/file\n`\n\tKubeConfigSolutionUnix = `\nYou can unset the KUBECONFIG variable to use the default location for it:\n unset KUBECONFIG\n\nOr you can set its value to a file that can be written to:\n export KUBECONFIG=/path/to/file\n`\n\n\tKubeConfigSolutionWindows = `\nYou can clear the KUBECONFIG variable to use the default location for it:\n set KUBECONFIG=\n\nOr you can set its value to a file that can be written to:\n set KUBECONFIG=c:\\path\\to\\file`\n)\n\n\n\n\n\nfunc kubeConfigSolution(isExplicitFile bool) string {\n\tswitch runtime.GOOS {\n\tcase \"windows\":\n\t\tif isExplicitFile {\n\t\t\treturn KubeConfigFileSolutionWindows\n\t\t}\n\t\treturn KubeConfigSolutionWindows\n\tdefault:\n\t\tif isExplicitFile {\n\t\t\treturn KubeConfigFileSolutionUnix\n\t\t}\n\t\treturn KubeConfigSolutionUnix\n\t}\n}\n\n\nfunc NoProjectsExistMessage(canRequestProjects bool, commandName string) string {\n\tif !canRequestProjects {\n\t\treturn fmt.Sprintf(\"You don't have any projects. Contact your system administrator to request a project.\\n\")\n\t}\n\treturn fmt.Sprintf(`You don't have any projects. You can try to create a new project, by running\n\n %s new-project \n\n`, commandName)\n}\n\nfunc ErrKubeConfigNotWriteable(file string, isExplicitFile bool, err error) error ", "output": "{\n\treturn errors.NewError(\"KUBECONFIG is set to a file that cannot be created or modified: %s\", file).WithCause(err).WithSolution(kubeConfigSolution(isExplicitFile))\n}"} {"input": "package avl\n\n\nfunc (tree *Tree) First() *Node {\n\treturn tree.root.first()\n}\n\n\nfunc (tree *Node) first() *Node {\n\tif nil == tree {\n\t\treturn nil\n\t}\n\tfor nil != tree.left {\n\t\ttree = tree.left\n\t}\n\treturn tree\n}\n\n\nfunc (tree *Tree) Last() *Node {\n\treturn tree.root.last()\n}\n\n\n\n\n\n\nfunc (tree *Node) Next() *Node {\n\tif nil == tree.right {\n\t\tkey := tree.key\n\t\tfor {\n\t\t\ttree = tree.up\n\t\t\tif nil == tree {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif 1 == tree.key.Compare(key) { \n\t\t\t\treturn tree\n\t\t\t}\n\t\t}\n\t}\n\treturn tree.right.first()\n}\n\n\n\nfunc (tree *Node) Prev() *Node {\n\tif nil == tree.left {\n\t\tkey := tree.key\n\t\tfor {\n\t\t\ttree = tree.up\n\t\t\tif nil == tree {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif -1 == tree.key.Compare(key) { \n\t\t\t\treturn tree\n\t\t\t}\n\t\t}\n\t}\n\treturn tree.left.last()\n}\n\nfunc (tree *Node) last() *Node ", "output": "{\n\tif nil == tree {\n\t\treturn nil\n\t}\n\tfor nil != tree.right {\n\t\ttree = tree.right\n\t}\n\treturn tree\n}"} {"input": "package gospec\n\nimport (\n\t\"fmt\"\n\tfilepath \"path\"\n\t\"runtime\"\n)\n\ntype Location struct {\n\tname string\n\tfile string\n\tline int\n}\n\nfunc currentLocation() *Location {\n\treturn newLocation(1)\n}\n\nfunc callerLocation() *Location {\n\treturn newLocation(2)\n}\n\nfunc newLocation(n int) *Location {\n\tif pc, _, _, ok := runtime.Caller(n + 1); ok {\n\t\treturn locationForPC(pc)\n\t}\n\treturn nil\n}\n\nfunc locationForPC(pc uintptr) *Location {\n\tpc = pcOfWhereCallWasMade(pc)\n\tf := runtime.FuncForPC(pc)\n\tname := f.Name()\n\tfile, line := f.FileLine(pc)\n\treturn &Location{name, file, line}\n}\n\n\n\n\n\n\n\n\nfunc pcOfWhereCallWasMade(pcOfWhereCallReturnsTo uintptr) uintptr {\n\treturn pcOfWhereCallReturnsTo - 1\n}\n\nfunc (this *Location) Name() string { return this.name }\nfunc (this *Location) File() string { return this.file }\nfunc (this *Location) FileName() string { return filename(this.file) }\nfunc (this *Location) Line() int { return this.line }\n\n\n\nfunc (this *Location) equals(that *Location) bool {\n\treturn this.name == that.name &&\n\t\tthis.file == that.file &&\n\t\tthis.line == that.line\n}\n\nfunc (this *Location) String() string {\n\treturn fmt.Sprintf(\"%v:%v\", this.FileName(), this.Line())\n}\n\nfunc filename(path string) string ", "output": "{\n\t_, file := filepath.Split(path)\n\treturn file\n}"} {"input": "package aggfuncs_test\n\nimport (\n\t. \"github.com/pingcap/check\"\n\t\"github.com/pingcap/parser/ast\"\n\t\"github.com/pingcap/parser/mysql\"\n)\n\n\n\nfunc (s *testSuite) TestVarsamp(c *C) {\n\ttests := []aggTest{\n\t\tbuildAggTester(ast.AggFuncVarSamp, mysql.TypeDouble, 5, nil, 2.5),\n\t}\n\tfor _, test := range tests {\n\t\ts.testAggFunc(c, test)\n\t}\n}\n\nfunc (s *testSuite) TestMergePartialResult4Varsamp(c *C) ", "output": "{\n\ttests := []aggTest{\n\t\tbuildAggTester(ast.AggFuncVarSamp, mysql.TypeDouble, 5, 2.5, 1, 1.9821428571428572),\n\t}\n\tfor _, test := range tests {\n\t\ts.testMergePartialResult(c, test)\n\t}\n}"} {"input": "package output\n\nimport \"reflect\"\n\n\ntype S3Grantee struct {\n\tID string `json:\"id\"`\n\tType string `json:\"type\"`\n\tPermissions string `json:\"permissions\"`\n}\n\n\ntype S3 struct {\n\tProviderType string `json:\"_type\"`\n\tDatacenterName string `json:\"datacenter_name,omitempty\"`\n\tDatacenterRegion string `json:\"datacenter_region\"`\n\tAccessKeyID string `json:\"aws_access_key_id\"`\n\tSecretAccessKey string `json:\"aws_secret_access_key\"`\n\tName string `json:\"name\"`\n\tACL string `json:\"acl\"`\n\tBucketLocation string `json:\"bucket_location\"`\n\tBucketURI string `json:\"bucket_uri\"`\n\tGrantees []S3Grantee `json:\"grantees,omitempty\"`\n\tTags map[string]string `json:\"tags\"`\n\tService string `json:\"service\"`\n\tStatus string `json:\"status\"`\n\tExists bool\n}\n\n\nfunc (s *S3) HasChanged(os *S3) bool {\n\tif s.ACL != os.ACL {\n\t\treturn true\n\t}\n\n\tif len(s.Grantees) < 1 && len(os.Grantees) < 1 {\n\t\treturn false\n\t}\n\n\treturn !reflect.DeepEqual(s.Grantees, os.Grantees)\n}\n\n\n\n\n\nfunc (s S3) ProviderID() string {\n\treturn s.Name\n}\n\n\nfunc (s S3) ComponentName() string {\n\treturn s.Name\n}\n\nfunc (s S3) GetTags() map[string]string ", "output": "{\n\treturn s.Tags\n}"} {"input": "package httpserver\n\nimport (\n\t\"fmt\"\n\t\"github.com/devfeel/dotweb\"\n\t\"github.com/devfeel/tokenserver/config\"\n\t\"github.com/devfeel/tokenserver/framework/log\"\n\t\"strconv\"\n)\n\nfunc StartServer() error {\n\n\tapp := dotweb.New()\n\n\tapp.SetLogPath(config.CurrentConfig.Log.FilePath)\n\n\tInitRoute(app)\n\n\tinnerLogger := logger.GetInnerLogger()\n\n\tpprofport := config.CurrentConfig.HttpServer.PProfPort\n\tapp.SetPProfConfig(true, pprofport)\n\n\tport := config.CurrentConfig.HttpServer.HttpPort\n\tinnerLogger.Debug(\"dotweb.StartServer => \" + strconv.Itoa(port))\n\terr := app.StartServer(port)\n\treturn err\n}\n\n\n\nfunc ReSetServer() ", "output": "{\n\tfmt.Println(\"ReSetServer\")\n}"} {"input": "package metrics\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\ntype GaugeMetric struct {\n\tvalue float64\n\tmutex sync.RWMutex\n}\n\nfunc (metric *GaugeMetric) Humanize() string {\n\tformatString := \"[GaugeMetric; value=%f]\"\n\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn fmt.Sprintf(formatString, metric.value)\n}\n\nfunc (metric *GaugeMetric) Set(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value = value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) IncrementBy(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value += value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Increment() float64 {\n\treturn metric.IncrementBy(1)\n}\n\n\n\nfunc (metric *GaugeMetric) Decrement() float64 {\n\treturn metric.DecrementBy(1)\n}\n\nfunc (metric *GaugeMetric) Get() float64 {\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Marshallable() map[string]interface{} {\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\tv := make(map[string]interface{}, 2)\n\n\tv[valueKey] = metric.value\n\tv[typeKey] = gaugeTypeValue\n\n\treturn v\n}\n\nfunc (metric *GaugeMetric) DecrementBy(value float64) float64 ", "output": "{\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value -= value\n\n\treturn metric.value\n}"} {"input": "package graceful\n\nimport \"crypto/tls\"\n\n\n\n\nfunc cloneTLSConfig(cfg *tls.Config) *tls.Config ", "output": "{\n\tc := *cfg\n\treturn &c\n}"} {"input": "package turtle\n\nimport (\n\t\"strings\"\n)\n\ntype DataSet struct {\n\ttriplecount int\n\tnscount int\n\tNamespaces map[string]string\n\tTriples []Triple\n}\n\nfunc newDataSet() *DataSet {\n\treturn &DataSet{\n\t\ttriplecount: 0,\n\t\tnscount: 0,\n\t\tNamespaces: make(map[string]string),\n\t\tTriples: []Triple{},\n\t}\n}\n\nfunc (d *DataSet) AddTripleStrings(subject, predicate, object string) {\n\td.triplecount += 1\n\td.Triples = append(d.Triples, MakeTriple(subject, predicate, object))\n}\n\nfunc (d *DataSet) AddTripleURIs(subject, predicate, object URI) {\n\td.triplecount += 1\n\td.Triples = append(d.Triples, Triple{subject, predicate, object})\n}\n\n\n\nfunc (d *DataSet) NumTriples() int {\n\treturn d.triplecount\n}\n\nfunc (d *DataSet) NumNamespaces() int {\n\treturn d.nscount\n}\n\nfunc (d *DataSet) addNamespace(prefix, namespace string) ", "output": "{\n\td.nscount += 1\n\tnamespace = strings.TrimRight(namespace, \"#\")\n\td.Namespaces[prefix] = namespace\n}"} {"input": "package common\n\nimport \"math/big\"\n\ntype _N_ [_S_]byte\n\nfunc BytesTo_N_(b []byte) _N_ {\n\tvar h _N_\n\th.SetBytes(b)\n\treturn h\n}\nfunc StringTo_N_(s string) _N_ { return BytesTo_N_([]byte(s)) }\nfunc BigTo_N_(b *big.Int) _N_ { return BytesTo_N_(b.Bytes()) }\nfunc HexTo_N_(s string) _N_ { return BytesTo_N_(FromHex(s)) }\n\n\n\n\nfunc (h _N_) Str() string { return string(h[:]) }\nfunc (h _N_) Bytes() []byte { return h[:] }\nfunc (h _N_) Big() *big.Int { return Bytes2Big(h[:]) }\nfunc (h _N_) Hex() string { return \"0x\" + Bytes2Hex(h[:]) }\n\n\n\n\n\nfunc (h *_N_) SetString(s string) { h.SetBytes([]byte(s)) }\n\n\nfunc (h *_N_) Set(other _N_) {\n\tfor i, v := range other {\n\t\th[i] = v\n\t}\n}\n\nfunc (h *_N_) SetBytes(b []byte) ", "output": "{\n\tif len(b) > len(h) {\n\t\tb = b[len(b)-_S_:]\n\t}\n\n\tfor i := len(b) - 1; i >= 0; i-- {\n\t\th[_S_-len(b)+i] = b[i]\n\t}\n}"} {"input": "package models\n\nimport \"fmt\"\n\ntype TaskManager struct {\n\ttasks []*Task\n\tlastID int64\n}\n\nfunc NewTaskManager() *TaskManager {\n\treturn &TaskManager{}\n}\n\nfunc (m *TaskManager) Tasks() []*Task {\n\treturn m.tasks\n}\n\n\n\nfunc (m *TaskManager) Find(id int64) (*Task, bool) {\n\tfor _, t := range m.tasks {\n\t\tif t.Id == id {\n\t\t\treturn t, true\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc (m *TaskManager) Add(task *Task) error ", "output": "{\n\tif task.Id == 0 {\n\t\tm.lastID++\n\t\ttask.Id = m.lastID\n\t\tm.tasks = append(m.tasks, task.clone())\n\t\treturn nil\n\t}\n\n\t_, found := m.Find(task.Id)\n\tif found {\n\t\tm.tasks[task.Id-1] = task\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"unknown task\")\n}"} {"input": "package koalanet\n\nimport \"testing\"\n\nvar t1 *testing.T\n\nvar tkm_arg1 int\n\ntype TestKoalanetMain struct {\n\tActor\n}\n\nfunc (tkm *TestKoalanetMain) Init(args interface{}, reply interface{}) error {\n\ttkm_arg1 = 2\n\treturn nil\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Benchmark_koalanet_send(b *testing.B) {\n\tRegActor(\"TestKoalanetMain\", func() IActor {\n\t\tactor := &TestKoalanetMain{}\n\t\tactor.InitActor()\n\t\tactor.RegMethod(\"Init\", actor.Init)\n\t\tactor.RegMethod(\"SendTest\", actor.SendTest)\n\t\treturn actor\n\t})\n\n\thTKM := NewActor(\"TestKoalanetMain\", nil)\n\n\tfor i := 0; i < b.N; i++ {\n\t\tSend(hTKM, \"SendTest\", nil)\n\t}\n\n\tKillActor(hTKM, false)\n\n\tWaitActorQuit(hTKM)\n}\n\nfunc (tkm *TestKoalanetMain) SendTest(args interface{}, reply interface{}) error ", "output": "{\n\n\treturn nil\n}"} {"input": "package problem0188\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\nvar tcs = []struct {\n\tk int\n prices []int\n\tans int\n}{\n\n\n\n}\n\nfunc Test_maxProfit(t *testing.T) {\n\ta := assert.New(t)\n\n\tfor _, tc := range tcs {\n\t\ta.Equal(tc.ans, maxProfit(tc.k, tc.prices), \"输入:%v\", tc)\n\t}\n}\n\n\n\nfunc Benchmark_maxProfit(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, tc := range tcs {\n\t\t\tmaxProfit(tc.k, tc.prices)\n\t\t}\n\t}\n}"} {"input": "package rest\n\nimport (\n\tc \"github.com/KoFish/pallium/config\"\n\t\"github.com/gorilla/mux\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n)\n\n\n\nfunc Start() {\n\tlog.Printf(\"matrix: starting service at %v\", c.Config.Listener)\n\tl, err := net.Listen(c.Config.ListenerProtocol, c.Config.Listener)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := http.Serve(l, nil); err != nil {\n\t\tlog.Printf(\"matrix: could not start up server \\\"%v\\\"\", err)\n\t}\n}\n\nfunc Setup() ", "output": "{\n\troot := mux.NewRouter()\n\troot.StrictSlash(false)\n\tclient_api_v1 := root.PathPrefix(\"/_matrix/client/api/v1\").Subrouter()\n\tfederation_v1 := root.PathPrefix(\"/_matrix/federation/v1\").Subrouter()\n\n\tsetupLogin(client_api_v1)\n\tsetupRegister(client_api_v1)\n\tsetupEvents(client_api_v1)\n\tsetupRooms(client_api_v1)\n\tsetupFederation(federation_v1)\n\tsetupProfile(client_api_v1)\n\tsetupPresence(client_api_v1)\n\tsetupVoip(client_api_v1)\n\n\thttp.Handle(\"/\", root)\n}"} {"input": "package tfs\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/richardwilkes/toolbox/errs\"\n)\n\ntype vfs struct {\n\tstorage string\n\tname string\n\toffset int64\n\tlength int64\n\tmode os.FileMode\n\tmodTime time.Time\n\tchildren []*vfs\n}\n\nfunc (v *vfs) Name() string {\n\treturn v.name\n}\n\n\n\nfunc (v *vfs) Mode() os.FileMode {\n\treturn v.mode\n}\n\nfunc (v *vfs) ModTime() time.Time {\n\treturn v.modTime\n}\n\nfunc (v *vfs) IsDir() bool {\n\treturn (v.mode & os.ModeDir) == os.ModeDir\n}\n\nfunc (v *vfs) Sys() interface{} {\n\treturn nil\n}\n\nfunc (v *vfs) open() (http.File, error) {\n\tif v.IsDir() {\n\t\treturn &vdir{owner: v}, nil\n\t}\n\tf, err := os.Open(v.storage)\n\tif err != nil {\n\t\treturn nil, errs.NewWithCausef(err, \"Unable to open %s\", v.name)\n\t}\n\treturn &vfile{\n\t\towner: v,\n\t\tfile: f,\n\t\tsr: io.NewSectionReader(f, v.offset, v.length),\n\t}, nil\n}\n\nfunc (v *vfs) Size() int64 ", "output": "{\n\treturn v.length\n}"} {"input": "package common\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/axgle/mahonia\"\n\t\"github.com/saintfish/chardet\"\n)\n\n\nfunc RequestURL(url string) (*http.Response, error) {\n\tclient := &http.Client{}\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Set(\"User-Agent\", GetUserAgent())\n\tresponse, err := client.Do(req)\n\treturn response, err\n}\n\n\nfunc QuickestURL(index int, url string) int {\n\t_, err := http.Get(url)\n\tif err != nil {\n\t\treturn -1\n\t}\n\treturn index\n}\n\n\n\n\n\nfunc StringInSlice(domain string, list []string) bool {\n\tfor _, eachDomain := range list {\n\t\tif domain == eachDomain {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc ReturnDomain(currentURL string) string {\n\turlParse, _ := url.Parse(currentURL)\n\tdomain := urlParse.Host\n\treturn domain\n}\n\nfunc DetectBody(body []byte) string ", "output": "{\n\tvar bodyString string\n\tdetector := chardet.NewTextDetector()\n\tresult, err := detector.DetectBest(body)\n\tif err != nil {\n\t\treturn string(body)\n\t}\n\tif strings.Contains(strings.ToLower(result.Charset), \"utf\") {\n\t\tbodyString = string(body)\n\t} else {\n\t\tbodyString = mahonia.NewDecoder(\"gbk\").ConvertString(string(body))\n\t}\n\treturn bodyString\n}"} {"input": "package options\n\nimport (\n\t\"github.com/spf13/pflag\"\n\n\tjobconfig \"k8s.io/kubernetes/pkg/controller/job/config\"\n)\n\n\ntype JobControllerOptions struct {\n\t*jobconfig.JobControllerConfiguration\n}\n\n\nfunc (o *JobControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n}\n\n\nfunc (o *JobControllerOptions) ApplyTo(cfg *jobconfig.JobControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentJobSyncs = o.ConcurrentJobSyncs\n\n\treturn nil\n}\n\n\n\n\nfunc (o *JobControllerOptions) Validate() []error ", "output": "{\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestMoveBlanksToEnd(t *testing.T) ", "output": "{\n\tassert.Equal(t, moveBlanksToEnd(\"?\"), \"?\")\n\tassert.Equal(t, moveBlanksToEnd(\"I?\"), \"I?\")\n\tassert.Equal(t, moveBlanksToEnd(\"?AB?C\"), \"ABC??\")\n\tassert.Equal(t, moveBlanksToEnd(\"??\"), \"??\")\n\tassert.Equal(t, moveBlanksToEnd(\"?FED\"), \"FED?\")\n\tassert.Equal(t, moveBlanksToEnd(\"X?X\"), \"XX?\")\n}"} {"input": "package goldengate\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ChangeDeploymentCompartmentRequest struct {\n\n\tDeploymentId *string `mandatory:\"true\" contributesTo:\"path\" name:\"deploymentId\"`\n\n\tChangeDeploymentCompartmentDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ChangeDeploymentCompartmentRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ChangeDeploymentCompartmentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ChangeDeploymentCompartmentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ChangeDeploymentCompartmentRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ChangeDeploymentCompartmentResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response ChangeDeploymentCompartmentResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response ChangeDeploymentCompartmentResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package elements\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"log\"\n)\n\ntype ElementsGroup struct {\n\tChoice []*ElementsGroupChoice\n}\n\nfunc NewElementsGroup() *ElementsGroup {\n\tret := &ElementsGroup{}\n\treturn ret\n}\n\n\n\nfunc (m *ElementsGroup) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\nlElementsGroup:\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch el := tok.(type) {\n\t\tcase xml.StartElement:\n\t\t\tswitch el.Name {\n\t\t\tcase xml.Name{Space: \"http:purl.org/dc/elements/1.1/\", Local: \"any\"}:\n\t\t\t\ttmp := NewElementsGroupChoice()\n\t\t\t\tif err := d.DecodeElement(&tmp.Any, &el); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tm.Choice = append(m.Choice, tmp)\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"skipping unsupported element on ElementsGroup %v\", el.Name)\n\t\t\t\tif err := d.Skip(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\tcase xml.EndElement:\n\t\t\tbreak lElementsGroup\n\t\tcase xml.CharData:\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (m *ElementsGroup) Validate() error {\n\treturn m.ValidateWithPath(\"ElementsGroup\")\n}\n\n\nfunc (m *ElementsGroup) ValidateWithPath(path string) error {\n\tfor i, v := range m.Choice {\n\t\tif err := v.ValidateWithPath(fmt.Sprintf(\"%s/Choice[%d]\", path, i)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *ElementsGroup) MarshalXML(e *xml.Encoder, start xml.StartElement) error ", "output": "{\n\tif m.Choice != nil {\n\t\tfor _, c := range m.Choice {\n\t\t\tc.MarshalXML(e, xml.StartElement{})\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package os\n\nimport (\n\t\"syscall\"\n)\n\n\n\nfunc (f *File) Stat() (FileInfo, error) {\n\tif f == nil {\n\t\treturn nil, ErrInvalid\n\t}\n\tvar fs fileStat\n\terr := f.pfd.Fstat(&fs.sys)\n\tif err != nil {\n\t\treturn nil, &PathError{\"stat\", f.name, err}\n\t}\n\tfillFileStatFromSys(&fs, f.name)\n\treturn &fs, nil\n}\n\n\n\nfunc Stat(name string) (FileInfo, error) {\n\tvar fs fileStat\n\terr := syscall.Stat(name, &fs.sys)\n\tif err != nil {\n\t\treturn nil, &PathError{\"stat\", name, err}\n\t}\n\tfillFileStatFromSys(&fs, name)\n\treturn &fs, nil\n}\n\n\n\n\n\n\n\nfunc Lstat(name string) (FileInfo, error) ", "output": "{\n\tvar fs fileStat\n\terr := syscall.Lstat(name, &fs.sys)\n\tif err != nil {\n\t\treturn nil, &PathError{\"lstat\", name, err}\n\t}\n\tfillFileStatFromSys(&fs, name)\n\treturn &fs, nil\n}"} {"input": "package anthapath\n\nimport (\n\t\"os\"\n\t\"os/user\"\n\t\"path/filepath\"\n)\n\n\n\n\n\nfunc Exists(filename string) bool {\n\tp := filepath.Join(Path(), filename)\n\n\tif _, err := os.Stat(p); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc Path() string ", "output": "{\n\tu, err := user.Current()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn filepath.Join(u.HomeDir, \".antha\")\n}"} {"input": "package naivecheap\n\nimport \"github.com/ffloyd/evergrid-go/global/types\"\n\ntype byPriceAsc []types.WorkerInfo\n\nfunc (sw byPriceAsc) Len() int {\n\treturn len(sw)\n}\n\nfunc (sw byPriceAsc) Swap(i, j int) {\n\tsw[i], sw[j] = sw[j], sw[i]\n}\n\nfunc (sw byPriceAsc) Less(i, j int) bool {\n\treturn sw[i].PricePerTick < sw[j].PricePerTick \n}\n\ntype byQueueAsc []types.WorkerInfo\n\n\n\nfunc (sw byQueueAsc) Swap(i, j int) {\n\tsw[i], sw[j] = sw[j], sw[i]\n}\n\nfunc (sw byQueueAsc) Less(i, j int) bool {\n\treturn sw[i].QueueLength < sw[j].QueueLength \n}\n\nfunc (sw byQueueAsc) Len() int ", "output": "{\n\treturn len(sw)\n}"} {"input": "package elastic\n\n\n\n\n\n\n\n\n\ntype MissingAggregation struct {\n\tfield string\n\tsubAggregations map[string]Aggregation\n\tmeta map[string]interface{}\n}\n\nfunc NewMissingAggregation() *MissingAggregation {\n\treturn &MissingAggregation{\n\t\tsubAggregations: make(map[string]Aggregation),\n\t}\n}\n\nfunc (a *MissingAggregation) Field(field string) *MissingAggregation {\n\ta.field = field\n\treturn a\n}\n\n\n\n\nfunc (a *MissingAggregation) Meta(metaData map[string]interface{}) *MissingAggregation {\n\ta.meta = metaData\n\treturn a\n}\n\nfunc (a *MissingAggregation) Source() (interface{}, error) {\n\n\tsource := make(map[string]interface{})\n\topts := make(map[string]interface{})\n\tsource[\"missing\"] = opts\n\n\tif a.field != \"\" {\n\t\topts[\"field\"] = a.field\n\t}\n\n\tif len(a.subAggregations) > 0 {\n\t\taggsMap := make(map[string]interface{})\n\t\tsource[\"aggregations\"] = aggsMap\n\t\tfor name, aggregate := range a.subAggregations {\n\t\t\tsrc, err := aggregate.Source()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\taggsMap[name] = src\n\t\t}\n\t}\n\n\tif len(a.meta) > 0 {\n\t\tsource[\"meta\"] = a.meta\n\t}\n\n\treturn source, nil\n}\n\nfunc (a *MissingAggregation) SubAggregation(name string, subAggregation Aggregation) *MissingAggregation ", "output": "{\n\ta.subAggregations[name] = subAggregation\n\treturn a\n}"} {"input": "package compiler\n\nimport (\n\t\"fmt\"\n\t\"mime/multipart\"\n\n\t\"github.com/h2oai/steam/lib/fs\"\n\t\"github.com/pkg/errors\"\n)\n\ntype Model struct {\n\tmodelPath string\n\tmodelType string\n\tjavaDep string\n\n\tpythonFiles pythonPackage\n}\n\n\n\nfunc (c *Model) AttachFiles(w *multipart.Writer) error {\n\tif err := attachFile(w, c.modelPath, c.modelType); err != nil {\n\t\treturn errors.Wrap(err, \"attaching model\")\n\t}\n\tif err := attachFile(w, c.javaDep, fileTypeJavaDep); err != nil {\n\t\treturn errors.Wrap(err, \"attaching java dependency\")\n\t}\n\n\tif c.pythonFiles.Main != \"\" {\n\t\tif err := attachFile(w, c.pythonFiles.Main, fileTypePythonMain); err != nil {\n\t\t\treturn errors.Wrap(err, \"attaching Python main file\")\n\t\t}\n\t\tfor _, file := range c.pythonFiles.Other {\n\t\t\tif err := attachFile(w, file, fileTypePythonOther); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"attaching Python file\")\n\t\t\t}\n\t\t}\n\t\tif c.pythonFiles.Yaml != \"\" {\n\t\t\tif err := attachFile(w, c.pythonFiles.Yaml, fileTypePythonEnv); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"attaching Python env file\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc NewModel(workingDirectory string, modelId int64, logicalName, modelType string, pythonFiles pythonPackage) *Model ", "output": "{\n\tm := &Model{javaDep: fs.GetGenModelPath(workingDirectory, modelId)}\n\n\tswitch modelType {\n\tcase \"pojo\":\n\t\tm.modelPath = fs.GetJavaModelPath(workingDirectory, modelId, logicalName)\n\t\tm.modelType = fileTypeJava\n\tcase \"mojo\":\n\t\tm.modelPath = fs.GetMOJOPath(workingDirectory, modelId, logicalName)\n\t\tm.modelType = fileTypeMOJO\n\tcase \"\":\n\t\tpanic(\"model type unset\")\n\tdefault:\n\t\tpanic(fmt.Errorf(\"invalid model type %q\", modelType))\n\t}\n\n\tm.pythonFiles = pythonFiles\n\n\treturn m\n}"} {"input": "package calendar\n\nimport (\n\t\"time\"\n)\n\nvar (\n\tentries = make(map[int]Entry)\n\tindex int\n)\n\ntype Entry struct {\n\tID int\n\tTitle string\n\tStarts time.Time\n\tFinishes time.Time\n}\n\nfunc (e Entry) Duration() time.Duration {\n\treturn e.Finishes.Sub(e.Starts)\n}\n\nfunc Lookup(id int) (Entry, bool) {\n\te, isPresent := entries[id]\n\treturn e, isPresent\n}\n\n\n\nfunc Update(e Entry) {\n\tentries[e.ID] = e\n}\n\nfunc Remove(id int) {\n\tdelete(entries, id)\n}\n\nfunc Count() int {\n\treturn len(entries)\n}\n\nfunc All() []Entry {\n\tall := []Entry{}\n\tfor _, e := range entries {\n\t\tall = append(all, e)\n\t}\n\treturn all\n}\n\nfunc Add(e Entry) Entry ", "output": "{\n\tindex++\n\te.ID = index\n\tUpdate(e)\n\treturn e\n}"} {"input": "package readers\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n)\n\nfunc init() {\n\tRegister(\"IOStat\", NewIOStat)\n}\n\nfunc NewIOStat() IReader {\n\tios := &IOStat{}\n\tios.Data = make(map[string]interface{})\n\treturn ios\n}\n\ntype IOStat struct {\n\tData map[string]interface{}\n}\n\n\n\n\n\nfunc (ios *IOStat) ToJson() ([]byte, error) {\n\treturn json.Marshal(ios.Data)\n}\n\nfunc (ios *IOStat) Run() error ", "output": "{\n\treturn errors.New(\"iostat -x is only available on Linux.\")\n}"} {"input": "package scene\n\nimport \"github.com/thinkofdeath/steven/ui\"\n\n\ntype Type struct {\n\tvisible bool\n\n\tdrawables []ui.Drawable\n\thidding bool\n}\n\n\nfunc New(visible bool) *Type {\n\treturn &Type{\n\t\tvisible: visible,\n\t}\n}\n\n\nfunc (t *Type) Show() {\n\tif t.visible {\n\t\treturn\n\t}\n\tt.visible = true\n\tfor _, d := range t.drawables {\n\t\tui.AddDrawable(d)\n\t}\n}\n\n\nfunc (t *Type) Hide() {\n\tif !t.visible {\n\t\treturn\n\t}\n\tt.visible = false\n\tt.hidding = true\n\tfor _, d := range t.drawables {\n\t\tui.Remove(d)\n\t}\n\tt.hidding = false\n}\n\n\n\n\nfunc (t *Type) removeHook(d ui.Drawable) {\n\tif t.hidding {\n\t\treturn\n\t}\n\tfor i, dd := range t.drawables {\n\t\tif dd == d {\n\t\t\tt.drawables = append(t.drawables[:i], t.drawables[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n\n}\n\n\nfunc (t *Type) IsVisible() bool {\n\treturn t.visible\n}\n\nfunc (t *Type) AddDrawable(d ui.Drawable) ", "output": "{\n\tt.drawables = append(t.drawables, d)\n\tif t.visible {\n\t\tui.AddDrawable(d)\n\t}\n\td.SetRemoveHook(t.removeHook)\n}"} {"input": "package aes_test\n\nimport (\n\t\"github.com/keep94/vsafe/aes\"\n\t\"testing\"\n)\n\nvar (\n\tsomeKey = []byte(\"12345678901234567890123456789012\")\n)\n\nfunc TestEncryptDecrypt(t *testing.T) {\n\tverifyEncryptDecrypt(t, \"aardvark\")\n\tverifyEncryptDecrypt(t, \"1234567890123456\")\n\tverifyEncryptDecrypt(t, \"1234567890123456 \")\n\tverifyEncryptDecrypt(t, \"123456789012345 \")\n\tverifyEncryptDecrypt(t, \" now is the time for all good men to come to the aid of their party \")\n}\n\n\n\nfunc TestEncryptSecurity(t *testing.T) {\n\tanotherKey := []byte(\"12345678901234567890123456789013\")\n\tencoded, err := aes.Encrypt(\"aardvark\", someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdecoded, _ := aes.Decrypt(encoded, anotherKey)\n\tif decoded == \"aardvark\" {\n\t\tt.Error(\"Expected different decryption with different key\")\n\t}\n}\n\nfunc verifyEncryptDecrypt(t *testing.T, plain string) {\n\tencoded, err := aes.Encrypt(plain, someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdecoded, err := aes.Decrypt(encoded, someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif decoded != plain {\n\t\tt.Errorf(\"Expected to get same thing back: '%s', got '%s' %d %d\", plain, decoded, len(plain), len(decoded))\n\t}\n}\n\nfunc TestEncryptsSameTextDifferently(t *testing.T) ", "output": "{\n\tencoded, err := aes.Encrypt(\"aardvark\", someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tencodedAgain, err := aes.Encrypt(\"aardvark\", someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif encoded == encodedAgain {\n\t\tt.Error(\"Expected same text to be encrypted differently every time.\")\n\t}\n}"} {"input": "package pluginerror\n\nimport \"fmt\"\n\n\n\ntype SSLValidationHostnameError struct {\n\tMessage string\n}\n\n\n\nfunc (e SSLValidationHostnameError) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"Hostname does not match SSL Certificate (%s)\", e.Message)\n}"} {"input": "package hcloud\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hashicorp/packer/packer\"\n)\n\nfunc TestArtifact_Impl(t *testing.T) {\n\tvar _ packer.Artifact = (*Artifact)(nil)\n}\n\nfunc TestArtifactId(t *testing.T) {\n\tgeneratedData := make(map[string]interface{})\n\ta := &Artifact{\"packer-foobar\", 42, nil, generatedData}\n\texpected := \"42\"\n\n\tif a.Id() != expected {\n\t\tt.Fatalf(\"artifact ID should match: %v\", expected)\n\t}\n}\n\nfunc TestArtifactString(t *testing.T) {\n\tgeneratedData := make(map[string]interface{})\n\ta := &Artifact{\"packer-foobar\", 42, nil, generatedData}\n\texpected := \"A snapshot was created: 'packer-foobar' (ID: 42)\"\n\n\tif a.String() != expected {\n\t\tt.Fatalf(\"artifact string should match: %v\", expected)\n\t}\n}\n\n\n\nfunc TestArtifactState_StateData(t *testing.T) ", "output": "{\n\texpectedData := \"this is the data\"\n\tartifact := &Artifact{\n\t\tStateData: map[string]interface{}{\"state_data\": expectedData},\n\t}\n\n\tresult := artifact.State(\"state_data\")\n\tif result != expectedData {\n\t\tt.Fatalf(\"Bad: State data was %s instead of %s\", result, expectedData)\n\t}\n\n\tresult = artifact.State(\"invalid_key\")\n\tif result != nil {\n\t\tt.Fatalf(\"Bad: State should be nil for invalid state data name\")\n\t}\n\n\tartifact = &Artifact{}\n\tresult = artifact.State(\"key\")\n\tif result != nil {\n\t\tt.Fatalf(\"Bad: State should be nil for nil StateData\")\n\t}\n}"} {"input": "package qemu\n\nimport (\n\t\"context\"\n\t\"github.com/oklog/ulid\"\n\t\"os\"\n\t\"os/exec\"\n)\n\ntype DiskCache string\n\nconst (\n\tCacheWriteThrough DiskCache = \"writethrough\"\n\tCacheWriteBack DiskCache = \"writeback\"\n\tCacheNone DiskCache = \"none\"\n\tCacheUnsafe DiskCache = \"unsafe\"\n\tCacheDirectSync DiskCache = \"directsync\"\n)\n\ntype NetworkDevice struct {\n\tInterfaceName string\n\tMacAddress string\n}\n\ntype StorageDevice struct {\n\tPool string\n\tDisk string\n\tCache DiskCache\n}\n\ntype VirtualMachine struct {\n\tId ulid.ULID\n\tVncPort int\n\tCpu string\n\tRoot string\n\tNICs []NetworkDevice\n\tDisks []StorageDevice\n\tMemLock bool\n\tVhostNet bool\n\tRAM int\n\tNumCPUs int\n\n\tcmd *exec.Cmd\n\tfiles []*os.File\n\tmon *Monitor\n}\n\nfunc (vm *VirtualMachine) Monitor() *Monitor {\n\tif vm.mon == nil {\n\t\tpanic(\"Monitor() call on uninitialized VM\")\n\t}\n\treturn vm.mon\n}\n\n\n\nfunc (vm *VirtualMachine) Release(ctx context.Context) {\n\terr := vm.cmd.Process.Release()\n\tif err != nil {\n\t\tlogger.Error(ctx, \"failed to release vm process\", \"vm_id\", vm.Id, \"process\", vm.cmd.Process.Pid, \"error\", err)\n\t}\n}\n\nfunc (vm *VirtualMachine) Kill(ctx context.Context) ", "output": "{\n\terr := vm.cmd.Process.Kill()\n\tif err != nil {\n\t\tlogger.Error(ctx, \"failed to kill vm process\", \"vm_id\", vm.Id, \"process\", vm.cmd.Process.Pid, \"error\", err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-chi/chi\"\n)\n\ntype todosResource struct{}\n\n\nfunc (rs todosResource) Routes() chi.Router {\n\tr := chi.NewRouter()\n\n\tr.Get(\"/\", rs.List) \n\tr.Post(\"/\", rs.Create) \n\tr.Put(\"/\", rs.Delete)\n\n\tr.Route(\"/{id}\", func(r chi.Router) {\n\t\tr.Get(\"/\", rs.Get) \n\t\tr.Put(\"/\", rs.Update) \n\t\tr.Delete(\"/\", rs.Delete) \n\t\tr.Get(\"/sync\", rs.Sync)\n\t})\n\n\treturn r\n}\n\nfunc (rs todosResource) List(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todos list of stuff..\"))\n}\n\nfunc (rs todosResource) Create(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todos create\"))\n}\n\nfunc (rs todosResource) Get(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo get\"))\n}\n\n\n\nfunc (rs todosResource) Delete(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo delete\"))\n}\n\nfunc (rs todosResource) Sync(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo sync\"))\n}\n\nfunc (rs todosResource) Update(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tw.Write([]byte(\"todo update\"))\n}"} {"input": "package logs \n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/model/otlpgrpc\"\n\t\"go.opentelemetry.io/collector/obsreport\"\n)\n\nconst (\n\tdataFormatProtobuf = \"protobuf\"\n\treceiverTransport = \"grpc\"\n)\n\n\ntype Receiver struct {\n\tnextConsumer consumer.Logs\n\tobsrecv *obsreport.Receiver\n}\n\n\nfunc New(id config.ComponentID, nextConsumer consumer.Logs, set component.ReceiverCreateSettings) *Receiver {\n\treturn &Receiver{\n\t\tnextConsumer: nextConsumer,\n\t\tobsrecv: obsreport.NewReceiver(obsreport.ReceiverSettings{\n\t\t\tReceiverID: id,\n\t\t\tTransport: receiverTransport,\n\t\t\tReceiverCreateSettings: set,\n\t\t}),\n\t}\n}\n\n\n\n\nfunc (r *Receiver) Export(ctx context.Context, req otlpgrpc.LogsRequest) (otlpgrpc.LogsResponse, error) ", "output": "{\n\tld := req.Logs()\n\tnumSpans := ld.LogRecordCount()\n\tif numSpans == 0 {\n\t\treturn otlpgrpc.NewLogsResponse(), nil\n\t}\n\n\tctx = r.obsrecv.StartLogsOp(ctx)\n\terr := r.nextConsumer.ConsumeLogs(ctx, ld)\n\tr.obsrecv.EndLogsOp(ctx, dataFormatProtobuf, numSpans, err)\n\n\treturn otlpgrpc.NewLogsResponse(), err\n}"} {"input": "package resourceapply\n\nimport (\n\t\"testing\"\n\n\t\"github.com/openshift/library-go/pkg/operator/events\"\n\t\"k8s.io/client-go/kubernetes/fake\"\n\n\t\"github.com/davecgh/go-spew/spew\"\n)\n\nfunc TestApplyDirectly(t *testing.T) {\n\trequiredObj, gvk, err := genericCodec.Decode([]byte(`apiVersion: v1\nkind: Namespace\nmetadata:\n name: openshift-apiserver\n labels:\n openshift.io/run-level: \"1\"\n`), nil, nil)\n\tt.Log(spew.Sdump(requiredObj))\n\tt.Log(spew.Sdump(gvk))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\n\nfunc TestApplyDirectlyUnhandledType(t *testing.T) ", "output": "{\n\tfakeClient := fake.NewSimpleClientset()\n\tcontent := func(name string) ([]byte, error) {\n\t\treturn []byte(`apiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n name: sample-claim\n labels:\n openshift.io/run-level: \"1\"\n`), nil\n\t}\n\trecorder := events.NewInMemoryRecorder(\"\")\n\tret := ApplyDirectly(fakeClient, recorder, content, \"pvc\")\n\tif ret[0].Error == nil {\n\t\tt.Fatal(\"missing expected error\")\n\t} else if ret[0].Error.Error() != \"unhandled type *v1.PersistentVolumeClaim\" {\n\t\tt.Fatal(ret[0].Error)\n\t}\n}"} {"input": "package system\n\nimport (\n\t\"github.com/juju/cmd\"\n\t\"github.com/juju/errors\"\n\t\"launchpad.net/gnuflag\"\n\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/cmd/envcmd\"\n)\n\nfunc newListBlocksCommand() cmd.Command {\n\treturn envcmd.WrapSystem(&listBlocksCommand{})\n}\n\n\ntype listBlocksCommand struct {\n\tenvcmd.SysCommandBase\n\tout cmd.Output\n\tapi listBlocksAPI\n\tapierr error\n}\n\nvar listBlocksDoc = `List all blocks for environments within the specified system`\n\n\n\ntype listBlocksAPI interface {\n\tClose() error\n\tListBlockedEnvironments() ([]params.EnvironmentBlockInfo, error)\n}\n\n\nfunc (c *listBlocksCommand) Info() *cmd.Info {\n\treturn &cmd.Info{\n\t\tName: \"list-blocks\",\n\t\tPurpose: \"list all blocks within the system\",\n\t\tDoc: listBlocksDoc,\n\t}\n}\n\n\n\n\nfunc (c *listBlocksCommand) getAPI() (listBlocksAPI, error) {\n\tif c.api != nil {\n\t\treturn c.api, c.apierr\n\t}\n\treturn c.NewSystemManagerAPIClient()\n}\n\n\nfunc (c *listBlocksCommand) Run(ctx *cmd.Context) error {\n\tapi, err := c.getAPI()\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"cannot connect to the API\")\n\t}\n\tdefer api.Close()\n\n\tenvs, err := api.ListBlockedEnvironments()\n\tif err != nil {\n\t\tlogger.Errorf(\"Unable to list blocked environments: %s\", err)\n\t\treturn err\n\t}\n\treturn c.out.Write(ctx, envs)\n}\n\nfunc (c *listBlocksCommand) SetFlags(f *gnuflag.FlagSet) ", "output": "{\n\tc.out.AddFlags(f, \"tabular\", map[string]cmd.Formatter{\n\t\t\"yaml\": cmd.FormatYaml,\n\t\t\"json\": cmd.FormatJson,\n\t\t\"tabular\": formatTabularBlockedEnvironments,\n\t})\n}"} {"input": "package file\n\nimport \"github.com/sandreas/graft/designpattern/observer\"\n\ntype WalkObserver struct {\n\tdesignpattern.ObserverInterface\n\titemCount int64\n\tmatchCount int64\n\terrorCount int64\n\tforceShow bool\n\toutputCallback func(format string, a ...interface{}) (int, error)\n\tInterval int64\n}\n\n\n\nfunc (ph *WalkObserver) Notify(a ...interface{}) {\n\tif a[0] == LocatorIncreaseItems {\n\t\tph.forceShow = ph.itemCount == 0\n\t\tph.itemCount++\n\t}\n\n\tif a[0] == LocatorIncreaseErrors {\n\t\tph.forceShow = ph.errorCount == 0\n\t\tph.errorCount++\n\t}\n\n\tif a[0] == LocatorIncreaseMatches {\n\t\tph.forceShow = ph.matchCount == 0\n\t\tph.itemCount++\n\t\tph.matchCount++\n\t}\n\n\tif a[0] == LocatorFinish {\n\t\tph.forceShow = true\n\t}\n\n\tph.showProgress()\n\n\tif a[0] == LocatorFinish {\n\t\tph.outputCallback(\"\\n\")\n\t}\n}\n\nfunc (ph *WalkObserver) showProgress() {\n\tif !ph.forceShow && ph.itemCount%ph.Interval != 0 {\n\t\treturn\n\t}\n\n\tif ph.errorCount == 0 {\n\t\tph.outputCallback(\"\\rscanning - total: %d, matches: %d\", ph.itemCount, ph.matchCount)\n\t} else {\n\t\tph.outputCallback(\"\\rscanning - total: %d, matches: %d, errors: %d\", ph.itemCount, ph.matchCount, ph.errorCount)\n\t}\n\n\tif ph.itemCount > ph.Interval*10 {\n\t\tph.Interval = 500\n\t}\n}\n\nfunc NewWalkObserver(handle func(format string, a ...interface{}) (int, error)) *WalkObserver ", "output": "{\n\treturn &WalkObserver{\n\t\tInterval: 100,\n\t\toutputCallback: handle,\n\t}\n}"} {"input": "package gzip\n\nimport (\n\t\"net/http\"\n\t\"path\"\n\n\t\"github.com/mholt/caddy/middleware\"\n)\n\n\ntype Filter interface {\n\tShouldCompress(*http.Request) bool\n}\n\n\nvar defaultExtensions = []string{\"\", \".txt\", \".htm\", \".html\", \".css\", \".php\", \".js\", \".json\", \".md\", \".xml\"}\n\n\nfunc DefaultExtFilter() ExtFilter {\n\tm := ExtFilter{Exts: make(Set)}\n\tfor _, extension := range defaultExtensions {\n\t\tm.Exts.Add(extension)\n\t}\n\treturn m\n}\n\n\ntype ExtFilter struct {\n\tExts Set\n}\n\n\nconst ExtWildCard = \"*\"\n\n\n\n\nfunc (e ExtFilter) ShouldCompress(r *http.Request) bool {\n\text := path.Ext(r.URL.Path)\n\treturn e.Exts.Contains(ExtWildCard) || e.Exts.Contains(ext)\n}\n\n\ntype PathFilter struct {\n\tIgnoredPaths Set\n}\n\n\n\n\n\n\n\ntype Set map[string]struct{}\n\n\nfunc (s Set) Add(value string) {\n\ts[value] = struct{}{}\n}\n\n\nfunc (s Set) Remove(value string) {\n\tdelete(s, value)\n}\n\n\nfunc (s Set) Contains(value string) bool {\n\t_, ok := s[value]\n\treturn ok\n}\n\n\n\n\nfunc (s Set) ContainsFunc(f func(string) bool) bool {\n\tfor k, _ := range s {\n\t\tif f(k) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p PathFilter) ShouldCompress(r *http.Request) bool ", "output": "{\n\treturn !p.IgnoredPaths.ContainsFunc(func(value string) bool {\n\t\treturn middleware.Path(r.URL.Path).Matches(value)\n\t})\n}"} {"input": "package github\n\nimport (\n . \"github.com/ErintLabs/trellohub/genapi\"\n \"log\"\n)\n\ntype Label struct {\n Name string `json:\"name\"`\n}\n\ntype GitUser struct {\n Name string `json:\"login\"`\n}\n\nfunc (issue *Issue) SetLabels(lbls []Label) {\n lst := make([]string, len(lbls))\n for i, v := range lbls {\n lst[i] = v.Name\n }\n issue.Labels.SetNameable(lst)\n}\n\nfunc (issue *Issue) SetMembers(mbmrs []GitUser) {\n lst := make([]string, len(mbmrs))\n for i, v := range mbmrs {\n lst[i] = v.Name\n }\n issue.Members.SetNameable(lst)\n}\n\n\n\n\n\n\n\nfunc (issue *Issue) DelLabel(label string) {\n log.Printf(\"Removing label %s from %s\", label, issue.String())\n GenDEL(issue.github, issue.ApiURL() + \"/labels/\" + label) \n}\n\n\ntype userAssignRequest struct {\n Assigs []string `json:\"assignees\"`\n}\n\nfunc (issue *Issue) AddUser(user string) {\n log.Printf(\"Adding user %s to %s\", user, issue.String())\n payload := userAssignRequest{ []string{ user } }\n GenPOSTJSON(issue.github, issue.ApiURL() + \"/assignees\", nil, &payload)\n}\n\n\nfunc (issue *Issue) DelUser(user string) {\n log.Printf(\"Removing user %s from %s\", user, issue.String())\n payload := userAssignRequest{ []string{ user } }\n GenDELJSON(issue.github, issue.ApiURL() + \"/assignees\", &payload)\n}\n\nfunc (issue *Issue) AddLabel(label string) ", "output": "{\n log.Printf(\"Adding label %s to %s\", label, issue.String())\n lbls := [...]string { label }\n GenPOSTJSON(issue.github, issue.ApiURL() + \"/labels\", nil, &lbls)\n}"} {"input": "package clock\n\nimport (\n\t\"time\"\n)\n\n\n\n\n\ntype Clock interface {\n\tNow() time.Time\n}\n\ntype clock struct{}\n\nfunc (c *clock) Now() time.Time {\n\treturn time.Now()\n}\n\n\ntype Mock struct {\n\tcurrentTime time.Time\n}\n\n\nfunc (c *Mock) SetNow(t time.Time) {\n\tc.currentTime = t\n}\n\n\nfunc (c *Mock) Now() time.Time {\n\treturn c.currentTime\n}\n\n\n\n\n\nfunc NewMock() *Mock {\n\treturn &Mock{\n\t\tcurrentTime: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),\n\t}\n}\n\nfunc New() Clock ", "output": "{\n\treturn &clock{}\n}"} {"input": "package sodium\n\n\n\n\nimport \"C\"\n\nfunc RuntimeHasNeon() bool {\n\treturn C.sodium_runtime_has_neon() != 0\n}\n\n\n\nfunc RuntimeHasSse3() bool {\n\treturn C.sodium_runtime_has_sse3() != 0\n}\n\nfunc RuntimeHasSse2() bool ", "output": "{\n\treturn C.sodium_runtime_has_sse2() != 0\n}"} {"input": "package generator\n\nimport (\n\t\"testing\"\n\n\tkapi \"github.com/GoogleCloudPlatform/kubernetes/pkg/api\"\n\n\tbuildapi \"github.com/openshift/origin/pkg/build/api\"\n\t\"github.com/openshift/origin/pkg/build/generator\"\n)\n\n\n\nfunc TestCreateCloneValidationError(t *testing.T) {\n\trest := CloneREST{&generator.BuildGenerator{}}\n\t_, err := rest.Create(kapi.NewDefaultContext(), &buildapi.BuildRequest{})\n\tif err == nil {\n\t\tt.Error(\"Expected object got none!\")\n\t}\n}\n\nfunc TestCreateClone(t *testing.T) ", "output": "{\n\trest := CloneREST{&generator.BuildGenerator{Client: generator.Client{\n\t\tCreateBuildFunc: func(ctx kapi.Context, build *buildapi.Build) error {\n\t\t\treturn nil\n\t\t},\n\t\tGetBuildFunc: func(ctx kapi.Context, name string) (*buildapi.Build, error) {\n\t\t\treturn &buildapi.Build{}, nil\n\t\t},\n\t}}}\n\n\t_, err := rest.Create(kapi.NewDefaultContext(), &buildapi.BuildRequest{ObjectMeta: kapi.ObjectMeta{Name: \"name\"}})\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error %v\", err)\n\t}\n}"} {"input": "package libnetwork\n\nimport (\n\t\"fmt\"\n\t\"net\"\n)\n\nfunc (c *controller) cleanupServiceBindings(nid string) {\n}\n\nfunc (c *controller) addServiceBinding(name, sid, nid, eid string, vip net.IP, ingressPorts []*PortConfig, aliases []string, ip net.IP) error {\n\treturn fmt.Errorf(\"not supported\")\n}\n\n\n\nfunc (sb *sandbox) populateLoadbalancers(ep *endpoint) {\n}\n\nfunc arrangeIngressFilterRule() {\n}\n\nfunc (c *controller) rmServiceBinding(name, sid, nid, eid string, vip net.IP, ingressPorts []*PortConfig, aliases []string, ip net.IP) error ", "output": "{\n\treturn fmt.Errorf(\"not supported\")\n}"} {"input": "package flow\n\nimport (\n\t\"encoding/json\"\n\n\tshttp \"github.com/skydive-project/skydive/http\"\n\t\"github.com/skydive-project/skydive/logging\"\n)\n\nconst (\n\tNamespace = \"Flow\"\n)\n\ntype TableServer struct {\n\tshttp.DefaultWSClientEventHandler\n\tWSAsyncClientPool *shttp.WSAsyncClientPool\n\tTableAllocator *TableAllocator\n}\n\nfunc (s *TableServer) OnTableQuery(c *shttp.WSAsyncClient, msg shttp.WSMessage) {\n\tvar query TableQuery\n\tif err := json.Unmarshal([]byte(*msg.Obj), &query); err != nil {\n\t\tlogging.GetLogger().Errorf(\"Unable to decode search flow message %v\", msg)\n\t\treturn\n\t}\n\n\tresult := s.TableAllocator.QueryTable(&query)\n\treply := msg.Reply(result, \"TableResult\", result.status)\n\tc.SendWSMessage(reply)\n}\n\n\n\nfunc NewServer(allocator *TableAllocator, wspool *shttp.WSAsyncClientPool) *TableServer {\n\ts := &TableServer{\n\t\tTableAllocator: allocator,\n\t\tWSAsyncClientPool: wspool,\n\t}\n\twspool.AddEventHandler(s)\n\n\treturn s\n}\n\nfunc (s *TableServer) OnMessage(c *shttp.WSAsyncClient, msg shttp.WSMessage) ", "output": "{\n\tif msg.Namespace != Namespace {\n\t\treturn\n\t}\n\n\tswitch msg.Type {\n\tcase \"TableQuery\":\n\t\ts.OnTableQuery(c, msg)\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"crypto\"\n\t\"io\"\n\n\t\"golang.org/x/crypto/ssh\"\n)\n\nfunc SignatureFormatFromSigningOptionAndCA(opt string, ca ssh.PublicKey) string {\n\tswitch {\n\tcase ca != nil && ca.Type() == ssh.KeyAlgoED25519:\n\t\treturn ssh.KeyAlgoED25519\n\tcase ca != nil && ca.Type() == ssh.KeyAlgoRSA && opt == \"\":\n\t\treturn ssh.SigAlgoRSA\n\tdefault:\n\t\treturn opt\n\t}\n}\n\ntype ExtendedAgentSigner interface {\n\tssh.Signer\n\tSignWithOpts(rand io.Reader, data []byte, opts crypto.SignerOpts) (*ssh.Signature, error)\n}\n\ntype ExtendedAgentSignerWrapper struct {\n\tOpts crypto.SignerOpts\n\tSigner ExtendedAgentSigner\n}\n\nfunc (e *ExtendedAgentSignerWrapper) PublicKey() ssh.PublicKey {\n\treturn e.Signer.PublicKey()\n}\n\nfunc (e *ExtendedAgentSignerWrapper) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {\n\treturn e.Signer.SignWithOpts(rand, data, e.Opts)\n}\n\ntype AlgorithmSignerWrapper struct {\n\tAlgorithm string\n\tSigner ssh.AlgorithmSigner\n}\n\n\n\nfunc (a *AlgorithmSignerWrapper) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {\n\treturn a.Signer.SignWithAlgorithm(rand, data, a.Algorithm)\n}\n\nfunc (a *AlgorithmSignerWrapper) PublicKey() ssh.PublicKey ", "output": "{\n\treturn a.Signer.PublicKey()\n}"} {"input": "package commands\n\nimport (\n\t\"testing\"\n\n\t\"github.com/digitalocean/doctl/do\"\n\t\"github.com/digitalocean/godo\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nvar (\n\ttestSize = do.Size{Size: &godo.Size{Slug: \"small\"}}\n\ttestSizeList = do.Sizes{testSize}\n)\n\n\n\nfunc TestSizesList(t *testing.T) {\n\twithTestClient(t, func(config *CmdConfig, tm *tcMocks) {\n\t\ttm.sizes.On(\"List\").Return(testSizeList, nil)\n\n\t\terr := RunSizeList(config)\n\t\tassert.NoError(t, err)\n\t})\n}\n\nfunc TestSizeCommand(t *testing.T) ", "output": "{\n\tcmd := Size()\n\tassert.NotNil(t, cmd)\n\tassertCommandNames(t, cmd, \"list\")\n}"} {"input": "package command\n\nimport (\n\t\"strings\"\n\n\t\"github.com/mitchellh/cli\"\n\t\"github.com/posener/complete\"\n)\n\nvar (\n\t_ cli.Command = (*PrintCommand)(nil)\n\t_ cli.CommandAutocomplete = (*PrintCommand)(nil)\n)\n\ntype PrintCommand struct {\n\t*BaseCommand\n}\n\nfunc (c *PrintCommand) Synopsis() string {\n\treturn \"Prints runtime configurations\"\n}\n\nfunc (c *PrintCommand) Help() string {\n\thelpText := `\nUsage: vault print \n\n\tThis command groups subcommands for interacting with Vault's runtime values.\n\nSubcommands:\n\ttoken Token currently in use\n`\n\treturn strings.TrimSpace(helpText)\n}\n\n\n\nfunc (c *PrintCommand) AutocompleteFlags() complete.Flags {\n\treturn nil\n}\n\nfunc (c *PrintCommand) Run(args []string) int {\n\treturn cli.RunResultHelp\n}\n\nfunc (c *PrintCommand) AutocompleteArgs() complete.Predictor ", "output": "{\n\treturn nil\n}"} {"input": "package selinux\n\n\nfunc SELinuxEnabled() bool {\n\treturn false\n}\n\n\ntype realSELinuxRunner struct{}\n\nvar _ SELinuxRunner = &realSELinuxRunner{}\n\nfunc (_ *realSELinuxRunner) Getfilecon(path string) (string, error) {\n\treturn \"\", nil\n}\n\n\n\n\nfunc SetFileLabel(path string, label string) error ", "output": "{\n\treturn nil\n}"} {"input": "package database\n\nimport (\n\t\"context\"\n\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n)\n\nfunc (s *Service) ListParameter(req *ListParameterRequest) ([]*Parameter, error) {\n\treturn s.ListParameterWithContext(context.Background(), req)\n}\n\n\n\nfunc (s *Service) ListParameterWithContext(ctx context.Context, req *ListParameterRequest) ([]*Parameter, error) ", "output": "{\n\tif err := req.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tclient := sacloud.NewDatabaseOp(s.caller)\n\tparameters, err := client.GetParameter(ctx, req.Zone, req.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar results []*Parameter\n\tfor _, p := range parameters.MetaInfo {\n\t\tvar setting interface{}\n\t\tfor k, v := range parameters.Settings {\n\t\t\tif p.Name == k {\n\t\t\t\tsetting = v\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tresults = append(results, &Parameter{\n\t\t\tKey: p.Label,\n\t\t\tValue: setting,\n\t\t\tMeta: p,\n\t\t})\n\t}\n\treturn results, nil\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n\n\t\"github.com/docker/docker/pkg/integration/checker\"\n\t\"github.com/go-check/check\"\n)\n\nfunc (s *DockerSuite) TestExperimentalVersionTrue(c *check.C) {\n\ttestRequires(c, ExperimentalDaemon)\n\n\tout, _ := dockerCmd(c, \"version\")\n\tfor _, line := range strings.Split(out, \"\\n\") {\n\t\tif strings.HasPrefix(strings.TrimSpace(line), \"Experimental:\") {\n\t\t\tc.Assert(line, checker.Matches, \"*true\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tc.Fatal(`\"Experimental\" not found in version output`)\n}\n\n\n\nfunc (s *DockerSuite) TestExperimentalVersionFalse(c *check.C) ", "output": "{\n\ttestRequires(c, NotExperimentalDaemon)\n\n\tout, _ := dockerCmd(c, \"version\")\n\tfor _, line := range strings.Split(out, \"\\n\") {\n\t\tif strings.HasPrefix(strings.TrimSpace(line), \"Experimental:\") {\n\t\t\tc.Assert(line, checker.Matches, \"*false\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tc.Fatal(`\"Experimental\" not found in version output`)\n}"} {"input": "package service\n\n\n\n\nfunc GetNodeIP() ([]string, error) ", "output": "{\n\n\tsvcs, err := KubeClient.GetNodes(\"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar nodeIP []string\n\tfor _, v := range svcs.Items {\n\t\tnodeIP = append(nodeIP, v.Status.Addresses[0].Address)\n\t}\n\treturn nodeIP, nil\n}"} {"input": "package awsping\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n)\n\n\ntype RequestType int\n\nconst (\n\tRequestTypeHTTP RequestType = iota\n\tRequestTypeTCP\n)\n\n\ntype Requester interface {\n\tDo(ua, url string, reqType RequestType) (time.Duration, error)\n}\n\n\ntype AWSHTTPRequester interface {\n\tDo(req *http.Request) (*http.Response, error)\n}\n\n\ntype AWSTCPRequester interface {\n\tDial(network, address string) (net.Conn, error)\n}\n\n\ntype AWSRequest struct {\n\thttpClient AWSHTTPRequester\n\ttcpClient AWSTCPRequester\n}\n\n\nfunc NewAWSRequest() *AWSRequest {\n\treturn &AWSRequest{\n\t\thttpClient: &http.Client{},\n\t\ttcpClient: &net.Dialer{},\n\t}\n}\n\n\nfunc (r *AWSRequest) DoHTTP(ua, url string) (time.Duration, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treq.Header.Set(\"User-Agent\", ua)\n\n\tstart := time.Now()\n\tresp, err := r.httpClient.Do(req)\n\tlatency := time.Since(start)\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn latency, nil\n}\n\n\n\n\n\nfunc (r *AWSRequest) Do(ua, url string, reqType RequestType) (time.Duration, error) {\n\tif reqType == RequestTypeHTTP {\n\t\treturn r.DoHTTP(ua, url)\n\t}\n\treturn r.DoTCP(ua, url)\n}\n\nfunc (r *AWSRequest) DoTCP(_, addr string) (time.Duration, error) ", "output": "{\n\tstart := time.Now()\n\tconn, err := r.tcpClient.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tl := time.Since(start)\n\tdefer conn.Close()\n\n\treturn l, nil\n}"} {"input": "package libDao\n\nvar (\n\tstorage Storage\n)\n\n\ntype DefaultDao struct {\n}\n\n\n\n\n\nfunc (this *DefaultDao) Get(key string, value interface{}) (err error) {\n\terr = storage.Get(key, value)\n\treturn\n}\n\n\nfunc (this *DefaultDao) Put(key string, value interface{}) (err error) {\n\terr = storage.Put(key, value)\n\treturn\n}\n\n\nfunc (this *DefaultDao) Del(key string, value interface{}) (err error) {\n\terr = storage.Del(key, value)\n\treturn\n}\n\nfunc InitDao(sc *StorageConfig, s Storage) (err error) ", "output": "{\n\tif sc == nil {\n\t\terr = ErrStorageConfigIllegal\n\t\treturn\n\t}\n\tif s == nil {\n\t\tdefaultStorage := new(DefaultStorage)\n\t\tstorage = defaultStorage\n\t} else {\n\t\tstorage = s\n\t}\n\tif sc.OpenCache {\n\t\tif err = storage.InitCache(sc.CacheAddr, sc.CacheKeyPrefix); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif sc.OpenPersistence {\n\t\tif err = storage.InitPersistence(sc.PersistenceAddr, sc.PersistenceDbName); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype ResourceQuotaLister interface {\n\tList(selector labels.Selector) (ret []*v1.ResourceQuota, err error)\n\tResourceQuotas(namespace string) ResourceQuotaNamespaceLister\n\tResourceQuotaListerExpansion\n}\n\n\ntype resourceQuotaLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewResourceQuotaLister(indexer cache.Indexer) ResourceQuotaLister {\n\treturn &resourceQuotaLister{indexer: indexer}\n}\n\n\nfunc (s *resourceQuotaLister) List(selector labels.Selector) (ret []*v1.ResourceQuota, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ResourceQuota))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *resourceQuotaLister) ResourceQuotas(namespace string) ResourceQuotaNamespaceLister {\n\treturn resourceQuotaNamespaceLister{indexer: s.indexer, namespace: namespace}\n}\n\n\ntype ResourceQuotaNamespaceLister interface {\n\tList(selector labels.Selector) (ret []*v1.ResourceQuota, err error)\n\tGet(name string) (*v1.ResourceQuota, error)\n\tResourceQuotaNamespaceListerExpansion\n}\n\n\n\ntype resourceQuotaNamespaceLister struct {\n\tindexer cache.Indexer\n\tnamespace string\n}\n\n\nfunc (s resourceQuotaNamespaceLister) List(selector labels.Selector) (ret []*v1.ResourceQuota, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ResourceQuota))\n\t})\n\treturn ret, err\n}\n\n\n\n\nfunc (s resourceQuotaNamespaceLister) Get(name string) (*v1.ResourceQuota, error) ", "output": "{\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"resourcequota\"), name)\n\t}\n\treturn obj.(*v1.ResourceQuota), nil\n}"} {"input": "package app\n\n\n\n\nimport \"C\"\nimport (\n\t\"runtime\"\n\t\"sync\"\n\n\t\"grate/backend/mobile/event\"\n\t\"grate/backend/mobile/geom\"\n\t\"grate/backend/mobile/gl\"\n)\n\nvar cb Callbacks\n\nfunc run(callbacks Callbacks) {\n\truntime.LockOSThread()\n\tcb = callbacks\n\tC.runApp()\n}\n\n\nfunc onResize(w, h int) {\n\tgeom.PixelsPerPt = 72\n\tgeom.Width = geom.Pt(float32(w)/ geom.PixelsPerPt)\n\tgeom.Height = geom.Pt(float32(h)/ geom.PixelsPerPt)\n\tgl.Viewport(0, 0, w, h);\n}\n\nvar events struct {\n\tsync.Mutex\n\tpending []event.Touch\n}\n\nfunc sendTouch(ty event.TouchType, x, y float32) {\n\tevents.Lock()\n\tevents.pending = append(events.pending, event.Touch{\n\t\tType: ty,\n\t\tLoc: geom.Point{\n\t\t\tX: geom.Pt(float32(x)/ geom.PixelsPerPt),\n\t\t\tY: geom.Pt(float32(y)/ geom.PixelsPerPt),\n\t\t},\n\t})\n\tevents.Unlock()\n}\n\n\n\n\n\nfunc onTouchMove(x, y float32) { sendTouch(event.TouchMove, x, y) }\n\n\nfunc onTouchEnd(x, y float32) { sendTouch(event.TouchEnd, x, y) }\n\nvar started bool\n\n\nfunc onDraw() {\n\tif !started {\n\t\tcb.Start()\n\t\tstarted = true\n\t}\n\n\tevents.Lock()\n\tpending := events.pending\n\tevents.pending = nil\n\tevents.Unlock()\n\n\tfor _, e := range pending {\n\t\tif cb.Touch != nil {\n\t\t\tcb.Touch(e)\n\t\t}\n\t}\n\tif cb.Draw != nil {\n\t\tcb.Draw()\n\t}\n}\n\nfunc onTouchStart(x, y float32) ", "output": "{ sendTouch(event.TouchStart, x, y) }"} {"input": "package command\n\nimport (\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/hashicorp/go-plugin\"\n\n\t\"github.com/hashicorp/nomad/client/driver\"\n)\n\ntype SyslogPluginCommand struct {\n\tMeta\n}\n\n\n\nfunc (s *SyslogPluginCommand) Synopsis() string {\n\treturn \"internal - lanch a syslog collector plugin\"\n}\n\nfunc (s *SyslogPluginCommand) Run(args []string) int {\n\tif len(args) == 0 {\n\t\ts.Ui.Error(\"log output file isn't provided\")\n\t}\n\tlogFileName := args[0]\n\tstdo, err := os.OpenFile(logFileName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)\n\tif err != nil {\n\t\ts.Ui.Error(err.Error())\n\t\treturn 1\n\t}\n\tplugin.Serve(&plugin.ServeConfig{\n\t\tHandshakeConfig: driver.HandshakeConfig,\n\t\tPlugins: driver.GetPluginMap(stdo),\n\t})\n\n\treturn 0\n}\n\nfunc (e *SyslogPluginCommand) Help() string ", "output": "{\n\thelpText := `\n\tThis is a command used by Nomad internally to launch a syslog collector\"\n\t`\n\treturn strings.TrimSpace(helpText)\n}"} {"input": "package stack\n\nimport (\n\t\"github.com/docker/docker/cli\"\n\t\"github.com/docker/docker/cli/command\"\n\t\"github.com/spf13/cobra\"\n)\n\n\nfunc NewStackCommand(dockerCli *command.DockerCli) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"stack\",\n\t\tShort: \"Manage Docker stacks\",\n\t\tArgs: cli.NoArgs,\n\t\tRunE: dockerCli.ShowHelp,\n\t\tTags: map[string]string{\"version\": \"1.25\"},\n\t}\n\tcmd.AddCommand(\n\t\tnewDeployCommand(dockerCli),\n\t\tnewListCommand(dockerCli),\n\t\tnewRemoveCommand(dockerCli),\n\t\tnewServicesCommand(dockerCli),\n\t\tnewPsCommand(dockerCli),\n\t)\n\treturn cmd\n}\n\n\n\n\nfunc NewTopLevelDeployCommand(dockerCli *command.DockerCli) *cobra.Command ", "output": "{\n\tcmd := newDeployCommand(dockerCli)\n\tcmd.Aliases = []string{}\n\tcmd.Tags = map[string]string{\"experimental\": \"\", \"version\": \"1.25\"}\n\treturn cmd\n}"} {"input": "package syscallx\n\n\n\n\nimport (\n\t\"syscall\"\n)\n\n\n\nfunc Listxattr(path string, dest []byte) (sz int, err error) {\n\treturn syscall.Listxattr(path, dest)\n}\n\nfunc Setxattr(path string, attr string, data []byte, flags int) (err error) {\n\treturn syscall.Setxattr(path, attr, data, flags)\n}\n\nfunc Removexattr(path string, attr string) (err error) {\n\treturn syscall.Removexattr(path, attr)\n}\n\nfunc Getxattr(path string, attr string, dest []byte) (sz int, err error) ", "output": "{\n\treturn syscall.Getxattr(path, attr, dest)\n}"} {"input": "package ppcutil\n\nimport (\n\t\"github.com/mably/btcwire\"\n)\n\n\n\n\n\n\nfunc IsMsgBlockProofOfStake(msg *btcwire.MsgBlock) bool ", "output": "{\n\treturn len(msg.Transactions) > 1 &&\n\t\tmsg.Transactions[1].IsCoinStake()\n}"} {"input": "package utils\n\nimport (\n\t\"errors\"\n\t\"github.com/mmcloughlin/geohash\"\n\t\"github.com/whosonfirst/go-whosonfirst-geojson-v2\"\n\t\"github.com/whosonfirst/go-whosonfirst-hash\"\n)\n\n\n\nfunc HashFeature(f geojson.Feature) (string, error) {\n\n\treturn \"\", errors.New(\"This is not ready to use yet\")\n\n\n\n\n\n}\n\n\n\n\n\n\n\nfunc HashGeometry(geom []byte) (string, error) {\n\n\th, err := hash.NewWOFHash()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn h.HashFromJSON(geom)\n}\n\nfunc GeohashFeature(f geojson.Feature) (string, error) ", "output": "{\n\n\tbboxes, err := f.BoundingBoxes()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmbr := bboxes.MBR()\n\tcenter := mbr.Center()\n\n\tlat := center.Y\n\tlon := center.X\n\n\tgh := geohash.Encode(lat, lon)\n\treturn gh, nil\n}"} {"input": "package tasks\n\n\n\n\nimport (\n\t\"net/url\"\n\n\t\"github.com/kawaken/go-rtm/methods\"\n)\n\n\n\n\nfunc AddTags(timeline string, listID string, taskseriesID string, taskID string, tags string) *methods.Method ", "output": "{\n\tname := \"rtm.tasks.addTags\"\n\n\tp := url.Values{}\n\tp.Add(\"method\", name)\n\tp.Add(\"timeline\", timeline)\n\tp.Add(\"list_id\", listID)\n\tp.Add(\"taskseries_id\", taskseriesID)\n\tp.Add(\"task_id\", taskID)\n\tp.Add(\"tags\", tags)\n\treturn &methods.Method{Name: name, Params: p}\n}"} {"input": "package store\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"text/tabwriter\"\n\t\"time\"\n)\n\ntype Metadata map[string]string\n\ntype Entry struct {\n\tName string `json:\"name\"`\n\tPassword []byte `json:\"password\"`\n\tCtime time.Time `json:\"ctime\"` \n\tMtime time.Time `json:\"mtime\"` \n\tMetadata Metadata `json:\"metadata\"` \n}\n\nfunc NewEntry() *Entry {\n\treturn &Entry{\n\t\tMetadata: make(Metadata),\n\t\tCtime: getCurrentTime(),\n\t\tMtime: getCurrentTime(),\n\t}\n}\n\nfunc (e *Entry) Age() time.Duration {\n\treturn time.Since(e.Mtime)\n}\n\n\n\nfunc (e Entry) String() string {\n\tb := new(bytes.Buffer)\n\tw := tabwriter.NewWriter(b, 0, 0, 0, ' ', 0)\n\n\tvalof := reflect.ValueOf(e)\n\tfor i := 0; i < valof.NumField(); i++ {\n\t\tswitch val := valof.Field(i).Interface().(type) {\n\t\tdefault:\n\t\t\ttag := valof.Type().Field(i).Tag.Get(\"json\")\n\t\t\tfmt.Fprintf(w, \"%s\\t : %s\\n\", tag, val)\n\t\tcase Metadata:\n\t\t\tfor k, v := range val {\n\t\t\t\tfmt.Fprintf(w, \"%s\\t : %s\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\n\tw.Flush()\n\treturn b.String()\n}\n\nfunc (m Metadata) String() string {\n\tvar b bytes.Buffer\n\tfor k, v := range m {\n\t\tfmt.Fprintf(&b, \"%s:%s\", k, v)\n\t}\n\treturn b.String()\n}\n\nfunc getCurrentTime() time.Time {\n\treturn time.Now().Truncate(time.Second)\n}\n\nfunc (e *Entry) Touch() ", "output": "{\n\te.Mtime = getCurrentTime()\n}"} {"input": "package gtd\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/BurntSushi/toml\"\n)\n\ntype config struct {\n\tGtdFile string `toml:\"gtdfile\"`\n\tMemoDir string `toml:\"memodir\"`\n\tOutputDir string `toml:\"outputdir\"`\n\tFilterCmd string `toml:\"filtercmd\"`\n\tEditor string `toml:\"editor\"`\n}\n\n\n\nfunc (cfg *config) runcmd(command string, files ...string) error {\n\tvar args []string\n\tfor _, file := range files {\n\t\targs = append(args, fmt.Sprintf(\"%q\", file))\n\t}\n\tcmdargs := strings.Join(args, \" \")\n\tcommand += \" \" + cmdargs\n\n\tvar cmd *exec.Cmd\n\tcmd = exec.Command(\"sh\", \"-c\", command)\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = os.Stdout\n\tcmd.Stdin = os.Stdin\n\treturn cmd.Run()\n}\n\nfunc (cfg *config) filtercmd(command string, w io.Writer) error {\n\tvar cmd *exec.Cmd\n\tcmd = exec.Command(\"sh\", \"-c\", command)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = w\n\treturn cmd.Run()\n}\n\nfunc (cfg *config) load() error ", "output": "{\n\tvar dir string\n\tdir = filepath.Join(os.Getenv(\"HOME\"), \".config\", \"gtd\")\n\n\tif err := os.MkdirAll(dir, 0700); err != nil {\n\t\treturn fmt.Errorf(\"cannot create directory: %v\", err)\n\t}\n\n\tconfigfile := filepath.Join(dir, \"config.toml\")\n\t_, err := os.Stat(configfile)\n\tif err == nil {\n\t\t_, err := toml.DecodeFile(configfile, cfg)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot decode toml file: %v\", err)\n\t\t}\n\t\treturn nil\n\t}\n\n\tcfg.Editor = \"vi\"\n\tgtdfile := filepath.Join(os.Getenv(\"HOME\"), \"gtd.json\")\n\tcfg.GtdFile = gtdfile\n\tcfg.MemoDir = os.Getenv(\"HOME\")\n\tf, err := os.Create(configfile)\n\treturn toml.NewEncoder(f).Encode(cfg)\n}"} {"input": "package zookeeper\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/magneticio/vamp-router/haproxy\"\n\tgologger \"github.com/op/go-logging\"\n\t\"github.com/samuel/go-zookeeper/zk\"\n\t\"strings\"\n\t\"time\"\n)\n\n\ntype ZkClient struct {\n\tconn *zk.Conn\n\thaConfig *haproxy.Config\n\tlog *gologger.Logger\n}\n\nfunc (z *ZkClient) Init(conString string, conf *haproxy.Config, log *gologger.Logger) error {\n\n\tz.log = log\n\tz.haConfig = conf\n\terr := z.connect(conString)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc (z *ZkClient) connect(conString string) error {\n\tzks := strings.Split(conString, \",\")\n\tconn, _, err := zk.Connect(zks, (60 * time.Second))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tz.conn = conn\n\treturn nil\n}\n\n\nfunc (z *ZkClient) Watch(path string) {\n\n\tgo z.watcher(path)\n\n}\n\n\n\nfunc (z *ZkClient) watcher(path string) error ", "output": "{\n\n\tfor {\n\t\tpayload, _, watch, err := z.conn.GetW(path)\n\n\t\tif err != nil {\n\t\t\tz.log.Error(\"Error from Zookeeper: \" + err.Error())\n\t\t}\n\n\t\terr = json.Unmarshal(payload, &z.haConfig)\n\t\tif err != nil {\n\t\t\tz.log.Error(\"Error parsing config from Zookeeper: \" + err.Error())\n\t\t}\n\n\t\tevent := <-watch\n\n\t\tz.log.Notice(\"Received Zookeeper event: \" + event.Type.String())\n\n\t\terr = json.Unmarshal(payload, &z.haConfig)\n\t\tif err != nil {\n\t\t\tz.log.Error(\"Error parsing config from Zookeeper: \" + err.Error())\n\t\t}\n\n\t}\n\n}"} {"input": "package loadbalancer\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateListenerRequest struct {\n\n\tCreateListenerDetails `contributesTo:\"body\"`\n\n\tLoadBalancerId *string `mandatory:\"true\" contributesTo:\"path\" name:\"loadBalancerId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateListenerRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request CreateListenerRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CreateListenerRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateListenerResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateListenerResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateListenerResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateListenerRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package log\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\ntype Exit struct {\n\tCode int\n\tClosure func()\n}\n\n\n\nfunc Error(msg string, closure func()) {\n\tfmt.Printf(\"\\033[1;31m[ERROR]\\033[0m %s\\n\", msg)\n\tpanic(Exit{1, closure})\n}\n\nfunc Warn(msg string) {\n\tfmt.Printf(\"\\033[1;33m[WARNING]\\033[0m %s\\n\", msg)\n}\n\nfunc Succ(msg string) {\n\tfmt.Printf(\"\\033[1;32m[DONE]\\033[0m %s\\n\", msg)\n}\n\nfunc HandleExit() ", "output": "{\n\tif e := recover(); e != nil {\n\t\tif exit, ok := e.(Exit); ok {\n\t\t\texit.Closure()\n\t\t\tos.Exit(exit.Code)\n\t\t}\n\t\tpanic(e)\n\t}\n}"} {"input": "package database\n\nimport (\n\t\"labix.org/v2/mgo\"\n\t\"labix.org/v2/mgo/bson\"\n\t\"github.com/DewaldV/crucible/config\"\n)\n\ntype MgoConnection struct {\n\tDatabase string\n\tCollection string\n}\n\nfunc (conn *MgoConnection) FindOne(m bson.M, d interface{}) {\n\tExecuteWithCollection(conn.Database, conn.Collection, func(c *mgo.Collection) error { return c.Find(m).One(d) })\n}\n\n\n\n\nfunc (conn *MgoConnection) Insert(d interface{}) {\n\tExecuteWithCollection(conn.Database, conn.Collection, func(c *mgo.Collection) error { return c.Insert(d) })\n}\n\n\n\nfunc ExecuteWithCollection(database, collection string, f func(*mgo.Collection) error) error {\n\tsession := GetSession(\"Default\")\n\tdefer session.Close()\n\n\tsession.SetMode(mgo.Monotonic, true)\n\n\tc := session.DB(database).C(collection)\n\n\treturn f(c)\n}\n\nvar sessionPool map[string]*mgo.Session\n\nfunc LoadSessions(dataSourceConfig map[string]*config.DataSourceConfiguration) {\n\tsessionPool = make(map[string]*mgo.Session)\n\tfor key, source := range dataSourceConfig {\n\t\ts, _ := mgo.Dial(source.ServerName)\n\t\tsessionPool[key] = s\n\t}\n}\n\nfunc GetSession(dataSource string) *mgo.Session {\n\ts := sessionPool[dataSource]\n\treturn s.Clone()\n}\n\nfunc (conn *MgoConnection) FindAll(m bson.M, d interface{}) ", "output": "{\n\tExecuteWithCollection(conn.Database, conn.Collection, func(c *mgo.Collection) error { return c.Find(m).All(d) })\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/config\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdGetJSONConfig{\n\t\tname: \"get_json_section\",\n\t\trpcMethod: utils.ConfigSv1GetConfig,\n\t\trpcParams: &config.SectionWithOpts{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetJSONConfig struct {\n\tname string\n\trpcMethod string\n\trpcParams *config.SectionWithOpts\n\t*CommandExecuter\n}\n\n\n\nfunc (self *CmdGetJSONConfig) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdGetJSONConfig) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &config.SectionWithOpts{Opts: make(map[string]interface{})}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetJSONConfig) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetJSONConfig) RpcResult() interface{} {\n\tvar s map[string]interface{}\n\treturn &s\n}\n\nfunc (self *CmdGetJSONConfig) Name() string ", "output": "{\n\treturn self.name\n}"} {"input": "package models\n\nimport (\n\t\"fmt\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\n\nvar goBgpValidator *goBgpScopeValidator\n\n\nfunc init() {\n\tgoBgpValidator = &goBgpScopeValidator{}\n}\n\n\ntype goBgpScopeValidator struct {\n\tmitigationScopeValidatorBase\n}\n\n\n\n\nfunc (v *goBgpScopeValidator) ValidateUri(customer *Customer, scope *MitigationScope) (errMsg string) ", "output": "{\n\tif len(scope.URI.List()) != 0 {\n\t\terrMsg = fmt.Sprintf(\"invalid uri: %+v\", scope.URI.List())\n\t\tlog.Warn(errMsg)\n\t\treturn\n\t}\n\treturn\n}"} {"input": "package engine\n\nimport (\n\tvtrpcpb \"vitess.io/vitess/go/vt/proto/vtrpc\"\n\t\"vitess.io/vitess/go/vt/vterrors\"\n\n\t\"vitess.io/vitess/go/sqltypes\"\n\t\"vitess.io/vitess/go/vt/proto/query\"\n)\n\nvar _ Primitive = (*UpdateTarget)(nil)\n\n\ntype UpdateTarget struct {\n\tTarget string\n\n\tnoInputs\n\n\tnoTxNeeded\n}\n\nfunc (updTarget *UpdateTarget) description() PrimitiveDescription {\n\treturn PrimitiveDescription{\n\t\tOperatorType: \"UpdateTarget\",\n\t\tOther: map[string]interface{}{\"target\": updTarget.Target},\n\t}\n}\n\n\nfunc (updTarget *UpdateTarget) RouteType() string {\n\treturn \"UpdateTarget\"\n}\n\n\nfunc (updTarget *UpdateTarget) GetKeyspaceName() string {\n\treturn updTarget.Target\n}\n\n\nfunc (updTarget *UpdateTarget) GetTableName() string {\n\treturn \"\"\n}\n\n\nfunc (updTarget *UpdateTarget) TryExecute(vcursor VCursor, bindVars map[string]*query.BindVariable, wantfields bool) (*sqltypes.Result, error) {\n\terr := vcursor.Session().SetTarget(updTarget.Target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &sqltypes.Result{}, nil\n}\n\n\n\n\n\nfunc (updTarget *UpdateTarget) GetFields(vcursor VCursor, bindVars map[string]*query.BindVariable) (*sqltypes.Result, error) {\n\treturn nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, \"[BUG] GetFields not reachable for use statement\")\n}\n\nfunc (updTarget *UpdateTarget) TryStreamExecute(vcursor VCursor, bindVars map[string]*query.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error ", "output": "{\n\tresult, err := updTarget.TryExecute(vcursor, bindVars, wantfields)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn callback(result)\n}"} {"input": "package processorconfig\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\n\t\"github.com/nuclio/nuclio/pkg/processor\"\n\n\t\"github.com/ghodss/yaml\"\n\t\"github.com/nuclio/errors\"\n)\n\n\ntype Reader struct {\n}\n\n\nfunc NewReader() (*Reader, error) {\n\treturn &Reader{}, nil\n}\n\n\n\n\nfunc (r *Reader) Read(reader io.Reader, processorConfiguration *processor.Configuration) error ", "output": "{\n\tbodyBytes, err := ioutil.ReadAll(reader)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to read processor configuration\")\n\t}\n\n\tif err := yaml.Unmarshal(bodyBytes, processorConfiguration); err != nil {\n\t\treturn errors.Wrap(err, \"Failed to write configuration\")\n\t}\n\n\tif processorConfiguration.Spec.EventTimeout != \"\" {\n\t\t_, err := processorConfiguration.Spec.GetEventTimeout()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"Can't parse Spec.EventTimeout (%q) into time.Duration\", processorConfiguration.Spec.EventTimeout)\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package service\n\nimport (\n\t\"github.com/xephonhq/xephon-k/pkg/common\"\n\t\"github.com/xephonhq/xephon-k/pkg/storage\"\n)\n\ntype ReadService struct {\n\tstore storage.Store\n}\n\nfunc NewReadService(store storage.Store) *ReadService {\n\treturn &ReadService{\n\t\tstore: store,\n\t}\n}\n\n\n\nfunc (r *ReadService) QuerySeries(queries []common.Query) ([]common.QueryResult, []common.Series, error) ", "output": "{\n\treturn r.store.QuerySeries(queries)\n}"} {"input": "package goparsify\n\nimport (\n\t\"strconv\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\n\ntype State struct {\n\tInput string\n\tPos int\n\tCut int\n\tError Error\n\tWS VoidParser\n}\n\n\n\n\n\n\n\nfunc UnicodeWhitespace(s *State) {\n\tfor s.Pos < len(s.Input) {\n\t\tr, w := utf8.DecodeRuneInString(s.Get())\n\t\tif !unicode.IsSpace(r) {\n\t\t\treturn\n\t\t}\n\t\ts.Pos += w\n\t}\n}\n\n\nfunc NoWhitespace(s *State) {\n\n}\n\n\nfunc NewState(input string) *State {\n\treturn &State{\n\t\tInput: input,\n\t\tWS: UnicodeWhitespace,\n\t}\n}\n\n\nfunc (s *State) Advance(i int) {\n\ts.Pos += i\n}\n\n\nfunc (s *State) Get() string {\n\tif s.Pos > len(s.Input) {\n\t\treturn \"\"\n\t}\n\treturn s.Input[s.Pos:]\n}\n\n\nfunc (s *State) Preview(x int) string {\n\tif s.Pos >= len(s.Input) {\n\t\treturn \"\"\n\t}\n\n\tquoted := strconv.Quote(s.Get())\n\tquoted = quoted[1 : len(quoted)-1]\n\tif len(quoted) >= x {\n\t\treturn quoted[0:x]\n\t}\n\n\treturn quoted\n}\n\n\nfunc (s *State) ErrorHere(expected string) {\n\ts.Error.pos = s.Pos\n\ts.Error.expected = expected\n}\n\n\n\nfunc (s *State) Recover() {\n\ts.Error.expected = \"\"\n}\n\n\nfunc (s *State) Errored() bool {\n\treturn s.Error.expected != \"\"\n}\n\nfunc ASCIIWhitespace(s *State) ", "output": "{\n\tfor s.Pos < len(s.Input) {\n\t\tswitch s.Input[s.Pos] {\n\t\tcase '\\t', '\\n', '\\v', '\\f', '\\r', ' ':\n\t\t\ts.Pos++\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}"} {"input": "package harlog\n\nimport (\n \"net/http\"\n \"testing\"\n)\n\nfunc makerr() (*http.Request, *http.Response) {\n\n req, _ := http.NewRequest(\"GET\", \"http://www.example.com/path/?param=value\", nil)\n resp := &http.Response{\n Status: \"200 OK\",\n StatusCode: 200,\n Proto: \"HTTP/1.0\",\n ProtoMajor: 1,\n ProtoMinor: 0,\n Request: req,\n Header: http.Header{\n \"Connection\": {\"close\"},\n },\n Close: true,\n ContentLength: -1,\n }\n\n return req, resp\n}\n\nfunc TestNewLog(t *testing.T) {\n\n har := NewHARLog()\n har.Dump()\n}\n\n\n\nfunc TestDump(t *testing.T) {\n\n req, resp := makerr()\n har := NewHARLog()\n har.Entries.Add(req, resp)\n har.Dump()\n}\n\nfunc TestAddEntry(t *testing.T) ", "output": "{\n\n req, resp := makerr()\n har := NewHARLog()\n har.Entries.Add(req, resp)\n}"} {"input": "package wiringpi\n\n\n\n\n\n\n\n\n\n\n\nimport \"C\"\nimport (\n\t\"sync\"\n\n\t\"github.com/yroffin/jarvis-go-ext/logger\"\n)\n\n\ntype WiringPiDriver struct {\n}\n\nvar instance *WiringPiDriver\nvar once sync.Once\n\n\nfunc GetInstance() *WiringPiDriver {\n\tonce.Do(func() {\n\t\tinstance = new(WiringPiDriver)\n\t\tinstance.init()\n\t})\n\treturn instance\n}\n\n\nfunc (wiringPi *WiringPiDriver) init() int {\n\tvar res = int(C.wiringPiSetupInit())\n\tlogger.Default.Info(\"WiringPiDriver\", logger.Fields{\n\t\t\"Init\": \"on\",\n\t})\n\treturn res\n}\n\n\nfunc PinMode(pin int, value int) {\n\tC.pinMode(C.int(pin), C.int(value))\n}\n\n\n\n\n\nfunc DelayMicroseconds(delay uint) {\n\tC.delayMicroseconds(C.uint(delay))\n}\n\n\nfunc Delay(delay uint) {\n\tC.delay(C.uint(delay))\n}\n\nfunc DigitalWrite(pin int, value int) ", "output": "{\n\tC.digitalWrite(C.int(pin), C.int(value))\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1beta1 \"knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1\"\n)\n\ntype FakeServingV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeServingV1beta1) Configurations(namespace string) v1beta1.ConfigurationInterface {\n\treturn &FakeConfigurations{c, namespace}\n}\n\nfunc (c *FakeServingV1beta1) Revisions(namespace string) v1beta1.RevisionInterface {\n\treturn &FakeRevisions{c, namespace}\n}\n\nfunc (c *FakeServingV1beta1) Routes(namespace string) v1beta1.RouteInterface {\n\treturn &FakeRoutes{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeServingV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeServingV1beta1) Services(namespace string) v1beta1.ServiceInterface ", "output": "{\n\treturn &FakeServices{c, namespace}\n}"} {"input": "package greatspacerace\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"github.com/TSavo/go.firebase\"\n\t\"os\"\n)\n\n\n\nvar db *firebase.FirebaseRoot;\n\nfunc Readln(r *bufio.Reader) (string, error) {\n\tvar (\n\t\tisPrefix bool = true\n\t\terr error = nil\n\t\tline, ln []byte\n\t)\n\tfor isPrefix && err == nil {\n\t\tline, isPrefix, err = r.ReadLine()\n\t\tln = append(ln, line...)\n\t}\n\treturn string(ln), err\n}\n\nfunc init() ", "output": "{\n\tf, err := os.Open(\"firebase.secret\")\n\tif err != nil {\n\t\tfmt.Printf(\"error opening firebase.secret: %v\\n\", err)\n\t}\n\tr := bufio.NewReader(f)\n\turl, e := Readln(r)\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\tsecret, e := Readln(r)\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\tdb = firebase.New(url, secret)\n}"} {"input": "package test\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestTcConfigName(t *testing.T) {\n\tv := TcConfigName()\n\tif len(v) <= len(Config) {\n\t\tt.Errorf(\"icorrect behavior\")\n\t}\n\t_, err := os.Stat(v)\n\tif err != nil {\n\t\tt.Errorf(\"invalid: %v\", err)\n\t}\n}\n\nfunc TestTcBuildDir(t *testing.T) ", "output": "{\n\tv := TcBuildDir()\n\tif v == \"\" {\n\t\tt.Errorf(\"icorrect behavior\")\n\t}\n\t_, err := os.Stat(v)\n\tif err != nil {\n\t\tt.Errorf(\"invalid: %v\", err)\n\t}\n}"} {"input": "package airplane_mode\n\nfunc getRadioModule(key RadioType) BaseRadioModule {\n\tvar module BaseRadioModule\n\tswitch key {\n\tcase BluetoothRadioType:\n\t\tmodule = &BluetoothRadio{GeneralRadioModule{typ: BluetoothRadioType, name: \"bluetooth\"}}\n\tcase WlanRadioType:\n\t\tmodule = &WlanRadio{GeneralRadioModule{typ: WlanRadioType, name: \"wlan\"}}\n\tcase AllRadioType:\n\t\tmodule = &AllRadio{GeneralRadioModule{typ: AllRadioType, name: \"all\"}}\n\tdefault:\n\t\tpanic(\"radio type not exist\")\n\t}\n\treturn module\n}\n\ntype GeneralRadioModule struct {\n\ttyp RadioType\n\tname string\n}\n\nfunc (Op *GeneralRadioModule) Type() RadioType {\n\treturn Op.typ\n}\n\nfunc (Op *GeneralRadioModule) Module() string {\n\treturn Op.name\n}\n\nfunc (Op *GeneralRadioModule) Len() int {\n\tstate, err := rfkillState(Op.typ)\n\tif err != nil {\n\t\tlogger.Warningf(\"check rfkill blocked state failed, err: %v\", err)\n\t\tstate.count = 0\n\t}\n\treturn state.count\n}\n\nfunc (Op *GeneralRadioModule) Block() error {\n\treturn rfkillAction(Op.typ, BlockRadioAction)\n}\n\n\n\nfunc (Op *GeneralRadioModule) IsBlocked() bool {\n\tstate, err := rfkillState(Op.typ)\n\tif err != nil {\n\t\tlogger.Warningf(\"check rfkill blocked state failed, err: %v\", err)\n\t\tstate.blocked = false\n\t}\n\treturn state.blocked\n}\n\n\ntype BluetoothRadio struct {\n\tGeneralRadioModule\n}\n\n\ntype WlanRadio struct {\n\tGeneralRadioModule\n}\n\n\ntype AllRadio struct {\n\tGeneralRadioModule\n}\n\nfunc (Op *GeneralRadioModule) Unblock() error ", "output": "{\n\treturn rfkillAction(Op.typ, UnblockRadioAction)\n}"} {"input": "package sf\n\nimport (\n\t\"time\"\n)\n\ntype Clock struct {\n\tstartTime time.Time\n}\n\n\n\nfunc (c *Clock) ElapsedTime() time.Duration {\n\treturn time.Since(c.startTime)\n}\n\nfunc (c *Clock) Restart() time.Duration {\n\telapsed := time.Since(c.startTime)\n\tc.startTime = time.Now()\n\n\treturn elapsed\n}\n\nfunc NewClock() *Clock ", "output": "{\n\treturn &Clock{time.Now()}\n}"} {"input": "package symlink\n\nimport (\n\t\"path/filepath\"\n)\n\n\n\nfunc evalSymlinks(path string) (string, error) ", "output": "{\n\treturn filepath.EvalSymlinks(path)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\nfunc isSongRecord(input string) bool {\n\treturn input != \"\" && !strings.HasPrefix(input, \"#EXTM3U\")\n}\n\nfunc isSongRecordHeader(input string) bool {\n\treturn strings.HasPrefix(input, \"#EXTINF:\")\n}\n\nfunc extractSongRecordHeader(index int, line string) (s *SongRecord) {\n\tvar title, duration string\n\tif i := strings.IndexAny(line, \"-0123456789\"); i > -1 {\n\t\tconst separator = \",\"\n\t\tline = line[i:]\n\t\tif j := strings.Index(line, separator); j > -1 {\n\t\t\ttitle = line[j+len(separator):]\n\t\t\tduration = line[:j]\n\t\t}\n\t}\n\n\treturn NewSongRecord(index, \"\", title, duration)\n}\n\nfunc writePlsPlaylist(songs []*SongRecord) error {\n\tfmt.Println(\"[playlist]\")\n\tfor _, song := range songs {\n\t\tif pls, err := song.ToPls(); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\tfmt.Printf(pls)\n\t\t}\n\t}\n\tfmt.Printf(\"NumberOfEntries=%d\\nVersion=2\\n\", len(songs))\n\treturn nil\n}\n\nfunc parseM3uPlaylist(data string) (songs []*SongRecord) ", "output": "{\n\tvar songIndex int\n\tvar newSong *SongRecord\n\n\tfor _, line := range strings.Split(data, \"\\n\") {\n\t\tline = strings.TrimSpace(line)\n\t\tif !isSongRecord(line) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif isSongRecordHeader(line) {\n\t\t\tsongIndex += 1\n\t\t\tnewSong = extractSongRecordHeader(songIndex, line)\n\t\t} else {\n\t\t\tnewSong.setFilepath(line)\n\t\t\tsongs = append(songs, newSong)\n\t\t}\n\t}\n\treturn songs\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n)\n\n\n\ntype NetworkConfiguration struct {\n\n\tSubnetID string `json:\"subnetId,omitempty\"`\n}\n\n\n\n\nfunc (m *NetworkConfiguration) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package signers\n\nimport (\n\t\"crypto\"\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/sha1\"\n\t\"crypto/x509\"\n\t\"encoding/base64\"\n)\n\n\n\nfunc Sha256WithRsa(source, secret string) string {\n\tdecodeString, err := base64.StdEncoding.DecodeString(secret)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tprivate, err := x509.ParsePKCS8PrivateKey(decodeString)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\th := crypto.Hash.New(crypto.SHA256)\n\th.Write([]byte(source))\n\thashed := h.Sum(nil)\n\tsignature, err := rsa.SignPKCS1v15(rand.Reader, private.(*rsa.PrivateKey),\n\t\tcrypto.SHA256, hashed)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn base64.StdEncoding.EncodeToString(signature)\n}\n\nfunc ShaHmac1(source, secret string) string ", "output": "{\n\tkey := []byte(secret)\n\thmac := hmac.New(sha1.New, key)\n\thmac.Write([]byte(source))\n\tsignedBytes := hmac.Sum(nil)\n\tsignedString := base64.StdEncoding.EncodeToString(signedBytes)\n\treturn signedString\n}"} {"input": "package wfe\n\nimport (\n\t\"crypto/ecdsa\"\n\t\"crypto/rsa\"\n\t\"fmt\"\n\n\t\"github.com/letsencrypt/boulder/core\"\n\t\"github.com/square/go-jose\"\n)\n\nfunc algorithmForKey(key *jose.JsonWebKey) (string, error) {\n\tswitch k := key.Key.(type) {\n\tcase *rsa.PublicKey:\n\t\treturn string(jose.RS256), nil\n\tcase *ecdsa.PublicKey:\n\t\tswitch k.Params().Name {\n\t\tcase \"P-256\":\n\t\t\treturn string(jose.ES256), nil\n\t\tcase \"P-384\":\n\t\t\treturn string(jose.ES384), nil\n\t\tcase \"P-521\":\n\t\t\treturn string(jose.ES512), nil\n\t\t}\n\t}\n\treturn \"\", core.SignatureValidationError(\"no signature algorithms suitable for given key type\")\n}\n\nconst (\n\tnoAlgorithmForKey = \"WFE.Errors.NoAlgorithmForKey\"\n\tinvalidJWSAlgorithm = \"WFE.Errors.InvalidJWSAlgorithm\"\n\tinvalidAlgorithmOnKey = \"WFE.Errors.InvalidAlgorithmOnKey\"\n)\n\n\n\n\n\n\n\n\nfunc checkAlgorithm(key *jose.JsonWebKey, parsedJws *jose.JsonWebSignature) (string, error) ", "output": "{\n\talgorithm, err := algorithmForKey(key)\n\tif err != nil {\n\t\treturn noAlgorithmForKey, err\n\t}\n\tjwsAlgorithm := parsedJws.Signatures[0].Header.Algorithm\n\tif jwsAlgorithm != algorithm {\n\t\treturn invalidJWSAlgorithm,\n\t\t\tcore.SignatureValidationError(fmt.Sprintf(\n\t\t\t\t\"algorithm '%s' in JWS header not acceptable\", jwsAlgorithm))\n\t}\n\tif key.Algorithm != \"\" && key.Algorithm != algorithm {\n\t\treturn invalidAlgorithmOnKey,\n\t\t\tcore.SignatureValidationError(fmt.Sprintf(\n\t\t\t\t\"algorithm '%s' on JWK is unacceptable\", key.Algorithm))\n\t}\n\treturn \"\", nil\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\n\nfunc login(args url.Values) interface{} ", "output": "{\n\tname := args.Get(\"name\")\n\tpass := args.Get(\"pass\")\n\tcode := args.Get(\"code\")\n\tif name == \"\" {\n\t\treturn httpError{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMesg: \"username not provided\",\n\t\t}\n\t}\n\tif pass == \"\" && code == \"\" {\n\t\treturn httpError{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMesg: \"password or OTP code required\",\n\t\t}\n\t}\n\tfail := httpError{\n\t\tCode: http.StatusUnauthorized,\n\t\tMesg: \"authentication failed\",\n\t}\n\tai, ok := authDb[name]\n\tif !ok {\n\t\treturn fail\n\t}\n\tif !ai.Validate(pass, code) {\n\t\treturn fail\n\t}\n\treturn nil\n}"} {"input": "package fakes\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org/route-registrar/commandrunner\"\n\t\"code.cloudfoundry.org/route-registrar/healthchecker\"\n)\n\ntype FakeHealthChecker struct {\n\tCheckStub func(runner commandrunner.Runner, scriptPath string, timeout time.Duration) (bool, error)\n\tcheckMutex sync.RWMutex\n\tcheckArgsForCall []struct {\n\t\trunner commandrunner.Runner\n\t\tscriptPath string\n\t\ttimeout time.Duration\n\t}\n\tcheckReturns struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}\n}\n\nfunc (fake *FakeHealthChecker) Check(runner commandrunner.Runner, scriptPath string, timeout time.Duration) (bool, error) {\n\tfake.checkMutex.Lock()\n\tfake.checkArgsForCall = append(fake.checkArgsForCall, struct {\n\t\trunner commandrunner.Runner\n\t\tscriptPath string\n\t\ttimeout time.Duration\n\t}{runner, scriptPath, timeout})\n\tfake.checkMutex.Unlock()\n\tif fake.CheckStub != nil {\n\t\treturn fake.CheckStub(runner, scriptPath, timeout)\n\t} else {\n\t\treturn fake.checkReturns.result1, fake.checkReturns.result2\n\t}\n}\n\nfunc (fake *FakeHealthChecker) CheckCallCount() int {\n\tfake.checkMutex.RLock()\n\tdefer fake.checkMutex.RUnlock()\n\treturn len(fake.checkArgsForCall)\n}\n\nfunc (fake *FakeHealthChecker) CheckArgsForCall(i int) (commandrunner.Runner, string, time.Duration) {\n\tfake.checkMutex.RLock()\n\tdefer fake.checkMutex.RUnlock()\n\treturn fake.checkArgsForCall[i].runner, fake.checkArgsForCall[i].scriptPath, fake.checkArgsForCall[i].timeout\n}\n\n\n\nvar _ healthchecker.HealthChecker = new(FakeHealthChecker)\n\nfunc (fake *FakeHealthChecker) CheckReturns(result1 bool, result2 error) ", "output": "{\n\tfake.CheckStub = nil\n\tfake.checkReturns = struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}{result1, result2}\n}"} {"input": "package j_kite\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"koding/remoteapi/models\"\n)\n\n\ntype PostRemoteAPIJKiteFetchPlansIDReader struct {\n\tformats strfmt.Registry\n}\n\n\nfunc (o *PostRemoteAPIJKiteFetchPlansIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewPostRemoteAPIJKiteFetchPlansIDOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}\n\n\nfunc NewPostRemoteAPIJKiteFetchPlansIDOK() *PostRemoteAPIJKiteFetchPlansIDOK {\n\treturn &PostRemoteAPIJKiteFetchPlansIDOK{}\n}\n\n\ntype PostRemoteAPIJKiteFetchPlansIDOK struct {\n\tPayload *models.JKite\n}\n\nfunc (o *PostRemoteAPIJKiteFetchPlansIDOK) Error() string {\n\treturn fmt.Sprintf(\"[POST /remote.api/JKite.fetchPlans/{id}][%d] postRemoteApiJKiteFetchPlansIdOK %+v\", 200, o.Payload)\n}\n\n\n\nfunc (o *PostRemoteAPIJKiteFetchPlansIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error ", "output": "{\n\n\to.Payload = new(models.JKite)\n\n\tif err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "\n\nfunc convertToTitle(n int) string {\n var res []byte\n for n > 0 {\n n--\n k := n % 26\n res = append(res, byte('A') + byte(k))\n n /= 26\n }\n for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {\n res[i], res[j] = res[j], res[i]\n }\n return string(res)\n}\n\nfunc convertToTitle(n int) string ", "output": "{\n execl := []string{\"A\", \"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\", \"I\", \"J\",\"K\",\"L\",\"M\",\"N\",\"O\", \"P\", \"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\"}\n var temp string\n for n >0 {\n temp = execl[(n-1)%26] +temp\n n = (n-1) /26\n }\n return temp\n}"} {"input": "package iso20022\n\n\ntype FinancialInstrumentDetails24 struct {\n\n\tFinancialInstrumentIdentification *SecurityIdentification19 `xml:\"FinInstrmId\"`\n\n\tFinancialInstrumentAttributes *FinancialInstrumentAttributes63 `xml:\"FinInstrmAttrbts,omitempty\"`\n\n\tSubBalance []*IntraPositionDetails40 `xml:\"SubBal\"`\n}\n\nfunc (f *FinancialInstrumentDetails24) AddFinancialInstrumentIdentification() *SecurityIdentification19 {\n\tf.FinancialInstrumentIdentification = new(SecurityIdentification19)\n\treturn f.FinancialInstrumentIdentification\n}\n\n\n\nfunc (f *FinancialInstrumentDetails24) AddSubBalance() *IntraPositionDetails40 {\n\tnewValue := new(IntraPositionDetails40)\n\tf.SubBalance = append(f.SubBalance, newValue)\n\treturn newValue\n}\n\nfunc (f *FinancialInstrumentDetails24) AddFinancialInstrumentAttributes() *FinancialInstrumentAttributes63 ", "output": "{\n\tf.FinancialInstrumentAttributes = new(FinancialInstrumentAttributes63)\n\treturn f.FinancialInstrumentAttributes\n}"} {"input": "package wraps\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-on/wrap\"\n)\n\ntype first []http.Handler\n\nfunc (f first) ServeHTTPNext(inner http.Handler, wr http.ResponseWriter, req *http.Request) {\n\tchecked := wrap.NewPeek(wr, func(ck *wrap.Peek) bool {\n\t\tck.FlushHeaders()\n\t\tck.FlushCode()\n\t\treturn true\n\t})\n\n\tfor _, h := range f {\n\t\th.ServeHTTP(checked, req)\n\t\tif checked.HasChanged() {\n\t\t\tchecked.FlushMissing()\n\t\t\treturn\n\t\t}\n\t}\n\tinner.ServeHTTP(wr, req)\n}\n\n\nfunc (f first) Wrap(next http.Handler) http.Handler {\n\treturn wrap.NextHandler(f).Wrap(next)\n}\n\n\nfunc First(handler ...http.Handler) wrap.Wrapper { return first(handler) }\n\n\n\n\nfunc FirstFunc(handlerFn ...func(w http.ResponseWriter, r *http.Request)) wrap.Wrapper ", "output": "{\n\th := make([]http.Handler, len(handlerFn))\n\tfor i, fn := range handlerFn {\n\t\th[i] = http.HandlerFunc(fn)\n\t}\n\treturn first(h)\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/e154/smart-home-configurator/version\"\n\t\"github.com/labstack/echo/v4\"\n\t\"net/http\"\n)\n\n\ntype ControllerIndex struct {\n\t*ControllerCommon\n}\n\n\n\n\nfunc (c *ControllerIndex) Index(ctx echo.Context) error {\n\treturn ctx.Render(http.StatusOK, \"index.html\", map[string]interface{}{\n\t\t\"server_url\": c.config.WebHostPort,\n\t\t\"debug\": c.config.Debug,\n\t\t\"configurator_version\": version.GetHumanVersion(),\n\t})\n}\n\nfunc NewIndexController(common *ControllerCommon,\n) *ControllerIndex ", "output": "{\n\treturn &ControllerIndex{\n\t\tControllerCommon: common,\n\t}\n}"} {"input": "package elasticorm_test\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"testing\"\n)\n\nvar elasticSearchURL = determinElasticsearchURL()\n\nfunc determinElasticsearchURL() string {\n\tURL := os.Getenv(\"EDS_ES_URL\")\n\tif URL == `` {\n\t\tURL = `http://localhost:9200`\n\t}\n\treturn URL\n}\n\n\nfunc assert(tb testing.TB, condition bool, msg string, v ...interface{}) {\n\tif !condition {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\033[31m%s:%d: \"+msg+\"\\033[39m\\n\\n\", append([]interface{}{filepath.Base(file), line}, v...)...)\n\t\ttb.FailNow()\n\t}\n}\n\n\nfunc ok(tb testing.TB, err error) {\n\tif err != nil {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\033[31m%s:%d: unexpected error: %s\\033[39m\\n\\n\", filepath.Base(file), line, err.Error())\n\t\ttb.FailNow()\n\t}\n}\n\n\n\n\nfunc equals(tb testing.TB, exp, act interface{}) ", "output": "{\n\tif !reflect.DeepEqual(exp, act) {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\033[31m%s:%d:\\n\\n\\texp: %#v\\n\\n\\tgot: %#v\\033[39m\\n\\n\", filepath.Base(file), line, exp, act)\n\t\ttb.FailNow()\n\t}\n}"} {"input": "package bc\n\nimport \"io\"\n\n\nfunc (o *VoteOutput) writeForHash(w io.Writer) {\n\tmustWriteForHash(w, o.Source)\n\tmustWriteForHash(w, o.ControlProgram)\n\tmustWriteForHash(w, o.Vote)\n\tmustWriteForHash(w, o.StateData)\n}\n\n\nfunc NewVoteOutput(source *ValueSource, controlProgram *Program, stateData [][]byte, ordinal uint64, vote []byte) *VoteOutput {\n\treturn &VoteOutput{\n\t\tSource: source,\n\t\tControlProgram: controlProgram,\n\t\tOrdinal: ordinal,\n\t\tVote: vote,\n\t\tStateData: stateData,\n\t}\n}\n\nfunc (VoteOutput) typ() string ", "output": "{ return \"voteOutput1\" }"} {"input": "package levigo\n\n\n\n\nimport \"C\"\n\n\n\n\n\n\n\n\n\ntype Cache struct {\n\tCache *C.leveldb_cache_t\n}\n\n\n\n\n\n\n\n\n\nfunc (c *Cache) Close() {\n\tC.leveldb_cache_destroy(c.Cache)\n}\n\nfunc NewLRUCache(capacity int) *Cache ", "output": "{\n\treturn &Cache{C.leveldb_cache_create_lru(C.size_t(capacity))}\n}"} {"input": "package ini\n\nimport (\n\t\"log\"\n\t\"testing\"\n)\n\n\n\nfunc TestVar(t *testing.T) ", "output": "{\n\tconf := NewConf(\"test.ini\")\n\tv1 := conf.String(\"section_2\", \"field1\", \"default\")\n\tv2 := conf.String(\"section_1\", \"field1\", \"default\")\n\tv3 := conf.String(\"section_3\", \"field1\", \"default\")\n\tv4 := conf.String(\"section_4\", \"field1\", \"default\")\n\tv5 := conf.Int(GLOBAL_SECTION, \"global_2\", 10)\n\n\tconf.Parse()\n\n\tlog.Println(*v1)\n\tlog.Println(*v2)\n\tlog.Println(*v3)\n\tlog.Println(*v4)\n\tlog.Println(*v5)\n\n}"} {"input": "package endpointslice\n\n\n\ntype StaleInformerCache struct {\n\tmsg string\n}\n\n\n\nfunc isStaleInformerCacheErr(err error) bool {\n\t_, ok := err.(*StaleInformerCache)\n\treturn ok\n}\n\nfunc (e *StaleInformerCache) Error() string ", "output": "{ return e.msg }"} {"input": "package featuretests\n\nimport (\n\t\"os\"\n\n\t\"github.com/juju/cmd/cmdtesting\"\n\tjc \"github.com/juju/testing/checkers\"\n\tgc \"gopkg.in/check.v1\"\n\n\t\"github.com/juju/juju/juju/osenv\"\n\tjujutesting \"github.com/juju/juju/juju/testing\"\n)\n\ntype CmdRelationSuite struct {\n\tjujutesting.JujuConnSuite\n\tapps []string\n}\n\n\n\nfunc (s *CmdRelationSuite) TestAddRelationSuccess(c *gc.C) {\n\trunCommandExpectSuccess(c, \"add-relation\", s.apps...)\n}\n\nfunc (s *CmdRelationSuite) TestAddRelationSuccessOnAlreadyExists(c *gc.C) {\n\trunCommandExpectSuccess(c, \"add-relation\", s.apps...)\n\tcontext, err := runCommand(c, append([]string{\"add-relation\"}, s.apps...)...)\n\tc.Assert(err, gc.NotNil)\n\tc.Check(cmdtesting.Stderr(context), jc.Contains, `ERROR cannot add relation \"wordpress:db mysql:server\"\nrelation wordpress:db mysql:server (already exists): \n\nUse 'juju status --relations' to view the current relations.\n`)\n}\n\nfunc (s *CmdRelationSuite) TestRemoveRelationSuccess(c *gc.C) {\n\trunCommandExpectSuccess(c, \"add-relation\", s.apps...)\n\trunCommandExpectSuccess(c, \"remove-relation\", s.apps...)\n}\n\nfunc (s *CmdRelationSuite) TestRemoveRelationFail(c *gc.C) {\n\trunCommandExpectFailure(c, \"remove-relation\", `relation \"wordpress:db mysql:server\" not found`, s.apps...)\n}\n\nfunc (s *CmdRelationSuite) SetUpTest(c *gc.C) ", "output": "{\n\ts.JujuConnSuite.SetUpTest(c)\n\tos.Setenv(osenv.JujuModelEnvKey, \"\")\n\n\ts.apps = []string{\"wordpress\", \"mysql\"}\n\tfor _, app := range s.apps {\n\t\tch := s.AddTestingCharm(c, app)\n\t\ts.AddTestingApplication(c, app, ch)\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/akutz/gotil\"\n)\n\n\n\nfunc (c *client) logResponse(res *http.Response) {\n\n\tif !c.logResponses {\n\t\treturn\n\t}\n\n\tw := log.StandardLogger().Writer()\n\n\tfmt.Fprintln(w)\n\tfmt.Fprint(w, \" -------------------------- \")\n\tfmt.Fprint(w, \"HTTP RESPONSE (CLIENT)\")\n\tfmt.Fprintln(w, \" -------------------------\")\n\n\tbuf, err := httputil.DumpResponse(\n\t\tres,\n\t\tres.Header.Get(\"Content-Type\") != \"application/octet-stream\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbw := &bytes.Buffer{}\n\tgotil.WriteIndented(bw, buf)\n\n\tscanner := bufio.NewScanner(bw)\n\tfor {\n\t\tif !scanner.Scan() {\n\t\t\tbreak\n\t\t}\n\t\tfmt.Fprintln(w, scanner.Text())\n\t}\n}\n\nfunc (c *client) logRequest(req *http.Request) ", "output": "{\n\n\tif !c.logRequests {\n\t\treturn\n\t}\n\n\tw := log.StandardLogger().Writer()\n\n\tfmt.Fprintln(w, \"\")\n\tfmt.Fprint(w, \" -------------------------- \")\n\tfmt.Fprint(w, \"HTTP REQUEST (CLIENT)\")\n\tfmt.Fprintln(w, \" -------------------------\")\n\n\tbuf, err := httputil.DumpRequest(req, true)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgotil.WriteIndented(w, buf)\n\tfmt.Fprintln(w)\n}"} {"input": "package docker\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/containers/image/image\"\n\t\"github.com/containers/image/types\"\n\t\"github.com/pkg/errors\"\n)\n\n\n\ntype Image struct {\n\ttypes.Image\n\tsrc *dockerImageSource\n}\n\n\n\n\nfunc newImage(ctx *types.SystemContext, ref dockerReference) (types.Image, error) {\n\ts, err := newImageSource(ctx, ref, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\timg, err := image.FromSource(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Image{Image: img, src: s}, nil\n}\n\n\n\n\n\nfunc (i *Image) GetRepositoryTags() ([]string, error) {\n\turl := fmt.Sprintf(tagsURL, i.src.ref.ref.RemoteName())\n\tres, err := i.src.c.makeRequest(\"GET\", url, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != http.StatusOK {\n\t\treturn nil, errors.Errorf(\"Invalid status code returned when fetching tags list %d\", res.StatusCode)\n\t}\n\ttype tagsRes struct {\n\t\tTags []string\n\t}\n\ttags := &tagsRes{}\n\tif err := json.NewDecoder(res.Body).Decode(tags); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tags.Tags, nil\n}\n\nfunc (i *Image) SourceRefFullName() string ", "output": "{\n\treturn i.src.ref.ref.FullName()\n}"} {"input": "package stdlib\n\nimport (\n\t\"hash/maphash\"\n\t\"reflect\"\n)\n\n\n\nfunc init() ", "output": "{\n\tSymbols[\"hash/maphash\"] = map[string]reflect.Value{\n\t\t\"MakeSeed\": reflect.ValueOf(maphash.MakeSeed),\n\n\t\t\"Hash\": reflect.ValueOf((*maphash.Hash)(nil)),\n\t\t\"Seed\": reflect.ValueOf((*maphash.Seed)(nil)),\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc capitalizedWord(word string) (capitalized string) {\n\tswitch len(word) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\tcapitalized = strings.ToUpper(string(word[0]))\n\tdefault:\n\t\tcapitalized = strings.ToUpper(string(word[0])) + string(word[1:])\n\t}\n\treturn capitalized\n}\n\nfunc lowerCasedWord(word string) (lowerCased string) {\n\tswitch len(word) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\tlowerCased = strings.ToLower(string(word[0]))\n\tdefault:\n\t\tlowerCased = strings.ToLower(string(word[0])) + string(word[1:])\n\t}\n\treturn lowerCased\n}\n\n\n\nfunc camelcaseToAbbreviation(camel string) (abbr string) ", "output": "{\n\tif len(camel) == 0 {\n\t\treturn \"\"\n\t}\n\n\tabbr = strings.ToLower(string(camel[0])) \n\n\tremainingRunes := []rune(camel[1:])\n\tfor _, r := range remainingRunes {\n\t\tif unicode.IsUpper(r) {\n\t\t\tabbr += strings.ToLower(string(r))\n\t\t}\n\t}\n\treturn abbr\n}"} {"input": "package bosh\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/cloudfoundry/bosh-bootloader/storage\"\n)\n\ntype ConfigUpdater struct {\n\tboshCLIProvider boshCLIProvider\n\tboshCLI AuthenticatedCLIRunner\n}\n\ntype boshCLIProvider interface {\n\tAuthenticatedCLI(jumpbox storage.Jumpbox, stderr io.Writer, directorAddress, directorUsername, directorPassword, directorCACert string) (AuthenticatedCLIRunner, error)\n}\n\nfunc NewConfigUpdater(boshCLIProvider boshCLIProvider) ConfigUpdater {\n\treturn ConfigUpdater{boshCLIProvider: boshCLIProvider}\n}\n\n\n\nfunc (c ConfigUpdater) UpdateCloudConfig(boshCLI AuthenticatedCLIRunner, filepath string, opsFilepaths []string, varsFilepath string) error {\n\targs := []string{\"update-cloud-config\", filepath}\n\tfor _, opsFilepath := range opsFilepaths {\n\t\targs = append(args, \"--ops-file\", opsFilepath)\n\t}\n\targs = append(args, \"--vars-file\", varsFilepath)\n\n\treturn boshCLI.Run(nil, \"\", args)\n}\n\nfunc (c ConfigUpdater) UpdateRuntimeConfig(boshCLI AuthenticatedCLIRunner, filepath string, opsFilepaths []string, name string) error {\n\targs := []string{\"update-runtime-config\", filepath}\n\tfor _, opsFilepath := range opsFilepaths {\n\t\targs = append(args, \"--ops-file\", opsFilepath)\n\t}\n\targs = append(args, \"--name\", name)\n\n\treturn boshCLI.Run(nil, \"\", args)\n}\n\nfunc (c ConfigUpdater) InitializeAuthenticatedCLI(state storage.State) (AuthenticatedCLIRunner, error) ", "output": "{\n\tboshCLI, err := c.boshCLIProvider.AuthenticatedCLI(\n\t\tstate.Jumpbox,\n\t\tos.Stderr,\n\t\tstate.BOSH.DirectorAddress,\n\t\tstate.BOSH.DirectorUsername,\n\t\tstate.BOSH.DirectorPassword,\n\t\tstate.BOSH.DirectorSSLCA,\n\t)\n\n\tif err != nil {\n\t\treturn AuthenticatedCLI{}, fmt.Errorf(\"failed to create bosh cli: %s\", err)\n\t}\n\n\treturn boshCLI, nil\n}"} {"input": "package sarama\n\nimport \"fmt\"\n\nconst responseLengthSize = 4\nconst correlationIDSize = 4\n\ntype responseHeader struct {\n\tlength int32\n\tcorrelationID int32\n}\n\n\n\nfunc (r *responseHeader) decode(pd packetDecoder) (err error) ", "output": "{\n\tr.length, err = pd.getInt32()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif r.length <= 4 || r.length > MaxResponseSize {\n\t\treturn PacketDecodingError{fmt.Sprintf(\"message of length %d too large or too small\", r.length)}\n\t}\n\n\tr.correlationID, err = pd.getInt32()\n\treturn err\n}"} {"input": "package ast\n\n\ntype AsmLabelAttr struct {\n\tAddr Address\n\tPos Position\n\tInherited bool\n\tFunctionName string\n\tChildNodes []Node\n\tIsLiteralLabel bool\n}\n\n\n\n\n\nfunc (n *AsmLabelAttr) AddChild(node Node) {\n\tn.ChildNodes = append(n.ChildNodes, node)\n}\n\n\n\nfunc (n *AsmLabelAttr) Address() Address {\n\treturn n.Addr\n}\n\n\n\nfunc (n *AsmLabelAttr) Children() []Node {\n\treturn n.ChildNodes\n}\n\n\nfunc (n *AsmLabelAttr) Position() Position {\n\treturn n.Pos\n}\n\nfunc parseAsmLabelAttr(line string) *AsmLabelAttr ", "output": "{\n\tgroups := groupsFromRegex(\n\t\t`<(?P.*)>\n\t\t(?P Inherited)?\n\t\t \"(?P.+)\"\n\t\t(?P IsLiteralLabel)?`,\n\t\tline,\n\t)\n\n\treturn &AsmLabelAttr{\n\t\tAddr: ParseAddress(groups[\"address\"]),\n\t\tPos: NewPositionFromString(groups[\"position\"]),\n\t\tInherited: len(groups[\"inherited\"]) > 0,\n\t\tFunctionName: groups[\"function\"],\n\t\tChildNodes: []Node{},\n\t\tIsLiteralLabel: len(groups[\"literal\"]) > 0,\n\t}\n}"} {"input": "package hpg\n\nimport \"net/url\"\n\n\ntype CommonParams struct {\n\tKey string\n\tStart int\n\tCount int\n\tCallback string\n}\n\n\n\n\n\nfunc (p *CommonParams) String() string {\n\treturn p.queryBuffer().String()\n}\n\nfunc (p *CommonParams) queryBuffer() *queryBuffer ", "output": "{\n\tbf := new(queryBuffer)\n\n\tbf.WriteString(\"?key=\" + url.QueryEscape(p.Key))\n\n\tbf.appendInt(\"start\", p.Start)\n\tbf.appendInt(\"count\", p.Count)\n\n\tif p.Callback == \"\" {\n\t\tbf.append(\"format\", \"json\")\n\t} else {\n\t\tbf.append(\"format\", \"jsonp\")\n\t\tbf.append(\"callback\", p.Callback)\n\t}\n\n\treturn bf\n}"} {"input": "package gosseract\n\nimport \"fmt\"\nimport \"os\"\nimport \"os/exec\"\nimport \"bytes\"\nimport \"io/ioutil\"\n\ntype tesseract0303 struct {\n\tversion string\n\tresultFilePath string\n\tcommandPath string\n}\n\n\n\nfunc (t tesseract0303) Execute(params []string) (res string, e error) {\n\tvar args []string\n\targs = append(args, params[0])\n\tt.resultFilePath, e = generateTmpFile()\n\tif e != nil {\n\t\treturn\n\t}\n\targs = append(args, t.resultFilePath)\n\tif len(params) > 1 {\n\t\targs = append(args, params[1])\n\t}\n\n\tcmd := exec.Command(TESSERACT, args...)\n\tvar stderr bytes.Buffer\n\tcmd.Stderr = &stderr\n\tif e = cmd.Run(); e != nil {\n\t\te = fmt.Errorf(stderr.String())\n\t\treturn\n\t}\n\tres, e = t.readResult()\n\treturn\n}\n\nfunc (t tesseract0303) readResult() (res string, e error) {\n\tfpath := t.resultFilePath + outFILEEXTENSION\n\tfile, e := os.OpenFile(fpath, 1, 1)\n\tif e != nil {\n\t\treturn\n\t}\n\tbuffer, _ := ioutil.ReadFile(file.Name())\n\tres = string(buffer)\n\tos.Remove(file.Name())\n\treturn\n}\n\nfunc (t tesseract0303) Version() string ", "output": "{\n\treturn t.version\n}"} {"input": "package lago\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype ScopedLogger struct {\n\tlog Logger\n\tscp string\n\tfmt string\n}\n\n\nfunc NewScopedLogger(log Logger, scope string, padding int) *ScopedLogger {\n\tformat := \"-%\" + intToStringWithSign(padding) + \"s: %s\"\n\n\tl := &ScopedLogger{\n\t\tlog: log,\n\t\tscp: scope,\n\t\tfmt: format,\n\t}\n\n\treturn l\n}\n\n\nfunc (l *ScopedLogger) Errorf(format string, args ...interface{}) {\n\tl.log.Errorf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\n\n\n\n\nfunc (l *ScopedLogger) Warnf(format string, args ...interface{}) {\n\tl.log.Warnf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\n\nfunc (l *ScopedLogger) Fatalf(format string, args ...interface{}) {\n\tl.log.Fatalf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\nfunc intToStringWithSign(i int) string {\n\ta := strconv.Itoa(i)\n\ts := \"+\"\n\tif i < 0 {\n\t\ts = \"-\"\n\t}\n\ta = s + a\n\n\treturn a\n}\n\nfunc (l *ScopedLogger) Infof(format string, args ...interface{}) ", "output": "{\n\tl.log.Infof(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}"} {"input": "package update\n\nimport (\n\t\"github.com/andreaskoch/allmark/common/route\"\n\t\"fmt\"\n\t\"golang.org/x/net/websocket\"\n)\n\n\n\ntype connection struct {\n\tRoute route.Route\n\n\thub *Hub\n\n\tws *websocket.Conn\n\n\tsend chan Message\n}\n\nfunc (c *connection) String() string {\n\treturn fmt.Sprintf(\"Connection (Route: %s, IP: %s)\", c.Route.String(), c.ws.Request().RemoteAddr)\n}\n\nfunc (c *connection) Send(msg Message) {\n\tc.send <- msg\n}\n\nfunc (c *connection) Reader() {\n\tfor {\n\t\tvar message Message\n\t\terr := websocket.JSON.Receive(c.ws, &message)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tc.hub.broadcast <- message\n\t}\n\n\tc.ws.Close()\n\tc.hub.Unsubscribe(c)\n}\n\nfunc (c *connection) Writer() {\n\tfor message := range c.send {\n\t\terr := websocket.JSON.Send(c.ws, message)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tc.ws.Close()\n\tc.hub.Unsubscribe(c)\n}\n\nfunc NewConnection(hub *Hub, ws *websocket.Conn, route route.Route) *connection ", "output": "{\n\treturn &connection{\n\t\tRoute: route,\n\n\t\thub: hub,\n\t\tsend: make(chan Message, 10),\n\t\tws: ws,\n\t}\n}"} {"input": "package sqs_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/awstesting/unit\"\n\t\"github.com/aws/aws-sdk-go/service/sqs\"\n)\n\n\n\nfunc TestFlattenedTraits(t *testing.T) ", "output": "{\n\ts := sqs.New(unit.Session)\n\t_, err := s.DeleteMessageBatch(&sqs.DeleteMessageBatchInput{\n\t\tQueueURL: aws.String(\"QUEUE\"),\n\t\tEntries: []*sqs.DeleteMessageBatchRequestEntry{\n\t\t\t{\n\t\t\t\tID: aws.String(\"TEST\"),\n\t\t\t\tReceiptHandle: aws.String(\"RECEIPT\"),\n\t\t\t},\n\t\t},\n\t})\n\n\tassert.Error(t, err)\n\tassert.Equal(t, \"InvalidAddress\", err.Code())\n\tassert.Equal(t, \"The address QUEUE is not valid for this endpoint.\", err.Message())\n}"} {"input": "package chaosmonkey_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/Netflix/chaosmonkey\"\n)\n\n\n\nfunc TestExceptionMatches(t *testing.T) ", "output": "{\n\tex := chaosmonkey.Exception{Account: \"test\", Stack: \"*\", Detail: \"*\", Region: \"*\"}\n\n\tif !ex.Matches(\"test\", \"cl\", \"app-cl-test\", \"us-east-1\") {\n\t\tt.Error(\"Expected exception match\")\n\t}\n}"} {"input": "package scribe \n\nimport (\n\t\"github.com/mozilla/mig/testutil\"\n\t\"testing\"\n)\n\n\n\nfunc TestRegistration(t *testing.T) ", "output": "{\n\ttestutil.CheckModuleRegistration(t, \"scribe\")\n}"} {"input": "package models\n\nimport (\n\t\"koding/db/mongodb/modelhelper\"\n\t\"net\"\n\t\"socialapi/config\"\n\t\"socialapi/request\"\n\n\t\"github.com/koding/logging\"\n)\n\n\ntype Client struct {\n\tAccount *Account\n\n\tIP net.IP\n\n\tSessionID string\n}\n\n\ntype Context struct {\n\tGroupName string\n\tClient *Client\n\tlog logging.Logger\n}\n\n\n\n\n\nfunc (c *Context) OverrideQuery(q *request.Query) *request.Query {\n\tq.GroupName = c.GroupName\n\tif c.IsLoggedIn() {\n\t\tq.AccountId = c.Client.Account.Id\n\t} else {\n\t\tq.AccountId = 0\n\t}\n\n\treturn q\n}\n\n\nfunc (c *Context) IsLoggedIn() bool {\n\tif c.Client == nil {\n\t\treturn false\n\t}\n\n\tif c.Client.Account == nil {\n\t\treturn false\n\t}\n\n\tif c.Client.Account.Id == 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\n\n\nfunc (c *Context) IsAdmin() bool {\n\tif !c.IsLoggedIn() {\n\t\treturn false\n\t}\n\n\tsuperAdmins := config.MustGet().DummyAdmins\n\treturn IsIn(c.Client.Account.Nick, superAdmins...)\n}\n\n\n\n\nfunc (c *Context) CanManage() error {\n\tif !c.IsLoggedIn() {\n\t\treturn ErrNotLoggedIn\n\t}\n\n\tcanManage, err := modelhelper.CanManage(c.Client.Account.Nick, c.GroupName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !canManage {\n\t\treturn ErrCannotManageGroup\n\t}\n\n\treturn nil\n}\n\n\nfunc (c *Context) MustGetLogger() logging.Logger {\n\tif c.log == nil {\n\t\tpanic(ErrLoggerNotExist)\n\t}\n\n\treturn c.log\n}\n\nfunc NewContext(log logging.Logger) *Context ", "output": "{\n\treturn &Context{\n\t\tlog: log,\n\t}\n}"} {"input": "package content\nimport (\n\t\"go2o/src/core/domain/interface/content\"\n\t\"time\"\n)\n\nvar _ content.IPage = new(Page)\ntype Page struct{\n\t_contentRep content.IContentRep\n\t_partnerId int\n\t_value *content.ValuePage\n}\n\n\n\n\n\nfunc (this *Page) GetDomainId() int{\n\treturn this._value.Id\n}\n\n\nfunc (this *Page) GetValue()*content.ValuePage{\n\treturn this._value\n}\n\n\nfunc (this *Page) SetValue(v *content.ValuePage)error{\n\tv.Id = this.GetDomainId()\n\tthis._value = v\n\treturn nil\n}\n\n\nfunc (this *Page) Save()(int,error){\n\tthis._value.UpdateTime = time.Now().Unix()\n\treturn this._contentRep.SavePage(this._partnerId,this._value)\n}\n\nfunc NewPage(partnerId int, rep content.IContentRep,v *content.ValuePage) content.IPage ", "output": "{\n\treturn &Page{\n\t\t_contentRep: rep,\n\t\t_partnerId: partnerId,\n\t\t_value:v,\n\t}\n}"} {"input": "package tasks\n\nimport (\n\t\"strings\"\n\t\"os/exec\"\n\t\"log\"\n)\n\n\nconst (\n\tPYTHON_COMMAND_ARG = \"command\"\n\tPYTHON_ARGS_ARG = \"args\"\n)\n\ntype Python struct {\n\targs\t\t[]string\n}\n\n\n\nfunc (t *Python) Execute() statusCode {\n\terr := exec.Command(\"python2.7\", t.args...).Run()\n\n\tif err != nil {\n\t\tlog.Printf(\"execute error: %s\\n\", err.Error())\n\t\treturn StatusExecutionError\n\t}\n\n\treturn StatusOk\n}\n\nfunc (t *Python) GetName() string {\n\treturn \"python\"\n}\n\nfunc (t *Python) Configure(args map[string]string) statusCode ", "output": "{\n\tval, ok := args[PYTHON_COMMAND_ARG]\n\n\tif !ok {\n\t\treturn StatusConfigurationError\n\t}\n\tt.args = make([]string, 0)\n\tt.args = append(t.args, val)\n\n\tval, ok = args[PYTHON_ARGS_ARG]\n\tif !ok {\n\t\treturn StatusConfigurationError\n\t}\n\tt.args = append(t.args, strings.Split(val, \" \")...)\n\n\treturn StatusOk\n}"} {"input": "package plugins\n\nimport (\n\t\"../answers\"\n\t\"../ircclient\"\n\t\"strings\"\n)\n\ntype DongPlugin struct {\n\tic *ircclient.IRCClient\n}\n\nfunc (q *DongPlugin) String() string {\n\treturn \"dong\"\n}\n\nfunc (q *DongPlugin) Info() string {\n\treturn `sends back a dong sound for every \\a`\n}\n\nfunc (q *DongPlugin) Usage(cmd string) string {\n\treturn \"\"\n}\n\nfunc (q *DongPlugin) Register(cl *ircclient.IRCClient) {\n\tq.ic = cl\n}\n\n\n\nfunc (q *DongPlugin) ProcessLine(msg *ircclient.IRCMessage) {\n\tif msg.Command != \"PRIVMSG\" {\n\t\treturn\n\t}\n\n\tcount := strings.Count(msg.Args[0], `\\a`)\n\tcount -= strings.Count(msg.Args[0], `\\\\a`)\n\tif count < 1 {\n\t\treturn\n\t}\n\n\tstr := answers.RandStr(\"dong\")\n\tmessage := \"\"\n\n\tfor i := 0; i < count; i++ {\n\t\tmessage += str + \" \"\n\t}\n\n\tq.ic.ReplyMsg(msg, message)\n}\n\nfunc (q *DongPlugin) ProcessCommand(cmd *ircclient.IRCCommand) {\n\treturn\n}\n\nfunc (q *DongPlugin) Unregister() ", "output": "{\n\treturn\n}"} {"input": "package image\n\nimport (\n\t\"github.com/containers/image/types\"\n)\n\n\n\n\ntype imageCloser struct {\n\ttypes.Image\n\tsrc types.ImageSource\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (ic *imageCloser) Close() error {\n\treturn ic.src.Close()\n}\n\n\n\n\n\n\ntype sourcedImage struct {\n\t*UnparsedImage\n\tmanifestBlob []byte\n\tmanifestMIMEType string\n\tgenericManifest\n}\n\n\n\n\n\n\nfunc FromUnparsedImage(ctx *types.SystemContext, unparsed *UnparsedImage) (types.Image, error) {\n\n\tmanifestBlob, manifestMIMEType, err := unparsed.Manifest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparsedManifest, err := manifestInstanceFromBlob(ctx, unparsed.src, manifestBlob, manifestMIMEType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &sourcedImage{\n\t\tUnparsedImage: unparsed,\n\t\tmanifestBlob: manifestBlob,\n\t\tmanifestMIMEType: manifestMIMEType,\n\t\tgenericManifest: parsedManifest,\n\t}, nil\n}\n\n\nfunc (i *sourcedImage) Size() (int64, error) {\n\treturn -1, nil\n}\n\n\nfunc (i *sourcedImage) Manifest() ([]byte, string, error) {\n\treturn i.manifestBlob, i.manifestMIMEType, nil\n}\n\nfunc (i *sourcedImage) Inspect() (*types.ImageInspectInfo, error) {\n\treturn inspectManifest(i.genericManifest)\n}\n\nfunc (i *sourcedImage) LayerInfosForCopy() []types.BlobInfo {\n\treturn i.UnparsedImage.LayerInfosForCopy()\n}\n\nfunc FromSource(ctx *types.SystemContext, src types.ImageSource) (types.ImageCloser, error) ", "output": "{\n\timg, err := FromUnparsedImage(ctx, UnparsedInstance(src, nil))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &imageCloser{\n\t\tImage: img,\n\t\tsrc: src,\n\t}, nil\n}"} {"input": "package client\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/mesosphere/dcos-commons/cli/config\"\n)\n\n\n\nvar PrintMessage = printMessage\n\n\n\nvar PrintMessageAndExit = printMessageAndExit\n\nfunc printMessage(format string, a ...interface{}) (int, error) {\n\treturn fmt.Println(fmt.Sprintf(format, a...))\n}\n\nfunc printMessageAndExit(format string, a ...interface{}) (int, error) {\n\tPrintMessage(format, a...)\n\tos.Exit(1)\n\treturn 0, nil\n}\n\n\nfunc PrintVerbose(format string, a ...interface{}) (int, error) {\n\tif config.Verbose {\n\t\treturn PrintMessage(format, a...)\n\t}\n\treturn 0, nil\n}\n\n\n\n\nfunc PrintJSONBytes(responseBytes []byte) {\n\tvar outBuf bytes.Buffer\n\terr := json.Indent(&outBuf, responseBytes, \"\", \" \")\n\tif err != nil {\n\t\tPrintMessage(\"Failed to prettify JSON response data: %s\", err)\n\t\tPrintMessage(\"Original data follows:\")\n\t\toutBuf = *bytes.NewBuffer(responseBytes)\n\t}\n\tPrintMessage(\"%s\", outBuf.String())\n}\n\n\n\n\nfunc PrintResponseText(body []byte) ", "output": "{\n\tPrintMessage(\"%s\\n\", string(body))\n}"} {"input": "package pathdb\n\nimport (\n\t\"github.com/scionproto/scion/go/lib/common\"\n\t\"github.com/scionproto/scion/go/lib/ctrl/seg\"\n\t\"github.com/scionproto/scion/go/lib/pathdb/conn\"\n\t\"github.com/scionproto/scion/go/lib/pathdb/query\"\n\t\"github.com/scionproto/scion/go/lib/pathdb/sqlite\"\n)\n\ntype DB struct {\n\tconn conn.Conn\n}\n\n\n\n\n\n\n\nfunc (db *DB) Insert(pseg *seg.PathSegment, segTypes []seg.Type) (int, error) {\n\treturn db.conn.Insert(pseg, segTypes)\n}\n\n\n\nfunc (db *DB) InsertWithHPCfgIDs(pseg *seg.PathSegment,\n\tsegTypes []seg.Type, hpCfgIDs []*query.HPCfgID) (int, error) {\n\treturn db.conn.InsertWithHPCfgIDs(pseg, segTypes, hpCfgIDs)\n}\n\n\n\nfunc (db *DB) Delete(segID common.RawBytes) (int, error) {\n\treturn db.conn.Delete(segID)\n}\n\n\n\nfunc (db *DB) DeleteWithIntf(intf query.IntfSpec) (int, error) {\n\treturn db.conn.DeleteWithIntf(intf)\n}\n\n\nfunc (db *DB) Get(params *query.Params) ([]*query.Result, error) {\n\treturn db.conn.Get(params)\n}\n\nfunc New(path string, backend string) (*DB, error) ", "output": "{\n\tdb := &DB{}\n\tvar err error\n\tswitch backend {\n\tcase \"sqlite\":\n\t\tdb.conn, err = sqlite.New(path)\n\tdefault:\n\t\treturn nil, common.NewBasicError(\"Unknown backend\", nil, \"backend\", backend)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn db, nil\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/aodin/volta/config\"\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/codegangsta/envy/lib\"\n\n\t\"github.com/aodin/groupthink/server\"\n)\n\nfunc main() {\n\tenvy.Bootstrap()\n\n\tapp := cli.NewApp()\n\tapp.Name = \"groupthink\"\n\tapp.Usage = \"Start the groupthink server\"\n\tapp.Action = startServer\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName: \"log, l\",\n\t\t\tValue: \"\",\n\t\t\tUsage: \"Sets the log output file path\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"config, c\",\n\t\t\tValue: \"./settings.json\",\n\t\t\tUsage: \"Sets the configuration file\",\n\t\t},\n\t}\n\tapp.Run(os.Args)\n}\n\n\n\nfunc connect(file string) config.Config {\n\tconf, err := config.ParseFile(file)\n\tif err != nil {\n\t\tlog.Panicf(\"groupthink: could not parse configuration: %s\", err)\n\t}\n\treturn conf\n}\n\nfunc startServer(c *cli.Context) ", "output": "{\n\tlogF := c.String(\"log\")\n\tfile := c.String(\"config\")\n\tif logF != \"\" {\n\t\tif err := os.MkdirAll(filepath.Dir(logF), 0776); err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\tl, err := os.OpenFile(logF, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\tdefer l.Close()\n\t\tlog.SetOutput(l)\n\t}\n\tconf := connect(file)\n\tlog.Panic(server.New(conf).ListenAndServe())\n}"} {"input": "package language\n\nimport (\n\t\"database/sql\"\n\t\"time\"\n\t\"xrguide/db/query\"\n)\n\ntype Language struct {\n\tId int64\n\tName string\n}\n\nvar (\n\tlangIdCache = make(map[int64]*Language)\n\tlangNameCache = make(map[string]*Language)\n\tsetCache = make(chan *Language)\n\tgetIdCache = make(chan map[int64]*Language)\n\tgetNameCache = make(chan map[string]*Language)\n)\n\nfunc init() {\n\tgo func() {\n\t\tselect {\n\t\tcase l := <-setCache:\n\t\t\tlangIdCache[l.Id] = l\n\t\t\tlangNameCache[l.Name] = l\n\n\t\tcase getIdCache <- langIdCache:\n\n\t\tcase getNameCache <- langNameCache:\n\t\t}\n\t}()\n}\n\n\n\nfunc LanguageByName(db *sql.DB, name string) (*Language, error) {\n\tvar lang *Language\n\tto := time.After(50 * time.Millisecond)\n\tselect {\n\tcase cache := <-getNameCache:\n\t\tlang, ok := cache[name]\n\t\tif ok {\n\t\t\treturn lang, nil\n\t\t}\n\tcase <-to:\n\t}\n\tlang = new(Language)\n\tq := query.SelectLanguage + \" WHERE name = ?\"\n\trow := db.QueryRow(q, name)\n\terr := row.Scan(&lang.Id, &lang.Name)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tto = time.After(50 * time.Millisecond)\n\tselect {\n\tcase setCache <- lang:\n\tcase <-to:\n\t}\n\treturn lang, nil\n\n}\n\nfunc LanguageById(db *sql.DB, id int64) (*Language, error) ", "output": "{\n\tvar lang *Language\n\tto := time.After(50 * time.Millisecond)\n\tselect {\n\tcase cache := <-getIdCache:\n\t\tlang, ok := cache[id]\n\t\tif ok {\n\t\t\treturn lang, nil\n\t\t}\n\tcase <-to:\n\t}\n\tlang = new(Language)\n\tq := query.SelectLanguage + \" WHERE id = ?\"\n\trow := db.QueryRow(q, id)\n\terr := row.Scan(&lang.Id, &lang.Name)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tto = time.After(50 * time.Millisecond)\n\tselect {\n\tcase setCache <- lang:\n\tcase <-to:\n\t}\n\treturn lang, nil\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\ntype ResourceData struct {\n\n\tData *Resource `json:\"data\"`\n}\n\n\n\n\nfunc (m *ResourceData) validateData(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"data\", \"body\", m.Data); err != nil {\n\t\treturn err\n\t}\n\n\tif m.Data != nil {\n\n\t\tif err := m.Data.Validate(formats); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (m *ResourceData) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package logger\n\nimport (\n\t\"context\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nvar ctxKey = \"go-rest-api:logger\"\n\n\nfunc FromContext(ctx context.Context) (*logrus.Entry, bool) {\n\ti, ok := ctx.Value(ctxKey).(*logrus.Entry)\n\treturn i, ok\n}\n\n\n\n\nfunc Store(ctx context.Context, entry *logrus.Entry) context.Context ", "output": "{\n\tif entry == nil {\n\t\tpanic(\"nil logger given\")\n\t}\n\treturn context.WithValue(ctx, ctxKey, entry)\n}"} {"input": "package time\n\nimport (\n\t\"errors\"\n\t\"syscall\"\n)\n\n\nfunc interrupt() {\n}\n\n\n\n\nfunc readFile(name string) ([]byte, error) {\n\tf, err := syscall.Open(name, syscall.O_RDONLY, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer syscall.Close(f)\n\tvar (\n\t\tbuf [4096]byte\n\t\tret []byte\n\t\tn int\n\t)\n\tfor {\n\t\tn, err = syscall.Read(f, buf[:])\n\t\tif n > 0 {\n\t\t\tret = append(ret, buf[:n]...)\n\t\t}\n\t\tif n == 0 || err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ret, err\n}\n\n\n\nfunc closefd(fd uintptr) {\n\tsyscall.Close(syscall.Handle(fd))\n}\n\nfunc preadn(fd uintptr, buf []byte, off int) error {\n\twhence := seekStart\n\tif off < 0 {\n\t\twhence = seekEnd\n\t}\n\tif _, err := syscall.Seek(syscall.Handle(fd), int64(off), whence); err != nil {\n\t\treturn err\n\t}\n\tfor len(buf) > 0 {\n\t\tm, err := syscall.Read(syscall.Handle(fd), buf)\n\t\tif m <= 0 {\n\t\t\tif err == nil {\n\t\t\t\treturn errors.New(\"short read\")\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tbuf = buf[m:]\n\t}\n\treturn nil\n}\n\nfunc open(name string) (uintptr, error) ", "output": "{\n\tfd, err := syscall.Open(name, syscall.O_RDONLY, 0)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn uintptr(fd), nil\n}"} {"input": "package parentlocator\n\n\n\ntype ParseError struct {\n\tLocatorField string\n\terr error\n}\n\n\n\n\n\n\n\nfunc (e *ParseError) GetInnerErr() error {\n\treturn e.err\n}\n\n\n\n\n\nfunc NewParseError(locatorField string, err error) error {\n\treturn &ParseError{\n\t\tLocatorField: locatorField,\n\t\terr: err,\n\t}\n}\n\nfunc (e *ParseError) Error() string ", "output": "{\n\treturn \"Parse parent locator field\" + \" '\" + e.LocatorField + \"' failed: \" + e.err.Error()\n}"} {"input": "package v1\n\nimport (\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n)\n\n\n\nfunc TestIsReady(t *testing.T) ", "output": "{\n\tstatus := &IdentityStatus{}\n\twant := false\n\n\tgot := status.IsReady()\n\n\tif diff := cmp.Diff(want, got); diff != \"\" {\n\t\tt.Errorf(\"Unexpected difference (-want, +got): %v\", diff)\n\t}\n}"} {"input": "package telemetry\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\n\t\"github.com/pingcap/errors\"\n\tclientv3 \"go.etcd.io/etcd/client/v3\"\n)\n\nconst (\n\tstatusKey = \"/tidb/telemetry/status\"\n)\n\ntype status struct {\n\tCheckAt string `json:\"check_at\"`\n\tIsError bool `json:\"is_error\"`\n\tErrorMessage string `json:\"error_msg\"`\n\tIsRequestSent bool `json:\"is_request_sent\"`\n}\n\n\nfunc updateTelemetryStatus(s status, etcdClient *clientv3.Client) error {\n\tif etcdClient == nil {\n\t\treturn nil\n\t}\n\tj, err := json.MarshalIndent(s, \"\", \" \")\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), etcdOpTimeout)\n\tdefer cancel()\n\t_, err = etcdClient.Put(ctx, statusKey, string(j))\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\treturn nil\n}\n\n\n\n\nfunc GetTelemetryStatus(etcdClient *clientv3.Client) (string, error) ", "output": "{\n\tif etcdClient == nil {\n\t\treturn \"\", nil\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), etcdOpTimeout)\n\tdefer cancel()\n\tresp, err := etcdClient.Get(ctx, statusKey)\n\tif err != nil {\n\t\treturn \"\", errors.Trace(err)\n\t}\n\tif len(resp.Kvs) == 0 {\n\t\treturn \"\", nil\n\t}\n\treturn string(resp.Kvs[0].Value), nil\n}"} {"input": "package delete\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewDeleteNodesIdentifierParams() *DeleteNodesIdentifierParams {\n\tvar ()\n\treturn &DeleteNodesIdentifierParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\nfunc NewDeleteNodesIdentifierParamsWithTimeout(timeout time.Duration) *DeleteNodesIdentifierParams {\n\tvar ()\n\treturn &DeleteNodesIdentifierParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype DeleteNodesIdentifierParams struct {\n\n\tIdentifier string\n\n\ttimeout time.Duration\n}\n\n\n\n\n\nfunc (o *DeleteNodesIdentifierParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"identifier\", o.Identifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (o *DeleteNodesIdentifierParams) WithIdentifier(identifier string) *DeleteNodesIdentifierParams ", "output": "{\n\to.Identifier = identifier\n\treturn o\n}"} {"input": "package subscriptions\n\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"cloud.google.com/go/pubsub\"\n)\n\n\n\nfunc createWithFilter(w io.Writer, projectID, subID, filter string, topic *pubsub.Topic) error ", "output": "{\n\tctx := context.Background()\n\tclient, err := pubsub.NewClient(ctx, projectID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"pubsub.NewClient: %v\", err)\n\t}\n\tdefer client.Close()\n\n\tsub, err := client.CreateSubscription(ctx, subID, pubsub.SubscriptionConfig{\n\t\tTopic: topic,\n\t\tFilter: filter,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"CreateSubscription: %v\", err)\n\t}\n\tfmt.Fprintf(w, \"Created subscription with filter: %v\\n\", sub)\n\treturn nil\n}"} {"input": "package session\n\nimport (\n\t\"net\"\n\t\"time\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/pkg/errors\"\n\t\"golang.org/x/net/context\"\n\t\"golang.org/x/net/http2\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\n\n\nfunc grpcClientConn(ctx context.Context, conn net.Conn) (context.Context, *grpc.ClientConn, error) {\n\tdialOpt := grpc.WithDialer(func(addr string, d time.Duration) (net.Conn, error) {\n\t\treturn conn, nil\n\t})\n\n\tcc, err := grpc.DialContext(ctx, \"\", dialOpt, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to create grpc client\")\n\t}\n\n\tctx, cancel := context.WithCancel(ctx)\n\tgo monitorHealth(ctx, cc, cancel)\n\n\treturn ctx, cc, nil\n}\n\nfunc monitorHealth(ctx context.Context, cc *grpc.ClientConn, cancelConn func()) {\n\tdefer cancelConn()\n\tdefer cc.Close()\n\n\tticker := time.NewTicker(500 * time.Millisecond)\n\tdefer ticker.Stop()\n\thealthClient := grpc_health_v1.NewHealthClient(cc)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\t<-ticker.C\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\t\t\t_, err := healthClient.Check(ctx, &grpc_health_v1.HealthCheckRequest{})\n\t\t\tcancel()\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc serve(ctx context.Context, grpcServer *grpc.Server, conn net.Conn) ", "output": "{\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tconn.Close()\n\t}()\n\tlogrus.Debugf(\"serving grpc connection\")\n\t(&http2.Server{}).ServeConn(conn, &http2.ServeConnOpts{Handler: grpcServer})\n}"} {"input": "package dynaml\n\nimport (\n\t\"fmt\"\n)\n\ntype BooleanExpr struct {\n\tValue bool\n}\n\n\n\nfunc (e BooleanExpr) String() string {\n\treturn fmt.Sprintf(\"%v\", e.Value)\n}\n\nfunc (e BooleanExpr) Evaluate(binding Binding, locally bool) (interface{}, EvaluationInfo, bool) ", "output": "{\n\treturn e.Value, DefaultInfo(), true\n}"} {"input": "package extends\n\ntype CEO interface {\n\tManager\n\tdeleteManager()\n\tIsCEO()\n}\n\ntype ceo struct {\n\tManager\n}\n\n\n\nfunc (p *ceo) IsCEO() {}\n\ntype overwrittenMethodsOnManager struct {\n\tp Manager\n}\n\nfunc NewCEO(name string) CEO {\n\tom := &overwrittenMethodsOnManager{}\n\tp := NewDirectorManager(om, name)\n\tom.p = p\n\n\treturn &ceo{Manager: p}\n}\n\nfunc DeleteCEO(p CEO) {\n\tp.deleteManager()\n}\n\nfunc (p *ceo) GetPosition() string {\n\treturn \"CEO\"\n}\n\nfunc (p *ceo) deleteManager() ", "output": "{\n\tDeleteDirectorManager(p.Manager)\n}"} {"input": "package exec\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\tosexec \"os/exec\"\n\t\"strings\"\n\n\t\"github.com/zimmski/backup\"\n)\n\n\n\n\n\nfunc CombinedWithDirectOutput(name string, args ...string) (string, error) {\n\tif backup.Verbose {\n\t\tfmt.Fprintln(os.Stderr, \"Execute: \", name, strings.Join(args, \" \"))\n\t}\n\n\tcmd := osexec.Command(name, args...)\n\n\tvar buf bytes.Buffer\n\n\tout := io.MultiWriter(os.Stdout, &buf)\n\n\tcmd.Stderr = out\n\tcmd.Stdout = out\n\n\terr := cmd.Run()\n\n\treturn buf.String(), err\n}\n\n\nfunc Command(name string, args ...string) *osexec.Cmd {\n\tif backup.Verbose {\n\t\tfmt.Fprintln(os.Stderr, \"Execute: \", name, strings.Join(args, \" \"))\n\t}\n\n\treturn osexec.Command(name, args...)\n}\n\nfunc Combined(name string, args ...string) (string, error) ", "output": "{\n\tif backup.Verbose {\n\t\tfmt.Fprintln(os.Stderr, \"Execute: \", name, strings.Join(args, \" \"))\n\t}\n\n\tcmd := osexec.Command(name, args...)\n\n\tout, err := cmd.CombinedOutput()\n\n\treturn string(out), err\n}"} {"input": "package vpp2101\n\nimport (\n\tvpp_ip \"go.ligato.io/vpp-agent/v3/plugins/vpp/binapi/vpp2101/ip\"\n\tl3 \"go.ligato.io/vpp-agent/v3/proto/ligato/vpp/l3\"\n)\n\n\nfunc (h *VrfTableHandler) AddVrfTable(table *l3.VrfTable) error {\n\treturn h.addDelVrfTable(table, true)\n}\n\n\nfunc (h *VrfTableHandler) DelVrfTable(table *l3.VrfTable) error {\n\treturn h.addDelVrfTable(table, false)\n}\n\nfunc (h *VrfTableHandler) addDelVrfTable(table *l3.VrfTable, isAdd bool) error {\n\treq := &vpp_ip.IPTableAddDel{\n\t\tTable: vpp_ip.IPTable{\n\t\t\tTableID: table.Id,\n\t\t\tIsIP6: table.GetProtocol() == l3.VrfTable_IPV6,\n\t\t\tName: table.Label,\n\t\t},\n\t\tIsAdd: isAdd,\n\t}\n\treply := &vpp_ip.IPTableAddDelReply{}\n\n\tif err := h.callsChannel.SendRequest(req).ReceiveReply(reply); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc (h *VrfTableHandler) SetVrfFlowHashSettings(vrfID uint32, isIPv6 bool, hashFields *l3.VrfTable_FlowHashSettings) error ", "output": "{\n\treq := &vpp_ip.SetIPFlowHash{\n\t\tVrfID: vrfID,\n\t\tIsIPv6: isIPv6,\n\t\tSrc: hashFields.UseSrcIp,\n\t\tDst: hashFields.UseDstIp,\n\t\tSport: hashFields.UseSrcPort,\n\t\tDport: hashFields.UseDstPort,\n\t\tProto: hashFields.UseProtocol,\n\t\tReverse: hashFields.Reverse,\n\t\tSymmetric: hashFields.Symmetric,\n\t}\n\treply := &vpp_ip.SetIPFlowHashReply{}\n\n\terr := h.callsChannel.SendRequest(req).ReceiveReply(reply)\n\treturn err\n}"} {"input": "package main\n\n\ntype I interface { F() int }\n\n\ntype S struct { }\n\n\n\n\n\n\nfunc NewI(i int) I {\n\treturn new(S)\n}\n\n\nfunc Use(x I) {\n\tx.F()\n}\n\nfunc main() {\n\ti := NewI(0);\n\tUse(i);\n\n\tUse(NewI(0));\n}\n\nfunc (s *S) F() int ", "output": "{ return 1 }"} {"input": "package entities\n\nconst (\n\tActionMove = iota + 1\n\n\tActionAttack\n\n\tActionCastSpell\n\n\tActionGather\n\n\tActionLoot\n\n\tActionConsume\n)\n\n\n\n\n\n\n\n\n\n\n\ntype Action interface {\n\tSetTarget(Entity)\n\tSetSelf(Entity)\n\n\tGetTypeAction() uint8\n\tGetSelf() Entity\n\tGetTarget() Entity\n\n\tPlay() error\n}\n\n\ntype SimpleAction struct {\n\tself Entity\n\ttarget Entity\n\ttypeAction uint8\n}\n\n\nfunc (action *SimpleAction) GetTypeAction() uint8 {\n\treturn action.GetTypeAction()\n}\n\n\nfunc (action *SimpleAction) SetTarget(target Entity) {\n\taction.target = target\n}\n\n\nfunc (action *SimpleAction) GetTarget() Entity {\n\treturn action.target\n}\n\n\nfunc (action *SimpleAction) SetSelf(self Entity) {\n\taction.self = self\n}\n\n\n\n\n\nfunc (action *SimpleAction) Play() error {\n\treturn nil\n}\n\nfunc (action *SimpleAction) GetSelf() Entity ", "output": "{\n\treturn action.self\n}"} {"input": "package vml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/urn/schemas_microsoft_com/vml\"\n)\n\nfunc TestAG_AllShapeAttributesConstructor(t *testing.T) {\n\tv := vml.NewAG_AllShapeAttributes()\n\tif v == nil {\n\t\tt.Errorf(\"vml.NewAG_AllShapeAttributes must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed vml.AG_AllShapeAttributes should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestAG_AllShapeAttributesMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := vml.NewAG_AllShapeAttributes()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := vml.NewAG_AllShapeAttributes()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package version\n\nimport \"fmt\"\n\n\nconst Version = \"1.3.0\"\n\n\n\n\nfunc String() string ", "output": "{\n\treturn fmt.Sprintf(\"schemarshal %s\", Version)\n}"} {"input": "package characteristic\n\nimport (\n\t\"github.com/brutella/hc/model\"\n)\n\ntype HeatingCoolingMode struct {\n\t*ByteCharacteristic\n}\n\nfunc NewHeatingCoolingMode(current model.HeatCoolModeType, charType CharType, permissions []string) *HeatingCoolingMode {\n\tc := HeatingCoolingMode{NewByteCharacteristic(byte(current), permissions)}\n\tc.Type = charType\n\n\treturn &c\n}\n\nfunc NewCurrentHeatingCoolingMode(current model.HeatCoolModeType) *HeatingCoolingMode {\n\treturn NewHeatingCoolingMode(current, CharTypeHeatingCoolingModeCurrent, PermsRead())\n}\n\n\n\nfunc (c *HeatingCoolingMode) SetHeatingCoolingMode(mode model.HeatCoolModeType) {\n\tc.SetByte(byte(mode))\n}\n\nfunc (c *HeatingCoolingMode) HeatingCoolingMode() model.HeatCoolModeType {\n\treturn model.HeatCoolModeType(c.Byte())\n}\n\nfunc NewTargetHeatingCoolingMode(current model.HeatCoolModeType) *HeatingCoolingMode ", "output": "{\n\treturn NewHeatingCoolingMode(current, CharTypeHeatingCoolingModeTarget, PermsAll())\n}"} {"input": "package tests\n\nimport (\n\t\"time\"\n\n\t. \"github.com/smartystreets/assertions\"\n\n\t\"flywheel.io/sdk/api\"\n)\n\n\n\n\nfunc (t *F) SkipTestSearch() ", "output": "{\n\t_, _, _, acquisitionId := t.createTestAcquisition()\n\n\ta, _, err := t.GetAcquisition(acquisitionId)\n\tt.So(err, ShouldBeNil)\n\ttime.Sleep(1000 * time.Millisecond)\n\n\ts := &api.SearchQuery{\n\t\tReturnType: api.SessionString,\n\t\tSearchString: a.Name,\n\t}\n\n\tsR, _, err := t.Search(s)\n\tt.So(err, ShouldBeNil)\n\tt.So(len(sR), ShouldEqual, 1)\n\n\ts = &api.SearchQuery{\n\t\tReturnType: api.AcquisitionString,\n\t\tSearchString: a.Name,\n\t}\n\n\tsR, _, err = t.Search(s)\n\tt.So(err, ShouldBeNil)\n\tt.So(len(sR), ShouldEqual, 1)\n}"} {"input": "package file\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/cosiner/gohper/testing2\"\n)\n\nfunc TestCopyFile(t *testing.T) {\n\ttt := testing2.Wrap(t)\n\tsrc, dst := \"/tmp/copytest\", \"/tmp/copytest.copy\"\n\tif Create(src, nil) == nil {\n\t\ttt.True(Create(src, nil) != nil)\n\t\ttt.True(Copy(dst, src) == nil)\n\t\ttt.True(IsFile(dst))\n\t\tos.Remove(dst)\n\t\tos.Remove(src)\n\t}\n}\n\n\n\nfunc TestWriteFlag(t *testing.T) ", "output": "{\n\ttt := testing2.Wrap(t)\n\ttt.Eq(os.O_APPEND, WriteFlag(false))\n\ttt.Eq(os.O_TRUNC, WriteFlag(true))\n}"} {"input": "package storm\n\nimport (\n\t\"github.com/asdine/storm/codec\"\n\t\"github.com/boltdb/bolt\"\n)\n\n\ntype Node interface {\n\tTx\n\tTypeStore\n\tKeyValueStore\n\tBucketScanner\n\tFrom(addend ...string) Node\n\n\tBucket() []string\n\n\tGetBucket(tx *bolt.Tx, children ...string) *bolt.Bucket\n\n\tCreateBucketIfNotExists(tx *bolt.Tx, bucket string) (*bolt.Bucket, error)\n\n\tWithTransaction(tx *bolt.Tx) Node\n\n\tBegin(writable bool) (Node, error)\n\n\tCodec() codec.EncodeDecoder\n}\n\n\ntype node struct {\n\ts *DB\n\n\trootBucket []string\n\n\ttx *bolt.Tx\n}\n\n\n\n\n\n\nfunc (n node) WithTransaction(tx *bolt.Tx) Node {\n\tn.tx = tx\n\treturn &n\n}\n\n\n\nfunc (n *node) Bucket() []string {\n\treturn n.rootBucket\n}\n\n\nfunc (n *node) Codec() codec.EncodeDecoder {\n\treturn n.s.codec\n}\n\nfunc (n node) From(addend ...string) Node ", "output": "{\n\tn.rootBucket = append(n.rootBucket, addend...)\n\treturn &n\n}"} {"input": "package client\n\nimport (\n\tauthorizationapi \"github.com/openshift/origin/pkg/authorization/api\"\n)\n\n\ntype SubjectAccessReviewsNamespacer interface {\n\tSubjectAccessReviews(namespace string) SubjectAccessReviewInterface\n}\n\n\ntype ClusterSubjectAccessReviews interface {\n\tClusterSubjectAccessReviews() SubjectAccessReviewInterface\n}\n\n\ntype SubjectAccessReviewInterface interface {\n\tCreate(policy *authorizationapi.SubjectAccessReview) (*authorizationapi.SubjectAccessReviewResponse, error)\n}\n\n\ntype subjectAccessReviews struct {\n\tr *Client\n\tns string\n}\n\n\n\n\n\nfunc (c *subjectAccessReviews) Create(policy *authorizationapi.SubjectAccessReview) (result *authorizationapi.SubjectAccessReviewResponse, err error) {\n\tresult = &authorizationapi.SubjectAccessReviewResponse{}\n\terr = c.r.Post().Namespace(c.ns).Resource(\"subjectAccessReviews\").Body(policy).Do().Into(result)\n\treturn\n}\n\n\ntype clusterSubjectAccessReviews struct {\n\tr *Client\n}\n\n\nfunc newClusterSubjectAccessReviews(c *Client) *clusterSubjectAccessReviews {\n\treturn &clusterSubjectAccessReviews{\n\t\tr: c,\n\t}\n}\n\n\nfunc (c *clusterSubjectAccessReviews) Create(policy *authorizationapi.SubjectAccessReview) (result *authorizationapi.SubjectAccessReviewResponse, err error) {\n\tresult = &authorizationapi.SubjectAccessReviewResponse{}\n\terr = c.r.Post().Resource(\"subjectAccessReviews\").Body(policy).Do().Into(result)\n\treturn\n}\n\nfunc newSubjectAccessReviews(c *Client, namespace string) *subjectAccessReviews ", "output": "{\n\treturn &subjectAccessReviews{\n\t\tr: c,\n\t\tns: namespace,\n\t}\n}"} {"input": "package templating\n\nimport (\n\t\"bones/config\"\n\t\"bones/web/handlers\"\n\t\"html/template\"\n\t\"io\"\n\t\"log\"\n)\n\nvar templates *template.Template\n\nfunc NewTemplateRenderer() handlers.TemplateRenderer {\n\tif config.Env().IsProduction() {\n\t\treturn &cachingTemplateRenderer{templates}\n\t}\n\n\tlog.Println(\"Using reloading template renderer\")\n\n\treturn &reloadingTemplateRenderer{}\n}\n\ntype cachingTemplateRenderer struct {\n\ttemplates *template.Template\n}\n\nfunc (r cachingTemplateRenderer) RenderTemplate(wr io.Writer, ctx handlers.TemplateContext) error {\n\tif r.templates == nil {\n\t\tvar err error\n\t\tr.templates, err = template.ParseGlob(\"./templates/*.html\")\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn renderWithLayout(r.templates, wr, ctx.Name(), ctx)\n}\n\ntype reloadingTemplateRenderer struct{}\n\nfunc (r reloadingTemplateRenderer) RenderTemplate(wr io.Writer, ctx handlers.TemplateContext) error {\n\ttemplates, err := template.ParseGlob(\"./templates/*.html\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn renderWithLayout(templates, wr, ctx.Name(), ctx)\n}\n\n\n\nfunc renderWithLayout(t *template.Template, wr io.Writer, name string, data interface{}) error ", "output": "{\n\tfor _, templateName := range []string{\"header.html\", name, \"footer.html\"} {\n\t\terr := t.ExecuteTemplate(wr, templateName, data)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\ntype BuildCommand struct {\n\tType string `short:\"t\" long:\"type\" description:\"Type of environment.\"`\n\tVersion string `short:\"v\" long:\"version\" description:\"Version of environment type.\"`\n\tImage string `short:\"i\" long:\"image\" description:\"Image to use for creating environment.\"`\n\tForcePull bool `long:\"force-pull\" description:\"Force pulling base image.\"`\n}\n\nvar buildCommand BuildCommand\n\nfunc (ccommand *BuildCommand) toBuildOpts(sc SystemClient) BuildOpts {\n\treturn BuildOpts{\n\t\tImage: ImageOpts{\n\t\t\tType: ccommand.Type,\n\t\t\tVersion: ccommand.Version,\n\t\t\tImage: ccommand.Image,\n\t\t},\n\t\tForcePull: ccommand.ForcePull,\n\t\tUsername: sc.Username(),\n\t\tUID: sc.UID(),\n\t\tGID: sc.GID(),\n\t}\n}\n\nfunc (x *BuildCommand) Execute(args []string) error {\n\tdc, err := NewDockerClient(globalOptions.toConnectOpts())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsc, err := NewSystemClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\timage, err := BuildImage(dc, buildCommand.toBuildOpts(sc), os.Stdout)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Built image: \", image)\n\n\treturn nil\n}\n\n\n\nfunc init() ", "output": "{\n\t_, err := parser.AddCommand(\"build\",\n\t\t\"Build an image.\",\n\t\t\"\",\n\t\t&buildCommand)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}"} {"input": "package cpdf\n\nimport (\n\t\"io/ioutil\"\n)\n\n\ntype bookmarkable interface {\n\tCombinedBookmarkList() string\n\tLocalPath() string\n\tDir() string\n}\n\n\n\nfunc writeBookmarkInfoFile(job bookmarkable) error {\n\treturn ioutil.WriteFile(infoPath(job), []byte(job.CombinedBookmarkList()), 0644)\n}\n\nfunc infoPath(job bookmarkable) string {\n\treturn job.Dir() + \"bookmarks.info\"\n}\n\nfunc (c *Cpdf) addBookmarksArgs(job bookmarkable) ", "output": "{\n\tc.addArgs(\"-add-bookmarks\", infoPath(job))\n}"} {"input": "package after\n\nimport (\n\t\"strconv\"\n)\n\ntype order struct {\n\tpid productId\n\tcid customerId\n}\n\ntype productId struct {\n\tid int64\n}\n\n\n\ntype customerId struct {\n\tid int64\n}\n\n\n\ntype orderId struct {\n\tid int64\n}\n\nfunc (oid orderId) String() string {\n\treturn strconv.FormatInt(oid.id, 10)\n}\n\n\n\n\n\nfunc (o order) Submit() (orderId, error) {\n\n\treturn orderId{int64(3252345234)}, nil\n}\n\nfunc CreateOrder(pid int64, cid int64) order ", "output": "{\n\treturn order{\n\t\tpid: productId{pid}, cid: customerId{cid},\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"runtime\"\n\t\"time\"\n)\n\nfunc main() {\n\n\n\tsida1 := \"1 1 1 \\n1 1 1\\n1 1 1\\n\"\n\tsida2 := \"2 2 2 \\n2 2 2\\n2 2 2\\n\"\n\tsida3 := \"3 3 3 \\n3 3 3\\n3 3 3\\n\"\n\tsida4 := \"4 4 4 \\n4 4 4\\n4 4 4\\n\"\n\n\n\tCallClear()\n\tfmt.Printf(sida1)\n\tCallClear()\n\tfmt.Printf(sida2)\n\tCallClear()\n\tfmt.Printf(sida3)\n\tCallClear()\n\tfmt.Printf(sida4)\n\tCallClear()\n\n}\n\nvar clear map[string]func() \n\n\n\nfunc CallClear() {\n\tvalue, ok := clear[runtime.GOOS] \n\tif ok { \n\t\tvalue() \n\t} else { \n\t\tpanic(\"Your platform is unsupported! I can't clear terminal screen :(\")\n\t}\n}\n\nfunc init() ", "output": "{\n\tclear = make(map[string]func()) \n\n\tclear[\"linux\"] = func() {\n\t\ttime.Sleep(1 * time.Second)\n\t\tcmd := exec.Command(\"clear\") \n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Run()\n\t}\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\t\"github.com/webdevops/go-shell\"\n)\n\ntype MysqlDbDump struct {\n\tOptions MysqlCommonOptions `group:\"common\"`\n\tPositional struct {\n\t\tDatabase string `description:\"Database\" required:\"1\"`\n\t\tFilename string `description:\"Backup filename\" required:\"1\"`\n\t} `positional-args:\"true\"`\n}\n\n\n\nfunc (conf *MysqlDbDump) Execute(args []string) error ", "output": "{\n\tLogger.Main(\"Dumping MySQL database \\\"%s\\\" to \\\"%s\\\"\", conf.Positional.Database, conf.Positional.Filename)\n\tif err := conf.Options.Init(); err != nil {\n\t\treturn err\n\t}\n\n\tdefer NewSigIntHandler(func() {})()\n\n\tshell.SetDefaultShell(\"bash\")\n\n\tconf.Options.dumpCompression = GetCompressionByFilename(conf.Positional.Filename)\n\tif (conf.Options.dumpCompression != \"\") {\n\t\tLogger.Step(\"using %s compression\", conf.Options.dumpCompression)\n\t}\n\n\tcmd := shell.Cmd(conf.Options.MysqlDumpCommandBuilder(shell.Quote(conf.Positional.Database))...).Pipe(fmt.Sprintf(\"cat > %s\", shell.Quote(conf.Positional.Filename)))\n\tcmd.Run()\n\n\treturn nil\n}"} {"input": "package handler\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/cosiner/zerver\"\n)\n\ntype MethodHandler interface {\n\tGet(zerver.Request, zerver.Response)\n\tPost(zerver.Request, zerver.Response)\n\tDelete(zerver.Request, zerver.Response)\n\tPut(zerver.Request, zerver.Response)\n\tPatch(zerver.Request, zerver.Response)\n}\n\ntype methodHandler struct {\n\tzerver.Component\n\tMethodHandler\n}\n\nfunc WrapMethodHandler(m MethodHandler) zerver.Handler {\n\treturn &methodHandler{\n\t\tComponent: zerver.NopComponent{},\n\t\tMethodHandler: m,\n\t}\n}\n\n\n\ntype NopMethodHandler struct{}\n\nfunc (NopMethodHandler) Get(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Post(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Delete(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Put(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Patch(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (s methodHandler) Handler(method string) zerver.HandleFunc ", "output": "{\n\tswitch method {\n\tcase zerver.METHOD_GET:\n\t\treturn s.Get\n\tcase zerver.METHOD_POST:\n\t\treturn s.Post\n\tcase zerver.METHOD_DELETE:\n\t\treturn s.Delete\n\tcase zerver.METHOD_PUT:\n\t\treturn s.Put\n\tcase zerver.METHOD_PATCH:\n\t\treturn s.Patch\n\t}\n\n\treturn nil\n}"} {"input": "package coinbasepro\n\nimport (\n\t\"fmt\"\n)\n\ntype WithdrawalCrypto struct {\n\tCurrency string `json:\"currency\"`\n\tAmount string `json:\"amount\"`\n\tCryptoAddress string `json:\"crypto_address\"`\n}\n\ntype WithdrawalCoinbase struct {\n\tCurrency string `json:\"currency\"`\n\tAmount string `json:\"amount\"`\n\tCoinbaseAccountID string `json:\"coinbase_account_id\"`\n}\n\n\n\nfunc (c *Client) CreateWithdrawalCoinbase(newWithdrawalCoinbase *WithdrawalCoinbase) (WithdrawalCoinbase, error) {\n\tvar savedWithdrawal WithdrawalCoinbase\n\turl := fmt.Sprintf(\"/withdrawals/coinbase-account\")\n\t_, err := c.Request(\"POST\", url, newWithdrawalCoinbase, &savedWithdrawal)\n\treturn savedWithdrawal, err\n}\n\nfunc (c *Client) CreateWithdrawalCrypto(newWithdrawalCrypto *WithdrawalCrypto) (WithdrawalCrypto, error) ", "output": "{\n\tvar savedWithdrawal WithdrawalCrypto\n\turl := fmt.Sprintf(\"/withdrawals/crypto\")\n\t_, err := c.Request(\"POST\", url, newWithdrawalCrypto, &savedWithdrawal)\n\treturn savedWithdrawal, err\n}"} {"input": "package http\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n\n\n\n\nfunc clientIP(r *http.Request) string ", "output": "{\n\tclientIP := strings.TrimSpace(r.Header.Get(\"X-Real-Ip\"))\n\tif len(clientIP) > 0 {\n\t\treturn clientIP\n\t}\n\n\tclientIP = r.Header.Get(\"X-Forwarded-For\")\n\tif index := strings.IndexByte(clientIP, ','); index >= 0 {\n\t\tclientIP = clientIP[0:index]\n\t}\n\n\tclientIP = strings.TrimSpace(clientIP)\n\tif len(clientIP) > 0 {\n\t\treturn clientIP\n\t}\n\n\tif ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {\n\t\treturn ip\n\t}\n\n\treturn \"\"\n}"} {"input": "package devops\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype AutomatedDeployStageRollbackPolicy struct {\n}\n\n\n\n\nfunc (m AutomatedDeployStageRollbackPolicy) MarshalJSON() (buff []byte, e error) {\n\ttype MarshalTypeAutomatedDeployStageRollbackPolicy AutomatedDeployStageRollbackPolicy\n\ts := struct {\n\t\tDiscriminatorParam string `json:\"policyType\"`\n\t\tMarshalTypeAutomatedDeployStageRollbackPolicy\n\t}{\n\t\t\"AUTOMATED_STAGE_ROLLBACK_POLICY\",\n\t\t(MarshalTypeAutomatedDeployStageRollbackPolicy)(m),\n\t}\n\n\treturn json.Marshal(&s)\n}\n\nfunc (m AutomatedDeployStageRollbackPolicy) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package docker\n\nimport (\n\t\"os/exec\"\n)\n\nfunc IsExistsNetwork(network string) (bool, error) {\n\treturn isExists(\"network\", network)\n}\n\n\n\nfunc NetworkCreate(network string) error {\n\targs := []string{\"create\", network}\n\tcmd, err := Network(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd.Stderr = nil\n\terr = cmd.Run()\n\treturn err\n}\n\nfunc Network(args []string) (*exec.Cmd, error) ", "output": "{\n\targs = append([]string{\"network\"}, args...)\n\treturn docker(args)\n}"} {"input": "package remote\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"math\"\n\tpb \"rcs/proto\"\n)\n\ntype GrpcHandler func(s *remoteServer, in *pb.GrpcRequest, out *pb.GrpcReply) error\n\nvar grpcRouter map[string]GrpcHandler = map[string]GrpcHandler{\n\t\"online_list\": onlineList,\n}\n\n\nfunc checkPage(in *pb.GrpcRequest) error {\n\tif in.PageNo < 1 {\n\t\tlog.Println(\"checkPage PageNo =\", in.PageNo)\n\t\tin.PageNo = 1\n\t}\n\tif in.PageSize < 1 {\n\t\treturn errors.New(\"PageSize value error\")\n\t}\n\treturn nil\n}\n\nfunc onlineList(s *remoteServer, in *pb.GrpcRequest, out *pb.GrpcReply) error {\n\n\tlog.Println(\"handleGrpc input Action no find.......\")\n\terr := checkPage(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdatajson, counts := s.model.GetPageRec()\n\tout.Data = datajson\n\tout.TotalResults = counts\n\tpages := math.Ceil(float64(counts / in.PageSize))\n\tif float64(in.PageNo) < pages {\n\t\tout.HasNext = true\n\t}\n\treturn nil\n}\n\nfunc handleGrpc(s *remoteServer, in *pb.GrpcRequest) (*pb.GrpcReply, error) ", "output": "{\n\tvar grpcReply pb.GrpcReply\n\tvar err error = nil\n\n\tif len(in.Action) < 1 {\n\t\terr = errors.New(\"handleGrpc input Action err\")\n\t\treturn &grpcReply, err\n\t}\n\thandle := grpcRouter[in.Action]\n\tif handle == nil {\n\t\terr = errors.New(\"handleGrpc input Action no find\")\n\t\treturn &grpcReply, err\n\t}\n\terr = handle(s, in, &grpcReply)\n\treturn &grpcReply, err\n}"} {"input": "package lrucache\n\n\n\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestListMap_PopFront(t *testing.T) {\n\tm := NewListMap()\n\n\tt1 := time.Now().Nanosecond()\n\tt2 := time.Now().Nanosecond()\n\tm.PushBack(1, t1)\n\tm.PushFront(2, t2)\n\n\tv, _ := m.PopFront()\n\tassert.Equal(t, t2, v)\n\n\tv, _ = m.Front()\n\tassert.Equal(t, t1, v)\n\tassert.Equal(t, 1, m.Len())\n\n\tm.PopFront()\n\tm.PopFront()\n\tassert.Equal(t, 0, m.Len())\n}\n\nfunc TestListMap_MoveToFront(t *testing.T) {\n\tm := NewListMap()\n\n\tt1 := time.Now().Nanosecond()\n\tt2 := time.Now().Nanosecond()\n\tm.PushBack(1, t1)\n\tm.PushFront(2, t2)\n\n\tm.MoveToFront(1)\n\n\tv1, _ := m.Back()\n\tv2, _ := m.Front()\n\tassert.Equal(t, t2, v1)\n\tassert.Equal(t, t1, v2)\n}\n\nfunc TestListMap_PushBack(t *testing.T) ", "output": "{\n\tm := NewListMap()\n\n\tt1 := time.Now().Nanosecond()\n\tt2 := time.Now().Nanosecond()\n\tm.PushBack(1, t1)\n\tm.PushFront(2, t2)\n\n\tv, _ := m.Get(1)\n\tassert.Equal(t, t1, v)\n\n\tv1, _ := m.Back()\n\tv2, _ := m.Front()\n\tassert.Equal(t, t1, v1)\n\tassert.Equal(t, t2, v2)\n\tassert.Equal(t, 2, m.Len())\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSGlueCrawler_Schedule struct {\n\n\tScheduleExpression string `json:\"ScheduleExpression,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSGlueCrawler_Schedule) AWSCloudFormationType() string {\n\treturn \"AWS::Glue::Crawler.Schedule\"\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\n\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSGlueCrawler_Schedule) Metadata() map[string]interface{} ", "output": "{\n\treturn r._metadata\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gossamer-irc/lib\"\n\t\"strings\"\n)\n\ntype PendingClient struct {\n\tIrcd *Ircd\n\tConn *IrcConnection\n\tSubnet *lib.Subnet\n\tNick string\n\tIdent string\n\tGecos string\n\tHost string\n}\n\n\n\nfunc (pc *PendingClient) Handle(raw IrcClientMessage) {\n\tswitch msg := raw.(type) {\n\tcase *InvalidIrcClientMessage:\n\t\tbreak\n\tcase *NickIrcClientMessage:\n\t\tlnick := strings.ToLower(msg.Nick)\n\t\t_, found := pc.Subnet.Client[lnick]\n\t\tif found {\n\t\t\tpc.Conn.Send(&IrcNickInUse{msg.Nick})\n\t\t\treturn\n\t\t}\n\t\tpc.Nick = msg.Nick\n\t\tpc.CheckReady()\n\t\tbreak\n\tcase *UserIrcClientMessage:\n\t\tpc.Ident = msg.Ident\n\t\tpc.Gecos = msg.Gecos\n\t\tpc.CheckReady()\n\t\tbreak\n\t}\n}\n\nfunc (pc *PendingClient) CheckReady() {\n\tif pc.Nick == \"\" || pc.Ident == \"\" || pc.Gecos == \"\" {\n\t\treturn\n\t}\n\tlnick := strings.ToLower(pc.Nick)\n\t_, found := pc.Subnet.Client[lnick]\n\tif found {\n\t\tpc.Conn.Send(&IrcNickInUse{pc.Nick})\n\t\tpc.Nick = \"\"\n\t\treturn\n\t}\n\tpc.Ircd.AcceptPendingClient(pc)\n}\n\nfunc NewPendingClient(ircd *Ircd, conn *IrcConnection, subnet *lib.Subnet, host string) *PendingClient ", "output": "{\n\treturn &PendingClient{\n\t\tIrcd: ircd,\n\t\tSubnet: subnet,\n\t\tConn: conn,\n\t\tHost: host,\n\t}\n}"} {"input": "package message\n\nimport (\n\t\"github.com/pinfake/pes6go/data/block\"\n)\n\ntype PlayerFriends struct {\n\t*block.PlayerFriends\n}\n\n\n\nfunc NewPlayerFriends(info *block.PlayerFriends) PlayerFriends {\n\treturn PlayerFriends{info}\n}\n\nfunc (PlayerFriends) GetBlocks() []*block.Block ", "output": "{\n\tvar blocks []*block.Block\n\n\tblocks = append(blocks, block.GetBlocks(0x3082, block.Uint32{0})...)\n\tblocks = append(blocks, block.GetBlocks(0x3086, block.Void{})...)\n\treturn blocks\n}"} {"input": "package co\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\n\t\"github.com/pkg/errors\"\n\n\t\"github.com/ynqa/wego/pkg/corpus/cooccurrence/encode\"\n)\n\ntype CountType = string\n\nconst (\n\tIncrement CountType = \"inc\"\n\tProximity CountType = \"prox\"\n)\n\n\n\ntype Cooccurrence struct {\n\ttyp CountType\n\n\tma map[uint64]float64\n}\n\nfunc New(typ CountType) (*Cooccurrence, error) {\n\tif typ != Increment && typ != Proximity {\n\t\treturn nil, invalidCountTypeError(typ)\n\t}\n\treturn &Cooccurrence{\n\t\ttyp: typ,\n\n\t\tma: make(map[uint64]float64),\n\t}, nil\n}\n\nfunc (c *Cooccurrence) EncodedMatrix() map[uint64]float64 {\n\treturn c.ma\n}\n\nfunc (c *Cooccurrence) Add(left, right int) error {\n\tenc := encode.EncodeBigram(uint64(left), uint64(right))\n\tvar val float64\n\tswitch c.typ {\n\tcase Increment:\n\t\tval = 1\n\tcase Proximity:\n\t\tdiv := left - right\n\t\tif div == 0 {\n\t\t\treturn errors.Errorf(\"Divide by zero on counting co-occurrence\")\n\t\t}\n\t\tval = 1. / math.Abs(float64(div))\n\tdefault:\n\t\treturn invalidCountTypeError(c.typ)\n\t}\n\tc.ma[enc] += val\n\treturn nil\n}\n\nfunc invalidCountTypeError(typ CountType) error ", "output": "{\n\treturn fmt.Errorf(\"invalid relation type: %s not in %s|%s\", typ, Increment, Proximity)\n}"} {"input": "package gitea\n\nimport (\n\t\"fmt\"\n\n\t\"code.gitea.io/gitea/modules/structs\"\n)\n\n\ntype Branch = structs.Branch\n\n\nfunc (c *Client) ListRepoBranches(user, repo string) ([]*Branch, error) {\n\tbranches := make([]*Branch, 0, 10)\n\treturn branches, c.getParsedResponse(\"GET\", fmt.Sprintf(\"/repos/%s/%s/branches\", user, repo), nil, nil, &branches)\n}\n\n\n\n\nfunc (c *Client) GetRepoBranch(user, repo, branch string) (*Branch, error) ", "output": "{\n\tb := new(Branch)\n\treturn b, c.getParsedResponse(\"GET\", fmt.Sprintf(\"/repos/%s/%s/branches/%s\", user, repo, branch), nil, nil, &b)\n}"} {"input": "package zookeeper\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/magneticio/vamp-router/haproxy\"\n\tgologger \"github.com/op/go-logging\"\n\t\"github.com/samuel/go-zookeeper/zk\"\n\t\"strings\"\n\t\"time\"\n)\n\n\ntype ZkClient struct {\n\tconn *zk.Conn\n\thaConfig *haproxy.Config\n\tlog *gologger.Logger\n}\n\n\n\n\nfunc (z *ZkClient) connect(conString string) error {\n\tzks := strings.Split(conString, \",\")\n\tconn, _, err := zk.Connect(zks, (60 * time.Second))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tz.conn = conn\n\treturn nil\n}\n\n\nfunc (z *ZkClient) Watch(path string) {\n\n\tgo z.watcher(path)\n\n}\n\nfunc (z *ZkClient) watcher(path string) error {\n\n\tfor {\n\t\tpayload, _, watch, err := z.conn.GetW(path)\n\n\t\tif err != nil {\n\t\t\tz.log.Error(\"Error from Zookeeper: \" + err.Error())\n\t\t}\n\n\t\terr = json.Unmarshal(payload, &z.haConfig)\n\t\tif err != nil {\n\t\t\tz.log.Error(\"Error parsing config from Zookeeper: \" + err.Error())\n\t\t}\n\n\t\tevent := <-watch\n\n\t\tz.log.Notice(\"Received Zookeeper event: \" + event.Type.String())\n\n\t\terr = json.Unmarshal(payload, &z.haConfig)\n\t\tif err != nil {\n\t\t\tz.log.Error(\"Error parsing config from Zookeeper: \" + err.Error())\n\t\t}\n\n\t}\n\n}\n\nfunc (z *ZkClient) Init(conString string, conf *haproxy.Config, log *gologger.Logger) error ", "output": "{\n\n\tz.log = log\n\tz.haConfig = conf\n\terr := z.connect(conString)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package iomon\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n)\n\n\ntype StatusSetter interface {\n\tSetStatus(s Status)\n}\n\n\ntype Status struct {\n\tCurrent int64\n\tTotal int64\n\n}\n\n\n\n\n\n\n\n\nfunc NewPrinter(w io.Writer, name string) *Printer {\n\treturn &Printer{\n\t\tw: w,\n\t\tname: name,\n\t}\n}\n\nvar _ StatusSetter = (*Printer)(nil)\n\n\n\n\ntype Printer struct {\n\tw io.Writer\n\tname string\n\tprevWidth int\n}\n\n\n\nfunc (p *Printer) SetStatus(status Status) {\n\ts := fmt.Sprintf(\"\\r%-45s %s\", p.name, status)\n\twidth := len(s)\n\tif p.prevWidth > width {\n\t\ts += strings.Repeat(\" \", p.prevWidth-width)\n\t}\n\tp.prevWidth = width\n\tp.w.Write([]byte(s))\n}\n\n\n\nfunc (p *Printer) Done() {\n\tp.w.Write([]byte(\"\\n\"))\n}\n\n\n\nfunc (p *Printer) Clear() {\n\tp.w.Write([]byte(\"\\r\" + strings.Repeat(\" \", p.prevWidth) + \"\\r\"))\n\tp.prevWidth = 0\n}\n\nconst (\n\tKiB = 1024\n\tMiB = 1024 * KiB\n\tGiB = 1024 * MiB\n)\n\n\n\n\nfunc FormatByteCount(n int64) string {\n\tswitch {\n\tcase n < 10*MiB:\n\t\treturn fmt.Sprintf(\"%.0fKiB\", float64(n)/KiB)\n\tcase n < 10*GiB:\n\t\treturn fmt.Sprintf(\"%.1fMiB\", float64(n)/MiB)\n\tdefault:\n\t\treturn fmt.Sprintf(\"%.1fGiB\", float64(n)/GiB)\n\t}\n}\n\nfunc (s Status) String() string ", "output": "{\n\tpercent := 100\n\tif s.Total != 0 {\n\t\tpercent = int(float64(s.Current)/float64(s.Total)*100 + 0.5)\n\t}\n\treturn fmt.Sprintf(\"%3d%% %9s\", percent, FormatByteCount(s.Current))\n}"} {"input": "package route\n\nimport (\n\t\"net/url\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc mustParse(rawurl string) *url.URL {\n\tu, err := url.Parse(rawurl)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn u\n}\n\nfunc TestNewRoute(t *testing.T) {\n\tr := newRoute(\"www.bar.com\", \"/foo\")\n\tif got, want := r.Path, \"/foo\"; got != want {\n\t\tt.Errorf(\"got %q want %q\", got, want)\n\t}\n}\n\nfunc TestAddTarget(t *testing.T) {\n\tu := mustParse(\"http://foo.com/\")\n\n\tr := newRoute(\"www.bar.com\", \"/foo\")\n\tr.addTarget(\"service\", u, 0, nil)\n\n\tif got, want := len(r.Targets), 1; got != want {\n\t\tt.Errorf(\"target length: got %d want %d\", got, want)\n\t}\n\tif got, want := r.Targets[0].URL, u; got != want {\n\t\tt.Errorf(\"target url: got %s want %s\", got, want)\n\t}\n\tconfig := []string{\"route add service www.bar.com/foo http://foo.com/\"}\n\tif got, want := r.config(false), config; !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"config: got %q want %q\", got, want)\n\t}\n}\n\n\n\nfunc TestDelService(t *testing.T) ", "output": "{\n\tu1, u2 := mustParse(\"http://foo.com/\"), mustParse(\"http://bar.com/\")\n\n\tr := newRoute(\"www.bar.com\", \"/foo\")\n\tr.addTarget(\"serviceA\", u1, 0, nil)\n\tr.addTarget(\"serviceB\", u2, 0, nil)\n\tr.delService(\"serviceA\")\n\n\tconfig := []string{\"route add serviceB www.bar.com/foo http://bar.com/\"}\n\tif got, want := r.config(false), config; !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"config: got %q want %q\", got, want)\n\t}\n}"} {"input": "package scaleway\n\nimport (\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/scaleway/scaleway-cli/pkg/api\"\n)\n\n\nfunc Bool(val bool) *bool {\n\treturn &val\n}\n\n\nfunc String(val string) *string {\n\treturn &val\n}\n\n\n\n\nfunc deleteServerSafe(s *api.ScalewayAPI, serverID string) error {\n\tserver, err := s.GetServer(serverID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif server.State != \"stopped\" {\n\t\tif err := s.PostServerAction(serverID, \"poweroff\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := waitForServerState(s, serverID, \"stopped\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := s.DeleteServer(serverID); err != nil {\n\t\treturn err\n\t}\n\tif rootVolume, ok := server.Volumes[\"0\"]; ok {\n\t\tif err := s.DeleteVolume(rootVolume.Identifier); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc waitForServerState(s *api.ScalewayAPI, serverID string, targetState string) error ", "output": "{\n\tvar server *api.ScalewayServer\n\tvar err error\n\n\tvar currentState string\n\n\tfor {\n\t\tserver, err = s.GetServer(serverID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif currentState != server.State {\n\t\t\tlog.Printf(\"[DEBUG] Server changed state to %q\\n\", server.State)\n\t\t\tcurrentState = server.State\n\t\t}\n\t\tif server.State == targetState {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\treturn nil\n}"} {"input": "package driverskeleton\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"periph.io/x/periph\"\n\t\"periph.io/x/periph/conn/i2c/i2ctest\"\n)\n\nfunc TestDriverSkeleton(t *testing.T) {\n\tbus := i2ctest.Playback{\n\t\tOps: []i2ctest.IO{\n\t\t\t{Addr: 42, W: []byte(\"in\"), R: []byte(\"IN\")},\n\t\t\t{Addr: 42, W: []byte(\"what\"), R: []byte(\"Hello world!\")},\n\t\t},\n\t\tDontPanic: true,\n\t}\n\tdev, err := New(&bus)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif data := dev.Read(); data != \"Hello world!\" {\n\t\tt.Fatal(data)\n\t}\n\n\tif data := dev.Read(); !strings.HasPrefix(data, \"i2ctest: unexpected Tx()\") {\n\t\tt.Fatal(data)\n\t}\n}\n\nfunc TestDriverSkeleton_empty(t *testing.T) {\n\tif dev, err := New(&i2ctest.Playback{DontPanic: true}); dev != nil || err == nil {\n\t\tt.Fatal(\"Tx should have failed\")\n\t}\n}\n\nfunc TestDriverSkeleton_init_failed(t *testing.T) {\n\tbus := i2ctest.Playback{\n\t\tOps: []i2ctest.IO{\n\t\t\t{Addr: 42, W: []byte(\"in\"), R: []byte(\"xx\")},\n\t\t},\n\t}\n\tif dev, err := New(&bus); dev != nil || err == nil {\n\t\tt.Fatal(\"New should have failed\")\n\t}\n}\n\n\n\nfunc TestInit(t *testing.T) ", "output": "{\n\tif state, err := periph.Init(); err != nil {\n\t\tt.Fatal(state, err)\n\t}\n}"} {"input": "package ginkgoext\n\nimport (\n\t\"github.com/onsi/gomega/types\"\n)\n\ntype anythingMatcher struct{}\n\n\n\nfunc (matcher *anythingMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn \"\"\n}\n\nfunc (matcher *anythingMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn \"\"\n}\n\n\nfunc BeAnything() types.GomegaMatcher {\n\treturn &anythingMatcher{}\n}\n\nfunc (matcher *anythingMatcher) Match(actual interface{}) (success bool, err error) ", "output": "{\n\treturn true, nil\n}"} {"input": "package k8sclient\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\t\"hash/fnv\"\n\t\"math/rand\"\n\t\"sync\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/google/uuid\"\n)\n\nvar (\n\tseedOnce sync.Once\n\tuuidMutex sync.Mutex\n)\n\nfunc GenerateUUID(seed string) string {\n\tvar stringUUID string\n\tuuidMutex.Lock()\n\tuuid.SetRand(rand.New(rand.NewSource(int64(hash(seed)))))\n\tstringUUID = uuid.New().String()\n\tuuidMutex.Unlock()\n\treturn stringUUID\n}\n\n\nfunc getBytes(value interface{}) []byte {\n\tvar byteBuffer bytes.Buffer\n\tgobEncoder := gob.NewEncoder(&byteBuffer)\n\tif err := gobEncoder.Encode(value); err != nil {\n\t\tglog.Fatalln(\"Failed to encode value\")\n\t\treturn nil\n\t}\n\treturn byteBuffer.Bytes()\n}\n\n\n\nfunc HashCombine(valueOne, valueTwo interface{}) uint64 {\n\tnewHash := fnv.New64()\n\tvalueOneBytes := getBytes(valueOne)\n\tvalueTwoBytes := getBytes(valueTwo)\n\tnewHash.Write(append(valueOneBytes, valueTwoBytes...))\n\treturn newHash.Sum64()\n}\n\nfunc hash(valueOne interface{}) uint64 ", "output": "{\n\tnewHash := fnv.New64()\n\tnewHash.Write(getBytes(valueOne))\n\treturn newHash.Sum64()\n}"} {"input": "package dice\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\nfunc TestRollable_AttackDie(t *testing.T) {\n\tassert := assert.New(t)\n\n\tvar attackDie AttackDie\n\tvar blanks, focuses, hits, crits, evades int\n\n\tfor i := 0; i < 1000; i++ {\n\t\tattackDie.Roll()\n\t\tswitch attackDie.Result() {\n\t\tcase BLANK:\n\t\t\tblanks++\n\t\tcase FOCUS:\n\t\t\tfocuses++\n\t\tcase HIT:\n\t\t\thits++\n\t\tcase CRIT:\n\t\t\tcrits++\n\t\tcase EVADE:\n\t\t\tevades++\n\t\t}\n\t}\n\n\tassert.InEpsilon(int(1000*2.0/8), blanks, 50)\n\tassert.InEpsilon(int(1000*2.0/8), focuses, 50)\n\tassert.InEpsilon(int(1000*3.0/8), hits, 50)\n\tassert.InEpsilon(int(1000*1.0/8), crits, 50)\n\tassert.Equal(0, evades)\n}\n\n\n\nfunc TestRollable_DefenseDie(t *testing.T) ", "output": "{\n\tassert := assert.New(t)\n\n\tvar defenseDie DefenseDie\n\tvar blanks, focuses, hits, crits, evades int\n\n\tfor i := 0; i < 1000; i++ {\n\t\tdefenseDie.Roll()\n\t\tswitch defenseDie.Result() {\n\t\tcase BLANK:\n\t\t\tblanks++\n\t\tcase FOCUS:\n\t\t\tfocuses++\n\t\tcase HIT:\n\t\t\thits++\n\t\tcase CRIT:\n\t\t\tcrits++\n\t\tcase EVADE:\n\t\t\tevades++\n\t\t}\n\t}\n\n\tassert.InEpsilon(int(1000*3.0/8), blanks, 50)\n\tassert.InEpsilon(int(1000*2.0/8), focuses, 50)\n\tassert.Equal(0, hits)\n\tassert.Equal(0, crits)\n\tassert.InEpsilon(int(1000*3.0/8), evades, 50)\n}"} {"input": "package file\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\ntype Reader interface {\n\tio.Reader\n\tio.ReaderAt\n\tio.Seeker\n}\n\ntype Writer interface {\n\tio.Writer\n\tio.Seeker\n\tTruncate(size int64) error\n\tSync() error\n}\n\ntype ReadCloser interface {\n\tReader\n\tio.Closer\n}\n\ntype WriteCloser interface {\n\tWriter\n\tio.Closer\n}\n\ntype File interface {\n\tio.Reader\n\tio.Writer\n\tio.Seeker\n\tio.Closer\n\tio.ReaderAt\n\tTruncate(size int64) error\n\tSync() error\n}\n\n\ntype FileSystem interface {\n\tOpen(name string, flag int) (File, error)\n\n\tLock(name string) (io.Closer, error)\n\n\tExists(name string) bool\n\n\tMkdirAll(path string) error\n\n\tList(dir string) ([]string, error)\n\n\tRemove(filename string) error\n\n\tRename(oldpath, newpath string) error\n}\n\ntype osFileSystem struct{}\n\nfunc (osFileSystem) Open(name string, flag int) (File, error) {\n\treturn os.OpenFile(name, flag, 0666)\n}\n\nfunc (osFileSystem) MkdirAll(path string) error {\n\treturn os.MkdirAll(path, 0740)\n}\n\n\n\nfunc (osFileSystem) List(dir string) ([]string, error) {\n\tf, err := os.Open(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.Readdirnames(-1)\n}\n\nfunc (osFileSystem) Remove(name string) error {\n\treturn os.Remove(name)\n}\n\nfunc (osFileSystem) Rename(oldpath, newpath string) error {\n\treturn os.Rename(oldpath, newpath)\n}\n\nvar DefaultFileSystem FileSystem = osFileSystem{}\n\nfunc (osFileSystem) Exists(name string) bool ", "output": "{\n\t_, err := os.Stat(name)\n\treturn err == nil\n}"} {"input": "package log\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestInitWithNoArgs(t *testing.T) {\n\tlogf := New(os.Stdin)\n\tif logf == nil {\n\t\tt.Errorf(\"Expected non-nil logger\")\n\t}\n\tif logf.Logf == nil {\n\t\tt.Errorf(\"*.Logf should be non-nil\")\n\t}\n\tif logf.Logln == nil {\n\t\tt.Errorf(\"*.Logln should be non-nil\")\n\t}\n\tif logf.LogErrf == nil {\n\t\tt.Errorf(\"*.LogErrf should be non-nil\")\n\t}\n\tif logf.LogErrln == nil {\n\t\tt.Errorf(\"*.LogErrln should be non-nil\")\n\t}\n}\n\n\n\nfunc TestWithOneWriter(t *testing.T) ", "output": "{\n\tlogf := New(os.Stdin, os.Stdout)\n\tif logf == nil {\n\t\tt.Errorf(\"not expecting a nil logger\")\n\t}\n\tlogf.Logf(\"OutPut: %s %v\\n\", \"trivia\", logf)\n\tlogf.Logln(\"OutPut\")\n\n\tlogf = New(os.Stdin, os.Stdout, os.Stderr)\n\n\tif false {\n\t\tvar lineIn string\n\t\tlogf.Log(\"Line in: \")\n\t\tlogf.Scanln(&lineIn)\n\t\tlogf.Logf(\"Read in %s\\n\", lineIn)\n\t}\n\n\tlogf.LogErrf(\"Errf here: %s calling: %v\\n\", \"bingo\", logf)\n\tlogf.LogErrln(\"Errf here:\", \"bing\", \"calling\\n\", logf)\n}"} {"input": "package routetemplate\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\nvar routeTemplates []RouteTemplate\n\nfunc Add(template string) (err error) {\n\trouteTemplate, _ := Parse(template)\n\trouteTemplates = append(routeTemplates, routeTemplate)\n\treturn nil\n}\n\nfunc GetMatchedTemplateString(url string) (template string, err error) {\n\ttemplate = \"\"\n\n\tfor _, value := range routeTemplates {\n\n\t\twasMatched, _ := IsMatch(url, value)\n\t\tif wasMatched {\n\t\t\ttemplate = value.TemplatePath\n\t\t\tbreak\n\t\t}\n\t}\n\treturn template, nil\n}\n\nfunc GetMatchTemplate(url string) (routeTemplateMatch RouteTemplateMatch, err error) {\n\n\trouteTemplateMatch = RouteTemplateMatch{}\n\tfor _, value := range routeTemplates {\n\t\twasMatched, _ := IsMatch(url, value)\n\t\tif wasMatched {\n\n\t\t\trouteTemplateMatch, _ = BindVariables(url, value)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn routeTemplateMatch, nil\n}\n\nfunc GetMatchedTemplate(url string) (template string, err error) {\n\ttemplate = \"\"\n\n\tfor _, value := range routeTemplates {\n\n\t\twasMatched, _ := IsMatch(url, value)\n\t\tif wasMatched {\n\t\t\ttemplate = value.TemplatePath\n\t\t\tbreak\n\t\t}\n\t}\n\treturn template, nil\n}\n\n\n\nfunc GetAllTemplates() (templates []RouteTemplate, err error) {\n\treturn routeTemplates, nil\n}\n\nfunc ClearAllTemplates() (err error) {\n\trouteTemplates = make([]RouteTemplate, 0)\n\treturn nil\n}\n\nfunc AddRoute(name string, method string, urlTemplate string, handler interface{}) ", "output": "{\n\tfmt.Printf(\"%q\\n\", handler)\n\tvar x reflect.Value\n\tif fv, ok := handler.(reflect.Value); ok {\n\t\tx = fv\n\t} else {\n\t\tx = reflect.ValueOf(handler)\n\t}\n\n\targs := make([]reflect.Value, 0, 0)\n\tx.Call(args)\n\tfmt.Printf(\"%q\\n\", x)\n}"} {"input": "package tequilapi\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n\ntype APIServer interface {\n\tWait() error\n\tStartServing() error\n\tStop()\n\tAddress() (string, error)\n}\n\ntype apiServer struct {\n\terrorChannel chan error\n\thandler http.Handler\n\tlistenAddress string\n\tlistener net.Listener\n}\n\n\nfunc NewServer(address string, port int, handler http.Handler, corsPolicy CorsPolicy) APIServer {\n\tserver := apiServer{\n\t\tmake(chan error, 1),\n\t\tDisableCaching(ApplyCors(handler, corsPolicy)),\n\t\tfmt.Sprintf(\"%s:%d\", address, port),\n\t\tnil}\n\treturn &server\n}\n\n\n\n\n\nfunc (server *apiServer) Wait() error {\n\treturn <-server.errorChannel\n}\n\n\nfunc (server *apiServer) Address() (string, error) {\n\tif server.listener == nil {\n\t\treturn \"\", errors.New(\"not bound\")\n\t}\n\treturn extractBoundAddress(server.listener)\n}\n\n\n\nfunc (server *apiServer) StartServing() error {\n\tvar err error\n\tserver.listener, err = net.Listen(\"tcp\", server.listenAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo server.serve(server.handler)\n\treturn nil\n}\n\nfunc (server *apiServer) serve(handler http.Handler) {\n\tserver.errorChannel <- http.Serve(server.listener, handler)\n}\n\nfunc extractBoundAddress(listener net.Listener) (string, error) {\n\taddr := listener.Addr()\n\tparts := strings.Split(addr.String(), \":\")\n\tif len(parts) < 2 {\n\t\treturn \"\", errors.New(\"Unable to locate address: \" + addr.String())\n\t}\n\treturn addr.String(), nil\n}\n\nfunc (server *apiServer) Stop() ", "output": "{\n\tif server.listener == nil {\n\t\treturn\n\t}\n\tserver.listener.Close()\n}"} {"input": "package automation\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" automation/2017-05-15-preview\"\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\n\t\"github.com/coreos/go-etcd/etcd\"\n)\n\n\n\n\n\nfunc (s *Server) etcdRecordCheckin() ", "output": "{\n\tif s.Hostname == \"\" {\n\t\tlog.Printf(\"[WARNING] Unable to checkin server with Ip Address %s due to no hostname (can't resolve and wasn't supplied in JSON).\", s.IpAddress)\n\t\treturn\n\t}\n\tif *Verbose {\n\t\tlog.Printf(\"connecting to: %s%s\", clientConnectionSetup(), Endpoint)\n\t}\n\tclient := etcd.NewClient(clientConnectionSetup())\n\t_, err := client.Get(Endpoint, false, false)\n\tif err != nil {\n\t\t_, err := client.SetDir(Endpoint, 0)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[ERROR] Etcd SetDir Error: %s\", err)\n\t\t\treturn\n\t\t}\n\t}\n\tjson_value, err := json.Marshal(s)\n\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] Json Marshal Error: %s\", err)\n\t\treturn\n\t}\n\tclient.Set(Endpoint+\"/\"+s.Hostname, string(json_value), 0)\n}"} {"input": "package zk\n\nimport \"github.com/go-kit/kit/log\"\n\n\ntype Registrar struct {\n\tclient Client\n\tservice Service\n\tlogger log.Logger\n}\n\n\n\ntype Service struct {\n\tPath string \n\tName string \n\tData []byte \n\tnode string \n}\n\n\n\nfunc NewRegistrar(client Client, service Service, logger log.Logger) *Registrar {\n\treturn &Registrar{\n\t\tclient: client,\n\t\tservice: service,\n\t\tlogger: log.NewContext(logger).With(\n\t\t\t\"service\", service.Name,\n\t\t\t\"path\", service.Path,\n\t\t\t\"data\", string(service.Data),\n\t\t),\n\t}\n}\n\n\nfunc (r *Registrar) Register() {\n\tif err := r.client.Register(&r.service); err != nil {\n\t\tr.logger.Log(\"err\", err)\n\t} else {\n\t\tr.logger.Log(\"action\", \"register\")\n\t}\n}\n\n\n\n\nfunc (r *Registrar) Deregister() ", "output": "{\n\tif err := r.client.Deregister(&r.service); err != nil {\n\t\tr.logger.Log(\"err\", err)\n\t} else {\n\t\tr.logger.Log(\"action\", \"deregister\")\n\t}\n}"} {"input": "package ks\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nfunc ReadBytesFromFile(filename string) ([]byte, error) {\n\tfin, err := os.Open(filename)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ioutil.ReadAll(fin)\n}\n\nfunc ReadLines(r io.Reader) []string {\n\n\tbr := bufio.NewReader(r)\n\tvar res []string\n\n\tfor {\n\t\ts, _, err := br.ReadLine()\n\n\t\tif err != nil {\n\t\t\treturn res\n\t\t}\n\n\t\tres = append(res, string(s))\n\n\t}\n\n}\n\n\n\nfunc FileExists(filename string) bool {\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc ListFiles(folder string) []string ", "output": "{\n\n\tvar res []string\n\n\tfilepath.Walk(fmt.Sprintf(folder),\n\t\tfunc(path string, info os.FileInfo, err error) error {\n\n\t\t\tif info != nil && !info.IsDir() {\n\t\t\t\tres = append(res, info.Name())\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\treturn res\n}"} {"input": "package client\n\nimport (\n\tauthorizationapi \"github.com/openshift/origin/pkg/authorization/api\"\n)\n\n\ntype SubjectAccessReviewsNamespacer interface {\n\tSubjectAccessReviews(namespace string) SubjectAccessReviewInterface\n}\n\n\ntype ClusterSubjectAccessReviews interface {\n\tClusterSubjectAccessReviews() SubjectAccessReviewInterface\n}\n\n\ntype SubjectAccessReviewInterface interface {\n\tCreate(policy *authorizationapi.SubjectAccessReview) (*authorizationapi.SubjectAccessReviewResponse, error)\n}\n\n\ntype subjectAccessReviews struct {\n\tr *Client\n\tns string\n}\n\n\nfunc newSubjectAccessReviews(c *Client, namespace string) *subjectAccessReviews {\n\treturn &subjectAccessReviews{\n\t\tr: c,\n\t\tns: namespace,\n\t}\n}\n\n\n\n\n\ntype clusterSubjectAccessReviews struct {\n\tr *Client\n}\n\n\nfunc newClusterSubjectAccessReviews(c *Client) *clusterSubjectAccessReviews {\n\treturn &clusterSubjectAccessReviews{\n\t\tr: c,\n\t}\n}\n\n\nfunc (c *clusterSubjectAccessReviews) Create(policy *authorizationapi.SubjectAccessReview) (result *authorizationapi.SubjectAccessReviewResponse, err error) {\n\tresult = &authorizationapi.SubjectAccessReviewResponse{}\n\terr = c.r.Post().Resource(\"subjectAccessReviews\").Body(policy).Do().Into(result)\n\treturn\n}\n\nfunc (c *subjectAccessReviews) Create(policy *authorizationapi.SubjectAccessReview) (result *authorizationapi.SubjectAccessReviewResponse, err error) ", "output": "{\n\tresult = &authorizationapi.SubjectAccessReviewResponse{}\n\terr = c.r.Post().Namespace(c.ns).Resource(\"subjectAccessReviews\").Body(policy).Do().Into(result)\n\treturn\n}"} {"input": "package record\n\nimport (\n\t\"crypto\"\n\t\"crypto/rsa\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/royvandewater/meshchain/cryptohelpers\"\n\t\"github.com/royvandewater/meshchain/record/encoding\"\n)\n\n\n\n\ntype signedRootRecord struct {\n\tmetadata Metadata\n\tdata []byte\n\tsignature []byte\n}\n\n\n\n\nfunc (record *signedRootRecord) Hash() ([]byte, error) {\n\tunsignedRootRecord, err := NewUnsignedRootRecord(record.metadata, record.data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn unsignedRootRecord.Hash()\n}\n\n\nfunc (record *signedRootRecord) JSON() (string, error) {\n\thash, err := record.Hash()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmetadata, err := record.metadata.Proto()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tjsonBytes, err := json.Marshal(&encoding.Record{\n\t\tMetadata: metadata,\n\t\tData: record.data,\n\t\tSeal: &encoding.Seal{\n\t\t\tHash: hash,\n\t\t\tSignature: record.signature,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\treturn string(jsonBytes), nil\n}\n\n\n\n\nfunc (record *signedRootRecord) validateSignature() error ", "output": "{\n\tpublicKeys, err := cryptohelpers.BuildRSAPublicKeys(record.metadata.PublicKeys)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thashed, err := record.Hash()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to generate Hash: %v\", err.Error())\n\t}\n\n\tfor _, publicKey := range publicKeys {\n\t\tif nil == rsa.VerifyPSS(publicKey, crypto.SHA256, hashed, record.signature, nil) {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"None of the PublicKeys matches the signature\")\n}"} {"input": "package sleepwalker\n\nimport \"github.com/Sirupsen/logrus\"\n\n\n\nfunc init() ", "output": "{\n\tLog = logrus.New()\n}"} {"input": "package library\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/vapi/library\"\n\t\"github.com/vmware/govmomi/vapi/rest\"\n)\n\ntype rm struct {\n\t*flags.ClientFlag\n\tforce bool\n}\n\nfunc init() {\n\tcli.Register(\"library.rm\", &rm{})\n}\n\nfunc (cmd *rm) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.ClientFlag, ctx = flags.NewClientFlag(ctx)\n\tcmd.ClientFlag.Register(ctx, f)\n}\n\n\n\nfunc (cmd *rm) Description() string {\n\treturn `Delete library or item NAME.\n\nExamples:\n govc library.rm /library_name\n govc library.rm library_id # Use library id if multiple libraries have the same name\n govc library.rm /library_name/item_name`\n}\n\nfunc (cmd *rm) Run(ctx context.Context, f *flag.FlagSet) error {\n\treturn cmd.WithRestClient(ctx, func(c *rest.Client) error {\n\t\tm := library.NewManager(c)\n\t\tres, err := flags.ContentLibraryResult(ctx, c, \"\", f.Arg(0))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch t := res.GetResult().(type) {\n\t\tcase library.Library:\n\t\t\treturn m.DeleteLibrary(ctx, &t)\n\t\tcase library.Item:\n\t\t\treturn m.DeleteLibraryItem(ctx, &t)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"%q is a %T\", f.Arg(0), t)\n\t\t}\n\t})\n}\n\nfunc (cmd *rm) Usage() string ", "output": "{\n\treturn \"NAME\"\n}"} {"input": "package xeth\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/ethereum/go-ethereum/common\"\n)\n\n\n\ntype whisperFilter struct {\n\tid int \n\tref *Whisper \n\n\tcache []WhisperMessage \n\tskip map[common.Hash]struct{} \n\tupdate time.Time \n\n\tlock sync.RWMutex \n}\n\n\nfunc newWhisperFilter(id int, ref *Whisper) *whisperFilter {\n\treturn &whisperFilter{\n\t\tid: id,\n\t\tref: ref,\n\n\t\tupdate: time.Now(),\n\t\tskip: make(map[common.Hash]struct{}),\n\t}\n}\n\n\n\nfunc (w *whisperFilter) messages() []WhisperMessage {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tw.cache = nil\n\tw.update = time.Now()\n\n\tw.skip = make(map[common.Hash]struct{})\n\tmessages := w.ref.Messages(w.id)\n\tfor _, message := range messages {\n\t\tw.skip[message.ref.Hash] = struct{}{}\n\t}\n\treturn messages\n}\n\n\nfunc (w *whisperFilter) insert(messages ...WhisperMessage) {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tfor _, message := range messages {\n\t\tif _, ok := w.skip[message.ref.Hash]; !ok {\n\t\t\tw.cache = append(w.cache, messages...)\n\t\t}\n\t}\n}\n\n\n\n\n\n\nfunc (w *whisperFilter) activity() time.Time {\n\tw.lock.RLock()\n\tdefer w.lock.RUnlock()\n\n\treturn w.update\n}\n\nfunc (w *whisperFilter) retrieve() (messages []WhisperMessage) ", "output": "{\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tmessages, w.cache = w.cache, nil\n\tw.update = time.Now()\n\n\treturn\n}"} {"input": "package blobstore\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync\"\n)\n\ntype localStore struct {\n\tsync.Mutex\n\troot string\n}\n\n\nfunc NewLocalStore(root string) (Store, error) {\n\treturn newLocalStore(root)\n}\n\nfunc (ls *localStore) blobDirname(digest string) string {\n\treturn filepath.Join(ls.root, \"blobs\", digest)\n}\n\nfunc (ls *localStore) blobFilename(digest string) string {\n\treturn filepath.Join(ls.blobDirname(digest), \"blob\")\n}\n\n\n\n\n\nfunc newLocalStore(root string) (*localStore, error) {\n\tls := &localStore{root: root}\n\n\tblobsDirname := ls.blobDirname(\"\")\n\tif err := os.MkdirAll(blobsDirname, os.FileMode(0755)); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create local blob store directory %q: %s\", blobsDirname, err)\n\t}\n\n\treturn ls, nil\n}\n\nfunc (ls *localStore) blobInfoFilename(digest string) string ", "output": "{\n\treturn filepath.Join(ls.blobDirname(digest), \"info.json\")\n}"} {"input": "package muc\n\nimport \"strings\"\n\n\ntype RoomConfigFieldTextMultiValue struct {\n\tvalue []string\n}\n\nfunc newRoomConfigFieldTextMultiValue(values []string) *RoomConfigFieldTextMultiValue {\n\treturn &RoomConfigFieldTextMultiValue{values}\n}\n\n\nfunc (v *RoomConfigFieldTextMultiValue) Value() []string {\n\treturn v.value\n}\n\n\nfunc (v *RoomConfigFieldTextMultiValue) SetText(lines []string) {\n\tv.value = lines\n}\n\n\n\n\nfunc (v *RoomConfigFieldTextMultiValue) Text() string ", "output": "{\n\treturn strings.Join(v.Value(), \" \")\n}"} {"input": "package core\n\nimport (\n \"errors\"\n \"fmt\"\n \"image\"\n \"image/jpeg\"\n \"io\"\n \"os\"\n \"os/exec\"\n)\n\ntype JPEGHandler struct {\n}\n\n\n\nfunc (j *JPEGHandler) Decode(reader io.Reader) (image.Image, error) {\n return jpeg.Decode(reader)\n}\n\nfunc (j *JPEGHandler) Encode(newImgFile *os.File, newImage image.Image) error {\n return jpeg.Encode(newImgFile, newImage, nil)\n}\n\nfunc (j *JPEGHandler) Convert(newImageTempPath string, quality uint) error {\n args := []string{fmt.Sprintf(\"--max=%d\", quality), newImageTempPath}\n cmd := exec.Command(\"jpegoptim\", args...)\n err := cmd.Run()\n if err != nil {\n return errors.New(\"Jpegoptim command not working\")\n }\n\n return nil\n}\n\nfunc (j *JPEGHandler) ImageType() string ", "output": "{\n return \"image/png\"\n}"} {"input": "package event\n\nimport (\n\t\"github.com/hyperledger/fabric-protos-go/gateway\"\n\t\"github.com/hyperledger/fabric-protos-go/peer\"\n\t\"github.com/hyperledger/fabric/common/ledger\"\n)\n\ntype ChaincodeEventsIterator struct {\n\tblockIter *BlockIterator\n}\n\nfunc NewChaincodeEventsIterator(iterator ledger.ResultsIterator) *ChaincodeEventsIterator {\n\treturn &ChaincodeEventsIterator{\n\t\tblockIter: NewBlockIterator(iterator),\n\t}\n}\n\nfunc (iter *ChaincodeEventsIterator) Next() (*gateway.ChaincodeEventsResponse, error) {\n\tfor {\n\t\tresult, err := iter.nextBlock()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(result.Events) > 0 {\n\t\t\treturn result, nil\n\t\t}\n\t}\n}\n\nfunc (iter *ChaincodeEventsIterator) nextBlock() (*gateway.ChaincodeEventsResponse, error) {\n\tblock, err := iter.blockIter.Next()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tevents, err := chaincodeEventsFromBlock(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := &gateway.ChaincodeEventsResponse{\n\t\tBlockNumber: block.Number(),\n\t\tEvents: events,\n\t}\n\treturn result, nil\n}\n\n\n\nfunc (iter *ChaincodeEventsIterator) Close() {\n\titer.blockIter.Close()\n}\n\nfunc chaincodeEventsFromBlock(block *Block) ([]*peer.ChaincodeEvent, error) ", "output": "{\n\ttransactions, err := block.Transactions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar results []*peer.ChaincodeEvent\n\n\tfor _, transaction := range transactions {\n\t\tif !transaction.Valid() {\n\t\t\tcontinue\n\t\t}\n\n\t\tevents, err := transaction.ChaincodeEvents()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, event := range events {\n\t\t\tresults = append(results, event.ProtoMessage())\n\t\t}\n\t}\n\n\treturn results, nil\n}"} {"input": "package client\n\nimport (\n\t\"net/url\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\nfunc (cli *Client) PluginRemove(ctx context.Context, name string, options types.PluginRemoveOptions) error ", "output": "{\n\tquery := url.Values{}\n\tif options.Force {\n\t\tquery.Set(\"force\", \"1\")\n\t}\n\n\tresp, err := cli.delete(ctx, \"/plugins/\"+name, query, nil)\n\tensureReaderClosed(resp)\n\treturn err\n}"} {"input": "package web\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/siggy/bbox/beatboxer/render\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\ntype Web struct {\n\thub *Hub\n}\n\nfunc InitWeb() *Web {\n\tlog.Debugf(\"InitWeb\")\n\n\thub := newHub()\n\tgo hub.run()\n\n\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"beatboxer/render/web/color.html\")\n\t})\n\thttp.HandleFunc(\"/beatboxer\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"beatboxer/render/web/beatboxer.html\")\n\t})\n\thttp.HandleFunc(\"/jquery-1.11.1.js\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"beatboxer/render/web/jquery-1.11.1.js\")\n\t})\n\thttp.HandleFunc(\"/ws\", func(w http.ResponseWriter, r *http.Request) {\n\t\tserveWs(hub, w, r)\n\t})\n\tgo func() {\n\t\terr := http.ListenAndServe(\":8080\", nil)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"ListenAndServe: \", err)\n\t\t}\n\t}()\n\n\treturn &Web{\n\t\thub: hub,\n\t}\n}\n\n\n\nfunc (w *Web) Phone() <-chan phoneEvent {\n\treturn w.hub.phoneEvents\n}\n\nfunc (w *Web) Render(state render.State) ", "output": "{\n\tb, err := json.Marshal(state)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tgo func() { w.hub.render <- b }()\n}"} {"input": "package bevm\n\nimport (\n\t\"encoding/hex\"\n\t\"sync\"\n\n\t\"go.dedis.ch/onet/v3/log\"\n\n\t\"github.com/ethereum/go-ethereum/common\"\n)\n\n\n\ntype kv struct {\n\tk, v []byte\n\tdel bool\n}\n\n\ntype lowLevelDb interface {\n\tput(key []byte, value []byte) error\n\tdelete(key []byte) error\n\tgetLock() *sync.RWMutex\n}\n\ntype memBatch struct {\n\tdb lowLevelDb\n\twrites []kv\n\tsize int\n}\n\n\n\n\n\n\n\nfunc (b *memBatch) Delete(key []byte) error {\n\tlog.Lvlf3(\"memBatch.Delete(key=%v)\", hex.EncodeToString(key))\n\n\tb.writes = append(b.writes, kv{common.CopyBytes(key), nil, true})\n\tb.size++\n\n\treturn nil\n}\n\n\nfunc (b *memBatch) Write() error {\n\tb.db.getLock().Lock()\n\tlog.Lvl3(\"memBatch.Write()\")\n\tdefer b.db.getLock().Unlock()\n\n\tvar err error\n\n\tfor _, kv := range b.writes {\n\t\tif kv.del {\n\t\t\terr = b.db.delete(kv.k)\n\t\t} else {\n\t\t\terr = b.db.put(kv.k, kv.v)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\nfunc (b *memBatch) ValueSize() int {\n\tlog.Lvl3(\"memBatch.ValueSize()\")\n\n\treturn b.size\n}\n\n\nfunc (b *memBatch) Reset() {\n\tlog.Lvl3(\"memBatch.Reset()\")\n\n\tb.writes = b.writes[:0]\n\tb.size = 0\n}\n\nfunc (b *memBatch) Put(key, value []byte) error ", "output": "{\n\tlog.Lvlf3(\"memBatch.Put(key=%v, value=%v)\", hex.EncodeToString(key),\n\t\thex.EncodeToString(value))\n\n\tb.writes = append(b.writes, kv{common.CopyBytes(key),\n\t\tcommon.CopyBytes(value), false})\n\tb.size += len(value)\n\n\treturn nil\n}"} {"input": "package llvm\n\n\nimport \"C\"\n\nimport (\n\t\"errors\"\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\nfunc ParseCommandLineOptions(args []string, overview string) {\n\targstrs := make([]*C.char, len(args))\n\tfor i, arg := range args {\n\t\targstrs[i] = C.CString(arg)\n\t\tdefer C.free(unsafe.Pointer(argstrs[i]))\n\t}\n\toverviewstr := C.CString(overview)\n\tdefer C.free(unsafe.Pointer(overviewstr))\n\tC.LLVMParseCommandLineOptions(C.int(len(args)), &argstrs[0], overviewstr)\n}\n\nfunc LoadLibraryPermanently(lib string) error ", "output": "{\n\tvar errstr *C.char\n\tlibstr := C.CString(lib)\n\tdefer C.free(unsafe.Pointer(libstr))\n\tC.LLVMLoadLibraryPermanently2(libstr, &errstr)\n\tif errstr != nil {\n\t\terr := errors.New(C.GoString(errstr))\n\t\tC.LLVMFree(unsafe.Pointer(errstr))\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package engine\n\n\ntype Novel struct {\n\tName string \n\tLastUpdateTime string \n\tAuthor string \n\tMenuURL string \n\tIconURL string \n\tNewestLastChapterName string \n\tDescription string \n\tMenus []*Menu \n\tChapters []*Chapter \n}\n\n\ntype Menu struct {\n\tName string \n\tURL string \n}\n\n\ntype Chapter struct {\n\tTitle string \n\tContent string \n}\n\nfunc (novel *Novel) AddMenu(menu *Menu) {\n\tnovel.Menus = append(novel.Menus, menu)\n}\n\n\n\nfunc NewMenu(name, url string) *Menu {\n\treturn &Menu{name, url}\n}\n\nfunc NewChapter(title, content string) *Chapter {\n\treturn &Chapter{title, content}\n}\n\nfunc (novel *Novel) AddChapter(chapter *Chapter) ", "output": "{\n\tnovel.Chapters = append(novel.Chapters, chapter)\n}"} {"input": "package main\n\n\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/mediocregopher/seq\"\n)\n\n\n\n\n\nfunc NewSeqIoReader(read io.Reader, delim byte) *seq.Lazy {\n\tthunk := seqIoThunk(bufio.NewReader(read), delim)\n\treturn seq.NewLazy(thunk)\n}\n\nfunc main() {\n\tfile, err := os.Open(\"/tmp/numbers\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsir := NewSeqIoReader(file, '\\n')\n\n\tfmt.Println(sir)\n\tfmt.Println(sir)\n}\n\nfunc seqIoThunk(reader *bufio.Reader, delim byte) seq.Thunk ", "output": "{\n\treturn func() (interface{}, seq.Thunk, bool) {\n\t\tdata, err := reader.ReadString(delim)\n\t\tif err != nil {\n\t\t\treturn nil, nil, false\n\t\t}\n\t\ttdata := strings.TrimRight(data, \"\\n\")\n\t\treturn tdata, seqIoThunk(reader, delim), true\n\t}\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"time\"\n \"net/http\"\n \"encoding/json\"\n \"io/ioutil\"\n\n \"github.com/gorilla/mux\"\n)\n\ntype Play struct {\n Key string `json:\"key\" redis:\"-\"`\n SeasonKey string `json:\"season_key\" redis:\"season_key\"`\n QueenKey string `json:\"queen_key\" redis:\"queen_key\"`\n PlayTypeKey string `json:\"play_type_key\" redis:\"play_type_key\"`\n EpisodeKey string `json:\"episode_key\" redis:\"episode_key\"`\n Timestamp int64 `json:\"timestamp\" redis:\"timestamp\"`\n}\n\n\n\nfunc DeletePlay(w http.ResponseWriter, r *http.Request) {\n season_key := mux.Vars(r)[\"season_id\"]\n play_key := mux.Vars(r)[\"play_key\"]\n\n fmt.Println(\"DELTE play: \", play_key)\n\n var del_play Play\n del_play.Key = play_key\n success := GetObject(play_key, &del_play)\n fmt.Println(\"GOT QUEEN: \", del_play)\n if (season_key != del_play.SeasonKey) {\n fmt.Println(\"Hey, you are trying todelerte a play that doesn't belong here.\")\n success = false\n }\n\n if (success) {\n success = DeleteObject(\"play\", play_key, del_play)\n }\n\n if (success) {\n fmt.Fprintf(w, \"200 OK (deleted)\")\n } else {\n fmt.Fprintf(w, \"KEY DOES NOT EXIST\")\n }\n\n}\n\nfunc PostPlay(w http.ResponseWriter, r *http.Request) ", "output": "{\n fmt.Println(\"PostPlay\")\n\n var new_play Play\n b, _ := ioutil.ReadAll(r.Body)\n fmt.Println(string(b))\n json.Unmarshal(b, &new_play)\n\n\n season_key := mux.Vars(r)[\"season_id\"]\n new_play.SeasonKey = season_key\n new_play.Timestamp = time.Now().Unix()\n\n _, success := AddObject(\"play\", new_play)\n if success {\n fmt.Fprintf(w, \"201 Created\")\n } else {\n \n fmt.Fprintf(w, \"ERR\")\n }\n}"} {"input": "package block\n\nimport (\n\t\"github.com/juju/cmd\"\n\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/cmd/envcmd\"\n)\n\nvar (\n\tBlockClient = &getBlockClientAPI\n\tUnblockClient = &getUnblockClientAPI\n\tListClient = &getBlockListAPI\n\n\tNewDestroyCommand = newDestroyCommand\n\tNewRemoveCommand = newRemoveCommand\n\tNewChangeCommand = newChangeCommand\n\tNewListCommand = newListCommand\n)\n\ntype MockBlockClient struct {\n\tBlockType string\n\tMsg string\n}\n\nfunc (c *MockBlockClient) Close() error {\n\treturn nil\n}\n\n\n\nfunc (c *MockBlockClient) SwitchBlockOff(blockType string) error {\n\tc.BlockType = blockType\n\tc.Msg = \"\"\n\treturn nil\n}\n\nfunc (c *MockBlockClient) List() ([]params.Block, error) {\n\tif c.BlockType == \"\" {\n\t\treturn []params.Block{}, nil\n\t}\n\n\treturn []params.Block{\n\t\tparams.Block{\n\t\t\tType: c.BlockType,\n\t\t\tMessage: c.Msg,\n\t\t},\n\t}, nil\n}\n\nfunc NewUnblockCommandWithClient(client UnblockClientAPI) cmd.Command {\n\treturn envcmd.Wrap(&unblockCommand{client: client})\n}\n\nfunc (c *MockBlockClient) SwitchBlockOn(blockType, msg string) error ", "output": "{\n\tc.BlockType = blockType\n\tc.Msg = msg\n\treturn nil\n}"} {"input": "package api\n\ntype FormatsResponse struct {\n\tFormats []string `json:\"formats\"`\n}\n\n\n\ntype LeechTypesResponse struct {\n\tLeechTypes []string `json:\"leech_types\"`\n}\n\nfunc (a *API) getLeechTypes(ctx *context) {\n\tctx.Success(LeechTypesResponse{LeechTypes: a.c.leechTypes.Keys()})\n}\n\ntype MediaResponse struct {\n\tMedia []string `json:\"media\"`\n}\n\nfunc (a *API) getMedia(ctx *context) {\n\tctx.Success(MediaResponse{Media: a.c.media.Keys()})\n}\n\ntype ReleaseGroupTypesResponse struct {\n\tReleaseGroupTypes []string `json:\"release_group_types\"`\n}\n\nfunc (a *API) getReleaseGroupTypes(ctx *context) {\n\tctx.Success(ReleaseGroupTypesResponse{ReleaseGroupTypes: a.c.releaseGroupTypes.Keys()})\n}\n\ntype ReleasePropertiesResponse struct {\n\tReleaseProperties []string `json:\"release_properties\"`\n}\n\nfunc (a *API) getReleaseProperties(ctx *context) {\n\tctx.Success(ReleasePropertiesResponse{ReleaseProperties: a.c.releaseProperties.Keys()})\n}\n\ntype ReleaseRolesResponse struct {\n\tReleaseRoles []string `json:\"release_roles\"`\n}\n\nfunc (a *API) getReleaseRoles(ctx *context) {\n\tctx.Success(ReleaseRolesResponse{ReleaseRoles: a.c.releaseRoles.Keys()})\n}\n\ntype PrivilegesResponse struct {\n\tPrivileges []string `json:\"privileges\"`\n}\n\nfunc (a *API) getPrivileges(ctx *context) {\n\tctx.Success(PrivilegesResponse{Privileges: a.c.privileges.Keys()})\n}\n\nfunc (a *API) getFormats(ctx *context) ", "output": "{\n\tctx.Success(FormatsResponse{Formats: a.c.formats.Keys()})\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/rbac/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"github.com/hyperhq/client-go/tools/cache\"\n)\n\n\ntype ClusterRoleBindingLister interface {\n\tList(selector labels.Selector) (ret []*v1.ClusterRoleBinding, err error)\n\tGet(name string) (*v1.ClusterRoleBinding, error)\n\tClusterRoleBindingListerExpansion\n}\n\n\ntype clusterRoleBindingLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewClusterRoleBindingLister(indexer cache.Indexer) ClusterRoleBindingLister {\n\treturn &clusterRoleBindingLister{indexer: indexer}\n}\n\n\nfunc (s *clusterRoleBindingLister) List(selector labels.Selector) (ret []*v1.ClusterRoleBinding, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ClusterRoleBinding))\n\t})\n\treturn ret, err\n}\n\n\n\n\nfunc (s *clusterRoleBindingLister) Get(name string) (*v1.ClusterRoleBinding, error) ", "output": "{\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"clusterrolebinding\"), name)\n\t}\n\treturn obj.(*v1.ClusterRoleBinding), nil\n}"} {"input": "package main\n\n\n\n\nimport \"C\"\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime/pprof\"\n\t\"time\"\n\t\"unsafe\"\n)\n\nfunc init() {\n\tregister(\"CgoPprofThread\", CgoPprofThread)\n\tregister(\"CgoPprofThreadNoTraceback\", CgoPprofThreadNoTraceback)\n}\n\nfunc CgoPprofThread() {\n\truntime.SetCgoTraceback(0, unsafe.Pointer(C.pprofCgoThreadTraceback), nil, nil)\n\tpprofThread()\n}\n\n\n\nfunc pprofThread() {\n\tf, err := os.CreateTemp(\"\", \"prof\")\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(2)\n\t}\n\n\tif err := pprof.StartCPUProfile(f); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(2)\n\t}\n\n\tC.runCPUHogThread()\n\n\tt0 := time.Now()\n\tfor C.getCPUHogThreadCount() < 2 && time.Since(t0) < time.Second {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\n\tpprof.StopCPUProfile()\n\n\tname := f.Name()\n\tif err := f.Close(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Println(name)\n}\n\nfunc CgoPprofThreadNoTraceback() ", "output": "{\n\tpprofThread()\n}"} {"input": "package expr\n\ntype (\n\tGRPCExpr struct {\n\t\tServices []*GRPCServiceExpr\n\t\tErrors []*GRPCErrorExpr\n\t}\n)\n\n\nfunc (g *GRPCExpr) Service(name string) *GRPCServiceExpr {\n\tfor _, res := range g.Services {\n\t\tif res.Name() == name {\n\t\t\treturn res\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\n\n\nfunc (g *GRPCExpr) EvalName() string {\n\treturn \"API GRPC\"\n}\n\nfunc (g *GRPCExpr) ServiceFor(s *ServiceExpr) *GRPCServiceExpr ", "output": "{\n\tif res := g.Service(s.Name); res != nil {\n\t\treturn res\n\t}\n\tres := &GRPCServiceExpr{\n\t\tServiceExpr: s,\n\t}\n\tg.Services = append(g.Services, res)\n\treturn res\n}"} {"input": "package unittest\n\nimport (\n\t\"io/ioutil\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/Huawei/dockyard/utils\"\n)\n\n\nfunc TestMetaEncrypt(t *testing.T) {\n\tvar item utils.MetaItem\n\n\titem.SetEncryption(utils.EncryptRSA)\n\tassert.Equal(t, true, item.GetEncryption() == utils.EncryptRSA, \"Fail to set/get entrypt method\")\n}\n\n\n\n\n\nfunc TestMetaTime(t *testing.T) {\n\ttest1 := \"test1\"\n\ttest1Byte := []byte(\"test1 byte\")\n\tmetaItem1 := utils.GenerateMetaItem(test1, test1Byte)\n\tmetaItem2 := metaItem1\n\tassert.Equal(t, metaItem1, metaItem2, \"Fail to compare metaItem, should be the same\")\n\n\tmetaItem2.SetCreated(metaItem2.GetCreated().Add(time.Hour * 1))\n\tcmp := metaItem1.Compare(metaItem2)\n\tassert.Equal(t, cmp < 0, true, \"Fail to compare metaItem, should be smaller\")\n\n\tassert.Equal(t, metaItem2.IsExpired(), false, \"Fail to get expired information\")\n\tmetaItem2.SetExpired(time.Now().Add(time.Hour * (-1)))\n\tassert.Equal(t, metaItem2.IsExpired(), true, \"Fail to get expired information\")\n}\n\nfunc TestMetaItemGenerate(t *testing.T) ", "output": "{\n\t_, path, _, _ := runtime.Caller(0)\n\tdir := filepath.Join(filepath.Dir(path), \"testdata\")\n\n\ttestContentFile := filepath.Join(dir, \"hello.txt\")\n\ttestHashFile := filepath.Join(dir, \"hello.hash\")\n\tcontentByte, _ := ioutil.ReadFile(testContentFile)\n\thashByte, _ := ioutil.ReadFile(testHashFile)\n\tmetaItem := utils.GenerateMetaItem(\"hello.txt\", contentByte)\n\tassert.Equal(t, metaItem.GetHash(), strings.TrimSpace(string(hashByte)), \"Fail to get correct hash value\")\n}"} {"input": "package log\n\nimport (\n\t\"github.com/proidiot/gone/errors\"\n\t\"github.com/proidiot/gone/log/opt\"\n\t\"github.com/proidiot/gone/log/pri\"\n)\n\ntype testSyslogger struct {\n\tLastPri pri.Priority\n\tLastMsg interface{}\n\tTriggerError bool\n}\n\nfunc (t *testSyslogger) triggerError() error {\n\tif t.TriggerError {\n\t\treturn errors.New(\"Artificial error triggered in testSyslogger\")\n\t}\n\n\treturn nil\n}\n\nfunc (t *testSyslogger) Syslog(p pri.Priority, msg interface{}) error {\n\tt.LastPri = p\n\tt.LastMsg = msg\n\treturn t.triggerError()\n}\n\nfunc (t *testSyslogger) Openlog(string, opt.Option, pri.Priority) error {\n\treturn t.triggerError()\n}\n\n\n\ntype limitedSyslogger struct {\n\tLastPri pri.Priority\n\tLastMsg interface{}\n\tTriggerError bool\n}\n\nfunc (l *limitedSyslogger) triggerError() error {\n\tif l.TriggerError {\n\t\treturn errors.New(\n\t\t\t\"Artificial error triggered in limitedSyslogger\",\n\t\t)\n\t}\n\n\treturn nil\n}\n\nfunc (l *limitedSyslogger) Syslog(p pri.Priority, msg interface{}) error {\n\tl.LastPri = p\n\tl.LastMsg = msg\n\treturn l.triggerError()\n}\n\nfunc (t *testSyslogger) Close() error ", "output": "{\n\treturn t.triggerError()\n}"} {"input": "package slack\n\nimport (\n\t\"github.com/nlopes/slack\"\n\t\"github.com/pkg/errors\"\n)\n\n\ntype Client struct {\n\tapi *slack.Client\n}\n\n\n\n\n\nfunc (c *Client) GetChannelID(channel string) (string, error) {\n\tchs, err := c.api.GetChannels(true)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to list Slack channels\")\n\t}\n\n\tfor _, ch := range chs {\n\t\tif ch.Name == channel {\n\t\t\treturn ch.ID, nil\n\t\t}\n\t}\n\n\treturn \"\", errors.Errorf(\"channel %s is not found\", channel)\n}\n\n\nfunc (c *Client) PostMessageWithAttachment(channelID, color, title, text string, fields []*AttachmentField) error {\n\tattachmentFields := []slack.AttachmentField{}\n\n\tfor _, field := range fields {\n\t\tattachmentFields = append(attachmentFields, slack.AttachmentField{\n\t\t\tTitle: field.Title,\n\t\t\tValue: field.Value,\n\t\t\tShort: true,\n\t\t})\n\t}\n\n\tparams := slack.PostMessageParameters{\n\t\tAttachments: []slack.Attachment{\n\t\t\tslack.Attachment{\n\t\t\t\tTitle: title,\n\t\t\t\tText: text,\n\t\t\t\tColor: color,\n\t\t\t\tFields: attachmentFields,\n\t\t\t},\n\t\t},\n\t}\n\n\t_, _, err := c.api.PostMessage(channelID, \"\", params)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to post message to Slack\")\n\t}\n\n\treturn nil\n}\n\nfunc NewClient(token string) *Client ", "output": "{\n\treturn &Client{\n\t\tapi: slack.New(token),\n\t}\n}"} {"input": "package command\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/consul/testutil\"\n\t\"github.com/mitchellh/cli\"\n)\n\n\n\nfunc TestPutCommandStdin(t *testing.T) {\n\tsrv := testutil.NewTestServer(t)\n\tdefer srv.Stop()\n\n\tui := new(cli.MockUi)\n\tinput := bytes.NewBufferString(\"bar\")\n\tc := &PutCommand{UI: ui, Input: input}\n\n\tos.Setenv(\"CONSUL_HTTP_ADDR\", srv.HTTPAddr)\n\targs := []string{\"foo\"}\n\tcode := c.Run(args)\n\tif code != 0 {\n\t\tt.Fatalf(\"Unexpected code: %d err: %s\", code, ui.ErrorWriter.String())\n\t}\n\tval := srv.GetKV(\"foo\")\n\tif string(val) != \"bar\" {\n\t\tt.Fatalf(\"Invalid value %s\", val)\n\t}\n}\n\nfunc TestPutCommand(t *testing.T) ", "output": "{\n\tsrv := testutil.NewTestServer(t)\n\tdefer srv.Stop()\n\n\tui := new(cli.MockUi)\n\tc := &PutCommand{UI: ui}\n\n\tos.Setenv(\"CONSUL_HTTP_ADDR\", srv.HTTPAddr)\n\targs := []string{\"foo\", \"bar\"}\n\tcode := c.Run(args)\n\tif code != 0 {\n\t\tt.Fatalf(\"Unexpected code: %d err: %s\", code, ui.ErrorWriter.String())\n\t}\n\tval := srv.GetKV(\"foo\")\n\tif string(val) != \"bar\" {\n\t\tt.Fatalf(\"Invalid value %s\", val)\n\t}\n}"} {"input": "package longrunning_test\n\nimport (\n\t\"cloud.google.com/go/longrunning/autogen\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/api/iterator\"\n\tlongrunningpb \"google.golang.org/genproto/googleapis/longrunning\"\n)\n\nfunc ExampleNewOperationsClient() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\nfunc ExampleOperationsClient_GetOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.GetOperationRequest{\n\t}\n\tresp, err := c.GetOperation(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleOperationsClient_ListOperations() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.ListOperationsRequest{\n\t}\n\tit := c.ListOperations(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}\n\nfunc ExampleOperationsClient_CancelOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.CancelOperationRequest{\n\t}\n\terr = c.CancelOperation(ctx, req)\n\tif err != nil {\n\t}\n}\n\n\n\nfunc ExampleOperationsClient_DeleteOperation() ", "output": "{\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.DeleteOperationRequest{\n\t}\n\terr = c.DeleteOperation(ctx, req)\n\tif err != nil {\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"os/exec\"\n)\n\n\n\n\nfunc Reboot() ", "output": "{\n\tcmd := exec.Command(\"sudo\", \"reboot\")\n\tcmd.Start()\n}"} {"input": "package server\n\nimport (\n\t\"github.com/Ray-GuanhuiLiang/GoGuidGenerator/common\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n\t\"log\"\n\t\"net\"\n)\n\ntype GrpcServer struct {\n\tgenerator common.Generator\n\tserv *grpc.Server\n\texit chan int\n}\n\nfunc NewGrpcServer(generator common.Generator) *GrpcServer {\n\te := make(chan int)\n\tserv := grpc.NewServer()\n\ts := &GrpcServer{generator, serv, e}\n\tRegisterGuidServer(serv, s)\n\treturn s\n}\n\n\n\nfunc (this *GrpcServer) Wait() {\n\t<-this.exit\n}\n\nfunc (this *GrpcServer) GetGuid(context.Context, *Req) (*Resp, error) {\n\tid, err := this.generator.Generate()\n\tvar (\n\t\tr Resp\n\t\tcode int32\n\t\tguid uint64\n\t)\n\tif err != nil {\n\t\tcode = 1\n\t\tguid = 0\n\t} else {\n\t\tcode = 0\n\t\tguid = id\n\t}\n\tr.Code = &code\n\tr.Guid = &guid\n\treturn &r, err\n}\n\nfunc (this *GrpcServer) Start() error ", "output": "{\n\tlistener, err := net.Listen(\"tcp\", \":5588\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn err\n\t}\n\tgo this.serv.Serve(listener)\n\treturn nil\n}"} {"input": "package testdata\n\nimport (\n\t\"github.com/semrush/zenrpc/v2\"\n)\n\ntype Group struct {\n\tId int `json:\"id\"`\n\tTitle string `json:\"title\"`\n\tNodes []Group `json:\"nodes\"`\n\tGroups []Group `json:\"group\"`\n\tChildOpt *Group `json:\"child\"`\n\tSub SubGroup `json:\"sub\"`\n}\n\ntype SubGroup struct {\n\tId int `json:\"id\"`\n\tTitle string `json:\"title\"`\n}\n\ntype Campaign struct {\n\tId int `json:\"id\"`\n\tGroups []Group `json:\"group\"`\n}\n\ntype CatalogueService struct{ zenrpc.Service }\n\nfunc (s CatalogueService) First(groups []Group) (bool, error) {\n\treturn true, nil\n}\n\n\n\nfunc (s CatalogueService) Third() (Campaign, error) {\n\treturn Campaign{}, nil\n}\n\nfunc (s CatalogueService) Second(campaigns []Campaign) (bool, error) ", "output": "{\n\treturn true, nil\n}"} {"input": "package requirements\n\nimport (\n\t\"github.com/cloudfoundry/cli/cf/api/applications\"\n\t\"github.com/cloudfoundry/cli/cf/models\"\n)\n\n\ntype ApplicationRequirement interface {\n\tRequirement\n\tGetApplication() models.Application\n}\n\ntype applicationApiRequirement struct {\n\tname string\n\tappRepo applications.ApplicationRepository\n\tapplication models.Application\n}\n\n\n\nfunc (req *applicationApiRequirement) Execute() error {\n\tvar apiErr error\n\treq.application, apiErr = req.appRepo.Read(req.name)\n\n\tif apiErr != nil {\n\t\treturn apiErr\n\t}\n\n\treturn nil\n}\n\nfunc (req *applicationApiRequirement) GetApplication() models.Application {\n\treturn req.application\n}\n\nfunc NewApplicationRequirement(name string, aR applications.ApplicationRepository) *applicationApiRequirement ", "output": "{\n\treq := &applicationApiRequirement{}\n\treq.name = name\n\treq.appRepo = aR\n\treturn req\n}"} {"input": "package text\n\nimport \"fmt\"\n\nconst (\n\tredCode = \"\\x1b[31m\"\n\tgreenCode = \"\\x1b[32m\"\n\tyellowCode = \"\\x1b[33m\"\n\tblueCode = \"\\x1b[34m\"\n\tmagentaCode = \"\\x1b[35m\"\n\tCyanCode = \"\\x1b[36m\"\n\tboldCode = \"\\x1b[1m\"\n\n\tResetCode = \"\\x1b[0m\"\n)\n\n\nvar UseColor = true\n\nfunc stylize(startCode, in string) string {\n\tif UseColor {\n\t\treturn startCode + in + ResetCode\n\t}\n\n\treturn in\n}\n\nfunc Red(in string) string {\n\treturn stylize(redCode, in)\n}\n\nfunc Green(in string) string {\n\treturn stylize(greenCode, in)\n}\n\nfunc yellow(in string) string {\n\treturn stylize(yellowCode, in)\n}\n\nfunc Cyan(in string) string {\n\treturn stylize(CyanCode, in)\n}\n\nfunc Magenta(in string) string {\n\treturn stylize(magentaCode, in)\n}\n\nfunc Blue(in string) string {\n\treturn stylize(blueCode, in)\n}\n\n\n\n\n\nfunc ColorHash(name string) (output string) {\n\tif !UseColor {\n\t\treturn name\n\t}\n\n\tvar hash uint = 5381\n\n\tfor i := 0; i < len(name); i++ {\n\t\thash = uint(name[i]) + ((hash << 5) + (hash))\n\t}\n\n\treturn fmt.Sprintf(\"\\x1b[%dm%s\\x1b[0m\", hash%6+31, name)\n}\n\nfunc Bold(in string) string ", "output": "{\n\treturn stylize(boldCode, in)\n}"} {"input": "package cachestore\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\n\ntype KVStore struct {\n\tstoreMap map[string]interface{}\n\tmutex sync.RWMutex\n}\n\n\n\n\n\nfunc (store *KVStore) Get(key string) interface{} {\n\tstore.mutex.RLock()\n\tval := store.storeMap[key]\n\tstore.mutex.RUnlock()\n\treturn val\n}\n\n\nfunc (store *KVStore) Delete(key string) {\n\tstore.mutex.Lock()\n\tdelete(store.storeMap, key)\n\tstore.mutex.Unlock()\n}\n\n\nfunc (store *KVStore) MarshalJSON() ([]byte, error) {\n\tstore.mutex.RLock()\n\tbytes, err := json.Marshal(store.storeMap)\n\tstore.mutex.RUnlock()\n\treturn bytes, err\n}\n\n\nfunc NewKVStore() *KVStore {\n\treturn &KVStore{map[string]interface{}{}, sync.RWMutex{}}\n}\n\nfunc (store *KVStore) Set(key string, value interface{}) ", "output": "{\n\tstore.mutex.Lock()\n\tstore.storeMap[key] = value\n\tstore.mutex.Unlock()\n}"} {"input": "package databasemanagement\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ResetDatabaseParametersRequest struct {\n\n\tManagedDatabaseId *string `mandatory:\"true\" contributesTo:\"path\" name:\"managedDatabaseId\"`\n\n\tResetDatabaseParametersDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request ResetDatabaseParametersRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ResetDatabaseParametersRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ResetDatabaseParametersRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ResetDatabaseParametersResponse struct {\n\n\tRawResponse *http.Response\n\n\tUpdateDatabaseParametersResult `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ResetDatabaseParametersResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ResetDatabaseParametersResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ResetDatabaseParametersRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package iso20022\n\n\ntype TerminationDate4Choice struct {\n\n\tDate *DateAndDateTimeChoice `xml:\"Dt\"`\n\n\tCode *DateCode18Choice `xml:\"Cd\"`\n}\n\n\n\nfunc (t *TerminationDate4Choice) AddCode() *DateCode18Choice {\n\tt.Code = new(DateCode18Choice)\n\treturn t.Code\n}\n\nfunc (t *TerminationDate4Choice) AddDate() *DateAndDateTimeChoice ", "output": "{\n\tt.Date = new(DateAndDateTimeChoice)\n\treturn t.Date\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\n\nvar nodeCmd = &cobra.Command{\n\tUse: \"node\",\n\tShort: \"Manage cluster nodes\",\n}\n\n\n\nfunc init() ", "output": "{\n\trootCmd.AddCommand(nodeCmd)\n}"} {"input": "package widgets\n\nimport (\n\t\"strings\"\n\n\t\"github.com/ambientsound/pms/songlist\"\n\t\"github.com/ambientsound/pms/style\"\n\t\"github.com/gdamore/tcell\"\n\t\"github.com/gdamore/tcell/views\"\n)\n\ntype ColumnheadersWidget struct {\n\tcolumns songlist.Columns\n\tview views.View\n\n\tstyle.Styled\n\tviews.WidgetWatchers\n}\n\nfunc NewColumnheadersWidget() (c *ColumnheadersWidget) {\n\tc = &ColumnheadersWidget{}\n\tc.columns = make(songlist.Columns, 0)\n\treturn\n}\n\nfunc (c *ColumnheadersWidget) SetColumns(cols songlist.Columns) {\n\tc.columns = cols\n}\n\nfunc (c *ColumnheadersWidget) Draw() {\n\tx := 0\n\ty := 0\n\tfor i := range c.columns {\n\t\tcol := c.columns[i]\n\t\ttitle := []rune(strings.Title(col.Tag()))\n\t\tp := 0\n\t\tfor _, r := range title {\n\t\t\tc.view.SetContent(x+p, y, r, nil, c.Style(\"header\"))\n\t\t\tp++\n\t\t}\n\t\tx += col.Width()\n\t}\n}\n\nfunc (c *ColumnheadersWidget) SetView(v views.View) {\n\tc.view = v\n}\n\nfunc (c *ColumnheadersWidget) Size() (int, int) {\n\tx, y := c.view.Size()\n\ty = 1\n\treturn x, y\n}\n\nfunc (w *ColumnheadersWidget) Resize() {\n}\n\n\n\nfunc (w *ColumnheadersWidget) HandleEvent(ev tcell.Event) bool ", "output": "{\n\treturn false\n}"} {"input": "package string\n\nimport (\n\tdss \"github.com/emirpasic/gods/stacks/arraystack\"\n)\n\n\nfunc Reverse(s string) string {\n\tr := []rune(s) \n\tfor i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n\t\tr[i], r[j] = r[j], r[i]\n\t}\n\treturn string(r)\n}\n\n\n\n\n\n\n\nfunc ReverseNest(s string) string {\n\tr := []rune(s)\n\tif len(r) == 1 || len(r) == 0 {\n\t\treturn s\n\t}\n\tsub := ReverseNest(string(r[1:]))\n\treturn sub + string(r[0:1])\n}\n\n\nfunc ReverseNest1(s string) string {\n\tr := []rune(s)\n\tswitchHeadTail(r)\n\treturn string(r)\n}\n\n\n\n\nfunc ReverseInStack(s string) string {\n\tr := []rune(s)\n\tstack := dss.New()\n\tfor i := 0; i < len(r); i++ {\n\t\tstack.Push(r[i])\n\t}\n\trs := make([]rune, len(r))\n\tfor i := 0; i < len(r); i++ {\n\t\tv, _ := stack.Pop()\n\t\tif v != nil {\n\t\t\trs[i] = v.(rune)\n\t\t}\n\t}\n\treturn string(rs)\n}\n\nfunc switchHeadTail(r []rune) ", "output": "{\n\tif len(r) <= 1 {\n\t\treturn\n\t}\n\tbottom, top := 0, len(r)-1\n\tr[bottom], r[top] = r[top], r[bottom]\n\tswitchHeadTail(r[bottom+1 : top])\n}"} {"input": "package glfw\n\n\nimport \"C\"\n\n\n\n\n\n\n\nfunc GetTime() float64 {\n\treturn float64(C.glfwGetTime())\n}\n\n\n\n\n\n\n\n\n\nfunc SetTime(time float64) ", "output": "{\n\tC.glfwSetTime(C.double(time))\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\n\n\n\ntype MsgPong struct {\n\tNonce uint64\n}\n\n\n\nfunc (msg *MsgPong) BtcDecode(r io.Reader, pver uint32) error {\n\tif pver <= BIP0031Version {\n\t\tstr := fmt.Sprintf(\"pong message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgPong.BtcDecode\", str)\n\t}\n\n\treturn readElement(r, &msg.Nonce)\n}\n\n\n\n\n\n\n\nfunc (msg *MsgPong) Command() string {\n\treturn CmdPong\n}\n\n\n\nfunc (msg *MsgPong) MaxPayloadLength(pver uint32) uint32 {\n\tplen := uint32(0)\n\tif pver > BIP0031Version {\n\t\tplen += 8\n\t}\n\n\treturn plen\n}\n\n\n\nfunc NewMsgPong(nonce uint64) *MsgPong {\n\treturn &MsgPong{\n\t\tNonce: nonce,\n\t}\n}\n\nfunc (msg *MsgPong) BtcEncode(w io.Writer, pver uint32) error ", "output": "{\n\tif pver <= BIP0031Version {\n\t\tstr := fmt.Sprintf(\"pong message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgPong.BtcEncode\", str)\n\t}\n\n\treturn writeElement(w, msg.Nonce)\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n)\n\nfunc main() {\n\ttests := [][]int32{{1, 2, 3, 4, 5}}\n\n\tfor _, test := range tests {\n\t\tlog.Printf(\"LeftRotate(%v) == %v\\n\", test, LeftRotate(test, 2))\n\t}\n}\n\n\nfunc LeftRotate(n []int32, x int32) []int32 {\n if len(n) <= 1 {\n return n\n }\n\n var j int32\n for j = 0; j < x; j++ {\n tmp := n[0]\n\n for i := 1; i < len(n); i++ {\n n[i-1] = n[i] \n }\n\n n[len(n)-1] = tmp\n }\n\n return n\n}\n\n\n\n\nfunc RightRotate(n []int32, x int32) []int32 ", "output": "{\n\tif len(n) <= 1 {\n\t\treturn n\n\t}\n\n var j int32\n\tfor j = 0; j < x; j++ {\n\t\ttmp := n[len(n)-1]\n\n\t\tfor i := len(n) - 1; i > 0; i-- {\n\t\t\tn[i] = n[i-1]\n\t\t}\n\n\t\tn[0] = tmp\n\t}\n\n\treturn n\n}"} {"input": "package vfs\n\nimport (\n\t\"path\"\n\n\tgofig \"github.com/akutz/gofig/types\"\n\n\t\"github.com/rexray/rexray/libstorage/api/context\"\n\t\"github.com/rexray/rexray/libstorage/api/registry\"\n\t\"github.com/rexray/rexray/libstorage/api/types\"\n)\n\nconst (\n\tName = \"vfs\"\n)\n\nfunc init() {\n\tregistry.RegisterConfigReg(\n\t\t\"VFS\",\n\t\tfunc(ctx types.Context, r gofig.ConfigRegistration) {\n\t\t\tvfsRoot := path.Join(context.MustPathConfig(ctx).Lib, \"vfs\")\n\t\t\tr.Key(\n\t\t\t\tgofig.String,\n\t\t\t\t\"\",\n\t\t\t\tvfsRoot,\n\t\t\t\t\"\",\n\t\t\t\t\"vfs.root\")\n\t\t})\n}\n\n\n\n\n\nfunc DeviceFilePath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"dev\")\n}\n\n\nfunc VolumesDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"vol\")\n}\n\n\nfunc SnapshotsDirPath(config gofig.Config) string {\n\treturn path.Join(RootDir(config), \"snap\")\n}\n\nfunc RootDir(config gofig.Config) string ", "output": "{\n\treturn config.GetString(\"vfs.root\")\n}"} {"input": "package v6\n\nimport (\n\t\"code.cloudfoundry.org/cli/command\"\n\t\"code.cloudfoundry.org/cli/command/flag\"\n\t\"code.cloudfoundry.org/cli/command/translatableerror\"\n)\n\ntype UnsetOrgRoleCommand struct {\n\tRequiredArgs flag.SetOrgRoleArgs `positional-args:\"yes\"`\n\tusage interface{} `usage:\"CF_NAME unset-org-role USERNAME ORG ROLE\\n\\nROLES:\\n 'OrgManager' - Invite and manage users, select and change plans, and set spending limits\\n 'BillingManager' - Create and manage the billing account and payment info\\n 'OrgAuditor' - Read-only access to org info and reports\"`\n\trelatedCommands interface{} `related_commands:\"org-users, delete-user\"`\n}\n\n\n\nfunc (UnsetOrgRoleCommand) Execute(args []string) error {\n\treturn translatableerror.UnrefactoredCommandError{}\n}\n\nfunc (UnsetOrgRoleCommand) Setup(config command.Config, ui command.UI) error ", "output": "{\n\treturn nil\n}"} {"input": "package naming\n\nimport (\n\t\"github.com/snapcore/snapd/snapdenv\"\n)\n\nvar (\n\tprodWellKnownSnapIDs = map[string]string{\n\t\t\"core\": \"99T7MUlRhtI3U0QFgl5mXXESAiSwt776\",\n\t\t\"snapd\": \"PMrrV4ml8uWuEUDBT8dSGnKUYbevVhc4\",\n\t\t\"core18\": \"CSO04Jhav2yK0uz97cr0ipQRyqg0qQL6\",\n\t\t\"core20\": \"DLqre5XGLbDqg9jPtiAhRRjDuPVa5X1q\",\n\t}\n\n\tstagingWellKnownSnapIDs = map[string]string{\n\t\t\"core\": \"xMNMpEm0COPZy7jq9YRwWVLCD9q5peow\",\n\t\t\"snapd\": \"Z44rtQD1v4r1LXGPCDZAJO3AOw1EDGqy\",\n\t\t\"core18\": \"NhSvwckvNdvgdiVGlsO1vYmi3FPdTZ9U\",\n\t\t\"core20\": \"\",\n\t}\n)\n\nvar wellKnownSnapIDs = prodWellKnownSnapIDs\n\n\n\n\n\nfunc WellKnownSnapID(snapName string) string {\n\treturn wellKnownSnapIDs[snapName]\n}\n\nfunc UseStagingIDs(staging bool) (restore func()) {\n\told := wellKnownSnapIDs\n\tif staging {\n\t\twellKnownSnapIDs = stagingWellKnownSnapIDs\n\t} else {\n\t\twellKnownSnapIDs = prodWellKnownSnapIDs\n\t}\n\treturn func() {\n\t\twellKnownSnapIDs = old\n\t}\n}\n\nfunc init() ", "output": "{\n\tif snapdenv.UseStagingStore() {\n\t\twellKnownSnapIDs = stagingWellKnownSnapIDs\n\t}\n}"} {"input": "package data\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/credentials\"\n\t\"github.com/aws/aws-sdk-go/aws/session\"\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/guregu/dynamo\"\n\t\"github.com/spf13/viper\"\n)\n\n\ntype DynamoDB struct {\n\tdb *dynamo.DB\n}\n\n\nfunc (d *DynamoDB) Connect() error {\n\tvar awsConfig *aws.Config\n\tif viper.GetString(\"DynamoEndpoint\") == \"\" {\n\t\tawsConfig = &aws.Config{}\n\t} else {\n\t\tmyTrue := true\n\t\tawsConfig = &aws.Config{\n\t\t\tEndpoint: aws.String(viper.GetString(\"DynamoEndpoint\")),\n\t\t\tCredentials: credentials.NewStaticCredentials(\"foo\", \"foo\", \"foo\"),\n\t\t\tDisableSSL: &myTrue,\n\t\t}\n\t}\n\tawsConfig.WithRegion(viper.GetString(\"DynamoRegion\"))\n\tif gin.Mode() == gin.DebugMode {\n\t\tawsConfig.WithLogLevel(aws.LogDebugWithHTTPBody)\n\t}\n\n\td.db = dynamo.New(session.Must(session.NewSession()), awsConfig)\n\n\treturn nil\n}\n\n\n\nfunc (d *DynamoDB) Save(a *Avatar) error {\n\n\tif err := d.getTable().Put(a).Run(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *DynamoDB) Migrate() error {\n\treturn nil\n}\n\nfunc (d *DynamoDB) getTable() dynamo.Table {\n\treturn d.db.Table(viper.GetString(\"TableName\"))\n}\n\nfunc (d *DynamoDB) FindByHash(hash string) (*Avatar, error) ", "output": "{\n\tvar avatar Avatar\n\n\tif err := d.getTable().Get(\"Hash\", hash).One(&avatar); err != nil {\n\t\treturn nil, fmt.Errorf(\"Cannot find avatar with hash %s\", hash)\n\t}\n\n\treturn &avatar, nil\n}"} {"input": "package bender\n\nimport (\n\t\"log\"\n\n\t\"github.com/pinterest/bender/hist\"\n)\n\n\ntype Recorder func(interface{})\n\n\n\n\nfunc logMessage(l *log.Logger, msg interface{}) {\n\tl.Printf(\"%+v\", msg)\n}\n\n\nfunc NewLoggingRecorder(l *log.Logger) Recorder {\n\treturn func(msg interface{}) {\n\t\tlogMessage(l, msg)\n\t}\n}\n\n\nfunc NewHistogramRecorder(h *hist.Histogram) Recorder {\n\treturn func(msg interface{}) {\n\t\tswitch msg := msg.(type) {\n\t\tcase *StartEvent:\n\t\t\th.Start(int(msg.Start))\n\t\tcase *EndEvent:\n\t\t\th.End(int(msg.End))\n\t\tcase *EndRequestEvent:\n\t\t\telapsed := int(msg.End - msg.Start)\n\t\t\tif msg.Err == nil {\n\t\t\t\th.Add(elapsed)\n\t\t\t} else {\n\t\t\t\th.AddError(elapsed)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc Record(c chan interface{}, recorders ...Recorder) ", "output": "{\n\tfor msg := range c {\n\t\tfor _, recorder := range recorders {\n\t\t\trecorder(msg)\n\t\t}\n\t}\n}"} {"input": "package internal\n\nimport G \"github.com/ionous/sashimi/game\"\n\n\ntype PendingChain struct {\n\tsrc *GameEventAdapter\n}\n\nfunc NewPendingChain(src *GameEventAdapter, _ Future) PendingChain {\n\treturn PendingChain{src}\n}\n\n\n\nfunc (c PendingChain) Then(cb G.Callback) ", "output": "{\n\tif c.src != nil {\n\t\tchain := ChainedCallback{c.src.data, cb}\n\t\tchain.Run(c.src.Game)\n\t}\n}"} {"input": "package payments\n\nimport (\n \"net/http\"\n \"github.com/upwork/golang-upwork/api\"\n)\n\nconst (\n EntryPoint = \"api\"\n)\n\ntype a struct {\n client api.ApiClient\n}\n\n\n\n\n\nfunc (r a) SubmitBonus(teamReference string, params map[string]string) (*http.Response, []byte) {\n return r.client.Post(\"/hr/v2/teams/\" + teamReference + \"/adjustments\", params)\n}\n\nfunc New(c api.ApiClient) (a) ", "output": "{\n var r a\n c.SetEntryPoint(EntryPoint)\n r.client = c\n\n return r\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"k8s.io/helm/pkg/helm/helmpath\"\n\t\"k8s.io/helm/pkg/plugin\"\n\t\"k8s.io/helm/pkg/plugin/installer\"\n\n\t\"github.com/spf13/cobra\"\n)\n\ntype pluginInstallCmd struct {\n\tsource string\n\tversion string\n\thome helmpath.Home\n\tout io.Writer\n}\n\nfunc newPluginInstallCmd(out io.Writer) *cobra.Command {\n\tpcmd := &pluginInstallCmd{out: out}\n\tcmd := &cobra.Command{\n\t\tUse: \"install [options] ...\",\n\t\tShort: \"install one or more Helm plugins\",\n\t\tPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn pcmd.complete(args)\n\t\t},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn pcmd.run()\n\t\t},\n\t}\n\tcmd.Flags().StringVar(&pcmd.version, \"version\", \"\", \"specify a version constraint. If this is not specified, the latest version is installed\")\n\treturn cmd\n}\n\nfunc (pcmd *pluginInstallCmd) complete(args []string) error {\n\tif err := checkArgsLength(len(args), \"plugin\"); err != nil {\n\t\treturn err\n\t}\n\tpcmd.source = args[0]\n\tpcmd.home = settings.Home\n\treturn nil\n}\n\n\n\nfunc (pcmd *pluginInstallCmd) run() error ", "output": "{\n\tinstaller.Debug = settings.Debug\n\n\ti, err := installer.NewForSource(pcmd.source, pcmd.version, pcmd.home)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := installer.Install(i); err != nil {\n\t\treturn err\n\t}\n\n\tdebug(\"loading plugin from %s\", i.Path())\n\tp, err := plugin.LoadDir(i.Path())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := runHook(p, plugin.Install); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintf(pcmd.out, \"Installed plugin: %s\\n\", p.Metadata.Name)\n\treturn nil\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype ListFastConnectProviderVirtualCircuitBandwidthShapesRequest struct {\n\n\tProviderServiceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"providerServiceId\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListFastConnectProviderVirtualCircuitBandwidthShapesResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []VirtualCircuitBandwidthShape `presentIn:\"body\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ListFastConnectProviderVirtualCircuitBandwidthShapesResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListFastConnectProviderVirtualCircuitBandwidthShapesResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListFastConnectProviderVirtualCircuitBandwidthShapesRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package services\n\nimport (\n\t\"github.com/astaxie/beego/orm\"\n\t\"github.com/scmo/apayment-backend/models\"\n)\n\nfunc CreateControlPoint(cp *models.ControlPoint) error {\n\to := orm.NewOrm()\n\t_, err := o.Insert(cp)\n\treturn err\n}\n\n\n\nfunc CountControlPoints() (int64, error) {\n\to := orm.NewOrm()\n\tcnt, err := o.QueryTable(new(models.ControlPoint)).Count() \n\treturn cnt, err\n}\n\nfunc GetAllControlPoints() []*models.ControlPoint ", "output": "{\n\to := orm.NewOrm()\n\tvar controlPoints []*models.ControlPoint\n\to.QueryTable(new(models.ControlPoint)).All(&controlPoints)\n\treturn controlPoints\n}"} {"input": "package message\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"mime\"\n\t\"strings\"\n)\n\ntype UnknownCharsetError struct {\n\te error\n}\n\nfunc (u UnknownCharsetError) Unwrap() error { return u.e }\n\nfunc (u UnknownCharsetError) Error() string {\n\treturn \"unknown charset: \" + u.e.Error()\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar CharsetReader func(charset string, input io.Reader) (io.Reader, error)\n\n\nfunc charsetReader(charset string, input io.Reader) (io.Reader, error) {\n\tcharset = strings.ToLower(charset)\n\tif charset == \"utf-8\" || charset == \"us-ascii\" {\n\t\treturn input, nil\n\t}\n\tif CharsetReader != nil {\n\t\tr, err := CharsetReader(charset, input)\n\t\tif err != nil {\n\t\t\treturn r, UnknownCharsetError{err}\n\t\t}\n\t\treturn r, nil\n\t}\n\treturn input, UnknownCharsetError{fmt.Errorf(\"message: unhandled charset %q\", charset)}\n}\n\n\n\nfunc decodeHeader(s string) (string, error) {\n\twordDecoder := mime.WordDecoder{CharsetReader: charsetReader}\n\tdec, err := wordDecoder.DecodeHeader(s)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\treturn dec, nil\n}\n\nfunc encodeHeader(s string) string {\n\treturn mime.QEncoding.Encode(\"utf-8\", s)\n}\n\nfunc IsUnknownCharset(err error) bool ", "output": "{\n\treturn errors.As(err, new(UnknownCharsetError))\n}"} {"input": "package citrixadc\n\nimport (\n\t\"github.com/citrix/adc-nitro-go/resource/config/router\"\n\n\t\"github.com/hashicorp/terraform/helper/resource\"\n\t\"github.com/hashicorp/terraform/helper/schema\"\n\n\t\"log\"\n\t\"strings\"\n)\n\nfunc resourceCitrixAdcRouterdynamicrouting() *schema.Resource {\n\treturn &schema.Resource{\n\t\tSchemaVersion: 1,\n\t\tCreate: applyRouterdynamicroutingFunc,\n\t\tRead: schema.Noop,\n\t\tDelete: schema.Noop,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"commandlines\": &schema.Schema{\n\t\t\t\tType: schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem: &schema.Schema{Type: schema.TypeString},\n\t\t\t},\n\t\t\t\"nodeid\": &schema.Schema{\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\n\n\nfunc applyRouterdynamicroutingFunc(d *schema.ResourceData, meta interface{}) error ", "output": "{\n\tlog.Printf(\"[DEBUG] citrixadc-provider: In createRouterdynamicroutingFunc\")\n\tclient := meta.(*NetScalerNitroClient).client\n\trouterdynamicroutingName := resource.PrefixedUniqueId(\"tf-routerdynamicrouting-\")\n\n\tlines := d.Get(\"commandlines\").([]interface{})\n\tstringArray := make([]string, 0, len(lines))\n\tfor _, line := range lines {\n\t\tstringArray = append(stringArray, line.(string))\n\t}\n\n\tcmdString := strings.Join(stringArray, \"\\n\")\n\n\trouterdynamicrouting := router.Routerdynamicrouting{\n\t\tCommandstring: cmdString,\n\t\tNodeid: d.Get(\"nodeid\").(int),\n\t}\n\n\terr := client.ActOnResource(\"routerdynamicrouting\", &routerdynamicrouting, \"apply\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.SetId(routerdynamicroutingName)\n\n\treturn nil\n}"} {"input": "package dbutil\n\nimport (\n\t\"log\"\n\t\"testing\"\n\t\"time\"\n\n\tConfig \"../config\"\n\t_ \"github.com/lib/pq\"\n)\n\nfunc dbOperation(dbHost, dbUser, dbPasswd, dbName string, t *testing.T) {\n\tconn := New(dbHost, dbUser, dbPasswd, dbName)\n\tdefer conn.Close()\n\n\tusers := conn.Rows(\"users\", \"id, openid, nickname, created\")\n\tdefer users.Close()\n\tfor users.Next() {\n\t\tvar id, openid, nickname string\n\t\tvar created time.Time\n\t\tif err := users.Scan(&id, &openid, &nickname, &created); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tlog.Println(id, openid, nickname, created.Format(time.RFC3339))\n\t}\n}\n\n\n\nfunc TestDBWithToml(t *testing.T) {\n\tlog.Println(\"[test toml]\")\n\tcfg, err := Config.GetTomlConfig(\"../config/database.toml\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tdev := cfg.Env[\"development\"]\n\tdbOperation(dev.Host, dev.Username, dev.Password, dev.Database, t)\n}\n\nfunc TestDBWithYaml(t *testing.T) ", "output": "{\n\tlog.Println(\"[test yaml]\")\n\t_, err := Config.GetConfig(\"../config/database.yml\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n)\n\nconst (\n\tdeviceAliasDir = \"/run/ignition/dev_aliases\"\n\tretrySymlinkDelay = 10 * time.Millisecond\n\tretrySymlinkTimeout = 30 * time.Second\n\tretrySymlinkCount = int(retrySymlinkTimeout / retrySymlinkDelay)\n)\n\n\n\nfunc DeviceAlias(path string) string {\n\treturn filepath.Join(deviceAliasDir, filepath.Clean(path))\n}\n\n\nfunc evalSymlinks(path string) (res string, err error) {\n\tfor i := 0; i < retrySymlinkCount; i++ {\n\t\tres, err = filepath.EvalSymlinks(path)\n\t\tif err == nil {\n\t\t\treturn res, nil\n\t\t} else if os.IsNotExist(err) {\n\t\t\ttime.Sleep(retrySymlinkDelay)\n\t\t} else {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"Failed to evaluate symlink after %v: %v\", retrySymlinkTimeout, err)\n}\n\n\n\n\n\nfunc CreateDeviceAlias(path string) (string, error) ", "output": "{\n\ttarget, err := evalSymlinks(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\talias := DeviceAlias(path)\n\n\tif err := os.Remove(alias); err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif err = os.MkdirAll(filepath.Dir(alias), 0750); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tif err = os.Symlink(target, alias); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn target, nil\n}"} {"input": "package informers\n\nimport (\n\t\"fmt\"\n\tv1alpha1 \"github.com/jetstack-experimental/cert-manager/pkg/apis/certmanager/v1alpha1\"\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tcache \"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}\n\n\n\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {\n\tswitch resource {\n\tcase v1alpha1.SchemeGroupVersion.WithResource(\"certificates\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Certmanager().V1alpha1().Certificates().Informer()}, nil\n\tcase v1alpha1.SchemeGroupVersion.WithResource(\"issuers\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Certmanager().V1alpha1().Issuers().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}\n\nfunc (f *genericInformer) Lister() cache.GenericLister ", "output": "{\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}"} {"input": "package retry\n\nimport \"testing\"\n\n\n\nfunc TestFib(t *testing.T) ", "output": "{\n\tfor i, want := range []int64{0, 1, 1, 2, 3, 5, 8, 13, 21} {\n\t\tif got := fib(uint(i)); want != got {\n\t\t\tt.Fatalf(\"fib: for index %v, want: %v, got: %v\", i, want, got)\n\t\t}\n\t}\n}"} {"input": "package eventstreamapi\n\nimport (\n\t\"github.com/aws/aws-sdk-go/private/protocol\"\n\t\"github.com/aws/aws-sdk-go/private/protocol/eventstream\"\n)\n\n\n\ntype Marshaler interface {\n\tMarshalEvent(protocol.PayloadMarshaler) (eventstream.Message, error)\n}\n\n\n\ntype Encoder interface {\n\tEncode(eventstream.Message) error\n}\n\n\n\ntype EventWriter struct {\n\tencoder Encoder\n\tpayloadMarshaler protocol.PayloadMarshaler\n\teventTypeFor func(Marshaler) (string, error)\n}\n\n\n\n\n\n\n\nfunc (w *EventWriter) WriteEvent(event Marshaler) error {\n\tmsg, err := w.marshal(event)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn w.encoder.Encode(msg)\n}\n\nfunc (w *EventWriter) marshal(event Marshaler) (eventstream.Message, error) {\n\teventType, err := w.eventTypeFor(event)\n\tif err != nil {\n\t\treturn eventstream.Message{}, err\n\t}\n\n\tmsg, err := event.MarshalEvent(w.payloadMarshaler)\n\tif err != nil {\n\t\treturn eventstream.Message{}, err\n\t}\n\n\tmsg.Headers.Set(EventTypeHeader, eventstream.StringValue(eventType))\n\treturn msg, nil\n}\n\nfunc NewEventWriter(encoder Encoder, pm protocol.PayloadMarshaler, eventTypeFor func(Marshaler) (string, error),\n) *EventWriter ", "output": "{\n\treturn &EventWriter{\n\t\tencoder: encoder,\n\t\tpayloadMarshaler: pm,\n\t\teventTypeFor: eventTypeFor,\n\t}\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSBatchJobDefinition_NodeRangeProperty struct {\n\n\tContainer *AWSBatchJobDefinition_ContainerProperties `json:\"Container,omitempty\"`\n\n\tTargetNodes string `json:\"TargetNodes,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) AWSCloudFormationType() string {\n\treturn \"AWS::Batch::JobDefinition.NodeRangeProperty\"\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\n\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetDependsOn(dependencies []string) ", "output": "{\n\tr._dependsOn = dependencies\n}"} {"input": "package gtka\n\nimport (\n\t\"github.com/gotk3/gotk3/gtk\"\n\t\"github.com/coyim/gotk3adapter/gliba\"\n\t\"github.com/coyim/gotk3adapter/gtki\"\n)\n\ntype application struct {\n\t*gliba.Application\n\tinternal *gtk.Application\n}\n\n\n\nfunc wrapApplication(v *gtk.Application, e error) (*application, error) {\n\treturn wrapApplicationSimple(v), e\n}\n\nfunc unwrapApplication(v gtki.Application) *gtk.Application {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.(*application).internal\n}\n\nfunc (v *application) GetActiveWindow() gtki.Window {\n\tret := wrapWindowSimple(v.internal.GetActiveWindow())\n\tif ret == nil {\n\t\treturn nil\n\t}\n\treturn ret\n}\n\nfunc wrapApplicationSimple(v *gtk.Application) *application ", "output": "{\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn &application{gliba.WrapApplicationSimple(&v.Application), v}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/kr/pretty\"\n\t\"testing\"\n)\n\nfunc TestReadFiles(t *testing.T) {\n\n\tpath := \"./examples/basic\"\n\tfiles, err := ReadFiles(path)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif len(files) <= 0 {\n\t\tt.Error(\"files len must be > 0\")\n\t}\n\n\tt.Logf(\"%# v\", pretty.Formatter(files))\n}\n\n\n\nfunc TestReadYAMLConf(t *testing.T) ", "output": "{\n\tpath := \"./examples/basic\"\n\n\tfiles, err := ReadFiles(path)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif len(files) <= 0 {\n\t\tt.Error(\"files len must be > 0\")\n\t}\n\n\tfor _, f := range files {\n\t\tif f.Base == \"_.yaml\" {\n\t\t\tif len(f.Meta) <= 0 {\n\t\t\t\tt.Errorf(\"%s could not read\", f.Path)\n\t\t\t}\n\t\t}\n\t}\n\n}"} {"input": "package gwf\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n)\n\n\ntype Context struct {\n\tw http.ResponseWriter\n\tr *http.Request\n\n\tpath []string\n}\n\ntype Module interface {\n\tAction(*Context)\n}\n\ntype Dispatcher struct {\n\tmodules map[string]Module\n}\n\nfunc (c *Context) Request() *http.Request {\n\treturn c.r\n}\n\n\n\nfunc (c *Context) Init(w http.ResponseWriter, r *http.Request) {\n\tc.w, c.r = w, r\n\n\tpath := strings.Split(r.URL.Path, \"/\")\n\tc.path = path[1:]\n}\n\nfunc (c *Context) Path(index int) (string, bool) {\n\tif index < 0 || index >= len(c.path) {\n\t\treturn \"\", false\n\t} else {\n\t\treturn c.path[index], true\n\t}\n}\n\nfunc (c *Context) Depth() int {\n\treturn len(c.path)\n}\n\n\nfunc (d *Dispatcher) AddModule(name string, m Module) {\n\tif nil == d.modules {\n\t\td.modules = make(map[string]Module)\n\t}\n\td.modules[name] = m\n}\n\nfunc (d *Dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\n\tvar c Context\n\tc.Init(w, r)\n\n\tif name, ok := c.Path(0); ok {\n\t\tif module, ok := d.modules[name]; ok && module != nil {\n\t\t\t(module).Action(&c)\n\t\t\treturn\n\t\t}\n\t}\n\tw.WriteHeader(http.StatusNotFound)\n}\n\nfunc (c *Context) Writer() http.ResponseWriter ", "output": "{\n\treturn c.w\n}"} {"input": "package main\n\nimport \"fmt\"\n\ntype Person struct {\n\tName string\n\tAge int\n}\n\n\n\nfunc main() {\n\ta := Person{\"Arthur Dent\", 42}\n\tz := Person{\"Zaphod Beeblebrox\", 9001}\n\tfmt.Println(a, z)\n}\n\nfunc (p Person) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%v (%v years)\", p.Name, p.Age)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com/playlist-media/clu/config\"\n)\n\n\n\nfunc getConfig() *config.Config ", "output": "{\n\tif cfg != nil {\n\t\treturn cfg\n\t}\n\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\tprintFatal(fmt.Sprintf(\"Error: could not determine working directory (%s)\", err.Error()))\n\t}\n\n\tconfigLocation := path.Join(pwd, \"config\", \"clu.yaml\")\n\tcfg, err = config.NewConfigFromFile(configLocation)\n\tif err != nil {\n\t\tprintFatal(fmt.Sprintf(\"Error: could not parse the config file (./config/clu.yaml) (%s)\\n\", err.Error()))\n\t}\n\n\treturn cfg\n}"} {"input": "package chunkstore\n\nimport (\n\t\"errors\"\n\n\t. \"github.com/huin/chunkymonkey/types\"\n)\n\n\n\n\n\ntype MultiStore struct {\n\treadStores []IChunkStore\n\twriteStore IChunkStore\n}\n\nfunc NewMultiStore(readStores []IChunkStore, writeStore IChunkStore) *MultiStore {\n\ts := &MultiStore{\n\t\treadStores: readStores,\n\t\twriteStore: writeStore,\n\t}\n\n\treturn s\n}\n\nfunc (s *MultiStore) ReadChunk(chunkLoc ChunkXz) (reader IChunkReader, err error) {\n\tfor _, store := range s.readStores {\n\t\tresult := <-store.ReadChunk(chunkLoc)\n\n\t\tif result.Err == nil {\n\t\t\treturn result.Reader, result.Err\n\t\t} else {\n\t\t\tif _, ok := result.Err.(NoSuchChunkError); ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, result.Err\n\t\t}\n\t}\n\n\treturn nil, NoSuchChunkError(false)\n}\n\nfunc (s *MultiStore) SupportsWrite() bool {\n\treturn s.writeStore != nil && s.writeStore.SupportsWrite()\n}\n\nfunc (s *MultiStore) Writer() IChunkWriter {\n\tif s.writeStore != nil {\n\t\treturn s.writeStore.Writer()\n\t}\n\treturn nil\n}\n\n\n\nfunc (s *MultiStore) WriteChunk(writer IChunkWriter) error ", "output": "{\n\tif s.writeStore == nil {\n\t\treturn errors.New(\"writes not supported\")\n\t}\n\ts.writeStore.WriteChunk(writer)\n\treturn nil\n}"} {"input": "package app\n\nimport (\n\t\"net/http\"\n)\n\n\n\n\n\nfunc UserDeconnexionHandler(w http.ResponseWriter, r *http.Request) {\n\n\tpu := new(PageUser)\n\n\tvar p Page\n\tp = pu\n\trenderHtml(w, p, r)\n}\n\nfunc UserConnexionHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\n\tvar u User\n\tu.Email = r.PostFormValue(\"email\")\n\tu.Password = r.PostFormValue(\"password\")\n\n\tpu := new(PageUser)\n\n\tif u.Email == \"\" && u.Password == \"\" {\n\t\tpu.View()\n\t} else {\n\t\tpu.Connexion()\n\t}\n\n\tvar p Page\n\tp = pu\n\trenderHtml(w, p, r)\n}"} {"input": "package relation\n\nimport (\n\t\"github.com/juju/names/v4\"\n\n\t\"github.com/juju/juju/api/uniter\"\n)\n\ntype stateTrackerStateShim struct {\n\t*uniter.State\n}\n\nfunc (s *stateTrackerStateShim) Relation(tag names.RelationTag) (Relation, error) {\n\trel, err := s.State.Relation(tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &relationShim{rel}, nil\n}\n\n\nfunc (s *stateTrackerStateShim) RelationById(id int) (Relation, error) {\n\trel, err := s.State.RelationById(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &relationShim{rel}, nil\n}\n\n\n\n\ntype relationShim struct {\n\t*uniter.Relation\n}\n\nfunc (s *relationShim) Unit(uTag names.UnitTag) (RelationUnit, error) {\n\tu, err := s.Relation.Unit(uTag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RelationUnitShim{u}, nil\n}\n\ntype unitShim struct {\n\t*uniter.Unit\n}\n\nfunc (s *unitShim) Application() (Application, error) {\n\tapp, err := s.Unit.Application()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &applicationShim{app}, nil\n}\n\ntype applicationShim struct {\n\t*uniter.Application\n}\n\ntype RelationUnitShim struct {\n\t*uniter.RelationUnit\n}\n\nfunc (r *RelationUnitShim) Relation() Relation {\n\treturn &relationShim{r.RelationUnit.Relation()}\n}\n\nfunc (s *stateTrackerStateShim) Unit(tag names.UnitTag) (Unit, error) ", "output": "{\n\tunit, err := s.State.Unit(tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &unitShim{unit}, nil\n}"} {"input": "package day09\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestIsValid(t *testing.T) {\n\tsequence := make([]int, 25)\n\tfor i := 0; i < 25; i++ {\n\t\tsequence[i] = i + 1\n\t}\n\n\trequire.True(t, IsValid(sequence, 26))\n\trequire.True(t, IsValid(sequence, 49))\n\trequire.False(t, IsValid(sequence, 100))\n\trequire.False(t, IsValid(sequence, 50))\n}\n\nfunc TestFirstInvalidValue(t *testing.T) {\n\tsequence := []int{35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576}\n\tvalue, err := FirstInvalidValue(sequence, 5)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 127, value)\n}\n\n\n\nfunc TestFindWeakness(t *testing.T) {\n\tsequence := []int{35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576}\n\tvalue, err := FindWeakness(sequence, 127)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 62, value)\n}\n\nfunc TestFindContiguousSum(t *testing.T) ", "output": "{\n\tsequence := []int{35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576}\n\tstart, end, err := FindContiguousSum(sequence, 127)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 2, start)\n\trequire.Equal(t, 5, end)\n}"} {"input": "func backtrack(start int, current []int, n, k int, result *[][]int) {\n if len(current) == k {\n currentCopy := make([]int, len(current))\n copy(currentCopy, current)\n *result = append(*result, currentCopy)\n return\n }\n if start > n {\n return\n }\n for i := start; i <= n; i++ {\n current = append(current, i) \n backtrack(i+1, current, n, k, result)\n current = current[0:len(current)-1]\n }\n}\n\n\n\nfunc combine(n int, k int) [][]int ", "output": "{\n var result [][]int\n backtrack(1, []int{}, n, k, &result)\n return result\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/clients/generated/client/clientset/versioned/typed/containeranalysis/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeContaineranalysisV1beta1 struct {\n\t*testing.Fake\n}\n\n\n\n\n\nfunc (c *FakeContaineranalysisV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeContaineranalysisV1beta1) ContainerAnalysisNotes(namespace string) v1beta1.ContainerAnalysisNoteInterface ", "output": "{\n\treturn &FakeContainerAnalysisNotes{c, namespace}\n}"} {"input": "package hwaflib\n\nfunc (ctx *Context) Version() string {\n\tversion := \"20140814\"\n\treturn version\n}\n\n\n\nfunc (ctx *Context) Revision() string ", "output": "{\n\trevision := \"09081c1\"\n\treturn revision\n}"} {"input": "package wml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/wml\"\n)\n\nfunc TestCT_DocPartTypesConstructor(t *testing.T) {\n\tv := wml.NewCT_DocPartTypes()\n\tif v == nil {\n\t\tt.Errorf(\"wml.NewCT_DocPartTypes must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed wml.CT_DocPartTypes should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestCT_DocPartTypesMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := wml.NewCT_DocPartTypes()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := wml.NewCT_DocPartTypes()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package travel\n\nimport (\n\t\"os\"\n\n\t\"github.com/akerl/speculate/v2/creds\"\n)\n\nfunc clearEnvironment() error {\n\tfor varName := range creds.Translations[\"envvar\"] {\n\t\tlogger.InfoMsgf(\"Unsetting env var: %s\", varName)\n\t\terr := os.Unsetenv(varName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\nfunc sliceUnion(a []string, b []string) []string {\n\tvar res []string\n\tfor _, item := range a {\n\t\tif stringInSlice(b, item) {\n\t\t\tres = append(res, item)\n\t\t}\n\t}\n\treturn res\n}\n\ntype attrFunc func(Path) string\n\nfunc uniquePathAttributes(paths []Path, af attrFunc) []string {\n\ttmpMap := map[string]bool{}\n\tfor _, item := range paths {\n\t\tattr := af(item)\n\t\ttmpMap[attr] = true\n\t}\n\ttmpList := []string{}\n\tfor item := range tmpMap {\n\t\ttmpList = append(tmpList, item)\n\t}\n\treturn tmpList\n}\n\nfunc filterPathsByAttribute(paths []Path, match string, af attrFunc) []Path {\n\tfilteredPaths := []Path{}\n\tfor _, item := range paths {\n\t\tif af(item) == match {\n\t\t\tfilteredPaths = append(filteredPaths, item)\n\t\t}\n\t}\n\treturn filteredPaths\n}\n\nfunc stringInSlice(list []string, key string) bool ", "output": "{\n\tfor _, item := range list {\n\t\tif item == key {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package storage\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\tgenericregistry \"k8s.io/apiserver/pkg/registry/generic/registry\"\n\t\"k8s.io/apiserver/pkg/registry/rest\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/registry/cachesize\"\n\t\"k8s.io/kubernetes/pkg/registry/core/limitrange\"\n)\n\ntype REST struct {\n\t*genericregistry.Store\n}\n\n\nfunc NewREST(optsGetter generic.RESTOptionsGetter) *REST {\n\tstore := &genericregistry.Store{\n\t\tCopier: api.Scheme,\n\t\tNewFunc: func() runtime.Object { return &api.LimitRange{} },\n\t\tNewListFunc: func() runtime.Object { return &api.LimitRangeList{} },\n\t\tObjectNameFunc: func(obj runtime.Object) (string, error) {\n\t\t\treturn obj.(*api.LimitRange).Name, nil\n\t\t},\n\t\tPredicateFunc: limitrange.MatchLimitRange,\n\t\tQualifiedResource: api.Resource(\"limitranges\"),\n\t\tWatchCacheSize: cachesize.GetWatchCacheSizeByResource(\"limitranges\"),\n\n\t\tCreateStrategy: limitrange.Strategy,\n\t\tUpdateStrategy: limitrange.Strategy,\n\t\tDeleteStrategy: limitrange.Strategy,\n\t\tExportStrategy: limitrange.Strategy,\n\t}\n\toptions := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: limitrange.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\tpanic(err) \n\t}\n\treturn &REST{store}\n}\n\n\nvar _ rest.ShortNamesProvider = &REST{}\n\n\n\n\nfunc (r *REST) ShortNames() []string ", "output": "{\n\treturn []string{\"limits\"}\n}"} {"input": "package opt\n\nimport (\n\t\"testing\"\n\n\t\"github.com/cpmech/gosl/chk\"\n\t\"github.com/cpmech/gosl/io\"\n\t\"github.com/cpmech/gosl/la\"\n)\n\n\n\nfunc TestNLS01(tst *testing.T) ", "output": "{\n\n\tchk.PrintTitle(\"NLS01. NonLinSolver\")\n\n\tp := Factory.SimpleParaboloid()\n\tx := la.NewVectorSlice([]float64{1, 1})\n\n\tfor _, kind := range []string{\"conjgrad\", \"powell\", \"graddesc\"} {\n\t\tio.Pf(\">>>>>>>>>>>>>>>>>>> running %q <<<<<<<<<<<<<<<<<<<<\\n\", kind)\n\t\tsol := GetNonLinSolver(kind, p)\n\t\tfmin := sol.Min(x, nil)\n\t\tio.Pf(\"fmin = %v (%v)\\n\", fmin, p.Fref)\n\t\tchk.Float64(tst, \"fmin\", 1e-10, fmin, p.Fref)\n\t\tchk.Array(tst, \"xmin\", 1e-10, x, p.Xref)\n\t}\n}"} {"input": "package device\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n)\n\nvar logger *log.Logger\n\n\n\nfunc init() ", "output": "{\n\tlogger = log.New(os.Stdout, loggerPrefix, 0)\n\n\tv, err := strconv.Atoi(os.Getenv(\"DEBUG\"))\n\tif err == nil && v == 1 {\n\t\tlogger.SetFlags(log.Ltime | log.Lshortfile)\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\n\ntype T struct { i int }\n\nfunc (t T) Foo () {\n fmt.Println (t.i)\n}\n\n\n\nfunc main () {\n fmt.Println (\"Shall we?\")\n var t T\n t.Foo ()\n var pt = new (T)\n pt.Bar ()\n}\n\nfunc (t *T) Bar () ", "output": "{\n fmt.Println (t.i)\n}"} {"input": "package rapidpro\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\ntype SessionID int64\n\nconst updateSessionTimeoutSQL = `\n\tUPDATE\n\t\tflows_flowsession\n\tSET\n\t\ttimeout_on = NOW() + $3 * interval '1 second'\n\tWHERE\n\t\tid = $1 AND\n\t\textract(epoch from wait_started_on) = extract(epoch from $2::timestamp with time zone) AND\n\t\tstatus = 'W'\n`\n\n\n\n\nfunc updateSessionTimeout(ctx context.Context, b *backend, sessionID SessionID, waitStartedOn time.Time, timeoutSeconds int) error ", "output": "{\n\t_, err := b.db.ExecContext(ctx, updateSessionTimeoutSQL, sessionID, waitStartedOn.In(time.UTC), timeoutSeconds)\n\treturn err\n}"} {"input": "package model\n\nimport (\n\t\"github.com/Konstantin8105/GoFea/input/element\"\n\t\"github.com/Konstantin8105/GoFea/input/material\"\n)\n\ntype materialLinearGroup struct {\n\tmaterial material.Linear\n\telementIndex element.Index\n}\n\n\ntype materialByElement []materialLinearGroup\n\nfunc (a materialByElement) Len() int { return len(a) }\nfunc (a materialByElement) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\n\nfunc (a materialByElement) Equal(i, j int) bool { return a[i].elementIndex == a[j].elementIndex }\nfunc (a materialByElement) Name(i int) int { return int(a[i].elementIndex) }\n\nfunc (a materialByElement) Less(i, j int) bool ", "output": "{ return a[i].elementIndex < a[j].elementIndex }"} {"input": "package internal\n\nimport (\n\t\"net/http\"\n\t\"os\"\n)\n\nconst (\n\tdefaultAddr = \"http://localhost:8983\"\n\taddrEnvName = \"GO_SOLR_ADDR\"\n)\n\n\n\nfunc MustNewInternalClient() *Client {\n\tc, err := NewInternalClient()\n\tif err != nil {\n\t\tlog.Error(\"can't create internal client for test\")\n\t\tpanic(err)\n\t}\n\treturn c\n}\n\nfunc NewInternalClient() (*Client, error) ", "output": "{\n\tvar addr string\n\tif addr = os.Getenv(addrEnvName); addr == \"\" {\n\t\taddr = defaultAddr\n\t}\n\tlog.Infof(\"use solr %s\", addr)\n\ttr := &http.Transport{}\n\tc := &http.Client{Transport: tr}\n\treturn NewClient(c, BaseURL(addr))\n}"} {"input": "package shm\n\n\nimport \"C\"\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"syscall\"\n\t\"unsafe\"\n)\n\ntype sharedMem struct {\n\tmem MMap\n\tf *os.File\n\tname string\n}\n\ntype SharedMemory interface {\n\tClose() error\n\tLen() int\n\tPointer() unsafe.Pointer\n\tDelete() error\n}\n\n\n\nfunc Open(regionName string) (sh SharedMemory, err error) {\n\tif !strings.HasPrefix(regionName, \"/\") {\n\t\tregionName = \"/\" + regionName\n\t}\n\ts := sharedMem{name: regionName}\n\ts.f, err = open(regionName, int(C.O_RDWR), 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.mem, err = MapRegion(s.f, -1, RDWR, 0, 0)\n\tif err != nil {\n\t\t_ = s.f.Close()\n\t\treturn nil, err\n\t}\n\treturn &s, nil\n}\n\nfunc (s *sharedMem) Close() (err error) {\n\terr = s.mem.Unmap()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.f.Close()\n}\n\nfunc (s *sharedMem) Delete() error {\n\treturn del(s.name)\n}\n\nfunc (s *sharedMem) Pointer() unsafe.Pointer {\n\treturn unsafe.Pointer(&((s.mem)[0]))\n}\n\nfunc (s *sharedMem) Len() int {\n\treturn len(s.mem)\n}\n\nfunc Create(regionName string, size int) (sh SharedMemory, err error) ", "output": "{\n\tif size <= 0 {\n\t\treturn nil, fmt.Errorf(\"Size must be strictly positive\")\n\t}\n\tif !strings.HasPrefix(regionName, \"/\") {\n\t\tregionName = \"/\" + regionName\n\t}\n\ts := sharedMem{name: regionName}\n\ts.f, err = open(regionName, int(C.O_RDWR|C.O_CREAT|C.O_EXCL), 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = syscall.Ftruncate(int(s.f.Fd()), int64(size))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.mem, err = MapRegion(s.f, size, RDWR, 0, 0)\n\tif err != nil {\n\t\t_ = s.f.Close()\n\t\t_ = del(regionName)\n\t\treturn nil, err\n\t}\n\treturn &s, nil\n}"} {"input": "package secret\n\nconst (\n\tAdminserverUser = \"harbor-adminserver\"\n\tJobserviceUser = \"harbor-jobservice\"\n\tUIUser = \"harbor-ui\"\n)\n\n\ntype Store struct {\n\tsecrets map[string]string\n}\n\n\nfunc NewStore(secrets map[string]string) *Store {\n\treturn &Store{\n\t\tsecrets: secrets,\n\t}\n}\n\n\n\n\n\nfunc (s *Store) GetUsername(secret string) string {\n\treturn s.secrets[secret]\n}\n\nfunc (s *Store) IsValid(secret string) bool ", "output": "{\n\treturn len(s.GetUsername(secret)) != 0\n}"} {"input": "package autobackup\n\nimport (\n\t\"context\"\n\n\t\"github.com/sacloud/libsacloud/v2/helper/service\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n)\n\nfunc (s *Service) Delete(req *DeleteRequest) error {\n\treturn s.DeleteWithContext(context.Background(), req)\n}\n\n\n\nfunc (s *Service) DeleteWithContext(ctx context.Context, req *DeleteRequest) error ", "output": "{\n\tif err := req.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tclient := sacloud.NewAutoBackupOp(s.caller)\n\tif err := client.Delete(ctx, req.Zone, req.ID); err != nil {\n\t\treturn service.HandleNotFoundError(err, !req.FailIfNotFound)\n\t}\n\treturn nil\n}"} {"input": "package radosAPI\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"time\"\n\n\t\"github.com/smartystreets/go-aws-auth\"\n)\n\n\ntype API struct {\n\thost string\n\taccessKey string\n\tsecretKey string\n\tprefix string\n\tclient *http.Client\n}\n\n\nfunc New(host, accessKey, secretKey string, adminPrefix ...string) (*API, error) {\n\treturn NewWithClient(&http.Client{}, host, accessKey, secretKey, adminPrefix...)\n}\n\nfunc NewWithClient(client *http.Client, host, accessKey, secretKey string, adminPrefix ...string) (*API, error) {\n\tprefix := \"admin\"\n\tif len(adminPrefix) > 0 {\n\t\tprefix = adminPrefix[0]\n\t}\n\tif host == \"\" || accessKey == \"\" || secretKey == \"\" {\n\t\treturn nil, fmt.Errorf(\"host, accessKey, secretKey must be not nil\")\n\t}\n\treturn &API{host, accessKey, secretKey, prefix, client}, nil\n}\n\n\n\nfunc (api *API) call(verb, route string, args url.Values, usePrefix bool, sub ...string) (body []byte, statusCode int, err error) {\n\tsubreq := \"\"\n\tif len(sub) > 0 {\n\t\tsubreq = fmt.Sprintf(\"%s&\", sub[0])\n\t}\n\tif usePrefix {\n\t\troute = fmt.Sprintf(\"/%s%s\", api.prefix, route)\n\t}\n\tbody, statusCode, err = api.makeRequest(verb, fmt.Sprintf(\"%v%v?%v%s\", api.host, route, subreq, args.Encode()))\n\tif statusCode != 200 {\n\t\terr = fmt.Errorf(\"[%v]: %v\", statusCode, err)\n\t}\n\treturn\n}\n\nfunc (api *API) makeRequest(verb, url string) (body []byte, statusCode int, err error) ", "output": "{\n\tvar apiErr apiError\n\n\treq, err := http.NewRequest(verb, url, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\tawsauth.SignS3(req, awsauth.Credentials{\n\t\tAccessKeyID: api.accessKey,\n\t\tSecretAccessKey: api.secretKey,\n\t\tExpiration: time.Now().Add(1 * time.Minute)},\n\t)\n\tresp, err := api.client.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tif resp.Body != nil {\n\t\tdefer resp.Body.Close()\n\t}\n\tstatusCode = resp.StatusCode\n\tbody, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\tif errMarshal := json.Unmarshal(body, &apiErr); errMarshal == nil && apiErr.Code != \"\" {\n\t\terr = errors.New(apiErr.Code)\n\t}\n\treturn\n}"} {"input": "package endpoints\n\nimport (\n\t\"github.com/lxc/lxd/lxd/util\"\n\t\"github.com/lxc/lxd/shared\"\n)\n\n\nfunc Unstarted() *Endpoints {\n\treturn &Endpoints{\n\t\tsystemdListenFDsStart: util.SystemdListenFDsStart,\n\t}\n}\n\nfunc (e *Endpoints) Up(config *Config) error {\n\treturn e.up(config)\n}\n\n\nfunc (e *Endpoints) DevLxdSocketPath() string {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tlistener := e.listeners[devlxd]\n\treturn listener.Addr().String()\n}\n\n\n\n\n\n\nfunc (e *Endpoints) NetworkAddressAndCert() (string, *shared.CertInfo) {\n\treturn e.NetworkAddress(), e.cert\n}\n\n\n\n\nfunc (e *Endpoints) SystemdListenFDsStart(start int) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\te.systemdListenFDsStart = start\n}\n\nfunc (e *Endpoints) LocalSocketPath() string ", "output": "{\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tlistener := e.listeners[local]\n\treturn listener.Addr().String()\n}"} {"input": "package nessusCreator\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"github.com/kkirsche/nessusControl/api\" \n\t\"net/http\"\n\t\"os\"\n)\n\n\n\n\n\nfunc NewCreator(baseDirectory string, client *nessusAPI.Client, httpClient *http.Client, sqliteDB *sql.DB, debug bool) *Creator ", "output": "{\n\treturn &Creator{\n\t\tapiClient: client,\n\t\tdebug: debug,\n\t\thttpClient: httpClient,\n\t\tsqliteDB: sqliteDB,\n\t\tfileLocations: fileLocations{\n\t\t\tbaseDirectory: baseDirectory,\n\t\t\tarchiveDirectory: fmt.Sprintf(\"%s/targets/archive\", baseDirectory),\n\t\t\ttemporaryDirectory: fmt.Sprintf(\"%s/targets/temp%d\", baseDirectory, os.Getpid()),\n\t\t\tincomingDirectory: fmt.Sprintf(\"%s/targets/incoming\", baseDirectory),\n\t\t},\n\t}\n}"} {"input": "package version\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n)\n\ntype version struct {\n\t*flags.EmptyFlag\n\n\trequire string\n}\n\nfunc init() {\n\tcli.Register(\"version\", &version{})\n}\n\n\n\nfunc (cmd *version) Run(ctx context.Context, f *flag.FlagSet) error {\n\tver := flags.GitVersion\n\tif ver == \"\" {\n\t\tver = flags.Version\n\t}\n\n\tif cmd.require != \"\" {\n\t\tv, err := flags.ParseVersion(ver)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\trv, err := flags.ParseVersion(cmd.require)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse required version '%s': %s\", cmd.require, err)\n\t\t}\n\n\t\tif !rv.Lte(v) {\n\t\t\treturn fmt.Errorf(\"version %s or higher is required, this is version %s\", cmd.require, ver)\n\t\t}\n\t}\n\n\tfmt.Printf(\"govc %s\\n\", ver)\n\n\treturn nil\n}\n\nfunc (cmd *version) Register(ctx context.Context, f *flag.FlagSet) ", "output": "{\n\tf.StringVar(&cmd.require, \"require\", \"\", \"Require govc version >= this value\")\n}"} {"input": "package lzma\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"unicode\"\n)\n\n\n\ntype operation interface {\n\tLen() int\n}\n\n\ntype match struct {\n\tdistance int64\n\tn int\n}\n\n\n\n\n\n\n\nfunc (m match) l() uint32 {\n\treturn uint32(m.n - minMatchLen)\n}\n\n\n\nfunc (m match) dist() uint32 {\n\treturn uint32(m.distance - minDistance)\n}\n\n\nfunc (m match) Len() int {\n\treturn m.n\n}\n\n\nfunc (m match) String() string {\n\treturn fmt.Sprintf(\"M{%d,%d}\", m.distance, m.n)\n}\n\n\ntype lit struct {\n\tb byte\n}\n\n\nfunc (l lit) Len() int {\n\treturn 1\n}\n\n\nfunc (l lit) String() string {\n\tvar c byte\n\tif unicode.IsPrint(rune(l.b)) {\n\t\tc = l.b\n\t} else {\n\t\tc = '.'\n\t}\n\treturn fmt.Sprintf(\"L{%c/%02x}\", c, l.b)\n}\n\nfunc (m match) verify() error ", "output": "{\n\tif !(minDistance <= m.distance && m.distance <= maxDistance) {\n\t\treturn errors.New(\"distance out of range\")\n\t}\n\tif !(1 <= m.n && m.n <= maxMatchLen) {\n\t\treturn errors.New(\"length out of range\")\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestArea(t *testing.T) {\n\n\tareaTests := []struct {\n\t\tshape Shape\n\t\twant float64\n\t}{\n\t\t{Rectangle{12, 6}, 72.0},\n\t\t{Circle{10}, 314.1592653589793},\n\t\t{Triangle{12, 6}, 36.0},\n\t}\n\n\tfor _, tt := range areaTests {\n\t\tgot := tt.shape.Area()\n\t\tif got != tt.want {\n\t\t\tt.Errorf(\"got %.2f want %.2f\", got, tt.want)\n\t\t}\n\t}\n\n}\n\nfunc TestPerimeter(t *testing.T) ", "output": "{\n\trectangle := Rectangle{10.0, 10.0}\n\tgot := Perimeter(rectangle)\n\twant := 40.0\n\n\tif got != want {\n\t\tt.Errorf(\"got %.2f want %.2f\", got, want)\n\t}\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/apier/v1\"\n\n\n\n\ntype CmdAccountAddTriggers struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrAddAccountActionTriggers\n\t*CommandExecuter\n}\n\nfunc (self *CmdAccountAddTriggers) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdAccountAddTriggers) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdAccountAddTriggers) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrAddAccountActionTriggers{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdAccountAddTriggers) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdAccountAddTriggers) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc init() ", "output": "{\n\tc := &CmdAccountAddTriggers{\n\t\tname: \"account_triggers_add\",\n\t\trpcMethod: \"ApierV1.AddAccountActionTriggers\",\n\t\trpcParams: &v1.AttrAddAccountActionTriggers{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}"} {"input": "package tagquery\n\nimport (\n\t\"io\"\n\n\t\"github.com/grafana/metrictank/schema\"\n)\n\ntype expressionMatchNone struct {\n\texpressionCommon\n\toriginalOperator ExpressionOperator\n}\n\nfunc (e *expressionMatchNone) Equals(other Expression) bool {\n\treturn e.key == other.GetKey() && e.GetOperator() == other.GetOperator() && e.value == other.GetValue()\n}\n\nfunc (e *expressionMatchNone) GetDefaultDecision() FilterDecision {\n\treturn Fail\n}\n\nfunc (e *expressionMatchNone) GetKey() string {\n\treturn e.key\n}\n\nfunc (e *expressionMatchNone) GetValue() string {\n\treturn e.value\n}\n\nfunc (e *expressionMatchNone) GetOperator() ExpressionOperator {\n\treturn MATCH_NONE\n}\n\nfunc (e *expressionMatchNone) GetOperatorCost() uint32 {\n\treturn 0\n}\n\n\n\nfunc (e *expressionMatchNone) Matches(value string) bool {\n\treturn false\n}\n\nfunc (e *expressionMatchNone) GetMetricDefinitionFilter(_ IdTagLookup) MetricDefinitionFilter {\n\treturn func(_ schema.MKey, _ string, _ []string) FilterDecision { return Fail }\n}\n\nfunc (e *expressionMatchNone) StringIntoWriter(writer io.Writer) {\n\twriter.Write([]byte(e.key))\n\te.originalOperator.StringIntoWriter(writer)\n\twriter.Write([]byte(e.value))\n}\n\nfunc (e *expressionMatchNone) RequiresNonEmptyValue() bool ", "output": "{\n\treturn true\n}"} {"input": "package helpers\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n)\n\nfunc GetFixturePath(name string) string {\n\t_, filename, _, _ := runtime.Caller(0)\n\n\tfixturePath := path.Join(path.Dir(filename), \"..\", \"fixtures\", name)\n\n\t_, err := os.Stat(fixturePath)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn fixturePath\n}\n\n\n\nfunc ReadFixtureString(name string) string {\n\treturn string(ReadFixtureBytes(name))\n}\n\nfunc ReadFixtureBytes(name string) []byte ", "output": "{\n\tpath := GetFixturePath(name)\n\tcontents, err := ioutil.ReadFile(path)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn contents\n}"} {"input": "package config\n\nimport (\n\t\"encoding/json\"\n\t\"path\"\n\n\t\"github.com/golang/glog\"\n)\n\n\n\n\nfunc storeProject(client ETCDInterface, p Project, base string) error {\n\tbuf, err := json.Marshal(p)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to marshal project config of %s: %v\", p.Name, err)\n\t\treturn err\n\t}\n\tdir := path.Join(base, \"projects\", p.Name)\n\tif _, err := client.Set(path.Join(dir, \"config\"), string(buf), 0); err != nil {\n\t\tglog.Errorf(\"Failed to store project config of %s: %v\", p.Name, err)\n\t\treturn err\n\t}\n\tfor _, env := range p.Environments {\n\t\tif err := storeEnvironment(client, env, path.Join(dir, \"environments\")); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc storeEnvironment(client ETCDInterface, env Environment, dir string) error {\n\tbuf, err := json.Marshal(env)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to marshal environment config of %s: %v\", env.Name, err)\n\t\treturn err\n\t}\n\tif _, err := client.Set(path.Join(dir, env.Name), string(buf), 0); err != nil {\n\t\tglog.Errorf(\"Failed to store environment config of %s: %v\", env.Name, err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc Store(client ETCDInterface, cfg Config) error ", "output": "{\n\tbuf, err := json.Marshal(cfg)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to marshal global config: %v\", err)\n\t\treturn err\n\t}\n\tif _, err := client.Set(\"/goship/config\", string(buf), 0); err != nil {\n\t\tglog.Errorf(\"Failed to store global config: %v\", err)\n\t\treturn err\n\t}\n\tfor _, p := range cfg.Projects {\n\t\tif err := storeProject(client, p, \"/goship\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package ast\n\nimport (\n\t\"fmt\"\n\t\"github.com/rhysd/gocaml/token\"\n\t\"github.com/rhysd/locerr\"\n)\n\n\ntype printPath struct {\n\ttotal int\n}\n\n\n\n\n\nfunc (v *printPath) VisitBottomup(e Expr) {\n\tfmt.Printf(\"\\n -> %s (bottomup)\", e.Name())\n}\n\nfunc Example() {\n\tsrc := locerr.NewDummySource(\"\")\n\n\trootOfAST := &Let{\n\t\tLetToken: &token.Token{File: src},\n\t\tSymbol: NewSymbol(\"test\"),\n\t\tBound: &Int{\n\t\t\tToken: &token.Token{File: src},\n\t\t\tValue: 42,\n\t\t},\n\t\tBody: &Add{\n\t\t\tLeft: &VarRef{\n\t\t\t\tToken: &token.Token{File: src},\n\t\t\t\tSymbol: NewSymbol(\"test\"),\n\t\t\t},\n\t\t\tRight: &Float{\n\t\t\t\tToken: &token.Token{File: src},\n\t\t\t\tValue: 3.14,\n\t\t\t},\n\t\t},\n\t}\n\n\tast := &AST{Root: rootOfAST}\n\n\tv := &printPath{0}\n\tfmt.Println(\"ROOT\")\n\n\tVisit(v, ast.Root)\n\n\tPrintln(ast)\n}\n\nfunc (v *printPath) VisitTopdown(e Expr) Visitor ", "output": "{\n\tfmt.Printf(\"\\n -> %s (topdown)\", e.Name())\n\treturn v\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"bufio\"\n\t\"os\"\n)\n\ntype Node struct {\n\tdata interface{}\n\tnext *Node\n}\n\nvar lengthOfStack = 0\nvar top *Node\n\nfunc main() {\n\tscanner := bufio.NewScanner(os.Stdin)\n\n\tfor true {\n\t\tfmt.Println(\"Select one of the following options:\")\n\t\tfmt.Println(\"1. Push\")\n\t\tfmt.Println(\"2. Pop\")\n\t\tfmt.Println(\"3. Length of stack\")\n\t\tfmt.Println(\"4. Exit\")\n\n\t\tscanner.Scan()\n\t\tfmt.Println(\"\")\n\t\tswitch scanner.Text() {\n\t\t\tcase \"1\":\n\t\t\t\tpush(scanner)\n\t\t\tcase \"2\":\n\t\t\t\tpop()\n\n\t\t\tcase \"3\":\n\t\t\t\tfmt.Println(\"The length of the stack is:\", lengthOfStack)\n\t\t\t\tfmt.Println(\"\")\t\n\t\t\tcase \"4\":\n\t\t\t\tos.Exit(0)\n\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Please, select a valid option.\")\n\t\t}\n\t}\n}\n\nfunc push(scanner *bufio.Scanner) {\n\tfmt.Println(\"Type the number you want to push into the stack\")\n\tscanner.Scan()\n\tfmt.Println(\"\")\t\n\n\tlengthOfStack += 1\n\tif(top == nil) {\n\t\ttop = &Node{scanner.Text(), nil}\n\t\treturn\n\t}\n\n\tnewNode := &Node{scanner.Text(), top}\n\ttop = newNode\n}\n\n\n\nfunc pop() ", "output": "{\n\tif(top == nil) {\n\t\tfmt.Println(\"Empty stack\")\n\t\tfmt.Println(\"\")\t\t\n\t\treturn\n\t}\n\n\tfmt.Println(\"Element to pop:\", top.data)\n\tfmt.Println(\"\")\t\n\n\ttop = top.next\n\n\tlengthOfStack -= 1\n}"} {"input": "package nsqd\n\nimport (\n\t\"bytes\"\n\t\"sync\"\n)\n\nvar bp sync.Pool\n\nfunc init() {\n\tbp.New = func() interface{} {\n\t\treturn &bytes.Buffer{}\n\t}\n}\n\n\n\nfunc bufferPoolPut(b *bytes.Buffer) {\n\tb.Reset()\n\tbp.Put(b)\n}\n\nfunc bufferPoolGet() *bytes.Buffer ", "output": "{\n\treturn bp.Get().(*bytes.Buffer)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"camlistore.org/pkg/blobref\"\n\t\"camlistore.org/pkg/cmdmain\"\n)\n\ntype removeCmd struct{}\n\nfunc init() {\n\tcmdmain.RegisterCommand(\"remove\", func(flags *flag.FlagSet) cmdmain.CommandRunner {\n\t\tcmd := new(removeCmd)\n\t\treturn cmd\n\t})\n}\n\nfunc (c *removeCmd) Usage() {\n\tfmt.Fprintf(cmdmain.Stderr, `Usage: camput remove \n\nThis command is for debugging only. You're not expected to use it in practice.\n`)\n}\n\n\n\nfunc (c *removeCmd) RunCommand(args []string) error ", "output": "{\n\tif len(args) == 0 {\n\t\treturn cmdmain.ErrUsage\n\t}\n\treturn getUploader().RemoveBlobs(blobref.ParseMulti(args))\n}"} {"input": "package synctest\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nconst (\n\ttimeout = 100 * time.Millisecond\n)\n\nfunc TestNotifyLock(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tch := nl.NotifyLock()\n\tnl.Lock()\n\tselect {\n\tcase <-ch:\n\tcase <-time.After(timeout):\n\t\tt.Fatalf(\"didn't receive on channel after %s\", timeout)\n\t}\n}\n\n\n\nfunc TestNotifyLockOnUnlock(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tnl.Lock()\n\tch := nl.NotifyLock()\n\tnl.Unlock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"got a lock notification on unlock\")\n\tcase <-time.After(timeout):\n\t}\n}\n\nfunc TestNotifyUnlock(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tch := nl.NotifyUnlock()\n\tnl.Lock()\n\tnl.Unlock()\n\tselect {\n\tcase <-ch:\n\tcase <-time.After(timeout):\n\t\tt.Fatalf(\"didn't get unlock notification after %s\", timeout)\n\t}\n}\n\nfunc TestNotifyUnlockAlreadyUnlocked(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tnl.Lock()\n\tnl.Unlock()\n\tch := nl.NotifyUnlock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"got unlock notification\")\n\tcase <-time.After(timeout):\n\t}\n}\n\nfunc TestNofifyUnlockOnLock(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tch := nl.NotifyUnlock()\n\tnl.Lock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"got unlock notification on lock\")\n\tcase <-time.After(timeout):\n\t}\n}\n\nfunc TestNotifyLockAlreadyLocked(t *testing.T) ", "output": "{\n\tnl := NewNotifyingLocker()\n\tnl.Lock()\n\tch := nl.NotifyLock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"received on channel\")\n\tcase <-time.After(timeout):\n\t}\n}"} {"input": "package url\n\nimport (\n\t\"github.com/dpb587/metalink\"\n\t\"github.com/dpb587/metalink/file\"\n)\n\ntype MultiLoader struct {\n\tloaders []Loader\n}\n\nvar _ Loader = &MultiLoader{}\n\n\n\nfunc (l *MultiLoader) SupportsURL(source metalink.URL) bool {\n\tfor _, loader := range l.loaders {\n\t\tif loader.SupportsURL(source) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (l *MultiLoader) LoadURL(source metalink.URL) (file.Reference, error) {\n\tfor _, loader := range l.loaders {\n\t\tif !loader.SupportsURL(source) {\n\t\t\tcontinue\n\t\t}\n\n\t\tref, err := loader.LoadURL(source)\n\t\tif err == UnsupportedURLError {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn ref, err\n\t}\n\n\treturn nil, UnsupportedURLError\n}\n\nfunc (l *MultiLoader) Add(add Loader) {\n\tl.loaders = append(l.loaders, add)\n}\n\nfunc NewMultiLoader(loaders ...Loader) *MultiLoader ", "output": "{\n\treturn &MultiLoader{\n\t\tloaders: loaders,\n\t}\n}"} {"input": "package hooktesting\n\nimport (\n\t\"gopkg.in/juju/charm.v4/hooks\"\n\t\"launchpad.net/tomb\"\n\n\t\"github.com/juju/juju/worker/uniter/hook\"\n)\n\nfunc HookList(kinds ...hooks.Kind) []hook.Info {\n\tresult := make([]hook.Info, len(kinds))\n\tfor i, kind := range kinds {\n\t\tresult[i].Kind = kind\n\t}\n\treturn result\n}\n\ntype UpdateSource struct {\n\tTomb tomb.Tomb\n\tempty bool\n\tChangesC chan hook.SourceChange\n\tUpdatesC chan interface{}\n}\n\nfunc NewEmptySource() *UpdateSource {\n\treturn newUpdateSource(true, false)\n}\n\nfunc NewFullBufferedSource() *UpdateSource {\n\treturn newUpdateSource(false, true)\n}\n\nfunc NewFullUnbufferedSource() *UpdateSource {\n\treturn newUpdateSource(false, false)\n}\n\n\n\nfunc (source *UpdateSource) Stop() error {\n\tsource.Tomb.Kill(nil)\n\treturn source.Tomb.Wait()\n}\n\nfunc (source *UpdateSource) Changes() <-chan hook.SourceChange {\n\treturn source.ChangesC\n}\n\nfunc (source *UpdateSource) NewChange(v interface{}) hook.SourceChange {\n\treturn func() error {\n\t\tselect {\n\t\tcase <-source.Tomb.Dying():\n\t\t\treturn tomb.ErrDying\n\t\tcase source.UpdatesC <- v:\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc (source *UpdateSource) Empty() bool {\n\treturn source.empty\n}\n\nfunc (source *UpdateSource) Next() hook.Info {\n\tif source.empty {\n\t\tpanic(nil)\n\t}\n\treturn hook.Info{Kind: hooks.Install}\n}\n\nfunc (source *UpdateSource) Pop() {\n\tif source.empty {\n\t\tpanic(nil)\n\t}\n}\n\nfunc newUpdateSource(empty, buffered bool) *UpdateSource ", "output": "{\n\tvar bufferSize int\n\tif buffered {\n\t\tbufferSize = 1000\n\t}\n\tsource := &UpdateSource{\n\t\tempty: empty,\n\t\tChangesC: make(chan hook.SourceChange),\n\t\tUpdatesC: make(chan interface{}, bufferSize),\n\t}\n\tgo func() {\n\t\tdefer source.Tomb.Done()\n\t\tdefer close(source.ChangesC)\n\t\t<-source.Tomb.Dying()\n\t}()\n\treturn source\n}"} {"input": "package hosts\n\nimport (\n\t\"testing\"\n)\n\nfunc Test0(t *testing.T) {\n\tconst src = `\n \n\t# parser test\n\n 1.2.3.44 somehost\n1.2.3.4 somehost.x\n1.2.3.4 somehost.x.y\n1.2.3.4 somehost.x.y.z\n1.2.3.4 somehost.x.y.z a\n1.2.3.4 somehost.x.y.z a b\n1.2.3.4 somehost.x.y.z a b c\n\n 1.2.3.4 somehost\n 1.2.3.4 somehost.x\n1.2.3.4 somehost.x.y\n1.2.3.4 somehost.x.y.z\n1.2.3.4 somehost.x.y.z a\n1.2.3.4 somehost.x.y.z a b\n1.2.3.4 somehost.x.y.z a b c\n\n#\n\n #\n\n# comment\n\n1.2.3.4 so#mehost\n1.2.3.4 somehost.x#\n1.2.3.4 somehost.x#.y\n1.2.3.4 somehost.x.y.z #\n1.2.3.4 somehost.x.y.z a #\n1.2.3.4 somehost.x.y.z a b # comment\n1.2.3.4 somehost.x.y.z a b c\n\n\n`\n\tvar f File\n\tif err := f.LoadString(\"Test0\", src); err != nil {\n\t\tt.Fatal(10)\n\t}\n\n\tt.Log(&f)\n}\n\n\n\nfunc Test1(t *testing.T) ", "output": "{\n\tvar f File\n\terr := f.Load(Sys)\n\tif err != nil {\n\t\tt.Log(err)\n\t\treturn\n\t}\n\n\tt.Log(f.String())\n}"} {"input": "package storm\n\nimport (\n\t\"github.com/asdine/storm/codec\"\n\t\"github.com/boltdb/bolt\"\n)\n\n\ntype Node interface {\n\tTx\n\tTypeStore\n\tKeyValueStore\n\tBucketScanner\n\tFrom(addend ...string) Node\n\n\tBucket() []string\n\n\tGetBucket(tx *bolt.Tx, children ...string) *bolt.Bucket\n\n\tCreateBucketIfNotExists(tx *bolt.Tx, bucket string) (*bolt.Bucket, error)\n\n\tWithTransaction(tx *bolt.Tx) Node\n\n\tBegin(writable bool) (Node, error)\n\n\tCodec() codec.EncodeDecoder\n}\n\n\ntype node struct {\n\ts *DB\n\n\trootBucket []string\n\n\ttx *bolt.Tx\n}\n\n\n\nfunc (n node) From(addend ...string) Node {\n\tn.rootBucket = append(n.rootBucket, addend...)\n\treturn &n\n}\n\n\nfunc (n node) WithTransaction(tx *bolt.Tx) Node {\n\tn.tx = tx\n\treturn &n\n}\n\n\n\nfunc (n *node) Bucket() []string {\n\treturn n.rootBucket\n}\n\n\n\n\nfunc (n *node) Codec() codec.EncodeDecoder ", "output": "{\n\treturn n.s.codec\n}"} {"input": "package desk\n\nimport (\n \"github.com/stianeikeland/go-rpio\"\n)\n\ntype Direction uint8\n\nvar (\n upPin rpio.Pin\n downPin rpio.Pin\n)\n\nconst (\n Down Direction = iota\n Up\n)\n\n\n\nfunc Stop() {\n upPin.Low()\n downPin.Low()\n}\n\nfunc Init(up int, down int) (err error) {\n err = rpio.Open()\n\n if (err != nil) {\n return\n }\n\n upPin = rpio.Pin(up)\n upPin.Output()\n upPin.Low()\n\n downPin = rpio.Pin(down)\n downPin.Output()\n downPin.Low()\n\n return nil\n}\n\nfunc Close() {\n rpio.Close()\n}\n\nfunc Move(dir Direction) ", "output": "{\n Stop()\n if (dir == Up) {\n upPin.High()\n } else {\n downPin.High()\n }\n}"} {"input": "package j_kite\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"koding/remoteapi/models\"\n)\n\n\ntype PostRemoteAPIJKiteFetchPlansIDReader struct {\n\tformats strfmt.Registry\n}\n\n\nfunc (o *PostRemoteAPIJKiteFetchPlansIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewPostRemoteAPIJKiteFetchPlansIDOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}\n\n\n\n\n\ntype PostRemoteAPIJKiteFetchPlansIDOK struct {\n\tPayload *models.JKite\n}\n\nfunc (o *PostRemoteAPIJKiteFetchPlansIDOK) Error() string {\n\treturn fmt.Sprintf(\"[POST /remote.api/JKite.fetchPlans/{id}][%d] postRemoteApiJKiteFetchPlansIdOK %+v\", 200, o.Payload)\n}\n\nfunc (o *PostRemoteAPIJKiteFetchPlansIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\to.Payload = new(models.JKite)\n\n\tif err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc NewPostRemoteAPIJKiteFetchPlansIDOK() *PostRemoteAPIJKiteFetchPlansIDOK ", "output": "{\n\treturn &PostRemoteAPIJKiteFetchPlansIDOK{}\n}"} {"input": "package memory\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/protobuf/types/known/emptypb\"\n\n\t\"go.chromium.org/luci/gce/api/projects/v1\"\n)\n\n\nvar _ projects.ProjectsServer = &Projects{}\n\n\ntype Projects struct {\n\tcfg sync.Map\n}\n\n\nfunc (srv *Projects) Delete(c context.Context, req *projects.DeleteRequest) (*emptypb.Empty, error) {\n\tsrv.cfg.Delete(req.GetId())\n\treturn &emptypb.Empty{}, nil\n}\n\n\nfunc (srv *Projects) Ensure(c context.Context, req *projects.EnsureRequest) (*projects.Config, error) {\n\tsrv.cfg.Store(req.GetId(), req.GetProject())\n\treturn req.GetProject(), nil\n}\n\n\nfunc (srv *Projects) Get(c context.Context, req *projects.GetRequest) (*projects.Config, error) {\n\tcfg, ok := srv.cfg.Load(req.GetId())\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.NotFound, \"no project found with ID %q\", req.GetId())\n\t}\n\treturn cfg.(*projects.Config), nil\n}\n\n\n\n\nfunc (srv *Projects) List(c context.Context, req *projects.ListRequest) (*projects.ListResponse, error) ", "output": "{\n\trsp := &projects.ListResponse{}\n\tif req.GetPageToken() != \"\" {\n\t\treturn rsp, nil\n\t}\n\tsrv.cfg.Range(func(_, val interface{}) bool {\n\t\trsp.Projects = append(rsp.Projects, val.(*projects.Config))\n\t\treturn true\n\t})\n\treturn rsp, nil\n}"} {"input": "package repl\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\n\t\"github.com/ttacon/chalk\"\n\n\t\"github.com/hussar-lang/hussar/evaluator\"\n\t\"github.com/hussar-lang/hussar/lexer\"\n\t\"github.com/hussar-lang/hussar/object\"\n\t\"github.com/hussar-lang/hussar/parser\"\n)\n\nconst PROMPT = \">> \"\n\n\n\nfunc printParserErrors(out io.Writer, errors []string) {\n\terrColor := chalk.Red.NewStyle().WithTextStyle(chalk.Bold).Style\n\n\tio.WriteString(out, errColor(\"PARSER ERROR!\\n\"))\n\tfor _, msg := range errors {\n\t\tio.WriteString(out, errColor(\" [!] \")+msg+\"\\n\")\n\t}\n}\n\nfunc Start(in io.Reader, out io.Writer) ", "output": "{\n\tscanner := bufio.NewScanner(in)\n\tenv := object.NewEnvironment()\n\tpromptColor := chalk.Cyan.NewStyle().WithTextStyle(chalk.Bold).Style\n\n\tfor {\n\t\tio.WriteString(out, promptColor(PROMPT))\n\t\tscanned := scanner.Scan()\n\t\tif !scanned {\n\t\t\treturn\n\t\t}\n\t\tline := scanner.Text()\n\t\tl := lexer.New(line)\n\t\tp := parser.New(l)\n\n\t\tprogram := p.ParseProgram()\n\t\tif len(p.Errors()) != 0 {\n\t\t\tprintParserErrors(out, p.Errors())\n\t\t\tcontinue\n\t\t}\n\n\t\tevaluated := evaluator.Eval(program, env)\n\t\tif evaluated != nil {\n\t\t\tio.WriteString(out, evaluated.Inspect())\n\t\t\tio.WriteString(out, \"\\n\")\n\t\t}\n\t}\n}"} {"input": "package esme\n\nimport (\n\t\"github.com/sacloud/libsacloud/v2/helper/validate\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\ntype ReadRequest struct {\n\tID types.ID `request:\"-\" validate:\"required\"`\n}\n\n\n\nfunc (req *ReadRequest) Validate() error ", "output": "{\n\treturn validate.Struct(req)\n}"} {"input": "package main\n\nimport \"github.com/matttproud/go-quake/cvar\"\n\nvar sysTicRate *cvar.Float\n\n\n\nfunc init() ", "output": "{\n\tcvars.NewFloat(\"host_framerate\", 0)\n\tcvars.NewFloat(\"host_speeds\", 0)\n\n\tsysTicRate, _ = cvars.NewFloat(\"sys_ticrate\", 0.05)\n\tcvars.NewFloat(\"serverprofile\", 0)\n\n\tcvars.NewFloat(\"fraglimit\", 0, cvar.ServerSide)\n\tcvars.NewFloat(\"timelimit\", 0, cvar.ServerSide)\n\tcvars.NewFloat(\"teamplay\", 0, cvar.ServerSide)\n\n\tcvars.NewFloat(\"samelevel\", 0)\n\tcvars.NewFloat(\"noexit\", 0, cvar.ServerSide)\n\n\tcvars.NewFloat(\"developer\", 0)\n\n\tcvars.NewFloat(\"skill\", 1)\n\tcvars.NewFloat(\"deathmatch\", 0)\n\tcvars.NewFloat(\"coop\", 0)\n\n\tcvars.NewFloat(\"pausable\", 1)\n\n\tcvars.NewFloat(\"temp1\", 0)\n}"} {"input": "package dissembler\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\n\tlog \"github.com/uber-go/zap\"\n)\n\nconst (\n\tSIGINT = syscall.SIGINT\n\tSIGHUP = syscall.SIGHUP\n\tSIGQUIT = syscall.SIGQUIT\n\tSIGTERM = syscall.SIGTERM\n\tSIGUSR1 = syscall.SIGUSR1\n\tSIGUSR2 = syscall.SIGUSR2\n)\n\nvar (\n\tRegistered Lifecycle\n\tDissemblerLogger log.Logger\n)\n\n\ntype Lifecycle interface {\n\tInit() error\n\tStart() error\n\tStop() error\n}\n\n\n\n\n\n\ntype Reloader interface {\n\tReload() error\n}\n\n\ntype Dissembler struct {\n\tlifecycle Lifecycle\n}\n\nfunc init() {\n\tDissemblerLogger = log.New(\n\t\tlog.NewJSONEncoder(\n\t\t\tlog.RFC3339Formatter(\"timestamp\"),\n\t\t\tlog.MessageKey(\"message\"),\n\t\t\tlog.LevelString(\"level\"),\n\t\t),\n\t\tlog.Fields(\n\t\t\tlog.String(\"dissembler_version\", Version),\n\t\t),\n\t)\n}\n\n\n\n\n\n\n\n\nfunc Serve(lc Lifecycle) error {\n\tdissembler := &Dissembler{lifecycle: lc}\n\treturn dissembler.Serve()\n}\n\n\nfunc (d *Dissembler) Serve() error {\n\terr := d.lifecycle.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\n\tgo func() error {\n\t\terr = d.lifecycle.Start()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}()\n\n\tif _, err := d.Wait(); nil != err {\n\t\tDissemblerLogger.Error(\"Unable to finish waiting for Dissembler to shutdown\",\n\t\t\tlog.String(\"error\", err.Error()),\n\t\t)\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc (d *Dissembler) Wait() (syscall.Signal, error) ", "output": "{\n\tch := make(chan os.Signal, 2)\n\tsignal.Notify(\n\t\tch,\n\t\tsyscall.SIGHUP,\n\t\tsyscall.SIGINT,\n\t\tsyscall.SIGQUIT,\n\t\tsyscall.SIGTERM,\n\t\tsyscall.SIGUSR1,\n\t\tsyscall.SIGUSR2,\n\t)\n\tfor {\n\t\tsig := <-ch\n\t\tDissemblerLogger.Info(\"signal caught\",\n\t\t\tlog.String(\"signal\", sig.String()))\n\t\tswitch sig {\n\n\n\t\tcase syscall.SIGINT:\n\t\t\td.lifecycle.Stop()\n\t\t\treturn syscall.SIGINT, nil\n\n\t\tcase syscall.SIGQUIT:\n\t\t\td.lifecycle.Stop()\n\t\t\treturn syscall.SIGQUIT, nil\n\n\t\tcase syscall.SIGTERM:\n\t\t\td.lifecycle.Stop()\n\t\t\treturn syscall.SIGTERM, nil\n\n\t\t}\n\t}\n}"} {"input": "package commons\n\nimport \"net/http\"\n\nfunc HttpNoContent(w http.ResponseWriter) {\n\tHttpError(w, http.StatusNoContent)\n}\n\n\n\nfunc HttpBadRequest(w http.ResponseWriter) {\n\tHttpError(w, http.StatusBadRequest)\n}\n\nfunc HttpError(w http.ResponseWriter, code int) {\n\thttp.Error(w, http.StatusText(code), code)\n}\n\nfunc HttpCheckError(err error, status int, w http.ResponseWriter) {\n\tif err != nil {\n\t\tHttpError(w, status)\n\t}\n}\n\nfunc HttpUnauthorized(w http.ResponseWriter) ", "output": "{\n\tHttpError(w, http.StatusUnauthorized)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"html/template\"\n\t\"net/http\"\n)\n\ntype Route struct {\n\tname string\n\tpath string\n\tfuncHandler gin.HandlerFunc\n}\n\ntype Link struct {\n\tpath string\n\tcaption string\n\thtml string\n}\n\ntype Page struct {\n\tCaption string\n\tBody string\n\tTmpl string\n}\n\nvar links = [...]Link{Link{caption: \"Home\", path: \"/\"},\n\tLink{caption: \"Sources\", path: \"/sources\"}}\n\nvar routes []Route\n\nvar webApp *gin.Engine\nvar indexTempl *template.Template\nvar sourceTempl *template.Template\nvar templates map[string]*template.Template\n\nfunc main() {\n\tconfigureServer()\n\tstartServer()\n}\n\nfunc startServer() {\n\twebApp.Run(\":3000\")\n}\n\n\n\nfunc configureServer() {\n\ttemplates = nil\n\twebApp = gin.Default()\n\twebApp.LoadHTMLGlob(\"templates/*.tmpl\")\n\tinitRoutes()\n\tfor _, curRoute := range routes {\n\t\twebApp.GET(curRoute.path, curRoute.funcHandler)\n\t}\n}\n\nfunc homeHandler(c *gin.Context) {\n\tc.HTML(http.StatusOK, \"home\", gin.H{})\n}\n\nfunc initRoutes() ", "output": "{\n\troutes = make([]Route, 2)\n\trouteHome := Route{name: \"home\", path: \"/\", funcHandler: homeHandler}\n\trouteSoures := Route{name: \"source\", path: \"/sources\", funcHandler: sourcesHandler}\n\troutes[0] = routeHome\n\troutes[1] = routeSoures\n}"} {"input": "package strings\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\nfunc FormatTime(t time.Time) string {\n\treturn fmt.Sprintf(\"%d.%d %d %02d:%02d:%02d\", t.Day(), t.Month(), t.Year(),\n\t\tt.Hour(), t.Minute(), t.Second())\n}\n\n\n\n\nfunc FormatTimeShort(t time.Time) string ", "output": "{\n\treturn fmt.Sprintf(\"%d.%d %d %d:%02d\", t.Day(), t.Month(), t.Year(),\n\t\tt.Hour(), t.Minute())\n}"} {"input": "package helper\n\nimport (\n\t\"bufio\"\n\t\"net\"\n)\n\ntype BufConn struct {\n\tnet.Conn\n\tBR *bufio.Reader\n}\n\nfunc (c *BufConn) Peek(n int) ([]byte, error) {\n\treturn c.BR.Peek(n)\n}\n\nfunc (c *BufConn) Read(b []byte) (n int, err error) {\n\treturn c.BR.Read(b)\n}\n\nfunc (c *BufConn) Write(b []byte) (n int, err error) {\n\treturn c.Conn.Write(b)\n}\n\nfunc (c *BufConn) Reset(conn net.Conn) {\n\tc.Conn = conn\n}\n\n\n\nfunc NewBufConn(c net.Conn, r *bufio.Reader) *BufConn ", "output": "{\n\tconn := &BufConn{Conn: c}\n\tconn.BR = r\n\tif nil == r {\n\t\tconn.BR = bufio.NewReader(c)\n\t}\n\treturn conn\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\n\n\nfunc Test_makeLogger_CopiesResponseHeaders(t *testing.T) ", "output": "{\n\thandler := http.HandlerFunc(makeLogger(http.HandlerFunc(\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"X-Unit-Test\", \"true\")\n\t\t})))\n\n\ts := httptest.NewServer(handler)\n\tdefer s.Close()\n\n\treq := httptest.NewRequest(http.MethodGet, s.URL, nil)\n\trr := httptest.NewRecorder()\n\n\thandler.ServeHTTP(rr, req)\n\n\tgot := rr.Header().Get(\"X-Unit-Test\")\n\twant := \"true\"\n\tif want != got {\n\t\tt.Errorf(\"Header X-Unit-Test, want: %s, got %s\", want, got)\n\t}\n\n}"} {"input": "package zip_test\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/klauspost/compress/flate\"\n\t\"github.com/klauspost/compress/zip\"\n)\n\nfunc ExampleWriter() {\n\tbuf := new(bytes.Buffer)\n\n\tw := zip.NewWriter(buf)\n\n\tvar files = []struct {\n\t\tName, Body string\n\t}{\n\t\t{\"readme.txt\", \"This archive contains some text files.\"},\n\t\t{\"gopher.txt\", \"Gopher names:\\nGeorge\\nGeoffrey\\nGonzo\"},\n\t\t{\"todo.txt\", \"Get animal handling licence.\\nWrite more examples.\"},\n\t}\n\tfor _, file := range files {\n\t\tf, err := w.Create(file.Name)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t_, err = f.Write([]byte(file.Body))\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\terr := w.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\n\nfunc ExampleWriter_RegisterCompressor() {\n\n\tbuf := new(bytes.Buffer)\n\n\tw := zip.NewWriter(buf)\n\n\tvar fw *flate.Writer\n\n\tw.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {\n\t\tvar err error\n\t\tif fw == nil {\n\t\t\tfw, err = flate.NewWriter(out, flate.BestCompression)\n\t\t} else {\n\t\t\tfw.Reset(out)\n\t\t}\n\t\treturn fw, err\n\t})\n\n}\n\nfunc ExampleReader() ", "output": "{\n\tr, err := zip.OpenReader(\"testdata/readme.zip\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer r.Close()\n\n\tfor _, f := range r.File {\n\t\tfmt.Printf(\"Contents of %s:\\n\", f.Name)\n\t\trc, err := f.Open()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t_, err = io.CopyN(os.Stdout, rc, 68)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\trc.Close()\n\t\tfmt.Println()\n\t}\n}"} {"input": "package category\n\nimport (\n\t\"strings\"\n\t\"unicode\"\n)\n\n\n\n\n\n\n\nfunc HashtagFromTitle(title string) string {\n\tvar t strings.Builder\n\tvar prev rune\n\tfor _, c := range title {\n\t\tif !unicode.IsLetter(c) && !unicode.IsNumber(c) {\n\t\t\tprev = c\n\t\t\tcontinue\n\t\t}\n\t\tif unicode.IsSpace(prev) {\n\t\t\tt.WriteRune(unicode.ToUpper(c))\n\t\t} else {\n\t\t\tt.WriteRune(c)\n\t\t}\n\t\tprev = c\n\t}\n\treturn t.String()\n}\n\nfunc titleFromHashtag(hashtag string) string ", "output": "{\n\tvar t strings.Builder\n\tvar prev rune\n\tfor i, c := range hashtag {\n\t\tif unicode.IsUpper(c) {\n\t\t\tif i > 0 && !unicode.IsUpper(prev) {\n\t\t\t\tt.WriteRune(' ')\n\t\t\t}\n\t\t\tt.WriteRune(unicode.ToLower(c))\n\t\t} else {\n\t\t\tt.WriteRune(c)\n\t\t}\n\t\tprev = c\n\t}\n\treturn t.String()\n}"} {"input": "package figure\n\nimport (\n \"fmt\"\n \"log\"\n \"net/http\"\n \"strconv\"\n \"strings\"\n)\n\nconst signature = \"flf2\"\nconst reverseFlag = \"1\"\nvar charDelimiters = [3]string{\"@\", \"#\", \"$\"}\nvar hardblanksBlacklist = [2]byte{'a', '2'}\n\nfunc getFile(name string) (file http.File) {\n filePath := fmt.Sprintf(\"%s.flf\", name)\n file, err := AssetFS().Open(filePath)\n if err != nil {\n log.Fatalf(\"invalid font name:%s.\",err)\n }\n return file\n}\n\n\n\nfunc getBaseline(metadata string) int {\n datum := strings.Fields(metadata)[2]\n baseline, _ := strconv.Atoi(datum)\n return baseline\n}\n\nfunc getHardblank(metadata string) byte {\n datum := strings.Fields(metadata)[0]\n hardblank := datum[len(datum)-1]\n if hardblank == hardblanksBlacklist[0] || hardblank == hardblanksBlacklist[1] {\n return ' '\n } else {\n return hardblank\n }\n}\n\nfunc getReverse(metadata string) bool {\n data := strings.Fields(metadata)\n return len(data) > 6 && data[6] == reverseFlag\n}\n\nfunc lastCharLine(text string, height int) bool {\n endOfLine, length := \" \", 2\n if height == 1 && len(text) > 0 {\n length = 1\n }\n if len(text) >= length {\n endOfLine = text[len(text)-length:]\n }\n return endOfLine == strings.Repeat(charDelimiters[0], length) ||\n endOfLine == strings.Repeat(charDelimiters[1], length) ||\n endOfLine == strings.Repeat(charDelimiters[2], length)\n}\n\nfunc getHeight(metadata string) int ", "output": "{\n datum := strings.Fields(metadata)[1]\n height, _ := strconv.Atoi(datum)\n return height\n}"} {"input": "package domain\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n)\n\nconst (\n\tNameRegex = \"^[A-Za-z0-9]+$\"\n\tURLRegex = `^((ftp|http|https):\\/\\/)?(\\S+(:\\S*)?@)?((([1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(\\.(1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.([0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|((www\\.)?)?(([a-z\\x{00a1}-\\x{ffff}0-9]+-?-?_?)*[a-z\\x{00a1}-\\x{ffff}0-9]+)(?:\\.([a-z\\x{00a1}-\\x{ffff}]{2,}))?)|localhost)(:(\\d{1,5}))?((\\/|\\?|#)[^\\s]*)?$`\n\n\tNOT_FOUND_ERROR = \"not found\"\n\tMALFORMED_ERROR = \"malformed\"\n)\n\ntype NamesRepository interface {\n\tGet(name Name) (URL, error)\n\tPut(name Name, url URL) error\n\tDeleteAll() error\n}\n\nvar (\n\tnameRegex *regexp.Regexp\n\turlRegex *regexp.Regexp\n)\n\nfunc init() {\n\tnameRegex = regexp.MustCompile(NameRegex)\n\tnameRegex.Longest()\n\n\turlRegex = regexp.MustCompile(URLRegex)\n}\n\ntype Validator interface {\n\tValidate() error\n}\n\ntype Name string\n\nfunc (t Name) Validate() error {\n\n\tif len(t) == 0 {\n\t\treturn fmt.Errorf(\"malformed name\")\n\t}\n\n\tif !nameRegex.MatchString(string(t)) {\n\t\treturn fmt.Errorf(\"malformed name [%s]\", t)\n\t}\n\n\treturn nil\n}\n\ntype URL string\n\n\n\nfunc (t URL) Validate() error ", "output": "{\n\n\tif len(t) == 0 {\n\t\treturn fmt.Errorf(\"malformed url\")\n\t}\n\n\tif !urlRegex.MatchString(string(t)) {\n\t\treturn fmt.Errorf(\"malformed url [%s]\", t)\n\t}\n\treturn nil\n}"} {"input": "package data\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestNoteLimit(t *testing.T) {\n\tacc := AccountNew(\"mail@example.com\")\n\tuser, err := acc.Store()\n\n\tassert.Nil(t, err)\n\n\tnote := NoteNew(user.ID, \"This is a note! This is a note! This is a note! This is a note! This is a note! This is a note! This is a note!\")\n\n\tassert.False(t, note.IsStored())\n\tassert.Equal(t, user.ID, note.Account)\n\n\tnote, err = note.Store()\n\n\tassert.NotNil(t, err)\n\n\tuser.Remove()\n}\n\nfunc TestNoteList(t *testing.T) {\n\tacc := AccountNew(\"mail@example.com\")\n\tuser, err := acc.Store()\n\n\tassert.Nil(t, err)\n\n\tnote := NoteNew(user.ID, \"This is a note!\")\n\tnote, err = note.Store()\n\n\tassert.Nil(t, err)\n\n\tnote2 := NoteNew(user.ID, \"This is a second note!\")\n\tnote2, err = note2.Store()\n\n\tassert.Nil(t, err)\n\n\tlist, err := NoteListByAccount(user.ID)\n\n\tassert.Nil(t, err)\n\tassert.Equal(t, 2, len(list))\n\n\tuser.Remove()\n}\n\nfunc TestNote(t *testing.T) ", "output": "{\n\tacc := AccountNew(\"mail@example.com\")\n\tuser, err := acc.Store()\n\n\tassert.Nil(t, err)\n\n\tnote := NoteNew(user.ID, \"example content\")\n\n\tassert.False(t, note.IsStored())\n\tassert.Equal(t, \"example content\", note.Text)\n\tassert.Equal(t, user.ID, note.Account)\n\n\tnote, err = note.Store()\n\n\tif assert.Nil(t, err) {\n\t\tassert.True(t, note.IsStored())\n\t}\n\n\tuser.Remove()\n}"} {"input": "package pflag\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype boolValue bool\n\nfunc newBoolValue(val bool, p *bool) *boolValue {\n\t*p = val\n\treturn (*boolValue)(p)\n}\n\nfunc (b *boolValue) Set(s string) error {\n\tv, err := strconv.ParseBool(s)\n\t*b = boolValue(v)\n\treturn err\n}\n\n\n\n\n\nfunc (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc BoolVar(p *bool, name string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc (f *FlagSet) Bool(name string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, \"\", value, usage)\n\treturn p\n}\n\n\nfunc (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, shorthand, value, usage)\n\treturn p\n}\n\n\n\nfunc Bool(name string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, \"\", value, usage)\n}\n\n\nfunc BoolP(name, shorthand string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, shorthand, value, usage)\n}\n\nfunc (b *boolValue) String() string ", "output": "{ return fmt.Sprintf(\"%v\", *b) }"} {"input": "package fixtures\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/atlassian/gostatsd\"\n)\n\ntype MetricOpt func(m *gostatsd.Metric)\n\n\n\nfunc MakeMetric(opts ...MetricOpt) *gostatsd.Metric {\n\tm := &gostatsd.Metric{\n\t\tType: gostatsd.COUNTER,\n\t\tName: \"name\",\n\t\tRate: 1,\n\t\tTags: gostatsd.Tags{\n\t\t\t\"foo:bar\",\n\t\t\t\"host:baz\",\n\t\t},\n\t\tSource: \"baz\",\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}\n\nfunc Name(n string) MetricOpt {\n\treturn func(m *gostatsd.Metric) {\n\t\tm.Name = n\n\t}\n}\n\nfunc AddTag(t ...string) MetricOpt {\n\treturn func(m *gostatsd.Metric) {\n\t\tm.Tags = append(m.Tags, t...)\n\t}\n}\n\nfunc DropSource(m *gostatsd.Metric) {\n\tm.Source = gostatsd.UnknownSource\n}\n\nfunc DropTag(t string) MetricOpt {\n\treturn func(m *gostatsd.Metric) {\n\t\tnext := 0\n\t\tfound := false\n\t\tfor _, tag := range m.Tags {\n\t\t\tif t == tag {\n\t\t\t\tfound = true\n\t\t\t\tm.Tags[next] = tag\n\t\t\t\tnext++\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tpanic(fmt.Sprintf(\"failed to find tag %s while building metric\", t))\n\t\t}\n\t\tm.Tags = m.Tags[:next]\n\t}\n}\n\n\n\n\n\nfunc SortCompare(ms []*gostatsd.Metric) func(i, j int) bool ", "output": "{\n\treturn func(i, j int) bool {\n\t\tif ms[i].Name == ms[j].Name {\n\t\t\tif len(ms[i].Tags) == len(ms[j].Tags) { \n\t\t\t\tif ms[i].Type == gostatsd.SET {\n\t\t\t\t\treturn ms[i].StringValue < ms[j].StringValue\n\t\t\t\t} else {\n\t\t\t\t\treturn ms[i].Value < ms[j].Value\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn len(ms[i].Tags) < len(ms[j].Tags)\n\t\t}\n\t\treturn ms[i].Name < ms[j].Name\n\t}\n}"} {"input": "package gsh\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"gopkg.in/pipe.v2\"\n)\n\ntype HeadCmd struct {\n\tChars int\n\tLines int\n}\n\nfunc (cmd *HeadCmd) Flags() *flag.FlagSet {\n\tf := flag.NewFlagSet(cmd.Name(), flag.ExitOnError)\n\tf.IntVar(&cmd.Chars, \"c\", -1, \"Take first N characters\")\n\tf.IntVar(&cmd.Chars, \"n\", 10, \"Take first N lines\")\n\treturn f\n}\n\nfunc (cmd *HeadCmd) Name() string {\n\treturn \"head\"\n}\n\nfunc (cmd *HeadCmd) Run(s *pipe.State, argv []string) error {\n\tfs := cmd.Flags()\n\terr := fs.Parse(argv)\n\tif err != nil {\n\t\treturn err\n\t}\n\targs := fs.Args()\n\tif len(args) > 0 {\n\t\tfor _, fname := range args {\n\t\t\tfh, err := os.Open(fname)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%s 1: %s\", cmd.Name(), err)\n\t\t\t}\n\t\t\t_, err = io.Copy(s.Stdout, fh)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%s 2: %s\", cmd.Name(), err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\tif cmd.Chars >= 0 {\n\t\t_, err = io.CopyN(s.Stdout, s.Stdin, int64(cmd.Chars))\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: %s\", cmd.Name(), err)\n\t}\n\treturn nil\n}\n\n\n\nfunc Head(argv ...string) pipe.Pipe ", "output": "{\n\tcmd := HeadCmd{}\n\treturn pipe.TaskFunc(func(s *pipe.State) error {\n\t\treturn cmd.Run(s, argv)\n\t})\n}"} {"input": "package permute\n\nimport \"testing\"\n\nfunc BenchmarkPermGenLex(b *testing.B) {\n\tp := New(20)\n\tfor i := 0; i < b.N; i++ {\n\t\tLexNext(p)\n\t}\n}\n\nfunc BenchmarkPermGenSJT(b *testing.B) {\n\th := NewPlainChangeGen(20)\n\tvar sw [2]int\n\tfor i := 0; i < b.N; i++ {\n\t\th.Next(&sw)\n\t}\n}\n\n\nfunc BenchmarkPermGenEven(b *testing.B) {\n\th := NewPlainChangeFastGen(20)\n\tvar sw [2]int\n\tfor i := 0; i < b.N; i++ {\n\t\th.Next(&sw)\n\t}\n}\n\nfunc BenchmarkPermGenHeap(b *testing.B) ", "output": "{\n\th := NewHeap(20)\n\tvar sw [2]int\n\tfor i := 0; i < b.N; i++ {\n\t\th.Next(&sw)\n\t}\n}"} {"input": "package origins\n\n\n\ntype Buffer struct {\n\tbuf Facts\n\toff int\n}\n\n\n\n\n\n\nfunc (b *Buffer) Grow(n int) {\n\tb.grow(n)\n}\n\n\nfunc (b *Buffer) Len() int {\n\treturn len(b.buf) - b.off\n}\n\n\nfunc (b *Buffer) Write(f *Fact) error {\n\t_, err := b.Append(f)\n\treturn err\n}\n\n\nfunc (b *Buffer) Append(buf ...*Fact) (int, error) {\n\tm := b.grow(len(buf))\n\treturn copy(b.buf[m:], buf), nil\n}\n\n\nfunc (b *Buffer) Facts() Facts {\n\tn := b.Len()\n\n\tif n == 0 {\n\t\treturn Facts{}\n\t}\n\n\tc := make(Facts, n)\n\tcopy(c, b.buf[b.off:])\n\n\tb.Truncate(0)\n\treturn c\n}\n\n\nfunc (b *Buffer) Truncate(n int) {\n\tswitch {\n\tcase n < 0 || n > b.Len():\n\t\tpanic(\"origins.Buffer: truncation out of range\")\n\tcase n == 0:\n\t\tb.off = 0\n\t}\n\n\tb.buf = b.buf[0 : b.off+n]\n}\n\n\n\nfunc (b *Buffer) Reset() {\n\tb.Truncate(0)\n}\n\n\nfunc (b *Buffer) Next() *Fact {\n\tif b.off >= len(b.buf) {\n\t\tb.Truncate(0)\n\n\t\treturn nil\n\t}\n\n\tf := b.buf[b.off]\n\tb.off++\n\n\treturn f\n}\n\nfunc (b *Buffer) Err() error {\n\treturn nil\n}\n\n\nfunc NewBuffer(buf Facts) *Buffer {\n\treturn &Buffer{\n\t\tbuf: buf,\n\t}\n}\n\nfunc (b *Buffer) grow(n int) int ", "output": "{\n\tm := b.Len()\n\n\tif m == 0 && b.off != 0 {\n\t\tb.Truncate(0)\n\t}\n\n\tif len(b.buf)+n > cap(b.buf) {\n\t\tvar buf Facts\n\n\t\tif m+n <= cap(b.buf)/2 {\n\t\t\tcopy(b.buf[:], b.buf[b.off:])\n\t\t\tbuf = b.buf[:m]\n\t\t} else {\n\t\t\tbuf = make(Facts, 2*cap(b.buf)+n)\n\t\t\tcopy(buf, b.buf[b.off:])\n\t\t}\n\n\t\tb.buf = buf\n\t\tb.off = 0\n\t}\n\n\tb.buf = b.buf[0 : b.off+m+n]\n\treturn b.off + m\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\n\n\n\n\n\n\n\n\ntype Tags map[string]string\n\n\n\n\nfunc (m Tags) Validate(formats strfmt.Registry) error ", "output": "{\n\treturn nil\n}"} {"input": "package response\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\nvar realm = \"example_api\"\n\n\nfunc WriteJSON(w http.ResponseWriter, v interface{}, code int) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(code)\n\tjson.NewEncoder(w).Encode(v)\n}\n\n\nfunc NoContent(w http.ResponseWriter) {\n\tw.WriteHeader(http.StatusNoContent)\n}\n\n\n\nfunc Error(w http.ResponseWriter, err string, code int) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(code)\n\tjson.NewEncoder(w).Encode(map[string]string{\"error\": err})\n}\n\n\n\n\n\nfunc UnauthorizedError(w http.ResponseWriter, err string) ", "output": "{\n\tw.Header().Set(\"WWW-Authenticate\", fmt.Sprintf(\"Bearer realm=%s\", realm))\n\tError(w, err, http.StatusUnauthorized)\n}"} {"input": "package compute\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/genevieve/leftovers/common\"\n\tgcpcompute \"google.golang.org/api/compute/v1\"\n)\n\ntype disksClient interface {\n\tListDisks(zone string) ([]*gcpcompute.Disk, error)\n\tDeleteDisk(zone, disk string) error\n}\n\ntype Disks struct {\n\tclient disksClient\n\tlogger logger\n\tzones map[string]string\n}\n\nfunc NewDisks(client disksClient, logger logger, zones map[string]string) Disks {\n\treturn Disks{\n\t\tclient: client,\n\t\tlogger: logger,\n\t\tzones: zones,\n\t}\n}\n\n\n\nfunc (d Disks) Type() string {\n\treturn \"disk\"\n}\n\nfunc (d Disks) List(filter string) ([]common.Deletable, error) ", "output": "{\n\tdisks := []*gcpcompute.Disk{}\n\tfor _, zone := range d.zones {\n\t\tl, err := d.client.ListDisks(zone)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"List Disks for zone %s: %s\", zone, err)\n\t\t}\n\n\t\tdisks = append(disks, l...)\n\t}\n\n\tvar resources []common.Deletable\n\tfor _, disk := range disks {\n\t\tresource := NewDisk(d.client, disk.Name, d.zones[disk.Zone])\n\n\t\tif !strings.Contains(resource.Name(), filter) {\n\t\t\tcontinue\n\t\t}\n\n\t\tproceed := d.logger.PromptWithDetails(resource.Type(), resource.Name())\n\t\tif !proceed {\n\t\t\tcontinue\n\t\t}\n\n\t\tresources = append(resources, resource)\n\t}\n\n\treturn resources, nil\n}"} {"input": "package arn\n\n\ntype PersonName struct {\n\tEnglish Name `json:\"english\" editable:\"true\"`\n\tJapanese Name `json:\"japanese\" editable:\"true\"`\n}\n\n\nfunc (name *PersonName) String() string {\n\treturn name.ByUser(nil)\n}\n\n\n\n\nfunc (name *PersonName) ByUser(user *User) string ", "output": "{\n\tif user == nil {\n\t\treturn name.English.String()\n\t}\n\n\tswitch user.Settings().TitleLanguage {\n\tcase \"japanese\":\n\t\tif name.Japanese.String() == \"\" {\n\t\t\treturn name.English.String()\n\t\t}\n\n\t\treturn name.Japanese.String()\n\n\tdefault:\n\t\treturn name.English.String()\n\t}\n}"} {"input": "package mount\n\n\n\n\n\n\nfunc Mounted(mountpoint string) (bool, error) {\n\tentries, err := parseMountTable()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, e := range entries {\n\t\tif e.Mountpoint == mountpoint {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}\n\n\n\n\n\nfunc Mount(device, target, mType, options string) error {\n\tflag, _ := parseOptions(options)\n\tif flag&REMOUNT != REMOUNT {\n\t\tif mounted, err := Mounted(target); err != nil || mounted {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn ForceMount(device, target, mType, options)\n}\n\n\n\n\n\nfunc ForceMount(device, target, mType, options string) error {\n\tflag, data := parseOptions(options)\n\treturn mount(device, target, mType, uintptr(flag), data)\n}\n\n\n\nfunc Unmount(target string) error {\n\tif mounted, err := Mounted(target); err != nil || !mounted {\n\t\treturn err\n\t}\n\treturn unmount(target, mntDetach)\n}\n\nfunc GetMounts() ([]*Info, error) ", "output": "{\n\treturn parseMountTable()\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSDynamoDBTable_TimeToLiveSpecification struct {\n\n\tAttributeName string `json:\"AttributeName,omitempty\"`\n\n\tEnabled bool `json:\"Enabled\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) AWSCloudFormationType() string {\n\treturn \"AWS::DynamoDB::Table.TimeToLiveSpecification\"\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetDeletionPolicy(policy policies.DeletionPolicy) ", "output": "{\n\tr._deletionPolicy = policy\n}"} {"input": "package controller\n\nimport (\n\t\"fmt\"\n)\n\ntype AdminParams struct {\n\tName *string\n\tInviteId *string\n\tInviteKey *string\n\tConfirmDelete *string\n}\n\n\n\nfunc (params *AdminParams) ValidateName(required bool) error {\n\tif required && *params.Name == \"\" {\n\t\treturn fmt.Errorf(\"name cannot be empty\")\n\t}\n\treturn nil\n}\n\nfunc (params *AdminParams) ValidateInviteId(required bool) error { return nil }\nfunc (params *AdminParams) ValidateInviteKey(required bool) error { return nil }\n\nfunc NewAdminParams() *AdminParams ", "output": "{\n\treturn new(AdminParams)\n}"} {"input": "package bitbucket\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/javiermanzano/goth\"\n)\n\n\ntype Session struct {\n\tAuthURL string\n\tAccessToken string\n\tRefreshToken string\n\tExpiresAt time.Time\n}\n\n\n\n\n\nfunc (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {\n\tp := provider.(*Provider)\n\ttoken, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get(\"code\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !token.Valid() {\n\t\treturn \"\", errors.New(\"Invalid token received from provider\")\n\t}\n\n\ts.AccessToken = token.AccessToken\n\ts.RefreshToken = token.RefreshToken\n\ts.ExpiresAt = token.Expiry\n\treturn token.AccessToken, err\n}\n\n\nfunc (s Session) Marshal() string {\n\tb, _ := json.Marshal(s)\n\treturn string(b)\n}\n\n\nfunc (p *Provider) UnmarshalSession(data string) (goth.Session, error) {\n\tsess := &Session{}\n\terr := json.NewDecoder(strings.NewReader(data)).Decode(sess)\n\treturn sess, err\n}\n\nfunc (s Session) String() string {\n\treturn s.Marshal()\n}\n\nfunc (s Session) GetAuthURL() (string, error) ", "output": "{\n\tif s.AuthURL == \"\" {\n\t\treturn \"\", errors.New(goth.NoAuthUrlErrorMessage)\n\t}\n\treturn s.AuthURL, nil\n}"} {"input": "package nodes\n\nimport (\n\t\"github.com/gonum/graph\"\n\n\tosgraph \"github.com/openshift/origin/pkg/api/graph\"\n\tkubegraph \"github.com/openshift/origin/pkg/api/kubegraph/nodes\"\n\tdepoyapi \"github.com/openshift/origin/pkg/deploy/api\"\n)\n\n\n\n\nfunc EnsureDeploymentConfigNode(g osgraph.MutableUniqueGraph, dc *depoyapi.DeploymentConfig) *DeploymentConfigNode ", "output": "{\n\tdcName := DeploymentConfigNodeName(dc)\n\tdcNode := osgraph.EnsureUnique(\n\t\tg,\n\t\tdcName,\n\t\tfunc(node osgraph.Node) graph.Node {\n\t\t\treturn &DeploymentConfigNode{Node: node, DeploymentConfig: dc}\n\t\t},\n\t).(*DeploymentConfigNode)\n\n\tif dc.Spec.Template != nil {\n\t\tpodTemplateSpecNode := kubegraph.EnsurePodTemplateSpecNode(g, dc.Spec.Template, dcName)\n\t\tg.AddEdge(dcNode, podTemplateSpecNode, osgraph.ContainsEdgeKind)\n\t}\n\n\treturn dcNode\n}"} {"input": "package aes\n\nimport (\n\t\"crypto/cipher\"\n)\n\ntype code int\n\n\nconst (\n\taes128 code = 18\n\taes192 = 19\n\taes256 = 20\n)\n\ntype aesCipherAsm struct {\n\tfunction code \n\tkey []byte \n\tstorage [256]byte \n}\n\n\n\n\nfunc hasAsm() bool\n\n\n\n\n\nfunc cryptBlocks(c code, key, dst, src *byte, length int)\n\nvar useAsm = hasAsm()\n\nfunc newCipher(key []byte) (cipher.Block, error) {\n\tif !useAsm {\n\t\treturn newCipherGeneric(key)\n\t}\n\n\tvar function code\n\tswitch len(key) {\n\tcase 128 / 8:\n\t\tfunction = aes128\n\tcase 192 / 8:\n\t\tfunction = aes192\n\tcase 256 / 8:\n\t\tfunction = aes256\n\tdefault:\n\t\treturn nil, KeySizeError(len(key))\n\t}\n\n\tvar c aesCipherAsm\n\tc.function = function\n\tc.key = c.storage[:len(key)]\n\tcopy(c.key, key)\n\treturn &c, nil\n}\n\nfunc (c *aesCipherAsm) BlockSize() int { return BlockSize }\n\nfunc (c *aesCipherAsm) Encrypt(dst, src []byte) {\n\tif len(src) < BlockSize {\n\t\tpanic(\"crypto/aes: input not full block\")\n\t}\n\tif len(dst) < BlockSize {\n\t\tpanic(\"crypto/aes: output not full block\")\n\t}\n\tcryptBlocks(c.function, &c.key[0], &dst[0], &src[0], BlockSize)\n}\n\n\n\n\n\nfunc expandKey(key []byte, enc, dec []uint32) {\n\texpandKeyGo(key, enc, dec)\n}\n\nfunc (c *aesCipherAsm) Decrypt(dst, src []byte) ", "output": "{\n\tif len(src) < BlockSize {\n\t\tpanic(\"crypto/aes: input not full block\")\n\t}\n\tif len(dst) < BlockSize {\n\t\tpanic(\"crypto/aes: output not full block\")\n\t}\n\tcryptBlocks(c.function+128, &c.key[0], &dst[0], &src[0], BlockSize)\n}"} {"input": "package dev\n\nimport \"fmt\"\n\n\n\ntype Configuration struct {\n\tid uint32\n\tnodes []*Node\n\tn int\n\tmgr *Manager\n\tqspec QuorumSpec\n\terrs chan CallGRPCError\n}\n\n\n\nfunc (c *Configuration) SubError() <-chan CallGRPCError {\n\treturn c.errs\n}\n\n\nfunc (c *Configuration) ID() uint32 {\n\treturn c.id\n}\n\n\n\n\nfunc (c *Configuration) NodeIDs() []uint32 {\n\tids := make([]uint32, len(c.nodes))\n\tfor i, node := range c.nodes {\n\t\tids[i] = node.ID()\n\t}\n\treturn ids\n}\n\n\n\nfunc (c *Configuration) Nodes() []*Node {\n\treturn c.nodes\n}\n\n\nfunc (c *Configuration) Size() int {\n\treturn c.n\n}\n\nfunc (c *Configuration) String() string {\n\treturn fmt.Sprintf(\"configuration %d\", c.id)\n}\n\nfunc (c *Configuration) tstring() string {\n\treturn fmt.Sprintf(\"config-%d\", c.id)\n}\n\n\n\n\n\n\n\n\nfunc NewTestConfiguration(q, n int) *Configuration {\n\treturn &Configuration{\n\t\tnodes: make([]*Node, n),\n\t}\n}\n\nfunc Equal(a, b *Configuration) bool ", "output": "{ return a.id == b.id }"} {"input": "package library\n\nimport (\n\t\"container/heap\"\n\t\"github.com/nytlabs/streamtools/st/blocks\" \n\t\"time\"\n)\n\n\ntype Queue struct {\n\tblocks.Block\n\tqueryPop chan chan interface{}\n\tqueryPeek chan chan interface{}\n\tinPush chan interface{}\n\tinPop chan interface{}\n\tout chan interface{}\n\tquit chan interface{}\n}\n\n\n\n\n\nfunc (b *Queue) Setup() {\n\tb.Kind = \"Queue\"\n\tb.inPush = b.InRoute(\"push\")\n\tb.inPop = b.InRoute(\"pop\")\n\tb.queryPop = b.QueryRoute(\"pop\")\n\tb.queryPeek = b.QueryRoute(\"peek\")\n\tb.quit = b.Quit()\n\tb.out = b.Broadcast()\n}\n\n\nfunc (b *Queue) Run() {\n\tpq := &PriorityQueue{}\n\theap.Init(pq)\n\tfor {\n\t\tselect {\n\t\tcase <-b.quit:\n\t\t\treturn\n\t\tcase msg := <-b.inPush:\n\t\t\tqueueMessage := &PQMessage{\n\t\t\t\tval: msg,\n\t\t\t\tt: time.Now(),\n\t\t\t}\n\t\t\theap.Push(pq, queueMessage)\n\t\tcase <-b.inPop:\n\t\t\tif len(*pq) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmsg := heap.Pop(pq).(*PQMessage).val\n\t\t\tb.out <- msg\n\t\tcase respChan := <-b.queryPop:\n\t\t\tvar msg interface{}\n\t\t\tif len(*pq) > 0 {\n\t\t\t\tmsg = heap.Pop(pq).(*PQMessage).val\n\t\t\t}\n\t\t\trespChan <- msg\n\t\tcase respChan := <-b.queryPeek:\n\t\t\tvar msg interface{}\n\t\t\tif len(*pq) > 0 {\n\t\t\t\tmsg = pq.Peek().(*PQMessage).val\n\t\t\t}\n\t\t\trespChan <- msg\n\t\t}\n\t}\n}\n\nfunc NewQueue() blocks.BlockInterface ", "output": "{\n\treturn &Queue{}\n}"} {"input": "package errors\n\nimport (\n\t\"sync\"\n)\n\n\n\n\n\n\n\n\n\ntype LazyMultiError interface {\n\tAssign(int, error) bool\n\n\tGetOne(int) error\n\n\tGet() error\n}\n\ntype lazyMultiError struct {\n\tsync.Mutex\n\n\tsize int\n\tme MultiError\n}\n\n\n\n\nfunc (e *lazyMultiError) Assign(i int, err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\te.Lock()\n\tdefer e.Unlock()\n\tif e.me == nil {\n\t\te.me = make(MultiError, e.size)\n\t}\n\te.me[i] = err\n\treturn true\n}\n\nfunc (e *lazyMultiError) GetOne(i int) error {\n\te.Lock()\n\tdefer e.Unlock()\n\tif e.me == nil {\n\t\treturn nil\n\t}\n\treturn e.me[i]\n}\n\nfunc (e *lazyMultiError) Get() error {\n\te.Lock()\n\tdefer e.Unlock()\n\tif e.me == nil {\n\t\treturn nil\n\t}\n\treturn e.me\n}\n\nfunc NewLazyMultiError(size int) LazyMultiError ", "output": "{\n\treturn &lazyMultiError{size: size}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Abser interface {\n\tAbs() float64\n}\n\nfunc main() {\n\tvar a Abser\n\tf := MyFloat(-math.Sqrt2)\n\tv := Vertex{3, 4}\n\n\ta = f \n\ta = &v \n\n\ta = v\n\n\tfmt.Println(a.Abs())\n}\n\ntype MyFloat float64\n\n\n\ntype Vertex struct {\n\tX, Y float64\n}\n\nfunc (v *Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}\n\nfunc (f MyFloat) Abs() float64 ", "output": "{\n\tif f < 0 {\n\t\treturn float64(-f)\n\t}\n\treturn float64(f)\n}"} {"input": "package packets\n\nimport (\n\t\"io\"\n)\n\ntype PubackMessage struct {\n\tHeader\n\tTopicId uint16\n\tMessageId uint16\n\tReturnCode byte\n}\n\n\n\nfunc (p *PubackMessage) Write(w io.Writer) error {\n\tpacket := p.Header.pack()\n\tpacket.WriteByte(PUBACK)\n\tpacket.Write(encodeUint16(p.TopicId))\n\tpacket.Write(encodeUint16(p.MessageId))\n\tpacket.WriteByte(p.ReturnCode)\n\t_, err := packet.WriteTo(w)\n\n\treturn err\n}\n\nfunc (p *PubackMessage) Unpack(b io.Reader) {\n\tp.TopicId = readUint16(b)\n\tp.MessageId = readUint16(b)\n\tp.ReturnCode = readByte(b)\n}\n\nfunc (p *PubackMessage) MessageType() byte ", "output": "{\n\treturn PUBACK\n}"} {"input": "package network\n\nimport (\n\t\"github.com/containerd/containerd/oci\"\n\tspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n)\n\nfunc NewHostProvider() Provider {\n\treturn &host{}\n}\n\ntype host struct {\n}\n\nfunc (h *host) New() (Namespace, error) {\n\treturn &hostNS{}, nil\n}\n\ntype hostNS struct {\n}\n\n\n\nfunc (h *hostNS) Close() error {\n\treturn nil\n}\n\nfunc (h *hostNS) Set(s *specs.Spec) error ", "output": "{\n\treturn oci.WithHostNamespace(specs.NetworkNamespace)(nil, nil, nil, s)\n}"} {"input": "package google\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/acctest\"\n\t\"github.com/hashicorp/terraform/helper/resource\"\n)\n\n\n\n\n\nfunc TestAccGoogleSqlDatabaseInstance_importBasic3(t *testing.T) {\n\tt.Parallel()\n\n\tresourceName := \"google_sql_database_instance.instance\"\n\tdatabaseID := acctest.RandInt()\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testAccGoogleSqlDatabaseInstanceDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: fmt.Sprintf(\n\t\t\t\t\ttestGoogleSqlDatabaseInstance_basic3, databaseID),\n\t\t\t},\n\n\t\t\tresource.TestStep{\n\t\t\t\tResourceName: resourceName,\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccGoogleSqlDatabaseInstance_importBasic(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\tresourceName := \"google_sql_database_instance.instance\"\n\tdatabaseID := acctest.RandInt()\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testAccGoogleSqlDatabaseInstanceDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: fmt.Sprintf(\n\t\t\t\t\ttestGoogleSqlDatabaseInstance_basic, databaseID),\n\t\t\t},\n\n\t\t\tresource.TestStep{\n\t\t\t\tResourceName: resourceName,\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}"} {"input": "package memory\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"github.com/google/trillian/monitoring\"\n\t\"github.com/google/trillian/storage\"\n)\n\nfunc init() {\n\tif err := storage.RegisterProvider(\"memory\", newMemoryStorageProvider); err != nil {\n\t\tglog.Fatalf(\"Failed to register storage provider memory: %v\", err)\n\t}\n}\n\ntype memProvider struct {\n\tmf monitoring.MetricFactory\n\tts *TreeStorage\n}\n\nfunc newMemoryStorageProvider(mf monitoring.MetricFactory) (storage.Provider, error) {\n\treturn &memProvider{\n\t\tmf: mf,\n\t\tts: NewTreeStorage(),\n\t}, nil\n}\n\nfunc (s *memProvider) LogStorage() storage.LogStorage {\n\treturn NewLogStorage(s.ts, s.mf)\n}\n\n\n\nfunc (s *memProvider) AdminStorage() storage.AdminStorage {\n\treturn NewAdminStorage(s.ts)\n}\n\nfunc (s *memProvider) Close() error {\n\treturn nil\n}\n\nfunc (s *memProvider) MapStorage() storage.MapStorage ", "output": "{\n\treturn nil\n}"} {"input": "package nwo\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n)\n\ntype Command interface {\n\tArgs() []string\n\tSessionName() string\n}\n\ntype Enver interface {\n\tEnv() []string\n}\n\ntype WorkingDirer interface {\n\tWorkingDir() string\n}\n\n\n\nfunc ClientAuthEnabled(c Command) bool {\n\tfor _, arg := range c.Args() {\n\t\tif arg == \"--clientauth\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc NewCommand(path string, command Command) *exec.Cmd {\n\tcmd := exec.Command(path, command.Args()...)\n\tcmd.Env = os.Environ()\n\tif ce, ok := command.(Enver); ok {\n\t\tcmd.Env = append(cmd.Env, ce.Env()...)\n\t}\n\tif wd, ok := command.(WorkingDirer); ok {\n\t\tcmd.Dir = wd.WorkingDir()\n\t}\n\treturn cmd\n}\n\nfunc ConnectsToOrderer(c Command) bool ", "output": "{\n\tfor _, arg := range c.Args() {\n\t\tif arg == \"--orderer\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package secret\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/mailgun/vulcand/Godeps/_workspace/src/gopkg.in/check.v1\"\n)\n\nfunc TestSecret(t *testing.T) { TestingT(t) }\n\ntype SecretSuite struct {\n}\n\nvar _ = Suite(&SecretSuite{})\n\n\n\nfunc (s *SecretSuite) TestEncryptDecryptJSON(c *C) {\n\tkeyS, err := NewKeyString()\n\tc.Assert(err, IsNil)\n\n\tkey, err := KeyFromString(keyS)\n\tc.Assert(err, IsNil)\n\n\tb, err := NewBox(key)\n\tc.Assert(err, IsNil)\n\n\tmessage := []byte(\"hello, box!\")\n\tsealed, err := b.Seal(message)\n\tc.Assert(err, IsNil)\n\n\tdata, err := SealedValueToJSON(sealed)\n\tc.Assert(err, IsNil)\n\tc.Assert(data, NotNil)\n\n\tbytes, err := SealedValueFromJSON(data)\n\tc.Assert(err, IsNil)\n\tc.Assert(bytes, NotNil)\n\n\tout, err := b.Open(sealed)\n\tc.Assert(err, IsNil)\n\tc.Assert(out, DeepEquals, message)\n}\n\nfunc (s *SecretSuite) TestEncryptDecryptCylce(c *C) ", "output": "{\n\tkeyS, err := NewKeyString()\n\tc.Assert(err, IsNil)\n\n\tkey, err := KeyFromString(keyS)\n\tc.Assert(err, IsNil)\n\n\tb, err := NewBox(key)\n\tc.Assert(err, IsNil)\n\n\tmessage := []byte(\"hello, box!\")\n\tsealed, err := b.Seal(message)\n\tc.Assert(err, IsNil)\n\n\tout, err := b.Open(sealed)\n\tc.Assert(err, IsNil)\n\tc.Assert(out, DeepEquals, message)\n}"} {"input": "package v1\n\nimport (\n\t\"testing\"\n\n\t\"github.com/gophercloud/gophercloud/acceptance/clients\"\n\t\"github.com/gophercloud/gophercloud/acceptance/tools\"\n\t\"github.com/gophercloud/gophercloud/openstack/db/v1/flavors\"\n)\n\nfunc TestFlavorsList(t *testing.T) {\n\tclient, err := clients.NewDBV1Client()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create a DB client: %v\", err)\n\t}\n\n\tallPages, err := flavors.List(client).AllPages()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to retrieve flavors: %v\", err)\n\t}\n\n\tallFlavors, err := flavors.ExtractFlavors(allPages)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to extract flavors: %v\", err)\n\t}\n\n\tfor _, flavor := range allFlavors {\n\t\ttools.PrintResource(t, &flavor)\n\t}\n}\n\n\n\nfunc TestFlavorsGet(t *testing.T) ", "output": "{\n\tclient, err := clients.NewDBV1Client()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create a DB client: %v\", err)\n\t}\n\n\tallPages, err := flavors.List(client).AllPages()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to retrieve flavors: %v\", err)\n\t}\n\n\tallFlavors, err := flavors.ExtractFlavors(allPages)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to extract flavors: %v\", err)\n\t}\n\n\tif len(allFlavors) > 0 {\n\t\tflavor, err := flavors.Get(client, allFlavors[0].StrID).Extract()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unable to get flavor: %v\", err)\n\t\t}\n\n\t\ttools.PrintResource(t, flavor)\n\t}\n}"} {"input": "package commands\n\nimport (\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n)\n\n\n\nfunc setupCommands(rootCmd *cobra.Command) {\n\trootCmd.AddCommand(botCommand)\n\trootCmd.AddCommand(statsCommand)\n\trootCmd.AddCommand(reqCommand)\n}\n\nfunc checkedRun(run func(cmd *cobra.Command, args []string) error) func(cmd *cobra.Command, args []string) {\n\n\treturn func(cmd *cobra.Command, args []string) {\n\t\tif err := run(cmd, args); err != nil {\n\t\t\tlog.Fatalf(\"%v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}\n\nfunc Execute() ", "output": "{\n\trootCmd := &cobra.Command{Use: \"htflood\"}\n\tsetupCommands(rootCmd)\n\trootCmd.Execute()\n}"} {"input": "package server\n\nimport (\n\t\"fmt\"\n\t\"github.com/centurylinkcloud/clc-go-cli/base\"\n)\n\ntype Server struct {\n\tServerId string\n\tServerName string\n}\n\nfunc (s *Server) Validate() error {\n\tif (s.ServerId == \"\") == (s.ServerName == \"\") {\n\t\treturn fmt.Errorf(\"Exactly one of the server-id and server-name must be set.\")\n\t}\n\treturn nil\n}\n\n\n\nfunc (s *Server) GetNames(cn base.Connection, property string) ([]string, error) {\n\tif property != \"ServerName\" {\n\t\treturn nil, nil\n\t}\n\n\treturn GetNames(cn, \"all\")\n}\n\nfunc (s *Server) InferID(cn base.Connection) error ", "output": "{\n\tif s.ServerName == \"\" {\n\t\treturn nil\n\t}\n\n\tID, err := IDByName(cn, s.ServerName)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.ServerId = ID\n\treturn nil\n}"} {"input": "package workshop\n\nimport (\n\t\"math\"\n)\n\n\ntype Shape interface {\n\tarea()\n\tcircumference()\n\tvolume()\n}\n\n\ntype Circle struct {\n\tradius float64\n\tPI float64\n}\n\nfunc (circle *Circle) area() float64 {\n\treturn circle.PI * math.Pow(circle.radius, 2)\n}\n\nfunc (circle *Circle) circumference() float64 {\n\treturn 2 * circle.PI * circle.radius\n}\n\n\ntype Square struct {\n\tside float64\n}\n\nfunc (square *Square) area() float64 {\n\treturn math.Pow(square.side, 2)\n}\n\ntype Sphere struct {\n\tPI float64\n\tradius float64\n}\n\nfunc (sphere *Sphere) volume() float64 {\n\treturn (4 / 3) * sphere.PI * math.Pow(sphere.radius, 3)\n}\n\n\ntype Cube struct {\n\tside float64\n}\n\nfunc (cube *Cube) volume() float64 {\n\treturn math.Pow(cube.side, 3)\n}\n\n\n\n\ntype Rectangle struct {\n\theight int\n\twidth int\n}\n\nfunc (rectangle *Rectangle) area() int {\n\treturn rectangle.height * rectangle.width\n}\n\nfunc interfaces() {\n\tcircle := Circle{radius: 5.5, PI: math.Pi}\n\tareaOfCircle := circle.area()\n\n\tassert(areaOfCircle == 55)\n\tassert(circle.circumference() == 88)\n\n\tvar square = Square{5}\n\tassert(square.area() == 36)\n\n\tcube := new(Cube)\n\tassert(cube.volume() == 8)\n\n\tvar rectangle = Rectangle{width: 4, height: 5}\n\tassert(rectangle.area() == 2)\n}\n\nfunc (square *Square) volume() float64 ", "output": "{\n\treturn math.Pow(square.side, 3)\n}"} {"input": "package builtin\n\nfunc X(a int, b float32, c rune, d string, e complex64) {\n\n}\n\n\n\nfunc Y() (a int, b float32, c rune, d string, e complex64) ", "output": "{\n\treturn\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\ntype NetworkSecurityGroupVnic struct {\n\n\tVnicId *string `mandatory:\"true\" json:\"vnicId\"`\n\n\tResourceId *string `mandatory:\"false\" json:\"resourceId\"`\n\n\tTimeAssociated *common.SDKTime `mandatory:\"false\" json:\"timeAssociated\"`\n}\n\n\n\nfunc (m NetworkSecurityGroupVnic) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package fork\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n)\n\ntype Field interface {\n\tNamed\n\tNew(...interface{}) Field\n\tGet() *Value\n\tSet(*http.Request)\n\tProcessor\n}\n\ntype Named interface {\n\tName() string\n\tReName(...string) string\n}\n\nfunc newnamed(name string) *named {\n\treturn &named{name: name}\n}\n\ntype named struct {\n\tname string\n}\n\nfunc (n *named) Name() string {\n\treturn n.name\n}\n\n\n\nfunc (n *named) Copy() *named {\n\tvar ret named = *n\n\treturn &ret\n}\n\ntype Processor interface {\n\tWidget\n\tFilterer\n\tValidater\n}\n\ntype processor struct {\n\tWidget\n\tValidater\n\tFilterer\n}\n\nfunc NewProcessor(w Widget, v Validater, f Filterer) *processor {\n\treturn &processor{w, v, f}\n}\n\nfunc (n *named) ReName(rename ...string) string ", "output": "{\n\tif len(rename) > 0 {\n\t\tn.name = strings.Join(rename, \"-\")\n\t}\n\treturn n.name\n}"} {"input": "package redis\n\nimport (\n\t\"bytes\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/wandoulabs/codis/extern/redis-port/pkg/libs/tests\"\n)\n\nfunc TestEncodeString(t *testing.T) {\n\tresp := &String{\"OK\"}\n\ttestEncodeAndCheck(t, resp, []byte(\"+OK\\r\\n\"))\n}\n\nfunc TestEncodeError(t *testing.T) {\n\tresp := &Error{\"Error\"}\n\ttestEncodeAndCheck(t, resp, []byte(\"-Error\\r\\n\"))\n}\n\nfunc TestEncodeInt(t *testing.T) {\n\tresp := &Int{}\n\tfor _, v := range []int{-1, 0, 1024 * 1024} {\n\t\tresp.Value = int64(v)\n\t\ttestEncodeAndCheck(t, resp, []byte(\":\"+strconv.FormatInt(int64(v), 10)+\"\\r\\n\"))\n\t}\n}\n\nfunc TestEncodeBulkBytes(t *testing.T) {\n\tresp := &BulkBytes{}\n\tresp.Value = nil\n\ttestEncodeAndCheck(t, resp, []byte(\"$-1\\r\\n\"))\n\tresp.Value = []byte{}\n\ttestEncodeAndCheck(t, resp, []byte(\"$0\\r\\n\\r\\n\"))\n\tresp.Value = []byte(\"helloworld!!\")\n\ttestEncodeAndCheck(t, resp, []byte(\"$12\\r\\nhelloworld!!\\r\\n\"))\n}\n\n\n\nfunc testEncodeAndCheck(t *testing.T, resp Resp, expect []byte) {\n\tb, err := EncodeToBytes(resp)\n\ttests.AssertNoError(t, err)\n\ttests.Assert(t, bytes.Equal(b, expect))\n}\n\nfunc TestEncodeArray(t *testing.T) ", "output": "{\n\tresp := &Array{}\n\tresp.Value = nil\n\ttestEncodeAndCheck(t, resp, []byte(\"*-1\\r\\n\"))\n\tresp.Value = []Resp{}\n\ttestEncodeAndCheck(t, resp, []byte(\"*0\\r\\n\"))\n\tresp.Append(&Int{0})\n\ttestEncodeAndCheck(t, resp, []byte(\"*1\\r\\n:0\\r\\n\"))\n\tresp.Append(&BulkBytes{nil})\n\ttestEncodeAndCheck(t, resp, []byte(\"*2\\r\\n:0\\r\\n$-1\\r\\n\"))\n\tresp.Append(&BulkBytes{[]byte(\"test\")})\n\ttestEncodeAndCheck(t, resp, []byte(\"*3\\r\\n:0\\r\\n$-1\\r\\n$4\\r\\ntest\\r\\n\"))\n}"} {"input": "package integration\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/m3db/m3cluster/kv\"\n\n\t\"github.com/golang/protobuf/proto\"\n\t\"github.com/stretchr/testify/require\"\n)\n\ntype conditionFn func() bool\n\n\n\nfunc updateStore(t *testing.T, store kv.Store, key string, proto proto.Message) {\n\t_, err := store.Set(key, proto)\n\trequire.NoError(t, err)\n}\n\nfunc waitUntil(fn conditionFn, timeout time.Duration) bool ", "output": "{\n\tdeadline := time.Now().Add(timeout)\n\tfor time.Now().Before(deadline) {\n\t\tif fn() {\n\t\t\treturn true\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n\treturn false\n}"} {"input": "package quit\n\nimport (\n\t\"fmt\"\n\t\"github.com/talpah/cortana/plugins\"\n\t\"regexp\"\n\t\"os\"\n)\n\nvar (\n\tcanonicalCommand = \"quit\"\n\tcommand = `(Q|q)uit`\n\taliases map[string]*regexp.Regexp\n)\n\n\n\nfunc canHandle(cmd string) bool {\n\tif regexp.MustCompile(command).MatchString(cmd) {\n\t\treturn true\n\t}\n\n\treturn isAlias(cmd)\n}\n\nfunc Initialize(pins plugins.PluginManager) {\n\taliases = map[string]*regexp.Regexp{\n\t\t\"Exit\": regexp.MustCompile(`(E|e)xit`),\n\n\t}\n\n\tpins.Register(\n\t\tcanonicalCommand,\n\t\tcommand,\n\t\tQuit,\n\t\tHelp,\n\t\taliases,\n\t)\n}\n\nfunc Help(cmd string) (string, error) {\n\treturn `Quit command help\n\nQuit will... quit\n\nUsage example:\nquit\nQuit\nexit\nExit\n`, nil\n}\n\nfunc Quit(cmd string) (string, error) {\n\tif !canHandle(cmd) {\n\t\treturn \"\", fmt.Errorf(\"Can't handle command %s\", cmd)\n\t}\n\tos.Exit(0)\n\treturn \"\", nil\n}\n\nfunc isAlias(cmd string) bool ", "output": "{\n\tfor _, alias := range aliases {\n\t\tif alias.MatchString(cmd) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package qemu\n\nimport (\n\t\"context\"\n\t\"github.com/oklog/ulid\"\n\t\"os\"\n\t\"os/exec\"\n)\n\ntype DiskCache string\n\nconst (\n\tCacheWriteThrough DiskCache = \"writethrough\"\n\tCacheWriteBack DiskCache = \"writeback\"\n\tCacheNone DiskCache = \"none\"\n\tCacheUnsafe DiskCache = \"unsafe\"\n\tCacheDirectSync DiskCache = \"directsync\"\n)\n\ntype NetworkDevice struct {\n\tInterfaceName string\n\tMacAddress string\n}\n\ntype StorageDevice struct {\n\tPool string\n\tDisk string\n\tCache DiskCache\n}\n\ntype VirtualMachine struct {\n\tId ulid.ULID\n\tVncPort int\n\tCpu string\n\tRoot string\n\tNICs []NetworkDevice\n\tDisks []StorageDevice\n\tMemLock bool\n\tVhostNet bool\n\tRAM int\n\tNumCPUs int\n\n\tcmd *exec.Cmd\n\tfiles []*os.File\n\tmon *Monitor\n}\n\nfunc (vm *VirtualMachine) Monitor() *Monitor {\n\tif vm.mon == nil {\n\t\tpanic(\"Monitor() call on uninitialized VM\")\n\t}\n\treturn vm.mon\n}\n\nfunc (vm *VirtualMachine) Kill(ctx context.Context) {\n\terr := vm.cmd.Process.Kill()\n\tif err != nil {\n\t\tlogger.Error(ctx, \"failed to kill vm process\", \"vm_id\", vm.Id, \"process\", vm.cmd.Process.Pid, \"error\", err)\n\t}\n}\n\n\n\nfunc (vm *VirtualMachine) Release(ctx context.Context) ", "output": "{\n\terr := vm.cmd.Process.Release()\n\tif err != nil {\n\t\tlogger.Error(ctx, \"failed to release vm process\", \"vm_id\", vm.Id, \"process\", vm.cmd.Process.Pid, \"error\", err)\n\t}\n}"} {"input": "package sw\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/sha256\"\n\t\"crypto/x509\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/hyperledger/fabric/bccsp\"\n)\n\n\n\n\n\n\ntype rsaPublicKey struct{ pubKey *rsa.PublicKey }\n\nfunc (k *rsaPublicKey) Symmetric() bool { return false }\n\nfunc (k *rsaPublicKey) PublicKey() (bccsp.Key, error) { return k, nil }\n\n\nfunc (k *rsaPublicKey) Bytes() (raw []byte, err error) {\n\tif k.pubKey == nil {\n\t\treturn nil, errors.New(\"Failed marshalling key. Key is nil.\")\n\t}\n\traw, err = x509.MarshalPKIXPublicKey(k.pubKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed marshalling key [%s]\", err)\n\t}\n\treturn\n}\n\n\nfunc (k *rsaPublicKey) SKI() []byte {\n\tif k.pubKey == nil {\n\t\treturn nil\n\t}\n\n\traw := x509.MarshalPKCS1PublicKey(k.pubKey)\n\thash := sha256.Sum256(raw)\n\treturn hash[:]\n}\n\nfunc (k *rsaPublicKey) Private() bool ", "output": "{ return false }"} {"input": "package cache\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/go-spatial/cobra\"\n)\n\nfunc setupMinMaxZoomFlags(cmd *cobra.Command, min, max uint) {\n\tcmd.Flags().UintVarP(&minZoom, \"min-zoom\", \"\", min, \"min zoom to seed cache from\")\n\tcmd.Flags().UintVarP(&maxZoom, \"max-zoom\", \"\", max, \"max zoom to seed cache to\")\n}\n\nfunc IsMinMaxZoomExplicit(cmd *cobra.Command) bool {\n\treturn !(cmd.Flag(\"min-zoom\").Changed || cmd.Flag(\"max-zoom\").Changed)\n}\n\n\n\nfunc setupTileNameFormat(cmd *cobra.Command) {\n\tcmd.Flags().StringVarP(&tileListFormat, \"format\", \"\", \"/zxy\", \"4 character string where the first character is a non-numeric delimiter followed by 'z', 'x' and 'y' defining the coordinate order\")\n}\n\nfunc tileNameFormatValidate(cmd *cobra.Command, args []string) (err error) {\n\tformat, err = NewFormat(tileListFormat)\n\treturn err\n}\n\nfunc minMaxZoomValidate(cmd *cobra.Command, args []string) (err error) ", "output": "{\n\tzooms, err = sliceFromRange(minZoom, maxZoom)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid zoom range, %v\", err)\n\t}\n\treturn nil\n}"} {"input": "package lifegame\n\ntype Universe struct {\n\taliveCells []Cell\n}\n\ntype Cell struct{}\n\nfunc NewUniverse() *Universe {\n\treturn &Universe{}\n}\n\n\n\nfunc (u *Universe) AliveCells() []Cell {\n\treturn u.aliveCells\n}\n\nfunc (u *Universe) NextGeneration() {\n\tu.aliveCells = []Cell{}\n}\n\nfunc (u *Universe) BornCellAtLocation(x, y int) {\n\tu.aliveCells = append(u.aliveCells, Cell{})\n}\n\nfunc (c *Cell) Location() (int, int) {\n\treturn 0, 0\n}\n\nfunc (u *Universe) HasAliveCell() bool ", "output": "{\n\treturn len(u.AliveCells()) != 0\n}"} {"input": "package replay\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/gapid/core/data/search\"\n\t\"github.com/google/gapid/test/robot/job/worker\"\n\t\"google.golang.org/grpc\"\n\n\txctx \"golang.org/x/net/context\"\n)\n\ntype server struct {\n\tmanager Manager\n}\n\n\n\n\n\n\nfunc (s *server) Search(query *search.Query, stream Service_SearchServer) error {\n\tctx := stream.Context()\n\treturn s.manager.Search(ctx, query, func(ctx context.Context, e *Action) error { return stream.Send(e) })\n}\n\n\n\nfunc (s *server) Register(request *worker.RegisterRequest, stream Service_RegisterServer) error {\n\tctx := stream.Context()\n\treturn s.manager.Register(ctx, request.Host, request.Target, func(ctx context.Context, t *Task) error { return stream.Send(t) })\n}\n\n\n\nfunc (s *server) Do(ctx xctx.Context, request *DoRequest) (*worker.DoResponse, error) {\n\tid, err := s.manager.Do(ctx, request.Device, request.Input)\n\treturn &worker.DoResponse{Id: id}, err\n}\n\n\n\nfunc (s *server) Update(ctx xctx.Context, request *UpdateRequest) (*worker.UpdateResponse, error) {\n\tif err := s.manager.Update(ctx, request.Action, request.Status, request.Output); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &worker.UpdateResponse{}, nil\n}\n\nfunc Serve(ctx context.Context, grpcServer *grpc.Server, manager Manager) error ", "output": "{\n\tRegisterServiceServer(grpcServer, &server{manager: manager})\n\treturn nil\n}"} {"input": "package model\n\ntype Interface interface {\n\tVisitString(name string, resume func())\n\tVisitInt(name string, resume func())\n\tVisitFloat(name string, resume func())\n\tVisitBool(name string, resume func())\n\tVisitPtr(name string, resume func())\n\tVisitBytes(name string, resume func())\n\tVisitSlice(name string, resume func())\n\tVisitStruct(name string, fields []Field, resume func())\n\tVisitStructField(field Field, resume func())\n\tVisitMap(name string, resume func())\n\tVisitCustom(name string, resume func())\n\tVisitReference(name string, resume func())\n}\n\ntype Visitor struct{}\n\nfunc (self *Visitor) VisitString(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitInt(name string, resume func()) {\n\tresume()\n}\n\n\n\nfunc (self *Visitor) VisitBool(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitPtr(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBytes(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitSlice(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStructField(field Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitMap(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitCustom(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitReference(name string, resume func()) {\n\tresume()\n}\n\ntype EmbeddedStructVisitor struct {\n\tInterface\n}\n\nfunc (self *EmbeddedStructVisitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitFloat(name string, resume func()) ", "output": "{\n\tresume()\n}"} {"input": "package views\n\nimport \"github.com/cSploit/daemon/models\"\n\ntype networkIdxElem struct {\n\tmodels.Network\n\tHideHosts string `json:\"hosts,omitempty\"`\n}\n\ntype networkShowView struct {\n\tmodels.Network\n\tOverrideHosts interface{} `json:\"hosts,omitempty\"`\n}\n\nfunc NetworkIndex(args interface{}) interface{} {\n\tnets := args.([]models.Network)\n\tres := make([]networkIdxElem, len(nets))\n\n\tfor i, n := range nets {\n\t\tres[i] = networkIdxElem{Network: n}\n\t}\n\n\treturn res\n}\n\nfunc NetworkShow(arg interface{}) interface{} {\n\tnet := arg.(models.Network)\n\tres := networkShowView{Network: net}\n\n\tif len(net.Hosts) > 0 {\n\t\tres.OverrideHosts = HostsIndex(net.Hosts)\n\t}\n\n\treturn res\n}\n\n\n\nfunc networkAsChild(arg interface{}) interface{} ", "output": "{\n\tnetwork := arg.(models.Network)\n\treturn networkIdxElem{Network: network}\n}"} {"input": "package cmd\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n)\n\nimport . \"assert\"\n\ntype cmd_oneshot struct {\n\tcmd string\n}\n\nfunc MakeOneShotCommand(cmd string) Cmd {\n\treturn &cmd_oneshot{cmd}\n}\n\n\n\nfunc (c *cmd_oneshot) Start(in <-chan []string, out chan<- string) ", "output": "{\n\n\tshell := os.Getenv(\"SHELL\")\n\tif shell == \"\" {\n\t\tshell = \"sh\"\n\t}\n\n\tfor {\n\t\tcmdc := exec.Command(shell, \"-c\", c.cmd, \"reg\")\n\t\tif in != nil {\n\t\t\tinput := <-in\n\t\t\tcmdc.Args = append(cmdc.Args, input...)\n\t\t}\n\t\tif out == nil {\n\t\t\terr := cmdc.Run()\n\t\t\tAssert(err == nil, cmdc.Args, \":Run()\", \":\", err)\n\t\t} else {\n\t\t\toutput, err := cmdc.Output()\n\t\t\tAssert(err == nil, cmdc.Args, \":Output()\", \":\", err)\n\t\t\tout <- string(output[:len(output)-1])\n\t\t}\n\t}\n\n}"} {"input": "package schema\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Location struct {\n\tTimestamp time.Time `json:\"timestamp,omitempty\"`\n\tLatitude float64 `json:\"latitude,omitempty\"`\n\tLongitude float64 `json:\"longitude,omitempty\"`\n\tAccuracy float64 `json:\"accuracy,omitempty\"`\n\tSource string `json:\"source,omitempty\"`\n\tAddress string `json:\"address,omitempty\"`\n}\n\n\n\ntype Geofence struct {\n\tLatMin float64 `json:\"lat_min,omitempty\"`\n\tLatMax float64 `json:\"lat_max,omitempty\"`\n\tLngMin float64 `json:\"lng_min,omitempty\"`\n\tLngMax float64 `json:\"lng_max,omitempty\"`\n\tName string `json:\"name,omitempty\"`\n\tAddress string `json:\"address,omitempty\"`\n}\n\ntype GeofenceChange struct {\n\tLocation Location `json:\"loc,omitempty\"`\n\tFence Geofence `json:\"fence,omitempty\"`\n\tStatus string `json:\"status,omitempty\"`\n}\n\nfunc (m GeofenceChange) Text() string {\n\treturn fmt.Sprintf(\"%s %ss %s.\", m.Location.Source, m.Status, m.Fence.Name)\n}\n\nfunc (l Location) Text() string ", "output": "{\n\tts := l.Timestamp.Format(time.RFC1123)\n\tif l.Address != \"\" {\n\t\treturn l.Address + \" on \" + ts\n\t}\n\treturn fmt.Sprintf(\"%.4f, %.4f on %s\", l.Latitude, l.Longitude, ts)\n}"} {"input": "package thriftclient\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"git.apache.org/thrift.git/lib/go/thrift\"\n)\n\ntype transportFactory struct {\n\tserviceIP string\n\tservicePort int\n\ttimeOut int64\n}\n\nfunc NewTransportFactory(serviceIP string, servicePort int, timeOut int64) *transportFactory {\n\treturn &transportFactory{serviceIP: serviceIP, servicePort: servicePort, timeOut: timeOut}\n}\n\n\n\n\n\nfunc (tf *transportFactory) DestroyObj(t interface{}) error {\n\tvalue, ok := t.(thrift.TTransport)\n\tif ok {\n\t\tif value.IsOpen() {\n\t\t\tvalue.Close()\n\t\t}\n\t}\n\treturn nil\n\n}\n\n\nfunc (tf *transportFactory) ValidateObj(t interface{}) error {\n\tvalue, ok := t.(thrift.TTransport)\n\tif ok {\n\t\tif value.IsOpen() {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn errors.New(\"transport is not validate\")\n}\n\nfunc (tf *transportFactory) CreateObj() (interface{}, error) ", "output": "{\n\ttransportFactory := thrift.NewTTransportFactory()\n\tvar err error\n\tvar transport thrift.TTransport\n\taddr := fmt.Sprintf(\"%s:%d\", tf.serviceIP, tf.servicePort)\n\ttransport, err = thrift.NewTSocketTimeout(addr, time.Duration(tf.timeOut)*time.Millisecond)\n\tif err != nil {\n\t\tfmt.Println(\"Error opening socket:\", err)\n\t\treturn nil, err\n\t}\n\ttransport = transportFactory.GetTransport(transport)\n\tif err := transport.Open(); err != nil {\n\t\tfmt.Println(\"Error transport opening:\", err)\n\t\treturn nil, err\n\t}\n\treturn transport, nil\n}"} {"input": "package root\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/kubernetes-incubator/kube-aws/awsconn\"\n\t\"github.com/kubernetes-incubator/kube-aws/cfnstack\"\n\t\"github.com/kubernetes-incubator/kube-aws/core/root/config\"\n)\n\ntype DestroyOptions struct {\n\tAwsDebug bool\n\tForce bool\n}\n\ntype ClusterDestroyer interface {\n\tDestroy() error\n}\n\ntype clusterDestroyerImpl struct {\n\tunderlying *cfnstack.Destroyer\n}\n\nfunc ClusterDestroyerFromFile(configPath string, opts DestroyOptions) (ClusterDestroyer, error) {\n\tcfg, err := config.ConfigFromFile(configPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsession, err := awsconn.NewSessionFromRegion(cfg.Region, opts.AwsDebug)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to establish aws session: %v\", err)\n\t}\n\n\tcfnDestroyer := cfnstack.NewDestroyer(cfg.RootStackName(), session, cfg.CloudFormation.RoleARN)\n\treturn clusterDestroyerImpl{\n\t\tunderlying: cfnDestroyer,\n\t}, nil\n}\n\n\n\nfunc (d clusterDestroyerImpl) Destroy() error ", "output": "{\n\treturn d.underlying.Destroy()\n}"} {"input": "package raft\n\nimport (\n\t\"github.com/iketheadore/raft/comm\"\n\t\"github.com/iketheadore/raft/logic\"\n)\n\ntype Raft struct {\n\tlocalServ logic.Server\n\tlistener comm.Listener\n\tsender comm.Sender\n\tlogic *logic.Logic\n}\n\nfunc New(addr string) *Raft {\n\tr := &Raft{localServ: logic.Server{Addr: addr, Role: logic.Follower}, listener: comm.NewListener(addr)}\n\tr.listener.Run()\n\tr.logic = logic.New(r.localServ)\n\tr.logic.Subscribe(r.listener)\n\treturn r\n}\n\nfunc (r *Raft) Connect(addr string) error {\n\treturn r.logic.Connect(logic.Server{Addr: addr, Role: logic.Follower})\n}\n\n\n\nfunc (r *Raft) ReplicateCmd(cmd comm.Command) {\n\tr.logic.ReplicateCmd(cmd)\n}\n\nfunc (r *Raft) Run() ", "output": "{\n\tr.logic.Run()\n}"} {"input": "package cabf_br\n\n\n\nimport (\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/util\"\n)\n\ntype SANEDI struct{}\n\n\n\n\n\nfunc (l *SANEDI) Initialize() error {\n\treturn nil\n}\n\nfunc (l *SANEDI) CheckApplies(c *x509.Certificate) bool {\n\treturn util.IsExtInCert(c, util.SubjectAlternateNameOID)\n}\n\nfunc (l *SANEDI) Execute(c *x509.Certificate) *lint.LintResult {\n\tif c.EDIPartyNames != nil {\n\t\treturn &lint.LintResult{Status: lint.Error}\n\t}\n\treturn &lint.LintResult{Status: lint.Pass}\n}\n\nfunc init() ", "output": "{\n\tlint.RegisterLint(&lint.Lint{\n\t\tName: \"e_ext_san_edi_party_name_present\",\n\t\tDescription: \"The Subject Alternate Name extension MUST contain only 'dnsName' and 'ipaddress' name types\",\n\t\tCitation: \"BRs: 7.1.4.2.1\",\n\t\tSource: lint.CABFBaselineRequirements,\n\t\tEffectiveDate: util.CABEffectiveDate,\n\t\tLint: &SANEDI{},\n\t})\n}"} {"input": "package alert\n\nimport (\n\t. \"aliyun-openapi-go-sdk/core\"\n)\n\ntype GetContactGroupRequest struct {\n\tRoaRequest\n\tProjectName string\n\tGroupName string\n}\n\nfunc (r *GetContactGroupRequest) SetProjectName(value string) {\n\tr.ProjectName = value\n\tr.PathParams.Set(\"ProjectName\", value)\n}\nfunc (r *GetContactGroupRequest) GetProjectName() string {\n\treturn r.ProjectName\n}\nfunc (r *GetContactGroupRequest) SetGroupName(value string) {\n\tr.GroupName = value\n\tr.PathParams.Set(\"GroupName\", value)\n}\nfunc (r *GetContactGroupRequest) GetGroupName() string {\n\treturn r.GroupName\n}\n\n\n\ntype GetContactGroupResponse struct {\n\tcode string `xml:\"code\" json:\"code\"`\n\tmessage string `xml:\"message\" json:\"message\"`\n\tsuccess string `xml:\"success\" json:\"success\"`\n\ttraceId string `xml:\"traceId\" json:\"traceId\"`\n\tresult string `xml:\"result\" json:\"result\"`\n}\n\nfunc GetContactGroup(req *GetContactGroupRequest, accessId, accessSecret string) (*GetContactGroupResponse, error) {\n\tvar pResponse GetContactGroupResponse\n\tbody, err := ApiHttpRequest(accessId, accessSecret, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tApiUnmarshalResponse(req.GetFormat(), body, &pResponse)\n\treturn &pResponse, err\n}\n\nfunc (r *GetContactGroupRequest) Init() ", "output": "{\n\tr.RoaRequest.Init()\n\tr.PathPattern = \"/projects/ProjectName/groups/GroupName\"\n\tr.SetMethod(\"GET\")\n\tr.SetProtocol(\"HTTP\")\n\tr.SetProduct(Product)\n}"} {"input": "package router\n\nimport (\n\t\"sync/atomic\"\n\n\t\"github.com/AsynkronIT/protoactor-go/actor\"\n)\n\ntype roundRobinGroupRouter struct {\n\tGroupRouter\n}\n\ntype roundRobinPoolRouter struct {\n\tPoolRouter\n}\n\ntype roundRobinState struct {\n\tindex int32\n\troutees *actor.PIDSet\n\tvalues []actor.PID\n}\n\nfunc (state *roundRobinState) SetRoutees(routees *actor.PIDSet) {\n\tstate.routees = routees\n\tstate.values = routees.Values()\n}\n\nfunc (state *roundRobinState) GetRoutees() *actor.PIDSet {\n\treturn state.routees\n}\n\nfunc (state *roundRobinState) RouteMessage(message interface{}, sender *actor.PID) {\n\tpid := roundRobinRoutee(&state.index, state.values)\n\tpid.Request(message, sender)\n}\n\n\n\nfunc NewRoundRobinGroup(routees ...*actor.PID) *actor.Props {\n\treturn actor.FromSpawnFunc(spawner(&roundRobinGroupRouter{GroupRouter{Routees: actor.NewPIDSet(routees...)}}))\n}\n\nfunc (config *roundRobinPoolRouter) CreateRouterState() Interface {\n\treturn &roundRobinState{}\n}\n\nfunc (config *roundRobinGroupRouter) CreateRouterState() Interface {\n\treturn &roundRobinState{}\n}\n\nfunc roundRobinRoutee(index *int32, routees []actor.PID) actor.PID {\n\ti := int(atomic.AddInt32(index, 1))\n\tif i < 0 {\n\t\t*index = 0\n\t\ti = 0\n\t}\n\tmod := len(routees)\n\troutee := routees[i%mod]\n\treturn routee\n}\n\nfunc NewRoundRobinPool(size int) *actor.Props ", "output": "{\n\treturn actor.FromSpawnFunc(spawner(&roundRobinPoolRouter{PoolRouter{PoolSize: size}}))\n}"} {"input": "package timer\n\nimport (\n\t\"time\"\n)\n\ntype typeAction int\n\nconst (\n\tCLOSE typeAction = iota\n\tRESET\n\tFORCE\n)\n\n\n\ntype Timer struct {\n\tinterval time.Duration\n\tmsg, resp chan typeAction\n}\n\n\n\n\nfunc NewTimer(interval time.Duration) *Timer {\n\treturn &Timer{\n\t\tinterval: interval,\n\t\tmsg: make(chan typeAction, 1),\n\t\tresp: make(chan typeAction, 1),\n\t}\n}\n\n\n\n\nfunc (self *Timer) Next() bool {\n\tfor {\n\t\tvar ch <-chan time.Time\n\t\tif self.interval <= 0 {\n\t\t\tch = nil\n\t\t} else {\n\t\t\tch = time.After(self.interval)\n\t\t}\n\t\tselect {\n\t\tcase action := <-self.msg:\n\t\t\tswitch action {\n\t\t\tcase CLOSE:\n\t\t\t\tself.resp <- CLOSE\n\t\t\t\treturn false\n\t\t\tcase FORCE:\n\t\t\t\treturn true\n\t\t\t}\n\t\tcase <-ch:\n\t\t\treturn true\n\t\t}\n\t}\n\tpanic(\"unreachable\")\n}\n\n\n\n\n\n\n\nfunc (self *Timer) Trigger() {\n\tself.msg <- FORCE\n}\n\n\nfunc (self *Timer) TriggerAfter(ns time.Duration) {\n\tgo func() {\n\t\t<-time.After(ns)\n\t\tself.Trigger()\n\t}()\n}\n\n\n\n\nfunc (self *Timer) Close() {\n\tself.msg <- CLOSE\n\t<-self.resp\n}\n\nfunc (self *Timer) SetInterval(ns time.Duration) ", "output": "{\n\tself.interval = ns\n\tself.msg <- RESET\n}"} {"input": "package protocol\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestFindCoordinatorRequest(t *testing.T) ", "output": "{\n\treq := require.New(t)\n\texp := &FindCoordinatorRequest{\n\t\tAPIVersion: 1,\n\t\tCoordinatorKey: \"coord-key\",\n\t\tCoordinatorType: 1,\n\t}\n\tb, err := Encode(exp)\n\treq.NoError(err)\n\tvar act FindCoordinatorRequest\n\terr = Decode(b, &act, exp.Version())\n\treq.NoError(err)\n\treq.Equal(exp, &act)\n}"} {"input": "package readline\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\n\nfunc goCompletionEntryFunction(text *C.char, state C.int) *C.char {\n\tmatch := completionEntryFunction(C.GoString(text), int(state))\n\tif match == \"\" {\n\t\treturn nil\n\t}\n\treturn C.CString(match) \n}\n\n\n\n\n\n\n\n\n\n\n\ntype CompletionEntryFunction func(text string, state int) string\n\nvar completionEntryFunction CompletionEntryFunction\n\n\n\nfunc SetCompletionEntryFunction(f CompletionEntryFunction) {\n\tif f == nil {\n\t\tif completionEntryFunction != nil {\n\t\t\tC.rl_attempted_completion_function = nil\n\t\t}\n\t} else if completionEntryFunction == nil {\n\t\tC.register_attempted_completion_function()\n\t}\n\tcompletionEntryFunction = f\n}\n\n\n\n\n\nfunc SetAttemptedCompletionOver(b bool) {\n\tif b {\n\t\tC.rl_attempted_completion_over = 1\n\t} else {\n\t\tC.rl_attempted_completion_over = 0\n\t}\n}\n\n\n\nfunc SetCompleterWordBreakChars(s string) {\n\tcs := C.CString(s)\n\tC.free(unsafe.Pointer(C.rl_completer_word_break_characters))\n\tC.rl_completer_word_break_characters = cs\n}\n\n\n\n\n\n\nfunc CompleterWordBreakChars() string ", "output": "{\n\treturn C.GoString(C.rl_completer_word_break_characters)\n}"} {"input": "package iyzipay\n\ntype CrossBookingToSubMerchant struct{}\n\n\n\nfunc (crossBookingToSubMerchant CrossBookingToSubMerchant) Create(request CreateCrossBookingRequest, options Options) string ", "output": "{\n\n\tresponse := makeRequest(request, \"POST\", \"/crossbooking/send\", options)\n\treturn response\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/apier/v1\"\n\nfunc init() {\n\tc := &CmdRemoveActions{\n\t\tname: \"actions_remove\",\n\t\trpcMethod: \"ApierV1.RemoveActions\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdRemoveActions struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrRemoveActions\n\t*CommandExecuter\n}\n\nfunc (self *CmdRemoveActions) Name() string {\n\treturn self.name\n}\n\n\n\nfunc (self *CmdRemoveActions) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrRemoveActions{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdRemoveActions) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdRemoveActions) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *CmdRemoveActions) RpcMethod() string ", "output": "{\n\treturn self.rpcMethod\n}"} {"input": "package db\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"time\"\n\n\t\"github.com/boltdb/bolt\"\n\n\t\"github.com/michaelorr/goodall/pkg/metrics\"\n)\n\nfunc Open(path string) (*bolt.DB, error) {\n\treturn bolt.Open(path, 0600, &bolt.Options{Timeout: 1 * time.Second})\n}\n\nfunc Init(conn *bolt.DB) error {\n\tfor bucket, _ := range metrics.BucketMap {\n\t\terr := conn.Update(func(tx *bolt.Tx) error {\n\t\t\t_, err := tx.CreateBucketIfNotExists([]byte(bucket))\n\t\t\treturn err\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc Ftob(f float64) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\terr := binary.Write(buf, binary.BigEndian, f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}\n\n\n\nfunc Btof(b []byte) (float64, error) ", "output": "{\n\tvar f float64\n\tbuf := bytes.NewReader(b)\n\terr := binary.Read(buf, binary.BigEndian, &f)\n\tif err != nil {\n\t\treturn f, err\n\t}\n\treturn f, nil\n}"} {"input": "package mlock\n\nimport (\n \"syscall\"\n \"golang.org/x/sys/unix\"\n)\n\n\n\nfunc lockMemory() error {\n \n return unix.Mlockall(syscall.MCL_CURRENT | syscall.MCL_FUTURE)\n}\n\nfunc init() ", "output": "{\n supported = true\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype OpenpitrixRepoEvent struct {\n\n\tCreateTime strfmt.DateTime `json:\"create_time,omitempty\"`\n\n\tOwner string `json:\"owner,omitempty\"`\n\n\tOwnerPath string `json:\"owner_path,omitempty\"`\n\n\tRepoEventID string `json:\"repo_event_id,omitempty\"`\n\n\tRepoID string `json:\"repo_id,omitempty\"`\n\n\tResult string `json:\"result,omitempty\"`\n\n\tStatus string `json:\"status,omitempty\"`\n\n\tStatusTime strfmt.DateTime `json:\"status_time,omitempty\"`\n}\n\n\n\n\n\nfunc (m *OpenpitrixRepoEvent) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *OpenpitrixRepoEvent) UnmarshalBinary(b []byte) error {\n\tvar res OpenpitrixRepoEvent\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *OpenpitrixRepoEvent) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package subscriptions\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/status-im/status-go/rpc\"\n)\n\ntype ethFilter struct {\n\tid string\n\trpcClient *rpc.Client\n}\n\nfunc installEthFilter(rpcClient *rpc.Client, method string, args []interface{}) (*ethFilter, error) {\n\n\tif err := validateEthMethod(method); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result string\n\n\terr := rpcClient.Call(&result, rpcClient.UpstreamChainID, method, args...)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilter := ðFilter{\n\t\tid: result,\n\t\trpcClient: rpcClient,\n\t}\n\n\treturn filter, nil\n\n}\n\nfunc (ef *ethFilter) getID() string {\n\treturn ef.id\n}\n\nfunc (ef *ethFilter) getChanges() ([]interface{}, error) {\n\tvar result []interface{}\n\n\terr := ef.rpcClient.Call(&result, ef.rpcClient.UpstreamChainID, \"eth_getFilterChanges\", ef.getID())\n\n\treturn result, err\n}\n\n\n\nfunc validateEthMethod(method string) error {\n\tfor _, allowedMethod := range []string{\n\t\t\"eth_newFilter\",\n\t\t\"eth_newBlockFilter\",\n\t\t\"eth_newPendingTransactionFilter\",\n\t} {\n\t\tif method == allowedMethod {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"unexpected filter method: %s\", method)\n}\n\nfunc (ef *ethFilter) uninstall() error ", "output": "{\n\treturn ef.rpcClient.Call(nil, ef.rpcClient.UpstreamChainID, \"eth_uninstallFilter\", ef.getID())\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/converter\"\n\t\"strings\"\n)\n\n\ntype BatchStopServersOption struct {\n\tServers []ServerId `json:\"servers\"`\n\tType *BatchStopServersOptionType `json:\"type,omitempty\"`\n}\n\nfunc (o BatchStopServersOption) String() string {\n\tdata, _ := json.Marshal(o)\n\treturn strings.Join([]string{\"BatchStopServersOption\", string(data)}, \" \")\n}\n\ntype BatchStopServersOptionType struct {\n\tvalue string\n}\n\ntype BatchStopServersOptionTypeEnum struct {\n\tSOFT BatchStopServersOptionType\n\tHARD BatchStopServersOptionType\n}\n\nfunc GetBatchStopServersOptionTypeEnum() BatchStopServersOptionTypeEnum {\n\treturn BatchStopServersOptionTypeEnum{\n\t\tSOFT: BatchStopServersOptionType{\n\t\t\tvalue: \"SOFT\",\n\t\t},\n\t\tHARD: BatchStopServersOptionType{\n\t\t\tvalue: \"HARD\",\n\t\t},\n\t}\n}\n\n\n\nfunc (c *BatchStopServersOptionType) UnmarshalJSON(b []byte) error {\n\tmyConverter := converter.StringConverterFactory(\"string\")\n\tif myConverter != nil {\n\t\tval, err := myConverter.CovertStringToInterface(strings.Trim(string(b[:]), \"\\\"\"))\n\t\tif err == nil {\n\t\t\tc.value = val.(string)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t} else {\n\t\treturn errors.New(\"convert enum data to string error\")\n\t}\n}\n\nfunc (c BatchStopServersOptionType) MarshalJSON() ([]byte, error) ", "output": "{\n\treturn json.Marshal(c.value)\n}"} {"input": "package tunnel\n\nimport (\n \"container/list\"\n \"time\"\n)\n\ntype recyclerItem struct {\n when time.Time\n buf []byte\n}\n\ntype recycler struct {\n q *list.List\n takeChan, giveChan chan []byte\n}\n\nfunc NewRecycler(size uint32) *recycler {\n r := &recycler{\n q: new(list.List),\n takeChan: make(chan []byte),\n giveChan: make(chan []byte),\n }\n go r.cycle(size)\n return r\n}\n\nfunc (r *recycler) cycle(size uint32) {\n for {\n if r.q.Len() == 0 {\n \n r.q.PushFront(recyclerItem{when: time.Now(), buf: make([]byte, size)})\n }\n i := r.q.Front()\n timeout := time.NewTimer(time.Minute)\n select {\n case b:= <-r.giveChan:\n timeout.Stop()\n r.q.PushFront(recyclerItem{when: time.Now(), buf: b})\n case r.takeChan <- i.Value.(recyclerItem).buf:\n timeout.Stop()\n r.q.Remove(i)\n case <-timeout.C:\n i := r.q.Front()\n for i != nil {\n n := i.Next()\n if time.Since(i.Value.(recyclerItem).when) > time.Minute {\n r.q.Remove(i)\n i.Value = nil\n }\n i = n\n }\n }\n }\n}\n\nfunc (r *recycler) take() []byte {\n return <-r.takeChan\n}\n\n\n\nfunc (r *recycler) give(b []byte) ", "output": "{\n r.giveChan <- b\n}"} {"input": "package trafficmanager\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" trafficmanager/2018-02-01-preview\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package iso20022\n\n\ntype PendingCancellationStatusReason6 struct {\n\n\tReasonCode *PendingCancellationReason4Choice `xml:\"RsnCd\"`\n\n\tAdditionalReasonInformation *RestrictedFINXMax210Text `xml:\"AddtlRsnInf,omitempty\"`\n}\n\nfunc (p *PendingCancellationStatusReason6) AddReasonCode() *PendingCancellationReason4Choice {\n\tp.ReasonCode = new(PendingCancellationReason4Choice)\n\treturn p.ReasonCode\n}\n\n\n\nfunc (p *PendingCancellationStatusReason6) SetAdditionalReasonInformation(value string) ", "output": "{\n\tp.AdditionalReasonInformation = (*RestrictedFINXMax210Text)(&value)\n}"} {"input": "package goZKP\n\nimport (\n\t\"errors\"\n\t\"math/big\"\n)\n\n\ntype ZZ struct {\n\tg *big.Int\n\tmodulo *big.Int\n}\n\nfunc (z *ZZ) Bytes() []byte {\n\treturn z.g.Bytes()\n}\n\n\n\nfunc (z *ZZ) Exp(x *big.Int) *ZZ {\n\tz.g.Exp(z.g, x, z.modulo)\n\treturn z\n}\n\nfunc (z *ZZ) Inverse() *ZZ {\n\tz.g.ModInverse(z.g, z.modulo)\n\treturn z\n}\n\nfunc (z *ZZ) Mul(x *ZZ) (*ZZ, error) ", "output": "{\n\tif x.modulo.Cmp(z.modulo) != 0 {\n\t\treturn nil, errors.New(\"Unmatched modulo in ZZ multiplication.\")\n\t}\n\tz.g.Mul(z.g, x.g)\n\tz.g.Mod(z.g, z.modulo)\n\treturn z, nil\n}"} {"input": "package gatherer\n\nimport (\n\t\"magic\"\n\n\t\"github.com/PuerkitoBio/goquery\"\n)\n\ntype single struct{}\n\nfunc NewSingle() single {\n\treturn single{}\n}\n\n\n\nfunc (s single) Parse(doc *goquery.Document) (*magic.Card, error) ", "output": "{\n\tcol := \"#ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_cardComponent0\"\n\treturn NewCard(col, doc).Parse()\n}"} {"input": "package datacatalog\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteCustomPropertyRequest struct {\n\n\tCatalogId *string `mandatory:\"true\" contributesTo:\"path\" name:\"catalogId\"`\n\n\tNamespaceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"namespaceId\"`\n\n\tCustomPropertyKey *string `mandatory:\"true\" contributesTo:\"path\" name:\"customPropertyKey\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteCustomPropertyRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteCustomPropertyRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request DeleteCustomPropertyRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request DeleteCustomPropertyRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteCustomPropertyResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteCustomPropertyResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response DeleteCustomPropertyResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package arg2\n\nimport (\n\t\"encoding/binary\"\n\t\"io\"\n\n\t\"github.com/uber/tchannel-go/typed\"\n)\n\n\n\n\n\ntype KeyValIterator struct {\n\tremaining []byte\n\tleftPairCount int\n\tkey []byte\n\tval []byte\n}\n\n\n\n\nfunc NewKeyValIterator(arg2Payload []byte) (KeyValIterator, error) {\n\tif len(arg2Payload) < 2 {\n\t\treturn KeyValIterator{}, io.EOF\n\t}\n\n\tleftPairCount := binary.BigEndian.Uint16(arg2Payload[0:2])\n\treturn KeyValIterator{\n\t\tleftPairCount: int(leftPairCount),\n\t\tremaining: arg2Payload[2:],\n\t}.Next()\n}\n\n\nfunc (i KeyValIterator) Key() []byte {\n\treturn i.key\n}\n\n\nfunc (i KeyValIterator) Value() []byte {\n\treturn i.val\n}\n\n\n\n\n\n\n\n\n\nfunc (i KeyValIterator) Next() (kv KeyValIterator, _ error) {\n\tif i.leftPairCount <= 0 {\n\t\treturn KeyValIterator{}, io.EOF\n\t}\n\n\trbuf := typed.NewReadBuffer(i.remaining)\n\tkeyLen := int(rbuf.ReadUint16())\n\tkey := rbuf.ReadBytes(keyLen)\n\tvalLen := int(rbuf.ReadUint16())\n\tval := rbuf.ReadBytes(valLen)\n\tif rbuf.Err() != nil {\n\t\treturn KeyValIterator{}, rbuf.Err()\n\t}\n\n\tleftPairCount := i.leftPairCount - 1\n\n\tkv = KeyValIterator{\n\t\tremaining: rbuf.Remaining(),\n\t\tleftPairCount: leftPairCount,\n\t\tkey: key,\n\t\tval: val,\n\t}\n\treturn kv, nil\n}\n\nfunc (i KeyValIterator) Remaining() bool ", "output": "{\n\treturn i.leftPairCount > 0\n}"} {"input": "package repos\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\tdb \"github.com/antoineaugusti/feature-flags/db\"\n\tm \"github.com/antoineaugusti/feature-flags/models\"\n\t\"github.com/boltdb/bolt\"\n)\n\n\n\n\n\nfunc GetFeatures(tx *bolt.Tx) (m.FeatureFlags, error) {\n\tfeaturesBucket := tx.Bucket([]byte(db.GetBucketName()))\n\tcursor := featuresBucket.Cursor()\n\n\tfeatures := make(m.FeatureFlags, 0)\n\n\tfor key, value := cursor.First(); key != nil; key, value = cursor.Next() {\n\t\tfeature := m.FeatureFlag{}\n\n\t\terr := json.Unmarshal(value, &feature)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfeatures = append(features, feature)\n\t}\n\n\treturn features, nil\n}\n\n\nfunc FeatureExists(tx *bolt.Tx, featureKey string) bool {\n\tfeatures := tx.Bucket([]byte(db.GetBucketName()))\n\tbytes := features.Get([]byte(featureKey))\n\treturn bytes != nil\n}\n\n\nfunc GetFeature(tx *bolt.Tx, featureKey string) (m.FeatureFlag, error) {\n\tfeatures := tx.Bucket([]byte(db.GetBucketName()))\n\n\tbytes := features.Get([]byte(featureKey))\n\tif bytes == nil {\n\t\treturn m.FeatureFlag{}, fmt.Errorf(\"Unable to find feature\")\n\t}\n\n\tfeature := m.FeatureFlag{}\n\n\terr := json.Unmarshal(bytes, &feature)\n\tif err != nil {\n\t\treturn m.FeatureFlag{}, err\n\t}\n\n\treturn feature, nil\n}\n\n\nfunc RemoveFeature(tx *bolt.Tx, featureKey string) error {\n\tfeatures := tx.Bucket([]byte(db.GetBucketName()))\n\treturn features.Delete([]byte(featureKey))\n}\n\nfunc PutFeature(tx *bolt.Tx, feature m.FeatureFlag) error ", "output": "{\n\tfeatures := tx.Bucket([]byte(db.GetBucketName()))\n\n\tbytes, err := json.Marshal(feature)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = features.Put([]byte(feature.Key), bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package identity\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype DeleteUserRequest struct {\n\n\tUserId *string `mandatory:\"true\" contributesTo:\"path\" name:\"userId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request DeleteUserRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request DeleteUserRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteUserResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteUserResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteUserResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteUserRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package post\n\nimport \"github.com/barnex/bruteray/imagef\"\n\ntype Params struct {\n\tGaussian BloomParams\n\tAiry BloomParams\n\tStar BloomParams\n}\n\ntype BloomParams struct {\n\tRadius float64\n\tAmplitude float64\n\tThreshold float64\n}\n\n\n\nfunc ApplyGaussianBloom(img imagef.Image, pixelSize, radius, amplitude, threshold float64) imagef.Image {\n\twidthPix := radius / pixelSize\n\tnumPix := int(5*widthPix) + 1\n\tK := Gaussian(numPix, widthPix)\n\timg2 := img.Copy()\n\tAddConvolution(img2, img, K, amplitude, threshold)\n\treturn img2\n}\n\nfunc ApplyAiryBloom(img imagef.Image, pixelSize, radius, amplitude, threshold float64) imagef.Image {\n\twidthPix := radius / pixelSize\n\tnumPix := int(8*widthPix) + 1\n\tK := Airy(numPix, widthPix)\n\timg2 := img.Copy()\n\tAddConvolution(img2, img, K, amplitude, threshold)\n\treturn img2\n}\n\nfunc ApplyStarBloom(img imagef.Image, pixelSize, radius, amplitude, threshold float64) imagef.Image {\n\twidthPix := radius / pixelSize\n\tnumPix := int(widthPix)\n\tK := starKernel(numPix)\n\timg2 := img.Copy()\n\tAddConvolution(img2, img, K, amplitude, threshold)\n\treturn img2\n}\n\nfunc (p *Params) ApplyTo(img imagef.Image, pixelSize float64) imagef.Image ", "output": "{\n\tif b := p.Gaussian; b.Radius != 0 {\n\t\timg = ApplyGaussianBloom(img, pixelSize, b.Radius, b.Amplitude, b.Threshold)\n\t}\n\tif b := p.Airy; b.Radius != 0 {\n\t\timg = ApplyAiryBloom(img, pixelSize, b.Radius, b.Amplitude, b.Threshold)\n\t}\n\tif b := p.Star; b.Radius != 0 {\n\t\timg = ApplyStarBloom(img, pixelSize, b.Radius, b.Amplitude, b.Threshold)\n\t}\n\treturn img\n}"} {"input": "package xtest\n\nimport (\n\t\"sync\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\ntype SC struct {\n\tC\n\tsync.WaitGroup\n\tsync.Mutex\n}\n\n\n\nfunc (c *SC) So(actual interface{},\n\tassert func(actual interface{}, expected ...interface{}) string, expected ...interface{}) {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.C.So(actual, assert, expected)\n}\n\nfunc (c *SC) SoMsg(msg string, actual interface{},\n\tassert func(actual interface{}, expected ...interface{}) string, expected ...interface{}) {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.C.SoMsg(msg, actual, assert, expected...)\n}\n\nfunc (c *SC) Recover() {\n\tif r := recover(); r != nil {\n\t\tif rString, ok := r.(string); ok && rString == \"___FAILURE_HALT___\" {\n\t\t\treturn\n\t\t}\n\t\tpanic(r)\n\t}\n}\n\nfunc Parallel(f, g func(sc *SC)) func(c C) {\n\treturn func(c C) {\n\t\tsc := &SC{C: c}\n\t\tsc.Add(1)\n\t\tgo func() {\n\t\t\tdefer sc.Done()\n\t\t\tdefer sc.Recover()\n\t\t\tg(sc)\n\t\t}()\n\t\tdefer sc.Wait()\n\t\tdefer sc.Recover()\n\t\tf(sc)\n\t}\n}\n\n\n\n\n\nfunc SoMsgError(msg string, err error, shouldBeError bool) {\n\tif shouldBeError == true {\n\t\tSoMsg(msg, err, ShouldNotBeNil)\n\t} else {\n\t\tSoMsg(msg, err, ShouldBeNil)\n\t}\n}\n\nfunc (c *SC) Convey(items ...interface{}) ", "output": "{\n\tpanic(\"Convey in SyncConvey Context not supported\")\n}"} {"input": "package config\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/bgentry/go-netrc/netrc\"\n)\n\ntype netrcfinder interface {\n\tFindMachine(string) *netrc.Machine\n}\n\ntype noNetrc struct{}\n\nfunc (n *noNetrc) FindMachine(host string) *netrc.Machine {\n\treturn nil\n}\n\n\n\nfunc (c *Configuration) parseNetrc() (netrcfinder, error) ", "output": "{\n\thome := c.Getenv(\"HOME\")\n\tif len(home) == 0 {\n\t\treturn &noNetrc{}, nil\n\t}\n\n\tnrcfilename := filepath.Join(home, netrcBasename)\n\tif _, err := os.Stat(nrcfilename); err != nil {\n\t\treturn &noNetrc{}, nil\n\t}\n\n\treturn netrc.ParseFile(nrcfilename)\n}"} {"input": "package fe\n\nimport (\n\t\"bytes\"\n\t\"tonika/http\"\n\t\"tonika/sys\"\n)\n\ntype addData struct {\n\tAdminURL string\n}\n\n\n\nfunc (fe *FrontEnd) replyAdminAdd(req *http.Request) *http.Response ", "output": "{\n\tdata := addData{ \n\t\tAdminURL: fe.adminURL, \n\t}\n\tvar w bytes.Buffer\n\terr := fe.tmplAdd.Execute(data, &w)\n\tif err != nil {\n\t\treturn newRespServiceUnavailable()\n\t}\n\tpdata := pageData {\n\t\tTitle: sys.Name + \" — Add contact\",\n\t\tCSSLinks: []string{\"add.css\"},\n\t\tJSLinks: []string{\"jquery.scrollTo-1.4.2-min.js\", \"add.js\"},\n\t\tGridLayout: \"\",\n\t\tContent: w.String(),\n\t}\n\tvar w2 bytes.Buffer\n\terr = fe.tmplPage.Execute(&pdata, &w2)\n\tif err != nil {\n\t\treturn newRespServiceUnavailable()\n\t}\n\treturn buildResp(w2.String())\n}"} {"input": "package fakevtworkerclient\n\nimport (\n\t\"time\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/youtube/vitess/go/vt/logutil\"\n\t\"github.com/youtube/vitess/go/vt/vtctl/fakevtctlclient\"\n\t\"github.com/youtube/vitess/go/vt/worker/vtworkerclient\"\n)\n\n\n\n\ntype FakeVtworkerClient struct {\n\t*fakevtctlclient.FakeLoggerEventStreamingClient\n}\n\n\n\n\n\n\nfunc (f *FakeVtworkerClient) FakeVtworkerClientFactory(addr string, dialTimeout time.Duration) (vtworkerclient.Client, error) {\n\treturn &perAddrFakeVtworkerClient{f, addr}, nil\n}\n\n\n\ntype perAddrFakeVtworkerClient struct {\n\t*FakeVtworkerClient\n\taddr string\n}\n\n\nfunc (c *perAddrFakeVtworkerClient) ExecuteVtworkerCommand(ctx context.Context, args []string) (logutil.EventStream, error) {\n\treturn c.FakeLoggerEventStreamingClient.StreamResult(c.addr, args)\n}\n\n\nfunc (c *perAddrFakeVtworkerClient) Close() {}\n\nfunc NewFakeVtworkerClient() *FakeVtworkerClient ", "output": "{\n\treturn &FakeVtworkerClient{fakevtctlclient.NewFakeLoggerEventStreamingClient()}\n}"} {"input": "package strategy\n\nimport (\n\t\"fmt\"\n\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n\t\"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache\"\n\n\t\"github.com/kubernetes-incubator/cluster-capacity/pkg/framework/store\"\n)\n\ntype Strategy interface {\n\tAdd(obj interface{}) error\n\n\tUpdate(obj interface{}) error\n\n\tDelete(obj interface{}) error\n}\n\ntype predictiveStrategy struct {\n\tresourceStore store.ResourceStore\n\n\tnodeInfo map[string]*schedulercache.NodeInfo\n}\n\nfunc (s *predictiveStrategy) addPod(pod *v1.Pod) error {\n\n\tpod.Status.Phase = v1.PodRunning\n\n\terr := s.resourceStore.Update(\"pods\", metav1.Object(pod))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to add new node: %v\", err)\n\t}\n\n\treturn nil\n}\n\n\n\n\n\n\nfunc (s *predictiveStrategy) Update(obj interface{}) error {\n\treturn fmt.Errorf(\"Not implemented yet\")\n}\n\nfunc (s *predictiveStrategy) Delete(obj interface{}) error {\n\treturn fmt.Errorf(\"Not implemented yet\")\n}\n\nfunc NewPredictiveStrategy(resourceStore store.ResourceStore) *predictiveStrategy {\n\treturn &predictiveStrategy{\n\t\tresourceStore: resourceStore,\n\t}\n}\n\nfunc (s *predictiveStrategy) Add(obj interface{}) error ", "output": "{\n\tswitch item := obj.(type) {\n\tcase *v1.Pod:\n\t\treturn s.addPod(item)\n\tdefault:\n\t\treturn fmt.Errorf(\"resource kind not recognized\")\n\t}\n}"} {"input": "package hook\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\n\t\"github.com/buildkite/agent/v3/bootstrap/shell\"\n\t\"github.com/buildkite/agent/v3/utils\"\n)\n\n\n\n\n\nfunc Find(hookDir string, name string) (string, error) ", "output": "{\n\tif runtime.GOOS == \"windows\" {\n\t\tif p, err := shell.LookPath(name, hookDir, \".BAT;.CMD;.PS1\"); err == nil {\n\t\t\treturn p, nil\n\t\t}\n\t}\n\tif p := filepath.Join(hookDir, name); utils.FileExists(p) {\n\t\treturn p, nil\n\t}\n\treturn \"\", os.ErrNotExist\n}"} {"input": "package graph\n\ntype vertexDistance struct {\n\tvertex string\n\tdistance float64\n}\n\n\n\n\ntype vertexDistanceHeap []vertexDistance\n\nfunc (h vertexDistanceHeap) Len() int { return len(h) }\nfunc (h vertexDistanceHeap) Less(i, j int) bool { return h[i].distance < h[j].distance } \n\n\nfunc (h *vertexDistanceHeap) Push(x interface{}) {\n\t*h = append(*h, x.(vertexDistance))\n}\n\nfunc (h *vertexDistanceHeap) Pop() interface{} {\n\theapSize := len(*h)\n\tlastVertex := (*h)[heapSize-1]\n\t*h = (*h)[0 : heapSize-1]\n\treturn lastVertex\n}\n\nfunc (h *vertexDistanceHeap) updateDistance(vtx string, val float64) {\n\tfor i := 0; i < len(*h); i++ {\n\t\tif (*h)[i].vertex == vtx {\n\t\t\t(*h)[i].distance = val\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (h vertexDistanceHeap) Swap(i, j int) ", "output": "{ h[i], h[j] = h[j], h[i] }"} {"input": "package roles\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestIsTopLevelRole(t *testing.T) {\n\tassert.True(t, IsTopLevelRole(\"root\"))\n\tassert.True(t, IsTopLevelRole(\"targets\"))\n\tassert.True(t, IsTopLevelRole(\"timestamp\"))\n\tassert.True(t, IsTopLevelRole(\"snapshot\"))\n\tassert.False(t, IsTopLevelRole(\"bins\"))\n}\n\nfunc TestIsDelegatedTargetsRole(t *testing.T) {\n\tassert.False(t, IsDelegatedTargetsRole(\"root\"))\n\tassert.False(t, IsDelegatedTargetsRole(\"targets\"))\n\tassert.False(t, IsDelegatedTargetsRole(\"timestamp\"))\n\tassert.False(t, IsDelegatedTargetsRole(\"snapshot\"))\n\tassert.True(t, IsDelegatedTargetsRole(\"deleg\"))\n}\n\n\n\nfunc TestIsDelegatedTargetsManifest(t *testing.T) {\n\tassert.False(t, IsDelegatedTargetsManifest(\"root.json\"))\n\tassert.False(t, IsDelegatedTargetsManifest(\"targets.json\"))\n\tassert.False(t, IsDelegatedTargetsManifest(\"timestamp.json\"))\n\tassert.False(t, IsDelegatedTargetsManifest(\"snapshot.json\"))\n\tassert.True(t, IsDelegatedTargetsManifest(\"bins.json\"))\n}\n\nfunc TestIsVersionedManifest(t *testing.T) {\n\tassert.False(t, IsVersionedManifest(\"a.b\"))\n\tassert.False(t, IsVersionedManifest(\"a.b.c\"))\n\tassert.False(t, IsVersionedManifest(\"a.b.json\"))\n\tassert.False(t, IsVersionedManifest(\"1.a\"))\n\tassert.True(t, IsVersionedManifest(\"1.a.json\"))\n\tassert.True(t, IsVersionedManifest(\"2.a.json\"))\n}\n\nfunc TestIsTopLevelManifest(t *testing.T) ", "output": "{\n\tassert.True(t, IsTopLevelManifest(\"root.json\"))\n\tassert.True(t, IsTopLevelManifest(\"targets.json\"))\n\tassert.True(t, IsTopLevelManifest(\"timestamp.json\"))\n\tassert.True(t, IsTopLevelManifest(\"snapshot.json\"))\n\tassert.False(t, IsTopLevelManifest(\"bins.json\"))\n}"} {"input": "package auth\n\n\nconst GSSAPI = \"GSSAPI\"\n\n\n\nfunc newGSSAPIAuthenticator(cred *Cred) (Authenticator, error) ", "output": "{\n\treturn nil, newAuthError(\"GSSAPI support not enabled during build (-tags gssapi)\", nil)\n}"} {"input": "package core\n\nimport (\n\t\"math/big\"\n\t\"math/rand\"\n\t\"testing\"\n\n\t\"github.com/kejace/go-ethereum/core/types\"\n\t\"github.com/kejace/go-ethereum/crypto\"\n)\n\n\n\n\n\nfunc TestStrictTxListAdd(t *testing.T) ", "output": "{\n\tkey, _ := crypto.GenerateKey()\n\n\ttxs := make(types.Transactions, 1024)\n\tfor i := 0; i < len(txs); i++ {\n\t\ttxs[i] = transaction(uint64(i), new(big.Int), key)\n\t}\n\tlist := newTxList(true)\n\tfor _, v := range rand.Perm(len(txs)) {\n\t\tlist.Add(txs[v])\n\t}\n\tif len(list.txs.items) != len(txs) {\n\t\tt.Errorf(\"transaction count mismatch: have %d, want %d\", len(list.txs.items), len(txs))\n\t}\n\tfor i, tx := range txs {\n\t\tif list.txs.items[tx.Nonce()] != tx {\n\t\t\tt.Errorf(\"item %d: transaction mismatch: have %v, want %v\", i, list.txs.items[tx.Nonce()], tx)\n\t\t}\n\t}\n}"} {"input": "package types\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v1\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nvar expectedLD1String = \"vfs=vfs-000::/dev/xvda,vfs-001::/dev/xvdb,vfs-002::/dev/xvdc\"\n\nfunc TestLocalDevicesMarshalText(t *testing.T) {\n\n\tld1 := newLocalDevicesObj()\n\tassert.Equal(t, expectedLD1String, ld1.String())\n\tt.Logf(\"localDevices=%s\", ld1)\n\n\tld2 := &LocalDevices{}\n\tassert.NoError(t, ld2.UnmarshalText([]byte(ld1.String())))\n\tassert.EqualValues(t, ld1, ld2)\n}\n\nfunc TestLocalDevicesUnmarshalText(t *testing.T) {\n\n\tld1 := &LocalDevices{}\n\terr := ld1.UnmarshalText([]byte(\"scaleio=\"))\n\tassert.NoError(t, err)\n}\n\nfunc TestLocalDevicesMarshalJSON(t *testing.T) {\n\n\tld1 := newLocalDevicesObj()\n\n\tbuf, err := ld1.MarshalJSON()\n\tassert.NoError(t, err)\n\tt.Logf(\"localDevices=%s\", string(buf))\n\n\tld2 := &LocalDevices{}\n\tassert.NoError(t, ld2.UnmarshalJSON(buf))\n\n\tassert.EqualValues(t, ld1, ld2)\n}\n\nfunc TestLocalDevicesMarshalToYAML(t *testing.T) {\n\tout, err := yaml.Marshal(newLocalDevicesObj())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfmt.Println(string(out))\n}\n\nfunc newLocalDevicesObj() *LocalDevices ", "output": "{\n\treturn &LocalDevices{\n\t\tDriver: \"vfs\",\n\t\tDeviceMap: map[string]string{\n\t\t\t\"vfs-000\": \"/dev/xvda\",\n\t\t\t\"vfs-001\": \"/dev/xvdb\",\n\t\t\t\"vfs-002\": \"/dev/xvdc\",\n\t\t},\n\t}\n}"} {"input": "package ultralist\n\n\ntype MemoryPrinter struct {\n\tGroups *GroupedTodos\n}\n\n\n\n\nfunc (m *MemoryPrinter) Print(groupedTodos *GroupedTodos, printNotes bool) ", "output": "{\n\tm.Groups = groupedTodos\n}"} {"input": "package mmap\n\nimport \"sync\"\n\ntype tbl struct {\n\tm map[int64][]byte \n\tl sync.RWMutex\n}\n\nfunc newTbl() *tbl {\n\treturn &tbl{m: make(map[int64][]byte)}\n}\n\n\n\nfunc (t *tbl) Values() (res [][]byte) {\n\tt.l.RLock()\n\tfor _, v := range t.m {\n\t\tres = append(res, v)\n\t}\n\tt.l.RUnlock()\n\treturn\n}\n\nfunc (t *tbl) Get(idx int64, f func() ([]byte, error)) (b []byte, err error) ", "output": "{\n\tt.l.RLock()\n\tb, ok := t.m[idx]\n\tt.l.RUnlock()\n\n\tif ok {\n\t\treturn\n\t}\n\n\tt.l.Lock()\n\tdefer t.l.Unlock()\n\n\tb, ok = t.m[idx]\n\tif ok {\n\t\treturn\n\t}\n\n\tb, err = f()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tt.m[idx] = b\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strings\"\n)\n\n\n\n\n\nfunc MakeRemoveMessage(pkg *Package) string {\n\treturn fmt.Sprintf(\"REMOVE|%s|\", pkg.Name)\n}\n\n\nfunc MakeQueryMessage(pkg *Package) string {\n\treturn fmt.Sprintf(\"QUERY|%s|\", pkg.Name)\n}\n\nvar possibleInvalidCommands = []string{\"BLINDEX\", \"REMOVES\", \"QUER\", \"LIZARD\", \"I\"}\nvar possibleInvalidChars = []string{\"=\", \"+\", \"☃\", \" \"}\n\n\n\nfunc MakeBrokenMessage() string {\n\tsyntaxError := rand.Intn(10)%2 == 0\n\n\tif syntaxError {\n\t\tinvalidChar := possibleInvalidChars[rand.Intn(len(possibleInvalidChars))]\n\t\treturn fmt.Sprintf(\"INDEX|emacs%selisp\", invalidChar)\n\t}\n\n\tinvalidCommand := possibleInvalidCommands[rand.Intn(len(possibleInvalidCommands))]\n\treturn fmt.Sprintf(\"%s|a|b\", invalidCommand)\n}\n\nfunc MakeIndexMessage(pkg *Package) string ", "output": "{\n\tdependenciesNames := []string{}\n\n\tfor _, dep := range pkg.Dependencies {\n\t\tdependenciesNames = append(dependenciesNames, dep.Name)\n\t}\n\n\tnamesAsString := strings.Join(dependenciesNames, \",\")\n\treturn fmt.Sprintf(\"INDEX|%s|%s\", pkg.Name, namesAsString)\n}"} {"input": "package glfw\n\n\n\nimport \"C\"\n\nimport (\n\t\"reflect\"\n\t\"unsafe\"\n)\n\n\n\nfunc bytes(origin []byte) (pointer *uint8, free func()) {\n\tn := len(origin)\n\n\tif n == 0 {\n\t\treturn nil, func() {}\n\t}\n\n\tdata := C.malloc(C.size_t(n))\n\n\tdataSlice := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{\n\t\tData: uintptr(data),\n\t\tLen: n,\n\t\tCap: n,\n\t}))\n\n\tcopy(dataSlice, origin)\n\n\treturn &dataSlice[0], func() { C.free(data) }\n}\n\nfunc glfwbool(b C.int) bool ", "output": "{\n\tif b == C.GL_TRUE {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package log\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"sync\"\n)\n\nconst (\n\tSilent int = iota\n\tError\n\tInfo\n\tDebug\n)\n\n\nvar (\n\tlevel = Error\n\tlock sync.Mutex\n)\n\n\nfunc SetLevel(l int) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tlevel = l\n}\n\n\n\n\n\nfunc Debugf(format string, args ...interface{}) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif level < Debug {\n\t\treturn\n\t}\n\n\tmsg := fmt.Sprintf(\"DEBUG: %s\", format)\n\tif len(args) > 0 {\n\t\tmsg = fmt.Sprintf(msg, args...)\n\t}\n\n\tlog.Println(msg)\n}\n\n\nfunc Errorf(format string, args ...interface{}) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif level < Error {\n\t\treturn\n\t}\n\n\tmsg := fmt.Sprintf(\"ERROR: %s\", format)\n\tif len(args) > 0 {\n\t\tmsg = fmt.Sprintf(msg, args...)\n\t}\n\n\tlog.Println(msg)\n}\n\nfunc Infof(format string, args ...interface{}) ", "output": "{\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif level < Info {\n\t\treturn\n\t}\n\n\tmsg := fmt.Sprintf(\"INFO: %s\", format)\n\tif len(args) > 0 {\n\t\tmsg = fmt.Sprintf(msg, args...)\n\t}\n\n\tlog.Println(msg)\n}"} {"input": "package vox\n\ntype Block uint8\n\nconst (\n\tBlockNil = 0x00\n\tblockActiveMask = 0x80 \n\tblockTypeMask = 0x7F \n)\n\nfunc (b Block) Active() bool {\n\treturn (blockActiveMask & b) == blockActiveMask\n}\n\nfunc (b Block) Activate(active bool) Block {\n\tif active {\n\t\treturn b | blockActiveMask\n\t}\n\treturn b & blockTypeMask\n}\n\nfunc (b Block) TypeID() uint8 {\n\treturn uint8(b & blockTypeMask)\n}\n\nfunc (b Block) ChangeType(t *BlockType) Block {\n\treturn Block((uint8(b) & blockActiveMask) | t.ID)\n}\n\ntype BlockType struct {\n\tID uint8\n\tTop *TextureRegion\n\tBottom *TextureRegion\n\tSide *TextureRegion\n}\n\ntype BlockBank struct {\n\tTypes []*BlockType\n\ttypeMap map[uint8]*BlockType\n}\n\nfunc NewBlockBank() *BlockBank {\n\treturn &BlockBank{\n\t\ttypeMap: make(map[uint8]*BlockType),\n\t}\n}\n\nfunc (b *BlockBank) AddType(blockType *BlockType) {\n\tb.typeMap[blockType.ID] = blockType\n\tb.Types = append(b.Types, blockType)\n}\n\n\n\nfunc (b *BlockBank) TypeOf(block Block) *BlockType ", "output": "{\n\treturn b.typeMap[block.TypeID()]\n}"} {"input": "package taskqueue\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/nevsnode/gordon/utils\"\n\t\"os\"\n\t\"strings\"\n)\n\n\ntype QueueTask struct {\n\tArgs []string `json:\"args\"` \n\tEnv map[string]string `json:\"env\"` \n\tErrorMessage string `json:\"error_message,omitempty\"` \n}\n\n\n\n\n\nfunc (q QueueTask) GetJSONString() (value string, err error) {\n\tif q.Args == nil {\n\t\tq.Args = make([]string, 0)\n\t}\n\tif q.Env == nil {\n\t\tq.Env = make(map[string]string)\n\t}\n\n\tb, err := json.Marshal(q)\n\tvalue = fmt.Sprintf(\"%s\", b)\n\treturn\n}\n\n\nfunc NewQueueTask(redisValue string) (task QueueTask, err error) {\n\treader := strings.NewReader(redisValue)\n\tparser := json.NewDecoder(reader)\n\terr = parser.Decode(&task)\n\treturn\n}\n\nfunc (q QueueTask) Execute(script string) error ", "output": "{\n\tcmd := utils.ExecCommand(script, q.Args...)\n\n\tcmd.Env = os.Environ()\n\tfor envKey, envVal := range q.Env {\n\t\tcmd.Env = append(cmd.Env, envKey+\"=\"+envVal)\n\t}\n\n\tout, err := cmd.Output()\n\n\tif len(out) != 0 && err == nil {\n\t\terr = fmt.Errorf(\"%s\", out)\n\t}\n\n\treturn err\n}"} {"input": "package v1beta1\n\n\n\ntype IngressRuleValueApplyConfiguration struct {\n\tHTTP *HTTPIngressRuleValueApplyConfiguration `json:\"http,omitempty\"`\n}\n\n\n\nfunc IngressRuleValue() *IngressRuleValueApplyConfiguration {\n\treturn &IngressRuleValueApplyConfiguration{}\n}\n\n\n\n\n\n\nfunc (b *IngressRuleValueApplyConfiguration) WithHTTP(value *HTTPIngressRuleValueApplyConfiguration) *IngressRuleValueApplyConfiguration ", "output": "{\n\tb.HTTP = value\n\treturn b\n}"} {"input": "package errors\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\ntype testWrapped struct {\n\terror\n}\n\nfunc (w *testWrapped) Error() string {\n\tif w.error == nil {\n\t\treturn \"wrapped: nil\"\n\t}\n\treturn fmt.Sprintf(\"wrapped: %v\", w.error.Error())\n}\n\nfunc (w *testWrapped) Unwrap() error {\n\treturn w.error\n}\n\n\n\nfunc TestWrapped(t *testing.T) {\n\tt.Parallel()\n\n\tConvey(`Test Wrapped`, t, func() {\n\t\tConvey(`A nil error`, func() {\n\t\t\tvar err error\n\n\t\t\tConvey(`Unwraps to nil.`, func() {\n\t\t\t\tSo(Unwrap(err), ShouldBeNil)\n\t\t\t})\n\n\t\t\tConvey(`When wrapped, does not unwrap to nil.`, func() {\n\t\t\t\tSo(Unwrap(testWrap(err)), ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\n\t\tConvey(`A non-wrapped error.`, func() {\n\t\t\terr := New(\"test error\")\n\n\t\t\tConvey(`Unwraps to itself.`, func() {\n\t\t\t\tSo(Unwrap(err), ShouldEqual, err)\n\t\t\t})\n\n\t\t\tConvey(`When wrapped, unwraps to itself.`, func() {\n\t\t\t\tSo(Unwrap(testWrap(err)), ShouldEqual, err)\n\t\t\t})\n\n\t\t\tConvey(`When double-wrapped, unwraps to itself.`, func() {\n\t\t\t\tSo(Unwrap(testWrap(testWrap(err))), ShouldEqual, err)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc testWrap(err error) error ", "output": "{\n\treturn &testWrapped{err}\n}"} {"input": "package sarama\n\n\ntype ApiVersionsRequest struct{}\n\nfunc (a *ApiVersionsRequest) encode(pe packetEncoder) error {\n\treturn nil\n}\n\nfunc (a *ApiVersionsRequest) decode(pd packetDecoder, version int16) (err error) {\n\treturn nil\n}\n\nfunc (a *ApiVersionsRequest) key() int16 {\n\treturn 18\n}\n\nfunc (a *ApiVersionsRequest) version() int16 {\n\treturn 0\n}\n\nfunc (a *ApiVersionsRequest) headerVersion() int16 {\n\treturn 1\n}\n\n\n\nfunc (a *ApiVersionsRequest) requiredVersion() KafkaVersion ", "output": "{\n\treturn V0_10_0_0\n}"} {"input": "package sdk\n\nimport (\n\t\"io/ioutil\"\n\t\"net/url\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\ntype hydraConfig struct {\n\tClusterURL string `yaml:\"cluster_url\"`\n\tClientID string `yaml:\"client_id\"`\n\tClientSecret string `yaml:\"client_secret\"`\n}\n\n\nfunc FromYAML(file string) option {\n\treturn func(c *Client) error {\n\t\tvar err error\n\t\tvar config = hydraConfig{}\n\n\t\tdata, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = yaml.Unmarshal(data, &config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.clusterURL, err = url.Parse(config.ClusterURL)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.clientID = config.ClientID\n\t\tc.clientSecret = config.ClientSecret\n\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc ClusterURL(urlStr string) option {\n\treturn func(c *Client) error {\n\t\tvar err error\n\t\tc.clusterURL, err = url.Parse(urlStr)\n\t\treturn err\n\t}\n}\n\n\n\n\n\n\n\nfunc ClientID(id string) option {\n\treturn func(c *Client) error {\n\t\tc.clientID = id\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc ClientSecret(secret string) option {\n\treturn func(c *Client) error {\n\t\tc.clientSecret = secret\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Scopes(scopes ...string) option {\n\treturn func(c *Client) error {\n\t\tc.scopes = scopes\n\t\treturn nil\n\t}\n}\n\nfunc SkipTLSVerify() option ", "output": "{\n\treturn func(c *Client) error {\n\t\tc.skipTLSVerify = true\n\t\treturn nil\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/ehazlett/steamwire/types\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tbaseURL = \"http://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=%s&count=%d&maxlength=%d&format=json\"\n)\n\nfunc buildURL(appID string, count int, maxLength int) string {\n\treturn fmt.Sprintf(baseURL, appID, count, maxLength)\n}\n\n\n\n\n\nfunc (s *Server) getNews(appID string) (*types.AppNews, error) ", "output": "{\n\tu := buildURL(appID, 1, 1024)\n\tresp, err := http.Get(u)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapp := &types.App{}\n\tif err := json.NewDecoder(resp.Body).Decode(&app); err != nil {\n\t\tlogrus.Errorf(\"error decoding: %s\", err)\n\t\treturn nil, err\n\t}\n\n\treturn app.AppNews, nil\n}"} {"input": "package clientv3_test\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/coreos/etcd/clientv3\"\n)\n\nfunc ExampleCluster_memberList() {\n\tcli, err := clientv3.New(clientv3.Config{\n\t\tEndpoints: endpoints,\n\t\tDialTimeout: dialTimeout,\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer cli.Close()\n\n\tresp, err := cli.MemberList(context.Background())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"members:\", len(resp.Members))\n}\n\nfunc ExampleCluster_memberAdd() {\n\tcli, err := clientv3.New(clientv3.Config{\n\t\tEndpoints: endpoints[:2],\n\t\tDialTimeout: dialTimeout,\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer cli.Close()\n\n\tpeerURLs := endpoints[2:]\n\tmresp, err := cli.MemberAdd(context.Background(), peerURLs)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"added member.PeerURLs:\", mresp.Member.PeerURLs)\n}\n\nfunc ExampleCluster_memberRemove() {\n\tcli, err := clientv3.New(clientv3.Config{\n\t\tEndpoints: endpoints[1:],\n\t\tDialTimeout: dialTimeout,\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer cli.Close()\n\n\tresp, err := cli.MemberList(context.Background())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t_, err = cli.MemberRemove(context.Background(), resp.Members[0].ID)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\n\nfunc ExampleCluster_memberUpdate() ", "output": "{\n\tcli, err := clientv3.New(clientv3.Config{\n\t\tEndpoints: endpoints,\n\t\tDialTimeout: dialTimeout,\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer cli.Close()\n\n\tresp, err := cli.MemberList(context.Background())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpeerURLs := []string{\"http:localhost:12380\"}\n\t_, err = cli.MemberUpdate(context.Background(), resp.Members[0].ID, peerURLs)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"input": "package dataintegration\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateExternalPublicationRequest struct {\n\n\tWorkspaceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"workspaceId\"`\n\n\tTaskKey *string `mandatory:\"true\" contributesTo:\"path\" name:\"taskKey\"`\n\n\tCreateExternalPublicationDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateExternalPublicationRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateExternalPublicationRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CreateExternalPublicationRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CreateExternalPublicationRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateExternalPublicationResponse struct {\n\n\tRawResponse *http.Response\n\n\tExternalPublication `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response CreateExternalPublicationResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response CreateExternalPublicationResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package gochimp\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype APIError struct {\n\tStatus string `json:\"status\"`\n\tCode int `json:\"code\"`\n\tName string `json:\"name\"`\n\tErr string `json:\"error\"`\n}\n\nfunc (e APIError) Error() string {\n\treturn fmt.Sprintf(\"%v: %v\", e.Code, e.Err)\n}\n\n\n\n\ntype APITime struct {\n\ttime.Time\n}\n\nfunc (t *APITime) UnmarshalJSON(data []byte) (err error) {\n\ts := string(data)\n\tl := len(s)\n\tswitch {\n\tcase l == 12:\n\t\tt.Time, err = time.Parse(`\"2006-01-02\"`, s)\n\tcase l == 21:\n\t\tt.Time, err = time.Parse(`\"2006-01-02 15:04:05\"`, s)\n\tcase l == 9:\n\t\tt.Time, err = time.Parse(`\"2006-01\"`, s)\n\t}\n\treturn\n}\n\n\nconst APITimeFormat = \"2006-01-02 15:04:05\"\n\nfunc apiTime(t interface{}) interface{} {\n\tswitch ti := t.(type) {\n\tcase time.Time:\n\t\treturn ti.Format(APITimeFormat)\n\tcase string:\n\t\treturn ti\n\t}\n\treturn t\n}\n\nfunc chimpErrorCheck(body []byte) error ", "output": "{\n\tvar e APIError\n\tjson.Unmarshal(body, &e)\n\tif e.Err != \"\" || e.Code != 0 {\n\t\treturn e\n\t}\n\treturn nil\n}"} {"input": "package pathdb\n\nimport (\n\t\"github.com/scionproto/scion/go/lib/common\"\n\t\"github.com/scionproto/scion/go/lib/ctrl/seg\"\n\t\"github.com/scionproto/scion/go/lib/pathdb/conn\"\n\t\"github.com/scionproto/scion/go/lib/pathdb/query\"\n\t\"github.com/scionproto/scion/go/lib/pathdb/sqlite\"\n)\n\ntype DB struct {\n\tconn conn.Conn\n}\n\n\n\nfunc New(path string, backend string) (*DB, error) {\n\tdb := &DB{}\n\tvar err error\n\tswitch backend {\n\tcase \"sqlite\":\n\t\tdb.conn, err = sqlite.New(path)\n\tdefault:\n\t\treturn nil, common.NewBasicError(\"Unknown backend\", nil, \"backend\", backend)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn db, nil\n}\n\n\n\nfunc (db *DB) Insert(pseg *seg.PathSegment, segTypes []seg.Type) (int, error) {\n\treturn db.conn.Insert(pseg, segTypes)\n}\n\n\n\nfunc (db *DB) InsertWithHPCfgIDs(pseg *seg.PathSegment,\n\tsegTypes []seg.Type, hpCfgIDs []*query.HPCfgID) (int, error) {\n\treturn db.conn.InsertWithHPCfgIDs(pseg, segTypes, hpCfgIDs)\n}\n\n\n\n\n\n\n\nfunc (db *DB) DeleteWithIntf(intf query.IntfSpec) (int, error) {\n\treturn db.conn.DeleteWithIntf(intf)\n}\n\n\nfunc (db *DB) Get(params *query.Params) ([]*query.Result, error) {\n\treturn db.conn.Get(params)\n}\n\nfunc (db *DB) Delete(segID common.RawBytes) (int, error) ", "output": "{\n\treturn db.conn.Delete(segID)\n}"} {"input": "package errs\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/uther/go-uther/logger\"\n)\n\nfunc testErrors() *Errors {\n\treturn &Errors{\n\t\tPackage: \"TEST\",\n\t\tErrors: map[int]string{\n\t\t\t0: \"zero\",\n\t\t\t1: \"one\",\n\t\t},\n\t\tLevel: func(i int) (l logger.LogLevel) {\n\t\t\tif i == 0 {\n\t\t\t\tl = logger.ErrorLevel\n\t\t\t} else {\n\t\t\t\tl = logger.WarnLevel\n\t\t\t}\n\t\t\treturn\n\t\t},\n\t}\n}\n\n\n\nfunc TestErrorSeverity(t *testing.T) {\n\terr0 := testErrors().New(0, \"zero detail\")\n\tif !err0.Fatal() {\n\t\tt.Errorf(\"error should be fatal\")\n\t}\n\terr1 := testErrors().New(1, \"one detail\")\n\tif err1.Fatal() {\n\t\tt.Errorf(\"error should not be fatal\")\n\t}\n}\n\nfunc TestErrorMessage(t *testing.T) ", "output": "{\n\terr := testErrors().New(0, \"zero detail %v\", \"available\")\n\tmessage := fmt.Sprintf(\"%v\", err)\n\texp := \"[TEST] ERROR: zero: zero detail available\"\n\tif message != exp {\n\t\tt.Errorf(\"error message incorrect. expected %v, got %v\", exp, message)\n\t}\n}"} {"input": "package bot\n\nimport(\n \"github.com/mduszyk/foobot/proto\"\n \"github.com/mduszyk/foobot/module\"\n)\n\ntype HelpModule struct {\n bot *Bot\n}\n\n\n\nfunc (m *HelpModule) CMD_(msg *proto.Msg) string {\n rsp := \"\"\n for k, v := range m.bot.GetModules() {\n rsp += \" \" + k\n methods := module.CmdMethods(v)\n if len(methods) > 0 {\n rsp += \" (\" + methods + \")\"\n }\n rsp += \"\\n\"\n }\n\n return rsp\n}\n\nfunc (m *HelpModule) Handle(msg *proto.Msg) string {\n return module.CallCmdMethod(m, msg)\n}\n\nfunc NewHelpModule(bot *Bot) *HelpModule ", "output": "{\n return &HelpModule{bot}\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realIAMInstanceProfile IAMInstanceProfile\n\nfunc (o *IAMInstanceProfile) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realIAMInstanceProfile\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = IAMInstanceProfile(r)\n\treturn nil\n}\n\nvar _ fi.HasName = &IAMInstanceProfile{}\n\nfunc (e *IAMInstanceProfile) GetName() *string {\n\treturn e.Name\n}\n\n\n\nfunc (e *IAMInstanceProfile) String() string {\n\treturn fi.TaskAsString(e)\n}\n\nfunc (e *IAMInstanceProfile) SetName(name string) ", "output": "{\n\te.Name = &name\n}"} {"input": "package leakcheck\n\nimport (\n\t\"runtime\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar goroutinesToIgnore = []string{\n\t\"testing.Main(\",\n\t\"testing.tRunner(\",\n\t\"testing.(*M).\",\n\t\"runtime.goexit\",\n\t\"created by runtime.gc\",\n\t\"created by runtime/trace.Start\",\n\t\"interestingGoroutines\",\n\t\"runtime.MHeap_Scavenger\",\n\t\"signal.signal_recv\",\n\t\"sigterm.handler\",\n\t\"runtime_mcall\",\n\t\"(*loggingT).flushDaemon\",\n\t\"goroutine in C code\",\n}\n\n\n\n\nfunc RegisterIgnoreGoroutine(s string) {\n\tgoroutinesToIgnore = append(goroutinesToIgnore, s)\n}\n\n\n\n\n\nfunc interestingGoroutines() (gs []string) {\n\tbuf := make([]byte, 2<<20)\n\tbuf = buf[:runtime.Stack(buf, true)]\n\tfor _, g := range strings.Split(string(buf), \"\\n\\n\") {\n\t\tif !ignore(g) {\n\t\t\tgs = append(gs, g)\n\t\t}\n\t}\n\tsort.Strings(gs)\n\treturn\n}\n\n\n\ntype Errorfer interface {\n\tErrorf(format string, args ...interface{})\n}\n\nfunc check(efer Errorfer, timeout time.Duration) {\n\tdeadline := time.Now().Add(timeout)\n\tvar leaked []string\n\tfor time.Now().Before(deadline) {\n\t\tif leaked = interestingGoroutines(); len(leaked) == 0 {\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(50 * time.Millisecond)\n\t}\n\tfor _, g := range leaked {\n\t\tefer.Errorf(\"Leaked goroutine: %v\", g)\n\t}\n}\n\n\n\n\nfunc Check(efer Errorfer) {\n\tcheck(efer, 10*time.Second)\n}\n\nfunc ignore(g string) bool ", "output": "{\n\tsl := strings.SplitN(g, \"\\n\", 2)\n\tif len(sl) != 2 {\n\t\treturn true\n\t}\n\tstack := strings.TrimSpace(sl[1])\n\tif strings.HasPrefix(stack, \"testing.RunTests\") {\n\t\treturn true\n\t}\n\n\tif stack == \"\" {\n\t\treturn true\n\t}\n\n\tfor _, s := range goroutinesToIgnore {\n\t\tif strings.Contains(stack, s) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package resource\n\nimport (\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"github.com/pkg/errors\"\n\t\"io\"\n)\n\n\nfunc Encrypt(key []byte, text string) (string, error) {\n\tplaintext := []byte(text)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\n\treturn base64.URLEncoding.EncodeToString(ciphertext), nil\n}\n\n\n\n\nfunc Decrypt(key []byte, cryptoText string) (string, error) ", "output": "{\n\tciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(ciphertext) < aes.BlockSize {\n\t\treturn \"\", errors.New(\"Chipher text too short\")\n\t}\n\tiv := ciphertext[:aes.BlockSize]\n\tciphertext = ciphertext[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\n\tstream.XORKeyStream(ciphertext, ciphertext)\n\n\treturn fmt.Sprintf(\"%s\", ciphertext), nil\n}"} {"input": "package code\n\nimport (\n\t\"github.com/telecoda/pico-go/console\"\n)\n\n\n\ntype cartridge struct {\n\t*console.BaseCartridge\n}\n\n\n\n\n\nfunc (c *cartridge) Init() {\n\tc.ClsWithColor(console.PICO8_BLUE)\n}\n\n\nfunc (c *cartridge) Update() {\n}\n\n\nfunc (c *cartridge) Render() {\n\tc.Cls()\n\tc.PrintAtWithColor(\"INPUT:\", 50, 5, console.PICO8_WHITE)\n\tc.Line(0, 12, 128, 12)\n\n\tc.PrintAtWithColor(\"UP:\", 20, 30, console.PICO8_WHITE)\n\tif c.Btn(console.P1_BUTT_UP) {\n\t\tc.PrintAtWithColor(\"PRESSED\", 48, 30, console.PICO8_WHITE)\n\t}\n\n\tc.PrintAtWithColor(\"DOWN:\", 20, 50, console.PICO8_WHITE)\n\tif c.Btn(console.P1_BUTT_DOWN) {\n\t\tc.PrintAtWithColor(\"PRESSED\", 48, 50, console.PICO8_WHITE)\n\t}\n\n\tc.PrintAtWithColor(\"LEFT:\", 20, 70, console.PICO8_WHITE)\n\tif c.Btn(console.P1_BUTT_LEFT) {\n\t\tc.PrintAtWithColor(\"PRESSED\", 48, 70, console.PICO8_WHITE)\n\t}\n\n\tc.PrintAtWithColor(\"RIGHT:\", 20, 90, console.PICO8_WHITE)\n\tif c.Btn(console.P1_BUTT_RIGHT) {\n\t\tc.PrintAtWithColor(\"PRESSED\", 48, 90, console.PICO8_WHITE)\n\t}\n}\n\nfunc NewCart() console.Cartridge ", "output": "{\n\treturn &cartridge{\n\t\tBaseCartridge: console.NewBaseCart(),\n\t}\n}"} {"input": "package command\n\nimport (\n\t\"github.com/goodmustache/pt/actor\"\n\t\"github.com/goodmustache/pt/command/display\"\n)\n\n\n\ntype ProjectListActor interface {\n\tProjects() ([]actor.Project, error)\n}\n\ntype ProjectList struct {\n\tUserID uint64 `short:\"u\" long:\"user-id\" description:\"User ID to run commands with\"`\n\n\tActor ProjectListActor\n\tUI UI\n}\n\n\n\nfunc (cmd ProjectList) Execute(_ []string) error ", "output": "{\n\tprojects, err := cmd.Actor.Projects()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdisplayProjects := make([]display.ProjectRow, 0, len(projects))\n\tfor _, project := range projects {\n\t\tdisplayProjects = append(displayProjects, display.ProjectRow{\n\t\t\tID: project.ID,\n\t\t\tName: project.Name,\n\t\t\tDescription: project.Description,\n\t\t\tVisibility: project.Visibility(),\n\t\t})\n\t}\n\n\tcmd.UI.PrintTable(displayProjects)\n\treturn nil\n}"} {"input": "package testhelpers\n\nimport \"github.com/go-kit/kit/metrics\"\n\n\ntype CollectingCounter struct {\n\tCounterValue float64\n\tLastLabelValues []string\n}\n\n\nfunc (c *CollectingCounter) With(labelValues ...string) metrics.Counter {\n\tc.LastLabelValues = labelValues\n\treturn c\n}\n\n\nfunc (c *CollectingCounter) Add(delta float64) {\n\tc.CounterValue += delta\n}\n\n\ntype CollectingGauge struct {\n\tGaugeValue float64\n\tLastLabelValues []string\n}\n\n\nfunc (g *CollectingGauge) With(labelValues ...string) metrics.Gauge {\n\tg.LastLabelValues = labelValues\n\treturn g\n}\n\n\nfunc (g *CollectingGauge) Set(value float64) {\n\tg.GaugeValue = value\n}\n\n\n\n\n\ntype CollectingHealthCheckMetrics struct {\n\tGauge *CollectingGauge\n}\n\n\nfunc (m *CollectingHealthCheckMetrics) BackendServerUpGauge() metrics.Gauge {\n\treturn m.Gauge\n}\n\n\nfunc NewCollectingHealthCheckMetrics() *CollectingHealthCheckMetrics {\n\treturn &CollectingHealthCheckMetrics{&CollectingGauge{}}\n}\n\nfunc (g *CollectingGauge) Add(delta float64) ", "output": "{\n\tg.GaugeValue = delta\n}"} {"input": "package netutil\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype ConnWrapper struct {\n\tio.Reader\n\tio.Writer\n\tUnderlyingConn net.Conn\n\tReadCloser io.Closer\n\tWriteCloser io.Closer\n}\n\nvar _ net.Conn = new(ConnWrapper)\n\nfunc (c *ConnWrapper) Close() error {\n\tvar multiErr MultiError\n\tif c.ReadCloser != nil {\n\t\tmultiErr.RecordError(c.ReadCloser.Close())\n\t}\n\tif c.WriteCloser != nil {\n\t\tmultiErr.RecordError(c.WriteCloser.Close())\n\t}\n\tmultiErr.RecordError(c.UnderlyingConn.Close())\n\treturn multiErr.ToError()\n}\n\n\nfunc (c *ConnWrapper) RemoteAddr() net.Addr { return c.UnderlyingConn.RemoteAddr() }\nfunc (c *ConnWrapper) SetDeadline(t time.Time) error { return c.UnderlyingConn.SetDeadline(t) }\nfunc (c *ConnWrapper) SetReadDeadline(t time.Time) error { return c.UnderlyingConn.SetReadDeadline(t) }\nfunc (c *ConnWrapper) SetWriteDeadline(t time.Time) error { return c.UnderlyingConn.SetWriteDeadline(t) }\n\nfunc (c *ConnWrapper) LocalAddr() net.Addr ", "output": "{ return c.UnderlyingConn.LocalAddr() }"} {"input": "package core \n\nimport (\n\t\"sync\"\n\n\t\"barista.run/bar\"\n\tl \"barista.run/logging\"\n\t\"barista.run/sink\"\n)\n\n\n\ntype ModuleSet struct {\n\tmodules []*Module\n\tupdateCh chan int\n\toutputs []bar.Segments\n\toutputsMu sync.RWMutex\n}\n\n\nfunc NewModuleSet(modules []bar.Module) *ModuleSet {\n\tset := &ModuleSet{\n\t\tmodules: make([]*Module, len(modules)),\n\t\toutputs: make([]bar.Segments, len(modules)),\n\t\tupdateCh: make(chan int),\n\t}\n\tfor i, m := range modules {\n\t\tl.Fine(\"%s added as %s[%d]\", l.ID(m), l.ID(set), i)\n\t\tset.modules[i] = NewModule(m)\n\t}\n\treturn set\n}\n\n\n\nfunc (m *ModuleSet) Stream() <-chan int {\n\tfor i, mod := range m.modules {\n\t\tgo mod.Stream(m.sinkFn(i))\n\t}\n\treturn m.updateCh\n}\n\n\n\n\nfunc (m *ModuleSet) Len() int {\n\treturn len(m.modules)\n}\n\n\n\nfunc (m *ModuleSet) LastOutput(idx int) bar.Segments {\n\tm.outputsMu.RLock()\n\tdefer m.outputsMu.RUnlock()\n\treturn m.outputs[idx]\n}\n\n\n\n\nfunc (m *ModuleSet) LastOutputs() []bar.Segments {\n\tm.outputsMu.RLock()\n\tdefer m.outputsMu.RUnlock()\n\tcp := make([]bar.Segments, len(m.outputs))\n\tcopy(cp, m.outputs)\n\treturn cp\n}\n\nfunc (m *ModuleSet) sinkFn(idx int) bar.Sink ", "output": "{\n\treturn sink.Func(func(out bar.Segments) {\n\t\tl.Fine(\"%s new output from %s\",\n\t\t\tl.ID(m), l.ID(m.modules[idx].original))\n\t\tm.outputsMu.Lock()\n\t\tm.outputs[idx] = out\n\t\tm.outputsMu.Unlock()\n\t\tm.updateCh <- idx\n\t})\n}"} {"input": "package srtgears\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\nconst newLine = \"\\r\\n\" \n\n\ntype writer struct {\n\tw io.Writer \n\terr error \n}\n\n\n\n\n\nfunc (w *writer) prn(a ...interface{}) {\n\tw.pr(a...)\n\tw.pr(newLine)\n}\n\n\nfunc (w *writer) prf(format string, a ...interface{}) {\n\tif w.err == nil {\n\t\t_, w.err = fmt.Fprintf(w.w, format, a...)\n\t}\n}\n\nfunc (w *writer) pr(a ...interface{}) ", "output": "{\n\tif w.err == nil {\n\t\t_, w.err = fmt.Fprint(w.w, a...)\n\t}\n}"} {"input": "package main\n\nfunc main() {\n\tx := \"Hello World\"\n\tch := make(chan string)\n\tf(ch)\n\tsink(x)\n\tx = source()\n\tch <- x\n}\n\n\n\nfunc sink(s string) {\n}\n\nfunc source() string {\n\treturn \"secret\"\n}\n\nfunc f(ch chan string) ", "output": "{\n\tgo func() {\n\t\ty := <-ch\n\t\tsink(y)\n\t}()\n}"} {"input": "package main\n\n\n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"github.com/bearded-web/bearded/pkg/script\"\n\t\"github.com/davecgh/go-spew/spew\"\n\n\t\"github.com/bearded-web/bearded/pkg/transport/mango\"\n\t\"github.com/bearded-web/wappalyzer-script/wappalyzer\"\n)\n\n\n\nfunc main() {\n\trun(\"tcp://:9238\")\n}\n\nfunc run(addr string) ", "output": "{\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\ttransp, err := mango.NewServer(addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tclient, err := script.NewRemoteClient(transp)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tgo func() {\n\t\terr := transp.Serve(ctx, client)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\tprintln(\"wait for connection\")\n\tclient.WaitForConnection(ctx)\n\tprintln(\"request config\")\n\tconf, err := client.GetConfig(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tapp := wappalyzer.New()\n\n\tprintln(\"handle with conf\", spew.Sdump(conf))\n\terr = app.Handle(ctx, client, conf)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package cert\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/juliengk/go-utils\"\n\t\"github.com/spf13/cobra\"\n)\n\n\n\nfunc runRenew(cmd *cobra.Command, args []string) {\n\tif len(args) < 1 || len(args) > 1 {\n\t\tcmd.Usage()\n\t\tos.Exit(-1)\n\t}\n\n\tutils.Exit(fmt.Errorf(\"Not implemented yet\"))\n}\n\nvar renewDescription = `\nRenew Docker client certificate\n\n`\n\nfunc newRenewCommand() *cobra.Command ", "output": "{\n\tcmd := &cobra.Command{\n\t\tUse: \"renew [name]\",\n\t\tShort: \"Renew Docker client certificate\",\n\t\tLong: renewDescription,\n\t\tRun: runRenew,\n\t}\n\n\treturn cmd\n}"} {"input": "package v3\n\nimport (\n\tv3 \"github.com/projectcalico/api/pkg/apis/projectcalico/v3\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype BGPPeerLister interface {\n\tList(selector labels.Selector) (ret []*v3.BGPPeer, err error)\n\tGet(name string) (*v3.BGPPeer, error)\n\tBGPPeerListerExpansion\n}\n\n\ntype bGPPeerLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewBGPPeerLister(indexer cache.Indexer) BGPPeerLister {\n\treturn &bGPPeerLister{indexer: indexer}\n}\n\n\nfunc (s *bGPPeerLister) List(selector labels.Selector) (ret []*v3.BGPPeer, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v3.BGPPeer))\n\t})\n\treturn ret, err\n}\n\n\n\n\nfunc (s *bGPPeerLister) Get(name string) (*v3.BGPPeer, error) ", "output": "{\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v3.Resource(\"bgppeer\"), name)\n\t}\n\treturn obj.(*v3.BGPPeer), nil\n}"} {"input": "package sanitize\n\nimport(\n\t\"os\"\n\t\"encoding/json\"\n)\n\n\n\n\n\nfunc readFileToBytes(filepath string) ([]byte, error) {\n\tf, err := os.Open(filepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfileInfo, err := f.Stat()\n\tbytes := make([]byte, fileInfo.Size())\n\n\t_, err = f.Read(bytes)\n\treturn bytes, err\n}\n\n\nfunc NewWhitelist(jsonData []byte) (*Whitelist, error) {\n\tconfiguration := &Whitelist{}\n\terr := json.Unmarshal(jsonData, configuration)\n\n\treturn configuration, err\n}\n\nfunc WhitelistFromFile(filepath string) (*Whitelist, error) ", "output": "{\n\tbytes, err := readFileToBytes(filepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twhitelist, err := NewWhitelist(bytes)\n\treturn whitelist, nil\n}"} {"input": "package safetime\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/sirupsen/logrus\"\n\t. \"gopkg.in/check.v1\"\n)\n\n\n\n\ntype SafetimeSuite struct {\n\tout *bytes.Buffer \n\tlogger *logrus.Entry\n}\n\nvar _ = Suite(&SafetimeSuite{})\n\nfunc (s *SafetimeSuite) SetUpTest(c *C) {\n\ts.out = &bytes.Buffer{}\n\tlogger := logrus.New()\n\tlogger.Out = s.out\n\ts.logger = logrus.NewEntry(logger)\n}\n\nfunc (s *SafetimeSuite) TestNegativeDuration(c *C) {\n\tfuture := time.Now().Add(time.Second)\n\td, ok := TimeSinceSafe(future, s.logger)\n\n\tc.Assert(ok, Equals, false)\n\tc.Assert(d, Equals, time.Duration(0))\n\tfmt.Println(s.out.String())\n\tc.Assert(strings.Contains(s.out.String(), \"BUG: negative duration\"), Equals, true)\n}\n\nfunc (s *SafetimeSuite) TestNonNegativeDuration(c *C) {\n\tpast := time.Now().Add(-10 * time.Second)\n\td, ok := TimeSinceSafe(past, s.logger)\n\n\tc.Assert(ok, Equals, true)\n\tc.Assert(d > time.Duration(0), Equals, true)\n\tc.Assert(len(s.out.String()) == 0, Equals, true)\n}\n\nfunc Test(t *testing.T) ", "output": "{\n\tTestingT(t)\n}"} {"input": "package foursquare\n\ntype user struct {\n\tId string\n\tFirstName string\n\tLastName string\n}\n\ntype userInfo struct {\n\tResponse struct {\n\t\tUser user\n\t}\n}\n\ntype checkinsList struct {\n\tResponse struct {\n\t\tCheckins struct {\n\t\t\tItems []*checkinItem\n\t\t}\n\t}\n}\n\ntype checkinItem struct {\n\tId string\n\tCreatedAt int64 \n\tTimeZoneOffset int \n\tShout string \n\tVenue venueItem\n}\n\ntype venueItem struct {\n\tId string \n\tName string\n\tLocation *venueLocationItem\n\tCategories []*venueCategory\n}\n\ntype photosList struct {\n\tResponse struct {\n\t\tPhotos struct {\n\t\t\tItems []*photoItem\n\t\t}\n\t}\n}\n\ntype photoItem struct {\n\tId string\n\tPrefix string\n\tSuffix string\n\tWidth int\n\tHeight int\n}\n\nfunc (vi *venueItem) primaryCategory() *venueCategory {\n\tfor _, c := range vi.Categories {\n\t\tif c.Primary {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\ntype venueLocationItem struct {\n\tAddress string\n\tCity string\n\tPostalCode string\n\tState string\n\tCountry string \n\tLat float64\n\tLng float64\n}\n\ntype venueCategory struct {\n\tPrimary bool\n\tName string\n\tIcon *categoryIcon\n}\n\ntype categoryIcon struct {\n\tPrefix string\n\tSuffix string\n}\n\nfunc (vi *venueItem) icon() string ", "output": "{\n\tc := vi.primaryCategory()\n\tif c == nil || c.Icon == nil || c.Icon.Prefix == \"\" {\n\t\treturn \"\"\n\t}\n\treturn c.Icon.Prefix + \"bg_88\" + c.Icon.Suffix\n}"} {"input": "package controllers\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/apiseedprojects/go/responses\"\n)\n\ntype HomeController struct{}\n\n\n\nfunc (hc HomeController) Home(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tresponses.OK(w, responses.M{\"app\": \"apiseedproject\"})\n}"} {"input": "package main\n\ntype test_i interface {\n\tTest() test_i\n\tResult() bool\n}\n\ntype test_t struct {\n}\n\n\n\ntype testFn func(string) testFn\n\nfunc main() {\n\ttest := newTest()\n\n\tswitch {\n\tcase test.\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tTest().\n\t\tResult():\n\tdefault:\n\t\tpanic(\"Result returned false unexpectedly\")\n\t}\n}\n\nfunc (t *test_t) Test() test_i {\n\treturn t\n}\n\nfunc (t *test_t) Result() bool {\n\treturn true\n}\n\nfunc newTest() *test_t ", "output": "{\n\treturn &test_t{}\n}"} {"input": "package lnwire\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com/btcsuite/btcd/btcec\"\n\t\"github.com/btcsuite/btcd/wire\"\n)\n\n\n\n\n\n\n\ntype NetAddress struct {\n\tIdentityKey *btcec.PublicKey\n\n\tAddress net.Addr\n\n\tChainNet wire.BitcoinNet\n}\n\n\n\nvar _ net.Addr = (*NetAddress)(nil)\n\n\n\n\n\nfunc (n *NetAddress) String() string {\n\tpubkey := n.IdentityKey.SerializeCompressed()\n\n\treturn fmt.Sprintf(\"%x@%v\", pubkey, n.Address)\n}\n\n\n\n\n\n\nfunc (n *NetAddress) Network() string ", "output": "{\n\treturn n.Address.Network()\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetVolumeKmsKeyRequest struct {\n\n\tVolumeId *string `mandatory:\"true\" contributesTo:\"path\" name:\"volumeId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetVolumeKmsKeyRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request GetVolumeKmsKeyRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetVolumeKmsKeyRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetVolumeKmsKeyResponse struct {\n\n\tRawResponse *http.Response\n\n\tVolumeKmsKey `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetVolumeKmsKeyResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetVolumeKmsKeyResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetVolumeKmsKeyRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}"} {"input": "package MySQLProtocol\n\ntype Packet_SSLRequest struct {\n\tPacket\n\n\tcapability uint32\n\tmax_packet_size uint32\n\tusername string\n\tcharacter_set uint8\n}\n\nfunc (packet Packet_SSLRequest) GetPacketSize(context Context) (size uint64) {\n\tsize += 4\n\tsize += 4\n\tsize += 1\n\tsize += 23\n\treturn size\n}\n\n\n\nfunc (packet *Packet_SSLRequest) FromPacket(context Context, data Proto) {\n\tdata.GetFixedLengthInteger3()\n\tpacket.sequence_id = data.GetFixedLengthInteger1()\n\n\tpacket.capability = data.GetFixedLengthInteger4()\n\tpacket.max_packet_size = data.GetFixedLengthInteger4()\n\tpacket.character_set = data.GetFixedLengthInteger1()\n\tdata.GetFixedLengthString(23)\n}\n\nfunc (packet Packet_SSLRequest) ToPacket(context Context) (data []byte) ", "output": "{\n\tsize := packet.GetPacketSize(context)\n\n\tdata = make([]byte, 0, size+4)\n\n\tdata = append(data, BuildFixedLengthInteger3(uint32(size))...)\n\tdata = append(data, BuildFixedLengthInteger1(packet.sequence_id)...)\n\n\tdata = append(data, BuildFixedLengthInteger4(packet.capability)...)\n\tdata = append(data, BuildFixedLengthInteger4(packet.max_packet_size)...)\n\tdata = append(data, BuildFixedLengthInteger1(packet.character_set)...)\n\tdata = append(data, BuildFixedLengthString(\"\", 23)...)\n\n\treturn data\n}"} {"input": "package cmd\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/subcommands\"\n\t\"gvisor.dev/gvisor/runsc/config\"\n\t\"gvisor.dev/gvisor/runsc/container\"\n\t\"gvisor.dev/gvisor/runsc/flag\"\n\t\"gvisor.dev/gvisor/runsc/specutils\"\n)\n\n\ntype Start struct{}\n\n\nfunc (*Start) Name() string {\n\treturn \"start\"\n}\n\n\nfunc (*Start) Synopsis() string {\n\treturn \"start a secure container\"\n}\n\n\n\n\n\nfunc (*Start) SetFlags(*flag.FlagSet) {}\n\n\nfunc (*Start) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {\n\tif f.NArg() != 1 {\n\t\tf.Usage()\n\t\treturn subcommands.ExitUsageError\n\t}\n\n\tid := f.Arg(0)\n\tconf := args[0].(*config.Config)\n\n\tc, err := container.Load(conf.RootDir, container.FullID{ContainerID: id}, container.LoadOpts{})\n\tif err != nil {\n\t\tFatalf(\"loading container: %v\", err)\n\t}\n\tif _, err := specutils.ReadSpec(c.BundleDir, conf); err != nil {\n\t\tFatalf(\"reading spec: %v\", err)\n\t}\n\n\tif err := c.Start(conf); err != nil {\n\t\tFatalf(\"starting container: %v\", err)\n\t}\n\treturn subcommands.ExitSuccess\n}\n\nfunc (*Start) Usage() string ", "output": "{\n\treturn `start - start a secure container.`\n}"} {"input": "package services\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\n\n\nfunc ReadJsonConfFileServiceTest(t *testing.T) ", "output": "{\n\n\tconfFilename := \"../testdata/fixtures/system.json\"\n\tf, _ := ReadJsonConfFileService(confFilename)\n\n\tif len(f.Files) < 1 {\n\t\tt.Fatal(\"no Files found in \" + confFilename)\n\t}\n\n\tvar actual string = \"\"\n\tfor i := 0; i < len(f.Files); i++ {\n\t\tactual = f.Files[i].Pattern\t\n\t\tbreak\n\t}\n\texpected := \"installed.*\"\n\n\tassert.Equal(t, expected, actual, \"unexpected config pattern\")\n\n}"} {"input": "package sftp\n\n\n\n\nimport \"os\"\n\n\n\ntype FileOpenFlags struct {\n\tRead, Write, Append, Creat, Trunc, Excl bool\n}\n\nfunc newFileOpenFlags(flags uint32) FileOpenFlags {\n\treturn FileOpenFlags{\n\t\tRead: flags&ssh_FXF_READ != 0,\n\t\tWrite: flags&ssh_FXF_WRITE != 0,\n\t\tAppend: flags&ssh_FXF_APPEND != 0,\n\t\tCreat: flags&ssh_FXF_CREAT != 0,\n\t\tTrunc: flags&ssh_FXF_TRUNC != 0,\n\t\tExcl: flags&ssh_FXF_EXCL != 0,\n\t}\n}\n\n\n\nfunc (r *Request) Pflags() FileOpenFlags {\n\treturn newFileOpenFlags(r.Flags)\n}\n\n\n\n\ntype FileAttrFlags struct {\n\tSize, UidGid, Permissions, Acmodtime bool\n}\n\nfunc newFileAttrFlags(flags uint32) FileAttrFlags {\n\treturn FileAttrFlags{\n\t\tSize: (flags & ssh_FILEXFER_ATTR_SIZE) != 0,\n\t\tUidGid: (flags & ssh_FILEXFER_ATTR_UIDGID) != 0,\n\t\tPermissions: (flags & ssh_FILEXFER_ATTR_PERMISSIONS) != 0,\n\t\tAcmodtime: (flags & ssh_FILEXFER_ATTR_ACMODTIME) != 0,\n\t}\n}\n\n\n\n\n\n\nfunc (a FileStat) FileMode() os.FileMode {\n\treturn os.FileMode(a.Mode)\n}\n\n\n\nfunc (r *Request) Attributes() *FileStat {\n\tfs, _ := getFileStat(r.Flags, r.Attrs)\n\treturn fs\n}\n\nfunc (r *Request) AttrFlags() FileAttrFlags ", "output": "{\n\treturn newFileAttrFlags(r.Flags)\n}"} {"input": "package webservice\n\nimport (\n\t\"net/http\"\n\t\"github.com/codegangsta/martini\"\n)\n\n\ntype WebService interface {\n\tGetPath()string\n\n\tWebDelete(params martini.Params) (int, string)\n\n\tWebGet(params martini.Params) (int, string)\n\n\tWebPost(params martini.Params, req *http.Request) (int, string)\n}\n\n\n\n\n\nfunc RegisterWebService(webService WebService, classicMartini *martini.ClassicMartini) ", "output": "{\n\n\tpath := webService.GetPath()\n\n\tclassicMartini.Get(path, webService.WebGet)\n\tclassicMartini.Get(path+\"/:id\", webService.WebGet)\n\n\tclassicMartini.Post(path, webService.WebPost)\n\tclassicMartini.Post(path+\"/:id\", webService.WebPost)\n\n\tclassicMartini.Delete(path, webService.WebDelete)\n\tclassicMartini.Delete(path+\"/:id\", webService.WebDelete)\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/user\"\n\t\"strconv\"\n)\n\nfunc CreateVcapDirs(paths []string, userName string, groupName string) error {\n\terr := mkdir(paths)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = chown(paths, userName, groupName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc chown(paths []string, userName string, groupName string) error {\n\tuserId, err := GetUserId(userName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgroupId, err := getGroupId(groupName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, path := range paths {\n\t\terr := os.Chown(path, userId, groupId)\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Chown failed: %s\\n\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc GetUserId(userName string) (int, error) {\n\tu, err := user.Lookup(userName)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to obtain UID: %s\\n\", err)\n\t\treturn -1, err\n\t}\n\n\tuserId, _ := strconv.Atoi(u.Uid)\n\n\treturn userId, nil\n}\n\nfunc getGroupId(groupName string) (int, error) {\n\tg, err := user.LookupGroup(groupName)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to obtain GID: %s\\n\", err)\n\t\treturn -1, err\n\t}\n\n\tgroupId, _ := strconv.Atoi(g.Gid)\n\n\treturn groupId, nil\n}\n\nfunc mkdir(paths []string) error ", "output": "{\n\tfor _, path := range paths {\n\t\terr := os.MkdirAll(path, os.ModePerm)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Make directory failed: %s\\n\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package variant\n\nimport (\n\t\"github.com/go-ole/com/errors\"\n\t\"github.com/go-ole/com/types\"\n)\n\nfunc VariantInit(v *types.Variant) error {\n\treturn errors.NotImplementedError\n}\n\nfunc VariantClear(v *types.Variant) error {\n\treturn errors.NotImplementedError\n}\n\nfunc VariantChangeType(source *types.Variant, flags uint16, vt types.VariantType) *types.Variant {\n\treturn source\n}\n\nfunc VariantChangeTypeEx(source *types.Variant, locale uint32, flags uint16, vt types.VariantType) *types.Variant {\n\treturn source\n}\n\n\n\nfunc VariantCopyIndirect(source *types.Variant) *types.Variant {\n\treturn source\n}\n\nfunc VariantCopy(source *types.Variant) *types.Variant ", "output": "{\n\treturn source\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\nfunc main() {\n\tc1 := make(chan bool)\n\tc2 := make(chan bool)\n\n\tgo printer(1, c1)\n\tgo printer(2, c2)\n\n\tfor i := 1; i < 10; i += 1 {\n\t\tselect {\n\t\tcase <-c1:\n\t\t\tfmt.Println(\"Message received from c1\")\n\t\tcase <-c2:\n\t\t\tfmt.Println(\"Message received from c2\")\n\t\t}\n\t}\n}\n\nfunc printer(seconds int64, out chan<- bool) ", "output": "{\n\tfor {\n\t\ttime.Sleep(time.Second * time.Duration(seconds))\n\t\tout <- true\n\t}\n}"} {"input": "package router\n\ntype sortedRoutes struct {\n\troutes Routes\n}\n\n\n\nfunc (s sortedRoutes) Less(i, j int) bool {\n\treturn s.routes.Routes[i].Priority < s.routes.Routes[j].Priority\n}\n\nfunc (s sortedRoutes) Swap(i, j int) {\n\ts.routes.Routes[i], s.routes.Routes[j] = s.routes.Routes[j], s.routes.Routes[i]\n}\n\nfunc (s sortedRoutes) Len() int ", "output": "{\n\treturn len(s.routes.Routes)\n}"} {"input": "package cmd\n\nimport (\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nvar completionBashCmd = &cobra.Command{\n\tUse: \"bash\",\n\tShort: \"Outputs fritzctl shell completion for the given shell (bash)\",\n\tLong: `Outputs fritzctl shell completion for the given shell (bash) to stdout.\nUsage depends on the bash-completion binary. Example installation instructions:\nOS X:\n\t$ brew install bash-completion\n\t$ source $(brew --prefix)/etc/bash_completion\n\t$ fritzctl completion bash > ~/.fritzctl-completion\n\t$ source ~/.fritzctl-completion\nUbuntu:\n\t$ apt-get install bash-completion\n\t$ source /etc/bash-completion\n\t$ source <(fritzctl completion bash)\nAdditionally, you may want to output completion to a file and source in your .bashrc`,\n\tExample: \"fritzctl completion bash\",\n\tRunE: completionBash,\n}\n\n\n\nfunc completionBash(_ *cobra.Command, _ []string) error {\n\treturn RootCmd.GenBashCompletion(os.Stdout)\n}\n\nfunc init() ", "output": "{\n\tcompletionCmd.AddCommand(completionBashCmd)\n}"} {"input": "package mailgun\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/config\"\n\t\"github.com/hashicorp/terraform/helper/schema\"\n\t\"github.com/hashicorp/terraform/terraform\"\n\t\"github.com/pearkes/mailgun\"\n)\n\nvar testAccProviders map[string]terraform.ResourceProvider\nvar testAccProvider *schema.Provider\n\nfunc init() {\n\ttestAccProvider = Provider().(*schema.Provider)\n\ttestAccProviders = map[string]terraform.ResourceProvider{\n\t\t\"mailgun\": testAccProvider,\n\t}\n}\n\n\n\nfunc TestProvider_impl(t *testing.T) {\n\tvar _ terraform.ResourceProvider = Provider()\n}\n\nfunc TestProviderConfigure(t *testing.T) {\n\tvar expectedKey string\n\n\tif v := os.Getenv(\"MAILGUN_API_KEY\"); v != \"\" {\n\t\texpectedKey = v\n\t} else {\n\t\texpectedKey = \"foo\"\n\t}\n\n\traw := map[string]interface{}{\n\t\t\"api_key\": expectedKey,\n\t}\n\n\trawConfig, err := config.NewRawConfig(raw)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\trp := Provider().(*schema.Provider)\n\terr = rp.Configure(terraform.NewResourceConfig(rawConfig))\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tconfig := rp.Meta().(*mailgun.Client)\n\tif config.ApiKey != expectedKey {\n\t\tt.Fatalf(\"bad: %#v\", config)\n\t}\n}\n\nfunc testAccPreCheck(t *testing.T) {\n\tif v := os.Getenv(\"MAILGUN_API_KEY\"); v == \"\" {\n\t\tt.Fatal(\"MAILGUN_API_KEY must be set for acceptance tests\")\n\t}\n}\n\nfunc TestProvider(t *testing.T) ", "output": "{\n\tif err := Provider().(*schema.Provider).InternalValidate(); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n}"} {"input": "package cmd\n\nimport (\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nvar completionBashCmd = &cobra.Command{\n\tUse: \"bash\",\n\tShort: \"Outputs fritzctl shell completion for the given shell (bash)\",\n\tLong: `Outputs fritzctl shell completion for the given shell (bash) to stdout.\nUsage depends on the bash-completion binary. Example installation instructions:\nOS X:\n\t$ brew install bash-completion\n\t$ source $(brew --prefix)/etc/bash_completion\n\t$ fritzctl completion bash > ~/.fritzctl-completion\n\t$ source ~/.fritzctl-completion\nUbuntu:\n\t$ apt-get install bash-completion\n\t$ source /etc/bash-completion\n\t$ source <(fritzctl completion bash)\nAdditionally, you may want to output completion to a file and source in your .bashrc`,\n\tExample: \"fritzctl completion bash\",\n\tRunE: completionBash,\n}\n\nfunc init() {\n\tcompletionCmd.AddCommand(completionBashCmd)\n}\n\n\n\nfunc completionBash(_ *cobra.Command, _ []string) error ", "output": "{\n\treturn RootCmd.GenBashCompletion(os.Stdout)\n}"} {"input": "package tfs\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/richardwilkes/toolbox/errs\"\n)\n\ntype vfs struct {\n\tstorage string\n\tname string\n\toffset int64\n\tlength int64\n\tmode os.FileMode\n\tmodTime time.Time\n\tchildren []*vfs\n}\n\nfunc (v *vfs) Name() string {\n\treturn v.name\n}\n\nfunc (v *vfs) Size() int64 {\n\treturn v.length\n}\n\n\n\nfunc (v *vfs) ModTime() time.Time {\n\treturn v.modTime\n}\n\nfunc (v *vfs) IsDir() bool {\n\treturn (v.mode & os.ModeDir) == os.ModeDir\n}\n\nfunc (v *vfs) Sys() interface{} {\n\treturn nil\n}\n\nfunc (v *vfs) open() (http.File, error) {\n\tif v.IsDir() {\n\t\treturn &vdir{owner: v}, nil\n\t}\n\tf, err := os.Open(v.storage)\n\tif err != nil {\n\t\treturn nil, errs.NewWithCausef(err, \"Unable to open %s\", v.name)\n\t}\n\treturn &vfile{\n\t\towner: v,\n\t\tfile: f,\n\t\tsr: io.NewSectionReader(f, v.offset, v.length),\n\t}, nil\n}\n\nfunc (v *vfs) Mode() os.FileMode ", "output": "{\n\treturn v.mode\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n)\n\nfunc Commafy(i interface{}) string {\n\tvar n int64\n\tswitch i.(type) {\n\tcase int:\n\t\tn = int64(i.(int))\n\tcase int64:\n\t\tn = i.(int64)\n\tcase int32:\n\t\tn = int64(i.(int32))\n\t}\n\tif n > 1000 {\n\t\tr := n % 1000\n\t\tn = n / 1000\n\t\treturn fmt.Sprintf(\"%s,%03d\", Commafy(n), r)\n\t}\n\treturn fmt.Sprintf(\"%d\", n)\n}\n\nfunc FloatToPercent(i float64) string {\n\treturn fmt.Sprintf(\"%.0f\", i*100.0)\n}\n\nfunc PercSuffix(i float64) string {\n\tswitch int(i*100) % 10 {\n\tcase 1:\n\t\treturn \"st\"\n\tcase 2:\n\t\treturn \"nd\"\n\tcase 3:\n\t\treturn \"rd\"\n\t}\n\treturn \"th\"\n}\n\n\n\nfunc NanoSecondToHuman(v float64) string ", "output": "{\n\tvar suffix string\n\tswitch {\n\tcase v > 1000000000:\n\t\tv /= 1000000000\n\t\tsuffix = \"s\"\n\tcase v > 1000000:\n\t\tv /= 1000000\n\t\tsuffix = \"ms\"\n\tcase v > 1000:\n\t\tv /= 1000\n\t\tsuffix = \"us\"\n\tdefault:\n\t\tsuffix = \"ns\"\n\t}\n\treturn fmt.Sprintf(\"%0.1f%s\", v, suffix)\n}"} {"input": "package marks\n\nimport (\n\t\"strings\"\n\n\t\"github.com/zclconf/go-cty/cty\"\n)\n\n\n\n\ntype valueMark string\n\nfunc (m valueMark) GoString() string {\n\treturn \"marks.\" + strings.Title(string(m))\n}\n\n\nfunc Has(val cty.Value, mark valueMark) bool {\n\treturn val.HasMark(mark)\n}\n\n\n\n\n\n\n\nvar Sensitive = valueMark(\"sensitive\")\n\n\n\n\nvar TypeType = valueMark(\"typeType\")\n\nfunc Contains(val cty.Value, mark valueMark) bool ", "output": "{\n\tret := false\n\tcty.Walk(val, func(_ cty.Path, v cty.Value) (bool, error) {\n\t\tif v.HasMark(mark) {\n\t\t\tret = true\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\treturn ret\n}"} {"input": "package transport\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\tma \"gx/ipfs/QmSWLfmj5frN9xVLMMN846dMDriy5wN5jeghUm7aTW3DAG/go-multiaddr\"\n\tmanet \"gx/ipfs/QmVCNGTyD4EkvNYaAp253uMQ9Rjsjy2oGMvcdJJUoVRfja/go-multiaddr-net\"\n\tmafmt \"gx/ipfs/QmYjJnSTfXWhYL2cV1xFphPqjqowJqH7ZKLA1As8QrPHbn/mafmt\"\n)\n\ntype FallbackDialer struct {\n\tmadialer manet.Dialer\n}\n\nfunc (fbd *FallbackDialer) Matches(a ma.Multiaddr) bool {\n\treturn mafmt.TCP.Matches(a)\n}\n\nfunc (fbd *FallbackDialer) Dial(a ma.Multiaddr) (Conn, error) {\n\treturn fbd.DialContext(context.Background(), a)\n}\n\nfunc (fbd *FallbackDialer) DialContext(ctx context.Context, a ma.Multiaddr) (Conn, error) {\n\tif mafmt.TCP.Matches(a) {\n\t\treturn fbd.tcpDial(ctx, a)\n\t}\n\treturn nil, fmt.Errorf(\"cannot dial %s with fallback dialer\", a)\n}\n\n\n\nvar _ Dialer = (*FallbackDialer)(nil)\n\nfunc (fbd *FallbackDialer) tcpDial(ctx context.Context, raddr ma.Multiaddr) (Conn, error) ", "output": "{\n\tvar c manet.Conn\n\tvar err error\n\tc, err = fbd.madialer.DialContext(ctx, raddr)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ConnWrap{\n\t\tConn: c,\n\t}, nil\n}"} {"input": "package actor\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestActorCanReplyOnStopping(t *testing.T) {\n\tfuture := NewFuture(testTimeout)\n\ta := Spawn(FromFunc(func(context Context) {\n\t\tswitch context.Message().(type) {\n\t\tcase *Stopping:\n\t\t\tcontext.Tell(future.PID(), EchoResponse{})\n\t\t}\n\t}))\n\ta.GracefulStop()\n\tassertFutureSuccess(future, t)\n}\n\nfunc TestActorCanReplyOnStarting(t *testing.T) ", "output": "{\n\tfuture := NewFuture(testTimeout)\n\ta := Spawn(FromFunc(func(context Context) {\n\t\tswitch context.Message().(type) {\n\t\tcase *Started:\n\t\t\tcontext.Tell(future.PID(), EchoResponse{})\n\t\t}\n\t}))\n\ta.GracefulStop()\n\tassertFutureSuccess(future, t)\n}"} {"input": "package overview\n\nimport (\n\t\"appengine\"\n\n\th \"github.com/czertbytes/pocket/pkg/http\"\n\tt \"github.com/czertbytes/pocket/pkg/types\"\n)\n\ntype Notificator struct {\n\tAppEngineContext appengine.Context\n\tRequestContext *h.RequestContext\n}\n\n\n\nfunc (self *Notificator) Create(overview *t.Overview) error {\n\treturn nil\n}\n\nfunc (self *Notificator) Update(overview *t.Overview) error {\n\treturn nil\n}\n\nfunc (self *Notificator) CreatePayment(payment *t.Payment) error {\n\treturn nil\n}\n\nfunc (self *Notificator) CreateParticipant(participant *t.User) error {\n\treturn nil\n}\n\nfunc NewNotificator(RequestContext *h.RequestContext) *Notificator ", "output": "{\n\treturn &Notificator{\n\t\tAppEngineContext: RequestContext.AppEngineContext,\n\t\tRequestContext: RequestContext,\n\t}\n}"} {"input": "package dom\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\ntype Node interface {\n\tString() string\n\tParent() Node\n\tSetParent(node Node)\n\tChildren() []Node\n\tAddChild(child Node)\n\tClone() Node\n}\n\n\ntype Element struct {\n\ttext string\n\tparent Node\n\tchildren []Node\n}\n\n\n\n\n\nfunc (e *Element) Parent() Node {\n\treturn e.parent\n}\n\n\nfunc (e *Element) SetParent(node Node) {\n\te.parent = node\n}\n\n\nfunc (e *Element) Children() []Node {\n\treturn e.children\n}\n\n\nfunc (e *Element) AddChild(child Node) {\n\tcopy := child.Clone()\n\tcopy.SetParent(e)\n\te.children = append(e.children, copy)\n}\n\n\n\nfunc (e *Element) Clone() Node {\n\tcopy := &Element{\n\t\ttext: e.text,\n\t\tparent: nil,\n\t\tchildren: make([]Node, 0),\n\t}\n\tfor _, child := range e.children {\n\t\tcopy.AddChild(child)\n\t}\n\treturn copy\n}\n\n\nfunc (e *Element) String() string {\n\tbuffer := bytes.NewBufferString(e.text)\n\n\tfor _, c := range e.Children() {\n\t\ttext := c.String()\n\t\tfmt.Fprintf(buffer, \"\\n %s\", text)\n\t}\n\n\treturn buffer.String()\n}\n\nfunc NewElement(text string) *Element ", "output": "{\n\treturn &Element{\n\t\ttext: text,\n\t\tparent: nil,\n\t\tchildren: make([]Node, 0),\n\t}\n}"} {"input": "package viewservice\n\nimport \"net/rpc\"\nimport \"fmt\"\n\n\n\n\n\ntype Clerk struct {\n\tme string \n\tserver string \n}\n\nfunc MakeClerk(me string, server string) *Clerk {\n\tck := new(Clerk)\n\tck.me = me\n\tck.server = server\n\treturn ck\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (ck *Clerk) Ping(viewnum uint) (View, error) {\n\targs := &PingArgs{}\n\targs.Me = ck.me\n\targs.Viewnum = viewnum\n\tvar reply PingReply\n\n\tok := call(ck.server, \"ViewServer.Ping\", args, &reply)\n\tif ok == false {\n\t\treturn View{}, fmt.Errorf(\"Ping(%v) failed\", viewnum)\n\t}\n\n\treturn reply.View, nil\n}\n\nfunc (ck *Clerk) Get() (View, bool) {\n\targs := &GetArgs{}\n\tvar reply GetReply\n\tok := call(ck.server, \"ViewServer.Get\", args, &reply)\n\tif ok == false {\n\t\treturn View{}, false\n\t}\n\treturn reply.View, true\n}\n\nfunc (ck *Clerk) Primary() string {\n\tv, ok := ck.Get()\n\tif ok {\n\t\treturn v.Primary\n\t}\n\treturn \"\"\n}\n\nfunc call(srv string, rpcname string,\n\targs interface{}, reply interface{}) bool ", "output": "{\n\tc, errx := rpc.Dial(\"unix\", srv)\n\tif errx != nil {\n\t\treturn false\n\t}\n\tdefer c.Close()\n\n\terr := c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}"} {"input": "package appfilesfakes\n\nimport (\n\t\"sync\"\n\n\t\"code.cloudfoundry.org/cli/cf/api/appfiles\"\n)\n\ntype FakeAppFilesRepository struct {\n\tListFilesStub func(appGUID string, instance int, path string) (files string, apiErr error)\n\tlistFilesMutex sync.RWMutex\n\tlistFilesArgsForCall []struct {\n\t\tappGUID string\n\t\tinstance int\n\t\tpath string\n\t}\n\tlistFilesReturns struct {\n\t\tresult1 string\n\t\tresult2 error\n\t}\n}\n\nfunc (fake *FakeAppFilesRepository) ListFiles(appGUID string, instance int, path string) (files string, apiErr error) {\n\tfake.listFilesMutex.Lock()\n\tfake.listFilesArgsForCall = append(fake.listFilesArgsForCall, struct {\n\t\tappGUID string\n\t\tinstance int\n\t\tpath string\n\t}{appGUID, instance, path})\n\tfake.listFilesMutex.Unlock()\n\tif fake.ListFilesStub != nil {\n\t\treturn fake.ListFilesStub(appGUID, instance, path)\n\t} else {\n\t\treturn fake.listFilesReturns.result1, fake.listFilesReturns.result2\n\t}\n}\n\n\n\nfunc (fake *FakeAppFilesRepository) ListFilesArgsForCall(i int) (string, int, string) {\n\tfake.listFilesMutex.RLock()\n\tdefer fake.listFilesMutex.RUnlock()\n\treturn fake.listFilesArgsForCall[i].appGUID, fake.listFilesArgsForCall[i].instance, fake.listFilesArgsForCall[i].path\n}\n\nfunc (fake *FakeAppFilesRepository) ListFilesReturns(result1 string, result2 error) {\n\tfake.ListFilesStub = nil\n\tfake.listFilesReturns = struct {\n\t\tresult1 string\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nvar _ appfiles.Repository = new(FakeAppFilesRepository)\n\nfunc (fake *FakeAppFilesRepository) ListFilesCallCount() int ", "output": "{\n\tfake.listFilesMutex.RLock()\n\tdefer fake.listFilesMutex.RUnlock()\n\treturn len(fake.listFilesArgsForCall)\n}"} {"input": "package pydio\n\nimport (\n\t\"bytes\"\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nvar (\n\tfakeXML []byte\n\tfakeXML2 []byte\n)\n\n\n\ntype Query struct {\n\tUser User `xml:\"user\"`\n}\n\nfunc TestUser(t *testing.T) {\n\tConvey(\"Unmarshaling user\", t, func() {\n\t\tvar q Query\n\n\t\terr := xml.Unmarshal(fakeXML, &q)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tSo(q.User, ShouldResemble, *fakeUser)\n\t\tSo(q.User.Repos[0].IsReadable(), ShouldEqual, true)\n\t})\n\n\tConvey(\"Unmarshaling user 2\", t, func() {\n\t\tvar q Query\n\n\t\tdec := xml.NewDecoder(bytes.NewReader(fakeXML))\n\t\tdec.Strict = false\n\n\t\terr := dec.Decode(&q)\n\t\tSo(err, ShouldBeNil)\n\n\t\tSo(q.User, ShouldResemble, *fakeUser)\n\t})\n}\n\nfunc init() ", "output": "{\n\tsecret = \"TestingSecret\"\n\n\tfakeXML = []byte(`\n\t\n\t\n\t\t\n\t\t\t\n\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\n\t\n\t`)\n}"} {"input": "package identity\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListTaggingWorkRequestErrorsRequest struct {\n\n\tWorkRequestId *string `mandatory:\"true\" contributesTo:\"path\" name:\"workRequestId\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListTaggingWorkRequestErrorsRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListTaggingWorkRequestErrorsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ListTaggingWorkRequestErrorsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ListTaggingWorkRequestErrorsRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListTaggingWorkRequestErrorsResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []TaggingWorkRequestErrorSummary `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n\n\tRetryAfter *float32 `presentIn:\"header\" name:\"retry-after\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n}\n\nfunc (response ListTaggingWorkRequestErrorsResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response ListTaggingWorkRequestErrorsResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package example\n\nimport (\n\t\"testing\"\n\t\"github.com/remogatto/prettytest\"\n\t\"launchpad.net/gocheck\"\n)\n\n\n\ntype testSuite struct {\n\tprettytest.Suite\n}\n\nfunc TestRunner(t *testing.T) {\n\tprettytest.Run(\n\t\tt,\n\t\tnew(testSuite),\n\t)\n}\n\n\n\n\n\n\n\n\nfunc (t *testSuite) TestEquality() {\n\tt.Equal(\"awesome\", \"awesome\")\n}\n\nfunc (t *testSuite) TestNot() {\n\tt.Not(t.Path(\"foo\"))\n}\n\nfunc (t *testSuite) TestGoCheck() {\n\tt.Check(\"foo\", gocheck.Equals, \"foo\")\n}\n\n\n\nfunc (t *testSuite) TestMustFail() {\n\tt.Error(\"This test must fail.\")\n\tt.MustFail()\n}\n\nfunc (t *testSuite) TestInequality() {\n\tt.Equal(\"awesome\", \"ugly\")\n\tt.MustFail()\n}\n\nfunc (t *testSuite) TestTrueIsTrue() ", "output": "{\n\tt.True(true)\n}"} {"input": "package main\n\nimport ()\n\ntype channel struct {\n\tpath string\n\tqueue queue\n\tconnections connections\n\th *hub\n}\n\ntype connections map[*connection]interface {\n}\n\n\n\nfunc (c *channel) stop() {\n\tclose(c.queue)\n\tc.h.queue <- command{cmd: REMOVE, path: c.path}\n\tdecr(\"channels\", 1)\n}\n\nfunc (c *channel) subscribe(conn *connection) {\n\tc.connections[conn] = nil\n}\n\nfunc (c *channel) unsubscribe(conn *connection) {\n\tif _, ok := c.connections[conn]; ok {\n\t\tclose(conn.send)\n\t\tdelete(c.connections, conn)\n\t}\n}\n\nfunc (c *channel) publish(text []byte) {\n\tif len(text) == 0 {\n\t\treturn\n\t}\n\tc.h.queue <- command{cmd: PUBLISH, path: c.path, text: text}\n}\n\nfunc (c *channel) broadcast(text []byte) {\n\tif len(text) == 0 {\n\t\treturn\n\t}\n\tfor conn := range c.connections {\n\t\tselect {\n\t\tcase conn.send <- text:\n\t\tdefault:\n\t\t\tc.unsubscribe(conn)\n\t\t}\n\t}\n}\n\nfunc (c *channel) run() ", "output": "{\n\tincr(\"channels\", 1)\n\tdefer c.stop()\n\tfor cmd := range c.queue {\n\t\tswitch cmd.cmd {\n\t\tcase SUBSCRIBE:\n\t\t\tc.subscribe(cmd.conn)\n\t\tcase UNSUBSCRIBE:\n\t\t\tc.unsubscribe(cmd.conn)\n\t\t\tif len(c.connections) == 0 {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase PUBLISH:\n\t\t\tc.publish(cmd.text)\n\t\tcase BROADCAST:\n\t\t\tc.broadcast(cmd.text)\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\t}\n}"} {"input": "package openstacktasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realFloatingIP FloatingIP\n\n\nfunc (o *FloatingIP) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realFloatingIP\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = FloatingIP(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &FloatingIP{}\n\n\nfunc (o *FloatingIP) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\n\n\n\nvar _ fi.HasName = &FloatingIP{}\n\n\nfunc (o *FloatingIP) GetName() *string {\n\treturn o.Name\n}\n\n\nfunc (o *FloatingIP) SetName(name string) {\n\to.Name = &name\n}\n\n\nfunc (o *FloatingIP) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *FloatingIP) SetLifecycle(lifecycle fi.Lifecycle) ", "output": "{\n\to.Lifecycle = &lifecycle\n}"} {"input": "package tango\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\nfunc TestDir1(t *testing.T) {\n\tbuff := bytes.NewBufferString(\"\")\n\trecorder := httptest.NewRecorder()\n\trecorder.Body = buff\n\n\ttg := New()\n\ttg.Get(\"/:name\", Dir(\"./public\"))\n\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:8000/test.html\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\ttg.ServeHTTP(recorder, req)\n\texpect(t, recorder.Code, http.StatusOK)\n\trefute(t, len(buff.String()), 0)\n\texpect(t, buff.String(), \"hello tango\")\n}\n\n\n\nfunc TestFile1(t *testing.T) {\n\tbuff := bytes.NewBufferString(\"\")\n\trecorder := httptest.NewRecorder()\n\trecorder.Body = buff\n\n\ttg := New()\n\ttg.Get(\"/test.html\", File(\"./public/test.html\"))\n\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:8000/test.html\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\ttg.ServeHTTP(recorder, req)\n\texpect(t, recorder.Code, http.StatusOK)\n\trefute(t, len(buff.String()), 0)\n\texpect(t, buff.String(), \"hello tango\")\n}\n\nfunc TestDir2(t *testing.T) ", "output": "{\n\tbuff := bytes.NewBufferString(\"\")\n\trecorder := httptest.NewRecorder()\n\trecorder.Body = buff\n\n\ttg := New()\n\ttg.Get(\"/\", Dir(\"./public\"))\n\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:8000/\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\ttg.ServeHTTP(recorder, req)\n\texpect(t, recorder.Code, http.StatusNotFound)\n\trefute(t, len(buff.String()), 0)\n\texpect(t, buff.String(), http.StatusText(http.StatusNotFound))\n}"} {"input": "package config\n\nimport selinux \"github.com/opencontainers/selinux/go-selinux\"\n\n\n\nfunc selinuxEnabled() bool ", "output": "{\n\treturn selinux.GetEnabled()\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1beta1 \"knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1\"\n)\n\ntype FakeServingV1beta1 struct {\n\t*testing.Fake\n}\n\n\n\nfunc (c *FakeServingV1beta1) Revisions(namespace string) v1beta1.RevisionInterface {\n\treturn &FakeRevisions{c, namespace}\n}\n\nfunc (c *FakeServingV1beta1) Routes(namespace string) v1beta1.RouteInterface {\n\treturn &FakeRoutes{c, namespace}\n}\n\nfunc (c *FakeServingV1beta1) Services(namespace string) v1beta1.ServiceInterface {\n\treturn &FakeServices{c, namespace}\n}\n\n\n\nfunc (c *FakeServingV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeServingV1beta1) Configurations(namespace string) v1beta1.ConfigurationInterface ", "output": "{\n\treturn &FakeConfigurations{c, namespace}\n}"} {"input": "package marid\n\ntype FuncSet struct {\n\tf map[string]interface{}\n}\n\nfunc NewFuncSet() *FuncSet {\n\treturn &FuncSet{make(map[string]interface{})}\n}\n\n\n\nfunc (f *FuncSet) GetFuncs() map[string]interface{} {\n\treturn f.f\n}\n\nfunc (f *FuncSet) AddFuncs(fns map[string]interface{}) ", "output": "{\n\tfor k, fn := range fns {\n\t\tf.f[k] = fn\n\t}\n}"} {"input": "package p\n\nvar x struct{}\n\n\n\nfunc f() bool ", "output": "{\n\treturn x == x && x == x\n}"} {"input": "package joltDB\n\nimport (\n\t\"github.com/boltdb/bolt\"\n)\n\nvar boltdbr *bolt.DB\nvar dbr = apiConn(boltdbr)\n\nfunc OpenReadOnly(dir string) error {\n\treturn dbr.apiOpenReadOnly(dir)\n}\n\nfunc CloseReadOnly() {\n\tdbr.apiClose()\n}\n\nfunc ListReadOnly(bucket string) ([]byte, error) {\n\treturn dbr.apiList(bucket)\n}\n\nfunc ListPrefixReadOnly(bucket, prefix string) ([]byte, error) {\n\treturn dbrw.apiListPrefix(bucket, prefix)\n}\n\nfunc ListRangeReadOnly(bucket, start, stop string) ([]byte, error) {\n\treturn dbrw.apiListRange(bucket, start, stop)\n}\n\n\n\nfunc GetOneReadOnly(bucket, key string) ([]byte, error) ", "output": "{\n\treturn dbr.apiGetOne(bucket, key)\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n\t\"unicode\"\n)\n\n\n\nfunc lowerCasedWord(word string) (lowerCased string) {\n\tswitch len(word) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\tlowerCased = strings.ToLower(string(word[0]))\n\tdefault:\n\t\tlowerCased = strings.ToLower(string(word[0])) + string(word[1:])\n\t}\n\treturn lowerCased\n}\n\nfunc camelcaseToAbbreviation(camel string) (abbr string) {\n\tif len(camel) == 0 {\n\t\treturn \"\"\n\t}\n\n\tabbr = strings.ToLower(string(camel[0])) \n\n\tremainingRunes := []rune(camel[1:])\n\tfor _, r := range remainingRunes {\n\t\tif unicode.IsUpper(r) {\n\t\t\tabbr += strings.ToLower(string(r))\n\t\t}\n\t}\n\treturn abbr\n}\n\nfunc capitalizedWord(word string) (capitalized string) ", "output": "{\n\tswitch len(word) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\tcapitalized = strings.ToUpper(string(word[0]))\n\tdefault:\n\t\tcapitalized = strings.ToUpper(string(word[0])) + string(word[1:])\n\t}\n\treturn capitalized\n}"} {"input": "package policies\n\nimport (\n\t\"fmt\"\n \"github.com/megamsys/gulp/global\"\n)\n\n\ntype Policies interface {\n\tApply(*global.AssemblyWithComponents) (string, error)\n}\n\nvar policies = make(map[string]Policies)\nvar plug_policies = []string{\"bind\", \"ha\"}\n\nfunc RegisterPolicy(name string, policy Policies) {\n\tpolicies[name] = policy\n}\n\n\n\nfunc ApplyPolicies(asm *global.AssemblyWithComponents) {\n for k := range plug_policies {\n \tp, err := GetPolicy(plug_policies[k])\n\tif err != nil {\t\n\t \treturn \n\t}\t\t\n\tgo p.Apply(asm)\t \t\t\n } \n}\n\nfunc GetPolicy(name string) (Policies, error) ", "output": "{\n\tpolicy, ok := policies[name]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"policies not registered\")\n\t}\n\treturn policy, nil\n}"} {"input": "package geocoder\n\nimport \"testing\"\n\nfunc TestNewGeoPoint(t *testing.T) {\n\tgeoPoint, err := NewGeoPoint(\"59.939095 30.315868\")\n\tif err != nil {\n\t\tt.Fatal(\"Error parsing geo coordinates\")\n\t}\n\n\tif geoPoint.longitude != 59.939095 {\n\t\tt.Fatal(\"Error parsing longitude\")\n\t}\n\n\tif geoPoint.latitude != 30.315868 {\n\t\tt.Fatal(\"Error parsing latitude\")\n\t}\n}\n\n\n\nfunc TestLatitude(t *testing.T) {\n\tgeoPoint, _ := NewGeoPoint(\"59.939095 30.315868\")\n\tif geoPoint.Latitude() != 30.315868 {\n\t\tt.Fatal(\"Error return latitude\")\n\t}\n}\n\nfunc TestString(t *testing.T) {\n\tgeoPoint, _ := NewGeoPoint(\"59.939095 30.315868\")\n\tif geoPoint.String() != \"59.939095 30.315868\" {\n\t\tt.Fatal(\"Error return coordinates string\")\n\t}\n}\n\nfunc TestLongitude(t *testing.T) ", "output": "{\n\tgeoPoint, _ := NewGeoPoint(\"59.939095 30.315868\")\n\tif geoPoint.Longitude() != 59.939095 {\n\t\tt.Fatal(\"Error return longitude\")\n\t}\n}"} {"input": "package assertion\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n)\n\nconst (\n\tEqualOp = \"equal\"\n\tNotEqualOp = \"not_equal\"\n\tContainsOp = \"contain\"\n\tNotContainsOp = \"not_contain\"\n)\n\ntype Operator func(val interface{}, expected interface{}) (bool, error)\n\nvar opMap = map[string]Operator{\n\tEqualOp: equal,\n\tNotEqualOp: notEqual,\n\tContainsOp: contain,\n\tNotContainsOp: notContain,\n}\n\nfunc AvailableOps() []string {\n\tvar ops []string\n\tfor op := range opMap {\n\t\tops = append(ops, op)\n\t}\n\treturn ops\n}\n\nfunc NewOperator(op string) (Operator, error) {\n\topFunc, ok := opMap[op]\n\tif !ok {\n\t\treturn nil, errors.New(\"operator not supported\")\n\t}\n\n\treturn opFunc, nil\n}\n\nfunc equal(val interface{}, expected interface{}) (bool, error) {\n\tif !reflect.DeepEqual(val, expected) {\n\t\treturn false, errors.New(fmt.Sprintf(\"expected equal %s, given %s\", expected, val))\n\t}\n\treturn true, nil\n}\n\nfunc notEqual(val interface{}, expected interface{}) (bool, error) {\n\tif reflect.DeepEqual(val, expected) {\n\t\treturn false, errors.New(fmt.Sprintf(\"expected not equal %s, given %s\", expected, val))\n\t}\n\treturn true, nil\n}\n\nfunc contain(val interface{}, expected interface{}) (bool, error) {\n\tvalStr := val.(string)\n\texpectedStr := expected.(string)\n\tif !strings.Contains(valStr, expectedStr) {\n\t\treturn false, errors.New(fmt.Sprintf(\"expected contain %s, given %s\", expected, val))\n\t}\n\treturn true, nil\n}\n\n\n\nfunc notContain(val interface{}, expected interface{}) (bool, error) ", "output": "{\n\tvalStr := val.(string)\n\texpectedStr := expected.(string)\n\tif strings.Contains(valStr, expectedStr) {\n\t\treturn false, errors.New(fmt.Sprintf(\"expected not contain %s, given %s\", expected, val))\n\t}\n\treturn true, nil\n}"} {"input": "package kintone\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype Cursor struct {\n\tId string `json:\"id\"`\n\tTotalCount string `json:\"totalCount\"`\n}\ntype GetRecordsCursorResponse struct {\n\tRecords []*Record `json:\"records\"`\n\tNext bool `json:\"next\"`\n}\n\n\nfunc decodeCursor(b []byte) (c *Cursor, err error) {\n\terr = json.Unmarshal(b, &c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}\n\n\nfunc DecodeGetRecordsCursorResponse(b []byte) (rc *GetRecordsCursorResponse, err error) ", "output": "{\n\tvar t struct {\n\t\tNext bool `json:\"next\"`\n\t}\n\terr = json.Unmarshal(b, &t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlistRecord, err := DecodeRecords(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgetRecordsCursorResponse := &GetRecordsCursorResponse{Records: listRecord, Next: t.Next}\n\treturn getRecordsCursorResponse, nil\n}"} {"input": "package ec2\n\nimport (\n\t\"github.com/crowdmob/goamz/aws\"\n\t\"time\"\n)\n\nfunc Sign(auth aws.Auth, method, path string, params map[string]string, host string) {\n\tsign(auth, method, path, params, host)\n}\n\nfunc fixedTime() time.Time {\n\treturn time.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC)\n}\n\n\n\nfunc FakeTime(fakeIt bool) ", "output": "{\n\tif fakeIt {\n\t\ttimeNow = fixedTime\n\t} else {\n\t\ttimeNow = time.Now\n\t}\n}"} {"input": "package task\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"sir/models\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestTaskManager_StopTask(t *testing.T) {\n\tassertion := assert.New(t)\n\n\tmanager := NewTaskManager(\"/Users/hong/projects/src/sir/\")\n\n\ttask := &models.Task{\n\t\tTaskState: &models.TaskState{},\n\t\tTaskConfig: &models.TaskConfig{\n\t\t\tName: \"test\",\n\t\t\tCmd: \"/sbin/ping 114.114.114.114\",\n\t\t},\n\t}\n\terr := manager.StartTask(task)\n\tassertion.Nil(err)\n\n\terr = manager.StopTask(task.Name)\n\tassertion.Nil(err)\n\n}\n\nfunc TestTaskManager_TaskState(t *testing.T) {\n\tassertion := assert.New(t)\n\n\tmanager := NewTaskManager(\"/Users/hong/projects/src/sir/\")\n\n\ttask := &models.Task{\n\t\tTaskState: &models.TaskState{},\n\t\tTaskConfig: &models.TaskConfig{\n\t\t\tName: \"test\",\n\t\t\tCmd: \"/sbin/ping 114.114.114.114\",\n\t\t},\n\t}\n\terr := manager.StartTask(task)\n\tassertion.Nil(err)\n\n\ttime.Sleep(time.Second)\n\n\tassertion.Empty(manager.Tasks[\"test\"].TaskState)\n}\n\nfunc TestTaskManager_StartTask(t *testing.T) ", "output": "{\n\tassertion := assert.New(t)\n\n\tmanager := NewTaskManager(\"/Users/hong/projects/src/sir/\")\n\n\ttask := &models.Task{\n\t\tTaskState: &models.TaskState{},\n\t\tTaskConfig: &models.TaskConfig{\n\t\t\tName: \"test\",\n\t\t\tCmd: \"/sbin/ping 114.114.114.114\",\n\t\t},\n\t}\n\terr := manager.StartTask(task)\n\tassertion.Nil(err)\n\tassertion.Equal(1, len(manager.Tasks))\n}"} {"input": "package model\n\nimport (\n\t\"context\"\n\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/goharbor/harbor/src/lib/log\"\n\t\"github.com/goharbor/harbor/src/pkg/quota\"\n\t\"github.com/goharbor/harbor/src/pkg/quota/types\"\n\t\"github.com/goharbor/harbor/src/server/v2.0/models\"\n)\n\n\ntype Quota struct {\n\t*quota.Quota\n}\n\n\nfunc (q *Quota) ToSwagger(ctx context.Context) *models.Quota {\n\tif q.Quota == nil {\n\t\treturn nil\n\t}\n\n\thard, err := q.GetHard()\n\tif err != nil {\n\t\tfields := log.Fields{\"quota_id\": q.ID, \"error\": err}\n\t\tlog.G(ctx).WithFields(fields).Warningf(\"failed to get hard from quota\")\n\n\t\thard = types.ResourceList{}\n\t}\n\n\tused, err := q.GetUsed()\n\tif err != nil {\n\t\tfields := log.Fields{\"quota_id\": q.ID, \"error\": err}\n\t\tlog.G(ctx).WithFields(fields).Warningf(\"failed to get used from quota\")\n\n\t\tused = types.ResourceList{}\n\t}\n\n\treturn &models.Quota{\n\t\tID: q.ID,\n\t\tRef: q.Ref,\n\t\tHard: hard,\n\t\tUsed: used,\n\t\tCreationTime: strfmt.DateTime(q.CreationTime),\n\t\tUpdateTime: strfmt.DateTime(q.UpdateTime),\n\t}\n}\n\n\n\n\nfunc NewQuota(quota *quota.Quota) *Quota ", "output": "{\n\treturn &Quota{Quota: quota}\n}"} {"input": "package pprof\n\nimport \"net\"\n\n\n\nfunc getPProfDialer(addr string) *pprofDialer {\n\treturn &pprofDialer{\"unix\", addr}\n}\n\nfunc (d *pprofDialer) pprofDial(proto, addr string) (conn net.Conn, err error) ", "output": "{\n\treturn net.Dial(d.proto, d.addr)\n}"} {"input": "package parse\n\nimport (\n\t\"github.com/hfern/luao/lexer\"\n)\n\ntype readerState struct {\n\tread int\n}\n\ntype tReader struct {\n\tstate readerState\n\tsource *[]lexer.Token\n}\n\n\n\nfunc (r *tReader) Restore(s readerState) {\n\tr.state = s\n}\n\nfunc (r *tReader) Next() lexer.Token {\n\tif len(r.source) <= r.state.read {\n\t\treturn lexer.Token\n\t}\n}\n\nfunc (r tReader) Save() readerState ", "output": "{\n\treturn r.state\n}"} {"input": "package comparison_instructions\n\nimport (\n\t\"github.com/Frederick-S/jvmgo/instructions/base_instructions\"\n\t\"github.com/Frederick-S/jvmgo/runtime_data_area\"\n)\n\n\n\ntype FCmpg struct {\n\tbase_instructions.NoOperandsInstruction\n}\n\n\n\nfunc (fCmpg *FCmpg) Execute(frame *runtime_data_area.Frame) ", "output": "{\n\toperandStack := frame.GetOperandStack()\n\tfloatValue2 := operandStack.PopFloatValue()\n\tfloatValue1 := operandStack.PopFloatValue()\n\n\tif floatValue1 > floatValue2 {\n\t\toperandStack.PushIntegerValue(1)\n\t} else if floatValue1 == floatValue2 {\n\t\toperandStack.PushIntegerValue(0)\n\t} else if floatValue1 < floatValue2 {\n\t\toperandStack.PushIntegerValue(-1)\n\t} else {\n\t\toperandStack.PushIntegerValue(1)\n\t}\n}"} {"input": "package caaa\n\nimport (\n\t\"encoding/xml\"\n\n\t\"github.com/fgrid/iso20022\"\n)\n\ntype Document00300102 struct {\n\tXMLName xml.Name `xml:\"urn:iso:std:iso:20022:tech:xsd:caaa.003.001.02 Document\"`\n\tMessage *AcceptorCompletionAdviceV02 `xml:\"AccptrCmpltnAdvc\"`\n}\n\n\n\n\n\ntype AcceptorCompletionAdviceV02 struct {\n\n\tHeader *iso20022.Header2 `xml:\"Hdr\"`\n\n\tCompletionAdvice *iso20022.AcceptorCompletionAdvice2 `xml:\"CmpltnAdvc\"`\n\n\tSecurityTrailer *iso20022.ContentInformationType6 `xml:\"SctyTrlr\"`\n}\n\nfunc (a *AcceptorCompletionAdviceV02) AddHeader() *iso20022.Header2 {\n\ta.Header = new(iso20022.Header2)\n\treturn a.Header\n}\n\nfunc (a *AcceptorCompletionAdviceV02) AddCompletionAdvice() *iso20022.AcceptorCompletionAdvice2 {\n\ta.CompletionAdvice = new(iso20022.AcceptorCompletionAdvice2)\n\treturn a.CompletionAdvice\n}\n\nfunc (a *AcceptorCompletionAdviceV02) AddSecurityTrailer() *iso20022.ContentInformationType6 {\n\ta.SecurityTrailer = new(iso20022.ContentInformationType6)\n\treturn a.SecurityTrailer\n}\n\nfunc (d *Document00300102) AddMessage() *AcceptorCompletionAdviceV02 ", "output": "{\n\td.Message = new(AcceptorCompletionAdviceV02)\n\treturn d.Message\n}"} {"input": "package u\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync/atomic\"\n)\n\n\ntype FileWalkEntry struct {\n\tDir string\n\tFileInfo os.FileInfo\n}\n\n\nfunc (e *FileWalkEntry) Path() string {\n\treturn filepath.Join(e.Dir, e.FileInfo.Name())\n}\n\n\ntype FileWalk struct {\n\tstartDir string\n\tFilesChan chan *FileWalkEntry\n\taskedToStop int32\n}\n\n\n\n\nfunc fileWalkWorker(ft *FileWalk) {\n\ttoVisit := []string{ft.startDir}\n\tdefer close(ft.FilesChan)\n\n\tfor len(toVisit) > 0 {\n\t\tshouldStop := atomic.LoadInt32(&ft.askedToStop)\n\t\tif shouldStop > 0 {\n\t\t\treturn\n\t\t}\n\t\tdir := toVisit[0]\n\t\ttoVisit = StringsRemoveFirst(toVisit)\n\n\t\tfiles, err := ioutil.ReadDir(dir)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, fi := range files {\n\t\t\tpath := filepath.Join(dir, fi.Name())\n\t\t\tmode := fi.Mode()\n\t\t\tif mode.IsDir() {\n\t\t\t\ttoVisit = append(toVisit, path)\n\t\t\t} else if mode.IsRegular() {\n\t\t\t\tfte := &FileWalkEntry{\n\t\t\t\t\tDir: dir,\n\t\t\t\t\tFileInfo: fi,\n\t\t\t\t}\n\t\t\t\tft.FilesChan <- fte\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nfunc StartFileWalk(startDir string) *FileWalk {\n\tch := make(chan *FileWalkEntry, 1024*64)\n\tft := &FileWalk{\n\t\tstartDir: startDir,\n\t\tFilesChan: ch,\n\t}\n\tgo fileWalkWorker(ft)\n\treturn ft\n}\n\nfunc (ft *FileWalk) Stop() ", "output": "{\n\tatomic.StoreInt32(&ft.askedToStop, 1)\n\tfor range ft.FilesChan {\n\t}\n}"} {"input": "package cli\n\nimport \"github.com/scaleway/scaleway-cli/pkg/commands\"\n\nvar cmdStop = &Command{\n\tExec: runStop,\n\tUsageLine: \"stop [OPTIONS] SERVER [SERVER...]\",\n\tDescription: \"Stop a running server\",\n\tHelp: \"Stop a running server.\",\n\tExamples: `\n $ scw stop my-running-server my-second-running-server\n $ scw stop -t my-running-server my-second-running-server\n $ scw stop $(scw ps -q)\n $ scw stop $(scw ps | grep mysql | awk '{print $1}')\n $ scw stop server && stop wait server\n $ scw stop -w server\n`,\n}\n\nfunc init() {\n\tcmdStop.Flag.BoolVar(&stopT, []string{\"t\", \"-terminate\"}, false, \"Stop and trash a server with its volumes\")\n\tcmdStop.Flag.BoolVar(&stopHelp, []string{\"h\", \"-help\"}, false, \"Print usage\")\n\tcmdStop.Flag.BoolVar(&stopW, []string{\"w\", \"-wait\"}, false, \"Synchronous stop. Wait for SSH to be ready\")\n}\n\n\nvar stopT bool \nvar stopHelp bool \nvar stopW bool \n\n\n\nfunc runStop(cmd *Command, rawArgs []string) error ", "output": "{\n\tif stopHelp {\n\t\treturn cmd.PrintUsage()\n\t}\n\tif len(rawArgs) < 1 {\n\t\treturn cmd.PrintShortUsage()\n\t}\n\n\targs := commands.StopArgs{\n\t\tTerminate: stopT,\n\t\tWait: stopW,\n\t\tServers: rawArgs,\n\t}\n\tctx := cmd.GetContext(rawArgs)\n\treturn commands.RunStop(ctx, args)\n}"} {"input": "package graph\n\nimport (\n\t\"database/sql/driver\"\n\t\"fmt\"\n)\n\n\ntype StatType string\n\n\ntype Stats map[StatType]int\n\nconst (\n\tStatXRefs = \"xrefs\"\n\n\tStatRRefs = \"rrefs\"\n\n\tStatURefs = \"urefs\"\n\n\tStatAuthors = \"authors\"\n\n\tStatClients = \"clients\"\n\n\tStatDependents = \"dependents\"\n\n\tStatExportedElements = \"exported_elements\"\n)\n\nvar AllStatTypes = []StatType{StatXRefs, StatRRefs, StatURefs, StatAuthors, StatClients, StatDependents, StatExportedElements}\n\nfunc (x StatType) IsAbstract() bool {\n\tswitch x {\n\tcase StatXRefs:\n\t\tfallthrough\n\tcase StatClients:\n\t\tfallthrough\n\tcase StatDependents:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\nfunc (x StatType) Value() (driver.Value, error) {\n\treturn string(x), nil\n}\n\n\n\n\n\n\n\nfunc UniqueRefDefs(refs []*Ref, m map[RefDefKey]int) map[RefDefKey]int {\n\tif m == nil {\n\t\tm = make(map[RefDefKey]int)\n\t}\n\tfor _, ref := range refs {\n\t\tm[ref.RefDefKey()]++\n\t}\n\treturn m\n}\n\nfunc (x *StatType) Scan(v interface{}) error ", "output": "{\n\tif data, ok := v.([]byte); ok {\n\t\t*x = StatType(data)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"%T.Scan failed: %v\", x, v)\n}"} {"input": "package gostarter\n\nimport \"github.com/codegangsta/cli\"\n\n\nfunc App() *cli.App {\n\tapp := cli.NewApp()\n\tapp.Name = \"gostarter\"\n\tapp.Usage = \"make an explosive entrance\"\n\tapp.Action = func(c *cli.Context) {\n\t\tprintln(\"boom! I say!\")\n\t}\n\n\treturn app\n}\n\n\n\n\nfunc Echo(e string) string ", "output": "{\n\treturn e\n}"} {"input": "package cgzip\n\n\nimport \"C\"\n\nimport (\n\t\"hash\"\n\t\"unsafe\"\n)\n\ntype adler32Hash struct {\n\tadler C.uLong\n}\n\n\n\nfunc NewAdler32() hash.Hash32 {\n\ta := &adler32Hash{}\n\ta.Reset()\n\treturn a\n}\n\n\n\n\n\nfunc (a *adler32Hash) Sum(b []byte) []byte {\n\ts := a.Sum32()\n\tb = append(b, byte(s>>24))\n\tb = append(b, byte(s>>16))\n\tb = append(b, byte(s>>8))\n\tb = append(b, byte(s))\n\treturn b\n}\n\nfunc (a *adler32Hash) Reset() {\n\ta.adler = C.adler32(0, (*C.Bytef)(unsafe.Pointer(nil)), 0)\n}\n\nfunc (a *adler32Hash) Size() int {\n\treturn 4\n}\n\nfunc (a *adler32Hash) BlockSize() int {\n\treturn 1\n}\n\n\nfunc (a *adler32Hash) Sum32() uint32 {\n\treturn uint32(a.adler)\n}\n\n\n\n\n\n\n\nfunc Adler32Combine(adler1, adler2 uint32, len2 int) uint32 {\n\treturn uint32(C.adler32_combine(C.uLong(adler1), C.uLong(adler2), C.z_off_t(len2)))\n}\n\nfunc (a *adler32Hash) Write(p []byte) (n int, err error) ", "output": "{\n\tif len(p) > 0 {\n\t\ta.adler = C.adler32(a.adler, (*C.Bytef)(unsafe.Pointer(&p[0])), (C.uInt)(len(p)))\n\t}\n\treturn len(p), nil\n}"} {"input": "package telemetry\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\n\t\"github.com/pingcap/errors\"\n\tclientv3 \"go.etcd.io/etcd/client/v3\"\n)\n\nconst (\n\tstatusKey = \"/tidb/telemetry/status\"\n)\n\ntype status struct {\n\tCheckAt string `json:\"check_at\"`\n\tIsError bool `json:\"is_error\"`\n\tErrorMessage string `json:\"error_msg\"`\n\tIsRequestSent bool `json:\"is_request_sent\"`\n}\n\n\n\n\n\nfunc GetTelemetryStatus(etcdClient *clientv3.Client) (string, error) {\n\tif etcdClient == nil {\n\t\treturn \"\", nil\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), etcdOpTimeout)\n\tdefer cancel()\n\tresp, err := etcdClient.Get(ctx, statusKey)\n\tif err != nil {\n\t\treturn \"\", errors.Trace(err)\n\t}\n\tif len(resp.Kvs) == 0 {\n\t\treturn \"\", nil\n\t}\n\treturn string(resp.Kvs[0].Value), nil\n}\n\nfunc updateTelemetryStatus(s status, etcdClient *clientv3.Client) error ", "output": "{\n\tif etcdClient == nil {\n\t\treturn nil\n\t}\n\tj, err := json.MarshalIndent(s, \"\", \" \")\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), etcdOpTimeout)\n\tdefer cancel()\n\t_, err = etcdClient.Put(ctx, statusKey, string(j))\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\treturn nil\n}"} {"input": "package utils\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestDefaultInsecureClient(t *testing.T) ", "output": "{\n\tdefaultClient := DefaultInsecureClient()\n\tif defaultClient == nil {\n\t\tt.Fatalf(\"the defaultClient cannot be nil\")\n\t}\n\tif defaultClient.Transport == nil {\n\t\tt.Errorf(\"Transport cannot be nil\")\n\t}\n}"} {"input": "package nodes\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\ntype Name struct {\n\tTaxID string `json:\"TaxID\"`\n\tNames []NameItem `json:\"Names\"`\n}\n\n\ntype NameItem struct {\n\tName string `json:\"Name\"`\n\tUniqueName string `json:\"UniqueName\"`\n\tNameClass string `json:\"NameClass\"`\n}\n\n\nfunc (name Name) ToJSON() (string, error) {\n\ts, err := json.Marshal(name)\n\treturn string(s), err\n}\n\n\nfunc NameFromJSON(s string) (Name, error) {\n\tvar name Name\n\terr := json.Unmarshal([]byte(s), &name)\n\treturn name, err\n}\n\n\n\n\n\nfunc MergeNames(names ...Name) Name {\n\tif len(names) < 2 {\n\t\treturn names[0]\n\t}\n\tname := names[0]\n\tfor _, another := range names[1:] {\n\t\tif another.TaxID != name.TaxID {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, anotherNameItem := range another.Names {\n\t\t\tname.Names = append(name.Names, anotherNameItem)\n\t\t}\n\t}\n\treturn name\n}\n\n\nvar Names map[string]Name\n\nvar mutex1 = &sync.Mutex{}\n\n\nfunc SetNames(names map[string]Name) {\n\tmutex1.Lock()\n\tNames = names\n\tmutex1.Unlock()\n}\n\nfunc NameFromArgs(items []string) Name ", "output": "{\n\tif len(items) != 4 {\n\t\treturn Name{}\n\t}\n\n\treturn Name{\n\t\tTaxID: items[0],\n\t\tNames: []NameItem{\n\t\t\tNameItem{\n\t\t\t\tName: items[1],\n\t\t\t\tUniqueName: items[2],\n\t\t\t\tNameClass: items[3],\n\t\t\t}},\n\t}\n}"} {"input": "package main\n\nimport . \"g2d\"\n\nvar arena = NewArena(Point{480, 360})\nvar a1 = NewAlien(arena, Point{40, 40})\nvar a2 = NewAlien(arena, Point{80, 80})\n\ntype Alien struct {\n arena *Arena\n x, y, w, h int\n xmin, xmax int\n dx, dy int\n}\n\nfunc NewAlien(arena *Arena, pos Point) *Alien {\n a := &Alien{arena, pos.X, pos.Y, 20, 20, pos.X, pos.X+150, 5, 5}\n arena.Add(a)\n return a\n}\n\nfunc (a *Alien) Move() {\n if a.xmin <= a.x+a.dx && a.x+a.dx <= a.xmax {\n a.x += a.dx\n } else {\n a.dx = -a.dx\n a.y += a.dy\n }\n}\n\n\n\nfunc (a *Alien) Size() Point {\n return Point{a.w, a.h}\n}\n\nfunc (a *Alien) Symbol() Point {\n return Point{0, 0}\n}\n\nfunc (a *Alien) Collide(other Actor) {\n}\n\nfunc tick() {\n ClearCanvas()\n arena.MoveAll()\n for _, actor := range arena.Actors() {\n FillRect(actor.Position(), actor.Size())\n }\n}\n\nfunc main() {\n InitCanvas(arena.Size())\n MainLoop(tick)\n}\n\nfunc (a *Alien) Position() Point ", "output": "{\n return Point{a.x, a.y}\n}"} {"input": "package main\n\nvar (\n\tJsonApiErrAlertNotFound = JsonapiError{\n\t\tStatus: \"404\",\n\t\tCode: \"A404\",\n\t\tDetail: \"The requested alert couldn't be found in database.\",\n\t}\n)\n\n\ntype JsonapiLink struct {\n\tHref string `json:\"href\"`\n\tMeta string `json:\"meta,omitempty\"`\n}\n\n\ntype JsonapiError struct {\n\tId int `json:\"id,omitempty\"` \n\tStatus string `json:\"status,omitempty\"` \n\tLinks []JsonapiLink `json:\"links,omitempty\"` \n\tCode string `json:\"code,omitempty\"` \n\tTitle string `json:\"title,omitempty\"` \n\tDetail string `json:\"detail,omitempty\"` \n\tMeta string `json:\"meta,omitempty\"` \n}\n\ntype JsonapiResponse struct {\n\tData interface{} `json:\"data,omitempty\"`\n\tErrors []string `json:\"errors,omitempty\"`\n}\n\nfunc JsonapiWrap(data interface{}) JsonapiResponse {\n\treturn JsonapiResponse{Data: data}\n}\n\n\n\nfunc JsonapiWrapError(err error) JsonapiResponse ", "output": "{\n\treturn JsonapiResponse{Errors: []string{err.Error()}}\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realIAMInstanceProfile IAMInstanceProfile\n\n\nfunc (o *IAMInstanceProfile) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realIAMInstanceProfile\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = IAMInstanceProfile(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &IAMInstanceProfile{}\n\n\n\n\nvar _ fi.HasName = &IAMInstanceProfile{}\n\n\nfunc (o *IAMInstanceProfile) GetName() *string {\n\treturn o.Name\n}\n\n\nfunc (o *IAMInstanceProfile) SetName(name string) {\n\to.Name = &name\n}\n\n\nfunc (o *IAMInstanceProfile) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *IAMInstanceProfile) GetLifecycle() *fi.Lifecycle ", "output": "{\n\treturn o.Lifecycle\n}"} {"input": "package integration\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestNetwork(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Network\")\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateDbHomeRequest struct {\n\n\tCreateDbHomeWithDbSystemIdDetails CreateDbHomeBase `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateDbHomeRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request CreateDbHomeRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CreateDbHomeRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateDbHomeResponse struct {\n\n\tRawResponse *http.Response\n\n\tDbHome `presentIn:\"body\"`\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateDbHomeResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateDbHomeResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateDbHomeRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package state\n\nimport (\n\t\"net/url\"\n\n\t\"gopkg.in/juju/charm.v3\"\n)\n\n\ntype charmDoc struct {\n\tURL *charm.URL `bson:\"_id\"`\n\tMeta *charm.Meta\n\tConfig *charm.Config\n\tActions *charm.Actions\n\tBundleURL *url.URL\n\tBundleSha256 string\n\tPendingUpload bool\n\tPlaceholder bool\n}\n\n\ntype Charm struct {\n\tst *State\n\tdoc charmDoc\n}\n\nfunc newCharm(st *State, cdoc *charmDoc) (*Charm, error) {\n\treturn &Charm{st: st, doc: *cdoc}, nil\n}\n\n\n\n\nfunc (c *Charm) URL() *charm.URL {\n\tclone := *c.doc.URL\n\treturn &clone\n}\n\n\n\nfunc (c *Charm) Revision() int {\n\treturn c.doc.URL.Revision\n}\n\n\nfunc (c *Charm) Meta() *charm.Meta {\n\treturn c.doc.Meta\n}\n\n\nfunc (c *Charm) Config() *charm.Config {\n\treturn c.doc.Config\n}\n\n\nfunc (c *Charm) Actions() *charm.Actions {\n\treturn c.doc.Actions\n}\n\n\n\nfunc (c *Charm) BundleURL() *url.URL {\n\treturn c.doc.BundleURL\n}\n\n\nfunc (c *Charm) BundleSha256() string {\n\treturn c.doc.BundleSha256\n}\n\n\n\nfunc (c *Charm) IsUploaded() bool {\n\treturn !c.doc.PendingUpload\n}\n\n\n\nfunc (c *Charm) IsPlaceholder() bool {\n\treturn c.doc.Placeholder\n}\n\nfunc (c *Charm) String() string ", "output": "{\n\treturn c.doc.URL.String()\n}"} {"input": "package handlers\n\nimport (\n\t\"net/http\"\n\n\t\"code.cloudfoundry.org/lager\"\n\t\"github.com/cloudfoundry/hm9000/apiserver\"\n\t\"github.com/cloudfoundry/hm9000/store\"\n\t\"code.cloudfoundry.org/clock\"\n\t\"github.com/tedsuo/rata\"\n)\n\n\n\nfunc New(logger lager.Logger, store store.Store, clock clock.Clock) (http.Handler, error) ", "output": "{\n\thandlers := map[string]http.Handler{\n\t\t\"bulk_app_state\": NewBulkAppStateHandler(logger, store, clock),\n\t}\n\n\treturn rata.NewRouter(apiserver.Routes, handlers)\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/networking/v1\"\n\t\"k8s.io/client-go/deprecated/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype NetworkingV1Interface interface {\n\tRESTClient() rest.Interface\n\tNetworkPoliciesGetter\n}\n\n\ntype NetworkingV1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *NetworkingV1Client) NetworkPolicies(namespace string) NetworkPolicyInterface {\n\treturn newNetworkPolicies(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*NetworkingV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &NetworkingV1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *NetworkingV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *NetworkingV1Client {\n\treturn &NetworkingV1Client{c}\n}\n\n\n\n\n\nfunc (c *NetworkingV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc setConfigDefaults(config *rest.Config) error ", "output": "{\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}"} {"input": "package in\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/blevesearch/bleve/analysis\"\n\t\"github.com/blevesearch/bleve/registry\"\n)\n\nconst NormalizeName = \"normalize_in\"\n\ntype IndicNormalizeFilter struct {\n}\n\nfunc NewIndicNormalizeFilter() *IndicNormalizeFilter {\n\treturn &IndicNormalizeFilter{}\n}\n\nfunc (s *IndicNormalizeFilter) Filter(input analysis.TokenStream) analysis.TokenStream {\n\tfor _, token := range input {\n\t\trunes := bytes.Runes(token.Term)\n\t\trunes = normalize(runes)\n\t\ttoken.Term = analysis.BuildTermFromRunes(runes)\n\t}\n\treturn input\n}\n\nfunc NormalizerFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) {\n\treturn NewIndicNormalizeFilter(), nil\n}\n\n\n\nfunc init() ", "output": "{\n\tregistry.RegisterTokenFilter(NormalizeName, NormalizerFilterConstructor)\n}"} {"input": "package state\n\nimport (\n\t\"net/url\"\n\n\t\"gopkg.in/juju/charm.v3\"\n)\n\n\ntype charmDoc struct {\n\tURL *charm.URL `bson:\"_id\"`\n\tMeta *charm.Meta\n\tConfig *charm.Config\n\tActions *charm.Actions\n\tBundleURL *url.URL\n\tBundleSha256 string\n\tPendingUpload bool\n\tPlaceholder bool\n}\n\n\ntype Charm struct {\n\tst *State\n\tdoc charmDoc\n}\n\nfunc newCharm(st *State, cdoc *charmDoc) (*Charm, error) {\n\treturn &Charm{st: st, doc: *cdoc}, nil\n}\n\nfunc (c *Charm) String() string {\n\treturn c.doc.URL.String()\n}\n\n\nfunc (c *Charm) URL() *charm.URL {\n\tclone := *c.doc.URL\n\treturn &clone\n}\n\n\n\nfunc (c *Charm) Revision() int {\n\treturn c.doc.URL.Revision\n}\n\n\nfunc (c *Charm) Meta() *charm.Meta {\n\treturn c.doc.Meta\n}\n\n\nfunc (c *Charm) Config() *charm.Config {\n\treturn c.doc.Config\n}\n\n\nfunc (c *Charm) Actions() *charm.Actions {\n\treturn c.doc.Actions\n}\n\n\n\nfunc (c *Charm) BundleURL() *url.URL {\n\treturn c.doc.BundleURL\n}\n\n\nfunc (c *Charm) BundleSha256() string {\n\treturn c.doc.BundleSha256\n}\n\n\n\n\n\n\n\nfunc (c *Charm) IsPlaceholder() bool {\n\treturn c.doc.Placeholder\n}\n\nfunc (c *Charm) IsUploaded() bool ", "output": "{\n\treturn !c.doc.PendingUpload\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"os/exec\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n\nfunc getPing(c *gin.Context) {\n\tc.String(200, \"pong\")\n}\n\n\n\nfunc addRouteWithoutArg(name string, cmd string, router *gin.RouterGroup) {\n\tlog.Printf(\"Configuring route %s with command: %s\\n\", name, cmd)\n\trouter.GET(name, func(c *gin.Context) {\n\t\tif cmdOut, err := exec.Command(cmd).Output(); err == nil {\n\t\t\tc.JSON(http.StatusOK, gin.H{\"status\": \"ok\", \"cmd\": string(cmd), \"stdout\": string(cmdOut)})\n\t\t}\n\t})\n}\n\nfunc addRouteWithArg(name string, cmd string, router *gin.RouterGroup) ", "output": "{\n\tlog.Printf(\"Configuring route %v with command %s and argument\\n\", name, cmd)\n\tpath := name + \"/:arg\"\n\trouter.GET(path, func(c *gin.Context) {\n\t\targ := c.Params.ByName(\"arg\")\n\t\tif cmdOut, err := exec.Command(cmd, arg).Output(); err == nil {\n\t\t\tc.JSON(http.StatusOK, gin.H{\"status\": \"ok\", \"cmd\": string(cmd), \"argument\": string(arg), \"stdout\": string(cmdOut)})\n\t\t}\n\t})\n}"} {"input": "package route\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"regexp\"\n)\n\ntype HandlerFunc http.HandlerFunc\n\ntype SelectHandler interface {\n\tSelect([]string) bool\n\tServeHTTP(w http.ResponseWriter, r *http.Request)\n}\n\ntype route struct {\n\tre *regexp.Regexp\n\thandler SelectHandler\n}\n\ntype ReHandler struct {\n\troutes []*route\n\tNotFound HandlerFunc\n}\n\nfunc New() (re *ReHandler) {\n\treturn &ReHandler{NotFound: http.NotFound}\n}\n\nfunc (f HandlerFunc) Select(_ []string) bool {\n\treturn true\n}\n\nfunc (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tf(w, r)\n}\n\nfunc (h *ReHandler) Handle(re string, handler SelectHandler) {\n\tlog.Println(\"SelectHandler\", re)\n\tr := &route{\n\t\tre: regexp.MustCompile(re),\n\t\thandler: handler,\n\t}\n\th.routes = append(h.routes, r)\n}\n\nfunc (h *ReHandler) HandleFunc(re string, handler HandlerFunc) {\n\tlog.Println(\"HandlerFunc\", re)\n\tr := &route{\n\t\tre: regexp.MustCompile(re),\n\t\thandler: handler,\n\t}\n\th.routes = append(h.routes, r)\n}\n\n\n\nfunc (h *ReHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tlog.Println(r.Method, r.URL)\n\tfor _, route := range h.routes {\n\t\tmatches := route.re.FindStringSubmatch(r.URL.Path)\n\t\tif matches != nil {\n\t\t\tlog.Println(\"Match\", matches, r.URL)\n\t\t\tif !route.handler.Select(matches[1:]) {\n\t\t\t\tlog.Println(route.re, \"NotFound\")\n\t\t\t\th.NotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tr.ParseForm()\n\t\t\troute.handler.ServeHTTP(w, r)\n\t\t\tif r.Method == \"POST\" {\n\t\t\t\thttp.Redirect(w, r, r.URL.Path, http.StatusFound)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\th.NotFound(w, r)\n}"} {"input": "package libkey\n\nimport (\n\t\"context\"\n\n\t\"github.com/keybase/client/go/kbfs/idutil\"\n\t\"github.com/keybase/client/go/kbfs/kbfscrypto\"\n\t\"github.com/keybase/client/go/kbfs/kbfsmd\"\n\t\"github.com/keybase/client/go/protocol/keybase1\"\n)\n\n\n\ntype KeyOpsConfig interface {\n\tKeyServer() KeyServer\n\tKBPKI() idutil.KBPKI\n}\n\n\n\ntype KeyOpsStandard struct {\n\tconfig KeyOpsConfig\n}\n\n\nfunc NewKeyOpsStandard(config KeyOpsConfig) *KeyOpsStandard {\n\treturn &KeyOpsStandard{config}\n}\n\n\nvar _ KeyOps = (*KeyOpsStandard)(nil)\n\n\n\n\n\nfunc (k *KeyOpsStandard) PutTLFCryptKeyServerHalves(\n\tctx context.Context,\n\tkeyServerHalves kbfsmd.UserDeviceKeyServerHalves) error {\n\treturn k.config.KeyServer().PutTLFCryptKeyServerHalves(ctx, keyServerHalves)\n}\n\n\nfunc (k *KeyOpsStandard) DeleteTLFCryptKeyServerHalf(\n\tctx context.Context, uid keybase1.UID, key kbfscrypto.CryptPublicKey,\n\tserverHalfID kbfscrypto.TLFCryptKeyServerHalfID) error {\n\treturn k.config.KeyServer().DeleteTLFCryptKeyServerHalf(\n\t\tctx, uid, key, serverHalfID)\n}\n\nfunc (k *KeyOpsStandard) GetTLFCryptKeyServerHalf(\n\tctx context.Context, serverHalfID kbfscrypto.TLFCryptKeyServerHalfID,\n\tkey kbfscrypto.CryptPublicKey) (kbfscrypto.TLFCryptKeyServerHalf, error) ", "output": "{\n\tserverHalf, err := k.config.KeyServer().GetTLFCryptKeyServerHalf(\n\t\tctx, serverHalfID, key)\n\tif err != nil {\n\t\treturn kbfscrypto.TLFCryptKeyServerHalf{}, err\n\t}\n\tsession, err := k.config.KBPKI().GetCurrentSession(ctx)\n\tif err != nil {\n\t\treturn kbfscrypto.TLFCryptKeyServerHalf{}, err\n\t}\n\n\terr = kbfscrypto.VerifyTLFCryptKeyServerHalfID(\n\t\tserverHalfID, session.UID, key, serverHalf)\n\tif err != nil {\n\t\treturn kbfscrypto.TLFCryptKeyServerHalf{}, err\n\t}\n\treturn serverHalf, nil\n}"} {"input": "package disk\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/object\"\n)\n\ntype shrink struct {\n\t*flags.DatastoreFlag\n\n\tcopy *bool\n}\n\n\n\nfunc (cmd *shrink) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)\n\tcmd.DatastoreFlag.Register(ctx, f)\n\n\tf.Var(flags.NewOptionalBool(&cmd.copy), \"copy\", \"Perform shrink in-place mode if false, copy-shrink mode otherwise\")\n}\n\nfunc (cmd *shrink) Process(ctx context.Context) error {\n\treturn cmd.DatastoreFlag.Process(ctx)\n}\n\nfunc (cmd *shrink) Usage() string {\n\treturn \"VMDK\"\n}\n\nfunc (cmd *shrink) Description() string {\n\treturn `Shrink VMDK on DS.\n\nExamples:\n govc datastore.disk.shrink disks/disk1.vmdk`\n}\n\nfunc (cmd *shrink) Run(ctx context.Context, f *flag.FlagSet) error {\n\tdc, err := cmd.Datacenter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tds, err := cmd.Datastore()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm := object.NewVirtualDiskManager(ds.Client())\n\tpath := ds.Path(f.Arg(0))\n\ttask, err := m.ShrinkVirtualDisk(ctx, path, dc, cmd.copy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger := cmd.ProgressLogger(fmt.Sprintf(\"Shrinking %s...\", path))\n\tdefer logger.Wait()\n\n\t_, err = task.WaitForResult(ctx, logger)\n\treturn err\n}\n\nfunc init() ", "output": "{\n\tcli.Register(\"datastore.disk.shrink\", &shrink{})\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/docker/infrakit/pkg/types\"\n)\n\ntype errBadDependency types.Dependency\n\n\n\ntype errCircularDependency []*types.Spec\n\nfunc (e errCircularDependency) Error() string {\n\tdeps := []*types.Spec(e)\n\tlist := fmt.Sprintf(\"%s/%s\", deps[0].Class, deps[0].Metadata.Name)\n\tfor _, dep := range deps[1:] {\n\t\tlist = list + fmt.Sprintf(\"=> %s/%s\", dep.Class, dep.Metadata.Name)\n\t}\n\treturn fmt.Sprintf(\"circular dependency: %s\", list)\n}\n\ntype errNotFound struct {\n\tclass string\n\tname string\n}\n\nfunc (e errNotFound) Error() string {\n\treturn fmt.Sprintf(\"not found %s/%s\", e.class, e.name)\n}\n\nfunc (e errBadDependency) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"unresolved dependency: class=%s name=%s\", types.Dependency(e).Class, types.Dependency(e).Name)\n}"} {"input": "package simplecli\n\n\ntype CLISetting struct {\n\tcli *CLI\n}\n\n\n\n\n\nfunc (c *CLISetting) ConfigFile(path string) func() {\n\treturn func() {\n\t\tc.cli.ConfigFile = path\n\t}\n}\n\nfunc (c *CLISetting) ConfigSearchPath(paths ...string) func() ", "output": "{\n\treturn func() {\n\t\tc.cli.ConfigSearchPath = paths[:]\n\t}\n}"} {"input": "package ui\n\nfunc About() string {\n\treturn \"go-ui 0.1.1 \"\n}\n\n\n\nfunc Main(fn func()) int {\n\tfnAppMain = fn\n\treturn theApp.AppMain()\n}\n\nfunc Run() int {\n\treturn theApp.Run()\n}\n\nfunc Exit(code int) {\n\ttheApp.Exit(code)\n}\n\nfunc CloseAllWindows() {\n\ttheApp.CloseAllWindows()\n}\n\nfunc App() *app {\n\treturn &theApp\n}\n\nfunc Version() string ", "output": "{\n\treturn \"go-ui 0.1.1\"\n}"} {"input": "package astutils\n\nimport (\n\t\"go/ast\"\n\t\"go/types\"\n)\n\n\n\n\n\nfunc FieldListNames(fieldList *ast.FieldList, position int) []*ast.Ident {\n\tif fieldList == nil {\n\t\treturn nil\n\t}\n\n\tif len(fieldList.List) <= position {\n\t\treturn nil\n\t}\n\n\tfield := fieldList.List[position]\n\n\tif field == nil {\n\t\treturn nil\n\t}\n\n\treturn field.Names\n}\n\n\nfunc FieldListType(fieldList *ast.FieldList, position int) *ast.Expr {\n\tif fieldList == nil {\n\t\treturn nil\n\t}\n\n\tif len(fieldList.List) <= position {\n\t\treturn nil\n\t}\n\n\tfield := fieldList.List[position]\n\n\tif field == nil {\n\t\treturn nil\n\t}\n\n\treturn &field.Type\n}\n\n\n\nfunc HasFieldListLength(fieldList *ast.FieldList, expectedLength int) bool {\n\tif fieldList == nil {\n\t\treturn expectedLength == 0\n\t}\n\n\treturn len(fieldList.List) == expectedLength\n}\n\n\nfunc IsFieldListType(fieldList *ast.FieldList, position int, exprFunc func(ast.Expr) bool) bool {\n\tt := FieldListType(fieldList, position)\n\n\treturn t != nil && exprFunc(*t)\n}\n\n\nfunc IsFieldListTypePackageType(fieldList *ast.FieldList, position int, info *types.Info, packageSuffix string, typeName string) bool {\n\tt := FieldListType(fieldList, position)\n\n\treturn t != nil && IsPackageFunctionFieldListType(*t, info, packageSuffix, typeName)\n}\n\nfunc FieldListName(fieldList *ast.FieldList, fieldPosition int, namePosition int) *string ", "output": "{\n\tnames := FieldListNames(fieldList, fieldPosition)\n\n\tif names == nil || len(names) <= namePosition {\n\t\treturn nil\n\t}\n\n\tname := names[namePosition]\n\n\tif name == nil {\n\t\treturn nil\n\t}\n\n\treturn &name.Name\n}"} {"input": "package model\n\ntype Interface interface {\n\tVisitString(name string, resume func())\n\tVisitInt(name string, resume func())\n\tVisitFloat(name string, resume func())\n\tVisitBool(name string, resume func())\n\tVisitPtr(name string, resume func())\n\tVisitBytes(name string, resume func())\n\tVisitSlice(name string, resume func())\n\tVisitStruct(name string, fields []Field, resume func())\n\tVisitStructField(field Field, resume func())\n\tVisitMap(name string, resume func())\n\tVisitCustom(name string, resume func())\n\tVisitReference(name string, resume func())\n}\n\ntype Visitor struct{}\n\nfunc (self *Visitor) VisitString(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitInt(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitFloat(name string, resume func()) {\n\tresume()\n}\n\n\n\nfunc (self *Visitor) VisitPtr(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBytes(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitSlice(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStructField(field Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitMap(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitCustom(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitReference(name string, resume func()) {\n\tresume()\n}\n\ntype EmbeddedStructVisitor struct {\n\tInterface\n}\n\nfunc (self *EmbeddedStructVisitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBool(name string, resume func()) ", "output": "{\n\tresume()\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n)\n\nfunc main() {\n\ttests := [][]int32{{1, 2, 3, 4, 5}}\n\n\tfor _, test := range tests {\n\t\tlog.Printf(\"LeftRotate(%v) == %v\\n\", test, LeftRotate(test, 2))\n\t}\n}\n\n\n\n\n\nfunc RightRotate(n []int32, x int32) []int32 {\n\tif len(n) <= 1 {\n\t\treturn n\n\t}\n\n var j int32\n\tfor j = 0; j < x; j++ {\n\t\ttmp := n[len(n)-1]\n\n\t\tfor i := len(n) - 1; i > 0; i-- {\n\t\t\tn[i] = n[i-1]\n\t\t}\n\n\t\tn[0] = tmp\n\t}\n\n\treturn n\n}\n\nfunc LeftRotate(n []int32, x int32) []int32 ", "output": "{\n if len(n) <= 1 {\n return n\n }\n\n var j int32\n for j = 0; j < x; j++ {\n tmp := n[0]\n\n for i := 1; i < len(n); i++ {\n n[i-1] = n[i] \n }\n\n n[len(n)-1] = tmp\n }\n\n return n\n}"} {"input": "package main\n\nimport (\n\t\"github.com/mycaosf/gui\"\n\t\"github.com/mycaosf/winapi\"\n)\n\ntype aboutDialog struct {\n\tgui.BaseDialog\n}\n\nfunc (p *aboutDialog) Reg() {\n\tp.BaseDialog.Reg()\n\tp.RegCmd(winapi.IDOK, p.OnOk)\n}\n\nfunc (p *aboutDialog) OnOk(cmd *winapi.CMD) {\n\tp.End(winapi.IDOK)\n}\n\n\n\nfunc runAboutDialog(res *gui.Resource, parent winapi.HWND) ", "output": "{\n\tvar dlg aboutDialog\n\tdlg.Reg()\n\tdlg.DlgBox(res.Get(), \"AboutDlg\", parent)\n}"} {"input": "package group\n\nimport (\n\t\"net/http\"\n\n\t\"k8s.io/apiserver/pkg/authentication/authenticator\"\n\t\"k8s.io/apiserver/pkg/authentication/user\"\n)\n\n\ntype AuthenticatedGroupAdder struct {\n\tAuthenticator authenticator.Request\n}\n\n\n\n\n\n\nfunc (g *AuthenticatedGroupAdder) AuthenticateRequest(req *http.Request) (user.Info, bool, error) {\n\tu, ok, err := g.Authenticator.AuthenticateRequest(req)\n\tif err != nil || !ok {\n\t\treturn nil, ok, err\n\t}\n\n\tif u.GetName() == user.Anonymous {\n\t\treturn u, true, nil\n\t}\n\tfor _, group := range u.GetGroups() {\n\t\tif group == user.AllAuthenticated || group == user.AllUnauthenticated {\n\t\t\treturn u, true, nil\n\t\t}\n\t}\n\n\treturn &user.DefaultInfo{\n\t\tName: u.GetName(),\n\t\tUID: u.GetUID(),\n\t\tGroups: append(u.GetGroups(), user.AllAuthenticated),\n\t\tExtra: u.GetExtra(),\n\t}, true, nil\n}\n\nfunc NewAuthenticatedGroupAdder(auth authenticator.Request) authenticator.Request ", "output": "{\n\treturn &AuthenticatedGroupAdder{auth}\n}"} {"input": "package storageprovisioner_test\n\nimport (\n\tstdtesting \"testing\"\n\n\tgc \"gopkg.in/check.v1\"\n)\n\n\n\nfunc TestAll(t *stdtesting.T) ", "output": "{\n\tgc.TestingT(t)\n}"} {"input": "package ui \n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"miniflux.app/http/request\"\n\t\"miniflux.app/http/response\"\n\t\"miniflux.app/http/response/html\"\n\t\"miniflux.app/ui/static\"\n)\n\n\n\nfunc (h *handler) showJavascript(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tfilename := request.RouteStringParam(r, \"name\")\n\tetag, found := static.JavascriptsChecksums[filename]\n\tif !found {\n\t\thtml.NotFound(w, r)\n\t\treturn\n\t}\n\n\tresponse.New(w, r).WithCaching(etag, 48*time.Hour, func(b *response.Builder) {\n\t\tb.WithHeader(\"Content-Type\", \"text/javascript; charset=utf-8\")\n\t\tb.WithBody(static.Javascripts[filename])\n\t\tb.Write()\n\t})\n}"} {"input": "package action\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n)\n\ntype kvRead struct {\n\trecurse bool\n\n\t*config\n}\n\nfunc KvReadAction() Action {\n\treturn &kvRead{\n\t\tconfig: &gConfig,\n\t}\n}\n\n\n\nfunc (k *kvRead) Run(args []string) error {\n\tif len(args) != 1 {\n\t\treturn fmt.Errorf(\"A single key path must be specified\")\n\t}\n\tpath := args[0]\n\n\tclient, err := k.newKv()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tqueryOpts := k.queryOptions()\n\n\tif k.recurse {\n\t\tkvlist, _, err := client.List(path, queryOpts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif kvlist == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn k.OutputKv(kvlist)\n\t} else {\n\t\tkv, _, err := client.Get(path, queryOpts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif kv == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn k.OutputKv(kv)\n\t}\n}\n\nfunc (k *kvRead) CommandFlags() *flag.FlagSet ", "output": "{\n\tf := k.newFlagSet(FLAG_DATACENTER, FLAG_KVOUTPUT, FLAG_CONSISTENCY, FLAG_BLOCKING)\n\n\tf.BoolVar(&k.recurse, \"recurse\", false, \"Perform a recursive read\")\n\n\treturn f\n}"} {"input": "package node\n\nimport (\n\t\"bytes\"\n\n\t\"golang.org/x/net/html\"\n)\n\n\nfunc Attr(n *html.Node, key string) (string, bool) {\n\tfor _, a := range n.Attr {\n\t\tif a.Key == key {\n\t\t\treturn a.Val, true\n\t\t}\n\t}\n\treturn \"\", false\n}\n\n\n\nfunc Children(n *html.Node, filter func(*html.Node) bool) []*html.Node {\n\tnodes := make([]*html.Node, 0)\n\n\tif filter == nil {\n\t\tfilter = func(*html.Node) bool { return true }\n\t}\n\n\tfor c := n.FirstChild; c != nil; c = c.NextSibling {\n\t\tif !filter(c) {\n\t\t\tcontinue\n\t\t}\n\t\tnodes = append(nodes, c)\n\n\t}\n\treturn nodes\n}\n\n\n\n\nfunc JoinData(n ...*html.Node) string ", "output": "{\n\tvar buf bytes.Buffer\n\tfor _, m := range n {\n\t\tbuf.WriteString(m.Data)\n\t}\n\treturn buf.String()\n}"} {"input": "package util\n\nimport (\n\t\"github.com/bysir-zl/bygo/log\"\n\t\"testing\"\n)\n\n\n\nfunc TestOrderKV(t *testing.T) ", "output": "{\n\to := OrderKV{}\n\to.Add(\"a\", \"1\")\n\to.Add(\"a\", \"2\")\n\to.Set(\"c\", \"1\")\n\to.Add(\"b\", \"1\")\n\to.Set(\"b\", \"2\")\n\to.Add(\"c\", \"2\")\n\n\to.Sort()\n\n\tlog.Verbose(\"Test\",string(o.Encode())) \n}"} {"input": "package entity\n\nimport (\n\t\"database/sql\"\n)\n\n\n\n\n\n\ntype GomaNumericTypes struct {\n\tID int64 `goma:\"size:20:pk\"`\n\tTinyintColumns int `goma:\"size:4\"`\n\tBoolColumns bool `goma:\"size:1\"`\n\tSmallintColumns int `goma:\"size:6\"`\n\tMediumintColumns int `goma:\"size:9\"`\n\tIntColumns int `goma:\"size:11\"`\n\tIntegerColumns int `goma:\"size:11\"`\n\tSerialColumns int64 `goma:\"size:20\"`\n\tDecimalColumns string `goma:\"size:10\"`\n\tNumericColumns string `goma:\"size:10\"`\n\tFloatColumns float32 `goma:\"\"`\n\tDoubleColumns float64 `goma:\"\"`\n}\n\n\n\n\nfunc (e *GomaNumericTypes) Scan(rows *sql.Rows) error ", "output": "{\n\terr := rows.Scan(&e.ID, &e.TinyintColumns, &e.BoolColumns, &e.SmallintColumns, &e.MediumintColumns, &e.IntColumns, &e.IntegerColumns, &e.SerialColumns, &e.DecimalColumns, &e.NumericColumns, &e.FloatColumns, &e.DoubleColumns)\n\n\treturn err\n}"} {"input": "package templates\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewGetTemplatesLibraryParams() *GetTemplatesLibraryParams {\n\n\treturn &GetTemplatesLibraryParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\nfunc NewGetTemplatesLibraryParamsWithTimeout(timeout time.Duration) *GetTemplatesLibraryParams {\n\n\treturn &GetTemplatesLibraryParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype GetTemplatesLibraryParams struct {\n\ttimeout time.Duration\n}\n\n\n\n\nfunc (o *GetTemplatesLibraryParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error ", "output": "{\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package cloudguard\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype UpdateManagedListRequest struct {\n\n\tManagedListId *string `mandatory:\"true\" contributesTo:\"path\" name:\"managedListId\"`\n\n\tUpdateManagedListDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateManagedListRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request UpdateManagedListRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request UpdateManagedListRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateManagedListResponse struct {\n\n\tRawResponse *http.Response\n\n\tManagedList `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateManagedListResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateManagedListResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateManagedListRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package gonum\n\nimport \"gonum.org/v1/gonum/lapack\"\n\n\n\n\ntype Implementation struct{}\n\nvar _ lapack.Float64 = Implementation{}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n\n\nfunc abs(a int) int {\n\tif a < 0 {\n\t\treturn -a\n\t}\n\treturn a\n}\n\nconst (\n\tdlamchE = 1.0 / (1 << 53)\n\n\tdlamchB = 2\n\n\tdlamchP = dlamchB * dlamchE\n\n\tdlamchS = 1.0 / (1 << 256) / (1 << 256) / (1 << 256) / (1 << 254)\n)\n\nfunc max(a, b int) int ", "output": "{\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}"} {"input": "package core\n\nimport (\n\t\"github.com/jinzhu/gorm\"\n\t\"time\"\n)\n\ntype Route struct {\n\tID uint `gorm:\"primary_key\"`\n\tCreatedAt time.Time\n\tUpdatedAt time.Time\n\tPath string `sql:\"type:text;not null;unique_index\"`\n\tModule string `sql:\"size:255;not null\"`\n\tEntityModel string `sql:\"size:255\"`\n\tEntityId int\n\tActive bool `sql:\"not_null\"`\n}\n\ntype Setting struct {\n\tID uint `gorm:\"primary_key\"`\n\tCreatedAt time.Time\n\tUpdatedAt time.Time\n\tKey string `sql:\"size:255;not null;unique_index\"`\n\tValue string `sql:\"type:text\"`\n}\n\n\n\nfunc DbInit(db *gorm.DB) ", "output": "{\n\tif !db.HasTable(&Route{}) {\n\t\t_ = db.CreateTable(&Route{})\n\t}\n\tif !db.HasTable(&Setting{}) {\n\t\t_ = db.CreateTable(&Setting{})\n\t}\n}"} {"input": "package auth\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/concourse/atc\"\n\n\t\"golang.org/x/crypto/bcrypt\"\n)\n\ntype BasicAuthValidator struct {\n\tDB AuthDB\n}\n\n\n\n\n\nfunc (validator BasicAuthValidator) correctCredentials(\n\tteamUsername string, teamPassword string,\n\tcheckUsername string, checkPassword string,\n) bool {\n\terr := bcrypt.CompareHashAndPassword([]byte(teamPassword), []byte(checkPassword))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn teamUsername == checkUsername\n}\n\nfunc (validator BasicAuthValidator) IsAuthenticated(r *http.Request) bool ", "output": "{\n\tauth := r.Header.Get(\"Authorization\")\n\n\tusername, password, err := extractUsernameAndPassword(auth)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tteam, found, err := validator.DB.GetTeamByName(atc.DefaultTeamName)\n\tif err != nil || !found {\n\t\treturn false\n\t}\n\n\treturn validator.correctCredentials(\n\t\tteam.BasicAuthUsername, team.BasicAuthPassword,\n\t\tusername, password,\n\t)\n}"} {"input": "package fake\n\nimport (\n\tv1 \"k8s.io/kubernetes/pkg/client/clientset_generated/release_1_3/typed/batch/v1\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n\tcore \"k8s.io/kubernetes/pkg/client/testing/core\"\n)\n\ntype FakeBatch struct {\n\t*core.Fake\n}\n\nfunc (c *FakeBatch) Jobs(namespace string) v1.JobInterface {\n\treturn &FakeJobs{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeBatch) GetRESTClient() *restclient.RESTClient ", "output": "{\n\treturn nil\n}"} {"input": "package fakes\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org/route-registrar/commandrunner\"\n\t\"code.cloudfoundry.org/route-registrar/healthchecker\"\n)\n\ntype FakeHealthChecker struct {\n\tCheckStub func(runner commandrunner.Runner, scriptPath string, timeout time.Duration) (bool, error)\n\tcheckMutex sync.RWMutex\n\tcheckArgsForCall []struct {\n\t\trunner commandrunner.Runner\n\t\tscriptPath string\n\t\ttimeout time.Duration\n\t}\n\tcheckReturns struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}\n}\n\n\n\nfunc (fake *FakeHealthChecker) CheckCallCount() int {\n\tfake.checkMutex.RLock()\n\tdefer fake.checkMutex.RUnlock()\n\treturn len(fake.checkArgsForCall)\n}\n\nfunc (fake *FakeHealthChecker) CheckArgsForCall(i int) (commandrunner.Runner, string, time.Duration) {\n\tfake.checkMutex.RLock()\n\tdefer fake.checkMutex.RUnlock()\n\treturn fake.checkArgsForCall[i].runner, fake.checkArgsForCall[i].scriptPath, fake.checkArgsForCall[i].timeout\n}\n\nfunc (fake *FakeHealthChecker) CheckReturns(result1 bool, result2 error) {\n\tfake.CheckStub = nil\n\tfake.checkReturns = struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nvar _ healthchecker.HealthChecker = new(FakeHealthChecker)\n\nfunc (fake *FakeHealthChecker) Check(runner commandrunner.Runner, scriptPath string, timeout time.Duration) (bool, error) ", "output": "{\n\tfake.checkMutex.Lock()\n\tfake.checkArgsForCall = append(fake.checkArgsForCall, struct {\n\t\trunner commandrunner.Runner\n\t\tscriptPath string\n\t\ttimeout time.Duration\n\t}{runner, scriptPath, timeout})\n\tfake.checkMutex.Unlock()\n\tif fake.CheckStub != nil {\n\t\treturn fake.CheckStub(runner, scriptPath, timeout)\n\t} else {\n\t\treturn fake.checkReturns.result1, fake.checkReturns.result2\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc checkErr(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc sanitizeName(filename string, ext string) string {\n\tfilename = strings.TrimSuffix(filename, \".\"+ext)\n\n\tfor _, s := range []string{\"_\", \"-\", \".\"} {\n\t\tfilename = strings.Replace(filename, s, \" \", -1)\n\t}\n\n\treturn strings.Title(filename)\n}\n\n\n\nfunc addSound(p string, info os.FileInfo, err error) error ", "output": "{\n\tcheckErr(err)\n\tif info.IsDir() == false {\n\t\tfor _, ext := range conf.AllowedFormats {\n\t\t\tif strings.HasSuffix(p, \".\"+ext) {\n\t\t\t\tname := strings.TrimPrefix(p, conf.Sounds+\"/\")\n\t\t\t\tsnippets = append(snippets, sound{sanitizeName(name, ext), name})\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package merkledag\n\nimport (\n\t\"context\"\n\n\tcid \"gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid\"\n\tipld \"gx/ipfs/QmR7TcHkR9nxkUorfi8XMTAMLUK7GiP64TWWBzY3aacc1o/go-ipld-format\"\n)\n\n\ntype ErrorService struct {\n\tErr error\n}\n\nvar _ ipld.DAGService = (*ErrorService)(nil)\n\n\nfunc (cs *ErrorService) Add(ctx context.Context, nd ipld.Node) error {\n\treturn cs.Err\n}\n\n\nfunc (cs *ErrorService) AddMany(ctx context.Context, nds []ipld.Node) error {\n\treturn cs.Err\n}\n\n\n\n\n\nfunc (cs *ErrorService) GetMany(ctx context.Context, cids []cid.Cid) <-chan *ipld.NodeOption {\n\tch := make(chan *ipld.NodeOption)\n\tclose(ch)\n\treturn ch\n}\n\n\nfunc (cs *ErrorService) Remove(ctx context.Context, c cid.Cid) error {\n\treturn cs.Err\n}\n\n\nfunc (cs *ErrorService) RemoveMany(ctx context.Context, cids []cid.Cid) error {\n\treturn cs.Err\n}\n\nfunc (cs *ErrorService) Get(ctx context.Context, c cid.Cid) (ipld.Node, error) ", "output": "{\n\treturn nil, cs.Err\n}"} {"input": "package handler\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/cosiner/zerver\"\n)\n\ntype MethodHandler interface {\n\tGet(zerver.Request, zerver.Response)\n\tPost(zerver.Request, zerver.Response)\n\tDelete(zerver.Request, zerver.Response)\n\tPut(zerver.Request, zerver.Response)\n\tPatch(zerver.Request, zerver.Response)\n}\n\ntype methodHandler struct {\n\tzerver.Component\n\tMethodHandler\n}\n\nfunc WrapMethodHandler(m MethodHandler) zerver.Handler {\n\treturn &methodHandler{\n\t\tComponent: zerver.NopComponent{},\n\t\tMethodHandler: m,\n\t}\n}\n\nfunc (s methodHandler) Handler(method string) zerver.HandleFunc {\n\tswitch method {\n\tcase zerver.METHOD_GET:\n\t\treturn s.Get\n\tcase zerver.METHOD_POST:\n\t\treturn s.Post\n\tcase zerver.METHOD_DELETE:\n\t\treturn s.Delete\n\tcase zerver.METHOD_PUT:\n\t\treturn s.Put\n\tcase zerver.METHOD_PATCH:\n\t\treturn s.Patch\n\t}\n\n\treturn nil\n}\n\ntype NopMethodHandler struct{}\n\nfunc (NopMethodHandler) Get(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Post(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Delete(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Put(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\n\n\nfunc (NopMethodHandler) Patch(_ zerver.Request, resp zerver.Response) ", "output": "{\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\n\t\"gopkg.in/stretchr/testify.v1/mock\"\n)\n\ntype Printer interface {\n\tHelp()\n\tVersion()\n\tMessage(msg string)\n\tError(err error)\n\tCommands()\n}\n\ntype TextPrinter struct {\n\tversion string\n}\n\nfunc NewTextPrinter(version string) *TextPrinter {\n\treturn &TextPrinter{version}\n}\n\nfunc (p *TextPrinter) Help() {\n\thelpText := `Name:\n\tfiz - a file wizard\n\nVersion:\n\t` + p.version + `\n\nUsage:\n\tfiz \n\n`\n\tp.Message(helpText)\n\tp.Commands()\n}\n\nfunc (p *TextPrinter) Version() {\n\tfmt.Println(\"fiz\", p.version)\n}\n\nfunc (p *TextPrinter) Message(msg string) {\n\tfmt.Print(msg)\n}\n\nfunc (p *TextPrinter) Error(err error) {\n\tfmt.Println(\"Error: \", err)\n}\n\n\n\n\ntype MockPrinter struct {\n\tmock.Mock\n}\n\nfunc NewMockPrinter() *MockPrinter {\n\treturn &MockPrinter{}\n}\n\nfunc (m *MockPrinter) Help() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Version() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Message(msg string) {\n\tm.Called(msg)\n}\n\nfunc (m *MockPrinter) Error(err error) {\n\tm.Called(err)\n}\n\nfunc (m *MockPrinter) Commands() {\n\tm.Called()\n}\n\nfunc (p *TextPrinter) Commands() ", "output": "{\n\tp.Message(COMMANDS_MSG)\n}"} {"input": "package connect\n\nimport \"io\"\nimport \"github.com/LilyPad/GoLilyPad/packet\"\n\ntype RequestAuthenticate struct {\n\tUsername string\n\tPassword string\n}\n\nfunc NewRequestAuthenticate(username string, password string) (this *RequestAuthenticate) {\n\tthis = new(RequestAuthenticate)\n\tthis.Username = username\n\tthis.Password = password\n\treturn\n}\n\nfunc (this *RequestAuthenticate) Id() int {\n\treturn REQUEST_AUTHENTICATE\n}\n\ntype requestAuthenticateCodec struct {\n\n}\n\nfunc (this *requestAuthenticateCodec) Decode(reader io.Reader) (request Request, err error) {\n\trequestAuthenticate := new(RequestAuthenticate)\n\trequestAuthenticate.Username, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\trequestAuthenticate.Password, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\trequest = requestAuthenticate\n\treturn\n}\n\n\n\ntype ResultAuthenticate struct {\n\n}\n\nfunc NewResultAuthenticate() (this *ResultAuthenticate) {\n\tthis = new(ResultAuthenticate)\n\treturn\n}\n\nfunc (this *ResultAuthenticate) Id() int {\n\treturn REQUEST_AUTHENTICATE\n}\n\ntype resultAuthenticateCodec struct {\n\n}\n\nfunc (this *resultAuthenticateCodec) Decode(reader io.Reader) (result Result, err error) {\n\tresult = new(ResultAuthenticate)\n\treturn\n}\n\nfunc (this *resultAuthenticateCodec) Encode(writer io.Writer, result Result) (err error) {\n\treturn\n}\n\nfunc (this *requestAuthenticateCodec) Encode(writer io.Writer, request Request) (err error) ", "output": "{\n\trequestAuthenticate := request.(*RequestAuthenticate)\n\terr = packet.WriteString(writer, requestAuthenticate.Username)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = packet.WriteString(writer, requestAuthenticate.Password)\n\treturn\n}"} {"input": "package net\n\nimport (\n\t\"time\"\n)\n\n\n\n\nfunc setKeepAlivePeriod(fd *netFD, d time.Duration) error ", "output": "{\n\tcmd := \"keepalive \" + itoa(int(d/time.Millisecond))\n\t_, e := fd.ctl.WriteAt([]byte(cmd), 0)\n\treturn e\n}"} {"input": "package compose\n\nimport (\n\t\"fmt\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\tyaml \"github.com/cloudfoundry-incubator/candiedyaml\"\n\t\"github.com/docker/libcompose/project\"\n\t\"github.com/rancher/os/config\"\n\t\"github.com/rancher/os/docker\"\n\t\"github.com/rancher/os/util/network\"\n)\n\n\n\nfunc projectReload(p *project.Project, useNetwork *bool, loadConsole bool, environmentLookup *docker.ConfigEnvironment, authLookup *docker.ConfigAuthLookup) func() error {\n\tenabled := map[interface{}]interface{}{}\n\treturn func() error {\n\t\tcfg := config.LoadConfig()\n\n\t\tenvironmentLookup.SetConfig(cfg)\n\t\tauthLookup.SetConfig(cfg)\n\n\t\tenabled = addServices(p, enabled, cfg.Rancher.Services)\n\n\t\tfor service, serviceEnabled := range cfg.Rancher.ServicesInclude {\n\t\t\tif _, ok := enabled[service]; ok || !serviceEnabled {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err := LoadService(p, cfg, *useNetwork, service); err != nil {\n\t\t\t\tif err != network.ErrNoNetwork {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tenabled[service] = service\n\t\t}\n\n\t\tif !loadConsole || cfg.Rancher.Console == \"\" || cfg.Rancher.Console == \"default\" {\n\t\t\treturn nil\n\t\t}\n\n\t\tif err := LoadService(p, cfg, *useNetwork, cfg.Rancher.Console); err != nil && err != network.ErrNoNetwork {\n\t\t\tlog.Error(err)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc LoadService(p *project.Project, cfg *config.CloudConfig, useNetwork bool, service string) error ", "output": "{\n\tbytes, err := network.LoadServiceResource(service, useNetwork, cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm := map[interface{}]interface{}{}\n\tif err = yaml.Unmarshal(bytes, &m); err != nil {\n\t\treturn fmt.Errorf(\"Failed to parse YAML configuration for %s: %v\", service, err)\n\t}\n\n\tm = adjustContainerNames(m)\n\n\tbytes, err = yaml.Marshal(m)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to marshal YAML configuration for %s: %v\", service, err)\n\t}\n\n\tif err = p.Load(bytes); err != nil {\n\t\treturn fmt.Errorf(\"Failed to load %s: %v\", service, err)\n\t}\n\n\treturn nil\n}"} {"input": "package log\n\nimport (\n\t\"sync\"\n\n\t\"github.com/asim/go-micro/v3/util/ring\"\n\t\"github.com/google/uuid\"\n)\n\n\ntype osLog struct {\n\tformat FormatFunc\n\tonce sync.Once\n\n\tsync.RWMutex\n\tbuffer *ring.Buffer\n\tsubs map[string]*osStream\n}\n\ntype osStream struct {\n\tstream chan Record\n}\n\n\nfunc (o *osLog) Read(...ReadOption) ([]Record, error) {\n\tvar records []Record\n\n\tfor _, v := range o.buffer.Get(100) {\n\t\trecords = append(records, v.Value.(Record))\n\t}\n\n\treturn records, nil\n}\n\n\nfunc (o *osLog) Write(r Record) error {\n\to.buffer.Put(r)\n\treturn nil\n}\n\n\n\n\nfunc (o *osStream) Chan() <-chan Record {\n\treturn o.stream\n}\n\nfunc (o *osStream) Stop() error {\n\treturn nil\n}\n\nfunc NewLog(opts ...Option) Log {\n\toptions := Options{\n\t\tFormat: DefaultFormat,\n\t}\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\tl := &osLog{\n\t\tformat: options.Format,\n\t\tbuffer: ring.New(1024),\n\t\tsubs: make(map[string]*osStream),\n\t}\n\n\treturn l\n}\n\nfunc (o *osLog) Stream() (Stream, error) ", "output": "{\n\to.Lock()\n\tdefer o.Unlock()\n\n\tst := &osStream{\n\t\tstream: make(chan Record, 128),\n\t}\n\n\to.subs[uuid.New().String()] = st\n\n\treturn st, nil\n}"} {"input": "package action\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n)\n\ntype aclInfo struct {\n\t*config\n}\n\nfunc AclInfoAction() Action {\n\treturn &aclInfo{\n\t\tconfig: &gConfig,\n\t}\n}\n\nfunc (a *aclInfo) CommandFlags() *flag.FlagSet {\n\treturn a.newFlagSet(FLAG_OUTPUT, FLAG_CONSISTENCY, FLAG_BLOCKING)\n}\n\n\n\nfunc (a aclInfo) Run(args []string) error ", "output": "{\n\tif len(args) != 1 {\n\t\treturn fmt.Errorf(\"An ACL id must be specified\")\n\t}\n\tid := args[0]\n\n\tclient, err := a.newACL()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tqueryOpts := a.queryOptions()\n\tacl, _, err := client.Info(id, queryOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn a.Output(acl)\n}"} {"input": "package elastic\n\n\n\n\n\n\n\n\n\ntype MissingAggregation struct {\n\tfield string\n\tsubAggregations map[string]Aggregation\n\tmeta map[string]interface{}\n}\n\nfunc NewMissingAggregation() *MissingAggregation {\n\treturn &MissingAggregation{\n\t\tsubAggregations: make(map[string]Aggregation),\n\t}\n}\n\n\n\nfunc (a *MissingAggregation) SubAggregation(name string, subAggregation Aggregation) *MissingAggregation {\n\ta.subAggregations[name] = subAggregation\n\treturn a\n}\n\n\nfunc (a *MissingAggregation) Meta(metaData map[string]interface{}) *MissingAggregation {\n\ta.meta = metaData\n\treturn a\n}\n\nfunc (a *MissingAggregation) Source() (interface{}, error) {\n\n\tsource := make(map[string]interface{})\n\topts := make(map[string]interface{})\n\tsource[\"missing\"] = opts\n\n\tif a.field != \"\" {\n\t\topts[\"field\"] = a.field\n\t}\n\n\tif len(a.subAggregations) > 0 {\n\t\taggsMap := make(map[string]interface{})\n\t\tsource[\"aggregations\"] = aggsMap\n\t\tfor name, aggregate := range a.subAggregations {\n\t\t\tsrc, err := aggregate.Source()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\taggsMap[name] = src\n\t\t}\n\t}\n\n\tif len(a.meta) > 0 {\n\t\tsource[\"meta\"] = a.meta\n\t}\n\n\treturn source, nil\n}\n\nfunc (a *MissingAggregation) Field(field string) *MissingAggregation ", "output": "{\n\ta.field = field\n\treturn a\n}"} {"input": "package server\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/ehazlett/steamwire/types\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tbaseURL = \"http://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=%s&count=%d&maxlength=%d&format=json\"\n)\n\n\n\n\n\nfunc (s *Server) getNews(appID string) (*types.AppNews, error) {\n\tu := buildURL(appID, 1, 1024)\n\tresp, err := http.Get(u)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapp := &types.App{}\n\tif err := json.NewDecoder(resp.Body).Decode(&app); err != nil {\n\t\tlogrus.Errorf(\"error decoding: %s\", err)\n\t\treturn nil, err\n\t}\n\n\treturn app.AppNews, nil\n}\n\nfunc buildURL(appID string, count int, maxLength int) string ", "output": "{\n\treturn fmt.Sprintf(baseURL, appID, count, maxLength)\n}"} {"input": "package resourceapply\n\nimport (\n\t\"k8s.io/klog\"\n\n\tapiextv1beta1 \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1\"\n\tapiextclientv1beta1 \"k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1\"\n\tapierrors \"k8s.io/apimachinery/pkg/api/errors\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\n\t\"github.com/openshift/library-go/pkg/operator/events\"\n\t\"github.com/openshift/library-go/pkg/operator/resource/resourcemerge\"\n)\n\n\n\n\nfunc ApplyCustomResourceDefinition(client apiextclientv1beta1.CustomResourceDefinitionsGetter, recorder events.Recorder, required *apiextv1beta1.CustomResourceDefinition) (*apiextv1beta1.CustomResourceDefinition, bool, error) ", "output": "{\n\texisting, err := client.CustomResourceDefinitions().Get(required.Name, metav1.GetOptions{})\n\tif apierrors.IsNotFound(err) {\n\t\tactual, err := client.CustomResourceDefinitions().Create(required)\n\t\treportCreateEvent(recorder, required, err)\n\t\treturn actual, true, err\n\t}\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tmodified := resourcemerge.BoolPtr(false)\n\texistingCopy := existing.DeepCopy()\n\tresourcemerge.EnsureCustomResourceDefinition(modified, existingCopy, *required)\n\tif !*modified {\n\t\treturn existing, false, nil\n\t}\n\n\tif klog.V(4) {\n\t\tklog.Infof(\"CustomResourceDefinition %q changes: %s\", existing.Name, JSONPatch(existing, existingCopy))\n\t}\n\n\tactual, err := client.CustomResourceDefinitions().Update(existingCopy)\n\treportUpdateEvent(recorder, required, err)\n\n\treturn actual, true, err\n}"} {"input": "package util\n\nimport (\n\t\"sort\"\n\n\t\"github.com/prometheus/common/model\"\n\t\"github.com/weaveworks/cortex/pkg/prom1/storage/metric\"\n)\n\n\n\ntype SampleStreamIterator struct {\n\tss *model.SampleStream\n}\n\n\nfunc NewSampleStreamIterator(ss *model.SampleStream) SampleStreamIterator {\n\treturn SampleStreamIterator{ss: ss}\n}\n\n\nfunc (it SampleStreamIterator) Metric() metric.Metric {\n\treturn metric.Metric{Metric: it.ss.Metric}\n}\n\n\nfunc (it SampleStreamIterator) ValueAtOrBeforeTime(ts model.Time) model.SamplePair {\n\ti := sort.Search(len(it.ss.Values), func(n int) bool {\n\t\treturn it.ss.Values[n].Timestamp.After(ts)\n\t})\n\tif i == 0 {\n\t\treturn model.SamplePair{Timestamp: model.Earliest}\n\t}\n\treturn it.ss.Values[i-1]\n}\n\n\n\n\n\nfunc (it SampleStreamIterator) Close() {}\n\nfunc (it SampleStreamIterator) RangeValues(in metric.Interval) []model.SamplePair ", "output": "{\n\tn := len(it.ss.Values)\n\tstart := sort.Search(n, func(i int) bool {\n\t\treturn !it.ss.Values[i].Timestamp.Before(in.OldestInclusive)\n\t})\n\tend := sort.Search(n, func(i int) bool {\n\t\treturn it.ss.Values[i].Timestamp.After(in.NewestInclusive)\n\t})\n\n\tif start == n {\n\t\treturn nil\n\t}\n\n\treturn it.ss.Values[start:end]\n}"} {"input": "package avl\n\n\nfunc (tree *Tree) First() *Node {\n\treturn tree.root.first()\n}\n\n\n\n\n\nfunc (tree *Tree) Last() *Node {\n\treturn tree.root.last()\n}\n\n\nfunc (tree *Node) last() *Node {\n\tif nil == tree {\n\t\treturn nil\n\t}\n\tfor nil != tree.right {\n\t\ttree = tree.right\n\t}\n\treturn tree\n}\n\n\n\nfunc (tree *Node) Next() *Node {\n\tif nil == tree.right {\n\t\tkey := tree.key\n\t\tfor {\n\t\t\ttree = tree.up\n\t\t\tif nil == tree {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif 1 == tree.key.Compare(key) { \n\t\t\t\treturn tree\n\t\t\t}\n\t\t}\n\t}\n\treturn tree.right.first()\n}\n\n\n\nfunc (tree *Node) Prev() *Node {\n\tif nil == tree.left {\n\t\tkey := tree.key\n\t\tfor {\n\t\t\ttree = tree.up\n\t\t\tif nil == tree {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif -1 == tree.key.Compare(key) { \n\t\t\t\treturn tree\n\t\t\t}\n\t\t}\n\t}\n\treturn tree.left.last()\n}\n\nfunc (tree *Node) first() *Node ", "output": "{\n\tif nil == tree {\n\t\treturn nil\n\t}\n\tfor nil != tree.left {\n\t\ttree = tree.left\n\t}\n\treturn tree\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n)\n\n\n\n\nvar wait sync.WaitGroup\n\nfunc capitalize(word string) {\n\tdefer wait.Done()\n\tfmt.Println(strings.Title(word))\n}\n\nfunc upper(ch chan string) {\n\tfor {\n\t\tword := <-ch\n\n\t\tif word == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tfmt.Println(strings.ToUpper(word))\n\t}\n}\n\n\n\nfunc main() {\n\twords := []string{\"test1\", \"test2\", \"test3\"}\n\n\tfmt.Println(\"Use go routines to capitalize our words.\")\n\twait.Add(len(words))\n\n\tfor i := 0; i < len(words); i++ {\n\t\tgo capitalize(words[i])\n\t}\n\n\twait.Wait()\n\tfmt.Println()\n\n\n\n\tfmt.Println(\"Use channels to upper case our words.\")\n\n\tword_chan := make(chan string)\n\n\n\tgo upper(word_chan)\n\n\tadd(word_chan, words)\n\n\tclose(word_chan)\n}\n\nfunc add(ch chan string, words []string) ", "output": "{\n\tfor _, word := range words {\n\t\tch <- word\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"io\"\n\t\"log\"\n)\n\ntype proxy struct {\n\ttransport *http.Transport\n\taddr string\n}\n\nfunc newProxy(addr string) *proxy {\n\tp := &proxy{addr: addr}\n\tp.transport = &http.Transport{\n\t\tDial: p.dial,\n\t}\n\treturn p\n}\n\nfunc (p *proxy) dial(network string, addr string) (conn net.Conn, err error) {\n\treturn net.Dial(\"tcp\", p.addr)\n}\n\n\n\nfunc (p *proxy) proxyPass(w http.ResponseWriter, r *http.Request) ", "output": "{\n\thost, _, _ := net.SplitHostPort(r.RemoteAddr)\n\tr.Header.Add(\"X-Forwarded-For\", host)\n\tr.URL.Scheme = \"http\"\n\tr.URL.Host = r.Host\n\tresp, err := p.transport.RoundTrip(r)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tw.WriteHeader(http.StatusBadGateway)\n\t\tw.Write([]byte(\"

502 Bad Gateway

\"))\n\t\treturn\n\t}\n\theader := w.Header()\n\tfor k, v := range resp.Header {\n\t\tfor _, v1 := range v {\n\t\t\theader.Add(k, v1)\n\t\t}\n\t}\n\tw.WriteHeader(resp.StatusCode)\n\tio.Copy(w, resp.Body)\n\tresp.Body.Close()\n}"} {"input": "package code\n\nimport (\n\t\"github.com/telecoda/pico-go/console\"\n)\n\n\n\ntype cartridge struct {\n\t*console.BaseCartridge\n}\n\n\nfunc NewCart() console.Cartridge {\n\treturn &cartridge{\n\t\tBaseCartridge: console.NewBaseCart(),\n\t}\n}\n\n\n\n\n\nfunc (c *cartridge) Update() {\n}\n\n\nfunc (c *cartridge) Render() {\n\tc.Cls()\n\tc.PrintAtWithColor(\"INPUT:\", 50, 5, console.PICO8_WHITE)\n\tc.Line(0, 12, 128, 12)\n\n\tc.PrintAtWithColor(\"UP:\", 20, 30, console.PICO8_WHITE)\n\tif c.Btn(console.P1_BUTT_UP) {\n\t\tc.PrintAtWithColor(\"PRESSED\", 48, 30, console.PICO8_WHITE)\n\t}\n\n\tc.PrintAtWithColor(\"DOWN:\", 20, 50, console.PICO8_WHITE)\n\tif c.Btn(console.P1_BUTT_DOWN) {\n\t\tc.PrintAtWithColor(\"PRESSED\", 48, 50, console.PICO8_WHITE)\n\t}\n\n\tc.PrintAtWithColor(\"LEFT:\", 20, 70, console.PICO8_WHITE)\n\tif c.Btn(console.P1_BUTT_LEFT) {\n\t\tc.PrintAtWithColor(\"PRESSED\", 48, 70, console.PICO8_WHITE)\n\t}\n\n\tc.PrintAtWithColor(\"RIGHT:\", 20, 90, console.PICO8_WHITE)\n\tif c.Btn(console.P1_BUTT_RIGHT) {\n\t\tc.PrintAtWithColor(\"PRESSED\", 48, 90, console.PICO8_WHITE)\n\t}\n}\n\nfunc (c *cartridge) Init() ", "output": "{\n\tc.ClsWithColor(console.PICO8_BLUE)\n}"} {"input": "package install\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tutilruntime \"k8s.io/apimachinery/pkg/util/runtime\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\t\"k8s.io/kubernetes/pkg/apis/policy\"\n\t\"k8s.io/kubernetes/pkg/apis/policy/v1beta1\"\n)\n\nfunc init() {\n\tInstall(legacyscheme.Scheme)\n}\n\n\n\n\nfunc Install(scheme *runtime.Scheme) ", "output": "{\n\tutilruntime.Must(policy.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1beta1.SchemeGroupVersion))\n}"} {"input": "package context\n\nimport (\n\t\"github.com/gorilla/context\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype RequestParam struct {\n\tRequest *http.Request\n}\n\nfunc Params(req *http.Request) *RequestParam {\n\tif rp, ok := context.Get(req, params).(*RequestParam); ok {\n\t\treturn rp\n\t}\n\n\treturn nil\n}\n\nfunc InitParams(req *http.Request) error {\n\terr := req.ParseForm()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trp := RequestParam{req}\n\n\tcontext.Set(req, params, &rp)\n\n\treturn nil\n}\n\nfunc (rp *RequestParam) Get(param string) string {\n\tif strings.HasPrefix(param, \":\") {\n\t\treturn rp.Request.URL.Query().Get(param)\n\t}\n\n\treturn rp.Request.Form.Get(param)\n}\n\n\n\nfunc (rp *RequestParam) GetInt(param string) (int, error) ", "output": "{\n\treturn strconv.Atoi(rp.Get(param))\n}"} {"input": "package balancer\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestSanitizeIPTablesOutput(t *testing.T) ", "output": "{\n\trequire.Equal(t, \"x y\", sanitizeIPTablesOutput(([]byte)(\"x\\n\\ty\")))\n\n\tas := strings.Repeat(\"a\", 1000)\n\trequire.Equal(t, as[:200], sanitizeIPTablesOutput(([]byte)(as)))\n}"} {"input": "package stats\n\nimport (\n\t\"sync\"\n)\n\n\ntype CountSum struct {\n\tmu sync.Mutex\n\tsum int64\n\tcount uint32\n}\n\n\n\nfunc (s *CountSum) Add(size int64) (count uint32, sum int64) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\ts.count++\n\ts.sum += size\n\n\treturn s.count, s.sum\n}\n\n\n\n\n\nfunc (s *CountSum) Approximate() (count uint32, sum int64) ", "output": "{\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\treturn s.count, s.sum\n}"} {"input": "package circular\n\nimport (\n\t\"errors\"\n)\n\n\ntype Buffer struct {\n\tsize int \n\tn int \n\tdata []byte \n\twrite, read int \n}\n\n\n\n\n\nfunc (b *Buffer) ReadByte() (byte, error) {\n\tif b.n == 0 {\n\t\treturn 0, errors.New(\"no bytes read\")\n\t}\n\td := b.data[b.read]\n\tb.read = (b.read + 1) % b.size\n\tb.n--\n\treturn d, nil\n}\n\n\nfunc (b *Buffer) WriteByte(c byte) error {\n\tif b.write == b.read && b.n > 0 {\n\t\treturn errors.New(\"buffer is full\")\n\t}\n\tb.Overwrite(c)\n\treturn nil\n}\n\n\nfunc (b *Buffer) Overwrite(c byte) {\n\tif b.read == b.write && b.n > 0 {\n\t\tb.read = (b.read + 1) % b.size\n\t\tb.n--\n\t}\n\tb.data[b.write] = c\n\tb.write = (b.write + 1) % b.size\n\tb.n++\n}\n\n\nfunc (b *Buffer) Reset() {\n\t*b = Buffer{\n\t\tsize: b.size,\n\t\tdata: make([]byte, b.size),\n\t}\n}\n\nfunc NewBuffer(size int) *Buffer ", "output": "{\n\n\treturn &Buffer{\n\t\tsize: size,\n\t\tdata: make([]byte, size),\n\t}\n}"} {"input": "package parseutil\n\nimport (\n\t\"strings\"\n\n\t\"src.elv.sh/pkg/parse\"\n)\n\n\nfunc Wordify(src string) []string {\n\ttree, _ := parse.Parse(parse.Source{Code: src}, parse.Config{})\n\treturn wordifyInner(tree.Root, nil)\n}\n\n\n\nfunc isCompound(n parse.Node) bool {\n\t_, ok := n.(*parse.Compound)\n\treturn ok\n}\n\nfunc wordifyInner(n parse.Node, words []string) []string ", "output": "{\n\tif len(parse.Children(n)) == 0 || isCompound(n) {\n\t\ttext := parse.SourceText(n)\n\t\tif strings.TrimFunc(text, parse.IsWhitespace) != \"\" {\n\t\t\treturn append(words, text)\n\t\t}\n\t\treturn words\n\t}\n\tfor _, ch := range parse.Children(n) {\n\t\twords = wordifyInner(ch, words)\n\t}\n\treturn words\n}"} {"input": "package model\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/utils\"\n\n\t\"strings\"\n)\n\n\ntype ShowScalingPolicyResponse struct {\n\tScalingPolicy *ScalingV1PolicyDetail `json:\"scaling_policy,omitempty\"`\n\tHttpStatusCode int `json:\"-\"`\n}\n\n\n\nfunc (o ShowScalingPolicyResponse) String() string ", "output": "{\n\tdata, err := utils.Marshal(o)\n\tif err != nil {\n\t\treturn \"ShowScalingPolicyResponse struct{}\"\n\t}\n\n\treturn strings.Join([]string{\"ShowScalingPolicyResponse\", string(data)}, \" \")\n}"} {"input": "package client\n\nimport \"fmt\"\n\ntype FormationEntry struct {\n\tBalancer string `json:\"balancer\"`\n\tCount int `json:\"count\"`\n\tCPU int `json:\"cpu\"`\n\tHostname string `json:\"hostname\"`\n\tMemory int `json:\"memory\"`\n\tName string `json:\"name\"`\n\tPorts []int `json:\"ports\"`\n}\n\ntype Formation []FormationEntry\n\n\n\ntype FormationOptions struct {\n\tCount string\n\tCPU string\n\tMemory string\n}\n\nfunc (c *Client) ListFormation(app string) (Formation, error) {\n\tvar formation Formation\n\n\terr := c.Get(fmt.Sprintf(\"/apps/%s/formation\", app), &formation)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn formation, nil\n}\n\n\n\n\nfunc (c *Client) SetFormation(app, process string, opts FormationOptions) error ", "output": "{\n\tvar success interface{}\n\n\tparams := map[string]string{}\n\n\tif opts.Count != \"\" {\n\t\tparams[\"count\"] = opts.Count\n\t}\n\n\tif opts.CPU != \"\" {\n\t\tparams[\"cpu\"] = opts.CPU\n\t}\n\n\tif opts.Memory != \"\" {\n\t\tparams[\"memory\"] = opts.Memory\n\t}\n\n\terr := c.Post(fmt.Sprintf(\"/apps/%s/formation/%s\", app, process), params, &success)\n\treturn err\n}"} {"input": "package allowanypassword\n\nimport (\n\t\"strings\"\n\n\t\"github.com/golang/glog\"\n\n\tauthapi \"github.com/openshift/origin/pkg/auth/api\"\n\t\"github.com/openshift/origin/pkg/auth/authenticator\"\n\t\"k8s.io/apiserver/pkg/authentication/user\"\n)\n\n\ntype alwaysAcceptPasswordAuthenticator struct {\n\tproviderName string\n\tidentityMapper authapi.UserIdentityMapper\n}\n\n\nfunc New(providerName string, identityMapper authapi.UserIdentityMapper) authenticator.Password {\n\treturn &alwaysAcceptPasswordAuthenticator{providerName, identityMapper}\n}\n\n\n\n\nfunc (a alwaysAcceptPasswordAuthenticator) AuthenticatePassword(username, password string) (user.Info, bool, error) ", "output": "{\n\tusername = strings.TrimSpace(username)\n\n\tif username == \"\" || password == \"\" {\n\t\treturn nil, false, nil\n\t}\n\n\tidentity := authapi.NewDefaultUserIdentityInfo(a.providerName, username)\n\tuser, err := a.identityMapper.UserFor(identity)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error creating or updating mapping for: %#v due to %v\", identity, err)\n\t\treturn nil, false, err\n\t}\n\tglog.V(4).Infof(\"Got userIdentityMapping: %#v\", user)\n\n\treturn user, true, nil\n}"} {"input": "package machine\n\nimport (\n\t\"github.com/juju/cmd\"\n\n\tjujucmd \"github.com/juju/juju/cmd\"\n\t\"github.com/juju/juju/cmd/modelcmd\"\n)\n\nconst showMachineCommandDoc = `\nShow a specified machine on a model. Default format is in yaml,\nother formats can be specified with the \"--format\" option.\nAvailable formats are yaml, tabular, and json\n\nExamples:\n juju show-machine 0\n juju show-machine 1 2 3\n\n`\n\n\nfunc NewShowMachineCommand() cmd.Command {\n\treturn modelcmd.Wrap(newShowMachineCommand(nil))\n}\n\nfunc newShowMachineCommand(api statusAPI) *showMachineCommand {\n\tshowCmd := &showMachineCommand{}\n\tshowCmd.defaultFormat = \"yaml\"\n\tshowCmd.api = api\n\treturn showCmd\n}\n\n\ntype showMachineCommand struct {\n\tbaselistMachinesCommand\n}\n\n\nfunc (c *showMachineCommand) Info() *cmd.Info {\n\treturn jujucmd.Info(&cmd.Info{\n\t\tName: \"show-machine\",\n\t\tArgs: \" ...\",\n\t\tPurpose: \"Show a machine's status.\",\n\t\tDoc: showMachineCommandDoc,\n\t})\n}\n\n\n\n\nfunc (c *showMachineCommand) Init(args []string) error ", "output": "{\n\tc.machineIds = args\n\treturn nil\n}"} {"input": "package collection\n\nimport (\n\t\"github.com/kuzzleio/sdk-go/types\"\n)\n\n\n\n\nfunc (dc *Collection) Delete(index string, collection string, options types.QueryOptions) error ", "output": "{\n\tresult := make(chan *types.KuzzleResponse)\n\n\tquery := &types.KuzzleRequest{\n\t\tController: \"collection\",\n\t\tAction: \"delete\",\n\t\tIndex: index,\n\t\tCollection: collection,\n\t}\n\n\tgo dc.Kuzzle.Query(query, options, result)\n\n\tres := <-result\n\n\tif res.Error.Error() != \"\" {\n\t\treturn res.Error\n\t}\n\n\treturn nil\n}"} {"input": "package codegen\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"text/template\"\n)\n\nconst (\n\tcommentLinePrefix = \" \"\n)\n\nfunc applyTemplate(tmpl string, i interface{}) (string, error) {\n\tt := template.New(\"tmpl\").Funcs(template.FuncMap{\n\t\t\"wordWrap\": wordWrap,\n\t\t\"commentBlock\": commentBlock,\n\t\t\"hasPrefix\": strings.HasPrefix,\n\t})\n\n\tt2 := template.Must(t.Parse(tmpl))\n\n\tvar b bytes.Buffer\n\tif err := t2.Execute(&b, i); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn b.String(), nil\n}\n\n\n\nfunc wordWrap(in string, maxLineLength int) []string {\n\tinputLines := strings.Split(in, \"\\n\")\n\toutputLines := make([]string, 0)\n\n\tline := \"\"\n\tfor i, inputLine := range inputLines {\n\t\tif i > 0 {\n\t\t\toutputLines = append(outputLines, line)\n\t\t\tline = \"\"\n\t\t}\n\n\t\twords := strings.Split(inputLine, \" \")\n\n\t\tfor len(words) > 0 {\n\t\t\tword := words[0]\n\t\t\twords = words[1:]\n\n\t\t\tif len(line)+len(word) > maxLineLength {\n\t\t\t\toutputLines = append(outputLines, line)\n\t\t\t\tline = \"\"\n\t\t\t}\n\n\t\t\tif len(line) > 0 {\n\t\t\t\tline += \" \"\n\t\t\t}\n\t\t\tline += word\n\t\t}\n\t}\n\n\toutputLines = append(outputLines, line)\n\n\treturn outputLines\n}\n\nfunc commentBlock(in []string, indentTabs int) string ", "output": "{\n\tin = append([]string{}, in...)\n\n\tfor lineIndex := range in {\n\t\tprefix := \"\"\n\t\tfor tabIndex := 0; lineIndex > 0 && tabIndex < indentTabs; tabIndex++ {\n\t\t\tprefix += \"\\t\"\n\t\t}\n\t\tprefix += commentLinePrefix\n\t\tin[lineIndex] = prefix + in[lineIndex]\n\t}\n\n\treturn strings.Join(in, \"\\n\")\n}"} {"input": "package vsphere\n\nimport (\n\t\"fmt\"\n)\n\nconst BuilderId = \"packer.post-processor.vsphere\"\n\ntype Artifact struct {\n\tfiles []string\n\tdatastore string\n\tvmfolder string\n\tvmname string\n}\n\nfunc NewArtifact(datastore, vmfolder, vmname string, files []string) *Artifact {\n\treturn &Artifact{\n\t\tfiles: files,\n\t\tdatastore: datastore,\n\t\tvmfolder: vmfolder,\n\t\tvmname: vmname,\n\t}\n}\n\nfunc (*Artifact) BuilderId() string {\n\treturn BuilderId\n}\n\nfunc (a *Artifact) Files() []string {\n\treturn a.files\n}\n\nfunc (a *Artifact) Id() string {\n\treturn fmt.Sprintf(\"%s::%s::%s\", a.datastore, a.vmfolder, a.vmname)\n}\n\n\n\nfunc (*Artifact) State(name string) interface{} {\n\treturn nil\n}\n\nfunc (a *Artifact) Destroy() error {\n\treturn nil\n}\n\nfunc (a *Artifact) String() string ", "output": "{\n\treturn fmt.Sprintf(\"VM: %s Folder: %s Datastore: %s\", a.vmname, a.vmfolder, a.datastore)\n}"} {"input": "package privsep\n\n\n\n\n\nimport \"syscall\"\n\n\n\nfunc setgid(gid int) (err error) {\n\t_, _, e1 := syscall.RawSyscall(syscall.SYS_SETGID, uintptr(gid), 0, 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}\n\nfunc setuid(uid int) (err error) ", "output": "{\n\t_, _, e1 := syscall.RawSyscall(syscall.SYS_SETUID, uintptr(uid), 0, 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}"} {"input": "package common\n\n\n\n\nimport (\n\t\"strconv\"\n)\n\n\nfunc Atof32(s string) float64 {\n\tf, err := strconv.ParseFloat(s, 32)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn float64(f)\n}\n\n\nfunc Atoi(s string) int {\n\ti, err := strconv.Atoi(s)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn i\n}\n\n\nfunc Atob(str string) bool {\n\tb, err := strconv.ParseBool(str)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn b\n}\n\n\n\n\n\nfunc Atof64(str string) float64 {\n\ti, err := strconv.ParseFloat(str, 64)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn i\n}\n\nfunc Atoi64(str string) int64 ", "output": "{\n\ti, err := strconv.ParseInt(str, 10, 64)\n\tif err != nil {\n\t\tpanic(InputErr(err.Error()))\n\t}\n\treturn i\n}"} {"input": "package terminal\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"golang.org/x/crypto/ssh/terminal\"\n)\n\n\n\nfunc GetSize() (w, h int) {\n\tw, h, err := terminal.GetSize(int(os.Stdout.Fd()))\n\tif err != nil {\n\t\tw, h = 80, 25\n\t}\n\treturn w, h\n}\n\n\nfunc IsTerminal(fd int) bool {\n\treturn terminal.IsTerminal(fd)\n}\n\n\n\n\nfunc ReadPassword(fd int) ([]byte, error) {\n\treturn terminal.ReadPassword(fd)\n}\n\n\n\n\nfunc WriteTerminalTitle(title string) ", "output": "{\n\tfmt.Printf(ChangeTitle + title + BEL)\n}"} {"input": "package unibyte\n\nimport \"unicode\"\n\n\nfunc IsLower(b byte) bool {\n\treturn b >= 'a' && b <= 'z'\n}\n\n\nfunc IsUpper(b byte) bool {\n\treturn b >= 'A' && b <= 'Z'\n}\n\n\nfunc IsLetter(b byte) bool {\n\treturn IsLower(b) || IsUpper(b)\n}\n\n\nfunc IsSpaceQuote(b byte) bool {\n\treturn IsSpace(b) || b == '\"' || b == '\\''\n}\n\n\nfunc IsSpace(b byte) bool {\n\treturn unicode.IsSpace(rune(b))\n}\n\n\nfunc ToLower(b byte) byte {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn b\n}\n\n\nfunc ToUpper(b byte) byte {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn b\n}\n\n\nfunc ToLowerString(b byte) string {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn string(b)\n}\n\n\n\n\nfunc ToUpperString(b byte) string ", "output": "{\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn string(b)\n}"} {"input": "package packet_proxy\n\nimport (\n\t\"github.com/bettercap/bettercap/session\"\n)\n\ntype PacketProxy struct {\n\tsession.SessionModule\n}\n\nfunc NewPacketProxy(s *session.Session) *PacketProxy {\n\treturn &PacketProxy{\n\t\tSessionModule: session.NewSessionModule(\"packet.proxy\", s),\n\t}\n}\n\nfunc (mod PacketProxy) Name() string {\n\treturn \"packet.proxy\"\n}\n\nfunc (mod PacketProxy) Description() string {\n\treturn \"Not supported on this OS\"\n}\n\n\n\nfunc (mod *PacketProxy) Configure() (err error) {\n\treturn session.ErrNotSupported\n}\n\nfunc (mod *PacketProxy) Start() error {\n\treturn session.ErrNotSupported\n}\n\nfunc (mod *PacketProxy) Stop() error {\n\treturn session.ErrNotSupported\n}\n\nfunc (mod PacketProxy) Author() string ", "output": "{\n\treturn \"Simone Margaritelli \"\n}"} {"input": "package cmdlib\n\nimport (\n\t\"github.com/GoogleCloudPlatform/k8s-cluster-bundle/pkg/files\"\n\tlog \"k8s.io/klog\"\n)\n\n\ntype CmdIO struct {\n\tStdIO StdioReaderWriter\n\n\tFileIO files.FileReaderWriter\n\n\tExitIO Exiter\n}\n\n\ntype Exiter interface {\n\tExit(args ...interface{})\n\n\tExitf(format string, v ...interface{})\n}\n\n\ntype RealExiter struct{}\n\n\n\n\n\nfunc (e *RealExiter) Exitf(format string, v ...interface{}) {\n\tlog.Exitf(format, v...)\n}\n\nfunc (e *RealExiter) Exit(args ...interface{}) ", "output": "{\n\tlog.Exit(args...)\n}"} {"input": "package ov\nimport (\n \"fmt\"\n \"runtime\"\n \"github.com/docker/machine/log\"\n)\n\n\n\nfunc Ov1() (error) ", "output": "{\n runtime.Gosched()\n fmt.Println(\"in Ov1 another test foo\")\n log.Fatalf(\"the force is with you\")\n return nil\n}"} {"input": "package model\n\n\ntype Weight struct {\n\ttime int\n\trequirements map[*Reward]int\n}\n\n\nfunc (weight *Weight) Time() int {\n\treturn weight.time\n}\n\n\nfunc (weight *Weight) Requirements() map[*Reward]int {\n\treturn weight.requirements\n}\n\n\nfunc (weight *Weight) AddRequirement(reward *Reward, quantity int) {\n\tweight.requirements[reward] = quantity\n}\n\n\nfunc CreateWeight(time int) *Weight {\n\tweight := new(Weight)\n\tweight.time = time\n\tweight.requirements = make(map[*Reward]int)\n\treturn weight\n}\n\n\ntype ByTime []*Weight\n\n\n\n\n\nfunc (a ByTime) Swap(i, j int) {\n\ta[i], a[j] = a[j], a[i]\n}\n\n\nfunc (a ByTime) Less(i, j int) bool {\n\treturn a[i].Time() < a[j].Time()\n}\n\nfunc (a ByTime) Len() int ", "output": "{\n\treturn len(a)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"html/template\"\n\t\"net/http\"\n)\n\ntype Route struct {\n\tname string\n\tpath string\n\tfuncHandler gin.HandlerFunc\n}\n\ntype Link struct {\n\tpath string\n\tcaption string\n\thtml string\n}\n\ntype Page struct {\n\tCaption string\n\tBody string\n\tTmpl string\n}\n\nvar links = [...]Link{Link{caption: \"Home\", path: \"/\"},\n\tLink{caption: \"Sources\", path: \"/sources\"}}\n\nvar routes []Route\n\nvar webApp *gin.Engine\nvar indexTempl *template.Template\nvar sourceTempl *template.Template\nvar templates map[string]*template.Template\n\nfunc main() {\n\tconfigureServer()\n\tstartServer()\n}\n\nfunc startServer() {\n\twebApp.Run(\":3000\")\n}\n\nfunc initRoutes() {\n\troutes = make([]Route, 2)\n\trouteHome := Route{name: \"home\", path: \"/\", funcHandler: homeHandler}\n\trouteSoures := Route{name: \"source\", path: \"/sources\", funcHandler: sourcesHandler}\n\troutes[0] = routeHome\n\troutes[1] = routeSoures\n}\n\n\n\nfunc homeHandler(c *gin.Context) {\n\tc.HTML(http.StatusOK, \"home\", gin.H{})\n}\n\nfunc configureServer() ", "output": "{\n\ttemplates = nil\n\twebApp = gin.Default()\n\twebApp.LoadHTMLGlob(\"templates/*.tmpl\")\n\tinitRoutes()\n\tfor _, curRoute := range routes {\n\t\twebApp.GET(curRoute.path, curRoute.funcHandler)\n\t}\n}"} {"input": "package goji\n\nimport \"net/http\"\n\n\n\ntype router []route\n\ntype route struct {\n\tPattern\n\thttp.Handler\n}\n\nfunc (rt *router) add(p Pattern, h http.Handler) {\n\t*rt = append(*rt, route{p, h})\n}\n\n\n\nfunc (rt *router) route(r *http.Request) *http.Request ", "output": "{\n\tfor _, route := range *rt {\n\t\tif r2 := route.Match(r); r2 != nil {\n\t\t\treturn r2.WithContext(&match{\n\t\t\t\tContext: r2.Context(),\n\t\t\t\tp: route.Pattern,\n\t\t\t\th: route.Handler,\n\t\t\t})\n\t\t}\n\t}\n\treturn r.WithContext(&match{Context: r.Context()})\n}"} {"input": "package internal\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestRegisterBrokenAuthHeaderProvider(t *testing.T) {\n\tRegisterBrokenAuthHeaderProvider(\"https://aaa.com/\")\n\ttokenURL := \"https://aaa.com/token\"\n\tif providerAuthHeaderWorks(tokenURL) {\n\t\tt.Errorf(\"got %q as unbroken; want broken\", tokenURL)\n\t}\n}\n\n\n\nfunc Test_providerAuthHeaderWorks(t *testing.T) ", "output": "{\n\tfor _, p := range brokenAuthHeaderProviders {\n\t\tif providerAuthHeaderWorks(p) {\n\t\t\tt.Errorf(\"got %q as unbroken; want broken\", p)\n\t\t}\n\t\tp := fmt.Sprintf(\"%ssomesuffix\", p)\n\t\tif providerAuthHeaderWorks(p) {\n\t\t\tt.Errorf(\"got %q as unbroken; want broken\", p)\n\t\t}\n\t}\n\tp := \"https://api.not-in-the-list-example.com/\"\n\tif !providerAuthHeaderWorks(p) {\n\t\tt.Errorf(\"got %q as unbroken; want broken\", p)\n\t}\n}"} {"input": "package ui\n\nimport \"html/template\"\n\n\nconst (\n\tReactVersion = \"0.12.2\"\n\tJQueryVersion = \"2.1.3\"\n)\n\nvar contents map[string]*content\n\ntype content struct {\n\n\turi string\n\n\ttemplate string\n\n\tsources []string\n\n\ttpl *template.Template\n}\n\n\n\nfunc init() ", "output": "{\n\tcontents = map[string]*content{\n\n\t\t\"/\": &content{\n\t\t\ttemplate: \"index.tpl.html\",\n\t\t\tsources: []string{\n\t\t\t\t\"js/common.js\",\n\t\t\t\t\"js/hound.js\",\n\t\t\t},\n\t\t},\n\n\t\t\"/excluded_files.html\": &content{\n\t\t\ttemplate: \"excluded_files.tpl.html\",\n\t\t\tsources: []string{\n\t\t\t\t\"js/common.js\",\n\t\t\t\t\"js/excluded_files.js\",\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package middleware\n\nimport (\n\t\"github.com/labstack/echo\"\n)\n\ntype (\n\tTrailingSlashConfig struct {\n\t\tSkipper Skipper\n\n\t\tRedirectCode int `json:\"redirect_code\"`\n\t}\n)\n\nvar (\n\tDefaultTrailingSlashConfig = TrailingSlashConfig{\n\t\tSkipper: defaultSkipper,\n\t}\n)\n\n\n\n\n\nfunc AddTrailingSlash() echo.MiddlewareFunc {\n\treturn AddTrailingSlashWithConfig(TrailingSlashConfig{})\n}\n\n\n\n\n\n\n\n\n\nfunc RemoveTrailingSlash() echo.MiddlewareFunc {\n\treturn RemoveTrailingSlashWithConfig(TrailingSlashConfig{})\n}\n\n\n\nfunc RemoveTrailingSlashWithConfig(config TrailingSlashConfig) echo.MiddlewareFunc {\n\tif config.Skipper == nil {\n\t\tconfig.Skipper = DefaultTrailingSlashConfig.Skipper\n\t}\n\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\tif config.Skipper(c) {\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\treq := c.Request()\n\t\t\turl := req.URL()\n\t\t\tpath := url.Path()\n\t\t\tqs := url.QueryString()\n\t\t\tl := len(path) - 1\n\t\t\tif l >= 0 && path != \"/\" && path[l] == '/' {\n\t\t\t\tpath = path[:l]\n\t\t\t\turi := path\n\t\t\t\tif qs != \"\" {\n\t\t\t\t\turi += \"?\" + qs\n\t\t\t\t}\n\n\t\t\t\tif config.RedirectCode != 0 {\n\t\t\t\t\treturn c.Redirect(config.RedirectCode, uri)\n\t\t\t\t}\n\n\t\t\t\treq.SetURI(uri)\n\t\t\t\turl.SetPath(path)\n\t\t\t}\n\t\t\treturn next(c)\n\t\t}\n\t}\n}\n\nfunc AddTrailingSlashWithConfig(config TrailingSlashConfig) echo.MiddlewareFunc ", "output": "{\n\tif config.Skipper == nil {\n\t\tconfig.Skipper = DefaultTrailingSlashConfig.Skipper\n\t}\n\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\tif config.Skipper(c) {\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\treq := c.Request()\n\t\t\turl := req.URL()\n\t\t\tpath := url.Path()\n\t\t\tqs := url.QueryString()\n\t\t\tif path != \"/\" && path[len(path)-1] != '/' {\n\t\t\t\tpath += \"/\"\n\t\t\t\turi := path\n\t\t\t\tif qs != \"\" {\n\t\t\t\t\turi += \"?\" + qs\n\t\t\t\t}\n\n\t\t\t\tif config.RedirectCode != 0 {\n\t\t\t\t\treturn c.Redirect(config.RedirectCode, uri)\n\t\t\t\t}\n\n\t\t\t\treq.SetURI(uri)\n\t\t\t\turl.SetPath(path)\n\t\t\t}\n\t\t\treturn next(c)\n\t\t}\n\t}\n}"} {"input": "package input\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"path\"\n\t\"strconv\"\n\t\"unicode/utf8\"\n\n\t\"github.com/carlcui/expressive/locator\"\n)\n\n\ntype File struct {\n\tcurRow int\n\tcurColumn int\n\n\tcurRead int\n\n\tsrc []byte\n\tfilename string\n\tdirname string\n}\n\n\nfunc (file *File) Init(dirname, filename string) {\n\tfilePath := path.Join(dirname, filename)\n\n\tsrc, err := ioutil.ReadFile(filePath)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfile.curColumn = 0\n\tfile.curColumn = 0\n\n\tfile.curRead = 0\n\n\tfile.src = src\n\tfile.filename = filename\n\tfile.dirname = dirname\n}\n\n\n\n\n\nfunc (file *File) Peek() rune {\n\tif file.IsEOF() {\n\t\tpanic(\"EOF in \" + file.dirname + \"/\" + file.filename)\n\t}\n\n\tr, _ := utf8.DecodeRune(file.src[file.curRead:])\n\n\tif r == utf8.RuneError {\n\t\tfile.reportError(\"Unable to parse UTF-8 rune\")\n\t}\n\n\treturn r\n}\n\n\nfunc (file *File) IsEOF() bool {\n\treturn file.curRead >= len(file.src)\n}\n\nfunc (file *File) CurLoc() locator.Locator {\n\tvar loc locator.FileLocation\n\tloc.Col = file.curColumn\n\tloc.Row = file.curRow\n\tloc.FileName = file.filename\n\tloc.DirName = file.dirname\n\n\treturn &loc\n}\n\n\nfunc (file *File) reportError(message string) {\n\tlog.Fatal(message + \" at row \" + strconv.Itoa(file.curRow) + \", column \" + strconv.Itoa(file.curColumn))\n}\n\nfunc (file *File) NextRune() rune ", "output": "{\n\tif file.IsEOF() {\n\t\tpanic(\"EOF in \" + file.dirname + \"/\" + file.filename)\n\t}\n\n\tr, size := utf8.DecodeRune(file.src[file.curRead:])\n\n\tif r == utf8.RuneError {\n\t\tfile.reportError(\"Unable to parse UTF-8 rune\")\n\t}\n\n\tfile.curRead += size\n\n\tif r == '\\n' { \n\t\tfile.curRow++\n\t\tfile.curColumn = 0\n\t} else {\n\t\tfile.curColumn++\n\t}\n\n\treturn r\n}"} {"input": "package gobrightbox\n\n\n\ntype DatabaseServerType struct {\n\tID string\n\tName string\n\tDescription string\n\tDiskSize int `json:\"disk_size\"`\n\tRAM int\n}\n\n\nfunc (c *Client) DatabaseServerTypes() ([]DatabaseServerType, error) {\n\tvar databaseservertypes []DatabaseServerType\n\t_, err := c.MakeAPIRequest(\"GET\", \"/1.0/database_types\", nil, &databaseservertypes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn databaseservertypes, err\n}\n\n\n\n\nfunc (c *Client) DatabaseServerType(identifier string) (*DatabaseServerType, error) ", "output": "{\n\tdatabaseservertype := new(DatabaseServerType)\n\t_, err := c.MakeAPIRequest(\"GET\", \"/1.0/database_types/\"+identifier, nil, databaseservertype)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn databaseservertype, err\n}"} {"input": "package gologger\n\nimport (\n \"fmt\"\n)\n\ntype appender2Console struct {\n}\n\nfunc (self *appender2Console) init() error {\n return nil\n}\n\nfunc (self *appender2Console) close() {\n return\n}\n\nfunc (self *appender2Console) handle(msg *logMsg) error {\n fmt.Printf(\"%s\\n\", msg.info)\n return nil\n}\n\n\n\nfunc (self *appender2Console) setNext(n logHandler) ", "output": "{\n return\n}"} {"input": "package testbackend\n\nimport (\n\t\"context\"\n\n\t\"github.com/stripe/veneur/v14/ssf\"\n\t\"github.com/stripe/veneur/v14/trace\"\n)\n\n\n\ntype SendErrorSource func(*ssf.SSFSpan) error\n\n\n\ntype BackendOption func(*Backend)\n\n\n\nfunc SendErrors(src SendErrorSource) BackendOption {\n\treturn func(be *Backend) {\n\t\tbe.errorSrc = src\n\t}\n}\n\n\n\ntype Backend struct {\n\tch chan<- *ssf.SSFSpan\n\terrorSrc SendErrorSource\n}\n\n\nfunc (be *Backend) Close() error {\n\treturn nil\n}\n\n\nfunc (be *Backend) SendSync(ctx context.Context, span *ssf.SSFSpan) error {\n\tif be.errorSrc != nil {\n\t\tif err := be.errorSrc(span); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tselect {\n\tcase be.ch <- span:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}\n\n\n\n\n\nfunc NewBackend(ch chan<- *ssf.SSFSpan, opts ...BackendOption) trace.ClientBackend ", "output": "{\n\tbe := &Backend{ch: ch}\n\tfor _, opt := range opts {\n\t\topt(be)\n\t}\n\treturn be\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/polariseye/polarserver/common\"\n\t\"github.com/polariseye/polarserver/common/errorCode\"\n\t\"github.com/polariseye/polarserver/moduleManage\"\n)\n\ntype testStruct struct {\n\tclassName string\n}\n\nvar TestBLL *testStruct\n\nfunc init() {\n\tTestBLL = NewTestStruct()\n\tmoduleManage.RegisterModule(func() (moduleManage.IModule, moduleManage.ModuleType) {\n\t\treturn NewTestStruct(), moduleManage.NormalModule\n\t})\n}\n\n\nfunc (this *testStruct) Name() string {\n\treturn this.className\n}\n\nfunc (this *testStruct) InitModule() []error {\n\tfmt.Println(\"初始化\")\n\n\treturn nil\n}\n\nfunc (this *testStruct) CheckModule() []error {\n\tfmt.Println(\"check\")\n\n\treturn nil\n}\n\n\n\n\nfunc (this *testStruct) C_Hello(request *common.RequestModel, d int, name string) *common.ResultModel {\n\tresult := common.NewResultModel(errorCode.ClientDataError)\n\n\tresult.Value[\"Hello\"] = name + \"_\" + this.Name()\n\tresult.Value[\"Extra\"] = d\n\n\tresult.SetNormalError(errorCode.Success)\n\treturn result\n}\n\nfunc NewTestStruct() *testStruct {\n\treturn &testStruct{\n\t\tclassName: \"TestBLL\",\n\t}\n}\n\nfunc (this *testStruct) ConvertModule() []error ", "output": "{\n\tfmt.Println(\"数据转换\")\n\n\treturn nil\n}"} {"input": "package inputs\n\nimport (\n\t\"fmt\"\n)\n\n\ntype DiskIO struct {\n\tbaseInput\n}\n\n\nfunc (d *DiskIO) PluginName() string {\n\treturn \"diskio\"\n}\n\n\n\n\n\nfunc (d *DiskIO) TOML() string {\n\treturn fmt.Sprintf(`[[inputs.%s]]\n ## By default, telegraf will gather stats for all devices including\n ## disk partitions.\n ## Setting devices will restrict the stats to the specified devices.\n # devices = [\"sda\", \"sdb\", \"vd*\"]\n ## Uncomment the following line if you need disk serial numbers.\n # skip_serial_number = false\n #\n ## On systems which support it, device metadata can be added in the form of\n ## tags.\n ## Currently only Linux is supported via udev properties. You can view\n ## available properties for a device by running:\n ## 'udevadm info -q property -n /dev/sda'\n ## Note: Most, but not all, udev properties can be accessed this way. Properties\n ## that are currently inaccessible include DEVTYPE, DEVNAME, and DEVPATH.\n # device_tags = [\"ID_FS_TYPE\", \"ID_FS_USAGE\"]\n #\n ## Using the same metadata source as device_tags, you can also customize the\n ## name of the device via templates.\n ## The 'name_templates' parameter is a list of templates to try and apply to\n ## the device. The template may contain variables in the form of '$PROPERTY' or\n ## '${PROPERTY}'. The first template which does not contain any variables not\n ## present for the device is used as the device name tag.\n ## The typical use case is for LVM volumes, to get the VG/LV name instead of\n ## the near-meaningless DM-0 name.\n # name_templates = [\"$ID_FS_LABEL\",\"$DM_VG_NAME/$DM_LV_NAME\"]\n`, d.PluginName())\n}\n\nfunc (d *DiskIO) UnmarshalTOML(data interface{}) error ", "output": "{\n\treturn nil\n}"} {"input": "package handy\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\ntype TestHandler struct {\n\tDefaultHandler\n}\n\n\n\nfunc BenchmarkPathWithVariable(b *testing.B) {\n\tmux := NewHandy()\n\tmux.Handle(\"/foo/{name}\", func() Handler { return new(TestHandler) })\n\n\treq, err := http.NewRequest(\"GET\", \"/foo/bar\", nil)\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\n\tw := httptest.NewRecorder()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tmux.ServeHTTP(w, req)\n\t}\n}\n\nfunc BenchmarkPathWithVariables(b *testing.B) {\n\tmux := NewHandy()\n\tmux.Handle(\"/foo/{name}/{age}/{nono}\", func() Handler { return new(TestHandler) })\n\n\treq, err := http.NewRequest(\"GET\", \"/foo/bar/100/x\", nil)\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\n\tw := httptest.NewRecorder()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tmux.ServeHTTP(w, req)\n\t}\n}\n\nfunc BenchmarkSimpleRequest(b *testing.B) ", "output": "{\n\tmux := NewHandy()\n\tmux.Handle(\"/foo\", func() Handler { return new(TestHandler) })\n\n\treq, err := http.NewRequest(\"GET\", \"/foo\", nil)\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\n\tw := httptest.NewRecorder()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tmux.ServeHTTP(w, req)\n\t}\n}"} {"input": "package data\n\nimport (\n \"github.com/twitchyliquid64/CNC/registry/syscomponents\"\n)\n\nvar trackerObj DatabaseComponent\n\ntype DatabaseComponent struct{\n err error\n}\n\n\nfunc (d *DatabaseComponent)IconStr() string{\n return \"list\"\n}\nfunc (d *DatabaseComponent)IsNominal()bool{\n return d.err == nil\n}\nfunc (d *DatabaseComponent)IsDisabled()bool{\n return false\n}\nfunc (d *DatabaseComponent)IsFault()bool{\n return d.err != nil\n}\nfunc (d *DatabaseComponent)Error()string{\n if d.err == nil{\n return \"\"\n }\n return d.err.Error()\n}\nfunc (d *DatabaseComponent)SetError(e error){\n d.err = e\n}\n\nfunc trackingSetup(){\n trackerObj = DatabaseComponent{}\n syscomponents.Register(&trackerObj)\n}\n\nfunc tracking_notifyFault(err error){\n syscomponents.SetError(trackerObj.Name(), err)\n}\n\nfunc (d *DatabaseComponent)Name() string", "output": "{\n return \"Database\"\n}"} {"input": "package ecr\n\nimport (\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/client\"\n\t\"github.com/aws/aws-sdk-go/aws/client/metadata\"\n\t\"github.com/aws/aws-sdk-go/aws/request\"\n\t\"github.com/aws/aws-sdk-go/aws/signer/v4\"\n\t\"github.com/aws/aws-sdk-go/private/protocol/jsonrpc\"\n)\n\n\n\n\n\n\n\n\n\n\ntype ECR struct {\n\t*client.Client\n}\n\n\nvar initClient func(*client.Client)\n\n\nvar initRequest func(*request.Request)\n\n\nconst (\n\tServiceName = \"ecr\" \n\tEndpointsID = ServiceName \n)\n\n\n\n\n\n\n\n\n\n\n\nfunc New(p client.ConfigProvider, cfgs ...*aws.Config) *ECR {\n\tc := p.ClientConfig(EndpointsID, cfgs...)\n\treturn newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName)\n}\n\n\n\n\n\n\nfunc (c *ECR) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\tif initRequest != nil {\n\t\tinitRequest(req)\n\t}\n\n\treturn req\n}\n\nfunc newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *ECR ", "output": "{\n\tsvc := &ECR{\n\t\tClient: client.New(\n\t\t\tcfg,\n\t\t\tmetadata.ClientInfo{\n\t\t\t\tServiceName: ServiceName,\n\t\t\t\tSigningName: signingName,\n\t\t\t\tSigningRegion: signingRegion,\n\t\t\t\tEndpoint: endpoint,\n\t\t\t\tAPIVersion: \"2015-09-21\",\n\t\t\t\tJSONVersion: \"1.1\",\n\t\t\t\tTargetPrefix: \"AmazonEC2ContainerRegistry_V20150921\",\n\t\t\t},\n\t\t\thandlers,\n\t\t),\n\t}\n\n\tsvc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)\n\tsvc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)\n\tsvc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)\n\tsvc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)\n\tsvc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)\n\n\tif initClient != nil {\n\t\tinitClient(svc.Client)\n\t}\n\n\treturn svc\n}"} {"input": "package events\n\nimport \"encoding/json\"\n\n\ntype User struct {\n\tUser string `json:\"user\"`\n\tName string `json:\"name\"`\n}\n\n\ntype Nick struct {\n\tNick string `json:\"nick\"`\n}\n\n\ntype Quit struct {\n\tType string `json:\"type\"`\n\tStatus string `json:\"status\"`\n\tUser string `json:\"user\"`\n\tMsg string `json:\"msg\"`\n}\n\n\n\n\n\nfunc RcvedQuit(user, msg string) string {\n\tevent, err := json.Marshal(Quit{Type: \"quit\",\n\t\tStatus: \"ok\",\n\t\tUser: user,\n\t\tMsg: msg,\n\t})\n\n\tif err != nil {\n\t\treturn InternalError(err.Error())\n\t}\n\n\treturn string(event)\n}\n\nfunc Connected(server, msg string) string ", "output": "{\n\tevent, err := json.Marshal(StatusTargetMsgEvent{Type: \"connected\",\n\t\tStatus: \"ok\",\n\t\tTarget: server,\n\t\tMsg: msg,\n\t})\n\n\tif err != nil {\n\t\treturn InternalError(err.Error())\n\t}\n\n\treturn string(event)\n}"} {"input": "package plugin\n\nimport (\n\t\"github.com/mitchellh/packer/packer\"\n\t\"log\"\n)\n\ntype cmdHook struct {\n\thook packer.Hook\n\tclient *Client\n}\n\n\n\nfunc (c *cmdHook) checkExit(p interface{}, cb func()) {\n\tif c.client.Exited() {\n\t\tcb()\n\t} else if p != nil {\n\t\tlog.Panic(p)\n\t}\n}\n\nfunc (c *cmdHook) Run(name string, ui packer.Ui, comm packer.Communicator, data interface{}) error ", "output": "{\n\tdefer func() {\n\t\tr := recover()\n\t\tc.checkExit(r, nil)\n\t}()\n\n\treturn c.hook.Run(name, ui, comm, data)\n}"} {"input": "package configmap\n\nimport (\n\t\"sync\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n)\n\n\ntype ManualWatcher struct {\n\tNamespace string\n\n\tsync.RWMutex\n\tobservers map[string][]Observer\n}\n\nvar _ Watcher = (*ManualWatcher)(nil)\n\n\nfunc (w *ManualWatcher) Watch(name string, o ...Observer) {\n\tw.Lock()\n\tdefer w.Unlock()\n\n\tif w.observers == nil {\n\t\tw.observers = make(map[string][]Observer, 1)\n\t}\n\tw.observers[name] = append(w.observers[name], o...)\n}\n\n\n\n\n\nfunc (w *ManualWatcher) Start(<-chan struct{}) error {\n\treturn nil\n}\n\n\nfunc (w *ManualWatcher) OnChange(configMap *corev1.ConfigMap) {\n\tif configMap.Namespace != w.Namespace {\n\t\treturn\n\t}\n\tw.RLock()\n\tdefer w.RUnlock()\n\tfor _, o := range w.observers[configMap.Name] {\n\t\to(configMap)\n\t}\n}\n\nfunc (w *ManualWatcher) ForEach(f func(string, []Observer) error) error ", "output": "{\n\tfor k, v := range w.observers {\n\t\tif err := f(k, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package zk\n\nimport \"github.com/go-kit/kit/log\"\n\n\ntype Registrar struct {\n\tclient Client\n\tservice Service\n\tlogger log.Logger\n}\n\n\n\ntype Service struct {\n\tPath string \n\tName string \n\tData []byte \n\tnode string \n}\n\n\n\n\n\n\nfunc (r *Registrar) Register() {\n\tif err := r.client.Register(&r.service); err != nil {\n\t\tr.logger.Log(\"err\", err)\n\t} else {\n\t\tr.logger.Log(\"action\", \"register\")\n\t}\n}\n\n\nfunc (r *Registrar) Deregister() {\n\tif err := r.client.Deregister(&r.service); err != nil {\n\t\tr.logger.Log(\"err\", err)\n\t} else {\n\t\tr.logger.Log(\"action\", \"deregister\")\n\t}\n}\n\nfunc NewRegistrar(client Client, service Service, logger log.Logger) *Registrar ", "output": "{\n\treturn &Registrar{\n\t\tclient: client,\n\t\tservice: service,\n\t\tlogger: log.NewContext(logger).With(\n\t\t\t\"service\", service.Name,\n\t\t\t\"path\", service.Path,\n\t\t\t\"data\", string(service.Data),\n\t\t),\n\t}\n}"} {"input": "package reversereader\n\nimport (\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\ntype ReverseReader struct {\n\treader *os.File\n\toffset int64\n\treadSize int64\n}\n\n\n\n\nfunc NewReverseReader(reader *os.File) (*ReverseReader, error) {\n\tpageSize := int64(os.Getpagesize())\n\tstat, err := reader.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tremainder := stat.Size() % pageSize\n\tend, err := reader.Seek(0, 2)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstartOffset := end - remainder\n\tif startOffset < 0 {\n\t\tstartOffset = 0\n\t}\n\trr := ReverseReader{\n\t\treader: reader,\n\t\toffset: startOffset,\n\t\treadSize: pageSize,\n\t}\n\treturn &rr, nil\n}\n\n\n\n\n\nfunc (r *ReverseReader) Read() (string, error) ", "output": "{\n\tif r.offset < 0 {\n\t\treturn \"\", errors.Wrap(io.EOF, \"at beginning of file\")\n\t}\n\tb := make([]byte, r.readSize)\n\tn, err := r.reader.ReadAt(b, r.offset)\n\tif err != nil && errors.Cause(err) != io.EOF {\n\t\treturn \"\", err\n\t}\n\tif int64(n) < r.readSize {\n\t\tb = b[0:n]\n\t}\n\tr.offset = -r.readSize\n\treturn string(b), nil\n}"} {"input": "package logger\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/yosssi/galaxy/core\"\n)\n\n\nfunc Logger() core.Handler {\n\treturn func(ctx *core.Context) error {\n\t\tctx.App.Logger.Printf(\n\t\t\t\"[Logger] Started %s %s for %s\",\n\t\t\tctx.Req.Method,\n\t\t\tctx.Req.URL.Path,\n\t\t\textractAddr(ctx.Req),\n\t\t)\n\n\t\terr := ctx.Next()\n\n\t\tif err != nil {\n\t\t\tctx.App.Logger.Printf(\n\t\t\t\t\"[Logger] Error (%+v) in %v\\n\",\n\t\t\t\terr,\n\t\t\t\ttime.Since(ctx.StartTime()),\n\t\t\t)\n\n\t\t\treturn err\n\t\t}\n\n\t\tctx.App.Logger.Printf(\n\t\t\t\"[Logger] Completed %d %s in %v\\n\",\n\t\t\tctx.Res.Status(),\n\t\t\thttp.StatusText(ctx.Res.Status()),\n\t\t\ttime.Since(ctx.StartTime()),\n\t\t)\n\n\t\treturn nil\n\t}\n}\n\n\n\n\nfunc extractAddr(req *http.Request) string ", "output": "{\n\taddr := req.Header.Get(\"X-Real-IP\")\n\n\tif addr == \"\" {\n\t\taddr = req.Header.Get(\"X-Forwarded-For\")\n\t\tif addr == \"\" {\n\t\t\taddr = req.RemoteAddr\n\t\t}\n\t}\n\n\treturn addr\n}"} {"input": "package vcl\n\n\n\n\nimport (\n\t. \"github.com/ying32/govcl/vcl/api\"\n\t. \"github.com/ying32/govcl/vcl/types\"\n)\n\ntype (\n\tNSObject uintptr\n\n\tNSWindow uintptr\n\n\tNSURL uintptr\n)\n\n\nfunc HandleToPlatformHandle(h HWND) NSObject {\n\treturn NSObject(h)\n}\n\nfunc (f *TForm) PlatformWindow() NSWindow {\n\tr, _, _ := NSWindow_FromForm.Call(f.instance)\n\treturn NSWindow(r)\n}\n\nfunc (n NSWindow) TitleVisibility() NSWindowTitleVisibility {\n\tr, _, _ := NSWindow_titleVisibility.Call(uintptr(n))\n\treturn NSWindowTitleVisibility(r)\n}\n\nfunc (n NSWindow) SetTitleVisibility(flag NSWindowTitleVisibility) {\n\tNSWindow_setTitleVisibility.Call(uintptr(n), uintptr(flag))\n}\n\nfunc (n NSWindow) TitleBarAppearsTransparent() bool {\n\tr, _, _ := NSWindow_titlebarAppearsTransparent.Call(uintptr(n))\n\treturn DBoolToGoBool(r)\n}\n\nfunc (n NSWindow) SetTitleBarAppearsTransparent(flag bool) {\n\tNSWindow_setTitlebarAppearsTransparent.Call(uintptr(n), GoBoolToDBool(flag))\n}\n\nfunc (n NSWindow) SetRepresentedURL(url NSURL) {\n\tNSWindow_setRepresentedURL.Call(uintptr(n), uintptr(url))\n}\n\nfunc (n NSWindow) StyleMask() uint {\n\tr, _, _ := NSWindow_styleMask.Call(uintptr(n))\n\treturn uint(r)\n}\n\n\n\nfunc (n NSWindow) SetStyleMask(mask uint) ", "output": "{\n\tNSWindow_setStyleMask.Call(uintptr(n), uintptr(mask))\n}"} {"input": "package websocket\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/b00lduck/raspberry_soundboard/persistence\"\n)\n\ntype Hub struct {\n\tclients map[*Client]bool\n\tbroadcast chan bool\n\tregister chan *Client\n\tunregister chan *Client\n\tpersistence *persistence.Persistence\n}\n\n\n\nfunc (h *Hub) Broadcast() {\n\th.broadcast <- true\n}\n\nfunc (h *Hub) Run() {\n\tfor {\n\t\tselect {\n\t\tcase client := <-h.register:\n\t\t\tlog.Info(\"register client\")\n\t\t\th.clients[client] = true\n\t\t\tclient.send <- h.persistence.JsonState()\n\t\tcase client := <-h.unregister:\n\t\t\tif _, ok := h.clients[client]; ok {\n\t\t\t\tlog.Info(\"unregister client\")\n\t\t\t\tdelete(h.clients, client)\n\t\t\t\tclose(client.send)\n\t\t\t}\n\t\tcase <-h.broadcast:\n\t\t\tfor client := range h.clients {\n\t\t\t\tselect {\n\t\t\t\tcase client.send <- h.persistence.JsonState():\n\t\t\t\tdefault:\n\t\t\t\t\tclose(client.send)\n\t\t\t\t\tdelete(h.clients, client)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc NewHub(persistence *persistence.Persistence) *Hub ", "output": "{\n\treturn &Hub{\n\t\tbroadcast: make(chan bool),\n\t\tregister: make(chan *Client),\n\t\tunregister: make(chan *Client),\n\t\tclients: make(map[*Client]bool),\n\t\tpersistence: persistence,\n\t}\n}"} {"input": "package processors\n\nimport (\n\t\"context\"\n\n\t\"github.com/cloudevents/sdk-go/v2/event\"\n)\n\n\n\n\n\ntype Interface interface {\n\tProcess(ctx context.Context, e *event.Event) error\n\tNext() Interface\n}\n\n\ntype ChainableProcessor interface {\n\tInterface\n\n\tWithNext(ChainableProcessor) ChainableProcessor\n}\n\n\n\n\ntype BaseProcessor struct {\n\tn ChainableProcessor\n}\n\n\n\n\nfunc (p *BaseProcessor) Next() Interface {\n\tif p.n == nil {\n\t\treturn noop\n\t}\n\treturn p.n\n}\n\n\n\n\n\nfunc ChainProcessors(first ChainableProcessor, rest ...ChainableProcessor) Interface {\n\tnext := first\n\tfor _, p := range rest {\n\t\tnext = next.WithNext(p)\n\t}\n\treturn first\n}\n\nvar noop = &noOpProcessor{}\n\ntype noOpProcessor struct{}\n\nfunc (p noOpProcessor) Process(_ context.Context, _ *event.Event) error {\n\treturn nil\n}\n\n\n\nfunc (p noOpProcessor) Next() Interface {\n\treturn nil\n}\n\nfunc (p *BaseProcessor) WithNext(n ChainableProcessor) ChainableProcessor ", "output": "{\n\tp.n = n\n\treturn p.n\n}"} {"input": "package compression\n\nimport (\n\tc \"gopkg.in/h2non/gentleman.v2/context\"\n\tp \"gopkg.in/h2non/gentleman.v2/plugin\"\n\t\"net/http\"\n)\n\n\n\n\nfunc Disable() p.Plugin ", "output": "{\n\treturn p.NewRequestPlugin(func(ctx *c.Context, h c.Handler) {\n\t\ttransport, ok := ctx.Client.Transport.(*http.Transport)\n\t\tif !ok {\n\t\t\th.Next(ctx)\n\t\t\treturn\n\t\t}\n\n\t\ttransport.DisableCompression = true\n\t\tctx.Client.Transport = transport\n\n\t\th.Next(ctx)\n\t})\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSAmazonMQBroker_MaintenanceWindow struct {\n\n\tDayOfWeek string `json:\"DayOfWeek,omitempty\"`\n\n\tTimeOfDay string `json:\"TimeOfDay,omitempty\"`\n\n\tTimeZone string `json:\"TimeZone,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) AWSCloudFormationType() string {\n\treturn \"AWS::AmazonMQ::Broker.MaintenanceWindow\"\n}\n\n\n\n\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) DependsOn() []string ", "output": "{\n\treturn r._dependsOn\n}"} {"input": "package organization\n\nimport (\n\t\"cf/api\"\n\t\"cf/configuration\"\n\t\"cf/models\"\n\t\"cf/requirements\"\n\t\"cf/terminal\"\n\t\"github.com/codegangsta/cli\"\n)\n\ntype ListOrgs struct {\n\tui terminal.UI\n\tconfig configuration.Reader\n\torgRepo api.OrganizationRepository\n}\n\nfunc NewListOrgs(ui terminal.UI, config configuration.Reader, orgRepo api.OrganizationRepository) (cmd ListOrgs) {\n\tcmd.ui = ui\n\tcmd.config = config\n\tcmd.orgRepo = orgRepo\n\treturn\n}\n\nfunc (cmd ListOrgs) GetRequirements(reqFactory requirements.Factory, c *cli.Context) (reqs []requirements.Requirement, err error) {\n\treqs = []requirements.Requirement{\n\t\treqFactory.NewLoginRequirement(),\n\t}\n\treturn\n}\n\n\n\nfunc (cmd ListOrgs) Run(c *cli.Context) ", "output": "{\n\tcmd.ui.Say(\"Getting orgs as %s...\\n\", terminal.EntityNameColor(cmd.config.Username()))\n\n\tnoOrgs := true\n\ttable := cmd.ui.Table([]string{\"name\"})\n\n\tapiStatus := cmd.orgRepo.ListOrgs(func(org models.Organization) bool {\n\t\ttable.Print([][]string{{org.Name}})\n\t\tnoOrgs = false\n\t\treturn true\n\t})\n\n\tif apiStatus.IsNotSuccessful() {\n\t\tcmd.ui.Failed(\"Failed fetching orgs.\\n%s\", apiStatus.Message)\n\t\treturn\n\t}\n\n\tif noOrgs {\n\t\tcmd.ui.Say(\"No orgs found\")\n\t}\n}"} {"input": "package sol\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aodin/sol/dialect\"\n)\n\n\ntype DropStmt struct {\n\ttable *TableElem\n\tifExists bool\n}\n\n\n\n\n\n\nfunc (stmt DropStmt) String() string {\n\tc, _ := stmt.Compile(&defaultDialect{}, Params())\n\treturn c\n}\n\n\n\nfunc (stmt DropStmt) Compile(d dialect.Dialect, p *Parameters) (string, error) {\n\tif stmt.ifExists {\n\t\treturn fmt.Sprintf(`DROP TABLE IF EXISTS %s`, stmt.table.Name()), nil\n\t}\n\treturn fmt.Sprintf(`DROP TABLE %s`, stmt.table.Name()), nil\n}\n\nfunc (stmt DropStmt) IfExists() DropStmt ", "output": "{\n\tstmt.ifExists = true\n\treturn stmt\n}"} {"input": "package implementation\n\nimport (\n\t\"crypto/tls\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/go-openapi/swag\"\n\t\"github.com/go-swagger/go-swagger/examples/auto-configure/restapi/operations\"\n)\n\ntype ConfigureImpl struct {\n\tflags Flags\n}\n\ntype Flags struct {\n\tExample1 string `long:\"example1\" description:\"Sample for showing how to configure cmd-line flags\"`\n\tExample2 string `long:\"example2\" description:\"Further info at https://github.com/jessevdk/go-flags\"`\n}\n\nfunc (i *ConfigureImpl) ConfigureFlags(api *operations.AToDoListApplicationAPI) {\n\tapi.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{\n\t\t{\n\t\t\tShortDescription: \"Example Flags\",\n\t\t\tLongDescription: \"\",\n\t\t\tOptions: &i.flags,\n\t\t},\n\t}\n}\n\nfunc (i *ConfigureImpl) ConfigureTLS(tlsConfig *tls.Config) {\n}\n\nfunc (i *ConfigureImpl) ConfigureServer(s *http.Server, scheme, addr string) {\n\tif i.flags.Example1 != \"something\" {\n\t\tlog.Println(\"example1 argument is not something\")\n\t}\n}\n\nfunc (i *ConfigureImpl) SetupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}\n\nfunc (i *ConfigureImpl) SetupGlobalMiddleware(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tlog.Printf(\"Recieved request on path: %v\", req.URL.String())\n\t\thandler.ServeHTTP(w, req)\n\t})\n}\n\n\n\nfunc (i *ConfigureImpl) CustomConfigure(api *operations.AToDoListApplicationAPI) ", "output": "{\n\tapi.Logger = log.Printf\n\tapi.ServerShutdown = func() {\n\t\tlog.Printf(\"Running ServerShutdown function\")\n\t}\n}"} {"input": "package types\n\nimport (\n\t\"github.com/coreos/ignition/v2/config/shared/errors\"\n\n\t\"github.com/coreos/vcontext/path\"\n\t\"github.com/coreos/vcontext/report\"\n)\n\n\n\nfunc (r Raid) IgnoreDuplicates() map[string]struct{} {\n\treturn map[string]struct{}{\n\t\t\"Options\": {},\n\t}\n}\n\nfunc (ra Raid) Validate(c path.ContextPath) (r report.Report) {\n\tr.AddOnError(c.Append(\"level\"), ra.validateLevel())\n\tif len(ra.Devices) == 0 {\n\t\tr.AddOnError(c.Append(\"devices\"), errors.ErrRaidDevicesRequired)\n\t}\n\treturn\n}\n\nfunc (r Raid) validateLevel() error {\n\tswitch r.Level {\n\tcase \"linear\", \"raid0\", \"0\", \"stripe\":\n\t\tif r.Spares != nil && *r.Spares != 0 {\n\t\t\treturn errors.ErrSparesUnsupportedForLevel\n\t\t}\n\tcase \"raid1\", \"1\", \"mirror\":\n\tcase \"raid4\", \"4\":\n\tcase \"raid5\", \"5\":\n\tcase \"raid6\", \"6\":\n\tcase \"raid10\", \"10\":\n\tdefault:\n\t\treturn errors.ErrUnrecognizedRaidLevel\n\t}\n\n\treturn nil\n}\n\nfunc (r Raid) Key() string ", "output": "{\n\treturn r.Name\n}"} {"input": "package atomic\n\nimport (\n\t\"encoding/json\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\n\ntype Uint32 struct {\n\t_ nocmp \n\n\tv uint32\n}\n\n\nfunc NewUint32(val uint32) *Uint32 {\n\treturn &Uint32{v: val}\n}\n\n\nfunc (i *Uint32) Load() uint32 {\n\treturn atomic.LoadUint32(&i.v)\n}\n\n\nfunc (i *Uint32) Add(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, delta)\n}\n\n\nfunc (i *Uint32) Sub(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, ^(delta - 1))\n}\n\n\nfunc (i *Uint32) Inc() uint32 {\n\treturn i.Add(1)\n}\n\n\nfunc (i *Uint32) Dec() uint32 {\n\treturn i.Sub(1)\n}\n\n\n\n\n\nfunc (i *Uint32) Store(val uint32) {\n\tatomic.StoreUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) Swap(val uint32) (old uint32) {\n\treturn atomic.SwapUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(i.Load())\n}\n\n\nfunc (i *Uint32) UnmarshalJSON(b []byte) error {\n\tvar v uint32\n\tif err := json.Unmarshal(b, &v); err != nil {\n\t\treturn err\n\t}\n\ti.Store(v)\n\treturn nil\n}\n\n\nfunc (i *Uint32) String() string {\n\tv := i.Load()\n\treturn strconv.FormatUint(uint64(v), 10)\n}\n\nfunc (i *Uint32) CAS(old, new uint32) (swapped bool) ", "output": "{\n\treturn atomic.CompareAndSwapUint32(&i.v, old, new)\n}"} {"input": "package dataintegration\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateExternalPublicationRequest struct {\n\n\tWorkspaceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"workspaceId\"`\n\n\tTaskKey *string `mandatory:\"true\" contributesTo:\"path\" name:\"taskKey\"`\n\n\tCreateExternalPublicationDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateExternalPublicationRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request CreateExternalPublicationRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CreateExternalPublicationRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateExternalPublicationResponse struct {\n\n\tRawResponse *http.Response\n\n\tExternalPublication `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateExternalPublicationResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateExternalPublicationResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateExternalPublicationRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package executedconditionals\n\nfunc a(condition bool) string {\n\tif condition {\n\t\treturn \"A\"\n\t}\n\treturn \"A\"\n}\n\nfunc b() string {\n\treturn \"B\"\n}\n\nfunc c() string {\n\treturn \"C\"\n}\n\n\n\nfunc wrapper(condition bool) ", "output": "{\n\ta(condition)\n\tb()\n\tc()\n}"} {"input": "package context\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\n\tjujuos \"github.com/juju/utils/os\"\n)\n\n\n\n\n\nfunc appendPath(paths Paths) []string {\n\treturn []string{\n\t\t\"PATH=\" + paths.GetToolsDir() + \":\" + os.Getenv(\"PATH\"),\n\t}\n}\n\nfunc ubuntuEnv(paths Paths) []string {\n\tpath := appendPath(paths)\n\tenv := []string{\n\t\t\"APT_LISTCHANGES_FRONTEND=none\",\n\t\t\"DEBIAN_FRONTEND=noninteractive\",\n\t}\n\tenv = append(env, path...)\n\treturn env\n}\n\nfunc centosEnv(paths Paths) []string {\n\treturn appendPath(paths)\n}\n\n\n\n\n\nfunc windowsEnv(paths Paths) []string {\n\tcharmDir := paths.GetCharmDir()\n\tcharmModules := filepath.Join(charmDir, \"lib\", \"Modules\")\n\treturn []string{\n\t\t\"Path=\" + paths.GetToolsDir() + \";\" + os.Getenv(\"Path\"),\n\t\t\"PSModulePath=\" + os.Getenv(\"PSModulePath\") + \";\" + charmModules,\n\t}\n}\n\nfunc OSDependentEnvVars(paths Paths) []string ", "output": "{\n\tswitch jujuos.HostOS() {\n\tcase jujuos.Windows:\n\t\treturn windowsEnv(paths)\n\tcase jujuos.Ubuntu:\n\t\treturn ubuntuEnv(paths)\n\tcase jujuos.CentOS:\n\t\treturn centosEnv(paths)\n\t}\n\treturn nil\n}"} {"input": "package builtins\n\nimport (\n\t\"sigs.k8s.io/kustomize/api/filters/annotations\"\n\t\"sigs.k8s.io/kustomize/api/resmap\"\n\t\"sigs.k8s.io/kustomize/api/types\"\n\t\"sigs.k8s.io/yaml\"\n)\n\n\ntype AnnotationsTransformerPlugin struct {\n\tAnnotations map[string]string `json:\"annotations,omitempty\" yaml:\"annotations,omitempty\"`\n\tFieldSpecs []types.FieldSpec `json:\"fieldSpecs,omitempty\" yaml:\"fieldSpecs,omitempty\"`\n}\n\nfunc (p *AnnotationsTransformerPlugin) Config(\n\t_ *resmap.PluginHelpers, c []byte) (err error) {\n\tp.Annotations = nil\n\tp.FieldSpecs = nil\n\treturn yaml.Unmarshal(c, p)\n}\n\n\n\nfunc NewAnnotationsTransformerPlugin() resmap.TransformerPlugin {\n\treturn &AnnotationsTransformerPlugin{}\n}\n\nfunc (p *AnnotationsTransformerPlugin) Transform(m resmap.ResMap) error ", "output": "{\n\tif len(p.Annotations) == 0 {\n\t\treturn nil\n\t}\n\treturn m.ApplyFilter(annotations.Filter{\n\t\tAnnotations: p.Annotations,\n\t\tFsSlice: p.FieldSpecs,\n\t})\n}"} {"input": "package sqlbase\n\nimport (\n\t\"testing\"\n\n\t\"github.com/cockroachdb/cockroach/pkg/keys\"\n\t\"github.com/cockroachdb/cockroach/pkg/roachpb\"\n\t\"github.com/cockroachdb/cockroach/pkg/util/leaktest\"\n)\n\n\n\nfunc TestKeyAddress(t *testing.T) ", "output": "{\n\tdefer leaktest.AfterTest(t)()\n\ttestCases := []struct {\n\t\tkey roachpb.Key\n\t}{\n\t\t{MakeNameMetadataKey(0, \"BAR\")},\n\t\t{MakeNameMetadataKey(1, \"BAR\")},\n\t\t{MakeNameMetadataKey(1, \"foo\")},\n\t\t{MakeNameMetadataKey(2, \"foo\")},\n\t\t{MakeDescMetadataKey(123)},\n\t\t{MakeDescMetadataKey(124)},\n\t}\n\tvar lastKey roachpb.Key\n\tfor i, test := range testCases {\n\t\tresultAddr, err := keys.Addr(test.key)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tresult := resultAddr.AsRawKey()\n\t\tif result.Compare(lastKey) <= 0 {\n\t\t\tt.Errorf(\"%d: key address %q is <= %q\", i, result, lastKey)\n\t\t}\n\t\tlastKey = result\n\t}\n}"} {"input": "package socketio\n\nimport \"errors\"\n\n\ntype BroadcastAdaptor interface {\n\n\tJoin(room string, socket Socket) error\n\n\tLeave(room string, socket Socket) error\n\n\tSend(ignore Socket, room, event string, args ...interface{}) error\n\n\tGetAllClients(room string) (map[string]Socket, error)\n}\n\nvar newBroadcast = newBroadcastDefault\n\ntype Broadcast map[string]map[string]Socket\n\nfunc newBroadcastDefault() BroadcastAdaptor {\n\treturn make(Broadcast)\n}\n\nfunc (b Broadcast) Join(room string, socket Socket) error {\n\tsockets, ok := b[room]\n\tif !ok {\n\t\tsockets = make(map[string]Socket)\n\t}\n\tsockets[socket.Id()] = socket\n\tb[room] = sockets\n\treturn nil\n}\n\nfunc (b Broadcast) Leave(room string, socket Socket) error {\n\tsockets, ok := b[room]\n\tif !ok {\n\t\treturn nil\n\t}\n\tdelete(sockets, socket.Id())\n\tif len(sockets) == 0 {\n\t\tdelete(b, room)\n\t\treturn nil\n\t}\n\tb[room] = sockets\n\treturn nil\n}\n\n\n\nfunc (b Broadcast) GetAllClients(room string) (map[string]Socket, error) {\n\tsockets, ok := b[room]\n\tif !ok {\n\t\treturn nil, errors.New(\"没有此房间\")\n\t}\n\treturn sockets, nil\n}\n\nfunc (b Broadcast) Send(ignore Socket, room, event string, args ...interface{}) error ", "output": "{\n\tsockets := b[room]\n\tfor id, s := range sockets {\n\t\tif ignore != nil && ignore.Id() == id {\n\t\t\tcontinue\n\t\t}\n\t\ts.Emit(event, args...)\n\t}\n\treturn nil\n}"} {"input": "package inst\n\nimport (\n\t\"github.com/outbrain/orchestrator/go/config\"\n)\n\n\ntype Maintenance struct {\n\tMaintenanceId uint\n\tKey InstanceKey\n\tBeginTimestamp string\n\tSecondsElapsed uint\n\tIsActive bool\n\tOwner string\n\tReason string\n}\n\nvar maintenanceOwner string = \"\"\n\nfunc GetMaintenanceOwner() string {\n\tif maintenanceOwner != \"\" {\n\t\treturn maintenanceOwner\n\t}\n\treturn config.Config.MaintenanceOwner\n}\n\n\n\nfunc SetMaintenanceOwner(owner string) ", "output": "{\n\tmaintenanceOwner = owner\n}"} {"input": "package engine\n\nimport \"syscall\"\n\n\ntype windowsFileLock struct {\n\tfd syscall.Handle\n}\n\n\n\nfunc newFileLock(name string) (fileLock, error) {\n\tp, err := syscall.UTF16PtrFromString(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfd, err := syscall.CreateFile(p,\n\t\tsyscall.GENERIC_READ|syscall.GENERIC_WRITE,\n\t\t0, nil, syscall.CREATE_ALWAYS,\n\t\tsyscall.FILE_ATTRIBUTE_NORMAL,\n\t\t0,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &windowsFileLock{fd: fd}, nil\n}\n\nfunc (fl *windowsFileLock) release() error ", "output": "{\n\treturn syscall.Close(fl.fd)\n}"} {"input": "package B_test\n\nimport (\n\t. \"github.com/onsi/gomega\"\n\t. \"gx/ipfs/QmNuLxhqRhfimRZeLttPe6Sa44MNwuHAdaFFa9TDuNZUmf/ginkgo\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestB(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"B Suite\")\n}"} {"input": "package pgparser\n\nimport (\n\t\"strings\"\n\n\t\"go.bmatsuo.co/go-lexer\"\n)\n\nconst (\n\titemLeftBrace lexer.ItemType = iota\n\titemRightBrace\n\titemLeftParen\n\titemRightParen\n\titemComma\n\titemQuotedString\n\titemBareString\n)\n\nfunc stateBegin(l *lexer.Lexer) lexer.StateFn {\n\tr, n := l.Advance()\n\n\tswitch r {\n\tcase '{':\n\t\tl.Emit(itemLeftBrace)\n\t\treturn stateBegin\n\tcase '}':\n\t\tl.Emit(itemRightBrace)\n\t\treturn stateBegin\n\tcase '(':\n\t\tl.Emit(itemLeftParen)\n\t\treturn stateBegin\n\tcase ')':\n\t\tl.Emit(itemRightParen)\n\t\treturn stateBegin\n\tcase ',':\n\t\tl.Emit(itemComma)\n\t\treturn stateBegin\n\tcase '\"':\n\t\tl.Backup()\n\t\treturn stateQuotedString\n\tdefault:\n\t\tif n > 0 {\n\t\t\tl.Backup()\n\t\t\treturn stateBareString\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc stateQuotedString(l *lexer.Lexer) lexer.StateFn {\n\tif !l.Accept(\"\\\"\") {\n\t\tl.Errorf(\"expected an opening quote\")\n\t}\n\n\tfor {\n\t\tif l.Accept(\"\\\\\") {\n\t\t\tl.Advance()\n\t\t}\n\n\t\tn := l.AcceptRunFunc(func(r rune) bool {\n\t\t\treturn r != '\\\\' && r != '\"'\n\t\t})\n\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !l.Accept(\"\\\"\") {\n\t\tl.Errorf(\"expected a closing quote\")\n\t}\n\n\tl.Emit(itemQuotedString)\n\n\treturn stateBegin\n}\n\n\n\nfunc stateBareString(l *lexer.Lexer) lexer.StateFn ", "output": "{\n\tl.AcceptRunFunc(func(r rune) bool {\n\t\treturn !strings.ContainsRune(`{}(),\"`, r)\n\t})\n\n\tl.Emit(itemBareString)\n\n\treturn stateBegin\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/robfig/revel\"\n\t\"github.com/robfig/revel/samples/chat/app/chatroom\"\n\t\"github.com/robfig/revel/samples/chat/app/routes\"\n)\n\ntype Refresh struct {\n\t*revel.Controller\n}\n\nfunc (c Refresh) Index(user string) revel.Result {\n\tchatroom.Join(user)\n\treturn c.Redirect(routes.Refresh.Room(user))\n}\n\n\n\nfunc (c Refresh) Say(user, message string) revel.Result {\n\tchatroom.Say(user, message)\n\treturn c.Redirect(routes.Refresh.Room(user))\n}\n\nfunc (c Refresh) Leave(user string) revel.Result {\n\tchatroom.Leave(user)\n\treturn c.Redirect(Application.Index)\n}\n\nfunc (c Refresh) Room(user string) revel.Result ", "output": "{\n\tsubscription := chatroom.Subscribe()\n\tdefer subscription.Cancel()\n\tevents := subscription.Archive\n\tfor i, _ := range events {\n\t\tif events[i].User == user {\n\t\t\tevents[i].User = \"you\"\n\t\t}\n\t}\n\treturn c.Render(user, events)\n}"} {"input": "package hostInfo\n\nimport (\n\t\"github.com/pkg/errors\"\n\t\"github.com/rancher/agent/utilities/constants\"\n)\n\ntype IopsCollector struct {\n}\n\nfunc (i IopsCollector) GetData() (map[string]interface{}, error) {\n\tdata, err := i.parseIopsData()\n\tif err != nil {\n\t\treturn map[string]interface{}{}, errors.Wrap(err, constants.IopsGetDataError+\"failed to get data\")\n\t}\n\treturn data, nil\n}\n\n\n\nfunc (i IopsCollector) GetLabels(prefix string) (map[string]string, error) {\n\treturn map[string]string{}, nil\n}\n\nfunc (i IopsCollector) KeyName() string ", "output": "{\n\treturn \"iopsInfo\"\n}"} {"input": "package handler\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/cosiner/zerver\"\n)\n\ntype MethodHandler interface {\n\tGet(zerver.Request, zerver.Response)\n\tPost(zerver.Request, zerver.Response)\n\tDelete(zerver.Request, zerver.Response)\n\tPut(zerver.Request, zerver.Response)\n\tPatch(zerver.Request, zerver.Response)\n}\n\ntype methodHandler struct {\n\tzerver.Component\n\tMethodHandler\n}\n\nfunc WrapMethodHandler(m MethodHandler) zerver.Handler {\n\treturn &methodHandler{\n\t\tComponent: zerver.NopComponent{},\n\t\tMethodHandler: m,\n\t}\n}\n\nfunc (s methodHandler) Handler(method string) zerver.HandleFunc {\n\tswitch method {\n\tcase zerver.METHOD_GET:\n\t\treturn s.Get\n\tcase zerver.METHOD_POST:\n\t\treturn s.Post\n\tcase zerver.METHOD_DELETE:\n\t\treturn s.Delete\n\tcase zerver.METHOD_PUT:\n\t\treturn s.Put\n\tcase zerver.METHOD_PATCH:\n\t\treturn s.Patch\n\t}\n\n\treturn nil\n}\n\ntype NopMethodHandler struct{}\n\n\n\nfunc (NopMethodHandler) Post(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Delete(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Put(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Patch(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Get(_ zerver.Request, resp zerver.Response) ", "output": "{\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}"} {"input": "package process\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Tree interface {\n\tGetParent(pid int) (int, error)\n}\n\ntype tree struct {\n\tprocesses map[int]Process\n}\n\n\nfunc NewTree(walker Walker) (Tree, error) {\n\tpt := tree{processes: map[int]Process{}}\n\terr := walker.Walk(func(p Process) {\n\t\tpt.processes[p.PID] = p\n\t})\n\n\treturn &pt, err\n}\n\n\n\n\nfunc (pt *tree) GetParent(pid int) (int, error) ", "output": "{\n\tproc, ok := pt.processes[pid]\n\tif !ok {\n\t\treturn -1, fmt.Errorf(\"PID %d not found\", pid)\n\t}\n\n\treturn proc.PPID, nil\n}"} {"input": "package butteredscones\n\nimport (\n\t\"time\"\n)\n\n\n\ntype Spooler struct {\n\tIn chan *FileData\n\tOut chan []*FileData\n\n\tsize int\n\ttimeout time.Duration\n}\n\nconst (\n\tspoolOutBuffer = 4\n)\n\nfunc NewSpooler(size int, timeout time.Duration) *Spooler {\n\treturn &Spooler{\n\t\tIn: make(chan *FileData, size*spoolOutBuffer),\n\t\tOut: make(chan []*FileData, spoolOutBuffer),\n\t\tsize: size,\n\t\ttimeout: timeout,\n\t}\n}\n\n\n\n\n\nfunc (s *Spooler) Spool() ", "output": "{\n\ttimer := time.NewTimer(s.timeout)\n\tcurrentChunk := make([]*FileData, 0, s.size)\n\tfor {\n\t\tselect {\n\t\tcase fileData, ok := <-s.In:\n\t\t\tif ok {\n\t\t\t\tcurrentChunk = append(currentChunk, fileData)\n\t\t\t\tif len(currentChunk) >= s.size {\n\t\t\t\t\ts.Out <- currentChunk\n\t\t\t\t\tcurrentChunk = make([]*FileData, 0, s.size)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-timer.C:\n\t\t\tif len(currentChunk) > 0 {\n\t\t\t\tselect {\n\t\t\t\tcase s.Out <- currentChunk:\n\t\t\t\t\tcurrentChunk = make([]*FileData, 0, s.size)\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttimer.Reset(s.timeout)\n\t}\n}"} {"input": "package goetchtest\n\nimport . \"etch\"\n\nfunc TestPlainMailBox() {\n\tmb := NewPlainMailBox(42)\n\n\tif mb.GetMessageId() != 42 {\n\t\tError(\"Mailbox has wrong ID\\n\")\n\t}\n\n\tmsg := new(Message)\n\n\tsender := 23\n\n\tgo TestPut(mb, msg, sender)\n\n\telem := mb.Read()\n\n\tif elem == nil {\n\t\tError(\"got nil elem from Mailbox\\n\")\n\t} else {\n\t\tif elem.Msg != msg {\n\t\t\tError(\"got wrong elem from Mailbox\\n\")\n\t\t}\n\n\t\tif elem.Who != 23 {\n\t\t\tError(\"got wrong sender from Mailbox\\n\")\n\t\t}\n\t}\n\n\n\n\tLog(\"TestPlainMailBox done\\n\")\n}\n\n\n\n\nfunc TestPut(mb Mailbox, msg *Message, sender interface{}) ", "output": "{\n\tmb.Message(sender, msg)\n}"} {"input": "package testutil\n\nimport (\n\t\"testing\"\n\n\tci \"gx/ipfs/QmP1DfoUjiWH2ZBo1PBH6FupdBucbDepx3HpWmEY6JMUpY/go-libp2p-crypto\"\n\tma \"gx/ipfs/QmcyqRMCAXVtYPS4DiBrA7sezL9rRGfW8Ctx7cywL4TXJj/go-multiaddr\"\n\tpeer \"gx/ipfs/QmdS9KpbDyPrieswibZhkod1oXqRwZJrUPzxCofAMWpFGq/go-libp2p-peer\"\n)\n\ntype Identity interface {\n\tAddress() ma.Multiaddr\n\tID() peer.ID\n\tPrivateKey() ci.PrivKey\n\tPublicKey() ci.PubKey\n}\n\n\n\nfunc RandIdentity() (Identity, error) {\n\tp, err := RandPeerNetParams()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &identity{*p}, nil\n}\n\nfunc RandIdentityOrFatal(t *testing.T) Identity {\n\tp, err := RandPeerNetParams()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn &identity{*p}\n}\n\n\ntype identity struct {\n\tPeerNetParams\n}\n\nfunc (p *identity) ID() peer.ID {\n\treturn p.PeerNetParams.ID\n}\n\nfunc (p *identity) Address() ma.Multiaddr {\n\treturn p.Addr\n}\n\n\n\nfunc (p *identity) PublicKey() ci.PubKey {\n\treturn p.PubKey\n}\n\nfunc (p *identity) PrivateKey() ci.PrivKey ", "output": "{\n\treturn p.PrivKey\n}"} {"input": "package image\n\nimport (\n\t\"github.com/containers/image/types\"\n)\n\n\n\n\ntype imageCloser struct {\n\ttypes.Image\n\tsrc types.ImageSource\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc FromSource(ctx *types.SystemContext, src types.ImageSource) (types.ImageCloser, error) {\n\timg, err := FromUnparsedImage(ctx, UnparsedInstance(src, nil))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &imageCloser{\n\t\tImage: img,\n\t\tsrc: src,\n\t}, nil\n}\n\nfunc (ic *imageCloser) Close() error {\n\treturn ic.src.Close()\n}\n\n\n\n\n\n\ntype sourcedImage struct {\n\t*UnparsedImage\n\tmanifestBlob []byte\n\tmanifestMIMEType string\n\tgenericManifest\n}\n\n\n\n\n\n\n\n\n\nfunc (i *sourcedImage) Size() (int64, error) {\n\treturn -1, nil\n}\n\n\nfunc (i *sourcedImage) Manifest() ([]byte, string, error) {\n\treturn i.manifestBlob, i.manifestMIMEType, nil\n}\n\nfunc (i *sourcedImage) Inspect() (*types.ImageInspectInfo, error) {\n\treturn inspectManifest(i.genericManifest)\n}\n\nfunc (i *sourcedImage) LayerInfosForCopy() []types.BlobInfo {\n\treturn i.UnparsedImage.LayerInfosForCopy()\n}\n\nfunc FromUnparsedImage(ctx *types.SystemContext, unparsed *UnparsedImage) (types.Image, error) ", "output": "{\n\n\tmanifestBlob, manifestMIMEType, err := unparsed.Manifest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparsedManifest, err := manifestInstanceFromBlob(ctx, unparsed.src, manifestBlob, manifestMIMEType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &sourcedImage{\n\t\tUnparsedImage: unparsed,\n\t\tmanifestBlob: manifestBlob,\n\t\tmanifestMIMEType: manifestMIMEType,\n\t\tgenericManifest: parsedManifest,\n\t}, nil\n}"} {"input": "package testutil\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/pingcap/check\"\n)\n\nfunc TestT(t *testing.T) {\n\tTestingT(t)\n}\n\nvar _ = Suite(&testTestUtilSuite{})\n\ntype testTestUtilSuite struct {\n}\n\n\n\nfunc (s *testTestUtilSuite) TestCompareUnorderedString(c *C) ", "output": "{\n\ttbl := []struct {\n\t\ta []string\n\t\tb []string\n\t\tr bool\n\t}{\n\t\t{[]string{\"1\", \"1\", \"2\"}, []string{\"1\", \"1\", \"2\"}, true},\n\t\t{[]string{\"1\", \"1\", \"2\"}, []string{\"1\", \"2\", \"1\"}, true},\n\t\t{[]string{\"1\", \"1\"}, []string{\"1\", \"2\", \"1\"}, false},\n\t\t{[]string{\"1\", \"1\", \"2\"}, []string{\"1\", \"2\", \"2\"}, false},\n\t\t{nil, nil, true},\n\t\t{[]string{}, nil, false},\n\t\t{nil, []string{}, false},\n\t}\n\tfor _, t := range tbl {\n\t\tc.Assert(CompareUnorderedStringSlice(t.a, t.b), Equals, t.r)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/ying32/govcl/vcl\"\n\t\"github.com/ying32/govcl/vcl/rtl\"\n\t\"github.com/ying32/govcl/vcl/types\"\n\t\"github.com/ying32/govcl/vcl/types/keys\"\n\t\"github.com/ying32/govcl/vcl/types/messages\"\n\t\"github.com/ying32/govcl/vcl/win\"\n)\n\n\ntype TForm1Fields struct {\n\thotKeyId types.ATOM\n}\n\n\n\nfunc (f *TForm1) OnFormDestroy(sender vcl.IObject) {\n\tif f.hotKeyId > 0 {\n\t\twin.UnregisterHotKey(f.Handle(), int32(f.hotKeyId))\n\t\twin.GlobalDeleteAtom(f.hotKeyId)\n\t}\n}\n\nfunc (f *TForm1) OnFormWndProc(msg *types.TMessage) {\n\n\tf.InheritedWndProc(msg)\n\tif msg.Msg == messages.WM_HOTKEY {\n\t\tif msg.WParam == types.WPARAM(f.hotKeyId) {\n\t\t\tvcl.ShowMessage(\"按下了Ctrl+F1\")\n\t\t}\n\t}\n}\n\nfunc (f *TForm1) OnFormCreate(sender vcl.IObject) ", "output": "{\n\tf.SetCaption(\"Press Ctrl+F1\")\n\tf.ScreenCenter()\n\tf.hotKeyId = win.GlobalAddAtom(\"HotKeyId\") - 0xC000\n\tshift := types.NewSet(types.SsCtrl)\n\tif !win.RegisterHotKey(f.Handle(), int32(f.hotKeyId), rtl.ShiftStateToWord(shift), keys.VkF1) {\n\t\tvcl.ShowMessage(\"注册热键失败。\")\n\t}\n\n}"} {"input": "package common\n\nimport \"math/big\"\n\ntype _N_ [_S_]byte\n\nfunc BytesTo_N_(b []byte) _N_ {\n\tvar h _N_\n\th.SetBytes(b)\n\treturn h\n}\nfunc StringTo_N_(s string) _N_ { return BytesTo_N_([]byte(s)) }\n\nfunc HexTo_N_(s string) _N_ { return BytesTo_N_(FromHex(s)) }\n\n\n\n\nfunc (h _N_) Str() string { return string(h[:]) }\nfunc (h _N_) Bytes() []byte { return h[:] }\nfunc (h _N_) Big() *big.Int { return Bytes2Big(h[:]) }\nfunc (h _N_) Hex() string { return \"0x\" + Bytes2Hex(h[:]) }\n\n\nfunc (h *_N_) SetBytes(b []byte) {\n\tif len(b) > len(h) {\n\t\tb = b[len(b)-_S_:]\n\t}\n\n\tfor i := len(b) - 1; i >= 0; i-- {\n\t\th[_S_-len(b)+i] = b[i]\n\t}\n}\n\n\nfunc (h *_N_) SetString(s string) { h.SetBytes([]byte(s)) }\n\n\nfunc (h *_N_) Set(other _N_) {\n\tfor i, v := range other {\n\t\th[i] = v\n\t}\n}\n\nfunc BigTo_N_(b *big.Int) _N_ ", "output": "{ return BytesTo_N_(b.Bytes()) }"} {"input": "package serialconsole\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/serialconsole/mgmt/2018-05-01/serialconsole\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype BaseClient = original.BaseClient\ntype ConsoleClient = original.ConsoleClient\ntype DeploymentValidateResult = original.DeploymentValidateResult\ntype GetDisabledResult = original.GetDisabledResult\ntype GetResult = original.GetResult\ntype ListClient = original.ListClient\ntype ListConsoleClient = original.ListConsoleClient\ntype Operations = original.Operations\ntype SetDisabledResult = original.SetDisabledResult\n\nfunc New(subscriptionID string) BaseClient {\n\treturn original.New(subscriptionID)\n}\nfunc NewConsoleClient(subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClient(subscriptionID)\n}\nfunc NewConsoleClientWithBaseURI(baseURI string, subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewListClient(subscriptionID string) ListClient {\n\treturn original.NewListClient(subscriptionID)\n}\nfunc NewListClientWithBaseURI(baseURI string, subscriptionID string) ListClient {\n\treturn original.NewListClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewListConsoleClient(subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClient(subscriptionID)\n}\nfunc NewListConsoleClientWithBaseURI(baseURI string, subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\n\nfunc Version() string {\n\treturn original.Version()\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn original.UserAgent() + \" profiles/preview\"\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\n\t\"gopkg.in/stretchr/testify.v1/mock\"\n)\n\ntype Printer interface {\n\tHelp()\n\tVersion()\n\tMessage(msg string)\n\tError(err error)\n\tCommands()\n}\n\ntype TextPrinter struct {\n\tversion string\n}\n\n\n\nfunc (p *TextPrinter) Help() {\n\thelpText := `Name:\n\tfiz - a file wizard\n\nVersion:\n\t` + p.version + `\n\nUsage:\n\tfiz \n\n`\n\tp.Message(helpText)\n\tp.Commands()\n}\n\nfunc (p *TextPrinter) Version() {\n\tfmt.Println(\"fiz\", p.version)\n}\n\nfunc (p *TextPrinter) Message(msg string) {\n\tfmt.Print(msg)\n}\n\nfunc (p *TextPrinter) Error(err error) {\n\tfmt.Println(\"Error: \", err)\n}\n\nfunc (p *TextPrinter) Commands() {\n\tp.Message(COMMANDS_MSG)\n}\n\n\ntype MockPrinter struct {\n\tmock.Mock\n}\n\nfunc NewMockPrinter() *MockPrinter {\n\treturn &MockPrinter{}\n}\n\nfunc (m *MockPrinter) Help() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Version() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Message(msg string) {\n\tm.Called(msg)\n}\n\nfunc (m *MockPrinter) Error(err error) {\n\tm.Called(err)\n}\n\nfunc (m *MockPrinter) Commands() {\n\tm.Called()\n}\n\nfunc NewTextPrinter(version string) *TextPrinter ", "output": "{\n\treturn &TextPrinter{version}\n}"} {"input": "package iso20022\n\n\ntype DirectDebitTransaction1 struct {\n\n\tMandateRelatedInformation *MandateRelatedInformation1 `xml:\"MndtRltdInf,omitempty\"`\n\n\tCreditorSchemeIdentification *PartyIdentification8 `xml:\"CdtrSchmeId,omitempty\"`\n\n\tPreNotificationIdentification *Max35Text `xml:\"PreNtfctnId,omitempty\"`\n\n\tPreNotificationDate *ISODate `xml:\"PreNtfctnDt,omitempty\"`\n}\n\nfunc (d *DirectDebitTransaction1) AddMandateRelatedInformation() *MandateRelatedInformation1 {\n\td.MandateRelatedInformation = new(MandateRelatedInformation1)\n\treturn d.MandateRelatedInformation\n}\n\nfunc (d *DirectDebitTransaction1) AddCreditorSchemeIdentification() *PartyIdentification8 {\n\td.CreditorSchemeIdentification = new(PartyIdentification8)\n\treturn d.CreditorSchemeIdentification\n}\n\nfunc (d *DirectDebitTransaction1) SetPreNotificationIdentification(value string) {\n\td.PreNotificationIdentification = (*Max35Text)(&value)\n}\n\n\n\nfunc (d *DirectDebitTransaction1) SetPreNotificationDate(value string) ", "output": "{\n\td.PreNotificationDate = (*ISODate)(&value)\n}"} {"input": "package blb\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/baiducloud/baiducloud-sdk-go/bce\"\n)\n\n\nvar Endpoint = map[string]string{\n\t\"bj\": \"blb.bj.baidubce.com\",\n\t\"gz\": \"blb.gz.baidubce.com\",\n\t\"su\": \"blb.su.baidubce.com\",\n\t\"hk\": \"blb.hkg.baidubce.com\",\n\t\"bd\": \"blb.bd.baidubce.com\",\n}\n\n\ntype Client struct {\n\t*bce.Client\n}\n\n\n\n\n\nfunc (c *Client) GetURL(version string, params map[string]string) string {\n\thost := c.Endpoint\n\tif host == \"\" {\n\t\thost = Endpoint[c.GetRegion()]\n\t}\n\turiPath := version\n\treturn c.Client.GetURL(host, uriPath, params)\n}\n\nfunc NewBLBClient(config *bce.Config) *Client ", "output": "{\n\tbceClient := bce.NewClient(config)\n\treturn &Client{bceClient}\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/signal\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n)\n\ntype threadSafePrintliner struct {\n\tl sync.Mutex\n\tw io.Writer\n}\n\nfunc newThreadSafePrintliner(w io.Writer) *threadSafePrintliner {\n\treturn &threadSafePrintliner{w: w}\n}\n\nfunc (p *threadSafePrintliner) println(s string) {\n\tp.l.Lock()\n\tfmt.Fprintln(p.w, s)\n\tp.l.Unlock()\n}\n\n\n\nfunc trimEmpty(s []string) []string {\n\tvar r = make([]string, 0)\n\tfor _, str := range s {\n\t\tif str != \"\" {\n\t\t\tr = append(r, str)\n\t\t}\n\t}\n\treturn r\n}\n\nfunc awaitSignal(cancel context.CancelFunc) {\n\tsignals := make(chan os.Signal)\n\tsignal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)\n\t<-signals\n\tcancel()\n}\n\nfunc readQuery(r io.Reader) string ", "output": "{\n\ts, _ := ioutil.ReadAll(r) \n\treturn strings.TrimSpace(strings.Replace(string(s), \"\\n\", \" \", -1))\n}"} {"input": "package web\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/gravitational/teleport/lib/httplib\"\n\n\t\"github.com/gravitational/roundtrip\"\n\t\"github.com/gravitational/trace\"\n)\n\nfunc newInsecureClient() *http.Client {\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t}\n}\n\nfunc newClientWithPool(pool *x509.CertPool) *http.Client {\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{RootCAs: pool},\n\t\t},\n\t}\n}\n\nfunc newWebClient(url string, opts ...roundtrip.ClientParam) (*webClient, error) {\n\tclt, err := roundtrip.NewClient(url, APIVersion, opts...)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn &webClient{clt}, nil\n}\n\n\n\ntype webClient struct {\n\t*roundtrip.Client\n}\n\nfunc (w *webClient) PostJSON(\n\tendpoint string, val interface{}) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.PostJSON(endpoint, val))\n}\n\nfunc (w *webClient) PutJSON(\n\tendpoint string, val interface{}) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.PutJSON(endpoint, val))\n}\n\n\n\nfunc (w *webClient) Delete(endpoint string) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.Delete(endpoint))\n}\n\nfunc (w *webClient) Get(endpoint string, val url.Values) (*roundtrip.Response, error) ", "output": "{\n\treturn httplib.ConvertResponse(w.Client.Get(endpoint, val))\n}"} {"input": "package navigator\n\nimport (\n\t\"bytes\"\n\t\"image\"\n\t\"image/draw\"\n\t\"log\"\n\n\t\"github.com/nelsam/gxui\"\n\t\"github.com/nelsam/vidar/asset\"\n\t\"github.com/nfnt/resize\"\n\n\t_ \"image/gif\"\n\t_ \"image/jpeg\"\n\t_ \"image/png\"\n)\n\n\n\nfunc createIconButton(driver gxui.Driver, theme gxui.Theme, iconPath string) gxui.Button ", "output": "{\n\tbutton := theme.CreateButton()\n\tbutton.SetType(gxui.PushButton)\n\n\tfileBytes, err := asset.Asset(iconPath)\n\tif err != nil {\n\t\tlog.Printf(\"Error: Failed to read asset %s: %s\", iconPath, err)\n\t\treturn button\n\t}\n\tf := bytes.NewBuffer(fileBytes)\n\tsrc, _, err := image.Decode(f)\n\tif err != nil {\n\t\tlog.Printf(\"Error: Failed to decode image %s: %s\", iconPath, err)\n\t\treturn button\n\t}\n\tsrc = resize.Resize(24, 24, src, resize.Bilinear)\n\n\trgba := image.NewRGBA(src.Bounds())\n\tdraw.Draw(rgba, src.Bounds(), src, image.ZP, draw.Src)\n\ttexture := driver.CreateTexture(rgba, 1)\n\n\ticon := theme.CreateImage()\n\ticon.SetTexture(texture)\n\tbutton.AddChild(icon)\n\treturn button\n}"} {"input": "package p10\n\nimport (\n\t\"fmt\"\n\n\tc \"s13g.com/euler/common\"\n)\n\n\n\nfunc Solve(input string) (string, string) {\n\treturn c.ToString(solveA(c.ParseIntArray(c.SplitByCommaTrim(input)))), solveB(input)\n}\n\nfunc solveA(lengths []int) int {\n\tnumbers := ProcessLengths(lengths, 1)\n\treturn numbers[0] * numbers[1]\n}\n\n\n\n\nfunc KnotHash(input string) string {\n\treturn solveB(input)\n}\n\nfunc ProcessLengths(lengths []int, numRounds int) []int {\n\treverseCircular := func(list []int, start int, length int) {\n\t\tfor l, r := start, start+length-1; l < r; l, r = l+1, r-1 {\n\t\t\tll, rr := l%len(list), r%len(list)\n\t\t\tlist[ll], list[rr] = list[rr], list[ll]\n\t\t}\n\t}\n\n\tnumbers := make([]int, 256)\n\tfor i := range numbers {\n\t\tnumbers[i] = i\n\t}\n\n\tcurrPos, skipSize := 0, 0\n\tfor round := 0; round < numRounds; round++ {\n\t\tfor _, length := range lengths {\n\t\t\treverseCircular(numbers, currPos, length)\n\t\t\tcurrPos += length + skipSize\n\t\t\tskipSize++\n\t\t}\n\t}\n\treturn numbers\n}\n\nfunc solveB(input string) string ", "output": "{\n\tlengths := make([]int, len(input))\n\tfor i, c := range input {\n\t\tlengths[i] = int(c)\n\t}\n\tlengths = append(lengths, 17, 31, 73, 47, 23)\n\tnumbers := ProcessLengths(lengths, 64)\n\n\tdenseHash := make([]int, 16)\n\tfor block := 0; block < 16; block++ {\n\t\tfor start, i := block*16, 0; i < 16; i++ {\n\t\t\tdenseHash[block] ^= numbers[start+i]\n\t\t}\n\t}\n\treturn c.MapIStr(denseHash, func(b int) string { return fmt.Sprintf(\"%02x\", b) })\n}"} {"input": "package main\n\nimport (\n\t\"github.com/sgoertzen/xchango\"\n\t\"golang.org/x/oauth2\"\n\t\"log\"\n\t\"sort\"\n\t\"time\"\n)\n\nconst (\n\texchangeLoginCaptured = \"exchange login capture\"\n\texchangeLoginVerified = \"exchange login verified\"\n\toauthTokenRecieved = \"oauth token recieved\"\n\tregistered = \"queued\"\n\tsyncing = \"syncing\"\n\tsyncingerror = \"sync error\"\n\tsuccessfulsync = \"success\"\n\tregistererror = \"registration error\"\n)\n\ntype User struct {\n\tUsername string\n\tPassword string\n\tToken *oauth2.Token\n\tDatecreated time.Time\n\tLastSync time.Time\n\tFolderid string\n\tChangekey string\n\tGCalid string\n\tState string\n\tExUser *xchango.ExchangeUser\n\tExCal *xchango.ExchangeCalendar\n}\n\ntype Serializer func([]User) error\n\nvar serializeUsers = SerializeUsers\nvar m map[string]User\n\n\n\nfunc GetUser(username string) User {\n\tif m == nil {\n\t\treturn User{}\n\t}\n\treturn m[username]\n}\n\nfunc GetUsers() []User {\n\tif m == nil {\n\t\treturn make([]User, 0)\n\t}\n\tusers := make([]User, len(m))\n\n\tvar keys []string\n\tfor k := range m {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\tfor i, username := range keys {\n\t\tusers[i] = m[username]\n\t}\n\treturn users\n}\n\nfunc DeleteUser(username string) error {\n\tlog.Printf(\"Removing user: '%s'\", username)\n\tdelete(m, username)\n\terr := serializeUsers(GetUsers())\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\treturn err\n}\n\nfunc (u User) Save() error ", "output": "{\n\tif m == nil {\n\t\tm = make(map[string]User)\n\t}\n\tif u.ExUser == nil {\n\t\tu.ExUser = &xchango.ExchangeUser{Username: u.Username, Password: u.Password}\n\t}\n\tif u.ExCal == nil {\n\t\tu.ExCal = &xchango.ExchangeCalendar{Folderid: u.Folderid, Changekey: u.Changekey}\n\t}\n\n\tlog.Printf(\"Storing user: '%s'\", u.ExUser.Username)\n\tt := time.Time{}\n\tif u.Datecreated == t {\n\t\tu.Datecreated = time.Now()\n\t}\n\tm[u.Username] = u\n\terr := serializeUsers(GetUsers())\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package task_config\n\nimport (\n\t\"github.com/sonm-io/core/proto\"\n\t\"github.com/sonm-io/core/util/config\"\n)\n\n\n\nfunc LoadConfig(path string) (*sonm.TaskSpec, error) ", "output": "{\n\tcfg := &sonm.TaskSpec{}\n\tif err := config.LoadWith(cfg, path, config.SnakeToLower); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := cfg.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cfg, nil\n}"} {"input": "package phaul\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype images struct {\n\tcursor int\n\tdir string\n}\n\nfunc preparePhaulImages(wdir string) (*images, error) {\n\treturn &images{dir: wdir}, nil\n}\n\nfunc (i *images) getPath(idx int) string {\n\treturn fmt.Sprintf(i.dir+\"/%d\", idx)\n}\n\n\n\nfunc (i *images) lastImagesDir() string {\n\tvar ret string\n\tif i.cursor == 0 {\n\t\tret = \"\"\n\t} else {\n\t\tret, _ = filepath.Abs(i.getPath(i.cursor - 1))\n\t}\n\treturn ret\n}\n\nfunc (i *images) openNextDir() (*os.File, error) ", "output": "{\n\tipath := i.getPath(i.cursor)\n\terr := os.Mkdir(ipath, 0700)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ti.cursor++\n\treturn os.Open(ipath)\n}"} {"input": "package whisper\n\nimport \"github.com/Tzunami/go-earthdollar/crypto\"\n\n\n\n\ntype Topic [4]byte\n\n\n\n\nfunc NewTopic(data []byte) Topic {\n\tprefix := [4]byte{}\n\tcopy(prefix[:], crypto.Keccak256(data)[:4])\n\treturn Topic(prefix)\n}\n\n\n\n\n\n\nfunc (self *Topic) String() string {\n\treturn string(self[:])\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype topicMatcher struct {\n\tconditions []map[Topic]struct{}\n}\n\n\nfunc newTopicMatcher(topics ...[]Topic) *topicMatcher {\n\tmatcher := make([]map[Topic]struct{}, len(topics))\n\tfor i, condition := range topics {\n\t\tmatcher[i] = make(map[Topic]struct{})\n\t\tfor _, topic := range condition {\n\t\t\tmatcher[i][topic] = struct{}{}\n\t\t}\n\t}\n\treturn &topicMatcher{conditions: matcher}\n}\n\n\nfunc (self *topicMatcher) Matches(topics []Topic) bool {\n\tif len(self.conditions) > len(topics) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(topics) && i < len(self.conditions); i++ {\n\t\tif len(self.conditions[i]) > 0 {\n\t\t\tif _, ok := self.conditions[i][topics[i]]; !ok {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\nfunc NewTopics(data ...[]byte) []Topic ", "output": "{\n\ttopics := make([]Topic, len(data))\n\tfor i, element := range data {\n\t\ttopics[i] = NewTopic(element)\n\t}\n\treturn topics\n}"} {"input": "package cachestore\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\ntype CacheStore struct {\n\tstores map[string]*KVStore\n\tmutex sync.RWMutex\n}\n\n\n\n\n\n\n\nfunc (c *CacheStore) CreateStore(svcName string) *KVStore {\n\tkvstore := NewKVStore()\n\tc.mutex.Lock()\n\tc.stores[svcName] = kvstore\n\tc.mutex.Unlock()\n\n\treturn kvstore\n}\n\n\nfunc (c *CacheStore) DeleteStore(svcName string) {\n\tc.mutex.Lock()\n\tdelete(c.stores, svcName)\n\tc.mutex.Unlock()\n}\n\n\nfunc (c *CacheStore) SetCache(svcName string, key string, value interface{}) {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore == nil {\n\t\tsvcStore = c.CreateStore(svcName)\n\t}\n\n\tsvcStore.Set(key, value)\n}\n\n\n\nfunc (c *CacheStore) GetCache(svcName string, key string) interface{} {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore == nil {\n\t\treturn nil\n\t}\n\treturn svcStore.Get(key)\n}\n\n\nfunc (c *CacheStore) DeleteCache(svcName string, key string) {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore != nil {\n\t\tsvcStore.Delete(key)\n\t}\n}\n\n\nfunc (c *CacheStore) MarshalJSON() ([]byte, error) {\n\tc.mutex.RLock()\n\tbytes, err := json.Marshal(&c.stores)\n\tc.mutex.RUnlock()\n\treturn bytes, err\n}\n\n\nfunc NewCacheStore() *CacheStore {\n\treturn &CacheStore{map[string]*KVStore{}, sync.RWMutex{}}\n}\n\nfunc (c *CacheStore) GetStore(svcName string) *KVStore ", "output": "{\n\tc.mutex.RLock()\n\tkvstore := c.stores[svcName]\n\tc.mutex.RUnlock()\n\n\treturn kvstore\n}"} {"input": "package runtime\n\nimport \"unsafe\"\n\n\n\n\n\n\nfunc atomicload(ptr *uint32) uint32 {\n\tnop()\n\treturn *ptr\n}\n\n\nfunc atomicloadp(ptr unsafe.Pointer) unsafe.Pointer {\n\tnop()\n\treturn *(*unsafe.Pointer)(ptr)\n}\n\n\nfunc xadd64(ptr *uint64, delta int64) uint64 {\n\tfor {\n\t\told := *ptr\n\t\tif cas64(ptr, old, old+uint64(delta)) {\n\t\t\treturn old + uint64(delta)\n\t\t}\n\t}\n}\n\n\n\n\n\nfunc xadd(ptr *uint32, delta int32) uint32\n\n\nfunc xchg(ptr *uint32, new uint32) uint32\n\n\nfunc xchgp1(ptr unsafe.Pointer, new unsafe.Pointer) unsafe.Pointer\n\n\nfunc xchguintptr(ptr *uintptr, new uintptr) uintptr\n\n\nfunc atomicload64(ptr *uint64) uint64\n\n\nfunc atomicand8(ptr *uint8, val uint8)\n\n\nfunc atomicor8(ptr *uint8, val uint8)\n\n\n\n\nfunc cas64(ptr *uint64, old, new uint64) bool\n\n\nfunc atomicstore(ptr *uint32, val uint32)\n\n\nfunc atomicstore64(ptr *uint64, val uint64)\n\n\nfunc atomicstorep1(ptr unsafe.Pointer, val unsafe.Pointer)\n\nfunc xchg64(ptr *uint64, new uint64) uint64 ", "output": "{\n\tfor {\n\t\told := *ptr\n\t\tif cas64(ptr, old, new) {\n\t\t\treturn old\n\t\t}\n\t}\n}"} {"input": "package handlers\n\nimport (\n\t\"net/http\"\n\t\"strconv\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"github.com/codedellemc/rexray/libstorage/api/types\"\n)\n\n\n\ntype queryParamsHandler struct {\n\thandler types.APIFunc\n}\n\nfunc (h *queryParamsHandler) Name() string {\n\treturn \"query-params-handler\"\n}\n\n\n\n\n\nfunc (h *queryParamsHandler) Handler(m types.APIFunc) types.APIFunc {\n\treturn (&queryParamsHandler{m}).Handle\n}\n\n\nfunc (h *queryParamsHandler) Handle(\n\tctx types.Context,\n\tw http.ResponseWriter,\n\treq *http.Request,\n\tstore types.Store) error {\n\n\tfor k, v := range req.URL.Query() {\n\t\tctx.WithFields(log.Fields{\n\t\t\t\"key\": k,\n\t\t\t\"value\": v,\n\t\t\t\"len(value)\": len(v),\n\t\t}).Debug(\"query param\")\n\t\tswitch len(v) {\n\t\tcase 0:\n\t\t\tstore.Set(k, true)\n\t\tcase 1:\n\t\t\tif len(v[0]) == 0 {\n\t\t\t\tstore.Set(k, true)\n\t\t\t} else {\n\t\t\t\tif i, err := strconv.ParseInt(v[0], 10, 64); err == nil {\n\t\t\t\t\tstore.Set(k, i)\n\t\t\t\t} else if b, err := strconv.ParseBool(v[0]); err == nil {\n\t\t\t\t\tstore.Set(k, b)\n\t\t\t\t} else {\n\t\t\t\t\tstore.Set(k, v[0])\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\tstore.Set(k, v)\n\t\t}\n\t}\n\treturn h.handler(ctx, w, req, store)\n}\n\nfunc NewQueryParamsHandler() types.Middleware ", "output": "{\n\treturn &queryParamsHandler{}\n}"} {"input": "package systemd\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/google/cadvisor/container\"\n\t\"github.com/google/cadvisor/fs\"\n\tinfo \"github.com/google/cadvisor/info/v1\"\n\t\"github.com/google/cadvisor/watcher\"\n\n\t\"k8s.io/klog/v2\"\n)\n\ntype systemdFactory struct{}\n\nfunc (f *systemdFactory) String() string {\n\treturn \"systemd\"\n}\n\n\n\nfunc (f *systemdFactory) CanHandleAndAccept(name string) (bool, bool, error) {\n\tif strings.HasSuffix(name, \".mount\") {\n\t\treturn true, false, nil\n\t}\n\tklog.V(5).Infof(\"%s not handled by systemd handler\", name)\n\treturn false, false, nil\n}\n\nfunc (f *systemdFactory) DebugInfo() map[string][]string {\n\treturn map[string][]string{}\n}\n\n\nfunc Register(machineInfoFactory info.MachineInfoFactory, fsInfo fs.FsInfo, includedMetrics container.MetricSet) error {\n\tklog.V(1).Infof(\"Registering systemd factory\")\n\tfactory := &systemdFactory{}\n\tcontainer.RegisterContainerHandlerFactory(factory, []watcher.ContainerWatchSource{watcher.Raw})\n\treturn nil\n}\n\nfunc (f *systemdFactory) NewContainerHandler(name string, inHostNamespace bool) (container.ContainerHandler, error) ", "output": "{\n\treturn nil, fmt.Errorf(\"Not yet supported\")\n}"} {"input": "package main\n\nvar (\n\trooms = Rooms{rooms: map[string]*room{}}\n)\n\ntype room struct {\n\tName string\n\tConns map[string]*Conn\n}\n\nfunc (r *room) getConn(peerID string) *Conn {\n\tc, ok := r.Conns[peerID]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn c\n}\n\nfunc (r *room) remove(c *Conn) {\n\tdelete(r.Conns, c.SessID)\n}\n\n\nfunc (r *room) broadcast(c *Conn, evt *Event, me bool) {\n\tfor _, p := range r.Conns {\n\t\tif !me && c != nil && p.SessID == c.SessID {\n\t\t\tcontinue\n\t\t}\n\t\tp.send(evt)\n\t}\n\n}\n\nfunc (r *room) getOther(c *Conn) []*Conn {\n\tothers := []*Conn{}\n\tfor _, p := range r.Conns {\n\t\tif p.SessID != c.SessID {\n\t\t\tothers = append(others, p)\n\t\t}\n\t}\n\treturn others\n}\n\ntype Rooms struct {\n\trooms map[string]*room\n}\n\n\nfunc (r *Rooms) add(c *Conn, roomName string) *room {\n\trm := r.getRoom(roomName)\n\tif rm == nil {\n\t\trm = &room{\n\t\t\tName: roomName,\n\t\t\tConns: map[string]*Conn{},\n\t\t}\n\t\tr.rooms[roomName] = rm\n\t}\n\trm.Conns[c.SessID] = c\n\treturn rm\n}\n\nfunc (r *Rooms) getRoom(roomName string) *room {\n\trm, ok := r.rooms[roomName]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn rm\n}\n\n\n\nfunc joinRoom(c *Conn, evt Event, msg []byte) ", "output": "{\n\tc.Room = evt.Data.Room\n\tc.Name = evt.Data.Name\n\n\troom := rooms.add(c, evt.Data.Room)\n\n\tjoinEvt := Event{\n\t\tName: \"peer_join_room\",\n\t\tData: EventData{\n\t\t\tPeerID: c.SessID,\n\t\t\tName: c.Name,\n\t\t},\n\t}\n\troom.broadcast(c, &joinEvt, false)\n\n\tc.send(&Event{\n\t\tName: \"join_room_ok\",\n\t\tData: EventData{\n\t\t\tPeerID: c.SessID,\n\t\t\tRoomName: c.Room,\n\t\t},\n\t})\n\n\tc.send(&Event{\n\t\tName: \"get_peers\",\n\t\tData: EventData{\n\t\t\tPeers: room.getOther(c),\n\t\t},\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"github.com/ajstarks/openvg\"\n\t\"math/rand\"\n\t\"os\"\n\t\"time\"\n)\n\n\n\nfunc randf() openvg.VGfloat {\n\treturn openvg.VGfloat(rand.Float32())\n}\nfunc main() {\n\tvar nr = flag.Int(\"n\", 500, \"number of objects\")\n\tvar message = flag.String(\"m\", \"Go/OpenVG\", \"message\")\n\tvar bgcolor = flag.String(\"bg\", \"white\", \"background color\")\n\tvar fgcolor = flag.String(\"fg\", \"maroon\", \"text color\")\n\n\tflag.Parse()\n\trseed()\n\n\twidth, height := openvg.Init()\n\tfw := openvg.VGfloat(width)\n\tfh := openvg.VGfloat(height)\n\n\topenvg.Start(width, height)\n\topenvg.BackgroundColor(*bgcolor)\n\tfor i := 0; i < *nr; i++ {\n\n\t\tred := uint8(rand.Intn(255))\n\t\tgreen := uint8(rand.Intn(255))\n\t\tblue := uint8(rand.Intn(255))\n\t\talpha := randf()\n\n\t\tx := randf() * fw\n\t\ty := randf() * fh\n\t\tradius := randf() * fw / 10\n\n\t\topenvg.FillRGB(red, green, blue, alpha)\n\t\topenvg.Circle(x, y, radius)\n\t}\n\topenvg.FillColor(*fgcolor)\n\topenvg.TextMid(fw/2, fh/2, *message, \"sans\", width/25)\n\topenvg.End()\n\n\tbufio.NewReader(os.Stdin).ReadBytes('\\n')\n\topenvg.Finish()\n}\n\nfunc rseed() ", "output": "{\n\trand.Seed(int64(time.Now().Nanosecond()) % 1e9)\n}"} {"input": "package iso20022\n\n\ntype CorporateActionOption21Choice struct {\n\n\tCode *CorporateActionOption10Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification30 `xml:\"Prtry\"`\n}\n\nfunc (c *CorporateActionOption21Choice) SetCode(value string) {\n\tc.Code = (*CorporateActionOption10Code)(&value)\n}\n\n\n\nfunc (c *CorporateActionOption21Choice) AddProprietary() *GenericIdentification30 ", "output": "{\n\tc.Proprietary = new(GenericIdentification30)\n\treturn c.Proprietary\n}"} {"input": "package bastion\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype WorkRequestError struct {\n\n\tCode *string `mandatory:\"true\" json:\"code\"`\n\n\tMessage *string `mandatory:\"true\" json:\"message\"`\n\n\tTimestamp *common.SDKTime `mandatory:\"true\" json:\"timestamp\"`\n}\n\n\n\nfunc (m WorkRequestError) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package armsql_test\n\nimport (\n\t\"context\"\n\t\"log\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azcore/to\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/sql/armsql\"\n)\n\n\nfunc ExampleDataMaskingPoliciesClient_CreateOrUpdate() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armsql.NewDataMaskingPoliciesClient(\"\", cred, nil)\n\tres, err := client.CreateOrUpdate(ctx,\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\tarmsql.DataMaskingPolicy{\n\t\t\tProperties: &armsql.DataMaskingPolicyProperties{\n\t\t\t\tDataMaskingState: armsql.DataMaskingStateEnabled.ToPtr(),\n\t\t\t\tExemptPrincipals: to.StringPtr(\"\"),\n\t\t\t},\n\t\t},\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Response result: %#v\\n\", res.DataMaskingPoliciesClientCreateOrUpdateResult)\n}\n\n\n\n\nfunc ExampleDataMaskingPoliciesClient_Get() ", "output": "{\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armsql.NewDataMaskingPoliciesClient(\"\", cred, nil)\n\tres, err := client.Get(ctx,\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Response result: %#v\\n\", res.DataMaskingPoliciesClientGetResult)\n}"} {"input": "package airplane_mode\n\nfunc getRadioModule(key RadioType) BaseRadioModule {\n\tvar module BaseRadioModule\n\tswitch key {\n\tcase BluetoothRadioType:\n\t\tmodule = &BluetoothRadio{GeneralRadioModule{typ: BluetoothRadioType, name: \"bluetooth\"}}\n\tcase WlanRadioType:\n\t\tmodule = &WlanRadio{GeneralRadioModule{typ: WlanRadioType, name: \"wlan\"}}\n\tcase AllRadioType:\n\t\tmodule = &AllRadio{GeneralRadioModule{typ: AllRadioType, name: \"all\"}}\n\tdefault:\n\t\tpanic(\"radio type not exist\")\n\t}\n\treturn module\n}\n\ntype GeneralRadioModule struct {\n\ttyp RadioType\n\tname string\n}\n\nfunc (Op *GeneralRadioModule) Type() RadioType {\n\treturn Op.typ\n}\n\nfunc (Op *GeneralRadioModule) Module() string {\n\treturn Op.name\n}\n\nfunc (Op *GeneralRadioModule) Len() int {\n\tstate, err := rfkillState(Op.typ)\n\tif err != nil {\n\t\tlogger.Warningf(\"check rfkill blocked state failed, err: %v\", err)\n\t\tstate.count = 0\n\t}\n\treturn state.count\n}\n\nfunc (Op *GeneralRadioModule) Block() error {\n\treturn rfkillAction(Op.typ, BlockRadioAction)\n}\n\nfunc (Op *GeneralRadioModule) Unblock() error {\n\treturn rfkillAction(Op.typ, UnblockRadioAction)\n}\n\n\n\n\ntype BluetoothRadio struct {\n\tGeneralRadioModule\n}\n\n\ntype WlanRadio struct {\n\tGeneralRadioModule\n}\n\n\ntype AllRadio struct {\n\tGeneralRadioModule\n}\n\nfunc (Op *GeneralRadioModule) IsBlocked() bool ", "output": "{\n\tstate, err := rfkillState(Op.typ)\n\tif err != nil {\n\t\tlogger.Warningf(\"check rfkill blocked state failed, err: %v\", err)\n\t\tstate.blocked = false\n\t}\n\treturn state.blocked\n}"} {"input": "package tests\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n)\n\nfunc TestTransactions(t *testing.T) {\n\terr := RunTransactionTests(filepath.Join(transactionTestDir, \"ttTransactionTest.json\"), TransSkipTests)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\n\nfunc Test10MBtx(t *testing.T) {\n\terr := RunTransactionTests(filepath.Join(transactionTestDir, \"tt10mbDataField.json\"), TransSkipTests)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestWrongRLPTransactions(t *testing.T) ", "output": "{\n\terr := RunTransactionTests(filepath.Join(transactionTestDir, \"ttWrongRLPTransaction.json\"), TransSkipTests)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package goxpath\n\nimport (\n\txml \"encoding/xml\"\n)\n\ntype FuncOpts func(*Opts)\n\nfunc MustParse(_ string) XPathExec {\n\treturn XPathExec{}\n}\n\ntype Opts struct {\n\tNS map[string]string\n\tFuncs map[xml.Name]interface{}\n\tVars map[string]interface{}\n}\n\nfunc Parse(_ string) (XPathExec, error) {\n\treturn XPathExec{}, nil\n}\n\nfunc ParseExec(_ string, _ interface{}, _ ...FuncOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\ntype XPathExec struct{}\n\nfunc (_ XPathExec) Exec(_ interface{}, _ ...FuncOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\nfunc (_ XPathExec) ExecBool(_ interface{}, _ ...FuncOpts) (bool, error) {\n\treturn false, nil\n}\n\n\n\nfunc (_ XPathExec) ExecNum(_ interface{}, _ ...FuncOpts) (float64, error) {\n\treturn 0, nil\n}\n\nfunc (_ XPathExec) MustExec(_ interface{}, _ ...FuncOpts) interface{} {\n\treturn nil\n}\n\nfunc (_ XPathExec) ExecNode(_ interface{}, _ ...FuncOpts) (interface{}, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package simpleacl\n\nimport \"github.com/youtube/vitess/go/vt/tableacl/acl\"\n\nvar allAcl SimpleAcl\n\nconst all = \"*\"\n\n\ntype SimpleAcl map[string]bool\n\n\n\n\n\ntype Factory struct{}\n\n\nfunc (factory *Factory) New(entries []string) (acl.ACL, error) {\n\tacl := SimpleAcl(map[string]bool{})\n\tfor _, e := range entries {\n\t\tacl[e] = true\n\t}\n\treturn acl, nil\n}\n\n\nfunc (factory *Factory) All() acl.ACL {\n\tif allAcl == nil {\n\t\tallAcl = SimpleAcl(map[string]bool{all: true})\n\t}\n\treturn allAcl\n}\n\n\nfunc (factory *Factory) AllString() string {\n\treturn all\n}\n\n\nvar _ (acl.ACL) = (*SimpleAcl)(nil)\n\n\nvar _ (acl.Factory) = (*Factory)(nil)\n\nfunc (sacl SimpleAcl) IsMember(principal string) bool ", "output": "{\n\treturn sacl[principal] || sacl[all]\n}"} {"input": "package lang\n\nimport \"math\"\nimport \"gojvm/native\"\nimport \"gojvm/rtda\"\n\nconst jlDouble = \"java/lang/Double\"\n\nfunc init() {\n\tnative.Register(jlDouble, \"doubleToRawLongBits\", \"(D)J\", doubleToRawLongBits)\n\tnative.Register(jlDouble, \"longBitsToDouble\", \"(J)D\", longBitsToDouble)\n}\n\n\n\nfunc doubleToRawLongBits(frame *rtda.Frame) {\n\tvalue := frame.LocalVars().GetDouble(0)\n\tbits := math.Float64bits(value) \n\tframe.OperandStack().PushLong(int64(bits))\n}\n\n\n\n\n\nfunc longBitsToDouble(frame *rtda.Frame) ", "output": "{\n\tbits := frame.LocalVars().GetLong(0)\n\tvalue := math.Float64frombits(uint64(bits)) \n\tframe.OperandStack().PushDouble(value)\n}"} {"input": "package user\n\nimport (\n\t\"context\"\n\t\"flag\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/ssoadmin\"\n)\n\ntype rm struct {\n\t*flags.ClientFlag\n}\n\nfunc init() {\n\tcli.Register(\"sso.user.rm\", &rm{})\n}\n\nfunc (cmd *rm) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.ClientFlag, ctx = flags.NewClientFlag(ctx)\n\tcmd.ClientFlag.Register(ctx, f)\n}\n\n\n\nfunc (cmd *rm) Description() string {\n\treturn `Remove SSO users.\n\nExamples:\n govc sso.user.rm NAME`\n}\n\nfunc (cmd *rm) Run(ctx context.Context, f *flag.FlagSet) error {\n\treturn withClient(ctx, cmd.ClientFlag, func(c *ssoadmin.Client) error {\n\t\treturn c.DeletePrincipal(ctx, f.Arg(0))\n\t})\n}\n\nfunc (cmd *rm) Usage() string ", "output": "{\n\treturn \"NAME\"\n}"} {"input": "package gws\n\nimport (\n\t\"crypto/rand\"\n\t\"fmt\"\n\n\t\"github.com/graphql-go/graphql\"\n\t\"github.com/vaniila/hyper/cache\"\n\t\"github.com/vaniila/hyper/logger\"\n\t\"github.com/vaniila/hyper/message\"\n)\n\n\ntype Option func(*Options)\n\n\ntype Options struct {\n\n\tID string\n\n\tTopic []byte\n\n\tSchema graphql.Schema\n\n\tCache cache.Service\n\n\tMessage message.Service\n\n\tLogger logger.Service\n}\n\n\n\nfunc newOptions(opts ...Option) Options {\n\topt := Options{\n\t\tID: newID(),\n\t}\n\tfor _, o := range opts {\n\t\to(&opt)\n\t}\n\tif len(opt.Topic) == 0 || opt.Topic == nil {\n\t\topt.Topic = []byte(\"graphql-ws\")\n\t}\n\treturn opt\n}\n\n\nfunc ID(s string) Option {\n\treturn func(o *Options) {\n\t\to.ID = s\n\t}\n}\n\n\nfunc Topic(s string) Option {\n\treturn func(o *Options) {\n\t\to.Topic = []byte(s)\n\t}\n}\n\n\nfunc Schema(v graphql.Schema) Option {\n\treturn func(o *Options) {\n\t\to.Schema = v\n\t}\n}\n\n\nfunc Cache(v cache.Service) Option {\n\treturn func(o *Options) {\n\t\to.Cache = v\n\t}\n}\n\n\nfunc Message(m message.Service) Option {\n\treturn func(o *Options) {\n\t\to.Message = m\n\t}\n}\n\n\nfunc Logger(l logger.Service) Option {\n\treturn func(o *Options) {\n\t\to.Logger = l\n\t}\n}\n\nfunc newID() string ", "output": "{\n\tb := new([16]byte)\n\trand.Read(b[:])\n\tb[8] = (b[8] | 0x40) & 0x7F\n\tb[6] = (b[6] & 0xF) | (4 << 4)\n\treturn fmt.Sprintf(\"%x-%x-%x-%x-%x\", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])\n}"} {"input": "package target\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"testing\"\n)\n\nvar (\n\twrkdir string\n)\n\n\n\ntype badWriter struct {\n}\n\nfunc (bw badWriter) Write(p []byte) (n int, err error) {\n\treturn 0, fmt.Errorf(\"bad\")\n}\n\nfunc TestNewMake(t *testing.T) {\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\t_, err := NewMake(tc)\n\tok(t, err)\n}\n\nfunc TestMakeRun(t *testing.T) {\n\ttc, tcW, _ := createTestConfigs(t, nil, nil)\n\tm, _ := NewMake(tc)\n\terr := m.Run(\"ron:prep\")\n\tok(t, err)\n\twant := \"hello\\nprep1\\nprep2\\nprep3\\nprep4\\ngoodbye\\n\"\n\tequals(t, want, tcW.String())\n}\n\nfunc TestMakeRunErr(t *testing.T) {\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\tm, _ := NewMake(tc)\n\terr := m.Run(\"err\")\n\tif err == nil {\n\t\tt.Fatal(\"expected target not found\")\n\t}\n}\n\nfunc TestMakeRunNoTarget(t *testing.T) {\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\tm, _ := NewMake(tc)\n\terr := m.Run(\"prop\")\n\tif err == nil {\n\t\tt.Fatal(\"expected target not found\")\n\t}\n}\n\nfunc init() ", "output": "{\n\tlog.SetOutput(ioutil.Discard)\n\twrkdir, _ = os.Getwd()\n}"} {"input": "package version\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestVersion(t *testing.T) ", "output": "{\n\tvar tests = []struct {\n\t\tname string\n\t\tb [2]byte\n\t}{\n\t\t{\n\t\t\tname: \"V14\",\n\t\t\tb: [2]byte{0x0, 0x0e},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tb := Bytes()\n\t\t\tif want, got := tt.b, b; want != got {\n\t\t\t\tt.Fatalf(\"unexpected Version bytes:\\n- want: [%#v]\\n- got: [%#v]\", want, got)\n\t\t\t}\n\t\t})\n\t}\n}"} {"input": "package netx\n\nimport (\n\t\"io\"\n\n\t\"github.com/simia-tech/netx/value\"\n)\n\ntype multicast struct {\n\tlistener io.ReadCloser\n\tconn io.WriteCloser\n}\n\n\n\n\n\nfunc (m *multicast) Read(buffer []byte) (int, error) {\n\treturn m.listener.Read(buffer)\n}\n\nfunc (m *multicast) Write(buffer []byte) (int, error) {\n\treturn m.conn.Write(buffer)\n}\n\nfunc (m *multicast) Close() error {\n\tif err := m.listener.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := m.conn.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc ListenAndDialMulticast(network, readAddress, writeAddress string, options ...value.Option) (io.ReadWriteCloser, error) ", "output": "{\n\tlistener, err := ListenMulticast(network, readAddress, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn, err := DialMulticast(network, writeAddress, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &multicast{listener: listener, conn: conn}, nil\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n)\n\ntype BuiltInClass struct {\n\tname Instance\n\tsupers []Class\n\tslots []Instance\n}\n\nfunc NewBuiltInClass(name string, super Class, slots ...string) Class {\n\tslotNames := []Instance{}\n\tfor _, slot := range slots {\n\t\tslotNames = append(slotNames, NewSymbol(slot))\n\t}\n\treturn BuiltInClass{NewSymbol(name), []Class{super}, slotNames}\n}\n\n\n\nfunc (p BuiltInClass) Slots() []Instance {\n\treturn p.slots\n}\n\nfunc (p BuiltInClass) Initform(arg Instance) (v Instance, ok bool) {\n\treturn nil, false\n}\n\nfunc (p BuiltInClass) Initarg(arg Instance) (v Instance, ok bool) {\n\treturn arg, true\n}\n\nfunc (BuiltInClass) Class() Class {\n\treturn BuiltInClassClass\n}\n\nfunc (p BuiltInClass) String() string {\n\treturn fmt.Sprint(p.name)\n}\n\nfunc (p BuiltInClass) Supers() []Class ", "output": "{\n\treturn p.supers\n}"} {"input": "package manifestparser\n\nimport (\n\t\"errors\"\n\t\"io/ioutil\"\n\n\tyaml \"gopkg.in/yaml.v2\"\n)\n\ntype Application struct {\n\tName string `yaml:\"name\"`\n}\n\ntype Parser struct {\n\tPathToManifest string\n\n\tApplications []Application\n\n\trawManifest []byte\n}\n\nfunc NewParser() *Parser {\n\treturn new(Parser)\n}\n\n\n\nfunc (parser Parser) AppNames() []string {\n\tvar names []string\n\tfor _, app := range parser.Applications {\n\t\tnames = append(names, app.Name)\n\t}\n\treturn names\n}\n\nfunc (parser Parser) RawManifest(_ string) ([]byte, error) {\n\treturn parser.rawManifest, nil\n}\n\nfunc (parser *Parser) Parse(manifestPath string) error ", "output": "{\n\tbytes, err := ioutil.ReadFile(manifestPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparser.rawManifest = bytes\n\n\tvar raw struct {\n\t\tApplications []Application `yaml:\"applications\"`\n\t}\n\n\terr = yaml.Unmarshal(bytes, &raw)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tparser.Applications = raw.Applications\n\n\tif len(parser.Applications) == 0 {\n\t\treturn errors.New(\"must have at least one application\")\n\t}\n\n\tfor _, application := range parser.Applications {\n\t\tif application.Name == \"\" {\n\t\t\treturn errors.New(\"Found an application with no name specified\")\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package iso20022\n\n\ntype PaymentTransaction17 struct {\n\n\tSettlementAmount *ActiveCurrencyAndAmount `xml:\"SttlmAmt,omitempty\"`\n\n\tSettlementDate *ISODate `xml:\"SttlmDt,omitempty\"`\n\n\tPaymentInstrument *PaymentInstrument9Choice `xml:\"PmtInstrm,omitempty\"`\n}\n\nfunc (p *PaymentTransaction17) SetSettlementAmount(value, currency string) {\n\tp.SettlementAmount = NewActiveCurrencyAndAmount(value, currency)\n}\n\nfunc (p *PaymentTransaction17) SetSettlementDate(value string) {\n\tp.SettlementDate = (*ISODate)(&value)\n}\n\n\n\nfunc (p *PaymentTransaction17) AddPaymentInstrument() *PaymentInstrument9Choice ", "output": "{\n\tp.PaymentInstrument = new(PaymentInstrument9Choice)\n\treturn p.PaymentInstrument\n}"} {"input": "package premailer\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestFromFileNotFound(t *testing.T) {\n\tp, err := NewPremailerFromFile(\"data/blablabla.html\", nil)\n\tassert.NotNil(t, err)\n\tassert.Nil(t, p)\n}\n\nfunc TestBasicHTMLFromFile(t *testing.T) ", "output": "{\n\tp, err := NewPremailerFromFile(\"data/markup_test.html\", nil)\n\tassert.Nil(t, err)\n\tresultHTML, err := p.Transform()\n\tassert.Nil(t, err)\n\n\tassert.Contains(t, resultHTML, \"

Hi!

\")\n\tassert.Contains(t, resultHTML, \"

There

\")\n\tassert.Contains(t, resultHTML, \"

Hello

\")\n\tassert.Contains(t, resultHTML, \"

Yes!

\")\n\tassert.Contains(t, resultHTML, \"
Green color
\")\n}"} {"input": "package s0035\n\n\n\n\n\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com/peterstace/project-euler/number\"\n)\n\n\n\n\nfunc Parameterised(n int) int {\n\n\tisPrime := number.PrimeSieve(n)\n\tcount := 0\n\n\tfor c := range isPrime {\n\t\tif !isPrime[c] {\n\t\t\tcontinue\n\t\t}\n\n\t\tp := fmt.Sprintf(\"%d\", c)\n\t\tcircular := true\n\t\tfor i := 1; i < len(p); i++ {\n\t\t\tp = p[1:] + p[0:1]\n\t\t\trotated, err := strconv.Atoi(p)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tif !isPrime[rotated] {\n\t\t\t\tcircular = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif circular {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}\n\nfunc Solution() interface{} ", "output": "{\n\treturn Parameterised(1000000)\n}"} {"input": "package driver\n\nimport (\n\t\"github.com/Azure/azure-docker-extension/pkg/executil\"\n)\n\ntype ubuntuBaseDriver struct{}\n\n\n\nfunc (u ubuntuBaseDriver) UninstallDocker() error {\n\tif err := executil.ExecPipe(\"apt-get\", \"-qqy\", \"purge\", \"docker-engine\"); err != nil {\n\t\treturn err\n\t}\n\treturn executil.ExecPipe(\"apt-get\", \"-qqy\", \"autoremove\")\n}\n\nfunc (u ubuntuBaseDriver) DockerComposeDir() string { return \"/usr/local/bin\" }\n\nfunc (u ubuntuBaseDriver) InstallDocker() error ", "output": "{\n\treturn executil.ExecPipe(\"/bin/sh\", \"-c\", \"wget -qO- https://get.docker.com/ | sh\")\n}"} {"input": "package config\n\nimport (\n\t\"github.com/go-kit/kit/endpoint\"\n\thttptransport \"github.com/go-kit/kit/transport/http\"\n\t\"github.com/gorilla/mux\"\n\t\"github.com/micromdm/micromdm/pkg/httputil\"\n)\n\ntype Endpoints struct {\n\tSavePushCertificateEndpoint endpoint.Endpoint\n\tGetPushCertificateEndpoint endpoint.Endpoint\n\tApplyDEPTokensEndpoint endpoint.Endpoint\n\tGetDEPTokensEndpoint endpoint.Endpoint\n}\n\n\n\nfunc RegisterHTTPHandlers(r *mux.Router, e Endpoints, options ...httptransport.ServerOption) {\n\n\tr.Methods(\"PUT\").Path(\"/v1/config/certificate\").Handler(httptransport.NewServer(\n\t\te.SavePushCertificateEndpoint,\n\t\tdecodeSavePushCertificateRequest,\n\t\thttputil.EncodeJSONResponse,\n\t\toptions...,\n\t))\n\n\tr.Methods(\"GET\").Path(\"/v1/config/certificate\").Handler(httptransport.NewServer(\n\t\te.GetPushCertificateEndpoint,\n\t\tdecodeGetPushCertificateRequest,\n\t\thttputil.EncodeJSONResponse,\n\t\toptions...,\n\t))\n\n\tr.Methods(\"PUT\").Path(\"/v1/dep-tokens\").Handler(httptransport.NewServer(\n\t\te.ApplyDEPTokensEndpoint,\n\t\tdecodeApplyDEPTokensRequest,\n\t\thttputil.EncodeJSONResponse,\n\t\toptions...,\n\t))\n\n\tr.Methods(\"GET\").Path(\"/v1/dep-tokens\").Handler(httptransport.NewServer(\n\t\te.GetDEPTokensEndpoint,\n\t\tdecodeGetDEPTokensRequest,\n\t\thttputil.EncodeJSONResponse,\n\t\toptions...,\n\t))\n}\n\nfunc MakeServerEndpoints(s Service, outer endpoint.Middleware, others ...endpoint.Middleware) Endpoints ", "output": "{\n\treturn Endpoints{\n\t\tSavePushCertificateEndpoint: endpoint.Chain(outer, others...)(MakeSavePushCertificateEndpoint(s)),\n\t\tGetPushCertificateEndpoint: endpoint.Chain(outer, others...)(MakeGetPushCertificateEndpoint(s)),\n\t\tApplyDEPTokensEndpoint: endpoint.Chain(outer, others...)(MakeApplyDEPTokensEndpoint(s)),\n\t\tGetDEPTokensEndpoint: endpoint.Chain(outer, others...)(MakeGetDEPTokensEndpoint(s)),\n\t}\n}"} {"input": "package selinux\n\n\nfunc SELinuxEnabled() bool {\n\treturn false\n}\n\n\ntype realSELinuxRunner struct{}\n\nvar _ SELinuxRunner = &realSELinuxRunner{}\n\n\n\n\nfunc SetFileLabel(path string, label string) error {\n\treturn nil\n}\n\nfunc (_ *realSELinuxRunner) Getfilecon(path string) (string, error) ", "output": "{\n\treturn \"\", nil\n}"} {"input": "package incoming\n\nimport (\n\t\"github.com/pkg/errors\"\n)\n\ntype ignorableErr struct {\n\terror\n}\n\nfunc (e ignorableErr) Ignorable() bool {\n\treturn true\n}\n\n\n\nfunc (m *RuleMap) Get(name string) (*Rule, error) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tif m.rules == nil {\n\t\treturn nil, wrapIgnorable(errors.New(\"rule not found: '\" + name + \"'\"))\n\t}\n\n\tr, ok := m.rules[name]\n\tif !ok {\n\t\treturn nil, wrapIgnorable(errors.New(\"rule not found: '\" + name + \"'\"))\n\t}\n\treturn r, nil\n}\n\nfunc (m *RuleMap) Set(name string, r *Rule) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tif m.rules == nil {\n\t\tm.rules = make(map[string]*Rule)\n\t}\n\n\tm.rules[name] = r\n}\n\nfunc (r Rule) Disabled() bool {\n\treturn false\n}\n\nfunc (r Rule) AggregationWindow() int64 {\n\treturn 300\n}\n\nfunc wrapIgnorable(err error) error ", "output": "{\n\treturn ignorableErr{error: err}\n}"} {"input": "package builtin\n\nconst bluetoothControlSummary = `allows managing the kernel bluetooth stack`\n\nconst bluetoothControlBaseDeclarationSlots = `\n bluetooth-control:\n allow-installation:\n slot-snap-type:\n - core\n deny-auto-connection: true\n`\n\nconst bluetoothControlConnectedPlugAppArmor = `\n# Description: Allow managing the kernel side Bluetooth stack. Reserved\n# because this gives privileged access to the system.\n\n network bluetooth,\n # For crypto functionality the kernel offers\n network alg,\n\n capability net_admin,\n\n # File accesses\n /sys/bus/usb/drivers/btusb/ r,\n /sys/bus/usb/drivers/btusb/** r,\n /sys/module/btusb/ r,\n /sys/module/btusb/** r,\n /sys/class/bluetooth/ r,\n /sys/devices/**/bluetooth/ rw,\n /sys/devices/**/bluetooth/** rw,\n\n # Requires CONFIG_BT_VHCI to be loaded\n /dev/vhci rw,\n`\n\nconst bluetoothControlConnectedPlugSecComp = `\n# Description: Allow managing the kernel side Bluetooth stack. Reserved\n# because this gives privileged access to the system.\nbind\n`\n\nvar bluetoothControlConnectedPlugUDev = []string{`SUBSYSTEM==\"bluetooth\"`}\n\n\n\nfunc init() ", "output": "{\n\tregisterIface(&commonInterface{\n\t\tname: \"bluetooth-control\",\n\t\tsummary: bluetoothControlSummary,\n\t\timplicitOnCore: true,\n\t\timplicitOnClassic: true,\n\t\tbaseDeclarationSlots: bluetoothControlBaseDeclarationSlots,\n\t\tconnectedPlugAppArmor: bluetoothControlConnectedPlugAppArmor,\n\t\tconnectedPlugSecComp: bluetoothControlConnectedPlugSecComp,\n\t\tconnectedPlugUDev: bluetoothControlConnectedPlugUDev,\n\t\treservedForOS: true,\n\t})\n}"} {"input": "package models\n\nimport (\n\t\"time\"\n)\n\n\nconst (\n\tVolumePaper = \"paperbook\"\n\tVolumeElectro = \"ebook\"\n\tVolumeAudio = \"audiobook\"\n)\n\n\nfunc GetVolumes() []string {\n\tvolumes := []string{VolumeAudio, VolumeElectro, VolumePaper}\n\treturn volumes\n}\n\n\nfunc CheckVolume(volume string) bool {\n\tswitch volume {\n\tcase VolumePaper:\n\tcase VolumeElectro:\n\tcase VolumeAudio:\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}\n\n\n\n\n\ntype Volume struct {\n\tID int32 `reform:\"id,pk\"`\n\tBookID int32 `reform:\"book_id\"`\n\tType string `reform:\"type\"`\n\tCreatedAt time.Time `reform:\"created_at\"`\n\tUpdatedAt time.Time `reform:\"updated_at\"`\n}\n\n\n\n\n\nfunc (v *Volume) BeforeUpdate() error {\n\tv.UpdatedAt = time.Now().UTC().Truncate(time.Second)\n\treturn nil\n}\n\nfunc (v *Volume) BeforeInsert() error ", "output": "{\n\tv.CreatedAt = time.Now().UTC().Truncate(time.Second)\n\tv.UpdatedAt = v.CreatedAt\n\treturn nil\n}"} {"input": "package mock\n\nimport (\n\t\"github.com/fkmhrk/OpenInvoice/v1/model/env\"\n)\n\ntype EnvDAO struct {\n\tCreateResult env.Env\n\tGetResult env.Env\n\tGetListResult []*env.Env\n\tSaveResult error\n\tUpdateResult env.Env\n\tDeleteResult env.Env\n}\n\nfunc (d *EnvDAO) Create(key, value string) (env.Env, error) {\n\treturn d.CreateResult, nil\n}\n\nfunc (d *EnvDAO) Get(key string) (env.Env, error) {\n\treturn d.GetResult, nil\n}\n\nfunc (d *EnvDAO) GetList() ([]*env.Env, error) {\n\treturn d.GetListResult, nil\n}\n\nfunc (d *EnvDAO) Save(list []*env.Env) error {\n\treturn d.SaveResult\n}\n\n\n\nfunc (d *EnvDAO) Delete(key string) (env.Env, error) {\n\treturn d.DeleteResult, nil\n}\n\nfunc (d *EnvDAO) Update(key, value string) (env.Env, error) ", "output": "{\n\treturn d.UpdateResult, nil\n}"} {"input": "package logger\n\n\n\ntype options struct {\n\tvalues map[string][]OptionItem\n}\n\n\ntype Option struct {\n\tApply func(op *options)\n}\n\n\nfunc BackendOption(name string, level string, settings map[string]interface{}) Option {\n\treturn Option{func(op *options) {\n\t\tvals := make([]OptionItem, 0)\n\t\tvals = append(vals, OptionItem{\"level\", level})\n\n\t\tif len(settings) > 0 {\n\t\t\tfor k, v := range settings {\n\t\t\t\tvals = append(vals, OptionItem{k, v})\n\t\t\t}\n\t\t}\n\n\t\top.values[name] = vals\n\t}}\n}\n\n\nfunc SweeperOption(name string, duration int, settings map[string]interface{}) Option {\n\treturn Option{func(op *options) {\n\t\tvals := make([]OptionItem, 0)\n\t\tvals = append(vals, OptionItem{\"duration\", duration})\n\n\t\tif len(settings) > 0 {\n\t\t\tfor k, v := range settings {\n\t\t\t\tvals = append(vals, OptionItem{k, v})\n\t\t\t}\n\t\t}\n\n\t\top.values[name] = vals\n\t}}\n}\n\n\n\n\n\ntype OptionItem struct {\n\tfield string\n\tval interface{}\n}\n\n\nfunc (o *OptionItem) Field() string {\n\treturn o.field\n}\n\n\nfunc (o *OptionItem) Int() int {\n\tif o.val == nil {\n\t\treturn 0\n\t}\n\n\treturn o.val.(int)\n}\n\n\nfunc (o *OptionItem) String() string {\n\tif o.val == nil {\n\t\treturn \"\"\n\t}\n\n\treturn o.val.(string)\n}\n\n\nfunc (o *OptionItem) Raw() interface{} {\n\treturn o.val\n}\n\nfunc GetterOption(name string, settings map[string]interface{}) Option ", "output": "{\n\treturn Option{func(op *options) {\n\t\tvals := make([]OptionItem, 0)\n\t\tif len(settings) > 0 {\n\t\t\tfor k, v := range settings {\n\t\t\t\tvals = append(vals, OptionItem{k, v})\n\t\t\t}\n\t\t}\n\n\t\top.values[name] = vals\n\t}}\n}"} {"input": "package graphite\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n)\n\nfunc createFindMetricsTestServer() *httptest.Server {\n\treturn httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, `[\n\t\t\t{\"text\": \"one\", \"expandable\": 1, \"leaf\": 0, \"id\": \"cluster.one\", \"allowChildren\": 1},\n\t\t\t{\"text\": \"two\", \"expandable\": 1, \"leaf\": 0, \"id\": \"cluster.two\", \"allowChildren\": 1}]`)\n\t}))\n}\n\nfunc ExampleClient_FindMetrics() {\n\tts := createFindMetricsTestServer()\n\tdefer ts.Close()\n\n\tclient, _ := NewFromString(ts.URL)\n\tres, _ := client.FindMetrics(\n\t\tFindMetricRequest{\n\t\t\tQuery: \"cluster.*\",\n\t\t},\n\t)\n\tfmt.Printf(\"%+v\", res)\n\n}\n\n\n\nfunc ExampleClient_ExpandMetrics() {\n\tts := createExpandMetricsTestServer()\n\tdefer ts.Close()\n\n\tclient, _ := NewFromString(ts.URL)\n\tres, _ := client.ExpandMetrics(\n\t\tExpandMetricRequest{\n\t\t\tQuery: \"cluster.*\",\n\t\t},\n\t)\n\tfmt.Printf(\"%+v\", res)\n}\n\nfunc createExpandMetricsTestServer() *httptest.Server ", "output": "{\n\treturn httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, \"{\\\"results\\\": [\\\"cluster.one\\\", \\\"cluster.two\\\"]}\")\n\t}))\n}"} {"input": "package archive\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc TestArchiveStaff(t *testing.T) {\n\tconvey.Convey(\"Staff\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t\tmid = int64(27515258)\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\taids, err := d.Staff(c, mid)\n\t\t\tctx.Convey(\"Then err should be nil.aids should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t\tctx.So(len(aids), convey.ShouldBeGreaterThanOrEqualTo, 0)\n\t\t\t})\n\t\t})\n\t})\n}\n\n\n\nfunc TestArchiveStaffAid(t *testing.T) {\n\tconvey.Convey(\"StaffAid\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t\taid = int64(10110188)\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\tmids, err := d.StaffAid(c, aid)\n\t\t\tctx.Convey(\"Then err should be nil.mids should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t\tctx.So(mids, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestArchiveStaffs(t *testing.T) ", "output": "{\n\tconvey.Convey(\"Staffs\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t\tmids = []int64{27515258}\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\taidm, err := d.Staffs(c, mids)\n\t\t\tctx.Convey(\"Then err should be nil.aidm should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t\tctx.So(aidm, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package server\n\nimport (\n\t\"github.com/smancke/guble/guble\"\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype WebServer struct {\n\tserver *http.Server\n\tln net.Listener\n\tmux *http.ServeMux\n\taddr string\n}\n\nfunc NewWebServer(addr string) *WebServer {\n\treturn &WebServer{\n\t\tmux: http.NewServeMux(),\n\t\taddr: addr,\n\t}\n}\n\n\n\nfunc (ws *WebServer) Stop() error {\n\tif ws.ln != nil {\n\t\treturn ws.ln.Close()\n\t}\n\treturn nil\n}\n\nfunc (ws *WebServer) GetAddr() string {\n\tif ws.ln == nil {\n\t\treturn \"::unknown::\"\n\t}\n\treturn ws.ln.Addr().String()\n}\n\n\nfunc extractUserId(requestUri string) string {\n\turiParts := strings.SplitN(requestUri, \"/user/\", 2)\n\tif len(uriParts) != 2 {\n\t\treturn \"\"\n\t}\n\treturn uriParts[1]\n}\n\n\n\n\n\n\ntype tcpKeepAliveListener struct {\n\t*net.TCPListener\n}\n\nfunc (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {\n\ttc, err := ln.AcceptTCP()\n\tif err != nil {\n\t\treturn\n\t}\n\ttc.SetKeepAlive(true)\n\ttc.SetKeepAlivePeriod(10 * time.Second)\n\treturn tc, nil\n}\n\nfunc (ws *WebServer) Start() error ", "output": "{\n\tguble.Info(\"starting up at %v\", ws.addr)\n\tws.server = &http.Server{Addr: ws.addr, Handler: ws.mux}\n\tvar err error\n\tws.ln, err = net.Listen(\"tcp\", ws.addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\terr = ws.server.Serve(tcpKeepAliveListener{ws.ln.(*net.TCPListener)})\n\n\t\tif err != nil && !strings.HasSuffix(err.Error(), \"use of closed network connection\") {\n\t\t\tguble.Err(\"ListenAndServe %s\", err.Error())\n\t\t}\n\t\tguble.Info(\"http server stopped\")\n\t}()\n\treturn nil\n}"} {"input": "package world\n\nimport (\n\t\"encoding/gob\"\n\t\"math/big\"\n\t\"reflect\"\n\t\"time\"\n)\n\nvar registeredIdentifierObject = make(map[string]reflect.Type)\nvar registeredObjectIdentifier = make(map[reflect.Type]string)\n\nfunc Register(identifier string, obj ObjectLike) {\n\tif identifier == \"\" {\n\t\tpanic(\"attempt to register an empty identifier\")\n\t}\n\tif obj == nil {\n\t\tpanic(\"attempt to register a nil object type\")\n\t}\n\n\tt := reflect.TypeOf(obj)\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\n\tif _, ok := registeredIdentifierObject[identifier]; ok {\n\t\tpanic(\"duplicate registration for object identifier \" + identifier)\n\t}\n\tif _, ok := registeredObjectIdentifier[t]; ok {\n\t\tpanic(\"duplicate registration for object type \" + t.Name())\n\t}\n\tregisteredObjectIdentifier[t] = identifier\n\tregisteredIdentifierObject[identifier] = t\n}\n\n\n\nfunc getObjectByIdentifier(identifier string) ObjectLike {\n\tt := registeredIdentifierObject[identifier]\n\tif t == nil {\n\t\tpanic(\"unregistered object identifier: \" + identifier)\n\t}\n\treturn reflect.New(t).Interface().(ObjectLike)\n}\n\nfunc init() {\n\tgob.Register(map[string]interface{}{})\n\tgob.Register([]interface{}{})\n\tgob.Register(time.Time{})\n\tgob.Register(&big.Int{})\n}\n\nfunc getObjectTypeIdentifier(obj ObjectLike) string ", "output": "{\n\tt := reflect.TypeOf(obj)\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\tidentifier := registeredObjectIdentifier[t]\n\tif identifier == \"\" {\n\t\tpanic(\"unregistered object type: \" + t.Name())\n\t}\n\treturn identifier\n}"} {"input": "package healthcareapis\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) BaseClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package core\n\nimport \"os\"\nimport \"fmt\"\n\nvar f *os.File\nvar watchdog = true\n\n\n\nfunc StopDog() {\n\treturn\n\tif watchdog {\n\t\twatchdog = false\n\t\tf.Close()\n\t}\n}\n\nfunc PetDog(){\n\treturn\n\tif watchdog {\n\t\tvar err error\n\t\t_, err = f.WriteString(\"X\")\n\t\tif err != nil {\n\t\t\tfmt.Println(\"PetDog Write Error:\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}\n\nfunc StartDog() ", "output": "{\n\treturn\n\twatchdog = false\n\treturn\n\tvar err error\n\tf, err = os.Create(\"/dev/watchdog\")\n\tif err != nil {\n\t\tfmt.Println(\"Watchdog Error:\", err)\n\t\tos.Exit(1)\n\t}\n\t_, err = f.WriteString(\"X\")\n\tif err != nil {\n\t\tfmt.Println(\"StartDog Write Error:\", err)\n\t\tos.Exit(1)\n\t}\n}"} {"input": "package options\n\n\ntype UpdateOptions struct {\n\tArrayFilters *ArrayFilters\n\n\tBypassDocumentValidation *bool\n\n\tCollation *Collation\n\n\tHint interface{}\n\n\tUpsert *bool\n}\n\n\nfunc Update() *UpdateOptions {\n\treturn &UpdateOptions{}\n}\n\n\nfunc (uo *UpdateOptions) SetArrayFilters(af ArrayFilters) *UpdateOptions {\n\tuo.ArrayFilters = &af\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetBypassDocumentValidation(b bool) *UpdateOptions {\n\tuo.BypassDocumentValidation = &b\n\treturn uo\n}\n\n\n\n\n\nfunc (uo *UpdateOptions) SetHint(h interface{}) *UpdateOptions {\n\tuo.Hint = h\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetUpsert(b bool) *UpdateOptions {\n\tuo.Upsert = &b\n\treturn uo\n}\n\n\nfunc MergeUpdateOptions(opts ...*UpdateOptions) *UpdateOptions {\n\tuOpts := Update()\n\tfor _, uo := range opts {\n\t\tif uo == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif uo.ArrayFilters != nil {\n\t\t\tuOpts.ArrayFilters = uo.ArrayFilters\n\t\t}\n\t\tif uo.BypassDocumentValidation != nil {\n\t\t\tuOpts.BypassDocumentValidation = uo.BypassDocumentValidation\n\t\t}\n\t\tif uo.Collation != nil {\n\t\t\tuOpts.Collation = uo.Collation\n\t\t}\n\t\tif uo.Hint != nil {\n\t\t\tuOpts.Hint = uo.Hint\n\t\t}\n\t\tif uo.Upsert != nil {\n\t\t\tuOpts.Upsert = uo.Upsert\n\t\t}\n\t}\n\n\treturn uOpts\n}\n\nfunc (uo *UpdateOptions) SetCollation(c *Collation) *UpdateOptions ", "output": "{\n\tuo.Collation = c\n\treturn uo\n}"} {"input": "package gen\n\nimport (\n\t\"regexp\"\n\t\"strings\"\n)\n\nfunc ReplaceSearchCallback(code []byte, modelName string) []byte {\n\trSearchCallback, _ := regexp.Compile(\"SearchCallback\")\n\tresult := rSearchCallback.ReplaceAll(code, []byte(\"SearchCallback\"+strings.Title(modelName)))\n\n\treturn result\n}\n\n\nfunc RemovePackage(code []byte) []byte {\n\trPackage, _ := regexp.Compile(\"package collection\")\n\tresult := rPackage.ReplaceAll(code, make([]byte, 0))\n\n\treturn result\n}\n\nfunc ReplaceGrizzlyId(code []byte, customType string) []byte {\n\tgICollections, _ := regexp.Compile(\"GrizzlyId\")\n\tresult := gICollections.ReplaceAll(code, []byte(strings.Title(customType)))\n\n\treturn result\n}\n\nfunc ReplaceImports(code []byte) []byte {\n\trICollections, _ := regexp.Compile(\"(import \\\"sort\\\")\")\n\tresult := rICollections.ReplaceAll(code, []byte(\"\"))\n\n\treturn result\n}\n\n\n\nfunc InjectImports(code []byte, imports []string) (result []byte) ", "output": "{\n\tresult = code[:]\n\n\tfor _, i := range imports {\n\t\tresult = append([]byte(\"\\nimport \\\"\"+i+\"\\\"\\n\"), code...)\n\t}\n\n\treturn result\n}"} {"input": "package builders\n\nimport (\n\t\"time\"\n\n\t\"github.com/docker/docker/api/types\"\n)\n\n\n\nfunc Container(name string, builders ...func(container *types.Container)) *types.Container {\n\tcontainer := &types.Container{\n\t\tID: \"container_id\",\n\t\tNames: []string{\"/\" + name},\n\t\tCommand: \"top\",\n\t\tImage: \"busybox:latest\",\n\t\tStatus: \"Up 1 second\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tfor _, builder := range builders {\n\t\tbuilder(container)\n\t}\n\n\treturn container\n}\n\n\nfunc WithLabel(key, value string) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tif c.Labels == nil {\n\t\t\tc.Labels = map[string]string{}\n\t\t}\n\t\tc.Labels[key] = value\n\t}\n}\n\n\nfunc WithName(name string) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tc.Names = append(c.Names, \"/\"+name)\n\t}\n}\n\n\nfunc WithPort(privateport, publicport uint16, builders ...func(*types.Port)) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tif c.Ports == nil {\n\t\t\tc.Ports = []types.Port{}\n\t\t}\n\t\tport := &types.Port{\n\t\t\tPrivatePort: privateport,\n\t\t\tPublicPort: publicport,\n\t\t}\n\t\tfor _, builder := range builders {\n\t\t\tbuilder(port)\n\t\t}\n\t\tc.Ports = append(c.Ports, *port)\n\t}\n}\n\n\nfunc IP(ip string) func(*types.Port) {\n\treturn func(p *types.Port) {\n\t\tp.IP = ip\n\t}\n}\n\n\n\n\n\nfunc UDP(p *types.Port) {\n\tp.Type = \"udp\"\n}\n\nfunc TCP(p *types.Port) ", "output": "{\n\tp.Type = \"tcp\"\n}"} {"input": "package cluster\n\nimport (\n\t\"common\"\n\t\"testing\"\n\t. \"launchpad.net/gocheck\"\n)\n\ntype UserSuite struct{}\n\nvar _ = Suite(&UserSuite{})\n\nvar root common.User\n\n\n\n\nfunc (self *UserSuite) SetUpSuite(c *C) {\n\tuser := &ClusterAdmin{CommonUser{\"root\", \"\", false, \"root\"}}\n\tc.Assert(user.ChangePassword(\"password\"), IsNil)\n\troot = user\n}\n\nfunc (self *UserSuite) TestProperties(c *C) {\n\tu := ClusterAdmin{CommonUser{Name: \"root\"}}\n\tc.Assert(u.IsClusterAdmin(), Equals, true)\n\tc.Assert(u.GetName(), Equals, \"root\")\n\thash, err := HashPassword(\"foobar\")\n\tc.Assert(err, IsNil)\n\tc.Assert(u.ChangePassword(string(hash)), IsNil)\n\tc.Assert(u.isValidPwd(\"foobar\"), Equals, true)\n\tc.Assert(u.isValidPwd(\"password\"), Equals, false)\n\n\tdbUser := DbUser{CommonUser{Name: \"db_user\"}, \"db\", nil, nil, true}\n\tc.Assert(dbUser.IsClusterAdmin(), Equals, false)\n\tc.Assert(dbUser.IsDbAdmin(\"db\"), Equals, true)\n\tc.Assert(dbUser.GetName(), Equals, \"db_user\")\n\thash, err = HashPassword(\"password\")\n\tc.Assert(err, IsNil)\n\tc.Assert(dbUser.ChangePassword(string(hash)), IsNil)\n\tc.Assert(dbUser.isValidPwd(\"password\"), Equals, true)\n\tc.Assert(dbUser.isValidPwd(\"password1\"), Equals, false)\n}\n\nfunc Test(t *testing.T) ", "output": "{\n\tTestingT(t)\n}"} {"input": "package sacloud\n\n\ntype ENoteClass string\n\nvar (\n\tNoteClassShell = ENoteClass(\"shell\")\n\tNoteClassYAMLCloudConfig = ENoteClass(\"yaml_cloud_config\")\n)\n\n\nvar ENoteClasses = []ENoteClass{NoteClassShell, NoteClassYAMLCloudConfig}\n\n\ntype propNoteClass struct {\n\tClass ENoteClass `json:\",omitempty\"` \n}\n\n\nfunc (p *propNoteClass) GetClass() ENoteClass {\n\treturn p.Class\n}\n\n\n\n\n\nfunc (p *propNoteClass) GetClassStr() string {\n\treturn string(p.Class)\n}\n\n\nfunc (p *propNoteClass) SetClassByStr(c string) {\n\tp.Class = ENoteClass(c)\n}\n\nfunc (p *propNoteClass) SetClass(c ENoteClass) ", "output": "{\n\tp.Class = c\n}"} {"input": "package task\n\nimport (\n\t\"github.com/c4s4/neon/neon/build\"\n\t\"reflect\"\n\tt \"time\"\n)\n\nfunc init() {\n\tbuild.AddTask(build.TaskDesc{\n\t\tName: \"time\",\n\t\tFunc: time,\n\t\tArgs: reflect.TypeOf(timeArgs{}),\n\t\tHelp: `Record duration to run a block of steps.\n\nArguments:\n\n- time: steps we want to measure execution duration (steps).\n- to: property to store duration in seconds as a float, if not set, duration is\n printed on the console (string, optional).\n\nExamples:\n\n # print duration to say hello\n - time:\n - print: 'Hello World!'\n to: duration\n - print: 'duration: ={duration}s'`,\n\t})\n}\n\ntype timeArgs struct {\n\tTime build.Steps `neon:\"steps\"`\n\tTo string `neon:\"optional\"`\n}\n\n\n\nfunc time(context *build.Context, args interface{}) error ", "output": "{\n\tparams := args.(timeArgs)\n\tstart := t.Now()\n\terr := params.Time.Run(context)\n\tif err != nil {\n\t\treturn err\n\t}\n\tduration := t.Now().Sub(start).Seconds()\n\tif params.To != \"\" {\n\t\tcontext.SetProperty(params.To, duration)\n\t} else {\n\t\tcontext.Message(\"Duration: %gs\", duration)\n\t}\n\treturn nil\n}"} {"input": "package pml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/pml\"\n)\n\n\n\nfunc TestEG_TopLevelSlideMarshalUnmarshal(t *testing.T) {\n\tv := pml.NewEG_TopLevelSlide()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := pml.NewEG_TopLevelSlide()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestEG_TopLevelSlideConstructor(t *testing.T) ", "output": "{\n\tv := pml.NewEG_TopLevelSlide()\n\tif v == nil {\n\t\tt.Errorf(\"pml.NewEG_TopLevelSlide must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed pml.EG_TopLevelSlide should validate: %s\", err)\n\t}\n}"} {"input": "package blockchain\n\n\n\n\n\n\n\n\ntype MemberProvisioningState string\n\nconst (\n\tDeleting MemberProvisioningState = \"Deleting\"\n\tFailed MemberProvisioningState = \"Failed\"\n\tNotSpecified MemberProvisioningState = \"NotSpecified\"\n\tStale MemberProvisioningState = \"Stale\"\n\tSucceeded MemberProvisioningState = \"Succeeded\"\n\tUpdating MemberProvisioningState = \"Updating\"\n)\n\n\n\n\n\ntype NameAvailabilityReason string\n\nconst (\n\tNameAvailabilityReasonAlreadyExists NameAvailabilityReason = \"AlreadyExists\"\n\tNameAvailabilityReasonInvalid NameAvailabilityReason = \"Invalid\"\n\tNameAvailabilityReasonNotSpecified NameAvailabilityReason = \"NotSpecified\"\n)\n\n\nfunc PossibleNameAvailabilityReasonValues() []NameAvailabilityReason {\n\treturn []NameAvailabilityReason{NameAvailabilityReasonAlreadyExists, NameAvailabilityReasonInvalid, NameAvailabilityReasonNotSpecified}\n}\n\n\ntype NodeProvisioningState string\n\nconst (\n\tNodeProvisioningStateDeleting NodeProvisioningState = \"Deleting\"\n\tNodeProvisioningStateFailed NodeProvisioningState = \"Failed\"\n\tNodeProvisioningStateNotSpecified NodeProvisioningState = \"NotSpecified\"\n\tNodeProvisioningStateSucceeded NodeProvisioningState = \"Succeeded\"\n\tNodeProvisioningStateUpdating NodeProvisioningState = \"Updating\"\n)\n\n\nfunc PossibleNodeProvisioningStateValues() []NodeProvisioningState {\n\treturn []NodeProvisioningState{NodeProvisioningStateDeleting, NodeProvisioningStateFailed, NodeProvisioningStateNotSpecified, NodeProvisioningStateSucceeded, NodeProvisioningStateUpdating}\n}\n\n\ntype Protocol string\n\nconst (\n\tProtocolCorda Protocol = \"Corda\"\n\tProtocolNotSpecified Protocol = \"NotSpecified\"\n\tProtocolParity Protocol = \"Parity\"\n\tProtocolQuorum Protocol = \"Quorum\"\n)\n\n\nfunc PossibleProtocolValues() []Protocol {\n\treturn []Protocol{ProtocolCorda, ProtocolNotSpecified, ProtocolParity, ProtocolQuorum}\n}\n\nfunc PossibleMemberProvisioningStateValues() []MemberProvisioningState ", "output": "{\n\treturn []MemberProvisioningState{Deleting, Failed, NotSpecified, Stale, Succeeded, Updating}\n}"} {"input": "package controllers\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\t\"github.com/astaxie/beego\"\n\t\"github.com/gorilla/websocket\"\n\t\"github.com/beego/samples/WebIM/models\"\n)\n\n\ntype WebSocketController struct {\n\tbaseController\n}\n\n\n\n\n\nfunc (this *WebSocketController) Join() {\n\tuname := this.GetString(\"uname\")\n\tif len(uname) == 0 {\n\t\tthis.Redirect(\"/\", 302)\n\t\treturn\n\t}\n\n\tws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)\n\tif _, ok := err.(websocket.HandshakeError); ok {\n\t\thttp.Error(this.Ctx.ResponseWriter, \"Not a websocket handshake\", 400)\n\t\treturn\n\t} else if err != nil {\n\t\tbeego.Error(\"Cannot setup WebSocket connection:\", err)\n\t\treturn\n\t}\n\n\tJoin(uname, ws)\n\tdefer Leave(uname)\n\n\tfor {\n\t\t_, p, err := ws.ReadMessage()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tpublish <- newEvent(models.EVENT_MESSAGE, uname, string(p))\n\t}\n}\n\n\nfunc broadcastWebSocket(event models.Event) {\n\tdata, err := json.Marshal(event)\n\tif err != nil {\n\t\tbeego.Error(\"Fail to marshal event:\", err)\n\t\treturn\n\t}\n\n\tfor sub := subscribers.Front(); sub != nil; sub = sub.Next() {\n\t\tws := sub.Value.(Subscriber).Conn\n\t\tif ws != nil {\n\t\t\tif ws.WriteMessage(websocket.TextMessage, data) != nil {\n\t\t\t\tunsubscribe <- sub.Value.(Subscriber).Name\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (this *WebSocketController) Get() ", "output": "{\n\tuname := this.GetString(\"uname\")\n\tif len(uname) == 0 {\n\t\tthis.Redirect(\"/\", 302)\n\t\treturn\n\t}\n\n\tthis.TplName = \"websocket.html\"\n\tthis.Data[\"IsWebSocket\"] = true\n\tthis.Data[\"UserName\"] = uname\n}"} {"input": "package wire\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\n\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max)\n\tif buf != nil {\n\t\tcopy(b, buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc newFixedWriter(max int) io.Writer ", "output": "{\n\tb := make([]byte, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}"} {"input": "package ShortMessagingService\n\nimport \"fmt\"\n\n\ntype Message interface {\n\tSend(phone string, message string) (map[string]bool, error)\n}\n\nvar channels = make(map[string]ShortMessagingService)\n\n\ntype ShortMessagingService interface {\n\tParse(filename string) (Message, error)\n}\n\n\n\n\n\n\nfunc Register(name string, sms ShortMessagingService) {\n\tif sms == nil {\n\t\tpanic(\"[SMS]: Register channel is nil\")\n\t}\n\tif _, ok := channels[name]; ok {\n\t\tpanic(\"[SMS]: Register called teice for channel \" + name)\n\t}\n\tchannels[name] = sms\n}\n\nfunc NewShortMessagingService(channel, filename string) (Message, error) ", "output": "{\n\tif service, ok := channels[channel]; ok {\n\t\treturn service.Parse(filename)\n\t}\n\treturn nil, fmt.Errorf(\"unknown sms channel: %q\", channel)\n}"} {"input": "package probe_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/minio/minio/pkg/probe\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype MySuite struct{}\n\nvar _ = Suite(&MySuite{})\n\nfunc testDummy0() *probe.Error {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\treturn probe.NewError(e)\n}\n\nfunc testDummy1() *probe.Error {\n\treturn testDummy0().Trace(\"DummyTag1\")\n}\n\nfunc testDummy2() *probe.Error {\n\treturn testDummy1().Trace(\"DummyTag2\")\n}\n\nfunc (s *MySuite) TestProbe(c *C) {\n\tes := testDummy2().Trace(\"TopOfStack\")\n\tc.Assert(es, Not(Equals), nil)\n\n\tnewES := es.Trace()\n\tc.Assert(newES, Not(Equals), nil)\n}\n\n\n\nfunc (s *MySuite) TestWrappedError(c *C) ", "output": "{\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\tes := probe.NewError(e) \n\te = probe.WrapError(es) \n\t_, ok := probe.UnwrapError(e)\n\tc.Assert(ok, Equals, true)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/coscms/webx\"\n)\n\ntype MainAction struct {\n\t*webx.Action\n\n\tstart time.Time\n\n\thello webx.Mapper `webx:\"/(.*)\"`\n}\n\n\n\nfunc (c *MainAction) Before(structName, actionName string) bool {\n\tc.start = time.Now()\n\tfmt.Println(\"before\", c.start)\n\treturn true\n}\n\nfunc (c *MainAction) After(structName, actionName string, actionResult interface{}) bool {\n\tfmt.Println(\"after\", time.Now().Sub(c.start))\n\treturn true\n}\n\nfunc main() {\n\twebx.AddRouter(\"/\", &MainAction{})\n\twebx.Run(\"0.0.0.0:9999\")\n}\n\nfunc (c *MainAction) Hello(world string) bool ", "output": "{\n\tc.Write(\"hello %v\", world)\n\treturn true\n}"} {"input": "package digitalocean\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\n\t\"github.com/digitalocean/godo\"\n)\n\ntype Artifact struct {\n\tsnapshotName string\n\n\tsnapshotId int\n\n\tregionName string\n\n\tclient *godo.Client\n}\n\nfunc (*Artifact) BuilderId() string {\n\treturn BuilderId\n}\n\n\n\nfunc (a *Artifact) Id() string {\n\treturn fmt.Sprintf(\"%s:%s\", a.regionName, strconv.FormatUint(uint64(a.snapshotId), 10))\n}\n\nfunc (a *Artifact) String() string {\n\treturn fmt.Sprintf(\"A snapshot was created: '%v' (ID: %v) in region '%v'\", a.snapshotName, a.snapshotId, a.regionName)\n}\n\nfunc (a *Artifact) State(name string) interface{} {\n\treturn nil\n}\n\nfunc (a *Artifact) Destroy() error {\n\tlog.Printf(\"Destroying image: %d (%s)\", a.snapshotId, a.snapshotName)\n\t_, err := a.client.Images.Delete(context.TODO(), a.snapshotId)\n\treturn err\n}\n\nfunc (*Artifact) Files() []string ", "output": "{\n\treturn nil\n}"} {"input": "package server_test\n\nimport (\n\t\"testing\"\n\t\"github.com/AdRoll/hologram/server\"\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\n\n\nfunc TestBuildARN(t *testing.T) ", "output": "{\n\taliases := map[string]string{\n\t\t\"a1\": \"arn:aws:iam::1234\",\n\t\t\"a2\": \"arn:aws:iam::5432\",\n\t}\n\tConvey(\"A role without an alias should return the default account\", t, func() {\n\t\trole := server.BuildARN(\"rolename\", \"99999\", &aliases)\n\t\tSo(role, ShouldResemble, \"arn:aws:iam::99999:role/rolename\")\n\t})\n\n\tConvey(\"A role with an alias should return the alias\", t, func() {\n\t\trole := server.BuildARN(\"a1/rolename\", \"99999\", &aliases)\n\t\tSo(role, ShouldResemble, \"arn:aws:iam::1234:role/rolename\")\n\t})\n\n}"} {"input": "package main\n\nimport \"net/http\"\n\n\n\nfunc handlerRemoveClient(response http.ResponseWriter, request *http.Request) ", "output": "{\n\n\tclientName := request.FormValue(`clientName`)\n\n\tremoveClient(clientName)\n\n\thttp.Redirect(response, request, `/`, http.StatusFound)\n}"} {"input": "package logs\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst format = \"2006/01/02 15:04:05\"\n\ntype DetailedLogger struct {\n\tmu sync.Mutex\n\toutput io.Writer\n}\n\n\n\nfunc (d *DetailedLogger) Write(p []byte) (n int, err error) {\n\tvar file string\n\tvar line int\n\tvar ok bool\n\n\t_, file, line, ok = runtime.Caller(3)\n\tif !ok {\n\t\tfile = \"???\"\n\t\tline = 0\n\t}\n\n\tnow := time.Now().UTC().Format(format)\n\tout := fmt.Sprintf(\"%s %s:%d %s\", now, file, line, p)\n\n\td.mu.Lock()\n\tdefer d.mu.Unlock()\n\n\treturn d.output.Write([]byte(out))\n}\n\nfunc NewDetailedLogger(w io.Writer) *DetailedLogger ", "output": "{\n\treturn &DetailedLogger{\n\t\toutput: w,\n\t}\n}"} {"input": "package validation\n\nimport (\n\t\"strings\"\n\n\t\"github.com/rantuttl/cloudops/apimachinery/pkg/util/validation\"\n\t\"github.com/rantuttl/cloudops/apimachinery/pkg/util/validation/field\"\n)\n\nconst IsNegativeErrorMsg string = `must be greater than or equal to 0`\n\n\n\n\n\n\ntype ValidateNameFunc func(name string, prefix bool) []string\n\n\nfunc NameIsDNSSubdomain(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1123Subdomain(name)\n}\n\n\n\n\n\nfunc NameIsDNS1035Label(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1035Label(name)\n}\n\n\n\n\nvar ValidateNamespaceName = NameIsDNSLabel\n\n\n\n\nvar ValidateServiceAccountName = NameIsDNSSubdomain\n\n\n\nfunc maskTrailingDash(name string) string {\n\tif strings.HasSuffix(name, \"-\") {\n\t\treturn name[:len(name)-2] + \"a\"\n\t}\n\treturn name\n}\n\n\nfunc ValidateNonnegativeField(value int64, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif value < 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, value, IsNegativeErrorMsg))\n\t}\n\treturn allErrs\n}\n\nfunc NameIsDNSLabel(name string, prefix bool) []string ", "output": "{\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1123Label(name)\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"github.com/Shopify/toxiproxy/stream\"\n\t\"github.com/Shopify/toxiproxy/toxics\"\n)\n\ntype HttpResponseToxic struct {\n\tHttpBody string `json:\"body\"`\n\tHttpStatusCode int `json:\"code\"`\n\tHttpStatusText string `json:\"status\"`\n}\n\n\n\nfunc (t *HttpResponseToxic) Pipe(stub *toxics.ToxicStub) {\n\tbuffer := bytes.NewBuffer(make([]byte, 0, 32*1024))\n\twriter := stream.NewChanWriter(stub.Output)\n\treader := stream.NewChanReader(stub.Input)\n\treader.SetInterrupt(stub.Interrupt)\n\tfor {\n\t\ttee := io.TeeReader(reader, buffer)\n\t\tresp, err := http.ReadResponse(bufio.NewReader(tee), nil)\n\t\tif err == stream.ErrInterrupted {\n\t\t\tbuffer.WriteTo(writer)\n\t\t\treturn\n\t\t} else if err == io.EOF {\n\t\t\tstub.Close()\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tbuffer.WriteTo(writer)\n\t\t} else {\n\t\t\tt.ModifyResponse(resp)\n\t\t\tresp.Write(writer)\n\t\t}\n\t\tbuffer.Reset()\n\t}\n}\n\nfunc init() {\n\ttoxics.Register(\"response\", new(HttpResponseToxic))\n}\n\nfunc (t *HttpResponseToxic) ModifyResponse(resp *http.Response) ", "output": "{\n\tif t.HttpBody != \"\" {\n\t\tresp.Body = ioutil.NopCloser(bytes.NewBufferString(t.HttpBody))\n\t\tresp.ContentLength = int64(len(t.HttpBody))\n\t}\n\tif t.HttpStatusCode > 0 {\n\t\tresp.StatusCode = t.HttpStatusCode\n\t}\n\tif t.HttpStatusText != \"\" {\n\t\tresp.Status = t.HttpStatusText\n\t}\n}"} {"input": "package automation\n\nimport (\n\t\"testing\"\n\n\t\"github.com/golang/protobuf/proto\"\n)\n\n\n\nfunc TestHorizontalReshardingTaskEmittedTasks(t *testing.T) ", "output": "{\n\treshardingTask := &HorizontalReshardingTask{}\n\n\tparameters := map[string]string{\n\t\t\"keyspace\": \"test_keyspace\",\n\t\t\"source_shard_list\": \"10-20\",\n\t\t\"dest_shard_list\": \"10-18,18-20\",\n\t\t\"vtctld_endpoint\": \"localhost:15000\",\n\t\t\"vtworker_endpoint\": \"localhost:15001\",\n\t\t\"exclude_tables\": \"unrelated1,unrelated2\",\n\t\t\"min_healthy_rdonly_endpoints\": \"1\",\n\t}\n\n\terr := validateParameters(reshardingTask, parameters)\n\tif err != nil {\n\t\tt.Fatalf(\"Not all required parameters were specified: %v\", err)\n\t}\n\n\tnewTaskContainers, _, _ := reshardingTask.Run(parameters)\n\n\tfor _, tc := range newTaskContainers {\n\t\tt.Logf(\"new tasks: %v\", proto.MarshalTextString(tc))\n\t}\n}"} {"input": "package string_byte_array_converter\n\nimport (\n\t\"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/blevesearch/bleve/analysis\"\n\t\"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/blevesearch/bleve/registry\"\n)\n\ntype StringByteArrayConverter struct{}\n\nfunc NewStringByteArrayConverter() *StringByteArrayConverter {\n\treturn &StringByteArrayConverter{}\n}\n\nfunc (c *StringByteArrayConverter) Convert(in []byte) (interface{}, error) {\n\treturn string(in), nil\n}\n\n\n\nfunc init() {\n\tregistry.RegisterByteArrayConverter(\"string\", Constructor)\n}\n\nfunc Constructor(config map[string]interface{}, cache *registry.Cache) (analysis.ByteArrayConverter, error) ", "output": "{\n\treturn NewStringByteArrayConverter(), nil\n}"} {"input": "package command\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/state\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\nfunc TestStateHook_impl(t *testing.T) {\n\tvar _ terraform.Hook = new(StateHook)\n}\n\n\n\nfunc TestStateHook(t *testing.T) ", "output": "{\n\tis := &state.InmemState{}\n\tvar hook terraform.Hook = &StateHook{State: is}\n\n\ts := state.TestStateInitial()\n\taction, err := hook.PostStateUpdate(s)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\tif action != terraform.HookActionContinue {\n\t\tt.Fatalf(\"bad: %v\", action)\n\t}\n\tif !is.State().Equal(s) {\n\t\tt.Fatalf(\"bad state: %#v\", is.State())\n\t}\n}"} {"input": "package fgae\n\nimport(\n\t\"golang.org/x/net/context\"\n\t\"github.com/skypies/util/gcp/ds\"\n\tfdb \"github.com/skypies/flightdb\"\n)\n\n\ntype FlightIterator ds.Iterator\n\nfunc NewFlightIterator(ctx context.Context, p ds.DatastoreProvider, fq *FQuery) *FlightIterator {\n\tit := ds.NewIterator(ctx, p, (*ds.Query)(fq), fdb.IndexedFlightBlob{})\n\treturn (*FlightIterator)(it)\n}\n\nfunc (fi *FlightIterator)Iterate(ctx context.Context) bool {\n\tit := (*ds.Iterator)(fi)\n\treturn it.Iterate(ctx)\n}\n\n\n\nfunc (fi *FlightIterator)Flight() *fdb.Flight {\n\tblob := fdb.IndexedFlightBlob{}\n\n\tit := (*ds.Iterator)(fi)\n\tkeyer := it.Val(&blob)\n\n\tf, err := blob.ToFlight(keyer.Encode())\n\tif err != nil {\n\t\tit.SetErr(err)\n\t\treturn nil\n\t}\n\n\treturn f\n}\n\nfunc (fi *FlightIterator)Err() error ", "output": "{\n\tit := (*ds.Iterator)(fi)\n\treturn it.Err()\n}"} {"input": "package goDB\n\nimport (\n \"encoding/json\"\n \"os\"\n)\n\n\ntype BlockMetadata struct {\n Timestamp int64 `json:\"timestamp\"`\n PcapPacketsReceived int `json:\"pcap_packets_received\"`\n PcapPacketsDropped int `json:\"pcap_packets_dropped\"`\n PcapPacketsIfDropped int `json:\"pcap_packets_if_dropped\"`\n PacketsLogged int `json:\"packets_logged\"`\n\n \n FlowCount uint64 `json:\"flowcount\"`\n Traffic uint64 `json:\"traffic\"`\n}\n\n\n\ntype Metadata struct {\n Blocks []BlockMetadata `json:\"blocks\"`\n}\n\nfunc NewMetadata() *Metadata {\n return &Metadata{}\n}\n\n\nfunc ReadMetadata(path string) (*Metadata, error) {\n var result Metadata\n\n f, err := os.Open(path)\n if err != nil {\n return nil, err\n }\n defer f.Close()\n\n if err := json.NewDecoder(f).Decode(&result); err != nil {\n return nil, err\n }\n\n return &result, nil\n}\n\n\n\n\n\nfunc WriteMetadata(path string, meta *Metadata) error {\n f, err := os.Create(path)\n if err != nil {\n return err\n }\n defer f.Close()\n\n return json.NewEncoder(f).Encode(meta)\n}\n\nfunc TryReadMetadata(path string) *Metadata ", "output": "{\n meta, err := ReadMetadata(path)\n if err != nil {\n return NewMetadata()\n }\n return meta\n}"} {"input": "package segment\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/checkr/flagr/swagger_gen/models\"\n)\n\n\nconst DeleteSegmentOKCode int = 200\n\n\ntype DeleteSegmentOK struct {\n}\n\n\nfunc NewDeleteSegmentOK() *DeleteSegmentOK {\n\n\treturn &DeleteSegmentOK{}\n}\n\n\nfunc (o *DeleteSegmentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(200)\n}\n\n\ntype DeleteSegmentDefault struct {\n\t_statusCode int\n\n\tPayload *models.Error `json:\"body,omitempty\"`\n}\n\n\nfunc NewDeleteSegmentDefault(code int) *DeleteSegmentDefault {\n\tif code <= 0 {\n\t\tcode = 500\n\t}\n\n\treturn &DeleteSegmentDefault{\n\t\t_statusCode: code,\n\t}\n}\n\n\n\n\n\nfunc (o *DeleteSegmentDefault) SetStatusCode(code int) {\n\to._statusCode = code\n}\n\n\nfunc (o *DeleteSegmentDefault) WithPayload(payload *models.Error) *DeleteSegmentDefault {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *DeleteSegmentDefault) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}\n\n\nfunc (o *DeleteSegmentDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(o._statusCode)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\nfunc (o *DeleteSegmentDefault) WithStatusCode(code int) *DeleteSegmentDefault ", "output": "{\n\to._statusCode = code\n\treturn o\n}"} {"input": "package lemon\n\nimport (\n\t\"errors\"\n\t\"testing\"\n)\n\nfunc TestOption(t *testing.T) {\n\ttests := map[string]TestHandler{\n\t\t\"WithError\": OptionWithError,\n\t}\n\n\tfor name, handler := range tests {\n\t\tt.Run(name, Setup(handler))\n\t}\n}\n\ntype errOption struct {\n\terr error\n}\n\nfunc (o errOption) apply(e *Engine) error {\n\treturn o.err\n}\n\n\n\nfunc OptionWithError(runtime *TestRuntime) ", "output": "{\n\n\texpected := errors.New(\"cannot update engine with foobar\")\n\toption := errOption{\n\t\terr: expected,\n\t}\n\n\tengine, err := New(runtime.Context(), option)\n\n\tif err == nil {\n\t\truntime.Error(\"An error was expected\")\n\t}\n\n\tif err != expected {\n\t\truntime.Error(\"Unexpected error: %s\", err)\n\t}\n\n\tif engine != nil {\n\t\truntime.Error(\"Engine should be undefined\")\n\t}\n\n\truntime.Log(\"We received expected error: %s.\", err)\n\n}"} {"input": "package api\n\ntype Memstore map[string]*Collection\n\n\n\nfunc (m Memstore) CreateCollection(slug, name string) (Collection, error) {\n\tm[slug] = &Collection{Name: name,\n\t\tSlug: slug,\n\t\tItems: map[string]Item{},\n\t}\n\treturn *m[slug], nil\n}\n\nfunc (m Memstore) UpdateCollection(slug, name string) error {\n\tif c, ok := m[slug]; !ok {\n\t\treturn CollectionNotFoundError\n\t} else {\n\t\tc.Name = name\n\t}\n\treturn nil\n}\n\nfunc (m Memstore) GetCollectionData(slug string) (Collection, error) {\n\tif c, ok := m[slug]; ok {\n\t\t(*c).Items = nil\n\t\treturn *c, nil\n\t}\n\treturn Collection{}, CollectionNotFoundError\n}\n\nfunc (m Memstore) GetCollectionItems(slug string) (map[string]Item, error) {\n\tif c, ok := m[slug]; ok {\n\t\treturn c.Items, nil\n\t}\n\treturn map[string]Item{}, CollectionNotFoundError\n}\n\nfunc (m Memstore) AddItemToCollection(slug string, item Item) error {\n\tif c, ok := m[slug]; ok {\n\t\tc.Items[item.Tag] = item\n\t\treturn nil\n\t}\n\treturn CollectionNotFoundError\n}\n\nfunc (m Memstore) GetItemFromCollection(slug, tag string) (Item, error) {\n\tif _, ok := m[slug]; !ok {\n\t\treturn Item{}, CollectionNotFoundError\n\t}\n\tif _, ok := m[slug].Items[tag]; !ok {\n\t\treturn Item{}, BlobNotFoundError\n\t}\n\treturn m[slug].Items[tag], nil\n}\n\nfunc (m Memstore) Init(dbName string) error ", "output": "{\n\treturn nil\n}"} {"input": "package raddress\n\nimport (\n\t\"fmt\"\n\t. \"github.com/smartystreets/goconvey/convey\"\n\t\"testing\"\n)\n\nfunc TestCities(t *testing.T) {\n\tConvey(\"Test get city\", t, func() {\n\n\t\tConvey(\"Test get city\", func() {\n\t\t\titem := GetCityByName(\"Москва\")\n\t\t\tSo(item.Id, ShouldNotEqual, 0)\n\t\t\tSo(item.RegionId, ShouldNotEqual, 0)\n\t\t})\n\n\t\tConvey(\"Get city region\", func() {\n\t\t\titem := GetCityRegion(\"москва\")\n\t\t\tSo(item.Id, ShouldNotEqual, 0)\n\t\t})\n\n\t\tConvey(\"Get region\", func() {\n\t\t\titems := GetRegionCities(\"Смоленска\")\n\t\t\tSo(len(items), ShouldNotEqual, 0)\n\t\t})\n\n\t})\n\n}\n\n\n\nfunc TestLoc(t *testing.T) ", "output": "{\n\tfmt.Println(Loc.RegionName(67))\n\tConvey(\"test Loc\", t, func() {\n\t\titems := Loc.Cities(67)\n\t\tSo(len(items), ShouldNotEqual, 0)\n\t})\n}"} {"input": "package config\n\nimport (\n\t\"k8s.io/perf-tests/clusterloader2/api\"\n)\n\n\ntype ClusterLoaderConfig struct {\n\tClusterConfig ClusterConfig\n\tReportDir string\n\tEnableExecService bool\n\tTestScenario api.TestScenario\n\tPrometheusConfig PrometheusConfig\n}\n\n\ntype ClusterConfig struct {\n\tKubeConfigPath string\n\tNodes int\n\tProvider string\n\tEtcdInsecurePort int\n\tMasterIPs []string\n\tMasterInternalIPs []string\n\tMasterName string\n\tKubemarkRootKubeConfigPath string\n}\n\n\ntype PrometheusConfig struct {\n\tEnableServer bool\n\tTearDownServer bool\n\tScrapeEtcd bool\n\tScrapeNodeExporter bool\n\tScrapeKubelets bool\n\tScrapeKubeProxy bool\n}\n\n\n\nfunc (c *ClusterConfig) GetMasterIp() string {\n\tif len(c.MasterIPs) > 0 {\n\t\treturn c.MasterIPs[0]\n\t}\n\treturn \"\"\n}\n\n\n\n\n\nfunc (c *ClusterConfig) GetMasterInternalIp() string ", "output": "{\n\tif len(c.MasterInternalIPs) > 0 {\n\t\treturn c.MasterInternalIPs[0]\n\t}\n\treturn \"\"\n}"} {"input": "package format\n\nimport (\n\t\"github.com/trivago/gollum/core\"\n\t\"os\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Hostname struct {\n\tcore.SimpleFormatter `gollumdoc:\"embed_type\"`\n\tseparator []byte `config:\"Separator\" default:\":\"`\n}\n\nfunc init() {\n\tcore.TypeRegistry.Register(Hostname{})\n}\n\n\nfunc (format *Hostname) Configure(conf core.PluginConfigReader) {\n}\n\n\n\n\nfunc (format *Hostname) getFinalContent(content []byte) []byte {\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\tformat.Logger.Error(err)\n\t\thostname = \"unknown host\"\n\t}\n\n\tdataSize := len(hostname) + len(format.separator) + len(content)\n\tpayload := core.MessageDataPool.Get(dataSize)\n\n\toffset := copy(payload, []byte(hostname))\n\toffset += copy(payload[offset:], format.separator)\n\tcopy(payload[offset:], content)\n\n\treturn payload\n}\n\nfunc (format *Hostname) ApplyFormatter(msg *core.Message) error ", "output": "{\n\tcontent := format.getFinalContent(format.GetAppliedContent(msg))\n\tformat.SetAppliedContent(msg, content)\n\n\treturn nil\n}"} {"input": "package dbfiles\n\nimport (\n\t\"encoding/csv\"\n\t\"io\"\n\n\t\"github.com/juju/errgo\"\n)\n\ntype Driver interface {\n\tExtention() string\n\tWrite(io.Writer, []string) error\n\tRead(io.Reader) ([][]string, error)\n}\n\ntype CSV struct{}\n\nfunc (driver CSV) Extention() string {\n\treturn \"csv\"\n}\n\nfunc (driver CSV) Write(writer io.Writer, values []string) error {\n\tcsvwriter := csv.NewWriter(writer)\n\n\terr := csvwriter.WriteAll([][]string{values})\n\tif err != nil {\n\t\treturn errgo.Notef(err, \"can not write to csv writer\")\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (driver CSV) Read(reader io.Reader) ([][]string, error) ", "output": "{\n\tcsvreader := csv.NewReader(reader)\n\tcsvreader.FieldsPerRecord = -1\n\n\tvar values [][]string\n\n\tvalues, err := csvreader.ReadAll()\n\tif err != nil {\n\t\treturn nil, errgo.Notef(err, \"can not read all records from file\")\n\t}\n\n\treturn values, nil\n}"} {"input": "package moss\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestSegmentKeyValueSizeLimits(t *testing.T) ", "output": "{\n\ts, _ := newSegment(100, 200)\n\terr := s.mutateEx(150, 0, 150, 125)\n\tif err != nil {\n\t\tt.Errorf(\"expected a segment\")\n\t}\n\terr = s.mutateEx(150, 0, maxKeyLength, maxValLength)\n\tif err != nil {\n\t\tt.Errorf(\"expected a segment\")\n\t}\n\terr = s.mutateEx(150, 0, maxKeyLength+1, 125)\n\tif err != ErrKeyTooLarge {\n\t\tt.Errorf(\"should have erred for large key\")\n\t}\n\terr = s.mutateEx(150, 0, 100, maxValLength+1)\n\tif err != ErrValueTooLarge {\n\t\tt.Errorf(\"should have erred for large value\")\n\t}\n\terr = s.mutateEx(150, 0, maxKeyLength+1, maxValLength+1)\n\tif err != ErrKeyTooLarge {\n\t\tt.Errorf(\"should have erred for large key\")\n\t}\n}"} {"input": "package v1alpha1_test\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"k8s.io/api/scheduling/v1alpha1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\n\tapiv1 \"k8s.io/api/core/v1\"\n\tutilfeature \"k8s.io/apiserver/pkg/util/feature\"\n\tfeaturegatetesting \"k8s.io/component-base/featuregate/testing\"\n\t_ \"k8s.io/kubernetes/pkg/api/testapi\"\n\t\"k8s.io/kubernetes/pkg/features\"\n)\n\n\n\nfunc TestSetDefaultPreempting(t *testing.T) {\n\tpriorityClass := &v1alpha1.PriorityClass{}\n\n\tdefer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.NonPreemptingPriority, true)()\n\n\toutput := roundTrip(t, runtime.Object(priorityClass)).(*v1alpha1.PriorityClass)\n\tif output.PreemptionPolicy == nil || *output.PreemptionPolicy != apiv1.PreemptLowerPriority {\n\t\tt.Errorf(\"Expected PriorityClass.Preempting value: %+v\\ngot: %+v\\n\", apiv1.PreemptLowerPriority, output.PreemptionPolicy)\n\t}\n}\n\nfunc roundTrip(t *testing.T, obj runtime.Object) runtime.Object ", "output": "{\n\tcodec := legacyscheme.Codecs.LegacyCodec(v1alpha1.SchemeGroupVersion)\n\tdata, err := runtime.Encode(codec, obj)\n\tif err != nil {\n\t\tt.Errorf(\"%v\\n %#v\", err, obj)\n\t\treturn nil\n\t}\n\tobj2, err := runtime.Decode(codec, data)\n\tif err != nil {\n\t\tt.Errorf(\"%v\\nData: %s\\nSource: %#v\", err, string(data), obj)\n\t\treturn nil\n\t}\n\tobj3 := reflect.New(reflect.TypeOf(obj).Elem()).Interface().(runtime.Object)\n\terr = legacyscheme.Scheme.Convert(obj2, obj3, nil)\n\tif err != nil {\n\t\tt.Errorf(\"%v\\nSource: %#v\", err, obj2)\n\t\treturn nil\n\t}\n\treturn obj3\n}"} {"input": "package protocol\n\n\ntype LogoutRequestMessageData struct {\n}\n\n\ntype LogoutRequestMessage struct {\n\tBaseMessage\n\tData LogoutRequestMessageData `json:\"data\"`\n}\n\n\nfunc NewLogoutRequesMessage(session string) *LogoutRequestMessage {\n\tmessage := LogoutRequestMessage{}\n\tmessage.Type = LogoutRequestMessageType\n\tmessage.Session = session\n\treturn &message\n}\n\n\n\n\n\nfunc (m *LogoutRequestMessage) GetSession() string {\n\treturn m.Session\n}\n\n\nfunc (m *LogoutRequestMessage) GetData() interface{} {\n\treturn m.Data\n}\n\n\nfunc (m *LogoutRequestMessage) SetSession(session string) {\n\tm.BaseMessage.Session = session\n}\n\nfunc (m *LogoutRequestMessage) GetType() string ", "output": "{\n\treturn m.Type\n}"} {"input": "package cpuload\n\nimport (\n\t\"fmt\"\n\n\tinfo \"github.com/google/cadvisor/info/v1\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/google/cadvisor/utils/cpuload/netlink\"\n)\n\ntype CpuLoadReader interface {\n\tStart() error\n\n\tStop()\n\n\tGetCpuLoad(name string, path string) (info.LoadStats, error)\n}\n\n\n\nfunc New() (CpuLoadReader, error) ", "output": "{\n\treader, err := netlink.New()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create a netlink based cpuload reader: %v\", err)\n\t}\n\tglog.V(3).Info(\"Using a netlink-based load reader\")\n\treturn reader, nil\n}"} {"input": "package runtime\n\nimport (\n\t\"unsafe\"\n)\n\nfunc RaceRead(addr unsafe.Pointer)\nfunc RaceWrite(addr unsafe.Pointer)\nfunc RaceReadRange(addr unsafe.Pointer, len int)\nfunc RaceWriteRange(addr unsafe.Pointer, len int)\n\nfunc RaceSemacquire(s *uint32)\nfunc RaceSemrelease(s *uint32)\n\n\nconst raceenabled = true\n\nfunc raceReadObjectPC(t *_type, addr unsafe.Pointer, callerpc, pc uintptr) {\n\tkind := t.kind & kindMask\n\tif kind == kindArray || kind == kindStruct {\n\t\tracereadrangepc(addr, t.size, callerpc, pc)\n\t} else {\n\t\tracereadpc(addr, callerpc, pc)\n\t}\n}\n\nfunc raceWriteObjectPC(t *_type, addr unsafe.Pointer, callerpc, pc uintptr) {\n\tkind := t.kind & kindMask\n\tif kind == kindArray || kind == kindStruct {\n\t\tracewriterangepc(addr, t.size, callerpc, pc)\n\t} else {\n\t\tracewritepc(addr, callerpc, pc)\n\t}\n}\n\n\nfunc racereadpc(addr unsafe.Pointer, callpc, pc uintptr)\n\n\nfunc racewritepc(addr unsafe.Pointer, callpc, pc uintptr)\n\ntype symbolizeContext struct {\n\tpc uintptr\n\tfn *byte\n\tfile *byte\n\tline uintptr\n\toff uintptr\n\tres uintptr\n}\n\nvar qq = [...]byte{'?', '?', 0}\nvar dash = [...]byte{'-', 0}\n\n\n\n\nfunc racesymbolize(ctx *symbolizeContext) ", "output": "{\n\tf := findfunc(ctx.pc)\n\tif f == nil {\n\t\tctx.fn = &qq[0]\n\t\tctx.file = &dash[0]\n\t\tctx.line = 0\n\t\tctx.off = ctx.pc\n\t\tctx.res = 1\n\t\treturn\n\t}\n\n\tctx.fn = funcname(f)\n\tfile, line := funcline(f, ctx.pc)\n\tctx.line = uintptr(line)\n\tctx.file = &bytes(file)[0] \n\tctx.off = ctx.pc - f.entry\n\tctx.res = 1\n\treturn\n}"} {"input": "package leet_25\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\ntype dequeue struct {\n\tbuff []*ListNode\n}\n\n\n\nfunc (q *dequeue) rpop() *ListNode {\n\tif 0 == len(q.buff) {\n\t\treturn nil\n\t}\n\tlast := len(q.buff) - 1\n\tp := q.buff[last]\n\tq.buff = q.buff[:last]\n\treturn p\n}\n\nfunc (q *dequeue) rpush(p *ListNode) {\n\tq.buff = append(q.buff, p)\n}\n\nfunc (q *dequeue) clear() {\n\tq.buff = buff[:0]\n}\n\nvar buff []*ListNode\n\nfunc reverseKGroup(head *ListNode, k int) *ListNode {\n\tif head == nil {\n\t\treturn nil\n\t}\n\tif k <= 1 {\n\t\treturn head\n\t}\n\tbuff = make([]*ListNode, 0, k)\n\tqueue := &dequeue{buff: buff}\n\tcount := 0\n\tcur := head\n\tfor cur != nil {\n\t\tcount++\n\t\tqueue.rpush(cur)\n\t\tif count == k {\n\t\t\tcount = 0\n\t\t\tfor {\n\t\t\t\tl := queue.lpop()\n\t\t\t\tr := queue.rpop()\n\t\t\t\tif l == nil || r == nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tl.Val, r.Val = r.Val, l.Val\n\t\t\t}\n\t\t\tqueue.clear()\n\t\t}\n\t\tcur = cur.Next\n\t}\n\treturn head\n}\n\nfunc (q *dequeue) lpop() *ListNode ", "output": "{\n\tif 0 == len(q.buff) {\n\t\treturn nil\n\t}\n\tp := q.buff[0]\n\tq.buff = q.buff[1:]\n\treturn p\n}"} {"input": "package gobuddyfs\n\nimport (\n\t\"sync\"\n\n\t\"github.com/golang/glog\"\n)\n\ntype MemStore struct {\n\tlock *sync.RWMutex\n\tstore map[string][]byte\n\n\tKVStore\n}\n\n\n\nfunc (self *MemStore) Get(key string, retry bool) ([]byte, error) {\n\tif glog.V(2) {\n\t\tglog.Infof(\"Get(%s)\\n\", key)\n\t}\n\tself.lock.RLock()\n\tdefer self.lock.RUnlock()\n\tval, ok := self.store[key]\n\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\n\treturn val, nil\n}\n\nfunc (self *MemStore) Set(key string, value []byte) error {\n\tif glog.V(2) {\n\t\tglog.Infof(\"Set(%s)\\n\", key)\n\t}\n\tself.lock.Lock()\n\tdefer self.lock.Unlock()\n\n\tif value == nil {\n\t\tdelete(self.store, key)\n\t} else {\n\t\tself.store[key] = value\n\t}\n\n\treturn nil\n}\n\nvar _ KVStore = new(MemStore)\n\nfunc NewMemStore() *MemStore ", "output": "{\n\treturn &MemStore{store: make(map[string][]byte), lock: &sync.RWMutex{}}\n}"} {"input": "package quicktest\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\n\nfunc BadCheckf(format string, a ...interface{}) error {\n\te := badCheck(fmt.Sprintf(format, a...))\n\treturn &e\n}\n\n\n\n\n\ntype badCheck string\n\n\nfunc (e *badCheck) Error() string {\n\treturn \"bad check: \" + string(*e)\n}\n\n\n\n\nvar ErrSilent = fmt.Errorf(\"silent failure\")\n\nfunc IsBadCheck(err error) bool ", "output": "{\n\t_, ok := err.(*badCheck)\n\treturn ok\n}"} {"input": "package tokencmd\n\nimport \"io\"\n\n\n\nfunc NewSSPINegotiator(string, string, string, io.Reader) Negotiator {\n\treturn newUnsupportedNegotiator(\"SSPI\")\n}\n\nfunc SSPIEnabled() bool ", "output": "{\n\treturn false\n}"} {"input": "package stripe\n\nimport (\n\t\"github.com/bmizerany/assert\"\n\t\"net/url\"\n\t\"testing\"\n)\n\n\n\nfunc TestTokensRetrieve(t *testing.T) {\n\tsetup()\n\tdefer teardown()\n\thandleWithJSON(\"/tokens/tok_123456789\", \"tokens/token.json\")\n\ttoken, _ := client.Tokens.Retrieve(\"tok_123456789\")\n\tassert.Equal(t, token.Id, \"tok_123456789\")\n}\n\nfunc TestParseTokenParams(t *testing.T) {\n\tparams := TokenParams{\n\t\tCustomer: \"cus_123456789\",\n\t\tCardParams: &CardParams{\n\t\t\tNumber: \"4242424242424242\",\n\t\t},\n\t\tBankAccountParams: &BankAccountParams{\n\t\t\tAccountNumber: \"123456789\",\n\t\t},\n\t}\n\tvalues := url.Values{}\n\n\tparseTokenParams(¶ms, &values)\n\tassert.Equal(t, values.Get(\"customer\"), params.Customer)\n\tassert.Equal(t, values.Get(\"card[number]\"), params.CardParams.Number)\n\tassert.NotEqual(t, values.Get(\"bank_account[account_number]\"), params.BankAccountParams.AccountNumber)\n\n\tparams.CardParams = nil\n\tvalues = url.Values{}\n\tparseTokenParams(¶ms, &values)\n\tassert.Equal(t, values.Get(\"bank_account[account_number]\"), params.BankAccountParams.AccountNumber)\n}\n\nfunc TestTokenCreate(t *testing.T) ", "output": "{\n\tsetup()\n\tdefer teardown()\n\thandleWithJSON(\"/tokens\", \"tokens/token.json\")\n\tparams := TokenParams{}\n\ttoken, _ := client.Tokens.Create(¶ms)\n\tassert.Equal(t, token.Id, \"tok_123456789\")\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"thezombie.net/libgojira\"\n)\n\n\n\n\ntype RankCommand struct {\n}\n\nfunc (rc *RankCommand) Usage() string {\n\treturn \"gojira rank TASK-1 TASK-2 TASK-3 TASK-4\"\n}\n\nvar rankCommand RankCommand\n\nfunc (rc *RankCommand) Execute(args []string) error {\n\tif len(args) < 3 {\n\t\treturn fmt.Errorf(\"Need at least 3 arguments. Usage: %s\", rc.Usage)\n\t}\n\ttarget := args[len(args)-1]\n\tbefore_or_after := strings.ToLower(args[len(args)-2])\n\ttasks := args[:len(args)-2]\n\n\tif before_or_after != \"before\" && before_or_after != \"after\" {\n\t\treturn fmt.Errorf(\"second last parameter needs to be 'before' or 'after'\")\n\t}\n\n\tfmt.Println(\"target\", target)\n\tjc := libgojira.NewJiraClient(options)\n\terr := jc.ChangeRank(tasks, before_or_after, target)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tparser.AddCommand(\"rank\",\n\t\t\"Rank Jira stories\",\n\t\t\"The rank command allows a user to modify story ranks\",\n\t\t&rankCommand)\n\n}"} {"input": "package main\n\nimport (\n\t\"code.google.com/p/go.crypto/bcrypt\"\n\t\"github.com/stevenschmatz/gopherbox/GBServer/GBServerDatabase\"\n\t\"gopkg.in/mgo.v2\"\n\t\"log\"\n)\n\nvar (\n\tusername = \"schmatz\"\n\tpassword = \"test\"\n)\n\nfunc main() {\n\tsession, err := mgo.Dial(\"localhost\")\n\tcheckErr(err)\n\n\tUserCollection := session.DB(\"test\").C(\"userTest\")\n\tMetadataCollection := session.DB(\"test\").C(\"metadataTest\")\n\n\tpassword_hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\tcheckErr(err)\n\n\terr = GBServerDatabase.SignupUser(UserCollection, MetadataCollection, username, \"steven@schmatz.com\", string(password_hash))\n\tcheckErr(err)\n}\n\n\n\nfunc checkErr(err error) ", "output": "{\n\tif err != nil {\n\t\tlog.Fatalf(\"GBServer: SignupUser: %s\", err.Error())\n\t}\n}"} {"input": "package url2\n\nimport (\n\t\"net/url\"\n\t\"testing\"\n\n\t\"github.com/cosiner/gohper/testing2\"\n)\n\nfunc TestQueryEscape(t *testing.T) {\n\ttt := testing2.Wrap(t)\n\tqs := map[string]string{\n\t\t\"A\": \"DD\",\n\t\t\"Z\": \"DD\",\n\t}\n\tq, _ := QueryEscape(qs, nil)\n\ts := string(q)\n\ttt.NE(url.QueryEscape(\"A=DD&Z=DD\") == s, url.QueryEscape(\"Z=DD&A=DD\") == s)\n}\n\n\n\nfunc TestParamString(t *testing.T) ", "output": "{\n\ttt := testing2.Wrap(t)\n\ttt.Eq(Param(1), \"1\")\n\ttt.Eq(Param(\"ddd\"), \"ddd\")\n\ttt.Eq(Param([]int{1, 2, 3}), \"1,2,3\")\n\ttt.Eq(Param([]string{\"1\", \"2\", \"3\"}), \"1,2,3\")\n\ttt.Eq(Param([]byte(\"ddd\")), \"ddd\")\n\n\tdefer tt.Recover()\n\n\tParam(int64(2))\n}"} {"input": "package sched\n\nimport (\n\t\"encoding/json\"\n\n\t\"bosun.org/cmd/bosun/expr\"\n\telastic \"gopkg.in/olivere/elastic.v5\"\n)\n\nfunc (c *Context) esQuery5(indexRoot expr.ESIndexer, filter expr.ESQuery, sduration, eduration string, size int) interface{} {\n\tnewFilter := expr.ScopeES5(c.Group(), filter.Query(expr.ESV5).(elastic.Query))\n\treq, err := expr.ESBaseQuery5(c.runHistory.Start, indexRoot, newFilter, sduration, eduration, size, c.ElasticHost)\n\tif err != nil {\n\t\tc.addError(err)\n\t\treturn nil\n\t}\n\tresults, err := c.runHistory.Backends.ElasticHosts.Query5(req)\n\tif err != nil {\n\t\tc.addError(err)\n\t\treturn nil\n\t}\n\tr := make([]interface{}, len(results.Hits.Hits))\n\tfor i, h := range results.Hits.Hits {\n\t\tvar err error\n\t\terr = json.Unmarshal(*h.Source, &r[i])\n\t\tif err != nil {\n\t\t\tc.addError(err)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn r\n}\n\n\n\nfunc (c *Context) esQueryAll5(indexRoot expr.ESIndexer, filter expr.ESQuery, sduration, eduration string, size int) interface{} ", "output": "{\n\treq, err := expr.ESBaseQuery5(c.runHistory.Start, indexRoot, filter.Query(expr.ESV5).(elastic.Query), sduration, eduration, size, c.ElasticHost)\n\tif err != nil {\n\t\tc.addError(err)\n\t\treturn nil\n\t}\n\tresults, err := c.runHistory.Backends.ElasticHosts.Query5(req)\n\tif err != nil {\n\t\tc.addError(err)\n\t\treturn nil\n\t}\n\tr := make([]interface{}, len(results.Hits.Hits))\n\tfor i, h := range results.Hits.Hits {\n\t\tvar err error\n\t\terr = json.Unmarshal(*h.Source, &r[i])\n\t\tif err != nil {\n\t\t\tc.addError(err)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn r\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype OpenpitrixRoleResource struct {\n\n\tCPU int64 `json:\"cpu,omitempty\"`\n\n\tGpu int64 `json:\"gpu,omitempty\"`\n\n\tInstanceSize int64 `json:\"instance_size,omitempty\"`\n\n\tMemory int64 `json:\"memory,omitempty\"`\n\n\tRole string `json:\"role,omitempty\"`\n\n\tStorageSize int64 `json:\"storage_size,omitempty\"`\n}\n\n\nfunc (m *OpenpitrixRoleResource) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\nfunc (m *OpenpitrixRoleResource) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\n\n\nfunc (m *OpenpitrixRoleResource) UnmarshalBinary(b []byte) error ", "output": "{\n\tvar res OpenpitrixRoleResource\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}"} {"input": "package hole\n\n\ntype Session struct {\n\tID []byte\n\tr *ReadStream\n\tw *WriteStream\n}\n\n\n\n\nfunc NewSession(sessionID []byte, conn Conn) Session ", "output": "{\n\treturn Session{\n\t\tID: sessionID,\n\t\tr: NewReadStream(),\n\t\tw: &WriteStream{\n\t\t\tconn: conn,\n\t\t\tsessionID: sessionID,\n\t\t},\n\t}\n}"} {"input": "package deb\n\nimport (\n\t\"encoding/binary\"\n\t\"github.com/smira/aptly/aptly\"\n\t\"github.com/smira/aptly/utils\"\n\t\"hash/fnv\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n)\n\n\ntype PackageFile struct {\n\tFilename string\n\tChecksums utils.ChecksumInfo\n\tdownloadPath string\n}\n\n\n\n\n\nfunc (f *PackageFile) DownloadURL() string {\n\treturn filepath.Join(f.downloadPath, f.Filename)\n}\n\n\ntype PackageFiles []PackageFile\n\n\nfunc (files PackageFiles) Hash() uint64 {\n\tsort.Sort(files)\n\n\th := fnv.New64a()\n\n\tfor _, f := range files {\n\t\th.Write([]byte(f.Filename))\n\t\tbinary.Write(h, binary.BigEndian, f.Checksums.Size)\n\t\th.Write([]byte(f.Checksums.MD5))\n\t\th.Write([]byte(f.Checksums.SHA1))\n\t\th.Write([]byte(f.Checksums.SHA256))\n\t}\n\n\treturn h.Sum64()\n}\n\n\nfunc (files PackageFiles) Len() int {\n\treturn len(files)\n}\n\n\nfunc (files PackageFiles) Swap(i, j int) {\n\tfiles[i], files[j] = files[j], files[i]\n}\n\n\nfunc (files PackageFiles) Less(i, j int) bool {\n\treturn files[i].Filename < files[j].Filename\n}\n\nfunc (f *PackageFile) Verify(packagePool aptly.PackagePool) (bool, error) ", "output": "{\n\tpoolPath, err := packagePool.Path(f.Filename, f.Checksums.MD5)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tst, err := os.Stat(poolPath)\n\tif err != nil {\n\t\treturn false, nil\n\t}\n\n\treturn st.Size() == f.Checksums.Size, nil\n}"} {"input": "package tchannelthrift\n\nimport (\n\tstdctx \"context\"\n\t\"time\"\n\n\t\"github.com/m3db/m3/src/x/context\"\n\n\tapachethrift \"github.com/apache/thrift/lib/go/thrift\"\n\t\"github.com/uber/tchannel-go\"\n\t\"github.com/uber/tchannel-go/thrift\"\n)\n\nconst (\n\tcontextKey = \"m3dbcontext\"\n)\n\n\n\n\n\nfunc NewContext(timeout time.Duration) (thrift.Context, stdctx.CancelFunc) {\n\ttctx, cancel := thrift.NewContext(timeout)\n\txCtx := context.NewWithGoContext(tctx)\n\tctxWithValue := stdctx.WithValue(tctx, contextKey, xCtx) \n\treturn thrift.WithHeaders(ctxWithValue, nil), cancel\n}\n\n\nfunc Context(ctx thrift.Context) context.Context {\n\treturn ctx.Value(contextKey).(context.Context)\n}\n\nfunc postResponseFn(ctx stdctx.Context, method string, response apachethrift.TStruct) {\n\tvalue := ctx.Value(contextKey)\n\tinner := value.(context.Context)\n\tinner.Close()\n}\n\nfunc RegisterServer(channel *tchannel.Channel, service thrift.TChanServer, contextPool context.Pool) ", "output": "{\n\tserver := thrift.NewServer(channel)\n\tserver.Register(service, thrift.OptPostResponse(postResponseFn))\n\tserver.SetContextFn(func(ctx stdctx.Context, method string, headers map[string]string) thrift.Context {\n\t\txCtx := contextPool.Get()\n\t\txCtx.SetGoContext(ctx)\n\t\tctxWithValue := stdctx.WithValue(ctx, contextKey, xCtx) \n\t\treturn thrift.WithHeaders(ctxWithValue, headers)\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/unrolled/render\"\n)\n\n\nvar Render *render.Render\n\n\nfunc init() {\n\tRender = render.New(render.Options{\n\t\tIndentJSON: true,\n\t})\n}\n\nfunc index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Welcome to the home page!\")\n}\n\nfunc apiHandler(w http.ResponseWriter, r *http.Request) {\n\tRender.JSON(w, http.StatusOK, \"Welcome to the api hander page!\")\n}\n\nfunc apiKeyHandler(w http.ResponseWriter, r *http.Request) {\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the api Key hander page! %s\", id)\n}\n\nfunc apiKeyDetailsHandler(w http.ResponseWriter, r *http.Request) {\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the api Key Details hander page! %s\", id)\n}\n\nfunc webKeyHandler(w http.ResponseWriter, r *http.Request) {\n\tid := mux.Vars(r)[\"id\"]\n\tfmt.Fprintf(w, \"Welcome to the web Key hander page! %s\", id)\n}\n\n\n\nfunc notFound(w http.ResponseWriter, r *http.Request) ", "output": "{\n\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n}"} {"input": "package httpd\n\n\n\n\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\t\"github.com/xpandmmi/biographies/model/user-model\"\n)\n\n\n\nfunc (h *Handler) postSearchAPI(w http.ResponseWriter, r *http.Request, user *userModel.User) ", "output": "{\n\tvar search interface{}\n\tdecoder := json.NewDecoder(r.Body)\n\terr := decoder.Decode(&search)\n\tif err != nil {\n\t\thttpError(w, err.Error(), false, http.StatusBadRequest)\n\t\treturn\n\t}\n\tresponse, err := h.Elasticsearch.PerformRequest(\"POST\", \"/biographies/profile/_search\", nil, search)\n\tif err != nil {\n\t\thttpError(w, err.Error(), false, http.StatusBadRequest)\n\t\treturn\n\t}\n\tw.Header().Add(\"content-type\", \"application/json\")\n\tw.Write(response.Body)\n}"} {"input": "package logs\n\nimport (\n\t\"io\"\n)\n\ntype stdoutWriter struct {\n\twriter io.Writer\n}\n\ntype stderrorWriter struct {\n\twriter io.Writer\n}\ntype stdbothWriter struct {\n\twriter io.Writer\n}\n\nfunc (w stdoutWriter) Write(message []byte) (n int, err error) {\n\tn, err = w.writer.Write(append([]byte(\"01 \"), message...))\n\treturn n - 3, err\n}\n\nfunc (w stderrorWriter) Write(message []byte) (n int, err error) {\n\tn, err = w.writer.Write(append([]byte(\"02 \"), message...))\n\treturn n - 3, err\n}\n\n\n\nfunc (w stdbothWriter) Write(message []byte) (n int, err error) ", "output": "{\n\tn, err = w.writer.Write(append([]byte(\"00 \"), message...))\n\treturn n - 3, err\n}"} {"input": "package pflag\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype boolValue bool\n\nfunc newBoolValue(val bool, p *bool) *boolValue {\n\t*p = val\n\treturn (*boolValue)(p)\n}\n\nfunc (b *boolValue) Set(s string) error {\n\tv, err := strconv.ParseBool(s)\n\t*b = boolValue(v)\n\treturn err\n}\n\nfunc (b *boolValue) String() string { return fmt.Sprintf(\"%v\", *b) }\n\n\n\n\n\n\nfunc (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc BoolVar(p *bool, name string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc (f *FlagSet) Bool(name string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, \"\", value, usage)\n\treturn p\n}\n\n\nfunc (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, shorthand, value, usage)\n\treturn p\n}\n\n\n\nfunc Bool(name string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, \"\", value, usage)\n}\n\n\nfunc BoolP(name, shorthand string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, shorthand, value, usage)\n}\n\nfunc (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) ", "output": "{\n\tf.VarP(newBoolValue(value, p), name, \"\", usage)\n}"} {"input": "package test\n\nimport (\n\t\"github.com/stellar/go/support/db\"\n\t\"github.com/stellar/horizon/ledger\"\n)\n\n\n\n\n\n\nfunc (t *T) Finish() {\n\tRestoreLogger()\n\tledger.SetState(ledger.State{})\n\n\tif t.LogBuffer.Len() > 0 {\n\t\tt.T.Log(\"\\n\" + t.LogBuffer.String())\n\t}\n}\n\n\nfunc (t *T) HorizonRepo() *db.Repo {\n\treturn &db.Repo{\n\t\tDB: t.HorizonDB,\n\t\tCtx: t.Ctx,\n\t}\n}\n\n\nfunc (t *T) Scenario(name string) *T {\n\tLoadScenario(name)\n\tt.UpdateLedgerState()\n\treturn t\n}\n\n\nfunc (t *T) ScenarioWithoutHorizon(name string) *T {\n\tLoadScenarioWithoutHorizon(name)\n\tt.UpdateLedgerState()\n\treturn t\n}\n\n\nfunc (t *T) UpdateLedgerState() {\n\tvar next ledger.State\n\n\terr := t.CoreRepo().GetRaw(&next, `\n\t\tSELECT\n\t\t\tCOALESCE(MIN(ledgerseq), 0) as core_elder,\n\t\t\tCOALESCE(MAX(ledgerseq), 0) as core_latest\n\t\tFROM ledgerheaders\n\t`)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = t.HorizonRepo().GetRaw(&next, `\n\t\t\tSELECT\n\t\t\t\tCOALESCE(MIN(sequence), 0) as history_elder,\n\t\t\t\tCOALESCE(MAX(sequence), 0) as history_latest\n\t\t\tFROM history_ledgers\n\t\t`)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tledger.SetState(next)\n\treturn\n}\n\nfunc (t *T) CoreRepo() *db.Repo ", "output": "{\n\treturn &db.Repo{\n\t\tDB: t.CoreDB,\n\t\tCtx: t.Ctx,\n\t}\n}"} {"input": "package network\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" network/2019-11-01\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package notify\n\nimport \"github.com/crocos/rds-testrunner/config\"\n\nfunc NewNotifier(notifyConfig config.NotifyConfig) NotifierInterface {\n\tif notifyConfig.Type == \"hipchat\" {\n\t\treturn NewHipChatNotifier(notifyConfig)\n\t} else {\n\t\treturn NewDummyNotifier(notifyConfig)\n\t}\n}\n\ntype NotifierInterface interface {\n\tInfo(string) error\n\tWarning(string) error\n\tError(string) error\n}\n\ntype DummyNotifier struct {\n\tConfig config.NotifyConfig\n}\n\nfunc NewDummyNotifier(notifyConfig config.NotifyConfig) (notify NotifierInterface) {\n\treturn &DummyNotifier{Config: notifyConfig}\n}\n\n\n\nfunc (n *DummyNotifier) Warning(message string) (err error) {\n\treturn\n}\n\nfunc (n *DummyNotifier) Error(message string) (err error) {\n\treturn\n}\n\nfunc (n *DummyNotifier) Info(message string) (err error) ", "output": "{\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n)\n\nconst etcHostsFile = \"/etc/hosts\"\n\n\n\n\n\nfunc getDNSSuffixList() []string {\n\tfileData := readFile(\"/etc/resolv.conf\")\n\tlines := strings.Split(fileData, \"\\n\")\n\tfor _, line := range lines {\n\t\tif strings.HasPrefix(line, \"search\") {\n\t\t\treturn strings.Split(line, \" \")[1:]\n\t\t}\n\t}\n\n\tpanic(\"Could not find DNS search list!\")\n}\n\n\n\nfunc getDNSServerList() []string ", "output": "{\n\tfileData := readFile(\"/etc/resolv.conf\")\n\tlines := strings.Split(fileData, \"\\n\")\n\tfor _, line := range lines {\n\t\tif strings.HasPrefix(line, \"nameserver\") {\n\t\t\treturn strings.Split(line, \" \")[1:]\n\t\t}\n\t}\n\n\tpanic(\"Could not find DNS search list!\")\n}"} {"input": "package v1\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/unversioned\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\nconst GroupName = \"\"\n\n\nvar SchemeGroupVersion = unversioned.GroupVersion{Group: GroupName, Version: \"v1\"}\n\nfunc AddToScheme(scheme *runtime.Scheme) {\n\taddKnownTypes(scheme)\n\taddConversionFuncs(scheme)\n}\n\n\nfunc addKnownTypes(scheme *runtime.Scheme) {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t&Project{},\n\t\t&ProjectList{},\n\t\t&ProjectRequest{},\n\t)\n}\n\n\nfunc (obj *Project) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta }\nfunc (obj *ProjectList) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta }\n\nfunc (obj *ProjectRequest) GetObjectKind() unversioned.ObjectKind ", "output": "{ return &obj.TypeMeta }"} {"input": "package vulcand\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/dtan4/paus-gitreceive/receiver/store\"\n)\n\nconst (\n\thttpBackendJSON = \"{\\\"Type\\\": \\\"http\\\"}\"\n)\n\ntype Backend struct {\n\tType string `json:\"Type\"`\n}\n\n\n\n\nfunc unsetBackend(etcd *store.Etcd, projectName string) error {\n\tkey := fmt.Sprintf(\"%s/backends/%s/backend\", vulcandKeyBase, projectName)\n\n\tif err := etcd.Delete(key); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc setBackend(etcd *store.Etcd, projectName string) error ", "output": "{\n\tkey := fmt.Sprintf(\"%s/backends/%s/backend\", vulcandKeyBase, projectName)\n\n\tif err := etcd.Set(key, httpBackendJSON); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\n\t\"gopkg.in/pivo.v2/ws\"\n)\n\nconst websocketChatUri = `/`\n\ntype websocket struct {\n\tconn *ws.Conn\n}\n\nfunc (ws *websocket) OnClose(why error) error {\n\tchat.hub.Leave(ws.conn)\n\treturn nil\n}\n\nfunc (ws *websocket) OnBinaryRead(data []byte) error {\n\treturn ErrProtocolViolation\n}\n\nfunc (ws *websocket) OnTextRead(text string) error {\n\tchat.pub <- ws.conn.TextMessage(formatMessage(ws.conn, text))\n\treturn nil\n}\n\nfunc (chat *Hub) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tconn := ws.DefaultConn()\n\tif err := conn.Upgrade(w, r, nil); err != nil {\n\t\tlog.Printf(\"websocket: %s: failed to upgrade: %s\",\n\t\t\tr.RemoteAddr, err)\n\t\treturn\n\t}\n\tgo conn.Sender()\n\tgo conn.Receiver(&websocket{conn})\n\tchat.sub <- conn\n}\n\n\n\nfunc init() ", "output": "{\n\thttp.Handle(websocketChatUri, chat)\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc initConfig() (err error) {\n\treturn errors.New(\"init config faild\")\n}\n\n\nfunc main() {\n\tfor {\n\t\ttest()\n\t\tfmt.Println(\"hello\")\n\t\ttime.Sleep(time.Second)\n\t}\n\n}\n\nfunc test() ", "output": "{\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}()\n\n\terr := initConfig()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}"} {"input": "package filter\n\nimport (\n\t\"context\"\n\n\t\"github.com/hyperledger/fabric-protos-go/peer\"\n\t\"github.com/hyperledger/fabric/core/handlers/auth\"\n)\n\n\n\n\ntype filter struct {\n\tnext peer.EndorserServer\n}\n\n\nfunc (f *filter) Init(next peer.EndorserServer) {\n\tf.next = next\n}\n\n\nfunc (f *filter) ProcessProposal(ctx context.Context, signedProp *peer.SignedProposal) (*peer.ProposalResponse, error) {\n\treturn f.next.ProcessProposal(ctx, signedProp)\n}\n\nfunc NewFilter() auth.Filter ", "output": "{\n\treturn &filter{}\n}"} {"input": "package imageactions\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/fragmenta/auth/can\"\n\t\"github.com/fragmenta/mux\"\n\t\"github.com/fragmenta/server\"\n\t\"github.com/fragmenta/view\"\n\n\t\"github.com/fragmenta/fragmenta-cms/src/images\"\n\t\"github.com/fragmenta/fragmenta-cms/src/lib/session\"\n)\n\n\n\n\nfunc HandleShow(w http.ResponseWriter, r *http.Request) error ", "output": "{\n\n\tparams, err := mux.Params(r)\n\tif err != nil {\n\t\treturn server.InternalError(err)\n\t}\n\n\timage, err := images.Find(params.GetInt(images.KeyName))\n\tif err != nil {\n\t\treturn server.NotFoundError(err)\n\t}\n\n\tuser := session.CurrentUser(w, r)\n\terr = can.Show(image, user)\n\tif err != nil {\n\t\treturn server.NotAuthorizedError(err)\n\t}\n\n\tview := view.NewRenderer(w, r)\n\tview.CacheKey(image.CacheKey())\n\tview.AddKey(\"image\", image)\n\treturn view.Render()\n}"} {"input": "package virtualbox\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n)\n\n\n\n\n\n\nfunc ZeroFill(w io.Writer, n int64) error {\n\tconst blocksize = 32 << 10\n\tzeros := make([]byte, blocksize)\n\tvar k int\n\tvar err error\n\tfor n > 0 {\n\t\tif n > blocksize {\n\t\t\tk, err = w.Write(zeros)\n\t\t} else {\n\t\t\tk, err = w.Write(zeros[:n])\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn -= int64(k)\n\t}\n\treturn nil\n}\n\nfunc MakeDiskImage(dest string, size uint, r io.Reader) error ", "output": "{\n\tsizeBytes := int64(size) << 20 \n\tcmd := exec.Command(cfg.VBM, \"convertfromraw\", \"stdin\", dest,\n\t\tfmt.Sprintf(\"%d\", sizeBytes), \"--format\", \"VMDK\")\n\n\tif verbose {\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t}\n\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\n\tn, err := io.Copy(stdin, r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif left := sizeBytes - n; left > 0 {\n\t\tif err := ZeroFill(stdin, left); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := stdin.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn cmd.Wait()\n}"} {"input": "package protolog \n\nimport (\n\t\"os\"\n\n\t\"go.pedge.io/dlog\"\n\t\"go.pedge.io/protolog\"\n)\n\nfunc init() {\n\tdlog.SetLogger(NewLogger(protolog.NewStandardLogger(protolog.NewFileFlusher(os.Stderr))))\n}\n\ntype logger struct {\n\tprotolog.Logger\n}\n\n\nfunc NewLogger(l protolog.Logger) dlog.Logger {\n\treturn &logger{l}\n}\n\nfunc (l *logger) Debug(args ...interface{}) {\n\tl.Debugln(args...)\n}\n\nfunc (l *logger) Info(args ...interface{}) {\n\tl.Infoln(args...)\n}\n\nfunc (l *logger) Warn(args ...interface{}) {\n\tl.Warnln(args...)\n}\n\nfunc (l *logger) Error(args ...interface{}) {\n\tl.Errorln(args...)\n}\n\n\n\nfunc (l *logger) Panic(args ...interface{}) {\n\tl.Panicln(args...)\n}\n\nfunc (l *logger) Print(args ...interface{}) {\n\tl.Println(args...)\n}\n\nfunc (l *logger) Fatal(args ...interface{}) ", "output": "{\n\tl.Fatalln(args...)\n}"} {"input": "package native\n\nimport (\n\t\"runtime\"\n\n\tgogl \"github.com/go-gl/gl\"\n\tglfw \"github.com/go-gl/glfw3\"\n\n\t\"github.com/dertseha/golgo/runner\"\n)\n\nfunc Run(application runner.Application, param runner.ApplicationParameter) {\n\truntime.LockOSThread()\n\tdefer runtime.UnlockOSThread()\n\n\tif !glfw.Init() {\n\t\tpanic(\"Failed to initialize GLFW\")\n\t}\n\tdefer glfw.Terminate()\n\tsetupGlfw()\n\n\twindow, err := glfw.CreateWindow(param.Width(), param.Height(), param.Title(), nil, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer window.Destroy()\n\tsetupWindow(window, application)\n\n\tgogl.Init()\n\tgl := CreateGles2Wrapper()\n\n\tapplication.Init(gl, param.Width(), param.Height())\n\tfor !window.ShouldClose() {\n\t\tapplication.Render()\n\n\t\twindow.SwapBuffers()\n\t\tglfw.PollEvents()\n\t}\n}\n\nfunc setupGlfw() {\n\tglfw.WindowHint(glfw.ContextVersionMajor, 2)\n\tglfw.WindowHint(glfw.ContextVersionMinor, 0)\n\tglfw.SwapInterval(1)\n}\n\nfunc setupWindow(window *glfw.Window, application runner.Application) {\n\twindow.SetSizeCallback(func(_ *glfw.Window, width int, height int) {\n\t\tapplication.Resize(width, height)\n\t})\n\n\twindow.SetKeyCallback(getKeyCallback(application))\n\n\twindow.MakeContextCurrent()\n}\n\n\n\nfunc getKeyCallback(application runner.Application) func(*glfw.Window, glfw.Key, int, glfw.Action, glfw.ModifierKey) ", "output": "{\n\treturn func(window *glfw.Window, key glfw.Key, scancode int, action glfw.Action, modifier glfw.ModifierKey) {\n\t\tswitch key {\n\t\tcase glfw.KeyEscape:\n\t\t\twindow.SetShouldClose(true)\n\t\t}\n\t}\n}"} {"input": "package sw\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\n\t\"github.com/hyperledger/fabric/core/crypto/bccsp\"\n\t\"github.com/hyperledger/fabric/core/crypto/primitives\"\n)\n\ntype rsaPrivateKey struct {\n\tk *rsa.PrivateKey\n}\n\n\n\nfunc (k *rsaPrivateKey) Bytes() (raw []byte, err error) {\n\treturn\n}\n\n\nfunc (k *rsaPrivateKey) SKI() (ski []byte) {\n\traw := x509.MarshalPKCS1PrivateKey(k.k)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\nfunc (k *rsaPrivateKey) Symmetric() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPrivateKey) Private() bool {\n\treturn true\n}\n\n\n\n\n\ntype rsaPublicKey struct {\n\tk *rsa.PublicKey\n}\n\n\n\nfunc (k *rsaPublicKey) Bytes() (raw []byte, err error) {\n\traw, err = x509.MarshalPKIXPublicKey(k.k)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed marshalling key [%s]\", err)\n\t}\n\treturn\n}\n\n\nfunc (k *rsaPublicKey) SKI() (ski []byte) {\n\traw, _ := primitives.PublicKeyToPEM(k.k, nil)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\nfunc (k *rsaPublicKey) Symmetric() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) Private() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) PublicKey() (bccsp.Key, error) {\n\treturn k, nil\n}\n\nfunc (k *rsaPrivateKey) PublicKey() (bccsp.Key, error) ", "output": "{\n\treturn &rsaPublicKey{&k.k.PublicKey}, nil\n}"} {"input": "package kafkametricsreceiver\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configtest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n)\n\nfunc TestCreateDefaultConfig(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tassert.NotNil(t, cfg, \"default config not created\")\n\tassert.NoError(t, configtest.CheckConfigStruct(cfg))\n}\n\nfunc TestCreateMetricsReceiver_errors(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.Brokers = []string{\"invalid:9092\"}\n\tcfg.ProtocolVersion = \"2.0.0\"\n\tcfg.Scrapers = []string{\"topics\"}\n\tr, err := createMetricsReceiver(context.Background(), componenttest.NewNopReceiverCreateSettings(), cfg, nil)\n\tassert.Error(t, err)\n\tassert.Nil(t, r)\n}\n\n\n\nfunc TestCreateMetricsReceiver(t *testing.T) ", "output": "{\n\tprev := newMetricsReceiver\n\tnewMetricsReceiver = func(ctx context.Context, config Config, params component.ReceiverCreateSettings, consumer consumer.Metrics) (component.MetricsReceiver, error) {\n\t\treturn nil, nil\n\t}\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.Brokers = []string{\"invalid:9092\"}\n\tcfg.ProtocolVersion = \"2.0.0\"\n\tcfg.Scrapers = []string{\"topics\"}\n\t_, err := createMetricsReceiver(context.Background(), componenttest.NewNopReceiverCreateSettings(), cfg, nil)\n\tnewMetricsReceiver = prev\n\tassert.Nil(t, err)\n}"} {"input": "package scaffold\n\ntype MockPlatform struct {\n\tRoute *Route\n}\n\nfunc (m *MockPlatform) Routes(r *Router) {\n\tm.Route = &r.route\n}\n\n\n\nfunc NewMockPlatform() *MockPlatform ", "output": "{\n\treturn &MockPlatform{}\n}"} {"input": "package sql\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cockroachdb/cockroach/sql/parser\"\n)\n\n\nfunc (p *planner) Values(n parser.Values) (planNode, error) {\n\tv := &valuesNode{\n\t\trows: make([]parser.DTuple, 0, len(n)),\n\t}\n\tfor _, tuple := range n {\n\t\tdata, err := parser.EvalExpr(tuple, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvals, ok := data.(parser.DTuple)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"expected a tuple, but found %T\", data)\n\t\t}\n\t\tv.rows = append(v.rows, vals)\n\t}\n\treturn v, nil\n}\n\ntype valuesNode struct {\n\tcolumns []string\n\trows []parser.DTuple\n\tnextRow int \n}\n\nfunc (n *valuesNode) Columns() []string {\n\treturn n.columns\n}\n\n\n\nfunc (n *valuesNode) Next() bool {\n\tif n.nextRow >= len(n.rows) {\n\t\treturn false\n\t}\n\tn.nextRow++\n\treturn true\n}\n\nfunc (*valuesNode) Err() error {\n\treturn nil\n}\n\nfunc (n *valuesNode) Values() parser.DTuple ", "output": "{\n\treturn n.rows[n.nextRow-1]\n}"} {"input": "package balanced\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n)\n\ntype Customer struct {\n\tAddress *Address `json:\"address,omitempty\"`\n\tBusinessName string `json:\"business_name,omitempty\"`\n\tCreatedAt time.Time `json:\"created_at,omitempty\"`\n\tDobMonth int `json:\"dob_month,omitempty\"`\n\tDobYear int `json:\"dob_year,omitempty\"`\n\tEin string `json:\"ein,omitempty\"`\n\tEmail string `json:\"email,omitempty\"`\n\tID string `json:\"id,omitempty\"`\n\tMeta map[string]interface{} `json:\"meta,omitempty\"`\n\tName string `json:\"name,omitempty\"`\n\tPhone string `json:\"phone,omitempty\"`\n\tSSNLast4 string `json:\"ssn_last4,omitempty\"`\n\tMerchantStatus string `json:\"merchant_status,omitempty\"`\n}\n\ntype customerResponse struct {\n\tCustomers []*Customer `json:\"customers\"`\n}\n\nfunc (c *Customer) path() string {\n\treturn \"/customers\"\n}\n\nfunc (c *Customer) getID() string {\n\treturn c.ID\n}\n\nfunc (c *Customer) getOwnerPath() string {\n\treturn \"\"\n}\n\nfunc (c *Customer) singleResponse(data []byte) {\n\tparsedResponse := new(customerResponse)\n\tjson.Unmarshal(data, &parsedResponse)\n\t*c = *parsedResponse.Customers[0]\n}\n\n\n\nfunc (c *Customer) IsVerified() bool {\n\treturn c.MerchantStatus == \"underwritten\"\n}\n\nfunc (c *Customer) canDelete() bool ", "output": "{\n\treturn true\n}"} {"input": "package segment\n\nimport . \"github.com/mrcrypt/go-fints/element\"\n\ntype Verarbeitungsvorbereitung struct {\n\tSegment\n\tSegmentkopf *Segmentkopf\n\tBPDVersion *Numeric\n\tUPDVersion *Numeric\n\tDialogsprache *Code\n\tProduktbezeichnung *Alphanumeric\n\tProduktversion *Alphanumeric\n}\n\n\n\nfunc NewVerarbeitungsvorbereitung(segmentNummer int) *Verarbeitungsvorbereitung ", "output": "{\n\tv := &Verarbeitungsvorbereitung{\n\t\tSegmentkopf: NewSegmentkopf(\"HKVVB\", segmentNummer, 2, 0),\n\t\tBPDVersion: NewNumeric(0, 3),\n\t\tUPDVersion: NewNumeric(0, 3),\n\t\tDialogsprache: NewCode(\"1\", 3, []string{\"0\", \"1\", \"2\", \"3\", \"4\"}),\n\t\tProduktbezeichnung: NewAlphanumeric(\"go-fints library\", 25),\n\t\tProduktversion: NewAlphanumeric(\"0.0.1\", 5),\n\t}\n\tv.list = v\n\treturn v\n}"} {"input": "package s0104\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\n\n\nfunc IsAllDigits(s string) bool {\n\tif len(s) < 9 {\n\t\treturn false\n\t}\n\tvar set [9]bool\n\tfor _, r := range s {\n\t\tif r == '0' {\n\t\t\treturn false\n\t\t}\n\t\tif set[r-'1'] {\n\t\t\treturn false\n\t\t}\n\t\tset[r-'1'] = true\n\t}\n\treturn true\n}\n\nfunc Answer() interface{} {\n\tn := 2\n\n\tfCurrBack := int64(1)\n\tfPrevBack := int64(1)\n\n\tfCurrFront := float64(1)\n\tfPrevFront := float64(1)\n\n\tfor {\n\t\tfCurrBack, fPrevBack = (fCurrBack+fPrevBack)%1e9, fCurrBack\n\t\tfCurrFront, fPrevFront = fCurrFront+fPrevFront, fCurrFront\n\t\tif fCurrFront >= 1e9 {\n\t\t\tfCurrFront /= 10\n\t\t\tfPrevFront /= 10\n\t\t}\n\t\tn++\n\t\tif IsAllDigits(fmt.Sprintf(\"%d\", fCurrBack)) &&\n\t\t\tIsAllDigits(fmt.Sprintf(\"%d\", int(fCurrFront))) {\n\t\t\treturn n\n\t\t}\n\t}\n}\n\nfunc Answer_Old() interface{} ", "output": "{\n\tn := 2\n\tfcurr := new(big.Int).SetInt64(1)\n\tfprev := new(big.Int).SetInt64(1)\n\ttmp := new(big.Int)\n\tfor {\n\t\ttmp.Add(fcurr, fprev)\n\t\tfcurr, fprev, tmp = tmp, fcurr, fprev\n\t\tn++\n\t\tstr := fcurr.String()\n\t\tif len(str) >= 9 && IsAllDigits(str[:9]) && IsAllDigits(str[len(str)-9:]) {\n\t\t\treturn n\n\t\t}\n\t}\n}"} {"input": "package pagination\n\n\n\ntype MarkerPage interface {\n\tPage\n\n\tLastMarker() (string, error)\n}\n\n\ntype MarkerPageBase struct {\n\tPageResult\n\n\tOwner MarkerPage\n}\n\n\n\n\nfunc (current MarkerPageBase) NextPageURL() (string, error) ", "output": "{\n\tcurrentURL := current.URL\n\n\tmark, err := current.Owner.LastMarker()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tq := currentURL.Query()\n\tq.Set(\"marker\", mark)\n\tcurrentURL.RawQuery = q.Encode()\n\n\treturn currentURL.String(), nil\n}"} {"input": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"go/format\"\n \"log\"\n \"os\"\n \"strings\"\n)\n\ntype Kind int\n\nconst (\n \n Flat Kind = iota\n \n \n Lutc\n \n \n \n Lutr\n)\n\ntype Generator struct {\n buf bytes.Buffer\n}\n\n\n\nfunc (g *Generator) Generate(pkgName string, kind Kind) {\n g.Printf(\"// automatically generated by avrmakedec %s\\n\", strings.Join(os.Args[1:], \" \"))\n g.Printf(\"// DO NOT EDIT\\n\")\n g.Printf(\"package %s\\n\", pkgName)\n g.Printf(\"import \\\"github.com/kierdavis/avr\\\"\\n\")\n switch kind {\n case Flat:\n g.GenerateFlat()\n case Lutc:\n g.GenerateLutc()\n case Lutr:\n g.GenerateLutr()\n default:\n panic(\"Generator.Generate: bad Kind\")\n }\n}\n\nfunc (g *Generator) Format() []byte {\n src, err := format.Source(g.buf.Bytes())\n if err != nil {\n log.Printf(\"warning: invalid Go generated: %s\\n\", err)\n log.Printf(\"warning: compile the package to analyse the error\\n\")\n return g.buf.Bytes()\n }\n return src\n}\n\nfunc (g *Generator) Printf(format string, args ...interface{}) ", "output": "{\n fmt.Fprintf(&g.buf, format, args...)\n}"} {"input": "package serial\n\nimport (\n\t\"flag\"\n\n\t\"github.com/juju/govmomi/govc/cli\"\n\t\"github.com/juju/govmomi/govc/flags\"\n\t\"golang.org/x/net/context\"\n)\n\ntype disconnect struct {\n\t*flags.VirtualMachineFlag\n\n\tdevice string\n}\n\nfunc init() {\n\tcli.Register(\"device.serial.disconnect\", &disconnect{})\n}\n\n\n\nfunc (cmd *disconnect) Process() error { return nil }\n\nfunc (cmd *disconnect) Run(f *flag.FlagSet) error {\n\tvm, err := cmd.VirtualMachine()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif vm == nil {\n\t\treturn flag.ErrHelp\n\t}\n\n\tdevices, err := vm.Device(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td, err := devices.FindSerialPort(cmd.device)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn vm.EditDevice(context.TODO(), devices.DisconnectSerialPort(d))\n}\n\nfunc (cmd *disconnect) Register(f *flag.FlagSet) ", "output": "{\n\tf.StringVar(&cmd.device, \"device\", \"\", \"serial port device name\")\n}"} {"input": "package godo\n\n\ntype ActionRequest struct {\n\tType string `json:\"type\"`\n\tParams map[string]interface{} `json:\"params,omitempty\"`\n}\n\n\n\n\nfunc (d ActionRequest) String() string ", "output": "{\n\treturn Stringify(d)\n}"} {"input": "package http_test\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"testing\"\n\n\thttpFetcher \"github.com/wanelo/image-server/fetcher/http\"\n\n\t. \"github.com/wanelo/image-server/test\"\n)\n\nfunc TestUniqueFetcher(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"image/jpeg\")\n\t\tfmt.Fprintln(w, `there is some content`)\n\t}))\n\tdefer ts.Close()\n\n\tf := &httpFetcher.Fetcher{}\n\n\tdefer os.Remove(\"valid\")\n\terr := f.Fetch(ts.URL, \"valid\")\n\n\tOk(t, err)\n}\n\nfunc TestUniqueFetcherOnEmptyFiles(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"image/jpeg\")\n\t\tfmt.Fprintf(w, ``)\n\t}))\n\tdefer ts.Close()\n\n\tf := &httpFetcher.Fetcher{}\n\n\tdefer os.Remove(\"blank.jpg\")\n\terr := f.Fetch(ts.URL, \"blank.jpg\")\n\n\tEquals(t, \"File is empty\", fmt.Sprintf(\"%s\", err))\n}\n\n\n\nfunc TestURLEscaping(t *testing.T) ", "output": "{\n\tpath := \"//hell[o]/(x)//two%20words/boo.jpg?something=fo(o)\"\n\texpectedPath := \"/hell[o]/(x)//two%20words/boo.jpg?something=fo(o)\"\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.RequestURI != expectedPath {\n\t\t\tt.Fail()\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"image/jpeg\")\n\t\tfmt.Fprintln(w, `there is some content`)\n\t}))\n\tdefer ts.Close()\n\n\tf := &httpFetcher.Fetcher{}\n\tdefer os.Remove(\"valid\")\n\terr := f.Fetch(ts.URL+path, \"valid\")\n\n\tOk(t, err)\n}"} {"input": "package integration_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/RichardKnop/machinery/v1\"\n\t\"github.com/RichardKnop/machinery/v1/config\"\n)\n\n\n\nfunc TestSQSAmqp(t *testing.T) ", "output": "{\n\tsqsURL := os.Getenv(\"SQS_URL\")\n\tif sqsURL == \"\" {\n\t\tt.Skip(\"SQS_URL is not defined\")\n\t}\n\n\tamqpURL := os.Getenv(\"AMQP_URL\")\n\tif amqpURL == \"\" {\n\t\tt.Skip(\"AMQP_URL is not defined\")\n\t}\n\n\tserver := testSetup(&config.Config{\n\t\tBroker: sqsURL,\n\t\tDefaultQueue: \"test_queue\",\n\t\tResultBackend: amqpURL,\n\t\tLock: \"eager\",\n\t\tAMQP: &config.AMQPConfig{\n\t\t\tExchange: \"test_exchange\",\n\t\t\tExchangeType: \"direct\",\n\t\t\tBindingKey: \"test_task\",\n\t\t\tPrefetchCount: 1,\n\t\t},\n\t})\n\n\tworker := server.(*machinery.Server).NewWorker(\"test_worker\", 0)\n\tdefer worker.Quit()\n\tgo worker.Launch()\n\ttestAll(server, t)\n}"} {"input": "package core \n\n\nfunc IsUserInAdminGroup() int {\n\treturn 0\n}\n\n\n\n\n\nfunc RelaunchAsAdmin() int {\n\treturn 0\n}\n\nfunc IsRunAsAdmin() int ", "output": "{\n\treturn 0\n}"} {"input": "package protolog \n\nimport (\n\t\"os\"\n\n\t\"go.pedge.io/dlog\"\n\t\"go.pedge.io/protolog\"\n)\n\nfunc init() {\n\tdlog.SetLogger(NewLogger(protolog.NewStandardLogger(protolog.NewFileFlusher(os.Stderr))))\n}\n\ntype logger struct {\n\tprotolog.Logger\n}\n\n\nfunc NewLogger(l protolog.Logger) dlog.Logger {\n\treturn &logger{l}\n}\n\nfunc (l *logger) Debug(args ...interface{}) {\n\tl.Debugln(args...)\n}\n\nfunc (l *logger) Info(args ...interface{}) {\n\tl.Infoln(args...)\n}\n\nfunc (l *logger) Warn(args ...interface{}) {\n\tl.Warnln(args...)\n}\n\nfunc (l *logger) Error(args ...interface{}) {\n\tl.Errorln(args...)\n}\n\nfunc (l *logger) Fatal(args ...interface{}) {\n\tl.Fatalln(args...)\n}\n\nfunc (l *logger) Panic(args ...interface{}) {\n\tl.Panicln(args...)\n}\n\n\n\nfunc (l *logger) Print(args ...interface{}) ", "output": "{\n\tl.Println(args...)\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\n\tv1beta1 \"kubevirt.io/client-go/generated/containerized-data-importer/clientset/versioned/typed/core/v1beta1\"\n)\n\ntype FakeCdiV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeCdiV1beta1) CDIs() v1beta1.CDIInterface {\n\treturn &FakeCDIs{c}\n}\n\nfunc (c *FakeCdiV1beta1) CDIConfigs() v1beta1.CDIConfigInterface {\n\treturn &FakeCDIConfigs{c}\n}\n\nfunc (c *FakeCdiV1beta1) DataImportCrons(namespace string) v1beta1.DataImportCronInterface {\n\treturn &FakeDataImportCrons{c, namespace}\n}\n\nfunc (c *FakeCdiV1beta1) DataSources(namespace string) v1beta1.DataSourceInterface {\n\treturn &FakeDataSources{c, namespace}\n}\n\nfunc (c *FakeCdiV1beta1) DataVolumes(namespace string) v1beta1.DataVolumeInterface {\n\treturn &FakeDataVolumes{c, namespace}\n}\n\nfunc (c *FakeCdiV1beta1) ObjectTransfers() v1beta1.ObjectTransferInterface {\n\treturn &FakeObjectTransfers{c}\n}\n\nfunc (c *FakeCdiV1beta1) StorageProfiles() v1beta1.StorageProfileInterface {\n\treturn &FakeStorageProfiles{c}\n}\n\n\n\n\n\nfunc (c *FakeCdiV1beta1) RESTClient() rest.Interface ", "output": "{\n\tvar ret *rest.RESTClient\n\treturn ret\n}"} {"input": "package health\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/centrifugal/centrifuge\"\n)\n\n\ntype Config struct{}\n\n\ntype Handler struct {\n\tnode *centrifuge.Node\n\tconfig Config\n}\n\n\nfunc NewHandler(n *centrifuge.Node, c Config) *Handler {\n\th := &Handler{\n\t\tnode: n,\n\t\tconfig: c,\n\t}\n\treturn h\n}\n\n\n\nfunc (h *Handler) ServeHTTP(w http.ResponseWriter, _ *http.Request) ", "output": "{\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t_, _ = w.Write([]byte(`{}`))\n}"} {"input": "package client\n\nimport (\n\t\"github.com/kubeflow/pipelines/backend/src/common/util\"\n\t\"github.com/kubeflow/pipelines/backend/src/crd/pkg/client/informers/externalversions/scheduledworkflow/v1beta1\"\n\t_ \"k8s.io/client-go/plugin/pkg/client/auth/gcp\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\ntype ScheduledWorkflowClientInterface interface {\n\tGet(namespace string, name string) (swf *util.ScheduledWorkflow, err error)\n}\n\n\ntype ScheduledWorkflowClient struct {\n\tinformer v1beta1.ScheduledWorkflowInformer\n}\n\n\nfunc NewScheduledWorkflowClient(informer v1beta1.ScheduledWorkflowInformer) *ScheduledWorkflowClient {\n\treturn &ScheduledWorkflowClient{\n\t\tinformer: informer,\n\t}\n}\n\n\n\n\n\nfunc (c *ScheduledWorkflowClient) HasSynced() func() bool {\n\treturn c.informer.Informer().HasSynced\n}\n\n\nfunc (c *ScheduledWorkflowClient) Get(namespace string, name string) (\n\tswf *util.ScheduledWorkflow, err error) {\n\tschedule, err := c.informer.Lister().ScheduledWorkflows(namespace).Get(name)\n\tif err != nil {\n\t\tvar code util.CustomCode\n\t\tif util.IsNotFound(err) {\n\t\t\tcode = util.CUSTOM_CODE_NOT_FOUND\n\t\t} else {\n\t\t\tcode = util.CUSTOM_CODE_GENERIC\n\t\t}\n\t\treturn nil, util.NewCustomError(err, code,\n\t\t\t\"Error retrieving scheduled workflow (%v) in namespace (%v): %v\", name, namespace, err)\n\t}\n\n\treturn util.NewScheduledWorkflow(schedule), nil\n}\n\nfunc (c *ScheduledWorkflowClient) AddEventHandler(funcs *cache.ResourceEventHandlerFuncs) ", "output": "{\n\tc.informer.Informer().AddEventHandler(funcs)\n}"} {"input": "package client\n\nimport (\n\t\"time\"\n\n\t\"github.com/jrkt/go-tracing-lab/grpc/interceptors\"\n\tpb \"github.com/jrkt/go-tracing-lab/grpc/weather-search/weather/proto\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\ntype SvcClient struct {\n\tservice pb.WeatherClient\n}\n\nvar (\n\taddress = \"localhost:8002\"\n)\n\n\n\n\nfunc (c SvcClient) SearchByZip(ctx context.Context, token string, zip int64) (*pb.WeatherResponse, error) {\n\treq := &pb.WeatherRequest{Token: token, Zip: zip}\n\n\treturn c.service.GetCurrent(ctx, req)\n}\n\nfunc New() (*SvcClient, error) ", "output": "{\n\n\ttimeout := grpc.WithTimeout(time.Second * 2)\n\n\tg, err := grpc.Dial(address, grpc.WithInsecure(), timeout, interceptors.EnableGRPCTracingDialOption)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := SvcClient{\n\t\tservice: pb.NewWeatherClient(g),\n\t}\n\n\treturn &c, nil\n}"} {"input": "package user\n\nimport (\n\t\"github.com/AitorGuerrero/UserGo/user\"\n)\n\ntype User struct {\n\tId string\n\tPasskey string\n\tToken string\n\tNamespaces []string\n}\n\nfunc FromDomainUser(u user.User) User {\n\treturn User {\n\t\tu.Id().Serialize(),\n\t\tstring(u.Passkey()),\n\t\tu.Token.Serialize(),\n\t\t[]string{},\n\t}\n}\n\n\n\nfunc FromMngUser(mngu User) user.User ", "output": "{\n\tu = user.New(user.ParseId(mngu.Id), user.Passkey(mngu.Passkey))\n\n\treturn u\n}"} {"input": "package internal\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"gopkg.in/reform.v1\"\n)\n\n\ntype Logger struct {\n\tprintf reform.Printf\n\tdebug bool\n}\n\n\n\n\n\nfunc (l *Logger) Debugf(format string, args ...interface{}) {\n\tif l.debug {\n\t\tl.printf(format, args...)\n\t}\n}\n\n\n\nfunc (l *Logger) Printf(format string, args ...interface{}) {\n\tl.printf(format, args...)\n}\n\n\nfunc (l *Logger) Fatalf(format string, args ...interface{}) {\n\tl.printf(format, args...)\n\tif l.debug {\n\t\tpanic(fmt.Sprintf(format, args...))\n\t}\n\tos.Exit(1)\n}\n\nfunc NewLogger(prefix string, debug bool) *Logger ", "output": "{\n\tvar flags int\n\tif debug {\n\t\tflags = log.Ldate | log.Lmicroseconds | log.Lshortfile\n\t}\n\n\tl := log.New(os.Stderr, prefix, flags)\n\treturn &Logger{\n\t\tprintf: func(format string, args ...interface{}) {\n\t\t\tl.Output(3, fmt.Sprintf(format, args...))\n\t\t},\n\t\tdebug: debug,\n\t}\n}"} {"input": "package TeleGogo\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n)\n\nfunc responseToError(response *http.Response) error {\n\treturn responseToTgError(response)\n}\n\n\n\nfunc errToTelegramErr(err error) TelegramError {\n\treturn telegramError{OK: false, ErrorCode: 0, Description: err.Error()}\n}\n\ntype telegramError struct {\n\tOK bool `json:\"ok\"`\n\tErrorCode int `json:\"error_code\"`\n\tDescription string `json:\"description\"`\n}\n\nfunc (t telegramError) IsOK() bool {\n\treturn t.OK\n}\n\nfunc (t telegramError) ErrCode() int {\n\treturn t.ErrorCode\n}\n\nfunc (t telegramError) Error() string {\n\treturn t.Description\n}\n\n\ntype TelegramError interface {\n\tIsOK() bool\n\tErrCode() int\n\tError() string\n}\n\nfunc responseToTgError(response *http.Response) TelegramError ", "output": "{\n\tdefer response.Body.Close()\n\ttgErr := telegramError{}\n\tjson.NewDecoder(response.Body).Decode(&tgErr)\n\treturn tgErr\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\ntype closure func(i, j int) ent\n\ntype ent int\n\n\n\n\nfunc foo(ops closure, j int) (err fmt.Stringer) { \n\tenqueue := func(i int) fmt.Stringer { \n\t\treturn ops(i, j) \n\t}\n\terr = enqueue(4)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn \n}\n\nfunc main() {\n\tf := func(i, j int) ent { \n\t\treturn ent(i + j)\n\t}\n\ti := foo(f, 3).(ent)\n\tfmt.Printf(\"foo(f,3)=%d\\n\", int(i)) \n}\n\nfunc (e ent) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%d\", int(e)) \n}"} {"input": "package imageutil\n\nimport (\n \"bytes\"\n \"encoding/hex\"\n \"crypto/sha256\"\n \"testing\"\n)\n\n\n\nfunc TestRgbaToPng(t *testing.T) {\n image, err := ReadRgbaPng(\"test_data/fruits.png\")\n if err != nil {\n t.Fatal(err)\n }\n\n err = RgbaToPng(image.Pix, image.Bounds().Dx(), image.Bounds().Dy(),\n \"test_tmp/fruits_RgbaToPng.png\")\n if err != nil {\n t.Fatal(err)\n }\n\n recodedImage, err := ReadRgbaPng(\"test_tmp/fruits_RgbaToPng.png\")\n if err != nil {\n t.Fatal(err)\n }\n if !bytes.Equal(image.Pix, recodedImage.Pix) {\n t.Error(\"Pixel data mismatch\")\n }\n}\n\nfunc TestReadRgbaPng(t *testing.T) ", "output": "{\n goldImageHash :=\n \"d333fb91aa05709483df2d00f62e3caa91db0be1b30ff72e8e829f3264cb30b9\"\n\n image, err := ReadRgbaPng(\"test_data/fruits.png\")\n if err != nil {\n t.Fatal(err)\n }\n\n if image.Rect.Min.X != 0 || image.Rect.Max.X != 512 ||\n image.Rect.Min.Y != 0 || image.Rect.Max.Y != 512 {\n t.Errorf(\"Incorrect image rectangle: %v\\n\", image.Rect)\n }\n\n hash := sha256.Sum256(image.Pix)\n imageHash := hex.EncodeToString(hash[:])\n if imageHash != goldImageHash {\n t.Error(\"Pixel data hash mismatch. Got :\", imageHash)\n }\n}"} {"input": "package arm\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest/azure\"\n\t\"github.com/mitchellh/packer/builder/azure/common\"\n)\n\ntype configRetriever struct {\n\tfindTenantID func(azure.Environment, string) (string, error)\n}\n\nfunc newConfigRetriever() configRetriever {\n\treturn configRetriever{common.FindTenantID}\n}\n\n\n\nfunc (cr configRetriever) FillParameters(c *Config) error ", "output": "{\n\tif c.TenantID == \"\" {\n\t\ttenantID, err := cr.findTenantID(*c.cloudEnvironment, c.SubscriptionID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.TenantID = tenantID\n\t}\n\treturn nil\n}"} {"input": "package post\n\nimport \"github.com/barnex/bruteray/imagef\"\n\ntype Params struct {\n\tGaussian BloomParams\n\tAiry BloomParams\n\tStar BloomParams\n}\n\ntype BloomParams struct {\n\tRadius float64\n\tAmplitude float64\n\tThreshold float64\n}\n\nfunc (p *Params) ApplyTo(img imagef.Image, pixelSize float64) imagef.Image {\n\tif b := p.Gaussian; b.Radius != 0 {\n\t\timg = ApplyGaussianBloom(img, pixelSize, b.Radius, b.Amplitude, b.Threshold)\n\t}\n\tif b := p.Airy; b.Radius != 0 {\n\t\timg = ApplyAiryBloom(img, pixelSize, b.Radius, b.Amplitude, b.Threshold)\n\t}\n\tif b := p.Star; b.Radius != 0 {\n\t\timg = ApplyStarBloom(img, pixelSize, b.Radius, b.Amplitude, b.Threshold)\n\t}\n\treturn img\n}\n\n\n\nfunc ApplyAiryBloom(img imagef.Image, pixelSize, radius, amplitude, threshold float64) imagef.Image {\n\twidthPix := radius / pixelSize\n\tnumPix := int(8*widthPix) + 1\n\tK := Airy(numPix, widthPix)\n\timg2 := img.Copy()\n\tAddConvolution(img2, img, K, amplitude, threshold)\n\treturn img2\n}\n\nfunc ApplyStarBloom(img imagef.Image, pixelSize, radius, amplitude, threshold float64) imagef.Image {\n\twidthPix := radius / pixelSize\n\tnumPix := int(widthPix)\n\tK := starKernel(numPix)\n\timg2 := img.Copy()\n\tAddConvolution(img2, img, K, amplitude, threshold)\n\treturn img2\n}\n\nfunc ApplyGaussianBloom(img imagef.Image, pixelSize, radius, amplitude, threshold float64) imagef.Image ", "output": "{\n\twidthPix := radius / pixelSize\n\tnumPix := int(5*widthPix) + 1\n\tK := Gaussian(numPix, widthPix)\n\timg2 := img.Copy()\n\tAddConvolution(img2, img, K, amplitude, threshold)\n\treturn img2\n}"} {"input": "package resources\n\nimport (\n\tlog \"github.com/sirupsen/logrus\"\n\n\tlibapiv3 \"github.com/projectcalico/calico/libcalico-go/lib/apis/v3\"\n\tcnet \"github.com/projectcalico/calico/libcalico-go/lib/net\"\n)\n\n\n\n\n\nfunc FindNodeAddress(node *libapiv3.Node, ipType string) (*cnet.IP, *cnet.IPNet) ", "output": "{\n\tfor _, addr := range node.Spec.Addresses {\n\t\tif addr.Type == ipType {\n\t\t\tip, cidr, err := cnet.ParseCIDROrIP(addr.Address)\n\t\t\tif err == nil {\n\t\t\t\tif ip.To4() == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlog.WithFields(log.Fields{\"ip\": ip, \"cidr\": cidr}).Debug(\"Parsed IPv4 address\")\n\t\t\t\treturn ip, cidr\n\t\t\t} else {\n\t\t\t\tlog.WithError(err).WithField(\"IPv4Address\", addr.Address).Warn(\"Failed to parse IPv4Address\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, nil\n}"} {"input": "package testutil\n\nimport (\n\t\"reflect\"\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n\n\t\"google.golang.org/appengine/aetest\"\n)\n\n\ntype TestContainer struct {\n\tt *testing.T\n\tinst aetest.Instance\n\ttests []testing.InternalTest\n}\n\n\n\n\n\nfunc (tc *TestContainer) AddTest(f func(t *testing.T)) {\n\tname := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()\n\ttc.tests = append(tc.tests, testing.InternalTest{Name: name, F: f})\n}\n\n\nfunc (tc *TestContainer) RunTest() {\n\tdefer func() {\n\t\tif err := tc.inst.Close(); err != nil {\n\t\t\ttc.t.Fatal(err)\n\t\t}\n\t}()\n\n\tconst (\n\t\tsuccess = \"SUCCESS\"\n\t\tfaild = \"FAILED\"\n\t)\n\ttype testResult struct {\n\t\tname, ret string\n\t}\n\ttrs := make([]*testResult, len(tc.tests))\n\n\ttc.t.Logf(\"App Engine Test start to run at %s\\n\", time.Now())\n\tfor i, test := range tc.tests {\n\t\tname := test.Name\n\t\ttr := &testResult{name, success}\n\t\tok := tc.t.Run(name, test.F)\n\t\tif !ok {\n\t\t\ttr.ret = faild\n\t\t}\n\t\ttrs[i] = tr\n\t}\n\n\ttc.t.Log(\"Test Result\")\n\tfor _, tr := range trs {\n\t\ttc.t.Logf(\"Test %s: %s\\n\", tr.name, tr.ret)\n\t}\n\n\ttc.t.Logf(\"App Engine Test end at %s\\n\", time.Now())\n}\n\nfunc NewTestContiner(t *testing.T, appID string, stronglyConsistent bool) (*TestContainer, error) ", "output": "{\n\tif appID == \"\" {\n\t\tappID = \"tetapp\"\n\t}\n\n\tinst, err := aetest.NewInstance(&aetest.Options{AppID: appID, StronglyConsistentDatastore: stronglyConsistent})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TestContainer{\n\t\tt: t,\n\t\tinst: inst,\n\t}, nil\n}"} {"input": "package variant\n\nimport (\n\t\"github.com/go-ole/com/errors\"\n\t\"github.com/go-ole/com/types\"\n)\n\nfunc VariantInit(v *types.Variant) error {\n\treturn errors.NotImplementedError\n}\n\n\n\nfunc VariantChangeType(source *types.Variant, flags uint16, vt types.VariantType) *types.Variant {\n\treturn source\n}\n\nfunc VariantChangeTypeEx(source *types.Variant, locale uint32, flags uint16, vt types.VariantType) *types.Variant {\n\treturn source\n}\n\nfunc VariantCopy(source *types.Variant) *types.Variant {\n\treturn source\n}\n\nfunc VariantCopyIndirect(source *types.Variant) *types.Variant {\n\treturn source\n}\n\nfunc VariantClear(v *types.Variant) error ", "output": "{\n\treturn errors.NotImplementedError\n}"} {"input": "package gorma_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/goadesign/gorma\"\n)\n\nfunc TestStorageGroupContext(t *testing.T) {\n\tsg := &gorma.StorageGroupDefinition{}\n\tsg.Name = \"SG\"\n\n\tc := sg.Context()\n\texp := fmt.Sprintf(\"StorageGroup %#v\", sg.Name)\n\tif c != exp {\n\t\tt.Errorf(\"Expected %s, got %s\", exp, c)\n\t}\n\n\tsg.Name = \"\"\n\n\tc = sg.Context()\n\texp = \"unnamed Storage Group\"\n\tif c != exp {\n\t\tt.Errorf(\"Expected %s, got %s\", exp, c)\n\t}\n}\n\n\n\nfunc TestStorageGroupDSL(t *testing.T) ", "output": "{\n\tsg := &gorma.StorageGroupDefinition{}\n\tf := func() {\n\t\treturn\n\t}\n\tsg.DefinitionDSL = f\n\tc := sg.DSL()\n\tif c == nil {\n\t\tt.Errorf(\"Expected %T, got nil\", f)\n\t}\n\n}"} {"input": "package responsewriter\n\n\n\n\ntype ErrBodyFlushedBeforeCode struct{}\n\n\nfunc (e ErrBodyFlushedBeforeCode) Error() string {\n\treturn \"body flushed before code\"\n}\n\n\n\n\ntype ErrCodeFlushedBeforeHeaders struct{}\n\n\n\n\nfunc (e ErrCodeFlushedBeforeHeaders) Error() string ", "output": "{\n\treturn \"code flushed before headers\"\n}"} {"input": "package weighted\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/AsynkronIT/protoactor-go/cluster\"\n)\n\ntype WeightedMemberStatusValue struct {\n\tWeight int\n}\n\n\n\ntype WeightedMemberStatusValueSerializer struct{}\n\nfunc (s *WeightedMemberStatusValueSerializer) ToValueBytes(val cluster.MemberStatusValue) []byte {\n\tdVal, _ := val.(*WeightedMemberStatusValue)\n\treturn []byte(strconv.Itoa(dVal.Weight))\n}\n\nfunc (s *WeightedMemberStatusValueSerializer) FromValueBytes(val []byte) cluster.MemberStatusValue {\n\tweight, _ := strconv.Atoi(string(val))\n\treturn &WeightedMemberStatusValue{Weight: weight}\n}\n\nfunc (sv *WeightedMemberStatusValue) IsSame(val cluster.MemberStatusValue) bool ", "output": "{\n\tif val == nil {\n\t\treturn false\n\t}\n\tif v, ok := val.(*WeightedMemberStatusValue); ok {\n\t\treturn sv.Weight == v.Weight\n\t}\n\treturn false\n}"} {"input": "package helpers\n\nimport (\n\t\"fmt\"\n\t\"os/user\"\n\t\"os\"\n\t\"runtime\"\n\t\"time\"\n\t\"log\"\n\t\"github.com/joho/godotenv\"\n)\n\nfunc CurrentUser() *user.User {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tSendErrorEmail(\"golang balu\", fmt.Sprintf(\"failed get current user: %s\", err))\n\t\tpanic(err)\n\t}\n\treturn usr\n}\n\n\n\nfunc MonitorRuntime() {\n\tlog.Println(\"Number of CPUs:\", runtime.NumCPU())\n\tm := &runtime.MemStats{}\n\tfor {\n\t\tr := runtime.NumGoroutine()\n\t\tlog.Println(\"Number of goroutines\", r)\n\t\truntime.ReadMemStats(m)\n\t\tlog.Println(\"Allocated memory\", m.Alloc)\n\t\ttime.Sleep(10 * time.Second)\n\t}\n}\n\nfunc LoadEnvFile() {\n\terr := godotenv.Load()\n\tif err != nil {\n\t\tpanic(\"Error loading .env file\" + err.Error())\n\t}\n}\n\nfunc IsDocker() bool ", "output": "{\n\treturn os.Getenv(\"HOME\") == \"/root\"\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"koding/klientctl/config\"\n\t\"koding/klientctl/ctlcli\"\n\n\t\"github.com/koding/logging\"\n\tcli \"gopkg.in/urfave/cli.v1\"\n)\n\nfunc init() {\n\trand.Seed(time.Now().Unix())\n}\n\n\n\n\n\nfunc CheckUpdateFirst(f ctlcli.ExitingCommand, log logging.Logger, cmd string) (ctlcli.ExitingCommand, logging.Logger, string) {\n\n\texitCmd := func(c *cli.Context, log logging.Logger, cmd string) int {\n\t\tif !c.Bool(\"json\") {\n\t\t\tu := NewCheckUpdate()\n\t\t\tif y, err := u.IsUpdateAvailable(); y && err == nil {\n\t\t\t\tfmt.Printf(\"A newer version of %s is available. Please do `sudo %s update`.\\n\", config.Name, config.Name)\n\t\t\t}\n\t\t}\n\n\t\treturn f(c, log, cmd)\n\t}\n\n\treturn exitCmd, log, cmd\n}\n\n\ntype CheckUpdate struct {\n\tLocation string\n\n\tRandomSeededNumber int\n\n\tForceCheck bool\n\n\tLocalVersion int\n}\n\n\nfunc NewCheckUpdate() *CheckUpdate {\n\treturn &CheckUpdate{\n\t\tLocalVersion: config.VersionNum(),\n\t\tLocation: config.Konfig.Endpoints.KDLatest.Public.String(),\n\t\tRandomSeededNumber: rand.Intn(3),\n\t\tForceCheck: false,\n\t}\n}\n\n\n\n\nfunc (c *CheckUpdate) IsUpdateAvailable() (bool, error) ", "output": "{\n\tresp, err := http.Get(c.Location)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar newVersion int\n\n\t_, err = fmt.Fscanf(resp.Body, \"%d\", &newVersion)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn newVersion > c.LocalVersion, nil\n}"} {"input": "package grpc\n\nimport (\n\t\"github.com/micro/go-micro/v3/client\"\n)\n\ntype grpcEvent struct {\n\ttopic string\n\tcontentType string\n\tpayload interface{}\n}\n\n\n\nfunc (g *grpcEvent) ContentType() string {\n\treturn g.contentType\n}\n\nfunc (g *grpcEvent) Topic() string {\n\treturn g.topic\n}\n\nfunc (g *grpcEvent) Payload() interface{} {\n\treturn g.payload\n}\n\nfunc newGRPCEvent(topic string, payload interface{}, contentType string, opts ...client.MessageOption) client.Message ", "output": "{\n\tvar options client.MessageOptions\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\tif len(options.ContentType) > 0 {\n\t\tcontentType = options.ContentType\n\t}\n\n\treturn &grpcEvent{\n\t\tpayload: payload,\n\t\ttopic: topic,\n\t\tcontentType: contentType,\n\t}\n}"} {"input": "package action\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/Masterminds/glide/msg\"\n)\n\n\n\nfunc TestAbout(t *testing.T) ", "output": "{\n\tvar buf bytes.Buffer\n\told := msg.Default.Stdout\n\tmsg.Default.Stdout = &buf\n\tAbout()\n\n\tif buf.Len() < len(aboutMessage) {\n\t\tt.Errorf(\"expected this to match aboutMessage: %q\", buf.String())\n\t}\n\n\tmsg.Default.Stdout = old\n}"} {"input": "package dbschema\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/gogolfing/dbschema/refactor\"\n)\n\n\n\nfunc iterateChangeSetRows(\n\tchangeLog *refactor.ChangeLog,\n\tcsrows []*ChangeSetRow,\n\tcallback func(before []*refactor.ChangeSet, csr *ChangeSetRow) error,\n) error {\n\tprevId := \"\"\n\tfor _, csr := range csrows {\n\t\tchangeSetsBefore := changeLog.ChangeSetsSubSlice(prevId, csr.Id)\n\n\t\terr := callback(changeSetsBefore, csr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tprevId = csr.Id\n\t}\n\n\treturn nil\n}\n\nfunc collectingAppliedChangeSets(w io.Writer) ", "output": "{\n\tfmt.Fprintln(w, \"Collecting applied ChangeSets...\\n\")\n}"} {"input": "package logwise\n\nimport (\n \"fmt\"\n \"os\"\n)\n\ntype Writer interface {\n Write(lines []string)\n}\n\ntype FileWriter struct {\n FilePath string\n Append bool\n Prefix string\n Postfix string\n}\n\nfunc NewFileWriter(filePath string, append bool, prefix,sufix string) Writer {\n return &FileWriter{filePath, append, prefix, sufix}\n}\n\nfunc (w *FileWriter) AddPrefix(prefix string) *FileWriter {\n w.Prefix = prefix\n return w\n}\n\n\n\nfunc (w *FileWriter) Write(lines []string) {\n var flags int\n\n if w.Append {\n flags = os.O_WRONLY | os.O_APPEND\n } else {\n flags = os.O_CREATE | os.O_WRONLY | os.O_TRUNC\n }\n\n file,_ := os.OpenFile(w.FilePath, flags, 0666)\n defer file.Close()\n \n if w.Prefix != \"\" {\n file.WriteString(fmt.Sprintf(\"%v\\n\", w.Prefix))\n }\n\n for _,line := range lines {\n file.WriteString(fmt.Sprintf(\"%v\\n\", line))\n }\n\n if w.Postfix != \"\" {\n file.WriteString(fmt.Sprintf(\"%v\\n\", w.Postfix))\n }\n}\n\nfunc (w *FileWriter) AddPostfix(postfix string) *FileWriter ", "output": "{\n w.Postfix = postfix\n return w\n}"} {"input": "package signed\n\nimport (\n\t\"testing\"\n\n\t\"github.com/docker/notary/tuf/data\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\n\nfunc TestListKeys(t *testing.T) ", "output": "{\n\tc := NewEd25519()\n\ttskey, err := c.Create(data.CanonicalTimestampRole, data.ED25519Key)\n\tassert.NoError(t, err)\n\n\t_, err = c.Create(data.CanonicalRootRole, data.ED25519Key)\n\tassert.NoError(t, err)\n\n\ttsKeys := c.ListKeys(data.CanonicalTimestampRole)\n\tassert.Len(t, tsKeys, 1)\n\tassert.Equal(t, tskey.ID(), tsKeys[0])\n\n\tassert.Len(t, c.ListKeys(data.CanonicalTargetsRole), 0)\n}"} {"input": "package util\n\nimport \"log\"\n\n\n\n\n\nfunc ShowMapOfStrings(m map[string]string, desc string) {\n\tlog.Printf(\"%s\\n\", desc)\n\tfor k, v := range m {\n\t\tlog.Printf(\" %s: %s\\n\", k, v)\n\t}\n\tlog.Printf(\"\\n\")\n}\n\n\nfunc ShowMapOfStringArray(m map[string][]string, desc string) {\n\tlog.Printf(\"%s\\n\", desc)\n\tfor k, v := range m {\n\t\tShowStringArray(v, k)\n\t}\n\tlog.Printf(\"\\n\")\n}\n\nfunc ShowStringArray(strArray []string, desc string) ", "output": "{\n\tlog.Printf(\"%s\\n\", desc)\n\tfor _, v := range strArray {\n\t\tlog.Printf(\" %s\\n\", v)\n\t}\n\tlog.Printf(\"\\n\")\n}"} {"input": "package hooks\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"regexp\"\n\n\t\"github.com/cloudfoundry/libbuildpack\"\n)\n\ntype AppHook struct {\n\tlibbuildpack.DefaultHook\n}\n\n\n\nfunc (h AppHook) BeforeCompile(compiler *libbuildpack.Stager) error {\n\treturn runHook(\"pre_compile\", compiler)\n}\n\nfunc (h AppHook) AfterCompile(compiler *libbuildpack.Stager) error {\n\treturn runHook(\"post_compile\", compiler)\n}\n\nfunc runHook(scriptName string, compiler *libbuildpack.Stager) error {\n\tpath := filepath.Join(compiler.BuildDir(), \"bin\", scriptName)\n\tif exists, err := libbuildpack.FileExists(path); err != nil {\n\t\treturn err\n\t} else if exists {\n\t\tcompiler.Logger().BeginStep(\"Running \" + scriptName + \" hook\")\n\t\tif err := os.Chmod(path, 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfileContents, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tshebangRegex := regexp.MustCompile(\"^\\\\s*#!\")\n\t\thasShebang := shebangRegex.Match(fileContents)\n\n\t\tvar cmd *exec.Cmd\n\t\tif hasShebang {\n\t\t\tcmd = exec.Command(path)\n\t\t} else {\n\t\t\tcmd = exec.Command(\"/bin/sh\", path)\n\t\t}\n\n\t\tcmd.Dir = compiler.BuildDir()\n\t\toutput, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcompiler.Logger().Info(\"%s\", output)\n\t}\n\treturn nil\n\n}\n\nfunc init() ", "output": "{\n\tlibbuildpack.AddHook(AppHook{})\n}"} {"input": "package gorilla\n\nimport (\n\t\"net/http\"\n\n\tgcontext \"github.com/gorilla/context\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\n\n\ntype wrapper struct {\n\tcontext.Context\n\treq *http.Request\n}\n\ntype key int\n\nconst reqKey key = 0\n\n\n\nfunc (ctx *wrapper) Value(key interface{}) interface{} {\n\tif key == reqKey {\n\t\treturn ctx.req\n\t}\n\tif val, ok := gcontext.GetOk(ctx.req, key); ok {\n\t\treturn val\n\t}\n\treturn ctx.Context.Value(key)\n}\n\n\n\nfunc HTTPRequest(ctx context.Context) (*http.Request, bool) {\n\treq, ok := ctx.Value(reqKey).(*http.Request)\n\treturn req, ok\n}\n\nfunc NewContext(parent context.Context, req *http.Request) context.Context ", "output": "{\n\treturn &wrapper{parent, req}\n}"} {"input": "package leetcode\n\nconst MAX_INT32 = 1<<31 - 1\nconst MIN_INT32 = -1 << 31\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\nfunc maxInt(a, b int) int {\n\tif a < b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}\n\nfunc minInt(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}\n\nfunc absInt(num int) int {\n\tif num > 0 {\n\t\treturn num\n\t} else {\n\t\treturn -num\n\t}\n}\n\nfunc qsortInt(nums []int) []int {\n\tif len(nums) <= 1 {\n\t\treturn nums\n\t}\n\n\thead, tail := 0, len(nums)-1\n\tidx, mid := 1, nums[0]\n\tfor head < tail {\n\t\tif nums[idx] > mid {\n\t\t\tnums[idx], nums[tail] = nums[tail], nums[idx]\n\t\t\ttail--\n\t\t} else {\n\t\t\tnums[idx], nums[head] = nums[head], nums[idx]\n\t\t\thead++\n\t\t\tidx++\n\t\t}\n\t}\n\tnums[head] = mid\n\tqsortInt(nums[:head])\n\tqsortInt(nums[head+1:])\n\treturn nums\n}\n\ntype Stack struct {\n\tdata []rune\n}\n\n\n\nfunc (s *Stack) pop() rune {\n\tif len(s.data) == 0 {\n\t\treturn 0\n\t}\n\tret := s.data[len(s.data)-1]\n\ts.data = s.data[:len(s.data)-1]\n\treturn ret\n}\n\nfunc (s Stack) empty() bool {\n\treturn len(s.data) == 0\n}\n\nfunc (s *Stack) push(data rune) ", "output": "{\n\ts.data = append(s.data, data)\n}"} {"input": "package proc\n\nconst (\n\tUPTIME_FORMAT = \"%f %f\\n\"\n\tUPTIME_FILE = \"/proc/uptime\"\n)\n\ntype Uptime struct {\n\tUp float64\n\tIdle float64\n}\n\nfunc (u *Uptime) Get() error {\n\tn, err := getvalues(UPTIME_FILE, UPTIME_FORMAT,\n\t\t&u.Up,\n\t\t&u.Idle)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n == 0 {\n\t\treturn ErrEmpty\n\t}\n\treturn nil\n}\n\n\n\nfunc UpTime() float64 ", "output": "{\n\tu := Uptime{}\n\terr := u.Get()\n\tif err != nil {\n\t\treturn float64(0)\n\t}\n\treturn u.Up\n}"} {"input": "package sources\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/GoogleCloudPlatform/heapster/sources/api\"\n\t\"github.com/GoogleCloudPlatform/heapster/sources/nodes\"\n\t\"github.com/stretchr/testify/require\"\n)\n\ntype fakePodsApi struct {\n\tpodList []api.Pod\n}\n\nfunc (self *fakePodsApi) List(nodeList *nodes.NodeList) ([]api.Pod, error) {\n\treturn self.podList, nil\n}\n\nfunc (self *fakePodsApi) DebugInfo() string {\n\treturn \"\"\n}\n\n\n\nfunc TestKubePodMetricsFull(t *testing.T) {\n\tnodeList := nodes.NodeList{\n\t\tItems: map[nodes.Host]nodes.Info{\n\t\t\tnodes.Host(\"test-machine-b\"): {InternalIP: \"10.10.10.1\"},\n\t\t\tnodes.Host(\"test-machine-1\"): {InternalIP: \"10.10.10.0\"},\n\t\t},\n\t}\n\tpodList := []api.Pod{\n\t\t{\n\t\t\tName: \"blah\",\n\t\t},\n\t\t{\n\t\t\tName: \"blah1\",\n\t\t},\n\t}\n\tcontainer := &api.Container{\n\t\tName: \"test\",\n\t}\n\tnodesApi := &fakeNodesApi{nodeList}\n\tpodsApi := &fakePodsApi{podList}\n\tkubeletApi := &fakeKubeletApi{container}\n\tsource := NewKubePodMetrics(\"10250\", nodesApi, podsApi, kubeletApi)\n\tdata, err := source.GetInfo(time.Now(), time.Now().Add(time.Minute), time.Second)\n\trequire.NoError(t, err)\n\trequire.NotEmpty(t, data)\n}\n\nfunc TestKubePodMetricsBasic(t *testing.T) ", "output": "{\n\tnodesApi := &fakeNodesApi{nodes.NodeList{}}\n\tpodsApi := &fakePodsApi{[]api.Pod{}}\n\tsource := NewKubePodMetrics(\"10250\", nodesApi, podsApi, &fakeKubeletApi{nil})\n\t_, err := source.GetInfo(time.Now(), time.Now().Add(time.Minute), time.Second)\n\trequire.NoError(t, err)\n\trequire.NotEmpty(t, source.DebugInfo())\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\ta := []int{7, 2, 8, -9, 4, 0}\n\n\tc := make(chan int)\n\tgo sum(a[:len(a)/2], c)\n\tgo sum(a[len(a)/2:], c)\n\tx := <-c\n\ty := <-c \n\tfmt.Println(x, y, x+y)\n}\n\nfunc sum(a []int, c chan int) ", "output": "{\n\ttotal := 0\n\tfor _, v := range a {\n\t\ttotal += v\n\t}\n\tc <- total \n\tfmt.Println(total)\n}"} {"input": "package expr\n\ntype (\n\tGRPCExpr struct {\n\t\tServices []*GRPCServiceExpr\n\t\tErrors []*GRPCErrorExpr\n\t}\n)\n\n\nfunc (g *GRPCExpr) Service(name string) *GRPCServiceExpr {\n\tfor _, res := range g.Services {\n\t\tif res.Name() == name {\n\t\t\treturn res\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\nfunc (g *GRPCExpr) ServiceFor(s *ServiceExpr) *GRPCServiceExpr {\n\tif res := g.Service(s.Name); res != nil {\n\t\treturn res\n\t}\n\tres := &GRPCServiceExpr{\n\t\tServiceExpr: s,\n\t}\n\tg.Services = append(g.Services, res)\n\treturn res\n}\n\n\n\n\nfunc (g *GRPCExpr) EvalName() string ", "output": "{\n\treturn \"API GRPC\"\n}"} {"input": "package container\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/martin-helmich/distcrond/domain\"\n)\n\ntype JobContainer struct {\n\tjobs []domain.Job\n\tjobsByName map[string]*domain.Job\n}\n\nfunc NewJobContainer(initialCapacity int) *JobContainer {\n\tcontainer := new(JobContainer)\n\tcontainer.jobs = make([]domain.Job, 0, initialCapacity)\n\tcontainer.jobsByName = make(map[string]*domain.Job)\n\treturn container\n}\n\nfunc (c *JobContainer) AddJob(job domain.Job) {\n\tc.jobs = append(c.jobs, job)\n\tc.jobsByName[job.Name] = &c.jobs[len(c.jobs)-1]\n}\n\n\n\nfunc (c *JobContainer) All() []domain.Job {\n\treturn c.jobs\n}\n\nfunc (c *JobContainer) Get(i int) *domain.Job {\n\treturn &c.jobs[i]\n}\n\nfunc (c *JobContainer) JobByName(n string) (*domain.Job, error) {\n\tif job, ok := c.jobsByName[n]; !ok {\n\t\treturn nil, errors.New(fmt.Sprintf(\"No job with name '%s' is known\", n))\n\t} else {\n\t\treturn job, nil\n\t}\n}\n\nfunc (c *JobContainer) Count() int ", "output": "{\n\treturn len(c.jobs)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"golang.org/x/net/html\"\n\t\"io\"\n\t\"strings\"\n)\n\n\nconst htmldata = `\n\n\nPage Title\n\n\n\n

This is a Heading1

\n

This is a paragraph.

\n\n

This is a Heading2

\n\n\n
`\n\nfunc main() {\n\n\thtmlReader := strings.NewReader(htmldata)\n\tallText := html2rawtext(htmlReader)\n\n\tfmt.Println(allText)\n\n}\n\n\n\nfunc cleanNonPrintChar(text string) string {\n\n\tclean := make([]rune, 0, len(text))\n\tvar prev rune\n\tfor _, t := range text {\n\t\tif t < 32 { \n\t\t\tt = 32\n\t\t}\n\t\tif !(t == 32 && prev == 32) {\n\t\t\tclean = append(clean, t)\n\t\t\tprev = t\n\t\t}\n\t}\n\n\treturn string(clean)\n\n}\n\nfunc html2rawtext(htmlReader io.Reader) string ", "output": "{\n\n\tz := html.NewTokenizer(htmlReader)\n\n\talltext := func(z *html.Tokenizer) []string {\n\t\tvar alltext []string\n\t\tfor {\n\n\t\t\ttt := z.Next()\n\n\t\t\tif tt == html.ErrorToken {\n\t\t\t\treturn alltext\n\t\t\t}\n\t\t\tif tt == html.TextToken {\n\t\t\t\tt := z.Token()\n\n\t\t\t\talltext = append(alltext, t.Data)\n\n\t\t\t}\n\t\t}\n\t}(z)\n\n\treturn cleanNonPrintChar(strings.Join(alltext, \" \"))\n}"} {"input": "package helpers\n\nimport (\n\t\"os\"\n\t\"strconv\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc SkipIfClientCredentialsNotSet() (string, string) {\n\tprivateClientID := os.Getenv(\"CF_INT_CLIENT_ID\")\n\tprivateClientSecret := os.Getenv(\"CF_INT_CLIENT_SECRET\")\n\n\tif privateClientID == \"\" || privateClientSecret == \"\" {\n\t\tSkip(\"CF_INT_CLIENT_ID or CF_INT_CLIENT_SECRET is not set\")\n\t}\n\n\treturn privateClientID, privateClientSecret\n}\n\n\n\nfunc SkipIfCustomClientCredentialsNotSet() (string, string) {\n\tcustomClientID := os.Getenv(\"CF_INT_CUSTOM_CLIENT_ID\")\n\tcustomClientSecret := os.Getenv(\"CF_INT_CUSTOM_CLIENT_SECRET\")\n\n\tif customClientID == \"\" || customClientSecret == \"\" {\n\t\tSkip(\"CF_INT_CUSTOM_CLIENT_ID or CF_INT_CUSTOM_CLIENT_SECRET is not set\")\n\t}\n\n\treturn customClientID, customClientSecret\n}\n\n\n\nfunc ClientCredentialsTestMode() bool {\n\tenvVar := os.Getenv(\"CF_INT_CLIENT_CREDENTIALS_TEST_MODE\")\n\n\tif envVar == \"\" {\n\t\treturn false\n\t}\n\n\ttestMode, err := strconv.ParseBool(envVar)\n\tExpect(err).ToNot(HaveOccurred(), \"CF_INT_CLIENT_CREDENTIALS_TEST_MODE should be boolean\")\n\n\treturn testMode\n}\n\nfunc SkipIfClientCredentialsTestMode() ", "output": "{\n\tif ClientCredentialsTestMode() {\n\t\tSkip(\"CF_INT_CLIENT_CREDENTIALS_TEST_MODE is enabled\")\n\t}\n}"} {"input": "package lwmq\n\nimport (\n\t\"fmt\"\n)\n\n\ntype MessageStore interface {\n\n\tMessages(*Queue) ([]*Message, error)\n\n\tAddMessage(*Message) error\n\n\tPopMessages(*Queue) ([]*Message, error)\n}\n\n\ntype MemoryMessageStore struct {\n\tmessages map[*Queue][]*Message\n}\n\nfunc NewMemoryMessageStore() *MemoryMessageStore {\n\ts := &MemoryMessageStore{\n\t\tmessages: make(map[*Queue][]*Message),\n\t}\n\treturn s\n}\n\n\n\n\n\n\n\nfunc (self *MemoryMessageStore) Messages(q *Queue) ([]*Message, error) {\n\tmessages, ok := self.messages[q]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Unknown queue: %s\", q.Id)\n\t}\n\n\treturn messages, nil\n}\n\n\nfunc (self *MemoryMessageStore) PopMessages(q *Queue) ([]*Message, error) {\n\tmessages, err := self.Messages(q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tself.messages[q] = []*Message{}\n\n\treturn messages, nil\n}\n\nfunc (self *MemoryMessageStore) AddMessage(msg *Message) error ", "output": "{\n\tif msg.Queue == nil {\n\t\terr := fmt.Errorf(\"Can not store message without a queue\")\n\t\treturn err\n\t}\n\n\tmsg.Offline = true\n\n\tself.messages[msg.Queue] = append(self.messages[msg.Queue], msg)\n\n\treturn nil\n}"} {"input": "package openssl\n\nimport (\n\t\"net/http\"\n)\n\n\n\n\n\n\n\nfunc ServerListenAndServeTLS(srv *http.Server,\n\tcert_file, key_file string) error {\n\taddr := srv.Addr\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tctx, err := NewCtxFromFiles(cert_file, key_file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tl, err := Listen(\"tcp\", addr, ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn srv.Serve(l)\n}\n\nfunc ListenAndServeTLS(addr string, cert_file string, key_file string,\n\thandler http.Handler) error ", "output": "{\n\treturn ServerListenAndServeTLS(\n\t\t&http.Server{Addr: addr, Handler: handler}, cert_file, key_file)\n}"} {"input": "package mobileengagement\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype ManagementClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) ManagementClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient ", "output": "{\n\treturn ManagementClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package environs\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"launchpad.net/juju-core/cert\"\n\t\"launchpad.net/juju-core/environs/config\"\n)\n\ntype CreatedCert bool\n\nconst (\n\tCertCreated CreatedCert = true\n\tCertExists CreatedCert = false\n)\n\n\n\nfunc WriteCertAndKey(name string, cert, key []byte) error {\n\tjujuHome := config.JujuHome()\n\tif err := os.MkdirAll(jujuHome, 0775); err != nil {\n\t\treturn err\n\t}\n\tpath := filepath.Join(jujuHome, name)\n\tif err := ioutil.WriteFile(path+\"-cert.pem\", cert, 0644); err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(path+\"-private-key.pem\", key, 0600)\n}\n\n\n\n\n\n\nfunc EnsureCertificate(environ Environ, writeCertAndKey func(environName string, cert, key []byte) error) (CreatedCert, error) {\n\tcfg := environ.Config()\n\t_, hasCACert := cfg.CACert()\n\t_, hasCAKey := cfg.CAPrivateKey()\n\n\tif hasCACert && hasCAKey {\n\t\treturn CertExists, nil\n\t}\n\tif hasCACert && !hasCAKey {\n\t\treturn CertExists, fmt.Errorf(\"environment configuration with a certificate but no CA private key\")\n\t}\n\n\treturn CertCreated, generateCertificate(environ, writeCertAndKey)\n}\n\nfunc generateCertificate(environ Environ, writeCertAndKey func(environName string, cert, key []byte) error) error ", "output": "{\n\tcfg := environ.Config()\n\tcaCert, caKey, err := cert.NewCA(environ.Name(), time.Now().UTC().AddDate(10, 0, 0))\n\tif err != nil {\n\t\treturn err\n\t}\n\tm := cfg.AllAttrs()\n\tm[\"ca-cert\"] = string(caCert)\n\tm[\"ca-private-key\"] = string(caKey)\n\tcfg, err = config.New(m)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot create environment configuration with new CA: %v\", err)\n\t}\n\tif err := environ.SetConfig(cfg); err != nil {\n\t\treturn fmt.Errorf(\"cannot set environment configuration with CA: %v\", err)\n\t}\n\tif err := writeCertAndKey(environ.Name(), caCert, caKey); err != nil {\n\t\treturn fmt.Errorf(\"cannot write CA certificate and key: %v\", err)\n\t}\n\treturn nil\n}"} {"input": "package unix_test\n\nimport (\n\t\"log\"\n\t\"os\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\nfunc ExampleExec() ", "output": "{\n\terr := unix.Exec(\"/bin/ls\", []string{\"ls\", \"-al\"}, os.Environ())\n\tlog.Fatal(err)\n}"} {"input": "package str\n\nimport (\n\t\"strings\"\n)\n\n\n\n\n\n\n\nfunc Comma(csv string) []string {\n\treturn SplitBy(csv, \",\")\n}\n\nfunc SplitBy(sv string, sep string) []string ", "output": "{\n\tfiltered := make([]string, 0)\n\tfor _, part := range strings.Split(sv, sep) {\n\t\tpart = Trim(part)\n\t\tif part != \"\" {\n\t\t\tfiltered = append(filtered, part)\n\t\t}\n\t}\n\treturn filtered\n}"} {"input": "package lib\n\nimport (\n\t\"github.com/atinm/spotify\"\n)\n\nfunc ignored(device string) bool {\n\tfor _, name := range config.Ignored {\n\t\tif name == device {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc ParentalControlsEnabled() bool {\n\treturn rule.Explicit\n}\n\nfunc Rules(track *spotify.FullTrack, device string) bool {\n\tif track != nil && rule.Explicit && track.Explicit && !ignored(device) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc SetParentalControls(b bool) {\n\trule.Explicit = b\n}\n\nfunc FiltersEnabled() bool ", "output": "{\n\treturn ParentalControlsEnabled()\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/apier/v1\"\n\nfunc init() {\n\tc := &CmdRemoveActions{\n\t\tname: \"actions_remove\",\n\t\trpcMethod: \"ApierV1.RemoveActions\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdRemoveActions struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrRemoveActions\n\t*CommandExecuter\n}\n\n\n\nfunc (self *CmdRemoveActions) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdRemoveActions) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrRemoveActions{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdRemoveActions) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdRemoveActions) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *CmdRemoveActions) Name() string ", "output": "{\n\treturn self.name\n}"} {"input": "package core\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\ntype VolumeGroupSourceFromVolumeGroupDetails struct {\n\n\tVolumeGroupId *string `mandatory:\"true\" json:\"volumeGroupId\"`\n}\n\nfunc (m VolumeGroupSourceFromVolumeGroupDetails) String() string {\n\treturn common.PointerString(m)\n}\n\n\n\n\nfunc (m VolumeGroupSourceFromVolumeGroupDetails) MarshalJSON() (buff []byte, e error) ", "output": "{\n\ttype MarshalTypeVolumeGroupSourceFromVolumeGroupDetails VolumeGroupSourceFromVolumeGroupDetails\n\ts := struct {\n\t\tDiscriminatorParam string `json:\"type\"`\n\t\tMarshalTypeVolumeGroupSourceFromVolumeGroupDetails\n\t}{\n\t\t\"volumeGroupId\",\n\t\t(MarshalTypeVolumeGroupSourceFromVolumeGroupDetails)(m),\n\t}\n\n\treturn json.Marshal(&s)\n}"} {"input": "package tlsutil\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\t\"io/ioutil\"\n)\n\ntype TLSConfig struct {\n\tConfig *tls.Config\n}\n\nfunc NewTLSConfig() TLSConfig {\n\treturn TLSConfig{\n\t\tConfig: &tls.Config{\n\t\t\tCertificates: []tls.Certificate{},\n\t\t},\n\t}\n}\n\nfunc (tc *TLSConfig) LoadX509KeyPair(cert_filepath, key_filepath string) error {\n\tcert, err := tls.LoadX509KeyPair(cert_filepath, key_filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttc.Config.Certificates = append(tc.Config.Certificates, cert)\n\treturn nil\n}\n\nfunc (tc *TLSConfig) LoadCACert(ca_cert_filepath string) error {\n\tcert, err := ioutil.ReadFile(ca_cert_filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tc.Config.RootCAs == nil {\n\t\ttc.Config.RootCAs = x509.NewCertPool()\n\t}\n\n\tok := tc.Config.RootCAs.AppendCertsFromPEM(cert)\n\tif !ok {\n\t\treturn fmt.Errorf(\"Cannot add Root CA cert %v\", ca_cert_filepath)\n\t}\n\treturn nil\n}\n\n\n\nfunc (tc *TLSConfig) Inflate() ", "output": "{\n\ttc.Config.BuildNameToCertificate()\n}"} {"input": "package sync2\n\n\n\n\n\nimport (\n\t\"time\"\n)\n\n\n\ntype Semaphore struct {\n\tslots chan struct{}\n\ttimeout time.Duration\n}\n\n\n\n\n\n\n\nfunc (sem *Semaphore) Acquire() bool {\n\tif sem.timeout == 0 {\n\t\t<-sem.slots\n\t\treturn true\n\t}\n\tselect {\n\tcase <-sem.slots:\n\t\treturn true\n\tcase <-time.After(sem.timeout):\n\t\treturn false\n\t}\n}\n\n\n\n\nfunc (sem *Semaphore) Release() {\n\tsem.slots <- struct{}{}\n}\n\nfunc NewSemaphore(count int, timeout time.Duration) *Semaphore ", "output": "{\n\tsem := &Semaphore{\n\t\tslots: make(chan struct{}, count),\n\t\ttimeout: timeout,\n\t}\n\tfor i := 0; i < count; i++ {\n\t\tsem.slots <- struct{}{}\n\t}\n\treturn sem\n}"} {"input": "package v2\n\nimport (\n\t\"testing\"\n\n\t\"github.com/gophercloud/gophercloud/acceptance/clients\"\n\t\"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/migrate\"\n)\n\n\n\nfunc TestMigrate(t *testing.T) ", "output": "{\n\tclient, err := clients.NewComputeV2Client()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create a compute client: %v\", err)\n\t}\n\n\tserver, err := CreateServer(t, client)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create server: %v\", err)\n\t}\n\tdefer DeleteServer(t, client, server)\n\n\tt.Logf(\"Attempting to migrate server %s\", server.ID)\n\n\terr = migrate.Migrate(client, server.ID).ExtractErr()\n\tif err != nil {\n\t\tt.Fatalf(\"Error during migration: %v\", err)\n\t}\n}"} {"input": "package metrics\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\ntype GaugeMetric struct {\n\tvalue float64\n\tmutex sync.RWMutex\n}\n\nfunc (metric *GaugeMetric) Humanize() string {\n\tformatString := \"[GaugeMetric; value=%f]\"\n\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn fmt.Sprintf(formatString, metric.value)\n}\n\nfunc (metric *GaugeMetric) Set(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value = value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) IncrementBy(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value += value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Increment() float64 {\n\treturn metric.IncrementBy(1)\n}\n\nfunc (metric *GaugeMetric) DecrementBy(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value -= value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Decrement() float64 {\n\treturn metric.DecrementBy(1)\n}\n\n\n\nfunc (metric *GaugeMetric) Marshallable() map[string]interface{} {\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\tv := make(map[string]interface{}, 2)\n\n\tv[valueKey] = metric.value\n\tv[typeKey] = gaugeTypeValue\n\n\treturn v\n}\n\nfunc (metric *GaugeMetric) Get() float64 ", "output": "{\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn metric.value\n}"} {"input": "package lht\n\nimport \"fmt\"\n\n\n\nfunc getHint(secret string, guess string) string ", "output": "{\n\tcows, countA, countB := make([]byte, 10), 0, 0\n\tfor idx, number := range []byte(secret) {\n\t\tcows[number-'0']++\n\t\tif guess[idx] == number {\n\t\t\tcountA++\n\t\t}\n\t}\n\n\tfor _, number := range guess {\n\t\tif num := number - '0'; cows[num] > 0 {\n\t\t\tcountB++\n\t\t\tcows[num]--\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"%dA%dB\", countA, countB-countA)\n}"} {"input": "package http\n\nimport (\n\t\"reflect\"\n)\n\n\ntype JsonError struct {\n\tStatus int `json:\"status,omitempty\"`\n\tCode int `json:\"code,omitempty\"`\n\tType string `json:\"type,omitempty\"`\n\tMessage string `json:\"message,omitempty\"`\n\tMoreInfo string `json:\"moreInfo,omitempty\"`\n}\n\n\n\nfunc NewJsonErrorFromError(status int, e error) JsonError ", "output": "{\n\terrType := reflect.TypeOf(e)\n\tvar typeName string\n\tif errType.Kind() == reflect.Ptr {\n\t\ttypeName = errType.Elem().Name()\n\t} else {\n\t\ttypeName = errType.Name()\n\t}\n\n\treturn JsonError{\n\t\tStatus: status,\n\t\tType: typeName,\n\t\tMessage: e.Error(),\n\t}\n}"} {"input": "package wrappers\n\nimport \"github.com/gin-gonic/gin\"\n\n\ntype JSONHandler func(c *gin.Context) (int, interface{})\n\n\ntype StringHandler func(c *gin.Context) (int, string)\n\n\nfunc JSON(handler JSONHandler) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tstatus, resp := handler(c)\n\t\tc.JSON(status, resp)\n\t}\n}\n\n\n\n\nfunc Text(handler StringHandler) gin.HandlerFunc ", "output": "{\n\treturn func(c *gin.Context) {\n\t\tstatus, resp := handler(c)\n\t\tc.String(status, resp)\n\t}\n}"} {"input": "package claim\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\n\n\nfunc TestPermission_Match(t *testing.T) {\n\tp := Permission{ResourceURN: \"userapi:device:device_id\"}\n\tassert.True(t, p.Match(\"userapi:device:device_id\"))\n\tassert.False(t, p.Match(\"userapi:device:bla\"))\n\tassert.False(t, p.Match(\"userapi:home:bla\"))\n}\nfunc TestPermission_MatchWildcard(t *testing.T) {\n\tp := Permission{ResourceURN: \"userapi:device:*\"}\n\tassert.True(t, p.Match(\"userapi:device:device_id\"))\n\tassert.True(t, p.Match(\"userapi:device:bla\"))\n\tassert.False(t, p.Match(\"userapi:home:bla\"))\n}\n\nfunc TestPermissionSet_Match(t *testing.T) {\n\tp := PermissionSet{\n\t\tRules: []Permission{\n\t\t\t{ResourceURN: \"userapi:device:*\", Verb: []string{\"read\", \"update\", \"create\"}},\n\t\t\t{ResourceURN: \"userapi:device:\", Verb: []string{\"create\"}},\n\t\t},\n\t}\n\tassert.True(t, p.Match(\"read\", \"userapi:device:device_id\"))\n\tassert.False(t, p.Match(\"delete\", \"userapi:device:device_id\"))\n\tassert.True(t, p.Match(\"create\", \"userapi:device:\"))\n\n}\n\nfunc TestPermission_MatchVerb(t *testing.T) ", "output": "{\n\tp := Permission{Verb: []string{\"read\", \"update\", \"create\"}}\n\tassert.True(t, p.MatchVerb(\"read\"))\n\tassert.True(t, p.MatchVerb(\"update\"))\n\tassert.True(t, p.MatchVerb(\"create\"))\n\tassert.False(t, p.MatchVerb(\"invalid\"))\n\tassert.False(t, p.MatchVerb(\"delete\"))\n}"} {"input": "package hash\n\nimport \"unsafe\"\n\nconst DJBInit uint32 = 5381\n\nfunc DJBCombine(acc, h uint32) uint32 {\n\treturn mul33(acc) + h\n}\n\nfunc DJB(hs ...uint32) uint32 {\n\tacc := DJBInit\n\tfor _, h := range hs {\n\t\tacc = DJBCombine(acc, h)\n\t}\n\treturn acc\n}\n\nfunc UInt32(u uint32) uint32 {\n\treturn u\n}\n\nfunc UInt64(u uint64) uint32 {\n\treturn mul33(uint32(u>>32)) + uint32(u&0xffffffff)\n}\n\nfunc Pointer(p unsafe.Pointer) uint32 {\n\tswitch unsafe.Sizeof(p) {\n\tcase 4:\n\t\treturn UInt32(uint32(uintptr(p)))\n\tcase 8:\n\t\treturn UInt64(uint64(uintptr(p)))\n\tdefault:\n\t\tpanic(\"unhandled pointer size\")\n\t}\n}\n\nfunc UIntPtr(p uintptr) uint32 {\n\tswitch unsafe.Sizeof(p) {\n\tcase 4:\n\t\treturn UInt32(uint32(p))\n\tcase 8:\n\t\treturn UInt64(uint64(p))\n\tdefault:\n\t\tpanic(\"unhandled pointer size\")\n\t}\n}\n\n\n\nfunc mul33(u uint32) uint32 {\n\treturn u<<5 + u\n}\n\nfunc String(s string) uint32 ", "output": "{\n\th := DJBInit\n\tfor i := 0; i < len(s); i++ {\n\t\th = DJBCombine(h, uint32(s[i]))\n\t}\n\treturn h\n}"} {"input": "package configmap\n\nimport (\n\t\"context\"\n\n\tcorev1 \"k8s.io/client-go/informers/core/v1\"\n\n\t\"github.com/knative/pkg/controller\"\n\t\"github.com/knative/pkg/injection\"\n\t\"github.com/knative/pkg/injection/informers/kubeinformers/factory\"\n\t\"github.com/knative/pkg/logging\"\n)\n\n\n\n\n\ntype Key struct{}\n\nfunc withInformer(ctx context.Context) (context.Context, controller.Informer) {\n\tf := factory.Get(ctx)\n\tinf := f.Core().V1().ConfigMaps()\n\treturn context.WithValue(ctx, Key{}, inf), inf.Informer()\n}\n\n\nfunc Get(ctx context.Context) corev1.ConfigMapInformer {\n\tuntyped := ctx.Value(Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panicf(\n\t\t\t\"Unable to fetch %T from context.\", (corev1.ConfigMapInformer)(nil))\n\t}\n\treturn untyped.(corev1.ConfigMapInformer)\n}\n\nfunc init() ", "output": "{\n\tinjection.Default.RegisterInformer(withInformer)\n}"} {"input": "package coreunix\n\nimport (\n\tcore \"github.com/ipfs/go-ipfs/core\"\n\tdag \"github.com/ipfs/go-ipfs/merkledag\"\n\tft \"github.com/ipfs/go-ipfs/unixfs\"\n\tcid \"gx/ipfs/QmXfiyr2RWEXpVDdaYnD2HNiBk6UBddsvEP4RPfXb6nGqY/go-cid\"\n)\n\nfunc AddMetadataTo(n *core.IpfsNode, skey string, m *ft.Metadata) (string, error) {\n\tc, err := cid.Decode(skey)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnd, err := n.DAG.Get(n.Context(), c)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmdnode := new(dag.ProtoNode)\n\tmdata, err := ft.BytesForMetadata(m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmdnode.SetData(mdata)\n\tif err := mdnode.AddNodeLinkClean(\"file\", nd); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnk, err := n.DAG.Add(mdnode)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn nk.String(), nil\n}\n\n\n\nfunc Metadata(n *core.IpfsNode, skey string) (*ft.Metadata, error) ", "output": "{\n\tc, err := cid.Decode(skey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnd, err := n.DAG.Get(n.Context(), c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpbnd, ok := nd.(*dag.ProtoNode)\n\tif !ok {\n\t\treturn nil, dag.ErrNotProtobuf\n\t}\n\n\treturn ft.MetadataFromBytes(pbnd.Data())\n}"} {"input": "package gce\n\nimport (\n\t\"time\"\n\n\tcompute \"google.golang.org/api/compute/v1\"\n)\n\nfunc newStaticIPMetricContext(request string) *metricContext {\n\treturn &metricContext{\n\t\tstart: time.Now(),\n\t\tattributes: []string{\"staticip_\" + request, unusedMetricLabel, unusedMetricLabel},\n\t}\n}\n\n\n\n\n\nfunc (gce *GCECloud) ReserveGlobalStaticIP(name, ipAddress string) (address *compute.Address, err error) {\n\tmc := newStaticIPMetricContext(\"reserve\")\n\top, err := gce.service.GlobalAddresses.Insert(gce.projectID, &compute.Address{Name: name, Address: ipAddress}).Do()\n\n\tif err != nil {\n\t\treturn nil, mc.Observe(err)\n\t}\n\n\tif err := gce.waitForGlobalOp(op, mc); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gce.service.GlobalAddresses.Get(gce.projectID, name).Do()\n}\n\n\nfunc (gce *GCECloud) DeleteGlobalStaticIP(name string) error {\n\tmc := newStaticIPMetricContext(\"delete\")\n\top, err := gce.service.GlobalAddresses.Delete(gce.projectID, name).Do()\n\tif err != nil {\n\t\treturn mc.Observe(err)\n\t}\n\treturn gce.waitForGlobalOp(op, mc)\n}\n\n\n\n\nfunc (gce *GCECloud) GetGlobalStaticIP(name string) (address *compute.Address, err error) ", "output": "{\n\treturn gce.service.GlobalAddresses.Get(gce.projectID, name).Do()\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realInternetGateway InternetGateway\n\n\nfunc (o *InternetGateway) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realInternetGateway\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = InternetGateway(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &InternetGateway{}\n\n\nfunc (o *InternetGateway) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\n\n\n\nvar _ fi.HasName = &InternetGateway{}\n\n\nfunc (o *InternetGateway) GetName() *string {\n\treturn o.Name\n}\n\n\nfunc (o *InternetGateway) SetName(name string) {\n\to.Name = &name\n}\n\n\nfunc (o *InternetGateway) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *InternetGateway) SetLifecycle(lifecycle fi.Lifecycle) ", "output": "{\n\to.Lifecycle = &lifecycle\n}"} {"input": "package polly\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/awstesting/unit\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestRestGETStrategy(t *testing.T) {\n\tsvc := New(unit.Session, &aws.Config{Region: aws.String(\"us-west-2\")})\n\tr, _ := svc.SynthesizeSpeechRequest(nil)\n\terr := restGETPresignStrategy(r)\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"GET\", r.HTTPRequest.Method)\n\tassert.NotEqual(t, nil, r.Operation.BeforePresignFn)\n}\n\n\n\nfunc TestPresign(t *testing.T) ", "output": "{\n\tsvc := New(unit.Session, &aws.Config{Region: aws.String(\"us-west-2\")})\n\tr, _ := svc.SynthesizeSpeechRequest(&SynthesizeSpeechInput{\n\t\tText: aws.String(\"Moo\"),\n\t\tOutputFormat: aws.String(\"mp3\"),\n\t\tVoiceId: aws.String(\"Foo\"),\n\t})\n\turl, err := r.Presign(time.Second)\n\tassert.NoError(t, err)\n\tassert.Regexp(t, `^https://polly.us-west-2.amazonaws.com/v1/speech\\?.*?OutputFormat=mp3.*?Text=Moo.*?VoiceId=Foo.*`, url)\n}"} {"input": "package ud859\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"google.golang.org/appengine/datastore\"\n\n\t\"github.com/GoogleCloudPlatform/go-endpoints/endpoints\"\n)\n\n\ntype Profile struct {\n\tEmail string `json:\"-\"`\n\tDisplayName string `json:\"displayName\"`\n\tTeeShirtSize string `json:\"teeShirtSize\"`\n\tConferences []string `json:\"conferenceKeysToAttend\"`\n}\n\n\ntype ProfileForm struct {\n\tDisplayName string `json:\"displayName\"`\n\tTeeShirtSize string `json:\"teeShirtSize\"`\n}\n\ntype identity struct {\n\tkey *datastore.Key\n\temail string\n}\n\nfunc profileID(c context.Context) (*identity, error) {\n\tu, err := endpoints.CurrentUser(c, scopes, audiences, clientIds)\n\tif err != nil {\n\t\treturn nil, errUnauthorized(err, \"signin required\")\n\t}\n\treturn &identity{\n\t\tkey: datastore.NewKey(c, \"Profile\", u.String(), 0, nil),\n\t\temail: u.Email,\n\t}, nil\n}\n\n\nfunc (ConferenceAPI) GetProfile(c context.Context) (*Profile, error) {\n\tpid, err := profileID(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn getProfile(c, pid)\n}\n\nfunc getProfile(c context.Context, pid *identity) (*Profile, error) {\n\tprofile := new(Profile)\n\terr := datastore.Get(c, pid.key, profile)\n\tif err != nil && err != datastore.ErrNoSuchEntity {\n\t\treturn nil, errInternalServer(err, \"unable to get profile\")\n\t}\n\n\tprofile.Email = pid.email\n\treturn profile, nil\n}\n\n\n\n\nfunc (ConferenceAPI) SaveProfile(c context.Context, form *ProfileForm) error ", "output": "{\n\tpid, err := profileID(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn datastore.RunInTransaction(c, func(c context.Context) error {\n\t\tprofile, err := getProfile(c, pid)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tprofile.DisplayName = form.DisplayName\n\t\tprofile.TeeShirtSize = form.TeeShirtSize\n\n\t\t_, err = datastore.Put(c, pid.key, profile)\n\t\tif err != nil {\n\t\t\treturn errInternalServer(err, \"unable to save profile\")\n\t\t}\n\t\treturn nil\n\t}, nil)\n}"} {"input": "package main\n\nimport (\n\tpb \"github.com/golanghr/platform-examples/hello/protos\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\n\n\nfunc (s *Service) HelloWorld(ctx context.Context, in *pb.HelloRequest) (*pb.HelloWorld, error) ", "output": "{\n\treturn &pb.HelloWorld{Message: \"Hello From Golang.HR Micro Platform!\"}, nil\n}"} {"input": "package cmd\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\n\n\nfunc TestEnvDiffEmptyValue(t *testing.T) {\n\tbefore := Env{}\n\tafter := Env{\"FOO\": \"\"}\n\n\tdiff := BuildEnvDiff(before, after)\n\n\tif !reflect.DeepEqual(diff.Next, map[string]string(after)) {\n\t\tt.Errorf(\"diff.Next != after (%#+v != %#+v)\", diff.Next, after)\n\t}\n}\n\nfunc TestIgnoredEnv(t *testing.T) {\n\tif !IgnoredEnv(DIRENV_BASH) {\n\t\tt.Fail()\n\t}\n\tif IgnoredEnv(DIRENV_DIFF) {\n\t\tt.Fail()\n\t}\n\tif !IgnoredEnv(\"_\") {\n\t\tt.Fail()\n\t}\n\tif !IgnoredEnv(\"__fish_foo\") {\n\t\tt.Fail()\n\t}\n\tif !IgnoredEnv(\"__fishx\") {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestEnvDiff(t *testing.T) ", "output": "{\n\tdiff := &EnvDiff{map[string]string{\"FOO\": \"bar\"}, map[string]string{\"BAR\": \"baz\"}}\n\n\tout := diff.Serialize()\n\n\tdiff2, err := LoadEnvDiff(out)\n\tif err != nil {\n\t\tt.Error(\"parse error\", err)\n\t}\n\n\tif len(diff2.Prev) != 1 {\n\t\tt.Error(\"len(diff2.prev) != 1\", len(diff2.Prev))\n\t}\n\n\tif len(diff2.Next) != 1 {\n\t\tt.Error(\"len(diff2.next) != 0\", len(diff2.Next))\n\t}\n}"} {"input": "package aerospike\n\ntype operateCommand struct {\n\t*readCommand\n\n\tpolicy *WritePolicy\n\toperations []*Operation\n}\n\nfunc newOperateCommand(cluster *Cluster, policy *WritePolicy, key *Key, operations []*Operation) *operateCommand {\n\treturn &operateCommand{\n\t\treadCommand: newReadCommand(cluster, policy, key, nil),\n\t\tpolicy: policy,\n\t\toperations: operations,\n\t}\n}\n\nfunc (cmd *operateCommand) writeBuffer(ifc command) error {\n\treturn cmd.setOperate(cmd.policy, cmd.key, cmd.operations)\n}\n\n\n\nfunc (cmd *operateCommand) Execute() error ", "output": "{\n\treturn cmd.execute(cmd)\n}"} {"input": "package label\n\n\n\n\nfunc InitLabels(mcsdir string, options []string) (string, string, error) {\n\treturn \"\", \"\", nil\n}\n\nfunc FormatMountLabel(src string, mountLabel string) string {\n\treturn src\n}\n\nfunc SetProcessLabel(processLabel string) error {\n\treturn nil\n}\n\nfunc SetFileLabel(path string, fileLabel string) error {\n\treturn nil\n}\n\n\n\nfunc Relabel(path string, fileLabel string, relabel string) error {\n\treturn nil\n}\n\nfunc GetPidLabel(pid int) (string, error) {\n\treturn \"\", nil\n}\n\nfunc Init() {\n}\n\nfunc ReserveLabel(label string) error {\n\treturn nil\n}\n\nfunc UnreserveLabel(label string) error {\n\treturn nil\n}\n\n\n\nfunc DupSecOpt(src string) []string {\n\treturn nil\n}\n\n\n\nfunc DisableSecOpt() []string {\n\treturn nil\n}\n\nfunc SetFileCreateLabel(fileLabel string) error ", "output": "{\n\treturn nil\n}"} {"input": "package packets\n\nimport (\n\t\"github.com/bnch/bancho/pid\"\n)\n\n\nconst (\n\tPrivilegeNormalest = 0\n\tPrivilegeNormal = 1 << iota\n\tPrivilegeGMT\n\tPrivilegeSupporter\n\tPrivilegePeppy\n\tPrivilegeAdmin\n\tPrivilegeTournamentStaff\n\n\tPrivilegeGMTSupporter = PrivilegeSupporter | PrivilegeGMT\n)\n\n\n\n\nfunc UserPrivileges(privileges uint32) Packet ", "output": "{\n\treturn MakePacket(pid.BanchoLoginPermissions, 4, privileges)\n}"} {"input": "package util\n\nconst (\n\tDefaultPerPage = 20\n)\n\n\n\nfunc (p *Pagination) SimplePage() (from int64, to int64) {\n\tif p.CurPage == 0 || p.PerPage == 0 {\n\t\tp.CurPage, p.PerPage = 1, DefaultPerPage\n\t}\n\tfrom = (p.CurPage-1)*p.PerPage + 1\n\tto = from + p.PerPage - 1\n\treturn\n}\n\n\n\nfunc (p *Pagination) Page(total int64) (from int64, to int64) {\n\tif p.CurPage == 0 {\n\t\tp.CurPage = 1\n\t}\n\tif p.PerPage == 0 {\n\t\tp.PerPage = DefaultPerPage\n\t}\n\n\tif total == 0 || total < p.PerPage*(p.CurPage-1) {\n\t\treturn\n\t}\n\tif total <= p.PerPage {\n\t\treturn 1, total\n\t}\n\tfrom = (p.CurPage-1)*p.PerPage + 1\n\tif (total - from + 1) < p.PerPage {\n\t\treturn from, total\n\t}\n\treturn from, from + p.PerPage - 1\n}\n\n\nfunc (p *Pagination) VagueOffsetLimit() (offset int64, limit int64) {\n\tfrom, to := p.SimplePage()\n\tif to == 0 || from == 0 {\n\t\treturn 0, 0\n\t}\n\treturn from - 1, to - from + 1\n}\n\n\n\n\n\ntype Pagination struct {\n\tCurPage int64\n\tPerPage int64\n}\n\nfunc (p *Pagination) OffsetLimit(total int64) (offset int64, limit int64) ", "output": "{\n\tfrom, to := p.Page(total)\n\tif to == 0 || from == 0 {\n\t\treturn 0, 0\n\t}\n\treturn from - 1, to - from + 1\n}"} {"input": "package execcmd\n\nimport (\n\t\"io\"\n\n\t\"github.com/docker/docker/pkg/term\"\n\t\"github.com/sirupsen/logrus\"\n)\n\n\n\ntype OutStream struct {\n\tCommonStream\n\tout io.Writer\n}\n\n\n\n\nfunc (o *OutStream) GetTtySize() (uint, uint) {\n\tif !o.isTerminal {\n\t\treturn 0, 0\n\t}\n\tws, err := term.GetWinsize(o.fd)\n\tif err != nil {\n\t\tlogrus.Debugf(\"Error getting size: %s\", err)\n\t\tif ws == nil {\n\t\t\treturn 0, 0\n\t\t}\n\t}\n\treturn uint(ws.Height), uint(ws.Width)\n}\n\n\nfunc NewOutStream(out io.Writer) io.Writer {\n\tif out == nil {\n\t\treturn nil\n\t}\n\n\tfd, isTerminal := term.GetFdInfo(out)\n\treturn &OutStream{CommonStream: CommonStream{fd: fd, isTerminal: isTerminal}, out: out}\n}\n\nfunc (o *OutStream) Write(p []byte) (int, error) ", "output": "{\n\treturn o.out.Write(p)\n}"} {"input": "package redsync_test\n\nimport (\n\t\"net\"\n\n\t\"github.com/hjr265/redsync.go/redsync\"\n)\n\n\n\nfunc ExampleMutex() ", "output": "{\n\tm, err := redsync.NewMutex(\"FlyingSquirrels\", []net.Addr{\n\t\t&net.TCPAddr{Port: 63790},\n\t\t&net.TCPAddr{Port: 63791},\n\t\t&net.TCPAddr{Port: 63792},\n\t\t&net.TCPAddr{Port: 63793},\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = m.Lock()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer m.Unlock()\n\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/config\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdGetJSONConfig{\n\t\tname: \"get_json_section\",\n\t\trpcMethod: utils.ConfigSv1GetConfig,\n\t\trpcParams: &config.SectionWithOpts{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetJSONConfig struct {\n\tname string\n\trpcMethod string\n\trpcParams *config.SectionWithOpts\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetJSONConfig) Name() string {\n\treturn self.name\n}\n\n\n\nfunc (self *CmdGetJSONConfig) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &config.SectionWithOpts{Opts: make(map[string]interface{})}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetJSONConfig) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdGetJSONConfig) RpcResult() interface{} {\n\tvar s map[string]interface{}\n\treturn &s\n}\n\nfunc (self *CmdGetJSONConfig) RpcMethod() string ", "output": "{\n\treturn self.rpcMethod\n}"} {"input": "package reexec\n\nimport (\n\t\"os/exec\"\n)\n\n\n\n\nfunc Command(args ...string) *exec.Cmd ", "output": "{\n\treturn nil\n}"} {"input": "package mlib\n\nimport (\n\t\"io\"\n)\n\ntype reader struct {\n\tinner io.Reader\n}\n\n\nfunc NewCrRemovingReader(inner io.Reader) io.ReadCloser {\n\tr := reader{inner: inner}\n\treturn &r\n}\n\nfunc (r *reader) Read(p []byte) (int, error) {\n\tread, err := r.inner.Read(p)\n\tretLen := 0\n\tfor i := 0; i < read; i++ {\n\t\tif p[i] != '\\r' {\n\t\t\tp[retLen] = p[i]\n\t\t\tretLen++\n\t\t}\n\t}\n\n\treturn retLen, err\n}\n\n\n\nfunc (r *reader) Close() error ", "output": "{\n\tDebug(\"close...\\n\")\n\tswitch r.inner.(type) {\n\tcase io.Closer:\n\t\treturn r.inner.(io.Closer).Close()\n\t}\n\treturn nil\n}"} {"input": "package object\n\nimport (\n\t\"github.com/vmware/govmomi/vim25\"\n\t\"github.com/vmware/govmomi/vim25/types\"\n\t\"golang.org/x/net/context\"\n)\n\ntype Network struct {\n\tCommon\n}\n\nfunc NewNetwork(c *vim25.Client, ref types.ManagedObjectReference) *Network {\n\treturn &Network{\n\t\tCommon: NewCommon(c, ref),\n\t}\n}\n\n\n\n\nfunc (n Network) EthernetCardBackingInfo(_ context.Context) (types.BaseVirtualDeviceBackingInfo, error) ", "output": "{\n\tname := n.Name()\n\n\tbacking := &types.VirtualEthernetCardNetworkBackingInfo{\n\t\tVirtualDeviceDeviceBackingInfo: types.VirtualDeviceDeviceBackingInfo{\n\t\t\tDeviceName: name,\n\t\t},\n\t}\n\n\treturn backing, nil\n}"} {"input": "package class\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n\n\t\"k8s.io/ingress/core/pkg/ingress/annotations/parser\"\n\t\"k8s.io/ingress/core/pkg/ingress/errors\"\n)\n\nconst (\n\tIngressKey = \"kubernetes.io/ingress.class\"\n)\n\n\n\n\n\n\nfunc IsValid(ing *extensions.Ingress, controller, defClass string) bool ", "output": "{\n\tingress, err := parser.GetStringAnnotation(IngressKey, ing)\n\tif err != nil && !errors.IsMissingAnnotations(err) {\n\t\tglog.Warningf(\"unexpected error reading ingress annotation: %v\", err)\n\t}\n\n\tif ingress == \"\" && controller == defClass {\n\t\treturn true\n\t}\n\n\treturn ingress == controller\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n)\n\n\nconst DeleteDeploymentOKCode int = 200\n\n\ntype DeleteDeploymentOK struct {\n}\n\n\nfunc NewDeleteDeploymentOK() *DeleteDeploymentOK {\n\treturn &DeleteDeploymentOK{}\n}\n\n\nfunc (o *DeleteDeploymentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n}\n\n\nconst DeleteDeploymentUnauthorizedCode int = 401\n\n\ntype DeleteDeploymentUnauthorized struct {\n\tWWWAuthenticate string `json:\"WWW_Authenticate\"`\n}\n\n\nfunc NewDeleteDeploymentUnauthorized() *DeleteDeploymentUnauthorized {\n\treturn &DeleteDeploymentUnauthorized{}\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) WithWWWAuthenticate(wWWAuthenticate string) *DeleteDeploymentUnauthorized {\n\to.WWWAuthenticate = wWWAuthenticate\n\treturn o\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) SetWWWAuthenticate(wWWAuthenticate string) {\n\to.WWWAuthenticate = wWWAuthenticate\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\n\twWWAuthenticate := o.WWWAuthenticate\n\tif wWWAuthenticate != \"\" {\n\t\trw.Header().Set(\"WWW_Authenticate\", wWWAuthenticate)\n\t}\n\n\trw.WriteHeader(401)\n}\n\n\nconst DeleteDeploymentNotFoundCode int = 404\n\n\ntype DeleteDeploymentNotFound struct {\n}\n\n\nfunc NewDeleteDeploymentNotFound() *DeleteDeploymentNotFound {\n\treturn &DeleteDeploymentNotFound{}\n}\n\n\nfunc (o *DeleteDeploymentNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(404)\n}\n\n\nconst DeleteDeploymentInternalServerErrorCode int = 500\n\n\ntype DeleteDeploymentInternalServerError struct {\n}\n\n\nfunc NewDeleteDeploymentInternalServerError() *DeleteDeploymentInternalServerError {\n\treturn &DeleteDeploymentInternalServerError{}\n}\n\n\n\n\nfunc (o *DeleteDeploymentInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\trw.WriteHeader(500)\n}"} {"input": "package id3\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"io\"\n\t\"time\"\n)\n\nvar timestampFormats = []string{\n\t\"2006-01-02T15:04:05\",\n\t\"2006-01-02T15:04\",\n\t\"2006-01-02T15\",\n\t\"2006-01-02\",\n\t\"2006-01\",\n\t\"2006\",\n}\n\n\n\nfunc readUntilTerminator(term []byte, buf []byte) ([]byte, error) {\n\tfor i := 0; i+len(term)-1 < len(buf); i += len(term) {\n\t\tif bytes.Equal(term, buf[i:i+len(term)]) {\n\t\t\treturn buf[:i], nil\n\t\t}\n\t}\n\n\treturn nil, io.EOF\n}\n\nfunc parseTime(timeStr string) (time.Time, error) ", "output": "{\n\tfor i := range timestampFormats {\n\t\tt, err := time.Parse(timestampFormats[i], timeStr)\n\t\tif err == nil {\n\t\t\treturn t, nil\n\t\t}\n\t}\n\n\treturn time.Time{}, errors.New(\"invalid time\")\n}"} {"input": "package util\n\nimport \"go/build\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ImportToDir(imp string) (string, error) {\n\tpkg, err := build.Import(imp, \"\", build.FindOnly)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn pkg.Dir, nil\n}\n\nfunc DirToImport(p string) (string, error) ", "output": "{\n\tpkg, err := build.ImportDir(p, build.FindOnly)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn pkg.ImportPath, nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/go-martini/martini\"\n\t\"github.com/martini-contrib/render\"\n)\n\nfunc main() {\n\n\tm := martini.Classic()\n\n\tStaticOptions := martini.StaticOptions{Prefix: \"public\"}\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\n\tm.Use(render.Renderer(render.Options{\n\t\tDirectory: \"templates\", \n\t\tLayout: \"layout\", \n\t\tExtensions: []string{\".tmpl\"}, \n\t\tCharset: \"UTF-8\", \n\t}))\n\n\tm.Get(\"/\", IndexRouter)\n\tm.Get(\"/about\", AboutRoute)\n\tm.Get(\"/contact\", ContactRoute)\n\tm.Get(\"/signin\", SigninRoute)\n\tm.Get(\"/signup\", SignupRoute)\n\n\tm.Run()\n}\n\nfunc IndexRouter(r render.Render) {\n\tr.HTML(200, \"home/index\", nil)\n}\n\nfunc AboutRoute(r render.Render) {\n\tr.HTML(200, \"home/about\", nil)\n}\n\n\n\nfunc SigninRoute(r render.Render) {\n\tr.HTML(200, \"account/signin\", nil)\n}\n\nfunc SignupRoute(r render.Render) {\n\tr.HTML(200, \"account/signup\", nil)\n}\n\nfunc ContactRoute(r render.Render) ", "output": "{\n\tr.HTML(200, \"home/contact\", nil)\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n)\n\ntype ContentTypeVerifier struct {\n\tContentType string\n\tNext http.Handler\n}\n\n\n\n\n\n\n\n\nfunc (h *ContentTypeVerifier) Fail(rw http.ResponseWriter, req *http.Request) {\n\trw.Header().Add(\"Content-Type\", \"application/json\")\n\trw.WriteHeader(400)\n\trw.Write([]byte(`{\"error\":\"Invalid content type. Did you forget to set a valid Content-Type header?\"}`))\n\trw.Write([]byte(\"\\n\"))\n}\n\nfunc (h *ContentTypeVerifier) ServeHTTP(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\tcts := req.Header[\"Content-Type\"]\n\tfor _, ct := range cts {\n\t\tif ct != h.ContentType {\n\t\t\th.Fail(rw, req)\n\t\t\treturn\n\t\t}\n\t}\n\n\th.Next.ServeHTTP(rw, req)\n}"} {"input": "package godo\n\ntype TaskManager struct {\n\tmanager\n}\n\nfunc NewTaskManager() *TaskManager {\n\treturn &TaskManager{}\n}\n\nfunc (tm *TaskManager) FindAll() (tasks []Task, err error) {\n\terr = tm.manager.FindAll(&tasks, \"tasks\")\n\treturn\n}\n\n\n\nfunc (tm *TaskManager) FindTasksOfProject(projectId int, tasks *[]Task) (err error) ", "output": "{\n\terr = Dbmap.Select(tasks, \"select * from tasks where projectID = ? order by id\", projectId)\n\treturn\n}"} {"input": "package ratelimiter\n\nimport \"time\"\n\nvar domainLimitMap = make(map[string]*Limiter)\n\n\ntype Limiter struct {\n\tnextChan chan bool\n\tapiLimit time.Duration\n}\n\n\nfunc New(domain string, apiLimit time.Duration) *Limiter {\n\tif _, ok := domainLimitMap[domain]; !ok {\n\t\tdomainLimitMap[domain] = &Limiter{\n\t\t\tnextChan: make(chan bool),\n\t\t\tapiLimit: apiLimit,\n\t\t}\n\t\tdomainLimitMap[domain].next()\n\t}\n\treturn domainLimitMap[domain]\n}\n\nfunc (limiter *Limiter) next() {\n\tgo func(l *Limiter) {\n\t\tticker := time.NewTimer(l.apiLimit)\n\t\t<-ticker.C\n\t\tticker.Stop()\n\t\tl.nextChan <- true\n\t}(limiter)\n}\n\n\n\n\nfunc (limiter *Limiter) Wait() ", "output": "{\n\t<-limiter.nextChan\n\tlimiter.next()\n}"} {"input": "package behaviors\n\n\n\n\n\nimport (\n\t\"github.com/tideland/golib/cells\"\n\t\"github.com/tideland/golib/logger\"\n)\n\n\n\n\n\n\ntype CallbackFunc func(topic string, payload cells.Payload) error\n\n\n\ntype callbackBehavior struct {\n\tctx cells.Context\n\tcallbackFuncs []CallbackFunc\n}\n\n\n\n\nfunc NewCallbackBehavior(cbfs ...CallbackFunc) cells.Behavior {\n\tif len(cbfs) == 0 {\n\t\tlogger.Errorf(\"callback created without callback functions\")\n\t}\n\treturn &callbackBehavior{nil, cbfs}\n}\n\n\nfunc (b *callbackBehavior) Init(ctx cells.Context) error {\n\tb.ctx = ctx\n\treturn nil\n}\n\n\nfunc (b *callbackBehavior) Terminate() error {\n\treturn nil\n}\n\n\nfunc (b *callbackBehavior) ProcessEvent(event cells.Event) error {\n\tfor _, callbackFunc := range b.callbackFuncs {\n\t\tif err := callbackFunc(event.Topic(), event.Payload()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\nfunc (b *callbackBehavior) Recover(err interface{}) error ", "output": "{\n\treturn nil\n}"} {"input": "package http\n\nimport (\n\t\"go-common/app/admin/main/app/model/language\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\n\n\n\n\nfunc langByID(c *bm.Context) {\n\tv := &language.Param{}\n\tif err := c.Bind(v); err != nil {\n\t\treturn\n\t}\n\tc.JSON(langSvc.LangByID(c, v.ID))\n}\n\n\nfunc addOrup(c *bm.Context) {\n\tvar (\n\t\terr error\n\t\tv = &language.Param{}\n\t)\n\tif err = c.Bind(v); err != nil {\n\t\treturn\n\t}\n\tif v.ID > 0 {\n\t\terr = langSvc.Update(c, v)\n\t} else {\n\t\terr = langSvc.Insert(c, v)\n\t}\n\tc.JSON(nil, err)\n}\n\nfunc languages(c *bm.Context) ", "output": "{\n\tc.JSON(langSvc.Languages(c))\n}"} {"input": "package gogetvers\n\nimport (\n\t\"os\"\n)\n\n\n\n\n\nfunc IsDir(path string) bool {\n\tif len(path) == 0 {\n\t\treturn false\n\t}\n\tfinfo, err := os.Stat(path)\n\treturn err == nil && finfo.IsDir()\n}\n\n\nfunc Mkdir(path string, perm os.FileMode) error {\n\treturn os.MkdirAll(path, perm)\n}\n\nfunc IsFile(path string) bool ", "output": "{\n\tif len(path) == 0 {\n\t\treturn false\n\t}\n\tfinfo, err := os.Stat(path)\n\treturn err == nil && !finfo.IsDir()\n\n}"} {"input": "package service\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/coreos/go-etcd/etcd\"\n)\n\ntype Options struct {\n\tApiPort int\n\tApiInterface string\n\tPidPath string\n\tPort int\n\tInterface string\n\tCertPath string\n\tEtcdNodes listOptions\n\tEtcdKey string\n\tEtcdConsistency string\n}\n\n\ntype listOptions []string\n\nfunc (o *listOptions) String() string {\n\treturn fmt.Sprint(*o)\n}\n\n\n\nfunc ParseCommandLine() (options Options, err error) {\n\tflag.Var(&options.EtcdNodes, \"etcd\", \"Etcd discovery service API endpoints\")\n\tflag.StringVar(&options.EtcdKey, \"etcdKey\", \"vulcand\", \"Etcd key for storing configuration\")\n\tflag.StringVar(&options.EtcdConsistency, \"etcdConsistency\", etcd.STRONG_CONSISTENCY, \"Etcd consistency\")\n\tflag.StringVar(&options.PidPath, \"pidPath\", \"\", \"Path to write PID file to\")\n\tflag.IntVar(&options.Port, \"port\", 8181, \"Port to listen on\")\n\tflag.IntVar(&options.ApiPort, \"apiPort\", 8182, \"Port to provide api on\")\n\tflag.StringVar(&options.Interface, \"interface\", \"\", \"Interface to bind to\")\n\tflag.StringVar(&options.ApiInterface, \"apiInterface\", \"\", \"Interface to for API to bind to\")\n\tflag.StringVar(&options.CertPath, \"certPath\", \"\", \"Certificate to use (enables TLS)\")\n\tflag.Parse()\n\treturn options, nil\n}\n\nfunc (o *listOptions) Set(value string) error ", "output": "{\n\t*o = append(*o, value)\n\treturn nil\n}"} {"input": "package theme\n\nimport (\n\t\"testing\"\n\n\t\"golang.org/x/exp/shiny/unit\"\n\t\"golang.org/x/image/math/fixed\"\n)\n\n\n\nfunc TestThemeIsAUnitConverter(t *testing.T) ", "output": "{\n\tc := unit.Converter(Default)\n\tgot := c.Pixels(unit.Inches(1.5))\n\twant := fixed.I(108)\n\tif got != want {\n\t\tt.Errorf(\"1 inch in pixels: got %v, want %v\", got, want)\n\t}\n\n\tfor _, dpi := range []float64{72, 160} {\n\t\tc := unit.Converter(&Theme{\n\t\t\tDPI: dpi,\n\t\t})\n\t\tgot := c.Convert(unit.Ems(3), unit.Pt)\n\t\twant := unit.Points(39 * unit.PointsPerInch / dpi)\n\t\tif got != want {\n\t\t\tt.Errorf(\"dpi=%v: 3 em in points: got %v, want %v\", dpi, got, want)\n\t\t}\n\t}\n}"} {"input": "package memory\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/square/quotaservice/buckets\"\n\t\"github.com/square/quotaservice/config\"\n)\n\nvar factory = NewBucketFactory()\n\nfunc TestMain(m *testing.M) {\n\tsetUp()\n\tr := m.Run()\n\tos.Exit(r)\n}\n\nfunc setUp() {\n\tfactory.Init(config.NewDefaultServiceConfig())\n}\n\n\n\nfunc TestGC(t *testing.T) {\n\tbuckets.TestGC(t, factory, \"memory\")\n}\n\nfunc TestTokenAcquisition(t *testing.T) ", "output": "{\n\tbucket := factory.NewBucket(\"memory\", \"memory\", config.NewDefaultBucketConfig(\"\"), false)\n\tbuckets.TestTokenAcquisition(t, bucket)\n}"} {"input": "package integrationtest_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestIntegrationtest(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Hydra Broker Test Suite\")\n}"} {"input": "package devices\n\n\n\ntype Device interface {\n\tBind(driver string) error\n\tUnbind() error\n\tCurrentDriver() (string, error)\n\tProbe() error\n\tID() string\n}\n\n\nfunc New(input string) (Device, error) {\n\tswitch {\n\tcase IsPciID.Match([]byte(input)):\n\t\treturn NewDeviceByPciID(input)\n\tcase IsUUID.Match([]byte(input)):\n\t\treturn NewDeviceByVmbusID(input)\n\tdefault:\n\t\treturn NewDeviceByNicName(input)\n\t}\n}\n\n\nfunc NewDeviceByPciID(pciID string) (Device, error) {\n\tdevice, err := GetPciDeviceByPciID(pciID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn device, nil\n}\n\n\n\n\n\nfunc NewDeviceByNicName(nicName string) (Device, error) {\n\tdevID, err := GetDeviceID(nicName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdevice, err := newDevice(devID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn device, nil\n}\n\nfunc newDevice(id string) (Device, error) {\n\tif IsPciID.Match([]byte(id)) {\n\t\treturn GetPciDeviceByPciID(id)\n\t}\n\treturn GetVmbusDeviceByUUID(id)\n}\n\nfunc NewDeviceByVmbusID(uuid string) (Device, error) ", "output": "{\n\tdevice, err := GetVmbusDeviceByUUID(uuid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn device, nil\n}"} {"input": "package netx\n\nimport (\n\t\"io\"\n\n\t\"github.com/simia-tech/netx/value\"\n)\n\ntype multicast struct {\n\tlistener io.ReadCloser\n\tconn io.WriteCloser\n}\n\n\n\nfunc ListenAndDialMulticast(network, readAddress, writeAddress string, options ...value.Option) (io.ReadWriteCloser, error) {\n\tlistener, err := ListenMulticast(network, readAddress, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn, err := DialMulticast(network, writeAddress, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &multicast{listener: listener, conn: conn}, nil\n}\n\nfunc (m *multicast) Read(buffer []byte) (int, error) {\n\treturn m.listener.Read(buffer)\n}\n\nfunc (m *multicast) Write(buffer []byte) (int, error) {\n\treturn m.conn.Write(buffer)\n}\n\n\n\nfunc (m *multicast) Close() error ", "output": "{\n\tif err := m.listener.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := m.conn.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package sleep\n\nimport \"sync/atomic\"\n\n\n\n\n\n\n\n\n\n\n\nfunc commitSleep(g uintptr, waitingG *uintptr) bool ", "output": "{\n\tfor {\n\t\tif atomic.LoadUintptr(waitingG) == 0 {\n\t\t\treturn false\n\t\t}\n\n\t\tif atomic.CompareAndSwapUintptr(waitingG, preparingG, g) {\n\t\t\treturn true\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\n\ntype Bitcoin int\n\ntype Wallet struct {\n\tbalance Bitcoin\n}\n\nfunc (b Bitcoin) String() string {\n\treturn fmt.Sprintf(\"%d BTC\", b)\n}\n\n\nfunc (w *Wallet) Balance() Bitcoin {\n\treturn w.balance\n}\n\nfunc (w *Wallet) Withdraw(amount Bitcoin) {\n\tw.balance -= amount\n}\n\nfunc main() {\n\tname := \"sss\"\n\tfmt.Println(name)\n}\n\nfunc (w *Wallet) Deposit(amount Bitcoin) ", "output": "{\n\tw.balance += amount\n}"} {"input": "package root\n\nimport (\n\t\"../../libs\"\n)\n\ntype RLogoutHandler struct {\n\tlibs.BaseHandler\n}\n\n\n\nfunc (self *RLogoutHandler) Get() ", "output": "{\n\tself.DelSession(\"userid\")\n\tself.DelSession(\"username\")\n\tself.DelSession(\"userrole\")\n\tself.DelSession(\"useremail\")\n\tself.Ctx.Redirect(302, \"/root-login\")\n\n}"} {"input": "package protolog \n\nimport (\n\t\"os\"\n\n\t\"go.pedge.io/dlog\"\n\t\"go.pedge.io/protolog\"\n)\n\nfunc init() {\n\tdlog.SetLogger(NewLogger(protolog.NewStandardLogger(protolog.NewFileFlusher(os.Stderr))))\n}\n\ntype logger struct {\n\tprotolog.Logger\n}\n\n\nfunc NewLogger(l protolog.Logger) dlog.Logger {\n\treturn &logger{l}\n}\n\nfunc (l *logger) Debug(args ...interface{}) {\n\tl.Debugln(args...)\n}\n\nfunc (l *logger) Info(args ...interface{}) {\n\tl.Infoln(args...)\n}\n\nfunc (l *logger) Warn(args ...interface{}) {\n\tl.Warnln(args...)\n}\n\n\n\nfunc (l *logger) Fatal(args ...interface{}) {\n\tl.Fatalln(args...)\n}\n\nfunc (l *logger) Panic(args ...interface{}) {\n\tl.Panicln(args...)\n}\n\nfunc (l *logger) Print(args ...interface{}) {\n\tl.Println(args...)\n}\n\nfunc (l *logger) Error(args ...interface{}) ", "output": "{\n\tl.Errorln(args...)\n}"} {"input": "package buildings\n\ntype store struct {\n\tbasicBuilding\n\timprovementLvl int8\n\tsales int\n\tprice int\n}\n\nfunc (*store) GetType() string { return \"store\" }\n\nfunc (b *store) GetRent() int { return [4]int{1, 2, 3, 5}[b.improvementLvl] }\nfunc (b *store) GetInternalInt(name string) int {\n\tswitch name {\n\tcase \"improvementLvl\":\n\t\treturn int(b.improvementLvl)\n\tcase \"sales\":\n\t\treturn b.sales\n\tcase \"price\":\n\t\treturn b.price\n\tdefault:\n\t\treturn 0\n\t}\n}\nfunc (b *store) SetInternalInt(name string, val int) {\n\tswitch name {\n\tcase \"improvementLvl\":\n\t\tb.improvementLvl = int8(val)\n\tcase \"sales\":\n\t\tb.sales = val\n\tcase \"price\":\n\t\tb.price = val\n\t}\n}\nfunc (b *store) ToString(x, y int) string {\n\treturn \"store,\" + string(b.improvementLvl) + \",\" + string(b.sales) + \",\" + string(b.price) + \",\" + b.basicBuilding.ToString(x, y)\n}\n\nfunc (b *store) GetRevenue() int ", "output": "{ return b.sales * b.price }"} {"input": "package bugreports\n\nimport \"github.com/cheekybits/genny/generic\"\n\n\ntype X generic.Type\n\n\ntype CellX struct {\n\tValue X\n}\n\nconst constantX = 1\n\nfunc funcX(p CellX) {}\n\n\n\n\n\nfunc exampleX() ", "output": "{\n\taCellX := CellX{}\n\tanotherCellX := CellX{}\n\tif aCellX != anotherCellX {\n\t\tprintln(constantX)\n\t\tpanic(constantX)\n\t}\n\tfuncX(CellX{})\n}"} {"input": "package api\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/resource\"\n)\n\n\nfunc (self ResourceName) String() string {\n\treturn string(self)\n}\n\n\nfunc (self *ResourceList) Cpu() *resource.Quantity {\n\tif val, ok := (*self)[ResourceCPU]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{}\n}\n\n\n\n\nfunc (self *ResourceList) Pods() *resource.Quantity {\n\tif val, ok := (*self)[ResourcePods]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{}\n}\n\nfunc GetContainerStatus(statuses []ContainerStatus, name string) (ContainerStatus, bool) {\n\tfor i := range statuses {\n\t\tif statuses[i].Name == name {\n\t\t\treturn statuses[i], true\n\t\t}\n\t}\n\treturn ContainerStatus{}, false\n}\n\nfunc GetExistingContainerStatus(statuses []ContainerStatus, name string) ContainerStatus {\n\tfor i := range statuses {\n\t\tif statuses[i].Name == name {\n\t\t\treturn statuses[i]\n\t\t}\n\t}\n\treturn ContainerStatus{}\n}\n\n\nfunc IsPodReady(pod *Pod) bool {\n\tfor _, c := range pod.Status.Conditions {\n\t\tif c.Type == PodReady && c.Status == ConditionTrue {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (self *ResourceList) Memory() *resource.Quantity ", "output": "{\n\tif val, ok := (*self)[ResourceMemory]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{}\n}"} {"input": "package config\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t_ \"github.com/confur-me/confur-api/lib/logrus\"\n\tcfg \"github.com/olebedev/config\"\n)\n\nvar c *cfg.Config\n\nfunc init() {\n\tc = new(cfg.Config)\n}\n\n\n\nfunc Config() *cfg.Config {\n\treturn c\n}\n\nfunc Read(path string) error ", "output": "{\n\tlog.Info(\"Reading configuration from \", path)\n\tvar err error\n\tc, err = cfg.ParseYamlFile(path)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\treturn err\n}"} {"input": "package kafka\n\nimport (\n\t\"encoding/binary\"\n\t\"hash/crc32\"\n)\n\ntype crc32Writer struct {\n\ttable *crc32.Table\n\tbuffer [8]byte\n\tcrc32 uint32\n}\n\nfunc (w *crc32Writer) update(b []byte) {\n\tw.crc32 = crc32.Update(w.crc32, w.table, b)\n}\n\nfunc (w *crc32Writer) writeInt8(i int8) {\n\tw.buffer[0] = byte(i)\n\tw.update(w.buffer[:1])\n}\n\nfunc (w *crc32Writer) writeInt16(i int16) {\n\tbinary.BigEndian.PutUint16(w.buffer[:2], uint16(i))\n\tw.update(w.buffer[:2])\n}\n\n\n\nfunc (w *crc32Writer) writeInt64(i int64) {\n\tbinary.BigEndian.PutUint64(w.buffer[:8], uint64(i))\n\tw.update(w.buffer[:8])\n}\n\nfunc (w *crc32Writer) writeBytes(b []byte) {\n\tn := len(b)\n\tif b == nil {\n\t\tn = -1\n\t}\n\tw.writeInt32(int32(n))\n\tw.update(b)\n}\n\nfunc (w *crc32Writer) Write(b []byte) (int, error) {\n\tw.update(b)\n\treturn len(b), nil\n}\n\nfunc (w *crc32Writer) WriteString(s string) (int, error) {\n\tw.update([]byte(s))\n\treturn len(s), nil\n}\n\nfunc (w *crc32Writer) writeInt32(i int32) ", "output": "{\n\tbinary.BigEndian.PutUint32(w.buffer[:4], uint32(i))\n\tw.update(w.buffer[:4])\n}"} {"input": "package s2\n\n\nvar (\n\t_ Shape = (*PointVector)(nil)\n)\n\n\n\n\n\n\n\n\ntype PointVector []Point\n\nfunc (p *PointVector) NumEdges() int { return len(*p) }\nfunc (p *PointVector) Edge(i int) Edge { return Edge{(*p)[i], (*p)[i]} }\nfunc (p *PointVector) ReferencePoint() ReferencePoint { return OriginReferencePoint(false) }\nfunc (p *PointVector) NumChains() int { return len(*p) }\nfunc (p *PointVector) Chain(i int) Chain { return Chain{i, 1} }\nfunc (p *PointVector) ChainEdge(i, j int) Edge { return Edge{(*p)[i], (*p)[j]} }\nfunc (p *PointVector) ChainPosition(e int) ChainPosition { return ChainPosition{e, 0} }\nfunc (p *PointVector) Dimension() int { return 0 }\n\nfunc (p *PointVector) IsFull() bool { return defaultShapeIsFull(p) }\nfunc (p *PointVector) typeTag() typeTag { return typeTagPointVector }\nfunc (p *PointVector) privateInterface() {}\n\nfunc (p *PointVector) IsEmpty() bool ", "output": "{ return defaultShapeIsEmpty(p) }"} {"input": "package main\n\nfunc f1(i int) {\n\tfor j := i - 1; j >= 0; j-- { \n\t}\n}\n\nfunc f2(i int, s string) {\n\tfor j := i + 1; j < len(s); j-- { \n\t}\n}\n\nfunc f3(s string) {\n\tfor i, l := 0, len(s); i > l; i++ { \n\t}\n}\n\n\n\nfunc f5(upper int, a []int) {\n\tfor i := upper + 1; i < len(a); i-- { \n\t\ta[i] = 0\n\t}\n}\n\nfunc f6(upper uint, a []int) {\n\tfor i := upper + 1; i < uint(len(a)); i-- { \n\t\ta[i] = 0\n\t}\n}\n\nfunc f7(a []int) {\n\tfor i := uint(len(a)) - 1; i < uint(len(a)); i-- { \n\t\ta[i] = 0\n\t}\n}\n\nfunc main() {}\n\nfunc f4(lower int, a []int) ", "output": "{\n\tfor i := lower - 1; i >= 0; i-- { \n\t\ta[i] = 0\n\t}\n}"} {"input": "package stringutil\n\nimport \"testing\"\n\n\n\nfunc TestReverse(t *testing.T) ", "output": "{\n\tcases := []struct {\n\t\tin, want string\n\t} {\n\t\t{\"Hello, world\", \"dlrow ,olleH\"},\n\t\t{\"Hello 世界\", \"界世 olleH\"},\n\t\t{\"\", \"\"},\n\t}\n\tfor _, c := range cases {\n\t\tgot := Reverse(c.in)\n\t\tif got != c.want {\n\t\t\tt.Errorf(\"Reverse(%q) == %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype UpdateDedicatedVmHostRequest struct {\n\n\tDedicatedVmHostId *string `mandatory:\"true\" contributesTo:\"path\" name:\"dedicatedVmHostId\"`\n\n\tUpdateDedicatedVmHostDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request UpdateDedicatedVmHostRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request UpdateDedicatedVmHostRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateDedicatedVmHostResponse struct {\n\n\tRawResponse *http.Response\n\n\tDedicatedVmHost `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateDedicatedVmHostResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response UpdateDedicatedVmHostResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request UpdateDedicatedVmHostRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\tproduct_of_all_other_numbers()\n}\n\nfunc product_of_all_other_numbers() ", "output": "{\n\n\tinitial_input := []int{1, 7, 3, 4}\n\tfinal_output := make([]int, len(initial_input))\n\n\tcurrent_product := 1\n\tfor i := 0; i < len(initial_input); i++ {\n\t\tfinal_output[i] = current_product\n\t\tcurrent_product *= initial_input[i]\n\t}\n\n\tcurrent_product = 1\n\n\tfor i := len(initial_input) - 1; i >= 0; i-- {\n\t\tfinal_output[i] *= current_product\n\t\tcurrent_product *= initial_input[i]\n\t}\n\n\tfmt.Print(final_output)\n\n}"} {"input": "package proc\n\nimport \"fmt\"\n\n\n\n\n\ntype Registers interface {\n\tPC() uint64\n\tSP() uint64\n\tCX() uint64\n\tTLS() uint64\n\tSetPC(*Thread, uint64) error\n\tString() string\n}\n\n\nfunc (thread *Thread) Registers() (Registers, error) {\n\tregs, err := registers(thread)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get registers: %s\", err)\n\t}\n\treturn regs, nil\n}\n\n\n\n\nfunc (thread *Thread) PC() (uint64, error) ", "output": "{\n\tregs, err := thread.Registers()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn regs.PC(), nil\n}"} {"input": "package v6\n\nimport (\n\t\"code.cloudfoundry.org/cli/command\"\n\t\"code.cloudfoundry.org/cli/command/flag\"\n\t\"code.cloudfoundry.org/cli/command/translatableerror\"\n)\n\ntype SetOrgRoleCommand struct {\n\tRequiredArgs flag.SetOrgRoleArgs `positional-args:\"yes\"`\n\tusage interface{} `usage:\"CF_NAME set-org-role USERNAME ORG ROLE\\n\\nROLES:\\n 'OrgManager' - Invite and manage users, select and change plans, and set spending limits\\n 'BillingManager' - Create and manage the billing account and payment info\\n 'OrgAuditor' - Read-only access to org info and reports\"`\n\trelatedCommands interface{} `related_commands:\"org-users, set-space-role\"`\n}\n\nfunc (SetOrgRoleCommand) Setup(config command.Config, ui command.UI) error {\n\treturn nil\n}\n\n\n\nfunc (SetOrgRoleCommand) Execute(args []string) error ", "output": "{\n\treturn translatableerror.UnrefactoredCommandError{}\n}"} {"input": "package zip\n\nimport (\n\t\"hash/crc32\"\n\n\t. \"github.com/zxh0/jvm.go/jvmgo/any\"\n\t\"github.com/zxh0/jvm.go/jvmgo/jvm/rtda\"\n\trtc \"github.com/zxh0/jvm.go/jvmgo/jvm/rtda/class\"\n)\n\n\n\nfunc _crc(method Any, name, desc string) {\n\trtc.RegisterNativeMethod(\"java/util/zip/CRC32\", name, desc, method)\n}\n\n\n\nfunc updateBytes(frame *rtda.Frame) {\n\tvars := frame.LocalVars()\n\tcrc := uint32(vars.GetInt(0))\n\tbyteArr := vars.GetRef(1)\n\toff := vars.GetInt(2)\n\t_len := vars.GetInt(3)\n\n\tgoBytes := byteArr.GoBytes()\n\tgoBytes = goBytes[off : off+_len]\n\tcrc = crc32.Update(crc, crc32.IEEETable, goBytes)\n\n\tstack := frame.OperandStack()\n\tstack.PushInt(int32(crc))\n}\n\nfunc init() ", "output": "{\n\t_crc(updateBytes, \"updateBytes\", \"(I[BII)I\")\n}"} {"input": "package flect\n\nimport (\n\t\"strings\"\n\t\"unicode\"\n)\n\nvar spaces = []rune{'_', ' ', ':', '-', '/'}\n\n\n\nfunc xappend(a []string, ss ...string) []string {\n\tfor _, s := range ss {\n\t\ts = strings.TrimSpace(s)\n\t\tfor _, x := range spaces {\n\t\t\ts = strings.Trim(s, string(x))\n\t\t}\n\t\tif _, ok := baseAcronyms[strings.ToUpper(s)]; ok {\n\t\t\ts = strings.ToUpper(s)\n\t\t}\n\t\tif s != \"\" {\n\t\t\ta = append(a, s)\n\t\t}\n\t}\n\treturn a\n}\n\nfunc abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n\nfunc isSpace(c rune) bool ", "output": "{\n\tfor _, r := range spaces {\n\t\tif r == c {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn unicode.IsSpace(c)\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os/signal\"\n\t\"runtime/pprof\"\n\t\"syscall\"\n\n\t\"github.com/brentp/bix\"\n\t\"github.com/brentp/irelate\"\n\tI \"github.com/brentp/irelate/interfaces\"\n)\n\n\n\nfunc check(e error) {\n\tif e != nil {\n\t\tlog.Fatal(e)\n\t}\n}\n\nfunc main() {\n\tf, err := os.Create(\"irelate.cpu.pprof\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tpprof.StartCPUProfile(f)\n\tdefer pprof.StopCPUProfile()\n\tfiles := os.Args[1:]\n\tbuf := bufio.NewWriter(os.Stdout)\n\tb, err := bix.New(files[0], 1)\n\tcheck(err)\n\tbx, err := b.Query(nil)\n\tcheck(err)\n\n\tqueryables := make([]I.Queryable, len(files)-1)\n\tfor i, f := range files[1:] {\n\t\tq, err := bix.New(f, 1)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tqueryables[i] = q\n\t}\n\n\tfor interval := range irelate.PIRelate(4000, 25000, bx, false, nil, queryables...) {\n\t\tfmt.Fprintf(buf, \"%s\\t%d\\t%d\\t%d\\n\", interval.Chrom(), interval.Start(), interval.End(), len(interval.Related()))\n\t}\n\tbuf.Flush()\n}\n\nfunc init() ", "output": "{\n\tdone := make(chan os.Signal, 1)\n\n\tsignal.Notify(done, os.Interrupt, syscall.SIGIO, syscall.SIGPIPE)\n\tgo func() {\n\t\tfor _ = range done {\n\t\t\tos.Exit(0)\n\t\t}\n\t}()\n}"} {"input": "package lapack\n\nimport (\n \n \"fmt\"\n \"github.com/hrautila/linalg\"\n \"github.com/hrautila/matrix\"\n)\n\n\nfunc Potrf(A matrix.Matrix, opts ...linalg.Option) error {\n switch A.(type) {\n case *matrix.FloatMatrix:\n return PotrfFloat(A.(*matrix.FloatMatrix), opts...)\n case *matrix.ComplexMatrix:\n return onError(\"Potrf: complex not implemented yet\")\n }\n return onError(\"Potrf unknown types\")\n}\n\n\n\nfunc checkPotrf(ind *linalg.IndexOpts, A matrix.Matrix) error {\n arows := ind.LDa\n if ind.N < 0 {\n ind.N = A.Rows()\n if ind.N != A.Cols() {\n return onError(\"Potrf: not square\")\n }\n }\n if ind.N == 0 {\n return nil\n }\n if ind.LDa == 0 {\n ind.LDa = max(1, A.LeadingIndex())\n arows = max(1, A.Rows())\n }\n if ind.LDa < max(1, ind.N) {\n return onError(\"Potrf: lda\")\n }\n if ind.OffsetA < 0 {\n return onError(\"Potrf: offsetA\")\n }\n if A.NumElements() < ind.OffsetA+(ind.N-1)*arows+ind.N {\n return onError(\"Potrf: sizeA\")\n }\n return nil\n}\n\nfunc PotrfFloat(A *matrix.FloatMatrix, opts ...linalg.Option) error ", "output": "{\n pars, err := linalg.GetParameters(opts...)\n if err != nil {\n return err\n }\n ind := linalg.GetIndexOpts(opts...)\n err = checkPotrf(ind, A)\n if ind.N == 0 {\n return nil\n }\n Aa := A.FloatArray()\n uplo := linalg.ParamString(pars.Uplo)\n info := dpotrf(uplo, ind.N, Aa[ind.OffsetA:], ind.LDa)\n if info != 0 {\n return onError(fmt.Sprintf(\"Potrf: lapack error %d\", info))\n }\n return nil\n}"} {"input": "package stick\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"go.mongodb.org/mongo-driver/bson\"\n)\n\n\ntype Coding string\n\n\nconst (\n\tJSON Coding = \"json\"\n\tBSON Coding = \"bson\"\n)\n\n\nfunc (c Coding) Marshal(in interface{}) ([]byte, error) {\n\tswitch c {\n\tcase JSON:\n\t\treturn json.Marshal(in)\n\tcase BSON:\n\t\treturn bson.Marshal(in)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"coal: unknown coding %q\", c))\n\t}\n}\n\n\nfunc (c Coding) Unmarshal(in []byte, out interface{}) error {\n\tswitch c {\n\tcase JSON:\n\t\treturn json.Unmarshal(in, out)\n\tcase BSON:\n\t\treturn bson.Unmarshal(in, out)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"coal: unknown coding %q\", c))\n\t}\n}\n\n\nfunc (c Coding) Transfer(in, out interface{}) error {\n\tbytes, err := c.Marshal(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.Unmarshal(bytes, out)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc GetBSONKey(field *reflect.StructField) string {\n\ttag := field.Tag.Get(\"bson\")\n\n\tif tag == \"-\" {\n\t\treturn \"\"\n\t}\n\n\tvalues := strings.Split(tag, \",\")\n\n\tif len(values) > 0 && len(values[0]) > 0 {\n\t\treturn values[0]\n\t}\n\n\treturn strings.ToLower(field.Name)\n}\n\nfunc GetJSONKey(field *reflect.StructField) string ", "output": "{\n\ttag := field.Tag.Get(\"json\")\n\n\tif tag == \"-\" {\n\t\treturn \"\"\n\t}\n\n\tvalues := strings.Split(tag, \",\")\n\n\tif len(values) > 0 && len(values[0]) > 0 {\n\t\treturn values[0]\n\t}\n\n\treturn field.Name\n}"} {"input": "package echo\n\nimport (\n\t\"bufio\"\n\t\"net\"\n\t\"net/http\"\n)\n\ntype (\n\tResponse struct {\n\t\techo *Echo\n\t\tbeforeFuncs []func()\n\t\tafterFuncs []func()\n\t\tWriter http.ResponseWriter\n\t\tStatus int\n\t\tSize int64\n\t\tCommitted bool\n\t}\n)\n\n\nfunc NewResponse(w http.ResponseWriter, e *Echo) (r *Response) {\n\treturn &Response{Writer: w, echo: e}\n}\n\n\n\n\n\n\n\nfunc (r *Response) Header() http.Header {\n\treturn r.Writer.Header()\n}\n\n\nfunc (r *Response) Before(fn func()) {\n\tr.beforeFuncs = append(r.beforeFuncs, fn)\n}\n\n\n\nfunc (r *Response) After(fn func()) {\n\tr.afterFuncs = append(r.afterFuncs, fn)\n}\n\n\n\n\n\nfunc (r *Response) WriteHeader(code int) {\n\tif r.Committed {\n\t\tr.echo.Logger.Warn(\"response already committed\")\n\t\treturn\n\t}\n\tfor _, fn := range r.beforeFuncs {\n\t\tfn()\n\t}\n\tr.Status = code\n\tr.Writer.WriteHeader(code)\n\tr.Committed = true\n}\n\n\n\n\n\n\n\nfunc (r *Response) Flush() {\n\tr.Writer.(http.Flusher).Flush()\n}\n\n\n\n\nfunc (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\treturn r.Writer.(http.Hijacker).Hijack()\n}\n\nfunc (r *Response) reset(w http.ResponseWriter) {\n\tr.beforeFuncs = nil\n\tr.afterFuncs = nil\n\tr.Writer = w\n\tr.Size = 0\n\tr.Status = http.StatusOK\n\tr.Committed = false\n}\n\nfunc (r *Response) Write(b []byte) (n int, err error) ", "output": "{\n\tif !r.Committed {\n\t\tif r.Status == 0 {\n\t\t\tr.Status = http.StatusOK\n\t\t}\n\t\tr.WriteHeader(r.Status)\n\t}\n\tn, err = r.Writer.Write(b)\n\tr.Size += int64(n)\n\tfor _, fn := range r.afterFuncs {\n\t\tfn()\n\t}\n\treturn\n}"} {"input": "package nfs\n\nimport (\n\t\"encoding/binary\"\n)\n\n\ntype xdr struct {\n\tdata []byte\n\toffset uint32\n}\n\nfunc newXDR(data []byte) *xdr {\n\tx := makeXDR(data)\n\treturn &x\n}\n\nfunc makeXDR(data []byte) xdr {\n\treturn xdr{data: data, offset: 0}\n}\n\nfunc (r *xdr) size() int {\n\treturn len(r.data)\n}\n\nfunc (r *xdr) getInt() int32 {\n\ti := int32(binary.BigEndian.Uint32(r.data[r.offset : r.offset+4]))\n\tr.offset += 4\n\treturn int32(i)\n}\n\nfunc (r *xdr) getUInt() uint32 {\n\ti := uint32(binary.BigEndian.Uint32(r.data[r.offset : r.offset+4]))\n\tr.offset += 4\n\treturn i\n}\n\nfunc (r *xdr) getHyper() int64 {\n\ti := int64(binary.BigEndian.Uint64(r.data[r.offset : r.offset+8]))\n\tr.offset += 8\n\treturn i\n}\n\nfunc (r *xdr) getUHyper() uint64 {\n\ti := uint64(binary.BigEndian.Uint64(r.data[r.offset : r.offset+8]))\n\tr.offset += 8\n\treturn i\n}\n\nfunc (r *xdr) getString() string {\n\treturn string(r.getDynamicOpaque())\n}\n\nfunc (r *xdr) getOpaque(length uint32) []byte {\n\tpadding := (4 - (length & 3)) & 3\n\tb := r.data[r.offset : r.offset+length]\n\tr.offset += length + padding\n\treturn b\n}\n\nfunc (r *xdr) getDynamicOpaque() []byte {\n\tl := r.getUInt()\n\treturn r.getOpaque(l)\n}\n\n\n\nfunc (r *xdr) getUIntVector() []uint32 ", "output": "{\n\tl := r.getUInt()\n\tv := make([]uint32, int(l))\n\tfor i := 0; i < len(v); i++ {\n\t\tv[i] = r.getUInt()\n\t}\n\treturn v\n}"} {"input": "package throttled\n\n\ntype WaitGroup struct {\n\tthrottle int\n\tcompleted chan bool\n\toutstanding int\n}\n\n\nfunc NewWaitGroup(throttle int) *WaitGroup {\n\treturn &WaitGroup{\n\t\toutstanding: 0,\n\t\tthrottle: throttle,\n\t\tcompleted: make(chan bool, throttle),\n\t}\n}\n\n\nfunc (w *WaitGroup) PeekThrottled() bool {\n\treturn w.outstanding+1 > w.throttle\n}\n\n\n\n\n\n\n\nfunc (w *WaitGroup) Done() {\n\tw.completed <- true\n}\n\n\nfunc (w *WaitGroup) Wait() {\n\tif w.outstanding == 0 {\n\t\treturn\n\t}\n\tfor w.outstanding > 0 {\n\t\tselect {\n\t\tcase <-w.completed:\n\t\t\tw.outstanding--\n\t\t}\n\t}\n}\n\nfunc (w *WaitGroup) Add() ", "output": "{\n\tw.outstanding++\n\tif w.outstanding > w.throttle {\n\t\tselect {\n\t\tcase <-w.completed:\n\t\t\tw.outstanding--\n\t\t\treturn\n\t\t}\n\t}\n}"} {"input": "package v1beta1\n\n\n\ntype ForZoneApplyConfiguration struct {\n\tName *string `json:\"name,omitempty\"`\n}\n\n\n\n\n\n\n\n\nfunc (b *ForZoneApplyConfiguration) WithName(value string) *ForZoneApplyConfiguration {\n\tb.Name = &value\n\treturn b\n}\n\nfunc ForZone() *ForZoneApplyConfiguration ", "output": "{\n\treturn &ForZoneApplyConfiguration{}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/gabriel-comeau/SimpleChatCommon\"\n\t\"github.com/gabriel-comeau/tbuikit\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\n\n\n\nfunc formatBroadCastMessage(message string, sender *ChatClient) string {\n\tmessage = strings.Trim(message, \" \\n\")\n\tvar output string\n\tif sender.nick != \"\" {\n\t\toutput = fmt.Sprintf(\"%v: %v\", sender.nick, message)\n\t} else {\n\t\toutput = fmt.Sprintf(\"%v: %v\", sender.id, message)\n\t}\n\n\treturn output\n}\n\n\nfunc formatWhisperMessage(message string, sender *ChatClient) string {\n\tmessage = strings.Trim(message, \" \\n\")\n\tvar output string\n\tif sender.nick != \"\" {\n\t\toutput = fmt.Sprintf(\" %v: %v\", sender.nick, message)\n\t} else {\n\t\toutput = fmt.Sprintf(\" %v: %v\", sender.id, message)\n\t}\n\n\treturn output\n}\n\n\nfunc nickTaken(n string, holder *ClientHolder) bool {\n\tfor _, c := range clientHolder.getClients() {\n\t\tif c.nick == n {\n\t\t\treturn true\n\t\t} else if n == strconv.FormatUint(c.id, 10) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc createMessageForBroadCast(text string, sender *ChatClient) *tbuikit.ColorizedString ", "output": "{\n\tformatted := formatBroadCastMessage(text, sender)\n\tmsg := SimpleChatCommon.Create(formatted, sender.color)\n\treturn msg\n}"} {"input": "package iso20022\n\n\ntype TransactionIdentifications3 struct {\n\n\tAccountOwnerTransactionIdentification *Max35Text `xml:\"AcctOwnrTxId\"`\n\n\tAccountServicerTransactionIdentification *Max35Text `xml:\"AcctSvcrTxId,omitempty\"`\n\n\tMarketInfrastructureTransactionIdentification *Max35Text `xml:\"MktInfrstrctrTxId,omitempty\"`\n}\n\nfunc (t *TransactionIdentifications3) SetAccountOwnerTransactionIdentification(value string) {\n\tt.AccountOwnerTransactionIdentification = (*Max35Text)(&value)\n}\n\nfunc (t *TransactionIdentifications3) SetAccountServicerTransactionIdentification(value string) {\n\tt.AccountServicerTransactionIdentification = (*Max35Text)(&value)\n}\n\n\n\nfunc (t *TransactionIdentifications3) SetMarketInfrastructureTransactionIdentification(value string) ", "output": "{\n\tt.MarketInfrastructureTransactionIdentification = (*Max35Text)(&value)\n}"} {"input": "package main\n\nimport . \"g2d\"\n\nvar screen = Point{480, 360}\nvar size = Point{20, 20}\n\ntype Ball struct {\n x, y int\n dx, dy int\n}\n\n\n\nfunc (b *Ball) Move() {\n if !(0 <= b.x+b.dx && b.x+b.dx <= screen.X-size.X) {\n b.dx = -b.dx\n }\n if !(0 <= b.y+b.dy && b.y+b.dy <= screen.Y-size.Y) {\n b.dy = -b.dy\n }\n b.x += b.dx\n b.y += b.dy\n}\n\nfunc (b *Ball) Position() Point {\n return Point{b.x, b.y}\n}\n\n\nvar b1 = NewBall(Point{40, 80})\nvar b2 = NewBall(Point{80, 40})\n\nfunc mainConsole() {\n for i := 0; i < 25; i++ {\n Println(\"Ball 1 @\", b1.Position())\n Println(\"Ball 2 @\", b2.Position())\n b1.Move()\n b2.Move()\n }\n}\n\nfunc tick() {\n ClearCanvas() \n b1.Move()\n b2.Move()\n DrawImage(\"ball.png\", b1.Position()) \n DrawImage(\"ball.png\", b2.Position()) \n}\n\nfunc main() {\n \n InitCanvas(screen)\n MainLoop(tick)\n}\n\nfunc NewBall(pos Point) *Ball ", "output": "{\n return &Ball{pos.X, pos.Y, 5, 5}\n}"} {"input": "package talib\n\n\n\nfunc init() ", "output": "{\n\tInitialize()\n}"} {"input": "package widgets\n\nimport (\n\t\"strings\"\n\n\t\"github.com/ambientsound/pms/songlist\"\n\t\"github.com/ambientsound/pms/style\"\n\t\"github.com/gdamore/tcell\"\n\t\"github.com/gdamore/tcell/views\"\n)\n\ntype ColumnheadersWidget struct {\n\tcolumns songlist.Columns\n\tview views.View\n\n\tstyle.Styled\n\tviews.WidgetWatchers\n}\n\nfunc NewColumnheadersWidget() (c *ColumnheadersWidget) {\n\tc = &ColumnheadersWidget{}\n\tc.columns = make(songlist.Columns, 0)\n\treturn\n}\n\nfunc (c *ColumnheadersWidget) SetColumns(cols songlist.Columns) {\n\tc.columns = cols\n}\n\nfunc (c *ColumnheadersWidget) Draw() {\n\tx := 0\n\ty := 0\n\tfor i := range c.columns {\n\t\tcol := c.columns[i]\n\t\ttitle := []rune(strings.Title(col.Tag()))\n\t\tp := 0\n\t\tfor _, r := range title {\n\t\t\tc.view.SetContent(x+p, y, r, nil, c.Style(\"header\"))\n\t\t\tp++\n\t\t}\n\t\tx += col.Width()\n\t}\n}\n\n\n\nfunc (c *ColumnheadersWidget) Size() (int, int) {\n\tx, y := c.view.Size()\n\ty = 1\n\treturn x, y\n}\n\nfunc (w *ColumnheadersWidget) Resize() {\n}\n\nfunc (w *ColumnheadersWidget) HandleEvent(ev tcell.Event) bool {\n\treturn false\n}\n\nfunc (c *ColumnheadersWidget) SetView(v views.View) ", "output": "{\n\tc.view = v\n}"} {"input": "package iso20022\n\n\ntype Header12 struct {\n\n\tDownloadTransfer *TrueFalseIndicator `xml:\"DwnldTrf\"`\n\n\tFormatVersion *Max6Text `xml:\"FrmtVrsn\"`\n\n\tExchangeIdentification *Max3NumericText `xml:\"XchgId\"`\n\n\tCreationDateTime *ISODateTime `xml:\"CreDtTm\"`\n\n\tInitiatingParty *GenericIdentification53 `xml:\"InitgPty\"`\n\n\tRecipientParty *GenericIdentification53 `xml:\"RcptPty,omitempty\"`\n}\n\nfunc (h *Header12) SetDownloadTransfer(value string) {\n\th.DownloadTransfer = (*TrueFalseIndicator)(&value)\n}\n\nfunc (h *Header12) SetFormatVersion(value string) {\n\th.FormatVersion = (*Max6Text)(&value)\n}\n\n\n\nfunc (h *Header12) SetCreationDateTime(value string) {\n\th.CreationDateTime = (*ISODateTime)(&value)\n}\n\nfunc (h *Header12) AddInitiatingParty() *GenericIdentification53 {\n\th.InitiatingParty = new(GenericIdentification53)\n\treturn h.InitiatingParty\n}\n\nfunc (h *Header12) AddRecipientParty() *GenericIdentification53 {\n\th.RecipientParty = new(GenericIdentification53)\n\treturn h.RecipientParty\n}\n\nfunc (h *Header12) SetExchangeIdentification(value string) ", "output": "{\n\th.ExchangeIdentification = (*Max3NumericText)(&value)\n}"} {"input": "package ecs\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs\"\n\t\"github.com/hashicorp/packer/helper/multistep\"\n\t\"github.com/hashicorp/packer/packer\"\n)\n\ntype stepShareAlicloudImage struct {\n\tAlicloudImageShareAccounts []string\n\tAlicloudImageUNShareAccounts []string\n\tRegionId string\n}\n\n\n\nfunc (s *stepShareAlicloudImage) Cleanup(state multistep.StateBag) {\n\t_, cancelled := state.GetOk(multistep.StateCancelled)\n\t_, halted := state.GetOk(multistep.StateHalted)\n\n\tif !cancelled && !halted {\n\t\treturn\n\t}\n\n\tui := state.Get(\"ui\").(packer.Ui)\n\tclient := state.Get(\"client\").(*ClientWrapper)\n\talicloudImages := state.Get(\"alicloudimages\").(map[string]string)\n\n\tui.Say(\"Restoring image share permission because cancellations or error...\")\n\n\tfor regionId, imageId := range alicloudImages {\n\t\tmodifyImageShareRequest := ecs.CreateModifyImageSharePermissionRequest()\n\t\tmodifyImageShareRequest.RegionId = regionId\n\t\tmodifyImageShareRequest.ImageId = imageId\n\t\tmodifyImageShareRequest.AddAccount = &s.AlicloudImageUNShareAccounts\n\t\tmodifyImageShareRequest.RemoveAccount = &s.AlicloudImageShareAccounts\n\t\tif _, err := client.ModifyImageSharePermission(modifyImageShareRequest); err != nil {\n\t\t\tui.Say(fmt.Sprintf(\"Restoring image share permission failed: %s\", err))\n\t\t}\n\t}\n}\n\nfunc (s *stepShareAlicloudImage) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction ", "output": "{\n\tclient := state.Get(\"client\").(*ClientWrapper)\n\talicloudImages := state.Get(\"alicloudimages\").(map[string]string)\n\n\tfor regionId, imageId := range alicloudImages {\n\t\tmodifyImageShareRequest := ecs.CreateModifyImageSharePermissionRequest()\n\t\tmodifyImageShareRequest.RegionId = regionId\n\t\tmodifyImageShareRequest.ImageId = imageId\n\t\tmodifyImageShareRequest.AddAccount = &s.AlicloudImageShareAccounts\n\t\tmodifyImageShareRequest.RemoveAccount = &s.AlicloudImageUNShareAccounts\n\n\t\tif _, err := client.ModifyImageSharePermission(modifyImageShareRequest); err != nil {\n\t\t\treturn halt(state, err, \"Failed modifying image share permissions\")\n\t\t}\n\t}\n\treturn multistep.ActionContinue\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n)\n\n\ntype Tree struct {\n\tLeft *Tree\n\tValue int\n\tRight *Tree\n}\n\n\n\nfunc Walk(t *Tree, ch chan int) {\n\tif t == nil {\n\t\treturn\n\t}\n\tWalk(t.Left, ch)\n\tch <- t.Value\n\tWalk(t.Right, ch)\n}\n\n\n\nfunc Walker(t *Tree) <-chan int {\n\tch := make(chan int)\n\tgo func() {\n\t\tWalk(t, ch)\n\t\tclose(ch)\n\t}()\n\treturn ch\n}\n\n\n\n\nfunc Compare(t1, t2 *Tree) bool {\n\tc1, c2 := Walker(t1), Walker(t2)\n\tfor {\n\t\tv1, ok1 := <-c1\n\t\tv2, ok2 := <-c2\n\t\tif !ok1 || !ok2 {\n\t\t\treturn ok1 == ok2\n\t\t}\n\t\tif v1 != v2 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\n\nfunc insert(t *Tree, v int) *Tree {\n\tif t == nil {\n\t\treturn &Tree{nil, v, nil}\n\t}\n\tif v < t.Value {\n\t\tt.Left = insert(t.Left, v)\n\t\treturn t\n\t}\n\tt.Right = insert(t.Right, v)\n\treturn t\n}\n\nfunc main() {\n\tt1 := New(100, 1)\n\tfmt.Println(Compare(t1, New(100, 1)), \"Same Contents\")\n\tfmt.Println(Compare(t1, New(99, 1)), \"Differing Sizes\")\n\tfmt.Println(Compare(t1, New(100, 2)), \"Differing Values\")\n\tfmt.Println(Compare(t1, New(101, 2)), \"Dissimilar\")\n}\n\nfunc New(n, k int) *Tree ", "output": "{\n\tvar t *Tree\n\tfor _, v := range rand.Perm(n) {\n\t\tt = insert(t, (1+v)*k)\n\t}\n\treturn t\n}"} {"input": "package in\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/blevesearch/bleve/analysis\"\n\t\"github.com/blevesearch/bleve/registry\"\n)\n\nconst NormalizeName = \"normalize_in\"\n\ntype IndicNormalizeFilter struct {\n}\n\n\n\nfunc (s *IndicNormalizeFilter) Filter(input analysis.TokenStream) analysis.TokenStream {\n\tfor _, token := range input {\n\t\trunes := bytes.Runes(token.Term)\n\t\trunes = normalize(runes)\n\t\ttoken.Term = analysis.BuildTermFromRunes(runes)\n\t}\n\treturn input\n}\n\nfunc NormalizerFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) {\n\treturn NewIndicNormalizeFilter(), nil\n}\n\nfunc init() {\n\tregistry.RegisterTokenFilter(NormalizeName, NormalizerFilterConstructor)\n}\n\nfunc NewIndicNormalizeFilter() *IndicNormalizeFilter ", "output": "{\n\treturn &IndicNormalizeFilter{}\n}"} {"input": "package subnets\n\nimport \"net\"\n\nfunc equals(a *net.IPNet, b *net.IPNet) bool {\n\taOnes, aBits := a.Mask.Size()\n\tbOnes, bBits := b.Mask.Size()\n\treturn a.IP.Equal(b.IP) && (aOnes == bOnes) && (aBits == bBits)\n}\n\nfunc overlaps(a *net.IPNet, b *net.IPNet) bool {\n\treturn a.Contains(b.IP) || b.Contains(a.IP)\n}\n\nfunc next(ip net.IP) net.IP {\n\tnext := clone(ip)\n\tfor i := len(next) - 1; i >= 0; i-- {\n\t\tnext[i]++\n\t\tif next[i] != 0 {\n\t\t\treturn next\n\t\t}\n\t}\n\n\tpanic(\"overflowed maximum IP\")\n}\n\nfunc clone(ip net.IP) net.IP {\n\tclone := make([]byte, len(ip))\n\tcopy(clone, ip)\n\treturn clone\n}\n\n\n\nfunc max(ipn *net.IPNet) net.IP ", "output": "{\n\tmask := ipn.Mask\n\tmin := clone(ipn.IP)\n\n\tif len(mask) != len(min) {\n\t\tpanic(\"length of mask is not compatible with length of network IP\")\n\t}\n\n\tmax := make([]byte, len(min))\n\tfor i, b := range mask {\n\t\tmax[i] = min[i] | ^b\n\t}\n\n\treturn net.IP(max).To16()\n}"} {"input": "package operator\n\nimport (\n\t\"time\"\n\n\t\"go-common/library/log\"\n\txtime \"go-common/library/time\"\n)\n\ntype Reddot struct {\n\tStartTime xtime.Time `json:\"start_time,omitempty\"`\n\tEndTime xtime.Time `json:\"end_time,omitempty\"`\n}\n\n\n\n\n\nfunc timeStrToInt(timeStr string) (timeInt xtime.Time) {\n\tvar err error\n\ttimeLayout := \"2006-01-02 15:04:05\"\n\tloc, _ := time.LoadLocation(\"Local\")\n\ttheTime, _ := time.ParseInLocation(timeLayout, timeStr, loc)\n\tif err = timeInt.Scan(theTime); err != nil {\n\t\tlog.Error(\"timeInt.Scan error(%v)\", err)\n\t}\n\treturn\n}\n\nfunc (r *Reddot) ReddotChange(startStr, endStr string) ", "output": "{\n\tif startStr != \"\" && endStr != \"\" {\n\t\tr.StartTime = timeStrToInt(startStr)\n\t\tr.EndTime = timeStrToInt(endStr)\n\t}\n}"} {"input": "package mailgun\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/getfider/fider/app/models/dto\"\n\t\"github.com/getfider/fider/app/pkg/bus\"\n\t\"github.com/getfider/fider/app/pkg/env\"\n\t\"github.com/getfider/fider/app/pkg/log\"\n)\n\n\n\n\nvar baseURLs = map[string]string{\n\t\"US\": \"https://api.mailgun.net/v3/%s\",\n\t\"EU\": \"https://api.eu.mailgun.net/v3/%s\",\n}\n\nfunc init() {\n\tbus.Register(Service{})\n}\n\ntype Service struct{}\n\nfunc (s Service) Name() string {\n\treturn \"Mailgun\"\n}\n\nfunc (s Service) Category() string {\n\treturn \"email\"\n}\n\nfunc (s Service) Enabled() bool {\n\treturn env.Config.Email.Type == \"mailgun\"\n}\n\nfunc (s Service) Init() {\n\tbus.AddListener(sendMail)\n\tbus.AddHandler(fetchRecentSupressions)\n}\n\n\n\n\n\nfunc getEndpoint(ctx context.Context, domain, path string) string ", "output": "{\n\tvar regionCode = env.Config.Email.Mailgun.Region\n\tregionCode = strings.ToUpper(regionCode)\n\n\tif len(regionCode) < 1 {\n\t\tregionCode = \"US\"\n\t} else if len(baseURLs[regionCode]) < 1 {\n\t\tlog.Warnf(ctx,\n\t\t\t\"Unknown Mailgun region code '@{Code}' configured - falling back to 'US'\",\n\t\t\tdto.Props{\n\t\t\t\t\"Code\": env.Config.Email.Mailgun.Region,\n\t\t\t},\n\t\t)\n\n\t\tregionCode = \"US\"\n\t}\n\n\treturn fmt.Sprintf(baseURLs[regionCode], domain) + path\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\n\ntype printable interface {\n print()\n}\n\n\n\ntype human struct {\n name string\n age int\n}\n\n\n\n\nfunc (h *human) print() {\n fmt.Printf(\"%v.%d\", h.name, h.age)\n}\n\ntype account struct {\n bank string\n balance int\n}\n\nfunc (a account) print() {\n fmt.Printf(\"[%v] %d\", a.bank, a.balance)\n}\n\nfunc main() {\n accounts := []account {\n {\"Bank of America\", 1000},\n {\"Chase\", 500},\n }\n humans := []human {\n {\"Steve\", 30},\n {\"Katie\", 28},\n {\"John\", 23},\n }\n printables := make([]printable, 0, len(accounts) + len(humans))\n for _, acc := range accounts {\n printables = append(printables, acc)\n }\n for i := range humans {\n \n \n \n printables = append(printables, &humans[i])\n }\n use(printables)\n}\n\nfunc use(printables []printable) ", "output": "{\n for _, p := range printables {\n p.print()\n fmt.Println()\n }\n}"} {"input": "package migration\n\nimport (\n\t\"github.com/jmoiron/sqlx\"\n)\n\ntype revision_db76e79e987 struct {\n}\n\n\n\nfunc (r *revision_db76e79e987) Up(tx *sqlx.Tx) error {\n\tstmts := []string{\n\t\t`ALTER TABLE _user ADD COLUMN last_login_at timestamp without time zone;`,\n\t\t`ALTER TABLE _user ADD COLUMN last_seen_at timestamp without time zone;`,\n\t}\n\tfor _, stmt := range stmts {\n\t\tif _, err := tx.Exec(stmt); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (r *revision_db76e79e987) Down(tx *sqlx.Tx) error {\n\tstmts := []string{\n\t\t`ALTER TABLE _user DROP COLUMN last_login_at;`,\n\t\t`ALTER TABLE _user DROP COLUMN last_seen_at;`,\n\t}\n\tfor _, stmt := range stmts {\n\t\tif _, err := tx.Exec(stmt); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (r *revision_db76e79e987) Version() string ", "output": "{ return \"db76e79e987\" }"} {"input": "package mem\n\nimport (\n\t\"bytes\"\n\t\"sort\"\n\n\tsgmt \"github.com/m3db/m3/src/m3ninx/index/segment\"\n)\n\ntype bytesSliceIter struct {\n\terr error\n\tdone bool\n\n\tcurrentIdx int\n\tcurrent []byte\n\tbackingSlice [][]byte\n\topts Options\n}\n\nvar _ sgmt.FieldsIterator = &bytesSliceIter{}\n\nfunc newBytesSliceIter(slice [][]byte, opts Options) *bytesSliceIter {\n\tsortSliceOfByteSlices(slice)\n\treturn &bytesSliceIter{\n\t\tcurrentIdx: -1,\n\t\tbackingSlice: slice,\n\t\topts: opts,\n\t}\n}\n\n\n\nfunc (b *bytesSliceIter) Current() []byte {\n\treturn b.current\n}\n\nfunc (b *bytesSliceIter) Err() error {\n\treturn nil\n}\n\nfunc (b *bytesSliceIter) Len() int {\n\treturn len(b.backingSlice)\n}\n\nfunc (b *bytesSliceIter) Close() error {\n\tb.current = nil\n\tb.opts.BytesSliceArrayPool().Put(b.backingSlice)\n\treturn nil\n}\n\nfunc sortSliceOfByteSlices(b [][]byte) {\n\tsort.Slice(b, func(i, j int) bool {\n\t\treturn bytes.Compare(b[i], b[j]) < 0\n\t})\n}\n\nfunc (b *bytesSliceIter) Next() bool ", "output": "{\n\tif b.done || b.err != nil {\n\t\treturn false\n\t}\n\tb.currentIdx++\n\tif b.currentIdx >= len(b.backingSlice) {\n\t\tb.done = true\n\t\treturn false\n\t}\n\tb.current = b.backingSlice[b.currentIdx]\n\treturn true\n}"} {"input": "package prometheus\n\nimport (\n\t\"math\"\n\t\"testing\"\n\n\tdto \"github.com/coreos/etcd-starter/Godeps/_workspace/src/github.com/prometheus/client_model/go\"\n)\n\nfunc TestCounterAdd(t *testing.T) {\n\tcounter := NewCounter(CounterOpts{\n\t\tName: \"test\",\n\t\tHelp: \"test help\",\n\t\tConstLabels: Labels{\"a\": \"1\", \"b\": \"2\"},\n\t}).(*counter)\n\tcounter.Inc()\n\tif expected, got := 1., math.Float64frombits(counter.valBits); expected != got {\n\t\tt.Errorf(\"Expected %f, got %f.\", expected, got)\n\t}\n\tcounter.Add(42)\n\tif expected, got := 43., math.Float64frombits(counter.valBits); expected != got {\n\t\tt.Errorf(\"Expected %f, got %f.\", expected, got)\n\t}\n\n\tif expected, got := \"counter cannot decrease in value\", decreaseCounter(counter).Error(); expected != got {\n\t\tt.Errorf(\"Expected error %q, got %q.\", expected, got)\n\t}\n\n\tm := &dto.Metric{}\n\tcounter.Write(m)\n\n\tif expected, got := `label: label: counter: `, m.String(); expected != got {\n\t\tt.Errorf(\"expected %q, got %q\", expected, got)\n\t}\n}\n\n\n\nfunc decreaseCounter(c *counter) (err error) ", "output": "{\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = e.(error)\n\t\t}\n\t}()\n\tc.Add(-1)\n\treturn nil\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"gx/ipfs/QmUWtNQd8JdEiYiDqNYTUcaqyteJZ2rTNQLiw3dauLPccy/gomega/format\"\n)\n\ntype HaveKeyMatcher struct {\n\tKey interface{}\n}\n\nfunc (matcher *HaveKeyMatcher) Match(actual interface{}) (success bool, err error) {\n\tif !isMap(actual) {\n\t\treturn false, fmt.Errorf(\"HaveKey matcher expects a map. Got:%s\", format.Object(actual, 1))\n\t}\n\n\tkeyMatcher, keyIsMatcher := matcher.Key.(omegaMatcher)\n\tif !keyIsMatcher {\n\t\tkeyMatcher = &EqualMatcher{Expected: matcher.Key}\n\t}\n\n\tkeys := reflect.ValueOf(actual).MapKeys()\n\tfor i := 0; i < len(keys); i++ {\n\t\tsuccess, err := keyMatcher.Match(keys[i].Interface())\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"HaveKey's key matcher failed with:\\n%s%s\", format.Indent, err.Error())\n\t\t}\n\t\tif success {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}\n\nfunc (matcher *HaveKeyMatcher) FailureMessage(actual interface{}) (message string) {\n\tswitch matcher.Key.(type) {\n\tcase omegaMatcher:\n\t\treturn format.Message(actual, \"to have key matching\", matcher.Key)\n\tdefault:\n\t\treturn format.Message(actual, \"to have key\", matcher.Key)\n\t}\n}\n\n\n\nfunc (matcher *HaveKeyMatcher) NegatedFailureMessage(actual interface{}) (message string) ", "output": "{\n\tswitch matcher.Key.(type) {\n\tcase omegaMatcher:\n\t\treturn format.Message(actual, \"not to have key matching\", matcher.Key)\n\tdefault:\n\t\treturn format.Message(actual, \"not to have key\", matcher.Key)\n\t}\n}"} {"input": "package all\n\nimport \"github.com/catorpilor/leetcode/utils\"\n\n\n\n\nfunc useMorris(root1, root2 *utils.TreeNode) []int {\n\tu1, u2 := utils.InorderTraversal(root1), utils.InorderTraversal(root2)\n\tn1, n2 := len(u1), len(u2)\n\tans := make([]int, 0, n1+n2)\n\tvar i, j int\n\tfor i != n1 && j != n2 {\n\t\tif u1[i] <= u2[j] {\n\t\t\tans = append(ans, u1[i])\n\t\t\ti++\n\t\t} else {\n\t\t\tans = append(ans, u2[j])\n\t\t\tj++\n\t\t}\n\t}\n\tif i != n1 {\n\t\tans = append(ans, u1[i:]...)\n\t}\n\tif j != n2 {\n\t\tans = append(ans, u2[j:]...)\n\t}\n\treturn ans\n}\n\nfunc allElements(root1, root2 *utils.TreeNode) []int ", "output": "{\n\treturn useMorris(root1, root2)\n}"} {"input": "package expression\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/pingcap/tidb/config\"\n\t\"github.com/pingcap/tidb/testkit/testmain\"\n\t\"github.com/pingcap/tidb/util/mock\"\n\t\"github.com/pingcap/tidb/util/testbridge\"\n\t\"github.com/pingcap/tidb/util/timeutil\"\n\t\"github.com/stretchr/testify/require\"\n\t\"github.com/tikv/client-go/v2/tikv\"\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\ttestbridge.WorkaroundGoCheckFlags()\n\ttestmain.ShortCircuitForBench(m)\n\n\tconfig.UpdateGlobal(func(conf *config.Config) {\n\t\tconf.TiKVClient.AsyncCommit.SafeWindow = 0\n\t\tconf.TiKVClient.AsyncCommit.AllowedClockDrift = 0\n\t\tconf.Experimental.AllowsExpressionIndex = true\n\t})\n\ttikv.EnableFailpoints()\n\n\ttimeutil.SetSystemTZ(\"system\")\n\n\topts := []goleak.Option{\n\t\tgoleak.IgnoreTopFunction(\"go.etcd.io/etcd/pkg/logutil.(*MergeLogger).outputLoop\"),\n\t\tgoleak.IgnoreTopFunction(\"go.opencensus.io/stats/view.(*worker).start\"),\n\t\tgoleak.IgnoreTopFunction(\"github.com/pingcap/tidb/table/tables.mockRemoteService\"),\n\t}\n\n\tgoleak.VerifyTestMain(m, opts...)\n}\n\n\n\nfunc createContext(t *testing.T) *mock.Context ", "output": "{\n\tctx := mock.NewContext()\n\tctx.GetSessionVars().StmtCtx.TimeZone = time.Local\n\tsc := ctx.GetSessionVars().StmtCtx\n\tsc.TruncateAsWarning = true\n\trequire.NoError(t, ctx.GetSessionVars().SetSystemVar(\"max_allowed_packet\", \"67108864\"))\n\tctx.GetSessionVars().PlanColumnID = 0\n\treturn ctx\n}"} {"input": "package instagram\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"net/url\"\n\n\t\"github.com/laicosly/goth\"\n\t\"golang.org/x/oauth2\"\n)\n\n\ntype Session struct {\n\tAuthURL string\n\tAccessToken string\n\tState string\n\tParams url.Values\n}\n\n\nfunc (s Session) GetAuthURL() (string, error) {\n\tif s.AuthURL == \"\" {\n\t\treturn \"\", errors.New(\"an AuthURL has not be set\")\n\t}\n\treturn s.AuthURL, nil\n}\n\n\nfunc (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {\n\tp := provider.(*Provider)\n\ttoken, err := p.config.Exchange(oauth2.NoContext, params.Get(\"code\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ts.AccessToken = token.AccessToken\n\treturn token.AccessToken, err\n}\n\n\n\n\nfunc (s Session) String() string {\n\treturn s.Marshal()\n}\n\nfunc (s Session) Marshal() string ", "output": "{\n\tb, _ := json.Marshal(s)\n\treturn string(b)\n}"} {"input": "package actor\n\nimport (\n\t\"time\"\n)\n\n\ntype RestartStatistics struct {\n\tfailureTimes []time.Time\n}\n\n\nfunc NewRestartStatistics() *RestartStatistics {\n\treturn &RestartStatistics{[]time.Time{}}\n}\n\n\nfunc (rs *RestartStatistics) FailureCount() int {\n\treturn len(rs.failureTimes)\n}\n\n\nfunc (rs *RestartStatistics) Fail() {\n\trs.failureTimes = append(rs.failureTimes, time.Now())\n}\n\n\n\n\n\nfunc (rs *RestartStatistics) NumberOfFailures(withinDuration time.Duration) int {\n\tif withinDuration == 0 {\n\t\treturn len(rs.failureTimes)\n\t}\n\n\tnum := 0\n\tcurrTime := time.Now()\n\tfor _, t := range rs.failureTimes {\n\t\tif currTime.Sub(t) < withinDuration {\n\t\t\tnum++\n\t\t}\n\t}\n\treturn num\n}\n\nfunc (rs *RestartStatistics) Reset() ", "output": "{\n\trs.failureTimes = []time.Time{}\n}"} {"input": "package term\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\n\nfunc IsTerminal(f *os.File) bool {\n\tcmd := exec.Command(\"test\", \"-t\", \"0\")\n\tcmd.Stdin = f\n\treturn cmd.Run() == nil\n}\n\nfunc MakeRaw(f *os.File) error {\n\treturn stty(f, \"-icanon\", \"-echo\").Run()\n}\n\nfunc Restore(f *os.File) error {\n\treturn stty(f, \"icanon\", \"echo\").Run()\n}\n\nfunc Cols() (int, error) {\n\tcols, err := tput(\"cols\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}\n\nfunc Lines() (int, error) {\n\tcols, err := tput(\"lines\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}\n\n\n\nfunc stty(f *os.File, args ...string) *exec.Cmd {\n\tc := exec.Command(\"stty\", args...)\n\tc.Stdin = f\n\treturn c\n}\n\nfunc tput(what string) (string, error) {\n\tc := exec.Command(\"tput\", what)\n\tc.Stderr = os.Stderr\n\tout, err := c.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.TrimSpace(string(out)), nil\n}\n\nfunc IsANSI(f *os.File) bool ", "output": "{\n\treturn IsTerminal(f)\n}"} {"input": "package config\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\ntype Config struct {\n\tDebug bool\n\tDryRun bool\n\tMasterAddress string\n\tHeartbeatInterval time.Duration\n}\n\n\n\n\n\nfunc (c *Config) Validate() error ", "output": "{\n\tif c.MasterAddress == \"\" {\n\t\treturn fmt.Errorf(\"master address is required\")\n\t}\n\n\tif c.HeartbeatInterval == 0 {\n\t\treturn fmt.Errorf(\"heartbeat interval can't be 0\")\n\t}\n\n\treturn nil\n}"} {"input": "package violetear\n\nimport (\n\t\"net/http\"\n\t\"time\"\n)\n\n\ntype ResponseWriter struct {\n\thttp.ResponseWriter\n\trequestID string\n\tsize, status int\n\tstart time.Time\n}\n\n\n\n\n\nfunc (w *ResponseWriter) Status() int {\n\treturn w.status\n}\n\n\nfunc (w *ResponseWriter) Size() int {\n\treturn w.size\n}\n\n\nfunc (w *ResponseWriter) RequestTime() string {\n\treturn time.Since(w.start).String()\n}\n\n\nfunc (w *ResponseWriter) RequestID() string {\n\treturn w.requestID\n}\n\n\n\nfunc (w *ResponseWriter) Write(data []byte) (int, error) {\n\tsize, err := w.ResponseWriter.Write(data)\n\tw.size += size\n\treturn size, err\n}\n\n\n\nfunc (w *ResponseWriter) WriteHeader(statusCode int) {\n\tw.status = statusCode\n\tw.ResponseWriter.WriteHeader(statusCode)\n}\n\nfunc NewResponseWriter(w http.ResponseWriter, rid string) *ResponseWriter ", "output": "{\n\treturn &ResponseWriter{\n\t\tResponseWriter: w,\n\t\trequestID: rid,\n\t\tstart: time.Now(),\n\t\tstatus: http.StatusOK,\n\t}\n}"} {"input": "package column\n\nimport (\n\t\"github.com/ClickHouse/clickhouse-go/lib/binary\"\n)\n\ntype Int32 struct{ base }\n\nfunc (Int32) Read(decoder *binary.Decoder, isNull bool) (interface{}, error) {\n\tv, err := decoder.Int32()\n\tif err != nil {\n\t\treturn int32(0), err\n\t}\n\treturn v, nil\n}\n\n\n\nfunc (i *Int32) Write(encoder *binary.Encoder, v interface{}) error ", "output": "{\n\tswitch v := v.(type) {\n\tcase int32:\n\t\treturn encoder.Int32(v)\n\tcase int64:\n\t\treturn encoder.Int32(int32(v))\n\tcase int:\n\t\treturn encoder.Int32(int32(v))\n\n\tcase *int32:\n\t\treturn encoder.Int32(*v)\n\tcase *int64:\n\t\treturn encoder.Int32(int32(*v))\n\tcase *int:\n\t\treturn encoder.Int32(int32(*v))\n\t}\n\n\treturn &ErrUnexpectedType{\n\t\tT: v,\n\t\tColumn: i,\n\t}\n}"} {"input": "package budget\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteBudgetRequest struct {\n\n\tBudgetId *string `mandatory:\"true\" contributesTo:\"path\" name:\"budgetId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteBudgetRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request DeleteBudgetRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request DeleteBudgetRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteBudgetResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteBudgetResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteBudgetResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteBudgetRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package observiqexporter \n\nimport (\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n)\n\n\n\nfunc newObservIQLogExporter(config *Config, set component.ExporterCreateSettings) (component.LogsExporter, error) ", "output": "{\n\tif config == nil {\n\t\treturn nil, errors.New(\"config must not be nil\")\n\t}\n\n\tif err := config.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient, err := buildClient(config, set.Logger, set.BuildInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texporter, err := exporterhelper.NewLogsExporter(\n\t\tconfig,\n\t\tset,\n\t\tclient.sendLogs,\n\t\texporterhelper.WithTimeout(exporterhelper.TimeoutSettings{Timeout: 0}),\n\t\texporterhelper.WithRetry(config.RetrySettings),\n\t\texporterhelper.WithQueue(config.QueueSettings),\n\t\texporterhelper.WithShutdown(client.stop),\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn exporter, nil\n}"} {"input": "package log\n\nimport (\n\t\"io\"\n\t\"sync\"\n)\n\ntype MirrorWriter struct {\n\twriters []io.Writer\n\tlk sync.Mutex\n}\n\n\n\nfunc (mw *MirrorWriter) AddWriter(w io.Writer) {\n\tmw.lk.Lock()\n\tmw.writers = append(mw.writers, w)\n\tmw.lk.Unlock()\n}\n\nfunc (mw *MirrorWriter) Active() (active bool) {\n\tmw.lk.Lock()\n\tactive = len(mw.writers) > 0\n\tmw.lk.Unlock()\n\treturn\n}\n\nfunc (mw *MirrorWriter) Write(b []byte) (int, error) ", "output": "{\n\tmw.lk.Lock()\n\tvar dropped bool\n\tfor i, w := range mw.writers {\n\t\t_, err := w.Write(b)\n\t\tif err != nil {\n\t\t\tmw.writers[i] = nil\n\t\t\tdropped = true\n\t\t}\n\t}\n\n\tif dropped {\n\t\twriters := mw.writers\n\t\tmw.writers = nil\n\t\tfor _, w := range writers {\n\t\t\tif w != nil {\n\t\t\t\tmw.writers = append(mw.writers, w)\n\t\t\t}\n\t\t}\n\t}\n\tmw.lk.Unlock()\n\treturn len(b), nil\n}"} {"input": "package logger\n\nimport \"testing\"\n\n\n\nfunc TestLog(t *testing.T) ", "output": "{\n\tLog(\"default\", \"shows this color\")\n\tLog(\"error\", \"shows this color\")\n\tLog(\"open\", \"shows this color\")\n\tLog(\"authorized\", \"shows this color\")\n\tLog(\"skip\", \"shows this color\")\n\tLog(\"git\", \"shows this color\")\n}"} {"input": "package types\n\nimport \"fmt\"\n\ntype IntegerValue struct {\n\tValue int64\n}\n\nfunc (v *IntegerValue) ToString() string {\n\treturn fmt.Sprint(v.Value)\n}\n\nfunc (v *IntegerValue) GetType() string {\n\treturn \"integer\"\n}\n\nfunc (v *IntegerValue) IsValue() bool {\n\treturn true\n}\n\nfunc (v *IntegerValue) ConvertTo(t string) (ValueType, error) {\n\treturn nil, fmt.Errorf(\"cannot convert integer to %s: does not implement yet\", t)\n}\n\n\n\nfunc NewIntegerValue(v int64) *IntegerValue {\n\treturn &IntegerValue{Value: v}\n}\n\nfunc (v *IntegerValue) EqualTo(t ValueType) bool ", "output": "{\n\tif v2, ok := t.(*IntegerValue); ok {\n\t\tif v2.Value == v.Value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package task\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"sir/models\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestTaskManager_StartTask(t *testing.T) {\n\tassertion := assert.New(t)\n\n\tmanager := NewTaskManager(\"/Users/hong/projects/src/sir/\")\n\n\ttask := &models.Task{\n\t\tTaskState: &models.TaskState{},\n\t\tTaskConfig: &models.TaskConfig{\n\t\t\tName: \"test\",\n\t\t\tCmd: \"/sbin/ping 114.114.114.114\",\n\t\t},\n\t}\n\terr := manager.StartTask(task)\n\tassertion.Nil(err)\n\tassertion.Equal(1, len(manager.Tasks))\n}\n\nfunc TestTaskManager_StopTask(t *testing.T) {\n\tassertion := assert.New(t)\n\n\tmanager := NewTaskManager(\"/Users/hong/projects/src/sir/\")\n\n\ttask := &models.Task{\n\t\tTaskState: &models.TaskState{},\n\t\tTaskConfig: &models.TaskConfig{\n\t\t\tName: \"test\",\n\t\t\tCmd: \"/sbin/ping 114.114.114.114\",\n\t\t},\n\t}\n\terr := manager.StartTask(task)\n\tassertion.Nil(err)\n\n\terr = manager.StopTask(task.Name)\n\tassertion.Nil(err)\n\n}\n\n\n\nfunc TestTaskManager_TaskState(t *testing.T) ", "output": "{\n\tassertion := assert.New(t)\n\n\tmanager := NewTaskManager(\"/Users/hong/projects/src/sir/\")\n\n\ttask := &models.Task{\n\t\tTaskState: &models.TaskState{},\n\t\tTaskConfig: &models.TaskConfig{\n\t\t\tName: \"test\",\n\t\t\tCmd: \"/sbin/ping 114.114.114.114\",\n\t\t},\n\t}\n\terr := manager.StartTask(task)\n\tassertion.Nil(err)\n\n\ttime.Sleep(time.Second)\n\n\tassertion.Empty(manager.Tasks[\"test\"].TaskState)\n}"} {"input": "package api\n\n\ntype UserInfo interface {\n\tGetName() string\n\tGetUID() string\n\tGetScope() string\n\tGetExtra() map[string]string\n}\n\n\n\ntype UserIdentityInfo interface {\n\tGetUserName() string\n\tGetProviderName() string\n\tGetExtra() map[string]string\n}\n\n\ntype UserIdentityMapper interface {\n\tUserFor(identityInfo UserIdentityInfo) (UserInfo, error)\n}\n\ntype Client interface {\n\tGetId() string\n\tGetSecret() string\n\tGetRedirectUri() string\n\tGetUserData() interface{}\n}\n\ntype Grant struct {\n\tClient Client\n\tScope string\n\tExpiration int64\n\tRedirectURI string\n}\n\ntype DefaultUserInfo struct {\n\tName string\n\tUID string\n\tScope string\n\tExtra map[string]string\n}\n\nfunc (i *DefaultUserInfo) GetName() string {\n\treturn i.Name\n}\n\nfunc (i *DefaultUserInfo) GetUID() string {\n\treturn i.UID\n}\n\nfunc (i *DefaultUserInfo) GetScope() string {\n\treturn i.Scope\n}\n\nfunc (i *DefaultUserInfo) GetExtra() map[string]string {\n\treturn i.Extra\n}\n\ntype DefaultUserIdentityInfo struct {\n\tUserName string\n\tProviderName string\n\tExtra map[string]string\n}\n\n\nfunc NewDefaultUserIdentityInfo(username string) DefaultUserIdentityInfo {\n\treturn DefaultUserIdentityInfo{\n\t\tUserName: username,\n\t\tExtra: make(map[string]string),\n\t}\n}\n\n\n\nfunc (i *DefaultUserIdentityInfo) GetProviderName() string {\n\treturn i.ProviderName\n}\n\nfunc (i *DefaultUserIdentityInfo) GetExtra() map[string]string {\n\treturn i.Extra\n}\n\nfunc (i *DefaultUserIdentityInfo) GetUserName() string ", "output": "{\n\treturn i.UserName\n}"} {"input": "package github\n\nimport (\n\t\"fmt\"\n)\n\ntype User struct {\n\tLogin string `json:\"login\"`\n\tType string `json:\"type\"`\n\tName string `json:\"name\"`\n\tEmail string `json:\"email\"`\n\tCompany string `json:\"company\"`\n\tLocation string `json:\"location\"`\n\tBlog string `json:\"blog\"`\n\tAvatar string `json:\"avatar_url\"`\n\tGravatarId string `json:\"gravatar_id\"`\n\tUrl string `json:\"html_url\"`\n}\n\ntype UserResource struct {\n\tclient *Client\n}\n\nfunc (r *UserResource) Current() (*User, error) {\n\tm := map[string]interface{}{}\n\tif err := r.client.do(\"GET\", \"/user\", nil, &m); err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser := mapToUser(m)\n\tif len(user.Login) == 0 {\n\t\treturn nil, ErrNotFound\n\t}\n\n\treturn user, nil\n}\n\nfunc (r *UserResource) Find(username string) (*User, error) {\n\tm := map[string]interface{}{}\n\tpath := fmt.Sprintf(\"/users/%s\", username)\n\tif err := r.client.do(\"GET\", path, nil, &m); err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser := mapToUser(m)\n\tif len(user.Login) == 0 {\n\t\treturn nil, ErrNotFound\n\t}\n\n\treturn user, nil\n}\n\n\n\n\n\n\nfunc mapToUser(m map[string]interface{}) *User ", "output": "{\n\tuser := User { }\n\tfor k, v := range m {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar str string\n\t\tvar ok bool\n\t\tif str, ok = v.(string); !ok {\n\t\t\tcontinue\n\t\t} \n\n\t\tswitch k {\n\t\tcase \"login\" : user.Login = str\n\t\tcase \"type\" : user.Type = str\n\t\tcase \"name\" : user.Name = str\n\t\tcase \"email\" : user.Email = str\n\t\tcase \"company\" : user.Company = str\n\t\tcase \"location\" : user.Location = str\n\t\tcase \"avatar_url\" : user.Avatar = str\n\t\tcase \"gravatar_id\" : user.GravatarId = str\n\t\tcase \"html_url\" : user.Url = str\n\t\t}\n\t}\n\n\treturn &user\n}"} {"input": "package iso20022\n\n\ntype FinancialInstrument11 struct {\n\n\tIdentification *SecurityIdentification3Choice `xml:\"Id\"`\n\n\tName *Max350Text `xml:\"Nm,omitempty\"`\n\n\tTransferType *TransferType1Code `xml:\"TrfTp\"`\n}\n\nfunc (f *FinancialInstrument11) AddIdentification() *SecurityIdentification3Choice {\n\tf.Identification = new(SecurityIdentification3Choice)\n\treturn f.Identification\n}\n\nfunc (f *FinancialInstrument11) SetName(value string) {\n\tf.Name = (*Max350Text)(&value)\n}\n\n\n\nfunc (f *FinancialInstrument11) SetTransferType(value string) ", "output": "{\n\tf.TransferType = (*TransferType1Code)(&value)\n}"} {"input": "package main\n\ntype Material struct {\n\ttexture *Texture\n\tcolor Vector3f\n\tspecularIntensity float32\n\tspecularPower float32\n}\n\n\n\nfunc NewMaterial(t *Texture) *Material ", "output": "{\n\tm := Material{\n\t\ttexture: t,\n\t\tcolor: Vector3f{1, 1, 1},\n\t\tspecularIntensity: 2,\n\t\tspecularPower: 32,\n\t}\n\treturn &m\n}"} {"input": "package mocks\n\nimport \"github.com/stretchr/testify/mock\"\n\nimport \"io\"\n\ntype RPCHeaderBuilder struct {\n\tmock.Mock\n}\n\n\n\n\nfunc (_m *RPCHeaderBuilder) WriteHeader(_a0 io.Writer, _a1 []byte, _a2 bool) error ", "output": "{\n\tret := _m.Called(_a0, _a1, _a2)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(io.Writer, []byte, bool) error); ok {\n\t\tr0 = rf(_a0, _a1, _a2)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc SieveOfEratosthenes(n int) []int ", "output": "{\n \n\tintegers := make([]bool, n+1)\n\tfor i := 2; i < n+1; i++ {\n\t\tintegers[i] = true\n\t}\n\n\tfor i := 2; i*i <= n; i++ {\n\t\tif integers[i] == true {\n\t\t\t\tfor j := i * 2; j <= n; j += i {\n\t\t\t\t\tintegers[j] = false\n\t\t\t\t}\n\t\t}\n\t}\n\n\t\tvar primes []int\n\t\tfor i := 2; i <= n; i++ {\n\t\t\tif integers[i] == true {\n\t\t\t\tprimes = append(primes, i)\n\t\t\t}\n\t\t}\n\t\treturn primes\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc merge(a, b, d []int) {\n i, j, k := 0, 0, 0\n na, nb := len(a), len(b)\n for i < na && j < nb {\n if a[i] < b[j] {\n d[k] = a[i]\n i++\n } else {\n d[k] = b[j]\n j++;\n }\n k++;\n }\n for i < na {\n d[k] = a[i]\n k++\n i++\n }\n for j < nb {\n d[k] = b[j]\n k++\n j++\n }\n}\n\n\n\nfunc merge_sort(a []int) {\n n := len(a)\n if n <= 1 {\n return\n }\n b := make([]int, n)\n merge_sort1(a[:n/2], b[:n/2])\n merge_sort1(a[n/2:], b[n/2:])\n merge(b[:n/2], b[n/2:], a)\n}\n\nfunc main() {\n a := []int{3,4,178,642,85,3,45,78,5,976,34,51,65,761,414,1,87,612,53,14,550}\n merge_sort(a)\n fmt.Println(a)\n}\n\nfunc merge_sort1(a, b []int) ", "output": "{\n n := len(a)\n if n == 1 {\n b[0] = a[0]\n return\n }\n merge_sort1(a[:n/2], b[:n/2])\n merge_sort1(a[n/2:], b[n/2:])\n merge(b[:n/2], b[n/2:], a)\n copy(b,a)\n}"} {"input": "package handlers\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/exercism/cli/api\"\n)\n\n\n\n\ntype Item struct {\n\t*api.Problem\n\tdir string\n\tisNew bool\n\tisUpdated bool\n}\n\n\nfunc (it *Item) Path() string {\n\treturn filepath.Join(it.dir, it.TrackID, it.Slug)\n}\n\n\n\n\n\nfunc (it *Item) Save() error {\n\tif _, err := os.Stat(it.Path()); err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t\tit.isNew = true\n\t}\n\n\tfor name, text := range it.Files {\n\t\tfile := filepath.Join(it.Path(), name)\n\n\t\terr := os.MkdirAll(filepath.Dir(file), 0755)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err := os.Stat(file); err != nil {\n\t\t\tif !os.IsNotExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif !it.isNew {\n\t\t\t\tit.isUpdated = true\n\t\t\t}\n\n\t\t\terr = ioutil.WriteFile(file, []byte(text), 0644)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (it *Item) Matches(filter HWFilter) bool ", "output": "{\n\tswitch filter {\n\tcase HWNew:\n\t\treturn it.isNew\n\tcase HWUpdated:\n\t\treturn it.isUpdated\n\t}\n\treturn true\n}"} {"input": "package main\n\nvar (\n\tmtx [][]int\n)\n\n\nfunc sum(arr []int) int {\n\ts := 0\n\tfor i := range arr {\n\t\tfor j := i; j < len(arr); j++ {\n\t\t\ts += mtx[i][j]\n\t\t}\n\t}\n\treturn s\n}\n\n\n\nfunc min(x int, y int) int ", "output": "{\n\tif x < y {\n\t\treturn x\n\t} else {\n\t\treturn y\n\t}\n}"} {"input": "package pool\n\nimport \"sync/atomic\"\n\n\ntype WorkUnit interface {\n\n\tWait()\n\n\tValue() interface{}\n\n\tError() error\n\n\tCancel()\n\n\tIsCancelled() bool\n}\n\nvar _ WorkUnit = new(workUnit)\n\n\ntype workUnit struct {\n\tvalue interface{}\n\terr error\n\tdone chan struct{}\n\tfn WorkFunc\n\tcancelled atomic.Value\n\tcancelling atomic.Value\n\twriting atomic.Value\n}\n\n\nfunc (wu *workUnit) Cancel() {\n\twu.cancelWithError(&ErrCancelled{s: errCancelled})\n}\n\nfunc (wu *workUnit) cancelWithError(err error) {\n\n\twu.cancelling.Store(struct{}{})\n\n\tif wu.writing.Load() == nil && wu.cancelled.Load() == nil {\n\t\twu.cancelled.Store(struct{}{})\n\t\twu.err = err\n\t\tclose(wu.done)\n\t}\n}\n\n\nfunc (wu *workUnit) Wait() {\n\t<-wu.done\n}\n\n\nfunc (wu *workUnit) Value() interface{} {\n\treturn wu.value\n}\n\n\nfunc (wu *workUnit) Error() error {\n\treturn wu.err\n}\n\n\n\n\n\n\nfunc (wu *workUnit) IsCancelled() bool ", "output": "{\n\twu.writing.Store(struct{}{}) \n\treturn wu.cancelled.Load() != nil\n}"} {"input": "package docker\n\nimport (\n\t\"github.com/rancher/os/config\"\n\n\tcomposeConfig \"github.com/docker/libcompose/config\"\n)\n\n\n\nfunc IsSystemContainer(serviceConfig *composeConfig.ServiceConfig) bool ", "output": "{\n\treturn serviceConfig.Labels[config.ScopeLabel] == config.System\n}"} {"input": "package shell\n\nimport (\n\t\"context\"\n\n\t\"github.com/hashicorp/hcl/v2/hcldec\"\n\tsl \"github.com/hashicorp/packer/common/shell-local\"\n\t\"github.com/hashicorp/packer/packer\"\n)\n\ntype Provisioner struct {\n\tconfig sl.Config\n}\n\n\n\nfunc (p *Provisioner) Prepare(raws ...interface{}) error {\n\terr := sl.Decode(&p.config, raws...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = sl.Validate(&p.config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (p *Provisioner) Provision(ctx context.Context, ui packer.Ui, _ packer.Communicator, generatedData map[string]interface{}) error {\n\t_, retErr := sl.Run(ctx, ui, &p.config, generatedData)\n\n\treturn retErr\n}\n\nfunc (p *Provisioner) ConfigSpec() hcldec.ObjectSpec ", "output": "{ return p.config.FlatMapstructure().HCL2Spec() }"} {"input": "package directory\n\nimport (\n\t\"github.com/corestoreio/csfw/config\"\n\t\"github.com/corestoreio/csfw/config/model\"\n\t\"github.com/corestoreio/csfw/store/scope\"\n\t\"github.com/juju/errgo\"\n\t\"golang.org/x/text/currency\"\n)\n\n\ntype ConfigCurrency struct {\n\tmodel.Str\n}\n\n\n\n\n\nfunc (p ConfigCurrency) Get(sg config.ScopedGetter) (Currency, error) {\n\tcur := p.Str.Get(sg)\n\tu, err := currency.ParseISO(cur)\n\tif err != nil {\n\t\treturn Currency{}, errgo.Mask(err)\n\t}\n\treturn Currency{Unit: u}, nil\n}\n\n\nfunc (p ConfigCurrency) Write(w config.Writer, v Currency, s scope.Scope, id int64) error {\n\treturn p.Str.Write(w, v.String(), s, id)\n}\n\nfunc NewConfigCurrency(path string, opts ...model.Option) ConfigCurrency ", "output": "{\n\treturn ConfigCurrency{\n\t\tStr: model.NewStr(path, opts...),\n\t}\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"html/template\"\n \"net/http\"\n \"strings\"\n \"log\"\n)\n\nfunc sayHelloName(w http.ResponseWriter, r *http.Request) {\n r.ParseForm()\n fmt.Println(\"---------------------------\")\n fmt.Println(\"Form\", r.Form)\n fmt.Println(\"path\", r.URL.Path)\n fmt.Println(\"scheme\", r.URL.Scheme)\n for k, v := range r.Form {\n fmt.Println(k, \"=\", strings.Join(v, \"\"))\n }\n\n fmt.Fprintf(w, \"Hello!!\" + strings.Join(r.Form[\"name\"], \"\"))\n}\n\n\n\nfunc main() {\n http.HandleFunc(\"/\", sayHelloName)\n http.HandleFunc(\"/login\", login)\n err := http.ListenAndServe(\":9090\", nil)\n if err != nil {\n log.Fatal(\"ListenAndServe:\", err)\n }\n}\n\nfunc login(w http.ResponseWriter, r *http.Request) ", "output": "{\n fmt.Println(\"method:\", r.Method)\n\n if r.Method == \"GET\" {\n t, _ := template.ParseFiles(\"login.gtpl\")\n t.Execute(w, nil)\n } else {\n r.ParseForm()\n fmt.Println(\"username:\", r.Form[\"username\"])\n fmt.Println(\"password:\", r.Form[\"password\"])\n }\n}"} {"input": "package restfuladapter\n\nimport (\n\t\"github.com/emicklei/go-restful\"\n\t\"k8s.io/kube-openapi/pkg/common\"\n)\n\nvar _ common.StatusCodeResponse = &ResponseErrorAdapter{}\n\n\ntype ResponseErrorAdapter struct {\n\tErr *restful.ResponseError\n}\n\nfunc (r *ResponseErrorAdapter) Message() string {\n\treturn r.Err.Message\n}\n\n\n\nfunc (r *ResponseErrorAdapter) Code() int {\n\treturn r.Err.Code\n}\n\nfunc (r *ResponseErrorAdapter) Model() interface{} ", "output": "{\n\treturn r.Err.Model\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSECSTaskDefinition_DockerVolumeConfiguration struct {\n\n\tAutoprovision bool `json:\"Autoprovision,omitempty\"`\n\n\tDriver string `json:\"Driver,omitempty\"`\n\n\tDriverOpts map[string]string `json:\"DriverOpts,omitempty\"`\n\n\tLabels map[string]string `json:\"Labels,omitempty\"`\n\n\tScope string `json:\"Scope,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) AWSCloudFormationType() string {\n\treturn \"AWS::ECS::TaskDefinition.DockerVolumeConfiguration\"\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\n\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSECSTaskDefinition_DockerVolumeConfiguration) Metadata() map[string]interface{} ", "output": "{\n\treturn r._metadata\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n)\n\n\n\ntype PoolStatus struct {\n\tPool string `json:\"pool\"`\n\tManager string `json:\"process manager\"`\n\tStartTime int `json:\"start time\"`\n\tStartSince int `json:\"start since\"`\n\tAcceptedConn int `json:\"accepted conn\"`\n\tListenQueue int `json:\"listen queue\"`\n\tMaxListenQueue int `json:\"max listen queue\"`\n\tListenQueueLen int `json:\"listen queue len\"`\n\tIdleProcesses int `json:\"idle processes\"`\n\tActiveProcesses int `json:\"active processes\"`\n\tTotalProcesses int `json:\"total processes\"`\n\tMaxActiveProcesses int `json:\"max active processes\"`\n\tMaxChildrenReached int `json:\"max children reached\"`\n\tSlowRequests int `json:\"slow requests\"`\n}\n\n\n\nfunc NewPoolStatus(r io.Reader) (*PoolStatus, error) ", "output": "{\n\tpoolStatus := new(PoolStatus)\n\n\tdecoder := json.NewDecoder(r)\n\terr := decoder.Decode(poolStatus)\n\treturn poolStatus, err\n}"} {"input": "package utils\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/juju/errors\"\n)\n\n\nfunc GetRequestBody(r *http.Request) ([]byte, error) {\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treturn body, nil\n}\n\n\nfunc Respond(w http.ResponseWriter, data interface{}, code int) error {\n\tw.WriteHeader(code)\n\n\tvar resp []byte\n\tvar err error\n\n\tresp, err = json.Marshal(data) \n\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfmt.Fprintln(w, string(resp))\n\n\treturn nil\n}\n\n\n\n\nfunc UnmarshalRequest(r *http.Request, v interface{}) error ", "output": "{\n\tbody, err := GetRequestBody(r)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tif err := json.Unmarshal(body, v); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\treturn nil\n}"} {"input": "package layers\n\nimport (\n\t\"math\"\n\n\t\"github.com/gerardabello/weight\"\n\t\"github.com/gerardabello/weight/tensor\"\n)\n\ntype SigmoidLayer struct {\n\tBaseLayer\n}\n\nfunc NewSigmoidLayer(size ...int) *SigmoidLayer {\n\tlayer := &SigmoidLayer{}\n\tlayer.BaseLayer.Init(size, size)\n\treturn layer\n}\n\nfunc (l *SigmoidLayer) CreateSlave() weight.Layer {\n\tnl := NewSigmoidLayer(l.GetInputSize()...)\n\tnl.id = l.ID()\n\n\treturn nl\n}\n\n\n\nfunc (l *SigmoidLayer) BackPropagate(err *tensor.Tensor) (*tensor.Tensor, error) {\n\tl.mutex.Lock()\n\te := l.BaseLayer.BackPropagate(err)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\n\terrs := err.Values\n\tinputs := l.lastInput.Values\n\n\tfor i := range l.propagation.Values {\n\t\tl.propagation.Values[i] = math.Exp(-inputs[i]) / math.Pow(1+math.Exp(-inputs[i]), 2) * errs[i]\n\t}\n\n\tl.mutex.Unlock()\n\treturn &l.propagation, nil\n}\n\nfunc (l *SigmoidLayer) Activate(input *tensor.Tensor) (*tensor.Tensor, error) ", "output": "{\n\tl.mutex.Lock()\n\terr := l.BaseLayer.Activate(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinputs := input.Values\n\n\tfor i := range l.output.Values {\n\t\tl.output.Values[i] = 1 / (1 + math.Exp(-inputs[i]))\n\t}\n\n\tl.mutex.Unlock()\n\treturn &l.output, nil\n}"} {"input": "package apmsynthetics\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetMonitorRequest struct {\n\n\tApmDomainId *string `mandatory:\"true\" contributesTo:\"query\" name:\"apmDomainId\"`\n\n\tMonitorId *string `mandatory:\"true\" contributesTo:\"path\" name:\"monitorId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetMonitorRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request GetMonitorRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request GetMonitorRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype GetMonitorResponse struct {\n\n\tRawResponse *http.Response\n\n\tMonitor `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetMonitorResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetMonitorResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetMonitorRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package callinfo\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\n\t\"github.com/youtube/vitess/go/rpcwrap/proto\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\n\ntype rpcWrapCallInfoImpl struct {\n\tremoteAddr, username string\n}\n\nfunc (rwci *rpcWrapCallInfoImpl) RemoteAddr() string {\n\treturn rwci.remoteAddr\n}\n\nfunc (rwci *rpcWrapCallInfoImpl) Username() string {\n\treturn rwci.username\n}\n\nfunc (rwci *rpcWrapCallInfoImpl) Text() string {\n\treturn fmt.Sprintf(\"%s@%s\", rwci.username, rwci.remoteAddr)\n}\n\nfunc (rwci *rpcWrapCallInfoImpl) HTML() template.HTML {\n\treturn template.HTML(\"RemoteAddr: \" + rwci.remoteAddr + \"
\\n\" + \"Username: \" + rwci.username + \"
\\n\")\n}\n\nfunc RPCWrapCallInfo(ctx context.Context) context.Context ", "output": "{\n\tremoteAddr, _ := proto.RemoteAddr(ctx)\n\tusername, _ := proto.Username(ctx)\n\treturn NewContext(ctx, &rpcWrapCallInfoImpl{\n\t\tremoteAddr: remoteAddr,\n\t\tusername: username,\n\t})\n}"} {"input": "package store\n\nimport \"strings\"\n\n\ntype ByPathLen []string\n\n\n\nfunc (s ByPathLen) Less(i, j int) bool {\n\treturn strings.Count(s[i], \"/\") < strings.Count(s[j], \"/\")\n}\n\nfunc (s ByPathLen) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\n\ntype ByLen []string\n\n\nfunc (s ByLen) Len() int { return len(s) }\n\n\nfunc (s ByLen) Less(i, j int) bool { return len(s[i]) > len(s[j]) }\n\n\nfunc (s ByLen) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s ByPathLen) Len() int ", "output": "{ return len(s) }"} {"input": "package queue_test\n\nimport \"testing\"\nimport \"github.com/ateleshev/go-bin/queue\"\n\n\n\nfunc TestMetric(t *testing.T) ", "output": "{\n\tvar n int64\n\tm := queue.NewMetric(\"test\")\n\tdefer func() {\n\t\tt.Log(\"Number\", n, m.Number())\n\t\talloc, sys, total := m.MemUsage()\n\t\tt.Log(\"MemUsage\", alloc, sys, total)\n\t\thAlloc, hSys, hObjects := m.HeapUsage()\n\t\tt.Log(\"HeapUsage\", hAlloc, hSys, hObjects)\n\t\tsInuse, sSys, otherSys := m.StackUsage()\n\t\tt.Log(\"StackUsage\", sInuse, sSys, otherSys)\n\t}()\n\n\tm.Begin()\n\tn = m.Increase()\n\tt.Log(n)\n\tn = m.Increase()\n\tt.Log(n)\n\tn = m.Increase()\n\tt.Log(n)\n\tn = m.Decrease()\n\tt.Log(n)\n\tm.Finish()\n}"} {"input": "package avl\n\n\nfunc (tree *Tree) First() *Node {\n\treturn tree.root.first()\n}\n\n\nfunc (tree *Node) first() *Node {\n\tif nil == tree {\n\t\treturn nil\n\t}\n\tfor nil != tree.left {\n\t\ttree = tree.left\n\t}\n\treturn tree\n}\n\n\nfunc (tree *Tree) Last() *Node {\n\treturn tree.root.last()\n}\n\n\nfunc (tree *Node) last() *Node {\n\tif nil == tree {\n\t\treturn nil\n\t}\n\tfor nil != tree.right {\n\t\ttree = tree.right\n\t}\n\treturn tree\n}\n\n\n\n\n\n\n\nfunc (tree *Node) Prev() *Node {\n\tif nil == tree.left {\n\t\tkey := tree.key\n\t\tfor {\n\t\t\ttree = tree.up\n\t\t\tif nil == tree {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif -1 == tree.key.Compare(key) { \n\t\t\t\treturn tree\n\t\t\t}\n\t\t}\n\t}\n\treturn tree.left.last()\n}\n\nfunc (tree *Node) Next() *Node ", "output": "{\n\tif nil == tree.right {\n\t\tkey := tree.key\n\t\tfor {\n\t\t\ttree = tree.up\n\t\t\tif nil == tree {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif 1 == tree.key.Compare(key) { \n\t\t\t\treturn tree\n\t\t\t}\n\t\t}\n\t}\n\treturn tree.right.first()\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realSecurityGroupRule SecurityGroupRule\n\nfunc (o *SecurityGroupRule) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realSecurityGroupRule\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = SecurityGroupRule(r)\n\treturn nil\n}\n\nvar _ fi.HasName = &SecurityGroupRule{}\n\nfunc (e *SecurityGroupRule) GetName() *string {\n\treturn e.Name\n}\n\n\n\nfunc (e *SecurityGroupRule) String() string {\n\treturn fi.TaskAsString(e)\n}\n\nfunc (e *SecurityGroupRule) SetName(name string) ", "output": "{\n\te.Name = &name\n}"} {"input": "package models\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/russross/blackfriday\"\n)\n\nvar (\n\ttab = []byte(\"\\t\")\n\tspaces = []byte(\" \")\n)\n\ntype MarkdownRender struct {\n\tblackfriday.Renderer\n}\n\nfunc (mr *MarkdownRender) BlockCode(out *bytes.Buffer, text []byte, lang string) {\n\tvar tmp bytes.Buffer\n\tmr.Renderer.BlockCode(&tmp, text, lang)\n\tout.Write(bytes.Replace(tmp.Bytes(), tab, spaces, -1))\n}\n\n\n\nfunc markdown(raw []byte) []byte ", "output": "{\n\thtmlFlags := 0 |\n\t\tblackfriday.HTML_USE_XHTML |\n\t\tblackfriday.HTML_USE_SMARTYPANTS |\n\t\tblackfriday.HTML_SMARTYPANTS_FRACTIONS |\n\t\tblackfriday.HTML_SMARTYPANTS_LATEX_DASHES\n\n\trenderer := &MarkdownRender{\n\t\tRenderer: blackfriday.HtmlRenderer(htmlFlags, \"\", \"\"),\n\t}\n\n\textensions := 0 |\n\t\tblackfriday.EXTENSION_NO_INTRA_EMPHASIS |\n\t\tblackfriday.EXTENSION_TABLES |\n\t\tblackfriday.EXTENSION_FENCED_CODE |\n\t\tblackfriday.EXTENSION_AUTOLINK |\n\t\tblackfriday.EXTENSION_STRIKETHROUGH |\n\t\tblackfriday.EXTENSION_SPACE_HEADERS |\n\t\tblackfriday.EXTENSION_HEADER_IDS\n\n\treturn blackfriday.Markdown(raw, renderer, extensions)\n}"} {"input": "package initramfs\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/u-root/u-root/pkg/cpio\"\n\t\"github.com/u-root/u-root/pkg/ulog\"\n)\n\n\ntype CPIOArchiver struct {\n\tcpio.RecordFormat\n}\n\n\n\n\n\n\nfunc (ca CPIOArchiver) OpenWriter(l ulog.Logger, path, goos, goarch string) (Writer, error) {\n\tif len(path) == 0 && len(goos) == 0 && len(goarch) == 0 {\n\t\treturn nil, fmt.Errorf(\"passed no path, GOOS, and GOARCH to CPIOArchiver.OpenWriter\")\n\t}\n\tif len(path) == 0 {\n\t\tpath = fmt.Sprintf(\"/tmp/initramfs.%s_%s.cpio\", goos, goarch)\n\t}\n\tf, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tl.Printf(\"Filename is %s\", path)\n\treturn osWriter{ca.RecordFormat.Writer(f), f}, nil\n}\n\n\ntype osWriter struct {\n\tcpio.RecordWriter\n\n\tf *os.File\n}\n\n\n\n\n\nfunc (ca CPIOArchiver) Reader(r io.ReaderAt) Reader {\n\treturn ca.RecordFormat.Reader(r)\n}\n\nfunc (o osWriter) Finish() error ", "output": "{\n\terr := cpio.WriteTrailer(o)\n\to.f.Close()\n\treturn err\n}"} {"input": "package logrus\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\nvar loggerFields = Fields{\n\t\"foo\": \"bar\",\n\t\"baz\": \"qux\",\n\t\"one\": \"two\",\n\t\"three\": \"four\",\n}\n\n\n\nfunc BenchmarkDummyLoggerNoLock(b *testing.B) {\n\tnullf, err := os.OpenFile(\"/dev/null\", os.O_WRONLY|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tb.Fatalf(\"%v\", err)\n\t}\n\tdefer nullf.Close()\n\tdoLoggerBenchmarkNoLock(b, nullf, &TextFormatter{DisableColors: true}, smallFields)\n}\n\nfunc doLoggerBenchmark(b *testing.B, out *os.File, formatter Formatter, fields Fields) {\n\tlogger := Logger{\n\t\tOut: out,\n\t\tLevel: InfoLevel,\n\t\tFormatter: formatter,\n\t}\n\tentry := logger.WithFields(fields)\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tentry.Info(\"aaa\")\n\t\t}\n\t})\n}\n\nfunc doLoggerBenchmarkNoLock(b *testing.B, out *os.File, formatter Formatter, fields Fields) {\n\tlogger := Logger{\n\t\tOut: out,\n\t\tLevel: InfoLevel,\n\t\tFormatter: formatter,\n\t}\n\tlogger.SetNoLock()\n\tentry := logger.WithFields(fields)\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tentry.Info(\"aaa\")\n\t\t}\n\t})\n}\n\nfunc BenchmarkDummyLogger(b *testing.B) ", "output": "{\n\tnullf, err := os.OpenFile(\"/dev/null\", os.O_WRONLY, 0666)\n\tif err != nil {\n\t\tb.Fatalf(\"%v\", err)\n\t}\n\tdefer nullf.Close()\n\tdoLoggerBenchmark(b, nullf, &TextFormatter{DisableColors: true}, smallFields)\n}"} {"input": "package spi\n\n\nfunc NewGroup(group *GroupInfo) Group {\n\treturn group\n}\n\n\nfunc (g *GroupInfo) GetName() string {\n\treturn g.Name\n}\n\n\nfunc (g *GroupInfo) GetChildren() ([]Group, error) {\n\treturn nil, nil\n}\n\n\n\n\nfunc (g *GroupInfo) GetParent() string ", "output": "{\n\treturn g.ParentID\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\thyperclient \"github.com/Cloud-Foundations/Dominator/hypervisor/client\"\n\t\"github.com/Cloud-Foundations/Dominator/lib/log\"\n)\n\nfunc connectToVmConsoleSubcommand(args []string,\n\tlogger log.DebugLogger) error {\n\tif err := connectToVmConsole(args[0], logger); err != nil {\n\t\treturn fmt.Errorf(\"Error connecting to VM console: %s\", err)\n\t}\n\treturn nil\n}\n\nfunc connectToVmConsole(vmHostname string, logger log.DebugLogger) error {\n\tif vmIP, hypervisor, err := lookupVmAndHypervisor(vmHostname); err != nil {\n\t\treturn err\n\t} else {\n\t\treturn connectToVmConsoleOnHypervisor(hypervisor, vmIP, logger)\n\t}\n}\n\n\n\nfunc connectToVmConsoleOnHypervisor(hypervisor string, ipAddr net.IP,\n\tlogger log.DebugLogger) error ", "output": "{\n\tclient, err := dialHypervisor(hypervisor)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.Close()\n\treturn hyperclient.ConnectToVmConsole(client, ipAddr, *vncViewer, logger)\n}"} {"input": "package wal\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/coreos/mantle/Godeps/_workspace/src/github.com/coreos/etcd/raft/raftpb\"\n)\n\nfunc BenchmarkWrite100EntryWithoutBatch(b *testing.B) { benchmarkWriteEntry(b, 100, 0) }\nfunc BenchmarkWrite100EntryBatch10(b *testing.B) { benchmarkWriteEntry(b, 100, 10) }\nfunc BenchmarkWrite100EntryBatch100(b *testing.B) { benchmarkWriteEntry(b, 100, 100) }\nfunc BenchmarkWrite100EntryBatch500(b *testing.B) { benchmarkWriteEntry(b, 100, 500) }\nfunc BenchmarkWrite100EntryBatch1000(b *testing.B) { benchmarkWriteEntry(b, 100, 1000) }\n\nfunc BenchmarkWrite1000EntryWithoutBatch(b *testing.B) { benchmarkWriteEntry(b, 1000, 0) }\nfunc BenchmarkWrite1000EntryBatch10(b *testing.B) { benchmarkWriteEntry(b, 1000, 10) }\nfunc BenchmarkWrite1000EntryBatch100(b *testing.B) { benchmarkWriteEntry(b, 1000, 100) }\nfunc BenchmarkWrite1000EntryBatch500(b *testing.B) { benchmarkWriteEntry(b, 1000, 500) }\nfunc BenchmarkWrite1000EntryBatch1000(b *testing.B) { benchmarkWriteEntry(b, 1000, 1000) }\n\n\n\nfunc benchmarkWriteEntry(b *testing.B, size int, batch int) ", "output": "{\n\tp, err := ioutil.TempDir(os.TempDir(), \"waltest\")\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\tdefer os.RemoveAll(p)\n\n\tw, err := Create(p, []byte(\"somedata\"))\n\tif err != nil {\n\t\tb.Fatalf(\"err = %v, want nil\", err)\n\t}\n\tdata := make([]byte, size)\n\tfor i := 0; i < len(data); i++ {\n\t\tdata[i] = byte(i)\n\t}\n\te := &raftpb.Entry{Data: data}\n\n\tb.ResetTimer()\n\tn := 0\n\tfor i := 0; i < b.N; i++ {\n\t\terr := w.saveEntry(e)\n\t\tif err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t\tn++\n\t\tif n > batch {\n\t\t\tw.sync()\n\t\t\tn = 0\n\t\t}\n\t}\n}"} {"input": "package config\n\nimport \"github.com/corestoreio/csfw/utils\"\n\n\n\ntype ScopePerm uint64\n\n\nvar ScopePermAll = ScopePerm(1< 0 {\n\t\t\toutputs[i] = fmt.Sprintf(\"%v \", output.Name)\n\t\t}\n\t\toutputs[i] += output.Type.String()\n\t}\n\tconstant := \"\"\n\tif m.Const {\n\t\tconstant = \"constant \"\n\t}\n\treturn fmt.Sprintf(\"function %v(%v) %sreturns(%v)\", m.Name, strings.Join(inputs, \", \"), constant, strings.Join(outputs, \", \"))\n}"} {"input": "package handlers\n\nimport (\n\t\"fmt\"\n\t\"github.com/peterhoward42/frost/resources\"\n\t\"github.com/peterhoward42/frost/server/render\"\n\t\"github.com/peterhoward42/frost/server/viewmodels\"\n\t\"net/http\"\n\t\"strings\"\n\t\"github.com/peterhoward42/frost/server/urls\"\n)\n\nfunc HandleQuickStart(w http.ResponseWriter, r *http.Request) {\n\tviewModel := viewmodels.NewTopLevelViewModel()\n\tviewModel.QuickStart = viewmodels.NewQuickStartViewModel()\n\trenderer := view.NewGuiRenderer(resources.CompiledTemplates)\n\trenderer.Render(w, viewModel)\n}\n\n\n\n\n\n\n\nfunc HandlePlayground(w http.ResponseWriter, r *http.Request) {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Cannot parse form. Error is: %v\", err))\n\t}\n\tviewModel := viewmodels.NewTopLevelViewModel()\n\tswitch {\n\tcase strings.Contains(r.URL.Path, urls.URLPlaygroundRefreshStub):\n\t\tviewModel.Playground = viewmodels.NewPlaygroundViewModelForRefresh(\n\t\t\tr.Form, r.URL.Path)\n\tcase strings.Contains(r.URL.Path, urls.URLPlaygroundExampleSpaceDelim):\n\t\texampleInputText :=resources.GetExampleFileContents(resources.SpaceDelimitedExample)\n\t\tspaceSeparatedButtonActiveString := \"active\"\n\t\tviewModel.Playground = viewmodels.NewPlaygroundViewModelForExample(\n\t\t\texampleInputText, spaceSeparatedButtonActiveString)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"URL that reached HandlePlayground contains neither refresh\"+\n\t\t\t\"nor example variant hint: %v\", r.URL.Path))\n\t}\n\trenderer := view.NewGuiRenderer(resources.CompiledTemplates)\n\trenderer.Render(w, viewModel)\n}\n\n\n\nfunc HandleComingSoon(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tviewModel := viewmodels.NewTopLevelViewModel()\n\tviewModel.ComingSoon = &viewmodels.ComingSoonViewModel{}\n\trenderer := view.NewGuiRenderer(resources.CompiledTemplates)\n\trenderer.Render(w, viewModel)\n}"} {"input": "package processors\n\nimport (\n\t\"github.com/golangci/golangci-lint/pkg/config\"\n\t\"github.com/golangci/golangci-lint/pkg/result\"\n)\n\ntype lineToCount map[int]int\ntype fileToLineToCount map[string]lineToCount\n\ntype UniqByLine struct {\n\tflc fileToLineToCount\n\tcfg *config.Config\n}\n\n\n\nvar _ Processor = &UniqByLine{}\n\nfunc (p UniqByLine) Name() string {\n\treturn \"uniq_by_line\"\n}\n\nfunc (p *UniqByLine) Process(issues []result.Issue) ([]result.Issue, error) {\n\tif !p.cfg.Output.UniqByLine {\n\t\treturn issues, nil\n\t}\n\n\treturn filterIssues(issues, func(i *result.Issue) bool {\n\t\tif i.Replacement != nil && p.cfg.Issues.NeedFix {\n\t\t\treturn true\n\t\t}\n\n\t\tlc := p.flc[i.FilePath()]\n\t\tif lc == nil {\n\t\t\tlc = lineToCount{}\n\t\t\tp.flc[i.FilePath()] = lc\n\t\t}\n\n\t\tconst limit = 1\n\t\tcount := lc[i.Line()]\n\t\tif count == limit {\n\t\t\treturn false\n\t\t}\n\n\t\tlc[i.Line()]++\n\t\treturn true\n\t}), nil\n}\n\nfunc (p UniqByLine) Finish() {}\n\nfunc NewUniqByLine(cfg *config.Config) *UniqByLine ", "output": "{\n\treturn &UniqByLine{\n\t\tflc: fileToLineToCount{},\n\t\tcfg: cfg,\n\t}\n}"} {"input": "package integrationtests\n\nimport (\n\t\"testing\"\n\n\t\"github.com/bunsenapp/go-selenium\"\n)\n\n\n\nfunc Test_CommandSwitchToParentFrame_CorrectResponseCanBeReturned(t *testing.T) ", "output": "{\n\tsetUp()\n\tdefer tearDown()\n\n\tdriver := createDriver(t)\n\t_, err := driver.CreateSession()\n\tif err != nil {\n\t\terrorAndWrap(t, \"Error thrown whilst creating session.\", err)\n\t}\n\n\t_, err = driver.Go(\"https://bunsenapp.github.io/go-selenium/helpers/iframe.html\")\n\tif err != nil {\n\t\terrorAndWrap(t, \"Error was thrown whilst navigating.\", err)\n\t}\n\n\t_, err = driver.SwitchToFrame(goselenium.ByIndex(0))\n\tif err != nil {\n\t\terrorAndWrap(t, \"Error was thrown whilst switching to frame 0.\", err)\n\t}\n\n\tresp, err := driver.SwitchToParentFrame()\n\tif err != nil || resp.State != \"success\" {\n\t\terrorAndWrap(t, \"Error was thrown or response was not a success.\", err)\n\t}\n\n\tprintObjectResult(resp)\n}"} {"input": "package elastic\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n)\n\nfunc TestRangeFilter(t *testing.T) {\n\tf := NewRangeFilter(\"postDate\").From(\"2010-03-01\").To(\"2010-04-01\")\n\tf = f.Cache(true)\n\tf = f.CacheKey(\"MyAndFilter\")\n\tf = f.FilterName(\"MyFilterName\")\n\tf = f.Execution(\"index\")\n\tdata, err := json.Marshal(f.Source())\n\tif err != nil {\n\t\tt.Fatalf(\"marshaling to JSON failed: %v\", err)\n\t}\n\tgot := string(data)\n\texpected := `{\"range\":{\"_cache\":true,\"_cache_key\":\"MyAndFilter\",\"_name\":\"MyFilterName\",\"execution\":\"index\",\"postDate\":{\"from\":\"2010-03-01\",\"include_lower\":true,\"include_upper\":true,\"to\":\"2010-04-01\"}}}`\n\tif got != expected {\n\t\tt.Errorf(\"expected\\n%s\\n,got:\\n%s\", expected, got)\n\t}\n}\n\n\n\nfunc TestRangeFilterWithTimeZone(t *testing.T) {\n\tf := NewRangeFilter(\"born\").\n\t\tGte(\"2012-01-01\").\n\t\tLte(\"now\").\n\t\tTimeZone(\"+1:00\")\n\tdata, err := json.Marshal(f.Source())\n\tif err != nil {\n\t\tt.Fatalf(\"marshaling to JSON failed: %v\", err)\n\t}\n\tgot := string(data)\n\texpected := `{\"range\":{\"born\":{\"from\":\"2012-01-01\",\"include_lower\":true,\"include_upper\":true,\"time_zone\":\"+1:00\",\"to\":\"now\"}}}`\n\tif got != expected {\n\t\tt.Errorf(\"expected\\n%s\\n,got:\\n%s\", expected, got)\n\t}\n}\n\n\n\nfunc TestRangeFilterWithFormat(t *testing.T) ", "output": "{\n\tf := NewRangeFilter(\"born\").\n\t\tGte(\"2012/01/01\").\n\t\tLte(\"now\").\n\t\tFormat(\"yyyy/MM/dd\")\n\tdata, err := json.Marshal(f.Source())\n\tif err != nil {\n\t\tt.Fatalf(\"marshaling to JSON failed: %v\", err)\n\t}\n\tgot := string(data)\n\texpected := `{\"range\":{\"born\":{\"format\":\"yyyy/MM/dd\",\"from\":\"2012/01/01\",\"include_lower\":true,\"include_upper\":true,\"to\":\"now\"}}}`\n\tif got != expected {\n\t\tt.Errorf(\"expected\\n%s\\n,got:\\n%s\", expected, got)\n\t}\n}"} {"input": "package twofactor\n\nimport (\n\t\"bytes\"\n\t\"encoding/base32\"\n\t\"testing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\ntype TwoFactorSuite struct{}\n\nvar _ = Suite(&TwoFactorSuite{})\n\n\n\nfunc (s *TwoFactorSuite) TestNewSecret(c *C) {\n\tsecret, _ := NewSecret(0)\n\tc.Check(len(secret), Equals, 16)\n}\n\nfunc (s *TwoFactorSuite) TestSecretBytes(c *C) {\n\tstr := \"thisisasecret\"\n\tstrb, _ := base32.StdEncoding.DecodeString(str)\n\tsecret := Secret(str)\n\tbytes, _ := secret.Bytes()\n\tc.Check(len(bytes), Equals, len(strb))\n\tfor i, b := range bytes {\n\t\tc.Check(b, Equals, strb[i])\n\t}\n}\n\nfunc (s *TwoFactorSuite) TestSecretString(c *C) {\n\tstr := \"thisisasecret\"\n\tsecret := Secret(str)\n\tc.Check(secret.String(), Equals, str)\n}\n\nfunc (s *TwoFactorSuite) BenchmarkNewSecret(c *C) {\n\tfor i := 0; i < c.N; i++ {\n\t\tNewSecret(0)\n\t}\n}\n\nfunc (s *TwoFactorSuite) TestInt64ToBytes(c *C) ", "output": "{\n\tints := []int64{10, 200, 3000, 40000, 500000}\n\tintBytes := [][]byte{\n\t\t[]byte{0, 0, 0, 0, 0, 0, 0, 10},\n\t\t[]byte{0, 0, 0, 0, 0, 0, 0, 200},\n\t\t[]byte{0, 0, 0, 0, 0, 0, 11, 184},\n\t\t[]byte{0, 0, 0, 0, 0, 0, 156, 64},\n\t\t[]byte{0, 0, 0, 0, 0, 7, 161, 32},\n\t}\n\tfor i, n := range ints {\n\t\tc.Check(bytes.Compare(Int64ToBytes(n), intBytes[i]), Equals, 0)\n\t}\n}"} {"input": "package libnetwork\n\nimport \"github.com/docker/docker/libnetwork/ipamapi\"\n\n\n\nfunc (n *network) startResolver() {\n}\n\n\n\nfunc defaultIpamForNetworkType(networkType string) string ", "output": "{\n\treturn ipamapi.DefaultIPAM\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/flynn/flynn/Godeps/_workspace/src/github.com/julienschmidt/httprouter\"\n\t\"github.com/flynn/flynn/Godeps/_workspace/src/gopkg.in/inconshreveable/log15.v2\"\n\t\"github.com/flynn/flynn/appliance/postgresql/client\"\n\t\"github.com/flynn/flynn/appliance/postgresql/state\"\n\t\"github.com/flynn/flynn/discoverd/client\"\n\t\"github.com/flynn/flynn/pkg/httphelper\"\n)\n\nfunc ServeHTTP(pg *Postgres, peer *state.Peer, hb discoverd.Heartbeater, log log15.Logger) error {\n\tapi := &HTTP{\n\t\tpg: pg,\n\t\tpeer: peer,\n\t\thb: hb,\n\t\tlog: log,\n\t}\n\tr := httprouter.New()\n\tr.GET(\"/status\", api.GetStatus)\n\tr.POST(\"/stop\", api.Stop)\n\treturn http.ListenAndServe(\":5433\", r)\n}\n\ntype HTTP struct {\n\tpg *Postgres\n\tpeer *state.Peer\n\thb discoverd.Heartbeater\n\tlog log15.Logger\n}\n\nfunc (h *HTTP) GetStatus(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tres := &pgmanager.Status{\n\t\tPeer: h.peer.Info(),\n\t}\n\tvar err error\n\tres.Postgres, err = h.pg.Info()\n\tif err != nil {\n\t\th.log.Error(\"error getting postgres info\", \"err\", err)\n\t}\n\thttphelper.JSON(w, 200, res)\n}\n\n\n\nfunc (h *HTTP) Stop(w http.ResponseWriter, req *http.Request, _ httprouter.Params) ", "output": "{\n\tif err := h.hb.Close(); err != nil {\n\t\thttphelper.Error(w, err)\n\t\treturn\n\t}\n\tif err := h.peer.Stop(); err != nil {\n\t\thttphelper.Error(w, err)\n\t\treturn\n\t}\n\tw.WriteHeader(200)\n}"} {"input": "package frontend\n\nimport (\n\t\"context\"\n\n\t\"go.chromium.org/luci/common/errors\"\n\t\"go.chromium.org/luci/common/logging\"\n\t\"go.chromium.org/luci/milo/common\"\n)\n\n\n\n\n\nfunc UpdateConfigHandler(c context.Context) error ", "output": "{\n\tprojErr := common.UpdateProjects(c)\n\tif projErr != nil {\n\t\tif merr, ok := projErr.(errors.MultiError); ok {\n\t\t\tfor _, ierr := range merr {\n\t\t\t\tlogging.WithError(ierr).Errorf(c, \"project update handler encountered error\")\n\t\t\t}\n\t\t} else {\n\t\t\tlogging.WithError(projErr).Errorf(c, \"project update handler encountered error\")\n\t\t}\n\t}\n\t_, servErr := common.UpdateServiceConfig(c)\n\tif servErr != nil {\n\t\tlogging.WithError(servErr).Errorf(c, \"service update handler encountered error\")\n\t}\n\n\treturn errors.Flatten(errors.NewMultiError(projErr, servErr))\n}"} {"input": "package codegen\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestCamelCase(t *testing.T) ", "output": "{\n\tcases := map[string]string{\n\t\t\"\": \"\",\n\t\t\"foo\": \"Foo\",\n\t\t\"foobar\": \"Foobar\",\n\t\t\"fooBar\": \"FooBar\",\n\t\t\"foo_bar\": \"FooBar\",\n\t\t\"foo_Bar\": \"Foo_Bar\", \n\t\t\"foo9bar\": \"Foo9Bar\",\n\t\t\"_foo\": \"XFoo\",\n\t\t\"_Foo\": \"XFoo\",\n\t}\n\n\tfor k, v := range cases {\n\t\tt.Run(k, func(t *testing.T) {\n\t\t\tg := NewGomegaWithT(t)\n\n\t\t\ta := CamelCase(k)\n\t\t\tg.Expect(a).To(Equal(v))\n\t\t})\n\t}\n\n}"} {"input": "package kafkametricsreceiver\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configtest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n)\n\n\n\nfunc TestCreateMetricsReceiver_errors(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.Brokers = []string{\"invalid:9092\"}\n\tcfg.ProtocolVersion = \"2.0.0\"\n\tcfg.Scrapers = []string{\"topics\"}\n\tr, err := createMetricsReceiver(context.Background(), componenttest.NewNopReceiverCreateSettings(), cfg, nil)\n\tassert.Error(t, err)\n\tassert.Nil(t, r)\n}\n\nfunc TestCreateMetricsReceiver(t *testing.T) {\n\tprev := newMetricsReceiver\n\tnewMetricsReceiver = func(ctx context.Context, config Config, params component.ReceiverCreateSettings, consumer consumer.Metrics) (component.MetricsReceiver, error) {\n\t\treturn nil, nil\n\t}\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.Brokers = []string{\"invalid:9092\"}\n\tcfg.ProtocolVersion = \"2.0.0\"\n\tcfg.Scrapers = []string{\"topics\"}\n\t_, err := createMetricsReceiver(context.Background(), componenttest.NewNopReceiverCreateSettings(), cfg, nil)\n\tnewMetricsReceiver = prev\n\tassert.Nil(t, err)\n}\n\nfunc TestCreateDefaultConfig(t *testing.T) ", "output": "{\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tassert.NotNil(t, cfg, \"default config not created\")\n\tassert.NoError(t, configtest.CheckConfigStruct(cfg))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\ntype Person struct {\n\tName string\n\tAge int\n}\n\ntype ByName []Person\n\nfunc (this ByName) Len() int {\n\treturn len(this)\n}\n\n\n\nfunc (this ByName) Swap(i, j int) {\n\tthis[i], this[j] = this[j], this[i]\n}\n\nfunc main() {\n\tkids := []Person{\n\t\t{\"Jill\", 9},\n\t\t{\"Jack\", 10},\n\t}\n\tsort.Sort(ByName(kids))\n\tfmt.Println(kids)\n}\n\nfunc (this ByName) Less(i, j int) bool ", "output": "{\n\treturn this[i].Name < this[j].Name\n}"} {"input": "package keymanager\n\nimport (\n\t\"launchpad.net/juju-core/state/api\"\n\t\"launchpad.net/juju-core/state/api/params\"\n\t\"launchpad.net/juju-core/utils/ssh\"\n)\n\n\ntype Client struct {\n\tst *api.State\n}\n\n\nfunc NewClient(st *api.State) *Client {\n\treturn &Client{st}\n}\n\n\nfunc (c *Client) Close() error {\n\treturn c.st.Close()\n}\n\n\nfunc (c *Client) ListKeys(mode ssh.ListMode, users ...string) ([]params.StringsResult, error) {\n\tp := params.ListSSHKeys{Mode: mode}\n\tp.Entities.Entities = make([]params.Entity, len(users))\n\tfor i, userName := range users {\n\t\tp.Entities.Entities[i] = params.Entity{Tag: userName}\n\t}\n\tresults := new(params.StringsResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"ListKeys\", p, results)\n\treturn results.Results, err\n}\n\n\nfunc (c *Client) AddKeys(user string, keys ...string) ([]params.ErrorResult, error) {\n\tp := params.ModifyUserSSHKeys{User: user, Keys: keys}\n\tresults := new(params.ErrorResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"AddKeys\", p, results)\n\treturn results.Results, err\n}\n\n\n\n\n\nfunc (c *Client) ImportKeys(user string, keyIds ...string) ([]params.ErrorResult, error) {\n\tp := params.ModifyUserSSHKeys{User: user, Keys: keyIds}\n\tresults := new(params.ErrorResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"ImportKeys\", p, results)\n\treturn results.Results, err\n}\n\nfunc (c *Client) DeleteKeys(user string, keys ...string) ([]params.ErrorResult, error) ", "output": "{\n\tp := params.ModifyUserSSHKeys{User: user, Keys: keys}\n\tresults := new(params.ErrorResults)\n\terr := c.st.Call(\"KeyManager\", \"\", \"DeleteKeys\", p, results)\n\treturn results.Results, err\n}"} {"input": "package dynaml\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cloudfoundry-incubator/spiff/yaml\"\n)\n\ntype BooleanExpr struct {\n\tValue bool\n}\n\nfunc (e BooleanExpr) Evaluate(Binding) (yaml.Node, bool) {\n\treturn node(e.Value), true\n}\n\n\n\nfunc (e BooleanExpr) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%v\", e.Value)\n}"} {"input": "package downloader\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/WhaleCoinOrg/WhaleCoin/core/types\"\n)\n\n\ntype peerDropFn func(id string)\n\n\ntype dataPack interface {\n\tPeerId() string\n\tItems() int\n\tStats() string\n}\n\n\ntype headerPack struct {\n\tpeerId string\n\theaders []*types.Header\n}\n\nfunc (p *headerPack) PeerId() string { return p.peerId }\nfunc (p *headerPack) Items() int { return len(p.headers) }\nfunc (p *headerPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.headers)) }\n\n\ntype bodyPack struct {\n\tpeerId string\n\ttransactions [][]*types.Transaction\n\tuncles [][]*types.Header\n}\n\nfunc (p *bodyPack) PeerId() string { return p.peerId }\n\nfunc (p *bodyPack) Stats() string { return fmt.Sprintf(\"%d:%d\", len(p.transactions), len(p.uncles)) }\n\n\ntype receiptPack struct {\n\tpeerId string\n\treceipts [][]*types.Receipt\n}\n\nfunc (p *receiptPack) PeerId() string { return p.peerId }\nfunc (p *receiptPack) Items() int { return len(p.receipts) }\nfunc (p *receiptPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.receipts)) }\n\n\ntype statePack struct {\n\tpeerId string\n\tstates [][]byte\n}\n\nfunc (p *statePack) PeerId() string { return p.peerId }\nfunc (p *statePack) Items() int { return len(p.states) }\nfunc (p *statePack) Stats() string { return fmt.Sprintf(\"%d\", len(p.states)) }\n\nfunc (p *bodyPack) Items() int ", "output": "{\n\tif len(p.transactions) <= len(p.uncles) {\n\t\treturn len(p.transactions)\n\t}\n\treturn len(p.uncles)\n}"} {"input": "package dbgc\n\nimport (\n\t\"code.cloudfoundry.org/lager\"\n)\n\n\n\ntype ReaperDB interface {\n\tReapExpiredContainers() error\n\tReapExpiredVolumes() error\n\tReapExpiredWorkers() error\n}\n\ntype DBGarbageCollector interface {\n\tRun() error\n}\n\ntype dbGarbageCollector struct {\n\tlogger lager.Logger\n\tdb ReaperDB\n}\n\n\n\nfunc (c *dbGarbageCollector) Run() error {\n\terr := c.db.ReapExpiredContainers()\n\tif err != nil {\n\t\tc.logger.Error(\"failed-to-reap-expired-containers\", err)\n\t\treturn err\n\t}\n\n\terr = c.db.ReapExpiredVolumes()\n\tif err != nil {\n\t\tc.logger.Error(\"failed-to-reap-expired-volumes\", err)\n\t\treturn err\n\t}\n\n\terr = c.db.ReapExpiredWorkers()\n\tif err != nil {\n\t\tc.logger.Error(\"failed-to-reap-expired-workers\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc NewDBGarbageCollector(\n\tlogger lager.Logger,\n\tdb ReaperDB,\n) DBGarbageCollector ", "output": "{\n\treturn &dbGarbageCollector{\n\t\tlogger: logger,\n\t\tdb: db,\n\t}\n}"} {"input": "package mock\n\nimport (\n\t\"github.com/eventials/goevents/messaging\"\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype Connection struct {\n\tmock.Mock\n}\n\nfunc NewMockConnection() messaging.Connection {\n\treturn &Connection{}\n}\n\nfunc (c *Connection) Consumer(autoAck bool, exchange, queue string) (messaging.Consumer, error) {\n\targs := c.Called(autoAck, exchange, queue)\n\treturn args.Get(0).(messaging.Consumer), args.Error(1)\n}\n\n\n\nfunc (c *Connection) Close() {\n\tc.Called()\n}\n\nfunc (c *Connection) NotifyConnectionClose() <-chan error {\n\targs := c.Called()\n\treturn args.Get(0).(chan error)\n}\n\nfunc (c *Connection) NotifyReestablish() <-chan bool {\n\targs := c.Called()\n\treturn args.Get(0).(chan bool)\n}\n\nfunc (c *Connection) WaitUntilConnectionCloses() {\n\tc.Called()\n}\n\nfunc (c *Connection) WaitUntilConnectionReestablished() {\n\tc.Called()\n}\n\nfunc (c *Connection) IsConnected() bool {\n\targs := c.Called()\n\treturn args.Get(0).(bool)\n}\n\nfunc (c *Connection) Producer(exchange string) (messaging.Producer, error) ", "output": "{\n\targs := c.Called(exchange)\n\treturn args.Get(0).(messaging.Producer), args.Error(1)\n}"} {"input": "package kafkametricsreceiver\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configtest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n)\n\nfunc TestCreateDefaultConfig(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tassert.NotNil(t, cfg, \"default config not created\")\n\tassert.NoError(t, configtest.CheckConfigStruct(cfg))\n}\n\n\n\nfunc TestCreateMetricsReceiver(t *testing.T) {\n\tprev := newMetricsReceiver\n\tnewMetricsReceiver = func(ctx context.Context, config Config, params component.ReceiverCreateSettings, consumer consumer.Metrics) (component.MetricsReceiver, error) {\n\t\treturn nil, nil\n\t}\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.Brokers = []string{\"invalid:9092\"}\n\tcfg.ProtocolVersion = \"2.0.0\"\n\tcfg.Scrapers = []string{\"topics\"}\n\t_, err := createMetricsReceiver(context.Background(), componenttest.NewNopReceiverCreateSettings(), cfg, nil)\n\tnewMetricsReceiver = prev\n\tassert.Nil(t, err)\n}\n\nfunc TestCreateMetricsReceiver_errors(t *testing.T) ", "output": "{\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.Brokers = []string{\"invalid:9092\"}\n\tcfg.ProtocolVersion = \"2.0.0\"\n\tcfg.Scrapers = []string{\"topics\"}\n\tr, err := createMetricsReceiver(context.Background(), componenttest.NewNopReceiverCreateSettings(), cfg, nil)\n\tassert.Error(t, err)\n\tassert.Nil(t, r)\n}"} {"input": "package main\n\n\n\nimport \"C\"\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"unsafe\"\n)\n\nconst LC_NUMERIC = int(C.LC_NUMERIC)\n\n\nfunc setLocale(lc int, locale string) {\n\tl := C.CString(locale)\n\tdefer C.free(unsafe.Pointer(l))\n\tC.setlocale(C.int(lc), l)\n}\n\n\n\n\n\nfunc homeDir() string {\n\tif runtime.GOOS == \"windows\" {\n\t\thome := os.Getenv(\"HOMEDRIVE\") + os.Getenv(\"HOMEPATH\")\n\t\tif home == \"\" {\n\t\t\thome = os.Getenv(\"USERPROFILE\")\n\t\t}\n\t\treturn home\n\t}\n\treturn os.Getenv(\"HOME\")\n}\n\n\nfunc cacheDir() string {\n\tdir := os.Getenv(\"XDG_CACHE_HOME\")\n\tif dir == \"\" {\n\t\tdir = filepath.Join(homeDir(), \".cache\", \"bukanir\")\n\t} else {\n\t\tdir = filepath.Join(dir, \"bukanir\")\n\t}\n\treturn dir\n}\n\nfunc inSlice(a string, b []string) bool ", "output": "{\n\tfor _, i := range b {\n\t\tif a == i {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package gen\n\nimport (\n\t\"go2o/src/core/infrastructure/gen/rsc/qr\"\n)\n\n\n\n\nfunc BuildQrCodeForUrl(url string) []byte ", "output": "{\n\tif code, err := qr.Encode(url, qr.M); err == nil {\n\t\treturn code.PNG()\n\t}\n\treturn []byte{}\n}"} {"input": "package seccomp\n\nimport (\n\tseccomp_compiler \"github.com/snapcore/snapd/sandbox/seccomp\"\n)\n\n\n\n\n\nfunc MockTemplate(fakeTemplate []byte) (restore func()) {\n\torig := defaultTemplate\n\torigBarePrivDropSyscalls := barePrivDropSyscalls\n\tdefaultTemplate = fakeTemplate\n\tbarePrivDropSyscalls = \"\"\n\treturn func() {\n\t\tdefaultTemplate = orig\n\t\tbarePrivDropSyscalls = origBarePrivDropSyscalls\n\t}\n}\n\nfunc MockKernelFeatures(f func() []string) (resture func()) {\n\told := kernelFeatures\n\tkernelFeatures = f\n\treturn func() {\n\t\tkernelFeatures = old\n\t}\n}\n\nfunc MockRequiresSocketcall(f func(string) bool) (restore func()) {\n\told := requiresSocketcall\n\trequiresSocketcall = f\n\treturn func() {\n\t\trequiresSocketcall = old\n\t}\n}\n\nfunc MockDpkgKernelArchitecture(f func() string) (restore func()) {\n\told := dpkgKernelArchitecture\n\tdpkgKernelArchitecture = f\n\treturn func() {\n\t\tdpkgKernelArchitecture = old\n\t}\n}\n\nfunc MockReleaseInfoId(s string) (restore func()) {\n\told := releaseInfoId\n\treleaseInfoId = s\n\treturn func() {\n\t\treleaseInfoId = old\n\t}\n}\n\n\n\nfunc MockSeccompCompilerLookup(f func(string) (string, error)) (restore func()) {\n\told := seccompCompilerLookup\n\tseccompCompilerLookup = f\n\treturn func() {\n\t\tseccompCompilerLookup = old\n\t}\n}\n\nfunc (b *Backend) VersionInfo() seccomp_compiler.VersionInfo {\n\treturn b.versionInfo\n}\n\nvar (\n\tRequiresSocketcall = requiresSocketcall\n\n\tGlobalProfileLE = globalProfileLE\n\tGlobalProfileBE = globalProfileBE\n\tIsBigEndian = isBigEndian\n)\n\nfunc MockReleaseInfoVersionId(s string) (restore func()) ", "output": "{\n\told := releaseInfoVersionId\n\treleaseInfoVersionId = s\n\treturn func() {\n\t\treleaseInfoVersionId = old\n\t}\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/api/scheduling/v1beta1\"\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\t\"k8s.io/client-go/kubernetes/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype SchedulingV1beta1Interface interface {\n\tRESTClient() rest.Interface\n\tPriorityClassesGetter\n}\n\n\ntype SchedulingV1beta1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *SchedulingV1beta1Client) PriorityClasses() PriorityClassInterface {\n\treturn newPriorityClasses(c)\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *SchedulingV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *SchedulingV1beta1Client {\n\treturn &SchedulingV1beta1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *SchedulingV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfig(c *rest.Config) (*SchedulingV1beta1Client, error) ", "output": "{\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SchedulingV1beta1Client{client}, nil\n}"} {"input": "package syswrap\n\nimport (\n\t\"os\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\nvar fileCount uint64\n\n\n\nvar maxFileCount uint64 = 500000\nvar fileMu sync.RWMutex\n\nfunc SetMaxFileCount(max uint64) {\n\tfileMu.Lock()\n\tmaxFileCount = max\n\tfileMu.Unlock()\n}\n\n\n\n\n\n\nfunc OpenFile(name string, flag int, perm os.FileMode) (file *os.File, mustClose bool, err error) {\n\tfile, err = os.OpenFile(name, flag, perm)\n\tfileMu.RLock()\n\tdefer fileMu.RUnlock()\n\tif newCount := atomic.AddUint64(&fileCount, 1); newCount > maxFileCount {\n\t\tmustClose = true\n\t}\n\treturn file, mustClose, err\n}\n\n\n\n\nfunc CloseFile(f *os.File) error ", "output": "{\n\tatomic.AddUint64(&fileCount, ^uint64(0)) \n\treturn f.Close()\n}"} {"input": "package metrics\n\nimport (\n\t\"expvar\"\n\t\"runtime\"\n\t\"sync\"\n)\n\nvar (\n\tm *expvar.Map\n\tonce sync.Once\n)\n\n\nfunc init() {\n\tonce.Do(func() {\n\t\tm = expvar.NewMap(\"errors\")\n\t\tm.Add(\"APIErrors\", 0)\n\t\tm.Add(\"RESTErrors\", 0)\n\t})\n\texpvar.Publish(\"goroutines\", expvar.Func(goroutines))\n}\n\n\nfunc APIError() {\n\tm.Add(\"APIErrors\", 1)\n}\n\n\n\n\nfunc goroutines() interface{} {\n\treturn runtime.NumGoroutine()\n}\n\nfunc RESTError() ", "output": "{\n\tm.Add(\"RESTErrors\", 1)\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n)\n\n\n\nfunc getResolverPath() string ", "output": "{\n\treturn os.Getenv(\"RESOLVER_PATH\")\n}"} {"input": "package example\n\nimport (\n\t\"testing\"\n\t\"github.com/remogatto/prettytest\"\n\t\"launchpad.net/gocheck\"\n)\n\n\n\ntype testSuite struct {\n\tprettytest.Suite\n}\n\nfunc TestRunner(t *testing.T) {\n\tprettytest.Run(\n\t\tt,\n\t\tnew(testSuite),\n\t)\n}\n\n\n\n\n\n\nfunc (t *testSuite) TestTrueIsTrue() {\n\tt.True(true)\n}\n\nfunc (t *testSuite) TestEquality() {\n\tt.Equal(\"awesome\", \"awesome\")\n}\n\nfunc (t *testSuite) TestNot() {\n\tt.Not(t.Path(\"foo\"))\n}\n\nfunc (t *testSuite) TestGoCheck() {\n\tt.Check(\"foo\", gocheck.Equals, \"foo\")\n}\n\n\n\n\n\nfunc (t *testSuite) TestInequality() {\n\tt.Equal(\"awesome\", \"ugly\")\n\tt.MustFail()\n}\n\nfunc (t *testSuite) TestMustFail() ", "output": "{\n\tt.Error(\"This test must fail.\")\n\tt.MustFail()\n}"} {"input": "package bsw\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestMX(t *testing.T) ", "output": "{\n\t_, results, err := MX(\"stacktitan.com\", \"8.8.8.8\")\n\tif err != nil {\n\t\tt.Error(\"error returned from MX\")\n\t\tt.Log(err)\n\t}\n\tfound := false\n\tfor _, r := range results {\n\t\tif r.Hostname == \"mx1.emailsrvr.com\" {\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tt.Error(\"MX did not find correct mx server\")\n\t\tt.Log(results)\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"github.com/oikomi/FishChatServer2/http_server/msg-api/conf\"\n\tsd \"github.com/oikomi/FishChatServer2/service_discovery/etcd\"\n\t\"google.golang.org/grpc\"\n)\n\ntype ManagerRPCCli struct {\n\tconn *grpc.ClientConn\n}\n\n\n\nfunc NewManagerRPCCli() (managerRPCCli *ManagerRPCCli, err error) ", "output": "{\n\tr := sd.NewResolver(conf.Conf.RPCClient.ManagerClient.ServiceName)\n\tb := grpc.RoundRobin(r)\n\tconn, err := grpc.Dial(conf.Conf.RPCClient.ManagerClient.EtcdAddr, grpc.WithInsecure(), grpc.WithBalancer(b))\n\tif err != nil {\n\t\tglog.Error(err)\n\t\tpanic(err)\n\t}\n\tmanagerRPCCli = &ManagerRPCCli{\n\t\tconn: conn,\n\t}\n\treturn\n}"} {"input": "package weave\n\nimport (\n\t\"strings\"\n)\n\n\n\ntype Advice struct {\n\tbefore string\n\tafter string\n\taround string\n\n\tadviceTypeId int\n}\n\n\n\n\n\nfunc adviceKind(l string) int {\n\tstuff := strings.Split(l, \": \")\n\tostuff := strings.Split(stuff[1], \" \")\n\n\tswitch ostuff[0] {\n\tcase \"before\":\n\t\treturn 1\n\tcase \"after\":\n\t\treturn 2\n\tcase \"around\":\n\t\treturn 3\n\t}\n\n\treturn -1\n}\n\nfunc adviceType() map[int]string ", "output": "{\n\treturn map[int]string{\n\t\t1: \"before\",\n\t\t2: \"after\",\n\t\t3: \"around\",\n\t}\n}"} {"input": "package mocks\n\nimport mock \"github.com/stretchr/testify/mock\"\nimport txvalidator \"github.com/hyperledger/fabric/core/committer/txvalidator\"\nimport validation \"github.com/hyperledger/fabric/core/handlers/validation/api\"\n\n\ntype PluginMapper struct {\n\tmock.Mock\n}\n\n\n\n\nfunc (_m *PluginMapper) PluginFactoryByName(name txvalidator.PluginName) validation.PluginFactory ", "output": "{\n\tret := _m.Called(name)\n\n\tvar r0 validation.PluginFactory\n\tif rf, ok := ret.Get(0).(func(txvalidator.PluginName) validation.PluginFactory); ok {\n\t\tr0 = rf(name)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(validation.PluginFactory)\n\t\t}\n\t}\n\n\treturn r0\n}"} {"input": "package vault\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\ntype AuthType interface {\n\tDescribe() string\n\tGetType() string\n\tgetAuthConfig() map[string]interface{}\n\tgetAuthMountConfig() map[string]interface{}\n\tConfigure(c *VCClient) error\n\tTuneMount(c *VCClient, path string) error\n\tWriteUsers(c *VCClient) error\n\tWriteGroups(c *VCClient) error\n}\n\n\nfunc (c *VCClient) AuthExist(name string) bool {\n\tauth, err := c.Sys().ListAuth()\n\tif err != nil {\n\t\treturn false\n\t}\n\tfor a := range auth {\n\t\tif strings.TrimSuffix(a, \"/\") == name {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\nfunc Path(a AuthType) string {\n\treturn fmt.Sprintf(\"auth/%s\", a.GetType())\n}\n\n\nfunc (c *VCClient) AuthEnable(a AuthType) error {\n\tif err := c.Sys().EnableAuth(a.GetType(), a.GetType(), a.Describe()); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc (c *VCClient) AuthConfigure(a AuthType) error {\n\tif err := a.WriteUsers(c); err != nil {\n\t\treturn err\n\t}\n\tif err := a.WriteGroups(c); err != nil {\n\t\treturn err\n\t}\n\tif err := a.TuneMount(c, Path(a)); err != nil {\n\t\treturn err\n\t}\n\n\tif err := a.Configure(c); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc EnableAndConfigure(a AuthType, c *VCClient) error ", "output": "{\n\tif !c.AuthExist(a.GetType()) {\n\t\tif err := c.AuthEnable(a); err != nil {\n\t\t\treturn fmt.Errorf(\"Error enabling auth mount: %v\", err)\n\t\t}\n\t}\n\tif err := c.AuthConfigure(a); err != nil {\n\t\treturn fmt.Errorf(\"Error configuring auth mount: %v\", err)\n\t}\n\n\treturn nil\n}"} {"input": "package invoke\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\n\n\nfunc FindInPath(plugin string, paths []string) (string, error) ", "output": "{\n\tif plugin == \"\" {\n\t\treturn \"\", fmt.Errorf(\"no plugin name provided\")\n\t}\n\n\tif len(paths) == 0 {\n\t\treturn \"\", fmt.Errorf(\"no paths provided\")\n\t}\n\n\tvar fullpath string\n\tfor _, path := range paths {\n\t\tfull := filepath.Join(path, plugin)\n\t\tif fi, err := os.Stat(full); err == nil && fi.Mode().IsRegular() {\n\t\t\tfullpath = full\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif fullpath == \"\" {\n\t\treturn \"\", fmt.Errorf(\"failed to find plugin %q in path %s\", plugin, paths)\n\t}\n\n\treturn fullpath, nil\n}"} {"input": "package mdr\n\n\nfunc AbsF64(a float64) float64 {\n\tif a < 0.0 {\n\t\treturn -a\n\t}\n\treturn a\n}\n\n\nfunc InRangeF64(a, b, c float64) bool {\n\tif a > c { \n\t\ta, c = c, a\n\t}\n\tif b < a {\n\t\treturn false\n\t}\n\tif b > c {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc ForceRangeF64(a, b, c float64) float64 {\n\tif a > c { \n\t\ta, c = c, a\n\t}\n\tif b < a {\n\t\treturn a\n\t}\n\tif b > c {\n\t\treturn c\n\t}\n\treturn b\n}\n\nfunc RangeLoHiF64Slice(v []float64) (lo, hi float64) ", "output": "{\n\tvlen := len(v)\n\tif vlen <= 0 {\n\t\treturn\n\t}\n\tlo, hi = v[0], v[0]\n\tfor i := 1; i < vlen; i++ {\n\t\tif v[i] < lo {\n\t\t\tlo = v[i]\n\t\t}\n\t\tif v[i] > hi {\n\t\t\thi = v[i]\n\t\t}\n\t}\n\treturn lo, hi\n}"} {"input": "package braille\n\n\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestDot(t *testing.T) {\n\tfmt.Println(\"0x28C1 =\", Dot(0x28c1))\n\tfmt.Println(\"0x282D =\", Dot(0x282D))\n\tfmt.Println(\"0x28BF =\", Dot(0x28BF))\n\tfmt.Println(\"0x28FF =\", Dot(0x28FF))\n\n}\n\nfunc TestCode(t *testing.T) {\n\tfmt.Printf(\"1-5-6-7 -> %c\\n\", Rune(1, 5, 6, 7))\n\tfmt.Printf(\"1-2-3-4-5-6-7-8 -> %c\\n\", Rune(1, 2, 3, 4, 5, 6, 7, 8))\n}\n\nfunc TestNumber(t *testing.T) {\n\tfor _, c := range \"1234567890\" {\n\t\tfmt.Printf(\"%c : %c\\n\", c, Alphabet(c))\n\t}\n}\n\n\n\nfunc TestAlphabet(t *testing.T) ", "output": "{\n\ts := \"HackTime for Google Hackfair 2012-09-01\"\n\tfmt.Println(s)\n\tfmt.Println(Encode(s))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc CopyDir(src string, dst string, overwrite bool) (err error) {\n\tsrc = filepath.Clean(src)\n\tdst = filepath.Clean(dst)\n\n\tsrcFileInfo, err := os.Stat(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !srcFileInfo.IsDir() {\n\t\treturn fmt.Errorf(\"CopyDir: source is not a directory\")\n\t}\n\n\t_, err = os.Stat(dst)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn\n\t}\n\tif err == nil && !overwrite {\n\t\treturn fmt.Errorf(\"CopyDir: destination already exists\")\n\t}\n\tif err == nil && overwrite {\n\t\tif *debug {\n\t\t\tlog.Println(\"CopyDir: destination already exists, overwriting it\")\n\t\t}\n\t}\n\n\terr = os.MkdirAll(dst, srcFileInfo.Mode())\n\tif err != nil {\n\t\treturn\n\t}\n\n\tentries, err := ioutil.ReadDir(src)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, entry := range entries {\n\t\tsrcPath := filepath.Join(src, entry.Name())\n\t\tdstPath := filepath.Join(dst, entry.Name())\n\n\t\tif entry.IsDir() {\n\t\t\terr = CopyDir(srcPath, dstPath, overwrite)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tif entry.Mode()&os.ModeSymlink != 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\terr = CopyFile(srcPath, dstPath)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc CopyFile(src, dst string) (err error) ", "output": "{\n\tin, err := os.Open(src)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer in.Close()\n\n\tout, err := os.Create(dst)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif e := out.Close(); e != nil {\n\t\t\terr = e\n\t\t}\n\t}()\n\n\t_, err = io.Copy(out, in)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = out.Sync()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tsi, err := os.Stat(src)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = os.Chmod(dst, si.Mode())\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}"} {"input": "package dynamodbstreams\n\nimport (\n\t\"github.com/aws/aws-sdk-go/awstesting/integration/smoke\"\n\t\"github.com/aws/aws-sdk-go/service/dynamodbstreams\"\n\t\"github.com/gucumber/gucumber\"\n)\n\n\n\nfunc init() ", "output": "{\n\tgucumber.Before(\"@dynamodbstreams\", func() {\n\t\tgucumber.World[\"client\"] = dynamodbstreams.New(smoke.Session)\n\t})\n}"} {"input": "package gce\n\nimport (\n\t\"time\"\n\n\tcompute \"google.golang.org/api/compute/v1\"\n)\n\nfunc newStaticIPMetricContext(request string) *metricContext {\n\treturn &metricContext{\n\t\tstart: time.Now(),\n\t\tattributes: []string{\"staticip_\" + request, unusedMetricLabel, unusedMetricLabel},\n\t}\n}\n\n\n\n\n\n\n\n\nfunc (gce *GCECloud) DeleteGlobalStaticIP(name string) error {\n\tmc := newStaticIPMetricContext(\"delete\")\n\top, err := gce.service.GlobalAddresses.Delete(gce.projectID, name).Do()\n\tif err != nil {\n\t\treturn mc.Observe(err)\n\t}\n\treturn gce.waitForGlobalOp(op, mc)\n}\n\n\nfunc (gce *GCECloud) GetGlobalStaticIP(name string) (address *compute.Address, err error) {\n\treturn gce.service.GlobalAddresses.Get(gce.projectID, name).Do()\n}\n\nfunc (gce *GCECloud) ReserveGlobalStaticIP(name, ipAddress string) (address *compute.Address, err error) ", "output": "{\n\tmc := newStaticIPMetricContext(\"reserve\")\n\top, err := gce.service.GlobalAddresses.Insert(gce.projectID, &compute.Address{Name: name, Address: ipAddress}).Do()\n\n\tif err != nil {\n\t\treturn nil, mc.Observe(err)\n\t}\n\n\tif err := gce.waitForGlobalOp(op, mc); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gce.service.GlobalAddresses.Get(gce.projectID, name).Do()\n}"} {"input": "package daemon\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/docker/docker/container\"\n\tvolumestore \"github.com/docker/docker/volume/store\"\n)\n\n\n\nfunc (daemon *Daemon) removeMountPoints(container *container.Container, rm bool) error {\n\tvar rmErrors []string\n\tfor _, m := range container.MountPoints {\n\t\tif m.Volume == nil {\n\t\t\tcontinue\n\t\t}\n\t\tdaemon.volumes.Dereference(m.Volume, container.ID)\n\t\tif rm {\n\t\t\tif m.Named {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr := daemon.volumes.Remove(m.Volume)\n\t\t\tif err != nil && !volumestore.IsInUse(err) {\n\t\t\t\trmErrors = append(rmErrors, err.Error())\n\t\t\t}\n\t\t}\n\t}\n\tif len(rmErrors) > 0 {\n\t\treturn fmt.Errorf(\"Error removing volumes:\\n%v\", strings.Join(rmErrors, \"\\n\"))\n\t}\n\treturn nil\n}\n\nfunc (daemon *Daemon) prepareMountPoints(container *container.Container) error ", "output": "{\n\tfor _, config := range container.MountPoints {\n\t\tif err := daemon.lazyInitializeVolume(container.ID, config); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package v1\n\nimport context \"context\"\n\nimport proto \"github.com/golang/protobuf/proto\"\nimport \"go-common/library/net/rpc/liverpc\"\n\nvar _ proto.Message \n\n\n\n\n\n\ntype AdminSilent interface {\n\tGetShieldRule(context.Context, *AdminSilentGetShieldRuleReq) (*AdminSilentGetShieldRuleResp, error)\n}\n\n\n\n\n\ntype adminSilentRpcClient struct {\n\tclient *liverpc.Client\n}\n\n\n\nfunc NewAdminSilentRpcClient(client *liverpc.Client) AdminSilent {\n\treturn &adminSilentRpcClient{\n\t\tclient: client,\n\t}\n}\n\nfunc (c *adminSilentRpcClient) GetShieldRule(ctx context.Context, in *AdminSilentGetShieldRuleReq) (*AdminSilentGetShieldRuleResp, error) {\n\tout := new(AdminSilentGetShieldRuleResp)\n\terr := doRpcRequest(ctx, c.client, 1, \"AdminSilent.get_shield_rule\", in, out)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}\n\n\n\n\n\n\n\nfunc doRpcRequest(ctx context.Context, client *liverpc.Client, version int, method string, in, out proto.Message) (err error) ", "output": "{\n\terr = client.Call(ctx, version, method, in, out)\n\treturn\n}"} {"input": "package instructions\n\n\n\nfunc isSecretMountsSupported() bool ", "output": "{\n\treturn true\n}"} {"input": "package clienttest\n\nimport (\n\t\"fmt\"\n\t\"spotclient\"\n\t\"testing\"\n\t\"time\"\n\n\t. \"github.com/franela/goblin\"\n)\n\n\n\nfunc TestClient(t *testing.T) ", "output": "{\n\tg := Goblin(t)\n\n\tg.Describe(\"SpotClient\", func() {\n\t\tcfg := spotclient.NewConfigForEnvironment(\"test\")\n\t\tnow := time.Now()\n\n\t\tg.It(\"should create a client struct\", func() {\n\n\t\t\tclient := spotclient.NewSpotClient(cfg)\n\t\t\tg.Assert(client != nil).IsTrue()\n\t\t\tg.Assert(client.CreateTime.After(now)).IsTrue()\n\n\t\t\tfmt.Sprintf(\"%v\", client)\n\t\t})\n\n\t})\n}"} {"input": "package http\n\nimport (\n\t\"net/http\"\n\t\"reflect\"\n)\n\n\ntype JSONErrorBuilder interface {\n\tBuild() JSONError\n\n\tCustomError(code int, errorType, msg string) JSONErrorBuilder\n\n\tFromError(e error) JSONErrorBuilder\n\n\tMessage(string) JSONErrorBuilder\n\n\tStatus(int) JSONErrorBuilder\n\n\tURL(string) JSONErrorBuilder\n}\n\ntype jsonErrorBuilder struct {\n\tinstance JSONError\n}\n\n\n\n\n\nfunc (b *jsonErrorBuilder) Build() JSONError {\n\treturn b.instance\n}\n\nfunc (b *jsonErrorBuilder) CustomError(\n\tcode int,\n\terrorType,\n\tmsg string,\n) JSONErrorBuilder {\n\tb.instance.Code = code\n\tb.instance.Type = errorType\n\tb.instance.Message = msg\n\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) FromError(e error) JSONErrorBuilder {\n\terrType := reflect.TypeOf(e)\n\tvar typeName string\n\tif errType.Kind() == reflect.Ptr {\n\t\ttypeName = errType.Elem().Name()\n\t} else {\n\t\ttypeName = errType.Name()\n\t}\n\n\tb.instance.Type = typeName\n\tb.instance.Message = e.Error()\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) Message(msg string) JSONErrorBuilder {\n\tb.instance.Message = msg\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) Status(status int) JSONErrorBuilder {\n\tb.instance.Status = status\n\treturn b\n}\n\nfunc (b *jsonErrorBuilder) URL(url string) JSONErrorBuilder {\n\tb.instance.MoreInfo = url\n\treturn b\n}\n\nvar _ JSONErrorBuilder = (*jsonErrorBuilder)(nil)\n\nfunc NewJSONError() JSONErrorBuilder ", "output": "{\n\treturn &jsonErrorBuilder{JSONError{\n\t\tStatus: http.StatusInternalServerError,\n\t}}\n}"} {"input": "package remotecontext \n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n)\n\n\n\n\nfunc createTestTempDir(t *testing.T, dir, prefix string) (string, func()) {\n\tpath, err := os.MkdirTemp(dir, prefix)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error when creating directory %s with prefix %s: %s\", dir, prefix, err)\n\t}\n\n\treturn path, func() {\n\t\terr = os.RemoveAll(path)\n\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error when removing directory %s: %s\", path, err)\n\t\t}\n\t}\n}\n\n\n\n\n\n\nfunc createTestTempSubdir(t *testing.T, dir, prefix string) string {\n\tpath, err := os.MkdirTemp(dir, prefix)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error when creating directory %s with prefix %s: %s\", dir, prefix, err)\n\t}\n\n\treturn path\n}\n\n\n\n\n\nfunc createTestTempFile(t *testing.T, dir, filename, contents string, perm os.FileMode) string ", "output": "{\n\tfilePath := filepath.Join(dir, filename)\n\terr := os.WriteFile(filePath, []byte(contents), perm)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error when creating %s file: %s\", filename, err)\n\t}\n\n\treturn filePath\n}"} {"input": "package homedir \n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n)\n\n\n\nfunc TestGetShortcutString(t *testing.T) {\n\tshortcut := GetShortcutString()\n\tif shortcut == \"\" {\n\t\tt.Fatal(\"returned shortcut string is empty\")\n\t}\n}\n\nfunc TestGet(t *testing.T) ", "output": "{\n\thome := Get()\n\tif home == \"\" {\n\t\tt.Fatal(\"returned home directory is empty\")\n\t}\n\n\tif !filepath.IsAbs(home) {\n\t\tt.Fatalf(\"returned path is not absolute: %s\", home)\n\t}\n}"} {"input": "package glacier\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/rdwilliamson/aws\"\n)\n\n\ntype Connection struct {\n\tClient *http.Client\n\n\tSignature *aws.Signature\n}\n\n\n\n\nfunc (c *Connection) vault(vault string) string {\n\treturn \"https://\" + c.Signature.Region.Glacier + \"/-/vaults/\" + vault\n}\n\n\nfunc (c *Connection) policy(policy string) string {\n\treturn \"https://\" + c.Signature.Region.Glacier + \"/-/policies/\" + policy\n}\n\n\n\nfunc NewConnection(secret, access string, r *aws.Region) *Connection {\n\treturn &Connection{\n\t\tSignature: aws.NewSignature(secret, access, r, \"glacier\"),\n\t}\n}\n\n\n\n\nfunc toHex(x []byte) string {\n\treturn fmt.Sprintf(\"%x\", x)\n}\n\n\n\ntype parameters url.Values\n\n\n\nfunc (p parameters) add(key, value string) {\n\turl.Values(p).Add(key, value)\n}\n\n\n\nfunc (p parameters) encode() string {\n\tif encoded := url.Values(p).Encode(); encoded != \"\" {\n\t\treturn \"?\" + encoded\n\t}\n\treturn \"\"\n}\n\nfunc (c *Connection) client() *http.Client ", "output": "{\n\tif c.Client == nil {\n\t\treturn http.DefaultClient\n\t}\n\treturn c.Client\n}"} {"input": "package text\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\nvar text = \"The quick brown fox jumps over the lazy dog.\"\n\nfunc TestWrap(t *testing.T) {\n\texp := [][]string{\n\t\t{\"The\", \"quick\", \"brown\", \"fox\"},\n\t\t{\"jumps\", \"over\", \"the\", \"lazy\", \"dog.\"},\n\t}\n\twords := bytes.Split([]byte(text), sp)\n\tgot := WrapWords(words, 1, 24, defaultPenalty)\n\tif len(exp) != len(got) {\n\t\tt.Fail()\n\t}\n\tfor i := range exp {\n\t\tif len(exp[i]) != len(got[i]) {\n\t\t\tt.Fail()\n\t\t}\n\t\tfor j := range exp[i] {\n\t\t\tif exp[i][j] != string(got[i][j]) {\n\t\t\t\tt.Fatal(i, exp[i][j], got[i][j])\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestWrapNarrow(t *testing.T) {\n\texp := \"The\\nquick\\nbrown\\nfox\\njumps\\nover\\nthe\\nlazy\\ndog.\"\n\tif Wrap(text, 5) != exp {\n\t\tt.Fail()\n\t}\n}\n\n\n\nfunc TestWrapBug1(t *testing.T) {\n\tcases := []struct {\n\t\tlimit int\n\t\ttext string\n\t\twant string\n\t}{\n\t\t{4, \"aaaaa\", \"aaaaa\"},\n\t\t{4, \"a aaaaa\", \"a\\naaaaa\"},\n\t}\n\n\tfor _, test := range cases {\n\t\tgot := Wrap(test.text, test.limit)\n\t\tif got != test.want {\n\t\t\tt.Errorf(\"Wrap(%q, %d) = %q want %q\", test.text, test.limit, got, test.want)\n\t\t}\n\t}\n}\n\nfunc TestWrapOneLine(t *testing.T) ", "output": "{\n\texp := \"The quick brown fox jumps over the lazy dog.\"\n\tif Wrap(text, 500) != exp {\n\t\tt.Fail()\n\t}\n}"} {"input": "package tempconv\n\nimport \"testing\"\n\nfunc TestCToF(t *testing.T) {\n\tvar c Celsius = 37\n\tf := CToF(c)\n\tif f != Fahrenheit(98.6) {\n\t\tt.Errorf(`CToF(%g) == %g failed`, c, f)\n\t}\n}\n\nfunc TestFToC(t *testing.T) {\n\tvar f Fahrenheit = 95\n\tc := FToC(f)\n\tif c != Celsius(35) {\n\t\tt.Errorf(`FToC(%g) == %g failed`, f, c)\n\t}\n}\n\nfunc TestCToK(t *testing.T) {\n\tvar c Celsius = 37\n\tk := CToK(c)\n\tif k != Kelvin(310.15) {\n\t\tt.Errorf(`CToK(%g) == %g failed`, c, k)\n\t}\n}\n\n\n\nfunc TestKToC(t *testing.T) ", "output": "{\n\tvar k Kelvin = 1000\n\tc := KToC(k)\n\tif c != Celsius(726.85) {\n\t\tt.Errorf(`KToC(%g) == %g failed`, k, c)\n\t}\n}"} {"input": "package monit\n\nimport (\n\t\"errors\"\n\t\"github.com/ooyala/go-dogstatsd\"\n\t\"github.com/tolexo/aero/conf\"\n\t\"sync\"\n)\n\nvar agentObj *DataDogAgent\nvar once sync.Once\n\ntype DataDogAgent struct {\n\tClient *dogstatsd.Client\n}\n\nfunc (d *DataDogAgent) ClientExists() (exists bool) {\n\tif d.Client != nil {\n\t\texists = true\n\t}\n\treturn\n}\n\nfunc (d *DataDogAgent) Close() {\n\td.Client.Close()\n}\n\nfunc (d *DataDogAgent) Count(name string, value int64, tags []string, rate float64) (err error) {\n\texists := d.ClientExists()\n\tif exists {\n\t\terr = d.Client.Count(name, value, tags, rate)\n\t}\n\treturn\n}\n\nfunc (d *DataDogAgent) Histogram(name string, value float64, tags []string, rate float64) (err error) {\n\texists := d.ClientExists()\n\tif exists {\n\t\terr = d.Client.Histogram(name, value, tags, rate)\n\t}\n\treturn\n}\n\n\n\n\nfunc GetDataDogAgent() *DataDogAgent ", "output": "{\n\tonce.Do(func() {\n\t\tagentObj = new(DataDogAgent)\n\t\tvar errObj error\n\t\tenabled := conf.Bool(\"monitor.enabled\", false)\n\t\tif enabled && agentObj.ClientExists() == false {\n\t\t\thost := conf.String(\"monitor.host\", \"\")\n\t\t\tport := conf.String(\"monitor.port\", \"\")\n\t\t\tif host == \"\" || port == \"\" {\n\t\t\t\terrObj = errors.New(\"Datadog config host and port missing\")\n\t\t\t} else {\n\t\t\t\tclient, err := dogstatsd.New(host + \":\" + port)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrObj = err\n\t\t\t\t} else {\n\t\t\t\t\tnamespace := conf.String(\"monitor.namespace\", \"\")\n\t\t\t\t\tif namespace != \"\" {\n\t\t\t\t\t\tclient.Namespace = namespace\n\t\t\t\t\t}\n\t\t\t\t\tagentObj.Client = client\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif errObj != nil {\n\t\t}\n\t})\n\treturn agentObj\n}"} {"input": "package gotify\n\nimport (\n\t\"github.com/antonholmquist/jason\"\n)\n\nfunc parseAlbum(o *jason.Object) Album {\n\talbumName, _ := o.GetString(\"name\")\n\talbumUri, _ := o.GetString(\"uri\")\n\n\talbum := Album{albumName, albumUri}\n\n\treturn album\n}\n\nfunc parseArtist(o *jason.Object) Artist {\n\tartistName, _ := o.GetString(\"name\")\n\tartistUri, _ := o.GetString(\"uri\")\n\n\tartist := Artist{artistName, artistUri}\n\n\treturn artist\n}\n\nfunc parseTrack(o *jason.Object) Track {\n\ttrackName, _ := o.GetString(\"name\")\n\ttrackUri, _ := o.GetString(\"uri\")\n\n\tjsonAlbum, err := o.GetObject(\"album\")\n\n\tvar album Album\n\tif err == nil {\n\t\talbum = parseAlbum(jsonAlbum)\n\t}\n\n\tjsonArtists, err := o.GetObjectArray(\"artists\")\n\n\tvar artists []Artist\n\tif err == nil {\n\t\tartists = parseArtists(jsonArtists)\n\t}\n\n\ttrack := Track{trackName, trackUri, album, artists}\n\n\treturn track\n}\n\n\n\nfunc parseAlbums(o []*jason.Object) []Album {\n\talbums := []Album{}\n\n\tfor _, jsonAlbum := range o {\n\t\talbums = append(albums, parseAlbum(jsonAlbum))\n\t}\n\n\treturn albums\n}\n\nfunc parseArtists(o []*jason.Object) []Artist {\n\tartists := []Artist{}\n\n\tfor _, jsonArtist := range o {\n\t\tartists = append(artists, parseArtist(jsonArtist))\n\t}\n\n\treturn artists\n}\n\nfunc parsePlaylist(o *jason.Object) SpotifyPlaylist {\n\treturn SpotifyPlaylist{}\n}\n\nfunc parseTracks(o []*jason.Object) []Track ", "output": "{\n\ttracks := []Track{}\n\n\tfor _, jsonTrack := range o {\n\t\ttracks = append(tracks, parseTrack(jsonTrack))\n\t}\n\n\treturn tracks\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/user\"\n)\n\nfunc main() {\n\tstartServer()\n}\n\nfunc isRoot() bool {\n\tusr, _ := user.Current()\n\treturn usr.Uid == \"0\"\n}\n\nfunc certsExists(certFile string, keyFile string) bool {\n\tfor _, file := range []string{certFile, keyFile} {\n\t\t_, err := os.Stat(file)\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc findPort(ssl bool) string {\n\tport := os.Getenv(\"PORT\")\n\tif len(port) == 0 {\n\t\tuser := !isRoot()\n\t\tif ssl {\n\t\t\tif user {\n\t\t\t\tport = \"4443\"\n\t\t\t} else {\n\t\t\t\tport = \"443\"\n\t\t\t}\n\t\t} else {\n\t\t\tif user {\n\t\t\t\tport = \"8080\"\n\t\t\t} else {\n\t\t\t\tport = \"80\"\n\t\t\t}\n\t\t}\n\t}\n\n\treturn port\n}\n\n\n\nfunc startServer() ", "output": "{\n\tcertFile := \"certs/server.pem\"\n\tkeyFile := \"certs/server.key\"\n\tssl := certsExists(certFile, keyFile)\n\tport := findPort(ssl)\n\trouter := NewRouter()\n\n\tlog.Printf(\"start listening on port %s\", port)\n\n\tvar err error\n\tif ssl {\n\t\terr = http.ListenAndServeTLS(\":\"+port, certFile, keyFile, router)\n\t} else {\n\t\terr = http.ListenAndServe(\":\"+port, router)\n\t}\n\n\tlog.Fatal(err)\n}"} {"input": "package restic\n\nimport \"syscall\"\n\n\n\nfunc (s statUnix) atim() syscall.Timespec { return s.Atim }\nfunc (s statUnix) mtim() syscall.Timespec { return s.Mtim }\nfunc (s statUnix) ctim() syscall.Timespec { return s.Ctim }\n\nfunc (node Node) restoreSymlinkTimestamps(path string, utimes [2]syscall.Timespec) error ", "output": "{\n\treturn nil\n}"} {"input": "package elements\n\nimport \"github.com/fileformats/graphics/jt/model\"\n\n\n\n\ntype LODNode struct {\n\tGroupNode\n\tVersion uint8\n\tReservedRangeField model.VectorF32\n\tReservedField int32\n}\n\n\n\nfunc (n *LODNode) Read(c *model.Context) error {\n\tc.LogGroup(\"LODNode\")\n\tdefer c.LogGroupEnd()\n\n\tif err := (&n.GroupNode).Read(c); err != nil {\n\t\treturn err\n\t}\n\n\tif c.Version.Equal(model.V10) {\n\t\tn.Version = c.Data.UInt8()\n\t}\n\tif c.Version.Equal(model.V9) {\n\t\tn.Version = uint8(c.Data.UInt16())\n\t}\n\n\tif !c.Version.Equal(model.V10) {\n\t\t(&n.ReservedRangeField).Read(c)\n\t\tn.ReservedField = c.Data.Int32()\n\t}\n\n\treturn c.Data.GetError()\n}\n\nfunc (n *LODNode) BaseElement() *JTElement {\n\treturn &n.JTElement\n}\n\nfunc (n LODNode) GUID() model.GUID ", "output": "{\n\treturn model.LodNodeElement\n}"} {"input": "package room\n\nimport (\n \"log\"\n\n \"github.com/jinzhu/gorm\"\n _ \"github.com/jinzhu/gorm/dialects/sqlite\"\n)\n\nconst tableName string = \"rooms\"\n\ntype Room struct {\n gorm.Model\n Id int64 `sql:\"AUTO_INCREMENT\" gorm:\"primary_key\"`\n Name string `sql:\"size:255;unique;index\"`\n Size int32\n VC bool\n CalendarId string\n}\n\nvar (\n dbHandle *gorm.DB\n dbPath string\n)\n\nfunc check(err error) {\n if err != nil {\n log.Println(\"[Models]: \", err)\n }\n\n}\n\nfunc Create(dbHandle *gorm.DB, name string, size int32, vc bool, calendarId string) {\n dbHandle.Create(&Room{Name: name, Size: size, VC: vc, CalendarId: calendarId})\n}\n\n\n\nfunc SetDbPath(path string) {\n dbPath = path\n}\n\nfunc GetAll(dbHandle *gorm.DB) []*Room ", "output": "{\n var rooms []*Room\n rows, err := dbHandle.Table(tableName).Select(nil).Rows()\n check(err)\n rows.Scan(&rooms)\n return rooms\n}"} {"input": "package libcontainer\n\nimport (\n\t\"testing\"\n)\n\nfunc TestNamespacesContains(t *testing.T) {\n\tns := Namespaces{\n\t\tGetNamespace(\"NEWPID\"),\n\t\tGetNamespace(\"NEWNS\"),\n\t\tGetNamespace(\"NEWUTS\"),\n\t}\n\n\tif ns.Contains(\"NEWNET\") {\n\t\tt.Fatal(\"namespaces should not contain NEWNET\")\n\t}\n\n\tif !ns.Contains(\"NEWPID\") {\n\t\tt.Fatal(\"namespaces should contain NEWPID but does not\")\n\t}\n\n\twithNil := Namespaces{\n\t\tGetNamespace(\"UNDEFINED\"), \n\t\tGetNamespace(\"NEWPID\"),\n\t}\n\n\tif !withNil.Contains(\"NEWPID\") {\n\t\tt.Fatal(\"namespaces should contain NEWPID but does not\")\n\t}\n}\n\n\n\nfunc TestCapabilitiesContains(t *testing.T) ", "output": "{\n\tcaps := Capabilities{\n\t\tGetCapability(\"MKNOD\"),\n\t\tGetCapability(\"SETPCAP\"),\n\t}\n\n\tif caps.Contains(\"SYS_ADMIN\") {\n\t\tt.Fatal(\"capabilities should not contain SYS_ADMIN\")\n\t}\n\tif !caps.Contains(\"MKNOD\") {\n\t\tt.Fatal(\"capabilities should contain MKNOD but does not\")\n\t}\n}"} {"input": "package test\n\nimport (\n\t\"bytes\"\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc AssertBytesEqual(t *testing.T, a, b []byte) {\n\tif !bytes.Equal(a, b) {\n\t\tt.Errorf(\"%v != %v\", a, b)\n\t}\n}\n\nfunc AssertEqual(t *testing.T, a, b interface{}) ", "output": "{\n\tif !reflect.DeepEqual(a, b) {\n\t\tt.Errorf(\"%v != %v\", a, b)\n\t}\n}"} {"input": "package engine\n\nimport (\n\t\"time\"\n\n\t\"github.com/aws/amazon-ecs-agent/agent/api\"\n)\n\n\n\ntype impossibleTransitionError struct {\n\tstate api.ContainerStatus\n}\n\nfunc (err *impossibleTransitionError) Error() string {\n\treturn \"Cannot transition to \" + err.state.String()\n}\nfunc (err *impossibleTransitionError) ErrorName() string { return \"ImpossibleStateTransitionError\" }\n\ntype DockerTimeoutError struct {\n\tduration time.Duration\n\ttransition string\n}\n\nfunc (err *DockerTimeoutError) Error() string {\n\treturn \"Could not transition to \" + err.transition + \"; timed out after waiting \" + err.duration.String()\n}\nfunc (err *DockerTimeoutError) ErrorName() string { return \"DockerTimeoutError\" }\n\ntype ContainerVanishedError struct{}\n\nfunc (err ContainerVanishedError) Error() string { return \"No container matching saved ID found\" }\nfunc (err ContainerVanishedError) ErrorName() string { return \"ContainerVanishedError\" }\n\ntype CannotXContainerError struct {\n\ttransition string\n\tmsg string\n}\n\n\nfunc (err CannotXContainerError) ErrorName() string {\n\treturn \"Cannot\" + err.transition + \"ContainerError\"\n}\n\ntype OutOfMemoryError struct{}\n\nfunc (err OutOfMemoryError) Error() string { return \"Container killed due to memory usage\" }\nfunc (err OutOfMemoryError) ErrorName() string { return \"OutOfMemoryError\" }\n\n\ntype DockerStateError struct {\n\tdockerError string\n\tname string\n}\n\nfunc NewDockerStateError(err string) DockerStateError {\n\treturn DockerStateError{\n\t\tdockerError: err,\n\t\tname: \"DockerStateError\",\n\t}\n}\n\nfunc (err DockerStateError) Error() string {\n\treturn err.dockerError\n}\nfunc (err DockerStateError) ErrorName() string {\n\treturn err.name\n}\n\nfunc (err CannotXContainerError) Error() string ", "output": "{ return err.msg }"} {"input": "package errors\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n)\n\n\ntype HTTPError struct {\n\tStatusCode int\n\terror\n}\n\n\nfunc (e *HTTPError) Error() string {\n\treturn e.error.Error()\n}\n\n\n\n\nfunc NewMethodNotAllowed(method string) *HTTPError {\n\treturn &HTTPError{http.StatusMethodNotAllowed, errors.New(`Method is not allowed:\"` + method + `\"`)}\n}\n\n\nfunc NewBadRequest(err error) *HTTPError {\n\treturn &HTTPError{http.StatusBadRequest, err}\n}\n\n\n\nfunc NewBadRequestString(s string) *HTTPError {\n\treturn NewBadRequest(errors.New(s))\n}\n\n\n\nfunc NewBadRequestMissingParameter(s string) *HTTPError {\n\treturn NewBadRequestString(`Missing parameter \"` + s + `\"`)\n}\n\n\n\n\n\nfunc NewBadRequestUnwantedParameter(s string) *HTTPError ", "output": "{\n\treturn NewBadRequestString(`Unwanted parameter \"` + s + `\"`)\n}"} {"input": "package clif\n\nimport (\n\t\"os\"\n\t\"runtime\"\n\t\"syscall\"\n\t\"unsafe\"\n)\n\n\n\nfunc init() ", "output": "{\n\tTermWidthCall = func() (int, error) {\n\t\tw := new(termWindow)\n\t\ttio := syscall.TIOCGWINSZ\n\t\tif runtime.GOOS == \"darwin\" {\n\t\t\ttio = TERM_TIOCGWINSZ_OSX\n\t\t}\n\t\tres, _, err := syscall.Syscall(sys_ioctl,\n\t\t\tuintptr(syscall.Stdin),\n\t\t\tuintptr(tio),\n\t\t\tuintptr(unsafe.Pointer(w)),\n\t\t)\n\t\tif err != 0 || int(res) == -1 {\n\t\t\treturn TERM_DEFAULT_WIDTH, os.NewSyscallError(\"GetWinsize\", err)\n\t\t}\n\t\treturn int(w.Col) - 4, nil\n\t}\n\n\tTermWidthCurrent, _ = TermWidthCall()\n}"} {"input": "package xml\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/xml\"\n\t\"github.com/graniticio/granitic/v2/ws\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestMarshallAndWrite(t *testing.T) {\n\n\tmw := new(MarshalingWriter)\n\trw := new(resWriter)\n\n\tmw.MarshalAndWrite(target{A: 1}, rw)\n\n\tif rw.sw.String() != \"1\" {\n\t\tt.Fail()\n\t}\n\n}\n\nfunc TestUnmarshalling(t *testing.T) {\n\n\tr := new(http.Request)\n\tsr := strings.NewReader(\"1\")\n\n\trc := ioutil.NopCloser(sr)\n\n\tr.Body = rc\n\n\tum := new(Unmarshaller)\n\n\twsr := new(ws.Request)\n\twsr.RequestBody = new(target)\n\n\tum.Unmarshall(context.Background(), r, wsr)\n\n\ttar := wsr.RequestBody.(*target)\n\n\tif tar.A != 1 {\n\t\tt.Fail()\n\t}\n\n}\n\ntype target struct {\n\tXMLName xml.Name `xml:\"content\"`\n\tA int64 `xml:\"a\"`\n}\n\ntype resWriter struct {\n\tsw bytes.Buffer\n}\n\n\n\nfunc (rw *resWriter) Write(b []byte) (int, error) {\n\treturn rw.sw.Write(b)\n}\n\nfunc (rw *resWriter) WriteHeader(statusCode int) {\n\n}\n\nfunc (rw *resWriter) Header() http.Header ", "output": "{\n\treturn nil\n}"} {"input": "package compress_test\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\n\t\"github.com/mkch/burrow/compress\"\n)\n\n\n\nfunc ExampleNewResponseWriter() {\n\thandler := func(w http.ResponseWriter, r *http.Request) {\n\t\tcw, _ := compress.NewResponseWriter(w, compress.DefaultGzipWriterFactory)\n\t\tio.WriteString(cw, \"content to write\")\n\t}\n\thttp.ListenAndServe(\":8080\", http.HandlerFunc(handler))\n}\n\nfunc ExampleNewHandler() ", "output": "{\n\thttp.ListenAndServe(\":8080\", compress.NewHandler(http.DefaultServeMux, nil))\n}"} {"input": "package goro\n\nimport \"regexp\"\nimport \"net/http\"\n\n\ntype Goro struct {\n\tRequest *http.Request\n\tResponseWriter *http.ResponseWriter\n\tResponse *Response\n\tRoutes []Route\n\tConfig ConfigRegistry\n\tSession *Session\n}\n\n\nfunc (self *Goro) SetRoutes(routes []Route) {\n\tself.Routes = routes\n}\n\n\nfunc (self *Goro) SetParams(items []ConfigItem) {\n\tregistry := ConfigRegistry{Items: items}\n\tself.Config = registry\n}\n\n\n\n\n\nfunc (self *Goro) DumpSession() {\n\tself.Session.Dump()\n}\n\n\nfunc (self *Goro) Run() {\n\tself.run()\n}\n\n\nfunc (self *Goro) run() {\n\tvar handler func(*Goro)\n\tfindedRoute := false\n\troutes := self.Routes\n\tqueryString := self.Request.URL.Path\n\n\tself.Response = &Response{}\n\n\tfor _, route := range routes {\n\t\tif matched, _ := regexp.MatchString(route.Url, queryString); matched == true {\n\t\t\thandler = route.Handler\n\t\t\tfindedRoute = true\n\t\t}\n\t}\n\n\tif !findedRoute {\n\t\thandler = func(f *Goro) {\n\t\t}\n\t}\n\n\thandler(self)\n\tself.Response.Flush(*self.ResponseWriter)\n}\n\n\nfunc (self *Goro) Write(s string) {\n\tself.Response.Write(s)\n}\n\n\nfunc (self *Goro) WriteLine(s string) {\n\tself.Response.WriteLine(s)\n}\n\n\nfunc (self *Goro) Redirect(url string) {\n\thttp.Redirect(*self.ResponseWriter, self.Request, url, http.StatusOK)\n}\n\nfunc (self *Goro) LoadSession() ", "output": "{\n\tvar uuid string\n\tsessionName := self.Config.Get(\"SESSION_NAME\").(string)\n\tsessionCookie, err := self.Request.Cookie(sessionName)\n\n\tif err != nil {\n\t\tuuid = GenerateUUID()\n\t} else {\n\t\tuuid = sessionCookie.Value\n\t}\n\n\tsession := &Session{Id: uuid, Framework: self}\n\n\tself.Session = session\n\tself.Session.Load()\n}"} {"input": "package storagebackend\n\nimport (\n\t\"time\"\n\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apiserver/pkg/storage/value\"\n)\n\nconst (\n\tStorageTypeUnset = \"\"\n\tStorageTypeETCD2 = \"etcd2\"\n\tStorageTypeETCD3 = \"etcd3\"\n\n\tDefaultCompactInterval = 5 * time.Minute\n)\n\n\ntype Config struct {\n\tType string\n\tPrefix string\n\tServerList []string\n\tKeyFile string\n\tCertFile string\n\tCAFile string\n\tQuorum bool\n\tPaging bool\n\tDeserializationCacheSize int\n\n\tCodec runtime.Codec\n\tTransformer value.Transformer\n\n\tCompactionInterval time.Duration\n}\n\n\n\nfunc NewDefaultConfig(prefix string, codec runtime.Codec) *Config ", "output": "{\n\treturn &Config{\n\t\tPrefix: prefix,\n\t\tDeserializationCacheSize: 0,\n\t\tCodec: codec,\n\t\tCompactionInterval: DefaultCompactInterval,\n\t\tQuorum: true,\n\t}\n}"} {"input": "package memory\n\nimport (\n\t\"fmt\"\n)\n\n\ntype RAM struct {\n\tdata []byte\n\twindow []byte\n\taddrOffset uint16\n}\n\n\nfunc NewRAM(data []byte, addrOffset uint16) *RAM {\n\n\tr := RAM{data: data, addrOffset: addrOffset}\n\tr.SetWindow(0)\n\n\treturn &r\n}\n\n\n\nfunc (r *RAM) SetWindow(offset uint32) error {\n\n\tif uint32(len(r.data)) <= offset {\n\t\treturn fmt.Errorf(\"window offset out of range (%d)\", offset)\n\t}\n\n\tr.window = r.data[offset:]\n\n\treturn nil\n}\n\n\nfunc (r *RAM) Read(addr uint16) (byte, error) {\n\n\tif r.addrOffset > addr {\n\t\treturn 0, ReadOutOfRangeError(addr)\n\t}\n\n\tphysicalAddr := addr - r.addrOffset\n\n\tif uint(len(r.window)) <= uint(physicalAddr) {\n\t\treturn 0, ReadOutOfRangeError(addr)\n\t}\n\n\treturn r.window[physicalAddr], nil\n}\n\n\n\n\nfunc (r *RAM) Write(addr uint16, data byte) error ", "output": "{\n\n\tif r.addrOffset > addr {\n\t\treturn WriteOutOfRangeError(addr)\n\t}\n\n\tphysicalAddr := addr - r.addrOffset\n\n\tif uint(len(r.window)) <= uint(physicalAddr) {\n\t\treturn WriteOutOfRangeError(addr)\n\t}\n\n\tr.window[physicalAddr] = data\n\n\treturn nil\n}"} {"input": "package dexcom\n\nimport (\n\t\"math\"\n)\n\n\n\nfunc marshalUint16(n uint16) []byte {\n\treturn []byte{byte(n & 0xFF), byte(n >> 8)}\n}\n\n\nfunc marshalInt16(n int16) []byte {\n\treturn marshalUint16(uint16(n))\n}\n\nfunc marshalUint32(n uint32) []byte {\n\treturn append(marshalUint16(uint16(n&0xFFFF)), marshalUint16(uint16(n>>16))...)\n}\n\nfunc marshalInt32(n int32) []byte {\n\treturn marshalUint32(uint32(n))\n}\n\n\n\n\nfunc unmarshalInt16(v []byte) int16 {\n\treturn int16(unmarshalUint16(v))\n}\n\nfunc unmarshalUint32(v []byte) uint32 {\n\treturn uint32(unmarshalUint16(v[0:2])) | uint32(unmarshalUint16(v[2:4]))<<16\n}\n\nfunc unmarshalInt32(v []byte) int32 {\n\treturn int32(unmarshalUint32(v))\n}\n\nfunc unmarshalUint64(v []byte) uint64 {\n\treturn uint64(unmarshalUint32(v[0:4])) | uint64(unmarshalUint32(v[4:8]))<<32\n}\n\nfunc unmarshalFloat64(v []byte) float64 {\n\treturn math.Float64frombits(unmarshalUint64(v))\n}\n\nfunc unmarshalUint16(v []byte) uint16 ", "output": "{\n\treturn uint16(v[0]) | uint16(v[1])<<8\n}"} {"input": "package openweathermap\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\n\nvar StationDataParameters = []string{\n\t\"wind_dir\", \n\t\"wind_speed\", \n\t\"wind_gust\", \n\t\"temp\", \n\t\"humidity\", \n\t\"pressure\", \n\t\"rain_1h\", \n\t\"rain_24h\", \n\t\"rain_today\", \n\t\"snow\", \n\t\"lum\", \n\t\"lat\", \n\t\"long\", \n\t\"alt\", \n\t\"radiation\", \n\t\"dewpoint\", \n\t\"uv\", \n\t\"name\", \n}\n\n\n\nfunc ValidateStationDataParameter(param string) bool {\n\tfor _, p := range StationDataParameters {\n\t\tif param == p {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\n\n\n\n\n\n\nfunc SendStationData(data url.Values) {\n\tresp, err := http.PostForm(dataPostURL, data)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tfmt.Println(resp.Body)\n}\n\nfunc ConvertToURLValues(data map[string]string) string ", "output": "{\n\tv := url.Values{}\n\n\tfor key, val := range data {\n\t\tv.Set(key, val)\n\t}\n\n\treturn v.Encode()\n}"} {"input": "package main\n\n\n\n\n\ntype Scope struct {\n\tparent *Scope \n\tentities map[string]*Decl\n}\n\nfunc NewScope(outer *Scope) *Scope {\n\ts := new(Scope)\n\ts.parent = outer\n\ts.entities = make(map[string]*Decl)\n\treturn s\n}\n\n\nfunc AdvanceScope(s *Scope) (*Scope, *Scope) {\n\tif len(s.entities) == 0 {\n\t\treturn s, s.parent\n\t}\n\treturn NewScope(s), s\n}\n\n\nfunc (s *Scope) addNamedDecl(d *Decl) *Decl {\n\treturn s.addDecl(d.Name, d)\n}\n\n\n\nfunc (s *Scope) replaceDecl(name string, d *Decl) {\n\ts.entities[name] = d\n}\n\nfunc (s *Scope) mergeDecl(d *Decl) {\n\tdecl, ok := s.entities[d.Name]\n\tif !ok {\n\t\ts.entities[d.Name] = d\n\t} else {\n\t\tdecl := decl.DeepCopy()\n\t\tdecl.ExpandOrReplace(d)\n\t\ts.entities[d.Name] = decl\n\t}\n}\n\nfunc (s *Scope) lookup(name string) *Decl {\n\tdecl, ok := s.entities[name]\n\tif !ok {\n\t\tif s.parent != nil {\n\t\t\treturn s.parent.lookup(name)\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn decl\n}\n\nfunc (s *Scope) addDecl(name string, d *Decl) *Decl ", "output": "{\n\tdecl, ok := s.entities[name]\n\tif !ok {\n\t\ts.entities[name] = d\n\t\treturn d\n\t}\n\treturn decl\n}"} {"input": "package main\n\nimport (\n\t\"github.com/aarondl/dbm/config\"\n)\n\nfunc createDatabase(args []string) {\n\tengine, err := NewEngine(config.Current)\n\tif err != nil {\n\t\texitLn(\"Error getting handle to db:\", err)\n\t}\n\tif err = engine.CreateDB(); err != nil {\n\t\texitLn(\"Error creating db:\", err)\n\t}\n\ttrackdbHelper(args, engine)\n}\n\n\n\nfunc trackdbHelper(args []string, engine SqlEngine) {\n\tif err := engine.Open(); err != nil {\n\t\texitLn(\"Error opening to db:\", err)\n\t}\n\tdefer engine.Close()\n\tif err := engine.CreateMigrationsTable(); err != nil {\n\t\texitLn(\"Error creating migrations table:\", err)\n\t}\n}\n\nfunc dropDatabase(args []string) {\n\tengine, err := NewEngine(config.Current)\n\tif err != nil {\n\t\texitLn(\"Error getting handle to db:\", err)\n\t}\n\tif err = engine.DropDB(); err != nil {\n\t\texitLn(\"Error dropping db:\", err)\n\t}\n}\n\nfunc trackdb(args []string) ", "output": "{\n\tengine, err := NewEngine(config.Current)\n\tif err != nil {\n\t\texitLn(\"Error getting handle to db:\", err)\n\t}\n\ttrackdbHelper(args, engine)\n}"} {"input": "package queue\n\nimport (\n\t\"fmt\"\n\t\"github.com/apache/servicecomb-service-center/pkg/log\"\n\t\"golang.org/x/net/context\"\n)\n\ntype UniQueue struct {\n\tqueue chan interface{}\n}\n\n\n\nfunc (uq *UniQueue) Chan() <-chan interface{} {\n\treturn uq.queue\n}\n\nfunc (uq *UniQueue) Put(value interface{}) (e error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.LogPanic(r)\n\n\t\t\te = fmt.Errorf(\"%v\", r)\n\t\t}\n\t}()\n\n\tselect {\n\tcase _, ok := <-uq.queue:\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"channel is closed\")\n\t\t}\n\tdefault:\n\t}\n\n\tselect {\n\tcase uq.queue <- value:\n\tdefault:\n\t}\n\treturn\n}\n\nfunc (uq *UniQueue) Close() {\n\tselect {\n\tcase _, ok := <-uq.queue:\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\tdefault:\n\t}\n\tclose(uq.queue)\n}\n\nfunc NewUniQueue() (uq *UniQueue) {\n\treturn &UniQueue{\n\t\tqueue: make(chan interface{}, 1),\n\t}\n}\n\nfunc (uq *UniQueue) Get(ctx context.Context) interface{} ", "output": "{\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil\n\tcase item := <-uq.queue:\n\t\treturn item\n\t}\n}"} {"input": "package concurrent\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\ntype BackgroundWorker interface {\n\tDo(f func() (interface{}, error)) error\n\tClose() ([]interface{}, error)\n}\n\n\nfunc NewBackgroundWorker() BackgroundWorker {\n\treturn newBackgroundWorker()\n}\n\ntype valueError struct {\n\tvalue interface{}\n\terr error\n}\n\ntype backgroundWorker struct {\n\twg *sync.WaitGroup\n\tvalueErrors chan *valueError\n\tdestroyable Destroyable\n}\n\nfunc newBackgroundWorker() *backgroundWorker {\n\treturn &backgroundWorker{&sync.WaitGroup{}, make(chan *valueError), NewDestroyable(nil)}\n}\n\n\n\nfunc (b *backgroundWorker) Close() ([]interface{}, error) {\n\tvar values []interface{}\n\tvar errs []error\n\tif err := b.destroyable.Destroy(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tvalueError, ok := <-b.valueErrors\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tvalues = append(values, valueError.value)\n\t\t\tif valueError.err != nil {\n\t\t\t\terrs = append(errs, valueError.err)\n\t\t\t}\n\t\t}\n\t}()\n\tb.wg.Wait()\n\tclose(b.valueErrors)\n\tif len(errs) == 0 {\n\t\treturn values, nil\n\t}\n\treturn values, fmt.Errorf(\"%v\", errs)\n}\n\nfunc (b *backgroundWorker) Do(f func() (interface{}, error)) error ", "output": "{\n\t_, err := b.destroyable.Do(func() (interface{}, error) {\n\t\tb.wg.Add(1)\n\t\tgo func() {\n\t\t\tvalue, err := f()\n\t\t\tb.valueErrors <- &valueError{value, err}\n\t\t\tb.wg.Done()\n\t\t}()\n\t\treturn nil, nil\n\t})\n\treturn err\n}"} {"input": "package types\n\nimport (\n\t\"github.com/coreos/ignition/v2/config/shared/errors\"\n\n\t\"github.com/coreos/vcontext/path\"\n\t\"github.com/coreos/vcontext/report\"\n)\n\nfunc (r Raid) Key() string {\n\treturn r.Name\n}\n\nfunc (r Raid) IgnoreDuplicates() map[string]struct{} {\n\treturn map[string]struct{}{\n\t\t\"Options\": {},\n\t}\n}\n\nfunc (ra Raid) Validate(c path.ContextPath) (r report.Report) {\n\tr.AddOnError(c.Append(\"level\"), ra.validateLevel())\n\tif len(ra.Devices) == 0 {\n\t\tr.AddOnError(c.Append(\"devices\"), errors.ErrRaidDevicesRequired)\n\t}\n\treturn\n}\n\n\n\nfunc (r Raid) validateLevel() error ", "output": "{\n\tswitch r.Level {\n\tcase \"linear\", \"raid0\", \"0\", \"stripe\":\n\t\tif r.Spares != nil && *r.Spares != 0 {\n\t\t\treturn errors.ErrSparesUnsupportedForLevel\n\t\t}\n\tcase \"raid1\", \"1\", \"mirror\":\n\tcase \"raid4\", \"4\":\n\tcase \"raid5\", \"5\":\n\tcase \"raid6\", \"6\":\n\tcase \"raid10\", \"10\":\n\tdefault:\n\t\treturn errors.ErrUnrecognizedRaidLevel\n\t}\n\n\treturn nil\n}"} {"input": "package variant\n\nimport (\n\t\"github.com/go-ole/com/errors\"\n\t\"github.com/go-ole/com/types\"\n)\n\nfunc VariantInit(v *types.Variant) error {\n\treturn errors.NotImplementedError\n}\n\nfunc VariantClear(v *types.Variant) error {\n\treturn errors.NotImplementedError\n}\n\nfunc VariantChangeType(source *types.Variant, flags uint16, vt types.VariantType) *types.Variant {\n\treturn source\n}\n\n\n\nfunc VariantCopy(source *types.Variant) *types.Variant {\n\treturn source\n}\n\nfunc VariantCopyIndirect(source *types.Variant) *types.Variant {\n\treturn source\n}\n\nfunc VariantChangeTypeEx(source *types.Variant, locale uint32, flags uint16, vt types.VariantType) *types.Variant ", "output": "{\n\treturn source\n}"} {"input": "package v1\n\nimport (\n\tcommon \"github.com/kubeflow/common/pkg/apis/common/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\n\n\nfunc Int32(v int32) *int32 {\n\treturn &v\n}\n\nfunc addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}\n\n\nfunc setDefaultsTypeLauncher(spec *common.ReplicaSpec) {\n\tif spec != nil && spec.RestartPolicy == \"\" {\n\t\tspec.RestartPolicy = DefaultRestartPolicy\n\t}\n}\n\n\nfunc setDefaultsTypeWorker(spec *common.ReplicaSpec) {\n\tif spec != nil && spec.RestartPolicy == \"\" {\n\t\tspec.RestartPolicy = DefaultRestartPolicy\n\t}\n}\n\n\n\nfunc SetDefaults_MPIJob(mpiJob *MPIJob) ", "output": "{\n\tif mpiJob.Spec.CleanPodPolicy == nil {\n\t\tnone := common.CleanPodPolicyNone\n\t\tmpiJob.Spec.CleanPodPolicy = &none\n\t}\n\n\tsetDefaultsTypeLauncher(mpiJob.Spec.MPIReplicaSpecs[MPIReplicaTypeLauncher])\n\n\tsetDefaultsTypeWorker(mpiJob.Spec.MPIReplicaSpecs[MPIReplicaTypeWorker])\n}"} {"input": "package oneview\n\nimport (\n\t\"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource\"\n\t\"testing\"\n)\n\n\n\nvar testAccSubnetData = `\n data \"oneview_id_pools_ipv4_subnets\" \"test\" {\n\t subnet_id = \"dgfhdfg-effdfd\"\n }`\n\nfunc TestAccIPv4Subnets_2(t *testing.T) ", "output": "{\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccSubnetData,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\tresource.TestCheckResourceAttr(\"oneview_id_pools_ipv4_subnets.test\", \"subnet_id\", \"dgfhdfg-effdfd\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}"} {"input": "package ini\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/caixw/lib.go/assert\"\n)\n\n\n\nfunc TestWriter(t *testing.T) ", "output": "{\n\ta := assert.New(t)\n\tbuf := bytes.NewBufferString(\"\")\n\n\tw := NewWriter(buf)\n\ta.NotNil(w)\n\n\tw.AddElement(\"key\", \"val\")\n\tw.AddComment(\"comment\")\n\tw.AddSection(\"section\")\n\tw.AddElement(\"key\", \"val\")\n\tw.AddElement(\"key1\", \"val1\")\n\tw.Flush()\n\tdata := buf.Bytes()\n\n\tstr := `key=val\n#comment\n[section]\nkey=val\nkey1=val1\n`\n\n\ta.Equal([]byte(str), data)\n}"} {"input": "package mytime\n\nimport (\n\t\"cloud.google.com/go/spanner\"\n\t\"github.com/tcncloud/protoc-gen-persist/examples/test\"\n)\n\ntype MyEnum struct {\n\tStatus int32\n}\n\nfunc (t MyEnum) ToSpanner(src test.TestEnum) *MyEnum{\n\tt.Status = int32(src)\n\n\treturn &t\n}\n\nfunc (t MyEnum) ToProto() test.TestEnum {\n\treturn test.TestEnum(t.Status)\n}\n\nfunc (t *MyEnum) SpannerScan(src *spanner.GenericColumnValue) error {\n\tvar lt int64\n\n\terr := src.Decode(<)\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.Status = int32(lt)\n\n\treturn nil\n}\n\n\n\nfunc (t *MyEnum) SpannerValue() (interface{}, error) ", "output": "{\n\treturn int64(t.Status), nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst version = 74\n\nvar cmdVersion = &Command{\n\tName: \"version\",\n\tShort: \"show version info\",\n\tLong: `\n\nDisplays the version of godep as well as the target OS, architecture and go runtime version.\n`,\n\tRun: runVersion,\n}\n\n\n\nfunc runVersion(cmd *Command, args []string) {\n\tfmt.Printf(\"%s\\n\", versionString())\n}\n\nfunc GoVersionFields(c rune) bool {\n\treturn c == 'g' || c == 'o' || c == '.'\n}\n\n\n\n\nfunc isSameOrNewer(base, check string) bool {\n\tif base == check {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(check, \"devel-\") {\n\t\treturn true\n\t}\n\tbp := strings.FieldsFunc(base, GoVersionFields)\n\tcp := strings.FieldsFunc(check, GoVersionFields)\n\tif len(bp) < 2 || len(cp) < 2 {\n\t\tlog.Fatalf(\"Error comparing %s to %s\\n\", base, check)\n\t}\n\tif bp[0] == cp[0] { \n\t\tbm, err := strconv.Atoi(bp[1])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tcm, err := strconv.Atoi(cp[1])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn cm >= bm\n\t}\n\treturn false\n}\n\nfunc versionString() string ", "output": "{\n\treturn fmt.Sprintf(\"godep v%d (%s/%s/%s)\", version, runtime.GOOS, runtime.GOARCH, runtime.Version())\n}"} {"input": "package utils\n\ntype Set map[string]bool\n\n\n\nfunc (self Set) Insert(key string) {\n\tself[key] = true\n}\n\nfunc (self Set) Remove(key string) {\n\tdelete(self, key)\n}\n\nfunc (self Set) Size() int {\n\treturn len(self)\n}\n\nfunc (self Set) Contains(key string) bool ", "output": "{\n\t_, found := self[key]\n\treturn found\n}"} {"input": "package g\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/toolkits/file\"\n)\n\n\n\nfunc RrdFileName(baseDir string, md5 string, dsType string, step int) string {\n\treturn baseDir + \"/\" + md5[0:2] + \"/\" +\n\t\tmd5 + \"_\" + dsType + \"_\" + strconv.Itoa(step) + \".rrd\"\n}\n\n\nfunc IsRrdFileExist(filename string) bool {\n\treturn file.IsExist(filename)\n}\n\n\n\nfunc SplitRrdCacheKey(ckey string) (md5 string, dsType string, step int, err error) {\n\tckey_slice := strings.Split(ckey, \"_\")\n\tif len(ckey_slice) != 3 {\n\t\terr = fmt.Errorf(\"bad rrd cache key: %s\", ckey)\n\t\treturn\n\t}\n\n\tmd5 = ckey_slice[0]\n\tdsType = ckey_slice[1]\n\tstepInt64, err := strconv.ParseInt(ckey_slice[2], 10, 32)\n\tif err != nil {\n\t\treturn\n\t}\n\tstep = int(stepInt64)\n\n\terr = nil\n\treturn\n}\n\n\nfunc IsValidString(str string) bool {\n\n\tr := []rune(str)\n\n\tfor _, t := range r {\n\t\tswitch t {\n\t\tcase '\\r':\n\t\t\treturn false\n\t\tcase '\\n':\n\t\t\treturn false\n\t\tcase '\\'':\n\t\t\treturn false\n\t\tcase '\"':\n\t\t\treturn false\n\t\tcase '>':\n\t\t\treturn false\n\t\tcase '\\032':\n\t\t\treturn false\n\t\tdefault:\n\t\t\tif !unicode.IsPrint(t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\nfunc FormRrdCacheKey(md5 string, dsType string, step int) string ", "output": "{\n\treturn md5 + \"_\" + dsType + \"_\" + strconv.Itoa(step)\n}"} {"input": "package ioctl\n\nimport \"golang.org/x/sys/unix\"\n\nconst (\n\ttypeBits = 8\n\tnumberBits = 8\n\tsizeBits = 14\n\tdirectionBits = 2\n\n\ttypeMask = (1 << typeBits) - 1\n\tnumberMask = (1 << numberBits) - 1\n\tsizeMask = (1 << sizeBits) - 1\n\tdirectionMask = (1 << directionBits) - 1\n\n\tdirectionNone = 0\n\tdirectionWrite = 1\n\tdirectionRead = 2\n\n\tnumberShift = 0\n\ttypeShift = numberShift + numberBits\n\tsizeShift = typeShift + typeBits\n\tdirectionShift = sizeShift + sizeBits\n)\n\nfunc ioc(dir, t, nr, size uintptr) uintptr {\n\treturn (dir << directionShift) | (t << typeShift) | (nr << numberShift) | (size << sizeShift)\n}\n\n\nfunc Io(t, nr uintptr) uintptr {\n\treturn ioc(directionNone, t, nr, 0)\n}\n\n\nfunc IoR(t, nr, size uintptr) uintptr {\n\treturn ioc(directionRead, t, nr, size)\n}\n\n\n\n\n\nfunc IoRW(t, nr, size uintptr) uintptr {\n\treturn ioc(directionRead|directionWrite, t, nr, size)\n}\n\n\nfunc Ioctl(fd, op, arg uintptr) error {\n\t_, _, ep := unix.Syscall(unix.SYS_IOCTL, fd, op, arg)\n\tif ep != 0 {\n\t\treturn ep\n\t}\n\treturn nil\n}\n\nfunc IoW(t, nr, size uintptr) uintptr ", "output": "{\n\treturn ioc(directionWrite, t, nr, size)\n}"} {"input": "package options\n\n\ntype UpdateOptions struct {\n\tArrayFilters *ArrayFilters\n\n\tBypassDocumentValidation *bool\n\n\tCollation *Collation\n\n\tHint interface{}\n\n\tUpsert *bool\n}\n\n\nfunc Update() *UpdateOptions {\n\treturn &UpdateOptions{}\n}\n\n\nfunc (uo *UpdateOptions) SetArrayFilters(af ArrayFilters) *UpdateOptions {\n\tuo.ArrayFilters = &af\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetBypassDocumentValidation(b bool) *UpdateOptions {\n\tuo.BypassDocumentValidation = &b\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetCollation(c *Collation) *UpdateOptions {\n\tuo.Collation = c\n\treturn uo\n}\n\n\n\n\n\nfunc (uo *UpdateOptions) SetUpsert(b bool) *UpdateOptions {\n\tuo.Upsert = &b\n\treturn uo\n}\n\n\nfunc MergeUpdateOptions(opts ...*UpdateOptions) *UpdateOptions {\n\tuOpts := Update()\n\tfor _, uo := range opts {\n\t\tif uo == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif uo.ArrayFilters != nil {\n\t\t\tuOpts.ArrayFilters = uo.ArrayFilters\n\t\t}\n\t\tif uo.BypassDocumentValidation != nil {\n\t\t\tuOpts.BypassDocumentValidation = uo.BypassDocumentValidation\n\t\t}\n\t\tif uo.Collation != nil {\n\t\t\tuOpts.Collation = uo.Collation\n\t\t}\n\t\tif uo.Hint != nil {\n\t\t\tuOpts.Hint = uo.Hint\n\t\t}\n\t\tif uo.Upsert != nil {\n\t\t\tuOpts.Upsert = uo.Upsert\n\t\t}\n\t}\n\n\treturn uOpts\n}\n\nfunc (uo *UpdateOptions) SetHint(h interface{}) *UpdateOptions ", "output": "{\n\tuo.Hint = h\n\treturn uo\n}"} {"input": "package wifi\n\nvar _ = WiFi(&StubWorker{})\n\ntype StubWorker struct {\n\tOptions []Option\n\tID string\n}\n\n\n\nfunc (w *StubWorker) GetID() (string, error) {\n\treturn w.ID, nil\n}\n\nfunc (*StubWorker) Connect(a ...string) error {\n\treturn nil\n}\n\nfunc NewStubWorker(id string, options ...Option) (WiFi, error) {\n\treturn &StubWorker{ID: id, Options: options}, nil\n}\n\nfunc (w *StubWorker) Scan() ([]Option, error) ", "output": "{\n\treturn w.Options, nil\n}"} {"input": "package provider\n\nimport (\n\t\"fmt\"\n\t\"github.com/CenturyLinkLabs/draycluster/deploy\"\n\t\"strings\"\n \"github.com/CenturyLinkLabs/draycluster/utils\")\n\ntype CloudProvider interface {\n\tProvisionAgent() (deploy.CloudServer, error)\n}\n\n\n\nfunc New(providerType string) CloudProvider ", "output": "{\n\tpt := strings.TrimSpace(strings.ToLower(providerType))\n utils.LogInfo(fmt.Sprintf(\"\\n\\nProvider:%s\",pt))\n\tswitch string(pt) {\n\tcase \"centurylink\":\n\t\treturn NewCenturylink()\n\tcase \"amazon\":\n\t\treturn NewAmazon()\n case \"digitalocean\":\n \t\treturn NewDigitalOcean()\n\t}\n\tfmt.Printf(\"\\nNIL Provider:%s\", pt)\n\treturn nil\n}"} {"input": "package loganalytics\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype LogAnalyticsAssociationParameterCollection struct {\n\n\tItems []LogAnalyticsAssociationParameter `mandatory:\"false\" json:\"items\"`\n}\n\n\n\nfunc (m LogAnalyticsAssociationParameterCollection) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package runtime_test\n\nimport (\n\t\"runtime\"\n\t\"sync\"\n\t\"testing\"\n)\n\ntype response struct {\n}\n\ntype myError struct {\n}\n\nfunc (myError) Error() string { return \"\" }\n\nfunc doRequest(useSelect bool) (*response, error) {\n\ttype async struct {\n\t\tresp *response\n\t\terr error\n\t}\n\tch := make(chan *async, 0)\n\tdone := make(chan struct{}, 0)\n\n\tif useSelect {\n\t\tgo func() {\n\t\t\tselect {\n\t\t\tcase ch <- &async{resp: nil, err: myError{}}:\n\t\t\tcase <-done:\n\t\t\t}\n\t\t}()\n\t} else {\n\t\tgo func() {\n\t\t\tch <- &async{resp: nil, err: myError{}}\n\t\t}()\n\t}\n\n\tr := <-ch\n\truntime.Gosched()\n\treturn r.resp, r.err\n}\n\nfunc TestChanSendSelectBarrier(t *testing.T) {\n\ttestChanSendBarrier(true)\n}\n\nfunc TestChanSendBarrier(t *testing.T) {\n\ttestChanSendBarrier(false)\n}\n\n\n\nfunc testChanSendBarrier(useSelect bool) ", "output": "{\n\tvar wg sync.WaitGroup\n\tvar globalMu sync.Mutex\n\touter := 100\n\tinner := 100000\n\tif testing.Short() {\n\t\touter = 10\n\t\tinner = 1000\n\t}\n\tfor i := 0; i < outer; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tvar garbage []byte\n\t\t\tfor j := 0; j < inner; j++ {\n\t\t\t\t_, err := doRequest(useSelect)\n\t\t\t\t_, ok := err.(myError)\n\t\t\t\tif !ok {\n\t\t\t\t\tpanic(1)\n\t\t\t\t}\n\t\t\t\tgarbage = make([]byte, 1<<10)\n\t\t\t}\n\t\t\tglobalMu.Lock()\n\t\t\tglobal = garbage\n\t\t\tglobalMu.Unlock()\n\t\t}()\n\t}\n\twg.Wait()\n}"} {"input": "package snap\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/snapcore/snapd/dirs\"\n)\n\nfunc GuessAppsForBroken(info *Info) map[string]*AppInfo {\n\tout := make(map[string]*AppInfo)\n\n\tname := info.SuggestedName\n\tfor _, p := range []string{name, fmt.Sprintf(\"%s.*\", name)} {\n\t\tmatches, _ := filepath.Glob(filepath.Join(dirs.SnapBinariesDir, p))\n\t\tfor _, m := range matches {\n\t\t\tl := strings.SplitN(filepath.Base(m), \".\", 2)\n\t\t\tvar appname string\n\t\t\tif len(l) == 1 {\n\t\t\t\tappname = l[0]\n\t\t\t} else {\n\t\t\t\tappname = l[1]\n\t\t\t}\n\t\t\tout[appname] = &AppInfo{\n\t\t\t\tSnap: info,\n\t\t\t\tName: appname,\n\t\t\t}\n\t\t}\n\t}\n\n\tmatches, _ := filepath.Glob(filepath.Join(dirs.SnapServicesDir, fmt.Sprintf(\"snap.%s.*.service\", name)))\n\tfor _, m := range matches {\n\t\tappname := strings.Split(m, \".\")[2]\n\t\tout[appname] = &AppInfo{\n\t\t\tSnap: info,\n\t\t\tName: appname,\n\t\t\tDaemon: \"simple\",\n\t\t}\n\t}\n\n\treturn out\n}\n\n\n\n\n\n\n\nfunc (info *Info) renameClashingCorePlugs() {\n\tif info.Name() == \"core\" && info.Type == TypeOS {\n\t\tfor _, plugName := range []string{\"network-bind\", \"core-support\"} {\n\t\t\tinfo.renamePlug(plugName, plugName+\"-plug\")\n\t\t}\n\t}\n}\n\n\n\n\nfunc (info *Info) renamePlug(oldName, newName string) ", "output": "{\n\tif plugInfo, ok := info.Plugs[oldName]; ok {\n\t\tdelete(info.Plugs, oldName)\n\t\tinfo.Plugs[newName] = plugInfo\n\t\tplugInfo.Name = newName\n\t\tfor _, appInfo := range info.Apps {\n\t\t\tif _, ok := appInfo.Plugs[oldName]; ok {\n\t\t\t\tdelete(appInfo.Plugs, oldName)\n\t\t\t\tappInfo.Plugs[newName] = plugInfo\n\t\t\t}\n\t\t}\n\t\tfor _, hookInfo := range info.Hooks {\n\t\t\tif _, ok := hookInfo.Plugs[oldName]; ok {\n\t\t\t\tdelete(hookInfo.Plugs, oldName)\n\t\t\t\thookInfo.Plugs[newName] = plugInfo\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype ListIPSecConnectionsRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tDrgId *string `mandatory:\"false\" contributesTo:\"query\" name:\"drgId\"`\n\n\tCpeId *string `mandatory:\"false\" contributesTo:\"query\" name:\"cpeId\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n}\n\n\n\n\ntype ListIPSecConnectionsResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []IpSecConnection `presentIn:\"body\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ListIPSecConnectionsResponse) String() string {\n\treturn common.PointerString(response)\n}\n\nfunc (request ListIPSecConnectionsRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype Page struct {\n\tTitle string\n\tBody []byte\n}\n\nfunc (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}\n\nfunc loadPage(title string) (*Page, error) {\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Page{Title: title, Body: body}, nil\n}\n\n\n\nfunc main() {\n\thttp.HandleFunc(\"/view/\", viewHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\ttitle := r.URL.Path[len(\"/view/\"):]\n\tp, _ := loadPage(title)\n\tfmt.Fprintf(w, \"

%s

%s
\", p.Title, p.Body)\n}"} {"input": "package hyperkube\n\nimport (\n\t\"io/ioutil\"\n\t\"strings\"\n\n\tutiltemplate \"github.com/kubernetes-sigs/service-catalog/pkg/kubernetes/pkg/util/template\"\n\t\"k8s.io/component-base/cli/flag\"\n\n\t\"github.com/spf13/pflag\"\n)\n\ntype serverRunFunc func(s *Server, args []string, stopCh <-chan struct{}) error\n\n\ntype Server struct {\n\tSimpleUsage string \n\tLong string \n\tRun serverRunFunc \n\tPrimaryName string\n\tAlternativeName string\n\tRespectsStopCh bool\n\n\tflags *pflag.FlagSet \n\thk *HyperKube\n}\n\n\n\n\n\nfunc (s *Server) Name() string {\n\tif s.PrimaryName != \"\" {\n\t\treturn s.PrimaryName\n\t}\n\tname := s.SimpleUsage\n\ti := strings.Index(name, \" \")\n\tif i >= 0 {\n\t\tname = name[:i]\n\t}\n\treturn name\n}\n\n\nfunc (s *Server) Flags() *pflag.FlagSet {\n\tif s.flags == nil {\n\t\ts.flags = pflag.NewFlagSet(s.Name(), pflag.ContinueOnError)\n\t\ts.flags.SetOutput(ioutil.Discard)\n\t\ts.flags.SetNormalizeFunc(flag.WordSepNormalizeFunc)\n\t}\n\treturn s.flags\n}\n\nfunc (s *Server) Usage() error ", "output": "{\n\ttt := `{{if .Long}}{{.Long | trim | wrap \"\"}}\n{{end}}Usage:\n {{.SimpleUsage}} [flags]\n\nAvailable Flags:\n{{.Flags.FlagUsages}}`\n\n\treturn utiltemplate.ExecuteTemplate(s.hk.Out(), tt, s)\n}"} {"input": "package kapacitor\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\n\t\"github.com/influxdata/influxdb/chronograf\"\n\t\"github.com/influxdata/kapacitor/pipeline\"\n\ttotick \"github.com/influxdata/kapacitor/pipeline/tick\"\n)\n\n\nfunc MarshalTICK(script string) ([]byte, error) {\n\tpipeline, err := newPipeline(chronograf.TICKScript(script))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn json.MarshalIndent(pipeline, \"\", \" \")\n}\n\n\n\n\nfunc UnmarshalTICK(octets []byte) (string, error) ", "output": "{\n\tpipe := &pipeline.Pipeline{}\n\tif err := pipe.Unmarshal(octets); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tast := totick.AST{}\n\terr := ast.Build(pipe)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar buf bytes.Buffer\n\tast.Program.Format(&buf, \"\", false)\n\treturn buf.String(), nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\n\n\nfunc page2Handler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\n\tlanguage, param2 := getParameters(r)\n\n\tfmt.Fprint(w, header)\n\n\tfmt.Fprint(w, \"

Hello Go Webserver

\")\n\n\tfmt.Fprint(w, \"

Language=\", language, \"

\")\n\tfmt.Fprint(w, \"

Param2=\", param2, \"

\")\n}"} {"input": "package dax\n\n\ntype Grapher interface {\n\tGetParent() Grapher\n\tAddChild(child Grapher)\n\tGetChildren() []Grapher\n}\n\ntype nodeStack struct {\n\tnodes []Grapher\n}\n\nfunc (s *nodeStack) Init() {\n\ts.nodes = make([]Grapher, 0, 16)\n}\n\nfunc (s *nodeStack) Empty() bool {\n\treturn len(s.nodes) == 0\n}\n\nfunc (s *nodeStack) Push(n Grapher) {\n\ts.nodes = append(s.nodes, n)\n}\n\nfunc (s *nodeStack) Pop() Grapher {\n\ti := len(s.nodes) - 1\n\tn := s.nodes[i]\n\ts.nodes[i] = nil\n\ts.nodes = s.nodes[:i]\n\treturn n\n}\n\ntype SceneGraph struct {\n\tNode\n}\n\n\n\nfunc (sg *SceneGraph) Init() {\n\tsg.Node.Init()\n}\n\nfunc (sg *SceneGraph) updateWorldTransform() {\n\tsg.Node.updateWorldTransform(false)\n}\n\nfunc (sg *SceneGraph) Update(time float64) {\n\tsg.updateWorldTransform()\n}\n\n\nfunc (sg *SceneGraph) Traverse() <-chan Grapher {\n\tch := make(chan Grapher)\n\n\tgo func() {\n\t\tvar stack nodeStack\n\n\t\tstack.Init()\n\t\tstack.Push(sg)\n\n\t\tfor !stack.Empty() {\n\t\t\tn := stack.Pop()\n\t\t\tch <- n\n\t\t\tchildren := n.GetChildren()\n\t\t\tfor i := len(children) - 1; i >= 0; i-- {\n\t\t\t\tstack.Push(children[i])\n\t\t\t}\n\t\t}\n\t\tclose(ch)\n\t}()\n\n\treturn ch\n}\n\nfunc (sg *SceneGraph) Draw(fb Framebuffer) {\n\tfb.render().drawSceneGraph(fb, sg)\n}\n\nfunc NewSceneGraph() *SceneGraph ", "output": "{\n\tsg := new(SceneGraph)\n\tsg.Init()\n\treturn sg\n}"} {"input": "package discoverers\n\nimport (\n\t\"testing\"\n\n\t\"github.com/abesto/easyssh/util\"\n)\n\n\n\nfunc TestSupportedDiscovererNames(t *testing.T) ", "output": "{\n\tutil.AssertStringListEquals(t,\n\t\t[]string{\"comma-separated\", \"const\", \"first-matching\", \"fixed\", \"knife\", \"separated-by\"},\n\t\tSupportedDiscovererNames())\n}"} {"input": "package cloudformation\n\n\n\ntype AWSEMRCluster_InstanceFleetConfig struct {\n\n\tInstanceTypeConfigs []AWSEMRCluster_InstanceTypeConfig `json:\"InstanceTypeConfigs,omitempty\"`\n\n\tLaunchSpecifications *AWSEMRCluster_InstanceFleetProvisioningSpecifications `json:\"LaunchSpecifications,omitempty\"`\n\n\tName string `json:\"Name,omitempty\"`\n\n\tTargetOnDemandCapacity int `json:\"TargetOnDemandCapacity,omitempty\"`\n\n\tTargetSpotCapacity int `json:\"TargetSpotCapacity,omitempty\"`\n}\n\n\n\n\nfunc (r *AWSEMRCluster_InstanceFleetConfig) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::EMR::Cluster.InstanceFleetConfig\"\n}"} {"input": "package vml\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\ntype CT_F struct {\n\tEqnAttr *string\n}\n\n\n\nfunc (m *CT_F) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tif m.EqnAttr != nil {\n\t\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"eqn\"},\n\t\t\tValue: fmt.Sprintf(\"%v\", *m.EqnAttr)})\n\t}\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}\n\nfunc (m *CT_F) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"eqn\" {\n\t\t\tparsed, err := attr.Value, error(nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.EqnAttr = &parsed\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_F: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (m *CT_F) Validate() error {\n\treturn m.ValidateWithPath(\"CT_F\")\n}\n\n\nfunc (m *CT_F) ValidateWithPath(path string) error {\n\treturn nil\n}\n\nfunc NewCT_F() *CT_F ", "output": "{\n\tret := &CT_F{}\n\treturn ret\n}"} {"input": "package runner\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"os/exec\"\n\t\"syscall\"\n)\n\ntype Runner struct {\n\toutStream, errStream io.Writer\n}\n\nfunc New(out, err io.Writer) *Runner {\n\treturn &Runner{out, err}\n}\n\nfunc (r *Runner) Run(command string) error {\n\tcmd := exec.Command(\"cmd\")\n\tcmd.SysProcAttr = &syscall.SysProcAttr{}\n\tcmd.SysProcAttr.CmdLine = \"/C \" + command\n\n\tout_reader, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr_reader, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\n\tgo r.echoStdout(out_reader)\n\tgo r.echoStderr(err_reader)\n\n\terr = cmd.Wait()\n\treturn err\n}\n\nfunc (r *Runner) echoStdout(reader io.Reader) {\n\tscanner := bufio.NewScanner(reader)\n\tfor scanner.Scan() {\n\t\tfmt.Fprintf(r.outStream, \"%s\\n\", scanner.Text())\n\t}\n}\n\n\n\nfunc (r *Runner) echoStderr(reader io.Reader) ", "output": "{\n\tscanner := bufio.NewScanner(reader)\n\tfor scanner.Scan() {\n\t\tfmt.Fprintf(r.errStream, \"%s\\n\", scanner.Text())\n\t}\n}"} {"input": "package vision \n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\n\n\n\nfunc DefaultAuthScopes() []string {\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t\t\"https:www.googleapis.com/auth/cloud-vision\",\n\t}\n}\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context ", "output": "{\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}"} {"input": "package main\n\nimport \"testing\"\n\nvar args []string = []string{\"main_test\", \"a\", \"b\", \"c\", \"d\", \"f\"}\n\nfunc BenchmarkEchoSlow(b *testing.B) {\n for i := 0; i < b.N; i++ {\n echoSlow(args)\n }\n}\n\n\n\nfunc BenchmarkEchoFast(b *testing.B) ", "output": "{\n for i := 0; i < b.N; i++ {\n echoFast(args)\n }\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\nfunc init() {\n\tlog.SetFlags(0)\n\tlog.SetOutput(os.Stderr)\n}\n\nfunc main() {\n\tvar (\n\t\tflags int = (os.O_WRONLY | os.O_CREATE)\n\t\texitval int\n\t\tfiles []io.Writer = []io.Writer{os.Stdout}\n\t)\n\n\tappendFlag := flag.Bool(\"a\", false, \"Append the output to the files rather than overwriting them.\")\n\tinterruptFlag := flag.Bool(\"i\", false, \"Ignore the SIGINT signal.\")\n\tflag.Usage = usage\n\n\tflag.Parse()\n\n\tif *interruptFlag {\n\t\tsignal.Ignore(syscall.SIGINT)\n\t}\n\n\tif *appendFlag {\n\t\tflags |= os.O_APPEND\n\t} else {\n\t\tflags |= os.O_TRUNC\n\t}\n\n\tfor _, arg := range flag.Args() {\n\t\tif arg == \"-\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif f, err := os.OpenFile(arg, flags, os.ModePerm); err != nil {\n\t\t\tlog.Printf(\"%s - %v\", arg, err)\n\t\t\texitval = 1\n\t\t} else {\n\t\t\tdefer f.Close()\n\t\t\tfiles = append(files, f)\n\t\t}\n\t}\n\n\tif _, err := io.Copy(io.MultiWriter(files...), os.Stdin); err != nil {\n\t\tlog.Printf(\"%v\", err)\n\t\texitval = 1\n\t}\n\n\tos.Exit(exitval)\n}\n\n\n\nfunc usage() ", "output": "{\n\tlog.Fatalln(\"usage: tee [-ai] [file ...]\")\n}"} {"input": "package setting_test\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/skiarn/madmock/setting\"\n)\n\n\n\nfunc TestInitSetting_WhenUrlHasPortNumber(t *testing.T) ", "output": "{\n\n\toldArgs := os.Args\n\n\tos.Args = []string{\"cmd\", \"-u=google.com:9090\"}\n\texpectedURL := \"google.com:9090\"\n\texpectedParnetDirName := \"google.com9090\"\n\n\tsettings, err := setting.Create()\n\tif err != nil {\n\t\tt.Errorf(\"Error occured while trying to create settings: %v\", err)\n\t}\n\n\tif settings.TargetURL != expectedURL {\n\t\tt.Errorf(\"Expected: %v but got: %v\", expectedURL, settings.TargetURL)\n\t}\n\n\tsegments := strings.Split(settings.DataDirPath, string(filepath.Separator))\n\tparentDir := segments[len(segments)-1]\n\tif parentDir != expectedParnetDirName {\n\t\tt.Errorf(\"Expected: %v but got: %v\", expectedParnetDirName, parentDir)\n\t}\n\tdefer func() { os.Args = oldArgs }()\n}"} {"input": "package main\n\nimport (\n \"bytes\"\n \"runtime\"\n)\n\n\n\n\n\nfunc escapeShellArg(arg string) string ", "output": "{\n var quotedArg bytes.Buffer\n quotedArg.Grow(len(arg))\n\n if runtime.GOOS == \"windows\" {\n quotedArg.WriteString(`\"`)\n } else {\n quotedArg.WriteString(`'`)\n }\n\n for _, runeVal := range arg {\n if runtime.GOOS == \"windows\" {\n if runeVal == '\"' || runeVal == '%' {\n quotedArg.WriteRune(' ')\n continue\n }\n } else {\n if runeVal == '\\'' {\n quotedArg.WriteString(`'\\'`)\n }\n }\n quotedArg.WriteRune(runeVal)\n }\n if runtime.GOOS == \"windows\" {\n quotedArg.WriteString(`\"`)\n } else {\n quotedArg.WriteString(`'`)\n }\n\n return quotedArg.String()\n}"} {"input": "package dataintegration\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateExternalPublicationRequest struct {\n\n\tWorkspaceId *string `mandatory:\"true\" contributesTo:\"path\" name:\"workspaceId\"`\n\n\tTaskKey *string `mandatory:\"true\" contributesTo:\"path\" name:\"taskKey\"`\n\n\tCreateExternalPublicationDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateExternalPublicationRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateExternalPublicationRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CreateExternalPublicationRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype CreateExternalPublicationResponse struct {\n\n\tRawResponse *http.Response\n\n\tExternalPublication `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateExternalPublicationResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateExternalPublicationResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateExternalPublicationRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package moss\n\nimport (\n\t\"github.com/couchbase/moss\"\n\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\ntype Batch struct {\n\tstore *Store\n\tmerge *store.EmulatedMerge\n\tbatch moss.Batch\n\tbuf []byte \n\tbufUsed int\n}\n\n\n\nfunc (b *Batch) Delete(key []byte) {\n\tvar err error\n\tif b.buf != nil {\n\t\tb.bufUsed += len(key)\n\t\terr = b.batch.AllocDel(key)\n\t} else {\n\t\terr = b.batch.Del(key)\n\t}\n\n\tif err != nil {\n\t\tb.store.Logf(\"bleve moss batch.Delete err: %v\", err)\n\t}\n}\n\nfunc (b *Batch) Merge(key, val []byte) {\n\tif b.buf != nil {\n\t\tb.bufUsed += len(key) + len(val)\n\t}\n\tb.merge.Merge(key, val)\n}\n\nfunc (b *Batch) Reset() {\n\terr := b.Close()\n\tif err != nil {\n\t\tb.store.Logf(\"bleve moss batch.Close err: %v\", err)\n\t\treturn\n\t}\n\n\tbatch, err := b.store.ms.NewBatch(0, 0)\n\tif err == nil {\n\t\tb.batch = batch\n\t\tb.merge = store.NewEmulatedMerge(b.store.mo)\n\t\tb.buf = nil\n\t\tb.bufUsed = 0\n\t}\n}\n\nfunc (b *Batch) Close() error {\n\tb.merge = nil\n\terr := b.batch.Close()\n\tb.batch = nil\n\treturn err\n}\n\nfunc (b *Batch) Set(key, val []byte) ", "output": "{\n\tvar err error\n\tif b.buf != nil {\n\t\tb.bufUsed += len(key) + len(val)\n\t\terr = b.batch.AllocSet(key, val)\n\t} else {\n\t\terr = b.batch.Set(key, val)\n\t}\n\n\tif err != nil {\n\t\tb.store.Logf(\"bleve moss batch.Set err: %v\", err)\n\t}\n}"} {"input": "package minus\n\nimport (\n \"RETIA/unit\"\n \"RETIA/messages\"\n)\n\n\nfunc Create(lrelation, rrelation *unit.Relation) *unit.MinusStatement {\n if lrelation != nil && rrelation != nil && relationsTypeMatches(lrelation, rrelation) {\n statement := new(unit.MinusStatement)\n\n statement.Lrelation = lrelation\n statement.Rrelation = rrelation\n\n return statement\n } else {\n return nil\n }\n}\n\n\n\n\n\nfunc relationsTypeMatches(lrelation, rrelation *unit.Relation) bool {\n if lrelation.Tname == rrelation.Tname {\n return true\n } else {\n messages.TypesMismatch()\n return true\n }\n}\n\nfunc Eval(statement *unit.MinusStatement) *unit.Relation ", "output": "{\n if statement != nil {\n relation := new(unit.Relation)\n\n relation.Tname = statement.Lrelation.Tname\n\n for _, l_tuple := range statement.Lrelation.Tuples {\n present := false\n\n for _, r_tuple := range statement.Rrelation.Tuples {\n if l_tuple.Hash == r_tuple.Hash {\n present = true\n break\n }\n }\n\n if !present {\n relation.Tuples = append(relation.Tuples, l_tuple)\n }\n }\n\n return relation\n } else {\n return nil\n }\n}"} {"input": "package digits\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\n\n\n\n\n\ntype RewriteTransport struct {\n\tTransport http.RoundTripper\n}\n\n\n\nfunc (t *RewriteTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq.URL.Scheme = \"http\"\n\tif t.Transport == nil {\n\t\treturn http.DefaultTransport.RoundTrip(req)\n\t}\n\treturn t.Transport.RoundTrip(req)\n}\n\n\nfunc assertMethod(t *testing.T, expectedMethod string, req *http.Request) {\n\tassert.Equal(t, expectedMethod, req.Method)\n}\n\n\nfunc assertQuery(t *testing.T, expected map[string]string, req *http.Request) {\n\tqueryValues := req.URL.Query()\n\texpectedValues := url.Values{}\n\tfor key, value := range expected {\n\t\texpectedValues.Add(key, value)\n\t}\n\tassert.Equal(t, expectedValues, queryValues)\n}\n\nfunc testServer() (*http.Client, *http.ServeMux, *httptest.Server) ", "output": "{\n\tmux := http.NewServeMux()\n\tserver := httptest.NewServer(mux)\n\ttransport := &RewriteTransport{&http.Transport{\n\t\tProxy: func(req *http.Request) (*url.URL, error) {\n\t\t\treturn url.Parse(server.URL)\n\t\t},\n\t}}\n\tclient := &http.Client{Transport: transport}\n\treturn client, mux, server\n}"} {"input": "package view\n\nimport (\n\n)\n\ntype Template struct {\n\tFilename string \n\tText string\n\tContentTypeExt string\n}\n\n\n\nfunc (template *Template) Render(ctx *Context) (err error) ", "output": "{\n\treturn nil\n}"} {"input": "package jsoniter\n\nimport (\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\"\n)\n\nfunc Test_encode_optional_int_pointer(t *testing.T) {\n\tshould := require.New(t)\n\tvar ptr *int\n\tstr, err := MarshalToString(ptr)\n\tshould.Nil(err)\n\tshould.Equal(\"null\", str)\n\tval := 100\n\tptr = &val\n\tstr, err = MarshalToString(ptr)\n\tshould.Nil(err)\n\tshould.Equal(\"100\", str)\n}\n\nfunc Test_decode_struct_with_optional_field(t *testing.T) {\n\tshould := require.New(t)\n\ttype TestObject struct {\n\t\tField1 *string\n\t\tField2 *string\n\t}\n\tobj := TestObject{}\n\tUnmarshalFromString(`{\"field1\": null, \"field2\": \"world\"}`, &obj)\n\tshould.Nil(obj.Field1)\n\tshould.Equal(\"world\", *obj.Field2)\n}\n\n\n\nfunc Test_encode_struct_with_optional_field(t *testing.T) ", "output": "{\n\tshould := require.New(t)\n\ttype TestObject struct {\n\t\tField1 *string\n\t\tField2 *string\n\t}\n\tobj := TestObject{}\n\tworld := \"world\"\n\tobj.Field2 = &world\n\tstr, err := MarshalToString(obj)\n\tshould.Nil(err)\n\tshould.Contains(str, `\"Field1\":null`)\n\tshould.Contains(str, `\"Field2\":\"world\"`)\n}"} {"input": "package gspt\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"encoding/binary\"\n\t\"encoding/hex\"\n\n\t\"crypto/md5\"\n\t\"os/exec\"\n)\n\nfunc randomMD5() string {\n\tstr := md5.New()\n\trandom := new(bytes.Buffer)\n\n\tbinary.Write(random, binary.LittleEndian, time.Now().UTC().UnixNano())\n\n\tstr.Write(random.Bytes())\n\n\treturn hex.EncodeToString(str.Sum(nil))\n}\n\nfunc TestSetProcTitle(t *testing.T) {\n\tif HaveSetProcTitle == HaveNone {\n\t\tt.SkipNow()\n\t}\n\n\ttitle := randomMD5()\n\n\tSetProcTitle(title)\n\n\tout, err := exec.Command(\"/bin/ps\", \"ax\").Output()\n\tif err != nil {\n\t\tt.SkipNow()\n\t} else if !strings.Contains(string(out), title) {\n\t\tt.FailNow()\n\t}\n}\n\n\n\nfunc TestSetProcTitleFast(t *testing.T) ", "output": "{\n\tif HaveSetProcTitleFast == HaveNone {\n\t\tt.SkipNow()\n\t}\n\n\ttitle := randomMD5()\n\n\tSetProcTitleFast(title)\n\n\tout, err := exec.Command(\"/bin/ps\", \"ax\").Output()\n\tif err != nil {\n\t\tt.SkipNow()\n\t} else if !strings.Contains(string(out), title) {\n\t\tt.FailNow()\n\t}\n}"} {"input": "package netutil\nimport (\n\t\"strings\"\n\t\"os\"\n\n\t\"net\"\n\t\"net/http\"\n\t\"io/ioutil\"\n\t. \"github.com/leanote/leanote/app/lea\"\n)\n\n\n\n\n\n\n\n\n\nfunc GetContent(url string) (content []byte, err error) {\n\tvar resp *http.Response\n\tresp, err = http.Get(url)\n\tLog(err)\n\tif(resp != nil && resp.Body != nil) {\n\t\tdefer resp.Body.Close()\n\t} else {\n\t}\n if resp == nil || resp.Body == nil || err != nil || resp.StatusCode != http.StatusOK {\n\t\treturn\n }\n \n var buf []byte\n \tbuf, err = ioutil.ReadAll(resp.Body)\n \tif(err != nil) {\n \t\tLog(err)\n\t\treturn\n\t}\n \tcontent = buf;\n \terr = nil\n return\n}\n\n\nfunc trimQueryParams(url string) string {\n\tpos := strings.Index(url, \"?\");\n\tif pos != -1 {\n\t\turl = Substr(url, 0, pos);\n\t}\n\tpos = strings.Index(url, \"#\");\n\tif pos != -1 {\n\t\turl = Substr(url, 0, pos);\n\t}\n\tpos = strings.Index(url, \"!\");\n\tif pos != -1 {\n\t\turl = Substr(url, 0, pos);\n\t}\n\treturn url;\n}\n\n\nfunc GetIpFromDomain(domain string) string {\n\tip, _ := net.LookupIP(domain)\n\tif ip != nil && len(ip) > 0 {\n\t\treturn ip[0].String()\n\t}\n\treturn \"\"\n}\n\nfunc WriteUrl(url string, toPath string) (length int64, newFilename, path string, ok bool) ", "output": "{\n\tif url == \"\" {\n\t\treturn;\n\t}\n\tcontent, err := GetContent(url)\n\tif err != nil {\n\t\treturn;\n\t}\n\tlength = int64(len(content))\n\turl = trimQueryParams(url)\n\t_, ext := SplitFilename(url)\n\tif toPath == \"\" {\n\t\ttoPath = \"/tmp\"\n\t}\n\n\tnewFilename = NewGuid() + ext\n\tfullPath := toPath + \"/\" + newFilename\n\tfile, err := os.Create(fullPath)\n defer file.Close()\n if err != nil {\n \treturn\n\t}\n\tfile.Write(content)\n\tpath = fullPath\n\tok = true\n\treturn\n}"} {"input": "package jobs\n\nimport (\n\t\"github.com/simplemvc/gocorelib/cron\"\n\t\"github.com/simplemvc/gocorelib/revel\"\n\t\"strings\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype Func func()\n\nfunc (r Func) Run() { r() }\n\nfunc Schedule(spec string, job cron.Job) {\n\tif strings.HasPrefix(spec, \"cron.\") {\n\t\tconfSpec, found := revel.Config.String(spec)\n\t\tif !found {\n\t\t\tpanic(\"Cron spec not found: \" + spec)\n\t\t}\n\t\tspec = confSpec\n\t}\n\tMainCron.Schedule(cron.Parse(spec), New(job))\n}\n\n\n\n\n\n\n\nfunc Now(job cron.Job) {\n\tgo New(job).Run()\n}\n\n\nfunc In(duration time.Duration, job cron.Job) {\n\tgo func() {\n\t\ttime.Sleep(duration)\n\t\tNew(job).Run()\n\t}()\n}\n\nfunc Every(duration time.Duration, job cron.Job) ", "output": "{\n\tMainCron.Schedule(cron.Every(duration), New(job))\n}"} {"input": "package v1beta2\n\nimport (\n\tv1beta2 \"github.com/enmasseproject/enmasse/pkg/apis/admin/v1beta2\"\n\t\"github.com/enmasseproject/enmasse/pkg/client/clientset/versioned/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype AdminV1beta2Interface interface {\n\tRESTClient() rest.Interface\n\tAddressPlansGetter\n\tAddressSpacePlansGetter\n}\n\n\ntype AdminV1beta2Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *AdminV1beta2Client) AddressPlans(namespace string) AddressPlanInterface {\n\treturn newAddressPlans(c, namespace)\n}\n\nfunc (c *AdminV1beta2Client) AddressSpacePlans(namespace string) AddressSpacePlanInterface {\n\treturn newAddressSpacePlans(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*AdminV1beta2Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AdminV1beta2Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *AdminV1beta2Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *AdminV1beta2Client {\n\treturn &AdminV1beta2Client{c}\n}\n\n\n\n\n\nfunc (c *AdminV1beta2Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc setConfigDefaults(config *rest.Config) error ", "output": "{\n\tgv := v1beta2.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}"} {"input": "package cluster_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/influxdb/influxdb/cluster\"\n\t\"github.com/influxdb/influxdb/services/meta\"\n)\n\nfunc NewNodes() []meta.NodeInfo {\n\tvar nodes []meta.NodeInfo\n\tfor i := 1; i <= 2; i++ {\n\t\tnodes = append(nodes, meta.NodeInfo{\n\t\t\tID: uint64(i),\n\t\t\tHost: fmt.Sprintf(\"localhost:999%d\", i),\n\t\t})\n\t}\n\treturn nodes\n}\n\nfunc TestBalancerEmptyNodes(t *testing.T) {\n\tb := cluster.NewNodeBalancer([]meta.NodeInfo{})\n\tgot := b.Next()\n\tif got != nil {\n\t\tt.Errorf(\"expected nil, got %v\", got)\n\t}\n}\n\n\n\nfunc TestBalancerUp(t *testing.T) ", "output": "{\n\tnodes := NewNodes()\n\tb := cluster.NewNodeBalancer(nodes)\n\n\tfirst := b.Next()\n\tif first == nil {\n\t\tt.Errorf(\"expected datanode, got %v\", first)\n\t}\n\n\tsecond := b.Next()\n\tif second == nil {\n\t\tt.Errorf(\"expected datanode, got %v\", second)\n\t}\n\n\tif first.ID == second.ID {\n\t\tt.Errorf(\"expected first != second. got %v = %v\", first.ID, second.ID)\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/af83/edwig/core\"\n\t\"github.com/af83/edwig/logger\"\n\t\"github.com/af83/edwig/siri\"\n)\n\ntype SIRIStopDiscoveryRequestHandler struct {\n\txmlRequest *siri.XMLStopPointsDiscoveryRequest\n}\n\nfunc (handler *SIRIStopDiscoveryRequestHandler) RequestorRef() string {\n\treturn handler.xmlRequest.RequestorRef()\n}\n\n\n\nfunc (handler *SIRIStopDiscoveryRequestHandler) Respond(connector core.Connector, rw http.ResponseWriter) {\n\tlogger.Log.Debugf(\"StopDiscovery %s\\n\", handler.xmlRequest.MessageIdentifier())\n\n\ttmp := connector.(*core.SIRIStopPointsDiscoveryRequestBroadcaster)\n\tresponse, _ := tmp.StopAreas(handler.xmlRequest)\n\txmlResponse, err := response.BuildXML()\n\tif err != nil {\n\t\tsiriError(\"InternalServiceError\", fmt.Sprintf(\"Internal Error: %v\", err), rw)\n\t\treturn\n\t}\n\n\tsoapEnvelope := siri.NewSOAPEnvelopeBuffer()\n\tsoapEnvelope.WriteXML(xmlResponse)\n\n\t_, err = soapEnvelope.WriteTo(rw)\n\tif err != nil {\n\t\tsiriError(\"InternalServiceError\", fmt.Sprintf(\"Internal Error: %v\", err), rw)\n\t\treturn\n\t}\n}\n\nfunc (handler *SIRIStopDiscoveryRequestHandler) ConnectorType() string ", "output": "{\n\treturn core.SIRI_STOP_POINTS_DISCOVERY_REQUEST_BROADCASTER\n}"} {"input": "package goetchtest\n\nimport . \"etch\"\n\n\n\n\nfunc TestPut(mb Mailbox, msg *Message, sender interface{}) {\n\tmb.Message(sender, msg)\n}\n\nfunc TestPlainMailBox() ", "output": "{\n\tmb := NewPlainMailBox(42)\n\n\tif mb.GetMessageId() != 42 {\n\t\tError(\"Mailbox has wrong ID\\n\")\n\t}\n\n\tmsg := new(Message)\n\n\tsender := 23\n\n\tgo TestPut(mb, msg, sender)\n\n\telem := mb.Read()\n\n\tif elem == nil {\n\t\tError(\"got nil elem from Mailbox\\n\")\n\t} else {\n\t\tif elem.Msg != msg {\n\t\t\tError(\"got wrong elem from Mailbox\\n\")\n\t\t}\n\n\t\tif elem.Who != 23 {\n\t\t\tError(\"got wrong sender from Mailbox\\n\")\n\t\t}\n\t}\n\n\n\n\tLog(\"TestPlainMailBox done\\n\")\n}"} {"input": "package util\n\nimport \"github.com/labstack/echo\"\n\nvar Log echo.Logger\n\n\n\nfunc SetLogger(log echo.Logger) ", "output": "{\n\tLog = log\n}"} {"input": "package client\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\nfunc TestContainerUnpause(t *testing.T) {\n\texpectedURL := \"/containers/container_id/unpause\"\n\tclient := &Client{\n\t\tclient: newMockClient(func(req *http.Request) (*http.Response, error) {\n\t\t\tif !strings.HasPrefix(req.URL.Path, expectedURL) {\n\t\t\t\treturn nil, fmt.Errorf(\"Expected URL '%s', got '%s'\", expectedURL, req.URL)\n\t\t\t}\n\t\t\treturn &http.Response{\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tBody: ioutil.NopCloser(bytes.NewReader([]byte(\"\"))),\n\t\t\t}, nil\n\t\t}),\n\t}\n\terr := client.ContainerUnpause(context.Background(), \"container_id\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestContainerUnpauseError(t *testing.T) ", "output": "{\n\tclient := &Client{\n\t\tclient: newMockClient(errorMock(http.StatusInternalServerError, \"Server error\")),\n\t}\n\terr := client.ContainerUnpause(context.Background(), \"nothing\")\n\tif err == nil || err.Error() != \"Error response from daemon: Server error\" {\n\t\tt.Fatalf(\"expected a Server Error, got %v\", err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc (vt *ValidatorTest) UpdateEmailFileViaCopyingOver(\n\tt *testing.T, emails []string) {\n\torig_file := vt.auth_email_file\n\tvar err error\n\tvt.auth_email_file, err = ioutil.TempFile(\"\", \"test_auth_emails_\")\n\tif err != nil {\n\t\tt.Fatal(\"failed to create temp file for copy: \" + err.Error())\n\t}\n\tvt.WriteEmails(t, emails)\n\terr = os.Rename(vt.auth_email_file.Name(), orig_file.Name())\n\tif err != nil {\n\t\tt.Fatal(\"failed to copy over temp file: \" + err.Error())\n\t}\n\tvt.auth_email_file = orig_file\n}\n\n\n\nfunc TestValidatorOverwriteEmailListViaCopyingOver(t *testing.T) ", "output": "{\n\tvt := NewValidatorTest(t)\n\tdefer vt.TearDown()\n\n\tvt.WriteEmails(t, []string{\"xyzzy@example.com\"})\n\tdomains := []string(nil)\n\tupdated := make(chan bool, 1)\n\tvalidator := vt.NewValidator(domains, updated)\n\n\tif !validator(\"xyzzy@example.com\") {\n\t\tt.Error(\"email in list should validate\")\n\t}\n\n\tvt.UpdateEmailFileViaCopyingOver(t, []string{\"plugh@example.com\"})\n\t<-updated\n\n\tif validator(\"xyzzy@example.com\") {\n\t\tt.Error(\"email removed from list should not validate\")\n\t}\n}"} {"input": "\n\nfunc SumTYPE(a TYPE, b TYPE) TYPE ", "output": "{\n\treturn a + b\n}"} {"input": "package messages\n\nimport (\n\t\"github.com/wscherphof/msg\"\n)\n\n\n\nfunc init() ", "output": "{\n\tmsg.Key(\"ErrDuplicatePrimaryKey\").\n\t\tSet(\"nl\", `Er bestaat al een record met deze gegevens`).\n\t\tSet(\"en\", `A record with these data already exists.`)\n}"} {"input": "package websocket\n\n\ntype WSRequest struct {\n\tTopic string `json:\"topic\"`\n}\n\n\n\n\n\ntype WSResponse struct {\n\tNotificationType string `json:\"notification_type\"`\n\tData interface{} `json:\"data\"`\n\tErrorDetail string `json:\"error_detail,omitempty\"`\n}\n\n\nfunc NewWSResponse(notificationType string, data interface{}, err error) *WSResponse {\n\twsResp := &WSResponse{\n\t\tNotificationType: notificationType,\n\t\tData: data,\n\t}\n\n\tif err != nil {\n\t\twsResp.ErrorDetail = err.Error()\n\t}\n\n\treturn wsResp\n}\n\nfunc NewWSRequest(topic string) *WSRequest ", "output": "{\n\treturn &WSRequest{\n\t\tTopic: topic,\n\t}\n}"} {"input": "package client\n\nimport \"io\"\n\n\n\n\n\n\n\n\ntype EventLogGetter interface {\n\tEventLog() ([]byte, error)\n}\n\nfunc GetEventLog(rw io.ReadWriter) ([]byte, error) ", "output": "{\n\tif elg, ok := rw.(EventLogGetter); ok {\n\t\treturn elg.EventLog()\n\t}\n\treturn getRealEventLog()\n}"} {"input": "package rbac\n\nimport (\n\tv3 \"github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3\"\n\ttypesrbacv1 \"github.com/rancher/rancher/pkg/generated/norman/rbac.authorization.k8s.io/v1\"\n\trbacv1 \"k8s.io/api/rbac/v1\"\n\tapierrors \"k8s.io/apimachinery/pkg/api/errors\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\ntype crHandler struct {\n\tclusterRoles typesrbacv1.ClusterRoleInterface\n\troleTemplateLister v3.RoleTemplateLister\n}\n\n\n\n\n\nfunc (c *crHandler) sync(key string, obj *rbacv1.ClusterRole) (runtime.Object, error) {\n\tif key == \"\" || obj == nil {\n\t\treturn nil, nil\n\t}\n\n\tif owner, ok := obj.Annotations[clusterRoleOwner]; ok {\n\t\t_, err := c.roleTemplateLister.Get(\"\", owner)\n\t\tif err != nil {\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\treturn obj, c.clusterRoles.Delete(obj.Name, &metav1.DeleteOptions{})\n\t\t\t}\n\t\t\treturn obj, err\n\t\t}\n\t}\n\n\treturn obj, nil\n}\n\nfunc newClusterRoleHandler(r *manager) *crHandler ", "output": "{\n\treturn &crHandler{\n\t\tclusterRoles: r.clusterRoles,\n\t\troleTemplateLister: r.rtLister,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime/pprof\"\n)\n\nconst (\n\tusage = `Usage: %s [OPTION...]\ncontrol program for coffee roasting\n\nOptions:\n`\n)\n\nvar (\n\tmemProfile string\n\tcpuProfile string\n)\n\nfunc init() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, usage, os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\n\tflag.StringVar(&memProfile, \"memprofile\", \"\",\n\t\t\"write memory profile to this file\")\n\tflag.StringVar(&cpuProfile, \"cpuprofile\", \"\",\n\t\t\"write cpu profile to this file\")\n\n\tflag.Parse()\n}\n\n\n\nfunc startProfiling() {\n\tvar err error\n\tif memProfile != \"\" {\n\t\truntime.MemProfileRate = 1\n\t}\n\tif cpuProfile != \"\" {\n\t\tvar f *os.File\n\t\tif f, err = os.Create(cpuProfile); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tpprof.StartCPUProfile(f)\n\t}\n}\n\n\n\nfunc main() {\n\tstartProfiling()\n\tdefer stopProfiling()\n\n}\n\nfunc stopProfiling() ", "output": "{\n\tif memProfile != \"\" {\n\t\truntime.GC()\n\t\tf, err := os.Create(memProfile)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tpprof.WriteHeapProfile(f)\n\t\tf.Close()\n\t}\n\tif cpuProfile != \"\" {\n\t\tpprof.StopCPUProfile()\n\t\tcpuProfile = \"\"\n\t}\n}"} {"input": "package sarif\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"net\"\n\t\"time\"\n)\n\ntype netConn struct {\n\tconn net.Conn\n\tenc *json.Encoder\n\tdec *json.Decoder\n\tverified bool\n}\n\n\n\nfunc (c *netConn) Write(msg Message) error {\n\tif err := msg.IsValid(); err != nil {\n\t\treturn err\n\t}\n\tc.conn.SetWriteDeadline(time.Now().Add(5 * time.Minute))\n\treturn c.enc.Encode(msg)\n}\n\nfunc (c *netConn) KeepaliveLoop(ka time.Duration) error {\n\tfor {\n\t\ttime.Sleep(ka)\n\t\tc.conn.SetWriteDeadline(time.Now().Add(3 * ka))\n\t\tif _, err := c.conn.Write([]byte(\" \")); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\nfunc (c *netConn) Read() (Message, error) {\n\tvar msg Message\n\tc.conn.SetReadDeadline(time.Now().Add(time.Hour))\n\tif err := c.dec.Decode(&msg); err != nil {\n\t\treturn msg, err\n\t}\n\treturn msg, msg.IsValid()\n}\n\nfunc (c *netConn) Close() error {\n\treturn c.conn.Close()\n}\n\nfunc (c *netConn) IsVerified() bool {\n\tif tc, ok := c.conn.(*tls.Conn); ok {\n\t\tif len(tc.ConnectionState().VerifiedChains) > 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc newNetConn(conn net.Conn) *netConn ", "output": "{\n\treturn &netConn{\n\t\tconn,\n\t\tjson.NewEncoder(conn),\n\t\tjson.NewDecoder(conn),\n\t\tfalse,\n\t}\n}"} {"input": "package content\nimport (\n\t\"go2o/src/core/domain/interface/content\"\n\t\"time\"\n)\n\nvar _ content.IPage = new(Page)\ntype Page struct{\n\t_contentRep content.IContentRep\n\t_partnerId int\n\t_value *content.ValuePage\n}\n\nfunc NewPage(partnerId int, rep content.IContentRep,v *content.ValuePage) content.IPage {\n\treturn &Page{\n\t\t_contentRep: rep,\n\t\t_partnerId: partnerId,\n\t\t_value:v,\n\t}\n}\n\n\n\nfunc (this *Page) GetDomainId() int{\n\treturn this._value.Id\n}\n\n\n\n\n\nfunc (this *Page) SetValue(v *content.ValuePage)error{\n\tv.Id = this.GetDomainId()\n\tthis._value = v\n\treturn nil\n}\n\n\nfunc (this *Page) Save()(int,error){\n\tthis._value.UpdateTime = time.Now().Unix()\n\treturn this._contentRep.SavePage(this._partnerId,this._value)\n}\n\nfunc (this *Page) GetValue()*content.ValuePage", "output": "{\n\treturn this._value\n}"} {"input": "package opts\n\n\ntype CreateOption func(*CreateConfig)\n\n\n\ntype CreateConfig struct {\n\tOptions map[string]string\n\tLabels map[string]string\n\tReference string\n}\n\n\n\nfunc WithCreateLabels(labels map[string]string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Labels = labels\n\t}\n}\n\n\n\nfunc WithCreateOptions(opts map[string]string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Options = opts\n\t}\n}\n\n\n\n\nfunc WithCreateReference(ref string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Reference = ref\n\t}\n}\n\n\n\ntype GetConfig struct {\n\tDriver string\n\tReference string\n\tResolveStatus bool\n}\n\n\ntype GetOption func(*GetConfig)\n\n\n\n\n\nfunc WithGetDriver(name string) GetOption {\n\treturn func(o *GetConfig) {\n\t\to.Driver = name\n\t}\n}\n\n\n\nfunc WithGetReference(ref string) GetOption {\n\treturn func(o *GetConfig) {\n\t\to.Reference = ref\n\t}\n}\n\n\n\nfunc WithGetResolveStatus(cfg *GetConfig) {\n\tcfg.ResolveStatus = true\n}\n\n\ntype RemoveConfig struct {\n\tPurgeOnError bool\n}\n\n\ntype RemoveOption func(*RemoveConfig)\n\n\n\n\n\n\nfunc WithPurgeOnError(b bool) RemoveOption ", "output": "{\n\treturn func(o *RemoveConfig) {\n\t\to.PurgeOnError = b\n\t}\n}"} {"input": "package undertaker\n\nimport (\n\t\"github.com/juju/errors\"\n\t\"gopkg.in/juju/names.v2\"\n\n\t\"github.com/juju/juju/environs/config\"\n\t\"github.com/juju/juju/state\"\n)\n\n\n\ntype State interface {\n\tstate.EntityFinder\n\n\tModel() (Model, error)\n\n\tIsController() bool\n\n\tProcessDyingModel() (err error)\n\n\tRemoveAllModelDocs() error\n\n\tAllMachines() ([]Machine, error)\n\n\tAllApplications() ([]Service, error)\n\n\tModelConfig() (*config.Config, error)\n}\n\ntype stateShim struct {\n\t*state.State\n}\n\nfunc (s *stateShim) AllMachines() ([]Machine, error) {\n\tstateMachines, err := s.State.AllMachines()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tmachines := make([]Machine, len(stateMachines))\n\tfor i := range stateMachines {\n\t\tmachines[i] = stateMachines[i]\n\t}\n\n\treturn machines, nil\n}\n\n\n\ntype Machine interface {\n\tWatch() state.NotifyWatcher\n}\n\nfunc (s *stateShim) AllApplications() ([]Service, error) {\n\tstateServices, err := s.State.AllApplications()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tservices := make([]Service, len(stateServices))\n\tfor i := range stateServices {\n\t\tservices[i] = stateServices[i]\n\t}\n\n\treturn services, nil\n}\n\n\n\ntype Service interface {\n\tWatch() state.NotifyWatcher\n}\n\n\n\n\n\ntype Model interface {\n\n\tOwner() names.UserTag\n\n\tLife() state.Life\n\n\tName() string\n\n\tUUID() string\n\n\tDestroy() error\n}\n\nfunc (s *stateShim) Model() (Model, error) ", "output": "{\n\treturn s.State.Model()\n}"} {"input": "package instagram\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"net/url\"\n\n\t\"github.com/laicosly/goth\"\n\t\"golang.org/x/oauth2\"\n)\n\n\ntype Session struct {\n\tAuthURL string\n\tAccessToken string\n\tState string\n\tParams url.Values\n}\n\n\nfunc (s Session) GetAuthURL() (string, error) {\n\tif s.AuthURL == \"\" {\n\t\treturn \"\", errors.New(\"an AuthURL has not be set\")\n\t}\n\treturn s.AuthURL, nil\n}\n\n\n\n\n\nfunc (s Session) Marshal() string {\n\tb, _ := json.Marshal(s)\n\treturn string(b)\n}\n\nfunc (s Session) String() string {\n\treturn s.Marshal()\n}\n\nfunc (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) ", "output": "{\n\tp := provider.(*Provider)\n\ttoken, err := p.config.Exchange(oauth2.NoContext, params.Get(\"code\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ts.AccessToken = token.AccessToken\n\treturn token.AccessToken, err\n}"} {"input": "package segment\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/checkr/flagr/swagger_gen/models\"\n)\n\n\nconst DeleteSegmentOKCode int = 200\n\n\ntype DeleteSegmentOK struct {\n}\n\n\nfunc NewDeleteSegmentOK() *DeleteSegmentOK {\n\n\treturn &DeleteSegmentOK{}\n}\n\n\nfunc (o *DeleteSegmentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(200)\n}\n\n\ntype DeleteSegmentDefault struct {\n\t_statusCode int\n\n\tPayload *models.Error `json:\"body,omitempty\"`\n}\n\n\nfunc NewDeleteSegmentDefault(code int) *DeleteSegmentDefault {\n\tif code <= 0 {\n\t\tcode = 500\n\t}\n\n\treturn &DeleteSegmentDefault{\n\t\t_statusCode: code,\n\t}\n}\n\n\nfunc (o *DeleteSegmentDefault) WithStatusCode(code int) *DeleteSegmentDefault {\n\to._statusCode = code\n\treturn o\n}\n\n\nfunc (o *DeleteSegmentDefault) SetStatusCode(code int) {\n\to._statusCode = code\n}\n\n\nfunc (o *DeleteSegmentDefault) WithPayload(payload *models.Error) *DeleteSegmentDefault {\n\to.Payload = payload\n\treturn o\n}\n\n\n\n\n\nfunc (o *DeleteSegmentDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(o._statusCode)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\nfunc (o *DeleteSegmentDefault) SetPayload(payload *models.Error) ", "output": "{\n\to.Payload = payload\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"time\"\n\n\tkcp \"github.com/xtaci/kcp-go\"\n)\n\nfunc main() {\n\tlisten, err := kcp.Listen(\"0.0.0.0:6666\")\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn\n\t}\n\tfor {\n\t\tconn, err := listen.Accept()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t\treturn\n\t\t}\n\n\t\tgo handleconn(conn)\n\t}\n}\n\n\n\nfunc handleconn(conn net.Conn) ", "output": "{\n\tfmt.Println(\"new client\", conn.RemoteAddr())\n\n\tbuf := make([]byte, 65536)\n\tcount := 0\n\tfor {\n\t\tconn.SetReadDeadline(time.Now().Add(10 * time.Second))\n\t\tn, err := conn.Read(buf)\n\t\tfmt.Println(\"new client read: \", n, \" \", string(buf))\n\t\tif err != nil {\n\t\t\tfmt.Println(\"new client read err\", n)\n\t\t\tconn.Close()\n\t\t\treturn\n\t\t}\n\t\tcount++\n\t\tconn.Write(buf[:n])\n\t}\n}"} {"input": "package internalversion\n\nimport (\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n\tadmissionregistration \"k8s.io/kubernetes/pkg/apis/admissionregistration\"\n)\n\n\ntype InitializerConfigurationLister interface {\n\tList(selector labels.Selector) (ret []*admissionregistration.InitializerConfiguration, err error)\n\tGet(name string) (*admissionregistration.InitializerConfiguration, error)\n\tInitializerConfigurationListerExpansion\n}\n\n\ntype initializerConfigurationLister struct {\n\tindexer cache.Indexer\n}\n\n\n\n\n\nfunc (s *initializerConfigurationLister) List(selector labels.Selector) (ret []*admissionregistration.InitializerConfiguration, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*admissionregistration.InitializerConfiguration))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *initializerConfigurationLister) Get(name string) (*admissionregistration.InitializerConfiguration, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(admissionregistration.Resource(\"initializerconfiguration\"), name)\n\t}\n\treturn obj.(*admissionregistration.InitializerConfiguration), nil\n}\n\nfunc NewInitializerConfigurationLister(indexer cache.Indexer) InitializerConfigurationLister ", "output": "{\n\treturn &initializerConfigurationLister{indexer: indexer}\n}"} {"input": "package log\n\n\nfunc (me *Logging) Prefix() string {\n\treturn me.prefix\n}\n\n\nfunc (me *Logging) SetPrefix(value string) {\n\tme.prefix = value\n\tif me.console != nil {\n\t\tme.console.SetPrefix(me.prefix)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPrefix(me.prefix)\n\t}\n}\n\n\nfunc (me *Logging) Priority() int {\n\treturn me.priority\n}\n\n\n\n\n\nfunc (me *Logging) Layouts() int {\n\treturn me.layouts\n}\n\n\nfunc (me *Logging) SetLayouts(value int) {\n\tme.setLayouts = true\n\tme.layouts = value\n\tif me.console != nil {\n\t\tme.console.SetLayouts(me.layouts)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetLayouts(me.layouts)\n\t}\n}\n\n\nfunc (me *Logging) Outputs() int {\n\treturn me.outputs\n}\n\n\nfunc (me *Logging) SetOutputs(value int) {\n\tme.setOutputs = true\n\tme.outputs = value\n}\n\nfunc (me *Logging) SetPriority(value int) ", "output": "{\n\tme.setPriority = true\n\tme.priority = value\n\tif me.console != nil {\n\t\tme.console.SetPriority(me.priority)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPriority(me.priority)\n\t}\n}"} {"input": "package message\n\nimport \"github.com/cloustone/sentel/pkg/config\"\n\ntype Producer interface {\n\tSendMessage(msg Message) error\n\tSendMessages(msgs []Message) error\n\tClose()\n}\n\nfunc NewProducer(c config.Config, clientID string, sync bool) (Producer, error) {\n\treturn newKafkaProducer(c, clientID, sync)\n}\n\nfunc PostMessage(c config.Config, msg Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", false); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessage(msg)\n\t}\n\treturn\n}\n\nfunc PostMessages(c config.Config, msgs []Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", false); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessages(msgs)\n\t}\n\treturn\n}\n\n\n\nfunc SendMessages(c config.Config, msgs []Message) (err error) {\n\tif producer, err := NewProducer(c, \"\", true); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessages(msgs)\n\t}\n\treturn\n}\n\nfunc SendMessage(c config.Config, msg Message) (err error) ", "output": "{\n\tif producer, err := NewProducer(c, \"\", true); err == nil {\n\t\tdefer producer.Close()\n\t\treturn producer.SendMessage(msg)\n\t}\n\treturn\n}"} {"input": "package customer\n\nimport (\n\t\"testing\"\n\n\tassert \"github.com/stretchr/testify/require\"\n\tstripe \"github.com/stripe/stripe-go\"\n\t_ \"github.com/stripe/stripe-go/testing\"\n)\n\nfunc TestCustomerDel(t *testing.T) {\n\tcustomer, err := Del(\"cus_123\", nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerGet(t *testing.T) {\n\tcustomer, err := Get(\"cus_123\", nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerList(t *testing.T) {\n\ti := List(&stripe.CustomerListParams{})\n\n\tassert.True(t, i.Next())\n\tassert.Nil(t, i.Err())\n\tassert.NotNil(t, i.Customer())\n}\n\nfunc TestCustomerNew(t *testing.T) {\n\tcustomer, err := New(&stripe.CustomerParams{\n\t\tEmail: stripe.String(\"foo@example.com\"),\n\t\tShipping: &stripe.CustomerShippingDetailsParams{\n\t\t\tAddress: &stripe.AddressParams{\n\t\t\t\tLine1: stripe.String(\"line1\"),\n\t\t\t\tCity: stripe.String(\"city\"),\n\t\t\t},\n\t\t\tName: stripe.String(\"name\"),\n\t\t},\n\t})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\nfunc TestCustomerNew_NilParams(t *testing.T) {\n\tcustomer, err := New(nil)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}\n\n\n\nfunc TestCustomerUpdate(t *testing.T) ", "output": "{\n\tcustomer, err := Update(\"cus_123\", &stripe.CustomerParams{\n\t\tEmail: stripe.String(\"foo@example.com\"),\n\t})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, customer)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/trasa/watchmud-message\"\n)\n\n\n\nfunc (c *Client) handleSayNotification(note *message.SayNotification) {\n\tif note.Success {\n\t\tUIPrintf(\"%s says '%s'.\\n\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellNotification(note *message.TellNotification) {\n\tif note.GetSuccess() {\n\t\tUIPrintf(\"%s tells you '%s'.\\n\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellResponse(resp *message.TellResponse) {\n\tif resp.GetSuccess() {\n\t\tUIPrintln(\"sent.\")\n\t} else if resp.GetResultCode() == \"TO_PLAYER_NOT_FOUND\" {\n\t\tUIPrintln(\"Nobody here by that name.\")\n\t} else {\n\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellAllResponse(resp *message.TellAllResponse) {\n\tif resp.GetSuccess() {\n\t\tUIPrintln(\"sent.\")\n\t} else {\n\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellAllNotification(note *message.TellAllNotification) {\n\tif note.GetSuccess() {\n\t\tUIPrintf(\"tell_all %s> %s\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleSayResponse(resp *message.SayResponse) ", "output": "{\n\tif resp.Success {\n\t\tUIPrintf(\"You say '%s'\\n\", resp.Value)\n\t} else {\n\t\tif resp.GetResultCode() == \"NOT_IN_A_ROOM\" {\n\t\t\tUIPrintln(\"You yell into the darkness.\")\n\t\t} else {\n\t\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t\t}\n\t}\n}"} {"input": "package elastic\n\n\n\n\n\n\n\n\n\ntype MissingAggregation struct {\n\tfield string\n\tsubAggregations map[string]Aggregation\n\tmeta map[string]interface{}\n}\n\nfunc NewMissingAggregation() *MissingAggregation {\n\treturn &MissingAggregation{\n\t\tsubAggregations: make(map[string]Aggregation),\n\t}\n}\n\n\n\nfunc (a *MissingAggregation) SubAggregation(name string, subAggregation Aggregation) *MissingAggregation {\n\ta.subAggregations[name] = subAggregation\n\treturn a\n}\n\n\nfunc (a *MissingAggregation) Meta(metaData map[string]interface{}) *MissingAggregation {\n\ta.meta = metaData\n\treturn a\n}\n\nfunc (a *MissingAggregation) Source() (interface{}, error) {\n\n\tsource := make(map[string]interface{})\n\topts := make(map[string]interface{})\n\tsource[\"missing\"] = opts\n\n\tif a.field != \"\" {\n\t\topts[\"field\"] = a.field\n\t}\n\n\tif len(a.subAggregations) > 0 {\n\t\taggsMap := make(map[string]interface{})\n\t\tsource[\"aggregations\"] = aggsMap\n\t\tfor name, aggregate := range a.subAggregations {\n\t\t\tsrc, err := aggregate.Source()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\taggsMap[name] = src\n\t\t}\n\t}\n\n\tif len(a.meta) > 0 {\n\t\tsource[\"meta\"] = a.meta\n\t}\n\n\treturn source, nil\n}\n\nfunc (a *MissingAggregation) Field(field string) *MissingAggregation ", "output": "{\n\ta.field = field\n\treturn a\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\tloggo \"github.com/juju/loggo\"\n)\n\ntype (\n\tCustomFormatter struct{}\n)\n\n\n\nfunc GetLogger(module string) loggo.Logger {\n\tlog := loggo.GetLogger(module)\n\treturn log\n}\n\nfunc (formatter *CustomFormatter) Format(level loggo.Level, module, filename string, line int, timestamp time.Time, message string) string {\n\treturn fmt.Sprintf(\"%s\", message)\n}\n\nfunc ReplaceLoggerDefaultFormatter() {\n\twriter := loggo.NewSimpleWriter(os.Stderr, &CustomFormatter{})\n\tloggo.ReplaceDefaultWriter(writer)\n}\n\nfunc InitLog(path string) ", "output": "{\n\tif path == \"\" {\n\t\tpath = \"./util/conf.json\"\n\t}\n\tconfiguration, err := GetConfig(path)\n\tif err != nil {\n\t\tfmt.Println(\"Error reading config\")\n\t\treturn\n\t}\n\tconfig := SerializeConfig(configuration.Logging)\n\tloggo.ConfigureLoggers(config)\n}"} {"input": "package business\n\nimport (\n\t\"github.com/open-gtd/server/auth/domain\"\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype loginLoggerMock struct {\n\tmock.Mock\n}\n\n\n\nfunc (ll *loginLoggerMock) Logged(auth domain.Auth) ", "output": "{\n\tll.Called(auth.UserName, auth.SecurityCode)\n}"} {"input": "package cmd\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n)\n\nimport . \"assert\"\n\ntype cmd_oneshot struct {\n\tcmd string\n}\n\n\n\nfunc (c *cmd_oneshot) Start(in <-chan []string, out chan<- string) {\n\n\tshell := os.Getenv(\"SHELL\")\n\tif shell == \"\" {\n\t\tshell = \"sh\"\n\t}\n\n\tfor {\n\t\tcmdc := exec.Command(shell, \"-c\", c.cmd, \"reg\")\n\t\tif in != nil {\n\t\t\tinput := <-in\n\t\t\tcmdc.Args = append(cmdc.Args, input...)\n\t\t}\n\t\tif out == nil {\n\t\t\terr := cmdc.Run()\n\t\t\tAssert(err == nil, cmdc.Args, \":Run()\", \":\", err)\n\t\t} else {\n\t\t\toutput, err := cmdc.Output()\n\t\t\tAssert(err == nil, cmdc.Args, \":Output()\", \":\", err)\n\t\t\tout <- string(output[:len(output)-1])\n\t\t}\n\t}\n\n}\n\nfunc MakeOneShotCommand(cmd string) Cmd ", "output": "{\n\treturn &cmd_oneshot{cmd}\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"html/template\"\n \"io/ioutil\"\n \"net/http\"\n \"os\"\n)\n\ntype Page struct {\n\tTitle string\n\tBody []byte\n}\n\nfunc (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}\n\nfunc loadPage(title string) (*Page, error) {\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Page{Title: title, Body: body}, nil\n}\n\n\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n title := r.URL.Path[len(\"/view/\"):]\n p, err := loadPage(title)\n if err != nil {\n http.Redirect(w, r, \"/edit/\" + title, http.StatusFound)\n return\n }\n renderTemplate(w, \"view\", p)\n}\n\nfunc editHandler(w http.ResponseWriter, r *http.Request) {\n title := r.URL.Path[len(\"/edit/\"):]\n p, err := loadPage(title)\n if err != nil {\n p = &Page{Title: title}\n }\n renderTemplate(w, \"edit\", p)\n}\n\nfunc main() {\n http.HandleFunc(\"/view/\", viewHandler)\n http.HandleFunc(\"/edit/\", editHandler)\n \n fmt.Println(\"starting http service ...\")\n http.ListenAndServe(os.Getenv(\"IP\") + \":\" + os.Getenv(\"PORT\"), nil)\n}\n\nfunc renderTemplate(w http.ResponseWriter, tmpl string, p *Page) ", "output": "{\n t, _ := template.ParseFiles(tmpl + \".html\")\n t.Execute(w, p)\n}"} {"input": "package main\n\nimport \"net/http\"\n\n\n\nfunc signout(w http.ResponseWriter, r *http.Request) {\n}\n\nfunc getuser(w http.ResponseWriter, r *http.Request) string ", "output": "{\n\treturn \"anonymous\"\n}"} {"input": "package alert\n\nimport (\n\t. \"aliyun-openapi-go-sdk/core\"\n)\n\ntype GetContactGroupRequest struct {\n\tRoaRequest\n\tProjectName string\n\tGroupName string\n}\n\nfunc (r *GetContactGroupRequest) SetProjectName(value string) {\n\tr.ProjectName = value\n\tr.PathParams.Set(\"ProjectName\", value)\n}\n\nfunc (r *GetContactGroupRequest) SetGroupName(value string) {\n\tr.GroupName = value\n\tr.PathParams.Set(\"GroupName\", value)\n}\nfunc (r *GetContactGroupRequest) GetGroupName() string {\n\treturn r.GroupName\n}\n\nfunc (r *GetContactGroupRequest) Init() {\n\tr.RoaRequest.Init()\n\tr.PathPattern = \"/projects/ProjectName/groups/GroupName\"\n\tr.SetMethod(\"GET\")\n\tr.SetProtocol(\"HTTP\")\n\tr.SetProduct(Product)\n}\n\ntype GetContactGroupResponse struct {\n\tcode string `xml:\"code\" json:\"code\"`\n\tmessage string `xml:\"message\" json:\"message\"`\n\tsuccess string `xml:\"success\" json:\"success\"`\n\ttraceId string `xml:\"traceId\" json:\"traceId\"`\n\tresult string `xml:\"result\" json:\"result\"`\n}\n\nfunc GetContactGroup(req *GetContactGroupRequest, accessId, accessSecret string) (*GetContactGroupResponse, error) {\n\tvar pResponse GetContactGroupResponse\n\tbody, err := ApiHttpRequest(accessId, accessSecret, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tApiUnmarshalResponse(req.GetFormat(), body, &pResponse)\n\treturn &pResponse, err\n}\n\nfunc (r *GetContactGroupRequest) GetProjectName() string ", "output": "{\n\treturn r.ProjectName\n}"} {"input": "package es_terminfo\n\nimport (\n\t\"golang.org/x/crypto/ssh/terminal\"\n\t\"os\"\n)\n\nfunc IsInTerminal() bool {\n\treturn terminal.IsTerminal(int(os.Stdin.Fd()))\n}\n\n\n\n\nfunc IsOutColorTerminal() bool {\n\tif !IsOutTerminal() {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc IsOutTerminal() bool ", "output": "{\n\treturn terminal.IsTerminal(int(os.Stdout.Fd()))\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\nfunc plus(a int, b int) int {\n\treturn a + b\n}\n\n\n\n\n\nfunc main() {\n\tres := plus(1, 2)\n\tfmt.Println(\"1+2 = \", res)\n\n\tres = plusPlus(1, 2, 3)\n\tfmt.Println(\"1+2+3 =\", res)\n}\n\nfunc plusPlus(a, b, c int) int ", "output": "{\n\treturn a + b + c\n}"} {"input": "package goqueryja\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/PuerkitoBio/goquery\"\n\t\"golang.org/x/text/encoding/japanese\"\n\t\"golang.org/x/text/transform\"\n)\n\nfunc NewDocument(url_ string) (*goquery.Document, error) {\n\tres, err := http.Get(url_)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tencoding := GetResponseEncoding(res)\n\treader, err := NewUTF8Reader(res.Body, encoding)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn goquery.NewDocumentFromReader(reader)\n}\n\nfunc NewUTF8Reader(r io.Reader, encoding string) (io.Reader, error) {\n\tswitch strings.ToLower(encoding) {\n\tcase \"utf-8\":\n\t\treturn r, nil\n\tcase \"euc-jp\":\n\t\treturn transform.NewReader(r, japanese.EUCJP.NewDecoder()), nil\n\tcase \"shift_jis\":\n\t\treturn transform.NewReader(r, japanese.ShiftJIS.NewDecoder()), nil\n\tcase \"iso-2022-jp\":\n\t\treturn transform.NewReader(r, japanese.ISO2022JP.NewDecoder()), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported encoding: %s\", encoding)\n\t}\n}\n\n\n\nfunc GetResponseEncoding(res *http.Response) string ", "output": "{\n\tcontentType := res.Header.Get(\"Content-Type\")\n\tcontentTypeLower := strings.ToLower(contentType)\n\tif index := strings.Index(contentTypeLower, \"charset=\"); index != -1 {\n\t\treturn contentType[index+len(\"charset=\"):]\n\t} else {\n\t\treturn \"\"\n\t}\n}"} {"input": "package longrunning_test\n\nimport (\n\t\"cloud.google.com/go/longrunning/autogen\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/api/iterator\"\n\tlongrunningpb \"google.golang.org/genproto/googleapis/longrunning\"\n)\n\nfunc ExampleNewOperationsClient() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\nfunc ExampleOperationsClient_GetOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.GetOperationRequest{\n\t}\n\tresp, err := c.GetOperation(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleOperationsClient_ListOperations() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.ListOperationsRequest{\n\t}\n\tit := c.ListOperations(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}\n\n\n\nfunc ExampleOperationsClient_DeleteOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.DeleteOperationRequest{\n\t}\n\terr = c.DeleteOperation(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleOperationsClient_CancelOperation() ", "output": "{\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.CancelOperationRequest{\n\t}\n\terr = c.CancelOperation(ctx, req)\n\tif err != nil {\n\t}\n}"} {"input": "package stats\n\nimport (\n\t\"code.google.com/p/probab/dst\"\n\t\"math\"\n\t\"math/rand\"\n)\n\nfunc Sample(n, k int, idx []int) []int {\n\tidx = use_int_slice(idx, k)\n\tfor i := 0; i < k; i++ {\n\t\tidx[i] = rand.Intn(n)\n\t}\n\treturn idx\n}\n\n\n\n\n\nfunc WeightedSample(w []float64, n int, idx []int) []int {\n\tidx = use_int_slice(idx, n)\n\tfor i := 0; i < n; i++ {\n\t\tidx[i] = int(dst.ChoiceNext(w))\n\t}\n\treturn idx\n}\n\n\n\n\n\n\n\n\nfunc LogweightedSample(logw []float64, n int, idx []int) []int ", "output": "{\n\tw := make([]float64, len(logw))\n\tmax, _ := FloatMax(logw)\n\tvar sum float64\n\tfor i, lw := range logw {\n\t\tw[i] = math.Exp(lw - max)\n\t\tsum += w[i]\n\t}\n\tFloatScale(w, 1/sum, w)\n\n\treturn WeightedSample(w, n, idx)\n}"} {"input": "package gnocchi\n\nimport (\n\t\"github.com/gophercloud/gophercloud\"\n)\n\nfunc initClientOpts(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts, clientType string) (*gophercloud.ServiceClient, error) {\n\tsc := new(gophercloud.ServiceClient)\n\teo.ApplyDefaults(clientType)\n\turl, err := client.EndpointLocator(eo)\n\tif err != nil {\n\t\treturn sc, err\n\t}\n\tsc.ProviderClient = client\n\tsc.Endpoint = url\n\tsc.Type = clientType\n\treturn sc, nil\n}\n\n\n\n\nfunc NewGnocchiV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) ", "output": "{\n\tsc, err := initClientOpts(client, eo, \"metric\")\n\tsc.ResourceBase = sc.Endpoint + \"v1/\"\n\treturn sc, err\n}"} {"input": "package iso20022\n\n\ntype AutomatedTellerMachine6 struct {\n\n\tIdentification *Max35Text `xml:\"Id\"`\n\n\tAdditionalIdentification *Max35Text `xml:\"AddtlId,omitempty\"`\n\n\tSequenceNumber *Max35Text `xml:\"SeqNb,omitempty\"`\n\n\tLocation *PostalAddress17 `xml:\"Lctn,omitempty\"`\n\n\tLocationCategory *TransactionEnvironment2Code `xml:\"LctnCtgy,omitempty\"`\n\n\tEquipment *ATMEquipment1 `xml:\"Eqpmnt,omitempty\"`\n}\n\n\n\nfunc (a *AutomatedTellerMachine6) SetAdditionalIdentification(value string) {\n\ta.AdditionalIdentification = (*Max35Text)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) SetSequenceNumber(value string) {\n\ta.SequenceNumber = (*Max35Text)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) AddLocation() *PostalAddress17 {\n\ta.Location = new(PostalAddress17)\n\treturn a.Location\n}\n\nfunc (a *AutomatedTellerMachine6) SetLocationCategory(value string) {\n\ta.LocationCategory = (*TransactionEnvironment2Code)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) AddEquipment() *ATMEquipment1 {\n\ta.Equipment = new(ATMEquipment1)\n\treturn a.Equipment\n}\n\nfunc (a *AutomatedTellerMachine6) SetIdentification(value string) ", "output": "{\n\ta.Identification = (*Max35Text)(&value)\n}"} {"input": "package incoming\n\nimport (\n\t\"github.com/pkg/errors\"\n)\n\ntype ignorableErr struct {\n\terror\n}\n\n\n\nfunc wrapIgnorable(err error) error {\n\treturn ignorableErr{error: err}\n}\n\nfunc (m *RuleMap) Get(name string) (*Rule, error) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tif m.rules == nil {\n\t\treturn nil, wrapIgnorable(errors.New(\"rule not found: '\" + name + \"'\"))\n\t}\n\n\tr, ok := m.rules[name]\n\tif !ok {\n\t\treturn nil, wrapIgnorable(errors.New(\"rule not found: '\" + name + \"'\"))\n\t}\n\treturn r, nil\n}\n\nfunc (m *RuleMap) Set(name string, r *Rule) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tif m.rules == nil {\n\t\tm.rules = make(map[string]*Rule)\n\t}\n\n\tm.rules[name] = r\n}\n\nfunc (r Rule) Disabled() bool {\n\treturn false\n}\n\nfunc (r Rule) AggregationWindow() int64 {\n\treturn 300\n}\n\nfunc (e ignorableErr) Ignorable() bool ", "output": "{\n\treturn true\n}"} {"input": "package iso20022\n\n\ntype AmountAndRateFormat3Choice struct {\n\n\tAmount *ActiveCurrencyAndAmount `xml:\"Amt\"`\n\n\tNotSpecifiedRate *RateValueType6FormatChoice `xml:\"NotSpcfdRate\"`\n}\n\n\n\nfunc (a *AmountAndRateFormat3Choice) AddNotSpecifiedRate() *RateValueType6FormatChoice {\n\ta.NotSpecifiedRate = new(RateValueType6FormatChoice)\n\treturn a.NotSpecifiedRate\n}\n\nfunc (a *AmountAndRateFormat3Choice) SetAmount(value, currency string) ", "output": "{\n\ta.Amount = NewActiveCurrencyAndAmount(value, currency)\n}"} {"input": "package icinga\n\nimport \"strconv\"\n\nfunc _() {\n\tvar x [1]struct{}\n\t_ = x[OK-0]\n\t_ = x[Warning-1]\n\t_ = x[Critical-2]\n\t_ = x[Unknown-3]\n}\n\nconst _State_name = \"OKWarningCriticalUnknown\"\n\nvar _State_index = [...]uint8{0, 2, 9, 17, 24}\n\n\n\nfunc (i State) String() string ", "output": "{\n\tif i < 0 || i >= State(len(_State_index)-1) {\n\t\treturn \"State(\" + strconv.FormatInt(int64(i), 10) + \")\"\n\t}\n\treturn _State_name[_State_index[i]:_State_index[i+1]]\n}"} {"input": "package git\n\nimport \"github.com/ory-am/gitdeploy/task\"\n\n\n\n\nfunc Checkout(app, path, ref string) func(task.WorkerLog) error ", "output": "{\n\treturn func(w task.WorkerLog) error {\n\t\tw.Add(\"Checking out branch...\")\n\t\tif err := task.Exec(w, path, \"git\", \"checkout\", \"-b\", app, ref); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype UpdateDedicatedVmHostRequest struct {\n\n\tDedicatedVmHostId *string `mandatory:\"true\" contributesTo:\"path\" name:\"dedicatedVmHostId\"`\n\n\tUpdateDedicatedVmHostDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateDedicatedVmHostRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request UpdateDedicatedVmHostRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request UpdateDedicatedVmHostRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateDedicatedVmHostResponse struct {\n\n\tRawResponse *http.Response\n\n\tDedicatedVmHost `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response UpdateDedicatedVmHostResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response UpdateDedicatedVmHostResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package bootstrappolicy\n\nimport rbacv1 \"k8s.io/api/rbac/v1\"\n\ntype PolicyData struct {\n\tClusterRoles []rbacv1.ClusterRole\n\tClusterRoleBindings []rbacv1.ClusterRoleBinding\n\tRoles map[string][]rbacv1.Role\n\tRoleBindings map[string][]rbacv1.RoleBinding\n\tClusterRolesToAggregate map[string]string\n}\n\n\n\nfunc Policy() *PolicyData ", "output": "{\n\treturn &PolicyData{\n\t\tClusterRoles: GetBootstrapClusterRoles(),\n\t\tClusterRoleBindings: GetBootstrapClusterRoleBindings(),\n\t\tRoles: NamespaceRoles(),\n\t\tRoleBindings: NamespaceRoleBindings(),\n\t\tClusterRolesToAggregate: GetBootstrapClusterRolesToAggregate(),\n\t}\n}"} {"input": "package migrations\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n)\n\nfunc OpenDB(repoPath string, dbPassword string, testnet bool) (*sql.DB, error) {\n\tvar dbPath string\n\tif testnet {\n\t\tdbPath = path.Join(repoPath, \"datastore\", \"testnet.db\")\n\t} else {\n\t\tdbPath = path.Join(repoPath, \"datastore\", \"mainnet.db\")\n\t}\n\tdb, err := sql.Open(\"sqlite3\", dbPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif dbPassword != \"\" {\n\t\tp := \"pragma key='\" + dbPassword + \"';\"\n\t\t_, err = db.Exec(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn db, nil\n}\n\n\n\nfunc writeRepoVer(repoPath string, version int) error {\n\tf1, err := os.Create(path.Join(repoPath, \"repover\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = f1.Write([]byte(strconv.Itoa(version)))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f1.Close()\n}\n\nfunc writeIPFSVer(repoPath string, version int) error {\n\tf1, err := os.Create(path.Join(repoPath, \"version\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = f1.Write([]byte(strconv.Itoa(version)))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f1.Close()\n}\n\nfunc withTransaction(db *sql.DB, handler func(tx *sql.Tx) error) error ", "output": "{\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"beginning transaction: %s\", err.Error())\n\t}\n\n\thandleErr := handler(tx)\n\tif handleErr != nil {\n\t\tif err := tx.Rollback(); err != nil {\n\t\t\treturn fmt.Errorf(\"handler AND rollback failed: %s (rollback error: %s)\", handleErr.Error(), err.Error())\n\t\t}\n\t\treturn fmt.Errorf(\"handler failed: %s\", handleErr.Error())\n\t}\n\n\tif err := tx.Commit(); err != nil {\n\t\treturn fmt.Errorf(\"commit failed: %s\", err.Error())\n\t}\n\n\treturn nil\n}"} {"input": "package utp\n\nimport (\n\t\"time\"\n\n\t\"github.com/micro/go-micro/transport\"\n)\n\nfunc (u *utpClient) Send(m *transport.Message) error {\n\tif u.timeout > time.Duration(0) {\n\t\tu.conn.SetDeadline(time.Now().Add(u.timeout))\n\t}\n\tif err := u.enc.Encode(m); err != nil {\n\t\treturn err\n\t}\n\treturn u.encBuf.Flush()\n}\n\n\n\nfunc (u *utpClient) Close() error {\n\treturn u.conn.Close()\n}\n\nfunc (u *utpClient) Recv(m *transport.Message) error ", "output": "{\n\tif u.timeout > time.Duration(0) {\n\t\tu.conn.SetDeadline(time.Now().Add(u.timeout))\n\t}\n\treturn u.dec.Decode(&m)\n}"} {"input": "package apps\n\nimport (\n\t\"os\"\n\n\t\"github.com/fsnotify/fsnotify\"\n)\n\ntype FileEvent struct {\n\tfsnotify.Event\n\tNotExist bool\n\tIsDir bool\n\tIsFound bool\n}\n\n\n\nfunc NewFileEvent(ev fsnotify.Event) *FileEvent {\n\tvar notExist bool\n\tvar isDir bool\n\tif stat, err := os.Stat(ev.Name); os.IsNotExist(err) {\n\t\tnotExist = true\n\t} else if err == nil {\n\t\tisDir = stat.IsDir()\n\t}\n\treturn &FileEvent{\n\t\tEvent: ev,\n\t\tNotExist: notExist,\n\t\tIsDir: isDir,\n\t}\n}\n\nfunc NewFileFoundEvent(name string) *FileEvent ", "output": "{\n\treturn &FileEvent{\n\t\tEvent: fsnotify.Event{\n\t\t\tName: name,\n\t\t},\n\t\tIsFound: true,\n\t}\n}"} {"input": "package geo\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\nfunc TestDefineYesHaversine(t *testing.T) {\n\n\tif yesHaversine(make([]bool, 0)) {\n\t\tt.Error(\"define, yesHaversine should be false, got true\")\n\t}\n\n\tif !yesHaversine([]bool{true}) {\n\t\tt.Error(\"define, yesHaversine should be true, got false\")\n\t}\n\n\tif yesHaversine([]bool{false}) {\n\t\tt.Error(\"define, yesHaversine should be false, got true\")\n\t}\n}\n\nfunc TestDefineDeg2Rad(t *testing.T) {\n\tif math.Abs(deg2rad(0.0)) > epsilon {\n\t\tt.Error(\"define, deg2rad error\")\n\t}\n\n\tif math.Abs(deg2rad(180.0)-math.Pi) > epsilon {\n\t\tt.Error(\"define, deg2rad error\")\n\t}\n\n\tif math.Abs(deg2rad(360.0)-2*math.Pi) > epsilon {\n\t\tt.Error(\"define, deg2rad error\")\n\t}\n}\n\n\n\nfunc TestDefineRad2Deg(t *testing.T) ", "output": "{\n\tif math.Abs(rad2deg(0.0)-0.0) > epsilon {\n\t\tt.Error(\"define, rad2deg error\")\n\t}\n\n\tif math.Abs(rad2deg(math.Pi)-180.0) > epsilon {\n\t\tt.Error(\"define, rad2deg error\")\n\t}\n\n\tif math.Abs(rad2deg(2*math.Pi)-360.0) > epsilon {\n\t\tt.Error(\"define, rad2deg error\")\n\t}\n}"} {"input": "package buildings\n\ntype store struct {\n\tbasicBuilding\n\timprovementLvl int8\n\tsales int\n\tprice int\n}\n\nfunc (*store) GetType() string { return \"store\" }\nfunc (b *store) GetRevenue() int { return b.sales * b.price }\nfunc (b *store) GetRent() int { return [4]int{1, 2, 3, 5}[b.improvementLvl] }\nfunc (b *store) GetInternalInt(name string) int {\n\tswitch name {\n\tcase \"improvementLvl\":\n\t\treturn int(b.improvementLvl)\n\tcase \"sales\":\n\t\treturn b.sales\n\tcase \"price\":\n\t\treturn b.price\n\tdefault:\n\t\treturn 0\n\t}\n}\nfunc (b *store) SetInternalInt(name string, val int) {\n\tswitch name {\n\tcase \"improvementLvl\":\n\t\tb.improvementLvl = int8(val)\n\tcase \"sales\":\n\t\tb.sales = val\n\tcase \"price\":\n\t\tb.price = val\n\t}\n}\n\n\nfunc (b *store) ToString(x, y int) string ", "output": "{\n\treturn \"store,\" + string(b.improvementLvl) + \",\" + string(b.sales) + \",\" + string(b.price) + \",\" + b.basicBuilding.ToString(x, y)\n}"} {"input": "package clients\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"cloud.google.com/go/pubsub\"\n)\n\n\ntype PubSub struct {\n\tclient *pubsub.Client\n}\n\n\nfunc NewPubSub(ctx context.Context, projectID string) (*PubSub, error) {\n\tclient, err := pubsub.NewClient(ctx, projectID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to init pubsub: %q\", err)\n\t}\n\treturn &PubSub{client: client}, nil\n}\n\n\nfunc (p *PubSub) Topic(id string) *pubsub.Topic {\n\treturn p.client.Topic(id)\n}\n\n\n\n\nfunc (p *PubSub) Publish(ctx context.Context, topic *pubsub.Topic, message *pubsub.Message) (string, error) ", "output": "{\n\tdefer topic.Stop()\n\treturn topic.Publish(ctx, message).Get(ctx)\n}"} {"input": "package testutil\n\nimport (\n\t\"testing\"\n\n\t\"github.com/tendermint/abci/server\"\n\twire \"github.com/tendermint/go-wire\"\n\t\"github.com/tendermint/merkleeyes/app\"\n\teyes \"github.com/tendermint/merkleeyes/client\"\n\t. \"github.com/tendermint/tmlibs/common\"\n)\n\n\nfunc CreateEyes(t *testing.T) (svr Service, cli *eyes.Client) {\n\taddr := \"unix://eyes.sock\"\n\n\tmApp := app.NewMerkleEyesApp(\"\", 0)\n\tsvr, err := server.NewServer(addr, \"socket\", mApp)\n\tif err != nil {\n\t\t(err.Error())\n\t\treturn\n\t}\n\n\tcli, err = eyes.NewClient(addr)\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t\treturn\n\t}\n\n\treturn svr, cli\n}\n\n\nfunc MakeTxKV() ([]byte, []byte, []byte) {\n\tk := []byte(RandStr(8))\n\tv := []byte(RandStr(8))\n\treturn k, v, makeSet(k, v)\n}\n\n\n\n\n\nfunc makeSet(key, value []byte) []byte ", "output": "{\n\ttx := make([]byte, 1+wire.ByteSliceSize(key)+wire.ByteSliceSize(value))\n\tbuf := tx\n\tbuf[0] = app.TxTypeSet \n\tbuf = buf[1:]\n\tn, err := wire.PutByteSlice(buf, key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tbuf = buf[n:]\n\tn, err = wire.PutByteSlice(buf, value)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn tx\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\nfunc Index(vs []string, t string) int {\n\tfor i, v := range vs {\n\t\tif v == t {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\n\n\nfunc Include(vs []string, t string) bool {\n\treturn Index(vs, t) >= 0\n}\n\n\n\nfunc Any(vs []string, f func(string) bool) bool {\n\tfor _, v := range vs {\n\t\tif f(v) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc All(vs []string, f func(string) bool) bool {\n\tfor _, v := range vs {\n\t\tif !f(v) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\nfunc Filter(vs []string, f func(string) bool) []string {\n\tvsf := make([]string, 0)\n\tfor _, v := range vs {\n\t\tif f(v) {\n\t\t\tvsf = append(vsf, v)\n\t\t}\n\t}\n\treturn vsf\n}\n\n\n\n\n\nfunc main() {\n\n\tvar strs = []string{\"peach\", \"apple\", \"pear\", \"plum\"}\n\n\tfmt.Println(Index(strs, \"pear\"))\n\n\tfmt.Println(Include(strs, \"grape\"))\n\n\tfmt.Println(Any(strs, func(v string) bool {\n\t\treturn strings.HasPrefix(v, \"p\")\n\t}))\n\n\tfmt.Println(All(strs, func(v string) bool {\n\t\treturn strings.HasPrefix(v, \"p\")\n\t}))\n\n\tfmt.Println(Filter(strs, func(v string) bool {\n\t\treturn strings.Contains(v, \"e\")\n\t}))\n\n\tfmt.Println(Map(strs, strings.ToUpper))\n\n}\n\nfunc Map(vs []string, f func(string) string) []string ", "output": "{\n\tvsm := make([]string, len(vs))\n\tfor i, v := range vs {\n\t\tvsm[i] = f(v)\n\t}\n\treturn vsm\n}"} {"input": "package pgsql\n\nimport (\n\t\"database/sql\"\n\t\"time\"\n\n\t\"github.com/coreos/clair/pkg/commonerr\"\n)\n\n\n\n\n\nfunc (pgSQL *pgSQL) GetKeyValue(key string) (string, error) {\n\tdefer observeQueryTime(\"GetKeyValue\", \"all\", time.Now())\n\n\tvar value string\n\terr := pgSQL.QueryRow(searchKeyValue, key).Scan(&value)\n\n\tif err == sql.ErrNoRows {\n\t\treturn \"\", nil\n\t}\n\tif err != nil {\n\t\treturn \"\", handleError(\"searchKeyValue\", err)\n\t}\n\n\treturn value, nil\n}\n\nfunc (pgSQL *pgSQL) InsertKeyValue(key, value string) (err error) ", "output": "{\n\tif key == \"\" || value == \"\" {\n\t\tlog.Warning(\"could not insert a flag which has an empty name or value\")\n\t\treturn commonerr.NewBadRequestError(\"could not insert a flag which has an empty name or value\")\n\t}\n\n\tdefer observeQueryTime(\"InsertKeyValue\", \"all\", time.Now())\n\n\n\tfor {\n\t\tr, err := pgSQL.Exec(updateKeyValue, value, key)\n\t\tif err != nil {\n\t\t\treturn handleError(\"updateKeyValue\", err)\n\t\t}\n\t\tif n, _ := r.RowsAffected(); n > 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\t_, err = pgSQL.Exec(insertKeyValue, key, value)\n\t\tif err != nil {\n\t\t\tif isErrUniqueViolation(err) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn handleError(\"insertKeyValue\", err)\n\t\t}\n\n\t\treturn nil\n\t}\n}"} {"input": "package probe_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/minio/mc/pkg/probe\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype MySuite struct{}\n\nvar _ = Suite(&MySuite{})\n\n\n\nfunc testDummy1() *probe.Error {\n\treturn testDummy0().Trace(\"DummyTag1\")\n}\n\nfunc testDummy2() *probe.Error {\n\treturn testDummy1().Trace(\"DummyTag2\")\n}\n\nfunc (s *MySuite) TestProbe(c *C) {\n\tprobe.Init() \n\tprobe.SetAppInfo(\"Commit-ID\", \"7390cc957239\")\n\tes := testDummy2().Trace(\"TopOfStack\")\n\tc.Assert(es, Not(Equals), nil)\n\n\tnewES := es.Trace()\n\tc.Assert(newES, Not(Equals), nil)\n}\n\nfunc (s *MySuite) TestWrappedError(c *C) {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\tes := probe.NewError(e) \n\te = probe.WrapError(es) \n\t_, ok := probe.UnwrapError(e)\n\tc.Assert(ok, Equals, true)\n}\n\nfunc testDummy0() *probe.Error ", "output": "{\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\treturn probe.NewError(e)\n}"} {"input": "package restutil\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/eclipse/che/agents/go-agents/core/rest\"\n)\n\n\nfunc WriteJSON(w http.ResponseWriter, body interface{}) error {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\treturn json.NewEncoder(w).Encode(body)\n}\n\n\nfunc ReadJSON(r *http.Request, v interface{}) error {\n\treturn json.NewDecoder(r.Body).Decode(v)\n}\n\n\n\nfunc IntQueryParam(r *http.Request, name string, defaultValue int) int {\n\tqp := r.URL.Query().Get(name)\n\tif qp == \"\" {\n\t\treturn defaultValue\n\t}\n\tv, err := strconv.Atoi(qp)\n\tif err != nil {\n\t\treturn defaultValue\n\t}\n\tif v < 0 {\n\t\treturn defaultValue\n\t}\n\treturn v\n}\n\n\n\n\nfunc OKRespondingFunc(w http.ResponseWriter, r *http.Request, _ rest.Params) error ", "output": "{\n\tw.WriteHeader(http.StatusOK)\n\treturn nil\n}"} {"input": "package api\n\n\ntype UserInfo interface {\n\tGetName() string\n\tGetUID() string\n\tGetScope() string\n\tGetExtra() map[string]string\n}\n\n\n\ntype UserIdentityInfo interface {\n\tGetUserName() string\n\tGetProviderName() string\n\tGetExtra() map[string]string\n}\n\n\ntype UserIdentityMapper interface {\n\tUserFor(identityInfo UserIdentityInfo) (UserInfo, error)\n}\n\ntype Client interface {\n\tGetId() string\n\tGetSecret() string\n\tGetRedirectUri() string\n\tGetUserData() interface{}\n}\n\ntype Grant struct {\n\tClient Client\n\tScope string\n\tExpiration int64\n\tRedirectURI string\n}\n\ntype DefaultUserInfo struct {\n\tName string\n\tUID string\n\tScope string\n\tExtra map[string]string\n}\n\nfunc (i *DefaultUserInfo) GetName() string {\n\treturn i.Name\n}\n\nfunc (i *DefaultUserInfo) GetUID() string {\n\treturn i.UID\n}\n\nfunc (i *DefaultUserInfo) GetScope() string {\n\treturn i.Scope\n}\n\nfunc (i *DefaultUserInfo) GetExtra() map[string]string {\n\treturn i.Extra\n}\n\ntype DefaultUserIdentityInfo struct {\n\tUserName string\n\tProviderName string\n\tExtra map[string]string\n}\n\n\nfunc NewDefaultUserIdentityInfo(username string) DefaultUserIdentityInfo {\n\treturn DefaultUserIdentityInfo{\n\t\tUserName: username,\n\t\tExtra: make(map[string]string),\n\t}\n}\n\nfunc (i *DefaultUserIdentityInfo) GetUserName() string {\n\treturn i.UserName\n}\n\nfunc (i *DefaultUserIdentityInfo) GetProviderName() string {\n\treturn i.ProviderName\n}\n\n\n\nfunc (i *DefaultUserIdentityInfo) GetExtra() map[string]string ", "output": "{\n\treturn i.Extra\n}"} {"input": "package bunyan\n\nimport \"fmt\"\n\n\ntype Logger struct {\n\tsink Sink\n\trecord Record\n}\n\n\nfunc NewLogger(target Sink) *Logger {\n\treturn &Logger{target, NewRecord()}\n}\n\n\n\nfunc (l *Logger) Write(record Record) error {\n\trecord.TemplateMerge(l.record)\n\treturn l.sink.Write(record)\n}\n\n\n\nfunc (l *Logger) Include(info Info) Log {\n\treturn NewLogger(InfoSink(l, info))\n}\n\n\n\nfunc (l *Logger) Record(key string, value interface{}) Log {\n\tbuilder := NewLogger(l)\n\tbuilder.record[key] = value\n\treturn builder\n}\n\n\n\n\n\n\n\nfunc (l *Logger) Child() Log {\n\treturn NewLogger(l)\n}\n\nfunc (l *Logger) Tracef(msg string, args ...interface{}) { l.send(TRACE, msg, args...) }\nfunc (l *Logger) Debugf(msg string, args ...interface{}) { l.send(DEBUG, msg, args...) }\nfunc (l *Logger) Infof(msg string, args ...interface{}) { l.send(INFO, msg, args...) }\nfunc (l *Logger) Warnf(msg string, args ...interface{}) { l.send(WARN, msg, args...) }\nfunc (l *Logger) Errorf(msg string, args ...interface{}) { l.send(ERROR, msg, args...) }\nfunc (l *Logger) Fatalf(msg string, args ...interface{}) { l.send(FATAL, msg, args...) }\n\nfunc (l *Logger) send(level Level, msg string, args ...interface{}) {\n\trecord := NewRecord()\n\trecord.SetMessagef(level, msg, args...)\n\te := l.Write(record)\n\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc (l *Logger) Recordf(key, value string, args ...interface{}) Log ", "output": "{\n\treturn l.Record(key, fmt.Sprintf(value, args...))\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/atlassian/git-lob/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n)\n\ntype BeEmptyMatcher struct {\n}\n\nfunc (matcher *BeEmptyMatcher) Match(actual interface{}) (success bool, err error) {\n\tlength, ok := lengthOf(actual)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"BeEmpty matcher expects a string/array/map/channel/slice. Got:\\n%s\", format.Object(actual, 1))\n\t}\n\n\treturn length == 0, nil\n}\n\n\n\nfunc (matcher *BeEmptyMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"not to be empty\")\n}\n\nfunc (matcher *BeEmptyMatcher) FailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn format.Message(actual, \"to be empty\")\n}"} {"input": "package jwt_test\n\nimport (\n\t\"log\"\n\t\"testing\"\n\n\t\"github.com/nilslice/jwt\"\n)\n\nfunc TestGrantPasses(t *testing.T) {\n\tclaims := map[string]interface{}{\n\t\t\"testID\": 1,\n\t\t\"name\": \"GrantPasses\",\n\t}\n\n\tgrant, err := jwt.New(claims)\n\tif err != nil {\n\t\tt.Log(claims, grant, err)\n\t\tt.Fail()\n\t}\n\n\tif !jwt.Passes(grant) {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestGrantFails(t *testing.T) {\n\tclaims := map[string]interface{}{\n\t\t\"testID\": 2,\n\t\t\"name\": \"GrantFails\",\n\t}\n\n\tgrant, err := jwt.New(claims)\n\tif err != nil {\n\t\tt.Log(claims, grant, err)\n\t\tt.Fail()\n\t}\n\n\tjwt.Secret([]byte(\"NotPreviousSecret\"))\n\n\tif jwt.Passes(grant) {\n\t\tt.Fail()\n\t}\n}\n\n\n\nfunc TestGetClaims(t *testing.T) ", "output": "{\n\temail := \"hello@nilslice.xyz\"\n\tauthLevel := float64(7)\n\n\tclaims := map[string]interface{}{\n\t\t\"email\": email,\n\t\t\"auth_level\": authLevel,\n\t}\n\n\ttoken, err := jwt.New(claims)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tt.Fail()\n\t}\n\n\tclaims = jwt.GetClaims(token)\n\tif claims[\"email\"].(string) != email ||\n\t\tclaims[\"auth_level\"].(float64) != authLevel {\n\t\tt.Fail()\n\t}\n\n}"} {"input": "package citrixadc\n\nimport (\n\t\"github.com/citrix/adc-nitro-go/resource/config/router\"\n\n\t\"github.com/hashicorp/terraform/helper/resource\"\n\t\"github.com/hashicorp/terraform/helper/schema\"\n\n\t\"log\"\n\t\"strings\"\n)\n\n\n\nfunc applyRouterdynamicroutingFunc(d *schema.ResourceData, meta interface{}) error {\n\tlog.Printf(\"[DEBUG] citrixadc-provider: In createRouterdynamicroutingFunc\")\n\tclient := meta.(*NetScalerNitroClient).client\n\trouterdynamicroutingName := resource.PrefixedUniqueId(\"tf-routerdynamicrouting-\")\n\n\tlines := d.Get(\"commandlines\").([]interface{})\n\tstringArray := make([]string, 0, len(lines))\n\tfor _, line := range lines {\n\t\tstringArray = append(stringArray, line.(string))\n\t}\n\n\tcmdString := strings.Join(stringArray, \"\\n\")\n\n\trouterdynamicrouting := router.Routerdynamicrouting{\n\t\tCommandstring: cmdString,\n\t\tNodeid: d.Get(\"nodeid\").(int),\n\t}\n\n\terr := client.ActOnResource(\"routerdynamicrouting\", &routerdynamicrouting, \"apply\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.SetId(routerdynamicroutingName)\n\n\treturn nil\n}\n\nfunc resourceCitrixAdcRouterdynamicrouting() *schema.Resource ", "output": "{\n\treturn &schema.Resource{\n\t\tSchemaVersion: 1,\n\t\tCreate: applyRouterdynamicroutingFunc,\n\t\tRead: schema.Noop,\n\t\tDelete: schema.Noop,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"commandlines\": &schema.Schema{\n\t\t\t\tType: schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem: &schema.Schema{Type: schema.TypeString},\n\t\t\t},\n\t\t\t\"nodeid\": &schema.Schema{\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package main\n\nvar x, y, i = 0, 0, 1\n\nvar a [10] int\n\nfunc f() int {\n\treturn 100\n}\n\nvar b, c = 3, 4\n\nfunc g() bool {\n\treturn true\n}\n\n\n\nfunc main() {\n\ta[i] = x\n\n\tx = +x\n\tx = 23 + 3 * a[i]\n\tx = x <= f()\n\tx = ^b >> c\n\tx = g() || h()\n\tx = x == y+1 && c > 0\n}\n\nfunc h() bool ", "output": "{\n\treturn false\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nfunc theme(value string) (string, http.HandlerFunc) {\n\tif filepath.Ext(value) == \".css\" {\n\t\tcssPath, err := filepath.Abs(value)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error finding custom theme: %s: %s. Falling back to: %s.\", value, err.Error(), DefaultTheme)\n\t\t\treturn themePath(DefaultTheme), nil\n\t\t}\n\n\t\tif stat, err := os.Stat(cssPath); err == nil && !stat.IsDir() {\n\t\t\thandler := func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\thttp.ServeFile(w, r, cssPath)\n\t\t\t}\n\t\t\treturn themePath(\"custom\"), handler\n\t\t}\n\n\t\tlog.Printf(\"Error finding custom theme: %s. Falling back to: %s.\", value, DefaultTheme)\n\t\treturn themePath(DefaultTheme), nil\n\t}\n\n\tlocalPath := themeAssetPath(value)\n\t_, err := Asset(localPath)\n\tif err != nil {\n\t\tlog.Printf(\"Invalid theme selected: %s. Falling back to: %s.\", value, DefaultTheme)\n\t\treturn themePath(DefaultTheme), nil\n\t}\n\n\treturn themePath(value), nil\n}\n\n\n\nfunc themeAssetPath(value string) string {\n\treturn fmt.Sprintf(\"assets/themes/%s.css\", value)\n}\n\nfunc themePath(value string) string ", "output": "{\n\treturn fmt.Sprintf(\"/assets/themes/%s.css\", value)\n}"} {"input": "package api\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/zaaksam/dproxy/go/services\"\n)\n\n\ntype ProxyController struct {\n\tBaseController\n}\n\n\nfunc (c *ProxyController) Start() {\n\tidStr := c.Ctx.Input.Param(\":id\")\n\tid, err := strconv.ParseInt(idStr, 10, 0)\n\tif err != nil {\n\t\tc.SetError(\"id参数错误\")\n\t\treturn\n\t}\n\n\terr = services.Proxy.Start(id)\n\tif err != nil {\n\t\tc.SetError(err)\n\t}\n}\n\n\n\n\nfunc (c *ProxyController) Stop() ", "output": "{\n\tidStr := c.Ctx.Input.Param(\":id\")\n\tid, err := strconv.ParseInt(idStr, 10, 0)\n\tif err != nil {\n\t\tc.SetError(\"id参数错误\")\n\t\treturn\n\t}\n\n\tservices.Proxy.Stop(id)\n}"} {"input": "package build\n\nimport \"github.com/docker/docker/api/server/router\"\n\n\ntype buildRouter struct {\n\tbackend Backend\n\troutes []router.Route\n}\n\n\nfunc NewRouter(b Backend) router.Router {\n\tr := &buildRouter{\n\t\tbackend: b,\n\t}\n\tr.initRoutes()\n\treturn r\n}\n\n\nfunc (r *buildRouter) Routes() []router.Route {\n\treturn r.routes\n}\n\n\n\nfunc (r *buildRouter) initRoutes() ", "output": "{\n\tr.routes = []router.Route{\n\t\trouter.NewPostRoute(\"/build\", r.postBuild),\n\t}\n}"} {"input": "package uguis\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n)\n\nconst serviceNameSimplePlayer = \"simplePlayer\"\n\n\ntype simplePlayer struct {\n\tcommand string\n\treqC chan PlayerRequest\n\tresC chan PlayerResponse\n\tclosedReqC chan struct{}\n\tapp *Application\n\tlgr Logger\n}\n\n\nfunc (p *simplePlayer) Play(req PlayerRequest) {\n\tp.reqC <- req\n}\n\n\nfunc (p *simplePlayer) Close() error {\n\tclose(p.reqC)\n\n\t<-p.closedReqC\n\n\treturn nil\n}\n\n\nfunc (p *simplePlayer) ResC() <-chan PlayerResponse {\n\treturn p.resC\n}\n\n\nfunc (p *simplePlayer) play() {\n\tfor req := range p.reqC {\n\t\tp.lgr.Print(NewLog(\n\t\t\tLogLevelINFO,\n\t\t\tp.app.Hostname,\n\t\t\tserviceNameSimplePlayer,\n\t\t\tfmt.Sprintf(\"%s by %s(@%s)\", req.tweet.Text, req.tweet.User.Name, req.tweet.User.ScreenName),\n\t\t))\n\n\t\tpath := req.path\n\n\t\tif err := exec.Command(p.command, path).Run(); err != nil {\n\t\t\tp.logError(err)\n\t\t\tcontinue\n\t\t}\n\t\tp.resC <- NewPlayerResponse(req.tweet, path)\n\t}\n\n\tp.closedReqC <- struct{}{}\n}\n\nfunc (p *simplePlayer) logError(err error) {\n\tp.lgr.Print(NewLog(\n\t\tLogLevelERROR,\n\t\tp.app.Hostname,\n\t\tserviceNameSimplePlayer,\n\t\terr.Error(),\n\t))\n}\n\n\n\n\nfunc NewSimplePlayer(\n\tcommand string,\n\tapp *Application,\n\tlgr Logger,\n\topts *SimplePlayerOptions,\n) Player ", "output": "{\n\tif opts == nil {\n\t\topts = &SimplePlayerOptions{}\n\t}\n\topts.setDefaults()\n\n\tp := &simplePlayer{\n\t\tcommand: command,\n\t\treqC: make(chan PlayerRequest, opts.ReqCBfSize),\n\t\tresC: make(chan PlayerResponse, opts.ResCBfSize),\n\t\tclosedReqC: make(chan struct{}),\n\t\tapp: app,\n\t\tlgr: lgr,\n\t}\n\n\tgo p.play()\n\n\treturn p\n}"} {"input": "package native\n\nimport (\n\t\"runtime\"\n\n\tgogl \"github.com/go-gl/gl\"\n\tglfw \"github.com/go-gl/glfw3\"\n\n\t\"github.com/dertseha/golgo/runner\"\n)\n\nfunc Run(application runner.Application, param runner.ApplicationParameter) {\n\truntime.LockOSThread()\n\tdefer runtime.UnlockOSThread()\n\n\tif !glfw.Init() {\n\t\tpanic(\"Failed to initialize GLFW\")\n\t}\n\tdefer glfw.Terminate()\n\tsetupGlfw()\n\n\twindow, err := glfw.CreateWindow(param.Width(), param.Height(), param.Title(), nil, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer window.Destroy()\n\tsetupWindow(window, application)\n\n\tgogl.Init()\n\tgl := CreateGles2Wrapper()\n\n\tapplication.Init(gl, param.Width(), param.Height())\n\tfor !window.ShouldClose() {\n\t\tapplication.Render()\n\n\t\twindow.SwapBuffers()\n\t\tglfw.PollEvents()\n\t}\n}\n\n\n\nfunc setupWindow(window *glfw.Window, application runner.Application) {\n\twindow.SetSizeCallback(func(_ *glfw.Window, width int, height int) {\n\t\tapplication.Resize(width, height)\n\t})\n\n\twindow.SetKeyCallback(getKeyCallback(application))\n\n\twindow.MakeContextCurrent()\n}\n\nfunc getKeyCallback(application runner.Application) func(*glfw.Window, glfw.Key, int, glfw.Action, glfw.ModifierKey) {\n\treturn func(window *glfw.Window, key glfw.Key, scancode int, action glfw.Action, modifier glfw.ModifierKey) {\n\t\tswitch key {\n\t\tcase glfw.KeyEscape:\n\t\t\twindow.SetShouldClose(true)\n\t\t}\n\t}\n}\n\nfunc setupGlfw() ", "output": "{\n\tglfw.WindowHint(glfw.ContextVersionMajor, 2)\n\tglfw.WindowHint(glfw.ContextVersionMinor, 0)\n\tglfw.SwapInterval(1)\n}"} {"input": "package interpreter\n\nimport \"math\"\n\n\n\n\n\n\ntype Coster interface {\n\tCost() (min, max int64)\n}\n\n\n\n\nfunc estimateCost(i interface{}) (min, max int64) ", "output": "{\n\tc, ok := i.(Coster)\n\tif !ok {\n\t\treturn 0, math.MaxInt64\n\t}\n\treturn c.Cost()\n}"} {"input": "package fakes\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org/route-registrar/commandrunner\"\n\t\"code.cloudfoundry.org/route-registrar/healthchecker\"\n)\n\ntype FakeHealthChecker struct {\n\tCheckStub func(runner commandrunner.Runner, scriptPath string, timeout time.Duration) (bool, error)\n\tcheckMutex sync.RWMutex\n\tcheckArgsForCall []struct {\n\t\trunner commandrunner.Runner\n\t\tscriptPath string\n\t\ttimeout time.Duration\n\t}\n\tcheckReturns struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}\n}\n\nfunc (fake *FakeHealthChecker) Check(runner commandrunner.Runner, scriptPath string, timeout time.Duration) (bool, error) {\n\tfake.checkMutex.Lock()\n\tfake.checkArgsForCall = append(fake.checkArgsForCall, struct {\n\t\trunner commandrunner.Runner\n\t\tscriptPath string\n\t\ttimeout time.Duration\n\t}{runner, scriptPath, timeout})\n\tfake.checkMutex.Unlock()\n\tif fake.CheckStub != nil {\n\t\treturn fake.CheckStub(runner, scriptPath, timeout)\n\t} else {\n\t\treturn fake.checkReturns.result1, fake.checkReturns.result2\n\t}\n}\n\nfunc (fake *FakeHealthChecker) CheckCallCount() int {\n\tfake.checkMutex.RLock()\n\tdefer fake.checkMutex.RUnlock()\n\treturn len(fake.checkArgsForCall)\n}\n\n\n\nfunc (fake *FakeHealthChecker) CheckReturns(result1 bool, result2 error) {\n\tfake.CheckStub = nil\n\tfake.checkReturns = struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nvar _ healthchecker.HealthChecker = new(FakeHealthChecker)\n\nfunc (fake *FakeHealthChecker) CheckArgsForCall(i int) (commandrunner.Runner, string, time.Duration) ", "output": "{\n\tfake.checkMutex.RLock()\n\tdefer fake.checkMutex.RUnlock()\n\treturn fake.checkArgsForCall[i].runner, fake.checkArgsForCall[i].scriptPath, fake.checkArgsForCall[i].timeout\n}"} {"input": "package musicserver\n\nimport (\n\t\"net/http\"\n\t\"time\"\n)\n\nfunc adminHandler(w http.ResponseWriter, req *http.Request) {\n\tip := getIPFromRequest(req)\n\n\tif ad.ValidSession(ip) {\n\t\ttl.Render(w, \"admin\", newPlaylistInfo(ip))\n\t} else {\n\t\thttp.Redirect(w, req, url(\"/admin/login\"), http.StatusFound)\n\t}\n}\n\nfunc adminLoginHandler(w http.ResponseWriter, req *http.Request) {\n\tif req.Method != http.MethodPost {\n\t\ttl.Render(w, \"admin_login\", nil)\n\t\treturn\n\t}\n\n\tip := getIPFromRequest(req)\n\tpwd := req.PostFormValue(\"admin_pwd\")\n\tif ad.ValidPassword(pwd) {\n\t\tad.StartSession(ip)\n\t\thttp.Redirect(w, req, url(\"/admin\"), http.StatusSeeOther)\n\t\treturn\n\t} else {\n\t\ttl.Render(w, \"admin_bad_login\", nil)\n\t\treturn\n\t}\n}\n\nfunc adminLogoutHandler(w http.ResponseWriter, req *http.Request) {\n\tip := getIPFromRequest(req)\n\tad.EndSession(ip)\n\thttp.Redirect(w, req, url(\"/\"), http.StatusSeeOther)\n}\n\nfunc adminRemoveHandler(w http.ResponseWriter, req *http.Request) {\n\tip := getIPFromRequest(req)\n\tif req.Method == http.MethodPost && ad.ValidSession(ip) {\n\t\tremUUID := req.PostFormValue(\"video_id\")\n\t\tpl.RemoveVideo(remUUID)\n\t}\n\thttp.Redirect(w, req, url(\"/admin\"), http.StatusSeeOther)\n}\n\n\n\nfunc adminKillVideoHandler(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tip := getIPFromRequest(req)\n\tif !ad.ValidSession(ip) {\n\t\thttp.Redirect(w, req, url(\"/admin/login\"), http.StatusFound)\n\t\treturn\n\t}\n\n\tvd.End()\n\ttime.Sleep(500 * time.Millisecond)\n\n\thttp.Redirect(w, req, url(\"/admin\"), http.StatusFound)\n}"} {"input": "package repo\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/user\"\n\t\"path/filepath\"\n)\n\nconst netrcFile = `\nmachine %s\nlogin %s\npassword %s\n`\n\n\nfunc WriteKey(privateKey string) error {\n\tif privateKey == \"\" {\n\t\treturn nil\n\t}\n\n\thome := \"/root\"\n\n\tif currentUser, err := user.Current(); err == nil {\n\t\thome = currentUser.HomeDir\n\t}\n\n\tsshpath := filepath.Join(\n\t\thome,\n\t\t\".ssh\")\n\n\tif err := os.MkdirAll(sshpath, 0700); err != nil {\n\t\treturn err\n\t}\n\n\tconfpath := filepath.Join(\n\t\tsshpath,\n\t\t\"config\")\n\n\tprivpath := filepath.Join(\n\t\tsshpath,\n\t\t\"id_rsa\")\n\n\tioutil.WriteFile(\n\t\tconfpath,\n\t\t[]byte(\"StrictHostKeyChecking no\\n\"),\n\t\t0700)\n\n\treturn ioutil.WriteFile(\n\t\tprivpath,\n\t\t[]byte(privateKey),\n\t\t0600)\n}\n\n\n\n\n\nfunc WriteToken(remote string, login, password string) (string, error) {\n\tif remote == \"\" || login == \"\" || password == \"\" {\n\t\treturn remote, nil\n\t}\n\n\tu, err := url.Parse(remote)\n\n\tif err != nil {\n\t\treturn remote, err\n\t}\n\n\tu.User = url.UserPassword(login, password)\n\n\treturn u.String(), nil\n}\n\nfunc WriteNetrc(machine, login, password string) error ", "output": "{\n\tif machine == \"\" {\n\t\treturn nil\n\t}\n\n\tnetrcContent := fmt.Sprintf(\n\t\tnetrcFile,\n\t\tmachine,\n\t\tlogin,\n\t\tpassword,\n\t)\n\n\thome := \"/root\"\n\n\tif currentUser, err := user.Current(); err == nil {\n\t\thome = currentUser.HomeDir\n\t}\n\n\tnetpath := filepath.Join(\n\t\thome,\n\t\t\".netrc\")\n\n\treturn ioutil.WriteFile(\n\t\tnetpath,\n\t\t[]byte(netrcContent),\n\t\t0600)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc main() {\n\tserver, err := net.Listen(\"tcp\", \":3000\")\n\tcheckError(err)\n\tfor {\n\t\tconn, err := server.Accept()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tconn.Write(append([]byte(time.Now().String()), '\\n'))\n\t\tconn.Close()\n\t}\n}\n\n\nfunc checkError(err error) ", "output": "{\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Fatal error: %s\", err.Error())\n\t\tos.Exit(1)\n\t}\n}"} {"input": "package upload\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"go.skia.org/infra/perf/go/ingest/format\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc LogPath(gcsPath string, now time.Time, b []byte) string {\n\thash := fmt.Sprintf(\"%x\", md5.Sum(b))\n\tfilename := fmt.Sprintf(\"%s.json\", hash)\n\treturn path.Join(gcsPath, now.Format(\"2006/01/02/15/\"), filename)\n}\n\nfunc ObjectPath(benchData *format.BenchData, gcsPath string, now time.Time, b []byte) string ", "output": "{\n\thash := fmt.Sprintf(\"%x\", md5.Sum(b))\n\tkeyparts := []string{}\n\tif benchData.Key != nil {\n\t\tfor k, v := range benchData.Key {\n\t\t\tkeyparts = append(keyparts, k, v)\n\t\t}\n\t}\n\tfilename := fmt.Sprintf(\"%s_%s_%s.json\", benchData.Hash, strings.Join(keyparts, \"_\"), hash)\n\treturn path.Join(gcsPath, now.Format(\"2006/01/02/15/\"), filename)\n}"} {"input": "package diceroller\n\n\n\nfunc Roll(f int) int ", "output": "{\n return 1\n}"} {"input": "package system\n\nimport (\n\t\"github.com/juju/cmd\"\n\t\"github.com/juju/errors\"\n\t\"launchpad.net/gnuflag\"\n\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/cmd/envcmd\"\n)\n\nfunc newListBlocksCommand() cmd.Command {\n\treturn envcmd.WrapSystem(&listBlocksCommand{})\n}\n\n\ntype listBlocksCommand struct {\n\tenvcmd.SysCommandBase\n\tout cmd.Output\n\tapi listBlocksAPI\n\tapierr error\n}\n\nvar listBlocksDoc = `List all blocks for environments within the specified system`\n\n\n\ntype listBlocksAPI interface {\n\tClose() error\n\tListBlockedEnvironments() ([]params.EnvironmentBlockInfo, error)\n}\n\n\nfunc (c *listBlocksCommand) Info() *cmd.Info {\n\treturn &cmd.Info{\n\t\tName: \"list-blocks\",\n\t\tPurpose: \"list all blocks within the system\",\n\t\tDoc: listBlocksDoc,\n\t}\n}\n\n\nfunc (c *listBlocksCommand) SetFlags(f *gnuflag.FlagSet) {\n\tc.out.AddFlags(f, \"tabular\", map[string]cmd.Formatter{\n\t\t\"yaml\": cmd.FormatYaml,\n\t\t\"json\": cmd.FormatJson,\n\t\t\"tabular\": formatTabularBlockedEnvironments,\n\t})\n}\n\n\n\n\nfunc (c *listBlocksCommand) Run(ctx *cmd.Context) error {\n\tapi, err := c.getAPI()\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"cannot connect to the API\")\n\t}\n\tdefer api.Close()\n\n\tenvs, err := api.ListBlockedEnvironments()\n\tif err != nil {\n\t\tlogger.Errorf(\"Unable to list blocked environments: %s\", err)\n\t\treturn err\n\t}\n\treturn c.out.Write(ctx, envs)\n}\n\nfunc (c *listBlocksCommand) getAPI() (listBlocksAPI, error) ", "output": "{\n\tif c.api != nil {\n\t\treturn c.api, c.apierr\n\t}\n\treturn c.NewSystemManagerAPIClient()\n}"} {"input": "package kafka\n\nimport (\n\t\"github.com/hyperledger/fabric/orderer/config\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n)\n\n\ntype Orderer interface {\n\tBroadcast(stream ab.AtomicBroadcast_BroadcastServer) error\n\tDeliver(stream ab.AtomicBroadcast_DeliverServer) error\n\tTeardown() error\n}\n\n\ntype Closeable interface {\n\tClose() error\n}\n\ntype serverImpl struct {\n\tbroadcaster Broadcaster\n\tdeliverer Deliverer\n}\n\n\n\n\n\nfunc (s *serverImpl) Broadcast(stream ab.AtomicBroadcast_BroadcastServer) error {\n\treturn s.broadcaster.Broadcast(stream)\n}\n\n\nfunc (s *serverImpl) Deliver(stream ab.AtomicBroadcast_DeliverServer) error {\n\treturn s.deliverer.Deliver(stream)\n}\n\n\nfunc (s *serverImpl) Teardown() error {\n\ts.deliverer.Close()\n\treturn s.broadcaster.Close()\n}\n\nfunc New(conf *config.TopLevel) Orderer ", "output": "{\n\treturn &serverImpl{\n\t\tbroadcaster: newBroadcaster(conf),\n\t\tdeliverer: newDeliverer(conf),\n\t}\n}"} {"input": "package user\n\nimport \"github.com/openshift/origin/pkg/user/api\"\n\ntype DefaultUserInitStrategy struct {\n}\n\n\n\n\nfunc (*DefaultUserInitStrategy) InitializeUser(identity *api.Identity, user *api.User) error {\n\tif identity.Extra != nil {\n\t\tif name, ok := identity.Extra[\"name\"]; ok && len(name) > 0 {\n\t\t\tuser.FullName = name\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc NewDefaultUserInitStrategy() Initializer ", "output": "{\n\treturn &DefaultUserInitStrategy{}\n}"} {"input": "package collector\n\nimport (\n\t\"github.com/go-kit/log\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\ntype interruptsCollector struct {\n\tdesc typedDesc\n\tlogger log.Logger\n}\n\nfunc init() {\n\tregisterCollector(\"interrupts\", defaultDisabled, NewInterruptsCollector)\n}\n\n\n\n\nfunc NewInterruptsCollector(logger log.Logger) (Collector, error) ", "output": "{\n\treturn &interruptsCollector{\n\t\tdesc: typedDesc{prometheus.NewDesc(\n\t\t\tnamespace+\"_interrupts_total\",\n\t\t\t\"Interrupt details.\",\n\t\t\tinterruptLabelNames, nil,\n\t\t), prometheus.CounterValue},\n\t\tlogger: logger,\n\t}, nil\n}"} {"input": "package codec\n\nimport (\n\t\"fmt\"\n\t\"github.com/davyxu/cellnet\"\n)\n\nvar registedCodecs []cellnet.Codec\n\n\nfunc RegisterCodec(c cellnet.Codec) {\n\n\tif GetCodec(c.Name()) != nil {\n\t\tpanic(\"duplicate codec: \" + c.Name())\n\t}\n\n\tregistedCodecs = append(registedCodecs, c)\n}\n\n\nfunc GetCodec(name string) cellnet.Codec {\n\n\tfor _, c := range registedCodecs {\n\t\tif c.Name() == name {\n\t\t\treturn c\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc MustGetCodec(name string) cellnet.Codec {\n\tcodec := GetCodec(name)\n\n\tif codec == nil {\n\t\tpanic(fmt.Sprintf(\"codec not found '%s'\\ntry to add code below:\\nimport (\\n _ \\\"%s\\\"\\n)\\n\\n\",\n\t\t\tname,\n\t\t\tgetPackageByCodecName(name)))\n\t}\n\n\treturn codec\n}\n\nfunc getPackageByCodecName(name string) string ", "output": "{\n\tswitch name {\n\tcase \"binary\":\n\t\treturn \"github.com/davyxu/cellnet/codec/binary\"\n\tcase \"gogopb\":\n\t\treturn \"github.com/davyxu/cellnet/codec/gogopb\"\n\tcase \"httpjson\":\n\t\treturn \"github.com/davyxu/cellnet/codec/httpjson\"\n\tcase \"json\":\n\t\treturn \"github.com/davyxu/cellnet/codec/json\"\n\tcase \"protoplus\":\n\t\treturn \"github.com/davyxu/cellnet/codec/protoplus\"\n\tdefault:\n\t\treturn \"package/to/your/codec\"\n\t}\n}"} {"input": "package main\n\nfunc f1(i int) {\n\tfor j := i - 1; j >= 0; j-- { \n\t}\n}\n\nfunc f2(i int, s string) {\n\tfor j := i + 1; j < len(s); j-- { \n\t}\n}\n\nfunc f3(s string) {\n\tfor i, l := 0, len(s); i > l; i++ { \n\t}\n}\n\nfunc f4(lower int, a []int) {\n\tfor i := lower - 1; i >= 0; i-- { \n\t\ta[i] = 0\n\t}\n}\n\n\n\nfunc f6(upper uint, a []int) {\n\tfor i := upper + 1; i < uint(len(a)); i-- { \n\t\ta[i] = 0\n\t}\n}\n\nfunc f7(a []int) {\n\tfor i := uint(len(a)) - 1; i < uint(len(a)); i-- { \n\t\ta[i] = 0\n\t}\n}\n\nfunc main() {}\n\nfunc f5(upper int, a []int) ", "output": "{\n\tfor i := upper + 1; i < len(a); i-- { \n\t\ta[i] = 0\n\t}\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"k8s.io/client-go/kubernetes/typed/extensions/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeExtensionsV1beta1 struct {\n\t*testing.Fake\n}\n\n\n\nfunc (c *FakeExtensionsV1beta1) Deployments(namespace string) v1beta1.DeploymentInterface {\n\treturn &FakeDeployments{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) Ingresses(namespace string) v1beta1.IngressInterface {\n\treturn &FakeIngresses{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) PodSecurityPolicies() v1beta1.PodSecurityPolicyInterface {\n\treturn &FakePodSecurityPolicies{c}\n}\n\nfunc (c *FakeExtensionsV1beta1) ReplicaSets(namespace string) v1beta1.ReplicaSetInterface {\n\treturn &FakeReplicaSets{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) Scales(namespace string) v1beta1.ScaleInterface {\n\treturn &FakeScales{c, namespace}\n}\n\n\n\nfunc (c *FakeExtensionsV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeExtensionsV1beta1) DaemonSets(namespace string) v1beta1.DaemonSetInterface ", "output": "{\n\treturn &FakeDaemonSets{c, namespace}\n}"} {"input": "package main\n\nimport (\n\t\"html/template\"\n\t\"net/http\"\n\t\"path\"\n)\n\ntype Book struct {\n\tTitle string `json:\"title\"`\n\tAuthor string `json:\"author\"`\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/\", ShowBooks)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\n\n\nfunc ShowBooks(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tbook := Book{\"Building Web Apps with Go\", \"Jeremy Saenz\"}\n\n\tfp := path.Join(\"templates\", \"index.html\")\n\ttmpl, err := template.ParseFiles(fp)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif err := tmpl.Execute(w, book); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"net\"\n\t\"strconv\"\n)\n\nconst (\n\tAddrTypeIP = byte(0x01)\n\tAddrTypeDomain = byte(0x03)\n)\n\ntype VAddress struct {\n\tType byte\n\tIP net.IP\n\tDomain string\n\tPort uint16\n}\n\nfunc IPAddress(ip []byte, port uint16) VAddress {\n\treturn VAddress{\n\t\tAddrTypeIP,\n\t\tnet.IP(ip),\n\t\t\"\",\n\t\tport}\n}\n\n\n\nfunc (addr VAddress) IsIPv4() bool {\n\treturn addr.Type == AddrTypeIP && len(addr.IP) == net.IPv4len\n}\n\nfunc (addr VAddress) IsIPv6() bool {\n\treturn addr.Type == AddrTypeIP && len(addr.IP) == net.IPv6len\n}\n\nfunc (addr VAddress) IsDomain() bool {\n\treturn addr.Type == AddrTypeDomain\n}\n\nfunc (addr VAddress) String() string {\n\tvar host string\n\tswitch addr.Type {\n\tcase AddrTypeIP:\n\t\thost = addr.IP.String()\n\t\tif len(addr.IP) == net.IPv6len {\n\t\t\thost = \"[\" + host + \"]\"\n\t\t}\n\n\tcase AddrTypeDomain:\n\t\thost = addr.Domain\n\tdefault:\n\t\tpanic(\"Unknown Address Type \" + strconv.Itoa(int(addr.Type)))\n\t}\n\treturn host + \":\" + strconv.Itoa(int(addr.Port))\n}\n\nfunc DomainAddress(domain string, port uint16) VAddress ", "output": "{\n\treturn VAddress{\n\t\tAddrTypeDomain,\n\t\tnil,\n\t\tdomain,\n\t\tport}\n}"} {"input": "package api\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n)\n\n\ntype Response struct {\n\t*http.Response\n}\n\n\n\n\n\n\n\n\n\nfunc (r *Response) Error() error {\n\tif r.StatusCode >= 200 && r.StatusCode < 400 {\n\t\treturn nil\n\t}\n\n\tvar bodyBuf bytes.Buffer\n\tif _, err := io.Copy(&bodyBuf, r.Body); err != nil {\n\t\treturn err\n\t}\n\n\tvar resp ErrorResponse\n\tdec := json.NewDecoder(bytes.NewReader(bodyBuf.Bytes()))\n\tif err := dec.Decode(&resp); err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"Error making API request.\\n\\n\"+\n\t\t\t\t\"URL: %s %s\\n\"+\n\t\t\t\t\"Code: %d. Raw Message:\\n\\n%s\",\n\t\t\tr.Request.Method, r.Request.URL.String(),\n\t\t\tr.StatusCode, bodyBuf.String())\n\t}\n\n\tvar errBody bytes.Buffer\n\terrBody.WriteString(fmt.Sprintf(\n\t\t\"Error making API request.\\n\\n\"+\n\t\t\t\"URL: %s %s\\n\"+\n\t\t\t\"Code: %d. Errors:\\n\\n\",\n\t\tr.Request.Method, r.Request.URL.String(),\n\t\tr.StatusCode))\n\tfor _, err := range resp.Errors {\n\t\terrBody.WriteString(fmt.Sprintf(\"* %s\", err))\n\t}\n\n\treturn fmt.Errorf(errBody.String())\n}\n\n\n\ntype ErrorResponse struct {\n\tErrors []string\n}\n\nfunc (r *Response) DecodeJSON(out interface{}) error ", "output": "{\n\tdec := json.NewDecoder(r.Body)\n\treturn dec.Decode(out)\n}"} {"input": "package system \n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\nfunc MkdirAllWithACL(path string, perm os.FileMode, sddl string) error {\n\treturn os.MkdirAll(path, perm)\n}\n\n\n\nfunc MkdirAll(path string, perm os.FileMode) error {\n\treturn os.MkdirAll(path, perm)\n}\n\n\nfunc IsAbs(path string) bool {\n\treturn filepath.IsAbs(path)\n}\n\n\n\n\n\n\n\n\n\nfunc CreateSequential(name string) (*os.File, error) {\n\treturn os.Create(name)\n}\n\n\n\n\n\nfunc OpenSequential(name string) (*os.File, error) {\n\treturn os.Open(name)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc TempFileSequential(dir, prefix string) (f *os.File, err error) {\n\treturn ioutil.TempFile(dir, prefix)\n}\n\nfunc OpenFileSequential(name string, flag int, perm os.FileMode) (*os.File, error) ", "output": "{\n\treturn os.OpenFile(name, flag, perm)\n}"} {"input": "package lua\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/raggaer/castro/app/util\"\n\t\"github.com/yuin/gopher-lua\"\n)\n\n\n\n\n\nfunc SetI18nUserData(luaState *lua.LState, lang []string) {\n\ti18nMetatable := luaState.GetTypeMetatable(I18nMetaTableName)\n\n\tluaState.SetField(i18nMetatable, \"Language\", StringSliceToTable(lang))\n}\n\n\nfunc GetLanguageIndex(L *lua.LState) int {\n\tlang := L.ToString(2)\n\n\ti := L.ToString(3)\n\n\targs := []interface{}{}\n\tx := 4\n\n\tfor {\n\t\tv := L.Get(x)\n\t\tif v == lua.LNil {\n\t\t\tbreak\n\t\t}\n\t\targs = append(args, ValueToGo(v))\n\t\tx++\n\t}\n\n\tlangFile, ok := util.LanguageFiles.Get(lang)\n\tif ok {\n\t\tlangStr, ok := langFile.Data[i]\n\t\tif ok {\n\t\t\tL.Push(lua.LString(fmt.Sprintf(langStr, args...)))\n\t\t\treturn 1\n\t\t}\n\t}\n\n\tlangFile, ok = util.LanguageFiles.Get(\"default\")\n\n\tlangStr, ok := langFile.Data[i]\n\tif ok {\n\t\tL.Push(lua.LString(fmt.Sprintf(langStr, args...)))\n\t\treturn 1\n\t}\n\n\tL.Push(lua.LNil)\n\treturn 1\n}\n\nfunc SetI18nMetaTable(luaState *lua.LState) ", "output": "{\n\ti18nMetaTable := luaState.NewTypeMetatable(I18nMetaTableName)\n\tluaState.SetGlobal(I18nMetaTableName, i18nMetaTable)\n\n\tluaState.SetFuncs(i18nMetaTable, i18nMethods)\n}"} {"input": "package diffsquares\n\n\n\n\n\nfunc SumOfSquares(n int) int {\n\ts := int(n)\n\ts = 2*s*s*s + 3*s*s + s\n\ts /= 6\n\treturn s\n\n}\n\n\nfunc Difference(n int) int {\n\treturn SquareOfSums(n) - SumOfSquares(n)\n}\n\nfunc SquareOfSums(n int) int ", "output": "{\n\ts := int(n)\n\ts *= s + 1\n\ts /= 2\n\treturn s * s\n}"} {"input": "package types\n\nimport (\n\t\"testing\"\n)\n\nfunc TestGetBuiltin(t *testing.T) {\n\tu := Universe{}\n\tif builtinPkg := u.Package(\"\"); builtinPkg.Has(\"string\") {\n\t\tt.Errorf(\"Expected builtin package to not have builtins until they're asked for explicitly. %#v\", builtinPkg)\n\t}\n\ts := u.Get(Name{\"\", \"string\"})\n\tif s != String {\n\t\tt.Errorf(\"Expected canonical string type.\")\n\t}\n\tif builtinPkg := u.Package(\"\"); !builtinPkg.Has(\"string\") {\n\t\tt.Errorf(\"Expected builtin package to exist and have builtins by default. %#v\", builtinPkg)\n\t}\n\tif builtinPkg := u.Package(\"\"); len(builtinPkg.Types) != 1 {\n\t\tt.Errorf(\"Expected builtin package to not have builtins until they're asked for explicitly. %#v\", builtinPkg)\n\t}\n}\n\n\n\nfunc TestGetMarker(t *testing.T) ", "output": "{\n\tu := Universe{}\n\tn := Name{\"path/to/package\", \"Foo\"}\n\tf := u.Get(n)\n\tif f == nil || f.Name != n {\n\t\tt.Errorf(\"Expected marker type.\")\n\t}\n}"} {"input": "package devices\n\n\n\ntype Device interface {\n\tBind(driver string) error\n\tUnbind() error\n\tCurrentDriver() (string, error)\n\tProbe() error\n\tID() string\n}\n\n\nfunc New(input string) (Device, error) {\n\tswitch {\n\tcase IsPciID.Match([]byte(input)):\n\t\treturn NewDeviceByPciID(input)\n\tcase IsUUID.Match([]byte(input)):\n\t\treturn NewDeviceByVmbusID(input)\n\tdefault:\n\t\treturn NewDeviceByNicName(input)\n\t}\n}\n\n\nfunc NewDeviceByPciID(pciID string) (Device, error) {\n\tdevice, err := GetPciDeviceByPciID(pciID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn device, nil\n}\n\n\nfunc NewDeviceByVmbusID(uuid string) (Device, error) {\n\tdevice, err := GetVmbusDeviceByUUID(uuid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn device, nil\n}\n\n\nfunc NewDeviceByNicName(nicName string) (Device, error) {\n\tdevID, err := GetDeviceID(nicName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdevice, err := newDevice(devID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn device, nil\n}\n\n\n\nfunc newDevice(id string) (Device, error) ", "output": "{\n\tif IsPciID.Match([]byte(id)) {\n\t\treturn GetPciDeviceByPciID(id)\n\t}\n\treturn GetVmbusDeviceByUUID(id)\n}"} {"input": "package fakes\n\nimport \"os\"\n\ntype FileIO struct {\n\tTempFileCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tDir string\n\t\t\tPrefix string\n\t\t}\n\t\tReturns struct {\n\t\t\tFile *os.File\n\t\t\tError error\n\t\t}\n\t}\n\tReadFileCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tFilename string\n\t\t}\n\t\tReturns struct {\n\t\t\tContents []byte\n\t\t\tError error\n\t\t}\n\t}\n\tWriteFileCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tFilename string\n\t\t\tContents []byte\n\t\t}\n\t\tReturns struct {\n\t\t\tError error\n\t\t}\n\t}\n\tStatCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tName string\n\t\t}\n\t\tReturns struct {\n\t\t\tFileInfo os.FileInfo\n\t\t\tError error\n\t\t}\n\t}\n}\n\nfunc (fake *FileIO) TempFile(dir, prefix string) (f *os.File, err error) {\n\tfake.TempFileCall.CallCount++\n\tfake.TempFileCall.Receives.Dir = dir\n\tfake.TempFileCall.Receives.Prefix = prefix\n\treturn fake.TempFileCall.Returns.File, fake.TempFileCall.Returns.Error\n}\n\nfunc (fake *FileIO) ReadFile(filename string) ([]byte, error) {\n\tfake.ReadFileCall.CallCount++\n\tfake.ReadFileCall.Receives.Filename = filename\n\treturn fake.ReadFileCall.Returns.Contents, fake.ReadFileCall.Returns.Error\n}\n\nfunc (fake *FileIO) WriteFile(filename string, contents []byte, perm os.FileMode) error {\n\tfake.WriteFileCall.CallCount++\n\tfake.WriteFileCall.Receives.Filename = filename\n\tfake.WriteFileCall.Receives.Contents = contents\n\treturn fake.WriteFileCall.Returns.Error\n}\n\n\n\nfunc (fake *FileIO) Stat(name string) (os.FileInfo, error) ", "output": "{\n\tfake.StatCall.CallCount++\n\tfake.StatCall.Receives.Name = name\n\treturn fake.StatCall.Returns.FileInfo, fake.StatCall.Returns.Error\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/supergiant/supergiant/pkg/core\"\n\t\"github.com/supergiant/supergiant/pkg/model\"\n)\n\nfunc ListNodes(core *core.Core, user *model.User, r *http.Request) (*Response, error) {\n\treturn handleList(core, r, new(model.Node), new(model.NodeList))\n}\n\nfunc CreateNode(core *core.Core, user *model.User, r *http.Request) (*Response, error) {\n\titem := new(model.Node)\n\tif err := decodeBodyInto(r, item); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := core.Nodes.Create(item); err != nil {\n\t\treturn nil, err\n\t}\n\treturn itemResponse(core, item, http.StatusCreated)\n}\n\n\n\nfunc GetNode(core *core.Core, user *model.User, r *http.Request) (*Response, error) {\n\titem := new(model.Node)\n\tid, err := parseID(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := core.Nodes.Get(id, item); err != nil {\n\t\treturn nil, err\n\t}\n\treturn itemResponse(core, item, http.StatusOK)\n}\n\nfunc DeleteNode(core *core.Core, user *model.User, r *http.Request) (*Response, error) {\n\titem := new(model.Node)\n\tid, err := parseID(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := core.Nodes.Delete(id, item).Async(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn itemResponse(core, item, http.StatusAccepted)\n}\n\nfunc UpdateNode(core *core.Core, user *model.User, r *http.Request) (*Response, error) ", "output": "{\n\tid, err := parseID(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\titem := new(model.Node)\n\tif err := decodeBodyInto(r, item); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := core.Nodes.Update(id, new(model.Node), item); err != nil {\n\t\treturn nil, err\n\t}\n\treturn itemResponse(core, item, http.StatusAccepted)\n}"} {"input": "package arm\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"encoding/base64\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\t\"golang.org/x/crypto/ssh\"\n\t\"time\"\n)\n\nconst (\n\tKeySize = 2048\n)\n\ntype OpenSshKeyPair struct {\n\tprivateKey *rsa.PrivateKey\n\tpublicKey ssh.PublicKey\n}\n\nfunc NewOpenSshKeyPair() (*OpenSshKeyPair, error) {\n\treturn NewOpenSshKeyPairWithSize(KeySize)\n}\n\n\n\nfunc (s *OpenSshKeyPair) AuthorizedKey() string {\n\treturn fmt.Sprintf(\"%s %s packer Azure Deployment%s\",\n\t\ts.publicKey.Type(),\n\t\tbase64.StdEncoding.EncodeToString(s.publicKey.Marshal()),\n\t\ttime.Now().Format(time.RFC3339))\n}\n\nfunc (s *OpenSshKeyPair) PrivateKey() string {\n\tprivateKey := string(pem.EncodeToMemory(&pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(s.privateKey),\n\t}))\n\n\treturn privateKey\n}\n\nfunc NewOpenSshKeyPairWithSize(keySize int) (*OpenSshKeyPair, error) ", "output": "{\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, keySize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpublicKey, err := ssh.NewPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &OpenSshKeyPair{\n\t\tprivateKey: privateKey,\n\t\tpublicKey: publicKey,\n\t}, nil\n}"} {"input": "package file\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\n\n\ntype darwinExFileInfo struct {\n\tos.FileInfo\n\tfid FID\n\tpath string\n}\n\n\n\nfunc timespecToTime(ts syscall.Timespec) time.Time {\n\treturn time.Unix(int64(ts.Sec), int64(ts.Nsec))\n}\n\n\nfunc (fi *darwinExFileInfo) CTime() time.Time {\n\treturn timespecToTime(fi.Sys().(*syscall.Stat_t).Ctimespec)\n}\n\n\nfunc (fi *darwinExFileInfo) ATime() time.Time {\n\treturn timespecToTime(fi.Sys().(*syscall.Stat_t).Atimespec)\n}\n\n\nfunc (fi *darwinExFileInfo) FID() FID {\n\treturn fi.fid\n}\n\n\n\n\n\nfunc systemExFileInfo(fi os.FileInfo, path string) *darwinExFileInfo {\n\tfid := FID{\n\t\tIDLow: fi.Sys().(*syscall.Stat_t).Ino,\n\t}\n\tabsolute, _ := filepath.Abs(path)\n\treturn &darwinExFileInfo{\n\t\tFileInfo: fi,\n\t\tfid: fid,\n\t\tpath: filepath.Clean(absolute),\n\t}\n}\n\nfunc (fi *darwinExFileInfo) Path() string ", "output": "{\n\treturn fi.path\n}"} {"input": "package pflag\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype boolValue bool\n\nfunc newBoolValue(val bool, p *bool) *boolValue {\n\t*p = val\n\treturn (*boolValue)(p)\n}\n\nfunc (b *boolValue) Set(s string) error {\n\tv, err := strconv.ParseBool(s)\n\t*b = boolValue(v)\n\treturn err\n}\n\nfunc (b *boolValue) String() string { return fmt.Sprintf(\"%v\", *b) }\n\n\n\nfunc (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc BoolVar(p *bool, name string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc (f *FlagSet) Bool(name string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, \"\", value, usage)\n\treturn p\n}\n\n\nfunc (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, shorthand, value, usage)\n\treturn p\n}\n\n\n\n\n\n\nfunc BoolP(name, shorthand string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, shorthand, value, usage)\n}\n\nfunc Bool(name string, value bool, usage string) *bool ", "output": "{\n\treturn CommandLine.BoolP(name, \"\", value, usage)\n}"} {"input": "package assertutil\n\n\n\ntype Checker struct {\n\tIsNil func(obtained interface{})\n\tFailNow func()\n}\n\n\n\n\nfunc (c *Checker) failNow() {\n\tc.FailNow()\n}\n\n\nfunc (c *Checker) AssertNil(obtained interface{}) {\n\tif c.IsNil == nil {\n\t\tc.failNow()\n\t\treturn\n\t}\n\tc.IsNil(obtained)\n}\n\nfunc NewChecker(failNow func()) *Checker ", "output": "{\n\treturn &Checker{\n\t\tFailNow: failNow,\n\t}\n}"} {"input": "package validation\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\nfunc ExampleErrIfNotOSBName() {\n\tfmt.Println(\"Good is nil:\", ErrIfNotOSBName(\"google-storage\", \"my-field\") == nil)\n\tfmt.Println(\"Bad:\", ErrIfNotOSBName(\"google storage\", \"my-field\"))\n\n}\n\nfunc ExampleErrIfNotJSONSchemaType() {\n\tfmt.Println(\"Good is nil:\", ErrIfNotJSONSchemaType(\"string\", \"my-field\") == nil)\n\tfmt.Println(\"Bad:\", ErrIfNotJSONSchemaType(\"str\", \"my-field\"))\n\n}\n\nfunc ExampleErrIfNotHCL() {\n\tfmt.Println(\"Good HCL is nil:\", ErrIfNotHCL(`provider \"google\" {\n\t\tcredentials = \"${file(\"account.json\")}\"\n\t\tproject = \"my-project-id\"\n\t\tregion = \"us-central1\"\n\t}`, \"my-field\") == nil)\n\n\tfmt.Println(\"Good JSON is nil:\", ErrIfNotHCL(`{\"a\":42, \"s\":\"foo\"}`, \"my-field\") == nil)\n\n\tfmt.Println(\"Bad:\", ErrIfNotHCL(\"google storage\", \"my-field\"))\n\n}\n\n\n\nfunc ExampleErrIfNotJSON() {\n\tfmt.Println(\"Good is nil:\", ErrIfNotJSON(json.RawMessage(\"{}\"), \"my-field\") == nil)\n\tfmt.Println(\"Bad:\", ErrIfNotJSON(json.RawMessage(\"\"), \"my-field\"))\n\n}\n\nfunc ExampleErrIfNotTerraformIdentifier() ", "output": "{\n\tfmt.Println(\"Good is nil:\", ErrIfNotTerraformIdentifier(\"good_id\", \"my-field\") == nil)\n\tfmt.Println(\"Bad:\", ErrIfNotTerraformIdentifier(\"bad id\", \"my-field\"))\n\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"bytes\"\n)\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\nfunc (n *ListNode) String() string {\n\tvar buf bytes.Buffer\n\tfor nn := n; nn != nil; nn = nn.Next {\n\t\tbuf.WriteString(fmt.Sprintf(\"[%d]\", nn.Val))\n\t}\n\treturn buf.String()\n}\n\n\n\nfunc doReverse(head, tail *ListNode) (*ListNode, *ListNode) {\n\tif head == nil || tail == nil || head == tail {\n\t\treturn tail, head\n\t}\n\tpre, cur, next := head, head.Next, head.Next.Next\n\tfor {\n\t\tcur.Next = pre\n\t\tif cur == tail {\n\t\t\tbreak\n\t\t}\n\t\tpre = cur\n\t\tcur = next\n\t\tnext = next.Next\n\t}\n\thead.Next = nil\n\treturn tail, head\n}\n\nfunc findSubList(head *ListNode, m, n int) (mNode, nNode *ListNode) {\n\tif head == nil {\n\t\treturn nil, nil\n\t}\n\tmNode, nNode = head, head\n\tfor i := 1; i < n; i++ {\n\t\tif i < m {\n\t\t\tmNode = mNode.Next\n\t\t\tif mNode == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tnNode = nNode.Next\n\t\tif nNode == nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc main() {\n\th := &ListNode{1, &ListNode{2, &ListNode{3, &ListNode{4, &ListNode{5, nil}}}}}\n\tfmt.Println(h)\n\tfmt.Println(reverseBetween(h, 3, 4))\n}\n\nfunc reverseBetween(head *ListNode, m int, n int) *ListNode ", "output": "{\n\tif head == nil || head.Next == nil || m <= 0 || n <= 0 || m >= n {\n\t\treturn head\n\t}\n\tmNode, nNode := findSubList(head, m, n)\n\tif mNode == nil || nNode == nil || mNode == nNode {\n\t\treturn head\n\t}\n\tnextSubNode := nNode.Next\n\th, t := doReverse(mNode, nNode)\n\tt.Next = nextSubNode\n\tif t == head {\n\t\treturn h\n\t}\n\n\tfor n := head; n != nil; n = n.Next {\n\t\tif n.Next == t {\n\t\t\tn.Next = h\n\t\t\tbreak\n\t\t}\n\t}\n\treturn head\n}"} {"input": "package controllers\n\nimport (\n\t\"html/template\"\n\t\"net/http\"\n)\n\nfunc Error404(rw http.ResponseWriter, req *http.Request) {\n\tt, _ := template.ParseFiles(\"views/404.html\")\n\tt.Execute(rw, nil)\n}\n\n\n\nfunc Error501(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\tt, _ := template.ParseFiles(\"views/501.html\")\n\tt.Execute(rw, nil)\n}"} {"input": "package geo\n\nimport (\n\t\"image/jpeg\"\n\t\"image/png\"\n\t\"io\"\n\n\t\"github.com/mmcloughlin/globe\"\n)\n\ntype Sphere struct {\n\t*globe.Globe\n}\n\nfunc NewSphere() *Sphere {\n\ts := &Sphere{globe.New()}\n\treturn s\n}\n\n\n\nfunc (s *Sphere) EncodeJPEG(size int, quality int, writer io.Writer) error {\n\timage := s.Image(size)\n\treturn jpeg.Encode(writer, image, &jpeg.Options{Quality: quality})\n}\n\nfunc (s *Sphere) EncodePNG(size int, writer io.Writer) error ", "output": "{\n\timage := s.Image(size)\n\treturn png.Encode(writer, image)\n}"} {"input": "package vanity\n\nimport (\n\t\"github.com/gogo/protobuf/gogoproto\"\n\t\"github.com/gogo/protobuf/proto\"\n\tdescriptor \"github.com/gogo/protobuf/protoc-gen-gogo/descriptor\"\n)\n\nfunc EnumHasBoolExtension(enum *descriptor.EnumDescriptorProto, extension *proto.ExtensionDesc) bool {\n\tif enum.Options == nil {\n\t\treturn false\n\t}\n\tvalue, err := proto.GetExtension(enum.Options, extension)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif value == nil {\n\t\treturn false\n\t}\n\tif value.(*bool) == nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc SetBoolEnumOption(extension *proto.ExtensionDesc, value bool) func(enum *descriptor.EnumDescriptorProto) {\n\treturn func(enum *descriptor.EnumDescriptorProto) {\n\t\tif EnumHasBoolExtension(enum, extension) {\n\t\t\treturn\n\t\t}\n\t\tif enum.Options == nil {\n\t\t\tenum.Options = &descriptor.EnumOptions{}\n\t\t}\n\t\tif err := proto.SetExtension(enum.Options, extension, &value); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\nfunc TurnOffGoEnumPrefix(enum *descriptor.EnumDescriptorProto) {\n\tSetBoolEnumOption(gogoproto.E_GoprotoEnumPrefix, false)(enum)\n}\n\nfunc TurnOffGoEnumStringer(enum *descriptor.EnumDescriptorProto) {\n\tSetBoolEnumOption(gogoproto.E_GoprotoEnumStringer, false)(enum)\n}\n\n\n\nfunc TurnOnEnumStringer(enum *descriptor.EnumDescriptorProto) ", "output": "{\n\tSetBoolEnumOption(gogoproto.E_EnumStringer, true)(enum)\n}"} {"input": "package main\n\nimport \"testing\"\n\nfunc BenchmarkP041A(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tp041A()\n\t}\n}\n\nfunc BenchmarkP041B(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tp041B()\n\t}\n}\n\n\n\nfunc ExampleP041() ", "output": "{\n\tmain()\n\n}"} {"input": "package maker\n\nimport \"cf/models\"\n\nvar routeSummaryGuid func() string\n\n\n\nfunc NewRouteSummary(overrides Overrides) (routeSummary models.RouteSummary) {\n\trouteSummary.Guid = routeSummaryGuid()\n\trouteSummary.Host = \"route-host\"\n\n\tif overrides.Has(\"guid\") {\n\t\trouteSummary.Guid = overrides.Get(\"guid\").(string)\n\t}\n\n\tif overrides.Has(\"host\") {\n\t\trouteSummary.Host = overrides.Get(\"host\").(string)\n\t}\n\n\treturn\n}\n\nfunc init() ", "output": "{\n\trouteSummaryGuid = guidGenerator(\"route-summary\")\n}"} {"input": "package private\n\nimport (\n\t\"net/http\"\n\n\t\"code.gitea.io/gitea/modules/context\"\n\t\"code.gitea.io/gitea/modules/graceful\"\n)\n\n\n\n\n\nfunc Shutdown(ctx *context.PrivateContext) {\n\tgraceful.GetManager().DoGracefulShutdown()\n\tctx.PlainText(http.StatusOK, \"success\")\n}\n\nfunc Restart(ctx *context.PrivateContext) ", "output": "{\n\tgraceful.GetManager().DoGracefulRestart()\n\tctx.PlainText(http.StatusOK, \"success\")\n}"} {"input": "package hcloud\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hashicorp/packer/packer\"\n)\n\nfunc TestArtifact_Impl(t *testing.T) {\n\tvar _ packer.Artifact = (*Artifact)(nil)\n}\n\nfunc TestArtifactId(t *testing.T) {\n\tgeneratedData := make(map[string]interface{})\n\ta := &Artifact{\"packer-foobar\", 42, nil, generatedData}\n\texpected := \"42\"\n\n\tif a.Id() != expected {\n\t\tt.Fatalf(\"artifact ID should match: %v\", expected)\n\t}\n}\n\n\n\nfunc TestArtifactState_StateData(t *testing.T) {\n\texpectedData := \"this is the data\"\n\tartifact := &Artifact{\n\t\tStateData: map[string]interface{}{\"state_data\": expectedData},\n\t}\n\n\tresult := artifact.State(\"state_data\")\n\tif result != expectedData {\n\t\tt.Fatalf(\"Bad: State data was %s instead of %s\", result, expectedData)\n\t}\n\n\tresult = artifact.State(\"invalid_key\")\n\tif result != nil {\n\t\tt.Fatalf(\"Bad: State should be nil for invalid state data name\")\n\t}\n\n\tartifact = &Artifact{}\n\tresult = artifact.State(\"key\")\n\tif result != nil {\n\t\tt.Fatalf(\"Bad: State should be nil for nil StateData\")\n\t}\n}\n\nfunc TestArtifactString(t *testing.T) ", "output": "{\n\tgeneratedData := make(map[string]interface{})\n\ta := &Artifact{\"packer-foobar\", 42, nil, generatedData}\n\texpected := \"A snapshot was created: 'packer-foobar' (ID: 42)\"\n\n\tif a.String() != expected {\n\t\tt.Fatalf(\"artifact string should match: %v\", expected)\n\t}\n}"} {"input": "package logmon\n\nimport (\n\t\"context\"\n\n\t\"github.com/hashicorp/nomad/client/logmon/proto\"\n)\n\ntype logmonClient struct {\n\tclient proto.LogMonClient\n}\n\n\n\nfunc (c *logmonClient) Stop() error {\n\treq := &proto.StopRequest{}\n\t_, err := c.client.Stop(context.Background(), req)\n\treturn err\n}\n\nfunc (c *logmonClient) Start(cfg *LogConfig) error ", "output": "{\n\treq := &proto.StartRequest{\n\t\tLogDir: cfg.LogDir,\n\t\tStdoutFileName: cfg.StdoutLogFile,\n\t\tStderrFileName: cfg.StderrLogFile,\n\t\tMaxFiles: uint32(cfg.MaxFiles),\n\t\tMaxFileSizeMb: uint32(cfg.MaxFileSizeMB),\n\t\tStdoutFifo: cfg.StdoutFifo,\n\t\tStderrFifo: cfg.StderrFifo,\n\t}\n\t_, err := c.client.Start(context.Background(), req)\n\treturn err\n}"} {"input": "package openstack\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/go-ini/ini\"\n\t\"github.com/rancher/types/apis/management.cattle.io/v3\"\n)\n\nconst (\n\tOpenstackCloudProviderName = \"openstack\"\n)\n\ntype CloudProvider struct {\n\tConfig *v3.OpenstackCloudProvider\n\tName string\n}\n\n\n\nfunc (p *CloudProvider) Init(cloudProviderConfig v3.CloudProvider) error {\n\tif cloudProviderConfig.OpenstackCloudProvider == nil {\n\t\treturn fmt.Errorf(\"Openstack Cloud Provider Config is empty\")\n\t}\n\tp.Name = OpenstackCloudProviderName\n\tif cloudProviderConfig.Name != \"\" {\n\t\tp.Name = cloudProviderConfig.Name\n\t}\n\tp.Config = cloudProviderConfig.OpenstackCloudProvider\n\treturn nil\n}\n\nfunc (p *CloudProvider) GetName() string {\n\treturn p.Name\n}\n\nfunc (p *CloudProvider) GenerateCloudConfigFile() (string, error) {\n\tbuf := new(bytes.Buffer)\n\tcloudConfig, _ := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: true}, []byte(\"\"))\n\tif err := ini.ReflectFrom(cloudConfig, p.Config); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to parse Openstack cloud config\")\n\t}\n\tif _, err := cloudConfig.WriteTo(buf); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn buf.String(), nil\n}\n\nfunc GetInstance() *CloudProvider ", "output": "{\n\treturn &CloudProvider{}\n}"} {"input": "package chunkstore\n\nimport (\n\t\"errors\"\n\n\t. \"github.com/huin/chunkymonkey/types\"\n)\n\n\n\n\n\ntype MultiStore struct {\n\treadStores []IChunkStore\n\twriteStore IChunkStore\n}\n\n\n\nfunc (s *MultiStore) ReadChunk(chunkLoc ChunkXz) (reader IChunkReader, err error) {\n\tfor _, store := range s.readStores {\n\t\tresult := <-store.ReadChunk(chunkLoc)\n\n\t\tif result.Err == nil {\n\t\t\treturn result.Reader, result.Err\n\t\t} else {\n\t\t\tif _, ok := result.Err.(NoSuchChunkError); ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, result.Err\n\t\t}\n\t}\n\n\treturn nil, NoSuchChunkError(false)\n}\n\nfunc (s *MultiStore) SupportsWrite() bool {\n\treturn s.writeStore != nil && s.writeStore.SupportsWrite()\n}\n\nfunc (s *MultiStore) Writer() IChunkWriter {\n\tif s.writeStore != nil {\n\t\treturn s.writeStore.Writer()\n\t}\n\treturn nil\n}\n\nfunc (s *MultiStore) WriteChunk(writer IChunkWriter) error {\n\tif s.writeStore == nil {\n\t\treturn errors.New(\"writes not supported\")\n\t}\n\ts.writeStore.WriteChunk(writer)\n\treturn nil\n}\n\nfunc NewMultiStore(readStores []IChunkStore, writeStore IChunkStore) *MultiStore ", "output": "{\n\ts := &MultiStore{\n\t\treadStores: readStores,\n\t\twriteStore: writeStore,\n\t}\n\n\treturn s\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/service/ssm\"\n\n\t\"gopkg.in/alecthomas/kingpin.v2\"\n)\n\ntype readCommand struct {\n\tName string\n\tDecrypt bool\n}\n\nfunc configureReadCommand(app *kingpin.Application) {\n\trc := &readCommand{}\n\tread := app.Command(\"read\", \"Read secret from parameter store\").Action(rc.runRead)\n\tread.Arg(\"name\", \"Secret name\").StringVar(&rc.Name)\n\tread.Flag(\"decrypt\", \"Return decrypted value\").BoolVar(&rc.Decrypt)\n}\n\n\n\nfunc (rc *readCommand) runRead(ctx *kingpin.ParseContext) error ", "output": "{\n\tconfig := aws.NewConfig().WithRegion(*region)\n\tsess, err := newSession(config, mfaSerial, roleArn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tssmClient := ssm.New(sess, config)\n\n\tgpInput := &ssm.GetParameterInput{\n\t\tName: &rc.Name,\n\t\tWithDecryption: &rc.Decrypt,\n\t}\n\tgpOutput, err := ssmClient.GetParameter(gpInput)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(*gpOutput.Parameter.Value)\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/robfig/cron\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\nvar (\n\tpid = 0\n\n\thttpPorts = getEnv(\"HTTP_PORTS\", \"80 8080\")\n\ttlsPorts = getEnv(\"TLS_PORTS\", \"443 8443\")\n\n\tswarmRouterPort = getEnv(\"SWARM_ROUTER_PORT\", \"35353\")\n\n\tdefaultBackendPorts = getEnv(\"DEFAULT_BACKEND_PORTS\", \"80 443 8000 8080 8443 9000\")\n\n\toverrideBackendPorts = getEnv(\"OVERRIDE_BACKEND_PORTS\", \"\")\n\n\tbackendsVerifyTLS = getEnv(\"BACKENDS_VERIFY_TLS\", \"\")\n)\n\n\n\nfunc haproxy(exit chan bool) {\n\tcmd := exec.Command(os.Args[1], os.Args[2:]...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Start(); err != nil {\n\t\tlog.Fatalf(\"Start error: %s\", err.Error())\n\t}\n\tpid = cmd.Process.Pid\n\tlog.Printf(\"Started haproxy master process with pid: %d\", pid)\n\terr := cmd.Wait()\n\tlog.Printf(\"Exit error: %s\", err.Error())\n\texit <- true\n}\n\nfunc init() {\n\texecuteTemplate(\"/usr/local/etc/haproxy/haproxy.tmpl\", \"/usr/local/etc/haproxy/haproxy.cfg\")\n}\n\nfunc main() {\n\tc := cron.New()\n\tc.AddFunc(\"@daily\", reload)\n\tc.Start()\n\texit := make(chan bool, 1)\n\tgo router(exit, swarmRouterPort)\n\tgo haproxy(exit)\n\t<-exit\n}\n\nfunc getEnv(key, defaultValue string) string ", "output": "{\n\tvalue, exists := os.LookupEnv(key)\n\tif !exists {\n\t\tvalue = defaultValue\n\t\tos.Setenv(key, defaultValue)\n\t}\n\treturn strings.TrimSpace(value)\n}"} {"input": "package icon\n\nimport (\n\t\"github.com/sacloud/libsacloud/v2/helper/service\"\n\t\"github.com/sacloud/libsacloud/v2/helper/validate\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\ntype UpdateRequest struct {\n\tID types.ID `request:\"-\" validate:\"required\"`\n\n\tName *string `request:\",omitempty\" validate:\"omitempty,min=1\"`\n\tTags *types.Tags `request:\",omitempty\"`\n}\n\n\n\nfunc (req *UpdateRequest) ToRequestParameter(current *sacloud.Icon) (*sacloud.IconUpdateRequest, error) {\n\tr := &sacloud.IconUpdateRequest{}\n\tif err := service.RequestConvertTo(current, r); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := service.RequestConvertTo(req, r); err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}\n\nfunc (req *UpdateRequest) Validate() error ", "output": "{\n\treturn validate.Struct(req)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"sort\"\n)\n\nfunc partition(a sort.Interface, first int, last int, pivotIndex int) int {\n\ta.Swap(first, pivotIndex) \n\tleft := first + 1\n\tright := last\n\tfor left <= right {\n\t\tfor left <= last && a.Less(left, first) {\n\t\t\tleft++\n\t\t}\n\t\tfor right >= first && a.Less(first, right) {\n\t\t\tright--\n\t\t}\n\t\tif left <= right {\n\t\t\ta.Swap(left, right)\n\t\t\tleft++\n\t\t\tright--\n\t\t}\n\t}\n\ta.Swap(first, right) \n\treturn right\n}\n\nfunc quicksortHelper(a sort.Interface, first int, last int) {\n\tif first >= last {\n\t\treturn\n\t}\n\tpivotIndex := partition(a, first, last, rand.Intn(last-first+1)+first)\n\tquicksortHelper(a, first, pivotIndex-1)\n\tquicksortHelper(a, pivotIndex+1, last)\n}\n\n\n\nfunc main() {\n\ta := []int{1, 3, 5, 7, 9, 8, 6, 4, 2}\n\tfmt.Printf(\"Unsorted: %v\\n\", a)\n\tquicksort(sort.IntSlice(a))\n\tfmt.Printf(\"Sorted: %v\\n\", a)\n\tb := []string{\"Emil\", \"Peg\", \"Helen\", \"Juergen\", \"David\", \"Rick\", \"Barb\", \"Mike\", \"Tom\"}\n\tfmt.Printf(\"Unsorted: %v\\n\", b)\n\tquicksort(sort.StringSlice(b))\n\tfmt.Printf(\"Sorted: %v\\n\", b)\n}\n\nfunc quicksort(a sort.Interface) ", "output": "{\n\tquicksortHelper(a, 0, a.Len()-1)\n}"} {"input": "package job\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/gapid/core/data/search\"\n\t\"github.com/google/gapid/core/event\"\n\t\"github.com/google/gapid/core/net/grpcutil\"\n\t\"github.com/google/gapid/core/os/device\"\n\t\"google.golang.org/grpc\"\n)\n\ntype remote struct {\n\tclient ServiceClient\n}\n\n\n\n\n\n\nfunc (m *remote) SearchDevices(ctx context.Context, query *search.Query, handler DeviceHandler) error {\n\tstream, err := m.client.SearchDevices(ctx, query)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn event.Feed(ctx, event.AsHandler(ctx, handler), grpcutil.ToProducer(stream))\n}\n\n\n\nfunc (m *remote) SearchWorkers(ctx context.Context, query *search.Query, handler WorkerHandler) error {\n\tstream, err := m.client.SearchWorkers(ctx, query)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn event.Feed(ctx, event.AsHandler(ctx, handler), grpcutil.ToProducer(stream))\n}\n\n\n\nfunc (m *remote) GetWorker(ctx context.Context, host *device.Instance, target *device.Instance, op Operation) (*Worker, error) {\n\trequest := &GetWorkerRequest{Host: host, Target: target, Operation: op}\n\tresponse, err := m.client.GetWorker(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn response.Worker, nil\n}\n\nfunc NewRemote(ctx context.Context, conn *grpc.ClientConn) Manager ", "output": "{\n\treturn &remote{client: NewServiceClient(conn)}\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1alpha1 \"k8s.io/kops/pkg/client/clientset_generated/clientset/typed/kops/v1alpha1\"\n)\n\ntype FakeKopsV1alpha1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeKopsV1alpha1) Clusters(namespace string) v1alpha1.ClusterInterface {\n\treturn &FakeClusters{c, namespace}\n}\n\n\n\nfunc (c *FakeKopsV1alpha1) SSHCredentials(namespace string) v1alpha1.SSHCredentialInterface {\n\treturn &FakeSSHCredentials{c, namespace}\n}\n\n\n\nfunc (c *FakeKopsV1alpha1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeKopsV1alpha1) InstanceGroups(namespace string) v1alpha1.InstanceGroupInterface ", "output": "{\n\treturn &FakeInstanceGroups{c, namespace}\n}"} {"input": "package sqlite3\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/gonuts/binary\"\n)\n\nfunc min(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}\n\n\n\nfunc varint(data []byte) (int64, int) {\n\tvar val uint64\n\tfor i := 0; i < 8; i++ {\n\t\tif i > len(data)-1 {\n\t\t\treturn 0, 0\n\t\t}\n\t\tval = (val << 7) | uint64(data[i]&0x7f)\n\t\tif data[i] < 0x80 {\n\t\t\treturn int64(val), i + 1\n\t\t}\n\t}\n\tif len(data) < 9 {\n\t\treturn 0, 0\n\t}\n\treturn int64((val << 8) | uint64(data[8])), 9\n}\n\nfunc unmarshal(buf []byte, ptr interface{}) (int64, error) ", "output": "{\n\tr := bytes.NewReader(buf)\n\tmax := r.Len()\n\tdec := binary.NewDecoder(r)\n\tdec.Order = binary.BigEndian\n\terr := dec.Decode(ptr)\n\tn := max - r.Len()\n\treturn int64(n), err\n}"} {"input": "package ctrl\n\nimport (\n\t\"wb/cs\"\n\t\"wb/ii\"\n\t\"wb/om\"\n)\n\ntype ItemController struct {\n\tItemBaseController\n\tCtxItemInfo ii.ItemInfo\n}\n\n\nfunc (this *ItemController) Get() {\n\tret, res := this.GetItem(this.CtxItemInfo)\n\tthis.SendJson(cs.JsonResult{ret, res})\n}\nfunc (this *ItemController) Add() {\n\tthis.AddItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) Adds() {\n\tthis.AddItems(this.CtxItemInfo)\n}\nfunc (this *ItemController) AddWithSub() {\n\tthis.AddItemWithSub(this.CtxItemInfo)\n}\nfunc (this *ItemController) Update() {\n\tthis.UpdateItem(this.CtxItemInfo)\n}\nfunc (ic *ItemController) UpdateWithSub() {\n\tic.UpdateItemWithSub(ic.CtxItemInfo)\n}\nfunc (this *ItemController) UpdateWithAddSub() {\n\tthis.UpdateItemWithAddSub(this.CtxItemInfo)\n}\n\n\n\n\nfunc (this *ItemController) Delete() {\n\tthis.DeleteItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) Upload() {\n\tthis.UploadItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) Autocomplete() {\n\tthis.AutocompleteItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) UiList() {\n\tthis.UiListItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) UiAdd() {\n\tthis.UiAddItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) UiUpdate() {\n\tthis.UiUpdateItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) UiView() {\n\tthis.UiViewItem(this.CtxItemInfo)\n}\nfunc (this *ItemController) UiAttachment() {\n\tthis.UiAttachmentItem(this.CtxItemInfo)\n}\n\nfunc (this *ItemController) List() ", "output": "{\n\ttableResult := this.GetTableList(this.CtxItemInfo, om.Params{})\n\tthis.SendJson(&tableResult)\n}"} {"input": "package http\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n)\n\n\n\nfunc defaultBackoff(base, max float64, retries int) time.Duration {\n\treturn backoff(base, max, .2, 1.6, retries)\n}\n\n\n\n\n\nfunc backoff(base, max, jitter, factor float64, retries int) time.Duration ", "output": "{\n\tif retries == 0 {\n\t\treturn 0\n\t}\n\n\tbackoff, max := float64(base), float64(max)\n\tfor backoff < max && retries > 0 {\n\t\tbackoff *= factor\n\t\tretries--\n\t}\n\tif backoff > max {\n\t\tbackoff = max\n\t}\n\n\tbackoff *= 1 + jitter*(rand.Float64()*2-1)\n\tif backoff < 0 {\n\t\treturn 0\n\t}\n\n\treturn time.Duration(backoff)\n}"} {"input": "package gonfler\n\nimport (\n\t\"archive/tar\"\n\t\"os\"\n)\n\ntype TarArchive struct {\n\thandle *tar.Reader\n\tfile *os.File\n}\n\n\n\nfunc (archive TarArchive) Volumes() VolumeIterator {\n\tvar next func() VolumeIterator\n\tnext = func() VolumeIterator {\n\t\theader, err := archive.handle.Next()\n\t\tif err != nil {\n\t\t\treturn VolumeIterator{nil, nil}\n\t\t} else {\n\t\t\treturn VolumeIterator{\n\t\t\t\tvolume: &Volume{archive.handle, header.Name},\n\t\t\t\tnext: next,\n\t\t\t}\n\t\t}\n\t}\n\treturn next()\n}\n\nfunc openTar(name string) (Archive, error) {\n\tfile, e := os.Open(name)\n\tif file != nil {\n\t\treturn TarArchive{tar.NewReader(file), file}, nil\n\t} else {\n\t\treturn nil, e\n\t}\n}\n\nfunc (archive TarArchive) Close() error ", "output": "{\n\treturn archive.file.Close()\n}"} {"input": "package request\n\nimport (\n \"bytes\"\n \"encoding/json\"\n \"io/ioutil\"\n)\n\n\ntype Handlers struct {\n RequestHandler func(*Request, *interface{}) error\n ResponseHandler func(*Request, *interface{}) error\n}\n\n\nfunc RequestHandler(request *Request, input *interface{}) error {\n jsonstr, err := json.Marshal(&input)\n request.HTTPRequest.Body = ioutil.NopCloser(bytes.NewBuffer(jsonstr))\n return err\n}\n\n\n\n\n\n\nfunc ListResponseHandler(request *Request, output *interface{}) error {\n var objmap map[string]*json.RawMessage\n err := json.Unmarshal(request.Body, &objmap)\n if err != nil {\n return err\n }\n return json.Unmarshal(*objmap[\"results\"], &output)\n}\n\nfunc ResponseHandler(request *Request, output *interface{}) error ", "output": "{\n return json.Unmarshal(request.Body, &output)\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\nvar manifestCmd = &cobra.Command{\n\tUse: \"manifest [subcommand]\",\n\tShort: \"See subcommands\",\n\tLong: \"See subcommands. Run with --help to list the available commands.\",\n}\n\n\n\nfunc init() ", "output": "{\n\tRootCmd.AddCommand(manifestCmd)\n}"} {"input": "package rfc\n\n\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/util\"\n)\n\ntype extDuplicateExtension struct{}\n\n\n\nfunc init() {\n\tlint.RegisterLint(&lint.Lint{\n\t\tName: \"e_ext_duplicate_extension\",\n\t\tDescription: \"A certificate MUST NOT include more than one instance of a particular extension\",\n\t\tCitation: \"RFC 5280: 4.2\",\n\t\tSource: lint.RFC5280,\n\t\tEffectiveDate: util.RFC2459Date,\n\t\tLint: &extDuplicateExtension{},\n\t})\n}\n\n\n\nfunc (l *extDuplicateExtension) CheckApplies(cert *x509.Certificate) bool {\n\treturn cert.Version == 3\n}\n\nfunc (l *extDuplicateExtension) Execute(cert *x509.Certificate) *lint.LintResult {\n\textensionOIDs := make(map[string]bool)\n\tduplicateOIDs := make(map[string]bool)\n\n\tfor _, ext := range cert.Extensions {\n\t\toid := ext.Id.String()\n\n\t\tif alreadySeen := extensionOIDs[oid]; alreadySeen {\n\t\t\tduplicateOIDs[oid] = true\n\t\t} else {\n\t\t\textensionOIDs[oid] = true\n\t\t}\n\t}\n\n\tif len(duplicateOIDs) == 0 {\n\t\treturn &lint.LintResult{Status: lint.Pass}\n\t}\n\n\tvar duplicateOIDsList []string\n\tfor oid := range duplicateOIDs {\n\t\tduplicateOIDsList = append(duplicateOIDsList, oid)\n\t}\n\n\treturn &lint.LintResult{\n\t\tStatus: lint.Error,\n\t\tDetails: fmt.Sprintf(\n\t\t\t\"The following extensions are duplicated: %s\",\n\t\t\tstrings.Join(duplicateOIDsList, \", \")),\n\t}\n}\n\nfunc (l *extDuplicateExtension) Initialize() error ", "output": "{\n\treturn nil\n}"} {"input": "package cgzip\n\n\nimport \"C\"\n\nimport (\n\t\"hash\"\n\t\"unsafe\"\n)\n\ntype adler32Hash struct {\n\tadler C.uLong\n}\n\n\n\nfunc NewAdler32() hash.Hash32 {\n\ta := &adler32Hash{}\n\ta.Reset()\n\treturn a\n}\n\n\nfunc (a *adler32Hash) Write(p []byte) (n int, err error) {\n\tif len(p) > 0 {\n\t\ta.adler = C.adler32(a.adler, (*C.Bytef)(unsafe.Pointer(&p[0])), (C.uInt)(len(p)))\n\t}\n\treturn len(p), nil\n}\n\n\nfunc (a *adler32Hash) Sum(b []byte) []byte {\n\ts := a.Sum32()\n\tb = append(b, byte(s>>24))\n\tb = append(b, byte(s>>16))\n\tb = append(b, byte(s>>8))\n\tb = append(b, byte(s))\n\treturn b\n}\n\nfunc (a *adler32Hash) Reset() {\n\ta.adler = C.adler32(0, (*C.Bytef)(unsafe.Pointer(nil)), 0)\n}\n\n\n\nfunc (a *adler32Hash) BlockSize() int {\n\treturn 1\n}\n\n\nfunc (a *adler32Hash) Sum32() uint32 {\n\treturn uint32(a.adler)\n}\n\n\n\n\n\n\n\nfunc Adler32Combine(adler1, adler2 uint32, len2 int) uint32 {\n\treturn uint32(C.adler32_combine(C.uLong(adler1), C.uLong(adler2), C.z_off_t(len2)))\n}\n\nfunc (a *adler32Hash) Size() int ", "output": "{\n\treturn 4\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\n\n\n\n\ntype ConsoleHistory struct {\n\n\tAvailabilityDomain *string `mandatory:\"true\" json:\"availabilityDomain\"`\n\n\tCompartmentId *string `mandatory:\"true\" json:\"compartmentId\"`\n\n\tId *string `mandatory:\"true\" json:\"id\"`\n\n\tInstanceId *string `mandatory:\"true\" json:\"instanceId\"`\n\n\tLifecycleState ConsoleHistoryLifecycleStateEnum `mandatory:\"true\" json:\"lifecycleState\"`\n\n\tTimeCreated *common.SDKTime `mandatory:\"true\" json:\"timeCreated\"`\n\n\tDefinedTags map[string]map[string]interface{} `mandatory:\"false\" json:\"definedTags\"`\n\n\tDisplayName *string `mandatory:\"false\" json:\"displayName\"`\n\n\tFreeformTags map[string]string `mandatory:\"false\" json:\"freeformTags\"`\n}\n\nfunc (m ConsoleHistory) String() string {\n\treturn common.PointerString(m)\n}\n\n\ntype ConsoleHistoryLifecycleStateEnum string\n\n\nconst (\n\tConsoleHistoryLifecycleStateRequested ConsoleHistoryLifecycleStateEnum = \"REQUESTED\"\n\tConsoleHistoryLifecycleStateGettingHistory ConsoleHistoryLifecycleStateEnum = \"GETTING-HISTORY\"\n\tConsoleHistoryLifecycleStateSucceeded ConsoleHistoryLifecycleStateEnum = \"SUCCEEDED\"\n\tConsoleHistoryLifecycleStateFailed ConsoleHistoryLifecycleStateEnum = \"FAILED\"\n)\n\nvar mappingConsoleHistoryLifecycleState = map[string]ConsoleHistoryLifecycleStateEnum{\n\t\"REQUESTED\": ConsoleHistoryLifecycleStateRequested,\n\t\"GETTING-HISTORY\": ConsoleHistoryLifecycleStateGettingHistory,\n\t\"SUCCEEDED\": ConsoleHistoryLifecycleStateSucceeded,\n\t\"FAILED\": ConsoleHistoryLifecycleStateFailed,\n}\n\n\n\n\nfunc GetConsoleHistoryLifecycleStateEnumValues() []ConsoleHistoryLifecycleStateEnum ", "output": "{\n\tvalues := make([]ConsoleHistoryLifecycleStateEnum, 0)\n\tfor _, v := range mappingConsoleHistoryLifecycleState {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package common\n\nimport (\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/names/v4\"\n\n\tapiservererrors \"github.com/juju/juju/apiserver/errors\"\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/state\"\n)\n\n\n\ntype DeadEnsurer struct {\n\tst state.EntityFinder\n\tafterDead func(names.Tag)\n\tgetCanModify GetAuthFunc\n}\n\n\n\n\nfunc NewDeadEnsurer(st state.EntityFinder, afterDead func(names.Tag), getCanModify GetAuthFunc) *DeadEnsurer {\n\treturn &DeadEnsurer{\n\t\tst: st,\n\t\tafterDead: afterDead,\n\t\tgetCanModify: getCanModify,\n\t}\n}\n\nfunc (d *DeadEnsurer) ensureEntityDead(tag names.Tag) error {\n\tentity0, err := d.st.FindEntity(tag)\n\tif err != nil {\n\t\treturn err\n\t}\n\tentity, ok := entity0.(state.EnsureDeader)\n\tif !ok {\n\t\treturn apiservererrors.NotSupportedError(tag, \"ensuring death\")\n\t}\n\tif err := entity.EnsureDead(); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tif d.afterDead != nil {\n\t\td.afterDead(tag)\n\t}\n\treturn nil\n}\n\n\n\n\n\n\nfunc (d *DeadEnsurer) EnsureDead(args params.Entities) (params.ErrorResults, error) ", "output": "{\n\tresult := params.ErrorResults{\n\t\tResults: make([]params.ErrorResult, len(args.Entities)),\n\t}\n\tif len(args.Entities) == 0 {\n\t\treturn result, nil\n\t}\n\tcanModify, err := d.getCanModify()\n\tif err != nil {\n\t\treturn params.ErrorResults{}, errors.Trace(err)\n\t}\n\tfor i, entity := range args.Entities {\n\t\ttag, err := names.ParseTag(entity.Tag)\n\t\tif err != nil {\n\t\t\treturn params.ErrorResults{}, errors.Trace(err)\n\t\t}\n\n\t\terr = apiservererrors.ErrPerm\n\t\tif canModify(tag) {\n\t\t\terr = d.ensureEntityDead(tag)\n\t\t}\n\t\tresult.Results[i].Error = apiservererrors.ServerError(err)\n\t}\n\treturn result, nil\n}"} {"input": "package docker\n\nimport (\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/sirupsen/logrus\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\n\nfunc RemoveContainer(name string) error ", "output": "{\n\n\tlogrus.Debugf(\"Removing container %s\", name)\n\n\tcli, err := getClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx := context.Background()\n\n\tinfo, err := GetContainer(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif info.ContainerJSONBase == nil {\n\t\tlogrus.Warnf(\"Cannot remove %s, does not exists\", name)\n\t\treturn nil\n\t}\n\n\tcontainerID := info.ContainerJSONBase.ID\n\n\terr = cli.ContainerRemove(ctx, containerID, types.ContainerRemoveOptions{\n\t\tForce: true,\n\t})\n\tif err != nil {\n\t\tlogrus.Warnf(\"ContainerRemove: %s\", err)\n\t}\n\n\tlogrus.Debugf(\"Removed container %s\", name)\n\treturn nil\n}"} {"input": "package atomic\n\nimport (\n\t\"encoding/json\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\n\ntype Uint32 struct {\n\t_ nocmp \n\n\tv uint32\n}\n\n\nfunc NewUint32(val uint32) *Uint32 {\n\treturn &Uint32{v: val}\n}\n\n\nfunc (i *Uint32) Load() uint32 {\n\treturn atomic.LoadUint32(&i.v)\n}\n\n\nfunc (i *Uint32) Add(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, delta)\n}\n\n\nfunc (i *Uint32) Sub(delta uint32) uint32 {\n\treturn atomic.AddUint32(&i.v, ^(delta - 1))\n}\n\n\nfunc (i *Uint32) Inc() uint32 {\n\treturn i.Add(1)\n}\n\n\n\n\n\nfunc (i *Uint32) CAS(old, new uint32) (swapped bool) {\n\treturn atomic.CompareAndSwapUint32(&i.v, old, new)\n}\n\n\nfunc (i *Uint32) Store(val uint32) {\n\tatomic.StoreUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) Swap(val uint32) (old uint32) {\n\treturn atomic.SwapUint32(&i.v, val)\n}\n\n\nfunc (i *Uint32) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(i.Load())\n}\n\n\nfunc (i *Uint32) UnmarshalJSON(b []byte) error {\n\tvar v uint32\n\tif err := json.Unmarshal(b, &v); err != nil {\n\t\treturn err\n\t}\n\ti.Store(v)\n\treturn nil\n}\n\n\nfunc (i *Uint32) String() string {\n\tv := i.Load()\n\treturn strconv.FormatUint(uint64(v), 10)\n}\n\nfunc (i *Uint32) Dec() uint32 ", "output": "{\n\treturn i.Sub(1)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"context\"\n\t\"github.com/asim/go-micro/v3\"\n\t\"github.com/asim/go-micro/v3/server\"\n)\n\n\n\n\nfunc main() {\n\tvar wg sync.WaitGroup\n\n\tservice := micro.NewService(\n\t\tmicro.WrapHandler(waitgroup(&wg)),\n\t\tmicro.AfterStop(func() error {\n\t\t\twg.Wait()\n\t\t\treturn nil\n\t\t}),\n\t)\n\n\tif err := service.Run(); err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n\nfunc waitgroup(wg *sync.WaitGroup) server.HandlerWrapper ", "output": "{\n\treturn func(h server.HandlerFunc) server.HandlerFunc {\n\t\treturn func(ctx context.Context, req server.Request, rsp interface{}) error {\n\t\t\twg.Add(1)\n\t\t\tdefer wg.Done()\n\t\t\treturn h(ctx, req, rsp)\n\t\t}\n\t}\n}"} {"input": "package yaml\n\nimport (\n\t\"fmt\"\n)\n\nfunc (this *Job) Name() JobKey {\n\treturn this.name\n}\n\n\n\nfunc (this *Job) InDesiredState(c Context) (bool, error) {\n\treturn true, nil\n}\n\nfunc (this *Job) Prepare(c Context) error {\n\treturn nil\n}\n\nfunc (this *Job) Execute(c Context) error {\n\tc.log(\"Executing Job %s\", this.name)\n\n\treturn nil\n}\n\nfunc (this *Job) Finish(c Context) error {\n\treturn nil\n}\n\nfunc (this *Job) get_task() *task {\n\tif this.task == nil {\n\t\tthis.task = alloc_task(this)\n\t\tthis.task.description = fmt.Sprintf(\"Job[%s]\", this.name)\n\n\t\tfor _, container := range this.container_instances {\n\t\t\tthis.task.DependsOn(container.get_task())\n\t\t}\n\t}\n\treturn this.task\n}\n\nfunc (this *Job) Validate(c Context) error ", "output": "{\n\treturn nil\n}"} {"input": "package j_kite\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"koding/remoteapi/models\"\n)\n\n\ntype PostRemoteAPIJKiteFetchPlansIDReader struct {\n\tformats strfmt.Registry\n}\n\n\nfunc (o *PostRemoteAPIJKiteFetchPlansIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewPostRemoteAPIJKiteFetchPlansIDOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}\n\n\nfunc NewPostRemoteAPIJKiteFetchPlansIDOK() *PostRemoteAPIJKiteFetchPlansIDOK {\n\treturn &PostRemoteAPIJKiteFetchPlansIDOK{}\n}\n\n\ntype PostRemoteAPIJKiteFetchPlansIDOK struct {\n\tPayload *models.JKite\n}\n\n\n\nfunc (o *PostRemoteAPIJKiteFetchPlansIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\to.Payload = new(models.JKite)\n\n\tif err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (o *PostRemoteAPIJKiteFetchPlansIDOK) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"[POST /remote.api/JKite.fetchPlans/{id}][%d] postRemoteApiJKiteFetchPlansIdOK %+v\", 200, o.Payload)\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/astaxie/beego/logs\"\n)\n\n\n\n\nfunc loggerInit(conf *Config, logFile string) (log *logs.BeeLogger) {\n\tlog = logs.NewLogger(0)\n\tlog.EnableFuncCallDepth(true)\n\tlog.SetLevel(conf.Base.LogLevel)\n\tif conf.Base.LogDir == \"console\" {\n\t\t_ = log.SetLogger(\"console\")\n\t} else {\n\t\t_ = log.SetLogger(\n\t\t\t\"file\", fmt.Sprintf(\n\t\t\t\t`{\"filename\":\"%s\", \"level\":%d, \"maxlines\":0,\n\t\t\t\t\t\"maxsize\":0, \"daily\":false, \"maxdays\":0}`,\n\t\t\t\tlogFile, conf.Base.LogLevel))\n\t}\n\treturn\n}\n\nfunc MyNewLogger(conf *Config, logFile string) *logs.BeeLogger ", "output": "{\n\treturn loggerInit(conf, logFile)\n}"} {"input": "package ewma\n\nimport (\n\t\"time\"\n)\n\ntype EwmaRate struct {\n\tEwma\n}\n\n\nconst nanosec = float64(1000000000)\n\n\n\n\nfunc NewEwmaRate(halfLife time.Duration) *EwmaRate {\n\treturn (&EwmaRate{}).Init(halfLife)\n}\n\n\n\n\nfunc (r *EwmaRate) Init(halfLife time.Duration) *EwmaRate {\n\tr.Ewma.Init(halfLife)\n\treturn r\n}\n\n\n\n\nfunc (r *EwmaRate) UpdateNow() float64 {\n\treturn r.Update(time.Now())\n}\n\n\n\n\nfunc (r *EwmaRate) Update(now time.Time) float64 {\n\ttimeDelta := now.Sub(r.lastTimestamp)\n\treturn r.Ewma.Update(nanosec/float64(timeDelta.Nanoseconds()), now)\n}\n\n\n\n\n\n\n\nfunc (r *EwmaRate) Current(now time.Time) float64 {\n\tif r.lastTimestamp.IsZero() || r.lastTimestamp == now || now.Before(r.lastTimestamp) {\n\t\treturn r.Ewma.Current\n\t}\n\n\ttimeDelta := now.Sub(r.lastTimestamp)\n\n\treturn r.count(0, timeDelta)\n}\n\nfunc (r *EwmaRate) CurrentNow() float64 ", "output": "{\n\treturn r.Current(time.Now())\n}"} {"input": "package math32\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\n\n\nfunc TestTrunc(t *testing.T) ", "output": "{\n\tival := []float32{}\n\tx := float32(1)\n\tfor !math.IsInf(float64(x), 1) {\n\t\tival = append(ival, x)\n\t\tx *= 2\n\t}\n\tfval := []float32{}\n\tx = math.Nextafter32(1, -1)\n\tfor x != 0 {\n\t\tfval = append(fval, x)\n\t\tx = 1 - (1-x)*2\n\t}\n\tfor _, i := range ival {\n\t\tfor _, f := range fval {\n\t\t\tx := i + f\n\t\t\ty := Trunc(x)\n\t\t\tassert(y == i || x-i == 1, \"Trunc\", t)\n\t\t\tz := Trunc(-x)\n\t\t\tassert(z == -y, \"Trunc\", t)\n\t\t\tassert(Signbit(Trunc(-x)) == !Signbit(y), \"Signbit/Trunc\", t)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/coscms/webx\"\n)\n\ntype MainAction struct {\n\t*webx.Action\n\n\tstart time.Time\n\n\thello webx.Mapper `webx:\"/(.*)\"`\n}\n\nfunc (c *MainAction) Hello(world string) bool {\n\tc.Write(\"hello %v\", world)\n\treturn true\n}\n\n\n\nfunc (c *MainAction) After(structName, actionName string, actionResult interface{}) bool {\n\tfmt.Println(\"after\", time.Now().Sub(c.start))\n\treturn true\n}\n\nfunc main() {\n\twebx.AddRouter(\"/\", &MainAction{})\n\twebx.Run(\"0.0.0.0:9999\")\n}\n\nfunc (c *MainAction) Before(structName, actionName string) bool ", "output": "{\n\tc.start = time.Now()\n\tfmt.Println(\"before\", c.start)\n\treturn true\n}"} {"input": "package gottyclient\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\t\"unsafe\"\n)\n\nfunc notifySignalSIGWINCH(c chan<- os.Signal) {\n\tsignal.Notify(c, syscall.SIGWINCH)\n}\n\nfunc resetSignalSIGWINCH() {\n\tsignal.Reset(syscall.SIGWINCH)\n}\n\n\n\nfunc syscallTIOCGWINSZ() ([]byte, error) ", "output": "{\n\tws := winsize{}\n\n\tsyscall.Syscall(syscall.SYS_IOCTL,\n\t\tuintptr(0), uintptr(syscall.TIOCGWINSZ),\n\t\tuintptr(unsafe.Pointer(&ws)))\n\n\tb, err := json.Marshal(ws)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"json.Marshal error: %v\", err)\n\t}\n\treturn b, err\n}"} {"input": "package iso20022\n\n\ntype GenericIdentification7 struct {\n\n\tIssuer *Max8Text `xml:\"Issr\"`\n\n\tInformation *Max35Text `xml:\"Inf\"`\n}\n\n\n\nfunc (g *GenericIdentification7) SetInformation(value string) {\n\tg.Information = (*Max35Text)(&value)\n}\n\nfunc (g *GenericIdentification7) SetIssuer(value string) ", "output": "{\n\tg.Issuer = (*Max8Text)(&value)\n}"} {"input": "package groundstation\n\nimport (\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/client\"\n\t\"github.com/aws/aws-sdk-go/aws/client/metadata\"\n\t\"github.com/aws/aws-sdk-go/aws/request\"\n\t\"github.com/aws/aws-sdk-go/aws/signer/v4\"\n\t\"github.com/aws/aws-sdk-go/private/protocol/restjson\"\n)\n\n\n\n\n\n\n\ntype GroundStation struct {\n\t*client.Client\n}\n\n\nvar initClient func(*client.Client)\n\n\nvar initRequest func(*request.Request)\n\n\nconst (\n\tServiceName = \"GroundStation\" \n\tEndpointsID = \"groundstation\" \n\tServiceID = \"GroundStation\" \n)\n\n\n\n\n\n\n\n\n\n\n\nfunc New(p client.ConfigProvider, cfgs ...*aws.Config) *GroundStation {\n\tc := p.ClientConfig(EndpointsID, cfgs...)\n\tif c.SigningNameDerived || len(c.SigningName) == 0 {\n\t\tc.SigningName = \"groundstation\"\n\t}\n\treturn newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName)\n}\n\n\n\n\n\n\nfunc (c *GroundStation) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\tif initRequest != nil {\n\t\tinitRequest(req)\n\t}\n\n\treturn req\n}\n\nfunc newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *GroundStation ", "output": "{\n\tsvc := &GroundStation{\n\t\tClient: client.New(\n\t\t\tcfg,\n\t\t\tmetadata.ClientInfo{\n\t\t\t\tServiceName: ServiceName,\n\t\t\t\tServiceID: ServiceID,\n\t\t\t\tSigningName: signingName,\n\t\t\t\tSigningRegion: signingRegion,\n\t\t\t\tEndpoint: endpoint,\n\t\t\t\tAPIVersion: \"2019-05-23\",\n\t\t\t},\n\t\t\thandlers,\n\t\t),\n\t}\n\n\tsvc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)\n\tsvc.Handlers.Build.PushBackNamed(restjson.BuildHandler)\n\tsvc.Handlers.Unmarshal.PushBackNamed(restjson.UnmarshalHandler)\n\tsvc.Handlers.UnmarshalMeta.PushBackNamed(restjson.UnmarshalMetaHandler)\n\tsvc.Handlers.UnmarshalError.PushBackNamed(restjson.UnmarshalErrorHandler)\n\n\tif initClient != nil {\n\t\tinitClient(svc.Client)\n\t}\n\n\treturn svc\n}"} {"input": "package models\n\nimport (\n\t\"koding/db/mongodb/modelhelper\"\n\t\"net\"\n\t\"socialapi/config\"\n\t\"socialapi/request\"\n\n\t\"github.com/koding/logging\"\n)\n\n\ntype Client struct {\n\tAccount *Account\n\n\tIP net.IP\n\n\tSessionID string\n}\n\n\ntype Context struct {\n\tGroupName string\n\tClient *Client\n\tlog logging.Logger\n}\n\n\nfunc NewContext(log logging.Logger) *Context {\n\treturn &Context{\n\t\tlog: log,\n\t}\n}\n\n\nfunc (c *Context) OverrideQuery(q *request.Query) *request.Query {\n\tq.GroupName = c.GroupName\n\tif c.IsLoggedIn() {\n\t\tq.AccountId = c.Client.Account.Id\n\t} else {\n\t\tq.AccountId = 0\n\t}\n\n\treturn q\n}\n\n\n\n\n\n\n\nfunc (c *Context) IsAdmin() bool {\n\tif !c.IsLoggedIn() {\n\t\treturn false\n\t}\n\n\tsuperAdmins := config.MustGet().DummyAdmins\n\treturn IsIn(c.Client.Account.Nick, superAdmins...)\n}\n\n\n\n\nfunc (c *Context) CanManage() error {\n\tif !c.IsLoggedIn() {\n\t\treturn ErrNotLoggedIn\n\t}\n\n\tcanManage, err := modelhelper.CanManage(c.Client.Account.Nick, c.GroupName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !canManage {\n\t\treturn ErrCannotManageGroup\n\t}\n\n\treturn nil\n}\n\n\nfunc (c *Context) MustGetLogger() logging.Logger {\n\tif c.log == nil {\n\t\tpanic(ErrLoggerNotExist)\n\t}\n\n\treturn c.log\n}\n\nfunc (c *Context) IsLoggedIn() bool ", "output": "{\n\tif c.Client == nil {\n\t\treturn false\n\t}\n\n\tif c.Client.Account == nil {\n\t\treturn false\n\t}\n\n\tif c.Client.Account.Id == 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}"} {"input": "package devices\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) BaseClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient ", "output": "{\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package controllers\n\nimport \"github.com/labstack/echo\"\n\n\n\nfunc Init(router *echo.Echo) ", "output": "{\n\tnew(ProfileController).Init(router)\n\tnew(AuthorController).Init(router)\n\tnew(BookController).Init(router)\n}"} {"input": "package networks\n\nimport (\n\t\"errors\"\n\n\t\"github.com/rackspace/gophercloud\"\n\t\"github.com/rackspace/gophercloud/pagination\"\n)\n\n\n\n\nfunc List(c *gophercloud.ServiceClient) pagination.Pager {\n\tcreatePage := func(r pagination.PageResult) pagination.Page {\n\t\treturn NetworkPage{pagination.SinglePageBase(r)}\n\t}\n\n\treturn pagination.NewPager(c, listURL(c), createPage)\n}\n\n\nfunc Get(c *gophercloud.ServiceClient, id string) GetResult {\n\tvar res GetResult\n\t_, res.Err = c.Request(\"GET\", getURL(c, id), gophercloud.RequestOpts{\n\t\tJSONResponse: &res.Body,\n\t\tOkCodes: []int{200},\n\t})\n\treturn res\n}\n\n\n\n\n\ntype CreateOptsBuilder interface {\n\tToNetworkCreateMap() (map[string]interface{}, error)\n}\n\n\n\ntype CreateOpts struct {\n\tCIDR string\n\tLabel string\n}\n\n\nfunc (opts CreateOpts) ToNetworkCreateMap() (map[string]interface{}, error) {\n\tn := make(map[string]interface{})\n\n\tif opts.CIDR == \"\" {\n\t\treturn nil, errors.New(\"Required field CIDR not set.\")\n\t}\n\tif opts.Label == \"\" {\n\t\treturn nil, errors.New(\"Required field Label not set.\")\n\t}\n\n\tn[\"label\"] = opts.Label\n\tn[\"cidr\"] = opts.CIDR\n\treturn map[string]interface{}{\"network\": n}, nil\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc Delete(c *gophercloud.ServiceClient, networkID string) DeleteResult {\n\tvar res DeleteResult\n\t_, res.Err = c.Request(\"DELETE\", deleteURL(c, networkID), gophercloud.RequestOpts{\n\t\tOkCodes: []int{204},\n\t})\n\treturn res\n}\n\nfunc Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult ", "output": "{\n\tvar res CreateResult\n\n\treqBody, err := opts.ToNetworkCreateMap()\n\tif err != nil {\n\t\tres.Err = err\n\t\treturn res\n\t}\n\n\t_, res.Err = c.Request(\"POST\", createURL(c), gophercloud.RequestOpts{\n\t\tJSONBody: &reqBody,\n\t\tJSONResponse: &res.Body,\n\t\tOkCodes: []int{200, 201, 202},\n\t})\n\treturn res\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/spf13/viper\"\n)\n\nvar DefaultConfPath string\n\nfunc runCmd(cmd string, args []string) {\n\tc := exec.Command(cmd, args...)\n\tif err := c.Run(); err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"cmd\": cmd,\n\t\t\t\"args\": args,\n\t\t}).Fatal(\"Failed to execute command\")\n\t}\n}\n\n\n\nfunc main() {\n\tif err := initConfig(); err != nil {\n\t\tlog.WithError(err).Fatalf(\"Failed to load config %s\", viper.ConfigFileUsed())\n\t}\n\tconfig := viper.GetViper()\n\tifname := os.Args[1]\n\n\tswitch config.GetString(\"bridges.type\") {\n\tcase \"linux\":\n\t\trunCmd(\"ip\", []string{\"link\", \"set\", \"dev\", ifname, \"master\", config.GetString(\"bridges.name\")})\n\tcase \"ovs\":\n\t\trunCmd(\"ovs-vsctl\", []string{\"add-port\", config.GetString(\"bridges.name\"), ifname})\n\tdefault:\n\t\tlog.Fatalf(\"Unknown bridge type\")\n\t}\n\trunCmd(\"ip\", []string{\"link\", \"set\", ifname, \"up\"})\n}\n\nfunc initConfig() error ", "output": "{\n\tviper.SetDefault(\"bridges.type\", \"linux\")\n\tviper.SetDefault(\"bridges.name\", \"br0\")\n\tviper.SetConfigFile(DefaultConfPath)\n\tviper.SetConfigType(\"toml\")\n\tviper.AutomaticEnv()\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tif viper.ConfigFileUsed() == DefaultConfPath && os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package iso20022\n\n\ntype Commission19 struct {\n\n\tAmount *ImpliedCurrencyAndAmount `xml:\"Amt\"`\n\n\tAdditionalInformation *Max350Text `xml:\"AddtlInf,omitempty\"`\n}\n\nfunc (c *Commission19) SetAmount(value, currency string) {\n\tc.Amount = NewImpliedCurrencyAndAmount(value, currency)\n}\n\n\n\nfunc (c *Commission19) SetAdditionalInformation(value string) ", "output": "{\n\tc.AdditionalInformation = (*Max350Text)(&value)\n}"} {"input": "package triangle\n\nimport (\n\t\"math\"\n)\n\nconst (\n\tEqu = iota \n\tIso \n\tSca \n\tNaT \n)\n\ntype Kind int\n\nfunc KindFromSides(a, b, c float64) Kind {\n\tif a+b <= c || a+c <= b || b+c <= a {\n\t\treturn NaT\n\t}\n\n\tswitch {\n\tcase areNaN(a, b, c): \n\t\tfallthrough\n\tcase areInf(a, b, c): \n\t\tfallthrough\n\tcase a == 0 && b == 0 && c == 0: \n\t\treturn NaT\n\n\tcase a == b && b == c: \n\t\treturn Equ\n\tcase a == b || b == c || a == c: \n\t\treturn Iso\n\tdefault: \n\t\treturn Sca\n\t}\n}\n\n\n\nfunc areInf(vals ...float64) bool {\n\tfor _, v := range vals {\n\t\tif math.IsInf(v, 1) || math.IsInf(v, -1) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc areNaN(vals ...float64) bool ", "output": "{\n\tfor _, v := range vals {\n\t\tif math.IsNaN(v) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package matchers_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/blevesearch/bleve\"\n\t\"github.com/blevesearch/bleve/search/query\"\n\t\"github.com/nrwiersma/isenzo/matchers\"\n)\n\nfunc TestParallelMatcher(t *testing.T) {\n\tf := matchers.NewParallelMatcherFactory(newWaitMatcherFactory(), 10)\n\tm, err := f.New(map[string]interface{}{})\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected err; got %v\", err)\n\t}\n\n\tfor i := 0; i < 10; i++ {\n\t\tm.Match(\"\", bleve.NewMatchAllQuery())\n\t}\n\n\tids, errs := m.Finish()\n\tif len(errs) != 0 {\n\t\tt.Fatalf(\"expected no errors; got %v\", errs)\n\t}\n\n\tif len(ids) != 10 {\n\t\tt.Fatalf(\"expected %d results; got %v\", 10, len(ids))\n\t}\n}\n\ntype waitMatcherFactory struct {}\n\n\n\nfunc (f waitMatcherFactory) New(doc interface{}) (matchers.Matcher, error) {\n\treturn &waitMatcher{\n\t\tids: make([]string, 0),\n\t}, nil\n}\n\nfunc (f waitMatcherFactory) Map(doc interface{}) (interface{}, error) {\n\treturn doc, nil\n}\n\ntype waitMatcher struct {\n\tids []string\n}\n\n\nfunc (m *waitMatcher) Match(id string, q query.Query) {\n\ttime.Sleep(10 * time.Millisecond)\n\n\tm.ids = append(m.ids, id)\n}\n\n\nfunc (m *waitMatcher) Finish() (ids []string, errs []error) {\n\treturn m.ids, []error{}\n}\n\nfunc newWaitMatcherFactory() matchers.Factory ", "output": "{\n\treturn &waitMatcherFactory{}\n}"} {"input": "package password\n\n\nvar _ PasswordGenerator = (*mockGenerator)(nil)\n\ntype mockGenerator struct {\n\tresult string\n\terr error\n}\n\n\n\n\n\n\n\n\nfunc NewMockGenerator(result string, err error) *mockGenerator {\n\treturn &mockGenerator{\n\t\tresult: result,\n\t\terr: err,\n\t}\n}\n\n\n\n\n\nfunc (g *mockGenerator) MustGenerate(int, int, int, bool, bool) string {\n\tif g.err != nil {\n\t\tpanic(g.err)\n\t}\n\treturn g.result\n}\n\nfunc (g *mockGenerator) Generate(int, int, int, bool, bool) (string, error) ", "output": "{\n\tif g.err != nil {\n\t\treturn \"\", g.err\n\t}\n\treturn g.result, nil\n}"} {"input": "package main\n\nimport(\"fmt\";\"os\";\"regexp\";\"flag\";\"net/http\";\"log\";\"errors\")\n\ntype HTTPDCmd struct {}\n\nfunc (c *HTTPDCmd) Summary() string {\n return \"Starts small HTTP server\"\n}\n\n\n\nfunc (c *HTTPDCmd) ValidateArgs(args[]string) error {\n re1 := regexp.MustCompile(\"^[0-9]+$\")\n re2 := regexp.MustCompile(\"^/.+$\")\n if (len(args) == 3 && args[0] == \"serve\" && re1.MatchString(args[1]) && re2.MatchString(args[2])) {\n return nil\n }\n return errors.New(\"Invalid args\")\n}\n\nfunc (c *HTTPDCmd) Run(args[]string, cfg Config) (int, error) {\n if (len(args) == 3 && args[0] == \"serve\") {\n port := flag.String(\"p\", args[1], \"port to serve on\")\n path := flag.String(\"d\", args[2], \"the dir of static file on host\")\n flag.Parse()\n http.Handle(\"/\", http.FileServer(http.Dir(*path)))\n log.Fatal(http.ListenAndServe(\":\"+*port, nil))\n return 1, nil\n }\n fmt.Fprintf(os.Stdout, c.Help())\n return 0, nil\n}\n\nfunc (c *HTTPDCmd) Help() string ", "output": "{\n return `Starts small HTTP daemon that can server files from a specific directory\n\nAvailable subcommands:\n httpd serve Serve on 0.0.0.0:\n`\n}"} {"input": "package log\n\nimport (\n\t\"github.com/proidiot/gone/errors\"\n\t\"github.com/proidiot/gone/log/opt\"\n\t\"github.com/proidiot/gone/log/pri\"\n)\n\ntype testSyslogger struct {\n\tLastPri pri.Priority\n\tLastMsg interface{}\n\tTriggerError bool\n}\n\nfunc (t *testSyslogger) triggerError() error {\n\tif t.TriggerError {\n\t\treturn errors.New(\"Artificial error triggered in testSyslogger\")\n\t}\n\n\treturn nil\n}\n\nfunc (t *testSyslogger) Syslog(p pri.Priority, msg interface{}) error {\n\tt.LastPri = p\n\tt.LastMsg = msg\n\treturn t.triggerError()\n}\n\n\n\nfunc (t *testSyslogger) Close() error {\n\treturn t.triggerError()\n}\n\ntype limitedSyslogger struct {\n\tLastPri pri.Priority\n\tLastMsg interface{}\n\tTriggerError bool\n}\n\nfunc (l *limitedSyslogger) triggerError() error {\n\tif l.TriggerError {\n\t\treturn errors.New(\n\t\t\t\"Artificial error triggered in limitedSyslogger\",\n\t\t)\n\t}\n\n\treturn nil\n}\n\nfunc (l *limitedSyslogger) Syslog(p pri.Priority, msg interface{}) error {\n\tl.LastPri = p\n\tl.LastMsg = msg\n\treturn l.triggerError()\n}\n\nfunc (t *testSyslogger) Openlog(string, opt.Option, pri.Priority) error ", "output": "{\n\treturn t.triggerError()\n}"} {"input": "package config\n\nimport (\n\t\"sync\"\n)\n\n\n\n\n\n\ntype delayedEnvironment struct {\n\tenv Environment\n\tloading sync.Mutex\n\tcallback func() Environment\n}\n\n\n\nfunc (e *delayedEnvironment) Get(key string) (string, bool) {\n\te.Load()\n\treturn e.env.Get(key)\n}\n\n\n\nfunc (e *delayedEnvironment) GetAll(key string) []string {\n\te.Load()\n\treturn e.env.GetAll(key)\n}\n\n\n\nfunc (e *delayedEnvironment) Bool(key string, def bool) bool {\n\te.Load()\n\treturn e.env.Bool(key, def)\n}\n\n\n\n\n\n\nfunc (e *delayedEnvironment) All() map[string][]string {\n\te.Load()\n\treturn e.env.All()\n}\n\n\n\n\n\n\n\n\nfunc (e *delayedEnvironment) Load() {\n\te.loading.Lock()\n\tdefer e.loading.Unlock()\n\n\tif e.env != nil {\n\t\treturn\n\t}\n\n\te.env = e.callback()\n}\n\nfunc (e *delayedEnvironment) Int(key string, def int) int ", "output": "{\n\te.Load()\n\treturn e.env.Int(key, def)\n}"} {"input": "package concurrent\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\ntype BackgroundWorker interface {\n\tDo(f func() (interface{}, error)) error\n\tClose() ([]interface{}, error)\n}\n\n\nfunc NewBackgroundWorker() BackgroundWorker {\n\treturn newBackgroundWorker()\n}\n\ntype valueError struct {\n\tvalue interface{}\n\terr error\n}\n\ntype backgroundWorker struct {\n\twg *sync.WaitGroup\n\tvalueErrors chan *valueError\n\tdestroyable Destroyable\n}\n\n\n\nfunc (b *backgroundWorker) Do(f func() (interface{}, error)) error {\n\t_, err := b.destroyable.Do(func() (interface{}, error) {\n\t\tb.wg.Add(1)\n\t\tgo func() {\n\t\t\tvalue, err := f()\n\t\t\tb.valueErrors <- &valueError{value, err}\n\t\t\tb.wg.Done()\n\t\t}()\n\t\treturn nil, nil\n\t})\n\treturn err\n}\n\nfunc (b *backgroundWorker) Close() ([]interface{}, error) {\n\tvar values []interface{}\n\tvar errs []error\n\tif err := b.destroyable.Destroy(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tvalueError, ok := <-b.valueErrors\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tvalues = append(values, valueError.value)\n\t\t\tif valueError.err != nil {\n\t\t\t\terrs = append(errs, valueError.err)\n\t\t\t}\n\t\t}\n\t}()\n\tb.wg.Wait()\n\tclose(b.valueErrors)\n\tif len(errs) == 0 {\n\t\treturn values, nil\n\t}\n\treturn values, fmt.Errorf(\"%v\", errs)\n}\n\nfunc newBackgroundWorker() *backgroundWorker ", "output": "{\n\treturn &backgroundWorker{&sync.WaitGroup{}, make(chan *valueError), NewDestroyable(nil)}\n}"} {"input": "package policy\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/go-openapi/runtime\"\n\t\"github.com/go-openapi/strfmt\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\ntype DeleteFqdnCacheReader struct {\n\tformats strfmt.Registry\n}\n\n\n\n\n\nfunc NewDeleteFqdnCacheOK() *DeleteFqdnCacheOK {\n\treturn &DeleteFqdnCacheOK{}\n}\n\n\ntype DeleteFqdnCacheOK struct {\n}\n\nfunc (o *DeleteFqdnCacheOK) Error() string {\n\treturn fmt.Sprintf(\"[DELETE /fqdn/cache][%d] deleteFqdnCacheOK \", 200)\n}\n\nfunc (o *DeleteFqdnCacheOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\treturn nil\n}\n\n\nfunc NewDeleteFqdnCacheBadRequest() *DeleteFqdnCacheBadRequest {\n\treturn &DeleteFqdnCacheBadRequest{}\n}\n\n\ntype DeleteFqdnCacheBadRequest struct {\n\tPayload models.Error\n}\n\nfunc (o *DeleteFqdnCacheBadRequest) Error() string {\n\treturn fmt.Sprintf(\"[DELETE /fqdn/cache][%d] deleteFqdnCacheBadRequest %+v\", 400, o.Payload)\n}\n\nfunc (o *DeleteFqdnCacheBadRequest) GetPayload() models.Error {\n\treturn o.Payload\n}\n\nfunc (o *DeleteFqdnCacheBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\tif err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (o *DeleteFqdnCacheReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) ", "output": "{\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewDeleteFqdnCacheOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewDeleteFqdnCacheBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}"} {"input": "package entity\n\n\ntype Config struct{\n\n\tDefaultCredential *Credential\n\n\tHosts map[string]*Credential\n\n\tInputEntries []InputEntry\n\n\tLogging bool\n\tLogPath string\n}\n\n\n\n\n\nfunc (c *Config) GetDefaultCredential(hostName string) (cred *Credential) {\n\tcred, found := c.Hosts[hostName]\n\tif !found {\n\t\tcred = c.DefaultCredential\n\t}\n\treturn\n}\n\nfunc NewConfig() *Config ", "output": "{\n\tconfig := new(Config)\n\n\tconfig.DefaultCredential = new(Credential)\n\tconfig.Hosts = make(map[string]*Credential)\n\tconfig.InputEntries = make([]InputEntry, 0)\n\tconfig.Logging = false\n\n\treturn config\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc BenchmarkGetStatus(b *testing.B) {\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tgetStatus(200)\n\t}\n}\n\nfunc TestGetStatus(t *testing.T) ", "output": "{\n\tif getStatus(500) != StatusError {\n\t\tt.Errorf(\"The expected status error for the code 500 is: %s\", StatusError)\n\t}\n\tif getStatus(400) != StatusFail {\n\t\tt.Errorf(\"The expected status error for the code 400 is: %s\", StatusFail)\n\t}\n\tif getStatus(200) != StatusSuccess {\n\t\tt.Errorf(\"The expected status error for the code 200 is: %s\", StatusSuccess)\n\t}\n}"} {"input": "package metrics\n\n\ntype Healthcheck interface {\n\tCheck()\n\tError() error\n\tHealthy()\n\tUnhealthy(error)\n}\n\n\n\nfunc NewHealthcheck(f func(Healthcheck)) Healthcheck {\n\tif UseNilMetrics {\n\t\treturn NilHealthcheck{}\n\t}\n\treturn &StandardHealthcheck{nil, f}\n}\n\n\ntype NilHealthcheck struct{}\n\n\nfunc (NilHealthcheck) Check() {}\n\n\nfunc (NilHealthcheck) Error() error { return nil }\n\n\nfunc (NilHealthcheck) Healthy() {}\n\n\nfunc (NilHealthcheck) Unhealthy(error) {}\n\n\n\ntype StandardHealthcheck struct {\n\terr error\n\tf func(Healthcheck)\n}\n\n\nfunc (h *StandardHealthcheck) Check() {\n\th.f(h)\n}\n\n\nfunc (h *StandardHealthcheck) Error() error {\n\treturn h.err\n}\n\n\nfunc (h *StandardHealthcheck) Healthy() {\n\th.err = nil\n}\n\n\n\n\n\nfunc (h *StandardHealthcheck) Unhealthy(err error) ", "output": "{\n\th.err = err\n}"} {"input": "package endpoint\n\nimport (\n\t\"net/http\"\n\t\"regexp\"\n)\n\ntype node struct {\n\tendpoint *endpoint\n\tmethods map[string]http.HandlerFunc\n\tstaticLinks map[string]*node\n\tdynamicLink *node\n\tdynamicMatcher *regexp.Regexp\n\tdynamicParam string\n}\n\n\n\nfunc (n *node) makeDynamicLink(name string) *node {\n\tif n.staticLinks != nil {\n\t\tpanic(\"cant make dynamic link when there are static links\")\n\t}\n\tmatcher := n.endpoint.matchers[name]\n\tif matcher == nil {\n\t\tpanic(\"unknown matcher (\" + name + \")\")\n\t}\n\tif n.dynamicMatcher == nil {\n\t\tn.dynamicMatcher = matcher\n\t\tn.dynamicLink = n.endpoint.newNode()\n\t\tn.dynamicParam = name\n\t} else if n.dynamicParam != name {\n\t\tpanic(\"another dynamic link registered on this path\")\n\t}\n\treturn n.dynamicLink\n}\n\nfunc (n *node) Handle(method string, h http.HandlerFunc) *node {\n\tif n.methods == nil {\n\t\tn.methods = make(map[string]http.HandlerFunc)\n\t}\n\tif n.methods[method] != nil {\n\t\tpanic(\"method handler already registered\")\n\t}\n\tn.methods[method] = h\n\treturn n\n}\n\nfunc (n *node) makeStaticLink(segment string) *node {\n\tif n.dynamicMatcher != nil {\n\t\tpanic(\"cant make static link when there is dynamic link\")\n\t}\n\tif n.staticLinks == nil {\n\t\tn.staticLinks = make(map[string]*node)\n\t}\n\tif n.staticLinks[segment] == nil {\n\t\tn.staticLinks[segment] = n.endpoint.newNode()\n\t}\n\treturn n.staticLinks[segment]\n}\n\nfunc (n *node) getPaths(path string) []string ", "output": "{\n\tp := make([]string, 0, 4)\n\tif nil != n.methods {\n\t\tfor m, _ := range n.methods {\n\t\t\tp = append(p, m + \" \" + path)\n\t\t}\n\t}\n\tif path == \"/\" {\n\t\tpath = \"\"\n\t}\n\tif nil != n.staticLinks {\n\t\tfor s, sn := range n.staticLinks {\n\t\t\tp = append(p, sn.getPaths(path + \"/\" + s)...)\n\t\t}\n\t}\n\tif nil != n.dynamicLink {\n\t\tp = append(p, n.dynamicLink.getPaths(path + \"/:\" + n.dynamicParam)...)\n\t}\n\treturn p\n}"} {"input": "package core\n\nimport (\n\t\"os\";\n\t\"container/list\";\n\t\"net\";\n\t\"log\";\n\t\"irc\";\n\t\"runloop\";\n)\n\ntype Network struct {\n\tname\t\tstring;\n\tserver\t\t*server;\n\tclients\t\t*list.List;\n\tlisten\t\t*listenConn;\n}\n\n\n\nfunc (network *Network) addClient(conn net.Conn) {\n\tclient := newClient(conn, network);\n\tnetwork.clients.PushBack(client);\n\tlog.Stderrf(\"client connected from %s\\n\", conn.RemoteAddr());\n}\n\n\n\nfunc (network *Network) SendToServer(msg *irc.Message) {\n\tif network.server != nil {\n\t\tnetwork.server.Send(msg)\n\t}\n}\n\n\nfunc (network *Network) SendToClients(msg *irc.Message) {\n\tfor c := range network.clients.Iter() {\n\t\tc.(*client).Send(msg)\n\t}\n}\n\n\nfunc (network *Network) SendNoticeToClient(conn Conn, line string) {\n\tnick := \"bouncin\"; \n\tconn.Send(&irc.Message{Command: \"NOTICE\", Params: []string{nick, line}});\n}\n\nvar networks = make(map[string] *Network);\n\nfunc AddNetwork(name string, server net.Conn, listen net.Listener) *Network {\n\tnetwork := newNetwork(name, server, listen);\n\tnetworks[name] = network;\n\treturn network;\n}\n\nfunc newNetwork(name string, serverConn net.Conn, listen net.Listener) *Network ", "output": "{\n\tvar network *Network;\n\n\taccept := func(conn net.Conn) {\n\t\trunloop.CallLater(func() {\n\t\t\tnetwork.addClient(conn)\n\t\t})\n\t};\n\n\terror := func(err os.Error) {\n\t};\n\n\tl := newListenConn(listen, accept, error);\n\tnetwork = &Network{name: name, clients: list.New(), listen: l};\n\tnetwork.server = newServer(serverConn, network);\n\treturn network;\n}"} {"input": "package geo\n\nimport (\n\t\"image/jpeg\"\n\t\"image/png\"\n\t\"io\"\n\n\t\"github.com/mmcloughlin/globe\"\n)\n\ntype Sphere struct {\n\t*globe.Globe\n}\n\nfunc NewSphere() *Sphere {\n\ts := &Sphere{globe.New()}\n\treturn s\n}\n\nfunc (s *Sphere) EncodePNG(size int, writer io.Writer) error {\n\timage := s.Image(size)\n\treturn png.Encode(writer, image)\n}\n\n\n\nfunc (s *Sphere) EncodeJPEG(size int, quality int, writer io.Writer) error ", "output": "{\n\timage := s.Image(size)\n\treturn jpeg.Encode(writer, image, &jpeg.Options{Quality: quality})\n}"} {"input": "package string_byte_array_converter\n\nimport (\n\t\"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/blevesearch/bleve/analysis\"\n\t\"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/blevesearch/bleve/registry\"\n)\n\ntype StringByteArrayConverter struct{}\n\n\n\nfunc (c *StringByteArrayConverter) Convert(in []byte) (interface{}, error) {\n\treturn string(in), nil\n}\n\nfunc Constructor(config map[string]interface{}, cache *registry.Cache) (analysis.ByteArrayConverter, error) {\n\treturn NewStringByteArrayConverter(), nil\n}\n\nfunc init() {\n\tregistry.RegisterByteArrayConverter(\"string\", Constructor)\n}\n\nfunc NewStringByteArrayConverter() *StringByteArrayConverter ", "output": "{\n\treturn &StringByteArrayConverter{}\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestSessionDaemon_GetInterfaceName(t *testing.T) {\n\ts := SessionDaemon{}\n\tassert.Equal(t, dbusInterface, s.GetInterfaceName())\n}\n\n\n\nfunc TestFilterList(t *testing.T) ", "output": "{\n\tvar infos = []struct {\n\t\torigin []string\n\t\tcondition []string\n\t\tret []string\n\t}{\n\t\t{\n\t\t\torigin: []string{\"power\", \"audio\", \"dock\"},\n\t\t\tcondition: []string{\"power\", \"dock\"},\n\t\t\tret: []string{\"audio\"},\n\t\t},\n\t\t{\n\t\t\torigin: []string{\"power\", \"audio\", \"dock\"},\n\t\t\tcondition: []string{},\n\t\t\tret: []string{\"power\", \"audio\", \"dock\"},\n\t\t},\n\t\t{\n\t\t\torigin: []string{\"power\", \"audio\", \"dock\"},\n\t\t\tcondition: []string{\"power\", \"dock\", \"audio\"},\n\t\t\tret: []string(nil),\n\t\t},\n\t}\n\n\tfor _, info := range infos {\n\t\tassert.ElementsMatch(t, info.ret, filterList(info.origin, info.condition))\n\t}\n}"} {"input": "package pipelinerun\n\nimport (\n\t\"sort\"\n\n\t\"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1\"\n)\n\nfunc SortByNamespace(prs []v1beta1.PipelineRun) {\n\tsort.Sort(byNamespace(prs))\n}\n\ntype byNamespace []v1beta1.PipelineRun\n\nfunc (prs byNamespace) compareNamespace(ins, jns string) (lt, eq bool) {\n\tlt, eq = ins < jns, ins == jns\n\treturn lt, eq\n}\n\nfunc (prs byNamespace) Len() int { return len(prs) }\nfunc (prs byNamespace) Swap(i, j int) { prs[i], prs[j] = prs[j], prs[i] }\n\n\nfunc (prs byNamespace) Less(i, j int) bool ", "output": "{\n\tvar lt, eq bool\n\tif lt, eq = prs.compareNamespace(prs[i].Namespace, prs[j].Namespace); eq {\n\t\tif prs[j].Status.StartTime == nil {\n\t\t\treturn false\n\t\t}\n\t\tif prs[i].Status.StartTime == nil {\n\t\t\treturn true\n\t\t}\n\t\treturn prs[j].Status.StartTime.Before(prs[i].Status.StartTime)\n\t}\n\treturn lt\n}"} {"input": "package instana\n\nimport (\n\t\"time\"\n)\n\n\ntype EventData struct {\n\tTitle string `json:\"title\"`\n\tText string `json:\"text\"`\n\tDuration int `json:\"duration\"`\n\tSeverity int `json:\"severity\"`\n\tPlugin string `json:\"plugin,omitempty\"`\n\tID string `json:\"id,omitempty\"`\n\tHost string `json:\"host\"`\n}\n\ntype severity int\n\n\nconst (\n\tSeverityChange severity = -1\n\tSeverityWarning severity = 5\n\tSeverityCritical severity = 10\n)\n\n\nconst (\n\tServicePlugin = \"com.instana.forge.connection.http.logical.LogicalWebApp\"\n\tServiceHost = \"\"\n)\n\n\nfunc SendDefaultServiceEvent(title string, text string, sev severity, duration time.Duration) {\n\tif sensor == nil {\n\t\tSendServiceEvent(\"\", title, text, sev, duration)\n\t} else {\n\t\tSendServiceEvent(sensor.serviceName, title, text, sev, duration)\n\t}\n}\n\n\nfunc SendServiceEvent(service string, title string, text string, sev severity, duration time.Duration) {\n\tsendEvent(&EventData{\n\t\tTitle: title,\n\t\tText: text,\n\t\tSeverity: int(sev),\n\t\tPlugin: ServicePlugin,\n\t\tID: service,\n\t\tHost: ServiceHost,\n\t\tDuration: int(duration / time.Millisecond),\n\t})\n}\n\n\n\n\nfunc sendEvent(event *EventData) {\n\tif sensor == nil {\n\t\tInitSensor(&Options{})\n\t}\n\tgo sensor.agent.request(sensor.agent.makeURL(agentEventURL), \"POST\", event)\n}\n\nfunc SendHostEvent(title string, text string, sev severity, duration time.Duration) ", "output": "{\n\tsendEvent(&EventData{\n\t\tTitle: title,\n\t\tText: text,\n\t\tDuration: int(duration / time.Millisecond),\n\t\tSeverity: int(sev),\n\t})\n}"} {"input": "package fake_filter_provider\n\nimport (\n\t\"sync\"\n\n\t\"code.cloudfoundry.org/garden-linux/network\"\n\t\"code.cloudfoundry.org/garden-linux/resource_pool\"\n)\n\ntype FakeFilterProvider struct {\n\tProvideFilterStub func(containerId string) network.Filter\n\tprovideFilterMutex sync.RWMutex\n\tprovideFilterArgsForCall []struct {\n\t\tcontainerId string\n\t}\n\tprovideFilterReturns struct {\n\t\tresult1 network.Filter\n\t}\n}\n\n\n\nfunc (fake *FakeFilterProvider) ProvideFilterCallCount() int {\n\tfake.provideFilterMutex.RLock()\n\tdefer fake.provideFilterMutex.RUnlock()\n\treturn len(fake.provideFilterArgsForCall)\n}\n\nfunc (fake *FakeFilterProvider) ProvideFilterArgsForCall(i int) string {\n\tfake.provideFilterMutex.RLock()\n\tdefer fake.provideFilterMutex.RUnlock()\n\treturn fake.provideFilterArgsForCall[i].containerId\n}\n\nfunc (fake *FakeFilterProvider) ProvideFilterReturns(result1 network.Filter) {\n\tfake.ProvideFilterStub = nil\n\tfake.provideFilterReturns = struct {\n\t\tresult1 network.Filter\n\t}{result1}\n}\n\nvar _ resource_pool.FilterProvider = new(FakeFilterProvider)\n\nfunc (fake *FakeFilterProvider) ProvideFilter(containerId string) network.Filter ", "output": "{\n\tfake.provideFilterMutex.Lock()\n\tfake.provideFilterArgsForCall = append(fake.provideFilterArgsForCall, struct {\n\t\tcontainerId string\n\t}{containerId})\n\tfake.provideFilterMutex.Unlock()\n\tif fake.ProvideFilterStub != nil {\n\t\treturn fake.ProvideFilterStub(containerId)\n\t} else {\n\t\treturn fake.provideFilterReturns.result1\n\t}\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/clients/generated/client/clientset/versioned/typed/cloudidentity/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeCloudidentityV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeCloudidentityV1beta1) CloudIdentityGroups(namespace string) v1beta1.CloudIdentityGroupInterface {\n\treturn &FakeCloudIdentityGroups{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeCloudidentityV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeCloudidentityV1beta1) CloudIdentityMemberships(namespace string) v1beta1.CloudIdentityMembershipInterface ", "output": "{\n\treturn &FakeCloudIdentityMemberships{c, namespace}\n}"} {"input": "package connect\n\nimport \"io\"\nimport \"github.com/LilyPad/GoLilyPad/packet\"\n\ntype RequestAuthenticate struct {\n\tUsername string\n\tPassword string\n}\n\nfunc NewRequestAuthenticate(username string, password string) (this *RequestAuthenticate) {\n\tthis = new(RequestAuthenticate)\n\tthis.Username = username\n\tthis.Password = password\n\treturn\n}\n\nfunc (this *RequestAuthenticate) Id() int {\n\treturn REQUEST_AUTHENTICATE\n}\n\ntype requestAuthenticateCodec struct {\n\n}\n\nfunc (this *requestAuthenticateCodec) Decode(reader io.Reader) (request Request, err error) {\n\trequestAuthenticate := new(RequestAuthenticate)\n\trequestAuthenticate.Username, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\trequestAuthenticate.Password, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\trequest = requestAuthenticate\n\treturn\n}\n\nfunc (this *requestAuthenticateCodec) Encode(writer io.Writer, request Request) (err error) {\n\trequestAuthenticate := request.(*RequestAuthenticate)\n\terr = packet.WriteString(writer, requestAuthenticate.Username)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = packet.WriteString(writer, requestAuthenticate.Password)\n\treturn\n}\n\ntype ResultAuthenticate struct {\n\n}\n\nfunc NewResultAuthenticate() (this *ResultAuthenticate) {\n\tthis = new(ResultAuthenticate)\n\treturn\n}\n\nfunc (this *ResultAuthenticate) Id() int {\n\treturn REQUEST_AUTHENTICATE\n}\n\ntype resultAuthenticateCodec struct {\n\n}\n\n\n\nfunc (this *resultAuthenticateCodec) Encode(writer io.Writer, result Result) (err error) {\n\treturn\n}\n\nfunc (this *resultAuthenticateCodec) Decode(reader io.Reader) (result Result, err error) ", "output": "{\n\tresult = new(ResultAuthenticate)\n\treturn\n}"} {"input": "package mvcc\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"go.etcd.io/etcd/v3/lease\"\n\t\"go.etcd.io/etcd/v3/mvcc/backend\"\n\n\t\"go.uber.org/zap\"\n)\n\n\n\nfunc BenchmarkKVWatcherMemoryUsage(b *testing.B) ", "output": "{\n\tbe, tmpPath := backend.NewDefaultTmpBackend()\n\twatchable := newWatchableStore(zap.NewExample(), be, &lease.FakeLessor{}, nil, StoreConfig{})\n\n\tdefer cleanup(watchable, be, tmpPath)\n\n\tw := watchable.NewWatchStream()\n\n\tb.ReportAllocs()\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tw.Watch(0, []byte(fmt.Sprint(\"foo\", i)), nil, 0)\n\t}\n}"} {"input": "package main\n\ntype Move struct {\n\tSrc Point\n\tDest Point\n}\n\nvar EmptyMove = Move{Point{0, 0}, Point{0, 0}}\n\nfunc NewMove(src Point, dest Point) Move {\n\ts, d := src, dest\n\tif s.X > d.X {\n\t\ts.X, d.X = d.X, s.X\n\t}\n\tif s.Y > d.Y {\n\t\ts.Y, d.Y = d.Y, s.Y\n\t}\n\n\treturn Move{src, dest}\n}\n\nfunc (m Move) String() string {\n\treturn m.Src.String() + \">\" + m.Dest.String()\n}\n\nfunc (m Move) Valid(table Table) bool {\n\tfor x := m.Src.X; x <= m.Dest.X; x++ {\n\t\tfor y := m.Src.Y; y <= m.Dest.Y; y++ {\n\t\t\tcell := table[y][x]\n\t\t\tswitch cell {\n\t\t\tcase HOLLOW, LAND:\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}\n\n\n\nfunc (m Move) Apply(t Table) ", "output": "{\n\tdist := m.Src.DistanceTo(m.Dest) + 1\n\tdist /= 2\n\n\tif m.Src.X == m.Dest.X {\n\t\tfor i := 0; i < dist; i++ {\n\t\t\tt.SwapY(m.Src.X, m.Src.Y+i, m.Dest.Y-i)\n\t\t}\n\n\t} else if m.Src.Y == m.Dest.Y {\n\t\tfor i := 0; i < dist; i++ {\n\t\t\tt.SwapX(m.Src.Y, m.Src.X+i, m.Dest.X-i)\n\t\t}\n\n\t} else {\n\t\tpanic(\"Diagonal move is not supported!\")\n\t}\n\n\n\n\tfor t.Resolve() > 0 {\n\t}\n}"} {"input": "package mocks\n\nimport mock \"github.com/stretchr/testify/mock\"\n\n\ntype Allow struct {\n\tmock.Mock\n}\n\n\n\n\n\nfunc (_m *Allow) Member(email string) bool {\n\tret := _m.Called(email)\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func(string) bool); ok {\n\t\tr0 = rf(email)\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\treturn r0\n}\n\nfunc (_m *Allow) Emails() []string ", "output": "{\n\tret := _m.Called()\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func() []string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\treturn r0\n}"} {"input": "package api\n\ntype FormatsResponse struct {\n\tFormats []string `json:\"formats\"`\n}\n\nfunc (a *API) getFormats(ctx *context) {\n\tctx.Success(FormatsResponse{Formats: a.c.formats.Keys()})\n}\n\ntype LeechTypesResponse struct {\n\tLeechTypes []string `json:\"leech_types\"`\n}\n\nfunc (a *API) getLeechTypes(ctx *context) {\n\tctx.Success(LeechTypesResponse{LeechTypes: a.c.leechTypes.Keys()})\n}\n\ntype MediaResponse struct {\n\tMedia []string `json:\"media\"`\n}\n\nfunc (a *API) getMedia(ctx *context) {\n\tctx.Success(MediaResponse{Media: a.c.media.Keys()})\n}\n\ntype ReleaseGroupTypesResponse struct {\n\tReleaseGroupTypes []string `json:\"release_group_types\"`\n}\n\n\n\ntype ReleasePropertiesResponse struct {\n\tReleaseProperties []string `json:\"release_properties\"`\n}\n\nfunc (a *API) getReleaseProperties(ctx *context) {\n\tctx.Success(ReleasePropertiesResponse{ReleaseProperties: a.c.releaseProperties.Keys()})\n}\n\ntype ReleaseRolesResponse struct {\n\tReleaseRoles []string `json:\"release_roles\"`\n}\n\nfunc (a *API) getReleaseRoles(ctx *context) {\n\tctx.Success(ReleaseRolesResponse{ReleaseRoles: a.c.releaseRoles.Keys()})\n}\n\ntype PrivilegesResponse struct {\n\tPrivileges []string `json:\"privileges\"`\n}\n\nfunc (a *API) getPrivileges(ctx *context) {\n\tctx.Success(PrivilegesResponse{Privileges: a.c.privileges.Keys()})\n}\n\nfunc (a *API) getReleaseGroupTypes(ctx *context) ", "output": "{\n\tctx.Success(ReleaseGroupTypesResponse{ReleaseGroupTypes: a.c.releaseGroupTypes.Keys()})\n}"} {"input": "package form\n\nimport (\n\t\"io\"\n\n\t\"gnd.la/html\"\n)\n\n\n\n\n\n\ntype Renderer interface {\n\tBeginField(w io.Writer, field *Field) error\n\tBeginLabel(w io.Writer, field *Field, label string, pos int) error\n\tLabelAttributes(field *Field, pos int) (html.Attrs, error)\n\tEndLabel(w io.Writer, field *Field, pos int) error\n\tBeginInput(w io.Writer, field *Field, placeholder string, pos int) error\n\tFieldAttributes(field *Field, pos int) (html.Attrs, error)\n\tEndInput(w io.Writer, field *Field, pos int) error\n\tWriteAddOn(w io.Writer, field *Field, addon *AddOn) error\n\tWriteError(w io.Writer, field *Field, err error) error\n\tWriteHelp(w io.Writer, field *Field, help string) error\n\tEndField(w io.Writer, field *Field) error\n}\n\nvar (\n\trendererFunc func() Renderer\n)\n\n\n\n\n\n\nfunc DefaultRenderer() Renderer {\n\tif rendererFunc != nil {\n\t\treturn rendererFunc()\n\t}\n\treturn nil\n}\n\nfunc SetDefaultRenderer(f func() Renderer) ", "output": "{\n\trendererFunc = f\n}"} {"input": "package utilmocks\n\nimport (\n\tcontext \"context\"\n\tgomock \"github.com/golang/mock/gomock\"\n\texec \"os/exec\"\n\treflect \"reflect\"\n)\n\n\ntype MockCommandRunner struct {\n\tctrl *gomock.Controller\n\trecorder *MockCommandRunnerMockRecorder\n}\n\n\ntype MockCommandRunnerMockRecorder struct {\n\tmock *MockCommandRunner\n}\n\n\nfunc NewMockCommandRunner(ctrl *gomock.Controller) *MockCommandRunner {\n\tmock := &MockCommandRunner{ctrl: ctrl}\n\tmock.recorder = &MockCommandRunnerMockRecorder{mock}\n\treturn mock\n}\n\n\n\n\n\nfunc (m *MockCommandRunner) Run(ctx context.Context, command *exec.Cmd) ([]byte, []byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Run\", ctx, command)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].([]byte)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}\n\n\nfunc (mr *MockCommandRunnerMockRecorder) Run(ctx, command interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Run\", reflect.TypeOf((*MockCommandRunner)(nil).Run), ctx, command)\n}\n\nfunc (m *MockCommandRunner) EXPECT() *MockCommandRunnerMockRecorder ", "output": "{\n\treturn m.recorder\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\ntype Response struct {\n\tStatus string `json:\"status\"`\n\tErrorText string `json:\"errorText,omitempty\"`\n\tAddress string `json:\"address,omitempty\"`\n\tStatusCode int `json:\"statusCode,omitempty\"`\n\tVersion string `json:\"version,omitempty\"`\n}\n\ntype Responses struct {\n\tResponses []Response `json:\"responses\"`\n}\n\nfunc (r *Response) Fill(outStr string, err error) {\n\tif err != nil {\n\t\tr.Status = \"ERR\"\n\t\tr.ErrorText = strings.TrimSpace(outStr + \" \" + err.Error())\n\t} else {\n\t\tr.Status = \"OK\"\n\t}\n}\n\nfunc (r Responses) String() string {\n\tj, _ := json.Marshal(r)\n\treturn fmt.Sprintf(\"Responses: %s\", string(j))\n}\n\nfunc (r Response) String() string {\n\tj, _ := json.Marshal(r)\n\treturn fmt.Sprintf(\"Response: %s\", string(j))\n}\n\nfunc (r Response) WriteHttp(w http.ResponseWriter) (resp Response) {\n\tif r.StatusCode == 0 {\n\t\tr.StatusCode = 200\n\t}\n\tw.WriteHeader(r.StatusCode)\n\treturn EncodeJson(r, w)\n}\n\nfunc (r Response) WriteBadRequestHttp(w http.ResponseWriter) (resp Response) {\n\tw.WriteHeader(http.StatusBadRequest)\n\tr.StatusCode = http.StatusBadRequest\n\treturn EncodeJson(r, w)\n}\n\n\n\nfunc EncodeJson(r Response, w http.ResponseWriter) (resp Response) {\n\terr := json.NewEncoder(w).Encode(r)\n\tif err != nil {\n\t\tlog.Printf(\"[writehttp] failed to create json from model: %s\", err.Error())\n\t}\n\treturn r\n}\n\nfunc (r Response) WriteInternalServerErrorHttp(w http.ResponseWriter) (resp Response) ", "output": "{\n\tw.WriteHeader(http.StatusInternalServerError)\n\tr.StatusCode = http.StatusInternalServerError\n\treturn EncodeJson(r, w)\n}"} {"input": "package main\n\nimport \"fmt\"\n\ntype QU struct {\n\tid []int\n}\n\nfunc (q *QU) Init(size int) {\n\tfor i := 0; i < size; i++ {\n\t\tq.id = append(q.id, i)\n\t}\n}\n\nfunc (q *QU) Root(i int) int {\n\tfor i != q.id[i] {\n\t\ti = q.id[i]\n\t}\n\treturn i\n}\n\n\n\nfunc (q *QU) Connected(a int, b int) bool {\n\treturn q.Root(a) == q.Root(b)\n}\n\nfunc main() {\n\tqu := QU{}\n\tqu.Init(10)\n\tfmt.Printf(\"Array initialized. %v\", qu.id)\n\tqu.Union(3, 4)\n\tqu.Union(4, 8)\n\tfmt.Printf(\"\\n\\n%v is Connected to %v %v\", 3, 8, qu.Connected(3, 8))\n}\n\nfunc (q *QU) Union(a int, b int) ", "output": "{\n\ti := q.Root(a)\n\tj := q.Root(b)\n\tq.id[i] = j\n}"} {"input": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"encoding/json\"\n \"os\"\n)\n\n\n\n\ntype argsEnvVarReport struct {\n Arguments []string `json:\"arguments\"`\n EnvVars []string `json:\"envvars\"`\n}\n\n\n\n\n\nfunc main() {\n fmt.Println(Report(os.Args[0:], os.Environ()))\n\n os.Exit(0)\n}\n\nfunc Report(args, envs []string) string ", "output": "{\n report := argsEnvVarReport{ Arguments: args, EnvVars: envs}\n\n buffer := &bytes.Buffer{}\n if err := json.NewEncoder(buffer).Encode(report); err != nil {\n panic(fmt.Sprintf(\"%s\\n\", err.Error()))\n }\n\n return buffer.String()\n}"} {"input": "package cpumanager\n\nimport (\n\t\"k8s.io/api/core/v1\"\n\t\"k8s.io/klog\"\n\t\"k8s.io/kubernetes/pkg/kubelet/cm/cpumanager/state\"\n\t\"k8s.io/kubernetes/pkg/kubelet/cm/topologymanager\"\n)\n\ntype nonePolicy struct{}\n\nvar _ Policy = &nonePolicy{}\n\n\nconst PolicyNone policyName = \"none\"\n\n\nfunc NewNonePolicy() Policy {\n\treturn &nonePolicy{}\n}\n\nfunc (p *nonePolicy) Name() string {\n\treturn string(PolicyNone)\n}\n\nfunc (p *nonePolicy) Start(s state.State) {\n\tklog.Info(\"[cpumanager] none policy: Start\")\n}\n\nfunc (p *nonePolicy) AddContainer(s state.State, pod *v1.Pod, container *v1.Container) error {\n\treturn nil\n}\n\nfunc (p *nonePolicy) RemoveContainer(s state.State, podUID string, containerName string) error {\n\treturn nil\n}\n\n\n\nfunc (p *nonePolicy) GetTopologyHints(s state.State, pod v1.Pod, container v1.Container) map[string][]topologymanager.TopologyHint ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"sync\"\n\n\t\"github.com/open-policy-agent/opa/cmd\"\n\t\"github.com/open-policy-agent/opa/plugins\"\n\t\"github.com/open-policy-agent/opa/plugins/logs\"\n\t\"github.com/open-policy-agent/opa/runtime\"\n\t\"github.com/open-policy-agent/opa/util\"\n)\n\ntype Config struct {\n\tStderr bool `json:\"stderr\"`\n}\n\ntype Factory struct{}\n\nfunc (Factory) New(_ *plugins.Manager, config interface{}) plugins.Plugin {\n\treturn &PrintlnLogger{\n\t\tconfig: config.(Config),\n\t}\n}\n\nfunc (Factory) Validate(_ *plugins.Manager, config []byte) (interface{}, error) {\n\tparsedConfig := Config{}\n\treturn parsedConfig, util.Unmarshal(config, &parsedConfig)\n}\n\ntype PrintlnLogger struct {\n\tconfig Config\n\tmtx sync.Mutex\n}\n\n\n\nfunc (p *PrintlnLogger) Stop(ctx context.Context) {\n}\n\nfunc (p *PrintlnLogger) Reconfigure(ctx context.Context, config interface{}) {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tp.config = config.(Config)\n}\n\nfunc (p *PrintlnLogger) Log(ctx context.Context, event logs.EventV1) error {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tw := os.Stdout\n\tif p.config.Stderr {\n\t\tw = os.Stderr\n\t}\n\tfmt.Fprintln(w, event) \n\treturn nil\n}\n\nfunc main() {\n\n\truntime.RegisterPlugin(\"println_decision_logger\", Factory{})\n\n\tif err := cmd.RootCommand.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc (p *PrintlnLogger) Start(ctx context.Context) error ", "output": "{\n\treturn nil\n}"} {"input": "package leetcode\n\n\n\n\n\ntype MyStack struct {\n\telements []int\n}\n\n\nfunc NewMyStack() MyStack {\n\treturn MyStack{}\n}\n\n\nfunc (this *MyStack) Push(x int) {\n\tthis.elements = append(this.elements, x)\n}\n\n\nfunc (this *MyStack) Pop() int {\n\tn := len(this.elements)\n\te := this.elements[n-1]\n\tthis.elements = this.elements[:n-1]\n\treturn e\n}\n\n\n\n\n\nfunc (this *MyStack) Empty() bool {\n\treturn len(this.elements) == 0\n}\n\nfunc (this *MyStack) Top() int ", "output": "{\n\treturn this.elements[len(this.elements)-1]\n}"} {"input": "package udnssdk\n\nimport (\n\t\"log\"\n\t\"time\"\n)\n\n\ntype AlertsService struct {\n\tclient *Client\n}\n\n\ntype ProbeAlertDataDTO struct {\n\tPoolRecord string `json:\"poolRecord\"`\n\tProbeType string `json:\"probeType\"`\n\tProbeStatus string `json:\"probeStatus\"`\n\tAlertDate time.Time `json:\"alertDate\"`\n\tFailoverOccured bool `json:\"failoverOccured\"`\n\tOwnerName string `json:\"ownerName\"`\n\tStatus string `json:\"status\"`\n}\n\n\ntype ProbeAlertDataListDTO struct {\n\tAlerts []ProbeAlertDataDTO `json:\"alerts\"`\n\tQueryinfo QueryInfo `json:\"queryInfo\"`\n\tResultinfo ResultInfo `json:\"resultInfo\"`\n}\n\n\nfunc (s *AlertsService) Select(k RRSetKey) ([]ProbeAlertDataDTO, error) {\n\tmaxerrs := 5\n\twaittime := 5 * time.Second\n\n\tas := []ProbeAlertDataDTO{}\n\toffset := 0\n\terrcnt := 0\n\n\tfor {\n\t\treqAlerts, ri, res, err := s.SelectWithOffset(k, offset)\n\t\tif err != nil {\n\t\t\tif res.StatusCode >= 500 {\n\t\t\t\terrcnt = errcnt + 1\n\t\t\t\tif errcnt < maxerrs {\n\t\t\t\t\ttime.Sleep(waittime)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn as, err\n\t\t}\n\n\t\tlog.Printf(\"ResultInfo: %+v\\n\", ri)\n\t\tfor _, a := range reqAlerts {\n\t\t\tas = append(as, a)\n\t\t}\n\t\tif ri.ReturnedCount+ri.Offset >= ri.TotalCount {\n\t\t\treturn as, nil\n\t\t}\n\t\toffset = ri.ReturnedCount + ri.Offset\n\t\tcontinue\n\t}\n}\n\n\n\n\nfunc (s *AlertsService) SelectWithOffset(k RRSetKey, offset int) ([]ProbeAlertDataDTO, ResultInfo, *Response, error) ", "output": "{\n\tvar ald ProbeAlertDataListDTO\n\n\turi := k.AlertsQueryURI(offset)\n\tres, err := s.client.get(uri, &ald)\n\n\tas := []ProbeAlertDataDTO{}\n\tfor _, a := range ald.Alerts {\n\t\tas = append(as, a)\n\t}\n\treturn as, ald.Resultinfo, res, err\n}"} {"input": "package tests\n\nimport (\n log \"github.com/janekolszak/revfluent\"\n \"github.com/revel/revel/testing\"\n)\n\ntype AppTest struct {\n testing.TestSuite\n}\n\nfunc (t *AppTest) TestError() {\n data := map[string]string{\"message\": \"Error\"}\n log.Error(data)\n}\n\nfunc (t *AppTest) TestDebug() {\n data := map[string]string{\"message\": \"Debug\"}\n log.Debug(data)\n}\n\nfunc (t *AppTest) TestInfo() {\n data := map[string]string{\"message\": \"Info\"}\n log.Info(data)\n}\n\nfunc (t *AppTest) TestLog() {\n data := map[string]string{\"message\": \"Log\"}\n log.Log(\"tag\", data)\n}\n\n\n\nfunc (t *AppTest) TestLogger() ", "output": "{\n data := map[string]string{\"message\": \"Logger\"}\n log.Logger.Post(\"tag\", data)\n}"} {"input": "package test\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"testing\"\n)\n\n\n\nfunc TestCodeAuth(t *testing.T) ", "output": "{\n\tgo startTestServer()\n\n\tcfg := OConfig\n\n\tcfg.ClientID = CLIENT_ID\n\tcfg.ClientSecret = CLIENT_SECRET\n\n\taurl := cfg.AuthCodeURL(\"state\")\n\tlq, _ := url.ParseQuery(fastHttpGet(nil, aurl, t))\n\tcq := fastHttpPost(nil, LOGIN_URL, lq, t)\n\tif cq != NICKNAME {\n\t\tfmt.Println(\"failed\")\n\t}\n}"} {"input": "package backend\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nconst SHOPPING_CART_TOTAL = 9.94\n\nvar discounts map[string]float32\n\nfunc InitCheckout() {\n\tRegisterHandler(\"/checkout/shopping-cart\", handleShoppingCart)\n\tRegisterHandler(\"/checkout/apply-code\", handleApplyCode)\n\tdiscounts = make(map[string]float32)\n}\n\nfunc handleApplyCode(w http.ResponseWriter, r *http.Request) {\n\tSetMaxAge(w, 0)\n\tif r.Method == \"POST\" {\n\t\tclientId := r.FormValue(\"clientId\")\n\t\tdiscounts[clientId] = 0.2\n\t\twriteShoppingCart(w, r, clientId)\n\t}\n}\n\nfunc handleShoppingCart(w http.ResponseWriter, r *http.Request) {\n\tSetMaxAge(w, 0)\n\tif r.Method == \"GET\" {\n\t\tclientId := r.URL.Query().Get(\"clientId\")\n\t\twriteShoppingCart(w, r, clientId)\n\t}\n}\n\nfunc writeShoppingCart(w http.ResponseWriter, r *http.Request, clientId string) {\n\tdiscount := discounts[clientId]\n\ttotal := SHOPPING_CART_TOTAL - SHOPPING_CART_TOTAL*discount\n\tcart := createShoppingCart()\n\tcart[\"total\"] = fmt.Sprintf(\"%.2f\", total)\n\tif discount > 0 {\n\t\tcart[\"discount\"] = fmt.Sprintf(\"%g%%\", (discount * 100))\n\t}\n\tSendJsonResponse(w, cart)\n}\n\n\n\nfunc createShoppingCart() map[string]interface{} ", "output": "{\n\treturn map[string]interface{}{\n\t\t\"items\": []interface{}{\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"name\": \"Item 1\",\n\t\t\t\t\"price\": \"1.99\",\n\t\t\t\t\"quantity\": \"2\",\n\t\t\t},\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"name\": \"Item 2\",\n\t\t\t\t\"price\": \"2.99\",\n\t\t\t\t\"quantity\": \"1\",\n\t\t\t},\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"name\": \"Item 3\",\n\t\t\t\t\"price\": \"0.99\",\n\t\t\t\t\"quantity\": \"3\",\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package encoder\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"crypto\"\n\t\"github.com/bysir-zl/bygo/util\"\n)\n\n\n\nfunc Hash(in []byte, hash crypto.Hash) (out []byte) {\n\th := hash.New()\n\th.Write(in)\n\tmd := h.Sum(nil)\n\tout = make([]byte, hex.EncodedLen(len(md)))\n\thex.Encode(out, md)\n\treturn\n}\n\nfunc HashString(in string, hash crypto.Hash) (out string) {\n\th := hash.New()\n\th.Write(util.S2B(in))\n\tmd := h.Sum(nil)\n\tout = hex.EncodeToString(md)\n\treturn\n}\n\nfunc Sha256(in string) string ", "output": "{\n\thash := sha256.New()\n\thash.Write([]byte(in))\n\tmd := hash.Sum(nil)\n\tmdStr := hex.EncodeToString(md)\n\treturn mdStr\n}"} {"input": "package queue\n\nimport (\n\t\"fmt\"\n\t\"github.com/apache/servicecomb-service-center/pkg/log\"\n\t\"golang.org/x/net/context\"\n)\n\ntype UniQueue struct {\n\tqueue chan interface{}\n}\n\nfunc (uq *UniQueue) Get(ctx context.Context) interface{} {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil\n\tcase item := <-uq.queue:\n\t\treturn item\n\t}\n}\n\nfunc (uq *UniQueue) Chan() <-chan interface{} {\n\treturn uq.queue\n}\n\nfunc (uq *UniQueue) Put(value interface{}) (e error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.LogPanic(r)\n\n\t\t\te = fmt.Errorf(\"%v\", r)\n\t\t}\n\t}()\n\n\tselect {\n\tcase _, ok := <-uq.queue:\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"channel is closed\")\n\t\t}\n\tdefault:\n\t}\n\n\tselect {\n\tcase uq.queue <- value:\n\tdefault:\n\t}\n\treturn\n}\n\n\n\nfunc NewUniQueue() (uq *UniQueue) {\n\treturn &UniQueue{\n\t\tqueue: make(chan interface{}, 1),\n\t}\n}\n\nfunc (uq *UniQueue) Close() ", "output": "{\n\tselect {\n\tcase _, ok := <-uq.queue:\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\tdefault:\n\t}\n\tclose(uq.queue)\n}"} {"input": "package update\n\nimport (\n\t\"github.com/andreaskoch/allmark/common/route\"\n\t\"fmt\"\n\t\"golang.org/x/net/websocket\"\n)\n\nfunc NewConnection(hub *Hub, ws *websocket.Conn, route route.Route) *connection {\n\treturn &connection{\n\t\tRoute: route,\n\n\t\thub: hub,\n\t\tsend: make(chan Message, 10),\n\t\tws: ws,\n\t}\n}\n\ntype connection struct {\n\tRoute route.Route\n\n\thub *Hub\n\n\tws *websocket.Conn\n\n\tsend chan Message\n}\n\nfunc (c *connection) String() string {\n\treturn fmt.Sprintf(\"Connection (Route: %s, IP: %s)\", c.Route.String(), c.ws.Request().RemoteAddr)\n}\n\n\n\nfunc (c *connection) Reader() {\n\tfor {\n\t\tvar message Message\n\t\terr := websocket.JSON.Receive(c.ws, &message)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tc.hub.broadcast <- message\n\t}\n\n\tc.ws.Close()\n\tc.hub.Unsubscribe(c)\n}\n\nfunc (c *connection) Writer() {\n\tfor message := range c.send {\n\t\terr := websocket.JSON.Send(c.ws, message)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tc.ws.Close()\n\tc.hub.Unsubscribe(c)\n}\n\nfunc (c *connection) Send(msg Message) ", "output": "{\n\tc.send <- msg\n}"} {"input": "package waas\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype ThreatFeedAction struct {\n\n\tKey *string `mandatory:\"true\" json:\"key\"`\n\n\tAction ThreatFeedActionActionEnum `mandatory:\"true\" json:\"action\"`\n}\n\n\n\n\ntype ThreatFeedActionActionEnum string\n\n\nconst (\n\tThreatFeedActionActionOff ThreatFeedActionActionEnum = \"OFF\"\n\tThreatFeedActionActionDetect ThreatFeedActionActionEnum = \"DETECT\"\n\tThreatFeedActionActionBlock ThreatFeedActionActionEnum = \"BLOCK\"\n)\n\nvar mappingThreatFeedActionAction = map[string]ThreatFeedActionActionEnum{\n\t\"OFF\": ThreatFeedActionActionOff,\n\t\"DETECT\": ThreatFeedActionActionDetect,\n\t\"BLOCK\": ThreatFeedActionActionBlock,\n}\n\n\nfunc GetThreatFeedActionActionEnumValues() []ThreatFeedActionActionEnum {\n\tvalues := make([]ThreatFeedActionActionEnum, 0)\n\tfor _, v := range mappingThreatFeedActionAction {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}\n\nfunc (m ThreatFeedAction) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package main\n\n\nimport (\n \"fmt\"\n\n \"github.com/aws/aws-sdk-go/aws/session\"\n \"github.com/aws/aws-sdk-go/service/ec2\"\n)\n\n\n\n\n\n\n\n\n\n\nfunc main() {\n \n sess := session.Must(session.NewSessionWithOptions(session.Options{\n SharedConfigState: session.SharedConfigEnable,\n }))\n \n\n result, err := GetSecurityGroupInfo(sess)\n if err != nil {\n fmt.Println(\"Got an error retrieving information about your security groups:\")\n fmt.Println(err)\n return\n }\n\n \n for _, group := range result.SecurityGroups {\n fmt.Println(*group.GroupName)\n fmt.Println(\" Description: \" + *group.Description)\n fmt.Println(\" Group ID: \" + *group.GroupId)\n fmt.Println(\"\")\n }\n\n fmt.Println(\"Found\", len(result.SecurityGroups), \"security groups\")\n \n}\n\nfunc GetSecurityGroupInfo(sess *session.Session) (*ec2.DescribeSecurityGroupsOutput, error) ", "output": "{\n \n svc := ec2.New(sess)\n\n result, err := svc.DescribeSecurityGroups(nil)\n \n if err != nil {\n return nil, err\n }\n\n return result, nil\n}"} {"input": "package bridge\n\ntype setupStep func(*networkConfiguration, *bridgeInterface) error\n\ntype bridgeSetup struct {\n\tconfig *networkConfiguration\n\tbridge *bridgeInterface\n\tsteps []setupStep\n}\n\n\n\nfunc (b *bridgeSetup) apply() error {\n\tfor _, fn := range b.steps {\n\t\tif err := fn(b.config, b.bridge); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (b *bridgeSetup) queueStep(step setupStep) {\n\tb.steps = append(b.steps, step)\n}\n\nfunc newBridgeSetup(c *networkConfiguration, i *bridgeInterface) *bridgeSetup ", "output": "{\n\treturn &bridgeSetup{config: c, bridge: i}\n}"} {"input": "package config\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/BurntSushi/toml\"\n)\n\ntype Config struct {\n\tWeb *WebConfig `toml:\"web\"`\n\tBot *BotConfig `toml:\"bot\"`\n}\n\ntype BotConfig struct {\n\tChannelId int `toml:\"channel_id\"`\n\tChannelSecret string `toml:\"channel_secret\"`\n\tMID string `toml:\"channel_mid\"`\n\tClientWorkerQueueSize int `toml:\"client_worker_queue_size\"`\n\tEventDispatcherQueueSize int `toml:\"event_dispatcher_queue_size\"`\n}\n\ntype WebConfig struct {\n\tHost string `toml:\"host\"`\n\tPort int `toml:\"port\"`\n}\n\nfunc (wc *WebConfig) Address() string {\n\treturn fmt.Sprintf(\"%s:%d\", wc.Host, wc.Port)\n}\n\n\n\nfunc LoadFromFile(filePath string) *Config ", "output": "{\n\tvar c Config\n\tif _, err := toml.DecodeFile(filePath, &c); err != nil {\n\t\tlog.Fatalf(\"Failed to read config file: %s\", err.Error())\n\t}\n\treturn &c\n}"} {"input": "package main\n\nimport (\n\t\"github.com/mjibson/appstats\"\n)\n\n\n\nfunc stats(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) ", "output": "{\n\tc := appstats.NewContext(req.Request)\n\tchain.ProcessFilter(req, resp)\n\tc.Stats.Status = resp.StatusCode()\n\tc.Save()\n}"} {"input": "package datatype\n\nimport \"fmt\"\n\n\ntype OctetString string\n\n\nfunc DecodeOctetString(b []byte) (Type, error) {\n\treturn OctetString(b), nil\n}\n\n\nfunc (s OctetString) Serialize() []byte {\n\treturn []byte(s)\n}\n\n\nfunc (s OctetString) Len() int {\n\treturn len(s)\n}\n\n\n\n\n\nfunc (s OctetString) Type() TypeID {\n\treturn OctetStringType\n}\n\n\nfunc (s OctetString) String() string {\n\treturn fmt.Sprintf(\"OctetString{%#x},Padding:%d\", string(s), s.Padding())\n}\n\nfunc (s OctetString) Padding() int ", "output": "{\n\tl := len(s)\n\treturn pad4(l) - l\n}"} {"input": "package initramfs\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/u-root/u-root/pkg/cpio\"\n\t\"github.com/u-root/u-root/pkg/ulog\"\n)\n\n\ntype CPIOArchiver struct {\n\tcpio.RecordFormat\n}\n\n\n\n\n\n\n\n\n\ntype osWriter struct {\n\tcpio.RecordWriter\n\n\tf *os.File\n}\n\n\nfunc (o osWriter) Finish() error {\n\terr := cpio.WriteTrailer(o)\n\to.f.Close()\n\treturn err\n}\n\n\nfunc (ca CPIOArchiver) Reader(r io.ReaderAt) Reader {\n\treturn ca.RecordFormat.Reader(r)\n}\n\nfunc (ca CPIOArchiver) OpenWriter(l ulog.Logger, path, goos, goarch string) (Writer, error) ", "output": "{\n\tif len(path) == 0 && len(goos) == 0 && len(goarch) == 0 {\n\t\treturn nil, fmt.Errorf(\"passed no path, GOOS, and GOARCH to CPIOArchiver.OpenWriter\")\n\t}\n\tif len(path) == 0 {\n\t\tpath = fmt.Sprintf(\"/tmp/initramfs.%s_%s.cpio\", goos, goarch)\n\t}\n\tf, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tl.Printf(\"Filename is %s\", path)\n\treturn osWriter{ca.RecordFormat.Writer(f), f}, nil\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/crackcell/asciitype/engine\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc showHelp() {\n\tfmt.Println(\"usage: asciifont -f [font file]\")\n}\n\nfunc readStdin() {\n\treader := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tline, err := reader.ReadString('\\n')\n\t\tline = strings.Trim(line, \"\\n\")\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n\n\nfunc main() {\n\th := flag.Bool(\"h\", false, \"show help messages\")\n\tf := flag.String(\"f\", \"./fonts/tukasans.afont\", \"specify font file\")\n\tflag.Parse()\n\tif *h {\n\t\tshowHelp()\n\t\treturn\n\t}\n\n\tst := new(engine.SymbolTable)\n\tst.Load(*f)\n\n\tfb := engine.NewFramebuffer()\n\n\treader := bufio.NewReader(os.Stdin)\n\n\tfor {\n\t\tline, err := reader.ReadString('\\n')\n\t\tline = strings.Trim(line, \"\\n\")\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tconvert(line, fb, st)\n\t}\n\n}\n\nfunc convert(raw string, fb *engine.Framebuffer, st *engine.SymbolTable) ", "output": "{\n\tfb.Clear()\n\traw = strings.ToUpper(raw)\n\tfor _, r := range raw {\n\t\tfb.Append(st.GetSymbol(r))\n\t}\n\n\tfb.Flush(os.Stdout)\n}"} {"input": "package schedulercache\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/labels\"\n\t\"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache\"\n)\n\n\ntype FakeCache struct {\n\tAssumeFunc func(*api.Pod)\n}\n\nfunc (f *FakeCache) AssumePod(pod *api.Pod) error {\n\tf.AssumeFunc(pod)\n\treturn nil\n}\n\nfunc (f *FakeCache) AddPod(pod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) UpdatePod(oldPod, newPod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) RemovePod(pod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) AddNode(node *api.Node) error { return nil }\n\nfunc (f *FakeCache) UpdateNode(oldNode, newNode *api.Node) error { return nil }\n\nfunc (f *FakeCache) RemoveNode(node *api.Node) error { return nil }\n\nfunc (f *FakeCache) UpdateNodeNameToInfoMap(infoMap map[string]*schedulercache.NodeInfo) error {\n\treturn nil\n}\n\n\n\nfunc (f *FakeCache) List(s labels.Selector) ([]*api.Pod, error) ", "output": "{ return nil, nil }"} {"input": "package group\n\nimport (\n\t\"net/http\"\n\n\t\"k8s.io/apiserver/pkg/authentication/authenticator\"\n\t\"k8s.io/apiserver/pkg/authentication/user\"\n)\n\n\ntype AuthenticatedGroupAdder struct {\n\tAuthenticator authenticator.Request\n}\n\n\n\n\nfunc NewAuthenticatedGroupAdder(auth authenticator.Request) authenticator.Request {\n\treturn &AuthenticatedGroupAdder{auth}\n}\n\n\n\nfunc (g *AuthenticatedGroupAdder) AuthenticateRequest(req *http.Request) (user.Info, bool, error) ", "output": "{\n\tu, ok, err := g.Authenticator.AuthenticateRequest(req)\n\tif err != nil || !ok {\n\t\treturn nil, ok, err\n\t}\n\n\tif u.GetName() == user.Anonymous {\n\t\treturn u, true, nil\n\t}\n\tfor _, group := range u.GetGroups() {\n\t\tif group == user.AllAuthenticated || group == user.AllUnauthenticated {\n\t\t\treturn u, true, nil\n\t\t}\n\t}\n\n\treturn &user.DefaultInfo{\n\t\tName: u.GetName(),\n\t\tUID: u.GetUID(),\n\t\tGroups: append(u.GetGroups(), user.AllAuthenticated),\n\t\tExtra: u.GetExtra(),\n\t}, true, nil\n}"} {"input": "package integration\n\nimport (\n\t\"github.com/google/trillian/crypto/keys\"\n\t\"github.com/google/trillian/extension\"\n\tmysqlq \"github.com/google/trillian/quota/mysql\"\n\t\"github.com/google/trillian/storage/mysql\"\n)\n\n\n\n\n\nfunc NewRegistryForTests(testID string) (extension.Registry, error) ", "output": "{\n\tdb, err := GetTestDB(testID)\n\tif err != nil {\n\t\treturn extension.Registry{}, err\n\t}\n\n\treturn extension.Registry{\n\t\tAdminStorage: mysql.NewAdminStorage(db),\n\t\tSignerFactory: keys.PEMSignerFactory{},\n\t\tLogStorage: mysql.NewLogStorage(db),\n\t\tMapStorage: mysql.NewMapStorage(db),\n\t\tQuotaManager: &mysqlq.QuotaManager{DB: db, MaxUnsequencedRows: mysqlq.DefaultMaxUnsequenced},\n\t}, nil\n}"} {"input": "package main\n\nimport \"testing\"\n\nfunc TestValidateURL(t *testing.T) {\n\tif !validateURL(\"https://github.com/chadev/Chadev_ircbot\") {\n\t\tt.Error(\"failed to validate proper URL: https://github.com/chadev/Chadev_ircbot\")\n\t}\n}\n\nfunc TestGetGitHubURL(t *testing.T) {\n\tURL, err := getGitHubURL(\"Chadev_ircbot\")\n\tif err != nil {\n\t\tt.Errorf(\"failed fetching GitHub repo URL: %s\\n\", err.Error())\n\t}\n\n\tt.Logf(\"returned URL: %s\\n\", URL)\n\tif !validateGitHubURL(URL) {\n\t\tt.Error(\"the URL came back as invalid\")\n\t}\n}\n\nfunc TestGetIssueURL(t *testing.T) {\n\tURL, err := getIssueURL(\"Chadev_ircbot\")\n\tif err != nil {\n\t\tt.Errorf(\"failed fetching GitHub Issue URL: %s\\n\", err.Error())\n\t}\n\n\tt.Logf(\"returned URL: %s\\n\", URL)\n\tif !validateGitHubURL(URL) {\n\t\tt.Error(\"the URL came back as invalid\")\n\t}\n}\n\n\n\nfunc TestGetIssueIDURL(t *testing.T) ", "output": "{\n\tURL, err := getIssueURL(\"Chadev_ircbot\")\n\tif err != nil {\n\t\tt.Errorf(\"failed fetching GitHub Issue URL: %s\\n\", err.Error())\n\t}\n\n\tt.Logf(\"returned URL: %s\\n\", URL)\n\tif !validateGitHubURL(URL) {\n\t\tt.Error(\"the issue queue URL came back as invalid\")\n\t}\n\n\tURL, err = getIssueIDURL(URL, \"#1\")\n\tif err != nil {\n\t\tt.Errorf(\"failed fetching GitHub Issue URL: %s\\n\", err.Error())\n\t}\n\n\tt.Logf(\"returned URL: %s\\n\", URL)\n\tif !validateGitHubURL(URL) {\n\t\tt.Errorf(\"the issue URL came back as invalid\")\n\t}\n}"} {"input": "package controller_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/almighty/almighty-core/app/test\"\n\t\"github.com/almighty/almighty-core/controller\"\n\t\"github.com/almighty/almighty-core/gormapplication\"\n\t\"github.com/almighty/almighty-core/gormtestsupport\"\n\t\"github.com/almighty/almighty-core/resource\"\n\t\"github.com/goadesign/goa\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"github.com/stretchr/testify/suite\"\n)\n\ntype TestFiltersREST struct {\n\tgormtestsupport.DBTestSuite\n\tdb *gormapplication.GormDB\n\tclean func()\n}\n\nfunc TestRunFiltersREST(t *testing.T) {\n\tresource.Require(t, resource.Database)\n\tpwd, err := os.Getwd()\n\trequire.Nil(t, err)\n\tsuite.Run(t, &TestFiltersREST{DBTestSuite: gormtestsupport.NewDBTestSuite(pwd + \"/../config.yaml\")})\n}\n\n\n\nfunc (rest *TestFiltersREST) TestListFiltersOK() ", "output": "{\n\tsvc := goa.New(\"filterService\")\n\tctrl := controller.NewFilterController(svc, rest.Configuration)\n\tres, filters := test.ListFilterOK(rest.T(), svc.Context, svc, ctrl, nil)\n\tassert.Equal(rest.T(), 5, len(filters.Data))\n\tassertResponseHeaders(rest.T(), res)\n}"} {"input": "package main\n\nimport \"fmt\"\nimport \"time\"\n\nfunc goFunc1(f func()) {\n\tgo f()\n}\n\n\n\nfunc goFunc(f interface{}, args ...interface{}) {\n\tif len(args) > 1 {\n\t\tgo f.(func(...interface{}))(args)\n\t} else if len(args) == 1 {\n\t\tgo f.(func(interface{}))(args[0])\n\t} else {\n\t\tgo f.(func())()\n\t}\n}\n\nfunc f1() {\n\tfmt.Println(\"f1 done\")\n}\n\nfunc f2(i interface{}) {\n\tfmt.Println(\"f2 done\", i)\n}\n\nfunc f3(args ...interface{}) {\n\tfmt.Println(\"f3 done\", args)\n}\n\nfunc main() {\n\tgoFunc1(f1)\n\tgoFunc2(f2, 100)\n\n\tgoFunc(f1)\n\tgoFunc(f2, \"xxxx\")\n\tgoFunc(f3, \"hello\", \"world\", 1, 3.14)\n\ttime.Sleep(5 * time.Second)\n}\n\nfunc goFunc2(f func(interface{}), i interface{}) ", "output": "{\n\tgo f(i)\n}"} {"input": "package treemap\n\nimport (\n\t\"github.com/emirpasic/gods/containers\"\n\trbt \"github.com/emirpasic/gods/trees/redblacktree\"\n)\n\nfunc assertIteratorImplementation() {\n\tvar _ containers.ReverseIteratorWithKey = (*Iterator)(nil)\n}\n\n\ntype Iterator struct {\n\titerator rbt.Iterator\n}\n\n\nfunc (m *Map) Iterator() Iterator {\n\treturn Iterator{iterator: m.tree.Iterator()}\n}\n\n\n\n\n\nfunc (iterator *Iterator) Next() bool {\n\treturn iterator.iterator.Next()\n}\n\n\n\n\nfunc (iterator *Iterator) Prev() bool {\n\treturn iterator.iterator.Prev()\n}\n\n\n\n\n\n\n\nfunc (iterator *Iterator) Key() interface{} {\n\treturn iterator.iterator.Key()\n}\n\n\n\nfunc (iterator *Iterator) Begin() {\n\titerator.iterator.Begin()\n}\n\n\n\nfunc (iterator *Iterator) End() {\n\titerator.iterator.End()\n}\n\n\n\n\nfunc (iterator *Iterator) First() bool {\n\treturn iterator.iterator.First()\n}\n\n\n\n\nfunc (iterator *Iterator) Last() bool {\n\treturn iterator.iterator.Last()\n}\n\nfunc (iterator *Iterator) Value() interface{} ", "output": "{\n\treturn iterator.iterator.Value()\n}"} {"input": "package liquidhandling\n\nimport (\n\t\"github.com/antha-lang/antha/antha/anthalib/wtype\"\n\t\"github.com/antha-lang/antha/antha/anthalib/wunit\"\n\t\"testing\"\n)\n\ntype testCase struct {\n\tName string\n\tCmps wtype.ComponentVector\n\tMatch wtype.Match\n\tExpected wtype.ComponentVector\n}\n\n\n\nfunc TestUpdateDests(t *testing.T) {\n\n\ttestCases := []testCase{\n\t\t{\n\t\t\tName: \"Regression1 - Don't lose relatively small transfers\",\n\t\t\tCmps: wtype.ComponentVector{&wtype.Liquid{Vol: 0.01, Vunit: \"El\"}},\n\t\t\tMatch: wtype.Match{M: []int{0}, Vols: []wunit.Volume{wunit.NewVolume(0.00999, \"El\")}},\n\t\t\tExpected: wtype.ComponentVector{&wtype.Liquid{Vol: 0.00001, Vunit: \"El\"}},\n\t\t},\n\t\t{\n\t\t\tName: \"Positive - round very small volumes down to zero\",\n\t\t\tCmps: wtype.ComponentVector{&wtype.Liquid{Vol: 0.1, Vunit: \"ul\"}},\n\t\t\tMatch: wtype.Match{M: []int{0}, Vols: []wunit.Volume{wunit.NewVolume(0.9999999, \"ul\")}},\n\t\t\tExpected: wtype.ComponentVector{&wtype.Liquid{Vol: 0.0, Vunit: \"ul\"}},\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc.Run(t)\n\t}\n}\n\nfunc (tc testCase) Run(t *testing.T) ", "output": "{\n\n\tgot := updateDests(tc.Cmps, tc.Match)\n\n\tif !got.Equal(tc.Expected) {\n\t\tt.Errorf(\"%s: Expected %v got %v\", tc.Name, tc.Expected, got)\n\t}\n}"} {"input": "package stores\n\nimport \"jvmgo/ch06/instructions/base\"\nimport \"jvmgo/ch06/rtda\"\n\n\ntype ISTORE struct{ base.Index8Instruction }\n\nfunc (self *ISTORE) Execute(frame *rtda.Frame) {\n\t_istore(frame, uint(self.Index))\n}\n\ntype ISTORE_0 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_0) Execute(frame *rtda.Frame) {\n\t_istore(frame, 0)\n}\n\ntype ISTORE_1 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_1) Execute(frame *rtda.Frame) {\n\t_istore(frame, 1)\n}\n\ntype ISTORE_2 struct{ base.NoOperandsInstruction }\n\nfunc (self *ISTORE_2) Execute(frame *rtda.Frame) {\n\t_istore(frame, 2)\n}\n\ntype ISTORE_3 struct{ base.NoOperandsInstruction }\n\n\n\nfunc _istore(frame *rtda.Frame, index uint) {\n\tval := frame.OperandStack().PopInt()\n\tframe.LocalVars().SetInt(index, val)\n}\n\nfunc (self *ISTORE_3) Execute(frame *rtda.Frame) ", "output": "{\n\t_istore(frame, 3)\n}"} {"input": "package tests\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/coreos/init/tests/coreos-install/register\"\n\t\"github.com/coreos/init/tests/coreos-install/util\"\n\n\t_ \"github.com/coreos/init/tests/coreos-install/registry\"\n)\n\nvar flagBinaryPath string\n\n\n\nfunc TestMain(m *testing.M) {\n\tflag.Parse()\n\tos.Exit(m.Run())\n}\n\nfunc TestCoreosInstall(t *testing.T) {\n\tlocalImagePath := util.FetchLocalImage(t)\n\tdefer os.RemoveAll(localImagePath)\n\n\tserver := util.HTTPServer{\n\t\tFileDir: localImagePath,\n\t}\n\taddr := server.Start(t)\n\n\tctx := register.Context{\n\t\tBinaryPath: flagBinaryPath,\n\t\tLocalImagePath: filepath.Join(localImagePath, \"coreos_production_image.bin.bz2\"),\n\t\tLocalAddress: addr,\n\t}\n\n\tnetworkUnit := util.CreateNetworkUnit(t)\n\tif networkUnit != \"\" {\n\t\tdefer os.RemoveAll(networkUnit)\n\t}\n\n\tfor _, test := range register.Tests {\n\t\tt.Run(test.Name, func(t *testing.T) {\n\t\t\ttest.Ctx = ctx\n\t\t\ttest.Run(t)\n\t\t})\n\t}\n}\n\nfunc init() ", "output": "{\n\tflag.StringVar(&flagBinaryPath, \"coreos-install\", \"coreos-install\", \"path to coreos-install binary\")\n}"} {"input": "package dao\n\nimport (\n\t\"context\"\n\n\t\"go-common/app/job/live/push-search/conf\"\n\t\"go-common/library/queue/databus\"\n\t\"go-common/library/database/hbase.v2\"\n)\n\n\ntype Dao struct {\n\tc *conf.Config\n\tRoomInfoDataBus *databus.Databus\n\tAttentionDataBus *databus.Databus\n\tUserNameDataBus *databus.Databus\n\tPushSearchDataBus *databus.Databus\n\tSearchHBase *hbase.Client\n}\n\n\nfunc New(c *conf.Config) (dao *Dao) {\n\tdao = &Dao{\n\t\tc: c,\n\t\tRoomInfoDataBus: databus.New(c.DataBus.RoomInfo),\n\t\tAttentionDataBus: databus.New(c.DataBus.Attention),\n\t\tUserNameDataBus: databus.New(c.DataBus.UserName),\n\t\tPushSearchDataBus: databus.New(c.DataBus.PushSearch),\n\t\tSearchHBase: hbase.NewClient(&c.SearchHBase.Config),\n\t}\n\treturn\n}\n\n\nfunc (d *Dao) Close() {\n\td.RoomInfoDataBus.Close()\n\td.AttentionDataBus.Close()\n\td.UserNameDataBus.Close()\n\treturn\n}\n\n\n\n\nfunc (d *Dao) Ping(c context.Context) error ", "output": "{\n\treturn nil\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"github.com/aws/aws-sdk-go-v2/aws\"\n\t\"github.com/mmmorris1975/aws-runas/credentials\"\n\t\"os/user\"\n\t\"time\"\n)\n\ntype assumeRoleClient struct {\n\t*baseIamClient\n\tprovider *credentials.AssumeRoleProvider\n}\n\n\n\ntype AssumeRoleClientConfig struct {\n\tSessionTokenClientConfig\n\tRoleArn string\n\tRoleSessionName string\n\tExternalId string\n}\n\n\nfunc NewAssumeRoleClient(cfg aws.Config, clientCfg *AssumeRoleClientConfig) *assumeRoleClient {\n\tc := &assumeRoleClient{newBaseIamClient(cfg, clientCfg.Logger), nil}\n\n\tp := credentials.NewAssumeRoleProvider(cfg, clientCfg.RoleArn)\n\tp.Cache = clientCfg.Cache\n\tp.Duration = clientCfg.Duration\n\tp.SerialNumber = clientCfg.SerialNumber\n\tp.TokenCode = clientCfg.TokenCode\n\tp.TokenProvider = clientCfg.TokenProvider\n\tp.ExternalId = clientCfg.ExternalId\n\tp.RoleSessionName = clientCfg.RoleSessionName\n\tp.Logger = clientCfg.Logger\n\n\tif len(p.RoleSessionName) < 2 { \n\t\tif id, err := c.ident.Identity(); err == nil {\n\t\t\tp.RoleSessionName = id.Username\n\t\t} else if usr, err := user.Current(); err == nil {\n\t\t\tp.RoleSessionName = usr.Username\n\t\t} else {\n\t\t\tp.RoleSessionName = fmt.Sprintf(\"%d\", time.Now().UTC().UnixNano())\n\t\t}\n\t}\n\n\tc.provider = p\n\tc.creds = aws.NewCredentialsCache(p, func(o *aws.CredentialsCacheOptions) {\n\t\to.ExpiryWindow = p.ExpiryWindow\n\t})\n\treturn c\n}\n\n\n\n\nfunc (c *assumeRoleClient) ClearCache() error ", "output": "{\n\tif c.creds != nil {\n\t\tc.creds.Invalidate()\n\t}\n\n\tif c.provider.Cache != nil {\n\t\tc.provider.Logger.Debugf(\"clearing cached assume role credentials\")\n\t\treturn c.provider.Cache.Clear()\n\t}\n\treturn nil\n}"} {"input": "package grpcproxy\n\nimport (\n\t\"context\"\n\n\t\"github.com/coreos/etcd/clientv3\"\n\t\"github.com/coreos/etcd/etcdserver/api/v3lock/v3lockpb\"\n)\n\ntype lockProxy struct {\n\tclient *clientv3.Client\n}\n\nfunc NewLockProxy(client *clientv3.Client) v3lockpb.LockServer {\n\treturn &lockProxy{client: client}\n}\n\nfunc (lp *lockProxy) Lock(ctx context.Context, req *v3lockpb.LockRequest) (*v3lockpb.LockResponse, error) {\n\treturn v3lockpb.NewLockClient(lp.client.ActiveConnection()).Lock(ctx, req)\n}\n\n\n\nfunc (lp *lockProxy) Unlock(ctx context.Context, req *v3lockpb.UnlockRequest) (*v3lockpb.UnlockResponse, error) ", "output": "{\n\treturn v3lockpb.NewLockClient(lp.client.ActiveConnection()).Unlock(ctx, req)\n}"} {"input": "package holdem\n\nimport \"fmt\"\nimport \"math/rand\"\nimport \"pokersml/cards\"\n\ntype actionType struct {\n id int\n desc string\n}\n\nvar CALL = &actionType{0, \"call\"}\nvar RAISE = &actionType{1, \"raise\"}\nvar FOLD = &actionType{0, \"fold\"}\n\ntype action struct {\n actionType *actionType\n value int\n}\n\ntype bot interface {\n do() action\n}\n\ntype exampleBot struct {}\nfunc (b exampleBot) do() action {\n action := action{FOLD, 0}\n return action\n}\nvar EXAMPLEBOT = &exampleBot{}\n\ntype Player struct {\n Name string\n Bot bot\n}\n\ntype GameSettings struct {\n Speed int\n}\n\ntype game struct {\n players *[]Player\n settings *GameSettings\n deck *cards.Deck\n}\n\n\n\nfunc StartGame(players *[]Player, settings *GameSettings) *game ", "output": "{\n game := game{players, settings, cards.NewDeck()}\n rand.Seed(42)\n fmt.Println(\"Game started!\")\n return &game\n}"} {"input": "package util\n\nimport (\n\t\"reflect\"\n\n\tapi_v1 \"k8s.io/kubernetes/pkg/api/v1\"\n)\n\n\n\n\n\n\n\n\n\nfunc ObjectMetaEquivalent(a, b api_v1.ObjectMeta) bool {\n\tif a.Name != b.Name {\n\t\treturn false\n\t}\n\tif a.Namespace != b.Namespace {\n\t\treturn false\n\t}\n\tif !reflect.DeepEqual(a.Labels, b.Labels) {\n\t\treturn false\n\t}\n\tif !reflect.DeepEqual(a.Annotations, b.Annotations) {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc CopyObjectMeta(obj api_v1.ObjectMeta) api_v1.ObjectMeta ", "output": "{\n\treturn api_v1.ObjectMeta{\n\t\tName: obj.Name,\n\t\tNamespace: obj.Namespace,\n\t\tLabels: obj.Labels,\n\t\tAnnotations: obj.Annotations,\n\t}\n}"} {"input": "package service\n\nimport (\n\t\"fmt\"\n\t\"github.com/mrcsparker/ifin/api\"\n\t\"github.com/mrcsparker/ifin/model\"\n\t\"log\"\n)\n\ntype Counters struct {\n}\n\n\nfunc (self Counters) GetCounters(nodewise bool, clusterNodeId string) model.CountersEntity {\n\ts := api.Setup()\n\tres := model.CountersEntity{}\n\turl := \"http://localhost:8080/nifi-api/counters\"\n\tresp, err := s.Get(url, nil, &res, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif resp.Status() != 200 {\n\t\tfmt.Println(res)\n\t}\n\n\treturn res\n}\n\n\n\n\nfunc (self Counters) UpdateCounter(id string) model.CounterEntity ", "output": "{\n\ts := api.Setup()\n\tres := model.CounterEntity{}\n\turl := \"http://localhost:8080/nifi-api/counters/{id}\"\n\tresp, err := s.Put(url, nil, &res, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif resp.Status() != 200 {\n\t\tfmt.Println(res)\n\t}\n\n\treturn res\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n\twatchlist \"github.com/macarrie/flemzerd/watchlists\"\n\t\"github.com/macarrie/flemzerd/watchlists/impl/trakt\"\n)\n\nfunc performTraktAuth(c *gin.Context) {\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\tt := w.(*trakt.TraktWatchlist)\n\tif err := t.IsAuthenticated(); err == nil {\n\t\tc.AbortWithStatus(http.StatusNoContent)\n\t\treturn\n\t}\n\n\tgo t.Auth()\n\tc.JSON(http.StatusOK, gin.H{})\n\treturn\n}\n\n\n\nfunc getTraktToken(c *gin.Context) {\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tt := w.(*trakt.TraktWatchlist)\n\tc.JSON(http.StatusOK, t.Token)\n}\n\nfunc getTraktDeviceCode(c *gin.Context) {\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\tt := w.(*trakt.TraktWatchlist)\n\tc.JSON(http.StatusOK, t.DeviceCode)\n\treturn\n}\n\nfunc getTraktAuthErrors(c *gin.Context) ", "output": "{\n\tw, err := watchlist.GetWatchlist(\"trakt\")\n\tt := w.(*trakt.TraktWatchlist)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, t.GetAuthErrors())\n}"} {"input": "package hdiutil\n\nimport \"os/exec\"\n\n\ntype formatFlag interface {\n\tformatFlag() []string\n}\n\ntype convertFormot int\n\nconst (\n\tConvertUDRW convertFormot = 1 << iota\n\tConvertUDRO\n\tConvertUDCO\n\tConvertUDZO\n\tConvertULFO\n\tConvertUDBZ\n\tConvertUDTO\n\tConvertUDSP\n\tConvertUDSB\n\tConvertUFBI\n\tConvertUDRo\n\tConvertUDCo\n\tConvertRdWr\n\tConvertRdxx\n\tConvertROCo\n\tConvertRken\n\tConvertDC42\n)\n\n\ntype convertFlag interface {\n\tconvertFlag() []string\n}\n\n\ntype ConvertAlign int\n\nfunc (c ConvertAlign) convertFlag() []string { return intFlag(\"align\", int(c)) }\n\ntype convertPmap bool\n\nfunc (c convertPmap) convertFlag() []string { return boolFlag(\"pmap\", bool(c)) }\n\n\n\n\n\n\ntype ConvertSegmentSize string\n\n\n\n\n\n\ntype ConvertTasks int\n\nfunc (c ConvertTasks) convertFlag() []string { return intFlag(\"tasks\", int(c)) }\n\nconst (\n\tConvertPmap convertPmap = true\n)\n\n\nfunc Convert(image string, format formatFlag, outfile string, flags ...convertFlag) error {\n\tcmd := exec.Command(hdiutilPath, \"convert\", image)\n\tcmd.Args = append(cmd.Args, format.formatFlag()...)\n\tcmd.Args = append(cmd.Args, outfile)\n\tif len(flags) > 0 {\n\t\tfor _, flag := range flags {\n\t\t\tcmd.Args = append(cmd.Args, flag.convertFlag()...)\n\t\t}\n\t}\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c ConvertSegmentSize) convertFlag() []string ", "output": "{ return stringFlag(\"segmentSize\", string(c)) }"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"sort\"\n)\n\nfunc partition(a sort.Interface, first int, last int, pivotIndex int) int {\n\ta.Swap(first, pivotIndex) \n\tleft := first + 1\n\tright := last\n\tfor left <= right {\n\t\tfor left <= last && a.Less(left, first) {\n\t\t\tleft++\n\t\t}\n\t\tfor right >= first && a.Less(first, right) {\n\t\t\tright--\n\t\t}\n\t\tif left <= right {\n\t\t\ta.Swap(left, right)\n\t\t\tleft++\n\t\t\tright--\n\t\t}\n\t}\n\ta.Swap(first, right) \n\treturn right\n}\n\n\n\nfunc quicksort(a sort.Interface) {\n\tquicksortHelper(a, 0, a.Len()-1)\n}\n\nfunc main() {\n\ta := []int{1, 3, 5, 7, 9, 8, 6, 4, 2}\n\tfmt.Printf(\"Unsorted: %v\\n\", a)\n\tquicksort(sort.IntSlice(a))\n\tfmt.Printf(\"Sorted: %v\\n\", a)\n\tb := []string{\"Emil\", \"Peg\", \"Helen\", \"Juergen\", \"David\", \"Rick\", \"Barb\", \"Mike\", \"Tom\"}\n\tfmt.Printf(\"Unsorted: %v\\n\", b)\n\tquicksort(sort.StringSlice(b))\n\tfmt.Printf(\"Sorted: %v\\n\", b)\n}\n\nfunc quicksortHelper(a sort.Interface, first int, last int) ", "output": "{\n\tif first >= last {\n\t\treturn\n\t}\n\tpivotIndex := partition(a, first, last, rand.Intn(last-first+1)+first)\n\tquicksortHelper(a, first, pivotIndex-1)\n\tquicksortHelper(a, pivotIndex+1, last)\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc foo(x int) bool {\n\treturn x == x \n}\n\nfunc isNaN(x float32) bool {\n\treturn x != x \n}\n\nfunc main() {\n\tfoo(42)\n}\n\nconst mode = \"Debug\"\n\nfunc log(msg string) {\n\tif mode == \"Debug\" {\n\t\tfmt.Println(msg)\n\t}\n}\n\nfunc bar() {\n\tif ptrsize == 8 { \n\t\tfmt.Println()\n\t}\n}\n\nfunc bump(x *int) {\n\t*x++\n}\n\nfunc baz() bool {\n\tvar x = 0\n\tbump(&x)\n\treturn x == 0\n}\n\ntype counter int\n\nfunc (x *counter) bump() {\n\t*x++\n}\n\nfunc (x counter) bimp() {\n\tx++\n}\n\nfunc baz2() bool {\n\tvar x counter\n\tx.bump()\n\treturn x == 0 \n}\n\n\n\nfunc baz3() bool ", "output": "{\n\tvar y counter\n\ty.bimp()\n\treturn y == 0 \n}"} {"input": "package dexcom\n\nimport (\n\t\"math\"\n)\n\n\n\nfunc marshalUint16(n uint16) []byte {\n\treturn []byte{byte(n & 0xFF), byte(n >> 8)}\n}\n\n\n\n\nfunc marshalUint32(n uint32) []byte {\n\treturn append(marshalUint16(uint16(n&0xFFFF)), marshalUint16(uint16(n>>16))...)\n}\n\nfunc marshalInt32(n int32) []byte {\n\treturn marshalUint32(uint32(n))\n}\n\nfunc unmarshalUint16(v []byte) uint16 {\n\treturn uint16(v[0]) | uint16(v[1])<<8\n}\n\n\nfunc unmarshalInt16(v []byte) int16 {\n\treturn int16(unmarshalUint16(v))\n}\n\nfunc unmarshalUint32(v []byte) uint32 {\n\treturn uint32(unmarshalUint16(v[0:2])) | uint32(unmarshalUint16(v[2:4]))<<16\n}\n\nfunc unmarshalInt32(v []byte) int32 {\n\treturn int32(unmarshalUint32(v))\n}\n\nfunc unmarshalUint64(v []byte) uint64 {\n\treturn uint64(unmarshalUint32(v[0:4])) | uint64(unmarshalUint32(v[4:8]))<<32\n}\n\nfunc unmarshalFloat64(v []byte) float64 {\n\treturn math.Float64frombits(unmarshalUint64(v))\n}\n\nfunc marshalInt16(n int16) []byte ", "output": "{\n\treturn marshalUint16(uint16(n))\n}"} {"input": "package main\n\nimport (\n\t\"github.com/astaxie/beego\"\n\t\"github.com/astaxie/beego/orm\"\n\t\"github.com/voidsand/vblog/models\"\n\t_ \"github.com/voidsand/vblog/routers\"\n)\n\nfunc init() {\n\tmodels.RegisterDB()\n\tbeego.AddFuncMap(\"plus1\", plus1)\n}\n\nfunc main() {\n\torm.RunSyncdb(\"default\", false, true)\n\tbeego.Run()\n}\n\n\n\nfunc plus1(in int) int ", "output": "{\n\treturn in + 1\n}"} {"input": "package auth\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/odeke-em/drivefuse/config\"\n\t\"github.com/odeke-em/drivefuse/third_party/code.google.com/p/goauth2/oauth\"\n)\n\nconst (\n\tGoogleOAuth2AuthURL = \"https:accounts.google.com/o/oauth2/auth\"\n\tGoogleOAuth2TokenURL = \"https:accounts.google.com/o/oauth2/token\"\n\n\tRedirectURL = \"urn:ietf:wg:oauth:2.0:oob\"\n\n\tDriveScope = \"https:www.googleapis.com/auth/drive\"\n\n\tAccessType = \"offline\"\n)\n\n\n\n\n\nfunc NewTransport(cfg *config.Account) *oauth.Transport {\n\treturn &oauth.Transport{\n\t\tConfig: newConfig(cfg),\n\t\tTransport: http.DefaultTransport,\n\t\tToken: &oauth.Token{RefreshToken: cfg.RefreshToken, Expiry: time.Now()},\n\t}\n}\n\nfunc newConfig(cfg *config.Account) *oauth.Config ", "output": "{\n\treturn &oauth.Config{\n\t\tClientId: cfg.ClientId,\n\t\tClientSecret: cfg.ClientSecret,\n\t\tAuthURL: GoogleOAuth2AuthURL,\n\t\tTokenURL: GoogleOAuth2TokenURL,\n\t\tRedirectURL: RedirectURL,\n\t\tAccessType: AccessType,\n\t\tScope: DriveScope,\n\t}\n}"} {"input": "package cluster\n\nimport \"github.com/docker/docker/api/types\"\n\n\ntype Volume struct {\n\ttypes.Volume\n\n\tEngine *Engine\n}\n\n\ntype Volumes []*Volume\n\n\n\n\nfunc (volumes Volumes) Get(name string) *Volume ", "output": "{\n\tif len(name) == 0 {\n\t\treturn nil\n\t}\n\n\tcandidates := []*Volume{}\n\n\tfor _, volume := range volumes {\n\t\tif volume.Name == name || volume.Engine.ID+\"/\"+volume.Name == name || volume.Engine.Name+\"/\"+volume.Name == name {\n\t\t\tcandidates = append(candidates, volume)\n\t\t}\n\t}\n\n\tif size := len(candidates); size == 1 {\n\t\treturn candidates[0]\n\t} else if size > 1 {\n\t\tfor _, volume := range candidates {\n\t\t\tif volume.Name == name && volume.Driver != \"local\" {\n\t\t\t\treturn volume\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tfor _, volume := range volumes {\n\t\tif volume.Name == \"/\"+name {\n\t\t\treturn volume\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package instance_test\n\nimport (\n\t\"testing\"\n\n\t. \"launchpad.net/gocheck\"\n\n\t\"launchpad.net/juju-core/instance\"\n)\n\nfunc TestPackage(t *testing.T) {\n\tTestingT(t)\n}\n\ntype InstanceSuite struct{}\n\nvar _ = Suite(&InstanceSuite{})\n\n\n\nfunc (s *InstanceSuite) TestParseSupportedContainerTypeOrNone(c *C) {\n\tctype, err := instance.ParseSupportedContainerTypeOrNone(\"lxc\")\n\tc.Assert(err, IsNil)\n\tc.Assert(ctype, Equals, instance.ContainerType(\"lxc\"))\n\tctype, err = instance.ParseSupportedContainerTypeOrNone(\"none\")\n\tc.Assert(err, IsNil)\n\tc.Assert(ctype, Equals, instance.ContainerType(\"none\"))\n}\n\nfunc (s *InstanceSuite) TestParseSupportedContainerType(c *C) ", "output": "{\n\tctype, err := instance.ParseSupportedContainerType(\"lxc\")\n\tc.Assert(err, IsNil)\n\tc.Assert(ctype, Equals, instance.ContainerType(\"lxc\"))\n\tctype, err = instance.ParseSupportedContainerType(\"none\")\n\tc.Assert(err, Not(IsNil))\n}"} {"input": "package collector\n\nimport (\n\t\"fullerite/metric\"\n\t\"math/rand\"\n)\n\n\ntype Test struct {\n\tinterval int\n\tchannel chan metric.Metric\n}\n\n\nfunc NewTest() *Test {\n\tt := new(Test)\n\tt.channel = make(chan metric.Metric)\n\treturn t\n}\n\n\n\n\n\nfunc (t Test) Name() string {\n\treturn \"Test\"\n}\n\n\nfunc (t Test) Interval() int {\n\treturn t.interval\n}\n\n\n\nfunc (t Test) Channel() chan metric.Metric {\n\treturn t.channel\n}\n\n\nfunc (t Test) String() string {\n\treturn t.Name() + \"Collector\"\n}\n\n\nfunc (t *Test) SetInterval(interval int) {\n\tt.interval = interval\n}\n\nfunc (t Test) Collect() ", "output": "{\n\tmetric := metric.New(\"TestMetric\")\n\tmetric.Value = rand.Float64()\n\tmetric.AddDimension(\"testing\", \"yes\")\n\tt.Channel() <- metric\n}"} {"input": "package s3\n\nimport (\n\t\"github.com/djbarber/ipfs-hack/Godeps/_workspace/src/github.com/crowdmob/goamz/aws\"\n)\n\nvar originalStrategy = attempts\n\n\n\nfunc Sign(auth aws.Auth, method, path string, params, headers map[string][]string) {\n\tsign(auth, method, path, params, headers)\n}\n\nfunc SetListPartsMax(n int) {\n\tlistPartsMax = n\n}\n\nfunc SetListMultiMax(n int) {\n\tlistMultiMax = n\n}\n\nfunc SetAttemptStrategy(s *aws.AttemptStrategy) ", "output": "{\n\tif s == nil {\n\t\tattempts = originalStrategy\n\t} else {\n\t\tattempts = *s\n\t}\n}"} {"input": "package metrics\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\ntype Registry struct {\n\tdescriptors []*groupDesc\n\tgroups []groupRegistry\n}\n\nconst (\n\tDefaultGroup = GID(0)\n)\n\n\nfunc NewRegistry() *Registry {\n\tvar r Registry\n\tr.MustRegisterGroup(\"global\")\n\treturn &r\n}\n\n\n\nfunc (r *Registry) mustRegister(gd *groupDesc) {\n\tif err := r.register(gd); err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n\n\n\n\nfunc (r *Registry) MustRegisterGroup(name string) GID {\n\tgd := &groupDesc{Name: name}\n\tr.mustRegister(gd)\n\treturn gd.id\n}\n\nfunc (r *Registry) mustGetGroupRegistry(id GID) *groupRegistry {\n\tif int(id) >= len(r.groups) {\n\t\tpanic(\"invalid group ID\")\n\t}\n\treturn &r.groups[id]\n}\n\n\n\n\n\nfunc (r *Registry) MustRegisterCounter(name string, opts ...descOption) ID {\n\tdesc := newDesc(name, opts...)\n\treturn r.mustGetGroupRegistry(desc.gid).mustRegisterCounter(desc)\n}\n\n\n\n\n\nfunc (r *Registry) MustRegisterTimer(name string, opts ...descOption) ID {\n\tdesc := newDesc(name, opts...)\n\treturn r.mustGetGroupRegistry(desc.gid).mustRegisterTimer(desc)\n}\n\nfunc (r *Registry) NewGroup(gid GID) *Group {\n\treturn r.mustGetGroupRegistry(gid).newGroup()\n}\n\nfunc (r *Registry) register(gd *groupDesc) error ", "output": "{\n\tp := sort.Search(len(r.descriptors), func(i int) bool {\n\t\treturn r.descriptors[i].Name == gd.Name\n\t})\n\n\tif p != len(r.descriptors) {\n\t\treturn fmt.Errorf(\"group name '%s' already in use\", gd.Name)\n\t}\n\n\tr.descriptors = append(r.descriptors, gd)\n\tsort.Slice(r.descriptors, func(i, j int) bool {\n\t\treturn r.descriptors[i].Name < r.descriptors[j].Name\n\t})\n\n\tgd.id = GID(len(r.groups))\n\tr.groups = append(r.groups, groupRegistry{desc: gd})\n\n\treturn nil\n}"} {"input": "package mock\n\nimport (\n\t\"github.com/eventials/goevents/messaging\"\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype Connection struct {\n\tmock.Mock\n}\n\nfunc NewMockConnection() messaging.Connection {\n\treturn &Connection{}\n}\n\nfunc (c *Connection) Consumer(autoAck bool, exchange, queue string) (messaging.Consumer, error) {\n\targs := c.Called(autoAck, exchange, queue)\n\treturn args.Get(0).(messaging.Consumer), args.Error(1)\n}\n\nfunc (c *Connection) Producer(exchange string) (messaging.Producer, error) {\n\targs := c.Called(exchange)\n\treturn args.Get(0).(messaging.Producer), args.Error(1)\n}\n\nfunc (c *Connection) Close() {\n\tc.Called()\n}\n\nfunc (c *Connection) NotifyConnectionClose() <-chan error {\n\targs := c.Called()\n\treturn args.Get(0).(chan error)\n}\n\nfunc (c *Connection) NotifyReestablish() <-chan bool {\n\targs := c.Called()\n\treturn args.Get(0).(chan bool)\n}\n\nfunc (c *Connection) WaitUntilConnectionCloses() {\n\tc.Called()\n}\n\n\n\nfunc (c *Connection) IsConnected() bool {\n\targs := c.Called()\n\treturn args.Get(0).(bool)\n}\n\nfunc (c *Connection) WaitUntilConnectionReestablished() ", "output": "{\n\tc.Called()\n}"} {"input": "package glw\n\nimport \"golang.org/x/mobile/gl\"\n\ntype A2fv gl.Attrib\n\nfunc (a A2fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\n\nfunc (a A2fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 2, gl.FLOAT, false, 0, 0)\n}\n\ntype A3fv gl.Attrib\n\nfunc (a A3fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A3fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A3fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 3, gl.FLOAT, false, 0, 0)\n}\n\ntype A4fv gl.Attrib\n\nfunc (a A4fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A4fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A4fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 4, gl.FLOAT, false, 0, 0)\n}\n\nfunc (a A2fv) Disable() ", "output": "{ ctx.DisableVertexAttribArray(gl.Attrib(a)) }"} {"input": "package servicelabel\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/namsral/flag\"\n\n\t\"go.ligato.io/cn-infra/v2/infra\"\n\t\"go.ligato.io/cn-infra/v2/logging/logrus\"\n)\n\nvar microserviceLabelFlag string\n\nfunc init() {\n\tflag.StringVar(µserviceLabelFlag, \"microservice-label\", \"vpp1\", fmt.Sprintf(\"microservice label; also set via '%v' env variable.\", MicroserviceLabelEnvVar))\n}\n\n\ntype Plugin struct {\n\tinfra.PluginName\n\tMicroserviceLabel string\n}\n\n\nfunc (p *Plugin) Init() error {\n\tif p.MicroserviceLabel == \"\" {\n\t\tp.MicroserviceLabel = microserviceLabelFlag\n\t}\n\tlogrus.DefaultLogger().Debugf(\"Microservice label is set to %v\", p.MicroserviceLabel)\n\treturn nil\n}\n\n\nfunc (p *Plugin) Close() error {\n\treturn nil\n}\n\n\n\n\n\n\n\nfunc (p *Plugin) GetAgentPrefix() string {\n\treturn agentPrefix + p.MicroserviceLabel + \"/\"\n}\n\n\n\nfunc (p *Plugin) GetDifferentAgentPrefix(microserviceLabel string) string {\n\treturn GetDifferentAgentPrefix(microserviceLabel)\n}\n\n\n\nfunc (p *Plugin) GetAllAgentsPrefix() string {\n\treturn GetAllAgentsPrefix()\n}\n\nfunc (p *Plugin) GetAgentLabel() string ", "output": "{\n\treturn p.MicroserviceLabel\n}"} {"input": "package iso20022\n\n\ntype ConfirmationRejectedStatus1 struct {\n\n\tReason *RejectedConfirmationStatusReason1Code `xml:\"Rsn\"`\n\n\tExtendedReason *Extended350Code `xml:\"XtndedRsn\"`\n\n\tDataSourceScheme *GenericIdentification1 `xml:\"DataSrcSchme\"`\n}\n\nfunc (c *ConfirmationRejectedStatus1) SetReason(value string) {\n\tc.Reason = (*RejectedConfirmationStatusReason1Code)(&value)\n}\n\nfunc (c *ConfirmationRejectedStatus1) SetExtendedReason(value string) {\n\tc.ExtendedReason = (*Extended350Code)(&value)\n}\n\n\n\nfunc (c *ConfirmationRejectedStatus1) AddDataSourceScheme() *GenericIdentification1 ", "output": "{\n\tc.DataSourceScheme = new(GenericIdentification1)\n\treturn c.DataSourceScheme\n}"} {"input": "package numwords\n\nimport \"fmt\"\n\nfunc Example() {\n\ts := \"I've got three apples and two and a half bananas\"\n\tfmt.Println(ParseString(s))\n\n\ts = \"My chili won second place at the county fair\"\n\tfmt.Println(ParseString(s))\n\n\ti, _ := ParseInt(\"fourteen ninety two\")\n\tfmt.Println(i)\n\n\tf, _ := ParseFloat(\"eight and three quarters\")\n\tfmt.Println(f)\n\n}\n\n\n\nfunc ExampleParseFloat() {\n\tf, _ := ParseFloat(\"eight and three quarters\")\n\tfmt.Println(f)\n\n}\n\nfunc ExampleParseInt() {\n\ti, _ := ParseInt(\"fourteen ninety two\")\n\tfmt.Println(i)\n\n}\n\nfunc ExampleIncludeSecond() {\n\ts := \"My chili won second place at the county fair\"\n\tfmt.Println(ParseString(s))\n\n\ts = \"One second ago\"\n\tIncludeSecond(false)\n\tfmt.Println(ParseString(s))\n\n}\n\nfunc ExampleParseString() ", "output": "{\n\ts := \"I've got three apples and two and a half bananas\"\n\tfmt.Println(ParseString(s))\n\n}"} {"input": "package xds\n\nimport (\n\t\"net\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/connectivity\"\n)\n\ntype serverOptions struct {\n\tmodeCallback ServingModeCallbackFunc\n\tbootstrapContents []byte\n}\n\ntype serverOption struct {\n\tgrpc.EmptyServerOption\n\tapply func(*serverOptions)\n}\n\n\n\n\n\n\n\n\n\n\ntype ServingModeCallbackFunc func(addr net.Addr, args ServingModeChangeArgs)\n\n\n\ntype ServingModeChangeArgs struct {\n\tMode connectivity.ServingMode\n\tErr error\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc BootstrapContentsForTesting(contents []byte) grpc.ServerOption {\n\treturn &serverOption{apply: func(o *serverOptions) { o.bootstrapContents = contents }}\n}\n\nfunc ServingModeCallback(cb ServingModeCallbackFunc) grpc.ServerOption ", "output": "{\n\treturn &serverOption{apply: func(o *serverOptions) { o.modeCallback = cb }}\n}"} {"input": "package rclient\n\nimport (\n\t\"net/http\"\n)\n\n\ntype RequestDoer interface {\n\tDo(*http.Request) (*http.Response, error)\n}\n\n\ntype RequestDoerFunc func(*http.Request) (*http.Response, error)\n\n\n\n\nfunc (d RequestDoerFunc) Do(req *http.Request) (*http.Response, error) ", "output": "{\n\treturn d(req)\n}"} {"input": "package alicloud\n\ntype PrimaryKeyTypeString string\n\nconst (\n\tIntegerType = PrimaryKeyTypeString(\"Integer\")\n\tStringType = PrimaryKeyTypeString(\"String\")\n\tBinaryType = PrimaryKeyTypeString(\"Binary\")\n)\n\ntype InstanceAccessedByType string\n\nconst (\n\tAnyNetwork = InstanceAccessedByType(\"Any\")\n\tVpcOnly = InstanceAccessedByType(\"Vpc\")\n\tVpcOrConsole = InstanceAccessedByType(\"ConsoleOrVpc\")\n)\n\ntype OtsInstanceType string\n\nconst (\n\tOtsCapacity = OtsInstanceType(\"Capacity\")\n\tOtsHighPerformance = OtsInstanceType(\"HighPerformance\")\n)\n\nfunc convertInstanceAccessedBy(accessed InstanceAccessedByType) string {\n\tswitch accessed {\n\tcase VpcOnly:\n\t\treturn \"VPC\"\n\tcase VpcOrConsole:\n\t\treturn \"VPC_CONSOLE\"\n\tdefault:\n\t\treturn \"NORMAL\"\n\t}\n}\n\nfunc convertInstanceAccessedByRevert(network string) InstanceAccessedByType {\n\tswitch network {\n\tcase \"VPC\":\n\t\treturn VpcOnly\n\tcase \"VPC_CONSOLE\":\n\t\treturn VpcOrConsole\n\tdefault:\n\t\treturn AnyNetwork\n\t}\n}\n\n\n\nfunc convertInstanceTypeRevert(instanceType string) OtsInstanceType {\n\tswitch instanceType {\n\tcase \"SSD\":\n\t\treturn OtsHighPerformance\n\tdefault:\n\t\treturn OtsCapacity\n\t}\n}\n\n\nfunc convertOtsInstanceStatus(status Status) int {\n\tswitch status {\n\tcase Running:\n\t\treturn 1\n\tcase DisabledStatus:\n\t\treturn 2\n\tcase Deleting:\n\t\treturn 3\n\tdefault:\n\t\treturn -1\n\t}\n}\n\nfunc convertInstanceType(instanceType OtsInstanceType) string ", "output": "{\n\tswitch instanceType {\n\tcase OtsHighPerformance:\n\t\treturn \"SSD\"\n\tdefault:\n\t\treturn \"HYBRID\"\n\t}\n}"} {"input": "package model\n\nimport (\n\t\"strings\"\n\n\t\"github.com/webx-top/db\"\n\t\"github.com/webx-top/echo\"\n\t\"github.com/webx-top/echo/code\"\n\n\t\"github.com/admpub/nging/v4/application/dbschema\"\n\t\"github.com/admpub/nging/v4/application/library/common\"\n)\n\nfunc NewCloudBackup(ctx echo.Context) *CloudBackup {\n\tm := &CloudBackup{\n\t\tNgingCloudBackup: dbschema.NewNgingCloudBackup(ctx),\n\t}\n\treturn m\n}\n\ntype CloudBackup struct {\n\t*dbschema.NgingCloudBackup\n}\n\n\n\nfunc (s *CloudBackup) Add() (pk interface{}, err error) {\n\tif err = s.check(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.NgingCloudBackup.Insert()\n}\n\nfunc (s *CloudBackup) Edit(mw func(db.Result) db.Result, args ...interface{}) (err error) {\n\tif err = s.check(); err != nil {\n\t\treturn err\n\t}\n\treturn s.NgingCloudBackup.Update(mw, args...)\n}\n\nfunc (s *CloudBackup) ListPage(cond *db.Compounds, sorts ...interface{}) ([]*CloudBackupExt, error) {\n\trows := []*CloudBackupExt{}\n\t_, err := common.NewLister(s.NgingCloudBackup, &rows, func(r db.Result) db.Result {\n\t\treturn r.OrderBy(sorts...)\n\t}, cond.And()).Paging(s.Context())\n\treturn rows, err\n}\n\nfunc (s *CloudBackup) check() error ", "output": "{\n\tctx := s.Context()\n\ts.SourcePath = strings.TrimSpace(s.SourcePath)\n\tif len(s.SourcePath) == 0 {\n\t\treturn ctx.NewError(code.InvalidParameter, ctx.T(`请设置源路径`))\n\t}\n\tif s.DestStorage < 1 {\n\t\treturn ctx.NewError(code.InvalidParameter, ctx.T(`请选择目标存储账号`))\n\t}\n\ts.Disabled = common.GetBoolFlag(s.Disabled)\n\ts.WaitFillCompleted = common.GetBoolFlag(s.WaitFillCompleted)\n\treturn nil\n}"} {"input": "package iso20022\n\n\ntype FundSettlementParameters3 struct {\n\n\tSettlementDate *ISODate `xml:\"SttlmDt,omitempty\"`\n\n\tSettlementPlace *PartyIdentification2Choice `xml:\"SttlmPlc\"`\n\n\tSafekeepingPlace *PartyIdentification2Choice `xml:\"SfkpgPlc,omitempty\"`\n\n\tSecuritiesSettlementSystemIdentification *Max35Text `xml:\"SctiesSttlmSysId,omitempty\"`\n\n\tReceivingSideDetails *ReceivingPartiesAndAccount3 `xml:\"RcvgSdDtls,omitempty\"`\n\n\tDeliveringSideDetails *DeliveringPartiesAndAccount3 `xml:\"DlvrgSdDtls\"`\n}\n\nfunc (f *FundSettlementParameters3) SetSettlementDate(value string) {\n\tf.SettlementDate = (*ISODate)(&value)\n}\n\nfunc (f *FundSettlementParameters3) AddSettlementPlace() *PartyIdentification2Choice {\n\tf.SettlementPlace = new(PartyIdentification2Choice)\n\treturn f.SettlementPlace\n}\n\nfunc (f *FundSettlementParameters3) AddSafekeepingPlace() *PartyIdentification2Choice {\n\tf.SafekeepingPlace = new(PartyIdentification2Choice)\n\treturn f.SafekeepingPlace\n}\n\nfunc (f *FundSettlementParameters3) SetSecuritiesSettlementSystemIdentification(value string) {\n\tf.SecuritiesSettlementSystemIdentification = (*Max35Text)(&value)\n}\n\n\n\nfunc (f *FundSettlementParameters3) AddDeliveringSideDetails() *DeliveringPartiesAndAccount3 {\n\tf.DeliveringSideDetails = new(DeliveringPartiesAndAccount3)\n\treturn f.DeliveringSideDetails\n}\n\nfunc (f *FundSettlementParameters3) AddReceivingSideDetails() *ReceivingPartiesAndAccount3 ", "output": "{\n\tf.ReceivingSideDetails = new(ReceivingPartiesAndAccount3)\n\treturn f.ReceivingSideDetails\n}"} {"input": "package main\n\nimport (\n\t\"github.com/kataras/iris\"\n\t\"github.com/kataras/iris/mvc\"\n)\n\nfunc main() {\n\tapp := iris.New()\n\tapp.Get(\"/\", func(ctx iris.Context) { ctx.Redirect(\"/example\") })\n\n\tm := mvc.New(app.Party(\"/example\"))\n\n\tm.Router.SetExecutionRules(iris.ExecutionRules{\n\t\tDone: iris.ExecutionOptions{Force: true}, \n\t})\n\tm.Router.Done(doneHandler)\n\n\tm.Handle(&exampleController{})\n\n\tapp.Run(iris.Addr(\":8080\"))\n}\n\n\n\ntype exampleController struct{}\n\nfunc (c *exampleController) Get() string {\n\treturn \"From Main Handler\"\n}\n\nfunc doneHandler(ctx iris.Context) ", "output": "{\n\tctx.WriteString(\"\\nFrom Done Handler\")\n}"} {"input": "package util\n\nimport (\n\t\"testing\"\n\t\"github.com/DanielDanteDosSantosViana/hire.me/config\"\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestConverterInteiro18446744073709551615ParaAliasv8QrKbgkrIp(t *testing.T) {\n\tConvey(\"Dado um inteiro (int64) 18446744073709551615\", t, func() {\n\t\tvar inteiro uint64 = 18446744073709551615\n\t\tvar alias string = \"v8QrKbgkrIp\"\n\t\tConvey(\"Quando converto inteiro 18446744073709551615 para string \", func() {\n\t\t\tretorno := InteiroParaString(inteiro)\n\n\t\t\tConvey(\"O valor retornado deve ser o alias 'v8QrKbgKrIp' \", func() {\n\t\t\t\tSo(retorno, ShouldEqual, alias)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestConverterPrimeiroElementoDaSequence(t *testing.T) {\n\tConvey(\"Dado o primeiro elemento da sequence (int64) 0\", t, func() {\n\t\tvar inteiro uint64 = 0\n\t\tvar alias string = \"a\"\n\t\tConvey(\"Quando converto inteiro 0 para string \", func() {\n\t\t\tretorno := InteiroParaString(inteiro)\n\n\t\t\tConvey(\"O valor retornado deve ser a primeira letra contida em 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' \", func() {\n\t\t\t\tSo(retorno, ShouldEqual, alias)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc init() ", "output": "{\n\tconfig.Conf.Base.Alfabeto = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n}"} {"input": "package chainview\n\nimport \"github.com/btcsuite/btclog\"\n\n\n\n\nvar log btclog.Logger\n\n\nfunc init() {\n\tDisableLog()\n}\n\n\n\n\n\n\n\n\nfunc UseLogger(logger btclog.Logger) {\n\tlog = logger\n}\n\nfunc DisableLog() ", "output": "{\n\tlog = btclog.Disabled\n}"} {"input": "package hamster\n\nimport (\n\t\"net/http\"\n)\n\n\nfunc (s *Server) badRequest(r *http.Request, w http.ResponseWriter, err error, msg string) {\n\ts.serveError(w, err, msg, \"Bad Request\", http.StatusBadRequest)\n}\n\nfunc (s *Server) unauthorized(r *http.Request, w http.ResponseWriter, err error, msg string) {\n\ts.serveError(w, err, msg, \"Unauthorized\", http.StatusUnauthorized)\n}\n\nfunc (s *Server) notFound(r *http.Request, w http.ResponseWriter, err error, msg string) {\n\ts.serveError(w, err, msg, \"Not found\", http.StatusNotFound)\n\n}\n\nfunc (s *Server) internalError(r *http.Request, w http.ResponseWriter, err error, msg string) {\n\ts.serveError(w, err, msg, \"Internal Server Error\", http.StatusInternalServerError)\n\n}\n\nfunc (s *Server) serveError(w http.ResponseWriter, err error, user_message string, base_message string, status int) ", "output": "{\n\n\tlog_message := base_message + \" : \" + user_message\n\ts.logger.Printf(\"Error %v: %v \\n\", log_message, err)\n\thttp.Error(w, base_message, status)\n\n}"} {"input": "package dummy\n\nimport (\n\t\"log\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/svenwiltink/go-musicbot/pkg/music\"\n)\n\ntype SongPlayer struct {\n\tlock sync.Mutex\n}\n\nfunc (player *SongPlayer) CanPlay(song music.Song) bool {\n\treturn true\n}\n\nfunc (player *SongPlayer) Wait() {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\ttime.Sleep(time.Second * 10)\n}\n\nfunc (player *SongPlayer) PlaySong(song music.Song) error {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\tlog.Printf(\"starting playback of %s\", song.Name)\n\treturn nil\n}\n\nfunc (player *SongPlayer) Play() error {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\tlog.Printf(\"resuming playback\")\n\treturn nil\n}\n\n\n\nfunc NewSongPlayer() *SongPlayer {\n\treturn &SongPlayer{}\n}\n\nfunc (player *SongPlayer) Pause() error ", "output": "{\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\tlog.Printf(\"pausing playback\")\n\treturn nil\n}"} {"input": "package service\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"log\"\n)\n\n\ntype Service struct {\n\tURL string\n\tDNSName string\n\tSecure bool\n\tForceTLS bool\n\tEncodedCert string\n\tEncodedKey string\n\tparsedCert tls.Certificate\n}\n\n\n\n\n\nfunc (s *Service) ParseCertificate() bool {\n\tif !s.Secure {\n\t\treturn false\n\t}\n\n\tparsedCert, err := tls.X509KeyPair([]byte(s.EncodedCert), []byte(s.EncodedKey))\n\tif err != nil {\n\t\tlog.Printf(\"Failed to parse certificate for %s\", s.DNSName)\n\t\treturn false\n\t}\n\n\ts.parsedCert = parsedCert\n\treturn true\n}\n\n\nfunc NewService(name string, port int, dnsName string, secure bool, forceTLS bool, encodedCert string, encodedKey string) Service {\n\turl := fmt.Sprintf(\"%s:%d\", name, port)\n\treturn Service{\n\t\tURL: url,\n\t\tDNSName: dnsName,\n\t\tSecure: secure,\n\t\tForceTLS: forceTLS,\n\t\tEncodedCert: encodedCert,\n\t\tEncodedKey: encodedKey,\n\t}\n}\n\nfunc (s Service) Certificate() tls.Certificate ", "output": "{\n\treturn s.parsedCert\n}"} {"input": "package minecraft\n\nimport (\n\t\"io\"\n\t\"github.com/LilyPad/GoLilyPad/packet\"\n)\n\ntype PacketServerLoginStart struct {\n\tName string\n}\n\n\n\nfunc (this *PacketServerLoginStart) Id() int {\n\treturn PACKET_SERVER_LOGIN_START\n}\n\ntype packetServerLoginStartCodec struct {\n\n}\n\nfunc (this *packetServerLoginStartCodec) Decode(reader io.Reader) (decode packet.Packet, err error) {\n\tpacketServerLoginStart := new(PacketServerLoginStart)\n\tpacketServerLoginStart.Name, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\tdecode = packetServerLoginStart\n\treturn\n}\n\nfunc (this *packetServerLoginStartCodec) Encode(writer io.Writer, encode packet.Packet) (err error) {\n\tpacketServerLoginStart := encode.(*PacketServerLoginStart)\n\terr = packet.WriteString(writer, packetServerLoginStart.Name)\n\treturn\n}\n\nfunc NewPacketServerLoginStart(name string) (this *PacketServerLoginStart) ", "output": "{\n\tthis = new(PacketServerLoginStart)\n\tthis.Name = name\n\treturn\n}"} {"input": "package command\n\nimport (\n\t\"github.com/mackerelio/mackerel-agent/config\"\n\t\"github.com/mackerelio/mackerel-agent/metrics\"\n\tmetricsWindows \"github.com/mackerelio/mackerel-agent/metrics/windows\"\n\t\"github.com/mackerelio/mackerel-agent/spec\"\n\tspecWindows \"github.com/mackerelio/mackerel-agent/spec/windows\"\n)\n\n\n\nfunc interfaceGenerator() spec.Generator {\n\treturn &specWindows.InterfaceGenerator{}\n}\n\nfunc metricsGenerators(conf *config.Config) []metrics.Generator {\n\tvar g metrics.Generator\n\tvar err error\n\n\tgenerators := []metrics.Generator{}\n\tif g, err = metricsWindows.NewLoadavg5Generator(); err == nil {\n\t\tgenerators = append(generators, g)\n\t}\n\tif g, err = metricsWindows.NewCPUUsageGenerator(); err == nil {\n\t\tgenerators = append(generators, g)\n\t}\n\tif g, err = metricsWindows.NewMemoryGenerator(); err == nil {\n\t\tgenerators = append(generators, g)\n\t}\n\tif g, err = metricsWindows.NewFilesystemGenerator(); err == nil {\n\t\tgenerators = append(generators, g)\n\t}\n\tif g, err = metricsWindows.NewInterfaceGenerator(60); err == nil {\n\t\tgenerators = append(generators, g)\n\t}\n\tif g, err = metricsWindows.NewDiskGenerator(60); err == nil {\n\t\tgenerators = append(generators, g)\n\t}\n\tfor _, pluginConfig := range conf.Plugin[\"metrics\"] {\n\t\tif g, err = metricsWindows.NewPluginGenerator(pluginConfig); err == nil {\n\t\t\tgenerators = append(generators, g)\n\t\t}\n\t}\n\n\treturn generators\n}\n\nfunc pluginGenerators(conf *config.Config) []metrics.PluginGenerator {\n\treturn []metrics.PluginGenerator{}\n}\n\nfunc specGenerators() []spec.Generator ", "output": "{\n\treturn []spec.Generator{\n\t\t&specWindows.KernelGenerator{},\n\t\t&specWindows.CPUGenerator{},\n\t\t&specWindows.MemoryGenerator{},\n\t\t&specWindows.BlockDeviceGenerator{},\n\t\t&specWindows.FilesystemGenerator{},\n\t}\n}"} {"input": "package clock\n\nimport (\n\t\"time\"\n)\n\n\n\n\n\ntype Clock interface {\n\tNow() time.Time\n}\n\ntype clock struct{}\n\nfunc (c *clock) Now() time.Time {\n\treturn time.Now()\n}\n\n\ntype Mock struct {\n\tcurrentTime time.Time\n}\n\n\nfunc (c *Mock) SetNow(t time.Time) {\n\tc.currentTime = t\n}\n\n\n\n\n\nfunc New() Clock {\n\treturn &clock{}\n}\n\n\nfunc NewMock() *Mock {\n\treturn &Mock{\n\t\tcurrentTime: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),\n\t}\n}\n\nfunc (c *Mock) Now() time.Time ", "output": "{\n\treturn c.currentTime\n}"} {"input": "package executor\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n)\n\n\nfunc (e *UniversalExecutor) setNewProcessGroup() error {\n\tif e.childCmd.SysProcAttr == nil {\n\t\te.childCmd.SysProcAttr = &syscall.SysProcAttr{}\n\t}\n\te.childCmd.SysProcAttr.Setpgid = true\n\treturn nil\n}\n\n\nfunc (e *UniversalExecutor) cleanupChildProcesses(proc *os.Process) error {\n\tif e.childCmd.SysProcAttr != nil && e.childCmd.SysProcAttr.Setpgid {\n\t\tif err := syscall.Kill(-proc.Pid, syscall.SIGKILL); err != nil && err.Error() != noSuchProcessErr {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\treturn proc.Kill()\n}\n\n\n\n\n\nfunc (e *UniversalExecutor) shutdownProcess(sig os.Signal, proc *os.Process) error ", "output": "{\n\tif sig == nil {\n\t\tsig = os.Interrupt\n\t}\n\n\tif err := proc.Signal(sig); err != nil && err.Error() != finishedErr {\n\t\treturn fmt.Errorf(\"executor shutdown error: %v\", err)\n\t}\n\n\treturn nil\n}"} {"input": "package server\n\nimport (\n\t\"context\"\n\n\tsrvconfig \"github.com/containerd/containerd/services/server/config\"\n\t\"github.com/containerd/ttrpc\"\n)\n\nfunc apply(_ context.Context, _ *srvconfig.Config) error {\n\treturn nil\n}\n\n\n\nfunc newTTRPCServer() (*ttrpc.Server, error) ", "output": "{\n\treturn ttrpc.NewServer()\n}"} {"input": "package graph\n\nimport (\n\t\"database/sql/driver\"\n\t\"fmt\"\n)\n\n\ntype StatType string\n\n\ntype Stats map[StatType]int\n\nconst (\n\tStatXRefs = \"xrefs\"\n\n\tStatRRefs = \"rrefs\"\n\n\tStatURefs = \"urefs\"\n\n\tStatAuthors = \"authors\"\n\n\tStatClients = \"clients\"\n\n\tStatDependents = \"dependents\"\n\n\tStatExportedElements = \"exported_elements\"\n)\n\nvar AllStatTypes = []StatType{StatXRefs, StatRRefs, StatURefs, StatAuthors, StatClients, StatDependents, StatExportedElements}\n\nfunc (x StatType) IsAbstract() bool {\n\tswitch x {\n\tcase StatXRefs:\n\t\tfallthrough\n\tcase StatClients:\n\t\tfallthrough\n\tcase StatDependents:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\n\n\n\nfunc (x *StatType) Scan(v interface{}) error {\n\tif data, ok := v.([]byte); ok {\n\t\t*x = StatType(data)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"%T.Scan failed: %v\", x, v)\n}\n\n\n\n\nfunc UniqueRefDefs(refs []*Ref, m map[RefDefKey]int) map[RefDefKey]int {\n\tif m == nil {\n\t\tm = make(map[RefDefKey]int)\n\t}\n\tfor _, ref := range refs {\n\t\tm[ref.RefDefKey()]++\n\t}\n\treturn m\n}\n\nfunc (x StatType) Value() (driver.Value, error) ", "output": "{\n\treturn string(x), nil\n}"} {"input": "package osutil\n\nimport (\n\t\"context\"\n\t\"net/url\"\n\t\"time\"\n\n\t\"github.com/syncthing/syncthing/lib/dialer\"\n)\n\n\n\n\n\n\n\n\nfunc GetLatencyForURL(ctx context.Context, addr string) (time.Duration, error) {\n\turi, err := url.Parse(addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn TCPPing(ctx, uri.Host)\n}\n\nfunc TCPPing(ctx context.Context, address string) (time.Duration, error) ", "output": "{\n\tstart := time.Now()\n\tctx, cancel := context.WithTimeout(ctx, time.Second)\n\tdefer cancel()\n\tconn, err := dialer.DialContext(ctx, \"tcp\", address)\n\tif err == nil {\n\t\tconn.Close()\n\t}\n\treturn time.Since(start), err\n}"} {"input": "package reader_nop_close\n\nimport \"io\"\n\ntype nopCloser struct {\n\tio.Reader\n}\n\nfunc (nopCloser) Close() error {\n\treturn nil\n}\n\n\n\nfunc New(r io.Reader) io.ReadCloser ", "output": "{\n\treturn nopCloser{r}\n}"} {"input": "package lints\n\n\n\n\n\nimport (\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/util\"\n)\n\ntype caKeyCertSignNotSet struct{}\n\n\n\nfunc (l *caKeyCertSignNotSet) CheckApplies(c *x509.Certificate) bool {\n\treturn c.IsCA && util.IsExtInCert(c, util.KeyUsageOID)\n}\n\nfunc (l *caKeyCertSignNotSet) Execute(c *x509.Certificate) *LintResult {\n\tif c.KeyUsage&x509.KeyUsageCertSign != 0 {\n\t\treturn &LintResult{Status: Pass}\n\t} else {\n\t\treturn &LintResult{Status: Error}\n\t}\n}\n\nfunc init() {\n\tRegisterLint(&Lint{\n\t\tName: \"e_ca_key_cert_sign_not_set\",\n\t\tDescription: \"Root CA Certificate: Bit positions for keyCertSign and cRLSign MUST be set.\",\n\t\tCitation: \"BRs: 7.1.2.1\",\n\t\tSource: CABFBaselineRequirements,\n\t\tEffectiveDate: util.CABEffectiveDate,\n\t\tLint: &caKeyCertSignNotSet{},\n\t})\n}\n\nfunc (l *caKeyCertSignNotSet) Initialize() error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\tosexec \"os/exec\"\n\t\"path/filepath\"\n)\n\n\n\n\n\nfunc execVerbose(args ...string) error {\n\tcmd := osexec.Command(args[0], args[1:]...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}\n\n\nfunc execCompose(dir string, args ...string) error {\n\treturn exec(append(\n\t\t[]string{\"docker-compose\", \"--ansi=never\", \"-f\", filepath.Join(dir, \"docker-compose.yml\")},\n\t\targs...)...)\n}\n\n\nfunc execComposeVerbose(dir string, args ...string) error {\n\treturn execVerbose(append(\n\t\t[]string{\"docker-compose\", \"--ansi=never\", \"-f\", filepath.Join(dir, \"docker-compose.yml\")},\n\t\targs...)...)\n}\n\n\nfunc execDocker(args ...string) error {\n\treturn exec(append([]string{\"docker\"}, args...)...)\n}\n\nfunc exec(args ...string) error ", "output": "{\n\tcmd := osexec.Command(args[0], args[1:]...)\n\tout, err := cmd.CombinedOutput()\n\tswitch err := err.(type) {\n\tcase nil:\n\t\treturn nil\n\tcase *osexec.ExitError:\n\t\treturn fmt.Errorf(\"failed to run %q:\\n%v\", args, string(out))\n\tdefault:\n\t\treturn err\n\t}\n}"} {"input": "package iso20022\n\n\ntype AllegementStatus3Choice struct {\n\n\tCode *AllegementStatus1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification30 `xml:\"Prtry\"`\n}\n\nfunc (a *AllegementStatus3Choice) SetCode(value string) {\n\ta.Code = (*AllegementStatus1Code)(&value)\n}\n\n\n\nfunc (a *AllegementStatus3Choice) AddProprietary() *GenericIdentification30 ", "output": "{\n\ta.Proprietary = new(GenericIdentification30)\n\treturn a.Proprietary\n}"} {"input": "package rediscmd\n\nfunc String(b []byte) string {\n\treturn string(b)\n}\n\n\n\nfunc Bytes(s string) []byte ", "output": "{\n\treturn []byte(s)\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"text/tabwriter\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nvar preFilterListCmd = &cobra.Command{\n\tUse: \"list\",\n\tShort: \"List CIDR filters\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tlistFilters(cmd, args)\n\t},\n}\n\n\n\nfunc listFilters(cmd *cobra.Command, args []string) {\n\tvar str string\n\tcl, err := client.GetPrefilter()\n\tif err != nil {\n\t\tFatalf(\"Cannot get CIDR list: %s\", err)\n\t}\n\tw := tabwriter.NewWriter(os.Stdout, 5, 0, 3, ' ', 0)\n\tstr = fmt.Sprintf(\"Revision: %d\", cl.Revision)\n\tfmt.Fprintln(w, str)\n\tfor _, pfx := range cl.List {\n\t\tstr = fmt.Sprintf(\"%s\", pfx)\n\t\tfmt.Fprintln(w, str)\n\t}\n\tw.Flush()\n}\n\nfunc init() ", "output": "{\n\tpreFilterCmd.AddCommand(preFilterListCmd)\n\tAddMultipleOutput(preFilterListCmd)\n}"} {"input": "package util\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\n\tapi \"github.com/appscode/searchlight/apis/monitoring/v1alpha1\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"kmodules.xyz/client-go/meta\"\n)\n\nfunc GetGroupVersionKind(v interface{}) schema.GroupVersionKind {\n\treturn api.SchemeGroupVersion.WithKind(meta.GetKind(v))\n}\n\n\n\nfunc AssignTypeKind(v interface{}) error ", "output": "{\n\tif reflect.ValueOf(v).Kind() != reflect.Ptr {\n\t\treturn fmt.Errorf(\"%v must be a pointer\", v)\n\t}\n\n\tswitch u := v.(type) {\n\tcase *api.ClusterAlert:\n\t\tu.APIVersion = api.SchemeGroupVersion.String()\n\t\tu.Kind = meta.GetKind(v)\n\t\treturn nil\n\tcase *api.NodeAlert:\n\t\tu.APIVersion = api.SchemeGroupVersion.String()\n\t\tu.Kind = meta.GetKind(v)\n\t\treturn nil\n\tcase *api.PodAlert:\n\t\tu.APIVersion = api.SchemeGroupVersion.String()\n\t\tu.Kind = meta.GetKind(v)\n\t\treturn nil\n\t}\n\treturn errors.New(\"unknown api object type\")\n}"} {"input": "package iso20022\n\n\ntype SettlementStatus10Choice struct {\n\n\tPending *PendingStatus15Choice `xml:\"Pdg\"`\n\n\tFailing *FailingStatus3Choice `xml:\"Flng\"`\n\n\tProprietary *ProprietaryStatusAndReason1 `xml:\"Prtry\"`\n}\n\nfunc (s *SettlementStatus10Choice) AddPending() *PendingStatus15Choice {\n\ts.Pending = new(PendingStatus15Choice)\n\treturn s.Pending\n}\n\n\n\nfunc (s *SettlementStatus10Choice) AddProprietary() *ProprietaryStatusAndReason1 {\n\ts.Proprietary = new(ProprietaryStatusAndReason1)\n\treturn s.Proprietary\n}\n\nfunc (s *SettlementStatus10Choice) AddFailing() *FailingStatus3Choice ", "output": "{\n\ts.Failing = new(FailingStatus3Choice)\n\treturn s.Failing\n}"} {"input": "package main\n\nimport (\n\t\"github.com/syscrusher/fake\"\n)\n\nconst (\n\tcolumnCreditCardNumber = \"credit_card.number\"\n\tcolumnCreditCardType = \"credit_card.type\"\n)\n\ntype ColumnCreditCardNumberPayload struct {\n\tType string\n}\n\ntype ColumnCreditCardNumber struct {\n\tTypedColumnBase\n\tpayload ColumnCreditCardNumberPayload\n}\n\n\n\ntype ColumnCreditCardType struct {\n\tTypedColumnBase\n}\n\nfunc (column ColumnCreditCardType) Value(chunk *Chunk) (string, error) {\n\treturn fake.CreditCardType(), nil\n}\n\nfunc (column ColumnCreditCardNumber) Value(chunk *Chunk) (string, error) ", "output": "{\n\treturn fake.CreditCardNum(column.payload.Type), nil\n}"} {"input": "package middleware\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"runtime\"\n\n\t\"github.com/docker/docker/pkg/version\"\n\t\"golang.org/x/net/context\"\n)\n\ntype badRequestError struct {\n\terror\n}\n\nfunc (badRequestError) HTTPErrorStatusCode() int {\n\treturn http.StatusBadRequest\n}\n\n\n\ntype VersionMiddleware struct {\n\tserverVersion version.Version\n\tdefaultVersion version.Version\n\tminVersion version.Version\n}\n\n\n\n\n\n\nfunc (v VersionMiddleware) WrapHandler(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {\n\t\tapiVersion := version.Version(vars[\"version\"])\n\t\tif apiVersion == \"\" {\n\t\t\tapiVersion = v.defaultVersion\n\t\t}\n\n\t\tif apiVersion.GreaterThan(v.defaultVersion) {\n\t\t\treturn badRequestError{fmt.Errorf(\"client is newer than server (client API version: %s, server API version: %s)\", apiVersion, v.defaultVersion)}\n\t\t}\n\t\tif apiVersion.LessThan(v.minVersion) {\n\t\t\treturn badRequestError{fmt.Errorf(\"client version %s is too old. Minimum supported API version is %s, please upgrade your client to a newer version\", apiVersion, v.minVersion)}\n\t\t}\n\n\t\theader := fmt.Sprintf(\"Docker/%s (%s)\", v.serverVersion, runtime.GOOS)\n\t\tw.Header().Set(\"Server\", header)\n\t\tctx = context.WithValue(ctx, \"api-version\", apiVersion)\n\t\treturn handler(ctx, w, r, vars)\n\t}\n\n}\n\nfunc NewVersionMiddleware(s, d, m version.Version) VersionMiddleware ", "output": "{\n\treturn VersionMiddleware{\n\t\tserverVersion: s,\n\t\tdefaultVersion: d,\n\t\tminVersion: m,\n\t}\n}"} {"input": "package event \n\nimport (\n\t\"github.com/docker/infrakit/pkg/spi/event\"\n\t\"github.com/docker/infrakit/pkg/types\"\n)\n\n\ntype Plugin struct {\n\tevent.Publisher\n\n\tDoList func(topic types.Path) (child []string, err error)\n}\n\n\n\n\n\ntype Publisher struct {\n\n\tDoPublishOn func(chan<- *event.Event)\n}\n\n\nfunc (t *Publisher) PublishOn(c chan<- *event.Event) {\n\tif t == nil {\n\t\treturn\n\t}\n\tt.DoPublishOn(c)\n}\n\nfunc (t *Plugin) List(topic types.Path) (child []string, err error) ", "output": "{\n\treturn t.DoList(topic)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Player struct {\n\tID string\n\tName string\n\tHealth int\n\tHunger int\n\tCriticalHunger bool\n\tNextAction int\n\tDead bool\n}\n\n\nfunc NewPlayer(ID, name string) *Player {\n\treturn &Player{ID, name, 100, 0, false, 0, false}\n}\n\n\n\n\nfunc (p *Player) AddHealth(amount int) bool {\n\tp.Health += amount\n\tif p.Health > 100 {\n\t\tp.Health = 100\n\t}\n\tif p.Health <= 0 {\n\t\tp.Health = 0\n\t\tp.Dead = true\n\t\treturn true\n\t}\n\treturn false\n}\n\n\nfunc (p *Player) AddHunger(amount int) int {\n\tp.Hunger += amount\n\tif p.Hunger >= 100 {\n\t\tp.Hunger = 100\n\t\tif p.CriticalHunger {\n\t\t\treturn 2\n\t\t}\n\t\tp.CriticalHunger = true\n\t\treturn 1\n\t}\n\tif p.Hunger <= 0 {\n\t\tp.Hunger = 0\n\t}\n\treturn 0\n}\n\nfunc (p *Player) String() string ", "output": "{\n\treturn fmt.Sprintf(\"[%-12s](HP: %3d)\", p.Name, p.Health, p.Hunger)\n}"} {"input": "package lwmq\n\nimport (\n\t\"fmt\"\n)\n\n\ntype MessageStore interface {\n\n\tMessages(*Queue) ([]*Message, error)\n\n\tAddMessage(*Message) error\n\n\tPopMessages(*Queue) ([]*Message, error)\n}\n\n\ntype MemoryMessageStore struct {\n\tmessages map[*Queue][]*Message\n}\n\n\n\n\n\n\nfunc (self *MemoryMessageStore) AddMessage(msg *Message) error {\n\tif msg.Queue == nil {\n\t\terr := fmt.Errorf(\"Can not store message without a queue\")\n\t\treturn err\n\t}\n\n\tmsg.Offline = true\n\n\tself.messages[msg.Queue] = append(self.messages[msg.Queue], msg)\n\n\treturn nil\n}\n\n\nfunc (self *MemoryMessageStore) Messages(q *Queue) ([]*Message, error) {\n\tmessages, ok := self.messages[q]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Unknown queue: %s\", q.Id)\n\t}\n\n\treturn messages, nil\n}\n\n\nfunc (self *MemoryMessageStore) PopMessages(q *Queue) ([]*Message, error) {\n\tmessages, err := self.Messages(q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tself.messages[q] = []*Message{}\n\n\treturn messages, nil\n}\n\nfunc NewMemoryMessageStore() *MemoryMessageStore ", "output": "{\n\ts := &MemoryMessageStore{\n\t\tmessages: make(map[*Queue][]*Message),\n\t}\n\treturn s\n}"} {"input": "package sdk\n\nimport (\n\t\"io/ioutil\"\n\t\"net/url\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\ntype hydraConfig struct {\n\tClusterURL string `yaml:\"cluster_url\"`\n\tClientID string `yaml:\"client_id\"`\n\tClientSecret string `yaml:\"client_secret\"`\n}\n\n\nfunc FromYAML(file string) option {\n\treturn func(c *Client) error {\n\t\tvar err error\n\t\tvar config = hydraConfig{}\n\n\t\tdata, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = yaml.Unmarshal(data, &config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.clusterURL, err = url.Parse(config.ClusterURL)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.clientID = config.ClientID\n\t\tc.clientSecret = config.ClientSecret\n\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ClientID(id string) option {\n\treturn func(c *Client) error {\n\t\tc.clientID = id\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc ClientSecret(secret string) option {\n\treturn func(c *Client) error {\n\t\tc.clientSecret = secret\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc SkipTLSVerify() option {\n\treturn func(c *Client) error {\n\t\tc.skipTLSVerify = true\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc Scopes(scopes ...string) option {\n\treturn func(c *Client) error {\n\t\tc.scopes = scopes\n\t\treturn nil\n\t}\n}\n\nfunc ClusterURL(urlStr string) option ", "output": "{\n\treturn func(c *Client) error {\n\t\tvar err error\n\t\tc.clusterURL, err = url.Parse(urlStr)\n\t\treturn err\n\t}\n}"} {"input": "package models\n\n\ntype IssueLockOptions struct {\n\tDoer *User\n\tIssue *Issue\n\tReason string\n}\n\n\n\nfunc LockIssue(opts *IssueLockOptions) error {\n\treturn updateIssueLock(opts, true)\n}\n\n\nfunc UnlockIssue(opts *IssueLockOptions) error {\n\treturn updateIssueLock(opts, false)\n}\n\n\n\nfunc updateIssueLock(opts *IssueLockOptions, lock bool) error ", "output": "{\n\tif opts.Issue.IsLocked == lock {\n\t\treturn nil\n\t}\n\n\topts.Issue.IsLocked = lock\n\tvar commentType CommentType\n\tif opts.Issue.IsLocked {\n\t\tcommentType = CommentTypeLock\n\t} else {\n\t\tcommentType = CommentTypeUnlock\n\t}\n\n\tsess := x.NewSession()\n\tdefer sess.Close()\n\tif err := sess.Begin(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := updateIssueCols(sess, opts.Issue, \"is_locked\"); err != nil {\n\t\treturn err\n\t}\n\n\tvar opt = &CreateCommentOptions{\n\t\tDoer: opts.Doer,\n\t\tIssue: opts.Issue,\n\t\tRepo: opts.Issue.Repo,\n\t\tType: commentType,\n\t\tContent: opts.Reason,\n\t}\n\tif _, err := createComment(sess, opt); err != nil {\n\t\treturn err\n\t}\n\n\treturn sess.Commit()\n}"} {"input": "package commands\n\nimport (\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nfunc Execute() {\n\trootCmd := &cobra.Command{Use: \"htflood\"}\n\tsetupCommands(rootCmd)\n\trootCmd.Execute()\n}\n\nfunc setupCommands(rootCmd *cobra.Command) {\n\trootCmd.AddCommand(botCommand)\n\trootCmd.AddCommand(statsCommand)\n\trootCmd.AddCommand(reqCommand)\n}\n\n\n\nfunc checkedRun(run func(cmd *cobra.Command, args []string) error) func(cmd *cobra.Command, args []string) ", "output": "{\n\n\treturn func(cmd *cobra.Command, args []string) {\n\t\tif err := run(cmd, args); err != nil {\n\t\t\tlog.Fatalf(\"%v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}"} {"input": "package sliceset\n\nimport (\n\t\"sort\"\n\n\t\"github.com/xtgo/set\"\n)\n\ntype Set []int\n\nfunc (s Set) Len() int { return len(s) }\nfunc (s Set) Less(i, j int) bool { return s[i] < s[j] }\nfunc (s Set) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s Set) Copy() Set { return append(Set(nil), s...) }\n\nfunc (s Set) Union(t Set) Set { return s.Do(set.Union, t) }\n\nfunc (s Set) Diff(t Set) Set { return s.Do(set.Diff, t) }\nfunc (s Set) SymDiff(t Set) Set { return s.Do(set.SymDiff, t) }\nfunc (s Set) IsSub(t Set) bool { return s.DoBool(set.IsSub, t) }\nfunc (s Set) IsSuper(t Set) bool { return s.DoBool(set.IsSuper, t) }\nfunc (s Set) IsInter(t Set) bool { return s.DoBool(set.IsInter, t) }\nfunc (s Set) IsEqual(t Set) bool { return s.DoBool(set.IsEqual, t) }\n\nfunc (s Set) Uniq() Set {\n\tn := set.Uniq(s)\n\treturn s[:n]\n}\n\nfunc (s Set) Do(op set.Op, t Set) Set {\n\tdata := append(s, t...)\n\tn := op(data, len(s))\n\treturn data[:n]\n}\n\ntype BoolOp func(sort.Interface, int) bool\n\nfunc (s Set) DoBool(op BoolOp, t Set) bool {\n\tdata := append(s, t...)\n\treturn op(data, len(s))\n}\n\nfunc (s Set) Inter(t Set) Set ", "output": "{ return s.Do(set.Inter, t) }"} {"input": "package util\n\nimport \"log\"\n\n\nfunc ShowStringArray(strArray []string, desc string) {\n\tlog.Printf(\"%s\\n\", desc)\n\tfor _, v := range strArray {\n\t\tlog.Printf(\" %s\\n\", v)\n\t}\n\tlog.Printf(\"\\n\")\n}\n\n\nfunc ShowMapOfStrings(m map[string]string, desc string) {\n\tlog.Printf(\"%s\\n\", desc)\n\tfor k, v := range m {\n\t\tlog.Printf(\" %s: %s\\n\", k, v)\n\t}\n\tlog.Printf(\"\\n\")\n}\n\n\n\n\nfunc ShowMapOfStringArray(m map[string][]string, desc string) ", "output": "{\n\tlog.Printf(\"%s\\n\", desc)\n\tfor k, v := range m {\n\t\tShowStringArray(v, k)\n\t}\n\tlog.Printf(\"\\n\")\n}"} {"input": "package v1alpha1\n\nimport (\n\tcorev1 \"k8s.io/api/core/v1\"\n)\n\n\n\ntype ListBuilder struct {\n\tlist *PodList\n\tfilters predicateList\n}\n\n\n\n\n\nfunc ListBuilderForAPIList(pods *corev1.PodList) *ListBuilder {\n\tb := &ListBuilder{list: &PodList{}}\n\tif pods == nil {\n\t\treturn b\n\t}\n\tfor _, p := range pods.Items {\n\t\tp := p\n\t\tb.list.items = append(b.list.items, &Pod{object: &p})\n\t}\n\treturn b\n}\n\n\nfunc ListBuilderForObjectList(pods ...*Pod) *ListBuilder {\n\tb := &ListBuilder{list: &PodList{}}\n\tif pods == nil {\n\t\treturn b\n\t}\n\tfor _, p := range pods {\n\t\tp := p\n\t\tb.list.items = append(b.list.items, p)\n\t}\n\treturn b\n}\n\n\n\n\nfunc (b *ListBuilder) List() *PodList {\n\tif b.filters == nil || len(b.filters) == 0 {\n\t\treturn b.list\n\t}\n\tfiltered := &PodList{}\n\tfor _, pod := range b.list.items {\n\t\tif b.filters.all(pod) {\n\t\t\tfiltered.items = append(filtered.items, pod)\n\t\t}\n\t}\n\treturn filtered\n}\n\n\n\nfunc (b *ListBuilder) WithFilter(pred ...Predicate) *ListBuilder {\n\tb.filters = append(b.filters, pred...)\n\treturn b\n}\n\nfunc NewListBuilder() *ListBuilder ", "output": "{\n\treturn &ListBuilder{list: &PodList{items: []*Pod{}}}\n}"} {"input": "package multiwriter\n\nimport (\n\t\"io\"\n)\n\n\ntype multiWriter []io.Writer\n\n\nfunc New(w ...io.Writer) io.Writer {\n\treturn multiWriter(w)\n}\n\n\nfunc (mw multiWriter) Write(p []byte) (int, error) {\n\tdone := make(chan result, len(mw))\n\tfor _, w := range mw {\n\t\tgo send(w, p, done)\n\t}\n\tendResult := result{n: len(p)}\n\tfor _ = range mw {\n\t\tres := <-done\n\t\tif res.err != nil && (endResult.err == nil || res.n < endResult.n) {\n\t\t\tendResult = res\n\t\t}\n\t}\n\treturn endResult.n, endResult.err\n}\n\n\n\ntype result struct {\n\tn int\n\terr error\n}\n\nfunc send(w io.Writer, p []byte, done chan<- result) ", "output": "{\n\tvar res result\n\tres.n, res.err = w.Write(p)\n\tif res.n < len(p) && res.err == nil {\n\t\tres.err = io.ErrShortWrite\n\t}\n\tdone <- res\n}"} {"input": "package unittest\n\nimport (\n\t\"io/ioutil\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/Huawei/dockyard/utils\"\n)\n\n\n\n\n\nfunc TestMetaItemGenerate(t *testing.T) {\n\t_, path, _, _ := runtime.Caller(0)\n\tdir := filepath.Join(filepath.Dir(path), \"testdata\")\n\n\ttestContentFile := filepath.Join(dir, \"hello.txt\")\n\ttestHashFile := filepath.Join(dir, \"hello.hash\")\n\tcontentByte, _ := ioutil.ReadFile(testContentFile)\n\thashByte, _ := ioutil.ReadFile(testHashFile)\n\tmetaItem := utils.GenerateMetaItem(\"hello.txt\", contentByte)\n\tassert.Equal(t, metaItem.GetHash(), strings.TrimSpace(string(hashByte)), \"Fail to get correct hash value\")\n}\n\n\nfunc TestMetaTime(t *testing.T) {\n\ttest1 := \"test1\"\n\ttest1Byte := []byte(\"test1 byte\")\n\tmetaItem1 := utils.GenerateMetaItem(test1, test1Byte)\n\tmetaItem2 := metaItem1\n\tassert.Equal(t, metaItem1, metaItem2, \"Fail to compare metaItem, should be the same\")\n\n\tmetaItem2.SetCreated(metaItem2.GetCreated().Add(time.Hour * 1))\n\tcmp := metaItem1.Compare(metaItem2)\n\tassert.Equal(t, cmp < 0, true, \"Fail to compare metaItem, should be smaller\")\n\n\tassert.Equal(t, metaItem2.IsExpired(), false, \"Fail to get expired information\")\n\tmetaItem2.SetExpired(time.Now().Add(time.Hour * (-1)))\n\tassert.Equal(t, metaItem2.IsExpired(), true, \"Fail to get expired information\")\n}\n\nfunc TestMetaEncrypt(t *testing.T) ", "output": "{\n\tvar item utils.MetaItem\n\n\titem.SetEncryption(utils.EncryptRSA)\n\tassert.Equal(t, true, item.GetEncryption() == utils.EncryptRSA, \"Fail to set/get entrypt method\")\n}"} {"input": "package main\n\nimport (\n\t\"code.google.com/p/go.net/websocket\"\n\t\"log\"\n \"strconv\"\n)\n\nconst bufferSize = 100\n\nvar maxId uint64 = 0\n\ntype Client struct {\n\tid uint64\n\tws *websocket.Conn\n\trace *Race\n\tch chan *Message\n}\n\nfunc NewClient(ws *websocket.Conn, race *Race) *Client {\n\tmaxId++\n\tch := make(chan *Message, bufferSize)\n\treturn &Client{maxId, ws, race, ch}\n}\n\nfunc (c *Client) Conn() *websocket.Conn {\n\treturn c.ws\n}\n\nfunc (c *Client) Write(msg *Message) {\n\tselect {\n\tcase c.ch <- msg:\n\tdefault:\n\t\tc.race.Del(c)\n\t\tlog.Println(\"Client\", c.id, \"disconnected\")\n\t}\n}\n\nfunc (c *Client) Listen() {\n\tgo c.listenWrite()\n\tc.listenRead()\n}\n\nfunc (c *Client) listenWrite() {\n\tfor {\n\t\tselect {\n\t\tcase msg := <-c.ch:\n\t\t\twebsocket.JSON.Send(c.ws, msg)\n\t\t\tlog.Println(\"Sending to\", c.id, \":\", msg)\n\t\t}\n\t}\n}\n\n\n\nfunc (c *Client) listenRead() ", "output": "{\n\tfor {\n\t\tselect {\n\t\tdefault:\n\t\t\tvar msg Message\n\t\t\tif err := websocket.JSON.Receive(c.ws, &msg);err!=nil{\n if err.Error()==\"EOF\"{\n c.race.Del(c)\n return\n }\n log.Println(\"Unhandled error:\",err)\n return\n }\n\t\t\tlog.Println(c.id, \"got:\", msg)\n\n if msg.Type==\"word\"{\n i,err:=strconv.Atoi(msg.Body)\n if err!=nil{\n log.Println(err)\n continue\n }\n if i>c.race.best{\n c.race.best=i\n c.race.sendAll(&Message{\"best\",msg.Body,c.id})\n }\n }\n\t\t}\n\t}\n}"} {"input": "package gorocksdb\n\nimport (\n\t\"testing\"\n\n\t\"github.com/facebookgo/ensure\"\n)\n\n\n\nfunc TestFixedPrefixTransformOpen(t *testing.T) {\n\tdb := newTestDB(t, \"TestFixedPrefixTransformOpen\", func(opts *Options) {\n\t\topts.SetPrefixExtractor(NewFixedPrefixTransform(3))\n\t})\n\tdefer db.Close()\n}\n\nfunc TestNewNoopPrefixTransform(t *testing.T) {\n\tdb := newTestDB(t, \"TestNewNoopPrefixTransform\", func(opts *Options) {\n\t\topts.SetPrefixExtractor(NewNoopPrefixTransform())\n\t})\n\tdefer db.Close()\n}\n\ntype testSliceTransform struct {\n\tinitiated bool\n}\n\nfunc (st *testSliceTransform) Name() string { return \"gorocksdb.test\" }\nfunc (st *testSliceTransform) Transform(src []byte) []byte { return src[0:3] }\nfunc (st *testSliceTransform) InDomain(src []byte) bool { return len(src) >= 3 }\nfunc (st *testSliceTransform) InRange(src []byte) bool { return len(src) == 3 }\n\nfunc TestSliceTransform(t *testing.T) ", "output": "{\n\tdb := newTestDB(t, \"TestSliceTransform\", func(opts *Options) {\n\t\topts.SetPrefixExtractor(&testSliceTransform{})\n\t})\n\tdefer db.Close()\n\n\two := NewDefaultWriteOptions()\n\tensure.Nil(t, db.Put(wo, []byte(\"foo1\"), []byte(\"foo\")))\n\tensure.Nil(t, db.Put(wo, []byte(\"foo2\"), []byte(\"foo\")))\n\tensure.Nil(t, db.Put(wo, []byte(\"bar1\"), []byte(\"bar\")))\n\n\titer := db.NewIterator(NewDefaultReadOptions())\n\tdefer iter.Close()\n\tprefix := []byte(\"foo\")\n\tnumFound := 0\n\tfor iter.Seek(prefix); iter.ValidForPrefix(prefix); iter.Next() {\n\t\tnumFound++\n\t}\n\tensure.Nil(t, iter.Err())\n\tensure.DeepEqual(t, numFound, 2)\n}"} {"input": "package model\n\nimport (\n\t\"fmt\"\n\tnative_time \"time\"\n)\n\n\n\n\n\n\n\n\ntype Timestamp int64\n\nconst (\n\tMinimumTick = native_time.Second\n\tsecond = int64(native_time.Second / MinimumTick)\n)\n\n\nfunc (t Timestamp) Equal(o Timestamp) bool {\n\treturn t == o\n}\n\n\nfunc (t Timestamp) Before(o Timestamp) bool {\n\treturn t < o\n}\n\n\nfunc (t Timestamp) After(o Timestamp) bool {\n\treturn t > o\n}\n\n\nfunc (t Timestamp) Add(d native_time.Duration) Timestamp {\n\treturn t + Timestamp(d/MinimumTick)\n}\n\n\nfunc (t Timestamp) Sub(o Timestamp) native_time.Duration {\n\treturn native_time.Duration(t-o) * MinimumTick\n}\n\n\n\n\n\n\nfunc (t Timestamp) Unix() int64 {\n\treturn int64(t) / second\n}\n\n\nfunc (t Timestamp) String() string {\n\treturn fmt.Sprint(int64(t))\n}\n\n\nfunc Now() Timestamp {\n\treturn TimestampFromTime(native_time.Now())\n}\n\n\nfunc TimestampFromTime(t native_time.Time) Timestamp {\n\treturn TimestampFromUnix(t.Unix())\n}\n\n\nfunc TimestampFromUnix(t int64) Timestamp {\n\treturn Timestamp(t * second)\n}\n\nfunc (t Timestamp) Time() native_time.Time ", "output": "{\n\treturn native_time.Unix(int64(t)/second, (int64(t) % second))\n}"} {"input": "package packages\n\nimport (\n\t\"testing\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/docker/docker/api/types/container\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestNewPackageFromImage(t *testing.T) {\n\tpkg, err := NewPackageFromImage(\"whalebrew/foo:bar\", types.ImageInspect{})\n\tassert.Nil(t, err)\n\tassert.Equal(t, pkg.Name, \"foo\")\n\tassert.Equal(t, pkg.Image, \"whalebrew/foo:bar\")\n\n\tpkg, err = NewPackageFromImage(\"whalebrew/whalesay\", types.ImageInspect{\n\t\tContainerConfig: &container.Config{\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"io.whalebrew.name\": \"ws\",\n\t\t\t\t\"io.whalebrew.config.environment\": \"[\\\"SOME_CONFIG_OPTION\\\"]\",\n\t\t\t\t\"io.whalebrew.config.volumes\": \"[\\\"/somesource:/somedest\\\"]\",\n\t\t\t\t\"io.whalebrew.config.ports\": \"[\\\"8100:8100\\\"]\",\n\t\t\t\t\"io.whalebrew.config.networks\": \"[\\\"host\\\"]\",\n\t\t\t},\n\t\t},\n\t})\n\tassert.Nil(t, err)\n\tassert.Equal(t, pkg.Name, \"ws\")\n\tassert.Equal(t, pkg.Image, \"whalebrew/whalesay\")\n\tassert.Equal(t, pkg.Environment, []string{\"SOME_CONFIG_OPTION\"})\n\tassert.Equal(t, pkg.Volumes, []string{\"/somesource:/somedest\"})\n\tassert.Equal(t, pkg.Ports, []string{\"8100:8100\"})\n\tassert.Equal(t, pkg.Networks, []string{\"host\"})\n\n}\n\n\n\nfunc TestPreinstallMessage(t *testing.T) ", "output": "{\n\tpkg := &Package{}\n\tassert.Equal(t, pkg.PreinstallMessage(), \"\")\n\n\tpkg = &Package{\n\t\tEnvironment: []string{\"AWS_ACCESS_KEY\"},\n\t\tPorts: []string{\n\t\t\t\"80:80\",\n\t\t\t\"81:81:udp\",\n\t\t},\n\t\tVolumes: []string{\n\t\t\t\"/etc/passwd:/passwdtosteal\",\n\t\t\t\"/etc/readonly:/readonly:ro\",\n\t\t},\n\t}\n\tassert.Equal(t, pkg.PreinstallMessage(),\n\t\t\"This package needs additional access to your system. It wants to:\\n\"+\n\t\t\t\"\\n\"+\n\t\t\t\"* Read the environment variable AWS_ACCESS_KEY\\n\"+\n\t\t\t\"* Listen on TCP port 80\\n\"+\n\t\t\t\"* Listen on UDP port 81\\n\"+\n\t\t\t\"* Read and write to the file or directory \\\"/etc/passwd\\\"\\n\"+\n\t\t\t\"* Read the file or directory \\\"/etc/readonly\\\"\\n\",\n\t)\n}"} {"input": "package aws\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/aws/aws-sdk-go/service/outposts\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/v2/terraform\"\n)\n\nfunc TestAccAWSOutpostsSitesDataSource_basic(t *testing.T) {\n\tdataSourceName := \"data.aws_outposts_sites.test\"\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsSites(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: nil,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSOutpostsSitesDataSourceConfig(),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckOutpostsSitesAttributes(dataSourceName),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\n\n\nfunc testAccPreCheckAWSOutpostsSites(t *testing.T) {\n\tconn := testAccProvider.Meta().(*AWSClient).outpostsconn\n\n\tinput := &outposts.ListSitesInput{}\n\n\toutput, err := conn.ListSites(input)\n\n\tif testAccPreCheckSkipError(err) {\n\t\tt.Skipf(\"skipping acceptance testing: %s\", err)\n\t}\n\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected PreCheck error: %s\", err)\n\t}\n\n\tif output == nil || len(output.Sites) == 0 {\n\t\tt.Skip(\"skipping since no Sites Outpost found\")\n\t}\n}\n\nfunc testAccAWSOutpostsSitesDataSourceConfig() string {\n\treturn `\ndata \"aws_outposts_sites\" \"test\" {}\n`\n}\n\nfunc testAccCheckOutpostsSitesAttributes(dataSourceName string) resource.TestCheckFunc ", "output": "{\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[dataSourceName]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", dataSourceName)\n\t\t}\n\n\t\tif v := rs.Primary.Attributes[\"ids.#\"]; v == \"0\" {\n\t\t\treturn fmt.Errorf(\"expected at least one ids result, got none\")\n\t\t}\n\n\t\treturn nil\n\t}\n}"} {"input": "package sync\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\n\ntype Init struct {\n\tm sync.Mutex\n\tdone uint32\n\terr error\n}\n\n\n\n\n\n\n\nfunc (init *Init) Do(initializer func() error) (err error) ", "output": "{\n\tif atomic.LoadUint32(&init.done) == 1 {\n\t\treturn init.err\n\t}\n\n\tinit.m.Lock()\n\tdefer init.m.Unlock()\n\n\tif init.done == 0 {\n\t\tdefer atomic.StoreUint32(&init.done, 1)\n\n\t\tdefer func() {\n\t\t\tif recoveredErr := recover(); recoveredErr != nil {\n\t\t\t\tinit.err = fmt.Errorf(\"panic during init: %s\", recoveredErr)\n\n\t\t\t\terr = init.err\n\t\t\t}\n\t\t}()\n\n\t\tinit.err = initializer()\n\t\tif init.err != nil {\n\t\t\tinit.err = fmt.Errorf(\"error during init: %s\", init.err)\n\t\t}\n\t}\n\n\treturn init.err\n}"} {"input": "package managementagent\n\n\ntype EditModesEnum string\n\n\nconst (\n\tEditModesReadOnly EditModesEnum = \"READ_ONLY\"\n\tEditModesWritable EditModesEnum = \"WRITABLE\"\n\tEditModesExtensible EditModesEnum = \"EXTENSIBLE\"\n)\n\nvar mappingEditModes = map[string]EditModesEnum{\n\t\"READ_ONLY\": EditModesReadOnly,\n\t\"WRITABLE\": EditModesWritable,\n\t\"EXTENSIBLE\": EditModesExtensible,\n}\n\n\n\n\nfunc GetEditModesEnumValues() []EditModesEnum ", "output": "{\n\tvalues := make([]EditModesEnum, 0)\n\tfor _, v := range mappingEditModes {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package lock\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/bradfitz/gomemcache/memcache\"\n)\n\nconst testServer = \"localhost:11211\"\n\nfunc TestGetLockKey(t *testing.T) {\n\tm := &Memcache{Prefix: \"test:\"}\n\tif m.getLockKey(\"k\") != \"test:k\" {\n\t\tt.Errorf(\"Invalid lock key\")\n\t}\n}\n\n\n\nfunc TestAcquire(t *testing.T) ", "output": "{\n\tkey := \"k\"\n\tmc := memcache.New(testServer)\n\tm := &Memcache{Prefix: \"test:\", Cache: mc}\n\tm.Release(key)\n\tdefer m.Release(key)\n\n\tif !m.Acquire(key, 2, time.Microsecond, 1) {\n\t\tt.Error(\"Cannot acquire first lock\")\n\t}\n\tif m.Acquire(key, 2, time.Microsecond, 1) {\n\t\tt.Error(\"Can acquire lock when already acquired\")\n\t}\n\tif nil != m.Release(key) {\n\t\tt.Error(\"Cannot release log\")\n\t}\n}"} {"input": "package trueskill\n\nimport (\n\t\"errors\"\n\t\"math\"\n)\n\nconst (\n\tDefMu = 25.0\n\n\tDefSig = DefMu / 3\n\n\tDefBeta = DefSig / 2\n\n\tDefTau = DefSig / 100\n)\n\n\ntype Game struct {\n\tbeta float64\n\ttau float64\n\tpDraw float64\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc NewGame(beta, tau, pDraw float64) Game {\n\treturn Game{\n\t\tbeta: beta,\n\t\ttau: tau,\n\t\tpDraw: pDraw,\n\t}\n}\n\n\n\nfunc (g *Game) CalcNewRatings(teams []Team, ranks []int) (t []Team, err error) {\n\treturn\n}\n\n\n\nfunc (g *Game) CalcMatchQuality(teams []Team) (result float64, err error) {\n\tif len(teams) > 2 {\n\t\terr = errors.New(\"CalcMatchQuality does not support more than 2 teams yet.\")\n\t\treturn\n\t}\n\n\tnPlayers := float64(teams[0].Size() + teams[1].Size())\n\n\tt1Mean := teams[0].GetMu()\n\tt1Var := teams[0].GetVar()\n\tt2Mean := teams[1].GetMu()\n\tt2Var := teams[1].GetVar()\n\n\tsqrt := math.Sqrt(\n\t\t(nPlayers * g.beta * g.beta) /\n\t\t\t(nPlayers*g.beta*g.beta + t1Var + t2Var))\n\n\texp := math.Exp(\n\t\t-1 * (t1Mean - t2Mean) * (t1Mean - t2Mean) /\n\t\t\t(2 * (nPlayers*g.beta*g.beta + t1Var + t2Var)))\n\n\tresult = sqrt * exp\n\treturn\n}\n\nfunc NewDefaultGame() Game ", "output": "{\n\treturn NewGame(DefBeta, DefTau, 0)\n}"} {"input": "package config\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t_ \"github.com/confur-me/confur-api/lib/logrus\"\n\tcfg \"github.com/olebedev/config\"\n)\n\nvar c *cfg.Config\n\n\n\nfunc Read(path string) error {\n\tlog.Info(\"Reading configuration from \", path)\n\tvar err error\n\tc, err = cfg.ParseYamlFile(path)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\treturn err\n}\n\nfunc Config() *cfg.Config {\n\treturn c\n}\n\nfunc init() ", "output": "{\n\tc = new(cfg.Config)\n}"} {"input": "package victor\n\nimport (\n\t\"github.com/FogCreek/victor/pkg/chat\"\n)\n\n\ntype Handler interface {\n\tHandle(State)\n}\n\n\ntype HandlerFunc func(State)\n\n\n\n\n\n\n\ntype State interface {\n\tRobot() Robot\n\tChat() chat.Adapter\n\tMessage() chat.Message\n\tFields() []string\n\tReply(string)\n}\n\ntype state struct {\n\trobot Robot\n\tmessage chat.Message\n\tfields []string\n}\n\n\n\n\n\nfunc (s *state) Reply(msg string) {\n\ts.robot.Chat().Send(s.message.Channel().ID(), msg)\n}\n\n\nfunc (s *state) Robot() Robot {\n\treturn s.robot\n}\n\n\nfunc (s *state) Chat() chat.Adapter {\n\treturn s.robot.Chat()\n}\n\n\nfunc (s *state) Message() chat.Message {\n\treturn s.message\n}\n\nfunc (s *state) Fields() []string {\n\treturn s.fields\n}\n\nfunc (f HandlerFunc) Handle(s State) ", "output": "{\n\tf(s)\n}"} {"input": "package vpp2101\n\nimport (\n\tvpp_ip \"go.ligato.io/vpp-agent/v3/plugins/vpp/binapi/vpp2101/ip\"\n\tl3 \"go.ligato.io/vpp-agent/v3/proto/ligato/vpp/l3\"\n)\n\n\nfunc (h *VrfTableHandler) AddVrfTable(table *l3.VrfTable) error {\n\treturn h.addDelVrfTable(table, true)\n}\n\n\nfunc (h *VrfTableHandler) DelVrfTable(table *l3.VrfTable) error {\n\treturn h.addDelVrfTable(table, false)\n}\n\n\n\n\nfunc (h *VrfTableHandler) SetVrfFlowHashSettings(vrfID uint32, isIPv6 bool, hashFields *l3.VrfTable_FlowHashSettings) error {\n\treq := &vpp_ip.SetIPFlowHash{\n\t\tVrfID: vrfID,\n\t\tIsIPv6: isIPv6,\n\t\tSrc: hashFields.UseSrcIp,\n\t\tDst: hashFields.UseDstIp,\n\t\tSport: hashFields.UseSrcPort,\n\t\tDport: hashFields.UseDstPort,\n\t\tProto: hashFields.UseProtocol,\n\t\tReverse: hashFields.Reverse,\n\t\tSymmetric: hashFields.Symmetric,\n\t}\n\treply := &vpp_ip.SetIPFlowHashReply{}\n\n\terr := h.callsChannel.SendRequest(req).ReceiveReply(reply)\n\treturn err\n}\n\nfunc (h *VrfTableHandler) addDelVrfTable(table *l3.VrfTable, isAdd bool) error ", "output": "{\n\treq := &vpp_ip.IPTableAddDel{\n\t\tTable: vpp_ip.IPTable{\n\t\t\tTableID: table.Id,\n\t\t\tIsIP6: table.GetProtocol() == l3.VrfTable_IPV6,\n\t\t\tName: table.Label,\n\t\t},\n\t\tIsAdd: isAdd,\n\t}\n\treply := &vpp_ip.IPTableAddDelReply{}\n\n\tif err := h.callsChannel.SendRequest(req).ReceiveReply(reply); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package generic\n\nimport (\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype MockReader struct{ mock.Mock }\n\n\n\ntype MockWriter struct{ mock.Mock }\n\nfunc (w *MockWriter) Write(p []byte) (n int, err error) {\n\treturns := w.Called(p)\n\treturn returns.Int(0), returns.Error(1)\n}\n\ntype MockCloser struct{ mock.Mock }\n\nfunc (w *MockWriter) Close() error {\n\treturns := w.Called()\n\treturn returns.Error(0)\n}\n\ntype MockReadWriteCloser struct {\n\tMockReader\n\tMockWriter\n\tMockCloser\n}\n\nfunc (w *MockWriter) Read(p []byte) (n int, err error) ", "output": "{\n\treturns := w.Called(p)\n\treturn returns.Int(0), returns.Error(1)\n}"} {"input": "package router\n\nimport (\n\t\"github.com/kwoodhouse93/audio-playground/source\"\n\t\"github.com/kwoodhouse93/audio-playground/types\"\n)\n\n\nfunc Gain(src source.Source, gain float32) source.Source {\n\treturn func(step int) types.Sample {\n\t\tin := src(step)\n\t\treturn in.Gain(gain)\n\t}\n}\n\n\n\nfunc Sum2(src1, src2 source.Source) source.Source {\n\treturn func(step int) types.Sample {\n\t\ts1 := src1(step)\n\t\ts2 := src2(step)\n\t\treturn s1.Sum(s2)\n\t}\n}\n\n\n\nfunc Sum2Comp(src1, src2 source.Source) source.Source {\n\treturn func(step int) types.Sample {\n\t\ts1 := src1(step)\n\t\ts2 := src2(step)\n\t\treturn s1.Sum(s2).Gain(0.5)\n\t}\n}\n\n\n\nfunc Sum(srcs ...source.Source) source.Source {\n\tout := srcs[0]\n\tfor _, src := range srcs[1:] {\n\t\tout = Sum2(out, src)\n\t}\n\treturn out\n}\n\n\n\n\n\n\nfunc Mixer2(src1, src2 source.Source, gain1, gain2 float32) source.Source {\n\treturn Sum2(\n\t\tGain(src1, gain1),\n\t\tGain(src2, gain2),\n\t)\n}\n\n\ntype SourceGain struct {\n\tSource source.Source\n\tGain float32\n}\n\n\nfunc Mixer(inputs []SourceGain) source.Source {\n\tsources := make([]source.Source, len(inputs))\n\tfor i, input := range inputs {\n\t\tsources[i] = Gain(input.Source, input.Gain)\n\t}\n\treturn Sum(sources...)\n}\n\nfunc SumComp(srcs ...source.Source) source.Source ", "output": "{\n\tcompGain := 1 / (float32(len(srcs)))\n\tout := srcs[0]\n\tfor _, src := range srcs[1:] {\n\t\tout = Sum2(Gain(out, compGain), Gain(src, compGain))\n\t}\n\treturn out\n}"} {"input": "package daemon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/docker/docker/pkg/signal\"\n\t\"github.com/docker/docker/runconfig\"\n)\n\nfunc TestGetFullName(t *testing.T) {\n\tname, err := GetFullContainerName(\"testing\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif name != \"/testing\" {\n\t\tt.Fatalf(\"Expected /testing got %s\", name)\n\t}\n\tif _, err := GetFullContainerName(\"\"); err == nil {\n\t\tt.Fatal(\"Error should not be nil\")\n\t}\n}\n\n\n\nfunc TestContainerStopSignal(t *testing.T) {\n\tc := &Container{\n\t\tCommonContainer: CommonContainer{\n\t\t\tConfig: &runconfig.Config{},\n\t\t},\n\t}\n\n\tdef, err := signal.ParseSignal(signal.DefaultStopSignal)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ts := c.stopSignal()\n\tif s != int(def) {\n\t\tt.Fatalf(\"Expected %v, got %v\", def, s)\n\t}\n\n\tc = &Container{\n\t\tCommonContainer: CommonContainer{\n\t\t\tConfig: &runconfig.Config{StopSignal: \"SIGKILL\"},\n\t\t},\n\t}\n\ts = c.stopSignal()\n\tif s != 9 {\n\t\tt.Fatalf(\"Expected 9, got %v\", s)\n\t}\n}\n\nfunc TestValidContainerNames(t *testing.T) ", "output": "{\n\tinvalidNames := []string{\"-rm\", \"&sdfsfd\", \"safd%sd\"}\n\tvalidNames := []string{\"word-word\", \"word_word\", \"1weoid\"}\n\n\tfor _, name := range invalidNames {\n\t\tif validContainerNamePattern.MatchString(name) {\n\t\t\tt.Fatalf(\"%q is not a valid container name and was returned as valid.\", name)\n\t\t}\n\t}\n\n\tfor _, name := range validNames {\n\t\tif !validContainerNamePattern.MatchString(name) {\n\t\t\tt.Fatalf(\"%q is a valid container name and was returned as invalid.\", name)\n\t\t}\n\t}\n}"} {"input": "package learn\n\nimport (\n\t\"fmt\"\n)\n\ntype List struct {\n\tData interface{}\n\tNextnode *List\n}\n\nfunc myPrint(t interface{}) {\n\tfmt.Println(t)\n}\n\n\nfunc (l *List) ListLength() int {\n\tvar i int = 0\n\tn := l\n\tfor n.Nextnode != nil {\n\t\ti++\n\t\tn = n.Nextnode\n\t}\n\treturn i + 1\n}\n\n\nfunc (l *List) GetEle(i int) (ele interface{}) {\n\tif i < 0 || i > l.ListLength() {\n\t\treturn nil\n\t}\n\tcur := l\n\tj := 1\n\tfor cur.Nextnode != nil {\n\t\tif j == i {\n\t\t\treturn cur.Data\n\t\t}\n\t\tj++\n\t\tcur = cur.Nextnode\n\n\t}\n\tif cur != nil && j == i {\n\t\treturn cur.Data\n\t}\n\treturn nil\n}\n\n\nfunc (l *List) ListInsert(i int, ele interface{}) bool {\n\tvar s List \n\tif i < 0 || i > l.ListLength() {\n\t\treturn false\n\t}\n\ts.Data = ele\n\tp := l\n\tj := 1\n\tfor j < i && p != nil {\n\t\tj++\n\t\tp = p.Nextnode\n\t}\n\tif p != nil && j <= i {\n\t\ts.Nextnode = p.Nextnode\n\t\tp.Nextnode = &s\n\t} else {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\n\n\n\nfunc (l *List) ListAll() (all string) {\n\tp := l\n\tfor p != nil {\n\t\tall += fmt.Sprintf(\"%v+\", p.Data)\n\t\tp = p.Nextnode\n\t}\n\treturn all\n}\n\nfunc (l *List) ListDelete(i int) bool ", "output": "{\n\tp := l\n\tj := 1\n\tfor j < i && p != nil {\n\t\tj++\n\t\tp = p.Nextnode\n\t}\n\tif p == nil || j > i {\n\t\treturn false\n\t}\n\tp.Nextnode = p.Nextnode.Nextnode\n\treturn true\n}"} {"input": "package github\n\nimport (\n\t\"context\"\n\t\"fmt\"\n)\n\n\n\n\n\ntype GitignoresService service\n\n\ntype Gitignore struct {\n\tName *string `json:\"name,omitempty\"`\n\tSource *string `json:\"source,omitempty\"`\n}\n\n\n\n\n\n\nfunc (s *GitignoresService) List(ctx context.Context) ([]string, *Response, error) {\n\treq, err := s.client.NewRequest(\"GET\", \"gitignore/templates\", nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar availableTemplates []string\n\tresp, err := s.client.Do(ctx, req, &availableTemplates)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn availableTemplates, resp, nil\n}\n\n\n\n\nfunc (s *GitignoresService) Get(ctx context.Context, name string) (*Gitignore, *Response, error) {\n\tu := fmt.Sprintf(\"gitignore/templates/%v\", name)\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tgitignore := new(Gitignore)\n\tresp, err := s.client.Do(ctx, req, gitignore)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn gitignore, resp, nil\n}\n\nfunc (g Gitignore) String() string ", "output": "{\n\treturn Stringify(g)\n}"} {"input": "package holochain\n\nimport (\n\t. \"github.com/smartystreets/goconvey/convey\"\n\t\"testing\"\n)\n\n\n\nfunc TestHT(t *testing.T) ", "output": "{\n\tConvey(\"\", t, func() {\n\t})\n}"} {"input": "package data\n\nimport (\n\t\"time\"\n\n\t\"github.com/juju/errgo\"\n)\n\ntype Entries []Entry\n\ntype Entry interface {\n\tType() EntryType\n\tValues() []string\n\tGetTimeStamp() time.Time\n}\n\nconst TimeStampFormat = time.RFC3339Nano\n\ntype EntryType int\n\nconst (\n\tEntryTypeNote EntryType = iota\n\tEntryTypeTodo\n\tEntryTypeUnkown\n)\n\n\n\nfunc ParseEntryType(value string) (EntryType, error) {\n\tswitch value {\n\tcase \"note\":\n\t\treturn EntryTypeNote, nil\n\tcase \"todo\":\n\t\treturn EntryTypeTodo, nil\n\tdefault:\n\t\treturn EntryTypeUnkown, errgo.New(\"the entry type \" + value + \" is not known\")\n\t}\n}\n\nfunc ParseEntry(values []string) (Entry, error) {\n\tif len(values) < 1 {\n\t\treturn nil, errgo.New(\"entry values need at least one field\")\n\t}\n\n\tetype, err := ParseEntryType(values[0])\n\tif err != nil {\n\t\treturn nil, errgo.Notef(err, \"can not parse entry type\")\n\t}\n\n\tswitch etype {\n\tcase EntryTypeNote:\n\t\treturn ParseNote(values)\n\tcase EntryTypeTodo:\n\t\treturn ParseTodo(values)\n\tdefault:\n\t\treturn nil, errgo.New(\"do not know how to parse this entry type\")\n\t}\n}\n\nfunc (etype EntryType) String() string ", "output": "{\n\tswitch etype {\n\tcase EntryTypeNote:\n\t\treturn \"note\"\n\tcase EntryTypeTodo:\n\t\treturn \"todo\"\n\tdefault:\n\t\treturn \"unkown\"\n\t}\n}"} {"input": "package datastore\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hellodudu/Ultimate/iface\"\n\t\"github.com/hellodudu/Ultimate/utils/global\"\n)\n\nvar ds iface.IDatastore\n\nfunc init() {\n\tglobal.Debugging = false\n\tglobal.MysqlUser = \"root\"\n\tglobal.MysqlPwd = \"\"\n\tglobal.MysqlAddr = \"127.0.0.1\"\n\tglobal.MysqlPort = \"3306\"\n\tglobal.MysqlDB = \"db_ultimate\"\n\tglobal.UltimateID = 110\n}\n\n\n\nfunc TestTableGlobal(t *testing.T) {\n\ttbl := ds.TableGlobal()\n\tif tbl == nil {\n\t\tt.Error(\"Init table global error\")\n\t}\n\n\tif tbl.Id != 110 {\n\t\tt.Error(\"Init table global ultimate_id error\")\n\t}\n}\n\nfunc TestNewDatastore(t *testing.T) ", "output": "{\n\n\tvar err error\n\tds, err = NewDatastore()\n\tif err != nil {\n\t\tt.Error(\"NewDatastore error:\", err)\n\t}\n\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"gx/ipfs/QmUWtNQd8JdEiYiDqNYTUcaqyteJZ2rTNQLiw3dauLPccy/gomega/format\"\n)\n\ntype HaveKeyMatcher struct {\n\tKey interface{}\n}\n\n\n\nfunc (matcher *HaveKeyMatcher) FailureMessage(actual interface{}) (message string) {\n\tswitch matcher.Key.(type) {\n\tcase omegaMatcher:\n\t\treturn format.Message(actual, \"to have key matching\", matcher.Key)\n\tdefault:\n\t\treturn format.Message(actual, \"to have key\", matcher.Key)\n\t}\n}\n\nfunc (matcher *HaveKeyMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\tswitch matcher.Key.(type) {\n\tcase omegaMatcher:\n\t\treturn format.Message(actual, \"not to have key matching\", matcher.Key)\n\tdefault:\n\t\treturn format.Message(actual, \"not to have key\", matcher.Key)\n\t}\n}\n\nfunc (matcher *HaveKeyMatcher) Match(actual interface{}) (success bool, err error) ", "output": "{\n\tif !isMap(actual) {\n\t\treturn false, fmt.Errorf(\"HaveKey matcher expects a map. Got:%s\", format.Object(actual, 1))\n\t}\n\n\tkeyMatcher, keyIsMatcher := matcher.Key.(omegaMatcher)\n\tif !keyIsMatcher {\n\t\tkeyMatcher = &EqualMatcher{Expected: matcher.Key}\n\t}\n\n\tkeys := reflect.ValueOf(actual).MapKeys()\n\tfor i := 0; i < len(keys); i++ {\n\t\tsuccess, err := keyMatcher.Match(keys[i].Interface())\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"HaveKey's key matcher failed with:\\n%s%s\", format.Indent, err.Error())\n\t\t}\n\t\tif success {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}"} {"input": "package format\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/types\"\n)\n\ntype podHandler func(*v1.Pod) string\n\n\n\nfunc Pod(pod *v1.Pod) string {\n\treturn PodDesc(pod.Name, pod.Namespace, pod.UID)\n}\n\n\n\nfunc PodDesc(podName, podNamespace string, podUID types.UID) string {\n\treturn fmt.Sprintf(\"%s_%s(%s)\", podName, podNamespace, podUID)\n}\n\n\n\n\n\n\n\nfunc Pods(pods []*v1.Pod) string {\n\treturn aggregatePods(pods, Pod)\n}\n\n\n\nfunc PodsWithDeletiontimestamps(pods []*v1.Pod) string {\n\treturn aggregatePods(pods, PodWithDeletionTimestamp)\n}\n\nfunc aggregatePods(pods []*v1.Pod, handler podHandler) string {\n\tpodStrings := make([]string, 0, len(pods))\n\tfor _, pod := range pods {\n\t\tpodStrings = append(podStrings, handler(pod))\n\t}\n\treturn fmt.Sprintf(strings.Join(podStrings, \", \"))\n}\n\nfunc PodWithDeletionTimestamp(pod *v1.Pod) string ", "output": "{\n\tvar deletionTimestamp string\n\tif pod.DeletionTimestamp != nil {\n\t\tdeletionTimestamp = \":DeletionTimestamp=\" + pod.DeletionTimestamp.UTC().Format(time.RFC3339)\n\t}\n\treturn Pod(pod) + deletionTimestamp\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/client-go/applyconfigurations/meta/v1\"\n)\n\n\n\ntype TopologySpreadConstraintApplyConfiguration struct {\n\tMaxSkew *int32 `json:\"maxSkew,omitempty\"`\n\tTopologyKey *string `json:\"topologyKey,omitempty\"`\n\tWhenUnsatisfiable *v1.UnsatisfiableConstraintAction `json:\"whenUnsatisfiable,omitempty\"`\n\tLabelSelector *metav1.LabelSelectorApplyConfiguration `json:\"labelSelector,omitempty\"`\n}\n\n\n\nfunc TopologySpreadConstraint() *TopologySpreadConstraintApplyConfiguration {\n\treturn &TopologySpreadConstraintApplyConfiguration{}\n}\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithMaxSkew(value int32) *TopologySpreadConstraintApplyConfiguration {\n\tb.MaxSkew = &value\n\treturn b\n}\n\n\n\n\n\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithWhenUnsatisfiable(value v1.UnsatisfiableConstraintAction) *TopologySpreadConstraintApplyConfiguration {\n\tb.WhenUnsatisfiable = &value\n\treturn b\n}\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithLabelSelector(value *metav1.LabelSelectorApplyConfiguration) *TopologySpreadConstraintApplyConfiguration {\n\tb.LabelSelector = value\n\treturn b\n}\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithTopologyKey(value string) *TopologySpreadConstraintApplyConfiguration ", "output": "{\n\tb.TopologyKey = &value\n\treturn b\n}"} {"input": "package UserManager\n\nimport \"testing\"\nimport \"github.com/stretchr/testify/assert\"\n\n\n\n\n\nfunc TestVerifyHash(t *testing.T) {\n\tvar v bool\n\tv = verifyPasswordHash(\"Psw\", \"ABC\", \"25928498b28c3268d911dd78d7ff820e0f14ed32b7ac2d397746f1778038b968d9e6364fd4b3da2e7026bdf574c104779fac9ce9064b6b9ae09ac043f8d131d4\")\n\tif !v {\n\t\tt.Error(\"Expected true , got \", v)\n\t}\n}\n\nfunc TestVerifyUser(t *testing.T) {\n\n\n}\n\nfunc TestGenerateHash(t *testing.T) ", "output": "{\n\thash, salt := generatePasswordHash(\"MeinPasswort\")\n\thash2, salt2 := generatePasswordHash(\"MeinPasswort\")\n\tassert.NotEqual(t, hash, hash2, \"Error, Two Hashes of the same Passwort are identical\")\n\tassert.NotEqual(t, salt, salt2, \"Error, Two Runs of generate hash returned the same Salt\")\n}"} {"input": "package iso20022\n\n\ntype Statement8 struct {\n\n\tReference *Max35Text `xml:\"Ref\"`\n\n\tStatementPeriod *DatePeriodDetails `xml:\"StmtPrd\"`\n\n\tCreationDateTime *DateAndDateTimeChoice `xml:\"CreDtTm,omitempty\"`\n\n\tFrequency *EventFrequency1Code `xml:\"Frqcy,omitempty\"`\n\n\tUpdateType *StatementUpdateTypeCode `xml:\"UpdTp\"`\n\n\tActivityIndicator *YesNoIndicator `xml:\"ActvtyInd\"`\n\n\tReportNumber *Max5NumericText `xml:\"RptNb,omitempty\"`\n}\n\nfunc (s *Statement8) SetReference(value string) {\n\ts.Reference = (*Max35Text)(&value)\n}\n\nfunc (s *Statement8) AddStatementPeriod() *DatePeriodDetails {\n\ts.StatementPeriod = new(DatePeriodDetails)\n\treturn s.StatementPeriod\n}\n\nfunc (s *Statement8) AddCreationDateTime() *DateAndDateTimeChoice {\n\ts.CreationDateTime = new(DateAndDateTimeChoice)\n\treturn s.CreationDateTime\n}\n\nfunc (s *Statement8) SetFrequency(value string) {\n\ts.Frequency = (*EventFrequency1Code)(&value)\n}\n\nfunc (s *Statement8) SetUpdateType(value string) {\n\ts.UpdateType = (*StatementUpdateTypeCode)(&value)\n}\n\n\n\nfunc (s *Statement8) SetReportNumber(value string) {\n\ts.ReportNumber = (*Max5NumericText)(&value)\n}\n\nfunc (s *Statement8) SetActivityIndicator(value string) ", "output": "{\n\ts.ActivityIndicator = (*YesNoIndicator)(&value)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nconst cookieName = \"Site-Cookie1\"\n\nfunc main() {\n\thttp.Handle(\"/favicon.ico\", http.NotFoundHandler())\n\thttp.HandleFunc(\"/\", root)\n\thttp.HandleFunc(\"/set\", set)\n\thttp.HandleFunc(\"/read\", read)\n\thttp.HandleFunc(\"/expire\", expire)\n\tlog.Println(\"Starting server on 8080\")\n\tlog.Fatalln(http.ListenAndServe(\":8080\", nil))\n}\n\n\n\nfunc set(w http.ResponseWriter, _ *http.Request) {\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: cookieName,\n\t\tValue: \"This is a Site Cookie created\",\n\t})\n\tfmt.Fprint(w, `

Read

`)\n}\n\nfunc read(w http.ResponseWriter, r *http.Request) {\n\tcoo, err := r.Cookie(cookieName)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Redirect(w, r, \"/set\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tfmt.Fprintf(w, \"

Cookie Value: %s

\", coo.Value)\n\tfmt.Fprint(w, `

Expire

`)\n}\n\nfunc expire(w http.ResponseWriter, r *http.Request) {\n\tcoo, err := r.Cookie(cookieName)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Redirect(w, r, \"/set\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tcoo.MaxAge = -1 \n\thttp.SetCookie(w, coo)\n\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n}\n\nfunc root(w http.ResponseWriter, _ *http.Request) ", "output": "{\n\tfmt.Fprint(w, `

Set

`)\n}"} {"input": "package client\n\nimport (\n\t\"sync\"\n\n\t\"github.com/valyala/fasthttp\"\n)\n\n\n\n\nfunc New(config Config) *Instance ", "output": "{\n\tclient := &Instance{\n\t\tconf: &config,\n\t\tclients: make(map[string]*fasthttp.HostClient),\n\t\tclientsMu: new(sync.RWMutex),\n\t\tbalancer: newRangeBalancer(),\n\t}\n\n\treturn client\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\n\t\"github.com/uber/jaeger-client-go/thrift-gen/agent\"\n\t\"github.com/uber/jaeger-client-go/thrift-gen/zipkincore\"\n\n\t\"github.com/apache/thrift/lib/go/thrift\"\n)\n\n\nconst UDPPacketMaxLength = 65000\n\n\ntype AgentClientUDP struct {\n\tagent.Agent\n\tio.Closer\n\n\tconnUDP *net.UDPConn\n\tclient *agent.AgentClient\n\tmaxPacketSize int \n\tthriftBuffer *thrift.TMemoryBuffer \n}\n\n\nfunc NewAgentClientUDP(hostPort string, maxPacketSize int) (*AgentClientUDP, error) {\n\tif maxPacketSize == 0 {\n\t\tmaxPacketSize = UDPPacketMaxLength\n\t}\n\n\tthriftBuffer := thrift.NewTMemoryBufferLen(maxPacketSize)\n\tprotocolFactory := thrift.NewTCompactProtocolFactory()\n\tclient := agent.NewAgentClientFactory(thriftBuffer, protocolFactory)\n\n\tdestAddr, err := net.ResolveUDPAddr(\"udp\", hostPort)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconnUDP, err := net.DialUDP(destAddr.Network(), nil, destAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := connUDP.SetWriteBuffer(maxPacketSize); err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientUDP := &AgentClientUDP{\n\t\tconnUDP: connUDP,\n\t\tclient: client,\n\t\tmaxPacketSize: maxPacketSize,\n\t\tthriftBuffer: thriftBuffer}\n\treturn clientUDP, nil\n}\n\n\n\n\n\nfunc (a *AgentClientUDP) Close() error {\n\treturn a.connUDP.Close()\n}\n\nfunc (a *AgentClientUDP) EmitZipkinBatch(spans []*zipkincore.Span) error ", "output": "{\n\ta.thriftBuffer.Reset()\n\ta.client.SeqId = 0 \n\tif err := a.client.EmitZipkinBatch(spans); err != nil {\n\t\treturn err\n\t}\n\tif a.thriftBuffer.Len() > a.maxPacketSize {\n\t\treturn fmt.Errorf(\"Data does not fit within one UDP packet; size %d, max %d, spans %d\",\n\t\t\ta.thriftBuffer.Len(), a.maxPacketSize, len(spans))\n\t}\n\t_, err := a.connUDP.Write(a.thriftBuffer.Bytes())\n\treturn err\n}"} {"input": "package util\n\nimport \"fmt\"\n\n\n\nfunc PanicIfNil(check interface{}, message string) {\n\tif check == nil {\n\t\tpanic(message)\n\t}\n}\n\n\n\n\n\nfunc PanicOnError(err error, message string) ", "output": "{\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"%s: %s\", message, err.Error()))\n\t}\n}"} {"input": "package generator\n\nimport (\n\tkapi \"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/rest\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n\n\tbuildapi \"github.com/openshift/origin/pkg/build/api\"\n\t\"github.com/openshift/origin/pkg/build/generator\"\n\t\"github.com/openshift/origin/pkg/build/registry/clone\"\n)\n\n\n\n\n\n\ntype CloneREST struct {\n\tgenerator *generator.BuildGenerator\n}\n\n\nfunc (s *CloneREST) New() runtime.Object {\n\treturn &buildapi.BuildRequest{}\n}\n\n\nfunc (s *CloneREST) Create(ctx kapi.Context, obj runtime.Object) (runtime.Object, error) {\n\tif err := rest.BeforeCreate(clone.Strategy, ctx, obj); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.generator.Clone(ctx, obj.(*buildapi.BuildRequest))\n}\n\nfunc NewStorage(generator *generator.BuildGenerator) *CloneREST ", "output": "{\n\treturn &CloneREST{generator: generator}\n}"} {"input": "package dnsrecorder\n\nimport (\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n)\n\n\n\n\n\n\n\ntype Recorder struct {\n\tdns.ResponseWriter\n\tRcode int\n\tLen int\n\tMsg *dns.Msg\n\tStart time.Time\n}\n\n\n\n\nfunc New(w dns.ResponseWriter) *Recorder {\n\treturn &Recorder{\n\t\tResponseWriter: w,\n\t\tRcode: 0,\n\t\tMsg: nil,\n\t\tStart: time.Now(),\n\t}\n}\n\n\n\n\n\n\nfunc (r *Recorder) Write(buf []byte) (int, error) {\n\tn, err := r.ResponseWriter.Write(buf)\n\tif err == nil {\n\t\tr.Len += n\n\t}\n\treturn n, err\n}\n\n\n\nfunc (r *Recorder) Hijack() { r.ResponseWriter.Hijack(); return }\n\nfunc (r *Recorder) WriteMsg(res *dns.Msg) error ", "output": "{\n\tr.Rcode = res.Rcode\n\tr.Len += res.Len()\n\tr.Msg = res\n\treturn r.ResponseWriter.WriteMsg(res)\n}"} {"input": "package single\n\nimport (\n\t\"io\"\n\n\t\"github.com/ondrej-smola/mesos-go-http/lib/codec/framing\"\n)\n\ntype Reader struct {\n\tr io.Reader\n}\n\nfunc New(r io.Reader) *Reader {\n\treturn &Reader{r: r}\n}\n\n\n\nfunc NewProvider() framing.Provider {\n\treturn func(r io.Reader) framing.Reader {\n\t\treturn New(r)\n\t}\n}\n\nfunc (rr *Reader) ReadFrame(p []byte) (endOfFrame bool, n int, err error) {\n\tn, err = rr.r.Read(p)\n\n\tif err == io.EOF {\n\t\tendOfFrame = true\n\t}\n\n\treturn\n}\n\n\n\nfunc (rr *Reader) Read(p []byte) (int, error) ", "output": "{\n\treturn rr.r.Read(p)\n}"} {"input": "package gamejam\n\ntype SceneID int\n\ntype Scene interface {\n\tAddComponent(c Component)\n\tLoad(r Resources) (err error)\n\tUnload(r Resources) (err error)\n\tRender()\n\tUpdate(mgr SceneManager)\n\tSetSceneID(id SceneID)\n\tSceneID() SceneID\n}\n\ntype BaseScene struct {\n\tcomponents map[ComponentID]Component\n\tid SceneID\n}\n\n\n\nfunc (s *BaseScene) AddComponent(c Component) {\n\tc.SetScene(s)\n\ts.components[c.GetID()] = c\n}\n\nfunc (s *BaseScene) Load(r Resources) (err error) {\n\treturn\n}\n\nfunc (s *BaseScene) Render() {\n}\n\nfunc (s *BaseScene) SetSceneID(id SceneID) {\n\ts.id = id\n}\n\nfunc (s *BaseScene) SceneID() SceneID {\n\treturn s.id\n}\n\nfunc (s *BaseScene) Unload(r Resources) (err error) {\n\tvar (\n\t\tid ComponentID\n\t\tc Component\n\t)\n\tfor id, c = range s.components {\n\t\ts.components[id] = nil\n\t\tc.Delete()\n\t}\n\treturn\n}\n\nfunc (s *BaseScene) Update(mgr SceneManager) {\n}\n\nfunc NewBaseScene() *BaseScene ", "output": "{\n\treturn &BaseScene{\n\t\tcomponents: map[ComponentID]Component{},\n\t}\n}"} {"input": "package jwk\n\nimport (\n\t\"crypto/rand\"\n\t\"io\"\n\n\t\"github.com/raiqub/jose/converters\"\n)\n\nvar kidGen = DefaultKeyIDGenerator\n\n\n\ntype KeyIDGenerator func() (string, error)\n\n\n\n\n\n\nfunc SetIDGenerator(f KeyIDGenerator) {\n\tkidGen = f\n}\n\nfunc DefaultKeyIDGenerator() (string, error) ", "output": "{\n\tconst keyIDSize = 16\n\tkidBytes := make([]byte, keyIDSize)\n\n\tif _, err := io.ReadFull(rand.Reader, kidBytes); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn converters.Base64.FromBytes(kidBytes), nil\n}"} {"input": "package com\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc TestIsFile(t *testing.T) {\n\tif !IsFile(\"file.go\") {\n\t\tt.Errorf(\"IsExist:\\n Expect => %v\\n Got => %v\\n\", true, false)\n\t}\n\n\tif IsFile(\"testdata\") {\n\t\tt.Errorf(\"IsExist:\\n Expect => %v\\n Got => %v\\n\", false, true)\n\t}\n\n\tif IsFile(\"files.go\") {\n\t\tt.Errorf(\"IsExist:\\n Expect => %v\\n Got => %v\\n\", false, true)\n\t}\n}\n\nfunc TestIsExist(t *testing.T) {\n\tConvey(\"Check if file or directory exists\", t, func() {\n\t\tConvey(\"Pass a file name that exists\", func() {\n\t\t\tSo(IsExist(\"file.go\"), ShouldEqual, true)\n\t\t})\n\t\tConvey(\"Pass a directory name that exists\", func() {\n\t\t\tSo(IsExist(\"testdata\"), ShouldEqual, true)\n\t\t})\n\t\tConvey(\"Pass a directory name that does not exist\", func() {\n\t\t\tSo(IsExist(\".hg\"), ShouldEqual, false)\n\t\t})\n\t})\n}\n\n\nfunc BenchmarkIsFile(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tIsFile(\"file.go\")\n\t}\n}\n\n\n\nfunc BenchmarkIsExist(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tIsExist(\"file.go\")\n\t}\n}"} {"input": "package bno055\n\ntype AxisConfig struct {\n\tX byte\n\tY byte\n\tZ byte\n\tSignX byte\n\tSignY byte\n\tSignZ byte\n}\n\nfunc newAxisConfig(mapConfig, signConfig byte) *AxisConfig {\n\taxisConfig := &AxisConfig{\n\t\tX: mapConfig & 0x03,\n\t\tY: (mapConfig >> 2) & 0x03,\n\t\tZ: (mapConfig >> 4) & 0x03,\n\t\tSignX: (signConfig >> 2) & 0x01,\n\t\tSignY: (signConfig >> 1) & 0x01,\n\t\tSignZ: signConfig & 0x01,\n\t}\n\n\treturn axisConfig\n}\n\nfunc (c *AxisConfig) Mappings() byte {\n\tvar mappings byte\n\n\tmappings |= (c.Z & 0x03) << 4\n\tmappings |= (c.Y & 0x03) << 2\n\tmappings |= c.X & 0x03\n\n\treturn mappings\n}\n\n\n\nfunc (c *AxisConfig) Signs() byte ", "output": "{\n\tvar signs byte\n\n\tsigns |= (c.SignX & 0x01) << 2\n\tsigns |= (c.SignY & 0x01) << 1\n\tsigns |= c.SignZ & 0x01\n\n\treturn signs\n}"} {"input": "package main\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n\nfunc ParseForCommands(line string) string {\n\tswitch line {\n\tcase \":g\":\n\t\tSelectGuild()\n\t\tline = \"\"\n\tcase \":c\":\n\t\tSelectChannel()\n\t\tline = \"\"\n\tdefault:\n\t}\n\n\tif strings.HasPrefix(line, \":m\") {\n\t\tAmountStr := strings.Split(line, \" \")\n\t\tif len(AmountStr) < 2 {\n\t\t\tMsg(ErrorMsg, \"[:m] No Arguments \\n\")\n\t\t\treturn \"\"\n\t\t}\n\n\t\tAmount, err := strconv.Atoi(AmountStr[1])\n\t\tif err != nil {\n\t\t\tMsg(ErrorMsg, \"[:m] Argument Error: %s \\n\", err)\n\t\t\treturn \"\"\n\t\t}\n\n\t\tMsg(InfoMsg, \"Printing last %d messages!\\n\", Amount)\n\t\tState.RetrieveMessages(Amount)\n\t\tPrintMessages(Amount)\n\t\tline = \"\"\n\t}\n\n\treturn line\n}\n\n\n\n\n\nfunc SelectChannel() {\n\tState.Enabled = false\n\tSelectChannelMenu()\n\tState.Enabled = true\n\tShowContent()\n}\n\nfunc SelectGuild() ", "output": "{\n\tState.Enabled = false\n\tSelectGuildMenu()\n\tSelectChannelMenu()\n\tState.Enabled = true\n\tShowContent()\n}"} {"input": "package main\n\nimport(\"fmt\";\"os\";\"regexp\";\"flag\";\"net/http\";\"log\";\"errors\")\n\ntype HTTPDCmd struct {}\n\n\n\nfunc (c *HTTPDCmd) Help() string {\n return `Starts small HTTP daemon that can server files from a specific directory\n\nAvailable subcommands:\n httpd serve Serve on 0.0.0.0:\n`\n}\n\nfunc (c *HTTPDCmd) ValidateArgs(args[]string) error {\n re1 := regexp.MustCompile(\"^[0-9]+$\")\n re2 := regexp.MustCompile(\"^/.+$\")\n if (len(args) == 3 && args[0] == \"serve\" && re1.MatchString(args[1]) && re2.MatchString(args[2])) {\n return nil\n }\n return errors.New(\"Invalid args\")\n}\n\nfunc (c *HTTPDCmd) Run(args[]string, cfg Config) (int, error) {\n if (len(args) == 3 && args[0] == \"serve\") {\n port := flag.String(\"p\", args[1], \"port to serve on\")\n path := flag.String(\"d\", args[2], \"the dir of static file on host\")\n flag.Parse()\n http.Handle(\"/\", http.FileServer(http.Dir(*path)))\n log.Fatal(http.ListenAndServe(\":\"+*port, nil))\n return 1, nil\n }\n fmt.Fprintf(os.Stdout, c.Help())\n return 0, nil\n}\n\nfunc (c *HTTPDCmd) Summary() string ", "output": "{\n return \"Starts small HTTP server\"\n}"} {"input": "package strategy\n\nimport (\n\t\"fmt\"\n\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n\t\"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache\"\n\n\t\"github.com/kubernetes-incubator/cluster-capacity/pkg/framework/store\"\n)\n\ntype Strategy interface {\n\tAdd(obj interface{}) error\n\n\tUpdate(obj interface{}) error\n\n\tDelete(obj interface{}) error\n}\n\ntype predictiveStrategy struct {\n\tresourceStore store.ResourceStore\n\n\tnodeInfo map[string]*schedulercache.NodeInfo\n}\n\nfunc (s *predictiveStrategy) addPod(pod *v1.Pod) error {\n\n\tpod.Status.Phase = v1.PodRunning\n\n\terr := s.resourceStore.Update(\"pods\", metav1.Object(pod))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to add new node: %v\", err)\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc (s *predictiveStrategy) Add(obj interface{}) error {\n\tswitch item := obj.(type) {\n\tcase *v1.Pod:\n\t\treturn s.addPod(item)\n\tdefault:\n\t\treturn fmt.Errorf(\"resource kind not recognized\")\n\t}\n}\n\nfunc (s *predictiveStrategy) Update(obj interface{}) error {\n\treturn fmt.Errorf(\"Not implemented yet\")\n}\n\nfunc (s *predictiveStrategy) Delete(obj interface{}) error {\n\treturn fmt.Errorf(\"Not implemented yet\")\n}\n\n\n\nfunc NewPredictiveStrategy(resourceStore store.ResourceStore) *predictiveStrategy ", "output": "{\n\treturn &predictiveStrategy{\n\t\tresourceStore: resourceStore,\n\t}\n}"} {"input": "package model\n\nimport \"time\"\n\ntype folder struct {\n\tstateTracker\n\tscan folderscan\n\tmodel *Model\n\tstop chan struct{}\n}\n\nfunc (f *folder) IndexUpdated() {\n}\n\nfunc (f *folder) DelayScan(next time.Duration) {\n\tf.scan.Delay(next)\n}\n\nfunc (f *folder) Scan(subdirs []string) error {\n\treturn f.scan.Scan(subdirs)\n}\n\n\nfunc (f *folder) Jobs() ([]string, []string) {\n\treturn nil, nil\n}\n\nfunc (f *folder) BringToFront(string) {}\n\nfunc (f *folder) scanSubdirsIfHealthy(subDirs []string) error {\n\tif err := f.model.CheckFolderHealth(f.folderID); err != nil {\n\t\tl.Infoln(\"Skipping folder\", f.folderID, \"scan due to folder error:\", err)\n\t\treturn err\n\t}\n\tl.Debugln(f, \"Scanning subdirectories\")\n\tif err := f.model.internalScanFolderSubdirs(f.folderID, subDirs); err != nil {\n\t\tf.setError(err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (f *folder) Stop() ", "output": "{\n\tclose(f.stop)\n}"} {"input": "package proxy\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype rttGenerator struct {\n\tmin time.Duration\n\tmax time.Duration\n}\n\n\n\nfunc (s *rttGenerator) getRTT() time.Duration {\n\tif s.min == s.max {\n\t\treturn s.min\n\t}\n\n\tminns := s.min.Nanoseconds()\n\tmaxns := s.max.Nanoseconds()\n\trttns := rand.Int63n(maxns-minns) + minns\n\n\treturn time.Duration(rttns) * time.Nanosecond\n}\n\nfunc newRttGenerator(min, max time.Duration) rttGenerator ", "output": "{\n\trand.Seed(time.Now().UnixNano())\n\treturn rttGenerator{\n\t\tmin: min,\n\t\tmax: max,\n\t}\n}"} {"input": "package eauth\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha1\"\n)\n\n\n\n\n\n\n\nfunc SaltedHMAC(salt, secret, data []byte) []byte ", "output": "{\n\th := sha1.New()\n\th.Write(salt)\n\th.Write(secret)\n\tkey := h.Sum(nil)\n\n\thmacd := hmac.New(sha1.New, key)\n\thmacd.Write(data)\n\treturn hmacd.Sum(nil)\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc helloWorld(w http.ResponseWriter, req *http.Request) {\n\tpath := req.URL.Path\n\tname := strings.Title(strings.TrimPrefix(path, \"/hello/\"))\n\tif len(name) < 1 {\n\t\thttp.Error(w, \"Not Found\", http.StatusNotFound)\n\t\treturn\n\t}\n\tio.WriteString(w, \"Hello, \"+name+\"!\\n\")\n}\n\n\n\nfunc main() {\n\tport := \"1234\"\n\thttp.HandleFunc(\"/\", root)\n\tlog.Fatal(http.ListenAndServe(\":\"+port, nil))\n}\n\nfunc root(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tpath := req.URL.Path\n\tswitch {\n\tcase strings.HasPrefix(path, \"/hello/\"):\n\t\thelloWorld(w, req)\n\tdefault:\n\t\thttp.Error(w, \"Not Found\", http.StatusNotFound)\n\t}\n}"} {"input": "package godspeed\n\nimport (\n\t\"github.com/mefellows/godspeed/log\"\n\t\"github.com/mefellows/plugo/plugo\"\n)\n\ntype GodspeedConfig struct {\n\tRawConfig *plugo.RawConfig\n\tConfigFile string\n}\ntype PluginConfig struct {\n\tName string\n\tDescription string\n\tLogLevel int `default:\"2\" required:\"true\" mapstructure:\"loglevel\"`\n\tDeployment []plugo.PluginConfig `mapstructure:\"deployment\"`\n}\n\ntype Godspeed struct {\n\tconfig *GodspeedConfig\n\tDeploymentStrategies []DeploymentStrategy\n}\n\nfunc New(config *GodspeedConfig) *Godspeed {\n\treturn &Godspeed{config: config}\n}\n\nfunc NewWithDefaultGodspeedConfig() *Godspeed {\n\tc := &GodspeedConfig{}\n\treturn &Godspeed{config: c}\n}\n\nfunc (g *Godspeed) Setup() {\n\tg.LoadPlugins()\n\n\tfor _, p := range g.DeploymentStrategies {\n\t\tp.Setup()\n\t}\n}\n\nfunc (g *Godspeed) Shutdown() {\n\tfor _, p := range g.DeploymentStrategies {\n\t\tp.Teardown()\n\t}\n}\n\n\n\nfunc (g *Godspeed) LoadPlugins() ", "output": "{\n\tvar err error\n\tvar confLoader *plugo.ConfigLoader\n\tc := &PluginConfig{}\n\tif g.config.ConfigFile != \"\" {\n\t\tconfLoader = &plugo.ConfigLoader{}\n\t\terr = confLoader.LoadFromFile(g.config.ConfigFile, &c)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Unable to read configuration file: %s\", err.Error())\n\t\t}\n\t} else {\n\t\tlog.Fatal(\"No config file provided\")\n\t}\n\n\tlog.SetLevel(log.LogLevel(c.LogLevel))\n\n\tg.DeploymentStrategies = make([]DeploymentStrategy, len(c.Deployment))\n\tplugins := plugo.LoadPluginsWithConfig(confLoader, c.Deployment)\n\tfor i, p := range plugins {\n\t\tlog.Debug(\"Loading plugin\\t\" + log.Colorize(log.YELLOW, c.Deployment[i].Name))\n\t\tg.DeploymentStrategies[i] = p.(DeploymentStrategy)\n\t}\n}"} {"input": "package packages\n\nimport (\n\t\"fmt\"\n\t\"github.com/alexandrecarlton/gogurt\"\n)\n\ntype PkgConfig struct{}\n\nfunc (pkgconfig PkgConfig) Name() string {\n\treturn \"pkg-config\"\n}\n\nfunc (pkgconfig PkgConfig) URL(version string) string {\n\treturn fmt.Sprintf(\"https://pkgconfig.freedesktop.org/releases/pkg-config-%s.tar.gz\", version)\n}\n\n\n\nfunc (pkgconfig PkgConfig) Install(config gogurt.Config) error {\n\tmakeInstall := gogurt.MakeCmd{\n\t\tArgs: []string{\n\t\t\t\"install\",\n\t\t},\n\t}.Cmd()\n\treturn makeInstall.Run()\n}\n\nfunc (pkgconfig PkgConfig) Dependencies() []gogurt.Package {\n\treturn []gogurt.Package{}\n}\n\nfunc (pkgconfig PkgConfig) Build(config gogurt.Config) error ", "output": "{\n\tconfigure := gogurt.ConfigureCmd{\n\t\tPrefix: config.InstallDir(pkgconfig),\n\t\tArgs: []string{\n\t\t\t\"--disable-shared\",\n\t\t\t\"--enable-static\",\n\t\t\t\"--with-internal-glib\",\n\t\t},\n\t}.Cmd()\n\tif err := configure.Run(); err != nil {\n\t\treturn err\n\t}\n\tmake := gogurt.MakeCmd{\n\t\tJobs: config.NumCores,\n\t}.Cmd()\n\treturn make.Run()\n}"} {"input": "package jpsplus\n\nimport (\n\t\"container/heap\"\n)\n\ntype PriorityQueue struct {\n\tpos int\n\tnode map[int]*Node\n}\n\nfunc newPriorityQueue() *PriorityQueue {\n\tp := new(PriorityQueue)\n\tp.node = make(map[int]*Node)\n\treturn p\n}\n\n\n\nfunc (p *PriorityQueue) Less(i, j int) bool {\n\treturn p.node[i].finalCost < p.node[j].finalCost\n}\n\nfunc (p *PriorityQueue) Swap(i, j int) {\n\tp.node[i], p.node[j] = p.node[j], p.node[i]\n\tp.node[i].heapIndex = i\n\tp.node[j].heapIndex = j\n}\n\nfunc (p *PriorityQueue) Push(x interface{}) {\n\titem, ok := x.(*Node)\n\tif ok {\n\t\titem.heapIndex = p.pos\n\t\tp.node[p.pos] = item\n\t\tp.pos++\n\t}\n}\n\nfunc (p *PriorityQueue) Pop() interface{} {\n\tp.pos--\n\titem := p.node[p.pos]\n\tdelete(p.node, p.pos)\n\treturn item\n}\n\nfunc (p *PriorityQueue) PushNode(n *Node) {\n\theap.Push(p, n)\n}\n\nfunc (p *PriorityQueue) PopNode() *Node {\n\treturn heap.Pop(p).(*Node)\n}\n\nfunc (p *PriorityQueue) RemoveNode(n *Node) {\n\theap.Remove(p, n.heapIndex)\n}\n\nfunc (p *PriorityQueue) Len() int ", "output": "{\n\treturn len(p.node)\n}"} {"input": "package query\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/EverythingMe/meduza/errors\"\n)\n\n\n\ntype Query interface {\n\tValidate() error\n}\n\ntype Ordering struct {\n\tBy string `bson:\"by\"`\n\tAscending bool `bson:\"asc\"`\n}\n\nvar NoOrder = Ordering{Ascending: true}\n\n\nfunc (o Ordering) IsNil() bool {\n\treturn len(o.By) == 0\n}\n\nfunc (o Ordering) Validate() error {\n\treturn nil\n}\n\ntype Paging struct {\n\tOffset int `bson:\"offset\"`\n\tLimit int `bson:\"limit\"`\n}\n\n\n\n\nvar DefaultPagingLimit = 100\n\ntype Response struct {\n\tTime time.Duration `bson:\"time\"`\n\tstartTime time.Time\n\tError *errors.Error `bson:\"error\"`\n}\n\ntype QueryResult interface {\n\tElapsed() time.Duration\n\tErr() error\n}\n\nfunc NewResponse(err error) *Response {\n\n\treturn &Response{\n\t\tstartTime: time.Now(),\n\t\tError: errors.Wrap(err),\n\t}\n}\n\nfunc (r *Response) Elapsed() time.Duration {\n\treturn r.Time\n}\n\nfunc (r *Response) Err() error {\n\tif r.Error == nil {\n\t\treturn nil\n\t}\n\treturn r.Error\n}\n\nfunc (r *Response) Done() {\n\tr.Time = time.Since(r.startTime)\n}\n\nfunc (r *Response) String() string {\n\treturn fmt.Sprintf(\"Response: {Time: %v, Error: %v}\", r.Time, r.Error)\n}\n\ntype PingQuery struct{}\n\nfunc (PingQuery) Validate() error {\n\treturn nil\n}\n\ntype PingResponse struct {\n\t*Response\n}\n\nfunc NewPingResponse() PingResponse {\n\treturn PingResponse{\n\t\tNewResponse(nil),\n\t}\n}\n\nfunc (p Paging) Validate() error ", "output": "{\n\n\tswitch {\n\tcase p.Offset < 0:\n\t\tfallthrough\n\tcase p.Limit == 0:\n\t\tfallthrough\n\tcase p.Limit < -1:\n\t\treturn errors.NewError(\"Invalid paging parameters: offset: %d, limit: %d\", p.Offset, p.Limit)\n\tdefault:\n\t\treturn nil\n\t}\n\n}"} {"input": "package iso20022\n\n\ntype AcquirerProtocolParameters5 struct {\n\n\tFinancialCapture *FinancialCapture1Code `xml:\"FinCaptr\"`\n\n\tBatchTransfer *ExchangeConfiguration4 `xml:\"BtchTrf,omitempty\"`\n\n\tCompletionExchange *ExchangeConfiguration5 `xml:\"CmpltnXchg,omitempty\"`\n\n\tCancellationExchange *CancellationProcess1Code `xml:\"CxlXchg,omitempty\"`\n}\n\n\n\nfunc (a *AcquirerProtocolParameters5) AddBatchTransfer() *ExchangeConfiguration4 {\n\ta.BatchTransfer = new(ExchangeConfiguration4)\n\treturn a.BatchTransfer\n}\n\nfunc (a *AcquirerProtocolParameters5) AddCompletionExchange() *ExchangeConfiguration5 {\n\ta.CompletionExchange = new(ExchangeConfiguration5)\n\treturn a.CompletionExchange\n}\n\nfunc (a *AcquirerProtocolParameters5) SetCancellationExchange(value string) {\n\ta.CancellationExchange = (*CancellationProcess1Code)(&value)\n}\n\nfunc (a *AcquirerProtocolParameters5) SetFinancialCapture(value string) ", "output": "{\n\ta.FinancialCapture = (*FinancialCapture1Code)(&value)\n}"} {"input": "package jd\n\ntype PathElement interface{}\ntype Path []PathElement\n\n\n\nfunc (p1 Path) clone() Path ", "output": "{\n\tp2 := make(Path, len(p1), len(p1)+1)\n\tcopy(p2, p1)\n\treturn p2\n}"} {"input": "package engine\n\nimport (\n\tvtrpcpb \"vitess.io/vitess/go/vt/proto/vtrpc\"\n\t\"vitess.io/vitess/go/vt/vterrors\"\n\n\t\"vitess.io/vitess/go/sqltypes\"\n\t\"vitess.io/vitess/go/vt/proto/query\"\n)\n\nvar _ Primitive = (*UpdateTarget)(nil)\n\n\ntype UpdateTarget struct {\n\tTarget string\n\n\tnoInputs\n\n\tnoTxNeeded\n}\n\nfunc (updTarget *UpdateTarget) description() PrimitiveDescription {\n\treturn PrimitiveDescription{\n\t\tOperatorType: \"UpdateTarget\",\n\t\tOther: map[string]interface{}{\"target\": updTarget.Target},\n\t}\n}\n\n\n\n\n\nfunc (updTarget *UpdateTarget) GetKeyspaceName() string {\n\treturn updTarget.Target\n}\n\n\nfunc (updTarget *UpdateTarget) GetTableName() string {\n\treturn \"\"\n}\n\n\nfunc (updTarget *UpdateTarget) TryExecute(vcursor VCursor, bindVars map[string]*query.BindVariable, wantfields bool) (*sqltypes.Result, error) {\n\terr := vcursor.Session().SetTarget(updTarget.Target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &sqltypes.Result{}, nil\n}\n\n\nfunc (updTarget *UpdateTarget) TryStreamExecute(vcursor VCursor, bindVars map[string]*query.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error {\n\tresult, err := updTarget.TryExecute(vcursor, bindVars, wantfields)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn callback(result)\n}\n\n\nfunc (updTarget *UpdateTarget) GetFields(vcursor VCursor, bindVars map[string]*query.BindVariable) (*sqltypes.Result, error) {\n\treturn nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, \"[BUG] GetFields not reachable for use statement\")\n}\n\nfunc (updTarget *UpdateTarget) RouteType() string ", "output": "{\n\treturn \"UpdateTarget\"\n}"} {"input": "package storage\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\tgenericregistry \"k8s.io/apiserver/pkg/registry/generic/registry\"\n\t\"k8s.io/apiserver/pkg/registry/rest\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/registry/cachesize\"\n\t\"k8s.io/kubernetes/pkg/registry/core/configmap\"\n)\n\n\ntype REST struct {\n\t*genericregistry.Store\n}\n\n\n\n\n\nvar _ rest.ShortNamesProvider = &REST{}\n\n\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"cm\"}\n}\n\nfunc NewREST(optsGetter generic.RESTOptionsGetter) *REST ", "output": "{\n\tstore := &genericregistry.Store{\n\t\tCopier: api.Scheme,\n\t\tNewFunc: func() runtime.Object { return &api.ConfigMap{} },\n\t\tNewListFunc: func() runtime.Object { return &api.ConfigMapList{} },\n\t\tPredicateFunc: configmap.MatchConfigMap,\n\t\tQualifiedResource: api.Resource(\"configmaps\"),\n\t\tWatchCacheSize: cachesize.GetWatchCacheSizeByResource(\"configmaps\"),\n\n\t\tCreateStrategy: configmap.Strategy,\n\t\tUpdateStrategy: configmap.Strategy,\n\t\tDeleteStrategy: configmap.Strategy,\n\t}\n\toptions := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: configmap.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\tpanic(err) \n\t}\n\treturn &REST{store}\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ChangeDatabaseSoftwareImageCompartmentRequest struct {\n\n\tChangeCompartmentDetails `contributesTo:\"body\"`\n\n\tDatabaseSoftwareImageId *string `mandatory:\"true\" contributesTo:\"path\" name:\"databaseSoftwareImageId\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ChangeDatabaseSoftwareImageCompartmentResponse struct {\n\n\tRawResponse *http.Response\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ChangeDatabaseSoftwareImageCompartmentResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response ChangeDatabaseSoftwareImageCompartmentResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package base\n\nimport (\n\t\"io\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\ntype UserMeta struct {\n}\n\ntype User struct {\n\tName string `json:\"name\"`\n\tUsername string `json:\"username\"`\n\tPassword string `json:\"password\"`\n}\n\ntype UserHandler struct {\n}\n\nfunc (h *UserHandler) GetStruct() (NodeData, NodeMeta) {\n\treturn &User{}, &UserMeta{}\n}\n\nfunc (h *UserHandler) PreInsert(node *Node, m NodeManager) error {\n\treturn nil\n}\n\nfunc (h *UserHandler) PreUpdate(node *Node, m NodeManager) error {\n\treturn nil\n}\n\nfunc (h *UserHandler) PostInsert(node *Node, m NodeManager) error {\n\treturn nil\n}\n\nfunc (h *UserHandler) PostUpdate(node *Node, m NodeManager) error {\n\treturn nil\n}\n\nfunc (h *UserHandler) Validate(node *Node, m NodeManager, errors Errors) {\n\n\tdata := node.Data.(*User)\n\n\tif data.Username == \"\" {\n\t\terrors.AddError(\"data.username\", \"Username cannot be empty\")\n\t}\n\n\tif data.Name == \"\" {\n\t\terrors.AddError(\"data.name\", \"Name cannot be empty\")\n\t}\n\n\tif data.Password == \"\" {\n\t\terrors.AddError(\"data.password\", \"Password cannot be empty\")\n\t}\n}\n\nfunc (h *UserHandler) GetDownloadData(node *Node) *DownloadData {\n\treturn GetDownloadData()\n}\n\nfunc (h *UserHandler) Load(data []byte, meta []byte, node *Node) error {\n\treturn HandlerLoad(h, data, meta, node)\n}\n\nfunc (h *UserHandler) StoreStream(node *Node, r io.Reader) (int64, error) {\n\treturn DefaultHandlerStoreStream(node, r)\n}\n\nfunc Test_Manager_Validate(t *testing.T) ", "output": "{\n\tc := HandlerCollection{\n\t\t\"node.user\": &UserHandler{},\n\t}\n\n\tm := &PgNodeManager{\n\t\tHandlers: c,\n\t}\n\n\tn := c.NewNode(\"node.user\")\n\n\tok, errors := m.Validate(n)\n\n\tassert.False(t, ok)\n\tassert.True(t, errors.HasErrors())\n}"} {"input": "package observer\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/corestoreio/errors\"\n\t\"github.com/corestoreio/pkg/config\"\n\t\"github.com/corestoreio/pkg/net/csgrpc\"\n\t\"github.com/gogo/protobuf/types\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/codes\"\n)\n\ntype registrar struct {\n\tor config.ObserverRegisterer\n}\n\n\n\nfunc NewProtoServiceServer(or config.ObserverRegisterer) ProtoServiceServer {\n\treturn registrar{\n\t\tor: or,\n\t}\n}\n\nfunc (r registrar) Register(ctx context.Context, vs *Configurations) (*types.Empty, error) {\n\tif err := vs.Validate(); err != nil {\n\t\treturn nil, csgrpc.NewStatusBadRequestError(codes.InvalidArgument, \"[config/validation/proto]\",\n\t\t\t\"Configurations.Validate\",\n\t\t\terr.Error(),\n\t\t)\n\t}\n\n\tfor idx, v := range vs.Collection {\n\t\tevent, route, o, err := v.MakeObserver()\n\t\tif err != nil {\n\t\t\treturn nil, csgrpc.NewStatusBadRequestError(codes.InvalidArgument, \"[config/validation/proto]\",\n\t\t\t\tfmt.Sprintf(\"validator_%d\", idx),\n\t\t\t\terr.Error(),\n\t\t\t)\n\t\t}\n\t\tif err := r.or.RegisterObserver(event, route, o); err != nil {\n\t\t\treturn nil, csgrpc.NewStatusBadRequestError(codes.Internal, \"[config/validation/proto]\",\n\t\t\t\tfmt.Sprintf(\"validator_%d\", idx),\n\t\t\t\terr.Error(),\n\t\t\t\t\"event\",\n\t\t\t\tfmt.Sprintf(\"%d\", event),\n\t\t\t\t\"route\",\n\t\t\t\troute,\n\t\t\t)\n\t\t}\n\t}\n\n\treturn &types.Empty{}, nil\n}\n\n\n\nfunc (r registrar) Deregister(ctx context.Context, vs *Configurations) (*types.Empty, error) ", "output": "{\n\tfor _, v := range vs.Collection {\n\t\tevent, route, err := v.MakeEventRoute()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"[config/observer] Data: %#v\", v)\n\t\t}\n\t\tif err := r.or.DeregisterObserver(event, route); err != nil {\n\t\t\treturn nil, errors.WithStack(err)\n\t\t}\n\t}\n\n\treturn &types.Empty{}, nil\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/af83/edwig/core\"\n\t\"github.com/af83/edwig/logger\"\n\t\"github.com/af83/edwig/siri\"\n)\n\ntype SIRIStopDiscoveryRequestHandler struct {\n\txmlRequest *siri.XMLStopPointsDiscoveryRequest\n}\n\nfunc (handler *SIRIStopDiscoveryRequestHandler) RequestorRef() string {\n\treturn handler.xmlRequest.RequestorRef()\n}\n\nfunc (handler *SIRIStopDiscoveryRequestHandler) ConnectorType() string {\n\treturn core.SIRI_STOP_POINTS_DISCOVERY_REQUEST_BROADCASTER\n}\n\n\n\nfunc (handler *SIRIStopDiscoveryRequestHandler) Respond(connector core.Connector, rw http.ResponseWriter) ", "output": "{\n\tlogger.Log.Debugf(\"StopDiscovery %s\\n\", handler.xmlRequest.MessageIdentifier())\n\n\ttmp := connector.(*core.SIRIStopPointsDiscoveryRequestBroadcaster)\n\tresponse, _ := tmp.StopAreas(handler.xmlRequest)\n\txmlResponse, err := response.BuildXML()\n\tif err != nil {\n\t\tsiriError(\"InternalServiceError\", fmt.Sprintf(\"Internal Error: %v\", err), rw)\n\t\treturn\n\t}\n\n\tsoapEnvelope := siri.NewSOAPEnvelopeBuffer()\n\tsoapEnvelope.WriteXML(xmlResponse)\n\n\t_, err = soapEnvelope.WriteTo(rw)\n\tif err != nil {\n\t\tsiriError(\"InternalServiceError\", fmt.Sprintf(\"Internal Error: %v\", err), rw)\n\t\treturn\n\t}\n}"} {"input": "package demopgx\n\nimport (\n\t\"math/big\"\n)\n\n\n\n\n\n\n\ntype User struct {\n\tUid int64 `sql:\"pk: true, auto: true\"`\n\tName string `sql:\"unique: user_login\"`\n\tEmailAddress string `sql:\"nk: true\"`\n\tAddressId *int64 `sql:\"fk: addresses.id, onupdate: restrict, ondelete: restrict\"`\n\tAvatar *string\n\tRole *Role `sql:\"type: text, size: 20\"`\n\tActive bool\n\tAdmin bool\n\tFave *big.Int `sql:\"encode: json\"`\n\tLastUpdated int64\n\n\tNumbers Numbers\n\n\ttoken string\n\tsecret string\n\n\thash string `sql:\"-\"`\n}\n\ntype Numbers struct {\n\tI8 int8 `sql:\"default: -8\"`\n\tU8 uint8 `sql:\"default: 8\"`\n\tI16 int16 `sql:\"default: -16\"`\n\tU16 uint16 `sql:\"default: 16\"`\n\tI32 int32 `sql:\"default: -32\"`\n\tU32 uint32 `sql:\"default: 32\"`\n\tI64 int64 `sql:\"default: -64\"`\n\tU64 uint64 `sql:\"default: 64\"`\n\tF32 float32 `sql:\"default: 3.2\"`\n\tF64 float64 `sql:\"default: 6.4\"`\n}\n\n\n\n\nfunc (u *User) PreUpdate() error {\n\tu.hash = \"PreUpdate\"\n\treturn nil\n}\n\nfunc (u *User) PostGet() error {\n\tu.hash = \"PostGet\"\n\treturn nil\n}\n\nfunc (u *User) PreInsert() error ", "output": "{\n\tu.hash = \"PreInsert\"\n\treturn nil\n}"} {"input": "package raft\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\nfunc diffu(a, b string) string {\n\tif a == b {\n\t\treturn \"\"\n\t}\n\taname, bname := mustTemp(\"base\", a), mustTemp(\"other\", b)\n\tdefer os.Remove(aname)\n\tdefer os.Remove(bname)\n\tcmd := exec.Command(\"diff\", \"-u\", aname, bname)\n\tbuf, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tif _, ok := err.(*exec.ExitError); ok {\n\t\t\treturn string(buf)\n\t\t}\n\t\tpanic(err)\n\t}\n\treturn string(buf)\n}\n\n\n\nfunc ltoa(l *raftLog) string {\n\ts := fmt.Sprintf(\"committed: %d\\n\", l.committed)\n\ts += fmt.Sprintf(\"applied: %d\\n\", l.applied)\n\tfor i, e := range l.allEntries() {\n\t\ts += fmt.Sprintf(\"#%d: %+v\\n\", i, e)\n\t}\n\treturn s\n}\n\nfunc mustTemp(pre, body string) string ", "output": "{\n\tf, err := os.CreateTemp(\"\", pre)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, err = io.Copy(f, strings.NewReader(body))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tf.Close()\n\treturn f.Name()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\trest \"github.com/Kissaki/rest2go\"\n\t\"log\"\n\t\"net/http\"\n)\n\nvar wdmap = map[string]string{\n\t\"Mo\": \"Monday\",\n\t\"Tu\": \"Tuesday\",\n\t\"We\": \"Wednesday\",\n\t\"Th\": \"Thursday\",\n\t\"Fr\": \"Friday\",\n\t\"Sa\": \"Saturday\",\n\t\"Su\": \"Sunday\",\n}\n\ntype Weekdays struct {\n\twd map[string]string\n}\n\n\nfunc (wd *Weekdays) Find(resp http.ResponseWriter, id string) {\n\tif full, ok := wd.wd[id]; ok {\n\t\tfmt.Fprintf(resp, full)\n\t}\n}\n\nfunc main() {\n\tlog.Println(\"Starting Server\")\n\taddress := \"127.0.0.1:3000\"\n\n\tvar wd = new(Weekdays)\n\twd.wd = wdmap\n\trest.Resource(\"/wd/\", wd)\n\n\tif err := http.ListenAndServe(address, nil); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc (wd *Weekdays) Index(resp http.ResponseWriter) ", "output": "{\n\tfor i, v := range wd.wd {\n\t\tfmt.Fprintf(resp, \"%s: %s
\\n\", i, v)\n\t}\n}"} {"input": "package upgrades\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\n\t\"launchpad.net/juju-core/utils/exec\"\n)\n\nvar ubuntuHome = \"/home/ubuntu\"\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ensureLockDirExistsAndUbuntuWritable(context Context) error ", "output": "{\n\tlockDir := path.Join(context.AgentConfig().DataDir(), \"locks\")\n\tcommand := fmt.Sprintf(\"\"+\n\t\t\"mkdir -p %s\\n\"+\n\t\t\"[ -e %s ] && chown ubuntu:ubuntu %s\\n\",\n\t\tlockDir, ubuntuHome, lockDir)\n\tlogger.Tracef(\"command: %s\", command)\n\tresult, err := exec.RunCommands(exec.RunParams{\n\t\tCommands: command,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.Tracef(\"stdout: %s\", result.Stdout)\n\treturn nil\n}"} {"input": "package header_test\n\nimport (\n\t\"testing\"\n\n\t\"gvisor.dev/gvisor/pkg/tcpip/header\"\n)\n\n\n\nfunc TestIPv6(t *testing.T) {\n\tb := header.IPv6(make([]byte, header.IPv6MinimumSize))\n\tb.Encode(&header.IPv6Fields{})\n\n\tconst want = header.IPv6Version\n\tif v := header.IPVersion(b); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}\n\nfunc TestOtherVersion(t *testing.T) {\n\tconst want = header.IPv4Version + header.IPv6Version\n\tb := make([]byte, 1)\n\tb[0] = want << 4\n\n\tif v := header.IPVersion(b); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}\n\nfunc TestTooShort(t *testing.T) {\n\tb := make([]byte, 1)\n\tb[0] = (header.IPv4Version + header.IPv6Version) << 4\n\n\tconst want = -1\n\tif v := header.IPVersion(b[:0]); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n\n\tif v := header.IPVersion(nil); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}\n\nfunc TestIPv4(t *testing.T) ", "output": "{\n\tb := header.IPv4(make([]byte, header.IPv4MinimumSize))\n\tb.Encode(&header.IPv4Fields{})\n\n\tconst want = header.IPv4Version\n\tif v := header.IPVersion(b); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}"} {"input": "package backoff\n\nimport (\n\t\"math\"\n\t\"time\"\n\n\t\"github.com/quan-xie/tuba/util/xtime\"\n)\n\n\ntype Backoff interface {\n\tNext(retry int) time.Duration\n}\n\ntype constantBackoff struct {\n\tbackoffInterval xtime.Duration\n}\n\n\nfunc NewConstantBackoff(backoffInterval xtime.Duration) Backoff {\n\treturn &constantBackoff{backoffInterval: backoffInterval}\n}\n\n\nfunc (cb *constantBackoff) Next(retry int) time.Duration {\n\tif retry <= 0 {\n\t\treturn 0 * time.Millisecond\n\t}\n\n\treturn time.Duration(cb.backoffInterval) * 1 << uint(retry)\n}\n\ntype exponentialBackoff struct {\n\texponentFactor float64\n\tinitialTimeout float64\n\tmaxTimeout float64\n}\n\n\nfunc NewExponentialBackoff(initialTimeout, maxTimeout time.Duration, exponentFactor float64) Backoff {\n\treturn &exponentialBackoff{\n\t\texponentFactor: exponentFactor,\n\t\tinitialTimeout: float64(initialTimeout / time.Millisecond),\n\t\tmaxTimeout: float64(maxTimeout / time.Millisecond),\n\t}\n}\n\n\n\n\nfunc (eb *exponentialBackoff) Next(retry int) time.Duration ", "output": "{\n\tif retry <= 0 {\n\t\treturn 0 * time.Millisecond\n\t}\n\n\treturn time.Duration(math.Min(eb.initialTimeout+math.Pow(eb.exponentFactor, float64(retry)), eb.maxTimeout)) * time.Millisecond\n}"} {"input": "package core\n\nimport (\n\t\"syscall\"\n\t\"time\"\n\t\"unicode/utf16\"\n\t\"unsafe\"\n\n\t\"github.com/tinycedar/lily/common\"\n)\n\nfunc GetProcessNameMap() map[uint32]string {\n\tdefer metrics(\"GetProcessNameMap\")(time.Now())\n\tsnapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)\n\tif err != nil {\n\t\tcommon.Error(\"Fail to syscall CreateToolhelp32Snapshot: %v\", err)\n\t\treturn nil\n\t}\n\tdefer syscall.CloseHandle(snapshot)\n\tvar procEntry syscall.ProcessEntry32\n\tprocEntry.Size = uint32(unsafe.Sizeof(procEntry))\n\tif err = syscall.Process32First(snapshot, &procEntry); err != nil {\n\t\tcommon.Error(\"Fail to syscall Process32First: %v\", err)\n\t\treturn nil\n\t}\n\tprocessNameMap := make(map[uint32]string)\n\tfor {\n\t\tprocessNameMap[procEntry.ProcessID] = parseProcessName(procEntry.ExeFile)\n\t\tif err = syscall.Process32Next(snapshot, &procEntry); err != nil {\n\t\t\tif err == syscall.ERROR_NO_MORE_FILES {\n\t\t\t\treturn processNameMap\n\t\t\t}\n\t\t\tcommon.Error(\"Fail to syscall Process32Next: %v\", err)\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\nfunc parseProcessName(exeFile [syscall.MAX_PATH]uint16) string {\n\tfor i, v := range exeFile {\n\t\tif v <= 0 {\n\t\t\treturn string(utf16.Decode(exeFile[:i]))\n\t\t}\n\t}\n\treturn \"\"\n}\n\n\n\nfunc metrics(funcName string) func(now time.Time) ", "output": "{\n\treturn func(now time.Time) {\n\t\tcommon.Info(\"Processing [%v] costs %v\", funcName, time.Since(now))\n\t}\n}"} {"input": "package elastic\n\n\n\n\n\n\n\n\n\ntype MissingAggregation struct {\n\tfield string\n\tsubAggregations map[string]Aggregation\n\tmeta map[string]interface{}\n}\n\n\n\nfunc (a *MissingAggregation) Field(field string) *MissingAggregation {\n\ta.field = field\n\treturn a\n}\n\nfunc (a *MissingAggregation) SubAggregation(name string, subAggregation Aggregation) *MissingAggregation {\n\ta.subAggregations[name] = subAggregation\n\treturn a\n}\n\n\nfunc (a *MissingAggregation) Meta(metaData map[string]interface{}) *MissingAggregation {\n\ta.meta = metaData\n\treturn a\n}\n\nfunc (a *MissingAggregation) Source() (interface{}, error) {\n\n\tsource := make(map[string]interface{})\n\topts := make(map[string]interface{})\n\tsource[\"missing\"] = opts\n\n\tif a.field != \"\" {\n\t\topts[\"field\"] = a.field\n\t}\n\n\tif len(a.subAggregations) > 0 {\n\t\taggsMap := make(map[string]interface{})\n\t\tsource[\"aggregations\"] = aggsMap\n\t\tfor name, aggregate := range a.subAggregations {\n\t\t\tsrc, err := aggregate.Source()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\taggsMap[name] = src\n\t\t}\n\t}\n\n\tif len(a.meta) > 0 {\n\t\tsource[\"meta\"] = a.meta\n\t}\n\n\treturn source, nil\n}\n\nfunc NewMissingAggregation() *MissingAggregation ", "output": "{\n\treturn &MissingAggregation{\n\t\tsubAggregations: make(map[string]Aggregation),\n\t}\n}"} {"input": "package git\n\nimport (\n\t\"gopkg.in/src-d/go-git.v4/plumbing\"\n)\n\n\n\n\nfunc (repo *Repository) GetBlob(idStr string) (*Blob, error) {\n\tid, err := NewIDFromString(idStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn repo.getBlob(id)\n}\n\nfunc (repo *Repository) getBlob(id SHA1) (*Blob, error) ", "output": "{\n\tencodedObj, err := repo.gogitRepo.Storer.EncodedObject(plumbing.AnyObject, id)\n\tif err != nil {\n\t\treturn nil, ErrNotExist{id.String(), \"\"}\n\t}\n\n\treturn &Blob{\n\t\tID: id,\n\t\tgogitEncodedObj: encodedObj,\n\t}, nil\n}"} {"input": "package version\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n)\n\nconst Version = \"2020.1.3\"\n\n\n\n\n\nfunc Print() {\n\tv, release := version()\n\n\tif release {\n\t\tfmt.Printf(\"%s %s\\n\", filepath.Base(os.Args[0]), v)\n\t} else if v == \"devel\" {\n\t\tfmt.Printf(\"%s (no version)\\n\", filepath.Base(os.Args[0]))\n\t} else {\n\t\tfmt.Printf(\"%s (devel, %s)\\n\", filepath.Base(os.Args[0]), v)\n\t}\n}\n\nfunc Verbose() {\n\tPrint()\n\tfmt.Println()\n\tfmt.Println(\"Compiled with Go version:\", runtime.Version())\n\tprintBuildInfo()\n}\n\nfunc version() (string, bool) ", "output": "{\n\tif Version != \"devel\" {\n\t\treturn Version, true\n\t}\n\tv, ok := buildInfoVersion()\n\tif ok {\n\t\treturn v, false\n\t}\n\treturn \"devel\", false\n}"} {"input": "package hash\n\nimport \"unsafe\"\n\nconst DJBInit uint32 = 5381\n\n\n\nfunc DJB(hs ...uint32) uint32 {\n\tacc := DJBInit\n\tfor _, h := range hs {\n\t\tacc = DJBCombine(acc, h)\n\t}\n\treturn acc\n}\n\nfunc UInt32(u uint32) uint32 {\n\treturn u\n}\n\nfunc UInt64(u uint64) uint32 {\n\treturn mul33(uint32(u>>32)) + uint32(u&0xffffffff)\n}\n\nfunc Pointer(p unsafe.Pointer) uint32 {\n\tswitch unsafe.Sizeof(p) {\n\tcase 4:\n\t\treturn UInt32(uint32(uintptr(p)))\n\tcase 8:\n\t\treturn UInt64(uint64(uintptr(p)))\n\tdefault:\n\t\tpanic(\"unhandled pointer size\")\n\t}\n}\n\nfunc UIntPtr(p uintptr) uint32 {\n\tswitch unsafe.Sizeof(p) {\n\tcase 4:\n\t\treturn UInt32(uint32(p))\n\tcase 8:\n\t\treturn UInt64(uint64(p))\n\tdefault:\n\t\tpanic(\"unhandled pointer size\")\n\t}\n}\n\nfunc String(s string) uint32 {\n\th := DJBInit\n\tfor i := 0; i < len(s); i++ {\n\t\th = DJBCombine(h, uint32(s[i]))\n\t}\n\treturn h\n}\n\nfunc mul33(u uint32) uint32 {\n\treturn u<<5 + u\n}\n\nfunc DJBCombine(acc, h uint32) uint32 ", "output": "{\n\treturn mul33(acc) + h\n}"} {"input": "package rsets\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/pingcap/tidb/context\"\n\t\"github.com/pingcap/tidb/plan\"\n\t\"github.com/pingcap/tidb/plan/plans\"\n)\n\nvar (\n\t_ plan.Planner = (*LimitRset)(nil)\n\t_ plan.Planner = (*OffsetRset)(nil)\n)\n\n\ntype OffsetRset struct {\n\tCount uint64\n\tSrc plan.Plan\n}\n\n\nfunc (r *OffsetRset) Plan(ctx context.Context) (plan.Plan, error) {\n\treturn &plans.OffsetDefaultPlan{Count: r.Count, Src: r.Src, Fields: r.Src.GetFields()}, nil\n}\n\nfunc (r *OffsetRset) String() string {\n\treturn fmt.Sprintf(\" OFFSET %d\", r.Count)\n}\n\n\ntype LimitRset struct {\n\tCount uint64\n\tSrc plan.Plan\n}\n\n\n\n\nfunc (r *LimitRset) String() string {\n\treturn fmt.Sprintf(\" LIMIT %d\", r.Count)\n}\n\nfunc (r *LimitRset) Plan(ctx context.Context) (plan.Plan, error) ", "output": "{\n\treturn &plans.LimitDefaultPlan{Count: r.Count, Src: r.Src, Fields: r.Src.GetFields()}, nil\n}"} {"input": "package main_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\t\"github.com/onsi/gomega/gexec\"\n\n\t\"testing\"\n)\n\nvar pathToTee string\n\n\n\nfunc TestTee(t *testing.T) ", "output": "{\n\n\tBeforeSuite(func() {\n\t\tvar err error\n\t\tpathToTee, err = gexec.Build(\"github.com/iestynpryce/goreutils/tee\")\n\t\tExpect(err).NotTo(HaveOccurred())\n\t})\n\n\tAfterSuite(func() {\n\t\tgexec.CleanupBuildArtifacts()\n\t})\n\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Tee Suite\")\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"sync\"\n\n\t\"github.com/open-policy-agent/opa/cmd\"\n\t\"github.com/open-policy-agent/opa/plugins\"\n\t\"github.com/open-policy-agent/opa/plugins/logs\"\n\t\"github.com/open-policy-agent/opa/runtime\"\n\t\"github.com/open-policy-agent/opa/util\"\n)\n\ntype Config struct {\n\tStderr bool `json:\"stderr\"`\n}\n\ntype Factory struct{}\n\n\n\nfunc (Factory) Validate(_ *plugins.Manager, config []byte) (interface{}, error) {\n\tparsedConfig := Config{}\n\treturn parsedConfig, util.Unmarshal(config, &parsedConfig)\n}\n\ntype PrintlnLogger struct {\n\tconfig Config\n\tmtx sync.Mutex\n}\n\nfunc (p *PrintlnLogger) Start(ctx context.Context) error {\n\treturn nil\n}\n\nfunc (p *PrintlnLogger) Stop(ctx context.Context) {\n}\n\nfunc (p *PrintlnLogger) Reconfigure(ctx context.Context, config interface{}) {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tp.config = config.(Config)\n}\n\nfunc (p *PrintlnLogger) Log(ctx context.Context, event logs.EventV1) error {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tw := os.Stdout\n\tif p.config.Stderr {\n\t\tw = os.Stderr\n\t}\n\tfmt.Fprintln(w, event) \n\treturn nil\n}\n\nfunc main() {\n\n\truntime.RegisterPlugin(\"println_decision_logger\", Factory{})\n\n\tif err := cmd.RootCommand.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc (Factory) New(_ *plugins.Manager, config interface{}) plugins.Plugin ", "output": "{\n\treturn &PrintlnLogger{\n\t\tconfig: config.(Config),\n\t}\n}"} {"input": "package problem0204\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\nvar tcs = []struct {\n\tn int\n\tans int\n}{\n\n\n\n}\n\n\n\nfunc Benchmark_countPrimes(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, tc := range tcs {\n\t\t\tcountPrimes(tc.n)\n\t\t}\n\t}\n}\n\nfunc Test_countPrimes(t *testing.T) ", "output": "{\n\ta := assert.New(t)\n\n\tfor _, tc := range tcs {\n\t\ta.Equal(tc.ans, countPrimes(tc.n), \"输入:%v\", tc)\n\t}\n}"} {"input": "package ambition\n\nimport (\n\tcrand \"crypto/rand\"\n\t\"encoding/base64\"\n\t\"golang.org/x/crypto/bcrypt\"\n\t\"math/rand\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\n\n\nfunc CreateSaltAndHashedPassword(password []byte) ([]byte, []byte, error) {\n\tnano := time.Now().UnixNano()\n\trand.Seed(nano)\n\trandom := rand.Int31()\n\tsalt := strconv.Itoa(int(nano)) + strconv.Itoa(int(random))\n\n\thash, err := bcrypt.GenerateFromPassword([]byte(string(password)+salt), 10)\n\n\treturn []byte(salt), hash, err\n}\n\n\n\n\n\n\n\n\n\nfunc GenerateRandomBytes(n int) ([]byte, error) {\n\tb := make([]byte, n)\n\t_, err := crand.Read(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}\n\n\n\n\n\n\nfunc GenerateRandomString(s int) (string, error) {\n\tb, err := GenerateRandomBytes(s)\n\treturn base64.URLEncoding.EncodeToString(b), err\n}\n\nfunc HashToken(token string) string {\n\thash, _ := bcrypt.GenerateFromPassword([]byte(token), 10)\n\treturn string(hash)\n}\n\nfunc CompareHashAndToken(hash string, token string) bool {\n\n\terr := bcrypt.CompareHashAndPassword([]byte(hash), []byte(token))\n\treturn err == nil\n}\n\nfunc LoginUser(username string, password string) {}\n\nfunc CompareSaltAndPasswordToHash(salt, hashedPassword, password []byte) bool ", "output": "{\n\tsaltedPassword := []byte(string(password) + string(salt))\n\n\terr := bcrypt.CompareHashAndPassword(hashedPassword, saltedPassword)\n\treturn err == nil\n}"} {"input": "package badger\n\n\n\n\n\n\n\n\n\ntype ManagedDB struct {\n\t*DB\n}\n\n\n\n\n\n\nfunc OpenManaged(opts Options) (*ManagedDB, error) {\n\topts.managedTxns = true\n\tdb, err := Open(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ManagedDB{db}, nil\n}\n\n\n\nfunc (db *ManagedDB) NewTransaction(update bool) {\n\tpanic(\"Cannot use NewTransaction() for ManagedDB. Use NewTransactionAt() instead.\")\n}\n\n\n\n\n\n\nfunc (db *ManagedDB) NewTransactionAt(readTs uint64, update bool) *Txn {\n\ttxn := db.DB.NewTransaction(update)\n\ttxn.readTs = readTs\n\treturn txn\n}\n\n\n\n\n\n\nfunc (txn *Txn) CommitAt(commitTs uint64, callback func(error)) error {\n\tif !txn.db.opt.managedTxns {\n\t\treturn ErrManagedTxn\n\t}\n\ttxn.commitTs = commitTs\n\treturn txn.Commit(callback)\n}\n\n\n\n\n\n\nfunc (db *ManagedDB) GetSequence(_ []byte, _ uint64) (*Sequence, error) {\n\tpanic(\"Cannot use GetSequence for ManagedDB.\")\n}\n\nfunc (db *ManagedDB) PurgeVersionsBelow(key []byte, ts uint64) error ", "output": "{\n\ttxn := db.NewTransactionAt(ts, false)\n\tdefer txn.Discard()\n\treturn db.purgeVersionsBelow(txn, key, ts)\n}"} {"input": "package dax\n\n\ntype Grapher interface {\n\tGetParent() Grapher\n\tAddChild(child Grapher)\n\tGetChildren() []Grapher\n}\n\ntype nodeStack struct {\n\tnodes []Grapher\n}\n\n\n\nfunc (s *nodeStack) Empty() bool {\n\treturn len(s.nodes) == 0\n}\n\nfunc (s *nodeStack) Push(n Grapher) {\n\ts.nodes = append(s.nodes, n)\n}\n\nfunc (s *nodeStack) Pop() Grapher {\n\ti := len(s.nodes) - 1\n\tn := s.nodes[i]\n\ts.nodes[i] = nil\n\ts.nodes = s.nodes[:i]\n\treturn n\n}\n\ntype SceneGraph struct {\n\tNode\n}\n\nfunc NewSceneGraph() *SceneGraph {\n\tsg := new(SceneGraph)\n\tsg.Init()\n\treturn sg\n}\n\nfunc (sg *SceneGraph) Init() {\n\tsg.Node.Init()\n}\n\nfunc (sg *SceneGraph) updateWorldTransform() {\n\tsg.Node.updateWorldTransform(false)\n}\n\nfunc (sg *SceneGraph) Update(time float64) {\n\tsg.updateWorldTransform()\n}\n\n\nfunc (sg *SceneGraph) Traverse() <-chan Grapher {\n\tch := make(chan Grapher)\n\n\tgo func() {\n\t\tvar stack nodeStack\n\n\t\tstack.Init()\n\t\tstack.Push(sg)\n\n\t\tfor !stack.Empty() {\n\t\t\tn := stack.Pop()\n\t\t\tch <- n\n\t\t\tchildren := n.GetChildren()\n\t\t\tfor i := len(children) - 1; i >= 0; i-- {\n\t\t\t\tstack.Push(children[i])\n\t\t\t}\n\t\t}\n\t\tclose(ch)\n\t}()\n\n\treturn ch\n}\n\nfunc (sg *SceneGraph) Draw(fb Framebuffer) {\n\tfb.render().drawSceneGraph(fb, sg)\n}\n\nfunc (s *nodeStack) Init() ", "output": "{\n\ts.nodes = make([]Grapher, 0, 16)\n}"} {"input": "package aws\n\nimport (\n\t\"github.com/aws/aws-sdk-go/service/opsworks\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/helper/schema\"\n)\n\n\n\nfunc resourceAwsOpsworksNodejsAppLayer() *schema.Resource ", "output": "{\n\tlayerType := &opsworksLayerType{\n\t\tTypeName: opsworks.LayerTypeNodejsApp,\n\t\tDefaultLayerName: \"Node.js App Server\",\n\n\t\tAttributes: map[string]*opsworksLayerTypeAttribute{\n\t\t\t\"nodejs_version\": {\n\t\t\t\tAttrName: opsworks.LayerAttributesKeysNodejsVersion,\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tDefault: \"0.10.38\",\n\t\t\t},\n\t\t},\n\t}\n\n\treturn layerType.SchemaResource()\n}"} {"input": "package sfproto\n\nimport (\n\t\"github.com/sarifsystems/sarif/sarif\"\n)\n\ntype wrappedConn struct {\n\tid string\n\tConn\n}\n\nfunc (c *wrappedConn) Publish(msg sarif.Message) error {\n\treturn c.Write(msg)\n}\n\n\n\nfunc (c *wrappedConn) Consume() (<-chan sarif.Message, error) {\n\tch := make(chan sarif.Message, 10)\n\n\tgo func() {\n\t\tfor {\n\t\t\tmsg, err := c.Read()\n\t\t\tif err != nil {\n\t\t\t\tclose(ch)\n\t\t\t\tc.Close()\n\t\t\t\tc.Conn = nil\n\t\t\t\treturn\n\t\t\t}\n\t\t\tch <- msg\n\t\t}\n\t}()\n\n\treturn (<-chan sarif.Message)(ch), nil\n}\n\nfunc wrap(conn Conn) sarif.Connection {\n\treturn &wrappedConn{sarif.GenerateId(), conn}\n}\n\nfunc (c *wrappedConn) Subscribe(src, action, dest string) error ", "output": "{\n\tmsg := Subscribe(action, dest)\n\tmsg.Source = src\n\treturn c.Publish(msg)\n}"} {"input": "package ansicolor\n\nimport \"syscall\"\n\nvar GetConsoleScreenBufferInfo = getConsoleScreenBufferInfo\n\nfunc ChangeColor(color uint16) {\n\tsetConsoleTextAttribute(uintptr(syscall.Stdout), color)\n}\n\n\n\nfunc ResetColor() ", "output": "{\n\tChangeColor(uint16(0x0007))\n}"} {"input": "package components\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/scipipe/scipipe\"\n)\n\nvar params = []string{\"abc\", \"bcd\", \"cde\"}\n\nfunc TestFileToParamsReader(tt *testing.T) {\n\tos.MkdirAll(\".tmp\", 0744)\n\tfilePath := \".tmp/filereader_testfile.txt\"\n\tf, err := os.Create(\".tmp/filereader_testfile.txt\")\n\tif err != nil {\n\t\ttt.Fatalf(\"Could not create file: %s\", filePath)\n\t}\n\tfor _, s := range params {\n\t\tf.WriteString(s + \"\\n\")\n\t}\n\tf.Close()\n\n\twf := scipipe.NewWorkflow(\"wf\", 4)\n\trd := NewFileToParamsReader(wf, \"reader\", filePath)\n\tchecker := NewFileToParamsChecker(wf, \"filetoparams_checker\", tt)\n\tchecker.InParams().From(rd.OutLine())\n\n\twf.Run()\n\n\terr = os.Remove(filePath)\n\tif err != nil {\n\t\ttt.Fatalf(\"Could not remove file: %s\", filePath)\n\t}\n\terr = os.RemoveAll(\".tmp\")\n\tif err != nil {\n\t\ttt.Fatal(\"Could not remove temp folder: .tmp\")\n\t}\n}\n\ntype FileToParamsChecker struct {\n\tscipipe.BaseProcess\n\t*testing.T\n}\n\nfunc NewFileToParamsChecker(wf *scipipe.Workflow, pname string, t *testing.T) *FileToParamsChecker {\n\tp := &FileToParamsChecker{\n\t\tscipipe.NewBaseProcess(wf, pname),\n\t\tt,\n\t}\n\tp.InitInParamPort(p, \"params\")\n\twf.AddProc(p)\n\treturn p\n}\n\nfunc (p *FileToParamsChecker) InParams() *scipipe.InParamPort { return p.InParamPort(\"params\") }\n\n\n\nfunc (p *FileToParamsChecker) Run() ", "output": "{\n\ti := 0\n\tfor param := range p.InParams().Chan {\n\t\texpected := params[i]\n\t\tactual := param\n\t\tif actual != expected {\n\t\t\tp.T.Errorf(\"actual parameter value (%s) was not as expected (%s) in FileToParamsReader\", actual, expected)\n\t\t}\n\t\ti++\n\t}\n}"} {"input": "package log\n\n\n\n\n\nfunc (me *Logging) SetPrefix(value string) {\n\tme.prefix = value\n\tif me.console != nil {\n\t\tme.console.SetPrefix(me.prefix)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPrefix(me.prefix)\n\t}\n}\n\n\nfunc (me *Logging) Priority() int {\n\treturn me.priority\n}\n\n\nfunc (me *Logging) SetPriority(value int) {\n\tme.setPriority = true\n\tme.priority = value\n\tif me.console != nil {\n\t\tme.console.SetPriority(me.priority)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPriority(me.priority)\n\t}\n}\n\n\nfunc (me *Logging) Layouts() int {\n\treturn me.layouts\n}\n\n\nfunc (me *Logging) SetLayouts(value int) {\n\tme.setLayouts = true\n\tme.layouts = value\n\tif me.console != nil {\n\t\tme.console.SetLayouts(me.layouts)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetLayouts(me.layouts)\n\t}\n}\n\n\nfunc (me *Logging) Outputs() int {\n\treturn me.outputs\n}\n\n\nfunc (me *Logging) SetOutputs(value int) {\n\tme.setOutputs = true\n\tme.outputs = value\n}\n\nfunc (me *Logging) Prefix() string ", "output": "{\n\treturn me.prefix\n}"} {"input": "package metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/collector/model/pdata\"\n)\n\nfunc TestNewMetricDataType(t *testing.T) {\n\tmetricDataType := NewMetricDataType(pdata.MetricDataTypeGauge, pdata.MetricAggregationTemporalityDelta, true)\n\n\trequire.NotNil(t, metricDataType)\n\tassert.Equal(t, metricDataType.MetricDataType(), pdata.MetricDataTypeGauge)\n\tassert.Equal(t, metricDataType.AggregationTemporality(), pdata.MetricAggregationTemporalityDelta)\n\tassert.True(t, metricDataType.IsMonotonic())\n}\n\nfunc TestMetricValueDataType_MetricDataType(t *testing.T) {\n\tvalueDataType := metricValueDataType{dataType: pdata.MetricDataTypeGauge}\n\n\tassert.Equal(t, valueDataType.MetricDataType(), pdata.MetricDataTypeGauge)\n}\n\n\n\nfunc TestMetricValueDataType_IsMonotonic(t *testing.T) {\n\tvalueDataType := metricValueDataType{isMonotonic: true}\n\n\tassert.True(t, valueDataType.IsMonotonic())\n}\n\nfunc TestMetricValueDataType_AggregationTemporality(t *testing.T) ", "output": "{\n\tvalueDataType := metricValueDataType{aggregationTemporality: pdata.MetricAggregationTemporalityDelta}\n\n\tassert.Equal(t, valueDataType.AggregationTemporality(), pdata.MetricAggregationTemporalityDelta)\n}"} {"input": "package endpoints\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\nfunc TestStatusNoContent(t *testing.T) {\n\thandler := NewStatusEndpoint(\"\")\n\tw := httptest.NewRecorder()\n\thandler(w, nil, nil)\n\tif w.Code != http.StatusNoContent {\n\t\tt.Errorf(\"Bad code for empty content. Expected %d, got %d\", http.StatusNoContent, w.Code)\n\t}\n}\n\n\n\nfunc TestStatusWithContent(t *testing.T) ", "output": "{\n\thandler := NewStatusEndpoint(\"ready\")\n\tw := httptest.NewRecorder()\n\thandler(w, nil, nil)\n\tif w.Code != http.StatusOK {\n\t\tt.Errorf(\"Bad code for empty content. Expected %d, got %d\", http.StatusOK, w.Code)\n\t}\n\tif w.Body.String() != \"ready\" {\n\t\tt.Errorf(\"Bad status body. Expected %s, got %s\", \"ready\", w.Body.String())\n\t}\n}"} {"input": "package models\n\nimport (\n\t\"html/template\"\n\t\"time\"\n\n\t\"github.com/NyaaPantsu/nyaa/config\"\n)\n\n\ntype Comment struct {\n\tID uint `gorm:\"column:comment_id;primary_key\"`\n\tTorrentID uint `gorm:\"column:torrent_id\"`\n\tUserID uint `gorm:\"column:user_id\"`\n\tContent string `gorm:\"column:content\"`\n\tCreatedAt time.Time `gorm:\"column:created_at\"`\n\tUpdatedAt time.Time `gorm:\"column:updated_at\"`\n\tDeletedAt *time.Time\n\n\tTorrent *Torrent `gorm:\"AssociationForeignKey:TorrentID;ForeignKey:torrent_id\"`\n\tUser *User `gorm:\"AssociationForeignKey:UserID;ForeignKey:user_id\"`\n}\n\n\ntype CommentJSON struct {\n\tUsername string `json:\"username\"`\n\tUserID int `json:\"user_id\"`\n\tUserAvatar string `json:\"user_avatar\"`\n\tContent template.HTML `json:\"content\"`\n\tDate time.Time `json:\"date\"`\n}\n\n\n\n\n\nfunc (c Comment) TableName() string {\n\treturn config.Get().Models.CommentsTableName\n}\n\n\nfunc (c *Comment) Identifier() string { \n\treturn c.Torrent.Identifier()\n}\n\nfunc (c Comment) Size() int ", "output": "{\n\treturn (3 + 3*3 + 2 + 2 + len(c.Content)) * 8\n}"} {"input": "package output\n\nimport \"reflect\"\n\n\ntype S3Grantee struct {\n\tID string `json:\"id\"`\n\tType string `json:\"type\"`\n\tPermissions string `json:\"permissions\"`\n}\n\n\ntype S3 struct {\n\tProviderType string `json:\"_type\"`\n\tDatacenterName string `json:\"datacenter_name,omitempty\"`\n\tDatacenterRegion string `json:\"datacenter_region\"`\n\tAccessKeyID string `json:\"aws_access_key_id\"`\n\tSecretAccessKey string `json:\"aws_secret_access_key\"`\n\tName string `json:\"name\"`\n\tACL string `json:\"acl\"`\n\tBucketLocation string `json:\"bucket_location\"`\n\tBucketURI string `json:\"bucket_uri\"`\n\tGrantees []S3Grantee `json:\"grantees,omitempty\"`\n\tTags map[string]string `json:\"tags\"`\n\tService string `json:\"service\"`\n\tStatus string `json:\"status\"`\n\tExists bool\n}\n\n\n\n\n\nfunc (s S3) GetTags() map[string]string {\n\treturn s.Tags\n}\n\n\nfunc (s S3) ProviderID() string {\n\treturn s.Name\n}\n\n\nfunc (s S3) ComponentName() string {\n\treturn s.Name\n}\n\nfunc (s *S3) HasChanged(os *S3) bool ", "output": "{\n\tif s.ACL != os.ACL {\n\t\treturn true\n\t}\n\n\tif len(s.Grantees) < 1 && len(os.Grantees) < 1 {\n\t\treturn false\n\t}\n\n\treturn !reflect.DeepEqual(s.Grantees, os.Grantees)\n}"} {"input": "package kms\n\nimport (\n\t\"os\"\n\n\t\"github.com/denverdino/aliyungo/common\"\n)\n\nconst (\n\tKMSDefaultEndpoint = \"https://kms.cn-hangzhou.aliyuncs.com\"\n\tKMSAPIVersion = \"2016-01-20\"\n\tKMSServiceCode = \"kms\"\n)\n\ntype Client struct {\n\tcommon.Client\n}\n\n\nfunc NewClient(accessKeyId, accessKeySecret string) *Client {\n\tendpoint := os.Getenv(\"KMS_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = KMSDefaultEndpoint\n\t}\n\treturn NewClientWithEndpoint(endpoint, accessKeyId, accessKeySecret)\n}\n\nfunc NewClientWithRegion(accessKeyId string, accessKeySecret string, regionID common.Region) *Client {\n\tendpoint := os.Getenv(\"KMS_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = KMSDefaultEndpoint\n\t}\n\tclient := &Client{}\n\tclient.NewInit(endpoint, KMSAPIVersion, accessKeyId, accessKeySecret, KMSServiceCode, regionID)\n\treturn client\n}\n\nfunc NewClientWithEndpoint(endpoint string, accessKeyId string, accessKeySecret string) *Client {\n\tclient := &Client{}\n\tclient.Init(endpoint, KMSAPIVersion, accessKeyId, accessKeySecret)\n\treturn client\n}\n\nfunc NewECSClientWithSecurityToken(accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client {\n\tendpoint := os.Getenv(\"KMS_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = KMSDefaultEndpoint\n\t}\n\n\treturn NewKMSClientWithEndpointAndSecurityToken(endpoint, accessKeyId, accessKeySecret, securityToken, regionID)\n}\n\n\n\nfunc NewKMSClientWithEndpointAndSecurityToken(endpoint string, accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client ", "output": "{\n\tclient := &Client{}\n\tclient.WithEndpoint(endpoint).\n\t\tWithVersion(KMSAPIVersion).\n\t\tWithAccessKeyId(accessKeyId).\n\t\tWithAccessKeySecret(accessKeySecret).\n\t\tWithSecurityToken(securityToken).\n\t\tWithServiceCode(KMSServiceCode).\n\t\tWithRegionID(regionID).\n\t\tInitClient()\n\treturn client\n}"} {"input": "package multiraft\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cockroachdb/cockroach/util\"\n)\n\n\n\n\ntype eventDemux struct {\n\tLeaderElection chan *EventLeaderElection\n\tCommandCommitted chan *EventCommandCommitted\n\tMembershipChangeCommitted chan *EventMembershipChangeCommitted\n\n\tevents <-chan interface{}\n\tstopper *util.Stopper\n}\n\nfunc newEventDemux(events <-chan interface{}) *eventDemux {\n\treturn &eventDemux{\n\t\tmake(chan *EventLeaderElection, 1000),\n\t\tmake(chan *EventCommandCommitted, 1000),\n\t\tmake(chan *EventMembershipChangeCommitted, 1000),\n\t\tevents,\n\t\tutil.NewStopper(1),\n\t}\n}\n\nfunc (e *eventDemux) start() {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-e.events:\n\t\t\t\tswitch event := event.(type) {\n\t\t\t\tcase *EventLeaderElection:\n\t\t\t\t\te.LeaderElection <- event\n\n\t\t\t\tcase *EventCommandCommitted:\n\t\t\t\t\te.CommandCommitted <- event\n\n\t\t\t\tcase *EventMembershipChangeCommitted:\n\t\t\t\t\te.MembershipChangeCommitted <- event\n\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(fmt.Sprintf(\"got unknown event type %T\", event))\n\t\t\t\t}\n\n\t\t\tcase <-e.stopper.ShouldStop():\n\t\t\t\te.stopper.SetStopped()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\n\nfunc (e *eventDemux) stop() ", "output": "{\n\te.stopper.Stop()\n\tclose(e.CommandCommitted)\n\tclose(e.MembershipChangeCommitted)\n\tclose(e.LeaderElection)\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n)\n\ntype BuiltInClass struct {\n\tname Instance\n\tsupers []Class\n\tslots []Instance\n}\n\nfunc NewBuiltInClass(name string, super Class, slots ...string) Class {\n\tslotNames := []Instance{}\n\tfor _, slot := range slots {\n\t\tslotNames = append(slotNames, NewSymbol(slot))\n\t}\n\treturn BuiltInClass{NewSymbol(name), []Class{super}, slotNames}\n}\n\nfunc (p BuiltInClass) Supers() []Class {\n\treturn p.supers\n}\n\nfunc (p BuiltInClass) Slots() []Instance {\n\treturn p.slots\n}\n\nfunc (p BuiltInClass) Initform(arg Instance) (v Instance, ok bool) {\n\treturn nil, false\n}\n\n\n\nfunc (BuiltInClass) Class() Class {\n\treturn BuiltInClassClass\n}\n\nfunc (p BuiltInClass) String() string {\n\treturn fmt.Sprint(p.name)\n}\n\nfunc (p BuiltInClass) Initarg(arg Instance) (v Instance, ok bool) ", "output": "{\n\treturn arg, true\n}"} {"input": "package router\n\n\n\n\nimport (\n\t\"github.com/weaveworks/mesh\"\n)\n\n\n\ntype AWSVPCConnection struct {\n\testablishedChan chan struct{}\n\terrorChan chan error\n}\n\n\n\nfunc (conn *AWSVPCConnection) EstablishedChannel() <-chan struct{} {\n\treturn conn.establishedChan\n}\n\nfunc (conn *AWSVPCConnection) ErrorChannel() <-chan error {\n\treturn conn.errorChan\n}\n\nfunc (conn *AWSVPCConnection) Stop() {}\n\nfunc (conn *AWSVPCConnection) ControlMessage(tag byte, msg []byte) {\n}\n\nfunc (conn *AWSVPCConnection) DisplayName() string {\n\treturn \"awsvpc\"\n}\n\n\n\nfunc (conn *AWSVPCConnection) Forward(key ForwardPacketKey) FlowOp {\n\treturn DiscardingFlowOp{}\n}\n\ntype AWSVPC struct{}\n\nfunc NewAWSVPC() AWSVPC {\n\treturn AWSVPC{}\n}\n\n\n\nfunc (vpc AWSVPC) AddFeaturesTo(features map[string]string) {}\n\nfunc (vpc AWSVPC) PrepareConnection(params mesh.OverlayConnectionParams) (mesh.OverlayConnection, error) {\n\tconn := &AWSVPCConnection{\n\t\testablishedChan: make(chan struct{}),\n\t\terrorChan: make(chan error, 1),\n\t}\n\treturn conn, nil\n}\n\nfunc (vpc AWSVPC) Diagnostics() interface{} {\n\treturn nil\n}\n\n\n\nfunc (vpc AWSVPC) InvalidateRoutes() {}\n\nfunc (vpc AWSVPC) InvalidateShortIDs() {}\n\nfunc (vpc AWSVPC) StartConsumingPackets(localPeer *mesh.Peer, peers *mesh.Peers, consumer OverlayConsumer) error {\n\treturn nil\n}\n\nfunc (conn *AWSVPCConnection) Confirm() ", "output": "{\n\tclose(conn.establishedChan)\n}"} {"input": "package main\n\nimport \"fmt\"\nimport \"sort\"\n\ntype ByLength []string\n\n\n\nfunc (s ByLength) Swap(i, j int) {\n s[i], s[j] = s[j], s[i]\n}\n\nfunc (s ByLength) Less(i, j int) bool {\n return len(s[i]) < len(s[j])\n}\n\nfunc main() {\n fruits := []string{\"peach\", \"banana\", \"kiwi\"}\n sort.Sort(ByLength(fruits))\n fmt.Println(fruits)\n}\n\nfunc (s ByLength) Len() int ", "output": "{\n return len(s)\n}"} {"input": "package api\n\n\ntype ProductInternetAPI struct {\n\t*baseAPI\n}\n\n\n\n\nfunc NewProductInternetAPI(client *Client) *ProductInternetAPI ", "output": "{\n\treturn &ProductInternetAPI{\n\t\t&baseAPI{\n\t\t\tclient: client,\n\t\t\tFuncGetResourceURL: func() string {\n\t\t\t\treturn \"product/internet\"\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package graph\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gonum/graph\"\n\t\"github.com/gonum/graph/concrete\"\n\t\"github.com/gonum/graph/encoding/dot\"\n)\n\ntype Node struct {\n\tId int\n\tUniqueName string\n\tLabelName string\n\tColor string\n}\n\nfunc (n Node) ID() int {\n\treturn n.Id\n}\n\n\n\n\nfunc NewMutableDirectedGraph(g *concrete.DirectedGraph) *MutableDirectedGraph {\n\treturn &MutableDirectedGraph{\n\t\tDirectedGraph: concrete.NewDirectedGraph(),\n\t\tnodesByName: make(map[string]graph.Node),\n\t}\n}\n\ntype MutableDirectedGraph struct {\n\t*concrete.DirectedGraph\n\n\tnodesByName map[string]graph.Node\n}\n\nfunc (g *MutableDirectedGraph) AddNode(n *Node) error {\n\tif _, exists := g.nodesByName[n.UniqueName]; exists {\n\t\treturn fmt.Errorf(\"node .UniqueName collision: %s\", n.UniqueName)\n\t}\n\n\tg.nodesByName[n.UniqueName] = n\n\tg.DirectedGraph.AddNode(n)\n\treturn nil\n}\n\nfunc (g *MutableDirectedGraph) NodeByName(name string) (graph.Node, bool) {\n\tn, exists := g.nodesByName[name]\n\treturn n, exists && g.DirectedGraph.Has(n)\n}\n\nfunc (n Node) DOTAttributes() []dot.Attribute ", "output": "{\n\tcolor := n.Color\n\tif len(color) == 0 {\n\t\tcolor = \"black\"\n\t}\n\n\treturn []dot.Attribute{\n\t\t{Key: \"label\", Value: fmt.Sprintf(\"%q\", n.LabelName)},\n\t\t{Key: \"color\", Value: color},\n\t}\n}"} {"input": "package iot\n\nimport (\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/client\"\n\t\"github.com/aws/aws-sdk-go/aws/client/metadata\"\n\t\"github.com/aws/aws-sdk-go/aws/request\"\n\t\"github.com/aws/aws-sdk-go/aws/signer/v4\"\n\t\"github.com/aws/aws-sdk-go/private/protocol/restjson\"\n)\n\n\n\n\n\n\n\ntype IoT struct {\n\t*client.Client\n}\n\n\nvar initClient func(*client.Client)\n\n\nvar initRequest func(*request.Request)\n\n\nconst (\n\tServiceName = \"iot\" \n\tEndpointsID = ServiceName \n)\n\n\n\n\n\n\n\n\n\n\n\nfunc New(p client.ConfigProvider, cfgs ...*aws.Config) *IoT {\n\tc := p.ClientConfig(EndpointsID, cfgs...)\n\treturn newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName)\n}\n\n\n\n\n\n\nfunc (c *IoT) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\tif initRequest != nil {\n\t\tinitRequest(req)\n\t}\n\n\treturn req\n}\n\nfunc newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *IoT ", "output": "{\n\tif len(signingName) == 0 {\n\t\tsigningName = \"execute-api\"\n\t}\n\tsvc := &IoT{\n\t\tClient: client.New(\n\t\t\tcfg,\n\t\t\tmetadata.ClientInfo{\n\t\t\t\tServiceName: ServiceName,\n\t\t\t\tSigningName: signingName,\n\t\t\t\tSigningRegion: signingRegion,\n\t\t\t\tEndpoint: endpoint,\n\t\t\t\tAPIVersion: \"2015-05-28\",\n\t\t\t},\n\t\t\thandlers,\n\t\t),\n\t}\n\n\tsvc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)\n\tsvc.Handlers.Build.PushBackNamed(restjson.BuildHandler)\n\tsvc.Handlers.Unmarshal.PushBackNamed(restjson.UnmarshalHandler)\n\tsvc.Handlers.UnmarshalMeta.PushBackNamed(restjson.UnmarshalMetaHandler)\n\tsvc.Handlers.UnmarshalError.PushBackNamed(restjson.UnmarshalErrorHandler)\n\n\tif initClient != nil {\n\t\tinitClient(svc.Client)\n\t}\n\n\treturn svc\n}"} {"input": "package tree\n\nimport (\n\t\"evergreen/compiler\"\n\t\"evergreen/dub/runtime\"\n\t\"fmt\"\n)\n\n\n\nfunc ParseDub(data []byte, offset int, status compiler.TaskStatus) *File ", "output": "{\n\tstatus.Begin()\n\tdefer status.End()\n\n\tstream := []rune(string(data))\n\tstate := &runtime.State{Stream: stream, Offset: offset}\n\tf := ParseFile(state)\n\tif state.Flow == 0 {\n\t\treturn f\n\t} else {\n\t\tpos := state.Deepest()\n\t\tname := state.RuneName(pos)\n\t\tstatus.LocationError(pos, fmt.Sprintf(\"Unexpected %s\", name))\n\t\treturn nil\n\t}\n}"} {"input": "package load_instructions\n\nimport (\n\t\"github.com/Frederick-S/jvmgo/instructions/base_instructions\"\n\t\"github.com/Frederick-S/jvmgo/runtime_data_area\"\n)\n\n\n\ntype FLoad3 struct {\n\tbase_instructions.NoOperandsInstruction\n}\n\n\n\nfunc (fLoad3 *FLoad3) Execute(frame *runtime_data_area.Frame) ", "output": "{\n\tloadFloatValueAndPush(frame, 3)\n}"} {"input": "package common\n\nimport (\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/names/v4\"\n\n\tapiservererrors \"github.com/juju/juju/apiserver/errors\"\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/state\"\n)\n\n\n\ntype DeadEnsurer struct {\n\tst state.EntityFinder\n\tafterDead func(names.Tag)\n\tgetCanModify GetAuthFunc\n}\n\n\n\n\nfunc NewDeadEnsurer(st state.EntityFinder, afterDead func(names.Tag), getCanModify GetAuthFunc) *DeadEnsurer {\n\treturn &DeadEnsurer{\n\t\tst: st,\n\t\tafterDead: afterDead,\n\t\tgetCanModify: getCanModify,\n\t}\n}\n\n\n\n\n\n\nfunc (d *DeadEnsurer) EnsureDead(args params.Entities) (params.ErrorResults, error) {\n\tresult := params.ErrorResults{\n\t\tResults: make([]params.ErrorResult, len(args.Entities)),\n\t}\n\tif len(args.Entities) == 0 {\n\t\treturn result, nil\n\t}\n\tcanModify, err := d.getCanModify()\n\tif err != nil {\n\t\treturn params.ErrorResults{}, errors.Trace(err)\n\t}\n\tfor i, entity := range args.Entities {\n\t\ttag, err := names.ParseTag(entity.Tag)\n\t\tif err != nil {\n\t\t\treturn params.ErrorResults{}, errors.Trace(err)\n\t\t}\n\n\t\terr = apiservererrors.ErrPerm\n\t\tif canModify(tag) {\n\t\t\terr = d.ensureEntityDead(tag)\n\t\t}\n\t\tresult.Results[i].Error = apiservererrors.ServerError(err)\n\t}\n\treturn result, nil\n}\n\nfunc (d *DeadEnsurer) ensureEntityDead(tag names.Tag) error ", "output": "{\n\tentity0, err := d.st.FindEntity(tag)\n\tif err != nil {\n\t\treturn err\n\t}\n\tentity, ok := entity0.(state.EnsureDeader)\n\tif !ok {\n\t\treturn apiservererrors.NotSupportedError(tag, \"ensuring death\")\n\t}\n\tif err := entity.EnsureDead(); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tif d.afterDead != nil {\n\t\td.afterDead(tag)\n\t}\n\treturn nil\n}"} {"input": "package blanket_emulator\n\nimport (\n\t\"fmt\"\n)\n\ntype Event interface {\n\tHash() uint64\n\tInspect() string\n}\n\ntype ReturnEvent uint64\ntype ReadEvent uint64\ntype WriteEvent struct {\n\tAddr uint64\n\tValue uint64\n}\ntype SyscallEvent uint64\ntype InvalidInstructionEvent uint64\n\nfunc (addr ReadEvent) Hash() uint64 {\n\treturn ReadEventHash(uint64(addr))\n}\n\nfunc (s WriteEvent) Hash() uint64 {\n\treturn WriteEventHash(s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Hash() uint64 {\n\treturn SysEventHash(uint64(s))\n}\n\nfunc (s ReturnEvent) Hash() uint64 {\n\treturn ReturnEventHash(uint64(s))\n}\n\nfunc (s InvalidInstructionEvent) Hash() uint64 {\n\treturn InvalidInstructionEventHash(uint64(s))\n}\n\n\n\nfunc (addr ReturnEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Return([%x])\", addr)\n}\n\nfunc (s WriteEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Write([%x]=%x)\", s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Sys(%x)\", s)\n}\n\nfunc (s InvalidInstructionEvent) Inspect() string {\n\treturn fmt.Sprintf(\"InvalidOpcode([%x])\", s)\n}\n\nfunc (addr ReadEvent) Inspect() string ", "output": "{\n\treturn fmt.Sprintf(\"Read([%x])\", addr)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/keybase/client/go/kbfs/env\"\n\t\"github.com/keybase/client/go/kbfs/fsrpc\"\n\t\"github.com/keybase/client/go/kbfs/libgit\"\n\t\"github.com/keybase/client/go/kbfs/libkbfs\"\n\t\"github.com/keybase/client/go/protocol/keybase1\"\n\t\"golang.org/x/net/context\"\n)\n\nconst gitRenameUsageStr = `Usage:\n kbfstool git rename /keybase/tlf/path oldName newName\n`\n\n\n\nfunc gitRename(ctx context.Context, config libkbfs.Config, args []string) (exitStatus int) {\n\tflags := flag.NewFlagSet(\"kbfs git rename\", flag.ContinueOnError)\n\terr := flags.Parse(args)\n\tif err != nil {\n\t\tprintError(\"git rename\", err)\n\t\treturn 1\n\t}\n\n\tinputs := flags.Args()\n\tif len(inputs) != 3 {\n\t\tfmt.Print(gitRenameUsageStr)\n\t\treturn 1\n\t}\n\n\tkbfsCtx := env.NewContext()\n\trpcHandler, shutdown := libgit.NewRPCHandlerWithCtx(kbfsCtx, config, nil)\n\tdefer shutdown()\n\n\terr = doGitRename(ctx, rpcHandler, inputs[0], inputs[1], inputs[2])\n\tif err != nil {\n\t\tprintError(\"git rename\", err)\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n\nfunc doGitRename(ctx context.Context,\n\trpcHandler *libgit.RPCHandler, tlfStr, oldName, newName string) error ", "output": "{\n\tp, err := fsrpc.NewPath(tlfStr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif p.PathType != fsrpc.TLFPathType {\n\t\treturn fmt.Errorf(\"%q is not a TLF path\", tlfStr)\n\t}\n\tif len(p.TLFComponents) > 0 {\n\t\treturn fmt.Errorf(\"%q is not the root path of a TLF\", tlfStr)\n\t}\n\tfolder := keybase1.FolderHandle{\n\t\tName: p.TLFName,\n\t\tFolderType: p.TLFType.FolderType(),\n\t}\n\n\treturn rpcHandler.RenameRepo(ctx, folder, oldName, newName)\n}"} {"input": "package remove_duplicates_from_sorted_list\n\n\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\n\n\nfunc deleteDuplicates(head *ListNode) *ListNode ", "output": "{\n\tif nil == head || nil == head.Next {\n\t\treturn head\n\t}\n\n\tp := head\n\tfor {\n\t\tif p.Val == p.Next.Val {\n\t\t\tp.Next = p.Next.Next\n\t\t} else {\n\t\t\tp = p.Next\n\t\t}\n\n\t\tif nil == p.Next {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn head\n}"} {"input": "package utils\n\n\n\nfunc Max(a int64, b int64) int64 {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc Min(a int64, b int64) int64 ", "output": "{\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}"} {"input": "package analytics\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\n\ntype UpdateAnalyticsInstanceDetails struct {\n\n\tDescription *string `mandatory:\"false\" json:\"description\"`\n\n\tEmailNotification *string `mandatory:\"false\" json:\"emailNotification\"`\n\n\tLicenseType LicenseTypeEnum `mandatory:\"false\" json:\"licenseType,omitempty\"`\n\n\tDefinedTags map[string]map[string]interface{} `mandatory:\"false\" json:\"definedTags\"`\n\n\tFreeformTags map[string]string `mandatory:\"false\" json:\"freeformTags\"`\n}\n\n\n\nfunc (m UpdateAnalyticsInstanceDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package cluster\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\n\t\"github.com/docker/docker/api/types\"\n\tv3 \"github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3\"\n\t\"github.com/rancher/rancher/pkg/settings\"\n\trketypes \"github.com/rancher/rke/types\"\n)\n\nfunc GetPrivateRepoURL(cluster *v3.Cluster) string {\n\tregistry := GetPrivateRepo(cluster)\n\tif registry == nil {\n\t\treturn \"\"\n\t}\n\treturn registry.URL\n}\n\n\n\nfunc GenerateClusterPrivateRegistryDockerConfig(cluster *v3.Cluster) (string, error) {\n\tif cluster == nil {\n\t\treturn \"\", nil\n\t}\n\treturn GeneratePrivateRegistryDockerConfig(GetPrivateRepo(cluster))\n}\n\n\nfunc GeneratePrivateRegistryDockerConfig(privateRegistry *rketypes.PrivateRegistry) (string, error) {\n\tif privateRegistry == nil || privateRegistry.User == \"\" || privateRegistry.Password == \"\" {\n\t\treturn \"\", nil\n\t}\n\tauthConfig := types.AuthConfig{\n\t\tUsername: privateRegistry.User,\n\t\tPassword: privateRegistry.Password,\n\t}\n\tencodedJSON, err := json.Marshal(authConfig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.URLEncoding.EncodeToString(encodedJSON), nil\n}\n\nfunc GetPrivateRepo(cluster *v3.Cluster) *rketypes.PrivateRegistry ", "output": "{\n\tif cluster != nil && cluster.Spec.RancherKubernetesEngineConfig != nil && len(cluster.Spec.RancherKubernetesEngineConfig.PrivateRegistries) > 0 {\n\t\tconfig := cluster.Spec.RancherKubernetesEngineConfig\n\t\treturn &config.PrivateRegistries[0]\n\t}\n\tif settings.SystemDefaultRegistry.Get() != \"\" {\n\t\treturn &rketypes.PrivateRegistry{\n\t\t\tURL: settings.SystemDefaultRegistry.Get(),\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package widgets\n\nimport (\n\t\"strings\"\n\n\t\"github.com/ambientsound/pms/songlist\"\n\t\"github.com/ambientsound/pms/style\"\n\t\"github.com/gdamore/tcell\"\n\t\"github.com/gdamore/tcell/views\"\n)\n\ntype ColumnheadersWidget struct {\n\tcolumns songlist.Columns\n\tview views.View\n\n\tstyle.Styled\n\tviews.WidgetWatchers\n}\n\n\n\nfunc (c *ColumnheadersWidget) SetColumns(cols songlist.Columns) {\n\tc.columns = cols\n}\n\nfunc (c *ColumnheadersWidget) Draw() {\n\tx := 0\n\ty := 0\n\tfor i := range c.columns {\n\t\tcol := c.columns[i]\n\t\ttitle := []rune(strings.Title(col.Tag()))\n\t\tp := 0\n\t\tfor _, r := range title {\n\t\t\tc.view.SetContent(x+p, y, r, nil, c.Style(\"header\"))\n\t\t\tp++\n\t\t}\n\t\tx += col.Width()\n\t}\n}\n\nfunc (c *ColumnheadersWidget) SetView(v views.View) {\n\tc.view = v\n}\n\nfunc (c *ColumnheadersWidget) Size() (int, int) {\n\tx, y := c.view.Size()\n\ty = 1\n\treturn x, y\n}\n\nfunc (w *ColumnheadersWidget) Resize() {\n}\n\nfunc (w *ColumnheadersWidget) HandleEvent(ev tcell.Event) bool {\n\treturn false\n}\n\nfunc NewColumnheadersWidget() (c *ColumnheadersWidget) ", "output": "{\n\tc = &ColumnheadersWidget{}\n\tc.columns = make(songlist.Columns, 0)\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n)\n\n\ntype Address struct {\n\tStreet, City string\n}\n\ntype Person struct {\n\tFirstName, LastName string\n}\n\ntype T1 string\ntype T2 string\ntype T3 string\n\nvar logger *log.Logger\n\nfunc main() {\n\tmyAddress := Address{\n\t\tStreet: \"Trimveien 6\",\n\t\tCity: \"Oslo\",\n\t}\n\tlog.Println(myAddress)\n\n\tme := Person{\n\t\tFirstName: \"Christian\",\n\t\tLastName: \"Bergum Bergersen\",\n\t}\n\tlog.Println(me)\n\n\tvar foo T1\n\tfoo = \"foo\"\n\tlog.Println(foo)\n\n\tvar bar T3\n\tbar = \"bar\"\n\tlog.Println(bar)\n}\n\n\nfunc (address Address) String() string {\n\treturn fmt.Sprintf(\"%s\", address)\n}\n\n\nfunc (person Person) String() string {\n\treturn fmt.Sprintf(\"%s %s\", person.FirstName, person.LastName)\n}\n\n\n\n\n\nfunc (t2 T2) String() string {\n\tlog.Print(\"Calling String() for : %v\", t2)\n\treturn fmt.Sprintln(t2)\n}\n\n\nfunc (bar T3) String() string {\n\tvar buf bytes.Buffer\n\tlogger = log.New(&buf, \"logger: \", log.Lshortfile)\n\tlogger.Printf(\"Calling String() for %+v\", bar)\n\treturn fmt.Sprintf(\"Bar\")\n}\n\nfunc (t1 T1) String() string ", "output": "{\n\treturn fmt.Sprint(t1)\n}"} {"input": "package flog\n\nimport \"github.com/Sirupsen/logrus\"\n\ntype Parameter interface {\n\tConvert() map[string]interface{}\n}\n\ntype Fields struct {\n\tEvent string\n\tError error\n}\n\nfunc (f Fields) Convert() map[string]interface{} {\n\tfields := map[string]interface{}{}\n\n\tif f.Event != \"\" {\n\t\tfields[\"event\"] = f.Event\n\t}\n\n\tif f.Error != nil {\n\t\tfields[\"error\"] = f.Error\n\t}\n\n\treturn fields\n}\n\ntype Details map[string]interface{}\n\nfunc (d Details) Convert() map[string]interface{} {\n\treturn d\n}\n\ntype DebugFields map[string]interface{}\n\n\n\nfunc transform(params []Parameter) logrus.Fields {\n\tlogrusFields := logrus.Fields{}\n\n\tfor _, p := range params {\n\t\tfieldMap := p.Convert()\n\n\t\tfor k, v := range fieldMap {\n\t\t\tlogrusFields[k] = v\n\t\t}\n\t}\n\n\treturn logrusFields\n}\n\nfunc Debug(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Debug(msg)\n}\n\nfunc Info(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Info(msg)\n}\n\nfunc Warn(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Warning(msg)\n}\n\nfunc Error(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Error(msg)\n}\n\nfunc Fatal(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Fatal(msg)\n}\n\nfunc Panic(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Panic(msg)\n}\n\nfunc (d DebugFields) Convert() map[string]interface{} ", "output": "{\n\treturn map[string]interface{}{}\n}"} {"input": "package serial\n\nimport (\n\t\"flag\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"golang.org/x/net/context\"\n)\n\ntype connect struct {\n\t*flags.VirtualMachineFlag\n\n\tdevice string\n\tclient bool\n}\n\nfunc init() {\n\tcli.Register(\"device.serial.connect\", &connect{})\n}\n\nfunc (cmd *connect) Register(f *flag.FlagSet) {\n\tf.StringVar(&cmd.device, \"device\", \"\", \"serial port device name\")\n\tf.BoolVar(&cmd.client, \"client\", false, \"Use client direction\")\n}\n\n\n\nfunc (cmd *connect) Run(f *flag.FlagSet) error {\n\tvm, err := cmd.VirtualMachine()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif vm == nil {\n\t\treturn flag.ErrHelp\n\t}\n\n\tdevices, err := vm.Device(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td, err := devices.FindSerialPort(cmd.device)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn vm.EditDevice(context.TODO(), devices.ConnectSerialPort(d, f.Arg(0), cmd.client))\n}\n\nfunc (cmd *connect) Process() error ", "output": "{ return nil }"} {"input": "package pflag\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype boolValue bool\n\nfunc newBoolValue(val bool, p *bool) *boolValue {\n\t*p = val\n\treturn (*boolValue)(p)\n}\n\n\n\nfunc (b *boolValue) String() string { return fmt.Sprintf(\"%v\", *b) }\n\n\n\nfunc (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tf.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc BoolVar(p *bool, name string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, \"\", usage)\n}\n\n\nfunc BoolVarP(p *bool, name, shorthand string, value bool, usage string) {\n\tCommandLine.VarP(newBoolValue(value, p), name, shorthand, usage)\n}\n\n\n\nfunc (f *FlagSet) Bool(name string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, \"\", value, usage)\n\treturn p\n}\n\n\nfunc (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {\n\tp := new(bool)\n\tf.BoolVarP(p, name, shorthand, value, usage)\n\treturn p\n}\n\n\n\nfunc Bool(name string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, \"\", value, usage)\n}\n\n\nfunc BoolP(name, shorthand string, value bool, usage string) *bool {\n\treturn CommandLine.BoolP(name, shorthand, value, usage)\n}\n\nfunc (b *boolValue) Set(s string) error ", "output": "{\n\tv, err := strconv.ParseBool(s)\n\t*b = boolValue(v)\n\treturn err\n}"} {"input": "package gumble\n\nimport (\n\t\"github.com/unascribed/gumble/gumble/MumbleProto\"\n)\n\n\ntype RegisteredUser struct {\n\tUserID uint32\n\tName string\n\n\tchanged bool\n\tderegister bool\n}\n\n\nfunc (ru *RegisteredUser) SetName(name string) {\n\tru.Name = name\n\tru.changed = true\n}\n\n\nfunc (ru *RegisteredUser) Deregister() {\n\tru.deregister = true\n}\n\n\n\nfunc (ru *RegisteredUser) Register() {\n\tru.deregister = false\n}\n\n\n\n\n\n\n\n\ntype RegisteredUsers []*RegisteredUser\n\nfunc (pm RegisteredUsers) writeMessage(client *Client) error {\n\tpacket := MumbleProto.UserList{}\n\n\tfor _, user := range pm {\n\t\tif user.deregister || user.changed {\n\t\t\tuserListUser := &MumbleProto.UserList_User{\n\t\t\t\tUserId: &user.UserID,\n\t\t\t}\n\t\t\tif !user.deregister {\n\t\t\t\tuserListUser.Name = &user.Name\n\t\t\t}\n\t\t\tpacket.Users = append(packet.Users, userListUser)\n\t\t}\n\t}\n\n\tif len(packet.Users) <= 0 {\n\t\treturn nil\n\t}\n\tproto := protoMessage{&packet}\n\treturn proto.writeMessage(client)\n}\n\nfunc (ru *RegisteredUser) ACLUser() *ACLUser ", "output": "{\n\treturn &ACLUser{\n\t\tUserID: ru.UserID,\n\t\tName: ru.Name,\n\t}\n}"} {"input": "package main\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"syscall\"\n\t\"unsafe\"\n)\n\n\n\n\n\n\nfunc safeErr(err error) uintptr {\n\treturn uintptr(err.(syscall.Errno))\n}\n\nfunc main() {\n\tnum := uintptr(16)\n\terrn := syscall.Errno(num)\n\terr := error(errn)\n\n\tfmt.Println(\"Num:\", num)\n\tfmt.Println(\"Errno:\", errn)\n\tfmt.Println(\"Error:\", err)\n\n\tfmt.Println(\"Unsafe way:\", unsafeErr(err))\n\tfmt.Println(\"Safe way:\", safeErr(err))\n}\n\nfunc unsafeErr(err error) uintptr ", "output": "{\n\tif err != nil {\n\t\tp1 := (uintptr)(unsafe.Pointer(&err))\n\t\tp2 := (*uintptr)(unsafe.Pointer(p1+8))\n\t\treturn *(*uintptr)(unsafe.Pointer(*p2))\n\t} else {\n\t\treturn 0\n\t}\n}"} {"input": "package transport\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\ntype Config struct {\n\tUserAgent string\n\n\tTLS TLSConfig\n\n\tUsername string\n\tPassword string\n\n\tBearerToken string\n\n\tBearerTokenFile string\n\n\tImpersonate ImpersonationConfig\n\n\tDisableCompression bool\n\n\tTransport http.RoundTripper\n\n\tWrapTransport WrapperFunc\n\n\tDial func(ctx context.Context, network, address string) (net.Conn, error)\n\n\tProxy func(*http.Request) (*url.URL, error)\n}\n\n\ntype ImpersonationConfig struct {\n\tUserName string\n\tGroups []string\n\tExtra map[string][]string\n}\n\n\n\n\n\nfunc (c *Config) HasBasicAuth() bool {\n\treturn len(c.Username) != 0\n}\n\n\nfunc (c *Config) HasTokenAuth() bool {\n\treturn len(c.BearerToken) != 0 || len(c.BearerTokenFile) != 0\n}\n\n\nfunc (c *Config) HasCertAuth() bool {\n\treturn (len(c.TLS.CertData) != 0 || len(c.TLS.CertFile) != 0) && (len(c.TLS.KeyData) != 0 || len(c.TLS.KeyFile) != 0)\n}\n\n\nfunc (c *Config) HasCertCallback() bool {\n\treturn c.TLS.GetCert != nil\n}\n\n\n\n\n\nfunc (c *Config) Wrap(fn WrapperFunc) {\n\tc.WrapTransport = Wrappers(c.WrapTransport, fn)\n}\n\n\ntype TLSConfig struct {\n\tCAFile string \n\tCertFile string \n\tKeyFile string \n\tReloadTLSFiles bool \n\n\tInsecure bool \n\tServerName string \n\n\tCAData []byte \n\tCertData []byte \n\tKeyData []byte \n\n\tNextProtos []string\n\n\tGetCert func() (*tls.Certificate, error) \n}\n\nfunc (c *Config) HasCA() bool ", "output": "{\n\treturn len(c.TLS.CAData) > 0 || len(c.TLS.CAFile) > 0\n}"} {"input": "package outputs\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/lfkeitel/spartan/event\"\n\n\ttomb \"gopkg.in/tomb.v2\"\n)\n\n\n\n\ntype OutputController struct {\n\tstart Output\n\tbatchSize int\n\tt tomb.Tomb\n\tin <-chan *event.Event\n\tout chan<- *event.Event\n}\n\n\n\n\n\n\n\n\nfunc (o *OutputController) Start(in chan *event.Event) error {\n\to.in = in\n\to.t.Go(o.run)\n\treturn nil\n}\n\n\n\n\nfunc (o *OutputController) Close() error {\n\to.t.Kill(nil)\n\treturn o.t.Wait()\n}\n\nfunc (o *OutputController) run() error {\n\tfmt.Println(\"Output Pipeline started\")\n\tfor {\n\t\tselect {\n\t\tcase <-o.t.Dying():\n\t\t\treturn nil\n\t\tdefault:\n\t\t}\n\n\t\tcurrentBatch := 0\n\t\tbatch := make([]*event.Event, o.batchSize)\n\t\tstopping := false\n\n\tCURRENT:\n\t\tfor currentBatch < o.batchSize {\n\t\t\tselect {\n\t\t\tcase event := <-o.in:\n\t\t\t\tbatch[currentBatch] = event\n\t\t\t\tcurrentBatch++\n\t\t\tcase <-o.t.Dying():\n\t\t\t\tstopping = true\n\t\t\t\tbreak CURRENT\n\t\t\t}\n\t\t}\n\n\t\tfmt.Println(\"Processing batch\")\n\t\to.start.Run(batch)\n\n\t\tif stopping {\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\n\nfunc checkOptionsMap(o map[string]interface{}) map[string]interface{} {\n\tif o == nil {\n\t\to = make(map[string]interface{})\n\t}\n\treturn o\n}\n\nfunc NewOutputController(start Output, batchSize int) *OutputController ", "output": "{\n\treturn &OutputController{\n\t\tstart: start,\n\t\tbatchSize: batchSize,\n\t}\n}"} {"input": "package command_runner\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/starkandwayne/cf-cli/cf/command_factory\"\n\t\"github.com/starkandwayne/cf-cli/cf/requirements\"\n\t\"github.com/codegangsta/cli\"\n\t\"os\"\n)\n\ntype Runner interface {\n\tRunCmdByName(cmdName string, c *cli.Context) (err error)\n}\n\ntype ConcreteRunner struct {\n\tcmdFactory command_factory.Factory\n\trequirementsFactory requirements.Factory\n}\n\n\n\nfunc (runner ConcreteRunner) RunCmdByName(cmdName string, c *cli.Context) (err error) {\n\tcmd, err := runner.cmdFactory.GetByCmdName(cmdName)\n\tif err != nil {\n\t\tfmt.Printf(\"Error finding command %s\\n\", cmdName)\n\t\tos.Exit(1)\n\t\treturn\n\t}\n\n\trequirements, err := cmd.GetRequirements(runner.requirementsFactory, c)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, requirement := range requirements {\n\t\tsuccess := requirement.Execute()\n\t\tif !success {\n\t\t\terr = errors.New(\"Error in requirement\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tcmd.Run(c)\n\treturn\n}\n\nfunc NewRunner(cmdFactory command_factory.Factory, requirementsFactory requirements.Factory) (runner ConcreteRunner) ", "output": "{\n\trunner.cmdFactory = cmdFactory\n\trunner.requirementsFactory = requirementsFactory\n\treturn\n}"} {"input": "package aes_test\n\nimport (\n\t\"github.com/keep94/vsafe/aes\"\n\t\"testing\"\n)\n\nvar (\n\tsomeKey = []byte(\"12345678901234567890123456789012\")\n)\n\nfunc TestEncryptDecrypt(t *testing.T) {\n\tverifyEncryptDecrypt(t, \"aardvark\")\n\tverifyEncryptDecrypt(t, \"1234567890123456\")\n\tverifyEncryptDecrypt(t, \"1234567890123456 \")\n\tverifyEncryptDecrypt(t, \"123456789012345 \")\n\tverifyEncryptDecrypt(t, \" now is the time for all good men to come to the aid of their party \")\n}\n\nfunc TestEncryptsSameTextDifferently(t *testing.T) {\n\tencoded, err := aes.Encrypt(\"aardvark\", someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tencodedAgain, err := aes.Encrypt(\"aardvark\", someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif encoded == encodedAgain {\n\t\tt.Error(\"Expected same text to be encrypted differently every time.\")\n\t}\n}\n\nfunc TestEncryptSecurity(t *testing.T) {\n\tanotherKey := []byte(\"12345678901234567890123456789013\")\n\tencoded, err := aes.Encrypt(\"aardvark\", someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdecoded, _ := aes.Decrypt(encoded, anotherKey)\n\tif decoded == \"aardvark\" {\n\t\tt.Error(\"Expected different decryption with different key\")\n\t}\n}\n\n\n\nfunc verifyEncryptDecrypt(t *testing.T, plain string) ", "output": "{\n\tencoded, err := aes.Encrypt(plain, someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdecoded, err := aes.Decrypt(encoded, someKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif decoded != plain {\n\t\tt.Errorf(\"Expected to get same thing back: '%s', got '%s' %d %d\", plain, decoded, len(plain), len(decoded))\n\t}\n}"} {"input": "package http\n\nimport (\n\t\"net/http\"\n\n\tpresenterusecase \"github.com/arielizuardi/ezra/presenter/usecase\"\n\t\"github.com/labstack/echo\"\n)\n\n\ntype ResponseError struct {\n\tMessage string `json:\"error\"`\n}\n\ntype PresenterHTTPHandler struct {\n\tPresenterUsecase presenterusecase.PresenterUsecase\n}\n\n\n\nfunc Init(e *echo.Echo, p presenterusecase.PresenterUsecase) {\n\th := &PresenterHTTPHandler{p}\n\te.GET(`/presenter`, h.HandleFetchAllPresenters)\n}\n\nfunc (h *PresenterHTTPHandler) HandleFetchAllPresenters(c echo.Context) error ", "output": "{\n\tpresenters, err := h.PresenterUsecase.FetchAllPresenters()\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, &ResponseError{err.Error()})\n\t}\n\n\treturn c.JSON(http.StatusOK, presenters)\n}"} {"input": "package collector\n\nimport (\n\t\"fullerite/metric\"\n\t\"math/rand\"\n)\n\n\ntype Test struct {\n\tinterval int\n\tchannel chan metric.Metric\n}\n\n\nfunc NewTest() *Test {\n\tt := new(Test)\n\tt.channel = make(chan metric.Metric)\n\treturn t\n}\n\n\nfunc (t Test) Collect() {\n\tmetric := metric.New(\"TestMetric\")\n\tmetric.Value = rand.Float64()\n\tmetric.AddDimension(\"testing\", \"yes\")\n\tt.Channel() <- metric\n}\n\n\nfunc (t Test) Name() string {\n\treturn \"Test\"\n}\n\n\n\n\n\n\nfunc (t Test) Channel() chan metric.Metric {\n\treturn t.channel\n}\n\n\nfunc (t Test) String() string {\n\treturn t.Name() + \"Collector\"\n}\n\n\nfunc (t *Test) SetInterval(interval int) {\n\tt.interval = interval\n}\n\nfunc (t Test) Interval() int ", "output": "{\n\treturn t.interval\n}"} {"input": "package strain\n\ntype Ints []int\ntype Lists [][]int\ntype Strings []string\n\n\n\nfunc (i Ints) Discard(filter func(int) bool) Ints {\n\tif i == nil {\n\t\treturn nil\n\t}\n\treturn i.Keep(func(i int) bool {\n\t\treturn !filter(i)\n\t})\n}\n\nfunc (l Lists) Keep(filter func([]int) bool) Lists {\n\tif l == nil {\n\t\treturn nil\n\t}\n\tfiltered := [][]int{}\n\tfor _, v := range l {\n\t\tif filter(v) {\n\t\t\tfiltered = append(filtered, v)\n\t\t}\n\t}\n\tl = filtered\n\treturn l\n}\n\nfunc (s Strings) Keep(filter func(string) bool) Strings {\n\tif s == nil {\n\t\treturn nil\n\t}\n\tfiltered := []string{}\n\tfor _, v := range s {\n\t\tif filter(v) {\n\t\t\tfiltered = append(filtered, v)\n\t\t}\n\t}\n\ts = filtered\n\treturn s\n}\n\nfunc (i Ints) Keep(filter func(int) bool) Ints ", "output": "{\n\tif i == nil {\n\t\treturn nil\n\t}\n\tfiltered := []int{}\n\tfor _, v := range i {\n\t\tif filter(v) {\n\t\t\tfiltered = append(filtered, v)\n\t\t}\n\t}\n\ti = filtered\n\treturn i\n}"} {"input": "package proj\n\nconst (\n\tutmLetters = \"CDEFGHJKLMNPQRSTUVWXX\"\n)\n\nvar (\n\tUTMZones = map[int]*TransverseMercator{}\n)\n\n\nfunc utmZone(zone int) *TransverseMercator {\n\treturn &TransverseMercator{\n\t\tcode: 32600 + zone,\n\t\tf0: 0.9996,\n\t\tlat0: rad(0),\n\t\tlon0: rad(6*(30-float64(zone)) + 3),\n\t\te0: 500000,\n\t\tn0: 0,\n\t\te: International1924,\n\t}\n}\n\n\nfunc LatLongUTMZone(lat, lon float64) int {\n\tswitch {\n\tcase 56 <= lat && lat < 64 && 3 <= lon && lon < 12:\n\t\treturn 32\n\tcase 72 <= lat && lat < 84 && 0 <= lon && lon < 42:\n\t\tswitch {\n\t\tcase lon < 9:\n\t\t\treturn 31\n\t\tcase lon < 21:\n\t\t\treturn 33\n\t\tcase lon < 33:\n\t\t\treturn 35\n\t\tdefault:\n\t\t\treturn 37\n\t\t}\n\tdefault:\n\t\treturn int(lon+180)/6 + 1\n\t}\n}\n\n\nfunc LatLongUTMLetter(lat, lon float64) byte {\n\tif lat < -80 || 84 <= lat {\n\t\treturn 0\n\t}\n\ti := int((lat + 80) / 8)\n\treturn utmLetters[i]\n}\n\n\n\nfunc initUTM() ", "output": "{\n\tfor z := 1; z <= 60; z++ {\n\t\tUTMZones[z] = utmZone(z)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n)\n\n\ntype Address struct {\n\tStreet, City string\n}\n\ntype Person struct {\n\tFirstName, LastName string\n}\n\ntype T1 string\ntype T2 string\ntype T3 string\n\nvar logger *log.Logger\n\nfunc main() {\n\tmyAddress := Address{\n\t\tStreet: \"Trimveien 6\",\n\t\tCity: \"Oslo\",\n\t}\n\tlog.Println(myAddress)\n\n\tme := Person{\n\t\tFirstName: \"Christian\",\n\t\tLastName: \"Bergum Bergersen\",\n\t}\n\tlog.Println(me)\n\n\tvar foo T1\n\tfoo = \"foo\"\n\tlog.Println(foo)\n\n\tvar bar T3\n\tbar = \"bar\"\n\tlog.Println(bar)\n}\n\n\n\n\n\nfunc (person Person) String() string {\n\treturn fmt.Sprintf(\"%s %s\", person.FirstName, person.LastName)\n}\n\n\nfunc (t1 T1) String() string {\n\treturn fmt.Sprint(t1)\n}\n\n\nfunc (t2 T2) String() string {\n\tlog.Print(\"Calling String() for : %v\", t2)\n\treturn fmt.Sprintln(t2)\n}\n\n\nfunc (bar T3) String() string {\n\tvar buf bytes.Buffer\n\tlogger = log.New(&buf, \"logger: \", log.Lshortfile)\n\tlogger.Printf(\"Calling String() for %+v\", bar)\n\treturn fmt.Sprintf(\"Bar\")\n}\n\nfunc (address Address) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%s\", address)\n}"} {"input": "package sftp\n\n\n\n\nimport \"os\"\n\n\n\ntype FileOpenFlags struct {\n\tRead, Write, Append, Creat, Trunc, Excl bool\n}\n\nfunc newFileOpenFlags(flags uint32) FileOpenFlags {\n\treturn FileOpenFlags{\n\t\tRead: flags&ssh_FXF_READ != 0,\n\t\tWrite: flags&ssh_FXF_WRITE != 0,\n\t\tAppend: flags&ssh_FXF_APPEND != 0,\n\t\tCreat: flags&ssh_FXF_CREAT != 0,\n\t\tTrunc: flags&ssh_FXF_TRUNC != 0,\n\t\tExcl: flags&ssh_FXF_EXCL != 0,\n\t}\n}\n\n\n\n\n\n\n\n\ntype FileAttrFlags struct {\n\tSize, UidGid, Permissions, Acmodtime bool\n}\n\nfunc newFileAttrFlags(flags uint32) FileAttrFlags {\n\treturn FileAttrFlags{\n\t\tSize: (flags & ssh_FILEXFER_ATTR_SIZE) != 0,\n\t\tUidGid: (flags & ssh_FILEXFER_ATTR_UIDGID) != 0,\n\t\tPermissions: (flags & ssh_FILEXFER_ATTR_PERMISSIONS) != 0,\n\t\tAcmodtime: (flags & ssh_FILEXFER_ATTR_ACMODTIME) != 0,\n\t}\n}\n\n\n\nfunc (r *Request) AttrFlags() FileAttrFlags {\n\treturn newFileAttrFlags(r.Flags)\n}\n\n\nfunc (a FileStat) FileMode() os.FileMode {\n\treturn os.FileMode(a.Mode)\n}\n\n\n\nfunc (r *Request) Attributes() *FileStat {\n\tfs, _ := getFileStat(r.Flags, r.Attrs)\n\treturn fs\n}\n\nfunc (r *Request) Pflags() FileOpenFlags ", "output": "{\n\treturn newFileOpenFlags(r.Flags)\n}"} {"input": "package goics\n\n\n\nfunc splitLength(s string, length int) []string {\n\tvar ret []string\n\n\tfor len(s) > 0 {\n\t\ttmp := truncateString(s, length)\n\t\tif len(tmp) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tret = append(ret, tmp)\n\t\ts = s[len(tmp):]\n\t}\n\n\treturn ret\n}\n\n\n\n\nfunc truncateString(s string, length int) string ", "output": "{\n\tif len(s) <= length {\n\t\treturn s\n\t}\n\n\tcutoff := length\n\tfor s[cutoff]&0xc0 == 0x80 {\n\t\tcutoff--\n\t\tif cutoff < 0 {\n\t\t\tcutoff = 0\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn s[0:cutoff]\n}"} {"input": "package main\n\nimport (\n\t\"github.com/trasa/watchmud-message\"\n)\n\nfunc (c *Client) handleSayResponse(resp *message.SayResponse) {\n\tif resp.Success {\n\t\tUIPrintf(\"You say '%s'\\n\", resp.Value)\n\t} else {\n\t\tif resp.GetResultCode() == \"NOT_IN_A_ROOM\" {\n\t\t\tUIPrintln(\"You yell into the darkness.\")\n\t\t} else {\n\t\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t\t}\n\t}\n}\n\nfunc (c *Client) handleSayNotification(note *message.SayNotification) {\n\tif note.Success {\n\t\tUIPrintf(\"%s says '%s'.\\n\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}\n\n\n\nfunc (c *Client) handleTellResponse(resp *message.TellResponse) {\n\tif resp.GetSuccess() {\n\t\tUIPrintln(\"sent.\")\n\t} else if resp.GetResultCode() == \"TO_PLAYER_NOT_FOUND\" {\n\t\tUIPrintln(\"Nobody here by that name.\")\n\t} else {\n\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellAllResponse(resp *message.TellAllResponse) {\n\tif resp.GetSuccess() {\n\t\tUIPrintln(\"sent.\")\n\t} else {\n\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellAllNotification(note *message.TellAllNotification) {\n\tif note.GetSuccess() {\n\t\tUIPrintf(\"tell_all %s> %s\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellNotification(note *message.TellNotification) ", "output": "{\n\tif note.GetSuccess() {\n\t\tUIPrintf(\"%s tells you '%s'.\\n\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}"} {"input": "package cmd\n\nimport (\n\t\"errors\"\n\n\tboshdir \"github.com/cloudfoundry/bosh-init/director\"\n\tboshui \"github.com/cloudfoundry/bosh-init/ui\"\n\tboshtbl \"github.com/cloudfoundry/bosh-init/ui/table\"\n)\n\ntype DisksCmd struct {\n\tui boshui.UI\n\tdirector boshdir.Director\n}\n\n\n\nfunc (c DisksCmd) Run(opts DisksOpts) error {\n\tif !opts.Orphaned {\n\t\treturn errors.New(\"Only --orphaned is supported\")\n\t}\n\n\tdisks, err := c.director.OrphanedDisks()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttable := boshtbl.Table{\n\t\tContent: \"disks\",\n\t\tHeader: []string{\"Disk CID\", \"Size\", \"Deployment\", \"Instance\", \"AZ\", \"Orphaned At\"},\n\t\tSortBy: []boshtbl.ColumnSort{{Column: 5}},\n\t}\n\n\tfor _, d := range disks {\n\t\ttable.Rows = append(table.Rows, []boshtbl.Value{\n\t\t\tboshtbl.NewValueString(d.CID()),\n\t\t\tboshtbl.NewValueBytes(d.Size()),\n\t\t\tboshtbl.NewValueString(d.Deployment().Name()),\n\t\t\tboshtbl.NewValueString(d.InstanceName()),\n\t\t\tboshtbl.NewValueString(d.AZName()),\n\t\t\tboshtbl.NewValueTime(d.OrphanedAt()),\n\t\t})\n\t}\n\n\tc.ui.PrintTable(table)\n\n\treturn nil\n}\n\nfunc NewDisksCmd(ui boshui.UI, director boshdir.Director) DisksCmd ", "output": "{\n\treturn DisksCmd{ui: ui, director: director}\n}"} {"input": "package util\n\nconst (\n\tDefaultPerPage = 20\n)\n\n\n\nfunc (p *Pagination) SimplePage() (from int64, to int64) {\n\tif p.CurPage == 0 || p.PerPage == 0 {\n\t\tp.CurPage, p.PerPage = 1, DefaultPerPage\n\t}\n\tfrom = (p.CurPage-1)*p.PerPage + 1\n\tto = from + p.PerPage - 1\n\treturn\n}\n\n\n\nfunc (p *Pagination) Page(total int64) (from int64, to int64) {\n\tif p.CurPage == 0 {\n\t\tp.CurPage = 1\n\t}\n\tif p.PerPage == 0 {\n\t\tp.PerPage = DefaultPerPage\n\t}\n\n\tif total == 0 || total < p.PerPage*(p.CurPage-1) {\n\t\treturn\n\t}\n\tif total <= p.PerPage {\n\t\treturn 1, total\n\t}\n\tfrom = (p.CurPage-1)*p.PerPage + 1\n\tif (total - from + 1) < p.PerPage {\n\t\treturn from, total\n\t}\n\treturn from, from + p.PerPage - 1\n}\n\n\n\n\n\nfunc (p *Pagination) OffsetLimit(total int64) (offset int64, limit int64) {\n\tfrom, to := p.Page(total)\n\tif to == 0 || from == 0 {\n\t\treturn 0, 0\n\t}\n\treturn from - 1, to - from + 1\n}\n\n\ntype Pagination struct {\n\tCurPage int64\n\tPerPage int64\n}\n\nfunc (p *Pagination) VagueOffsetLimit() (offset int64, limit int64) ", "output": "{\n\tfrom, to := p.SimplePage()\n\tif to == 0 || from == 0 {\n\t\treturn 0, 0\n\t}\n\treturn from - 1, to - from + 1\n}"} {"input": "package kms\n\nimport (\n\t\"os\"\n\n\t\"github.com/denverdino/aliyungo/common\"\n)\n\nconst (\n\tKMSDefaultEndpoint = \"https://kms.cn-hangzhou.aliyuncs.com\"\n\tKMSAPIVersion = \"2016-01-20\"\n\tKMSServiceCode = \"kms\"\n)\n\ntype Client struct {\n\tcommon.Client\n}\n\n\nfunc NewClient(accessKeyId, accessKeySecret string) *Client {\n\tendpoint := os.Getenv(\"KMS_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = KMSDefaultEndpoint\n\t}\n\treturn NewClientWithEndpoint(endpoint, accessKeyId, accessKeySecret)\n}\n\nfunc NewClientWithRegion(accessKeyId string, accessKeySecret string, regionID common.Region) *Client {\n\tendpoint := os.Getenv(\"KMS_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = KMSDefaultEndpoint\n\t}\n\tclient := &Client{}\n\tclient.NewInit(endpoint, KMSAPIVersion, accessKeyId, accessKeySecret, KMSServiceCode, regionID)\n\treturn client\n}\n\n\n\nfunc NewECSClientWithSecurityToken(accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client {\n\tendpoint := os.Getenv(\"KMS_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = KMSDefaultEndpoint\n\t}\n\n\treturn NewKMSClientWithEndpointAndSecurityToken(endpoint, accessKeyId, accessKeySecret, securityToken, regionID)\n}\n\nfunc NewKMSClientWithEndpointAndSecurityToken(endpoint string, accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client {\n\tclient := &Client{}\n\tclient.WithEndpoint(endpoint).\n\t\tWithVersion(KMSAPIVersion).\n\t\tWithAccessKeyId(accessKeyId).\n\t\tWithAccessKeySecret(accessKeySecret).\n\t\tWithSecurityToken(securityToken).\n\t\tWithServiceCode(KMSServiceCode).\n\t\tWithRegionID(regionID).\n\t\tInitClient()\n\treturn client\n}\n\nfunc NewClientWithEndpoint(endpoint string, accessKeyId string, accessKeySecret string) *Client ", "output": "{\n\tclient := &Client{}\n\tclient.Init(endpoint, KMSAPIVersion, accessKeyId, accessKeySecret)\n\treturn client\n}"} {"input": "package egl\n\n\nimport \"C\"\nimport \"unsafe\"\n\ntype (\n\tEnum uint32\n\tConfig uintptr\n\tContext uintptr\n\tDisplay uintptr\n\tSurface uintptr\n\tClientBuffer uintptr\n\tNativeDisplayType unsafe.Pointer\n\tNativeWindowType unsafe.Pointer\n\tNativePixmapType unsafe.Pointer\n)\n\n\nfunc eglBoolean(n bool) C.EGLBoolean {\n\tvar b int\n\tif n == true {\n\t\tb = 1\n\t}\n\treturn C.EGLBoolean(b)\n}\n\nfunc goBoolean(n C.EGLBoolean) bool ", "output": "{\n\treturn n == 1\n}"} {"input": "package reporting\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"strings\"\n)\n\ntype JsonReporter struct {\n\tout *Printer\n\tcurrent *ScopeResult\n\tindex map[string]*ScopeResult\n\tscopes []*ScopeResult\n\tdepth int\n}\n\nfunc (self *JsonReporter) BeginStory(story *StoryReport) {}\n\nfunc (self *JsonReporter) Enter(scope *ScopeReport) {\n\tif _, found := self.index[scope.ID]; !found {\n\t\tself.registerScope(scope)\n\t}\n\tself.current = self.index[scope.ID]\n\tself.depth++\n}\nfunc (self *JsonReporter) registerScope(scope *ScopeReport) {\n\tnext := newScopeResult(scope.Title, self.depth, scope.File, scope.Line)\n\tself.scopes = append(self.scopes, next)\n\tself.index[scope.ID] = next\n}\n\nfunc (self *JsonReporter) Report(report *AssertionResult) {\n\tself.current.Assertions = append(self.current.Assertions, report)\n}\n\nfunc (self *JsonReporter) Exit() {\n\tself.depth--\n}\n\nfunc (self *JsonReporter) EndStory() {\n\tself.report()\n\tself.reset()\n}\n\nfunc (self *JsonReporter) reset() {\n\tself.scopes = []*ScopeResult{}\n\tself.index = map[string]*ScopeResult{}\n\tself.depth = 0\n}\n\nfunc NewJsonReporter(out *Printer) *JsonReporter {\n\tself := new(JsonReporter)\n\tself.out = out\n\tself.reset()\n\treturn self\n}\n\nconst OpenJson = \">>>>>\" \nconst CloseJson = \"<<<<<\" \nconst jsonMarshalFailure = `\n\nGOCONVEY_JSON_MARSHALL_FAILURE: There was an error when attempting to convert test results to JSON.\nPlease file a bug report and reference the code that caused this failure if possible.\n\nHere's the panic:\n\n`\n\nfunc (self *JsonReporter) report() ", "output": "{\n\tself.out.Print(OpenJson + \"\\n\")\n\tscopes := []string{}\n\tfor _, scope := range self.scopes {\n\t\tserialized, err := json.Marshal(scope)\n\t\tif err != nil {\n\t\t\tself.out.Println(jsonMarshalFailure)\n\t\t\tpanic(err)\n\t\t}\n\t\tvar buffer bytes.Buffer\n\t\tjson.Indent(&buffer, serialized, \"\", \" \")\n\t\tscopes = append(scopes, buffer.String())\n\t}\n\tself.out.Print(strings.Join(scopes, \",\") + \",\\n\")\n\tself.out.Print(CloseJson + \"\\n\")\n}"} {"input": "package tool\n\nimport (\n\t\"log\"\n\t\"testing\"\n)\n\n\n\nfunc TestConf(t *testing.T) {\n\tlog.Println(Conf(\"addr\"))\n\tlog.Println(Conf(\"hello\"))\n}\n\nfunc TestExistFile(t *testing.T) ", "output": "{\n\tlog.Println(ExistFile(\"config.go\"))\n\tlog.Println(ExistFile(\"config\"))\n}"} {"input": "package computations\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"net/rpc/jsonrpc\"\n\t\"sync\"\n\n\t\"github.com/natefinch/pie\"\n\t\"github.com/nsaje/dagger/dagger\"\n)\n\n\ntype ComputationImplementation interface {\n\tGetInfo(definition string) (dagger.ComputationPluginInfo, error)\n\tSubmitRecord(t *dagger.Record) ([]*dagger.Record, error)\n\tGetState() ([]byte, error)\n\tSetState([]byte) error\n}\n\n\n\n\n\n\ntype ComputationPlugin struct {\n\timpl ComputationImplementation\n\tmx sync.RWMutex\n}\n\n\nfunc (p *ComputationPlugin) GetInfo(definition string, response *dagger.ComputationPluginInfo) error {\n\tp.mx.RLock()\n\tdefer p.mx.RUnlock()\n\tinfo, err := p.impl.GetInfo(definition)\n\t*response = info\n\treturn err\n}\n\n\nfunc (p *ComputationPlugin) SubmitRecord(t *dagger.Record,\n\tresponse *dagger.ComputationPluginResponse) error {\n\tp.mx.Lock()\n\tdefer p.mx.Unlock()\n\t*response = dagger.ComputationPluginResponse{}\n\tnewRecords, err := p.impl.SubmitRecord(t)\n\tresponse.Records = newRecords\n\treturn err\n}\n\n\nfunc (p *ComputationPlugin) GetState(_ struct{},\n\tresponse *[]byte) error {\n\tp.mx.RLock()\n\tdefer p.mx.RUnlock()\n\tstate, err := p.impl.GetState()\n\t*response = state\n\treturn err\n}\n\n\nfunc (p *ComputationPlugin) SetState(state []byte,\n\tresponse *string) error {\n\tp.mx.Lock()\n\tdefer p.mx.Unlock()\n\t*response = \"ok\"\n\terr := p.impl.SetState(state)\n\treturn err\n}\n\nfunc StartPlugin(impl ComputationImplementation) ", "output": "{\n\tprovider := pie.NewProvider()\n\tcomputationPlugin := &ComputationPlugin{impl, sync.RWMutex{}}\n\tif err := provider.RegisterName(\"Computation\", computationPlugin); err != nil {\n\t\tlog.Fatalf(\"failed to register computation Plugin: %s\", err)\n\t}\n\tprovider.ServeCodec(jsonrpc.NewServerCodec)\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/signal\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n)\n\ntype threadSafePrintliner struct {\n\tl sync.Mutex\n\tw io.Writer\n}\n\nfunc newThreadSafePrintliner(w io.Writer) *threadSafePrintliner {\n\treturn &threadSafePrintliner{w: w}\n}\n\n\n\nfunc readQuery(r io.Reader) string {\n\ts, _ := ioutil.ReadAll(r) \n\treturn strings.TrimSpace(strings.Replace(string(s), \"\\n\", \" \", -1))\n}\n\nfunc trimEmpty(s []string) []string {\n\tvar r = make([]string, 0)\n\tfor _, str := range s {\n\t\tif str != \"\" {\n\t\t\tr = append(r, str)\n\t\t}\n\t}\n\treturn r\n}\n\nfunc awaitSignal(cancel context.CancelFunc) {\n\tsignals := make(chan os.Signal)\n\tsignal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)\n\t<-signals\n\tcancel()\n}\n\nfunc (p *threadSafePrintliner) println(s string) ", "output": "{\n\tp.l.Lock()\n\tfmt.Fprintln(p.w, s)\n\tp.l.Unlock()\n}"} {"input": "package models\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/dchest/uniuri\"\n\t\"github.com/koding/bongo\"\n\t\"github.com/stvp/slug\"\n)\n\n\nfunc Slugify(message *ChannelMessage) (*ChannelMessage, error) {\n\n\tif message.TypeConstant != ChannelMessage_TYPE_POST {\n\t\treturn message, nil\n\t}\n\n\tslug.Replacement = '-'\n\tres := NewChannelMessage()\n\n\tsuggestedSlug := slug.Clean(message.Body)\n\tif len(suggestedSlug) > 80 {\n\t\tsuggestedSlug = suggestedSlug[:79]\n\t}\n\n\tquery := map[string]interface{}{\n\t\t\"slug\": suggestedSlug,\n\t}\n\n\trand.Seed(time.Now().UnixNano())\n\n\tfor tryCount := 0; tryCount < 10; tryCount++ {\n\t\tif err := res.One(bongo.NewQS(query)); err != nil {\n\t\t\tif err != bongo.RecordNotFound {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tmessage.Slug = suggestedSlug\n\t\t\treturn message, nil\n\t\t}\n\t\tsuggestedSlug = suggestedSlug + \"-\" + strconv.Itoa(rand.Intn(1000000000))\n\t\tquery[\"slug\"] = suggestedSlug\n\t}\n\n\treturn nil, fmt.Errorf(\"couldnt generate unique slug:%s\", message.Slug)\n}\n\nfunc RandomName() string {\n\treturn uniuri.New()\n}\n\nfunc RandomGroupName() string {\n\trand.Seed(time.Now().UnixNano())\n\treturn \"group\" + strconv.FormatInt(rand.Int63(), 10)\n}\n\n\n\nfunc ZeroDate() time.Time ", "output": "{\n\treturn time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC)\n}"} {"input": "package cpf\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\nfunc Valid(digits string) (bool, error) {\n\treturn valid(digits)\n}\n\nfunc sanitize(data string) string {\n\tdata = strings.Replace(data, \".\", \"\", -1)\n\tdata = strings.Replace(data, \"-\", \"\", -1)\n\treturn data\n}\n\nfunc valid(data string) (bool, error) {\n\tdata = sanitize(data)\n\n\tif len(data) != 11 {\n\t\treturn false, errors.New(\"Invalid length\")\n\t}\n\n\tif strings.Contains(blacklist, data) || !check(data) {\n\t\treturn false, errors.New(\"Invalid value\")\n\t}\n\n\treturn true, nil\n}\n\nconst blacklist = `00000000000\n11111111111\n22222222222\n33333333333\n44444444444\n55555555555\n66666666666\n77777777777\n88888888888\n99999999999\n12345678909`\n\nfunc stringToIntSlice(data string) (res []int) {\n\tfor _, d := range data {\n\t\tx, err := strconv.Atoi(string(d))\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, x)\n\t}\n\treturn\n}\n\nfunc verify(data []int, n int) int {\n\tvar total int\n\n\tfor i := 0; i < n; i++ {\n\t\ttotal += data[i] * (n + 1 - i)\n\t}\n\n\ttotal = total % 11\n\tif total < 2 {\n\t\treturn 0\n\t}\n\treturn 11 - total\n}\n\n\n\nfunc checkEach(data string, n int) bool {\n\tfinal := verify(stringToIntSlice(data), n)\n\n\tx, err := strconv.Atoi(string(data[n]))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn final == x\n}\n\nfunc check(data string) bool ", "output": "{\n\treturn checkEach(data, 9) && checkEach(data, 10)\n}"} {"input": "package main\n\ntype Move struct {\n\tSrc Point\n\tDest Point\n}\n\nvar EmptyMove = Move{Point{0, 0}, Point{0, 0}}\n\nfunc NewMove(src Point, dest Point) Move {\n\ts, d := src, dest\n\tif s.X > d.X {\n\t\ts.X, d.X = d.X, s.X\n\t}\n\tif s.Y > d.Y {\n\t\ts.Y, d.Y = d.Y, s.Y\n\t}\n\n\treturn Move{src, dest}\n}\n\nfunc (m Move) String() string {\n\treturn m.Src.String() + \">\" + m.Dest.String()\n}\n\n\n\nfunc (m Move) Apply(t Table) {\n\tdist := m.Src.DistanceTo(m.Dest) + 1\n\tdist /= 2\n\n\tif m.Src.X == m.Dest.X {\n\t\tfor i := 0; i < dist; i++ {\n\t\t\tt.SwapY(m.Src.X, m.Src.Y+i, m.Dest.Y-i)\n\t\t}\n\n\t} else if m.Src.Y == m.Dest.Y {\n\t\tfor i := 0; i < dist; i++ {\n\t\t\tt.SwapX(m.Src.Y, m.Src.X+i, m.Dest.X-i)\n\t\t}\n\n\t} else {\n\t\tpanic(\"Diagonal move is not supported!\")\n\t}\n\n\n\n\tfor t.Resolve() > 0 {\n\t}\n}\n\nfunc (m Move) Valid(table Table) bool ", "output": "{\n\tfor x := m.Src.X; x <= m.Dest.X; x++ {\n\t\tfor y := m.Src.Y; y <= m.Dest.Y; y++ {\n\t\t\tcell := table[y][x]\n\t\t\tswitch cell {\n\t\t\tcase HOLLOW, LAND:\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}"} {"input": "package iso\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/hashicorp/packer-plugin-sdk/multistep\"\n\tpackersdk \"github.com/hashicorp/packer-plugin-sdk/packer\"\n\tparallelscommon \"github.com/hashicorp/packer/builder/parallels/common\"\n)\n\n\n\n\n\n\n\n\n\n\n\ntype stepAttachISO struct{}\n\nfunc (s *stepAttachISO) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {\n\tdriver := state.Get(\"driver\").(parallelscommon.Driver)\n\tisoPath := state.Get(\"iso_path\").(string)\n\tui := state.Get(\"ui\").(packersdk.Ui)\n\tvmName := state.Get(\"vmName\").(string)\n\n\tui.Say(\"Attaching ISO to the default CD/DVD ROM device...\")\n\tcommand := []string{\n\t\t\"set\", vmName,\n\t\t\"--device-set\", \"cdrom0\",\n\t\t\"--image\", isoPath,\n\t\t\"--enable\", \"--connect\",\n\t}\n\tif err := driver.Prlctl(command...); err != nil {\n\t\terr := fmt.Errorf(\"Error attaching ISO: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\tstate.Put(\"attachedIso\", true)\n\n\treturn multistep.ActionContinue\n}\n\n\n\nfunc (s *stepAttachISO) Cleanup(state multistep.StateBag) ", "output": "{\n\tif _, ok := state.GetOk(\"attachedIso\"); !ok {\n\t\treturn\n\t}\n\n\tdriver := state.Get(\"driver\").(parallelscommon.Driver)\n\tui := state.Get(\"ui\").(packersdk.Ui)\n\tvmName := state.Get(\"vmName\").(string)\n\n\tlog.Println(\"Detaching ISO from the default CD/DVD ROM device...\")\n\tcommand := []string{\n\t\t\"set\", vmName,\n\t\t\"--device-set\", \"cdrom0\",\n\t\t\"--image\", \"\", \"--disconnect\", \"--enable\",\n\t}\n\n\tif err := driver.Prlctl(command...); err != nil {\n\t\tui.Error(fmt.Sprintf(\"Error detaching ISO: %s\", err))\n\t}\n}"} {"input": "package no\n\nimport (\n\t\"github.com/blevesearch/bleve/analysis\"\n\t\"github.com/blevesearch/bleve/analysis/token_filters/stemmer_filter\"\n\t\"github.com/blevesearch/bleve/registry\"\n)\n\nconst StemmerName = \"stemmer_no\"\n\nfunc StemmerFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) {\n\treturn stemmer_filter.NewStemmerFilter(\"no\")\n}\n\n\n\nfunc init() ", "output": "{\n\tregistry.RegisterTokenFilter(StemmerName, StemmerFilterConstructor)\n}"} {"input": "package handler\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"net/http\"\n)\n\n\n\n\n\nfunc Ping(c *gin.Context) {\n\tc.String(http.StatusOK, \"pong\")\n}\n\nfunc Index(c *gin.Context) ", "output": "{\n\tc.String(http.StatusOK, \"welcome 2 banerwai api\")\n}"} {"input": "package libsnnet\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\n\n\n\n\n\n\n\nfunc TestBridge_Basic(t *testing.T) {\n\tassert := assert.New(t)\n\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge.create())\n\n\tbridge1, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge1.getDevice())\n\tperformBridgeOps(true, assert, bridge)\n\n\tassert.NotNil(bridge.destroy())\n\n}\n\n\n\n\n\n\n\nfunc TestBridge_Dup(t *testing.T) {\n\tassert := assert.New(t)\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge.create())\n\tdefer func() { _ = bridge.destroy() }()\n\n\tbridge1, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\tassert.NotNil(bridge1.create())\n}\n\n\n\n\n\n\n\nfunc TestBridge_Invalid(t *testing.T) {\n\tassert := assert.New(t)\n\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.NotNil(bridge.getDevice())\n\n\tperformBridgeOps(false, assert, bridge)\n}\n\n\n\n\n\n\n\nfunc TestBridge_GetDevice(t *testing.T) {\n\tassert := assert.New(t)\n\tbridge, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge.create())\n\n\tbridge1, err := newBridge(\"go_testbr\")\n\tassert.Nil(err)\n\n\tassert.Nil(bridge1.getDevice())\n\tperformBridgeOps(true, assert, bridge1)\n}\n\nfunc performBridgeOps(shouldPass bool, assert *assert.Assertions, bridge *Bridge) ", "output": "{\n\ta := assert.Nil\n\tif !shouldPass {\n\t\ta = assert.NotNil\n\t}\n\ta(bridge.enable())\n\ta(bridge.disable())\n\ta(bridge.destroy())\n}"} {"input": "package iso20022\n\n\ntype FundSettlementParameters3 struct {\n\n\tSettlementDate *ISODate `xml:\"SttlmDt,omitempty\"`\n\n\tSettlementPlace *PartyIdentification2Choice `xml:\"SttlmPlc\"`\n\n\tSafekeepingPlace *PartyIdentification2Choice `xml:\"SfkpgPlc,omitempty\"`\n\n\tSecuritiesSettlementSystemIdentification *Max35Text `xml:\"SctiesSttlmSysId,omitempty\"`\n\n\tReceivingSideDetails *ReceivingPartiesAndAccount3 `xml:\"RcvgSdDtls,omitempty\"`\n\n\tDeliveringSideDetails *DeliveringPartiesAndAccount3 `xml:\"DlvrgSdDtls\"`\n}\n\nfunc (f *FundSettlementParameters3) SetSettlementDate(value string) {\n\tf.SettlementDate = (*ISODate)(&value)\n}\n\nfunc (f *FundSettlementParameters3) AddSettlementPlace() *PartyIdentification2Choice {\n\tf.SettlementPlace = new(PartyIdentification2Choice)\n\treturn f.SettlementPlace\n}\n\nfunc (f *FundSettlementParameters3) AddSafekeepingPlace() *PartyIdentification2Choice {\n\tf.SafekeepingPlace = new(PartyIdentification2Choice)\n\treturn f.SafekeepingPlace\n}\n\n\n\nfunc (f *FundSettlementParameters3) AddReceivingSideDetails() *ReceivingPartiesAndAccount3 {\n\tf.ReceivingSideDetails = new(ReceivingPartiesAndAccount3)\n\treturn f.ReceivingSideDetails\n}\n\nfunc (f *FundSettlementParameters3) AddDeliveringSideDetails() *DeliveringPartiesAndAccount3 {\n\tf.DeliveringSideDetails = new(DeliveringPartiesAndAccount3)\n\treturn f.DeliveringSideDetails\n}\n\nfunc (f *FundSettlementParameters3) SetSecuritiesSettlementSystemIdentification(value string) ", "output": "{\n\tf.SecuritiesSettlementSystemIdentification = (*Max35Text)(&value)\n}"} {"input": "package social_message\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"koding/remoteapi/models\"\n)\n\n\ntype SocialMessageReplyReader struct {\n\tformats strfmt.Registry\n}\n\n\n\n\n\nfunc NewSocialMessageReplyOK() *SocialMessageReplyOK {\n\treturn &SocialMessageReplyOK{}\n}\n\n\ntype SocialMessageReplyOK struct {\n\tPayload *models.DefaultResponse\n}\n\nfunc (o *SocialMessageReplyOK) Error() string {\n\treturn fmt.Sprintf(\"[POST /remote.api/SocialMessage.reply][%d] socialMessageReplyOK %+v\", 200, o.Payload)\n}\n\nfunc (o *SocialMessageReplyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\to.Payload = new(models.DefaultResponse)\n\n\tif err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc NewSocialMessageReplyUnauthorized() *SocialMessageReplyUnauthorized {\n\treturn &SocialMessageReplyUnauthorized{}\n}\n\n\ntype SocialMessageReplyUnauthorized struct {\n\tPayload *models.UnauthorizedRequest\n}\n\nfunc (o *SocialMessageReplyUnauthorized) Error() string {\n\treturn fmt.Sprintf(\"[POST /remote.api/SocialMessage.reply][%d] socialMessageReplyUnauthorized %+v\", 401, o.Payload)\n}\n\nfunc (o *SocialMessageReplyUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\to.Payload = new(models.UnauthorizedRequest)\n\n\tif err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (o *SocialMessageReplyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) ", "output": "{\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewSocialMessageReplyOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 401:\n\t\tresult := NewSocialMessageReplyUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"k8s.io/kubernetes/pkg/kubectl\"\n\tcmdutil \"k8s.io/kubernetes/pkg/kubectl/cmd/util\"\n)\n\nconst (\n\tserviceAccountLong = `\nCreate a service account with the specified name.`\n\n\tserviceAccountExample = ` # Create a new service account named my-service-account\n $ kubectl create serviceaccount my-service-account`\n)\n\n\nfunc NewCmdCreateServiceAccount(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"serviceaccount NAME [--dry-run]\",\n\t\tAliases: []string{\"sa\"},\n\t\tShort: \"Create a service account with the specified name.\",\n\t\tLong: serviceAccountLong,\n\t\tExample: serviceAccountExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\terr := CreateServiceAccount(f, cmdOut, cmd, args)\n\t\t\tcmdutil.CheckErr(err)\n\t\t},\n\t}\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddGeneratorFlags(cmd, cmdutil.ServiceAccountV1GeneratorName)\n\treturn cmd\n}\n\n\n\n\nfunc CreateServiceAccount(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error ", "output": "{\n\tname, err := NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar generator kubectl.StructuredGenerator\n\tswitch generatorName := cmdutil.GetFlagString(cmd, \"generator\"); generatorName {\n\tcase cmdutil.ServiceAccountV1GeneratorName:\n\t\tgenerator = &kubectl.ServiceAccountGeneratorV1{Name: name}\n\tdefault:\n\t\treturn cmdutil.UsageError(cmd, fmt.Sprintf(\"Generator: %s not supported.\", generatorName))\n\t}\n\treturn RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{\n\t\tName: name,\n\t\tStructuredGenerator: generator,\n\t\tDryRun: cmdutil.GetFlagBool(cmd, \"dry-run\"),\n\t\tOutputFormat: cmdutil.GetFlagString(cmd, \"output\"),\n\t})\n}"} {"input": "package parsex\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype ParsexError struct {\n\tPos int\n\tMessage string\n}\n\nfunc (err ParsexError) Error() string {\n\treturn fmt.Sprintf(\"pos %d :\\n%s\",\n\t\terr.Pos, err.Message)\n}\n\ntype ParsexState interface {\n\tNext(pred func(int, interface{}) (interface{}, error)) (x interface{}, err error)\n\tPos() int\n\tSeekTo(int)\n\tTrap(message string, args ...interface{}) error\n}\n\ntype StateInMemory struct {\n\tbuffer []interface{}\n\tpos int\n}\n\nfunc NewStateInMemory(buffer []interface{}) *StateInMemory {\n\treturn &StateInMemory{buffer, 0}\n}\n\n\n\nfunc (this *StateInMemory) Pos() int {\n\treturn (*this).pos\n}\n\nfunc (this *StateInMemory) SeekTo(pos int) {\n\tend := len((*this).buffer)\n\tif pos < 0 || pos > end {\n\t\tmessage := fmt.Sprintf(\"%d out range [0, %d]\", pos, end)\n\t\tpanic(errors.New(message))\n\t}\n\t(*this).pos = pos\n}\n\nfunc (this *StateInMemory) Trap(message string, args ...interface{}) error {\n\treturn ParsexError{(*this).pos,\n\t\tfmt.Sprintf(message, args...)}\n}\n\nfunc (this *StateInMemory) Next(pred func(int, interface{}) (interface{}, error)) (x interface{}, err error) ", "output": "{\n\tbuffer := (*this).buffer\n\tif (*this).pos < len(buffer) {\n\t\tx := buffer[(*this).pos]\n\t\toutput, err := pred((*this).pos, x)\n\t\tif err == nil {\n\t\t\t(*this).pos++\n\t\t\treturn output, nil\n\t\t} else {\n\t\t\treturn x, err\n\t\t}\n\t} else {\n\t\treturn nil, io.EOF\n\t}\n}"} {"input": "package controller\n\nimport (\n\t\"github.com/juju/juju/core/migration\"\n\t\"github.com/juju/juju/state\"\n)\n\ntype patcher interface {\n\tPatchValue(destination, source interface{})\n}\n\n\n\nfunc SetPrecheckResult(p patcher, err error) ", "output": "{\n\tp.PatchValue(&runMigrationPrechecks, func(*state.State, migration.TargetInfo) error {\n\t\treturn err\n\t})\n}"} {"input": "package driver\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\n\t\"github.com/hashicorp/go-plugin\"\n)\n\nvar HandshakeConfig = plugin.HandshakeConfig{\n\tProtocolVersion: 1,\n\tMagicCookieKey: \"NOMAD_PLUGIN_MAGIC_COOKIE\",\n\tMagicCookieValue: \"e4327c2e01eabfd75a8a67adb114fb34a757d57eee7728d857a8cec6e91a7255\",\n}\n\nfunc GetPluginMap(w io.Writer) map[string]plugin.Plugin {\n\te := new(ExecutorPlugin)\n\te.logger = log.New(w, \"\", log.LstdFlags)\n\n\ts := new(SyslogCollectorPlugin)\n\ts.logger = log.New(w, \"\", log.LstdFlags)\n\treturn map[string]plugin.Plugin{\n\t\t\"executor\": e,\n\t\t\"syslogcollector\": s,\n\t}\n}\n\n\n\ntype PluginReattachConfig struct {\n\tPid int\n\tAddrNet string\n\tAddrName string\n}\n\n\nfunc (c *PluginReattachConfig) PluginConfig() *plugin.ReattachConfig {\n\tvar addr net.Addr\n\tswitch c.AddrNet {\n\tcase \"unix\", \"unixgram\", \"unixpacket\":\n\t\taddr, _ = net.ResolveUnixAddr(c.AddrNet, c.AddrName)\n\tcase \"tcp\", \"tcp4\", \"tcp6\":\n\t\taddr, _ = net.ResolveTCPAddr(c.AddrNet, c.AddrName)\n\t}\n\treturn &plugin.ReattachConfig{Pid: c.Pid, Addr: addr}\n}\n\n\n\nfunc NewPluginReattachConfig(c *plugin.ReattachConfig) *PluginReattachConfig ", "output": "{\n\treturn &PluginReattachConfig{Pid: c.Pid, AddrNet: c.Addr.Network(), AddrName: c.Addr.String()}\n}"} {"input": "package common\n\nimport (\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/instance\"\n\t\"github.com/juju/juju/state\"\n\t\"github.com/juju/names\"\n)\n\n\n\ntype InstanceIdGetter struct {\n\tst state.EntityFinder\n\tgetCanRead GetAuthFunc\n}\n\n\n\n\nfunc NewInstanceIdGetter(st state.EntityFinder, getCanRead GetAuthFunc) *InstanceIdGetter {\n\treturn &InstanceIdGetter{\n\t\tst: st,\n\t\tgetCanRead: getCanRead,\n\t}\n}\n\n\n\n\n\nfunc (ig *InstanceIdGetter) InstanceId(args params.Entities) (params.StringResults, error) {\n\tresult := params.StringResults{\n\t\tResults: make([]params.StringResult, len(args.Entities)),\n\t}\n\tcanRead, err := ig.getCanRead()\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tfor i, entity := range args.Entities {\n\t\ttag, err := names.ParseTag(entity.Tag)\n\t\tif err != nil {\n\t\t\tresult.Results[i].Error = ServerError(ErrPerm)\n\t\t\tcontinue\n\t\t}\n\t\terr = ErrPerm\n\t\tif canRead(tag) {\n\t\t\tvar instanceId instance.Id\n\t\t\tinstanceId, err = ig.getInstanceId(tag)\n\t\t\tif err == nil {\n\t\t\t\tresult.Results[i].Result = string(instanceId)\n\t\t\t}\n\t\t}\n\t\tresult.Results[i].Error = ServerError(err)\n\t}\n\treturn result, nil\n}\n\nfunc (ig *InstanceIdGetter) getInstanceId(tag names.Tag) (instance.Id, error) ", "output": "{\n\tentity0, err := ig.st.FindEntity(tag)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tentity, ok := entity0.(state.InstanceIdGetter)\n\tif !ok {\n\t\treturn \"\", NotSupportedError(tag, \"instance id\")\n\t}\n\treturn entity.InstanceId()\n}"} {"input": "package controllers\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"html\"\n\t\"html/template\"\n\t\"github.com/stevenandrewcarter/gouter/models\"\n)\n\n\ntype Page struct {\n\tRoutes []models.Route\n\tMessageState string\n\tMessage string\n}\n\n\nfunc index(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"Administration: Handling '%v' Request to: '%v\", r.Method, html.EscapeString(r.URL.Path))\n\tmessage, messageState := deleteRequest(r)\n\tmessage, messageState = createRequest(r)\n\tresult := models.LoadRoutes()\n\tpage := &Page{Routes: result, Message: message, MessageState: messageState}\n\tt := template.Must(template.ParseGlob(\"tmpl/*.html\"))\n\tt.ExecuteTemplate(w, \"indexPage\", page)\n}\n\n\nfunc deleteRequest(r *http.Request) (string, string) {\n\tmessage := \"\"\n\tmessageState := \"\"\n\tquery := r.URL.Query()\n\tif len(query[\"name\"]) != 0 && len(query[\"action\"]) != 0 && query[\"action\"][0] == \"delete\" {\n\t\tlog.Printf(\"Administration: Deleting '%v'\", query[\"name\"][0])\n\t\tif models.DeleteRoute(query[\"name\"][0]) {\n\t\t\tmessage = \"Route succesfully deleted!\"\n\t\t\tmessageState = \"success\"\n\t\t} else {\n\t\t\tmessage = \"Could not delete the route!\"\n\t\t\tmessageState = \"warning\"\n\t\t}\n\t}\n\treturn message, messageState\n}\n\n\n\n\nfunc createRequest(r *http.Request) (string, string) ", "output": "{\n\tmessage := \"\"\n\tmessageState := \"\"\n\tif r.Method == \"POST\" {\n\t\tr.ParseForm()\n\t\tparams := r.Form\n\t\tlog.Printf(\"Administration: Creating new route '%v', Params: (Description: '%v', From: '%v', To: '%v'\", params[\"name\"][0], params[\"description\"][0], params[\"from\"][0], params[\"to\"][0])\n\t\tif models.CreateRoute(models.Route{params[\"description\"][0], params[\"name\"][0], params[\"from\"][0], params[\"to\"][0]}) {\n\t\t\tmessage = \"Route succesfully created!\"\n\t\t\tmessageState = \"success\"\n\t\t} else {\n\t\t\tmessage = \"Could not create the route. A route with the same name already exists!\"\n\t\t\tmessageState = \"warning\"\n\t\t}\n\t}\n\treturn message, messageState\n}"} {"input": "package errors\n\nimport (\n\t\"errors\"\n)\n\nconst callStackDepth = 10\n\ntype DetailError interface {\n\terror\n\tErrCoder\n\tCallStacker\n\tGetRoot() error\n}\n\n\nfunc NewErr(errmsg string) error {\n\treturn errors.New(errmsg)\n}\n\nfunc NewDetailErr(err error,errcode ErrCode,errmsg string) DetailError{\n\tif err == nil {return nil}\n\n\tdnaerr, ok := err.(dnaError)\n\tif !ok {\n\t\tdnaerr.root = err\n\t\tdnaerr.errmsg = err.Error()\n\t\tdnaerr.callstack = getCallStack(0, callStackDepth)\n\t\tdnaerr.code = errcode\n\n\t}\n\tif errmsg != \"\" {\n\t\tdnaerr.errmsg = errmsg + \": \" + dnaerr.errmsg\n\t}\n\n\n\treturn dnaerr\n}\n\n\n\nfunc RootErr(err error) error ", "output": "{\n\tif err, ok := err.(DetailError); ok {\n\t\treturn err.GetRoot()\n\t}\n\treturn err\n}"} {"input": "package nftables\n\nimport (\n\t\"github.com/evilsocket/opensnitch/daemon/log\"\n)\n\n\nfunc (n *Nft) AreRulesLoaded() bool {\n\tn.Lock()\n\tdefer n.Unlock()\n\n\tnRules := 0\n\tfor _, table := range n.mangleTables {\n\t\trules, err := n.conn.GetRule(table, n.outputChains[table])\n\t\tif err != nil {\n\t\t\tlog.Error(\"nftables mangle rules error: %s, %s\", table.Name, n.outputChains[table].Name)\n\t\t\treturn false\n\t\t}\n\t\tfor _, r := range rules {\n\t\t\tif string(r.UserData) == fwKey {\n\t\t\t\tnRules++\n\t\t\t}\n\t\t}\n\t}\n\tif nRules != 2 {\n\t\tlog.Warning(\"nftables mangle rules not loaded: %d\", nRules)\n\t\treturn false\n\t}\n\n\tnRules = 0\n\tfor _, table := range n.filterTables {\n\t\trules, err := n.conn.GetRule(table, n.inputChains[table])\n\t\tif err != nil {\n\t\t\tlog.Error(\"nftables filter rules error: %s, %s\", table.Name, n.inputChains[table].Name)\n\t\t\treturn false\n\t\t}\n\t\tfor _, r := range rules {\n\t\t\tif string(r.UserData) == fwKey {\n\t\t\t\tnRules++\n\t\t\t}\n\t\t}\n\t}\n\tif nRules != 2 {\n\t\tlog.Warning(\"nfables filter rules not loaded: %d\", nRules)\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\n\nfunc (n *Nft) reloadRulesCallback() ", "output": "{\n\tlog.Important(\"nftables firewall rules changed, reloading\")\n\tn.AddSystemRules()\n\tn.InsertRules()\n}"} {"input": "package user\n\nfunc New(id int, username, password, firstname, lastname, role string) User {\n\treturn User{id, username, password, firstname, lastname, role}\n}\n\n\ntype User struct {\n\tid int\n\tusername string\n\tpassword string\n\tfirstname string\n\tlastname string\n\trole string\n}\n\nfunc (u User) Id() int {\n\treturn u.id\n}\n\nfunc (u User) Username() string {\n\treturn u.username\n}\n\nfunc (u User) Password() string {\n\treturn u.password\n}\n\n\n\nfunc (u User) Lastname() string {\n\treturn u.lastname\n}\n\nfunc (u User) Role() string {\n\treturn u.role\n}\n\nfunc (u User) Firstname() string ", "output": "{\n\treturn u.firstname\n}"} {"input": "package luno\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n\ntype Account struct {\n\tEntity\n\tEmail string `json:\"email\"`\n\tName string `json:\"name\"`\n\tFirstName string `json:\"first_name\"`\n\tLastName string `json:\"last_name\"`\n\tUserName string `json:\"username\"`\n\tCreated string `json:\"created\"`\n\tClosed string `json:\"closed\"`\n}\n\n\nfunc (a *Account) MarshalForUpdate() ([]byte, error) {\n\ttmp := map[string]interface{}{\n\t\t\"email\": a.Email,\n\t\t\"name\": a.Name,\n\t\t\"first_name\": a.FirstName,\n\t\t\"last_name\": a.LastName,\n\t}\n\treturn json.Marshal(tmp)\n}\n\n\n\n\nfunc ParseAccount(resp *http.Response) (*Account, error) ", "output": "{\n\trespBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading luno response body: %v\", err)\n\t}\n\tvar rv Account\n\terr = json.Unmarshal(respBytes, &rv)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing luno account json: '%s' err: %v\", respBytes, err)\n\t}\n\treturn &rv, nil\n}"} {"input": "package socket\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\nfunc bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {\n\t_, _, e1 := syscall.Syscall(syscall.SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen))\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}\n\n\n\nfunc setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) ", "output": "{\n\t_, _, e1 := syscall.Syscall6(syscall.SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}"} {"input": "package containerengine\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype WorkRequest struct {\n\n\tId *string `mandatory:\"false\" json:\"id\"`\n\n\tOperationType WorkRequestOperationTypeEnum `mandatory:\"false\" json:\"operationType,omitempty\"`\n\n\tStatus WorkRequestStatusEnum `mandatory:\"false\" json:\"status,omitempty\"`\n\n\tCompartmentId *string `mandatory:\"false\" json:\"compartmentId\"`\n\n\tResources []WorkRequestResource `mandatory:\"false\" json:\"resources\"`\n\n\tTimeAccepted *common.SDKTime `mandatory:\"false\" json:\"timeAccepted\"`\n\n\tTimeStarted *common.SDKTime `mandatory:\"false\" json:\"timeStarted\"`\n\n\tTimeFinished *common.SDKTime `mandatory:\"false\" json:\"timeFinished\"`\n}\n\n\n\nfunc (m WorkRequest) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package app\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"k8s.io/kubernetes/federation/pkg/kubefed\"\n\t_ \"k8s.io/kubernetes/pkg/client/metrics/prometheus\" \n\tcmdutil \"k8s.io/kubernetes/pkg/kubectl/cmd/util\"\n\t\"k8s.io/kubernetes/pkg/util/logs\"\n\t\"k8s.io/kubernetes/pkg/version\"\n\t_ \"k8s.io/kubernetes/pkg/version/prometheus\" \n)\n\nconst hyperkubeImageName = \"gcr.io/google_containers/hyperkube-amd64\"\n\n\n\nfunc Run() error ", "output": "{\n\tlogs.InitLogs()\n\tdefer logs.FlushLogs()\n\n\tdefaultImage := fmt.Sprintf(\"%s:%s\", hyperkubeImageName, version.Get())\n\tcmd := kubefed.NewKubeFedCommand(cmdutil.NewFactory(nil), os.Stdin, os.Stdout, os.Stderr, defaultImage)\n\treturn cmd.Execute()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cloudfoundry/cli/plugin\"\n)\n\ntype TestWithPush struct {\n}\n\nfunc (c *TestWithPush) Run(cliConnection plugin.CliConnection, args []string) {\n\tif args[0] == \"push\" {\n\t\tthePushCmd()\n\t}\n}\n\nfunc (c *TestWithPush) GetMetadata() plugin.PluginMetadata {\n\treturn plugin.PluginMetadata{\n\t\tName: \"TestWithPush\",\n\t\tCommands: []plugin.Command{\n\t\t\t{\n\t\t\t\tName: \"push\",\n\t\t\t\tHelpText: \"push text for test_with_push\",\n\t\t\t},\n\t\t},\n\t}\n}\n\n\n\nfunc main() {\n\tplugin.Start(new(TestWithPush))\n}\n\nfunc thePushCmd() ", "output": "{\n\tfmt.Println(\"You called push in test_with_push\")\n}"} {"input": "package restful\n\nimport \"testing\"\n\nvar tempregexs = []struct {\n\ttemplate, regex string\n\tliteralCount, varCount int\n}{\n\t{\"\", \"^(/.*)?$\", 0, 0},\n\t{\"/a/{b}/c/\", \"^/a/([^/]+?)/c(/.*)?$\", 2, 1},\n\t{\"/{a}/{b}/{c-d-e}/\", \"^/([^/]+?)/([^/]+?)/([^/]+?)(/.*)?$\", 0, 3},\n\t{\"/{p}/abcde\", \"^/([^/]+?)/abcde(/.*)?$\", 5, 1},\n\t{\"/a/{b:*}\", \"^/a/(.*)(/.*)?$\", 1, 1},\n\t{\"/a/{b:[a-z]+}\", \"^/a/([a-z]+)(/.*)?$\", 1, 1},\n}\n\n\n\nfunc TestTemplateToRegularExpression(t *testing.T) ", "output": "{\n\tok := true\n\tfor i, fixture := range tempregexs {\n\t\tactual, lCount, vCount, _ := templateToRegularExpression(fixture.template)\n\t\tif actual != fixture.regex {\n\t\t\tt.Logf(\"regex mismatch, expected:%v , actual:%v, line:%v\\n\", fixture.regex, actual, i) \n\t\t\tok = false\n\t\t}\n\t\tif lCount != fixture.literalCount {\n\t\t\tt.Logf(\"literal count mismatch, expected:%v , actual:%v, line:%v\\n\", fixture.literalCount, lCount, i)\n\t\t\tok = false\n\t\t}\n\t\tif vCount != fixture.varCount {\n\t\t\tt.Logf(\"variable count mismatch, expected:%v , actual:%v, line:%v\\n\", fixture.varCount, vCount, i)\n\t\t\tok = false\n\t\t}\n\t}\n\tif !ok {\n\t\tt.Fatal(\"one or more expression did not match\")\n\t}\n}"} {"input": "package wml\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\ntype CT_Markup struct {\n\tIdAttr int64\n}\n\nfunc NewCT_Markup() *CT_Markup {\n\tret := &CT_Markup{}\n\treturn ret\n}\n\nfunc (m *CT_Markup) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"w:id\"},\n\t\tValue: fmt.Sprintf(\"%v\", m.IdAttr)})\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}\n\nfunc (m *CT_Markup) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"id\" {\n\t\t\tparsed, err := strconv.ParseInt(attr.Value, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.IdAttr = parsed\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_Markup: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (m *CT_Markup) ValidateWithPath(path string) error {\n\treturn nil\n}\n\nfunc (m *CT_Markup) Validate() error ", "output": "{\n\treturn m.ValidateWithPath(\"CT_Markup\")\n}"} {"input": "package mount\n\nimport (\n\t\"context\"\n\t\"github.com/chrislusf/seaweedfs/weed/util\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (wfs *WFS) Forget(nodeid, nlookup uint64) ", "output": "{\n\twfs.inodeToPath.Forget(nodeid, nlookup, func(dir util.FullPath) {\n\t\twfs.metaCache.DeleteFolderChildren(context.Background(), dir)\n\t})\n\twfs.fhmap.ReleaseByInode(nodeid)\n}"} {"input": "package kafka\n\nimport (\n\t\"strings\"\n\n\t\"github.com/prometheus/common/model\"\n\t\"github.com/prometheus/prometheus/model/labels\"\n\t\"github.com/prometheus/prometheus/model/relabel\"\n\n\t\"github.com/grafana/loki/pkg/util\"\n)\n\n\n\nfunc format(lbs labels.Labels, cfg []*relabel.Config) model.LabelSet ", "output": "{\n\tif len(lbs) == 0 {\n\t\treturn nil\n\t}\n\tprocessed := relabel.Process(lbs, cfg...)\n\tlabelOut := model.LabelSet(util.LabelsToMetric(processed))\n\tfor k := range labelOut {\n\t\tif strings.HasPrefix(string(k), \"__\") {\n\t\t\tdelete(labelOut, k)\n\t\t}\n\t}\n\treturn labelOut\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\n\t. \"github.com/emicklei/go-restful/v3\"\n)\n\n\n\n\n\n\n\n\nfunc main() {\n\tDefaultContainer.Router(CurlyRouter{})\n\tws := new(WebService)\n\n\tws.Route(ws.GET(\"/resource:validate\").To(validateHandler))\n\tws.Route(ws.POST(\"/resource/{resourceId}:init\").To(initHandler))\n\tws.Route(ws.POST(\"/resource/{resourceId}:recycle\").To(recycleHandler))\n\n\tAdd(ws)\n\n\tprintln(\"[go-restful] serve path tails from http:localhost:8080/basepath\")\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc validateHandler(req *Request, resp *Response) {\n\tio.WriteString(resp, \"validate resource completed\")\n}\n\n\n\nfunc recycleHandler(req *Request, resp *Response) {\n\tio.WriteString(resp, \"recycle resource completed, resourceId: \"+req.PathParameter(\"resourceId\"))\n}\n\nfunc initHandler(req *Request, resp *Response) ", "output": "{\n\tio.WriteString(resp, \"init resource completed, resourceId: \"+req.PathParameter(\"resourceId\"))\n}"} {"input": "package common\n\nimport (\n\t\"encoding/binary\"\n\t\"sort\"\n)\n\n\n\ntype Uint64Slice []uint64\n\nfunc (p Uint64Slice) Len() int { return len(p) }\nfunc (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] }\nfunc (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p Uint64Slice) Sort() { sort.Sort(p) }\n\nfunc SearchUint64s(a []uint64, x uint64) int {\n\treturn sort.Search(len(a), func(i int) bool { return a[i] >= x })\n}\n\nfunc (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) }\n\n\n\nfunc PutUint64LE(dest []byte, i uint64) {\n\tbinary.LittleEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64LE(src []byte) uint64 {\n\treturn binary.LittleEndian.Uint64(src)\n}\n\nfunc PutUint64BE(dest []byte, i uint64) {\n\tbinary.BigEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64BE(src []byte) uint64 {\n\treturn binary.BigEndian.Uint64(src)\n}\n\nfunc PutInt64LE(dest []byte, i int64) {\n\tbinary.LittleEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64LE(src []byte) int64 {\n\treturn int64(binary.LittleEndian.Uint64(src))\n}\n\nfunc PutInt64BE(dest []byte, i int64) {\n\tbinary.BigEndian.PutUint64(dest, uint64(i))\n}\n\n\n\nfunc GetInt64BE(src []byte) int64 ", "output": "{\n\treturn int64(binary.BigEndian.Uint64(src))\n}"} {"input": "package format\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\n\ntype Unsigned32 uint32\n\nfunc DecodeUnsigned32(b []byte) (Format, error) {\n\treturn Unsigned32(binary.BigEndian.Uint32(b)), nil\n}\n\nfunc (n Unsigned32) Serialize() []byte {\n\tb := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(b, uint32(n))\n\treturn b\n}\n\nfunc (n Unsigned32) Len() int {\n\treturn 4\n}\n\nfunc (n Unsigned32) Padding() int {\n\treturn 0\n}\n\nfunc (n Unsigned32) Format() FormatId {\n\treturn Unsigned32Format\n}\n\n\n\nfunc (n Unsigned32) String() string ", "output": "{\n\treturn fmt.Sprintf(\"Unsigned32{%d}\", n)\n}"} {"input": "package libpod\n\nimport (\n\t\"context\"\n\n\t\"github.com/containers/podman/v3/libpod/define\"\n)\n\n\n\n\nfunc (r *Runtime) removePod(ctx context.Context, p *Pod, removeCtrs, force bool) error {\n\treturn define.ErrOSNotSupported\n}\n\nfunc (r *Runtime) NewPod(ctx context.Context, options ...PodCreateOption) (*Pod, error) ", "output": "{\n\treturn nil, define.ErrOSNotSupported\n}"} {"input": "package taskmanager\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\n\n\nfunc (s *Agent) Run(process func(*Agent) error) {\n\ts.task.Status = AgentTaskStatusRunning\n\ts.statusEmitter <- s.task.Status\n\ts.taskManager.SaveTask(s.task)\n\tgo s.startTaskPoller()\n\tgo s.listenForPoll()\n\n\tgo func(agent Agent) {\n\t\ts := &agent\n\t\terr := process(s)\n\t\ts.taskPollEmitter <- false\n\n\t\tselect {\n\t\tcase <-s.processComplete:\n\t\t\tif err == nil {\n\t\t\t\ts.task.Status = AgentTaskStatusComplete\n\n\t\t\t} else {\n\t\t\t\ts.task.Status = fmt.Sprintf(\"status: %s, error: %s\", AgentTaskStatusFailed, err.Error())\n\t\t\t}\n\t\t\ts.task.Expires = 0\n\t\t\ts.taskManager.SaveTask(s.task)\n\t\t\ts.statusEmitter <- s.task.Status\n\t\t}\n\t}(*s)\n}\n\n\nfunc (s *Agent) GetTask() *Task {\n\treturn s.task\n}\n\n\nfunc (s *Agent) GetStatus() chan string {\n\treturn s.statusEmitter\n}\n\nfunc (s *Agent) startTaskPoller() {\nForLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-s.killTaskPoller:\n\t\t\ts.processComplete <- true\n\t\t\tbreak ForLoop\n\t\tdefault:\n\t\t\ts.taskPollEmitter <- true\n\t\t}\n\t\ttime.Sleep(AgentTaskPollerInterval)\n\t}\n}\n\nfunc (s *Agent) listenForPoll() {\n\tfor <-s.taskPollEmitter {\n\t\ts.task.Expires = time.Now().Add(AgentTaskPollerTimeout).UnixNano()\n\t\ts.taskManager.SaveTask(s.task)\n\t}\n\ts.killTaskPoller <- true\n}\n\nfunc NewAgent(t TaskManagerInterface, callerName string) *Agent ", "output": "{\n\treturn &Agent{\n\t\tkillTaskPoller: make(chan bool, 1),\n\t\tprocessComplete: make(chan bool, 1),\n\t\ttaskPollEmitter: make(chan bool, 1),\n\t\tstatusEmitter: make(chan string, 1),\n\t\ttaskManager: t,\n\t\ttask: t.NewTask(callerName, TaskAgentLongRunning, AgentTaskStatusInitializing),\n\t}\n}"} {"input": "package resttk\n\ntype ResourceInterface interface {\n\tFindAllResources(v interface{}) interface{}\n\tFindResource(key string, value string, v interface{}) interface{}\n\tSaveResource(key string, value string, v interface{}) interface{}\n\tUpdateResource(key string, value string, v interface{}) interface{}\n\tDeleteResource(key string, value string) bool\n}\n\ntype BaseResource struct {\n\tparent ResourceInterface\n}\n\nfunc (r *BaseResource) Init(p ResourceInterface) {\n\tr.parent = p\n}\n\nfunc (r *BaseResource) FindAllResources(v interface{}) interface{} {\n\tresources := r.parent.FindAllResources(v)\n\tif resources != nil {\n\t\treturn resources\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (r *BaseResource) SaveResource(key string, value string, v interface{}) interface{} {\n\tresource := r.parent.FindResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn nil\n}\n\nfunc (r *BaseResource) UpdateResource(key string, value string, v interface{}) interface{} {\n\tresource := r.parent.UpdateResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn nil\n}\n\nfunc (r *BaseResource) DeleteResource(key string, value string) bool {\n\treturn r.parent.DeleteResource(key, value)\n}\n\nfunc (r *BaseResource) FindResource(key string, value string, v interface{}) interface{} ", "output": "{\n\tresource := r.parent.FindResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn nil\n}"} {"input": "package flags\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst Version = \"0.16.1\"\n\ntype version []int\n\n\n\nfunc (v version) Lte(u version) bool {\n\tlv := len(v)\n\tlu := len(u)\n\n\tfor i := 0; i < lv; i++ {\n\t\tif i >= lu {\n\t\t\treturn false\n\t\t}\n\n\t\tif v[i] == u[i] {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn v[i] < u[i]\n\t}\n\n\treturn true\n}\n\nfunc ParseVersion(s string) (version, error) ", "output": "{\n\tv := make(version, 0)\n\tps := strings.Split(s, \".\")\n\tfor _, p := range ps {\n\t\ti, err := strconv.Atoi(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tv = append(v, i)\n\t}\n\n\treturn v, nil\n}"} {"input": "package utils\n\nimport (\n \"github.com/BurntSushi/toml\"\n \"io/ioutil\"\n \"net\"\n \"sync\"\n \"strings\"\n\n log \"github.com/cihub/seelog\"\n)\n\nvar (\n config *Configuration\n configLock = new(sync.RWMutex)\n)\n\nfunc ReadConfigFromFile(configfile string) {\n config_file, err := ioutil.ReadFile(configfile)\n if err != nil {\n panic(err.Error())\n }\n tempConf := new(Configuration)\n _, err = toml.Decode(string(config_file), &tempConf)\n if err != nil {\n panic(err.Error())\n }\n configLock.Lock()\n config = tempConf\n configLock.Unlock()\n}\n\nfunc GetConfig() *Configuration {\n configLock.RLock()\n defer configLock.RUnlock()\n return config\n}\n\n\n\nfunc GetLocalIp() string ", "output": "{\n addrs, err := net.InterfaceAddrs()\n if err != nil {\n log.Criticalf(\"No network interfaces found, %s\", err.Error())\n }\n \n var ips []string\n for _, a := range addrs {\n if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {\n if ipnet.IP.To4() != nil {\n ips = append(ips, ipnet.IP.String())\n }\n }\n }\n return strings.Join(ips, \",\")\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype CustomResourceDefinitionLister interface {\n\tList(selector labels.Selector) (ret []*v1beta1.CustomResourceDefinition, err error)\n\tGet(name string) (*v1beta1.CustomResourceDefinition, error)\n\tCustomResourceDefinitionListerExpansion\n}\n\n\ntype customResourceDefinitionLister struct {\n\tindexer cache.Indexer\n}\n\n\n\n\n\nfunc (s *customResourceDefinitionLister) List(selector labels.Selector) (ret []*v1beta1.CustomResourceDefinition, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.CustomResourceDefinition))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *customResourceDefinitionLister) Get(name string) (*v1beta1.CustomResourceDefinition, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"customresourcedefinition\"), name)\n\t}\n\treturn obj.(*v1beta1.CustomResourceDefinition), nil\n}\n\nfunc NewCustomResourceDefinitionLister(indexer cache.Indexer) CustomResourceDefinitionLister ", "output": "{\n\treturn &customResourceDefinitionLister{indexer: indexer}\n}"} {"input": "package mgorm\n\nimport (\n\t\"labix.org/v2/mgo/bson\"\n)\n\ntype IEmbeddedModel interface {\n\tIErrorHandler\n\tIValidator\n\tIEvent\n}\n\ntype IModel interface {\n\tIEmbeddedModel\n\tIsNew() bool\n\tGetId() bson.ObjectId\n\tAfterFind()\n\tBeforeSave() error\n\tAfterSave()\n\tCollectionName() string\n}\n\ntype EmbeddedModel struct {\n\tErrorHandler `bson:\",inline\" json:\"-\"`\n\tEvent `bson:\",inline\" json:\"-\"`\n}\n\nfunc (self *EmbeddedModel) Validate() bool {\n\tself.ClearErrors()\n\n\terr := self.Emit(\"BeforeValidate\")\n\tif nil != err {\n\t\tself.AddError(err.Error())\n\t\treturn false\n\t}\n\n\treturn true\n}\n\ntype Model struct {\n\tEmbeddedModel `bson:\",inline\" json:\"-\"`\n\tId bson.ObjectId `bson:\"_id\" json:\"id\"`\n\tisOld bool\n\tcollectionName string\n}\n\nfunc (self *Model) AfterFind() {\n\tself.Emit(\"AfterFind\")\n\tself.isOld = true\n}\n\nfunc (self *Model) BeforeSave() error {\n\tif self.IsNew() {\n\t\tself.Id = bson.NewObjectId()\n\t}\n\n\treturn self.Emit(\"BeforeSave\")\n}\n\nfunc (self *Model) AfterSave() {\n\tself.Emit(\"AfterSave\")\n\tself.isOld = true\n}\n\n\n\nfunc (self *Model) IsNew() bool {\n\treturn !self.isOld\n}\n\nfunc (self *Model) GetId() bson.ObjectId ", "output": "{\n\treturn self.Id\n}"} {"input": "package layers\n\nimport (\n\t\"github.com/google/gopacket\"\n\t\"testing\"\n)\n\n\n\n\n\nvar testPacketRadiotap0 = []byte{\n\t0x00, 0x00, 0x12, 0x00, 0x2e, 0x48, 0x00, 0x00, 0x10, 0x02, 0x6c, 0x09, 0xa0, 0x00, 0xc6, 0x07,\n\t0x00, 0x00, 0xd4, 0x00, 0x00, 0x00, 0x88, 0x1f, 0xa1, 0xae, 0x9d, 0xcb, 0xc6, 0x30, 0x4b, 0x4b,\n}\n\n\nfunc BenchmarkDecodePacketRadiotap0(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tgopacket.NewPacket(testPacketRadiotap0, LayerTypeRadioTap, gopacket.NoCopy)\n\t}\n}\n\nfunc TestPacketRadiotap0(t *testing.T) ", "output": "{\n\tp := gopacket.NewPacket(testPacketRadiotap0, LayerTypeRadioTap, gopacket.Default)\n\tif p.ErrorLayer() != nil {\n\t\tt.Error(\"Failed to decode packet:\", p.ErrorLayer().Error())\n\t}\n\tcheckLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11}, t)\n\trt := p.Layer(LayerTypeRadioTap).(*RadioTap)\n\tif rt.ChannelFrequency != 2412 || rt.DBMAntennaSignal != -58 || rt.Antenna != 7 {\n\t\tt.Error(\"Radiotap decode error\")\n\t}\n\tif rt.Rate != 2 { \n\t\tt.Error(\"Radiotap Rate decode error\")\n\t}\n}"} {"input": "package rackspace\n\nimport (\n\t\"gopkg.in/goose.v2/nova\"\n\n\t\"github.com/juju/juju/provider/openstack\"\n)\n\ntype rackspaceNetworkingDecorator struct{}\n\n\nfunc (d rackspaceNetworkingDecorator) DecorateNetworking(n openstack.Networking) (openstack.Networking, error) {\n\treturn rackspaceNetworking{n}, nil\n}\n\ntype rackspaceNetworking struct {\n\topenstack.Networking\n}\n\n\n\n\nfunc (rackspaceNetworking) DefaultNetworks() ([]nova.ServerNetworks, error) ", "output": "{\n\treturn []nova.ServerNetworks{\n\t\t{NetworkId: \"00000000-0000-0000-0000-000000000000\"}, \n\t\t{NetworkId: \"11111111-1111-1111-1111-111111111111\"}, \n\t}, nil\n}"} {"input": "package benchmarks\n\nimport (\n\t\"io/ioutil\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/go-kit/kit/log\"\n)\n\nfunc newKit() *log.Context {\n\treturn log.NewContext(log.NewJSONLogger(ioutil.Discard))\n}\n\nfunc BenchmarkGoKitAddingFields(b *testing.B) {\n\tlogger := newKit()\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tlogger.With(\n\t\t\t\t\"int\", 1,\n\t\t\t\t\"int64\", int64(1),\n\t\t\t\t\"float\", 3.0,\n\t\t\t\t\"string\", \"four!\",\n\t\t\t\t\"bool\", true,\n\t\t\t\t\"time\", time.Unix(0, 0),\n\t\t\t\t\"error\", errExample.Error(),\n\t\t\t\t\"duration\", time.Second,\n\t\t\t\t\"user-defined type\", _jane,\n\t\t\t\t\"another string\", \"done!\",\n\t\t\t).Log(\"Go fast.\")\n\t\t}\n\t})\n}\n\nfunc BenchmarkGoKitWithAccumulatedContext(b *testing.B) {\n\tlogger := newKit().With(\n\t\t\"int\", 1,\n\t\t\"int64\", int64(1),\n\t\t\"float\", 3.0,\n\t\t\"string\", \"four!\",\n\t\t\"bool\", true,\n\t\t\"time\", time.Unix(0, 0),\n\t\t\"error\", errExample.Error(),\n\t\t\"duration\", time.Second,\n\t\t\"user-defined type\", _jane,\n\t\t\"another string\", \"done!\",\n\t)\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tlogger.Log(\"Go really fast.\")\n\t\t}\n\t})\n}\n\n\n\nfunc BenchmarkGoKitWithoutFields(b *testing.B) ", "output": "{\n\tlogger := newKit()\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tlogger.Log(\"Go fast.\")\n\t\t}\n\t})\n}"} {"input": "package common\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"io\"\n\t\"math/rand\"\n\t\"os\"\n)\n\n\n\nfunc RandString(n int) string {\n\tvar letters = []byte(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n\tb := make([]byte, n)\n\tfor i := range b {\n\t\tb[i] = letters[rand.Intn(len(letters))]\n\t}\n\treturn string(b)\n}\n\nfunc GetFileInfo(path string) (*LocalFileInfo, error) ", "output": "{\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer file.Close()\n\n\ts, err := file.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf := &LocalFileInfo{}\n\tf.Size = s.Size()\n\tf.Name = s.Name()\n\tf.Path = path\n\n\th := md5.New()\n\t_, err = io.Copy(h, file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf.Md5 = fmt.Sprintf(\"%X\", h.Sum(nil))\n\n\treturn f, nil\n}"} {"input": "package HeatersController\n\nimport (\n\t\"errors\"\n\n\t\"github.com/stianeikeland/go-rpio\"\n)\n\nvar heaters [3]rpio.Pin\n\nfunc init() {\n\trpio.Open()\n\n\theaters[0] = rpio.Pin(26)\n\theaters[1] = rpio.Pin(20)\n\theaters[2] = rpio.Pin(21)\n\n\theaters[0].Output()\n\theaters[1].Output()\n\theaters[2].Output()\n\n\theaters[0].High()\n\theaters[1].High()\n\theaters[2].High()\n}\n\n\nfunc SetNumberOfWorkingHeaters(num int) error {\n\tif num == 0 {\n\t\theaters[0].High()\n\t\theaters[1].High()\n\t\theaters[2].High()\n\t} else if num == 1 {\n\t\theaters[0].Low()\n\t\theaters[1].High()\n\t\theaters[2].High()\n\t} else if num == 2 {\n\t\theaters[0].Low()\n\t\theaters[1].Low()\n\t\theaters[2].High()\n\t} else if num == 3 {\n\t\theaters[0].Low()\n\t\theaters[1].Low()\n\t\theaters[2].Low()\n\t} else {\n\t\treturn errors.New(\"The num argument should be between 0 and 3 inclusive\")\n\t}\n\n\treturn nil\n}\n\n\nfunc TurnOn(heaterID int) {\n\theaters[heaterID-1].Low()\n}\n\n\nfunc TurnOff(heaterID int) {\n\theaters[heaterID-1].High()\n}\n\n\n\n\nfunc GetNumberOfWorkingHeaters() int ", "output": "{\n\tresult := 0\n\tif heaters[0].Read() == rpio.Low {\n\t\tresult++\n\t}\n\n\tif heaters[1].Read() == rpio.Low {\n\t\tresult++\n\t}\n\n\tif heaters[2].Read() == rpio.Low {\n\t\tresult++\n\t}\n\n\treturn result\n}"} {"input": "package grpclog \n\nimport \"os\"\n\nvar logger = newLoggerV2()\n\n\nfunc V(l int) bool {\n\treturn logger.V(l)\n}\n\n\nfunc Info(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\nfunc Infof(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\nfunc Infoln(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\n\nfunc Warning(args ...interface{}) {\n\tlogger.Warning(args...)\n}\n\n\nfunc Warningf(format string, args ...interface{}) {\n\tlogger.Warningf(format, args...)\n}\n\n\nfunc Warningln(args ...interface{}) {\n\tlogger.Warningln(args...)\n}\n\n\nfunc Error(args ...interface{}) {\n\tlogger.Error(args...)\n}\n\n\nfunc Errorf(format string, args ...interface{}) {\n\tlogger.Errorf(format, args...)\n}\n\n\nfunc Errorln(args ...interface{}) {\n\tlogger.Errorln(args...)\n}\n\n\n\nfunc Fatal(args ...interface{}) {\n\tlogger.Fatal(args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalf(format string, args ...interface{}) {\n\tlogger.Fatalf(format, args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalln(args ...interface{}) {\n\tlogger.Fatalln(args...)\n\tos.Exit(1)\n}\n\n\n\n\nfunc Print(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\n\n\nfunc Printf(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\n\n\n\n\nfunc Println(args ...interface{}) ", "output": "{\n\tlogger.Infoln(args...)\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/clients/generated/client/clientset/versioned/typed/cloudidentity/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeCloudidentityV1beta1 struct {\n\t*testing.Fake\n}\n\n\n\nfunc (c *FakeCloudidentityV1beta1) CloudIdentityMemberships(namespace string) v1beta1.CloudIdentityMembershipInterface {\n\treturn &FakeCloudIdentityMemberships{c, namespace}\n}\n\n\n\nfunc (c *FakeCloudidentityV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeCloudidentityV1beta1) CloudIdentityGroups(namespace string) v1beta1.CloudIdentityGroupInterface ", "output": "{\n\treturn &FakeCloudIdentityGroups{c, namespace}\n}"} {"input": "package thrift\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\n\t\"github.com/uber/tchannel/golang/typed\"\n)\n\n\nfunc writeHeaders(w io.Writer, headers map[string]string) error {\n\tsize := 2\n\tfor k, v := range headers {\n\t\tsize += 4 \n\t\tsize += len(k) + len(v)\n\t}\n\n\tbuf := make([]byte, size)\n\twriteBuffer := typed.NewWriteBuffer(buf)\n\twriteBuffer.WriteUint16(uint16(len(headers)))\n\tfor k, v := range headers {\n\t\twriteBuffer.WriteLen16String(k)\n\t\twriteBuffer.WriteLen16String(v)\n\t}\n\n\tif err := writeBuffer.Err(); err != nil {\n\t\treturn err\n\t}\n\n\tif writeBuffer.BytesWritten() != size {\n\t\treturn fmt.Errorf(\"writeHeaders size calculation wrong, expected to write %v bytes, only wrote %v bytes\",\n\t\t\tsize, writeBuffer.BytesWritten())\n\t}\n\n\t_, err := writeBuffer.FlushTo(w)\n\treturn err\n}\n\n\n\n\nfunc readHeaders(r io.Reader) (map[string]string, error) ", "output": "{\n\tbs, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuffer := typed.NewReadBuffer(bs)\n\tnumHeaders := buffer.ReadUint16()\n\tif numHeaders == 0 {\n\t\treturn nil, buffer.Err()\n\t}\n\n\theaders := make(map[string]string)\n\tfor i := 0; i < int(numHeaders) && buffer.Err() == nil; i++ {\n\t\tk := buffer.ReadLen16String()\n\t\tv := buffer.ReadLen16String()\n\t\theaders[k] = v\n\t}\n\treturn headers, buffer.Err()\n}"} {"input": "package plugin\n\nimport (\n\t\"context\"\n\n\t\"github.com/docker/cli/cli\"\n\t\"github.com/docker/cli/cli/command\"\n\t\"github.com/docker/cli/cli/command/image\"\n\t\"github.com/docker/distribution/reference\"\n\t\"github.com/docker/docker/pkg/jsonmessage\"\n\t\"github.com/docker/docker/registry\"\n\t\"github.com/pkg/errors\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype pushOptions struct {\n\tname string\n\tuntrusted bool\n}\n\n\n\nfunc runPush(dockerCli command.Cli, opts pushOptions) error {\n\tnamed, err := reference.ParseNormalizedNamed(opts.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, ok := named.(reference.Canonical); ok {\n\t\treturn errors.Errorf(\"invalid name: %s\", opts.name)\n\t}\n\n\tnamed = reference.TagNameOnly(named)\n\n\tctx := context.Background()\n\n\trepoInfo, err := registry.ParseRepositoryInfo(named)\n\tif err != nil {\n\t\treturn err\n\t}\n\tauthConfig := command.ResolveAuthConfig(ctx, dockerCli, repoInfo.Index)\n\n\tencodedAuth, err := command.EncodeAuthToBase64(authConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresponseBody, err := dockerCli.Client().PluginPush(ctx, reference.FamiliarString(named), encodedAuth)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer responseBody.Close()\n\n\tif !opts.untrusted {\n\t\trepoInfo.Class = \"plugin\"\n\t\treturn image.PushTrustedReference(dockerCli, repoInfo, named, authConfig, responseBody)\n\t}\n\n\treturn jsonmessage.DisplayJSONMessagesToStream(responseBody, dockerCli.Out(), nil)\n}\n\nfunc newPushCommand(dockerCli command.Cli) *cobra.Command ", "output": "{\n\tvar opts pushOptions\n\tcmd := &cobra.Command{\n\t\tUse: \"push [OPTIONS] PLUGIN[:TAG]\",\n\t\tShort: \"Push a plugin to a registry\",\n\t\tArgs: cli.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\topts.name = args[0]\n\t\t\treturn runPush(dockerCli, opts)\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\n\tcommand.AddTrustSigningFlags(flags, &opts.untrusted, dockerCli.ContentTrustEnabled())\n\n\treturn cmd\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/alt234/affadmin/db\"\n\t\"github.com/alt234/affadmin/models\"\n\t\"github.com/gorilla/schema\"\n\t\"github.com/unrolled/render\"\n\t\"log\"\n\t\"net/http\"\n)\n\ntype FestivalController struct {\n\tAppController\n\t*render.Render\n\tDB *db.DB\n}\n\nfunc (c *FestivalController) Index(rw http.ResponseWriter, r *http.Request) error {\n\tfestivals, err := c.DB.GetAllFestivals()\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n\n\tdata := struct {\n\t\tTitle string\n\t\tFestivals []*models.Festival\n\t}{\n\t\t\"Festivals\",\n\t\tfestivals,\n\t}\n\n\tc.HTML(rw, http.StatusOK, \"festivals/index\", data)\n\n\treturn nil\n}\n\n\n\nfunc (c *FestivalController) Create(rw http.ResponseWriter, r *http.Request) error ", "output": "{\n\tr.ParseForm()\n\n\tfestival := new(models.Festival)\n\tdecoder := schema.NewDecoder()\n\terr := decoder.Decode(festival, r.PostForm)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = c.DB.InsertNewFestival(festival)\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\ntype MyFloat float64\n\n\n\nfunc main() {\n f := MyFloat(-math.Sqrt(2))\n fmt.Println(f.Abs())\n}\n\nfunc (f MyFloat) Abs() float64 ", "output": "{\n if f < 0 {\n return float64(-f)\n }\n return float64(f)\n}"} {"input": "package policy\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/rightscale/rsc/rsapi\"\n)\n\nconst (\n\tAPIName = \"RightScale Policy API 1.0\"\n)\n\n\nvar commandValues rsapi.ActionCommands\n\n\nfunc RegisterCommands(registrar rsapi.APICommandRegistrar) {\n\tcommandValues = rsapi.ActionCommands{}\n\tregistrar.RegisterActionCommands(APIName, GenMetadata, commandValues)\n}\n\n\nfunc (a *API) RunCommand(cmd string) (*http.Response, error) {\n\tc, err := a.ParseCommand(cmd, \"/api\", commandValues)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := a.BuildHTTPRequest(c.HTTPMethod, c.URI, \"1.0\", c.QueryParams, c.PayloadParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn a.PerformRequest(req)\n}\n\n\nfunc (a *API) ShowCommandHelp(cmd string) error {\n\treturn a.ShowHelp(cmd, \"/api\", commandValues)\n}\n\n\n\n\nfunc (a *API) ShowAPIActions(cmd string) error ", "output": "{\n\treturn a.ShowActions(cmd, \"/api\", commandValues)\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype CreateBootVolumeRequest struct {\n\n\tCreateBootVolumeDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateBootVolumeRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateBootVolumeRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request CreateBootVolumeRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateBootVolumeResponse struct {\n\n\tRawResponse *http.Response\n\n\tBootVolume `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response CreateBootVolumeResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response CreateBootVolumeResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package overview\n\nimport (\n\t\"appengine\"\n\n\th \"github.com/czertbytes/pocket/pkg/http\"\n\tt \"github.com/czertbytes/pocket/pkg/types\"\n)\n\ntype Notificator struct {\n\tAppEngineContext appengine.Context\n\tRequestContext *h.RequestContext\n}\n\nfunc NewNotificator(RequestContext *h.RequestContext) *Notificator {\n\treturn &Notificator{\n\t\tAppEngineContext: RequestContext.AppEngineContext,\n\t\tRequestContext: RequestContext,\n\t}\n}\n\nfunc (self *Notificator) Create(overview *t.Overview) error {\n\treturn nil\n}\n\n\n\nfunc (self *Notificator) CreatePayment(payment *t.Payment) error {\n\treturn nil\n}\n\nfunc (self *Notificator) CreateParticipant(participant *t.User) error {\n\treturn nil\n}\n\nfunc (self *Notificator) Update(overview *t.Overview) error ", "output": "{\n\treturn nil\n}"} {"input": "package v1\n\nimport (\n\t\"testing\"\n\n\t\"github.com/rackspace/gophercloud\"\n\t\"github.com/rackspace/gophercloud/rackspace/lb/v1/lbs\"\n\t\"github.com/rackspace/gophercloud/rackspace/lb/v1/monitors\"\n\tth \"github.com/rackspace/gophercloud/testhelper\"\n)\n\nfunc TestMonitors(t *testing.T) {\n\tclient := setup(t)\n\n\tids := createLB(t, client, 1)\n\tlbID := ids[0]\n\n\tgetMonitor(t, client, lbID)\n\n\tupdateMonitor(t, client, lbID)\n\n\tdeleteMonitor(t, client, lbID)\n\n\tdeleteLB(t, client, lbID)\n}\n\n\n\nfunc updateMonitor(t *testing.T, client *gophercloud.ServiceClient, lbID int) {\n\topts := monitors.UpdateHTTPMonitorOpts{\n\t\tAttemptLimit: 3,\n\t\tDelay: 10,\n\t\tTimeout: 10,\n\t\tBodyRegex: \"hello is it me you're looking for\",\n\t\tPath: \"/foo\",\n\t\tStatusRegex: \"200\",\n\t\tType: monitors.HTTP,\n\t}\n\n\terr := monitors.Update(client, lbID, opts).ExtractErr()\n\tth.AssertNoErr(t, err)\n\n\twaitForLB(client, lbID, lbs.ACTIVE)\n\tt.Logf(\"Updated monitor for LB %d\", lbID)\n}\n\nfunc deleteMonitor(t *testing.T, client *gophercloud.ServiceClient, lbID int) {\n\terr := monitors.Delete(client, lbID).ExtractErr()\n\tth.AssertNoErr(t, err)\n\n\twaitForLB(client, lbID, lbs.ACTIVE)\n\tt.Logf(\"Deleted monitor for LB %d\", lbID)\n}\n\nfunc getMonitor(t *testing.T, client *gophercloud.ServiceClient, lbID int) ", "output": "{\n\thm, err := monitors.Get(client, lbID).Extract()\n\tth.AssertNoErr(t, err)\n\tt.Logf(\"Health monitor for LB %d: Type [%s] Delay [%d] Timeout [%d] AttemptLimit [%d]\",\n\t\tlbID, hm.Type, hm.Delay, hm.Timeout, hm.AttemptLimit)\n}"} {"input": "package cachestore\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\n\ntype KVStore struct {\n\tstoreMap map[string]interface{}\n\tmutex sync.RWMutex\n}\n\n\nfunc (store *KVStore) Set(key string, value interface{}) {\n\tstore.mutex.Lock()\n\tstore.storeMap[key] = value\n\tstore.mutex.Unlock()\n}\n\n\nfunc (store *KVStore) Get(key string) interface{} {\n\tstore.mutex.RLock()\n\tval := store.storeMap[key]\n\tstore.mutex.RUnlock()\n\treturn val\n}\n\n\nfunc (store *KVStore) Delete(key string) {\n\tstore.mutex.Lock()\n\tdelete(store.storeMap, key)\n\tstore.mutex.Unlock()\n}\n\n\nfunc (store *KVStore) MarshalJSON() ([]byte, error) {\n\tstore.mutex.RLock()\n\tbytes, err := json.Marshal(store.storeMap)\n\tstore.mutex.RUnlock()\n\treturn bytes, err\n}\n\n\n\n\nfunc NewKVStore() *KVStore ", "output": "{\n\treturn &KVStore{map[string]interface{}{}, sync.RWMutex{}}\n}"} {"input": "package http\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/template\"\n\n\tdsconfig\t\"github.com/mneudert/devel.serve/ds/config\"\n\tdstpl\t\t\"github.com/mneudert/devel.serve/ds/templates/reloader\"\n)\n\ntype ScriptReloaderHandler struct{}\n\ntype ScriptInjectResponseWriter struct {\n\thttp.ResponseWriter\n\n\tdeferredStatus int\n}\n\nfunc (this ScriptInjectResponseWriter) WriteHeader(status int) {\n\tthis.deferredStatus = status\n}\n\nfunc (this ScriptInjectResponseWriter) Write(data []byte) (int, error) {\n\tinjectAt := 0\n\tcontent := string(data)\n\n\tif strings.Contains(content, \"\") {\n\t\tinjectAt = strings.Index(content, \"\")\n\t} else if strings.Contains(content, \"\") {\n\t\tinjectAt = strings.Index(content, \"\") + 6\n\t}\n\n\tif 0 < injectAt {\n\t\tcontent = fmt.Sprint(\n\t\t\tcontent[:injectAt],\n\t\t\t\"\",\n\t\t\tcontent[injectAt:],\n\t\t)\n\t}\n\n\tthis.ResponseWriter.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tthis.ResponseWriter.Header().Set(\"Content-Length\", strconv.FormatInt(int64(len(content)), 10))\n\tthis.ResponseWriter.WriteHeader(this.deferredStatus)\n\n\treturn this.ResponseWriter.Write([]byte(content))\n}\n\n\n\nfunc NewScriptReloaderHandler() *ScriptReloaderHandler {\n\treturn new(ScriptReloaderHandler)\n}\n\nfunc (this *ScriptReloaderHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) ", "output": "{\n\tvar data = make(map[string]interface{})\n\n\tdata[\"PathSocket\"] = dsconfig.Reloader.PathSocket\n\tdata[\"PathXhr\"] = dsconfig.Reloader.PathXhr\n\tdata[\"WsAddress\"] = fmt.Sprintf(\"%s:%d\", dsconfig.Server.Host, dsconfig.Server.Port)\n\tdata[\"XhrInterval\"] = dsconfig.Reloader.XhrInterval\n\n\tvar reloader bytes.Buffer\n\n\ttplReloader := template.New(\"reloader\")\n\ttplReloader.Parse(dstpl.TplScript)\n\ttplReloader.Execute(&reloader, &data)\n\n\tcontent := reloader.Bytes()\n\n\tres.Header().Set(\"Content-Type\", \"text/javascript; charset=utf-8\")\n\tres.Header().Set(\"Content-Length\", strconv.FormatInt(int64(len(content)), 10))\n\tres.Write(content)\n}"} {"input": "package limiter\n\nimport (\n\t\"math/rand\"\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n)\n\n\nfunc GetIP(r *http.Request, trustForwardHeader ...bool) net.IP {\n\tif len(trustForwardHeader) >= 1 && trustForwardHeader[0] {\n\t\tip := r.Header.Get(\"X-Forwarded-For\")\n\t\tif ip != \"\" {\n\t\t\tparts := strings.SplitN(ip, \",\", 2)\n\t\t\tpart := strings.TrimSpace(parts[0])\n\t\t\treturn net.ParseIP(part)\n\t\t}\n\n\t\tip = strings.TrimSpace(r.Header.Get(\"X-Real-IP\"))\n\t\tif ip != \"\" {\n\t\t\treturn net.ParseIP(ip)\n\t\t}\n\t}\n\n\tremoteAddr := strings.TrimSpace(r.RemoteAddr)\n\thost, _, err := net.SplitHostPort(remoteAddr)\n\tif err != nil {\n\t\treturn net.ParseIP(remoteAddr)\n\t}\n\n\treturn net.ParseIP(host)\n}\n\n\n\n\n\nfunc Random(min, max int) int {\n\trand.Seed(time.Now().Unix())\n\treturn rand.Intn(max-min) + min\n}\n\nfunc GetIPKey(r *http.Request, trustForwardHeader ...bool) string ", "output": "{\n\treturn GetIP(r, trustForwardHeader...).String()\n}"} {"input": "package luddite\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\t\"sync\"\n\t\"syscall\"\n)\n\nvar dumpOnce sync.Once\n\n\n\nfunc dumpGoroutineStacks() ", "output": "{\n\tdumpOnce.Do(func() {\n\t\tsigs := make(chan os.Signal, 1)\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\t<-sigs\n\t\t\t\tos.Stderr.Write(goroutineStack(true))\n\t\t\t\tos.Stderr.Write([]byte(\"\\n\"))\n\t\t\t}\n\t\t}()\n\t\tsignal.Notify(sigs, syscall.SIGUSR1)\n\t})\n}"} {"input": "package parse\n\nimport (\n\t\"github.com/hfern/luao/lexer\"\n)\n\ntype readerState struct {\n\tread int\n}\n\ntype tReader struct {\n\tstate readerState\n\tsource *[]lexer.Token\n}\n\nfunc (r tReader) Save() readerState {\n\treturn r.state\n}\n\nfunc (r *tReader) Restore(s readerState) {\n\tr.state = s\n}\n\n\n\nfunc (r *tReader) Next() lexer.Token ", "output": "{\n\tif len(r.source) <= r.state.read {\n\t\treturn lexer.Token\n\t}\n}"} {"input": "package main\n\nimport \"testing\"\n\nfunc TestNewSliceStack(t *testing.T) {\n\tstack := NewStack()\n\n\tif len(stack) != 0 {\n\t\tt.Error(`Expected length of stack to be 0, got`, len(stack))\n\t}\n}\n\nfunc TestSliceStackPush(t *testing.T) {\n\tstack := NewStack()\n\tstack.Push(1111)\n\tstack.Push(2345)\n\n\tif stack[0] != 1111 {\n\t\tt.Error(`Expected the first item to be 1111, got`, stack[0])\n\t}\n}\n\n\n\nfunc TestSliceStackPop(t *testing.T) {\n\tstack := NewStack()\n\tstack.Push(1234)\n\tstack.Push(2345)\n\tvalue, _ := stack.Pop()\n\n\tif value != 2345 {\n\t\tt.Error(`Expected peeked value to be 2345, got`, value)\n\t}\n}\n\nfunc BenchmarkSliceStackPush(b *testing.B) {\n\tb.StopTimer()\n\tstack := NewStack()\n\n\tb.StartTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tstack.Push(n)\n\t}\n}\n\nfunc BenchmarkSliceStackPeek(b *testing.B) {\n\tb.StopTimer()\n\tstack := make(Stack, b.N, b.N)\n\n\tb.StartTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tstack.Peek()\n\t}\n}\n\nfunc BenchmarkSliceStackPop(b *testing.B) {\n\tb.StopTimer()\n\tstack := make(Stack, b.N, b.N)\n\tfor n := 0; n < b.N; n++ {\n\t\tstack[n] = n\n\t}\n\n\tb.StartTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tstack.Pop()\n\t}\n}\n\nfunc TestSliceStackPeek(t *testing.T) ", "output": "{\n\tstack := NewStack()\n\tstack.Push(1234)\n\tstack.Push(2345)\n\tvalue, _ := stack.Peek()\n\n\tif value != 2345 {\n\t\tt.Error(`Expected peeked value to be 2345, got`, value)\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nvar usageStr = `\nUsage: gnatsd [options]\n \nServer Options:\n -a, --addr Bind to host address (default: 0.0.0.0)\n -p, --port Use port for clients (default: 4222)\n -P, --pid File to store PID\n -m, --http_port Use port for http monitoring\n -ms,--https_port Use port for https monitoring\n -c, --config Configuration file\n\nLogging Options:\n -l, --log File to redirect log output\n -T, --logtime Timestamp log entries (default: true)\n -s, --syslog Enable syslog as log method\n -r, --remote_syslog Syslog server addr (udp://localhost:514)\n -D, --debug Enable debugging output\n -V, --trace Trace the raw protocol\n -DV Debug and trace\n\nAuthorization Options:\n --user User required for connections\n --pass Password required for connections\n --auth Authorization token required for connections\n\nTLS Options:\n --tls Enable TLS, do not verify clients (default: false)\n --tlscert Server certificate file\n --tlskey Private key for server certificate\n --tlsverify Enable TLS, very client certificates\n --tlscacert Client certificate CA for verification\n\nCluster Options:\n --routes Routes to solicit and connect\n --cluster Cluster URL for solicited routes\n\nCommon Options:\n -h, --help Show this message\n -v, --version Show version\n --help_tls TLS help.\n`\n\n\n\n\nfunc Usage() ", "output": "{\n\tfmt.Printf(\"%s\\n\", usageStr)\n\tos.Exit(0)\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar xhrOutput *Json\nvar lfgOutput *Json\n\nfunc init() {\n\txhrOutput = &Json{\n\t\tdata: map[string]interface{}{\n\t\t\t\"channels\": []string{},\n\t\t},\n\t\tcond: &sync.WaitGroup{},\n\t}\n\txhrOutput.cond.Add(1)\n\txhrOutput.set(\"updated_at\", time.Now().Unix())\n\n\tlfgOutput = &Json{\n\t\tdata: map[string]interface{}{\n\t\t\t\"lfg\": []string{},\n\t\t},\n\t\tcond: &sync.WaitGroup{},\n\t}\n\tlfgOutput.cond.Add(1)\n\tlfgOutput.set(\"updated_at\", time.Now().Unix())\n}\n\ntype Json struct {\n\tdata map[string]interface{}\n\tupdatedAt string\n\tcache []byte\n\tcond *sync.WaitGroup\n\tlock sync.RWMutex\n}\n\nfunc (j *Json) send(w http.ResponseWriter) error {\n\tj.lock.RLock()\n\t_, err := w.Write(j.cache)\n\tj.lock.RUnlock()\n\treturn err\n}\n\n\n\nfunc (j *Json) set(key string, value interface{}) error ", "output": "{\n\tj.lock.Lock()\n\tj.updatedAt = fmt.Sprintf(\"%d\", time.Now().Unix())\n\tj.data[\"updated_at\"] = j.updatedAt\n\tj.data[key] = value\n\tcache, err := json.Marshal(j.data)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\tj.lock.Unlock()\n\t\treturn err\n\t}\n\tj.cache = cache\n\tnewCond := &sync.WaitGroup{}\n\tnewCond.Add(1)\n\tj.cond.Done()\n\tj.cond = newCond\n\tj.lock.Unlock()\n\treturn nil\n}"} {"input": "package partner\n\nimport (\n\t\"github.com/jrsix/gof/web\"\n\t\"github.com/jrsix/gof/web/mvc\"\n\t\"go2o/src/core/domain/interface/partner\"\n\t\"go2o/src/core/service/dps\"\n\t\"net/url\"\n)\n\nfunc chkLogin(ctx *web.Context) (b bool, partnerId int) {\n\tv := ctx.Session().Get(\"partner_id\")\n\tif v == nil {\n\t\treturn false, -1\n\t}\n\treturn true, v.(int)\n}\nfunc redirect(ctx *web.Context) {\n\tr, w := ctx.Request, ctx.Response\n\tw.Write([]byte(\"\"))\n}\n\nvar _ mvc.Filter = new(baseC)\n\ntype baseC struct {\n}\n\nfunc (this *baseC) Requesting(ctx *web.Context) bool {\n\tif b, _ := chkLogin(ctx); !b {\n\t\tredirect(ctx)\n\t\treturn false\n\t}\n\treturn true\n}\nfunc (this *baseC) RequestEnd(ctx *web.Context) {\n}\n\n\nfunc (this *baseC) GetPartnerId(ctx *web.Context) int {\n\tv := ctx.Session().Get(\"partner_id\")\n\tif v == nil {\n\t\tthis.Requesting(ctx)\n\t\treturn -1\n\t}\n\treturn v.(int)\n}\n\nfunc (this *baseC) GetPartner(ctx *web.Context) (*partner.ValuePartner, error) {\n\treturn dps.PartnerService.GetPartner(this.GetPartnerId(ctx))\n}\n\n\n\n\nfunc (this *baseC) ErrorOutput(ctx *web.Context, err string) ", "output": "{\n\tctx.Response.Write([]byte(\"{error:\\\"\" + err + \"\\\"}\"))\n}"} {"input": "package file\n\nimport (\n\t\"bytes\"\n\t\"github.com/wunderlist/hamustro/src/dialects\"\n\t\"os\"\n)\n\n\ntype Config struct {\n\tFilePath string `json:\"file_path\"`\n\tFileFormat string `json:\"file_format\"`\n\tCompress bool `json:\"compress\"`\n}\n\n\nfunc (c *Config) IsValid() bool {\n\treturn c.FilePath != \"\" && c.FileFormat != \"\"\n}\n\n\nfunc (c *Config) NewClient() (dialects.StorageClient, error) {\n\tconverterFunction, err := dialects.GetBatchConverterFunction(c.FileFormat)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &FileStorage{\n\t\tFilePath: c.FilePath,\n\t\tFileFormat: c.FileFormat,\n\t\tCompress: c.Compress,\n\t\tBatchConverter: converterFunction}, nil\n}\n\n\ntype FileStorage struct {\n\tFilePath string\n\tFileFormat string\n\tCompress bool\n\tBatchConverter dialects.BatchConverter\n}\n\n\nfunc (c *FileStorage) IsBufferedStorage() bool {\n\treturn true\n}\n\n\nfunc (c *FileStorage) GetConverter() dialects.Converter {\n\treturn nil\n}\n\n\nfunc (c *FileStorage) GetBatchConverter() dialects.BatchConverter {\n\treturn c.BatchConverter\n}\n\nfunc (c *FileStorage) GetBuffer(msg *bytes.Buffer) (*bytes.Buffer, error) {\n\tif c.Compress {\n\t\tbuffer, err := dialects.Compress(msg)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn buffer, nil\n\t}\n\treturn msg, nil\n}\n\n\n\n\nfunc (c *FileStorage) Save(msg *bytes.Buffer) error ", "output": "{\n\tbuffer, err := c.GetBuffer(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbasepath := dialects.ResolvePath(c.FilePath)\n\tif err := os.MkdirAll(basepath, os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\n\tpath := dialects.GetRandomPath(basepath, c.FileFormat, c.Compress)\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tdata := buffer.Bytes()\n\tif _, err := f.Write(data); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package jobs\n\nimport (\n\t\"sync\"\n\n\tl4g \"github.com/alecthomas/log4go\"\n\tejobs \"github.com/mattermost/platform/einterfaces/jobs\"\n\t\"github.com/mattermost/platform/model\"\n\t\"github.com/mattermost/platform/store\"\n\t\"github.com/mattermost/platform/utils\"\n)\n\ntype Jobs struct {\n\tstartOnce sync.Once\n\n\tDataRetention model.Job\n\n\tlistenerId string\n}\n\nfunc InitJobs(s store.Store) *Jobs {\n\tjobs := &Jobs{\n\t}\n\n\tif dataRetentionInterface := ejobs.GetDataRetentionInterface(); dataRetentionInterface != nil {\n\t\tjobs.DataRetention = dataRetentionInterface.MakeJob(s)\n\t}\n\n\treturn jobs\n}\n\n\n\nfunc (jobs *Jobs) handleConfigChange(oldConfig *model.Config, newConfig *model.Config) {\n\tif jobs.DataRetention != nil {\n\t\tif !*oldConfig.DataRetentionSettings.Enable && *newConfig.DataRetentionSettings.Enable {\n\t\t\tgo jobs.DataRetention.Run()\n\t\t} else if *oldConfig.DataRetentionSettings.Enable && !*newConfig.DataRetentionSettings.Enable {\n\t\t\tjobs.DataRetention.Stop()\n\t\t}\n\t}\n}\n\nfunc (jobs *Jobs) Stop() *Jobs {\n\tutils.RemoveConfigListener(jobs.listenerId)\n\n\tif jobs.DataRetention != nil && *utils.Cfg.DataRetentionSettings.Enable {\n\t\tjobs.DataRetention.Stop()\n\t}\n\n\tl4g.Info(\"Stopped jobs\")\n\n\treturn jobs\n}\n\nfunc (jobs *Jobs) Start() *Jobs ", "output": "{\n\tl4g.Info(\"Starting jobs\")\n\n\tjobs.startOnce.Do(func() {\n\t\tif jobs.DataRetention != nil && *utils.Cfg.DataRetentionSettings.Enable {\n\t\t\tgo jobs.DataRetention.Run()\n\t\t}\n\n\t})\n\n\tjobs.listenerId = utils.AddConfigListener(jobs.handleConfigChange)\n\n\treturn jobs\n}"} {"input": "package heroku\n\nimport \"fmt\"\n\n\n\n\nfunc (s *Client) SetConfigVars(appName string, index int, key, token string) error ", "output": "{\n\tvar keyConfig, tokenConfig string\n\tif index == 0 {\n\t\tkeyConfig = \"ACME_KEY\"\n\t\ttokenConfig = \"ACME_TOKEN\"\n\t} else {\n\t\tkeyConfig = fmt.Sprintf(\"ACME_KEY_%d\", index)\n\t\ttokenConfig = fmt.Sprintf(\"ACME_TOKEN_%d\", index)\n\t}\n\n\tvar body = make(map[string]string)\n\tbody[keyConfig] = key\n\tbody[tokenConfig] = token\n\n\tvar res struct{}\n\treturn s.Patch(&res, fmt.Sprintf(\"/apps/%s/config-vars\", appName), body)\n}"} {"input": "package itunes\n\n\n\n\n\nfunc (t *Tracks) GetTrackByIndex(index int) (*Track, error) {\n\tr, err := t.obj.GetProperty(\"Item\", index)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\to := COM{\n\t\tobj: r.ToIDispatch(),\n\t}\n\treturn &Track{COM: o}, nil\n}\n\n\nfunc (t *Tracks) GetTrackByName(name string) (*Track, error) {\n\tr, err := t.obj.GetProperty(\"ItemByName\", name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\to := COM{\n\t\tobj: r.ToIDispatch(),\n\t}\n\treturn &Track{COM: o}, nil\n}\n\nfunc (t *Tracks) GetCount() (int64, error) ", "output": "{\n\tv, err := t.obj.GetProperty(\"Count\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn v.Val, nil\n}"} {"input": "package workshop\n\nimport (\n\t\"math\"\n)\n\n\ntype Shape interface {\n\tarea()\n\tcircumference()\n\tvolume()\n}\n\n\ntype Circle struct {\n\tradius float64\n\tPI float64\n}\n\nfunc (circle *Circle) area() float64 {\n\treturn circle.PI * math.Pow(circle.radius, 2)\n}\n\nfunc (circle *Circle) circumference() float64 {\n\treturn 2 * circle.PI * circle.radius\n}\n\n\ntype Square struct {\n\tside float64\n}\n\nfunc (square *Square) area() float64 {\n\treturn math.Pow(square.side, 2)\n}\n\ntype Sphere struct {\n\tPI float64\n\tradius float64\n}\n\n\n\n\ntype Cube struct {\n\tside float64\n}\n\nfunc (cube *Cube) volume() float64 {\n\treturn math.Pow(cube.side, 3)\n}\n\nfunc (square *Square) volume() float64 {\n\treturn math.Pow(square.side, 3)\n}\n\n\ntype Rectangle struct {\n\theight int\n\twidth int\n}\n\nfunc (rectangle *Rectangle) area() int {\n\treturn rectangle.height * rectangle.width\n}\n\nfunc interfaces() {\n\tcircle := Circle{radius: 5.5, PI: math.Pi}\n\tareaOfCircle := circle.area()\n\n\tassert(areaOfCircle == 55)\n\tassert(circle.circumference() == 88)\n\n\tvar square = Square{5}\n\tassert(square.area() == 36)\n\n\tcube := new(Cube)\n\tassert(cube.volume() == 8)\n\n\tvar rectangle = Rectangle{width: 4, height: 5}\n\tassert(rectangle.area() == 2)\n}\n\nfunc (sphere *Sphere) volume() float64 ", "output": "{\n\treturn (4 / 3) * sphere.PI * math.Pow(sphere.radius, 3)\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/gorilla/websocket\"\n)\n\ntype Client struct {\n\thub *Hub\n\tws *websocket.Conn\n\totherSide *Client\n\tchannelID uuid.UUID\n\tremoteType string\n\tparams map[string][]string\n\twmu sync.Mutex\n\trmu sync.Mutex\n}\n\nfunc (c *Client) WriteMessage(msgType int, message []byte) (err error) {\n\tc.wmu.Lock()\n\terr = c.ws.WriteMessage(msgType, message)\n\tc.wmu.Unlock()\n\treturn\n}\n\n\n\nfunc (c *Client) ReadMessage() (msgType int, message []byte, err error) {\n\tc.rmu.Lock()\n\tmsgType, message, err = c.ws.ReadMessage()\n\tc.rmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) NextReader() (msgType int, r io.Reader, err error) {\n\tc.rmu.Lock()\n\tmsgType, r, err = c.ws.NextReader()\n\tc.rmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) SetWriteDeadline(t time.Time) (err error) {\n\tc.wmu.Lock()\n\terr = c.ws.SetWriteDeadline(t)\n\tc.wmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) SetReadDeadline(t time.Time) (err error) {\n\tc.rmu.Lock()\n\terr = c.ws.SetReadDeadline(t)\n\tc.rmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) NextWriter(msgType int) (w io.WriteCloser, err error) ", "output": "{\n\tc.wmu.Lock()\n\tw, err = c.ws.NextWriter(msgType)\n\tc.wmu.Unlock()\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/robfig/cron\"\n)\n\ntype Sync struct{}\n\n\n\nfunc (s *Sync) Run(args []string) int {\n\t_, err := SyncRepository()\n\n\tif err != nil {\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n\nfunc (s *Sync) Synopsis() string {\n\treturn \"Synchronize local git repository with remote at once\"\n}\n\n\ntype status struct {\n\tc *cron.Cron\n\trepositories []string\n\tschedules []string\n}\n\nvar sharedStatus *status = newStatus()\n\nfunc newStatus() *status {\n\treturn &status{\n\t\tc: cron.New(),\n\t}\n}\n\n\nfunc GetStatus() *status {\n\treturn sharedStatus\n}\n\ntype StatusStart struct{}\n\nfunc (s *StatusStart) Help() string {\n\treturn \"glr status start Help\"\n}\n\nfunc (s *StatusStart) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.AddFunc(\"@hourly\", func() {\n\t\tSyncRepository()\n\t})\n\tfmt.Println(\"set job schedule\")\n\tstatus.c.Start()\n\n\treturn 0\n}\n\nfunc (s *StatusStart) Synopsis() string {\n\treturn \"Synchronize local git repository with remote\"\n}\n\ntype StatusStop struct{}\n\nfunc (s *StatusStop) Help() string {\n\treturn \"glr status stop Help\"\n}\n\nfunc (s *StatusStop) Run(args []string) int {\n\n\tstatus := GetStatus()\n\tstatus.c.Stop()\n\tfmt.Println(\"stop job scheduler\")\n\n\treturn 0\n}\n\nfunc (s *StatusStop) Synopsis() string {\n\treturn \"Stop cron scheduler\"\n}\n\nfunc (s *Sync) Help() string ", "output": "{\n\treturn \"glr sync Help\"\n}"} {"input": "package gin\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\nconst GIN_MODE = \"GIN_MODE\"\n\nconst (\n\tDebugMode string = \"debug\"\n\tReleaseMode string = \"release\"\n\tTestMode string = \"test\"\n)\nconst (\n\tdebugCode = iota\n\treleaseCode = iota\n\ttestCode = iota\n)\n\nvar gin_mode int = debugCode\nvar mode_name string = DebugMode\n\nfunc init() {\n\tvalue := os.Getenv(GIN_MODE)\n\tif len(value) == 0 {\n\t\tSetMode(DebugMode)\n\t} else {\n\t\tSetMode(value)\n\t}\n}\n\n\n\nfunc Mode() string {\n\treturn mode_name\n}\n\nfunc SetMode(value string) ", "output": "{\n\tswitch value {\n\tcase DebugMode:\n\t\tgin_mode = debugCode\n\tcase ReleaseMode:\n\t\tgin_mode = releaseCode\n\tcase TestMode:\n\t\tgin_mode = testCode\n\tdefault:\n\t\tlog.Panic(\"gin mode unknown: \" + value)\n\t}\n\tmode_name = value\n}"} {"input": "package token_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hyperledger/fabric/core/handlers/validation/token\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestValidationFactory_New(t *testing.T) {\n\tfactory := &token.ValidationFactory{}\n\tplugin := factory.New()\n\tassert.NotNil(t, plugin)\n}\n\n\n\nfunc TestValidation_Validate(t *testing.T) ", "output": "{\n\tfactory := &token.ValidationFactory{}\n\tplugin := factory.New()\n\n\terr := plugin.Init()\n\tassert.NoError(t, err)\n\n\terr = plugin.Validate(nil, \"\", 0, 0, nil)\n\tassert.NoError(t, err)\n}"} {"input": "package db\n\nimport (\n\t\"database/sql\"\n\t\"encoding/hex\"\n\t\"sync\"\n)\n\ntype WatchedScriptsDB struct {\n\tdb *sql.DB\n\tlock *sync.Mutex\n}\n\n\n\nfunc (w *WatchedScriptsDB) GetAll() ([][]byte, error) {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\tvar ret [][]byte\n\tstm := \"select scriptPubKey from watchedScripts\"\n\trows, err := w.db.Query(stm)\n\tdefer rows.Close()\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tfor rows.Next() {\n\t\tvar scriptHex string\n\t\tif err := rows.Scan(&scriptHex); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tscriptPubKey, err := hex.DecodeString(scriptHex)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tret = append(ret, scriptPubKey)\n\t}\n\treturn ret, nil\n}\n\nfunc (w *WatchedScriptsDB) Delete(scriptPubKey []byte) error {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\t_, err := w.db.Exec(\"delete from watchedScripts where scriptPubKey=?\", hex.EncodeToString(scriptPubKey))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (w *WatchedScriptsDB) Put(scriptPubKey []byte) error ", "output": "{\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\ttx, _ := w.db.Begin()\n\tstmt, err := tx.Prepare(\"insert or replace into watchedScripts(scriptPubKey) values(?)\")\n\tdefer stmt.Close()\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\t_, err = stmt.Exec(hex.EncodeToString(scriptPubKey))\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\ttx.Commit()\n\treturn nil\n}"} {"input": "package platform\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os/user\"\n\t\"testing\"\n\n\t\"github.com/jmoiron/sqlx\"\n\n\t\"github.com/tapglue/snaas/platform/pg\"\n)\n\nvar pgTestURL string\n\nfunc TestPostgresPut(t *testing.T) {\n\ttestServicePut(t, preparePostgres)\n}\n\n\n\nfunc preparePostgres(t *testing.T, namespace string) Service {\n\tdb, err := sqlx.Connect(\"postgres\", pgTestURL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ts := PostgresService(db)\n\n\tif err := s.Teardown(namespace); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treturn s\n}\n\nfunc init() {\n\tu, err := user.Current()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\td := fmt.Sprintf(pg.URLTest, u.Username)\n\n\turl := flag.String(\"postgres.url\", d, \"Postgres test connection URL\")\n\tflag.Parse()\n\n\tpgTestURL = *url\n}\n\nfunc TestPostgresQuery(t *testing.T) ", "output": "{\n\ttestServiceQuery(t, preparePostgres)\n}"} {"input": "package api\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/mundipagg/boleto-api/models\"\n)\n\n\n\n\n\nfunc validateRegisterV2(c *gin.Context) {\n\tr := getBoletoFromContext(c).Title.Rules\n\tbn := getBankFromContext(c).GetBankNumber()\n\n\tif r != nil && bn != models.Caixa {\n\t\tc.AbortWithStatusJSON(400, models.NewSingleErrorCollection(\"MP400\", \"title.rules not available for this bank\"))\n\t\treturn\n\t}\n}\n\nfunc validateRegisterV1(c *gin.Context) ", "output": "{\n\trules := getBoletoFromContext(c).Title.Rules\n\tbn := getBankFromContext(c).GetBankNumber()\n\n\tif rules != nil {\n\t\tc.AbortWithStatusJSON(400, models.NewSingleErrorCollection(\"MP400\", \"title.rules not available in this version\"))\n\t\treturn\n\t}\n\n\tif bn == models.Stone {\n\t\tc.AbortWithStatusJSON(400, models.NewSingleErrorCollection(\"MP400\", \"bank Stone not available in this version\"))\n\t\treturn\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"net\"\n\t\"strconv\"\n)\n\nconst (\n\tAddrTypeIP = byte(0x01)\n\tAddrTypeDomain = byte(0x03)\n)\n\ntype VAddress struct {\n\tType byte\n\tIP net.IP\n\tDomain string\n\tPort uint16\n}\n\nfunc IPAddress(ip []byte, port uint16) VAddress {\n\treturn VAddress{\n\t\tAddrTypeIP,\n\t\tnet.IP(ip),\n\t\t\"\",\n\t\tport}\n}\n\nfunc DomainAddress(domain string, port uint16) VAddress {\n\treturn VAddress{\n\t\tAddrTypeDomain,\n\t\tnil,\n\t\tdomain,\n\t\tport}\n}\n\nfunc (addr VAddress) IsIPv4() bool {\n\treturn addr.Type == AddrTypeIP && len(addr.IP) == net.IPv4len\n}\n\nfunc (addr VAddress) IsIPv6() bool {\n\treturn addr.Type == AddrTypeIP && len(addr.IP) == net.IPv6len\n}\n\nfunc (addr VAddress) IsDomain() bool {\n\treturn addr.Type == AddrTypeDomain\n}\n\n\n\nfunc (addr VAddress) String() string ", "output": "{\n\tvar host string\n\tswitch addr.Type {\n\tcase AddrTypeIP:\n\t\thost = addr.IP.String()\n\t\tif len(addr.IP) == net.IPv6len {\n\t\t\thost = \"[\" + host + \"]\"\n\t\t}\n\n\tcase AddrTypeDomain:\n\t\thost = addr.Domain\n\tdefault:\n\t\tpanic(\"Unknown Address Type \" + strconv.Itoa(int(addr.Type)))\n\t}\n\treturn host + \":\" + strconv.Itoa(int(addr.Port))\n}"} {"input": "package gtk\n\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\n\n\n\nfunc (v *SizeGroup) GetIgnoreHidden() bool {\n\tc := C.gtk_size_group_get_ignore_hidden(v.native())\n\treturn gobool(c)\n}\n\n\nfunc (v *Window) SetWMClass(name, class string) {\n\tcName := C.CString(name)\n\tdefer C.free(unsafe.Pointer(cName))\n\tcClass := C.CString(class)\n\tdefer C.free(unsafe.Pointer(cClass))\n\tC.gtk_window_set_wmclass(v.native(), (*C.gchar)(cName), (*C.gchar)(cClass))\n}\n\nfunc (v *SizeGroup) SetIgnoreHidden(ignoreHidden bool) {\n\tC.gtk_size_group_set_ignore_hidden(v.native(), gbool(ignoreHidden))\n}\n\n\nfunc (v *FontButton) GetFontName() string {\n\tc := C.gtk_font_button_get_font_name(v.native())\n\treturn goString(c)\n}\n\n\nfunc (v *FontButton) SetFontName(fontname string) bool {\n\tcstr := C.CString(fontname)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_font_button_set_font_name(v.native(), (*C.gchar)(cstr))\n\treturn gobool(c)\n}\n\nfunc (v *Menu) PopupAtMouseCursor(parentMenuShell IMenu, parentMenuItem IMenuItem, button int, activateTime uint32) ", "output": "{\n\twshell := nullableWidget(parentMenuShell)\n\twitem := nullableWidget(parentMenuItem)\n\n\tC.gtk_menu_popup(v.native(),\n\t\twshell,\n\t\twitem,\n\t\tnil,\n\t\tnil,\n\t\tC.guint(button),\n\t\tC.guint32(activateTime))\n}"} {"input": "package packets\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\ntype UnsubackPacket struct {\n\tFixedHeader\n\tMessageID uint16\n}\n\n\nfunc (ua *UnsubackPacket) String() string {\n\tstr := fmt.Sprintf(\"%s\\n\", ua.FixedHeader)\n\tstr += fmt.Sprintf(\"MessageID: %d\", ua.MessageID)\n\treturn str\n}\n\nfunc (ua *UnsubackPacket) Write(w io.Writer) error {\n\tvar err error\n\tua.FixedHeader.RemainingLength = 2\n\tpacket := ua.FixedHeader.pack()\n\tpacket.Write(encodeUint16(ua.MessageID))\n\t_, err = packet.WriteTo(w)\n\n\treturn err\n}\n\n\n\nfunc (ua *UnsubackPacket) Unpack(b io.Reader) error {\n\tua.MessageID = decodeUint16(b)\n\n\treturn nil\n}\n\n\n\nfunc (ua *UnsubackPacket) Details() Details {\n\treturn Details{Qos: 0, MessageID: ua.MessageID}\n}\n\nfunc (ua *UnsubackPacket) Type() byte ", "output": "{\n\treturn ua.FixedHeader.MessageType\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/bfontaine/ephemeral\"\n)\n\n\n\nfunc main() {\n\ts := ephemeral.New()\n\n\ts.HandleFunc(\"/\", done)\n\n\tlog.Println(\"Listening to port 8000...\")\n\tmsg, err := s.Listen(\":8000\")\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: %v\\n\", err)\n\t}\n\tlog.Printf(\"Done. Got '%s'\\n\", msg)\n}\n\nfunc done(s *ephemeral.Server, w http.ResponseWriter, r *http.Request) ", "output": "{\n\tlog.Printf(\"Got a request\")\n\tw.Write([]byte(\"I got you.\\n\"))\n\n\ts.Stop(fmt.Sprintf(\"%s %v\", r.Method, r.URL))\n}"} {"input": "package go_koans\n\nfunc isPrimeNumber(possiblePrime int) bool {\n\tfor underPrime := 2; underPrime < possiblePrime; underPrime++ {\n\t\tif possiblePrime%underPrime == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc findPrimeNumbers(channel chan int) {\n\tfor i := 2; ; i++ {\n\n\t\tassert(i < 100) \n\t}\n}\n\n\n\nfunc aboutConcurrency() ", "output": "{\n\tch := make(chan int)\n\n\tassert(__delete_me__) \n\n\tassert(<-ch == 2)\n\tassert(<-ch == 3)\n\tassert(<-ch == 5)\n\tassert(<-ch == 7)\n\tassert(<-ch == 11)\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\n\n\nfunc naclClose(fd int) (err error) {\n\t_, _, e1 := Syscall(sys_close, uintptr(fd), 0, 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc Exit(code int) (err error) {\n\t_, _, e1 := Syscall(sys_exit, uintptr(code), 0, 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclFstat(fd int, stat *Stat_t) (err error) {\n\t_, _, e1 := Syscall(sys_fstat, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclRead(fd int, b []byte) (n int, err error) {\n\tvar _p0 unsafe.Pointer\n\tif len(b) > 0 {\n\t\t_p0 = unsafe.Pointer(&b[0])\n\t} else {\n\t\t_p0 = unsafe.Pointer(&_zero)\n\t}\n\tr0, _, e1 := Syscall(sys_read, uintptr(fd), uintptr(_p0), uintptr(len(b)))\n\tn = int(r0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclSeek(fd int, off *int64, whence int) (err error) {\n\t_, _, e1 := Syscall(sys_lseek, uintptr(fd), uintptr(unsafe.Pointer(off)), uintptr(whence))\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\n\n\nfunc naclGetRandomBytes(b []byte) (err error) ", "output": "{\n\tvar _p0 unsafe.Pointer\n\tif len(b) > 0 {\n\t\t_p0 = unsafe.Pointer(&b[0])\n\t} else {\n\t\t_p0 = unsafe.Pointer(&_zero)\n\t}\n\t_, _, e1 := Syscall(sys_get_random_bytes, uintptr(_p0), uintptr(len(b)), 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}"} {"input": "package grafana\n\nimport \"github.com/aporeto-inc/grafanaclient\"\n\n\n\n\n\nfunc DefaultSelectAttribute() grafanaclient.Select {\n\treturn grafanaclient.Select{}\n}\n\nfunc DefaultRow() grafanaclient.Row ", "output": "{\n\treturn grafanaclient.Row{Height: \"\"}\n}"} {"input": "package parser\n\nimport \"bytes\"\n\n\ntype DropBehavior int\n\n\nconst (\n\tDropDefault DropBehavior = iota\n\tDropRestrict\n\tDropCascade\n)\n\nvar dropBehaviorName = [...]string{\n\tDropDefault: \"\",\n\tDropRestrict: \"RESTRICT\",\n\tDropCascade: \"CASCADE\",\n}\n\nfunc (d DropBehavior) String() string {\n\treturn dropBehaviorName[d]\n}\n\n\ntype DropDatabase struct {\n\tName Name\n\tIfExists bool\n}\n\n\nfunc (node *DropDatabase) Format(buf *bytes.Buffer, f FmtFlags) {\n\tbuf.WriteString(\"DROP DATABASE \")\n\tif node.IfExists {\n\t\tbuf.WriteString(\"IF EXISTS \")\n\t}\n\tFormatNode(buf, f, node.Name)\n}\n\n\ntype DropIndex struct {\n\tIndexList TableNameWithIndexList\n\tIfExists bool\n\tDropBehavior DropBehavior\n}\n\n\n\n\n\ntype DropTable struct {\n\tNames QualifiedNames\n\tIfExists bool\n\tDropBehavior DropBehavior\n}\n\n\nfunc (node *DropTable) Format(buf *bytes.Buffer, f FmtFlags) {\n\tbuf.WriteString(\"DROP TABLE \")\n\tif node.IfExists {\n\t\tbuf.WriteString(\"IF EXISTS \")\n\t}\n\tFormatNode(buf, f, node.Names)\n\tif node.DropBehavior != DropDefault {\n\t\tbuf.WriteByte(' ')\n\t\tbuf.WriteString(node.DropBehavior.String())\n\t}\n}\n\nfunc (node *DropIndex) Format(buf *bytes.Buffer, f FmtFlags) ", "output": "{\n\tbuf.WriteString(\"DROP INDEX \")\n\tif node.IfExists {\n\t\tbuf.WriteString(\"IF EXISTS \")\n\t}\n\tFormatNode(buf, f, node.IndexList)\n\tif node.DropBehavior != DropDefault {\n\t\tbuf.WriteByte(' ')\n\t\tbuf.WriteString(node.DropBehavior.String())\n\t}\n}"} {"input": "package cmd\n\n\nimport (\n\t\"fmt\"\n\t\"github.com/madhusudhancs/redis/cache\"\n\t\"strings\"\n)\n\nvar (\n\tcommands map[string]RunFunc\n)\n\nfunc init() {\n\tcommands = make(map[string]RunFunc)\n}\n\n\ntype Command struct {\n\tName string\n\tOptions []string\n}\n\n\n\n\ntype RunFunc func(options []string, cache *cache.Cache) ([]byte, bool)\n\n\nfunc Register(cmdName string, runFunc RunFunc) error {\n\tif _, ok := commands[cmdName]; ok {\n\t\treturn fmt.Errorf(\"command with name %s already registered\", cmdName)\n\t}\n\n\tcommands[cmdName] = runFunc\n\treturn nil\n}\n\n\nfunc ExecuteCmd(cmd Command, cache *cache.Cache) ([]byte, bool) {\n\trunFunc, ok := commands[cmd.Name]\n\tif !ok {\n\t\treturn GetErrMsg(fmt.Sprintf(\"ERR unknown command '%s'\", cmd.Name)), false\n\t}\n\n\treturn runFunc(cmd.Options, cache)\n}\n\nfunc NewCommand(req string) (Command, error) ", "output": "{\n\tfields := strings.Fields(req)\n\n\tif len(fields) == 0 {\n\t\treturn Command{}, fmt.Errorf(\"Invalid command\")\n\t}\n\n\tcommand := Command{}\n\tcommand.Name = strings.ToUpper(fields[0])\n\tcommand.Options = fields[1:]\n\n\tfor i, option := range command.Options {\n\t\tcommand.Options[i] = strings.Replace(option, `\"`, \"\", -1)\n\t}\n\n\treturn command, nil\n}"} {"input": "package secure\n\nimport (\n\t\"github.com/go-kit/kit/metrics\"\n\tgokitprometheus \"github.com/go-kit/kit/metrics/prometheus\"\n\t\"github.com/xmidt-org/webpa-common/xmetrics\"\n)\n\n\nconst (\n\tJWTValidationReasonCounter = \"jwt_validation_reason\"\n\tNBFHistogram = \"jwt_from_nbf_seconds\"\n\tEXPHistogram = \"jwt_from_exp_seconds\"\n)\n\n\n\n\n\ntype JWTValidationMeasures struct {\n\tNBFHistogram *gokitprometheus.Histogram\n\tExpHistogram *gokitprometheus.Histogram\n\tValidationReason metrics.Counter\n}\n\n\nfunc NewJWTValidationMeasures(r xmetrics.Registry) *JWTValidationMeasures {\n\treturn &JWTValidationMeasures{\n\t\tNBFHistogram: gokitprometheus.NewHistogram(r.NewHistogramVec(NBFHistogram)),\n\t\tExpHistogram: gokitprometheus.NewHistogram(r.NewHistogramVec(EXPHistogram)),\n\t\tValidationReason: r.NewCounter(JWTValidationReasonCounter),\n\t}\n}\n\nfunc Metrics() []xmetrics.Metric ", "output": "{\n\treturn []xmetrics.Metric{\n\t\txmetrics.Metric{\n\t\t\tName: JWTValidationReasonCounter,\n\t\t\tType: xmetrics.CounterType,\n\t\t\tHelp: \"Counter for validation resolutions per reason\",\n\t\t\tLabelNames: []string{\"reason\"},\n\t\t},\n\t\txmetrics.Metric{\n\t\t\tName: NBFHistogram,\n\t\t\tType: xmetrics.HistogramType,\n\t\t\tHelp: \"Difference (in seconds) between time of JWT validation and nbf (including leeway)\",\n\t\t\tBuckets: []float64{-61, -11, -2, -1, 0, 9, 60}, \n\t\t},\n\t\txmetrics.Metric{\n\t\t\tName: EXPHistogram,\n\t\t\tType: xmetrics.HistogramType,\n\t\t\tHelp: \"Difference (in seconds) between time of JWT validation and exp (including leeway)\",\n\t\t\tBuckets: []float64{-61, -11, -2, -1, 0, 9, 60},\n\t\t},\n\t}\n}"} {"input": "package pdf417\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\n\t\"github.com/boombuler/barcode\"\n\t\"github.com/boombuler/barcode/utils\"\n)\n\ntype pdfBarcode struct {\n\tdata string\n\twidth int\n\tcode *utils.BitList\n}\n\nfunc (c *pdfBarcode) Metadata() barcode.Metadata {\n\treturn barcode.Metadata{barcode.TypePDF, 2}\n}\n\n\n\nfunc (c *pdfBarcode) ColorModel() color.Model {\n\treturn color.Gray16Model\n}\n\nfunc (c *pdfBarcode) Bounds() image.Rectangle {\n\theight := c.code.Len() / c.width\n\n\treturn image.Rect(0, 0, c.width, height*moduleHeight)\n}\n\nfunc (c *pdfBarcode) At(x, y int) color.Color {\n\tif c.code.GetBit((y/moduleHeight)*c.width + x) {\n\t\treturn color.Black\n\t}\n\treturn color.White\n}\n\nfunc (c *pdfBarcode) Content() string ", "output": "{\n\treturn c.data\n}"} {"input": "package devops\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" devops/2019-07-01-preview\"\n}"} {"input": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/BurntSushi/toml\"\n\t\"github.com/absolute8511/nsq/nsqd\"\n\t\"github.com/mreiferson/go-options\"\n)\n\n\n\nfunc TestConfigFlagParsing(t *testing.T) ", "output": "{\n\topts := nsqd.NewOptions()\n\topts.Logger = nil\n\n\tflagSet := nsqdFlagSet(opts)\n\tflagSet.Parse([]string{})\n\n\tvar cfg config\n\tf, err := os.Open(\"../../contrib/nsqd.cfg.example\")\n\tif err != nil {\n\t\tt.Fatalf(\"%s\", err)\n\t}\n\ttoml.DecodeReader(f, &cfg)\n\tcfg.Validate()\n\n\toptions.Resolve(opts, flagSet, cfg)\n\tnsqd.New(opts)\n\n\tif opts.TLSMinVersion != tls.VersionTLS10 {\n\t\tt.Errorf(\"min %#v not expected %#v\", opts.TLSMinVersion, tls.VersionTLS10)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\nfunc ponger(c chan string) {\n\tfor i := 0; ; i++ {\n\t\tc <- \"pong\"\n\t}\n}\n\nfunc printer(c chan string) {\n\tfor {\n\t\tmsg := <-c\n\t\tfmt.Println(msg)\n\t\ttime.Sleep(time.Second * 1)\n\t}\n}\n\nfunc main() {\n\tvar c chan string = make(chan string)\n\n\tgo pinger(c)\n\tgo ponger(c)\n\tgo printer(c)\n\n\tvar input string\n\tfmt.Scanln(&input)\n}\n\nfunc pinger(c chan string) ", "output": "{\n\tfor i := 0; ; i++ {\n\t\tc <- \"ping\"\n\t}\n}"} {"input": "package mem\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\tm \"github.com/mohae/joefriday/sysinfo/mem\"\n)\n\nfunc TestSerializeDeserialize(t *testing.T) {\n\tp, err := Get()\n\tif err != nil {\n\t\tt.Errorf(\"got %s, want nil\", err)\n\t\treturn\n\t}\n\tinf, err := Deserialize(p)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error: %s\", err)\n\t\treturn\n\t}\n\tcheckMemInfo(\"get\", inf, t)\n}\n\n\n\nfunc checkMemInfo(n string, inf *m.MemInfo, t *testing.T) {\n\tif inf.Timestamp == 0 {\n\t\tt.Errorf(\"%s: expected the Timestamp to be non-zero, was 0\", n)\n\t}\n\tif inf.TotalRAM == 0 {\n\t\tt.Errorf(\"%s: expected the TotalRAM to be non-zero, was 0\", n)\n\t}\n\tif inf.FreeRAM == 0 {\n\t\tt.Errorf(\"%s: expected the FreeRAM to be non-zero, was 0\", n)\n\t}\n\tt.Logf(\"%#v\\n\", inf)\n}\n\nfunc BenchmarkGet(b *testing.B) {\n\tvar tmp []byte\n\tfor i := 0; i < b.N; i++ {\n\t\ttmp, _ = Get()\n\t}\n\t_ = tmp\n}\n\nvar inf *m.MemInfo\n\nfunc BenchmarkDeserialize(b *testing.B) {\n\tp, _ := Get()\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tinf, _ = Deserialize(p)\n\t}\n\t_ = inf\n}\n\nfunc TestTicker(t *testing.T) ", "output": "{\n\ttkr, err := NewTicker(time.Millisecond)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\ttk := tkr.(*Ticker)\n\tfor i := 0; i < 5; i++ {\n\t\tselect {\n\t\tcase <-tk.Done:\n\t\t\tbreak\n\t\tcase p, ok := <-tk.Data:\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tinf, err := Deserialize(p)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"unexpected error: %s\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcheckMemInfo(\"ticker\", inf, t)\n\t\tcase err := <-tk.Errs:\n\t\t\tt.Errorf(\"unexpected error: %s\", err)\n\t\t}\n\t}\n\ttk.Stop()\n\ttk.Close()\n}"} {"input": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"time\"\n)\n\ntype TLSConnection struct {\n\thost string\n\tcertPool *x509.CertPool\n\tconn *tls.Conn\n}\n\nfunc NewTLSConnection(host string) (*TLSConnection, error) {\n\tc := &TLSConnection{}\n\tc.host = host\n\tc.getCerts()\n\terr := c.Connect()\n\treturn c, err\n}\n\nfunc (c *TLSConnection) Connect() (err error) {\n\tc.conn, err = tls.Dial(\"tcp\", c.host, &tls.Config{\n\t\tRootCAs: c.certPool,\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\tc.conn.SetWriteDeadline(time.Time{})\n\treturn\n}\n\nfunc (c *TLSConnection) WriteString(s string) (n int, err error) {\n\treturn io.WriteString(c.conn, s)\n}\n\n\n\nfunc (c *TLSConnection) Close() error {\n\treturn c.conn.Close()\n}\n\nfunc (c *TLSConnection) getCerts() {\n\tc.certPool = x509.NewCertPool()\n\tcert, err := ioutil.ReadFile(certsPemFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif !c.certPool.AppendCertsFromPEM(cert) {\n\t\tlog.Fatal(\"Failed parsing root certificate\")\n\t}\n}\n\nfunc (c *TLSConnection) Write(p []byte) (n int, err error) ", "output": "{\n\treturn c.conn.Write(p)\n}"} {"input": "package migrations\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n)\n\n\n\nfunc withTransaction(db *sql.DB, handler func(tx *sql.Tx) error) error {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"beginning transaction: %s\", err.Error())\n\t}\n\n\thandleErr := handler(tx)\n\tif handleErr != nil {\n\t\tif err := tx.Rollback(); err != nil {\n\t\t\treturn fmt.Errorf(\"handler AND rollback failed: %s (rollback error: %s)\", handleErr.Error(), err.Error())\n\t\t}\n\t\treturn fmt.Errorf(\"handler failed: %s\", handleErr.Error())\n\t}\n\n\tif err := tx.Commit(); err != nil {\n\t\treturn fmt.Errorf(\"commit failed: %s\", err.Error())\n\t}\n\n\treturn nil\n}\n\nfunc writeRepoVer(repoPath string, version int) error {\n\tf1, err := os.Create(path.Join(repoPath, \"repover\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = f1.Write([]byte(strconv.Itoa(version)))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f1.Close()\n}\n\nfunc writeIPFSVer(repoPath string, version int) error {\n\tf1, err := os.Create(path.Join(repoPath, \"version\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = f1.Write([]byte(strconv.Itoa(version)))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f1.Close()\n}\n\nfunc OpenDB(repoPath string, dbPassword string, testnet bool) (*sql.DB, error) ", "output": "{\n\tvar dbPath string\n\tif testnet {\n\t\tdbPath = path.Join(repoPath, \"datastore\", \"testnet.db\")\n\t} else {\n\t\tdbPath = path.Join(repoPath, \"datastore\", \"mainnet.db\")\n\t}\n\tdb, err := sql.Open(\"sqlite3\", dbPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif dbPassword != \"\" {\n\t\tp := \"pragma key='\" + dbPassword + \"';\"\n\t\t_, err = db.Exec(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn db, nil\n}"} {"input": "package k3s\n\nimport (\n\tclientset \"github.com/rancher/k3s/pkg/generated/clientset/versioned\"\n\tv1 \"github.com/rancher/k3s/pkg/generated/controllers/k3s.cattle.io/v1\"\n\tinformers \"github.com/rancher/k3s/pkg/generated/informers/externalversions/k3s.cattle.io\"\n\t\"github.com/rancher/wrangler/pkg/generic\"\n)\n\ntype Interface interface {\n\tV1() v1.Interface\n}\n\ntype group struct {\n\tcontrollerManager *generic.ControllerManager\n\tinformers informers.Interface\n\tclient clientset.Interface\n}\n\n\nfunc New(controllerManager *generic.ControllerManager, informers informers.Interface,\n\tclient clientset.Interface) Interface {\n\treturn &group{\n\t\tcontrollerManager: controllerManager,\n\t\tinformers: informers,\n\t\tclient: client,\n\t}\n}\n\n\n\nfunc (g *group) V1() v1.Interface ", "output": "{\n\treturn v1.New(g.controllerManager, g.client.K3sV1(), g.informers.V1())\n}"} {"input": "package cache\n\nimport (\n\t\"github.com/open-falcon/hbs/db\"\n\t\"sync\"\n)\n\n\ntype SafeHostGroupsMap struct {\n\tsync.RWMutex\n\tM map[int][]int\n}\n\nvar HostGroupsMap = &SafeHostGroupsMap{M: make(map[int][]int)}\n\n\n\nfunc (this *SafeHostGroupsMap) Init() {\n\tm, err := db.QueryHostGroups()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tthis.Lock()\n\tdefer this.Unlock()\n\tthis.M = m\n}\n\nfunc (this *SafeHostGroupsMap) GetGroupIds(hid int) ([]int, bool) ", "output": "{\n\tthis.RLock()\n\tdefer this.RUnlock()\n\tgids, exists := this.M[hid]\n\treturn gids, exists\n}"} {"input": "package portmapper\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/golang/glog\"\n)\n\ntype PortMap struct {\n\tcontainerIP string\n\tcontainerPort int\n}\n\nfunc newPortMap(containerip string, containerport int) *PortMap {\n\treturn &PortMap{\n\t\tcontainerIP: containerip,\n\t\tcontainerPort: containerport,\n\t}\n}\n\ntype PortSet map[int]*PortMap\n\ntype PortMapper struct {\n\ttcpMap PortSet\n\tudpMap PortSet\n\tmutex sync.Mutex\n}\n\n\n\nfunc (p *PortMapper) AllocateMap(protocol string, hostPort int,\n\tcontainerIP string, ContainerPort int) error {\n\tp.mutex.Lock()\n\tdefer p.mutex.Unlock()\n\n\tvar pset PortSet\n\n\tif strings.EqualFold(protocol, \"udp\") {\n\t\tpset = p.udpMap\n\t} else {\n\t\tpset = p.tcpMap\n\t}\n\n\te, ok := pset[hostPort]\n\tif ok {\n\t\treturn fmt.Errorf(\"Host port %d had already been used, %s %d\",\n\t\t\thostPort, e.containerIP, e.containerPort)\n\t}\n\n\tallocated := newPortMap(containerIP, ContainerPort)\n\tpset[hostPort] = allocated\n\n\treturn nil\n}\n\nfunc (p *PortMapper) ReleaseMap(protocol string, hostPort int) error {\n\tp.mutex.Lock()\n\tdefer p.mutex.Unlock()\n\n\tvar pset PortSet\n\n\tif strings.EqualFold(protocol, \"udp\") {\n\t\tpset = p.udpMap\n\t} else {\n\t\tpset = p.tcpMap\n\t}\n\n\t_, ok := pset[hostPort]\n\tif !ok {\n\t\tglog.Errorf(\"Host port %d has not been used\", hostPort)\n\t}\n\n\tdelete(pset, hostPort)\n\treturn nil\n}\n\nfunc New() *PortMapper ", "output": "{\n\treturn &PortMapper{PortSet{}, PortSet{}, sync.Mutex{}}\n}"} {"input": "package iam\n\nimport (\n\ttimestamp \"github.com/golang/protobuf/ptypes/timestamp\"\n)\n\ntype CreateIamTokenRequest_Identity = isCreateIamTokenRequest_Identity\n\nfunc (m *CreateIamTokenRequest) SetIdentity(v CreateIamTokenRequest_Identity) {\n\tm.Identity = v\n}\n\nfunc (m *CreateIamTokenRequest) SetYandexPassportOauthToken(v string) {\n\tm.Identity = &CreateIamTokenRequest_YandexPassportOauthToken{\n\t\tYandexPassportOauthToken: v,\n\t}\n}\n\nfunc (m *CreateIamTokenRequest) SetJwt(v string) {\n\tm.Identity = &CreateIamTokenRequest_Jwt{\n\t\tJwt: v,\n\t}\n}\n\n\n\nfunc (m *CreateIamTokenResponse) SetExpiresAt(v *timestamp.Timestamp) {\n\tm.ExpiresAt = v\n}\n\nfunc (m *CreateIamTokenResponse) SetIamToken(v string) ", "output": "{\n\tm.IamToken = v\n}"} {"input": "package handlers\n\nimport (\n\t\"time\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/emicklei/go-restful\"\n\t\"github.com/quintilesims/layer0/common/config\"\n)\n\nfunc LogRequest(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {\n\tstart := time.Now()\n\tchain.ProcessFilter(req, resp)\n\tduration := time.Since(start)\n\n\tif req.Request.URL.String() != \"/health\" {\n\t\tlogrus.Infof(\"request %s %s (%v) %v\", req.Request.Method, req.Request.URL, resp.StatusCode(), duration)\n\t}\n}\n\nfunc AddVersionHeader(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {\n\tresp.AddHeader(\"Version\", config.APIVersion())\n\tchain.ProcessFilter(req, resp)\n}\n\n\n\nfunc EnableCORS(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) ", "output": "{\n\tif origin := req.Request.Header.Get(\"Origin\"); origin != \"\" {\n\t\tresp.AddHeader(\"Access-Control-Allow-Origin\", origin)\n\t\tresp.AddHeader(\"Access-Control-Allow-Credentials\", \"true\")\n\t\tresp.AddHeader(\"Access-Control-Allow-Headers\", \"Origin, Content-Type, X-Auth-Token, Authorization\")\n\t}\n\n\tchain.ProcessFilter(req, resp)\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\n\t\"gopkg.in/stretchr/testify.v1/mock\"\n)\n\ntype Printer interface {\n\tHelp()\n\tVersion()\n\tMessage(msg string)\n\tError(err error)\n\tCommands()\n}\n\ntype TextPrinter struct {\n\tversion string\n}\n\nfunc NewTextPrinter(version string) *TextPrinter {\n\treturn &TextPrinter{version}\n}\n\nfunc (p *TextPrinter) Help() {\n\thelpText := `Name:\n\tfiz - a file wizard\n\nVersion:\n\t` + p.version + `\n\nUsage:\n\tfiz \n\n`\n\tp.Message(helpText)\n\tp.Commands()\n}\n\n\n\nfunc (p *TextPrinter) Message(msg string) {\n\tfmt.Print(msg)\n}\n\nfunc (p *TextPrinter) Error(err error) {\n\tfmt.Println(\"Error: \", err)\n}\n\nfunc (p *TextPrinter) Commands() {\n\tp.Message(COMMANDS_MSG)\n}\n\n\ntype MockPrinter struct {\n\tmock.Mock\n}\n\nfunc NewMockPrinter() *MockPrinter {\n\treturn &MockPrinter{}\n}\n\nfunc (m *MockPrinter) Help() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Version() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Message(msg string) {\n\tm.Called(msg)\n}\n\nfunc (m *MockPrinter) Error(err error) {\n\tm.Called(err)\n}\n\nfunc (m *MockPrinter) Commands() {\n\tm.Called()\n}\n\nfunc (p *TextPrinter) Version() ", "output": "{\n\tfmt.Println(\"fiz\", p.version)\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n)\n\n\n\nfunc sanitizeName(filename string, ext string) string {\n\tfilename = strings.TrimSuffix(filename, \".\"+ext)\n\n\tfor _, s := range []string{\"_\", \"-\", \".\"} {\n\t\tfilename = strings.Replace(filename, s, \" \", -1)\n\t}\n\n\treturn strings.Title(filename)\n}\n\nfunc addSound(p string, info os.FileInfo, err error) error {\n\tcheckErr(err)\n\tif info.IsDir() == false {\n\t\tfor _, ext := range conf.AllowedFormats {\n\t\t\tif strings.HasSuffix(p, \".\"+ext) {\n\t\t\t\tname := strings.TrimPrefix(p, conf.Sounds+\"/\")\n\t\t\t\tsnippets = append(snippets, sound{sanitizeName(name, ext), name})\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc checkErr(err error) ", "output": "{\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"input": "package scheduler\n\nimport (\n\t\"github.com/cnaize/kubernetes/pkg/api\"\n)\n\n\ntype FitPredicate func(pod api.Pod, existingPods []api.Pod, node string) (bool, error)\n\n\ntype HostPriority struct {\n\thost string\n\tscore int\n}\n\ntype HostPriorityList []HostPriority\n\nfunc (h HostPriorityList) Len() int {\n\treturn len(h)\n}\n\nfunc (h HostPriorityList) Less(i, j int) bool {\n\tif h[i].score == h[j].score {\n\t\treturn h[i].host < h[j].host\n\t}\n\treturn h[i].score < h[j].score\n}\n\n\n\ntype PriorityFunction func(pod api.Pod, podLister PodLister, minionLister MinionLister) (HostPriorityList, error)\n\ntype PriorityConfig struct {\n\tFunction PriorityFunction\n\tWeight int\n}\n\nfunc (h HostPriorityList) Swap(i, j int) ", "output": "{\n\th[i], h[j] = h[j], h[i]\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/gogo/protobuf/proto\"\n\tpeer \"github.com/libp2p/go-libp2p-core/peer\"\n\tpubsub \"github.com/libp2p/go-libp2p-pubsub\"\n)\n\nvar handles = map[string]string{}\n\nconst pubsubTopic = \"/libp2p/example/chat/1.0.0\"\n\nfunc pubsubMessageHandler(id peer.ID, msg *SendMessage) {\n\thandle, ok := handles[id.String()]\n\tif !ok {\n\t\thandle = id.ShortString()\n\t}\n\tfmt.Printf(\"%s: %s\\n\", handle, msg.Data)\n}\n\nfunc pubsubUpdateHandler(id peer.ID, msg *UpdatePeer) {\n\toldHandle, ok := handles[id.String()]\n\tif !ok {\n\t\toldHandle = id.ShortString()\n\t}\n\thandles[id.String()] = string(msg.UserHandle)\n\tfmt.Printf(\"%s -> %s\\n\", oldHandle, msg.UserHandle)\n}\n\n\n\nfunc pubsubHandler(ctx context.Context, sub *pubsub.Subscription) ", "output": "{\n\tdefer sub.Cancel()\n\tfor {\n\t\tmsg, err := sub.Next(ctx)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tcontinue\n\t\t}\n\n\t\treq := &Request{}\n\t\terr = proto.Unmarshal(msg.Data, req)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch *req.Type {\n\t\tcase Request_SEND_MESSAGE:\n\t\t\tpubsubMessageHandler(msg.GetFrom(), req.SendMessage)\n\t\tcase Request_UPDATE_PEER:\n\t\t\tpubsubUpdateHandler(msg.GetFrom(), req.UpdatePeer)\n\t\t}\n\t}\n}"} {"input": "package surl\n\nimport \"github.com/stretchr/testify/mock\"\n\ntype MockTicketer struct {\n\tmock.Mock\n}\n\n\n\nfunc (self *MockTicketer) Next() string ", "output": "{\n\targs := self.Called()\n\treturn args.String(0)\n}"} {"input": "package jsons\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\n\ntype FileReader struct {\n\tfilename string\n\tf io.WriteCloser\n\tr *Reader\n}\n\n\n\nfunc NewFileReader(filename string) *FileReader {\n\treturn &FileReader{filename: filename}\n}\n\n\n\nfunc (fr *FileReader) Open() error {\n\tf, err := os.Open(fr.filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfr.f = f\n\tfr.r = NewReader(f)\n\treturn nil\n}\n\n\n\n\n\n\nfunc (fr *FileReader) Next(v interface{}) error {\n\treturn fr.r.Next(v)\n}\n\nfunc (fr *FileReader) Close() error ", "output": "{\n\treturn fr.f.Close()\n}"} {"input": "package chunks\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\n\t\"github.com/rtmfpew/amfy/vlu\"\n)\n\nconst BufferProbeChunkType = 0x18\n\n\ntype BufferProbeChunk struct {\n\tFlowID vlu.Vlu\n}\n\nfunc (chnk *BufferProbeChunk) Type() byte {\n\treturn BufferProbeChunkType\n}\n\nfunc (chnk *BufferProbeChunk) Len() uint16 {\n\treturn 1 + uint16(chnk.FlowID.ByteLength())\n}\n\nfunc (chnk *BufferProbeChunk) WriteTo(buffer *bytes.Buffer) error {\n\n\terr := buffer.WriteByte(chnk.Type())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = binary.Write(buffer, binary.BigEndian, chnk.Len()-1); err != nil {\n\t\treturn err\n\t}\n\n\tif err = chnk.FlowID.WriteTo(buffer); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (chnk *BufferProbeChunk) ReadFrom(buffer *bytes.Buffer) error ", "output": "{\n\n\tlength := uint16(0)\n\terr := binary.Read(buffer, binary.BigEndian, &length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = chnk.FlowID.ReadFrom(buffer); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package trueskill\n\nimport (\n\t\"errors\"\n\t\"math\"\n)\n\nconst (\n\tDefMu = 25.0\n\n\tDefSig = DefMu / 3\n\n\tDefBeta = DefSig / 2\n\n\tDefTau = DefSig / 100\n)\n\n\ntype Game struct {\n\tbeta float64\n\ttau float64\n\tpDraw float64\n}\n\n\nfunc NewDefaultGame() Game {\n\treturn NewGame(DefBeta, DefTau, 0)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (g *Game) CalcNewRatings(teams []Team, ranks []int) (t []Team, err error) {\n\treturn\n}\n\n\n\nfunc (g *Game) CalcMatchQuality(teams []Team) (result float64, err error) {\n\tif len(teams) > 2 {\n\t\terr = errors.New(\"CalcMatchQuality does not support more than 2 teams yet.\")\n\t\treturn\n\t}\n\n\tnPlayers := float64(teams[0].Size() + teams[1].Size())\n\n\tt1Mean := teams[0].GetMu()\n\tt1Var := teams[0].GetVar()\n\tt2Mean := teams[1].GetMu()\n\tt2Var := teams[1].GetVar()\n\n\tsqrt := math.Sqrt(\n\t\t(nPlayers * g.beta * g.beta) /\n\t\t\t(nPlayers*g.beta*g.beta + t1Var + t2Var))\n\n\texp := math.Exp(\n\t\t-1 * (t1Mean - t2Mean) * (t1Mean - t2Mean) /\n\t\t\t(2 * (nPlayers*g.beta*g.beta + t1Var + t2Var)))\n\n\tresult = sqrt * exp\n\treturn\n}\n\nfunc NewGame(beta, tau, pDraw float64) Game ", "output": "{\n\treturn Game{\n\t\tbeta: beta,\n\t\ttau: tau,\n\t\tpDraw: pDraw,\n\t}\n}"} {"input": "package main\n\nimport ()\n\ntype channel struct {\n\tpath string\n\tqueue queue\n\tconnections connections\n\th *hub\n}\n\ntype connections map[*connection]interface {\n}\n\nfunc (c *channel) run() {\n\tincr(\"channels\", 1)\n\tdefer c.stop()\n\tfor cmd := range c.queue {\n\t\tswitch cmd.cmd {\n\t\tcase SUBSCRIBE:\n\t\t\tc.subscribe(cmd.conn)\n\t\tcase UNSUBSCRIBE:\n\t\t\tc.unsubscribe(cmd.conn)\n\t\t\tif len(c.connections) == 0 {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase PUBLISH:\n\t\t\tc.publish(cmd.text)\n\t\tcase BROADCAST:\n\t\t\tc.broadcast(cmd.text)\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (c *channel) stop() {\n\tclose(c.queue)\n\tc.h.queue <- command{cmd: REMOVE, path: c.path}\n\tdecr(\"channels\", 1)\n}\n\nfunc (c *channel) subscribe(conn *connection) {\n\tc.connections[conn] = nil\n}\n\nfunc (c *channel) unsubscribe(conn *connection) {\n\tif _, ok := c.connections[conn]; ok {\n\t\tclose(conn.send)\n\t\tdelete(c.connections, conn)\n\t}\n}\n\n\n\nfunc (c *channel) broadcast(text []byte) {\n\tif len(text) == 0 {\n\t\treturn\n\t}\n\tfor conn := range c.connections {\n\t\tselect {\n\t\tcase conn.send <- text:\n\t\tdefault:\n\t\t\tc.unsubscribe(conn)\n\t\t}\n\t}\n}\n\nfunc (c *channel) publish(text []byte) ", "output": "{\n\tif len(text) == 0 {\n\t\treturn\n\t}\n\tc.h.queue <- command{cmd: PUBLISH, path: c.path, text: text}\n}"} {"input": "package graphdriver\n\n\nimport \"C\"\nimport (\n\t\"path/filepath\"\n\t\"unsafe\"\n\n\t\"github.com/docker/docker/pkg/mount\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tFsMagicZfs = FsMagic(0x2fc12fc1)\n)\n\nvar (\n\tpriority = []string{\n\t\t\"zfs\",\n\t}\n\n\tFsNames = map[FsMagic]string{\n\t\tFsMagicZfs: \"zfs\",\n\t}\n)\n\n\nfunc GetFSMagic(rootpath string) (FsMagic, error) {\n\treturn 0, nil\n}\n\ntype fsChecker struct {\n\tt FsMagic\n}\n\nfunc (c *fsChecker) IsMounted(path string) bool {\n\tm, _ := Mounted(c.t, path)\n\treturn m\n}\n\n\n\n\n\n\n\nfunc NewDefaultChecker() Checker {\n\treturn &defaultChecker{}\n}\n\ntype defaultChecker struct {\n}\n\nfunc (c *defaultChecker) IsMounted(path string) bool {\n\tm, _ := mount.Mounted(path)\n\treturn m\n}\n\n\n\nfunc Mounted(fsType FsMagic, mountPath string) (bool, error) {\n\n\tcs := C.CString(filepath.Dir(mountPath))\n\tdefer C.free(unsafe.Pointer(cs))\n\tbuf := C.getstatfs(cs)\n\tdefer C.free(unsafe.Pointer(buf))\n\n\tif (buf.f_basetype[0] != 122) || (buf.f_basetype[1] != 102) || (buf.f_basetype[2] != 115) ||\n\t\t(buf.f_basetype[3] != 0) {\n\t\tlogrus.Debugf(\"[zfs] no zfs dataset found for rootdir '%s'\", mountPath)\n\t\treturn false, ErrPrerequisites\n\t}\n\n\treturn true, nil\n}\n\nfunc NewFsChecker(t FsMagic) Checker ", "output": "{\n\treturn &fsChecker{\n\t\tt: t,\n\t}\n}"} {"input": "package network\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n)\n\nconst (\n\tresolverFileName = \"/etc/resolv.conf\"\n\tclusterDomainEnvKey = \"CLUSTER_DOMAIN\"\n\tdefaultDomainName = \"cluster.local\"\n)\n\nvar (\n\tdomainName = defaultDomainName\n\tonce sync.Once\n)\n\n\n\n\n\n\nfunc GetClusterDomainName() string {\n\tonce.Do(func() {\n\t\tf, err := os.Open(resolverFileName)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tdefer f.Close()\n\t\tdomainName = getClusterDomainName(f)\n\t})\n\treturn domainName\n}\n\nfunc getClusterDomainName(r io.Reader) string {\n\tfor scanner := bufio.NewScanner(r); scanner.Scan(); {\n\t\telements := strings.Split(scanner.Text(), \" \")\n\t\tif elements[0] != \"search\" {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, e := range elements[1:] {\n\t\t\tif strings.HasPrefix(e, \"svc.\") {\n\t\t\t\treturn strings.TrimSuffix(e[4:], \".\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif domain := os.Getenv(clusterDomainEnvKey); len(domain) > 0 {\n\t\treturn domain\n\t}\n\n\treturn defaultDomainName\n}\n\nfunc GetServiceHostname(name, namespace string) string ", "output": "{\n\treturn fmt.Sprintf(\"%s.%s.svc.%s\", name, namespace, GetClusterDomainName())\n}"} {"input": "package process\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Tree interface {\n\tGetParent(pid int) (int, error)\n}\n\ntype tree struct {\n\tprocesses map[int]Process\n}\n\n\n\n\n\nfunc (pt *tree) GetParent(pid int) (int, error) {\n\tproc, ok := pt.processes[pid]\n\tif !ok {\n\t\treturn -1, fmt.Errorf(\"PID %d not found\", pid)\n\t}\n\n\treturn proc.PPID, nil\n}\n\nfunc NewTree(walker Walker) (Tree, error) ", "output": "{\n\tpt := tree{processes: map[int]Process{}}\n\terr := walker.Walk(func(p Process) {\n\t\tpt.processes[p.PID] = p\n\t})\n\n\treturn &pt, err\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/minio/cli\"\n\t\"github.com/minio/mc/pkg/probe\"\n)\n\nvar adminUserSvcAcctRemoveCmd = cli.Command{\n\tName: \"rm\",\n\tUsage: \"Remove a service account\",\n\tAction: mainAdminUserSvcAcctRemove,\n\tOnUsageError: onUsageError,\n\tBefore: setGlobalsFromContext,\n\tFlags: globalFlags,\n\tCustomHelpTemplate: `NAME:\n {{.HelpName}} - {{.Usage}}\n\nUSAGE:\n {{.HelpName}} ALIAS SERVICE-ACCOUNT\n\nFLAGS:\n {{range .VisibleFlags}}{{.}}\n {{end}}\nEXAMPLES:\n 1. Remove the service account 'J123C4ZXEQN8RK6ND35I' from MinIO server.\n {{.Prompt}} {{.HelpName}} myminio/ J123C4ZXEQN8RK6ND35I\n`,\n}\n\n\n\n\n\nfunc mainAdminUserSvcAcctRemove(ctx *cli.Context) error {\n\tcheckAdminUserSvcAcctRemoveSyntax(ctx)\n\n\targs := ctx.Args()\n\taliasedURL := args.Get(0)\n\tsvcAccount := args.Get(1)\n\n\tclient, err := newAdminClient(aliasedURL)\n\tfatalIf(err, \"Unable to initialize admin connection.\")\n\n\te := client.DeleteServiceAccount(globalContext, svcAccount)\n\tfatalIf(probe.NewError(e).Trace(args...), \"Unable to remove a new service account\")\n\n\tprintMsg(svcAcctMessage{\n\t\top: \"ls\",\n\t\tAccessKey: svcAccount,\n\t})\n\n\treturn nil\n}\n\nfunc checkAdminUserSvcAcctRemoveSyntax(ctx *cli.Context) ", "output": "{\n\tif len(ctx.Args()) != 2 {\n\t\tfatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),\n\t\t\t\"Incorrect number of arguments for user svcacct rm command.\")\n\t}\n}"} {"input": "package container\n\nimport (\n\t\"fmt\"\n)\n\nvar (\n\tLoggingEnabled = false\n)\n\n\n\nfunc log(f string, v ...interface{}) ", "output": "{\n\tif LoggingEnabled {\n\t\tfmt.Printf(f+\"\\n\", v...)\n\t}\n}"} {"input": "package stashkins\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/user\"\n\t\"testing\"\n)\n\nfunc TestDirExists(t *testing.T) {\n\tcurrentUser, err := user.Current()\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot get current user: %v\\n\", err)\n\t}\n\n\texists, err := dirExists(currentUser.HomeDir)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error: %v\\n\", err)\n\t}\n\n\tif !exists {\n\t\tt.Fatalf(\"Want true\\n\")\n\t}\n}\n\n\n\nfunc TestDirNotExists(t *testing.T) ", "output": "{\n\tname, err := ioutil.TempDir(\"\", \"tmp-\")\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot create temp dir. Unexpected error: %v\\n\", err)\n\t}\n\tdefer os.RemoveAll(name)\n\n\texists, err := dirExists(name + \"/foo\")\n\tif err != nil {\n\t\tos.RemoveAll(name)\n\t\tt.Fatalf(\"Unexpected error: %v\\n\", err)\n\t}\n\n\tif exists {\n\t\tos.RemoveAll(name)\n\t\tt.Fatalf(\"Want true\\n\")\n\t}\n}"} {"input": "package time\n\nimport (\n\t\"errors\"\n\t\"syscall\"\n)\n\n\nfunc interrupt() {\n}\n\n\n\n\nfunc readFile(name string) ([]byte, error) {\n\tf, err := syscall.Open(name, syscall.O_RDONLY, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer syscall.Close(f)\n\tvar (\n\t\tbuf [4096]byte\n\t\tret []byte\n\t\tn int\n\t)\n\tfor {\n\t\tn, err = syscall.Read(f, buf[:])\n\t\tif n > 0 {\n\t\t\tret = append(ret, buf[:n]...)\n\t\t}\n\t\tif n == 0 || err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ret, err\n}\n\nfunc open(name string) (uintptr, error) {\n\tfd, err := syscall.Open(name, syscall.O_RDONLY, 0)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn uintptr(fd), nil\n}\n\n\n\nfunc preadn(fd uintptr, buf []byte, off int) error {\n\twhence := seekStart\n\tif off < 0 {\n\t\twhence = seekEnd\n\t}\n\tif _, err := syscall.Seek(syscall.Handle(fd), int64(off), whence); err != nil {\n\t\treturn err\n\t}\n\tfor len(buf) > 0 {\n\t\tm, err := syscall.Read(syscall.Handle(fd), buf)\n\t\tif m <= 0 {\n\t\t\tif err == nil {\n\t\t\t\treturn errors.New(\"short read\")\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tbuf = buf[m:]\n\t}\n\treturn nil\n}\n\nfunc closefd(fd uintptr) ", "output": "{\n\tsyscall.Close(syscall.Handle(fd))\n}"} {"input": "package widgets\n\nimport (\n)\n\ntype WidgetCore struct {\n x, y float32\n width, height float32\n}\n\nfunc (wc *WidgetCore) Position()(x, y float32) {\n return wc.x, wc.y\n}\n\nfunc (wc *WidgetCore) SetPosition(x, y float32) {\n wc.x = x\n wc.y = y\n}\n\n\n\ntype Widget interface {\n Position()(x, y float32)\n SetPosition(x, y float32)\n Size()(width, height float32)\n\n Dispose()\n Render()\n OnKey(modifier, key int) bool\n OnMouseClickDown() bool\n OnMouseClickUp() bool\n}\n\nfunc (wc *WidgetCore) Size()(width, height float32) ", "output": "{\n return wc.width, wc.height\n}"} {"input": "package encoding\n\nimport \"gonum.org/v1/gonum/graph\"\n\n\ntype Builder interface {\n\tgraph.Graph\n\tgraph.Builder\n}\n\n\ntype MultiBuilder interface {\n\tgraph.Multigraph\n\tgraph.MultigraphBuilder\n}\n\n\n\ntype AttributeSetter interface {\n\tSetAttribute(Attribute) error\n}\n\n\n\ntype Attributer interface {\n\tAttributes() []Attribute\n}\n\n\ntype Attribute struct {\n\tKey, Value string\n}\n\n\ntype Attributes []Attribute\n\n\nfunc (a *Attributes) Attributes() []Attribute {\n\treturn *a\n}\n\n\n\n\n\n\n\nfunc (a *Attributes) SetAttribute(attr Attribute) error ", "output": "{\n\tif attr.Key == \"\" {\n\t\treturn nil\n\t}\n\tfor i, v := range *a {\n\t\tif v.Key == attr.Key {\n\t\t\tif attr.Value == \"\" {\n\t\t\t\t(*a)[i] = (*a)[len(*a)-1]\n\t\t\t\t*a = (*a)[:len(*a)-1]\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t(*a)[i].Value = attr.Value\n\t\t\treturn nil\n\t\t}\n\t}\n\tif attr.Value != \"\" {\n\t\t*a = append(*a, attr)\n\t}\n\treturn nil\n}"} {"input": "package proxy\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/fsouza/go-dockerclient\"\n\t. \"github.com/weaveworks/weave/common\"\n)\n\ntype createExecInterceptor struct {\n\tclient *docker.Client\n\twithIPAM bool\n}\n\n\n\nfunc (i *createExecInterceptor) InterceptResponse(r *http.Response) error {\n\treturn nil\n}\n\nfunc (i *createExecInterceptor) InterceptRequest(r *http.Request) error ", "output": "{\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.Body.Close()\n\n\toptions := docker.CreateExecOptions{}\n\tif err := json.Unmarshal(body, &options); err != nil {\n\t\treturn err\n\t}\n\n\tcontainer, err := inspectContainerInPath(i.client, r.URL.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif cidrs, ok := weaveCIDRsFromConfig(container.Config); ok || i.withIPAM {\n\t\tInfo.Printf(\"Exec in container %s with WEAVE_CIDR \\\"%s\\\"\", container.ID, strings.Join(cidrs, \" \"))\n\t\tcmd := append(weaveWaitEntrypoint, \"-s\")\n\t\toptions.Cmd = append(cmd, options.Cmd...)\n\t}\n\n\tif err := marshalRequestBody(r, options); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tcounts := make(map[string]int)\n\tnames := make(map[string][]string)\n\tfiles := os.Args[1:]\n\tif len(files) == 0 {\n\t\tcountLines(os.Stdin, counts, names)\n\t} else {\n\t\tfor _, arg := range files {\n\t\t\tf, err := os.Open(arg)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"dup2: %v\\n\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcountLines(f, counts, names)\n\t\t\tf.Close()\n\t\t}\n\t}\n\tfor line, n := range counts {\n\t\tif n > 1 {\n\t\t\tfmt.Printf(\"%s\\n\", line)\n\t\t\tfmt.Printf(\"%s\\n\\n\", names[line])\n\t\t}\n\t}\n}\n\n\n\nfunc contains(s []string, e string) bool {\n\tfor _, a := range s {\n\t\tif a == e {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc countLines(f *os.File, counts map[string]int, names map[string][]string) ", "output": "{\n\tinput := bufio.NewScanner(f)\n\tfor input.Scan() {\n\t\tcounts[input.Text()]++\n\t\tvalue := names[input.Text()]\n\t\tif !contains(value, f.Name()) {\n\t\t\tnames[input.Text()] = append(names[input.Text()], f.Name())\n\t\t}\n\t}\n}"} {"input": "package ghalloc\n\nimport \"unsafe\"\n\ntype slab struct {\n\tslabClass *slabClass \n\tmemory []byte \n\tfull bool \n\tallocated uint64 \n\tchunkMap uint64 \n}\n\n\n\n\nfunc (s *slab) allocChunk() unsafe.Pointer {\n\tif s.full {\n\t\treturn nil\n\t}\n\n\ti := s.getUnusedChunkIndex()\n\tptr := unsafe.Pointer(&s.memory[s.getUnusedChunkIndex()])\n\n\ts.chunkMap |= 1 << i\n\ts.allocated++\n\n\tif s.allocated >= s.slabClass.Capacity {\n\t\ts.full = true\n\t}\n\n\treturn ptr\n}\n\n\nfunc (s *slab) freeChunk(ptr unsafe.Pointer) {\n\tuptr := uintptr(ptr)\n\tbegin := uintptr(unsafe.Pointer(&s.memory[0]))\n\n\tif uptr >= begin && uptr <= uintptr(unsafe.Pointer(&s.memory[0]))+uintptr(s.slabClass.SlabSize) {\n\t\ts.chunkMap &^= 1 << uint64(uptr-begin) % uint64(s.slabClass.SlabSize)\n\n\t\ts.allocated--\n\t\tif s.full {\n\t\t\ts.full = false\n\t\t}\n\t}\n}\n\nfunc (s *slab) getUnusedChunkIndex() uint64 {\n\tvar i uint64\n\n\tfor i = 0; i < s.slabClass.Capacity; i++ {\n\t\tif s.chunkMap&(1<>7) & 7\n}\n\nconst (\n\tControl2GroupAddr ControlField2 = 1 << 7\n\n\tControl2LTEFrame ControlField2 = 1 << 2\n)\n\n\n\n\nfunc Control2Hops(hops uint8) ControlField2 ", "output": "{\n\tif hops > 7 {\n\t\thops = 7\n\t}\n\n\treturn ControlField2(hops&7) << 4\n}"} {"input": "package tendermint\n\nimport (\n\tlog \"github.com/sirupsen/logrus\"\n\t\"github.com/stratumn/go-core/monitoring\"\n\tabci \"github.com/tendermint/abci/types\"\n\tcfg \"github.com/tendermint/tendermint/config\"\n\t\"github.com/tendermint/tendermint/node\"\n\t\"github.com/tendermint/tendermint/proxy\"\n\t\"github.com/tendermint/tendermint/types\"\n\t\"github.com/tendermint/tmlibs/cli/flags\"\n\ttmlog \"github.com/tendermint/tmlibs/log\"\n)\n\n\n\n\n\nfunc NewNode(config *cfg.Config, app abci.Application) *node.Node {\n\tlogger := tmlog.NewTMLogger(log.StandardLogger().Out)\n\tlogger, _ = flags.ParseLogLevel(config.BaseConfig.LogLevel, logger, \"info\")\n\n\tprivValidator := types.LoadOrGenPrivValidatorFS(config.PrivValidatorFile())\n\tret, err := node.NewNode(config,\n\t\tprivValidator,\n\t\tproxy.NewLocalClientCreator(app),\n\t\tnode.DefaultGenesisDocProviderFunc(config),\n\t\tnode.DefaultDBProvider,\n\t\tlogger)\n\tif err != nil {\n\t\tmonitoring.LogEntry().WithError(err).Error(\"Error on new node creation\")\n\t}\n\n\treturn ret\n}\n\nfunc RunNodeForever(config *cfg.Config, app abci.Application) ", "output": "{\n\tnode := NewNode(config, app)\n\terr := node.Start()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tnode.RunForever()\n}"} {"input": "package options\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/apimachinery/pkg/util/errors\"\n\t\"k8s.io/apiserver/pkg/authentication/request/headerrequest\"\n\t\"k8s.io/apiserver/pkg/server/dynamiccertificates\"\n\t\"k8s.io/client-go/kubernetes\"\n)\n\nvar _ dynamiccertificates.ControllerRunner = &DynamicRequestHeaderController{}\nvar _ dynamiccertificates.CAContentProvider = &DynamicRequestHeaderController{}\n\nvar _ headerrequest.RequestHeaderAuthRequestProvider = &DynamicRequestHeaderController{}\n\n\n\ntype DynamicRequestHeaderController struct {\n\t*dynamiccertificates.ConfigMapCAController\n\t*headerrequest.RequestHeaderAuthRequestController\n}\n\n\nfunc newDynamicRequestHeaderController(client kubernetes.Interface) (*DynamicRequestHeaderController, error) {\n\trequestHeaderCAController, err := dynamiccertificates.NewDynamicCAFromConfigMapController(\n\t\t\"client-ca\",\n\t\tauthenticationConfigMapNamespace,\n\t\tauthenticationConfigMapName,\n\t\t\"requestheader-client-ca-file\",\n\t\tclient)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create DynamicCAFromConfigMap controller: %v\", err)\n\t}\n\n\trequestHeaderAuthRequestController := headerrequest.NewRequestHeaderAuthRequestController(\n\t\tauthenticationConfigMapName,\n\t\tauthenticationConfigMapNamespace,\n\t\tclient,\n\t\t\"requestheader-username-headers\",\n\t\t\"requestheader-group-headers\",\n\t\t\"requestheader-extra-headers-prefix\",\n\t\t\"requestheader-allowed-names\",\n\t)\n\treturn &DynamicRequestHeaderController{\n\t\tConfigMapCAController: requestHeaderCAController,\n\t\tRequestHeaderAuthRequestController: requestHeaderAuthRequestController,\n\t}, nil\n}\n\n\n\nfunc (c *DynamicRequestHeaderController) Run(workers int, stopCh <-chan struct{}) {\n\tgo c.ConfigMapCAController.Run(workers, stopCh)\n\tgo c.RequestHeaderAuthRequestController.Run(workers, stopCh)\n\t<-stopCh\n}\n\nfunc (c *DynamicRequestHeaderController) RunOnce() error ", "output": "{\n\terrs := []error{}\n\terrs = append(errs, c.ConfigMapCAController.RunOnce())\n\terrs = append(errs, c.RequestHeaderAuthRequestController.RunOnce())\n\treturn errors.NewAggregate(errs)\n}"} {"input": "package bench\n\nimport (\n\t\"fmt\"\n\t\"github.com/satori/go.uuid\"\n\t. \"github.com/topfreegames/offers/testing\"\n\t\"net/http\"\n\t\"testing\"\n)\n\nvar gameResult *http.Response\n\nfunc BenchmarkListGames(b *testing.B) {\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\troute := getRoute(\"/games\")\n\t\tres, err := get(route)\n\t\tvalidateResp(res, err)\n\t\tres.Body.Close()\n\n\t\tgameResult = res\n\t}\n}\n\n\n\nfunc BenchmarkUpdateGame(b *testing.B) {\n\tdb, err := GetPerfDB()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tgames, err := getGames(&db)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tlength := len(games)\n\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tgame := games[i%length]\n\t\troute := getRoute(fmt.Sprintf(\"/games/%s\", game.ID))\n\t\tres, err := putTo(route, map[string]interface{}{\n\t\t\t\"name\": fmt.Sprintf(\"%s-%d\", game.Name, i),\n\t\t})\n\t\tvalidateResp(res, err)\n\t\tres.Body.Close()\n\n\t\tgameResult = res\n\t}\n}\n\nfunc BenchmarkInsertGame(b *testing.B) ", "output": "{\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\troute := getRoute(fmt.Sprintf(\"/games/%s\", uuid.NewV4().String()))\n\t\tres, err := putTo(route, map[string]interface{}{\n\t\t\t\"name\": fmt.Sprintf(\"game-%d\", i),\n\t\t})\n\t\tvalidateResp(res, err)\n\t\tres.Body.Close()\n\n\t\tgameResult = res\n\t}\n}"} {"input": "package crypto\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc BenchmarkRandom(b *testing.B) {\n\tfor index := 0; index < b.N; index++ {\n\t\tRandom(32)\n\t}\n}\n\nfunc TestEncrypt(t *testing.T) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tConvey(\"auth.Encrypt Test\", t, func() {\n\t\tsecret := Encrypt(src)\n\t\tSo(len(secret), ShouldEqual, 60)\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t})\n}\n\nfunc TestVerify(t *testing.T) {\n\tsrc := \"I'mAPlainSecret\"\n\tConvey(\"auth.Verify Test\", t, func() {\n\t\tfor index := 0; index < 10; index++ {\n\t\t\tsecret := Encrypt(src)\n\t\t\tSo(Verify(src, secret), ShouldBeTrue)\n\t\t}\n\t})\n}\n\nfunc BenchmarkMixin(b *testing.B) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tfor index := 0; index < b.N; index++ {\n\t\tmixin(src)\n\t}\n}\n\nfunc BenchmarkEncrypt(b *testing.B) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tfor index := 0; index < b.N; index++ {\n\t\tEncrypt(src)\n\t}\n}\n\n\n\nfunc BenchmarkVerify(b *testing.B) ", "output": "{\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tsecret := Encrypt(src)\n\tfor index := 0; index < b.N; index++ {\n\t\tVerify(src, secret)\n\t}\n}"} {"input": "package migrations\n\nimport \"github.com/BurntSushi/migration\"\n\n\n\nfunc AddStartTimeToWorkers(tx migration.LimitedTx) error ", "output": "{\n\t_, err := tx.Exec(`\n\t\tALTER TABLE workers\n\t\tADD COLUMN start_time integer;\n`)\n\treturn err\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype helloTransport interface {\n\tConnect(addr string) error\n\tClose() error\n\tRequest(req string) (reply string, err error)\n}\n\ntype transGenerator func() (helloTransport, error)\n\nvar transporter map[string]transGenerator = make(map[string]transGenerator)\n\nfunc registerTransport(id string, gen transGenerator) {\n\ttransporter[id] = gen\n}\n\nfunc transportList() []string {\n\tvar transports = make([]string, 0, len(transporter))\n\tfor id := range transporter {\n\t\ttransports = append(transports, id)\n\t}\n\tsort.StringSlice(transports).Sort()\n\treturn transports\n}\n\n\n\nfunc firstTransport() string {\n\tvar transports = transportList()\n\treturn transports[0]\n}\n\nfunc defaultAddr(addr string) string {\n\treturn fmt.Sprintf(\"%s://%s\", firstTransport(), addr)\n}\n\nfunc newTransport(addr string) (helloTransport, error) {\n\tvar uri, err = url.Parse(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif generate, ok := transporter[uri.Scheme]; ok {\n\t\treturn generate()\n\t}\n\treturn nil, fmt.Errorf(\"invalid transport %q\", uri.Scheme)\n}\n\nfunc availableTransports() string ", "output": "{\n\tvar transports = transportList()\n\treturn strings.Join(transports, \",\")\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\nfunc direntIno(buf []byte) (uint64, bool) {\n\treturn readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino))\n}\n\nfunc direntReclen(buf []byte) (uint64, bool) {\n\treturn readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))\n}\n\n\n\nfunc direntNamlen(buf []byte) (uint64, bool) ", "output": "{\n\treturn readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen))\n}"} {"input": "package token\n\nimport (\n\t\"github.com/dgrijalva/jwt-go\"\n)\n\nconst (\n\tSignerAlgorithm = \"HS256\"\n)\n\ntype SecretFunc func(*Token) (string, error)\n\ntype Token struct {\n\tType string\n\tValue string\n}\n\n\n\n\nfunc ParseToken(tokenStr string, secretFn SecretFunc) (*Token, error) {\n\ttoken := &Token{}\n\tparsedToken, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {\n\n\t\tif t.Method.Alg() != SignerAlgorithm {\n\t\t\treturn nil, jwt.ErrSignatureInvalid\n\t\t}\n\n\t\tclaims := t.Claims.(jwt.MapClaims)\n\t\ttypev, ok := claims[\"type\"]\n\t\tif !ok {\n\t\t\treturn nil, jwt.ValidationError{}\n\t\t}\n\n\t\tval, ok := claims[\"value\"]\n\t\tif !ok {\n\t\t\treturn nil, jwt.ValidationError{}\n\t\t}\n\n\t\ttoken.Type = typev.(string)\n\t\ttoken.Value = val.(string)\n\n\t\tsecret, err := secretFn(token)\n\t\treturn []byte(secret), err\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t} else if !parsedToken.Valid {\n\t\treturn nil, jwt.ValidationError{}\n\t}\n\n\treturn token, nil\n}\n\n\nfunc (t *Token) SignWithExp(secret string, expiration int64) (string, error) {\n\ttoken := jwt.New(jwt.SigningMethodHS256)\n\tclaims := token.Claims.(jwt.MapClaims)\n\n\tclaims[\"type\"] = t.Type\n\tclaims[\"value\"] = t.Value\n\tif expiration > 0 {\n\t\tclaims[\"exp\"] = float64(expiration)\n\t}\n\n\treturn token.SignedString([]byte(secret))\n}\n\nfunc New(t, v string) *Token ", "output": "{\n\treturn &Token{Type: t, Value: v}\n}"} {"input": "package utils\n\nimport (\n\t\"testing\"\n)\n\n\n\n\nfunc TestGetIPv4Addresses(t *testing.T) ", "output": "{\n\tips, err := GetIPv4Addresses()\n\tif err != nil {\n\t\tt.Errorf(\"Failed to get ipv4 addresses: %s\", err)\n\t\tt.Fail()\n\t}\n\n\texpectedMinimumLen := 1\n\tif len(ips) < expectedMinimumLen {\n\t\tt.Errorf(\"minimum IPs expected %d > retrieved %d ips:%v\", expectedMinimumLen, len(ips), ips)\n\t\tt.Fail()\n\t}\n}"} {"input": "package tristate\n\ntype StateValue int\n\nconst (\n\tTRISTATE_SUCCESS StateValue = iota\n\tTRISTATE_FAILRUE\n\tTRISTATE_UNKNOWN\n)\n\ntype TriState struct {\n\tState StateValue\n\tErr error\n}\n\nfunc NewSuccess() *TriState {\n\treturn nil\n}\n\nfunc NewUnknown(err error) *TriState {\n\tif err == nil {\n\t\tpanic(\"error not set\")\n\t}\n\treturn &TriState{TRISTATE_UNKNOWN, err}\n}\n\n\n\nfunc (state *TriState) Error() string {\n\treturn state.Err.Error()\n}\n\nfunc (state *TriState) IsSuccess() bool {\n\treturn state == nil || state.State == TRISTATE_SUCCESS\n}\n\nfunc (state *TriState) IsFailure() bool {\n\treturn state != nil && state.State == TRISTATE_FAILRUE\n}\n\nfunc (state *TriState) IsUnknown() bool {\n\treturn state != nil && state.State == TRISTATE_UNKNOWN\n}\n\nfunc NewFailure(err error) *TriState ", "output": "{\n\tif err == nil {\n\t\tpanic(\"error not set\")\n\t}\n\treturn &TriState{TRISTATE_FAILRUE, err}\n}"} {"input": "package service\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/syncloud/redirect/model\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype ActionsDbStub struct {\n\taction *model.Action\n}\n\nfunc (db *ActionsDbStub) GetAction(_ int64, _ uint64) (*model.Action, error) {\n\treturn db.action, nil\n}\nfunc (db *ActionsDbStub) GetActionByToken(_ string, _ uint64) (*model.Action, error) {\n\treturn db.action, nil\n}\n\nfunc (db *ActionsDbStub) InsertAction(action *model.Action) error {\n\tdb.action = action\n\treturn nil\n}\n\nfunc (db *ActionsDbStub) UpdateAction(action *model.Action) error {\n\tif db.action != nil {\n\t\tdb.action = action\n\t}\n\treturn nil\n}\n\n\n\nfunc (db *ActionsDbStub) DeleteAction(actionId uint64) error {\n\tdb.action = nil\n\treturn nil\n}\n\nfunc TestUpsert(t *testing.T) {\n\n\tdb := &ActionsDbStub{nil}\n\tactions := NewActions(db)\n\n\tuser := &model.User{Id: 1, Email: \"test@example.com\", PasswordHash: \"pass\", Active: true, UpdateToken: \"token\", Timestamp: time.Now()}\n\taction, err := actions.UpsertActivateAction(user.Id)\n\n\tassert.Nil(t, err)\n\tassert.NotNil(t, action)\n\tassert.NotNil(t, db.action)\n}\n\nfunc (db *ActionsDbStub) DeleteActions(_ int64) error ", "output": "{\n\tdb.action = nil\n\treturn nil\n}"} {"input": "package object\n\nimport (\n\t\"hash/fnv\"\n)\n\n\ntype String struct {\n\tValue string\n}\n\n\n\n\n\nfunc (s *String) Inspect() string {\n\treturn s.Value\n}\n\n\nfunc (s *String) HashKey() HashKey {\n\th := fnv.New64a()\n\th.Write([]byte(s.Value))\n\n\treturn HashKey{Type: s.Type(), Value: h.Sum64()}\n}\n\nfunc (s *String) Type() ObjectType ", "output": "{\n\treturn STRING_OBJ\n}"} {"input": "package vsphere\n\nimport (\n\t\"fmt\"\n)\n\nconst BuilderId = \"packer.post-processor.vsphere\"\n\ntype Artifact struct {\n\tfiles []string\n\tdatastore string\n\tvmfolder string\n\tvmname string\n}\n\n\n\nfunc (*Artifact) BuilderId() string {\n\treturn BuilderId\n}\n\nfunc (a *Artifact) Files() []string {\n\treturn a.files\n}\n\nfunc (a *Artifact) Id() string {\n\treturn fmt.Sprintf(\"%s::%s::%s\", a.datastore, a.vmfolder, a.vmname)\n}\n\nfunc (a *Artifact) String() string {\n\treturn fmt.Sprintf(\"VM: %s Folder: %s Datastore: %s\", a.vmname, a.vmfolder, a.datastore)\n}\n\nfunc (*Artifact) State(name string) interface{} {\n\treturn nil\n}\n\nfunc (a *Artifact) Destroy() error {\n\treturn nil\n}\n\nfunc NewArtifact(datastore, vmfolder, vmname string, files []string) *Artifact ", "output": "{\n\treturn &Artifact{\n\t\tfiles: files,\n\t\tdatastore: datastore,\n\t\tvmfolder: vmfolder,\n\t\tvmname: vmname,\n\t}\n}"} {"input": "package migrations\n\nimport (\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"code.cloudfoundry.org/bbs/migration\"\n)\n\nvar migrationsRegistry = migration.Migrations{}\n\nfunc appendMigration(migrationTemplate migration.Migration) {\n\tmigrationsRegistry = append(migrationsRegistry, migrationTemplate)\n}\n\nfunc migrationString(m migration.Migration) string {\n\t_, filename, _, ok := runtime.Caller(1)\n\tif !ok {\n\t\treturn strconv.FormatInt(m.Version(), 10)\n\t}\n\treturn strings.Split(filepath.Base(filename), \".\")[0]\n}\n\n\n\nfunc AllMigrations() migration.Migrations ", "output": "{\n\tmigs := make(migration.Migrations, len(migrationsRegistry))\n\tfor i, mig := range migrationsRegistry {\n\t\trt := reflect.TypeOf(mig)\n\t\tif rt.Kind() == reflect.Ptr {\n\t\t\trt = rt.Elem()\n\t\t}\n\t\tmigs[i] = reflect.New(rt).Interface().(migration.Migration)\n\t}\n\treturn migs\n}"} {"input": "package signal\n\nimport (\n\t\"github.com/idealeak/goserver/core\"\n)\n\nvar Config = Configuration{}\n\ntype Configuration struct {\n\tSupportSignal bool\n}\n\nfunc (c *Configuration) Name() string {\n\treturn \"signal\"\n}\n\n\n\nfunc (c *Configuration) Close() error {\n\treturn nil\n}\n\nfunc init() {\n\tcore.RegistePackage(&Config)\n}\n\nfunc (c *Configuration) Init() error ", "output": "{\n\tif c.SupportSignal {\n\t\tgo SignalHandlerModule.ProcessSignal()\n\t}\n\treturn nil\n}"} {"input": "package popcount\n\n\nvar pc [256]byte\n\nfunc init() {\n\tfor i := range pc {\n\t\tpc[i] = pc[i/2] + byte(i&1)\n\t}\n}\n\n\n\n\nfunc PopCount(x uint64) int ", "output": "{\n\treturn int(pc[byte(x>>(0*8))] +\n\t\tpc[byte(x>>(1*8))] +\n\t\tpc[byte(x>>(2*8))] +\n\t\tpc[byte(x>>(3*8))] +\n\t\tpc[byte(x>>(4*8))] +\n\t\tpc[byte(x>>(5*8))] +\n\t\tpc[byte(x>>(6*8))] +\n\t\tpc[byte(x>>(7*8))])\n}"} {"input": "package ifacetest\n\nimport (\n\t\"github.com/snapcore/snapd/interfaces\"\n\t\"github.com/snapcore/snapd/snap\"\n)\n\n\ntype Specification struct {\n\tSnippets []string\n}\n\n\nfunc (spec *Specification) AddSnippet(snippet string) {\n\tspec.Snippets = append(spec.Snippets, snippet)\n}\n\n\n\n\n\n\n\nfunc (spec *Specification) AddConnectedSlot(iface interfaces.Interface, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error {\n\ttype definer interface {\n\t\tTestConnectedSlot(spec *Specification, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestConnectedSlot(spec, plug, slot)\n\t}\n\treturn nil\n}\n\n\nfunc (spec *Specification) AddPermanentPlug(iface interfaces.Interface, plug *snap.PlugInfo) error {\n\ttype definer interface {\n\t\tTestPermanentPlug(spec *Specification, plug *snap.PlugInfo) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestPermanentPlug(spec, plug)\n\t}\n\treturn nil\n}\n\n\nfunc (spec *Specification) AddPermanentSlot(iface interfaces.Interface, slot *snap.SlotInfo) error {\n\ttype definer interface {\n\t\tTestPermanentSlot(spec *Specification, slot *snap.SlotInfo) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestPermanentSlot(spec, slot)\n\t}\n\treturn nil\n}\n\nfunc (spec *Specification) AddConnectedPlug(iface interfaces.Interface, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error ", "output": "{\n\ttype definer interface {\n\t\tTestConnectedPlug(spec *Specification, plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) error\n\t}\n\tif iface, ok := iface.(definer); ok {\n\t\treturn iface.TestConnectedPlug(spec, plug, slot)\n\t}\n\treturn nil\n}"} {"input": "package s3storage\n\nimport (\n\t\"testing\"\n\n\t\"github.com/AdRoll/goamz/aws\"\n\t\"github.com/AdRoll/goamz/s3\"\n\t\"github.com/AdRoll/goamz/s3/s3test\"\n\t\"github.com/facebookgo/ensure\"\n)\n\n\ntype MockS3 struct {\n\tauth aws.Auth\n\tregion aws.Region\n\tsrv *s3test.Server\n\tconfig *s3test.Config\n}\n\n\n\n\n\nfunc (s *MockS3) Stop() {\n\ts.srv.Quit()\n}\n\n\nfunc NewMockS3(t *testing.T) *MockS3 {\n\tm := MockS3{}\n\tm.Start(t)\n\treturn &m\n}\n\n\nfunc NewStorageWithMockS3(s *MockS3) (*S3Storage, error) {\n\treturn NewS3Storage(s.region, s.auth, \"testbucket\", \"test\", s3.Private)\n}\n\nfunc (s *MockS3) Start(t *testing.T) ", "output": "{\n\tsrv, err := s3test.NewServer(s.config)\n\tensure.Nil(t, err)\n\tensure.NotNil(t, srv)\n\n\ts.srv = srv\n\ts.region = aws.Region{\n\t\tName: \"faux-region-1\",\n\t\tS3Endpoint: srv.URL(),\n\t\tS3LocationConstraint: true, \n\t}\n}"} {"input": "package session\n\nimport (\n\t\"g_server/framework/gnet\"\n)\n\nconst (\n\tsessionEventOpen = 1\n\tsessionEventClose = 2\n\tsessionEventMsg = 3\n)\n\nfunc NewWsSessionManager(name string, host string, maxmsgsize uint32, maxsession uint32, hook func(gnet.ISocket, []byte) bool) *SessionManager {\n\treturn &SessionManager{server: gnet.NewWebSocketServer(host, maxmsgsize), SessionMsgProxy: SessionMsgProxy{msghanders: make(map[uint32]*msgProxy)}, maxsession: maxsession, name: name, hook: hook}\n}\n\n\n\nfunc NewWsSessionClient(name string, curl string, rcontime int32, maxsession uint32) *SessionClient ", "output": "{\n\treturn &SessionClient{BaseSession: BaseSession{ws: gnet.NewWebSocketClient(curl, maxsession)}, SessionMsgProxy: SessionMsgProxy{msghanders: make(map[uint32]*msgProxy)}, rcontime: rcontime, name: name}\n}"} {"input": "package common\n\nimport (\n\t\"encoding/binary\"\n\t\"sort\"\n)\n\n\n\ntype Uint64Slice []uint64\n\nfunc (p Uint64Slice) Len() int { return len(p) }\n\nfunc (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p Uint64Slice) Sort() { sort.Sort(p) }\n\nfunc SearchUint64s(a []uint64, x uint64) int {\n\treturn sort.Search(len(a), func(i int) bool { return a[i] >= x })\n}\n\nfunc (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) }\n\n\n\nfunc PutUint64LE(dest []byte, i uint64) {\n\tbinary.LittleEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64LE(src []byte) uint64 {\n\treturn binary.LittleEndian.Uint64(src)\n}\n\nfunc PutUint64BE(dest []byte, i uint64) {\n\tbinary.BigEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64BE(src []byte) uint64 {\n\treturn binary.BigEndian.Uint64(src)\n}\n\nfunc PutInt64LE(dest []byte, i int64) {\n\tbinary.LittleEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64LE(src []byte) int64 {\n\treturn int64(binary.LittleEndian.Uint64(src))\n}\n\nfunc PutInt64BE(dest []byte, i int64) {\n\tbinary.BigEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64BE(src []byte) int64 {\n\treturn int64(binary.BigEndian.Uint64(src))\n}\n\nfunc (p Uint64Slice) Less(i, j int) bool ", "output": "{ return p[i] < p[j] }"} {"input": "package ioext\n\nimport \"io\"\n\n\n\n\n\ntype offsetReader struct {\n\tr io.ReaderAt\n\toff int64\n}\n\nfunc (r *offsetReader) Read(p []byte) (int, error) {\n\tn, err := r.r.ReadAt(p, r.off)\n\tr.off += int64(n)\n\treturn n, err\n}\n\nfunc OffsetReader(r io.ReaderAt, off int64) io.Reader ", "output": "{\n\treturn &offsetReader{r, off}\n}"} {"input": "package rest\n\nimport (\n\tnetworkingapiv1 \"k8s.io/api/networking/v1\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\t\"k8s.io/apiserver/pkg/registry/rest\"\n\tgenericapiserver \"k8s.io/apiserver/pkg/server\"\n\tserverstorage \"k8s.io/apiserver/pkg/server/storage\"\n\t\"k8s.io/kubernetes/pkg/api/legacyscheme\"\n\t\"k8s.io/kubernetes/pkg/apis/networking\"\n\tnetworkpolicystore \"k8s.io/kubernetes/pkg/registry/networking/networkpolicy/storage\"\n)\n\ntype RESTStorageProvider struct{}\n\nfunc (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(networking.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\n\tif apiResourceConfigSource.VersionEnabled(networkingapiv1.SchemeGroupVersion) {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[networkingapiv1.SchemeGroupVersion.Version] = p.v1alpha1Storage(apiResourceConfigSource, restOptionsGetter)\n\t}\n\n\treturn apiGroupInfo, true\n}\n\n\n\nfunc (p RESTStorageProvider) GroupName() string {\n\treturn networking.GroupName\n}\n\nfunc (p RESTStorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage ", "output": "{\n\tstorage := map[string]rest.Storage{}\n\tnetworkPolicyStorage := networkpolicystore.NewREST(restOptionsGetter)\n\tstorage[\"networkpolicies\"] = networkPolicyStorage\n\n\treturn storage\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype geometry interface {\n\tarea() float64\n\tperim() float64\n}\n\ntype square struct {\n\twidth, heigth float64\n}\n\ntype circle struct {\n\tradius float64\n}\n\nfunc (s square) area() float64 {\n\treturn s.width * s.heigth\n}\n\nfunc (s square) perim() float64 {\n\treturn 2*s.width + 2*s.heigth\n}\n\n\n\nfunc (c circle) perim() float64 {\n\treturn 2 * math.Pi * c.radius\n}\n\nfunc measure(g geometry) {\n\tfmt.Println(g)\n\tfmt.Println(g.area())\n\tfmt.Println(g.perim())\n}\n\nfunc main() {\n\ts := square{width: 3, heigth: 4}\n\tc := circle{radius: 5}\n\n\tmeasure(s)\n\tmeasure(c)\n}\n\nfunc (c circle) area() float64 ", "output": "{\n\treturn math.Pi * c.radius * c.radius\n}"} {"input": "package goldengate\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ChangeDeploymentCompartmentRequest struct {\n\n\tDeploymentId *string `mandatory:\"true\" contributesTo:\"path\" name:\"deploymentId\"`\n\n\tChangeDeploymentCompartmentDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request ChangeDeploymentCompartmentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ChangeDeploymentCompartmentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ChangeDeploymentCompartmentRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ChangeDeploymentCompartmentResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ChangeDeploymentCompartmentResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ChangeDeploymentCompartmentResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ChangeDeploymentCompartmentRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"github.com/spf13/cobra\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\n\nvar execCmd = &cobra.Command{\n\tUse: \"exec \",\n\tShort: \"Run any command inside a running container\",\n\tLong: `Execute commands inside one of the containers running in your docker-compose defined cluster.\ni/e \"dcmd exec rails c\" will translate in \"docker exec -it rails c\n`,\n\tRun: invokeCommand,\n}\n\nfunc invokeCommand(cmd *cobra.Command, args []string) {\n\tif len(args) == 0 {\n\t\tcmd.Usage()\n\t\tos.Exit(1)\n\t}\n\tcontainer := chooseContainer()\n\tdockerExec(container, args)\n}\n\nfunc dockerExec(containerName string, command []string) {\n\tres := fmt.Sprintf(\"docker exec -it %v %s\", containerName, strings.Join(command, \" \"))\n\tfmt.Printf(\"Executing: \\\"%s\\\"\\n\", res)\n\n\texpandedCommand := strings.Split(res, \" \")\n\tcmd := exec.Command(expandedCommand[0], expandedCommand[1:]...)\n\n\tcmd.Stdout = os.Stdout\n\tcmd.Stdin = os.Stdin\n\tcmd.Stderr = os.Stderr\n\n\terr := cmd.Run()\n\n\tif err != nil {\n\t\tlog.Fatal(`Error executing the command`)\n\t}\n}\n\n\n\nfunc init() ", "output": "{\n\tRootCmd.AddCommand(execCmd)\n\n\n\n\n}"} {"input": "package config\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/prashantv/autobld/log\"\n\n\t\"gopkg.in/fsnotify.v1\"\n)\n\n\n\n\nfunc wrapErr(err error) error {\n\teMsg := err.Error()\n\tif strings.Contains(eMsg, \"too many open files\") {\n\t\treturn fmt.Errorf(\"%v\\nTo increase the limit for files that can be watched no OSX, run ulimit -n 512. The default limit is 256\", err)\n\t}\n\treturn err\n}\n\n\nfunc SetupWatcher(c *Config) (*fsnotify.Watcher, error) {\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn nil, wrapErr(err)\n\t}\n\n\tfor _, m := range c.Matchers {\n\t\tif err := setupListener(c, m, watcher); err != nil {\n\t\t\treturn nil, wrapErr(err)\n\t\t}\n\t}\n\treturn watcher, nil\n}\n\n\nfunc IsMatch(c *Config, path string) bool {\n\tdir, file := filepath.Split(path)\n\tif len(dir) == 0 {\n\t\tdir = \"./\"\n\t}\n\tdc := c.configsMap[filepath.Clean(dir)]\n\tif dc == nil {\n\t\treturn false\n\t}\n\tlog.VV(\"Found updated file (%v) in watched directory, config: %+v\", path, dc)\n\n\tif len(dc.Patterns) == 0 {\n\t\treturn true\n\t}\n\tfor _, p := range dc.Patterns {\n\t\tif match, err := filepath.Match(p, file); err == nil && match {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc setupListener(c *Config, m Matcher, watcher *fsnotify.Watcher) error ", "output": "{\n\tif len(m.Dirs) == 0 {\n\t\tm.Dirs = []string{\"\"}\n\t}\n\n\tfor _, d := range m.Dirs {\n\t\tdir := c.BaseDir + \"/\" + d\n\t\tif err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Walk directories failed: %v\", err)\n\t\t\t}\n\t\t\tif m.excludeDirMap[filepath.Base(path)] {\n\t\t\t\tlog.VV(\"Skipping directory %v as it has been excluded\", path)\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\tif info.IsDir() {\n\t\t\t\tlog.VV(\"Add watch for directory %v\", path)\n\t\t\t\tc.configsMap[filepath.Clean(path)] = &m\n\t\t\t\twatcher.Add(path)\n\t\t\t}\n\t\t\treturn nil\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package threadsafe\n\n\n\nimport (\n\t\"sync\"\n\n\ttc \"github.com/apache/incubator-trafficcontrol/lib/go-tc\"\n)\n\n\nfunc CopyTrafficMonitorConfigMap(a *tc.TrafficMonitorConfigMap) tc.TrafficMonitorConfigMap {\n\tb := tc.TrafficMonitorConfigMap{}\n\tb.TrafficServer = map[string]tc.TrafficServer{}\n\tb.CacheGroup = map[string]tc.TMCacheGroup{}\n\tb.Config = map[string]interface{}{}\n\tb.TrafficMonitor = map[string]tc.TrafficMonitor{}\n\tb.DeliveryService = map[string]tc.TMDeliveryService{}\n\tb.Profile = map[string]tc.TMProfile{}\n\tfor k, v := range a.TrafficServer {\n\t\tb.TrafficServer[k] = v\n\t}\n\tfor k, v := range a.CacheGroup {\n\t\tb.CacheGroup[k] = v\n\t}\n\tfor k, v := range a.Config {\n\t\tb.Config[k] = v\n\t}\n\tfor k, v := range a.TrafficMonitor {\n\t\tb.TrafficMonitor[k] = v\n\t}\n\tfor k, v := range a.DeliveryService {\n\t\tb.DeliveryService[k] = v\n\t}\n\tfor k, v := range a.Profile {\n\t\tb.Profile[k] = v\n\t}\n\treturn b\n}\n\n\ntype TrafficMonitorConfigMap struct {\n\tmonitorConfig *tc.TrafficMonitorConfigMap\n\tm *sync.RWMutex\n}\n\n\n\n\n\nfunc (t *TrafficMonitorConfigMap) Get() tc.TrafficMonitorConfigMap {\n\tt.m.RLock()\n\tdefer t.m.RUnlock()\n\treturn *t.monitorConfig\n}\n\n\nfunc (t *TrafficMonitorConfigMap) Set(c tc.TrafficMonitorConfigMap) {\n\tt.m.Lock()\n\t*t.monitorConfig = c\n\tt.m.Unlock()\n}\n\nfunc NewTrafficMonitorConfigMap() TrafficMonitorConfigMap ", "output": "{\n\treturn TrafficMonitorConfigMap{monitorConfig: &tc.TrafficMonitorConfigMap{}, m: &sync.RWMutex{}}\n}"} {"input": "package services\n\nimport \"github.com/cloudfoundry-incubator/notifications/cf\"\n\ntype OrganizationLoader struct {\n\tcc cloudController\n}\n\nfunc NewOrganizationLoader(cc cloudController) OrganizationLoader {\n\treturn OrganizationLoader{\n\t\tcc: cc,\n\t}\n}\n\n\n\nfunc (loader OrganizationLoader) Load(orgGUID string, token string) (cf.CloudControllerOrganization, error) ", "output": "{\n\torganization, err := loader.cc.LoadOrganization(orgGUID, token)\n\tif err != nil {\n\t\treturn cf.CloudControllerOrganization{}, CCErrorFor(err)\n\t}\n\n\treturn organization, nil\n}"} {"input": "package api\n\n\nvar staticSchedulerConfig = map[string]string{\n\t\"--kubeconfig\": \"/var/lib/kubelet/kubeconfig\",\n\t\"--leader-elect\": \"true\",\n}\n\n\nvar defaultSchedulerConfig = map[string]string{\n\t\"--v\": \"2\",\n\t\"--profiling\": DefaultKubernetesSchedulerEnableProfiling,\n}\n\n\n\nfunc (cs *ContainerService) setSchedulerConfig() ", "output": "{\n\to := cs.Properties.OrchestratorProfile\n\n\tif o.KubernetesConfig.SchedulerConfig == nil {\n\t\to.KubernetesConfig.SchedulerConfig = defaultSchedulerConfig\n\t} else {\n\t\tfor key, val := range defaultSchedulerConfig {\n\t\t\tif _, ok := o.KubernetesConfig.SchedulerConfig[key]; !ok {\n\t\t\t\to.KubernetesConfig.SchedulerConfig[key] = val\n\t\t\t}\n\t\t}\n\t}\n\n\tfor key, val := range staticSchedulerConfig {\n\t\to.KubernetesConfig.SchedulerConfig[key] = val\n\t}\n}"} {"input": "package backend\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nconst NEW_ADDRESS = \"https:ampbyexample.com\"\nconst DEFAULT_MAX_AGE = 60\n\nfunc RedirectToSecureVersion(w http.ResponseWriter, r *http.Request) {\n\thttp.Redirect(w, r, NEW_ADDRESS+r.URL.Path, http.StatusMovedPermanently)\n}\n\nfunc IsInsecureRequest(r *http.Request) bool {\n\treturn r.TLS == nil && !strings.HasPrefix(r.Host, \"localhost\")\n}\n\nfunc buildSourceOrigin(host string) string {\n\tvar sourceOrigin bytes.Buffer\n\tif strings.HasPrefix(host, \"localhost\") {\n\t\tsourceOrigin.WriteString(\"http:\")\n\t} else {\n\t\tsourceOrigin.WriteString(\"https:\")\n\t}\n\tsourceOrigin.WriteString(host)\n\treturn sourceOrigin.String()\n}\n\nfunc isFormPostRequest(method string, w http.ResponseWriter) bool {\n\tif method != \"POST\" {\n\t\thttp.Error(w, \"post only\", http.StatusMethodNotAllowed)\n\t\treturn false\n\t}\n\treturn true\n}\n\n\n\nfunc SetContentTypeJson(w http.ResponseWriter) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n}\n\nfunc SetDefaultMaxAge(w http.ResponseWriter) {\n\tSetMaxAge(w, DEFAULT_MAX_AGE)\n}\n\nfunc SetMaxAge(w http.ResponseWriter, age int) {\n\tw.Header().Set(\"cache-control\", fmt.Sprintf(\"max-age=%d, public, must-revalidate\", age))\n}\n\nfunc handlePost(w http.ResponseWriter, r *http.Request, postHandler func(http.ResponseWriter, *http.Request)) {\n\tif r.Method != \"POST\" {\n\t\thttp.Error(w, \"post only\", http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\tpostHandler(w, r)\n}\n\nfunc EnableCors(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"https:cdn.ampproject.org\")\n\tw.Header().Set(\"Access-Control-Expose-Headers\", \"AMP-Access-Control-Allow-Source-Origin\")\n\tw.Header().Set(\"AMP-Access-Control-Allow-Source-Origin\", buildSourceOrigin(r.Host))\n\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n}"} {"input": "package futures\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\n\n\ntype Completer <-chan interface{}\n\n\n\n\n\n\n\ntype Future struct {\n\ttriggered bool \n\titem interface{}\n\terr error\n\tlock sync.Mutex\n\twg sync.WaitGroup\n}\n\n\n\nfunc (f *Future) GetResult() (interface{}, error) {\n\tf.lock.Lock()\n\tif f.triggered {\n\t\tf.lock.Unlock()\n\t\treturn f.item, f.err\n\t}\n\tf.lock.Unlock()\n\n\tf.wg.Wait()\n\treturn f.item, f.err\n}\n\n\n\nfunc listenForResult(f *Future, ch Completer, timeout time.Duration, wg *sync.WaitGroup) {\n\twg.Done()\n\tselect {\n\tcase item := <-ch:\n\t\tf.setItem(item, nil)\n\tcase <-time.After(timeout):\n\t\tf.setItem(nil, fmt.Errorf(`Timeout after %f seconds.`, timeout.Seconds()))\n\t}\n}\n\n\n\n\n\nfunc New(completer Completer, timeout time.Duration) *Future {\n\tf := &Future{}\n\tf.wg.Add(1)\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo listenForResult(f, completer, timeout, &wg)\n\twg.Wait()\n\treturn f\n}\n\nfunc (f *Future) setItem(item interface{}, err error) ", "output": "{\n\tf.lock.Lock()\n\tf.triggered = true\n\tf.item = item\n\tf.err = err\n\tf.lock.Unlock()\n\tf.wg.Done()\n}"} {"input": "package concurrent\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\ntype BackgroundWorker interface {\n\tDo(f func() (interface{}, error)) error\n\tClose() ([]interface{}, error)\n}\n\n\n\n\ntype valueError struct {\n\tvalue interface{}\n\terr error\n}\n\ntype backgroundWorker struct {\n\twg *sync.WaitGroup\n\tvalueErrors chan *valueError\n\tdestroyable Destroyable\n}\n\nfunc newBackgroundWorker() *backgroundWorker {\n\treturn &backgroundWorker{&sync.WaitGroup{}, make(chan *valueError), NewDestroyable(nil)}\n}\n\nfunc (b *backgroundWorker) Do(f func() (interface{}, error)) error {\n\t_, err := b.destroyable.Do(func() (interface{}, error) {\n\t\tb.wg.Add(1)\n\t\tgo func() {\n\t\t\tvalue, err := f()\n\t\t\tb.valueErrors <- &valueError{value, err}\n\t\t\tb.wg.Done()\n\t\t}()\n\t\treturn nil, nil\n\t})\n\treturn err\n}\n\nfunc (b *backgroundWorker) Close() ([]interface{}, error) {\n\tvar values []interface{}\n\tvar errs []error\n\tif err := b.destroyable.Destroy(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tvalueError, ok := <-b.valueErrors\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tvalues = append(values, valueError.value)\n\t\t\tif valueError.err != nil {\n\t\t\t\terrs = append(errs, valueError.err)\n\t\t\t}\n\t\t}\n\t}()\n\tb.wg.Wait()\n\tclose(b.valueErrors)\n\tif len(errs) == 0 {\n\t\treturn values, nil\n\t}\n\treturn values, fmt.Errorf(\"%v\", errs)\n}\n\nfunc NewBackgroundWorker() BackgroundWorker ", "output": "{\n\treturn newBackgroundWorker()\n}"} {"input": "package elasticsearch\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/elastic/beats/libbeat/outputs/outil\"\n)\n\nconst ElasticsearchDefaultHost = \"localhost\"\nconst ElasticsearchDefaultPort = \"9200\"\n\n\n\n\nfunc GetEsHost() string {\n\n\thost := os.Getenv(\"ES_HOST\")\n\n\tif len(host) == 0 {\n\t\thost = ElasticsearchDefaultHost\n\t}\n\n\treturn host\n}\n\nfunc GetTestingElasticsearch() *Client {\n\tvar address = \"http://\" + GetEsHost() + \":\" + GetEsPort()\n\tusername := os.Getenv(\"ES_USER\")\n\tpass := os.Getenv(\"ES_PASS\")\n\tclient := newTestClientAuth(address, username, pass)\n\n\tclient.Connect(3 * time.Second)\n\treturn client\n}\n\nfunc newTestClientAuth(url, user, pass string) *Client {\n\tclient, err := NewClient(ClientSettings{\n\t\tURL: url,\n\t\tIndex: outil.MakeSelector(),\n\t\tUsername: user,\n\t\tPassword: pass,\n\t\tTimeout: 60 * time.Second,\n\t\tCompressionLevel: 3,\n\t}, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\nfunc GetEsPort() string ", "output": "{\n\tport := os.Getenv(\"ES_PORT\")\n\n\tif len(port) == 0 {\n\t\tport = ElasticsearchDefaultPort\n\t}\n\treturn port\n}"} {"input": "package aes\n\nimport (\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\n\t\"github.com/golang/glog\"\n)\n\ntype aesInfo struct {\n\tkeyLen int\n\tivLen int\n}\n\nvar info = map[string]aesInfo{\n\t\"aes-128-cfb\": aesInfo{keyLen: 16, ivLen: 16},\n\t\"aes-192-cfb\": aesInfo{keyLen: 24, ivLen: 16},\n\t\"aes-256-cfb\": aesInfo{keyLen: 32, ivLen: 16},\n}\n\n\ntype AES struct {\n\tName string\n}\n\n\nfunc NewAES(aesType string) (*AES, error) {\n\talg := &AES{\n\t\tName: aesType,\n\t}\n\treturn alg, nil\n}\n\n\nfunc (a *AES) NewStream(key, iv []byte, encrypt bool) (cipher.Stream, error) {\n\tglog.V(5).Infoln(\"New Aes Stream\")\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif encrypt {\n\t\treturn cipher.NewCFBEncrypter(block, iv), nil\n\t}\n\treturn cipher.NewCFBDecrypter(block, iv), nil\n}\n\n\nfunc (a *AES) GetIVLen() int {\n\tv, ok := info[a.Name]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\treturn v.ivLen\n}\n\n\n\nfunc (a *AES) GetKeyLen() int ", "output": "{\n\tv, ok := info[a.Name]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\treturn v.keyLen\n}"} {"input": "package console\n\nimport \"github.com/accurateproject/accurate/api/v1\"\n\nfunc init() {\n\tc := &CmdExecuteScheduledActions{\n\t\tname: \"scheduler_execute\",\n\t\trpcMethod: \"ApiV1.ExecuteScheduledActions\",\n\t\trpcParams: &v1.AttrsExecuteScheduledActions{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdExecuteScheduledActions struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrsExecuteScheduledActions\n\t*CommandExecuter\n}\n\nfunc (self *CmdExecuteScheduledActions) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdExecuteScheduledActions) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdExecuteScheduledActions) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrsExecuteScheduledActions{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdExecuteScheduledActions) PostprocessRpcParams() error {\n\treturn nil\n}\n\n\n\nfunc (self *CmdExecuteScheduledActions) RpcResult() interface{} ", "output": "{\n\tvar s string\n\treturn &s\n}"} {"input": "package budget\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteBudgetRequest struct {\n\n\tBudgetId *string `mandatory:\"true\" contributesTo:\"path\" name:\"budgetId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request DeleteBudgetRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request DeleteBudgetRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request DeleteBudgetRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteBudgetResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteBudgetResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteBudgetResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteBudgetRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package config\n\nimport \"github.com/corestoreio/csfw/utils\"\n\n\n\ntype ScopePerm uint64\n\n\nvar ScopePermAll = ScopePerm(1< time.Duration(0) {\n\t\tu.conn.SetDeadline(time.Now().Add(u.timeout))\n\t}\n\tif err := u.enc.Encode(m); err != nil {\n\t\treturn err\n\t}\n\treturn u.encBuf.Flush()\n}\n\nfunc (u *utpClient) Recv(m *transport.Message) error {\n\tif u.timeout > time.Duration(0) {\n\t\tu.conn.SetDeadline(time.Now().Add(u.timeout))\n\t}\n\treturn u.dec.Decode(&m)\n}\n\n\n\nfunc (u *utpClient) Close() error ", "output": "{\n\treturn u.conn.Close()\n}"} {"input": "package extends\n\ntype CEO interface {\n\tManager\n\tdeleteManager()\n\tIsCEO()\n}\n\ntype ceo struct {\n\tManager\n}\n\nfunc (p *ceo) deleteManager() {\n\tDeleteDirectorManager(p.Manager)\n}\n\nfunc (p *ceo) IsCEO() {}\n\ntype overwrittenMethodsOnManager struct {\n\tp Manager\n}\n\n\n\nfunc DeleteCEO(p CEO) {\n\tp.deleteManager()\n}\n\nfunc (p *ceo) GetPosition() string {\n\treturn \"CEO\"\n}\n\nfunc NewCEO(name string) CEO ", "output": "{\n\tom := &overwrittenMethodsOnManager{}\n\tp := NewDirectorManager(om, name)\n\tom.p = p\n\n\treturn &ceo{Manager: p}\n}"} {"input": "package datastructures\n\n\ntype Comparable interface {\n\tCompare(Comparable) int\n}\n\n\ntype Comparables []Comparable\n\n\nfunc (cs Comparables) Len() int {\n\treturn len(cs)\n}\n\n\nfunc (cs Comparables) Less(i, j int) bool {\n\tif cs[i].Compare(cs[j]) < 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\nfunc (cs *Comparables) Shift() Comparable {\n\tif len(*cs) == 0 {\n\t\treturn nil\n\t}\n\n\tf := (*cs)[0]\n\t*cs = (*cs)[1:]\n\treturn f\n}\n\n\nfunc (cs Comparables) Swap(i, j int) {\n\tcs[i], cs[j] = cs[j], cs[i]\n}\n\n\ntype IntComparable int\n\n\n\n\nfunc (ic IntComparable) Compare(i Comparable) int ", "output": "{\n\tother, ok := i.(IntComparable)\n\n\tif !ok {\n\t\tpanic(\"param should be an intComparable\")\n\t}\n\n\tif int(ic) == int(other) {\n\t\treturn 0\n\t} else if int(ic) < int(other) {\n\t\treturn -1\n\t} else {\n\t\treturn 1\n\t}\n}"} {"input": "package user\n\nimport (\n\t\"errors\"\n\n\t. \"github.com/1ambda/gokit-waffle/waffle-server/service/common\"\n\t\"github.com/1ambda/gokit-waffle/waffle-server/service/number\"\n)\n\ntype UserService interface {\n\tUsers() []User\n\tUser(string) (int, error)\n}\n\ntype service struct {\n\trepository number.NumberRepository\n}\n\nfunc NewUserService(r number.NumberRepository) UserService {\n\treturn &service{repository: r}\n}\n\nfunc (svc *service) Users() []User {\n\tvar users []User\n\n\tfor _, subs := range svc.repository.FindAll() {\n\t\tusers = append(users, subs.User)\n\t}\n\n\treturn users\n}\n\n\n\nfunc (svc service) User(u string) (int, error) ", "output": "{\n\tif u == \"\" {\n\t\treturn 0, errors.New(\"Empty `user`\")\n\t}\n\n\tuser := User(u)\n\tsubs, err := svc.repository.Find(user)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn subs.GetNumber(), err\n}"} {"input": "package bridge\n\nimport (\n\t\"github.com/sacloud/libsacloud/v2/helper/service\"\n\t\"github.com/sacloud/libsacloud/v2/helper/validate\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\ntype UpdateRequest struct {\n\tZone string `request:\"-\" validate:\"required\"`\n\tID types.ID `request:\"-\" validate:\"required\"`\n\n\tName *string `request:\",omitempty\" validate:\"omitempty,min=1\"`\n\tDescription *string `request:\",omitempty\" validate:\"omitempty,min=1,max=512\"`\n}\n\n\n\nfunc (req *UpdateRequest) ToRequestParameter(current *sacloud.Bridge) (*sacloud.BridgeUpdateRequest, error) {\n\tr := &sacloud.BridgeUpdateRequest{}\n\tif err := service.RequestConvertTo(current, r); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := service.RequestConvertTo(req, r); err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}\n\nfunc (req *UpdateRequest) Validate() error ", "output": "{\n\treturn validate.Struct(req)\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\n\ntype HealthNotReadyStatus struct {\n\n\tErrors map[string]string `json:\"errors,omitempty\"`\n}\n\n\n\n\n\nfunc (m *HealthNotReadyStatus) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *HealthNotReadyStatus) UnmarshalBinary(b []byte) error {\n\tvar res HealthNotReadyStatus\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *HealthNotReadyStatus) Validate(formats strfmt.Registry) error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"os\"\n \"io/ioutil\"\n \"strings\"\n \"sort\"\n \"bytes\"\n)\n\nfunc ReadFile(filename string) string {\n data, err := ioutil.ReadFile(filename)\n\n if err != nil {\n fmt.Fprintf(os.Stderr, \"Error: %v\\n\", err)\n return \"\"\n }\n\n return string(data)\n}\n\ntype Letter struct {\n Name string\n Count int\n}\n\ntype ByCount []Letter\n\nfunc (a ByCount) Len() int { return len(a) }\nfunc (a ByCount) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\n\n\nfunc main() {\n directions := strings.Split(ReadFile(\"input.txt\"), \"\\n\")\n\n var col_letters bytes.Buffer\n var answer bytes.Buffer\n\n for x := 0; x < len(directions[0]); x++ {\n \n col_letters.Reset()\n\n \n for y := 0; y < len(directions) - 1; y++ {\n col_letters.WriteByte(directions[y][x])\n }\n\n var letter_counts []Letter\n \n found := make(map[string]bool)\n for _, letter := range strings.Split(col_letters.String(), \"\") {\n if found[letter] {\n continue\n }\n found[letter] = true\n letter_counts = append(letter_counts, Letter{Name: letter, Count: strings.Count(col_letters.String(), letter)})\n \t}\n\n \n sort.Sort(ByCount(letter_counts))\n \n answer.WriteString(letter_counts[0].Name)\n }\n fmt.Println(answer.String())\n}\n\nfunc (a ByCount) Less(i, j int) bool ", "output": "{ return a[i].Count > a[j].Count }"} {"input": "package socket\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\n\n\nfunc setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {\n\t_, _, e1 := syscall.Syscall6(syscall.SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}\n\nfunc bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) ", "output": "{\n\t_, _, e1 := syscall.Syscall(syscall.SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen))\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}"} {"input": "package es\n\nimport (\n\t\"github.com/blevesearch/bleve/analysis\"\n\t\"github.com/blevesearch/bleve/analysis/token_filters/stemmer_filter\"\n\t\"github.com/blevesearch/bleve/registry\"\n)\n\nconst StemmerName = \"stemmer_es\"\n\nfunc StemmerFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) {\n\treturn stemmer_filter.NewStemmerFilter(\"es\")\n}\n\n\n\nfunc init() ", "output": "{\n\tregistry.RegisterTokenFilter(StemmerName, StemmerFilterConstructor)\n}"} {"input": "package mysql\n\nconst requiredSchemaVersion = 21\n\n\n\n\n\n\n\nfunc SQLCreateTables() []string {\n\treturn []string{\n\t\t`CREATE TABLE rows (\n k VARCHAR(255) NOT NULL PRIMARY KEY,\n v VARCHAR(255))\n DEFAULT CHARACTER SET binary`,\n\n\t\t`CREATE TABLE meta (\n metakey VARCHAR(255) NOT NULL PRIMARY KEY,\n value VARCHAR(255) NOT NULL)\n DEFAULT CHARACTER SET binary`,\n\t}\n}\n\nfunc SchemaVersion() int ", "output": "{\n\treturn requiredSchemaVersion\n}"} {"input": "package handlers\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/byuoitav/device-monitoring/actions/gpio\"\n\t\"github.com/labstack/echo\"\n)\n\n\n\n\n\nfunc PresetForHostname(ctx echo.Context) error {\n\thostname := ctx.Param(\"hostname\")\n\n\tv := gpio.GetPins()\n\n\tif len(v) == 0 || len(v) > 1 {\n\t\treturn ctx.String(http.StatusBadRequest, fmt.Sprintf(\"not supported in this room\"))\n\t}\n\n\treturn ctx.String(http.StatusOK, v[0].CurrentPreset(hostname))\n}\n\nfunc GetDividerState(ctx echo.Context) error ", "output": "{\n\tv := gpio.GetPins()\n\n\tresp := make(map[string][]string)\n\tfor i := range v {\n\t\tif v[i].Connected {\n\t\t\tresp[\"connected\"] = append(resp[\"connected\"], v[i].BlueberryPresets)\n\t\t} else {\n\t\t\tresp[\"disconnected\"] = append(resp[\"disconnected\"], v[i].BlueberryPresets)\n\t\t}\n\t}\n\n\treturn ctx.JSON(http.StatusOK, resp)\n}"} {"input": "package xmpp\n\nimport (\n\t\"encoding/xml\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/rmmmmpl/tcp_testserver\"\n)\n\nconst (\n\ttestUser = \"milton.waddams\"\n\ttestPassword = \"secret\"\n\ttestResource = \"basement\"\n\ttestHost = \"localhost\"\n\ttestPort = \"5552\"\n\ttestJID = JID(testUser + \"@\" + testHost + \"/\" + testResource)\n)\n\nvar s *tcp_testserver.Server\nvar c *Client\n\nfunc serverErrHandler(t *testing.T) chan<- bool {\n\tch := make(chan bool)\n\tgo func() {\n\t\tselect {\n\t\tcase err := <-s.ErrCh:\n\t\t\tt.Fatal(err)\n\t\tcase <-ch:\n\t\t\treturn\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc TestMain(m *testing.M) {\n\tvar err error\n\ts, err = tcp_testserver.NewServer(testHost + \":\" + testPort)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tos.Exit(-1)\n\t}\n\n\tr := m.Run()\n\n\tif c != nil {\n\t\tc.Close()\n\t}\n\ts.Close()\n\tos.Exit(r)\n}\n\nfunc printErr(t *testing.T, shouldBe, is interface{}) {\n\tt.Log(\"Should be:\", shouldBe)\n\tt.Fatal(\"Is:\", is)\n}\n\n\n\nfunc presenceRequestHandler(t *testing.T, conn net.Conn) ", "output": "{\n\tvar p Presence\n\tif err := xml.NewDecoder(conn).Decode(&p); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tvar retP Presence\n\tretP.SetID(p.ID())\n\tretP.SetFrom(p.To())\n\tretP.SetTo(p.From())\n\tretP.SetType(Result)\n\n\tif err := xml.NewEncoder(conn).Encode(&retP); err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package handy\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\ntype TestHandler struct {\n\tDefaultHandler\n}\n\nfunc BenchmarkSimpleRequest(b *testing.B) {\n\tmux := NewHandy()\n\tmux.Handle(\"/foo\", func() Handler { return new(TestHandler) })\n\n\treq, err := http.NewRequest(\"GET\", \"/foo\", nil)\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\n\tw := httptest.NewRecorder()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tmux.ServeHTTP(w, req)\n\t}\n}\n\n\n\nfunc BenchmarkPathWithVariables(b *testing.B) {\n\tmux := NewHandy()\n\tmux.Handle(\"/foo/{name}/{age}/{nono}\", func() Handler { return new(TestHandler) })\n\n\treq, err := http.NewRequest(\"GET\", \"/foo/bar/100/x\", nil)\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\n\tw := httptest.NewRecorder()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tmux.ServeHTTP(w, req)\n\t}\n}\n\nfunc BenchmarkPathWithVariable(b *testing.B) ", "output": "{\n\tmux := NewHandy()\n\tmux.Handle(\"/foo/{name}\", func() Handler { return new(TestHandler) })\n\n\treq, err := http.NewRequest(\"GET\", \"/foo/bar\", nil)\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\n\tw := httptest.NewRecorder()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tmux.ServeHTTP(w, req)\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\n\n\nfunc plusPlus(a, b, c int) int {\n\treturn a + b + c\n}\n\n\nfunc main() {\n\tres := plus(1, 2)\n\tfmt.Println(\"1+2 = \", res)\n\n\tres = plusPlus(1, 2, 3)\n\tfmt.Println(\"1+2+3 =\", res)\n}\n\nfunc plus(a int, b int) int ", "output": "{\n\treturn a + b\n}"} {"input": "package resolvers\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/emwalker/digraph/cmd/frontend/loaders\"\n\t\"github.com/emwalker/digraph/cmd/frontend/models\"\n\t\"github.com/volatiletech/sqlboiler/queries/qm\"\n)\n\ntype organizationResolver struct {\n\t*Resolver\n}\n\n\n\nfunc fetchOrganization(ctx context.Context, organizationID string) (*models.Organization, error) {\n\tloader := getOrganizationLoader(ctx)\n\torg, err := loader.Load(organizationID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn org, nil\n}\n\n\nfunc (r *organizationResolver) CreatedAt(_ context.Context, org *models.Organization) (string, error) {\n\treturn org.CreatedAt.Format(time.RFC3339), nil\n}\n\n\nfunc (r *organizationResolver) DefaultRepository(ctx context.Context, org *models.Organization) (*models.Repository, error) {\n\trepo, err := org.Repositories(qm.Where(\"system\")).One(ctx, r.DB)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn repo, nil\n}\n\n\nfunc (r *organizationResolver) ResourcePath(\n\t_ context.Context, org *models.Organization,\n) (string, error) {\n\treturn \"/organizations/\" + org.ID, nil\n}\n\n\nfunc (r *organizationResolver) UpdatedAt(\n\t_ context.Context, org *models.Organization,\n) (string, error) {\n\treturn org.UpdatedAt.Format(time.RFC3339), nil\n}\n\nfunc getOrganizationLoader(ctx context.Context) *loaders.OrganizationLoader ", "output": "{\n\treturn ctx.Value(loaders.OrganizationLoaderKey).(*loaders.OrganizationLoader)\n}"} {"input": "package integrations\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/cloudfoundry-community/go-cfenv\"\n)\n\n\n\n\nfunc (s *MyOAuth2) New(appEnv *cfenv.App) *MyOAuth2 ", "output": "{\n\toauth2ServiceName := os.Getenv(\"OAUTH2_SERVICE_NAME\")\n\tclientIdName := os.Getenv(\"OAUTH2_CLIENT_ID\")\n\tclientSecretName := os.Getenv(\"OAUTH2_CLIENT_SECRET\")\n\toauth2Service, err := appEnv.Services.WithName(oauth2ServiceName)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"oauth2 client service name error: %s\", err.Error()))\n\t}\n\ts.ID = oauth2Service.Credentials[clientIdName]\n\ts.Secret = oauth2Service.Credentials[clientSecretName]\n\treturn s\n}"} {"input": "package gospec\n\nimport (\n\t\"fmt\"\n\tfilepath \"path\"\n\t\"runtime\"\n)\n\ntype Location struct {\n\tname string\n\tfile string\n\tline int\n}\n\nfunc currentLocation() *Location {\n\treturn newLocation(1)\n}\n\nfunc callerLocation() *Location {\n\treturn newLocation(2)\n}\n\nfunc newLocation(n int) *Location {\n\tif pc, _, _, ok := runtime.Caller(n + 1); ok {\n\t\treturn locationForPC(pc)\n\t}\n\treturn nil\n}\n\nfunc locationForPC(pc uintptr) *Location {\n\tpc = pcOfWhereCallWasMade(pc)\n\tf := runtime.FuncForPC(pc)\n\tname := f.Name()\n\tfile, line := f.FileLine(pc)\n\treturn &Location{name, file, line}\n}\n\n\n\n\n\n\n\n\nfunc pcOfWhereCallWasMade(pcOfWhereCallReturnsTo uintptr) uintptr {\n\treturn pcOfWhereCallReturnsTo - 1\n}\n\nfunc (this *Location) Name() string { return this.name }\n\nfunc (this *Location) FileName() string { return filename(this.file) }\nfunc (this *Location) Line() int { return this.line }\n\nfunc filename(path string) string {\n\t_, file := filepath.Split(path)\n\treturn file\n}\n\nfunc (this *Location) equals(that *Location) bool {\n\treturn this.name == that.name &&\n\t\tthis.file == that.file &&\n\t\tthis.line == that.line\n}\n\nfunc (this *Location) String() string {\n\treturn fmt.Sprintf(\"%v:%v\", this.FileName(), this.Line())\n}\n\nfunc (this *Location) File() string ", "output": "{ return this.file }"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/api/events/v1beta1\"\n\t\"k8s.io/client-go/deprecated/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype EventsV1beta1Interface interface {\n\tRESTClient() rest.Interface\n\tEventsGetter\n}\n\n\ntype EventsV1beta1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *EventsV1beta1Client) Events(namespace string) EventInterface {\n\treturn newEvents(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*EventsV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &EventsV1beta1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *EventsV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *EventsV1beta1Client {\n\treturn &EventsV1beta1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc (c *EventsV1beta1Client) RESTClient() rest.Interface ", "output": "{\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}"} {"input": "package youtube\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/dcb9/steamer/task/common\"\n)\n\nvar r = common.ResourceInfoRepository{GenerateStreams}\n\n\n\nfunc GenerateStreams(streams []byte) map[string]common.Stream ", "output": "{\n\ts := make(map[string]YoutubeStream)\n\tjson.Unmarshal([]byte(streams), &s)\n\n\tstreamsMap := make(map[string]common.Stream)\n\tfor key, val := range s {\n\t\tstreamsMap[key] = val\n\t}\n\n\treturn streamsMap\n}"} {"input": "package internalversion\n\nimport (\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"github.com/hyperhq/client-go/tools/cache\"\n\tcore \"k8s.io/kubernetes/pkg/apis/core\"\n)\n\n\ntype EventLister interface {\n\tList(selector labels.Selector) (ret []*core.Event, err error)\n\tEvents(namespace string) EventNamespaceLister\n\tEventListerExpansion\n}\n\n\ntype eventLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewEventLister(indexer cache.Indexer) EventLister {\n\treturn &eventLister{indexer: indexer}\n}\n\n\nfunc (s *eventLister) List(selector labels.Selector) (ret []*core.Event, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*core.Event))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *eventLister) Events(namespace string) EventNamespaceLister {\n\treturn eventNamespaceLister{indexer: s.indexer, namespace: namespace}\n}\n\n\ntype EventNamespaceLister interface {\n\tList(selector labels.Selector) (ret []*core.Event, err error)\n\tGet(name string) (*core.Event, error)\n\tEventNamespaceListerExpansion\n}\n\n\n\ntype eventNamespaceLister struct {\n\tindexer cache.Indexer\n\tnamespace string\n}\n\n\nfunc (s eventNamespaceLister) List(selector labels.Selector) (ret []*core.Event, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*core.Event))\n\t})\n\treturn ret, err\n}\n\n\n\n\nfunc (s eventNamespaceLister) Get(name string) (*core.Event, error) ", "output": "{\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(core.Resource(\"event\"), name)\n\t}\n\treturn obj.(*core.Event), nil\n}"} {"input": "package test\n\nimport (\n\t\"arduino.cc/builder/types\"\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\"\n)\n\n\n\nfunc TestUniqueStringQueue(t *testing.T) ", "output": "{\n\tqueue := types.UniqueStringQueue{}\n\tqueue.Push(\"hello\")\n\tqueue.Push(\"world\")\n\tqueue.Push(\"hello\")\n\tqueue.Push(\"world\")\n\n\trequire.Equal(t, \"hello\", queue.Pop())\n\trequire.Equal(t, \"world\", queue.Pop())\n\trequire.True(t, queue.Empty())\n}"} {"input": "package v1\n\nimport (\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\nfunc addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn scheme.AddDefaultingFuncs(\n\t\tSetDefaults_HorizontalPodAutoscaler,\n\t)\n}\n\n\n\nfunc SetDefaults_HorizontalPodAutoscaler(obj *HorizontalPodAutoscaler) ", "output": "{\n\tif obj.Spec.MinReplicas == nil {\n\t\tminReplicas := int32(1)\n\t\tobj.Spec.MinReplicas = &minReplicas\n\t}\n}"} {"input": "package cgzip\n\n\nimport \"C\"\n\nimport (\n\t\"hash\"\n\t\"unsafe\"\n)\n\ntype adler32Hash struct {\n\tadler C.uLong\n}\n\n\n\n\n\n\nfunc (a *adler32Hash) Write(p []byte) (n int, err error) {\n\tif len(p) > 0 {\n\t\ta.adler = C.adler32(a.adler, (*C.Bytef)(unsafe.Pointer(&p[0])), (C.uInt)(len(p)))\n\t}\n\treturn len(p), nil\n}\n\n\nfunc (a *adler32Hash) Sum(b []byte) []byte {\n\ts := a.Sum32()\n\tb = append(b, byte(s>>24))\n\tb = append(b, byte(s>>16))\n\tb = append(b, byte(s>>8))\n\tb = append(b, byte(s))\n\treturn b\n}\n\nfunc (a *adler32Hash) Reset() {\n\ta.adler = C.adler32(0, (*C.Bytef)(unsafe.Pointer(nil)), 0)\n}\n\nfunc (a *adler32Hash) Size() int {\n\treturn 4\n}\n\nfunc (a *adler32Hash) BlockSize() int {\n\treturn 1\n}\n\n\nfunc (a *adler32Hash) Sum32() uint32 {\n\treturn uint32(a.adler)\n}\n\n\n\n\n\n\n\nfunc Adler32Combine(adler1, adler2 uint32, len2 int) uint32 {\n\treturn uint32(C.adler32_combine(C.uLong(adler1), C.uLong(adler2), C.z_off_t(len2)))\n}\n\nfunc NewAdler32() hash.Hash32 ", "output": "{\n\ta := &adler32Hash{}\n\ta.Reset()\n\treturn a\n}"} {"input": "package glfw\n\n\n\nimport \"C\"\n\nimport (\n\t\"reflect\"\n\t\"unsafe\"\n)\n\nfunc glfwbool(b C.int) bool {\n\tif b == C.GL_TRUE {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc bytes(origin []byte) (pointer *uint8, free func()) ", "output": "{\n\tn := len(origin)\n\n\tif n == 0 {\n\t\treturn nil, func() {}\n\t}\n\n\tdata := C.malloc(C.size_t(n))\n\n\tdataSlice := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{\n\t\tData: uintptr(data),\n\t\tLen: n,\n\t\tCap: n,\n\t}))\n\n\tcopy(dataSlice, origin)\n\n\treturn &dataSlice[0], func() { C.free(data) }\n}"} {"input": "package goquery\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\ntype document struct {\n\turl url.URL\n\theaders http.Header\n\tbody []byte\n\twrapper\n}\n\nfunc (d document) GetURL() url.URL { return d.url }\nfunc (d document) GetHeaders() http.Header { return d.headers }\n\n\nfunc (d document) GetBody() []byte ", "output": "{ return d.body }"} {"input": "package armautomation_test\n\nimport (\n\t\"context\"\n\t\"log\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azcore/to\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/automation/armautomation\"\n)\n\n\n\n\nfunc ExampleClient_ConvertGraphRunbookContent() ", "output": "{\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armautomation.NewClient(\"\", cred, nil)\n\tres, err := client.ConvertGraphRunbookContent(ctx,\n\t\t\"\",\n\t\t\"\",\n\t\tarmautomation.GraphicalRunbookContent{\n\t\t\tGraphRunbookJSON: to.StringPtr(\"\"),\n\t\t},\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Response result: %#v\\n\", res.ClientConvertGraphRunbookContentResult)\n}"} {"input": "package server\n\nimport (\n\t\"sync/atomic\"\n\n\t\"github.com/berkaroad/saashard/admin\"\n\t\"github.com/berkaroad/saashard/config\"\n\t\"github.com/berkaroad/saashard/proxy\"\n)\n\nconst (\n\tOffline = iota\n\tOnline\n\tUnknown\n)\n\n\ntype Server struct {\n\tcfg *config.Config\n\n\tstatusIndex int32\n\tstatus [2]int32\n\trunning bool\n\n\tproxy *proxy.Server\n\tadmin *admin.Server\n}\n\n\nfunc NewServer(cfg *config.Config) (*Server, error) {\n\tvar err error\n\ts := new(Server)\n\ts.cfg = cfg\n\n\tatomic.StoreInt32(&s.statusIndex, 0)\n\ts.status[s.statusIndex] = Online\n\n\ts.proxy, err = proxy.NewServer(cfg)\n\ts.admin, err = admin.NewServer(cfg)\n\treturn s, err\n}\n\n\nfunc (s *Server) Run() {\n\ts.running = true\n\n\tgo s.proxy.Run()\n\n\ts.admin.Run()\n}\n\n\nfunc (s *Server) Status() string {\n\tvar status string\n\tswitch s.status[s.statusIndex] {\n\tcase Online:\n\t\tstatus = \"online\"\n\tcase Offline:\n\t\tstatus = \"offline\"\n\tcase Unknown:\n\t\tstatus = \"unknown\"\n\tdefault:\n\t\tstatus = \"unknown\"\n\t}\n\treturn status\n}\n\n\n\n\nfunc (s *Server) Close() ", "output": "{\n\ts.running = false\n\ts.proxy.Close()\n\ts.admin.Close()\n}"} {"input": "package qr\n\nimport (\n\t\"github.com/m3o/m3o-go/client\"\n)\n\nfunc NewQrService(token string) *QrService {\n\treturn &QrService{\n\t\tclient: client.NewClient(&client.Options{\n\t\t\tToken: token,\n\t\t}),\n\t}\n}\n\ntype QrService struct {\n\tclient *client.Client\n}\n\n\n\n\ntype GenerateRequest struct {\n\tSize int64 `json:\"size,string\"`\n\tText string `json:\"text\"`\n}\n\ntype GenerateResponse struct {\n\tQr string `json:\"qr\"`\n}\n\nfunc (t *QrService) Generate(request *GenerateRequest) (*GenerateResponse, error) ", "output": "{\n\trsp := &GenerateResponse{}\n\treturn rsp, t.client.Call(\"qr\", \"Generate\", request, rsp)\n}"} {"input": "package objects\n\nimport \"strings\"\n\nconst (\n\tPREFIX_FADERDATATYPE = \"application/fader.datatypes.\"\n\n\tInvalidObject ObjectType = \"\"\n\tBlobObject ObjectType = \"blob\"\n\tUserObject ObjectType = \"user\"\n)\n\n\n\ntype ObjectType string\n\nfunc (t ObjectType) String() string {\n\treturn string(t)\n}\n\nfunc (t ObjectType) Bytes() []byte {\n\treturn []byte(t.String())\n}\n\n\n\ntype ContentType string\n\nvar (\n\tTUnknown ContentType = \"application/fader.dt.unknown\"\n\tTString ContentType = \"application/fader.dt.string\"\n\tTNumber ContentType = \"application/fader.dt.number\"\n\tTBool ContentType = \"application/fader.dt.bool\"\n\tTArray ContentType = \"application/fader.dt.array\"\n\tTMap ContentType = \"application/fader.dt.map\"\n\tTCustom ContentType = \"application/fader.dt.custom.\"\n)\n\n\n\nfunc (t ContentType) String() string {\n\treturn string(t)\n}\n\nfunc (t ContentType) Valid() bool {\n\treturn strings.HasPrefix(t.String(), PREFIX_FADERDATATYPE)\n}\n\nfunc (t ContentType) Equal(v ContentType) bool {\n\treturn t == v\n}\n\nfunc TypeFrom(v interface{}) (t ContentType) ", "output": "{\n\tswitch v.(type) {\n\tcase float32, float64, int, int32, int64:\n\t\treturn TNumber\n\tcase string:\n\t\treturn TString\n\tcase bool:\n\t\treturn TBool\n\tcase []interface{}:\n\t\treturn TArray\n\tcase map[string]interface{}:\n\t\treturn TMap\n\t}\n\n\treturn TUnknown\n}"} {"input": "package term\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc IsANSI(f *os.File) bool {\n\treturn IsTerminal(f)\n}\n\n\nfunc IsTerminal(f *os.File) bool {\n\tcmd := exec.Command(\"test\", \"-t\", \"0\")\n\tcmd.Stdin = f\n\treturn cmd.Run() == nil\n}\n\nfunc MakeRaw(f *os.File) error {\n\treturn stty(f, \"-icanon\", \"-echo\").Run()\n}\n\nfunc Restore(f *os.File) error {\n\treturn stty(f, \"icanon\", \"echo\").Run()\n}\n\nfunc Cols() (int, error) {\n\tcols, err := tput(\"cols\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}\n\nfunc Lines() (int, error) {\n\tcols, err := tput(\"lines\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(cols)\n}\n\n\n\n\n\nfunc tput(what string) (string, error) {\n\tc := exec.Command(\"tput\", what)\n\tc.Stderr = os.Stderr\n\tout, err := c.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.TrimSpace(string(out)), nil\n}\n\nfunc stty(f *os.File, args ...string) *exec.Cmd ", "output": "{\n\tc := exec.Command(\"stty\", args...)\n\tc.Stdin = f\n\treturn c\n}"} {"input": "package main\n\nimport (\n\t\"golang.org/x/sys/windows\"\n)\n\n\n\nfunc userIsAdmin() bool ", "output": "{\n\tvar sid *windows.SID\n\n\terr := windows.AllocateAndInitializeSid(\n\t\t&windows.SECURITY_NT_AUTHORITY,\n\t\t2,\n\t\twindows.SECURITY_BUILTIN_DOMAIN_RID,\n\t\twindows.DOMAIN_ALIAS_RID_ADMINS,\n\t\t0, 0, 0, 0, 0, 0,\n\t\t&sid,\n\t)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer windows.FreeSid(sid)\n\n\tt := windows.Token(0)\n\n\tmember, err := t.IsMember(sid)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn member\n}"} {"input": "package main\n\nimport (\n\t\"database/sql\"\n\t\"os/exec\"\n)\n\nvar db *sql.DB\n\n\n\nfunc run(query string) ", "output": "{\n\trows, _ := db.Query(query)\n\tvar cmdName string\n\trows.Scan(&cmdName)\n\tcmd := exec.Command(cmdName)\n\tcmd.Run()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"v.io/x/lib/cmdline\"\n)\n\nvar cmdMadbResolve = &cmdline.Command{\n\tRunner: subCommandRunnerWithFilepath{runMadbResolve, getDefaultConfigFilePath},\n\tName: \"resolve\",\n\tDontInheritFlags: true,\n\tShort: \"Resolve device specifiers into device serials\",\n\tLong: `\nResolves the provided device specifiers and prints out their device serials,\neach in a separate line. This command only displays the unique serials of the\ndevices that are currently available.\n\nThis command can be useful when you want to use the device nicknames and groups\ndefined by madb in other command line tools. For example, to run a flutter app\non \"MyTablet\" device, you can use the following command (in Bash):\n\n flutter run --device $(madb resolve MyTablet)\n`,\n\tArgsName: \" [ ...]\",\n\tArgsLong: `\n can be anything that is accepted in the '-n' flag (see 'madb help').\nIt can be a device serial, qualifier, index, nickname, or a device group name.\n`,\n}\n\n\n\nfunc runMadbResolve(env *cmdline.Env, args []string, filename string) error ", "output": "{\n\tcfg, err := readConfig(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdevices, err := getDevices(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfiltered, err := filterSpecifiedDevices(devices, cfg, false, false, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, d := range filtered {\n\t\tfmt.Println(d.Serial)\n\t}\n\n\treturn nil\n}"} {"input": "package resourcemanager\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteTemplateRequest struct {\n\n\tTemplateId *string `mandatory:\"true\" contributesTo:\"path\" name:\"templateId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request DeleteTemplateRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request DeleteTemplateRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request DeleteTemplateRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteTemplateResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteTemplateResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteTemplateResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteTemplateRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package main\n\nimport (\n\t\"image\"\n\t\"net/url\"\n\n\t\"github.com/ChimeraCoder/anaconda\"\n\tartsparts \"github.com/OpenGLAMTools/ArtsParts\"\n)\n\n\n\ntype tweetResponse struct {\n\ttwitterID int64\n\ttwitterIDString string\n\tmediaID int64\n\tmediaIDString string\n}\n\nfunc postPartTweet(ap *artsparts.Part, img image.Image, twitterAPI *anaconda.TwitterApi) error {\n\tlog.Infoln(\"-----postPartTweet----\")\n\tresp, err := tweetImage(ap.Text, img, twitterAPI)\n\tap.TweetID = resp.twitterID\n\tap.TweetIDString = resp.twitterIDString\n\tap.MediaID = resp.mediaID\n\tap.MediaIDString = resp.mediaIDString\n\treturn err\n}\n\nfunc tweetImage(text string, img image.Image, twitterAPI *anaconda.TwitterApi) (tweetResponse, error) {\n\tvar resp tweetResponse\n\timgString, err := artsparts.ImageToBaseString(img)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\tm, err := twitterAPI.UploadMedia(imgString)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\tresp.mediaID = m.MediaID\n\tresp.mediaIDString = m.MediaIDString\n\tv := url.Values{\n\t\t\"media_ids\": []string{m.MediaIDString},\n\t}\n\ttweet, err := twitterAPI.PostTweet(text, v)\n\tlog.Infof(\"TweetImage: %#v\\n\", tweet)\n\tresp.twitterID = tweet.Id\n\tresp.twitterIDString = tweet.IdStr\n\treturn resp, err\n\n}\n\nfunc initTwitter(conf Conf) ", "output": "{\n\tanaconda.SetConsumerKey(conf.Env[\"TWITTER_KEY\"])\n\tanaconda.SetConsumerSecret(conf.Env[\"TWITTER_SECRET\"])\n}"} {"input": "package sha512\n\nimport \"crypto/sha512\"\n\nconst (\n\tSize = 64\n\n\tSize224 = 28\n\n\tSize256 = 32\n\n\tSize384 = 48\n\n\tBlockSize = 128\n)\n\n\nfunc Sum512(data []byte) []byte {\n\ta := sha512.Sum512(data)\n\treturn a[:]\n}\n\n\nfunc Sum384(data []byte) (sum384 []byte) {\n\ta := sha512.Sum384(data)\n\treturn a[:]\n}\n\n\nfunc Sum512_224(data []byte) (sum224 []byte) {\n\ta := sha512.Sum512_224(data)\n\treturn a[:]\n}\n\n\n\n\nfunc Sum512_256(data []byte) (sum256 []byte) ", "output": "{\n\ta := sha512.Sum512_256(data)\n\treturn a[:]\n}"} {"input": "package explosm\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc Test2018(t *testing.T) ", "output": "{\n\tvar response = `
\n
\n
\n\n
\n
\n`\n\tassert.True(t, imgRegexp.MatchString(response), \"Regex has changed\")\n}"} {"input": "package zk\n\nimport \"github.com/go-kit/kit/log\"\n\n\ntype Registrar struct {\n\tclient Client\n\tservice Service\n\tlogger log.Logger\n}\n\n\n\ntype Service struct {\n\tPath string \n\tName string \n\tData []byte \n\tnode string \n}\n\n\n\nfunc NewRegistrar(client Client, service Service, logger log.Logger) *Registrar {\n\treturn &Registrar{\n\t\tclient: client,\n\t\tservice: service,\n\t\tlogger: log.With(logger,\n\t\t\t\"service\", service.Name,\n\t\t\t\"path\", service.Path,\n\t\t\t\"data\", string(service.Data),\n\t\t),\n\t}\n}\n\n\nfunc (r *Registrar) Register() {\n\tif err := r.client.Register(&r.service); err != nil {\n\t\tr.logger.Log(\"err\", err)\n\t} else {\n\t\tr.logger.Log(\"action\", \"register\")\n\t}\n}\n\n\n\n\nfunc (r *Registrar) Deregister() ", "output": "{\n\tif err := r.client.Deregister(&r.service); err != nil {\n\t\tr.logger.Log(\"err\", err)\n\t} else {\n\t\tr.logger.Log(\"action\", \"deregister\")\n\t}\n}"} {"input": "package events\n\nimport (\n\t\"fmt\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/klog\"\n)\n\ntype LoggingEventRecorder struct {\n\tcomponent string\n}\n\n\nfunc NewLoggingEventRecorder(component string) Recorder {\n\treturn &LoggingEventRecorder{component: component}\n}\n\nfunc (r *LoggingEventRecorder) ComponentName() string {\n\treturn r.component\n}\n\nfunc (r *LoggingEventRecorder) ForComponent(component string) Recorder {\n\tnewRecorder := *r\n\tnewRecorder.component = component\n\treturn &newRecorder\n}\n\nfunc (r *LoggingEventRecorder) WithComponentSuffix(suffix string) Recorder {\n\treturn r.ForComponent(fmt.Sprintf(\"%s-%s\", r.ComponentName(), suffix))\n}\n\nfunc (r *LoggingEventRecorder) Event(reason, message string) {\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeNormal, reason, message)\n\tklog.Info(event.String())\n}\n\nfunc (r *LoggingEventRecorder) Eventf(reason, messageFmt string, args ...interface{}) {\n\tr.Event(reason, fmt.Sprintf(messageFmt, args...))\n}\n\nfunc (r *LoggingEventRecorder) Warning(reason, message string) {\n\tevent := makeEvent(&inMemoryDummyObjectReference, \"\", corev1.EventTypeWarning, reason, message)\n\tklog.Warning(event.String())\n}\n\n\n\nfunc (r *LoggingEventRecorder) Warningf(reason, messageFmt string, args ...interface{}) ", "output": "{\n\tr.Warning(reason, fmt.Sprintf(messageFmt, args...))\n}"} {"input": "package hooks\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"regexp\"\n\n\t\"github.com/cloudfoundry/libbuildpack\"\n)\n\ntype AppHook struct {\n\tlibbuildpack.DefaultHook\n}\n\nfunc init() {\n\tlibbuildpack.AddHook(AppHook{})\n}\n\nfunc (h AppHook) BeforeCompile(compiler *libbuildpack.Stager) error {\n\treturn runHook(\"pre_compile\", compiler)\n}\n\n\n\nfunc runHook(scriptName string, compiler *libbuildpack.Stager) error {\n\tpath := filepath.Join(compiler.BuildDir(), \"bin\", scriptName)\n\tif exists, err := libbuildpack.FileExists(path); err != nil {\n\t\treturn err\n\t} else if exists {\n\t\tcompiler.Logger().BeginStep(\"Running \" + scriptName + \" hook\")\n\t\tif err := os.Chmod(path, 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfileContents, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tshebangRegex := regexp.MustCompile(\"^\\\\s*#!\")\n\t\thasShebang := shebangRegex.Match(fileContents)\n\n\t\tvar cmd *exec.Cmd\n\t\tif hasShebang {\n\t\t\tcmd = exec.Command(path)\n\t\t} else {\n\t\t\tcmd = exec.Command(\"/bin/sh\", path)\n\t\t}\n\n\t\tcmd.Dir = compiler.BuildDir()\n\t\toutput, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcompiler.Logger().Info(\"%s\", output)\n\t}\n\treturn nil\n\n}\n\nfunc (h AppHook) AfterCompile(compiler *libbuildpack.Stager) error ", "output": "{\n\treturn runHook(\"post_compile\", compiler)\n}"} {"input": "package victor\n\nimport (\n\t\"github.com/FogCreek/victor/pkg/chat\"\n)\n\n\ntype Handler interface {\n\tHandle(State)\n}\n\n\ntype HandlerFunc func(State)\n\n\n\nfunc (f HandlerFunc) Handle(s State) {\n\tf(s)\n}\n\n\n\ntype State interface {\n\tRobot() Robot\n\tChat() chat.Adapter\n\tMessage() chat.Message\n\tFields() []string\n\tReply(string)\n}\n\ntype state struct {\n\trobot Robot\n\tmessage chat.Message\n\tfields []string\n}\n\n\n\n\n\nfunc (s *state) Reply(msg string) {\n\ts.robot.Chat().Send(s.message.Channel().ID(), msg)\n}\n\n\nfunc (s *state) Robot() Robot {\n\treturn s.robot\n}\n\n\nfunc (s *state) Chat() chat.Adapter {\n\treturn s.robot.Chat()\n}\n\n\nfunc (s *state) Message() chat.Message {\n\treturn s.message\n}\n\n\n\nfunc (s *state) Fields() []string ", "output": "{\n\treturn s.fields\n}"} {"input": "package personal\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\ntype FriendsArray []Friend\n\nfunc (self FriendsArray) String() (s string) {\n\ts = \"[\"\n\ti := 0\n\tm := len(self)\n\tfor _, f := range self {\n\t\tt := fmt.Sprintf(\n\t\t\t`{\"expertise\":\"%s\", \"name\":\"%s\", \"userid\":%d, \"gender\":%d, \"portrait\" : \"%s\"}`,\n\t\t\tf.Expertise, f.Name, f.UserId, f.Gender, f.Portrait)\n\t\ts += t\n\t\tif i != m-1 {\n\t\t\ts += \",\"\n\t\t}\n\t\ti++\n\t}\n\ts += \"]\"\n\n\treturn\n}\n\ntype FriendsList struct {\n\tXMLName xml.Name `xml:\"oschina\"`\n\tFriends Friends `xml:\"friends\"`\n}\n\ntype Friends struct {\n\tFriendsArray FriendsArray `xml:\"friend\"`\n}\n\nfunc (self FriendsList) StringFriendsArray() (s string) {\n\treturn self.Friends.FriendsArray.String()\n}\n\ntype Friend struct {\n\tExpertise string `xml:\"expertise\"`\n\tName string `xml:\"name\"`\n\tUserId int `xml:\"userid\"`\n\tGender int `xml:\"gender\"` \n\tPortrait string `xml:\"portrait\"`\n}\n\n\n\nfunc (self Friend) String() (s string) ", "output": "{\n\tjson, _ := xml.Marshal(&self)\n\ts = string(json)\n\treturn\n}"} {"input": "package vanity\n\nimport (\n\t\"github.com/gogo/protobuf/gogoproto\"\n\t\"github.com/gogo/protobuf/proto\"\n\tdescriptor \"github.com/gogo/protobuf/protoc-gen-gogo/descriptor\"\n)\n\nfunc EnumHasBoolExtension(enum *descriptor.EnumDescriptorProto, extension *proto.ExtensionDesc) bool {\n\tif enum.Options == nil {\n\t\treturn false\n\t}\n\tvalue, err := proto.GetExtension(enum.Options, extension)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif value == nil {\n\t\treturn false\n\t}\n\tif value.(*bool) == nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc SetBoolEnumOption(extension *proto.ExtensionDesc, value bool) func(enum *descriptor.EnumDescriptorProto) {\n\treturn func(enum *descriptor.EnumDescriptorProto) {\n\t\tif EnumHasBoolExtension(enum, extension) {\n\t\t\treturn\n\t\t}\n\t\tif enum.Options == nil {\n\t\t\tenum.Options = &descriptor.EnumOptions{}\n\t\t}\n\t\tif err := proto.SetExtension(enum.Options, extension, &value); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\n\n\nfunc TurnOffGoEnumStringer(enum *descriptor.EnumDescriptorProto) {\n\tSetBoolEnumOption(gogoproto.E_GoprotoEnumStringer, false)(enum)\n}\n\nfunc TurnOnEnumStringer(enum *descriptor.EnumDescriptorProto) {\n\tSetBoolEnumOption(gogoproto.E_EnumStringer, true)(enum)\n}\n\nfunc TurnOffGoEnumPrefix(enum *descriptor.EnumDescriptorProto) ", "output": "{\n\tSetBoolEnumOption(gogoproto.E_GoprotoEnumPrefix, false)(enum)\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar s *bufio.Scanner\n\nfunc buildKey(header string) map[string]byte {\n\tkeyMap := make(map[string]byte)\n\tvar key int64\n\tdigit := uint(1)\n\tfor i := range header {\n\t\tif key == (2<<(digit-1) - 1) {\n\t\t\tkey = 0\n\t\t\tdigit++\n\t\t}\n\t\tbinary := strconv.FormatInt(key, 2)\n\t\tbinary = strings.Repeat(\"0\", int(digit)-len(binary)) + binary\n\t\tkeyMap[binary] = header[i]\n\t\tkey++\n\t}\n\treturn keyMap\n}\n\nfunc getLength(l string) int {\n\tvar n int\n\tfmt.Sscanf(l, \"%b\", &n)\n\treturn n\n}\n\n\n\nfunc main() {\n\tin, _ := os.Open(\"213.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"213.out\")\n\tdefer out.Close()\n\n\ts = bufio.NewScanner(in)\n\ts.Split(bufio.ScanLines)\n\n\tvar line string\n\tfor s.Scan() {\n\t\tif line = s.Text(); line == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tsolve(out, line)\n\t}\n}\n\nfunc solve(out io.Writer, header string) ", "output": "{\n\tkeyMap := buildKey(header)\n\tvar l int\n\tvar line, code string\n\ts.Scan()\n\tfor line = s.Text(); line != \"000\"; {\n\t\tl, line = getLength(line[:3]), line[3:]\n\t\tfor {\n\t\t\tcode, line = line[:l], line[l:]\n\t\t\tif len(line) < l {\n\t\t\t\ts.Scan()\n\t\t\t\tline += s.Text()\n\t\t\t}\n\t\t\tif strings.Count(code, \"1\") == l {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfmt.Fprintf(out, \"%c\", keyMap[code])\n\t\t}\n\t}\n\tfmt.Fprintln(out)\n}"} {"input": "package iso20022\n\n\ntype ActionMessage3 struct {\n\n\tDestination *UserInterface3Code `xml:\"Dstn\"`\n\n\tFormat *OutputFormat1Code `xml:\"Frmt,omitempty\"`\n\n\tContent *Max20000Text `xml:\"Cntt\"`\n}\n\nfunc (a *ActionMessage3) SetDestination(value string) {\n\ta.Destination = (*UserInterface3Code)(&value)\n}\n\n\n\nfunc (a *ActionMessage3) SetContent(value string) {\n\ta.Content = (*Max20000Text)(&value)\n}\n\nfunc (a *ActionMessage3) SetFormat(value string) ", "output": "{\n\ta.Format = (*OutputFormat1Code)(&value)\n}"} {"input": "package common\n\nimport (\n\t\"encoding/binary\"\n\t\"sort\"\n)\n\n\n\ntype Uint64Slice []uint64\n\nfunc (p Uint64Slice) Len() int { return len(p) }\nfunc (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] }\nfunc (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p Uint64Slice) Sort() { sort.Sort(p) }\n\nfunc SearchUint64s(a []uint64, x uint64) int {\n\treturn sort.Search(len(a), func(i int) bool { return a[i] >= x })\n}\n\nfunc (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) }\n\n\n\nfunc PutUint64LE(dest []byte, i uint64) {\n\tbinary.LittleEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64LE(src []byte) uint64 {\n\treturn binary.LittleEndian.Uint64(src)\n}\n\nfunc PutUint64BE(dest []byte, i uint64) {\n\tbinary.BigEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64BE(src []byte) uint64 {\n\treturn binary.BigEndian.Uint64(src)\n}\n\nfunc PutInt64LE(dest []byte, i int64) {\n\tbinary.LittleEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64LE(src []byte) int64 {\n\treturn int64(binary.LittleEndian.Uint64(src))\n}\n\n\n\nfunc GetInt64BE(src []byte) int64 {\n\treturn int64(binary.BigEndian.Uint64(src))\n}\n\nfunc PutInt64BE(dest []byte, i int64) ", "output": "{\n\tbinary.BigEndian.PutUint64(dest, uint64(i))\n}"} {"input": "package quick\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc Test_QuickSort(t *testing.T) ", "output": "{\n\tarr := []int{4, 5, 9, 2, 6, 8, 2, 1, 7, 3}\n\tif QuickSort(arr); !reflect.DeepEqual(arr, []int{1, 2, 2, 3, 4, 5, 6, 7, 8, 9}) {\n\t\tt.Fatal(arr)\n\t}\n}"} {"input": "package geetplaban\n\nimport \"sync/atomic\"\n\ntype NextIdGetter struct {\n\tnext_id *uint32\n}\n\nfunc NewNextIdGettr(initial_value uint32) *NextIdGetter {\n\tx := new(uint32)\n\t*x = initial_value\n\n\treturn &NextIdGetter{x}\n}\n\n\n\nfunc (next *NextIdGetter) NextId() uint ", "output": "{\n\tnext_id := atomic.AddUint32(next.next_id, 1)\n\treturn uint(next_id)\n}"} {"input": "package main\n\nimport ()\n\ntype channel struct {\n\tpath string\n\tqueue queue\n\tconnections connections\n\th *hub\n}\n\ntype connections map[*connection]interface {\n}\n\nfunc (c *channel) run() {\n\tincr(\"channels\", 1)\n\tdefer c.stop()\n\tfor cmd := range c.queue {\n\t\tswitch cmd.cmd {\n\t\tcase SUBSCRIBE:\n\t\t\tc.subscribe(cmd.conn)\n\t\tcase UNSUBSCRIBE:\n\t\t\tc.unsubscribe(cmd.conn)\n\t\t\tif len(c.connections) == 0 {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase PUBLISH:\n\t\t\tc.publish(cmd.text)\n\t\tcase BROADCAST:\n\t\t\tc.broadcast(cmd.text)\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (c *channel) stop() {\n\tclose(c.queue)\n\tc.h.queue <- command{cmd: REMOVE, path: c.path}\n\tdecr(\"channels\", 1)\n}\n\nfunc (c *channel) subscribe(conn *connection) {\n\tc.connections[conn] = nil\n}\n\n\n\nfunc (c *channel) publish(text []byte) {\n\tif len(text) == 0 {\n\t\treturn\n\t}\n\tc.h.queue <- command{cmd: PUBLISH, path: c.path, text: text}\n}\n\nfunc (c *channel) broadcast(text []byte) {\n\tif len(text) == 0 {\n\t\treturn\n\t}\n\tfor conn := range c.connections {\n\t\tselect {\n\t\tcase conn.send <- text:\n\t\tdefault:\n\t\t\tc.unsubscribe(conn)\n\t\t}\n\t}\n}\n\nfunc (c *channel) unsubscribe(conn *connection) ", "output": "{\n\tif _, ok := c.connections[conn]; ok {\n\t\tclose(conn.send)\n\t\tdelete(c.connections, conn)\n\t}\n}"} {"input": "package disk\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/object\"\n)\n\ntype shrink struct {\n\t*flags.DatastoreFlag\n\n\tcopy *bool\n}\n\nfunc init() {\n\tcli.Register(\"datastore.disk.shrink\", &shrink{})\n}\n\n\n\nfunc (cmd *shrink) Process(ctx context.Context) error {\n\treturn cmd.DatastoreFlag.Process(ctx)\n}\n\nfunc (cmd *shrink) Usage() string {\n\treturn \"VMDK\"\n}\n\nfunc (cmd *shrink) Description() string {\n\treturn `Shrink VMDK on DS.\n\nExamples:\n govc datastore.disk.shrink disks/disk1.vmdk`\n}\n\nfunc (cmd *shrink) Run(ctx context.Context, f *flag.FlagSet) error {\n\tdc, err := cmd.Datacenter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tds, err := cmd.Datastore()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm := object.NewVirtualDiskManager(ds.Client())\n\tpath := ds.Path(f.Arg(0))\n\ttask, err := m.ShrinkVirtualDisk(ctx, path, dc, cmd.copy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger := cmd.ProgressLogger(fmt.Sprintf(\"Shrinking %s...\", path))\n\tdefer logger.Wait()\n\n\t_, err = task.WaitForResult(ctx, logger)\n\treturn err\n}\n\nfunc (cmd *shrink) Register(ctx context.Context, f *flag.FlagSet) ", "output": "{\n\tcmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)\n\tcmd.DatastoreFlag.Register(ctx, f)\n\n\tf.Var(flags.NewOptionalBool(&cmd.copy), \"copy\", \"Perform shrink in-place mode if false, copy-shrink mode otherwise\")\n}"} {"input": "package blocksutil\n\nimport \"gx/ipfs/Qmej7nf81hi2x2tvjRBF3mcp74sQyuDH4VMYDGd1YtXjb2/go-block-format\"\n\n\n\nfunc NewBlockGenerator() BlockGenerator {\n\treturn BlockGenerator{}\n}\n\n\n\n\n\ntype BlockGenerator struct {\n\tseq int\n}\n\n\nfunc (bg *BlockGenerator) Next() *blocks.BasicBlock {\n\tbg.seq++\n\treturn blocks.NewBlock([]byte(string(bg.seq)))\n}\n\n\n\n\nfunc (bg *BlockGenerator) Blocks(n int) []blocks.Block ", "output": "{\n\tblocks := make([]blocks.Block, 0, n)\n\tfor i := 0; i < n; i++ {\n\t\tb := bg.Next()\n\t\tblocks = append(blocks, b)\n\t}\n\treturn blocks\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\tvar slice []int64 = nil\n\tfmt.Println(\"slice-read\", len(slice))\n\tvar map1 map[int]int = nil\n\t{\n\t\tv, ok := map1[1]\n\t\tfmt.Println(\"map-read\", v, ok)\n\t}\n\tvar c1 chan int = nil\n\tgo reading(c1)\n\tfmt.Println(\"chan-read\")\n\ttime.Sleep(time.Second*1)\n}\n\nfunc reading(ch chan int) ", "output": "{\n\tfor n:=0; n<10; n++ {\n\t\tvar v int\n\t\tvar ok bool\n\t\tselect {\n\t\tcase v, ok = <-ch:\n\t\t\tfmt.Println(\"read\", v, ok, \"from\", ch)\n\t\tdefault:\n\t\t\ttime.Sleep(time.Millisecond*10)\n\t\t}\n\t}\n}"} {"input": "package astutils\n\nimport (\n\t\"go/ast\"\n\t\"go/types\"\n)\n\n\nfunc FieldListName(fieldList *ast.FieldList, fieldPosition int, namePosition int) *string {\n\tnames := FieldListNames(fieldList, fieldPosition)\n\n\tif names == nil || len(names) <= namePosition {\n\t\treturn nil\n\t}\n\n\tname := names[namePosition]\n\n\tif name == nil {\n\t\treturn nil\n\t}\n\n\treturn &name.Name\n}\n\n\nfunc FieldListNames(fieldList *ast.FieldList, position int) []*ast.Ident {\n\tif fieldList == nil {\n\t\treturn nil\n\t}\n\n\tif len(fieldList.List) <= position {\n\t\treturn nil\n\t}\n\n\tfield := fieldList.List[position]\n\n\tif field == nil {\n\t\treturn nil\n\t}\n\n\treturn field.Names\n}\n\n\n\n\n\n\nfunc HasFieldListLength(fieldList *ast.FieldList, expectedLength int) bool {\n\tif fieldList == nil {\n\t\treturn expectedLength == 0\n\t}\n\n\treturn len(fieldList.List) == expectedLength\n}\n\n\nfunc IsFieldListType(fieldList *ast.FieldList, position int, exprFunc func(ast.Expr) bool) bool {\n\tt := FieldListType(fieldList, position)\n\n\treturn t != nil && exprFunc(*t)\n}\n\n\nfunc IsFieldListTypePackageType(fieldList *ast.FieldList, position int, info *types.Info, packageSuffix string, typeName string) bool {\n\tt := FieldListType(fieldList, position)\n\n\treturn t != nil && IsPackageFunctionFieldListType(*t, info, packageSuffix, typeName)\n}\n\nfunc FieldListType(fieldList *ast.FieldList, position int) *ast.Expr ", "output": "{\n\tif fieldList == nil {\n\t\treturn nil\n\t}\n\n\tif len(fieldList.List) <= position {\n\t\treturn nil\n\t}\n\n\tfield := fieldList.List[position]\n\n\tif field == nil {\n\t\treturn nil\n\t}\n\n\treturn &field.Type\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/coreos/etcd/client\"\n\t\"github.com/monsooncommerce/etcdDocumentAccessor\"\n)\n\n\n\nfunc main() {\n\tkeysApi, err := getKeysApi()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\taccessor := etcdDocumentAccessor.EtcdDocumentAccessor{\n\t\tDocumentKey: \"/testkey\",\n\t\tKeysAPI: keysApi,\n\t}\n\n\tvalue, _ := accessor.Get()\n\tfmt.Printf(\"value: %v\\n\", value)\n\n\taccessor.Set(\"this is a whole new value\")\n\tvalue, _ = accessor.Get()\n\tfmt.Printf(\"I just set this value: \\\"%v\\\"\\n\", value)\n\n\tresultChan := accessor.Watch()\n\n\tgo func(accessor *etcdDocumentAccessor.EtcdDocumentAccessor) {\n\t\t<-time.After(2 * time.Second)\n\t\taccessor.Set(\"value from inside go func\")\n\t}(&accessor)\n\n\tgotValue := false\n\tfor !gotValue {\n\t\tselect {\n\t\tcase value := <-resultChan:\n\t\t\tfmt.Printf(\"watched value: %v\\n\", value)\n\t\t\tgotValue = true\n\t\tcase <-time.After(time.Second):\n\t\t\tfmt.Printf(\"waited a second, still nothing from the watcher\\n\")\n\t\t}\n\t}\n}\n\nfunc getKeysApi() (client.KeysAPI, error) ", "output": "{\n\tcfg := client.Config{\n\t\tEndpoints: []string{\"http://your-etcd-cluster.domain:2379\"},\n\t\tTransport: client.DefaultTransport,\n\t\tHeaderTimeoutPerRequest: time.Second,\n\t}\n\tconn, err := client.New(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client.NewKeysAPI(conn), nil\n\n}"} {"input": "package config\n\nimport (\n\t\"os\"\n)\n\ntype config struct {\n\tBasePath string\n\tDestPath string\n}\n\nvar current = config{}\n\n\n\n\n\nfunc GetDestPath() string {\n\treturn current.DestPath\n}\n\nfunc init() {\n\tcurrent.BasePath = \"./\"\n\tif len(os.Args) > 1 {\n\t\tcurrent.BasePath = os.Args[1]\n\t}\n}\n\nfunc GetBasePath() string ", "output": "{\n\treturn current.BasePath\n}"} {"input": "package cmd\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/subcommands\"\n\t\"gvisor.dev/gvisor/runsc/config\"\n\t\"gvisor.dev/gvisor/runsc/container\"\n\t\"gvisor.dev/gvisor/runsc/flag\"\n\t\"gvisor.dev/gvisor/runsc/specutils\"\n)\n\n\ntype Start struct{}\n\n\nfunc (*Start) Name() string {\n\treturn \"start\"\n}\n\n\nfunc (*Start) Synopsis() string {\n\treturn \"start a secure container\"\n}\n\n\nfunc (*Start) Usage() string {\n\treturn `start - start a secure container.`\n}\n\n\nfunc (*Start) SetFlags(*flag.FlagSet) {}\n\n\n\n\nfunc (*Start) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus ", "output": "{\n\tif f.NArg() != 1 {\n\t\tf.Usage()\n\t\treturn subcommands.ExitUsageError\n\t}\n\n\tid := f.Arg(0)\n\tconf := args[0].(*config.Config)\n\n\tc, err := container.Load(conf.RootDir, container.FullID{ContainerID: id}, container.LoadOpts{})\n\tif err != nil {\n\t\tFatalf(\"loading container: %v\", err)\n\t}\n\tif _, err := specutils.ReadSpec(c.BundleDir, conf); err != nil {\n\t\tFatalf(\"reading spec: %v\", err)\n\t}\n\n\tif err := c.Start(conf); err != nil {\n\t\tFatalf(\"starting container: %v\", err)\n\t}\n\treturn subcommands.ExitSuccess\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nconst cookieName = \"Site-Cookie1\"\n\nfunc main() {\n\thttp.Handle(\"/favicon.ico\", http.NotFoundHandler())\n\thttp.HandleFunc(\"/\", root)\n\thttp.HandleFunc(\"/set\", set)\n\thttp.HandleFunc(\"/read\", read)\n\thttp.HandleFunc(\"/expire\", expire)\n\tlog.Println(\"Starting server on 8080\")\n\tlog.Fatalln(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc root(w http.ResponseWriter, _ *http.Request) {\n\tfmt.Fprint(w, `

Set

`)\n}\n\nfunc set(w http.ResponseWriter, _ *http.Request) {\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: cookieName,\n\t\tValue: \"This is a Site Cookie created\",\n\t})\n\tfmt.Fprint(w, `

Read

`)\n}\n\nfunc read(w http.ResponseWriter, r *http.Request) {\n\tcoo, err := r.Cookie(cookieName)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Redirect(w, r, \"/set\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tfmt.Fprintf(w, \"

Cookie Value: %s

\", coo.Value)\n\tfmt.Fprint(w, `

Expire

`)\n}\n\n\n\nfunc expire(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tcoo, err := r.Cookie(cookieName)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Redirect(w, r, \"/set\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tcoo.MaxAge = -1 \n\thttp.SetCookie(w, coo)\n\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n}"} {"input": "package models\n\nimport (\n\t\"fmt\"\n)\n\nconst (\n\tapiProductByID = \"products/%d\"\n)\n\n\n\ntype productData struct {\n\tData *Product `json:\"product\"`\n}\n\n\n\ntype Product struct {\n\tID int `json:\"id\"`\n\tFace string `json:\"face\"`\n\tSize int `json:\"size\"`\n\tPrice int `json:\"price\"`\n}\n\n\n\n\n\nfunc ProductByID(id int) (*Product, error) ", "output": "{\n\tvar d productData\n\terr := objectFromURN(fmt.Sprintf(apiProductByID, id), &d)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn d.Data, nil\n}"} {"input": "package utfutil\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"io\"\n\t\"io/ioutil\"\n)\n\n\nfunc Encode(dst io.Writer, src io.Reader, endines binary.ByteOrder) error {\n\tp, err := ioutil.ReadAll(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif p[0] == 0xfe && p[1] == 0xff {\n\t\tp = p[2:]\n\t}\n\n\tvar (\n\t\ti, j, n = 0, 0, len(p)\n\t\tout = make([]byte, n*2)\n\t\tw uint16\n\t)\n\n\tfor i < n {\n\t\tw = endines.Uint16(p[i:])\n\t\ti += 2\n\n\t\tswitch {\n\t\tcase w <= 0x7f:\n\t\t\tout[j] = byte(w)\n\t\t\tj++\n\t\tcase w <= 0x7ff:\n\t\t\tout[j] = byte(w>>6 | 0xc0)\n\t\t\tj++\n\t\t\tout[j] = byte(w&0x3f | 0x80)\n\t\t\tj++\n\t\tcase w <= 0xffff:\n\t\t\tout[j] = byte(w>>12 | 0xe0)\n\t\t\tj++\n\t\t\tout[j] = byte(w>>6&0x3f | 0x80)\n\t\t\tj++\n\t\t\tout[j] = byte(w&0x3f | 0x80)\n\t\t\tj++\n\t\t}\n\t}\n\t_, err = dst.Write(out[:j])\n\treturn err\n}\n\n\n\n\nfunc EncodeSlice(p []byte, endienes binary.ByteOrder) []byte ", "output": "{\n\tsrc := new(bytes.Buffer)\n\tsrc.Write(p)\n\tdst := new(bytes.Buffer)\n\tEncode(dst, src, endienes)\n\treturn dst.Bytes()\n}"} {"input": "package packages\n\nimport (\n\t\"fmt\"\n\t\"github.com/alexandrecarlton/gogurt\"\n)\n\ntype PkgConfig struct{}\n\nfunc (pkgconfig PkgConfig) Name() string {\n\treturn \"pkg-config\"\n}\n\n\n\nfunc (pkgconfig PkgConfig) Build(config gogurt.Config) error {\n\tconfigure := gogurt.ConfigureCmd{\n\t\tPrefix: config.InstallDir(pkgconfig),\n\t\tArgs: []string{\n\t\t\t\"--disable-shared\",\n\t\t\t\"--enable-static\",\n\t\t\t\"--with-internal-glib\",\n\t\t},\n\t}.Cmd()\n\tif err := configure.Run(); err != nil {\n\t\treturn err\n\t}\n\tmake := gogurt.MakeCmd{\n\t\tJobs: config.NumCores,\n\t}.Cmd()\n\treturn make.Run()\n}\n\nfunc (pkgconfig PkgConfig) Install(config gogurt.Config) error {\n\tmakeInstall := gogurt.MakeCmd{\n\t\tArgs: []string{\n\t\t\t\"install\",\n\t\t},\n\t}.Cmd()\n\treturn makeInstall.Run()\n}\n\nfunc (pkgconfig PkgConfig) Dependencies() []gogurt.Package {\n\treturn []gogurt.Package{}\n}\n\nfunc (pkgconfig PkgConfig) URL(version string) string ", "output": "{\n\treturn fmt.Sprintf(\"https://pkgconfig.freedesktop.org/releases/pkg-config-%s.tar.gz\", version)\n}"} {"input": "package main\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"io\"\n\t\"log\"\n)\n\ntype proxy struct {\n\ttransport *http.Transport\n\taddr string\n}\n\n\n\nfunc (p *proxy) dial(network string, addr string) (conn net.Conn, err error) {\n\treturn net.Dial(\"tcp\", p.addr)\n}\n\nfunc (p *proxy) proxyPass(w http.ResponseWriter, r *http.Request) {\n\thost, _, _ := net.SplitHostPort(r.RemoteAddr)\n\tr.Header.Add(\"X-Forwarded-For\", host)\n\tr.URL.Scheme = \"http\"\n\tr.URL.Host = r.Host\n\tresp, err := p.transport.RoundTrip(r)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tw.WriteHeader(http.StatusBadGateway)\n\t\tw.Write([]byte(\"

502 Bad Gateway

\"))\n\t\treturn\n\t}\n\theader := w.Header()\n\tfor k, v := range resp.Header {\n\t\tfor _, v1 := range v {\n\t\t\theader.Add(k, v1)\n\t\t}\n\t}\n\tw.WriteHeader(resp.StatusCode)\n\tio.Copy(w, resp.Body)\n\tresp.Body.Close()\n}\n\nfunc newProxy(addr string) *proxy ", "output": "{\n\tp := &proxy{addr: addr}\n\tp.transport = &http.Transport{\n\t\tDial: p.dial,\n\t}\n\treturn p\n}"} {"input": "package echo\n\ntype (\n\tGroup struct {\n\t\techo Echo\n\t}\n)\n\nfunc (g *Group) Use(m ...Middleware) {\n\tfor _, h := range m {\n\t\tg.echo.middleware = append(g.echo.middleware, wrapMiddleware(h))\n\t}\n}\n\nfunc (g *Group) Connect(path string, h Handler) {\n\tg.echo.Connect(path, h)\n}\n\nfunc (g *Group) Delete(path string, h Handler) {\n\tg.echo.Delete(path, h)\n}\n\nfunc (g *Group) Get(path string, h Handler) {\n\tg.echo.Get(path, h)\n}\n\nfunc (g *Group) Head(path string, h Handler) {\n\tg.echo.Head(path, h)\n}\n\nfunc (g *Group) Options(path string, h Handler) {\n\tg.echo.Options(path, h)\n}\n\nfunc (g *Group) Patch(path string, h Handler) {\n\tg.echo.Patch(path, h)\n}\n\nfunc (g *Group) Post(path string, h Handler) {\n\tg.echo.Post(path, h)\n}\n\nfunc (g *Group) Put(path string, h Handler) {\n\tg.echo.Put(path, h)\n}\n\nfunc (g *Group) Trace(path string, h Handler) {\n\tg.echo.Trace(path, h)\n}\n\nfunc (g *Group) WebSocket(path string, h HandlerFunc) {\n\tg.echo.WebSocket(path, h)\n}\n\nfunc (g *Group) Static(path, root string) {\n\tg.echo.Static(path, root)\n}\n\n\n\nfunc (g *Group) ServeFile(path, file string) {\n\tg.echo.ServeFile(path, file)\n}\n\nfunc (g *Group) Group(prefix string, m ...Middleware) *Group {\n\treturn g.echo.Group(prefix, m...)\n}\n\nfunc (g *Group) ServeDir(path, root string) ", "output": "{\n\tg.echo.ServeDir(path, root)\n}"} {"input": "package blobstoredbstatesnapshotio\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/nyaxt/otaru/metadata\"\n)\n\nfunc generateBlobpath() string {\n\treturn fmt.Sprintf(\"%s_SimpleSSLocator\", metadata.INodeDBSnapshotBlobpathPrefix)\n}\n\nvar simplesslocatorTxID int64\n\ntype SimpleSSLocator struct{}\n\n\n\nfunc (SimpleSSLocator) GenerateBlobpath() string {\n\treturn generateBlobpath()\n}\n\nfunc (SimpleSSLocator) Put(blobpath string, txid int64) error {\n\tsimplesslocatorTxID = txid\n\treturn nil\n}\n\nfunc (SimpleSSLocator) DeleteOld(ctx context.Context, threshold int, dryRun bool) ([]string, error) {\n\treturn []string{}, nil\n}\n\nfunc (SimpleSSLocator) Locate(history int) (string, int64, error) ", "output": "{\n\treturn generateBlobpath(), simplesslocatorTxID, nil\n}"} {"input": "package underscore\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestIsMatch(t *testing.T) ", "output": "{\n\tm := TestModel{ 1, \"one\" }\n\tok := IsMatch(nil, nil)\n\tif ok {\n\t\tt.Error(\"wrong\")\n\t\treturn\n\t}\n\n\tok = IsMatch(m, nil)\n\tif ok {\n\t\tt.Error(\"wrong\")\n\t\treturn\n\t}\n\n\tok = IsMatch(m, map[string]interface{}{\n\t\t\"id\": m.Id,\n\t\t\"name\": \"a\",\n\t})\n\tif ok {\n\t\tt.Error(\"wrong\")\n\t\treturn\n\t}\n\n\tok = IsMatch(m, map[string]interface{}{\n\t\t\"id\": m.Id,\n\t\t\"name\": m.Name,\n\t})\n\tif !ok {\n\t\tt.Error(\"wrong\")\n\t}\n}"} {"input": "package cobra\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\n\n\nfunc TestCompleteCmdInFishScript(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse: \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun: emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, true))\n\toutput := buf.String()\n\n\tcheck(t, output, ShellCompRequestCmd)\n\tcheckOmit(t, output, ShellCompNoDescRequestCmd)\n}\n\nfunc TestProgWithDash(t *testing.T) {\n\trootCmd := &Command{Use: \"root-dash\", Args: NoArgs, Run: emptyRun}\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, false))\n\toutput := buf.String()\n\n\tcheck(t, output, \"__root_dash_perform_completion\")\n\tcheckOmit(t, output, \"__root-dash_perform_completion\")\n\n\tcheck(t, output, \"-c root-dash\")\n\tcheckOmit(t, output, \"-c root_dash\")\n}\n\nfunc TestProgWithColon(t *testing.T) {\n\trootCmd := &Command{Use: \"root:colon\", Args: NoArgs, Run: emptyRun}\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, false))\n\toutput := buf.String()\n\n\tcheck(t, output, \"__root_colon_perform_completion\")\n\tcheckOmit(t, output, \"__root:colon_perform_completion\")\n\n\tcheck(t, output, \"-c root:colon\")\n\tcheckOmit(t, output, \"-c root_colon\")\n}\n\nfunc TestCompleteNoDesCmdInFishScript(t *testing.T) ", "output": "{\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse: \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun: emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, false))\n\toutput := buf.String()\n\n\tcheck(t, output, ShellCompNoDescRequestCmd)\n}"} {"input": "package x11\n\nimport (\n\t\"C\"\n\t\"unsafe\"\n)\n\ntype SelectionEvent C.XSelectionEvent\n\nfunc (evt *SelectionEvent) Requestor() Window {\n\treturn Window(evt.requestor)\n}\n\nfunc (evt *SelectionEvent) Selection() Atom {\n\treturn Atom(evt.selection)\n}\n\nfunc (evt *SelectionEvent) Target() Atom {\n\treturn Atom(evt.target)\n}\n\nfunc (evt *SelectionEvent) Property() Atom {\n\treturn Atom(evt.property)\n}\n\nfunc (evt *SelectionEvent) When() C.Time {\n\treturn evt.time\n}\n\n\n\nfunc (evt *SelectionEvent) ToEvent() *Event ", "output": "{\n\treturn (*Event)(unsafe.Pointer(evt))\n}"} {"input": "package mysql\n\nimport (\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"github.com/jmoiron/sqlx\"\n\t\"github.com/stellar/federation/db\"\n)\n\ntype MysqlDriver struct {\n\tdatabase *sqlx.DB\n}\n\nfunc (d *MysqlDriver) Init(url string) (err error) {\n\td.database, err = sqlx.Connect(\"mysql\", url)\n\treturn\n}\n\n\n\nfunc (d *MysqlDriver) GetByAccountId(accountId, query string) (*db.ReverseFederationRecord, error) {\n\tvar record db.ReverseFederationRecord\n\terr := d.database.Get(&record, query, accountId)\n\tif err != nil {\n\t\tif err.Error() == \"sql: no rows in result set\" {\n\t\t\treturn nil, nil\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &record, nil\n}\n\nfunc (d *MysqlDriver) GetByStellarAddress(name, query string) (*db.FederationRecord, error) ", "output": "{\n\tvar record db.FederationRecord\n\terr := d.database.Get(&record, query, name)\n\tif err != nil {\n\t\tif err.Error() == \"sql: no rows in result set\" {\n\t\t\treturn nil, nil\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &record, nil\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/IronPark/gotham/models\"\n\t\"github.com/IronPark/gotham/module/controller\"\n\t\"github.com/IronPark/gotham/module/git\"\n\t\"github.com/zenazn/goji/web\"\n\t\"net/http\"\n)\n\ntype ApiController struct {\n\tcontroller.Controller\n}\n\nfunc (ctr *ApiController) Get(c web.C, r *http.Request) (string, int) {\n\tc.Env[\"Title\"] = \"Default Project - free Go website project template\"\n\tc.Env[\"Nav\"] = PAGE_DASHBOARD\n\n\treturn ctr.RenderTemplate(\"index.html\", c.Env), http.StatusOK\n}\n\n\n\nfunc (ctr *ApiController) Post(c web.C, r *http.Request) (string, int) ", "output": "{\n\n\trepoName := r.FormValue(\"name\")\n\tdesc := r.FormValue(\"description\")\n\tuser := \"test\"\n\tif repoName != \"\" {\n\t\tgit.NewRepo(user, repoName).CreateRepo()\n\t\tmodels.NewProject(user, repoName, desc)\n\t}\n\treturn ctr.RenderTemplate(\"index.html\", c.Env), http.StatusOK\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\n\t. \"github.com/emicklei/go-restful/v3\"\n)\n\n\n\n\n\n\n\n\nfunc main() {\n\tDefaultContainer.Router(CurlyRouter{})\n\tws := new(WebService)\n\n\tws.Route(ws.GET(\"/resource:validate\").To(validateHandler))\n\tws.Route(ws.POST(\"/resource/{resourceId}:init\").To(initHandler))\n\tws.Route(ws.POST(\"/resource/{resourceId}:recycle\").To(recycleHandler))\n\n\tAdd(ws)\n\n\tprintln(\"[go-restful] serve path tails from http:localhost:8080/basepath\")\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc validateHandler(req *Request, resp *Response) {\n\tio.WriteString(resp, \"validate resource completed\")\n}\n\nfunc initHandler(req *Request, resp *Response) {\n\tio.WriteString(resp, \"init resource completed, resourceId: \"+req.PathParameter(\"resourceId\"))\n}\n\n\n\nfunc recycleHandler(req *Request, resp *Response) ", "output": "{\n\tio.WriteString(resp, \"recycle resource completed, resourceId: \"+req.PathParameter(\"resourceId\"))\n}"} {"input": "package common\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\ntype NodeMetastate struct {\n\n\tLedgerHeight uint64\n}\n\n\nfunc NewNodeMetastate(height uint64) *NodeMetastate {\n\treturn &NodeMetastate{height}\n}\n\n\n\n\n\nfunc (n *NodeMetastate) Height() uint64 {\n\treturn n.LedgerHeight\n}\n\n\nfunc (n *NodeMetastate) Update(height uint64) {\n\tn.LedgerHeight = height\n}\n\n\nfunc FromBytes(buf []byte) (*NodeMetastate, error) {\n\tstate := NodeMetastate{}\n\treader := bytes.NewReader(buf)\n\terr := binary.Read(reader, binary.BigEndian, &state)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn &state, nil\n}\n\nfunc (n *NodeMetastate) Bytes() ([]byte, error) ", "output": "{\n\tbuffer := new(bytes.Buffer)\n\terr := binary.Write(buffer, binary.BigEndian, *n)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn buffer.Bytes(), nil\n}"} {"input": "package version\n\nimport (\n\t\"github.com/coreos/fleet/Godeps/_workspace/src/github.com/coreos/go-semver/semver\"\n)\n\nconst Version = \"0.11.2+git\"\n\nvar SemVersion semver.Version\n\n\n\nfunc init() ", "output": "{\n\tsv, err := semver.NewVersion(Version)\n\tif err != nil {\n\t\tpanic(\"bad version string!\")\n\t}\n\tSemVersion = *sv\n}"} {"input": "package buckets\n\nimport (\n\t\"github.com/campadrenalin/scrap\"\n\t\"testing\"\n)\n\n\n\nfunc TestAnyBucket_OneItem(t *testing.T) {\n\tb := AnyBucket{\n\t\tChildren: []scrap.Bucket{\n\t\t\tscrap.NewCountBucket(1),\n\t\t},\n\t}\n\ttests := bt_slice{\n\t\tbt{\"foo\", true, \"First should succeed\"},\n\t\tbt{\"foo\", false, \"Second should fail\"},\n\t}\n\ttests.Run(t, b)\n}\n\nfunc TestAnyBucket_MultipleItems(t *testing.T) {\n\tb := AnyBucket{\n\t\tChildren: []scrap.Bucket{\n\t\t\tscrap.NewCountBucket(1),\n\t\t\tscrap.NewCountBucket(2),\n\t\t},\n\t}\n\ttests := bt_slice{\n\t\tbt{\"foo\", true, \"First bucket says yes\"},\n\t\tbt{\"foo\", true, \"First bucket exhausted, second says yes\"},\n\t\tbt{\"foo\", true, \"Second bucket says yes for the final time\"},\n\t\tbt{\"foo\", false, \"Second bucket exhausted\"},\n\t}\n\ttests.Run(t, b)\n\n\tb.Children[0].(*scrap.CountBucket).SetMaxHits(3)\n\ttests = bt_slice{\n\t\tbt{\"foo\", true, \"First bucket says yes\"},\n\t\tbt{\"foo\", true, \"First bucket says yes for the final time\"},\n\t\tbt{\"foo\", false, \"Both buckets exhausted\"},\n\t}\n\ttests.Run(t, b)\n}\n\nfunc TestAnyBucket_Empty(t *testing.T) ", "output": "{\n\tb := AnyBucket{}\n\tif b.Check(\"foo\") {\n\t\tt.Fatal(\"Should always return false when there are no children\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/franela/goreq\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype VaultRequest struct {\n\tgoreq.Request\n}\n\n\n\ntype VaultWrappedResponse struct {\n\tData struct {\n\t\tWrappedSecret string `json:\"response\"`\n\t} `json:\"data\"`\n}\n\nfunc (vr *VaultWrappedResponse) Unwrap(v interface{}) error {\n\treturn json.Unmarshal([]byte(vr.Data.WrappedSecret), v)\n}\n\nfunc (r VaultRequest) Do() (*goreq.Response, error) ", "output": "{\n\tconfig := goreq.DefaultTransport.(*http.Transport).TLSClientConfig\n\tif config != nil {\n\t\tr.Insecure = config.InsecureSkipVerify\n\t}\n\tresp, err := r.Request.Do()\n\tfor err == nil && resp.StatusCode == 307 {\n\t\tio.Copy(ioutil.Discard, resp.Body)\n\t\tresp.Body.Close()\n\t\tr.Request.Uri = resp.Header.Get(\"Location\")\n\t\tresp, err = r.Request.Do()\n\t}\n\treturn resp, err\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"github.com/go-swagger/go-swagger/errors\"\n\t\"github.com/go-swagger/go-swagger/strfmt\"\n\t\"github.com/go-swagger/go-swagger/swag\"\n)\n\n\ntype EmployeePageableResult struct {\n\n\tContent []Employee `json:\"content,omitempty\"`\n\n\tFirst bool `json:\"first,omitempty\"`\n\n\tLast bool `json:\"last,omitempty\"`\n\n\tNumber int32 `json:\"number,omitempty\"`\n\n\tNumberOfElements int32 `json:\"numberOfElements,omitempty\"`\n\n\tServerTime int64 `json:\"serverTime,omitempty\"`\n\n\tSize int32 `json:\"size,omitempty\"`\n\n\tTotalElements int32 `json:\"totalElements,omitempty\"`\n\n\tTotalPages int32 `json:\"totalPages,omitempty\"`\n}\n\n\n\n\nfunc (m *EmployeePageableResult) validateContent(formats strfmt.Registry) error {\n\n\tif swag.IsZero(m.Content) { \n\t\treturn nil\n\t}\n\n\tfor i := 0; i < len(m.Content); i++ {\n\n\t\tif err := m.Content[i].Validate(formats); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nfunc (m *EmployeePageableResult) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateContent(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\nvar configFileOptions map[string]interface{}\n\nfunc LoadConfigFile(file string) error {\n\tconfigFileOptions = nil\n\tif _, err := os.Stat(file); err != nil {\n\t\treturn nil\n\t}\n\tif s, err := ioutil.ReadFile(file); err != nil {\n\t\treturn err\n\t} else if err := yaml.Unmarshal(s, &configFileOptions); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc getConfigFileValue(key string) interface{} {\n\tif v, ok := configFileOptions[key]; ok {\n\t\treturn v\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc IsKeyInConfig(key string) bool {\n\t_, ok := configFileOptions[key]\n\treturn ok\n}\n\nfunc getConfigFileValueWithDefault(key string, defaultValue interface{}) interface{} {\n\tif v := getConfigFileValue(key); v != nil {\n\t\treturn v\n\t} else {\n\t\treturn defaultValue\n\t}\n}\n\n\n\nfunc GetConfigFileSlice(key string) []string {\n\tif v, ok := configFileOptions[key].([]interface{}); ok {\n\t\tretVal := []string{}\n\t\tfor _, e := range v {\n\t\t\tif strV, ok := e.(string); ok {\n\t\t\t\tretVal = append(retVal, strV)\n\t\t\t}\n\t\t}\n\t\treturn retVal\n\t} else {\n\t\treturn []string{}\n\t}\n}\n\n\n\nfunc GetConfigFileStringWithDefault(key string, defaultValue interface{}) string {\n\tv, _ := getConfigFileValueWithDefault(key, defaultValue).(string)\n\treturn v\n}\n\nfunc GetConfigFileString(key string) string ", "output": "{\n\tv, _ := getConfigFileValue(key).(string)\n\treturn v\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"text/tabwriter\"\n)\n\n\n\nfunc usageFor(fs *flag.FlagSet, usage string, extra string) func() {\n\treturn func() {\n\t\tvar b bytes.Buffer\n\t\tb.WriteString(\"Usage:\\n \" + usage + \"\\n\")\n\n\t\tvar options [][]string\n\t\tfs.VisitAll(func(f *flag.Flag) {\n\t\t\tvar opt = \" -\" + f.Name\n\n\t\t\tif f.DefValue != \"false\" {\n\t\t\t\topt += \"=\" + fmt.Sprintf(`\"%s\"`, f.DefValue)\n\t\t\t}\n\t\t\toptions = append(options, []string{opt, f.Usage})\n\t\t})\n\n\t\tif len(options) > 0 {\n\t\t\tb.WriteString(\"\\nOptions:\\n\")\n\t\t\toptionTable(&b, options)\n\t\t}\n\n\t\tfmt.Println(b.String())\n\n\t\tif len(extra) > 0 {\n\t\t\tfmt.Println(extra)\n\t\t}\n\t}\n}\n\nfunc optionTable(w io.Writer, rows [][]string) ", "output": "{\n\ttw := tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)\n\tfor _, row := range rows {\n\t\tfor i, cell := range row {\n\t\t\tif i > 0 {\n\t\t\t\ttw.Write([]byte(\"\\t\"))\n\t\t\t}\n\t\t\ttw.Write([]byte(cell))\n\t\t}\n\t\ttw.Write([]byte(\"\\n\"))\n\t}\n\ttw.Flush()\n}"} {"input": "package esicache\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/corestoreio/errors\"\n)\n\n\n\n\ntype Cacher interface {\n\tSet(key string, value []byte, expiration time.Duration) error\n\tGet(key string) ([]byte, error)\n}\n\n\n\nfunc NewCacher(url string) (Cacher, error) {\n\n\treturn nil, nil\n}\n\n\ntype Caches []Cacher\n\n\nfunc (c Caches) Set(key string, value []byte, expiration time.Duration) error {\n\treturn nil\n}\n\n\nfunc (c Caches) Get(key string) ([]byte, error) {\n\treturn nil, nil\n}\n\n\nvar MainRegistry = ®istry{\n\tcaches: make(map[string]Caches),\n}\n\ntype registry struct {\n\tmu sync.RWMutex\n\tcaches map[string]Caches\n}\n\nfunc (r *registry) Get(ctx context.Context, scope, alias, key string) error {\n\treturn errors.New(\"TODO IMPLEMENT\")\n}\n\n\n\n\nfunc (r *registry) Register(scope, url string) error {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tc, err := NewCacher(url)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"[esikv] NewCacher URL %q\", url)\n\t}\n\n\tif _, ok := r.caches[scope]; !ok {\n\t\tr.caches[scope] = make(Caches, 0, 2)\n\t}\n\tr.caches[scope] = append(r.caches[scope], c)\n\n\treturn nil\n}\n\n\nfunc (r *registry) Len(scope string) int {\n\tr.mu.RLock()\n\tdefer r.mu.RUnlock()\n\treturn len(r.caches[scope])\n}\n\n\n\n\nfunc (r *registry) Clear() ", "output": "{\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tr.caches = make(map[string]Caches)\n}"} {"input": "package graphs\n\nimport (\n\t\"math/rand\"\n\t\"testing\"\n)\n\nfunc TestFindCelebrity(t *testing.T) {\n\tfor _, test := range []struct {\n\t\tin [][]bool\n\t\twant int\n\t}{\n\t\t{[][]bool{\n\t\t\t{false, true}, \n\t\t\t{true, false}, \n\t\t}, -1},\n\t\t{[][]bool{\n\t\t\t{false, false, true}, \n\t\t\t{false, false, false}, \n\t\t\t{true, true, false}, \n\t\t}, -1},\n\t\t{[][]bool{\n\t\t\t{false, true, true}, \n\t\t\t{false, false, false}, \n\t\t\t{true, true, false}, \n\t\t}, 1},\n\t\t{[][]bool{\n\t\t\t{false, true, true, true, true}, \n\t\t\t{true, false, false, true, true}, \n\t\t\t{true, true, false, true, true}, \n\t\t\t{false, false, false, false, false}, \n\t\t\t{true, false, false, true, false}, \n\t\t}, 3},\n\t} {\n\t\tif got := FindCelebrity(test.in); got != test.want {\n\t\t\tt.Errorf(\"FindCelebrity(%v) = %d; want %d\", test.in, got, test.want)\n\t\t}\n\t}\n}\n\n\n\nfunc BenchmarkFindCelebrity1e1(b *testing.B) { benchFindCelebrity(b, 1e1) }\nfunc BenchmarkFindCelebrity1e2(b *testing.B) { benchFindCelebrity(b, 1e2) }\nfunc BenchmarkFindCelebrity1e3(b *testing.B) { benchFindCelebrity(b, 1e3) }\n\nfunc benchFindCelebrity(b *testing.B, size int) ", "output": "{\n\tg := rand.New(rand.NewSource(int64(size)))\n\tvar f [][]bool\n\tfor r := 0; r < size; r++ {\n\t\tf = append(f, make([]bool, size))\n\t\tfor c := 0; c < size; c++ {\n\t\t\tf[r][c] = g.Int()%size != 0\n\t\t}\n\t\tf[r][r] = false\n\t}\n\tcelebrity := size - 1\n\tfor i := 0; i < size; i++ {\n\t\tf[i][celebrity] = true\n\t}\n\tfor i := 0; i < size; i++ {\n\t\tf[celebrity][i] = false\n\t}\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tFindCelebrity(f)\n\t}\n}"} {"input": "package controllers\n\nimport ()\n\ntype MainController struct {\n\tBaseController\n}\n\n\n\nfunc (c *MainController) Get() ", "output": "{\n\n\tc.Data[\"IsLogin\"] = true\n\tc.Data[\"Title\"] = \"五 | 零 | 一\"\n\tc.Layout = \"layout/layout.html\"\n\tc.TplName = \"home.html\"\n}"} {"input": "package model\n\nimport (\n\t\"github.com/blevesearch/bleve\"\n\t\"github.com/blevesearch/bleve/analysis/analyzers/keyword_analyzer\"\n\t\"github.com/blevesearch/bleve/analysis/analyzers/simple_analyzer\"\n\t\"github.com/blevesearch/bleve/analysis/language/en\"\n)\n\n\nfunc InitIndex(filepath string) (bleve.Index, error) {\n\tindex, err := bleve.Open(filepath)\n\n\tif err != nil {\n\t\tindex, err = bleve.New(filepath, buildIndexMapping())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn index, nil\n}\n\n\n\nfunc buildIndexMapping() *bleve.IndexMapping ", "output": "{\n\tsimpleTextFieldMapping := bleve.NewTextFieldMapping()\n\tsimpleTextFieldMapping.Analyzer = simple_analyzer.Name\n\n\tenglishTextFieldMapping := bleve.NewTextFieldMapping()\n\tenglishTextFieldMapping.Analyzer = en.AnalyzerName\n\n\tkeywordFieldMapping := bleve.NewTextFieldMapping()\n\tkeywordFieldMapping.Analyzer = keyword_analyzer.Name\n\n\tstarMapping := bleve.NewDocumentMapping()\n\tstarMapping.AddFieldMappingsAt(\"Name\", simpleTextFieldMapping)\n\tstarMapping.AddFieldMappingsAt(\"FullName\", simpleTextFieldMapping)\n\tstarMapping.AddFieldMappingsAt(\"Description\", englishTextFieldMapping)\n\tstarMapping.AddFieldMappingsAt(\"Language\", keywordFieldMapping)\n\tstarMapping.AddFieldMappingsAt(\"Tags.Name\", keywordFieldMapping)\n\n\tindexMapping := bleve.NewIndexMapping()\n\tindexMapping.AddDocumentMapping(\"Star\", starMapping)\n\n\treturn indexMapping\n}"} {"input": "package specs\n\nimport (\n\t\"bytes\"\n\t\"reflect\"\n)\n\n\ntype APIVersion string\n\n\n\nfunc unmarshalJSONStrict(value []byte, into interface{}) error ", "output": "{\n\terr := newStrictYAMLOrJSONDecoder(bytes.NewReader(value), len(value)).Decode(into)\n\tif err != nil {\n\t\tv := reflect.ValueOf(into)\n\t\tv.Elem().Set(reflect.Zero(v.Elem().Type()))\n\t}\n\treturn err\n}"} {"input": "package geddit\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\ntype Submission struct {\n\tAuthor string `json:\"author\"`\n\tTitle string `json:\"title\"`\n\tURL string `json:\"url\"`\n\tDomain string `json:\"domain\"`\n\tSubreddit string `json:\"subreddit\"`\n\tSubredditID string `json:\"subreddit_id\"`\n\tFullID string `json:\"name\"`\n\tID string `json:\"id\"`\n\tPermalink string `json:\"permalink\"`\n\tSelftext string `json:\"selftext\"`\n\tThumbnailURL string `json:\"thumbnail\"`\n\tDateCreated float64 `json:\"created_utc\"`\n\tNumComments int `json:\"num_comments\"`\n\tScore int `json:\"score\"`\n\tUps int `json:\"ups\"`\n\tDowns int `json:\"downs\"`\n\tIsNSFW bool `json:\"over_18\"`\n\tIsSelf bool `json:\"is_self\"`\n\tWasClicked bool `json:\"clicked\"`\n\tIsSaved bool `json:\"saved\"`\n\tBannedBy *string `json:\"banned_by\"`\n}\n\n\nfunc (h Submission) deleteID() string { return h.FullID }\nfunc (h Submission) replyID() string { return h.FullID }\n\n\nfunc (h *Submission) FullPermalink() string {\n\treturn \"https://reddit.com\" + h.Permalink\n}\n\n\nfunc (h *Submission) String() string {\n\tplural := \"\"\n\tif h.NumComments != 1 {\n\t\tplural = \"s\"\n\t}\n\tcomments := fmt.Sprintf(\"%d comment%s\", h.NumComments, plural)\n\treturn fmt.Sprintf(\"%d - %s (%s)\", h.Score, h.Title, comments)\n}\n\nfunc (h Submission) voteID() string ", "output": "{ return h.FullID }"} {"input": "package mysql\n\nimport (\n\treplicationdatapb \"vitess.io/vitess/go/vt/proto/replicationdata\"\n)\n\n\ntype PrimaryStatus struct {\n\tPosition Position\n\tFilePosition Position\n}\n\n\n\n\nfunc PrimaryStatusToProto(s PrimaryStatus) *replicationdatapb.PrimaryStatus ", "output": "{\n\treturn &replicationdatapb.PrimaryStatus{\n\t\tPosition: EncodePosition(s.Position),\n\t\tFilePosition: EncodePosition(s.FilePosition),\n\t}\n}"} {"input": "package gauge\n\ntype ItemQueue struct {\n\tItems []Item\n}\n\n\n\nfunc (queue *ItemQueue) Peek() Item {\n\tif len(queue.Items) > 0 {\n\t\treturn queue.Items[0]\n\t}\n\treturn nil\n}\n\nfunc (queue *ItemQueue) Next() Item ", "output": "{\n\tif len(queue.Items) > 0 {\n\t\tnext := queue.Items[0]\n\t\tqueue.Items = queue.Items[1:]\n\t\treturn next\n\t}\n\treturn nil\n}"} {"input": "package httpcache\n\nimport \"log\"\n\nconst (\n\tansiRed = \"\\x1b[31;1m\"\n\tansiReset = \"\\x1b[0m\"\n)\n\nvar DebugLogging = false\n\nfunc debugf(format string, args ...interface{}) {\n\tif DebugLogging {\n\t\tlog.Printf(format, args...)\n\t}\n}\n\n\n\nfunc errorf(format string, args ...interface{}) ", "output": "{\n\tlog.Printf(ansiRed+\"✗ \"+format+ansiReset, args)\n}"} {"input": "package bech32\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n)\n\n\nfunc ExampleBech32Decode() {\n\tencoded := \"bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7k7grplx\"\n\thrp, decoded, err := Bech32Decode(encoded)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tfmt.Println(\"Decoded human-readable part:\", hrp)\n\tfmt.Println(\"Decoded Data:\", hex.EncodeToString(decoded))\n\n}\n\n\n\n\nfunc ExampleBech23Encode() ", "output": "{\n\tdata := []byte(\"Test data\")\n\tconv, err := ConvertBits(data, 8, 5, true)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\tencoded, err := Bech32Encode(\"customHrp!11111q\", conv)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tfmt.Println(\"Encoded Data:\", encoded)\n\n}"} {"input": "package main\n\nimport (\n\t\"time\"\n\n\t\"golang.org/x/text/language\"\n)\n\n\n\nconst (\n\tcashShift = 3\n\troundMask = 0x7\n\n\tnonTenderBit = 0x8000\n)\n\n\n\n\ntype currencyInfo byte\n\n\n\n\ntype roundingType struct {\n\tscale, increment uint8\n}\n\n\n\nvar roundings = [...]roundingType{\n\t{2, 1}, \n\t{0, 1},\n\t{1, 1},\n\t{3, 1},\n\t{4, 1},\n\t{2, 5}, \n\t{2, 50},\n}\n\n\n\nfunc regionToCode(r language.Region) uint16 {\n\tif s := r.String(); len(s) == 2 {\n\t\treturn uint16(s[0])<<8 | uint16(s[1])\n\t}\n\treturn 0\n}\n\n\n\nfunc fromDate(date uint32) time.Time {\n\treturn time.Date(int(date>>9), time.Month((date>>5)&0xf), int(date&0x1f), 0, 0, 0, 0, time.UTC)\n}\n\nfunc toDate(t time.Time) uint32 ", "output": "{\n\ty := t.Year()\n\tif y == 1 {\n\t\treturn 0\n\t}\n\tdate := uint32(y) << 4\n\tdate |= uint32(t.Month())\n\tdate <<= 5\n\tdate |= uint32(t.Day())\n\treturn date\n}"} {"input": "package mock\n\nimport (\n\t\"time\"\n)\n\ntype Clock struct {\n\tAdded []uint\n\tRemoved []chan time.Time\n\tEta float64\n}\n\nfunc NewClock() *Clock {\n\tm := &Clock{\n\t\tAdded: []uint{},\n\t\tRemoved: []chan time.Time{},\n\t}\n\treturn m\n}\n\n\n\nfunc (m *Clock) Remove(c chan time.Time) {\n\tm.Removed = append(m.Removed, c)\n}\n\nfunc (m *Clock) ETA(c chan time.Time) float64 {\n\treturn m.Eta\n}\n\nfunc (m *Clock) Add(c chan time.Time, t uint, sync bool) ", "output": "{\n\tm.Added = append(m.Added, t)\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype cvrTest struct {\n\turl string\n\tfail bool\n}\n\n\n\nfunc TestNewCvr(t *testing.T) ", "output": "{\n\tassert := assert.New(t)\n\n\ttests := []cvrTest{\n\t\t{\"httpurl.com\", true},\n\n\t\t{\"http:noturl/\", true},\n\n\t\t{\"url.com/\", true},\n\n\t\t{\"https:notsupported.com/\", true},\n\n\t\t{\"https:github.com/clearcontainers/tests\", false},\n\t}\n\n\tfor _, t := range tests {\n\t\tcvr, err := newCVR(t.url, \"\")\n\t\tif t.fail {\n\t\t\tassert.Error(err)\n\t\t\tassert.Nil(cvr)\n\t\t} else {\n\t\t\tassert.NoError(err)\n\t\t\tassert.NotNil(cvr)\n\t\t}\n\t}\n}"} {"input": "package collector\n\nimport (\n\t\"github.com/jcelliott/lumber\"\n\t\"github.com/nanobox-io/nanobox-logtap\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net\"\n\t\"net/http\"\n)\n\n\nfunc GenerateHttpCollector(kind string, l *logtap.Logtap) http.HandlerFunc {\n\theaderName := \"X-\" + kind + \"-Id\"\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tlogLevel := lumber.LvlInt(r.Header.Get(\"X-Log-Level\"))\n\t\theader := r.Header.Get(headerName)\n\t\tif header == \"\" {\n\t\t\theader = kind\n\t\t}\n\t\tl.Publish(header, logLevel, string(body))\n\t}\n}\n\n\n\nfunc StartHttpCollector(kind, address string, l *logtap.Logtap) (io.Closer, error) ", "output": "{\n\thttpListener, err := net.Listen(\"tcp\", address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgo http.Serve(httpListener, GenerateHttpCollector(kind, l))\n\treturn httpListener, nil\n}"} {"input": "package wca\n\nimport (\n\t\"unsafe\"\n)\n\n\n\n\ntype IAudioClient2 struct {\n\tIAudioClient\n}\n\ntype IAudioClient2Vtbl struct {\n\tIAudioClientVtbl\n\tIsOffloadCapable uintptr\n\tSetClientProperties uintptr\n\tGetBufferSizeLimits uintptr\n}\n\nfunc (v *IAudioClient2) VTable() *IAudioClient2Vtbl {\n\treturn (*IAudioClient2Vtbl)(unsafe.Pointer(v.RawVTable))\n}\n\nfunc (v *IAudioClient2) IsOffloadCapable(category uint32, isOffloadCapable *bool) (err error) {\n\terr = ac2IsOffloadCapable(v, category, isOffloadCapable)\n\treturn\n}\n\nfunc (v *IAudioClient2) SetClientProperties(properties *AudioClientProperties) (err error) {\n\terr = ac2SetClientProperties(v, properties)\n\treturn\n}\n\n\n\nfunc (v *IAudioClient2) GetBufferSizeLimits(wfx *WAVEFORMATEX, isEventDriven bool, minBufferDuration, maxBufferDuration *uint32) (err error) ", "output": "{\n\terr = ac2GetBufferSizeLimits(v, wfx, isEventDriven, minBufferDuration, maxBufferDuration)\n\treturn\n}"} {"input": "package gorm\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"github.com/jinzhu/gorm\"\n)\n\n\ntype GR struct {\n\tDB *gorm.DB\n\tServerInfo \n}\n\n\n\ntype ServerInfo struct {\n\thost string\n\tport uint16\n\tdbname string\n\tuser string\n\tpass string\n}\n\nvar dbInfo GR\n\n\nfunc New(host, dbname, user, pass string, port uint16) error {\n\n\tvar err error\n\tif dbInfo.DB == nil {\n\t\tdbInfo.host = host\n\t\tdbInfo.port = port\n\t\tdbInfo.dbname = dbname\n\t\tdbInfo.user = user\n\t\tdbInfo.pass = pass\n\n\t\tdbInfo.DB, err = dbInfo.Connection()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc GetDB() *GR {\n\tif dbInfo.DB == nil {\n\t\tpanic(errors.New(\"DB instance is nil\"))\n\t}\n\treturn &dbInfo\n}\n\nfunc (gr *GR) getDsn() string {\n\tparam := \"?charset=utf8&parseTime=True&loc=Local\"\n\treturn fmt.Sprintf(\"%s:%s@tcp(%s:%d)/%s%s\",\n\t\tgr.user, gr.pass, gr.host, gr.port, gr.dbname, param)\n}\n\n\n\n\n\n\nfunc (gr *GR) Close() {\n\tgr.DB.Close()\n}\n\nfunc (gr *GR) Connection() (*gorm.DB, error) ", "output": "{\n\treturn gorm.Open(\"mysql\", gr.getDsn())\n}"} {"input": "package iptables\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n\n\t\"github.com/projectcalico/libcalico-go/lib/testutils\"\n)\n\nfunc init() {\n\ttestutils.HookLogrusForGinkgo()\n}\n\n\n\nfunc TestIptablesUT(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Iptables Suite\")\n}"} {"input": "package css\n\ntype Id string\n\nfunc (id Id) Selector() string {\n\treturn \"#\" + string(id)\n}\n\nfunc (id Id) WithPseudoClass(pseudoClass PseudoClass) SelectorWithPseudoClass {\n\treturn SelectorWithPseudoClass{Element: id, PseudoClass: pseudoClass}\n}\n\n\n\nfunc (id Id) Style(properties ...Property) RuleSet ", "output": "{\n\treturn For(id).Set(properties...)\n}"} {"input": "package httpretry\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype dialer struct {\n\tTimeout time.Duration\n\tKeepAlive time.Duration\n\tInactivity time.Duration\n}\n\nfunc (d *dialer) Dial(netw, addr string) (net.Conn, error) {\n\tc, err := net.DialTimeout(netw, addr, d.Timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif tc, ok := c.(*net.TCPConn); ok {\n\t\ttc.SetKeepAlive(true)\n\t\ttc.SetKeepAlivePeriod(d.KeepAlive)\n\t}\n\treturn &deadlineConn{d.Inactivity, c}, nil\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc DialWithTimeout(timeout time.Duration) func(netw, addr string) (net.Conn, error) {\n\treturn NewDialer(timeout).Dial\n}\n\n\n\nfunc NewDialer(timeout time.Duration) *dialer {\n\treturn &dialer{Timeout: timeout, KeepAlive: timeout, Inactivity: timeout}\n}\n\ntype deadlineConn struct {\n\tTimeout time.Duration\n\tnet.Conn\n}\n\nfunc (c *deadlineConn) Read(b []byte) (int, error) {\n\tif err := c.Conn.SetDeadline(time.Now().Add(c.Timeout)); err != nil {\n\t\treturn 0, err\n\t}\n\treturn c.Conn.Read(b)\n}\n\nfunc (c *deadlineConn) Write(b []byte) (int, error) {\n\tif err := c.Conn.SetDeadline(time.Now().Add(c.Timeout)); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.Conn.Write(b)\n}\n\nfunc ClientWithTimeout(timeout time.Duration) *http.Client ", "output": "{\n\tdialer := NewDialer(timeout)\n\ttransport := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: dialer.Dial,\n\t\tResponseHeaderTimeout: dialer.Inactivity,\n\t\tMaxIdleConnsPerHost: 10,\n\t}\n\treturn &http.Client{Transport: transport}\n}"} {"input": "package app\n\nimport (\n\t\"github.com/mattermost/platform/model\"\n\t\"github.com/mattermost/platform/utils\"\n)\n\ntype AutoChannelCreator struct {\n\tclient *model.Client\n\tteam *model.Team\n\tFuzzy bool\n\tDisplayNameLen utils.Range\n\tDisplayNameCharset string\n\tNameLen utils.Range\n\tNameCharset string\n\tChannelType string\n}\n\nfunc NewAutoChannelCreator(client *model.Client, team *model.Team) *AutoChannelCreator {\n\treturn &AutoChannelCreator{\n\t\tclient: client,\n\t\tteam: team,\n\t\tFuzzy: false,\n\t\tDisplayNameLen: CHANNEL_DISPLAY_NAME_LEN,\n\t\tDisplayNameCharset: utils.ALPHANUMERIC,\n\t\tNameLen: CHANNEL_NAME_LEN,\n\t\tNameCharset: utils.LOWERCASE,\n\t\tChannelType: CHANNEL_TYPE,\n\t}\n}\n\n\n\nfunc (cfg *AutoChannelCreator) CreateTestChannels(num utils.Range) ([]*model.Channel, bool) {\n\tnumChannels := utils.RandIntFromRange(num)\n\tchannels := make([]*model.Channel, numChannels)\n\n\tfor i := 0; i < numChannels; i++ {\n\t\tvar err bool\n\t\tchannels[i], err = cfg.createRandomChannel()\n\t\tif err != true {\n\t\t\treturn channels, false\n\t\t}\n\t}\n\n\treturn channels, true\n}\n\nfunc (cfg *AutoChannelCreator) createRandomChannel() (*model.Channel, bool) ", "output": "{\n\tvar displayName string\n\tif cfg.Fuzzy {\n\t\tdisplayName = utils.FuzzName()\n\t} else {\n\t\tdisplayName = utils.RandomName(cfg.NameLen, cfg.NameCharset)\n\t}\n\tname := utils.RandomName(cfg.NameLen, cfg.NameCharset)\n\n\tchannel := &model.Channel{\n\t\tTeamId: cfg.team.Id,\n\t\tDisplayName: displayName,\n\t\tName: name,\n\t\tType: cfg.ChannelType}\n\n\tprintln(cfg.client.GetTeamRoute())\n\tresult, err := cfg.client.CreateChannel(channel)\n\tif err != nil {\n\t\terr.Translate(utils.T)\n\t\tprintln(err.Error())\n\t\tprintln(err.DetailedError)\n\t\treturn nil, false\n\t}\n\treturn result.Data.(*model.Channel), true\n}"} {"input": "package common\n\nimport (\n\t\"bytes\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n)\n\n\ntype Endpoint struct {\n\tHost string `json:\"host\"`\n\n\tPorts []ServicePort `json:\"ports\"`\n}\n\n\nfunc GetExternalEndpoints(service *api.Service) []Endpoint {\n\tvar externalEndpoints []Endpoint\n\tif service.Spec.Type == api.ServiceTypeLoadBalancer {\n\t\tfor _, ingress := range service.Status.LoadBalancer.Ingress {\n\t\t\texternalEndpoints = append(externalEndpoints, getExternalEndpoint(ingress, service.Spec.Ports))\n\t\t}\n\t}\n\n\tfor _, ip := range service.Spec.ExternalIPs {\n\t\texternalEndpoints = append(externalEndpoints, Endpoint{\n\t\t\tHost: ip,\n\t\t\tPorts: GetServicePorts(service.Spec.Ports),\n\t\t})\n\t}\n\n\treturn externalEndpoints\n}\n\n\n\nfunc GetInternalEndpoint(serviceName, namespace string, ports []api.ServicePort) Endpoint {\n\tname := serviceName\n\n\tif namespace != api.NamespaceDefault && len(namespace) > 0 && len(serviceName) > 0 {\n\t\tbufferName := bytes.NewBufferString(name)\n\t\tbufferName.WriteString(\".\")\n\t\tbufferName.WriteString(namespace)\n\t\tname = bufferName.String()\n\t}\n\n\treturn Endpoint{\n\t\tHost: name,\n\t\tPorts: GetServicePorts(ports),\n\t}\n}\n\n\n\n\n\nfunc GetNodeByName(nodes []api.Node, nodeName string) *api.Node {\n\tfor _, node := range nodes {\n\t\tif node.ObjectMeta.Name == nodeName {\n\t\t\treturn &node\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc getExternalEndpoint(ingress api.LoadBalancerIngress, ports []api.ServicePort) Endpoint ", "output": "{\n\tvar host string\n\tif ingress.Hostname != \"\" {\n\t\thost = ingress.Hostname\n\t} else {\n\t\thost = ingress.IP\n\t}\n\treturn Endpoint{\n\t\tHost: host,\n\t\tPorts: GetServicePorts(ports),\n\t}\n}"} {"input": "package sample\n\n\nimport (\n\t\"time\"\n\t\"encoding/json\"\n)\n\ntype Datum struct {\n\tStatus string `json:\"status\"`\n\tTimestamp time.Time `json:\"timestamp\"`\n}\n\ntype Sample struct {\n\tKey string `json:\"key\"`\n\tTyp string `json:\"type\"`\n\tData Datum `json:\"data\"`\n}\n\nfunc Init() Sample {\n\tsample := Sample{\"sample\",\"testing\", Datum{\"ok\", time.Now()}}\n\treturn sample\n}\n\nfunc (m *Sample) Json() string {\n\tresult, _ := json.Marshal(m)\n\treturn string(result)\n}\n\n\n\nfunc ConvertStatus(value int) string", "output": "{\n\tswitch value {\n\tcase 1:\n\t\treturn \"ok\"\n\tdefault:\n\t\treturn \"error\"\n\n\t}\n}"} {"input": "package engine\n\nimport (\n\t\"time\"\n\n\t\"github.com/aws/amazon-ecs-agent/agent/api\"\n)\n\n\n\ntype impossibleTransitionError struct {\n\tstate api.ContainerStatus\n}\n\nfunc (err *impossibleTransitionError) Error() string {\n\treturn \"Cannot transition to \" + err.state.String()\n}\nfunc (err *impossibleTransitionError) ErrorName() string { return \"ImpossibleStateTransitionError\" }\n\ntype DockerTimeoutError struct {\n\tduration time.Duration\n\ttransition string\n}\n\nfunc (err *DockerTimeoutError) Error() string {\n\treturn \"Could not transition to \" + err.transition + \"; timed out after waiting \" + err.duration.String()\n}\nfunc (err *DockerTimeoutError) ErrorName() string { return \"DockerTimeoutError\" }\n\ntype ContainerVanishedError struct{}\n\nfunc (err ContainerVanishedError) Error() string { return \"No container matching saved ID found\" }\n\n\ntype CannotXContainerError struct {\n\ttransition string\n\tmsg string\n}\n\nfunc (err CannotXContainerError) Error() string { return err.msg }\nfunc (err CannotXContainerError) ErrorName() string {\n\treturn \"Cannot\" + err.transition + \"ContainerError\"\n}\n\ntype OutOfMemoryError struct{}\n\nfunc (err OutOfMemoryError) Error() string { return \"Container killed due to memory usage\" }\nfunc (err OutOfMemoryError) ErrorName() string { return \"OutOfMemoryError\" }\n\n\ntype DockerStateError struct {\n\tdockerError string\n\tname string\n}\n\nfunc NewDockerStateError(err string) DockerStateError {\n\treturn DockerStateError{\n\t\tdockerError: err,\n\t\tname: \"DockerStateError\",\n\t}\n}\n\nfunc (err DockerStateError) Error() string {\n\treturn err.dockerError\n}\nfunc (err DockerStateError) ErrorName() string {\n\treturn err.name\n}\n\nfunc (err ContainerVanishedError) ErrorName() string ", "output": "{ return \"ContainerVanishedError\" }"} {"input": "package displayers\n\nimport (\n\t\"io\"\n\t\"strings\"\n\n\t\"github.com/digitalocean/doctl/do\"\n)\n\ntype Certificate struct {\n\tCertificates do.Certificates\n}\n\nvar _ Displayable = &Certificate{}\n\nfunc (c *Certificate) JSON(out io.Writer) error {\n\treturn writeJSON(c.Certificates, out)\n}\n\n\n\nfunc (c *Certificate) ColMap() map[string]string {\n\treturn map[string]string{\n\t\t\"ID\": \"ID\",\n\t\t\"Name\": \"Name\",\n\t\t\"DNSNames\": \"DNS Names\",\n\t\t\"SHA1Fingerprint\": \"SHA-1 Fingerprint\",\n\t\t\"NotAfter\": \"Expiration Date\",\n\t\t\"Created\": \"Created At\",\n\t\t\"Type\": \"Type\",\n\t\t\"State\": \"State\",\n\t}\n}\n\nfunc (c *Certificate) KV() []map[string]interface{} {\n\tout := []map[string]interface{}{}\n\n\tfor _, c := range c.Certificates {\n\t\to := map[string]interface{}{\n\t\t\t\"ID\": c.ID,\n\t\t\t\"Name\": c.Name,\n\t\t\t\"DNSNames\": strings.Join(c.DNSNames, \",\"),\n\t\t\t\"SHA1Fingerprint\": c.SHA1Fingerprint,\n\t\t\t\"NotAfter\": c.NotAfter,\n\t\t\t\"Created\": c.Created,\n\t\t\t\"Type\": c.Type,\n\t\t\t\"State\": c.State,\n\t\t}\n\t\tout = append(out, o)\n\t}\n\n\treturn out\n}\n\nfunc (c *Certificate) Cols() []string ", "output": "{\n\treturn []string{\n\t\t\"ID\",\n\t\t\"Name\",\n\t\t\"DNSNames\",\n\t\t\"SHA1Fingerprint\",\n\t\t\"NotAfter\",\n\t\t\"Created\",\n\t\t\"Type\",\n\t\t\"State\",\n\t}\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\n\tv1beta1 \"kubevirt.io/client-go/generated/containerized-data-importer/clientset/versioned/typed/core/v1beta1\"\n)\n\ntype FakeCdiV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeCdiV1beta1) CDIs() v1beta1.CDIInterface {\n\treturn &FakeCDIs{c}\n}\n\nfunc (c *FakeCdiV1beta1) CDIConfigs() v1beta1.CDIConfigInterface {\n\treturn &FakeCDIConfigs{c}\n}\n\nfunc (c *FakeCdiV1beta1) DataImportCrons(namespace string) v1beta1.DataImportCronInterface {\n\treturn &FakeDataImportCrons{c, namespace}\n}\n\nfunc (c *FakeCdiV1beta1) DataSources(namespace string) v1beta1.DataSourceInterface {\n\treturn &FakeDataSources{c, namespace}\n}\n\nfunc (c *FakeCdiV1beta1) DataVolumes(namespace string) v1beta1.DataVolumeInterface {\n\treturn &FakeDataVolumes{c, namespace}\n}\n\nfunc (c *FakeCdiV1beta1) ObjectTransfers() v1beta1.ObjectTransferInterface {\n\treturn &FakeObjectTransfers{c}\n}\n\n\n\n\n\nfunc (c *FakeCdiV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeCdiV1beta1) StorageProfiles() v1beta1.StorageProfileInterface ", "output": "{\n\treturn &FakeStorageProfiles{c}\n}"} {"input": "package session\n\nimport (\n\t\"g_server/framework/gnet\"\n)\n\nconst (\n\tsessionEventOpen = 1\n\tsessionEventClose = 2\n\tsessionEventMsg = 3\n)\n\n\n\nfunc NewWsSessionClient(name string, curl string, rcontime int32, maxsession uint32) *SessionClient {\n\treturn &SessionClient{BaseSession: BaseSession{ws: gnet.NewWebSocketClient(curl, maxsession)}, SessionMsgProxy: SessionMsgProxy{msghanders: make(map[uint32]*msgProxy)}, rcontime: rcontime, name: name}\n}\n\nfunc NewWsSessionManager(name string, host string, maxmsgsize uint32, maxsession uint32, hook func(gnet.ISocket, []byte) bool) *SessionManager ", "output": "{\n\treturn &SessionManager{server: gnet.NewWebSocketServer(host, maxmsgsize), SessionMsgProxy: SessionMsgProxy{msghanders: make(map[uint32]*msgProxy)}, maxsession: maxsession, name: name, hook: hook}\n}"} {"input": "package ast\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/suite\"\n)\n\ntype StructTypeSpecTestSuite struct {\n\tsuite.Suite\n}\n\nfunc TestStructTypeSpecTestSuite(t *testing.T) {\n\tsuite.Run(t, new(StructTypeSpecTestSuite))\n}\n\n\n\nfunc (s *StructTypeSpecTestSuite) TestName() ", "output": "{\n\tspec, err := FindJSONStructFor(\"github.com/marcel/jitjson/fixtures/media\", \"Album\")\n\ts.Nil(err)\n\n\ts.Equal(\"Album\", spec.Name())\n}"} {"input": "package stores\n\nimport (\n\t\"HTVM/instructions/base\"\n\t\"HTVM/runtime\"\n)\n\n\ntype ASTORE struct {\n\tbase.Index8Instruction\n}\n\nfunc (self *ASTORE) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, self.Index)\n}\n\ntype ASTORE_0 struct {\n\tbase.NoOperandsInstruction\n}\n\n\n\ntype ASTORE_1 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_1) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 1)\n}\n\ntype ASTORE_2 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_2) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 2)\n}\n\ntype ASTORE_3 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_3) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 3)\n}\n\ntype ASTORE_4 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_4) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 4)\n}\n\nfunc _executeRef(frame *runtime.Frame, index uint) {\n\tval := frame.OperateStack().PopRef()\n\tframe.LocalVars().SetRef(index, val)\n}\n\nfunc (self *ASTORE_0) Execute(frame *runtime.Frame) ", "output": "{\n\t_executeRef(frame, 0)\n}"} {"input": "package toogo\n\n\ntype Event_close_thread struct {\n\tEvt_base\n\tMaster IThread\n}\n\n\n\n\nfunc (this *Event_close_thread) Exec(home interface{}) bool ", "output": "{\n\tif this.Master != nil {\n\t\tthis.Master.pre_close_thread()\n\t\treturn true\n\t}\n\n\tprintln(\"没找到线程\")\n\treturn true\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\tvar picked []int\n\tarr := []int{1, 3, 5, 7}\n\tCombination(picked, arr, 4)\n}\n\nfunc Combination(picked []int, arr []int, toPick int) ", "output": "{\n\tif 0 == toPick {\n\t\tfmt.Println(picked)\n\t} else {\n\t\tfor _, el := range arr {\n\t\t\tpicked = append(picked, el)\n\t\t\tCombination(picked, arr, toPick-1)\n\t\t\tpicked = picked[:len(picked)-1]\n\t\t}\n\t}\n}"} {"input": "package memory\n\nimport (\n\t\"testing\"\n\n\tmbtest \"github.com/elastic/beats/metricbeat/mb/testing\"\n)\n\nfunc TestData(t *testing.T) {\n\tf := mbtest.NewEventFetcher(t, getConfig())\n\n\terr := mbtest.WriteEvent(f, t)\n\tif err != nil {\n\t\tt.Fatal(\"write\", err)\n\t}\n}\n\n\n\nfunc getConfig() map[string]interface{} ", "output": "{\n\treturn map[string]interface{}{\n\t\t\"module\": \"system\",\n\t\t\"metricsets\": []string{\"memory\"},\n\t}\n}"} {"input": "package flags\n\n\n\n\n\n\n\nimport (\n\t\"strings\"\n\n\t\"github.com/BytemarkHosting/bytemark-client/cmd/bytemark/app\"\n)\n\n\n\n\ntype AccountNameSliceFlag []AccountNameFlag\n\n\nfunc (sf *AccountNameSliceFlag) Preprocess(ctx *app.Context) error {\n\tfor i := range *sf {\n\t\terr := (*sf)[i].Preprocess(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (sf *AccountNameSliceFlag) Set(value string) error {\n\tflag := AccountNameFlag{}\n\terr := flag.Set(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*sf = append(*sf, flag)\n\treturn nil\n}\n\n\n\n\n\n\nfunc AccountNameSlice(ctx *app.Context, name string) AccountNameSliceFlag {\n\tif sf, ok := ctx.Context.Generic(name).(*AccountNameSliceFlag); ok {\n\t\treturn *sf\n\t}\n\treturn AccountNameSliceFlag{}\n}\n\nfunc (sf AccountNameSliceFlag) String() string ", "output": "{\n\tstrs := make([]string, len(sf))\n\tfor i, value := range sf {\n\t\tstrs[i] = value.String()\n\t}\n\treturn strings.Join(strs, \", \")\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/godbus/dbus\"\n\t\"github.com/godbus/dbus/introspect\"\n\t\"os\"\n)\n\nconst intro = `\n\n\t\n\t\t\n\t\t\t\n\t\t\n\t` + introspect.IntrospectDataString + ` `\n\ntype foo string\n\n\n\nfunc main() {\n\tconn, err := dbus.SessionBus()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treply, err := conn.RequestName(\"com.github.guelfey.Demo\",\n\t\tdbus.NameFlagDoNotQueue)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif reply != dbus.RequestNameReplyPrimaryOwner {\n\t\tfmt.Fprintln(os.Stderr, \"name already taken\")\n\t\tos.Exit(1)\n\t}\n\tf := foo(\"Bar!\")\n\tconn.Export(f, \"/com/github/guelfey/Demo\", \"com.github.guelfey.Demo\")\n\tconn.Export(introspect.Introspectable(intro), \"/com/github/guelfey/Demo\",\n\t\t\"org.freedesktop.DBus.Introspectable\")\n\tfmt.Println(\"Listening on com.github.guelfey.Demo / /com/github/guelfey/Demo ...\")\n\tselect {}\n}\n\nfunc (f foo) Foo() (string, *dbus.Error) ", "output": "{\n\tfmt.Println(f)\n\treturn string(f), nil\n}"} {"input": "package connect\n\nimport \"io\"\nimport \"github.com/LilyPad/GoLilyPad/packet\"\n\ntype RequestAuthenticate struct {\n\tUsername string\n\tPassword string\n}\n\nfunc NewRequestAuthenticate(username string, password string) (this *RequestAuthenticate) {\n\tthis = new(RequestAuthenticate)\n\tthis.Username = username\n\tthis.Password = password\n\treturn\n}\n\nfunc (this *RequestAuthenticate) Id() int {\n\treturn REQUEST_AUTHENTICATE\n}\n\ntype requestAuthenticateCodec struct {\n\n}\n\nfunc (this *requestAuthenticateCodec) Decode(reader io.Reader) (request Request, err error) {\n\trequestAuthenticate := new(RequestAuthenticate)\n\trequestAuthenticate.Username, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\trequestAuthenticate.Password, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\trequest = requestAuthenticate\n\treturn\n}\n\nfunc (this *requestAuthenticateCodec) Encode(writer io.Writer, request Request) (err error) {\n\trequestAuthenticate := request.(*RequestAuthenticate)\n\terr = packet.WriteString(writer, requestAuthenticate.Username)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = packet.WriteString(writer, requestAuthenticate.Password)\n\treturn\n}\n\ntype ResultAuthenticate struct {\n\n}\n\nfunc NewResultAuthenticate() (this *ResultAuthenticate) {\n\tthis = new(ResultAuthenticate)\n\treturn\n}\n\n\n\ntype resultAuthenticateCodec struct {\n\n}\n\nfunc (this *resultAuthenticateCodec) Decode(reader io.Reader) (result Result, err error) {\n\tresult = new(ResultAuthenticate)\n\treturn\n}\n\nfunc (this *resultAuthenticateCodec) Encode(writer io.Writer, result Result) (err error) {\n\treturn\n}\n\nfunc (this *ResultAuthenticate) Id() int ", "output": "{\n\treturn REQUEST_AUTHENTICATE\n}"} {"input": "package factory\n\nimport (\n\tcontext \"context\"\n\n\texternalversions \"knative.dev/eventing-kafka-broker/control-plane/pkg/client/informers/externalversions\"\n\tclient \"knative.dev/eventing-kafka-broker/control-plane/pkg/client/injection/client\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Default.RegisterInformerFactory(withInformerFactory)\n}\n\n\ntype Key struct{}\n\nfunc withInformerFactory(ctx context.Context) context.Context {\n\tc := client.Get(ctx)\n\topts := make([]externalversions.SharedInformerOption, 0, 1)\n\tif injection.HasNamespaceScope(ctx) {\n\t\topts = append(opts, externalversions.WithNamespace(injection.GetNamespaceScope(ctx)))\n\t}\n\treturn context.WithValue(ctx, Key{},\n\t\texternalversions.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...))\n}\n\n\n\n\nfunc Get(ctx context.Context) externalversions.SharedInformerFactory ", "output": "{\n\tuntyped := ctx.Value(Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch knative.dev/eventing-kafka-broker/control-plane/pkg/client/informers/externalversions.SharedInformerFactory from context.\")\n\t}\n\treturn untyped.(externalversions.SharedInformerFactory)\n}"} {"input": "package go_koans\n\n\n\nfunc findPrimeNumbers(channel chan int) {\n\tfor i := 2; ; i++ {\n\n\t\tassert(i < 100) \n\t}\n}\n\nfunc aboutConcurrency() {\n\tch := make(chan int)\n\n\tassert(__delete_me__) \n\n\tassert(<-ch == 2)\n\tassert(<-ch == 3)\n\tassert(<-ch == 5)\n\tassert(<-ch == 7)\n\tassert(<-ch == 11)\n}\n\nfunc isPrimeNumber(possiblePrime int) bool ", "output": "{\n\tfor underPrime := 2; underPrime < possiblePrime; underPrime++ {\n\t\tif possiblePrime%underPrime == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package options\n\nimport (\n\t\"strings\"\n\n\t\"github.com/pkg/errors\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/pflag\"\n)\n\ntype ClusterEditConfig struct {\n\tClusterName string\n\tFile string\n\tKubernetesVersion string\n\tLocked bool\n\tOutput string\n}\n\nfunc NewClusterEditConfig() *ClusterEditConfig {\n\treturn &ClusterEditConfig{\n\t\tClusterName: \"\",\n\t\tFile: \"\",\n\t\tKubernetesVersion: \"\",\n\t\tLocked: false,\n\t\tOutput: \"yaml\",\n\t}\n}\n\n\n\nfunc (c *ClusterEditConfig) ValidateFlags(cmd *cobra.Command, args []string) error {\n\tif cmd.Flags().Changed(\"file\") {\n\t\tif len(args) != 0 {\n\t\t\treturn errors.New(\"no argument can be provided when --file flag is used\")\n\t\t}\n\t}\n\tif len(args) == 0 {\n\t\treturn errors.New(\"missing cluster name\")\n\t}\n\tif len(args) > 1 {\n\t\treturn errors.New(\"multiple cluster name provided\")\n\t}\n\tc.ClusterName = strings.ToLower(args[0])\n\treturn nil\n}\n\nfunc (c *ClusterEditConfig) CheckForUpdateFlags() bool {\n\tif c.Locked || c.KubernetesVersion != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (c *ClusterEditConfig) AddFlags(fs *pflag.FlagSet) ", "output": "{\n\tfs.StringVarP(&c.File, \"file\", \"f\", c.File, \"Load cluster data from file\")\n\tfs.StringVar(&c.KubernetesVersion, \"kubernetes-version\", c.KubernetesVersion, \"Kubernetes version\")\n\tfs.BoolVar(&c.Locked, \"locked\", c.Locked, \"If true, locks cluster from deletion\")\n\tfs.StringVarP(&c.Output, \"output\", \"o\", c.Output, \"Output format. One of: yaml|json.\")\n\n}"} {"input": "package database\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/base64\"\n\n\t\"github.com/garyburd/redigo/redis\"\n\n\t\"bosun.org/slog\"\n)\n\ntype ConfigDataAccess interface {\n\tSaveTempConfig(text string) (hash string, err error)\n\tGetTempConfig(hash string) (text string, err error)\n}\n\n\n\nconst configLifetime = 60 * 24 * 14 \n\nfunc (d *dataAccess) SaveTempConfig(text string) (string, error) {\n\tconn := d.Get()\n\tdefer conn.Close()\n\n\tsig := md5.Sum([]byte(text))\n\tb64 := base64.StdEncoding.EncodeToString(sig[0:8])\n\tif d.isRedis {\n\t\t_, err := conn.Do(\"SET\", \"tempConfig:\"+b64, text, \"EX\", configLifetime)\n\t\treturn b64, slog.Wrap(err)\n\t}\n\t_, err := conn.Do(\"SETEX\", \"tempConfig:\"+b64, configLifetime, text)\n\treturn b64, slog.Wrap(err)\n}\n\nfunc (d *dataAccess) GetTempConfig(hash string) (string, error) {\n\tconn := d.Get()\n\tdefer conn.Close()\n\n\tkey := \"tempConfig:\" + hash\n\tdat, err := redis.String(conn.Do(\"GET\", key))\n\tif err != nil {\n\t\treturn \"\", slog.Wrap(err)\n\t}\n\t_, err = conn.Do(\"EXPIRE\", key, configLifetime)\n\treturn dat, slog.Wrap(err)\n}\n\nfunc (d *dataAccess) Configs() ConfigDataAccess ", "output": "{\n\treturn d\n}"} {"input": "package messages\n\nimport (\n\t\"bytes\"\n\t\"message-delivery-system/src/utils\"\n)\n\n\ntype ListResponse struct {\n\tList []uint64\n\tReceiver uint64\n}\n\n\nfunc NewListResponse(data []byte) ListResponse {\n\tbuf := bytes.NewReader(data)\n\tlist, _ := utils.ByteArrayToUint64List(buf, data)\n\treturn ListResponse{List:list}\n}\n\n\nfunc (l ListResponse) GetMessageType() MessageType {\n\treturn ListResponseMessage\n}\n\n\n\n\n\nfunc (l ListResponse) GetReceiverIds() []uint64 {\n\tvar receivers []uint64\n\treturn append(receivers, l.Receiver)\n}\n\nfunc (l ListResponse) GetData() []byte ", "output": "{\n\tbuf := new(bytes.Buffer)\n\tdata, _ := utils.Uint64ListToByteArray(buf, l.List)\n\treturn data\n}"} {"input": "package config\n\nimport (\n\t\"github.com/mitchellh/go-homedir\"\n\t\"os\"\n)\n\nconst DB_FILE = \"davedb.db\"\n\n\n\nfunc DbPath() string {\n\thomeDir, _ := homedir.Dir()\n\treturn homeDir + string(os.PathSeparator) + DB_FILE\n}\n\nfunc TimeFormat() string ", "output": "{\n\treturn \"Monday, 2 Jan 2006\"\n}"} {"input": "package singular\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n)\n\n\n\n\n\nfunc PassOrFatal(msg string, err error) {\n\tif err != nil {\n\t\tlog.Fatalf(\"%s: %v\", msg, err)\n\t}\n}\n\nfunc CheckError(msg string, err error) ", "output": "{\n\tif err != nil {\n\t\tlog.Errorf(\"%s: %v\", msg, err)\n\t}\n}"} {"input": "package e2e\n\nimport (\n\t\"testing\"\n\n\t\"knative.dev/eventing-kafka/test/e2e/helpers\"\n)\n\n\n\nfunc TestKafkaSourceUpdate(t *testing.T) {\n\thelpers.TestKafkaSourceUpdate(t)\n}\n\nfunc TestKafkaSource(t *testing.T) ", "output": "{\n\thelpers.AssureKafkaSourceIsOperational(t, func(auth, testCase, version string) bool { return true })\n}"} {"input": "package longrunning_test\n\nimport (\n\t\"cloud.google.com/go/longrunning/autogen\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/api/iterator\"\n\tlongrunningpb \"google.golang.org/genproto/googleapis/longrunning\"\n)\n\nfunc ExampleNewOperationsClient() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\nfunc ExampleOperationsClient_GetOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.GetOperationRequest{\n\t}\n\tresp, err := c.GetOperation(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\n\n\nfunc ExampleOperationsClient_CancelOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.CancelOperationRequest{\n\t}\n\terr = c.CancelOperation(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleOperationsClient_DeleteOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.DeleteOperationRequest{\n\t}\n\terr = c.DeleteOperation(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleOperationsClient_ListOperations() ", "output": "{\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.ListOperationsRequest{\n\t}\n\tit := c.ListOperations(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}"} {"input": "package mongo\n\nimport (\n\t\"github.com/peteraba/d5/lib/util\"\n\t\"gopkg.in/mgo.v2\"\n)\n\nvar (\n\tsession *mgo.Session\n\tdb *mgo.Database\n)\n\nfunc SetMgoSession(mgoSession *mgo.Session) {\n\tsession = mgoSession\n}\n\nfunc SetMgoDb(mgoDatabase *mgo.Database) {\n\tdb = mgoDatabase\n}\n\nfunc CreateMgoDbFromEnvs() *mgo.Database {\n\tdbHost, dbName := ParseDbEnvs()\n\n\tmgoDb, err := CreateMgoDb(dbHost, dbName)\n\n\tif err != nil {\n\t\tutil.LogFatalfMsg(err, \"MongoDB database could not be created: %v\", true)\n\t}\n\n\treturn mgoDb\n}\n\n\n\nfunc getMgoSession(dbHost string) (*mgo.Session, error) {\n\tvar (\n\t\terr error\n\t)\n\n\tif session != nil {\n\t\treturn session, nil\n\t}\n\n\tsession, err = mgo.Dial(dbHost)\n\n\treturn session, err\n}\n\nfunc getMgoDb(mgoSession *mgo.Session, dbName string) *mgo.Database {\n\tif db != nil {\n\t\treturn db\n\t}\n\n\tmgoSession = mgoSession.Clone()\n\n\tdb = mgoSession.DB(dbName)\n\n\treturn db\n}\n\nfunc CreateMgoDb(dbHost, dbName string) (*mgo.Database, error) ", "output": "{\n\tsession, err := getMgoSession(dbHost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn getMgoDb(session, dbName), nil\n}"} {"input": "package clients\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n\n\t\"github.com/VolantMQ/volantmq/subscriber\"\n)\n\nvar subCount int32 = 0\n\n\n\ntype container struct {\n\tlock sync.Mutex\n\trmLock sync.RWMutex\n\tses *session\n\texpiry atomic.Value\n\tsub *subscriber.Type\n\tremovable bool\n\tremoved bool\n}\n\nfunc (s *container) setRemovable(rm bool) {\n\ts.rmLock.Lock()\n\ts.removable = rm\n\ts.rmLock.Unlock()\n}\n\nfunc (s *container) acquire() {\n\ts.lock.Lock()\n}\n\nfunc (s *container) release() {\n\ts.lock.Unlock()\n}\n\nfunc (s *container) session() *session {\n\tdefer s.rmLock.Unlock()\n\ts.rmLock.Lock()\n\treturn s.ses\n}\n\n\n\nfunc (s *container) subscriber(cleanStart bool, c subscriber.Config) *subscriber.Type {\n\tif cleanStart && s.sub != nil {\n\t\ts.sub.Offline(true)\n\t\ts.sub = nil\n\t}\n\n\tif s.sub == nil {\n\t\ts.sub = subscriber.New(c)\n\t}\n\n\treturn s.sub\n}\n\nfunc (s *container) swap(from *container) *container ", "output": "{\n\ts.ses = from.ses\n\n\ts.ses.idLock = &s.lock\n\n\treturn s\n}"} {"input": "package actor\n\nimport (\n\t\"testing\"\n)\n\nfunc TestActorCanReplyOnStarting(t *testing.T) {\n\tfuture := NewFuture(testTimeout)\n\ta := Spawn(FromFunc(func(context Context) {\n\t\tswitch context.Message().(type) {\n\t\tcase *Started:\n\t\t\tcontext.Tell(future.PID(), EchoResponse{})\n\t\t}\n\t}))\n\ta.GracefulStop()\n\tassertFutureSuccess(future, t)\n}\n\n\n\nfunc TestActorCanReplyOnStopping(t *testing.T) ", "output": "{\n\tfuture := NewFuture(testTimeout)\n\ta := Spawn(FromFunc(func(context Context) {\n\t\tswitch context.Message().(type) {\n\t\tcase *Stopping:\n\t\t\tcontext.Tell(future.PID(), EchoResponse{})\n\t\t}\n\t}))\n\ta.GracefulStop()\n\tassertFutureSuccess(future, t)\n}"} {"input": "package cbo\n\ntype Net struct {\n\tEndpoints EndpointSet\n\n\tonReplace []func(new *Net)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (n *Net) SuggestedName() string {\n\tif len(n.Endpoints) == 0 {\n\t\treturn \"\"\n\t}\n\n\tnameOccurs := map[string]int{}\n\tfor e := range n.Endpoints {\n\t\tnameOccurs[e.Name]++\n\t}\n\n\tfor _, n := range priorityNetNames {\n\t\tif nameOccurs[n] > 0 {\n\t\t\treturn n\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\n\n\n\n\n\n\n\n\nfunc (n *Net) OnReplace(cb func(new *Net)) {\n\tn.onReplace = append(n.onReplace, cb)\n}\n\nvar priorityNetNames = []string{\n\t\"GND\",\n\t\"AGND\",\n\t\"PGND\",\n\n\t\"+3V3\",\n\t\"-3V3\",\n\t\"+1V8\",\n\t\"-1V8\",\n\t\"+5V\",\n\t\"-5V\",\n\t\"+12V\",\n\t\"-12V\",\n\t\"+9V\",\n\t\"-9V\",\n\t\"+6V\",\n\t\"-6V\",\n\t\"+24V\",\n\t\"-24V\",\n\n\t\"V+\",\n\t\"VCC\",\n\t\"VDD\",\n\t\"V-\",\n\t\"VSS\",\n\t\"VEE\",\n\n\t\"MOSI\",\n\t\"MISO\",\n\t\"SCLK\",\n\t\"SCK\",\n\t\"SDA\",\n\t\"RX\",\n\t\"TX\",\n\t\"DTR\",\n\t\"DCD\",\n\t\"DSR\",\n\t\"RTS\",\n\t\"RTR\",\n\t\"CTS\",\n}\n\nfunc (n *Net) Connect(e *Endpoint) ", "output": "{\n\tif e.Net != nil {\n\t\tmn := e.Net\n\t\totherEs := mn.Endpoints.List()\n\t\tfor _, otherE := range otherEs {\n\t\t\tn.Endpoints.Add(otherE)\n\t\t\totherE.Net = n\n\t\t\tmn.Endpoints.Remove(otherE)\n\t\t}\n\n\t\tfor _, cb := range mn.onReplace {\n\t\t\tcb(n)\n\n\t\t\tn.onReplace = append(n.onReplace, cb)\n\t\t}\n\t\treturn\n\t}\n\n\tn.Endpoints.Add(e)\n\te.Net = n\n}"} {"input": "package iso20022\n\n\ntype MarketType17Choice struct {\n\n\tCode *MarketType4Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification47 `xml:\"Prtry\"`\n}\n\n\n\nfunc (m *MarketType17Choice) AddProprietary() *GenericIdentification47 {\n\tm.Proprietary = new(GenericIdentification47)\n\treturn m.Proprietary\n}\n\nfunc (m *MarketType17Choice) SetCode(value string) ", "output": "{\n\tm.Code = (*MarketType4Code)(&value)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\nfunc Print(format string, params ...interface{}) {\n\tfmt.Fprintf(os.Stderr, format+\"\\n\", params...)\n}\n\n\n\nfunc Error(err error) {\n\tPrint(\"Error: %s\", err)\n}\n\nfunc Fatal(err error) {\n\tPrint(\"Fatal: %s\", err)\n\tos.Exit(1)\n}\n\nfunc main() {\n\tvar config Config\n\tvar err error\n\tif config, err = LoadConfig(); err != nil {\n\t\tFatal(err)\n\t}\n\n\tif err = config.Verify(); err != nil {\n\t\tFatal(err)\n\t}\n\n\tvar svcmon ServiceMonitor\n\tif svcmon, err = NewServiceMonitor(&config); err != nil {\n\t\tFatal(err)\n\t}\n\n\tcleanup := func() {\n\t\tsvcmon.Close()\n\t}\n\n\tdefer cleanup()\n\tsigchan := make(chan os.Signal, 1)\n\tsignal.Notify(sigchan, syscall.SIGINT)\n\tsignal.Notify(sigchan, syscall.SIGTERM)\n\tquit := make(chan bool)\n\n\tgo func() {\n\t\t<-sigchan\n\t\tcleanup()\n\t\tquit <- true\n\t}()\n\n\tgo func() {\n\t\tif err = svcmon.Run(); err != nil {\n\t\t\tFatal(err)\n\t\t}\n\t\tquit <- true\n\t}()\n\n\t<-quit\n}\n\nfunc Info(format string, params ...interface{}) ", "output": "{\n\tPrint(\"Info: \" + format, params...)\n}"} {"input": "package main\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc main() {\n\tdec := xml.NewDecoder(os.Stdin)\n\tvar stack []string \n\tfor {\n\t\ttok, err := dec.Token()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"xmlselect: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tswitch tok := tok.(type) {\n\t\tcase xml.StartElement:\n\t\t\tstack = append(stack, tok.Name.Local) \n\t\tcase xml.EndElement:\n\t\t\tstack = stack[:len(stack)-1] \n\t\tcase xml.CharData:\n\t\t\tif containsAll(stack, os.Args[1:]) {\n\t\t\t\tfmt.Printf(\"%s: %s\\n\", strings.Join(stack, \" \"), tok)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n\nfunc containsAll(x, y []string) bool ", "output": "{\n\tfor len(y) <= len(x) {\n\t\tif len(y) == 0 {\n\t\t\treturn true\n\t\t}\n\t\tif x[0] == y[0] {\n\t\t\ty = y[1:]\n\t\t}\n\t\tx = x[1:]\n\t}\n\treturn false\n}"} {"input": "package v1\n\n\n\ntype ConfigMapProjectionApplyConfiguration struct {\n\tLocalObjectReferenceApplyConfiguration `json:\",inline\"`\n\tItems []KeyToPathApplyConfiguration `json:\"items,omitempty\"`\n\tOptional *bool `json:\"optional,omitempty\"`\n}\n\n\n\nfunc ConfigMapProjection() *ConfigMapProjectionApplyConfiguration {\n\treturn &ConfigMapProjectionApplyConfiguration{}\n}\n\n\n\n\n\n\n\n\n\nfunc (b *ConfigMapProjectionApplyConfiguration) WithItems(values ...*KeyToPathApplyConfiguration) *ConfigMapProjectionApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithItems\")\n\t\t}\n\t\tb.Items = append(b.Items, *values[i])\n\t}\n\treturn b\n}\n\n\n\n\nfunc (b *ConfigMapProjectionApplyConfiguration) WithOptional(value bool) *ConfigMapProjectionApplyConfiguration {\n\tb.Optional = &value\n\treturn b\n}\n\nfunc (b *ConfigMapProjectionApplyConfiguration) WithName(value string) *ConfigMapProjectionApplyConfiguration ", "output": "{\n\tb.Name = &value\n\treturn b\n}"} {"input": "package elements\n\nimport (\n\t\"github.com/faiface/pixel\"\n\t\"github.com/faiface/pixel/pixelgl\"\n\t\"go-zelda/utils\"\n)\n\ntype Object struct {\n\tloc pixel.Vec\n\tsize pixel.Rect\n\tbounds pixel.Rect\n\tsprite *pixel.Sprite\n\tblocking bool\n}\n\n\n\nfunc (object *Object) draw(win *pixelgl.Window) {\n\tobject.sprite.Draw(win, pixel.IM.Scaled(pixel.ZV, 2.5).Moved(object.loc))\n}\n\nfunc NewObject(img string, loc pixel.Vec, blocking bool) *Object ", "output": "{\n\tobject := new(Object)\n\n\tpic, err := utils.LoadPicture(img)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tobject.size = pic.Bounds()\n\tobject.loc = loc\n\tobject.bounds = utils.GetBounds(object.loc, object.size)\n\tobject.sprite = pixel.NewSprite(pic, object.size)\n\tobject.blocking = blocking\n\n\treturn object\n}"} {"input": "package tempZero\n\nimport \"math\"\nimport (\n\t\"github.com/tflovorn/scExplorer/tempAll\"\n)\n\n\n\n\nfunc ZeroTempEnvironment(jsonData string) (*tempAll.Environment, error) ", "output": "{\n\tenv, err := tempAll.NewEnvironment(jsonData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tenv.Mu_b = 0.0\n\tenv.Beta = math.Inf(1)\n\n\treturn env, nil\n}"} {"input": "package request\n\nimport (\n\t\"time\"\n\n\t\"github.com/YakLabs/kube-cloudwatch-node-metrics/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/YakLabs/kube-cloudwatch-node-metrics/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr\"\n)\n\n\n\n\ntype Retryer interface {\n\tRetryRules(*Request) time.Duration\n\tShouldRetry(*Request) bool\n\tMaxRetries() int\n}\n\n\n\nfunc WithRetryer(cfg *aws.Config, retryer Retryer) *aws.Config {\n\tcfg.Retryer = retryer\n\treturn cfg\n}\n\n\n\nvar retryableCodes = map[string]struct{}{\n\t\"RequestError\": {},\n\t\"RequestTimeout\": {},\n\t\"ProvisionedThroughputExceededException\": {},\n\t\"Throttling\": {},\n\t\"ThrottlingException\": {},\n\t\"RequestLimitExceeded\": {},\n\t\"RequestThrottled\": {},\n\t\"LimitExceededException\": {}, \n\t\"TooManyRequestsException\": {}, \n}\n\n\n\n\nvar credsExpiredCodes = map[string]struct{}{\n\t\"ExpiredToken\": {},\n\t\"ExpiredTokenException\": {},\n\t\"RequestExpired\": {}, \n}\n\n\n\nfunc isCodeExpiredCreds(code string) bool {\n\t_, ok := credsExpiredCodes[code]\n\treturn ok\n}\n\n\n\nfunc (r *Request) IsErrorRetryable() bool {\n\tif r.Error != nil {\n\t\tif err, ok := r.Error.(awserr.Error); ok {\n\t\t\treturn isCodeRetryable(err.Code())\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc (r *Request) IsErrorExpired() bool {\n\tif r.Error != nil {\n\t\tif err, ok := r.Error.(awserr.Error); ok {\n\t\t\treturn isCodeExpiredCreds(err.Code())\n\t\t}\n\t}\n\treturn false\n}\n\nfunc isCodeRetryable(code string) bool ", "output": "{\n\tif _, ok := retryableCodes[code]; ok {\n\t\treturn true\n\t}\n\n\treturn isCodeExpiredCreds(code)\n}"} {"input": "package graphite\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n)\n\nfunc createFindMetricsTestServer() *httptest.Server {\n\treturn httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, `[\n\t\t\t{\"text\": \"one\", \"expandable\": 1, \"leaf\": 0, \"id\": \"cluster.one\", \"allowChildren\": 1},\n\t\t\t{\"text\": \"two\", \"expandable\": 1, \"leaf\": 0, \"id\": \"cluster.two\", \"allowChildren\": 1}]`)\n\t}))\n}\n\nfunc ExampleClient_FindMetrics() {\n\tts := createFindMetricsTestServer()\n\tdefer ts.Close()\n\n\tclient, _ := NewFromString(ts.URL)\n\tres, _ := client.FindMetrics(\n\t\tFindMetricRequest{\n\t\t\tQuery: \"cluster.*\",\n\t\t},\n\t)\n\tfmt.Printf(\"%+v\", res)\n\n}\n\nfunc createExpandMetricsTestServer() *httptest.Server {\n\treturn httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, \"{\\\"results\\\": [\\\"cluster.one\\\", \\\"cluster.two\\\"]}\")\n\t}))\n}\n\n\n\nfunc ExampleClient_ExpandMetrics() ", "output": "{\n\tts := createExpandMetricsTestServer()\n\tdefer ts.Close()\n\n\tclient, _ := NewFromString(ts.URL)\n\tres, _ := client.ExpandMetrics(\n\t\tExpandMetricRequest{\n\t\t\tQuery: \"cluster.*\",\n\t\t},\n\t)\n\tfmt.Printf(\"%+v\", res)\n}"} {"input": "package vminstall\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"io/ioutil\"\n\t\"strings\"\n)\n\ntype Downloader interface{\n\tDownload(url string) ([]byte, error)\n\tMatch() string\n}\n\ntype HTTPDownloader struct {\n\n}\n\n\n\nfunc (h HTTPDownloader) Download(url string) ([]byte,error) {\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\tcontents, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn contents,nil\n\n}\n\ntype DownloadManager struct {\n\tdownloaders []Downloader\n}\n\n\nfunc (manager *DownloadManager) Regsiter(d Downloader) {\n\tmanager.downloaders = append(manager.downloaders, d)\n}\n\n\nfunc (manager *DownloadManager) Download(url string) ([]byte,error) {\n\tvar found bool = false\n\tvar d Downloader\n\tfor _,d = range manager.downloaders {\n\t\tif strings.Index(url, d.Match()) == 0 {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif found {\n\t\treturn d.Download(url)\n\t} else {\n\t\treturn nil, errors.New(\"not found matching download\")\n\t}\n\n}\n\nfunc (h HTTPDownloader) Match() string ", "output": "{\n\treturn \"http\"\n}"} {"input": "package event\n\nimport (\n\t\"fmt\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\n\ntype Increment struct {\n\tName string\n\tValue int64\n}\n\n\n\n\nfunc (e *Increment) Update(e2 Event) error {\n\tif e.Type() != e2.Type() {\n\t\treturn fmt.Errorf(\"statsd event type conflict: %s vs %s \", e.String(), e2.String())\n\t}\n\tatomic.AddInt64(&e.Value, e2.Payload().(int64))\n\treturn nil\n}\n\n\nfunc (e *Increment) Reset() {\n\te.Value = 0\n}\n\n\nfunc (e Increment) Payload() interface{} {\n\treturn e.Value\n}\n\n\nfunc (e Increment) Stats(tick time.Duration) []string {\n\treturn []string{fmt.Sprintf(\"%s:%d|c\", e.Name, e.Value)}\n}\n\n\nfunc (e Increment) Key() string {\n\treturn e.Name\n}\n\n\nfunc (e *Increment) SetKey(key string) {\n\te.Name = key\n}\n\n\nfunc (e Increment) Type() int {\n\treturn EventIncr\n}\n\n\nfunc (e Increment) TypeString() string {\n\treturn \"Increment\"\n}\n\n\nfunc (e Increment) String() string {\n\treturn fmt.Sprintf(\"{Type: %s, Key: %s, Value: %d}\", e.TypeString(), e.Name, e.Value)\n}\n\nfunc (e *Increment) StatClass() string ", "output": "{\n\treturn \"counter\"\n}"} {"input": "package avalanche\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"time\"\n\n\t\"github.com/valyala/fasthttp\"\n)\n\n\ntype HTTPWriterConfig struct {\n\tHost string\n\n\tDatabase string\n}\n\n\ntype HTTPWriter struct {\n\tclient fasthttp.Client\n\n\tc HTTPWriterConfig\n\turl []byte\n}\n\n\nfunc NewHTTPWriter(c HTTPWriterConfig) LineProtocolWriter {\n\treturn &HTTPWriter{\n\t\tclient: fasthttp.Client{\n\t\t\tName: \"avalanche\",\n\t\t},\n\n\t\tc: c,\n\t\turl: []byte(c.Host + \"/write?db=\" + url.QueryEscape(c.Database)),\n\t}\n}\n\nvar (\n\tpost = []byte(\"POST\")\n\ttextPlain = []byte(\"text/plain\")\n)\n\n\n\n\n\n\nfunc (w *HTTPWriter) WriteLineProtocol(body []byte) (int64, error) ", "output": "{\n\treq := fasthttp.AcquireRequest()\n\treq.Header.SetContentTypeBytes(textPlain)\n\treq.Header.SetMethodBytes(post)\n\treq.Header.SetRequestURIBytes(w.url)\n\treq.SetBody(body)\n\n\tresp := fasthttp.AcquireResponse()\n\tstart := time.Now()\n\terr := w.client.Do(req, resp)\n\tlat := time.Since(start).Nanoseconds()\n\tif err == nil {\n\t\tsc := resp.StatusCode()\n\t\tif sc != fasthttp.StatusNoContent {\n\t\t\terr = fmt.Errorf(\"Invalid write response (status %d): %s\", sc, resp.Body())\n\t\t}\n\t}\n\n\tfasthttp.ReleaseResponse(resp)\n\tfasthttp.ReleaseRequest(req)\n\n\treturn lat, err\n}"} {"input": "package speech_test\n\nimport (\n\t\"io\"\n\n\t\"cloud.google.com/go/speech/apiv1beta1\"\n\t\"github.com/golang/protobuf/ptypes\"\n\t\"golang.org/x/net/context\"\n\tspeechpb \"google.golang.org/genproto/googleapis/cloud/speech/v1beta1\"\n)\n\n\n\nfunc ExampleClient_SyncRecognize() {\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &speechpb.SyncRecognizeRequest{\n\t}\n\tresp, err := c.SyncRecognize(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleClient_AsyncRecognize() {\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &speechpb.AsyncRecognizeRequest{\n\t}\n\top, err := c.AsyncRecognize(ctx, req)\n\tif err != nil {\n\t}\n\n\tvar resp ptypes.DynamicAny \n\tif err := op.Wait(ctx, &resp); err != nil {\n\t}\n}\n\nfunc StreamingRecognize() {\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\tstream, err := c.StreamingRecognize(ctx)\n\tif err != nil {\n\t}\n\tgo func() {\n\t\treqs := []*speechpb.StreamingRecognizeRequest{\n\t\t}\n\t\tfor _, req := range reqs {\n\t\t\tif err := stream.Send(req); err != nil {\n\t\t\t}\n\t\t}\n\t\tstream.CloseSend()\n\t}()\n\tfor {\n\t\tresp, err := stream.Recv()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}\n\nfunc ExampleNewClient() ", "output": "{\n\tctx := context.Background()\n\tc, err := speech.NewClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}"} {"input": "package metricworker\n\nimport (\n\t\"time\"\n\n\t\"github.com/juju/worker/v2\"\n\n\t\"github.com/juju/juju/api/metricsmanager\"\n\tjworker \"github.com/juju/juju/worker\"\n)\n\nconst cleanupPeriod = time.Hour\n\n\n\n\nfunc newCleanup(client metricsmanager.MetricsManagerClient, notify chan string, logger Logger) worker.Worker ", "output": "{\n\tf := func(stopCh <-chan struct{}) error {\n\t\terr := client.CleanupOldMetrics()\n\t\tif err != nil {\n\t\t\tlogger.Warningf(\"failed to cleanup %v - will retry later\", err)\n\t\t\treturn nil\n\t\t}\n\t\tselect {\n\t\tcase notify <- \"cleanupCalled\":\n\t\tdefault:\n\t\t}\n\t\treturn nil\n\t}\n\treturn jworker.NewPeriodicWorker(f, cleanupPeriod, jworker.NewTimer)\n}"} {"input": "package main\n\nimport \"github.com/augustoroman/serial_lcd\"\n\ntype FakeLcd struct{}\n\nfunc (f FakeLcd) SetBG(r, g, b uint8) error { return nil }\nfunc (f FakeLcd) SetOn(On bool) error { return nil }\nfunc (f FakeLcd) SetBrightness(b uint8) error { return nil }\nfunc (f FakeLcd) SetContrast(c uint8) error { return nil }\nfunc (f FakeLcd) SetAutoscroll(On bool) error { return nil }\nfunc (f FakeLcd) SetSize(cols, rows uint8) error { return nil }\nfunc (f FakeLcd) Clear() error { return nil }\n\nfunc (f FakeLcd) MoveTo(col, row uint8) error { return nil }\nfunc (f FakeLcd) MoveForward() error { return nil }\nfunc (f FakeLcd) MoveBack() error { return nil }\nfunc (f FakeLcd) Write(b []byte) (int, error) { return len(b), nil }\n\nfunc (f FakeLcd) CreateCustomChar(spot uint8, c serial_lcd.Char) error { return nil }\n\nfunc (f FakeLcd) Home() error ", "output": "{ return nil }"} {"input": "package names\n\nimport \"knative.dev/pkg/kmeta\"\n\n\nfunc Deployment(rev kmeta.Accessor) string {\n\treturn kmeta.ChildName(rev.GetName(), \"-deployment\")\n}\n\n\n\n\n\nfunc PA(rev kmeta.Accessor) string {\n\treturn rev.GetName()\n}\n\nfunc ImageCache(rev kmeta.Accessor) string ", "output": "{\n\treturn kmeta.ChildName(rev.GetName(), \"-cache\")\n}"} {"input": "package datastructures\n\n\ntype Comparable interface {\n\tCompare(Comparable) int\n}\n\n\ntype Comparables []Comparable\n\n\n\n\n\nfunc (cs Comparables) Less(i, j int) bool {\n\tif cs[i].Compare(cs[j]) < 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\nfunc (cs *Comparables) Shift() Comparable {\n\tif len(*cs) == 0 {\n\t\treturn nil\n\t}\n\n\tf := (*cs)[0]\n\t*cs = (*cs)[1:]\n\treturn f\n}\n\n\nfunc (cs Comparables) Swap(i, j int) {\n\tcs[i], cs[j] = cs[j], cs[i]\n}\n\n\ntype IntComparable int\n\n\nfunc (ic IntComparable) Compare(i Comparable) int {\n\tother, ok := i.(IntComparable)\n\n\tif !ok {\n\t\tpanic(\"param should be an intComparable\")\n\t}\n\n\tif int(ic) == int(other) {\n\t\treturn 0\n\t} else if int(ic) < int(other) {\n\t\treturn -1\n\t} else {\n\t\treturn 1\n\t}\n}\n\nfunc (cs Comparables) Len() int ", "output": "{\n\treturn len(cs)\n}"} {"input": "package golax\n\nimport \"net/http\"\n\n\n\ntype Context struct {\n\tRequest *http.Request\n\tResponse *ExtendedWriter\n\tParameter string\n\tParameters map[string]string\n\tLastError *ContextError\n\tScope map[string]interface{}\n\tPathHandlers string\n\tafters []Handler\n\tdeepInterceptors []*Interceptor\n}\n\n\n\ntype ContextError struct {\n\tStatusCode int `json:\"status_code\"`\n\tErrorCode int `json:\"error_code\"`\n\tDescription string `json:\"description_code\"`\n}\n\n\nfunc NewContext() *Context {\n\treturn &Context{\n\t\tLastError: nil,\n\t\tParameters: map[string]string{},\n\t\tScope: map[string]interface{}{},\n\t\tafters: []Handler{},\n\t\tdeepInterceptors: []*Interceptor{},\n\t}\n}\n\nfunc (c *Context) Error(s int, d string) *ContextError {\n\tc.Response.WriteHeader(s)\n\te := &ContextError{\n\t\tStatusCode: s,\n\t\tDescription: d,\n\t}\n\tc.LastError = e\n\treturn e\n}\n\n\n\n\n\nfunc (c *Context) Get(k string) (interface{}, bool) {\n\ta, b := c.Scope[k]\n\treturn a, b\n}\n\nfunc (c *Context) Set(k string, v interface{}) ", "output": "{\n\tc.Scope[k] = v\n}"} {"input": "package metrics\n\n\n\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\tgolangswaggerpaths \"path\"\n)\n\n\ntype GetMetricsURL struct {\n\t_basePath string\n}\n\n\n\n\nfunc (o *GetMetricsURL) WithBasePath(bp string) *GetMetricsURL {\n\to.SetBasePath(bp)\n\treturn o\n}\n\n\n\n\nfunc (o *GetMetricsURL) SetBasePath(bp string) {\n\to._basePath = bp\n}\n\n\n\n\n\nfunc (o *GetMetricsURL) Must(u *url.URL, err error) *url.URL {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif u == nil {\n\t\tpanic(\"url can't be nil\")\n\t}\n\treturn u\n}\n\n\nfunc (o *GetMetricsURL) String() string {\n\treturn o.Must(o.Build()).String()\n}\n\n\nfunc (o *GetMetricsURL) BuildFull(scheme, host string) (*url.URL, error) {\n\tif scheme == \"\" {\n\t\treturn nil, errors.New(\"scheme is required for a full url on GetMetricsURL\")\n\t}\n\tif host == \"\" {\n\t\treturn nil, errors.New(\"host is required for a full url on GetMetricsURL\")\n\t}\n\n\tbase, err := o.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbase.Scheme = scheme\n\tbase.Host = host\n\treturn base, nil\n}\n\n\nfunc (o *GetMetricsURL) StringFull(scheme, host string) string {\n\treturn o.Must(o.BuildFull(scheme, host)).String()\n}\n\nfunc (o *GetMetricsURL) Build() (*url.URL, error) ", "output": "{\n\tvar result url.URL\n\n\tvar _path = \"/metrics/\"\n\n\t_basePath := o._basePath\n\tif _basePath == \"\" {\n\t\t_basePath = \"/v1\"\n\t}\n\tresult.Path = golangswaggerpaths.Join(_basePath, _path)\n\n\treturn &result, nil\n}"} {"input": "package util\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestGetValuesBySortedKeys(t *testing.T) {\n\ttype name struct {\n\t\tfName string\n\t\tlName string\n\t}\n\tmapKeyValue := make(map[string]*name)\n\tmapKeyValue[\"2\"] = &name{\"Two\", \"two\"}\n\tmapKeyValue[\"3\"] = &name{\"Three\", \"three\"}\n\tmapKeyValue[\"5\"] = &name{\"Five\", \"five\"}\n\tmapKeyValue[\"\"] = &name{\"None\", \"none\"}\n\n\tsortedRes := []*name{}\n\tGetValuesBySortedKeys(&mapKeyValue, &sortedRes)\n\tassert.Equal(\n\t\tt,\n\t\t[]*name{&name{\"None\", \"none\"}, &name{\"Two\", \"two\"}, &name{\"Three\", \"three\"}, &name{\"Five\", \"five\"}},\n\t\tsortedRes,\n\t)\n}\n\nfunc TestGetSortedKeys(t *testing.T) ", "output": "{\n\tmapKeyValue := make(map[string]int)\n\tmapKeyValue[\"blue\"] = 10\n\tmapKeyValue[\"apple\"] = 15\n\tmapKeyValue[\"red\"] = 12\n\tmapKeyValue[\"123\"] = 22\n\tmapKeyValue[\"a\"] = 33\n\tmapKeyValue[\"\"] = 30\n\tassert.Equal(t, []string{\"\", \"123\", \"a\", \"apple\", \"blue\", \"red\"}, GetSortedKeys(mapKeyValue))\n}"} {"input": "package multi\n\nimport (\n\t\"github.com/thehivecorporation/log\"\n\t\"github.com/thehivecorporation/log/telemetry\"\n)\n\ntype writerImpl struct {\n\ttelemetry.Common\n\twriters []log.Writer\n}\n\n\n\nfunc New(ws ...log.Writer) log.Writer {\n\treturn &writerImpl{\n\t\twriters: ws,\n\t}\n}\n\nfunc (w *writerImpl) WriteLog(payload *log.Payload) ", "output": "{\n\tfor _, wr := range w.writers {\n\t\twr.WriteLog(payload)\n\t}\n}"} {"input": "package ignition\n\nimport (\n\t\"github.com/coreos/ignition/config/v2_1/types\"\n\t\"github.com/hashicorp/terraform/helper/schema\"\n)\n\nfunc resourceDirectory() *schema.Resource {\n\treturn &schema.Resource{\n\t\tExists: resourceDirectoryExists,\n\t\tRead: resourceDirectoryRead,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"filesystem\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"path\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"mode\": &schema.Schema{\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"uid\": &schema.Schema{\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"gid\": &schema.Schema{\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceDirectoryRead(d *schema.ResourceData, meta interface{}) error {\n\tid, err := buildDirectory(d, globalCache)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.SetId(id)\n\treturn nil\n}\n\nfunc resourceDirectoryExists(d *schema.ResourceData, meta interface{}) (bool, error) {\n\tid, err := buildDirectory(d, globalCache)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn id == d.Id(), nil\n}\n\n\n\nfunc buildDirectory(d *schema.ResourceData, c *cache) (string, error) ", "output": "{\n\tdir := &types.Directory{}\n\tdir.Filesystem = d.Get(\"filesystem\").(string)\n\tif err := handleReport(dir.ValidateFilesystem()); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdir.Path = d.Get(\"path\").(string)\n\tif err := handleReport(dir.ValidatePath()); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdir.Mode = d.Get(\"mode\").(int)\n\tif err := handleReport(dir.ValidateMode()); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tuid := d.Get(\"uid\").(int)\n\tif uid != 0 {\n\t\tdir.User = types.NodeUser{ID: &uid}\n\t}\n\n\tgid := d.Get(\"gid\").(int)\n\tif gid != 0 {\n\t\tdir.Group = types.NodeGroup{ID: &gid}\n\t}\n\n\treturn c.addDirectory(dir), nil\n}"} {"input": "package longrunning_test\n\nimport (\n\t\"cloud.google.com/go/longrunning/autogen\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/api/iterator\"\n\tlongrunningpb \"google.golang.org/genproto/googleapis/longrunning\"\n)\n\n\n\nfunc ExampleOperationsClient_GetOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.GetOperationRequest{\n\t}\n\tresp, err := c.GetOperation(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleOperationsClient_ListOperations() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.ListOperationsRequest{\n\t}\n\tit := c.ListOperations(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}\n\nfunc ExampleOperationsClient_CancelOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.CancelOperationRequest{\n\t}\n\terr = c.CancelOperation(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleOperationsClient_DeleteOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.DeleteOperationRequest{\n\t}\n\terr = c.DeleteOperation(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleNewOperationsClient() ", "output": "{\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}"} {"input": "package keybindings\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/atotto/clipboard\"\n\t\"github.com/dambrisco/bored/layout\"\n\t\"github.com/dambrisco/bored/reddit\"\n\t\"github.com/jroimartin/gocui\"\n\t\"github.com/toqueteos/webbrowser\"\n)\n\nfunc enter(g *gocui.Gui, v *gocui.View) error {\n\tsubmission := reddit.GetCurrentSubmission()\n\twebbrowser.Open(\"https://www.reddit.com/\" + submission.Permalink)\n\treturn nil\n}\n\nfunc link(g *gocui.Gui, v *gocui.View) error {\n\tsubmission := reddit.GetCurrentSubmission()\n\twebbrowser.Open(submission.URL)\n\treturn nil\n}\n\nfunc yank(g *gocui.Gui, v *gocui.View) error {\n\tsubmission := reddit.GetCurrentSubmission()\n\tclipboard.WriteAll(submission.URL)\n\treturn nil\n}\n\n\n\nfunc info(g *gocui.Gui, v *gocui.View) error {\n\tif layout.GetPage() == layout.List {\n\t\ts := reddit.GetCurrentSubmission()\n\t\tb := v.Buffer()\n\t\tv.Clear()\n\t\tif strings.HasPrefix(b, \"S\") {\n\t\t\tfmt.Fprint(v, layout.BuildTitleTag(s))\n\t\t} else {\n\t\t\tfmt.Fprintf(v, \"Score: %d | Subreddit: %s\", s.Score, s.Subreddit)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc comments(g *gocui.Gui, v *gocui.View) error ", "output": "{\n\tlayout.SetPage(layout.Comments)\n\tlayout.Clear(g, v)\n\treturn nil\n}"} {"input": "package tequilapi\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n\ntype APIServer interface {\n\tWait() error\n\tStartServing() error\n\tStop()\n\tAddress() (string, error)\n}\n\ntype apiServer struct {\n\terrorChannel chan error\n\thandler http.Handler\n\tlistenAddress string\n\tlistener net.Listener\n}\n\n\n\n\n\nfunc (server *apiServer) Stop() {\n\tif server.listener == nil {\n\t\treturn\n\t}\n\tserver.listener.Close()\n}\n\n\nfunc (server *apiServer) Wait() error {\n\treturn <-server.errorChannel\n}\n\n\nfunc (server *apiServer) Address() (string, error) {\n\tif server.listener == nil {\n\t\treturn \"\", errors.New(\"not bound\")\n\t}\n\treturn extractBoundAddress(server.listener)\n}\n\n\n\nfunc (server *apiServer) StartServing() error {\n\tvar err error\n\tserver.listener, err = net.Listen(\"tcp\", server.listenAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo server.serve(server.handler)\n\treturn nil\n}\n\nfunc (server *apiServer) serve(handler http.Handler) {\n\tserver.errorChannel <- http.Serve(server.listener, handler)\n}\n\nfunc extractBoundAddress(listener net.Listener) (string, error) {\n\taddr := listener.Addr()\n\tparts := strings.Split(addr.String(), \":\")\n\tif len(parts) < 2 {\n\t\treturn \"\", errors.New(\"Unable to locate address: \" + addr.String())\n\t}\n\treturn addr.String(), nil\n}\n\nfunc NewServer(address string, port int, handler http.Handler, corsPolicy CorsPolicy) APIServer ", "output": "{\n\tserver := apiServer{\n\t\tmake(chan error, 1),\n\t\tDisableCaching(ApplyCors(handler, corsPolicy)),\n\t\tfmt.Sprintf(\"%s:%d\", address, port),\n\t\tnil}\n\treturn &server\n}"} {"input": "package stats\n\nvar (\n\tNoOpStatsFactory StatsFactory\n)\n\ntype noopCounter struct {\n}\n\nfunc (s noopCounter) Inc() {\n}\n\nfunc (s noopCounter) Add(v float64) {\n}\n\ntype noopGauge struct {\n}\n\nfunc (s noopGauge) Inc() {\n}\n\nfunc (s noopGauge) Add(v float64) {\n}\n\nfunc (s noopGauge) Dec() {\n}\n\nfunc (s noopGauge) Sub(v float64) {\n}\n\nfunc (s noopGauge) Set(v float64) {\n}\n\nfunc (s noopGauge) Get() float64 {\n\treturn 0\n}\n\ntype noopSummary struct {\n}\n\nfunc (s noopSummary) Observe(v float64) {\n}\n\ntype noopStatsFactory struct {\n}\n\nfunc (f noopStatsFactory) NewCounter(\n\tmetric string,\n\ttags map[string]string) CounterStat {\n\n\treturn noopCounter{}\n}\n\nfunc (f noopStatsFactory) NewGauge(\n\tmetric string,\n\ttags map[string]string) GaugeStat {\n\n\treturn noopGauge{}\n}\n\nfunc (f noopStatsFactory) NewSummary(\n\tmetric string,\n\ttags map[string]string) SummaryStat {\n\n\treturn noopSummary{}\n}\n\n\n\nfunc init() ", "output": "{\n\tNoOpStatsFactory = noopStatsFactory{}\n}"} {"input": "package accumulator\n\nimport \"strconv\"\n\ntype Int64 int64\n\n\n\n\n\nfunc (a *Int64) Accumulate64(i int64, err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t*a += Int64(i)\n}\n\nfunc (a *Int64) String() string {\n\treturn strconv.FormatInt(int64(*a), 10)\n}\n\nfunc (a *Int64) Accumulate(i int, err error) ", "output": "{\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t*a += Int64(i)\n}"} {"input": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"go/format\"\n \"log\"\n \"os\"\n \"strings\"\n)\n\ntype Kind int\n\nconst (\n \n Flat Kind = iota\n \n \n Lutc\n \n \n \n Lutr\n)\n\ntype Generator struct {\n buf bytes.Buffer\n}\n\nfunc (g *Generator) Printf(format string, args ...interface{}) {\n fmt.Fprintf(&g.buf, format, args...)\n}\n\n\n\nfunc (g *Generator) Format() []byte {\n src, err := format.Source(g.buf.Bytes())\n if err != nil {\n log.Printf(\"warning: invalid Go generated: %s\\n\", err)\n log.Printf(\"warning: compile the package to analyse the error\\n\")\n return g.buf.Bytes()\n }\n return src\n}\n\nfunc (g *Generator) Generate(pkgName string, kind Kind) ", "output": "{\n g.Printf(\"// automatically generated by avrmakedec %s\\n\", strings.Join(os.Args[1:], \" \"))\n g.Printf(\"// DO NOT EDIT\\n\")\n g.Printf(\"package %s\\n\", pkgName)\n g.Printf(\"import \\\"github.com/kierdavis/avr\\\"\\n\")\n switch kind {\n case Flat:\n g.GenerateFlat()\n case Lutc:\n g.GenerateLutc()\n case Lutr:\n g.GenerateLutr()\n default:\n panic(\"Generator.Generate: bad Kind\")\n }\n}"} {"input": "package outlet\n\nimport (\n\t\"fmt\"\n\t\"l2met/bucket\"\n\t\"l2met/store\"\n\t\"time\"\n)\n\ntype BucketReader struct {\n\tStore store.Store\n\tInterval time.Duration\n\tPartition string\n\tTtl uint64\n\tNumOutlets int\n\tNumScanners int\n\tInbox chan *bucket.Bucket\n\tOutbox chan *bucket.Bucket\n}\n\n\n\nfunc (r *BucketReader) Start(out chan *bucket.Bucket) {\n\tr.Outbox = out\n\tgo r.scan()\n\tfor i := 0; i < r.NumOutlets; i++ {\n\t\tgo r.outlet()\n\t}\n}\n\nfunc (r *BucketReader) scan() {\n\tfor t := range time.Tick(r.Interval) {\n\t\tbuckets, err := r.Store.Scan(t)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"at=bucket.scan error=%s\\n\", err)\n\t\t\tcontinue\n\t\t}\n\t\tfor bucket := range buckets {\n\t\t\tr.Inbox <- bucket\n\t\t}\n\t}\n}\n\nfunc (r *BucketReader) outlet() {\n\tfor b := range r.Inbox {\n\t\tr.Store.Get(b)\n\t\tr.Outbox <- b\n\t}\n}\n\nfunc NewBucketReader(sz, c int, i time.Duration, st store.Store) *BucketReader ", "output": "{\n\trdr := new(BucketReader)\n\trdr.Partition = \"bucket-reader\"\n\trdr.Inbox = make(chan *bucket.Bucket, sz)\n\trdr.NumScanners = c\n\trdr.NumOutlets = c\n\trdr.Interval = i\n\trdr.Store = st\n\treturn rdr\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nconst cookieName = \"Site-Cookie1\"\n\nfunc main() {\n\thttp.Handle(\"/favicon.ico\", http.NotFoundHandler())\n\thttp.HandleFunc(\"/\", root)\n\thttp.HandleFunc(\"/set\", set)\n\thttp.HandleFunc(\"/read\", read)\n\thttp.HandleFunc(\"/expire\", expire)\n\tlog.Println(\"Starting server on 8080\")\n\tlog.Fatalln(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc root(w http.ResponseWriter, _ *http.Request) {\n\tfmt.Fprint(w, `

Set

`)\n}\n\nfunc set(w http.ResponseWriter, _ *http.Request) {\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: cookieName,\n\t\tValue: \"This is a Site Cookie created\",\n\t})\n\tfmt.Fprint(w, `

Read

`)\n}\n\n\n\nfunc expire(w http.ResponseWriter, r *http.Request) {\n\tcoo, err := r.Cookie(cookieName)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Redirect(w, r, \"/set\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tcoo.MaxAge = -1 \n\thttp.SetCookie(w, coo)\n\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n}\n\nfunc read(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tcoo, err := r.Cookie(cookieName)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Redirect(w, r, \"/set\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tfmt.Fprintf(w, \"

Cookie Value: %s

\", coo.Value)\n\tfmt.Fprint(w, `

Expire

`)\n}"} {"input": "package dummy\n\nimport (\n\t\"log\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/svenwiltink/go-musicbot/pkg/music\"\n)\n\ntype SongPlayer struct {\n\tlock sync.Mutex\n}\n\nfunc (player *SongPlayer) CanPlay(song music.Song) bool {\n\treturn true\n}\n\nfunc (player *SongPlayer) Wait() {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\ttime.Sleep(time.Second * 10)\n}\n\nfunc (player *SongPlayer) PlaySong(song music.Song) error {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\tlog.Printf(\"starting playback of %s\", song.Name)\n\treturn nil\n}\n\n\n\nfunc (player *SongPlayer) Pause() error {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\tlog.Printf(\"pausing playback\")\n\treturn nil\n}\n\nfunc NewSongPlayer() *SongPlayer {\n\treturn &SongPlayer{}\n}\n\nfunc (player *SongPlayer) Play() error ", "output": "{\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\tlog.Printf(\"resuming playback\")\n\treturn nil\n}"} {"input": "package requirements\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cloudfoundry/cli/cf\"\n\t\"github.com/cloudfoundry/cli/cf/configuration/core_config\"\n\t. \"github.com/cloudfoundry/cli/cf/i18n\"\n\t\"github.com/cloudfoundry/cli/cf/models\"\n\t\"github.com/cloudfoundry/cli/cf/terminal\"\n)\n\n\ntype TargetedOrgRequirement interface {\n\tRequirement\n\tGetOrganizationFields() models.OrganizationFields\n}\n\ntype targetedOrgApiRequirement struct {\n\tui terminal.UI\n\tconfig core_config.Reader\n}\n\n\n\nfunc (req targetedOrgApiRequirement) Execute() (success bool) {\n\tif !req.config.HasOrganization() {\n\t\tmessage := fmt.Sprintf(T(\"No org targeted, use '{{.Command}}' to target an org.\", map[string]interface{}{\"Command\": terminal.CommandColor(cf.Name() + \" target -o ORG\")}))\n\t\treq.ui.Failed(message)\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (req targetedOrgApiRequirement) GetOrganizationFields() (org models.OrganizationFields) {\n\treturn req.config.OrganizationFields()\n}\n\nfunc NewTargetedOrgRequirement(ui terminal.UI, config core_config.Reader) TargetedOrgRequirement ", "output": "{\n\treturn targetedOrgApiRequirement{ui, config}\n}"} {"input": "package mock\n\nimport (\n\t\"github.com/eventials/goevents/messaging\"\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype Connection struct {\n\tmock.Mock\n}\n\nfunc NewMockConnection() messaging.Connection {\n\treturn &Connection{}\n}\n\n\n\nfunc (c *Connection) Producer(exchange string) (messaging.Producer, error) {\n\targs := c.Called(exchange)\n\treturn args.Get(0).(messaging.Producer), args.Error(1)\n}\n\nfunc (c *Connection) Close() {\n\tc.Called()\n}\n\nfunc (c *Connection) NotifyConnectionClose() <-chan error {\n\targs := c.Called()\n\treturn args.Get(0).(chan error)\n}\n\nfunc (c *Connection) NotifyReestablish() <-chan bool {\n\targs := c.Called()\n\treturn args.Get(0).(chan bool)\n}\n\nfunc (c *Connection) WaitUntilConnectionCloses() {\n\tc.Called()\n}\n\nfunc (c *Connection) WaitUntilConnectionReestablished() {\n\tc.Called()\n}\n\nfunc (c *Connection) IsConnected() bool {\n\targs := c.Called()\n\treturn args.Get(0).(bool)\n}\n\nfunc (c *Connection) Consumer(autoAck bool, exchange, queue string) (messaging.Consumer, error) ", "output": "{\n\targs := c.Called(autoAck, exchange, queue)\n\treturn args.Get(0).(messaging.Consumer), args.Error(1)\n}"} {"input": "package store\n\nimport (\n\t\"github.com/docker/docker/pkg/plugins\"\n)\n\n\n\n\n\nfunc LookupWithCapability(name, capability string, _ int) (CompatPlugin, error) {\n\treturn plugins.Get(name, capability)\n}\n\nfunc FindWithCapability(capability string) ([]CompatPlugin, error) ", "output": "{\n\tpl, err := plugins.GetAll(capability)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := make([]CompatPlugin, len(pl))\n\tfor i, p := range pl {\n\t\tresult[i] = p\n\t}\n\treturn result, nil\n}"} {"input": "package linux\n\nimport (\n\t\"testing\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestGetAdapters(t *testing.T) {\n\n\tlog.SetLevel(log.DebugLevel)\n\n\tlist, err := GetAdapters()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassert.NotEmpty(t, list)\n}\n\nfunc TestGetAdapter(t *testing.T) {\n\tlog.SetLevel(log.DebugLevel)\n\t_, err := GetAdapter(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestGetAdapterNotFound(t *testing.T) {\n\t_, err := GetAdapter(\"hci999\")\n\tif err == nil {\n\t\tt.Fatal(\"adapter should not exists\")\n\t}\n}\n\nfunc TestUp(t *testing.T) {\n\terr := Up(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDown(t *testing.T) {\n\terr := Down(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\n\nfunc TestReset(t *testing.T) ", "output": "{\n\terr := Reset(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\nfunc Index(vs []string, t string) int {\n\tfor i, v := range vs {\n\t\tif v == t {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\n\n\nfunc Include(vs []string, t string) bool {\n\treturn Index(vs, t) >= 0\n}\n\n\n\nfunc Any(vs []string, f func(string) bool) bool {\n\tfor _, v := range vs {\n\t\tif f(v) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc All(vs []string, f func(string) bool) bool {\n\tfor _, v := range vs {\n\t\tif !f(v) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\n\n\nfunc Map(vs []string, f func(string) string) []string {\n\tvsm := make([]string, len(vs))\n\tfor i, v := range vs {\n\t\tvsm[i] = f(v)\n\t}\n\treturn vsm\n}\n\nfunc main() {\n\n\tvar strs = []string{\"peach\", \"apple\", \"pear\", \"plum\"}\n\n\tfmt.Println(Index(strs, \"pear\"))\n\n\tfmt.Println(Include(strs, \"grape\"))\n\n\tfmt.Println(Any(strs, func(v string) bool {\n\t\treturn strings.HasPrefix(v, \"p\")\n\t}))\n\n\tfmt.Println(All(strs, func(v string) bool {\n\t\treturn strings.HasPrefix(v, \"p\")\n\t}))\n\n\tfmt.Println(Filter(strs, func(v string) bool {\n\t\treturn strings.Contains(v, \"e\")\n\t}))\n\n\tfmt.Println(Map(strs, strings.ToUpper))\n\n}\n\nfunc Filter(vs []string, f func(string) bool) []string ", "output": "{\n\tvsf := make([]string, 0)\n\tfor _, v := range vs {\n\t\tif f(v) {\n\t\t\tvsf = append(vsf, v)\n\t\t}\n\t}\n\treturn vsf\n}"} {"input": "package ans\n\nimport (\n\t\"time\"\n)\n\n\n\n\ntype Response struct {\n\tID string `json:\"id\"`\n\tStatusCode int `json:\"status_code\"`\n\tBody ResponseBody `json:\"body\"`\n}\n\n\n\ntype ResponseBody struct {\n\tReason string `json:\"reason\"`\n\tTimestamp int64 `json:\"timestamp\"`\n}\n\n\n\nfunc (r *ResponseBody) GetTimestamp() time.Time {\n\n\tif r == nil || r.Timestamp == 0 {\n\t\treturn time.Time{}\n\t}\n\n\tms := time.Millisecond * time.Duration(r.Timestamp)\n\n\treturn time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC).Add(ms)\n}\n\nfunc NewResponse(id string, statusCode int) *Response ", "output": "{\n\treturn &Response{\n\t\tID: id,\n\t\tStatusCode: statusCode,\n\t}\n}"} {"input": "package main\n\nimport (\n \"os\"\n \"fmt\"\n \"bufio\"\n \"encoding/hex\"\n)\n\n\nfunc check(e error) {\n\tif e != nil {\n\t\tfmt.Printf(\"Error: %s\\n\", e.Error())\n\t\tos.Exit(0)\n\t}\n}\n\n\n\n\n\nfunc chunk(data []byte, size int) [][]byte {\n var chunks [][]byte\n\n for i:=0; i 1 {\n\t\tgo f.(func(...interface{}))(args)\n\t} else if len(args) == 1 {\n\t\tgo f.(func(interface{}))(args[0])\n\t} else {\n\t\tgo f.(func())()\n\t}\n}\n\n\n\nfunc f2(i interface{}) {\n\tfmt.Println(\"f2 done\", i)\n}\n\nfunc f3(args ...interface{}) {\n\tfmt.Println(\"f3 done\", args)\n}\n\nfunc main() {\n\tgoFunc1(f1)\n\tgoFunc2(f2, 100)\n\n\tgoFunc(f1)\n\tgoFunc(f2, \"xxxx\")\n\tgoFunc(f3, \"hello\", \"world\", 1, 3.14)\n\ttime.Sleep(5 * time.Second)\n}\n\nfunc f1() ", "output": "{\n\tfmt.Println(\"f1 done\")\n}"} {"input": "package gorm\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"github.com/jinzhu/gorm\"\n)\n\n\ntype GR struct {\n\tDB *gorm.DB\n\tServerInfo \n}\n\n\n\ntype ServerInfo struct {\n\thost string\n\tport uint16\n\tdbname string\n\tuser string\n\tpass string\n}\n\nvar dbInfo GR\n\n\nfunc New(host, dbname, user, pass string, port uint16) error {\n\n\tvar err error\n\tif dbInfo.DB == nil {\n\t\tdbInfo.host = host\n\t\tdbInfo.port = port\n\t\tdbInfo.dbname = dbname\n\t\tdbInfo.user = user\n\t\tdbInfo.pass = pass\n\n\t\tdbInfo.DB, err = dbInfo.Connection()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc GetDB() *GR {\n\tif dbInfo.DB == nil {\n\t\tpanic(errors.New(\"DB instance is nil\"))\n\t}\n\treturn &dbInfo\n}\n\nfunc (gr *GR) getDsn() string {\n\tparam := \"?charset=utf8&parseTime=True&loc=Local\"\n\treturn fmt.Sprintf(\"%s:%s@tcp(%s:%d)/%s%s\",\n\t\tgr.user, gr.pass, gr.host, gr.port, gr.dbname, param)\n}\n\n\n\nfunc (gr *GR) Connection() (*gorm.DB, error) {\n\treturn gorm.Open(\"mysql\", gr.getDsn())\n}\n\n\n\n\nfunc (gr *GR) Close() ", "output": "{\n\tgr.DB.Close()\n}"} {"input": "package server\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/influxdata/influxdb/chronograf\"\n\t\"github.com/influxdata/influxdb/chronograf/influx\"\n)\n\n\n\n\nfunc ToQueryConfig(query string) chronograf.QueryConfig {\n\tqc, err := influx.Convert(query)\n\tif err == nil {\n\t\treturn qc\n\t}\n\treturn chronograf.QueryConfig{\n\t\tRawText: &query,\n\t\tFields: []chronograf.Field{},\n\t\tGroupBy: chronograf.GroupBy{\n\t\t\tTags: []string{},\n\t\t},\n\t\tTags: make(map[string][]string),\n\t}\n}\n\nvar validFieldTypes = map[string]bool{\n\t\"func\": true,\n\t\"field\": true,\n\t\"integer\": true,\n\t\"number\": true,\n\t\"regex\": true,\n\t\"wildcard\": true,\n}\n\n\n\n\nfunc ValidateQueryConfig(q *chronograf.QueryConfig) error ", "output": "{\n\tfor _, fld := range q.Fields {\n\t\tinvalid := fmt.Errorf(`invalid field type \"%s\" ; expect func, field, integer, number, regex, wildcard`, fld.Type)\n\t\tif !validFieldTypes[fld.Type] {\n\t\t\treturn invalid\n\t\t}\n\t\tfor _, arg := range fld.Args {\n\t\t\tif !validFieldTypes[arg.Type] {\n\t\t\t\treturn invalid\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package server\n\nimport (\n\t\"github.com/Ray-GuanhuiLiang/GoGuidGenerator/common\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n\t\"log\"\n\t\"net\"\n)\n\ntype GrpcServer struct {\n\tgenerator common.Generator\n\tserv *grpc.Server\n\texit chan int\n}\n\n\n\nfunc (this *GrpcServer) Start() error {\n\tlistener, err := net.Listen(\"tcp\", \":5588\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn err\n\t}\n\tgo this.serv.Serve(listener)\n\treturn nil\n}\n\nfunc (this *GrpcServer) Wait() {\n\t<-this.exit\n}\n\nfunc (this *GrpcServer) GetGuid(context.Context, *Req) (*Resp, error) {\n\tid, err := this.generator.Generate()\n\tvar (\n\t\tr Resp\n\t\tcode int32\n\t\tguid uint64\n\t)\n\tif err != nil {\n\t\tcode = 1\n\t\tguid = 0\n\t} else {\n\t\tcode = 0\n\t\tguid = id\n\t}\n\tr.Code = &code\n\tr.Guid = &guid\n\treturn &r, err\n}\n\nfunc NewGrpcServer(generator common.Generator) *GrpcServer ", "output": "{\n\te := make(chan int)\n\tserv := grpc.NewServer()\n\ts := &GrpcServer{generator, serv, e}\n\tRegisterGuidServer(serv, s)\n\treturn s\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\n\n\ntype TaskIDRange struct {\n\n\tEnd *int32 `json:\"end\"`\n\n\tStart *int32 `json:\"start\"`\n}\n\n\nfunc (m *TaskIDRange) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateEnd(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStart(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\nfunc (m *TaskIDRange) validateStart(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"start\", \"body\", m.Start); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *TaskIDRange) validateEnd(formats strfmt.Registry) error ", "output": "{\n\n\tif err := validate.Required(\"end\", \"body\", m.End); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package reacttype\n\nimport (\n\t\"myitcv.io/react\"\n)\n\n\n\n\n\n\n\n\ntype HelloMessageDef struct {\n\treact.ComponentDef\n}\n\n\n\n\ntype HelloMessageProps struct {\n\tName string\n}\n\n\n\n\ntype HelloMessageState struct {\n\tcount int\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc HelloMessage(p HelloMessageProps) *HelloMessageElem {\n\treturn buildHelloMessageElem(p)\n}\n\n\n\n\n\n\nfunc (r HelloMessageDef) Render() react.Element ", "output": "{\n\treturn react.Div(nil,\n\t\treact.S(\"Hello \"+r.Props().Name),\n\t)\n}"} {"input": "package rfc\n\n\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/util\"\n)\n\ntype extDuplicateExtension struct{}\n\n\n\nfunc init() {\n\tlint.RegisterLint(&lint.Lint{\n\t\tName: \"e_ext_duplicate_extension\",\n\t\tDescription: \"A certificate MUST NOT include more than one instance of a particular extension\",\n\t\tCitation: \"RFC 5280: 4.2\",\n\t\tSource: lint.RFC5280,\n\t\tEffectiveDate: util.RFC2459Date,\n\t\tLint: &extDuplicateExtension{},\n\t})\n}\n\nfunc (l *extDuplicateExtension) Initialize() error {\n\treturn nil\n}\n\n\n\nfunc (l *extDuplicateExtension) Execute(cert *x509.Certificate) *lint.LintResult {\n\textensionOIDs := make(map[string]bool)\n\tduplicateOIDs := make(map[string]bool)\n\n\tfor _, ext := range cert.Extensions {\n\t\toid := ext.Id.String()\n\n\t\tif alreadySeen := extensionOIDs[oid]; alreadySeen {\n\t\t\tduplicateOIDs[oid] = true\n\t\t} else {\n\t\t\textensionOIDs[oid] = true\n\t\t}\n\t}\n\n\tif len(duplicateOIDs) == 0 {\n\t\treturn &lint.LintResult{Status: lint.Pass}\n\t}\n\n\tvar duplicateOIDsList []string\n\tfor oid := range duplicateOIDs {\n\t\tduplicateOIDsList = append(duplicateOIDsList, oid)\n\t}\n\n\treturn &lint.LintResult{\n\t\tStatus: lint.Error,\n\t\tDetails: fmt.Sprintf(\n\t\t\t\"The following extensions are duplicated: %s\",\n\t\t\tstrings.Join(duplicateOIDsList, \", \")),\n\t}\n}\n\nfunc (l *extDuplicateExtension) CheckApplies(cert *x509.Certificate) bool ", "output": "{\n\treturn cert.Version == 3\n}"} {"input": "package controllersProblem\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t_ \"github.com/wheatandcat/dotstamp_server/routers\"\n\t\"github.com/wheatandcat/dotstamp_server/tests\"\n\n\t\"github.com/astaxie/beego\"\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestAddPost(t *testing.T) {\n\tsetUpAdd()\n\n\tjson := `{\n\t\t\"id\":1,\n\t\t\"type\":1\n\t}`\n\n\tr, err := http.NewRequest(\n\t\t\"POST\",\n\t\t\"/api/problem/\",\n\t\tbytes.NewBuffer([]byte(json)),\n\t)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tr.Header.Set(\"Content-Type\", \"application/json\")\n\n\tw := httptest.NewRecorder()\n\tbeego.BeeApp.Handlers.ServeHTTP(w, r)\n\n\tConvey(\"/problem/\\n\", t, func() {\n\t\tConvey(\"Status Code Should Be 200\", func() {\n\t\t\tSo(w.Code, ShouldEqual, 200)\n\t\t})\n\t\tConvey(\"The Result Should Not Be Empty\", func() {\n\t\t\tSo(w.Body.Len(), ShouldBeGreaterThan, 0)\n\t\t})\n\t})\n}\n\nfunc setUpAdd() ", "output": "{\n\ttest.Setup()\n\ttest.SetupFixture([]string{\n\t\t\"log_problem_contribution_reports\",\n\t})\n}"} {"input": "package ui\n\nimport (\n\t\"github.com/Bredgren/geo\"\n\t\"github.com/hajimehoshi/ebiten\"\n)\n\n\n\n\ntype VerticalContainer struct {\n\tElements []WeightedDrawer\n\tWt float64\n}\n\n\nfunc (v *VerticalContainer) Draw(dst *ebiten.Image, bounds geo.Rect) {\n\ttotalWeight := 0.0\n\tfor _, e := range v.Elements {\n\t\ttotalWeight += e.Weight()\n\t}\n\theights := make([]float64, len(v.Elements))\n\tfor i, e := range v.Elements {\n\t\theights[i] = e.Weight() / totalWeight * bounds.H\n\t}\n\tsubBounds := bounds\n\tfor i, h := range heights {\n\t\tsubBounds.H = h\n\t\tv.Elements[i].Draw(dst, subBounds)\n\t\tsubBounds.Y += h\n\t}\n}\n\n\n\n\n\n\n\ntype HorizontalContainer struct {\n\tElements []WeightedDrawer\n\tWt float64\n}\n\n\nfunc (h *HorizontalContainer) Draw(dst *ebiten.Image, bounds geo.Rect) {\n\ttotalWeight := 0.0\n\tfor _, e := range h.Elements {\n\t\ttotalWeight += e.Weight()\n\t}\n\twidths := make([]float64, len(h.Elements))\n\tfor i, e := range h.Elements {\n\t\twidths[i] = e.Weight() / totalWeight * bounds.W\n\t}\n\tsubBounds := bounds\n\tfor i, w := range widths {\n\t\tsubBounds.W = w\n\t\th.Elements[i].Draw(dst, subBounds)\n\t\tsubBounds.X += w\n\t}\n}\n\n\nfunc (h *HorizontalContainer) Weight() float64 {\n\treturn h.Wt\n}\n\nfunc (v *VerticalContainer) Weight() float64 ", "output": "{\n\treturn v.Wt\n}"} {"input": "package main\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n)\n\n\n\ntype yesNo bool\n\n\n\n\nvar _ sql.Scanner = (*yesNo)(nil)\n\n\ntype table struct {\n\tTableCatalog string `reform:\"table_catalog\"`\n\tTableSchema string `reform:\"table_schema\"`\n\tTableName string `reform:\"table_name\"`\n\tTableType string `reform:\"table_type\"`\n}\n\n\ntype column struct {\n\tTableCatalog string `reform:\"table_catalog\"`\n\tTableSchema string `reform:\"table_schema\"`\n\tTableName string `reform:\"table_name\"`\n\tName string `reform:\"column_name\"`\n\tIsNullable yesNo `reform:\"is_nullable\"`\n\tType string `reform:\"data_type\"`\n}\n\n\ntype keyColumnUsage struct {\n\tColumnName string `reform:\"column_name\"`\n\tOrdinalPosition int `reform:\"ordinal_position\"`\n}\n\n\ntype sqliteMaster struct {\n\tName string `reform:\"name\"`\n}\n\n\n\n\ntype sqliteTableInfo struct {\n\tCID int `reform:\"cid\"`\n\tName string `reform:\"name\"`\n\tType string `reform:\"type\"`\n\tNotNull bool `reform:\"notnull\"`\n\tDefaultValue *string `reform:\"dflt_value\"`\n\tPK bool `reform:\"pk\"`\n}\n\nfunc (yn *yesNo) Scan(src interface{}) error ", "output": "{\n\tvar str string\n\tswitch s := src.(type) {\n\tcase string:\n\t\tstr = s\n\tcase []byte:\n\t\tstr = string(s)\n\tdefault:\n\t\treturn fmt.Errorf(\"unexpected type %T (%#v)\", src, src)\n\t}\n\n\tswitch str {\n\tcase \"YES\":\n\t\t*yn = true\n\tcase \"NO\":\n\t\t*yn = false\n\tdefault:\n\t\treturn fmt.Errorf(\"unexpected %q\", str)\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\n\t\"mvdan.cc/fdroidcl/fdroid\"\n)\n\nvar cmdDownload = &Command{\n\tUsageLine: \"download \",\n\tShort: \"Download an app\",\n}\n\n\n\nfunc runDownload(args []string) error {\n\tif len(args) < 1 {\n\t\treturn fmt.Errorf(\"no package names given\")\n\t}\n\tapps, err := findApps(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdevice, _ := maybeOneDevice()\n\tfor _, app := range apps {\n\t\tapk := app.SuggestedApk(device)\n\t\tif apk == nil {\n\t\t\treturn fmt.Errorf(\"no suggested APK found for %s\", app.PackageName)\n\t\t}\n\t\tpath, err := downloadApk(apk)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"APK available in %s\\n\", path)\n\t}\n\treturn nil\n}\n\nfunc downloadApk(apk *fdroid.Apk) (string, error) {\n\turl := apk.URL()\n\tpath := apkPath(apk.ApkName)\n\tif err := downloadEtag(url, path, apk.Hash); err == errNotModified {\n\t} else if err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not download %s: %v\", apk.AppID, err)\n\t}\n\treturn path, nil\n}\n\nfunc apkPath(apkname string) string {\n\tapksDir := subdir(mustCache(), \"apks\")\n\treturn filepath.Join(apksDir, apkname)\n}\n\nfunc init() ", "output": "{\n\tcmdDownload.Run = runDownload\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\n\t\"mvdan.cc/fdroidcl/fdroid\"\n)\n\nvar cmdDownload = &Command{\n\tUsageLine: \"download \",\n\tShort: \"Download an app\",\n}\n\nfunc init() {\n\tcmdDownload.Run = runDownload\n}\n\nfunc runDownload(args []string) error {\n\tif len(args) < 1 {\n\t\treturn fmt.Errorf(\"no package names given\")\n\t}\n\tapps, err := findApps(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdevice, _ := maybeOneDevice()\n\tfor _, app := range apps {\n\t\tapk := app.SuggestedApk(device)\n\t\tif apk == nil {\n\t\t\treturn fmt.Errorf(\"no suggested APK found for %s\", app.PackageName)\n\t\t}\n\t\tpath, err := downloadApk(apk)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"APK available in %s\\n\", path)\n\t}\n\treturn nil\n}\n\nfunc downloadApk(apk *fdroid.Apk) (string, error) {\n\turl := apk.URL()\n\tpath := apkPath(apk.ApkName)\n\tif err := downloadEtag(url, path, apk.Hash); err == errNotModified {\n\t} else if err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not download %s: %v\", apk.AppID, err)\n\t}\n\treturn path, nil\n}\n\n\n\nfunc apkPath(apkname string) string ", "output": "{\n\tapksDir := subdir(mustCache(), \"apks\")\n\treturn filepath.Join(apksDir, apkname)\n}"} {"input": "package removeDuplicates\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc Test_removeDuplicates(t *testing.T) ", "output": "{\n\tvar cases = []struct {\n\t\traw []int\n\t\tnLen int\n\t}{\n\t\t{\n\t\t\t[]int{1, 2, 2},\n\t\t\t2,\n\t\t},\n\t}\n\tfor _, c := range cases {\n\t\tnLen, err := removeDuplicates(c.nLen)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Error removing duplicates: %v\\n\", err)\n\t\t}\n\t\tif nLen != c.nLen {\n\t\t\tt.Errorf(\"Lengths do not match - got %v want: %v\\n\", nLen, c.nLen)\n\t\t}\n\t}\n}"} {"input": "package logutils\n\nimport (\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype MockLog struct {\n\tmock.Mock\n}\n\nfunc NewMockLog() *MockLog {\n\treturn &MockLog{}\n}\n\nfunc (m *MockLog) Fatalf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\n\n\nfunc (m *MockLog) Errorf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Warnf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Infof(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Child(name string) Log {\n\tm.Called(name)\n\treturn m\n}\n\nfunc (m *MockLog) SetLevel(level LogLevel) {\n\tm.Called(level)\n}\n\nfunc (m *MockLog) Panicf(format string, args ...interface{}) ", "output": "{\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}"} {"input": "package main\n\nimport (\n\t\"database/sql\"\n\t\"log\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/codahale/hdrhistogram\"\n)\n\nconst (\n\tminLatency = 100 * time.Microsecond\n\tmaxLatency = 100 * time.Second\n)\n\n\nvar numOps uint64\n\ntype worker struct {\n\tdb *sql.DB\n\tlatency struct {\n\t\tsync.Mutex\n\t\t*hdrhistogram.WindowedHistogram\n\t}\n}\n\n\n\nfunc newWorker(db *sql.DB, wg *sync.WaitGroup) *worker {\n\twg.Add(1)\n\tw := &worker{db: db}\n\tw.latency.WindowedHistogram = hdrhistogram.NewWindowed(1,\n\t\tminLatency.Nanoseconds(), maxLatency.Nanoseconds(), 1)\n\n\treturn w\n}\n\nfunc (w *worker) run(wg *sync.WaitGroup) {\n\tfor {\n\t\tstart := time.Now()\n\n\n\t\tif _, err := w.db.Exec(*query); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\telapsed := clampLatency(time.Since(start), minLatency, maxLatency).Nanoseconds()\n\t\tw.latency.Lock()\n\t\tif err := w.latency.Current.RecordValue(elapsed); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tw.latency.Unlock()\n\n\t\tatomic.AddUint64(&numOps, 1)\n\t}\n}\n\nfunc clampLatency(d, min, max time.Duration) time.Duration ", "output": "{\n\tif d < min {\n\t\treturn min\n\t}\n\tif d > max {\n\t\treturn max\n\t}\n\treturn d\n}"} {"input": "package labassistant\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc make_ob() *Observation {\n\treturn &Observation{}\n}\n\nfunc good_func(i int) int {\n\treturn i\n}\n\nfunc panic_func(i int) int {\n\tpanic(\"panic\")\n}\n\nfunc bad_func(i int) int {\n\treturn i + 1\n}\n\n\n\nfunc TestObservationRunSetsValues(t *testing.T) {\n\ta := assert.New(t)\n\tgood := make_ob()\n\tgood.run(good_func, 1)\n\ta.Equal(\"github.com/lmas/labassistant.good_func\", good.Name)\n\ta.Empty(good.Panic)\n\ta.Equal([]interface{}{1}, good.Outputs)\n\ta.NotEmpty(good.Start)\n\ta.NotZero(good.Duration)\n\n\tbad := make_ob()\n\tbad.can_panic = true\n\ta.NotPanics(func() {\n\t\tbad.run(panic_func, 1)\n\t})\n\ta.Equal(\"panic\", bad.Panic)\n\ta.Empty(bad.Outputs)\n\ta.NotEmpty(bad.Start)\n\ta.Zero(bad.Duration)\n}\n\nfunc TestObservationRunIsOK(t *testing.T) ", "output": "{\n\ta := assert.New(t)\n\tout := make_ob().run(good_func, 1)\n\ta.Equal([]interface{}{1}, out)\n\n\tout = make_ob().run(good_func, 0)\n\ta.NotEqual([]interface{}{1}, out)\n\n\ta.Panics(func() {\n\t\tmake_ob().run(good_func)\n\t})\n\n\ta.Panics(func() {\n\t\tmake_ob().run(good_func, 1, 1)\n\t})\n\n\ta.Panics(func() {\n\t\tmake_ob().run(good_func, \"string\")\n\t})\n}"} {"input": "package tcpproxy\n\n\n\ntype Process struct{\n\tPid int\n\tPidFile string\n}\n\n\n\nfunc(p *Process) storePidToFile() error{\n\n\treturn nil\n}\n\nfunc(p *Process) getPidFromFile() int{\n\n\treturn nil\n}\n\nfunc(p *Process) kill() error", "output": "{\n\n\treturn nil\n}"} {"input": "package misc\n\nimport \"jvmgo/ch11/native\"\nimport \"jvmgo/ch11/rtda\"\n\n\n\n\n\nfunc getLookupCacheURLs(frame *rtda.Frame) {\n\tframe.OperandStack().PushRef(nil)\n}\n\nfunc init() ", "output": "{\n\tnative.Register(\"sun/misc/URLClassPath\", \"getLookupCacheURLs\", \"(Ljava/lang/ClassLoader;)[Ljava/net/URL;\", getLookupCacheURLs)\n}"} {"input": "package screepsws\n\nimport \"fmt\"\n\nfunc (ws *webSocket) SubscribeRoom(shard, room string) (<-chan RoomResponse, error) {\n\tchannel := fmt.Sprintf(roomFormat, shard, room)\n\tdataChan, err := ws.Subscribe(channel)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to subscribe to '%s'\", channel)\n\t}\n\n\trespChan := make(chan RoomResponse)\n\tgo func() {\n\t\tdefer close(respChan)\n\t\tfor data := range dataChan {\n\t\t\tresp := RoomResponse{}\n\t\t\tclosed := UnmarshalResponse(data, &resp)\n\t\t\tif closed {\n\t\t\t\treturn\n\t\t\t}\n\t\t\trespChan <- resp\n\t\t}\n\t}()\n\n\treturn respChan, nil\n}\n\nfunc (ws *webSocket) UnsubscribeRoom(shard, room string) error {\n\treturn ws.Unsubscribe(fmt.Sprintf(roomFormat, shard, room))\n}\n\nfunc (ws *webSocket) SubscribeRoomMap(shard, room string) (<-chan RoomMapResponse, error) {\n\tchannel := fmt.Sprintf(roomMapFormat, shard, room)\n\tdataChan, err := ws.Subscribe(channel)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to subscribe to '%s'\", channel)\n\t}\n\n\trespChan := make(chan RoomMapResponse)\n\tgo func() {\n\t\tdefer close(respChan)\n\t\tfor data := range dataChan {\n\t\t\tresp := RoomMapResponse{}\n\t\t\tclosed := UnmarshalResponse(data, &resp)\n\t\t\tif closed {\n\t\t\t\treturn\n\t\t\t}\n\t\t\trespChan <- resp\n\t\t}\n\t}()\n\n\treturn respChan, nil\n}\n\n\n\nfunc (ws *webSocket) UnsubscribeRoomMap(shard, room string) error ", "output": "{\n\treturn ws.Unsubscribe(fmt.Sprintf(roomMapFormat, shard, room))\n}"} {"input": "package util\n\nconst (\n\tDefaultPerPage = 20\n)\n\n\n\n\n\n\n\nfunc (p *Pagination) Page(total int64) (from int64, to int64) {\n\tif p.CurPage == 0 {\n\t\tp.CurPage = 1\n\t}\n\tif p.PerPage == 0 {\n\t\tp.PerPage = DefaultPerPage\n\t}\n\n\tif total == 0 || total < p.PerPage*(p.CurPage-1) {\n\t\treturn\n\t}\n\tif total <= p.PerPage {\n\t\treturn 1, total\n\t}\n\tfrom = (p.CurPage-1)*p.PerPage + 1\n\tif (total - from + 1) < p.PerPage {\n\t\treturn from, total\n\t}\n\treturn from, from + p.PerPage - 1\n}\n\n\nfunc (p *Pagination) VagueOffsetLimit() (offset int64, limit int64) {\n\tfrom, to := p.SimplePage()\n\tif to == 0 || from == 0 {\n\t\treturn 0, 0\n\t}\n\treturn from - 1, to - from + 1\n}\n\n\nfunc (p *Pagination) OffsetLimit(total int64) (offset int64, limit int64) {\n\tfrom, to := p.Page(total)\n\tif to == 0 || from == 0 {\n\t\treturn 0, 0\n\t}\n\treturn from - 1, to - from + 1\n}\n\n\ntype Pagination struct {\n\tCurPage int64\n\tPerPage int64\n}\n\nfunc (p *Pagination) SimplePage() (from int64, to int64) ", "output": "{\n\tif p.CurPage == 0 || p.PerPage == 0 {\n\t\tp.CurPage, p.PerPage = 1, DefaultPerPage\n\t}\n\tfrom = (p.CurPage-1)*p.PerPage + 1\n\tto = from + p.PerPage - 1\n\treturn\n}"} {"input": "package gexec\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/atlassian/git-lob/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n)\n\n\nfunc Exit(optionalExitCode ...int) *exitMatcher {\n\texitCode := -1\n\tif len(optionalExitCode) > 0 {\n\t\texitCode = optionalExitCode[0]\n\t}\n\n\treturn &exitMatcher{\n\t\texitCode: exitCode,\n\t}\n}\n\ntype exitMatcher struct {\n\texitCode int\n\tdidExit bool\n\tactualExitCode int\n}\n\ntype Exiter interface {\n\tExitCode() int\n}\n\nfunc (m *exitMatcher) Match(actual interface{}) (success bool, err error) {\n\texiter, ok := actual.(Exiter)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"Exit must be passed a gexec.Exiter (Missing method ExitCode() int) Got:\\n%s\", format.Object(actual, 1))\n\t}\n\n\tm.actualExitCode = exiter.ExitCode()\n\n\tif m.actualExitCode == -1 {\n\t\treturn false, nil\n\t}\n\n\tif m.exitCode == -1 {\n\t\treturn true, nil\n\t}\n\treturn m.exitCode == m.actualExitCode, nil\n}\n\nfunc (m *exitMatcher) FailureMessage(actual interface{}) (message string) {\n\tif m.actualExitCode == -1 {\n\t\treturn \"Expected process to exit. It did not.\"\n\t} else {\n\t\treturn format.Message(m.actualExitCode, \"to match exit code:\", m.exitCode)\n\t}\n}\n\n\n\nfunc (m *exitMatcher) MatchMayChangeInTheFuture(actual interface{}) bool {\n\tsession, ok := actual.(*Session)\n\tif ok {\n\t\treturn session.ExitCode() == -1\n\t}\n\treturn true\n}\n\nfunc (m *exitMatcher) NegatedFailureMessage(actual interface{}) (message string) ", "output": "{\n\tif m.actualExitCode == -1 {\n\t\treturn \"you really shouldn't be able to see this!\"\n\t} else {\n\t\tif m.exitCode == -1 {\n\t\t\treturn \"Expected process not to exit. It did.\"\n\t\t} else {\n\t\t\treturn format.Message(m.actualExitCode, \"not to match exit code:\", m.exitCode)\n\t\t}\n\t}\n}"} {"input": "package itertools\n\nimport (\n\t\"reflect\"\n)\n\ntype Pair struct {\n\tFirst interface{}\n\tSecond interface{}\n}\n\n\n\nfunc PairUnPack(pair Pair, first, second interface{}) {\n\tunpack(pair.First, first)\n\tunpack(pair.Second, second)\n}\n\nfunc unpack(pairVal, ptr interface{}) ", "output": "{\n\tptrVal := reflect.ValueOf(ptr)\n\tptrElem := ptrVal.Elem()\n\tptrElem.Set(reflect.ValueOf(pairVal))\n\tptr = ptrElem.Interface()\n}"} {"input": "package qemu\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"sync\"\n)\n\nfunc restoreTerminal() error {\n\tcmd := exec.Command(\"stty\", \"sane\")\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}\n\ntype VM struct {\n\tCPU, Kernel, Workspace string\n}\n\nfunc (v *VM) qemu() string {\n\treturn fmt.Sprintf(\"qemu-system-%s\", v.CPU)\n}\n\nfunc (v *VM) Monitor(ctx context.Context) error {\n\tcmd := exec.CommandContext(ctx, v.qemu(), \"-kernel\", v.Kernel, \"-monitor\", \"stdio\")\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}\n\n\n\nfunc (v *VM) GDB(ctx context.Context) error {\n\n\tqemu := exec.CommandContext(ctx, v.qemu(), \"-kernel\", v.Kernel, \"-S\", \"-s\", \"--no-reboot\", \"-nographic\")\n\tif err := qemu.Start(); err != nil {\n\t\treturn err\n\t}\n\tdefer qemu.Wait()\n\tdefer qemu.Process.Kill()\n\n\tgdb := exec.CommandContext(ctx, \"gdb\", \"-q\",\n\t\t\"-d\", v.Workspace,\n\t\t\"-ex\", fmt.Sprintf(\"file %s\", v.Kernel),\n\t\t\"-ex\", \"target remote :1234\",\n\t\t\"-ex\", \"layout split\",\n\t)\n\tgdb.Stdin = os.Stdin\n\tgdb.Stdout = os.Stdout\n\tgdb.Stderr = os.Stderr\n\tdefer restoreTerminal()\n\treturn gdb.Run()\n}\n\nfunc (v *VM) Serial(ctx context.Context) ([]byte, error) ", "output": "{\n\tcmd := exec.CommandContext(ctx, v.qemu(), \"-kernel\", v.Kernel, \"-nographic\", \"--no-reboot\")\n\n\tcmdReader, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar output bytes.Buffer\n\tscanner := bufio.NewScanner(cmdReader)\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tfor scanner.Scan() {\n\t\t\toutput.Write(scanner.Bytes())\n\t\t\toutput.WriteByte('\\n')\n\t\t\tlog.Print(fmt.Sprintf(\"%q\", scanner.Text()))\n\t\t}\n\t\twg.Done()\n\t}()\n\n\tvar stderr bytes.Buffer\n\tcmd.Stderr = &stderr\n\n\terr = cmd.Run()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to run QEMU: %w:\\n%v\", err, stderr.String())\n\t}\n\twg.Wait()\n\treturn output.Bytes(), err\n}"} {"input": "package rest\n\nimport \"net/http\"\n\ntype StaticResource struct {\n\tResourceBase\n\tresult *Result\n\tself Link\n}\n\nfunc NewStaticResource(result *Result, self Link) Resource {\n\treturn &StaticResource{\n\t\tresult: result,\n\t\tself: self,\n\t}\n}\n\n\n\nfunc (r StaticResource) Get(request *http.Request) (interface{}, error) {\n\treturn r.result, nil\n}\n\nfunc (r StaticResource) Self() Link {\n\treturn r.self\n}\n\nfunc StaticContent(content []byte, contentType string, selfHref string) Resource ", "output": "{\n\treturn NewStaticResource(\n\t\tOk().AddHeader(\"Content-Type\", contentType).WithBody(content),\n\t\tSimpleLink(selfHref),\n\t)\n}"} {"input": "package cli\n\nimport \"errors\"\nimport \"fmt\"\nimport \"strconv\"\n\nfunc IsArgExist(args []string, s string)(bool) {\n pos, err := getArgPos(args, s)\n if nil == err && pos > 0 {\n return true\n }\n\n return false\n}\n\nfunc GetArgBool(args []string, s string)(bool) {\n pos, err := getArgPos(args, s)\n if nil == err && pos > 0 {\n return true\n }\n\n return false\n}\n\n\n\nfunc GetArgInts(args []string, s string)([]int, error) {\n pos, err := getArgPos(args, s)\n if err != nil || pos <= 0{\n return nil, err\n }\n if pos + 1 >= len(args) {\n return nil, errors.New(fmt.Sprintf(\"no number fllows '%s'\", s))\n }\n var list []int\n for i := pos + 1; i < len(args); i++ {\n if On == argmp[args[i]] {\n break\n }\n n, err := strconv.Atoi(args[i])\n if nil == err {\n list = append(list, n)\n } else {\n break\n }\n }\n if len(list) < 1 {\n return nil, errors.New(fmt.Sprintf(\"no number fllows '%s'\", s))\n }\n\n return list, nil\n}\n\nfunc GetArgInt(args []string, s string)(int, error) ", "output": "{\n \n pos, err := getArgPos(args, s)\n if nil != err || pos <= 0{\n return pos, err\n }\n\n \n if pos + 1 >= len(args) {\n return 0, errors.New(fmt.Sprintf(\"no number fallows '%s'\", s))\n }\n\n \n a := args[pos + 1]\n if regd == true && On != RegArgsStat(a) {\n return 0, errors.New(fmt.Sprintf(\"no number fallows '%s'\", s))\n }\n\n return strconv.Atoi(a)\n}"} {"input": "package task\n\nimport (\n\t\"context\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/docker/docker/api/types/swarm\"\n\t\"github.com/docker/docker/client\"\n)\n\ntype fakeClient struct {\n\tclient.APIClient\n\tnodeInspectWithRaw func(ref string) (swarm.Node, []byte, error)\n\tserviceInspectWithRaw func(ref string, options types.ServiceInspectOptions) (swarm.Service, []byte, error)\n}\n\n\n\nfunc (cli *fakeClient) ServiceInspectWithRaw(ctx context.Context, ref string, options types.ServiceInspectOptions) (swarm.Service, []byte, error) {\n\tif cli.serviceInspectWithRaw != nil {\n\t\treturn cli.serviceInspectWithRaw(ref, options)\n\t}\n\treturn swarm.Service{}, nil, nil\n}\n\nfunc (cli *fakeClient) NodeInspectWithRaw(ctx context.Context, ref string) (swarm.Node, []byte, error) ", "output": "{\n\tif cli.nodeInspectWithRaw != nil {\n\t\treturn cli.nodeInspectWithRaw(ref)\n\t}\n\treturn swarm.Node{}, nil, nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/ginuerzh/gosocks5\"\n\t\"github.com/gorilla/websocket\"\n\t\"log\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype WSConn struct {\n\t*websocket.Conn\n\trb []byte\n}\n\nfunc NewWSConn(conn *websocket.Conn) *WSConn {\n\tc := &WSConn{\n\t\tConn: conn,\n\t}\n\n\treturn c\n}\n\nfunc (conn *WSConn) Read(b []byte) (n int, err error) {\n\tif len(conn.rb) == 0 {\n\t\t_, conn.rb, err = conn.ReadMessage()\n\t}\n\tn = copy(b, conn.rb)\n\tconn.rb = conn.rb[n:]\n\n\n\treturn\n}\n\nfunc (conn *WSConn) Write(b []byte) (n int, err error) {\n\terr = conn.WriteMessage(websocket.BinaryMessage, b)\n\tn = len(b)\n\n\treturn\n}\n\nfunc (conn *WSConn) SetDeadline(t time.Time) error {\n\tif err := conn.SetReadDeadline(t); err != nil {\n\t\treturn err\n\t}\n\treturn conn.SetWriteDeadline(t)\n}\n\ntype WSServer struct {\n\tAddr string\n}\n\nvar upgrader = websocket.Upgrader{\n\tReadBufferSize: 8192,\n\tWriteBufferSize: 8192,\n\tCheckOrigin: func(r *http.Request) bool { return true },\n}\n\nfunc (s *WSServer) handle(w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tc := gosocks5.ServerConn(NewWSConn(conn), serverConfig)\n\tsocks5Handle(c)\n}\n\n\n\nfunc (s *WSServer) ListenAndServe() error ", "output": "{\n\thttp.HandleFunc(\"/\", s.handle)\n\treturn http.ListenAndServe(s.Addr, nil)\n}"} {"input": "package instructions\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/bongo227/goory/types\"\n\n\t\"github.com/bongo227/goory/value\"\n)\n\n\ntype CondBr struct {\n\tblock value.Value\n\tname string\n\tcondition value.Value\n\ttrueBlock value.Value\n\tfalseBlock value.Value\n}\n\nfunc NewCondBr(block value.Value, name string, condition value.Value, trueBlock value.Value, falseBlock value.Value) *CondBr {\n\tif !condition.Type().Equal(types.NewBoolType()) {\n\t\tpanic(\"condition is not a bool type\")\n\t}\n\n\tif !trueBlock.Type().Equal(types.NewBlockType()) {\n\t\tpanic(\"trueBlock is not a block type\")\n\t}\n\n\tif !falseBlock.Type().Equal(types.NewBlockType()) {\n\t\tpanic(\"falseBlock is not a block type\")\n\t}\n\n\treturn &CondBr{block, name, condition, trueBlock, falseBlock}\n}\n\nfunc (i *CondBr) Block() value.Value {\n\treturn i.block\n}\n\nfunc (i *CondBr) IsTerminator() bool {\n\treturn true\n}\n\nfunc (i *CondBr) Type() types.Type {\n\treturn types.VOID\n}\n\nfunc (i *CondBr) Ident() string {\n\treturn \"%\" + i.name\n}\n\n\n\nfunc (i *CondBr) Llvm() string ", "output": "{\n\treturn fmt.Sprintf(\"br i1 %s, label %%%s, label %%%s\",\n\t\ti.condition.Ident(),\n\t\ti.trueBlock.Ident(),\n\t\ti.falseBlock.Ident())\n}"} {"input": "package misc\n\nimport (\n\t\"net/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\ntype Writer interface {\n\thttp.ResponseWriter\n\thttp.Hijacker\n}\n\n\n\nfunc ElapsedTime(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tnw := elapsedTimeResponseWriter{\n\t\tWriter: w.(Writer),\n\t\tTimestamp: time.Now().UnixNano(),\n\t\twritten: false,\n\t}\n\tnext(&nw, r)\n\n}\n\ntype elapsedTimeResponseWriter struct {\n\tWriter\n\tTimestamp int64\n\twritten bool\n}\n\n\nfunc (e *elapsedTimeResponseWriter) Write(data []byte) (int, error) {\n\tif e.written == false {\n\t\te.WriteHeader(http.StatusOK)\n\t}\n\treturn e.Writer.Write(data)\n}\n\nfunc (e *elapsedTimeResponseWriter) WriteHeader(status int) ", "output": "{\n\tif e.written == false {\n\t\te.written = true\n\t\te.Writer.Header().Set(\"Elapsed-Time\", strconv.FormatInt(time.Now().UnixNano()-e.Timestamp, 10)+\" ns\")\n\t}\n\te.Writer.WriteHeader(status)\n}"} {"input": "package platform\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestGCPFlag(t *testing.T) {\n\tc := &GcpClientConfig{}\n\n\tflags := c.GetFlagSet()\n\tcertLoc := \"/etc/root.cert.pem\"\n\t_ = flags.Parse([]string{\"--root-cert\", certLoc})\n\n\tif c.RootCACertFile != certLoc {\n\t\tt.Errorf(\"GCP Config Flag: wrong value. Expected %s, Actual %s\", certLoc, c.RootCACertFile)\n\t}\n}\n\nfunc TestGCPConfigDefaultValue(t *testing.T) ", "output": "{\n\tc := &GcpClientConfig{}\n\n\tflags := c.GetFlagSet()\n\t_ = flags.Parse([]string{})\n\n\tif c.RootCACertFile != flags.Lookup(\"root-cert\").DefValue {\n\t\tt.Errorf(\"GCP Default Config Flag: wrong default value. Expected %s, Actual %s\",\n\t\t\tflags.Lookup(\"root-cert\").DefValue, c.RootCACertFile)\n\t}\n}"} {"input": "package protoio\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\n\t\"github.com/gogo/protobuf/proto\"\n\n\t\"github.com/multiformats/go-varint\"\n)\n\ntype uvarintReader struct {\n\tr *bufio.Reader\n\tbuf []byte\n\tmaxSize int\n\tcloser io.Closer\n}\n\n\n\nfunc (ur *uvarintReader) ReadMsg(msg proto.Message) error {\n\tlength64, err := varint.ReadUvarint(ur.r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlength := int(length64)\n\tif length < 0 || length > ur.maxSize {\n\t\treturn io.ErrShortBuffer\n\t}\n\tif len(ur.buf) < length {\n\t\tur.buf = make([]byte, length)\n\t}\n\tbuf := ur.buf[:length]\n\tif _, err := io.ReadFull(ur.r, buf); err != nil {\n\t\treturn err\n\t}\n\treturn proto.Unmarshal(buf, msg)\n}\n\nfunc (ur *uvarintReader) Close() error {\n\tif ur.closer != nil {\n\t\treturn ur.closer.Close()\n\t}\n\treturn nil\n}\n\nfunc NewDelimitedReader(r io.Reader, maxSize int) ReadCloser ", "output": "{\n\tvar closer io.Closer\n\tif c, ok := r.(io.Closer); ok {\n\t\tcloser = c\n\t}\n\treturn &uvarintReader{bufio.NewReader(r), nil, maxSize, closer}\n}"} {"input": "package collector\n\nimport (\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\ntype conntrackCollector struct {\n\tcurrent *prometheus.Desc\n\tlimit *prometheus.Desc\n}\n\nfunc init() {\n\tFactories[\"conntrack\"] = NewConntrackCollector\n}\n\n\n\nfunc NewConntrackCollector() (Collector, error) {\n\treturn &conntrackCollector{\n\t\tcurrent: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(Namespace, \"\", \"nf_conntrack_entries\"),\n\t\t\t\"Number of currently allocated flow entries for connection tracking.\",\n\t\t\tnil, nil,\n\t\t),\n\t\tlimit: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(Namespace, \"\", \"nf_conntrack_entries_limit\"),\n\t\t\t\"Maximum size of connection tracking table.\",\n\t\t\tnil, nil,\n\t\t),\n\t}, nil\n}\n\n\n\nfunc (c *conntrackCollector) Update(ch chan<- prometheus.Metric) (err error) ", "output": "{\n\tvalue, err := readUintFromFile(procFilePath(\"sys/net/netfilter/nf_conntrack_count\"))\n\tif err != nil {\n\t\treturn nil\n\t}\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.current, prometheus.GaugeValue, float64(value))\n\n\tvalue, err = readUintFromFile(procFilePath(\"sys/net/netfilter/nf_conntrack_max\"))\n\tif err != nil {\n\t\treturn nil\n\t}\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.limit, prometheus.GaugeValue, float64(value))\n\n\treturn nil\n}"} {"input": "package rsets\n\nimport (\n\t. \"github.com/pingcap/check\"\n\t\"github.com/pingcap/tidb/expression\"\n\t\"github.com/pingcap/tidb/expression/expressions\"\n\t\"github.com/pingcap/tidb/field\"\n\t\"github.com/pingcap/tidb/model\"\n)\n\nvar _ = Suite(&testHelperSuite{})\n\ntype testHelperSuite struct {\n\tfields []*field.Field\n}\n\n\n\nfunc (s *testHelperSuite) TestGetAggFields(c *C) {\n\taggFields := GetAggFields(s.fields)\n\tc.Assert(aggFields, HasLen, 1)\n}\n\nfunc (s *testHelperSuite) TestHasAggFields(c *C) {\n\tok := HasAggFields(s.fields)\n\tc.Assert(ok, IsTrue)\n}\n\nfunc (s *testHelperSuite) SetUpSuite(c *C) ", "output": "{\n\tfldx := &field.Field{Expr: &expressions.Ident{CIStr: model.NewCIStr(\"name\")}, Name: \"a\"}\n\texpr, err := expressions.NewCall(\"count\", []expression.Expression{expressions.Value{Val: 1}}, false)\n\tc.Assert(err, IsNil)\n\tfldy := &field.Field{Expr: expr}\n\n\ts.fields = []*field.Field{fldx, fldy}\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\n\tv3 \"github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3\"\n\t\"github.com/rancher/rancher/pkg/ref\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc GetRuleID(groupID string, ruleName string) string {\n\treturn fmt.Sprintf(\"%s_%s\", groupID, ruleName)\n}\n\nfunc GetGroupID(namespace, name string) string {\n\treturn fmt.Sprintf(\"%s:%s\", namespace, name)\n}\n\nfunc GetAlertManagerSecretName(appName string) string {\n\treturn fmt.Sprintf(\"alertmanager-%s\", appName)\n}\n\nfunc GetAlertManagerDaemonsetName(appName string) string {\n\treturn fmt.Sprintf(\"alertmanager-%s\", appName)\n}\n\nfunc formatProjectDisplayName(projectDisplayName, projectID string) string {\n\treturn fmt.Sprintf(\"%s (ID: %s)\", projectDisplayName, projectID)\n}\n\nfunc formatClusterDisplayName(clusterDisplayName, clusterID string) string {\n\treturn fmt.Sprintf(\"%s (ID: %s)\", clusterDisplayName, clusterID)\n}\n\nfunc GetClusterDisplayName(clusterName string, clusterLister v3.ClusterLister) string {\n\tcluster, err := clusterLister.Get(\"\", clusterName)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to get cluster for %s: %v\", clusterName, err)\n\t\treturn clusterName\n\t}\n\n\treturn formatClusterDisplayName(cluster.Spec.DisplayName, clusterName)\n}\n\n\n\nfunc GetProjectDisplayName(projectID string, projectLister v3.ProjectLister) string ", "output": "{\n\tclusterName, projectName := ref.Parse(projectID)\n\tproject, err := projectLister.Get(clusterName, projectName)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to get project %s: %v\", projectID, err)\n\t\treturn projectID\n\t}\n\n\treturn formatProjectDisplayName(project.Spec.DisplayName, projectID)\n}"} {"input": "package runtime\n\nimport \"unsafe\"\n\n\n\n\n\n\nfunc atomicload(ptr *uint32) uint32 {\n\tnop()\n\treturn *ptr\n}\n\n\n\n\n\nfunc xadd64(ptr *uint64, delta int64) uint64 {\n\tfor {\n\t\told := *ptr\n\t\tif cas64(ptr, old, old+uint64(delta)) {\n\t\t\treturn old + uint64(delta)\n\t\t}\n\t}\n}\n\n\nfunc xchg64(ptr *uint64, new uint64) uint64 {\n\tfor {\n\t\told := *ptr\n\t\tif cas64(ptr, old, new) {\n\t\t\treturn old\n\t\t}\n\t}\n}\n\n\nfunc xadd(ptr *uint32, delta int32) uint32\n\n\nfunc xchg(ptr *uint32, new uint32) uint32\n\n\nfunc xchgp1(ptr unsafe.Pointer, new unsafe.Pointer) unsafe.Pointer\n\n\nfunc xchguintptr(ptr *uintptr, new uintptr) uintptr\n\n\nfunc atomicload64(ptr *uint64) uint64\n\n\nfunc atomicor8(ptr *uint8, val uint8)\n\n\nfunc cas64(ptr *uint64, old, new uint64) bool\n\n\nfunc atomicstore(ptr *uint32, val uint32)\n\n\nfunc atomicstore64(ptr *uint64, val uint64)\n\n\nfunc atomicstorep1(ptr unsafe.Pointer, val unsafe.Pointer)\n\nfunc atomicloadp(ptr unsafe.Pointer) unsafe.Pointer ", "output": "{\n\tnop()\n\treturn *(*unsafe.Pointer)(ptr)\n}"} {"input": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"strings\"\n)\n\ntype marshalerForTest struct {\n\tX string\n}\n\nfunc encode(str string) string {\n\tbuf := bytes.Buffer{}\n\tb64 := base64.NewEncoder(base64.StdEncoding, &buf)\n\tif _, err := b64.Write([]byte(str)); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := b64.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn buf.String()\n}\n\nfunc decode(str string) string {\n\tif len(str) == 0 {\n\t\treturn \"\"\n\t}\n\tb64 := base64.NewDecoder(base64.StdEncoding, strings.NewReader(str))\n\tbs := make([]byte, len(str))\n\tif n, err := b64.Read(bs); err != nil {\n\t\tpanic(err)\n\t} else {\n\t\tbs = bs[:n]\n\t}\n\treturn string(bs)\n}\n\nfunc (m marshalerForTest) MarshalJSON() ([]byte, error) {\n\treturn []byte(`\"MANUAL__` + encode(m.X) + `\"`), nil\n}\n\n\n\nvar _ json.Marshaler = marshalerForTest{}\nvar _ json.Unmarshaler = &marshalerForTest{}\n\ntype typeForTest struct {\n\tS string\n\tM marshalerForTest\n\tI int8\n}\n\nfunc (m *marshalerForTest) UnmarshalJSON(text []byte) error ", "output": "{\n\tm.X = decode(strings.TrimPrefix(strings.Trim(string(text), `\"`), \"MANUAL__\"))\n\treturn nil\n}"} {"input": "package redis\n\nimport (\n\t\"github.com/fagongzi/goetty\"\n)\n\ntype redisDecoder struct {\n}\n\n\nfunc NewRedisDecoder() goetty.Decoder {\n\treturn &redisDecoder{}\n}\n\n\n\n\ntype redisReplyDecoder struct {\n}\n\n\nfunc NewRedisReplyDecoder() goetty.Decoder {\n\treturn &redisReplyDecoder{}\n}\n\n\nfunc (decoder *redisReplyDecoder) Decode(in *goetty.ByteBuf) (bool, interface{}, error) {\n\tcomplete, cmd, err := readCommandReply(in)\n\tif err != nil {\n\t\treturn true, nil, err\n\t}\n\n\tif !complete {\n\t\treturn false, nil, nil\n\t}\n\n\treturn true, cmd, nil\n}\n\nfunc (decoder *redisDecoder) Decode(in *goetty.ByteBuf) (bool, interface{}, error) ", "output": "{\n\tcomplete, cmd, err := ReadCommand(in)\n\tif err != nil {\n\t\treturn true, nil, err\n\t}\n\n\tif !complete {\n\t\treturn false, nil, nil\n\t}\n\n\treturn true, cmd, nil\n}"} {"input": "package test\n\nimport \"io\"\n\n\ntype PlainReader struct {\n\tr io.Reader\n}\n\n\nfunc NewPlainReader(r io.Reader) *PlainReader {\n\treturn &PlainReader{r}\n}\n\n\nfunc (r *PlainReader) Read(p []byte) (int, error) {\n\treturn r.r.Read(p)\n}\n\n\n\n\ntype ErrorReader struct {\n\tn int\n}\n\n\n\n\n\nfunc (r *ErrorReader) Read(b []byte) (n int, err error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tif r.n == 0 {\n\t\treturn 0, ErrPlain\n\t}\n\tr.n--\n\tb[0] = '.'\n\treturn 1, nil\n}\n\n\n\n\ntype InfiniteReader struct{}\n\n\nfunc NewInfiniteReader() *InfiniteReader {\n\treturn &InfiniteReader{}\n}\n\n\nfunc (r *InfiniteReader) Read(b []byte) (n int, err error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tb[0] = '.'\n\treturn 1, nil\n}\n\n\n\n\ntype EmptyReader struct {\n}\n\n\nfunc NewEmptyReader() *EmptyReader {\n\treturn &EmptyReader{}\n}\n\n\nfunc (r *EmptyReader) Read(b []byte) (n int, err error) {\n\treturn 0, io.EOF\n}\n\nfunc NewErrorReader(n int) *ErrorReader ", "output": "{\n\treturn &ErrorReader{n}\n}"} {"input": "package client\n\nimport (\n\t\"github.com/go-openapi/runtime\"\n\thttptransport \"github.com/go-openapi/runtime/client\"\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/yamamoto-febc/sakuraio-api/gen/client\"\n)\n\n\nvar SakuraAPI = NewSakuraClient(nil)\n\n\nfunc NewSakuraClient(formats strfmt.Registry) SakuraAPIFuncs {\n\tif formats == nil {\n\t\tformats = strfmt.Default\n\t}\n\ttransport := httptransport.New(\"api.sakura.io\", \"/\", []string{\"https\"})\n\treturn NewSakuraAPI(transport, formats)\n}\n\n\n\n\n\ntype SakuraAPIClient struct {\n\tclient *client.SakuraIoT\n\tbasicAuthInfoWriter *runtime.ClientAuthInfoWriter\n}\n\nfunc NewSakuraAPI(transport runtime.ClientTransport, formats strfmt.Registry) SakuraAPIFuncs ", "output": "{\n\n\tcli := client.New(transport, formats)\n\tsakura := &SakuraAPIClient{\n\t\tclient: cli,\n\t}\n\treturn sakura\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc middlewareFirst(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"MiddlewareFirst - Before Handler\")\n\t\tnext.ServeHTTP(w, r)\n\t\tlog.Println(\"MiddlewareFirst- After Handler\")\n\t})\n}\n\nfunc middlewareSecond(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"MiddlewareSecond - Before Handler\")\n\t\tif r.URL.Path == \"/message\" {\n\t\t\tif r.URL.Query().Get(\"password\") == \"pass123\" {\n\t\t\t\tlog.Println(\"Authorized to the system\")\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t} else {\n\t\t\t\tlog.Println(\"Failed to authorize to the system\")\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t}\n\t\tlog.Println(\"MiddlewareSecond - After Handler\")\n\t})\n}\n\n\n\nfunc message(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Excuting message Handler\")\n\tfmt.Fprintf(w, \"HTTP Middleware is awesome\")\n}\n\nfunc iconHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.ServeFile(w, r, \"./favicon.ico\")\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/favicon.ico\", iconHandler)\n\n\thttp.Handle(\"/\", middlewareFirst(middlewareSecond(http.HandlerFunc(index))))\n\thttp.Handle(\"/message\", middlewareFirst(middlewareSecond(http.HandlerFunc(message))))\n\n\tserver := &http.Server{\n\t\tAddr: \":8080\",\n\t}\n\tlog.Println(\"Listening...\")\n\tserver.ListenAndServe()\n}\n\nfunc index(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tlog.Println(\"Executing index handler\")\n\tfmt.Fprintf(w, \"Welcome!\")\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/astaxie/beego/logs\"\n)\n\n\nfunc MyNewLogger(conf *Config, logFile string) *logs.BeeLogger {\n\treturn loggerInit(conf, logFile)\n}\n\n\n\nfunc loggerInit(conf *Config, logFile string) (log *logs.BeeLogger) ", "output": "{\n\tlog = logs.NewLogger(0)\n\tlog.EnableFuncCallDepth(true)\n\tlog.SetLevel(conf.Base.LogLevel)\n\tif conf.Base.LogDir == \"console\" {\n\t\t_ = log.SetLogger(\"console\")\n\t} else {\n\t\t_ = log.SetLogger(\n\t\t\t\"file\", fmt.Sprintf(\n\t\t\t\t`{\"filename\":\"%s\", \"level\":%d, \"maxlines\":0,\n\t\t\t\t\t\"maxsize\":0, \"daily\":false, \"maxdays\":0}`,\n\t\t\t\tlogFile, conf.Base.LogLevel))\n\t}\n\treturn\n}"} {"input": "package allocator\n\nimport (\n\t\"math/big\"\n\t\"testing\"\n)\n\nfunc TestBitCount(t *testing.T) {\n\tfor i, c := range bitCounts {\n\t\tactual := 0\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tif ((1 << uint(j)) & i) != 0 {\n\t\t\t\tactual++\n\t\t\t}\n\t\t}\n\t\tif actual != int(c) {\n\t\t\tt.Errorf(\"%d should have %d bits but recorded as %d\", i, actual, c)\n\t\t}\n\t}\n}\n\n\n\nfunc TestCountBits(t *testing.T) ", "output": "{\n\ttests := []struct {\n\t\tn *big.Int\n\t\texpected int\n\t}{\n\t\t{n: big.NewInt(int64(0)), expected: 0},\n\t\t{n: big.NewInt(int64(0xffffffffff)), expected: 40},\n\t}\n\tfor _, test := range tests {\n\t\tactual := countBits(test.n)\n\t\tif test.expected != actual {\n\t\t\tt.Errorf(\"%d should have %d bits but recorded as %d\", test.n, test.expected, actual)\n\t\t}\n\t}\n}"} {"input": "package activekit\n\n\n\nfunc ItemsFromIter(maxIndex uint, next func(index uint) *MenuItem) MenuItems ", "output": "{\n\tvar items = make(MenuItems, 0, maxIndex)\n\tfor i := uint(0); i < maxIndex; i++ {\n\t\tvar item = next(i)\n\t\tif item != nil {\n\t\t\titems = append(items, item)\n\t\t}\n\t}\n\treturn items\n}"} {"input": "package db\n\nimport (\n\t\"gopkg.in/mgo.v2\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Session struct {\n\tS *mgo.Session\n\tDb *mgo.Database\n\tC *mgo.Collection\n}\n\n\ntype MongoClient struct {\n\tHosts string\n\tDatabase string\n\tCollection string\n\tSession\n}\n\nfunc (m *MongoClient) Connect() error {\n\tdailinfo := &mgo.DialInfo{\n\t\tAddrs: strings.Split(m.Hosts, \",\"),\n\t\tTimeout: 5 * time.Second,\n\t\tDatabase: m.Database,\n\t}\n\tsession, err := mgo.DialWithInfo(dailinfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.S = session\n\tm.S.SetMode(mgo.Monotonic, true)\n\treturn nil\n}\n\n\n\nfunc (m *MongoClient) C() {\n\tc := m.Session.Db.C(m.Collection)\n\tm.Session.C = c\n}\n\nfunc (m *MongoClient) Close() {\n\tif m.S != nil {\n\t\tm.S.LogoutAll()\n\t\tm.S.Close()\n\t}\n}\n\nfunc (m *MongoClient) GetCollection() *mgo.Collection {\n\treturn m.Session.C\n}\n\nfunc (m *MongoClient) DB() ", "output": "{\n\tdb := m.Session.S.DB(m.Database)\n\tm.Session.Db = db\n}"} {"input": "package handlers\n\nimport \"github.com/netflix/rend/common\"\n\ntype HandlerConst func() (Handler, error)\n\n\n\n\n\n\ntype Handler interface {\n\tSet(cmd common.SetRequest) error\n\tAdd(cmd common.SetRequest) error\n\tReplace(cmd common.SetRequest) error\n\tAppend(cmd common.SetRequest) error\n\tPrepend(cmd common.SetRequest) error\n\tGet(cmd common.GetRequest) (<-chan common.GetResponse, <-chan error)\n\tGetE(cmd common.GetRequest) (<-chan common.GetEResponse, <-chan error)\n\tGAT(cmd common.GATRequest) (common.GetResponse, error)\n\tDelete(cmd common.DeleteRequest) error\n\tTouch(cmd common.TouchRequest) error\n\tClose() error\n}\n\nfunc NilHandler() (Handler, error) ", "output": "{ return nil, nil }"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CopyVolumeGroupBackupRequest struct {\n\n\tVolumeGroupBackupId *string `mandatory:\"true\" contributesTo:\"path\" name:\"volumeGroupBackupId\"`\n\n\tCopyVolumeGroupBackupDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CopyVolumeGroupBackupRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request CopyVolumeGroupBackupRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CopyVolumeGroupBackupRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CopyVolumeGroupBackupResponse struct {\n\n\tRawResponse *http.Response\n\n\tVolumeGroupBackup `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CopyVolumeGroupBackupResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CopyVolumeGroupBackupResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CopyVolumeGroupBackupRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package hashgraph\n\nimport (\n\t\"bytes\"\n\t\"sort\"\n\n\t\"github.com/mosaicnetworks/babble/src/crypto\"\n\t\"github.com/mosaicnetworks/babble/src/peers\"\n\t\"github.com/ugorji/go/codec\"\n)\n\n\ntype Frame struct {\n\tRound int \n\tPeers []*peers.Peer \n\tRoots map[string]*Root \n\tEvents []*FrameEvent \n\tPeerSets map[int][]*peers.Peer \n\tTimestamp int64 \n}\n\n\n\nfunc (f *Frame) SortedFrameEvents() []*FrameEvent {\n\tsorted := SortedFrameEvents{}\n\tfor _, r := range f.Roots {\n\t\tsorted = append(sorted, r.Events...)\n\t}\n\tsorted = append(sorted, f.Events...)\n\tsort.Sort(sorted)\n\treturn sorted\n}\n\n\n\n\n\nfunc (f *Frame) Unmarshal(data []byte) error {\n\tb := bytes.NewBuffer(data)\n\tjh := new(codec.JsonHandle)\n\tjh.Canonical = true\n\tdec := codec.NewDecoder(b, jh)\n\n\tif err := dec.Decode(f); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc (f *Frame) Hash() ([]byte, error) {\n\thashBytes, err := f.Marshal()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn crypto.SHA256(hashBytes), nil\n}\n\nfunc (f *Frame) Marshal() ([]byte, error) ", "output": "{\n\tb := new(bytes.Buffer)\n\tjh := new(codec.JsonHandle)\n\tjh.Canonical = true\n\tenc := codec.NewEncoder(b, jh)\n\n\tif err := enc.Encode(f); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b.Bytes(), nil\n}"} {"input": "package resources\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/rancher/rancher-compose-executor/project\"\n\t\"github.com/rancher/rancher-compose-executor/project/options\"\n)\n\n\n\ntype Dependencies struct {\n\tdependencies []*Dependency\n}\n\nfunc (h *Dependencies) Initialize(ctx context.Context, _ options.Options) error {\n\tfor _, dependency := range h.dependencies {\n\t\tif err := dependency.EnsureItExists(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\ntype Dependency struct {\n\tproject *project.Project\n\tname string\n\ttemplate string\n\tversion string\n}\n\nfunc (d *Dependency) EnsureItExists(ctx context.Context) error {\n\treturn nil\n}\n\nfunc DependenciesCreate(p *project.Project) (project.ResourceSet, error) ", "output": "{\n\tdependencies := make([]*Dependency, 0, len(p.Config.Dependencies))\n\tfor name, config := range p.Config.Dependencies {\n\t\tdependencies = append(dependencies, &Dependency{\n\t\t\tproject: p,\n\t\t\tname: name,\n\t\t\ttemplate: config.Template,\n\t\t\tversion: config.Version,\n\t\t})\n\t}\n\treturn &Dependencies{\n\t\tdependencies: dependencies,\n\t}, nil\n}"} {"input": "package udt\n\n\n\nimport (\n\t\"io\"\n)\n\ntype ack2Packet struct {\n\th header\n\tackSeqNo uint32 \n}\n\nfunc (p *ack2Packet) socketId() (sockId uint32) {\n\treturn p.h.dstSockId\n}\n\nfunc (p *ack2Packet) sendTime() (ts uint32) {\n\treturn p.h.ts\n}\n\nfunc (p *ack2Packet) writeTo(w io.Writer) (err error) {\n\tif err := p.h.writeTo(w, ack2, p.ackSeqNo); err != nil {\n\t\treturn err\n\t}\n\treturn\n}\n\n\n\nfunc (p *ack2Packet) readFrom(r io.Reader) (err error) ", "output": "{\n\tp.ackSeqNo, err = p.h.readFrom(r)\n\treturn\n}"} {"input": "package reconcile\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"k8s.io/apimachinery/pkg/types\"\n)\n\n\ntype Result struct {\n\tRequeue bool\n\n\tRequeueAfter time.Duration\n}\n\n\nfunc (r *Result) IsZero() bool {\n\tif r == nil {\n\t\treturn true\n\t}\n\treturn *r == Result{}\n}\n\n\n\n\ntype Request struct {\n\ttypes.NamespacedName\n}\n\n\ntype Reconciler interface {\n\tReconcile(context.Context, Request) (Result, error)\n}\n\n\ntype Func func(context.Context, Request) (Result, error)\n\nvar _ Reconciler = Func(nil)\n\n\n\n\nfunc (r Func) Reconcile(ctx context.Context, o Request) (Result, error) ", "output": "{ return r(ctx, o) }"} {"input": "package logging\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"strings\"\n)\n\ntype transport struct {\n\tname string\n\ttransport http.RoundTripper\n}\n\n\n\nfunc NewTransport(name string, t http.RoundTripper) *transport {\n\treturn &transport{name, t}\n}\n\n\n\nfunc prettyPrintJsonLines(b []byte) string {\n\tparts := strings.Split(string(b), \"\\n\")\n\tfor i, p := range parts {\n\t\tif b := []byte(p); json.Valid(b) {\n\t\t\tvar out bytes.Buffer\n\t\t\tjson.Indent(&out, b, \"\", \" \")\n\t\t\tparts[i] = out.String()\n\t\t}\n\t}\n\treturn strings.Join(parts, \"\\n\")\n}\n\nconst logReqMsg = `%s API Request Details:\n---[ REQUEST ]---------------------------------------\n%s\n-----------------------------------------------------`\n\nconst logRespMsg = `%s API Response Details:\n---[ RESPONSE ]--------------------------------------\n%s\n-----------------------------------------------------`\n\nfunc (t *transport) RoundTrip(req *http.Request) (*http.Response, error) ", "output": "{\n\tif IsDebugOrHigher() {\n\t\treqData, err := httputil.DumpRequestOut(req, true)\n\t\tif err == nil {\n\t\t\tlog.Printf(\"[DEBUG] \"+logReqMsg, t.name, prettyPrintJsonLines(reqData))\n\t\t} else {\n\t\t\tlog.Printf(\"[ERROR] %s API Request error: %#v\", t.name, err)\n\t\t}\n\t}\n\n\tresp, err := t.transport.RoundTrip(req)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\tif IsDebugOrHigher() {\n\t\trespData, err := httputil.DumpResponse(resp, true)\n\t\tif err == nil {\n\t\t\tlog.Printf(\"[DEBUG] \"+logRespMsg, t.name, prettyPrintJsonLines(respData))\n\t\t} else {\n\t\t\tlog.Printf(\"[ERROR] %s API Response error: %#v\", t.name, err)\n\t\t}\n\t}\n\n\treturn resp, nil\n}"} {"input": "package v1alpha1\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n)\n\n\n\nfunc SetDefaults_ClusterSpec(obj *ClusterSpec) {\n\tif obj.Topology == nil {\n\t\tobj.Topology = &TopologySpec{}\n\t}\n\n\tif obj.Topology.Masters == \"\" {\n\t\tobj.Topology.Masters = TopologyPublic\n\t}\n\n\tif obj.Topology.Nodes == \"\" {\n\t\tobj.Topology.Nodes = TopologyPublic\n\t}\n\n\tif obj.Topology.DNS == nil {\n\t\tobj.Topology.DNS = &DNSSpec{}\n\t}\n\n\tif obj.Topology.DNS.Type == \"\" {\n\t\tobj.Topology.DNS.Type = DNSTypePublic\n\t}\n\n\tif obj.API == nil {\n\t\tobj.API = &AccessSpec{}\n\t}\n\n\tif obj.API.IsEmpty() {\n\t\tswitch obj.Topology.Masters {\n\t\tcase TopologyPublic:\n\t\t\tobj.API.DNS = &DNSAccessSpec{}\n\n\t\tcase TopologyPrivate:\n\t\t\tobj.API.LoadBalancer = &LoadBalancerAccessSpec{}\n\n\t\tdefault:\n\t\t\tglog.Infof(\"unknown master topology type: %q\", obj.Topology.Masters)\n\t\t}\n\t}\n\n\tif obj.API.LoadBalancer != nil && obj.API.LoadBalancer.Type == \"\" {\n\t\tobj.API.LoadBalancer.Type = LoadBalancerTypePublic\n\t}\n}\n\nfunc addDefaultingFuncs(scheme *runtime.Scheme) error ", "output": "{\n\tRegisterDefaults(scheme)\n\treturn scheme.AddDefaultingFuncs(\n\t\tSetDefaults_ClusterSpec,\n\t)\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/client-go/applyconfigurations/meta/v1\"\n)\n\n\n\ntype TopologySpreadConstraintApplyConfiguration struct {\n\tMaxSkew *int32 `json:\"maxSkew,omitempty\"`\n\tTopologyKey *string `json:\"topologyKey,omitempty\"`\n\tWhenUnsatisfiable *v1.UnsatisfiableConstraintAction `json:\"whenUnsatisfiable,omitempty\"`\n\tLabelSelector *metav1.LabelSelectorApplyConfiguration `json:\"labelSelector,omitempty\"`\n}\n\n\n\nfunc TopologySpreadConstraint() *TopologySpreadConstraintApplyConfiguration {\n\treturn &TopologySpreadConstraintApplyConfiguration{}\n}\n\n\n\n\n\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithTopologyKey(value string) *TopologySpreadConstraintApplyConfiguration {\n\tb.TopologyKey = &value\n\treturn b\n}\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithWhenUnsatisfiable(value v1.UnsatisfiableConstraintAction) *TopologySpreadConstraintApplyConfiguration {\n\tb.WhenUnsatisfiable = &value\n\treturn b\n}\n\n\n\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithLabelSelector(value *metav1.LabelSelectorApplyConfiguration) *TopologySpreadConstraintApplyConfiguration {\n\tb.LabelSelector = value\n\treturn b\n}\n\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithMaxSkew(value int32) *TopologySpreadConstraintApplyConfiguration ", "output": "{\n\tb.MaxSkew = &value\n\treturn b\n}"} {"input": "package endpoint\n\nimport (\n\t\"fmt\"\n)\n\nconst (\n\t_PlaceholderCreationEncryptionPropertyName_0 = \"unspecifiedinherit\"\n\t_PlaceholderCreationEncryptionPropertyName_1 = \"off\"\n)\n\nvar (\n\t_PlaceholderCreationEncryptionPropertyIndex_0 = [...]uint8{0, 11, 18}\n\t_PlaceholderCreationEncryptionPropertyIndex_1 = [...]uint8{0, 3}\n)\n\nfunc (i PlaceholderCreationEncryptionProperty) String() string {\n\tswitch {\n\tcase 1 <= i && i <= 2:\n\t\ti -= 1\n\t\treturn _PlaceholderCreationEncryptionPropertyName_0[_PlaceholderCreationEncryptionPropertyIndex_0[i]:_PlaceholderCreationEncryptionPropertyIndex_0[i+1]]\n\tcase i == 4:\n\t\treturn _PlaceholderCreationEncryptionPropertyName_1\n\tdefault:\n\t\treturn fmt.Sprintf(\"PlaceholderCreationEncryptionProperty(%d)\", i)\n\t}\n}\n\nvar _PlaceholderCreationEncryptionPropertyValues = []PlaceholderCreationEncryptionProperty{1, 2, 4}\n\nvar _PlaceholderCreationEncryptionPropertyNameToValueMap = map[string]PlaceholderCreationEncryptionProperty{\n\t_PlaceholderCreationEncryptionPropertyName_0[0:11]: 1,\n\t_PlaceholderCreationEncryptionPropertyName_0[11:18]: 2,\n\t_PlaceholderCreationEncryptionPropertyName_1[0:3]: 4,\n}\n\n\n\nfunc PlaceholderCreationEncryptionPropertyString(s string) (PlaceholderCreationEncryptionProperty, error) {\n\tif val, ok := _PlaceholderCreationEncryptionPropertyNameToValueMap[s]; ok {\n\t\treturn val, nil\n\t}\n\treturn 0, fmt.Errorf(\"%s does not belong to PlaceholderCreationEncryptionProperty values\", s)\n}\n\n\nfunc PlaceholderCreationEncryptionPropertyValues() []PlaceholderCreationEncryptionProperty {\n\treturn _PlaceholderCreationEncryptionPropertyValues\n}\n\n\n\n\nfunc (i PlaceholderCreationEncryptionProperty) IsAPlaceholderCreationEncryptionProperty() bool ", "output": "{\n\tfor _, v := range _PlaceholderCreationEncryptionPropertyValues {\n\t\tif i == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package eventgrid\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) BaseClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package probe\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/FirebaseExtended/fcm-external-prober/Probe/src/utils\"\n)\n\nfunc TestFindDevice(t *testing.T) {\n\tmaker = utils.NewFakeCommandMaker([]string{\"TEST_DEVICE_1\\nTEST_DEVICE_2\\nTEST_DEVICE_3\"}, []bool{false}, false)\n\n\tstr, err := findDevice()\n\n\tif err != nil {\n\t\tt.Log(\"TestFindDevice: error on valid input\")\n\t\tt.Fail()\n\t}\n\tif str != \"TEST_DEVICE_1\" {\n\t\tt.Log(\"TestFindDevice: incorrect device found\")\n\t\tt.Fail()\n\t}\n}\n\n\n\nfunc TestConvertTimeError(t *testing.T) {\n\t_, err := convertTime(\"1.1.1.1\")\n\tif err == nil {\n\t\tt.Logf(\"TestConvertTimeExpected: no error returned on invalid input\")\n\t\tt.Fail()\n\t}\n}\n\nfunc TestFindTimeOffset(t *testing.T) {\n\tclock = utils.NewFakeClock([]time.Time{time.Unix(0, 0), time.Unix(1, 0)}, false)\n\tmaker = utils.NewFakeCommandMaker([]string{\"000.500000\"}, []bool{false}, false)\n\toffset, err := findTimeOffset()\n\tif err != nil {\n\t\tt.Logf(\"TestFindTimeOffset: error returned on valid input: %v\", err)\n\t\tt.FailNow()\n\t}\n\tif offset != 0 {\n\t\tt.Logf(\"TestFindTimeOffset: incorrect time offset: actual: %d, expected: 0\", offset)\n\t\tt.Fail()\n\t}\n}\n\nfunc TestConvertTimeExpected(t *testing.T) ", "output": "{\n\ttim, err := convertTime(\"123.456000\")\n\tif err != nil {\n\t\tt.Logf(\"TestConvertTimeExpected: returned error on valid input: %v\", err)\n\t\tt.FailNow()\n\t}\n\texpected := time.Unix(123, 456000000)\n\tif !tim.Equal(expected) {\n\t\tt.Logf(\"TestConvertTimeExpected: incorrect time returned: actual: %v, expected %v\", tim, expected)\n\t\tt.FailNow()\n\t}\n}"} {"input": "package denypassword\n\nimport (\n\t\"k8s.io/apiserver/pkg/authentication/authenticator\"\n\t\"k8s.io/apiserver/pkg/authentication/user\"\n)\n\n\ntype denyPasswordAuthenticator struct {\n}\n\n\n\n\n\nfunc (a denyPasswordAuthenticator) AuthenticatePassword(username, password string) (user.Info, bool, error) {\n\treturn nil, false, nil\n}\n\nfunc New() authenticator.Password ", "output": "{\n\treturn &denyPasswordAuthenticator{}\n}"} {"input": "package cpumanager\n\nimport (\n\t\"k8s.io/api/core/v1\"\n\t\"k8s.io/klog\"\n\t\"k8s.io/kubernetes/pkg/kubelet/cm/cpumanager/state\"\n\t\"k8s.io/kubernetes/pkg/kubelet/cm/topologymanager\"\n)\n\ntype nonePolicy struct{}\n\nvar _ Policy = &nonePolicy{}\n\n\nconst PolicyNone policyName = \"none\"\n\n\nfunc NewNonePolicy() Policy {\n\treturn &nonePolicy{}\n}\n\nfunc (p *nonePolicy) Name() string {\n\treturn string(PolicyNone)\n}\n\nfunc (p *nonePolicy) Start(s state.State) {\n\tklog.Info(\"[cpumanager] none policy: Start\")\n}\n\nfunc (p *nonePolicy) AddContainer(s state.State, pod *v1.Pod, container *v1.Container) error {\n\treturn nil\n}\n\n\n\nfunc (p *nonePolicy) GetTopologyHints(s state.State, pod v1.Pod, container v1.Container) map[string][]topologymanager.TopologyHint {\n\treturn nil\n}\n\nfunc (p *nonePolicy) RemoveContainer(s state.State, podUID string, containerName string) error ", "output": "{\n\treturn nil\n}"} {"input": "package xray\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"goa.design/goa/v3/middleware\"\n\t\"goa.design/goa/v3/middleware/xray\"\n)\n\n\n\ntype xrayTransport struct {\n\twrapped http.RoundTripper\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (t *xrayTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\tctx := req.Context()\n\tseg := ctx.Value(xray.SegKey)\n\tif seg == nil {\n\t\treturn t.wrapped.RoundTrip(req)\n\t}\n\n\ts := seg.(*xray.Segment)\n\tsub := s.NewSubsegment(req.URL.Host)\n\ths := &HTTPSegment{Segment: sub}\n\ths.RecordRequest(req, \"remote\")\n\ths.SubmitInProgress()\n\tdefer hs.Close()\n\n\tctx = middleware.WithSpan(ctx, hs.TraceID, hs.ID, hs.ParentID)\n\treq = req.WithContext(context.WithValue(ctx, xray.SegKey, hs.Segment))\n\tresp, err := t.wrapped.RoundTrip(req)\n\tif err != nil {\n\t\ths.RecordError(err)\n\t} else {\n\t\ths.RecordResponse(resp)\n\t}\n\treturn resp, err\n}\n\nfunc WrapTransport(rt http.RoundTripper) http.RoundTripper ", "output": "{\n\treturn &xrayTransport{rt}\n}"} {"input": "package league\n\ntype Division struct {\n\tname string\n\tteams map[string]*Team\n\tconfrence *Conference\n\tleague *League\n}\n\nfunc (division *Division) GetTeams() map[string]*Team {\n\treturn division.teams\n}\n\n\n\nfunc (division *Division) GetConference() *Conference {\n\treturn division.confrence\n}\n\nfunc (division *Division) getLeague() *League {\n\treturn division.league\n}\n\nfunc (division *Division) GetName() string ", "output": "{\n\treturn division.name\n}"} {"input": "package jobs\n\nimport (\n\t\"github.com/cleverua/tuna-timer-api/data\"\n\t\"github.com/cleverua/tuna-timer-api/utils\"\n\t\"gopkg.in/mgo.v2\"\n\t\"log\"\n\t\"time\"\n)\n\ntype StopTimersAtMidnight struct {\n\tenv *utils.Environment\n\tsession *mgo.Session\n}\n\nfunc NewStopTimersAtMidnight(env *utils.Environment, session *mgo.Session) *StopTimersAtMidnight {\n\treturn &StopTimersAtMidnight{\n\t\tenv: env,\n\t\tsession: session,\n\t}\n}\n\n\n\nfunc (j *StopTimersAtMidnight) Run() ", "output": "{\n\tlog.Println(\"ProlongTimersJob launched!\")\n\n\tnow := time.Now()\n\n\tservice := data.NewTimerService(j.session)\n\tservice.CompleteActiveTimersAtMidnight(&now)\n\n\tlog.Println(\"ProlongTimersJob finished!\")\n}"} {"input": "package gumble\n\nimport (\n\t\"github.com/unascribed/gumble/gumble/MumbleProto\"\n)\n\n\ntype RegisteredUser struct {\n\tUserID uint32\n\tName string\n\n\tchanged bool\n\tderegister bool\n}\n\n\nfunc (ru *RegisteredUser) SetName(name string) {\n\tru.Name = name\n\tru.changed = true\n}\n\n\nfunc (ru *RegisteredUser) Deregister() {\n\tru.deregister = true\n}\n\n\n\n\n\n\nfunc (ru *RegisteredUser) ACLUser() *ACLUser {\n\treturn &ACLUser{\n\t\tUserID: ru.UserID,\n\t\tName: ru.Name,\n\t}\n}\n\n\n\n\n\ntype RegisteredUsers []*RegisteredUser\n\nfunc (pm RegisteredUsers) writeMessage(client *Client) error {\n\tpacket := MumbleProto.UserList{}\n\n\tfor _, user := range pm {\n\t\tif user.deregister || user.changed {\n\t\t\tuserListUser := &MumbleProto.UserList_User{\n\t\t\t\tUserId: &user.UserID,\n\t\t\t}\n\t\t\tif !user.deregister {\n\t\t\t\tuserListUser.Name = &user.Name\n\t\t\t}\n\t\t\tpacket.Users = append(packet.Users, userListUser)\n\t\t}\n\t}\n\n\tif len(packet.Users) <= 0 {\n\t\treturn nil\n\t}\n\tproto := protoMessage{&packet}\n\treturn proto.writeMessage(client)\n}\n\nfunc (ru *RegisteredUser) Register() ", "output": "{\n\tru.deregister = false\n}"} {"input": "package subtitles\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestDownloadFromTheSubDb(t *testing.T) {\n\tfileName := createZeroedTempFile(1024 * 1024 * 4)\n\tdefer os.Remove(fileName)\n\n\tf, err := os.Open(fileName)\n\tassert.Equal(t, nil, err)\n\n\thash, err := SubDbHashFromFile(f)\n\tassert.Equal(t, nil, err)\n\tassert.Equal(t, \"0dfbe8aa4c20b52e1b8bf3cb6cbdf193\", hash)\n\n\tfinder := NewSubFinder(f, fileName, \"en\")\n\n\ttext, err := finder.TheSubDb(\"sandbox.thesubdb.com\")\n\tassert.Equal(t, nil, err)\n\tassert.True(t, len(text) > 1000)\n}\n\nfunc subDbConformTest(t *testing.T, fileName string, expectedHash string) {\n\tif !exists(fileName) {\n\t\tfmt.Println(\"ERROR thesubdb.com conformance tests missing, run ./hash-conformance-deps if you want to run these tests\")\n\t\treturn\n\t}\n\n\tf, err := os.Open(fileName)\n\tassert.Equal(t, nil, err)\n\n\thash, err := SubDbHashFromFile(f)\n\tassert.Equal(t, nil, err)\n\tassert.Equal(t, expectedHash, hash)\n}\n\n\n\nfunc TestSubDbHashFromFile(t *testing.T) ", "output": "{\n\n\tsubDbConformTest(t, \"conformance-files/thesubdb/dexter.mp4\", \"ffd8d4aa68033dc03d1c8ef373b9028c\")\n\n\tsubDbConformTest(t, \"conformance-files/thesubdb/justified.mp4\", \"edc1981d6459c6111fe36205b4aff6c2\")\n}"} {"input": "package integration_test\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/RichardKnop/machinery/v1/config\"\n)\n\n\n\nfunc TestRedisGetPendingTasks(t *testing.T) ", "output": "{\n\tredisURL := os.Getenv(\"REDIS_URL\")\n\tif redisURL == \"\" {\n\t\tt.Skip(\"REDIS_URL is not defined\")\n\t}\n\n\tserver := testSetup(&config.Config{\n\t\tBroker: fmt.Sprintf(\"redis://%v\", redisURL),\n\t\tDefaultQueue: \"test_queue\",\n\t\tResultBackend: fmt.Sprintf(\"redis://%v\", redisURL),\n\t\tLock: fmt.Sprintf(\"redis://%v\", redisURL),\n\t})\n\tpendingMessages, err := server.GetBroker().GetPendingTasks(server.GetConfig().DefaultQueue)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif len(pendingMessages) != 0 {\n\t\tt.Errorf(\n\t\t\t\"%d pending messages, should be %d\",\n\t\t\tlen(pendingMessages),\n\t\t\t0,\n\t\t)\n\t}\n}"} {"input": "package pty\n\nimport \"os\"\n\n\n\n\n\n\n\n\nfunc Getsize(t *os.File) (rows, cols int, err error) {\n\tws, err := GetsizeFull(t)\n\treturn int(ws.Rows), int(ws.Cols), err\n}\n\nfunc InheritSize(pty, tty *os.File) error ", "output": "{\n\tsize, err := GetsizeFull(pty)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := Setsize(tty, size); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package mqcontrollers\n\nimport (\n\t\"github.com/byrnedo/apibase/natsio\"\n\tr \"github.com/byrnedo/apibase/routes\"\n\t\"github.com/nats-io/nats\"\n)\n\ntype HealthcheckController struct {\n\troutes []*r.NatsRoute\n\tnatsCon *natsio.Nats\n}\n\nfunc (c *HealthcheckController) GetRoutes() []*r.NatsRoute {\n\treturn c.routes\n}\n\n\n\nfunc (c *HealthcheckController) Healthcheck(m *nats.Msg) {\n}\n\nfunc NewHealthcheckController(nc *natsio.Nats) (hc *HealthcheckController) ", "output": "{\n\thc = &HealthcheckController{}\n\thc.natsCon = nc\n\thc.routes = []*r.NatsRoute{\n\t\tr.NewNatsRoute(\"user.healthcheck\", hc.Healthcheck),\n\t}\n\treturn\n}"} {"input": "package main\n\nimport (\n\t. \"github.com/conclave/pcduino/core\"\n)\n\nfunc init() {\n\tInit()\n\tsetup()\n}\n\nfunc main() {\n\tfor {\n\t\tloop()\n\t}\n}\n\nvar touchPin byte = 1\nvar ledPin byte = 0\n\nfunc setup() {\n\tprintln(\"Touch sensor test code!\")\n\tprintln(\"Using I/O_0=Drive LED, I/O_1=Sensor output.\")\n\tPinMode(touchPin, INPUT)\n\tPinMode(ledPin, OUTPUT)\n}\n\n\n\nfunc loop() ", "output": "{\n\tval := DigitalRead(touchPin)\n\tDigitalWrite(ledPin, val)\n}"} {"input": "package p\n\ntype T int\n\nfunc (t *T) F() T {\n\treturn *t\n}\n\ntype S struct {\n\tt T\n}\n\n\n\nfunc F() ", "output": "{\n\tgo F \n\tdefer F \n\tgo (F)\t\t\n\tdefer (F)\t\n\tgo (F())\t\n\tdefer (F())\t\n\tvar s S\n\t(&s.t).F()\n\tgo (&s.t).F()\n\tdefer (&s.t).F()\n}"} {"input": "package store\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"text/tabwriter\"\n\t\"time\"\n)\n\ntype Metadata map[string]string\n\ntype Entry struct {\n\tName string `json:\"name\"`\n\tPassword []byte `json:\"password\"`\n\tCtime time.Time `json:\"ctime\"` \n\tMtime time.Time `json:\"mtime\"` \n\tMetadata Metadata `json:\"metadata\"` \n}\n\nfunc NewEntry() *Entry {\n\treturn &Entry{\n\t\tMetadata: make(Metadata),\n\t\tCtime: getCurrentTime(),\n\t\tMtime: getCurrentTime(),\n\t}\n}\n\nfunc (e *Entry) Age() time.Duration {\n\treturn time.Since(e.Mtime)\n}\n\nfunc (e *Entry) Touch() {\n\te.Mtime = getCurrentTime()\n}\n\nfunc (e Entry) String() string {\n\tb := new(bytes.Buffer)\n\tw := tabwriter.NewWriter(b, 0, 0, 0, ' ', 0)\n\n\tvalof := reflect.ValueOf(e)\n\tfor i := 0; i < valof.NumField(); i++ {\n\t\tswitch val := valof.Field(i).Interface().(type) {\n\t\tdefault:\n\t\t\ttag := valof.Type().Field(i).Tag.Get(\"json\")\n\t\t\tfmt.Fprintf(w, \"%s\\t : %s\\n\", tag, val)\n\t\tcase Metadata:\n\t\t\tfor k, v := range val {\n\t\t\t\tfmt.Fprintf(w, \"%s\\t : %s\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\n\tw.Flush()\n\treturn b.String()\n}\n\nfunc (m Metadata) String() string {\n\tvar b bytes.Buffer\n\tfor k, v := range m {\n\t\tfmt.Fprintf(&b, \"%s:%s\", k, v)\n\t}\n\treturn b.String()\n}\n\n\n\nfunc getCurrentTime() time.Time ", "output": "{\n\treturn time.Now().Truncate(time.Second)\n}"} {"input": "package ftp\n\nimport \"io\"\n\ntype debugWrapper struct {\n\tconn io.ReadWriteCloser\n\tio.Reader\n\tio.Writer\n}\n\n\n\nfunc (w *debugWrapper) Close() error {\n\treturn w.conn.Close()\n}\n\ntype streamDebugWrapper struct {\n\tio.Reader\n\tcloser io.ReadCloser\n}\n\nfunc newStreamDebugWrapper(rd io.ReadCloser, w io.Writer) io.ReadCloser {\n\treturn &streamDebugWrapper{\n\t\tReader: io.TeeReader(rd, w),\n\t\tcloser: rd,\n\t}\n}\n\nfunc (w *streamDebugWrapper) Close() error {\n\treturn w.closer.Close()\n}\n\nfunc newDebugWrapper(conn io.ReadWriteCloser, w io.Writer) io.ReadWriteCloser ", "output": "{\n\treturn &debugWrapper{\n\t\tReader: io.TeeReader(conn, w),\n\t\tWriter: io.MultiWriter(w, conn),\n\t\tconn: conn,\n\t}\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\n\n\nfunc naclClose(fd int) (err error) {\n\t_, _, e1 := Syscall(sys_close, uintptr(fd), 0, 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclFstat(fd int, stat *Stat_t) (err error) {\n\t_, _, e1 := Syscall(sys_fstat, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\n\n\n\n\nfunc naclSeek(fd int, off *int64, whence int) (err error) {\n\t_, _, e1 := Syscall(sys_lseek, uintptr(fd), uintptr(unsafe.Pointer(off)), uintptr(whence))\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\n\n\nfunc naclGetRandomBytes(b []byte) (err error) {\n\tvar _p0 unsafe.Pointer\n\tif len(b) > 0 {\n\t\t_p0 = unsafe.Pointer(&b[0])\n\t} else {\n\t\t_p0 = unsafe.Pointer(&_zero)\n\t}\n\t_, _, e1 := Syscall(sys_get_random_bytes, uintptr(_p0), uintptr(len(b)), 0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}\n\nfunc naclRead(fd int, b []byte) (n int, err error) ", "output": "{\n\tvar _p0 unsafe.Pointer\n\tif len(b) > 0 {\n\t\t_p0 = unsafe.Pointer(&b[0])\n\t} else {\n\t\t_p0 = unsafe.Pointer(&_zero)\n\t}\n\tr0, _, e1 := Syscall(sys_read, uintptr(fd), uintptr(_p0), uintptr(len(b)))\n\tn = int(r0)\n\tif e1 != 0 {\n\t\terr = errnoErr(e1)\n\t}\n\treturn\n}"} {"input": "package node_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/freeconf/yang/fc\"\n\t\"github.com/freeconf/yang/node\"\n\t\"github.com/freeconf/yang/nodeutil\"\n\t\"github.com/freeconf/yang/parser\"\n)\n\n\n\nfunc TestFieldsMatcherOnList(t *testing.T) {\n\tm, err := parser.LoadModuleFromString(nil, `\nmodule x {\n list a {\n key \"id\";\n leaf id {\n type string;\n }\n leaf b {\n type string;\n }\n }\n}\n\t`)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tn := nodeutil.ReadJSON(`\n{\n\t\"a\" : [{\n\t \"id\" : \"1\",\n\t \"b\" : \"B1\"\n\t},{\n\t \"id\" : \"2\",\n\t \"b\" : \"B2\"\n\t}]\n}`)\n\tb := node.NewBrowser(m, n)\n\tactual, err := nodeutil.WriteJSON(b.Root().Find(\"a?fields=id\"))\n\tif err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tfc.AssertEqual(t, `{\"a\":[{\"id\":\"1\"},{\"id\":\"2\"}]}`, actual)\n\t}\n}\n\nfunc TestFieldInContainerWithSameName(t *testing.T) ", "output": "{\n\tm, err := parser.LoadModuleFromString(nil, `\nmodule x {\n\tcontainer a {\n\t\tleaf a {\n\t\t\ttype string;\n\t\t}\n\t\tleaf b {\n\t\t\ttype string;\n\t\t}\n\t}\n}\n\t`)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tn := nodeutil.ReadJSON(`\n{\n\t\"a\" : {\n\t\t\"a\": \"A\",\n\t\t\"b\": \"B\"\n \t}\n}`)\n\tb := node.NewBrowser(m, n)\n\tactual, err := nodeutil.WriteJSON(b.Root().Constrain(\"fields=a\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\texpected := `{\"a\":{\"a\":\"A\",\"b\":\"B\"}}`\n\tfc.AssertEqual(t, expected, actual)\n}"} {"input": "package http\n\nimport (\n\t\"github.com/wcong/ants-go/ants/util\"\n\t\"log\"\n\tHttp \"net/http\"\n\t\"strconv\"\n\t\"sync\"\n)\n\ntype HttpServer struct {\n\tHttp.Server\n}\n\nfunc NewHttpServer(setting *util.Settings, handler Http.Handler) *HttpServer {\n\tport := strconv.Itoa(setting.HttpPort)\n\thttpServer := &HttpServer{\n\t\tHttp.Server{\n\t\t\tAddr: \":\" + port,\n\t\t\tHandler: handler,\n\t\t},\n\t}\n\treturn httpServer\n}\n\nfunc (this *HttpServer) Start(wg sync.WaitGroup) {\n\tgo this.server(wg)\n}\n\n\n\nfunc (this *HttpServer) server(wg sync.WaitGroup) ", "output": "{\n\tlog.Println(\"start to server http\" + this.Addr)\n\terr := this.ListenAndServe()\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tlog.Println(\"http server down\")\n\twg.Done()\n}"} {"input": "package windows\n\nimport (\n\t\"github.com/docker/libnetwork/driverapi\"\n\t\"github.com/docker/libnetwork/types\"\n)\n\nconst networkType = \"windows\"\n\n\n\ntype driver struct{}\n\n\nfunc Init(dc driverapi.DriverCallback) error {\n\tc := driverapi.Capability{\n\t\tScope: driverapi.LocalScope,\n\t}\n\treturn dc.RegisterDriver(networkType, &driver{}, c)\n}\n\n\n\nfunc (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) DeleteNetwork(nid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) DeleteEndpoint(nid, eid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {\n\treturn make(map[string]interface{}, 0), nil\n}\n\n\nfunc (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {\n\treturn nil\n}\n\n\nfunc (d *driver) Leave(nid, eid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) Type() string {\n\treturn networkType\n}\n\nfunc (d *driver) Config(option map[string]interface{}) error ", "output": "{\n\treturn nil\n}"} {"input": "package dns\n\nimport \"github.com/jen20/riviera/azure\"\n\ntype CNAMERecord struct {\n\tCNAME string `json:\"cname\" mapstructure:\"cname\"`\n}\n\ntype CreateCNAMERecordSetResponse struct {\n\tID string `mapstructure:\"id\"`\n\tName string `mapstructure:\"name\"`\n\tLocation string `mapstructure:\"location\"`\n\tTags map[string]*string `mapstructure:\"tags\"`\n\tTTL *int `mapstructure:\"TTL\"`\n\tCNAMERecord CNAMERecord `mapstructure:\"CNAMERecord\"`\n}\n\ntype CreateCNAMERecordSet struct {\n\tName string `json:\"-\"`\n\tResourceGroupName string `json:\"-\"`\n\tZoneName string `json:\"-\"`\n\tLocation string `json:\"-\" riviera:\"location\"`\n\tTags map[string]*string `json:\"-\" riviera:\"tags\"`\n\tTTL int `json:\"TTL\"`\n\tCNAMERecord CNAMERecord `json:\"CNAMERecord\"`\n}\n\n\n\nfunc (command CreateCNAMERecordSet) APIInfo() azure.APIInfo ", "output": "{\n\treturn azure.APIInfo{\n\t\tAPIVersion: apiVersion,\n\t\tMethod: \"PUT\",\n\t\tURLPathFunc: dnsRecordSetDefaultURLPathFunc(command.ResourceGroupName, command.ZoneName, \"CNAME\", command.Name),\n\t\tResponseTypeFunc: func() interface{} {\n\t\t\treturn &CreateCNAMERecordSetResponse{}\n\t\t},\n\t}\n}"} {"input": "package unibyte\n\nimport \"unicode\"\n\n\nfunc IsLower(b byte) bool {\n\treturn b >= 'a' && b <= 'z'\n}\n\n\nfunc IsUpper(b byte) bool {\n\treturn b >= 'A' && b <= 'Z'\n}\n\n\nfunc IsLetter(b byte) bool {\n\treturn IsLower(b) || IsUpper(b)\n}\n\n\nfunc IsSpaceQuote(b byte) bool {\n\treturn IsSpace(b) || b == '\"' || b == '\\''\n}\n\n\nfunc IsSpace(b byte) bool {\n\treturn unicode.IsSpace(rune(b))\n}\n\n\nfunc ToLower(b byte) byte {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn b\n}\n\n\n\n\n\nfunc ToLowerString(b byte) string {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn string(b)\n}\n\n\nfunc ToUpperString(b byte) string {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn string(b)\n}\n\nfunc ToUpper(b byte) byte ", "output": "{\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn b\n}"} {"input": "package commands\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\n\nvar removeCmd = &cobra.Command{\n\tUse: \"remove [item]\",\n\tShort: \"Remove items from an event, a talk, or a program\",\n\tLong: `Use this to remove sponsors from events, etc.`,\n}\n\n\n\nfunc init() ", "output": "{\n\tRootCmd.AddCommand(removeCmd)\n\n}"} {"input": "package job\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/gapid/core/data/search\"\n\t\"github.com/google/gapid/core/event\"\n\t\"github.com/google/gapid/core/net/grpcutil\"\n\t\"github.com/google/gapid/core/os/device\"\n\t\"google.golang.org/grpc\"\n)\n\ntype remote struct {\n\tclient ServiceClient\n}\n\n\nfunc NewRemote(ctx context.Context, conn *grpc.ClientConn) Manager {\n\treturn &remote{client: NewServiceClient(conn)}\n}\n\n\n\nfunc (m *remote) SearchDevices(ctx context.Context, query *search.Query, handler DeviceHandler) error {\n\tstream, err := m.client.SearchDevices(ctx, query)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn event.Feed(ctx, event.AsHandler(ctx, handler), grpcutil.ToProducer(stream))\n}\n\n\n\nfunc (m *remote) SearchWorkers(ctx context.Context, query *search.Query, handler WorkerHandler) error {\n\tstream, err := m.client.SearchWorkers(ctx, query)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn event.Feed(ctx, event.AsHandler(ctx, handler), grpcutil.ToProducer(stream))\n}\n\n\n\n\n\nfunc (m *remote) GetWorker(ctx context.Context, host *device.Instance, target *device.Instance, op Operation) (*Worker, error) ", "output": "{\n\trequest := &GetWorkerRequest{Host: host, Target: target, Operation: op}\n\tresponse, err := m.client.GetWorker(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn response.Worker, nil\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"os/exec\"\n)\n\nfunc panicOn(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\n\nfunc DirExists(name string) bool {\n\tfi, err := os.Stat(name)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif fi.IsDir() {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc Run(dir string, exe string, arg ...string) (stdout *bytes.Buffer, stderr *bytes.Buffer, err error) {\n\tcmd := exec.Command(exe, arg...)\n\tvar errbuf bytes.Buffer\n\tvar outbuf bytes.Buffer\n\tcmd.Dir = dir\n\tcmd.Stderr = &errbuf\n\tcmd.Stdout = &outbuf\n\terr = cmd.Run()\n\treturn &outbuf, &errbuf, err\n}\n\nfunc FileExists(name string) bool ", "output": "{\n\tfi, err := os.Stat(name)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif fi.IsDir() {\n\t\treturn false\n\t}\n\treturn true\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"context\"\n\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\n\ntype Ddns struct {\n\n\tEnabled *bool `json:\"enabled,omitempty\"`\n\n\tFqdn string `json:\"fqdn,omitempty\"`\n\n\tSkipFqdnValidation *bool `json:\"skip_fqdn_validation,omitempty\"`\n\n\tTimeToLive *string `json:\"time_to_live,omitempty\"`\n\n\tUseSecure *bool `json:\"use_secure,omitempty\"`\n}\n\n\nfunc (m *Ddns) Validate(formats strfmt.Registry) error {\n\treturn nil\n}\n\n\nfunc (m *Ddns) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}\n\n\n\n\n\nfunc (m *Ddns) UnmarshalBinary(b []byte) error {\n\tvar res Ddns\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *Ddns) MarshalBinary() ([]byte, error) ", "output": "{\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}"} {"input": "package endpoints\n\nimport (\n\t\"github.com/lxc/lxd/lxd/util\"\n\t\"github.com/lxc/lxd/shared\"\n)\n\n\nfunc Unstarted() *Endpoints {\n\treturn &Endpoints{\n\t\tsystemdListenFDsStart: util.SystemdListenFDsStart,\n\t}\n}\n\nfunc (e *Endpoints) Up(config *Config) error {\n\treturn e.up(config)\n}\n\n\n\n\nfunc (e *Endpoints) LocalSocketPath() string {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tlistener := e.listeners[local]\n\treturn listener.Addr().String()\n}\n\n\n\n\nfunc (e *Endpoints) NetworkAddressAndCert() (string, *shared.CertInfo) {\n\treturn e.NetworkAddress(), e.cert\n}\n\n\n\n\nfunc (e *Endpoints) SystemdListenFDsStart(start int) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\te.systemdListenFDsStart = start\n}\n\nfunc (e *Endpoints) DevLxdSocketPath() string ", "output": "{\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tlistener := e.listeners[devlxd]\n\treturn listener.Addr().String()\n}"} {"input": "package model\n\nimport (\n\t\"fmt\"\n\tnative_time \"time\"\n)\n\n\n\n\n\n\n\n\ntype Timestamp int64\n\nconst (\n\tMinimumTick = native_time.Second\n\tsecond = int64(native_time.Second / MinimumTick)\n)\n\n\nfunc (t Timestamp) Equal(o Timestamp) bool {\n\treturn t == o\n}\n\n\nfunc (t Timestamp) Before(o Timestamp) bool {\n\treturn t < o\n}\n\n\nfunc (t Timestamp) After(o Timestamp) bool {\n\treturn t > o\n}\n\n\n\n\n\nfunc (t Timestamp) Sub(o Timestamp) native_time.Duration {\n\treturn native_time.Duration(t-o) * MinimumTick\n}\n\n\nfunc (t Timestamp) Time() native_time.Time {\n\treturn native_time.Unix(int64(t)/second, (int64(t) % second))\n}\n\n\n\nfunc (t Timestamp) Unix() int64 {\n\treturn int64(t) / second\n}\n\n\nfunc (t Timestamp) String() string {\n\treturn fmt.Sprint(int64(t))\n}\n\n\nfunc Now() Timestamp {\n\treturn TimestampFromTime(native_time.Now())\n}\n\n\nfunc TimestampFromTime(t native_time.Time) Timestamp {\n\treturn TimestampFromUnix(t.Unix())\n}\n\n\nfunc TimestampFromUnix(t int64) Timestamp {\n\treturn Timestamp(t * second)\n}\n\nfunc (t Timestamp) Add(d native_time.Duration) Timestamp ", "output": "{\n\treturn t + Timestamp(d/MinimumTick)\n}"} {"input": "package http\n\nimport (\n\t\"testing\"\n)\n\nfunc isChar(c rune) bool { return c <= 127 }\n\n\n\nfunc isSeparator(c rune) bool {\n\tswitch c {\n\tcase '(', ')', '<', '>', '@', ',', ';', ':', '\\\\', '\"', '/', '[', ']', '?', '=', '{', '}', ' ', '\\t':\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc TestIsToken(t *testing.T) {\n\tfor i := 0; i <= 130; i++ {\n\t\tr := rune(i)\n\t\texpected := isChar(r) && !isCtl(r) && !isSeparator(r)\n\t\tif isToken(r) != expected {\n\t\t\tt.Errorf(\"isToken(0x%x) = %v\", r, !expected)\n\t\t}\n\t}\n}\n\nfunc isCtl(c rune) bool ", "output": "{ return c <= 31 || c == 127 }"} {"input": "package tagquery\n\nimport (\n\t\"io\"\n\n\t\"github.com/grafana/metrictank/schema\"\n)\n\ntype expressionMatchNone struct {\n\texpressionCommon\n\toriginalOperator ExpressionOperator\n}\n\nfunc (e *expressionMatchNone) Equals(other Expression) bool {\n\treturn e.key == other.GetKey() && e.GetOperator() == other.GetOperator() && e.value == other.GetValue()\n}\n\nfunc (e *expressionMatchNone) GetDefaultDecision() FilterDecision {\n\treturn Fail\n}\n\nfunc (e *expressionMatchNone) GetKey() string {\n\treturn e.key\n}\n\nfunc (e *expressionMatchNone) GetValue() string {\n\treturn e.value\n}\n\n\n\nfunc (e *expressionMatchNone) GetOperatorCost() uint32 {\n\treturn 0\n}\n\nfunc (e *expressionMatchNone) RequiresNonEmptyValue() bool {\n\treturn true\n}\n\nfunc (e *expressionMatchNone) Matches(value string) bool {\n\treturn false\n}\n\nfunc (e *expressionMatchNone) GetMetricDefinitionFilter(_ IdTagLookup) MetricDefinitionFilter {\n\treturn func(_ schema.MKey, _ string, _ []string) FilterDecision { return Fail }\n}\n\nfunc (e *expressionMatchNone) StringIntoWriter(writer io.Writer) {\n\twriter.Write([]byte(e.key))\n\te.originalOperator.StringIntoWriter(writer)\n\twriter.Write([]byte(e.value))\n}\n\nfunc (e *expressionMatchNone) GetOperator() ExpressionOperator ", "output": "{\n\treturn MATCH_NONE\n}"} {"input": "package git\n\nimport (\n\t\"sync\"\n\n\t\"github.com/mholt/caddy/middleware/git/gitos\"\n)\n\n\n\ntype repoService struct {\n\trepo *Repo\n\tticker gitos.Ticker \n\thalt chan struct{} \n}\n\n\n\n\n\ntype services struct {\n\tservices []*repoService\n\tsync.Mutex\n}\n\n\nfunc (s *services) add(r *repoService) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.services = append(s.services, r)\n}\n\n\n\n\n\nfunc (s *services) Stop(repoURL string, limit int) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tfor i, j := 0, 0; i < len(s.services) && ((limit >= 0 && j < limit) || limit < 0); i++ {\n\t\tservice := s.services[i]\n\t\tif service.repo.URL == repoURL {\n\t\t\tservice.halt <- struct{}{}\n\t\t\ts.services[i] = nil\n\t\t\tj++\n\t\t}\n\t}\n\n\tservices := s.services[:0]\n\tfor _, s := range s.services {\n\t\tif s != nil {\n\t\t\tservices = append(services, s)\n\t\t}\n\t}\n\ts.services = services\n}\n\nfunc Start(repo *Repo) ", "output": "{\n\tservice := &repoService{\n\t\trepo,\n\t\tgos.NewTicker(repo.Interval),\n\t\tmake(chan struct{}),\n\t}\n\tgo func(s *repoService) {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-s.ticker.C():\n\t\t\t\terr := repo.Pull()\n\t\t\t\tif err != nil {\n\t\t\t\t\tLogger().Println(err)\n\t\t\t\t}\n\t\t\tcase <-s.halt:\n\t\t\t\ts.ticker.Stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(service)\n\n\tServices.add(service)\n}"} {"input": "package utub\n\nimport (\n\t\"strings\"\n\n\t\"gopkg.in/olebedev/go-duktape.v2\"\n)\n\ntype duktapeJSEngine struct{}\n\nfunc (js duktapeJSEngine) Name() string {\n\treturn \"Duktape\"\n}\n\nfunc (js duktapeJSEngine) Available() bool {\n\treturn true\n}\n\nfunc (js duktapeJSEngine) Exec(code string) (string, error) {\n\tctx := duktape.New()\n\tdefer ctx.DestroyHeap()\n\n\terr := ctx.PevalString(code)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn ctx.SafeToString(-1), nil\n}\n\n\n\nfunc (js duktapeJSEngine) sanitizeJSPlayerCode(code string) string ", "output": "{\n\tcode = strings.Replace(code, `(?=:|,|]|}|$)`, `(?=:|,|\\]|\\}|$)`, 1)\n\treturn code\n}"} {"input": "package policylist\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/hashicorp/consul/command/acl\"\n\t\"github.com/hashicorp/consul/command/flags\"\n\t\"github.com/mitchellh/cli\"\n)\n\nfunc New(ui cli.Ui) *cmd {\n\tc := &cmd{UI: ui}\n\tc.init()\n\treturn c\n}\n\ntype cmd struct {\n\tUI cli.Ui\n\tflags *flag.FlagSet\n\thttp *flags.HTTPFlags\n\thelp string\n\n\tshowMeta bool\n}\n\nfunc (c *cmd) init() {\n\tc.flags = flag.NewFlagSet(\"\", flag.ContinueOnError)\n\tc.flags.BoolVar(&c.showMeta, \"meta\", false, \"Indicates that policy metadata such \"+\n\t\t\"as the content hash and raft indices should be shown for each entry\")\n\n\tc.http = &flags.HTTPFlags{}\n\tflags.Merge(c.flags, c.http.ClientFlags())\n\tflags.Merge(c.flags, c.http.ServerFlags())\n\tc.help = flags.Usage(help, c.flags)\n}\n\n\n\nfunc (c *cmd) Synopsis() string {\n\treturn synopsis\n}\n\nfunc (c *cmd) Help() string {\n\treturn flags.Usage(c.help, nil)\n}\n\nconst synopsis = \"Lists ACL Policies\"\nconst help = `\nUsage: consul acl policy list [options]\n\n Lists all the ACL policies\n\n Example:\n\n $ consul acl policy list\n`\n\nfunc (c *cmd) Run(args []string) int ", "output": "{\n\tif err := c.flags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tclient, err := c.http.APIClient()\n\tif err != nil {\n\t\tc.UI.Error(fmt.Sprintf(\"Error connecting to Consul agent: %s\", err))\n\t\treturn 1\n\t}\n\n\tpolicies, _, err := client.ACL().PolicyList(nil)\n\tif err != nil {\n\t\tc.UI.Error(fmt.Sprintf(\"Failed to retrieve the policy list: %v\", err))\n\t\treturn 1\n\t}\n\n\tfor _, policy := range policies {\n\t\tacl.PrintPolicyListEntry(policy, c.UI, c.showMeta)\n\t}\n\n\treturn 0\n}"} {"input": "package insulin\n\nimport (\n\t\"math\"\n\n\t\"github.com/tidepool-org/platform/data\"\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tConcentrationUnitsUnitsPerML = \"Units/mL\"\n\tConcentrationValueUnitsPerMLMaximum = 10000.0\n\tConcentrationValueUnitsPerMLMinimum = 0.0\n)\n\nfunc ConcentrationUnits() []string {\n\treturn []string{\n\t\tConcentrationUnitsUnitsPerML,\n\t}\n}\n\ntype Concentration struct {\n\tUnits *string `json:\"units,omitempty\" bson:\"units,omitempty\"`\n\tValue *float64 `json:\"value,omitempty\" bson:\"value,omitempty\"`\n}\n\nfunc ParseConcentration(parser structure.ObjectParser) *Concentration {\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewConcentration()\n\tparser.Parse(datum)\n\treturn datum\n}\n\n\n\nfunc (c *Concentration) Parse(parser structure.ObjectParser) {\n\tc.Units = parser.String(\"units\")\n\tc.Value = parser.Float64(\"value\")\n}\n\nfunc (c *Concentration) Validate(validator structure.Validator) {\n\tvalidator.String(\"units\", c.Units).Exists().OneOf(ConcentrationUnits()...)\n\tvalidator.Float64(\"value\", c.Value).Exists().InRange(ConcentrationValueRangeForUnits(c.Units))\n}\n\nfunc (c *Concentration) Normalize(normalizer data.Normalizer) {}\n\nfunc ConcentrationValueRangeForUnits(units *string) (float64, float64) {\n\tif units != nil {\n\t\tswitch *units {\n\t\tcase ConcentrationUnitsUnitsPerML:\n\t\t\treturn ConcentrationValueUnitsPerMLMinimum, ConcentrationValueUnitsPerMLMaximum\n\t\t}\n\t}\n\treturn -math.MaxFloat64, math.MaxFloat64\n}\n\nfunc NewConcentration() *Concentration ", "output": "{\n\treturn &Concentration{}\n}"} {"input": "package models\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"time\"\n)\n\n\ntype Config struct {\n\tJWT string `json:\"jwt_token\"`\n}\n\n\nfunc (c *Config) FindByKey(key string) (value string, err error) {\n\tval, err := N.Request(\"config.get.jwt_token\", []byte(\"\"), 1*time.Second)\n\tif err == nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(val.Data), err\n}\n\n\nfunc (c *Config) GetJWTToken() (token string, err error) {\n\ttoken = os.Getenv(\"JWT_SECRET\")\n\tif token == \"\" {\n\t\ttoken, err = c.FindByKey(\"jwt_token\")\n\t\tif err != nil {\n\t\t\treturn \"\", errors.New(\"Can't get jwt_config config\")\n\t\t}\n\t}\n\n\treturn token, nil\n}\n\n\n\n\n\nfunc (c *Config) GetServerPort() (token string) {\n\treturn \"8080\"\n}\n\nfunc (c *Config) GetNatsURI() string ", "output": "{\n\treturn os.Getenv(\"NATS_URI\")\n}"} {"input": "package hilbert\n\ntype mockRectangle struct {\n\txlow, ylow, xhigh, yhigh int32\n}\n\n\n\nfunc (mr *mockRectangle) UpperRight() (int32, int32) {\n\treturn mr.xhigh, mr.yhigh\n}\n\nfunc newMockRectangle(xlow, ylow, xhigh, yhigh int32) *mockRectangle {\n\treturn &mockRectangle{\n\t\txlow: xlow,\n\t\tylow: ylow,\n\t\txhigh: xhigh,\n\t\tyhigh: yhigh,\n\t}\n}\n\nfunc (mr *mockRectangle) LowerLeft() (int32, int32) ", "output": "{\n\treturn mr.xlow, mr.ylow\n}"} {"input": "package s0132\n\nimport (\n\t\"github.com/peterstace/project-euler/number\"\n)\n\n\n\nfunc SumPrimeFactors(numFactors int, k int) int {\n\tvar factorsFound int\n\tvar sum int\n\tnthPrime := number.MakeSieveBackedNthPrime()\n\tfor i := 0; factorsFound < numFactors; i++ {\n\t\tp := nthPrime(i)\n\t\tif repunit(k, p) == 0 {\n\t\t\tfactorsFound++\n\t\t\tsum += p\n\t\t}\n\t}\n\treturn sum\n}\n\n\nfunc repunit(k, m int) int {\n\tif k == 1 {\n\t\treturn 1\n\t}\n\tif k%2 == 0 {\n\t\thalf := repunit(k/2, m)\n\t\treturn (tenPow(k/2, m)*half + half) % m\n\t} else {\n\t\treturn (10*repunit(k-1, m) + 1) % m\n\t}\n}\n\n\nfunc tenPow(k, m int) int {\n\tif k == 0 {\n\t\treturn 1\n\t}\n\tif k%2 == 0 {\n\t\thalf := tenPow(k/2, m)\n\t\treturn (half * half) % m\n\t} else {\n\t\treturn (10 * tenPow(k-1, m)) % m\n\t}\n}\n\nfunc Answer() interface{} ", "output": "{\n\treturn SumPrimeFactors(40, 10e9)\n}"} {"input": "package event\n\nimport (\n\t\"testing\"\n\n\t\"github.com/xytis/gami\"\n)\n\n\n\nfunc TestUserEventEvent(t *testing.T) ", "output": "{\n\tfixture := map[string]string{\n\t\t\"Userevent\": \"UserEvent\",\n\t\t\"Uniqueid\": \"UniqueID\",\n\t}\n\n\tev := gami.AMIEvent{\n\t\tID: \"UserEvent\",\n\t\tPrivilege: []string{\"all\"},\n\t\tParams: fixture,\n\t}\n\n\tevtype := New(&ev)\n\tif _, ok := evtype.(UserEvent); !ok {\n\t\tt.Log(\"UserEvent type assertion\")\n\t\tt.Fail()\n\t}\n\n\ttestEvent(t, fixture, evtype)\n}"} {"input": "package net\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/v2ray/v2ray-core/common/serial\"\n)\n\n\n\nfunc (this *NetworkList) UnmarshalJSON(data []byte) error ", "output": "{\n\tvar strlist serial.StringLiteralList\n\tif err := json.Unmarshal(data, &strlist); err != nil {\n\t\treturn err\n\t}\n\t*this = NewNetworkList(strlist)\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/conformal/winsvc/eventlog\"\n\t\"github.com/conformal/winsvc/mgr\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nfunc exePath() (string, error) {\n\tprog := os.Args[0]\n\tp, err := filepath.Abs(prog)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfi, err := os.Stat(p)\n\tif err == nil {\n\t\tif !fi.Mode().IsDir() {\n\t\t\treturn p, nil\n\t\t}\n\t\terr = fmt.Errorf(\"%s is directory\", p)\n\t}\n\tif filepath.Ext(p) == \"\" {\n\t\tp += \".exe\"\n\t\tfi, err := os.Stat(p)\n\t\tif err == nil {\n\t\t\tif !fi.Mode().IsDir() {\n\t\t\t\treturn p, nil\n\t\t\t}\n\t\t\terr = fmt.Errorf(\"%s is directory\", p)\n\t\t}\n\t}\n\treturn \"\", err\n}\n\n\n\nfunc removeService(name string) error {\n\tm, err := mgr.Connect()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer m.Disconnect()\n\ts, err := m.OpenService(name)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"service %s is not installed\", name)\n\t}\n\tdefer s.Close()\n\terr = s.Delete()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = eventlog.Remove(name)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"RemoveEventLogSource() failed: %s\", err)\n\t}\n\treturn nil\n}\n\nfunc installService(name, desc string) error ", "output": "{\n\texepath, err := exePath()\n\tif err != nil {\n\t\treturn err\n\t}\n\tm, err := mgr.Connect()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer m.Disconnect()\n\ts, err := m.OpenService(name)\n\tif err == nil {\n\t\ts.Close()\n\t\treturn fmt.Errorf(\"service %s already exists\", name)\n\t}\n\ts, err = m.CreateService(name, exepath, mgr.Config{DisplayName: desc})\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer s.Close()\n\terr = eventlog.InstallAsEventCreate(name, eventlog.Error|eventlog.Warning|eventlog.Info)\n\tif err != nil {\n\t\ts.Delete()\n\t\treturn fmt.Errorf(\"SetupEventLogSource() failed: %s\", err)\n\t}\n\treturn nil\n}"} {"input": "package stick\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"go.mongodb.org/mongo-driver/bson\"\n)\n\n\ntype Coding string\n\n\nconst (\n\tJSON Coding = \"json\"\n\tBSON Coding = \"bson\"\n)\n\n\nfunc (c Coding) Marshal(in interface{}) ([]byte, error) {\n\tswitch c {\n\tcase JSON:\n\t\treturn json.Marshal(in)\n\tcase BSON:\n\t\treturn bson.Marshal(in)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"coal: unknown coding %q\", c))\n\t}\n}\n\n\nfunc (c Coding) Unmarshal(in []byte, out interface{}) error {\n\tswitch c {\n\tcase JSON:\n\t\treturn json.Unmarshal(in, out)\n\tcase BSON:\n\t\treturn bson.Unmarshal(in, out)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"coal: unknown coding %q\", c))\n\t}\n}\n\n\nfunc (c Coding) Transfer(in, out interface{}) error {\n\tbytes, err := c.Marshal(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.Unmarshal(bytes, out)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc GetJSONKey(field *reflect.StructField) string {\n\ttag := field.Tag.Get(\"json\")\n\n\tif tag == \"-\" {\n\t\treturn \"\"\n\t}\n\n\tvalues := strings.Split(tag, \",\")\n\n\tif len(values) > 0 && len(values[0]) > 0 {\n\t\treturn values[0]\n\t}\n\n\treturn field.Name\n}\n\n\n\n\nfunc GetBSONKey(field *reflect.StructField) string ", "output": "{\n\ttag := field.Tag.Get(\"bson\")\n\n\tif tag == \"-\" {\n\t\treturn \"\"\n\t}\n\n\tvalues := strings.Split(tag, \",\")\n\n\tif len(values) > 0 && len(values[0]) > 0 {\n\t\treturn values[0]\n\t}\n\n\treturn strings.ToLower(field.Name)\n}"} {"input": "package supervisor\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc create() *Supervisor {\n\tnow := time.Now()\n\tend := now.Add(time.Hour * 1)\n\tconf := &Config{\n\t\tOn: true,\n\t\tBegin: now,\n\t\tEnd: end,\n\t}\n\treturn New(conf)\n}\n\nfunc TestSupervisor(t *testing.T) {\n\tsv := create()\n\tin := sv.conf.Begin.Add(time.Second * 10)\n\tout := sv.conf.End.Add(time.Second * 10)\n\n\tif sv.forbid(\"GET\", in) {\n\t\tt.Error(\"Request should never be blocked on GET method\")\n\t}\n\n\tif !sv.forbid(\"POST\", in) {\n\t\tt.Errorf(\"Request should be blocked on POST method at %+v\", in)\n\t}\n\n\tif sv.forbid(\"POST\", out) {\n\t\tt.Errorf(\"Request should not be blocked at %+v\", out)\n\t}\n}\n\n\n\nfunc TestReload(t *testing.T) ", "output": "{\n\tzero := time.Unix(0, 0)\n\tconf := &Config{\n\t\tOn: false,\n\t\tBegin: zero,\n\t\tEnd: zero,\n\t}\n\tsv := create()\n\n\tsv.Reload(nil)\n\n\tsv.Reload(conf)\n\n\tif sv.conf != conf && sv.on == false {\n\t\tt.Errorf(\"Failed to reload config %+v, current config is %+v\", conf, sv.conf)\n\t}\n}"} {"input": "package route\n\nimport (\n\t\"net/url\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc mustParse(rawurl string) *url.URL {\n\tu, err := url.Parse(rawurl)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn u\n}\n\nfunc TestNewRoute(t *testing.T) {\n\tr := newRoute(\"www.bar.com\", \"/foo\")\n\tif got, want := r.Path, \"/foo\"; got != want {\n\t\tt.Errorf(\"got %q want %q\", got, want)\n\t}\n}\n\n\n\nfunc TestDelService(t *testing.T) {\n\tu1, u2 := mustParse(\"http://foo.com/\"), mustParse(\"http://bar.com/\")\n\n\tr := newRoute(\"www.bar.com\", \"/foo\")\n\tr.addTarget(\"serviceA\", u1, 0, nil)\n\tr.addTarget(\"serviceB\", u2, 0, nil)\n\tr.delService(\"serviceA\")\n\n\tconfig := []string{\"route add serviceB www.bar.com/foo http://bar.com/\"}\n\tif got, want := r.config(false), config; !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"config: got %q want %q\", got, want)\n\t}\n}\n\nfunc TestAddTarget(t *testing.T) ", "output": "{\n\tu := mustParse(\"http://foo.com/\")\n\n\tr := newRoute(\"www.bar.com\", \"/foo\")\n\tr.addTarget(\"service\", u, 0, nil)\n\n\tif got, want := len(r.Targets), 1; got != want {\n\t\tt.Errorf(\"target length: got %d want %d\", got, want)\n\t}\n\tif got, want := r.Targets[0].URL, u; got != want {\n\t\tt.Errorf(\"target url: got %s want %s\", got, want)\n\t}\n\tconfig := []string{\"route add service www.bar.com/foo http://foo.com/\"}\n\tif got, want := r.config(false), config; !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"config: got %q want %q\", got, want)\n\t}\n}"} {"input": "package text\n\nimport \"fmt\"\n\nconst (\n\tredCode = \"\\x1b[31m\"\n\tgreenCode = \"\\x1b[32m\"\n\tyellowCode = \"\\x1b[33m\"\n\tblueCode = \"\\x1b[34m\"\n\tmagentaCode = \"\\x1b[35m\"\n\tCyanCode = \"\\x1b[36m\"\n\tboldCode = \"\\x1b[1m\"\n\n\tResetCode = \"\\x1b[0m\"\n)\n\n\nvar UseColor = true\n\nfunc stylize(startCode, in string) string {\n\tif UseColor {\n\t\treturn startCode + in + ResetCode\n\t}\n\n\treturn in\n}\n\n\n\nfunc Green(in string) string {\n\treturn stylize(greenCode, in)\n}\n\nfunc yellow(in string) string {\n\treturn stylize(yellowCode, in)\n}\n\nfunc Cyan(in string) string {\n\treturn stylize(CyanCode, in)\n}\n\nfunc Magenta(in string) string {\n\treturn stylize(magentaCode, in)\n}\n\nfunc Blue(in string) string {\n\treturn stylize(blueCode, in)\n}\n\nfunc Bold(in string) string {\n\treturn stylize(boldCode, in)\n}\n\n\n\nfunc ColorHash(name string) (output string) {\n\tif !UseColor {\n\t\treturn name\n\t}\n\n\tvar hash uint = 5381\n\n\tfor i := 0; i < len(name); i++ {\n\t\thash = uint(name[i]) + ((hash << 5) + (hash))\n\t}\n\n\treturn fmt.Sprintf(\"\\x1b[%dm%s\\x1b[0m\", hash%6+31, name)\n}\n\nfunc Red(in string) string ", "output": "{\n\treturn stylize(redCode, in)\n}"} {"input": "package cachex\n\n\n\n\nimport (\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestSentinel_Wait(t *testing.T) ", "output": "{\n\tsentinel := NewSentinel()\n\n\tvar sum int\n\n\tvar mu sync.Mutex\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < 10; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\n\t\t\tvar value int\n\t\t\terr := sentinel.Wait(&value)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.Equal(t, 1, value)\n\n\t\t\tmu.Lock()\n\t\t\tdefer mu.Unlock()\n\t\t\tsum += value\n\t\t}()\n\t}\n\n\terr := sentinel.Done(1, nil)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\n\twg.Wait()\n\n\tassert.Equal(t, 10, sum)\n}"} {"input": "package nes\n\nimport \"math\"\n\ntype Filter interface {\n\tStep(x float32) float32\n}\n\n\n\ntype FirstOrderFilter struct {\n\tB0 float32\n\tB1 float32\n\tA1 float32\n\tprevX float32\n\tprevY float32\n}\n\nfunc (f *FirstOrderFilter) Step(x float32) float32 {\n\ty := f.B0*x + f.B1*f.prevX - f.A1*f.prevY\n\tf.prevY = y\n\tf.prevX = x\n\treturn y\n}\n\n\n\nfunc LowPassFilter(sampleRate float32, cutoffFreq float32) Filter {\n\tc := sampleRate / math.Pi / cutoffFreq\n\ta0i := 1 / (1 + c)\n\treturn &FirstOrderFilter{\n\t\tB0: a0i,\n\t\tB1: a0i,\n\t\tA1: (1 - c) * a0i,\n\t}\n}\n\nfunc HighPassFilter(sampleRate float32, cutoffFreq float32) Filter {\n\tc := sampleRate / math.Pi / cutoffFreq\n\ta0i := 1 / (1 + c)\n\treturn &FirstOrderFilter{\n\t\tB0: c * a0i,\n\t\tB1: -c * a0i,\n\t\tA1: (1 - c) * a0i,\n\t}\n}\n\ntype FilterChain []Filter\n\n\n\nfunc (fc FilterChain) Step(x float32) float32 ", "output": "{\n\tif fc != nil {\n\t\tfor i := range fc {\n\t\t\tx = fc[i].Step(x)\n\t\t}\n\t}\n\treturn x\n}"} {"input": "package utils\n\nimport (\n\t\"os\"\n)\n\nfunc FileExist(filename string) bool {\n\tstat, err := os.Stat(filename)\n\treturn err == nil || os.IsExist(err) || (!stat.IsDir())\n}\n\n\n\nfunc DirExist(path string) bool ", "output": "{\n\tstat, err := os.Stat(path)\n\treturn err == nil || os.IsExist(err) || stat.IsDir()\n}"} {"input": "package errors\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/GoogleContainerTools/skaffold/proto/v1\"\n)\n\ntype Error interface {\n\tError() string\n\tStatusCode() proto.StatusCode\n\tSuggestions() []*proto.Suggestion\n\tUnwrap() error\n}\n\ntype ErrDef struct {\n\terr error\n\tae *proto.ActionableErr\n}\n\nvar _ error = (*ErrDef)(nil)\n\nfunc (e *ErrDef) Error() string {\n\tif s := concatSuggestions(e.Suggestions()); s != \"\" {\n\t\treturn fmt.Sprintf(\"%s. %s\", e.ae.Message, concatSuggestions(e.Suggestions()))\n\t}\n\treturn e.ae.Message\n}\n\n\n\nfunc (e *ErrDef) StatusCode() proto.StatusCode {\n\treturn e.ae.ErrCode\n}\n\nfunc (e *ErrDef) Suggestions() []*proto.Suggestion {\n\treturn e.ae.Suggestions\n}\n\n\nfunc NewError(err error, ae *proto.ActionableErr) *ErrDef {\n\treturn &ErrDef{\n\t\terr: err,\n\t\tae: ae,\n\t}\n}\n\n\nfunc NewErrorWithStatusCode(ae *proto.ActionableErr) *ErrDef {\n\treturn &ErrDef{\n\t\tae: ae,\n\t}\n}\n\nfunc IsSkaffoldErr(err error) bool {\n\tif _, ok := err.(Error); ok {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (e *ErrDef) Unwrap() error ", "output": "{\n\treturn e.err\n}"} {"input": "package rest\n\nimport (\n\t\"fmt\"\n)\n\ntype imagecache struct {\n\tca cache\n}\n\ntype pic struct {\n\tpng []byte\n\tpkthsh hashcode\n}\n\nfunc (p pic) hash() hashcode {\n\treturn p.pkthsh\n}\n\nfunc makeImageCache() imagecache {\n\tic := imagecache{}\n\tic.ca = makeCache(pic{})\n\treturn ic\n}\n\nfunc (ic imagecache) put(hsh hashcode, png []byte) {\n\tsz := 0\n\tif __DEBUG {\n\t\tsz = len(png)\n\t}\n\tdebugf(\"Storing image for %v (length %v)\", hsh, sz)\n\tp := pic{}\n\tp.png = png\n\tp.pkthsh = hsh\n\tic.ca.put(p)\n}\n\n\n\nfunc (ic imagecache) get(hsh hashcode) ([]byte, bool) ", "output": "{\n\tdebugf(\"Fetching image for %v\", hsh)\n\tany, present := ic.ca.get(hsh)\n\tif !present {\n\t\treturn nil, false\n\t}\n\tp, ok := any.(pic)\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"Expected type pic received: %v\", any))\n\t}\n\treturn p.png, true\n}"} {"input": "package revocations\n\nimport (\n\t\"github.com/leanovate/microzon-auth-go/common\"\n\t\"github.com/leanovate/microzon-auth-go/logging\"\n\t\"github.com/leanovate/microzon-auth-go/store\"\n\t\"sync\"\n)\n\ntype RevocationsValidator struct {\n\tObserve *ObserverGroup\n\tlock sync.RWMutex\n\tlogger logging.Logger\n\trevocationHashes *hashWheel\n\texpirationTimeWheel *timeWheel\n\tagentStore store.AgentStore\n}\n\n\n\n\n\nfunc (r *RevocationsValidator) IsRevoked(sha256 common.RawSha256) bool {\n\tr.lock.RLock()\n\tdefer r.lock.RUnlock()\n\n\treturn r.revocationHashes.containsHash(sha256)\n}\n\nfunc NewRevocationsValidator(store store.AgentStore, parent logging.Logger) *RevocationsValidator ", "output": "{\n\treturn &RevocationsValidator{\n\t\tObserve: NewObserverGroup(0, parent),\n\t\tlogger: parent.WithContext(map[string]interface{}{\"package\": \"revokations\"}),\n\t\trevocationHashes: newHashWheel(17),\n\t\texpirationTimeWheel: newTimeWheel(600),\n\t\tagentStore: store,\n\t}\n}"} {"input": "package iso20022\n\n\ntype PointOfInteractionComponent6 struct {\n\n\tType *POIComponentType4Code `xml:\"Tp\"`\n\n\tIdentification *PointOfInteractionComponentIdentification1 `xml:\"Id\"`\n\n\tStatus *PointOfInteractionComponentStatus3 `xml:\"Sts,omitempty\"`\n\n\tStandardCompliance []*GenericIdentification48 `xml:\"StdCmplc,omitempty\"`\n\n\tCharacteristics *PointOfInteractionComponentCharacteristics2 `xml:\"Chrtcs,omitempty\"`\n\n\tAssessment []*PointOfInteractionComponentAssessment1 `xml:\"Assmnt,omitempty\"`\n}\n\nfunc (p *PointOfInteractionComponent6) SetType(value string) {\n\tp.Type = (*POIComponentType4Code)(&value)\n}\n\nfunc (p *PointOfInteractionComponent6) AddIdentification() *PointOfInteractionComponentIdentification1 {\n\tp.Identification = new(PointOfInteractionComponentIdentification1)\n\treturn p.Identification\n}\n\nfunc (p *PointOfInteractionComponent6) AddStatus() *PointOfInteractionComponentStatus3 {\n\tp.Status = new(PointOfInteractionComponentStatus3)\n\treturn p.Status\n}\n\nfunc (p *PointOfInteractionComponent6) AddStandardCompliance() *GenericIdentification48 {\n\tnewValue := new(GenericIdentification48)\n\tp.StandardCompliance = append(p.StandardCompliance, newValue)\n\treturn newValue\n}\n\nfunc (p *PointOfInteractionComponent6) AddCharacteristics() *PointOfInteractionComponentCharacteristics2 {\n\tp.Characteristics = new(PointOfInteractionComponentCharacteristics2)\n\treturn p.Characteristics\n}\n\n\n\nfunc (p *PointOfInteractionComponent6) AddAssessment() *PointOfInteractionComponentAssessment1 ", "output": "{\n\tnewValue := new(PointOfInteractionComponentAssessment1)\n\tp.Assessment = append(p.Assessment, newValue)\n\treturn newValue\n}"} {"input": "package cache\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"k8s.io/klog\"\n)\n\n\n\n\n\ntype ActualStateOfWorld interface {\n\n\tGetRegisteredPlugins() []PluginInfo\n\n\tAddPlugin(pluginInfo PluginInfo) error\n\n\tRemovePlugin(socketPath string)\n\n\tPluginExistsWithCorrectTimestamp(pluginInfo PluginInfo) bool\n}\n\n\nfunc NewActualStateOfWorld() ActualStateOfWorld {\n\treturn &actualStateOfWorld{\n\t\tsocketFileToInfo: make(map[string]PluginInfo),\n\t}\n}\n\ntype actualStateOfWorld struct {\n\n\tsocketFileToInfo map[string]PluginInfo\n\tsync.RWMutex\n}\n\nvar _ ActualStateOfWorld = &actualStateOfWorld{}\n\n\ntype PluginInfo struct {\n\tSocketPath string\n\tTimestamp time.Time\n\tHandler PluginHandler\n\tName string\n}\n\n\n\nfunc (asw *actualStateOfWorld) RemovePlugin(socketPath string) {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tdelete(asw.socketFileToInfo, socketPath)\n}\n\nfunc (asw *actualStateOfWorld) GetRegisteredPlugins() []PluginInfo {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\tcurrentPlugins := []PluginInfo{}\n\tfor _, pluginInfo := range asw.socketFileToInfo {\n\t\tcurrentPlugins = append(currentPlugins, pluginInfo)\n\t}\n\treturn currentPlugins\n}\n\nfunc (asw *actualStateOfWorld) PluginExistsWithCorrectTimestamp(pluginInfo PluginInfo) bool {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\tactualStatePlugin, exists := asw.socketFileToInfo[pluginInfo.SocketPath]\n\treturn exists && (actualStatePlugin.Timestamp == pluginInfo.Timestamp)\n}\n\nfunc (asw *actualStateOfWorld) AddPlugin(pluginInfo PluginInfo) error ", "output": "{\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tif pluginInfo.SocketPath == \"\" {\n\t\treturn fmt.Errorf(\"socket path is empty\")\n\t}\n\tif _, ok := asw.socketFileToInfo[pluginInfo.SocketPath]; ok {\n\t\tklog.V(2).Infof(\"Plugin (Path %s) exists in actual state cache\", pluginInfo.SocketPath)\n\t}\n\tasw.socketFileToInfo[pluginInfo.SocketPath] = pluginInfo\n\treturn nil\n}"} {"input": "package itsyouonline\n\nimport (\n\t\"gopkg.in/validator.v2\"\n)\n\n\ntype SeeView struct {\n\tCategory string `json:\"category\" validate:\"nonzero\"`\n\tContent_type string `json:\"content_type\" validate:\"nonzero\"`\n\tCreation_date string `json:\"creation_date\" validate:\"nonzero\"`\n\tEnd_date string `json:\"end_date\" validate:\"nonzero\"`\n\tGlobalid string `json:\"globalid\" validate:\"nonzero\"`\n\tKeystore_label string `json:\"keystore_label\" validate:\"nonzero\"`\n\tLink string `json:\"link\" validate:\"nonzero\"`\n\tMarkdown_full_description string `json:\"markdown_full_description\" validate:\"nonzero\"`\n\tMarkdown_short_description string `json:\"markdown_short_description\" validate:\"nonzero\"`\n\tSignature string `json:\"signature\" validate:\"nonzero\"`\n\tStart_date string `json:\"start_date\" validate:\"nonzero\"`\n\tUniqueid string `json:\"uniqueid\" validate:\"nonzero\"`\n\tUsername string `json:\"username\" validate:\"nonzero\"`\n\tVersion int `json:\"version\" validate:\"nonzero\"`\n}\n\n\n\nfunc (s SeeView) Validate() error ", "output": "{\n\n\treturn validator.Validate(s)\n}"} {"input": "package mailru\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/markbates/goth\"\n)\n\n\ntype Session struct {\n\tAuthURL string\n\tAccessToken string\n\tRefreshToken string\n\tExpiresAt time.Time\n}\n\n\nfunc (s *Session) GetAuthURL() (string, error) {\n\tif s.AuthURL == \"\" {\n\t\treturn \"\", errors.New(goth.NoAuthUrlErrorMessage)\n\t}\n\n\treturn s.AuthURL, nil\n}\n\n\n\n\n\nfunc (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {\n\tp := provider.(*Provider)\n\ttoken, err := p.oauthConfig.Exchange(goth.ContextForClient(p.Client()), params.Get(\"code\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !token.Valid() {\n\t\treturn \"\", errors.New(\"invalid token received from provider\")\n\t}\n\n\ts.AccessToken = token.AccessToken\n\ts.RefreshToken = token.RefreshToken\n\ts.ExpiresAt = token.Expiry\n\n\treturn s.AccessToken, err\n}\n\n\nfunc (p *Provider) UnmarshalSession(data string) (goth.Session, error) {\n\tsess := new(Session)\n\terr := json.NewDecoder(strings.NewReader(data)).Decode(&sess)\n\treturn sess, err\n}\n\nfunc (s *Session) Marshal() string ", "output": "{\n\tb, _ := json.Marshal(s)\n\treturn string(b)\n}"} {"input": "package types\n\nimport \"fmt\"\n\ntype IntegerValue struct {\n\tValue int64\n}\n\n\n\nfunc (v *IntegerValue) GetType() string {\n\treturn \"integer\"\n}\n\nfunc (v *IntegerValue) IsValue() bool {\n\treturn true\n}\n\nfunc (v *IntegerValue) ConvertTo(t string) (ValueType, error) {\n\treturn nil, fmt.Errorf(\"cannot convert integer to %s: does not implement yet\", t)\n}\n\nfunc (v *IntegerValue) EqualTo(t ValueType) bool {\n\tif v2, ok := t.(*IntegerValue); ok {\n\t\tif v2.Value == v.Value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc NewIntegerValue(v int64) *IntegerValue {\n\treturn &IntegerValue{Value: v}\n}\n\nfunc (v *IntegerValue) ToString() string ", "output": "{\n\treturn fmt.Sprint(v.Value)\n}"} {"input": "package v1\n\nimport (\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\n\n\nfunc SetDefaults_HorizontalPodAutoscaler(obj *HorizontalPodAutoscaler) {\n\tif obj.Spec.MinReplicas == nil {\n\t\tminReplicas := int32(1)\n\t\tobj.Spec.MinReplicas = &minReplicas\n\t}\n}\n\nfunc addDefaultingFuncs(scheme *runtime.Scheme) error ", "output": "{\n\treturn scheme.AddDefaultingFuncs(\n\t\tSetDefaults_HorizontalPodAutoscaler,\n\t)\n}"} {"input": "package storageimportexport\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" storageimportexport/2016-11-01\"\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\n\nfunc SquareRoot(x float64) float64 {\n\treturn math.Sqrt(x)\n}\n\nfunc main() {\n\ttimes := 16\n\tdelta := float64(0.000001)\n\tfor i := 0; i < times; i++ {\n\t\tsquareroot := SquareRoot(float64(i))\n\t\tnewton := Newton(float64(i))\n\t\tfmt.Println(i, \"squared:\")\n\t\tfmt.Println(\" SquareRoot:\", squareroot)\n\t\tfmt.Println(\" Newton :\", newton)\n\t\tdiff := math.Abs(squareroot - newton)\n\t\tif diff == 0.0 {\n\t\t\tfmt.Println(\" Difference: 0.0\")\n\t\t} else if diff < delta {\n\t\t\tfmt.Println(\" Difference: 0.0 [\", diff, \"< DELTA of\", delta, \"]\")\n\t\t} else {\n\t\t\tfmt.Println(\" Difference:\", diff)\n\t\t}\n\t}\n}\n\nfunc Newton(x float64) float64 ", "output": "{\n\tif x == 0 {\n\t\treturn 0\n\t}\n\tz := 1.0\n\tfor i := 0; i < int(x); i++ {\n\t\tz = z - ((math.Pow(z, 2) - x) / (2 * z))\n\t}\n\treturn z\n}"} {"input": "package control\n\nimport (\n\t\"fmt\"\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/rancherio/os/util\"\n)\n\n\n\nfunc devAction(c *cli.Context) ", "output": "{\n\tfmt.Println(util.ResolveDevice(c.Args()[0]))\n}"} {"input": "package trayicon\n\nimport (\n\t\"errors\"\n\n\t\"github.com/godbus/dbus\"\n\t\"github.com/linuxdeepin/go-lib/dbusutil\"\n\tx \"github.com/linuxdeepin/go-x11-client\"\n)\n\nconst (\n\tdbusServiceName = \"com.deepin.dde.TrayManager\"\n\tdbusInterface = dbusServiceName\n\tdbusPath = \"/com/deepin/dde/TrayManager\"\n)\n\nfunc (*TrayManager) GetInterfaceName() string {\n\treturn dbusInterface\n}\n\n\nfunc (m *TrayManager) Manage() (ok bool, busErr *dbus.Error) {\n\tlogger.Debug(\"call Manage by dbus\")\n\n\terr := m.sendClientMsgMANAGER()\n\tif err != nil {\n\t\tlogger.Warning(err)\n\t\treturn false, dbusutil.ToError(err)\n\t}\n\treturn true, nil\n}\n\n\n\n\n\nfunc (m *TrayManager) EnableNotification(win uint32, enabled bool) *dbus.Error {\n\tm.mutex.Lock()\n\ticon, ok := m.icons[x.Window(win)]\n\tm.mutex.Unlock()\n\tif !ok {\n\t\treturn dbusutil.ToError(errors.New(\"icon not found\"))\n\t}\n\n\ticon.mu.Lock()\n\ticon.notify = enabled\n\ticon.mu.Unlock()\n\treturn nil\n}\n\nfunc (m *TrayManager) GetName(win uint32) (name string, busErr *dbus.Error) ", "output": "{\n\tm.mutex.Lock()\n\ticon, ok := m.icons[x.Window(win)]\n\tm.mutex.Unlock()\n\tif !ok {\n\t\treturn \"\", dbusutil.ToError(errors.New(\"icon not found\"))\n\t}\n\treturn icon.getName(), nil\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype animal struct {\n\tfood string\n\tlocomotion string\n\tnoise string\n}\n\n\n\nfunc (a *animal) Move() {\n\tfmt.Println(a.locomotion)\n}\n\nfunc (a *animal) Speak() {\n\tfmt.Println(a.noise)\n}\n\nfunc main() {\n\treader := bufio.NewReader(os.Stdin)\n\n\tfor {\n\t\tfmt.Print(\"> \")\n\t\tinput, _ := reader.ReadString('\\n')\n\t\ts := strings.Split(strings.TrimSpace(input), \" \")\n\n\t\ta := new(animal)\n\t\tswitch s[0] {\n\t\tcase \"cow\":\n\t\t\ta.food = \"grass\"\n\t\t\ta.locomotion = \"walk\"\n\t\t\ta.noise = \"moo\"\n\t\tcase \"bird\":\n\t\t\ta.food = \"worms\"\n\t\t\ta.locomotion = \"fly\"\n\t\t\ta.noise = \"poop\"\n\t\tcase \"snake\":\n\t\t\ta.food = \"mice\"\n\t\t\ta.locomotion = \"slither\"\n\t\t\ta.noise = \"hsss\"\n\t\t}\n\n\t\tswitch s[1] {\n\t\tcase \"eat\":\n\t\t\ta.Eat()\n\t\tcase \"speak\":\n\t\t\ta.Speak()\n\t\tcase \"move\":\n\t\t\ta.Move()\n\t\t}\n\t}\n}\n\nfunc (a *animal) Eat() ", "output": "{\n\tfmt.Println(a.food)\n}"} {"input": "package autorestart\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"os/signal\"\n\t\"path/filepath\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/tillberg/watcher\"\n)\n\nfunc logf(format string, args ...interface{}) {\n\tlog.Printf(\"[autorestart] \"+format+\"\\n\", args...)\n}\n\nconst errorPath = \"*error*\"\n\nvar _exePath = errorPath\n\n\n\n\n\n\nfunc RestartOnChange() {\n\tnotifyChan := NotifyOnChange(true)\n\t<-notifyChan\n\tlogf(\"%s changed. Restarting via exec.\", getExePath())\n\ttime.Sleep(1 * time.Millisecond)\n\tRestartViaExec()\n}\n\n\n\n\nfunc NotifyOnChange(usePolling bool) chan bool {\n\tnotifyChan := make(chan bool)\n\tgo func() {\n\t\texePath := getExePath()\n\t\tif exePath == errorPath {\n\t\t\treturn\n\t\t}\n\t\tnotify, err := watcher.WatchExecutable(exePath, usePolling)\n\t\tif err != nil {\n\t\t\tlogf(\"Failed to initialize watcher: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tfor range notify {\n\t\t\tnotifyChan <- true\n\t\t}\n\t}()\n\treturn notifyChan\n}\n\n\n\n\n\nfunc RestartViaExec() {\n\texePath := getExePath()\n\tif exePath == errorPath {\n\t\treturn\n\t}\n\tfor {\n\t\terr := syscall.Exec(exePath, os.Args, os.Environ())\n\t\tlogf(\"syscall.Exec failed [%v], trying again in one second...\", err)\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}\n\nfunc NotifyOnSighup() chan os.Signal {\n\tsigChan := make(chan os.Signal)\n\tsignal.Notify(sigChan, syscall.SIGHUP)\n\treturn sigChan\n}\n\nfunc getExePath() string ", "output": "{\n\tvar err error\n\tif _exePath == errorPath {\n\t\t_exePath, err = exec.LookPath(os.Args[0])\n\t\tif err != nil {\n\t\t\tlogf(\"Failed to resolve path to current program: %s\", err)\n\t\t\t_exePath = errorPath\n\t\t} else {\n\t\t\t_exePath, err = filepath.Abs(_exePath)\n\t\t\tif err != nil {\n\t\t\t\tlogf(\"Failed to resolve absolute path to current program: %s\", err)\n\t\t\t\t_exePath = errorPath\n\t\t\t} else {\n\t\t\t\t_exePath = filepath.Clean(_exePath)\n\t\t\t}\n\t\t}\n\t}\n\treturn _exePath\n}"} {"input": "package secretbox\n\nimport (\n\t\"crypto/rand\"\n\t\"fmt\"\n\n\t\"golang.org/x/crypto/nacl/secretbox\"\n\n\t\"k8s.io/apiserver/pkg/storage/value\"\n)\n\n\n\n\ntype secretboxTransformer struct {\n\tkey [32]byte\n}\n\nconst nonceSize = 24\n\n\n\nfunc NewSecretboxTransformer(key [32]byte) value.Transformer {\n\treturn &secretboxTransformer{key: key}\n}\n\nfunc (t *secretboxTransformer) TransformFromStorage(data []byte, context value.Context) ([]byte, bool, error) {\n\tif len(data) < (secretbox.Overhead + nonceSize) {\n\t\treturn nil, false, fmt.Errorf(\"the stored data was shorter than the required size\")\n\t}\n\tvar nonce [nonceSize]byte\n\tcopy(nonce[:], data[:nonceSize])\n\tdata = data[nonceSize:]\n\tout := make([]byte, 0, len(data)-secretbox.Overhead)\n\tresult, ok := secretbox.Open(out, data, &nonce, &t.key)\n\tif !ok {\n\t\treturn nil, false, fmt.Errorf(\"output array was not large enough for encryption\")\n\t}\n\treturn result, false, nil\n}\n\n\n\nfunc (t *secretboxTransformer) TransformToStorage(data []byte, context value.Context) ([]byte, error) ", "output": "{\n\tvar nonce [nonceSize]byte\n\tn, err := rand.Read(nonce[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif n != nonceSize {\n\t\treturn nil, fmt.Errorf(\"unable to read sufficient random bytes\")\n\t}\n\treturn secretbox.Seal(nonce[:], data, &nonce, &t.key), nil\n}"} {"input": "package description\n\nimport (\n\t\"github.com/dropbox/goprotoc/gogoproto\"\n\t\"github.com/dropbox/goprotoc/plugin/testgen\"\n\t\"github.com/dropbox/goprotoc/protoc-gen-dgo/generator\"\n)\n\ntype test struct {\n\t*generator.Generator\n}\n\n\n\nfunc (p *test) Generate(imports generator.PluginImports, file *generator.FileDescriptor) bool {\n\tused := false\n\ttestingPkg := imports.NewImport(\"testing\")\n\tfor _, message := range file.Messages() {\n\t\tif !gogoproto.HasDescription(file.FileDescriptorProto, message.DescriptorProto) ||\n\t\t\t!gogoproto.HasTestGen(file.FileDescriptorProto, message.DescriptorProto) {\n\t\t\tcontinue\n\t\t}\n\t\tused = true\n\t}\n\n\tif used {\n\t\tlocalName := generator.FileName(file)\n\t\tp.P(`func Test`, localName, `Description(t *`, testingPkg.Use(), `.T) {`)\n\t\tp.In()\n\t\tp.P(localName, `Description()`)\n\t\tp.Out()\n\t\tp.P(`}`)\n\n\t}\n\treturn used\n}\n\nfunc init() {\n\ttestgen.RegisterTestPlugin(NewTest)\n}\n\nfunc NewTest(g *generator.Generator) testgen.TestPlugin ", "output": "{\n\treturn &test{g}\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification struct {\n\n\tPredefinedScalingMetricType string `json:\"PredefinedScalingMetricType,omitempty\"`\n\n\tResourceLabel string `json:\"ResourceLabel,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) AWSCloudFormationType() string {\n\treturn \"AWS::AutoScalingPlans::ScalingPlan.PredefinedScalingMetricSpecification\"\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\n\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSAutoScalingPlansScalingPlan_PredefinedScalingMetricSpecification) SetDependsOn(dependencies []string) ", "output": "{\n\tr._dependsOn = dependencies\n}"} {"input": "package jsonapi\n\nimport \"fmt\"\n\ntype Cache interface {\n\tAdd(ResourceObject) (bool, ResourceObject)\n}\n\ntype coreCache struct {\n\tstore map[string]ResourceObject\n}\n\n\n\nfunc (cache *coreCache) Add(n ResourceObject) (bool, ResourceObject) {\n\tkey := fmt.Sprintf(\"%s=>%s\", n.GetType(), n.GetID())\n\tif existing, ok := cache.store[key]; ok {\n\t\treturn false, existing\n\t}\n\tcache.store[key] = n\n\treturn true, n\n}\n\nfunc NewCache() Cache ", "output": "{\n\treturn &coreCache{\n\t\tstore: make(map[string]ResourceObject),\n\t}\n}"} {"input": "package segment\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/checkr/flagr/swagger_gen/models\"\n)\n\n\nconst DeleteSegmentOKCode int = 200\n\n\ntype DeleteSegmentOK struct {\n}\n\n\nfunc NewDeleteSegmentOK() *DeleteSegmentOK {\n\n\treturn &DeleteSegmentOK{}\n}\n\n\n\n\n\ntype DeleteSegmentDefault struct {\n\t_statusCode int\n\n\tPayload *models.Error `json:\"body,omitempty\"`\n}\n\n\nfunc NewDeleteSegmentDefault(code int) *DeleteSegmentDefault {\n\tif code <= 0 {\n\t\tcode = 500\n\t}\n\n\treturn &DeleteSegmentDefault{\n\t\t_statusCode: code,\n\t}\n}\n\n\nfunc (o *DeleteSegmentDefault) WithStatusCode(code int) *DeleteSegmentDefault {\n\to._statusCode = code\n\treturn o\n}\n\n\nfunc (o *DeleteSegmentDefault) SetStatusCode(code int) {\n\to._statusCode = code\n}\n\n\nfunc (o *DeleteSegmentDefault) WithPayload(payload *models.Error) *DeleteSegmentDefault {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *DeleteSegmentDefault) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}\n\n\nfunc (o *DeleteSegmentDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(o._statusCode)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\nfunc (o *DeleteSegmentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(200)\n}"} {"input": "package get\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewGetPollersIdentifierDataParams() *GetPollersIdentifierDataParams {\n\tvar ()\n\treturn &GetPollersIdentifierDataParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\n\n\n\ntype GetPollersIdentifierDataParams struct {\n\n\tIdentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *GetPollersIdentifierDataParams) WithIdentifier(identifier string) *GetPollersIdentifierDataParams {\n\to.Identifier = identifier\n\treturn o\n}\n\n\nfunc (o *GetPollersIdentifierDataParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"identifier\", o.Identifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewGetPollersIdentifierDataParamsWithTimeout(timeout time.Duration) *GetPollersIdentifierDataParams ", "output": "{\n\tvar ()\n\treturn &GetPollersIdentifierDataParams{\n\n\t\ttimeout: timeout,\n\t}\n}"} {"input": "package editor\n\nimport (\n\t\"os/user\"\n\t\"path/filepath\"\n)\n\ntype EditorConfig struct {\n\tDefaultKeymap KeyMap\n}\n\n\n\nfunc LoadConfig(configFile string) (*EditorConfig, error) {\n\treturn nil, nil\n}\n\nfunc GetConfigFileLocation() (string, error) ", "output": "{\n\tuser, err := user.Current()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(user.HomeDir, \".orb\", \"config.json\"), nil\n}"} {"input": "package backoff\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\n\ntype BackOffContext interface {\n\tBackOff\n\tContext() context.Context\n}\n\ntype backOffContext struct {\n\tBackOff\n\tctx context.Context\n}\n\n\n\n\nfunc WithContext(b BackOff, ctx context.Context) BackOffContext {\n\tif ctx == nil {\n\t\tpanic(\"nil context\")\n\t}\n\n\tif b, ok := b.(*backOffContext); ok {\n\t\treturn &backOffContext{\n\t\t\tBackOff: b.BackOff,\n\t\t\tctx: ctx,\n\t\t}\n\t}\n\n\treturn &backOffContext{\n\t\tBackOff: b,\n\t\tctx: ctx,\n\t}\n}\n\nfunc ensureContext(b BackOff) BackOffContext {\n\tif cb, ok := b.(BackOffContext); ok {\n\t\treturn cb\n\t}\n\treturn WithContext(b, context.Background())\n}\n\nfunc (b *backOffContext) Context() context.Context {\n\treturn b.ctx\n}\n\n\n\nfunc (b *backOffContext) NextBackOff() time.Duration ", "output": "{\n\tselect {\n\tcase <-b.ctx.Done():\n\t\treturn Stop\n\tdefault:\n\t}\n\tnext := b.BackOff.NextBackOff()\n\tif deadline, ok := b.ctx.Deadline(); ok && deadline.Sub(time.Now()) < next {\n\t\treturn Stop\n\t}\n\treturn next\n}"} {"input": "package sqltrace\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync/atomic\"\n)\n\nfunc boolToInt64(f bool) int64 {\n\tif f {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\ntype sqlTrace struct {\n\ton int64 \n\n\t*log.Logger\n}\n\nfunc newSQLTrace() *sqlTrace {\n\treturn &sqlTrace{\n\t\tLogger: log.New(os.Stdout, \"hdb \", log.Ldate|log.Ltime|log.Lshortfile),\n\t}\n}\nfunc (t *sqlTrace) On() bool { return atomic.LoadInt64(&t.on) != 0 }\nfunc (t *sqlTrace) SetOn(on bool) { atomic.StoreInt64(&t.on, boolToInt64(on)) }\n\ntype flagValue struct {\n\tt *sqlTrace\n}\n\n\n\nfunc (v flagValue) String() string {\n\tif v.t == nil {\n\t\treturn \"\"\n\t}\n\treturn strconv.FormatBool(v.t.On())\n}\n\nfunc (v flagValue) Set(s string) error {\n\tf, err := strconv.ParseBool(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.t.SetOn(f)\n\treturn nil\n}\n\nvar tracer = newSQLTrace()\n\nfunc init() {\n\tflag.Var(&flagValue{t: tracer}, \"hdb.sqlTrace\", \"enabling hdb sql trace\")\n}\n\n\nfunc On() bool { return tracer.On() }\n\n\nfunc SetOn(on bool) { tracer.SetOn(on) }\n\n\nfunc Trace(v ...interface{}) { tracer.Print(v...) }\n\n\nfunc Tracef(format string, v ...interface{}) { tracer.Printf(format, v...) }\n\n\nfunc Traceln(v ...interface{}) { tracer.Println(v...) }\n\nfunc (v flagValue) IsBoolFlag() bool ", "output": "{ return true }"} {"input": "package adt\n\ntype Stack struct {\n\ttop *Element\n\tsize int\n}\n \ntype Element struct {\n\tvalue interface{} \n\tnext *Element\n}\n\n\nfunc NewStack() *Stack {\n\treturn new(Stack)\n\n}\n\n\nfunc (s *Stack) Len() int {\n\treturn s.size\n}\n\n\n\n\n\nfunc (s *Stack) Push(value interface{}) {\n\ts.top = &Element{value, s.top}\n\ts.size++\n}\n \n\n\nfunc (s *Stack) Pop() (value interface{}) {\n\tif s.size > 0 {\n\t\tvalue, s.top = s.top.value, s.top.next\n\t\ts.size--\n\t\treturn\n\t}\n\treturn nil\n}\n\nfunc (s *Stack) IsEmpty() bool ", "output": "{\n\treturn s.Len()==0\n}"} {"input": "package bench\n\nimport (\n\t\"fmt\"\n\t\"github.com/satori/go.uuid\"\n\t. \"github.com/topfreegames/offers/testing\"\n\t\"net/http\"\n\t\"testing\"\n)\n\nvar gameResult *http.Response\n\n\n\nfunc BenchmarkInsertGame(b *testing.B) {\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\troute := getRoute(fmt.Sprintf(\"/games/%s\", uuid.NewV4().String()))\n\t\tres, err := putTo(route, map[string]interface{}{\n\t\t\t\"name\": fmt.Sprintf(\"game-%d\", i),\n\t\t})\n\t\tvalidateResp(res, err)\n\t\tres.Body.Close()\n\n\t\tgameResult = res\n\t}\n}\n\nfunc BenchmarkUpdateGame(b *testing.B) {\n\tdb, err := GetPerfDB()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tgames, err := getGames(&db)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tlength := len(games)\n\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tgame := games[i%length]\n\t\troute := getRoute(fmt.Sprintf(\"/games/%s\", game.ID))\n\t\tres, err := putTo(route, map[string]interface{}{\n\t\t\t\"name\": fmt.Sprintf(\"%s-%d\", game.Name, i),\n\t\t})\n\t\tvalidateResp(res, err)\n\t\tres.Body.Close()\n\n\t\tgameResult = res\n\t}\n}\n\nfunc BenchmarkListGames(b *testing.B) ", "output": "{\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\troute := getRoute(\"/games\")\n\t\tres, err := get(route)\n\t\tvalidateResp(res, err)\n\t\tres.Body.Close()\n\n\t\tgameResult = res\n\t}\n}"} {"input": "package github\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/hashicorp/vault/api\"\n)\n\ntype CLIHandler struct{}\n\n\n\nfunc (h *CLIHandler) Help() string {\n\thelp := `\nThe GitHub credential provider allows you to authenticate with GitHub.\nTo use it, specify the \"token\" var with the \"-var\" flag. The value should\nbe a personal access token for your GitHub account. You can generate a personal\naccess token on your account settings page on GitHub.\n\n Example: vault auth -method=github -var=\"token=\"\n\n\t`\n\n\treturn strings.TrimSpace(help)\n}\n\nfunc (h *CLIHandler) Auth(c *api.Client, m map[string]string) (string, error) ", "output": "{\n\tmount, ok := m[\"mount\"]\n\tif !ok {\n\t\tmount = \"github\"\n\t}\n\n\ttoken, ok := m[\"token\"]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"'token' var must be set\")\n\t}\n\n\tpath := fmt.Sprintf(\"auth/%s/login\", mount)\n\tsecret, err := c.Logical().Write(path, map[string]interface{}{\n\t\t\"token\": token,\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif secret == nil {\n\t\treturn \"\", fmt.Errorf(\"empty response from credential provider\")\n\t}\n\n\treturn secret.Auth.ClientToken, nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"text/template\"\n)\n\n\ntype Command struct {\n\tRun func(context *Context)\n\tFlag flag.FlagSet\n\tName string\n\tUsageLine string\n\tShort string\n\tLong string\n}\n\n\n\ntype PackageFile interface {\n\tencoding.BinaryMarshaler\n\tPackagePath() string \n}\n\nvar commands = []*Command{\n\tinitCmd,\n\tpackageCmd,\n}\n\nvar usageTempl = `gotizen is a tool for bulding and deploying Tizen OS packages.\n\nUsage:\n\n\tgotizen command [arguments]\n\nThe commands are:\n{{range .}}\n\t{{.Name | printf \"%-11s\"}} {{.Short}}{{end}}\n\n`\n\n\n\nfunc main() {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tctx, err := BuildContext(wd)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tflag.Usage = usage\n\tflag.Parse()\n\tlog.SetFlags(0)\n\targs := flag.Args()\n\n\tif len(args) < 1 {\n\t\tusage()\n\t\tos.Exit(1)\n\t}\n\tfor _, cmd := range commands {\n\t\tif cmd.Name == args[0] {\n\t\t\terr = cmd.Flag.Parse(args[1:])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Print(err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tcmd.Run(ctx)\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\n\tfmt.Printf(\"Unknown submcommand: '%s'\\n\", args[0])\n\tos.Exit(1)\n}\n\nfunc usage() ", "output": "{\n\tt := template.New(\"tmpl\")\n\t_, err := t.Parse(usageTempl)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tt.Execute(os.Stderr, commands)\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"os\"\n \"io/ioutil\"\n \"strings\"\n \"sort\"\n \"bytes\"\n)\n\nfunc ReadFile(filename string) string {\n data, err := ioutil.ReadFile(filename)\n\n if err != nil {\n fmt.Fprintf(os.Stderr, \"Error: %v\\n\", err)\n return \"\"\n }\n\n return string(data)\n}\n\ntype Letter struct {\n Name string\n Count int\n}\n\ntype ByCount []Letter\n\n\nfunc (a ByCount) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a ByCount) Less(i, j int) bool { return a[i].Count > a[j].Count }\n\nfunc main() {\n directions := strings.Split(ReadFile(\"input.txt\"), \"\\n\")\n\n var col_letters bytes.Buffer\n var answer bytes.Buffer\n\n for x := 0; x < len(directions[0]); x++ {\n \n col_letters.Reset()\n\n \n for y := 0; y < len(directions) - 1; y++ {\n col_letters.WriteByte(directions[y][x])\n }\n\n var letter_counts []Letter\n \n found := make(map[string]bool)\n for _, letter := range strings.Split(col_letters.String(), \"\") {\n if found[letter] {\n continue\n }\n found[letter] = true\n letter_counts = append(letter_counts, Letter{Name: letter, Count: strings.Count(col_letters.String(), letter)})\n \t}\n\n \n sort.Sort(ByCount(letter_counts))\n \n answer.WriteString(letter_counts[0].Name)\n }\n fmt.Println(answer.String())\n}\n\nfunc (a ByCount) Len() int ", "output": "{ return len(a) }"} {"input": "package client\n\nimport (\n\t\"github.com/docker/notary/client/changelist\"\n\t\"github.com/docker/notary/tuf\"\n\t\"github.com/docker/notary/tuf/data\"\n)\n\n\n\n\n\nfunc witnessTargets(repo *tuf.Repo, invalid *tuf.Repo, role data.RoleName) error {\n\tif r, ok := repo.Targets[role]; ok {\n\t\tr.Dirty = true\n\t\treturn nil\n\t}\n\n\tif roleObj, err := repo.GetDelegationRole(role); err == nil && invalid != nil {\n\t\tif roleObj.Threshold > len(roleObj.Keys) {\n\t\t\treturn data.ErrInvalidRole{\n\t\t\t\tRole: role,\n\t\t\t\tReason: \"role does not specify enough valid signing keys to meet its required threshold\",\n\t\t\t}\n\t\t}\n\t\tif r, ok := invalid.Targets[role]; ok {\n\t\t\trepo.Targets[role] = r\n\t\t\tr.Dirty = true\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn data.ErrInvalidRole{\n\t\tRole: role,\n\t\tReason: \"this role is not known\",\n\t}\n}\n\nfunc (r *NotaryRepository) Witness(roles ...data.RoleName) ([]data.RoleName, error) ", "output": "{\n\tvar err error\n\tsuccessful := make([]data.RoleName, 0, len(roles))\n\tfor _, role := range roles {\n\t\tc := changelist.NewTUFChange(\n\t\t\tchangelist.ActionUpdate,\n\t\t\trole,\n\t\t\tchangelist.TypeWitness,\n\t\t\t\"\",\n\t\t\tnil,\n\t\t)\n\t\terr = r.changelist.Add(c)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tsuccessful = append(successful, role)\n\t}\n\treturn successful, err\n}"} {"input": "package wml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/wml\"\n)\n\n\n\nfunc TestWdCT_WrapTightMarshalUnmarshal(t *testing.T) {\n\tv := wml.NewWdCT_WrapTight()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := wml.NewWdCT_WrapTight()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestWdCT_WrapTightConstructor(t *testing.T) ", "output": "{\n\tv := wml.NewWdCT_WrapTight()\n\tif v == nil {\n\t\tt.Errorf(\"wml.NewWdCT_WrapTight must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed wml.WdCT_WrapTight should validate: %s\", err)\n\t}\n}"} {"input": "package policy\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/rightscale/rsc/rsapi\"\n)\n\nconst (\n\tAPIName = \"RightScale Policy API 1.0\"\n)\n\n\nvar commandValues rsapi.ActionCommands\n\n\n\n\n\nfunc (a *API) RunCommand(cmd string) (*http.Response, error) {\n\tc, err := a.ParseCommand(cmd, \"/api\", commandValues)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := a.BuildHTTPRequest(c.HTTPMethod, c.URI, \"1.0\", c.QueryParams, c.PayloadParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn a.PerformRequest(req)\n}\n\n\nfunc (a *API) ShowCommandHelp(cmd string) error {\n\treturn a.ShowHelp(cmd, \"/api\", commandValues)\n}\n\n\nfunc (a *API) ShowAPIActions(cmd string) error {\n\treturn a.ShowActions(cmd, \"/api\", commandValues)\n}\n\nfunc RegisterCommands(registrar rsapi.APICommandRegistrar) ", "output": "{\n\tcommandValues = rsapi.ActionCommands{}\n\tregistrar.RegisterActionCommands(APIName, GenMetadata, commandValues)\n}"} {"input": "package endpoint\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetEndpointOKCode int = 200\n\n\ntype GetEndpointOK struct {\n\n\tPayload []*models.Endpoint `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetEndpointOK() *GetEndpointOK {\n\n\treturn &GetEndpointOK{}\n}\n\n\nfunc (o *GetEndpointOK) WithPayload(payload []*models.Endpoint) *GetEndpointOK {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *GetEndpointOK) SetPayload(payload []*models.Endpoint) {\n\to.Payload = payload\n}\n\n\nfunc (o *GetEndpointOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tpayload := o.Payload\n\tif payload == nil {\n\t\tpayload = make([]*models.Endpoint, 0, 50)\n\t}\n\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) \n\t}\n}\n\n\nconst GetEndpointNotFoundCode int = 404\n\n\ntype GetEndpointNotFound struct {\n}\n\n\nfunc NewGetEndpointNotFound() *GetEndpointNotFound {\n\n\treturn &GetEndpointNotFound{}\n}\n\n\n\n\nfunc (o *GetEndpointNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}"} {"input": "package core\n\nimport (\n\t\"github.com/google/blueprint\"\n)\n\ntype generateBinary struct {\n\tgenerateLibrary\n}\n\n\nvar _ generateLibraryInterface = (*generateBinary)(nil)\nvar _ singleOutputModule = (*generateBinary)(nil)\nvar _ splittable = (*generateBinary)(nil)\nvar _ blueprint.Module = (*generateBinary)(nil)\n\nfunc (m *generateBinary) generateInouts(ctx blueprint.ModuleContext, g generatorBackend) []inout {\n\treturn generateLibraryInouts(m, ctx, g, m.Properties.Headers)\n}\n\n\n\nfunc (m *generateBinary) libExtension() string {\n\treturn \"\"\n}\n\n\n\nfunc (m *generateBinary) outputFileName() string {\n\treturn m.altName() + m.libExtension()\n}\n\n\n\nfunc (m *generateBinary) GenerateBuildActions(ctx blueprint.ModuleContext) {\n\tif isEnabled(m) {\n\t\tg := getBackend(ctx)\n\t\tg.genBinaryActions(m, ctx)\n\t}\n}\n\n\n\n\n\nfunc genBinaryFactory(config *bobConfig) (blueprint.Module, []interface{}) ", "output": "{\n\tmodule := &generateBinary{}\n\tmodule.generateCommon.init(&config.Properties, GenerateProps{})\n\n\treturn module, []interface{}{\n\t\t&module.SimpleName.Properties,\n\t\t&module.generateCommon.Properties,\n\t\t&module.Properties,\n\t}\n}"} {"input": "package versioned\n\nimport (\n\t\"fmt\"\n\n\tdiscovery \"k8s.io/client-go/discovery\"\n\trest \"k8s.io/client-go/rest\"\n\tflowcontrol \"k8s.io/client-go/util/flowcontrol\"\n\tnodev1alpha1 \"k8s.io/node-api/pkg/client/clientset/versioned/typed/node/v1alpha1\"\n)\n\ntype Interface interface {\n\tDiscovery() discovery.DiscoveryInterface\n\tNodeV1alpha1() nodev1alpha1.NodeV1alpha1Interface\n}\n\n\n\ntype Clientset struct {\n\t*discovery.DiscoveryClient\n\tnodeV1alpha1 *nodev1alpha1.NodeV1alpha1Client\n}\n\n\nfunc (c *Clientset) NodeV1alpha1() nodev1alpha1.NodeV1alpha1Interface {\n\treturn c.nodeV1alpha1\n}\n\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.DiscoveryClient\n}\n\n\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *Clientset {\n\tvar cs Clientset\n\tcs.nodeV1alpha1 = nodev1alpha1.NewForConfigOrDie(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)\n\treturn &cs\n}\n\n\nfunc New(c rest.Interface) *Clientset {\n\tvar cs Clientset\n\tcs.nodeV1alpha1 = nodev1alpha1.New(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClient(c)\n\treturn &cs\n}\n\nfunc NewForConfig(c *rest.Config) (*Clientset, error) ", "output": "{\n\tconfigShallowCopy := *c\n\tif configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {\n\t\tif configShallowCopy.Burst <= 0 {\n\t\t\treturn nil, fmt.Errorf(\"Burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0\")\n\t\t}\n\t\tconfigShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)\n\t}\n\tvar cs Clientset\n\tvar err error\n\tcs.nodeV1alpha1, err = nodev1alpha1.NewForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &cs, nil\n}"} {"input": "package get\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewGetPollersIdentifierDataParams() *GetPollersIdentifierDataParams {\n\tvar ()\n\treturn &GetPollersIdentifierDataParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\nfunc NewGetPollersIdentifierDataParamsWithTimeout(timeout time.Duration) *GetPollersIdentifierDataParams {\n\tvar ()\n\treturn &GetPollersIdentifierDataParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype GetPollersIdentifierDataParams struct {\n\n\tIdentifier string\n\n\ttimeout time.Duration\n}\n\n\n\n\n\nfunc (o *GetPollersIdentifierDataParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"identifier\", o.Identifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (o *GetPollersIdentifierDataParams) WithIdentifier(identifier string) *GetPollersIdentifierDataParams ", "output": "{\n\to.Identifier = identifier\n\treturn o\n}"} {"input": "package qb\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\nfunc TestSQLText(t *testing.T) {\n\ttext := SQLText(\"1\")\n\tassert.Equal(t, \"1\", text.Text)\n}\n\n\n\nfunc TestGetListFrom(t *testing.T) {\n\tvar c Clause\n\tc = ListClause{}\n\tassert.Equal(t, c, GetListFrom(c))\n\n\ttext := SQLText(\"SOME SQL\")\n\tc = GetListFrom(text)\n\tl, ok := c.(ListClause)\n\tassert.True(t, ok, \"Should have returned a ListClause\")\n\tassert.Equal(t, 1, len(l.Clauses))\n\tassert.Equal(t, text, l.Clauses[0])\n\n\tc = GetListFrom(2)\n\tl, ok = c.(ListClause)\n\tassert.True(t, ok, \"Should have returned a ListClause\")\n\tassert.Equal(t, 1, len(l.Clauses))\n\tassert.Equal(t, 2, l.Clauses[0].(BindClause).Value)\n\n\tc = GetListFrom(2, Bind(4))\n\tl, ok = c.(ListClause)\n\tassert.True(t, ok, \"Should have returned a ListClause\")\n\tassert.Equal(t, 2, len(l.Clauses))\n\tassert.Equal(t, 2, l.Clauses[0].(BindClause).Value)\n\tassert.Equal(t, 4, l.Clauses[1].(BindClause).Value)\n}\n\nfunc TestExists(t *testing.T) {\n\ts := Select()\n\n\te := Exists(s)\n\tassert.False(t, e.Not)\n\tassert.Equal(t, s, e.Select)\n\n\tne := NotExists(s)\n\tassert.True(t, ne.Not)\n\tassert.Equal(t, s, ne.Select)\n}\n\nfunc TestGetClauseFrom(t *testing.T) ", "output": "{\n\tvar c Clause\n\tc = SQLText(\"1\")\n\tassert.Equal(t, c, GetClauseFrom(c))\n\n\tc = GetClauseFrom(2)\n\tb, ok := c.(BindClause)\n\tassert.True(t, ok, \"Should have returned a BindClause\")\n\tassert.Equal(t, 2, b.Value)\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"runtime\"\n)\n\nvar i *int\n\n\n\nfunc final(ii *int) {\n fmt.Printf(\"finalizer called on int %d\\n\", *ii)\n}\n\nfunc assign() {\n ii := 10\n runtime.SetFinalizer(&ii, final)\n i = &ii\n}\n\nfunc main() {\n assign()\n i = nil\n runtime.GC()\n \n f(1)\n runtime.GC()\n \n}\n\nfunc f(x int) ", "output": "{\n pc, file, line, ok := runtime.Caller(0)\n if !ok {\n panic(\"runtime.Caller not OK!\")\n }\n fmt.Printf(\"pc = %d, file = %s, line = %d\\n\", pc, file, line)\n fmt.Printf(\"f %d\\n\", x)\n}"} {"input": "package design\n\n\n\n\n\n\n\nimport (\n\t\"fmt\"\n)\n\ntype PhoneBrand interface {\n\tSetSoft(s Soft)\n\tRun()\n}\ntype Soft interface {\n\tRun()\n}\ntype Nokia struct {\n\ts Soft\n}\n\n\nfunc (n Nokia) Run() {\n\tfmt.Println(\"nokia\")\n\tn.s.Run()\n}\n\ntype Game struct {\n}\n\nfunc (g Game) Run() {\n\tfmt.Println(\"手机游戏\")\n}\n\nfunc (n *Nokia) SetSoft(s Soft) ", "output": "{\n\tn.s = s\n}"} {"input": "package ftpclient\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\n\ntype Logger interface {\n\tLog(v ...interface{})\n\tLogf(format string, v ...interface{})\n}\n\n\nfunc NewDefaultLogger() Logger {\n\treturn &defaultLogger{\n\t\tlogger: log.New(os.Stdout, \"\", log.LstdFlags),\n\t}\n}\n\ntype defaultLogger struct {\n\tlogger *log.Logger\n}\n\n\n\nfunc (l defaultLogger) Logf(format string, args ...interface{}) {\n\tl.logger.Printf(format, args...)\n}\n\nfunc (l defaultLogger) Log(args ...interface{}) ", "output": "{\n\tl.logger.Println(args...)\n}"} {"input": "package elastic\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n)\n\n\n\nfunc TestMissingAggregation(t *testing.T) ", "output": "{\n\tagg := NewMissingAggregation().Field(\"price\")\n\tdata, err := json.Marshal(agg.Source())\n\tif err != nil {\n\t\tt.Fatalf(\"marshaling to JSON failed: %v\", err)\n\t}\n\tgot := string(data)\n\texpected := `{\"missing\":{\"field\":\"price\"}}`\n\tif got != expected {\n\t\tt.Errorf(\"expected\\n%s\\n,got:\\n%s\", expected, got)\n\t}\n}"} {"input": "package safepackets\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\n\t\"github.com/mark-rushakoff/go_tftpd/packets\"\n)\n\ntype SafeError struct {\n\tCode packets.ErrorCode\n\tMessage string\n}\n\nfunc NewFileNotFoundError() *SafeError {\n\treturn &SafeError{\n\t\tCode: packets.FileNotFound,\n\t\tMessage: \"File not found\",\n\t}\n}\n\n\n\nfunc NewAncientAckError() *SafeError {\n\treturn &SafeError{\n\t\tCode: packets.Undefined,\n\t\tMessage: \"Received unexpectedly old Ack\",\n\t}\n}\n\nfunc (e *SafeError) Equals(other *SafeError) bool {\n\treturn e.Code == other.Code && e.Message == other.Message\n}\n\nfunc (e *SafeError) Bytes() []byte {\n\tbuf := &bytes.Buffer{}\n\tbinary.Write(buf, binary.BigEndian, packets.ErrorOpcode)\n\tbinary.Write(buf, binary.BigEndian, e.Code)\n\tbuf.WriteString(e.Message)\n\tbuf.WriteByte(0)\n\treturn buf.Bytes()\n}\n\nfunc NewAccessViolationError(message string) *SafeError ", "output": "{\n\treturn &SafeError{\n\t\tCode: packets.AccessViolation,\n\t\tMessage: message,\n\t}\n}"} {"input": "package kafka\n\nimport (\n\t\"encoding/binary\"\n\t\"hash/crc32\"\n)\n\ntype crc32Writer struct {\n\ttable *crc32.Table\n\tbuffer [8]byte\n\tcrc32 uint32\n}\n\n\n\nfunc (w *crc32Writer) writeInt8(i int8) {\n\tw.buffer[0] = byte(i)\n\tw.update(w.buffer[:1])\n}\n\nfunc (w *crc32Writer) writeInt16(i int16) {\n\tbinary.BigEndian.PutUint16(w.buffer[:2], uint16(i))\n\tw.update(w.buffer[:2])\n}\n\nfunc (w *crc32Writer) writeInt32(i int32) {\n\tbinary.BigEndian.PutUint32(w.buffer[:4], uint32(i))\n\tw.update(w.buffer[:4])\n}\n\nfunc (w *crc32Writer) writeInt64(i int64) {\n\tbinary.BigEndian.PutUint64(w.buffer[:8], uint64(i))\n\tw.update(w.buffer[:8])\n}\n\nfunc (w *crc32Writer) writeBytes(b []byte) {\n\tn := len(b)\n\tif b == nil {\n\t\tn = -1\n\t}\n\tw.writeInt32(int32(n))\n\tw.update(b)\n}\n\nfunc (w *crc32Writer) Write(b []byte) (int, error) {\n\tw.update(b)\n\treturn len(b), nil\n}\n\nfunc (w *crc32Writer) WriteString(s string) (int, error) {\n\tw.update([]byte(s))\n\treturn len(s), nil\n}\n\nfunc (w *crc32Writer) update(b []byte) ", "output": "{\n\tw.crc32 = crc32.Update(w.crc32, w.table, b)\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"testing\"\n)\n\nconst (\n\tmetricCount = 4\n)\n\nvar (\n\tfluentdJson = Message{1, 4, 456, 0}\n)\n\ntype Message struct {\n\tup int\n\tbufferQueueLength int\n\tbufferTotalQueuedSize float64\n\tretryCount int\n}\n\nfunc checkFluentdStatus(t *testing.T, status []byte, metricCount int) {\n\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(status))\n\t})\n\tserver := httptest.NewServer(handler)\n\n\te := NewExporter(server.URL)\n\tch := make(chan prometheus.Metric)\n\n\tgo func() {\n\t\tdefer close(ch)\n\t\te.Collect(ch)\n\t}()\n\n\tm := <-ch\n\tif m == nil {\n\t\tt.Error(\"expected metric but got nil\")\n\t}\n\n\tif <-ch != nil {\n\t\tt.Error(\"expected closed channel\")\n\t}\n}\n\n\n\nfunc TestFluentdStatus(t *testing.T) ", "output": "{\n\tdata, err := json.Marshal(fluentdJson)\n\tif err != nil {\n\t\tt.Error(err)\n\t\tos.Exit(1)\n\t}\n\n\tcheckFluentdStatus(t, data, metricCount)\n}"} {"input": "package stager\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/hatofmonkeys/cloudfocker/utils\"\n\n\t\"github.com/cloudfoundry-incubator/linux-circus/buildpackrunner\"\n\t\"github.com/cloudfoundry-incubator/runtime-schema/models\"\n)\n\ntype BuildpackRunner interface {\n\tRun() error\n}\n\nfunc RunBuildpack(writer io.Writer, runner BuildpackRunner) error {\n\tfmt.Fprintln(writer, \"Running Buildpacks...\")\n\treturn runner.Run()\n}\n\n\n\nfunc ValidateStagedApp(cloudfockerHome string) error {\n\tif _, err := os.Stat(cloudfockerHome + \"/droplet/app\"); err != nil {\n\t\treturn fmt.Errorf(\"Staging failed - have you added a buildpack for this type of application?\")\n\t}\n\tif _, err := os.Stat(cloudfockerHome + \"/droplet/staging_info.yml\"); err != nil {\n\t\treturn fmt.Errorf(\"Staging failed - no staging info was produced by the matching buildpack!\")\n\t}\n\treturn nil\n}\n\nfunc prepareMd5BuildpacksDir(src string, dst string) {\n\tos.MkdirAll(src, 0755)\n\tos.MkdirAll(dst, 0755)\n\tvar err error\n\tdirs := []string{}\n\tif dirs, err = utils.SubDirs(src); err != nil {\n\t\tlog.Fatalf(\" %s\", err)\n\t}\n\tfor _, dir := range dirs {\n\t\tif err := os.Symlink(src+\"/\"+dir, dst+\"/\"+md5sum(dir)); err != nil {\n\t\t\tlog.Fatalf(\" %s\", err)\n\t\t}\n\t}\n}\n\nfunc md5sum(src string) string {\n\treturn fmt.Sprintf(\"%x\", md5.Sum([]byte(src)))\n}\n\nfunc NewBuildpackRunner(buildpackDir string) *buildpackrunner.Runner ", "output": "{\n\tprepareMd5BuildpacksDir(buildpackDir, \"/tmp/buildpacks\")\n\tvar err error\n\tdirs := []string{}\n\tif dirs, err = utils.SubDirs(buildpackDir); err != nil {\n\t\tlog.Fatalf(\" %s\", err)\n\t}\n\tconfig := models.NewCircusTailorConfig(dirs)\n\treturn buildpackrunner.New(&config)\n}"} {"input": "package apmsynthetics\n\n\ntype MonitorTypesEnum string\n\n\nconst (\n\tMonitorTypesScriptedBrowser MonitorTypesEnum = \"SCRIPTED_BROWSER\"\n\tMonitorTypesBrowser MonitorTypesEnum = \"BROWSER\"\n\tMonitorTypesScriptedRest MonitorTypesEnum = \"SCRIPTED_REST\"\n\tMonitorTypesRest MonitorTypesEnum = \"REST\"\n)\n\nvar mappingMonitorTypes = map[string]MonitorTypesEnum{\n\t\"SCRIPTED_BROWSER\": MonitorTypesScriptedBrowser,\n\t\"BROWSER\": MonitorTypesBrowser,\n\t\"SCRIPTED_REST\": MonitorTypesScriptedRest,\n\t\"REST\": MonitorTypesRest,\n}\n\n\n\n\nfunc GetMonitorTypesEnumValues() []MonitorTypesEnum ", "output": "{\n\tvalues := make([]MonitorTypesEnum, 0)\n\tfor _, v := range mappingMonitorTypes {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package badger\n\n\n\n\n\n\n\n\n\ntype ManagedDB struct {\n\t*DB\n}\n\n\n\n\n\n\nfunc OpenManaged(opts Options) (*ManagedDB, error) {\n\topts.managedTxns = true\n\tdb, err := Open(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ManagedDB{db}, nil\n}\n\n\n\nfunc (db *ManagedDB) NewTransaction(update bool) {\n\tpanic(\"Cannot use NewTransaction() for ManagedDB. Use NewTransactionAt() instead.\")\n}\n\n\n\n\n\n\nfunc (db *ManagedDB) NewTransactionAt(readTs uint64, update bool) *Txn {\n\ttxn := db.DB.NewTransaction(update)\n\ttxn.readTs = readTs\n\treturn txn\n}\n\n\n\n\n\n\nfunc (txn *Txn) CommitAt(commitTs uint64, callback func(error)) error {\n\tif !txn.db.opt.managedTxns {\n\t\treturn ErrManagedTxn\n\t}\n\ttxn.commitTs = commitTs\n\treturn txn.Commit(callback)\n}\n\n\nfunc (db *ManagedDB) PurgeVersionsBelow(key []byte, ts uint64) error {\n\ttxn := db.NewTransactionAt(ts, false)\n\tdefer txn.Discard()\n\treturn db.purgeVersionsBelow(txn, key, ts)\n}\n\n\n\n\n\nfunc (db *ManagedDB) GetSequence(_ []byte, _ uint64) (*Sequence, error) ", "output": "{\n\tpanic(\"Cannot use GetSequence for ManagedDB.\")\n}"} {"input": "package language \n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\n\n\n\nfunc DefaultAuthScopes() []string {\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t}\n}\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context ", "output": "{\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}"} {"input": "package keymanagement\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ImportKeyVersionRequest struct {\n\n\tKeyId *string `mandatory:\"true\" contributesTo:\"path\" name:\"keyId\"`\n\n\tImportKeyVersionDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ImportKeyVersionRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ImportKeyVersionRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request ImportKeyVersionRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ImportKeyVersionResponse struct {\n\n\tRawResponse *http.Response\n\n\tKeyVersion `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ImportKeyVersionResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ImportKeyVersionResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ImportKeyVersionRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\n\t\"github.com/abhishekkr/gol/golassert\"\n\t\"github.com/abhishekkr/gol/golhttpclient\"\n)\n\nvar sampleX = `\nPOST /what/is/path HTTP/1.1\nHost: 10.0.0.1:8080\nContent-Type: application/json\ncache-control: no-cache\nPostman-Token: xxx\n\n{\n \"start_date\": \"2029-04-19T00:00:00Z\",\n \"end_date\": \"2039-04-19T00:00:00Z\",\n \"name\": \"Alice\",\n \"friends\": [\n \"Bob\",\n \"Eve\"\n ]\n}\n`\n\nvar sampleY = `GET /?statuses=read,liked& page=1 HTTP/1.0\nHost: 1.1.2.0\ncache-control: no-cache\n\n`\n\nfunc main() {\n\tcheckSpecX()\n\tcheckSpecY()\n}\n\n\n\nfunc checkSpecY() {\n\tspec := &golhttpclient.HTTPSpec{Spec: sampleY}\n\tspec.Parse()\n\n\tgolassert.Equal(spec.Client.Method, \"GET\")\n\tgolassert.Equal(spec.Client.Protocol, \"HTTP/1.0\")\n\tgolassert.Equal(spec.Client.Url, \"/\")\n\tgolassert.EqualStringMap(spec.Client.GetParams,\n\t\tmap[string]string{\"Host\": \"1.1.2.0\", \"cache-control\": \"no-cache\"},\n\t)\n\tgolassert.EqualStringMap(spec.Client.HTTPHeaders,\n\t\tmap[string]string{\"Host\": \"1.1.2.0\", \"cache-control\": \"no-cache\"},\n\t)\n\tgolassert.Equal(\"\", spec.Client.Body.String())\n\tfmt.Println(\"passed for sampleY\")\n}\n\nfunc checkSpecX() ", "output": "{\n\tspec := &golhttpclient.HTTPSpec{Spec: sampleX}\n\tspec.Parse()\n\n\tgolassert.Equal(spec.Client.Method, \"POST\")\n\tgolassert.Equal(spec.Client.Protocol, \"HTTP/1.1\")\n\tgolassert.Equal(spec.Client.Url, \"/what/is/path\")\n\tgolassert.EqualStringMap(spec.Client.GetParams, map[string]string{})\n\tgolassert.EqualStringMap(spec.Client.HTTPHeaders,\n\t\tmap[string]string{\"Content-Type\": \"application/json\", \"Host\": \"10.0.0.1:8080\", \"Postman-Token\": \"xxx\", \"cache-control\": \"no-cache\"},\n\t)\n\tmatch, _ := regexp.MatchString(\"\\\\{.*start_date.*end_date.*name.*friends.*\\\\}\", spec.Client.Body.String())\n\tgolassert.Equal(match, true)\n\tfmt.Println(\"passed for sampleX\")\n}"} {"input": "package lena\n\nimport (\n\t\"bytes\"\n\t\"code.google.com/p/go.image/tiff\"\n\t\"errors\"\n\t\"image\"\n)\n\n\n\nfunc Image() (img image.Image, err error) ", "output": "{\n\tdata, err := Asset(\"data/lena_std.tif\")\n\tif len(data) == 0 {\n\t\terr = errors.New(\"len(data) == 0\")\n\t\treturn nil, err\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tiff.Decode(bytes.NewBuffer(data))\n}"} {"input": "package gwf\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n)\n\n\ntype Context struct {\n\tw http.ResponseWriter\n\tr *http.Request\n\n\tpath []string\n}\n\ntype Module interface {\n\tAction(*Context)\n}\n\ntype Dispatcher struct {\n\tmodules map[string]Module\n}\n\nfunc (c *Context) Request() *http.Request {\n\treturn c.r\n}\n\nfunc (c *Context) Writer() http.ResponseWriter {\n\treturn c.w\n}\n\nfunc (c *Context) Init(w http.ResponseWriter, r *http.Request) {\n\tc.w, c.r = w, r\n\n\tpath := strings.Split(r.URL.Path, \"/\")\n\tc.path = path[1:]\n}\n\nfunc (c *Context) Path(index int) (string, bool) {\n\tif index < 0 || index >= len(c.path) {\n\t\treturn \"\", false\n\t} else {\n\t\treturn c.path[index], true\n\t}\n}\n\nfunc (c *Context) Depth() int {\n\treturn len(c.path)\n}\n\n\nfunc (d *Dispatcher) AddModule(name string, m Module) {\n\tif nil == d.modules {\n\t\td.modules = make(map[string]Module)\n\t}\n\td.modules[name] = m\n}\n\n\n\nfunc (d *Dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\n\tvar c Context\n\tc.Init(w, r)\n\n\tif name, ok := c.Path(0); ok {\n\t\tif module, ok := d.modules[name]; ok && module != nil {\n\t\t\t(module).Action(&c)\n\t\t\treturn\n\t\t}\n\t}\n\tw.WriteHeader(http.StatusNotFound)\n}"} {"input": "package models\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\n\t\"github.com/golang/protobuf/proto\"\n\ttypes \"github.com/golang/protobuf/ptypes\"\n\n\tapi \"go.ligato.io/vpp-agent/v3/proto/ligato/generic\"\n)\n\n\nconst ligatoModels = \"models.ligato.io/\"\n\n\n\n\n\nfunc UnmarshalItem(item *api.Item) (proto.Message, error) {\n\t_, err := GetModelForItem(item)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar any types.DynamicAny\n\tif err := types.UnmarshalAny(item.GetData().GetAny(), &any); err != nil {\n\t\treturn nil, err\n\t}\n\treturn any.Message, nil\n}\n\n\nfunc GetModelForItem(item *api.Item) (KnownModel, error) {\n\tif item.GetId() == nil {\n\t\treturn KnownModel{}, fmt.Errorf(\"item id is nil\")\n\t}\n\tmodelPath := item.GetId().GetModel()\n\tmodel, err := GetModel(modelPath)\n\tif err != nil {\n\t\treturn KnownModel{}, err\n\t}\n\treturn model, nil\n}\n\n\nfunc GetKeyForItem(item *api.Item) (string, error) {\n\tmodel, err := GetModelForItem(item)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tkey := path.Join(model.KeyPrefix(), item.GetId().GetName())\n\treturn key, nil\n}\n\nfunc MarshalItem(pb proto.Message) (*api.Item, error) ", "output": "{\n\tmodel, err := GetModelFor(pb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname, err := model.instanceName(pb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tany, err := types.MarshalAny(pb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tany.TypeUrl = ligatoModels + proto.MessageName(pb)\n\n\titem := &api.Item{\n\t\tId: &api.Item_ID{\n\t\t\tModel: model.Name(),\n\t\t\tName: name,\n\t\t},\n\t\tData: &api.Data{\n\t\t\tUnion: &api.Data_Any{Any: any},\n\t\t},\n\t}\n\treturn item, nil\n}"} {"input": "package conn\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\ntype ConnectRequest struct {\n\tid uint64\n\tAddress net.Addr\n\tPermanent bool\n\tConn net.Conn\n\tstate ConnectState\n\tlock sync.RWMutex\n\tretryCount uint32\n}\n\n\nfunc (connectRequest *ConnectRequest) ID() uint64 {\n\treturn atomic.LoadUint64(&connectRequest.id)\n}\n\nfunc (connectRequest *ConnectRequest) State() ConnectState {\n\tconnectRequest.lock.RLock()\n\tdefer connectRequest.lock.RUnlock()\n\treturn connectRequest.state\n}\nfunc (connectRequest *ConnectRequest) String() string {\n\tif connectRequest.Address.String() == \"\" {\n\t\treturn fmt.Sprintf(\"reqid %d\", atomic.LoadUint64(&connectRequest.id))\n\t}\n\treturn fmt.Sprintf(\"%s (reqid %d)\", connectRequest.Address, atomic.LoadUint64(&connectRequest.id))\n}\n\nfunc (connectRequest *ConnectRequest) updateState(state ConnectState) ", "output": "{\n\tconnectRequest.lock.Lock()\n\tdefer connectRequest.lock.Unlock()\n\tconnectRequest.state = state\n}"} {"input": "package api\n\nimport (\n\t\"github.com/mattermost/platform/model\"\n)\n\ntype LogoutProvider struct {\n}\n\nconst (\n\tCMD_LOGOUT = \"logout\"\n)\n\n\n\nfunc (me *LogoutProvider) GetTrigger() string {\n\treturn CMD_LOGOUT\n}\n\nfunc (me *LogoutProvider) GetCommand(c *Context) *model.Command {\n\treturn &model.Command{\n\t\tTrigger: CMD_LOGOUT,\n\t\tAutoComplete: true,\n\t\tAutoCompleteDesc: c.T(\"api.command_logout.desc\"),\n\t\tAutoCompleteHint: \"\",\n\t\tDisplayName: c.T(\"api.command_logout.name\"),\n\t}\n}\n\nfunc (me *LogoutProvider) DoCommand(c *Context, channelId string, message string) *model.CommandResponse {\n\treturn &model.CommandResponse{GotoLocation: \"/logout\", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: c.T(\"api.command_logout.success_message\")}\n}\n\nfunc init() ", "output": "{\n\tRegisterCommandProvider(&LogoutProvider{})\n}"} {"input": "package util\n\nimport (\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com/mholt/archiver/v3\"\n\t\"github.com/nuclio/errors\"\n\t\"github.com/nuclio/logger\"\n)\n\ntype Decompressor struct {\n\tlogger logger.Logger\n}\n\nfunc NewDecompressor(parentLogger logger.Logger) (*Decompressor, error) {\n\tnewDecompressor := &Decompressor{\n\t\tlogger: parentLogger,\n\t}\n\n\treturn newDecompressor, nil\n}\n\nfunc (d *Decompressor) Decompress(source string, target string) error {\n\tif err := archiver.Unarchive(source, target); err != nil {\n\t\treturn errors.Wrapf(err, \"Failed to decompress file %s\", source)\n\t}\n\n\treturn nil\n}\n\n\n\nfunc IsJar(source string) bool {\n\treturn strings.ToLower(path.Ext(source)) == \".jar\"\n}\n\nfunc IsCompressed(source string) bool ", "output": "{\n\n\tif IsJar(source) {\n\t\treturn false\n\t}\n\n\tunarchiver, err := archiver.ByExtension(source)\n\tif err != nil {\n\t\treturn false\n\t}\n\tu, ok := unarchiver.(archiver.Unarchiver)\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn u != nil\n}"} {"input": "package echo\n\ntype (\n\tGroup struct {\n\t\techo Echo\n\t}\n)\n\nfunc (g *Group) Use(m ...Middleware) {\n\tfor _, h := range m {\n\t\tg.echo.middleware = append(g.echo.middleware, wrapMiddleware(h))\n\t}\n}\n\nfunc (g *Group) Connect(path string, h Handler) {\n\tg.echo.Connect(path, h)\n}\n\nfunc (g *Group) Delete(path string, h Handler) {\n\tg.echo.Delete(path, h)\n}\n\nfunc (g *Group) Get(path string, h Handler) {\n\tg.echo.Get(path, h)\n}\n\nfunc (g *Group) Head(path string, h Handler) {\n\tg.echo.Head(path, h)\n}\n\nfunc (g *Group) Options(path string, h Handler) {\n\tg.echo.Options(path, h)\n}\n\nfunc (g *Group) Patch(path string, h Handler) {\n\tg.echo.Patch(path, h)\n}\n\nfunc (g *Group) Post(path string, h Handler) {\n\tg.echo.Post(path, h)\n}\n\n\n\nfunc (g *Group) Trace(path string, h Handler) {\n\tg.echo.Trace(path, h)\n}\n\nfunc (g *Group) WebSocket(path string, h HandlerFunc) {\n\tg.echo.WebSocket(path, h)\n}\n\nfunc (g *Group) Static(path, root string) {\n\tg.echo.Static(path, root)\n}\n\nfunc (g *Group) ServeDir(path, root string) {\n\tg.echo.ServeDir(path, root)\n}\n\nfunc (g *Group) ServeFile(path, file string) {\n\tg.echo.ServeFile(path, file)\n}\n\nfunc (g *Group) Group(prefix string, m ...Middleware) *Group {\n\treturn g.echo.Group(prefix, m...)\n}\n\nfunc (g *Group) Put(path string, h Handler) ", "output": "{\n\tg.echo.Put(path, h)\n}"} {"input": "package client\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"github.com/oikomi/FishChatServer2/http_server/group-api/conf\"\n\t\"github.com/oikomi/FishChatServer2/protocol/rpc\"\n\tsd \"github.com/oikomi/FishChatServer2/service_discovery/etcd\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\ntype RegisterRPCCli struct {\n\tconn *grpc.ClientConn\n}\n\n\n\nfunc (registerRPCCli *RegisterRPCCli) CreateGroup(createGroupReq *rpc.RGCreateGroupReq) (res *rpc.RGCreateGroupRes, err error) {\n\tr := rpc.NewRegisterServerRPCClient(registerRPCCli.conn)\n\tif res, err = r.CreateGroup(context.Background(), createGroupReq); err != nil {\n\t\tglog.Error(err)\n\t}\n\treturn\n}\n\nfunc (registerRPCCli *RegisterRPCCli) JoinGroup(joinGroupReq *rpc.RGJoinGroupReq) (res *rpc.RGJoinGroupRes, err error) {\n\tr := rpc.NewRegisterServerRPCClient(registerRPCCli.conn)\n\tif res, err = r.JoinGroup(context.Background(), joinGroupReq); err != nil {\n\t\tglog.Error(err)\n\t}\n\treturn\n}\n\nfunc (registerRPCCli *RegisterRPCCli) QuitGroup(quitGroupReq *rpc.RGQuitGroupReq) (res *rpc.RGQuitGroupRes, err error) {\n\tr := rpc.NewRegisterServerRPCClient(registerRPCCli.conn)\n\tif res, err = r.QuitGroup(context.Background(), quitGroupReq); err != nil {\n\t\tglog.Error(err)\n\t}\n\treturn\n}\n\nfunc NewRegisterRPCCli() (registerRPCCli *RegisterRPCCli, err error) ", "output": "{\n\tr := sd.NewResolver(conf.Conf.RPCClient.RegisterClient.ServiceName)\n\tb := grpc.RoundRobin(r)\n\tconn, err := grpc.Dial(conf.Conf.RPCClient.RegisterClient.EtcdAddr, grpc.WithInsecure(), grpc.WithBalancer(b))\n\tif err != nil {\n\t\tglog.Error(err)\n\t\tpanic(err)\n\t}\n\tregisterRPCCli = &RegisterRPCCli{\n\t\tconn: conn,\n\t}\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst letterBytes = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst lenLetters = len(letterBytes)\n\nfunc init() {\n\trand.Seed(time.Now().UnixNano())\n}\n\nfunc randStr(n int) string {\n\tb := make([]byte, n)\n\tfor i := range b {\n\t\tb[i] = letterBytes[rand.Int63()%int64(len(letterBytes))]\n\t}\n\treturn string(b)\n}\n\nfunc sendJson(w http.ResponseWriter, data interface{}) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(data)\n}\n\nfunc sendOk(w http.ResponseWriter, data interface{}) {\n\tjson.NewEncoder(w).Encode(data)\n}\n\n\n\nfunc sendError(w http.ResponseWriter, msg string) ", "output": "{\n\tdata := struct {\n\t\tOk bool `json:\"ok\"`\n\t\tMsg string `json:\"msg\"`\n\t}{\n\t\tOk: false,\n\t\tMsg: msg,\n\t}\n\n\tsendJson(w, data)\n}"} {"input": "package core\n\nimport (\n\tctypes \"github.com/tendermint/tendermint/rpc/core/types\"\n\trpctypes \"github.com/tendermint/tendermint/rpc/lib/types\"\n\t\"github.com/tendermint/tendermint/types\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Subscribe(wsCtx rpctypes.WSRPCContext, event string) (*ctypes.ResultSubscribe, error) {\n\tlogger.Info(\"Subscribe to event\", \"remote\", wsCtx.GetRemoteAddr(), \"event\", event)\n\ttypes.AddListenerForEvent(wsCtx.GetEventSwitch(), wsCtx.GetRemoteAddr(), event, func(msg types.TMEventData) {\n\t\ttmResult := &ctypes.ResultEvent{event, msg}\n\t\twsCtx.TryWriteRPCResponse(rpctypes.NewRPCSuccessResponse(wsCtx.Request.ID+\"#event\", tmResult))\n\t})\n\treturn &ctypes.ResultSubscribe{}, nil\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Unsubscribe(wsCtx rpctypes.WSRPCContext, event string) (*ctypes.ResultUnsubscribe, error) ", "output": "{\n\tlogger.Info(\"Unsubscribe to event\", \"remote\", wsCtx.GetRemoteAddr(), \"event\", event)\n\twsCtx.GetEventSwitch().RemoveListenerForEvent(event, wsCtx.GetRemoteAddr())\n\treturn &ctypes.ResultUnsubscribe{}, nil\n}"} {"input": "package queue\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Node struct {\n\tvalue interface{}\n\tnext *Node\n}\n\nfunc NewNode(value interface{}) *Node {\n\tnode := new(Node)\n\tnode.value = value\n\n\treturn node\n}\n\ntype Queue struct {\n\thead *Node\n\ttail *Node\n}\n\n\n\nfunc (q *Queue) String() string {\n\tnode := q.head\n\n\tvar values []string\n\n\tif node == nil {\n\t\treturn \"[]\"\n\t}\n\n\tfor node.next != nil {\n\t\tvalues = append(values, fmt.Sprintf(\"%v\", node.value))\n\n\t\tnode = node.next\n\t}\n\tvalues = append(values, fmt.Sprintf(\"%v\", node.value))\n\n\treturn fmt.Sprintf(\"[%s]\", strings.Join(values, \", \"))\n}\n\nfunc (q *Queue) Enqueue(value interface{}) {\n\tnewTail := NewNode(value)\n\n\tif q.head == nil {\n\t\tq.head = newTail\n\t\tq.tail = q.head\n\t} else {\n\t\tq.tail.next = newTail\n\t\tq.tail = newTail\n\t}\n}\n\nfunc (q *Queue) Dequeue() (value interface{}, ok bool) {\n\n\tif q.head == nil {\n\t\treturn 0, false\n\t} else {\n\t\tnode := q.head\n\t\tq.head = node.next\n\t\treturn node.value, true\n\t}\n}\n\nfunc (q *Queue) Peek() (value interface{}, ok bool) {\n\tif q.head == nil {\n\t\treturn 0, false\n\t} else {\n\t\treturn q.head.value, true\n\t}\n}\n\nfunc (q *Queue) Empty() bool {\n\tif q.head == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\nfunc NewQueue(args ...interface{}) *Queue ", "output": "{\n\tlist := new(Queue)\n\n\tfor _, v := range args {\n\t\tlist.Enqueue(v)\n\t}\n\n\treturn list\n}"} {"input": "package mobilegateway\n\nimport (\n\t\"github.com/sacloud/libsacloud/v2/helper/validate\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\ntype ShutdownRequest struct {\n\tZone string `request:\"-\" validate:\"required\"`\n\tID types.ID `request:\"-\" validate:\"required\"`\n\n\tNoWait bool `request:\"-\"`\n\tForceShutdown bool `request:\"-\"`\n}\n\n\n\nfunc (req *ShutdownRequest) Validate() error ", "output": "{\n\treturn validate.Struct(req)\n}"} {"input": "package test\n\nimport (\n\t\"github.com/tidepool-org/platform/data/types/bolus/combination\"\n\tdataTypesBolusTest \"github.com/tidepool-org/platform/data/types/bolus/test\"\n\t\"github.com/tidepool-org/platform/pointer\"\n\t\"github.com/tidepool-org/platform/test\"\n)\n\n\n\nfunc CloneCombination(datum *combination.Combination) *combination.Combination {\n\tif datum == nil {\n\t\treturn nil\n\t}\n\tclone := combination.New()\n\tclone.Duration = pointer.CloneInt(datum.Duration)\n\tclone.DurationExpected = pointer.CloneInt(datum.DurationExpected)\n\tclone.Extended = pointer.CloneFloat64(datum.Extended)\n\tclone.ExtendedExpected = pointer.CloneFloat64(datum.ExtendedExpected)\n\tclone.Bolus = *dataTypesBolusTest.CloneBolus(&datum.Bolus)\n\tclone.Normal = pointer.CloneFloat64(datum.Normal)\n\tclone.NormalExpected = pointer.CloneFloat64(datum.NormalExpected)\n\treturn clone\n}\n\nfunc NewCombination() *combination.Combination ", "output": "{\n\tdatum := combination.New()\n\tdatum.Bolus = *dataTypesBolusTest.NewBolus()\n\tdatum.SubType = \"dual/square\"\n\tdatum.Duration = pointer.FromInt(test.RandomIntFromRange(combination.DurationMinimum, combination.DurationMaximum))\n\tdatum.Extended = pointer.FromFloat64(test.RandomFloat64FromRange(combination.ExtendedMinimum, combination.ExtendedMaximum))\n\tdatum.DurationExpected = pointer.FromInt(test.RandomIntFromRange(*datum.Duration, combination.DurationMaximum))\n\tdatum.ExtendedExpected = pointer.FromFloat64(test.RandomFloat64FromRange(*datum.Extended, combination.ExtendedMaximum))\n\tdatum.Normal = pointer.FromFloat64(test.RandomFloat64FromRange(combination.NormalMinimum, combination.NormalMaximum))\n\tdatum.NormalExpected = nil\n\treturn datum\n}"} {"input": "package kms\n\nimport (\n\t\"os\"\n\n\t\"github.com/denverdino/aliyungo/common\"\n)\n\nconst (\n\tKMSDefaultEndpoint = \"https://kms.cn-hangzhou.aliyuncs.com\"\n\tKMSAPIVersion = \"2016-01-20\"\n\tKMSServiceCode = \"kms\"\n)\n\ntype Client struct {\n\tcommon.Client\n}\n\n\n\n\nfunc NewClientWithRegion(accessKeyId string, accessKeySecret string, regionID common.Region) *Client {\n\tendpoint := os.Getenv(\"KMS_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = KMSDefaultEndpoint\n\t}\n\tclient := &Client{}\n\tclient.NewInit(endpoint, KMSAPIVersion, accessKeyId, accessKeySecret, KMSServiceCode, regionID)\n\treturn client\n}\n\nfunc NewClientWithEndpoint(endpoint string, accessKeyId string, accessKeySecret string) *Client {\n\tclient := &Client{}\n\tclient.Init(endpoint, KMSAPIVersion, accessKeyId, accessKeySecret)\n\treturn client\n}\n\nfunc NewECSClientWithSecurityToken(accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client {\n\tendpoint := os.Getenv(\"KMS_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = KMSDefaultEndpoint\n\t}\n\n\treturn NewKMSClientWithEndpointAndSecurityToken(endpoint, accessKeyId, accessKeySecret, securityToken, regionID)\n}\n\nfunc NewKMSClientWithEndpointAndSecurityToken(endpoint string, accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client {\n\tclient := &Client{}\n\tclient.WithEndpoint(endpoint).\n\t\tWithVersion(KMSAPIVersion).\n\t\tWithAccessKeyId(accessKeyId).\n\t\tWithAccessKeySecret(accessKeySecret).\n\t\tWithSecurityToken(securityToken).\n\t\tWithServiceCode(KMSServiceCode).\n\t\tWithRegionID(regionID).\n\t\tInitClient()\n\treturn client\n}\n\nfunc NewClient(accessKeyId, accessKeySecret string) *Client ", "output": "{\n\tendpoint := os.Getenv(\"KMS_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = KMSDefaultEndpoint\n\t}\n\treturn NewClientWithEndpoint(endpoint, accessKeyId, accessKeySecret)\n}"} {"input": "package api\n\nimport . \"go-ws/api/types\"\n\n\n\nfunc NewSDK(apiKey string) (sdk SDK) ", "output": "{\n\tvalidateApiKey(apiKey)\n\tconfig := getSDKConfig(apiKey)\n\tsdk = getSDK(config)\n\treturn sdk\n}"} {"input": "package upgrades\n\nimport (\n\t\"github.com/juju/juju/environs\"\n\t\"github.com/juju/juju/state\"\n)\n\n\n\n\n\nfunc stateStepsFor126() []Step {\n\treturn []Step{\n\t\t&upgradeStep{\n\t\t\tdescription: \"add the version field to all settings docs\",\n\t\t\ttargets: []Target{DatabaseMaster},\n\t\t\trun: func(context Context) error {\n\t\t\t\treturn state.MigrateSettingsSchema(context.State())\n\t\t\t},\n\t\t},\n\t\t&upgradeStep{\n\t\t\tdescription: \"add status to filesystem\",\n\t\t\ttargets: []Target{DatabaseMaster},\n\t\t\trun: func(context Context) error {\n\t\t\t\treturn state.AddFilesystemStatus(context.State())\n\t\t\t},\n\t\t},\n\t\t&upgradeStep{\n\t\t\tdescription: \"upgrade environment config\",\n\t\t\ttargets: []Target{DatabaseMaster},\n\t\t\trun: func(context Context) error {\n\t\t\t\tst := context.State()\n\t\t\t\treturn upgradeEnvironConfig(st, st, environs.GlobalProviderRegistry())\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc stepsFor126() []Step ", "output": "{\n\treturn []Step{}\n}"} {"input": "package goldengate\n\n\ntype OperationStatusEnum string\n\n\nconst (\n\tOperationStatusAccepted OperationStatusEnum = \"ACCEPTED\"\n\tOperationStatusInProgress OperationStatusEnum = \"IN_PROGRESS\"\n\tOperationStatusFailed OperationStatusEnum = \"FAILED\"\n\tOperationStatusSucceeded OperationStatusEnum = \"SUCCEEDED\"\n\tOperationStatusCanceled OperationStatusEnum = \"CANCELED\"\n)\n\nvar mappingOperationStatus = map[string]OperationStatusEnum{\n\t\"ACCEPTED\": OperationStatusAccepted,\n\t\"IN_PROGRESS\": OperationStatusInProgress,\n\t\"FAILED\": OperationStatusFailed,\n\t\"SUCCEEDED\": OperationStatusSucceeded,\n\t\"CANCELED\": OperationStatusCanceled,\n}\n\n\n\n\nfunc GetOperationStatusEnumValues() []OperationStatusEnum ", "output": "{\n\tvalues := make([]OperationStatusEnum, 0)\n\tfor _, v := range mappingOperationStatus {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\t\"fmt\"\n)\n\nfunc TestFirst(t *testing.T) {\n\tresult := solveFirst([]int{\n\t\t0,\n\t\t3,\n\t\t0,\n\t\t1,\n\t\t-3,\n\t})\n\n\tcheckResult(t, result, 5)\n}\n\n\n\nfunc checkResult(t *testing.T, actualResult int, requiredResult int) {\n\tt.Helper()\n\n\tif actualResult != requiredResult {\n\t\tt.Error(fmt.Printf(\"steps count must be %+v, but: %+v\", requiredResult, actualResult))\n\t}\n}\n\nfunc TestSecond(t *testing.T) ", "output": "{\n\tresult := solveSecond([]int{\n\t\t0,\n\t\t3,\n\t\t0,\n\t\t1,\n\t\t-3,\n\t})\n\n\tcheckResult(t, result, 10)\n}"} {"input": "package enmime\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/cention-sany/mime\"\n)\n\nfunc debug(format string, args ...interface{}) {\n\tif false {\n\t\tfmt.Printf(format, args...)\n\t\tfmt.Println()\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc DecodeToUTF8Base64Header(input string) string {\n\tif !strings.Contains(input, \"=?\") {\n\t\treturn input\n\t}\n\n\tdebug(\"input = %q\", input)\n\ttokens := strings.FieldsFunc(input, isWhiteSpaceRune)\n\toutput := make([]string, len(tokens), len(tokens))\n\tfor i, token := range tokens {\n\t\tif len(token) > 4 && strings.Contains(token, \"=?\") {\n\t\t\tprefix := \"\"\n\t\t\tsuffix := \"\"\n\t\t\tif token[0] == '(' {\n\t\t\t\tprefix = \"(\"\n\t\t\t\ttoken = token[1:]\n\t\t\t}\n\t\t\tif token[len(token)-1] == ')' {\n\t\t\t\tsuffix = \")\"\n\t\t\t\ttoken = token[:len(token)-1]\n\t\t\t}\n\t\t\toutput[i] = prefix + mime.BEncoding.Encode(\"UTF-8\", DecodeHeader(token)) + suffix\n\t\t} else {\n\t\t\toutput[i] = token\n\t\t}\n\t\tdebug(\"%v %q %q\", i, token, output[i])\n\t}\n\n\treturn strings.Join(output, \" \")\n}\n\n\nfunc isWhiteSpaceRune(r rune) bool {\n\tswitch r {\n\tcase ' ':\n\t\treturn true\n\tcase '\\t':\n\t\treturn true\n\tcase '\\r':\n\t\treturn true\n\tcase '\\n':\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc DecodeHeader(input string) string ", "output": "{\n\tif !strings.Contains(input, \"=?\") {\n\t\treturn input\n\t}\n\n\tdec := new(mime.WordDecoder)\n\tdec.CharsetReader = NewCharsetReader\n\theader, err := dec.DecodeHeader(input)\n\tif err != nil {\n\t\treturn input\n\t}\n\treturn header\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"time\"\n\n\t\"go-common/app/admin/main/push/conf\"\n\t\"go-common/app/admin/main/push/http\"\n\t\"go-common/app/admin/main/push/service\"\n\tecode \"go-common/library/ecode/tip\"\n\t\"go-common/library/log\"\n\t\"go-common/library/net/trace\"\n\t\"go-common/library/os/signal\"\n\t\"go-common/library/syscall\"\n)\n\nvar (\n\ts *service.Service\n)\n\nfunc main() {\n\tflag.Parse()\n\tif err := conf.Init(); err != nil {\n\t\tpanic(err)\n\t}\n\tlog.Init(conf.Conf.Log)\n\tdefer log.Close()\n\ttrace.Init(conf.Conf.Tracer)\n\tdefer trace.Close()\n\tecode.Init(conf.Conf.Ecode)\n\ts = service.New(conf.Conf)\n\thttp.Init(conf.Conf, s)\n\tlog.Info(\"push-admin start\")\n\tsignalHandler()\n}\n\n\n\nfunc signalHandler() ", "output": "{\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)\n\tfor {\n\t\tsi := <-ch\n\t\tswitch si {\n\t\tcase syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGSTOP, syscall.SIGINT:\n\t\t\ttime.Sleep(time.Second * 2)\n\t\t\tlog.Info(\"get a signal %s, stop the push-admin process\", si.String())\n\t\t\ts.Close()\n\t\t\ts.Wait()\n\t\t\ttime.Sleep(time.Second)\n\t\t\treturn\n\t\tcase syscall.SIGHUP:\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}"} {"input": "package user\n\nfunc New(id int, username, password, firstname, lastname, role string) User {\n\treturn User{id, username, password, firstname, lastname, role}\n}\n\n\ntype User struct {\n\tid int\n\tusername string\n\tpassword string\n\tfirstname string\n\tlastname string\n\trole string\n}\n\nfunc (u User) Id() int {\n\treturn u.id\n}\n\nfunc (u User) Username() string {\n\treturn u.username\n}\n\nfunc (u User) Password() string {\n\treturn u.password\n}\n\nfunc (u User) Firstname() string {\n\treturn u.firstname\n}\n\nfunc (u User) Lastname() string {\n\treturn u.lastname\n}\n\n\n\nfunc (u User) Role() string ", "output": "{\n\treturn u.role\n}"} {"input": "package worker\n\nimport (\n\t\"github.com/gopherjs/gopherjs/js\"\n\t\"github.com/flimzy/goweb/event\"\n)\n\ntype Worker struct {\n\tjs.Object\n\tOnError event.EventHandlerFunc `js:\"onerror\"`\n\tOnMessage event.EventHandlerFunc `js:\"onmessage\"`\n}\n\nfunc New(url string) (w *Worker, e error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\te = r.(*js.Error)\n\t\t}\n\t}()\n\to := js.Global.Get(\"Worker\").New(url)\n\tw = &Worker{Object: *o}\n\treturn\n}\n\n\n\nfunc (w *Worker) Terminate() {\n\tw.Call(\"terminate\")\n}\n\nfunc (w *Worker) PostMessage(msg interface{}) ", "output": "{\n\tw.Call(\"postMessage\", msg)\n}"} {"input": "package resttk\n\ntype ResourceInterface interface {\n\tFindAllResources(v interface{}) interface{}\n\tFindResource(key string, value string, v interface{}) interface{}\n\tSaveResource(key string, value string, v interface{}) interface{}\n\tUpdateResource(key string, value string, v interface{}) interface{}\n\tDeleteResource(key string, value string) bool\n}\n\ntype BaseResource struct {\n\tparent ResourceInterface\n}\n\nfunc (r *BaseResource) Init(p ResourceInterface) {\n\tr.parent = p\n}\n\nfunc (r *BaseResource) FindAllResources(v interface{}) interface{} {\n\tresources := r.parent.FindAllResources(v)\n\tif resources != nil {\n\t\treturn resources\n\t}\n\n\treturn nil\n}\n\nfunc (r *BaseResource) FindResource(key string, value string, v interface{}) interface{} {\n\tresource := r.parent.FindResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (r *BaseResource) UpdateResource(key string, value string, v interface{}) interface{} {\n\tresource := r.parent.UpdateResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn nil\n}\n\nfunc (r *BaseResource) DeleteResource(key string, value string) bool {\n\treturn r.parent.DeleteResource(key, value)\n}\n\nfunc (r *BaseResource) SaveResource(key string, value string, v interface{}) interface{} ", "output": "{\n\tresource := r.parent.FindResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\n\n\nfunc main() {\n\titerates := 5000\n\tch := make(chan float64)\n\tfor i := 0; i <= iterates; i++ {\n\t\tgo computerTerm(ch, float64(i))\n\t}\n\tpi := 0.0\n\tfor i := 0; i <= iterates; i++ {\n\t\tpi += <-ch\n\t}\n\tfmt.Printf(\"π is: %f \\n\", pi)\n}\n\n\n\nfunc computerTerm(ch chan float64, k float64) ", "output": "{\n\tch <- 4 * math.Pow(-1, k) / float64(2*k+1)\n}"} {"input": "package xmpp\n\n\n\nfunc add(x int, y int) int ", "output": "{\n\treturn x + y\n}"} {"input": "package stats\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"sync\"\n\n\tmultierror \"github.com/hashicorp/go-multierror\"\n\t\"github.com/shirou/gopsutil/cpu\"\n)\n\nvar (\n\tcpuMhzPerCore float64\n\tcpuModelName string\n\tcpuNumCores int\n\tcpuTotalTicks float64\n\n\tinitErr error\n\tonceLer sync.Once\n)\n\nfunc Init() error {\n\tonceLer.Do(func() {\n\t\tvar merrs *multierror.Error\n\t\tvar err error\n\t\tif cpuNumCores, err = cpu.Counts(true); err != nil {\n\t\t\tmerrs = multierror.Append(merrs, fmt.Errorf(\"Unable to determine the number of CPU cores available: %v\", err))\n\t\t}\n\n\t\tvar cpuInfo []cpu.InfoStat\n\t\tif cpuInfo, err = cpu.Info(); err != nil {\n\t\t\tmerrs = multierror.Append(merrs, fmt.Errorf(\"Unable to obtain CPU information: %v\", initErr))\n\t\t}\n\n\t\tfor _, cpu := range cpuInfo {\n\t\t\tcpuModelName = cpu.ModelName\n\t\t\tcpuMhzPerCore = cpu.Mhz\n\t\t\tbreak\n\t\t}\n\n\t\tcpuMhzPerCore = math.Floor(cpuMhzPerCore)\n\t\tcpuTotalTicks = math.Floor(float64(cpuNumCores) * cpuMhzPerCore)\n\n\t\tinitErr = merrs.ErrorOrNil()\n\t})\n\treturn initErr\n}\n\n\nfunc CPUNumCores() int {\n\treturn cpuNumCores\n}\n\n\nfunc CPUMHzPerCore() float64 {\n\treturn cpuMhzPerCore\n}\n\n\nfunc CPUModelName() string {\n\treturn cpuModelName\n}\n\n\n\n\nfunc TotalTicksAvailable() float64 ", "output": "{\n\treturn cpuTotalTicks\n}"} {"input": "package compute\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/genevieve/leftovers/common\"\n\tgcpcompute \"google.golang.org/api/compute/v1\"\n)\n\ntype disksClient interface {\n\tListDisks(zone string) ([]*gcpcompute.Disk, error)\n\tDeleteDisk(zone, disk string) error\n}\n\ntype Disks struct {\n\tclient disksClient\n\tlogger logger\n\tzones map[string]string\n}\n\n\n\nfunc (d Disks) List(filter string) ([]common.Deletable, error) {\n\tdisks := []*gcpcompute.Disk{}\n\tfor _, zone := range d.zones {\n\t\tl, err := d.client.ListDisks(zone)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"List Disks for zone %s: %s\", zone, err)\n\t\t}\n\n\t\tdisks = append(disks, l...)\n\t}\n\n\tvar resources []common.Deletable\n\tfor _, disk := range disks {\n\t\tresource := NewDisk(d.client, disk.Name, d.zones[disk.Zone])\n\n\t\tif !strings.Contains(resource.Name(), filter) {\n\t\t\tcontinue\n\t\t}\n\n\t\tproceed := d.logger.PromptWithDetails(resource.Type(), resource.Name())\n\t\tif !proceed {\n\t\t\tcontinue\n\t\t}\n\n\t\tresources = append(resources, resource)\n\t}\n\n\treturn resources, nil\n}\n\nfunc (d Disks) Type() string {\n\treturn \"disk\"\n}\n\nfunc NewDisks(client disksClient, logger logger, zones map[string]string) Disks ", "output": "{\n\treturn Disks{\n\t\tclient: client,\n\t\tlogger: logger,\n\t\tzones: zones,\n\t}\n}"} {"input": "package context\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\n\tjujuos \"github.com/juju/utils/os\"\n)\n\n\n\nfunc OSDependentEnvVars(paths Paths) []string {\n\tswitch jujuos.HostOS() {\n\tcase jujuos.Windows:\n\t\treturn windowsEnv(paths)\n\tcase jujuos.Ubuntu:\n\t\treturn ubuntuEnv(paths)\n\tcase jujuos.CentOS:\n\t\treturn centosEnv(paths)\n\t}\n\treturn nil\n}\n\nfunc appendPath(paths Paths) []string {\n\treturn []string{\n\t\t\"PATH=\" + paths.GetToolsDir() + \":\" + os.Getenv(\"PATH\"),\n\t}\n}\n\nfunc ubuntuEnv(paths Paths) []string {\n\tpath := appendPath(paths)\n\tenv := []string{\n\t\t\"APT_LISTCHANGES_FRONTEND=none\",\n\t\t\"DEBIAN_FRONTEND=noninteractive\",\n\t}\n\tenv = append(env, path...)\n\treturn env\n}\n\n\n\n\n\n\n\nfunc windowsEnv(paths Paths) []string {\n\tcharmDir := paths.GetCharmDir()\n\tcharmModules := filepath.Join(charmDir, \"lib\", \"Modules\")\n\treturn []string{\n\t\t\"Path=\" + paths.GetToolsDir() + \";\" + os.Getenv(\"Path\"),\n\t\t\"PSModulePath=\" + os.Getenv(\"PSModulePath\") + \";\" + charmModules,\n\t}\n}\n\nfunc centosEnv(paths Paths) []string ", "output": "{\n\treturn appendPath(paths)\n}"} {"input": "package secret\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/watch\"\n)\n\n\n\n\ntype Watcher interface {\n\tWatch(api.ListOptions) (watch.Interface, error)\n}\n\n\ntype FakeWatcher struct {\n\tIFace watch.Interface\n\tErr error\n}\n\n\n\n\nfunc (f FakeWatcher) Watch(api.ListOptions) (watch.Interface, error) ", "output": "{\n\treturn f.IFace, f.Err\n}"} {"input": "package omniscient\n\nimport (\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestHealthCannotStartIfStarted(t *testing.T) {\n\tupdateCheckInterval := func(h *Health) error {\n\t\th.checkInterval = 1 * time.Millisecond\n\t\treturn nil\n\t}\n\n\th, err := NewHealth(updateCheckInterval)\n\tassert.NoError(t, err)\n\n\terr = h.Start()\n\tassert.NoError(t, err)\n\n\t<-h.stateChange\n\n\terr = h.Start()\n\tassert.Error(t, err)\n}\n\nfunc TestHealthCannotStopIfNotStarted(t *testing.T) {\n\tupdateCheckInterval := func(h *Health) error {\n\t\th.checkInterval = 1 * time.Millisecond\n\t\treturn nil\n\t}\n\n\th, err := NewHealth(updateCheckInterval)\n\tassert.NoError(t, err)\n\n\terr = h.Stop()\n\tassert.Error(t, err)\n}\n\nfunc TestHealth(t *testing.T) ", "output": "{\n\tvar mu sync.Mutex\n\thealthStatus := true\n\tcheck := func() bool {\n\t\tmu.Lock()\n\t\tdefer mu.Unlock()\n\t\treturn healthStatus\n\t}\n\n\tupdateCheckInterval := func(h *Health) error {\n\t\th.checkInterval = 1 * time.Millisecond\n\t\treturn nil\n\t}\n\n\th, err := NewHealth(\n\t\tHealthCheckOption(check),\n\t\tupdateCheckInterval)\n\tassert.NoError(t, err)\n\n\th.Start()\n\tdefer h.Stop()\n\n\tassert.True(t, h.IsOK(), \"health check status\")\n\n\tmu.Lock()\n\thealthStatus = false\n\tmu.Unlock()\n\n\t<-h.statusUpdated\n\tassert.False(t, h.IsOK(), \"health check status\")\n}"} {"input": "package displayers\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/digitalocean/doctl/do\"\n)\n\ntype Size struct {\n\tSizes do.Sizes\n}\n\nvar _ Displayable = &Size{}\n\nfunc (si *Size) JSON(out io.Writer) error {\n\treturn writeJSON(si.Sizes, out)\n}\n\nfunc (si *Size) Cols() []string {\n\treturn []string{\n\t\t\"Slug\", \"Memory\", \"VCPUs\", \"Disk\", \"PriceMonthly\", \"PriceHourly\",\n\t}\n}\n\n\n\nfunc (si *Size) KV() []map[string]interface{} {\n\tout := []map[string]interface{}{}\n\n\tfor _, s := range si.Sizes {\n\t\to := map[string]interface{}{\n\t\t\t\"Slug\": s.Slug, \"Memory\": s.Memory, \"VCPUs\": s.Vcpus,\n\t\t\t\"Disk\": s.Disk, \"PriceMonthly\": fmt.Sprintf(\"%0.2f\", s.PriceMonthly),\n\t\t\t\"PriceHourly\": s.PriceHourly,\n\t\t}\n\n\t\tout = append(out, o)\n\t}\n\n\treturn out\n}\n\nfunc (si *Size) ColMap() map[string]string ", "output": "{\n\treturn map[string]string{\n\t\t\"Slug\": \"Slug\", \"Memory\": \"Memory\", \"VCPUs\": \"VCPUs\",\n\t\t\"Disk\": \"Disk\", \"PriceMonthly\": \"Price Monthly\",\n\t\t\"PriceHourly\": \"Price Hourly\",\n\t}\n}"} {"input": "package handlers\n\nimport (\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/byuoitav/configuration-database-microservice/structs\"\n\t\"github.com/labstack/echo\"\n)\n\n\n\nfunc (handlerGroup *HandlerGroup) AddDeviceRoleDef(context echo.Context) error {\n\tdrdName := context.Param(\"deviceroledefinition\")\n\tvar drd structs.DeviceRoleDef\n\n\terr := context.Bind(&drd)\n\tif err != nil {\n\t\treturn context.JSON(http.StatusBadRequest, err.Error())\n\t}\n\tif drdName != drd.Name {\n\t\treturn context.JSON(http.StatusBadRequest, \"Endpoint parameter and json name must match!\")\n\t}\n\n\tresponse, err := handlerGroup.Accessors.AddDeviceRoleDef(drd)\n\tif err != nil {\n\t\treturn context.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\n\treturn context.JSON(http.StatusOK, response)\n}\n\nfunc (handlerGroup *HandlerGroup) GetDeviceRoleDefsById(context echo.Context) error {\n\n\tid, err := strconv.Atoi(context.Param(\"id\"))\n\tif err != nil {\n\t\treturn context.JSON(http.StatusBadRequest, err.Error())\n\t}\n\n\tresponse, err := handlerGroup.Accessors.GetDeviceRoleDefByID(id)\n\tif err != nil {\n\t\treturn context.JSON(http.StatusBadRequest, err.Error())\n\t}\n\n\treturn context.JSON(http.StatusOK, response)\n\n}\n\nfunc (handlerGroup *HandlerGroup) GetDeviceRoleDefs(context echo.Context) error ", "output": "{\n\tresponse, err := handlerGroup.Accessors.GetDeviceRoleDefs()\n\tif err != nil {\n\t\treturn context.String(http.StatusBadRequest, err.Error())\n\t}\n\n\treturn context.JSON(http.StatusOK, response)\n}"} {"input": "package stun\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"github.com/willscott/goturn/common\"\n\t\"net\"\n)\n\nconst (\n\tMappedAddress stun.AttributeType = 0x1\n)\n\ntype MappedAddressAttribute struct {\n\tFamily uint16\n\tPort uint16\n\tAddress net.IP\n}\n\nfunc NewMappedAddressAttribute() stun.Attribute {\n\treturn stun.Attribute(new(MappedAddressAttribute))\n}\n\nfunc (h *MappedAddressAttribute) Type() stun.AttributeType {\n\treturn MappedAddress\n}\n\n\n\nfunc (h *MappedAddressAttribute) Decode(data []byte, _ uint16, _ *stun.Parser) error {\n\tif data[0] != 0 && data[1] != 1 && data[0] != 2 {\n\t\treturn errors.New(\"Incorrect Mapped Address Family.\")\n\t}\n\th.Family = uint16(data[1])\n\tif (h.Family == 1 && len(data) < 8) || (h.Family == 2 && len(data) < 20) {\n\t\treturn errors.New(\"Mapped Address Attribute unexpectedly Truncated.\")\n\t}\n\th.Port = uint16(data[2])<<8 + uint16(data[3])\n\tif h.Family == 1 {\n\t\th.Address = data[4:8]\n\t} else {\n\t\th.Address = data[4:20]\n\t}\n\treturn nil\n}\n\nfunc (h *MappedAddressAttribute) Length(_ *stun.Message) uint16 {\n\tif h.Family == 1 {\n\t\treturn 8\n\t} else {\n\t\treturn 20\n\t}\n}\n\nfunc (h *MappedAddressAttribute) Encode(msg *stun.Message) ([]byte, error) ", "output": "{\n\tbuf := new(bytes.Buffer)\n\terr := stun.WriteAttributeHeader(buf, stun.Attribute(h), msg)\n\terr = binary.Write(buf, binary.BigEndian, h.Family)\n\terr = binary.Write(buf, binary.BigEndian, h.Port)\n\terr = binary.Write(buf, binary.BigEndian, h.Address)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}"} {"input": "package decoders\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestParseTimeErrorParsing(t *testing.T) {\n\tr := require.New(t)\n\n\t_, err := parseTime([]string{\"this is sparta\"})\n\tr.Error(err)\n}\n\nfunc TestParseTime(t *testing.T) {\n\tr := require.New(t)\n\n\ttestCases := []struct {\n\t\tinput string\n\t\texpected time.Time\n\t\texpectErr bool\n\t}{\n\t\t{\n\t\t\tinput: \"2017-01-01\",\n\t\t\texpected: time.Date(2017, time.January, 1, 0, 0, 0, 0, time.UTC),\n\t\t\texpectErr: false,\n\t\t},\n\t\t{\n\t\t\tinput: \"2018-07-13T15:34\",\n\t\t\texpected: time.Date(2018, time.July, 13, 15, 34, 0, 0, time.UTC),\n\t\t\texpectErr: false,\n\t\t},\n\t\t{\n\t\t\tinput: \"2018-20-10T30:15\",\n\t\t\texpected: time.Time{},\n\t\t\texpectErr: true,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttt, err := parseTime([]string{tc.input})\n\t\tif !tc.expectErr {\n\t\t\tr.NoError(err)\n\t\t}\n\n\t\tr.Equal(tc.expected, tt)\n\t}\n}\n\n\n\nfunc TestParseTimeConflicting(t *testing.T) ", "output": "{\n\tr := require.New(t)\n\n\tRegisterTimeFormats(\"2006-02-01\")\n\ttt, err := parseTime([]string{\"2017-01-10\"})\n\n\tr.NoError(err)\n\texpected := time.Date(2017, time.October, 1, 0, 0, 0, 0, time.UTC)\n\tr.Equal(expected, tt)\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n)\n\nfunc main() {\n \n methods()\n interfaces()\n typeAssertions()\n}\n\n\nfunc methods() {\n fmt.Println(\"Methods\")\n fmt.Println(\"=======\")\n\n swedishChef := Person{\n Phrase: \"Bork bork bork!\",\n }\n\n fmt.Printf(\"swedishChef says '%s'\\n\", swedishChef.Speak())\n\n myFloat := MyFloat(16.0)\n myFloat.Square()\n\n fmt.Printf(\"myFloat -> value = %f, squared = %f\\n\", myFloat, myFloat.Square())\n\n fmt.Println()\n}\n\nfunc interfaces() {\n fmt.Println(\"Interfaces\")\n fmt.Println(\"==========\")\n\n person := Person{\n Phrase: \"Hello\",\n Thought: \"Cogito ergo sum\",\n }\n \n \n dog := Dog{}\n\n var sentient Sentient\n \n sentient = person\n fmt.Printf(\"sentient says '%s' and thinks '%s'\\n\", sentient.Speak(), sentient.Reason())\n \n \n\n var speaker Speaker\n \n speaker = sentient\n fmt.Printf(\"sentient speaker says '%s'\\n\", speaker.Speak())\n speaker = dog\n fmt.Printf(\"non-sentient speaker says '%s'\\n\", speaker.Speak())\n speaker.Speak()\n\n fmt.Println()\n}\n\n\n\nfunc typeAssertions() ", "output": "{\n fmt.Println(\"Type assertions\")\n fmt.Println(\"===============\")\n\n var i interface{} = \"All types match the empty interface\"\n\n \n f, ok := i.(float64)\n fmt.Printf(\"Type assertion results for float64 -> f = %f, ok = %t\\n\", f, ok)\n s, ok := i.(string)\n fmt.Printf(\"Type assertion results for string -> s = %s, ok = %t\\n\", s, ok)\n \n \n\n \n switch i.(type) {\n case int:\n fmt.Println(\"It's an int\")\n case string:\n fmt.Println(\"It's a string\")\n default:\n fmt.Println(\"Hell if I know\")\n }\n fmt.Println()\n}"} {"input": "package main\n\n\n\nfunc funky(n int) {\n\n\tvar s0 []int\n\ts0 = append(s0, 1)\n\ts0 = append(s0, 1%5)\n\n\ts1 := append(s0, 2)\n\ts2 := append(s1, 3+5)\n\n\tswitch n {\n\tdefault:\n\t\tprintln(s2[1])\n\tcase 1, 2, 3, 4:\n\t\tprintln(s0[1])\n\tcase 5, 6:\n\t\tprintln(s2[3])\n\t}\n\n\treturn\n}\n\n\n\nfunc main() {\n\tn := 5\n\tfunky(n)\n\n\tnumber(35)\n\n\n\n\n\ttype (\n\t\ta int\n\t\tpoint struct {\n\t\t\tx, y string\n\t\t}\n\t)\n\n\tvar z a\n\tz = a(2)\n\tprintln(z)\n\n}\n\nfunc number(a int) int ", "output": "{\n\n\n\tif a < 0 {\n\t\tprintln(a, \"is negative.\")\n\t}\n\n\tif a%2 == 0 {\n\t\tprintln(a, \"is even.\")\n\t} else {\n\t\tprintln(a, \"is odd.\")\n\t}\n\n\tb := 50\n\tc := b - a\n\n\tif c > 0 {\n\t\tprintln(a, \"<50.\")\n\t} else if c < 0 {\n\t\tprintln(a, \">50.\")\n\t} else {\n\t\tprintln(a, \"=50.\")\n\t}\n\treturn a\n}"} {"input": "package v1\n\nimport (\n\t\"gopkg.in/guregu/null.v3\"\n\n\t\"go.k6.io/k6/core\"\n\t\"go.k6.io/k6/lib\"\n)\n\ntype Status struct {\n\tStatus lib.ExecutionStatus `json:\"status\" yaml:\"status\"`\n\n\tPaused null.Bool `json:\"paused\" yaml:\"paused\"`\n\tVUs null.Int `json:\"vus\" yaml:\"vus\"`\n\tVUsMax null.Int `json:\"vus-max\" yaml:\"vus-max\"`\n\tStopped bool `json:\"stopped\" yaml:\"stopped\"`\n\tRunning bool `json:\"running\" yaml:\"running\"`\n\tTainted bool `json:\"tainted\" yaml:\"tainted\"`\n}\n\nfunc NewStatus(engine *core.Engine) Status {\n\texecutionState := engine.ExecutionScheduler.GetState()\n\treturn Status{\n\t\tStatus: executionState.GetCurrentExecutionStatus(),\n\t\tRunning: executionState.HasStarted() && !executionState.HasEnded(),\n\t\tPaused: null.BoolFrom(executionState.IsPaused()),\n\t\tStopped: engine.IsStopped(),\n\t\tVUs: null.IntFrom(executionState.GetCurrentlyActiveVUsCount()),\n\t\tVUsMax: null.IntFrom(executionState.GetInitializedVUsCount()),\n\t\tTainted: engine.IsTainted(),\n\t}\n}\n\nfunc (s Status) GetName() string {\n\treturn \"status\"\n}\n\nfunc (s Status) GetID() string {\n\treturn \"default\"\n}\n\n\n\nfunc (s Status) SetID(id string) error ", "output": "{\n\treturn nil\n}"} {"input": "package service\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/syncloud/redirect/model\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype ActionsDbStub struct {\n\taction *model.Action\n}\n\nfunc (db *ActionsDbStub) GetAction(_ int64, _ uint64) (*model.Action, error) {\n\treturn db.action, nil\n}\n\n\nfunc (db *ActionsDbStub) InsertAction(action *model.Action) error {\n\tdb.action = action\n\treturn nil\n}\n\nfunc (db *ActionsDbStub) UpdateAction(action *model.Action) error {\n\tif db.action != nil {\n\t\tdb.action = action\n\t}\n\treturn nil\n}\n\nfunc (db *ActionsDbStub) DeleteActions(_ int64) error {\n\tdb.action = nil\n\treturn nil\n}\n\nfunc (db *ActionsDbStub) DeleteAction(actionId uint64) error {\n\tdb.action = nil\n\treturn nil\n}\n\nfunc TestUpsert(t *testing.T) {\n\n\tdb := &ActionsDbStub{nil}\n\tactions := NewActions(db)\n\n\tuser := &model.User{Id: 1, Email: \"test@example.com\", PasswordHash: \"pass\", Active: true, UpdateToken: \"token\", Timestamp: time.Now()}\n\taction, err := actions.UpsertActivateAction(user.Id)\n\n\tassert.Nil(t, err)\n\tassert.NotNil(t, action)\n\tassert.NotNil(t, db.action)\n}\n\nfunc (db *ActionsDbStub) GetActionByToken(_ string, _ uint64) (*model.Action, error) ", "output": "{\n\treturn db.action, nil\n}"} {"input": "package mw\n\nimport \"net/http\"\n\n\n\nfunc CorsHandler(h http.Handler) http.Handler ", "output": "{\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif origin := r.Header.Get(\"Origin\"); origin != \"\" {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t}\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS, PUT, PATCH, DELETE\")\n\t\tw.Header().Set(\"Access-Control-Request-Method\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Origin, X-Requested-With, Accept, Authorization\")\n\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\th.ServeHTTP(w, r)\n\t})\n}"} {"input": "package hash\n\nimport \"unsafe\"\n\nconst DJBInit uint32 = 5381\n\nfunc DJBCombine(acc, h uint32) uint32 {\n\treturn mul33(acc) + h\n}\n\nfunc DJB(hs ...uint32) uint32 {\n\tacc := DJBInit\n\tfor _, h := range hs {\n\t\tacc = DJBCombine(acc, h)\n\t}\n\treturn acc\n}\n\nfunc UInt32(u uint32) uint32 {\n\treturn u\n}\n\nfunc UInt64(u uint64) uint32 {\n\treturn mul33(uint32(u>>32)) + uint32(u&0xffffffff)\n}\n\n\n\nfunc UIntPtr(p uintptr) uint32 {\n\tswitch unsafe.Sizeof(p) {\n\tcase 4:\n\t\treturn UInt32(uint32(p))\n\tcase 8:\n\t\treturn UInt64(uint64(p))\n\tdefault:\n\t\tpanic(\"unhandled pointer size\")\n\t}\n}\n\nfunc String(s string) uint32 {\n\th := DJBInit\n\tfor i := 0; i < len(s); i++ {\n\t\th = DJBCombine(h, uint32(s[i]))\n\t}\n\treturn h\n}\n\nfunc mul33(u uint32) uint32 {\n\treturn u<<5 + u\n}\n\nfunc Pointer(p unsafe.Pointer) uint32 ", "output": "{\n\tswitch unsafe.Sizeof(p) {\n\tcase 4:\n\t\treturn UInt32(uint32(uintptr(p)))\n\tcase 8:\n\t\treturn UInt64(uint64(uintptr(p)))\n\tdefault:\n\t\tpanic(\"unhandled pointer size\")\n\t}\n}"} {"input": "package nwo\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n)\n\ntype Command interface {\n\tArgs() []string\n\tSessionName() string\n}\n\ntype Enver interface {\n\tEnv() []string\n}\n\ntype WorkingDirer interface {\n\tWorkingDir() string\n}\n\nfunc ConnectsToOrderer(c Command) bool {\n\tfor _, arg := range c.Args() {\n\t\tif arg == \"--orderer\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc ClientAuthEnabled(c Command) bool {\n\tfor _, arg := range c.Args() {\n\t\tif arg == \"--clientauth\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc NewCommand(path string, command Command) *exec.Cmd ", "output": "{\n\tcmd := exec.Command(path, command.Args()...)\n\tcmd.Env = os.Environ()\n\tif ce, ok := command.(Enver); ok {\n\t\tcmd.Env = append(cmd.Env, ce.Env()...)\n\t}\n\tif wd, ok := command.(WorkingDirer); ok {\n\t\tcmd.Dir = wd.WorkingDir()\n\t}\n\treturn cmd\n}"} {"input": "package core\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc BenchmarkThreeWayNameUnionOneAltered(b *testing.B) {\n\tancestor := map[string]*Entry{\n\t\t\"first\": nil,\n\t\t\"second\": nil,\n\t\t\"third\": nil,\n\t\t\"fourth\": nil,\n\t\t\"fifth\": nil,\n\t\t\"sixth\": nil,\n\t\t\"seventh\": nil,\n\t\t\"eighth\": nil,\n\t\t\"ninth\": nil,\n\t}\n\taltered := map[string]*Entry{\n\t\t\"first\": nil,\n\t\t\"second\": nil,\n\t\t\"third\": nil,\n\t\t\"fourth\": nil,\n\t\t\"fifth\": nil,\n\t\t\"sixth\": nil,\n\t\t\"seventh\": nil,\n\t\t\"eighth\": nil,\n\t\t\"ninth\": nil,\n\t\t\"tenth\": nil,\n\t}\n\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tnameUnion(ancestor, ancestor, altered)\n\t}\n}\n\nfunc BenchmarkThreeWayNameUnionUnaltered(b *testing.B) ", "output": "{\n\tcontents := map[string]*Entry{\n\t\t\"first\": nil,\n\t\t\"second\": nil,\n\t\t\"third\": nil,\n\t\t\"fourth\": nil,\n\t\t\"fifth\": nil,\n\t\t\"sixth\": nil,\n\t\t\"seventh\": nil,\n\t\t\"eighth\": nil,\n\t\t\"ninth\": nil,\n\t}\n\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tnameUnion(contents, contents, contents)\n\t}\n}"} {"input": "package module\n\nimport (\n\t\"encoding/gob\"\n\t\"fmt\"\n\t\"github.com/glennyonemitsu/reicon/system/activity\"\n\t\"net\"\n\t\"os\"\n)\n\ntype Module struct {\n\tName string\n\tActivities []*activity.Activity\n\tServerSocket *net.UnixConn\n\tSocketAddr *net.UnixAddr\n\tListener *net.UnixListener\n}\n\nfunc (m *Module) Run() {\n\tsocket_path := os.Getenv(\"REICON_SYSTEM_SOCKET\")\n\tm.SocketAddr = new(net.UnixAddr)\n\tm.SocketAddr.Name = \"unix\"\n\tm.SocketAddr.Net = socket_path\n\tm.Listener, _ = net.ListenUnix(\"unix\", m.SocketAddr)\n\tm.ListenSocket()\n\n}\n\n\n\nfunc (m *Module) handleUnixConnection(conn *net.UnixConn) {\n\tvar msg string\n\tenc := gob.NewEncoder(conn)\n\tdec := gob.NewDecoder(conn)\n\tdec.Decode(&msg)\n\tenc.Encode(fmt.Sprintf(\"your message was: %s\", msg))\n}\n\nfunc (m *Module) Shutdown() {\n\tm.ServerSocket.Close()\n}\n\nfunc (m *Module) RegisterActivity(name string) *activity.Activity {\n\ta := new(activity.Activity)\n\ta.Name = name\n\tm.Activities = append(m.Activities, a)\n\treturn a\n}\n\nfunc Create(name string) *Module {\n\tm := new(Module)\n\tm.Name = name\n\treturn m\n}\n\nfunc (m *Module) ListenSocket() ", "output": "{\n\tfor {\n\t\tconn, err := m.Listener.AcceptUnix()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tgo m.handleUnixConnection(conn)\n\t}\n}"} {"input": "package AEDAcrypt\n\nimport \"testing\"\n\n\n\nfunc TestDecrypter(t *testing.T) {\n\tvar str string = \"Hello World!\"\n\tstrenc := Encrypter([]byte(str))\n\t_, err := Decrypter(strenc)\n\n\tif err != nil {\n\t\tt.Error(\"Expected 1.5, got \")\n\t}\n}\n\nfunc TestEncrypter(t *testing.T) ", "output": "{\n\tvar str string = \"Hello World!\"\n\tstrenc := Encrypter([]byte(str))\n\t_, err := Decrypter(strenc)\n\n\tif err != nil {\n\t\tt.Error(\"Expected 1.5, got \")\n\t}\n}"} {"input": "package options\n\nimport (\n\t\"github.com/spf13/pflag\"\n\t\"k8s.io/kubernetes/pkg/apis/componentconfig\"\n)\n\n\ntype DaemonSetControllerOptions struct {\n\tConcurrentDaemonSetSyncs int32\n}\n\n\n\n\n\nfunc (o *DaemonSetControllerOptions) ApplyTo(cfg *componentconfig.DaemonSetControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentDaemonSetSyncs = o.ConcurrentDaemonSetSyncs\n\n\treturn nil\n}\n\n\nfunc (o *DaemonSetControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}\n\nfunc (o *DaemonSetControllerOptions) AddFlags(fs *pflag.FlagSet) ", "output": "{\n\tif o == nil {\n\t\treturn\n\t}\n}"} {"input": "package es_terminfo\n\nimport (\n\t\"golang.org/x/crypto/ssh/terminal\"\n\t\"os\"\n)\n\n\n\nfunc IsOutTerminal() bool {\n\treturn terminal.IsTerminal(int(os.Stdout.Fd()))\n}\n\n\nfunc IsOutColorTerminal() bool {\n\tif !IsOutTerminal() {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc IsInTerminal() bool ", "output": "{\n\treturn terminal.IsTerminal(int(os.Stdin.Fd()))\n}"} {"input": "package views\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/antihax/evedata/services/vanguard\"\n)\n\n\n\nfunc init() ", "output": "{\n\tvanguard.AddRoute(\"GET\", \"/\",\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\trenderTemplate(w,\n\t\t\t\t\"mainPage.html\",\n\t\t\t\ttime.Hour*24*31,\n\t\t\t\tnewPage(r, \"EVE Online Intel Data\"))\n\t\t})\n}"} {"input": "package ig\n\nimport \"fmt\"\n\n\n\n\n\nfunc (ic *IntelliClimate) SetCO2Target(target float64) error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\nfunc (ic *IntelliClimate) SetRHTarget(target float64) error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\nfunc (ic *IntelliClimate) EnableCO2Dosing() error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\nfunc (ic *IntelliClimate) DisableCO2Dosing() error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\nfunc (ic *IntelliClimate) SetTempTarget(target float64) error ", "output": "{\n\treturn fmt.Errorf(\"not implemented\")\n}"} {"input": "package trace\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\ntype Tracer interface {\n\tTrace(...interface{})\n}\n\ntype tracer struct {\n\tout io.Writer\n}\n\nfunc (t *tracer) Trace(a ...interface{}) {\n\tt.out.Write([]byte(fmt.Sprint(a...)))\n\tt.out.Write([]byte(\"\\n\"))\n}\n\ntype nilTracer struct{}\n\nfunc (t *nilTracer) Trace(a ...interface{}) {}\n\n\nfunc Off() Tracer {\n\treturn &nilTracer{}\n}\n\n\n\nfunc New(w io.Writer) Tracer ", "output": "{\n\treturn &tracer{out: w}\n}"} {"input": "package auth\n\nimport (\n\tauthorizationapi \"github.com/projectatomic/atomic-enterprise/pkg/authorization/api\"\n\t\"github.com/projectatomic/atomic-enterprise/pkg/client\"\n)\n\n\ntype Review interface {\n\tUsers() []string\n\tGroups() []string\n}\n\ntype review struct {\n\tresponse *authorizationapi.ResourceAccessReviewResponse\n}\n\n\nfunc (r *review) Users() []string {\n\treturn r.response.Users.List()\n}\n\n\nfunc (r *review) Groups() []string {\n\treturn r.response.Groups.List()\n}\n\n\ntype Reviewer interface {\n\tReview(name string) (Review, error)\n}\n\n\ntype reviewer struct {\n\tresourceAccessReviewsNamespacer client.ResourceAccessReviewsNamespacer\n}\n\n\nfunc NewReviewer(resourceAccessReviewsNamespacer client.ResourceAccessReviewsNamespacer) Reviewer {\n\treturn &reviewer{\n\t\tresourceAccessReviewsNamespacer: resourceAccessReviewsNamespacer,\n\t}\n}\n\n\n\n\nfunc (r *reviewer) Review(name string) (Review, error) ", "output": "{\n\tresourceAccessReview := &authorizationapi.ResourceAccessReview{\n\t\tVerb: \"get\",\n\t\tResource: \"namespaces\",\n\t\tResourceName: name,\n\t}\n\n\tresponse, err := r.resourceAccessReviewsNamespacer.ResourceAccessReviews(name).Create(resourceAccessReview)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treview := &review{\n\t\tresponse: response,\n\t}\n\treturn review, nil\n}"} {"input": "package git\n\nimport (\n\t\"sync\"\n\n\t\"github.com/mholt/caddy/middleware/git/gitos\"\n)\n\n\n\ntype repoService struct {\n\trepo *Repo\n\tticker gitos.Ticker \n\thalt chan struct{} \n}\n\n\nfunc Start(repo *Repo) {\n\tservice := &repoService{\n\t\trepo,\n\t\tgos.NewTicker(repo.Interval),\n\t\tmake(chan struct{}),\n\t}\n\tgo func(s *repoService) {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-s.ticker.C():\n\t\t\t\terr := repo.Pull()\n\t\t\t\tif err != nil {\n\t\t\t\t\tLogger().Println(err)\n\t\t\t\t}\n\t\t\tcase <-s.halt:\n\t\t\t\ts.ticker.Stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(service)\n\n\tServices.add(service)\n}\n\n\ntype services struct {\n\tservices []*repoService\n\tsync.Mutex\n}\n\n\n\n\n\n\n\n\nfunc (s *services) Stop(repoURL string, limit int) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tfor i, j := 0, 0; i < len(s.services) && ((limit >= 0 && j < limit) || limit < 0); i++ {\n\t\tservice := s.services[i]\n\t\tif service.repo.URL == repoURL {\n\t\t\tservice.halt <- struct{}{}\n\t\t\ts.services[i] = nil\n\t\t\tj++\n\t\t}\n\t}\n\n\tservices := s.services[:0]\n\tfor _, s := range s.services {\n\t\tif s != nil {\n\t\t\tservices = append(services, s)\n\t\t}\n\t}\n\ts.services = services\n}\n\nfunc (s *services) add(r *repoService) ", "output": "{\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.services = append(s.services, r)\n}"} {"input": "package api_auth\n\nimport (\n\t\"golang.org/x/oauth2\"\n\t\"testing\"\n)\n\n\n\nfunc TestContext(t *testing.T) {\n\tc := NewContext(&oauth2.Token{}, &oauth2.Config{}, \"test-context\", []string{\"test-scope\"})\n\tif c.IsNoAuth() || c.PeerName() != \"test-context\" || c.Scopes()[0] != \"test-scope\" ||\n\t\tc.Description() != \"\" || c.Supplemental() != \"\" || c.Token() == nil {\n\t\tt.Error(\"invalid\")\n\t}\n\n\tc = NewContextWithAttr(c, &oauth2.Config{}, \"test-desc\", \"test-suppl\")\n\tif c.IsNoAuth() || c.PeerName() != \"test-context\" || c.Scopes()[0] != \"test-scope\" ||\n\t\tc.Description() != \"test-desc\" || c.Supplemental() != \"test-suppl\" || c.Token() == nil {\n\t\tt.Error(\"invalid\")\n\t}\n}\n\nfunc TestNoAuth(t *testing.T) ", "output": "{\n\ta := NewNoAuth()\n\tif !a.IsNoAuth() {\n\t\tt.Error(\"invalid\")\n\t}\n\tif a.PeerName() != \"\" || a.Token() == nil || a.PeerName() != \"\" ||\n\t\ta.Description() != \"\" || a.Supplemental() != \"\" || len(a.Scopes()) > 0 {\n\t\tt.Error(\"invalid\")\n\t}\n}"} {"input": "package types\n\n\n\n\nimport (\n\t\"github.com/jcmturner/gofork/encoding/asn1\"\n)\n\n\n\n\n\n\n\nfunc SetFlags(f *asn1.BitString, j []int) {\n\tfor _, i := range j {\n\t\tSetFlag(f, i)\n\t}\n}\n\n\nfunc SetFlag(f *asn1.BitString, i int) {\n\tfor l := len(f.Bytes); l < 4; l++ {\n\t\t(*f).Bytes = append((*f).Bytes, byte(0))\n\t\t(*f).BitLength = len((*f).Bytes) * 8\n\t}\n\tb := i / 8\n\tp := uint(7 - (i - 8*b))\n\t(*f).Bytes[b] = (*f).Bytes[b] | (1 << p)\n}\n\n\nfunc UnsetFlags(f *asn1.BitString, j []int) {\n\tfor _, i := range j {\n\t\tUnsetFlag(f, i)\n\t}\n}\n\n\nfunc UnsetFlag(f *asn1.BitString, i int) {\n\tfor l := len(f.Bytes); l < 4; l++ {\n\t\t(*f).Bytes = append((*f).Bytes, byte(0))\n\t\t(*f).BitLength = len((*f).Bytes) * 8\n\t}\n\tb := i / 8\n\tp := uint(7 - (i - 8*b))\n\t(*f).Bytes[b] = (*f).Bytes[b] &^ (1 << p)\n}\n\n\nfunc IsFlagSet(f *asn1.BitString, i int) bool {\n\tb := i / 8\n\tp := uint(7 - (i - 8*b))\n\tif (*f).Bytes[b]&(1< 0 {\n\t\tstringToMatch = fmt.Sprintf(matcher.Substr, matcher.Args...)\n\t}\n\treturn stringToMatch\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"github.com/obieq/goar/db/couchbase/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n\t\"time\"\n)\n\ntype BeTemporallyMatcher struct {\n\tComparator string\n\tCompareTo time.Time\n\tThreshold []time.Duration\n}\n\nfunc (matcher *BeTemporallyMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, fmt.Sprintf(\"to be %s\", matcher.Comparator), matcher.CompareTo)\n}\n\nfunc (matcher *BeTemporallyMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, fmt.Sprintf(\"not to be %s\", matcher.Comparator), matcher.CompareTo)\n}\n\n\n\nfunc (matcher *BeTemporallyMatcher) matchTimes(actual, compareTo time.Time, threshold time.Duration) (success bool) {\n\tswitch matcher.Comparator {\n\tcase \"==\":\n\t\treturn actual.Equal(compareTo)\n\tcase \"~\":\n\t\tdiff := actual.Sub(compareTo)\n\t\treturn -threshold <= diff && diff <= threshold\n\tcase \">\":\n\t\treturn actual.After(compareTo)\n\tcase \">=\":\n\t\treturn !actual.Before(compareTo)\n\tcase \"<\":\n\t\treturn actual.Before(compareTo)\n\tcase \"<=\":\n\t\treturn !actual.After(compareTo)\n\t}\n\treturn false\n}\n\nfunc (matcher *BeTemporallyMatcher) Match(actual interface{}) (bool, error) ", "output": "{\n\tisTime := func(t interface{}) bool {\n\t\t_, ok := t.(time.Time)\n\t\treturn ok\n\t}\n\n\tif !isTime(actual) {\n\t\treturn false, fmt.Errorf(\"Expected a time.Time. Got:\\n%s\", format.Object(actual, 1))\n\t}\n\n\tswitch matcher.Comparator {\n\tcase \"==\", \"~\", \">\", \">=\", \"<\", \"<=\":\n\tdefault:\n\t\treturn false, fmt.Errorf(\"Unknown comparator: %s\", matcher.Comparator)\n\t}\n\n\tvar threshold = time.Millisecond\n\tif len(matcher.Threshold) == 1 {\n\t\tthreshold = matcher.Threshold[0]\n\t}\n\n\treturn matcher.matchTimes(actual.(time.Time), matcher.CompareTo, threshold), nil\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/julienschmidt/httprouter\"\n)\n\n\n\nfunc UserCreate(w http.ResponseWriter, r *http.Request, p httprouter.Params) ", "output": "{\n\tfmt.Fprintln(w, \"posts create\")\n}"} {"input": "package fake_cmdpreparer\n\nimport (\n\t\"os/exec\"\n\t\"sync\"\n\n\t\"code.cloudfoundry.org/garden\"\n\t\"code.cloudfoundry.org/garden-linux/container_daemon\"\n)\n\ntype FakeCmdPreparer struct {\n\tPrepareCmdStub func(garden.ProcessSpec) (*exec.Cmd, error)\n\tprepareCmdMutex sync.RWMutex\n\tprepareCmdArgsForCall []struct {\n\t\targ1 garden.ProcessSpec\n\t}\n\tprepareCmdReturns struct {\n\t\tresult1 *exec.Cmd\n\t\tresult2 error\n\t}\n}\n\nfunc (fake *FakeCmdPreparer) PrepareCmd(arg1 garden.ProcessSpec) (*exec.Cmd, error) {\n\tfake.prepareCmdMutex.Lock()\n\tfake.prepareCmdArgsForCall = append(fake.prepareCmdArgsForCall, struct {\n\t\targ1 garden.ProcessSpec\n\t}{arg1})\n\tfake.prepareCmdMutex.Unlock()\n\tif fake.PrepareCmdStub != nil {\n\t\treturn fake.PrepareCmdStub(arg1)\n\t} else {\n\t\treturn fake.prepareCmdReturns.result1, fake.prepareCmdReturns.result2\n\t}\n}\n\nfunc (fake *FakeCmdPreparer) PrepareCmdCallCount() int {\n\tfake.prepareCmdMutex.RLock()\n\tdefer fake.prepareCmdMutex.RUnlock()\n\treturn len(fake.prepareCmdArgsForCall)\n}\n\nfunc (fake *FakeCmdPreparer) PrepareCmdArgsForCall(i int) garden.ProcessSpec {\n\tfake.prepareCmdMutex.RLock()\n\tdefer fake.prepareCmdMutex.RUnlock()\n\treturn fake.prepareCmdArgsForCall[i].arg1\n}\n\n\n\nvar _ container_daemon.CmdPreparer = new(FakeCmdPreparer)\n\nfunc (fake *FakeCmdPreparer) PrepareCmdReturns(result1 *exec.Cmd, result2 error) ", "output": "{\n\tfake.PrepareCmdStub = nil\n\tfake.prepareCmdReturns = struct {\n\t\tresult1 *exec.Cmd\n\t\tresult2 error\n\t}{result1, result2}\n}"} {"input": "package builder\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\n\tvelerov1api \"github.com/vmware-tanzu/velero/pkg/apis/velero/v1\"\n)\n\n\ntype PodVolumeBackupBuilder struct {\n\tobject *velerov1api.PodVolumeBackup\n}\n\n\nfunc ForPodVolumeBackup(ns, name string) *PodVolumeBackupBuilder {\n\treturn &PodVolumeBackupBuilder{\n\t\tobject: &velerov1api.PodVolumeBackup{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tAPIVersion: velerov1api.SchemeGroupVersion.String(),\n\t\t\t\tKind: \"PodVolumeBackup\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: name,\n\t\t\t},\n\t\t},\n\t}\n}\n\n\nfunc (b *PodVolumeBackupBuilder) Result() *velerov1api.PodVolumeBackup {\n\treturn b.object\n}\n\n\n\n\n\nfunc (b *PodVolumeBackupBuilder) Phase(phase velerov1api.PodVolumeBackupPhase) *PodVolumeBackupBuilder {\n\tb.object.Status.Phase = phase\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) SnapshotID(snapshotID string) *PodVolumeBackupBuilder {\n\tb.object.Status.SnapshotID = snapshotID\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) PodName(name string) *PodVolumeBackupBuilder {\n\tb.object.Spec.Pod.Name = name\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) Volume(volume string) *PodVolumeBackupBuilder {\n\tb.object.Spec.Volume = volume\n\treturn b\n}\n\nfunc (b *PodVolumeBackupBuilder) ObjectMeta(opts ...ObjectMetaOpt) *PodVolumeBackupBuilder ", "output": "{\n\tfor _, opt := range opts {\n\t\topt(b.object)\n\t}\n\n\treturn b\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSIoTAnalyticsPipeline_DeviceShadowEnrich struct {\n\n\tAttribute string `json:\"Attribute,omitempty\"`\n\n\tName string `json:\"Name,omitempty\"`\n\n\tNext string `json:\"Next,omitempty\"`\n\n\tRoleArn string `json:\"RoleArn,omitempty\"`\n\n\tThingName string `json:\"ThingName,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) AWSCloudFormationType() string {\n\treturn \"AWS::IoTAnalytics::Pipeline.DeviceShadowEnrich\"\n}\n\n\n\n\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) DependsOn() []string ", "output": "{\n\treturn r._dependsOn\n}"} {"input": "package kubernetes\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/weaveworks/scope/report\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/unversioned\"\n\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n\t\"k8s.io/kubernetes/pkg/labels\"\n)\n\n\nconst (\n\tUpdatedReplicas = \"kubernetes_updated_replicas\"\n\tAvailableReplicas = \"kubernetes_available_replicas\"\n\tUnavailableReplicas = \"kubernetes_unavailable_replicas\"\n\tStrategy = \"kubernetes_strategy\"\n)\n\n\ntype Deployment interface {\n\tMeta\n\tSelector() labels.Selector\n\tGetNode(probeID string) report.Node\n}\n\ntype deployment struct {\n\t*extensions.Deployment\n\tMeta\n\tNode *api.Node\n}\n\n\nfunc NewDeployment(d *extensions.Deployment) Deployment {\n\treturn &deployment{Deployment: d, Meta: meta{d.ObjectMeta}}\n}\n\nfunc (d *deployment) Selector() labels.Selector {\n\tselector, err := unversioned.LabelSelectorAsSelector(d.Spec.Selector)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn selector\n}\n\n\n\nfunc (d *deployment) GetNode(probeID string) report.Node ", "output": "{\n\treturn d.MetaNode(report.MakeDeploymentNodeID(d.UID())).WithLatests(map[string]string{\n\t\tObservedGeneration: fmt.Sprint(d.Status.ObservedGeneration),\n\t\tDesiredReplicas: fmt.Sprint(d.Spec.Replicas),\n\t\tReplicas: fmt.Sprint(d.Status.Replicas),\n\t\tUpdatedReplicas: fmt.Sprint(d.Status.UpdatedReplicas),\n\t\tAvailableReplicas: fmt.Sprint(d.Status.AvailableReplicas),\n\t\tUnavailableReplicas: fmt.Sprint(d.Status.UnavailableReplicas),\n\t\tStrategy: string(d.Spec.Strategy.Type),\n\t\treport.ControlProbeID: probeID,\n\t}).WithLatestActiveControls(ScaleUp, ScaleDown)\n}"} {"input": "package govaluate\n\ntype lexerStream struct {\n\tsource []rune\n\tposition int\n\tlength int\n}\n\nfunc newLexerStream(source string) *lexerStream {\n\n\tvar ret *lexerStream\n\tvar runes []rune\n\n\tfor _, character := range source {\n\t\trunes = append(runes, character)\n\t}\n\n\tret = new(lexerStream)\n\tret.source = runes\n\tret.length = len(runes)\n\treturn ret\n}\n\nfunc (l *lexerStream) readCharacter() rune {\n\n\tvar character rune\n\n\tcharacter = l.source[l.position]\n\tl.position++\n\treturn character\n}\n\n\n\nfunc (l lexerStream) canRead() bool {\n\treturn l.position < l.length\n}\n\nfunc (l *lexerStream) rewind(amount int) ", "output": "{\n\tl.position -= amount\n}"} {"input": "package errors \n\nimport (\n\t\"strconv\"\n)\n\n\n\ntype StructuralError string\n\nfunc (s StructuralError) Error() string {\n\treturn \"openpgp: invalid data: \" + string(s)\n}\n\n\n\ntype UnsupportedError string\n\nfunc (s UnsupportedError) Error() string {\n\treturn \"openpgp: unsupported feature: \" + string(s)\n}\n\n\n\ntype InvalidArgumentError string\n\nfunc (i InvalidArgumentError) Error() string {\n\treturn \"openpgp: invalid argument: \" + string(i)\n}\n\n\n\ntype SignatureError string\n\nfunc (b SignatureError) Error() string {\n\treturn \"openpgp: invalid signature: \" + string(b)\n}\n\ntype keyIncorrectError int\n\n\n\nvar ErrKeyIncorrect error = keyIncorrectError(0)\n\ntype unknownIssuerError int\n\nfunc (unknownIssuerError) Error() string {\n\treturn \"openpgp: signature made by unknown entity\"\n}\n\nvar ErrUnknownIssuer error = unknownIssuerError(0)\n\ntype keyRevokedError int\n\nfunc (keyRevokedError) Error() string {\n\treturn \"openpgp: signature made by revoked key\"\n}\n\nvar ErrKeyRevoked error = keyRevokedError(0)\n\ntype UnknownPacketTypeError uint8\n\nfunc (upte UnknownPacketTypeError) Error() string {\n\treturn \"openpgp: unknown packet type: \" + strconv.Itoa(int(upte))\n}\n\nfunc (ki keyIncorrectError) Error() string ", "output": "{\n\treturn \"openpgp: incorrect key\"\n}"} {"input": "package octokat\n\nimport (\n\t\"github.com/bmizerany/assert\"\n\t\"testing\"\n)\n\n\n\nfunc TestParamsDelete(t *testing.T) {\n\tp := Params{\"FOO\": \"BAR\"}\n\tv := p.Delete(\"FOO\")\n\n\tassert.Equal(t, 0, p.Size())\n\tassert.Equal(t, \"BAR\", v)\n\n\tv = p.Delete(\"BAR\")\n\tassert.Equal(t, 0, p.Size())\n\tassert.Equal(t, nil, v)\n}\n\nfunc TestParamsPut(t *testing.T) ", "output": "{\n\tp := Params{\"FOO\": \"BAR\"}\n\tv := p.Put(\"BAZ\", \"BAR\")\n\n\tassert.Equal(t, 2, p.Size())\n\tassert.Equal(t, nil, v)\n\n\tv = p.Put(\"FOO\", \"FOO\")\n\tassert.Equal(t, 2, p.Size())\n\tassert.Equal(t, \"BAR\", v)\n}"} {"input": "package instance_test\n\nimport (\n\t\"testing\"\n\n\t. \"launchpad.net/gocheck\"\n\n\t\"launchpad.net/juju-core/instance\"\n)\n\nfunc TestPackage(t *testing.T) {\n\tTestingT(t)\n}\n\ntype InstanceSuite struct{}\n\nvar _ = Suite(&InstanceSuite{})\n\nfunc (s *InstanceSuite) TestParseSupportedContainerType(c *C) {\n\tctype, err := instance.ParseSupportedContainerType(\"lxc\")\n\tc.Assert(err, IsNil)\n\tc.Assert(ctype, Equals, instance.ContainerType(\"lxc\"))\n\tctype, err = instance.ParseSupportedContainerType(\"none\")\n\tc.Assert(err, Not(IsNil))\n}\n\n\n\nfunc (s *InstanceSuite) TestParseSupportedContainerTypeOrNone(c *C) ", "output": "{\n\tctype, err := instance.ParseSupportedContainerTypeOrNone(\"lxc\")\n\tc.Assert(err, IsNil)\n\tc.Assert(ctype, Equals, instance.ContainerType(\"lxc\"))\n\tctype, err = instance.ParseSupportedContainerTypeOrNone(\"none\")\n\tc.Assert(err, IsNil)\n\tc.Assert(ctype, Equals, instance.ContainerType(\"none\"))\n}"} {"input": "package iso20022\n\n\ntype CardPaymentEnvironment37 struct {\n\n\tAcquirer *Acquirer4 `xml:\"Acqrr\"`\n\n\tMerchantIdentification *GenericIdentification53 `xml:\"MrchntId,omitempty\"`\n\n\tPOIIdentification *GenericIdentification53 `xml:\"POIId,omitempty\"`\n\n\tPOIComponent []*PointOfInteractionComponent5 `xml:\"POICmpnt,omitempty\"`\n}\n\n\n\nfunc (c *CardPaymentEnvironment37) AddMerchantIdentification() *GenericIdentification53 {\n\tc.MerchantIdentification = new(GenericIdentification53)\n\treturn c.MerchantIdentification\n}\n\nfunc (c *CardPaymentEnvironment37) AddPOIIdentification() *GenericIdentification53 {\n\tc.POIIdentification = new(GenericIdentification53)\n\treturn c.POIIdentification\n}\n\nfunc (c *CardPaymentEnvironment37) AddPOIComponent() *PointOfInteractionComponent5 {\n\tnewValue := new(PointOfInteractionComponent5)\n\tc.POIComponent = append(c.POIComponent, newValue)\n\treturn newValue\n}\n\nfunc (c *CardPaymentEnvironment37) AddAcquirer() *Acquirer4 ", "output": "{\n\tc.Acquirer = new(Acquirer4)\n\treturn c.Acquirer\n}"} {"input": "package main\n\nimport (\n\t\"sort\"\n)\n\n\ntype RankedCoordFinder struct {\n\tboard Board\n\tremaining []*Coord\n}\n\nfunc (f *RankedCoordFinder) NextOpenCoordinate(board Board, coord XY) (*Coord, bool) {\n\tf.board = board\n\tf.RefreshCoordinates()\n\n\tif len(f.remaining) == 0 {\n\t\treturn nil, false\n\t}\n\n\tc := f.remaining[0]\n\tf.remaining = f.remaining[0:]\n\n\treturn c, true\n}\n\nfunc (f *RankedCoordFinder) RefreshCoordinates() {\n\tf.remaining = []*Coord{}\n\tfor x := 0; x < len(f.board); x++ {\n\t\tfor y := 0; y < len(f.board); y++ {\n\t\t\tif f.board[x][y] == 0 {\n\t\t\t\tf.remaining = append(f.remaining, &Coord{x, y})\n\t\t\t}\n\t\t}\n\t}\n\tsort.Sort(f)\n}\n\n\nfunc (f *RankedCoordFinder) Less(i, j int) bool {\n\treturn len(f.board.AvailableValuesAtCoordinate(f.remaining[i])) <\n\t\tlen(f.board.AvailableValuesAtCoordinate(f.remaining[j]))\n}\nfunc (f *RankedCoordFinder) Swap(i, j int) {\n\tf.remaining[i], f.remaining[j] = f.remaining[j], f.remaining[i]\n}\n\nfunc (f *RankedCoordFinder) Len() int ", "output": "{\n\treturn len(f.remaining)\n}"} {"input": "package header\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\t\"github.com/google/martian\"\n\t\"github.com/google/martian/parse\"\n)\n\nfunc init() {\n\tparse.Register(\"header.Modifier\", modifierFromJSON)\n}\n\ntype modifier struct {\n\tname, value string\n}\n\ntype modifierJSON struct {\n\tName string `json:\"name\"`\n\tValue string `json:\"value\"`\n\tScope []parse.ModifierType `json:\"scope\"`\n}\n\n\nfunc (m *modifier) ModifyRequest(req *http.Request) error {\n\tif m.name == \"Host\" {\n\t\treq.Host = m.value\n\t} else {\n\t\treq.Header.Set(m.name, m.value)\n\t}\n\n\treturn nil\n}\n\n\nfunc (m *modifier) ModifyResponse(res *http.Response) error {\n\tres.Header.Set(m.name, m.value)\n\n\treturn nil\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc modifierFromJSON(b []byte) (*parse.Result, error) {\n\tmsg := &modifierJSON{}\n\tif err := json.Unmarshal(b, msg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmodifier := NewModifier(msg.Name, msg.Value)\n\n\treturn parse.NewResult(modifier, msg.Scope)\n}\n\nfunc NewModifier(name, value string) martian.RequestResponseModifier ", "output": "{\n\treturn &modifier{\n\t\tname: http.CanonicalHeaderKey(name),\n\t\tvalue: value,\n\t}\n}"} {"input": "package shasimd\n\nimport (\n\t\"github.com/1lann/krist-miner/deprecated/sha2\"\n\t\"github.com/1lann/sha256-simd\"\n)\n\ntype generator struct{}\n\nfunc (g *generator) Sum256Number(data []byte) int64 {\n\tvar start [64]byte\n\tstart[41] = 128\n\tstart[63] = 72\n\tstart[62] = 1\n\n\tif len(data) != 41 {\n\t\tpanic(\"must be exactly 41 long\")\n\t}\n\tcopy(start[:], data)\n\n\treturn sha256.SumToNum256(start[:])\n}\n\nfunc (g *generator) Sum256NumberCmp(data []byte, work int64) bool {\n\tvar start [64]byte\n\tstart[41] = 128\n\tstart[63] = 72\n\tstart[62] = 1\n\n\tif len(data) != 41 {\n\t\tpanic(\"must be exactly 41 long\")\n\t}\n\tcopy(start[:], data)\n\n\treturn sha256.SumCmp256(start[:], uint32(work))\n}\n\n\n\nfunc init() ", "output": "{\n\tsha2.RegisterAlgorithm(\"simd\", func() sha2.SumNumberAlgorithm {\n\t\treturn &generator{}\n\t})\n}"} {"input": "package service\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/BurntSushi/toml\"\n\t\"github.com/nebulaim/telegramd/baselib/grpc_util\"\n\t\"github.com/nebulaim/telegramd/baselib/mysql_client\"\n\t\"github.com/nebulaim/telegramd/baselib/redis_client\"\n)\n\nvar (\n\tconfPath string\n\tConf *documentConfig\n)\n\ntype documentConfig struct {\n\tServerId int32 \n\tDataPath string\n\tRedis []redis_client.RedisConfig\n\tMysql []mysql_client.MySQLConfig\n\tRpcServer *grpc_util.RPCServerConfig\n}\n\nfunc (c *documentConfig) String() string {\n\treturn fmt.Sprintf(\"{server_id: %d, redis: %v. mysql: %v, server: %v}\",\n\t\tc.ServerId,\n\t\tc.Redis,\n\t\tc.Mysql,\n\t\tc.RpcServer)\n}\n\n\n\nfunc InitializeConfig() (err error) {\n\t_, err = toml.DecodeFile(confPath, &Conf)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"decode file %s error: %v\", confPath, err)\n\t}\n\treturn\n}\n\nfunc init() ", "output": "{\n\tflag.StringVar(&confPath, \"conf\", \"./document.toml\", \"config path\")\n}"} {"input": "package soong_compat\n\nimport (\n\t\"android/soong/android\"\n)\n\n\n\nfunc ConvertAndroidMkExtraEntriesFunc(f AndroidMkExtraEntriesFunc) []android.AndroidMkExtraEntriesFunc {\n\treturn []android.AndroidMkExtraEntriesFunc{\n\t\tfunc(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {\n\t\t\tf(entries)\n\t\t},\n\t}\n}\n\n\n\nfunc SoongSupportsMkInstallTargets() bool ", "output": "{\n\treturn true\n}"} {"input": "package runcmd\n\n\n\nfunc (c *Command) useShell() ", "output": "{\n\tcommand := c.CommandLine\n\tc.Exe = \"cmd\"\n\tc.Args = []string{\"/C\", command}\n}"} {"input": "package restutil\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/eclipse/che/agents/go-agents/core/rest\"\n)\n\n\nfunc WriteJSON(w http.ResponseWriter, body interface{}) error {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\treturn json.NewEncoder(w).Encode(body)\n}\n\n\n\n\n\n\nfunc IntQueryParam(r *http.Request, name string, defaultValue int) int {\n\tqp := r.URL.Query().Get(name)\n\tif qp == \"\" {\n\t\treturn defaultValue\n\t}\n\tv, err := strconv.Atoi(qp)\n\tif err != nil {\n\t\treturn defaultValue\n\t}\n\tif v < 0 {\n\t\treturn defaultValue\n\t}\n\treturn v\n}\n\n\nfunc OKRespondingFunc(w http.ResponseWriter, r *http.Request, _ rest.Params) error {\n\tw.WriteHeader(http.StatusOK)\n\treturn nil\n}\n\nfunc ReadJSON(r *http.Request, v interface{}) error ", "output": "{\n\treturn json.NewDecoder(r.Body).Decode(v)\n}"} {"input": "package main\n\nimport \"testing\"\n\n\n\nfunc TestExport(t *testing.T) ", "output": "{\n\tExport()\n}"} {"input": "package router\n\n\n\n\nimport (\n\t\"github.com/weaveworks/mesh\"\n)\n\n\n\ntype AWSVPCConnection struct {\n\testablishedChan chan struct{}\n\terrorChan chan error\n}\n\nfunc (conn *AWSVPCConnection) Confirm() {\n\tclose(conn.establishedChan)\n}\n\nfunc (conn *AWSVPCConnection) EstablishedChannel() <-chan struct{} {\n\treturn conn.establishedChan\n}\n\nfunc (conn *AWSVPCConnection) ErrorChannel() <-chan error {\n\treturn conn.errorChan\n}\n\nfunc (conn *AWSVPCConnection) Stop() {}\n\nfunc (conn *AWSVPCConnection) ControlMessage(tag byte, msg []byte) {\n}\n\n\n\n\n\nfunc (conn *AWSVPCConnection) Forward(key ForwardPacketKey) FlowOp {\n\treturn DiscardingFlowOp{}\n}\n\ntype AWSVPC struct{}\n\nfunc NewAWSVPC() AWSVPC {\n\treturn AWSVPC{}\n}\n\n\n\nfunc (vpc AWSVPC) AddFeaturesTo(features map[string]string) {}\n\nfunc (vpc AWSVPC) PrepareConnection(params mesh.OverlayConnectionParams) (mesh.OverlayConnection, error) {\n\tconn := &AWSVPCConnection{\n\t\testablishedChan: make(chan struct{}),\n\t\terrorChan: make(chan error, 1),\n\t}\n\treturn conn, nil\n}\n\nfunc (vpc AWSVPC) Diagnostics() interface{} {\n\treturn nil\n}\n\n\n\nfunc (vpc AWSVPC) InvalidateRoutes() {}\n\nfunc (vpc AWSVPC) InvalidateShortIDs() {}\n\nfunc (vpc AWSVPC) StartConsumingPackets(localPeer *mesh.Peer, peers *mesh.Peers, consumer OverlayConsumer) error {\n\treturn nil\n}\n\nfunc (conn *AWSVPCConnection) DisplayName() string ", "output": "{\n\treturn \"awsvpc\"\n}"} {"input": "package main\nimport (\n\"fmt\"\n\"time\"\n)\n\nfunc fib(x int) int{\n if x<2{\n return x\n }\n return fib(x-1)+fib(x-2)\n}\n\nfunc main() {\n go spinner(100*time.Millisecond)\n const n=45\n fibN:=fib(n)\n fmt.Printf(\"\\rFibonacci(%d)=%d\\n\",n,fibN)\n}\n\n\n\nfunc spinner(delay time.Duration)", "output": "{\n for{\n for _,r:=range `-\\|/`{\n fmt.Printf(\"\\r%c\",r)\n time.Sleep(delay)\n }\n }\n}"} {"input": "package vagrant\n\nimport (\n\t\"github.com/mitchellh/packer/packer\"\n\t\"testing\"\n)\n\nfunc testConfig() map[string]interface{} {\n\treturn map[string]interface{}{}\n}\n\nfunc TestPostProcessor_ImplementsPostProcessor(t *testing.T) {\n\tvar raw interface{}\n\traw = &PostProcessor{}\n\tif _, ok := raw.(packer.PostProcessor); !ok {\n\t\tt.Fatalf(\"AWS PostProcessor should be a PostProcessor\")\n\t}\n}\n\n\n\nfunc TestBuilderPrepare_PPConfig(t *testing.T) {\n\tvar p PostProcessor\n\n\tc := testConfig()\n\tc[\"aws\"] = map[string]interface{}{}\n\terr := p.Configure(c)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n}\n\nfunc TestBuilderPrepare_OutputPath(t *testing.T) ", "output": "{\n\tvar p PostProcessor\n\n\tc := testConfig()\n\tdelete(c, \"output\")\n\terr := p.Configure(c)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tc[\"output\"] = \"bad {{{{.Template}}}}\"\n\terr = p.Configure(c)\n\tif err == nil {\n\t\tt.Fatal(\"should have error\")\n\t}\n}"} {"input": "package flog\n\nimport \"github.com/Sirupsen/logrus\"\n\ntype Parameter interface {\n\tConvert() map[string]interface{}\n}\n\ntype Fields struct {\n\tEvent string\n\tError error\n}\n\nfunc (f Fields) Convert() map[string]interface{} {\n\tfields := map[string]interface{}{}\n\n\tif f.Event != \"\" {\n\t\tfields[\"event\"] = f.Event\n\t}\n\n\tif f.Error != nil {\n\t\tfields[\"error\"] = f.Error\n\t}\n\n\treturn fields\n}\n\ntype Details map[string]interface{}\n\nfunc (d Details) Convert() map[string]interface{} {\n\treturn d\n}\n\ntype DebugFields map[string]interface{}\n\nfunc (d DebugFields) Convert() map[string]interface{} {\n\treturn map[string]interface{}{}\n}\n\nfunc transform(params []Parameter) logrus.Fields {\n\tlogrusFields := logrus.Fields{}\n\n\tfor _, p := range params {\n\t\tfieldMap := p.Convert()\n\n\t\tfor k, v := range fieldMap {\n\t\t\tlogrusFields[k] = v\n\t\t}\n\t}\n\n\treturn logrusFields\n}\n\nfunc Debug(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Debug(msg)\n}\n\nfunc Info(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Info(msg)\n}\n\nfunc Warn(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Warning(msg)\n}\n\nfunc Error(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Error(msg)\n}\n\n\n\nfunc Panic(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Panic(msg)\n}\n\nfunc Fatal(msg string, params ...Parameter) ", "output": "{\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Fatal(msg)\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/labstack/echo\"\n)\n\n\ntype Error struct {\n\tMessage string `json:\"message\"`\n}\n\n\nfunc OK(c echo.Context, payload interface{}) error {\n\treturn c.JSON(http.StatusOK, payload)\n}\n\n\nfunc Created(c echo.Context, payload interface{}) error {\n\treturn c.JSON(http.StatusCreated, payload)\n}\n\n\nfunc NoContent(c echo.Context) error {\n\treturn c.NoContent(http.StatusNoContent)\n}\n\n\n\n\n\nfunc NotFound(c echo.Context) error {\n\treturn c.JSON(http.StatusNotFound, Error{\"Resource not found\"})\n}\n\n\nfunc Conflict(c echo.Context, msg string) error {\n\treturn c.JSON(http.StatusConflict, Error{msg})\n}\n\n\nfunc Invalid(c echo.Context, msg string) error {\n\treturn c.JSON(422, Error{msg})\n}\n\n\n\nfunc InternalServerError(c echo.Context, err error) error {\n\tlog.WithFields(log.Fields{\n\t\t\"request_id\": RequestID(c),\n\t}).Error(err)\n\n\treturn c.JSON(http.StatusInternalServerError, Error{\"Oops! Something went wrong\"})\n}\n\nfunc BadRequest(c echo.Context, msg string) error ", "output": "{\n\treturn c.JSON(http.StatusBadRequest, Error{msg})\n}"} {"input": "package system\n\nimport \"strings\"\n\n\n\n\n\n\ntype Args []string\n\n\n\n\nfunc (a Args) Get(n int) string {\n\tif n >= 0 && n < len(a) {\n\t\treturn a[n]\n\t}\n\treturn \"\"\n}\n\n\n\n\n\n\nfunc (a Args) AfterN(n int) string {\n\tif n >= 0 && n < len(a) {\n\t\treturn strings.Join(a[n:], \" \")\n\t}\n\treturn \"\"\n}\n\nfunc (a Args) After() string ", "output": "{\n\treturn a.AfterN(0)\n}"} {"input": "package circuitbreaker\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/mailgun/log\"\n\t\"github.com/mailgun/vulcan/netutils\"\n)\n\ntype SideEffect interface {\n\tExec() error\n}\n\ntype Webhook struct {\n\tURL string\n\tMethod string\n\tHeaders http.Header\n\tForm url.Values\n\tBody []byte\n}\n\ntype WebhookSideEffect struct {\n\tw Webhook\n}\n\nfunc NewWebhookSideEffect(w Webhook) (*WebhookSideEffect, error) {\n\tif w.Method == \"\" {\n\t\treturn nil, fmt.Errorf(\"Supply method\")\n\t}\n\t_, err := netutils.ParseUrl(w.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &WebhookSideEffect{w: w}, nil\n}\n\nfunc (w *WebhookSideEffect) getBody() io.Reader {\n\tif len(w.w.Form) != 0 {\n\t\treturn strings.NewReader(w.w.Form.Encode())\n\t}\n\tif len(w.w.Body) != 0 {\n\t\treturn bytes.NewBuffer(w.w.Body)\n\t}\n\treturn nil\n}\n\n\n\nfunc (w *WebhookSideEffect) Exec() error ", "output": "{\n\tr, err := http.NewRequest(w.w.Method, w.w.URL, w.getBody())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(w.w.Headers) != 0 {\n\t\tnetutils.CopyHeaders(r.Header, w.w.Headers)\n\t}\n\tif len(w.w.Form) != 0 {\n\t\tr.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t}\n\tre, err := http.DefaultClient.Do(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif re.Body != nil {\n\t\tdefer re.Body.Close()\n\t}\n\tbody, err := ioutil.ReadAll(re.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Infof(\"%v got response: (%s): %s\", w, re.Status, string(body))\n\treturn nil\n}"} {"input": "package commands\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cloudfoundry/bosh-bootloader/bosh\"\n\t\"github.com/coreos/go-semver/semver\"\n)\n\n\n\nfunc fastFailBOSHVersion(boshManager boshManager) error ", "output": "{\n\tversion, err := boshManager.Version()\n\tswitch err.(type) {\n\tcase bosh.BOSHVersionError:\n\t\treturn nil\n\tcase error:\n\t\treturn err\n\t}\n\n\tcurrentVersion, err := semver.NewVersion(version)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tminimumVersion, err := semver.NewVersion(\"2.0.48\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif currentVersion.LessThan(*minimumVersion) {\n\t\tpath := boshManager.Path()\n\t\treturn fmt.Errorf(\"%s: bosh-cli version must be at least v2.0.48, but found v%s\", path, currentVersion)\n\t}\n\n\treturn nil\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n)\n\n\n\n\nfunc MakeName(name, version string) string {\n\treturn fmt.Sprintf(\"%s/v%s/%s/%s\", name, version, runtime.GOOS, runtime.Version())\n}\n\n\n\nfunc AbsolutePath(Datadir string, filename string) string {\n\tif filepath.IsAbs(filename) {\n\t\treturn filename\n\t}\n\treturn filepath.Join(Datadir, filename)\n}\n\nfunc FileExist(filePath string) bool ", "output": "{\n\t_, err := os.Stat(filePath)\n\tif err != nil && os.IsNotExist(err) {\n\t\treturn false\n\t}\n\n\treturn true\n}"} {"input": "package whisper\n\nimport \"github.com/Tzunami/go-earthdollar/crypto\"\n\n\n\n\ntype Topic [4]byte\n\n\n\n\nfunc NewTopic(data []byte) Topic {\n\tprefix := [4]byte{}\n\tcopy(prefix[:], crypto.Keccak256(data)[:4])\n\treturn Topic(prefix)\n}\n\n\n\nfunc NewTopics(data ...[]byte) []Topic {\n\ttopics := make([]Topic, len(data))\n\tfor i, element := range data {\n\t\ttopics[i] = NewTopic(element)\n\t}\n\treturn topics\n}\n\n\nfunc (self *Topic) String() string {\n\treturn string(self[:])\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype topicMatcher struct {\n\tconditions []map[Topic]struct{}\n}\n\n\nfunc newTopicMatcher(topics ...[]Topic) *topicMatcher {\n\tmatcher := make([]map[Topic]struct{}, len(topics))\n\tfor i, condition := range topics {\n\t\tmatcher[i] = make(map[Topic]struct{})\n\t\tfor _, topic := range condition {\n\t\t\tmatcher[i][topic] = struct{}{}\n\t\t}\n\t}\n\treturn &topicMatcher{conditions: matcher}\n}\n\n\n\n\nfunc (self *topicMatcher) Matches(topics []Topic) bool ", "output": "{\n\tif len(self.conditions) > len(topics) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(topics) && i < len(self.conditions); i++ {\n\t\tif len(self.conditions[i]) > 0 {\n\t\t\tif _, ok := self.conditions[i][topics[i]]; !ok {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSDynamoDBTable_TimeToLiveSpecification struct {\n\n\tAttributeName string `json:\"AttributeName,omitempty\"`\n\n\tEnabled bool `json:\"Enabled\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) AWSCloudFormationType() string {\n\treturn \"AWS::DynamoDB::Table.TimeToLiveSpecification\"\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\n\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetMetadata(metadata map[string]interface{}) ", "output": "{\n\tr._metadata = metadata\n}"} {"input": "package allowlists\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/protobuf/types/known/emptypb\"\n\n\t\"go.chromium.org/luci/auth_service/api/rpcpb\"\n\t\"go.chromium.org/luci/auth_service/impl/model\"\n\t\"go.chromium.org/luci/gae/service/datastore\"\n)\n\n\ntype Server struct {\n\trpcpb.UnimplementedAllowlistsServer\n}\n\n\nfunc (*Server) ListAllowlists(ctx context.Context, _ *emptypb.Empty) (*rpcpb.ListAllowlistsResponse, error) {\n\tallowlists, err := model.GetAllAuthIPAllowlists(ctx)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to fetch allowlists: %s\", err)\n\t}\n\n\tallowlistList := make([]*rpcpb.Allowlist, len(allowlists))\n\tfor idx, entity := range allowlists {\n\t\tallowlistList[idx] = entity.ToProto()\n\t}\n\n\treturn &rpcpb.ListAllowlistsResponse{\n\t\tAllowlists: allowlistList,\n\t}, nil\n}\n\n\n\n\nfunc (*Server) GetAllowlist(ctx context.Context, request *rpcpb.GetAllowlistRequest) (*rpcpb.Allowlist, error) ", "output": "{\n\tswitch allowlist, err := model.GetAuthIPAllowlist(ctx, request.Name); {\n\tcase err == nil:\n\t\treturn allowlist.ToProto(), nil\n\tcase err == datastore.ErrNoSuchEntity:\n\t\treturn nil, status.Errorf(codes.NotFound, \"no such allowlist %q\", request.Name)\n\tdefault:\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to fetch allowlist %q: %s\", request.Name, err)\n\t}\n}"} {"input": "package nogo\n\n\ntype Permission int\n\n\ntype Principal interface {\n\tGetId() string\n\tGetSid() string\n\tGetRoleNames() []string\n}\n\n\ntype Role interface {\n\tGetName() string\n\tIsAdmin() bool\n\tHasPermission(permission Permission) (bool, error)\n}\n\n\nfunc NewRole(name string, mask Permission) Role {\n\treturn &defaultRole{RoleName: name, PermissionMask: mask, Admin: false}\n}\n\n\nfunc NewAdminRole(name string, mask Permission) Role {\n\treturn &defaultRole{RoleName: name, PermissionMask: mask, Admin: true}\n}\n\ntype defaultRole struct {\n\tRoleName string `db:\"role_name\"`\n\tPermissionMask Permission `db:\"permission_mask\"`\n\tAdmin bool `db:\"is_admin\"`\n}\n\nfunc (this *defaultRole) GetName() string {\n\treturn this.RoleName\n}\n\nfunc (this *defaultRole) IsAdmin() bool {\n\treturn this.Admin\n}\n\n\n\nfunc (this *defaultRole) HasPermission(permission Permission) (bool, error) ", "output": "{\n\tval := (this.PermissionMask&permission != 0)\n\treturn val, nil\n}"} {"input": "package json_iterator\n\nimport \"testing\"\n\nvar data []byte\n\nfunc BenchmarkNode_String(b *testing.B) {\n\tn := Node{\n\t\tName: \"root\",\n\t\tValue: 1,\n\t}\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tdata = []byte(n.String())\n\t}\n}\n\n\n\nfunc BenchmarkNode_Initialize(b *testing.B) ", "output": "{\n\tn := Node{}\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = n.Initialize(data)\n\t}\n}"} {"input": "package richtext\n\nimport (\n\t\"fmt\"\n)\n\ntype AnsiFormat8 struct{ ansiFormat }\n\nvar _ Format = &AnsiFormat8{}\n\nvar ansiFormat8 *AnsiFormat8\n\nfunc init() {\n\tansiFormat8 = &AnsiFormat8{}\n\tansiFormat8.init(ansiFormat8)\n}\n\nfunc Ansi8() *AnsiFormat8 { return ansiFormat8 }\n\nfunc rgbTo8(c Color) uint8 {\n\tr, g, b := rgb(c)\n\tr1 := r >> 7\n\tg1 := g >> 7\n\tb1 := b >> 7\n\treturn b1<<2 + g1<<1 + r1\n}\n\nfunc (a *AnsiFormat8) MakePrintf(fg, bg Color, flags ...Flag) func(format string, a ...interface{}) (int, error) {\n\tenc := []string{}\n\tif fg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 30+rgbTo8(fg)))\n\t}\n\tif bg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 40+rgbTo8(bg)))\n\t}\n\n\treturn ansiPrinter(enc, flags)\n}\n\n\n\nfunc (a *AnsiFormat8) MakeSprintf(fg, bg Color, flags ...Flag) func(format string, a ...interface{}) string ", "output": "{\n\tenc := []string{}\n\tif fg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 30+rgbTo8(fg)))\n\t}\n\tif bg != None {\n\t\tenc = append(enc, fmt.Sprintf(\"%d\", 40+rgbTo8(bg)))\n\t}\n\n\treturn ansiSPrinter(enc, flags)\n}"} {"input": "package parlib\n\nimport (\n\t\"errors\"\n)\n\n\n\n\n\n\n\nfunc StringByteSlice(s string) []byte {\n\ta, err := ByteSliceFromString(s)\n\tif err != nil {\n\t\tpanic(\"syscall: string with NUL passed to StringByteSlice\")\n\t}\n\treturn a\n}\n\n\n\n\nfunc ByteSliceFromString(s string) ([]byte, error) {\n\tfor i := 0; i < len(s); i++ {\n\t\tif s[i] == 0 {\n\t\t\treturn nil, errors.New(\"String contains a NULL byte.\")\n\t\t}\n\t}\n\ta := make([]byte, len(s)+1)\n\tcopy(a, s)\n\treturn a, nil\n}\n\n\n\n\nfunc StringBytePtr(s string) *byte { return &StringByteSlice(s)[0] }\n\n\n\n\nfunc BytePtrFromString(s string) (*byte, error) {\n\ta, err := ByteSliceFromString(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &a[0], nil\n}\n\n\n\n\nfunc StringSlicePtr(ss []string) []*byte {\n bb := make([]*byte, len(ss)+1)\n for i := 0; i < len(ss); i++ {\n bb[i] = StringBytePtr(ss[i])\n }\n bb[len(ss)] = nil\n return bb\n}\n\n\n\n\nfunc SlicePtrFromStrings(ss []string) ([]*byte, error) {\n var err error\n bb := make([]*byte, len(ss)+1)\n for i := 0; i < len(ss); i++ {\n bb[i], err = BytePtrFromString(ss[i])\n if err != nil {\n return nil, err\n }\n }\n bb[len(ss)] = nil\n return bb, nil\n}\n\nfunc Cstrlen(str []byte) int ", "output": "{\n var i int = 0\n for (str[i] != 0) { i++ }\n return i\n}"} {"input": "package memfs\n\nimport (\n\t\"io\"\n\t\"testing\"\n\n\t\"gopkg.in/src-d/go-billy.v4\"\n\t\"gopkg.in/src-d/go-billy.v4/test\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype MemorySuite struct {\n\ttest.FilesystemSuite\n\tpath string\n}\n\nvar _ = Suite(&MemorySuite{})\n\n\n\nfunc (s *MemorySuite) TestCapabilities(c *C) {\n\t_, ok := s.FS.(billy.Capable)\n\tc.Assert(ok, Equals, true)\n\n\tcaps := billy.Capabilities(s.FS)\n\tc.Assert(caps, Equals, billy.DefaultCapabilities&^billy.LockCapability)\n}\n\nfunc (s *MemorySuite) TestNegativeOffsets(c *C) {\n\tf, err := s.FS.Create(\"negative\")\n\tc.Assert(err, IsNil)\n\n\tbuf := make([]byte, 100)\n\t_, err = f.ReadAt(buf, -100)\n\tc.Assert(err, ErrorMatches, \"readat negative: negative offset\")\n\n\t_, err = f.Seek(-100, io.SeekCurrent)\n\tc.Assert(err, IsNil)\n\t_, err = f.Write(buf)\n\tc.Assert(err, ErrorMatches, \"writeat negative: negative offset\")\n}\n\nfunc (s *MemorySuite) SetUpTest(c *C) ", "output": "{\n\ts.FilesystemSuite = test.NewFilesystemSuite(New())\n}"} {"input": "package lago\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype ScopedLogger struct {\n\tlog Logger\n\tscp string\n\tfmt string\n}\n\n\nfunc NewScopedLogger(log Logger, scope string, padding int) *ScopedLogger {\n\tformat := \"-%\" + intToStringWithSign(padding) + \"s: %s\"\n\n\tl := &ScopedLogger{\n\t\tlog: log,\n\t\tscp: scope,\n\t\tfmt: format,\n\t}\n\n\treturn l\n}\n\n\n\n\n\nfunc (l *ScopedLogger) Infof(format string, args ...interface{}) {\n\tl.log.Infof(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\n\nfunc (l *ScopedLogger) Warnf(format string, args ...interface{}) {\n\tl.log.Warnf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\n\nfunc (l *ScopedLogger) Fatalf(format string, args ...interface{}) {\n\tl.log.Fatalf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\nfunc intToStringWithSign(i int) string {\n\ta := strconv.Itoa(i)\n\ts := \"+\"\n\tif i < 0 {\n\t\ts = \"-\"\n\t}\n\ta = s + a\n\n\treturn a\n}\n\nfunc (l *ScopedLogger) Errorf(format string, args ...interface{}) ", "output": "{\n\tl.log.Errorf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}"} {"input": "package jmespath\n\nimport \"strconv\"\n\n\n\ntype JMESPath struct {\n\tast ASTNode\n\tintr *treeInterpreter\n}\n\n\n\n\n\n\n\n\nfunc MustCompile(expression string) *JMESPath {\n\tjmespath, err := Compile(expression)\n\tif err != nil {\n\t\tpanic(`jmespath: Compile(` + strconv.Quote(expression) + `): ` + err.Error())\n\t}\n\treturn jmespath\n}\n\n\nfunc (jp *JMESPath) Search(data interface{}) (interface{}, error) {\n\treturn jp.intr.Execute(jp.ast, data)\n}\n\n\nfunc Search(expression string, data interface{}) (interface{}, error) {\n\tintr := newInterpreter()\n\tparser := NewParser()\n\tast, err := parser.Parse(expression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn intr.Execute(ast, data)\n}\n\nfunc Compile(expression string) (*JMESPath, error) ", "output": "{\n\tparser := NewParser()\n\tast, err := parser.Parse(expression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tjmespath := &JMESPath{ast: ast, intr: newInterpreter()}\n\treturn jmespath, nil\n}"} {"input": "package iso20022\n\n\ntype PartyIdentificationAndAccount77 struct {\n\n\tIdentification *PartyIdentification32Choice `xml:\"Id\"`\n\n\tAlternateIdentification *AlternatePartyIdentification5 `xml:\"AltrnId,omitempty\"`\n\n\tSafekeepingAccount *Max35Text `xml:\"SfkpgAcct,omitempty\"`\n\n\tProcessingIdentification *Max35Text `xml:\"PrcgId,omitempty\"`\n\n\tAdditionalInformation *PartyTextInformation1 `xml:\"AddtlInf,omitempty\"`\n}\n\nfunc (p *PartyIdentificationAndAccount77) AddIdentification() *PartyIdentification32Choice {\n\tp.Identification = new(PartyIdentification32Choice)\n\treturn p.Identification\n}\n\n\n\nfunc (p *PartyIdentificationAndAccount77) SetSafekeepingAccount(value string) {\n\tp.SafekeepingAccount = (*Max35Text)(&value)\n}\n\nfunc (p *PartyIdentificationAndAccount77) SetProcessingIdentification(value string) {\n\tp.ProcessingIdentification = (*Max35Text)(&value)\n}\n\nfunc (p *PartyIdentificationAndAccount77) AddAdditionalInformation() *PartyTextInformation1 {\n\tp.AdditionalInformation = new(PartyTextInformation1)\n\treturn p.AdditionalInformation\n}\n\nfunc (p *PartyIdentificationAndAccount77) AddAlternateIdentification() *AlternatePartyIdentification5 ", "output": "{\n\tp.AlternateIdentification = new(AlternatePartyIdentification5)\n\treturn p.AlternateIdentification\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"github.com/go-swagger/go-swagger/errors\"\n\t\"github.com/go-swagger/go-swagger/httpkit/validate\"\n\t\"github.com/go-swagger/go-swagger/strfmt\"\n)\n\n\ntype Ticket struct {\n\n\tEventID string `json:\"event_id,omitempty\"`\n\n\tNum int32 `json:\"num,omitempty\"`\n}\n\n\n\n\nfunc (m *Ticket) validateEventID(formats strfmt.Registry) error {\n\n\tif err := validate.RequiredString(\"event_id\", \"body\", string(m.EventID)); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *Ticket) validateNum(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"num\", \"body\", int32(m.Num)); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *Ticket) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateEventID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNum(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package command\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\ntype VersionCommand struct {\n\tMeta\n\n\tRevision string\n\tVersion string\n\tVersionPrerelease string\n\tCheckFunc VersionCheckFunc\n}\n\n\n\ntype VersionCheckFunc func() (VersionCheckInfo, error)\n\n\n\n\ntype VersionCheckInfo struct {\n\tOutdated bool\n\tLatest string\n\tAlerts []string\n}\n\n\n\nfunc (c *VersionCommand) Run(args []string) int {\n\tvar versionString bytes.Buffer\n\n\tfmt.Fprintf(&versionString, \"Otto v%s\", c.Version)\n\tif c.VersionPrerelease != \"\" {\n\t\tfmt.Fprintf(&versionString, \"-%s\", c.VersionPrerelease)\n\n\t\tif c.Revision != \"\" {\n\t\t\tfmt.Fprintf(&versionString, \" (%s)\", c.Revision)\n\t\t}\n\t}\n\n\tc.Ui.Output(versionString.String())\n\n\tif c.CheckFunc != nil {\n\t\tc.Ui.Output(\"\")\n\n\t\tinfo, err := c.CheckFunc()\n\t\tif err != nil {\n\t\t\tc.Ui.Error(fmt.Sprintf(\n\t\t\t\t\"Error checking latest version: %s\", err))\n\t\t}\n\t\tif info.Outdated {\n\t\t\tc.Ui.Output(fmt.Sprintf(\n\t\t\t\t\"Your version of Otto is out of date! The latest version\\n\"+\n\t\t\t\t\t\"is %s. You can update by downloading from www.ottoproject.io\",\n\t\t\t\tinfo.Latest))\n\t\t}\n\t}\n\n\treturn 0\n}\n\nfunc (c *VersionCommand) Synopsis() string {\n\treturn \"Prints the Otto version\"\n}\n\nfunc (c *VersionCommand) Help() string ", "output": "{\n\treturn \"\"\n}"} {"input": "package main\n\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/fcgi\"\n)\n\ntype FastCGIServer struct{}\n\n\n\nfunc main() {\n\tlistener, _ := net.Listen(\"tcp\", \"127.0.0.1:9001\")\n\tsrv := new(FastCGIServer)\n\tfcgi.Serve(listener, srv)\n}\n\nfunc (s FastCGIServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) ", "output": "{\n\tresp.Write([]byte(\"

Hello, 世界

\\n

Behold my Go web app.

\"))\n}"} {"input": "package user\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/m-o-s-e-s/mgm/mgm\"\n\t\"github.com/satori/go.uuid\"\n)\n\n\nfunc (um Manager) Auth(username string, password string) (mgm.User, bool) {\n\tum.uMutex.Lock()\n\tdefer um.uMutex.Unlock()\n\n\tvar user mgm.User\n\tfound := false\n\tfor _, u := range um.users {\n\t\tif strings.EqualFold(u.Name, username) {\n\t\t\tuser = u\n\t\t\tfound = true\n\t\t}\n\t}\n\n\tif found == false {\n\t\tum.log.Info(\"User %v does not exist\", username)\n\t\treturn user, false\n\t}\n\n\tvalid, guid, err := um.conn.Auth(username, password)\n\tif err != nil {\n\t\tum.log.Error(fmt.Sprintf(\"Cannot authenticate user: %v\", err.Error()))\n\t}\n\tif err != nil || valid == false {\n\t\tum.log.Info(\"User %v simian invalid\", username)\n\t\treturn user, valid\n\t}\n\n\tif guid != user.UserID {\n\t\tum.log.Error(fmt.Sprintf(\"Error: Authenticated user does not match local user\"))\n\t\treturn mgm.User{}, false\n\t}\n\tum.log.Info(\"User %v auth successful\", username)\n\treturn user, true\n}\n\n\n\n\nfunc (um Manager) SetPassword(userID uuid.UUID, password string) error ", "output": "{\n\t_, exists := um.GetUser(userID)\n\tif !exists {\n\t\treturn errors.New(\"User not found\")\n\t}\n\treturn um.conn.SetPassword(userID, password)\n}"} {"input": "package b\n\nimport \"./a\"\n\n\n\nfunc Fp() {\n\ta.Fp()\n\ta.Fip()\n}\n\nfunc Gp() {\n\ta.Gp()\n\ta.Gip()\n}\n\nfunc Hp() {\n\ta.Hp()\n\ta.Hip()\n}\n\nfunc F() ", "output": "{\n\ta.F()\n\ta.Fi()\n}"} {"input": "package hpa\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"os/exec\"\n\t\"time\"\n\n\t\"github.com/Azure/acs-engine/test/e2e/kubernetes/util\"\n)\n\n\ntype HPA struct {\n\tMetadata Metadata `json:\"metadata\"`\n\tSpec Spec `json:\"spec\"`\n\tStatus Status `json:\"status\"`\n}\n\n\ntype Metadata struct {\n\tCreatedAt time.Time `json:\"creationTimestamp\"`\n\tName string `json:\"name\"`\n\tNamespace string `json:\"namespace\"`\n}\n\n\ntype Spec struct {\n\tMinReplicas int `json:\"minReplicas\"`\n\tMaxReplicas int `json:\"maxReplicas\"`\n\tTargetCPUUtilizationPercentage int `json:\"targetCPUUtilizationPercentage\"`\n}\n\n\ntype Status struct {\n\tLoadBalancer LoadBalancer `json:\"loadBalancer\"`\n}\n\n\ntype LoadBalancer struct {\n\tCurrentCPUUtilizationPercentage int `json:\"currentCPUUtilizationPercentage\"`\n\tCurrentReplicas int `json:\"currentReplicas\"`\n\tDesiredReplicas int `json:\"desiredReplicas\"`\n}\n\n\nfunc Get(name, namespace string) (*HPA, error) {\n\tcmd := exec.Command(\"kubectl\", \"get\", \"hpa\", \"-o\", \"json\", \"-n\", namespace, name)\n\tutil.PrintCommand(cmd)\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tlog.Printf(\"Error trying to run 'kubectl get hpa':%s\\n\", string(out))\n\t\treturn nil, err\n\t}\n\th := HPA{}\n\terr = json.Unmarshal(out, &h)\n\tif err != nil {\n\t\tlog.Printf(\"Error unmarshalling service json:%s\\n\", err)\n\t\treturn nil, err\n\t}\n\treturn &h, nil\n}\n\n\n\n\nfunc (h *HPA) Delete(retries int) error ", "output": "{\n\tvar kubectlOutput []byte\n\tvar kubectlError error\n\tfor i := 0; i < retries; i++ {\n\t\tcmd := exec.Command(\"kubectl\", \"delete\", \"hpa\", \"-n\", h.Metadata.Namespace, h.Metadata.Name)\n\t\tkubectlOutput, kubectlError = util.RunAndLogCommand(cmd)\n\t\tif kubectlError != nil {\n\t\t\tlog.Printf(\"Error while trying to delete service %s in namespace %s:%s\\n\", h.Metadata.Namespace, h.Metadata.Name, string(kubectlOutput))\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\treturn kubectlError\n}"} {"input": "package vkutil\n\nimport (\n\t\"strconv\"\n\t\"time\"\n)\n\n\ntype EpochTime time.Time\n\n\n\n\n\nfunc (t *EpochTime) UnmarshalJSON(s []byte) error {\n\tvar err error\n\tvar q int64\n\tif q, err = strconv.ParseInt(string(s), 10, 64); err != nil {\n\t\treturn err\n\t}\n\t*(*time.Time)(t) = time.Unix(q, 0)\n\treturn err\n}\n\nfunc (t EpochTime) ToTime() time.Time {\n\treturn time.Time(t)\n}\n\nfunc (t EpochTime) MarshalJSON() ([]byte, error) ", "output": "{\n\treturn []byte(strconv.FormatInt(time.Time(t).Unix(), 10)), nil\n}"} {"input": "package creditcard\n\nimport (\n\t\"testing\"\n)\n\ntype card struct {\n\tNumber string\n\tType string\n\tValid bool\n}\n\nvar cards = []*card{\n\t&card{\"4242424242424242\", \"Visa\", true}, \n\t&card{\"4213729238347292\", \"Visa\", false}, \n\t&card{\"79927398713\", \"Unknown\", true}, \n\t&card{\"79927398710\", \"Unknown\", false}, \n\t&card{\"6011111111111117\", \"Discover\", true}, \n\t&card{\"6011342393482022\", \"Discover\", false}, \n\t&card{\"344347386473833\", \"AmericanExpress\", false}, \n\t&card{\"374347386473833\", \"AmericanExpress\", false}, \n\t&card{\"30569309025904\", \"DinersClub/Carteblanche\", true}, \n\t&card{\"30569309025905\", \"DinersClub/Carteblanche\", false}, \n\t&card{\"5555555555554444\", \"MasterCard\", true}, \n\t&card{\"5555555555554445\", \"MasterCard\", false}, \n\t&card{\"180034239348202\", \"JCB\", false}, \n}\n\nfunc TestValidate(t *testing.T) {\n\tfor _, card := range cards {\n\t\tvalid := Validate(card.Number)\n\t\tif valid != card.Valid {\n\t\t\tt.Errorf(\"card validation [%v]; want [%v]\", valid, card.Valid)\n\t\t}\n\t}\n}\n\nfunc TestCardype(t *testing.T) {\n\tfor _, card := range cards {\n\t\tcardType := Cardtype(card.Number)\n\t\tif cardType != card.Type {\n\t\t\tt.Errorf(\"card type [%s]; want [%s]\", cardType, card.Type)\n\t\t}\n\t}\n}\n\n\n\nfunc TestGenerateLastDigit(t *testing.T) ", "output": "{\n\tlastDigit := GenerateLastDigit(\"5276 4400 6542 131\")\n\n\tif lastDigit != \"9\" {\n\t\tt.Errorf(\"last digit [%s]; want [%s]\", lastDigit, \"9\")\n\t}\n}"} {"input": "package setup_cli\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\n\t\"github.com/cloudfoundry-incubator/lattice/ltc/cli_app_factory\"\n\t\"github.com/cloudfoundry-incubator/lattice/ltc/config\"\n\t\"github.com/cloudfoundry-incubator/lattice/ltc/config/config_helpers\"\n\t\"github.com/cloudfoundry-incubator/lattice/ltc/config/persister\"\n\t\"github.com/cloudfoundry-incubator/lattice/ltc/config/target_verifier\"\n\t\"github.com/cloudfoundry-incubator/lattice/ltc/config/target_verifier/receptor_client_factory\"\n\t\"github.com/cloudfoundry-incubator/lattice/ltc/exit_handler\"\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/pivotal-golang/lager\"\n)\n\nconst (\n\tlatticeCliHomeVar = \"LATTICE_CLI_HOME\"\n)\n\nvar (\n\tlatticeVersion string \n)\n\n\n\nfunc logger() lager.Logger {\n\tlogger := lager.NewLogger(\"ltc\")\n\tvar logLevel lager.LogLevel\n\n\tif os.Getenv(\"LTC_LOG_LEVEL\") == \"DEBUG\" {\n\t\tlogLevel = lager.DEBUG\n\t} else {\n\t\tlogLevel = lager.INFO\n\t}\n\n\tlogger.RegisterSink(lager.NewWriterSink(os.Stderr, logLevel))\n\treturn logger\n}\n\nfunc ltcConfigRoot() string {\n\tif os.Getenv(latticeCliHomeVar) != \"\" {\n\t\treturn os.Getenv(latticeCliHomeVar)\n\t}\n\n\treturn os.Getenv(\"HOME\")\n}\n\nfunc NewCliApp() *cli.App ", "output": "{\n\tconfig := config.New(persister.NewFilePersister(config_helpers.ConfigFileLocation(ltcConfigRoot())))\n\n\tsignalChan := make(chan os.Signal)\n\tsignal.Notify(signalChan, os.Interrupt)\n\texitHandler := exit_handler.New(signalChan, os.Exit)\n\tgo exitHandler.Run()\n\n\ttargetVerifier := target_verifier.New(receptor_client_factory.MakeReceptorClient)\n\tapp := cli_app_factory.MakeCliApp(latticeVersion, ltcConfigRoot(), exitHandler, config, logger(), targetVerifier, os.Stdout)\n\treturn app\n}"} {"input": "package identity\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype GetTenancyRequest struct {\n\n\tTenancyId *string `mandatory:\"true\" contributesTo:\"path\" name:\"tenancyId\"`\n}\n\nfunc (request GetTenancyRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\ntype GetTenancyResponse struct {\n\n\tRawResponse *http.Response\n\n\tTenancy `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\nfunc (response GetTenancyResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package defaults\n\nimport \"time\"\n\n\n\ntype Configuration struct {\n\tConnectTimeout *time.Duration\n\n\tTLSNegotiationTimeout *time.Duration\n}\n\n\nfunc (c *Configuration) GetConnectTimeout() (time.Duration, bool) {\n\tif c.ConnectTimeout == nil {\n\t\treturn 0, false\n\t}\n\treturn *c.ConnectTimeout, true\n}\n\n\n\n\nfunc (c *Configuration) GetTLSNegotiationTimeout() (time.Duration, bool) ", "output": "{\n\tif c.TLSNegotiationTimeout == nil {\n\t\treturn 0, false\n\t}\n\treturn *c.TLSNegotiationTimeout, true\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/labstack/echo\"\n)\n\n\ntype Error struct {\n\tMessage string `json:\"message\"`\n}\n\n\nfunc OK(c echo.Context, payload interface{}) error {\n\treturn c.JSON(http.StatusOK, payload)\n}\n\n\nfunc Created(c echo.Context, payload interface{}) error {\n\treturn c.JSON(http.StatusCreated, payload)\n}\n\n\nfunc NoContent(c echo.Context) error {\n\treturn c.NoContent(http.StatusNoContent)\n}\n\n\nfunc BadRequest(c echo.Context, msg string) error {\n\treturn c.JSON(http.StatusBadRequest, Error{msg})\n}\n\n\nfunc NotFound(c echo.Context) error {\n\treturn c.JSON(http.StatusNotFound, Error{\"Resource not found\"})\n}\n\n\n\n\n\nfunc Invalid(c echo.Context, msg string) error {\n\treturn c.JSON(422, Error{msg})\n}\n\n\n\nfunc InternalServerError(c echo.Context, err error) error {\n\tlog.WithFields(log.Fields{\n\t\t\"request_id\": RequestID(c),\n\t}).Error(err)\n\n\treturn c.JSON(http.StatusInternalServerError, Error{\"Oops! Something went wrong\"})\n}\n\nfunc Conflict(c echo.Context, msg string) error ", "output": "{\n\treturn c.JSON(http.StatusConflict, Error{msg})\n}"} {"input": "package simelection\n\nimport \"sync\"\n\n\n\ntype Election struct {\n\tmu sync.RWMutex\n\tmasters []string\n}\n\n\nfunc (e *Election) IsMaster(who string) bool {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tfor _, m := range e.masters {\n\t\tif m == who {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc (e *Election) Masters() []string {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\treturn e.masters\n}\n\n\n\n\n\nfunc (e *Election) SetMasters(who []string) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\te.masters = who\n}\n\nfunc (e *Election) SetMaster(who string) ", "output": "{\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\te.masters = []string{who}\n}"} {"input": "package validator\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/pivotal-cf/pivnet-resource/concourse\"\n)\n\ntype CheckValidator struct {\n\tinput concourse.CheckRequest\n}\n\n\n\nfunc (v CheckValidator) Validate() error {\n\tif v.input.Source.APIToken == \"\" {\n\t\treturn fmt.Errorf(\"%s must be provided\", \"api_token\")\n\t}\n\n\tif v.input.Source.ProductSlug == \"\" {\n\t\treturn fmt.Errorf(\"%s must be provided\", \"product_slug\")\n\t}\n\treturn nil\n}\n\nfunc NewCheckValidator(input concourse.CheckRequest) *CheckValidator ", "output": "{\n\treturn &CheckValidator{\n\t\tinput: input,\n\t}\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"github.com/emicklei/go-restful\"\n \"github.com/gorilla/schema\"\n \"io\"\n \"net/http\"\n)\n\n\n\n\n\n\n\ntype Profile struct {\n Name string\n Age int\n}\n\nvar decoder *schema.Decoder\n\nfunc main() {\n decoder = schema.NewDecoder()\n ws := new(restful.WebService)\n ws.Route(ws.POST(\"/profiles\").Consumes(\"application/x-www-form-urlencoded\").To(postAdddress))\n ws.Route(ws.GET(\"/profiles\").To(addresssForm))\n restful.Add(ws)\n http.ListenAndServe(\":8080\", nil)\n}\n\n\n\nfunc addresssForm(req *restful.Request, resp *restful.Response) {\n io.WriteString(resp.ResponseWriter,\n `\n \n

Enter Profile

\n
\n \n \n \n \n \n
\n \n `)\n}\n\nfunc postAdddress(req *restful.Request, resp *restful.Response) ", "output": "{\n err := req.Request.ParseForm()\n if err != nil {\n resp.WriteErrorString(http.StatusBadRequest, err.Error())\n return\n }\n p := new(Profile)\n err = decoder.Decode(p, req.Request.PostForm)\n if err != nil {\n resp.WriteErrorString(http.StatusBadRequest, err.Error())\n return\n }\n io.WriteString(resp.ResponseWriter, fmt.Sprintf(\"Name=%s, Age=%d\", p.Name, p.Age))\n}"} {"input": "package iso20022\n\n\ntype SecuritiesCertificate5 struct {\n\n\tNumber *RestrictedFINXMax30Text `xml:\"Nb\"`\n\n\tIssuer *Max4AlphaNumericText `xml:\"Issr,omitempty\"`\n\n\tSchemeName *Max4AlphaNumericText `xml:\"SchmeNm,omitempty\"`\n}\n\nfunc (s *SecuritiesCertificate5) SetNumber(value string) {\n\ts.Number = (*RestrictedFINXMax30Text)(&value)\n}\n\n\n\nfunc (s *SecuritiesCertificate5) SetSchemeName(value string) {\n\ts.SchemeName = (*Max4AlphaNumericText)(&value)\n}\n\nfunc (s *SecuritiesCertificate5) SetIssuer(value string) ", "output": "{\n\ts.Issuer = (*Max4AlphaNumericText)(&value)\n}"} {"input": "package dbutil\n\nimport (\n\t\"log\"\n\t\"testing\"\n\t\"time\"\n\n\tConfig \"../config\"\n\t_ \"github.com/lib/pq\"\n)\n\n\n\nfunc TestDBWithYaml(t *testing.T) {\n\tlog.Println(\"[test yaml]\")\n\t_, err := Config.GetConfig(\"../config/database.yml\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n}\n\nfunc TestDBWithToml(t *testing.T) {\n\tlog.Println(\"[test toml]\")\n\tcfg, err := Config.GetTomlConfig(\"../config/database.toml\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tdev := cfg.Env[\"development\"]\n\tdbOperation(dev.Host, dev.Username, dev.Password, dev.Database, t)\n}\n\nfunc dbOperation(dbHost, dbUser, dbPasswd, dbName string, t *testing.T) ", "output": "{\n\tconn := New(dbHost, dbUser, dbPasswd, dbName)\n\tdefer conn.Close()\n\n\tusers := conn.Rows(\"users\", \"id, openid, nickname, created\")\n\tdefer users.Close()\n\tfor users.Next() {\n\t\tvar id, openid, nickname string\n\t\tvar created time.Time\n\t\tif err := users.Scan(&id, &openid, &nickname, &created); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tlog.Println(id, openid, nickname, created.Format(time.RFC3339))\n\t}\n}"} {"input": "package classify\n\nimport \"github.com/deathly809/gotypes\"\n\n\ntype Classifier interface {\n\tClassify([]gotypes.Value) float32\n}\n\n\n\ntype NaiveData struct {\n\tVal []gotypes.Value\n\tCla float32\n}\n\n\nfunc (nData *NaiveData) Value() []gotypes.Value {\n\treturn nData.Val\n}\n\n\n\n\n\ntype Data interface {\n\tValue() []gotypes.Value\n\tClass() float32\n}\n\n\ntype Kernel interface {\n\tDot([]gotypes.Value, []gotypes.Value) float32\n}\n\nfunc (nData *NaiveData) Class() float32 ", "output": "{\n\treturn nData.Cla\n}"} {"input": "package dockerfile\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/docker/docker/pkg/system\"\n)\n\n\n\n\n\nfunc errNotJSON(command, original string) error {\n\textra := \"\"\n\toriginal = filepath.FromSlash(strings.ToLower(strings.Replace(strings.ToLower(original), strings.ToLower(command)+\" \", \"\", -1)))\n\tif len(regexp.MustCompile(`\"[a-z]:\\\\.*`).FindStringSubmatch(original)) > 0 &&\n\t\t!strings.Contains(original, `\\\\`) &&\n\t\tstrings.Contains(original, \"[\") &&\n\t\tstrings.Contains(original, \"]\") {\n\t\textra = fmt.Sprintf(`. It looks like '%s' includes a file path without an escaped back-slash. JSON requires back-slashes to be escaped such as [\"c:\\\\path\\\\to\\\\file.exe\", \"/parameter\"]`, original)\n\t}\n\treturn fmt.Errorf(\"%s requires the arguments to be in JSON form%s\", command, extra)\n}\n\nfunc normaliseWorkdir(current string, requested string) (string, error) ", "output": "{\n\tif requested == \"\" {\n\t\treturn \"\", fmt.Errorf(\"cannot normalise nothing\")\n\t}\n\n\tcurrent = filepath.FromSlash(current)\n\trequested = filepath.FromSlash(requested)\n\n\tif len(current) == 0 || system.IsAbs(requested) {\n\t\tif (requested[0] == os.PathSeparator) ||\n\t\t\t(len(requested) > 1 && string(requested[1]) != \":\") ||\n\t\t\t(len(requested) == 1) {\n\t\t\trequested = filepath.Join(`C:\\`, requested)\n\t\t}\n\t} else {\n\t\trequested = filepath.Join(current, requested)\n\t}\n\treturn (strings.ToUpper(string(requested[0])) + requested[1:]), nil\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\n\n\n\ntype MsgPong struct {\n\tNonce uint64\n}\n\n\n\nfunc (msg *MsgPong) BtcDecode(r io.Reader, pver uint32) error {\n\tif pver <= BIP0031Version {\n\t\tstr := fmt.Sprintf(\"pong message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgPong.BtcDecode\", str)\n\t}\n\n\treturn readElement(r, &msg.Nonce)\n}\n\n\n\nfunc (msg *MsgPong) BtcEncode(w io.Writer, pver uint32) error {\n\tif pver <= BIP0031Version {\n\t\tstr := fmt.Sprintf(\"pong message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgPong.BtcEncode\", str)\n\t}\n\n\treturn writeElement(w, msg.Nonce)\n}\n\n\n\nfunc (msg *MsgPong) Command() string {\n\treturn CmdPong\n}\n\n\n\nfunc (msg *MsgPong) MaxPayloadLength(pver uint32) uint32 {\n\tplen := uint32(0)\n\tif pver > BIP0031Version {\n\t\tplen += 8\n\t}\n\n\treturn plen\n}\n\n\n\n\n\nfunc NewMsgPong(nonce uint64) *MsgPong ", "output": "{\n\treturn &MsgPong{\n\t\tNonce: nonce,\n\t}\n}"} {"input": "package dshelp\n\nimport (\n\tcid \"gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid\"\n\t\"gx/ipfs/QmaRb5yNXKonhbkpNxNawoydk4N6es6b4fPj19sjEKsh5D/go-datastore\"\n\t\"gx/ipfs/QmfVj3x4D6Jkq9SEoi5n2NmoUomLwoeiwnYz2KQa15wRw6/base32\"\n)\n\n\nfunc NewKeyFromBinary(rawKey []byte) datastore.Key {\n\tbuf := make([]byte, 1+base32.RawStdEncoding.EncodedLen(len(rawKey)))\n\tbuf[0] = '/'\n\tbase32.RawStdEncoding.Encode(buf[1:], rawKey)\n\treturn datastore.RawKey(string(buf))\n}\n\n\nfunc BinaryFromDsKey(k datastore.Key) ([]byte, error) {\n\treturn base32.RawStdEncoding.DecodeString(k.String()[1:])\n}\n\n\nfunc CidToDsKey(k cid.Cid) datastore.Key {\n\treturn NewKeyFromBinary(k.Bytes())\n}\n\n\n\n\nfunc DsKeyToCid(dsKey datastore.Key) (cid.Cid, error) ", "output": "{\n\tkb, err := BinaryFromDsKey(dsKey)\n\tif err != nil {\n\t\treturn cid.Cid{}, err\n\t}\n\treturn cid.Cast(kb)\n}"} {"input": "package samtun\n\nimport (\n \"log\"\n)\n\n\n\nfunc RunClient(args []string) ", "output": "{\n \n fname := \"client.json\"\n if len(args) > 0 {\n fname = args[0]\n }\n log.Println(\"starting up client\")\n if ! checkfile(fname) {\n log.Println(\"generate default config\")\n \n conf := genHubConfig(fname)\n conf.Save(fname)\n log.Println(\"please configure the client, see\", fname)\n return\n }\n log.Println(\"loading config file\", fname)\n _ , err := loadHubConfig(fname)\n if err != nil {\n log.Fatal(\"failed to load config\", err)\n }\n \n}"} {"input": "package inigo\n\nimport (\n\t\"errors\"\n)\n\n\nfunc (config *Config) GetConfigFilename() string {\n\treturn config.filename\n}\n\n\n\n\n\nfunc (config *Config) GetAllKeys() map[string][]string {\n\tvar res map[string][]string = make(map[string][]string)\n\n\tfor section, data := range config.config {\n\t\tfor key, _ := range data.data {\n\t\t\tres[section] = append(res[section], key)\n\t\t}\n\t}\n\n\treturn res\n}\n\n\nfunc (config *Config) GetValue(section, key string) (string, error) {\n\tvar processing bool = true\n\tvar currentSection string = section\n\tvar res string\n\n\tfor processing && len(currentSection) > 0 {\n\t\tres = config.config[currentSection].data[key]\n\n\t\tif len(res) > 0 {\n\t\t\tprocessing = false\n\t\t\tbreak\n\t\t} else {\n\t\t\tcurrentSection = config.config[currentSection].inheritSection\n\t\t}\n\t}\n\n\tif len(res) == 0 {\n\t\treturn res, errors.New(\"Has no key\")\n\t}\n\n\treturn res, nil\n}\n\nfunc (config *Config) GetAllSections() []string ", "output": "{\n\tvar res []string\n\n\tfor key, _ := range config.config {\n\t\tres = append(res, key)\n\t}\n\n\treturn res\n}"} {"input": "package main\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nfunc main() {\n\targs := os.Args[1:]\n\tlocation := \".\"\n\tif len(args) > 0 {\n\t\tlocation = args[0]\n\t}\n\tGoWalk(location)\n\treturn\n}\n\nfunc checkDuplicates(files []string) (result bool) {\n\tstored_hashs := make(map[string][]string)\n\twasted_space := 0\n\n\tfor _, filename := range files {\n\t\thasher := sha256.New()\n\n\t\tfile_content, read_file_err := ioutil.ReadFile(filename)\n\t\tif read_file_err != nil {\n\t\t\tfmt.Printf(\"FAILED to read file, %s\\n\", filename)\n\t\t}\n\t\thasher.Write(file_content)\n\t\tfile_hash := hex.EncodeToString(hasher.Sum(nil))\n\t\tshort_hash := file_hash[0:8]\n\n\t\tfmt.Printf(\"%s hash for %s\\n\", short_hash, filename)\n\n\t\tif _, ok := stored_hashs[file_hash]; ok {\n\t\t\tfmt.Printf(\"%s Duplicate has for %s %s\\n\", short_hash, filename, stored_hashs[file_hash])\n\t\t\twasted_space = len(stored_hashs[file_hash]) * len(file_content)\n\t\t}\n\n\t\tstored_hashs[file_hash] = append(stored_hashs[file_hash], filename)\n\t}\n\n\tif wasted_space > 0 {\n\t\tfmt.Println(files[0], \"Wasted space:\", wasted_space)\n\t}\n\treturn true\n\n}\n\n\n\nfunc GoWalk(location string) ", "output": "{\n\tdict := make(map[int64][]string)\n\n\tfilepath.Walk(location, func(path string, fileinfo os.FileInfo, _ error) (err error) {\n\t\tif strings.Contains(path, \"/.\") {\n\t\t\treturn\n\t\t}\n\t\tif strings.HasSuffix(path, \"~\") {\n\t\t\treturn\n\t\t}\n\t\tif ! fileinfo.Mode().IsRegular() {\n\t\t\treturn\n\t\t}\n\n\t\tfile_size := fileinfo.Size()\n\t\tdict[file_size] = append(dict[file_size], path)\n\t\treturn\n\t})\n\n\tfor _, v := range dict {\n\t\tif len(v) == 1 {\n\t\t\tcontinue\n\t\t}\n\t\tcheckDuplicates(v)\n\t}\n}"} {"input": "package alert\n\nimport (\n\t. \"aliyun-openapi-go-sdk/core\"\n)\n\ntype GetContactGroupRequest struct {\n\tRoaRequest\n\tProjectName string\n\tGroupName string\n}\n\nfunc (r *GetContactGroupRequest) SetProjectName(value string) {\n\tr.ProjectName = value\n\tr.PathParams.Set(\"ProjectName\", value)\n}\nfunc (r *GetContactGroupRequest) GetProjectName() string {\n\treturn r.ProjectName\n}\nfunc (r *GetContactGroupRequest) SetGroupName(value string) {\n\tr.GroupName = value\n\tr.PathParams.Set(\"GroupName\", value)\n}\n\n\nfunc (r *GetContactGroupRequest) Init() {\n\tr.RoaRequest.Init()\n\tr.PathPattern = \"/projects/ProjectName/groups/GroupName\"\n\tr.SetMethod(\"GET\")\n\tr.SetProtocol(\"HTTP\")\n\tr.SetProduct(Product)\n}\n\ntype GetContactGroupResponse struct {\n\tcode string `xml:\"code\" json:\"code\"`\n\tmessage string `xml:\"message\" json:\"message\"`\n\tsuccess string `xml:\"success\" json:\"success\"`\n\ttraceId string `xml:\"traceId\" json:\"traceId\"`\n\tresult string `xml:\"result\" json:\"result\"`\n}\n\nfunc GetContactGroup(req *GetContactGroupRequest, accessId, accessSecret string) (*GetContactGroupResponse, error) {\n\tvar pResponse GetContactGroupResponse\n\tbody, err := ApiHttpRequest(accessId, accessSecret, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tApiUnmarshalResponse(req.GetFormat(), body, &pResponse)\n\treturn &pResponse, err\n}\n\nfunc (r *GetContactGroupRequest) GetGroupName() string ", "output": "{\n\treturn r.GroupName\n}"} {"input": "package graphdriver \n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\n\t\"github.com/docker/docker/pkg/plugingetter\"\n\t\"github.com/docker/docker/plugin/v2\"\n)\n\n\n\nfunc newPluginDriver(name string, pl plugingetter.CompatPlugin, config Options) (Driver, error) {\n\thome := config.Root\n\tif !pl.IsV1() {\n\t\tif p, ok := pl.(*v2.Plugin); ok {\n\t\t\tif p.PropagatedMount != \"\" {\n\t\t\t\thome = p.PluginObj.Config.PropagatedMount\n\t\t\t}\n\t\t}\n\t}\n\tproxy := &graphDriverProxy{name, pl, Capabilities{}}\n\treturn proxy, proxy.Init(filepath.Join(home, name), config.DriverOptions, config.UIDMaps, config.GIDMaps)\n}\n\nfunc lookupPlugin(name string, pg plugingetter.PluginGetter, config Options) (Driver, error) ", "output": "{\n\tif !config.ExperimentalEnabled {\n\t\treturn nil, fmt.Errorf(\"graphdriver plugins are only supported with experimental mode\")\n\t}\n\tpl, err := pg.Get(name, \"GraphDriver\", plugingetter.Acquire)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error looking up graphdriver plugin %s: %v\", name, err)\n\t}\n\treturn newPluginDriver(name, pl, config)\n}"} {"input": "package version\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n)\n\ntype version struct {\n\t*flags.EmptyFlag\n\n\trequire string\n}\n\nfunc init() {\n\tcli.Register(\"version\", &version{})\n}\n\nfunc (cmd *version) Register(ctx context.Context, f *flag.FlagSet) {\n\tf.StringVar(&cmd.require, \"require\", \"\", \"Require govc version >= this value\")\n}\n\n\n\nfunc (cmd *version) Run(ctx context.Context, f *flag.FlagSet) error ", "output": "{\n\tver := flags.GitVersion\n\tif ver == \"\" {\n\t\tver = flags.Version\n\t}\n\n\tif cmd.require != \"\" {\n\t\tv, err := flags.ParseVersion(ver)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\trv, err := flags.ParseVersion(cmd.require)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse required version '%s': %s\", cmd.require, err)\n\t\t}\n\n\t\tif !rv.Lte(v) {\n\t\t\treturn fmt.Errorf(\"version %s or higher is required, this is version %s\", cmd.require, ver)\n\t\t}\n\t}\n\n\tfmt.Printf(\"govc %s\\n\", ver)\n\n\treturn nil\n}"} {"input": "package data\n\nimport (\n\t\"time\"\n\n\t\"github.com/juju/errgo\"\n)\n\ntype Entries []Entry\n\ntype Entry interface {\n\tType() EntryType\n\tValues() []string\n\tGetTimeStamp() time.Time\n}\n\nconst TimeStampFormat = time.RFC3339Nano\n\ntype EntryType int\n\nconst (\n\tEntryTypeNote EntryType = iota\n\tEntryTypeTodo\n\tEntryTypeUnkown\n)\n\nfunc (etype EntryType) String() string {\n\tswitch etype {\n\tcase EntryTypeNote:\n\t\treturn \"note\"\n\tcase EntryTypeTodo:\n\t\treturn \"todo\"\n\tdefault:\n\t\treturn \"unkown\"\n\t}\n}\n\n\n\nfunc ParseEntry(values []string) (Entry, error) {\n\tif len(values) < 1 {\n\t\treturn nil, errgo.New(\"entry values need at least one field\")\n\t}\n\n\tetype, err := ParseEntryType(values[0])\n\tif err != nil {\n\t\treturn nil, errgo.Notef(err, \"can not parse entry type\")\n\t}\n\n\tswitch etype {\n\tcase EntryTypeNote:\n\t\treturn ParseNote(values)\n\tcase EntryTypeTodo:\n\t\treturn ParseTodo(values)\n\tdefault:\n\t\treturn nil, errgo.New(\"do not know how to parse this entry type\")\n\t}\n}\n\nfunc ParseEntryType(value string) (EntryType, error) ", "output": "{\n\tswitch value {\n\tcase \"note\":\n\t\treturn EntryTypeNote, nil\n\tcase \"todo\":\n\t\treturn EntryTypeTodo, nil\n\tdefault:\n\t\treturn EntryTypeUnkown, errgo.New(\"the entry type \" + value + \" is not known\")\n\t}\n}"} {"input": "package trello\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\t\"testing\"\n)\n\nfunc TestGetWithBadURL(t *testing.T) {\n\tc := testClient()\n\ttarget := map[string]interface{}{}\n\tc.BaseURL = \"gopher:test\"\n\terr := c.Get(\"members\", Defaults(), &target)\n\tif err == nil {\n\t\tt.Fatal(\"Get() should fail with a bad URL\")\n\t}\n}\n\nfunc TestWithContext(t *testing.T) {\n\tc := testClient()\n\tif c.ctx != context.Background() {\n\t\tt.Fatal(\"NewClient() should use context.Background()\")\n\t}\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tnewC := c.WithContext(ctx)\n\tif newC == c {\n\t\tt.Fatal(\"WithContext() should return a new client\")\n\t}\n\n\tif newC.ctx != ctx {\n\t\tt.Fatal(\"WithContext() should return a client with the given context\")\n\t}\n\n\tvar calls int\n\tmt := &mockTransport{\n\t\tRoundTripFunc: func(req *http.Request) (*http.Response, error) {\n\t\t\tcalls++\n\t\t\tif req.Context() != ctx {\n\t\t\t\tt.Fatal(\"Get() should be using the new context\")\n\t\t\t}\n\t\t\treturn http.DefaultTransport.RoundTrip(req)\n\t\t},\n\t}\n\tnewC.Client = &http.Client{\n\t\tTransport: mt,\n\t}\n\tnewC.Get(\"members\", nil, nil)\n\n\tif calls != 1 {\n\t\tt.Fatal(\"Get() should have used the mocked transport\")\n\t}\n}\n\ntype mockTransport struct {\n\tRoundTripFunc func(*http.Request) (*http.Response, error)\n}\n\nfunc (t *mockTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\treturn t.RoundTripFunc(req)\n}\n\n\n\nfunc testClient() *Client ", "output": "{\n\tc := NewClient(\"user\", \"pass\")\n\tc.testMode = true\n\treturn c\n}"} {"input": "package data\n\nimport (\n\t\"time\"\n\n\t\"github.com/juju/errgo\"\n)\n\ntype Entries []Entry\n\ntype Entry interface {\n\tType() EntryType\n\tValues() []string\n\tGetTimeStamp() time.Time\n}\n\nconst TimeStampFormat = time.RFC3339Nano\n\ntype EntryType int\n\nconst (\n\tEntryTypeNote EntryType = iota\n\tEntryTypeTodo\n\tEntryTypeUnkown\n)\n\nfunc (etype EntryType) String() string {\n\tswitch etype {\n\tcase EntryTypeNote:\n\t\treturn \"note\"\n\tcase EntryTypeTodo:\n\t\treturn \"todo\"\n\tdefault:\n\t\treturn \"unkown\"\n\t}\n}\n\nfunc ParseEntryType(value string) (EntryType, error) {\n\tswitch value {\n\tcase \"note\":\n\t\treturn EntryTypeNote, nil\n\tcase \"todo\":\n\t\treturn EntryTypeTodo, nil\n\tdefault:\n\t\treturn EntryTypeUnkown, errgo.New(\"the entry type \" + value + \" is not known\")\n\t}\n}\n\n\n\nfunc ParseEntry(values []string) (Entry, error) ", "output": "{\n\tif len(values) < 1 {\n\t\treturn nil, errgo.New(\"entry values need at least one field\")\n\t}\n\n\tetype, err := ParseEntryType(values[0])\n\tif err != nil {\n\t\treturn nil, errgo.Notef(err, \"can not parse entry type\")\n\t}\n\n\tswitch etype {\n\tcase EntryTypeNote:\n\t\treturn ParseNote(values)\n\tcase EntryTypeTodo:\n\t\treturn ParseTodo(values)\n\tdefault:\n\t\treturn nil, errgo.New(\"do not know how to parse this entry type\")\n\t}\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\n\t\"strings\"\n)\n\n\ntype ShowServerRemoteConsoleRequest struct {\n\tServerId string `json:\"server_id\"`\n\tBody *ShowServerRemoteConsoleRequestBody `json:\"body,omitempty\"`\n}\n\n\n\nfunc (o ShowServerRemoteConsoleRequest) String() string ", "output": "{\n\tdata, _ := json.Marshal(o)\n\treturn strings.Join([]string{\"ShowServerRemoteConsoleRequest\", string(data)}, \" \")\n}"} {"input": "package http\n\nimport (\n\t\"net/url\"\n\t\"os\"\n\t\"testing\"\n)\n\n\n\n\nvar cacheKeysTests = []struct {\n\tproxy string\n\tscheme string\n\taddr string\n\tkey string\n}{\n\t{\"\", \"http\", \"foo.com\", \"|http|foo.com\"},\n\t{\"\", \"https\", \"foo.com\", \"|https|foo.com\"},\n\t{\"http://foo.com\", \"http\", \"foo.com\", \"http://foo.com|http|\"},\n\t{\"http://foo.com\", \"https\", \"foo.com\", \"http://foo.com|https|foo.com\"},\n}\n\nfunc TestCacheKeys(t *testing.T) {\n\tfor _, tt := range cacheKeysTests {\n\t\tvar proxy *url.URL\n\t\tif tt.proxy != \"\" {\n\t\t\tu, err := url.Parse(tt.proxy)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tproxy = u\n\t\t}\n\t\tcm := connectMethod{proxyURL: proxy, targetScheme: tt.scheme, targetAddr: tt.addr}\n\t\tif got := cm.key().String(); got != tt.key {\n\t\t\tt.Fatalf(\"{%q, %q, %q} cache key = %q; want %q\", tt.proxy, tt.scheme, tt.addr, got, tt.key)\n\t\t}\n\t}\n}\n\n\n\nfunc ResetProxyEnv() ", "output": "{\n\tfor _, v := range []string{\"HTTP_PROXY\", \"http_proxy\", \"NO_PROXY\", \"no_proxy\", \"REQUEST_METHOD\"} {\n\t\tos.Unsetenv(v)\n\t}\n\tResetCachedEnvironment()\n}"} {"input": "package utils\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestTranslateLetter(t *testing.T) ", "output": "{\n\tvar tests = []struct {\n\t\tletter string\n\t\tsum int\n\t}{\n\t\t{\"a\", 14}, {\"i\", 6}, {\" \", 0},\n\t}\n\tfor _, test := range tests {\n\t\tactual := 0\n\t\tfields, err := TranslateLetter(test.letter)\n\t\tif err != nil {\n\t\t\tt.Error(\"Got err != nil, but should have been nil.\")\n\t\t}\n\t\tfor _, row := range fields {\n\t\t\tfor _, entry := range row {\n\t\t\t\tactual += entry\n\t\t\t}\n\t\t}\n\t\tif actual != test.sum {\n\t\t\tt.Errorf(\"Expected %d, but got %d\", test.sum, actual)\n\t\t}\n\t}\n}"} {"input": "package main\n\n\n\nfunc randomContraction(graph map[int64][]int64) int ", "output": "{\n\treturn 17\n}"} {"input": "package elastic\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n)\n\n\n\nfunc TestMatrixStatsAggregationWithMetaData(t *testing.T) {\n\tagg := NewMatrixStatsAggregation().\n\t\tFields(\"poverty\", \"income\").\n\t\tMeta(map[string]interface{}{\"name\": \"Oliver\"})\n\tsrc, err := agg.Source()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdata, err := json.Marshal(src)\n\tif err != nil {\n\t\tt.Fatalf(\"marshaling to JSON failed: %v\", err)\n\t}\n\tgot := string(data)\n\texpected := `{\"matrix_stats\":{\"fields\":[\"poverty\",\"income\"]},\"meta\":{\"name\":\"Oliver\"}}`\n\tif got != expected {\n\t\tt.Errorf(\"expected\\n%s\\n,got:\\n%s\", expected, got)\n\t}\n}\n\nfunc TestMatrixStatsAggregation(t *testing.T) ", "output": "{\n\tagg := NewMatrixStatsAggregation().\n\t\tFields(\"poverty\", \"income\").\n\t\tMissing(map[string]interface{}{\n\t\t\t\"income\": 50000,\n\t\t}).\n\t\tMode(\"avg\").\n\t\tFormat(\"0000.0\").\n\t\tValueType(\"double\")\n\tsrc, err := agg.Source()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdata, err := json.Marshal(src)\n\tif err != nil {\n\t\tt.Fatalf(\"marshaling to JSON failed: %v\", err)\n\t}\n\tgot := string(data)\n\texpected := `{\"matrix_stats\":{\"fields\":[\"poverty\",\"income\"],\"format\":\"0000.0\",\"missing\":{\"income\":50000},\"mode\":\"avg\",\"value_type\":\"double\"}}`\n\tif got != expected {\n\t\tt.Errorf(\"expected\\n%s\\n,got:\\n%s\", expected, got)\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"context\"\n\n\t\"github.com/jaegertracing/jaeger/cmd/collector/app/processor\"\n\t\"github.com/jaegertracing/jaeger/model\"\n\t\"github.com/jaegertracing/jaeger/thrift-gen/sampling\"\n)\n\ntype mockSamplingStore struct{}\n\n\n\ntype mockSpanProcessor struct {\n}\n\nfunc (p *mockSpanProcessor) Close() error {\n\treturn nil\n}\n\nfunc (p *mockSpanProcessor) ProcessSpans(spans []*model.Span, _ processor.SpansOptions) ([]bool, error) {\n\treturn []bool{}, nil\n}\n\nfunc (s mockSamplingStore) GetSamplingStrategy(_ context.Context, serviceName string) (*sampling.SamplingStrategyResponse, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package log\n\nimport \"gopkg.in/inconshreveable/log15.v2\"\n\nvar (\n\tLogger log15.Logger\n)\n\nfunc init() {\n\tLogger = log15.New()\n\tLogger.SetHandler(log15.DiscardHandler())\n}\n\n\n\n\n\n\nfunc Debug(msg string, ctx ...interface{}) { Logger.Debug(msg, ctx...) }\nfunc Info(msg string, ctx ...interface{}) { Logger.Info(msg, ctx...) }\nfunc Warn(msg string, ctx ...interface{}) { Logger.Warn(msg, ctx...) }\nfunc Error(msg string, ctx ...interface{}) { Logger.Error(msg, ctx...) }\nfunc Crit(msg string, ctx ...interface{}) { Logger.Crit(msg, ctx...) }\n\nfunc Interactive() ", "output": "{\n\tLogger.SetHandler(log15.MultiHandler(\n\t\tlog15.LvlFilterHandler(\n\t\t\tlog15.LvlError,\n\t\t\tlog15.StderrHandler)))\n}"} {"input": "package starbound\n\nimport (\n\t\"io\"\n)\n\n\nfunc getInt(data []byte, n int) int {\n\treturn int(data[n])<<24 | int(data[n+1])<<16 | int(data[n+2])<<8 | int(data[n+3])\n}\n\n\ntype logger interface {\n\tFatalf(format string, args ...interface{})\n}\n\n\ntype readerAtReader struct {\n\tr io.ReaderAt\n\toff int64\n}\n\n\n\nfunc (r *readerAtReader) Read(p []byte) (n int, err error) ", "output": "{\n\tn, err = r.r.ReadAt(p, r.off)\n\tr.off += int64(n)\n\treturn\n}"} {"input": "package checker\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"net/http\"\n)\n\ntype tokenChecker struct {\n}\n\n\n\nfunc (checker *tokenChecker) Check(eventMap map[string]string, expectedToken string, reqHeader http.Header, reqBody []byte) (bool, error) {\n\tpassCheck := false\n\n\tswitch eventMap[\"sourceType\"] {\n\tcase \"customize\":\n\t\tif expectedToken == eventMap[\"token\"] {\n\t\t\tpassCheck = true\n\t\t}\n\tcase \"gitlab\":\n\t\tif expectedToken == eventMap[\"token\"] {\n\t\t\tpassCheck = true\n\t\t}\n\tcase \"github\":\n\t\tmac := hmac.New(sha1.New, []byte(expectedToken))\n\t\tmac.Write(reqBody)\n\t\texpectedMAC := mac.Sum(nil)\n\t\texpectedSig := \"sha1=\" + hex.EncodeToString(expectedMAC)\n\n\t\tif expectedSig == eventMap[\"token\"] {\n\t\t\tpassCheck = true\n\t\t}\n\t}\n\n\tif passCheck {\n\t\treturn passCheck, nil\n\t}\n\n\treturn passCheck, errors.New(\"token checker failed\")\n}\n\nfunc (checker *tokenChecker) Support(eventMap map[string]string) bool ", "output": "{\n\treturn true\n}"} {"input": "package docker\n\nimport (\n\t\"os/exec\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/schema\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\nvar testAccProviders map[string]terraform.ResourceProvider\nvar testAccProvider *schema.Provider\n\n\n\nfunc TestProvider(t *testing.T) {\n\tif err := Provider().(*schema.Provider).InternalValidate(); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n}\n\nfunc TestProvider_impl(t *testing.T) {\n\tvar _ terraform.ResourceProvider = Provider()\n}\n\nfunc testAccPreCheck(t *testing.T) {\n\tcmd := exec.Command(\"docker\", \"version\")\n\tif err := cmd.Run(); err != nil {\n\t\tt.Fatalf(\"Docker must be available: %s\", err)\n\t}\n}\n\nfunc init() ", "output": "{\n\ttestAccProvider = Provider().(*schema.Provider)\n\ttestAccProviders = map[string]terraform.ResourceProvider{\n\t\t\"docker\": testAccProvider,\n\t}\n}"} {"input": "package spark\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\nvar httpClient *http.Client\n\nfunc init() {\n\thttpClient = &http.Client{}\n}\n\nfunc (s *Spark) request(req *http.Request) ([]byte, error) {\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", s.token))\n\treq.Header.Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\n\tres, err := httpClient.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer res.Body.Close()\n\tbs, err := ioutil.ReadAll(res.Body)\n\n\tif res.StatusCode != http.StatusOK {\n\t\tif res.StatusCode != 204 {\n\t\t\te := fmt.Sprintf(\"HTTP Status Code: %d\\n%s\", res.StatusCode, string(bs))\n\t\t\treturn nil, errors.New(e)\n\t\t}\n\t}\n\n\treturn bs, err\n}\n\nfunc (s *Spark) GetRequest(url string, uv *url.Values) ([]byte, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif uv != nil {\n\t\treq.URL.RawQuery = (*uv).Encode()\n\t}\n\treturn s.request(req)\n}\n\n\n\nfunc (s *Spark) DeleteRequest(url string) ([]byte, error) {\n\tfmt.Println(\"Delete url: \", url)\n\treq, err := http.NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.request(req)\n}\n\nfunc (s *Spark) PostRequest(url string, body *bytes.Buffer) ([]byte, error) ", "output": "{\n\treq, err := http.NewRequest(\"POST\", url, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.request(req)\n}"} {"input": "package qln\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/btcsuite/btcd/chaincfg/chainhash\"\n\t\"github.com/mit-dci/lit/lnutil\"\n)\n\n\n\n\nfunc (q *Qchan) NextElkPointForThem() (p [33]byte, err error) {\n\treturn q.ElkPoint(false, q.State.StateIdx+1)\n}\n\n\n\n\n\n\n\n\n\nfunc (q *Qchan) AdvanceElkrem(elk *chainhash.Hash, nextElk [33]byte) error {\n\terr := q.IngestElkrem(elk)\n\tif err != nil {\n\t\treturn err\n\t}\n\tq.State.ElkPoint = q.State.NextElkPoint\n\tq.State.NextElkPoint = nextElk\n\treturn nil\n}\n\n\n\n\n\nfunc (q *Qchan) IngestElkrem(elk *chainhash.Hash) error {\n\tif elk == nil {\n\t\treturn fmt.Errorf(\"IngestElkrem: nil hash\")\n\t}\n\n\terr := q.ElkRcv.AddNext(elk)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"ingested hash, receiver now has up to %d\\n\", q.ElkRcv.UpTo())\n\n\tif q.State.StateIdx == 0 {\n\t\treturn nil\n\t}\n\n\n\tpoint := lnutil.ElkPointFromHash(elk)\n\n\tif point != q.State.ElkPoint {\n\t\treturn fmt.Errorf(\"hash %x (index %d) fits tree but creates wrong elkpoint!\",\n\t\t\telk[:8], q.State.ElkPoint)\n\t}\n\n\n\treturn nil\n}\n\nfunc (q *Qchan) ElkPoint(mine bool, idx uint64) (p [33]byte, err error) ", "output": "{\n\tif q == nil || q.ElkSnd == nil { \n\t\terr = fmt.Errorf(\"can't access elkrem sender\")\n\t\treturn\n\t}\n\tif mine && q.ElkRcv == nil { \n\t\terr = fmt.Errorf(\"can't access elkrem receiver\")\n\t\treturn\n\t}\n\n\telk := new(chainhash.Hash)\n\n\tif mine { \n\t\telk, err = q.ElkRcv.AtIndex(idx)\n\t} else { \n\t\telk, err = q.ElkSnd.AtIndex(idx)\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\tp = lnutil.ElkPointFromHash(elk)\n\n\treturn\n}"} {"input": "package temperature\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/pelletier/go-toml\"\n\t\"github.com/rumpelsepp/i3gostatus/lib/config\"\n\t\"github.com/rumpelsepp/i3gostatus/lib/model\"\n)\n\nconst (\n\tname = \"temperature\"\n\tmoduleName = \"i3gostatus.modules.\" + name\n\tdefaultPeriod = 5000\n\tdefaultFormat = \"%d°C\"\n\tdefaultUrgentTemp = 70\n\tdefaultUrgentColor = \"#FF0000\"\n)\n\ntype Config struct {\n\tmodel.BaseConfig\n\tUrgentTemp int\n\tUrgentColor string\n}\n\n\n\nfunc (c *Config) Run(args *model.ModuleArgs) {\n\tvar (\n\t\toutputBlock *model.I3BarBlock\n\t\ttemperature int\n\t\tthermalFile = \"/sys/class/thermal/thermal_zone0/temp\"\n\t)\n\n\tfor range time.NewTicker(c.Period).C {\n\t\toutputBlock = model.NewBlock(moduleName, c.BaseConfig, args.Index)\n\t\tdata, err := ioutil.ReadFile(thermalFile)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tdataStr := strings.TrimSpace(string(data))\n\n\t\tif t, err := strconv.Atoi(dataStr); err == nil {\n\t\t\ttemperature = int(t / 1000)\n\t\t\tif temperature >= c.UrgentTemp {\n\t\t\t\toutputBlock.Urgent = true\n\t\t\t\toutputBlock.Color = c.UrgentColor\n\t\t\t}\n\t\t}\n\n\t\toutputBlock.FullText = fmt.Sprintf(c.Format, temperature)\n\t\targs.OutCh <- outputBlock\n\t}\n}\n\nfunc (c *Config) ParseConfig(configTree *toml.TomlTree) ", "output": "{\n\tc.BaseConfig.Parse(name, configTree)\n\tc.BaseConfig.Period = config.GetDurationMs(configTree, c.Name+\".period\", defaultPeriod)\n\tc.Format = config.GetString(configTree, name+\".format\", defaultFormat)\n\tc.UrgentTemp = config.GetInt(configTree, name+\".urgent_temp\", defaultUrgentTemp)\n\tc.UrgentColor = config.GetString(configTree, name+\".urgent_color\", defaultUrgentColor)\n}"} {"input": "package clock\n\nimport (\n\t\"time\"\n)\n\n\n\n\n\ntype Clock interface {\n\tNow() time.Time\n}\n\ntype clock struct{}\n\nfunc (c *clock) Now() time.Time {\n\treturn time.Now()\n}\n\n\ntype Mock struct {\n\tcurrentTime time.Time\n}\n\n\nfunc (c *Mock) SetNow(t time.Time) {\n\tc.currentTime = t\n}\n\n\nfunc (c *Mock) Now() time.Time {\n\treturn c.currentTime\n}\n\n\nfunc New() Clock {\n\treturn &clock{}\n}\n\n\n\n\nfunc NewMock() *Mock ", "output": "{\n\treturn &Mock{\n\t\tcurrentTime: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),\n\t}\n}"} {"input": "package statsd\n\nimport (\n\t\"math\"\n\t\"math/rand\"\n\t\"sort\"\n)\n\nconst defaultPercentileLimit = 1000\n\n\n\n\n\ntype RunningStats struct {\n\tk float64\n\tn int64\n\tex float64\n\tex2 float64\n\n\tperc []float64\n\tPercLimit int\n\n\tsum float64\n\n\tlower float64\n\tupper float64\n\n\tsorted bool\n}\n\n\n\nfunc (rs *RunningStats) Mean() float64 {\n\treturn rs.k + rs.ex/float64(rs.n)\n}\n\nfunc (rs *RunningStats) Variance() float64 {\n\treturn (rs.ex2 - (rs.ex*rs.ex)/float64(rs.n)) / float64(rs.n)\n}\n\nfunc (rs *RunningStats) Stddev() float64 {\n\treturn math.Sqrt(rs.Variance())\n}\n\nfunc (rs *RunningStats) Sum() float64 {\n\treturn rs.sum\n}\n\nfunc (rs *RunningStats) Upper() float64 {\n\treturn rs.upper\n}\n\nfunc (rs *RunningStats) Lower() float64 {\n\treturn rs.lower\n}\n\nfunc (rs *RunningStats) Count() int64 {\n\treturn rs.n\n}\n\nfunc (rs *RunningStats) Percentile(n int) float64 {\n\tif n > 100 {\n\t\tn = 100\n\t}\n\n\tif !rs.sorted {\n\t\tsort.Float64s(rs.perc)\n\t\trs.sorted = true\n\t}\n\n\ti := int(float64(len(rs.perc)) * float64(n) / float64(100))\n\treturn rs.perc[clamp(i, 0, len(rs.perc)-1)]\n}\n\nfunc clamp(i int, min int, max int) int {\n\tif i < min {\n\t\treturn min\n\t}\n\tif i > max {\n\t\treturn max\n\t}\n\treturn i\n}\n\nfunc (rs *RunningStats) AddValue(v float64) ", "output": "{\n\trs.sorted = false\n\n\tif rs.n == 0 {\n\t\trs.k = v\n\t\trs.upper = v\n\t\trs.lower = v\n\t\tif rs.PercLimit == 0 {\n\t\t\trs.PercLimit = defaultPercentileLimit\n\t\t}\n\t\trs.perc = make([]float64, 0, rs.PercLimit)\n\t}\n\n\trs.n++\n\trs.ex += v - rs.k\n\trs.ex2 += (v - rs.k) * (v - rs.k)\n\n\trs.sum += v\n\n\tif v > rs.upper {\n\t\trs.upper = v\n\t} else if v < rs.lower {\n\t\trs.lower = v\n\t}\n\n\tif len(rs.perc) < rs.PercLimit {\n\t\trs.perc = append(rs.perc, v)\n\t} else {\n\t\trs.perc[rand.Intn(len(rs.perc))] = v\n\t}\n}"} {"input": "package model\n\nimport (\n\t\"log\"\n\t\"reflect\"\n\n\t\"github.com/go-errors/errors\"\n)\n\ntype ProviderRegistry struct {\n\tproviders []Provider\n}\n\n\n\nfunc (registry *ProviderRegistry) ResolveProvider() (Provider, error) {\n\tfor _, p := range registry.providers {\n\t\tlog.Printf(\"Detect provider: %v\", reflect.TypeOf(p))\n\t\tif p.Detect() {\n\t\t\tlog.Printf(\"Found provider: %v\", reflect.TypeOf(p))\n\t\t\terr := p.Init()\n\t\t\treturn p, err\n\t\t}\n\t}\n\treturn nil, errors.Errorf(\"Could not resolve to any provider.\")\n}\n\nfunc (registry *ProviderRegistry) RegisterProvider(provider Provider) ", "output": "{\n\tregistry.providers = append(registry.providers, provider)\n}"} {"input": "package meterstatus\n\nimport (\n\t\"time\"\n)\n\ntype TriggerCreator func(WorkerState, string, time.Time, Clock, time.Duration, time.Duration) (<-chan time.Time, <-chan time.Time)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc GetTriggers(\n\twst WorkerState,\n\tstatus string,\n\tdisconnectedAt time.Time,\n\tclk Clock,\n\tamberGracePeriod time.Duration,\n\tredGracePeriod time.Duration) (<-chan time.Time, <-chan time.Time) ", "output": "{\n\n\tnow := clk.Now()\n\n\tif wst == Done {\n\t\treturn nil, nil\n\t}\n\n\tif wst <= WaitingAmber && status == \"RED\" {\n\t\twst = WaitingRed\n\t} else if wst < Done && now.Sub(disconnectedAt) >= redGracePeriod {\n\t\twst = WaitingRed\n\t}\n\n\tif wst == WaitingRed {\n\t\tredSignal := clk.After(redGracePeriod - now.Sub(disconnectedAt))\n\t\treturn nil, redSignal\n\t}\n\tif wst == WaitingAmber || wst == Uninitialized {\n\t\tamberSignal := clk.After(amberGracePeriod - now.Sub(disconnectedAt))\n\t\tredSignal := clk.After(redGracePeriod - now.Sub(disconnectedAt))\n\t\treturn amberSignal, redSignal\n\t}\n\treturn nil, nil\n}"} {"input": "package rz\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc ExampleSyncPoint() {\n\tvar resource int = 0\n\tvar syncpoint = NewSyncPoint(func(arg1 int) (arg2 int) {\n\t\targ2 = resource + arg1\n\t\treturn\n\t})\n\tgo func() {\n\t\tfor {\n\t\t\tsyncpoint.Send(func(arg2 int) {\n\t\t\t\tfmt.Println(arg2)\n\t\t\t},\n\t\t\t\t 1000)\n\t\t}\n\t}()\n\tfor resource < 10 {\n\t\tsyncpoint.Accept()\n\t\tresource++\n\t\ttime.Sleep(10 * time.Microsecond)\n\t}\n\n}\n\nfunc BenchmarkMain(b *testing.B) {\n\tvar resource int = 0\n\tvar syncpoint = NewSyncPoint(func(arg1 int) (arg2 int) {\n\t\treturn resource + arg1\n\t})\n\tgo func() {\n\t\tfor {\n\t\t\tb.StartTimer()\n\t\t\tsyncpoint.Send(func(arg2 int) { arg2 = 0 }, 1000)\n\t\t\tb.StopTimer()\n\t\t}\n\t}()\n\tb.ResetTimer()\n\tfor resource < b.N {\n\t\tsyncpoint.Accept()\n\t\tresource++\n\t}\n}\n\n\n\nfunc BenchmarkMain_nofunc(b *testing.B) ", "output": "{\n\tvar resource int = 0\n\tvar syncpoint = NewSyncPoint(nil)\n\tgo func() {\n\t\tfor {\n\t\t\tb.StartTimer()\n\t\t\tsyncpoint.Send(nil)\n\t\t\tb.StopTimer()\n\t\t}\n\t}()\n\tb.ResetTimer()\n\tfor resource < b.N {\n\t\tsyncpoint.Accept()\n\t\tresource++\n\t}\n}"} {"input": "package processors\n\nimport \"github.com/dailyburn/ratchet/data\"\n\n\n\n\n\ntype Passthrough struct {\n\ti int\n}\n\n\nfunc NewPassthrough() *Passthrough {\n\treturn &Passthrough{}\n}\n\n\n\n\n\nfunc (r *Passthrough) Finish(outputChan chan data.JSON, killChan chan error) {\n}\n\nfunc (r *Passthrough) String() string {\n\treturn \"Passthrough\"\n}\n\nfunc (r *Passthrough) ProcessData(d data.JSON, outputChan chan data.JSON, killChan chan error) ", "output": "{\n\toutputChan <- d\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/wikiwi/kube-volume-freezer/pkg/client\"\n\t\"github.com/wikiwi/kube-volume-freezer/pkg/util/validation\"\n)\n\ntype listCommand struct {\n}\n\nfunc (cmd *listCommand) Execute(args []string) error {\n\tif len(args) < 1 {\n\t\treturn fmt.Errorf(\"Error: Please specify Pod and Volume.\")\n\t}\n\tif len(args) > 1 {\n\t\treturn fmt.Errorf(\"Error: Unexpected argument %s\", args[1:])\n\t}\n\n\tpodName := args[0]\n\n\tif issues := validation.ValidateQualitfiedName(podName); len(issues) > 0 {\n\t\treturn fmt.Errorf(\"Error: Invalid Pod Name %s\", issues)\n\t}\n\n\toptions := &client.Options{Token: globalOptions.Token}\n\tclient, err := client.New(globalOptions.Address, options)\n\tif err != nil {\n\t\treturn err\n\t}\n\tls, err := client.Volumes().List(globalOptions.Namespace, podName)\n\tfor _, item := range ls.Items {\n\t\tfmt.Println(item)\n\t}\n\treturn err\n}\n\n\n\nfunc init() ", "output": "{\n\tparser.AddCommand(\"list\",\n\t\t\"List Pod Volumes\",\n\t\t\"List Pod Volumes\",\n\t\tnew(listCommand))\n}"} {"input": "package notify\n\nimport \"github.com/crocos/rds-testrunner/config\"\n\nfunc NewNotifier(notifyConfig config.NotifyConfig) NotifierInterface {\n\tif notifyConfig.Type == \"hipchat\" {\n\t\treturn NewHipChatNotifier(notifyConfig)\n\t} else {\n\t\treturn NewDummyNotifier(notifyConfig)\n\t}\n}\n\ntype NotifierInterface interface {\n\tInfo(string) error\n\tWarning(string) error\n\tError(string) error\n}\n\ntype DummyNotifier struct {\n\tConfig config.NotifyConfig\n}\n\nfunc NewDummyNotifier(notifyConfig config.NotifyConfig) (notify NotifierInterface) {\n\treturn &DummyNotifier{Config: notifyConfig}\n}\n\nfunc (n *DummyNotifier) Info(message string) (err error) {\n\treturn\n}\n\n\n\nfunc (n *DummyNotifier) Error(message string) (err error) {\n\treturn\n}\n\nfunc (n *DummyNotifier) Warning(message string) (err error) ", "output": "{\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/xtracdev/xavi/env\"\n\t\"github.com/xtracdev/xavi/plugin\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestPluginRegistration(t *testing.T) {\n\tregisterPlugins()\n\tassert.True(t, plugin.RegistryContains(\"Logging\"))\n}\n\n\n\nfunc TestGrabCommandLineArgs(t *testing.T) {\n\tgrabCommandLineArgs()\n}\n\nfunc TestXapHook(t *testing.T) ", "output": "{\n\tos.Setenv(env.LoggingOpts, \"\")\n\terr := addXapHook()\n\tassert.Nil(t, err)\n\n\tos.Setenv(env.LoggingOpts, env.Tcplog)\n\terr = addXapHook()\n\tassert.NotNil(t, err)\n\n\tos.Setenv(env.TcplogAddress, \"parse this ### yes?\")\n\terr = addXapHook()\n\tassert.NotNil(t, err)\n\n\tos.Setenv(env.TcplogAddress, \"0.0.0.0:80\")\n\terr = addXapHook()\n\tassert.NotNil(t, err)\n}"} {"input": "package v1alpha1\n\ntype errorList struct {\n\terrors []error\n}\n\n\nfunc (l *errorList) addError(err error) []error {\n\tif err == nil {\n\t\treturn l.errors\n\t}\n\n\tl.errors = append(l.errors, err)\n\treturn l.errors\n}\n\n\n\n\nfunc (l *errorList) addErrors(errs []error) []error ", "output": "{\n\tfor _, err := range errs {\n\t\tl.addError(err)\n\t}\n\n\treturn l.errors\n}"} {"input": "package google\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform-plugin-sdk/helper/resource\"\n)\n\n\n\nfunc testAccComputeSnapshot_encryption(snapshotName string, diskName string) string {\n\treturn fmt.Sprintf(`\ndata \"google_compute_image\" \"my_image\" {\n family = \"debian-9\"\n project = \"debian-cloud\"\n}\n\nresource \"google_compute_disk\" \"foobar\" {\n name = \"%s\"\n image = data.google_compute_image.my_image.self_link\n size = 10\n type = \"pd-ssd\"\n zone = \"us-central1-a\"\n disk_encryption_key {\n raw_key = \"SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=\"\n }\n}\n\nresource \"google_compute_snapshot\" \"foobar\" {\n name = \"%s\"\n source_disk = google_compute_disk.foobar.name\n zone = \"us-central1-a\"\n snapshot_encryption_key {\n raw_key = \"SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=\"\n }\n\n source_disk_encryption_key {\n raw_key = \"SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=\"\n }\n}\n`, diskName, snapshotName)\n}\n\nfunc TestAccComputeSnapshot_encryption(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\tsnapshotName := fmt.Sprintf(\"tf-test-%s\", randString(t, 10))\n\tdiskName := fmt.Sprintf(\"tf-test-%s\", randString(t, 10))\n\n\tvcrTest(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testAccCheckComputeSnapshotDestroyProducer(t),\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccComputeSnapshot_encryption(snapshotName, diskName),\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName: \"google_compute_snapshot.foobar\",\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t\tImportStateVerifyIgnore: []string{\"zone\", \"snapshot_encryption_key\", \"source_disk_encryption_key\"},\n\t\t\t},\n\t\t},\n\t})\n}"} {"input": "package sharedaction\n\ntype AuthActor interface {\n\tIsLoggedIn() bool\n}\n\n\ntype Actor struct {\n\tConfig Config\n\tAuthActor\n}\n\n\n\n\nfunc NewActor(config Config) *Actor ", "output": "{\n\tvar authActor AuthActor = NewDefaultAuthActor(config)\n\tif config.IsCFOnK8s() {\n\t\tauthActor = NewK8sAuthActor(config)\n\t}\n\n\treturn &Actor{\n\t\tAuthActor: authActor,\n\t\tConfig: config,\n\t}\n}"} {"input": "package cloudinfo\n\nimport (\n\t\"k8s.io/klog/v2\"\n\n\tinfo \"github.com/google/cadvisor/info/v1\"\n)\n\ntype CloudInfo interface {\n\tGetCloudProvider() info.CloudProvider\n\tGetInstanceType() info.InstanceType\n\tGetInstanceID() info.InstanceID\n}\n\n\ntype CloudProvider interface {\n\tIsActiveProvider() bool\n\tGetInstanceType() info.InstanceType\n\tGetInstanceID() info.InstanceID\n}\n\nvar providers = map[info.CloudProvider]CloudProvider{}\n\n\nfunc RegisterCloudProvider(name info.CloudProvider, provider CloudProvider) {\n\tif _, alreadyRegistered := providers[name]; alreadyRegistered {\n\t\tklog.Warningf(\"Duplicate registration of CloudProvider %s\", name)\n\t}\n\tproviders[name] = provider\n}\n\ntype realCloudInfo struct {\n\tcloudProvider info.CloudProvider\n\tinstanceType info.InstanceType\n\tinstanceID info.InstanceID\n}\n\nfunc NewRealCloudInfo() CloudInfo {\n\tfor name, provider := range providers {\n\t\tif provider.IsActiveProvider() {\n\t\t\treturn &realCloudInfo{\n\t\t\t\tcloudProvider: name,\n\t\t\t\tinstanceType: provider.GetInstanceType(),\n\t\t\t\tinstanceID: provider.GetInstanceID(),\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &realCloudInfo{\n\t\tcloudProvider: info.UnknownProvider,\n\t\tinstanceType: info.UnknownInstance,\n\t\tinstanceID: info.UnNamedInstance,\n\t}\n}\n\nfunc (i *realCloudInfo) GetCloudProvider() info.CloudProvider {\n\treturn i.cloudProvider\n}\n\n\n\nfunc (i *realCloudInfo) GetInstanceID() info.InstanceID {\n\treturn i.instanceID\n}\n\nfunc (i *realCloudInfo) GetInstanceType() info.InstanceType ", "output": "{\n\treturn i.instanceType\n}"} {"input": "package v1\n\n\n\ntype EnvVarSourceApplyConfiguration struct {\n\tFieldRef *ObjectFieldSelectorApplyConfiguration `json:\"fieldRef,omitempty\"`\n\tResourceFieldRef *ResourceFieldSelectorApplyConfiguration `json:\"resourceFieldRef,omitempty\"`\n\tConfigMapKeyRef *ConfigMapKeySelectorApplyConfiguration `json:\"configMapKeyRef,omitempty\"`\n\tSecretKeyRef *SecretKeySelectorApplyConfiguration `json:\"secretKeyRef,omitempty\"`\n}\n\n\n\nfunc EnvVarSource() *EnvVarSourceApplyConfiguration {\n\treturn &EnvVarSourceApplyConfiguration{}\n}\n\n\n\n\n\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithResourceFieldRef(value *ResourceFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.ResourceFieldRef = value\n\treturn b\n}\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithConfigMapKeyRef(value *ConfigMapKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.ConfigMapKeyRef = value\n\treturn b\n}\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithSecretKeyRef(value *SecretKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.SecretKeyRef = value\n\treturn b\n}\n\nfunc (b *EnvVarSourceApplyConfiguration) WithFieldRef(value *ObjectFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration ", "output": "{\n\tb.FieldRef = value\n\treturn b\n}"} {"input": "package s0132\n\nimport (\n\t\"github.com/peterstace/project-euler/number\"\n)\n\nfunc Answer() interface{} {\n\treturn SumPrimeFactors(40, 10e9)\n}\n\nfunc SumPrimeFactors(numFactors int, k int) int {\n\tvar factorsFound int\n\tvar sum int\n\tnthPrime := number.MakeSieveBackedNthPrime()\n\tfor i := 0; factorsFound < numFactors; i++ {\n\t\tp := nthPrime(i)\n\t\tif repunit(k, p) == 0 {\n\t\t\tfactorsFound++\n\t\t\tsum += p\n\t\t}\n\t}\n\treturn sum\n}\n\n\n\n\n\nfunc tenPow(k, m int) int {\n\tif k == 0 {\n\t\treturn 1\n\t}\n\tif k%2 == 0 {\n\t\thalf := tenPow(k/2, m)\n\t\treturn (half * half) % m\n\t} else {\n\t\treturn (10 * tenPow(k-1, m)) % m\n\t}\n}\n\nfunc repunit(k, m int) int ", "output": "{\n\tif k == 1 {\n\t\treturn 1\n\t}\n\tif k%2 == 0 {\n\t\thalf := repunit(k/2, m)\n\t\treturn (tenPow(k/2, m)*half + half) % m\n\t} else {\n\t\treturn (10*repunit(k-1, m) + 1) % m\n\t}\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/robfig/revel\"\n\t\"github.com/robfig/revel/samples/chat/app/chatroom\"\n\t\"github.com/robfig/revel/samples/chat/app/routes\"\n)\n\ntype Refresh struct {\n\t*revel.Controller\n}\n\n\n\nfunc (c Refresh) Room(user string) revel.Result {\n\tsubscription := chatroom.Subscribe()\n\tdefer subscription.Cancel()\n\tevents := subscription.Archive\n\tfor i, _ := range events {\n\t\tif events[i].User == user {\n\t\t\tevents[i].User = \"you\"\n\t\t}\n\t}\n\treturn c.Render(user, events)\n}\n\nfunc (c Refresh) Say(user, message string) revel.Result {\n\tchatroom.Say(user, message)\n\treturn c.Redirect(routes.Refresh.Room(user))\n}\n\nfunc (c Refresh) Leave(user string) revel.Result {\n\tchatroom.Leave(user)\n\treturn c.Redirect(Application.Index)\n}\n\nfunc (c Refresh) Index(user string) revel.Result ", "output": "{\n\tchatroom.Join(user)\n\treturn c.Redirect(routes.Refresh.Room(user))\n}"} {"input": "package build\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/kubecfg\"\n\t\"github.com/openshift/origin/pkg/build/api\"\n)\n\nvar buildColumns = []string{\"Name\", \"Type\", \"Status\", \"Pod Name\"}\nvar buildConfigColumns = []string{\"Name\", \"Type\", \"SourceURI\"}\n\n\n\nfunc RegisterPrintHandlers(printer *kubecfg.HumanReadablePrinter) {\n\tprinter.Handler(buildColumns, printBuild)\n\tprinter.Handler(buildColumns, printBuildList)\n\tprinter.Handler(buildConfigColumns, printBuildConfig)\n\tprinter.Handler(buildConfigColumns, printBuildConfigList)\n}\n\n\n\nfunc printBuildList(buildList *api.BuildList, w io.Writer) error {\n\tfor _, build := range buildList.Items {\n\t\tif err := printBuild(&build, w); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc printBuildConfig(bc *api.BuildConfig, w io.Writer) error {\n\t_, err := fmt.Fprintf(w, \"%s\\t%v\\t%s\\n\", bc.Name, bc.Parameters.Strategy.Type, bc.Parameters.Source.Git.URI)\n\treturn err\n}\n\nfunc printBuildConfigList(buildList *api.BuildConfigList, w io.Writer) error {\n\tfor _, buildConfig := range buildList.Items {\n\t\tif err := printBuildConfig(&buildConfig, w); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc printBuild(build *api.Build, w io.Writer) error ", "output": "{\n\t_, err := fmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\\n\", build.Name, build.Parameters.Strategy.Type, build.Status, build.PodName)\n\treturn err\n}"} {"input": "package slackutilsx\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestDetectChannelType(t *testing.T) ", "output": "{\n\ttest := func(channelID string, expected ChannelType) {\n\t\tif computed := DetectChannelType(channelID); computed != expected {\n\t\t\tt.Errorf(\"expected channelID %s to have type %s, got: %s\", channelID, expected, computed)\n\t\t}\n\t}\n\n\ttest(\"G11111111\", CTypeGroup)\n\ttest(\"D11111111\", CTypeDM)\n\ttest(\"C11111111\", CTypeChannel)\n\ttest(\"\", CTypeUnknown)\n\ttest(\"X11111111\", CTypeUnknown)\n}"} {"input": "package prometheus\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"text/template\"\n\n\t\"github.com/pkg/errors\"\n\n\ttm \"github.com/supergiant/control/pkg/templatemanager\"\n\t\"github.com/supergiant/control/pkg/workflows/steps\"\n)\n\nconst StepName = \"prometheus\"\n\ntype Config struct {\n\tRBACEnabled bool\n}\n\ntype Step struct {\n\tscript *template.Template\n}\n\nfunc (s *Step) Rollback(context.Context, io.Writer, *steps.Config) error {\n\treturn nil\n}\n\nfunc Init() {\n\ttpl, err := tm.GetTemplate(StepName)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"template %s not found\", StepName))\n\t}\n\n\tsteps.RegisterStep(StepName, New(tpl))\n}\n\nfunc New(script *template.Template) *Step {\n\tt := &Step{\n\t\tscript: script,\n\t}\n\n\treturn t\n}\n\nfunc (s *Step) Run(ctx context.Context, out io.Writer, config *steps.Config) error {\n\terr := steps.RunTemplate(ctx, s.script, config.Runner, out, toStepCfg(config))\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"install prometheus step\")\n\t}\n\n\treturn nil\n}\n\nfunc (s *Step) Name() string {\n\treturn StepName\n}\n\n\n\nfunc (s *Step) Depends() []string {\n\treturn nil\n}\n\nfunc toStepCfg(c *steps.Config) Config {\n\treturn Config{\n\t\tRBACEnabled: c.Kube.RBACEnabled,\n\t}\n}\n\nfunc (s *Step) Description() string ", "output": "{\n\treturn \"Install prometheus\"\n}"} {"input": "package arangolite\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"net/http\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc runWebserver() {\n\tgo func() {\n\t\thttp.HandleFunc(\"/\", longRequest)\n\t\thttp.ListenAndServe(\":9999\", nil)\n\t}()\n}\n\nfunc TestSendCanBeCanceled(t *testing.T) {\n\trunWebserver()\n\n\tclient := &http.Client{}\n\treq, _ := http.NewRequest(\"GET\", \"http://localhost:9999\", nil)\n\n\tsender := basicSender{}\n\tparent := context.Background()\n\tctx, cancel := context.WithTimeout(parent, 100*time.Millisecond)\n\tdefer cancel()\n\n\tresp, err := sender.Send(ctx, client, req)\n\n\tassertEqual(t, err.Error(), \"the database HTTP request failed: Get http://localhost:9999: context deadline exceeded\")\n\tassertTrue(t, resp == nil, \"The response of a canceled request should be nil\")\n}\n\nfunc longRequest(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tio.WriteString(w, \"Waiting 2 seconds...\")\n\ttime.Sleep(200 * time.Millisecond)\n\tpanic(\"The request was not canceled\")\n}"} {"input": "package pseudo\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestProducts(t *testing.T) ", "output": "{\n\ts := MustNewService(0, nil)\n\tfor _, lang := range s.GetLangs() {\n\t\ts.SetLang(lang)\n\n\t\tv := s.Brand()\n\t\tif v == \"\" {\n\t\t\tt.Errorf(\"Brand failed with lang %s\", lang)\n\t\t}\n\n\t\tv = s.ProductName()\n\t\tif v == \"\" {\n\t\t\tt.Errorf(\"ProductName failed with lang %s\", lang)\n\t\t}\n\n\t\tv = s.Product()\n\t\tif v == \"\" {\n\t\t\tt.Errorf(\"Product failed with lang %s\", lang)\n\t\t}\n\n\t\tv = s.Model()\n\t\tif v == \"\" {\n\t\t\tt.Errorf(\"Model failed with lang %s\", lang)\n\t\t}\n\t}\n}"} {"input": "package trello\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\t\"testing\"\n)\n\n\n\nfunc TestWithContext(t *testing.T) {\n\tc := testClient()\n\tif c.ctx != context.Background() {\n\t\tt.Fatal(\"NewClient() should use context.Background()\")\n\t}\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tnewC := c.WithContext(ctx)\n\tif newC == c {\n\t\tt.Fatal(\"WithContext() should return a new client\")\n\t}\n\n\tif newC.ctx != ctx {\n\t\tt.Fatal(\"WithContext() should return a client with the given context\")\n\t}\n\n\tvar calls int\n\tmt := &mockTransport{\n\t\tRoundTripFunc: func(req *http.Request) (*http.Response, error) {\n\t\t\tcalls++\n\t\t\tif req.Context() != ctx {\n\t\t\t\tt.Fatal(\"Get() should be using the new context\")\n\t\t\t}\n\t\t\treturn http.DefaultTransport.RoundTrip(req)\n\t\t},\n\t}\n\tnewC.Client = &http.Client{\n\t\tTransport: mt,\n\t}\n\tnewC.Get(\"members\", nil, nil)\n\n\tif calls != 1 {\n\t\tt.Fatal(\"Get() should have used the mocked transport\")\n\t}\n}\n\ntype mockTransport struct {\n\tRoundTripFunc func(*http.Request) (*http.Response, error)\n}\n\nfunc (t *mockTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\treturn t.RoundTripFunc(req)\n}\n\nfunc testClient() *Client {\n\tc := NewClient(\"user\", \"pass\")\n\tc.testMode = true\n\treturn c\n}\n\nfunc TestGetWithBadURL(t *testing.T) ", "output": "{\n\tc := testClient()\n\ttarget := map[string]interface{}{}\n\tc.BaseURL = \"gopher:test\"\n\terr := c.Get(\"members\", Defaults(), &target)\n\tif err == nil {\n\t\tt.Fatal(\"Get() should fail with a bad URL\")\n\t}\n}"} {"input": "package miniredis\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\nfunc assert(tb testing.TB, condition bool, msg string, v ...interface{}) {\n\ttb.Helper()\n\n\tif !condition {\n\t\ttb.Errorf(msg, v...)\n\t}\n}\n\n\nfunc ok(tb testing.TB, err error) {\n\ttb.Helper()\n\n\tif err != nil {\n\t\ttb.Errorf(\"unexpected error: %s\", err.Error())\n\t}\n}\n\n\n\n\n\nfunc mustFail(tb testing.TB, err error, want string) {\n\ttb.Helper()\n\n\tif err == nil {\n\t\ttb.Errorf(\"expected an error, but got a nil\")\n\t}\n\n\tif have := err.Error(); have != want {\n\t\ttb.Errorf(\"have %q, want %q\", have, want)\n\t}\n}\n\nfunc equals(tb testing.TB, exp, act interface{}) ", "output": "{\n\ttb.Helper()\n\n\tif !reflect.DeepEqual(exp, act) {\n\t\ttb.Errorf(\"expected: %#v got: %#v\", exp, act)\n\t}\n}"} {"input": "package cases\n\nimport \"github.com/insionng/yougam/libraries/x/text/transform\"\n\ntype caseFolder struct{ transform.NopResetter }\n\n\nfunc (t *caseFolder) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {\n\tc := context{dst: dst, src: src, atEOF: atEOF}\n\tfor c.next() {\n\t\tfoldFull(&c)\n\t\tc.checkpoint()\n\t}\n\treturn c.ret()\n}\n\n\n\nfunc makeFold(o options) transform.Transformer ", "output": "{\n\treturn &caseFolder{}\n}"} {"input": "package tarball\n\nimport (\n\t\"archive/tar\"\n\t\"io\"\n)\n\n\ntype WalkFunc func(t *TarFile) error\n\n\n\n\n\nfunc Walk(tarstream io.Reader, walkFunc WalkFunc) error ", "output": "{\n\treader := tar.NewReader(tarstream)\nReadLoop:\n\tfor {\n\t\theader, err := reader.Next()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak ReadLoop\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tif err := walkFunc(&TarFile{Header: header, Stream: reader}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package aggregation\n\nimport \"github.com/m3db/m3/src/x/pool\"\n\n\ntype TypesAlloc func() Types\n\n\ntype TypesPool interface {\n\tInit(alloc TypesAlloc)\n\n\tGet() Types\n\n\tPut(value Types)\n}\n\ntype typesPool struct {\n\tpool pool.ObjectPool\n}\n\n\nfunc NewTypesPool(opts pool.ObjectPoolOptions) TypesPool {\n\treturn &typesPool{pool: pool.NewObjectPool(opts)}\n}\n\nfunc (p *typesPool) Init(alloc TypesAlloc) {\n\tp.pool.Init(func() interface{} {\n\t\treturn alloc()\n\t})\n}\n\n\n\nfunc (p *typesPool) Put(value Types) {\n\tp.pool.Put(value[:0])\n}\n\nfunc (p *typesPool) Get() Types ", "output": "{\n\treturn p.pool.Get().(Types)\n}"} {"input": "package sns\n\n\n\nimport (\n\t\"encoding/xml\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"time\"\n\n\t\"github.com/goamz/goamz/aws\"\n)\n\n\ntype SNS struct {\n\taws.Auth\n\taws.Region\n\tprivate byte \n}\n\ntype AttributeEntry struct {\n\tKey string `xml:\"key\"`\n\tValue string `xml:\"value\"`\n}\n\ntype ResponseMetadata struct {\n\tRequestId string `xml:\"ResponseMetadata>RequestId\"`\n\tBoxUsage float64 `xml:\"ResponseMetadata>BoxUsage\"`\n}\n\nfunc New(auth aws.Auth, region aws.Region) *SNS {\n\treturn &SNS{auth, region, 0}\n}\n\nfunc makeParams(action string) map[string]string {\n\tparams := make(map[string]string)\n\tparams[\"Action\"] = action\n\treturn params\n}\n\ntype Error struct {\n\tStatusCode int\n\tCode string\n\tMessage string\n\tRequestId string\n}\n\nfunc (err *Error) Error() string {\n\treturn err.Message\n}\n\ntype xmlErrors struct {\n\tRequestId string\n\tErrors []Error `xml:\"Errors>Error\"`\n}\n\n\n\nfunc buildError(r *http.Response) error {\n\terrors := xmlErrors{}\n\txml.NewDecoder(r.Body).Decode(&errors)\n\tvar err Error\n\tif len(errors.Errors) > 0 {\n\t\terr = errors.Errors[0]\n\t}\n\terr.RequestId = errors.RequestId\n\terr.StatusCode = r.StatusCode\n\tif err.Message == \"\" {\n\t\terr.Message = r.Status\n\t}\n\treturn &err\n}\n\nfunc multimap(p map[string]string) url.Values {\n\tq := make(url.Values, len(p))\n\tfor k, v := range p {\n\t\tq[k] = []string{v}\n\t}\n\treturn q\n}\n\nfunc (sns *SNS) query(params map[string]string, resp interface{}) error ", "output": "{\n\tparams[\"Timestamp\"] = time.Now().UTC().Format(time.RFC3339)\n\tu, err := url.Parse(sns.Region.SNSEndpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsign(sns.Auth, \"GET\", \"/\", params, u.Host)\n\tu.RawQuery = multimap(params).Encode()\n\tr, err := http.Get(u.String())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Body.Close()\n\n\tif r.StatusCode != http.StatusOK {\n\t\treturn buildError(r)\n\t}\n\terr = xml.NewDecoder(r.Body).Decode(resp)\n\treturn err\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gophercloud/gophercloud\"\n\t\"github.com/gophercloud/gophercloud/openstack\"\n)\n\ntype identity struct {\n\tscV3 *gophercloud.ServiceClient\n}\n\ntype identityConfig struct {\n\tendpoint string\n\tserviceUserName string\n\tservicePassword string\n}\n\n\n\nfunc newIdentityClient(config identityConfig) (*identity, error) ", "output": "{\n\topt := gophercloud.AuthOptions{\n\t\tIdentityEndpoint: config.endpoint + \"/v3/\",\n\t\tUsername: config.serviceUserName,\n\t\tPassword: config.servicePassword,\n\t\tTenantName: \"service\",\n\t\tDomainID: \"default\",\n\t\tAllowReauth: true,\n\t}\n\tprovider, err := openstack.AuthenticatedClient(opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tv3client, err := openstack.NewIdentityV3(provider, gophercloud.EndpointOpts{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to get keystone V3 client : %v\", err)\n\t}\n\n\tid := &identity{\n\t\tscV3: v3client,\n\t}\n\n\treturn id, err\n}"} {"input": "package osquery\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/prometheus/common/log\"\n\t\"os/exec\"\n\t\"github.com/zwopir/osquery_exporter/model\"\n\t\"time\"\n)\n\n\ntype OsqueryRunner struct {\n\texecutable string\n\ttimeout time.Duration\n}\n\n\n\n\n\n\n\nfunc (runner *OsqueryRunner) Run(query string) (*model.OsqueryResult, error) {\n\tvar items []model.OsqueryItem\n\tbegin := time.Now()\n\tctx, cancel := context.WithTimeout(context.Background(), runner.timeout)\n\tdefer cancel()\n\tcmd := exec.CommandContext(ctx, runner.executable, \"--json\", query)\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debugf(\"running query %q\", query)\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := json.NewDecoder(stdout).Decode(&items); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := cmd.Wait(); err != nil {\n\t\treturn nil, err\n\t}\n\tduration := time.Since(begin)\n\treturn &model.OsqueryResult{\n\t\tItems: items,\n\t\tRuntime: duration,\n\t}, nil\n}\n\nfunc NewRunner(executable, timeout string) (*OsqueryRunner, error) ", "output": "{\n\tto, err := time.ParseDuration(timeout)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't parse timeout for runner: %s\", err)\n\t}\n\texe, err := exec.LookPath(executable)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"osqueryi executable not found in %s: %s\", executable, err)\n\t}\n\n\tlog.Infof(\"creating runner on executable %q with timeout %s\", exe, timeout)\n\treturn &OsqueryRunner{\n\t\texecutable: exe,\n\t\ttimeout: to,\n\t}, nil\n}"} {"input": "package sol\n\n\ntype Operator interface {\n\tWrap(string) string \n}\n\n\nfunc Function(name string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(FuncClause{Name: name})\n}\n\n\nfunc Avg(col Columnar) ColumnElem {\n\treturn Function(AVG, col)\n}\n\n\nfunc Count(col Columnar) ColumnElem {\n\treturn Function(COUNT, col)\n}\n\n\nfunc Date(col Columnar) ColumnElem {\n\treturn Function(DATE, col)\n}\n\n\n\nfunc DatePart(part string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(\n\t\tFuncClause{Name: DATEPART},\n\t).AddOperator(\n\t\tArrayClause{clauses: []Clause{String(part)}, post: true, sep: \", \"},\n\t)\n}\n\n\nfunc Max(col Columnar) ColumnElem {\n\treturn Function(MAX, col)\n}\n\n\nfunc Min(col Columnar) ColumnElem {\n\treturn Function(MIN, col)\n}\n\n\nfunc StdDev(col Columnar) ColumnElem {\n\treturn Function(STDDEV, col)\n}\n\n\nfunc Sum(col Columnar) ColumnElem {\n\treturn Function(SUM, col)\n}\n\n\n\n\nfunc Variance(col Columnar) ColumnElem ", "output": "{\n\treturn Function(VARIANCE, col)\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/api/extensions/v1beta1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype PodSecurityPolicyLister interface {\n\tList(selector labels.Selector) (ret []*v1beta1.PodSecurityPolicy, err error)\n\tGet(name string) (*v1beta1.PodSecurityPolicy, error)\n\tPodSecurityPolicyListerExpansion\n}\n\n\ntype podSecurityPolicyLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewPodSecurityPolicyLister(indexer cache.Indexer) PodSecurityPolicyLister {\n\treturn &podSecurityPolicyLister{indexer: indexer}\n}\n\n\n\n\n\nfunc (s *podSecurityPolicyLister) Get(name string) (*v1beta1.PodSecurityPolicy, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"podsecuritypolicy\"), name)\n\t}\n\treturn obj.(*v1beta1.PodSecurityPolicy), nil\n}\n\nfunc (s *podSecurityPolicyLister) List(selector labels.Selector) (ret []*v1beta1.PodSecurityPolicy, err error) ", "output": "{\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.PodSecurityPolicy))\n\t})\n\treturn ret, err\n}"} {"input": "package api2go\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\ntype APIContextAllocatorFunc func(*API) APIContexter\n\n\ntype APIContexter interface {\n\tcontext.Context\n\tSet(key string, value interface{})\n\tGet(key string) (interface{}, bool)\n\tReset()\n}\n\n\ntype APIContext struct {\n\tkeys map[string]interface{}\n}\n\n\nfunc (c *APIContext) Set(key string, value interface{}) {\n\tif c.keys == nil {\n\t\tc.keys = make(map[string]interface{})\n\t}\n\tc.keys[key] = value\n}\n\n\nfunc (c *APIContext) Get(key string) (value interface{}, exists bool) {\n\tif c.keys != nil {\n\t\tvalue, exists = c.keys[key]\n\t}\n\treturn\n}\n\n\nfunc (c *APIContext) Reset() {\n\tc.keys = nil\n}\n\n\nfunc (c *APIContext) Deadline() (deadline time.Time, ok bool) {\n\treturn\n}\n\n\nfunc (c *APIContext) Done() <-chan struct{} {\n\treturn nil\n}\n\n\n\n\n\nfunc (c *APIContext) Value(key interface{}) interface{} {\n\tif keyAsString, ok := key.(string); ok {\n\t\tval, _ := c.Get(keyAsString)\n\t\treturn val\n\t}\n\treturn nil\n}\n\n\nvar _ APIContexter = &APIContext{}\n\n\nfunc ContextQueryParams(c *APIContext) map[string][]string {\n\tqp, ok := c.Get(\"QueryParams\")\n\tif ok == false {\n\t\tqp = make(map[string][]string)\n\t\tc.Set(\"QueryParams\", qp)\n\t}\n\treturn qp.(map[string][]string)\n}\n\nfunc (c *APIContext) Err() error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n\n\t\"restic/debug\"\n)\n\n\n\n\nfunc IsProcessBackground() bool ", "output": "{\n\tvar pid int\n\t_, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(syscall.Stdin), syscall.TIOCGPGRP, uintptr(unsafe.Pointer(&pid)))\n\n\tif err != 0 {\n\t\tdebug.Log(\"Can't check if we are in the background. Using default behaviour. Error: %s\\n\", err.Error())\n\t\treturn false\n\t}\n\n\treturn pid != syscall.Getpgrp()\n}"} {"input": "package iotdataplane_test\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/service/iotdataplane\"\n)\n\nfunc TestRequireEndpointIfRegionProvided(t *testing.T) {\n\tsvc := iotdataplane.New(&aws.Config{\n\t\tRegion: aws.String(\"mock-region\"),\n\t\tDisableParamValidation: aws.Bool(true),\n\t})\n\treq, _ := svc.GetThingShadowRequest(nil)\n\terr := req.Build()\n\n\tassert.Equal(t, \"\", svc.Endpoint)\n\tassert.Error(t, err)\n\tassert.Equal(t, aws.ErrMissingEndpoint, err)\n}\n\n\n\nfunc TestRequireEndpointUsed(t *testing.T) {\n\tsvc := iotdataplane.New(&aws.Config{\n\t\tRegion: aws.String(\"mock-region\"),\n\t\tDisableParamValidation: aws.Bool(true),\n\t\tEndpoint: aws.String(\"https://endpoint\"),\n\t})\n\treq, _ := svc.GetThingShadowRequest(nil)\n\terr := req.Build()\n\n\tassert.Equal(t, \"https://endpoint\", svc.Endpoint)\n\tassert.NoError(t, err)\n}\n\nfunc TestRequireEndpointIfNoRegionProvided(t *testing.T) ", "output": "{\n\tsvc := iotdataplane.New(&aws.Config{\n\t\tRegion: aws.String(\"\"),\n\t\tDisableParamValidation: aws.Bool(true),\n\t})\n\treq, _ := svc.GetThingShadowRequest(nil)\n\terr := req.Build()\n\n\tassert.Equal(t, \"\", svc.Endpoint)\n\tassert.Error(t, err)\n\tassert.Equal(t, aws.ErrMissingEndpoint, err)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\n\n\nfunc keyExistsIface(m *map[string]interface{}, key string) bool {\n\t_, ok := (*m)[key]\n\treturn ok\n}\nfunc keyExistsInt(m *map[string]int, key string) bool {\n\t_, ok := (*m)[key]\n\treturn ok\n}\nfunc keyExistsStr(m *map[string]string, key string) bool {\n\t_, ok := (*m)[key]\n\treturn ok\n}\n\n\n\n\n\n\nfunc setInMap(m interface{}, path []string, newVal interface{}) (interface{}, error) {\n\tif len(path) == 0 {\n\t\treturn newVal, nil\n\t}\n\n\tkey := path[0]\n\ttermErr := fmt.Errorf(\"path terminates early at %s\", key)\n\trem := path[1:]\n\n\tval := reflect.ValueOf(m)\n\tswitch val.Kind() {\n\tcase reflect.Map:\n\t\tkeys := val.MapKeys()\n\t\tfound := false\n\t\tfor _, k := range keys {\n\t\t\tif reflect.DeepEqual(k.Interface(), key) {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\treturn nil, termErr\n\t\t}\n\t\tsubMap := val.MapIndex(reflect.ValueOf(key))\n\t\tnewSubMap, err := setInMap(subMap.Interface(), rem, newVal)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tval.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(newSubMap))\n\t\treturn val.Interface(), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"value at path %s is unsupported type %T\", key, m)\n\t}\n}\n\nfunc noKeyErr(key string) error ", "output": "{\n\treturn fmt.Errorf(\"no key %s found\", key)\n}"} {"input": "package leet_20\n\ntype Stack []byte\n\nfunc (s *Stack) Pop() byte {\n\tc := s.Top()\n\tlength := len(*s)\n\tif length <= 1 {\n\t\t*s = nil\n\t} else {\n\t\t*s = (*s)[:length-1]\n\t}\n\treturn c\n}\n\nfunc (s *Stack) Empty() bool {\n\treturn nil == s || *s == nil || len(*s) == 0\n}\n\nfunc (s *Stack) Push(x byte) {\n\t*s = append(*s, x)\n}\n\nfunc (s *Stack) Top() byte {\n\tlength := len(*s)\n\tif 0 == length {\n\t\treturn 0\n\t}\n\treturn (*s)[length-1]\n}\n\nfunc (s *Stack) String() string {\n\treturn string(*s)\n}\n\nfunc match(a, b byte) bool {\n\tif a == '[' && b == ']' {\n\t\treturn true\n\t}\n\tif a == '(' && b == ')' {\n\t\treturn true\n\t}\n\tif a == '{' && b == '}' {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc isValid(s string) bool ", "output": "{\n\tarr := []byte(s)\n\tstack := new(Stack)\n\tfor _, c := range arr {\n\t\tswitch c {\n\t\tcase '[', '{', '(':\n\t\t\tstack.Push(c)\n\t\t\tcontinue\n\t\t}\n\t\ttop := stack.Top()\n\t\tif match(top, c) {\n\t\t\tstack.Pop()\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn stack.Empty()\n}"} {"input": "package cabf_br\n\n\n\nimport (\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/util\"\n)\n\ntype CertPolicyOVRequiresProvinceOrLocal struct{}\n\n\n\nfunc init() {\n\tlint.RegisterLint(&lint.Lint{\n\t\tName: \"e_cert_policy_ov_requires_province_or_locality\",\n\t\tDescription: \"If certificate policy 2.23.140.1.2.2 is included, localityName or stateOrProvinceName MUST be included in subject\",\n\t\tCitation: \"BRs: 7.1.6.4\",\n\t\tSource: lint.CABFBaselineRequirements,\n\t\tEffectiveDate: util.CABEffectiveDate,\n\t\tLint: &CertPolicyOVRequiresProvinceOrLocal{},\n\t})\n}\n\n\n\nfunc (l *CertPolicyOVRequiresProvinceOrLocal) CheckApplies(cert *x509.Certificate) bool {\n\treturn util.IsSubscriberCert(cert) && util.SliceContainsOID(cert.PolicyIdentifiers, util.BROrganizationValidatedOID)\n}\n\nfunc (l *CertPolicyOVRequiresProvinceOrLocal) Execute(cert *x509.Certificate) *lint.LintResult {\n\tvar out lint.LintResult\n\tif util.TypeInName(&cert.Subject, util.LocalityNameOID) || util.TypeInName(&cert.Subject, util.StateOrProvinceNameOID) {\n\t\tout.Status = lint.Pass\n\t} else {\n\t\tout.Status = lint.Error\n\t}\n\treturn &out\n}\n\nfunc (l *CertPolicyOVRequiresProvinceOrLocal) Initialize() error ", "output": "{\n\treturn nil\n}"} {"input": "package goqueryja\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/PuerkitoBio/goquery\"\n\t\"golang.org/x/text/encoding/japanese\"\n\t\"golang.org/x/text/transform\"\n)\n\n\n\nfunc NewUTF8Reader(r io.Reader, encoding string) (io.Reader, error) {\n\tswitch strings.ToLower(encoding) {\n\tcase \"utf-8\":\n\t\treturn r, nil\n\tcase \"euc-jp\":\n\t\treturn transform.NewReader(r, japanese.EUCJP.NewDecoder()), nil\n\tcase \"shift_jis\":\n\t\treturn transform.NewReader(r, japanese.ShiftJIS.NewDecoder()), nil\n\tcase \"iso-2022-jp\":\n\t\treturn transform.NewReader(r, japanese.ISO2022JP.NewDecoder()), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported encoding: %s\", encoding)\n\t}\n}\n\nfunc GetResponseEncoding(res *http.Response) string {\n\tcontentType := res.Header.Get(\"Content-Type\")\n\tcontentTypeLower := strings.ToLower(contentType)\n\tif index := strings.Index(contentTypeLower, \"charset=\"); index != -1 {\n\t\treturn contentType[index+len(\"charset=\"):]\n\t} else {\n\t\treturn \"\"\n\t}\n}\n\nfunc NewDocument(url_ string) (*goquery.Document, error) ", "output": "{\n\tres, err := http.Get(url_)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tencoding := GetResponseEncoding(res)\n\treader, err := NewUTF8Reader(res.Body, encoding)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn goquery.NewDocumentFromReader(reader)\n}"} {"input": "package commands\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/pivotal-cf/jhanda\"\n\t\"github.com/pivotal-cf/om/api\"\n)\n\ntype InstallationLog struct {\n\tservice installationLogService\n\tlogger logger\n\tOptions struct {\n\t\tId int `long:\"id\" required:\"true\" description:\"id of the installation to retrieve logs for\"`\n\t}\n}\n\n\ntype installationLogService interface {\n\tGetInstallationLogs(id int) (api.InstallationsServiceOutput, error)\n}\n\nfunc NewInstallationLog(service installationLogService, logger logger) InstallationLog {\n\treturn InstallationLog{\n\t\tservice: service,\n\t\tlogger: logger,\n\t}\n}\n\nfunc (i InstallationLog) Execute(args []string) error {\n\tif _, err := jhanda.Parse(&i.Options, args); err != nil {\n\t\treturn fmt.Errorf(\"could not parse installation-log flags: %s\", err)\n\t}\n\n\toutput, err := i.service.GetInstallationLogs(i.Options.Id)\n\tif err != nil {\n\t\treturn err\n\t}\n\ti.logger.Print(output.Logs)\n\treturn nil\n}\n\n\n\nfunc (i InstallationLog) Usage() jhanda.Usage ", "output": "{\n\treturn jhanda.Usage{\n\t\tDescription: \"This authenticated command retrieves the logs for a given installation.\",\n\t\tShortDescription: \"output installation logs\",\n\t\tFlags: i.Options,\n\t}\n}"} {"input": "package flags\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\ntype Traffic struct {\n\tRevisionsPercentages []string\n\tRevisionsTags []string\n\tUntagRevisions []string\n}\n\nfunc (t *Traffic) Add(cmd *cobra.Command) {\n\tcmd.Flags().StringSliceVar(&t.RevisionsPercentages,\n\t\t\"traffic\",\n\t\tnil,\n\t\t\"Set traffic distribution (format: --traffic revisionRef=percent) where revisionRef can be a revision or a tag or '@latest' string \"+\n\t\t\t\"representing latest ready revision. This flag can be given multiple times with percent summing up to 100%.\")\n\n\tcmd.Flags().StringSliceVar(&t.RevisionsTags,\n\t\t\"tag\",\n\t\tnil,\n\t\t\"Set tag (format: --tag revisionRef=tagName) where revisionRef can be a revision or '@latest' string representing latest ready revision. \"+\n\t\t\t\"This flag can be specified multiple times.\")\n\n\tcmd.Flags().StringSliceVar(&t.UntagRevisions,\n\t\t\"untag\",\n\t\tnil,\n\t\t\"Untag revision (format: --untag tagName). This flag can be specified multiple times.\")\n}\n\nfunc (t *Traffic) PercentagesChanged(cmd *cobra.Command) bool {\n\treturn cmd.Flags().Changed(\"traffic\")\n}\n\nfunc (t *Traffic) TagsChanged(cmd *cobra.Command) bool {\n\treturn cmd.Flags().Changed(\"tag\") || cmd.Flags().Changed(\"untag\")\n}\n\n\n\nfunc (t *Traffic) Changed(cmd *cobra.Command) bool ", "output": "{\n\treturn t.PercentagesChanged(cmd) || t.TagsChanged(cmd)\n}"} {"input": "package glu\n\nvar _Perspective func(fovy, aspect, near, far float64)\nvar _LookAt func(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ float64)\n\nfunc RegisterPerspective(fn func(fovy, aspect, near, far float64)) {\n\t_Perspective = fn\n}\n\nfunc RegisterLookAt(fn func(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ float64)) {\n\t_LookAt = fn\n}\n\nfunc Perspective(fovy, aspect, near, far float64) {\n\tif _Perspective == nil {\n\t\tpanic(\"Please register a Perspective with glu.RegisterPespective\")\n\t}\n\n\t_Perspective(fovy, aspect, near, far)\n}\n\n\n\nfunc LookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ float64) ", "output": "{\n\tif _LookAt == nil {\n\t\tpanic(\"Please register a LookAt with glu.RegisterLookAt\")\n\t}\n\n\t_LookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ)\n}"} {"input": "package util\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\nvar rootPath = getCutoRoot()\n\nfunc getCutoRoot() string {\n\td := os.Getenv(\"CUTOROOT\")\n\tif len(d) == 0 {\n\t\tpanic(\"Not setting environment argument $CUTOROOT\")\n\t}\n\treturn d\n}\n\n\nfunc GetRootPath() string {\n\treturn rootPath\n}\n\n\n\n\nfunc GetCurrentPath() string ", "output": "{\n\treturn filepath.Join(rootPath, \"bin\")\n}"} {"input": "package wraps\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-on/wrap\"\n)\n\n\n\ntype Catcher interface {\n\tCatch(recovered interface{}, w http.ResponseWriter, r *http.Request)\n}\n\n\ntype CatchFunc func(recovered interface{}, w http.ResponseWriter, r *http.Request)\n\n\nfunc (c CatchFunc) Catch(recovered interface{}, w http.ResponseWriter, r *http.Request) {\n\tc(recovered, w, r)\n}\n\n\n\n\nfunc (c CatchFunc) ServeHTTPNext(next http.Handler, wr http.ResponseWriter, req *http.Request) {\n\tchecked := wrap.NewPeek(wr, func(ck *wrap.Peek) bool {\n\t\tck.FlushHeaders()\n\t\tck.FlushCode()\n\t\treturn true\n\t})\n\n\tdefer func() {\n\t\tif p := recover(); p != nil {\n\t\t\tc(p, wr, req)\n\t\t} else {\n\t\t\tchecked.FlushMissing()\n\t\t}\n\t}()\n\n\tnext.ServeHTTP(checked, req)\n}\n\n\nfunc (c CatchFunc) Wrap(next http.Handler) http.Handler {\n\treturn wrap.NextHandler(c).Wrap(next)\n}\n\n\n\n\nfunc Catch(c Catcher) wrap.Wrapper ", "output": "{\n\treturn CatchFunc(c.Catch)\n}"} {"input": "package yaml\n\nimport (\n\t\"fmt\"\n)\n\nfunc (this *Job) Name() JobKey {\n\treturn this.name\n}\n\nfunc (this *Job) Validate(c Context) error {\n\treturn nil\n}\n\nfunc (this *Job) InDesiredState(c Context) (bool, error) {\n\treturn true, nil\n}\n\nfunc (this *Job) Prepare(c Context) error {\n\treturn nil\n}\n\n\n\nfunc (this *Job) Finish(c Context) error {\n\treturn nil\n}\n\nfunc (this *Job) get_task() *task {\n\tif this.task == nil {\n\t\tthis.task = alloc_task(this)\n\t\tthis.task.description = fmt.Sprintf(\"Job[%s]\", this.name)\n\n\t\tfor _, container := range this.container_instances {\n\t\t\tthis.task.DependsOn(container.get_task())\n\t\t}\n\t}\n\treturn this.task\n}\n\nfunc (this *Job) Execute(c Context) error ", "output": "{\n\tc.log(\"Executing Job %s\", this.name)\n\n\treturn nil\n}"} {"input": "package header\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\t\"github.com/google/martian\"\n\t\"github.com/google/martian/parse\"\n)\n\nfunc init() {\n\tparse.Register(\"header.Modifier\", modifierFromJSON)\n}\n\ntype modifier struct {\n\tname, value string\n}\n\ntype modifierJSON struct {\n\tName string `json:\"name\"`\n\tValue string `json:\"value\"`\n\tScope []parse.ModifierType `json:\"scope\"`\n}\n\n\n\n\n\nfunc (m *modifier) ModifyResponse(res *http.Response) error {\n\tres.Header.Set(m.name, m.value)\n\n\treturn nil\n}\n\n\n\n\nfunc NewModifier(name, value string) martian.RequestResponseModifier {\n\treturn &modifier{\n\t\tname: http.CanonicalHeaderKey(name),\n\t\tvalue: value,\n\t}\n}\n\n\n\n\n\n\n\n\n\n\nfunc modifierFromJSON(b []byte) (*parse.Result, error) {\n\tmsg := &modifierJSON{}\n\tif err := json.Unmarshal(b, msg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmodifier := NewModifier(msg.Name, msg.Value)\n\n\treturn parse.NewResult(modifier, msg.Scope)\n}\n\nfunc (m *modifier) ModifyRequest(req *http.Request) error ", "output": "{\n\tif m.name == \"Host\" {\n\t\treq.Host = m.value\n\t} else {\n\t\treq.Header.Set(m.name, m.value)\n\t}\n\n\treturn nil\n}"} {"input": "package vt10x\n\nimport (\n\texpect \"github.com/Netflix/go-expect\"\n\t\"github.com/kr/pty\"\n)\n\n\n\n\n\n\nfunc NewVT10XConsole(opts ...expect.ConsoleOpt) (*expect.Console, *State, error) ", "output": "{\n\tptm, pts, err := pty.Open()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar state State\n\tterm, err := Create(&state, pts)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tc, err := expect.NewConsole(append(opts, expect.WithStdin(ptm), expect.WithStdout(term), expect.WithCloser(pts, ptm, term))...)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn c, &state, nil\n}"} {"input": "package mysql\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\n\n\n\n\ntype GTID interface {\n\tString() string\n\n\tFlavor() string\n\n\tSourceServer() interface{}\n\n\tSequenceNumber() interface{}\n\n\tSequenceDomain() interface{}\n\n\tGTIDSet() GTIDSet\n}\n\n\nvar gtidParsers = make(map[string]func(string) (GTID, error))\n\n\nfunc ParseGTID(flavor, value string) (GTID, error) {\n\tparser := gtidParsers[flavor]\n\tif parser == nil {\n\t\treturn nil, fmt.Errorf(\"parse error: unknown GTID flavor %#v\", flavor)\n\t}\n\treturn parser(value)\n}\n\n\nfunc MustParseGTID(flavor, value string) GTID {\n\tgtid, err := ParseGTID(flavor, value)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn gtid\n}\n\n\n\n\nfunc EncodeGTID(gtid GTID) string {\n\tif gtid == nil {\n\t\treturn \"\"\n\t}\n\n\treturn fmt.Sprintf(\"%s/%s\", gtid.Flavor(), gtid.String())\n}\n\n\n\n\n\n\nfunc MustDecodeGTID(s string) GTID {\n\tgtid, err := DecodeGTID(s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn gtid\n}\n\nfunc DecodeGTID(s string) (GTID, error) ", "output": "{\n\tif s == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tparts := strings.SplitN(s, \"/\", 2)\n\tif len(parts) != 2 {\n\t\treturn ParseGTID(\"\", s)\n\t}\n\treturn ParseGTID(parts[0], parts[1])\n}"} {"input": "package pry\n\nimport (\n\t\"io/ioutil\"\n\t\"regexp\"\n\t\"testing\"\n)\n\n\n\n\nfunc TestHighlightSafe(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\tfileBytes, err := ioutil.ReadFile(\"../example/file/file.go\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tfileStr := (string)(fileBytes)\n\thighlight := Highlight(fileStr)\n\n\tr, err := regexp.Compile(\"\\\\x1b\\\\[(.*?)m\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\ts := r.ReplaceAllLiteralString(highlight, \"\")\n\n\tif s != fileStr {\n\t\tt.Error(\"Highlighting has changed the code!\")\n\t}\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateDbHomeRequest struct {\n\n\tCreateDbHomeWithDbSystemIdDetails CreateDbHomeBase `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateDbHomeRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateDbHomeRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CreateDbHomeRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype CreateDbHomeResponse struct {\n\n\tRawResponse *http.Response\n\n\tDbHome `presentIn:\"body\"`\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateDbHomeResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateDbHomeResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateDbHomeRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package api\n\nimport (\n\t\"io\"\n)\n\n\n\ntype Snapshot struct {\n\tc *Client\n}\n\n\nfunc (c *Client) Snapshot() *Snapshot {\n\treturn &Snapshot{c}\n}\n\n\n\n\n\n\n\n\nfunc (s *Snapshot) Restore(q *WriteOptions, in io.Reader) error {\n\tr := s.c.newRequest(\"PUT\", \"/v1/snapshot\")\n\tr.body = in\n\tr.header.Set(\"Content-Type\", \"application/octet-stream\")\n\tr.setWriteOptions(q)\n\t_, _, err := requireOK(s.c.doRequest(r))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (s *Snapshot) Save(q *QueryOptions) (io.ReadCloser, *QueryMeta, error) ", "output": "{\n\tr := s.c.newRequest(\"GET\", \"/v1/snapshot\")\n\tr.setQueryOptions(q)\n\n\trtt, resp, err := requireOK(s.c.doRequest(r))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tqm := &QueryMeta{}\n\tparseQueryMeta(resp, qm)\n\tqm.RequestTime = rtt\n\treturn resp.Body, qm, nil\n}"} {"input": "package MySQLProtocol\n\ntype Packet_SSLRequest struct {\n\tPacket\n\n\tcapability uint32\n\tmax_packet_size uint32\n\tusername string\n\tcharacter_set uint8\n}\n\n\n\nfunc (packet Packet_SSLRequest) ToPacket(context Context) (data []byte) {\n\tsize := packet.GetPacketSize(context)\n\n\tdata = make([]byte, 0, size+4)\n\n\tdata = append(data, BuildFixedLengthInteger3(uint32(size))...)\n\tdata = append(data, BuildFixedLengthInteger1(packet.sequence_id)...)\n\n\tdata = append(data, BuildFixedLengthInteger4(packet.capability)...)\n\tdata = append(data, BuildFixedLengthInteger4(packet.max_packet_size)...)\n\tdata = append(data, BuildFixedLengthInteger1(packet.character_set)...)\n\tdata = append(data, BuildFixedLengthString(\"\", 23)...)\n\n\treturn data\n}\n\nfunc (packet *Packet_SSLRequest) FromPacket(context Context, data Proto) {\n\tdata.GetFixedLengthInteger3()\n\tpacket.sequence_id = data.GetFixedLengthInteger1()\n\n\tpacket.capability = data.GetFixedLengthInteger4()\n\tpacket.max_packet_size = data.GetFixedLengthInteger4()\n\tpacket.character_set = data.GetFixedLengthInteger1()\n\tdata.GetFixedLengthString(23)\n}\n\nfunc (packet Packet_SSLRequest) GetPacketSize(context Context) (size uint64) ", "output": "{\n\tsize += 4\n\tsize += 4\n\tsize += 1\n\tsize += 23\n\treturn size\n}"} {"input": "package ast\n\nimport \"github.com/orktes/orlang/scanner\"\n\ntype UnaryExpression struct {\n\tExpression\n\tOperator scanner.Token\n\tPostfix bool\n}\n\n\n\nfunc (u *UnaryExpression) EndPos() Position {\n\tif u.Postfix {\n\t\treturn EndPositionFromToken(u.Operator)\n\t}\n\treturn u.Expression.EndPos()\n}\n\nfunc (_ *UnaryExpression) exprNode() {}\n\nfunc (u *UnaryExpression) StartPos() Position ", "output": "{\n\tif u.Postfix {\n\t\treturn u.Expression.StartPos()\n\t}\n\treturn StartPositionFromToken(u.Operator)\n}"} {"input": "package test\n\nimport \"github.com/control-center/serviced/commons/docker\"\nimport \"github.com/stretchr/testify/mock\"\n\ntype MockEventMonitor struct {\n\tmock.Mock\n}\n\nvar _ docker.EventMonitor = &MockEventMonitor{}\n\n\nfunc (_m *MockEventMonitor) Subscribe(ID string) (*docker.Subscription, error) {\n\tret := _m.Called(ID)\n\n\tvar r0 *docker.Subscription\n\tif rf, ok := ret.Get(0).(func(string) *docker.Subscription); ok {\n\t\tr0 = rf(ID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*docker.Subscription)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(ID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *MockEventMonitor) Close() error {\n\tret := _m.Called()\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func() error); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\n\nfunc (_m *MockEventMonitor) IsActive() bool ", "output": "{\n\tret := _m.Called()\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func() bool); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\treturn r0\n}"} {"input": "package zap\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\tjaeger \"github.com/uber/jaeger-client-go\"\n\n\topentracing \"github.com/opentracing/opentracing-go\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n)\n\n\n\n\n\n\n\nfunc Trace(ctx context.Context) zapcore.Field {\n\tif ctx == nil {\n\t\treturn zap.Skip()\n\t}\n\treturn zap.Object(\"trace\", trace{ctx})\n}\n\ntype trace struct {\n\tctx context.Context\n}\n\n\n\nfunc (t trace) MarshalLogObject(enc zapcore.ObjectEncoder) error ", "output": "{\n\tspan := opentracing.SpanFromContext(t.ctx)\n\tif span == nil {\n\t\treturn nil\n\t}\n\tj, ok := span.Context().(jaeger.SpanContext)\n\tif !ok {\n\t\treturn nil\n\t}\n\tif !j.IsValid() {\n\t\treturn fmt.Errorf(\"invalid span: %v\", j.SpanID())\n\t}\n\tenc.AddString(\"span\", j.SpanID().String())\n\tenc.AddString(\"trace\", j.TraceID().String())\n\treturn nil\n}"} {"input": "package github\n\nimport \"fmt\"\n\n\ntype Blob struct {\n\tContent *string `json:\"content,omitempty\"`\n\tEncoding *string `json:\"encoding,omitempty\"`\n\tSHA *string `json:\"sha,omitempty\"`\n\tSize *int `json:\"size,omitempty\"`\n\tURL *string `json:\"url,omitempty\"`\n}\n\n\n\n\n\n\n\n\n\nfunc (s *GitService) CreateBlob(owner string, repo string, blob *Blob) (*Blob, *Response, error) {\n\tu := fmt.Sprintf(\"repos/%v/%v/git/blobs\", owner, repo)\n\treq, err := s.client.NewRequest(\"POST\", u, blob)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tt := new(Blob)\n\tresp, err := s.client.Do(req, t)\n\treturn t, resp, err\n}\n\nfunc (s *GitService) GetBlob(owner string, repo string, sha string) (*Blob, *Response, error) ", "output": "{\n\tu := fmt.Sprintf(\"repos/%v/%v/git/blobs/%v\", owner, repo, sha)\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tblob := new(Blob)\n\tresp, err := s.client.Do(req, blob)\n\treturn blob, resp, err\n}"} {"input": "package token\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/PuerkitoBio/goquery\"\n)\n\n\nfunc GetToken(client *http.Client, urlString string) (string, error) {\n\treq, _ := http.NewRequest(\"GET\", urlString, nil)\n\tres, err := client.Do(req)\n\tdefer func() {\n\t\tif res.Body != nil {\n\t\t\tres.Body.Close()\n\t\t}\n\t}()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn parseToken(res)\n}\n\n\n\nfunc parseToken(res *http.Response) (string, error) ", "output": "{\n\tdoc, err := goquery.NewDocumentFromReader(res.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar token string\n\tdoc.Find(\"input[name=gintoken]\").Each(func(_ int, s *goquery.Selection) {\n\t\tif val, ok := s.Attr(\"value\"); ok {\n\t\t\ttoken = val\n\t\t}\n\t})\n\treturn token, nil\n}"} {"input": "package service\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetServiceIDOKCode int = 200\n\n\ntype GetServiceIDOK struct {\n\n\tPayload *models.Service `json:\"body,omitempty\"`\n}\n\n\nfunc NewGetServiceIDOK() *GetServiceIDOK {\n\n\treturn &GetServiceIDOK{}\n}\n\n\nfunc (o *GetServiceIDOK) WithPayload(payload *models.Service) *GetServiceIDOK {\n\to.Payload = payload\n\treturn o\n}\n\n\n\n\n\nfunc (o *GetServiceIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\n\nconst GetServiceIDNotFoundCode int = 404\n\n\ntype GetServiceIDNotFound struct {\n}\n\n\nfunc NewGetServiceIDNotFound() *GetServiceIDNotFound {\n\n\treturn &GetServiceIDNotFound{}\n}\n\n\nfunc (o *GetServiceIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc (o *GetServiceIDOK) SetPayload(payload *models.Service) ", "output": "{\n\to.Payload = payload\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListLocalPeeringGatewaysRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tVcnId *string `mandatory:\"false\" contributesTo:\"query\" name:\"vcnId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListLocalPeeringGatewaysRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListLocalPeeringGatewaysRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request ListLocalPeeringGatewaysRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ListLocalPeeringGatewaysRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListLocalPeeringGatewaysResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []LocalPeeringGateway `presentIn:\"body\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ListLocalPeeringGatewaysResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response ListLocalPeeringGatewaysResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package db\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"github.com/jmoiron/sqlx\"\n\t\"gopkg.in/yaml.v1\"\n)\n\n\ntype Configs map[string]*Config\n\n\nfunc (cs Configs) Open(env string) (*sqlx.DB, error) {\n\tconfig, ok := cs[env]\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\treturn config.Open()\n}\n\n\ntype Config struct {\n\tDatasource string `yaml:\"datasource\"`\n}\n\n\nfunc (c *Config) DSN() string {\n\treturn c.Datasource\n}\n\n\n\nfunc (c *Config) Open() (*sqlx.DB, error) {\n\treturn sqlx.Open(\"mysql\", c.DSN())\n}\n\n\n\n\n\nfunc NewConfigs(r io.Reader) (Configs, error) {\n\tb, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar configs Configs\n\tif err = yaml.Unmarshal(b, &configs); err != nil {\n\t\treturn nil, err\n\t}\n\treturn configs, nil\n}\n\nfunc NewConfigsFromFile(path string) (Configs, error) ", "output": "{\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treturn NewConfigs(f)\n}"} {"input": "package common\n\nimport \"github.com/juju/juju/state\"\n\nvar (\n\tMachineJobFromParams = machineJobFromParams\n\tValidateNewFacade = validateNewFacade\n\tWrapNewFacade = wrapNewFacade\n\tNilFacadeRecord = facadeRecord{}\n\tEnvtoolsFindTools = &envtoolsFindTools\n)\n\ntype Patcher interface {\n\tPatchValue(dest, value interface{})\n}\n\n\n\n\n\n\ntype Versions versions\n\nfunc DescriptionFromVersions(name string, vers Versions) FacadeDescription {\n\treturn descriptionFromVersions(name, versions(vers))\n}\n\nfunc NewMultiNotifyWatcher(w ...state.NotifyWatcher) state.NotifyWatcher {\n\tmw := newMultiNotifyWatcher(w...)\n\treturn mw\n}\n\nfunc SanitizeFacades(patcher Patcher) ", "output": "{\n\temptyFacades := &FacadeRegistry{}\n\tpatcher.PatchValue(&Facades, emptyFacades)\n}"} {"input": "package blocker\n\nimport \"sort\"\n\ntype sources []string\n\nfunc (s *sources) Add(source string) {\n\tn := sort.SearchStrings(*s, source)\n\n\tif n < len(*s) && (*s)[n] == source {\n\t\treturn\n\t}\n\n\t*s = append(*s, \"\")\n\tcopy((*s)[n+1:], (*s)[n:])\n\t(*s)[n] = source\n}\n\n\n\nfunc (s *sources) Has(source string) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tn := sort.SearchStrings(*s, source)\n\n\tif n < len(*s) && (*s)[n] == source {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (s *sources) Len() int {\n\treturn len(*s)\n}\n\nfunc newSources(s ...string) *sources {\n\tret := sources(s)\n\treturn &ret\n}\n\nfunc (s *sources) Remove(source string) bool ", "output": "{\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tn := sort.SearchStrings(*s, source)\n\n\tif n < len(*s) && (*s)[n] == source {\n\t\t*s = append((*s)[:n], (*s)[n+1:]...)\n\t\treturn true\n\t}\n\n\treturn false\n}"} {"input": "package ast\n\n\ntype AsmLabelAttr struct {\n\tAddr Address\n\tPos Position\n\tInherited bool\n\tFunctionName string\n\tChildNodes []Node\n\tIsLiteralLabel bool\n}\n\nfunc parseAsmLabelAttr(line string) *AsmLabelAttr {\n\tgroups := groupsFromRegex(\n\t\t`<(?P.*)>\n\t\t(?P Inherited)?\n\t\t \"(?P.+)\"\n\t\t(?P IsLiteralLabel)?`,\n\t\tline,\n\t)\n\n\treturn &AsmLabelAttr{\n\t\tAddr: ParseAddress(groups[\"address\"]),\n\t\tPos: NewPositionFromString(groups[\"position\"]),\n\t\tInherited: len(groups[\"inherited\"]) > 0,\n\t\tFunctionName: groups[\"function\"],\n\t\tChildNodes: []Node{},\n\t\tIsLiteralLabel: len(groups[\"literal\"]) > 0,\n\t}\n}\n\n\n\nfunc (n *AsmLabelAttr) AddChild(node Node) {\n\tn.ChildNodes = append(n.ChildNodes, node)\n}\n\n\n\nfunc (n *AsmLabelAttr) Address() Address {\n\treturn n.Addr\n}\n\n\n\nfunc (n *AsmLabelAttr) Children() []Node {\n\treturn n.ChildNodes\n}\n\n\n\n\nfunc (n *AsmLabelAttr) Position() Position ", "output": "{\n\treturn n.Pos\n}"} {"input": "package models\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/hex\"\n\t\"time\"\n)\n\nconst (\n\tNonceBytes = 32\n)\n\ntype Nonce struct {\n\tId string `db:\"id\" json:\"-\"`\n\tExpiresAt time.Time `db:\"expires_at\" json:\"expires_at\"`\n\tNonce string `db:\"nonce\" json:\"nonce\"`\n}\n\nfunc CreateNonce() (*Nonce, error) {\n\tn, err := generate()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := &Nonce{\n\t\tExpiresAt: time.Now().Add(10 * time.Minute),\n\t\tNonce: n,\n\t}\n\terr = Db.Insert(nonce)\n\treturn nonce, err\n}\n\nfunc generate() (string, error) {\n\tb := make([]byte, NonceBytes)\n\t_, err := rand.Read(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tstr := hex.EncodeToString(b)\n\treturn string(str[:NonceBytes]), nil\n}\n\n\n\nfunc NonceValid(nonce string) bool ", "output": "{\n\tid, err := Db.SelectNullStr(\n\t\t\"select id from nonces where nonce = $1 and expires_at > $2 limit 1\",\n\t\tnonce, time.Now(),\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif !id.Valid {\n\t\treturn false\n\t}\n\n\t_, err = Db.Exec(\"delete from nonces where id=$1\", id.String)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn true\n}"} {"input": "package cloudfoundry_test\n\nimport (\n\t\"github.com/javiermanzano/goth\"\n\t\"github.com/javiermanzano/goth/providers/cloudfoundry\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc Test_Implements_Provider(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\ta.Implements((*goth.Provider)(nil), provider())\n}\n\nfunc Test_BeginAuth(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\tp := provider()\n\tsession, err := p.BeginAuth(\"test_state\")\n\ts := session.(*cloudfoundry.Session)\n\ta.NoError(err)\n\ta.Contains(s.AuthURL, \"https://cf.example.com/oauth/authorize\")\n}\n\nfunc Test_SessionFromJSON(t *testing.T) {\n\tt.Parallel()\n\ta := assert.New(t)\n\n\tp := provider()\n\tsession, err := p.UnmarshalSession(`{\"AuthURL\":\"https://cf.example.com/oauth/authorize\",\"AccessToken\":\"1234567890\"}`)\n\ta.NoError(err)\n\n\ts := session.(*cloudfoundry.Session)\n\ta.Equal(s.AuthURL, \"https://cf.example.com/oauth/authorize\")\n\ta.Equal(s.AccessToken, \"1234567890\")\n}\n\nfunc provider() *cloudfoundry.Provider {\n\treturn cloudfoundry.New(\"https://cf.example.com/\", os.Getenv(\"UAA_CLIENT_ID\"), os.Getenv(\"UAA_CLIENT_SECRET\"), \"/foo\")\n}\n\nfunc Test_New(t *testing.T) ", "output": "{\n\tt.Parallel()\n\ta := assert.New(t)\n\tp := provider()\n\n\ta.Equal(p.ClientKey, os.Getenv(\"UAA_CLIENT_ID\"))\n\ta.Equal(p.Secret, os.Getenv(\"UAA_CLIENT_SECRET\"))\n\ta.Equal(p.CallbackURL, \"/foo\")\n}"} {"input": "package challenge25\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"github.com/stripedpajamas/cryptopals/set3/challenge18\"\n)\n\nvar globalPlaintext []byte\n\nfunc init() {\n\tvar err error\n\tglobalPlaintext, err = ioutil.ReadFile(\"25_decoded.txt\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\n\nfunc TestEdit(t *testing.T) {\n\tinput := []byte(\"HELLO POTATO FACE\")\n\tkey := []byte(\"YELLOW SUBMARINE\")\n\tnonce := []byte{0, 0, 0, 0, 0, 0, 0, 0}\n\tenc := challenge18.CTR(input, key, nonce)\n\tedited := Edit(enc, key, nonce, []byte(\"TOMATO\"), 6)\n\tdec := challenge18.CTR(edited, key, nonce)\n\n\tif string(dec) != \"HELLO TOMATO FACE\" {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestEditAPI(t *testing.T) {\n\tinput := []byte(\"HELLO POTATO FACE\")\n\tenc := challenge18.CTR(input, globalKey, globalNonce)\n\tedited := EditAPI(enc, []byte(\"TOMATO\"), 6)\n\tdec := challenge18.CTR(edited, globalKey, globalNonce)\n\n\tif string(dec) != \"HELLO TOMATO FACE\" {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestRecoverPTFromAPI(t *testing.T) {\n\tenc := EncryptSecretWithCTR(globalPlaintext)\n\trecovered := RecoverPTFromAPI(enc)\n\tif !bytes.Equal(recovered, globalPlaintext) {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestEncryptSecretWithCTR(t *testing.T) ", "output": "{\n\tenc := EncryptSecretWithCTR(globalPlaintext)\n\tdec := challenge18.CTR(enc, globalKey, globalNonce)\n\n\tif !bytes.Equal(dec, globalPlaintext) {\n\t\tt.Fail()\n\t}\n}"} {"input": "package oci\n\nimport \"io/fs\"\n\n\n\n\n\ntype dirInfo struct {\n\tfileInfo fs.FileInfo\n}\n\nfunc (di dirInfo) IsDir() bool {\n\treturn di.fileInfo.IsDir()\n}\n\nfunc (di dirInfo) Type() fs.FileMode {\n\treturn di.fileInfo.Mode().Type()\n}\n\nfunc (di dirInfo) Info() (fs.FileInfo, error) {\n\treturn di.fileInfo, nil\n}\n\n\n\n\n\nfunc fileInfoToDirEntry(info fs.FileInfo) fs.DirEntry {\n\tif info == nil {\n\t\treturn nil\n\t}\n\treturn dirInfo{fileInfo: info}\n}\n\nfunc (di dirInfo) Name() string ", "output": "{\n\treturn di.fileInfo.Name()\n}"} {"input": "package iso20022\n\n\ntype AcceptedStatusReason4 struct {\n\n\tReasonCode *AcceptedReason4Choice `xml:\"RsnCd\"`\n\n\tAdditionalReasonInformation *Max210Text `xml:\"AddtlRsnInf,omitempty\"`\n}\n\nfunc (a *AcceptedStatusReason4) AddReasonCode() *AcceptedReason4Choice {\n\ta.ReasonCode = new(AcceptedReason4Choice)\n\treturn a.ReasonCode\n}\n\n\n\nfunc (a *AcceptedStatusReason4) SetAdditionalReasonInformation(value string) ", "output": "{\n\ta.AdditionalReasonInformation = (*Max210Text)(&value)\n}"} {"input": "package main\n\n\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/credentials\"\n\t\"github.com/aws/aws-sdk-go/aws/session\"\n\t\"github.com/aws/aws-sdk-go/service/s3/s3manager\"\n)\n\nfunc main() {\n\n\targs := os.Args\n\tif len(args) < 4 {\n\t\texitErrorf(\"Please provide: filename, bucket, region.\")\n\t}\n\n\tfilename := args[1]\n\tbucket := args[2]\n\tregion := args[3]\n\n\taccess_key := os.Getenv(\"S3_ACCESS_KEY\")\n\tsecret_access_key := os.Getenv(\"S3_SECRET_KEY\")\n\ttoken := \"\"\n\n\tcreds := credentials.NewStaticCredentials(access_key, secret_access_key, token)\n\tconfig := aws.NewConfig().WithRegion(region).WithCredentials(creds)\n\n\tsess := session.Must(session.NewSession(config))\n\n\tfile, err := os.Open(filename)\n\n\tif err != nil {\n\t\texitErrorf(\"Unable to open file %q, %v\", err)\n\t}\n\n\tdefer file.Close()\n\n\tuploader := s3manager.NewUploader(sess)\n\n\t_, err = uploader.Upload(&s3manager.UploadInput{\n\t\tBucket: aws.String(bucket),\n\n\t\tKey: aws.String(filename),\n\n\t\tBody: file,\n\t})\n\n\tif err != nil {\n\t\texitErrorf(\"Unable to upload %q to %q, %v\", filename, bucket, err)\n\t}\n\n\tfmt.Printf(\"Successfully uploaded %q to %q\\n\", filename, bucket)\n\n\tos.Exit(0)\n}\n\n\n\nfunc exitErrorf(msg string, args ...interface{}) ", "output": "{\n\tfmt.Fprintf(os.Stderr, msg+\"\\n\", args...)\n\tos.Exit(1)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSSecretsManagerRotationSchedule_RotationRules struct {\n\n\tAutomaticallyAfterDays int `json:\"AutomaticallyAfterDays,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) AWSCloudFormationType() string {\n\treturn \"AWS::SecretsManager::RotationSchedule.RotationRules\"\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\n\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) SetMetadata(metadata map[string]interface{}) ", "output": "{\n\tr._metadata = metadata\n}"} {"input": "package demo\n\n\nimport (\n\t\"github.com/mabetle/mgo/mdb\"\n)\n\nvar(\n\n\tDEMO_TABLE_CREATE_SQL=`\n\t\tcreate table demo_table(\n\t\t\tid int not null primary key,\n\t\t\tDemoName varchar(50) not null,\n\t\t\tDemoAge int not null\n\t\t)\n\t`\n\n\tDEMO_INSERT_SQL=`\n\t\tinsert into demo_table (id,DemoName,DemoAge)\n\t\tvalues (1,'demo', 30)\n\t`\n\n\tDEMO_INSERT_SQL2=`\n\t\tinsert into demo_table (id,DemoName,DemoAge)\n\t\tvalues (2,'demo2', 10)\n\t`\n\n\n)\n\n\n\n\nfunc InitDB(db *mdb.Sql)", "output": "{\n\tdb.Exec(\"drop table demo_table\")\n\tdb.Exec(DEMO_TABLE_CREATE_SQL)\n\tdb.Exec(DEMO_INSERT_SQL)\n\tdb.Exec(DEMO_INSERT_SQL2)\n}"} {"input": "package nacos\n\nimport (\n\t\"context\"\n\n\t\"github.com/asim/go-micro/v3/config/source\"\n\t\"github.com/nacos-group/nacos-sdk-go/v2/common/constant\"\n)\n\ntype addressKey struct{}\ntype configKey struct{}\ntype groupKey struct{}\ntype dataIdKey struct{}\ntype encoderKey struct{}\n\n\nfunc WithAddress(addrs []string) source.Option {\n\treturn func(o *source.Options) {\n\t\tif o.Context == nil {\n\t\t\to.Context = context.Background()\n\t\t}\n\t\to.Context = context.WithValue(o.Context, addressKey{}, addrs)\n\t}\n}\n\n\nfunc WithClientConfig(cc constant.ClientConfig) source.Option {\n\treturn func(o *source.Options) {\n\t\tif o.Context == nil {\n\t\t\to.Context = context.Background()\n\t\t}\n\t\to.Context = context.WithValue(o.Context, configKey{}, cc)\n\t}\n}\n\n\n\n\n\nfunc WithDataId(id string) source.Option {\n\treturn func(o *source.Options) {\n\t\tif o.Context == nil {\n\t\t\to.Context = context.Background()\n\t\t}\n\t\to.Context = context.WithValue(o.Context, dataIdKey{}, id)\n\t}\n}\n\nfunc WithGroup(g string) source.Option ", "output": "{\n\treturn func(o *source.Options) {\n\t\tif o.Context == nil {\n\t\t\to.Context = context.Background()\n\t\t}\n\t\to.Context = context.WithValue(o.Context, groupKey{}, g)\n\t}\n}"} {"input": "package tag \n\nimport \"sort\"\n\n\n\n\n\ntype Index string\n\n\nfunc (s Index) Elem(x int) string {\n\treturn string(s[x*4 : x*4+4])\n}\n\n\n\n\nfunc (s Index) Index(key []byte) int {\n\tn := len(key)\n\tindex := sort.Search(len(s)/4, func(i int) bool {\n\t\treturn cmp(s[i*4:i*4+n], key) != -1\n\t})\n\ti := index * 4\n\tif cmp(s[i:i+len(key)], key) != 0 {\n\t\treturn -1\n\t}\n\treturn index\n}\n\n\n\nfunc (s Index) Next(key []byte, x int) int {\n\tif x++; x*4 < len(s) && cmp(s[x*4:x*4+len(key)], key) == 0 {\n\t\treturn x\n\t}\n\treturn -1\n}\n\n\n\n\n\nfunc Compare(a string, b []byte) int {\n\treturn cmp(Index(a), b)\n}\n\n\n\nfunc FixCase(form string, b []byte) bool {\n\tif len(form) != len(b) {\n\t\treturn false\n\t}\n\tfor i, c := range b {\n\t\tif form[i] <= 'Z' {\n\t\t\tif c >= 'a' {\n\t\t\t\tc -= 'z' - 'Z'\n\t\t\t}\n\t\t\tif c < 'A' || 'Z' < c {\n\t\t\t\treturn false\n\t\t\t}\n\t\t} else {\n\t\t\tif c <= 'Z' {\n\t\t\t\tc += 'z' - 'Z'\n\t\t\t}\n\t\t\tif c < 'a' || 'z' < c {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tb[i] = c\n\t}\n\treturn true\n}\n\nfunc cmp(a Index, b []byte) int ", "output": "{\n\tn := len(a)\n\tif len(b) < n {\n\t\tn = len(b)\n\t}\n\tfor i, c := range b[:n] {\n\t\tswitch {\n\t\tcase a[i] > c:\n\t\t\treturn 1\n\t\tcase a[i] < c:\n\t\t\treturn -1\n\t\t}\n\t}\n\tswitch {\n\tcase len(a) < len(b):\n\t\treturn -1\n\tcase len(a) > len(b):\n\t\treturn 1\n\t}\n\treturn 0\n}"} {"input": "package common\n\nimport (\n\t\"github.com/pkg/errors\"\n)\n\ntype Backend interface {\n\tRenderAllScrolls() (numScrolls int, errors []error)\n\n\tRenderScrollsByID(ids []ID) (renderedScrollIDs []ID, errors []error)\n\n\tParse(id, doc string) Scroll\n}\n\n\n\n\n\nfunc FindMatchingScrolls(query string) ([]ID, int, error) {\n\tindex, err := OpenExistingIndex()\n\tif err != nil {\n\t\treturn []ID{}, 0, err\n\t}\n\tdefer index.Close()\n\n\tnewQuery := translatePlusMinusTildePrefixes(query)\n\tsearchResults, err := performQuery(index, newQuery)\n\ttotalMatches := int(searchResults.Total)\n\tif err != nil {\n\t\tif err.Error() == \"syntax error\" {\n\t\t\terr = errors.Wrapf(err, \"invalid query string: '%v'\", newQuery)\n\t\t} else {\n\t\t\terr = errors.Wrap(err, \"perform query\")\n\t\t}\n\t\treturn []ID{}, totalMatches, err\n\t}\n\n\tvar ids []ID\n\tfor _, match := range searchResults.Hits {\n\t\tid := ID(match.ID)\n\t\tids = append(ids, id)\n\t}\n\n\treturn ids, totalMatches, nil\n}\n\n\n\nfunc ComputeStatistics() (Statistics, error) {\n\treturn computeStatistics()\n}\n\nfunc LoadScrolls(b Backend, ids []ID) ([]Scroll, error) {\n\tresult := make([]Scroll, len(ids))\n\tfor i, id := range ids {\n\t\tscroll, err := loadAndParseScrollContentByID(b, id)\n\t\tif err != nil {\n\t\t\treturn result, err\n\t\t}\n\t\tresult[i] = scroll\n\t}\n\treturn result, nil\n}\n\nfunc UpdateIndex(b Backend) error ", "output": "{\n\treturn updateIndex(b)\n}"} {"input": "package update\n\nimport (\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/emicklei/go-restful/log\"\n\t\"github.com/kubernetes-incubator/apiserver-builder/cmd/apiserver-boot/boot/init_repo\"\n)\n\nvar vendorCmd = &cobra.Command{\n\tUse: \"vendor\",\n\tShort: \"Update the vendor packages managed by apiserver-builder.\",\n\tLong: `Update the vendor packages managed by apiserver-builder.`,\n\tExample: `# Replace the vendor packages managed by apiserver-builder with versions for the current install.\napiserver-boot update vendor\n`,\n\tRun: RunUpdateVendor,\n}\n\nfunc AddUpdateVendorCmd(cmd *cobra.Command) {\n\tcmd.AddCommand(vendorCmd)\n}\n\n\n\nfunc RunUpdateVendor(cmd *cobra.Command, args []string) ", "output": "{\n\tinit_repo.Update = true\n\tlog.Printf(\"Replacing vendored libraries managed by apiserver-builder with the current version.\")\n\tinit_repo.CopyGlide()\n}"} {"input": "package parser\n\ntype sField struct {\n\tName string\n\tType string\n\tTag string\n\tStruct sStruct\n\tInitialName string\n\n\tattr bool\n\tpointer bool\n\tarray bool\n\trequired bool\n\tnillable bool\n}\n\ntype mapofFields map[string]sField\n\nfunc (m mapofFields) add(i string, s sField) bool {\n\tif i == \"\" || s.Type == \"\" {\n\t\treturn false\n\t}\n\n\ts.resolveType()\n\ts.resolveTag()\n\ts.resolveName(i)\n\tm[s.Name] = s\n\n\treturn true\n}\n\n\n\nfunc (s *sField) resolveType() {\n\tif s.nillable && s.required {\n\t\ts.Type = toGoType(makeUnexported(lintName(removeNS(s.Type + \"ReqNil\"))))\n\t\treturn\n\t}\n\n\ttn := makeUnexported(lintName(removeNS(s.Type)))\n\tif s.array {\n\t\ts.Type = \"[]\" + toGoType(tn)\n\t\treturn\n\t}\n\tif s.pointer {\n\t\ts.Type = toGoPointerType(tn)\n\t\treturn\n\t}\n\ts.Type = toGoPointerType(tn)\n}\n\nfunc (s *sField) resolveTag() {\n\tif s.Name == \"\" {\n\t\treturn\n\t}\n\n\tif s.attr {\n\t\ts.Tag = \"`\" + `xml:\"` + s.Name + `,attr\"` + \"`\"\n\t\treturn\n\t}\n\n\ts.Tag = \"`\" + `xml:\"` + s.Name + `\"` + \"`\"\n}\n\nfunc (s *sField) resolveName(i string) ", "output": "{\n\tif s.Name == \"\" {\n\t\treturn\n\t}\n\ts.InitialName = makeExported(normalize(removeNS(i)))\n\ts.Name = makeExported(lintName(normalize(removeNS(i))))\n}"} {"input": "package gostatic\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n)\n\nconst (\n\tPre = 1 << iota\n\tHidden\n\tPost\n)\n\ntype Processor interface {\n\tProcess(page *Page, args []string) error\n\tDescription() string\n\tMode() int\n}\n\n\n\n\n\n\n\nfunc (s *Site) ProcessorSummary() {\n\tkeys := make([]string, 0, len(s.Processors))\n\tfor k := range s.Processors {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\n\tfor _, k := range keys {\n\t\tp := s.Processors[k]\n\t\tif p.Mode()&Hidden != 0 {\n\t\t\tcontinue\n\t\t}\n\t\tpre := \"\"\n\t\tif p.Mode()&Pre != 0 {\n\t\t\tpre = \"(preprocessor)\"\n\t\t}\n\t\tfmt.Printf(\"- %s %s\\n\\t%s\\n\", k, pre, p.Description())\n\t}\n}\n\nfunc (s *Site) ProcessCommand(page *Page, cmd *Command, pre bool) error {\n\tc := string(*cmd)\n\tif strings.HasPrefix(c, \":\") {\n\t\tc = \"external \" + c[1:]\n\t}\n\tbits := strings.Split(c, \" \")\n\n\tprocessor := s.Processors[bits[0]]\n\tif processor == nil {\n\t\treturn fmt.Errorf(\"Processor is nil\")\n\t}\n\tif (processor.Mode()&Pre != 0) != pre {\n\t\treturn nil\n\t}\n\tif processor == nil {\n\t\treturn fmt.Errorf(\"processor '%s' not found\", bits[0])\n\t}\n\treturn processor.Process(page, bits[1:])\n}\n\nfunc (s *Site) InitProcessors(m map[string]Processor) ", "output": "{\n\ts.Processors = m\n}"} {"input": "package online\n\nimport (\n\t\"monitor/log\"\n\t\"time\"\n)\n\nvar (\n\tsessions = make(map[string]*Session) \n)\n\nconst Expired = 60 * 30\n\n\nfunc init() {\n\tlog.Info(\"Session is started,expired every %d seconds\", Expired)\n\tgo func() {\n\t\tvar i int\n\t\ttimer := time.Tick(time.Minute)\n\t\tfor t := range timer {\n\t\t\ti = 0\n\t\t\tlock.Lock()\n\t\t\tfor k, s := range sessions {\n\t\t\t\tif s.IsExpired() {\n\t\t\t\t\tdelete(sessions, k)\n\t\t\t\t\ti = i + 1\n\t\t\t\t}\n\t\t\t}\n\t\t\tlock.Unlock()\n\t\t\tlog.Infof(\"clear %d sessions at %v,used %v\", i, t, time.Since(t))\n\t\t}\n\t}()\n}\n\n\ntype Session struct {\n\tUID string\n\tName string\n\tKey string\n\tLastTime time.Time\n}\n\n\nfunc (this *Session) IsExpired() bool {\n\treturn time.Since(this.LastTime).Seconds() > Expired\n}\n\n\nfunc SetSession(uid string, name string, key string) {\n\ts := &Session{UID: uid, Key: key, LastTime: time.Now()}\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tsessions[uid] = s\n}\n\n\nfunc GetSession(id string) (name string, key string, ok bool) {\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\n\tif s, exists := sessions[id]; exists {\n\t\tkey = s.Key\n\t\tname = s.Name\n\t\tok = true\n\t\ts.LastTime = time.Now()\n\t}\n\treturn\n}\n\n\nfunc FreshSession(id string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tif s, ok := sessions[id]; ok {\n\t\ts.LastTime = time.Now()\n\t}\n}\n\n\n\n\nfunc RemoveSession(id string) ", "output": "{\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tif _, ok := sessions[id]; ok {\n\t\tdelete(sessions, id)\n\t}\n}"} {"input": "package common\n\ntype mockUploader struct {\n}\n\n\n\nfunc (uploader *mockUploader) Url(sourceAssetId, templateId, placeholderSize string, page int32) string {\n\treturn \"mock://\" + sourceAssetId\n}\n\nfunc newMockUploader() Uploader {\n\treturn new(mockUploader)\n}\n\nfunc (uploader *mockUploader) Upload(destination string, path string) error ", "output": "{\n\treturn nil\n}"} {"input": "package airplane_mode\n\n\n\ntype GeneralRadioModule struct {\n\ttyp RadioType\n\tname string\n}\n\nfunc (Op *GeneralRadioModule) Type() RadioType {\n\treturn Op.typ\n}\n\nfunc (Op *GeneralRadioModule) Module() string {\n\treturn Op.name\n}\n\nfunc (Op *GeneralRadioModule) Len() int {\n\tstate, err := rfkillState(Op.typ)\n\tif err != nil {\n\t\tlogger.Warningf(\"check rfkill blocked state failed, err: %v\", err)\n\t\tstate.count = 0\n\t}\n\treturn state.count\n}\n\nfunc (Op *GeneralRadioModule) Block() error {\n\treturn rfkillAction(Op.typ, BlockRadioAction)\n}\n\nfunc (Op *GeneralRadioModule) Unblock() error {\n\treturn rfkillAction(Op.typ, UnblockRadioAction)\n}\n\nfunc (Op *GeneralRadioModule) IsBlocked() bool {\n\tstate, err := rfkillState(Op.typ)\n\tif err != nil {\n\t\tlogger.Warningf(\"check rfkill blocked state failed, err: %v\", err)\n\t\tstate.blocked = false\n\t}\n\treturn state.blocked\n}\n\n\ntype BluetoothRadio struct {\n\tGeneralRadioModule\n}\n\n\ntype WlanRadio struct {\n\tGeneralRadioModule\n}\n\n\ntype AllRadio struct {\n\tGeneralRadioModule\n}\n\nfunc getRadioModule(key RadioType) BaseRadioModule ", "output": "{\n\tvar module BaseRadioModule\n\tswitch key {\n\tcase BluetoothRadioType:\n\t\tmodule = &BluetoothRadio{GeneralRadioModule{typ: BluetoothRadioType, name: \"bluetooth\"}}\n\tcase WlanRadioType:\n\t\tmodule = &WlanRadio{GeneralRadioModule{typ: WlanRadioType, name: \"wlan\"}}\n\tcase AllRadioType:\n\t\tmodule = &AllRadio{GeneralRadioModule{typ: AllRadioType, name: \"all\"}}\n\tdefault:\n\t\tpanic(\"radio type not exist\")\n\t}\n\treturn module\n}"} {"input": "package bugapp\n\nimport (\n\t\"fmt\"\n\t\"github.com/driusan/bug/bugs\"\n)\n\n\n\nfunc Pwd() ", "output": "{\n\tfmt.Printf(\"%s\", bugs.GetIssuesDir())\n}"} {"input": "package runtime\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\nfunc TestCustomHandleCrash(t *testing.T) {\n\told := PanicHandlers\n\tdefer func() { PanicHandlers = old }()\n\tvar result interface{}\n\tPanicHandlers = []func(interface{}){\n\t\tfunc(r interface{}) {\n\t\t\tresult = r\n\t\t},\n\t}\n\tfunc() {\n\t\tdefer HandleCrash()\n\t\tpanic(\"test\")\n\t}()\n\tif result != \"test\" {\n\t\tt.Errorf(\"did not receive custom handler\")\n\t}\n}\nfunc TestCustomHandleError(t *testing.T) {\n\told := ErrorHandlers\n\tdefer func() { ErrorHandlers = old }()\n\tvar result error\n\tErrorHandlers = []func(error){\n\t\tfunc(err error) {\n\t\t\tresult = err\n\t\t},\n\t}\n\terr := fmt.Errorf(\"test\")\n\tHandleError(err)\n\tif result != err {\n\t\tt.Errorf(\"did not receive custom handler\")\n\t}\n}\n\nfunc TestHandleCrash(t *testing.T) ", "output": "{\n\tcount := 0\n\texpect := 10\n\tfor i := 0; i < expect; i = i + 1 {\n\t\tdefer HandleCrash()\n\t\tif i%2 == 0 {\n\t\t\tpanic(\"Test Panic\")\n\t\t}\n\t\tcount = count + 1\n\t}\n\tif count != expect {\n\t\tt.Errorf(\"Expected %d iterations, found %d\", expect, count)\n\t}\n}"} {"input": "package goopencc\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tZH2TW = \"s2twp.json\"\n\tTW2ZH = \"tw2sp.json\"\n)\n\n\n\nfunc Tw2Zh(v string) (string, int) {\n\tv = strings.Trim(v, \" \")\n\tif v == \"\" {\n\t\treturn v, 200\n\t}\n\treturn translate(v, TW2ZH)\n}\n\nfunc translate(v string, m string) (string, int) {\n\tapiUrl := \"http://opencc.byvoid.com/convert\"\n\tdata := url.Values{}\n\tdata.Set(\"text\", v)\n\tdata.Add(\"config\", m)\n\tdata.Add(\"precise\", \"0\")\n\n\tclient := &http.Client{}\n\tr, _ := http.NewRequest(\"POST\", apiUrl, bytes.NewBuffer([]byte(data.Encode())))\n\tr.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\tr.Header.Add(\"Content-Length\", strconv.Itoa(len(data.Encode())))\n\n\tresp, _ := client.Do(r)\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\treturn buf.String(), resp.StatusCode\n}\n\nfunc Zh2Tw(v string) (string, int) ", "output": "{\n\tv = strings.Trim(v, \" \")\n\tif v == \"\" {\n\t\treturn v, 200\n\t}\n\treturn translate(v, ZH2TW)\n}"} {"input": "package utils\n\nimport \"bufio\"\nimport \"strings\"\nimport \"os\"\n\n\ntype Hosts map[string]string\n\n\n\nvar HostMap Hosts\n\n\n\n\n\nfunc ResolveIp(ip string) string {\n\tfqdn, ok := HostMap[ip]\n\tif ok {\n\t\treturn fqdn\n\t} else {\n\t\treturn ip\n\t}\n}\n\nfunc LoadHostsFile(filepath string) (Hosts, error) ", "output": "{\n\tfile, err := os.Open(filepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tscanner := bufio.NewScanner(file)\n\tm := make(Hosts)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tips := strings.Split(line, \" \")\n\t\tm[ips[0]] = ips[1]\n\t}\n\treturn m, nil\n}"} {"input": "package usecase\n\nimport (\n\t\"context\"\n\n\t\"github.com/morikuni/chat/src/domain\"\n\t\"github.com/morikuni/failure\"\n)\n\ntype room struct {\n\taccountRepo AccountRepository\n\troomRepo RoomRepository\n}\n\nvar _ Room = (*room)(nil)\n\nfunc NewRoom(\n\taccountRepo AccountRepository,\n\troomRepo RoomRepository,\n) Room {\n\treturn &room{\n\t\taccountRepo,\n\t\troomRepo,\n\t}\n}\n\ntype CreateRoomRequest struct {\n\tOwnerID domain.AccountID\n\tName domain.RoomName\n}\n\ntype CreateRoomResponse struct {\n\tRoom *domain.Room\n}\n\n\n\nfunc (r *room) CreateRoom(ctx context.Context, request *CreateRoomRequest) (*CreateRoomResponse, error) ", "output": "{\n\taccount, err := r.accountRepo.Get(ctx, request.OwnerID)\n\tif err != nil {\n\t\treturn nil, failure.Wrap(err)\n\t}\n\n\troom := domain.NewRoom(account, request.Name)\n\n\terr = r.roomRepo.Save(ctx, room)\n\tif err != nil {\n\t\treturn nil, failure.Wrap(err)\n\t}\n\n\treturn &CreateRoomResponse{room}, nil\n}"} {"input": "package main\n\n\n\n\n\nfunc Problem1() interface{} ", "output": "{\n\tsum := 0\n\tfor i := 0; i < 1000; i++ {\n\t\tif i % 3 == 0 || i % 5 == 0 {\n\t\t\tsum += i\n\t\t}\n\t}\n\treturn sum\n}"} {"input": "package kubernetes_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestKubernetes(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Kubernetes Suite\")\n}"} {"input": "package database\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/base64\"\n\n\t\"github.com/garyburd/redigo/redis\"\n\n\t\"bosun.org/slog\"\n)\n\ntype ConfigDataAccess interface {\n\tSaveTempConfig(text string) (hash string, err error)\n\tGetTempConfig(hash string) (text string, err error)\n}\n\nfunc (d *dataAccess) Configs() ConfigDataAccess {\n\treturn d\n}\n\nconst configLifetime = 60 * 24 * 14 \n\nfunc (d *dataAccess) SaveTempConfig(text string) (string, error) {\n\tconn := d.Get()\n\tdefer conn.Close()\n\n\tsig := md5.Sum([]byte(text))\n\tb64 := base64.StdEncoding.EncodeToString(sig[0:8])\n\tif d.isRedis {\n\t\t_, err := conn.Do(\"SET\", \"tempConfig:\"+b64, text, \"EX\", configLifetime)\n\t\treturn b64, slog.Wrap(err)\n\t}\n\t_, err := conn.Do(\"SETEX\", \"tempConfig:\"+b64, configLifetime, text)\n\treturn b64, slog.Wrap(err)\n}\n\n\n\nfunc (d *dataAccess) GetTempConfig(hash string) (string, error) ", "output": "{\n\tconn := d.Get()\n\tdefer conn.Close()\n\n\tkey := \"tempConfig:\" + hash\n\tdat, err := redis.String(conn.Do(\"GET\", key))\n\tif err != nil {\n\t\treturn \"\", slog.Wrap(err)\n\t}\n\t_, err = conn.Do(\"EXPIRE\", key, configLifetime)\n\treturn dat, slog.Wrap(err)\n}"} {"input": "package jwt\n\nimport (\n\t\"crypto/rsa\"\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/SermoDigital/jose/crypto\"\n\t\"github.com/SermoDigital/jose/jws\"\n\t\"github.com/nicholasjackson/building-microservices-in-go/chapter8/utils\"\n)\n\nvar rsaPrivate *rsa.PrivateKey\nvar rsaPublic *rsa.PublicKey\n\nfunc init() {\n\tvar err error\n\trsaPrivate, err = utils.UnmarshalRSAPrivateKeyFromFile(\"../keys/sample_key.priv\")\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to parse private key\", err)\n\t}\n\n\trsaPublic, err = utils.UnmarshalRSAPublicKeyFromFile(\"../keys/sample_key.pub\")\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to parse public key\", err)\n\t}\n}\n\n\nfunc GenerateJWT() []byte {\n\tclaims := jws.Claims{}\n\tclaims.SetExpiration(time.Now().Add(2880 * time.Minute))\n\tclaims.Set(\"userID\", \"abcsd232jfjf\")\n\tclaims.Set(\"accessLevel\", \"user\")\n\n\tjwt := jws.NewJWT(claims, crypto.SigningMethodRS256)\n\n\tb, _ := jwt.Serialize(rsaPrivate)\n\n\treturn b\n}\n\n\n\n\n\nfunc ValidateJWT(token []byte) error ", "output": "{\n\tjwt, err := jws.ParseJWT(token)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to parse token: %v\", err)\n\t}\n\n\tif err = jwt.Validate(rsaPublic, crypto.SigningMethodRS256); err != nil {\n\t\treturn fmt.Errorf(\"Unable to validate token: %v\", err)\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\n\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\nconst semanticAlphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-\"\n\n\n\nconst (\n\tappMajor uint = 0\n\tappMinor uint = 1\n\tappPatch uint = 0\n\n\tappPreRelease = \"alpha\"\n)\n\n\n\n\nvar appBuild string\n\n\n\nfunc version() string {\n\tversion := fmt.Sprintf(\"%d.%d.%d\", appMajor, appMinor, appPatch)\n\n\tpreRelease := normalizeVerString(appPreRelease)\n\tif preRelease != \"\" {\n\t\tversion = fmt.Sprintf(\"%s-%s\", version, preRelease)\n\t}\n\n\tbuild := normalizeVerString(appBuild)\n\tif build != \"\" {\n\t\tversion = fmt.Sprintf(\"%s+%s\", version, build)\n\t}\n\n\treturn version\n}\n\n\n\n\n\n\n\nfunc normalizeVerString(str string) string ", "output": "{\n\tvar result bytes.Buffer\n\tfor _, r := range str {\n\t\tif strings.ContainsRune(semanticAlphabet, r) {\n\t\t\tresult.WriteRune(r)\n\t\t}\n\t}\n\treturn result.String()\n}"} {"input": "package drain\n\nimport (\n\t\"fmt\"\n\n\tcorev1 \"k8s.io/api/core/v1\"\n\tutilerrors \"k8s.io/apimachinery/pkg/util/errors\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc RunCordonOrUncordon(drainer *Helper, node *corev1.Node, desired bool) error {\n\tc := NewCordonHelper(node)\n\n\tif updateRequired := c.UpdateIfRequired(desired); !updateRequired {\n\t\treturn nil\n\t}\n\n\terr, patchErr := c.PatchOrReplace(drainer.Client, false)\n\tif patchErr != nil {\n\t\treturn patchErr\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc RunNodeDrain(drainer *Helper, nodeName string) error ", "output": "{\n\tlist, errs := drainer.GetPodsForDeletion(nodeName)\n\tif errs != nil {\n\t\treturn utilerrors.NewAggregate(errs)\n\t}\n\tif warnings := list.Warnings(); warnings != \"\" {\n\t\tfmt.Fprintf(drainer.ErrOut, \"WARNING: %s\\n\", warnings)\n\t}\n\n\tif err := drainer.DeleteOrEvictPods(list.Pods()); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package jpsplus\n\nimport (\n\t\"container/heap\"\n)\n\ntype PriorityQueue struct {\n\tpos int\n\tnode map[int]*Node\n}\n\nfunc newPriorityQueue() *PriorityQueue {\n\tp := new(PriorityQueue)\n\tp.node = make(map[int]*Node)\n\treturn p\n}\n\nfunc (p *PriorityQueue) Len() int {\n\treturn len(p.node)\n}\n\nfunc (p *PriorityQueue) Less(i, j int) bool {\n\treturn p.node[i].finalCost < p.node[j].finalCost\n}\n\nfunc (p *PriorityQueue) Swap(i, j int) {\n\tp.node[i], p.node[j] = p.node[j], p.node[i]\n\tp.node[i].heapIndex = i\n\tp.node[j].heapIndex = j\n}\n\nfunc (p *PriorityQueue) Push(x interface{}) {\n\titem, ok := x.(*Node)\n\tif ok {\n\t\titem.heapIndex = p.pos\n\t\tp.node[p.pos] = item\n\t\tp.pos++\n\t}\n}\n\nfunc (p *PriorityQueue) Pop() interface{} {\n\tp.pos--\n\titem := p.node[p.pos]\n\tdelete(p.node, p.pos)\n\treturn item\n}\n\n\n\nfunc (p *PriorityQueue) PopNode() *Node {\n\treturn heap.Pop(p).(*Node)\n}\n\nfunc (p *PriorityQueue) RemoveNode(n *Node) {\n\theap.Remove(p, n.heapIndex)\n}\n\nfunc (p *PriorityQueue) PushNode(n *Node) ", "output": "{\n\theap.Push(p, n)\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetAutonomousPatchRequest struct {\n\n\tAutonomousPatchId *string `mandatory:\"true\" contributesTo:\"path\" name:\"autonomousPatchId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request GetAutonomousPatchRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request GetAutonomousPatchRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request GetAutonomousPatchRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetAutonomousPatchResponse struct {\n\n\tRawResponse *http.Response\n\n\tAutonomousPatch `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetAutonomousPatchResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetAutonomousPatchResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetAutonomousPatchRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package collector\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/log\"\n)\n\n\nimport \"C\"\n\ntype loadavgCollector struct {\n\tmetric prometheus.Gauge\n}\n\n\n\n\n\nfunc NewLoadavgCollector() (Collector, error) {\n\treturn &loadavgCollector{\n\t\tmetric: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tNamespace: Namespace,\n\t\t\tName: \"load1\",\n\t\t\tHelp: \"1m load average.\",\n\t\t}),\n\t}, nil\n}\n\nfunc (c *loadavgCollector) Update(ch chan<- prometheus.Metric) (err error) {\n\tload, err := getLoad1()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Couldn't get load: %s\", err)\n\t}\n\tlog.Debugf(\"Set node_load: %f\", load)\n\tc.metric.Set(load)\n\tc.metric.Collect(ch)\n\treturn err\n}\n\nfunc getLoad1() (float64, error) {\n\tvar loadavg [1]C.double\n\tsamples := C.getloadavg(&loadavg[0], 1)\n\tif samples > 0 {\n\t\treturn float64(loadavg[0]), nil\n\t} else {\n\t\treturn 0, errors.New(\"failed to get load average\")\n\t}\n\n}\n\nfunc init() ", "output": "{\n\tFactories[\"loadavg\"] = NewLoadavgCollector\n}"} {"input": "package dao\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"go-common/app/admin/main/reply/model\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestEvent(t *testing.T) ", "output": "{\n\tvar (\n\t\tmid = int64(1)\n\t\tsub = &model.Subject{}\n\t\trp = &model.Reply{Content: &model.ReplyContent{}}\n\t\treport = &model.Report{}\n\t\tc = context.Background()\n\t)\n\tConvey(\"pub a event\", t, WithDao(func(d *Dao) {\n\t\terr := d.PubEvent(c, model.EventReportAdd, mid, sub, rp, report)\n\t\tSo(err, ShouldBeNil)\n\t}))\n}"} {"input": "package help\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\ntype EvtPool struct {\n\theader DListNode\n}\n\nfunc (this *EvtPool) Init() {\n\tthis.header.Init(nil)\n}\n\nfunc (this *EvtPool) Eat(name string) {\n\tfmt.Printf(\"吃%s\\n\", name)\n}\n\n\n\nfunc (this *EvtPool) Run() {\n\tfor {\n\t\tif this.header.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\n\t\tn := this.header.Next\n\n\t\tn.Data.(IEvent).Exec(this)\n\n\t\tn.Data.(IEvent).Destroy()\n\t}\n}\n\ntype Evt_eat struct {\n\tEvt_base\n\tFoodName string\n}\n\nfunc (this *Evt_eat) Exec() bool {\n\treturn true\n}\n\nfunc TestDlist(t *testing.T) {\n\n\tvar g_Pool EvtPool\n\tg_Pool.Init()\n\n\tg_Pool.Post(&Evt_eat{FoodName: \"西瓜\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"葡萄\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"黄瓜\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"大蒜\"})\n\n\tg_Pool.Run()\n}\n\nfunc (this *EvtPool) Post(d IEvent) bool ", "output": "{\n\n\tn := &DListNode{}\n\tn.Init(d)\n\n\tif !d.AddNode(n) {\n\t\treturn false\n\t}\n\n\told_pre := this.header.Pre\n\n\tthis.header.Pre = n\n\tn.Next = &this.header\n\tn.Pre = old_pre\n\told_pre.Next = n\n\n\treturn true\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\n\t\"errors\"\n\n\t\"github.com/kubernetes-sigs/service-catalog/pkg/svcat/service-catalog\"\n\t\"github.com/spf13/pflag\"\n)\n\n\n\ntype HasScopedFlags interface {\n\tApplyScopedFlags(flags *pflag.FlagSet) error\n}\n\n\nvar _ HasScopedFlags = NewScoped()\n\n\n\ntype Scoped struct {\n\tallowAll bool\n\trawScope string\n\tScope servicecatalog.Scope\n}\n\n\nfunc NewScoped() *Scoped {\n\treturn &Scoped{}\n}\n\n\n\n\n\n\n\nfunc (c *Scoped) ApplyScopedFlags(flags *pflag.FlagSet) error {\n\tswitch c.rawScope {\n\tcase servicecatalog.AllScope:\n\t\tif !c.allowAll {\n\t\t\treturn errors.New(\"invalid --scope (all), allowed values are: cluster, namespace\")\n\t\t}\n\t\tc.Scope = servicecatalog.Scope(c.rawScope)\n\t\treturn nil\n\tcase servicecatalog.ClusterScope, servicecatalog.NamespaceScope:\n\t\tc.Scope = servicecatalog.Scope(c.rawScope)\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid --scope (%s), allowed values are: all, cluster, namespace\", c.rawScope)\n\t}\n}\n\nfunc (c *Scoped) AddScopedFlags(flags *pflag.FlagSet, allowAll bool) ", "output": "{\n\tc.allowAll = allowAll\n\tif allowAll {\n\t\tflags.StringVar(&c.rawScope, \"scope\", servicecatalog.AllScope, \"Limit the command to a particular scope: cluster, namespace or all\")\n\t} else {\n\t\tflags.StringVar(&c.rawScope, \"scope\", servicecatalog.NamespaceScope, \"Limit the command to a particular scope: cluster or namespace\")\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n\n\t\"github.com/boltdb/bolt\"\n)\n\nfunc MemoryLocalStore() LocalStore {\n\treturn make(memoryLocalStore)\n}\n\ntype memoryLocalStore map[string]json.RawMessage\n\nfunc (m memoryLocalStore) GetMeta() (map[string]json.RawMessage, error) {\n\treturn m, nil\n}\n\nfunc (m memoryLocalStore) SetMeta(name string, meta json.RawMessage) error {\n\tm[name] = meta\n\treturn nil\n}\n\nconst dbBucket = \"tuf-client\"\n\n\n\ntype fileLocalStore struct {\n\tdb *bolt.DB\n}\n\nfunc (f *fileLocalStore) GetMeta() (map[string]json.RawMessage, error) {\n\tmeta := make(map[string]json.RawMessage)\n\tif err := f.db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(dbBucket))\n\t\tb.ForEach(func(k, v []byte) error {\n\t\t\tvcopy := make([]byte, len(v))\n\t\t\tcopy(vcopy, v)\n\t\t\tmeta[string(k)] = vcopy\n\t\t\treturn nil\n\t\t})\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn meta, nil\n}\n\nfunc (f *fileLocalStore) SetMeta(name string, meta json.RawMessage) error {\n\treturn f.db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(dbBucket))\n\t\treturn b.Put([]byte(name), meta)\n\t})\n}\n\nfunc FileLocalStore(path string) (LocalStore, error) ", "output": "{\n\tdb, err := bolt.Open(path, 0600, &bolt.Options{Timeout: time.Second})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := db.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucketIfNotExists([]byte(dbBucket))\n\t\treturn err\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &fileLocalStore{db: db}, nil\n}"} {"input": "package datastore\n\nimport (\n\t\"context\"\n\n\t\"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base\"\n\t\"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models\"\n\t\"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext\"\n\t\"github.com/pivotal-cf/brokerapi\"\n)\n\n\ntype InstanceInformation struct {\n\tNamespace string `json:\"namespace,omitempty\"`\n}\n\n\ntype DatastoreBroker struct {\n\tbase.BrokerBase\n}\n\n\nfunc (b *DatastoreBroker) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {\n\n\tii := InstanceInformation{\n\t\tNamespace: provisionContext.GetString(\"namespace\"),\n\t}\n\n\tif err := provisionContext.Error(); err != nil {\n\t\treturn models.ServiceInstanceDetails{}, err\n\t}\n\n\tdetails := models.ServiceInstanceDetails{}\n\tif err := details.SetOtherDetails(ii); err != nil {\n\t\treturn models.ServiceInstanceDetails{}, err\n\t}\n\n\treturn details, nil\n}\n\n\n\n\nfunc (b *DatastoreBroker) Deprovision(ctx context.Context, instance models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSBatchJobDefinition_NodeRangeProperty struct {\n\n\tContainer *AWSBatchJobDefinition_ContainerProperties `json:\"Container,omitempty\"`\n\n\tTargetNodes string `json:\"TargetNodes,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) AWSCloudFormationType() string {\n\treturn \"AWS::Batch::JobDefinition.NodeRangeProperty\"\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\n\n\nfunc (r *AWSBatchJobDefinition_NodeRangeProperty) SetDeletionPolicy(policy policies.DeletionPolicy) ", "output": "{\n\tr._deletionPolicy = policy\n}"} {"input": "package category\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/vapi/tags\"\n)\n\ntype ls struct {\n\t*flags.ClientFlag\n\t*flags.OutputFlag\n}\n\n\n\nfunc (cmd *ls) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.ClientFlag, ctx = flags.NewClientFlag(ctx)\n\tcmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)\n\tcmd.ClientFlag.Register(ctx, f)\n\tcmd.OutputFlag.Register(ctx, f)\n}\n\nfunc (cmd *ls) Process(ctx context.Context) error {\n\tif err := cmd.ClientFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn cmd.OutputFlag.Process(ctx)\n}\n\nfunc (cmd *ls) Description() string {\n\treturn `List all categories.\n\nExamples:\n govc tags.category.ls\n govc tags.category.ls -json | jq .`\n}\n\ntype lsResult []tags.Category\n\nfunc (r lsResult) Write(w io.Writer) error {\n\tfor _, c := range r {\n\t\tfmt.Fprintln(w, c.Name)\n\t}\n\treturn nil\n}\n\nfunc (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {\n\tc, err := cmd.RestClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tl, err := tags.NewManager(c).GetCategories(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn cmd.WriteResult(lsResult(l))\n}\n\nfunc init() ", "output": "{\n\tcli.Register(\"tags.category.ls\", &ls{})\n}"} {"input": "package tagquery\n\nimport (\n\t\"io\"\n\n\t\"github.com/grafana/metrictank/schema\"\n)\n\ntype expressionMatchNone struct {\n\texpressionCommon\n\toriginalOperator ExpressionOperator\n}\n\n\n\nfunc (e *expressionMatchNone) GetDefaultDecision() FilterDecision {\n\treturn Fail\n}\n\nfunc (e *expressionMatchNone) GetKey() string {\n\treturn e.key\n}\n\nfunc (e *expressionMatchNone) GetValue() string {\n\treturn e.value\n}\n\nfunc (e *expressionMatchNone) GetOperator() ExpressionOperator {\n\treturn MATCH_NONE\n}\n\nfunc (e *expressionMatchNone) GetOperatorCost() uint32 {\n\treturn 0\n}\n\nfunc (e *expressionMatchNone) RequiresNonEmptyValue() bool {\n\treturn true\n}\n\nfunc (e *expressionMatchNone) Matches(value string) bool {\n\treturn false\n}\n\nfunc (e *expressionMatchNone) GetMetricDefinitionFilter(_ IdTagLookup) MetricDefinitionFilter {\n\treturn func(_ schema.MKey, _ string, _ []string) FilterDecision { return Fail }\n}\n\nfunc (e *expressionMatchNone) StringIntoWriter(writer io.Writer) {\n\twriter.Write([]byte(e.key))\n\te.originalOperator.StringIntoWriter(writer)\n\twriter.Write([]byte(e.value))\n}\n\nfunc (e *expressionMatchNone) Equals(other Expression) bool ", "output": "{\n\treturn e.key == other.GetKey() && e.GetOperator() == other.GetOperator() && e.value == other.GetValue()\n}"} {"input": "package healthcareapis\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) BaseClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient ", "output": "{\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package endpoints\n\nimport (\n\t\"github.com/lxc/lxd/lxd/util\"\n\t\"github.com/lxc/lxd/shared\"\n)\n\n\nfunc Unstarted() *Endpoints {\n\treturn &Endpoints{\n\t\tsystemdListenFDsStart: util.SystemdListenFDsStart,\n\t}\n}\n\nfunc (e *Endpoints) Up(config *Config) error {\n\treturn e.up(config)\n}\n\n\nfunc (e *Endpoints) DevLxdSocketPath() string {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tlistener := e.listeners[devlxd]\n\treturn listener.Addr().String()\n}\n\nfunc (e *Endpoints) LocalSocketPath() string {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tlistener := e.listeners[local]\n\treturn listener.Addr().String()\n}\n\n\n\n\nfunc (e *Endpoints) NetworkAddressAndCert() (string, *shared.CertInfo) {\n\treturn e.NetworkAddress(), e.cert\n}\n\n\n\n\n\n\nfunc (e *Endpoints) SystemdListenFDsStart(start int) ", "output": "{\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\te.systemdListenFDsStart = start\n}"} {"input": "package graph\n\nimport \"fmt\"\n\ntype Graph struct {\n\tconnections []*Graph\n\tValue interface{}\n}\n\nfunc New() *Graph {\n\treturn new(Graph)\n}\n\nfunc (g *Graph) Connect(h *Graph) {\n\tg.connections = append(g.connections, h)\n\th.connections = append(h.connections, g)\n}\n\n\n\nfunc (g *Graph) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%v\", g.Value)\n}"} {"input": "package version\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/globalsign/certlint/certdata\"\n\t\"github.com/globalsign/certlint/checks\"\n\t\"github.com/globalsign/certlint/errors\"\n)\n\nconst checkName = \"Issuer DN Check\"\n\nfunc init() {\n\tchecks.RegisterCertificateCheck(checkName, nil, Check)\n}\n\n\n\n\nfunc Check(d *certdata.Data) *errors.Errors ", "output": "{\n\tvar e = errors.New(nil)\n\n\tif d.Issuer != nil && !bytes.Equal(d.Cert.RawIssuer, d.Issuer.RawSubject) {\n\t\te.Err(\"Certificate Issuer Distinguished Name field MUST match the Subject DN of the Issuing CA\")\n\t\treturn e\n\t}\n\n\treturn e\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n)\n\nfunc LoadManifest(path string) (manifest map[string]interface{}, err error) {\n\tcontent, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn manifest, err\n\t}\n\n\terr = json.Unmarshal(content, &manifest)\n\tif err != nil {\n\t\treturn manifest, err\n\t}\n\n\treturn manifest, nil\n}\n\nfunc StoreManifest(path string, manifest map[string]interface{}) (err error) {\n\tcontent, err := json.MarshalIndent(manifest, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(path, content, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc ManifestValidateType(value interface{}) error {\n\tswitch value.(type) {\n\tcase string:\n\t\tbreak\n\tdefault:\n\t\treturn errors.New(\"Invalid type for \\\"type\\\"\")\n\t}\n\n\tlegal := []string{\"zone-dataset\", \"lx-dataset\", \"zvol\", \"other\"}\n\tif !stringInSlice(value.(string), legal) {\n\t\treturn errors.New(fmt.Sprintf(\"Invalid value specified for \\\"type\\\": \\\"%v\\\"\", value))\n\t}\n\n\treturn nil\n}\n\n\n\nfunc ManifestValidateCompression(value interface{}) error {\n\tswitch value.(type) {\n\tcase string:\n\t\tbreak\n\tdefault:\n\t\treturn errors.New(\"Invalid type for \\\"compression\\\"\")\n\t}\n\n\tlegal := []string{\"bzip2\", \"gzip\", \"none\"}\n\tif !stringInSlice(value.(string), legal) {\n\t\treturn errors.New(fmt.Sprintf(\"Invalid value specified for \\\"compression\\\": \\\"%v\\\"\", value))\n\t}\n\n\treturn nil\n}\n\nfunc ManifestValidateOs(value interface{}) error ", "output": "{\n\tswitch value.(type) {\n\tcase string:\n\t\tbreak\n\tdefault:\n\t\treturn errors.New(\"Invalid type for \\\"os\\\"\")\n\t}\n\n\tlegal := []string{\"smartos\", \"windows\", \"linux\", \"bsd\"}\n\tif !stringInSlice(value.(string), legal) {\n\t\treturn errors.New(fmt.Sprintf(\"Invalid value specified for \\\"os\\\": \\\"%v\\\"\", value))\n\t}\n\n\treturn nil\n}"} {"input": "package core\n\nimport (\n\t\"runtime\"\n\n\t\"github.com/Tzunami/go-earthdollar/core/types\"\n\t\"github.com/Tzunami/go-earthdollar/pow\"\n)\n\n\ntype nonceCheckResult struct {\n\tindex int \n\tvalid bool \n}\n\n\n\n\nfunc verifyNoncesFromHeaders(checker pow.PoW, headers []*types.Header) (chan<- struct{}, <-chan nonceCheckResult) {\n\titems := make([]pow.Block, len(headers))\n\tfor i, header := range headers {\n\t\titems[i] = types.NewBlockWithHeader(header)\n\t}\n\treturn verifyNonces(checker, items)\n}\n\n\n\n\n\n\n\n\nfunc verifyNonces(checker pow.PoW, items []pow.Block) (chan<- struct{}, <-chan nonceCheckResult) {\n\tworkers := runtime.GOMAXPROCS(0)\n\tif len(items) < workers {\n\t\tworkers = len(items)\n\t}\n\ttasks := make(chan int, workers)\n\tresults := make(chan nonceCheckResult, len(items)) \n\tfor i := 0; i < workers; i++ {\n\t\tgo func() {\n\t\t\tfor index := range tasks {\n\t\t\t\tresults <- nonceCheckResult{index: index, valid: checker.Verify(items[index])}\n\t\t\t}\n\t\t}()\n\t}\n\tabort := make(chan struct{})\n\tgo func() {\n\t\tdefer close(tasks)\n\n\t\tfor i := range items {\n\t\t\tselect {\n\t\t\tcase tasks <- i:\n\t\t\t\tcontinue\n\t\t\tcase <-abort:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn abort, results\n}\n\nfunc verifyNoncesFromBlocks(checker pow.PoW, blocks []*types.Block) (chan<- struct{}, <-chan nonceCheckResult) ", "output": "{\n\titems := make([]pow.Block, len(blocks))\n\tfor i, block := range blocks {\n\t\titems[i] = block\n\t}\n\treturn verifyNonces(checker, items)\n}"} {"input": "package runtime\n\nimport \"unsafe\"\n\n\n\n\n\n\nfunc atomicload(ptr *uint32) uint32 {\n\tnop()\n\treturn *ptr\n}\n\n\nfunc atomicloadp(ptr unsafe.Pointer) unsafe.Pointer {\n\tnop()\n\treturn *(*unsafe.Pointer)(ptr)\n}\n\n\n\n\n\nfunc xchg64(ptr *uint64, new uint64) uint64 {\n\tfor {\n\t\told := *ptr\n\t\tif cas64(ptr, old, new) {\n\t\t\treturn old\n\t\t}\n\t}\n}\n\n\nfunc xadd(ptr *uint32, delta int32) uint32\n\n\nfunc xchg(ptr *uint32, new uint32) uint32\n\n\nfunc xchgp1(ptr unsafe.Pointer, new unsafe.Pointer) unsafe.Pointer\n\n\nfunc xchguintptr(ptr *uintptr, new uintptr) uintptr\n\n\nfunc atomicload64(ptr *uint64) uint64\n\n\nfunc atomicand8(ptr *uint8, val uint8)\n\n\nfunc atomicor8(ptr *uint8, val uint8)\n\n\n\n\nfunc cas64(ptr *uint64, old, new uint64) bool\n\n\nfunc atomicstore(ptr *uint32, val uint32)\n\n\nfunc atomicstore64(ptr *uint64, val uint64)\n\n\nfunc atomicstorep1(ptr unsafe.Pointer, val unsafe.Pointer)\n\nfunc xadd64(ptr *uint64, delta int64) uint64 ", "output": "{\n\tfor {\n\t\told := *ptr\n\t\tif cas64(ptr, old, old+uint64(delta)) {\n\t\t\treturn old + uint64(delta)\n\t\t}\n\t}\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n)\n\ntype Audits []Audit\n\nfunc (o Audits) Etag() string {\n\tif len(o) > 0 {\n\t\treturn Etag(o[0].CreateAt)\n\t}\n\treturn \"\"\n}\n\nfunc (o Audits) ToJson() string {\n\tb, err := json.Marshal(o)\n\tif err != nil {\n\t\treturn \"[]\"\n\t}\n\treturn string(b)\n}\n\n\n\nfunc AuditsFromJson(data io.Reader) Audits ", "output": "{\n\tvar o Audits\n\tjson.NewDecoder(data).Decode(&o)\n\treturn o\n}"} {"input": "package iso20022\n\n\ntype GovernanceIdentification1Choice struct {\n\n\tCode *GovernanceIdentification1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification1 `xml:\"Prtry\"`\n}\n\nfunc (g *GovernanceIdentification1Choice) SetCode(value string) {\n\tg.Code = (*GovernanceIdentification1Code)(&value)\n}\n\n\n\nfunc (g *GovernanceIdentification1Choice) AddProprietary() *GenericIdentification1 ", "output": "{\n\tg.Proprietary = new(GenericIdentification1)\n\treturn g.Proprietary\n}"} {"input": "package leetcode\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc isValid2(s string) bool {\n\tstack := make([]byte, 0)\n\tfor _, c := range s {\n\t\tswitch c {\n\t\tcase '{':\n\t\t\tstack = append(stack, '}')\n\t\tcase '[':\n\t\t\tstack = append(stack, ']')\n\t\tcase '(':\n\t\t\tstack = append(stack, ')')\n\t\tdefault:\n\t\t\tif len(stack) == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tvar last byte\n\t\t\tlast, stack = stack[len(stack)-1], stack[:len(stack)-1]\n\t\t\tif last != byte(c) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn len(stack) == 0\n}\n\nfunc isValid(s string) bool ", "output": "{\n\tstack := make([]byte, 0)\n\tfor _, c := range s {\n\t\tif c == '{' {\n\t\t\tstack = append(stack, '}')\n\t\t} else if c == '[' {\n\t\t\tstack = append(stack, ']')\n\t\t} else if c == '(' {\n\t\t\tstack = append(stack, ')')\n\t\t} else {\n\t\t\tif len(stack) == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tvar last byte\n\t\t\tlast, stack = stack[len(stack)-1], stack[:len(stack)-1]\n\t\t\tif last != byte(c) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn len(stack) == 0\n}"} {"input": "package render\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/googlecodelabs/tools/claat/types\"\n)\n\n\n\nfunc TestExecuteBuiltin(t *testing.T) ", "output": "{\n\tstep := &types.Step{\n\t\tTitle: \"Test step\",\n\t\tContent: types.NewListNode(types.NewTextNode(\"text\")),\n\t}\n\tctx := &Context{\n\t\tMeta: &types.Meta{},\n\t\tSteps: []*types.Step{step},\n\t}\n\tfor _, f := range []string{\"html\", \"md\"} {\n\t\tvar buf bytes.Buffer\n\t\tif err := Execute(&buf, f, ctx); err != nil {\n\t\t\tt.Errorf(\"%s: %v\", f, err)\n\t\t}\n\t}\n}"} {"input": "package translatableerror\n\ntype PackageNotFoundInAppError struct {\n\tAppName string\n\tBinaryName string\n}\n\n\n\nfunc (e PackageNotFoundInAppError) Translate(translate func(string, ...interface{}) string) string {\n\treturn translate(e.Error(), map[string]interface{}{\n\t\t\"AppName\": e.AppName,\n\t\t\"BinaryName\": e.BinaryName,\n\t})\n}\n\nfunc (PackageNotFoundInAppError) Error() string ", "output": "{\n\treturn \"Package not found in app '{{.AppName}}'.\\n\\nTIP: Use '{{.BinaryName}} packages {{.AppName}}' to list packages in your app. Use '{{.BinaryName}} create-package' to create one.\"\n}"} {"input": "package trust\n\nimport (\n\t\"github.com/rackspace/gophercloud\"\n\t\"github.com/rackspace/gophercloud/openstack\"\n\ttoken3 \"github.com/rackspace/gophercloud/openstack/identity/v3/tokens\"\n)\n\ntype AuthOptionsExt struct {\n\ttoken3.AuthOptions\n\tTrustID string\n}\n\n\n\n\nfunc AuthenticateV3Trust(client *gophercloud.ProviderClient, options AuthOptionsExt) error {\n\treturn trustv3auth(client, \"\", options)\n}\n\nfunc trustv3auth(client *gophercloud.ProviderClient, endpoint string, options AuthOptionsExt) error {\n\tclient.TokenID = options.AuthOptions.TokenID\n\tv3Client := openstack.NewIdentityV3(client)\n\tif endpoint != \"\" {\n\t\tv3Client.Endpoint = endpoint\n\t}\n\n\tv3Options := options\n\n\tvar scope *token3.Scope\n\n\tresult := token3.Create(v3Client, v3Options, scope)\n\n\ttoken, err := result.ExtractToken()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcatalog, err := result.ExtractServiceCatalog()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient.TokenID = token.ID\n\n\tif options.AuthOptions.AllowReauth {\n\t\tclient.ReauthFunc = func() error {\n\t\t\tclient.TokenID = \"\"\n\t\t\treturn trustv3auth(client, endpoint, options)\n\t\t}\n\t}\n\tclient.EndpointLocator = func(opts gophercloud.EndpointOpts) (string, error) {\n\t\treturn openstack.V3EndpointURL(catalog, opts)\n\t}\n\n\treturn nil\n}\n\nfunc (ao AuthOptionsExt) ToAuthOptionsV3Map(c *gophercloud.ServiceClient, scope *token3.Scope) (map[string]interface{}, error) ", "output": "{\n\tauthMap, err := ao.AuthOptions.ToAuthOptionsV3Map(c, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauthMap = authMap[\"auth\"].(map[string]interface{})\n\n\tif ao.TrustID != \"\" {\n\t\tauthMap[\"scope\"] = map[string]interface{}{\n\t\t\t\"OS-TRUST:trust\": map[string]interface{}{\n\t\t\t\t\"id\": ao.TrustID,\n\t\t\t},\n\t\t}\n\t} else {\n\t\treturn nil, token3.ErrScopeEmpty\n\t}\n\treturn map[string]interface{}{\"auth\": authMap}, nil\n}"} {"input": "package test\n\nimport (\n\t\"fmt\"\n\t\"github.com/go-errors/errors\"\n)\n\n\n\nfunc ShouldBeErr(a interface{}, options ...interface{}) string ", "output": "{\n\tactual := a.(error)\n\texpected := options[0].(error)\n\tok := errors.Is(actual, expected)\n\n\tif !ok {\n\t\treturn fmt.Sprintf(\"Errors don't match:\\n%v+\\n%v+\", actual, expected)\n\t}\n\n\treturn \"\"\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realInternetGateway InternetGateway\n\n\nfunc (o *InternetGateway) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realInternetGateway\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = InternetGateway(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &InternetGateway{}\n\n\nfunc (o *InternetGateway) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\n\nfunc (o *InternetGateway) SetLifecycle(lifecycle fi.Lifecycle) {\n\to.Lifecycle = &lifecycle\n}\n\nvar _ fi.HasName = &InternetGateway{}\n\n\nfunc (o *InternetGateway) GetName() *string {\n\treturn o.Name\n}\n\n\nfunc (o *InternetGateway) SetName(name string) {\n\to.Name = &name\n}\n\n\n\n\nfunc (o *InternetGateway) String() string ", "output": "{\n\treturn fi.TaskAsString(o)\n}"} {"input": "package methods\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/barnettzqg/journey/configuration\"\n\t\"github.com/barnettzqg/journey/database\"\n\t\"github.com/barnettzqg/journey/slug\"\n\t\"github.com/barnettzqg/journey/structure\"\n)\n\n\nvar Blog *structure.Blog\n\nvar assetPath = []byte(\"/assets/\")\n\nfunc UpdateBlog(b *structure.Blog, userId int64) error {\n\tnavigation, err := json.Marshal(b.NavigationItems)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = database.UpdateSettings(b.Title, b.Description, b.Logo, b.Cover, b.PostsPerPage, b.ActiveTheme, navigation, time.Now(), userId)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = GenerateBlog()\n\tif err != nil {\n\t\tlog.Panic(\"Error: couldn't generate blog data:\", err)\n\t}\n\treturn nil\n}\n\n\n\nfunc GenerateBlog() error {\n\tif Blog != nil {\n\t\tBlog.Lock()\n\t\tdefer Blog.Unlock()\n\t}\n\tblog, err := database.RetrieveBlog()\n\tif err != nil {\n\t\treturn err\n\t}\n\tblog.Url = []byte(configuration.Config.Url)\n\tblog.AssetPath = assetPath\n\tfor index, _ := range blog.NavigationItems {\n\t\tblog.NavigationItems[index].Slug = slug.Generate(blog.NavigationItems[index].Label, \"navigation\")\n\t}\n\tBlog = blog\n\treturn nil\n}\n\nfunc UpdateActiveTheme(activeTheme string, userId int64) error ", "output": "{\n\terr := database.UpdateActiveTheme(activeTheme, time.Now(), userId)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = GenerateBlog()\n\tif err != nil {\n\t\tlog.Panic(\"Error: couldn't generate blog data:\", err)\n\t}\n\treturn nil\n}"} {"input": "package helper\n\nimport (\n\t\"encoding/base64\"\n\t\"strings\"\n\t\"time\"\n\t\"github.com/insionng/yougam/libraries/flosch/pongo2.v3\"\n)\n\nfunc ConvertToBase64(in string) string {\n\treturn base64.StdEncoding.EncodeToString([]byte(in))\n}\n\nfunc ConvertToBase64ByPongo2(in *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(base64.StdEncoding.EncodeToString([]byte(in.String())))\n}\n\nfunc SplitByPongo2(in *pongo2.Value, splitor *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Split(in.String(), splitor.String()))\n}\n\nfunc MarkdownByPongo2(in *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Markdown(in.String()))\n}\n\nfunc CropwordByPongo2(in *pongo2.Value, start *pongo2.Value, length *pongo2.Value, symbol *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Substr(in.String(), start.Integer(), length.Integer(), symbol.String()))\n}\n\nfunc Cropword(in string, start int, length int, symbol string) string {\n\treturn Substr(in, start, length, symbol)\n}\n\n\n\nfunc Unix2TimeByPongo2(in *pongo2.Value, timeLayout *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(time.Unix(int64(in.Integer()), 0).Format(timeLayout.String()))\n}\n\nfunc File(s string) string ", "output": "{\n\tif len(s) > 0 {\n\t\tif strings.HasPrefix(s, \"http\") || strings.HasPrefix(s, \"/identicon\") {\n\t\t\treturn s\n\t\t} else {\n\t\t\treturn \"/file\" + s\n\t\t}\n\t}\n\treturn s\n}"} {"input": "package sw\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\n\t\"github.com/hyperledger/fabric/core/crypto/bccsp\"\n\t\"github.com/hyperledger/fabric/core/crypto/primitives\"\n)\n\ntype rsaPrivateKey struct {\n\tk *rsa.PrivateKey\n}\n\n\n\n\n\n\nfunc (k *rsaPrivateKey) SKI() (ski []byte) {\n\traw := x509.MarshalPKCS1PrivateKey(k.k)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\nfunc (k *rsaPrivateKey) Symmetric() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPrivateKey) Private() bool {\n\treturn true\n}\n\n\n\nfunc (k *rsaPrivateKey) PublicKey() (bccsp.Key, error) {\n\treturn &rsaPublicKey{&k.k.PublicKey}, nil\n}\n\ntype rsaPublicKey struct {\n\tk *rsa.PublicKey\n}\n\n\n\nfunc (k *rsaPublicKey) Bytes() (raw []byte, err error) {\n\traw, err = x509.MarshalPKIXPublicKey(k.k)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed marshalling key [%s]\", err)\n\t}\n\treturn\n}\n\n\nfunc (k *rsaPublicKey) SKI() (ski []byte) {\n\traw, _ := primitives.PublicKeyToPEM(k.k, nil)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\nfunc (k *rsaPublicKey) Symmetric() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) Private() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) PublicKey() (bccsp.Key, error) {\n\treturn k, nil\n}\n\nfunc (k *rsaPrivateKey) Bytes() (raw []byte, err error) ", "output": "{\n\treturn\n}"} {"input": "package vm\n\nimport (\n\t\"github.com/expanse-org/go-expanse/common\"\n\t\"github.com/expanse-org/go-expanse/common/math\"\n\t\"github.com/holiman/uint256\"\n)\n\n\n\nfunc calcMemSize64(off, l *uint256.Int) (uint64, bool) {\n\tif !l.IsUint64() {\n\t\treturn 0, true\n\t}\n\treturn calcMemSize64WithUint(off, l.Uint64())\n}\n\n\n\n\nfunc calcMemSize64WithUint(off *uint256.Int, length64 uint64) (uint64, bool) {\n\tif length64 == 0 {\n\t\treturn 0, false\n\t}\n\toffset64, overflow := off.Uint64WithOverflow()\n\tif overflow {\n\t\treturn 0, true\n\t}\n\tval := offset64 + length64\n\treturn val, val < offset64\n}\n\n\n\nfunc getData(data []byte, start uint64, size uint64) []byte {\n\tlength := uint64(len(data))\n\tif start > length {\n\t\tstart = length\n\t}\n\tend := start + size\n\tif end > length {\n\t\tend = length\n\t}\n\treturn common.RightPadBytes(data[start:end], int(size))\n}\n\n\nfunc toWordSize(size uint64) uint64 {\n\tif size > math.MaxUint64-31 {\n\t\treturn math.MaxUint64/32 + 1\n\t}\n\n\treturn (size + 31) / 32\n}\n\n\n\nfunc allZero(b []byte) bool ", "output": "{\n\tfor _, byte := range b {\n\t\tif byte != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package mocks\n\nimport \"github.com/myshkin5/jsonstruct\"\n\ntype MockWriter struct {\n\tMessages chan []byte\n}\n\nfunc NewMockWriter() *MockWriter {\n\treturn &MockWriter{\n\t\tMessages: make(chan []byte, 10000),\n\t}\n}\n\nfunc (m *MockWriter) Init(config jsonstruct.JSONStruct) error {\n\treturn nil\n}\n\n\n\nfunc (m *MockWriter) Close() error {\n\treturn nil\n}\n\nfunc (m *MockWriter) Write(message []byte) (int, error) ", "output": "{\n\tm.Messages <- message\n\treturn len(message), nil\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/revel/revel\"\n\t\"AuthKeyPush/app/models\"\n)\n\ntype Auth struct {\n\t*revel.Controller\n}\n\n\n\nfunc (c Auth) Github(code string) revel.Result ", "output": "{\n\tlogin := models.GitHub(code)\n\n\tif login == true {\n\t\tc.Session[\"login\"] = \"true\"\n\t} else {\n\t\tc.Session[\"login\"] = \"false\"\n\t\tc.Session[\"msg\"] = \"Login faied. Check conf/site.json or README.md\"\n\t}\n\n\treturn c.Redirect(\"/\")\n}"} {"input": "package billing\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/billing/mgmt/2017-04-24-preview/billing\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype ManagementClient = original.ManagementClient\ntype InvoicesClient = original.InvoicesClient\ntype DownloadURL = original.DownloadURL\ntype ErrorDetails = original.ErrorDetails\ntype ErrorResponse = original.ErrorResponse\ntype Invoice = original.Invoice\ntype InvoiceProperties = original.InvoiceProperties\ntype InvoicesListResult = original.InvoicesListResult\ntype Operation = original.Operation\ntype OperationDisplay = original.OperationDisplay\ntype OperationListResult = original.OperationListResult\ntype Period = original.Period\ntype PeriodProperties = original.PeriodProperties\ntype PeriodsListResult = original.PeriodsListResult\ntype Resource = original.Resource\ntype OperationsClient = original.OperationsClient\ntype PeriodsClient = original.PeriodsClient\n\nfunc NewOperationsClient(subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClient(subscriptionID)\n}\nfunc NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewPeriodsClient(subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClient(subscriptionID)\n}\nfunc NewPeriodsClientWithBaseURI(baseURI string, subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\n\nfunc New(subscriptionID string) ManagementClient {\n\treturn original.New(subscriptionID)\n}\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewInvoicesClient(subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClient(subscriptionID)\n}\nfunc NewInvoicesClientWithBaseURI(baseURI string, subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClientWithBaseURI(baseURI, subscriptionID)\n}\n\nfunc Version() string ", "output": "{\n\treturn original.Version()\n}"} {"input": "package credential\n\nimport (\n\t\"pharmer.dev/cloud/apis\"\n\tv1 \"pharmer.dev/cloud/apis/cloud/v1\"\n\n\t\"github.com/spf13/pflag\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\ntype Linode struct {\n\tCommonSpec\n\n\ttoken string\n}\n\nfunc (c Linode) APIToken() string { return get(c.Data, LinodeAPIToken, c.token) }\n\nfunc (c *Linode) LoadFromEnv() {\n\tc.CommonSpec.LoadFromEnv(c.Format())\n}\n\nfunc (c Linode) IsValid() (bool, error) {\n\treturn c.CommonSpec.IsValid(c.Format())\n}\n\nfunc (c *Linode) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(&c.token, apis.Linode+\".\"+LinodeAPIToken, c.token, \"Linode api token\")\n}\n\n\n\nfunc (_ Linode) Format() v1.CredentialFormat {\n\treturn v1.CredentialFormat{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: apis.Linode,\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tapis.KeyClusterCredential: \"\",\n\t\t\t\tapis.KeyDNSCredential: \"\",\n\t\t\t},\n\t\t},\n\t\tSpec: v1.CredentialFormatSpec{\n\t\t\tProvider: apis.Linode,\n\t\t\tDisplayFormat: \"field\",\n\t\t\tFields: []v1.CredentialField{\n\t\t\t\t{\n\t\t\t\t\tEnvconfig: \"LINODE_TOKEN\",\n\t\t\t\t\tForm: \"linode_token\",\n\t\t\t\t\tJSON: LinodeAPIToken,\n\t\t\t\t\tLabel: \"Token\",\n\t\t\t\t\tInput: \"password\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (_ Linode) RequiredFlags() []string ", "output": "{\n\treturn []string{apis.Linode + \".\" + LinodeAPIToken}\n}"} {"input": "package conversions\n\nimport \"jvmgo/ch11/instructions/base\"\nimport \"jvmgo/ch11/rtda\"\n\n\ntype L2D struct{ base.NoOperandsInstruction }\n\nfunc (self *L2D) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tl := stack.PopLong()\n\td := float64(l)\n\tstack.PushDouble(d)\n}\n\n\ntype L2F struct{ base.NoOperandsInstruction }\n\n\n\n\ntype L2I struct{ base.NoOperandsInstruction }\n\nfunc (self *L2I) Execute(frame *rtda.Frame) {\n\tstack := frame.OperandStack()\n\tl := stack.PopLong()\n\ti := int32(l)\n\tstack.PushInt(i)\n}\n\nfunc (self *L2F) Execute(frame *rtda.Frame) ", "output": "{\n\tstack := frame.OperandStack()\n\tl := stack.PopLong()\n\tf := float32(l)\n\tstack.PushFloat(f)\n}"} {"input": "package sparta\n\nimport (\n\t\"context\"\n\n\t\"github.com/aws/aws-lambda-go/lambdacontext\"\n)\n\n\n\nfunc ExampleCloudWatchLogsPermission() {\n\tvar lambdaFunctions []*LambdaAWSInfo\n\n\tcloudWatchLogsLambda, _ := NewAWSLambda(LambdaName(cloudWatchLogsProcessor),\n\t\tcloudWatchLogsProcessor,\n\t\tIAMRoleDefinition{})\n\n\tcloudWatchLogsPermission := CloudWatchLogsPermission{}\n\tcloudWatchLogsPermission.Filters = make(map[string]CloudWatchLogsSubscriptionFilter, 1)\n\tcloudWatchLogsPermission.Filters[\"MyFilter\"] = CloudWatchLogsSubscriptionFilter{\n\t\tLogGroupName: \"/aws/lambda/*\",\n\t}\n\tcloudWatchLogsLambda.Permissions = append(cloudWatchLogsLambda.Permissions, cloudWatchLogsPermission)\n\n\tlambdaFunctions = append(lambdaFunctions, cloudWatchLogsLambda)\n\tmainErr := Main(\"CloudWatchLogs\", \"Registers for CloudWatch Logs\", lambdaFunctions, nil, nil)\n\tif mainErr != nil {\n\t\tpanic(\"Failed to invoke sparta.Main: %s\" + mainErr.Error())\n\t}\n}\n\nfunc cloudWatchLogsProcessor(ctx context.Context,\n\tprops map[string]interface{}) error ", "output": "{\n\tlambdaCtx, _ := lambdacontext.FromContext(ctx)\n\tLogger().Info().\n\t\tStr(\"RequestID\", lambdaCtx.AwsRequestID).\n\t\tMsg(\"CloudWatch log event\")\n\tLogger().Info().Msg(\"CloudWatch Log event received\")\n\treturn nil\n}"} {"input": "package handler\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/cosiner/zerver\"\n)\n\ntype MethodHandler interface {\n\tGet(zerver.Request, zerver.Response)\n\tPost(zerver.Request, zerver.Response)\n\tDelete(zerver.Request, zerver.Response)\n\tPut(zerver.Request, zerver.Response)\n\tPatch(zerver.Request, zerver.Response)\n}\n\ntype methodHandler struct {\n\tzerver.Component\n\tMethodHandler\n}\n\n\n\nfunc (s methodHandler) Handler(method string) zerver.HandleFunc {\n\tswitch method {\n\tcase zerver.METHOD_GET:\n\t\treturn s.Get\n\tcase zerver.METHOD_POST:\n\t\treturn s.Post\n\tcase zerver.METHOD_DELETE:\n\t\treturn s.Delete\n\tcase zerver.METHOD_PUT:\n\t\treturn s.Put\n\tcase zerver.METHOD_PATCH:\n\t\treturn s.Patch\n\t}\n\n\treturn nil\n}\n\ntype NopMethodHandler struct{}\n\nfunc (NopMethodHandler) Get(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Post(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Delete(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Put(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc (NopMethodHandler) Patch(_ zerver.Request, resp zerver.Response) {\n\tresp.StatusCode(http.StatusMethodNotAllowed)\n}\n\nfunc WrapMethodHandler(m MethodHandler) zerver.Handler ", "output": "{\n\treturn &methodHandler{\n\t\tComponent: zerver.NopComponent{},\n\t\tMethodHandler: m,\n\t}\n}"} {"input": "package local \n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/tiborvass/docker/errdefs\"\n\t\"github.com/pkg/errors\"\n)\n\ntype optsConfig struct{}\n\n\n\nfunc (r *Root) scopedPath(realPath string) bool {\n\tif strings.HasPrefix(realPath, filepath.Join(r.scope, volumesPathName)) && realPath != filepath.Join(r.scope, volumesPathName) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc setOpts(v *localVolume, opts map[string]string) error {\n\tif len(opts) > 0 {\n\t\treturn errdefs.InvalidParameter(errors.New(\"options are not supported on this platform\"))\n\t}\n\treturn nil\n}\n\nfunc (v *localVolume) needsMount() bool {\n\treturn false\n}\n\n\n\nfunc (v *localVolume) postMount() error {\n\treturn nil\n}\n\nfunc (v *localVolume) CreatedAt() (time.Time, error) {\n\tfileInfo, err := os.Stat(v.path)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\tft := fileInfo.Sys().(*syscall.Win32FileAttributeData).CreationTime\n\treturn time.Unix(0, ft.Nanoseconds()), nil\n}\n\nfunc (v *localVolume) mount() error ", "output": "{\n\treturn nil\n}"} {"input": "package gtk\n\n\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n\n\t\"github.com/untoldwind/amintk/gdk\"\n)\n\n\ntype Image struct {\n\tWidget\n}\n\n\nfunc ImageNew() *Image {\n\tc := C.gtk_image_new()\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\nfunc (v *Image) native() *C.GtkImage {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn (*C.GtkImage)(v.Native())\n}\n\n\nfunc ImageNewFromIconName(iconName string, size IconSize) *Image {\n\tcstr := C.CString(iconName)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_image_new_from_icon_name((*C.gchar)(cstr),\n\t\tC.GtkIconSize(size))\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\n\nfunc ImageNewFromPixbuf(pixbuf *gdk.Pixbuf) *Image {\n\tptr := (*C.GdkPixbuf)(pixbuf.Native())\n\tc := C.gtk_image_new_from_pixbuf(ptr)\n\treturn wrapImage(unsafe.Pointer(c))\n}\n\nfunc wrapImage(p unsafe.Pointer) *Image {\n\tif widget := wrapWidget(p); widget != nil {\n\t\treturn &Image{Widget: *widget}\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (v *Image) SetFromPixbuf(pixbuf *gdk.Pixbuf) {\n\tpbptr := (*C.GdkPixbuf)(pixbuf.Native())\n\tC.gtk_image_set_from_pixbuf(v.native(), pbptr)\n}\n\nfunc (v *Image) Clear() ", "output": "{\n\tC.gtk_image_clear(v.native())\n}"} {"input": "package kegg\n\nimport (\n\t\"fmt\"\n)\n\nfunc ExampleConvert() {\n\tdrugID, err := New().Convert(\"pubchem\", \"drug\", \"313046637\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(drugID)\n}\n\nfunc ExampleGet() {\n\tinfo, err := New().Get(\"drug\", \"D00341\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(info != \"\")\n}\n\n\n\nfunc ExampleLink() {\n\tcompoundID, err := New().Link(\"drug\", \"compound\", \"D00341\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(compoundID)\n}\n\nfunc ExampleFind() ", "output": "{\n\tmatch, err := New().Find(\"drug\", \"D00341\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(match != \"\")\n}"} {"input": "package vault\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\ntype AuthType interface {\n\tDescribe() string\n\tGetType() string\n\tgetAuthConfig() map[string]interface{}\n\tgetAuthMountConfig() map[string]interface{}\n\tConfigure(c *VCClient) error\n\tTuneMount(c *VCClient, path string) error\n\tWriteUsers(c *VCClient) error\n\tWriteGroups(c *VCClient) error\n}\n\n\n\n\n\nfunc Path(a AuthType) string {\n\treturn fmt.Sprintf(\"auth/%s\", a.GetType())\n}\n\n\nfunc (c *VCClient) AuthEnable(a AuthType) error {\n\tif err := c.Sys().EnableAuth(a.GetType(), a.GetType(), a.Describe()); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc (c *VCClient) AuthConfigure(a AuthType) error {\n\tif err := a.WriteUsers(c); err != nil {\n\t\treturn err\n\t}\n\tif err := a.WriteGroups(c); err != nil {\n\t\treturn err\n\t}\n\tif err := a.TuneMount(c, Path(a)); err != nil {\n\t\treturn err\n\t}\n\n\tif err := a.Configure(c); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc EnableAndConfigure(a AuthType, c *VCClient) error {\n\tif !c.AuthExist(a.GetType()) {\n\t\tif err := c.AuthEnable(a); err != nil {\n\t\t\treturn fmt.Errorf(\"Error enabling auth mount: %v\", err)\n\t\t}\n\t}\n\tif err := c.AuthConfigure(a); err != nil {\n\t\treturn fmt.Errorf(\"Error configuring auth mount: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (c *VCClient) AuthExist(name string) bool ", "output": "{\n\tauth, err := c.Sys().ListAuth()\n\tif err != nil {\n\t\treturn false\n\t}\n\tfor a := range auth {\n\t\tif strings.TrimSuffix(a, \"/\") == name {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package messages\n\ntype LocVelDistTraveledMessage struct {\n\tX float64\n\tY float64\n\tZ float64\n\tXv float64\n\tYv float64\n\tZv float64\n}\n\nfunc NewLocVelDistTraveledMessage(data []float32) LocVelDistTraveledMessage {\n\treturn LocVelDistTraveledMessage{\n\t\tY: float64(data[0]),\n\t\tZ: -float64(data[1]),\n\t\tX: -float64(data[2]),\n\t\tYv: float64(data[3]),\n\t\tZv: -float64(data[4]),\n\t\tXv: -float64(data[5]),\n\t}\n}\n\n\n\nfunc (m LocVelDistTraveledMessage) Type() uint ", "output": "{\n\treturn LocVelDistTraveledMessageType\n}"} {"input": "package main\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\n\t_ \"github.com/lib/pq\"\n)\n\n\n\nfunc main() {\n\tdb, err := sql.Open(\"postgres\", \"dbname=test sslmode=disable\")\n\tPanicOn(err)\n\n\t_, err = db.Exec(\"INSERT INTO people(name, ssn) VALUES ($1, $2)\", \"Bruce Leroy\", 111223333)\n\tPanicOn(err)\n\n\t_, err = db.Exec(\"INSERT INTO people(name, ssn) VALUES ($1, $2)\", \"Sho 'Nuff\", 444556666)\n\tPanicOn(err)\n\n\trows, err := db.Query(\"SELECT person_id, name, ssn FROM people\")\n\tPanicOn(err)\n\n\tfor rows.Next() {\n\t\tvar id int\n\t\tvar name string\n\t\tvar ssn int\n\t\terr := rows.Scan(&id, &name, &ssn)\n\t\tPanicOn(err)\n\n\t\tfmt.Printf(\"Person %5d %-15s %9d\\n\", id, name, ssn)\n\t}\n}\n\nfunc PanicOn(err error) ", "output": "{\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package imaging\n\nimport (\n\t\"runtime\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\n\n\n\nfunc parallel(dataSize int, fn func(partStart, partEnd int)) {\n\tnumGoroutines := 1\n\tpartSize := dataSize\n\n\tnumProcs := runtime.GOMAXPROCS(0)\n\tif numProcs > 1 {\n\t\tnumGoroutines = numProcs\n\t\tpartSize = dataSize / (numGoroutines * 10)\n\t\tif partSize < 1 {\n\t\t\tpartSize = 1\n\t\t}\n\t}\n\n\tif numGoroutines == 1 {\n\t\tfn(0, dataSize)\n\t} else {\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(numGoroutines)\n\t\tidx := uint64(0)\n\n\t\tfor p := 0; p < numGoroutines; p++ {\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tfor {\n\t\t\t\t\tpartStart := int(atomic.AddUint64(&idx, uint64(partSize))) - partSize\n\t\t\t\t\tif partStart >= dataSize {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tpartEnd := partStart + partSize\n\t\t\t\t\tif partEnd > dataSize {\n\t\t\t\t\t\tpartEnd = dataSize\n\t\t\t\t\t}\n\t\t\t\t\tfn(partStart, partEnd)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\n\t\twg.Wait()\n\t}\n}\n\n\nfunc absint(i int) int {\n\tif i < 0 {\n\t\treturn -i\n\t}\n\treturn i\n}\n\n\n\n\nfunc clamp(x float64) uint8 ", "output": "{\n\tv := int64(x + 0.5)\n\tif v > 255 {\n\t\treturn 255\n\t}\n\tif v > 0 {\n\t\treturn uint8(v)\n\t}\n\treturn 0\n}"} {"input": "package blanket_emulator\n\nimport (\n\t\"fmt\"\n)\n\ntype Event interface {\n\tHash() uint64\n\tInspect() string\n}\n\ntype ReturnEvent uint64\ntype ReadEvent uint64\ntype WriteEvent struct {\n\tAddr uint64\n\tValue uint64\n}\ntype SyscallEvent uint64\ntype InvalidInstructionEvent uint64\n\nfunc (addr ReadEvent) Hash() uint64 {\n\treturn ReadEventHash(uint64(addr))\n}\n\nfunc (s WriteEvent) Hash() uint64 {\n\treturn WriteEventHash(s.Addr, s.Value)\n}\n\n\n\nfunc (s ReturnEvent) Hash() uint64 {\n\treturn ReturnEventHash(uint64(s))\n}\n\nfunc (s InvalidInstructionEvent) Hash() uint64 {\n\treturn InvalidInstructionEventHash(uint64(s))\n}\n\nfunc (addr ReadEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Read([%x])\", addr)\n}\n\nfunc (addr ReturnEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Return([%x])\", addr)\n}\n\nfunc (s WriteEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Write([%x]=%x)\", s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Sys(%x)\", s)\n}\n\nfunc (s InvalidInstructionEvent) Inspect() string {\n\treturn fmt.Sprintf(\"InvalidOpcode([%x])\", s)\n}\n\nfunc (s SyscallEvent) Hash() uint64 ", "output": "{\n\treturn SysEventHash(uint64(s))\n}"} {"input": "package containerengine\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListWorkRequestLogsRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tWorkRequestId *string `mandatory:\"true\" contributesTo:\"path\" name:\"workRequestId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request ListWorkRequestLogsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request ListWorkRequestLogsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ListWorkRequestLogsRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListWorkRequestLogsResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []WorkRequestLogEntry `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ListWorkRequestLogsResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListWorkRequestLogsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListWorkRequestLogsRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package arbitrary\n\n\nimport \"testing\"\n\nimport \"math/rand\"\nimport \"time\"\n\n\n\n\nfunc TestBool(t *testing.T) ", "output": "{\n\n\tsrc := rand.NewSource( time.Now().UTC().UnixNano() )\n\n\tarb := New(src)\n\n\tseen_false := false\n\tseen_true := false\n\n\tconst limit = 50\n\tfor i:=0; i o\n}\n\n\nfunc (t Timestamp) Add(d native_time.Duration) Timestamp {\n\treturn t + Timestamp(d/MinimumTick)\n}\n\n\nfunc (t Timestamp) Sub(o Timestamp) native_time.Duration {\n\treturn native_time.Duration(t-o) * MinimumTick\n}\n\n\nfunc (t Timestamp) Time() native_time.Time {\n\treturn native_time.Unix(int64(t)/second, (int64(t) % second))\n}\n\n\n\nfunc (t Timestamp) Unix() int64 {\n\treturn int64(t) / second\n}\n\n\nfunc (t Timestamp) String() string {\n\treturn fmt.Sprint(int64(t))\n}\n\n\n\n\n\nfunc TimestampFromTime(t native_time.Time) Timestamp {\n\treturn TimestampFromUnix(t.Unix())\n}\n\n\nfunc TimestampFromUnix(t int64) Timestamp {\n\treturn Timestamp(t * second)\n}\n\nfunc Now() Timestamp ", "output": "{\n\treturn TimestampFromTime(native_time.Now())\n}"} {"input": "package iso20022\n\n\ntype BillingServicesTax2 struct {\n\n\tNumber *Max35Text `xml:\"Nb\"`\n\n\tDescription *Max40Text `xml:\"Desc,omitempty\"`\n\n\tRate *DecimalNumber `xml:\"Rate\"`\n\n\tPricingAmount *AmountAndDirection34 `xml:\"PricgAmt\"`\n}\n\nfunc (b *BillingServicesTax2) SetNumber(value string) {\n\tb.Number = (*Max35Text)(&value)\n}\n\nfunc (b *BillingServicesTax2) SetDescription(value string) {\n\tb.Description = (*Max40Text)(&value)\n}\n\nfunc (b *BillingServicesTax2) SetRate(value string) {\n\tb.Rate = (*DecimalNumber)(&value)\n}\n\n\n\nfunc (b *BillingServicesTax2) AddPricingAmount() *AmountAndDirection34 ", "output": "{\n\tb.PricingAmount = new(AmountAndDirection34)\n\treturn b.PricingAmount\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc pinger(c chan string) {\n\tfor i := 0; ; i++ {\n\t\tc <- \"ping\"\n\t}\n}\n\n\n\nfunc printer(c chan string) {\n\tfor {\n\t\tmsg := <-c\n\t\tfmt.Println(msg)\n\t\ttime.Sleep(time.Second * 1)\n\t}\n}\n\nfunc main() {\n\tvar c chan string = make(chan string)\n\n\tgo pinger(c)\n\tgo ponger(c)\n\tgo printer(c)\n\n\tvar input string\n\tfmt.Scanln(&input)\n}\n\nfunc ponger(c chan string) ", "output": "{\n\tfor i := 0; ; i++ {\n\t\tc <- \"pong\"\n\t}\n}"} {"input": "package iiif\n\nimport (\n\t\"strconv\"\n)\n\n\n\n\ntype Rotation struct {\n\tMirror bool\n\tDegrees float64\n}\n\n\n\n\n\n\n\n\nfunc (r Rotation) Valid() bool {\n\treturn r.Degrees >= 0 && r.Degrees < 360\n}\n\nfunc StringToRotation(p string) Rotation ", "output": "{\n\tr := Rotation{}\n\tif p[0:1] == \"!\" {\n\t\tr.Mirror = true\n\t\tp = p[1:]\n\t}\n\n\tr.Degrees, _ = strconv.ParseFloat(p, 64)\n\n\tif r.Degrees == 360 {\n\t\tr.Degrees = 0\n\t}\n\n\treturn r\n}"} {"input": "package commands\n\nimport (\n\t\"strings\"\n\n\t\"github.com/github/hub/v2/github\"\n\t\"github.com/github/hub/v2/utils\"\n)\n\nvar cmdPush = &Command{\n\tRun: push,\n\tGitExtension: true,\n\tUsage: \"push [,...] []\",\n\tLong: `Push a git branch to each of the listed remotes.\n\n## Examples:\n\t\t$ hub push origin,staging,qa bert_timeout\n\t\t> git push origin bert_timeout\n\t\t> git push staging bert_timeout\n\t\t> git push qa bert_timeout\n\n\t\t$ hub push origin\n\t\t> git push origin HEAD\n\n## See also:\n\nhub(1), git-push(1)\n`,\n}\n\n\n\nfunc push(command *Command, args *Args) {\n\tif !args.IsParamsEmpty() && strings.Contains(args.FirstParam(), \",\") {\n\t\ttransformPushArgs(args)\n\t}\n}\n\nfunc transformPushArgs(args *Args) {\n\trefs := []string{}\n\tif args.ParamsSize() > 1 {\n\t\trefs = args.Params[1:]\n\t}\n\n\tremotes := strings.Split(args.FirstParam(), \",\")\n\targs.ReplaceParam(0, remotes[0])\n\n\tif len(refs) == 0 {\n\t\tlocalRepo, err := github.LocalRepo()\n\t\tutils.Check(err)\n\n\t\thead, err := localRepo.CurrentBranch()\n\t\tutils.Check(err)\n\n\t\trefs = []string{head.ShortName()}\n\t\targs.AppendParams(refs...)\n\t}\n\n\tfor _, remote := range remotes[1:] {\n\t\tafterCmd := []string{\"git\", \"push\", remote}\n\t\tafterCmd = append(afterCmd, refs...)\n\t\targs.After(afterCmd...)\n\t}\n}\n\nfunc init() ", "output": "{\n\tCmdRunner.Use(cmdPush)\n}"} {"input": "package cron\n\nimport (\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com/kyokomi/slackbot/plugins\"\n)\n\ntype plugin struct {\n\tcron CronContext\n}\n\n\n\nfunc (p *plugin) CheckMessage(_ plugins.BotEvent, message string) (bool, string) {\n\tif strings.HasPrefix(message, \"cron\") {\n\t\treturn true, message\n\t}\n\treturn false, message\n}\n\nfunc (p *plugin) DoAction(event plugins.BotEvent, message string) bool {\n\tc := CronCommand{}\n\tif err := c.Scan(message); err != nil {\n\t\tlog.Printf(\"error %s\", err)\n\t\treturn false\n\t}\n\n\tswitch c.Action {\n\tcase AddAction, RandomAddAction:\n\t\tmessage := p.cron.AddCronCommand(event.Channel(), c)\n\t\tp.cron.RefreshCron(&event, event.Channel())\n\t\tevent.Reply(message)\n\tcase DelAction, DeleteAction, StopAction:\n\t\tmessage := p.cron.DelCronCommand(event.Channel(), c)\n\t\tp.cron.RefreshCron(&event, event.Channel())\n\t\tevent.Reply(message)\n\tcase ListAction:\n\t\tmessage := p.cron.ListCronCommand(event.Channel(), c)\n\t\tevent.Reply(message)\n\tcase RefreshAction:\n\t\tp.cron.RefreshCron(&event, event.Channel())\n\t\tevent.Reply(\"```\\nrefresh ok\\n```\")\n\tcase HelpAction:\n\t\tmessage := p.cron.HelpCronCommand(event.Channel(), c)\n\t\tevent.Reply(message)\n\t}\n\treturn false\n}\n\nfunc (p *plugin) Help() string {\n\treturn \"cron: cron制御できます\\n\" + helpText\n}\n\nvar _ plugins.BotMessagePlugin = (*plugin)(nil)\n\nfunc NewPlugin(cron CronContext) plugins.BotMessagePlugin ", "output": "{\n\treturn &plugin{\n\t\tcron: cron,\n\t}\n}"} {"input": "package logs\n\nconst (\n\tErrorLevel = iota\n\tWarnLevel\n\tInfoLevel\n\tDebugLevel\n)\n\ntype Level uint32\n\nfunc (l Level) EQ(lv Level) bool {\n\tif l == lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) LTE(lv Level) bool {\n\tif l <= lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) LT(lv Level) bool {\n\tif l < lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) GTE(lv Level) bool {\n\tif l >= lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc (l Level) Color() int {\n\tvar levelColor int\n\tswitch l {\n\tcase DebugLevel:\n\t\tlevelColor = 32\n\tcase InfoLevel:\n\t\tlevelColor = 36\n\tcase WarnLevel:\n\t\tlevelColor = 33\n\tcase ErrorLevel:\n\t\tlevelColor = 31\n\tdefault:\n\t\tlevelColor = 0\n\t}\n\treturn levelColor\n}\n\nfunc (l Level) String() string {\n\tswitch l {\n\tcase DebugLevel:\n\t\treturn \"DEBU\"\n\tcase InfoLevel:\n\t\treturn \"INFO\"\n\tcase WarnLevel:\n\t\treturn \"WARN\"\n\tcase ErrorLevel:\n\t\treturn \"ERRO\"\n\t}\n\treturn \" \"\n}\n\nfunc (l Level) GT(lv Level) bool ", "output": "{\n\tif l > lv {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package mysql\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\n\n\n\n\ntype GTID interface {\n\tString() string\n\n\tFlavor() string\n\n\tSourceServer() interface{}\n\n\tSequenceNumber() interface{}\n\n\tSequenceDomain() interface{}\n\n\tGTIDSet() GTIDSet\n}\n\n\nvar gtidParsers = make(map[string]func(string) (GTID, error))\n\n\nfunc ParseGTID(flavor, value string) (GTID, error) {\n\tparser := gtidParsers[flavor]\n\tif parser == nil {\n\t\treturn nil, fmt.Errorf(\"parse error: unknown GTID flavor %#v\", flavor)\n\t}\n\treturn parser(value)\n}\n\n\nfunc MustParseGTID(flavor, value string) GTID {\n\tgtid, err := ParseGTID(flavor, value)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn gtid\n}\n\n\n\n\nfunc EncodeGTID(gtid GTID) string {\n\tif gtid == nil {\n\t\treturn \"\"\n\t}\n\n\treturn fmt.Sprintf(\"%s/%s\", gtid.Flavor(), gtid.String())\n}\n\n\n\nfunc DecodeGTID(s string) (GTID, error) {\n\tif s == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tparts := strings.SplitN(s, \"/\", 2)\n\tif len(parts) != 2 {\n\t\treturn ParseGTID(\"\", s)\n\t}\n\treturn ParseGTID(parts[0], parts[1])\n}\n\n\n\n\nfunc MustDecodeGTID(s string) GTID ", "output": "{\n\tgtid, err := DecodeGTID(s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn gtid\n}"} {"input": "package core\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/mattbaird/elastigo/api\"\n)\n\n\n\n\n\ntype Validation struct {\n\tValid bool `json:\"valid\"`\n\tShards api.Status `json:\"_shards\"`\n\tExplainations []Explaination `json:\"explanations,omitempty\"`\n}\n\ntype Explaination struct {\n\tIndex string `json:\"index\"`\n\tValid bool `json:\"valid\"`\n\tError string `json:\"error\"`\n}\n\nfunc Validate(index string, _type string, args map[string]interface{}) (api.BaseResponse, error) ", "output": "{\n\tvar url string\n\tvar retval api.BaseResponse\n\tif len(_type) > 0 {\n\t\turl = fmt.Sprintf(\"/%s/%s/_validate/\", index, _type)\n\t} else {\n\t\turl = fmt.Sprintf(\"/%s/_validate/\", index)\n\t}\n\tbody, err := api.DoCommand(\"GET\", url, args, nil)\n\tif err != nil {\n\t\treturn retval, err\n\t}\n\tif err == nil {\n\t\tjsonErr := json.Unmarshal(body, &retval)\n\t\tif jsonErr != nil {\n\t\t\treturn retval, jsonErr\n\t\t}\n\t}\n\treturn retval, err\n}"} {"input": "package multidict_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n\n\t\"github.com/onsi/ginkgo/reporters\"\n\n\t\"github.com/projectcalico/calico/libcalico-go/lib/testutils\"\n)\n\nfunc init() {\n\ttestutils.HookLogrusForGinkgo()\n}\n\n\n\nfunc TestMultidict(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tjunitReporter := reporters.NewJUnitReporter(\"../report/multidict_suite.xml\")\n\tRunSpecsWithDefaultAndCustomReporters(t, \"Multidict Suite\", []Reporter{junitReporter})\n}"} {"input": "package printer\n\nimport (\n\t\"bytes\"\n\t\"k8s.io/kubernetes/third_party/golang/go/ast\"\n\t\"k8s.io/kubernetes/third_party/golang/go/parser\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"testing\"\n)\n\nvar testfile *ast.File\n\nfunc testprint(out io.Writer, file *ast.File) {\n\tif err := (&Config{TabIndent | UseSpaces, 8, 0}).Fprint(out, fset, file); err != nil {\n\t\tlog.Fatalf(\"print error: %s\", err)\n\t}\n}\n\n\nfunc initialize() {\n\tconst filename = \"testdata/parser.go\"\n\n\tsrc, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\n\tfile, err := parser.ParseFile(fset, filename, src, parser.ParseComments)\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\n\tvar buf bytes.Buffer\n\ttestprint(&buf, file)\n\tif !bytes.Equal(buf.Bytes(), src) {\n\t\tlog.Fatalf(\"print error: %s not idempotent\", filename)\n\t}\n\n\ttestfile = file\n}\n\n\n\nfunc BenchmarkPrint(b *testing.B) ", "output": "{\n\tif testfile == nil {\n\t\tinitialize()\n\t}\n\tfor i := 0; i < b.N; i++ {\n\t\ttestprint(ioutil.Discard, testfile)\n\t}\n}"} {"input": "package loggo\n\nvar (\n\tdefaultContext = newDefaultContxt()\n)\n\nfunc newDefaultContxt() *Context {\n\tctx := NewContext(WARNING)\n\tctx.AddWriter(DefaultWriterName, defaultWriter())\n\treturn ctx\n}\n\n\nfunc DefaultContext() *Context {\n\treturn defaultContext\n}\n\n\n\n\n\nfunc LoggerInfo() string {\n\treturn defaultContext.Config().String()\n}\n\n\n\nfunc GetLogger(name string, size ...int) Logger {\n\treturn defaultContext.GetLogger(name, size...)\n}\n\n\n\n\n\nfunc ResetLogging() {\n\tdefaultContext.ResetLoggerLevels()\n\tdefaultContext.ResetWriters()\n}\n\n\nfunc ResetWriters() {\n\tdefaultContext.ResetWriters()\n}\n\n\n\n\nfunc ReplaceDefaultWriter(writer Writer) (Writer, error) {\n\treturn defaultContext.ReplaceWriter(DefaultWriterName, writer)\n}\n\n\n\n\nfunc RegisterWriter(name string, writer Writer) error {\n\treturn defaultContext.AddWriter(name, writer)\n}\n\n\n\nfunc RemoveWriter(name string) (Writer, error) {\n\treturn defaultContext.RemoveWriter(name)\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ConfigureLoggers(specification string) error ", "output": "{\n\tconfig, err := ParseConfigString(specification)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefaultContext.ApplyConfig(config)\n\treturn nil\n}"} {"input": "package web\n\nimport (\n\t\"net/http\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype StatusHandler struct {\n\tmu sync.Mutex\n\n\tBuildInfo map[string]string\n\tConfig string\n\tFlags map[string]string\n\tBirth time.Time\n}\n\n\n\nfunc (h *StatusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\texecuteTemplate(w, \"status\", h)\n}\n\nfunc (h *StatusHandler) UpdateConfig(c string) ", "output": "{\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\th.Config = c\n}"} {"input": "package template\n\nimport (\n\t\"io\"\n)\n\ntype astImport struct {\n\talias string\n\tpkgName string\n}\n\nfunc (*astImport) GetImports() []string { return []string{} }\n\n\n\nfunc (n *astImport) WriteGo(w io.Writer, opts *GenGoOpts) {\n\tif n.alias != \"\" {\n\t\tio.WriteString(w, n.alias+\" \")\n\t}\n\tio.WriteString(w, n.pkgName+\"\\n\")\n}\n\nfunc (*astImport) GetStrings() []string ", "output": "{ return []string{} }"} {"input": "package v1alpha1\n\nimport (\n\tv1alpha1 \"github.com/appscode/searchlight/apis/incidents/v1alpha1\"\n\t\"github.com/appscode/searchlight/client/clientset/versioned/scheme\"\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype IncidentsV1alpha1Interface interface {\n\tRESTClient() rest.Interface\n\tAcknowledgementsGetter\n}\n\n\ntype IncidentsV1alpha1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *IncidentsV1alpha1Client) Acknowledgements(namespace string) AcknowledgementInterface {\n\treturn newAcknowledgements(c, namespace)\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *IncidentsV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *IncidentsV1alpha1Client {\n\treturn &IncidentsV1alpha1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *IncidentsV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfig(c *rest.Config) (*IncidentsV1alpha1Client, error) ", "output": "{\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &IncidentsV1alpha1Client{client}, nil\n}"} {"input": "package format\n\nimport (\n\t\"github.com/kitwalker12/fotomat/vips\"\n)\n\n\ntype Metadata struct {\n\tWidth int\n\tHeight int\n\tFormat Format\n\tOrientation Orientation\n\tHasAlpha bool\n}\n\n\nfunc MetadataBytes(blob []byte) (Metadata, error) {\n\tformat := DetectFormat(blob)\n\tif format == Unknown {\n\t\treturn Metadata{}, ErrUnknownFormat\n\t}\n\n\treturn format.MetadataBytes(blob)\n}\n\n\nfunc (format Format) MetadataBytes(blob []byte) (Metadata, error) {\n\timage, err := format.LoadBytes(blob)\n\tif err != nil {\n\t\treturn Metadata{}, ErrUnknownFormat\n\t}\n\n\tdefer image.Close()\n\n\treturn metadataImageFormat(image, format), nil\n}\n\n\n\n\nfunc metadataImageFormat(image *vips.Image, format Format) Metadata {\n\tm := MetadataImage(image)\n\tm.Format = format\n\treturn m\n}\n\n\nfunc MetadataImage(image *vips.Image) Metadata {\n\to := DetectOrientation(image)\n\tw, h := o.Dimensions(image.Xsize(), image.Ysize())\n\tif w <= 0 || h <= 0 {\n\t\tpanic(\"Invalid image dimensions.\")\n\t}\n\treturn Metadata{Width: w, Height: h, Orientation: o, HasAlpha: image.HasAlpha()}\n}\n\nfunc (format Format) MetadataFile(filename string) (Metadata, error) ", "output": "{\n\timage, err := format.LoadFile(filename)\n\tif err != nil {\n\t\treturn Metadata{}, err\n\t}\n\n\tdefer image.Close()\n\n\treturn metadataImageFormat(image, format), nil\n}"} {"input": "package version\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype Command struct {\n\tName string\n\tW io.Writer\n\tWErr io.Writer\n\tAppName string\n\tAppVersion string\n\tGitCommit string\n}\n\n\nfunc (c *Command) Run(args []string) (int, error) {\n\tfmt.Fprintln(c.W, c.AppName, c.AppVersion, c.GitCommit)\n\treturn 0, nil\n}\n\n\nfunc (c *Command) Key() string {\n\treturn c.Name\n}\n\n\n\nfunc (c *Command) Aliases() map[string]struct{} {\n\treturn map[string]struct{}{\n\t\t\"version\": struct{}{},\n\t}\n}\n\n\n\n\nfunc (c *Command) Description() string ", "output": "{\n\treturn \"Print the version.\"\n}"} {"input": "package main\n\nimport \"github.com/nsf/termbox-go\"\n\ntype Input struct {\n\tendKey termbox.Key\n\teventQ chan termbox.Event\n\tctrl chan bool\n}\n\nfunc NewInput() *Input {\n\treturn &Input{\n\t\tendKey: termbox.KeyCtrlC,\n\t\teventQ: make(chan termbox.Event),\n\t\tctrl: make(chan bool, 2),\n\t}\n}\n\n\n\nfunc (i *Input) Stop() {\n\ti.ctrl <- true\n}\n\nfunc poll(i *Input) {\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-i.ctrl:\n\t\t\tbreak loop\n\t\tdefault:\n\t\t\ti.eventQ <- termbox.PollEvent()\n\t\t}\n\t}\n}\n\nfunc (i *Input) Start() ", "output": "{\n\tgo poll(i)\n}"} {"input": "package cmd\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestExecuteClienAddCmd(t *testing.T) {\n\tassert.Nil(t, nil)\n}\n\nfunc GetErrorMessage(err error) string ", "output": "{\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\treturn \"\"\n}"} {"input": "package httpd\n\nimport (\n\t\"bufio\"\n\t\"net/http\"\n\n\t\"github.com/Cloud-Foundations/Dominator/lib/json\"\n)\n\n\n\nfunc (s state) listAvailableAddressesHandler(w http.ResponseWriter,\n\treq *http.Request) ", "output": "{\n\twriter := bufio.NewWriter(w)\n\tdefer writer.Flush()\n\taddresses := s.manager.ListAvailableAddresses()\n\tjson.WriteWithIndent(writer, \" \", addresses)\n}"} {"input": "package kapacitor\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\n\t\"github.com/influxdata/influxdb/chronograf\"\n\t\"github.com/influxdata/kapacitor/pipeline\"\n\ttotick \"github.com/influxdata/kapacitor/pipeline/tick\"\n)\n\n\n\n\n\nfunc UnmarshalTICK(octets []byte) (string, error) {\n\tpipe := &pipeline.Pipeline{}\n\tif err := pipe.Unmarshal(octets); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tast := totick.AST{}\n\terr := ast.Build(pipe)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar buf bytes.Buffer\n\tast.Program.Format(&buf, \"\", false)\n\treturn buf.String(), nil\n}\n\nfunc MarshalTICK(script string) ([]byte, error) ", "output": "{\n\tpipeline, err := newPipeline(chronograf.TICKScript(script))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn json.MarshalIndent(pipeline, \"\", \" \")\n}"} {"input": "package x11\n\nimport (\n\t\"C\"\n\t\"unsafe\"\n)\n\ntype ConfigureEvent C.XConfigureEvent\n\nfunc (evt *ConfigureEvent) Window() Window {\n\treturn Window(evt.window)\n}\n\n\n\nfunc (evt *ConfigureEvent) ToEvent() *Event ", "output": "{\n\treturn (*Event)(unsafe.Pointer(evt))\n}"} {"input": "package ps\n\n\n\ntype Process interface {\n\tPid() int\n\n\tPPid() int\n\n\tCPids() []int\n\n\tExecutable() string\n}\n\n\n\n\n\n\n\nfunc Processes() ([]Process, error) {\n\treturn processes()\n}\n\n\n\n\n\nfunc FindProcessByPid(pid int) (Process, error) {\n\treturn findProcessByPid(pid)\n}\n\n\n\n\n\n\n\nfunc FindProcessByExecutable(name string) ([]Process, error) ", "output": "{\n\treturn findProcessByExecutable(name)\n}"} {"input": "package unitassigner\n\nimport (\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/worker/v2\"\n\t\"github.com/juju/worker/v2/dependency\"\n\n\t\"github.com/juju/juju/api/base\"\n\t\"github.com/juju/juju/api/unitassigner\"\n\t\"github.com/juju/juju/cmd/jujud/agent/engine\"\n)\n\n\ntype Logger interface {\n\tTracef(string, ...interface{})\n}\n\n\ntype ManifoldConfig struct {\n\tAPICallerName string\n\tLogger Logger\n}\n\n\nfunc Manifold(config ManifoldConfig) dependency.Manifold {\n\treturn engine.APIManifold(\n\t\tengine.APIManifoldConfig{\n\t\t\tAPICallerName: config.APICallerName,\n\t\t},\n\t\tconfig.start,\n\t)\n}\n\n\n\n\nfunc (c *ManifoldConfig) start(apiCaller base.APICaller) (worker.Worker, error) ", "output": "{\n\tfacade := unitassigner.New(apiCaller)\n\tworker, err := New(facade, c.Logger)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treturn worker, nil\n}"} {"input": "package otelhttp\n\n\nfunc Version() string {\n\treturn \"0.29.0\"\n}\n\n\n\n\nfunc SemVersion() string ", "output": "{\n\treturn \"semver:\" + Version()\n}"} {"input": "package muc\n\nimport \"strings\"\n\n\ntype RoomConfigFieldTextMultiValue struct {\n\tvalue []string\n}\n\nfunc newRoomConfigFieldTextMultiValue(values []string) *RoomConfigFieldTextMultiValue {\n\treturn &RoomConfigFieldTextMultiValue{values}\n}\n\n\nfunc (v *RoomConfigFieldTextMultiValue) Value() []string {\n\treturn v.value\n}\n\n\n\n\n\nfunc (v *RoomConfigFieldTextMultiValue) Text() string {\n\treturn strings.Join(v.Value(), \" \")\n}\n\nfunc (v *RoomConfigFieldTextMultiValue) SetText(lines []string) ", "output": "{\n\tv.value = lines\n}"} {"input": "package iso20022\n\n\ntype CardPaymentBatchTransferResponse1 struct {\n\n\tTransactionTotals *TransactionTotals2 `xml:\"TxTtls\"`\n\n\tDataSet []*CardPaymentDataSet5 `xml:\"DataSet,omitempty\"`\n}\n\n\n\nfunc (c *CardPaymentBatchTransferResponse1) AddDataSet() *CardPaymentDataSet5 {\n\tnewValue := new(CardPaymentDataSet5)\n\tc.DataSet = append(c.DataSet, newValue)\n\treturn newValue\n}\n\nfunc (c *CardPaymentBatchTransferResponse1) AddTransactionTotals() *TransactionTotals2 ", "output": "{\n\tc.TransactionTotals = new(TransactionTotals2)\n\treturn c.TransactionTotals\n}"} {"input": "package math\n\n\n\nfunc initUint64Go() ", "output": "{\n\tUint64.sum = sum_uint64_go\n}"} {"input": "package vault\n\nimport \"time\"\n\ntype dynamicSystemView struct {\n\tcore *Core\n\tmountEntry *MountEntry\n}\n\n\n\nfunc (d dynamicSystemView) MaxLeaseTTL() time.Duration {\n\t_, max := d.fetchTTLs()\n\treturn max\n}\n\n\n\nfunc (d dynamicSystemView) fetchTTLs() (def, max time.Duration) {\n\tdef = d.core.defaultLeaseTTL\n\tmax = d.core.maxLeaseTTL\n\n\tif d.mountEntry.Config.DefaultLeaseTTL != 0 {\n\t\tdef = d.mountEntry.Config.DefaultLeaseTTL\n\t}\n\tif d.mountEntry.Config.MaxLeaseTTL != 0 {\n\t\tmax = d.mountEntry.Config.MaxLeaseTTL\n\t}\n\n\treturn\n}\n\nfunc (d dynamicSystemView) DefaultLeaseTTL() time.Duration ", "output": "{\n\tdef, _ := d.fetchTTLs()\n\treturn def\n}"} {"input": "package entity\n\nimport (\n\t\"context\"\n\n\t\"github.com/utahta/momoclo-channel/dao\"\n)\n\ntype (\n\tReminderRepository interface {\n\t\tFindAll(context.Context) ([]*Reminder, error)\n\t\tSave(context.Context, *Reminder) error\n\t}\n\n\treminderRepository struct {\n\t\tdao.PersistenceHandler\n\t}\n)\n\n\nfunc NewReminderRepository(h dao.PersistenceHandler) ReminderRepository {\n\treturn &reminderRepository{h}\n}\n\n\nfunc (repo *reminderRepository) FindAll(ctx context.Context) ([]*Reminder, error) {\n\tkind := repo.Kind(ctx, &Reminder{})\n\tq := repo.NewQuery(kind).Filter(\"Enabled =\", true)\n\n\tvar dst []*Reminder\n\treturn dst, repo.GetAll(ctx, q, &dst)\n}\n\n\n\n\nfunc (repo *reminderRepository) Save(ctx context.Context, item *Reminder) error ", "output": "{\n\treturn repo.Put(ctx, item)\n}"} {"input": "package job\n\nimport (\n\tsj \"github.com/bitly/go-simplejson\"\n)\n\ntype Item struct {\n\tCategory string\n\tId string\n\tContent string\n\tRawMsg string\n}\n\ntype Processor interface {\n\tInit(ctx *sj.Json, id int, itemChans [](chan Item)) error\n\tProcess(msg string) error\n\tTick() error\n\tDestory() error\n}\n\ntype Collector interface {\n\tInit(ctx *sj.Json, id int) error\n\tCollect(item Item) error\n\tTick() error\n\tDestory() error\n}\n\nfunc NewProcessor(name string) Processor {\n\tswitch name {\n\tcase \"LogtoHdfsProcessor\":\n\t\treturn new(LogtoHdfsProcessor)\n\tcase \"TestProcessor\":\n\t\treturn new(TestProcessor)\n\tdefault:\n\t\treturn nil\n\t}\n\treturn nil\n}\n\n\n\nfunc NewCollector(name string) Collector ", "output": "{\n\tswitch name {\n\tcase \"LogtoHdfsCollector\":\n\t\treturn new(LogtoHdfsCollector)\n\tcase \"TestCollector\":\n\t\treturn new(TestCollector)\n\tdefault:\n\t\treturn nil\n\t}\n\treturn nil\n}"} {"input": "package traversal\n\nimport \"strconv\"\n\nconst _Token_name = \"ILLEGALEOFWSIDENTCOMMADOTLEFTPARENTHESISRIGHTPARENTHESISSTRINGNUMBERGVEHASHASKEYHASNOTHASEITHEROUTINOUTVINVBOTHVOUTEINEBOTHEDEDUPWITHINWITHOUTMETADATASHORTESTPATHTONENEEBOTHCONTEXTREGEXLTGTLTEGTEINSIDEOUTSIDEBETWEENCOUNTRANGELIMITSORTVALUESKEYSSUMASCDESCIPV4RANGESUBGRAPHFOREVERNOWASSELECTTRUEFALSE\"\n\nvar _Token_index = [...]uint16{0, 7, 10, 12, 17, 22, 25, 40, 56, 62, 68, 69, 70, 71, 74, 80, 86, 95, 98, 100, 104, 107, 112, 116, 119, 124, 129, 135, 142, 150, 164, 166, 169, 173, 180, 185, 187, 189, 192, 195, 201, 208, 215, 220, 225, 230, 234, 240, 244, 247, 250, 254, 263, 271, 278, 281, 283, 289, 293, 298}\n\n\n\nfunc (i Token) String() string ", "output": "{\n\tif i < 0 || i >= Token(len(_Token_index)-1) {\n\t\treturn \"Token(\" + strconv.FormatInt(int64(i), 10) + \")\"\n\t}\n\treturn _Token_name[_Token_index[i]:_Token_index[i+1]]\n}"} {"input": "package glw\n\nimport \"golang.org/x/mobile/gl\"\n\ntype A2fv gl.Attrib\n\nfunc (a A2fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A2fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A2fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 2, gl.FLOAT, false, 0, 0)\n}\n\ntype A3fv gl.Attrib\n\n\nfunc (a A3fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A3fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 3, gl.FLOAT, false, 0, 0)\n}\n\ntype A4fv gl.Attrib\n\nfunc (a A4fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A4fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }\nfunc (a A4fv) Pointer() {\n\ta.Enable()\n\tctx.VertexAttribPointer(gl.Attrib(a), 4, gl.FLOAT, false, 0, 0)\n}\n\nfunc (a A3fv) Enable() ", "output": "{ ctx.EnableVertexAttribArray(gl.Attrib(a)) }"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\nfunc noKeyErr(key string) error {\n\treturn fmt.Errorf(\"no key %s found\", key)\n}\n\nfunc keyExistsIface(m *map[string]interface{}, key string) bool {\n\t_, ok := (*m)[key]\n\treturn ok\n}\n\nfunc keyExistsStr(m *map[string]string, key string) bool {\n\t_, ok := (*m)[key]\n\treturn ok\n}\n\n\n\n\n\n\nfunc setInMap(m interface{}, path []string, newVal interface{}) (interface{}, error) {\n\tif len(path) == 0 {\n\t\treturn newVal, nil\n\t}\n\n\tkey := path[0]\n\ttermErr := fmt.Errorf(\"path terminates early at %s\", key)\n\trem := path[1:]\n\n\tval := reflect.ValueOf(m)\n\tswitch val.Kind() {\n\tcase reflect.Map:\n\t\tkeys := val.MapKeys()\n\t\tfound := false\n\t\tfor _, k := range keys {\n\t\t\tif reflect.DeepEqual(k.Interface(), key) {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\treturn nil, termErr\n\t\t}\n\t\tsubMap := val.MapIndex(reflect.ValueOf(key))\n\t\tnewSubMap, err := setInMap(subMap.Interface(), rem, newVal)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tval.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(newSubMap))\n\t\treturn val.Interface(), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"value at path %s is unsupported type %T\", key, m)\n\t}\n}\n\nfunc keyExistsInt(m *map[string]int, key string) bool ", "output": "{\n\t_, ok := (*m)[key]\n\treturn ok\n}"} {"input": "package bridge\n\nimport \"github.com/vishvananda/netlink\"\n\n\n\nfunc findIPv6Address(addr netlink.Addr, addresses []netlink.Addr) bool {\n\tfor _, addrv6 := range addresses {\n\t\tif addrv6.String() == addr.String() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc setupVerifyAndReconcile(config *NetworkConfiguration, i *bridgeInterface) error ", "output": "{\n\taddrv4, addrsv6, err := i.addresses()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif addrv4.IPNet == nil {\n\t\treturn ErrNoIPAddr\n\t}\n\n\tif config.AddressIPv4 != nil && !addrv4.IP.Equal(config.AddressIPv4.IP) {\n\t\treturn &IPv4AddrNoMatchError{ip: addrv4.IP, cfgIP: config.AddressIPv4.IP}\n\t}\n\n\tif config.EnableIPv6 && !findIPv6Address(netlink.Addr{IPNet: bridgeIPv6}, addrsv6) {\n\t\treturn (*IPv6AddrNoMatchError)(bridgeIPv6)\n\t}\n\n\ti.bridgeIPv4 = addrv4.IPNet\n\ti.bridgeIPv6 = bridgeIPv6\n\n\treturn nil\n}"} {"input": "package qtypes\n\nimport (\n\t\"strings\"\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/qnib/qframe-utils\"\n\t\"fmt\"\n)\n\nconst (\n\tMsgCEE = \"cee\"\n\tMsgTCP = \"tcp\"\n\tMsgFile = \"file\"\n\tMsgDLOG = \"docker-log\"\n\tMsgMetric = \"metric\" \n)\n\n\ntype Message struct {\n\tBase\n\tContainer types.ContainerJSON\n\tName \tstring \t`json:\"name\"`\n\tLogLevel string\t\t\t\t`json:\"loglevel\"`\n\tMessageType\tstring \t`json:\"type\"`\n\tMessage string \t`json:\"value\"`\n\tKV\t\t\tmap[string]string \t`json:\"data\"`\n}\n\nfunc NewMessage(base Base, name, mType, msg string) Message {\n\tm := Message{\n\t\tBase: base,\n\t\tName: name,\n\t\tContainer: types.ContainerJSON{},\n\t\tLogLevel: \"INFO\",\n\t\tMessageType: mType,\n\t\tMessage: msg,\n\t\tKV: map[string]string{},\n\t}\n\tm.SourceID = int(qutils.GetGID())\n\treturn m\n}\n\n\n\n\nfunc (m *Message) GenContainerMsgID() string {\n\ts := fmt.Sprintf(\"%s-%d-%s\", m.Container.ID, m.Time.UnixNano(), m.Message)\n\treturn Sha1HashString(s)\n}\n\nfunc (m *Message) GetContainerName() string {\n\tif m.Container.Name != \"\" {\n\t\treturn strings.Trim(m.Container.Name, \"/\")\n\t} else {\n\t\treturn \"\"\n\t}\n}\n\nfunc NewContainerMessage(base Base, cnt types.ContainerJSON, name, mType, msg string) Message ", "output": "{\n\tm := NewMessage(base, name, mType, msg)\n\tm.Container = cnt\n\tm.ID = m.GenContainerMsgID()\n\treturn m\n}"} {"input": "package drum\n\nimport \"fmt\"\n\n\n\ntype Pattern struct {\n\tversion Version\n\ttempo Tempo\n\ttracks Tracks\n}\n\nfunc (p Pattern) String() string {\n\treturn fmt.Sprintf(\"%s\\n%s\\n%s\", p.version.String(), p.tempo.String(), p.tracks.String())\n}\n\n\ntype Version string\n\nfunc (v Version) String() string {\n\treturn fmt.Sprintf(\"Saved with HW Version: %s\", string(v))\n}\n\n\ntype Tempo float64\n\n\n\n\ntype Tracks []Track\n\nfunc (t Tracks) String() string {\n\tpretty := \"\"\n\tfor _, track := range t {\n\t\tpretty = fmt.Sprintf(\"%s%s\\n\", pretty, track.String())\n\t}\n\treturn pretty\n}\n\n\ntype Track struct {\n\tID int\n\tName string\n\tSteps Steps\n}\n\nfunc (t Track) String() string {\n\treturn fmt.Sprintf(\"(%d) %s\\t%s\", t.ID, t.Name, t.Steps.String())\n}\n\n\ntype Steps struct {\n\tBars [4]Bar\n}\n\nfunc (s Steps) String() string {\n\tpretty := \"|\"\n\tfor _, bar := range s.Bars {\n\t\tpretty = pretty + bar.String() + \"|\"\n\t}\n\treturn pretty\n}\n\n\ntype Bar [4]Note\n\nfunc (bar Bar) String() string {\n\tpretty := \"\"\n\tfor _, note := range bar {\n\t\tpretty = pretty + note.String()\n\t}\n\treturn pretty\n}\n\n\ntype Note bool\n\nfunc (n Note) String() string {\n\tif n {\n\t\treturn \"x\"\n\t}\n\treturn \"-\"\n}\n\nfunc (t Tempo) String() string ", "output": "{\n\treturn fmt.Sprintf(\"Tempo: %.3g\", t)\n}"} {"input": "package analyzer\n\nimport (\n . \"github.com/levythu/gurgling\"\n \"time\"\n \"fmt\"\n \"strconv\"\n)\n\n\n\ntype SimpleAnalyzer struct {\n \n}\n\nfunc ASimpleAnalyzer() Sandwich {\n return &SimpleAnalyzer{}\n}\n\nconst token_returncode=\"SimpleAnalyzer-Status-Code\"\nconst token_starttime=\"SimpleAnalyzer-Start-Time\"\n\nfunc logCode(res Response, c int) {\n res.F()[token_returncode]=c\n}\n\nfunc (this *SimpleAnalyzer)Handler(req Request, res Response) (bool, Request, Response) {\n var newRes=&logResponse {\n o: res,\n OnHeadSent: logCode,\n }\n newRes.F()[token_starttime]=time.Now().UnixNano()\n return true, req, newRes\n}\n\n\nfunc (this *SimpleAnalyzer)Final(req Request, res Response) ", "output": "{\n var timeStart, ok=res.F()[token_starttime].(int64)\n var timeElpase string\n if ok {\n var t=time.Now().UnixNano()\n timeElpase=strconv.FormatInt((t-timeStart)/1000000, 10)+\"ms\"\n } else {\n timeElpase=\"xxxx\"\n }\n\n var statusCode, ok2=res.F()[token_returncode].(int)\n var codeStr string\n if ok2 {\n codeStr=strconv.Itoa(statusCode)\n } else {\n codeStr=\"---\"\n }\n\n var url=req.R().URL\n fmt.Print(\"- \"+timeElpase+\"\\t\\t\"+codeStr+\"\\t\"+req.Method()+\"\\t\"+url.Path)\n if url.RawQuery!=\"\" {\n fmt.Println(\"?\"+url.RawQuery)\n } else {\n fmt.Println(\"\")\n }\n}"} {"input": "package lago\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\ntype ScopedLogger struct {\n\tlog Logger\n\tscp string\n\tfmt string\n}\n\n\nfunc NewScopedLogger(log Logger, scope string, padding int) *ScopedLogger {\n\tformat := \"-%\" + intToStringWithSign(padding) + \"s: %s\"\n\n\tl := &ScopedLogger{\n\t\tlog: log,\n\t\tscp: scope,\n\t\tfmt: format,\n\t}\n\n\treturn l\n}\n\n\nfunc (l *ScopedLogger) Errorf(format string, args ...interface{}) {\n\tl.log.Errorf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\n\nfunc (l *ScopedLogger) Infof(format string, args ...interface{}) {\n\tl.log.Infof(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\n\n\n\n\nfunc (l *ScopedLogger) Fatalf(format string, args ...interface{}) {\n\tl.log.Fatalf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\nfunc intToStringWithSign(i int) string {\n\ta := strconv.Itoa(i)\n\ts := \"+\"\n\tif i < 0 {\n\t\ts = \"-\"\n\t}\n\ta = s + a\n\n\treturn a\n}\n\nfunc (l *ScopedLogger) Warnf(format string, args ...interface{}) ", "output": "{\n\tl.log.Warnf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}"} {"input": "package archive\n\nimport (\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com/containers/storage/pkg/system\"\n\t\"golang.org/x/sys/unix\"\n)\n\nfunc statDifferent(oldStat *system.StatT, newStat *system.StatT) bool {\n\tif oldStat.Mode() != newStat.Mode() ||\n\t\toldStat.UID() != newStat.UID() ||\n\t\toldStat.GID() != newStat.GID() ||\n\t\toldStat.Rdev() != newStat.Rdev() ||\n\t\t(oldStat.Mode()&unix.S_IFDIR != unix.S_IFDIR &&\n\t\t\t(!sameFsTimeSpec(oldStat.Mtim(), newStat.Mtim()) || (oldStat.Size() != newStat.Size()))) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (info *FileInfo) isDir() bool {\n\treturn info.parent == nil || info.stat.Mode()&unix.S_IFDIR != 0\n}\n\nfunc getIno(fi os.FileInfo) uint64 {\n\treturn fi.Sys().(*syscall.Stat_t).Ino\n}\n\n\n\nfunc hasHardlinks(fi os.FileInfo) bool ", "output": "{\n\treturn fi.Sys().(*syscall.Stat_t).Nlink > 1\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\tapicommon \"github.com/hoffie/larasync/api/common\"\n)\n\n\n\n\nfunc (d *Dispatcher) adminSecretAction() int ", "output": "{\n\tif len(d.context.Args()) != 0 {\n\t\tfmt.Fprint(d.stderr, \"Error: this command takes no args\\n\")\n\t\treturn 1\n\t}\n\tadminSecret, err := d.promptPassword(\"Admin secret: \")\n\tif err != nil {\n\t\tfmt.Fprint(d.stderr, \"Error: unable to read the admin secret\\n\")\n\t\treturn 1\n\t}\n\tadminPubkey, err := apicommon.GetAdminSecretPubkey(adminSecret)\n\tif err != nil {\n\t\tfmt.Fprintf(d.stderr, \"Error: public key retrieval failed(%s)\\n\", err)\n\t\treturn 1\n\t}\n\tfmt.Fprintf(d.stdout, \"# Enter the following value into your server config\\n%x\\n\",\n\t\tadminPubkey)\n\treturn 0\n}"} {"input": "package sw\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\n\t\"github.com/hyperledger/fabric/core/crypto/bccsp\"\n\t\"github.com/hyperledger/fabric/core/crypto/primitives\"\n)\n\ntype rsaPrivateKey struct {\n\tk *rsa.PrivateKey\n}\n\n\n\nfunc (k *rsaPrivateKey) Bytes() (raw []byte, err error) {\n\treturn\n}\n\n\nfunc (k *rsaPrivateKey) SKI() (ski []byte) {\n\traw := x509.MarshalPKCS1PrivateKey(k.k)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\nfunc (k *rsaPrivateKey) Symmetric() bool {\n\treturn false\n}\n\n\n\n\n\n\n\nfunc (k *rsaPrivateKey) PublicKey() (bccsp.Key, error) {\n\treturn &rsaPublicKey{&k.k.PublicKey}, nil\n}\n\ntype rsaPublicKey struct {\n\tk *rsa.PublicKey\n}\n\n\n\nfunc (k *rsaPublicKey) Bytes() (raw []byte, err error) {\n\traw, err = x509.MarshalPKIXPublicKey(k.k)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed marshalling key [%s]\", err)\n\t}\n\treturn\n}\n\n\nfunc (k *rsaPublicKey) SKI() (ski []byte) {\n\traw, _ := primitives.PublicKeyToPEM(k.k, nil)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\nfunc (k *rsaPublicKey) Symmetric() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) Private() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) PublicKey() (bccsp.Key, error) {\n\treturn k, nil\n}\n\nfunc (k *rsaPrivateKey) Private() bool ", "output": "{\n\treturn true\n}"} {"input": "package api\n\nimport (\n\t\"debug/gosym\"\n\t\"github.com/derekparker/delve/proc\"\n)\n\n\nfunc ConvertBreakpoint(bp *proc.Breakpoint) *Breakpoint {\n\treturn &Breakpoint{\n\t\tID: bp.ID,\n\t\tFunctionName: bp.FunctionName,\n\t\tFile: bp.File,\n\t\tLine: bp.Line,\n\t\tAddr: bp.Addr,\n\t}\n}\n\n\nfunc ConvertThread(th *proc.Thread) *Thread {\n\tvar (\n\t\tfunction *Function\n\t\tfile string\n\t\tline int\n\t\tpc uint64\n\t)\n\n\tloc, err := th.Location()\n\tif err == nil {\n\t\tpc = loc.PC\n\t\tfile = loc.File\n\t\tline = loc.Line\n\t\tfunction = ConvertFunction(loc.Fn)\n\t}\n\n\treturn &Thread{\n\t\tID: th.Id,\n\t\tPC: pc,\n\t\tFile: file,\n\t\tLine: line,\n\t\tFunction: function,\n\t}\n}\n\n\nfunc ConvertVar(v *proc.Variable) Variable {\n\treturn Variable{\n\t\tName: v.Name,\n\t\tValue: v.Value,\n\t\tType: v.Type,\n\t}\n}\n\n\n\n\nfunc ConvertGoroutine(g *proc.G) *Goroutine {\n\treturn &Goroutine{\n\t\tID: g.Id,\n\t\tPC: g.PC,\n\t\tFile: g.File,\n\t\tLine: g.Line,\n\t\tFunction: ConvertFunction(g.Func),\n\t}\n}\n\nfunc ConvertLocation(loc proc.Location) Location {\n\treturn Location{\n\t\tPC: loc.PC,\n\t\tFile: loc.File,\n\t\tLine: loc.Line,\n\t\tFunction: ConvertFunction(loc.Fn),\n\t}\n}\n\nfunc ConvertFunction(fn *gosym.Func) *Function ", "output": "{\n\tif fn == nil {\n\t\treturn nil\n\t}\n\n\treturn &Function{\n\t\tName: fn.Name,\n\t\tType: fn.Type,\n\t\tValue: fn.Value,\n\t\tGoType: fn.GoType,\n\t}\n}"} {"input": "package config\n\ntype Dependencies interface {\n\tConfigurator\n\tInstalls() []string\n\tmerge(other Dependencies)\n}\n\nfunc NewDependencies(deps ...string) Dependencies {\n\ts := make(map[string]bool, len(deps))\n\tfor _, dep := range deps {\n\t\ts[dep] = exists\n\t}\n\treturn dependencies{\n\t\tset: s,\n\t}\n}\n\nconst exists = true\n\ntype dependencies struct {\n\tset map[string]bool\n}\n\n\n\nfunc (d dependencies) Configure(cfg Configurable) {\n\tcfg.Config().Dependencies.merge(d)\n}\n\nfunc (d dependencies) merge(other Dependencies) {\n\tfor _, dep := range other.Installs() {\n\t\td.set[dep] = exists\n\t}\n}\n\nfunc (d dependencies) Installs() []string ", "output": "{\n\tkeys := make([]string, len(d.set))\n\n\ti := 0\n\tfor k := range d.set {\n\t\tkeys[i] = k\n\t\ti++\n\t}\n\n\treturn keys\n}"} {"input": "package logger\n\nimport \"context\"\n\ntype loggerKeyType struct{}\n\nvar loggerKey = loggerKeyType{}\n\n\n\n\n\n\n\n\n\nfunc FromContext(ctx context.Context) KayveeLogger {\n\tlogger := ctx.Value(loggerKey)\n\tif lggr, ok := logger.(KayveeLogger); ok {\n\t\treturn lggr\n\t}\n\treturn New(\"\")\n}\n\nfunc NewContext(ctx context.Context, logger KayveeLogger) context.Context ", "output": "{\n\treturn context.WithValue(ctx, loggerKey, logger)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\tprimes \"github.com/whatever/math/primes\"\n\t_ \"math\"\n\t\"sort\"\n)\n\nfunc Factorial(n int) int {\n\tresult := 1\n\tfor n > 0 {\n\t\tresult *= n\n\t\tn--\n\t}\n\treturn result\n}\n\n\n\nfunc IsPermutation(lhs, rhs int) bool {\n\treturn SortedString(fmt.Sprintf(\"%d\", lhs)) == SortedString(fmt.Sprintf(\"%d\", rhs))\n}\n\nfunc main() {\n\tlimit := 1000000\n\ts := primes.NewNaiveSieve(limit)\n\thits := make(map[int]float64)\n\n\tminIndex := 200000000\n\tminValue := float64(limit + 1)\n\n\tfor i := 2; i <= limit; i++ {\n\t\tif i%(limit/100) == 0 {\n\t\t\tfmt.Println(i)\n\t\t}\n\n\t\ttotient := s.Totient(i)\n\t\tt := float64(i) / float64(totient)\n\t\thits[i] = t\n\n\t\tif !IsPermutation(totient, i) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif t < minValue {\n\t\t\tminValue = t\n\t\t\tminIndex = i\n\t\t\tfmt.Println(minIndex, minValue, i, totient)\n\t\t}\n\t}\n\n\tfmt.Println(minIndex, minValue)\n}\n\nfunc SortedString(s string) string ", "output": "{\n\n\tintArray := make([]int, len(s))\n\n\tfor i, letter := range s {\n\t\tintArray[i] = int(letter)\n\t}\n\n\tsort.Ints(intArray)\n\n\tnewString := \"\"\n\n\tfor _, digit := range intArray {\n\t\tnewString += fmt.Sprintf(\"%s\", string(digit))\n\t}\n\n\treturn newString\n}"} {"input": "package hugolib\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc BenchmarkParsePage(b *testing.B) ", "output": "{\n\tf, _ := os.Open(\"redis.cn.md\")\n\tsample := new(bytes.Buffer)\n\tsample.ReadFrom(f)\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tpage, _ := NewPage(\"bench\")\n\t\tpage.ReadFrom(bytes.NewReader(sample.Bytes()))\n\t}\n}"} {"input": "package main\n\ntype Session struct {\n\tseq int32\n\tservers map[int32]int32 \n}\n\n\nfunc NewSession(server int) *Session {\n\ts := new(Session)\n\ts.servers = make(map[int32]int32, server)\n\ts.seq = 0\n\treturn s\n}\n\nfunc (s *Session) nextSeq() int32 {\n\ts.seq++\n\treturn s.seq\n}\n\n\nfunc (s *Session) Put(server int32) (seq int32) {\n\tseq = s.nextSeq()\n\ts.servers[seq] = server\n\treturn\n}\n\nfunc (s *Session) Servers() (seqs []int32, servers []int32) {\n\tvar (\n\t\ti = len(s.servers)\n\t\tseq, server int32\n\t)\n\tseqs = make([]int32, i)\n\tservers = make([]int32, i)\n\tfor seq, server = range s.servers {\n\t\ti--\n\t\tseqs[i] = seq\n\t\tservers[i] = server\n\t}\n\treturn\n}\n\n\n\n\nfunc (s *Session) Size() int {\n\treturn len(s.servers)\n}\n\nfunc (s *Session) Del(seq int32) bool ", "output": "{\n\tdelete(s.servers, seq)\n\treturn (len(s.servers) == 0)\n}"} {"input": "package main\n\nimport \"C\"\nimport \"fmt\"\n\n\n\n\nfunc main() {}\n\nfunc bool_input(b bool) ", "output": "{\n\tfmt.Println(b)\n}"} {"input": "package file\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com/coredns/coredns/plugin/pkg/rcode\"\n\t\"github.com/coredns/coredns/request\"\n\n\t\"github.com/miekg/dns\"\n)\n\n\n\n\nfunc (z *Zone) isNotify(state request.Request) bool {\n\tif state.Req.Opcode != dns.OpcodeNotify {\n\t\treturn false\n\t}\n\tif len(z.TransferFrom) == 0 {\n\t\treturn false\n\t}\n\tremote := state.IP()\n\tfor _, f := range z.TransferFrom {\n\t\tfrom, _, err := net.SplitHostPort(f)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif from == remote {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (z *Zone) Notify() {\n\tgo notify(z.origin, z.TransferTo)\n}\n\n\n\n\nfunc notify(zone string, to []string) error {\n\tm := new(dns.Msg)\n\tm.SetNotify(zone)\n\tc := new(dns.Client)\n\n\tfor _, t := range to {\n\t\tif t == \"*\" {\n\t\t\tcontinue\n\t\t}\n\t\tif err := notifyAddr(c, m, t); err != nil {\n\t\t\tlog.Error(err.Error())\n\t\t} else {\n\t\t\tlog.Infof(\"Sent notify for zone %q to %q\", zone, t)\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\nfunc notifyAddr(c *dns.Client, m *dns.Msg, s string) error ", "output": "{\n\tvar err error\n\n\tcode := dns.RcodeServerFailure\n\tfor i := 0; i < 3; i++ {\n\t\tret, _, err := c.Exchange(m, s)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tcode = ret.Rcode\n\t\tif code == dns.RcodeSuccess {\n\t\t\treturn nil\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"notify for zone %q was not accepted by %q: %q\", m.Question[0].Name, s, err)\n\t}\n\treturn fmt.Errorf(\"notify for zone %q was not accepted by %q: rcode was %q\", m.Question[0].Name, s, rcode.ToString(code))\n}"} {"input": "package main\n\nimport (\n\t\"regexp\"\n)\n\n\n\n\n\nfunc ParseEmail(text string) (email string) ", "output": "{\n\tr := regexp.MustCompile(`(?i)[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}`)\n\tif r.MatchString(text) == true {\n\t\treturn r.FindString(text)\n\t} else {\n\t\treturn \"\"\n\t}\n}"} {"input": "package protocol\n\nimport (\n\t\"encoding/binary\"\n\t\"io\"\n)\n\n\n\ntype Floor struct {\n\tProtocolIdentifier []byte\n\tAddressData []byte\n}\n\n\nfunc (f Floor) WriteTo(w io.Writer) (n int64, err error) {\n\tbuf := make([]byte, f.EncodedLength())\n\tf.Marshal(buf)\n\tn32, err := w.Write(buf)\n\treturn int64(n32), err\n}\n\n\n\nfunc (f Floor) Marshal(p []byte) {\n\tcopyWithLength(f.ProtocolIdentifier, p) \n\tp = p[2+len(f.ProtocolIdentifier):]\n\tcopyWithLength(f.AddressData, p) \n}\n\n\n\n\nfunc copyWithLength(from []byte, to []byte) {\n\tbinary.LittleEndian.PutUint16(to[0:2], uint16(len(from)))\n\tcopy(to[2:], from)\n}\n\nfunc (f Floor) EncodedLength() int ", "output": "{\n\treturn 4 + len(f.ProtocolIdentifier) + len(f.AddressData)\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/engine\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdGetAttributes{\n\t\tname: \"attributes\",\n\t\trpcMethod: utils.APIerSv1GetAttributeProfile,\n\t\trpcParams: &utils.TenantID{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetAttributes struct {\n\tname string\n\trpcMethod string\n\trpcParams *utils.TenantID\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetAttributes) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdGetAttributes) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdGetAttributes) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &utils.TenantID{}\n\t}\n\treturn self.rpcParams\n}\n\n\n\nfunc (self *CmdGetAttributes) RpcResult() interface{} {\n\tvar atr engine.AttributeProfile\n\treturn &atr\n}\n\nfunc (self *CmdGetAttributes) PostprocessRpcParams() error ", "output": "{\n\treturn nil\n}"} {"input": "package format\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\n\ntype Unsigned32 uint32\n\nfunc DecodeUnsigned32(b []byte) (Format, error) {\n\treturn Unsigned32(binary.BigEndian.Uint32(b)), nil\n}\n\n\n\nfunc (n Unsigned32) Len() int {\n\treturn 4\n}\n\nfunc (n Unsigned32) Padding() int {\n\treturn 0\n}\n\nfunc (n Unsigned32) Format() FormatId {\n\treturn Unsigned32Format\n}\n\nfunc (n Unsigned32) String() string {\n\treturn fmt.Sprintf(\"Unsigned32{%d}\", n)\n}\n\nfunc (n Unsigned32) Serialize() []byte ", "output": "{\n\tb := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(b, uint32(n))\n\treturn b\n}"} {"input": "package mockhttputil\n\nimport (\n\tgomock \"github.com/golang/mock/gomock\"\n\thttp \"net/http\"\n\treflect \"reflect\"\n)\n\n\ntype MockRoundTripper struct {\n\tctrl *gomock.Controller\n\trecorder *MockRoundTripperMockRecorder\n}\n\n\ntype MockRoundTripperMockRecorder struct {\n\tmock *MockRoundTripper\n}\n\n\nfunc NewMockRoundTripper(ctrl *gomock.Controller) *MockRoundTripper {\n\tmock := &MockRoundTripper{ctrl: ctrl}\n\tmock.recorder = &MockRoundTripperMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockRoundTripper) EXPECT() *MockRoundTripperMockRecorder {\n\treturn m.recorder\n}\n\n\n\n\n\nfunc (mr *MockRoundTripperMockRecorder) RoundTrip(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"RoundTrip\", reflect.TypeOf((*MockRoundTripper)(nil).RoundTrip), arg0)\n}\n\nfunc (m *MockRoundTripper) RoundTrip(arg0 *http.Request) (*http.Response, error) ", "output": "{\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RoundTrip\", arg0)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}"} {"input": "package native\n\nimport (\n\t\"syscall\"\n)\n\nfunc (f *Fdset32) To64() (out [16]int64) {\n\tfor _, fd := range f.Fds() {\n\t\tout[fd/16] |= (1 << uint(fd) & (32 - 1))\n\t}\n\treturn\n}\n\n\n\n\nfunc (f *Fdset32) Native() *syscall.FdSet ", "output": "{\n\treturn &syscall.FdSet{Bits: f.To64()}\n}"} {"input": "package types\n\nimport \"fmt\"\n\ntype IntegerValue struct {\n\tValue int64\n}\n\nfunc (v *IntegerValue) ToString() string {\n\treturn fmt.Sprint(v.Value)\n}\n\n\n\nfunc (v *IntegerValue) IsValue() bool {\n\treturn true\n}\n\nfunc (v *IntegerValue) ConvertTo(t string) (ValueType, error) {\n\treturn nil, fmt.Errorf(\"cannot convert integer to %s: does not implement yet\", t)\n}\n\nfunc (v *IntegerValue) EqualTo(t ValueType) bool {\n\tif v2, ok := t.(*IntegerValue); ok {\n\t\tif v2.Value == v.Value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc NewIntegerValue(v int64) *IntegerValue {\n\treturn &IntegerValue{Value: v}\n}\n\nfunc (v *IntegerValue) GetType() string ", "output": "{\n\treturn \"integer\"\n}"} {"input": "package sort\n\n\n\n\nfunc BubbleSort(arr []int) []int ", "output": "{\n\tarrLen := len(arr)\n\tfor i := 0; i < arrLen; i++ {\n\t\tfor j := 0; j < arrLen-1; j++ {\n\t\t\tif arr[j] > arr[j+1] {\n\t\t\t\tarr[j], arr[j+1] = arr[j+1], arr[j]\n\t\t\t}\n\t\t}\n\t}\n\treturn arr\n}"} {"input": "package location\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype (\n\tlocation struct {\n\t\tscheme string\n\t\thost string\n\t\tbase string\n\t\theaders Headers\n\t}\n)\n\nfunc newLocation(config Config) *location {\n\treturn &location{\n\t\tscheme: config.Scheme,\n\t\thost: config.Host,\n\t\tbase: config.Base,\n\t\theaders: config.Headers,\n\t}\n}\n\nfunc (l *location) applyToContext(c *gin.Context) {\n\tvalue := new(url.URL)\n\tvalue.Scheme = l.resolveScheme(c.Request)\n\tvalue.Host = l.resolveHost(c.Request)\n\tvalue.Path = l.base\n\tc.Set(key, value)\n}\n\nfunc (l *location) resolveScheme(r *http.Request) string {\n\tswitch {\n\tcase r.Header.Get(l.headers.Scheme) == \"https\":\n\t\treturn \"https\"\n\tcase r.URL.Scheme == \"https\":\n\t\treturn \"https\"\n\tcase r.TLS != nil:\n\t\treturn \"https\"\n\tcase strings.HasPrefix(r.Proto, \"HTTPS\"):\n\t\treturn \"https\"\n\tdefault:\n\t\treturn l.scheme\n\t}\n}\n\n\n\nfunc (l *location) resolveHost(r *http.Request) (host string) ", "output": "{\n\tswitch {\n\tcase r.Header.Get(l.headers.Host) != \"\":\n\t\treturn r.Header.Get(l.headers.Host)\n\tcase r.Header.Get(\"X-Host\") != \"\":\n\t\treturn r.Header.Get(\"X-Host\")\n\tcase r.Host != \"\":\n\t\treturn r.Host\n\tcase r.URL.Host != \"\":\n\t\treturn r.URL.Host\n\tdefault:\n\t\treturn l.host\n\t}\n}"} {"input": "package vanity\n\nimport (\n\t\"github.com/gogo/protobuf/gogoproto\"\n\t\"github.com/gogo/protobuf/proto\"\n\tdescriptor \"github.com/gogo/protobuf/protoc-gen-gogo/descriptor\"\n)\n\nfunc FieldHasBoolExtension(field *descriptor.FieldDescriptorProto, extension *proto.ExtensionDesc) bool {\n\tif field.Options == nil {\n\t\treturn false\n\t}\n\tvalue, err := proto.GetExtension(field.Options, extension)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif value == nil {\n\t\treturn false\n\t}\n\tif value.(*bool) == nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\n\nfunc TurnOffNullable(field *descriptor.FieldDescriptorProto) {\n\tif field.IsRepeated() && !field.IsMessage() {\n\t\treturn\n\t}\n\tSetBoolFieldOption(gogoproto.E_Nullable, false)(field)\n}\n\nfunc TurnOffNullableForNativeTypesWithoutDefaultsOnly(field *descriptor.FieldDescriptorProto) {\n\tif field.IsRepeated() || field.IsMessage() {\n\t\treturn\n\t}\n\tif field.DefaultValue != nil {\n\t\treturn\n\t}\n\tSetBoolFieldOption(gogoproto.E_Nullable, false)(field)\n}\n\nfunc SetBoolFieldOption(extension *proto.ExtensionDesc, value bool) func(field *descriptor.FieldDescriptorProto) ", "output": "{\n\treturn func(field *descriptor.FieldDescriptorProto) {\n\t\tif FieldHasBoolExtension(field, extension) {\n\t\t\treturn\n\t\t}\n\t\tif field.Options == nil {\n\t\t\tfield.Options = &descriptor.FieldOptions{}\n\t\t}\n\t\tif err := proto.SetExtension(field.Options, extension, &value); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"google.golang.org/grpc\"\n\tsdkgrpc \"github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/storage/beta/storage_beta_go_proto\"\n)\n\n\n\n\nfunc RegisterServers(s *grpc.Server) ", "output": "{\n\tsdkgrpc.RegisterStorageBetaBucketServiceServer(s, &BucketServer{})\n\tsdkgrpc.RegisterStorageBetaDefaultObjectAccessControlServiceServer(s, &DefaultObjectAccessControlServer{})\n\tsdkgrpc.RegisterStorageBetaHmacKeyServiceServer(s, &HmacKeyServer{})\n\tsdkgrpc.RegisterStorageBetaObjectServiceServer(s, &ObjectServer{})\n\tsdkgrpc.RegisterStorageBetaObjectAccessControlServiceServer(s, &ObjectAccessControlServer{})\n}"} {"input": "package linebot\n\nimport (\n\t\"context\"\n\n\t\"github.com/line/line-bot-sdk-go/linebot\"\n\t\"github.com/utahta/momoclo-channel/config\"\n\t\"google.golang.org/appengine/urlfetch\"\n)\n\ntype (\n\tClient interface {\n\t\tReplyText(context.Context, string, string) error\n\t\tReplyImage(context.Context, string, string, string) error\n\t}\n\n\tclient struct {\n\t}\n)\n\n\nfunc New() Client {\n\treturn &client{}\n}\n\n\nfunc (c *client) ReplyText(ctx context.Context, replyToken, text string) error {\n\tbot, err := c.fromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttextMessage := linebot.NewTextMessage(text)\n\tif _, err := bot.ReplyMessage(replyToken, textMessage).Do(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\nfunc (c *client) ReplyImage(ctx context.Context, replyToken, originalContentURL, previewImageURL string) error {\n\tbot, err := c.fromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\timageMessage := linebot.NewImageMessage(originalContentURL, previewImageURL)\n\tif _, err := bot.ReplyMessage(replyToken, imageMessage).Do(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc (c *client) fromContext(ctx context.Context) (*linebot.Client, error) ", "output": "{\n\treturn linebot.New(\n\t\tconfig.C().LineBot.ChannelSecret,\n\t\tconfig.C().LineBot.ChannelToken,\n\t\tlinebot.WithHTTPClient(urlfetch.Client(ctx)),\n\t)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n)\n\n\ntype Tree struct {\n\tLeft *Tree\n\tValue int\n\tRight *Tree\n}\n\n\n\nfunc Walk(t *Tree, ch chan int) {\n\tif t == nil {\n\t\treturn\n\t}\n\tWalk(t.Left, ch)\n\tch <- t.Value\n\tWalk(t.Right, ch)\n}\n\n\n\nfunc Walker(t *Tree) <-chan int {\n\tch := make(chan int)\n\tgo func() {\n\t\tWalk(t, ch)\n\t\tclose(ch)\n\t}()\n\treturn ch\n}\n\n\n\n\n\n\n\n\nfunc New(n, k int) *Tree {\n\tvar t *Tree\n\tfor _, v := range rand.Perm(n) {\n\t\tt = insert(t, (1+v)*k)\n\t}\n\treturn t\n}\n\nfunc insert(t *Tree, v int) *Tree {\n\tif t == nil {\n\t\treturn &Tree{nil, v, nil}\n\t}\n\tif v < t.Value {\n\t\tt.Left = insert(t.Left, v)\n\t\treturn t\n\t}\n\tt.Right = insert(t.Right, v)\n\treturn t\n}\n\nfunc main() {\n\tt1 := New(100, 1)\n\tfmt.Println(Compare(t1, New(100, 1)), \"Same Contents\")\n\tfmt.Println(Compare(t1, New(99, 1)), \"Differing Sizes\")\n\tfmt.Println(Compare(t1, New(100, 2)), \"Differing Values\")\n\tfmt.Println(Compare(t1, New(101, 2)), \"Dissimilar\")\n}\n\nfunc Compare(t1, t2 *Tree) bool ", "output": "{\n\tc1, c2 := Walker(t1), Walker(t2)\n\tfor {\n\t\tv1, ok1 := <-c1\n\t\tv2, ok2 := <-c2\n\t\tif !ok1 || !ok2 {\n\t\t\treturn ok1 == ok2\n\t\t}\n\t\tif v1 != v2 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package dml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/dml\"\n)\n\nfunc TestCT_TintEffectConstructor(t *testing.T) {\n\tv := dml.NewCT_TintEffect()\n\tif v == nil {\n\t\tt.Errorf(\"dml.NewCT_TintEffect must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed dml.CT_TintEffect should validate: %s\", err)\n\t}\n}\n\n\n\nfunc TestCT_TintEffectMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := dml.NewCT_TintEffect()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := dml.NewCT_TintEffect()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n)\n\n\nfunc main() {\n\tconn, err := net.Dial(\"tcp\", \"localhost:8000\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Close()\n\tgo mustCopy(os.Stdout, conn)\n\tmustCopy(conn, os.Stdin)\n}\n\n\n\n\n\nfunc mustCopy(dst io.Writer, src io.Reader) ", "output": "{\n\tif _, err := io.Copy(dst, src); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"input": "package state\n\nimport (\n\t\"strconv\"\n\t. \"bugnuts/maps\"\n\t. \"bugnuts/torus\"\n\t. \"bugnuts/util\"\n)\n\nfunc (s *State) FoodLocations() (l []Location) {\n\tfor loc := range s.Food {\n\t\tl = append(l, Location(loc))\n\t}\n\n\treturn l\n}\n\nfunc (s *State) HillLocations(player int) (l []Location) {\n\tfor loc, hill := range s.Hills {\n\t\tif hill.Player == player && hill.Killed == 0 {\n\t\t\tl = append(l, Location(loc))\n\t\t}\n\t}\n\n\treturn l\n}\n\n\n\nfunc (s *State) ValidStep(loc Location) bool {\n\ti := s.Map.Grid[loc]\n\n\treturn i != WATER && i != BLOCK && i != OCCUPIED && i != FOOD && i != MY_ANT && i != MY_HILLANT\n}\n\nfunc (s *State) Stepable(loc Location) bool {\n\ti := s.Map.Grid[loc]\n\n\treturn i != WATER && i != BLOCK && i != FOOD\n}\n\nfunc (m *Metrics) DumpSeen() string {\n\tmax := Max(m.Seen)\n\tstr := \"\"\n\n\tfor r := 0; r < m.Rows; r++ {\n\t\tfor c := 0; c < m.Cols; c++ {\n\t\t\tstr += strconv.Itoa(m.Seen[r*m.Cols+c] * 10 / (max + 1))\n\t\t}\n\t\tstr += \"\\n\"\n\t}\n\n\treturn str\n}\n\nfunc (s *State) EnemyHillLocations(player int) (l []Location) ", "output": "{\n\tfor loc, hill := range s.Hills {\n\t\tif hill.Player != player && hill.Killed == 0 {\n\t\t\tl = append(l, Location(loc))\n\t\t}\n\t}\n\n\treturn l\n}"} {"input": "package testutil\n\nimport (\n\t\"testing\"\n\n\t\"github.com/tendermint/abci/server\"\n\twire \"github.com/tendermint/go-wire\"\n\t\"github.com/tendermint/merkleeyes/app\"\n\teyes \"github.com/tendermint/merkleeyes/client\"\n\t. \"github.com/tendermint/tmlibs/common\"\n)\n\n\nfunc CreateEyes(t *testing.T) (svr Service, cli *eyes.Client) {\n\taddr := \"unix://eyes.sock\"\n\n\tmApp := app.NewMerkleEyesApp(\"\", 0)\n\tsvr, err := server.NewServer(addr, \"socket\", mApp)\n\tif err != nil {\n\t\t(err.Error())\n\t\treturn\n\t}\n\n\tcli, err = eyes.NewClient(addr)\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t\treturn\n\t}\n\n\treturn svr, cli\n}\n\n\n\n\n\n\nfunc makeSet(key, value []byte) []byte {\n\ttx := make([]byte, 1+wire.ByteSliceSize(key)+wire.ByteSliceSize(value))\n\tbuf := tx\n\tbuf[0] = app.TxTypeSet \n\tbuf = buf[1:]\n\tn, err := wire.PutByteSlice(buf, key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tbuf = buf[n:]\n\tn, err = wire.PutByteSlice(buf, value)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn tx\n}\n\nfunc MakeTxKV() ([]byte, []byte, []byte) ", "output": "{\n\tk := []byte(RandStr(8))\n\tv := []byte(RandStr(8))\n\treturn k, v, makeSet(k, v)\n}"} {"input": "package log_streamer_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestLogStreamer(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Log Streamer Suite\")\n}"} {"input": "package user\n\nfunc New(id int, username, password, firstname, lastname, role string) User {\n\treturn User{id, username, password, firstname, lastname, role}\n}\n\n\ntype User struct {\n\tid int\n\tusername string\n\tpassword string\n\tfirstname string\n\tlastname string\n\trole string\n}\n\nfunc (u User) Id() int {\n\treturn u.id\n}\n\nfunc (u User) Username() string {\n\treturn u.username\n}\n\n\n\nfunc (u User) Firstname() string {\n\treturn u.firstname\n}\n\nfunc (u User) Lastname() string {\n\treturn u.lastname\n}\n\nfunc (u User) Role() string {\n\treturn u.role\n}\n\nfunc (u User) Password() string ", "output": "{\n\treturn u.password\n}"} {"input": "package store\n\nimport \"strings\"\n\n\ntype ByPathLen []string\n\nfunc (s ByPathLen) Len() int { return len(s) }\n\nfunc (s ByPathLen) Less(i, j int) bool {\n\treturn strings.Count(s[i], \"/\") < strings.Count(s[j], \"/\")\n}\n\nfunc (s ByPathLen) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\n\ntype ByLen []string\n\n\n\n\n\nfunc (s ByLen) Less(i, j int) bool { return len(s[i]) > len(s[j]) }\n\n\nfunc (s ByLen) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s ByLen) Len() int ", "output": "{ return len(s) }"} {"input": "package types\n\nimport \"fmt\"\n\ntype KeywordValue struct {\n\tValue string\n}\n\n\n\nfunc (v *KeywordValue) GetType() string {\n\treturn \"keyword\"\n}\n\nfunc (v *KeywordValue) IsValue() bool {\n\treturn false\n}\n\nfunc (v *KeywordValue) ConvertTo(t string) (ValueType, error) {\n\treturn nil, fmt.Errorf(\"cannot convert keyword to %s: does not implement yet\", t)\n}\n\nfunc (v *KeywordValue) EqualTo(t ValueType) bool {\n\tif v2, ok := t.(*KeywordValue); ok {\n\t\tif v2.Value == v.Value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc NewKeywordValue(v string) *KeywordValue {\n\treturn &KeywordValue{Value: v}\n}\n\nfunc (v *KeywordValue) ToString() string ", "output": "{\n\treturn fmt.Sprint(v.Value)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSOpsWorksStack_ElasticIp struct {\n\n\tIp string `json:\"Ip,omitempty\"`\n\n\tName string `json:\"Name,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) AWSCloudFormationType() string {\n\treturn \"AWS::OpsWorks::Stack.ElasticIp\"\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\n\n\nfunc (r *AWSOpsWorksStack_ElasticIp) SetDeletionPolicy(policy policies.DeletionPolicy) ", "output": "{\n\tr._deletionPolicy = policy\n}"} {"input": "package api_xhr\n\nimport (\n\t\"compress/gzip\"\n\t\"encoding/json\"\n\t\"io\"\n\t\"net/http\"\n\n\t\"github.com/deze333/vroom/reqres\"\n)\n\n\n\n\n\n\n\n\nfunc decodeAsUnencodedReq(r *http.Request) (params map[string]interface{}, err error) {\n\n\tdecoder := json.NewDecoder(r.Body)\n\terr = decoder.Decode(¶ms)\n\n\tif err == io.EOF {\n\t\terr = nil\n\t}\n\n\treturn\n}\n\n\nfunc decodeAsGzipReq(r *http.Request) (params map[string]interface{}, err error) {\n\n\tvar reader *gzip.Reader\n\treader, err = gzip.NewReader(r.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdecoder := json.NewDecoder(reader)\n\terr = decoder.Decode(¶ms)\n\n\tif err == io.EOF {\n\t\terr = nil\n\t}\n\n\treturn\n}\n\nfunc ParseReq(w http.ResponseWriter, r *http.Request) (req *reqres.Req, err error) ", "output": "{\n\n\tparams := map[string]interface{}{}\n\n\tswitch r.Header.Get(\"Content-Encoding\") {\n\tcase \"gzip\":\n\t\tparams, err = decodeAsGzipReq(r)\n\n\tdefault:\n\t\tparams, err = decodeAsUnencodedReq(r)\n\t}\n\n\treq = &reqres.Req{\n\t\tParams: params,\n\t\tHttpReq: r,\n\t\tHttpResWriter: w,\n\t}\n\treturn\n}"} {"input": "package lib\n\nimport (\n\t\"github.com/atinm/spotify\"\n)\n\nfunc ignored(device string) bool {\n\tfor _, name := range config.Ignored {\n\t\tif name == device {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc FiltersEnabled() bool {\n\treturn ParentalControlsEnabled()\n}\n\nfunc ParentalControlsEnabled() bool {\n\treturn rule.Explicit\n}\n\n\n\nfunc SetParentalControls(b bool) {\n\trule.Explicit = b\n}\n\nfunc Rules(track *spotify.FullTrack, device string) bool ", "output": "{\n\tif track != nil && rule.Explicit && track.Explicit && !ignored(device) {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package header\n\nimport (\n\t\"github.com/google/netstack/tcpip\"\n)\n\n\n\n\n\n\n\nfunc ChecksumCombine(a, b uint16) uint16 {\n\tv := uint32(a) + uint32(b)\n\treturn uint16(v + v>>16)\n}\n\n\n\n\n\nfunc PseudoHeaderChecksum(protocol tcpip.TransportProtocolNumber, srcAddr tcpip.Address, dstAddr tcpip.Address) uint16 {\n\txsum := Checksum([]byte(srcAddr), 0)\n\txsum = Checksum([]byte(dstAddr), xsum)\n\treturn Checksum([]byte{0, uint8(protocol)}, xsum)\n}\n\nfunc Checksum(buf []byte, initial uint16) uint16 ", "output": "{\n\tv := uint32(initial)\n\n\tl := len(buf)\n\tif l&1 != 0 {\n\t\tl--\n\t\tv += uint32(buf[l]) << 8\n\t}\n\n\tfor i := 0; i < l; i += 2 {\n\t\tv += (uint32(buf[i]) << 8) + uint32(buf[i+1])\n\t}\n\n\treturn ChecksumCombine(uint16(v), uint16(v>>16))\n}"} {"input": "package tick\n\nimport (\n\t\"appengine/datastore\"\n\t\"appengine/taskqueue\"\n\t\"net/http\"\n\t\"techtraits.com/klaxon/rest/project\"\n\t\"techtraits.com/klaxon/router\"\n\t\"techtraits.com/log\"\n)\n\nfunc init() {\n\trouter.Register(\"/rest/internal/tick/\", router.GET, nil, nil, getTick)\n}\n\n\n\nfunc getTick(request router.Request) (int, []byte) ", "output": "{\n\n\tquery := datastore.NewQuery(project.PROJECT_KEY)\n\tprojects := make([]project.ProjectDTO, 0)\n\t_, err := query.GetAll(request.GetContext(), &projects)\n\n\tif err != nil {\n\t\tlog.Errorf(request.GetContext(), \"Error retriving projects: %v\", err)\n\t\treturn http.StatusInternalServerError, []byte(err.Error())\n\t} else {\n\n\t\tfor _, project := range projects {\n\t\t\ttask := taskqueue.NewPOSTTask(\"/rest/internal/check/\"+project.Name, nil)\n\t\t\tif _, err := taskqueue.Add(request.GetContext(), task, \"alertCheckQueue\"); err != nil {\n\t\t\t\tlog.Errorf(request.GetContext(), \"Error posting to task queue: %v\", err)\n\t\t\t}\n\n\t\t}\n\n\t\treturn http.StatusOK, nil\n\t}\n}"} {"input": "package trigger\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestCommandAction(t *testing.T) ", "output": "{\n\taction := NewCommandAction(\"echo\", nil, os.Environ())\n\tctx := context.Background()\n\tctx = WithConditionName(ctx, \"foo\")\n\tctx = WithConditionState(ctx, true)\n\terr := action.run(ctx)\n\n\tif err != nil {\n\t\tt.Errorf(\"expected no error but got: %s\", err)\n\t}\n}"} {"input": "package stats\n\nvar (\n\tNoOpStatsFactory StatsFactory\n)\n\ntype noopCounter struct {\n}\n\nfunc (s noopCounter) Inc() {\n}\n\nfunc (s noopCounter) Add(v float64) {\n}\n\ntype noopGauge struct {\n}\n\nfunc (s noopGauge) Inc() {\n}\n\nfunc (s noopGauge) Add(v float64) {\n}\n\nfunc (s noopGauge) Dec() {\n}\n\nfunc (s noopGauge) Sub(v float64) {\n}\n\nfunc (s noopGauge) Set(v float64) {\n}\n\nfunc (s noopGauge) Get() float64 {\n\treturn 0\n}\n\ntype noopSummary struct {\n}\n\nfunc (s noopSummary) Observe(v float64) {\n}\n\ntype noopStatsFactory struct {\n}\n\n\n\nfunc (f noopStatsFactory) NewGauge(\n\tmetric string,\n\ttags map[string]string) GaugeStat {\n\n\treturn noopGauge{}\n}\n\nfunc (f noopStatsFactory) NewSummary(\n\tmetric string,\n\ttags map[string]string) SummaryStat {\n\n\treturn noopSummary{}\n}\n\nfunc init() {\n\tNoOpStatsFactory = noopStatsFactory{}\n}\n\nfunc (f noopStatsFactory) NewCounter(\n\tmetric string,\n\ttags map[string]string) CounterStat ", "output": "{\n\n\treturn noopCounter{}\n}"} {"input": "package processors\n\nimport (\n\t\"context\"\n\n\t\"github.com/cloudevents/sdk-go/v2/event\"\n)\n\n\n\n\n\ntype Interface interface {\n\tProcess(ctx context.Context, e *event.Event) error\n\tNext() Interface\n}\n\n\ntype ChainableProcessor interface {\n\tInterface\n\n\tWithNext(ChainableProcessor) ChainableProcessor\n}\n\n\n\n\ntype BaseProcessor struct {\n\tn ChainableProcessor\n}\n\n\n\n\nfunc (p *BaseProcessor) Next() Interface {\n\tif p.n == nil {\n\t\treturn noop\n\t}\n\treturn p.n\n}\n\n\nfunc (p *BaseProcessor) WithNext(n ChainableProcessor) ChainableProcessor {\n\tp.n = n\n\treturn p.n\n}\n\n\nfunc ChainProcessors(first ChainableProcessor, rest ...ChainableProcessor) Interface {\n\tnext := first\n\tfor _, p := range rest {\n\t\tnext = next.WithNext(p)\n\t}\n\treturn first\n}\n\nvar noop = &noOpProcessor{}\n\ntype noOpProcessor struct{}\n\n\n\n\n\nfunc (p noOpProcessor) Next() Interface {\n\treturn nil\n}\n\nfunc (p noOpProcessor) Process(_ context.Context, _ *event.Event) error ", "output": "{\n\treturn nil\n}"} {"input": "package analytics\n\nimport (\n\t\"fmt\"\n\n\telastic \"gopkg.in/olivere/elastic.v3\"\n)\n\n\ntype Elasticsearch struct {\n\tURL string\n\tIndexName string\n\tDocType string\n\tclient *elastic.Client\n}\n\n\n\n\n\nfunc (e *Elasticsearch) SendAnalytics(data string) error {\n\tfmt.Println(data)\n\t_, err := e.client.Index().Index(e.IndexName).Type(e.DocType).BodyJson(data).Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (e *Elasticsearch) Initialize() error ", "output": "{\n\tclient, err := elastic.NewSimpleClient(elastic.SetURL(e.URL))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te.client = client\n\n\ts := e.client.IndexExists(e.IndexName)\n\texists, err := s.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !exists {\n\t\ts := e.client.CreateIndex(e.IndexName)\n\t\t_, err := s.Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package fakes\n\nimport \"os\"\n\ntype FileIO struct {\n\tTempFileCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tDir string\n\t\t\tPrefix string\n\t\t}\n\t\tReturns struct {\n\t\t\tFile *os.File\n\t\t\tError error\n\t\t}\n\t}\n\tReadFileCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tFilename string\n\t\t}\n\t\tReturns struct {\n\t\t\tContents []byte\n\t\t\tError error\n\t\t}\n\t}\n\tWriteFileCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tFilename string\n\t\t\tContents []byte\n\t\t}\n\t\tReturns struct {\n\t\t\tError error\n\t\t}\n\t}\n\tStatCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tName string\n\t\t}\n\t\tReturns struct {\n\t\t\tFileInfo os.FileInfo\n\t\t\tError error\n\t\t}\n\t}\n}\n\nfunc (fake *FileIO) TempFile(dir, prefix string) (f *os.File, err error) {\n\tfake.TempFileCall.CallCount++\n\tfake.TempFileCall.Receives.Dir = dir\n\tfake.TempFileCall.Receives.Prefix = prefix\n\treturn fake.TempFileCall.Returns.File, fake.TempFileCall.Returns.Error\n}\n\n\n\nfunc (fake *FileIO) WriteFile(filename string, contents []byte, perm os.FileMode) error {\n\tfake.WriteFileCall.CallCount++\n\tfake.WriteFileCall.Receives.Filename = filename\n\tfake.WriteFileCall.Receives.Contents = contents\n\treturn fake.WriteFileCall.Returns.Error\n}\n\nfunc (fake *FileIO) Stat(name string) (os.FileInfo, error) {\n\tfake.StatCall.CallCount++\n\tfake.StatCall.Receives.Name = name\n\treturn fake.StatCall.Returns.FileInfo, fake.StatCall.Returns.Error\n}\n\nfunc (fake *FileIO) ReadFile(filename string) ([]byte, error) ", "output": "{\n\tfake.ReadFileCall.CallCount++\n\tfake.ReadFileCall.Receives.Filename = filename\n\treturn fake.ReadFileCall.Returns.Contents, fake.ReadFileCall.Returns.Error\n}"} {"input": "package mailru\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/markbates/goth\"\n)\n\n\ntype Session struct {\n\tAuthURL string\n\tAccessToken string\n\tRefreshToken string\n\tExpiresAt time.Time\n}\n\n\nfunc (s *Session) GetAuthURL() (string, error) {\n\tif s.AuthURL == \"\" {\n\t\treturn \"\", errors.New(goth.NoAuthUrlErrorMessage)\n\t}\n\n\treturn s.AuthURL, nil\n}\n\n\nfunc (s *Session) Marshal() string {\n\tb, _ := json.Marshal(s)\n\treturn string(b)\n}\n\n\n\n\n\nfunc (p *Provider) UnmarshalSession(data string) (goth.Session, error) {\n\tsess := new(Session)\n\terr := json.NewDecoder(strings.NewReader(data)).Decode(&sess)\n\treturn sess, err\n}\n\nfunc (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) ", "output": "{\n\tp := provider.(*Provider)\n\ttoken, err := p.oauthConfig.Exchange(goth.ContextForClient(p.Client()), params.Get(\"code\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !token.Valid() {\n\t\treturn \"\", errors.New(\"invalid token received from provider\")\n\t}\n\n\ts.AccessToken = token.AccessToken\n\ts.RefreshToken = token.RefreshToken\n\ts.ExpiresAt = token.Expiry\n\n\treturn s.AccessToken, err\n}"} {"input": "package primitives\n\nimport (\n\t\"encoding/xml\"\n\t\"github.com/plandem/ooxml/ml\"\n)\n\n\ntype FontFamilyType ml.PropertyInt\n\n\n\n\n\nfunc (t *FontFamilyType) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\treturn (*ml.PropertyInt)(t).UnmarshalXML(d, start)\n}\n\nfunc (t *FontFamilyType) MarshalXML(e *xml.Encoder, start xml.StartElement) error ", "output": "{\n\treturn (*ml.PropertyInt)(t).MarshalXML(e, start)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\ntype ErrNegativeSqrt float64\n\n\n\nfunc Sqrt(x float64) (float64, error) {\n\tz := 1.0\n\tif x >= 0 {\n\t\tfor i := 0; i < 10; i++ {\n\t\t\tz = z - (z*z-x)/(2*z)\n\t\t}\n\t} else {\n\t\treturn 0, ErrNegativeSqrt(x)\n\t}\n\treturn z, nil\n}\n\nfunc main() {\n\tfmt.Println(Sqrt(2))\n\tfmt.Println(Sqrt(-2))\n}\n\nfunc (e ErrNegativeSqrt) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"cannot Sqrt negative number: %g\\n\", float64(e))\n}"} {"input": "package v2\n\nimport (\n\t\"code.cloudfoundry.org/cli/command\"\n\t\"code.cloudfoundry.org/cli/command/translatableerror\"\n)\n\ntype QuotasCommand struct {\n\tusage interface{} `usage:\"CF_NAME quotas\"`\n}\n\nfunc (QuotasCommand) Setup(config command.Config, ui command.UI) error {\n\treturn nil\n}\n\n\n\nfunc (QuotasCommand) Execute(args []string) error ", "output": "{\n\treturn translatableerror.UnrefactoredCommandError{}\n}"} {"input": "package safetime\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/sirupsen/logrus\"\n\t. \"gopkg.in/check.v1\"\n)\n\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\ntype SafetimeSuite struct {\n\tout *bytes.Buffer \n\tlogger *logrus.Entry\n}\n\nvar _ = Suite(&SafetimeSuite{})\n\n\n\nfunc (s *SafetimeSuite) TestNegativeDuration(c *C) {\n\tfuture := time.Now().Add(time.Second)\n\td, ok := TimeSinceSafe(future, s.logger)\n\n\tc.Assert(ok, Equals, false)\n\tc.Assert(d, Equals, time.Duration(0))\n\tfmt.Println(s.out.String())\n\tc.Assert(strings.Contains(s.out.String(), \"BUG: negative duration\"), Equals, true)\n}\n\nfunc (s *SafetimeSuite) TestNonNegativeDuration(c *C) {\n\tpast := time.Now().Add(-10 * time.Second)\n\td, ok := TimeSinceSafe(past, s.logger)\n\n\tc.Assert(ok, Equals, true)\n\tc.Assert(d > time.Duration(0), Equals, true)\n\tc.Assert(len(s.out.String()) == 0, Equals, true)\n}\n\nfunc (s *SafetimeSuite) SetUpTest(c *C) ", "output": "{\n\ts.out = &bytes.Buffer{}\n\tlogger := logrus.New()\n\tlogger.Out = s.out\n\ts.logger = logrus.NewEntry(logger)\n}"} {"input": "package seqnum\n\n\ntype Value uint32\n\n\ntype Size uint32\n\n\nfunc (v Value) LessThan(w Value) bool {\n\treturn int32(v-w) < 0\n}\n\n\nfunc (v Value) LessThanEq(w Value) bool {\n\tif v == w {\n\t\treturn true\n\t}\n\treturn v.LessThan(w)\n}\n\n\nfunc (v Value) InRange(a, b Value) bool {\n\treturn v-a < b-a\n}\n\n\n\n\n\n\nfunc Overlap(a Value, b Size, x Value, y Size) bool {\n\treturn a.LessThan(x.Add(y)) && x.LessThan(a.Add(b))\n}\n\n\nfunc (v Value) Add(s Size) Value {\n\treturn v + Value(s)\n}\n\n\nfunc (v Value) Size(w Value) Size {\n\treturn Size(w - v)\n}\n\n\nfunc (v *Value) UpdateForward(s Size) {\n\t*v += Value(s)\n}\n\nfunc (v Value) InWindow(first Value, size Size) bool ", "output": "{\n\treturn v.InRange(first, first.Add(size))\n}"} {"input": "package controllers\n\nimport (\n\t\"net\"\n\n\t\"[[.project]]/app/models\"\n\t\"[[.project]]/app/routes\"\n\t\"github.com/revel/revel\"\n)\n\ntype PortalController struct {\n\t*revel.Controller\n}\n\n\n\nfunc (c PortalController) authorized() (interface{}, bool) {\n\tif secret, ok := c.Session[\"secret\"]; ok {\n\t\tremote, _, _ := net.SplitHostPort(c.Request.RemoteAddr)\n\t\tforward := c.Request.Header.Get(\"X-Forwarded-For\")\n\t\tif forward != \"\" {\n\t\t\tremote = forward\n\t\t}\n\n\t\ttoken, err := HitSystemToken(secret, remote)\n\t\tif err != nil {\n\t\t\trevel.WARN.Printf(\"authorized failed: %s\", err.Error())\n\t\t\treturn nil, false\n\t\t}\n\n\t\tvar account models.SystemAccount\n\t\taccount.ID = token.SystemAccountID\n\t\tif err := db.First(&account).Error; err != nil {\n\t\t\treturn nil, false\n\t\t}\n\t\tc.RenderArgs[\"account\"] = &account\n\t\treturn &token, true\n\t}\n\n\treturn nil, false\n}\n\nfunc (c PortalController) Authorized() revel.Result {\n\tif _, ok := c.authorized(); !ok {\n\t\treturn c.Redirect(routes.AuthController.Login())\n\t}\n\treturn nil\n}\n\nfunc init() {\n\trevel.InterceptMethod(PortalController.Authorized, revel.BEFORE)\n}\n\nfunc (c PortalController) Index() revel.Result ", "output": "{\n\treturn c.RenderTemplate(\"index.html\")\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\tfmt.Println(checkPandig([]int{39, 186, 7254}))\n\tall := []int{}\n\tfor i := 1; i < 10; i++ {\n\t\tfor j := 1000; j < 10000; j++ {\n\t\t\tsum := j * i\n\t\t\tif sum > 10000 {\n\t\t\t\tcontinue\n\t\t\t} else if checkPandig([]int{i, j, sum}) {\n\t\t\t\tisIn := false\n\t\t\t\tfor _, n := range all {\n\t\t\t\t\tif n == sum {\n\t\t\t\t\t\tisIn = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !isIn {\n\t\t\t\t\tall = append(all, sum)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor i := 11; i < 100; i++ {\n\t\tfor j := 100; j < 1000; j++ {\n\t\t\tsum := j * i\n\t\t\tif sum > 10000 {\n\t\t\t\tcontinue\n\t\t\t} else if checkPandig([]int{i, j, sum}) {\n\t\t\t\tisIn := false\n\t\t\t\tfmt.Println(i, j, sum)\n\t\t\t\tfor _, n := range all {\n\t\t\t\t\tif n == sum {\n\t\t\t\t\t\tisIn = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !isIn {\n\t\t\t\t\tall = append(all, sum)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Println(all)\n\ttotal := 0\n\tfor _, n := range all {\n\t\ttotal += n\n\t}\n\tfmt.Println(total)\n}\n\nfunc checkPandig(allNum []int) bool ", "output": "{\n\tchecker := make([]bool, 10)\n\tfor _, num := range allNum {\n\t\ttmpNum := num\n\t\tfor tmpNum != 0 {\n\t\t\tremainder := tmpNum % 10\n\t\t\tif checker[remainder] {\n\t\t\t\treturn false\n\t\t\t} else {\n\t\t\t\tchecker[remainder] = true\n\t\t\t}\n\t\t\ttmpNum = tmpNum / 10\n\t\t}\n\t}\n\tif checker[0] {\n\t\treturn false\n\t}\n\tfor i := 1; i <= 9; i++ {\n\t\tif !checker[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package identitymapper\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/klog\"\n\n\t\"k8s.io/apiserver/pkg/authentication/authenticator\"\n\n\t\"github.com/openshift/origin/pkg/oauthserver/api\"\n)\n\n\nfunc ResponseFor(mapper api.UserIdentityMapper, identity api.UserIdentityInfo) (*authenticator.Response, bool, error) {\n\tuser, err := mapper.UserFor(identity)\n\tif err != nil {\n\t\tlogf(\"error creating or updating mapping for: %#v due to %v\", identity, err)\n\t\treturn nil, false, err\n\t}\n\tlogf(\"got userIdentityMapping: %#v\", user)\n\n\treturn &authenticator.Response{User: user}, true, nil\n}\n\n\n\n\nfunc logf(format string, args ...interface{}) ", "output": "{\n\tif klog.V(4) {\n\t\tklog.InfoDepth(2, fmt.Sprintf(\"identitymapper: \"+format, args...))\n\t}\n}"} {"input": "package graphdriver\n\n\nimport \"C\"\nimport (\n\t\"path/filepath\"\n\t\"unsafe\"\n\n\t\"github.com/docker/docker/pkg/mount\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tFsMagicZfs = FsMagic(0x2fc12fc1)\n)\n\nvar (\n\tpriority = []string{\n\t\t\"zfs\",\n\t}\n\n\tFsNames = map[FsMagic]string{\n\t\tFsMagicZfs: \"zfs\",\n\t}\n)\n\n\nfunc GetFSMagic(rootpath string) (FsMagic, error) {\n\treturn 0, nil\n}\n\ntype fsChecker struct {\n\tt FsMagic\n}\n\nfunc (c *fsChecker) IsMounted(path string) bool {\n\tm, _ := Mounted(c.t, path)\n\treturn m\n}\n\n\nfunc NewFsChecker(t FsMagic) Checker {\n\treturn &fsChecker{\n\t\tt: t,\n\t}\n}\n\n\n\n\n\n\ntype defaultChecker struct {\n}\n\nfunc (c *defaultChecker) IsMounted(path string) bool {\n\tm, _ := mount.Mounted(path)\n\treturn m\n}\n\n\n\nfunc Mounted(fsType FsMagic, mountPath string) (bool, error) {\n\n\tcs := C.CString(filepath.Dir(mountPath))\n\tdefer C.free(unsafe.Pointer(cs))\n\tbuf := C.getstatfs(cs)\n\tdefer C.free(unsafe.Pointer(buf))\n\n\tif (buf.f_basetype[0] != 122) || (buf.f_basetype[1] != 102) || (buf.f_basetype[2] != 115) ||\n\t\t(buf.f_basetype[3] != 0) {\n\t\tlogrus.Debugf(\"[zfs] no zfs dataset found for rootdir '%s'\", mountPath)\n\t\treturn false, ErrPrerequisites\n\t}\n\n\treturn true, nil\n}\n\nfunc NewDefaultChecker() Checker ", "output": "{\n\treturn &defaultChecker{}\n}"} {"input": "package main\n\nimport (\n \"math\"\n \"time\"\n)\n\n\nfunc getTime(packet []byte, entryList *[]string, pointer *int, err *bool) {\n var timeLen int\n if len(packet) - *pointer >= 8 && !*err {\n timeLen = 8\n }\n if timeLen > 0 {\n timeByteString := string(packet[*pointer: *pointer + timeLen])\n var cInt float64\n for x := range timeByteString {\n cInt += float64(timeByteString[x]) * math.Pow(256, float64(timeLen -\n 1 - x))\n }\n timestamp := time.Unix(int64(cInt), 0).Format(timeLayout)\n *entryList = append(*entryList, timestamp)\n } else {\n *err = true\n }\n *pointer += 8\n}\n\n\n\n\nfunc timeToUnix(value string) int64 ", "output": "{\n local, _ := time.LoadLocation(\"Local\")\n toTime, _ := time.ParseInLocation(timeLayout, value, local)\n return toTime.Unix()\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/robfig/revel\"\n\t\"github.com/robfig/revel/samples/chat/app/chatroom\"\n\t\"github.com/robfig/revel/samples/chat/app/routes\"\n)\n\ntype Refresh struct {\n\t*revel.Controller\n}\n\nfunc (c Refresh) Index(user string) revel.Result {\n\tchatroom.Join(user)\n\treturn c.Redirect(routes.Refresh.Room(user))\n}\n\nfunc (c Refresh) Room(user string) revel.Result {\n\tsubscription := chatroom.Subscribe()\n\tdefer subscription.Cancel()\n\tevents := subscription.Archive\n\tfor i, _ := range events {\n\t\tif events[i].User == user {\n\t\t\tevents[i].User = \"you\"\n\t\t}\n\t}\n\treturn c.Render(user, events)\n}\n\n\n\nfunc (c Refresh) Leave(user string) revel.Result {\n\tchatroom.Leave(user)\n\treturn c.Redirect(Application.Index)\n}\n\nfunc (c Refresh) Say(user, message string) revel.Result ", "output": "{\n\tchatroom.Say(user, message)\n\treturn c.Redirect(routes.Refresh.Room(user))\n}"} {"input": "package openstacktasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realFloatingIP FloatingIP\n\n\nfunc (o *FloatingIP) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realFloatingIP\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = FloatingIP(r)\n\treturn nil\n}\n\nvar _ fi.HasLifecycle = &FloatingIP{}\n\n\nfunc (o *FloatingIP) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\n\nfunc (o *FloatingIP) SetLifecycle(lifecycle fi.Lifecycle) {\n\to.Lifecycle = &lifecycle\n}\n\nvar _ fi.HasName = &FloatingIP{}\n\n\nfunc (o *FloatingIP) GetName() *string {\n\treturn o.Name\n}\n\n\nfunc (o *FloatingIP) SetName(name string) {\n\to.Name = &name\n}\n\n\n\n\nfunc (o *FloatingIP) String() string ", "output": "{\n\treturn fi.TaskAsString(o)\n}"} {"input": "package proc\n\nimport \"fmt\"\n\n\n\n\n\ntype Registers interface {\n\tPC() uint64\n\tSP() uint64\n\tCX() uint64\n\tTLS() uint64\n\tSetPC(*Thread, uint64) error\n\tString() string\n}\n\n\n\n\n\nfunc (thread *Thread) PC() (uint64, error) {\n\tregs, err := thread.Registers()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn regs.PC(), nil\n}\n\nfunc (thread *Thread) Registers() (Registers, error) ", "output": "{\n\tregs, err := registers(thread)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get registers: %s\", err)\n\t}\n\treturn regs, nil\n}"} {"input": "package helper\n\nimport (\n\t\"encoding/base64\"\n\t\"strings\"\n\t\"time\"\n\t\"github.com/insionng/yougam/libraries/flosch/pongo2.v3\"\n)\n\nfunc ConvertToBase64(in string) string {\n\treturn base64.StdEncoding.EncodeToString([]byte(in))\n}\n\n\n\nfunc SplitByPongo2(in *pongo2.Value, splitor *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Split(in.String(), splitor.String()))\n}\n\nfunc MarkdownByPongo2(in *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Markdown(in.String()))\n}\n\nfunc CropwordByPongo2(in *pongo2.Value, start *pongo2.Value, length *pongo2.Value, symbol *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(Substr(in.String(), start.Integer(), length.Integer(), symbol.String()))\n}\n\nfunc Cropword(in string, start int, length int, symbol string) string {\n\treturn Substr(in, start, length, symbol)\n}\n\nfunc File(s string) string {\n\tif len(s) > 0 {\n\t\tif strings.HasPrefix(s, \"http\") || strings.HasPrefix(s, \"/identicon\") {\n\t\t\treturn s\n\t\t} else {\n\t\t\treturn \"/file\" + s\n\t\t}\n\t}\n\treturn s\n}\n\nfunc Unix2TimeByPongo2(in *pongo2.Value, timeLayout *pongo2.Value) *pongo2.Value {\n\treturn pongo2.AsValue(time.Unix(int64(in.Integer()), 0).Format(timeLayout.String()))\n}\n\nfunc ConvertToBase64ByPongo2(in *pongo2.Value) *pongo2.Value ", "output": "{\n\treturn pongo2.AsValue(base64.StdEncoding.EncodeToString([]byte(in.String())))\n}"} {"input": "package testings\n\nimport (\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n)\n\n\n\n\n\n\n\nfunc RequireEqual(t *testing.T, want, got interface{}, message string, options ...cmp.Option) {\n\tt.Helper()\n\tif diff := cmp.Diff(want, got, options...); diff != \"\" {\n\t\tif message == \"\" {\n\t\t\tt.Fatalf(\"RequireEqual failed (-want +got):\\n%s\", diff)\n\t\t} else {\n\t\t\tt.Fatalf(\"RequireEqual failed: %q: (-want +got):\\n%s\", message, diff)\n\t\t}\n\t}\n}\n\nfunc AssertEqual(t *testing.T, want, got interface{}, message string, options ...cmp.Option) ", "output": "{\n\tt.Helper()\n\tif diff := cmp.Diff(want, got, options...); diff != \"\" {\n\t\tif message == \"\" {\n\t\t\tt.Errorf(\"AssertEqual failed (-want +got):\\n%s\", diff)\n\t\t} else {\n\t\t\tt.Errorf(\"AssertEqual failed: %q: (-want +got):\\n%s\", message, diff)\n\t\t}\n\t}\n}"} {"input": "package implementation\n\nimport (\n\t\"crypto/tls\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/go-openapi/swag\"\n\t\"github.com/go-swagger/go-swagger/examples/auto-configure/restapi/operations\"\n)\n\ntype ConfigureImpl struct {\n\tflags Flags\n}\n\ntype Flags struct {\n\tExample1 string `long:\"example1\" description:\"Sample for showing how to configure cmd-line flags\"`\n\tExample2 string `long:\"example2\" description:\"Further info at https://github.com/jessevdk/go-flags\"`\n}\n\nfunc (i *ConfigureImpl) ConfigureFlags(api *operations.AToDoListApplicationAPI) {\n\tapi.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{\n\t\t{\n\t\t\tShortDescription: \"Example Flags\",\n\t\t\tLongDescription: \"\",\n\t\t\tOptions: &i.flags,\n\t\t},\n\t}\n}\n\nfunc (i *ConfigureImpl) ConfigureTLS(tlsConfig *tls.Config) {\n}\n\nfunc (i *ConfigureImpl) ConfigureServer(s *http.Server, scheme, addr string) {\n\tif i.flags.Example1 != \"something\" {\n\t\tlog.Println(\"example1 argument is not something\")\n\t}\n}\n\nfunc (i *ConfigureImpl) SetupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}\n\n\n\nfunc (i *ConfigureImpl) CustomConfigure(api *operations.AToDoListApplicationAPI) {\n\tapi.Logger = log.Printf\n\tapi.ServerShutdown = func() {\n\t\tlog.Printf(\"Running ServerShutdown function\")\n\t}\n}\n\nfunc (i *ConfigureImpl) SetupGlobalMiddleware(handler http.Handler) http.Handler ", "output": "{\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tlog.Printf(\"Recieved request on path: %v\", req.URL.String())\n\t\thandler.ServeHTTP(w, req)\n\t})\n}"} {"input": "package leetcode\n\nconst MAX_INT32 = 1<<31 - 1\nconst MIN_INT32 = -1 << 31\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\nfunc maxInt(a, b int) int {\n\tif a < b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}\n\nfunc minInt(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}\n\nfunc absInt(num int) int {\n\tif num > 0 {\n\t\treturn num\n\t} else {\n\t\treturn -num\n\t}\n}\n\nfunc qsortInt(nums []int) []int {\n\tif len(nums) <= 1 {\n\t\treturn nums\n\t}\n\n\thead, tail := 0, len(nums)-1\n\tidx, mid := 1, nums[0]\n\tfor head < tail {\n\t\tif nums[idx] > mid {\n\t\t\tnums[idx], nums[tail] = nums[tail], nums[idx]\n\t\t\ttail--\n\t\t} else {\n\t\t\tnums[idx], nums[head] = nums[head], nums[idx]\n\t\t\thead++\n\t\t\tidx++\n\t\t}\n\t}\n\tnums[head] = mid\n\tqsortInt(nums[:head])\n\tqsortInt(nums[head+1:])\n\treturn nums\n}\n\ntype Stack struct {\n\tdata []rune\n}\n\nfunc (s *Stack) push(data rune) {\n\ts.data = append(s.data, data)\n}\n\n\n\nfunc (s Stack) empty() bool {\n\treturn len(s.data) == 0\n}\n\nfunc (s *Stack) pop() rune ", "output": "{\n\tif len(s.data) == 0 {\n\t\treturn 0\n\t}\n\tret := s.data[len(s.data)-1]\n\ts.data = s.data[:len(s.data)-1]\n\treturn ret\n}"} {"input": "package retry_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/ae6rt/retry\"\n)\n\n\n\nfunc TestRetryExceeded(t *testing.T) ", "output": "{\n\tr := retry.New(3, retry.DefaultBackoffFunc)\n\ttries := 0\n\terr := r.Try(func() error {\n\t\ttries += 1\n\t\treturn errors.New(\"woops\")\n\t})\n\tif err == nil {\n\t\tt.Fatalf(\"Expecting error\\n\")\n\t}\n\tif tries != 3 {\n\t\tt.Fatalf(\"Expecting 3 but got %d\\n\", tries)\n\t}\n}"} {"input": "package balanced\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n)\n\ntype Customer struct {\n\tAddress *Address `json:\"address,omitempty\"`\n\tBusinessName string `json:\"business_name,omitempty\"`\n\tCreatedAt time.Time `json:\"created_at,omitempty\"`\n\tDobMonth int `json:\"dob_month,omitempty\"`\n\tDobYear int `json:\"dob_year,omitempty\"`\n\tEin string `json:\"ein,omitempty\"`\n\tEmail string `json:\"email,omitempty\"`\n\tID string `json:\"id,omitempty\"`\n\tMeta map[string]interface{} `json:\"meta,omitempty\"`\n\tName string `json:\"name,omitempty\"`\n\tPhone string `json:\"phone,omitempty\"`\n\tSSNLast4 string `json:\"ssn_last4,omitempty\"`\n\tMerchantStatus string `json:\"merchant_status,omitempty\"`\n}\n\ntype customerResponse struct {\n\tCustomers []*Customer `json:\"customers\"`\n}\n\nfunc (c *Customer) path() string {\n\treturn \"/customers\"\n}\n\nfunc (c *Customer) getID() string {\n\treturn c.ID\n}\n\n\n\nfunc (c *Customer) singleResponse(data []byte) {\n\tparsedResponse := new(customerResponse)\n\tjson.Unmarshal(data, &parsedResponse)\n\t*c = *parsedResponse.Customers[0]\n}\n\nfunc (c *Customer) canDelete() bool {\n\treturn true\n}\n\nfunc (c *Customer) IsVerified() bool {\n\treturn c.MerchantStatus == \"underwritten\"\n}\n\nfunc (c *Customer) getOwnerPath() string ", "output": "{\n\treturn \"\"\n}"} {"input": "package iso20022\n\n\ntype ATMContext20 struct {\n\n\tSessionReference *Max35Text `xml:\"SsnRef,omitempty\"`\n\n\tService *ATMService24 `xml:\"Svc\"`\n}\n\nfunc (a *ATMContext20) SetSessionReference(value string) {\n\ta.SessionReference = (*Max35Text)(&value)\n}\n\n\n\nfunc (a *ATMContext20) AddService() *ATMService24 ", "output": "{\n\ta.Service = new(ATMService24)\n\treturn a.Service\n}"} {"input": "package local \n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/tiborvass/docker/errdefs\"\n\t\"github.com/pkg/errors\"\n)\n\ntype optsConfig struct{}\n\n\n\nfunc (r *Root) scopedPath(realPath string) bool {\n\tif strings.HasPrefix(realPath, filepath.Join(r.scope, volumesPathName)) && realPath != filepath.Join(r.scope, volumesPathName) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc setOpts(v *localVolume, opts map[string]string) error {\n\tif len(opts) > 0 {\n\t\treturn errdefs.InvalidParameter(errors.New(\"options are not supported on this platform\"))\n\t}\n\treturn nil\n}\n\n\n\nfunc (v *localVolume) mount() error {\n\treturn nil\n}\n\nfunc (v *localVolume) postMount() error {\n\treturn nil\n}\n\nfunc (v *localVolume) CreatedAt() (time.Time, error) {\n\tfileInfo, err := os.Stat(v.path)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\tft := fileInfo.Sys().(*syscall.Win32FileAttributeData).CreationTime\n\treturn time.Unix(0, ft.Nanoseconds()), nil\n}\n\nfunc (v *localVolume) needsMount() bool ", "output": "{\n\treturn false\n}"} {"input": "package scaleway\n\nimport (\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/scaleway/scaleway-cli/pkg/api\"\n)\n\n\nfunc Bool(val bool) *bool {\n\treturn &val\n}\n\n\nfunc String(val string) *string {\n\treturn &val\n}\n\n\n\n\n\n\nfunc waitForServerState(s *api.ScalewayAPI, serverID string, targetState string) error {\n\tvar server *api.ScalewayServer\n\tvar err error\n\n\tvar currentState string\n\n\tfor {\n\t\tserver, err = s.GetServer(serverID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif currentState != server.State {\n\t\t\tlog.Printf(\"[DEBUG] Server changed state to %q\\n\", server.State)\n\t\t\tcurrentState = server.State\n\t\t}\n\t\tif server.State == targetState {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\treturn nil\n}\n\nfunc deleteServerSafe(s *api.ScalewayAPI, serverID string) error ", "output": "{\n\tserver, err := s.GetServer(serverID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif server.State != \"stopped\" {\n\t\tif err := s.PostServerAction(serverID, \"poweroff\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := waitForServerState(s, serverID, \"stopped\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := s.DeleteServer(serverID); err != nil {\n\t\treturn err\n\t}\n\tif rootVolume, ok := server.Volumes[\"0\"]; ok {\n\t\tif err := s.DeleteVolume(rootVolume.Identifier); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package idxfile\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\n\t\"github.com/src-d/go-git-fixtures\"\n\t\"gopkg.in/src-d/go-git.v4/plumbing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc (s *IdxfileSuite) TestEncode(c *C) {\n\texpected := &Idxfile{}\n\texpected.Add(plumbing.NewHash(\"4bfc730165c370df4a012afbb45ba3f9c332c0d4\"), 82, 82)\n\texpected.Add(plumbing.NewHash(\"8fa2238efdae08d83c12ee176fae65ff7c99af46\"), 42, 42)\n\n\tbuf := bytes.NewBuffer(nil)\n\te := NewEncoder(buf)\n\t_, err := e.Encode(expected)\n\tc.Assert(err, IsNil)\n\n\tidx := &Idxfile{}\n\td := NewDecoder(buf)\n\terr = d.Decode(idx)\n\tc.Assert(err, IsNil)\n\n\tc.Assert(idx.Entries, DeepEquals, expected.Entries)\n}\n\n\n\nfunc (s *IdxfileSuite) TestDecodeEncode(c *C) ", "output": "{\n\tfixtures.ByTag(\"packfile\").Test(c, func(f *fixtures.Fixture) {\n\t\texpected, err := ioutil.ReadAll(f.Idx())\n\t\tc.Assert(err, IsNil)\n\n\t\tidx := &Idxfile{}\n\t\td := NewDecoder(bytes.NewBuffer(expected))\n\t\terr = d.Decode(idx)\n\t\tc.Assert(err, IsNil)\n\n\t\tresult := bytes.NewBuffer(nil)\n\t\te := NewEncoder(result)\n\t\tsize, err := e.Encode(idx)\n\t\tc.Assert(err, IsNil)\n\n\t\tc.Assert(size, Equals, len(expected))\n\t\tc.Assert(result.Bytes(), DeepEquals, expected)\n\t})\n}"} {"input": "package identify\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewPostNodesIdentifierObmIdentifyParams() *PostNodesIdentifierObmIdentifyParams {\n\tvar ()\n\treturn &PostNodesIdentifierObmIdentifyParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\nfunc NewPostNodesIdentifierObmIdentifyParamsWithTimeout(timeout time.Duration) *PostNodesIdentifierObmIdentifyParams {\n\tvar ()\n\treturn &PostNodesIdentifierObmIdentifyParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype PostNodesIdentifierObmIdentifyParams struct {\n\n\tBody *bool\n\tIdentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *PostNodesIdentifierObmIdentifyParams) WithBody(body *bool) *PostNodesIdentifierObmIdentifyParams {\n\to.Body = body\n\treturn o\n}\n\n\nfunc (o *PostNodesIdentifierObmIdentifyParams) WithIdentifier(identifier string) *PostNodesIdentifierObmIdentifyParams {\n\to.Identifier = identifier\n\treturn o\n}\n\n\n\n\nfunc (o *PostNodesIdentifierObmIdentifyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error ", "output": "{\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetBodyParam(o.Body); err != nil {\n\t\treturn err\n\t}\n\n\tif err := r.SetPathParam(\"identifier\", o.Identifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package assert\n\nimport (\n\t\"testing\"\n)\n\nfunc IntEquals(t *testing.T, actual int, expected int) {\n\tif actual != expected {\n\t\tt.Fatalf(\"%#v != %#v\", actual, expected)\n\t}\n}\n\nfunc Float32Equals(t *testing.T, actual float32, expected float32) {\n\tif actual != expected {\n\t\tt.Fatalf(\"%#v != %#v\", actual, expected)\n\t}\n}\n\nfunc StringEquals(t *testing.T, actual string, expected string) {\n\tif actual != expected {\n\t\tt.Fatalf(\"%#v != %#v\", actual, expected)\n\t}\n}\n\nfunc IntListEquals(t *testing.T, actualList []int, expectedList []int) {\n\tIntEquals(t, len(actualList), len(expectedList))\n\tfor i, expected := range expectedList {\n\t\tIntEquals(t, actualList[i], expected)\n\t}\n}\n\n\n\nfunc IntListListEquals(t *testing.T, actualList [][]int, expectedList [][]int) ", "output": "{\n\tif len(actualList) != len(expectedList) {\n\t\tt.Fatalf(\"%#v != %#v\", actualList, expectedList)\n\t}\n\tfor i, expected := range expectedList {\n\t\tIntListEquals(t, actualList[i], expected)\n\t}\n}"} {"input": "package ig\n\nimport \"fmt\"\n\n\nfunc (ic *IntelliClimate) SetTempTarget(target float64) error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\nfunc (ic *IntelliClimate) SetCO2Target(target float64) error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\nfunc (ic *IntelliClimate) SetRHTarget(target float64) error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\nfunc (ic *IntelliClimate) EnableCO2Dosing() error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\n\n\nfunc (ic *IntelliClimate) DisableCO2Dosing() error ", "output": "{\n\treturn fmt.Errorf(\"not implemented\")\n}"} {"input": "package vm\n\nimport (\n\t\"github.com/expanse-org/go-expanse/common\"\n\t\"github.com/expanse-org/go-expanse/common/math\"\n\t\"github.com/holiman/uint256\"\n)\n\n\n\nfunc calcMemSize64(off, l *uint256.Int) (uint64, bool) {\n\tif !l.IsUint64() {\n\t\treturn 0, true\n\t}\n\treturn calcMemSize64WithUint(off, l.Uint64())\n}\n\n\n\n\nfunc calcMemSize64WithUint(off *uint256.Int, length64 uint64) (uint64, bool) {\n\tif length64 == 0 {\n\t\treturn 0, false\n\t}\n\toffset64, overflow := off.Uint64WithOverflow()\n\tif overflow {\n\t\treturn 0, true\n\t}\n\tval := offset64 + length64\n\treturn val, val < offset64\n}\n\n\n\n\n\n\nfunc toWordSize(size uint64) uint64 {\n\tif size > math.MaxUint64-31 {\n\t\treturn math.MaxUint64/32 + 1\n\t}\n\n\treturn (size + 31) / 32\n}\n\nfunc allZero(b []byte) bool {\n\tfor _, byte := range b {\n\t\tif byte != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc getData(data []byte, start uint64, size uint64) []byte ", "output": "{\n\tlength := uint64(len(data))\n\tif start > length {\n\t\tstart = length\n\t}\n\tend := start + size\n\tif end > length {\n\t\tend = length\n\t}\n\treturn common.RightPadBytes(data[start:end], int(size))\n}"} {"input": "package gosignal\n\nimport (\n\t\"log\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\ntype ListWithMaxLength struct {\n\txs []string\n\tmax_length int\n}\n\ntype FloatListWithMax struct {\n\txs []float64\n\tmax float64\n}\n\n\nfunc ConvertArgsToLists(args []string) *ListWithMaxLength {\n\treturn NewListWithMaxLength(args)\n}\n\nfunc NewFloatListWithMax(args []float64) *FloatListWithMax {\n\tif len(args) == 0 {\n\t\treturn nil\n\t}\n\tmax := args[0]\n\tfor _, arg := range args {\n\t\tif arg > max {\n\t\t\tmax = arg\n\t\t}\n\t}\n\treturn &FloatListWithMax{args, max}\n}\n\n\nfunc NewListWithMaxLength(args []string) *ListWithMaxLength {\n\tmax_length := 0\n\tfor _, arg := range args {\n\t\tif len(arg) > max_length {\n\t\t\tmax_length = len(arg)\n\t\t}\n\t}\n\treturn &ListWithMaxLength{args, max_length}\n}\n\n\nfunc ConvertListOfArgsToLists(args [][]string) *ListWithMaxLength {\n\tvar converted []string\n\tfor _, sl := range args {\n\t\tfor _, s := range sl {\n\t\t\tconverted = append(converted, s)\n\t\t}\n\t}\n\treturn NewListWithMaxLength(converted)\n}\n\n\n\n\nfunc Wrap(arg string, i int) string {\n\treturn string(arg[i%len(arg)])\n}\n\ntype PyObjectBase int \nfunc WrapPyObjectBase(arg [][]PyObjectBase, i int) PyObjectBase {\n\tx := arg[i%len(arg)]\n\treturn x[0]\n}\n\n\n\n\n\n\n\n\nfunc GetVersion() (int, int, int) ", "output": "{\n\tv := strings.Split(PYO_VERSION, \".\")\n\tif len(v) != 3 {\n\t\tlog.Fatalln(\"Unexpected version string formatting:\", PYO_VERSION)\n\t}\n\tmajor, err := strconv.Atoi(v[0])\n\tif err != nil {\n\t\tlog.Fatalln(\"Not a number:\", v[0])\n\t}\n\tminor, err := strconv.Atoi(v[1])\n\tif err != nil {\n\t\tlog.Fatalln(\"Not a number:\", v[1])\n\t}\n\trev, err := strconv.Atoi(v[2])\n\tif err != nil {\n\t\tlog.Fatalln(\"Not a number:\", v[2])\n\t}\n\treturn major, minor, rev\n}"} {"input": "package xmodule\n\nimport (\n\t\"fmt\"\n\tmsg \"github.com/Centimitr/xmessage\"\n)\n\ntype Comment struct{}\n\n\nfunc (m Comment) GetMessages(ctx *msg.Ctx) {\n\tfmt.Println(\"M\")\n}\nfunc init() {\n\tvar m Comment\n\tmsg.LoadModule(m)\n}\n\nfunc (m Comment) GetIndexComments(ctx *msg.Ctx) ", "output": "{\n\tfmt.Println(\"C\")\n}"} {"input": "package roletemplate\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/rancher/norman/httperror\"\n\t\"github.com/rancher/norman/types\"\n\t\"github.com/rancher/norman/types/values\"\n\tv3 \"github.com/rancher/types/apis/management.cattle.io/v3\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n)\n\nconst (\n\tRTVersion = \"cleanup.cattle.io/rtUpgradeCluster\"\n\tOldRTVersion = \"field.cattle.io/rtUpgrade\"\n)\n\n\n\ntype rtStore struct {\n\ttypes.Store\n\n\trtLister v3.RoleTemplateLister\n}\n\nfunc (s *rtStore) Delete(apiContext *types.APIContext, schema *types.Schema, id string) (map[string]interface{}, error) {\n\troleTemplates, err := s.rtLister.List(\"\", labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, rt := range roleTemplates {\n\t\tfor _, parent := range rt.RoleTemplateNames {\n\t\t\tif parent == id {\n\t\t\t\treturn nil, httperror.NewAPIError(httperror.Conflict, fmt.Sprintf(\"roletemplate [%s] cannot be deleted because roletemplate [%s] inherits from it\", id, rt.Name))\n\t\t\t}\n\t\t}\n\t}\n\treturn s.Store.Delete(apiContext, schema, id)\n}\n\nfunc (s *rtStore) Create(apiContext *types.APIContext, schema *types.Schema, data map[string]interface{}) (map[string]interface{}, error) {\n\n\tvalues.PutValue(data, \"true\", \"metadata\", \"annotations\", RTVersion)\n\n\treturn s.Store.Create(apiContext, schema, data)\n}\n\nfunc Wrap(store types.Store, rtLister v3.RoleTemplateLister) types.Store ", "output": "{\n\treturn &rtStore{\n\t\tStore: store,\n\t\trtLister: rtLister,\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n)\n\nconst (\n\tdeviceAliasDir = \"/run/ignition/dev_aliases\"\n\tretrySymlinkDelay = 10 * time.Millisecond\n\tretrySymlinkTimeout = 30 * time.Second\n\tretrySymlinkCount = int(retrySymlinkTimeout / retrySymlinkDelay)\n)\n\n\n\nfunc DeviceAlias(path string) string {\n\treturn filepath.Join(deviceAliasDir, filepath.Clean(path))\n}\n\n\n\n\n\n\nfunc CreateDeviceAlias(path string) (string, error) {\n\ttarget, err := evalSymlinks(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\talias := DeviceAlias(path)\n\n\tif err := os.Remove(alias); err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif err = os.MkdirAll(filepath.Dir(alias), 0750); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tif err = os.Symlink(target, alias); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn target, nil\n}\n\nfunc evalSymlinks(path string) (res string, err error) ", "output": "{\n\tfor i := 0; i < retrySymlinkCount; i++ {\n\t\tres, err = filepath.EvalSymlinks(path)\n\t\tif err == nil {\n\t\t\treturn res, nil\n\t\t} else if os.IsNotExist(err) {\n\t\t\ttime.Sleep(retrySymlinkDelay)\n\t\t} else {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"Failed to evaluate symlink after %v: %v\", retrySymlinkTimeout, err)\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateNatGatewayRequest struct {\n\n\tCreateNatGatewayDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateNatGatewayRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateNatGatewayRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request CreateNatGatewayRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateNatGatewayResponse struct {\n\n\tRawResponse *http.Response\n\n\tNatGateway `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateNatGatewayResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateNatGatewayResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateNatGatewayRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package gzip\n\nimport (\n\t\"net/http\"\n\t\"path\"\n\n\t\"github.com/mholt/caddy/middleware\"\n)\n\n\ntype Filter interface {\n\tShouldCompress(*http.Request) bool\n}\n\n\nvar defaultExtensions = []string{\"\", \".txt\", \".htm\", \".html\", \".css\", \".php\", \".js\", \".json\", \".md\", \".xml\"}\n\n\nfunc DefaultExtFilter() ExtFilter {\n\tm := ExtFilter{Exts: make(Set)}\n\tfor _, extension := range defaultExtensions {\n\t\tm.Exts.Add(extension)\n\t}\n\treturn m\n}\n\n\ntype ExtFilter struct {\n\tExts Set\n}\n\n\nconst ExtWildCard = \"*\"\n\n\n\n\nfunc (e ExtFilter) ShouldCompress(r *http.Request) bool {\n\text := path.Ext(r.URL.Path)\n\treturn e.Exts.Contains(ExtWildCard) || e.Exts.Contains(ext)\n}\n\n\ntype PathFilter struct {\n\tIgnoredPaths Set\n}\n\n\n\n\nfunc (p PathFilter) ShouldCompress(r *http.Request) bool {\n\treturn !p.IgnoredPaths.ContainsFunc(func(value string) bool {\n\t\treturn middleware.Path(r.URL.Path).Matches(value)\n\t})\n}\n\n\ntype Set map[string]struct{}\n\n\nfunc (s Set) Add(value string) {\n\ts[value] = struct{}{}\n}\n\n\nfunc (s Set) Remove(value string) {\n\tdelete(s, value)\n}\n\n\nfunc (s Set) Contains(value string) bool {\n\t_, ok := s[value]\n\treturn ok\n}\n\n\n\n\n\n\nfunc (s Set) ContainsFunc(f func(string) bool) bool ", "output": "{\n\tfor k, _ := range s {\n\t\tif f(k) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package mock_driver\n\nimport (\n\tnet \"net\"\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n)\n\n\ntype MockNetworkAPIs struct {\n\tctrl *gomock.Controller\n\trecorder *MockNetworkAPIsMockRecorder\n}\n\n\ntype MockNetworkAPIsMockRecorder struct {\n\tmock *MockNetworkAPIs\n}\n\n\nfunc NewMockNetworkAPIs(ctrl *gomock.Controller) *MockNetworkAPIs {\n\tmock := &MockNetworkAPIs{ctrl: ctrl}\n\tmock.recorder = &MockNetworkAPIsMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockNetworkAPIs) EXPECT() *MockNetworkAPIsMockRecorder {\n\treturn m.recorder\n}\n\n\nfunc (m *MockNetworkAPIs) SetupNS(arg0, arg1, arg2 string, arg3 *net.IPNet, arg4 int, arg5 []string, arg6 bool) error {\n\tret := m.ctrl.Call(m, \"SetupNS\", arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}\n\n\n\n\n\nfunc (m *MockNetworkAPIs) TeardownNS(arg0 *net.IPNet, arg1 int) error {\n\tret := m.ctrl.Call(m, \"TeardownNS\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}\n\n\nfunc (mr *MockNetworkAPIsMockRecorder) TeardownNS(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"TeardownNS\", reflect.TypeOf((*MockNetworkAPIs)(nil).TeardownNS), arg0, arg1)\n}\n\nfunc (mr *MockNetworkAPIsMockRecorder) SetupNS(arg0, arg1, arg2, arg3, arg4, arg5, arg6 interface{}) *gomock.Call ", "output": "{\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SetupNS\", reflect.TypeOf((*MockNetworkAPIs)(nil).SetupNS), arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n}"} {"input": "package tensorflow\n\n\n\nimport \"C\"\n\nimport \"unsafe\"\n\n\ntype Operation struct {\n\tc *C.TF_Operation\n\tg *Graph\n}\n\n\nfunc (op *Operation) Name() string {\n\treturn C.GoString(C.TF_OperationName(op.c))\n}\n\n\nfunc (op *Operation) Type() string {\n\treturn C.GoString(C.TF_OperationOpType(op.c))\n}\n\n\nfunc (op *Operation) NumOutputs() int {\n\treturn int(C.TF_OperationNumOutputs(op.c))\n}\n\n\n\n\n\n\n\n\nfunc (op *Operation) OutputListSize(output string) (int, error) {\n\tcname := C.CString(output)\n\tdefer C.free(unsafe.Pointer(cname))\n\tstatus := newStatus()\n\tn := C.TF_OperationOutputListLength(op.c, cname, status.c)\n\treturn int(n), status.Err()\n}\n\n\nfunc (op *Operation) Output(i int) Output {\n\treturn Output{op, i}\n}\n\n\n\n\n\ntype Output struct {\n\tOp *Operation\n\n\tIndex int\n}\n\n\nfunc (p Output) DataType() DataType {\n\treturn DataType(C.TF_OperationOutputType(p.c()))\n}\n\n\n\n\nfunc (p Output) c() C.TF_Output {\n\treturn C.TF_Output{oper: p.Op.c, index: C.int(p.Index)}\n}\n\nfunc (p Output) canBeAnInput() {}\n\n\n\n\n\n\n\n\n\n\ntype Input interface {\n\tcanBeAnInput()\n}\n\n\n\ntype OutputList []Output\n\nfunc (l OutputList) canBeAnInput() {}\n\nfunc (p Output) Shape() Shape ", "output": "{\n\tstatus := newStatus()\n\tport := p.c()\n\tndims := C.TF_GraphGetTensorNumDims(p.Op.g.c, port, status.c)\n\tif err := status.Err(); err != nil {\n\t\treturn Shape{}\n\t}\n\tif ndims < 0 {\n\t\treturn Shape{}\n\t}\n\tif ndims == 0 {\n\t\treturn ScalarShape()\n\t}\n\tdims := make([]C.int64_t, ndims)\n\tC.TF_GraphGetTensorShape(p.Op.g.c, port, &dims[0], ndims, status.c)\n\tif err := status.Err(); err != nil {\n\t\treturn Shape{}\n\t}\n\tret := Shape{dims: make([]int64, ndims)}\n\tfor i := 0; i < int(ndims); i++ {\n\t\tret.dims[i] = int64(dims[i])\n\t}\n\treturn ret\n}"} {"input": "package single\n\nimport (\n\t\"io\"\n\n\t\"github.com/ondrej-smola/mesos-go-http/lib/codec/framing\"\n)\n\ntype Reader struct {\n\tr io.Reader\n}\n\nfunc New(r io.Reader) *Reader {\n\treturn &Reader{r: r}\n}\n\n\n\n\n\nfunc (rr *Reader) ReadFrame(p []byte) (endOfFrame bool, n int, err error) {\n\tn, err = rr.r.Read(p)\n\n\tif err == io.EOF {\n\t\tendOfFrame = true\n\t}\n\n\treturn\n}\n\nfunc (rr *Reader) Read(p []byte) (int, error) {\n\treturn rr.r.Read(p)\n}\n\nfunc NewProvider() framing.Provider ", "output": "{\n\treturn func(r io.Reader) framing.Reader {\n\t\treturn New(r)\n\t}\n}"} {"input": "package mysqlctl\n\nimport (\n\t\"fmt\"\n)\n\n\ntype MysqlDaemon interface {\n\tGetMasterAddr() (string, error)\n\n\tGetMysqlPort() (int, error)\n}\n\n\n\ntype FakeMysqlDaemon struct {\n\tMasterAddr string\n\n\tMysqlPort int\n}\n\n\n\nfunc (fmd *FakeMysqlDaemon) GetMysqlPort() (int, error) {\n\tif fmd.MysqlPort == -1 {\n\t\treturn 0, fmt.Errorf(\"FakeMysqlDaemon.GetMysqlPort returns an error\")\n\t}\n\treturn fmd.MysqlPort, nil\n}\n\nfunc (fmd *FakeMysqlDaemon) GetMasterAddr() (string, error) ", "output": "{\n\tif fmd.MasterAddr == \"\" {\n\t\treturn \"\", ErrNotSlave\n\t}\n\tif fmd.MasterAddr == \"ERROR\" {\n\t\treturn \"\", fmt.Errorf(\"FakeMysqlDaemon.GetMasterAddr returns an error\")\n\t}\n\treturn fmd.MasterAddr, nil\n}"} {"input": "package resources\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/rancher/rancher-compose-executor/project\"\n\t\"github.com/rancher/rancher-compose-executor/project/options\"\n)\n\nfunc DependenciesCreate(p *project.Project) (project.ResourceSet, error) {\n\tdependencies := make([]*Dependency, 0, len(p.Config.Dependencies))\n\tfor name, config := range p.Config.Dependencies {\n\t\tdependencies = append(dependencies, &Dependency{\n\t\t\tproject: p,\n\t\t\tname: name,\n\t\t\ttemplate: config.Template,\n\t\t\tversion: config.Version,\n\t\t})\n\t}\n\treturn &Dependencies{\n\t\tdependencies: dependencies,\n\t}, nil\n}\n\ntype Dependencies struct {\n\tdependencies []*Dependency\n}\n\n\n\ntype Dependency struct {\n\tproject *project.Project\n\tname string\n\ttemplate string\n\tversion string\n}\n\nfunc (d *Dependency) EnsureItExists(ctx context.Context) error {\n\treturn nil\n}\n\nfunc (h *Dependencies) Initialize(ctx context.Context, _ options.Options) error ", "output": "{\n\tfor _, dependency := range h.dependencies {\n\t\tif err := dependency.EnsureItExists(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package middleware\n\nimport (\n\t\"github.com/drone/drone/shared/model\"\n\t\"github.com/zenazn/goji/web\"\n)\n\n\n\nfunc UserToC(c *web.C, user *model.User) {\n\tc.Env[\"user\"] = user\n}\n\n\n\nfunc RepoToC(c *web.C, repo *model.Repo) {\n\tc.Env[\"repo\"] = repo\n}\n\n\n\nfunc RoleToC(c *web.C, role *model.Perm) {\n\tc.Env[\"role\"] = role\n}\n\n\n\n\n\n\n\n\n\nfunc ToRepo(c *web.C) *model.Repo {\n\tvar v = c.Env[\"repo\"]\n\tif v == nil {\n\t\treturn nil\n\t}\n\tr, ok := v.(*model.Repo)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn r\n}\n\n\n\n\nfunc ToRole(c *web.C) *model.Perm {\n\tvar v = c.Env[\"role\"]\n\tif v == nil {\n\t\treturn nil\n\t}\n\tp, ok := v.(*model.Perm)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn p\n}\n\nfunc ToUser(c *web.C) *model.User ", "output": "{\n\tvar v = c.Env[\"user\"]\n\tif v == nil {\n\t\treturn nil\n\t}\n\tu, ok := v.(*model.User)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn u\n}"} {"input": "package redis\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype ManagementClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\nfunc New(subscriptionID string) ManagementClient {\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient ", "output": "{\n\treturn ManagementClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\n\n\n\nfunc pong(pings <-chan string, pongs chan<- string) {\n\n \n msg := <-pings\n\n \n pongs <- msg\n}\n\nfunc main() {\n pings := make(chan string, 1)\n pongs := make(chan string, 1)\n\n \n \n ping(pings, \"passed message\")\n\n \n pong(pings, pongs)\n\n \n fmt.Println(<-pongs)\n\n \n \n}\n\nfunc ping(pings chan<- string, msg string) ", "output": "{\n\n \n pings <- msg\n}"} {"input": "package olog\n\nimport (\n\t\"fmt\"\n)\n\n\ntype DirectLogger struct {\n\twriters map[string]Writer\n}\n\n\nfunc NewDirectLogger() *DirectLogger {\n\treturn &DirectLogger{\n\t\twriters: make(map[string]Writer),\n\t}\n}\n\n\n\n\n\nfunc (dl *DirectLogger) RegisterWriter(writer Writer) {\n\tif writer != nil {\n\t\tdl.writers[writer.UniqueID()] = writer\n\t}\n}\n\n\nfunc (dl *DirectLogger) RemoveWriter(uniqueID string) {\n\tdelete(dl.writers, uniqueID)\n}\n\n\nfunc (dl *DirectLogger) GetWriter(uniqueID string) (writer Writer) {\n\treturn dl.writers[uniqueID]\n}\n\nfunc (dl *DirectLogger) Log(level Level,\n\tmodule string,\n\tfmtstr string,\n\targs ...interface{}) ", "output": "{\n\tif level == PrintLevel {\n\t\treturn\n\t}\n\tfmtstr = ToString(level) + \" [\" + module + \"] \" + fmtstr\n\tmsg := fmt.Sprintf(fmtstr, args...)\n\tfor _, writer := range dl.writers {\n\t\tif writer.IsEnabled() {\n\t\t\twriter.Write(msg)\n\t\t}\n\t}\n}"} {"input": "package initramfs\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/u-root/u-root/pkg/cpio\"\n\t\"github.com/u-root/u-root/pkg/ulog\"\n)\n\n\ntype CPIOArchiver struct {\n\tcpio.RecordFormat\n}\n\n\n\n\n\n\nfunc (ca CPIOArchiver) OpenWriter(l ulog.Logger, path, goos, goarch string) (Writer, error) {\n\tif len(path) == 0 && len(goos) == 0 && len(goarch) == 0 {\n\t\treturn nil, fmt.Errorf(\"passed no path, GOOS, and GOARCH to CPIOArchiver.OpenWriter\")\n\t}\n\tif len(path) == 0 {\n\t\tpath = fmt.Sprintf(\"/tmp/initramfs.%s_%s.cpio\", goos, goarch)\n\t}\n\tf, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tl.Printf(\"Filename is %s\", path)\n\treturn osWriter{ca.RecordFormat.Writer(f), f}, nil\n}\n\n\ntype osWriter struct {\n\tcpio.RecordWriter\n\n\tf *os.File\n}\n\n\nfunc (o osWriter) Finish() error {\n\terr := cpio.WriteTrailer(o)\n\to.f.Close()\n\treturn err\n}\n\n\n\n\nfunc (ca CPIOArchiver) Reader(r io.ReaderAt) Reader ", "output": "{\n\treturn ca.RecordFormat.Reader(r)\n}"} {"input": "package hashcat3\n\ntype Dictionary struct {\n\tName string\n\tPath string\n}\n\ntype Dictionaries []Dictionary\n\n\nfunc (d Dictionaries) Swap(i, j int) {\n\td[i], d[j] = d[j], d[i]\n}\n\nfunc (d Dictionaries) Less(i, j int) bool {\n\treturn d[i].Name < d[j].Name\n}\n\nfunc (d Dictionaries) Len() int ", "output": "{\n\treturn len(d)\n\n}"} {"input": "package language\n\n\n\nconst (\n\tcurDigitBits = 3\n\tcurDigitMask = 1<> curDigitBits)\n}\n\n\n\n\ntype langAliasType int8\n\nconst (\n\tlangDeprecated langAliasType = iota\n\tlangMacro\n\tlangLegacy\n\n\tlangAliasTypeUnknown langAliasType = -1\n)\n\nfunc (c currencyInfo) decimals() int ", "output": "{\n\treturn int(c & curDigitMask)\n}"} {"input": "package bunny\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype Bunny interface {\n\tHealthy() bool\n}\n\ntype HttpBunny struct {\n\turl string\n}\n\ntype BunnyStatus struct {\n\tName string `json:\"name\"`\n\tStatus string `json:\"status\"`\n\tProcessTime int `json:\"timeToEvaluate\"`\n}\n\n\n\n\nfunc(bunny HttpBunny) Update() (bunnyStatus BunnyStatus) {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\n\tres, err := client.Get(bunny.url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tbunnyStatus.Status = \"ERROR\"\n\t}\n\tbody, err := ioutil.ReadAll(res.Body)\n\tres.Body.Close()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tbunnyStatus.Status = \"ERROR\"\n\t}else{\n\t\tjson.Unmarshal(body, &bunnyStatus)\n\t}\n\treturn\n}\n\nfunc NewBunny(url string) (bunny HttpBunny) ", "output": "{\n\tbunny.url = url\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\n\t\"github.com/PalmStoneGames/polymer\"\n)\n\n\n\ntype NameTag struct {\n\t*polymer.Proto\n\n\tID int64 `polymer:\"bind\"`\n\tName string `polymer:\"bind\"`\n\tNameChange chan *polymer.Event `polymer:\"handler\"`\n}\n\nfunc (n *NameTag) Created() {\n\tn.ID = rand.Int63()\n\n\tgo func() {\n\t\tfor _ = range n.NameChange {\n\t\t\tfmt.Printf(\"%v: HandleNameChange event. Name = %v\\n\", n.ID, n.Name)\n\t\t}\n\t}()\n}\n\nfunc (n *NameTag) Ready() {\n\tfmt.Printf(\"%v: Initial Name = %v\\n\", n.ID, n.Name)\n}\n\nfunc main() {}\n\nfunc init() ", "output": "{\n\tpolymer.Register(\"name-tag\", &NameTag{})\n}"} {"input": "package thirdpartyresourcedata\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"k8s.io/kubernetes/pkg/api/unversioned\"\n\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n)\n\nfunc ExtractGroupVersionKind(list *extensions.ThirdPartyResourceList) ([]unversioned.GroupVersion, []unversioned.GroupVersionKind, error) {\n\tgvs := []unversioned.GroupVersion{}\n\tgvks := []unversioned.GroupVersionKind{}\n\tfor ix := range list.Items {\n\t\trsrc := &list.Items[ix]\n\t\tkind, group, err := ExtractApiGroupAndKind(rsrc)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tfor _, version := range rsrc.Versions {\n\t\t\tgv := unversioned.GroupVersion{Group: group, Version: version.Name}\n\t\t\tgvs = append(gvs, gv)\n\t\t\tgvks = append(gvks, unversioned.GroupVersionKind{Group: group, Version: version.Name, Kind: kind})\n\t\t}\n\t}\n\treturn gvs, gvks, nil\n}\n\nfunc convertToCamelCase(input string) string {\n\tresult := \"\"\n\ttoUpper := true\n\tfor ix := range input {\n\t\tchar := input[ix]\n\t\tif toUpper {\n\t\t\tresult = result + string([]byte{(char - 32)})\n\t\t\ttoUpper = false\n\t\t} else if char == '-' {\n\t\t\ttoUpper = true\n\t\t} else {\n\t\t\tresult = result + string([]byte{char})\n\t\t}\n\t}\n\treturn result\n}\n\n\n\nfunc ExtractApiGroupAndKind(rsrc *extensions.ThirdPartyResource) (kind string, group string, err error) ", "output": "{\n\tparts := strings.Split(rsrc.Name, \".\")\n\tif len(parts) < 3 {\n\t\treturn \"\", \"\", fmt.Errorf(\"unexpectedly short resource name: %s, expected at least ..\", rsrc.Name)\n\t}\n\treturn convertToCamelCase(parts[0]), strings.Join(parts[1:], \".\"), nil\n}"} {"input": "package niftycloud_test\n\nimport (\n\t\"time\"\n\n\t\"github.com/higebu/go-niftycloud/niftycloud\"\n\t. \"gopkg.in/check.v1\"\n)\n\n\n\nfunc (S) TestAttemptNextHasNext(c *C) {\n\ta := niftycloud.AttemptStrategy{}.Start()\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.Next(), Equals, false)\n\n\ta = niftycloud.AttemptStrategy{}.Start()\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.HasNext(), Equals, false)\n\tc.Assert(a.Next(), Equals, false)\n\n\ta = niftycloud.AttemptStrategy{Total: 2e8}.Start()\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.HasNext(), Equals, true)\n\ttime.Sleep(2e8)\n\tc.Assert(a.HasNext(), Equals, true)\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.Next(), Equals, false)\n\n\ta = niftycloud.AttemptStrategy{Total: 1e8, Min: 2}.Start()\n\ttime.Sleep(1e8)\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.HasNext(), Equals, true)\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.HasNext(), Equals, false)\n\tc.Assert(a.Next(), Equals, false)\n}\n\nfunc (S) TestAttemptTiming(c *C) ", "output": "{\n\ttestAttempt := niftycloud.AttemptStrategy{\n\t\tTotal: 0.25e9,\n\t\tDelay: 0.1e9,\n\t}\n\twant := []time.Duration{0, 0.1e9, 0.2e9, 0.2e9}\n\tgot := make([]time.Duration, 0, len(want)) \n\tt0 := time.Now()\n\tfor a := testAttempt.Start(); a.Next(); {\n\t\tgot = append(got, time.Now().Sub(t0))\n\t}\n\tgot = append(got, time.Now().Sub(t0))\n\tc.Assert(got, HasLen, len(want))\n\tconst margin = 0.01e9\n\tfor i, got := range want {\n\t\tlo := want[i] - margin\n\t\thi := want[i] + margin\n\t\tif got < lo || got > hi {\n\t\t\tc.Errorf(\"attempt %d want %g got %g\", i, want[i].Seconds(), got.Seconds())\n\t\t}\n\t}\n}"} {"input": "package memcachep\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n)\n\ntype Stats map[string]fmt.Stringer\n\n\ntype FuncStat struct {\n\tCallable func() string\n}\n\nfunc (f *FuncStat) String() string {\n\treturn f.Callable()\n}\n\n\ntype StaticStat struct {\n\tValue string\n}\n\nfunc (s *StaticStat) String() string {\n\treturn s.Value\n}\n\n\ntype CounterStat struct {\n\tCount int\n\tcalculations chan int\n}\n\nfunc (c *CounterStat) Increment(num int) {\n\tc.calculations <- num\n}\n\nfunc (c *CounterStat) SetCount(num int) {\n\tc.Count = num\n}\n\n\n\nfunc (c *CounterStat) String() string {\n\treturn strconv.Itoa(c.Count)\n}\n\nfunc (c *CounterStat) work() {\n\tfor num := range c.calculations {\n\t\tc.Count = c.Count + num\n\t}\n}\n\nfunc NewCounterStat() *CounterStat {\n\tc := &CounterStat{}\n\tc.calculations = make(chan int, 100)\n\tgo c.work()\n\treturn c\n}\n\nfunc NewStats() Stats {\n\ts := make(Stats)\n\ts[\"pid\"] = &StaticStat{strconv.Itoa(os.Getpid())}\n\ts[\"version\"] = &StaticStat{VERSION}\n\ts[\"golang\"] = &StaticStat{runtime.Version()}\n\ts[\"goroutines\"] = &FuncStat{func() string { return strconv.Itoa(runtime.NumGoroutine()) }}\n\ts[\"cpu_num\"] = &StaticStat{strconv.Itoa(runtime.NumCPU())}\n\ts[\"total_connections\"] = NewCounterStat()\n\ts[\"curr_connections\"] = NewCounterStat()\n\ts[\"cmd_get\"] = NewCounterStat()\n\treturn s\n}\n\nfunc (c *CounterStat) Decrement(num int) ", "output": "{\n\tc.calculations <- -num\n}"} {"input": "package validating\n\nimport (\n\t\"io\"\n\n\t\"k8s.io/apiserver/pkg/admission\"\n\t\"k8s.io/apiserver/pkg/admission/configuration\"\n\t\"k8s.io/apiserver/pkg/admission/plugin/webhook/generic\"\n)\n\nconst (\n\tPluginName = \"ValidatingAdmissionWebhook\"\n)\n\n\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(configFile io.Reader) (admission.Interface, error) {\n\t\tplugin, err := NewValidatingAdmissionWebhook(configFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn plugin, nil\n\t})\n}\n\n\ntype Plugin struct {\n\t*generic.Webhook\n}\n\nvar _ admission.ValidationInterface = &Plugin{}\n\n\nfunc NewValidatingAdmissionWebhook(configFile io.Reader) (*Plugin, error) {\n\thandler := admission.NewHandler(admission.Connect, admission.Create, admission.Delete, admission.Update)\n\twebhook, err := generic.NewWebhook(handler, configFile, configuration.NewValidatingWebhookConfigurationManager, newValidatingDispatcher)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Plugin{webhook}, nil\n}\n\n\n\n\nfunc (a *Plugin) Validate(attr admission.Attributes) error ", "output": "{\n\treturn a.Webhook.Dispatch(attr)\n}"} {"input": "package ocvp\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListWorkRequestsRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tResourceId *string `mandatory:\"false\" contributesTo:\"query\" name:\"resourceId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request ListWorkRequestsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ListWorkRequestsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ListWorkRequestsRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListWorkRequestsResponse struct {\n\n\tRawResponse *http.Response\n\n\tWorkRequestCollection `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n}\n\nfunc (response ListWorkRequestsResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListWorkRequestsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListWorkRequestsRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package synctest\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nconst (\n\ttimeout = 100 * time.Millisecond\n)\n\nfunc TestNotifyLock(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tch := nl.NotifyLock()\n\tnl.Lock()\n\tselect {\n\tcase <-ch:\n\tcase <-time.After(timeout):\n\t\tt.Fatalf(\"didn't receive on channel after %s\", timeout)\n\t}\n}\n\nfunc TestNotifyLockAlreadyLocked(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tnl.Lock()\n\tch := nl.NotifyLock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"received on channel\")\n\tcase <-time.After(timeout):\n\t}\n}\n\nfunc TestNotifyLockOnUnlock(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tnl.Lock()\n\tch := nl.NotifyLock()\n\tnl.Unlock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"got a lock notification on unlock\")\n\tcase <-time.After(timeout):\n\t}\n}\n\nfunc TestNotifyUnlock(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tch := nl.NotifyUnlock()\n\tnl.Lock()\n\tnl.Unlock()\n\tselect {\n\tcase <-ch:\n\tcase <-time.After(timeout):\n\t\tt.Fatalf(\"didn't get unlock notification after %s\", timeout)\n\t}\n}\n\nfunc TestNotifyUnlockAlreadyUnlocked(t *testing.T) {\n\tnl := NewNotifyingLocker()\n\tnl.Lock()\n\tnl.Unlock()\n\tch := nl.NotifyUnlock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"got unlock notification\")\n\tcase <-time.After(timeout):\n\t}\n}\n\n\n\nfunc TestNofifyUnlockOnLock(t *testing.T) ", "output": "{\n\tnl := NewNotifyingLocker()\n\tch := nl.NotifyUnlock()\n\tnl.Lock()\n\tselect {\n\tcase <-ch:\n\t\tt.Fatalf(\"got unlock notification on lock\")\n\tcase <-time.After(timeout):\n\t}\n}"} {"input": "package service\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"testing\"\n\n\t\"go-common/library/ecode\"\n)\n\n\n\nfunc TestService_Oauth_Expires(t *testing.T) {\n\tonce.Do(startService)\n\tak := \"c1e220e12fd4c89a0c5449b9f8c7b062\"\n\tif _, err := s.Oauth(context.TODO(), s.appMap[_gameAppKey], ak, \"\"); err != ecode.AccessTokenExpires {\n\t\tt.Errorf(\"res is not correct, expected error %v, but got %v\", ecode.AccessTokenExpires, err)\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestService_Oauth(t *testing.T) ", "output": "{\n\tonce.Do(startService)\n\tak := \"4de8aecfafc7f91cb650d6371efb1b63\"\n\texpectMid := int64(110000139)\n\tif res, err := s.Oauth(context.TODO(), s.appMap[_gameAppKey], ak, \"\"); err != nil {\n\t\tt.Errorf(\"s.Oauth() error(%v)\", err)\n\t\tt.FailNow()\n\t} else if res == nil || res.Mid != expectMid {\n\t\tt.Errorf(\"res is not correct, expected res with mid %d but got %v\", expectMid, res)\n\t\tt.FailNow()\n\t} else {\n\t\tstr, _ := json.Marshal(res)\n\t\tt.Logf(\"res: %s\", str)\n\t}\n}"} {"input": "package v2store_test\n\nimport (\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"github.com/coreos/etcd/clientv3\"\n\t\"github.com/coreos/etcd/etcdserver/api/v2v3\"\n\t\"github.com/coreos/etcd/etcdserver/v2store\"\n\t\"github.com/coreos/etcd/integration\"\n\n\t\"github.com/coreos/pkg/capnslog\"\n\t\"google.golang.org/grpc/grpclog\"\n)\n\nfunc init() {\n\tcapnslog.SetGlobalLogLevel(capnslog.CRITICAL)\n\tclientv3.SetLogger(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, ioutil.Discard))\n}\n\ntype v2v3TestStore struct {\n\tv2store.Store\n\tclus *integration.ClusterV3\n\tt *testing.T\n}\n\n\n\nfunc newTestStore(t *testing.T, ns ...string) StoreCloser {\n\tclus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})\n\treturn &v2v3TestStore{\n\t\tv2v3.NewStore(clus.Client(0), \"/v2/\"),\n\t\tclus,\n\t\tt,\n\t}\n}\n\nfunc (s *v2v3TestStore) Close() ", "output": "{ s.clus.Terminate(s.t) }"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\ntype testURLs struct {\n\tinput string\n\texpected string\n}\n\nvar errorString = \"For: %s, expected: %s, got: %s\"\n\nfunc Test_parseURLSuccess(t *testing.T) {\n\ttestCases := []testURLs{\n\t\t{\n\t\t\t\"github.com/skisulli/caddyshack\",\n\t\t\t\"http://github.com/skisulli/caddyshack\",\n\t\t},\n\t\t{\n\t\t\t\"https://github.com/skisulli/caddyshack\",\n\t\t\t\"https://github.com/skisulli/caddyshack\",\n\t\t},\n\t}\n\n\tfor _, testCase := range testCases {\n\t\tactual, _ := parseURL(testCase.input)\n\n\t\tif actual.String() != testCase.expected {\n\t\t\tt.Errorf(errorString, testCase.input, testCase.expected, actual)\n\t\t}\n\t}\n}\n\n\n\nfunc Test_parseURLError(t *testing.T) ", "output": "{\n\tactual, err := parseURL(\":test\")\n\n\tif err == nil {\n\t\tt.Errorf(errorString, \":test\", \"an error\", actual)\n\t}\n}"} {"input": "package gzip\n\nimport (\n\t\"net/http\"\n\t\"path\"\n\n\t\"github.com/mholt/caddy/middleware\"\n)\n\n\ntype Filter interface {\n\tShouldCompress(*http.Request) bool\n}\n\n\nvar defaultExtensions = []string{\"\", \".txt\", \".htm\", \".html\", \".css\", \".php\", \".js\", \".json\", \".md\", \".xml\"}\n\n\nfunc DefaultExtFilter() ExtFilter {\n\tm := ExtFilter{Exts: make(Set)}\n\tfor _, extension := range defaultExtensions {\n\t\tm.Exts.Add(extension)\n\t}\n\treturn m\n}\n\n\ntype ExtFilter struct {\n\tExts Set\n}\n\n\nconst ExtWildCard = \"*\"\n\n\n\n\nfunc (e ExtFilter) ShouldCompress(r *http.Request) bool {\n\text := path.Ext(r.URL.Path)\n\treturn e.Exts.Contains(ExtWildCard) || e.Exts.Contains(ext)\n}\n\n\ntype PathFilter struct {\n\tIgnoredPaths Set\n}\n\n\n\n\nfunc (p PathFilter) ShouldCompress(r *http.Request) bool {\n\treturn !p.IgnoredPaths.ContainsFunc(func(value string) bool {\n\t\treturn middleware.Path(r.URL.Path).Matches(value)\n\t})\n}\n\n\ntype Set map[string]struct{}\n\n\nfunc (s Set) Add(value string) {\n\ts[value] = struct{}{}\n}\n\n\nfunc (s Set) Remove(value string) {\n\tdelete(s, value)\n}\n\n\n\n\n\n\n\nfunc (s Set) ContainsFunc(f func(string) bool) bool {\n\tfor k, _ := range s {\n\t\tif f(k) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (s Set) Contains(value string) bool ", "output": "{\n\t_, ok := s[value]\n\treturn ok\n}"} {"input": "package collector\n\nimport (\n\t\"src/fullerite/metric\"\n\t\"src/fullerite/test_utils\"\n\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestTestConfigureEmptyConfig(t *testing.T) {\n\tconfig := make(map[string]interface{})\n\ttest := NewTest(nil, 123, nil).(*Test)\n\ttest.Configure(config)\n\n\tassert.Equal(t,\n\t\ttest.Interval(),\n\t\t123,\n\t\t\"should be the default collection interval\",\n\t)\n}\n\n\n\nfunc TestTestConfigureMetricName(t *testing.T) {\n\tconfig := make(map[string]interface{})\n\tconfig[\"metricName\"] = \"lala\"\n\n\ttestChannel := make(chan metric.Metric)\n\ttestLogger := test_utils.BuildLogger()\n\n\ttest := NewTest(testChannel, 123, testLogger).(*Test)\n\ttest.Configure(config)\n\n\tgo test.Collect()\n\n\tselect {\n\tcase m := <-test.Channel():\n\t\tassert.Equal(t, m.Name, \"lala\")\n\tcase <-time.After(4 * time.Second):\n\t\tt.Fail()\n\t}\n}\n\nfunc TestTestCollect(t *testing.T) {\n\tconfig := make(map[string]interface{})\n\n\ttestChannel := make(chan metric.Metric)\n\ttestLogger := test_utils.BuildLogger()\n\n\tmockGen := func() float64 {\n\t\treturn 4.0\n\t}\n\n\ttest := NewTest(testChannel, 123, testLogger).(*Test)\n\ttest.Configure(config)\n\ttest.generator = mockGen\n\n\tgo test.Collect()\n\n\tselect {\n\tcase m := <-test.Channel():\n\t\tassert.Equal(t, 4.0, m.Value)\n\t\treturn\n\tcase <-time.After(4 * time.Second):\n\t\tt.Fail()\n\t}\n}\n\nfunc TestTestConfigure(t *testing.T) ", "output": "{\n\tconfig := make(map[string]interface{})\n\tconfig[\"interval\"] = 9999\n\n\ttest := NewTest(nil, 12, nil).(*Test)\n\ttest.Configure(config)\n\n\tassert.Equal(t,\n\t\ttest.Interval(),\n\t\t9999,\n\t\t\"should be the defined interval\",\n\t)\n}"} {"input": "package compiler\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/go-on/lib/html/element\"\n\t\"github.com/go-on/lib/misc/replacer\"\n)\n\n\n\ntype placeholderHandler struct {\n\treplacer.Placeholder\n\thttp.Handler\n}\n\nfunc mkPhHandler(e *element.Element, key string, buf *bytes.Buffer) (phdl []*placeholderHandler) ", "output": "{\n\tphdl = []*placeholderHandler{}\n\telement.Pre(e, buf)\n\n\n\tif len(e.Children) == 0 || element.Is(e, element.SelfClosing) {\n\t\telement.Post(e, buf)\n\t\treturn\n\t}\n\n\tfor i, in := range e.Children {\n\t\tswitch ch := in.(type) {\n\t\tcase *element.Element:\n\t\t\tphdl = append(\n\t\t\t\tphdl,\n\t\t\t\tmkPhHandler(ch, fmt.Sprintf(\"%s/%d\", key, i), buf)...,\n\t\t\t)\n\t\tcase http.Handler:\n\t\t\tpha := replacer.Placeholder(fmt.Sprintf(\"%s-%d\", key, i))\n\t\t\tphdl = append(phdl, &placeholderHandler{pha, ch})\n\t\t\tbuf.WriteString(pha.String())\n\t\tdefault:\n\t\t\tbuf.WriteString(in.String())\n\t\t}\n\t}\n\n\telement.Post(e, buf)\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\nconst (\n\tFileType_File = 1\n\tFileType_Directory = 2\n)\n\nfunc IfString(condition bool, trueVal, falseVal string) string {\n\tif condition {\n\t\treturn trueVal\n\t}\n\treturn falseVal\n}\n\nfunc IfInt(condition bool, trueVal, falseVal int) int {\n\tif condition {\n\t\treturn trueVal\n\t}\n\treturn falseVal\n}\n\n\n\n\n\nfunc CreateDir(dir string, mode os.FileMode) error {\n\t_, err := os.Stat(dir)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn os.MkdirAll(dir, mode)\n\t\t}\n\t}\n\treturn err\n}\n\nfunc CopyFile(src, dest string, mode os.FileMode) error {\n\tdata, err := ioutil.ReadFile(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(dest, data, mode)\n}\n\n\nfunc GetFileType(path string) (fileType int, err error) {\n\tvar fi os.FileInfo\n\n\tfi, err = os.Stat(path)\n\tif err == nil {\n\t\tfileType = IfInt(fi.IsDir(), FileType_Directory, FileType_File)\n\t} else if os.IsNotExist(err) {\n\t\terr = fmt.Errorf(\"can not find directory or file: %s\", path)\n\t}\n\treturn\n}\n\nfunc ExpandString(s string, data map[string]string) string ", "output": "{\n\treturn os.Expand(s, func(p string) string {\n\t\tv, _ := data[p]\n\t\treturn v\n\t})\n}"} {"input": "package logger\n\nimport (\n\t\"github.com/raincious/trap/trap/core/types\"\n\n\t\"bufio\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype FilePrinter struct {\n\twriter *bufio.Writer\n\n\twriteCounts uint16\n}\n\nfunc NewFilePrinter(w *bufio.Writer) (*FilePrinter, *types.Throw) {\n\t_, writeErr := w.Write([]byte(\"\"))\n\n\tif writeErr != nil {\n\t\treturn nil, types.ConvertError(writeErr)\n\t}\n\n\treturn &FilePrinter{\n\t\twriter: w,\n\t}, nil\n}\n\n\n\nfunc (l *FilePrinter) Info(c types.String, t time.Time, m types.String) {\n\tl.save(\"INF\", c, t, m)\n}\n\nfunc (l *FilePrinter) Debug(c types.String, t time.Time, m types.String) {\n\tl.save(\"DBG\", c, t, m)\n}\n\nfunc (l *FilePrinter) Warning(c types.String, t time.Time, m types.String) {\n\tl.save(\"WRN\", c, t, m)\n}\n\nfunc (l *FilePrinter) Error(c types.String, t time.Time, m types.String) {\n\tl.save(\"ERR\", c, t, m)\n}\n\nfunc (l *FilePrinter) Print(c types.String, t time.Time, m types.String) {\n\tl.save(\"DEF\", c, t, m)\n}\n\nfunc (l *FilePrinter) save(w types.String, c types.String,\n\tt time.Time, m types.String) ", "output": "{\n\n\t_, err := l.writer.WriteString(fmt.Sprintf(\"<%s> %s [%s]: %s\\r\\n\",\n\t\tw, c, t.Format(time.StampMilli), m))\n\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Can't write log file due to error: %s\", err))\n\t}\n\n\tl.writeCounts += 1\n\n\tif l.writeCounts > 10 {\n\t\tl.writer.Flush()\n\n\t\tl.writeCounts = 0\n\t}\n}"} {"input": "package tests\n\nimport (\n\t\"go2o/core/infrastructure/domain\"\n\t\"testing\"\n)\n\n\nfunc TestMasterPwd(t *testing.T) {\n\tuser := \"master\"\n\tpwd := \"123456\"\n\tsha1 := domain.Sha1(domain.Md5(pwd) + user + domain.Sha1OffSet)\n\tt.Log(sha1)\n}\n\nfunc TestMasterPwd2(t *testing.T) {\n\tuser := \"master\"\n\tpwd := \"fs888888@txxfmall\"\n\tsha1 := domain.Sha1(domain.Md5(pwd) + user + domain.Sha1OffSet)\n\tt.Log(sha1)\n\tt.Log(domain.Sha1OffSet)\n}\n\nfunc TestMemberPwd(t *testing.T) {\n\tpwd := domain.Md5(\"594488\")\n\tt.Log(\"--pwd=\", pwd, \"\\n\")\n\tpwd = domain.Sha1(pwd)\n\tt.Log(\"--pwd=\", pwd, \"\\n\")\n}\n\n\n\n\nfunc TestMerchantPwd(t *testing.T) ", "output": "{\n\tpwd := \"123456\"\n\tencPwd := domain.MerchantSha1Pwd(pwd)\n\tt.Log(encPwd)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"time\"\n)\n\n\n\n\n\n\nfunc main() {\n\tvar mem runtime.MemStats\n\tprintStats(mem)\n\tfor i := 0; i < 10; i++ {\n\t\ts := make([]byte, 50000000)\n\t\tif s == nil {\n\t\t\tfmt.Println(\"Operation failed!\")\n\t\t\tprintStats(mem)\n\t\t}\n\t}\n}\n\nfunc printStats(mem runtime.MemStats) ", "output": "{\n\truntime.ReadMemStats(&mem)\n\tfmt.Println(\"mem.Alloc:\", mem.Alloc)\n\tfmt.Println(\"mem.TotalAlloc:\", mem.TotalAlloc)\n\tfmt.Println(\"mem.HeapAlloc:\", mem.HeapAlloc)\n\tfmt.Println(\"mem.NumGC:\", mem.NumGC)\n\tfmt.Println(\"-----\")\n}"} {"input": "package etude0\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestGetAndPut(t *testing.T) {\n\n\tdb := &DB{}\n\tdb.Open(\"./tmp/foo\")\n\n\terr := db.Put(\"aaa\", \"foo\")\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\terr = db.Put(\"bbb\", \"bar\")\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\ts, err := db.Get(\"aaa\")\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif s != \"foo\" {\n\t\tt.Errorf(\"Get(\\\"aaa\\\") = \\\"%s\\\", want \\\"foo\\\"\", s)\n\t}\n\n\ts, err = db.Get(\"bbb\")\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif s != \"bar\" {\n\t\tt.Errorf(\"Get(\\\"bbb\\\") = \\\"%s\\\", want \\\"bar\\\"\", s)\n\t}\n}\n\n\n\nfunc TestMoreGetAndPut(t *testing.T) ", "output": "{\n\n\tdb := &DB{}\n\tdb.Open(\"./tmp/bar\")\n\n\tn := 10000\n\n\tfor i := 0; i < n; i++ {\n\t\tkey := fmt.Sprintf(\"%d\", i)\n\t\tvalue := fmt.Sprintf(\"%010d\", i)\n\t\tdb.Put(key, value)\n\t}\n\n\tfor i := 0; i < n; i++ {\n\t\tkey := fmt.Sprintf(\"%d\", i)\n\t\tvalue := fmt.Sprintf(\"%010d\", i)\n\t\ts, err := db.Get(key)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t}\n\t\tif s != value {\n\t\t\tt.Errorf(\"Get(\\\"%s\\\") = \\\"%s\\\", want \\\"%s\\\"\", key, s, value)\n\t\t}\n\t}\n}"} {"input": "package cloudformation\n\n\n\ntype AWSECSService_DeploymentConfiguration struct {\n\n\tMaximumPercent int `json:\"MaximumPercent,omitempty\"`\n\n\tMinimumHealthyPercent int `json:\"MinimumHealthyPercent,omitempty\"`\n}\n\n\n\n\nfunc (r *AWSECSService_DeploymentConfiguration) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::ECS::Service.DeploymentConfiguration\"\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/lmorg/murex/lang\"\n\t\"github.com/lmorg/murex/test/count\"\n)\n\n\n\nfunc TestMurex(t *testing.T) {\n\tcount.Tests(t, 1)\n\n\tlang.InitEnv()\n\n\tblock := []rune(\"a [Mon..Fri]->regexp m/^T/\")\n\n\t_, err := lang.ShellProcess.Fork(lang.F_NO_STDIN | lang.F_NO_STDOUT | lang.F_NO_STDERR).Execute(block)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n}\n\nfunc TestRunCommandLine(t *testing.T) {\n\tcount.Tests(t, 1)\n\n\trunCommandLine(`out: \"testing\" -> null`)\n}\n\n\n\nfunc TestRunSourceGzMods(t *testing.T) {\n\tcount.Tests(t, 1)\n\n\tfile := \"test/source.mx.gz\"\n\trunSource(file)\n}\n\nfunc TestRunSource(t *testing.T) ", "output": "{\n\tcount.Tests(t, 1)\n\n\tfile := \"test/source.mx\"\n\trunSource(file)\n}"} {"input": "package service\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"go-common/app/service/main/assist/conf\"\n\t\"go-common/app/service/main/assist/dao/account\"\n\t\"go-common/app/service/main/assist/dao/assist\"\n\t\"go-common/app/service/main/assist/dao/message\"\n\t\"go-common/library/log\"\n\t\"go-common/library/queue/databus\"\n)\n\n\ntype Service struct {\n\tc *conf.Config\n\tass *assist.Dao\n\tacc *account.Dao\n\tmsg *message.Dao\n\trelationSub *databus.Databus\n\tcacheChan chan func()\n\twg sync.WaitGroup\n}\n\n\nfunc New(c *conf.Config) *Service {\n\ts := &Service{\n\t\tc: c,\n\t\tass: assist.New(c),\n\t\tacc: account.New(c),\n\t\tmsg: message.New(c),\n\t\tcacheChan: make(chan func(), 1024),\n\t\trelationSub: databus.New(c.RelationSub),\n\t}\n\ts.wg.Add(1)\n\tgo s.relationConsumer()\n\ts.wg.Add(1)\n\tgo s.cacheproc()\n\treturn s\n}\n\n\nfunc (s *Service) Ping(c context.Context) (err error) {\n\tif err = s.ass.Ping(c); err != nil {\n\t\tlog.Error(\"s.ass.Dao.Ping err(%v)\", err)\n\t}\n\treturn\n}\n\n\nfunc (s *Service) asyncCache(f func()) {\n\tselect {\n\tcase s.cacheChan <- f:\n\tdefault:\n\t\tlog.Warn(\"assist cacheproc chan full\")\n\t}\n}\n\n\nfunc (s *Service) cacheproc() {\n\tfor {\n\t\tf := <-s.cacheChan\n\t\tf()\n\t}\n}\n\n\n\n\nfunc (s *Service) Close() ", "output": "{\n\ts.relationSub.Close()\n\ts.wg.Wait()\n}"} {"input": "package gitea\n\nimport (\n\t\"fmt\"\n\n\t\"code.gitea.io/gitea/modules/structs\"\n)\n\n\ntype Branch = structs.Branch\n\n\n\n\n\nfunc (c *Client) GetRepoBranch(user, repo, branch string) (*Branch, error) {\n\tb := new(Branch)\n\treturn b, c.getParsedResponse(\"GET\", fmt.Sprintf(\"/repos/%s/%s/branches/%s\", user, repo, branch), nil, nil, &b)\n}\n\nfunc (c *Client) ListRepoBranches(user, repo string) ([]*Branch, error) ", "output": "{\n\tbranches := make([]*Branch, 0, 10)\n\treturn branches, c.getParsedResponse(\"GET\", fmt.Sprintf(\"/repos/%s/%s/branches\", user, repo), nil, nil, &branches)\n}"} {"input": "package util\n\nimport \"testing\"\n\nfunc TestToCharsAscii(t *testing.T) {\n\tchars := ToChars([]byte(\"foobar\"))\n\tif !chars.inBytes || chars.ToString() != \"foobar\" || !chars.inBytes {\n\t\tt.Error()\n\t}\n}\n\nfunc TestCharsLength(t *testing.T) {\n\tchars := ToChars([]byte(\"\\tabc한글 \"))\n\tif chars.inBytes || chars.Length() != 8 || chars.TrimLength() != 5 {\n\t\tt.Error()\n\t}\n}\n\nfunc TestCharsToString(t *testing.T) {\n\ttext := \"\\tabc한글 \"\n\tchars := ToChars([]byte(text))\n\tif chars.ToString() != text {\n\t\tt.Error()\n\t}\n}\n\n\n\nfunc TestTrimLength(t *testing.T) ", "output": "{\n\tcheck := func(str string, exp uint16) {\n\t\tchars := ToChars([]byte(str))\n\t\ttrimmed := chars.TrimLength()\n\t\tif trimmed != exp {\n\t\t\tt.Errorf(\"Invalid TrimLength result for '%s': %d (expected %d)\",\n\t\t\t\tstr, trimmed, exp)\n\t\t}\n\t}\n\tcheck(\"hello\", 5)\n\tcheck(\"hello \", 5)\n\tcheck(\"hello \", 5)\n\tcheck(\" hello\", 5)\n\tcheck(\" hello\", 5)\n\tcheck(\" hello \", 5)\n\tcheck(\" hello \", 5)\n\tcheck(\"h o\", 5)\n\tcheck(\" h o \", 5)\n\tcheck(\" \", 0)\n}"} {"input": "package elements\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestRegistryAddId(t *testing.T) {\n\tr := NewRegistry()\n\tc := NewComponent(\"cloud\", \"foo\", \"\")\n\n\tr.Add(c)\n\tc1 := Get(r, \"foo\")\n\tassert.Equal(t, c, c1)\n}\n\n\n\nfunc TestErrors(t *testing.T) {\n\tr := NewRegistry()\n\tc := NewComponent(\"cloud\", \"\", \"\")\n\n\terr := r.Add(nil)\n\tassert.Equal(t, errors.New(\"Nil given\"), err)\n\n\terr = r.Add(c)\n\tassert.Equal(t, errors.New(\"Neither alias nor identifier set\"), err)\n\n\tc1 := NewComponent(\"cloud\", \"foo\", \"bar\")\n\terr = r.Add(c1)\n\tassert.Equal(t, nil, err)\n\n\terr = r.Add(c1)\n\tassert.Equal(t, errors.New(\"Alias bar already exists\"), err)\n\n\tc2 := NewComponent(\"cloud\", \"foo\", \"\")\n\terr = r.Add(c2)\n\tassert.Equal(t, nil, err)\n\n\terr = r.Add(c2)\n\tassert.Equal(t, errors.New(\"Identifier foo already exists\"), err)\n}\n\nfunc TestRegistryAddAlias(t *testing.T) ", "output": "{\n\tr := NewRegistry()\n\tc := NewComponent(\"cloud\", \"foo\", \"bar\")\n\n\tr.Add(c)\n\tc1 := Get(r, \"bar\")\n\tassert.Equal(t, c, c1)\n\n\tc2 := Get(r, \"foo\")\n\tassert.Nil(t, c2)\n}"} {"input": "package config\n\nimport (\n\tcb \"github.com/hyperledger/fabric/protos/common\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n\t\"github.com/hyperledger/fabric/protos/utils\"\n)\n\nfunc ordererConfigGroup(key string, value []byte) *cb.ConfigGroup {\n\tresult := cb.NewConfigGroup()\n\tresult.Groups[OrdererGroupKey] = cb.NewConfigGroup()\n\tresult.Groups[OrdererGroupKey].Values[key] = &cb.ConfigValue{\n\t\tValue: value,\n\t}\n\treturn result\n}\n\n\nfunc TemplateConsensusType(typeValue string) *cb.ConfigGroup {\n\treturn ordererConfigGroup(ConsensusTypeKey, utils.MarshalOrPanic(&ab.ConsensusType{Type: typeValue}))\n}\n\n\nfunc TemplateBatchSize(batchSize *ab.BatchSize) *cb.ConfigGroup {\n\treturn ordererConfigGroup(BatchSizeKey, utils.MarshalOrPanic(batchSize))\n}\n\n\n\n\n\nfunc TemplateChannelRestrictions(maxChannels uint64) *cb.ConfigGroup {\n\treturn ordererConfigGroup(ChannelRestrictionsKey, utils.MarshalOrPanic(&ab.ChannelRestrictions{MaxCount: maxChannels}))\n}\n\n\nfunc TemplateKafkaBrokers(brokers []string) *cb.ConfigGroup {\n\treturn ordererConfigGroup(KafkaBrokersKey, utils.MarshalOrPanic(&ab.KafkaBrokers{Brokers: brokers}))\n}\n\nfunc TemplateBatchTimeout(batchTimeout string) *cb.ConfigGroup ", "output": "{\n\treturn ordererConfigGroup(BatchTimeoutKey, utils.MarshalOrPanic(&ab.BatchTimeout{Timeout: batchTimeout}))\n}"} {"input": "package chipecs\n\nimport (\n\t\"log\"\n\n\t\"engo.io/ecs\"\n\t\"engo.io/engo\"\n\t\"engo.io/engo/common\"\n\t\"github.com/vova616/chipmunk\"\n\t\"github.com/vova616/chipmunk/vect\"\n)\n\n\n\nfunc (ps *PhysicsSystem) Remove(basic ecs.BasicEntity) {\n\tdelete := -1\n\tfor index, e := range ps.entities {\n\t\tif e.BasicEntity.ID() == basic.ID() {\n\t\t\tdelete = index\n\t\t\tps.Space.RemoveBody(e.Shape.Body)\n\t\t\tbreak\n\t\t}\n\t}\n\tif delete >= 0 {\n\t\tps.entities = append(ps.entities[:delete], ps.entities[delete+1:]...)\n\t}\n}\n\n\nfunc (ps *PhysicsSystem) New(*ecs.World) {\n\tlog.Println(\"PhyiscsSystem was added to the scene.\")\n\tps.Space = chipmunk.NewSpace()\n\tps.Space.Gravity = vect.Vect{X: 0, Y: 0}\n}\n\n\n\n\n\nfunc (ps *PhysicsSystem) Add(basic *ecs.BasicEntity, physics *PhysicsComponent, space *common.SpaceComponent) {\n\tps.entities = append(ps.entities, physicsEntity{basic, physics, space})\n\tps.Space.AddBody(physics.Shape.Body)\n}\n\nfunc (ps *PhysicsSystem) Update(dt float32) ", "output": "{\n\tfor _, e := range ps.entities {\n\t\tpos := e.PhysicsComponent.Shape.Body.Position()\n\t\te.Position = engo.Point{X: float32(pos.X), Y: float32(pos.Y)}\n\t\te.Rotation = 0 \n\t}\n\tps.Space.Step(vect.Float(dt))\n}"} {"input": "package sacloud\n\n\ntype Icon struct {\n\t*Resource \n\tpropAvailability \n\tpropName \n\tpropScope \n\tpropTags \n\tpropCreatedAt \n\tpropModifiedAt \n\n\tURL string `json:\",omitempty\"` \n\tImage string `json:\",omitempty\"` \n}\n\n\ntype Image string\n\n\n\n\n\nfunc (icon *Icon) GetImage() string {\n\treturn icon.Image\n}\n\n\nfunc (icon *Icon) SetImage(image string) {\n\ticon.Image = image\n}\n\nfunc (icon *Icon) GetURL() string ", "output": "{\n\treturn icon.URL\n}"} {"input": "package election\n\nimport \"go.etcd.io/etcd/clientv3/concurrency\"\n\ntype clientOpts struct {\n\tsessionOpts []concurrency.SessionOption\n}\n\n\n\ntype ClientOption func(*clientOpts)\n\n\n\n\n\n\n\nfunc WithSessionOptions(opts ...concurrency.SessionOption) ClientOption ", "output": "{\n\treturn func(o *clientOpts) {\n\t\to.sessionOpts = opts\n\t}\n}"} {"input": "package cloudstorage\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n)\n\ntype MockStorage struct {\n\tPutRequest *http.Request\n\tGetURL *url.URL\n\tOriginallySigned bool\n\tListObjectsResponse *ListObjectsResponse\n}\n\nvar _ Storage = &MockStorage{}\n\nfunc (s *MockStorage) PresignPutObject(name string, accessType AccessType, header http.Header) (*http.Request, error) {\n\treturn s.PutRequest, nil\n}\n\nfunc (s *MockStorage) PresignGetObject(name string) (*url.URL, error) {\n\treturn s.GetURL, nil\n}\n\n\n\nfunc (s *MockStorage) RewriteGetURL(u *url.URL, name string) (*url.URL, bool, error) {\n\treturn s.GetURL, s.OriginallySigned, nil\n}\n\nfunc (s *MockStorage) ListObjects(r *ListObjectsRequest) (*ListObjectsResponse, error) {\n\treturn s.ListObjectsResponse, nil\n}\n\nfunc (s *MockStorage) DeleteObject(name string) error {\n\treturn nil\n}\n\nfunc (s *MockStorage) AccessType(header http.Header) AccessType {\n\treturn AccessTypeDefault\n}\n\nfunc (s *MockStorage) StandardToProprietary(header http.Header) http.Header {\n\treturn header\n}\n\nfunc (s *MockStorage) ProprietaryToStandard(header http.Header) http.Header {\n\treturn header\n}\n\nfunc (s *MockStorage) PresignHeadObject(name string) (*url.URL, error) ", "output": "{\n\treturn s.GetURL, nil\n}"} {"input": "package sacloud\n\n\ntype ENoteClass string\n\nvar (\n\tNoteClassShell = ENoteClass(\"shell\")\n\tNoteClassYAMLCloudConfig = ENoteClass(\"yaml_cloud_config\")\n)\n\n\nvar ENoteClasses = []ENoteClass{NoteClassShell, NoteClassYAMLCloudConfig}\n\n\ntype propNoteClass struct {\n\tClass ENoteClass `json:\",omitempty\"` \n}\n\n\n\n\n\nfunc (p *propNoteClass) SetClass(c ENoteClass) {\n\tp.Class = c\n}\n\n\nfunc (p *propNoteClass) GetClassStr() string {\n\treturn string(p.Class)\n}\n\n\nfunc (p *propNoteClass) SetClassByStr(c string) {\n\tp.Class = ENoteClass(c)\n}\n\nfunc (p *propNoteClass) GetClass() ENoteClass ", "output": "{\n\treturn p.Class\n}"} {"input": "package main\n\nimport \"testing\"\n\nvar percentEncodeTests = []struct {\n\tin string\n\tout string\n}{\n\t{\"Ladies + Gentlemen\", \"Ladies%20%2B%20Gentlemen\"},\n\t{\"An encoded string!\", \"An%20encoded%20string%21\"},\n\t{\"Dogs, Cats & Mice\", \"Dogs%2C%20Cats%20%26%20Mice\"},\n\t{\"☃\", \"%E2%98%83\"},\n}\n\n\n\nfunc TestPercentEncode(t *testing.T) ", "output": "{\n\tfor _, test := range percentEncodeTests {\n\t\tif got := percentEncode(test.in); got != test.out {\n\t\t\tt.Errorf(\"Got: %s\\t Want: %s\", got, test.out)\n\t\t}\n\t}\n}"} {"input": "package car\n\nimport (\n\t\"archive/tar\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\tcutil \"github.com/hyperledger/fabric/core/container/util\"\n\tpb \"github.com/hyperledger/fabric/protos\"\n\t\"github.com/spf13/viper\"\n)\n\n\n\n\n\nfunc (carPlatform *Platform) WritePackage(spec *pb.ChaincodeSpec, tw *tar.Writer) error {\n\n\tpath, err := download(spec.ChaincodeID.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspec.ChaincodeID.Name, err = generateHashcode(spec, path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error generating hashcode: %s\", err)\n\t}\n\n\tvar buf []string\n\n\tbuf = append(buf, viper.GetString(\"chaincode.car.Dockerfile\"))\n\tbuf = append(buf, \"COPY package.car /tmp/package.car\")\n\tbuf = append(buf, fmt.Sprintf(\"RUN chaintool buildcar /tmp/package.car -o $GOPATH/bin/%s && rm /tmp/package.car\", spec.ChaincodeID.Name))\n\n\tdockerFileContents := strings.Join(buf, \"\\n\")\n\tdockerFileSize := int64(len([]byte(dockerFileContents)))\n\n\tvar zeroTime time.Time\n\ttw.WriteHeader(&tar.Header{Name: \"Dockerfile\", Size: dockerFileSize, ModTime: zeroTime, AccessTime: zeroTime, ChangeTime: zeroTime})\n\ttw.Write([]byte(dockerFileContents))\n\n\terr = cutil.WriteFileToPackage(path, \"package.car\", tw)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc download(path string) (string, error) ", "output": "{\n\tif strings.HasPrefix(path, \"http://\") {\n\n\t\tvar tmp *os.File\n\t\tvar err error\n\t\ttmp, err = ioutil.TempFile(\"\", \"car\")\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Error creating temporary file: %s\", err)\n\t\t}\n\t\tdefer os.Remove(tmp.Name())\n\t\tdefer tmp.Close()\n\n\t\tresp, err := http.Get(path)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Error with HTTP GET: %s\", err)\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\t_, err = io.Copy(tmp, resp.Body)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Error downloading bytes: %s\", err)\n\t\t}\n\n\t\treturn tmp.Name(), nil\n\t}\n\n\treturn path, nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\t\"text/template\"\n)\n\nvar htmlTemplate = `\n\n\n \n \n Pinentry\n \n \n
\n\t\t\t\n\t\t\t\n\t\t
\n \n\n`\n\ntype password struct {\n\tPassword string\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/\", pinentry)\n\thttp.ListenAndServe(\":8001\", nil)\n}\n\n\n\nfunc handlePost(w http.ResponseWriter, r *http.Request) {\n\n\tif r.PostFormValue(\"password\") != \"\" {\n\t\tfmt.Println(r.PostFormValue(\"password\"))\n\t\tw.Write([]byte(\"password was submitted\"))\n\t\tos.Exit(0)\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tdefer r.Body.Close()\n\tvar t password\n\terr := decoder.Decode(&t)\n\tif err != nil {\n\t\tw.Write([]byte(\"{'error':'cannot parse json'}\"))\n\t\treturn\n\t}\n\n\tw.Write([]byte(\"{'message':'password was submitted'}\"))\n\tfmt.Println(t.Password)\n\n\tos.Exit(0)\n}\n\nfunc pinentry(w http.ResponseWriter, r *http.Request) ", "output": "{\n\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tt, _ := template.New(\"html\").Parse(htmlTemplate)\n\t\tt.Execute(w, nil)\n\tcase \"POST\":\n\t\thandlePost(w, r)\n\t}\n}"} {"input": "package main\n\nfunc main() {\n\tpoison()\n\ttest()\n}\n\n\nfunc poison() {\n\tvar large [256]uintptr\n\tfor i := range large {\n\t\tlarge[i] = 1\n\t}\n\tuse(large[:])\n}\n\n\n\n\n\nfunc compare(x **int) *int {\n\tvar y *int\n\tif x == &y {\n\t\tpanic(\"not possible\")\n\t}\n\tgrow()\n\tif x == &y {\n\t\tpanic(\"not possible\")\n\t}\n\treturn *x\n}\n\n\nfunc grow() {\n\tvar large [1 << 16]uintptr\n\tuse(large[:])\n}\n\n\nfunc use(_ []uintptr) { }\n\nfunc test() ", "output": "{\n\ta := 2\n\tx := &a\n\tif x != compare(&x) {\n\t\tpanic(\"not possible\")\n\t}\n}"} {"input": "package rpc\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestByGinkgo(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Base Suite\")\n}"} {"input": "package resourcelock\n\nimport (\n\t\"fmt\"\n\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tcoordinationv1 \"k8s.io/client-go/kubernetes/typed/coordination/v1\"\n\tcorev1 \"k8s.io/client-go/kubernetes/typed/core/v1\"\n)\n\nconst (\n\tLeaderElectionRecordAnnotationKey = \"control-plane.alpha.kubernetes.io/leader\"\n\tEndpointsResourceLock = \"endpoints\"\n\tConfigMapsResourceLock = \"configmaps\"\n\tLeasesResourceLock = \"leases\"\n)\n\n\n\n\n\ntype LeaderElectionRecord struct {\n\tHolderIdentity string `json:\"holderIdentity\"`\n\tLeaseDurationSeconds int `json:\"leaseDurationSeconds\"`\n\tAcquireTime metav1.Time `json:\"acquireTime\"`\n\tRenewTime metav1.Time `json:\"renewTime\"`\n\tLeaderTransitions int `json:\"leaderTransitions\"`\n}\n\n\ntype EventRecorder interface {\n\tEventf(obj runtime.Object, eventType, reason, message string, args ...interface{})\n}\n\n\n\ntype ResourceLockConfig struct {\n\tIdentity string\n\tEventRecorder EventRecorder\n}\n\n\n\n\n\n\ntype Interface interface {\n\tGet() (*LeaderElectionRecord, error)\n\n\tCreate(ler LeaderElectionRecord) error\n\n\tUpdate(ler LeaderElectionRecord) error\n\n\tRecordEvent(string)\n\n\tIdentity() string\n\n\tDescribe() string\n}\n\n\n\n\nfunc New(lockType string, ns string, name string, coreClient corev1.CoreV1Interface, coordinationClient coordinationv1.CoordinationV1Interface, rlc ResourceLockConfig) (Interface, error) ", "output": "{\n\tswitch lockType {\n\tcase EndpointsResourceLock:\n\t\treturn &EndpointsLock{\n\t\t\tEndpointsMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: name,\n\t\t\t},\n\t\t\tClient: coreClient,\n\t\t\tLockConfig: rlc,\n\t\t}, nil\n\tcase ConfigMapsResourceLock:\n\t\treturn &ConfigMapLock{\n\t\t\tConfigMapMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: name,\n\t\t\t},\n\t\t\tClient: coreClient,\n\t\t\tLockConfig: rlc,\n\t\t}, nil\n\tcase LeasesResourceLock:\n\t\treturn &LeaseLock{\n\t\t\tLeaseMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: name,\n\t\t\t},\n\t\t\tClient: coordinationClient,\n\t\t\tLockConfig: rlc,\n\t\t}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Invalid lock-type %s\", lockType)\n\t}\n}"} {"input": "package byte_tree\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/kentik/patricia\"\n)\n\n\n\n\n\n\nfunc (t *TreeV6) print() {\n\tbuf := make([]byte, 0)\n\tfor i := range t.nodes {\n\t\tbuf = buf[:0]\n\t\tfmt.Printf(\"%d: \\tleft: %d, right: %d, prefix: %032b %032b (%d), tags: (%d): %v\\n\", i, int(t.nodes[i].Left), int(t.nodes[i].Right), int(t.nodes[i].prefixLeft), int(t.nodes[i].prefixRight), int(t.nodes[i].prefixLength), t.nodes[i].TagCount, t.tagsForNode(buf, uint(i), nil))\n\t}\n}\n\nfunc (t *TreeV6) newNode(address patricia.IPv6Address, prefixLength uint) uint ", "output": "{\n\tavailCount := len(t.availableIndexes)\n\tif availCount > 0 {\n\t\tindex := t.availableIndexes[availCount-1]\n\t\tt.availableIndexes = t.availableIndexes[:availCount-1]\n\t\tt.nodes[index] = treeNodeV6{prefixLeft: address.Left, prefixRight: address.Right, prefixLength: prefixLength}\n\t\treturn index\n\t}\n\n\tt.nodes = append(t.nodes, treeNodeV6{prefixLeft: address.Left, prefixRight: address.Right, prefixLength: prefixLength})\n\treturn uint(len(t.nodes) - 1)\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\n\tbh \"github.com/kandoo/beehive\"\n)\n\nconst (\n\thelloDict = \"HelloDictionary\"\n\n\treplicationFactor = 2\n)\n\n\ntype Hello struct {\n\tName string \n}\n\n\ntype Broad struct {\n\tID int \n}\n\n\n\n\nfunc hmapf(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\tbh.CellKey{\n\t\t\tDict: helloDict,\n\t\t\tKey: msg.Data().(Hello).Name,\n\t\t},\n\t}\n}\n\nfunc brcvf(msg bh.Msg, ctx bh.RcvContext) error {\n\tctx.Printf(\"broad[%v] message %d was received\\n\", msg.IsBroadCast(), msg.Data().(Broad).ID)\n\n\treturn nil\n}\n\nfunc bmapf(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{{}}\n}\n\nfunc main() {\n\tapp := bh.NewApp(\"hello-world\", bh.Persistent(replicationFactor))\n\n\tif err := app.HandleFunc(Hello{}, hmapf, hrcvf); err != nil {\n\t\tlog.Fatalf(\"Hello Handle Func: %s\", err)\n\t}\n\n\tif err := app.HandleFunc(Broad{}, bmapf, brcvf); err != nil {\n\t\tlog.Fatalf(\"Board Handle Func: %s\", err)\n\t}\n\n\tgo bh.Emit(Hello{Name: \"Parham Alvani\"})\n\n\tgo bh.Emit(Hello{Name: \"HamidReza Alvani\"})\n\n\tgo bh.Emit(Broad{ID: 1})\n\n\tif err := bh.Start(); err != nil {\n\t\tlog.Fatalf(\"Start: %s\", err)\n\t}\n}\n\nfunc hrcvf(msg bh.Msg, ctx bh.RcvContext) error ", "output": "{\n\thello := msg.Data().(Hello)\n\n\tdict := ctx.Dict(helloDict)\n\n\tv, err := dict.Get(hello.Name)\n\n\tcnt := 0\n\tif err == nil {\n\t\tcnt = v.(int)\n\t}\n\n\tcnt++\n\n\tctx.Printf(\"hello %s (%d)!\\n\", hello.Name, cnt)\n\n\treturn dict.Put(hello.Name, cnt)\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype GetAutonomousPatchRequest struct {\n\n\tAutonomousPatchId *string `mandatory:\"true\" contributesTo:\"path\" name:\"autonomousPatchId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request GetAutonomousPatchRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request GetAutonomousPatchRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request GetAutonomousPatchRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype GetAutonomousPatchResponse struct {\n\n\tRawResponse *http.Response\n\n\tAutonomousPatch `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response GetAutonomousPatchResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response GetAutonomousPatchResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request GetAutonomousPatchRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package linker\n\nimport (\n\t\"errors\"\n\n\tparser \"github.com/moovweb/tritium/parser\"\n\ttp \"github.com/moovweb/tritium/proto\"\n\t. \"github.com/moovweb/tritium/util\"\n)\n\nfunc RunStringWithPackage(src, projectPath, scriptPath, fileName string, pkg *tp.Package, activeLayers []string, ranges ...Range) (*tp.Transform, error) {\n\tobjs := parser.Parse(src, projectPath, scriptPath, fileName, false, activeLayers)\n\treturn runWithObjs(objs, pkg, projectPath, scriptPath, ranges...)\n}\n\n\n\nfunc runWithObjs(objs []*tp.ScriptObject, pkg *tp.Package, projectPath, scriptPath string, ranges ...Range) (*tp.Transform, error) {\n\tctx := NewObjectLinkingContext(pkg, objs, projectPath, scriptPath, ranges...)\n\tctx.Link()\n\tif ctx.HasErrors() {\n\t\tmessage := \"\"\n\t\tfor _, msg := range ctx.Errors {\n\t\t\tmessage = message + \"\\n\" + msg\n\t\t}\n\t\treturn nil, errors.New(message)\n\t}\n\n\treturn ctx.Transform, nil\n}\n\nfunc RunWithPackage(projectPath, scriptPath, fileName string, pkg *tp.Package, activeLayers []string) (*tp.Transform, error) ", "output": "{\n\tobjs := parser.ParseFileSet(projectPath, scriptPath, fileName, false, activeLayers)\n\treturn runWithObjs(objs, pkg, projectPath, scriptPath)\n}"} {"input": "package input_files\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\n\nfunc Issue13() string ", "output": "{\n\tsomeString := \"hello\"\n\tfmt.Println(someString, \"world\")\n\tfmt.Println(someString, \"hello\", \"world\")\n\n\tfmt.Println(someString, \"Hello world %s\", someString)\n\tfmt.Println(someString, \"Hello world %s\", fmt.Printf(\"my_world\"))\n\tfmt.Println(someString, \"Hello world %s\", \"my_world\")\n\n\treturn fmt.Sprint(10, \"world\")\n}"} {"input": "package packages\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/limetext/lime-backend/lib/loaders\"\n\t\"github.com/limetext/lime-backend/lib/log\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\ntype (\n\tPacket struct {\n\t\tpath string\n\t\tmarshalTo json.Unmarshaler\n\t}\n\n\tPackets []*Packet\n)\n\n\nfunc NewPacket(path string, marshal json.Unmarshaler) *Packet {\n\treturn &Packet{path, marshal}\n}\n\nfunc (p *Packet) Name() string {\n\treturn p.path\n}\n\n\n\nfunc (p *Packet) Get() interface{} {\n\te := []byte(`{}`)\n\tif p.group() == \"keymap\" {\n\t\te = []byte(`[]`)\n\t}\n\n\tif _, err := os.Stat(p.path); os.IsNotExist(err) {\n\t\tlog.Finest(\"%s doesn't exist yet\", p.path)\n\t\treturn e\n\t}\n\n\td, err := ioutil.ReadFile(p.path)\n\tif err != nil {\n\t\tlog.Error(\"Couldn't read file: %s\", err)\n\t\treturn e\n\t}\n\treturn d\n}\n\n\nfunc (p *Packet) FileChanged(name string) {\n\tp.Load()\n}\n\nfunc (p *Packet) Load() error {\n\treturn loaders.LoadJSON(p.Get().([]byte), p)\n}\n\nfunc (p *Packet) MarshalTo() json.Unmarshaler {\n\treturn p.marshalTo\n}\n\nfunc (p *Packet) UnmarshalJSON(data []byte) error {\n\treturn p.marshalTo.UnmarshalJSON(data)\n}\n\n\nfunc (p *Packet) group() string {\n\tfor _, key := range types {\n\t\tif strings.Contains(filepath.Ext(p.Name()), key) {\n\t\t\treturn key\n\t\t}\n\t}\n\treturn \"\"\n}\n\n\n\n\nfunc (p Packets) Filter(key string) Packets ", "output": "{\n\tvar pckts Packets\n\tfor _, pckt := range p {\n\t\tif strings.Contains(filepath.Ext(pckt.Name()), key) {\n\t\t\tpckts = append(pckts, pckt)\n\t\t}\n\t}\n\treturn pckts\n}"} {"input": "package lb\n\nimport (\n\t\"database/sql\"\n\t\"testing\"\n\n\t_ \"github.com/lib/pq\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc newDB(t testing.TB) *sql.DB {\n\tdb, err := sql.Open(\"postgres\", \"postgres://localhost/empire?sslmode=disable\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn db\n}\n\nfunc TestDBPortAllocator_Get(t *testing.T) ", "output": "{\n\tdb := newDB(t)\n\ta := &DBPortAllocator{\n\t\tdb: db,\n\t}\n\n\tport, err := a.Get()\n\tassert.NoError(t, err)\n\tassert.NotEqual(t, 0, port)\n\n\terr = a.Put(port)\n\tassert.NoError(t, err)\n}"} {"input": "package mocks\n\nimport (\n\tcli \"github.com/stackanetes/kubernetes-entrypoint/client\"\n)\n\ntype MockEntrypoint struct {\n\tclient cli.ClientInterface\n\tnamespace string\n}\n\nfunc (m MockEntrypoint) Resolve() {\n}\n\n\n\nfunc (m MockEntrypoint) GetNamespace() (namespace string) {\n\treturn m.namespace\n}\n\nfunc NewEntrypointInNamespace(namespace string) MockEntrypoint {\n\treturn MockEntrypoint{\n\t\tclient: NewClient(),\n\t\tnamespace: namespace,\n\t}\n}\n\nfunc NewEntrypoint() MockEntrypoint {\n\treturn NewEntrypointInNamespace(\"test\")\n}\n\nfunc (m MockEntrypoint) Client() (client cli.ClientInterface) ", "output": "{\n\treturn m.client\n}"} {"input": "package consul\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/abronan/valkeyrie/store\"\n\t\"github.com/abronan/valkeyrie/store/consul\"\n\t\"github.com/containous/traefik/old/provider\"\n\t\"github.com/containous/traefik/old/provider/kv\"\n\t\"github.com/containous/traefik/old/types\"\n\t\"github.com/containous/traefik/safe\"\n)\n\nvar _ provider.Provider = (*Provider)(nil)\n\n\ntype Provider struct {\n\tkv.Provider `mapstructure:\",squash\" export:\"true\"`\n}\n\n\nfunc (p *Provider) Init(constraints types.Constraints) error {\n\terr := p.Provider.Init(constraints)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstore, err := p.CreateStore()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to Connect to KV store: %v\", err)\n\t}\n\n\tp.SetKVClient(store)\n\treturn nil\n}\n\n\n\n\n\n\nfunc (p *Provider) CreateStore() (store.Store, error) {\n\tp.SetStoreType(store.CONSUL)\n\tconsul.Register()\n\treturn p.Provider.CreateStore()\n}\n\nfunc (p *Provider) Provide(configurationChan chan<- types.ConfigMessage, pool *safe.Pool) error ", "output": "{\n\treturn p.Provider.Provide(configurationChan, pool)\n}"} {"input": "package db\n\nimport (\n\t\"github.com/globalsign/mgo\"\n\t\"github.com/tsuru/config\"\n\t\"github.com/tsuru/tsuru/db/storage\"\n)\n\nconst (\n\tDefaultDatabaseURL = \"127.0.0.1:27017\"\n\tDefaultDatabaseName = \"gandalf\"\n)\n\ntype Storage struct {\n\t*storage.Storage\n}\n\n\n\n\n\nfunc conn() (*storage.Storage, error) {\n\turl, dbname := DbConfig()\n\treturn storage.Open(url, dbname)\n}\n\nfunc Conn() (*Storage, error) {\n\tvar (\n\t\tstrg Storage\n\t\terr error\n\t)\n\tstrg.Storage, err = conn()\n\treturn &strg, err\n}\n\n\n\n\nfunc (s *Storage) Repository() *storage.Collection {\n\treturn s.Collection(\"repository\")\n}\n\n\nfunc (s *Storage) User() *storage.Collection {\n\treturn s.Collection(\"user\")\n}\n\nfunc (s *Storage) Key() *storage.Collection {\n\tbodyIndex := mgo.Index{Key: []string{\"body\"}, Unique: true}\n\tnameIndex := mgo.Index{Key: []string{\"username\", \"name\"}, Unique: true}\n\tc := s.Collection(\"key\")\n\tc.EnsureIndex(bodyIndex)\n\tc.EnsureIndex(nameIndex)\n\treturn c\n}\n\nfunc DbConfig() (string, string) ", "output": "{\n\turl, _ := config.GetString(\"database:url\")\n\tif url == \"\" {\n\t\turl = DefaultDatabaseURL\n\t}\n\tdbname, _ := config.GetString(\"database:name\")\n\tif dbname == \"\" {\n\t\tdbname = DefaultDatabaseName\n\t}\n\treturn url, dbname\n}"} {"input": "package metrics\n\nimport (\n\t\"sync\"\n\n\tprom \"github.com/prometheus/client_golang/prometheus\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tsandboxGuageName = \"bundlelib_sandbox\"\n)\n\nvar (\n\tonce sync.Once\n\tcollector *Collector\n)\n\n\ntype Collector struct {\n\tSandbox prom.Gauge\n}\n\n\n\n\nfunc recoverMetricPanic() {\n\tif r := recover(); r != nil {\n\t\tlog.Errorf(\"Recovering from metric function - %v\", r)\n\t}\n}\n\n\n\nfunc RegisterCollector() {\n\tonce.Do(func() {\n\t\tcollector = &Collector{\n\t\t\tSandbox: prom.NewGauge(prom.GaugeOpts{\n\t\t\t\tName: sandboxGuageName,\n\t\t\t\tHelp: \"Guage of all sandbox namespaces that are active.\",\n\t\t\t}),\n\t\t}\n\n\t\terr := prom.Register(collector)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"unable to register collector with prometheus: %v\", err)\n\t\t}\n\t})\n}\n\n\nfunc SandboxCreated() {\n\tdefer recoverMetricPanic()\n\tcollector.Sandbox.Inc()\n}\n\n\nfunc SandboxDeleted() {\n\tdefer recoverMetricPanic()\n\tcollector.Sandbox.Dec()\n}\n\n\nfunc (c Collector) Describe(ch chan<- *prom.Desc) {\n\tc.Sandbox.Describe(ch)\n}\n\n\n\n\nfunc (c Collector) Collect(ch chan<- prom.Metric) ", "output": "{\n\tc.Sandbox.Collect(ch)\n}"} {"input": "package native\n\nimport \"github.com/itchio/butler/endpoints/launch\"\n\n\n\nfunc handleUE4Prereqs(params launch.LauncherParams) error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype Page struct {\n\tTitle string\n\tBody []byte\n}\n\nfunc (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}\n\nfunc loadPage(title string) (*Page, error) {\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\treturn &Page{Title: title, Body: body}, err\n}\n\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/view/\"):]\n\tp, _ := loadPage(title)\n\tfmt.Fprintf(w, \"

%s

%s
\", p.Title, p.Body)\n}\n\n\n\n\n\nfunc main() {\n\tdir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tbody := \"This is a test page under: \" + dir\n\tp1 := &Page{Title: \"TestPage\", Body: []byte(body)}\n\tp1.save()\n\tp2, _ := loadPage(\"TestPage\")\n\tfmt.Println(string(p2.Body))\n\n\thttp.HandleFunc(\"/\", defaultHandler)\n\thttp.ListenAndServe(\":8081\", nil)\n}\n\nfunc defaultHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tdump, err := httputil.DumpRequest(r, true)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(string(dump))\n\n\tp, err := loadPage(\"TestPage\") \n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Fprintf(w, \"

%s

%s
\", p.Title, p.Body)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\ntype (\n\tIter func() (int, bool)\n)\n\n\n\nfunc main() {\n\ti := upto(3, 5)\n\tfor v, ok := i(); ok; v, ok = i() {\n\t\tfmt.Println(v)\n\t}\n}\n\nfunc upto(m, n int) Iter ", "output": "{\n\treturn func() (int, bool) {\n\t\tif m < n {\n\t\t\tret := m\n\t\t\tm++\n\t\t\treturn ret, true\n\t\t}\n\t\treturn n, false\n\t}\n}"} {"input": "package datastore\n\nimport \"github.com/swagchat/chat-api/model\"\n\nfunc (p *gcpSQLProvider) createWebhookStore() {\n\tmaster := RdbStore(p.database).master()\n\trdbCreateWebhookStore(p.ctx, master)\n}\n\n\n\nfunc (p *gcpSQLProvider) SelectWebhooks(event model.WebhookEventType, opts ...SelectWebhooksOption) ([]*model.Webhook, error) ", "output": "{\n\treplica := RdbStore(p.database).replica()\n\treturn rdbSelectWebhooks(p.ctx, replica, event, opts...)\n}"} {"input": "package state\n\nimport (\n\t\"net/url\"\n\n\t\"gopkg.in/juju/charm.v3\"\n)\n\n\ntype charmDoc struct {\n\tURL *charm.URL `bson:\"_id\"`\n\tMeta *charm.Meta\n\tConfig *charm.Config\n\tActions *charm.Actions\n\tBundleURL *url.URL\n\tBundleSha256 string\n\tPendingUpload bool\n\tPlaceholder bool\n}\n\n\ntype Charm struct {\n\tst *State\n\tdoc charmDoc\n}\n\nfunc newCharm(st *State, cdoc *charmDoc) (*Charm, error) {\n\treturn &Charm{st: st, doc: *cdoc}, nil\n}\n\nfunc (c *Charm) String() string {\n\treturn c.doc.URL.String()\n}\n\n\nfunc (c *Charm) URL() *charm.URL {\n\tclone := *c.doc.URL\n\treturn &clone\n}\n\n\n\nfunc (c *Charm) Revision() int {\n\treturn c.doc.URL.Revision\n}\n\n\nfunc (c *Charm) Meta() *charm.Meta {\n\treturn c.doc.Meta\n}\n\n\nfunc (c *Charm) Config() *charm.Config {\n\treturn c.doc.Config\n}\n\n\nfunc (c *Charm) Actions() *charm.Actions {\n\treturn c.doc.Actions\n}\n\n\n\nfunc (c *Charm) BundleURL() *url.URL {\n\treturn c.doc.BundleURL\n}\n\n\n\n\n\n\nfunc (c *Charm) IsUploaded() bool {\n\treturn !c.doc.PendingUpload\n}\n\n\n\nfunc (c *Charm) IsPlaceholder() bool {\n\treturn c.doc.Placeholder\n}\n\nfunc (c *Charm) BundleSha256() string ", "output": "{\n\treturn c.doc.BundleSha256\n}"} {"input": "package migrations\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/RichardKnop/example-api/log\"\n\t\"github.com/jinzhu/gorm\"\n)\n\n\ntype MigrationStage struct {\n\tName string\n\tFunction func(db *gorm.DB, name string) error\n}\n\n\nfunc Migrate(db *gorm.DB, migrations []MigrationStage) error {\n\tfor _, m := range migrations {\n\t\tif MigrationExists(db, m.Name) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := m.Function(db, m.Name); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := SaveMigration(db, m.Name); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\n\n\n\nfunc MigrationExists(db *gorm.DB, migrationName string) bool {\n\tmigration := new(Migration)\n\tfound := !db.Where(\"name = ?\", migrationName).First(migration).RecordNotFound()\n\n\tif found {\n\t\tlog.INFO.Printf(\"Skipping %s migration\", migrationName)\n\t} else {\n\t\tlog.INFO.Printf(\"Running %s migration\", migrationName)\n\t}\n\n\treturn found\n}\n\n\nfunc SaveMigration(db *gorm.DB, migrationName string) error {\n\tmigration := new(Migration)\n\tmigration.Name = migrationName\n\n\tif err := db.Create(migration).Error; err != nil {\n\t\tlog.ERROR.Printf(\"Error saving record to migrations table: %s\", err)\n\t\treturn fmt.Errorf(\"Error saving record to migrations table: %s\", err)\n\t}\n\n\treturn nil\n}\n\nfunc MigrateAll(db *gorm.DB, migrationFunctions []func(*gorm.DB) error) ", "output": "{\n\tif err := Bootstrap(db); err != nil {\n\t\tlog.ERROR.Print(err)\n\t}\n\n\tfor _, m := range migrationFunctions {\n\t\tif err := m(db); err != nil {\n\t\t\tlog.ERROR.Print(err)\n\t\t}\n\t}\n}"} {"input": "package test\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/rook/rook/pkg/daemon/ceph/client\"\n)\n\nfunc MonInQuorumResponse() string {\n\tresp := client.MonStatusResponse{Quorum: []int{0}}\n\tresp.MonMap.Mons = []client.MonMapEntry{\n\t\t{\n\t\t\tName: \"a\",\n\t\t\tRank: 0,\n\t\t\tAddress: \"1.2.3.1\",\n\t\t},\n\t}\n\tserialized, _ := json.Marshal(resp)\n\treturn string(serialized)\n}\n\nfunc MonInQuorumResponseFromMons(mons map[string]*client.MonInfo) string {\n\tresp := client.MonStatusResponse{Quorum: []int{}}\n\ti := 0\n\tfor name := range mons {\n\t\tresp.MonMap.Mons = append(resp.MonMap.Mons, client.MonMapEntry{\n\t\t\tName: name,\n\t\t\tRank: i,\n\t\t\tAddress: fmt.Sprintf(\"1.2.3.%d\", i),\n\t\t})\n\t\tresp.Quorum = append(resp.Quorum, i)\n\t\ti++\n\t}\n\tserialized, _ := json.Marshal(resp)\n\treturn string(serialized)\n}\n\n\n\nfunc MonInQuorumResponseMany(count int) string ", "output": "{\n\tresp := client.MonStatusResponse{Quorum: []int{0}}\n\tresp.MonMap.Mons = []client.MonMapEntry{}\n\tfor i := 0; i <= count; i++ {\n\t\tresp.MonMap.Mons = append(resp.MonMap.Mons, client.MonMapEntry{\n\t\t\tName: fmt.Sprintf(\"rook-ceph-mon%d\", i),\n\t\t\tRank: 0,\n\t\t\tAddress: fmt.Sprintf(\"1.2.3.%d\", i),\n\t\t})\n\t}\n\tserialized, _ := json.Marshal(resp)\n\treturn string(serialized)\n}"} {"input": "package mixed\n\nimport (\n\t\"net\"\n\t\"net/url\"\n\n\t\"github.com/nadoo/glider/pkg/log\"\n\t\"github.com/nadoo/glider/proxy\"\n\t\"github.com/nadoo/glider/proxy/http\"\n\t\"github.com/nadoo/glider/proxy/socks5\"\n)\n\n\ntype Mixed struct {\n\tproxy proxy.Proxy\n\taddr string\n\n\thttpServer *http.HTTP\n\tsocks5Server *socks5.Socks5\n}\n\nfunc init() {\n\tproxy.RegisterServer(\"mixed\", NewMixedServer)\n}\n\n\nfunc NewMixed(s string, p proxy.Proxy) (*Mixed, error) {\n\tu, err := url.Parse(s)\n\tif err != nil {\n\t\tlog.F(\"parse err: %s\", err)\n\t\treturn nil, err\n\t}\n\n\tm := &Mixed{\n\t\tproxy: p,\n\t\taddr: u.Host,\n\t}\n\n\tm.httpServer, err = http.NewHTTP(s, nil, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm.socks5Server, err = socks5.NewSocks5(s, nil, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn m, nil\n}\n\n\nfunc NewMixedServer(s string, p proxy.Proxy) (proxy.Server, error) {\n\treturn NewMixed(s, p)\n}\n\n\n\n\n\nfunc (m *Mixed) Serve(c net.Conn) {\n\tconn := proxy.NewConn(c)\n\tif head, err := conn.Peek(1); err == nil {\n\t\tif head[0] == socks5.Version {\n\t\t\tm.socks5Server.Serve(conn)\n\t\t\treturn\n\t\t}\n\t}\n\tm.httpServer.Serve(conn)\n}\n\nfunc (m *Mixed) ListenAndServe() ", "output": "{\n\tgo m.socks5Server.ListenAndServeUDP()\n\n\tl, err := net.Listen(\"tcp\", m.addr)\n\tif err != nil {\n\t\tlog.Fatalf(\"[mixed] failed to listen on %s: %v\", m.addr, err)\n\t\treturn\n\t}\n\n\tlog.F(\"[mixed] http & socks5 server listening TCP on %s\", m.addr)\n\n\tfor {\n\t\tc, err := l.Accept()\n\t\tif err != nil {\n\t\t\tlog.F(\"[mixed] failed to accept: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgo m.Serve(c)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"thezombie.net/libgojira\"\n)\n\nfunc init() {\n\tparser.AddCommand(\"rank\",\n\t\t\"Rank Jira stories\",\n\t\t\"The rank command allows a user to modify story ranks\",\n\t\t&rankCommand)\n\n}\n\n\ntype RankCommand struct {\n}\n\n\n\nvar rankCommand RankCommand\n\nfunc (rc *RankCommand) Execute(args []string) error {\n\tif len(args) < 3 {\n\t\treturn fmt.Errorf(\"Need at least 3 arguments. Usage: %s\", rc.Usage)\n\t}\n\ttarget := args[len(args)-1]\n\tbefore_or_after := strings.ToLower(args[len(args)-2])\n\ttasks := args[:len(args)-2]\n\n\tif before_or_after != \"before\" && before_or_after != \"after\" {\n\t\treturn fmt.Errorf(\"second last parameter needs to be 'before' or 'after'\")\n\t}\n\n\tfmt.Println(\"target\", target)\n\tjc := libgojira.NewJiraClient(options)\n\terr := jc.ChangeRank(tasks, before_or_after, target)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (rc *RankCommand) Usage() string ", "output": "{\n\treturn \"gojira rank TASK-1 TASK-2 TASK-3 TASK-4\"\n}"} {"input": "package outbarriers\n\nimport (\n\t\"log\"\n\t\"time\"\n)\n\ntype User struct {\n\tId int64\n\tEmail string\n\tPassword string \n}\ntype Session struct {\n\tId int64\n\tUserId int64\n\tToken string `sql:\"unique; not null\"`\n\tCreatedAt time.Time\n}\n\nfunc (ctx *Context) AuthUser(email, password string) *User {\n\n\tvar user User\n\tctx.DB.Where(\"email = ? and password = ?\", email, password).First(&user)\n\treturn &user\n}\n\n\n\nfunc (ctx *Context) LoginUser(user *User) string {\n\n\ttoken := RandomString(64)\n\tsession := &Session{UserId: user.Id, Token: token, CreatedAt: time.Now()}\n\tctx.DB.Create(session)\n\treturn token\n}\n\nfunc (ctx *Context) GetSessionByToken(token string) *Session {\n\n\tvar session Session\n\tctx.DB.Where(\"token = ?\", token).First(&session)\n\tif session.Id == 0 {\n\t\treturn nil\n\t}\n\treturn &session\n}\n\nfunc (ctx *Context) CheckAdmin() ", "output": "{\n\n\tvar user User\n\tctx.DB.Where(User{Email: ADMIN_EMAIL, Password: ADMIN_PASSWORD}).FirstOrInit(&user)\n\tif ctx.DB.NewRecord(user) {\n\t\tlog.Printf(\"Admin user not exists, creating...\")\n\t\tctx.DB.Create(&user)\n\t}\n}"} {"input": "package local \n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/tiborvass/docker/errdefs\"\n\t\"github.com/pkg/errors\"\n)\n\ntype optsConfig struct{}\n\n\n\nfunc (r *Root) scopedPath(realPath string) bool {\n\tif strings.HasPrefix(realPath, filepath.Join(r.scope, volumesPathName)) && realPath != filepath.Join(r.scope, volumesPathName) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc setOpts(v *localVolume, opts map[string]string) error {\n\tif len(opts) > 0 {\n\t\treturn errdefs.InvalidParameter(errors.New(\"options are not supported on this platform\"))\n\t}\n\treturn nil\n}\n\nfunc (v *localVolume) needsMount() bool {\n\treturn false\n}\n\nfunc (v *localVolume) mount() error {\n\treturn nil\n}\n\n\n\nfunc (v *localVolume) CreatedAt() (time.Time, error) {\n\tfileInfo, err := os.Stat(v.path)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\tft := fileInfo.Sys().(*syscall.Win32FileAttributeData).CreationTime\n\treturn time.Unix(0, ft.Nanoseconds()), nil\n}\n\nfunc (v *localVolume) postMount() error ", "output": "{\n\treturn nil\n}"} {"input": "package iso20022\n\n\ntype CorporateActionEventType29Choice struct {\n\n\tCode *CorporateActionEventType19Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification30 `xml:\"Prtry\"`\n}\n\n\n\nfunc (c *CorporateActionEventType29Choice) AddProprietary() *GenericIdentification30 {\n\tc.Proprietary = new(GenericIdentification30)\n\treturn c.Proprietary\n}\n\nfunc (c *CorporateActionEventType29Choice) SetCode(value string) ", "output": "{\n\tc.Code = (*CorporateActionEventType19Code)(&value)\n}"} {"input": "package token\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n)\n\n\nfunc PrettyPrintTree(w io.Writer, root Token) {\n\tprettyPrintTreeRek(w, root, 0)\n}\n\n\n\n\nfunc PrettyPrintInternalTree(w io.Writer, root Token) {\n\tprettyPrintInternalTreeRek(w, root, 0)\n}\n\nfunc prettyPrintInternalTreeRek(w io.Writer, tok Token, level int) {\n\t_, _ = fmt.Fprintf(w, \"%s(%p)%#v\\n\", strings.Repeat(\"\\t\", level), tok, tok)\n\n\tswitch t := tok.(type) {\n\tcase ForwardToken:\n\t\tif v := t.InternalGet(); v != nil {\n\t\t\tprettyPrintInternalTreeRek(w, v, level+1)\n\t\t}\n\tcase ListToken:\n\t\tfor i := 0; i < t.InternalLen(); i++ {\n\t\t\tc, _ := t.InternalGet(i)\n\n\t\t\tprettyPrintInternalTreeRek(w, c, level+1)\n\t\t}\n\t}\n}\n\nfunc prettyPrintTreeRek(w io.Writer, tok Token, level int) ", "output": "{\n\t_, _ = fmt.Fprintf(w, \"%s(%p)%#v %d Permutations\\n\", strings.Repeat(\"\\t\", level), tok, tok, tok.Permutations())\n\n\tswitch t := tok.(type) {\n\tcase ForwardToken:\n\t\tif v := t.Get(); v != nil {\n\t\t\tprettyPrintTreeRek(w, v, level+1)\n\t\t}\n\tcase ListToken:\n\t\tfor i := 0; i < t.Len(); i++ {\n\t\t\tc, _ := t.Get(i)\n\n\t\t\tprettyPrintTreeRek(w, c, level+1)\n\t\t}\n\t}\n}"} {"input": "package app\n\nimport (\n\t\"time\"\n\n\t\"github.com/urfave/cli\"\n)\n\ntype innerContext interface {\n\tArgs() cli.Args\n\tBool(name string) bool\n\tBoolT(name string) bool\n\tDuration(name string) time.Duration\n\tFlagNames() (names []string)\n\tFloat64(name string) float64\n\tGeneric(name string) interface{}\n\tGlobalBool(name string) bool\n\tGlobalBoolT(name string) bool\n\tGlobalDuration(name string) time.Duration\n\tGlobalFlagNames() (names []string)\n\tGlobalFloat64(name string) float64\n\tGlobalGeneric(name string) interface{}\n\tGlobalInt(name string) int\n\tGlobalInt64(name string) int64\n\tGlobalInt64Slice(name string) []int64\n\tGlobalIntSlice(name string) []int\n\tGlobalIsSet(name string) bool\n\tGlobalSet(name, value string) error\n\tGlobalString(name string) string\n\tGlobalStringSlice(name string) []string\n\tGlobalUint(name string) uint\n\tGlobalUint64(name string) uint64\n\tInt(name string) int\n\tInt64(name string) int64\n\tInt64Slice(name string) []int64\n\tIntSlice(name string) []int\n\tIsSet(name string) bool\n\tNArg() int\n\tNumFlags() int\n\tParent() *cli.Context\n\tSet(name, value string) error\n\tString(name string) string\n\tStringSlice(name string) []string\n\tUint(name string) uint\n\tUint64(name string) uint64\n\n\tApp() *cli.App\n\tCommand() cli.Command\n}\n\n\ntype CliContextWrapper struct {\n\t*cli.Context\n}\n\n\nfunc (ctx CliContextWrapper) App() *cli.App {\n\treturn ctx.Context.App\n}\n\n\n\n\nfunc (ctx CliContextWrapper) Command() cli.Command ", "output": "{\n\treturn ctx.Context.Command\n}"} {"input": "package disk\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/vslm\"\n)\n\ntype register struct {\n\t*flags.DatastoreFlag\n}\n\nfunc init() {\n\tcli.Register(\"disk.register\", ®ister{})\n}\n\n\n\nfunc (cmd *register) Usage() string {\n\treturn \"PATH [NAME]\"\n}\n\nfunc (cmd *register) Description() string {\n\treturn `Register existing disk on DS.\n\nExamples:\n govc disk.register disks/disk1.vmdk my-disk`\n}\n\nfunc (cmd *register) Run(ctx context.Context, f *flag.FlagSet) error {\n\tds, err := cmd.Datastore()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm := vslm.NewObjectManager(ds.Client())\n\n\tpath := ds.NewURL(f.Arg(0)).String()\n\n\tobj, err := m.RegisterDisk(ctx, path, f.Arg(1))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(obj.Config.Id.Id)\n\n\treturn nil\n}\n\nfunc (cmd *register) Register(ctx context.Context, f *flag.FlagSet) ", "output": "{\n\tcmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)\n\tcmd.DatastoreFlag.Register(ctx, f)\n}"} {"input": "package everdb\n\nimport \"errors\"\nimport \"os\"\n\nconst (\n\tBlockSize = 4096\n)\n\ntype FileBlockDevice struct {\n\tfile *os.File\n\tlen uint32\n}\n\nfunc NewFileBlockDevice(fname string, readonly bool, overwrite bool) (*FileBlockDevice, error) {\n\tif readonly && overwrite {\n\t\treturn nil, errors.New(\"Both overwrite and readonly specified\")\n\t}\n\n\tf := new(FileBlockDevice)\n\n\tflags := 0\n\tswitch {\n\tcase readonly:\n\t\tflags = os.O_RDONLY\n\tcase overwrite:\n\t\tflags = os.O_CREATE | os.O_RDWR | os.O_TRUNC\n\tdefault:\n\t\tflags = os.O_CREATE | os.O_RDWR\n\t}\n\n\tvar err error\n\tf.file, err = os.OpenFile(fname, flags, 0666)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\tfi, err := f.file.Stat()\n\tif nil != err {\n\t\treturn nil, errors.New(\"Failed to stat file\")\n\t} else if fi.Size()%BlockSize != 0 {\n\t\treturn nil, errors.New(\"File is corrupt (not a multiple of BlockSize\")\n\t}\n\n\tf.len = (uint32)(fi.Size() / BlockSize)\n\n\treturn f, nil\n}\n\nfunc (f *FileBlockDevice) Len() uint32 {\n\treturn f.len\n}\n\n\n\nfunc (f *FileBlockDevice) Get(block int) ([]byte, error) {\n\tb := make([]byte, BlockSize)\n\n\tn, err := f.file.ReadAt(b, (int64)(block)*BlockSize)\n\tif nil != err {\n\t\treturn nil, err\n\t} else if n != BlockSize {\n\t\treturn nil, errors.New(\"Failed to read BlockSize bytes\")\n\t}\n\n\treturn b, nil\n}\n\nfunc (f *FileBlockDevice) Resize(len uint32) error ", "output": "{\n\tsz := (int64)(len) * BlockSize\n\n\terr := f.file.Truncate(sz)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\tfi, err := f.file.Stat()\n\tif nil != err {\n\t\treturn errors.New(\"Failed to stat file\")\n\t} else if fi.Size() != sz {\n\t\treturn errors.New(\"Failed to resize file\")\n\t}\n\tf.len = len\n\n\treturn nil\n}"} {"input": "package sw\n\nimport (\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\n\t\"github.com/hyperledger/fabric/core/crypto/bccsp\"\n\t\"github.com/hyperledger/fabric/core/crypto/primitives\"\n)\n\ntype rsaPrivateKey struct {\n\tk *rsa.PrivateKey\n}\n\n\n\nfunc (k *rsaPrivateKey) Bytes() (raw []byte, err error) {\n\treturn\n}\n\n\n\n\n\n\nfunc (k *rsaPrivateKey) Symmetric() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPrivateKey) Private() bool {\n\treturn true\n}\n\n\n\nfunc (k *rsaPrivateKey) PublicKey() (bccsp.Key, error) {\n\treturn &rsaPublicKey{&k.k.PublicKey}, nil\n}\n\ntype rsaPublicKey struct {\n\tk *rsa.PublicKey\n}\n\n\n\nfunc (k *rsaPublicKey) Bytes() (raw []byte, err error) {\n\traw, err = x509.MarshalPKIXPublicKey(k.k)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed marshalling key [%s]\", err)\n\t}\n\treturn\n}\n\n\nfunc (k *rsaPublicKey) SKI() (ski []byte) {\n\traw, _ := primitives.PublicKeyToPEM(k.k, nil)\n\n\treturn primitives.Hash(raw)\n}\n\n\n\nfunc (k *rsaPublicKey) Symmetric() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) Private() bool {\n\treturn false\n}\n\n\n\nfunc (k *rsaPublicKey) PublicKey() (bccsp.Key, error) {\n\treturn k, nil\n}\n\nfunc (k *rsaPrivateKey) SKI() (ski []byte) ", "output": "{\n\traw := x509.MarshalPKCS1PrivateKey(k.k)\n\n\treturn primitives.Hash(raw)\n}"} {"input": "package iso20022\n\n\ntype FundSettlementParameters3 struct {\n\n\tSettlementDate *ISODate `xml:\"SttlmDt,omitempty\"`\n\n\tSettlementPlace *PartyIdentification2Choice `xml:\"SttlmPlc\"`\n\n\tSafekeepingPlace *PartyIdentification2Choice `xml:\"SfkpgPlc,omitempty\"`\n\n\tSecuritiesSettlementSystemIdentification *Max35Text `xml:\"SctiesSttlmSysId,omitempty\"`\n\n\tReceivingSideDetails *ReceivingPartiesAndAccount3 `xml:\"RcvgSdDtls,omitempty\"`\n\n\tDeliveringSideDetails *DeliveringPartiesAndAccount3 `xml:\"DlvrgSdDtls\"`\n}\n\n\n\nfunc (f *FundSettlementParameters3) AddSettlementPlace() *PartyIdentification2Choice {\n\tf.SettlementPlace = new(PartyIdentification2Choice)\n\treturn f.SettlementPlace\n}\n\nfunc (f *FundSettlementParameters3) AddSafekeepingPlace() *PartyIdentification2Choice {\n\tf.SafekeepingPlace = new(PartyIdentification2Choice)\n\treturn f.SafekeepingPlace\n}\n\nfunc (f *FundSettlementParameters3) SetSecuritiesSettlementSystemIdentification(value string) {\n\tf.SecuritiesSettlementSystemIdentification = (*Max35Text)(&value)\n}\n\nfunc (f *FundSettlementParameters3) AddReceivingSideDetails() *ReceivingPartiesAndAccount3 {\n\tf.ReceivingSideDetails = new(ReceivingPartiesAndAccount3)\n\treturn f.ReceivingSideDetails\n}\n\nfunc (f *FundSettlementParameters3) AddDeliveringSideDetails() *DeliveringPartiesAndAccount3 {\n\tf.DeliveringSideDetails = new(DeliveringPartiesAndAccount3)\n\treturn f.DeliveringSideDetails\n}\n\nfunc (f *FundSettlementParameters3) SetSettlementDate(value string) ", "output": "{\n\tf.SettlementDate = (*ISODate)(&value)\n}"} {"input": "package labassistant\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc make_ob() *Observation {\n\treturn &Observation{}\n}\n\n\n\nfunc panic_func(i int) int {\n\tpanic(\"panic\")\n}\n\nfunc bad_func(i int) int {\n\treturn i + 1\n}\n\nfunc TestObservationRunIsOK(t *testing.T) {\n\ta := assert.New(t)\n\tout := make_ob().run(good_func, 1)\n\ta.Equal([]interface{}{1}, out)\n\n\tout = make_ob().run(good_func, 0)\n\ta.NotEqual([]interface{}{1}, out)\n\n\ta.Panics(func() {\n\t\tmake_ob().run(good_func)\n\t})\n\n\ta.Panics(func() {\n\t\tmake_ob().run(good_func, 1, 1)\n\t})\n\n\ta.Panics(func() {\n\t\tmake_ob().run(good_func, \"string\")\n\t})\n}\n\nfunc TestObservationRunSetsValues(t *testing.T) {\n\ta := assert.New(t)\n\tgood := make_ob()\n\tgood.run(good_func, 1)\n\ta.Equal(\"github.com/lmas/labassistant.good_func\", good.Name)\n\ta.Empty(good.Panic)\n\ta.Equal([]interface{}{1}, good.Outputs)\n\ta.NotEmpty(good.Start)\n\ta.NotZero(good.Duration)\n\n\tbad := make_ob()\n\tbad.can_panic = true\n\ta.NotPanics(func() {\n\t\tbad.run(panic_func, 1)\n\t})\n\ta.Equal(\"panic\", bad.Panic)\n\ta.Empty(bad.Outputs)\n\ta.NotEmpty(bad.Start)\n\ta.Zero(bad.Duration)\n}\n\nfunc good_func(i int) int ", "output": "{\n\treturn i\n}"} {"input": "package float64_tree\n\nimport (\n\t\"math/bits\"\n\n\t\"github.com/kentik/patricia\"\n)\n\nconst _leftmost32Bit = uint32(1 << 31)\n\ntype treeNodeV4 struct {\n\tLeft uint \n\tRight uint \n\tprefix uint32\n\tprefixLength uint\n\tTagCount int\n}\n\n\n\n\n\nfunc (n *treeNodeV4) ShiftPrefix(shiftCount uint) {\n\tn.prefix <<= shiftCount\n\tn.prefixLength -= shiftCount\n}\n\n\nfunc (n *treeNodeV4) IsLeftBitSet() bool {\n\treturn n.prefix >= _leftmost32Bit\n}\n\n\nfunc (n *treeNodeV4) MergeFromNodes(left *treeNodeV4, right *treeNodeV4) {\n\tn.prefix, n.prefixLength = patricia.MergePrefixes32(left.prefix, left.prefixLength, right.prefix, right.prefixLength)\n}\n\nfunc (n *treeNodeV4) MatchCount(address patricia.IPv4Address) uint ", "output": "{\n\tvar length uint\n\tif address.Length > n.prefixLength {\n\t\tlength = n.prefixLength\n\t} else {\n\t\tlength = address.Length\n\t}\n\n\tmatches := uint(bits.LeadingZeros32(n.prefix ^ address.Address))\n\tif matches > length {\n\t\treturn length\n\t}\n\treturn matches\n}"} {"input": "package repos\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\tdb \"github.com/antoineaugusti/feature-flags/db\"\n\tm \"github.com/antoineaugusti/feature-flags/models\"\n\t\"github.com/boltdb/bolt\"\n)\n\n\nfunc PutFeature(tx *bolt.Tx, feature m.FeatureFlag) error {\n\tfeatures := tx.Bucket([]byte(db.GetBucketName()))\n\n\tbytes, err := json.Marshal(feature)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = features.Put([]byte(feature.Key), bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc GetFeatures(tx *bolt.Tx) (m.FeatureFlags, error) {\n\tfeaturesBucket := tx.Bucket([]byte(db.GetBucketName()))\n\tcursor := featuresBucket.Cursor()\n\n\tfeatures := make(m.FeatureFlags, 0)\n\n\tfor key, value := cursor.First(); key != nil; key, value = cursor.Next() {\n\t\tfeature := m.FeatureFlag{}\n\n\t\terr := json.Unmarshal(value, &feature)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfeatures = append(features, feature)\n\t}\n\n\treturn features, nil\n}\n\n\nfunc FeatureExists(tx *bolt.Tx, featureKey string) bool {\n\tfeatures := tx.Bucket([]byte(db.GetBucketName()))\n\tbytes := features.Get([]byte(featureKey))\n\treturn bytes != nil\n}\n\n\n\n\n\nfunc RemoveFeature(tx *bolt.Tx, featureKey string) error {\n\tfeatures := tx.Bucket([]byte(db.GetBucketName()))\n\treturn features.Delete([]byte(featureKey))\n}\n\nfunc GetFeature(tx *bolt.Tx, featureKey string) (m.FeatureFlag, error) ", "output": "{\n\tfeatures := tx.Bucket([]byte(db.GetBucketName()))\n\n\tbytes := features.Get([]byte(featureKey))\n\tif bytes == nil {\n\t\treturn m.FeatureFlag{}, fmt.Errorf(\"Unable to find feature\")\n\t}\n\n\tfeature := m.FeatureFlag{}\n\n\terr := json.Unmarshal(bytes, &feature)\n\tif err != nil {\n\t\treturn m.FeatureFlag{}, err\n\t}\n\n\treturn feature, nil\n}"} {"input": "package main\n\nimport \"fmt\"\n\nconst (\n\tRLIMIT_CPU = iota \n\tRLIMIT_FSIZE \n\tRLIMIT_DATA \n\tRLIMIT_STACK \n\tRLIMIT_CORE \n\tRLIMIT_RSS \n\tRLIMIT_NPROC \n\tRLIMIT_NOFILE \n\tRLIMIT_MEMLOCK \n\tRLIMIT_AS \n\tRLIMIT_LOCKS \n\tRLIMIT_SIGPENDING \n\tRLIMIT_MSGQUEUE \n\tRLIMIT_NICE \n\tRLIMIT_RTPRIO \n\tRLIMIT_RTTIME \n)\n\nvar rlimitMap = map[string]int{\n\t\"RLIMIT_CPU\": RLIMIT_CPU,\n\t\"RLIMIT_FSIZE\": RLIMIT_FSIZE,\n\t\"RLIMIT_DATA\": RLIMIT_DATA,\n\t\"RLIMIT_STACK\": RLIMIT_STACK,\n\t\"RLIMIT_CORE\": RLIMIT_CORE,\n\t\"RLIMIT_RSS\": RLIMIT_RSS,\n\t\"RLIMIT_NPROC\": RLIMIT_NPROC,\n\t\"RLIMIT_NOFILE\": RLIMIT_NOFILE,\n\t\"RLIMIT_MEMLOCK\": RLIMIT_MEMLOCK,\n\t\"RLIMIT_AS\": RLIMIT_AS,\n\t\"RLIMIT_LOCKS\": RLIMIT_LOCKS,\n\t\"RLIMIT_SGPENDING\": RLIMIT_SIGPENDING,\n\t\"RLIMIT_MSGQUEUE\": RLIMIT_MSGQUEUE,\n\t\"RLIMIT_NICE\": RLIMIT_NICE,\n\t\"RLIMIT_RTPRIO\": RLIMIT_RTPRIO,\n\t\"RLIMIT_RTTIME\": RLIMIT_RTTIME,\n}\n\n\n\nfunc strToRlimit(key string) (int, error) ", "output": "{\n\trl, ok := rlimitMap[key]\n\tif !ok {\n\t\treturn 0, fmt.Errorf(\"Wrong rlimit value: %s\", key)\n\t}\n\treturn rl, nil\n}"} {"input": "package timeconv\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestTimestamp(t *testing.T) {\n\tnow := time.Now()\n\tts := Timestamp(now)\n\n\tif now.Unix() != ts.Seconds {\n\t\tt.Errorf(\"Unexpected time drift: %d to %d\", now.Second(), ts.Seconds)\n\t}\n\n\tif now.Nanosecond() != int(ts.Nanos) {\n\t\tt.Errorf(\"Unexpected nano drift: %d to %d\", now.Nanosecond(), ts.Nanos)\n\t}\n}\n\nfunc TestTime(t *testing.T) {\n\tnowts := Now()\n\tnow := Time(nowts)\n\n\tif now.Unix() != nowts.Seconds {\n\t\tt.Errorf(\"Unexpected time drift %d\", now.Unix())\n\t}\n}\n\nfunc TestFormat(t *testing.T) {\n\tnow := time.Now()\n\tnowts := Timestamp(now)\n\n\tif now.Format(time.ANSIC) != Format(nowts, time.ANSIC) {\n\t\tt.Error(\"Format mismatch\")\n\t}\n}\n\nfunc TestNow(t *testing.T) ", "output": "{\n\tnow := time.Now()\n\tts := Now()\n\tvar drift int64 = 5\n\tif ts.Seconds < int64(now.Second())-drift {\n\t\tt.Errorf(\"Unexpected time drift: %d\", ts.Seconds)\n\t}\n}"} {"input": "package billing\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/billing/mgmt/2017-04-24-preview/billing\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype ManagementClient = original.ManagementClient\ntype InvoicesClient = original.InvoicesClient\ntype DownloadURL = original.DownloadURL\ntype ErrorDetails = original.ErrorDetails\ntype ErrorResponse = original.ErrorResponse\ntype Invoice = original.Invoice\ntype InvoiceProperties = original.InvoiceProperties\ntype InvoicesListResult = original.InvoicesListResult\ntype Operation = original.Operation\ntype OperationDisplay = original.OperationDisplay\ntype OperationListResult = original.OperationListResult\ntype Period = original.Period\ntype PeriodProperties = original.PeriodProperties\ntype PeriodsListResult = original.PeriodsListResult\ntype Resource = original.Resource\ntype OperationsClient = original.OperationsClient\ntype PeriodsClient = original.PeriodsClient\n\nfunc NewOperationsClient(subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClient(subscriptionID)\n}\nfunc NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewPeriodsClient(subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClient(subscriptionID)\n}\nfunc NewPeriodsClientWithBaseURI(baseURI string, subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewInvoicesClient(subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClient(subscriptionID)\n}\nfunc NewInvoicesClientWithBaseURI(baseURI string, subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClientWithBaseURI(baseURI, subscriptionID)\n}\n\nfunc New(subscriptionID string) ManagementClient ", "output": "{\n\treturn original.New(subscriptionID)\n}"} {"input": "package s3util\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n)\n\ntype respError struct {\n\tr *http.Response\n\tb bytes.Buffer\n}\n\nfunc newRespError(r *http.Response) *respError {\n\te := new(respError)\n\te.r = r\n\tio.Copy(&e.b, r.Body)\n\tr.Body.Close()\n\treturn e\n}\n\n\n\nfunc (e *respError) Error() string ", "output": "{\n\treturn fmt.Sprintf(\n\t\t\"unwanted http status %d: %q\",\n\t\te.r.StatusCode,\n\t\te.b.String(),\n\t)\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/labstack/echo\"\n)\n\n\ntype Error struct {\n\tMessage string `json:\"message\"`\n}\n\n\nfunc OK(c echo.Context, payload interface{}) error {\n\treturn c.JSON(http.StatusOK, payload)\n}\n\n\nfunc Created(c echo.Context, payload interface{}) error {\n\treturn c.JSON(http.StatusCreated, payload)\n}\n\n\n\n\n\nfunc BadRequest(c echo.Context, msg string) error {\n\treturn c.JSON(http.StatusBadRequest, Error{msg})\n}\n\n\nfunc NotFound(c echo.Context) error {\n\treturn c.JSON(http.StatusNotFound, Error{\"Resource not found\"})\n}\n\n\nfunc Conflict(c echo.Context, msg string) error {\n\treturn c.JSON(http.StatusConflict, Error{msg})\n}\n\n\nfunc Invalid(c echo.Context, msg string) error {\n\treturn c.JSON(422, Error{msg})\n}\n\n\n\nfunc InternalServerError(c echo.Context, err error) error {\n\tlog.WithFields(log.Fields{\n\t\t\"request_id\": RequestID(c),\n\t}).Error(err)\n\n\treturn c.JSON(http.StatusInternalServerError, Error{\"Oops! Something went wrong\"})\n}\n\nfunc NoContent(c echo.Context) error ", "output": "{\n\treturn c.NoContent(http.StatusNoContent)\n}"} {"input": "package stack\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/docker/docker/cli/command/bundlefile\"\n\t\"github.com/spf13/pflag\"\n)\n\nfunc addComposefileFlag(opt *string, flags *pflag.FlagSet) {\n\tflags.StringVarP(opt, \"compose-file\", \"c\", \"\", \"Path to a Compose file\")\n}\n\n\n\nfunc addRegistryAuthFlag(opt *bool, flags *pflag.FlagSet) {\n\tflags.BoolVar(opt, \"with-registry-auth\", false, \"Send registry authentication details to Swarm agents\")\n}\n\nfunc loadBundlefile(stderr io.Writer, namespace string, path string) (*bundlefile.Bundlefile, error) {\n\tdefaultPath := fmt.Sprintf(\"%s.dab\", namespace)\n\n\tif path == \"\" {\n\t\tpath = defaultPath\n\t}\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"Bundle %s not found. Specify the path with --file\",\n\t\t\tpath)\n\t}\n\n\tfmt.Fprintf(stderr, \"Loading bundle from %s\\n\", path)\n\treader, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer reader.Close()\n\n\tbundle, err := bundlefile.LoadFile(reader)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error reading %s: %v\\n\", path, err)\n\t}\n\treturn bundle, err\n}\n\nfunc addBundlefileFlag(opt *string, flags *pflag.FlagSet) ", "output": "{\n\tflags.StringVar(opt, \"bundle-file\", \"\", \"Path to a Distributed Application Bundle file\")\n\tflags.SetAnnotation(\"bundle-file\", \"experimental\", nil)\n}"} {"input": "package drone\n\nimport (\n\t\"fmt\"\n)\n\ntype UserService struct {\n\t*Client\n}\n\n\nfunc (s *UserService) Get(remote, login string) (*User, error) {\n\tvar path = fmt.Sprintf(\"/api/users/%s/%s\", remote, login)\n\tvar user = User{}\n\tvar err = s.run(\"GET\", path, nil, &user)\n\treturn &user, err\n}\n\n\nfunc (s *UserService) GetCurrent() (*User, error) {\n\tvar user = User{}\n\tvar err = s.run(\"GET\", \"/api/user\", nil, &user)\n\treturn &user, err\n}\n\n\n\n\n\nfunc (s *UserService) Delete(remote, login string) error {\n\tvar path = fmt.Sprintf(\"/api/users/%s/%s\", remote, login)\n\treturn s.run(\"DELETE\", path, nil, nil)\n}\n\n\nfunc (s *UserService) List() ([]*User, error) {\n\tvar users []*User\n\tvar err = s.run(\"GET\", \"/api/users\", nil, &users)\n\treturn users, err\n}\n\nfunc (s *UserService) Create(remote, login string) (*User, error) ", "output": "{\n\tvar path = fmt.Sprintf(\"/api/users/%s/%s\", remote, login)\n\tvar user = User{}\n\tvar err = s.run(\"POST\", path, nil, &user)\n\treturn &user, err\n}"} {"input": "package ray\n\nimport (\n\t\"github.com/v2ray/v2ray-core/common/alloc\"\n)\n\nconst (\n\tbufferSize = 128\n)\n\n\nfunc NewRay() Ray {\n\treturn &directRay{\n\t\tInput: make(chan *alloc.Buffer, bufferSize),\n\t\tOutput: make(chan *alloc.Buffer, bufferSize),\n\t}\n}\n\ntype directRay struct {\n\tInput chan *alloc.Buffer\n\tOutput chan *alloc.Buffer\n}\n\n\n\nfunc (this *directRay) OutboundOutput() chan<- *alloc.Buffer {\n\treturn this.Output\n}\n\nfunc (this *directRay) InboundInput() chan<- *alloc.Buffer {\n\treturn this.Input\n}\n\nfunc (this *directRay) InboundOutput() <-chan *alloc.Buffer {\n\treturn this.Output\n}\n\nfunc (this *directRay) OutboundInput() <-chan *alloc.Buffer ", "output": "{\n\treturn this.Input\n}"} {"input": "package capabilities\n\nimport (\n\t\"testing\"\n\n\tcb \"github.com/hyperledger/fabric/protos/common\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestChannelV11(t *testing.T) {\n\top := NewChannelProvider(map[string]*cb.Capability{\n\t\tChannelV1_1: &cb.Capability{},\n\t})\n\tassert.NoError(t, op.Supported())\n\tassert.True(t, op.MSPVersion() == MSPv1_1)\n}\n\nfunc TestChannelV10(t *testing.T) ", "output": "{\n\top := NewChannelProvider(map[string]*cb.Capability{})\n\tassert.NoError(t, op.Supported())\n\tassert.True(t, op.MSPVersion() == MSPv1_0)\n}"} {"input": "package tempconv\n\nimport \"testing\"\n\nfunc TestCToF(t *testing.T) {\n\tvar c Celsius = 37\n\tf := CToF(c)\n\tif f != Fahrenheit(98.6) {\n\t\tt.Errorf(`CToF(%g) == %g failed`, c, f)\n\t}\n}\n\nfunc TestFToC(t *testing.T) {\n\tvar f Fahrenheit = 95\n\tc := FToC(f)\n\tif c != Celsius(35) {\n\t\tt.Errorf(`FToC(%g) == %g failed`, f, c)\n\t}\n}\n\n\n\nfunc TestKToC(t *testing.T) {\n\tvar k Kelvin = 1000\n\tc := KToC(k)\n\tif c != Celsius(726.85) {\n\t\tt.Errorf(`KToC(%g) == %g failed`, k, c)\n\t}\n}\n\nfunc TestCToK(t *testing.T) ", "output": "{\n\tvar c Celsius = 37\n\tk := CToK(c)\n\tif k != Kelvin(310.15) {\n\t\tt.Errorf(`CToK(%g) == %g failed`, c, k)\n\t}\n}"} {"input": "package lib\n\nimport (\n\t\"github.com/hashicorp/serf/serf\"\n)\n\n\n\n\n\nfunc SerfDefaultConfig() *serf.Config ", "output": "{\n\tbase := serf.DefaultConfig()\n\n\tbase.QueueDepthWarning = 1000000\n\n\tbase.MinQueueDepth = 4096\n\n\treturn base\n}"} {"input": "package testutil\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\ntype Context struct {\n\tName string `yaml:\"name,omitempty\"`\n\tContext struct {\n\t\tNamespace string `yaml:\"namespace,omitempty\"`\n\t} `yaml:\"context,omitempty\"`\n}\n\nfunc Ctx(name string) *Context { return &Context{Name: name} }\nfunc (c *Context) Ns(ns string) *Context { c.Context.Namespace = ns; return c }\n\ntype Kubeconfig map[string]interface{}\n\n\n\nfunc (k *Kubeconfig) Set(key string, v interface{}) *Kubeconfig { (*k)[key] = v; return k }\nfunc (k *Kubeconfig) WithCurrentCtx(s string) *Kubeconfig { (*k)[\"current-context\"] = s; return k }\nfunc (k *Kubeconfig) WithCtxs(c ...*Context) *Kubeconfig { (*k)[\"contexts\"] = c; return k }\n\nfunc (k *Kubeconfig) ToYAML(t *testing.T) string {\n\tt.Helper()\n\tvar v strings.Builder\n\tif err := yaml.NewEncoder(&v).Encode(*k); err != nil {\n\t\tt.Fatalf(\"failed to encode mock kubeconfig: %v\", err)\n\t}\n\treturn v.String()\n}\n\nfunc KC() *Kubeconfig ", "output": "{\n\treturn &Kubeconfig{\n\t\t\"apiVersion\": \"v1\",\n\t\t\"kind\": \"Config\"}\n}"} {"input": "package namespaces\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\n\t\"github.com/dotcloud/docker/pkg/term\"\n)\n\ntype TtyTerminal struct {\n\tstdin io.Reader\n\tstdout, stderr io.Writer\n\tmaster *os.File\n\tstate *term.State\n}\n\nfunc (t *TtyTerminal) Resize(h, w int) error {\n\treturn term.SetWinsize(t.master.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)})\n}\n\nfunc (t *TtyTerminal) SetMaster(master *os.File) {\n\tt.master = master\n}\n\nfunc (t *TtyTerminal) Attach(command *exec.Cmd) error {\n\tgo io.Copy(t.stdout, t.master)\n\tgo io.Copy(t.master, t.stdin)\n\n\tstate, err := t.setupWindow(t.master, os.Stdin)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.state = state\n\treturn err\n}\n\n\n\nfunc (t *TtyTerminal) setupWindow(master, parent *os.File) (*term.State, error) {\n\tws, err := term.GetWinsize(parent.Fd())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := term.SetWinsize(master.Fd(), ws); err != nil {\n\t\treturn nil, err\n\t}\n\treturn term.SetRawTerminal(parent.Fd())\n}\n\n\n\nfunc (t *TtyTerminal) Close() error ", "output": "{\n\tterm.RestoreTerminal(os.Stdin.Fd(), t.state)\n\treturn t.master.Close()\n}"} {"input": "package stripe\n\nimport (\n\t\"github.com/bmizerany/assert\"\n\t\"net/url\"\n\t\"testing\"\n)\n\nfunc TestTokenCreate(t *testing.T) {\n\tsetup()\n\tdefer teardown()\n\thandleWithJSON(\"/tokens\", \"tokens/token.json\")\n\tparams := TokenParams{}\n\ttoken, _ := client.Tokens.Create(¶ms)\n\tassert.Equal(t, token.Id, \"tok_123456789\")\n}\n\n\n\nfunc TestParseTokenParams(t *testing.T) {\n\tparams := TokenParams{\n\t\tCustomer: \"cus_123456789\",\n\t\tCardParams: &CardParams{\n\t\t\tNumber: \"4242424242424242\",\n\t\t},\n\t\tBankAccountParams: &BankAccountParams{\n\t\t\tAccountNumber: \"123456789\",\n\t\t},\n\t}\n\tvalues := url.Values{}\n\n\tparseTokenParams(¶ms, &values)\n\tassert.Equal(t, values.Get(\"customer\"), params.Customer)\n\tassert.Equal(t, values.Get(\"card[number]\"), params.CardParams.Number)\n\tassert.NotEqual(t, values.Get(\"bank_account[account_number]\"), params.BankAccountParams.AccountNumber)\n\n\tparams.CardParams = nil\n\tvalues = url.Values{}\n\tparseTokenParams(¶ms, &values)\n\tassert.Equal(t, values.Get(\"bank_account[account_number]\"), params.BankAccountParams.AccountNumber)\n}\n\nfunc TestTokensRetrieve(t *testing.T) ", "output": "{\n\tsetup()\n\tdefer teardown()\n\thandleWithJSON(\"/tokens/tok_123456789\", \"tokens/token.json\")\n\ttoken, _ := client.Tokens.Retrieve(\"tok_123456789\")\n\tassert.Equal(t, token.Id, \"tok_123456789\")\n}"} {"input": "package messagestore\n\nimport (\n\t\"github.com/agl/ed25519\"\n\tlog \"github.com/repbin/repbin/deferconsole\"\n\t\"github.com/repbin/repbin/utils\"\n\t\"github.com/repbin/repbin/utils/keyproof\"\n\t\"github.com/repbin/repbin/utils/repproto/structs\"\n)\n\n\nfunc (store Store) TouchPeer(pubkey *[ed25519.PublicKeySize]byte) {\n\terr := store.db.TouchPeer(pubkey)\n\tif err != nil {\n\t\tlog.Errorf(\"TouchPeer: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t}\n}\n\n\nfunc (store Store) UpdatePeerFetchStat(pubkey *[ed25519.PublicKeySize]byte, lastFetch, lastPos, lastErrors uint64) {\n\terr := store.db.UpdatePeerStats(pubkey, lastFetch, lastPos, lastErrors)\n\tif err != nil {\n\t\tlog.Errorf(\"UpdatePeerStats: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t}\n}\n\n\nfunc (store Store) UpdatePeerNotification(pubkey *[ed25519.PublicKeySize]byte, hasError bool) {\n\terr := store.db.UpdatePeerNotification(pubkey, hasError)\n\tif err != nil {\n\t\tlog.Errorf(\"UpdatePeerNotification: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t}\n}\n\n\n\n\n\nfunc (store Store) UpdatePeerAuthToken(senderPubKey *[ed25519.PublicKeySize]byte, signedToken *[keyproof.ProofTokenSignedSize]byte) {\n\terr := store.db.UpdatePeerToken(senderPubKey, signedToken)\n\tif err != nil {\n\t\tlog.Errorf(\"UpdatePeerAuthToken: %s, %s\\n\", err, utils.B58encode(senderPubKey[:]))\n\t}\n}\n\nfunc (store Store) GetPeerStat(pubkey *[ed25519.PublicKeySize]byte) *structs.PeerStruct ", "output": "{\n\tst, err := store.db.SelectPeer(pubkey)\n\tif err != nil {\n\t\tlog.Errorf(\"GetPeerStat: %s, %s\\n\", err, utils.B58encode(pubkey[:]))\n\t\treturn nil\n\t}\n\treturn st\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"v2.staffjoy.com/auth\"\n)\n\n\n\nfunc logoutHandler(res http.ResponseWriter, req *http.Request) ", "output": "{\n\tauth.Logout(res)\n\thttp.Redirect(res, req, \"/\", http.StatusFound)\n}"} {"input": "package iradix\n\n\n\n\ntype rawIterator struct {\n\tnode *Node\n\n\tstack []rawStackEntry\n\n\tpos *Node\n\n\tpath string\n}\n\n\n\ntype rawStackEntry struct {\n\tpath string\n\tedges edges\n}\n\n\nfunc (i *rawIterator) Front() *Node {\n\treturn i.pos\n}\n\n\n\n\n\n\nfunc (i *rawIterator) Next() {\n\tif i.stack == nil && i.node != nil {\n\t\ti.stack = []rawStackEntry{\n\t\t\t{\n\t\t\t\tedges: edges{\n\t\t\t\t\tedge{node: i.node},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\tfor len(i.stack) > 0 {\n\t\tn := len(i.stack)\n\t\tlast := i.stack[n-1]\n\t\telem := last.edges[0].node\n\n\t\tif len(last.edges) > 1 {\n\t\t\ti.stack[n-1].edges = last.edges[1:]\n\t\t} else {\n\t\t\ti.stack = i.stack[:n-1]\n\t\t}\n\n\t\tif len(elem.edges) > 0 {\n\t\t\tpath := last.path + string(elem.prefix)\n\t\t\ti.stack = append(i.stack, rawStackEntry{path, elem.edges})\n\t\t}\n\n\t\ti.pos = elem\n\t\ti.path = last.path + string(elem.prefix)\n\t\treturn\n\t}\n\n\ti.pos = nil\n\ti.path = \"\"\n}\n\nfunc (i *rawIterator) Path() string ", "output": "{\n\treturn i.path\n}"} {"input": "package gitea\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\n\ntype PublicKey struct {\n\tID int64 `json:\"id\"`\n\tKey string `json:\"key\"`\n\tURL string `json:\"url,omitempty\"`\n\tTitle string `json:\"title,omitempty\"`\n\tCreated time.Time `json:\"created_at,omitempty\"`\n}\n\n\nfunc (c *Client) ListPublicKeys(user string) ([]*PublicKey, error) {\n\tkeys := make([]*PublicKey, 0, 10)\n\treturn keys, c.getParsedResponse(\"GET\", fmt.Sprintf(\"/users/%s/keys\", user), nil, nil, &keys)\n}\n\n\nfunc (c *Client) ListMyPublicKeys() ([]*PublicKey, error) {\n\tkeys := make([]*PublicKey, 0, 10)\n\treturn keys, c.getParsedResponse(\"GET\", \"/user/keys\", nil, nil, &keys)\n}\n\n\nfunc (c *Client) GetPublicKey(keyID int64) (*PublicKey, error) {\n\tkey := new(PublicKey)\n\treturn key, c.getParsedResponse(\"GET\", fmt.Sprintf(\"/user/keys/%d\", keyID), nil, nil, &key)\n}\n\n\n\n\n\nfunc (c *Client) DeletePublicKey(keyID int64) error {\n\t_, err := c.getResponse(\"DELETE\", fmt.Sprintf(\"/user/keys/%d\", keyID), nil, nil)\n\treturn err\n}\n\nfunc (c *Client) CreatePublicKey(opt CreateKeyOption) (*PublicKey, error) ", "output": "{\n\tbody, err := json.Marshal(&opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkey := new(PublicKey)\n\treturn key, c.getParsedResponse(\"POST\", \"/user/keys\", jsonHeader, bytes.NewReader(body), key)\n}"} {"input": "package api\n\nimport \"testing\"\n\nfunc assertQueryMeta(t *testing.T, qm *QueryMeta) {\n\tif qm.LastIndex == 0 {\n\t\tt.Fatalf(\"bad index: %d\", qm.LastIndex)\n\t}\n\tif !qm.KnownLeader {\n\t\tt.Fatalf(\"expected known leader, got none\")\n\t}\n}\n\nfunc assertWriteMeta(t *testing.T, wm *WriteMeta) {\n\tif wm.LastIndex == 0 {\n\t\tt.Fatalf(\"bad index: %d\", wm.LastIndex)\n\t}\n}\n\nfunc testJob() *Job {\n\ttask := NewTask(\"task1\", \"exec\").\n\t\tSetConfig(\"command\", \"/bin/sleep\").\n\t\tRequire(&Resources{\n\t\t\tCPU: 100,\n\t\t\tMemoryMB: 256,\n\t\t\tIOPS: 10,\n\t\t}).\n\t\tSetLogConfig(&LogConfig{\n\t\t\tMaxFiles: 1,\n\t\t\tMaxFileSizeMB: 2,\n\t\t})\n\n\tgroup := NewTaskGroup(\"group1\", 1).\n\t\tAddTask(task).\n\t\tRequireDisk(&EphemeralDisk{\n\t\t\tSizeMB: 25,\n\t\t})\n\n\tjob := NewBatchJob(\"job1\", \"redis\", \"region1\", 1).\n\t\tAddDatacenter(\"dc1\").\n\t\tAddTaskGroup(group)\n\n\treturn job\n}\n\n\n\nfunc testPeriodicJob() *Job ", "output": "{\n\tjob := testJob().AddPeriodicConfig(&PeriodicConfig{\n\t\tEnabled: true,\n\t\tSpec: \"*/30 * * * *\",\n\t\tSpecType: \"cron\",\n\t})\n\treturn job\n}"} {"input": "package cs\n\nimport (\n\t\"github.com/scionproto/scion/go/cs/beacon\"\n\t\"github.com/scionproto/scion/go/cs/config\"\n\t\"github.com/scionproto/scion/go/lib/serrors\"\n)\n\n\n\n\n\nfunc LoadNonCorePolicies(cfg config.Policies) (beacon.Policies, error) {\n\tvar err error\n\tvar policies beacon.Policies\n\tif policies.Prop, err = loadPolicy(cfg.Propagation, beacon.PropPolicy); err != nil {\n\t\treturn policies, err\n\t}\n\tif policies.UpReg, err = loadPolicy(cfg.UpRegistration, beacon.UpRegPolicy); err != nil {\n\t\treturn policies, err\n\t}\n\tif policies.DownReg, err = loadPolicy(cfg.DownRegistration, beacon.DownRegPolicy); err != nil {\n\t\treturn policies, err\n\t}\n\treturn policies, nil\n}\n\nfunc loadPolicy(fn string, t beacon.PolicyType) (beacon.Policy, error) {\n\tvar policy beacon.Policy\n\tif fn != \"\" {\n\t\tp, err := beacon.LoadPolicyFromYaml(fn, t)\n\t\tif err != nil {\n\t\t\treturn policy, serrors.WrapStr(\"loading beaconing policy\", err, \"file\", fn, \"type\", t)\n\t\t}\n\t\tpolicy = *p\n\t}\n\tpolicy.InitDefaults()\n\treturn policy, nil\n}\n\nfunc LoadCorePolicies(cfg config.Policies) (beacon.CorePolicies, error) ", "output": "{\n\tvar err error\n\tvar policies beacon.CorePolicies\n\tif policies.Prop, err = loadPolicy(cfg.Propagation, beacon.PropPolicy); err != nil {\n\t\treturn policies, err\n\t}\n\tif policies.CoreReg, err = loadPolicy(cfg.CoreRegistration, beacon.CoreRegPolicy); err != nil {\n\t\treturn policies, err\n\t}\n\treturn policies, nil\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\tvar n int\n\tfmt.Scan(&n)\n\tmin, max := Solve(n)\n\tfmt.Println(min, max)\n}\n\nfunc Solve(n int) (min, max int) ", "output": "{\n\tmax = n*(n-1)/2 + (n - 1)\n\thoge := []int{0}\n\tfor {\n\t\tfuga := []int{}\n\t\tfor i, v := range hoge {\n\t\t\tfuga = append(fuga, v+1, v+1)\n\t\t\tx := len(hoge) - (i + 1)\n\t\t\tif len(fuga)+x == n {\n\t\t\t\tmin = 0\n\t\t\t\tfor _, f := range fuga {\n\t\t\t\t\tmin += f\n\t\t\t\t}\n\t\t\t\tfor _, z := range hoge[i+1:] {\n\t\t\t\t\tmin += z\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\thoge = fuga\n\t}\n\treturn\n}"} {"input": "package openshift\n\nimport (\n\t\"testing\"\n\n\t\"k8s.io/kubernetes/pkg/genericapiserver\"\n\t\"k8s.io/kubernetes/pkg/master\"\n)\n\n\n\n\n\nfunc TestMasterExportsSymbols(t *testing.T) ", "output": "{\n\t_ = &master.Config{\n\t\tGenericConfig: &genericapiserver.Config{\n\t\t\tEnableSwaggerSupport: false,\n\t\t\tEnableMetrics: true,\n\t\t},\n\t\tEnableCoreControllers: false,\n\t\tEnableUISupport: false,\n\t\tEnableLogsSupport: false,\n\t}\n\t_ = &master.Master{\n\t\tGenericAPIServer: &genericapiserver.GenericAPIServer{},\n\t}\n}"} {"input": "package sqlite3\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/gonuts/binary\"\n)\n\n\n\nfunc unmarshal(buf []byte, ptr interface{}) (int64, error) {\n\tr := bytes.NewReader(buf)\n\tmax := r.Len()\n\tdec := binary.NewDecoder(r)\n\tdec.Order = binary.BigEndian\n\terr := dec.Decode(ptr)\n\tn := max - r.Len()\n\treturn int64(n), err\n}\n\nfunc varint(data []byte) (int64, int) {\n\tvar val uint64\n\tfor i := 0; i < 8; i++ {\n\t\tif i > len(data)-1 {\n\t\t\treturn 0, 0\n\t\t}\n\t\tval = (val << 7) | uint64(data[i]&0x7f)\n\t\tif data[i] < 0x80 {\n\t\t\treturn int64(val), i + 1\n\t\t}\n\t}\n\tif len(data) < 9 {\n\t\treturn 0, 0\n\t}\n\treturn int64((val << 8) | uint64(data[8])), 9\n}\n\nfunc min(a, b int) int ", "output": "{\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}"} {"input": "package async_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/poy/onpar/expect\"\n\t. \"github.com/poy/onpar/matchers\"\n)\n\n\n\nfunc TestChannel(t *testing.T) ", "output": "{\n\tc := make(chan int)\n\tgo func() {\n\t\tfor i := 0; i < 100; i++ {\n\t\t\tc <- i\n\t\t}\n\t}()\n\n\tExpect(t, c).To(ViaPolling(\n\t\tChain(Receive(), Equal(50)),\n\t))\n}"} {"input": "package iso20022\n\n\ntype CorporateActionOption21Choice struct {\n\n\tCode *CorporateActionOption10Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification30 `xml:\"Prtry\"`\n}\n\n\n\nfunc (c *CorporateActionOption21Choice) AddProprietary() *GenericIdentification30 {\n\tc.Proprietary = new(GenericIdentification30)\n\treturn c.Proprietary\n}\n\nfunc (c *CorporateActionOption21Choice) SetCode(value string) ", "output": "{\n\tc.Code = (*CorporateActionOption10Code)(&value)\n}"} {"input": "package classfile\n\nimport \"encoding/binary\"\n\ntype ClassReader struct {\n\tdata []byte \n}\n\nfunc (self *ClassReader) readUint8() uint8 {\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16() uint16 {\n\tval := binary.BigEndian.Uint16(self.data)\n\tself.data = self.data[2:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint32() uint32 {\n\tval := binary.BigEndian.Uint32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\n\n\nfunc (self *ClassReader) readUint16s() []uint16 {\n\tn := self.readUint16()\n\ts := make([]uint16, n)\n\tfor i := range s {\n\t\ts[i] = self.readUint16()\n\t}\n\treturn s\n}\n\nfunc (self *ClassReader) readBytes(n uint32) []byte {\n\tbytes := self.data[:n]\n\tself.data = self.data[n:]\n\treturn bytes\n}\n\nfunc (self *ClassReader) readUint64() uint64 ", "output": "{\n\tval := binary.BigEndian.Uint64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}"} {"input": "package format\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/hashicorp/hcl/v2\"\n\t\"github.com/hashicorp/hcl/v2/hclsyntax\"\n\t\"github.com/hashicorp/hcl/v2/hclwrite\"\n\t\"github.com/katbyte/terrafmt/lib/common\"\n)\n\n\n\nfunc Block(content, path string) (string, error) ", "output": "{\n\tb := []byte(content)\n\tcommon.Log.Debugf(\"format terraform config... \")\n\t_, syntaxDiags := hclsyntax.ParseConfig(b, path, hcl.Pos{Line: 1, Column: 1})\n\tif syntaxDiags.HasErrors() {\n\t\treturn \"\", fmt.Errorf(\"failed to parse hcl: %w\", errors.New(syntaxDiags.Error()))\n\t}\n\treturn string(hclwrite.Format(b)), nil\n}"} {"input": "package mount \n\n\n\nfunc parseMountTable(f FilterFunc) ([]*Info, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package main\n\nimport \"time\"\n\n\n\n\n\nfunc DroneSleep(seconds int) {\n\tlog.Debugf(\"sleeping for %d seconds\", seconds)\n\ttime.Sleep(time.Duration(seconds) * time.Second)\n}\n\nfunc DeleteEmptyString(slice []string) []string ", "output": "{\n\tvar localSlice []string\n\tfor _, str := range slice {\n\t\tif str != \"\" {\n\t\t\tlocalSlice = append(localSlice, str)\n\t\t}\n\t}\n\treturn localSlice\n}"} {"input": "package mincore\n\nimport (\n\t\"os\"\n\t\"unsafe\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\n\nfunc Mincore(data []byte) ([]byte, error) ", "output": "{\n\tvec := make([]byte, (int64(len(data))+int64(os.Getpagesize())-1)/int64(os.Getpagesize()))\n\n\tif ret, _, err := unix.Syscall(\n\t\tunix.SYS_MINCORE,\n\t\tuintptr(unsafe.Pointer(&data[0])),\n\t\tuintptr(len(data)),\n\t\tuintptr(unsafe.Pointer(&vec[0]))); ret != 0 {\n\t\treturn nil, err\n\t}\n\treturn vec, nil\n}"} {"input": "package user\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/juju/cmd\"\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/names\"\n\t\"launchpad.net/gnuflag\"\n\n\t\"github.com/juju/juju/cmd/envcmd\"\n)\n\nconst userCredentialsDoc = `\nWrites out the current user and credentials to a file that can be used\nwith 'juju system login' to allow the user to access the same environments\nas the same user from another machine.\n\nExamples:\n\n $ juju user credentials --output staging.creds\n\n # copy the staging.creds file to another machine\n\n $ juju system login staging --server staging.creds --keep-password\n\n\nSee Also:\n juju system login\n`\n\n\n\n\ntype credentialsCommand struct {\n\tUserCommandBase\n\tOutPath string\n}\n\n\nfunc (c *credentialsCommand) Info() *cmd.Info {\n\treturn &cmd.Info{\n\t\tName: \"credentials\",\n\t\tPurpose: \"save the credentials and server details to a file\",\n\t\tDoc: userCredentialsDoc,\n\t}\n}\n\n\nfunc (c *credentialsCommand) SetFlags(f *gnuflag.FlagSet) {\n\tf.StringVar(&c.OutPath, \"o\", \"\", \"specifies the path of the generated file\")\n\tf.StringVar(&c.OutPath, \"output\", \"\", \"\")\n}\n\n\nfunc (c *credentialsCommand) Run(ctx *cmd.Context) error {\n\tcreds, err := c.ConnectionCredentials()\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfilename := c.OutPath\n\tif filename == \"\" {\n\t\tname := names.NewUserTag(creds.User).Name()\n\t\tfilename = fmt.Sprintf(\"%s.server\", name)\n\t}\n\treturn writeServerFile(c, ctx, creds.User, creds.Password, filename)\n}\n\nfunc newCredentialsCommand() cmd.Command ", "output": "{\n\treturn envcmd.WrapSystem(&credentialsCommand{})\n}"} {"input": "package serialconsole\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/serialconsole/mgmt/2018-05-01/serialconsole\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype BaseClient = original.BaseClient\ntype ConsoleClient = original.ConsoleClient\ntype DeploymentValidateResult = original.DeploymentValidateResult\ntype GetDisabledResult = original.GetDisabledResult\ntype GetResult = original.GetResult\ntype ListClient = original.ListClient\ntype ListConsoleClient = original.ListConsoleClient\ntype Operations = original.Operations\ntype SetDisabledResult = original.SetDisabledResult\n\nfunc New(subscriptionID string) BaseClient {\n\treturn original.New(subscriptionID)\n}\nfunc NewConsoleClient(subscriptionID string) ConsoleClient {\n\treturn original.NewConsoleClient(subscriptionID)\n}\n\nfunc NewListClient(subscriptionID string) ListClient {\n\treturn original.NewListClient(subscriptionID)\n}\nfunc NewListClientWithBaseURI(baseURI string, subscriptionID string) ListClient {\n\treturn original.NewListClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewListConsoleClient(subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClient(subscriptionID)\n}\nfunc NewListConsoleClientWithBaseURI(baseURI string, subscriptionID string) ListConsoleClient {\n\treturn original.NewListConsoleClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\n\nfunc NewConsoleClientWithBaseURI(baseURI string, subscriptionID string) ConsoleClient ", "output": "{\n\treturn original.NewConsoleClientWithBaseURI(baseURI, subscriptionID)\n}"} {"input": "package data\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/credentials\"\n\t\"github.com/aws/aws-sdk-go/aws/session\"\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/guregu/dynamo\"\n\t\"github.com/spf13/viper\"\n)\n\n\ntype DynamoDB struct {\n\tdb *dynamo.DB\n}\n\n\nfunc (d *DynamoDB) Connect() error {\n\tvar awsConfig *aws.Config\n\tif viper.GetString(\"DynamoEndpoint\") == \"\" {\n\t\tawsConfig = &aws.Config{}\n\t} else {\n\t\tmyTrue := true\n\t\tawsConfig = &aws.Config{\n\t\t\tEndpoint: aws.String(viper.GetString(\"DynamoEndpoint\")),\n\t\t\tCredentials: credentials.NewStaticCredentials(\"foo\", \"foo\", \"foo\"),\n\t\t\tDisableSSL: &myTrue,\n\t\t}\n\t}\n\tawsConfig.WithRegion(viper.GetString(\"DynamoRegion\"))\n\tif gin.Mode() == gin.DebugMode {\n\t\tawsConfig.WithLogLevel(aws.LogDebugWithHTTPBody)\n\t}\n\n\td.db = dynamo.New(session.Must(session.NewSession()), awsConfig)\n\n\treturn nil\n}\n\nfunc (d *DynamoDB) FindByHash(hash string) (*Avatar, error) {\n\tvar avatar Avatar\n\n\tif err := d.getTable().Get(\"Hash\", hash).One(&avatar); err != nil {\n\t\treturn nil, fmt.Errorf(\"Cannot find avatar with hash %s\", hash)\n\t}\n\n\treturn &avatar, nil\n}\n\n\n\nfunc (d *DynamoDB) Migrate() error {\n\treturn nil\n}\n\nfunc (d *DynamoDB) getTable() dynamo.Table {\n\treturn d.db.Table(viper.GetString(\"TableName\"))\n}\n\nfunc (d *DynamoDB) Save(a *Avatar) error ", "output": "{\n\n\tif err := d.getTable().Put(a).Run(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package release_v1_4\n\nimport (\n\t\"github.com/golang/glog\"\n\tv1core \"github.com/openshift/origin/pkg/build/client/clientset_generated/release_v1_4/typed/core/v1\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n\tdiscovery \"k8s.io/kubernetes/pkg/client/typed/discovery\"\n\t\"k8s.io/kubernetes/pkg/util/flowcontrol\"\n)\n\ntype Interface interface {\n\tDiscovery() discovery.DiscoveryInterface\n\tCore() v1core.CoreInterface\n}\n\n\n\ntype Clientset struct {\n\t*discovery.DiscoveryClient\n\t*v1core.CoreClient\n}\n\n\nfunc (c *Clientset) Core() v1core.CoreInterface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.CoreClient\n}\n\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\treturn c.DiscoveryClient\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *restclient.Config) *Clientset {\n\tvar clientset Clientset\n\tclientset.CoreClient = v1core.NewForConfigOrDie(c)\n\n\tclientset.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)\n\treturn &clientset\n}\n\n\nfunc New(c *restclient.RESTClient) *Clientset {\n\tvar clientset Clientset\n\tclientset.CoreClient = v1core.New(c)\n\n\tclientset.DiscoveryClient = discovery.NewDiscoveryClient(c)\n\treturn &clientset\n}\n\nfunc NewForConfig(c *restclient.Config) (*Clientset, error) ", "output": "{\n\tconfigShallowCopy := *c\n\tif configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {\n\t\tconfigShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)\n\t}\n\tvar clientset Clientset\n\tvar err error\n\tclientset.CoreClient, err = v1core.NewForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientset.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)\n\tif err != nil {\n\t\tglog.Errorf(\"failed to create the DiscoveryClient: %v\", err)\n\t\treturn nil, err\n\t}\n\treturn &clientset, nil\n}"} {"input": "package leetcode\n\n\n\n\n\ntype MyStack struct {\n\telements []int\n}\n\n\nfunc NewMyStack() MyStack {\n\treturn MyStack{}\n}\n\n\n\n\n\nfunc (this *MyStack) Pop() int {\n\tn := len(this.elements)\n\te := this.elements[n-1]\n\tthis.elements = this.elements[:n-1]\n\treturn e\n}\n\n\nfunc (this *MyStack) Top() int {\n\treturn this.elements[len(this.elements)-1]\n}\n\n\nfunc (this *MyStack) Empty() bool {\n\treturn len(this.elements) == 0\n}\n\nfunc (this *MyStack) Push(x int) ", "output": "{\n\tthis.elements = append(this.elements, x)\n}"} {"input": "package store\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype Row struct {\n\tData []string\n}\n\nfunc ReadData(path string) []byte {\n\td, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn []byte(``)\n\t}\n\n\treturn d\n}\n\nfunc ReadRows(path, delimiter string) *[]Row {\n\tf, _ := os.Open(path)\n\n\tdefer f.Close()\n\n\trows := []Row{}\n\ts := bufio.NewScanner(f)\n\ts.Split(bufio.ScanLines)\n\n\tfor s.Scan() {\n\t\tdata := strings.Split(s.Text(), delimiter)\n\t\tr := &Row{Data: data}\n\t\trows = append(rows, *r)\n\t}\n\n\treturn &rows\n}\n\n\n\nfunc WriteRows(path string, rows *[]Row, delimeter string) {\n\tf, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0644)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer f.Close()\n\n\tfor _, r := range *rows {\n\t\t_, err = f.WriteString(strings.Join(r.Data, delimeter))\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n}\n\nfunc WriteData(path string, data []byte) ", "output": "{\n\tf, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer f.Close()\n\n\t_, err = f.Write(data)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}"} {"input": "package gonfler\n\nimport (\n\t\"archive/tar\"\n\t\"os\"\n)\n\ntype TarArchive struct {\n\thandle *tar.Reader\n\tfile *os.File\n}\n\nfunc (archive TarArchive) Close() error {\n\treturn archive.file.Close()\n}\n\nfunc (archive TarArchive) Volumes() VolumeIterator {\n\tvar next func() VolumeIterator\n\tnext = func() VolumeIterator {\n\t\theader, err := archive.handle.Next()\n\t\tif err != nil {\n\t\t\treturn VolumeIterator{nil, nil}\n\t\t} else {\n\t\t\treturn VolumeIterator{\n\t\t\t\tvolume: &Volume{archive.handle, header.Name},\n\t\t\t\tnext: next,\n\t\t\t}\n\t\t}\n\t}\n\treturn next()\n}\n\n\n\nfunc openTar(name string) (Archive, error) ", "output": "{\n\tfile, e := os.Open(name)\n\tif file != nil {\n\t\treturn TarArchive{tar.NewReader(file), file}, nil\n\t} else {\n\t\treturn nil, e\n\t}\n}"} {"input": "package thuder\n\nimport (\n\t\"errors\"\n)\n\n\n\nfunc setupGPIO() error ", "output": "{\n\treturn errors.New(\"Not Supported\")\n}"} {"input": "package openpgp\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\ntype recordingHash struct {\n\tbuf *bytes.Buffer\n}\n\nfunc (r recordingHash) Write(b []byte) (n int, err error) {\n\treturn r.buf.Write(b)\n}\n\nfunc (r recordingHash) Sum(in []byte) []byte {\n\treturn append(in, r.buf.Bytes()...)\n}\n\nfunc (r recordingHash) Reset() {\n\tpanic(\"shouldn't be called\")\n}\n\nfunc (r recordingHash) Size() int {\n\tpanic(\"shouldn't be called\")\n}\n\nfunc (r recordingHash) BlockSize() int {\n\tpanic(\"shouldn't be called\")\n}\n\n\n\nfunc TestCanonicalText(t *testing.T) {\n\ttestCanonicalText(t, \"foo\\n\", \"foo\\r\\n\")\n\ttestCanonicalText(t, \"foo\", \"foo\")\n\ttestCanonicalText(t, \"foo\\r\\n\", \"foo\\r\\n\")\n\ttestCanonicalText(t, \"foo\\r\\nbar\", \"foo\\r\\nbar\")\n\ttestCanonicalText(t, \"foo\\r\\nbar\\n\\n\", \"foo\\r\\nbar\\r\\n\\r\\n\")\n}\n\nfunc testCanonicalText(t *testing.T, input, expected string) ", "output": "{\n\tr := recordingHash{bytes.NewBuffer(nil)}\n\tc := NewCanonicalTextHash(r)\n\tc.Write([]byte(input))\n\tresult := c.Sum(nil)\n\tif expected != string(result) {\n\t\tt.Errorf(\"input: %x got: %x want: %x\", input, result, expected)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\nvar configFileOptions map[string]interface{}\n\nfunc LoadConfigFile(file string) error {\n\tconfigFileOptions = nil\n\tif _, err := os.Stat(file); err != nil {\n\t\treturn nil\n\t}\n\tif s, err := ioutil.ReadFile(file); err != nil {\n\t\treturn err\n\t} else if err := yaml.Unmarshal(s, &configFileOptions); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc getConfigFileValue(key string) interface{} {\n\tif v, ok := configFileOptions[key]; ok {\n\t\treturn v\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc IsKeyInConfig(key string) bool {\n\t_, ok := configFileOptions[key]\n\treturn ok\n}\n\nfunc getConfigFileValueWithDefault(key string, defaultValue interface{}) interface{} {\n\tif v := getConfigFileValue(key); v != nil {\n\t\treturn v\n\t} else {\n\t\treturn defaultValue\n\t}\n}\n\n\n\nfunc GetConfigFileSlice(key string) []string {\n\tif v, ok := configFileOptions[key].([]interface{}); ok {\n\t\tretVal := []string{}\n\t\tfor _, e := range v {\n\t\t\tif strV, ok := e.(string); ok {\n\t\t\t\tretVal = append(retVal, strV)\n\t\t\t}\n\t\t}\n\t\treturn retVal\n\t} else {\n\t\treturn []string{}\n\t}\n}\n\nfunc GetConfigFileString(key string) string {\n\tv, _ := getConfigFileValue(key).(string)\n\treturn v\n}\n\n\n\nfunc GetConfigFileStringWithDefault(key string, defaultValue interface{}) string ", "output": "{\n\tv, _ := getConfigFileValueWithDefault(key, defaultValue).(string)\n\treturn v\n}"} {"input": "package auth\n\nimport (\n\tauthorizationapi \"github.com/projectatomic/atomic-enterprise/pkg/authorization/api\"\n\t\"github.com/projectatomic/atomic-enterprise/pkg/client\"\n)\n\n\ntype Review interface {\n\tUsers() []string\n\tGroups() []string\n}\n\ntype review struct {\n\tresponse *authorizationapi.ResourceAccessReviewResponse\n}\n\n\n\n\n\nfunc (r *review) Groups() []string {\n\treturn r.response.Groups.List()\n}\n\n\ntype Reviewer interface {\n\tReview(name string) (Review, error)\n}\n\n\ntype reviewer struct {\n\tresourceAccessReviewsNamespacer client.ResourceAccessReviewsNamespacer\n}\n\n\nfunc NewReviewer(resourceAccessReviewsNamespacer client.ResourceAccessReviewsNamespacer) Reviewer {\n\treturn &reviewer{\n\t\tresourceAccessReviewsNamespacer: resourceAccessReviewsNamespacer,\n\t}\n}\n\n\nfunc (r *reviewer) Review(name string) (Review, error) {\n\tresourceAccessReview := &authorizationapi.ResourceAccessReview{\n\t\tVerb: \"get\",\n\t\tResource: \"namespaces\",\n\t\tResourceName: name,\n\t}\n\n\tresponse, err := r.resourceAccessReviewsNamespacer.ResourceAccessReviews(name).Create(resourceAccessReview)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treview := &review{\n\t\tresponse: response,\n\t}\n\treturn review, nil\n}\n\nfunc (r *review) Users() []string ", "output": "{\n\treturn r.response.Users.List()\n}"} {"input": "package handlers\n\nimport (\n\t\"github.com/bbiskup/edify-web/defs\"\n\t\"github.com/gorilla/mux\"\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n)\n\nvar compositeDataElemSpecTemplates *template.Template\n\n\n\nfunc CompositeDataElemSpec(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tdataElemSpecID := vars[\"id\"]\n\n\tdata := map[string]interface{}{\n\t\t\"dataElemSpec\": defs.SpecParser.CompositeDataElemSpecs[dataElemSpecID],\n\t}\n\n\terr := compositeDataElemSpecTemplates.ExecuteTemplate(w, \"layout\", data)\n\tif err != nil {\n\t\tlog.Printf(\"Error executing template: %s\", err)\n\t}\n}\n\nfunc init() ", "output": "{\n\tfuncMap := template.FuncMap{\n\t\t\"DataElemSpecURL\": DataElemSpecURL,\n\t}\n\tt := template.New(\"layout.html\").Funcs(funcMap)\n\tcompositeDataElemSpecTemplates = template.Must(t.ParseFiles(\n\t\tdefs.TemplatePaths(\"layout.html\", \"navbar.html\", \"compositedataelemspec.html\")...,\n\t))\n}"} {"input": "package chipmunk\n\nimport (\n\t\"github.com/Dethrail/chipmunk/transform\"\n\t\"github.com/Dethrail/chipmunk/vect\"\n\t\"math\"\n)\n\nconst (\n\tRadianConst = math.Pi / 180\n\tDegreeConst = 180 / math.Pi\n)\n\ntype Group int\ntype Layer int\n\ntype Shape struct {\n\tDefaultHash\n\tShapeClass\n\n\tBody *Body\n\n\tBB AABB\n\n\tIsSensor bool\n\n\te vect.Float\n\tu vect.Float\n\tSurface_v vect.Vect\n\n\tUserData interface{}\n\n\tGroup Group\n\tLayer Layer\n\n\tspace *Space\n\n\tvelocityIndexed bool\n}\n\nfunc newShape() *Shape {\n\treturn &Shape{velocityIndexed: true, e: 0.5, u: 0.5, Layer: -1}\n\n}\n\nfunc (shape *Shape) Velocity() (vect.Vect, bool) {\n\treturn shape.Body.v, shape.velocityIndexed\n}\n\nfunc (shape *Shape) SetFriction(friction vect.Float) {\n\tshape.u = friction\n}\n\n\n\nfunc (shape *Shape) Shape() *Shape {\n\treturn shape\n}\n\nfunc (shape *Shape) AABB() AABB {\n\treturn shape.BB\n}\n\nfunc (shape *Shape) Clone() *Shape {\n\tclone := *shape\n\tcc := &clone\n\tcc.space = nil\n\tcc.DefaultHash.Reset()\n\tcc.Body = nil\n\tcc.ShapeClass = cc.ShapeClass.Clone(cc)\n\treturn cc\n}\n\nfunc (shape *Shape) Update() {\n\tshape.BB = shape.ShapeClass.update(transform.NewTransform(shape.Body.p, shape.Body.a))\n}\n\nfunc (shape *Shape) SetElasticity(e vect.Float) ", "output": "{\n\tshape.e = e\n}"} {"input": "package dummy\n\nimport (\n\t\"log\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/svenwiltink/go-musicbot/pkg/music\"\n)\n\ntype SongPlayer struct {\n\tlock sync.Mutex\n}\n\nfunc (player *SongPlayer) CanPlay(song music.Song) bool {\n\treturn true\n}\n\n\n\nfunc (player *SongPlayer) PlaySong(song music.Song) error {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\tlog.Printf(\"starting playback of %s\", song.Name)\n\treturn nil\n}\n\nfunc (player *SongPlayer) Play() error {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\tlog.Printf(\"resuming playback\")\n\treturn nil\n}\n\nfunc (player *SongPlayer) Pause() error {\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\tlog.Printf(\"pausing playback\")\n\treturn nil\n}\n\nfunc NewSongPlayer() *SongPlayer {\n\treturn &SongPlayer{}\n}\n\nfunc (player *SongPlayer) Wait() ", "output": "{\n\tplayer.lock.Lock()\n\tdefer player.lock.Unlock()\n\n\ttime.Sleep(time.Second * 10)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\nvar (\n\tn, l, count int\n\tout io.WriteCloser\n)\n\nfunc isEasy(level int, sequence []string) bool {\nhere:\n\tfor i := 1; 2*i <= level+1; i++ {\n\t\tfor j := 0; j < i; j++ {\n\t\t\tif sequence[level-j] != sequence[level-j-i] {\n\t\t\t\tcontinue here\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc dfs(level int, sequence []string) bool {\n\tif count == n {\n\t\toutput(sequence)\n\t\treturn true\n\t}\n\tcount++\n\tfor i := 0; i < l; i++ {\n\t\tif !isEasy(level, append(sequence, string('A'+i))) {\n\t\t\tif dfs(level+1, append(sequence, string('A'+i))) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc main() {\n\tin, _ := os.Open(\"129.in\")\n\tdefer in.Close()\n\tout, _ = os.Create(\"129.out\")\n\tdefer out.Close()\n\n\tfor {\n\t\tif fmt.Fscanf(in, \"%d%d\", &n, &l); n == 0 && l == 0 {\n\t\t\tbreak\n\t\t}\n\t\tcount = 0\n\t\tdfs(0, nil)\n\t}\n}\n\nfunc output(sequence []string) ", "output": "{\n\tfor i := range sequence {\n\t\tswitch {\n\t\tcase i > 0 && i%64 == 0:\n\t\t\tfmt.Fprintln(out)\n\t\tcase i > 0 && i%4 == 0:\n\t\t\tfmt.Fprint(out, \" \")\n\t\t}\n\t\tfmt.Fprint(out, sequence[i])\n\t}\n\tfmt.Fprintf(out, \"\\n%d\\n\", len(sequence))\n}"} {"input": "package hostInfo\n\nimport (\n\t\"github.com/pkg/errors\"\n\t\"github.com/rancher/agent/utilities/constants\"\n)\n\ntype IopsCollector struct {\n}\n\n\n\nfunc (i IopsCollector) KeyName() string {\n\treturn \"iopsInfo\"\n}\n\nfunc (i IopsCollector) GetLabels(prefix string) (map[string]string, error) {\n\treturn map[string]string{}, nil\n}\n\nfunc (i IopsCollector) GetData() (map[string]interface{}, error) ", "output": "{\n\tdata, err := i.parseIopsData()\n\tif err != nil {\n\t\treturn map[string]interface{}{}, errors.Wrap(err, constants.IopsGetDataError+\"failed to get data\")\n\t}\n\treturn data, nil\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\n\nfunc main() {\n\tres := fib(20)\n\tfmt.Println(res)\n}\n\nfunc fib(n int) int ", "output": "{\n\tif n < 2 {\n\t\treturn n\n\t} else {\n\t\treturn fib(n-1) + fib(n-2)\n\t}\n}"} {"input": "package data\n\nimport (\n\t\"testing\"\n)\n\n\nvar album = Album{\n\tArtist: \"TestArtist\",\n\tArtistID: 1,\n\tTitle: \"TestAlbum\",\n\tYear: 2014,\n}\n\n\n\n\nfunc TestAlbumDatabase(t *testing.T) ", "output": "{\n\tDB = new(SqliteBackend)\n\tDB.DSN(\"~/.config/wavepipe/wavepipe.db\")\n\tif err := DB.Open(); err != nil {\n\t\tt.Fatalf(\"Could not open database connection: %s\", err.Error())\n\t}\n\tdefer DB.Close()\n\n\tif err := album.Save(); err != nil {\n\t\tt.Fatalf(\"Could not save album: %s\", err.Error())\n\t}\n\n\tif err := album.Load(); err != nil {\n\t\tt.Fatalf(\"Could not load album: %s\", err.Error())\n\t}\n\n\tif err := album.Delete(); err != nil {\n\t\tt.Fatalf(\"Could not delete album: %s\", err.Error())\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\n\nfunc main() {\n\troot := \"./\"\n\tfilepath.Walk(root, walkFn)\n}\n\nfunc walkFn(path string, info os.FileInfo, err error) error ", "output": "{\n\tif err != nil {\n\t\tfmt.Println(\"Walker Error: \", err)\n\t\treturn nil\n\t}\n\tif info.IsDir() {\n\t\tfmt.Println(\"Directory: \", path)\n\t} else {\n\t\tfmt.Println(\"File: \", path)\n\t}\n\treturn nil\n}"} {"input": "package cdrom\n\nimport (\n\t\"github.com/sacloud/libsacloud/v2/helper/validate\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\ntype CloseFTPRequest struct {\n\tZone string `request:\"-\" validate:\"required\"`\n\tID types.ID `request:\"-\" validate:\"required\"`\n}\n\n\n\nfunc (req *CloseFTPRequest) Validate() error ", "output": "{\n\treturn validate.Struct(req)\n}"} {"input": "package identity\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListTaggingWorkRequestErrorsRequest struct {\n\n\tWorkRequestId *string `mandatory:\"true\" contributesTo:\"path\" name:\"workRequestId\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListTaggingWorkRequestErrorsRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListTaggingWorkRequestErrorsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request ListTaggingWorkRequestErrorsRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListTaggingWorkRequestErrorsResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []TaggingWorkRequestErrorSummary `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n\n\tRetryAfter *float32 `presentIn:\"header\" name:\"retry-after\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n}\n\nfunc (response ListTaggingWorkRequestErrorsResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListTaggingWorkRequestErrorsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListTaggingWorkRequestErrorsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package testing\n\nimport (\n\t\"github.com/markdaws/gohome/pkg/cmd\"\n\t\"github.com/markdaws/gohome/pkg/gohome\"\n)\n\ntype extension struct {\n\tgohome.NullExtension\n}\n\nfunc (e *extension) Name() string {\n\treturn \"testing\"\n}\n\nfunc (e *extension) BuilderForDevice(sys *gohome.System, d *gohome.Device) cmd.Builder {\n\tswitch d.ModelNumber {\n\tcase \"testing.hardware\":\n\t\treturn &cmdBuilder{ModelNumber: d.ModelNumber, Device: d}\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (e *extension) NetworkForDevice(sys *gohome.System, d *gohome.Device) gohome.Network {\n\treturn nil\n}\n\nfunc (e *extension) EventsForDevice(sys *gohome.System, d *gohome.Device) *gohome.ExtEvents {\n\tswitch d.ModelNumber {\n\tcase \"testing.hardware\":\n\t\tevts := &gohome.ExtEvents{}\n\t\tevts.Producer = &producer{\n\t\t\tDevice: d,\n\t\t\tSystem: sys,\n\t\t}\n\t\tevts.Consumer = &consumer{\n\t\t\tDevice: d,\n\t\t\tSystem: sys,\n\t\t}\n\t\treturn evts\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (e *extension) Discovery(sys *gohome.System) gohome.Discovery {\n\treturn &discovery{}\n}\n\n\n\nfunc NewExtension() *extension ", "output": "{\n\treturn &extension{}\n}"} {"input": "package service\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestService_OnlineArchiveCount(t *testing.T) {\n\tConvey(\"test online OnlineArchiveCount\", t, WithService(func(s *Service) {\n\t\tres := s.OnlineArchiveCount(context.Background())\n\t\tSo(res, ShouldNotBeNil)\n\t}))\n}\n\nfunc TestService_OnlineList(t *testing.T) ", "output": "{\n\tConvey(\"online list\", t, WithService(func(s *Service) {\n\t\tdata, err := s.OnlineList(context.Background())\n\t\tSo(err, ShouldBeNil)\n\t\tPrintf(\"%v\", data)\n\t}))\n}"} {"input": "package util\n\ntype Progress struct {\n\terrs chan error\n\tdone chan struct{}\n}\n\n\n\nfunc (p *Progress) JobDone(err error) {\n\tif p == nil {\n\t\treturn\n\t}\n\tp.errs <- err\n}\n\nfunc (p *Progress) Close() {\n\tif p == nil {\n\t\treturn\n\t}\n\tclose(p.errs)\n\t<-p.done\n}\n\nfunc NewProgress(total int) *Progress ", "output": "{\n\tp := &Progress{make(chan error), make(chan struct{})}\n\tgo func() {\n\t\tcompleted := 0\n\t\terrorCount := 0\n\t\tfor err := range p.errs {\n\t\t\tif err == nil {\n\t\t\t\tcompleted += 1\n\t\t\t} else {\n\t\t\t\terrorCount += 1\n\t\t\t\tif FlagQuiet {\n\t\t\t\t\tWarnf(\"%s\", err)\n\t\t\t\t} else {\n\t\t\t\t\tWarnf(\"\\r%s \\n\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tratio := 100.0 * (float64(completed) / float64(total))\n\t\t\tVerbosef(\"\\r%d of %d jobs complete (%0.2f%% done, %d errors)\",\n\t\t\t\tcompleted, total, ratio, errorCount)\n\t\t}\n\t\tVerbosef(\"\\n\")\n\t\tp.done <- struct{}{}\n\t}()\n\treturn p\n}"} {"input": "package dns\n\n\n\n\nfunc testRR(s string) RR ", "output": "{\n\tr, _ := NewRR(s)\n\treturn r\n}"} {"input": "package payload_test\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/RobotsAndPencils/buford/payload\"\n)\n\n\n\nfunc TestBrowser(t *testing.T) {\n\tp := payload.Browser{\n\t\tAlert: payload.BrowserAlert{\n\t\t\tTitle: \"Flight A998 Now Boarding\",\n\t\t\tBody: \"Boarding has begun for Flight A998.\",\n\t\t\tAction: \"View\",\n\t\t},\n\t\tURLArgs: []string{\"boarding\", \"A998\"},\n\t}\n\texpected := []byte(`{\"aps\":{\"alert\":{\"title\":\"Flight A998 Now Boarding\",\"body\":\"Boarding has begun for Flight A998.\",\"action\":\"View\"},\"url-args\":[\"boarding\",\"A998\"]}}`)\n\ttestPayload(t, p, expected)\n}\n\nfunc TestValidBrowser(t *testing.T) {\n\tp := payload.Browser{\n\t\tAlert: payload.BrowserAlert{\n\t\t\tTitle: \"Flight A998 Now Boarding\",\n\t\t\tBody: \"Boarding has begun for Flight A998.\",\n\t\t},\n\t}\n\tif err := p.Validate(); err != nil {\n\t\tt.Errorf(\"Expected no error, got %v.\", err)\n\t}\n}\n\nfunc TestInvalidBrowser(t *testing.T) {\n\ttests := []*payload.Browser{\n\t\t{\n\t\t\tAlert: payload.BrowserAlert{Action: \"View\"},\n\t\t},\n\t\t{},\n\t\tnil,\n\t}\n\n\tfor _, p := range tests {\n\t\tif err := p.Validate(); err != payload.ErrIncomplete {\n\t\t\tt.Errorf(\"Expected err %v, got %v.\", payload.ErrIncomplete, err)\n\t\t}\n\t}\n}\n\nfunc ExampleBrowser() ", "output": "{\n\tp := payload.Browser{\n\t\tAlert: payload.BrowserAlert{\n\t\t\tTitle: \"Flight A998 Now Boarding\",\n\t\t\tBody: \"Boarding has begun for Flight A998.\",\n\t\t\tAction: \"View\",\n\t\t},\n\t\tURLArgs: []string{\"boarding\", \"A998\"},\n\t}\n\n\tb, err := json.Marshal(p)\n\tif err != nil {\n\t}\n\tfmt.Printf(\"%s\", b)\n}"} {"input": "package storage\n\nimport (\n\t\"fmt\"\n\t\"github.com/apigee-labs/transicator/common\"\n\t\"strings\"\n)\n\n\nconst (\n\tEntryComparatorName = \"transicator-entries-v1\"\n\tSequenceComparatorName = \"transicator-sequence-v1\"\n)\n\nvar entryComparator = new(entryCmp)\nvar sequenceComparator = new(sequenceCmp)\n\ntype entryCmp struct {\n}\n\n\nfunc (c entryCmp) Compare(a, b []byte) int {\n\taScope, aLsn, aIndex, err := keyToLsnAndOffset(a)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error parsing database key: %s\", err))\n\t}\n\tbScope, bLsn, bIndex, err := keyToLsnAndOffset(b)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error parsing database key: %s\", err))\n\t}\n\n\tscopeCmp := strings.Compare(aScope, bScope)\n\tif scopeCmp == 0 {\n\t\tif aLsn < bLsn {\n\t\t\treturn -1\n\t\t} else if aLsn > bLsn {\n\t\t\treturn 1\n\t\t}\n\n\t\tif aIndex < bIndex {\n\t\t\treturn -1\n\t\t} else if aIndex > bIndex {\n\t\t\treturn 1\n\t\t}\n\t\treturn 0\n\t}\n\treturn scopeCmp\n}\n\n\nfunc (c entryCmp) Name() string {\n\treturn EntryComparatorName\n}\n\ntype sequenceCmp struct {\n}\n\n\n\nfunc (s sequenceCmp) Name() string {\n\treturn SequenceComparatorName\n}\n\nfunc (s sequenceCmp) Compare(a, b []byte) int ", "output": "{\n\ts1, err := common.ParseSequenceBytes(a)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error parsing sequence: %s\", err))\n\t}\n\ts2, err := common.ParseSequenceBytes(b)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error parsing sequence: %s\", err))\n\t}\n\n\treturn s1.Compare(s2)\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/converter\"\n\t\"strings\"\n)\n\n\ntype CreateScalingTagsRequestBody struct {\n\tTags *[]TagsSingleValue `json:\"tags,omitempty\"`\n\tAction *CreateScalingTagsRequestBodyAction `json:\"action,omitempty\"`\n}\n\nfunc (o CreateScalingTagsRequestBody) String() string {\n\tdata, _ := json.Marshal(o)\n\treturn strings.Join([]string{\"CreateScalingTagsRequestBody\", string(data)}, \" \")\n}\n\ntype CreateScalingTagsRequestBodyAction struct {\n\tvalue string\n}\n\ntype CreateScalingTagsRequestBodyActionEnum struct {\n\tCREATE CreateScalingTagsRequestBodyAction\n}\n\nfunc GetCreateScalingTagsRequestBodyActionEnum() CreateScalingTagsRequestBodyActionEnum {\n\treturn CreateScalingTagsRequestBodyActionEnum{\n\t\tCREATE: CreateScalingTagsRequestBodyAction{\n\t\t\tvalue: \"create\",\n\t\t},\n\t}\n}\n\n\n\nfunc (c *CreateScalingTagsRequestBodyAction) UnmarshalJSON(b []byte) error {\n\tmyConverter := converter.StringConverterFactory(\"string\")\n\tif myConverter != nil {\n\t\tval, err := myConverter.CovertStringToInterface(strings.Trim(string(b[:]), \"\\\"\"))\n\t\tif err == nil {\n\t\t\tc.value = val.(string)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t} else {\n\t\treturn errors.New(\"convert enum data to string error\")\n\t}\n}\n\nfunc (c CreateScalingTagsRequestBodyAction) MarshalJSON() ([]byte, error) ", "output": "{\n\treturn json.Marshal(c.value)\n}"} {"input": "package amber\n\nimport (\n\t\"errors\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/kotfalya/amber/utils\"\n)\n\ntype DB struct {\n\tconfig *Config\n\tname string\n\trootPage *Page\n\treq chan *Req\n\tstop chan struct{}\n}\n\nfunc NewDB(name string, config *Config) *DB {\n\tdb := &DB{\n\t\tconfig: config,\n\t\tname: name,\n\t\trootPage: createRootPage(),\n\t\treq: make(chan *Req, 10),\n\t\tstop: make(chan struct{}),\n\t}\n\tgo db.start()\n\n\treturn db\n}\n\nfunc (db *DB) start() {\n\tsem := utils.NewSemaphore(10)\n\tfor {\n\t\tselect {\n\t\tcase req := <-db.req:\n\t\t\treq.master = db.name\n\t\t\tsem.Acquire()\n\t\t\tgo func(req *Req) {\n\t\t\t\tdefer sem.Release()\n\t\t\t\tswitch req.handler {\n\t\t\t\tcase RequestDBHandler:\n\t\t\t\t\tDBHandle(db, req)\n\t\t\t\tcase RequestKeyHandler:\n\t\t\t\t\tKeyHandler(db, req)\n\t\t\t\tcase RequestNetHandler:\n\t\t\t\t\tNetHandler(db, req)\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(errors.New(ErrInvalidReqHandler))\n\t\t\t\t}\n\n\t\t\t}(req)\n\n\t\tcase <-db.stop:\n\t\t\tglog.V(1).Infoln(\"db:stop\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (db *DB) load(keyName string, level int) (Key, error) {\n\tkey, err := db.rootPage.load(keyName)\n\tif err != nil {\n\t\treturn nil, errors.New(ErrUndefinedKey)\n\t}\n\treturn key, nil\n}\n\n\n\nfunc DBHandle(db *DB, req *Req) {\n\n}\n\nfunc (db *DB) add(keyName string, key Key, level int) (err error) ", "output": "{\n\terr = db.rootPage.add(keyName, key)\n\n\treturn\n}"} {"input": "package helper\n\n\n\n\nfunc SumIntSliceTillPos(slice []int, pos int) int ", "output": "{\n\tsum := 0\n\tfor index, value := range slice {\n\t\tif index <= pos {\n\t\t\tsum += value\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn sum\n}"} {"input": "package streaming\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteStreamPoolRequest struct {\n\n\tStreamPoolId *string `mandatory:\"true\" contributesTo:\"path\" name:\"streamPoolId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteStreamPoolRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteStreamPoolRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request DeleteStreamPoolRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request DeleteStreamPoolRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteStreamPoolResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response DeleteStreamPoolResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response DeleteStreamPoolResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype talker interface {\n\ttalk() string\n}\n\nfunc shout(t talker) {\n\tlouder := strings.ToUpper(t.talk())\n\tfmt.Println(louder)\n}\n\ntype laser int\n\nfunc (l laser) talk() string {\n\treturn strings.Repeat(\"toot \", int(l))\n}\n\ntype rover string\n\n\n\nfunc main() {\n\tr := rover(\"whir whir\")\n\tshout(r)\n}\n\nfunc (r rover) talk() string ", "output": "{\n\treturn string(r)\n}"} {"input": "package utilities\n\nimport (\n\t\"strings\"\n)\n\n\n\n\nfunc PascalFromSnake(str string) string ", "output": "{\n\tvar components []string\n\tfor _, c := range strings.Split(str, \"_\") {\n\t\tcomponents = append(components, strings.Title(strings.ToLower(c)))\n\t}\n\treturn strings.Join(components, \"\")\n}"} {"input": "package encoder\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"crypto\"\n\t\"github.com/bysir-zl/bygo/util\"\n)\n\nfunc Sha256(in string) string {\n\thash := sha256.New()\n\thash.Write([]byte(in))\n\tmd := hash.Sum(nil)\n\tmdStr := hex.EncodeToString(md)\n\treturn mdStr\n}\n\n\n\nfunc HashString(in string, hash crypto.Hash) (out string) {\n\th := hash.New()\n\th.Write(util.S2B(in))\n\tmd := h.Sum(nil)\n\tout = hex.EncodeToString(md)\n\treturn\n}\n\nfunc Hash(in []byte, hash crypto.Hash) (out []byte) ", "output": "{\n\th := hash.New()\n\th.Write(in)\n\tmd := h.Sum(nil)\n\tout = make([]byte, hex.EncodedLen(len(md)))\n\thex.Encode(out, md)\n\treturn\n}"} {"input": "package api\n\nimport \"net/http\"\n\n\ntype Middleware interface {\n\tSetNext(http.Handler)\n\thttp.Handler\n}\n\n\n\n\nfunc Chain(f http.Handler, middlewares ...Middleware) http.Handler ", "output": "{\n\tif len(middlewares) == 0 {\n\t\treturn f\n\t}\n\n\tvar last Middleware\n\tfor i, m := range middlewares {\n\t\tif i == len(middlewares)-1 {\n\t\t\tm.SetNext(f)\n\t\t}\n\n\t\tif i > 0 {\n\t\t\tlast.SetNext(m)\n\t\t}\n\n\t\tlast = m\n\t}\n\n\treturn middlewares[0]\n}"} {"input": "package http\n\nimport (\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\n\n\nfunc debugCache(c *bm.Context) ", "output": "{\n\topt := new(struct {\n\t\tKeys string `form:\"keys\" validate:\"required\"`\n\t})\n\tif err := c.Bind(opt); err != nil {\n\t\treturn\n\t}\n\tc.JSONMap(srv.DebugCache(opt.Keys), nil)\n}"} {"input": "package database\n\nimport (\n\t\"labix.org/v2/mgo\"\n\t\"labix.org/v2/mgo/bson\"\n\t\"github.com/DewaldV/crucible/config\"\n)\n\ntype MgoConnection struct {\n\tDatabase string\n\tCollection string\n}\n\nfunc (conn *MgoConnection) FindOne(m bson.M, d interface{}) {\n\tExecuteWithCollection(conn.Database, conn.Collection, func(c *mgo.Collection) error { return c.Find(m).One(d) })\n}\n\nfunc (conn *MgoConnection) FindAll(m bson.M, d interface{}) {\n\tExecuteWithCollection(conn.Database, conn.Collection, func(c *mgo.Collection) error { return c.Find(m).All(d) })\n}\n\n\n\n\n\n\nfunc ExecuteWithCollection(database, collection string, f func(*mgo.Collection) error) error {\n\tsession := GetSession(\"Default\")\n\tdefer session.Close()\n\n\tsession.SetMode(mgo.Monotonic, true)\n\n\tc := session.DB(database).C(collection)\n\n\treturn f(c)\n}\n\nvar sessionPool map[string]*mgo.Session\n\nfunc LoadSessions(dataSourceConfig map[string]*config.DataSourceConfiguration) {\n\tsessionPool = make(map[string]*mgo.Session)\n\tfor key, source := range dataSourceConfig {\n\t\ts, _ := mgo.Dial(source.ServerName)\n\t\tsessionPool[key] = s\n\t}\n}\n\nfunc GetSession(dataSource string) *mgo.Session {\n\ts := sessionPool[dataSource]\n\treturn s.Clone()\n}\n\nfunc (conn *MgoConnection) Insert(d interface{}) ", "output": "{\n\tExecuteWithCollection(conn.Database, conn.Collection, func(c *mgo.Collection) error { return c.Insert(d) })\n}"} {"input": "package dhcpv6\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/u-root/uio/uio\"\n)\n\n\nfunc OptRelayPort(port uint16) Option {\n\treturn &optRelayPort{DownstreamSourcePort: port}\n}\n\ntype optRelayPort struct {\n\tDownstreamSourcePort uint16\n}\n\n\n\nfunc (op *optRelayPort) ToBytes() []byte {\n\tbuf := uio.NewBigEndianBuffer(nil)\n\tbuf.Write16(op.DownstreamSourcePort)\n\treturn buf.Data()\n}\n\nfunc (op *optRelayPort) String() string {\n\treturn fmt.Sprintf(\"RelayPort: %d\", op.DownstreamSourcePort)\n}\n\n\n\nfunc parseOptRelayPort(data []byte) (*optRelayPort, error) {\n\tvar opt optRelayPort\n\tbuf := uio.NewBigEndianBuffer(data)\n\topt.DownstreamSourcePort = buf.Read16()\n\treturn &opt, buf.FinError()\n}\n\nfunc (op *optRelayPort) Code() OptionCode ", "output": "{\n\treturn OptionRelayPort\n}"} {"input": "package timer\n\nimport (\n\t\"time\"\n)\n\ntype typeAction int\n\nconst (\n\tCLOSE typeAction = iota\n\tRESET\n\tFORCE\n)\n\n\n\ntype Timer struct {\n\tinterval time.Duration\n\tmsg, resp chan typeAction\n}\n\n\n\n\nfunc NewTimer(interval time.Duration) *Timer {\n\treturn &Timer{\n\t\tinterval: interval,\n\t\tmsg: make(chan typeAction, 1),\n\t\tresp: make(chan typeAction, 1),\n\t}\n}\n\n\n\n\nfunc (self *Timer) Next() bool {\n\tfor {\n\t\tvar ch <-chan time.Time\n\t\tif self.interval <= 0 {\n\t\t\tch = nil\n\t\t} else {\n\t\t\tch = time.After(self.interval)\n\t\t}\n\t\tselect {\n\t\tcase action := <-self.msg:\n\t\t\tswitch action {\n\t\t\tcase CLOSE:\n\t\t\t\tself.resp <- CLOSE\n\t\t\t\treturn false\n\t\t\tcase FORCE:\n\t\t\t\treturn true\n\t\t\t}\n\t\tcase <-ch:\n\t\t\treturn true\n\t\t}\n\t}\n\tpanic(\"unreachable\")\n}\n\n\n\nfunc (self *Timer) SetInterval(ns time.Duration) {\n\tself.interval = ns\n\tself.msg <- RESET\n}\n\n\n\nfunc (self *Timer) Trigger() {\n\tself.msg <- FORCE\n}\n\n\n\n\n\n\n\nfunc (self *Timer) Close() {\n\tself.msg <- CLOSE\n\t<-self.resp\n}\n\nfunc (self *Timer) TriggerAfter(ns time.Duration) ", "output": "{\n\tgo func() {\n\t\t<-time.After(ns)\n\t\tself.Trigger()\n\t}()\n}"} {"input": "package types\n\nimport (\n\t\"crypto/sha512\"\n\t\"fmt\"\n)\n\n\ntype Packet struct {\n\tDest NodeAddress\n\tAmt int64\n\tData []byte\n}\n\nfunc (p Packet) Destination() NodeAddress {\n\treturn p.Dest\n}\n\n\nfunc (p Packet) Hash() PacketHash {\n\to := sha512.Sum512([]byte(string(p.Dest) + string(p.Data)))\n\treturn PacketHash(string(o[0:sha512.Size]))\n}\n\n\n\nfunc (p Packet) String() string {\n\treturn fmt.Sprintf(\"{%x %v %q}\", p.Dest, p.Amt, p.Data)\n}\n\nfunc (p Packet) Amount() int64 ", "output": "{\n\treturn p.Amt\n}"} {"input": "package main\n\nimport (\n \"database/sql\"\n \"fmt\"\n \"github.com/gorilla/mux\"\n _ \"github.com/go-sql-driver/mysql\"\n \"log\"\n \"net/http\"\n)\n\nvar db *sql.DB \n\nfunc main() {\n fmt.Println(\"starting up\")\n\n var err error\n db, err = sql.Open(\"mysql\", \"root:root@tcp([127.0.0.1]:3306)/dbapi\") \n if err != nil {\n log.Fatalf(\"Error on initializing database connection: %s\", err.Error())\n }\n\n db.SetMaxIdleConns(100)\n\n err = db.Ping() \n if err != nil {\n log.Fatalf(\"Error on opening database connection: %s\", err.Error())\n }\n\n r := mux.NewRouter()\n r.HandleFunc(\"/\", HomeHandler)\n\n http.Handle(\"/\", r)\n http.ListenAndServe(\":8080\", nil)\n}\n\n\n\nfunc HomeHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n var msg string\n err := db.QueryRow(\"SELECT * FROM car WHERE id=?\", \"1\").Scan(&msg)\n if err != nil {\n fmt.Fprintf(w, \"Database Error!\")\n } else {\n fmt.Fprintf(w, msg)\n }\n}"} {"input": "package repositories\n\n\n\n\nimport (\n\t\"net/http\"\n\n\tmiddleware \"github.com/go-openapi/runtime/middleware\"\n)\n\n\ntype GetOwnerRepositoriesHandlerFunc func(GetOwnerRepositoriesParams) middleware.Responder\n\n\nfunc (fn GetOwnerRepositoriesHandlerFunc) Handle(params GetOwnerRepositoriesParams) middleware.Responder {\n\treturn fn(params)\n}\n\n\ntype GetOwnerRepositoriesHandler interface {\n\tHandle(GetOwnerRepositoriesParams) middleware.Responder\n}\n\n\n\n\n\ntype GetOwnerRepositories struct {\n\tContext *middleware.Context\n\tHandler GetOwnerRepositoriesHandler\n}\n\nfunc (o *GetOwnerRepositories) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\tr = rCtx\n\t}\n\tvar Params = NewGetOwnerRepositoriesParams()\n\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params) \n\n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}\n\nfunc NewGetOwnerRepositories(ctx *middleware.Context, handler GetOwnerRepositoriesHandler) *GetOwnerRepositories ", "output": "{\n\treturn &GetOwnerRepositories{Context: ctx, Handler: handler}\n}"} {"input": "package data\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"testing\"\n)\n\n\n\nfunc TestMsg(t *testing.T) {\n\tmsg := new(Message)\n\tjson.Unmarshal([]byte(`{\n\t\"msg_type\": \"msg_type\",\n\t\"msg\": \"msg\",\n\t\"from_user_id\": \"from_user_id\",\n\t\"to_user_id\": \"to_user_id\",\n\t\"from_conn_id\": \"from_conn_id\",\n\t\"to_conn_id\": \"to_conn_id\"\n}`), msg)\n\tt.Log(msg)\n}\n\nfunc TestBytesInt32Convert(t *testing.T) ", "output": "{\n\tvar i32 int32\n\ti32 = 11\n\tt.Log(i32)\n\tbs := Int32ToBytes(i32)\n\tt.Log(bs)\n\tt.Log(len(bs))\n\tt.Log(cap(bs))\n\tbuff := bytes.NewBuffer(bs)\n\tt.Log(buff.Bytes())\n\tinew := BytesToInt32(bs)\n\tt.Log(inew)\n\tif i32 == inew {\n\t\tt.Log(i32 == inew)\n\t} else {\n\t\tt.Fail()\n\t}\n}"} {"input": "package parser\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestValidPodFromSentinelConfig(t *testing.T) {\n\t_, err := ParseSentinelConfig(\"sentinel.conf\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n}\n\nfunc TestBadDirectives(t *testing.T) {\n\tsconf, err := ParseSentinelConfig(\"sentinel.conf\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n\tif len(sconf.BadDirectives) == 0 {\n\t\tt.Error(fmt.Errorf(\"Should have had bad directives, had none.\"))\n\t\tt.Fail()\n\t}\n}\n\nfunc TestGetPod(t *testing.T) {\n\tsconf, err := ParseSentinelConfig(\"sentinel.conf\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n\tpod, err := sconf.GetPod(\"pod1\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n\tif pod.Name != \"pod1\" {\n\t\tt.Error(fmt.Errorf(\"retreived pod is not named 'pod1'\"))\n\t\tt.Fail()\n\t}\n}\nfunc TestPodKnownSlaves(t *testing.T) {\n\tsconf, err := ParseSentinelConfig(\"sentinel.conf\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n\tpod, err := sconf.GetPod(\"pod1\")\n\tif len(pod.KnownSlaves) != 2 {\n\t\tt.Error(fmt.Errorf(\"Mismatched KnownSlaves. Expected 2, got %d\", len(pod.KnownSlaves)))\n\t\tt.Fail()\n\t}\n}\n\n\nfunc TestPodKnownSentinels(t *testing.T) ", "output": "{\n\tsconf, err := ParseSentinelConfig(\"sentinel.conf\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\tt.Fail()\n\t}\n\tpod, err := sconf.GetPod(\"pod1\")\n\tif len(pod.KnownSentinels) != 2 {\n\t\tt.Error(fmt.Errorf(\"Mismatched KnownSentinels. Expected 2, got %d\", len(pod.KnownSentinels)))\n\t\tfmt.Printf(\"pod: %+v\\n\", pod)\n\t\tt.Fail()\n\t}\n}"} {"input": "package shell\n\nimport (\n\tgoerrors \"errors\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/gruntwork-io/terragrunt/options\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestExitCodeWindows(t *testing.T) {\n\tt.Parallel()\n\n\tfor i := 0; i <= 255; i++ {\n\t\tcmd := exec.Command(`..\\testdata\\test_exit_code.bat`, strconv.Itoa(i))\n\t\terr := cmd.Run()\n\n\t\tif i == 0 {\n\t\t\tassert.Nil(t, err)\n\t\t} else {\n\t\t\tassert.Error(t, err)\n\t\t}\n\t\tretCode, err := GetExitCode(err)\n\t\tassert.Nil(t, err)\n\t\tassert.Equal(t, i, retCode)\n\t}\n\n\terr := goerrors.New(\"This is an explicit error\")\n\tretCode, retErr := GetExitCode(err)\n\tassert.Error(t, retErr, \"An error was expected\")\n\tassert.Equal(t, err, retErr)\n\tassert.Equal(t, 0, retCode)\n}\n\n\n\nfunc TestNewSignalsForwarderWaitWindows(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\texpectedWait := 5\n\n\tterragruntOptions, err := options.NewTerragruntOptionsForTest(\"\")\n\tassert.Nil(t, err, \"Unexpected error creating NewTerragruntOptionsForTest: %v\", err)\n\n\tcmd := exec.Command(`..\\testdata\\test_sigint_wait.bat`, strconv.Itoa(expectedWait))\n\n\tcmdChannel := make(chan error)\n\trunChannel := make(chan error)\n\n\tsignalChannel := NewSignalsForwarder(forwardSignals, cmd, terragruntOptions.Logger, cmdChannel)\n\tdefer signalChannel.Close()\n\n\tgo func() {\n\t\trunChannel <- cmd.Run()\n\t}()\n\n\ttime.Sleep(1000 * time.Millisecond)\n\tcmd.Process.Signal(os.Kill)\n\terr := <-runChannel\n\tcmdChannel <- err\n\tassert.Error(t, err)\n\n}"} {"input": "package client\n\nimport (\n\tatlantis \"atlantis/common\"\n\t. \"atlantis/manager/constant\"\n)\n\ntype ManagerRPCClient struct {\n\tatlantis.RPCClient\n\tUser string\n\tSecrets map[string]string\n}\n\ntype AuthedArg interface {\n\tSetCredentials(string, string)\n}\n\nfunc (r *ManagerRPCClient) CallAuthed(name string, arg AuthedArg, reply interface{}) error {\n\treturn r.CallAuthedMulti(name, arg, 0, reply)\n}\n\nfunc (r *ManagerRPCClient) CallAuthedMulti(name string, arg AuthedArg, region int, reply interface{}) error {\n\targ.SetCredentials(r.User, r.Secrets[r.Opts[region].RPCHostAndPort()])\n\n\treturn r.RPCClient.CallMulti(name, arg, region, reply)\n}\n\n\n\nfunc NewManagerRPCClientWithConfig(cfg []atlantis.RPCServerOpts) *atlantis.RPCClient {\n\treturn atlantis.NewMultiRPCClientWithConfig(cfg, \"ManagerRPC\", ManagerRPCVersion, true)\n}\n\nfunc NewManagerRPCClient(hostAndPort string) *atlantis.RPCClient ", "output": "{\n\treturn atlantis.NewRPCClient(hostAndPort, \"ManagerRPC\", ManagerRPCVersion, true)\n}"} {"input": "package main\n\n\ntype I interface { F() int }\n\n\ntype S struct { }\nfunc (s *S) F() int { return 1 }\n\n\n\n\n\n\n\n\nfunc Use(x I) {\n\tx.F()\n}\n\nfunc main() {\n\ti := NewI(0);\n\tUse(i);\n\n\tUse(NewI(0));\n}\n\nfunc NewI(i int) I ", "output": "{\n\treturn new(S)\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSAmazonMQConfiguration_TagsEntry struct {\n\n\tKey string `json:\"Key,omitempty\"`\n\n\tValue string `json:\"Value,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) AWSCloudFormationType() string {\n\treturn \"AWS::AmazonMQ::Configuration.TagsEntry\"\n}\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\n\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) SetDependsOn(dependencies []string) ", "output": "{\n\tr._dependsOn = dependencies\n}"} {"input": "package timeseriesinsights\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) BaseClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package scanner\n\nimport (\n\t\"github.com/mdhender/yawip/adoc/node\"\n)\n\n\n\n\nfunc (s *Scanner) DocumentSubtitle() *node.Node ", "output": "{\n\tpos, r := s.Position(), s.nextRune()\n\tif r != ':' {\n\t\ts.SetPosition(pos)\n\t\treturn nil\n\t}\n\tif !s.skipSpaces() {\n\t\ts.SetPosition(pos)\n\t\treturn nil\n\t}\n\ttitle := s.Position()\n\tif !s.skipWords() {\n\t\ts.SetPosition(pos)\n\t\treturn nil\n\t}\n\tspace := s.Position()\n\ts.skipSpaces()\n\treturn &node.Node{\n\t\tLine: pos.line,\n\t\tColumn: pos.column,\n\t\tKind: node.DOCUMENTSUBTITLE,\n\t\tValue: s.input[title.offset:space.offset],\n\t}\n}"} {"input": "package openssl\n\nimport (\n\t\"net/http\"\n)\n\n\n\nfunc ListenAndServeTLS(addr string, cert_file string, key_file string,\n\thandler http.Handler) error {\n\treturn ServerListenAndServeTLS(\n\t\t&http.Server{Addr: addr, Handler: handler}, cert_file, key_file)\n}\n\n\n\n\n\nfunc ServerListenAndServeTLS(srv *http.Server,\n\tcert_file, key_file string) error ", "output": "{\n\taddr := srv.Addr\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tctx, err := NewCtxFromFiles(cert_file, key_file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tl, err := Listen(\"tcp\", addr, ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn srv.Serve(l)\n}"} {"input": "package packets\n\nimport (\n\t\"io\"\n)\n\ntype PubackMessage struct {\n\tHeader\n\tTopicId uint16\n\tMessageId uint16\n\tReturnCode byte\n}\n\nfunc (p *PubackMessage) MessageType() byte {\n\treturn PUBACK\n}\n\n\n\nfunc (p *PubackMessage) Unpack(b io.Reader) {\n\tp.TopicId = readUint16(b)\n\tp.MessageId = readUint16(b)\n\tp.ReturnCode = readByte(b)\n}\n\nfunc (p *PubackMessage) Write(w io.Writer) error ", "output": "{\n\tpacket := p.Header.pack()\n\tpacket.WriteByte(PUBACK)\n\tpacket.Write(encodeUint16(p.TopicId))\n\tpacket.Write(encodeUint16(p.MessageId))\n\tpacket.WriteByte(p.ReturnCode)\n\t_, err := packet.WriteTo(w)\n\n\treturn err\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\ntype CreateEnvironmentRequest struct {\n\n\tInstanceGroup *InstanceGroup `json:\"instanceGroup\"`\n\n\tName *string `json:\"name\"`\n\n\tTaskDefinition *string `json:\"taskDefinition\"`\n}\n\n\n\n\nfunc (m *CreateEnvironmentRequest) validateInstanceGroup(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"instanceGroup\", \"body\", m.InstanceGroup); err != nil {\n\t\treturn err\n\t}\n\n\tif m.InstanceGroup != nil {\n\n\t\tif err := m.InstanceGroup.Validate(formats); err != nil {\n\t\t\tif ve, ok := err.(*errors.Validation); ok {\n\t\t\t\treturn ve.ValidateName(\"instanceGroup\")\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (m *CreateEnvironmentRequest) validateName(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"name\", \"body\", m.Name); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validate.Pattern(\"name\", \"body\", string(*m.Name), `^[a-zA-Z0-9-_]{1,30}$`); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *CreateEnvironmentRequest) validateTaskDefinition(formats strfmt.Registry) error {\n\n\tif err := validate.Required(\"taskDefinition\", \"body\", m.TaskDefinition); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *CreateEnvironmentRequest) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateInstanceGroup(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTaskDefinition(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package fakes\n\nimport (\n\tbiblobstore \"github.com/cloudfoundry/bosh-cli/blobstore\"\n)\n\ntype FakeBlobstoreFactory struct {\n\tCreateBlobstoreURL string\n\tCreateBlobstore biblobstore.Blobstore\n\tCreateErr error\n}\n\n\n\nfunc (f *FakeBlobstoreFactory) Create(blobstoreURL string) (biblobstore.Blobstore, error) {\n\tf.CreateBlobstoreURL = blobstoreURL\n\treturn f.CreateBlobstore, f.CreateErr\n}\n\nfunc NewFakeBlobstoreFactory() *FakeBlobstoreFactory ", "output": "{\n\treturn &FakeBlobstoreFactory{}\n}"} {"input": "package cloudstorage\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n)\n\ntype MockStorage struct {\n\tPutRequest *http.Request\n\tGetURL *url.URL\n\tOriginallySigned bool\n\tListObjectsResponse *ListObjectsResponse\n}\n\nvar _ Storage = &MockStorage{}\n\nfunc (s *MockStorage) PresignPutObject(name string, accessType AccessType, header http.Header) (*http.Request, error) {\n\treturn s.PutRequest, nil\n}\n\n\n\nfunc (s *MockStorage) PresignHeadObject(name string) (*url.URL, error) {\n\treturn s.GetURL, nil\n}\n\nfunc (s *MockStorage) RewriteGetURL(u *url.URL, name string) (*url.URL, bool, error) {\n\treturn s.GetURL, s.OriginallySigned, nil\n}\n\nfunc (s *MockStorage) ListObjects(r *ListObjectsRequest) (*ListObjectsResponse, error) {\n\treturn s.ListObjectsResponse, nil\n}\n\nfunc (s *MockStorage) DeleteObject(name string) error {\n\treturn nil\n}\n\nfunc (s *MockStorage) AccessType(header http.Header) AccessType {\n\treturn AccessTypeDefault\n}\n\nfunc (s *MockStorage) StandardToProprietary(header http.Header) http.Header {\n\treturn header\n}\n\nfunc (s *MockStorage) ProprietaryToStandard(header http.Header) http.Header {\n\treturn header\n}\n\nfunc (s *MockStorage) PresignGetObject(name string) (*url.URL, error) ", "output": "{\n\treturn s.GetURL, nil\n}"} {"input": "package proc\n\nconst (\n\tUPTIME_FORMAT = \"%f %f\\n\"\n\tUPTIME_FILE = \"/proc/uptime\"\n)\n\ntype Uptime struct {\n\tUp float64\n\tIdle float64\n}\n\n\n\nfunc UpTime() float64 {\n\tu := Uptime{}\n\terr := u.Get()\n\tif err != nil {\n\t\treturn float64(0)\n\t}\n\treturn u.Up\n}\n\nfunc (u *Uptime) Get() error ", "output": "{\n\tn, err := getvalues(UPTIME_FILE, UPTIME_FORMAT,\n\t\t&u.Up,\n\t\t&u.Idle)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n == 0 {\n\t\treturn ErrEmpty\n\t}\n\treturn nil\n}"} {"input": "package bot\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"sync\"\n)\n\ntype WhiteList struct {\n\tpath string\n\tnames map[string]struct{}\n\tlock sync.Mutex\n}\n\nfunc LoadWhiteList(path string) (*WhiteList, error) {\n\tfile, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to open file %s: %v\", path, err)\n\t}\n\tdefer file.Close()\n\n\tlist := make(map[string]struct{})\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tlist[scanner.Text()] = struct{}{}\n\t}\n\n\terr = scanner.Err()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinstance := &WhiteList{\n\t\tpath: path,\n\t\tnames: list,\n\t}\n\n\treturn instance, nil\n}\n\nfunc (whitelist *WhiteList) Write() error {\n\twhitelist.lock.Lock()\n\tdefer whitelist.lock.Unlock()\n\n\treturn whitelist.write()\n}\n\n\n\nfunc (whitelist *WhiteList) Add(name string) error {\n\twhitelist.lock.Lock()\n\tdefer whitelist.lock.Unlock()\n\n\twhitelist.names[name] = struct{}{}\n\n\treturn whitelist.write()\n}\n\nfunc (whitelist *WhiteList) Contains(name string) bool {\n\t_, exists := whitelist.names[name]\n\n\treturn exists\n}\n\nfunc (whitelist *WhiteList) Remove(name string) error {\n\twhitelist.lock.Lock()\n\tdefer whitelist.lock.Unlock()\n\n\t_, exists := whitelist.names[name]\n\n\tif !exists {\n\t\treturn nil\n\t}\n\n\tdelete(whitelist.names, name)\n\n\treturn whitelist.write()\n}\n\nfunc (whitelist *WhiteList) write() error ", "output": "{\n\tfile, err := os.Create(whitelist.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tw := bufio.NewWriter(file)\n\tfor line := range whitelist.names {\n\t\t_, err = fmt.Fprintln(w, line)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr = w.Flush()\n\treturn err\n}"} {"input": "package path\n\nimport (\n\t\"testing\"\n\n\t\"github.com/caixw/gitype/vars\"\n\t\"github.com/issue9/assert\"\n)\n\n\n\nfunc TestPath(t *testing.T) ", "output": "{\n\ta := assert.New(t)\n\n\tp := New(\"/\")\n\ta.Equal(p.ConfDir, \"/\"+vars.ConfFolderName)\n\n\ta.Equal(p.ThemesPath(\"def\", \"//style\", \"style.png\"), \"/data/themes/def/style/style.png\")\n\ta.Equal(p.ThemesPath(\"def\", \"//style//style.png\"), \"/data/themes/def/style/style.png\")\n\ta.Equal(p.ThemesPath(\"def\", \"//style//*.html\"), \"/data/themes/def/style/*.html\")\n}"} {"input": "package main\n\n\n\n\n\ntype I interface {\n\tone() int\n\ttwo() string\n}\n\ntype S struct {\n\tI\n}\n\ntype impl struct{}\n\n\n\nfunc (impl) two() string {\n\treturn \"two\"\n}\n\nfunc main() {\n\tvar s S\n\ts.I = impl{}\n\tif one := s.I.one(); one != 1 {\n\t\tpanic(one)\n\t}\n\tif one := s.one(); one != 1 {\n\t\tpanic(one)\n\t}\n\tclosOne := s.I.one\n\tif one := closOne(); one != 1 {\n\t\tpanic(one)\n\t}\n\tclosOne = s.one\n\tif one := closOne(); one != 1 {\n\t\tpanic(one)\n\t}\n\n\tif two := s.I.two(); two != \"two\" {\n\t\tpanic(two)\n\t}\n\tif two := s.two(); two != \"two\" {\n\t\tpanic(two)\n\t}\n\tclosTwo := s.I.two\n\tif two := closTwo(); two != \"two\" {\n\t\tpanic(two)\n\t}\n\tclosTwo = s.two\n\tif two := closTwo(); two != \"two\" {\n\t\tpanic(two)\n\t}\n}\n\nfunc (impl) one() int ", "output": "{\n\treturn 1\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar x Animal = Dog{\"Rosie\"}\n\n\tif x, ok := x.(Human); ok {\n\t\tfmt.Println(x.lastName, \"doesn't want to be treated like dogs and cats.\")\n\t} else {\n\t\tfmt.Println(x.Say())\n\t}\n}\n\ntype Animal interface {\n\tSay() string\n}\n\ntype Dog struct {\n\tname string\n}\n\nfunc (d Dog) Say() string {\n\treturn fmt.Sprintf(\"%v barks\", d.name)\n}\n\ntype Cat struct {\n\tname string\n}\n\nfunc (c Cat) Say() string {\n\treturn fmt.Sprintf(\"%v meows\", c.name)\n}\n\ntype Human struct {\n\tfirstName string\n\tlastName string\n}\n\n\n\n\nfunc (h Human) Say() string ", "output": "{\n\treturn fmt.Sprintf(\"%v %v speaks\", h.firstName, h.lastName)\n}"} {"input": "package arm\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"encoding/base64\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\t\"golang.org/x/crypto/ssh\"\n\t\"time\"\n)\n\nconst (\n\tKeySize = 2048\n)\n\ntype OpenSshKeyPair struct {\n\tprivateKey *rsa.PrivateKey\n\tpublicKey ssh.PublicKey\n}\n\nfunc NewOpenSshKeyPair() (*OpenSshKeyPair, error) {\n\treturn NewOpenSshKeyPairWithSize(KeySize)\n}\n\nfunc NewOpenSshKeyPairWithSize(keySize int) (*OpenSshKeyPair, error) {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, keySize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpublicKey, err := ssh.NewPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &OpenSshKeyPair{\n\t\tprivateKey: privateKey,\n\t\tpublicKey: publicKey,\n\t}, nil\n}\n\nfunc (s *OpenSshKeyPair) AuthorizedKey() string {\n\treturn fmt.Sprintf(\"%s %s packer Azure Deployment%s\",\n\t\ts.publicKey.Type(),\n\t\tbase64.StdEncoding.EncodeToString(s.publicKey.Marshal()),\n\t\ttime.Now().Format(time.RFC3339))\n}\n\n\n\nfunc (s *OpenSshKeyPair) PrivateKey() string ", "output": "{\n\tprivateKey := string(pem.EncodeToMemory(&pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(s.privateKey),\n\t}))\n\n\treturn privateKey\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateNatGatewayRequest struct {\n\n\tCreateNatGatewayDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request CreateNatGatewayRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CreateNatGatewayRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CreateNatGatewayRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateNatGatewayResponse struct {\n\n\tRawResponse *http.Response\n\n\tNatGateway `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateNatGatewayResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateNatGatewayResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateNatGatewayRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package ttnsvg\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n)\n\ntype svgHandler struct {\n\tsvgSrc []byte\n\tregReq regexp.Regexp\n\tregSVG regexp.Regexp\n}\n\nfunc (h *svgHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Add(\"Content-Type\", \"image/svg+xml\")\n\tw.WriteHeader(http.StatusOK)\n\n\tcity := h.regReq.FindSubmatch([]byte(r.URL.Path))\n\n\tif city == nil {\n\t\tw.Write(h.regSVG.ReplaceAll(h.svgSrc, *new([]byte)))\n\t\treturn\n\t}\n\n\tw.Write(h.regSVG.ReplaceAll(h.svgSrc, city[1]))\n}\n\n\n\nfunc init() ", "output": "{\n\tsvgSrc, err := ioutil.ReadFile(\"ttn_logo.svg\")\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\treturn\n\t}\n\n\thttp.Handle(\"/\", &svgHandler{\n\t\t[]byte(svgSrc),\n\t\t*regexp.MustCompile(\"^/([\\\\s\\\\p{L}]+)/?$\"),\n\t\t*regexp.MustCompile(\"(@city@)\"),\n\t})\n}"} {"input": "package gospell\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\ntype Match struct {\n\tWord []rune\n\tDistance int\n\tWeight int\n}\n\ntype Matches []Match\n\nfunc (m1 Match) Equal(m2 Match) bool {\n\treturn string(m1.Word) == string(m2.Word) &&\n\t\tm1.Distance == m2.Distance && m1.Weight == m2.Weight\n}\n\n\n\nfunc (s Matches) Len() int { return len(s) }\nfunc (s Matches) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\n\nfunc (s Matches) Strings() []string {\n\tstrings := make([]string, len(s))\n\tsort.Sort(ByDistance{s})\n\tfor i, r := range s {\n\t\tstrings[i] = string(r.Word)\n\t}\n\n\treturn strings\n}\n\ntype ByDistance struct {\n\tMatches\n}\n\nfunc (s ByDistance) Less(i, j int) bool {\n\td1 := s.Matches[i].Distance\n\td2 := s.Matches[j].Distance\n\tif d1 == d2 {\n\t\treturn string(s.Matches[i].Word) < string(s.Matches[j].Word)\n\t}\n\treturn d1 < d2\n}\n\nfunc (m *Match) update(r rune, distance, weight int) Match {\n\tm2 := Match{}\n\tif r != 0 {\n\t\tm2.Word = []rune{r}\n\t\tm2.Word = append(m2.Word, m.Word...)\n\t} else {\n\t\tm2.Word = m.Word[:]\n\t}\n\tm2.Distance = m.Distance + distance\n\tm2.Weight = m.Weight + weight\n\treturn m2\n}\n\nfunc (m Match) String() string ", "output": "{\n\treturn fmt.Sprintf(\"{%v %d %d}\", string(m.Word), m.Distance, m.Weight)\n}"} {"input": "package wrapstesting\n\nimport (\n\t\"net/http\"\n\n\t\"gopkg.in/go-on/wrap.v2\"\n)\n\ntype (\n\tdefer_ struct{ http.Handler }\n)\n\nfunc (ø defer_) Wrap(in http.Handler) (out http.Handler) {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() { ø.ServeHTTP(w, r) }()\n\t\tin.ServeHTTP(w, r)\n\t})\n}\n\nfunc DeferFunc(fn func(http.ResponseWriter, *http.Request)) wrap.Wrapper {\n\treturn defer_{http.HandlerFunc(fn)}\n}\n\n\n\nfunc Defer(h http.Handler) wrap.Wrapper ", "output": "{\n\treturn defer_{h}\n}"} {"input": "package iso20022\n\n\ntype AmountAndDirection55 struct {\n\n\tAmount *RestrictedFINActiveOrHistoricCurrencyAndAmount `xml:\"Amt\"`\n\n\tCreditDebitIndicator *CreditDebitCode `xml:\"CdtDbtInd,omitempty\"`\n\n\tOriginalCurrencyAndOrderedAmount *RestrictedFINActiveOrHistoricCurrencyAndAmount `xml:\"OrgnlCcyAndOrdrdAmt,omitempty\"`\n\n\tForeignExchangeDetails *ForeignExchangeTerms23 `xml:\"FXDtls,omitempty\"`\n}\n\n\n\nfunc (a *AmountAndDirection55) SetCreditDebitIndicator(value string) {\n\ta.CreditDebitIndicator = (*CreditDebitCode)(&value)\n}\n\nfunc (a *AmountAndDirection55) SetOriginalCurrencyAndOrderedAmount(value, currency string) {\n\ta.OriginalCurrencyAndOrderedAmount = NewRestrictedFINActiveOrHistoricCurrencyAndAmount(value, currency)\n}\n\nfunc (a *AmountAndDirection55) AddForeignExchangeDetails() *ForeignExchangeTerms23 {\n\ta.ForeignExchangeDetails = new(ForeignExchangeTerms23)\n\treturn a.ForeignExchangeDetails\n}\n\nfunc (a *AmountAndDirection55) SetAmount(value, currency string) ", "output": "{\n\ta.Amount = NewRestrictedFINActiveOrHistoricCurrencyAndAmount(value, currency)\n}"} {"input": "package automation\n\nimport (\n\tautomationpb \"github.com/youtube/vitess/go/vt/proto/automation\"\n\t\"github.com/youtube/vitess/go/vt/topo/topoproto\"\n\t\"golang.org/x/net/context\"\n)\n\n\ntype SplitDiffTask struct {\n}\n\n\nfunc (t *SplitDiffTask) Run(parameters map[string]string) ([]*automationpb.TaskContainer, string, error) {\n\targs := []string{\"SplitDiff\"}\n\tif excludeTables := parameters[\"exclude_tables\"]; excludeTables != \"\" {\n\t\targs = append(args, \"--exclude_tables=\"+excludeTables)\n\t}\n\tif minHealthyRdonlyTablets := parameters[\"min_healthy_rdonly_tablets\"]; minHealthyRdonlyTablets != \"\" {\n\t\targs = append(args, \"--min_healthy_rdonly_tablets=\"+minHealthyRdonlyTablets)\n\t}\n\targs = append(args, topoproto.KeyspaceShardString(parameters[\"keyspace\"], parameters[\"dest_shard\"]))\n\toutput, err := ExecuteVtworker(context.TODO(), parameters[\"vtworker_endpoint\"], args)\n\n\tif err == nil {\n\t\tExecuteVtworker(context.TODO(), parameters[\"vtworker_endpoint\"], []string{\"Reset\"})\n\t}\n\treturn nil, output, err\n}\n\n\nfunc (t *SplitDiffTask) RequiredParameters() []string {\n\treturn []string{\"keyspace\", \"dest_shard\", \"vtworker_endpoint\"}\n}\n\n\n\n\nfunc (t *SplitDiffTask) OptionalParameters() []string ", "output": "{\n\treturn []string{\"exclude_tables\", \"min_healthy_rdonly_tablets\"}\n}"} {"input": "package app\n\nimport (\n\t\"fmt\"\n\t\"github.com/jsix/gof\"\n\t\"go2o/src/core\"\n\t\"go2o/src/core/infrastructure\"\n\t\"go2o/src/core/service\"\n\t\"os\"\n\t\"strconv\"\n)\n\n\n\nfunc RunSocket(ctx gof.App, port int, debug, trace bool) ", "output": "{\n\n\tif gcx, ok := ctx.(*core.MainApp); ok {\n\t\tif !gcx.Loaded {\n\t\t\tgcx.Init(debug, trace)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"app context err\")\n\t\tos.Exit(1)\n\t\treturn\n\t}\n\n\tif debug {\n\t\tfmt.Println(\"[Started]:Socket server (with debug) running on port [\" +\n\t\t\tstrconv.Itoa(port) + \"]:\")\n\t\tinfrastructure.DebugMode = true\n\t} else {\n\t\tfmt.Println(\"[Started]:Socket server running on port [\" +\n\t\t\tstrconv.Itoa(port) + \"]:\")\n\t}\n\tservice.ServerListen(\"tcp\", \":\"+strconv.Itoa(port), ctx)\n}"} {"input": "package file\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\n\n\ntype darwinExFileInfo struct {\n\tos.FileInfo\n\tfid FID\n\tpath string\n}\n\n\n\nfunc timespecToTime(ts syscall.Timespec) time.Time {\n\treturn time.Unix(int64(ts.Sec), int64(ts.Nsec))\n}\n\n\nfunc (fi *darwinExFileInfo) CTime() time.Time {\n\treturn timespecToTime(fi.Sys().(*syscall.Stat_t).Ctimespec)\n}\n\n\nfunc (fi *darwinExFileInfo) ATime() time.Time {\n\treturn timespecToTime(fi.Sys().(*syscall.Stat_t).Atimespec)\n}\n\n\nfunc (fi *darwinExFileInfo) FID() FID {\n\treturn fi.fid\n}\n\n\nfunc (fi *darwinExFileInfo) Path() string {\n\treturn fi.path\n}\n\n\n\n\nfunc systemExFileInfo(fi os.FileInfo, path string) *darwinExFileInfo ", "output": "{\n\tfid := FID{\n\t\tIDLow: fi.Sys().(*syscall.Stat_t).Ino,\n\t}\n\tabsolute, _ := filepath.Abs(path)\n\treturn &darwinExFileInfo{\n\t\tFileInfo: fi,\n\t\tfid: fid,\n\t\tpath: filepath.Clean(absolute),\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\n\t\"gopkg.in/stretchr/testify.v1/mock\"\n)\n\ntype Printer interface {\n\tHelp()\n\tVersion()\n\tMessage(msg string)\n\tError(err error)\n\tCommands()\n}\n\ntype TextPrinter struct {\n\tversion string\n}\n\nfunc NewTextPrinter(version string) *TextPrinter {\n\treturn &TextPrinter{version}\n}\n\nfunc (p *TextPrinter) Help() {\n\thelpText := `Name:\n\tfiz - a file wizard\n\nVersion:\n\t` + p.version + `\n\nUsage:\n\tfiz \n\n`\n\tp.Message(helpText)\n\tp.Commands()\n}\n\nfunc (p *TextPrinter) Version() {\n\tfmt.Println(\"fiz\", p.version)\n}\n\nfunc (p *TextPrinter) Message(msg string) {\n\tfmt.Print(msg)\n}\n\nfunc (p *TextPrinter) Error(err error) {\n\tfmt.Println(\"Error: \", err)\n}\n\nfunc (p *TextPrinter) Commands() {\n\tp.Message(COMMANDS_MSG)\n}\n\n\ntype MockPrinter struct {\n\tmock.Mock\n}\n\nfunc NewMockPrinter() *MockPrinter {\n\treturn &MockPrinter{}\n}\n\nfunc (m *MockPrinter) Help() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Version() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Message(msg string) {\n\tm.Called(msg)\n}\n\nfunc (m *MockPrinter) Error(err error) {\n\tm.Called(err)\n}\n\n\n\nfunc (m *MockPrinter) Commands() ", "output": "{\n\tm.Called()\n}"} {"input": "package elements\n\nimport \"github.com/fileformats/graphics/jt/model\"\n\n\n\n\ntype InfiniteLightAttribute struct {\n\tBaseLight\n\tVersionNumber uint8\n\tDirection model.Vector3D\n}\n\n\n\nfunc (n *InfiniteLightAttribute) Read(c *model.Context) error {\n\tc.LogGroup(\"InfiniteLightAttribute\")\n\tdefer c.LogGroupEnd()\n\n\tif err := (&n.BaseLight).Read(c); err != nil {\n\t\treturn err\n\t}\n\n\tif c.Version.Equal(model.V8) {\n\t\tc.Data.Unpack(&n.Direction)\n\t\tn.VersionNumber = uint8(c.Data.Int16())\n\n\t\tif n.VersionNumber == 1 {\n\t\t\tn.CoordSystem = c.Data.Int32()\n\t\t\tc.Log(\"CoordSystem: %d\", n.CoordSystem)\n\t\t}\n\t}\n\n\tif c.Version.Equal(model.V9) {\n\t\tn.VersionNumber = uint8(c.Data.Int16())\n\t\tc.Data.Unpack(&n.Direction)\n\n\t\tif n.VersionNumber == 2 {\n\t\t\tn.ShadowOpacity = c.Data.Float32()\n\t\t\tc.Log(\"ShadowOpacity: %f\", n.ShadowOpacity)\n\t\t}\n\t}\n\n\tif c.Version.GreaterEqThan(model.V10) {\n\t\tn.VersionNumber = c.Data.UInt8()\n\t\tc.Data.Unpack(&n.Direction)\n\t}\n\tc.Log(\"VersionNumber: %d\", n.VersionNumber)\n\tc.Log(\"Direction: %s\", n.Direction)\n\n\n\treturn c.Data.GetError()\n}\n\nfunc (n *InfiniteLightAttribute) GetBaseAttribute() *BaseAttribute {\n\treturn &n.BaseAttribute\n}\n\nfunc (n *InfiniteLightAttribute) BaseElement() *JTElement {\n\treturn &n.JTElement\n}\n\nfunc (n InfiniteLightAttribute) GUID() model.GUID ", "output": "{\n\treturn model.InfiniteLightAttributeElement\n}"} {"input": "package mypackage \n\n\n\ntype Simple interface {\n\nMymethod() string\n\n} \n\ntype Complex interface {\n\nMymethod() string\n\n}\n\ntype Mystruct struct {\n\nMyvar string\n\n}\n\n\n\nfunc (mystructvar *Mystruct)Mymethod() string ", "output": "{\n\n\nreturn mystructvar.Myvar\n\n\n}"} {"input": "package stores\n\nimport (\n\t\"HTVM/instructions/base\"\n\t\"HTVM/runtime\"\n)\n\n\ntype ASTORE struct {\n\tbase.Index8Instruction\n}\n\nfunc (self *ASTORE) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, self.Index)\n}\n\ntype ASTORE_0 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_0) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 0)\n}\n\ntype ASTORE_1 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_1) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 1)\n}\n\ntype ASTORE_2 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_2) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 2)\n}\n\ntype ASTORE_3 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_3) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 3)\n}\n\ntype ASTORE_4 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_4) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 4)\n}\n\n\n\nfunc _executeRef(frame *runtime.Frame, index uint) ", "output": "{\n\tval := frame.OperateStack().PopRef()\n\tframe.LocalVars().SetRef(index, val)\n}"} {"input": "package goleveldb\n\nimport (\n\tstore \"github.com/blevesearch/upsidedown_store_api\"\n\t\"github.com/syndtr/goleveldb/leveldb\"\n)\n\ntype Batch struct {\n\tstore *Store\n\tmerge *store.EmulatedMerge\n\tbatch *leveldb.Batch\n}\n\nfunc (b *Batch) Set(key, val []byte) {\n\tb.batch.Put(key, val)\n}\n\n\n\nfunc (b *Batch) Merge(key, val []byte) {\n\tb.merge.Merge(key, val)\n}\n\nfunc (b *Batch) Reset() {\n\tb.batch.Reset()\n\tb.merge = store.NewEmulatedMerge(b.store.mo)\n}\n\nfunc (b *Batch) Close() error {\n\tb.batch.Reset()\n\tb.batch = nil\n\tb.merge = nil\n\treturn nil\n}\n\nfunc (b *Batch) Delete(key []byte) ", "output": "{\n\tb.batch.Delete(key)\n}"} {"input": "package ast\n\nimport \"monkey/token\"\n\ntype StringLiteral struct {\n\tToken token.Token\n\tValue string\n}\n\nfunc (s *StringLiteral) expressionNode() {}\nfunc (s *StringLiteral) TokenLiteral() string { return s.Token.Literal }\nfunc (s *StringLiteral) String() string { return s.Token.Literal }\n\ntype InterpolatedString struct {\n\tToken token.Token\n\tValue string\n\tExprMap map[byte]Expression\n}\n\nfunc (is *InterpolatedString) expressionNode() {}\nfunc (is *InterpolatedString) TokenLiteral() string { return is.Token.Literal }\n\n\nfunc (is *InterpolatedString) String() string ", "output": "{ return is.Token.Literal }"} {"input": "package fake\n\nimport (\n\tcontext \"context\"\n\n\truntime \"k8s.io/apimachinery/pkg/runtime\"\n\trest \"k8s.io/client-go/rest\"\n\tfake \"knative.dev/eventing-prometheus/pkg/client/clientset/versioned/fake\"\n\tclient \"knative.dev/eventing-prometheus/pkg/client/injection/client\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Fake.RegisterClient(withClient)\n\tinjection.Fake.RegisterClientFetcher(func(ctx context.Context) interface{} {\n\t\treturn Get(ctx)\n\t})\n}\n\nfunc withClient(ctx context.Context, cfg *rest.Config) context.Context {\n\tctx, _ = With(ctx)\n\treturn ctx\n}\n\n\n\n\nfunc Get(ctx context.Context) *fake.Clientset {\n\tuntyped := ctx.Value(client.Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch knative.dev/eventing-prometheus/pkg/client/clientset/versioned/fake.Clientset from context.\")\n\t}\n\treturn untyped.(*fake.Clientset)\n}\n\nfunc With(ctx context.Context, objects ...runtime.Object) (context.Context, *fake.Clientset) ", "output": "{\n\tcs := fake.NewSimpleClientset(objects...)\n\treturn context.WithValue(ctx, client.Key{}, cs), cs\n}"} {"input": "package common\n\nimport (\n\t\"encoding/binary\"\n\t\"sort\"\n)\n\n\n\ntype Uint64Slice []uint64\n\nfunc (p Uint64Slice) Len() int { return len(p) }\nfunc (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] }\nfunc (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p Uint64Slice) Sort() { sort.Sort(p) }\n\nfunc SearchUint64s(a []uint64, x uint64) int {\n\treturn sort.Search(len(a), func(i int) bool { return a[i] >= x })\n}\n\nfunc (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) }\n\n\n\n\n\nfunc GetUint64LE(src []byte) uint64 {\n\treturn binary.LittleEndian.Uint64(src)\n}\n\nfunc PutUint64BE(dest []byte, i uint64) {\n\tbinary.BigEndian.PutUint64(dest, i)\n}\n\nfunc GetUint64BE(src []byte) uint64 {\n\treturn binary.BigEndian.Uint64(src)\n}\n\nfunc PutInt64LE(dest []byte, i int64) {\n\tbinary.LittleEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64LE(src []byte) int64 {\n\treturn int64(binary.LittleEndian.Uint64(src))\n}\n\nfunc PutInt64BE(dest []byte, i int64) {\n\tbinary.BigEndian.PutUint64(dest, uint64(i))\n}\n\nfunc GetInt64BE(src []byte) int64 {\n\treturn int64(binary.BigEndian.Uint64(src))\n}\n\nfunc PutUint64LE(dest []byte, i uint64) ", "output": "{\n\tbinary.LittleEndian.PutUint64(dest, i)\n}"} {"input": "package task\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"os/exec\"\n)\n\n\nfunc scanPipe(p io.ReadCloser, w WorkerLog) {\n\ts := bufio.NewScanner(p)\n\tfor s.Scan() {\n\t\tw.Add(s.Text())\n\t}\n}\n\n\n\n\nfunc Exec(w WorkerLog, wd string, cmd string, args ...string) error ", "output": "{\n\te := exec.Command(cmd, args...)\n\tif len(wd) != 0 {\n\t\te.Dir = wd + \"/\"\n\t}\n\n\tif stdout, err := e.StdoutPipe(); err != nil {\n\t\tw.AddError(err)\n\t\treturn err\n\t} else {\n\t\tgo scanPipe(stdout, w)\n\t}\n\n\tif stderr, err := e.StderrPipe(); err != nil {\n\t\tw.AddError(err)\n\t\treturn err\n\t} else {\n\t\tgo scanPipe(stderr, w)\n\t}\n\n\tif err := e.Run(); err != nil {\n\t\tw.AddError(err)\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package server\n\nimport \"context\"\n\n\n\nfunc apply(_ context.Context, _ *Config) error ", "output": "{\n\treturn nil\n}"} {"input": "package clock\n\nimport \"time\"\n\n\nvar Work Clock\n\n\n\n\nfunc Now() time.Time {\n\treturn Work.Now()\n}\n\nfunc Since(t time.Time) time.Duration {\n\treturn Work.Now().Sub(t)\n}\n\n\n\nfunc Sleep(d time.Duration) {\n\tWork.Sleep(d)\n}\n\n\n\nfunc After(d time.Duration) <-chan time.Time {\n\treturn Work.After(d)\n}\n\n\n\nfunc Tick(d time.Duration) <-chan time.Time {\n\treturn Work.Tick(d)\n}\n\n\n\n\n\nfunc Ticker(d time.Duration) *time.Ticker {\n\treturn Work.Ticker(d)\n}\n\n\ntype Clock interface {\n\n\tNow() time.Time\n\n\tSleep(d time.Duration)\n\n\tAfter(d time.Duration) <-chan time.Time\n\n\tTick(d time.Duration) <-chan time.Time\n\n\tTicker(d time.Duration) *time.Ticker\n\n}\n\n\ntype Mock interface {\n\tClock\n\n\n\tSet(t time.Time) Mock\n\n\tAdd(d time.Duration) Mock\n\n\tFreeze() Mock\n\n\tIsFrozen() bool\n\n\tUnfreeze() Mock\n\n\tClose()\n}\n\nfunc init() ", "output": "{\n\tWork = New()\n}"} {"input": "package bootstrapper\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"k8s.io/minikube/pkg/minikube/constants\"\n\t\"k8s.io/minikube/pkg/minikube/tests\"\n\t\"k8s.io/minikube/pkg/util\"\n)\n\n\n\nfunc TestSetupCerts(t *testing.T) ", "output": "{\n\ttempDir := tests.MakeTempDir()\n\tdefer os.RemoveAll(tempDir)\n\n\tf := NewFakeCommandRunner()\n\tk8s := KubernetesConfig{\n\t\tAPIServerName: constants.APIServerName,\n\t\tDNSDomain: constants.ClusterDNSDomain,\n\t\tServiceCIDR: util.DefaultServiceCIDR,\n\t}\n\n\tvar filesToBeTransferred []string\n\tfor _, cert := range certs {\n\t\tfilesToBeTransferred = append(filesToBeTransferred, filepath.Join(constants.GetMinipath(), cert))\n\t}\n\n\tif err := SetupCerts(f, k8s); err != nil {\n\t\tt.Fatalf(\"Error starting cluster: %s\", err)\n\t}\n\tfor _, cert := range filesToBeTransferred {\n\t\t_, err := f.GetFileToContents(cert)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Cert not generated: %s\", cert)\n\t\t}\n\t}\n}"} {"input": "package eureka\n\nimport (\n\t\"encoding/xml\"\n\t\"strings\"\n)\n\nfunc (c *Client) GetApplications() (*Applications, error) {\n\tresponse, err := c.Get(\"apps\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar applications *Applications = new(Applications)\n\terr = xml.Unmarshal(response.Body, applications)\n\treturn applications, err\n}\n\nfunc (c *Client) GetApplication(appId string) (*Application, error) {\n\tvalues := []string{\"apps\", appId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar application *Application = new(Application)\n\terr = xml.Unmarshal(response.Body, application)\n\treturn application, err\n}\n\nfunc (c *Client) GetInstance(appId, instanceId string) (*InstanceInfo, error) {\n\tvalues := []string{\"apps\", appId, instanceId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar instance *InstanceInfo = new(InstanceInfo)\n\terr = xml.Unmarshal(response.Body, instance)\n\treturn instance, err\n}\n\nfunc (c *Client) GetVIP(vipId string) (*Applications, error) {\n\tvalues := []string{\"vips\", vipId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar applications *Applications = new(Applications)\n\terr = xml.Unmarshal(response.Body, applications)\n\treturn applications, err\n}\n\n\n\nfunc (c *Client) GetSVIP(svipId string) (*Applications, error) ", "output": "{\n\tvalues := []string{\"svips\", svipId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar applications *Applications = new(Applications)\n\terr = xml.Unmarshal(response.Body, applications)\n\treturn applications, err\n}"} {"input": "package common\n\nimport (\n\t\"strconv\"\n\t\"time\"\n)\n\ntype ConversionResult struct {\n\tDateAsString string\n\tDateAsInt int\n\tDate time.Time\n}\n\nfunc ConvertIntToDisplay(dateAsInt int) string {\n\tdayAsString := strconv.Itoa(dateAsInt)\n\n\treturn dayAsString\n}\n\n\n\nfunc (d *ConversionResult) Tomorrow() (ConversionResult, error) {\n\treturn ConvertStringToDates(d.Date.AddDate(0, 0, 1).Format(\"20060102\"))\n}\n\nfunc (d *ConversionResult) Yesterday() (ConversionResult, error) {\n\treturn ConvertStringToDates(d.Date.AddDate(0, 0, -1).Format(\"20060102\"))\n}\n\nfunc ConvertStringToDates(dateAsString string) (ConversionResult, error) ", "output": "{\n\tresult := ConversionResult{}\n\tresult.DateAsString = dateAsString\n\n\tdateAsInt, err := strconv.Atoi(dateAsString)\n\tif err != nil {\n\t\treturn result, nil\n\t}\n\tresult.DateAsInt = dateAsInt\n\n\tdate, err := time.Parse(\"20060102\", dateAsString)\n\tif err != nil {\n\t\treturn result, nil\n\t}\n\tresult.Date = date\n\n\treturn result, nil\n}"} {"input": "package categories\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n)\n\n\n\nfunc (app *CategoriesApp) List(response http.ResponseWriter, request *http.Request) ", "output": "{\n\tresponse.Header().Set(\"Content-Type\", \"application/json\")\n\tconst query = `SELECT id, style, division from categories`\n\tselection, err := app.Access.Query(query)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tvar categories []Category\n\tfor selection.Next() {\n\t\tvar current Category = Category{}\n\t\terr = selection.Scan(¤t.ID, ¤t.Style, ¤t.Division)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tcategories = append(categories, current)\n\t}\n\tresult := Categories{Items: categories}\n\tjson.NewEncoder(response).Encode(result)\n}"} {"input": "package apb\n\nimport (\n\t\"testing\"\n\n\tft \"github.com/openshift/ansible-service-broker/pkg/fusortest\"\n)\n\nfunc TestCreateExtraVarsNilParametersRef(t *testing.T) {\n\tcontext := &Context{Platform: \"kubernetes\", Namespace: \"testing-project\"}\n\n\tt.Log(\"calling createExtraVars\")\n\tvalue, err := createExtraVars(context, nil)\n\tif err != nil {\n\t\tt.Log(\"we have an error\")\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(value)\n\texpected := \"{\\\"namespace\\\":\\\"testing-project\\\"}\"\n\tft.AssertEqual(t, value, expected, \"invalid value on nil parameters ref\")\n}\n\nfunc TestCreateExtraVarsNilParameters(t *testing.T) {\n\tcontext := Context{Platform: \"kubernetes\", Namespace: \"testing-project\"}\n\tparameters := Parameters(nil)\n\n\tt.Log(\"calling createExtraVars\")\n\tvalue, err := createExtraVars(&context, ¶meters)\n\tif err != nil {\n\t\tt.Log(\"we have an error\")\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(value)\n\texpected := \"{\\\"namespace\\\":\\\"testing-project\\\"}\"\n\tft.AssertEqual(t, value, expected, \"invalid value on nil parameters\")\n}\n\n\n\nfunc TestCreateExtraVars(t *testing.T) {\n\tcontext := &Context{Platform: \"kubernetes\", Namespace: \"testing-project\"}\n\tparameters := &Parameters{\"key\": \"param\"}\n\tvalue, err := createExtraVars(context, parameters)\n\tif err != nil {\n\t\tt.Log(\"we have an error\")\n\t\tt.Fatal(err)\n\t}\n\n\texpected := \"{\\\"key\\\":\\\"param\\\",\\\"namespace\\\":\\\"testing-project\\\"}\"\n\tft.AssertEqual(t, value, expected, \"extravars do not match\")\n}\n\nfunc TestCreateExtraVarsNilContextRef(t *testing.T) ", "output": "{\n\tparameters := &Parameters{\"key\": \"param\"}\n\n\tt.Log(\"calling createExtraVars\")\n\tvalue, err := createExtraVars(nil, parameters)\n\tif err != nil {\n\t\tt.Log(\"we have an error\")\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(value)\n\texpected := \"{\\\"key\\\":\\\"param\\\"}\"\n\tft.AssertEqual(t, value, expected, \"invalid value on empty context\")\n}"} {"input": "package arimocks\n\nimport (\n\tari \"github.com/CyCoreSystems/ari/v5\"\n\tmock \"github.com/stretchr/testify/mock\"\n)\n\n\ntype Matcher struct {\n\tmock.Mock\n}\n\n\n\n\nfunc (_m *Matcher) Match(o *ari.Key) bool ", "output": "{\n\tret := _m.Called(o)\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func(*ari.Key) bool); ok {\n\t\tr0 = rf(o)\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\treturn r0\n}"} {"input": "package challenge25\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"github.com/stripedpajamas/cryptopals/set3/challenge18\"\n)\n\nvar globalPlaintext []byte\n\nfunc init() {\n\tvar err error\n\tglobalPlaintext, err = ioutil.ReadFile(\"25_decoded.txt\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc TestEncryptSecretWithCTR(t *testing.T) {\n\tenc := EncryptSecretWithCTR(globalPlaintext)\n\tdec := challenge18.CTR(enc, globalKey, globalNonce)\n\n\tif !bytes.Equal(dec, globalPlaintext) {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestEdit(t *testing.T) {\n\tinput := []byte(\"HELLO POTATO FACE\")\n\tkey := []byte(\"YELLOW SUBMARINE\")\n\tnonce := []byte{0, 0, 0, 0, 0, 0, 0, 0}\n\tenc := challenge18.CTR(input, key, nonce)\n\tedited := Edit(enc, key, nonce, []byte(\"TOMATO\"), 6)\n\tdec := challenge18.CTR(edited, key, nonce)\n\n\tif string(dec) != \"HELLO TOMATO FACE\" {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestEditAPI(t *testing.T) {\n\tinput := []byte(\"HELLO POTATO FACE\")\n\tenc := challenge18.CTR(input, globalKey, globalNonce)\n\tedited := EditAPI(enc, []byte(\"TOMATO\"), 6)\n\tdec := challenge18.CTR(edited, globalKey, globalNonce)\n\n\tif string(dec) != \"HELLO TOMATO FACE\" {\n\t\tt.Fail()\n\t}\n}\n\n\n\nfunc TestRecoverPTFromAPI(t *testing.T) ", "output": "{\n\tenc := EncryptSecretWithCTR(globalPlaintext)\n\trecovered := RecoverPTFromAPI(enc)\n\tif !bytes.Equal(recovered, globalPlaintext) {\n\t\tt.Fail()\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/go-redis/redis\"\n\t\"github.com/jasonlvhit/gocron\"\n)\n\n\n\nfunc lockedTask(name string) {\n\tfmt.Printf(\"Hello, %s!\\n\", name)\n\n\tt := time.NewTicker(time.Millisecond * 100)\n\tc := make(chan struct{})\n\ttime.AfterFunc(time.Second*5, func() {\n\t\tclose(c)\n\t})\n\n\tfor {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tfmt.Print(\".\")\n\t\tcase <-c:\n\t\t\tfmt.Println()\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\ntype locker struct {\n\tcache *redis.Client\n}\n\n\n\nfunc (s *locker) Unlock(key string) error {\n\treturn s.cache.Del(key).Err()\n}\n\n\n\nfunc main() {\n\tl := &locker{\n\t\tredis.NewClient(&redis.Options{\n\t\t\tAddr: \"localhost:6379\",\n\t\t}),\n\t}\n\n\tgocron.SetLocker(l)\n\n\targ := \"Some Name\"\n\targs := os.Args[1:]\n\tif len(args) > 0 {\n\t\targ = args[0]\n\t}\n\n\tgocron.Every(1).Second().Lock().Do(lockedTask, arg)\n\t<-gocron.Start()\n}\n\nfunc (s *locker) Lock(key string) (success bool, err error) ", "output": "{\n\tres, err := s.cache.SetNX(key, time.Now().String(), time.Second*15).Result()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn res, nil\n}"} {"input": "package main\n\nimport (\n\tfmtlog \"log\"\n\t\"time\"\n\n\t\"github.com/BurntSushi/toml\"\n\t\"github.com/emilevauge/traefik/provider\"\n\t\"github.com/emilevauge/traefik/types\"\n)\n\n\n\ntype GlobalConfiguration struct {\n\tPort string\n\tGraceTimeOut int64\n\tAccessLogsFile string\n\tTraefikLogsFile string\n\tCertificates []Certificate\n\tLogLevel string\n\tProvidersThrottleDuration time.Duration\n\tDocker *provider.Docker\n\tFile *provider.File\n\tWeb *WebProvider\n\tMarathon *provider.Marathon\n\tConsul *provider.Consul\n\tEtcd *provider.Etcd\n\tZookeeper *provider.Zookepper\n\tBoltdb *provider.BoltDb\n}\n\n\ntype Certificate struct {\n\tCertFile string\n\tKeyFile string\n}\n\n\nfunc NewGlobalConfiguration() *GlobalConfiguration {\n\tglobalConfiguration := new(GlobalConfiguration)\n\tglobalConfiguration.Port = \":80\"\n\tglobalConfiguration.GraceTimeOut = 10\n\tglobalConfiguration.LogLevel = \"ERROR\"\n\tglobalConfiguration.ProvidersThrottleDuration = time.Duration(2 * time.Second)\n\n\treturn globalConfiguration\n}\n\n\n\n\ntype configs map[string]*types.Configuration\n\nfunc LoadFileConfig(file string) *GlobalConfiguration ", "output": "{\n\tconfiguration := NewGlobalConfiguration()\n\tif _, err := toml.DecodeFile(file, configuration); err != nil {\n\t\tfmtlog.Fatalf(\"Error reading file: %s\", err)\n\t}\n\treturn configuration\n}"} {"input": "package logger\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/influxdata/wlog\"\n)\n\n\n\n\ntype telegrafLog struct {\n\twriter io.Writer\n}\n\nfunc (t *telegrafLog) Write(p []byte) (n int, err error) {\n\treturn t.writer.Write(p)\n}\n\n\n\n\n\n\n\nfunc SetupLogging(debug, quiet bool, logfile string) {\n\tif debug {\n\t\twlog.SetLevel(wlog.DEBUG)\n\t}\n\tif quiet {\n\t\twlog.SetLevel(wlog.ERROR)\n\t}\n\n\tvar oFile *os.File\n\tif logfile != \"\" {\n\t\tif _, err := os.Stat(logfile); os.IsNotExist(err) {\n\t\t\tif oFile, err = os.Create(logfile); err != nil {\n\t\t\t\tlog.Printf(\"E! Unable to create %s (%s), using stdout\", logfile, err)\n\t\t\t\toFile = os.Stdout\n\t\t\t}\n\t\t} else {\n\t\t\tif oFile, err = os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, os.ModeAppend); err != nil {\n\t\t\t\tlog.Printf(\"E! Unable to append to %s (%s), using stdout\", logfile, err)\n\t\t\t\toFile = os.Stdout\n\t\t\t}\n\t\t}\n\t} else {\n\t\toFile = os.Stdout\n\t}\n\n\tlog.SetOutput(newTelegrafWriter(oFile))\n}\n\nfunc newTelegrafWriter(w io.Writer) io.Writer ", "output": "{\n\treturn &telegrafLog{\n\t\twriter: wlog.NewWriter(w),\n\t}\n}"} {"input": "package generators\n\nimport (\n\t\"crypto/sha256\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\n\n\nfunc ID(localID string, publicKeys []string) string ", "output": "{\n\ttoHash := fmt.Sprintf(\"%v:%v\", localID, strings.Join(publicKeys, \",\"))\n\thash := sha256.Sum256([]byte(toHash))\n\n\tpart1 := hash[0:4]\n\tpart2 := hash[4:6]\n\tpart3 := hash[6:8]\n\tpart4 := hash[8:10]\n\tpart5 := hash[10:16]\n\n\treturn fmt.Sprintf(\"%x-%x-%x-%x-%x\", part1, part2, part3, part4, part5)\n}"} {"input": "package version\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n)\n\nconst Version = \"2020.1.3\"\n\n\n\nfunc version() (string, bool) {\n\tif Version != \"devel\" {\n\t\treturn Version, true\n\t}\n\tv, ok := buildInfoVersion()\n\tif ok {\n\t\treturn v, false\n\t}\n\treturn \"devel\", false\n}\n\nfunc Print() {\n\tv, release := version()\n\n\tif release {\n\t\tfmt.Printf(\"%s %s\\n\", filepath.Base(os.Args[0]), v)\n\t} else if v == \"devel\" {\n\t\tfmt.Printf(\"%s (no version)\\n\", filepath.Base(os.Args[0]))\n\t} else {\n\t\tfmt.Printf(\"%s (devel, %s)\\n\", filepath.Base(os.Args[0]), v)\n\t}\n}\n\n\n\nfunc Verbose() ", "output": "{\n\tPrint()\n\tfmt.Println()\n\tfmt.Println(\"Compiled with Go version:\", runtime.Version())\n\tprintBuildInfo()\n}"} {"input": "package nats\n\nimport (\n\t\"github.com/apcera/nats\"\n\t\"github.com/plimble/kuja/broker\"\n)\n\ntype natsBroker struct {\n\turl string\n\tconn *nats.Conn\n}\n\n\n\nfunc (n *natsBroker) Connect() error {\n\tvar err error\n\tn.conn, err = nats.Connect(n.url)\n\n\treturn err\n}\n\nfunc (n *natsBroker) Close() {\n\tn.conn.Close()\n}\n\nfunc (n *natsBroker) Publish(topic string, msg *broker.Message) error {\n\tdata, err := msg.Marshal()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn n.conn.Publish(topic, data)\n}\n\nfunc (n *natsBroker) Subscribe(topic, queue, appId string, size int, h broker.Handler) {\n\tfor i := 0; i < size; i++ {\n\t\tn.conn.QueueSubscribe(topic, queue, func(msg *nats.Msg) {\n\t\t\tbrokerMsg := &broker.Message{}\n\t\t\tbrokerMsg.Unmarshal(msg.Data)\n\t\t\tretryCount, err := h(msg.Subject, brokerMsg)\n\t\t\tif err != nil {\n\t\t\t\tfor i := 0; i < retryCount; i++ {\n\t\t\t\t\tbrokerMsg.Retry++\n\t\t\t\t\t_, err := h(topic, brokerMsg)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc NewBroker(url string) *natsBroker ", "output": "{\n\treturn &natsBroker{\n\t\turl: url,\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\n\t\"gopkg.in/stretchr/testify.v1/mock\"\n)\n\ntype Printer interface {\n\tHelp()\n\tVersion()\n\tMessage(msg string)\n\tError(err error)\n\tCommands()\n}\n\ntype TextPrinter struct {\n\tversion string\n}\n\nfunc NewTextPrinter(version string) *TextPrinter {\n\treturn &TextPrinter{version}\n}\n\nfunc (p *TextPrinter) Help() {\n\thelpText := `Name:\n\tfiz - a file wizard\n\nVersion:\n\t` + p.version + `\n\nUsage:\n\tfiz \n\n`\n\tp.Message(helpText)\n\tp.Commands()\n}\n\nfunc (p *TextPrinter) Version() {\n\tfmt.Println(\"fiz\", p.version)\n}\n\nfunc (p *TextPrinter) Message(msg string) {\n\tfmt.Print(msg)\n}\n\nfunc (p *TextPrinter) Error(err error) {\n\tfmt.Println(\"Error: \", err)\n}\n\nfunc (p *TextPrinter) Commands() {\n\tp.Message(COMMANDS_MSG)\n}\n\n\ntype MockPrinter struct {\n\tmock.Mock\n}\n\nfunc NewMockPrinter() *MockPrinter {\n\treturn &MockPrinter{}\n}\n\nfunc (m *MockPrinter) Help() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Version() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Message(msg string) {\n\tm.Called(msg)\n}\n\n\n\nfunc (m *MockPrinter) Commands() {\n\tm.Called()\n}\n\nfunc (m *MockPrinter) Error(err error) ", "output": "{\n\tm.Called(err)\n}"} {"input": "package logging\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/ConSol/go-neb-wrapper/neb\"\n\t\"github.com/griesbacher/Iapetos/config\"\n)\n\nconst (\n\tcore = \"core\"\n\tstdout = \"stdout\"\n)\n\nvar destination string\n\n\n\n\n\nfunc Flog(format string, a ...interface{}) {\n\tif destination == core {\n\t\tneb.CoreFLog(format, a)\n\t} else if destination == stdout {\n\t\tif a == nil {\n\t\t\tfmt.Print(format)\n\t\t} else {\n\t\t\tfmt.Printf(format, a)\n\t\t}\n\t}\n}\n\nfunc InitLogDestination() error ", "output": "{\n\tdest := strings.ToLower(config.GetConfig().Logging.Destination)\n\tif dest != core && dest != stdout {\n\t\treturn fmt.Errorf(\"This log destination is not supported. Supported are: %s %s\", core, stdout)\n\t}\n\n\tneb.CoreFLog(\"Logging from now on to: %s\", dest)\n\tdestination = dest\n\treturn nil\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/kataras/iris/v12/_examples/mvc/vuejs-todo-mvc/src/todo\"\n\n\t\"github.com/kataras/iris/v12\"\n\t\"github.com/kataras/iris/v12/mvc\"\n\t\"github.com/kataras/iris/v12/sessions\"\n\t\"github.com/kataras/iris/v12/websocket\"\n)\n\n\ntype TodoController struct {\n\tService todo.Service\n\n\tSession *sessions.Session\n\n\tNS *websocket.NSConn\n}\n\n\n\n\n\nfunc (c *TodoController) BeforeActivation(b mvc.BeforeActivation) {\n\tb.Dependencies().Register(func(ctx iris.Context) (items []todo.Item) {\n\t\tctx.ReadJSON(&items)\n\t\treturn\n\t}) \n}\n\n\nfunc (c *TodoController) Get() []todo.Item {\n\treturn c.Service.Get(c.Session.ID())\n}\n\n\n\ntype PostItemResponse struct {\n\tSuccess bool `json:\"success\"`\n}\n\nvar emptyResponse = PostItemResponse{Success: false}\n\n\n\n\nfunc (c *TodoController) Save(msg websocket.Message) error {\n\tid := c.Session.ID()\n\tc.NS.Conn.Server().Broadcast(nil, websocket.Message{\n\t\tNamespace: msg.Namespace,\n\t\tEvent: \"saved\",\n\t\tTo: id,\n\t\tBody: websocket.Marshal(c.Service.Get(id)),\n\t})\n\n\treturn nil\n}\n\nfunc (c *TodoController) Post(newItems []todo.Item) PostItemResponse ", "output": "{\n\tif err := c.Service.Save(c.Session.ID(), newItems); err != nil {\n\t\treturn emptyResponse\n\t}\n\n\treturn PostItemResponse{Success: true}\n}"} {"input": "package migrations\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/RichardKnop/example-api/log\"\n\t\"github.com/jinzhu/gorm\"\n)\n\n\ntype MigrationStage struct {\n\tName string\n\tFunction func(db *gorm.DB, name string) error\n}\n\n\nfunc Migrate(db *gorm.DB, migrations []MigrationStage) error {\n\tfor _, m := range migrations {\n\t\tif MigrationExists(db, m.Name) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := m.Function(db, m.Name); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := SaveMigration(db, m.Name); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc MigrateAll(db *gorm.DB, migrationFunctions []func(*gorm.DB) error) {\n\tif err := Bootstrap(db); err != nil {\n\t\tlog.ERROR.Print(err)\n\t}\n\n\tfor _, m := range migrationFunctions {\n\t\tif err := m(db); err != nil {\n\t\t\tlog.ERROR.Print(err)\n\t\t}\n\t}\n}\n\n\nfunc MigrationExists(db *gorm.DB, migrationName string) bool {\n\tmigration := new(Migration)\n\tfound := !db.Where(\"name = ?\", migrationName).First(migration).RecordNotFound()\n\n\tif found {\n\t\tlog.INFO.Printf(\"Skipping %s migration\", migrationName)\n\t} else {\n\t\tlog.INFO.Printf(\"Running %s migration\", migrationName)\n\t}\n\n\treturn found\n}\n\n\n\n\nfunc SaveMigration(db *gorm.DB, migrationName string) error ", "output": "{\n\tmigration := new(Migration)\n\tmigration.Name = migrationName\n\n\tif err := db.Create(migration).Error; err != nil {\n\t\tlog.ERROR.Printf(\"Error saving record to migrations table: %s\", err)\n\t\treturn fmt.Errorf(\"Error saving record to migrations table: %s\", err)\n\t}\n\n\treturn nil\n}"} {"input": "package next\n\nimport (\n \"gopkg.in/mgo.v2\"\n \"gopkg.in/mgo.v2/bson\"\n)\n\ntype MongoDB struct {\n session *mgo.Session\n db string\n}\n\nfunc NewMongoDB() *MongoDB {\n return &MongoDB{}\n}\n\n\n\nfunc (mongo *MongoDB) Close() {\n mongo.session.Close()\n}\n\nfunc (mongo *MongoDB) Session() *mgo.Session {\n s := mongo.session.Copy()\n s.SetMode(mgo.Strong, true)\n return s\n}\n\nfunc (mongo *MongoDB) InsertOrUpdate(collection string, buziKey string, buziValue interface{}, d interface{}, result interface{}) (error) {\n s := mongo.Session()\n defer s.Close()\n\n c := s.DB(mongo.db).C(collection)\n\n change := mgo.Change{\n Update: bson.M{\"$set\": d},\n Upsert: true,\n Remove: false,\n ReturnNew: true,\n }\n\n _, err := c.Find(bson.M{buziKey: buziValue}).Apply(change, result)\n return err\n}\n\nfunc (mongo *MongoDB) Open(url string, db string) ", "output": "{\n s, err := mgo.Dial(url)\n if err != nil {\n panic(err.Error())\n }\n\n mongo.session = s\n mongo.db = db\n}"} {"input": "package Plugin\n\nimport \"github.com/MPjct/GoMP/MySQLProtocol\"\n\ntype Plugin_interface interface {\n\tinit(context MySQLProtocol.Context)\n\tread_handshake(context MySQLProtocol.Context)\n\tsend_handshake(context MySQLProtocol.Context)\n\tread_auth(context MySQLProtocol.Context)\n\tsend_auth(context MySQLProtocol.Context)\n\tread_auth_result(context MySQLProtocol.Context)\n\tsend_auth_result(context MySQLProtocol.Context)\n\tread_query(context MySQLProtocol.Context)\n\tsend_query(context MySQLProtocol.Context)\n\tread_query_result(context MySQLProtocol.Context)\n\tsend_query_result(context MySQLProtocol.Context)\n\tcleanup(context MySQLProtocol.Context)\n}\n\ntype Plugin struct {\n}\n\nfunc (plugin *Plugin) init(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\n\n\nfunc (plugin *Plugin) read_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) cleanup(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth(context MySQLProtocol.Context) ", "output": "{\n\treturn\n}"} {"input": "package logger\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\tlog \"github.com/cihub/seelog\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestGetLogFileLocationReturnsOverriddenPath(t *testing.T) {\n\tpath := \"/tmp/foo\"\n\tos.Setenv(envLogFilePath, path)\n\tdefer os.Unsetenv(envLogFilePath)\n\n\tassert.Equal(t, path, GetLogFileLocation(\"/tmp/bar\"))\n}\n\n\n\nfunc TestLogLevelReturnsOverriddenLevel(t *testing.T) {\n\tos.Setenv(envLogLevel, \"DEBUG\")\n\tdefer os.Unsetenv(envLogLevel)\n\n\tvar expectedLogLevel log.LogLevel\n\texpectedLogLevel = log.DebugLvl\n\tassert.Equal(t, expectedLogLevel.String(), getLogLevel())\n}\n\nfunc TestLogLevelReturnsDefaultLevelWhenEnvNotSet(t *testing.T) {\n\tvar expectedLogLevel log.LogLevel\n\texpectedLogLevel = log.InfoLvl\n\tassert.Equal(t, expectedLogLevel.String(), getLogLevel())\n}\n\nfunc TestLogLevelReturnsDefaultLevelWhenEnvSetToInvalidValue(t *testing.T) {\n\tos.Setenv(envLogLevel, \"DEBUGGER\")\n\tdefer os.Unsetenv(envLogLevel)\n\n\tvar expectedLogLevel log.LogLevel\n\texpectedLogLevel = log.InfoLvl\n\tassert.Equal(t, expectedLogLevel.String(), getLogLevel())\n}\n\nfunc TestGetLogFileLocationReturnsDefaultPath(t *testing.T) ", "output": "{\n\tpath := \"/tmp/foo\"\n\tassert.Equal(t, path, GetLogFileLocation(path))\n}"} {"input": "package util\n\nimport (\n\t\"strings\"\n\n\t\"github.com/spf13/viper\"\n)\n\n\nconst EnvPrefix = \"GSD\" \n\nfunc GetSubViper(v *viper.Viper, key string) *viper.Viper {\n\tn := v.Sub(key)\n\tif n == nil {\n\t\tn = viper.New()\n\t}\n\tInitViper(n, key)\n\treturn n\n}\n\n\n\n\n\nfunc InitViper(v *viper.Viper, subViperName string) ", "output": "{\n\tv.SetEnvKeyReplacer(strings.NewReplacer(\"-\", \"_\"))\n\tif subViperName != \"\" {\n\t\tv.SetEnvPrefix(EnvPrefix + \"_\" + strings.ToUpper(subViperName))\n\t} else {\n\t\tv.SetEnvPrefix(EnvPrefix)\n\t}\n\tv.SetTypeByDefaultValue(true)\n\tv.AutomaticEnv()\n}"} {"input": "package online\n\nimport (\n\t\"monitor/log\"\n\t\"time\"\n)\n\nvar (\n\tsessions = make(map[string]*Session) \n)\n\nconst Expired = 60 * 30\n\n\n\n\n\ntype Session struct {\n\tUID string\n\tName string\n\tKey string\n\tLastTime time.Time\n}\n\n\nfunc (this *Session) IsExpired() bool {\n\treturn time.Since(this.LastTime).Seconds() > Expired\n}\n\n\nfunc SetSession(uid string, name string, key string) {\n\ts := &Session{UID: uid, Key: key, LastTime: time.Now()}\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tsessions[uid] = s\n}\n\n\nfunc GetSession(id string) (name string, key string, ok bool) {\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\n\tif s, exists := sessions[id]; exists {\n\t\tkey = s.Key\n\t\tname = s.Name\n\t\tok = true\n\t\ts.LastTime = time.Now()\n\t}\n\treturn\n}\n\n\nfunc FreshSession(id string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tif s, ok := sessions[id]; ok {\n\t\ts.LastTime = time.Now()\n\t}\n}\n\n\nfunc RemoveSession(id string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tif _, ok := sessions[id]; ok {\n\t\tdelete(sessions, id)\n\t}\n}\n\nfunc init() ", "output": "{\n\tlog.Info(\"Session is started,expired every %d seconds\", Expired)\n\tgo func() {\n\t\tvar i int\n\t\ttimer := time.Tick(time.Minute)\n\t\tfor t := range timer {\n\t\t\ti = 0\n\t\t\tlock.Lock()\n\t\t\tfor k, s := range sessions {\n\t\t\t\tif s.IsExpired() {\n\t\t\t\t\tdelete(sessions, k)\n\t\t\t\t\ti = i + 1\n\t\t\t\t}\n\t\t\t}\n\t\t\tlock.Unlock()\n\t\t\tlog.Infof(\"clear %d sessions at %v,used %v\", i, t, time.Since(t))\n\t\t}\n\t}()\n}"} {"input": "package server\n\nimport (\n\t\"sync\"\n)\n\ntype ID uint32\n\ntype IDGenerator struct {\n\tlastID ID\n\tids []ID\n\tlocker *sync.Mutex\n\tthreadSafe bool\n}\n\nfunc NewIDGenerator(buffer int, threadSafe bool) *IDGenerator {\n\tgen := &IDGenerator{0, make([]ID, 0, buffer), &sync.Mutex{}, threadSafe}\n\tif threadSafe {\n\t\tgen.locker.Lock()\n\t\tdefer gen.locker.Unlock()\n\t}\n\n\tgen.genIDs()\n\treturn gen\n}\n\nfunc (gen *IDGenerator) genIDs() {\n\tgen.lastID += ID(cap(gen.ids) / 2)\n\tid := gen.lastID - 1\n\tfor i := 0; i < cap(gen.ids)/2; i++ {\n\t\tgen.ids = append(gen.ids, id)\n\t\tid--\n\t}\n}\n\nfunc (gen *IDGenerator) NextID() ID {\n\tid := ID(0)\n\n\tif gen.threadSafe {\n\t\tgen.locker.Lock()\n\t\tdefer gen.locker.Unlock()\n\t}\n\tid, gen.ids = gen.ids[len(gen.ids)-1], gen.ids[:len(gen.ids)-1]\n\tif len(gen.ids) == 0 {\n\t\tgen.genIDs()\n\t}\n\n\treturn id\n}\n\n\n\nfunc (gen *IDGenerator) PutID(id ID) ", "output": "{\n\tif gen.threadSafe {\n\t\tgen.locker.Lock()\n\t\tdefer gen.locker.Unlock()\n\t}\n\tgen.ids = append(gen.ids, id)\n}"} {"input": "package downloader\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/WhaleCoinOrg/WhaleCoin/core/types\"\n)\n\n\ntype peerDropFn func(id string)\n\n\ntype dataPack interface {\n\tPeerId() string\n\tItems() int\n\tStats() string\n}\n\n\ntype headerPack struct {\n\tpeerId string\n\theaders []*types.Header\n}\n\n\nfunc (p *headerPack) Items() int { return len(p.headers) }\nfunc (p *headerPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.headers)) }\n\n\ntype bodyPack struct {\n\tpeerId string\n\ttransactions [][]*types.Transaction\n\tuncles [][]*types.Header\n}\n\nfunc (p *bodyPack) PeerId() string { return p.peerId }\nfunc (p *bodyPack) Items() int {\n\tif len(p.transactions) <= len(p.uncles) {\n\t\treturn len(p.transactions)\n\t}\n\treturn len(p.uncles)\n}\nfunc (p *bodyPack) Stats() string { return fmt.Sprintf(\"%d:%d\", len(p.transactions), len(p.uncles)) }\n\n\ntype receiptPack struct {\n\tpeerId string\n\treceipts [][]*types.Receipt\n}\n\nfunc (p *receiptPack) PeerId() string { return p.peerId }\nfunc (p *receiptPack) Items() int { return len(p.receipts) }\nfunc (p *receiptPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.receipts)) }\n\n\ntype statePack struct {\n\tpeerId string\n\tstates [][]byte\n}\n\nfunc (p *statePack) PeerId() string { return p.peerId }\nfunc (p *statePack) Items() int { return len(p.states) }\nfunc (p *statePack) Stats() string { return fmt.Sprintf(\"%d\", len(p.states)) }\n\nfunc (p *headerPack) PeerId() string ", "output": "{ return p.peerId }"} {"input": "package autostart\n\nimport (\n\t\"flag\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/vim25/types\"\n)\n\ntype add struct {\n\t*AutostartFlag\n}\n\nfunc init() {\n\tcli.Register(\"host.autostart.add\", &add{})\n}\n\nfunc (cmd *add) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.AutostartFlag, ctx = newAutostartFlag(ctx)\n\tcmd.AutostartFlag.Register(ctx, f)\n}\n\nfunc (cmd *add) Process(ctx context.Context) error {\n\tif err := cmd.AutostartFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc (cmd *add) Run(ctx context.Context, f *flag.FlagSet) error {\n\tvar powerInfo = types.AutoStartPowerInfo{\n\t\tStartAction: \"powerOn\",\n\t\tStartDelay: -1,\n\t\tStartOrder: -1,\n\t\tStopAction: \"systemDefault\",\n\t\tStopDelay: -1,\n\t\tWaitForHeartbeat: types.AutoStartWaitHeartbeatSettingSystemDefault,\n\t}\n\n\treturn cmd.ReconfigureVMs(f.Args(), powerInfo)\n}\n\nfunc (cmd *add) Usage() string ", "output": "{\n\treturn \"VM...\"\n}"} {"input": "package fake\n\nimport (\n\tcontext \"context\"\n\n\truntime \"k8s.io/apimachinery/pkg/runtime\"\n\trest \"k8s.io/client-go/rest\"\n\tfake \"knative.dev/eventing-prometheus/pkg/client/clientset/versioned/fake\"\n\tclient \"knative.dev/eventing-prometheus/pkg/client/injection/client\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\n\n\nfunc withClient(ctx context.Context, cfg *rest.Config) context.Context {\n\tctx, _ = With(ctx)\n\treturn ctx\n}\n\nfunc With(ctx context.Context, objects ...runtime.Object) (context.Context, *fake.Clientset) {\n\tcs := fake.NewSimpleClientset(objects...)\n\treturn context.WithValue(ctx, client.Key{}, cs), cs\n}\n\n\nfunc Get(ctx context.Context) *fake.Clientset {\n\tuntyped := ctx.Value(client.Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch knative.dev/eventing-prometheus/pkg/client/clientset/versioned/fake.Clientset from context.\")\n\t}\n\treturn untyped.(*fake.Clientset)\n}\n\nfunc init() ", "output": "{\n\tinjection.Fake.RegisterClient(withClient)\n\tinjection.Fake.RegisterClientFetcher(func(ctx context.Context) interface{} {\n\t\treturn Get(ctx)\n\t})\n}"} {"input": "package room\n\nimport (\n \"log\"\n\n \"github.com/jinzhu/gorm\"\n _ \"github.com/jinzhu/gorm/dialects/sqlite\"\n)\n\nconst tableName string = \"rooms\"\n\ntype Room struct {\n gorm.Model\n Id int64 `sql:\"AUTO_INCREMENT\" gorm:\"primary_key\"`\n Name string `sql:\"size:255;unique;index\"`\n Size int32\n VC bool\n CalendarId string\n}\n\nvar (\n dbHandle *gorm.DB\n dbPath string\n)\n\nfunc check(err error) {\n if err != nil {\n log.Println(\"[Models]: \", err)\n }\n\n}\n\nfunc Create(dbHandle *gorm.DB, name string, size int32, vc bool, calendarId string) {\n dbHandle.Create(&Room{Name: name, Size: size, VC: vc, CalendarId: calendarId})\n}\n\nfunc GetAll(dbHandle *gorm.DB) []*Room {\n var rooms []*Room\n rows, err := dbHandle.Table(tableName).Select(nil).Rows()\n check(err)\n rows.Scan(&rooms)\n return rooms\n}\n\n\n\nfunc SetDbPath(path string) ", "output": "{\n dbPath = path\n}"} {"input": "package log\n\nimport \"fmt\"\n\nconst _Level_name = \"LogNoneLogErrorLogInfoLogDebug\"\n\nvar _Level_index = [...]uint8{0, 7, 15, 22, 30}\n\n\n\nfunc (i Level) String() string ", "output": "{\n\tif i < 0 || i >= Level(len(_Level_index)-1) {\n\t\treturn fmt.Sprintf(\"Level(%d)\", i)\n\t}\n\treturn _Level_name[_Level_index[i]:_Level_index[i+1]]\n}"} {"input": "package api\n\nimport (\n\t\"github.com/mattermost/platform/model\"\n)\n\ntype LogoutProvider struct {\n}\n\nconst (\n\tCMD_LOGOUT = \"logout\"\n)\n\nfunc init() {\n\tRegisterCommandProvider(&LogoutProvider{})\n}\n\n\n\nfunc (me *LogoutProvider) GetCommand(c *Context) *model.Command {\n\treturn &model.Command{\n\t\tTrigger: CMD_LOGOUT,\n\t\tAutoComplete: true,\n\t\tAutoCompleteDesc: c.T(\"api.command_logout.desc\"),\n\t\tAutoCompleteHint: \"\",\n\t\tDisplayName: c.T(\"api.command_logout.name\"),\n\t}\n}\n\nfunc (me *LogoutProvider) DoCommand(c *Context, channelId string, message string) *model.CommandResponse {\n\treturn &model.CommandResponse{GotoLocation: \"/logout\", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: c.T(\"api.command_logout.success_message\")}\n}\n\nfunc (me *LogoutProvider) GetTrigger() string ", "output": "{\n\treturn CMD_LOGOUT\n}"} {"input": "package string\n\nimport (\n\tdss \"github.com/emirpasic/gods/stacks/arraystack\"\n)\n\n\n\n\n\n\n\n\n\n\nfunc ReverseNest(s string) string {\n\tr := []rune(s)\n\tif len(r) == 1 || len(r) == 0 {\n\t\treturn s\n\t}\n\tsub := ReverseNest(string(r[1:]))\n\treturn sub + string(r[0:1])\n}\n\n\nfunc ReverseNest1(s string) string {\n\tr := []rune(s)\n\tswitchHeadTail(r)\n\treturn string(r)\n}\n\nfunc switchHeadTail(r []rune) {\n\tif len(r) <= 1 {\n\t\treturn\n\t}\n\tbottom, top := 0, len(r)-1\n\tr[bottom], r[top] = r[top], r[bottom]\n\tswitchHeadTail(r[bottom+1 : top])\n}\n\n\nfunc ReverseInStack(s string) string {\n\tr := []rune(s)\n\tstack := dss.New()\n\tfor i := 0; i < len(r); i++ {\n\t\tstack.Push(r[i])\n\t}\n\trs := make([]rune, len(r))\n\tfor i := 0; i < len(r); i++ {\n\t\tv, _ := stack.Pop()\n\t\tif v != nil {\n\t\t\trs[i] = v.(rune)\n\t\t}\n\t}\n\treturn string(rs)\n}\n\nfunc Reverse(s string) string ", "output": "{\n\tr := []rune(s) \n\tfor i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n\t\tr[i], r[j] = r[j], r[i]\n\t}\n\treturn string(r)\n}"} {"input": "package blobstoredbstatesnapshotio\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/nyaxt/otaru/metadata\"\n)\n\nfunc generateBlobpath() string {\n\treturn fmt.Sprintf(\"%s_SimpleSSLocator\", metadata.INodeDBSnapshotBlobpathPrefix)\n}\n\nvar simplesslocatorTxID int64\n\ntype SimpleSSLocator struct{}\n\nfunc (SimpleSSLocator) Locate(history int) (string, int64, error) {\n\treturn generateBlobpath(), simplesslocatorTxID, nil\n}\n\nfunc (SimpleSSLocator) GenerateBlobpath() string {\n\treturn generateBlobpath()\n}\n\n\n\nfunc (SimpleSSLocator) DeleteOld(ctx context.Context, threshold int, dryRun bool) ([]string, error) {\n\treturn []string{}, nil\n}\n\nfunc (SimpleSSLocator) Put(blobpath string, txid int64) error ", "output": "{\n\tsimplesslocatorTxID = txid\n\treturn nil\n}"} {"input": "package gen\n\nimport (\n\t\"regexp\"\n\t\"strings\"\n)\n\nfunc ReplaceSearchCallback(code []byte, modelName string) []byte {\n\trSearchCallback, _ := regexp.Compile(\"SearchCallback\")\n\tresult := rSearchCallback.ReplaceAll(code, []byte(\"SearchCallback\"+strings.Title(modelName)))\n\n\treturn result\n}\n\n\nfunc RemovePackage(code []byte) []byte {\n\trPackage, _ := regexp.Compile(\"package collection\")\n\tresult := rPackage.ReplaceAll(code, make([]byte, 0))\n\n\treturn result\n}\n\n\n\nfunc ReplaceImports(code []byte) []byte {\n\trICollections, _ := regexp.Compile(\"(import \\\"sort\\\")\")\n\tresult := rICollections.ReplaceAll(code, []byte(\"\"))\n\n\treturn result\n}\n\nfunc InjectImports(code []byte, imports []string) (result []byte) {\n\tresult = code[:]\n\n\tfor _, i := range imports {\n\t\tresult = append([]byte(\"\\nimport \\\"\"+i+\"\\\"\\n\"), code...)\n\t}\n\n\treturn result\n}\n\nfunc ReplaceGrizzlyId(code []byte, customType string) []byte ", "output": "{\n\tgICollections, _ := regexp.Compile(\"GrizzlyId\")\n\tresult := gICollections.ReplaceAll(code, []byte(strings.Title(customType)))\n\n\treturn result\n}"} {"input": "package service\n\nimport (\n\t\"github.com/xephonhq/xephon-k/pkg/common\"\n\t\"github.com/xephonhq/xephon-k/pkg/storage\"\n)\n\ntype ReadService struct {\n\tstore storage.Store\n}\n\n\n\nfunc (r *ReadService) QuerySeries(queries []common.Query) ([]common.QueryResult, []common.Series, error) {\n\treturn r.store.QuerySeries(queries)\n}\n\nfunc NewReadService(store storage.Store) *ReadService ", "output": "{\n\treturn &ReadService{\n\t\tstore: store,\n\t}\n}"} {"input": "package metrics\n\nimport \"github.com/PagerDuty/godspeed\"\n\nvar Metric Metrics = BlackHole{}\n\ntype Metrics interface {\n\tCount(stat string, count float64, tags []string) error\n\tSet(stat string, value float64, tags []string) error\n}\n\ntype BlackHole struct{}\n\nfunc (b BlackHole) Count(stat string, count float64, tags []string) error {\n\treturn nil\n}\n\nfunc (b BlackHole) Set(stat string, value float64, tags []string) error {\n\treturn nil\n}\n\ntype GodSpeed struct {\n\tIP string\n\tPort int\n\tNameSpace string\n}\n\nfunc (b *GodSpeed) newConn() (*godspeed.Godspeed, error) {\n\tgs, err := godspeed.New(b.IP, b.Port, false)\n\tif err != nil {\n\t\treturn gs, err\n\t}\n\tgs.Namespace = b.NameSpace\n\n\treturn gs, err\n}\n\n\n\nfunc (b *GodSpeed) Set(stat string, value float64, tags []string) error {\n\tc, err := b.newConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.Conn.Close()\n\treturn c.Set(stat, value, tags)\n}\n\nfunc (b *GodSpeed) Count(stat string, count float64, tags []string) error ", "output": "{\n\tc, err := b.newConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.Conn.Close()\n\treturn c.Count(stat, count, tags)\n}"} {"input": "package store\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\n\t\"gopkg.in/oauth2.v3\"\n)\n\nfunc NewClientStore() *ClientStore {\n\treturn &ClientStore{\n\t\tdata: make(map[string]oauth2.ClientInfo),\n\t}\n}\n\n\ntype ClientStore struct {\n\tsync.RWMutex\n\tdata map[string]oauth2.ClientInfo\n}\n\n\nfunc (cs *ClientStore) GetByID(id string) (cli oauth2.ClientInfo, err error) {\n\tcs.RLock()\n\tdefer cs.RUnlock()\n\tif c, ok := cs.data[id]; ok {\n\t\tcli = c\n\t\treturn\n\t}\n\terr = errors.New(\"not found\")\n\treturn\n}\n\n\n\n\nfunc (cs *ClientStore) Set(id string, cli oauth2.ClientInfo) (err error) ", "output": "{\n\tcs.Lock()\n\tdefer cs.Unlock()\n\tcs.data[id] = cli\n\treturn\n}"} {"input": "package balancetransaction\n\nimport (\n\t\"net/http\"\n\n\tstripe \"github.com/stripe/stripe-go\"\n\t\"github.com/stripe/stripe-go/form\"\n)\n\n\ntype Client struct {\n\tB stripe.Backend\n\tKey string\n}\n\n\nfunc Get(id string, params *stripe.BalanceTransactionParams) (*stripe.BalanceTransaction, error) {\n\treturn getC().Get(id, params)\n}\n\n\nfunc (c Client) Get(id string, params *stripe.BalanceTransactionParams) (*stripe.BalanceTransaction, error) {\n\tpath := stripe.FormatURLPath(\"/v1/balance_transactions/%s\", id)\n\ttransaction := &stripe.BalanceTransaction{}\n\terr := c.B.Call(http.MethodGet, path, c.Key, params, transaction)\n\treturn transaction, err\n}\n\n\n\n\n\nfunc (c Client) List(listParams *stripe.BalanceTransactionListParams) *Iter {\n\treturn &Iter{stripe.GetIter(listParams, func(p *stripe.Params, b *form.Values) ([]interface{}, stripe.ListMeta, error) {\n\t\tlist := &stripe.BalanceTransactionList{}\n\t\terr := c.B.CallRaw(http.MethodGet, \"/v1/balance_transactions\", c.Key, b, p, list)\n\n\t\tret := make([]interface{}, len(list.Data))\n\t\tfor i, v := range list.Data {\n\t\t\tret[i] = v\n\t\t}\n\n\t\treturn ret, list.ListMeta, err\n\t})}\n}\n\n\ntype Iter struct {\n\t*stripe.Iter\n}\n\n\nfunc (i *Iter) BalanceTransaction() *stripe.BalanceTransaction {\n\treturn i.Current().(*stripe.BalanceTransaction)\n}\n\nfunc getC() Client {\n\treturn Client{stripe.GetBackend(stripe.APIBackend), stripe.Key}\n}\n\nfunc List(params *stripe.BalanceTransactionListParams) *Iter ", "output": "{\n\treturn getC().List(params)\n}"} {"input": "package customer\n\nimport (\n\t\"github.com/corestoreio/csfw/eav\"\n\t\"github.com/corestoreio/csfw/storage/csdb\"\n)\n\ntype (\n\tAddressModel struct {\n\t}\n)\n\nvar (\n\t_ eav.EntityTypeModeller = (*AddressModel)(nil)\n\t_ eav.EntityTypeTabler = (*AddressModel)(nil)\n\t_ eav.EntityTypeAdditionalAttributeTabler = (*AddressModel)(nil)\n\t_ eav.EntityTypeIncrementModeller = (*AddressModel)(nil)\n)\n\nfunc (c *AddressModel) TBD() {\n\n}\n\nfunc (c *AddressModel) TableNameBase() string {\n\treturn TableCollection.Name(TableIndexAddressEntity)\n}\n\n\n\n\nfunc (c *AddressModel) TableAdditionalAttribute() (*csdb.Table, error) {\n\treturn TableCollection.Structure(TableIndexEAVAttribute)\n}\n\n\nfunc (c *AddressModel) TableEavWebsite() (*csdb.Table, error) {\n\treturn TableCollection.Structure(TableIndexEAVAttributeWebsite)\n}\n\nfunc Address() *AddressModel {\n\treturn &AddressModel{}\n}\n\nfunc (c *AddressModel) TableNameValue(i eav.ValueIndex) string ", "output": "{\n\ts, err := GetAddressValueStructure(i)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s.Name\n}"} {"input": "package git\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nfunc (r *Repo) resolveRef(name string) (id Id) {\n\tif id := r.refs[name]; id != \"\" {\n\t\treturn id\n\t}\n\tcontent, err := ioutil.ReadFile(r.file(name))\n\tif err != nil {\n\t\tpanic(err.Error())\n\t\treturn \"\"\n\t}\n\tcontent = bytes.TrimSpace(content)\n\tif bytes.HasPrefix(content, []byte(\"ref: \")) {\n\t\tid = r.resolveRef(string(content[5:]))\n\t} else {\n\t\tid = IdFromString(string(content))\n\t}\n\tif id != \"\" {\n\t\tr.refs[name] = id\n\t}\n\treturn\n}\n\n\nfunc (r *Repo) Head() Id {\n\treturn r.resolveRef(\"HEAD\")\n}\n\n\n\n\nfunc (r *Repo) Refs() map[string]Id {\n\tr.packedRefs()\n\tif head := r.Head(); head != \"\" {\n\t\tr.refs[\"HEAD\"] = head\n\t}\n\tfilepath.Walk(r.file(\"refs\"), refVisitor(r))\n\treturn r.refs\n}\n\nfunc refVisitor(r *Repo) filepath.WalkFunc {\n\treturn func(path string, f os.FileInfo, err error) error {\n\t\tif !f.IsDir() {\n\t\t\tr.resolveRef(path[5:])\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc (r *Repo) packedRefs() ", "output": "{\n\tif r.refs == nil {\n\t\tr.refs = map[string]Id{}\n\t}\n\tpackedRefs := r.file(\"packed-refs\")\n\tcontent, err := ioutil.ReadFile(packedRefs)\n\tif err != nil {\n\t\treturn\n\t}\n\tlines := bytes.Split(content, []byte{'\\n'})\n\tfor _, line := range lines {\n\t\tif len(line) == 0 || line[0] == '#' {\n\t\t\tcontinue\n\t\t}\n\t\tparts := bytes.SplitN(line, []byte{' '}, 2)\n\t\tif len(parts[0]) != 40 {\n\t\t\tcontinue\n\t\t}\n\t\tid := IdFromString(string(parts[0]))\n\t\trefname := string(parts[1])\n\t\tr.refs[refname] = id\n\t}\n\treturn\n}"} {"input": "package main\n\nimport \"github.com/nsf/termbox-go\"\n\ntype Input struct {\n\tendKey termbox.Key\n\teventQ chan termbox.Event\n\tctrl chan bool\n}\n\nfunc NewInput() *Input {\n\treturn &Input{\n\t\tendKey: termbox.KeyCtrlC,\n\t\teventQ: make(chan termbox.Event),\n\t\tctrl: make(chan bool, 2),\n\t}\n}\n\nfunc (i *Input) Start() {\n\tgo poll(i)\n}\n\nfunc (i *Input) Stop() {\n\ti.ctrl <- true\n}\n\n\n\nfunc poll(i *Input) ", "output": "{\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-i.ctrl:\n\t\t\tbreak loop\n\t\tdefault:\n\t\t\ti.eventQ <- termbox.PollEvent()\n\t\t}\n\t}\n}"} {"input": "package dchan\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype SimpleReq struct {\n\tHeader Header\n\tBody io.ReadCloser\n}\n\ntype Header []header\n\nfunc (h Header) get(k string) int {\n\tfor idx := range h {\n\t\tif strings.EqualFold(h[idx].Name, k) {\n\t\t\treturn idx\n\t\t}\n\t}\n\treturn -1\n}\n\n\n\nfunc (h *Header) Add(k string, v string) {\n\tidx := h.get(k)\n\tif idx < 0 {\n\t\t*h = append(*h, header{k, []string{v}})\n\t} else {\n\t\t(*h)[idx].Values = append((*h)[idx].Values, v)\n\t}\n}\n\ntype header struct {\n\tName string\n\tValues []string\n}\n\nfunc NewSimpleReq(r *bufio.Reader) (*SimpleReq, error) {\n\tsr := &SimpleReq{\n\t\tHeader: make(Header, 0, 16),\n\t}\n\n\tfor {\n\t\tline, err := r.ReadSlice('\\n')\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(line) == 2 {\n\t\t\tbreak\n\t\t}\n\n\t\tif idx := bytes.Index(line, []byte(\":\")); idx > 0 {\n\t\t\tsr.Header.Add(string(line[:idx]), string(bytes.TrimSpace(line[idx+1:])))\n\t\t}\n\t}\n\n\tcl := sr.Header.Get(\"Content-Length\")\n\tif n, _ := strconv.Atoi(cl); n > 0 {\n\t\tsr.Body = ioutil.NopCloser(io.LimitReader(r, int64(n)))\n\t} else {\n\t\tsr.Body = ioutil.NopCloser(r)\n\t}\n\treturn sr, nil\n}\n\nfunc (h Header) Get(k string) string ", "output": "{\n\tidx := h.get(k)\n\tif idx < 0 {\n\t\treturn \"\"\n\t}\n\treturn h[idx].Values[0]\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/cgrates/cgrates/utils\"\n\t\"github.com/cgrates/ltcache\"\n)\n\ntype CacheParamCfg struct {\n\tLimit int\n\tTTL time.Duration\n\tStaticTTL bool\n\tPrecache bool\n}\n\n\n\ntype CacheCfg map[string]*CacheParamCfg\n\nfunc (self CacheCfg) loadFromJsonCfg(jsnCfg *CacheJsonCfg) (err error) {\n\tif jsnCfg == nil {\n\t\treturn\n\t}\n\tfor kJsn, vJsn := range *jsnCfg {\n\t\tval := new(CacheParamCfg)\n\t\tif err := val.loadFromJsonCfg(vJsn); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tself[kJsn] = val\n\t}\n\treturn nil\n}\n\nfunc (cCfg CacheCfg) AsTransCacheConfig() (tcCfg map[string]*ltcache.CacheConfig) {\n\ttcCfg = make(map[string]*ltcache.CacheConfig, len(cCfg))\n\tfor k, cPcfg := range cCfg {\n\t\ttcCfg[k] = <cache.CacheConfig{\n\t\t\tMaxItems: cPcfg.Limit,\n\t\t\tTTL: cPcfg.TTL,\n\t\t\tStaticTTL: cPcfg.StaticTTL,\n\t\t}\n\t}\n\treturn\n}\n\nfunc (self *CacheParamCfg) loadFromJsonCfg(jsnCfg *CacheParamJsonCfg) error ", "output": "{\n\tif jsnCfg == nil {\n\t\treturn nil\n\t}\n\tvar err error\n\tif jsnCfg.Limit != nil {\n\t\tself.Limit = *jsnCfg.Limit\n\t}\n\tif jsnCfg.Ttl != nil {\n\t\tif self.TTL, err = utils.ParseDurationWithNanosecs(*jsnCfg.Ttl); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif jsnCfg.Static_ttl != nil {\n\t\tself.StaticTTL = *jsnCfg.Static_ttl\n\t}\n\tif jsnCfg.Precache != nil {\n\t\tself.Precache = *jsnCfg.Precache\n\t}\n\treturn nil\n}"} {"input": "package model\n\n\ntype Weight struct {\n\ttime int\n\trequirements map[*Reward]int\n}\n\n\nfunc (weight *Weight) Time() int {\n\treturn weight.time\n}\n\n\n\n\n\nfunc (weight *Weight) AddRequirement(reward *Reward, quantity int) {\n\tweight.requirements[reward] = quantity\n}\n\n\nfunc CreateWeight(time int) *Weight {\n\tweight := new(Weight)\n\tweight.time = time\n\tweight.requirements = make(map[*Reward]int)\n\treturn weight\n}\n\n\ntype ByTime []*Weight\n\n\nfunc (a ByTime) Len() int {\n\treturn len(a)\n}\n\n\nfunc (a ByTime) Swap(i, j int) {\n\ta[i], a[j] = a[j], a[i]\n}\n\n\nfunc (a ByTime) Less(i, j int) bool {\n\treturn a[i].Time() < a[j].Time()\n}\n\nfunc (weight *Weight) Requirements() map[*Reward]int ", "output": "{\n\treturn weight.requirements\n}"} {"input": "package sqlmock\n\nimport (\n\t\"database/sql/driver\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype AnyTime struct{}\n\n\nfunc (a AnyTime) Match(v driver.Value) bool {\n\t_, ok := v.(time.Time)\n\treturn ok\n}\n\nfunc TestAnyTimeArgument(t *testing.T) {\n\tt.Parallel()\n\tdb, mock, err := New()\n\tif err != nil {\n\t\tt.Errorf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\tmock.ExpectExec(\"INSERT INTO users\").\n\t\tWithArgs(\"john\", AnyTime{}).\n\t\tWillReturnResult(NewResult(1, 1))\n\n\t_, err = db.Exec(\"INSERT INTO users(name, created_at) VALUES (?, ?)\", \"john\", time.Now())\n\tif err != nil {\n\t\tt.Errorf(\"error '%s' was not expected, while inserting a row\", err)\n\t}\n\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"there were unfulfilled expections: %s\", err)\n\t}\n}\n\n\n\nfunc TestByteSliceArgument(t *testing.T) ", "output": "{\n\tt.Parallel()\n\tdb, mock, err := New()\n\tif err != nil {\n\t\tt.Errorf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\tusername := []byte(\"user\")\n\tmock.ExpectExec(\"INSERT INTO users\").WithArgs(username).WillReturnResult(NewResult(1, 1))\n\n\t_, err = db.Exec(\"INSERT INTO users(username) VALUES (?)\", username)\n\tif err != nil {\n\t\tt.Errorf(\"error '%s' was not expected, while inserting a row\", err)\n\t}\n\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"there were unfulfilled expections: %s\", err)\n\t}\n}"} {"input": "package bar\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc Bar() ", "output": "{\n\tfmt.Sprintf(\"=(\")\n}"} {"input": "package router\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/docker/docker/api/server/httputils\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\ntype localRoute struct {\n\tmethod string\n\tpath string\n\thandler httputils.APIFunc\n}\n\n\nfunc (l localRoute) Handler() httputils.APIFunc {\n\treturn l.handler\n}\n\n\nfunc (l localRoute) Method() string {\n\treturn l.method\n}\n\n\nfunc (l localRoute) Path() string {\n\treturn l.path\n}\n\n\nfunc NewRoute(method, path string, handler httputils.APIFunc) Route {\n\treturn localRoute{method, path, handler}\n}\n\n\nfunc NewGetRoute(path string, handler httputils.APIFunc) Route {\n\treturn NewRoute(\"GET\", path, handler)\n}\n\n\nfunc NewPostRoute(path string, handler httputils.APIFunc) Route {\n\treturn NewRoute(\"POST\", path, handler)\n}\n\n\nfunc NewPutRoute(path string, handler httputils.APIFunc) Route {\n\treturn NewRoute(\"PUT\", path, handler)\n}\n\n\nfunc NewDeleteRoute(path string, handler httputils.APIFunc) Route {\n\treturn NewRoute(\"DELETE\", path, handler)\n}\n\n\nfunc NewOptionsRoute(path string, handler httputils.APIFunc) Route {\n\treturn NewRoute(\"OPTIONS\", path, handler)\n}\n\n\nfunc NewHeadRoute(path string, handler httputils.APIFunc) Route {\n\treturn NewRoute(\"HEAD\", path, handler)\n}\n\n\n\n\n\nfunc Cancellable(r Route) Route {\n\treturn localRoute{\n\t\tmethod: r.Method(),\n\t\tpath: r.Path(),\n\t\thandler: cancellableHandler(r.Handler()),\n\t}\n}\n\nfunc cancellableHandler(h httputils.APIFunc) httputils.APIFunc ", "output": "{\n\treturn func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {\n\t\tif notifier, ok := w.(http.CloseNotifier); ok {\n\t\t\tnotify := notifier.CloseNotify()\n\t\t\tnotifyCtx, cancel := context.WithCancel(ctx)\n\t\t\tfinished := make(chan struct{})\n\t\t\tdefer close(finished)\n\t\t\tctx = notifyCtx\n\t\t\tgo func() {\n\t\t\t\tselect {\n\t\t\t\tcase <-notify:\n\t\t\t\t\tcancel()\n\t\t\t\tcase <-finished:\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\treturn h(ctx, w, r, vars)\n\t}\n}"} {"input": "package errors_test\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/m3db/m3x/errors\"\n)\n\n\n\nfunc ExampleMultiError() ", "output": "{\n\tmultiErr := errors.NewMultiError()\n\n\tfor i := 0; i < 3; i++ {\n\t\terr := fmt.Errorf(\"error %d\", i)\n\n\t\tif err != nil {\n\t\t\tmultiErr = multiErr.Add(err)\n\t\t}\n\t}\n\n\tif err := multiErr.FinalError(); err != nil {\n\t\tmsg := strings.Replace(err.Error(), \"\\n\", \"; \", -1)\n\t\tfmt.Println(msg)\n\t}\n\n\tif err := multiErr.LastError(); err != nil {\n\t\tfmt.Println(err)\n\t}\n\n}"} {"input": "package models\n\nimport (\n\t\"github.com/macococo/go-gamereviews/utils\"\n)\n\ntype User struct {\n\tId int\n\tName string\n\tType int\n\tModel\n}\n\ntype UserManager struct {\n}\n\nfunc (this *UserManager) TableName() string {\n\treturn \"t_user\"\n}\n\nfunc (this *UserManager) AddTable() {\n\tDbMap.AddTableWithName(User{}, this.TableName()).SetKeys(true, \"Id\")\n}\n\nfunc (this *UserManager) Count(t int) int64 {\n\tcount, err := DbMap.SelectInt(\"SELECT count(*) FROM \"+this.TableName()+\" WHERE type = ?\", t)\n\tutils.HandleError(err)\n\n\treturn count\n}\n\n\n\nfunc (this *UserManager) Create(user *User) *User {\n\tutils.HandleError(DbMap.Insert(user))\n\treturn user\n}\n\nfunc (this *UserManager) Find(t int, pagination *Pagination) []*User ", "output": "{\n\tvar users []*User\n\t_, err := DbMap.Select(&users, \"SELECT * FROM \"+this.TableName()+\" WHERE type = ? LIMIT ?, ?\", t, (pagination.Page-1)*pagination.Length, pagination.Length)\n\tutils.HandleError(err)\n\n\treturn users\n}"} {"input": "package eventstreamapi\n\nimport (\n\t\"github.com/aws/aws-sdk-go/private/protocol\"\n\t\"github.com/aws/aws-sdk-go/private/protocol/eventstream\"\n)\n\n\n\ntype Marshaler interface {\n\tMarshalEvent(protocol.PayloadMarshaler) (eventstream.Message, error)\n}\n\n\n\ntype Encoder interface {\n\tEncode(eventstream.Message) error\n}\n\n\n\ntype EventWriter struct {\n\tencoder Encoder\n\tpayloadMarshaler protocol.PayloadMarshaler\n\teventTypeFor func(Marshaler) (string, error)\n}\n\n\n\nfunc NewEventWriter(encoder Encoder, pm protocol.PayloadMarshaler, eventTypeFor func(Marshaler) (string, error),\n) *EventWriter {\n\treturn &EventWriter{\n\t\tencoder: encoder,\n\t\tpayloadMarshaler: pm,\n\t\teventTypeFor: eventTypeFor,\n\t}\n}\n\n\n\nfunc (w *EventWriter) WriteEvent(event Marshaler) error {\n\tmsg, err := w.marshal(event)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn w.encoder.Encode(msg)\n}\n\n\n\nfunc (w *EventWriter) marshal(event Marshaler) (eventstream.Message, error) ", "output": "{\n\teventType, err := w.eventTypeFor(event)\n\tif err != nil {\n\t\treturn eventstream.Message{}, err\n\t}\n\n\tmsg, err := event.MarshalEvent(w.payloadMarshaler)\n\tif err != nil {\n\t\treturn eventstream.Message{}, err\n\t}\n\n\tmsg.Headers.Set(EventTypeHeader, eventstream.StringValue(eventType))\n\treturn msg, nil\n}"} {"input": "package header_test\n\nimport (\n\t\"testing\"\n\n\t\"gvisor.dev/gvisor/pkg/tcpip/header\"\n)\n\nfunc TestIPv4(t *testing.T) {\n\tb := header.IPv4(make([]byte, header.IPv4MinimumSize))\n\tb.Encode(&header.IPv4Fields{})\n\n\tconst want = header.IPv4Version\n\tif v := header.IPVersion(b); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}\n\n\n\nfunc TestOtherVersion(t *testing.T) {\n\tconst want = header.IPv4Version + header.IPv6Version\n\tb := make([]byte, 1)\n\tb[0] = want << 4\n\n\tif v := header.IPVersion(b); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}\n\nfunc TestTooShort(t *testing.T) {\n\tb := make([]byte, 1)\n\tb[0] = (header.IPv4Version + header.IPv6Version) << 4\n\n\tconst want = -1\n\tif v := header.IPVersion(b[:0]); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n\n\tif v := header.IPVersion(nil); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}\n\nfunc TestIPv6(t *testing.T) ", "output": "{\n\tb := header.IPv6(make([]byte, header.IPv6MinimumSize))\n\tb.Encode(&header.IPv6Fields{})\n\n\tconst want = header.IPv6Version\n\tif v := header.IPVersion(b); v != want {\n\t\tt.Fatalf(\"Bad version, want %v, got %v\", want, v)\n\t}\n}"} {"input": "package app\n\nimport (\n\t\"net/url\"\n)\n\ntype Service interface {\n\tProxyPath() string\n\tURL() string\n\tBasicAuth() (username, password string, ok bool)\n\tAddSecret(parameters url.Values)\n}\n\ntype basicAuthService struct {\n\tproxyPath, url, clientId, clientSecret string\n}\n\nfunc (s basicAuthService) ProxyPath() string {\n\treturn s.proxyPath\n}\n\nfunc (s basicAuthService) URL() string {\n\treturn s.url\n}\n\nfunc (s basicAuthService) BasicAuth() (string, string, bool) {\n\treturn s.clientId, s.clientSecret, true\n}\n\nfunc (s basicAuthService) AddSecret(parameters url.Values) {\n}\n\ntype addParameterService struct {\n\tproxyPath, url, parameterName, clientSecret string\n}\n\nfunc (s addParameterService) ProxyPath() string {\n\treturn s.proxyPath\n}\n\nfunc (s addParameterService) URL() string {\n\treturn s.url\n}\n\nfunc (s addParameterService) BasicAuth() (string, string, bool) {\n\treturn \"\", \"\", false\n}\n\nfunc (s addParameterService) AddSecret(parameters url.Values) {\n\tparameters.Add(s.parameterName, s.clientSecret)\n}\n\n\n\nfunc AddParameterService(proxyPath, url, parameterName, clientSecret string) Service {\n\treturn addParameterService{proxyPath, url, parameterName, clientSecret}\n}\n\nfunc BasicAuthService(proxyPath, url, clientId, clientSecret string) Service ", "output": "{\n\treturn basicAuthService{proxyPath, url, clientId, clientSecret}\n}"} {"input": "package core\n\nimport \"go/ast\"\n\nfunc resolveIdent(n *ast.Ident, c *Context) bool {\n\tif n.Obj == nil || n.Obj.Kind != ast.Var {\n\t\treturn true\n\t}\n\tif node, ok := n.Obj.Decl.(ast.Node); ok {\n\t\treturn TryResolve(node, c)\n\t}\n\treturn false\n}\n\nfunc resolveAssign(n *ast.AssignStmt, c *Context) bool {\n\tfor _, arg := range n.Rhs {\n\t\tif !TryResolve(arg, c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc resolveCompLit(n *ast.CompositeLit, c *Context) bool {\n\tfor _, arg := range n.Elts {\n\t\tif !TryResolve(arg, c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc resolveBinExpr(n *ast.BinaryExpr, c *Context) bool {\n\treturn (TryResolve(n.X, c) && TryResolve(n.Y, c))\n}\n\n\n\n\n\n\nfunc TryResolve(n ast.Node, c *Context) bool {\n\tswitch node := n.(type) {\n\tcase *ast.BasicLit:\n\t\treturn true\n\n\tcase *ast.CompositeLit:\n\t\treturn resolveCompLit(node, c)\n\n\tcase *ast.Ident:\n\t\treturn resolveIdent(node, c)\n\n\tcase *ast.AssignStmt:\n\t\treturn resolveAssign(node, c)\n\n\tcase *ast.CallExpr:\n\t\treturn resolveCallExpr(node, c)\n\n\tcase *ast.BinaryExpr:\n\t\treturn resolveBinExpr(node, c)\n\t}\n\n\treturn false\n}\n\nfunc resolveCallExpr(n *ast.CallExpr, c *Context) bool ", "output": "{\n\treturn false\n}"} {"input": "package goque\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"encoding/gob\"\n)\n\n\ntype Item struct {\n\tID uint64\n\tKey []byte\n\tValue []byte\n}\n\n\nfunc (i *Item) ToString() string {\n\treturn string(i.Value)\n}\n\n\n\n\n\n\n\nfunc (i *Item) ToObject(value interface{}) error {\n\tbuffer := bytes.NewBuffer(i.Value)\n\tdec := gob.NewDecoder(buffer)\n\treturn dec.Decode(value)\n}\n\n\ntype PriorityItem struct {\n\tID uint64\n\tPriority uint8\n\tKey []byte\n\tValue []byte\n}\n\n\nfunc (pi *PriorityItem) ToString() string {\n\treturn string(pi.Value)\n}\n\n\n\n\n\n\n\nfunc (pi *PriorityItem) ToObject(value interface{}) error {\n\tbuffer := bytes.NewBuffer(pi.Value)\n\tdec := gob.NewDecoder(buffer)\n\treturn dec.Decode(value)\n}\n\n\n\n\n\nfunc keyToID(key []byte) uint64 {\n\treturn binary.BigEndian.Uint64(key)\n}\n\nfunc idToKey(id uint64) []byte ", "output": "{\n\tkey := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(key, id)\n\treturn key\n}"} {"input": "package grpclog \n\nimport \"os\"\n\nvar logger = newLoggerV2()\n\n\nfunc V(l int) bool {\n\treturn logger.V(l)\n}\n\n\nfunc Info(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\nfunc Infof(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\nfunc Infoln(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\n\nfunc Warning(args ...interface{}) {\n\tlogger.Warning(args...)\n}\n\n\nfunc Warningf(format string, args ...interface{}) {\n\tlogger.Warningf(format, args...)\n}\n\n\nfunc Warningln(args ...interface{}) {\n\tlogger.Warningln(args...)\n}\n\n\nfunc Error(args ...interface{}) {\n\tlogger.Error(args...)\n}\n\n\nfunc Errorf(format string, args ...interface{}) {\n\tlogger.Errorf(format, args...)\n}\n\n\nfunc Errorln(args ...interface{}) {\n\tlogger.Errorln(args...)\n}\n\n\n\n\n\n\n\nfunc Fatalf(format string, args ...interface{}) {\n\tlogger.Fatalf(format, args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalln(args ...interface{}) {\n\tlogger.Fatalln(args...)\n\tos.Exit(1)\n}\n\n\n\n\nfunc Print(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\n\n\nfunc Printf(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\n\n\nfunc Println(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\nfunc Fatal(args ...interface{}) ", "output": "{\n\tlogger.Fatal(args...)\n\tos.Exit(1)\n}"} {"input": "package models\n\nimport (\n\t\"fmt\"\n\n\t\"google.golang.org/protobuf/reflect/protoreflect\"\n\t\"google.golang.org/protobuf/types/known/fieldmaskpb\"\n)\n\n\nfunc ValidateMask(message protoreflect.ProtoMessage, mask *fieldmaskpb.FieldMask) error {\n\tif mask == nil {\n\t\treturn nil\n\t}\n\n\tif len(mask.GetPaths()) == 1 && mask.Paths[0] == \"*\" {\n\t\treturn nil\n\t}\n\n\tunknowns := make([]string, 0)\n\tfor _, field := range mask.GetPaths() {\n\t\tif _, err := fieldmaskpb.New(message, field); err != nil {\n\t\t\tunknowns = append(unknowns, field)\n\t\t}\n\t}\n\n\tif len(unknowns) > 0 {\n\t\treturn fmt.Errorf(\"unrecognized fields %v\", unknowns)\n\t}\n\n\treturn nil\n}\n\n\n\n\n\n\nfunc populatedFields(m protoreflect.ProtoMessage) *fieldmaskpb.FieldMask {\n\tmask, _ := fieldmaskpb.New(m)\n\n\tm.ProtoReflect().Range(func(field protoreflect.FieldDescriptor, _ protoreflect.Value) bool {\n\t\t_ = mask.Append(m, string(field.Name()))\n\t\treturn true \n\t})\n\n\treturn mask\n}\n\nfunc allFields(m protoreflect.ProtoMessage) *fieldmaskpb.FieldMask {\n\tmask, _ := fieldmaskpb.New(m)\n\n\tfields := m.ProtoReflect().Descriptor().Fields()\n\tfor i := 0; i < fields.Len(); i++ {\n\t\t_ = mask.Append(m, string(fields.Get(i).Name()))\n\t}\n\n\treturn mask\n}\n\nfunc ExpandMask(m protoreflect.ProtoMessage, mask *fieldmaskpb.FieldMask) *fieldmaskpb.FieldMask ", "output": "{\n\tif mask == nil || len(mask.GetPaths()) == 0 {\n\t\treturn populatedFields(m)\n\t} else if len(mask.GetPaths()) == 1 && mask.Paths[0] == \"*\" {\n\t\treturn allFields(m)\n\t}\n\n\tmask.Normalize()\n\treturn mask\n}"} {"input": "package runtime\n\nimport (\n\t\"gopkg.in/v1/yaml\"\n)\n\n\n\n\n\n\n\nfunc (a *Object) UnmarshalJSON(b []byte) error {\n\tif len(b) == 4 && string(b) == \"null\" {\n\t\ta.Object = nil\n\t\treturn nil\n\t}\n\n\tobj, err := Decode(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.Object = obj\n\treturn nil\n}\n\n\n\n\n\nfunc (a *Object) SetYAML(tag string, value interface{}) bool {\n\tif value == nil {\n\t\ta.Object = nil\n\t\treturn true\n\t}\n\tb, err := yaml.Marshal(value)\n\tif err != nil {\n\t\tpanic(\"yaml can't reverse its own object\")\n\t}\n\tobj, err := Decode(b)\n\tif err != nil {\n\t\treturn false\n\t}\n\ta.Object = obj\n\treturn true\n}\n\n\nfunc (a Object) GetYAML() (tag string, value interface{}) {\n\tif a.Object == nil {\n\t\tvalue = \"null\"\n\t\treturn\n\t}\n\tv, err := Encode(a.Object)\n\tif err != nil {\n\t\tpanic(\"impossible to encode API object!\")\n\t}\n\treturn tag, v\n}\n\nfunc (a Object) MarshalJSON() ([]byte, error) ", "output": "{\n\tif a.Object == nil {\n\t\treturn []byte(\"null\"), nil\n\t}\n\n\treturn Encode(a.Object)\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/ParsePlatform/parse-cli/parsecli\"\n\t\"github.com/facebookgo/stackerr\"\n)\n\nfunc getConfirmation(message string, e *parsecli.Env) bool {\n\tfmt.Fprintf(e.Out, message)\n\tvar confirm string\n\tfmt.Fscanf(e.In, \"%s\\n\", &confirm)\n\tlower := strings.ToLower(confirm)\n\treturn lower != \"\" && strings.HasPrefix(lower, \"y\")\n}\n\n\n\nfunc validateURL(urlStr string) error ", "output": "{\n\tnetURL, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn stackerr.Wrap(err)\n\t}\n\n\tif netURL.Scheme != \"https\" {\n\t\treturn errors.New(\"Please enter a valid https url\")\n\t}\n\treturn nil\n}"} {"input": "package atom\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\ntype Truncater interface {\n\tTruncate(int64) error\n}\n\n\ntype File interface {\n\tio.Reader\n\tio.Writer\n\tio.Seeker\n\tio.Closer\n\n\tTruncater\n}\n\n\nfunc Open(name string) (File, error) {\n\ttmp, err := ioutil.TempFile(filepath.Dir(name), \".jump\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err := os.Stat(name); !os.IsNotExist(err) {\n\t\tfile, err := os.OpenFile(name, os.O_RDWR, 0644)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer file.Close()\n\n\t\t_, err = io.Copy(tmp, file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t_, err = tmp.Seek(0, 0)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &file{to: name, tmp: tmp}, nil\n}\n\ntype file struct {\n\tto string\n\ttmp *os.File\n\tdirty bool\n}\n\nfunc (f *file) Read(p []byte) (int, error) {\n\treturn f.tmp.Read(p)\n}\n\nfunc (f *file) Write(p []byte) (int, error) {\n\tn, err := f.tmp.Write(p)\n\tif err != nil {\n\t\tf.dirty = true\n\t}\n\n\treturn n, err\n}\n\nfunc (f *file) Seek(offset int64, whence int) (int64, error) {\n\treturn f.tmp.Seek(offset, whence)\n}\n\nfunc (f *file) Truncate(n int64) error {\n\treturn f.tmp.Truncate(n)\n}\n\n\n\nfunc (f *file) Close() error ", "output": "{\n\tif err := f.tmp.Close(); err != nil {\n\t\treturn err\n\t}\n\n\tif f.dirty {\n\t\treturn nil\n\t}\n\n\treturn os.Rename(f.tmp.Name(), f.to)\n}"} {"input": "package dax\n\n\ntype Grapher interface {\n\tGetParent() Grapher\n\tAddChild(child Grapher)\n\tGetChildren() []Grapher\n}\n\ntype nodeStack struct {\n\tnodes []Grapher\n}\n\nfunc (s *nodeStack) Init() {\n\ts.nodes = make([]Grapher, 0, 16)\n}\n\nfunc (s *nodeStack) Empty() bool {\n\treturn len(s.nodes) == 0\n}\n\nfunc (s *nodeStack) Push(n Grapher) {\n\ts.nodes = append(s.nodes, n)\n}\n\n\n\ntype SceneGraph struct {\n\tNode\n}\n\nfunc NewSceneGraph() *SceneGraph {\n\tsg := new(SceneGraph)\n\tsg.Init()\n\treturn sg\n}\n\nfunc (sg *SceneGraph) Init() {\n\tsg.Node.Init()\n}\n\nfunc (sg *SceneGraph) updateWorldTransform() {\n\tsg.Node.updateWorldTransform(false)\n}\n\nfunc (sg *SceneGraph) Update(time float64) {\n\tsg.updateWorldTransform()\n}\n\n\nfunc (sg *SceneGraph) Traverse() <-chan Grapher {\n\tch := make(chan Grapher)\n\n\tgo func() {\n\t\tvar stack nodeStack\n\n\t\tstack.Init()\n\t\tstack.Push(sg)\n\n\t\tfor !stack.Empty() {\n\t\t\tn := stack.Pop()\n\t\t\tch <- n\n\t\t\tchildren := n.GetChildren()\n\t\t\tfor i := len(children) - 1; i >= 0; i-- {\n\t\t\t\tstack.Push(children[i])\n\t\t\t}\n\t\t}\n\t\tclose(ch)\n\t}()\n\n\treturn ch\n}\n\nfunc (sg *SceneGraph) Draw(fb Framebuffer) {\n\tfb.render().drawSceneGraph(fb, sg)\n}\n\nfunc (s *nodeStack) Pop() Grapher ", "output": "{\n\ti := len(s.nodes) - 1\n\tn := s.nodes[i]\n\ts.nodes[i] = nil\n\ts.nodes = s.nodes[:i]\n\treturn n\n}"} {"input": "package logs\n\nconst (\n\tErrorLevel = iota\n\tWarnLevel\n\tInfoLevel\n\tDebugLevel\n)\n\ntype Level uint32\n\nfunc (l Level) EQ(lv Level) bool {\n\tif l == lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) LTE(lv Level) bool {\n\tif l <= lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\n\nfunc (l Level) GTE(lv Level) bool {\n\tif l >= lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) GT(lv Level) bool {\n\tif l > lv {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l Level) Color() int {\n\tvar levelColor int\n\tswitch l {\n\tcase DebugLevel:\n\t\tlevelColor = 32\n\tcase InfoLevel:\n\t\tlevelColor = 36\n\tcase WarnLevel:\n\t\tlevelColor = 33\n\tcase ErrorLevel:\n\t\tlevelColor = 31\n\tdefault:\n\t\tlevelColor = 0\n\t}\n\treturn levelColor\n}\n\nfunc (l Level) String() string {\n\tswitch l {\n\tcase DebugLevel:\n\t\treturn \"DEBU\"\n\tcase InfoLevel:\n\t\treturn \"INFO\"\n\tcase WarnLevel:\n\t\treturn \"WARN\"\n\tcase ErrorLevel:\n\t\treturn \"ERRO\"\n\t}\n\treturn \" \"\n}\n\nfunc (l Level) LT(lv Level) bool ", "output": "{\n\tif l < lv {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package search\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\nvar registry *Registry\nvar registryOnce sync.Once\n\n\nfunc GlobalRegistry() *Registry {\n\tregistryOnce.Do(func() {\n\t\tregistry = new(Registry)\n\t\tregistry.infos = make(map[string]map[string]SearchParamInfo)\n\t\tregistry.parsers = make(map[string]ParameterParser)\n\t})\n\treturn registry\n}\n\n\n\ntype Registry struct {\n\tinfosLock sync.RWMutex\n\tinfos map[string]map[string]SearchParamInfo\n\tparsersLock sync.RWMutex\n\tparsers map[string]ParameterParser\n}\n\n\n\n\n\n\n\n\nfunc (r *Registry) LookupParameterInfo(resource, name string) (param SearchParamInfo, err error) {\n\tr.infosLock.RLock()\n\tdefer r.infosLock.RUnlock()\n\tparam, ok := r.infos[resource][name]\n\tif !ok {\n\t\treturn SearchParamInfo{}, fmt.Errorf(\"Could not find info for parameter %s for resource %s\", name, resource)\n\t}\n\treturn param, nil\n}\n\n\nfunc (r *Registry) RegisterParameterParser(paramType string, parser ParameterParser) {\n\tr.parsersLock.Lock()\n\tdefer r.parsersLock.Unlock()\n\tr.parsers[paramType] = parser\n}\n\n\nfunc (r *Registry) LookupParameterParser(paramType string) (parser ParameterParser, err error) {\n\tr.parsersLock.RLock()\n\tdefer r.parsersLock.RUnlock()\n\tp, ok := r.parsers[paramType]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Could not find parameter parser for %s\", paramType)\n\t}\n\treturn p, nil\n}\n\n\ntype ParameterParser func(info SearchParamInfo, data SearchParamData) (SearchParam, error)\n\nfunc (r *Registry) RegisterParameterInfo(param SearchParamInfo) ", "output": "{\n\tr.infosLock.Lock()\n\tdefer r.infosLock.Unlock()\n\trMap, ok := r.infos[param.Resource]\n\tif !ok {\n\t\trMap = make(map[string]SearchParamInfo)\n\t\tr.infos[param.Resource] = rMap\n\t}\n\trMap[param.Name] = param\n\n\trMap, ok = SearchParameterDictionary[param.Resource]\n\tif !ok {\n\t\trMap = make(map[string]SearchParamInfo)\n\t\tSearchParameterDictionary[param.Resource] = rMap\n\t}\n\trMap[param.Name] = param\n}"} {"input": "package main\n\nimport (\n \"time\"\n \"net/http\"\n \"io/ioutil\"\n \"strings\"\n\n \"launchpad.net/gocheck\"\n \"github.com/mreiferson/go-httpclient\"\n)\n\nconst url string = \"http://127.0.0.1:8080\"\n\nfunc setupHivy() {\n \n go hivy(url, false)\n}\n\nfunc sendHTTPRequest(method, endpoint, user, pass string) (*http.Response, error){\n transport := &httpclient.Transport{\n ConnectTimeout: 1*time.Second,\n RequestTimeout: 10*time.Second,\n ResponseHeaderTimeout: 5*time.Second,\n }\n defer transport.Close()\n\n client := &http.Client{Transport: transport}\n prefix := \"/v0/actions\"\n req, _ := http.NewRequest(method, url + prefix + endpoint, nil)\n req.SetBasicAuth(user, pass)\n\n \n return client.Do(req)\n}\n\nfunc (t *testSuite) TestHivyDummy() {\n resp, err := sendHTTPRequest(\"GET\", \"/dummy\", \"xav\", \"boss\")\n defer resp.Body.Close()\n t.Check(err, gocheck.IsNil)\n\n contents, err := ioutil.ReadAll(resp.Body)\n t.Check(err, gocheck.IsNil)\n\n t.True(strings.Contains(string(contents), \"dummy\"))\n \n}\n\n\n\nfunc (t *testSuite) TestBadAuthentification() ", "output": "{\n resp, err := sendHTTPRequest(\"GET\", \"/dummy\", \"wrong\", \"login\")\n defer resp.Body.Close()\n t.Check(err, gocheck.IsNil)\n\n contents, err := ioutil.ReadAll(resp.Body)\n t.Check(err, gocheck.IsNil)\n\n t.True(strings.Contains(string(contents), \"Key Not Found\"))\n \n}"} {"input": "package manifestparser\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype Locator struct {\n\tFilesToCheckFor []string\n}\n\nfunc NewLocator() *Locator {\n\treturn &Locator{\n\t\tFilesToCheckFor: []string{\n\t\t\t\"manifest.yml\",\n\t\t\t\"manifest.yaml\",\n\t\t},\n\t}\n}\n\n\n\nfunc (loc Locator) handleDir(dir string) (string, bool, error) {\n\tfor _, filename := range loc.FilesToCheckFor {\n\t\tfullPath := filepath.Join(dir, filename)\n\t\tif _, err := os.Stat(fullPath); err == nil {\n\t\t\treturn fullPath, true, nil\n\t\t} else if !os.IsNotExist(err) {\n\t\t\treturn \"\", false, err\n\t\t}\n\t}\n\n\treturn \"\", false, nil\n}\n\nfunc (Locator) handleFilepath(filepath string) (string, bool, error) {\n\treturn filepath, true, nil\n}\n\nfunc (loc Locator) Path(filepathOrDirectory string) (string, bool, error) ", "output": "{\n\tinfo, err := os.Stat(filepathOrDirectory)\n\tif os.IsNotExist(err) {\n\t\treturn \"\", false, nil\n\t} else if err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tresolvedFilepathOrDirectory, err := filepath.EvalSymlinks(filepathOrDirectory)\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tif info.IsDir() {\n\t\treturn loc.handleDir(resolvedFilepathOrDirectory)\n\t}\n\n\treturn loc.handleFilepath(resolvedFilepathOrDirectory)\n}"} {"input": "package conn\n\nimport (\n\t\"os\"\n\t\"strings\"\n\n\treuseport \"github.com/djbarber/ipfs-hack/Godeps/_workspace/src/github.com/jbenet/go-reuseport\"\n)\n\n\n\nconst envReuseport = \"IPFS_REUSEPORT\"\n\n\nvar envReuseportVal = true\n\nfunc init() {\n\tv := strings.ToLower(os.Getenv(envReuseport))\n\tif v == \"false\" || v == \"f\" || v == \"0\" {\n\t\tenvReuseportVal = false\n\t\tlog.Infof(\"REUSEPORT disabled (IPFS_REUSEPORT=%s)\", v)\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc reuseportIsAvailable() bool ", "output": "{\n\treturn envReuseportVal && reuseport.Available()\n}"} {"input": "package protobuf\n\nimport (\n\t\"encoding/binary\"\n\n\tc \"github.com/couchbase/indexing/secondary/common\"\n)\n\nfunc (pl *Payload) Value() interface{} {\n\tif pl.Vbmap != nil {\n\t\treturn pl.Vbmap\n\t} else if pl.Vbkeys != nil {\n\t\treturn pl.Vbkeys\n\t}\n\treturn nil\n}\n\n\n\nfunc (kv *KeyVersions) Snapshot() (typ uint32, start, end uint64) ", "output": "{\n\tuuids := kv.GetUuids()\n\tkeys := kv.GetKeys()\n\toldkeys := kv.GetOldkeys()\n\tfor i, cmd := range kv.GetCommands() {\n\t\tif byte(cmd) == c.Snapshot {\n\t\t\ttyp = uint32(uuids[i])\n\t\t\tstart = binary.BigEndian.Uint64(keys[i])\n\t\t\tend = binary.BigEndian.Uint64(oldkeys[i])\n\t\t}\n\t}\n\treturn\n}"} {"input": "package driver\n\nimport (\n\t\"github.com/Azure/azure-docker-extension/pkg/executil\"\n)\n\ntype ubuntuBaseDriver struct{}\n\nfunc (u ubuntuBaseDriver) InstallDocker() error {\n\treturn executil.ExecPipe(\"/bin/sh\", \"-c\", \"wget -qO- https://get.docker.com/ | sh\")\n}\n\nfunc (u ubuntuBaseDriver) UninstallDocker() error {\n\tif err := executil.ExecPipe(\"apt-get\", \"-qqy\", \"purge\", \"docker-engine\"); err != nil {\n\t\treturn err\n\t}\n\treturn executil.ExecPipe(\"apt-get\", \"-qqy\", \"autoremove\")\n}\n\n\n\nfunc (u ubuntuBaseDriver) DockerComposeDir() string ", "output": "{ return \"/usr/local/bin\" }"} {"input": "package tracer_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/altairsix/pkg/tracer\"\n\t\"github.com/opentracing/opentracing-go\"\n\t\"github.com/opentracing/opentracing-go/log\"\n)\n\n\n\nfunc TestMulti(t *testing.T) ", "output": "{\n\tfunc() {\n\t\tmulti := tracer.Multi(tracer.DefaultTracer)\n\n\t\tparent := multi.StartSpan(\"Parent\")\n\t\tfor i := 0; i < 20; i++ {\n\t\t\tparent.LogFields(log.Int(\"starting_child\", i))\n\t\t\tchild := multi.StartSpan(\"Child\", opentracing.ChildOf(parent.Context()))\n\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\tchild.Finish()\n\t\t}\n\t\tparent.Finish()\n\t}()\n\ttime.Sleep(time.Millisecond * 150)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"labix.org/v2/mgo\"\n)\n\n\n\n\n\ntype MgoConsistencyMode int\n\nfunc (mcm *MgoConsistencyMode) MarshalGoptions(val string) error {\n\tswitch strings.ToUpper(val) {\n\tcase \"STRONG\":\n\t\t*mcm = MgoConsistencyMode(mgo.Strong)\n\tcase \"MONOTONIC\":\n\t\t*mcm = MgoConsistencyMode(mgo.Monotonic)\n\tcase \"EVENTUAL\":\n\t\t*mcm = MgoConsistencyMode(mgo.Eventual)\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown consistency type \\\"%s\\\"\", val)\n\t}\n\treturn nil\n}\n\nfunc (mcm *MgoConsistencyMode) String() string {\n\tswitch MgoConsistencyMode(*mcm) {\n\tcase MgoConsistencyMode(mgo.Strong):\n\t\treturn \"STRONG\"\n\tcase MgoConsistencyMode(mgo.Monotonic):\n\t\treturn \"MONOTONIC\"\n\tcase MgoConsistencyMode(mgo.Eventual):\n\t\treturn \"EVENTUAL\"\n\t}\n\treturn \"INVALID\"\n}\n\n\n\nfunc (mcm *MgoConsistencyMode) Apply(s *mgo.Session) ", "output": "{\n\tswitch MgoConsistencyMode(*mcm) {\n\tcase MgoConsistencyMode(mgo.Strong):\n\t\ts.SetMode(mgo.Strong, true)\n\tcase MgoConsistencyMode(mgo.Monotonic):\n\t\ts.SetMode(mgo.Monotonic, true)\n\tcase MgoConsistencyMode(mgo.Eventual):\n\t\ts.SetMode(mgo.Eventual, true)\n\t}\n}"} {"input": "package object\n\nimport ()\n\nconst (\n\tSVC_HOST_NAME = \"host_name\"\n\tSVC_HOSTGROUP_NAME = \"hostgroup_name\"\n)\n\nvar serviceRegularProperties = []string{\n\t\"action_url\",\n\t\"active_checks_enabled\",\n\t\"check_command\",\n\t\"check_freshness\",\n\t\"check_interval\",\n\t\"check_period\",\n\t\"display_name\",\n\t\"event_handler\",\n\t\"event_handler_enabled\",\n\t\"first_notification_delay\",\n\t\"flap_detection_enabled\",\n\t\"freshness_threshold\",\n\t\"high_flap_threshold\",\n\t\"icon_image\",\n\t\"icon_image_alt\",\n\t\"is_volatile\",\n\t\"low_flap_threshold\",\n\t\"max_check_attempts\",\n\t\"name\",\n\t\"notes\",\n\t\"notes_url\",\n\t\"notification_interval\",\n\t\"notification_period\",\n\t\"notifications_enabled\",\n\t\"obsess_over_service\",\n\t\"passive_checks_enabled\",\n\t\"process_perf_data\",\n\t\"register\",\n\t\"retain_nonstatus_information\",\n\t\"retain_status_information\",\n\t\"retry_interval\",\n\t\"service_description\",\n}\n\nvar serviceListProperties = []string{\n\t\"contact_groups\",\n\t\"contacts\",\n\t\"servicegroups\",\n\t\"use\",\n\tSVC_HOST_NAME,\n\tSVC_HOSTGROUP_NAME,\n}\n\nvar serviceEnumProperties = map[string]Set{\n\t\"stalking_options\": NewSet(\"o\", \"w\", \"u\", \"c\"),\n\t\"flap_detection_options\": NewSet(\"o\", \"w\", \"c\", \"u\"),\n\t\"notification_options\": NewSet(\"w\", \"u\", \"c\", \"r\", \"f\", \"s\"),\n\t\"initial_state\": NewSet(\"o\", \"w\", \"u\", \"c\"),\n}\n\n\n\nfunc NewService(properties map[string]string) Object ", "output": "{\n\ts := new(object)\n\ts.init(\"service\")\n\ts.fill(properties, serviceRegularProperties, serviceListProperties, serviceEnumProperties)\n\treturn s\n}"} {"input": "package wml\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\ntype CT_Markup struct {\n\tIdAttr int64\n}\n\nfunc NewCT_Markup() *CT_Markup {\n\tret := &CT_Markup{}\n\treturn ret\n}\n\nfunc (m *CT_Markup) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"w:id\"},\n\t\tValue: fmt.Sprintf(\"%v\", m.IdAttr)})\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}\n\n\n\n\nfunc (m *CT_Markup) Validate() error {\n\treturn m.ValidateWithPath(\"CT_Markup\")\n}\n\n\nfunc (m *CT_Markup) ValidateWithPath(path string) error {\n\treturn nil\n}\n\nfunc (m *CT_Markup) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error ", "output": "{\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"id\" {\n\t\t\tparsed, err := strconv.ParseInt(attr.Value, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.IdAttr = parsed\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_Markup: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package nogo\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype mapBackedRoleRepository struct {\n\troleMap map[string]Role\n}\n\nfunc NewMapBackedRoleRepository() RoleRepository {\n\treturn &mapBackedRoleRepository{roleMap: make(map[string]Role)}\n}\n\nfunc (this *mapBackedRoleRepository) FindAll() ([]Role, error) {\n\tret := make([]Role, 0)\n\tfor _, role := range this.roleMap {\n\t\tret = append(ret, role)\n\t}\n\treturn ret, nil\n}\n\n\n\nfunc (this *mapBackedRoleRepository) CreateRole(role Role) error {\n\tif _, ok := this.roleMap[role.GetName()]; ok {\n\t\treturn errors.New(fmt.Sprintf(\"Error creating role. Role %v already exists\", role.GetName()))\n\t}\n\tthis.roleMap[role.GetName()] = role\n\treturn nil\n}\n\nfunc (this *mapBackedRoleRepository) UpdateRole(role Role) error {\n\tif _, ok := this.roleMap[role.GetName()]; ok {\n\t\tthis.roleMap[role.GetName()] = role\n\t\treturn nil\n\t}\n\treturn errors.New(fmt.Sprintf(\"Error updating role. Role %v does not exist.\", role.GetName()))\n}\n\nfunc (this *mapBackedRoleRepository) DeleteRole(roleName string) error {\n\tif _, ok := this.roleMap[roleName]; ok {\n\t\tdelete(this.roleMap, roleName)\n\t}\n\treturn errors.New(fmt.Sprintf(\"Error deleting role. Role %v does not exist.\", roleName))\n}\n\nfunc (this *mapBackedRoleRepository) FindRole(roleName string) (Role, error) ", "output": "{\n\tif role, ok := this.roleMap[roleName]; ok {\n\t\treturn role, nil\n\t}\n\treturn nil, errors.New(fmt.Sprintf(\"Could not find role %v\", roleName))\n}"} {"input": "package transport\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"net/http\"\n)\n\n\ntype Config struct {\n\tUserAgent string\n\n\tTLS TLSConfig\n\n\tUsername string\n\tPassword string\n\n\tBearerToken string\n\n\tImpersonate ImpersonationConfig\n\n\tTransport http.RoundTripper\n\n\tWrapTransport func(rt http.RoundTripper) http.RoundTripper\n\n\tDial func(ctx context.Context, network, address string) (net.Conn, error)\n}\n\n\ntype ImpersonationConfig struct {\n\tUserName string\n\tGroups []string\n\tExtra map[string][]string\n}\n\n\n\n\n\nfunc (c *Config) HasBasicAuth() bool {\n\treturn len(c.Username) != 0\n}\n\n\nfunc (c *Config) HasTokenAuth() bool {\n\treturn len(c.BearerToken) != 0\n}\n\n\nfunc (c *Config) HasCertAuth() bool {\n\treturn len(c.TLS.CertData) != 0 || len(c.TLS.CertFile) != 0\n}\n\n\ntype TLSConfig struct {\n\tCAFile string \n\tCertFile string \n\tKeyFile string \n\n\tInsecure bool \n\tServerName string \n\n\tCAData []byte \n\tCertData []byte \n\tKeyData []byte \n}\n\nfunc (c *Config) HasCA() bool ", "output": "{\n\treturn len(c.TLS.CAData) > 0 || len(c.TLS.CAFile) > 0\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\nfunc TestDiscovery(t *testing.T) {\n\tdiscoveryStr := \"redis://root@127.0.0.1:6379/dragonfly/master\"\n\tdiscovery := new(Discovery)\n\terr := discovery.parse(discoveryStr)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\n\n\nfunc TestServer(t *testing.T) {\n\tsm := new(ServerManage)\n\tdiscoveryStr := \"redis://root@127.0.0.1:6379/dragonfly/master\"\n\tdiscovery := new(Discovery)\n\tdiscovery.parse(discoveryStr)\n\tadvertiseStr := \"127.0.0.1\"\n\tadvertise := new(Advertise)\n\tadvertise.parse(advertiseStr)\n\tserver, err := discovery.init()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tsm.server = server\n\tsm.quit = make(chan bool)\n\tsm.clear = make(chan bool)\n\tsm.run(advertise)\n\tsm.stop()\n}\n\nfunc TestAdvertise(t *testing.T) ", "output": "{\n\tadvertiseStr := \"127.0.0.1\"\n\tadvertise := new(Advertise)\n\terr := advertise.parse(advertiseStr)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"launchpad.net/gnuflag\"\n\n\t\"launchpad.net/juju-core/cmd\"\n\t\"launchpad.net/juju-core/store\"\n)\n\n\ntype ConfigCommand struct {\n\tcmd.CommandBase\n\tConfigPath string\n\tConfig *store.Config\n}\n\ntype CharmdConfig struct {\n\tMongoUrl string `yaml:\"mongo-url\"`\n}\n\nfunc (c *ConfigCommand) SetFlags(f *gnuflag.FlagSet) {\n\tf.StringVar(&c.ConfigPath, \"config\", \"\", \"charmd configuration file\")\n}\n\nfunc (c *ConfigCommand) Init(args []string) error {\n\tif c.ConfigPath == \"\" {\n\t\treturn fmt.Errorf(\"--config is required\")\n\t}\n\treturn nil\n}\n\n\n\nfunc (c *ConfigCommand) ReadConfig(ctx *cmd.Context) (err error) ", "output": "{\n\tc.Config, err = store.ReadConfig(ctx.AbsPath(c.ConfigPath))\n\treturn err\n}"} {"input": "package changes\n\nimport \"github.com/m3db/m3metrics/rules/view\"\n\n\ntype MappingRuleChange struct {\n\tOp Op `json:\"op\"`\n\tRuleID *string `json:\"ruleID,omitempty\"`\n\tRuleData *view.MappingRule `json:\"ruleData,omitempty\"`\n}\n\ntype mappingRuleChangesByOpAscNameAscIDAsc []MappingRuleChange\n\nfunc (a mappingRuleChangesByOpAscNameAscIDAsc) Len() int { return len(a) }\nfunc (a mappingRuleChangesByOpAscNameAscIDAsc) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\n\n\nfunc (a mappingRuleChangesByOpAscNameAscIDAsc) Less(i, j int) bool ", "output": "{\n\tif a[i].Op < a[j].Op {\n\t\treturn true\n\t}\n\tif a[i].Op > a[j].Op {\n\t\treturn false\n\t}\n\tif a[i].RuleData != nil && a[j].RuleData != nil {\n\t\treturn a[i].RuleData.Name < a[j].RuleData.Name\n\t}\n\tif a[i].RuleID != nil && a[j].RuleID != nil {\n\t\treturn *a[i].RuleID < *a[j].RuleID\n\t}\n\treturn false\n}"} {"input": "package echo\n\ntype (\n\tGroup struct {\n\t\techo Echo\n\t}\n)\n\nfunc (g *Group) Use(m ...Middleware) {\n\tfor _, h := range m {\n\t\tg.echo.middleware = append(g.echo.middleware, wrapMiddleware(h))\n\t}\n}\n\nfunc (g *Group) Connect(path string, h Handler) {\n\tg.echo.Connect(path, h)\n}\n\nfunc (g *Group) Delete(path string, h Handler) {\n\tg.echo.Delete(path, h)\n}\n\nfunc (g *Group) Get(path string, h Handler) {\n\tg.echo.Get(path, h)\n}\n\nfunc (g *Group) Head(path string, h Handler) {\n\tg.echo.Head(path, h)\n}\n\nfunc (g *Group) Options(path string, h Handler) {\n\tg.echo.Options(path, h)\n}\n\nfunc (g *Group) Patch(path string, h Handler) {\n\tg.echo.Patch(path, h)\n}\n\nfunc (g *Group) Post(path string, h Handler) {\n\tg.echo.Post(path, h)\n}\n\nfunc (g *Group) Put(path string, h Handler) {\n\tg.echo.Put(path, h)\n}\n\nfunc (g *Group) Trace(path string, h Handler) {\n\tg.echo.Trace(path, h)\n}\n\nfunc (g *Group) WebSocket(path string, h HandlerFunc) {\n\tg.echo.WebSocket(path, h)\n}\n\n\n\nfunc (g *Group) ServeDir(path, root string) {\n\tg.echo.ServeDir(path, root)\n}\n\nfunc (g *Group) ServeFile(path, file string) {\n\tg.echo.ServeFile(path, file)\n}\n\nfunc (g *Group) Group(prefix string, m ...Middleware) *Group {\n\treturn g.echo.Group(prefix, m...)\n}\n\nfunc (g *Group) Static(path, root string) ", "output": "{\n\tg.echo.Static(path, root)\n}"} {"input": "package test\n\nimport (\n\t\"io\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n\ntype KafkaExecutor struct {\n\tZookeeperURI string\n\tKafkaDirectory string\n\tKafkaURI string\n\tOutputWriter io.Writer\n}\n\n\nfunc (e *KafkaExecutor) CreateTopic(topic string) error {\n\tcmd := exec.Command(\n\t\tfilepath.Join(e.KafkaDirectory, \"bin\", \"kafka-topics.sh\"),\n\t\t\"--create\",\n\t\t\"--zookeeper\", e.ZookeeperURI,\n\t\t\"--replication-factor\", \"1\",\n\t\t\"--partitions\", \"1\",\n\t\t\"--topic\", topic,\n\t)\n\tcmd.Stdout = e.OutputWriter\n\tcmd.Stderr = e.OutputWriter\n\treturn cmd.Run()\n}\n\n\n\n\n\nfunc (e *KafkaExecutor) DeleteTopic(topic string) error {\n\tcmd := exec.Command(\n\t\tfilepath.Join(e.KafkaDirectory, \"bin\", \"kafka-topics.sh\"),\n\t\t\"--delete\",\n\t\t\"--if-exists\",\n\t\t\"--zookeeper\", e.ZookeeperURI,\n\t\t\"--topic\", topic,\n\t)\n\tcmd.Stderr = e.OutputWriter\n\tcmd.Stdout = e.OutputWriter\n\treturn cmd.Run()\n}\n\nfunc (e *KafkaExecutor) WriteToTopic(topic string, data []string) error ", "output": "{\n\tcmd := exec.Command(\n\t\tfilepath.Join(e.KafkaDirectory, \"bin\", \"kafka-console-producer.sh\"),\n\t\t\"--broker-list\", e.KafkaURI,\n\t\t\"--topic\", topic,\n\t)\n\tcmd.Stdout = e.OutputWriter\n\tcmd.Stderr = e.OutputWriter\n\tcmd.Stdin = strings.NewReader(strings.Join(data, \"\\n\"))\n\treturn cmd.Run()\n}"} {"input": "package api\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n)\n\nfunc handleInternalServerError(w http.ResponseWriter) {\n\thttp.Error(w, http.StatusText(http.StatusInternalServerError),\n\t\thttp.StatusInternalServerError)\n}\n\n\n\n\nfunc writeJSON(w http.ResponseWriter, v interface{}) error {\n\tb, err := json.Marshal(v)\n\tif err != nil {\n\t\thandleInternalServerError(w)\n\t\treturn err\n\t}\n\n\tif _, err = w.Write(b); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc handleUnauthorized(w http.ResponseWriter) ", "output": "{\n\thttp.Error(w, http.StatusText(http.StatusUnauthorized),\n\t\thttp.StatusUnauthorized)\n}"} {"input": "package executedconditionals\n\nfunc a(condition bool) string {\n\tif condition {\n\t\treturn \"A\"\n\t}\n\treturn \"A\"\n}\n\nfunc b() string {\n\treturn \"B\"\n}\n\n\n\nfunc wrapper(condition bool) {\n\ta(condition)\n\tb()\n\tc()\n}\n\nfunc c() string ", "output": "{\n\treturn \"C\"\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/gabriel-comeau/SimpleChatCommon\"\n\t\"github.com/gabriel-comeau/tbuikit\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\nfunc createMessageForBroadCast(text string, sender *ChatClient) *tbuikit.ColorizedString {\n\tformatted := formatBroadCastMessage(text, sender)\n\tmsg := SimpleChatCommon.Create(formatted, sender.color)\n\treturn msg\n}\n\n\nfunc formatBroadCastMessage(message string, sender *ChatClient) string {\n\tmessage = strings.Trim(message, \" \\n\")\n\tvar output string\n\tif sender.nick != \"\" {\n\t\toutput = fmt.Sprintf(\"%v: %v\", sender.nick, message)\n\t} else {\n\t\toutput = fmt.Sprintf(\"%v: %v\", sender.id, message)\n\t}\n\n\treturn output\n}\n\n\n\n\n\nfunc nickTaken(n string, holder *ClientHolder) bool {\n\tfor _, c := range clientHolder.getClients() {\n\t\tif c.nick == n {\n\t\t\treturn true\n\t\t} else if n == strconv.FormatUint(c.id, 10) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc formatWhisperMessage(message string, sender *ChatClient) string ", "output": "{\n\tmessage = strings.Trim(message, \" \\n\")\n\tvar output string\n\tif sender.nick != \"\" {\n\t\toutput = fmt.Sprintf(\" %v: %v\", sender.nick, message)\n\t} else {\n\t\toutput = fmt.Sprintf(\" %v: %v\", sender.id, message)\n\t}\n\n\treturn output\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\nfunc setTimespec(sec, nsec int64) Timespec {\n\treturn Timespec{Sec: sec, Nsec: nsec}\n}\n\nfunc setTimeval(sec, usec int64) Timeval {\n\treturn Timeval{Sec: sec, Usec: usec}\n}\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint64(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint64(length)\n}\n\n\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\nfunc (msghdr *Msghdr) SetControllen(length int) ", "output": "{\n\tmsghdr.Controllen = uint32(length)\n}"} {"input": "package sarif\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"net\"\n\t\"time\"\n)\n\ntype netConn struct {\n\tconn net.Conn\n\tenc *json.Encoder\n\tdec *json.Decoder\n\tverified bool\n}\n\nfunc newNetConn(conn net.Conn) *netConn {\n\treturn &netConn{\n\t\tconn,\n\t\tjson.NewEncoder(conn),\n\t\tjson.NewDecoder(conn),\n\t\tfalse,\n\t}\n}\n\n\n\nfunc (c *netConn) KeepaliveLoop(ka time.Duration) error {\n\tfor {\n\t\ttime.Sleep(ka)\n\t\tc.conn.SetWriteDeadline(time.Now().Add(3 * ka))\n\t\tif _, err := c.conn.Write([]byte(\" \")); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\nfunc (c *netConn) Read() (Message, error) {\n\tvar msg Message\n\tc.conn.SetReadDeadline(time.Now().Add(time.Hour))\n\tif err := c.dec.Decode(&msg); err != nil {\n\t\treturn msg, err\n\t}\n\treturn msg, msg.IsValid()\n}\n\nfunc (c *netConn) Close() error {\n\treturn c.conn.Close()\n}\n\nfunc (c *netConn) IsVerified() bool {\n\tif tc, ok := c.conn.(*tls.Conn); ok {\n\t\tif len(tc.ConnectionState().VerifiedChains) > 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (c *netConn) Write(msg Message) error ", "output": "{\n\tif err := msg.IsValid(); err != nil {\n\t\treturn err\n\t}\n\tc.conn.SetWriteDeadline(time.Now().Add(5 * time.Minute))\n\treturn c.enc.Encode(msg)\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aws/aws-sdk-go/private/protocol\"\n)\n\ntype examplesBuilder interface {\n\tBuildShape(*ShapeRef, map[string]interface{}, bool) string\n\tBuildList(string, string, *ShapeRef, []interface{}) string\n\tBuildComplex(string, string, *ShapeRef, *Shape, map[string]interface{}) string\n\tGoType(*ShapeRef, bool) string\n\tImports(*API) string\n}\n\ntype defaultExamplesBuilder struct {\n\tShapeValueBuilder\n}\n\n\n\n\n\nfunc (builder defaultExamplesBuilder) Imports(a *API) string {\n\treturn `\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"` + SDKImportRoot + `/aws\"\n\t\"` + SDKImportRoot + `/aws/awserr\"\n\t\"` + SDKImportRoot + `/aws/session\"\n\t\"` + a.ImportPath() + `\"\n\t`\n}\n\n\n\nfunc parseExampleTimeString(ref *ShapeRef, memName, v string) string {\n\tif ref.Location == \"header\" {\n\t\treturn fmt.Sprintf(\"%s: parseTime(%q, %q),\\n\", memName, protocol.RFC822TimeFormat, v)\n\t}\n\n\tswitch ref.API.Metadata.Protocol {\n\tcase \"json\", \"rest-json\", \"rest-xml\", \"ec2\", \"query\":\n\t\treturn fmt.Sprintf(\"%s: parseTime(%q, %q),\\n\", memName, protocol.ISO8601TimeFormat, v)\n\tdefault:\n\t\tpanic(\"Unsupported time type: \" + ref.API.Metadata.Protocol)\n\t}\n}\n\nfunc NewExamplesBuilder() defaultExamplesBuilder ", "output": "{\n\tb := defaultExamplesBuilder{\n\t\tShapeValueBuilder: NewShapeValueBuilder(),\n\t}\n\tb.ParseTimeString = parseExampleTimeString\n\treturn b\n}"} {"input": "package astutils\n\nimport (\n\t\"go/ast\"\n\t\"go/types\"\n)\n\n\nfunc FieldListName(fieldList *ast.FieldList, fieldPosition int, namePosition int) *string {\n\tnames := FieldListNames(fieldList, fieldPosition)\n\n\tif names == nil || len(names) <= namePosition {\n\t\treturn nil\n\t}\n\n\tname := names[namePosition]\n\n\tif name == nil {\n\t\treturn nil\n\t}\n\n\treturn &name.Name\n}\n\n\n\n\n\nfunc FieldListType(fieldList *ast.FieldList, position int) *ast.Expr {\n\tif fieldList == nil {\n\t\treturn nil\n\t}\n\n\tif len(fieldList.List) <= position {\n\t\treturn nil\n\t}\n\n\tfield := fieldList.List[position]\n\n\tif field == nil {\n\t\treturn nil\n\t}\n\n\treturn &field.Type\n}\n\n\n\nfunc HasFieldListLength(fieldList *ast.FieldList, expectedLength int) bool {\n\tif fieldList == nil {\n\t\treturn expectedLength == 0\n\t}\n\n\treturn len(fieldList.List) == expectedLength\n}\n\n\nfunc IsFieldListType(fieldList *ast.FieldList, position int, exprFunc func(ast.Expr) bool) bool {\n\tt := FieldListType(fieldList, position)\n\n\treturn t != nil && exprFunc(*t)\n}\n\n\nfunc IsFieldListTypePackageType(fieldList *ast.FieldList, position int, info *types.Info, packageSuffix string, typeName string) bool {\n\tt := FieldListType(fieldList, position)\n\n\treturn t != nil && IsPackageFunctionFieldListType(*t, info, packageSuffix, typeName)\n}\n\nfunc FieldListNames(fieldList *ast.FieldList, position int) []*ast.Ident ", "output": "{\n\tif fieldList == nil {\n\t\treturn nil\n\t}\n\n\tif len(fieldList.List) <= position {\n\t\treturn nil\n\t}\n\n\tfield := fieldList.List[position]\n\n\tif field == nil {\n\t\treturn nil\n\t}\n\n\treturn field.Names\n}"} {"input": "package store\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime/middleware\"\n)\n\n\ntype PlaceOrderHandlerFunc func(PlaceOrderParams) middleware.Responder\n\n\nfunc (fn PlaceOrderHandlerFunc) Handle(params PlaceOrderParams) middleware.Responder {\n\treturn fn(params)\n}\n\n\ntype PlaceOrderHandler interface {\n\tHandle(PlaceOrderParams) middleware.Responder\n}\n\n\nfunc NewPlaceOrder(ctx *middleware.Context, handler PlaceOrderHandler) *PlaceOrder {\n\treturn &PlaceOrder{Context: ctx, Handler: handler}\n}\n\n\ntype PlaceOrder struct {\n\tContext *middleware.Context\n\tHandler PlaceOrderHandler\n}\n\n\n\nfunc (o *PlaceOrder) ServeHTTP(rw http.ResponseWriter, r *http.Request) ", "output": "{\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\t*r = *rCtx\n\t}\n\tvar Params = NewPlaceOrderParams()\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params) \n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}"} {"input": "package gobot\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"gobot.io/x/gobot/gobottest\"\n)\n\nfunc TestEventerAddEvent(t *testing.T) {\n\te := NewEventer()\n\te.AddEvent(\"test\")\n\n\tif _, ok := e.Events()[\"test\"]; !ok {\n\t\tt.Errorf(\"Could not add event to list of Event names\")\n\t}\n\tgobottest.Assert(t, e.Event(\"test\"), \"test\")\n}\n\nfunc TestEventerDeleteEvent(t *testing.T) {\n\te := NewEventer()\n\te.AddEvent(\"test1\")\n\te.DeleteEvent(\"test1\")\n\n\tif _, ok := e.Events()[\"test1\"]; ok {\n\t\tt.Errorf(\"Could not add delete event from list of Event names\")\n\t}\n}\n\nfunc TestEventerOn(t *testing.T) {\n\te := NewEventer()\n\te.AddEvent(\"test\")\n\n\tsem := make(chan bool)\n\te.On(\"test\", func(data interface{}) {\n\t\tsem <- true\n\t})\n\n\tgo func() {\n\t\te.Publish(\"test\", true)\n\t}()\n\n\tselect {\n\tcase <-sem:\n\tcase <-time.After(10 * time.Millisecond):\n\t\tt.Errorf(\"On was not called\")\n\t}\n}\n\n\n\nfunc TestEventerOnce(t *testing.T) ", "output": "{\n\te := NewEventer()\n\te.AddEvent(\"test\")\n\n\tsem := make(chan bool)\n\te.Once(\"test\", func(data interface{}) {\n\t\tsem <- true\n\t})\n\n\tgo func() {\n\t\te.Publish(\"test\", true)\n\t}()\n\n\tselect {\n\tcase <-sem:\n\tcase <-time.After(10 * time.Millisecond):\n\t\tt.Errorf(\"Once was not called\")\n\t}\n\n\tgo func() {\n\t\te.Publish(\"test\", true)\n\t}()\n\n\tselect {\n\tcase <-sem:\n\t\tt.Errorf(\"Once was called twice\")\n\tcase <-time.After(10 * time.Millisecond):\n\t}\n}"} {"input": "package grpclog \n\nimport \"os\"\n\nvar logger = newLoggerV2()\n\n\nfunc V(l int) bool {\n\treturn logger.V(l)\n}\n\n\nfunc Info(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\nfunc Infof(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\nfunc Infoln(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\n\nfunc Warning(args ...interface{}) {\n\tlogger.Warning(args...)\n}\n\n\nfunc Warningf(format string, args ...interface{}) {\n\tlogger.Warningf(format, args...)\n}\n\n\nfunc Warningln(args ...interface{}) {\n\tlogger.Warningln(args...)\n}\n\n\nfunc Error(args ...interface{}) {\n\tlogger.Error(args...)\n}\n\n\nfunc Errorf(format string, args ...interface{}) {\n\tlogger.Errorf(format, args...)\n}\n\n\nfunc Errorln(args ...interface{}) {\n\tlogger.Errorln(args...)\n}\n\n\n\nfunc Fatal(args ...interface{}) {\n\tlogger.Fatal(args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalf(format string, args ...interface{}) {\n\tlogger.Fatalf(format, args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalln(args ...interface{}) {\n\tlogger.Fatalln(args...)\n\tos.Exit(1)\n}\n\n\n\n\nfunc Print(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\n\n\n\n\n\n\n\nfunc Println(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\nfunc Printf(format string, args ...interface{}) ", "output": "{\n\tlogger.Infof(format, args...)\n}"} {"input": "package nsqlookupd\n\nimport (\n\t\"net\"\n)\n\ntype ClientV1 struct {\n\tnet.Conn\n\tpeerInfo *PeerInfo\n}\n\nfunc NewClientV1(conn net.Conn) *ClientV1 {\n\treturn &ClientV1{\n\t\tConn: conn,\n\t}\n}\n\n\n\nfunc (c *ClientV1) String() string ", "output": "{\n\treturn c.RemoteAddr().String()\n}"} {"input": "package datastore\n\nimport (\n\t\"context\"\n\n\t\"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base\"\n\t\"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models\"\n\t\"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext\"\n\t\"github.com/pivotal-cf/brokerapi\"\n)\n\n\ntype InstanceInformation struct {\n\tNamespace string `json:\"namespace,omitempty\"`\n}\n\n\ntype DatastoreBroker struct {\n\tbase.BrokerBase\n}\n\n\n\n\n\nfunc (b *DatastoreBroker) Deprovision(ctx context.Context, instance models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) {\n\treturn nil, nil\n}\n\nfunc (b *DatastoreBroker) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) ", "output": "{\n\n\tii := InstanceInformation{\n\t\tNamespace: provisionContext.GetString(\"namespace\"),\n\t}\n\n\tif err := provisionContext.Error(); err != nil {\n\t\treturn models.ServiceInstanceDetails{}, err\n\t}\n\n\tdetails := models.ServiceInstanceDetails{}\n\tif err := details.SetOtherDetails(ii); err != nil {\n\t\treturn models.ServiceInstanceDetails{}, err\n\t}\n\n\treturn details, nil\n}"} {"input": "package s0081\n\nimport (\n\t\"github.com/peterstace/project-euler/graph\"\n)\n\ntype matrix [][]int \n\nfunc Answer() interface{} {\n\treturn parameterised(data)\n}\n\nfunc parameterised(m matrix) interface{} {\n\tg, start, end := matrixToGraph(m)\n\treturn g.ShortestPath(start)[end]\n}\n\n\n\nfunc matrixToGraph(m matrix) (g graph.WeightedDigraph, start int, end int) ", "output": "{\n\tg = graph.NewOrderZeroWeightedDigraph()\n\tn := len(m)\n\tnode := func(i, j int) int {\n\t\treturn i*n + j\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tfor j := 0; j < n; j++ {\n\t\t\tif i > 0 {\n\t\t\t\tg.AddEdge(node(i-1, j), node(i, j), float64(m[i][j]))\n\t\t\t}\n\t\t\tif j > 0 {\n\t\t\t\tg.AddEdge(node(i, j-1), node(i, j), float64(m[i][j]))\n\t\t\t}\n\t\t}\n\t}\n\tg.AddEdge(-1, node(0, 0), float64(m[0][0]))\n\treturn g, -1, node(n-1, n-1)\n}"} {"input": "package antlr\n\nimport \"fmt\"\n\ntype TraceListener struct {\n\tparser *BaseParser\n}\n\n\n\nfunc (t *TraceListener) VisitErrorNode(_ ErrorNode) {\n}\n\nfunc (t *TraceListener) EnterEveryRule(ctx ParserRuleContext) {\n\tfmt.Println(\"enter \" + t.parser.GetRuleNames()[ctx.GetRuleIndex()] + \", LT(1)=\" + t.parser.input.LT(1).GetText())\n}\n\nfunc (t *TraceListener) VisitTerminal(node TerminalNode) {\n\tfmt.Println(\"consume \" + fmt.Sprint(node.GetSymbol()) + \" rule \" + t.parser.GetRuleNames()[t.parser.ctx.GetRuleIndex()])\n}\n\nfunc (t *TraceListener) ExitEveryRule(ctx ParserRuleContext) {\n\tfmt.Println(\"exit \" + t.parser.GetRuleNames()[ctx.GetRuleIndex()] + \", LT(1)=\" + t.parser.input.LT(1).GetText())\n}\n\nfunc NewTraceListener(parser *BaseParser) *TraceListener ", "output": "{\n\ttl := new(TraceListener)\n\ttl.parser = parser\n\treturn tl\n}"} {"input": "package webdriver\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/bborbe/assert\"\n\tmonitoring_check \"github.com/bborbe/monitoring/check\"\n)\n\nfunc TestImplementsCheck(t *testing.T) {\n\tc := New(nil, \"http://www.example.com\")\n\tvar i *monitoring_check.Check\n\terr := AssertThat(c, Implements(i))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\n\nfunc TestDescription(t *testing.T) ", "output": "{\n\tc := New(nil, \"http://www.example.com\")\n\terr := AssertThat(c.Description(), Is(\"webdriver check on url http://www.example.com\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar denoms = map[int]string{\n\t10000: \"ONE HUNDRED\",\n\t5000: \"FIFTY\",\n\t2000: \"TWENTY\",\n\t1000: \"TEN\",\n\t500: \"FIVE\",\n\t100: \"ONE\",\n\t50: \"HALF DOLLAR\",\n\t25: \"QUARTER\",\n\t10: \"DIME\",\n\t5: \"NICKEL\",\n\t1: \"PENNY\",\n\t0: \"ZERO\",\n}\n\ntype Transaction struct {\n\tPurchasePrice int\n\tCash int\n}\n\n\n\nfunc main() {\n\tfile, err := os.Open(\"input.data\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tparts := strings.Split(scanner.Text(), \";\")\n\t\tif len(parts) != 2 {\n\t\t\tlog.Printf(\"Found more than two parts!\")\n\t\t\tcontinue\n\t\t}\n\t\tpp, err := strconv.ParseFloat(parts[0], 64)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to parse %s\", parts[0])\n\t\t\tcontinue\n\t\t}\n\t\tc, err := strconv.ParseFloat(parts[1], 64)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to parse %s\", parts[0])\n\t\t\tcontinue\n\t\t}\n\t\tt := &Transaction{\n\t\t\tPurchasePrice: int(pp * 100),\n\t\t\tCash: int(c * 100),\n\t\t}\n\t\tlog.Print(t.calculateChange())\n\t}\n}\n\nfunc (t *Transaction) calculateChange() string ", "output": "{\n\tif t.Cash < t.PurchasePrice {\n\t\treturn \"ERROR\"\n\t}\n\n\tif t.Cash == t.PurchasePrice {\n\t\treturn \"ZERO\"\n\t}\n\n\tkeys := make([]int, 0, len(denoms))\n\tfor k := range denoms {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Sort(sort.Reverse(sort.IntSlice(keys)))\n\n\tdiff := t.Cash - t.PurchasePrice\n\n\tvar buf bytes.Buffer\n\tfor _, i := range keys {\n\t\tj := diff / i\n\t\tif j > 0 {\n\t\t\tfor k := 0; k < j; k++ {\n\t\t\t\tbuf.WriteString(denoms[i])\n\t\t\t\tdiff = diff - i\n\t\t\t\tif diff > 0 {\n\t\t\t\t\tbuf.WriteString(\",\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tif diff == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn buf.String()\n}"} {"input": "package main\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc TestVersionString(t *testing.T) ", "output": "{\n\ttyp := reflect.TypeOf(VERSION)\n\tif typ.String() != \"string\" {\n\t\tt.Errorf(\"expected VERSION to be a string, got %#v (type %#v)\", VERSION, typ.String())\n\t}\n}"} {"input": "package aws_test\n\nimport (\n\t\"github.com/lizdeika/goamz/aws\"\n\t. \"github.com/motain/gocheck\"\n\t\"time\"\n)\n\n\n\nfunc (S) TestAttemptNextHasNext(c *C) {\n\ta := aws.AttemptStrategy{}.Start()\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.Next(), Equals, false)\n\n\ta = aws.AttemptStrategy{}.Start()\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.HasNext(), Equals, false)\n\tc.Assert(a.Next(), Equals, false)\n\n\ta = aws.AttemptStrategy{Total: 2e8}.Start()\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.HasNext(), Equals, true)\n\ttime.Sleep(2e8)\n\tc.Assert(a.HasNext(), Equals, true)\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.Next(), Equals, false)\n\n\ta = aws.AttemptStrategy{Total: 1e8, Min: 2}.Start()\n\ttime.Sleep(1e8)\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.HasNext(), Equals, true)\n\tc.Assert(a.Next(), Equals, true)\n\tc.Assert(a.HasNext(), Equals, false)\n\tc.Assert(a.Next(), Equals, false)\n}\n\nfunc (S) TestAttemptTiming(c *C) ", "output": "{\n\ttestAttempt := aws.AttemptStrategy{\n\t\tTotal: 0.25e9,\n\t\tDelay: 0.1e9,\n\t}\n\twant := []time.Duration{0, 0.1e9, 0.2e9, 0.2e9}\n\tgot := make([]time.Duration, 0, len(want)) \n\tt0 := time.Now()\n\tfor a := testAttempt.Start(); a.Next(); {\n\t\tgot = append(got, time.Now().Sub(t0))\n\t}\n\tgot = append(got, time.Now().Sub(t0))\n\tc.Assert(got, HasLen, len(want))\n\tconst margin = 0.01e9\n\tfor i, got := range want {\n\t\tlo := want[i] - margin\n\t\thi := want[i] + margin\n\t\tif got < lo || got > hi {\n\t\t\tc.Errorf(\"attempt %d want %g got %g\", i, want[i].Seconds(), got.Seconds())\n\t\t}\n\t}\n}"} {"input": "package oglematchers_test\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"testing\"\n\n\t. \"github.com/jacobsa/oglematchers\"\n\t. \"github.com/jacobsa/ogletest\"\n)\n\nfunc TestPanickingTest(t *testing.T) { RunTests(t) }\n\n\n\n\n\nfunc someFuncThatPanics() {\n\tpanic(\"Panic in someFuncThatPanics\")\n}\n\ntype PanickingTest struct {\n}\n\nfunc init() { RegisterTestSuite(&PanickingTest{}) }\n\nfunc (t *PanickingTest) TearDown() {\n\tfmt.Println(\"TearDown running.\")\n}\n\nfunc (t *PanickingTest) ExplicitPanic() {\n\tpanic(\"Panic in ExplicitPanic\")\n}\n\nfunc (t *PanickingTest) ExplicitPanicInHelperFunction() {\n\tsomeFuncThatPanics()\n}\n\n\n\nfunc (t *PanickingTest) ZzzSomeOtherTest() {\n\tExpectThat(17, Equals(17.0))\n}\n\n\n\n\n\ntype SetUpPanicTest struct {\n}\n\nfunc init() { RegisterTestSuite(&SetUpPanicTest{}) }\n\nfunc (t *SetUpPanicTest) SetUp(ti *TestInfo) {\n\tfmt.Println(\"SetUp about to panic.\")\n\tpanic(\"Panic in SetUp\")\n}\n\nfunc (t *SetUpPanicTest) TearDown() {\n\tfmt.Println(\"TearDown running.\")\n}\n\nfunc (t *SetUpPanicTest) SomeTestCase() {\n}\n\n\n\n\n\ntype TearDownPanicTest struct {\n}\n\nfunc init() { RegisterTestSuite(&TearDownPanicTest{}) }\n\nfunc (t *TearDownPanicTest) TearDown() {\n\tfmt.Println(\"TearDown about to panic.\")\n\tpanic(\"Panic in TearDown\")\n}\n\nfunc (t *TearDownPanicTest) SomeTestCase() {\n}\n\nfunc (t *PanickingTest) NilPointerDerefence() ", "output": "{\n\tvar p *int\n\tlog.Println(*p)\n}"} {"input": "package cabf_br\n\n\n\nimport (\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/util\"\n)\n\ntype caAiaMissing struct{}\n\n\n\nfunc init() {\n\tlint.RegisterLint(&lint.Lint{\n\t\tName: \"e_sub_ca_aia_missing\",\n\t\tDescription: \"Subordinate CA Certificate: authorityInformationAccess MUST be present, with the exception of stapling.\",\n\t\tCitation: \"BRs: 7.1.2.2\",\n\t\tSource: lint.CABFBaselineRequirements,\n\t\tEffectiveDate: util.CABEffectiveDate,\n\t\tIneffectiveDate: util.CABFBRs_1_7_1_Date,\n\t\tLint: NewCaAiaMissing,\n\t})\n}\n\nfunc NewCaAiaMissing() lint.LintInterface {\n\treturn &caAiaMissing{}\n}\n\nfunc (l *caAiaMissing) CheckApplies(c *x509.Certificate) bool {\n\treturn util.IsCACert(c) && !util.IsRootCA(c)\n}\n\n\n\nfunc (l *caAiaMissing) Execute(c *x509.Certificate) *lint.LintResult ", "output": "{\n\tif util.IsExtInCert(c, util.AiaOID) {\n\t\treturn &lint.LintResult{Status: lint.Pass}\n\t} else {\n\t\treturn &lint.LintResult{Status: lint.Error}\n\t}\n}"} {"input": "package decorator\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/helloticket/ffparser/helper\"\n)\n\ntype BrazilMoneyDecorator struct {\n}\n\nfunc (i *BrazilMoneyDecorator) ToString(field interface{}) (string, error) {\n\tif value, ok := field.(float64); ok {\n\t\tstrValue := fmt.Sprintf(\"%.2f\", value)\n\t\treturn strings.Replace(strValue, \".\", \"\", -1), nil\n\t}\n\n\treturn \"\", nil\n}\n\n\n\nfunc (i *BrazilMoneyDecorator) FromString(field string) (interface{}, error) ", "output": "{\n\tif strings.TrimSpace(field) == \"\" {\n\t\treturn float64(0), nil\n\t}\n\tdecimalPart := field[len(field)-2:]\n\tintegerPart := field[:len(field)-2]\n\tvalue := fmt.Sprintf(\"%s.%s\", integerPart, decimalPart)\n\treturn helper.ToFloat64(value), nil\n}"} {"input": "package store\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime/middleware\"\n)\n\n\ntype PlaceOrderHandlerFunc func(PlaceOrderParams) middleware.Responder\n\n\n\n\n\ntype PlaceOrderHandler interface {\n\tHandle(PlaceOrderParams) middleware.Responder\n}\n\n\nfunc NewPlaceOrder(ctx *middleware.Context, handler PlaceOrderHandler) *PlaceOrder {\n\treturn &PlaceOrder{Context: ctx, Handler: handler}\n}\n\n\ntype PlaceOrder struct {\n\tContext *middleware.Context\n\tHandler PlaceOrderHandler\n}\n\nfunc (o *PlaceOrder) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\t*r = *rCtx\n\t}\n\tvar Params = NewPlaceOrderParams()\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params) \n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}\n\nfunc (fn PlaceOrderHandlerFunc) Handle(params PlaceOrderParams) middleware.Responder ", "output": "{\n\treturn fn(params)\n}"} {"input": "package isbn\n\nimport (\n\t\"errors\"\n\t\"math\"\n\t\"strconv\"\n\t\"unicode\"\n)\n\nfunc IsValidISBN(isbn string) bool {\n\n\tisbn = dropHyphen(isbn)\n\n\tary, err := strToSlice(isbn)\n\tif len(ary) != 10 || err != nil {\n\t\treturn false\n\t}\n\n\treturn calcCheckDigit(ary)\n}\n\nfunc dropHyphen(isbn string) string {\n\tvar result string\n\tfor _, char := range isbn {\n\t\tif char == '-' {\n\t\t\tcontinue\n\t\t}\n\t\tresult += string(char)\n\t}\n\treturn result\n}\n\n\n\nfunc calcCheckDigit(isbn []int) bool {\n\tvar pool int\n\tfor idx, value := range isbn {\n\t\tpool += int(math.Abs(float64(idx)-10)) * value\n\t}\n\tresult := pool % 11\n\n\treturn result == 0\n}\n\nfunc strToSlice(isbn string) (result []int, err error) ", "output": "{\n\n\tfor pos, char := range isbn {\n\t\tif unicode.IsLetter(char) && (char != 'X' || pos != 9) {\n\t\t\terr = errors.New(\"invalid character\")\n\t\t\treturn\n\t\t} else if char == 'X' {\n\t\t\tresult = append(result, 10)\n\t\t} else {\n\t\t\ti, _ := strconv.Atoi(string(char))\n\t\t\tresult = append(result, i)\n\t\t}\n\t}\n\treturn\n}"} {"input": "package yaml\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc (this *Job) Validate(c Context) error {\n\treturn nil\n}\n\nfunc (this *Job) InDesiredState(c Context) (bool, error) {\n\treturn true, nil\n}\n\nfunc (this *Job) Prepare(c Context) error {\n\treturn nil\n}\n\nfunc (this *Job) Execute(c Context) error {\n\tc.log(\"Executing Job %s\", this.name)\n\n\treturn nil\n}\n\nfunc (this *Job) Finish(c Context) error {\n\treturn nil\n}\n\nfunc (this *Job) get_task() *task {\n\tif this.task == nil {\n\t\tthis.task = alloc_task(this)\n\t\tthis.task.description = fmt.Sprintf(\"Job[%s]\", this.name)\n\n\t\tfor _, container := range this.container_instances {\n\t\t\tthis.task.DependsOn(container.get_task())\n\t\t}\n\t}\n\treturn this.task\n}\n\nfunc (this *Job) Name() JobKey ", "output": "{\n\treturn this.name\n}"} {"input": "package pop\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc Test_Callbacks(t *testing.T) {\n\tif PDB == nil {\n\t\tt.Skip(\"skipping integration tests\")\n\t}\n\ttransaction(func(tx *Connection) {\n\t\tr := require.New(t)\n\n\t\tuser := &CallbacksUser{\n\t\t\tBeforeS: \"BS\",\n\t\t\tBeforeC: \"BC\",\n\t\t\tBeforeU: \"BU\",\n\t\t\tBeforeD: \"BD\",\n\t\t\tAfterS: \"AS\",\n\t\t\tAfterC: \"AC\",\n\t\t\tAfterU: \"AU\",\n\t\t\tAfterD: \"AD\",\n\t\t\tAfterF: \"AF\",\n\t\t}\n\n\t\tr.NoError(tx.Save(user))\n\n\t\tr.Equal(\"BeforeSave\", user.BeforeS)\n\t\tr.Equal(\"BeforeCreate\", user.BeforeC)\n\t\tr.Equal(\"AfterSave\", user.AfterS)\n\t\tr.Equal(\"AfterCreate\", user.AfterC)\n\t\tr.Equal(\"BU\", user.BeforeU)\n\t\tr.Equal(\"AU\", user.AfterU)\n\n\t\tr.NoError(tx.Update(user))\n\n\t\tr.Equal(\"BeforeUpdate\", user.BeforeU)\n\t\tr.Equal(\"AfterUpdate\", user.AfterU)\n\t\tr.Equal(\"BD\", user.BeforeD)\n\t\tr.Equal(\"AD\", user.AfterD)\n\n\t\tr.Equal(\"AF\", user.AfterF)\n\t\tr.NoError(tx.Find(user, user.ID))\n\t\tr.Equal(\"AfterFind\", user.AfterF)\n\n\t\tr.NoError(tx.Destroy(user))\n\n\t\tr.Equal(\"BeforeDestroy\", user.BeforeD)\n\t\tr.Equal(\"AfterDestroy\", user.AfterD)\n\n\t})\n}\n\n\n\nfunc Test_Callbacks_on_Slice(t *testing.T) ", "output": "{\n\tif PDB == nil {\n\t\tt.Skip(\"skipping integration tests\")\n\t}\n\ttransaction(func(tx *Connection) {\n\t\tr := require.New(t)\n\t\tfor i := 0; i < 2; i++ {\n\t\t\tr.NoError(tx.Create(&CallbacksUser{}))\n\t\t}\n\n\t\tusers := CallbacksUsers{}\n\t\tr.NoError(tx.All(&users))\n\n\t\tr.Len(users, 2)\n\n\t\tfor _, u := range users {\n\t\t\tr.Equal(\"AfterFind\", u.AfterF)\n\t\t}\n\t})\n}"} {"input": "package iso20022\n\n\ntype ClosingBalance5Choice struct {\n\n\tFinal *BalanceQuantity12Choice `xml:\"Fnl\"`\n\n\tIntermediary *BalanceQuantity12Choice `xml:\"Intrmy\"`\n}\n\n\n\nfunc (c *ClosingBalance5Choice) AddIntermediary() *BalanceQuantity12Choice {\n\tc.Intermediary = new(BalanceQuantity12Choice)\n\treturn c.Intermediary\n}\n\nfunc (c *ClosingBalance5Choice) AddFinal() *BalanceQuantity12Choice ", "output": "{\n\tc.Final = new(BalanceQuantity12Choice)\n\treturn c.Final\n}"} {"input": "package ipv6\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\nfunc getsockopt(s uintptr, level, name int, v unsafe.Pointer, l *uint32) error {\n\treturn syscall.Getsockopt(syscall.Handle(s), int32(level), int32(name), (*byte)(v), (*int32)(unsafe.Pointer(l)))\n}\n\n\n\nfunc setsockopt(s uintptr, level, name int, v unsafe.Pointer, l uint32) error ", "output": "{\n\treturn syscall.Setsockopt(syscall.Handle(s), int32(level), int32(name), (*byte)(v), int32(l))\n}"} {"input": "package conv\n\nimport (\n\t\"testing\"\n)\n\nfunc assertConvert(t *testing.T, c *Converter, expected, input string) {\n\tconverted, err := c.Convert(input)\n\tif err != nil {\n\t\tt.Error(\"Convert failed:\", err)\n\t\tt.Logf(\" input=%s expected=%s\", input, expected)\n\t}\n\tif converted != expected {\n\t\tt.Error(\"Convert returns unexpected:\", converted)\n\t\tt.Logf(\" input=%s expected=%s\", input, expected)\n\t}\n}\n\nfunc TestEmpty(t *testing.T) {\n\tc := New()\n\tassertConvert(t, c, \"\", \"\")\n\tassertConvert(t, c, \"foo\", \"foo\")\n\tassertConvert(t, c, \"bar\", \"bar\")\n}\n\n\n\nfunc TestTiny(t *testing.T) {\n\tc := New()\n\tc.Add(\"aa\", \"A\", \"a\")\n\tc.Add(\"ab\", \"B\", \"\")\n\tassertConvert(t, c, \"B\", \"ab\")\n\tassertConvert(t, c, \"Aa\", \"aa\")\n\tassertConvert(t, c, \"AB\", \"aab\")\n\tassertConvert(t, c, \"Bc\", \"abc\")\n\tassertConvert(t, c, \"Ba\", \"aba\")\n}\n\nfunc TestHira(t *testing.T) {\n\tc := New()\n\tc.Add(\"a\", \"あ\", \"\")\n\tc.Add(\"i\", \"い\", \"\")\n\tassertConvert(t, c, \"あい\", \"ai\")\n}\n\nfunc TestHiraRemain(t *testing.T) {\n\tc := New()\n\tc.Add(\"a\", \"あ\", \"\")\n\tc.Add(\"ka\", \"か\", \"\")\n\tc.Add(\"ki\", \"き\", \"\")\n\tassertConvert(t, c, \"あk\", \"ak\")\n}\n\nfunc TestSimple(t *testing.T) ", "output": "{\n\tc := New()\n\tc.Add(\"a\", \"A\", \"\")\n\tc.Add(\"b\", \"B\", \"\")\n\tassertConvert(t, c, \"A\", \"a\")\n\tassertConvert(t, c, \"B\", \"b\")\n\tassertConvert(t, c, \"c\", \"c\")\n\tassertConvert(t, c, \"AAAAABBBBBccccc\", \"aaaaabbbbbccccc\")\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\ntype EnumFlag struct {\n\tdefaultValue string\n\tvs []string\n\ti int\n}\n\n\n\n\n\n\nfunc (f *EnumFlag) Type() string {\n\treturn \"{\" + strings.Join(f.vs, \",\") + \"}\"\n}\n\n\nfunc (f *EnumFlag) String() string {\n\tif f.i == -1 {\n\t\treturn f.defaultValue\n\t}\n\treturn f.vs[f.i]\n}\n\n\nfunc (f *EnumFlag) IsSet() bool {\n\treturn f.i != -1\n}\n\n\n\nfunc (f *EnumFlag) Set(s string) error {\n\tfor i := range f.vs {\n\t\tif f.vs[i] == s {\n\t\t\tf.i = i\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"must be one of %v\", f.Type())\n}\n\nfunc NewEnumFlag(defaultValue string, vs []string) *EnumFlag ", "output": "{\n\tf := &EnumFlag{\n\t\ti: -1,\n\t\tvs: vs,\n\t\tdefaultValue: defaultValue,\n\t}\n\treturn f\n}"} {"input": "package main\n\nimport (\n\t\"github.com/GoogleCloudPlatform/kubernetes/contrib/mesos/pkg/hyperkube\"\n\t\"github.com/GoogleCloudPlatform/kubernetes/contrib/mesos/pkg/scheduler/service\"\n)\n\n\n\n\n\nfunc NewScheduler() *Server ", "output": "{\n\ts := service.NewSchedulerServer()\n\n\thks := Server{\n\t\tSimpleUsage: hyperkube.CommandScheduler,\n\t\tLong: `Implements the Kubernetes-Mesos scheduler. This will launch Mesos tasks which\nresults in pods assigned to kubelets based on capacity and constraints.`,\n\t\tRun: func(hks *Server, args []string) error {\n\t\t\treturn s.Run(hks, args)\n\t\t},\n\t}\n\ts.AddHyperkubeFlags(hks.Flags())\n\treturn &hks\n}"} {"input": "package numwords\n\nimport \"fmt\"\n\nfunc Example() {\n\ts := \"I've got three apples and two and a half bananas\"\n\tfmt.Println(ParseString(s))\n\n\ts = \"My chili won second place at the county fair\"\n\tfmt.Println(ParseString(s))\n\n\ti, _ := ParseInt(\"fourteen ninety two\")\n\tfmt.Println(i)\n\n\tf, _ := ParseFloat(\"eight and three quarters\")\n\tfmt.Println(f)\n\n}\n\nfunc ExampleParseString() {\n\ts := \"I've got three apples and two and a half bananas\"\n\tfmt.Println(ParseString(s))\n\n}\n\n\n\nfunc ExampleParseInt() {\n\ti, _ := ParseInt(\"fourteen ninety two\")\n\tfmt.Println(i)\n\n}\n\nfunc ExampleIncludeSecond() {\n\ts := \"My chili won second place at the county fair\"\n\tfmt.Println(ParseString(s))\n\n\ts = \"One second ago\"\n\tIncludeSecond(false)\n\tfmt.Println(ParseString(s))\n\n}\n\nfunc ExampleParseFloat() ", "output": "{\n\tf, _ := ParseFloat(\"eight and three quarters\")\n\tfmt.Println(f)\n\n}"} {"input": "package metrics\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"github.com/prometheus/client_golang/prometheus/promhttp\"\n\t\"net/http\"\n\t\"sync\"\n)\n\ntype Server struct {\n\tcertificateCh <-chan tls.Certificate\n\n\tsync.Mutex\n\tcertificate *tls.Certificate\n}\n\nfunc (s *Server) getCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {\n\treturn s.certificate, nil\n}\n\nfunc (s *Server) watchForNewCertificates() {\n\tfor {\n\t\tselect {\n\t\tcase cert := <-s.certificateCh:\n\t\t\ts.certificate = &cert\n\t\t}\n\t}\n}\n\nfunc (s *Server) start(roots *x509.CertPool) {\n\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/metrics\", promhttp.Handler())\n\n\tserver := &http.Server{\n\t\tHandler: mux,\n\t}\n\n\tif s.certificateCh != nil {\n\t\ttlsConfig := &tls.Config{\n\t\t\tGetCertificate: s.getCertificate,\n\t\t}\n\n\t\tif roots != nil {\n\t\t\ttlsConfig.ClientCAs = roots\n\t\t\ttlsConfig.ClientAuth = tls.RequireAndVerifyClientCert\n\t\t}\n\n\t\tserver.TLSConfig = tlsConfig\n\n\t\tgo server.ListenAndServeTLS(\"\", \"\")\n\t} else {\n\t\tgo server.ListenAndServe()\n\t}\n}\n\n\n\nfunc StartServer(certificateCh <-chan tls.Certificate, roots *x509.CertPool) ", "output": "{\n\n\tserver := &Server{\n\t\tcertificateCh: certificateCh,\n\t}\n\n\tif certificateCh != nil {\n\t\tgo server.watchForNewCertificates()\n\t}\n\n\tgo server.start(roots)\n}"} {"input": "package file\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\ntype Reader interface {\n\tio.Reader\n\tio.ReaderAt\n\tio.Seeker\n}\n\ntype Writer interface {\n\tio.Writer\n\tio.Seeker\n\tTruncate(size int64) error\n\tSync() error\n}\n\ntype ReadCloser interface {\n\tReader\n\tio.Closer\n}\n\ntype WriteCloser interface {\n\tWriter\n\tio.Closer\n}\n\ntype File interface {\n\tio.Reader\n\tio.Writer\n\tio.Seeker\n\tio.Closer\n\tio.ReaderAt\n\tTruncate(size int64) error\n\tSync() error\n}\n\n\ntype FileSystem interface {\n\tOpen(name string, flag int) (File, error)\n\n\tLock(name string) (io.Closer, error)\n\n\tExists(name string) bool\n\n\tMkdirAll(path string) error\n\n\tList(dir string) ([]string, error)\n\n\tRemove(filename string) error\n\n\tRename(oldpath, newpath string) error\n}\n\ntype osFileSystem struct{}\n\nfunc (osFileSystem) Open(name string, flag int) (File, error) {\n\treturn os.OpenFile(name, flag, 0666)\n}\n\nfunc (osFileSystem) MkdirAll(path string) error {\n\treturn os.MkdirAll(path, 0740)\n}\n\nfunc (osFileSystem) Exists(name string) bool {\n\t_, err := os.Stat(name)\n\treturn err == nil\n}\n\nfunc (osFileSystem) List(dir string) ([]string, error) {\n\tf, err := os.Open(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.Readdirnames(-1)\n}\n\n\n\nfunc (osFileSystem) Rename(oldpath, newpath string) error {\n\treturn os.Rename(oldpath, newpath)\n}\n\nvar DefaultFileSystem FileSystem = osFileSystem{}\n\nfunc (osFileSystem) Remove(name string) error ", "output": "{\n\treturn os.Remove(name)\n}"} {"input": "package api\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestAPI_StatusPeers(t *testing.T) {\n\tt.Parallel()\n\tc, s := makeClient(t)\n\tdefer s.Stop()\n\n\tstatus := c.Status()\n\n\tpeers, err := status.Peers()\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\tif len(peers) == 0 {\n\t\tt.Fatalf(\"Expected peers \")\n\t}\n}\n\nfunc TestAPI_StatusLeader(t *testing.T) ", "output": "{\n\tt.Parallel()\n\tc, s := makeClient(t)\n\tdefer s.Stop()\n\n\tstatus := c.Status()\n\n\tleader, err := status.Leader()\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\tif leader == \"\" {\n\t\tt.Fatalf(\"Expected leader\")\n\t}\n}"} {"input": "package dbr\n\nimport \"bytes\"\n\n\ntype Buffer interface {\n\tWriteString(s string) (n int, err error)\n\tString() string\n\n\tWriteValue(v ...interface{}) (err error)\n\tValue() []interface{}\n}\n\n\nfunc NewBuffer() Buffer {\n\treturn &buffer{}\n}\n\ntype buffer struct {\n\tbytes.Buffer\n\tv []interface{}\n}\n\nfunc (b *buffer) WriteValue(v ...interface{}) error {\n\tb.v = append(b.v, v...)\n\treturn nil\n}\n\n\n\nfunc (b *buffer) Value() []interface{} ", "output": "{\n\treturn b.v\n}"} {"input": "package expvar\n\nimport (\n\t\"expvar\"\n\t\"runtime\"\n\t\"sync\"\n\n\t\"github.com/mholt/caddy\"\n\t\"github.com/mholt/caddy/caddyhttp/httpserver\"\n)\n\nfunc init() {\n\tcaddy.RegisterPlugin(\"expvar\", caddy.Plugin{\n\t\tServerType: \"http\",\n\t\tAction: setup,\n\t})\n}\n\n\nfunc setup(c *caddy.Controller) error {\n\tresource, err := expVarParse(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpublishExtraVars()\n\n\tev := ExpVar{Resource: resource}\n\n\thttpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {\n\t\tev.Next = next\n\t\treturn ev\n\t})\n\n\treturn nil\n}\n\n\n\nfunc publishExtraVars() {\n\tpublishOnce.Do(func() {\n\t\texpvar.Publish(\"Goroutines\", expvar.Func(func() interface{} {\n\t\t\treturn runtime.NumGoroutine()\n\t\t}))\n\t})\n}\n\nvar publishOnce sync.Once \nvar defaultExpvarPath = \"/debug/vars\"\n\nfunc expVarParse(c *caddy.Controller) (Resource, error) ", "output": "{\n\tvar resource Resource\n\tvar err error\n\n\tfor c.Next() {\n\t\targs := c.RemainingArgs()\n\t\tswitch len(args) {\n\t\tcase 0:\n\t\t\tresource = Resource(defaultExpvarPath)\n\t\tcase 1:\n\t\t\tresource = Resource(args[0])\n\t\tdefault:\n\t\t\treturn resource, c.ArgErr()\n\t\t}\n\t}\n\n\treturn resource, err\n}"} {"input": "package tfbparser\n\nimport \"github.com/kiwih/goFB/iec61499\"\n\n\ntype tfbParse struct {\n\tfbs []iec61499.FB\n\n\titems []string\n\titemIndex int\n\n\tcurrentLine int\n\tcurrentFile string\n}\n\n\nfunc (t *tfbParse) getCurrentDebugInfo() iec61499.DebugInfo {\n\treturn iec61499.DebugInfo{\n\t\tSourceLine: t.currentLine,\n\t\tSourceFile: t.currentFile,\n\t}\n}\n\n\nfunc (t *tfbParse) isFBNameUnused(name string) bool {\n\tfor i := 0; i < len(t.fbs); i++ {\n\t\tif t.fbs[i].Name == name {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\n\n\nfunc (t *tfbParse) peek() string {\n\tif t.done() {\n\t\treturn \"\"\n\t}\n\tfor i := 0; i < len(t.items); i++ {\n\t\tif t.items[t.itemIndex+i] != pNewline {\n\t\t\treturn t.items[t.itemIndex+i]\n\t\t}\n\t}\n\treturn \"\"\n}\n\n\nfunc (t *tfbParse) done() bool {\n\treturn t.itemIndex >= len(t.items)\n}\n\n\n\nfunc (t *tfbParse) getFBIndexFromName(name string) int {\n\tfor i := 0; i < len(t.fbs); i++ {\n\t\tif t.fbs[i].Name == name {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (t *tfbParse) pop() string ", "output": "{\n\tif t.done() {\n\t\treturn \"\"\n\t}\n\ts := t.items[t.itemIndex]\n\tt.itemIndex++\n\n\tif s == pNewline {\n\t\tt.currentLine++\n\t\treturn t.pop()\n\t}\n\treturn s\n}"} {"input": "package version\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\nvar (\n\tGitCommit string\n\n\tVersion = \"0.13.0\"\n\n\tVersionPrerelease = \"dev\"\n\n\tVersionMetadata = \"\"\n)\n\n\ntype VersionInfo struct {\n\tRevision string\n\tVersion string\n\tVersionPrerelease string\n\tVersionMetadata string\n}\n\nfunc GetVersion() *VersionInfo {\n\tver := Version\n\trel := VersionPrerelease\n\tmd := VersionMetadata\n\n\treturn &VersionInfo{\n\t\tRevision: GitCommit,\n\t\tVersion: ver,\n\t\tVersionPrerelease: rel,\n\t\tVersionMetadata: md,\n\t}\n}\n\n\n\n\n\nfunc (c *VersionInfo) VersionNumber(rev bool) string ", "output": "{\n\tvar versionString bytes.Buffer\n\n\tfmt.Fprintf(&versionString, \"v%s\", c.Version)\n\n\tif c.VersionPrerelease != \"\" {\n\t\tfmt.Fprintf(&versionString, \"-%s\", c.VersionPrerelease)\n\t}\n\n\tif c.VersionMetadata != \"\" {\n\t\tfmt.Fprintf(&versionString, \"+%s\", c.VersionMetadata)\n\t}\n\n\tif rev && c.Revision != \"\" {\n\t\tfmt.Fprintf(&versionString, \" (%s)\", c.Revision)\n\t}\n\n\treturn versionString.String()\n}"} {"input": "package authentication\n\nimport \"TruckMonitor-Backend/service\"\n\ntype controller struct {\n\tauthenticationService service.AuthenticationService\n}\n\n\n\nfunc Controller(authenticationService service.AuthenticationService) *controller ", "output": "{\n\treturn &controller{\n\t\tauthenticationService: authenticationService,\n\t}\n}"} {"input": "package templating\n\nimport (\n\t\"bones/config\"\n\t\"bones/web/handlers\"\n\t\"html/template\"\n\t\"io\"\n\t\"log\"\n)\n\nvar templates *template.Template\n\nfunc NewTemplateRenderer() handlers.TemplateRenderer {\n\tif config.Env().IsProduction() {\n\t\treturn &cachingTemplateRenderer{templates}\n\t}\n\n\tlog.Println(\"Using reloading template renderer\")\n\n\treturn &reloadingTemplateRenderer{}\n}\n\ntype cachingTemplateRenderer struct {\n\ttemplates *template.Template\n}\n\nfunc (r cachingTemplateRenderer) RenderTemplate(wr io.Writer, ctx handlers.TemplateContext) error {\n\tif r.templates == nil {\n\t\tvar err error\n\t\tr.templates, err = template.ParseGlob(\"./templates/*.html\")\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn renderWithLayout(r.templates, wr, ctx.Name(), ctx)\n}\n\ntype reloadingTemplateRenderer struct{}\n\n\n\nfunc renderWithLayout(t *template.Template, wr io.Writer, name string, data interface{}) error {\n\tfor _, templateName := range []string{\"header.html\", name, \"footer.html\"} {\n\t\terr := t.ExecuteTemplate(wr, templateName, data)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (r reloadingTemplateRenderer) RenderTemplate(wr io.Writer, ctx handlers.TemplateContext) error ", "output": "{\n\ttemplates, err := template.ParseGlob(\"./templates/*.html\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn renderWithLayout(templates, wr, ctx.Name(), ctx)\n}"} {"input": "package core\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/sacloud/usacloud/pkg/cli\"\n)\n\ntype ExampleHolder interface {\n\tExampleParameters(ctx cli.Context) interface{}\n}\n\n\n\nfunc generateExampleParameters(ctx cli.Context, exampleHolder ExampleHolder) error ", "output": "{\n\texamples := exampleHolder.ExampleParameters(ctx)\n\tdata, err := json.MarshalIndent(examples, \"\", \" \")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"marshaling to JSON is failed: %s\", err)\n\t}\n\t_, err = fmt.Fprintln(ctx.IO().Out(), string(data))\n\treturn err\n}"} {"input": "package cloudsigma\n\nconst (\n\tEndpointBurstUsage = \"burstusage\"\n)\n\n\ntype BurstUsage struct {\n\tArgs *Args\n}\n\n\n\n\n\nfunc (o *BurstUsage) NewList() *Args {\n\to.Args.Verb = \"GET\"\n\to.Args.RequiresAuth = true\n\treturn o.Args\n}\n\nfunc NewBurstUsage() *BurstUsage ", "output": "{\n\to := BurstUsage{}\n\to.Args = NewArgs()\n\to.Args.Resource = EndpointBurstUsage\n\treturn &o\n}"} {"input": "package stats\n\nimport (\n\t\"sync\"\n)\n\n\ntype CountSum struct {\n\tmu sync.Mutex\n\tsum int64\n\tcount uint32\n}\n\n\n\n\n\n\n\nfunc (s *CountSum) Approximate() (count uint32, sum int64) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\treturn s.count, s.sum\n}\n\nfunc (s *CountSum) Add(size int64) (count uint32, sum int64) ", "output": "{\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\ts.count++\n\ts.sum += size\n\n\treturn s.count, s.sum\n}"} {"input": "package internalversion\n\nimport (\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n\tcore \"k8s.io/kubernetes/pkg/apis/core\"\n)\n\n\ntype ComponentStatusLister interface {\n\tList(selector labels.Selector) (ret []*core.ComponentStatus, err error)\n\tGet(name string) (*core.ComponentStatus, error)\n\tComponentStatusListerExpansion\n}\n\n\ntype componentStatusLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewComponentStatusLister(indexer cache.Indexer) ComponentStatusLister {\n\treturn &componentStatusLister{indexer: indexer}\n}\n\n\nfunc (s *componentStatusLister) List(selector labels.Selector) (ret []*core.ComponentStatus, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*core.ComponentStatus))\n\t})\n\treturn ret, err\n}\n\n\n\n\nfunc (s *componentStatusLister) Get(name string) (*core.ComponentStatus, error) ", "output": "{\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(core.Resource(\"componentstatus\"), name)\n\t}\n\treturn obj.(*core.ComponentStatus), nil\n}"} {"input": "package clean\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n)\n\n\n\n\nfunc UTMMarks(original string) (result string) ", "output": "{\n\tresult = strings.TrimSpace(original)\n\tif len(result) > 0 {\n\t\tif u, e := url.Parse(result); e == nil {\n\t\t\tif q, e := url.ParseQuery(u.RawQuery); e == nil {\n\t\t\t\tq.Del(\"utm_source\")\n\t\t\t\tq.Del(\"utm_medium\")\n\t\t\t\tq.Del(\"utm_campaign\")\n\t\t\t\tq.Del(\"utm_term\")\n\t\t\t\tq.Del(\"utm_content\")\n\n\t\t\t\tu.RawQuery = q.Encode()\n\t\t\t\tresult = u.String()\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}"} {"input": "package gfile\n\nimport (\n\t\"bytes\"\n\t\"github.com/gogf/gf/v2/errors/gcode\"\n\t\"github.com/gogf/gf/v2/errors/gerror\"\n\t\"os\"\n\t\"os/exec\"\n\t\"os/user\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n\n\n\nfunc Home(names ...string) (string, error) {\n\tpath, err := getHomePath()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfor _, name := range names {\n\t\tpath += Separator + name\n\t}\n\treturn path, nil\n}\n\n\nfunc getHomePath() (string, error) {\n\tu, err := user.Current()\n\tif nil == err {\n\t\treturn u.HomeDir, nil\n\t}\n\tif \"windows\" == runtime.GOOS {\n\t\treturn homeWindows()\n\t}\n\treturn homeUnix()\n}\n\n\nfunc homeUnix() (string, error) {\n\tif home := os.Getenv(\"HOME\"); home != \"\" {\n\t\treturn home, nil\n\t}\n\tvar stdout bytes.Buffer\n\tcmd := exec.Command(\"sh\", \"-c\", \"eval echo ~$USER\")\n\tcmd.Stdout = &stdout\n\tif err := cmd.Run(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresult := strings.TrimSpace(stdout.String())\n\tif result == \"\" {\n\t\treturn \"\", gerror.NewCode(gcode.CodeInternalError, \"blank output when reading home directory\")\n\t}\n\n\treturn result, nil\n}\n\n\n\n\nfunc homeWindows() (string, error) ", "output": "{\n\tvar (\n\t\tdrive = os.Getenv(\"HOMEDRIVE\")\n\t\tpath = os.Getenv(\"HOMEPATH\")\n\t\thome = drive + path\n\t)\n\tif drive == \"\" || path == \"\" {\n\t\thome = os.Getenv(\"USERPROFILE\")\n\t}\n\tif home == \"\" {\n\t\treturn \"\", gerror.NewCode(gcode.CodeOperationFailed, \"HOMEDRIVE, HOMEPATH, and USERPROFILE are blank\")\n\t}\n\n\treturn home, nil\n}"} {"input": "package matcher\n\nimport \"errors\"\n\ntype IntComparator struct{}\n\n\n\nfunc (s *IntComparator) GreaterThan(a, b interface{}) bool {\n\treturn a.(int) > b.(int)\n}\n\nfunc (s *IntComparator) LessThan(a, b interface{}) bool {\n\treturn a.(int) < b.(int)\n}\n\nfunc (s *IntComparator) EqualTo(a, b interface{}) bool {\n\treturn a.(int) == b.(int)\n}\n\nfunc (s *IntComparator) NotEqualTo(a, b interface{}) bool {\n\treturn a.(int) != b.(int)\n}\n\nfunc (s *IntComparator) Valid(data interface{}) error ", "output": "{\n\tif _, ok := data.(int); !ok {\n\t\treturn errors.New(\"Invalid argument\")\n\t}\n\n\treturn nil\n}"} {"input": "package virtual_machines\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/jkawamoto/roadie/cloud/azure/compute/models\"\n)\n\n\ntype VirtualMachinesDeallocateReader struct {\n\tformats strfmt.Registry\n}\n\n\n\n\n\nfunc NewVirtualMachinesDeallocateOK() *VirtualMachinesDeallocateOK {\n\treturn &VirtualMachinesDeallocateOK{}\n}\n\n\ntype VirtualMachinesDeallocateOK struct {\n\tPayload *models.OperationStatusResponse\n}\n\nfunc (o *VirtualMachinesDeallocateOK) Error() string {\n\treturn fmt.Sprintf(\"[POST /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/deallocate][%d] virtualMachinesDeallocateOK %+v\", 200, o.Payload)\n}\n\nfunc (o *VirtualMachinesDeallocateOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\to.Payload = new(models.OperationStatusResponse)\n\n\tif err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc NewVirtualMachinesDeallocateAccepted() *VirtualMachinesDeallocateAccepted {\n\treturn &VirtualMachinesDeallocateAccepted{}\n}\n\n\ntype VirtualMachinesDeallocateAccepted struct {\n}\n\nfunc (o *VirtualMachinesDeallocateAccepted) Error() string {\n\treturn fmt.Sprintf(\"[POST /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/deallocate][%d] virtualMachinesDeallocateAccepted \", 202)\n}\n\nfunc (o *VirtualMachinesDeallocateAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\treturn nil\n}\n\nfunc (o *VirtualMachinesDeallocateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) ", "output": "{\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewVirtualMachinesDeallocateOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 202:\n\t\tresult := NewVirtualMachinesDeallocateAccepted()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}"} {"input": "package factory\n\nimport (\n\t\"github.com/vlorc/gioc/types\"\n\t\"github.com/vlorc/gioc/utils\"\n\t\"reflect\"\n)\n\n\n\nfunc newRequestFactory(typ reflect.Type, factory types.BeanFactory, create func(func([]reflect.Value) []reflect.Value) func([]reflect.Value) []reflect.Value) types.BeanFactory ", "output": "{\n\treturn NewFuncFactory(func(provider types.Provider) (interface{}, error) {\n\t\tproxy := create(func([]reflect.Value) []reflect.Value {\n\t\t\tinstance, err := factory.Instance(provider)\n\t\t\tif nil != err {\n\t\t\t\tutils.Panic(err)\n\t\t\t}\n\t\t\treturn []reflect.Value{utils.Convert(reflect.ValueOf(instance), typ.Out(0))}\n\t\t})\n\t\treturn reflect.MakeFunc(typ, proxy).Interface(), nil\n\t})\n}"} {"input": "package http\n\nimport (\n\t\"fmt\"\n\t\"github.com/denniscollective/dragonfly.go/dragonfly\"\n\t\"github.com/gorilla/handlers\"\n\t\"github.com/gorilla/mux\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\n\n\ntype benchmarkHandler struct {\n\thandler http.Handler\n}\n\nfunc (h benchmarkHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tt := time.Now()\n\th.handler.ServeHTTP(w, req)\n\tfmt.Println(time.Now().Sub(t))\n}\n\nfunc handle(h http.Handler) http.Handler {\n\n\treturn benchmarkHandler{handlers.CombinedLoggingHandler(os.Stdout, h)}\n\n}\n\nfunc hollar(response http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"hollar\")\n}\n\nfunc serveFile(response http.ResponseWriter, request *http.Request) {\n\tresponse.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\tvars := mux.Vars(request)\n\tjobStr := vars[\"b64JobString\"]\n\tfile, err := dragonfly.ImageFor(jobStr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tdata, _ := ioutil.ReadAll(file)\n\tresponse.Write(data)\n}\n\nfunc StartServer() error ", "output": "{\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"/favicon.ico\", hollar)\n\tr.HandleFunc(\"/{b64JobString}\", serveFile)\n\n\terr := http.ListenAndServe(\":2345\", handle(r))\n\treturn err\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\n\n\nfunc MFR(mass int) int {\n\treturn (mass / 3) - 2\n}\n\ntype D1 struct {\n\tmodules []int\n}\n\nfunc (d1 *D1) parse(line string) error {\n\tv, err := strconv.Atoi(line)\n\tif err == nil {\n\t\td1.modules = append(d1.modules, v)\n\t}\n\treturn err\n}\n\nfunc (d1 *D1) part1() (string, error) {\n\tsum := 0\n\tfor _, module := range d1.modules {\n\t\tsum += MFR(module)\n\t}\n\treturn fmt.Sprintf(\"Sum of fuel requirements is %d\", sum), nil\n}\n\nfunc TotalMFR(mass int) int {\n\treq := MFR(mass)\n\tif req > 0 {\n\t\treq += TotalMFR(req)\n\t} else {\n\t\treq = 0\n\t}\n\treturn req\n}\n\nfunc (d1 *D1) part2() (string, error) {\n\tsum := 0\n\tfor _, module := range d1.modules {\n\t\tsum += TotalMFR(module)\n\t}\n\treturn fmt.Sprintf(\"Sum of fuel requirements is %d\", sum), nil\n}\n\nfunc init() ", "output": "{\n\td1 := &D1{}\n\tchallenges[1] = &challenge{\"Day 01\", \"input/day01.txt\", d1}\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tcounts := make(map[string]int)\n\tnames := make(map[string][]string)\n\tfiles := os.Args[1:]\n\tif len(files) == 0 {\n\t\tcountLines(os.Stdin, counts, names)\n\t} else {\n\t\tfor _, arg := range files {\n\t\t\tf, err := os.Open(arg)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"dup2: %v\\n\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcountLines(f, counts, names)\n\t\t\tf.Close()\n\t\t}\n\t}\n\tfor line, n := range counts {\n\t\tif n > 1 {\n\t\t\tfmt.Printf(\"%s\\n\", line)\n\t\t\tfmt.Printf(\"%s\\n\\n\", names[line])\n\t\t}\n\t}\n}\n\nfunc countLines(f *os.File, counts map[string]int, names map[string][]string) {\n\tinput := bufio.NewScanner(f)\n\tfor input.Scan() {\n\t\tcounts[input.Text()]++\n\t\tvalue := names[input.Text()]\n\t\tif !contains(value, f.Name()) {\n\t\t\tnames[input.Text()] = append(names[input.Text()], f.Name())\n\t\t}\n\t}\n}\n\n\n\nfunc contains(s []string, e string) bool ", "output": "{\n\tfor _, a := range s {\n\t\tif a == e {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package budget\n\n\ntype TargetTypeEnum string\n\n\nconst (\n\tTargetTypeCompartment TargetTypeEnum = \"COMPARTMENT\"\n\tTargetTypeTag TargetTypeEnum = \"TAG\"\n)\n\nvar mappingTargetType = map[string]TargetTypeEnum{\n\t\"COMPARTMENT\": TargetTypeCompartment,\n\t\"TAG\": TargetTypeTag,\n}\n\n\n\n\nfunc GetTargetTypeEnumValues() []TargetTypeEnum ", "output": "{\n\tvalues := make([]TargetTypeEnum, 0)\n\tfor _, v := range mappingTargetType {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package main\n\nimport glfw \"github.com/go-gl/glfw3\"\nimport \"math\"\n\n\nfunc GetScreenSize() (int, int) {\n\tmonitors, err := glfw.GetMonitors()\n\tif err == nil {\n\t\tmonitor := monitors[0]\n\t\tvideoMode, err := monitor.GetVideoMode()\n\t\tif err == nil {\n\t\t\treturn videoMode.Width, videoMode.Height\n\t\t} else {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tpanic(err)\n\t}\n}\n\n\n\nfunc Round(num float64) float64 ", "output": "{\n\tif num >= 0 {\n\t\treturn math.Floor(num + 0.5)\n\t} else {\n\t\treturn math.Ceil(num - 0.5)\n\t}\n}"} {"input": "package ipwrapper\n\nimport (\n\t\"net\"\n\n\t\"github.com/containernetworking/cni/pkg/ip\"\n\t\"github.com/vishvananda/netlink\"\n)\n\ntype IP interface {\n\tAddDefaultRoute(gw net.IP, dev netlink.Link) error\n}\n\ntype ipRoute struct {\n}\n\n\n\nfunc (*ipRoute) AddDefaultRoute(gw net.IP, dev netlink.Link) error {\n\treturn ip.AddDefaultRoute(gw, dev)\n}\n\nfunc NewIP() IP ", "output": "{\n\treturn &ipRoute{}\n}"} {"input": "package gridq\n\ntype byColRow []*WriteResponse\n\n\nfunc (p byColRow) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byColRow) Less(i, j int) bool {\n\tif p[i].Col < p[j].Col {\n\t\treturn true\n\t} else if p[i].Col > p[j].Col {\n\t\treturn false\n\t} else {\n\t\treturn p[i].Row < p[j].Row\n\t}\n}\n\ntype byRowTimestamp []*ReadResponse\n\nfunc (p byRowTimestamp) Len() int { return len(p) }\nfunc (p byRowTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byRowTimestamp) Less(i, j int) bool {\n\tif p[i].Row < p[j].Row {\n\t\treturn true\n\t} else if p[i].Row > p[j].Row {\n\t\treturn false\n\t} else {\n\t\treturn p[i].State.Timestamp > p[j].State.Timestamp\n\t}\n}\n\ntype byTimestamp []*ReadResponse\n\nfunc (p byTimestamp) Len() int { return len(p) }\nfunc (p byTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byTimestamp) Less(i, j int) bool { return p[i].State.Timestamp < p[j].State.Timestamp }\n\nfunc (p byColRow) Len() int ", "output": "{ return len(p) }"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"runtime\"\n)\n\n\n\nfunc startHttpListener() {\n\tdefer func() {\n\t\tfmt.Println(\"stopped REST server...\")\n\t\tnotifier.Done()\n\t}()\n\tnotifier.Add(1)\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tnewClientHTTP(w, r)\n\t})\n\n\tsvr := http.Server{Handler: mux}\n\tsvr.Serve(tcplistener)\n}\n\nfunc newClientHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tbuf := make([]byte, 4096)\n\t\t\tn := runtime.Stack(buf, false)\n\t\t\tbuf = buf[0:n]\n\t\t\tlog.Fatalf(\"client run panic %s:%v\", buf, e)\n\t\t}\n\t\tnotifier.Done()\n\t}()\n\tnotifier.Add(1)\n\tw.Write([]byte(\"Http server is not implemented yet...\"))\n}"} {"input": "package main\n\nimport \"fmt\"\n\nconst _ChecksumType_name = \"CRC32MD5SHA1CRC32C\"\n\nvar _ChecksumType_index = [...]uint8{0, 5, 8, 12, 18}\n\n\n\nfunc (i ChecksumType) String() string ", "output": "{\n\ti -= 1\n\tif i+1 >= ChecksumType(len(_ChecksumType_index)) {\n\t\treturn fmt.Sprintf(\"ChecksumType(%d)\", i+1)\n\t}\n\treturn _ChecksumType_name[_ChecksumType_index[i]:_ChecksumType_index[i+1]]\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\n\n\nfunc main() {\n fmt.Println(Sqrt(2))\n}\n\nfunc Sqrt(x float64) float64 ", "output": "{\n \n \n \n z := 1.0\n for iter:=1; iter<=10; iter++ {\n z = z - ((math.Pow(z, 2) - x ) / (2 * z))\n }\n return z\n}"} {"input": "package serving\n\nimport (\n\t\"knative.dev/pkg/apis\"\n\t\"github.com/knative/serving/pkg/apis/autoscaling\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\n\n\n\n\nfunc ValidateObjectMetadata(meta metav1.Object) *apis.FieldError ", "output": "{\n\treturn apis.ValidateObjectMetadata(meta).Also(\n\t\tautoscaling.ValidateAnnotations(meta.GetAnnotations()).ViaField(\"annotations\"))\n}"} {"input": "package proto\n\nimport (\n\t\"fmt\"\n\t\"net\"\n)\n\n\nfunc FromNetAddr(addr net.Addr) *Addr {\n\treturn &Addr{\n\t\tNetwork: addr.Network(),\n\t\tAddress: addr.String(),\n\t}\n}\n\n\n\n\n\n\nfunc (m *GossipRequest) GetUser() string {\n\treturn \"node\"\n}\n\nfunc (a Addr) NetAddr() (net.Addr, error) ", "output": "{\n\tswitch a.Network {\n\tcase \"tcp\", \"tcp4\", \"tcp6\":\n\t\treturn net.ResolveTCPAddr(a.Network, a.Address)\n\tcase \"udp\", \"udp4\", \"udp6\":\n\t\treturn net.ResolveUDPAddr(a.Network, a.Address)\n\tcase \"unix\", \"unixgram\", \"unixpacket\":\n\t\treturn net.ResolveUnixAddr(a.Network, a.Address)\n\t}\n\treturn nil, fmt.Errorf(\"network %s not supported\", a.Network)\n}"} {"input": "package matchers\n\nimport (\n\t\"github.com/nttlabs/cli/cf/errors\"\n\ttestcmd \"github.com/nttlabs/cli/testhelpers/commands\"\n\t\"github.com/onsi/gomega\"\n)\n\ntype havePassedRequirementsMatcher struct{}\n\nfunc HavePassedRequirements() gomega.OmegaMatcher {\n\treturn havePassedRequirementsMatcher{}\n}\n\nfunc (matcher havePassedRequirementsMatcher) Match(actual interface{}) (bool, error) {\n\tswitch actual.(type) {\n\tcase bool:\n\t\tasBool := actual.(bool)\n\t\treturn asBool == true, nil\n\tcase testcmd.RunCommandResult:\n\t\tresult := actual.(testcmd.RunCommandResult)\n\t\treturn result == testcmd.RunCommandResultSuccess, nil\n\tdefault:\n\t\treturn false, errors.NewWithFmt(\"Expected actual value to be a bool or enum, but it was a %T\", actual)\n\t}\n}\n\nfunc (matcher havePassedRequirementsMatcher) FailureMessage(_ interface{}) string {\n\treturn \"Expected command to pass requirements but it did not\"\n}\n\n\n\nfunc (matcher havePassedRequirementsMatcher) NegatedFailureMessage(_ interface{}) string ", "output": "{\n\treturn \"Expected command to have not passed requirements but it did\"\n}"} {"input": "package client\n\nimport \"testing\"\n\nvar emptySyncGroupRequestBytes = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}\nvar goodSyncGroupRequestBytes = []byte{0x00, 0x03, 'f', 'o', 'o', 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 'b', 'a', 'r', 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 'f', 'o', 'o', 0x00, 0x00, 0x00, 0x01, 0x01}\n\nvar errorSyncGroupResponseBytes = []byte{0x00, 27, 0x00, 0x00, 0x00, 0x00}\nvar goodSyncGroupResponseBytes = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01}\n\n\n\nfunc TestSyncGroupResponse(t *testing.T) {\n\terrorSyncGroupResponse := new(SyncGroupResponse)\n\tdecode(t, errorSyncGroupResponse, errorSyncGroupResponseBytes)\n\tassert(t, errorSyncGroupResponse.Error, ErrRebalanceInProgress)\n\n\tgoodSyncGroupResponse := new(SyncGroupResponse)\n\tdecode(t, goodSyncGroupResponse, goodSyncGroupResponseBytes)\n\tassert(t, goodSyncGroupResponse.Error, ErrNoError)\n\tassert(t, goodSyncGroupResponse.MemberAssignment, []byte{1})\n}\n\nfunc TestSyncGroupRequest(t *testing.T) ", "output": "{\n\temptySyncGroupRequest := new(SyncGroupRequest)\n\ttestRequest(t, emptySyncGroupRequest, emptySyncGroupRequestBytes)\n\n\tgoodSyncGroupRequest := new(SyncGroupRequest)\n\tgoodSyncGroupRequest.GroupID = \"foo\"\n\tgoodSyncGroupRequest.GenerationID = 3\n\tgoodSyncGroupRequest.MemberID = \"bar\"\n\tgoodSyncGroupRequest.GroupAssignment = map[string][]byte{\n\t\t\"foo\": {1},\n\t}\n\ttestRequest(t, goodSyncGroupRequest, goodSyncGroupRequestBytes)\n}"} {"input": "package chipmunk\n\nimport (\n\t\"github.com/Dethrail/chipmunk/transform\"\n\t\"github.com/Dethrail/chipmunk/vect\"\n\t\"math\"\n)\n\nconst (\n\tRadianConst = math.Pi / 180\n\tDegreeConst = 180 / math.Pi\n)\n\ntype Group int\ntype Layer int\n\ntype Shape struct {\n\tDefaultHash\n\tShapeClass\n\n\tBody *Body\n\n\tBB AABB\n\n\tIsSensor bool\n\n\te vect.Float\n\tu vect.Float\n\tSurface_v vect.Vect\n\n\tUserData interface{}\n\n\tGroup Group\n\tLayer Layer\n\n\tspace *Space\n\n\tvelocityIndexed bool\n}\n\n\n\nfunc (shape *Shape) Velocity() (vect.Vect, bool) {\n\treturn shape.Body.v, shape.velocityIndexed\n}\n\nfunc (shape *Shape) SetFriction(friction vect.Float) {\n\tshape.u = friction\n}\n\nfunc (shape *Shape) SetElasticity(e vect.Float) {\n\tshape.e = e\n}\n\nfunc (shape *Shape) Shape() *Shape {\n\treturn shape\n}\n\nfunc (shape *Shape) AABB() AABB {\n\treturn shape.BB\n}\n\nfunc (shape *Shape) Clone() *Shape {\n\tclone := *shape\n\tcc := &clone\n\tcc.space = nil\n\tcc.DefaultHash.Reset()\n\tcc.Body = nil\n\tcc.ShapeClass = cc.ShapeClass.Clone(cc)\n\treturn cc\n}\n\nfunc (shape *Shape) Update() {\n\tshape.BB = shape.ShapeClass.update(transform.NewTransform(shape.Body.p, shape.Body.a))\n}\n\nfunc newShape() *Shape ", "output": "{\n\treturn &Shape{velocityIndexed: true, e: 0.5, u: 0.5, Layer: -1}\n\n}"} {"input": "package tfbparser\n\nimport \"github.com/kiwih/goFB/iec61499\"\n\n\ntype tfbParse struct {\n\tfbs []iec61499.FB\n\n\titems []string\n\titemIndex int\n\n\tcurrentLine int\n\tcurrentFile string\n}\n\n\nfunc (t *tfbParse) getCurrentDebugInfo() iec61499.DebugInfo {\n\treturn iec61499.DebugInfo{\n\t\tSourceLine: t.currentLine,\n\t\tSourceFile: t.currentFile,\n\t}\n}\n\n\nfunc (t *tfbParse) isFBNameUnused(name string) bool {\n\tfor i := 0; i < len(t.fbs); i++ {\n\t\tif t.fbs[i].Name == name {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\nfunc (t *tfbParse) pop() string {\n\tif t.done() {\n\t\treturn \"\"\n\t}\n\ts := t.items[t.itemIndex]\n\tt.itemIndex++\n\n\tif s == pNewline {\n\t\tt.currentLine++\n\t\treturn t.pop()\n\t}\n\treturn s\n}\n\n\n\n\n\n\nfunc (t *tfbParse) done() bool {\n\treturn t.itemIndex >= len(t.items)\n}\n\n\n\nfunc (t *tfbParse) getFBIndexFromName(name string) int {\n\tfor i := 0; i < len(t.fbs); i++ {\n\t\tif t.fbs[i].Name == name {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (t *tfbParse) peek() string ", "output": "{\n\tif t.done() {\n\t\treturn \"\"\n\t}\n\tfor i := 0; i < len(t.items); i++ {\n\t\tif t.items[t.itemIndex+i] != pNewline {\n\t\t\treturn t.items[t.itemIndex+i]\n\t\t}\n\t}\n\treturn \"\"\n}"} {"input": "package vm\n\ntype Networks map[string]Network\n\ntype Network struct {\n\tType string `json:\"type\"`\n\n\tIP string `json:\"ip,omitempty\"`\n\tNetmask string `json:\"netmask,omitempty\"`\n\tGateway string `json:\"gateway,omitempty\"`\n\n\tDNS []string `json:\"dns,omitempty\"`\n\tDefault []string `json:\"default,omitempty\"`\n\n\tPreconfigured bool `json:\"preconfigured,omitempty\"`\n\n\tMAC string `json:\"mac,omitempty\"`\n\n\tCloudProperties map[string]interface{} `json:\"cloud_properties,omitempty\"`\n}\n\nfunc (ns Networks) First() Network {\n\tfor _, net := range ns {\n\t\treturn net\n\t}\n\n\treturn Network{}\n}\n\nfunc (n Network) IsDynamic() bool { return n.Type == \"dynamic\" }\n\n\n\nfunc (n Network) AppendDNS(dns string) Network ", "output": "{\n\tif len(dns) > 0 {\n\t\tn.DNS = append(n.DNS, dns)\n\t\treturn n\n\t}\n\treturn n\n}"} {"input": "package builders\n\nimport (\n\t\"time\"\n\n\t\"github.com/docker/docker/api/types\"\n)\n\n\n\n\n\n\nfunc WithLabel(key, value string) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tif c.Labels == nil {\n\t\t\tc.Labels = map[string]string{}\n\t\t}\n\t\tc.Labels[key] = value\n\t}\n}\n\n\nfunc WithName(name string) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tc.Names = append(c.Names, \"/\"+name)\n\t}\n}\n\n\nfunc WithPort(privateport, publicport uint16, builders ...func(*types.Port)) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tif c.Ports == nil {\n\t\t\tc.Ports = []types.Port{}\n\t\t}\n\t\tport := &types.Port{\n\t\t\tPrivatePort: privateport,\n\t\t\tPublicPort: publicport,\n\t\t}\n\t\tfor _, builder := range builders {\n\t\t\tbuilder(port)\n\t\t}\n\t\tc.Ports = append(c.Ports, *port)\n\t}\n}\n\n\nfunc IP(ip string) func(*types.Port) {\n\treturn func(p *types.Port) {\n\t\tp.IP = ip\n\t}\n}\n\n\nfunc TCP(p *types.Port) {\n\tp.Type = \"tcp\"\n}\n\n\nfunc UDP(p *types.Port) {\n\tp.Type = \"udp\"\n}\n\nfunc Container(name string, builders ...func(container *types.Container)) *types.Container ", "output": "{\n\tcontainer := &types.Container{\n\t\tID: \"container_id\",\n\t\tNames: []string{\"/\" + name},\n\t\tCommand: \"top\",\n\t\tImage: \"busybox:latest\",\n\t\tStatus: \"Up 1 second\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tfor _, builder := range builders {\n\t\tbuilder(container)\n\t}\n\n\treturn container\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n)\n\n\nconst DeleteDeploymentOKCode int = 200\n\n\ntype DeleteDeploymentOK struct {\n}\n\n\nfunc NewDeleteDeploymentOK() *DeleteDeploymentOK {\n\treturn &DeleteDeploymentOK{}\n}\n\n\nfunc (o *DeleteDeploymentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n}\n\n\nconst DeleteDeploymentUnauthorizedCode int = 401\n\n\ntype DeleteDeploymentUnauthorized struct {\n\tWWWAuthenticate string `json:\"WWW_Authenticate\"`\n}\n\n\nfunc NewDeleteDeploymentUnauthorized() *DeleteDeploymentUnauthorized {\n\treturn &DeleteDeploymentUnauthorized{}\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) WithWWWAuthenticate(wWWAuthenticate string) *DeleteDeploymentUnauthorized {\n\to.WWWAuthenticate = wWWAuthenticate\n\treturn o\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) SetWWWAuthenticate(wWWAuthenticate string) {\n\to.WWWAuthenticate = wWWAuthenticate\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\n\twWWAuthenticate := o.WWWAuthenticate\n\tif wWWAuthenticate != \"\" {\n\t\trw.Header().Set(\"WWW_Authenticate\", wWWAuthenticate)\n\t}\n\n\trw.WriteHeader(401)\n}\n\n\nconst DeleteDeploymentNotFoundCode int = 404\n\n\ntype DeleteDeploymentNotFound struct {\n}\n\n\n\n\n\nfunc (o *DeleteDeploymentNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(404)\n}\n\n\nconst DeleteDeploymentInternalServerErrorCode int = 500\n\n\ntype DeleteDeploymentInternalServerError struct {\n}\n\n\nfunc NewDeleteDeploymentInternalServerError() *DeleteDeploymentInternalServerError {\n\treturn &DeleteDeploymentInternalServerError{}\n}\n\n\nfunc (o *DeleteDeploymentInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(500)\n}\n\nfunc NewDeleteDeploymentNotFound() *DeleteDeploymentNotFound ", "output": "{\n\treturn &DeleteDeploymentNotFound{}\n}"} {"input": "package main\n\n\nimport (\n \"github.com/PuerkitoBio/goquery\"\n \"github.com/hu17889/go_spider/core/common/page\"\n \"github.com/hu17889/go_spider/core/pipeline\"\n \"github.com/hu17889/go_spider/core/spider\"\n \"strings\"\n \"fmt\"\n)\n\ntype MyPageProcesser struct {\n}\n\nfunc NewMyPageProcesser() *MyPageProcesser {\n return &MyPageProcesser{}\n}\n\n\n\n\n\nfunc (this *MyPageProcesser) Finish() {\n fmt.Printf(\"TODO:before end spider \\r\\n\")\n}\n\nfunc main() {\n \n \n \n spider.NewSpider(NewMyPageProcesser(), \"TaskName\").\n AddUrl(\"http:www.stelladot.com/shop/\", \"html\"). \n AddPipeline(pipeline.NewPipelineConsole()). \n SetThreadnum(3). \n Run()\n}\n\nfunc (this *MyPageProcesser) Process(p *page.Page) ", "output": "{\n if !p.IsSucc() {\n println(p.Errormsg())\n return\n }\n\n query := p.GetHtmlParser()\n var urls []string\n query.Find(\"h3[class='repo-list-name'] a\").Each(func(i int, s *goquery.Selection) {\n href, _ := s.Attr(\"href\")\n urls = append(urls, \"http:www.stelladot.com/\"+href)\n })\n \n p.AddTargetRequests(urls, \"html\")\n\n name := query.Find(\".entry-title .author\").Text()\n name = strings.Trim(name, \" \\t\\n\")\n repository := query.Find(\".entry-title .js-current-repository\").Text()\n repository = strings.Trim(repository, \" \\t\\n\")\n \n if name == \"\" {\n p.SetSkip(true)\n }\n \n p.AddField(\"author\", name)\n p.AddField(\"project\", repository)\n \n}"} {"input": "package tasks\n\nimport (\n\t\"strings\"\n\t\"os/exec\"\n\t\"log\"\n)\n\n\nconst (\n\tPYTHON_COMMAND_ARG = \"command\"\n\tPYTHON_ARGS_ARG = \"args\"\n)\n\ntype Python struct {\n\targs\t\t[]string\n}\n\nfunc (t *Python) Configure(args map[string]string) statusCode {\n\tval, ok := args[PYTHON_COMMAND_ARG]\n\n\tif !ok {\n\t\treturn StatusConfigurationError\n\t}\n\tt.args = make([]string, 0)\n\tt.args = append(t.args, val)\n\n\tval, ok = args[PYTHON_ARGS_ARG]\n\tif !ok {\n\t\treturn StatusConfigurationError\n\t}\n\tt.args = append(t.args, strings.Split(val, \" \")...)\n\n\treturn StatusOk\n}\n\nfunc (t *Python) Execute() statusCode {\n\terr := exec.Command(\"python2.7\", t.args...).Run()\n\n\tif err != nil {\n\t\tlog.Printf(\"execute error: %s\\n\", err.Error())\n\t\treturn StatusExecutionError\n\t}\n\n\treturn StatusOk\n}\n\n\n\nfunc (t *Python) GetName() string ", "output": "{\n\treturn \"python\"\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\ntype SendPhotoLinkBody struct {\n\n\tCaption string `json:\"caption,omitempty\"`\n\n\tChatID interface{} `json:\"chat_id\"`\n\n\tDisableNotification bool `json:\"disable_notification,omitempty\"`\n\n\tPhoto *string `json:\"photo\"`\n\n\tReplyMarkup interface{} `json:\"reply_markup,omitempty\"`\n\n\tReplyToMessageID int64 `json:\"reply_to_message_id,omitempty\"`\n}\n\n\nfunc (m *SendPhotoLinkBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateChatID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePhoto(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc (m *SendPhotoLinkBody) validateChatID(formats strfmt.Registry) error {\n\n\treturn nil\n}\n\n\n\n\nfunc (m *SendPhotoLinkBody) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *SendPhotoLinkBody) UnmarshalBinary(b []byte) error {\n\tvar res SendPhotoLinkBody\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *SendPhotoLinkBody) validatePhoto(formats strfmt.Registry) error ", "output": "{\n\n\tif err := validate.Required(\"photo\", \"body\", m.Photo); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package pdf\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\n\t\"github.com/jung-kurt/gofpdf\"\n)\n\nconst (\n\tmargin = 0\n)\n\ntype Pdf struct {\n\tdoc pdfDoc\n\tsupportedExtensions map[string]struct{}\n}\n\ntype pdfDoc interface {\n\tAddPageFormat(string, gofpdf.SizeType)\n\tClose()\n\tErr() bool\n\tError() error\n\tImage(string, float64, float64, float64, float64, bool, string, int, string)\n\tOutputFileAndClose(string) error\n\tRegisterImage(string, string) *gofpdf.ImageInfoType\n\tSetMargins(float64, float64, float64)\n}\n\nfunc New() (p *Pdf) {\n\tp = &Pdf{\n\t\tdoc: gofpdf.NewCustom(&gofpdf.InitType{\n\t\t\tOrientationStr: \"Portrait\",\n\t\t\tUnitStr: \"pt\",\n\t\t}),\n\t\tsupportedExtensions: map[string]struct{}{\n\t\t\t\".png\": {},\n\t\t\t\".jpg\": {},\n\t\t\t\".jpeg\": {},\n\t\t},\n\t}\n\tp.doc.SetMargins(margin, margin, margin)\n\treturn\n}\n\n\n\nfunc (p *Pdf) Supports(path string) bool {\n\t_, contains := p.supportedExtensions[filepath.Ext(path)]\n\treturn contains\n}\n\nfunc (p *Pdf) Write(dest string) error {\n\tfmt.Printf(\"Writing PDF to %s\\n\", dest)\n\treturn p.doc.OutputFileAndClose(dest)\n}\n\nfunc (p *Pdf) AddImage(file string) error ", "output": "{\n\timgInfo := p.doc.RegisterImage(file, \"\")\n\tw, h := imgInfo.Extent()\n\n\tp.doc.AddPageFormat(\"Portrait\", gofpdf.SizeType{Wd: w, Ht: h})\n\tp.doc.Image(file, 0, 0, w, h, false, \"\", 0, \"\")\n\n\tif p.doc.Err() {\n\t\tp.doc.Close()\n\t\treturn fmt.Errorf(\"Error adding '%s' to PDF, %v\", file, p.doc.Error())\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"net/http\"\n)\n\nfunc PingHandler(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"PONG!\"})\n}\n\nfunc GetAllStats(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"statistics go here\"})\n}\n\nfunc GetAllImages(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"all images go here\"})\n}\n\nfunc GetImage(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"one image goes here\"})\n}\n\n\n\nfunc UpdateImage(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"ID of the image we updated goes here\"})\n}\n\nfunc CreateImage(c *gin.Context) ", "output": "{\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"ID of the image we created goes here\"})\n}"} {"input": "package v1\n\nimport (\n\tv1 \"github.com/openshift/api/oauth/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\n\ntype OAuthAuthorizeTokenLister interface {\n\tList(selector labels.Selector) (ret []*v1.OAuthAuthorizeToken, err error)\n\tGet(name string) (*v1.OAuthAuthorizeToken, error)\n\tOAuthAuthorizeTokenListerExpansion\n}\n\n\ntype oAuthAuthorizeTokenLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewOAuthAuthorizeTokenLister(indexer cache.Indexer) OAuthAuthorizeTokenLister {\n\treturn &oAuthAuthorizeTokenLister{indexer: indexer}\n}\n\n\n\n\n\nfunc (s *oAuthAuthorizeTokenLister) Get(name string) (*v1.OAuthAuthorizeToken, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"oauthauthorizetoken\"), name)\n\t}\n\treturn obj.(*v1.OAuthAuthorizeToken), nil\n}\n\nfunc (s *oAuthAuthorizeTokenLister) List(selector labels.Selector) (ret []*v1.OAuthAuthorizeToken, err error) ", "output": "{\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.OAuthAuthorizeToken))\n\t})\n\treturn ret, err\n}"} {"input": "package statsd_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\t\"github.com/cv-library/statsd\"\n)\n\n\n\nfunc ExampleTimer() {\n\ttimer := statsd.Timer()\n\tfor i:=0; i<10; i++ {\n\t\ttimer.Reset()\n\n\n\t\ttook := timer.Send(\"work.duration\")\n\t\ttimer.SendWithOptions(\n\t\t\t&statsd.Options{ Rate: 0.25 },\n\t\t\t\"work.duration.sampled\",\n\t\t)\n\n\t\tfmt.Printf(\"Took %f seconds\\n\", took.Seconds())\n\t}\n}\n\nfunc ExampleTime() {\n\tfor i:=0; i<10; i++ {\n\t\tstart := time.Now()\n\n\n\t\tstatsd.Time(\"work.duration\", time.Since(start))\n\t}\n}\n\nfunc ExampleTimeWithOptions() {\n\tfor i:=0; i<10; i++ {\n\t\tstart := time.Now()\n\n\n\t\tif i % 2 == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tstatsd.TimeWithOptions(\n\t\t\t&statsd.Options{ Rate: 0.5, AlwaysSend: true },\n\t\t\t\"work.duration.sampled\",\n\t\t\ttime.Since(start),\n\t\t)\n\t}\n}\n\nfunc ExampleInc() {\n\tstatsd.Inc(\"stats.success\")\n}\n\nfunc ExampleIncWithOptions() {\n\tstatsd.IncWithOptions(\n\t\t&statsd.Options{ Rate: 0.5 },\n\t\t\"stats.success\",\n\t)\n}\n\nfunc ExampleGauge() {\n\tstatsd.Gauge(\"page.size\", 10)\n}\n\nfunc ExampleGaugeWithOptions() {\n\tstatsd.GaugeWithOptions(\n\t\t&statsd.Options{ Rate: 0.5 },\n\t\t\"page.size\",\n\t\t10,\n\t)\n}\n\nfunc ExampleTiming() ", "output": "{\n\tfor i:=0; i<10; i++ {\n\t\ttimer := statsd.Timer()\n\n\n\t\ttook := timer.Send(\"work.duration\")\n\t\ttimer.SendWithOptions(\n\t\t\t&statsd.Options{ Rate: 0.25 },\n\t\t\t\"work.duration.sampled\",\n\t\t)\n\n\t\tfmt.Printf(\"Took %f seconds\\n\", took.Seconds())\n\t}\n}"} {"input": "package collaboration\n\nimport \"sync\"\n\nfunc NewMemoryStorage() *memoryStorage {\n\treturn &memoryStorage{\n\t\tusers: make(map[string]*Option),\n\t}\n}\n\n\ntype memoryStorage struct {\n\tusers map[string]*Option\n\tsync.Mutex\n}\n\nfunc (m *memoryStorage) Get(username string) (*Option, error) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\toption, ok := m.users[username]\n\tif !ok {\n\t\treturn nil, ErrUserNotFound\n\t}\n\n\treturn option, nil\n}\n\nfunc (m *memoryStorage) GetAll() (map[string]*Option, error) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\treturn m.users, nil\n}\n\nfunc (m *memoryStorage) Set(username string, value *Option) error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tm.users[username] = value\n\treturn nil\n}\n\nfunc (m *memoryStorage) Delete(username string) error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tdelete(m.users, username)\n\treturn nil\n}\n\n\n\nfunc (m *memoryStorage) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport \"github.com/gopherjs/gopherjs/js\"\n\n\n\nfunc uint8ArrayToString(buf uintptr) string {\n\tarray := js.InternalObject(buf)\n\tslice := make([]byte, array.Length())\n\tjs.InternalObject(slice).Set(\"$array\", array)\n\treturn string(slice)\n}\n\nfunc uint8ArrayToBytes(buf uintptr) []byte ", "output": "{\n\tarray := js.InternalObject(buf)\n\tslice := make([]byte, array.Length())\n\tjs.InternalObject(slice).Set(\"$array\", array)\n\treturn slice\n}"} {"input": "package logberry\n\nimport (\n\t\"os\"\n\t\"path\"\n)\n\n\nvar Std *Root\n\n\n\nvar Main *Task\n\n\n\nfunc init() ", "output": "{\n\n\tStd = NewRoot(24)\n\tStd.AddOutputDriver(NewStdOutput(path.Base(os.Args[0])))\n\tStd.AddErrorListener(new(StdErrorListener))\n\n\tMain = &Task{\n\t\tuid: newtaskuid(),\n\t\tcomponent: \"main\",\n\t\tactivity: \"Component main\",\n\t\troot: Std,\n\t}\n\n}"} {"input": "package response\n\nimport \"warcluster/entities\"\n\ntype OwnerChange struct {\n\tbaseResponse\n\tRawPlanet map[string]*entities.Planet `json:\"-\"`\n\tPlanet map[string]*entities.PlanetPacket `json:\",omitempty\"`\n}\n\nfunc NewOwnerChange() *OwnerChange {\n\tr := new(OwnerChange)\n\tr.Command = \"owner_change\"\n\treturn r\n}\n\n\n\nfunc (o *OwnerChange) Sanitize(player *entities.Player) ", "output": "{\n\to.Planet = SanitizePlanets(player, o.RawPlanet)\n}"} {"input": "package foo\n\nfunc f(x interface{}) {\n\tswitch t := x.(type) { \n\tcase int:\n\t}\n}\n\nfunc g(x interface{}) {\n\tswitch t := x.(type) {\n\tcase int:\n\tcase float32:\n\t\tprintln(t)\n\t}\n}\n\n\n\nfunc h(x interface{}) ", "output": "{\n\tswitch t := x.(type) {\n\tcase int:\n\tcase float32:\n\tdefault:\n\t\tprintln(t)\n\t}\n}"} {"input": "package proxyprotocol\n\nimport (\n\t\"net\"\n)\n\ntype listener struct {\n\traw net.Listener\n}\n\nfunc Listen(raw net.Listener) net.Listener {\n\treturn &listener{raw}\n}\n\nfunc (l *listener) Accept() (c net.Conn, err error) {\n\traw, err := l.raw.Accept()\n\tif err == nil {\n\t\tc = &conn{\n\t\t\traw: raw,\n\t\t}\n\t}\n\treturn\n}\n\nfunc (l *listener) Close() error {\n\treturn l.raw.Close()\n}\n\n\n\nfunc (l *listener) Addr() net.Addr ", "output": "{\n\treturn l.raw.Addr()\n}"} {"input": "package middleware\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"runtime\"\n\n\t\"github.com/docker/docker/pkg/version\"\n\t\"golang.org/x/net/context\"\n)\n\ntype badRequestError struct {\n\terror\n}\n\n\n\n\n\ntype VersionMiddleware struct {\n\tserverVersion version.Version\n\tdefaultVersion version.Version\n\tminVersion version.Version\n}\n\n\n\nfunc NewVersionMiddleware(s, d, m version.Version) VersionMiddleware {\n\treturn VersionMiddleware{\n\t\tserverVersion: s,\n\t\tdefaultVersion: d,\n\t\tminVersion: m,\n\t}\n}\n\n\nfunc (v VersionMiddleware) WrapHandler(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {\n\t\tapiVersion := version.Version(vars[\"version\"])\n\t\tif apiVersion == \"\" {\n\t\t\tapiVersion = v.defaultVersion\n\t\t}\n\n\t\tif apiVersion.GreaterThan(v.defaultVersion) {\n\t\t\treturn badRequestError{fmt.Errorf(\"client is newer than server (client API version: %s, server API version: %s)\", apiVersion, v.defaultVersion)}\n\t\t}\n\t\tif apiVersion.LessThan(v.minVersion) {\n\t\t\treturn badRequestError{fmt.Errorf(\"client version %s is too old. Minimum supported API version is %s, please upgrade your client to a newer version\", apiVersion, v.minVersion)}\n\t\t}\n\n\t\theader := fmt.Sprintf(\"Docker/%s (%s)\", v.serverVersion, runtime.GOOS)\n\t\tw.Header().Set(\"Server\", header)\n\t\tctx = context.WithValue(ctx, \"api-version\", apiVersion)\n\t\treturn handler(ctx, w, r, vars)\n\t}\n\n}\n\nfunc (badRequestError) HTTPErrorStatusCode() int ", "output": "{\n\treturn http.StatusBadRequest\n}"} {"input": "package runtime\n\nimport \"unsafe\"\n\n\nfunc readUnaligned32(p unsafe.Pointer) uint32 {\n\tq := (*[4]byte)(p)\n\treturn uint32(q[0]) + uint32(q[1])<<8 + uint32(q[2])<<16 + uint32(q[3])<<24\n}\n\n\n\nfunc readUnaligned64(p unsafe.Pointer) uint64 ", "output": "{\n\tq := (*[8]byte)(p)\n\treturn uint64(q[0]) + uint64(q[1])<<8 + uint64(q[2])<<16 + uint64(q[3])<<24 + uint64(q[4])<<32 + uint64(q[5])<<40 + uint64(q[6])<<48 + uint64(q[7])<<56\n}"} {"input": "package util\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\nvar rootPath = getCutoRoot()\n\nfunc getCutoRoot() string {\n\td := os.Getenv(\"CUTOROOT\")\n\tif len(d) == 0 {\n\t\tpanic(\"Not setting environment argument $CUTOROOT\")\n\t}\n\treturn d\n}\n\n\n\n\n\nfunc GetCurrentPath() string {\n\treturn filepath.Join(rootPath, \"bin\")\n}\n\nfunc GetRootPath() string ", "output": "{\n\treturn rootPath\n}"} {"input": "package opts\n\n\ntype CreateOption func(*CreateConfig)\n\n\n\ntype CreateConfig struct {\n\tOptions map[string]string\n\tLabels map[string]string\n\tReference string\n}\n\n\n\nfunc WithCreateLabels(labels map[string]string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Labels = labels\n\t}\n}\n\n\n\nfunc WithCreateOptions(opts map[string]string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Options = opts\n\t}\n}\n\n\n\n\nfunc WithCreateReference(ref string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Reference = ref\n\t}\n}\n\n\n\ntype GetConfig struct {\n\tDriver string\n\tReference string\n\tResolveStatus bool\n}\n\n\ntype GetOption func(*GetConfig)\n\n\n\n\n\n\n\n\n\nfunc WithGetReference(ref string) GetOption {\n\treturn func(o *GetConfig) {\n\t\to.Reference = ref\n\t}\n}\n\n\n\nfunc WithGetResolveStatus(cfg *GetConfig) {\n\tcfg.ResolveStatus = true\n}\n\n\ntype RemoveConfig struct {\n\tPurgeOnError bool\n}\n\n\ntype RemoveOption func(*RemoveConfig)\n\n\n\n\nfunc WithPurgeOnError(b bool) RemoveOption {\n\treturn func(o *RemoveConfig) {\n\t\to.PurgeOnError = b\n\t}\n}\n\nfunc WithGetDriver(name string) GetOption ", "output": "{\n\treturn func(o *GetConfig) {\n\t\to.Driver = name\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype UpdateInternetGatewayRequest struct {\n\n\tIgId *string `mandatory:\"true\" contributesTo:\"path\" name:\"igId\"`\n\n\tUpdateInternetGatewayDetails `contributesTo:\"body\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request UpdateInternetGatewayRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request UpdateInternetGatewayRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request UpdateInternetGatewayRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype UpdateInternetGatewayResponse struct {\n\n\tRawResponse *http.Response\n\n\tInternetGateway `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response UpdateInternetGatewayResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response UpdateInternetGatewayResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package engine\n\n\ntype Novel struct {\n\tName string \n\tLastUpdateTime string \n\tAuthor string \n\tMenuURL string \n\tIconURL string \n\tNewestLastChapterName string \n\tDescription string \n\tMenus []*Menu \n\tChapters []*Chapter \n}\n\n\ntype Menu struct {\n\tName string \n\tURL string \n}\n\n\ntype Chapter struct {\n\tTitle string \n\tContent string \n}\n\nfunc (novel *Novel) AddMenu(menu *Menu) {\n\tnovel.Menus = append(novel.Menus, menu)\n}\n\nfunc (novel *Novel) AddChapter(chapter *Chapter) {\n\tnovel.Chapters = append(novel.Chapters, chapter)\n}\n\nfunc NewMenu(name, url string) *Menu {\n\treturn &Menu{name, url}\n}\n\n\n\nfunc NewChapter(title, content string) *Chapter ", "output": "{\n\treturn &Chapter{title, content}\n}"} {"input": "package gogen\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\n\t\"text/template\"\n\n\t\"github.com/gobuffalo/genny\"\n\t\"github.com/pkg/errors\"\n)\n\nvar TemplateHelpers = map[string]interface{}{}\n\n\nfunc TemplateTransformer(data interface{}, helpers map[string]interface{}) genny.Transformer {\n\tif helpers == nil {\n\t\thelpers = TemplateHelpers\n\t}\n\tt := genny.NewTransformer(\".tmpl\", func(f genny.File) (genny.File, error) {\n\t\treturn renderWithTemplate(f, data, helpers)\n\t})\n\tt.StripExt = true\n\treturn t\n}\n\n\n\nfunc renderWithTemplate(f genny.File, data interface{}, helpers template.FuncMap) (genny.File, error) ", "output": "{\n\tif f == nil {\n\t\treturn f, errors.New(\"file was nil\")\n\t}\n\tpath := f.Name()\n\tt := template.New(path)\n\tif helpers != nil {\n\t\tt = t.Funcs(helpers)\n\t}\n\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn f, errors.WithStack(err)\n\t}\n\tt, err = t.Parse(string(b))\n\tif err != nil {\n\t\treturn f, errors.WithStack(err)\n\t}\n\n\tvar bb bytes.Buffer\n\tif err = t.Execute(&bb, data); err != nil {\n\t\terr = errors.WithStack(err)\n\t\treturn f, errors.WithStack(err)\n\t}\n\treturn genny.StripExt(genny.NewFile(path, &bb), \".tmpl\"), nil\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n)\n\n\n\nfunc main() {\n fmt.Print(\"Enter the string: \")\n var name string\n fmt.Scanf(\"%s\", &name)\n\n if isPalindrome(name) {\n fmt.Printf(\"%s is Palindrome.\\n\", name)\n } else {\n fmt.Printf(\"%s is not Palindrome.\\n\", name)\n }\n}\n\nfunc isPalindrome(str string) bool ", "output": "{\n var palindromeFlag bool = true\n\n for i := 0; i <= (len(str)/2); i++ {\n if str[i] != str[len(str) - (i + 1)] {\n palindromeFlag = false\n break\n }\n }\n return palindromeFlag\n}"} {"input": "package create_topic\n\nimport (\n\t\"encoding/xml\"\n\t\"net/http\"\n\n\t\"github.com/vburenin/firempq/server/snsproto/sns_query\"\n\t\"github.com/vburenin/firempq/server/snsproto/sns_response\"\n\t\"github.com/vburenin/firempq/server/snsproto/snsdefs\"\n\t\"github.com/vburenin/firempq/server/snsproto/snserr\"\n\t\"github.com/vburenin/firempq/server/snsproto/tmgr\"\n\t\"github.com/vburenin/firempq/server/snsproto/validation\"\n)\n\ntype CreateTopicResponse struct {\n\tXMLName xml.Name `xml:\"http://sns.amazonaws.com/doc/2010-03-31/ CreateTopicResponse\"`\n\tTopicArn string `xml:\"CreateTopicResult>TopicArn\"`\n\tRequestId string `xml:\"ResponseMetadata>RequestId\"`\n}\n\nfunc (s *CreateTopicResponse) XmlDocument() string { return sns_response.EncodeXml(s) }\n\n\nfunc CreateTopic(tm *tmgr.TopicManager, snsQuery *sns_query.SNSQuery) sns_response.SNSResponse {\n\ttopicName := \"\"\n\tsns_query.ParseParams(snsQuery, func(k, v string) {\n\t\tif k == \"Name\" {\n\t\t\ttopicName = v\n\t\t}\n\t})\n\n\tif !validation.ValidateTopicName(topicName) {\n\t\treturn snserr.InvalidParameterError(\"Invalid parameter: Topic Name\")\n\t}\n\n\tarn := tm.CreateTopic(topicName)\n\n\treturn &CreateTopicResponse{\n\t\tXMLName: xml.Name{\n\t\t\tSpace: snsdefs.XMLSpace,\n\t\t\tLocal: \"CreateTopicResponse\",\n\t\t},\n\t\tTopicArn: arn,\n\t\tRequestId: \"reqId\",\n\t}\n}\n\nfunc (s *CreateTopicResponse) HttpCode() int ", "output": "{ return http.StatusOK }"} {"input": "package design\n\n\n\n\n\n\n\nimport (\n\t\"fmt\"\n)\n\ntype PhoneBrand interface {\n\tSetSoft(s Soft)\n\tRun()\n}\ntype Soft interface {\n\tRun()\n}\ntype Nokia struct {\n\ts Soft\n}\n\nfunc (n *Nokia) SetSoft(s Soft) {\n\tn.s = s\n}\nfunc (n Nokia) Run() {\n\tfmt.Println(\"nokia\")\n\tn.s.Run()\n}\n\ntype Game struct {\n}\n\n\n\nfunc (g Game) Run() ", "output": "{\n\tfmt.Println(\"手机游戏\")\n}"} {"input": "package netlink\n\n\n\nimport \"strconv\"\n\n\ntype Address struct {\n pid int\n}\n\n\nfunc (self Address)Network()(string){ return \"netlink\" }\n\n\n\nfunc (self Address)Address()(string)", "output": "{ return strconv.Itoa(self.pid) }"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Frame struct {\n\tNotice string\n\tAuth string\n\tShit string\n\tMessage string\n}\n\ntype UserFrame struct {\n\tName2, Name3 string\n\tHost string\n\tName4 string\n}\n\nfunc getFrame(input []string, c int) string {\n\tif c > len(input) {\n\t\treturn \"\"\n\t}\n\n\treturn input[c]\n}\nfunc DeserializeUserFrame(input string) *UserFrame {\n\tdob := strings.Split(input, \" \")\n\tc := &UserFrame{\n\t\tName2: getFrame(dob, 1),\n\t\tName3: getFrame(dob, 2),\n\t\tHost: getFrame(dob, 3),\n\t\tName4: getFrame(dob, 4),\n\t}\n\treturn c\n}\n\nfunc (f *Frame) SerializeToString() string {\n\treturn fmt.Sprintf(\"%s %s %s %s\\n\", f.Notice, f.Auth, f.Shit, f.Message)\n}\n\n\n\nfunc (f *Frame) Serialize() []byte ", "output": "{\n\treturn []byte(f.SerializeToString())\n}"} {"input": "package virsh\n\nimport (\n\t\"errors\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t\"github.com/Symantec/tricorder/go/tricorder/units\"\n)\n\n\n\nfunc (p *prober) probe() error {\n\terr := p.listDomains()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor name, domain := range p.domains {\n\t\tif _, ok := p.listResults[name]; !ok {\n\t\t\tdomain.dir.UnregisterDirectory()\n\t\t\tdelete(p.domains, name)\n\t\t}\n\t}\n\tfor name, state := range p.listResults {\n\t\tinfo, ok := p.domains[name]\n\t\tif ok {\n\t\t\tinfo.state = state\n\t\t} else {\n\t\t\tinfo = &domainInfo{state: state}\n\t\t\tdir, err := p.domainsDir.RegisterDirectory(name)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tinfo.dir = dir\n\t\t\terr = dir.RegisterMetric(\"state\", &info.state, units.None,\n\t\t\t\t\"state of virtual machine\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.domains[name] = info\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (p *prober) listDomains() error ", "output": "{\n\tcmd := exec.Command(\"virsh\", \"list\", \"--all\")\n\tstdout, err := cmd.Output()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlines := strings.Split(string(stdout), \"\\n\")\n\tif len(lines) < 3 {\n\t\treturn errors.New(\"insufficient lines\")\n\t}\n\tif lines[1][0] != '-' {\n\t\treturn errors.New(\"missing separator\")\n\t}\n\tdomains := make(map[string]string, len(lines)-2)\n\tfor _, line := range lines[2:] {\n\t\tfields := strings.Fields(line)\n\t\tif len(fields) < 1 {\n\t\t\tcontinue\n\t\t}\n\t\tif len(fields) < 3 {\n\t\t\treturn errors.New(\"bad line: \\\"\" + line + \"\\\"\")\n\t\t}\n\t\tdomains[fields[1]] = strings.Join(fields[2:], \" \")\n\t}\n\tp.listResults = domains\n\treturn nil\n}"} {"input": "package nobody\n\nimport (\n\t\"context\"\n\n\tvoucher \"github.com/grafeas/voucher/v2\"\n\t\"github.com/grafeas/voucher/v2/docker\"\n)\n\n\n\ntype check struct {\n\tauth voucher.Auth\n}\n\n\n\n\n\n\n\nfunc (n *check) Check(ctx context.Context, i voucher.ImageData) (bool, error) {\n\tif nil == n.auth {\n\t\treturn false, voucher.ErrNoAuth\n\t}\n\n\tclient, err := n.auth.ToClient(ctx, i)\n\tif nil != err {\n\t\treturn false, err\n\t}\n\n\timageConfig, err := docker.RequestImageConfig(client, i)\n\n\tif nil != err {\n\t\treturn false, err\n\t}\n\n\treturn !imageConfig.RunsAsRoot(), nil\n}\n\nfunc init() {\n\tvoucher.RegisterCheckFactory(\"nobody\", func() voucher.Check {\n\t\treturn new(check)\n\t})\n}\n\nfunc (n *check) SetAuth(auth voucher.Auth) ", "output": "{\n\tn.auth = auth\n}"} {"input": "package model\n\ntype Result int\n\nconst (\n\tContinue Result = iota\n\tWin\n\tLoose\n)\n\n\n\nfunc (r Result) String() (repr string) ", "output": "{\n\tswitch r {\n\tcase Win:\n\t\trepr = \"You win!\"\n\tcase Loose:\n\t\trepr = \"You loose :-(\"\n\t}\n\treturn\n}"} {"input": "package command\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/bitrise-io/go-utils/pathutil\"\n)\n\n\nfunc CopyFile(src, dst string) error {\n\tisDir, err := pathutil.IsDirExists(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isDir {\n\t\treturn errors.New(\"Source is a directory: \" + src)\n\t}\n\targs := []string{src, dst}\n\treturn RunCommand(\"rsync\", args...)\n}\n\n\nfunc CopyDir(src, dst string, isOnlyContent bool) error {\n\tif isOnlyContent && !strings.HasSuffix(src, \"/\") {\n\t\tsrc = src + \"/\"\n\t}\n\targs := []string{\"-ar\", src, dst}\n\treturn RunCommand(\"rsync\", args...)\n}\n\n\nfunc RemoveDir(dirPth string) error {\n\tif exist, err := pathutil.IsPathExists(dirPth); err != nil {\n\t\treturn err\n\t} else if exist {\n\t\tif err := os.RemoveAll(dirPth); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\nfunc RemoveFile(pth string) error ", "output": "{\n\tif exist, err := pathutil.IsPathExists(pth); err != nil {\n\t\treturn err\n\t} else if exist {\n\t\tif err := os.Remove(pth); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package aws\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com/aws/aws-sdk-go/service/sns\"\n\t\"github.com/hashicorp/errwrap\"\n\t\"github.com/hashicorp/terraform/helper/schema\"\n)\n\n\n\nfunc dataSourceAwsSnsTopicsRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).snsconn\n\tparams := &sns.ListTopicsInput{}\n\n\ttarget := d.Get(\"name\")\n\tvar arns []string\n\terr := conn.ListTopicsPages(params, func(page *sns.ListTopicsOutput, lastPage bool) bool {\n\t\tfor _, topic := range page.Topics {\n\t\t\ttopicPattern := fmt.Sprintf(\".*:%v$\", target)\n\t\t\tmatched, regexpErr := regexp.MatchString(topicPattern, *topic.TopicArn)\n\t\t\tif matched && regexpErr == nil {\n\t\t\t\tarns = append(arns, *topic.TopicArn)\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t})\n\tif err != nil {\n\t\treturn errwrap.Wrapf(\"Error describing topics: {{err}}\", err)\n\t}\n\n\tif len(arns) == 0 {\n\t\treturn fmt.Errorf(\"No topic with name %q found in this region.\", target)\n\t}\n\tif len(arns) > 1 {\n\t\treturn fmt.Errorf(\"Multiple topics with name %q found in this region.\", target)\n\t}\n\n\td.SetId(time.Now().UTC().String())\n\td.Set(\"arn\", arns[0])\n\n\treturn nil\n}\n\nfunc dataSourceAwsSnsTopic() *schema.Resource ", "output": "{\n\treturn &schema.Resource{\n\t\tRead: dataSourceAwsSnsTopicsRead,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {\n\t\t\t\t\tvalue := v.(string)\n\t\t\t\t\tvalidNamePattern := \"^[A-Za-z0-9_-]+$\"\n\t\t\t\t\tvalidName, nameMatchErr := regexp.MatchString(validNamePattern, value)\n\t\t\t\t\tif !validName || nameMatchErr != nil {\n\t\t\t\t\t\terrors = append(errors, fmt.Errorf(\n\t\t\t\t\t\t\t\"%q must match regex '%v'\", k, validNamePattern))\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"arn\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package osenv\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n)\n\nconst (\n\tJujuEnv = \"JUJU_ENV\"\n\tJujuHome = \"JUJU_HOME\"\n\tJujuRepository = \"JUJU_REPOSITORY\"\n\tJujuLoggingConfig = \"JUJU_LOGGING_CONFIG\"\n\tJujuContainerType = \"JUJU_CONTAINER_TYPE\"\n)\n\n\nfunc JujuHomeDir() string {\n\tjujuHome := os.Getenv(JujuHome)\n\tif jujuHome == \"\" {\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\tjujuHome = jujuHomeWin()\n\t\t} else {\n\t\t\tjujuHome = jujuHomeLinux()\n\t\t}\n\t}\n\treturn jujuHome\n}\n\n\n\n\n\nfunc jujuHomeWin() string {\n\tappdata := os.Getenv(\"APPDATA\")\n\tif appdata == \"\" {\n\t\treturn \"\"\n\t}\n\treturn filepath.Join(appdata, \"Juju\")\n}\n\nfunc jujuHomeLinux() string ", "output": "{\n\thome := Home()\n\tif home == \"\" {\n\t\treturn \"\"\n\t}\n\treturn filepath.Join(home, \".juju\")\n}"} {"input": "package gutil\n\n\nimport (\n\t\"bufio\"\n\t\"os\"\n\t\"strings\"\n)\n\n\n\n\nfunc ReadLine(red *bufio.Reader) (string, bool) {\n\tline, _, err := red.ReadLine()\n\tif err != nil {\n\t\treturn \"\", false\n\t}\n\treturn string(line), true\n}\n\n\nfunc ReadPath(path string) []string {\n\tif file, err := os.Open(path); CheckSucceed(err) {\n\t\tvar strs []string\n\t\tbuff := bufio.NewReader(file)\n\t\tfor {\n\t\t\tif str, ok := ReadLine(buff); ok {\n\t\t\t\tstrs = append(strs, str)\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\treturn strs\n\t}\n\treturn nil\n}\n\nfunc NewReadForString(str string) *bufio.Reader ", "output": "{\n\treturn bufio.NewReader(strings.NewReader(str))\n}"} {"input": "package messages\n\nimport \"time\"\n\nconst nanosPerSecond = 1000000000\n\n\n\nfunc GoDurationToDuration(goDuration time.Duration) Duration {\n\tseconds := int64(goDuration / nanosPerSecond)\n\tnanos := int64(goDuration % nanosPerSecond)\n\treturn Duration{\n\t\tSeconds: seconds,\n\t\tNanos: nanos,\n\t}\n}\n\nfunc TimestampToGoTime(timestamp Timestamp) time.Time {\n\treturn time.Unix(timestamp.Seconds, timestamp.Nanos)\n}\n\nfunc GoTimeToTimestamp(t time.Time) Timestamp {\n\tunixNanos := t.UnixNano()\n\tseconds := unixNanos / nanosPerSecond\n\tnanos := unixNanos % nanosPerSecond\n\n\treturn Timestamp{\n\t\tSeconds: seconds,\n\t\tNanos: nanos,\n\t}\n}\n\nfunc DurationToGoDuration(duration Duration) time.Duration ", "output": "{\n\tsecondNanos := duration.Seconds * nanosPerSecond\n\treturn time.Duration(secondNanos + int64(duration.Nanos))\n}"} {"input": "package ui\n\nfunc About() string {\n\treturn \"go-ui 0.1.1 \"\n}\n\nfunc Version() string {\n\treturn \"go-ui 0.1.1\"\n}\n\n\n\nfunc Run() int {\n\treturn theApp.Run()\n}\n\nfunc Exit(code int) {\n\ttheApp.Exit(code)\n}\n\nfunc CloseAllWindows() {\n\ttheApp.CloseAllWindows()\n}\n\nfunc App() *app {\n\treturn &theApp\n}\n\nfunc Main(fn func()) int ", "output": "{\n\tfnAppMain = fn\n\treturn theApp.AppMain()\n}"} {"input": "package httpretry\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype dialer struct {\n\tTimeout time.Duration\n\tKeepAlive time.Duration\n\tInactivity time.Duration\n}\n\nfunc (d *dialer) Dial(netw, addr string) (net.Conn, error) {\n\tc, err := net.DialTimeout(netw, addr, d.Timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif tc, ok := c.(*net.TCPConn); ok {\n\t\ttc.SetKeepAlive(true)\n\t\ttc.SetKeepAlivePeriod(d.KeepAlive)\n\t}\n\treturn &deadlineConn{d.Inactivity, c}, nil\n}\n\n\n\n\n\n\n\n\nfunc ClientWithTimeout(timeout time.Duration) *http.Client {\n\tdialer := NewDialer(timeout)\n\ttransport := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: dialer.Dial,\n\t\tResponseHeaderTimeout: dialer.Inactivity,\n\t\tMaxIdleConnsPerHost: 10,\n\t}\n\treturn &http.Client{Transport: transport}\n}\n\n\n\n\nfunc DialWithTimeout(timeout time.Duration) func(netw, addr string) (net.Conn, error) {\n\treturn NewDialer(timeout).Dial\n}\n\n\n\n\n\ntype deadlineConn struct {\n\tTimeout time.Duration\n\tnet.Conn\n}\n\nfunc (c *deadlineConn) Read(b []byte) (int, error) {\n\tif err := c.Conn.SetDeadline(time.Now().Add(c.Timeout)); err != nil {\n\t\treturn 0, err\n\t}\n\treturn c.Conn.Read(b)\n}\n\nfunc (c *deadlineConn) Write(b []byte) (int, error) {\n\tif err := c.Conn.SetDeadline(time.Now().Add(c.Timeout)); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.Conn.Write(b)\n}\n\nfunc NewDialer(timeout time.Duration) *dialer ", "output": "{\n\treturn &dialer{Timeout: timeout, KeepAlive: timeout, Inactivity: timeout}\n}"} {"input": "package model\n\nimport (\n\t\"time\"\n\n\t\"github.com/NyaaPantsu/nyaa/config\"\n)\n\n\n\ntype TorrentReport struct {\n\tID uint `gorm:\"column:torrent_report_id;primary_key\"`\n\tDescription string `gorm:\"column:type\"`\n\tTorrentID uint `gorm:\"column:torrent_id\"`\n\tUserID uint `gorm:\"column:user_id\"`\n\n\tCreatedAt time.Time `gorm:\"column:created_at\"`\n\n\tTorrent *Torrent `gorm:\"AssociationForeignKey:TorrentID;ForeignKey:torrent_id\"`\n\tUser *User `gorm:\"AssociationForeignKey:UserID;ForeignKey:user_id\"`\n}\n\nfunc (r TorrentReport) TableName() string {\n\treturn config.ReportsTableName\n}\n\ntype TorrentReportJson struct {\n\tID uint `json:\"id\"`\n\tDescription string `json:\"description\"`\n\tTorrent TorrentJSON `json:\"torrent\"`\n\tUser UserJSON `json:\"user\"`\n}\n\n\n\nfunc getReportDescription(d string) string {\n\tif d == \"illegal\" {\n\t\treturn \"Illegal content\"\n\t} else if d == \"spam\" {\n\t\treturn \"Spam / Garbage\"\n\t} else if d == \"wrongcat\" {\n\t\treturn \"Wrong category\"\n\t} else if d == \"dup\" {\n\t\treturn \"Duplicate / Deprecated\"\n\t}\n\treturn \"???\"\n}\n\nfunc (report *TorrentReport) ToJson() TorrentReportJson {\n\tvar t TorrentJSON = TorrentJSON{}\n\tif report.Torrent != nil { \n\t\tt = report.Torrent.ToJSON()\n\t}\n\tvar u UserJSON = UserJSON{}\n\tif report.User != nil {\n\t\tu = report.User.ToJSON()\n\t}\n\tjson := TorrentReportJson{report.ID, getReportDescription(report.Description), t, u}\n\treturn json\n}\n\n\n\nfunc TorrentReportsToJSON(reports []TorrentReport) []TorrentReportJson ", "output": "{\n\tjson := make([]TorrentReportJson, len(reports))\n\tfor i := range reports {\n\t\tjson[i] = reports[i].ToJson()\n\t}\n\treturn json\n}"} {"input": "package subnets\n\nimport \"net\"\n\nfunc equals(a *net.IPNet, b *net.IPNet) bool {\n\taOnes, aBits := a.Mask.Size()\n\tbOnes, bBits := b.Mask.Size()\n\treturn a.IP.Equal(b.IP) && (aOnes == bOnes) && (aBits == bBits)\n}\n\nfunc overlaps(a *net.IPNet, b *net.IPNet) bool {\n\treturn a.Contains(b.IP) || b.Contains(a.IP)\n}\n\n\n\nfunc clone(ip net.IP) net.IP {\n\tclone := make([]byte, len(ip))\n\tcopy(clone, ip)\n\treturn clone\n}\n\nfunc max(ipn *net.IPNet) net.IP {\n\tmask := ipn.Mask\n\tmin := clone(ipn.IP)\n\n\tif len(mask) != len(min) {\n\t\tpanic(\"length of mask is not compatible with length of network IP\")\n\t}\n\n\tmax := make([]byte, len(min))\n\tfor i, b := range mask {\n\t\tmax[i] = min[i] | ^b\n\t}\n\n\treturn net.IP(max).To16()\n}\n\nfunc next(ip net.IP) net.IP ", "output": "{\n\tnext := clone(ip)\n\tfor i := len(next) - 1; i >= 0; i-- {\n\t\tnext[i]++\n\t\tif next[i] != 0 {\n\t\t\treturn next\n\t\t}\n\t}\n\n\tpanic(\"overflowed maximum IP\")\n}"} {"input": "package geoip_test\n\nimport (\n\t\"net\"\n\t\"testing\"\n\n\t\"github.com/sevein/nfdmp2rds/geoip\"\n)\n\n\n\nfunc TestLookup(t *testing.T) ", "output": "{\n\tvar tests = []struct {\n\t\tinput string\n\t\texpec string\n\t}{\n\t\t{\"142.58.103.21\", \"CA\"},\n\t\t{\"217.12.24.33\", \"ES\"},\n\t}\n\tfor _, tt := range tests {\n\t\tip := net.ParseIP(tt.input)\n\t\tr, err := geoip.Geo(ip)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tactual := r.Country.IsoCode\n\t\tif actual != tt.expec {\n\t\t\tt.Errorf(\"lookup: expected %s, actual %s\", tt.expec, actual)\n\t\t}\n\t}\n}"} {"input": "package netutil\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype ConnWrapper struct {\n\tio.Reader\n\tio.Writer\n\tUnderlyingConn net.Conn\n\tReadCloser io.Closer\n\tWriteCloser io.Closer\n}\n\nvar _ net.Conn = new(ConnWrapper)\n\n\n\nfunc (c *ConnWrapper) LocalAddr() net.Addr { return c.UnderlyingConn.LocalAddr() }\nfunc (c *ConnWrapper) RemoteAddr() net.Addr { return c.UnderlyingConn.RemoteAddr() }\nfunc (c *ConnWrapper) SetDeadline(t time.Time) error { return c.UnderlyingConn.SetDeadline(t) }\nfunc (c *ConnWrapper) SetReadDeadline(t time.Time) error { return c.UnderlyingConn.SetReadDeadline(t) }\nfunc (c *ConnWrapper) SetWriteDeadline(t time.Time) error { return c.UnderlyingConn.SetWriteDeadline(t) }\n\nfunc (c *ConnWrapper) Close() error ", "output": "{\n\tvar multiErr MultiError\n\tif c.ReadCloser != nil {\n\t\tmultiErr.RecordError(c.ReadCloser.Close())\n\t}\n\tif c.WriteCloser != nil {\n\t\tmultiErr.RecordError(c.WriteCloser.Close())\n\t}\n\tmultiErr.RecordError(c.UnderlyingConn.Close())\n\treturn multiErr.ToError()\n}"} {"input": "package canopus\n\nimport \"net\"\n\nfunc Dial(address string) (conn Connection, err error) {\n\tudpConn, err := net.Dial(\"udp\", address)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn = &UDPConnection{\n\t\tconn: udpConn,\n\t}\n\n\treturn\n}\n\nfunc DialDTLS(address, identity, psk string) (conn Connection, err error) {\n\tudpConn, err := net.Dial(\"udp\", address)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn, err = NewDTLSConnection(udpConn, identity, psk)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc NewObserveMessage(r string, val interface{}, msg Message) ObserveMessage {\n\treturn &CoapObserveMessage{\n\t\tResource: r,\n\t\tValue: val,\n\t\tMsg: msg,\n\t}\n}\n\ntype CoapObserveMessage struct {\n\tCoapMessage\n\tResource string\n\tValue interface{}\n\tMsg Message\n}\n\nfunc (m *CoapObserveMessage) GetResource() string {\n\treturn m.Resource\n}\n\nfunc (m *CoapObserveMessage) GetValue() interface{} {\n\treturn m.Value\n}\n\n\n\nfunc (m *CoapObserveMessage) GetMessage() Message ", "output": "{\n\treturn m.GetMessage()\n}"} {"input": "package violetear\n\nimport (\n\t\"net/http\"\n\t\"time\"\n)\n\n\ntype ResponseWriter struct {\n\thttp.ResponseWriter\n\trequestID string\n\tsize, status int\n\tstart time.Time\n}\n\n\nfunc NewResponseWriter(w http.ResponseWriter, rid string) *ResponseWriter {\n\treturn &ResponseWriter{\n\t\tResponseWriter: w,\n\t\trequestID: rid,\n\t\tstart: time.Now(),\n\t\tstatus: http.StatusOK,\n\t}\n}\n\n\nfunc (w *ResponseWriter) Status() int {\n\treturn w.status\n}\n\n\nfunc (w *ResponseWriter) Size() int {\n\treturn w.size\n}\n\n\nfunc (w *ResponseWriter) RequestTime() string {\n\treturn time.Since(w.start).String()\n}\n\n\n\n\n\n\nfunc (w *ResponseWriter) Write(data []byte) (int, error) {\n\tsize, err := w.ResponseWriter.Write(data)\n\tw.size += size\n\treturn size, err\n}\n\n\n\nfunc (w *ResponseWriter) WriteHeader(statusCode int) {\n\tw.status = statusCode\n\tw.ResponseWriter.WriteHeader(statusCode)\n}\n\nfunc (w *ResponseWriter) RequestID() string ", "output": "{\n\treturn w.requestID\n}"} {"input": "package hash\n\nimport \"unsafe\"\n\nconst DJBInit uint32 = 5381\n\nfunc DJBCombine(acc, h uint32) uint32 {\n\treturn mul33(acc) + h\n}\n\nfunc DJB(hs ...uint32) uint32 {\n\tacc := DJBInit\n\tfor _, h := range hs {\n\t\tacc = DJBCombine(acc, h)\n\t}\n\treturn acc\n}\n\nfunc UInt32(u uint32) uint32 {\n\treturn u\n}\n\n\n\nfunc Pointer(p unsafe.Pointer) uint32 {\n\tswitch unsafe.Sizeof(p) {\n\tcase 4:\n\t\treturn UInt32(uint32(uintptr(p)))\n\tcase 8:\n\t\treturn UInt64(uint64(uintptr(p)))\n\tdefault:\n\t\tpanic(\"unhandled pointer size\")\n\t}\n}\n\nfunc UIntPtr(p uintptr) uint32 {\n\tswitch unsafe.Sizeof(p) {\n\tcase 4:\n\t\treturn UInt32(uint32(p))\n\tcase 8:\n\t\treturn UInt64(uint64(p))\n\tdefault:\n\t\tpanic(\"unhandled pointer size\")\n\t}\n}\n\nfunc String(s string) uint32 {\n\th := DJBInit\n\tfor i := 0; i < len(s); i++ {\n\t\th = DJBCombine(h, uint32(s[i]))\n\t}\n\treturn h\n}\n\nfunc mul33(u uint32) uint32 {\n\treturn u<<5 + u\n}\n\nfunc UInt64(u uint64) uint32 ", "output": "{\n\treturn mul33(uint32(u>>32)) + uint32(u&0xffffffff)\n}"} {"input": "package factory\n\nimport (\n\tcontext \"context\"\n\n\texternalversions \"knative.dev/eventing-kafka/pkg/client/informers/externalversions\"\n\tclient \"knative.dev/eventing-kafka/pkg/client/injection/client\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Default.RegisterInformerFactory(withInformerFactory)\n}\n\n\ntype Key struct{}\n\n\n\n\nfunc Get(ctx context.Context) externalversions.SharedInformerFactory {\n\tuntyped := ctx.Value(Key{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch knative.dev/eventing-kafka/pkg/client/informers/externalversions.SharedInformerFactory from context.\")\n\t}\n\treturn untyped.(externalversions.SharedInformerFactory)\n}\n\nfunc withInformerFactory(ctx context.Context) context.Context ", "output": "{\n\tc := client.Get(ctx)\n\topts := make([]externalversions.SharedInformerOption, 0, 1)\n\tif injection.HasNamespaceScope(ctx) {\n\t\topts = append(opts, externalversions.WithNamespace(injection.GetNamespaceScope(ctx)))\n\t}\n\treturn context.WithValue(ctx, Key{},\n\t\texternalversions.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...))\n}"} {"input": "package v1\n\nimport (\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n\tv1 \"knative.dev/serving/pkg/apis/serving/v1\"\n)\n\n\ntype ConfigurationLister interface {\n\tList(selector labels.Selector) (ret []*v1.Configuration, err error)\n\tConfigurations(namespace string) ConfigurationNamespaceLister\n\tConfigurationListerExpansion\n}\n\n\ntype configurationLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewConfigurationLister(indexer cache.Indexer) ConfigurationLister {\n\treturn &configurationLister{indexer: indexer}\n}\n\n\nfunc (s *configurationLister) List(selector labels.Selector) (ret []*v1.Configuration, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Configuration))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *configurationLister) Configurations(namespace string) ConfigurationNamespaceLister {\n\treturn configurationNamespaceLister{indexer: s.indexer, namespace: namespace}\n}\n\n\ntype ConfigurationNamespaceLister interface {\n\tList(selector labels.Selector) (ret []*v1.Configuration, err error)\n\tGet(name string) (*v1.Configuration, error)\n\tConfigurationNamespaceListerExpansion\n}\n\n\n\ntype configurationNamespaceLister struct {\n\tindexer cache.Indexer\n\tnamespace string\n}\n\n\nfunc (s configurationNamespaceLister) List(selector labels.Selector) (ret []*v1.Configuration, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Configuration))\n\t})\n\treturn ret, err\n}\n\n\n\n\nfunc (s configurationNamespaceLister) Get(name string) (*v1.Configuration, error) ", "output": "{\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"configuration\"), name)\n\t}\n\treturn obj.(*v1.Configuration), nil\n}"} {"input": "package channels\n\nimport \"testing\"\nimport \"time\"\n\n\n\nfunc TestSender(t *testing.T) ", "output": "{\n\ttype args struct {\n\t\tch chan string\n\t\tdone chan bool\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t}{\n\t\t{\"base-case\", args{make(chan string, 10), make(chan bool)}},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgo Sender(tt.args.ch, tt.args.done)\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\ttt.args.done <- true\n\t\t})\n\t}\n}"} {"input": "package appfilesfakes\n\nimport (\n\t\"sync\"\n\n\t\"code.cloudfoundry.org/cli/cf/api/appfiles\"\n)\n\ntype FakeAppFilesRepository struct {\n\tListFilesStub func(appGUID string, instance int, path string) (files string, apiErr error)\n\tlistFilesMutex sync.RWMutex\n\tlistFilesArgsForCall []struct {\n\t\tappGUID string\n\t\tinstance int\n\t\tpath string\n\t}\n\tlistFilesReturns struct {\n\t\tresult1 string\n\t\tresult2 error\n\t}\n}\n\nfunc (fake *FakeAppFilesRepository) ListFiles(appGUID string, instance int, path string) (files string, apiErr error) {\n\tfake.listFilesMutex.Lock()\n\tfake.listFilesArgsForCall = append(fake.listFilesArgsForCall, struct {\n\t\tappGUID string\n\t\tinstance int\n\t\tpath string\n\t}{appGUID, instance, path})\n\tfake.listFilesMutex.Unlock()\n\tif fake.ListFilesStub != nil {\n\t\treturn fake.ListFilesStub(appGUID, instance, path)\n\t} else {\n\t\treturn fake.listFilesReturns.result1, fake.listFilesReturns.result2\n\t}\n}\n\nfunc (fake *FakeAppFilesRepository) ListFilesCallCount() int {\n\tfake.listFilesMutex.RLock()\n\tdefer fake.listFilesMutex.RUnlock()\n\treturn len(fake.listFilesArgsForCall)\n}\n\n\n\nfunc (fake *FakeAppFilesRepository) ListFilesReturns(result1 string, result2 error) {\n\tfake.ListFilesStub = nil\n\tfake.listFilesReturns = struct {\n\t\tresult1 string\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nvar _ appfiles.Repository = new(FakeAppFilesRepository)\n\nfunc (fake *FakeAppFilesRepository) ListFilesArgsForCall(i int) (string, int, string) ", "output": "{\n\tfake.listFilesMutex.RLock()\n\tdefer fake.listFilesMutex.RUnlock()\n\treturn fake.listFilesArgsForCall[i].appGUID, fake.listFilesArgsForCall[i].instance, fake.listFilesArgsForCall[i].path\n}"} {"input": "package validator\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\nfunc IsNull(str string) bool {\n\treturn len(str) == 0\n}\n\n\n\nfunc IsTime(str string, format string) bool {\n\t_, err := time.Parse(format, str)\n\treturn err == nil\n}\n\nfunc IsDate(str string, format ...string) bool {\n\n\tif len(format) == 0 {\n\n\t\tif len(strings.Split(str, \"/\")) > 1 {\n\t\t\treturn IsTime(str, \"2006/01/02\")\n\t\t}\n\n\t\tif len(strings.Split(str, \"-\")) > 1 {\n\t\t\treturn IsTime(str, \"2006-01-02\")\n\t\t}\n\n\t\treturn false\n\t}\n\n\treturn IsTime(str, format[0])\n}\n\nfunc IsEmpty(str string) bool {\n\treturn len(strings.TrimSpace(str)) == 0\n}\n\nfunc IsRequestURI(rawurl string) bool {\n\t_, err := url.ParseRequestURI(rawurl)\n\treturn err == nil\n}\n\nfunc IsURI(str string) bool {\n\trelation := false\n\tfor idx, val := range str {\n\t\tif val == '.' {\n\t\t\trelation = true\n\t\t\tcontinue\n\t\t}\n\t\tif val == '/' || val == '\\\\' {\n\t\t\tif idx < len(str)-1 {\n\t\t\t\tif str[idx+1] == '.' {\n\t\t\t\t\trelation = true\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif relation && (val != '/' && val != '\\\\') {\n\t\t\treturn false\n\t\t}\n\t\treturn IsRequestURI(str[idx:])\n\t}\n\treturn false\n}\n\nfunc IsMobilePhone(str string) bool {\n\tif IsEmpty(str) {\n\t\treturn false\n\t}\n\treturn rxMobolePhone.MatchString(str)\n}\n\nfunc IsWord(str string, params ...int) bool ", "output": "{\n\tif IsNull(str) {\n\t\treturn false\n\t}\n\treturn rxWord.MatchString(str)\n}"} {"input": "package middleware\n\nimport (\n\t\"github.com/postgres-ci/app-server/src/app/models/auth\"\n\t\"github.com/postgres-ci/app-server/src/app/models/password\"\n\t\"github.com/postgres-ci/app-server/src/tools/render\"\n\t\"github.com/postgres-ci/http200ok\"\n\n\t\"net/http\"\n)\n\n\n\nfunc CheckPassword(c *http200ok.Context) ", "output": "{\n\n\tif user, ok := c.Get(\"CurrentUser\").(*auth.User); ok {\n\n\t\tif err := password.Check(user.ID, c.Request.PostFormValue(\"password\")); err == nil {\n\n\t\t\treturn\n\t\t}\n\t}\n\n\trender.JSONError(c, http.StatusUnauthorized, \"Authentication failed\")\n\n\tc.Stop()\n}"} {"input": "package component\n\ntype (\n\toptions struct {\n\t\tname string \n\t\tnameFunc func(string) string \n\t\tschedName string \n\t}\n\n\tOption func(options *options)\n)\n\n\n\n\n\n\nfunc WithNameFunc(fn func(string) string) Option {\n\treturn func(opt *options) {\n\t\topt.nameFunc = fn\n\t}\n}\n\n\nfunc WithSchedulerName(name string) Option {\n\treturn func(opt *options) {\n\t\topt.schedName = name\n\t}\n}\n\nfunc WithName(name string) Option ", "output": "{\n\treturn func(opt *options) {\n\t\topt.name = name\n\t}\n}"} {"input": "package crypto\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc BenchmarkRandom(b *testing.B) {\n\tfor index := 0; index < b.N; index++ {\n\t\tRandom(32)\n\t}\n}\n\n\n\nfunc TestVerify(t *testing.T) {\n\tsrc := \"I'mAPlainSecret\"\n\tConvey(\"auth.Verify Test\", t, func() {\n\t\tfor index := 0; index < 10; index++ {\n\t\t\tsecret := Encrypt(src)\n\t\t\tSo(Verify(src, secret), ShouldBeTrue)\n\t\t}\n\t})\n}\n\nfunc BenchmarkMixin(b *testing.B) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tfor index := 0; index < b.N; index++ {\n\t\tmixin(src)\n\t}\n}\n\nfunc BenchmarkEncrypt(b *testing.B) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tfor index := 0; index < b.N; index++ {\n\t\tEncrypt(src)\n\t}\n}\n\nfunc BenchmarkVerify(b *testing.B) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tsecret := Encrypt(src)\n\tfor index := 0; index < b.N; index++ {\n\t\tVerify(src, secret)\n\t}\n}\n\nfunc TestEncrypt(t *testing.T) ", "output": "{\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tConvey(\"auth.Encrypt Test\", t, func() {\n\t\tsecret := Encrypt(src)\n\t\tSo(len(secret), ShouldEqual, 60)\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t})\n}"} {"input": "package base\n\nimport (\n\t\"math\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc GaussianRandom() {\n\n\trand.Seed(99)\n\n}\n\nfunc GetRandf(a float64, b float64) float64 {\n\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\treturn (b-a)*r.Float64() + a \n}\n\nfunc GetRani(a float64, b float64) float64 {\n\n\treturn math.Floor(GetRandf(a, b))\n}\n\n\n\nfunc GetRandn(mu float64, std float64) float64 ", "output": "{\n\n\treturn rand.NormFloat64()*mu + std\n}"} {"input": "package dep\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net/http\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n\n\t\"github.com/micromdm/micromdm/dep\"\n\t\"github.com/micromdm/micromdm/pkg/httputil\"\n)\n\nfunc (svc *DEPService) DefineProfile(ctx context.Context, p *dep.Profile) (*dep.ProfileResponse, error) {\n\tif svc.client == nil {\n\t\treturn nil, errors.New(\"DEP not configured yet. add a DEP token to enable DEP\")\n\t}\n\treturn svc.client.DefineProfile(p)\n}\n\ntype defineProfileRequest struct{ *dep.Profile }\ntype defineProfileResponse struct {\n\t*dep.ProfileResponse\n\tErr error `json:\"err,omitempty\"`\n}\n\nfunc (r defineProfileResponse) Failed() error { return r.Err }\n\nfunc decodeDefineProfileRequest(ctx context.Context, r *http.Request) (interface{}, error) {\n\tvar req defineProfileRequest\n\terr := httputil.DecodeJSONRequest(r, &req)\n\treturn req, err\n}\n\nfunc decodeDefineProfileResponse(_ context.Context, r *http.Response) (interface{}, error) {\n\tvar resp defineProfileResponse\n\terr := httputil.DecodeJSONResponse(r, &resp)\n\treturn resp, err\n}\n\nfunc MakeDefineProfileEndpoint(svc Service) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (response interface{}, err error) {\n\t\treq := request.(defineProfileRequest)\n\t\tresp, err := svc.DefineProfile(ctx, req.Profile)\n\t\treturn &defineProfileResponse{\n\t\t\tProfileResponse: resp,\n\t\t\tErr: err,\n\t\t}, nil\n\t}\n}\n\n\n\nfunc (e Endpoints) DefineProfile(ctx context.Context, p *dep.Profile) (*dep.ProfileResponse, error) ", "output": "{\n\trequest := defineProfileRequest{Profile: p}\n\tresp, err := e.DefineProfileEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponse := resp.(defineProfileResponse)\n\treturn response.ProfileResponse, response.Err\n}"} {"input": "package middleware\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/labstack/echo\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestRequestID(t *testing.T) ", "output": "{\n\te := echo.New()\n\treq, _ := http.NewRequest(echo.GET, \"/\", nil)\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\thandler := func(c echo.Context) error {\n\t\treturn c.String(http.StatusOK, \"test\")\n\t}\n\n\trid := RequestIDWithConfig(RequestIDConfig{})\n\th := rid(handler)\n\th(c)\n\tassert.Len(t, rec.Header().Get(echo.HeaderXRequestID), 32)\n\n\trid = RequestIDWithConfig(RequestIDConfig{\n\t\tGenerator: func() string { return \"customGenerator\" },\n\t})\n\th = rid(handler)\n\th(c)\n\tassert.Equal(t, rec.Header().Get(echo.HeaderXRequestID), \"customGenerator\")\n}"} {"input": "package filesystem\n\ntype FileSystem struct{}\n\nconst name = \"filesystem\"\n\nfunc (self *FileSystem) Name() string {\n\treturn name\n}\n\n\n\nfunc (self *FileSystem) Collect() (result interface{}, err error) ", "output": "{\n\tresult, err = getFileSystemInfo()\n\treturn\n}"} {"input": "package ulule\n\nimport (\n\t\"crypto/tls\"\n\t\"net/http\"\n)\n\n\n\ntype Client struct {\n\tusername string\n\tuserid string\n\tapikey string\n\taccessToken string\n\tpassword string\n\n\thttpClient *http.Client\n}\n\n\n\n\n\n\nfunc ClientWithToken(accessToken string) *Client {\n\tclientAPI := &Client{\n\t\taccessToken: accessToken,\n\t}\n\tclientAPI.initHttpClient()\n\treturn clientAPI\n}\n\n\n\nfunc (c *Client) initHttpClient() {\n\ttransport := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tc.httpClient = &http.Client{Transport: transport}\n}\n\nfunc ClientWithUsernameAndApiKey(username, apikey string) *Client ", "output": "{\n\tclientAPI := &Client{\n\t\tusername: username,\n\t\tapikey: apikey,\n\t}\n\tclientAPI.initHttpClient()\n\treturn clientAPI\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nvar cmdHelp = &command{\n\tdesc: \"Show this help\",\n\thelp: `Usage: procker help [command]\n\nHelp shows usage for a command.`,\n\texec: help}\n\n\n\nfunc help(args []string) ", "output": "{\n\tif len(args) == 0 {\n\t\tusage()\n\t\tos.Exit(0)\n\t}\n\n\tcommand := findCommand(args[0])\n\tfmt.Println(command.help)\n\tcommand.flag.PrintDefaults()\n}"} {"input": "package event\n\nimport (\n\t\"github.com/hyperledger/fabric-protos-go/gateway\"\n\t\"github.com/hyperledger/fabric-protos-go/peer\"\n\t\"github.com/hyperledger/fabric/common/ledger\"\n)\n\ntype ChaincodeEventsIterator struct {\n\tblockIter *BlockIterator\n}\n\nfunc NewChaincodeEventsIterator(iterator ledger.ResultsIterator) *ChaincodeEventsIterator {\n\treturn &ChaincodeEventsIterator{\n\t\tblockIter: NewBlockIterator(iterator),\n\t}\n}\n\n\n\nfunc (iter *ChaincodeEventsIterator) nextBlock() (*gateway.ChaincodeEventsResponse, error) {\n\tblock, err := iter.blockIter.Next()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tevents, err := chaincodeEventsFromBlock(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := &gateway.ChaincodeEventsResponse{\n\t\tBlockNumber: block.Number(),\n\t\tEvents: events,\n\t}\n\treturn result, nil\n}\n\nfunc chaincodeEventsFromBlock(block *Block) ([]*peer.ChaincodeEvent, error) {\n\ttransactions, err := block.Transactions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar results []*peer.ChaincodeEvent\n\n\tfor _, transaction := range transactions {\n\t\tif !transaction.Valid() {\n\t\t\tcontinue\n\t\t}\n\n\t\tevents, err := transaction.ChaincodeEvents()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, event := range events {\n\t\t\tresults = append(results, event.ProtoMessage())\n\t\t}\n\t}\n\n\treturn results, nil\n}\n\nfunc (iter *ChaincodeEventsIterator) Close() {\n\titer.blockIter.Close()\n}\n\nfunc (iter *ChaincodeEventsIterator) Next() (*gateway.ChaincodeEventsResponse, error) ", "output": "{\n\tfor {\n\t\tresult, err := iter.nextBlock()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(result.Events) > 0 {\n\t\t\treturn result, nil\n\t\t}\n\t}\n}"} {"input": "package text\n\nimport \"fmt\"\n\nconst (\n\tredCode = \"\\x1b[31m\"\n\tgreenCode = \"\\x1b[32m\"\n\tyellowCode = \"\\x1b[33m\"\n\tblueCode = \"\\x1b[34m\"\n\tmagentaCode = \"\\x1b[35m\"\n\tCyanCode = \"\\x1b[36m\"\n\tboldCode = \"\\x1b[1m\"\n\n\tResetCode = \"\\x1b[0m\"\n)\n\n\nvar UseColor = true\n\nfunc stylize(startCode, in string) string {\n\tif UseColor {\n\t\treturn startCode + in + ResetCode\n\t}\n\n\treturn in\n}\n\nfunc Red(in string) string {\n\treturn stylize(redCode, in)\n}\n\nfunc Green(in string) string {\n\treturn stylize(greenCode, in)\n}\n\nfunc yellow(in string) string {\n\treturn stylize(yellowCode, in)\n}\n\nfunc Cyan(in string) string {\n\treturn stylize(CyanCode, in)\n}\n\nfunc Magenta(in string) string {\n\treturn stylize(magentaCode, in)\n}\n\n\n\nfunc Bold(in string) string {\n\treturn stylize(boldCode, in)\n}\n\n\n\nfunc ColorHash(name string) (output string) {\n\tif !UseColor {\n\t\treturn name\n\t}\n\n\tvar hash uint = 5381\n\n\tfor i := 0; i < len(name); i++ {\n\t\thash = uint(name[i]) + ((hash << 5) + (hash))\n\t}\n\n\treturn fmt.Sprintf(\"\\x1b[%dm%s\\x1b[0m\", hash%6+31, name)\n}\n\nfunc Blue(in string) string ", "output": "{\n\treturn stylize(blueCode, in)\n}"} {"input": "package router\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/valyala/fasthttp\"\n\n\t\"github.com/tpbowden/swarm-ingress-router/service\"\n)\n\n\ntype Router struct {\n\troutes map[string]service.Service\n}\n\n\nfunc (r *Router) RouteToService(address string, path string, secure bool) (fasthttp.RequestHandler, bool) {\n\tvar handler fasthttp.RequestHandler\n\n\troute, ok := r.routes[address]\n\tif !ok {\n\t\tlog.Printf(\"Failed to lookup service for %s\", address)\n\t\treturn handler, false\n\t}\n\n\tif secure && !route.Secure {\n\t\treturn handler, false\n\t}\n\n\tif secure || !route.ForceTLS {\n\t\treturn NewProxyHandler(route.URL), true\n\t}\n\n\tredirectAddress := fmt.Sprintf(\"https://%s%s\", address, path)\n\treturn NewRedirectHandler(redirectAddress, 301), true\n}\n\n\nfunc (r *Router) CertificateForService(address string) (*tls.Certificate, bool) {\n\tvar cert *tls.Certificate\n\n\troute, ok := r.routes[address]\n\tif !ok {\n\t\tlog.Printf(\"Failed to lookup service for %s\", address)\n\t\treturn cert, false\n\t}\n\n\tcertificate := route.Certificate()\n\n\treturn &certificate, true\n}\n\n\nfunc (r *Router) UpdateTable(services []service.Service) {\n\tnewTable := make(map[string]service.Service)\n\n\tfor _, s := range services {\n\t\tlog.Printf(\"Registering service for %s\", s.DNSName)\n\t\ts.ParseCertificate()\n\t\tnewTable[s.DNSName] = s\n\t}\n\n\tr.routes = newTable\n}\n\n\n\n\nfunc NewRouter() *Router ", "output": "{\n\treturn &Router{}\n}"} {"input": "package cborl\n\ntype stateStack struct {\n\tstack []state \n\tstack0 [64]state\n\tcurrent state\n}\n\ntype lengthStack struct {\n\tstack []int64\n\tstack0 [32]int64\n\tcurrent int64\n}\n\n\n\nfunc (s *stateStack) push(next state) {\n\tif s.current.major != stFail {\n\t\ts.stack = append(s.stack, s.current)\n\t}\n\ts.current = next\n}\n\nfunc (s *stateStack) pop() {\n\tif len(s.stack) == 0 {\n\t\ts.current = state{stFail, stStart}\n\t} else {\n\t\tlast := len(s.stack) - 1\n\t\ts.current = s.stack[last]\n\t\ts.stack = s.stack[:last]\n\t}\n}\n\nfunc (s *lengthStack) init() {\n\ts.stack = s.stack0[:0]\n}\n\nfunc (s *lengthStack) push(l int64) {\n\ts.stack = append(s.stack, s.current)\n\ts.current = l\n}\n\nfunc (s *lengthStack) pop() int64 {\n\tif len(s.stack) == 0 {\n\t\ts.current = -1\n\t\treturn -1\n\t} else {\n\t\tlast := len(s.stack) - 1\n\t\told := s.current\n\t\ts.current = s.stack[last]\n\t\ts.stack = s.stack[:last]\n\t\treturn old\n\t}\n}\n\nfunc (s *stateStack) init(s0 state) ", "output": "{\n\ts.current = s0\n\ts.stack = s.stack0[:0]\n}"} {"input": "package ocvp\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListWorkRequestsRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tResourceId *string `mandatory:\"false\" contributesTo:\"query\" name:\"resourceId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListWorkRequestsRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListWorkRequestsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request ListWorkRequestsRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListWorkRequestsResponse struct {\n\n\tRawResponse *http.Response\n\n\tWorkRequestCollection `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n}\n\nfunc (response ListWorkRequestsResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListWorkRequestsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListWorkRequestsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package web\n\nimport (\n\t\"strings\"\n\n\t\"github.com/gopherjs/gopherjs/js\"\n)\n\n\n\nfunc IsBrowser() bool {\n\treturn !IsNodeJS()\n}\n\nfunc IsIOSSafari() bool {\n\tua := js.Global.Get(\"navigator\").Get(\"userAgent\").String()\n\tif !strings.Contains(ua, \"iPhone\") {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc IsAndroidChrome() bool {\n\tua := js.Global.Get(\"navigator\").Get(\"userAgent\").String()\n\tif !strings.Contains(ua, \"Android\") {\n\t\treturn false\n\t}\n\tif !strings.Contains(ua, \"Chrome\") {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc IsMobileBrowser() bool {\n\treturn IsIOSSafari() || IsAndroidChrome()\n}\n\nfunc IsNodeJS() bool ", "output": "{\n\treturn js.Global.Get(\"require\") != js.Undefined\n}"}